heimdal-7.5.0/0000755000175000017500000000000013212450770011253 5ustar niknikheimdal-7.5.0/kcm/0000755000175000017500000000000013212450764012030 5ustar niknikheimdal-7.5.0/kcm/glue.c0000644000175000017500000001430113026237312013122 0ustar niknik/* * Copyright (c) 2005, PADL Software Pty Ltd. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of PADL Software nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY PADL SOFTWARE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL PADL SOFTWARE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "kcm_locl.h" RCSID("$Id$"); /* * Server-side loopback glue for credentials cache operations; this * must be initialized with kcm_internal_ccache(), it is not for real * use. This entire file assumes the cache is locked, it does not do * any concurrency checking for multithread applications. */ #define KCMCACHE(X) ((kcm_ccache)(X)->data.data) #define CACHENAME(X) (KCMCACHE(X)->name) static const char * kcmss_get_name(krb5_context context, krb5_ccache id) { return CACHENAME(id); } static krb5_error_code kcmss_resolve(krb5_context context, krb5_ccache *id, const char *res) { return KRB5_FCC_INTERNAL; } static krb5_error_code kcmss_gen_new(krb5_context context, krb5_ccache *id) { return KRB5_FCC_INTERNAL; } static krb5_error_code kcmss_initialize(krb5_context context, krb5_ccache id, krb5_principal primary_principal) { krb5_error_code ret; kcm_ccache c = KCMCACHE(id); KCM_ASSERT_VALID(c); ret = kcm_zero_ccache_data_internal(context, c); if (ret) return ret; ret = krb5_copy_principal(context, primary_principal, &c->client); return ret; } static krb5_error_code kcmss_close(krb5_context context, krb5_ccache id) { kcm_ccache c = KCMCACHE(id); KCM_ASSERT_VALID(c); id->data.data = NULL; id->data.length = 0; return 0; } static krb5_error_code kcmss_destroy(krb5_context context, krb5_ccache id) { krb5_error_code ret; kcm_ccache c = KCMCACHE(id); KCM_ASSERT_VALID(c); ret = kcm_ccache_destroy(context, CACHENAME(id)); return ret; } static krb5_error_code kcmss_store_cred(krb5_context context, krb5_ccache id, krb5_creds *creds) { krb5_error_code ret; kcm_ccache c = KCMCACHE(id); krb5_creds *tmp; KCM_ASSERT_VALID(c); ret = kcm_ccache_store_cred_internal(context, c, creds, 1, &tmp); return ret; } static krb5_error_code kcmss_retrieve(krb5_context context, krb5_ccache id, krb5_flags which, const krb5_creds *mcred, krb5_creds *creds) { krb5_error_code ret; kcm_ccache c = KCMCACHE(id); krb5_creds *credp; KCM_ASSERT_VALID(c); ret = kcm_ccache_retrieve_cred_internal(context, c, which, mcred, &credp); if (ret) return ret; ret = krb5_copy_creds_contents(context, credp, creds); if (ret) return ret; return 0; } static krb5_error_code kcmss_get_principal(krb5_context context, krb5_ccache id, krb5_principal *principal) { krb5_error_code ret; kcm_ccache c = KCMCACHE(id); KCM_ASSERT_VALID(c); ret = krb5_copy_principal(context, c->client, principal); return ret; } static krb5_error_code kcmss_get_first (krb5_context context, krb5_ccache id, krb5_cc_cursor *cursor) { kcm_ccache c = KCMCACHE(id); KCM_ASSERT_VALID(c); *cursor = c->creds; return (*cursor == NULL) ? KRB5_CC_END : 0; } static krb5_error_code kcmss_get_next (krb5_context context, krb5_ccache id, krb5_cc_cursor *cursor, krb5_creds *creds) { krb5_error_code ret; kcm_ccache c = KCMCACHE(id); KCM_ASSERT_VALID(c); ret = krb5_copy_creds_contents(context, &((struct kcm_creds *)cursor)->cred, creds); if (ret) return ret; *cursor = ((struct kcm_creds *)cursor)->next; if (*cursor == 0) ret = KRB5_CC_END; return ret; } static krb5_error_code kcmss_end_get (krb5_context context, krb5_ccache id, krb5_cc_cursor *cursor) { *cursor = NULL; return 0; } static krb5_error_code kcmss_remove_cred(krb5_context context, krb5_ccache id, krb5_flags which, krb5_creds *cred) { krb5_error_code ret; kcm_ccache c = KCMCACHE(id); KCM_ASSERT_VALID(c); ret = kcm_ccache_remove_cred_internal(context, c, which, cred); return ret; } static krb5_error_code kcmss_set_flags(krb5_context context, krb5_ccache id, krb5_flags flags) { return 0; } static krb5_error_code kcmss_get_version(krb5_context context, krb5_ccache id) { return 0; } static const krb5_cc_ops krb5_kcmss_ops = { KRB5_CC_OPS_VERSION, "KCM", kcmss_get_name, kcmss_resolve, kcmss_gen_new, kcmss_initialize, kcmss_destroy, kcmss_close, kcmss_store_cred, kcmss_retrieve, kcmss_get_principal, kcmss_get_first, kcmss_get_next, kcmss_end_get, kcmss_remove_cred, kcmss_set_flags, kcmss_get_version, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, }; krb5_error_code kcm_internal_ccache(krb5_context context, kcm_ccache c, krb5_ccache id) { id->ops = &krb5_kcmss_ops; id->data.length = sizeof(*c); id->data.data = c; return 0; } heimdal-7.5.0/kcm/renew.c0000644000175000017500000000766313026237312013323 0ustar niknik/* * Copyright (c) 2005, PADL Software Pty Ltd. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of PADL Software nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY PADL SOFTWARE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL PADL SOFTWARE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "kcm_locl.h" RCSID("$Id$"); krb5_error_code kcm_ccache_refresh(krb5_context context, kcm_ccache ccache, krb5_creds **credp) { krb5_error_code ret; krb5_creds in, *out; krb5_kdc_flags flags; krb5_const_realm realm; krb5_ccache_data ccdata; const char *estr; memset(&in, 0, sizeof(in)); KCM_ASSERT_VALID(ccache); if (ccache->client == NULL) { /* no primary principal */ kcm_log(0, "Refresh credentials requested but no client principal"); return KRB5_CC_NOTFOUND; } HEIMDAL_MUTEX_lock(&ccache->mutex); /* Fake up an internal ccache */ kcm_internal_ccache(context, ccache, &ccdata); /* Find principal */ in.client = ccache->client; if (ccache->server != NULL) { ret = krb5_copy_principal(context, ccache->server, &in.server); if (ret) { estr = krb5_get_error_message(context, ret); kcm_log(0, "Failed to copy service principal: %s", estr); krb5_free_error_message(context, estr); goto out; } } else { realm = krb5_principal_get_realm(context, in.client); ret = krb5_make_principal(context, &in.server, realm, KRB5_TGS_NAME, realm, NULL); if (ret) { estr = krb5_get_error_message(context, ret); kcm_log(0, "Failed to make TGS principal for realm %s: %s", realm, estr); krb5_free_error_message(context, estr); goto out; } } if (ccache->tkt_life) in.times.endtime = time(NULL) + ccache->tkt_life; if (ccache->renew_life) in.times.renew_till = time(NULL) + ccache->renew_life; flags.i = 0; flags.b.renewable = TRUE; flags.b.renew = TRUE; ret = krb5_get_kdc_cred(context, &ccdata, flags, NULL, NULL, &in, &out); if (ret) { estr = krb5_get_error_message(context, ret); kcm_log(0, "Failed to renew credentials for cache %s: %s", ccache->name, estr); krb5_free_error_message(context, estr); goto out; } /* Swap them in */ kcm_ccache_remove_creds_internal(context, ccache); ret = kcm_ccache_store_cred_internal(context, ccache, out, 0, credp); if (ret) { estr = krb5_get_error_message(context, ret); kcm_log(0, "Failed to store credentials for cache %s: %s", ccache->name, estr); krb5_free_error_message(context, estr); krb5_free_creds(context, out); goto out; } free(out); /* but not contents */ out: HEIMDAL_MUTEX_unlock(&ccache->mutex); return ret; } heimdal-7.5.0/kcm/kcm-protos.h0000644000175000017500000001277113212445605014305 0ustar niknik/* This is a generated file */ #ifndef __kcm_protos_h__ #define __kcm_protos_h__ #ifndef DOXY #include #ifdef __cplusplus extern "C" { #endif krb5_error_code kcm_access ( krb5_context /*context*/, kcm_client */*client*/, kcm_operation /*opcode*/, kcm_ccache /*ccache*/); krb5_error_code kcm_ccache_acquire ( krb5_context /*context*/, kcm_ccache /*ccache*/, krb5_creds **/*credp*/); krb5_error_code kcm_ccache_destroy ( krb5_context /*context*/, const char */*name*/); krb5_error_code kcm_ccache_destroy_client ( krb5_context /*context*/, kcm_client */*client*/, const char */*name*/); krb5_error_code kcm_ccache_destroy_if_empty ( krb5_context /*context*/, kcm_ccache /*ccache*/); krb5_error_code kcm_ccache_enqueue_default ( krb5_context /*context*/, kcm_ccache /*ccache*/, krb5_creds */*newcred*/); struct kcm_creds * kcm_ccache_find_cred_uuid ( krb5_context /*context*/, kcm_ccache /*ccache*/, kcmuuid_t /*uuid*/); char * kcm_ccache_first_name (kcm_client */*client*/); krb5_error_code kcm_ccache_gen_new ( krb5_context /*context*/, pid_t /*pid*/, uid_t /*uid*/, gid_t /*gid*/, kcm_ccache */*ccache*/); krb5_error_code kcm_ccache_get_uuids ( krb5_context /*context*/, kcm_client */*client*/, kcm_operation /*opcode*/, krb5_storage */*sp*/); krb5_error_code kcm_ccache_new ( krb5_context /*context*/, const char */*name*/, kcm_ccache */*ccache*/); krb5_error_code kcm_ccache_new_client ( krb5_context /*context*/, kcm_client */*client*/, const char */*name*/, kcm_ccache */*ccache_p*/); char *kcm_ccache_nextid ( pid_t /*pid*/, uid_t /*uid*/, gid_t /*gid*/); krb5_error_code kcm_ccache_refresh ( krb5_context /*context*/, kcm_ccache /*ccache*/, krb5_creds **/*credp*/); krb5_error_code kcm_ccache_remove_cred ( krb5_context /*context*/, kcm_ccache /*ccache*/, krb5_flags /*whichfields*/, const krb5_creds */*mcreds*/); krb5_error_code kcm_ccache_remove_cred_internal ( krb5_context /*context*/, kcm_ccache /*ccache*/, krb5_flags /*whichfields*/, const krb5_creds */*mcreds*/); krb5_error_code kcm_ccache_remove_creds ( krb5_context /*context*/, kcm_ccache /*ccache*/); krb5_error_code kcm_ccache_remove_creds_internal ( krb5_context /*context*/, kcm_ccache /*ccache*/); krb5_error_code kcm_ccache_resolve ( krb5_context /*context*/, const char */*name*/, kcm_ccache */*ccache*/); krb5_error_code kcm_ccache_resolve_by_uuid ( krb5_context /*context*/, kcmuuid_t /*uuid*/, kcm_ccache */*ccache*/); krb5_error_code kcm_ccache_resolve_client ( krb5_context /*context*/, kcm_client */*client*/, kcm_operation /*opcode*/, const char */*name*/, kcm_ccache */*ccache*/); krb5_error_code kcm_ccache_retrieve_cred ( krb5_context /*context*/, kcm_ccache /*ccache*/, krb5_flags /*whichfields*/, const krb5_creds */*mcreds*/, krb5_creds **/*credp*/); krb5_error_code kcm_ccache_retrieve_cred_internal ( krb5_context /*context*/, kcm_ccache /*ccache*/, krb5_flags /*whichfields*/, const krb5_creds */*mcreds*/, krb5_creds **/*creds*/); krb5_error_code kcm_ccache_store_cred ( krb5_context /*context*/, kcm_ccache /*ccache*/, krb5_creds */*creds*/, int /*copy*/); krb5_error_code kcm_ccache_store_cred_internal ( krb5_context /*context*/, kcm_ccache /*ccache*/, krb5_creds */*creds*/, int /*copy*/, krb5_creds **/*credp*/); krb5_error_code kcm_chmod ( krb5_context /*context*/, kcm_client */*client*/, kcm_ccache /*ccache*/, uint16_t /*mode*/); krb5_error_code kcm_chown ( krb5_context /*context*/, kcm_client */*client*/, kcm_ccache /*ccache*/, uid_t /*uid*/, gid_t /*gid*/); krb5_error_code kcm_cleanup_events ( krb5_context /*context*/, kcm_ccache /*ccache*/); void kcm_configure ( int /*argc*/, char **/*argv*/); krb5_error_code kcm_debug_ccache (krb5_context /*context*/); krb5_error_code kcm_debug_events (krb5_context /*context*/); krb5_error_code kcm_dispatch ( krb5_context /*context*/, kcm_client */*client*/, krb5_data */*req_data*/, krb5_data */*resp_data*/); krb5_error_code kcm_enqueue_event ( krb5_context /*context*/, kcm_event */*event*/); krb5_error_code kcm_enqueue_event_internal ( krb5_context /*context*/, kcm_event */*event*/); krb5_error_code kcm_enqueue_event_relative ( krb5_context /*context*/, kcm_event */*event*/); krb5_error_code kcm_internal_ccache ( krb5_context /*context*/, kcm_ccache /*c*/, krb5_ccache /*id*/); int kcm_is_same_session ( kcm_client */*client*/, uid_t /*uid*/, pid_t /*session*/); void kcm_log ( int /*level*/, const char */*fmt*/, ...); char* kcm_log_msg ( int /*level*/, const char */*fmt*/, ...); char* kcm_log_msg_va ( int /*level*/, const char */*fmt*/, va_list /*ap*/); const char * kcm_op2string (kcm_operation /*opcode*/); void kcm_openlog (void); krb5_error_code kcm_release_ccache ( krb5_context /*context*/, kcm_ccache /*c*/); krb5_error_code kcm_remove_event ( krb5_context /*context*/, kcm_event */*event*/); krb5_error_code kcm_retain_ccache ( krb5_context /*context*/, kcm_ccache /*ccache*/); krb5_error_code kcm_run_events ( krb5_context /*context*/, time_t /*now*/); void kcm_service ( void */*ctx*/, const heim_idata */*req*/, const heim_icred /*cred*/, heim_ipc_complete /*complete*/, heim_sipc_call /*cctx*/); void kcm_session_add (pid_t /*session_id*/); void kcm_session_setup_handler (void); krb5_error_code kcm_zero_ccache_data ( krb5_context /*context*/, kcm_ccache /*cache*/); krb5_error_code kcm_zero_ccache_data_internal ( krb5_context /*context*/, kcm_ccache_data */*cache*/); #ifdef __cplusplus } #endif #endif /* DOXY */ #endif /* __kcm_protos_h__ */ heimdal-7.5.0/kcm/events.c0000644000175000017500000002503513026237312013500 0ustar niknik/* * Copyright (c) 2005, PADL Software Pty Ltd. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of PADL Software nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY PADL SOFTWARE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL PADL SOFTWARE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "kcm_locl.h" RCSID("$Id$"); /* thread-safe in case we multi-thread later */ static HEIMDAL_MUTEX events_mutex = HEIMDAL_MUTEX_INITIALIZER; static kcm_event *events_head = NULL; static time_t last_run = 0; static char *action_strings[] = { "NONE", "ACQUIRE_CREDS", "RENEW_CREDS", "DESTROY_CREDS", "DESTROY_EMPTY_CACHE" }; krb5_error_code kcm_enqueue_event(krb5_context context, kcm_event *event) { krb5_error_code ret; if (event->action == KCM_EVENT_NONE) { return 0; } HEIMDAL_MUTEX_lock(&events_mutex); ret = kcm_enqueue_event_internal(context, event); HEIMDAL_MUTEX_unlock(&events_mutex); return ret; } static void print_times(time_t t, char buf[64]) { if (t) strftime(buf, 64, "%m-%dT%H:%M", gmtime(&t)); else strlcpy(buf, "never", 64); } static void log_event(kcm_event *event, char *msg) { char fire_time[64], expire_time[64]; print_times(event->fire_time, fire_time); print_times(event->expire_time, expire_time); kcm_log(7, "%s event %08x: fire_time %s fire_count %d expire_time %s " "backoff_time %d action %s cache %s", msg, event, fire_time, event->fire_count, expire_time, event->backoff_time, action_strings[event->action], event->ccache->name); } krb5_error_code kcm_enqueue_event_internal(krb5_context context, kcm_event *event) { kcm_event **e; if (event->action == KCM_EVENT_NONE) return 0; for (e = &events_head; *e != NULL; e = &(*e)->next) ; *e = (kcm_event *)malloc(sizeof(kcm_event)); if (*e == NULL) { return KRB5_CC_NOMEM; } (*e)->valid = 1; (*e)->fire_time = event->fire_time; (*e)->fire_count = 0; (*e)->expire_time = event->expire_time; (*e)->backoff_time = event->backoff_time; (*e)->action = event->action; kcm_retain_ccache(context, event->ccache); (*e)->ccache = event->ccache; (*e)->next = NULL; log_event(*e, "enqueuing"); return 0; } /* * Dump events list on SIGUSR2 */ krb5_error_code kcm_debug_events(krb5_context context) { kcm_event *e; for (e = events_head; e != NULL; e = e->next) log_event(e, "debug"); return 0; } krb5_error_code kcm_enqueue_event_relative(krb5_context context, kcm_event *event) { krb5_error_code ret; kcm_event e; e = *event; e.backoff_time = e.fire_time; e.fire_time += time(NULL); ret = kcm_enqueue_event(context, &e); return ret; } static krb5_error_code kcm_remove_event_internal(krb5_context context, kcm_event **e) { kcm_event *next; next = (*e)->next; (*e)->valid = 0; (*e)->fire_time = 0; (*e)->fire_count = 0; (*e)->expire_time = 0; (*e)->backoff_time = 0; kcm_release_ccache(context, (*e)->ccache); (*e)->next = NULL; free(*e); *e = next; return 0; } static int is_primary_credential_p(krb5_context context, kcm_ccache ccache, krb5_creds *newcred) { krb5_flags whichfields; if (ccache->client == NULL) return 0; if (newcred->client == NULL || !krb5_principal_compare(context, ccache->client, newcred->client)) return 0; /* XXX just checks whether it's the first credential in the cache */ if (ccache->creds == NULL) return 0; whichfields = KRB5_TC_MATCH_KEYTYPE | KRB5_TC_MATCH_FLAGS_EXACT | KRB5_TC_MATCH_TIMES_EXACT | KRB5_TC_MATCH_AUTHDATA | KRB5_TC_MATCH_2ND_TKT | KRB5_TC_MATCH_IS_SKEY; return krb5_compare_creds(context, whichfields, newcred, &ccache->creds->cred); } /* * Setup default events for a new credential */ static krb5_error_code kcm_ccache_make_default_event(krb5_context context, kcm_event *event, krb5_creds *newcred) { krb5_error_code ret = 0; kcm_ccache ccache = event->ccache; event->fire_time = 0; event->expire_time = 0; event->backoff_time = KCM_EVENT_DEFAULT_BACKOFF_TIME; if (newcred == NULL) { /* no creds, must be acquire creds request */ if ((ccache->flags & KCM_MASK_KEY_PRESENT) == 0) { kcm_log(0, "Cannot acquire credentials without a key"); return KRB5_FCC_INTERNAL; } event->fire_time = time(NULL); /* right away */ event->action = KCM_EVENT_ACQUIRE_CREDS; } else if (is_primary_credential_p(context, ccache, newcred)) { if (newcred->flags.b.renewable) { event->action = KCM_EVENT_RENEW_CREDS; ccache->flags |= KCM_FLAGS_RENEWABLE; } else { if (ccache->flags & KCM_MASK_KEY_PRESENT) event->action = KCM_EVENT_ACQUIRE_CREDS; else event->action = KCM_EVENT_NONE; ccache->flags &= ~(KCM_FLAGS_RENEWABLE); } /* requeue with some slop factor */ event->fire_time = newcred->times.endtime - KCM_EVENT_QUEUE_INTERVAL; } else { event->action = KCM_EVENT_NONE; } return ret; } krb5_error_code kcm_ccache_enqueue_default(krb5_context context, kcm_ccache ccache, krb5_creds *newcred) { kcm_event event; krb5_error_code ret; memset(&event, 0, sizeof(event)); event.ccache = ccache; ret = kcm_ccache_make_default_event(context, &event, newcred); if (ret) return ret; ret = kcm_enqueue_event_internal(context, &event); if (ret) return ret; return 0; } krb5_error_code kcm_remove_event(krb5_context context, kcm_event *event) { krb5_error_code ret; kcm_event **e; int found = 0; log_event(event, "removing"); HEIMDAL_MUTEX_lock(&events_mutex); for (e = &events_head; *e != NULL; e = &(*e)->next) { if (event == *e) { *e = event->next; found++; break; } } if (!found) { ret = KRB5_CC_NOTFOUND; goto out; } ret = kcm_remove_event_internal(context, &event); out: HEIMDAL_MUTEX_unlock(&events_mutex); return ret; } krb5_error_code kcm_cleanup_events(krb5_context context, kcm_ccache ccache) { kcm_event **e; KCM_ASSERT_VALID(ccache); HEIMDAL_MUTEX_lock(&events_mutex); for (e = &events_head; *e != NULL; e = &(*e)->next) { if ((*e)->valid && (*e)->ccache == ccache) { kcm_remove_event_internal(context, e); } if (*e == NULL) break; } HEIMDAL_MUTEX_unlock(&events_mutex); return 0; } static krb5_error_code kcm_fire_event(krb5_context context, kcm_event **e) { kcm_event *event; krb5_error_code ret; krb5_creds *credp = NULL; int oneshot = 1; event = *e; switch (event->action) { case KCM_EVENT_ACQUIRE_CREDS: ret = kcm_ccache_acquire(context, event->ccache, &credp); oneshot = 0; break; case KCM_EVENT_RENEW_CREDS: ret = kcm_ccache_refresh(context, event->ccache, &credp); if (ret == KRB5KRB_AP_ERR_TKT_EXPIRED) { ret = kcm_ccache_acquire(context, event->ccache, &credp); } oneshot = 0; break; case KCM_EVENT_DESTROY_CREDS: ret = kcm_ccache_destroy(context, event->ccache->name); break; case KCM_EVENT_DESTROY_EMPTY_CACHE: ret = kcm_ccache_destroy_if_empty(context, event->ccache); break; default: ret = KRB5_FCC_INTERNAL; break; } event->fire_count++; if (ret) { /* Reschedule failed event for another time */ event->fire_time += event->backoff_time; if (event->backoff_time < KCM_EVENT_MAX_BACKOFF_TIME) event->backoff_time *= 2; /* Remove it if it would never get executed */ if (event->expire_time && event->fire_time > event->expire_time) kcm_remove_event_internal(context, e); } else { if (!oneshot) { char *cpn; if (krb5_unparse_name(context, event->ccache->client, &cpn)) cpn = NULL; kcm_log(0, "%s credentials in cache %s for principal %s", (event->action == KCM_EVENT_ACQUIRE_CREDS) ? "Acquired" : "Renewed", event->ccache->name, (cpn != NULL) ? cpn : ""); if (cpn != NULL) free(cpn); /* Succeeded, but possibly replaced with another event */ ret = kcm_ccache_make_default_event(context, event, credp); if (ret || event->action == KCM_EVENT_NONE) oneshot = 1; else log_event(event, "requeuing"); } if (oneshot) kcm_remove_event_internal(context, e); } return ret; } krb5_error_code kcm_run_events(krb5_context context, time_t now) { krb5_error_code ret; kcm_event **e; const char *estr; HEIMDAL_MUTEX_lock(&events_mutex); /* Only run event queue every N seconds */ if (now < last_run + KCM_EVENT_QUEUE_INTERVAL) { HEIMDAL_MUTEX_unlock(&events_mutex); return 0; } /* go through events list, fire and expire */ for (e = &events_head; *e != NULL; e = &(*e)->next) { if ((*e)->valid == 0) continue; if (now >= (*e)->fire_time) { ret = kcm_fire_event(context, e); if (ret) { estr = krb5_get_error_message(context, ret); kcm_log(1, "Could not fire event for cache %s: %s", (*e)->ccache->name, estr); krb5_free_error_message(context, estr); } } else if ((*e)->expire_time && now >= (*e)->expire_time) { ret = kcm_remove_event_internal(context, e); if (ret) { estr = krb5_get_error_message(context, ret); kcm_log(1, "Could not expire event for cache %s: %s", (*e)->ccache->name, estr); krb5_free_error_message(context, estr); } } if (*e == NULL) break; } last_run = now; HEIMDAL_MUTEX_unlock(&events_mutex); return 0; } heimdal-7.5.0/kcm/cache.c0000644000175000017500000003357613062303006013242 0ustar niknik/* * Copyright (c) 2005, PADL Software Pty Ltd. * All rights reserved. * * Portions Copyright (c) 2009 Apple Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of PADL Software nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY PADL SOFTWARE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL PADL SOFTWARE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "kcm_locl.h" HEIMDAL_MUTEX ccache_mutex = HEIMDAL_MUTEX_INITIALIZER; kcm_ccache_data *ccache_head = NULL; static unsigned int ccache_nextid = 0; char *kcm_ccache_nextid(pid_t pid, uid_t uid, gid_t gid) { unsigned n; char *name; int ret; HEIMDAL_MUTEX_lock(&ccache_mutex); n = ++ccache_nextid; HEIMDAL_MUTEX_unlock(&ccache_mutex); ret = asprintf(&name, "%ld:%u", (long)uid, n); if (ret == -1) return NULL; return name; } krb5_error_code kcm_ccache_resolve(krb5_context context, const char *name, kcm_ccache *ccache) { kcm_ccache p; krb5_error_code ret; *ccache = NULL; ret = KRB5_FCC_NOFILE; HEIMDAL_MUTEX_lock(&ccache_mutex); for (p = ccache_head; p != NULL; p = p->next) { if ((p->flags & KCM_FLAGS_VALID) == 0) continue; if (strcmp(p->name, name) == 0) { ret = 0; break; } } if (ret == 0) { kcm_retain_ccache(context, p); *ccache = p; } HEIMDAL_MUTEX_unlock(&ccache_mutex); return ret; } krb5_error_code kcm_ccache_resolve_by_uuid(krb5_context context, kcmuuid_t uuid, kcm_ccache *ccache) { kcm_ccache p; krb5_error_code ret; *ccache = NULL; ret = KRB5_FCC_NOFILE; HEIMDAL_MUTEX_lock(&ccache_mutex); for (p = ccache_head; p != NULL; p = p->next) { if ((p->flags & KCM_FLAGS_VALID) == 0) continue; if (memcmp(p->uuid, uuid, sizeof(*uuid)) == 0) { ret = 0; break; } } if (ret == 0) { kcm_retain_ccache(context, p); *ccache = p; } HEIMDAL_MUTEX_unlock(&ccache_mutex); return ret; } krb5_error_code kcm_ccache_get_uuids(krb5_context context, kcm_client *client, kcm_operation opcode, krb5_storage *sp) { krb5_error_code ret; kcm_ccache p; ret = KRB5_FCC_NOFILE; HEIMDAL_MUTEX_lock(&ccache_mutex); for (p = ccache_head; p != NULL; p = p->next) { if ((p->flags & KCM_FLAGS_VALID) == 0) continue; ret = kcm_access(context, client, opcode, p); if (ret) { ret = 0; continue; } krb5_storage_write(sp, p->uuid, sizeof(p->uuid)); } HEIMDAL_MUTEX_unlock(&ccache_mutex); return ret; } krb5_error_code kcm_debug_ccache(krb5_context context) { kcm_ccache p; for (p = ccache_head; p != NULL; p = p->next) { char *cpn = NULL, *spn = NULL; int ncreds = 0; struct kcm_creds *k; if ((p->flags & KCM_FLAGS_VALID) == 0) { kcm_log(7, "cache %08x: empty slot"); continue; } KCM_ASSERT_VALID(p); for (k = p->creds; k != NULL; k = k->next) ncreds++; if (p->client != NULL) krb5_unparse_name(context, p->client, &cpn); if (p->server != NULL) krb5_unparse_name(context, p->server, &spn); kcm_log(7, "cache %08x: name %s refcnt %d flags %04x mode %04o " "uid %d gid %d client %s server %s ncreds %d", p, p->name, p->refcnt, p->flags, p->mode, p->uid, p->gid, (cpn == NULL) ? "" : cpn, (spn == NULL) ? "" : spn, ncreds); if (cpn != NULL) free(cpn); if (spn != NULL) free(spn); } return 0; } static void kcm_free_ccache_data_internal(krb5_context context, kcm_ccache_data *cache) { KCM_ASSERT_VALID(cache); if (cache->name != NULL) { free(cache->name); cache->name = NULL; } if (cache->flags & KCM_FLAGS_USE_KEYTAB) { krb5_kt_close(context, cache->key.keytab); cache->key.keytab = NULL; } else if (cache->flags & KCM_FLAGS_USE_CACHED_KEY) { krb5_free_keyblock_contents(context, &cache->key.keyblock); krb5_keyblock_zero(&cache->key.keyblock); } cache->flags = 0; cache->mode = 0; cache->uid = -1; cache->gid = -1; cache->session = -1; kcm_zero_ccache_data_internal(context, cache); cache->tkt_life = 0; cache->renew_life = 0; cache->next = NULL; cache->refcnt = 0; HEIMDAL_MUTEX_unlock(&cache->mutex); HEIMDAL_MUTEX_destroy(&cache->mutex); } krb5_error_code kcm_ccache_destroy(krb5_context context, const char *name) { kcm_ccache *p, ccache; krb5_error_code ret; ret = KRB5_FCC_NOFILE; HEIMDAL_MUTEX_lock(&ccache_mutex); for (p = &ccache_head; *p != NULL; p = &(*p)->next) { if (((*p)->flags & KCM_FLAGS_VALID) == 0) continue; if (strcmp((*p)->name, name) == 0) { ret = 0; break; } } if (ret) goto out; if ((*p)->refcnt != 1) { ret = EAGAIN; goto out; } ccache = *p; *p = (*p)->next; kcm_free_ccache_data_internal(context, ccache); free(ccache); out: HEIMDAL_MUTEX_unlock(&ccache_mutex); return ret; } static krb5_error_code kcm_ccache_alloc(krb5_context context, const char *name, kcm_ccache *ccache) { kcm_ccache slot = NULL, p; krb5_error_code ret; int new_slot = 0; *ccache = NULL; /* First, check for duplicates */ HEIMDAL_MUTEX_lock(&ccache_mutex); ret = 0; for (p = ccache_head; p != NULL; p = p->next) { if (p->flags & KCM_FLAGS_VALID) { if (strcmp(p->name, name) == 0) { ret = KRB5_CC_WRITE; break; } } else if (slot == NULL) slot = p; } if (ret) goto out; /* * Create an enpty slot for us. */ if (slot == NULL) { slot = (kcm_ccache_data *)malloc(sizeof(*slot)); if (slot == NULL) { ret = KRB5_CC_NOMEM; goto out; } slot->next = ccache_head; HEIMDAL_MUTEX_init(&slot->mutex); new_slot = 1; } RAND_bytes(slot->uuid, sizeof(slot->uuid)); slot->name = strdup(name); if (slot->name == NULL) { ret = KRB5_CC_NOMEM; goto out; } slot->refcnt = 1; slot->flags = KCM_FLAGS_VALID; slot->mode = S_IRUSR | S_IWUSR; slot->uid = -1; slot->gid = -1; slot->client = NULL; slot->server = NULL; slot->creds = NULL; slot->key.keytab = NULL; slot->tkt_life = 0; slot->renew_life = 0; if (new_slot) ccache_head = slot; *ccache = slot; HEIMDAL_MUTEX_unlock(&ccache_mutex); return 0; out: HEIMDAL_MUTEX_unlock(&ccache_mutex); if (new_slot && slot != NULL) { HEIMDAL_MUTEX_destroy(&slot->mutex); free(slot); } return ret; } krb5_error_code kcm_ccache_remove_creds_internal(krb5_context context, kcm_ccache ccache) { struct kcm_creds *k; k = ccache->creds; while (k != NULL) { struct kcm_creds *old; krb5_free_cred_contents(context, &k->cred); old = k; k = k->next; free(old); } ccache->creds = NULL; return 0; } krb5_error_code kcm_ccache_remove_creds(krb5_context context, kcm_ccache ccache) { krb5_error_code ret; KCM_ASSERT_VALID(ccache); HEIMDAL_MUTEX_lock(&ccache->mutex); ret = kcm_ccache_remove_creds_internal(context, ccache); HEIMDAL_MUTEX_unlock(&ccache->mutex); return ret; } krb5_error_code kcm_zero_ccache_data_internal(krb5_context context, kcm_ccache_data *cache) { if (cache->client != NULL) { krb5_free_principal(context, cache->client); cache->client = NULL; } if (cache->server != NULL) { krb5_free_principal(context, cache->server); cache->server = NULL; } kcm_ccache_remove_creds_internal(context, cache); return 0; } krb5_error_code kcm_zero_ccache_data(krb5_context context, kcm_ccache cache) { krb5_error_code ret; KCM_ASSERT_VALID(cache); HEIMDAL_MUTEX_lock(&cache->mutex); ret = kcm_zero_ccache_data_internal(context, cache); HEIMDAL_MUTEX_unlock(&cache->mutex); return ret; } krb5_error_code kcm_retain_ccache(krb5_context context, kcm_ccache ccache) { KCM_ASSERT_VALID(ccache); HEIMDAL_MUTEX_lock(&ccache->mutex); ccache->refcnt++; HEIMDAL_MUTEX_unlock(&ccache->mutex); return 0; } krb5_error_code kcm_release_ccache(krb5_context context, kcm_ccache c) { krb5_error_code ret = 0; KCM_ASSERT_VALID(c); HEIMDAL_MUTEX_lock(&c->mutex); if (c->refcnt == 1) { kcm_free_ccache_data_internal(context, c); free(c); } else { c->refcnt--; HEIMDAL_MUTEX_unlock(&c->mutex); } return ret; } krb5_error_code kcm_ccache_gen_new(krb5_context context, pid_t pid, uid_t uid, gid_t gid, kcm_ccache *ccache) { krb5_error_code ret; char *name; name = kcm_ccache_nextid(pid, uid, gid); if (name == NULL) { return KRB5_CC_NOMEM; } ret = kcm_ccache_new(context, name, ccache); free(name); return ret; } krb5_error_code kcm_ccache_new(krb5_context context, const char *name, kcm_ccache *ccache) { krb5_error_code ret; ret = kcm_ccache_alloc(context, name, ccache); if (ret == 0) { /* * one reference is held by the linked list, * one by the caller */ kcm_retain_ccache(context, *ccache); } return ret; } krb5_error_code kcm_ccache_destroy_if_empty(krb5_context context, kcm_ccache ccache) { krb5_error_code ret; KCM_ASSERT_VALID(ccache); if (ccache->creds == NULL) { ret = kcm_ccache_destroy(context, ccache->name); } else ret = 0; return ret; } krb5_error_code kcm_ccache_store_cred(krb5_context context, kcm_ccache ccache, krb5_creds *creds, int copy) { krb5_error_code ret; krb5_creds *tmp; KCM_ASSERT_VALID(ccache); HEIMDAL_MUTEX_lock(&ccache->mutex); ret = kcm_ccache_store_cred_internal(context, ccache, creds, copy, &tmp); HEIMDAL_MUTEX_unlock(&ccache->mutex); return ret; } struct kcm_creds * kcm_ccache_find_cred_uuid(krb5_context context, kcm_ccache ccache, kcmuuid_t uuid) { struct kcm_creds *c; for (c = ccache->creds; c != NULL; c = c->next) if (memcmp(c->uuid, uuid, sizeof(c->uuid)) == 0) return c; return NULL; } krb5_error_code kcm_ccache_store_cred_internal(krb5_context context, kcm_ccache ccache, krb5_creds *creds, int copy, krb5_creds **credp) { struct kcm_creds **c; krb5_error_code ret; for (c = &ccache->creds; *c != NULL; c = &(*c)->next) ; *c = (struct kcm_creds *)calloc(1, sizeof(**c)); if (*c == NULL) return KRB5_CC_NOMEM; RAND_bytes((*c)->uuid, sizeof((*c)->uuid)); *credp = &(*c)->cred; if (copy) { ret = krb5_copy_creds_contents(context, creds, *credp); if (ret) { free(*c); *c = NULL; } } else { **credp = *creds; ret = 0; } return ret; } krb5_error_code kcm_ccache_remove_cred_internal(krb5_context context, kcm_ccache ccache, krb5_flags whichfields, const krb5_creds *mcreds) { krb5_error_code ret; struct kcm_creds **c; ret = KRB5_CC_NOTFOUND; for (c = &ccache->creds; *c != NULL; c = &(*c)->next) { if (krb5_compare_creds(context, whichfields, mcreds, &(*c)->cred)) { struct kcm_creds *cred = *c; *c = cred->next; krb5_free_cred_contents(context, &cred->cred); free(cred); ret = 0; if (*c == NULL) break; } } return ret; } krb5_error_code kcm_ccache_remove_cred(krb5_context context, kcm_ccache ccache, krb5_flags whichfields, const krb5_creds *mcreds) { krb5_error_code ret; KCM_ASSERT_VALID(ccache); HEIMDAL_MUTEX_lock(&ccache->mutex); ret = kcm_ccache_remove_cred_internal(context, ccache, whichfields, mcreds); HEIMDAL_MUTEX_unlock(&ccache->mutex); return ret; } krb5_error_code kcm_ccache_retrieve_cred_internal(krb5_context context, kcm_ccache ccache, krb5_flags whichfields, const krb5_creds *mcreds, krb5_creds **creds) { krb5_boolean match; struct kcm_creds *c; krb5_error_code ret; memset(creds, 0, sizeof(*creds)); ret = KRB5_CC_END; match = FALSE; for (c = ccache->creds; c != NULL; c = c->next) { match = krb5_compare_creds(context, whichfields, mcreds, &c->cred); if (match) break; } if (match) { ret = 0; *creds = &c->cred; } return ret; } krb5_error_code kcm_ccache_retrieve_cred(krb5_context context, kcm_ccache ccache, krb5_flags whichfields, const krb5_creds *mcreds, krb5_creds **credp) { krb5_error_code ret; KCM_ASSERT_VALID(ccache); HEIMDAL_MUTEX_lock(&ccache->mutex); ret = kcm_ccache_retrieve_cred_internal(context, ccache, whichfields, mcreds, credp); HEIMDAL_MUTEX_unlock(&ccache->mutex); return ret; } char * kcm_ccache_first_name(kcm_client *client) { kcm_ccache p; char *name = NULL; HEIMDAL_MUTEX_lock(&ccache_mutex); for (p = ccache_head; p != NULL; p = p->next) { if (kcm_is_same_session(client, p->uid, p->session)) break; } if (p) name = strdup(p->name); HEIMDAL_MUTEX_unlock(&ccache_mutex); return name; } heimdal-7.5.0/kcm/connect.c0000644000175000017500000000550313026237312013623 0ustar niknik/* * Copyright (c) 1997-2005 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Portions Copyright (c) 2009 Apple Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "kcm_locl.h" void kcm_service(void *ctx, const heim_idata *req, const heim_icred cred, heim_ipc_complete complete, heim_sipc_call cctx) { kcm_client peercred; krb5_error_code ret; krb5_data request, rep; unsigned char *buf; size_t len; krb5_data_zero(&rep); peercred.uid = heim_ipc_cred_get_uid(cred); peercred.gid = heim_ipc_cred_get_gid(cred); peercred.pid = heim_ipc_cred_get_pid(cred); peercred.session = heim_ipc_cred_get_session(cred); if (req->length < 4) { kcm_log(1, "malformed request from process %d (too short)", peercred.pid); (*complete)(cctx, EINVAL, NULL); return; } buf = req->data; len = req->length; if (buf[0] != KCM_PROTOCOL_VERSION_MAJOR || buf[1] != KCM_PROTOCOL_VERSION_MINOR) { kcm_log(1, "incorrect protocol version %d.%d from process %d", buf[0], buf[1], peercred.pid); (*complete)(cctx, EINVAL, NULL); return; } request.data = buf + 2; request.length = len - 2; /* buf is now pointing at opcode */ ret = kcm_dispatch(kcm_context, &peercred, &request, &rep); (*complete)(cctx, ret, &rep); krb5_data_free(&rep); } heimdal-7.5.0/kcm/acl.c0000644000175000017500000001204212136107747012736 0ustar niknik/* * Copyright (c) 2005, PADL Software Pty Ltd. * All rights reserved. * * Portions Copyright (c) 2009 Apple Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of PADL Software nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY PADL SOFTWARE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL PADL SOFTWARE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "kcm_locl.h" krb5_error_code kcm_access(krb5_context context, kcm_client *client, kcm_operation opcode, kcm_ccache ccache) { int read_p = 0; int write_p = 0; uint16_t mask; krb5_error_code ret; KCM_ASSERT_VALID(ccache); switch (opcode) { case KCM_OP_INITIALIZE: case KCM_OP_DESTROY: case KCM_OP_STORE: case KCM_OP_REMOVE_CRED: case KCM_OP_SET_FLAGS: case KCM_OP_CHOWN: case KCM_OP_CHMOD: case KCM_OP_GET_INITIAL_TICKET: case KCM_OP_GET_TICKET: case KCM_OP_MOVE_CACHE: case KCM_OP_SET_DEFAULT_CACHE: case KCM_OP_SET_KDC_OFFSET: write_p = 1; read_p = 0; break; case KCM_OP_NOOP: case KCM_OP_GET_NAME: case KCM_OP_RESOLVE: case KCM_OP_GEN_NEW: case KCM_OP_RETRIEVE: case KCM_OP_GET_PRINCIPAL: case KCM_OP_GET_CRED_UUID_LIST: case KCM_OP_GET_CRED_BY_UUID: case KCM_OP_GET_CACHE_UUID_LIST: case KCM_OP_GET_CACHE_BY_UUID: case KCM_OP_GET_DEFAULT_CACHE: case KCM_OP_GET_KDC_OFFSET: write_p = 0; read_p = 1; break; default: ret = KRB5_FCC_PERM; goto out; } if (ccache->flags & KCM_FLAGS_OWNER_IS_SYSTEM) { /* System caches cannot be reinitialized or destroyed by users */ if (opcode == KCM_OP_INITIALIZE || opcode == KCM_OP_DESTROY || opcode == KCM_OP_REMOVE_CRED || opcode == KCM_OP_MOVE_CACHE) { ret = KRB5_FCC_PERM; goto out; } /* Let root always read system caches */ if (CLIENT_IS_ROOT(client)) { ret = 0; goto out; } } /* start out with "other" mask */ mask = S_IROTH|S_IWOTH; /* root can do anything */ if (CLIENT_IS_ROOT(client)) { if (read_p) mask |= S_IRUSR|S_IRGRP|S_IROTH; if (write_p) mask |= S_IWUSR|S_IWGRP|S_IWOTH; } /* same session same as owner */ if (kcm_is_same_session(client, ccache->uid, ccache->session)) { if (read_p) mask |= S_IROTH; if (write_p) mask |= S_IWOTH; } /* owner */ if (client->uid == ccache->uid) { if (read_p) mask |= S_IRUSR; if (write_p) mask |= S_IWUSR; } /* group */ if (client->gid == ccache->gid) { if (read_p) mask |= S_IRGRP; if (write_p) mask |= S_IWGRP; } ret = (ccache->mode & mask) ? 0 : KRB5_FCC_PERM; out: if (ret) { kcm_log(2, "Process %d is not permitted to call %s on cache %s", client->pid, kcm_op2string(opcode), ccache->name); } return ret; } krb5_error_code kcm_chmod(krb5_context context, kcm_client *client, kcm_ccache ccache, uint16_t mode) { KCM_ASSERT_VALID(ccache); /* System cache mode can only be set at startup */ if (ccache->flags & KCM_FLAGS_OWNER_IS_SYSTEM) return KRB5_FCC_PERM; if (ccache->uid != client->uid) return KRB5_FCC_PERM; if (ccache->gid != client->gid) return KRB5_FCC_PERM; HEIMDAL_MUTEX_lock(&ccache->mutex); ccache->mode = mode; HEIMDAL_MUTEX_unlock(&ccache->mutex); return 0; } krb5_error_code kcm_chown(krb5_context context, kcm_client *client, kcm_ccache ccache, uid_t uid, gid_t gid) { KCM_ASSERT_VALID(ccache); /* System cache owner can only be set at startup */ if (ccache->flags & KCM_FLAGS_OWNER_IS_SYSTEM) return KRB5_FCC_PERM; if (ccache->uid != client->uid) return KRB5_FCC_PERM; if (ccache->gid != client->gid) return KRB5_FCC_PERM; HEIMDAL_MUTEX_lock(&ccache->mutex); ccache->uid = uid; ccache->gid = gid; HEIMDAL_MUTEX_unlock(&ccache->mutex); return 0; } heimdal-7.5.0/kcm/sessions.c0000644000175000017500000000502313026237312014035 0ustar niknik/* * Copyright (c) 2009 Kungliga Tekniska Hgskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Portions Copyright (c) 2009 Apple Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "kcm_locl.h" #if 0 #include #endif void kcm_session_add(pid_t session_id) { kcm_log(1, "monitor session: %d\n", session_id); } void kcm_session_setup_handler(void) { #if 0 au_sdev_handle_t *h; dispatch_queue_t bgq; h = au_sdev_open(AU_SDEVF_ALLSESSIONS); if (h == NULL) return; bgq = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0); dispatch_async(bgq, ^{ for (;;) { auditinfo_addr_t aio; int event; if (au_sdev_read_aia(h, &event, &aio) != 0) continue; /* * Ignore everything but END. This should relly be * CLOSE but since that is delayed until the credential * is reused, we can't do that * */ if (event != AUE_SESSION_END) continue; dispatch_async(dispatch_get_main_queue(), ^{ kcm_cache_remove_session(aio.ai_asid); }); } }); #endif } heimdal-7.5.0/kcm/config.c0000644000175000017500000002313113026237312013434 0ustar niknik/* * Copyright (c) 2005, PADL Software Pty Ltd. * All rights reserved. * * Portions Copyright (c) 2009 Apple Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of PADL Software nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY PADL SOFTWARE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL PADL SOFTWARE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "kcm_locl.h" #include #include static const char *config_file; /* location of kcm config file */ size_t max_request = 0; /* maximal size of a request */ char *socket_path = NULL; char *door_path = NULL; static char *max_request_str; /* `max_request' as a string */ int detach_from_console = -1; int daemon_child = -1; static const char *system_cache_name = NULL; static const char *system_keytab = NULL; static const char *system_principal = NULL; static const char *system_server = NULL; static const char *system_perms = NULL; static const char *system_user = NULL; static const char *system_group = NULL; static const char *renew_life = NULL; static const char *ticket_life = NULL; int launchd_flag = 0; int disallow_getting_krbtgt = 0; int name_constraints = -1; static int help_flag; static int version_flag; static struct getargs args[] = { { "cache-name", 0, arg_string, &system_cache_name, "system cache name", "cachename" }, { "config-file", 'c', arg_string, &config_file, "location of config file", "file" }, { "group", 'g', arg_string, &system_group, "system cache group", "group" }, { "max-request", 0, arg_string, &max_request, "max size for a kcm-request", "size" }, { "launchd", 0, arg_flag, &launchd_flag, "when in use by launchd", NULL }, { "detach", 0 , arg_flag, &detach_from_console, "detach from console", NULL }, { "daemon-child", 0 , arg_integer, &daemon_child, "private argument, do not use", NULL }, { "help", 'h', arg_flag, &help_flag, NULL, NULL }, { "system-principal", 'k', arg_string, &system_principal, "system principal name", "principal" }, { "lifetime", 'l', arg_string, &ticket_life, "lifetime of system tickets", "time" }, { "mode", 'm', arg_string, &system_perms, "octal mode of system cache", "mode" }, { "name-constraints", 'n', arg_negative_flag, &name_constraints, "disable credentials cache name constraints", NULL }, { "disallow-getting-krbtgt", 0, arg_flag, &disallow_getting_krbtgt, "disable fetching krbtgt from the cache", NULL }, { "renewable-life", 'r', arg_string, &renew_life, "renewable lifetime of system tickets", "time" }, { "socket-path", 's', arg_string, &socket_path, "path to kcm domain socket", "path" }, #ifdef HAVE_DOOR_CREATE { "door-path", 's', arg_string, &door_path, "path to kcm door", "path" }, #endif { "server", 'S', arg_string, &system_server, "server to get system ticket for", "principal" }, { "keytab", 't', arg_string, &system_keytab, "system keytab name", "keytab" }, { "user", 'u', arg_string, &system_user, "system cache owner", "user" }, { "version", 'v', arg_flag, &version_flag, NULL, NULL } }; static int num_args = sizeof(args) / sizeof(args[0]); static void usage(int ret) { arg_printusage (args, num_args, NULL, ""); exit (ret); } static int parse_owners(kcm_ccache ccache) { uid_t uid = 0; gid_t gid = 0; struct passwd *pw; struct group *gr; int uid_p = 0; int gid_p = 0; if (system_user != NULL) { if (isdigit((unsigned char)system_user[0])) { pw = getpwuid(atoi(system_user)); } else { pw = getpwnam(system_user); } if (pw == NULL) { return errno; } system_user = strdup(pw->pw_name); if (system_user == NULL) { return ENOMEM; } uid = pw->pw_uid; uid_p = 1; gid = pw->pw_gid; gid_p = 1; } if (system_group != NULL) { if (isdigit((unsigned char)system_group[0])) { gr = getgrgid(atoi(system_group)); } else { gr = getgrnam(system_group); } if (gr == NULL) { return errno; } gid = gr->gr_gid; gid_p = 1; } if (uid_p) ccache->uid = uid; else ccache->uid = 0; /* geteuid() XXX */ if (gid_p) ccache->gid = gid; else ccache->gid = 0; /* getegid() XXX */ return 0; } static const char * kcm_system_config_get_string(const char *string) { return krb5_config_get_string(kcm_context, NULL, "kcm", "system_ccache", string, NULL); } static krb5_error_code ccache_init_system(void) { kcm_ccache ccache; krb5_error_code ret; if (system_cache_name == NULL) system_cache_name = kcm_system_config_get_string("cc_name"); ret = kcm_ccache_new(kcm_context, system_cache_name ? system_cache_name : "SYSTEM", &ccache); if (ret) return ret; ccache->flags |= KCM_FLAGS_OWNER_IS_SYSTEM; ccache->flags |= KCM_FLAGS_USE_KEYTAB; ret = parse_owners(ccache); if (ret) return ret; ret = krb5_parse_name(kcm_context, system_principal, &ccache->client); if (ret) { kcm_release_ccache(kcm_context, ccache); return ret; } if (system_server == NULL) system_server = kcm_system_config_get_string("server"); if (system_server != NULL) { ret = krb5_parse_name(kcm_context, system_server, &ccache->server); if (ret) { kcm_release_ccache(kcm_context, ccache); return ret; } } if (system_keytab == NULL) system_keytab = kcm_system_config_get_string("keytab_name"); if (system_keytab != NULL) { ret = krb5_kt_resolve(kcm_context, system_keytab, &ccache->key.keytab); } else { ret = krb5_kt_default(kcm_context, &ccache->key.keytab); } if (ret) { kcm_release_ccache(kcm_context, ccache); return ret; } if (renew_life == NULL) renew_life = kcm_system_config_get_string("renew_life"); if (renew_life == NULL) renew_life = "6 months"; if (renew_life != NULL) { ccache->renew_life = parse_time(renew_life, "s"); if (ccache->renew_life < 0) { kcm_release_ccache(kcm_context, ccache); return EINVAL; } } if (ticket_life == NULL) ticket_life = kcm_system_config_get_string("ticket_life"); if (ticket_life != NULL) { ccache->tkt_life = parse_time(ticket_life, "s"); if (ccache->tkt_life < 0) { kcm_release_ccache(kcm_context, ccache); return EINVAL; } } if (system_perms == NULL) system_perms = kcm_system_config_get_string("mode"); if (system_perms != NULL) { int mode; if (sscanf(system_perms, "%o", &mode) != 1) return EINVAL; ccache->mode = mode; } if (disallow_getting_krbtgt == -1) { disallow_getting_krbtgt = krb5_config_get_bool_default(kcm_context, NULL, FALSE, "kcm", "disallow-getting-krbtgt", NULL); } /* enqueue default actions for credentials cache */ ret = kcm_ccache_enqueue_default(kcm_context, ccache, NULL); kcm_release_ccache(kcm_context, ccache); /* retained by event queue */ return ret; } void kcm_configure(int argc, char **argv) { krb5_error_code ret; int optidx = 0; const char *p; while (getarg(args, num_args, argc, argv, &optidx)) warnx("error at argument `%s'", argv[optidx]); if (help_flag) usage (0); if (version_flag) { print_version(NULL); exit(0); } argc -= optidx; argv += optidx; if (argc != 0) usage(1); { char **files; if(config_file == NULL) config_file = _PATH_KCM_CONF; ret = krb5_prepend_config_files_default(config_file, &files); if (ret) krb5_err(kcm_context, 1, ret, "getting configuration files"); ret = krb5_set_config_files(kcm_context, files); krb5_free_config_files(files); if(ret) krb5_err(kcm_context, 1, ret, "reading configuration files"); } if(max_request_str) max_request = parse_bytes(max_request_str, NULL); if(max_request == 0){ p = krb5_config_get_string (kcm_context, NULL, "kcm", "max-request", NULL); if(p) max_request = parse_bytes(p, NULL); } if (system_principal == NULL) { system_principal = kcm_system_config_get_string("principal"); } if (system_principal != NULL) { ret = ccache_init_system(); if (ret) krb5_err(kcm_context, 1, ret, "initializing system ccache"); } if(detach_from_console == -1) detach_from_console = krb5_config_get_bool_default(kcm_context, NULL, FALSE, "kcm", "detach", NULL); kcm_openlog(); if(max_request == 0) max_request = 64 * 1024; } heimdal-7.5.0/kcm/protocol.c0000644000175000017500000011136613026237312014040 0ustar niknik/* * Copyright (c) 2005, PADL Software Pty Ltd. * All rights reserved. * * Portions Copyright (c) 2009 Apple Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of PADL Software nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY PADL SOFTWARE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL PADL SOFTWARE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "kcm_locl.h" #include static void kcm_drop_default_cache(krb5_context context, kcm_client *client, char *name); int kcm_is_same_session(kcm_client *client, uid_t uid, pid_t session) { #if 0 /* XXX pppd is running in diffrent session the user */ if (session != -1) return (client->session == session); else #endif return (client->uid == uid); } static krb5_error_code kcm_op_noop(krb5_context context, kcm_client *client, kcm_operation opcode, krb5_storage *request, krb5_storage *response) { KCM_LOG_REQUEST(context, client, opcode); return 0; } /* * Request: * NameZ * Response: * NameZ * */ static krb5_error_code kcm_op_get_name(krb5_context context, kcm_client *client, kcm_operation opcode, krb5_storage *request, krb5_storage *response) { krb5_error_code ret; char *name = NULL; kcm_ccache ccache; ret = krb5_ret_stringz(request, &name); if (ret) return ret; KCM_LOG_REQUEST_NAME(context, client, opcode, name); ret = kcm_ccache_resolve_client(context, client, opcode, name, &ccache); if (ret) { free(name); return ret; } ret = krb5_store_stringz(response, ccache->name); if (ret) { kcm_release_ccache(context, ccache); free(name); return ret; } free(name); kcm_release_ccache(context, ccache); return 0; } /* * Request: * * Response: * NameZ */ static krb5_error_code kcm_op_gen_new(krb5_context context, kcm_client *client, kcm_operation opcode, krb5_storage *request, krb5_storage *response) { krb5_error_code ret; char *name; KCM_LOG_REQUEST(context, client, opcode); name = kcm_ccache_nextid(client->pid, client->uid, client->gid); if (name == NULL) { return KRB5_CC_NOMEM; } ret = krb5_store_stringz(response, name); free(name); return ret; } /* * Request: * NameZ * Principal * * Response: * */ static krb5_error_code kcm_op_initialize(krb5_context context, kcm_client *client, kcm_operation opcode, krb5_storage *request, krb5_storage *response) { kcm_ccache ccache; krb5_principal principal; krb5_error_code ret; char *name; #if 0 kcm_event event; #endif KCM_LOG_REQUEST(context, client, opcode); ret = krb5_ret_stringz(request, &name); if (ret) return ret; ret = krb5_ret_principal(request, &principal); if (ret) { free(name); return ret; } ret = kcm_ccache_new_client(context, client, name, &ccache); if (ret) { free(name); krb5_free_principal(context, principal); return ret; } ccache->client = principal; free(name); #if 0 /* * Create a new credentials cache. To mitigate DoS attacks we will * expire it in 30 minutes unless it has some credentials added * to it */ event.fire_time = 30 * 60; event.expire_time = 0; event.backoff_time = 0; event.action = KCM_EVENT_DESTROY_EMPTY_CACHE; event.ccache = ccache; ret = kcm_enqueue_event_relative(context, &event); #endif kcm_release_ccache(context, ccache); return ret; } /* * Request: * NameZ * * Response: * */ static krb5_error_code kcm_op_destroy(krb5_context context, kcm_client *client, kcm_operation opcode, krb5_storage *request, krb5_storage *response) { krb5_error_code ret; char *name; ret = krb5_ret_stringz(request, &name); if (ret) return ret; KCM_LOG_REQUEST_NAME(context, client, opcode, name); ret = kcm_ccache_destroy_client(context, client, name); if (ret == 0) kcm_drop_default_cache(context, client, name); free(name); return ret; } /* * Request: * NameZ * Creds * * Response: * */ static krb5_error_code kcm_op_store(krb5_context context, kcm_client *client, kcm_operation opcode, krb5_storage *request, krb5_storage *response) { krb5_creds creds; krb5_error_code ret; kcm_ccache ccache; char *name; ret = krb5_ret_stringz(request, &name); if (ret) return ret; KCM_LOG_REQUEST_NAME(context, client, opcode, name); ret = krb5_ret_creds(request, &creds); if (ret) { free(name); return ret; } ret = kcm_ccache_resolve_client(context, client, opcode, name, &ccache); if (ret) { free(name); krb5_free_cred_contents(context, &creds); return ret; } ret = kcm_ccache_store_cred(context, ccache, &creds, 0); if (ret) { free(name); krb5_free_cred_contents(context, &creds); kcm_release_ccache(context, ccache); return ret; } kcm_ccache_enqueue_default(context, ccache, &creds); free(name); kcm_release_ccache(context, ccache); return 0; } /* * Request: * NameZ * WhichFields * MatchCreds * * Response: * Creds * */ static krb5_error_code kcm_op_retrieve(krb5_context context, kcm_client *client, kcm_operation opcode, krb5_storage *request, krb5_storage *response) { uint32_t flags; krb5_creds mcreds; krb5_error_code ret; kcm_ccache ccache; char *name; krb5_creds *credp; int free_creds = 0; ret = krb5_ret_stringz(request, &name); if (ret) return ret; KCM_LOG_REQUEST_NAME(context, client, opcode, name); ret = krb5_ret_uint32(request, &flags); if (ret) { free(name); return ret; } ret = krb5_ret_creds_tag(request, &mcreds); if (ret) { free(name); return ret; } if (disallow_getting_krbtgt && mcreds.server->name.name_string.len == 2 && strcmp(mcreds.server->name.name_string.val[0], KRB5_TGS_NAME) == 0) { free(name); krb5_free_cred_contents(context, &mcreds); return KRB5_FCC_PERM; } ret = kcm_ccache_resolve_client(context, client, opcode, name, &ccache); if (ret) { free(name); krb5_free_cred_contents(context, &mcreds); return ret; } ret = kcm_ccache_retrieve_cred(context, ccache, flags, &mcreds, &credp); if (ret && ((flags & KRB5_GC_CACHED) == 0) && !krb5_is_config_principal(context, mcreds.server)) { krb5_ccache_data ccdata; /* try and acquire */ HEIMDAL_MUTEX_lock(&ccache->mutex); /* Fake up an internal ccache */ kcm_internal_ccache(context, ccache, &ccdata); /* glue cc layer will store creds */ ret = krb5_get_credentials(context, 0, &ccdata, &mcreds, &credp); if (ret == 0) free_creds = 1; HEIMDAL_MUTEX_unlock(&ccache->mutex); } if (ret == 0) { ret = krb5_store_creds(response, credp); } free(name); krb5_free_cred_contents(context, &mcreds); kcm_release_ccache(context, ccache); if (free_creds) krb5_free_cred_contents(context, credp); return ret; } /* * Request: * NameZ * * Response: * Principal */ static krb5_error_code kcm_op_get_principal(krb5_context context, kcm_client *client, kcm_operation opcode, krb5_storage *request, krb5_storage *response) { krb5_error_code ret; kcm_ccache ccache; char *name; ret = krb5_ret_stringz(request, &name); if (ret) return ret; KCM_LOG_REQUEST_NAME(context, client, opcode, name); ret = kcm_ccache_resolve_client(context, client, opcode, name, &ccache); if (ret) { free(name); return ret; } if (ccache->client == NULL) ret = KRB5_CC_NOTFOUND; else ret = krb5_store_principal(response, ccache->client); free(name); kcm_release_ccache(context, ccache); return 0; } /* * Request: * NameZ * * Response: * UUIDs * */ static krb5_error_code kcm_op_get_cred_uuid_list(krb5_context context, kcm_client *client, kcm_operation opcode, krb5_storage *request, krb5_storage *response) { struct kcm_creds *creds; krb5_error_code ret; kcm_ccache ccache; char *name; ret = krb5_ret_stringz(request, &name); if (ret) return ret; KCM_LOG_REQUEST_NAME(context, client, opcode, name); ret = kcm_ccache_resolve_client(context, client, opcode, name, &ccache); free(name); if (ret) return ret; for (creds = ccache->creds ; creds ; creds = creds->next) { ssize_t sret; sret = krb5_storage_write(response, &creds->uuid, sizeof(creds->uuid)); if (sret != sizeof(creds->uuid)) { ret = ENOMEM; break; } } kcm_release_ccache(context, ccache); return ret; } /* * Request: * NameZ * Cursor * * Response: * Creds */ static krb5_error_code kcm_op_get_cred_by_uuid(krb5_context context, kcm_client *client, kcm_operation opcode, krb5_storage *request, krb5_storage *response) { krb5_error_code ret; kcm_ccache ccache; char *name; struct kcm_creds *c; kcmuuid_t uuid; ssize_t sret; ret = krb5_ret_stringz(request, &name); if (ret) return ret; KCM_LOG_REQUEST_NAME(context, client, opcode, name); ret = kcm_ccache_resolve_client(context, client, opcode, name, &ccache); free(name); if (ret) return ret; sret = krb5_storage_read(request, &uuid, sizeof(uuid)); if (sret != sizeof(uuid)) { kcm_release_ccache(context, ccache); krb5_clear_error_message(context); return KRB5_CC_IO; } c = kcm_ccache_find_cred_uuid(context, ccache, uuid); if (c == NULL) { kcm_release_ccache(context, ccache); return KRB5_CC_END; } HEIMDAL_MUTEX_lock(&ccache->mutex); ret = krb5_store_creds(response, &c->cred); HEIMDAL_MUTEX_unlock(&ccache->mutex); kcm_release_ccache(context, ccache); return ret; } /* * Request: * NameZ * WhichFields * MatchCreds * * Response: * */ static krb5_error_code kcm_op_remove_cred(krb5_context context, kcm_client *client, kcm_operation opcode, krb5_storage *request, krb5_storage *response) { uint32_t whichfields; krb5_creds mcreds; krb5_error_code ret; kcm_ccache ccache; char *name; ret = krb5_ret_stringz(request, &name); if (ret) return ret; KCM_LOG_REQUEST_NAME(context, client, opcode, name); ret = krb5_ret_uint32(request, &whichfields); if (ret) { free(name); return ret; } ret = krb5_ret_creds_tag(request, &mcreds); if (ret) { free(name); return ret; } ret = kcm_ccache_resolve_client(context, client, opcode, name, &ccache); if (ret) { free(name); krb5_free_cred_contents(context, &mcreds); return ret; } ret = kcm_ccache_remove_cred(context, ccache, whichfields, &mcreds); /* XXX need to remove any events that match */ free(name); krb5_free_cred_contents(context, &mcreds); kcm_release_ccache(context, ccache); return ret; } /* * Request: * NameZ * Flags * * Response: * */ static krb5_error_code kcm_op_set_flags(krb5_context context, kcm_client *client, kcm_operation opcode, krb5_storage *request, krb5_storage *response) { uint32_t flags; krb5_error_code ret; kcm_ccache ccache; char *name; ret = krb5_ret_stringz(request, &name); if (ret) return ret; KCM_LOG_REQUEST_NAME(context, client, opcode, name); ret = krb5_ret_uint32(request, &flags); if (ret) { free(name); return ret; } ret = kcm_ccache_resolve_client(context, client, opcode, name, &ccache); if (ret) { free(name); return ret; } /* we don't really support any flags yet */ free(name); kcm_release_ccache(context, ccache); return 0; } /* * Request: * NameZ * UID * GID * * Response: * */ static krb5_error_code kcm_op_chown(krb5_context context, kcm_client *client, kcm_operation opcode, krb5_storage *request, krb5_storage *response) { uint32_t uid; uint32_t gid; krb5_error_code ret; kcm_ccache ccache; char *name; ret = krb5_ret_stringz(request, &name); if (ret) return ret; KCM_LOG_REQUEST_NAME(context, client, opcode, name); ret = krb5_ret_uint32(request, &uid); if (ret) { free(name); return ret; } ret = krb5_ret_uint32(request, &gid); if (ret) { free(name); return ret; } ret = kcm_ccache_resolve_client(context, client, opcode, name, &ccache); if (ret) { free(name); return ret; } ret = kcm_chown(context, client, ccache, uid, gid); free(name); kcm_release_ccache(context, ccache); return ret; } /* * Request: * NameZ * Mode * * Response: * */ static krb5_error_code kcm_op_chmod(krb5_context context, kcm_client *client, kcm_operation opcode, krb5_storage *request, krb5_storage *response) { uint16_t mode; krb5_error_code ret; kcm_ccache ccache; char *name; ret = krb5_ret_stringz(request, &name); if (ret) return ret; KCM_LOG_REQUEST_NAME(context, client, opcode, name); ret = krb5_ret_uint16(request, &mode); if (ret) { free(name); return ret; } ret = kcm_ccache_resolve_client(context, client, opcode, name, &ccache); if (ret) { free(name); return ret; } ret = kcm_chmod(context, client, ccache, mode); free(name); kcm_release_ccache(context, ccache); return ret; } /* * Protocol extensions for moving ticket acquisition responsibility * from client to KCM follow. */ /* * Request: * NameZ * ServerPrincipalPresent * ServerPrincipal OPTIONAL * Key * * Repsonse: * */ static krb5_error_code kcm_op_get_initial_ticket(krb5_context context, kcm_client *client, kcm_operation opcode, krb5_storage *request, krb5_storage *response) { krb5_error_code ret; kcm_ccache ccache; char *name; int8_t not_tgt = 0; krb5_principal server = NULL; krb5_keyblock key; krb5_keyblock_zero(&key); ret = krb5_ret_stringz(request, &name); if (ret) return ret; KCM_LOG_REQUEST_NAME(context, client, opcode, name); ret = krb5_ret_int8(request, ¬_tgt); if (ret) { free(name); return ret; } if (not_tgt) { ret = krb5_ret_principal(request, &server); if (ret) { free(name); return ret; } } ret = krb5_ret_keyblock(request, &key); if (ret) { free(name); if (server != NULL) krb5_free_principal(context, server); return ret; } ret = kcm_ccache_resolve_client(context, client, opcode, name, &ccache); if (ret == 0) { HEIMDAL_MUTEX_lock(&ccache->mutex); if (ccache->server != NULL) { krb5_free_principal(context, ccache->server); ccache->server = NULL; } krb5_free_keyblock(context, &ccache->key.keyblock); ccache->server = server; ccache->key.keyblock = key; ccache->flags |= KCM_FLAGS_USE_CACHED_KEY; ret = kcm_ccache_enqueue_default(context, ccache, NULL); if (ret) { ccache->server = NULL; krb5_keyblock_zero(&ccache->key.keyblock); ccache->flags &= ~(KCM_FLAGS_USE_CACHED_KEY); } HEIMDAL_MUTEX_unlock(&ccache->mutex); } free(name); if (ret != 0) { krb5_free_principal(context, server); krb5_free_keyblock_contents(context, &key); } kcm_release_ccache(context, ccache); return ret; } /* * Request: * NameZ * ServerPrincipal * KDCFlags * EncryptionType * * Repsonse: * */ static krb5_error_code kcm_op_get_ticket(krb5_context context, kcm_client *client, kcm_operation opcode, krb5_storage *request, krb5_storage *response) { krb5_error_code ret; kcm_ccache ccache; char *name; krb5_principal server = NULL; krb5_ccache_data ccdata; krb5_creds in, *out; krb5_kdc_flags flags; memset(&in, 0, sizeof(in)); ret = krb5_ret_stringz(request, &name); if (ret) return ret; KCM_LOG_REQUEST_NAME(context, client, opcode, name); ret = krb5_ret_uint32(request, &flags.i); if (ret) { free(name); return ret; } ret = krb5_ret_int32(request, &in.session.keytype); if (ret) { free(name); return ret; } ret = krb5_ret_principal(request, &server); if (ret) { free(name); return ret; } ret = kcm_ccache_resolve_client(context, client, opcode, name, &ccache); if (ret) { krb5_free_principal(context, server); free(name); return ret; } HEIMDAL_MUTEX_lock(&ccache->mutex); /* Fake up an internal ccache */ kcm_internal_ccache(context, ccache, &ccdata); in.client = ccache->client; in.server = server; in.times.endtime = 0; /* glue cc layer will store creds */ ret = krb5_get_credentials_with_flags(context, 0, flags, &ccdata, &in, &out); HEIMDAL_MUTEX_unlock(&ccache->mutex); krb5_free_principal(context, server); if (ret == 0) krb5_free_cred_contents(context, out); kcm_release_ccache(context, ccache); free(name); return ret; } /* * Request: * OldNameZ * NewNameZ * * Repsonse: * */ static krb5_error_code kcm_op_move_cache(krb5_context context, kcm_client *client, kcm_operation opcode, krb5_storage *request, krb5_storage *response) { krb5_error_code ret; kcm_ccache oldid, newid; char *oldname, *newname; ret = krb5_ret_stringz(request, &oldname); if (ret) return ret; KCM_LOG_REQUEST_NAME(context, client, opcode, oldname); ret = krb5_ret_stringz(request, &newname); if (ret) { free(oldname); return ret; } /* move to ourself is simple, done! */ if (strcmp(oldname, newname) == 0) { free(oldname); free(newname); return 0; } ret = kcm_ccache_resolve_client(context, client, opcode, oldname, &oldid); if (ret) { free(oldname); free(newname); return ret; } /* Check if new credential cache exists, if not create one. */ ret = kcm_ccache_resolve_client(context, client, opcode, newname, &newid); if (ret == KRB5_FCC_NOFILE) ret = kcm_ccache_new_client(context, client, newname, &newid); free(newname); if (ret) { free(oldname); kcm_release_ccache(context, oldid); return ret; } HEIMDAL_MUTEX_lock(&oldid->mutex); HEIMDAL_MUTEX_lock(&newid->mutex); /* move content */ { kcm_ccache_data tmp; #define MOVE(n,o,f) { tmp.f = n->f ; n->f = o->f; o->f = tmp.f; } MOVE(newid, oldid, flags); MOVE(newid, oldid, client); MOVE(newid, oldid, server); MOVE(newid, oldid, creds); MOVE(newid, oldid, tkt_life); MOVE(newid, oldid, renew_life); MOVE(newid, oldid, key); MOVE(newid, oldid, kdc_offset); #undef MOVE } HEIMDAL_MUTEX_unlock(&oldid->mutex); HEIMDAL_MUTEX_unlock(&newid->mutex); kcm_release_ccache(context, oldid); kcm_release_ccache(context, newid); ret = kcm_ccache_destroy_client(context, client, oldname); if (ret == 0) kcm_drop_default_cache(context, client, oldname); free(oldname); return ret; } static krb5_error_code kcm_op_get_cache_uuid_list(krb5_context context, kcm_client *client, kcm_operation opcode, krb5_storage *request, krb5_storage *response) { KCM_LOG_REQUEST(context, client, opcode); return kcm_ccache_get_uuids(context, client, opcode, response); } static krb5_error_code kcm_op_get_cache_by_uuid(krb5_context context, kcm_client *client, kcm_operation opcode, krb5_storage *request, krb5_storage *response) { krb5_error_code ret; kcmuuid_t uuid; ssize_t sret; kcm_ccache cache; KCM_LOG_REQUEST(context, client, opcode); sret = krb5_storage_read(request, &uuid, sizeof(uuid)); if (sret != sizeof(uuid)) { krb5_clear_error_message(context); return KRB5_CC_IO; } ret = kcm_ccache_resolve_by_uuid(context, uuid, &cache); if (ret) return ret; ret = kcm_access(context, client, opcode, cache); if (ret) ret = KRB5_FCC_NOFILE; if (ret == 0) ret = krb5_store_stringz(response, cache->name); kcm_release_ccache(context, cache); return ret; } struct kcm_default_cache *default_caches; static krb5_error_code kcm_op_get_default_cache(krb5_context context, kcm_client *client, kcm_operation opcode, krb5_storage *request, krb5_storage *response) { struct kcm_default_cache *c; krb5_error_code ret; const char *name = NULL; char *n = NULL; int aret; KCM_LOG_REQUEST(context, client, opcode); for (c = default_caches; c != NULL; c = c->next) { if (kcm_is_same_session(client, c->uid, c->session)) { name = c->name; break; } } if (name == NULL) name = n = kcm_ccache_first_name(client); if (name == NULL) { aret = asprintf(&n, "%d", (int)client->uid); if (aret != -1) name = n; } if (name == NULL) return ENOMEM; ret = krb5_store_stringz(response, name); if (n) free(n); return ret; } static void kcm_drop_default_cache(krb5_context context, kcm_client *client, char *name) { struct kcm_default_cache **c; for (c = &default_caches; *c != NULL; c = &(*c)->next) { if (!kcm_is_same_session(client, (*c)->uid, (*c)->session)) continue; if (strcmp((*c)->name, name) == 0) { struct kcm_default_cache *h = *c; *c = (*c)->next; free(h->name); free(h); break; } } } static krb5_error_code kcm_op_set_default_cache(krb5_context context, kcm_client *client, kcm_operation opcode, krb5_storage *request, krb5_storage *response) { struct kcm_default_cache *c; krb5_error_code ret; char *name; ret = krb5_ret_stringz(request, &name); if (ret) return ret; KCM_LOG_REQUEST_NAME(context, client, opcode, name); for (c = default_caches; c != NULL; c = c->next) { if (kcm_is_same_session(client, c->uid, c->session)) break; } if (c == NULL) { c = malloc(sizeof(*c)); if (c == NULL) { free(name); return ENOMEM; } c->session = client->session; c->uid = client->uid; c->name = name; c->next = default_caches; default_caches = c; } else { free(c->name); c->name = name; } return 0; } static krb5_error_code kcm_op_get_kdc_offset(krb5_context context, kcm_client *client, kcm_operation opcode, krb5_storage *request, krb5_storage *response) { krb5_error_code ret; kcm_ccache ccache; char *name; ret = krb5_ret_stringz(request, &name); if (ret) return ret; KCM_LOG_REQUEST_NAME(context, client, opcode, name); ret = kcm_ccache_resolve_client(context, client, opcode, name, &ccache); free(name); if (ret) return ret; HEIMDAL_MUTEX_lock(&ccache->mutex); ret = krb5_store_int32(response, ccache->kdc_offset); HEIMDAL_MUTEX_unlock(&ccache->mutex); kcm_release_ccache(context, ccache); return ret; } static krb5_error_code kcm_op_set_kdc_offset(krb5_context context, kcm_client *client, kcm_operation opcode, krb5_storage *request, krb5_storage *response) { krb5_error_code ret; kcm_ccache ccache; int32_t offset; char *name; ret = krb5_ret_stringz(request, &name); if (ret) return ret; KCM_LOG_REQUEST_NAME(context, client, opcode, name); ret = krb5_ret_int32(request, &offset); if (ret) { free(name); return ret; } ret = kcm_ccache_resolve_client(context, client, opcode, name, &ccache); free(name); if (ret) return ret; HEIMDAL_MUTEX_lock(&ccache->mutex); ccache->kdc_offset = offset; HEIMDAL_MUTEX_unlock(&ccache->mutex); kcm_release_ccache(context, ccache); return ret; } struct kcm_ntlm_cred { kcmuuid_t uuid; char *user; char *domain; krb5_data nthash; uid_t uid; pid_t session; struct kcm_ntlm_cred *next; }; static struct kcm_ntlm_cred *ntlm_head; static void free_cred(struct kcm_ntlm_cred *cred) { free(cred->user); free(cred->domain); krb5_data_free(&cred->nthash); free(cred); } /* * name * domain * ntlm hash * * Reply: * uuid */ static struct kcm_ntlm_cred * find_ntlm_cred(const char *user, const char *domain, kcm_client *client) { struct kcm_ntlm_cred *c; for (c = ntlm_head; c != NULL; c = c->next) if ((user[0] == '\0' || strcmp(user, c->user) == 0) && (domain == NULL || strcmp(domain, c->domain) == 0) && kcm_is_same_session(client, c->uid, c->session)) return c; return NULL; } static krb5_error_code kcm_op_add_ntlm_cred(krb5_context context, kcm_client *client, kcm_operation opcode, krb5_storage *request, krb5_storage *response) { struct kcm_ntlm_cred *cred, *c; krb5_error_code ret; cred = calloc(1, sizeof(*cred)); if (cred == NULL) return ENOMEM; RAND_bytes(cred->uuid, sizeof(cred->uuid)); ret = krb5_ret_stringz(request, &cred->user); if (ret) goto error; ret = krb5_ret_stringz(request, &cred->domain); if (ret) goto error; ret = krb5_ret_data(request, &cred->nthash); if (ret) goto error; /* search for dups */ c = find_ntlm_cred(cred->user, cred->domain, client); if (c) { krb5_data hash = c->nthash; c->nthash = cred->nthash; cred->nthash = hash; free_cred(cred); cred = c; } else { cred->next = ntlm_head; ntlm_head = cred; } cred->uid = client->uid; cred->session = client->session; /* write response */ (void)krb5_storage_write(response, &cred->uuid, sizeof(cred->uuid)); return 0; error: free_cred(cred); return ret; } /* * { "HAVE_NTLM_CRED", NULL }, * * input: * name * domain */ static krb5_error_code kcm_op_have_ntlm_cred(krb5_context context, kcm_client *client, kcm_operation opcode, krb5_storage *request, krb5_storage *response) { struct kcm_ntlm_cred *c; char *user = NULL, *domain = NULL; krb5_error_code ret; ret = krb5_ret_stringz(request, &user); if (ret) goto error; ret = krb5_ret_stringz(request, &domain); if (ret) goto error; if (domain[0] == '\0') { free(domain); domain = NULL; } c = find_ntlm_cred(user, domain, client); if (c == NULL) ret = ENOENT; error: free(user); if (domain) free(domain); return ret; } /* * { "DEL_NTLM_CRED", NULL }, * * input: * name * domain */ static krb5_error_code kcm_op_del_ntlm_cred(krb5_context context, kcm_client *client, kcm_operation opcode, krb5_storage *request, krb5_storage *response) { struct kcm_ntlm_cred **cp, *c; char *user = NULL, *domain = NULL; krb5_error_code ret; ret = krb5_ret_stringz(request, &user); if (ret) goto error; ret = krb5_ret_stringz(request, &domain); if (ret) goto error; for (cp = &ntlm_head; *cp != NULL; cp = &(*cp)->next) { if (strcmp(user, (*cp)->user) == 0 && strcmp(domain, (*cp)->domain) == 0 && kcm_is_same_session(client, (*cp)->uid, (*cp)->session)) { c = *cp; *cp = c->next; free_cred(c); break; } } error: free(user); free(domain); return ret; } /* * { "DO_NTLM_AUTH", NULL }, * * input: * name:string * domain:string * type2:data * * reply: * type3:data * flags:int32 * session-key:data */ #define NTLM_FLAG_SESSIONKEY 1 #define NTLM_FLAG_NTLM2_SESSION 2 #define NTLM_FLAG_KEYEX 4 static krb5_error_code kcm_op_do_ntlm(krb5_context context, kcm_client *client, kcm_operation opcode, krb5_storage *request, krb5_storage *response) { struct kcm_ntlm_cred *c; struct ntlm_type2 type2; struct ntlm_type3 type3; char *user = NULL, *domain = NULL; struct ntlm_buf ndata, sessionkey; krb5_data data; krb5_error_code ret; uint32_t flags = 0; memset(&type2, 0, sizeof(type2)); memset(&type3, 0, sizeof(type3)); sessionkey.data = NULL; sessionkey.length = 0; ret = krb5_ret_stringz(request, &user); if (ret) goto error; ret = krb5_ret_stringz(request, &domain); if (ret) goto error; if (domain[0] == '\0') { free(domain); domain = NULL; } c = find_ntlm_cred(user, domain, client); if (c == NULL) { ret = EINVAL; goto error; } ret = krb5_ret_data(request, &data); if (ret) goto error; ndata.data = data.data; ndata.length = data.length; ret = heim_ntlm_decode_type2(&ndata, &type2); krb5_data_free(&data); if (ret) goto error; if (domain && strcmp(domain, type2.targetname) == 0) { ret = EINVAL; goto error; } type3.username = c->user; type3.flags = type2.flags; type3.targetname = type2.targetname; type3.ws = rk_UNCONST("workstation"); /* * NTLM Version 1 if no targetinfo buffer. */ if (1 || type2.targetinfo.length == 0) { struct ntlm_buf tmpsesskey; if (type2.flags & NTLM_NEG_NTLM2_SESSION) { unsigned char nonce[8]; if (RAND_bytes(nonce, sizeof(nonce)) != 1) { ret = EINVAL; goto error; } ret = heim_ntlm_calculate_ntlm2_sess(nonce, type2.challenge, c->nthash.data, &type3.lm, &type3.ntlm); } else { ret = heim_ntlm_calculate_ntlm1(c->nthash.data, c->nthash.length, type2.challenge, &type3.ntlm); } if (ret) goto error; ret = heim_ntlm_build_ntlm1_master(c->nthash.data, c->nthash.length, &tmpsesskey, &type3.sessionkey); if (ret) { if (type3.lm.data) free(type3.lm.data); if (type3.ntlm.data) free(type3.ntlm.data); goto error; } free(tmpsesskey.data); if (ret) { if (type3.lm.data) free(type3.lm.data); if (type3.ntlm.data) free(type3.ntlm.data); goto error; } flags |= NTLM_FLAG_SESSIONKEY; #if 0 } else { struct ntlm_buf sessionkey; unsigned char ntlmv2[16]; struct ntlm_targetinfo ti; /* verify infotarget */ ret = heim_ntlm_decode_targetinfo(&type2.targetinfo, 1, &ti); if(ret) { _gss_ntlm_delete_sec_context(minor_status, context_handle, NULL); *minor_status = ret; return GSS_S_FAILURE; } if (ti.domainname && strcmp(ti.domainname, name->domain) != 0) { _gss_ntlm_delete_sec_context(minor_status, context_handle, NULL); *minor_status = EINVAL; return GSS_S_FAILURE; } ret = heim_ntlm_calculate_ntlm2(ctx->client->key.data, ctx->client->key.length, type3.username, name->domain, type2.challenge, &type2.targetinfo, ntlmv2, &type3.ntlm); if (ret) { _gss_ntlm_delete_sec_context(minor_status, context_handle, NULL); *minor_status = ret; return GSS_S_FAILURE; } ret = heim_ntlm_build_ntlm1_master(ntlmv2, sizeof(ntlmv2), &sessionkey, &type3.sessionkey); memset(ntlmv2, 0, sizeof(ntlmv2)); if (ret) { _gss_ntlm_delete_sec_context(minor_status, context_handle, NULL); *minor_status = ret; return GSS_S_FAILURE; } flags |= NTLM_FLAG_NTLM2_SESSION | NTLM_FLAG_SESSION; if (type3.flags & NTLM_NEG_KEYEX) flags |= NTLM_FLAG_KEYEX; ret = krb5_data_copy(&ctx->sessionkey, sessionkey.data, sessionkey.length); free(sessionkey.data); if (ret) { _gss_ntlm_delete_sec_context(minor_status, context_handle, NULL); *minor_status = ret; return GSS_S_FAILURE; } #endif } #if 0 if (flags & NTLM_FLAG_NTLM2_SESSION) { _gss_ntlm_set_key(&ctx->u.v2.send, 0, (ctx->flags & NTLM_NEG_KEYEX), ctx->sessionkey.data, ctx->sessionkey.length); _gss_ntlm_set_key(&ctx->u.v2.recv, 1, (ctx->flags & NTLM_NEG_KEYEX), ctx->sessionkey.data, ctx->sessionkey.length); } else { flags |= NTLM_FLAG_SESSION; RC4_set_key(&ctx->u.v1.crypto_recv.key, ctx->sessionkey.length, ctx->sessionkey.data); RC4_set_key(&ctx->u.v1.crypto_send.key, ctx->sessionkey.length, ctx->sessionkey.data); } #endif ret = heim_ntlm_encode_type3(&type3, &ndata, NULL); if (ret) goto error; data.data = ndata.data; data.length = ndata.length; ret = krb5_store_data(response, data); heim_ntlm_free_buf(&ndata); if (ret) goto error; ret = krb5_store_int32(response, flags); if (ret) goto error; data.data = sessionkey.data; data.length = sessionkey.length; ret = krb5_store_data(response, data); if (ret) goto error; error: free(type3.username); heim_ntlm_free_type2(&type2); free(user); if (domain) free(domain); return ret; } /* * { "GET_NTLM_UUID_LIST", NULL } * * reply: * 1 user domain * 0 [ end of list ] */ static krb5_error_code kcm_op_get_ntlm_user_list(krb5_context context, kcm_client *client, kcm_operation opcode, krb5_storage *request, krb5_storage *response) { struct kcm_ntlm_cred *c; krb5_error_code ret; for (c = ntlm_head; c != NULL; c = c->next) { if (!kcm_is_same_session(client, c->uid, c->session)) continue; ret = krb5_store_uint32(response, 1); if (ret) return ret; ret = krb5_store_stringz(response, c->user); if (ret) return ret; ret = krb5_store_stringz(response, c->domain); if (ret) return ret; } return krb5_store_uint32(response, 0); } /* * */ static struct kcm_op kcm_ops[] = { { "NOOP", kcm_op_noop }, { "GET_NAME", kcm_op_get_name }, { "RESOLVE", kcm_op_noop }, { "GEN_NEW", kcm_op_gen_new }, { "INITIALIZE", kcm_op_initialize }, { "DESTROY", kcm_op_destroy }, { "STORE", kcm_op_store }, { "RETRIEVE", kcm_op_retrieve }, { "GET_PRINCIPAL", kcm_op_get_principal }, { "GET_CRED_UUID_LIST", kcm_op_get_cred_uuid_list }, { "GET_CRED_BY_UUID", kcm_op_get_cred_by_uuid }, { "REMOVE_CRED", kcm_op_remove_cred }, { "SET_FLAGS", kcm_op_set_flags }, { "CHOWN", kcm_op_chown }, { "CHMOD", kcm_op_chmod }, { "GET_INITIAL_TICKET", kcm_op_get_initial_ticket }, { "GET_TICKET", kcm_op_get_ticket }, { "MOVE_CACHE", kcm_op_move_cache }, { "GET_CACHE_UUID_LIST", kcm_op_get_cache_uuid_list }, { "GET_CACHE_BY_UUID", kcm_op_get_cache_by_uuid }, { "GET_DEFAULT_CACHE", kcm_op_get_default_cache }, { "SET_DEFAULT_CACHE", kcm_op_set_default_cache }, { "GET_KDC_OFFSET", kcm_op_get_kdc_offset }, { "SET_KDC_OFFSET", kcm_op_set_kdc_offset }, { "ADD_NTLM_CRED", kcm_op_add_ntlm_cred }, { "HAVE_USER_CRED", kcm_op_have_ntlm_cred }, { "DEL_NTLM_CRED", kcm_op_del_ntlm_cred }, { "DO_NTLM_AUTH", kcm_op_do_ntlm }, { "GET_NTLM_USER_LIST", kcm_op_get_ntlm_user_list } }; const char * kcm_op2string(kcm_operation opcode) { if (opcode >= sizeof(kcm_ops)/sizeof(kcm_ops[0])) return "Unknown operation"; return kcm_ops[opcode].name; } krb5_error_code kcm_dispatch(krb5_context context, kcm_client *client, krb5_data *req_data, krb5_data *resp_data) { krb5_error_code ret; kcm_method method; krb5_storage *req_sp = NULL; krb5_storage *resp_sp = NULL; uint16_t opcode; resp_sp = krb5_storage_emem(); if (resp_sp == NULL) { return ENOMEM; } if (client->pid == -1) { kcm_log(0, "Client had invalid process number"); ret = KRB5_FCC_INTERNAL; goto out; } req_sp = krb5_storage_from_data(req_data); if (req_sp == NULL) { kcm_log(0, "Process %d: failed to initialize storage from data", client->pid); ret = KRB5_CC_IO; goto out; } ret = krb5_ret_uint16(req_sp, &opcode); if (ret) { kcm_log(0, "Process %d: didn't send a message", client->pid); goto out; } if (opcode >= sizeof(kcm_ops)/sizeof(kcm_ops[0])) { kcm_log(0, "Process %d: invalid operation code %d", client->pid, opcode); ret = KRB5_FCC_INTERNAL; goto out; } method = kcm_ops[opcode].method; if (method == NULL) { kcm_log(0, "Process %d: operation code %s not implemented", client->pid, kcm_op2string(opcode)); ret = KRB5_FCC_INTERNAL; goto out; } /* seek past place for status code */ krb5_storage_seek(resp_sp, 4, SEEK_SET); ret = (*method)(context, client, opcode, req_sp, resp_sp); out: if (req_sp != NULL) { krb5_storage_free(req_sp); } krb5_storage_seek(resp_sp, 0, SEEK_SET); krb5_store_int32(resp_sp, ret); ret = krb5_storage_to_data(resp_sp, resp_data); krb5_storage_free(resp_sp); return ret; } heimdal-7.5.0/kcm/main.c0000644000175000017500000000570513026237312013122 0ustar niknik/* * Copyright (c) 1997-2002 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "kcm_locl.h" RCSID("$Id$"); krb5_context kcm_context = NULL; const char *service_name = "org.h5l.kcm"; static RETSIGTYPE sigusr1(int sig) { kcm_debug_ccache(kcm_context); } static RETSIGTYPE sigusr2(int sig) { kcm_debug_events(kcm_context); } int main(int argc, char **argv) { krb5_error_code ret; setprogname(argv[0]); ret = krb5_init_context(&kcm_context); if (ret) { errx (1, "krb5_init_context failed: %d", ret); return ret; } kcm_configure(argc, argv); #ifdef HAVE_SIGACTION { struct sigaction sa; sa.sa_flags = 0; sa.sa_handler = sigusr1; sigemptyset(&sa.sa_mask); sigaction(SIGUSR1, &sa, NULL); sa.sa_handler = sigusr2; sigaction(SIGUSR2, &sa, NULL); sa.sa_handler = SIG_IGN; sigaction(SIGPIPE, &sa, NULL); } #else signal(SIGUSR1, sigusr1); signal(SIGUSR2, sigusr2); signal(SIGPIPE, SIG_IGN); #endif if (detach_from_console && !launchd_flag && daemon_child == -1) roken_detach_prep(argc, argv, "--daemon-child"); rk_pidfile(NULL); if (launchd_flag) { heim_sipc mach; heim_sipc_launchd_mach_init(service_name, kcm_service, NULL, &mach); } else { heim_sipc un; heim_sipc_service_unix(service_name, kcm_service, NULL, &un); } roken_detach_finish(NULL, daemon_child); heim_ipc_main(); krb5_free_context(kcm_context); return 0; } heimdal-7.5.0/kcm/kcm.cat80000644000175000017500000001057113212450764013367 0ustar niknik KCM(8) BSD System Manager's Manual KCM(8) NNAAMMEE kkccmm -- process-based credential cache for Kerberos tickets. SSYYNNOOPPSSIISS kkccmm [----ccaacchhee--nnaammee==_c_a_c_h_e_n_a_m_e] [--cc _f_i_l_e | ----ccoonnffiigg--ffiillee==_f_i_l_e] [--gg _g_r_o_u_p | ----ggrroouupp==_g_r_o_u_p] [----mmaaxx--rreeqquueesstt==_s_i_z_e] [----ddiissaallllooww--ggeettttiinngg--kkrrbbttggtt] [----ddeettaacchh] [--hh | ----hheellpp] [--kk _p_r_i_n_c_i_p_a_l | ----ssyysstteemm--pprriinncciippaall==_p_r_i_n_c_i_p_a_l] [--ll _t_i_m_e | ----lliiffeettiimmee==_t_i_m_e] [--mm _m_o_d_e | ----mmooddee==_m_o_d_e] [--nn | ----nnoo--nnaammee--ccoonnssttrraaiinnttss] [--rr _t_i_m_e | ----rreenneewwaabbllee--lliiffee==_t_i_m_e] [--ss _p_a_t_h | ----ssoocckkeett--ppaatthh==_p_a_t_h] [----ddoooorr--ppaatthh==_p_a_t_h] [--SS _p_r_i_n_c_i_p_a_l | ----sseerrvveerr==_p_r_i_n_c_i_p_a_l] [--tt _k_e_y_t_a_b | ----kkeeyyttaabb==_k_e_y_t_a_b] [--uu _u_s_e_r | ----uusseerr==_u_s_e_r] [--vv | ----vveerrssiioonn] DDEESSCCRRIIPPTTIIOONN kkccmm is a process based credential cache. To use it, set the KRB5CCNAME environment variable to `KCM:_u_i_d' or add the stanza [libdefaults] default_cc_name = KCM:%{uid} to the _/_e_t_c_/_k_r_b_5_._c_o_n_f configuration file and make sure kkccmm is started in the system startup files. The kkccmm daemon can hold the credentials for all users in the system. Access control is done with Unix-like permissions. The daemon checks the access on all operations based on the uid and gid of the user. The tick- ets are renewed as long as is permitted by the KDC's policy. The kkccmm daemon can also keep a SYSTEM credential that server processes can use to access services. One example of usage might be an nss_ldap module that quickly needs to get credentials and doesn't want to renew the ticket itself. Supported options: ----ccaacchhee--nnaammee==_c_a_c_h_e_n_a_m_e system cache name --cc _f_i_l_e, ----ccoonnffiigg--ffiillee==_f_i_l_e location of config file --gg _g_r_o_u_p, ----ggrroouupp==_g_r_o_u_p system cache group ----mmaaxx--rreeqquueesstt==_s_i_z_e max size for a kcm-request ----ddiissaallllooww--ggeettttiinngg--kkrrbbttggtt disallow extracting any krbtgt from the kkccmm daemon. ----ddeettaacchh detach from console --hh, ----hheellpp --kk _p_r_i_n_c_i_p_a_l, ----ssyysstteemm--pprriinncciippaall==_p_r_i_n_c_i_p_a_l system principal name --ll _t_i_m_e, ----lliiffeettiimmee==_t_i_m_e lifetime of system tickets --mm _m_o_d_e, ----mmooddee==_m_o_d_e octal mode of system cache --nn, ----nnoo--nnaammee--ccoonnssttrraaiinnttss disable credentials cache name constraints --rr _t_i_m_e, ----rreenneewwaabbllee--lliiffee==_t_i_m_e renewable lifetime of system tickets --ss _p_a_t_h, ----ssoocckkeett--ppaatthh==_p_a_t_h path to kcm domain socket ----ddoooorr--ppaatthh==_p_a_t_h path to kcm door socket --SS _p_r_i_n_c_i_p_a_l, ----sseerrvveerr==_p_r_i_n_c_i_p_a_l server to get system ticket for --tt _k_e_y_t_a_b, ----kkeeyyttaabb==_k_e_y_t_a_b system keytab name --uu _u_s_e_r, ----uusseerr==_u_s_e_r system cache owner --vv, ----vveerrssiioonn BSD May 29, 2005 BSD heimdal-7.5.0/kcm/client.c0000644000175000017500000001251113026237312013445 0ustar niknik/* * Copyright (c) 2005, PADL Software Pty Ltd. * All rights reserved. * * Portions Copyright (c) 2009 Apple Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of PADL Software nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY PADL SOFTWARE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL PADL SOFTWARE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "kcm_locl.h" #include krb5_error_code kcm_ccache_resolve_client(krb5_context context, kcm_client *client, kcm_operation opcode, const char *name, kcm_ccache *ccache) { krb5_error_code ret; const char *estr; ret = kcm_ccache_resolve(context, name, ccache); if (ret) { estr = krb5_get_error_message(context, ret); kcm_log(1, "Failed to resolve cache %s: %s", name, estr); krb5_free_error_message(context, estr); return ret; } ret = kcm_access(context, client, opcode, *ccache); if (ret) { ret = KRB5_FCC_NOFILE; /* don't disclose */ kcm_release_ccache(context, *ccache); } return ret; } krb5_error_code kcm_ccache_destroy_client(krb5_context context, kcm_client *client, const char *name) { krb5_error_code ret; kcm_ccache ccache; const char *estr; ret = kcm_ccache_resolve(context, name, &ccache); if (ret) { estr = krb5_get_error_message(context, ret); kcm_log(1, "Failed to resolve cache %s: %s", name, estr); krb5_free_error_message(context, estr); return ret; } ret = kcm_access(context, client, KCM_OP_DESTROY, ccache); kcm_cleanup_events(context, ccache); kcm_release_ccache(context, ccache); if (ret) return ret; return kcm_ccache_destroy(context, name); } krb5_error_code kcm_ccache_new_client(krb5_context context, kcm_client *client, const char *name, kcm_ccache *ccache_p) { krb5_error_code ret; kcm_ccache ccache; const char *estr; /* We insist the ccache name starts with UID or UID: */ if (name_constraints != 0) { char prefix[64]; size_t prefix_len; int bad = 1; snprintf(prefix, sizeof(prefix), "%ld:", (long)client->uid); prefix_len = strlen(prefix); if (strncmp(name, prefix, prefix_len) == 0) bad = 0; else { prefix[prefix_len - 1] = '\0'; if (strcmp(name, prefix) == 0) bad = 0; } /* Allow root to create badly-named ccaches */ if (bad && !CLIENT_IS_ROOT(client)) return KRB5_CC_BADNAME; } ret = kcm_ccache_resolve(context, name, &ccache); if (ret == 0) { if ((ccache->uid != client->uid || ccache->gid != client->gid) && !CLIENT_IS_ROOT(client)) return KRB5_FCC_PERM; } else if (ret != KRB5_FCC_NOFILE && !(CLIENT_IS_ROOT(client) && ret == KRB5_FCC_PERM)) { return ret; } if (ret == KRB5_FCC_NOFILE) { ret = kcm_ccache_new(context, name, &ccache); if (ret) { estr = krb5_get_error_message(context, ret); kcm_log(1, "Failed to initialize cache %s: %s", name, estr); krb5_free_error_message(context, estr); return ret; } /* bind to current client */ ccache->uid = client->uid; ccache->gid = client->gid; ccache->session = client->session; } else { ret = kcm_zero_ccache_data(context, ccache); if (ret) { estr = krb5_get_error_message(context, ret); kcm_log(1, "Failed to empty cache %s: %s", name, estr); krb5_free_error_message(context, estr); kcm_release_ccache(context, ccache); return ret; } kcm_cleanup_events(context, ccache); } ret = kcm_access(context, client, KCM_OP_INITIALIZE, ccache); if (ret) { kcm_release_ccache(context, ccache); kcm_ccache_destroy(context, name); return ret; } /* * Finally, if the user is root and the cache was created under * another user's name, chown the cache to that user and their * default gid. */ if (CLIENT_IS_ROOT(client)) { unsigned long uid; int matches = sscanf(name,"%ld:",&uid); if (matches == 0) matches = sscanf(name,"%ld",&uid); if (matches == 1) { struct passwd *pwd = getpwuid(uid); if (pwd != NULL) { gid_t gid = pwd->pw_gid; kcm_chown(context, client, ccache, uid, gid); } } } *ccache_p = ccache; return 0; } heimdal-7.5.0/kcm/headers.h0000644000175000017500000000472512136107747013630 0ustar niknik/* * Copyright (c) 2005, PADL Software Pty Ltd. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of PADL Software nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY PADL SOFTWARE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL PADL SOFTWARE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #ifndef __HEADERS_H__ #define __HEADERS_H__ #include #include #include #include #include #include #include #include #ifdef HAVE_SYS_TYPES_H #include #endif #ifdef HAVE_SYS_PARAM_H #include #endif #ifdef HAVE_FCNTL_H #include #endif #ifdef HAVE_SYS_SELECT_H #include #endif #ifdef HAVE_SYS_SOCKET_H #include #endif #ifdef HAVE_SYS_UN_H #include #endif #ifdef HAVE_SYS_UCRED_H #include #endif #ifdef HAVE_UTIL_H #include #endif #ifdef HAVE_LIBUTIL_H #include #endif #include #include #include #include #include #include #include #include #include #include #include "crypto-headers.h" #endif /* __HEADERS_H__ */ heimdal-7.5.0/kcm/acquire.c0000644000175000017500000001126013026237312013620 0ustar niknik/* * Copyright (c) 2005, PADL Software Pty Ltd. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of PADL Software nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY PADL SOFTWARE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL PADL SOFTWARE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "kcm_locl.h" /* * Get a new ticket using a keytab/cached key and swap it into * an existing redentials cache */ krb5_error_code kcm_ccache_acquire(krb5_context context, kcm_ccache ccache, krb5_creds **credp) { krb5_error_code ret = 0; krb5_creds cred; krb5_const_realm realm; krb5_get_init_creds_opt *opt = NULL; krb5_ccache_data ccdata; char *in_tkt_service = NULL; const char *estr; *credp = NULL; memset(&cred, 0, sizeof(cred)); KCM_ASSERT_VALID(ccache); /* We need a cached key or keytab to acquire credentials */ if (ccache->flags & KCM_FLAGS_USE_CACHED_KEY) { if (ccache->key.keyblock.keyvalue.length == 0) krb5_abortx(context, "kcm_ccache_acquire: KCM_FLAGS_USE_CACHED_KEY without key"); } else if (ccache->flags & KCM_FLAGS_USE_KEYTAB) { if (ccache->key.keytab == NULL) krb5_abortx(context, "kcm_ccache_acquire: KCM_FLAGS_USE_KEYTAB without keytab"); } else { kcm_log(0, "Cannot acquire initial credentials for cache %s without key", ccache->name); return KRB5_FCC_INTERNAL; } HEIMDAL_MUTEX_lock(&ccache->mutex); /* Fake up an internal ccache */ kcm_internal_ccache(context, ccache, &ccdata); /* Now, actually acquire the creds */ if (ccache->server != NULL) { ret = krb5_unparse_name(context, ccache->server, &in_tkt_service); if (ret) { estr = krb5_get_error_message(context, ret); kcm_log(0, "Failed to unparse service principal name for cache %s: %s", ccache->name, estr); krb5_free_error_message(context, estr); goto out; } } realm = krb5_principal_get_realm(context, ccache->client); ret = krb5_get_init_creds_opt_alloc(context, &opt); if (ret) goto out; krb5_get_init_creds_opt_set_default_flags(context, "kcm", realm, opt); if (ccache->tkt_life != 0) krb5_get_init_creds_opt_set_tkt_life(opt, ccache->tkt_life); if (ccache->renew_life != 0) krb5_get_init_creds_opt_set_renew_life(opt, ccache->renew_life); if (ccache->flags & KCM_FLAGS_USE_CACHED_KEY) { ret = krb5_get_init_creds_keyblock(context, &cred, ccache->client, &ccache->key.keyblock, 0, in_tkt_service, opt); } else { /* loosely based on lib/krb5/init_creds_pw.c */ ret = krb5_get_init_creds_keytab(context, &cred, ccache->client, ccache->key.keytab, 0, in_tkt_service, opt); } if (ret) { estr = krb5_get_error_message(context, ret); kcm_log(0, "Failed to acquire credentials for cache %s: %s", ccache->name, estr); krb5_free_error_message(context, estr); goto out; } /* Swap them in */ kcm_ccache_remove_creds_internal(context, ccache); ret = kcm_ccache_store_cred_internal(context, ccache, &cred, 0, credp); if (ret) { estr = krb5_get_error_message(context, ret); kcm_log(0, "Failed to store credentials for cache %s: %s", ccache->name, estr); krb5_free_error_message(context, estr); krb5_free_cred_contents(context, &cred); goto out; } out: free(in_tkt_service); if (opt) krb5_get_init_creds_opt_free(context, opt); HEIMDAL_MUTEX_unlock(&ccache->mutex); return ret; } heimdal-7.5.0/kcm/Makefile.am0000644000175000017500000000157613026237312014070 0ustar niknik# $Id$ include $(top_srcdir)/Makefile.am.common AM_CPPFLAGS += $(INCLUDE_libintl) -I$(srcdir)/../lib/krb5 libexec_PROGRAMS = kcm kcm_SOURCES = \ acl.c \ acquire.c \ cache.c \ client.c \ config.c \ connect.c \ events.c \ glue.c \ headers.h \ kcm_locl.h \ log.c \ main.c \ protocol.c \ sessions.c \ renew.c noinst_HEADERS = $(srcdir)/kcm-protos.h $(srcdir)/kcm-protos.h: $(kcm_SOURCES) cd $(srcdir); perl ../cf/make-proto.pl -o kcm-protos.h -q -P comment $(kcm_SOURCES) || rm -f kcm-protos.h $(kcm_OBJECTS): $(srcdir)/kcm-protos.h man_MANS = kcm.8 LDADD = $(top_builddir)/lib/hdb/libhdb.la \ $(top_builddir)/lib/krb5/libkrb5.la \ $(LIB_hcrypto) \ $(top_builddir)/lib/asn1/libasn1.la \ $(top_builddir)/lib/ntlm/libheimntlm.la \ $(top_builddir)/lib/ipc/libheim-ipcs.la \ $(LIB_roken) \ $(LIB_door_create) \ $(LIB_pidfile) EXTRA_DIST = NTMakefile $(man_MANS) heimdal-7.5.0/kcm/Makefile.in0000644000175000017500000011000213212444520014060 0ustar niknik# Makefile.in generated by automake 1.15.1 from Makefile.am. # @configure_input@ # Copyright (C) 1994-2017 Free Software Foundation, Inc. # This Makefile.in is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, # with or without modifications, as long as this notice is preserved. # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY, to the extent permitted by law; without # even the implied warranty of MERCHANTABILITY or FITNESS FOR A # PARTICULAR PURPOSE. @SET_MAKE@ # $Id$ # $Id$ # $Id$ VPATH = @srcdir@ am__is_gnu_make = { \ if test -z '$(MAKELEVEL)'; then \ false; \ elif test -n '$(MAKE_HOST)'; then \ true; \ elif test -n '$(MAKE_VERSION)' && test -n '$(CURDIR)'; then \ true; \ else \ false; \ fi; \ } am__make_running_with_option = \ case $${target_option-} in \ ?) ;; \ *) echo "am__make_running_with_option: internal error: invalid" \ "target option '$${target_option-}' specified" >&2; \ exit 1;; \ esac; \ has_opt=no; \ sane_makeflags=$$MAKEFLAGS; \ if $(am__is_gnu_make); then \ sane_makeflags=$$MFLAGS; \ else \ case $$MAKEFLAGS in \ *\\[\ \ ]*) \ bs=\\; \ sane_makeflags=`printf '%s\n' "$$MAKEFLAGS" \ | sed "s/$$bs$$bs[$$bs $$bs ]*//g"`;; \ esac; \ fi; \ skip_next=no; \ strip_trailopt () \ { \ flg=`printf '%s\n' "$$flg" | sed "s/$$1.*$$//"`; \ }; \ for flg in $$sane_makeflags; do \ test $$skip_next = yes && { skip_next=no; continue; }; \ case $$flg in \ *=*|--*) continue;; \ -*I) strip_trailopt 'I'; skip_next=yes;; \ -*I?*) strip_trailopt 'I';; \ -*O) strip_trailopt 'O'; skip_next=yes;; \ -*O?*) strip_trailopt 'O';; \ -*l) strip_trailopt 'l'; skip_next=yes;; \ -*l?*) strip_trailopt 'l';; \ -[dEDm]) skip_next=yes;; \ -[JT]) skip_next=yes;; \ esac; \ case $$flg in \ *$$target_option*) has_opt=yes; break;; \ esac; \ done; \ test $$has_opt = yes am__make_dryrun = (target_option=n; $(am__make_running_with_option)) am__make_keepgoing = (target_option=k; $(am__make_running_with_option)) pkgdatadir = $(datadir)/@PACKAGE@ pkgincludedir = $(includedir)/@PACKAGE@ pkglibdir = $(libdir)/@PACKAGE@ pkglibexecdir = $(libexecdir)/@PACKAGE@ am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd install_sh_DATA = $(install_sh) -c -m 644 install_sh_PROGRAM = $(install_sh) -c install_sh_SCRIPT = $(install_sh) -c INSTALL_HEADER = $(INSTALL_DATA) transform = $(program_transform_name) NORMAL_INSTALL = : PRE_INSTALL = : POST_INSTALL = : NORMAL_UNINSTALL = : PRE_UNINSTALL = : POST_UNINSTALL = : build_triplet = @build@ host_triplet = @host@ libexec_PROGRAMS = kcm$(EXEEXT) subdir = kcm ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 am__aclocal_m4_deps = $(top_srcdir)/cf/aix.m4 \ $(top_srcdir)/cf/auth-modules.m4 \ $(top_srcdir)/cf/broken-getaddrinfo.m4 \ $(top_srcdir)/cf/broken-glob.m4 \ $(top_srcdir)/cf/broken-realloc.m4 \ $(top_srcdir)/cf/broken-snprintf.m4 $(top_srcdir)/cf/broken.m4 \ $(top_srcdir)/cf/broken2.m4 $(top_srcdir)/cf/c-attribute.m4 \ $(top_srcdir)/cf/capabilities.m4 \ $(top_srcdir)/cf/check-compile-et.m4 \ $(top_srcdir)/cf/check-getpwnam_r-posix.m4 \ $(top_srcdir)/cf/check-man.m4 \ $(top_srcdir)/cf/check-netinet-ip-and-tcp.m4 \ $(top_srcdir)/cf/check-type-extra.m4 \ $(top_srcdir)/cf/check-var.m4 $(top_srcdir)/cf/crypto.m4 \ $(top_srcdir)/cf/db.m4 $(top_srcdir)/cf/destdirs.m4 \ $(top_srcdir)/cf/dispatch.m4 $(top_srcdir)/cf/dlopen.m4 \ $(top_srcdir)/cf/find-func-no-libs.m4 \ $(top_srcdir)/cf/find-func-no-libs2.m4 \ $(top_srcdir)/cf/find-func.m4 \ $(top_srcdir)/cf/find-if-not-broken.m4 \ $(top_srcdir)/cf/framework-security.m4 \ $(top_srcdir)/cf/have-struct-field.m4 \ $(top_srcdir)/cf/have-type.m4 $(top_srcdir)/cf/irix.m4 \ $(top_srcdir)/cf/krb-bigendian.m4 \ $(top_srcdir)/cf/krb-func-getlogin.m4 \ $(top_srcdir)/cf/krb-ipv6.m4 $(top_srcdir)/cf/krb-prog-ln-s.m4 \ $(top_srcdir)/cf/krb-prog-perl.m4 \ $(top_srcdir)/cf/krb-readline.m4 \ $(top_srcdir)/cf/krb-struct-spwd.m4 \ $(top_srcdir)/cf/krb-struct-winsize.m4 \ $(top_srcdir)/cf/largefile.m4 $(top_srcdir)/cf/libtool.m4 \ $(top_srcdir)/cf/ltoptions.m4 $(top_srcdir)/cf/ltsugar.m4 \ $(top_srcdir)/cf/ltversion.m4 $(top_srcdir)/cf/lt~obsolete.m4 \ $(top_srcdir)/cf/mips-abi.m4 $(top_srcdir)/cf/misc.m4 \ $(top_srcdir)/cf/need-proto.m4 $(top_srcdir)/cf/osfc2.m4 \ $(top_srcdir)/cf/otp.m4 $(top_srcdir)/cf/pkg.m4 \ $(top_srcdir)/cf/proto-compat.m4 $(top_srcdir)/cf/pthreads.m4 \ $(top_srcdir)/cf/resolv.m4 $(top_srcdir)/cf/retsigtype.m4 \ $(top_srcdir)/cf/roken-frag.m4 \ $(top_srcdir)/cf/socket-wrapper.m4 $(top_srcdir)/cf/sunos.m4 \ $(top_srcdir)/cf/telnet.m4 $(top_srcdir)/cf/test-package.m4 \ $(top_srcdir)/cf/version-script.m4 $(top_srcdir)/cf/wflags.m4 \ $(top_srcdir)/cf/win32.m4 $(top_srcdir)/cf/with-all.m4 \ $(top_srcdir)/acinclude.m4 $(top_srcdir)/configure.ac am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \ $(ACLOCAL_M4) DIST_COMMON = $(srcdir)/Makefile.am $(noinst_HEADERS) \ $(am__DIST_COMMON) mkinstalldirs = $(install_sh) -d CONFIG_HEADER = $(top_builddir)/include/config.h CONFIG_CLEAN_FILES = CONFIG_CLEAN_VPATH_FILES = am__installdirs = "$(DESTDIR)$(libexecdir)" "$(DESTDIR)$(man8dir)" PROGRAMS = $(libexec_PROGRAMS) am_kcm_OBJECTS = acl.$(OBJEXT) acquire.$(OBJEXT) cache.$(OBJEXT) \ client.$(OBJEXT) config.$(OBJEXT) connect.$(OBJEXT) \ events.$(OBJEXT) glue.$(OBJEXT) log.$(OBJEXT) main.$(OBJEXT) \ protocol.$(OBJEXT) sessions.$(OBJEXT) renew.$(OBJEXT) kcm_OBJECTS = $(am_kcm_OBJECTS) kcm_LDADD = $(LDADD) am__DEPENDENCIES_1 = kcm_DEPENDENCIES = $(top_builddir)/lib/hdb/libhdb.la \ $(top_builddir)/lib/krb5/libkrb5.la $(am__DEPENDENCIES_1) \ $(top_builddir)/lib/asn1/libasn1.la \ $(top_builddir)/lib/ntlm/libheimntlm.la \ $(top_builddir)/lib/ipc/libheim-ipcs.la $(am__DEPENDENCIES_1) \ $(am__DEPENDENCIES_1) $(am__DEPENDENCIES_1) AM_V_lt = $(am__v_lt_@AM_V@) am__v_lt_ = $(am__v_lt_@AM_DEFAULT_V@) am__v_lt_0 = --silent am__v_lt_1 = AM_V_P = $(am__v_P_@AM_V@) am__v_P_ = $(am__v_P_@AM_DEFAULT_V@) am__v_P_0 = false am__v_P_1 = : AM_V_GEN = $(am__v_GEN_@AM_V@) am__v_GEN_ = $(am__v_GEN_@AM_DEFAULT_V@) am__v_GEN_0 = @echo " GEN " $@; am__v_GEN_1 = AM_V_at = $(am__v_at_@AM_V@) am__v_at_ = $(am__v_at_@AM_DEFAULT_V@) am__v_at_0 = @ am__v_at_1 = depcomp = $(SHELL) $(top_srcdir)/depcomp am__depfiles_maybe = depfiles am__mv = mv -f COMPILE = $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) \ $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) LTCOMPILE = $(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) \ $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) \ $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) \ $(AM_CFLAGS) $(CFLAGS) AM_V_CC = $(am__v_CC_@AM_V@) am__v_CC_ = $(am__v_CC_@AM_DEFAULT_V@) am__v_CC_0 = @echo " CC " $@; am__v_CC_1 = CCLD = $(CC) LINK = $(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) \ $(LIBTOOLFLAGS) --mode=link $(CCLD) $(AM_CFLAGS) $(CFLAGS) \ $(AM_LDFLAGS) $(LDFLAGS) -o $@ AM_V_CCLD = $(am__v_CCLD_@AM_V@) am__v_CCLD_ = $(am__v_CCLD_@AM_DEFAULT_V@) am__v_CCLD_0 = @echo " CCLD " $@; am__v_CCLD_1 = SOURCES = $(kcm_SOURCES) DIST_SOURCES = $(kcm_SOURCES) am__can_run_installinfo = \ case $$AM_UPDATE_INFO_DIR in \ n|no|NO) false;; \ *) (install-info --version) >/dev/null 2>&1;; \ esac am__vpath_adj_setup = srcdirstrip=`echo "$(srcdir)" | sed 's|.|.|g'`; am__vpath_adj = case $$p in \ $(srcdir)/*) f=`echo "$$p" | sed "s|^$$srcdirstrip/||"`;; \ *) f=$$p;; \ esac; am__strip_dir = f=`echo $$p | sed -e 's|^.*/||'`; am__install_max = 40 am__nobase_strip_setup = \ srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*|]/\\\\&/g'` am__nobase_strip = \ for p in $$list; do echo "$$p"; done | sed -e "s|$$srcdirstrip/||" am__nobase_list = $(am__nobase_strip_setup); \ for p in $$list; do echo "$$p $$p"; done | \ sed "s| $$srcdirstrip/| |;"' / .*\//!s/ .*/ ./; s,\( .*\)/[^/]*$$,\1,' | \ $(AWK) 'BEGIN { files["."] = "" } { files[$$2] = files[$$2] " " $$1; \ if (++n[$$2] == $(am__install_max)) \ { print $$2, files[$$2]; n[$$2] = 0; files[$$2] = "" } } \ END { for (dir in files) print dir, files[dir] }' am__base_list = \ sed '$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;s/\n/ /g' | \ sed '$$!N;$$!N;$$!N;$$!N;s/\n/ /g' am__uninstall_files_from_dir = { \ test -z "$$files" \ || { test ! -d "$$dir" && test ! -f "$$dir" && test ! -r "$$dir"; } \ || { echo " ( cd '$$dir' && rm -f" $$files ")"; \ $(am__cd) "$$dir" && rm -f $$files; }; \ } man8dir = $(mandir)/man8 MANS = $(man_MANS) HEADERS = $(noinst_HEADERS) am__tagged_files = $(HEADERS) $(SOURCES) $(TAGS_FILES) $(LISP) # Read a list of newline-separated strings from the standard input, # and print each of them once, without duplicates. Input order is # *not* preserved. am__uniquify_input = $(AWK) '\ BEGIN { nonempty = 0; } \ { items[$$0] = 1; nonempty = 1; } \ END { if (nonempty) { for (i in items) print i; }; } \ ' # Make sure the list of sources is unique. This is necessary because, # e.g., the same source file might be shared among _SOURCES variables # for different programs/libraries. am__define_uniq_tagged_files = \ list='$(am__tagged_files)'; \ unique=`for i in $$list; do \ if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ done | $(am__uniquify_input)` ETAGS = etags CTAGS = ctags am__DIST_COMMON = $(srcdir)/Makefile.in \ $(top_srcdir)/Makefile.am.common \ $(top_srcdir)/cf/Makefile.am.common $(top_srcdir)/depcomp DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST) ACLOCAL = @ACLOCAL@ AIX_EXTRA_KAFS = @AIX_EXTRA_KAFS@ AMTAR = @AMTAR@ AM_DEFAULT_VERBOSITY = @AM_DEFAULT_VERBOSITY@ AR = @AR@ AS = @AS@ ASN1_COMPILE = @ASN1_COMPILE@ ASN1_COMPILE_DEP = @ASN1_COMPILE_DEP@ AUTOCONF = @AUTOCONF@ AUTOHEADER = @AUTOHEADER@ AUTOMAKE = @AUTOMAKE@ AWK = @AWK@ CANONICAL_HOST = @CANONICAL_HOST@ CAPNG_CFLAGS = @CAPNG_CFLAGS@ CAPNG_LIBS = @CAPNG_LIBS@ CATMAN = @CATMAN@ CATMANEXT = @CATMANEXT@ CC = @CC@ CCDEPMODE = @CCDEPMODE@ CFLAGS = @CFLAGS@ COMPILE_ET = @COMPILE_ET@ CPP = @CPP@ CPPFLAGS = @CPPFLAGS@ CYGPATH_W = @CYGPATH_W@ DB1LIB = @DB1LIB@ DB3LIB = @DB3LIB@ DBHEADER = @DBHEADER@ DEFS = @DEFS@ DEPDIR = @DEPDIR@ DIR_com_err = @DIR_com_err@ DIR_hdbdir = @DIR_hdbdir@ DIR_roken = @DIR_roken@ DLLTOOL = @DLLTOOL@ DSYMUTIL = @DSYMUTIL@ DUMPBIN = @DUMPBIN@ ECHO_C = @ECHO_C@ ECHO_N = @ECHO_N@ ECHO_T = @ECHO_T@ EGREP = @EGREP@ ENABLE_AFS_STRING_TO_KEY = @ENABLE_AFS_STRING_TO_KEY@ EXEEXT = @EXEEXT@ FGREP = @FGREP@ GCD_MIG = @GCD_MIG@ GREP = @GREP@ GROFF = @GROFF@ INCLUDES_roken = @INCLUDES_roken@ INCLUDE_libedit = @INCLUDE_libedit@ INCLUDE_libintl = @INCLUDE_libintl@ INCLUDE_openldap = @INCLUDE_openldap@ INCLUDE_openssl_crypto = @INCLUDE_openssl_crypto@ INCLUDE_readline = @INCLUDE_readline@ INCLUDE_sqlite3 = @INCLUDE_sqlite3@ INSTALL = @INSTALL@ INSTALL_DATA = @INSTALL_DATA@ INSTALL_PROGRAM = @INSTALL_PROGRAM@ INSTALL_SCRIPT = @INSTALL_SCRIPT@ INSTALL_STRIP_PROGRAM = @INSTALL_STRIP_PROGRAM@ LD = @LD@ LDFLAGS = @LDFLAGS@ LDFLAGS_VERSION_SCRIPT = @LDFLAGS_VERSION_SCRIPT@ LEX = @LEX@ LEXLIB = @LEXLIB@ LEX_OUTPUT_ROOT = @LEX_OUTPUT_ROOT@ LIBADD_roken = @LIBADD_roken@ LIBOBJS = @LIBOBJS@ LIBS = @LIBS@ LIBTOOL = @LIBTOOL@ LIB_AUTH_SUBDIRS = @LIB_AUTH_SUBDIRS@ LIB_bswap16 = @LIB_bswap16@ LIB_bswap32 = @LIB_bswap32@ LIB_bswap64 = @LIB_bswap64@ LIB_com_err = @LIB_com_err@ LIB_com_err_a = @LIB_com_err_a@ LIB_com_err_so = @LIB_com_err_so@ LIB_crypt = @LIB_crypt@ LIB_db_create = @LIB_db_create@ LIB_dbm_firstkey = @LIB_dbm_firstkey@ LIB_dbopen = @LIB_dbopen@ LIB_dispatch_async_f = @LIB_dispatch_async_f@ LIB_dladdr = @LIB_dladdr@ LIB_dlopen = @LIB_dlopen@ LIB_dn_expand = @LIB_dn_expand@ LIB_dns_search = @LIB_dns_search@ LIB_door_create = @LIB_door_create@ LIB_freeaddrinfo = @LIB_freeaddrinfo@ LIB_gai_strerror = @LIB_gai_strerror@ LIB_getaddrinfo = @LIB_getaddrinfo@ LIB_gethostbyname = @LIB_gethostbyname@ LIB_gethostbyname2 = @LIB_gethostbyname2@ LIB_getnameinfo = @LIB_getnameinfo@ LIB_getpwnam_r = @LIB_getpwnam_r@ LIB_getsockopt = @LIB_getsockopt@ LIB_hcrypto = @LIB_hcrypto@ LIB_hcrypto_a = @LIB_hcrypto_a@ LIB_hcrypto_appl = @LIB_hcrypto_appl@ LIB_hcrypto_so = @LIB_hcrypto_so@ LIB_hstrerror = @LIB_hstrerror@ LIB_kdb = @LIB_kdb@ LIB_libedit = @LIB_libedit@ LIB_libintl = @LIB_libintl@ LIB_loadquery = @LIB_loadquery@ LIB_logout = @LIB_logout@ LIB_logwtmp = @LIB_logwtmp@ LIB_openldap = @LIB_openldap@ LIB_openpty = @LIB_openpty@ LIB_openssl_crypto = @LIB_openssl_crypto@ LIB_otp = @LIB_otp@ LIB_pidfile = @LIB_pidfile@ LIB_readline = @LIB_readline@ LIB_res_ndestroy = @LIB_res_ndestroy@ LIB_res_nsearch = @LIB_res_nsearch@ LIB_res_search = @LIB_res_search@ LIB_roken = @LIB_roken@ LIB_security = @LIB_security@ LIB_setsockopt = @LIB_setsockopt@ LIB_socket = @LIB_socket@ LIB_sqlite3 = @LIB_sqlite3@ LIB_syslog = @LIB_syslog@ LIB_tgetent = @LIB_tgetent@ LIPO = @LIPO@ LMDBLIB = @LMDBLIB@ LN_S = @LN_S@ LTLIBOBJS = @LTLIBOBJS@ LT_SYS_LIBRARY_PATH = @LT_SYS_LIBRARY_PATH@ MAINT = @MAINT@ MAKEINFO = @MAKEINFO@ MANIFEST_TOOL = @MANIFEST_TOOL@ MKDIR_P = @MKDIR_P@ NDBMLIB = @NDBMLIB@ NM = @NM@ NMEDIT = @NMEDIT@ NO_AFS = @NO_AFS@ NROFF = @NROFF@ OBJDUMP = @OBJDUMP@ OBJEXT = @OBJEXT@ OTOOL = @OTOOL@ OTOOL64 = @OTOOL64@ PACKAGE = @PACKAGE@ PACKAGE_BUGREPORT = @PACKAGE_BUGREPORT@ PACKAGE_NAME = @PACKAGE_NAME@ PACKAGE_STRING = @PACKAGE_STRING@ PACKAGE_TARNAME = @PACKAGE_TARNAME@ PACKAGE_URL = @PACKAGE_URL@ PACKAGE_VERSION = @PACKAGE_VERSION@ PATH_SEPARATOR = @PATH_SEPARATOR@ PERL = @PERL@ PKG_CONFIG = @PKG_CONFIG@ PTHREAD_CFLAGS = @PTHREAD_CFLAGS@ PTHREAD_LDADD = @PTHREAD_LDADD@ PTHREAD_LIBADD = @PTHREAD_LIBADD@ RANLIB = @RANLIB@ SED = @SED@ SET_MAKE = @SET_MAKE@ SHELL = @SHELL@ SLC = @SLC@ SLC_DEP = @SLC_DEP@ STRIP = @STRIP@ VERSION = @VERSION@ VERSIONING = @VERSIONING@ WFLAGS = @WFLAGS@ WFLAGS_LITE = @WFLAGS_LITE@ YACC = @YACC@ YFLAGS = @YFLAGS@ abs_builddir = @abs_builddir@ abs_srcdir = @abs_srcdir@ abs_top_builddir = @abs_top_builddir@ abs_top_srcdir = @abs_top_srcdir@ ac_ct_AR = @ac_ct_AR@ ac_ct_CC = @ac_ct_CC@ ac_ct_DUMPBIN = @ac_ct_DUMPBIN@ am__include = @am__include@ am__leading_dot = @am__leading_dot@ am__quote = @am__quote@ am__tar = @am__tar@ am__untar = @am__untar@ bindir = @bindir@ build = @build@ build_alias = @build_alias@ build_cpu = @build_cpu@ build_os = @build_os@ build_vendor = @build_vendor@ builddir = @builddir@ datadir = @datadir@ datarootdir = @datarootdir@ db_type = @db_type@ db_type_preference = @db_type_preference@ docdir = @docdir@ dpagaix_cflags = @dpagaix_cflags@ dpagaix_ldadd = @dpagaix_ldadd@ dpagaix_ldflags = @dpagaix_ldflags@ dvidir = @dvidir@ exec_prefix = @exec_prefix@ host = @host@ host_alias = @host_alias@ host_cpu = @host_cpu@ host_os = @host_os@ host_vendor = @host_vendor@ htmldir = @htmldir@ includedir = @includedir@ infodir = @infodir@ install_sh = @install_sh@ libdir = @libdir@ libexecdir = @libexecdir@ localedir = @localedir@ localstatedir = @localstatedir@ mandir = @mandir@ mkdir_p = @mkdir_p@ oldincludedir = @oldincludedir@ pdfdir = @pdfdir@ prefix = @prefix@ program_transform_name = @program_transform_name@ psdir = @psdir@ sbindir = @sbindir@ sharedstatedir = @sharedstatedir@ srcdir = @srcdir@ subdirs = @subdirs@ sysconfdir = @sysconfdir@ target_alias = @target_alias@ top_build_prefix = @top_build_prefix@ top_builddir = @top_builddir@ top_srcdir = @top_srcdir@ SUFFIXES = .et .h .pc.in .pc .x .z .hx .1 .3 .5 .7 .8 .cat1 .cat3 \ .cat5 .cat7 .cat8 DEFAULT_INCLUDES = -I. -I$(srcdir) -I$(top_builddir)/include -I$(top_srcdir)/include AM_CPPFLAGS = $(INCLUDES_roken) $(INCLUDE_libintl) \ -I$(srcdir)/../lib/krb5 @do_roken_rename_TRUE@ROKEN_RENAME = -DROKEN_RENAME AM_CFLAGS = $(WFLAGS) CP = cp buildinclude = $(top_builddir)/include LIB_XauReadAuth = @LIB_XauReadAuth@ LIB_el_init = @LIB_el_init@ LIB_getattr = @LIB_getattr@ LIB_getpwent_r = @LIB_getpwent_r@ LIB_odm_initialize = @LIB_odm_initialize@ LIB_setpcred = @LIB_setpcred@ INCLUDE_krb4 = @INCLUDE_krb4@ LIB_krb4 = @LIB_krb4@ libexec_heimdaldir = $(libexecdir)/heimdal NROFF_MAN = groff -mandoc -Tascii @NO_AFS_FALSE@LIB_kafs = $(top_builddir)/lib/kafs/libkafs.la $(AIX_EXTRA_KAFS) @NO_AFS_TRUE@LIB_kafs = @KRB5_TRUE@LIB_krb5 = $(top_builddir)/lib/krb5/libkrb5.la \ @KRB5_TRUE@ $(top_builddir)/lib/asn1/libasn1.la @KRB5_TRUE@LIB_gssapi = $(top_builddir)/lib/gssapi/libgssapi.la LIB_heimbase = $(top_builddir)/lib/base/libheimbase.la @DCE_TRUE@LIB_kdfs = $(top_builddir)/lib/kdfs/libkdfs.la #silent-rules heim_verbose = $(heim_verbose_$(V)) heim_verbose_ = $(heim_verbose_$(AM_DEFAULT_VERBOSITY)) heim_verbose_0 = @echo " GEN "$@; kcm_SOURCES = \ acl.c \ acquire.c \ cache.c \ client.c \ config.c \ connect.c \ events.c \ glue.c \ headers.h \ kcm_locl.h \ log.c \ main.c \ protocol.c \ sessions.c \ renew.c noinst_HEADERS = $(srcdir)/kcm-protos.h man_MANS = kcm.8 LDADD = $(top_builddir)/lib/hdb/libhdb.la \ $(top_builddir)/lib/krb5/libkrb5.la \ $(LIB_hcrypto) \ $(top_builddir)/lib/asn1/libasn1.la \ $(top_builddir)/lib/ntlm/libheimntlm.la \ $(top_builddir)/lib/ipc/libheim-ipcs.la \ $(LIB_roken) \ $(LIB_door_create) \ $(LIB_pidfile) EXTRA_DIST = NTMakefile $(man_MANS) all: all-am .SUFFIXES: .SUFFIXES: .et .h .pc.in .pc .x .z .hx .1 .3 .5 .7 .8 .cat1 .cat3 .cat5 .cat7 .cat8 .c .lo .o .obj $(srcdir)/Makefile.in: @MAINTAINER_MODE_TRUE@ $(srcdir)/Makefile.am $(top_srcdir)/Makefile.am.common $(top_srcdir)/cf/Makefile.am.common $(am__configure_deps) @for dep in $?; do \ case '$(am__configure_deps)' in \ *$$dep*) \ ( cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh ) \ && { if test -f $@; then exit 0; else break; fi; }; \ exit 1;; \ esac; \ done; \ echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign kcm/Makefile'; \ $(am__cd) $(top_srcdir) && \ $(AUTOMAKE) --foreign kcm/Makefile Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status @case '$?' in \ *config.status*) \ cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh;; \ *) \ echo ' cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe)'; \ cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe);; \ esac; $(top_srcdir)/Makefile.am.common $(top_srcdir)/cf/Makefile.am.common $(am__empty): $(top_builddir)/config.status: $(top_srcdir)/configure $(CONFIG_STATUS_DEPENDENCIES) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(top_srcdir)/configure: @MAINTAINER_MODE_TRUE@ $(am__configure_deps) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(ACLOCAL_M4): @MAINTAINER_MODE_TRUE@ $(am__aclocal_m4_deps) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(am__aclocal_m4_deps): install-libexecPROGRAMS: $(libexec_PROGRAMS) @$(NORMAL_INSTALL) @list='$(libexec_PROGRAMS)'; test -n "$(libexecdir)" || list=; \ if test -n "$$list"; then \ echo " $(MKDIR_P) '$(DESTDIR)$(libexecdir)'"; \ $(MKDIR_P) "$(DESTDIR)$(libexecdir)" || exit 1; \ fi; \ for p in $$list; do echo "$$p $$p"; done | \ sed 's/$(EXEEXT)$$//' | \ while read p p1; do if test -f $$p \ || test -f $$p1 \ ; then echo "$$p"; echo "$$p"; else :; fi; \ done | \ sed -e 'p;s,.*/,,;n;h' \ -e 's|.*|.|' \ -e 'p;x;s,.*/,,;s/$(EXEEXT)$$//;$(transform);s/$$/$(EXEEXT)/' | \ sed 'N;N;N;s,\n, ,g' | \ $(AWK) 'BEGIN { files["."] = ""; dirs["."] = 1 } \ { d=$$3; if (dirs[d] != 1) { print "d", d; dirs[d] = 1 } \ if ($$2 == $$4) files[d] = files[d] " " $$1; \ else { print "f", $$3 "/" $$4, $$1; } } \ END { for (d in files) print "f", d, files[d] }' | \ while read type dir files; do \ if test "$$dir" = .; then dir=; else dir=/$$dir; fi; \ test -z "$$files" || { \ echo " $(INSTALL_PROGRAM_ENV) $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=install $(INSTALL_PROGRAM) $$files '$(DESTDIR)$(libexecdir)$$dir'"; \ $(INSTALL_PROGRAM_ENV) $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=install $(INSTALL_PROGRAM) $$files "$(DESTDIR)$(libexecdir)$$dir" || exit $$?; \ } \ ; done uninstall-libexecPROGRAMS: @$(NORMAL_UNINSTALL) @list='$(libexec_PROGRAMS)'; test -n "$(libexecdir)" || list=; \ files=`for p in $$list; do echo "$$p"; done | \ sed -e 'h;s,^.*/,,;s/$(EXEEXT)$$//;$(transform)' \ -e 's/$$/$(EXEEXT)/' \ `; \ test -n "$$list" || exit 0; \ echo " ( cd '$(DESTDIR)$(libexecdir)' && rm -f" $$files ")"; \ cd "$(DESTDIR)$(libexecdir)" && rm -f $$files clean-libexecPROGRAMS: @list='$(libexec_PROGRAMS)'; test -n "$$list" || exit 0; \ echo " rm -f" $$list; \ rm -f $$list || exit $$?; \ test -n "$(EXEEXT)" || exit 0; \ list=`for p in $$list; do echo "$$p"; done | sed 's/$(EXEEXT)$$//'`; \ echo " rm -f" $$list; \ rm -f $$list kcm$(EXEEXT): $(kcm_OBJECTS) $(kcm_DEPENDENCIES) $(EXTRA_kcm_DEPENDENCIES) @rm -f kcm$(EXEEXT) $(AM_V_CCLD)$(LINK) $(kcm_OBJECTS) $(kcm_LDADD) $(LIBS) mostlyclean-compile: -rm -f *.$(OBJEXT) distclean-compile: -rm -f *.tab.c @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/acl.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/acquire.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/cache.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/client.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/config.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/connect.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/events.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/glue.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/log.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/main.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/protocol.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/renew.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/sessions.Po@am__quote@ .c.o: @am__fastdepCC_TRUE@ $(AM_V_CC)$(COMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o $@ $< @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='$<' object='$@' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(COMPILE) -c -o $@ $< .c.obj: @am__fastdepCC_TRUE@ $(AM_V_CC)$(COMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o $@ `$(CYGPATH_W) '$<'` @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='$<' object='$@' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(COMPILE) -c -o $@ `$(CYGPATH_W) '$<'` .c.lo: @am__fastdepCC_TRUE@ $(AM_V_CC)$(LTCOMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o $@ $< @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='$<' object='$@' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LTCOMPILE) -c -o $@ $< mostlyclean-libtool: -rm -f *.lo clean-libtool: -rm -rf .libs _libs install-man8: $(man_MANS) @$(NORMAL_INSTALL) @list1=''; \ list2='$(man_MANS)'; \ test -n "$(man8dir)" \ && test -n "`echo $$list1$$list2`" \ || exit 0; \ echo " $(MKDIR_P) '$(DESTDIR)$(man8dir)'"; \ $(MKDIR_P) "$(DESTDIR)$(man8dir)" || exit 1; \ { for i in $$list1; do echo "$$i"; done; \ if test -n "$$list2"; then \ for i in $$list2; do echo "$$i"; done \ | sed -n '/\.8[a-z]*$$/p'; \ fi; \ } | while read p; do \ if test -f $$p; then d=; else d="$(srcdir)/"; fi; \ echo "$$d$$p"; echo "$$p"; \ done | \ sed -e 'n;s,.*/,,;p;h;s,.*\.,,;s,^[^8][0-9a-z]*$$,8,;x' \ -e 's,\.[0-9a-z]*$$,,;$(transform);G;s,\n,.,' | \ sed 'N;N;s,\n, ,g' | { \ list=; while read file base inst; do \ if test "$$base" = "$$inst"; then list="$$list $$file"; else \ echo " $(INSTALL_DATA) '$$file' '$(DESTDIR)$(man8dir)/$$inst'"; \ $(INSTALL_DATA) "$$file" "$(DESTDIR)$(man8dir)/$$inst" || exit $$?; \ fi; \ done; \ for i in $$list; do echo "$$i"; done | $(am__base_list) | \ while read files; do \ test -z "$$files" || { \ echo " $(INSTALL_DATA) $$files '$(DESTDIR)$(man8dir)'"; \ $(INSTALL_DATA) $$files "$(DESTDIR)$(man8dir)" || exit $$?; }; \ done; } uninstall-man8: @$(NORMAL_UNINSTALL) @list=''; test -n "$(man8dir)" || exit 0; \ files=`{ for i in $$list; do echo "$$i"; done; \ l2='$(man_MANS)'; for i in $$l2; do echo "$$i"; done | \ sed -n '/\.8[a-z]*$$/p'; \ } | sed -e 's,.*/,,;h;s,.*\.,,;s,^[^8][0-9a-z]*$$,8,;x' \ -e 's,\.[0-9a-z]*$$,,;$(transform);G;s,\n,.,'`; \ dir='$(DESTDIR)$(man8dir)'; $(am__uninstall_files_from_dir) ID: $(am__tagged_files) $(am__define_uniq_tagged_files); mkid -fID $$unique tags: tags-am TAGS: tags tags-am: $(TAGS_DEPENDENCIES) $(am__tagged_files) set x; \ here=`pwd`; \ $(am__define_uniq_tagged_files); \ shift; \ if test -z "$(ETAGS_ARGS)$$*$$unique"; then :; else \ test -n "$$unique" || unique=$$empty_fix; \ if test $$# -gt 0; then \ $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ "$$@" $$unique; \ else \ $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ $$unique; \ fi; \ fi ctags: ctags-am CTAGS: ctags ctags-am: $(TAGS_DEPENDENCIES) $(am__tagged_files) $(am__define_uniq_tagged_files); \ test -z "$(CTAGS_ARGS)$$unique" \ || $(CTAGS) $(CTAGSFLAGS) $(AM_CTAGSFLAGS) $(CTAGS_ARGS) \ $$unique GTAGS: here=`$(am__cd) $(top_builddir) && pwd` \ && $(am__cd) $(top_srcdir) \ && gtags -i $(GTAGS_ARGS) "$$here" cscopelist: cscopelist-am cscopelist-am: $(am__tagged_files) list='$(am__tagged_files)'; \ case "$(srcdir)" in \ [\\/]* | ?:[\\/]*) sdir="$(srcdir)" ;; \ *) sdir=$(subdir)/$(srcdir) ;; \ esac; \ for i in $$list; do \ if test -f "$$i"; then \ echo "$(subdir)/$$i"; \ else \ echo "$$sdir/$$i"; \ fi; \ done >> $(top_builddir)/cscope.files distclean-tags: -rm -f TAGS ID GTAGS GRTAGS GSYMS GPATH tags distdir: $(DISTFILES) @srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ topsrcdirstrip=`echo "$(top_srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ list='$(DISTFILES)'; \ dist_files=`for file in $$list; do echo $$file; done | \ sed -e "s|^$$srcdirstrip/||;t" \ -e "s|^$$topsrcdirstrip/|$(top_builddir)/|;t"`; \ case $$dist_files in \ */*) $(MKDIR_P) `echo "$$dist_files" | \ sed '/\//!d;s|^|$(distdir)/|;s,/[^/]*$$,,' | \ sort -u` ;; \ esac; \ for file in $$dist_files; do \ if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \ if test -d $$d/$$file; then \ dir=`echo "/$$file" | sed -e 's,/[^/]*$$,,'`; \ if test -d "$(distdir)/$$file"; then \ find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ fi; \ if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \ cp -fpR $(srcdir)/$$file "$(distdir)$$dir" || exit 1; \ find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ fi; \ cp -fpR $$d/$$file "$(distdir)$$dir" || exit 1; \ else \ test -f "$(distdir)/$$file" \ || cp -p $$d/$$file "$(distdir)/$$file" \ || exit 1; \ fi; \ done $(MAKE) $(AM_MAKEFLAGS) \ top_distdir="$(top_distdir)" distdir="$(distdir)" \ dist-hook check-am: all-am $(MAKE) $(AM_MAKEFLAGS) check-local check: check-am all-am: Makefile $(PROGRAMS) $(MANS) $(HEADERS) all-local installdirs: for dir in "$(DESTDIR)$(libexecdir)" "$(DESTDIR)$(man8dir)"; do \ test -z "$$dir" || $(MKDIR_P) "$$dir"; \ done install: install-am install-exec: install-exec-am install-data: install-data-am uninstall: uninstall-am install-am: all-am @$(MAKE) $(AM_MAKEFLAGS) install-exec-am install-data-am installcheck: installcheck-am install-strip: if test -z '$(STRIP)'; then \ $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ install; \ else \ $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'" install; \ fi mostlyclean-generic: clean-generic: distclean-generic: -test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES) -test . = "$(srcdir)" || test -z "$(CONFIG_CLEAN_VPATH_FILES)" || rm -f $(CONFIG_CLEAN_VPATH_FILES) maintainer-clean-generic: @echo "This command is intended for maintainers to use" @echo "it deletes files that may require special tools to rebuild." clean: clean-am clean-am: clean-generic clean-libexecPROGRAMS clean-libtool \ mostlyclean-am distclean: distclean-am -rm -rf ./$(DEPDIR) -rm -f Makefile distclean-am: clean-am distclean-compile distclean-generic \ distclean-tags dvi: dvi-am dvi-am: html: html-am html-am: info: info-am info-am: install-data-am: install-man @$(NORMAL_INSTALL) $(MAKE) $(AM_MAKEFLAGS) install-data-hook install-dvi: install-dvi-am install-dvi-am: install-exec-am: install-exec-local install-libexecPROGRAMS install-html: install-html-am install-html-am: install-info: install-info-am install-info-am: install-man: install-man8 install-pdf: install-pdf-am install-pdf-am: install-ps: install-ps-am install-ps-am: installcheck-am: maintainer-clean: maintainer-clean-am -rm -rf ./$(DEPDIR) -rm -f Makefile maintainer-clean-am: distclean-am maintainer-clean-generic mostlyclean: mostlyclean-am mostlyclean-am: mostlyclean-compile mostlyclean-generic \ mostlyclean-libtool pdf: pdf-am pdf-am: ps: ps-am ps-am: uninstall-am: uninstall-libexecPROGRAMS uninstall-man @$(NORMAL_INSTALL) $(MAKE) $(AM_MAKEFLAGS) uninstall-hook uninstall-man: uninstall-man8 .MAKE: check-am install-am install-data-am install-strip uninstall-am .PHONY: CTAGS GTAGS TAGS all all-am all-local check check-am \ check-local clean clean-generic clean-libexecPROGRAMS \ clean-libtool cscopelist-am ctags ctags-am dist-hook distclean \ distclean-compile distclean-generic distclean-libtool \ distclean-tags distdir dvi dvi-am html html-am info info-am \ install install-am install-data install-data-am \ install-data-hook install-dvi install-dvi-am install-exec \ install-exec-am install-exec-local install-html \ install-html-am install-info install-info-am \ install-libexecPROGRAMS install-man install-man8 install-pdf \ install-pdf-am install-ps install-ps-am install-strip \ installcheck installcheck-am installdirs maintainer-clean \ maintainer-clean-generic mostlyclean mostlyclean-compile \ mostlyclean-generic mostlyclean-libtool pdf pdf-am ps ps-am \ tags tags-am uninstall uninstall-am uninstall-hook \ uninstall-libexecPROGRAMS uninstall-man uninstall-man8 .PRECIOUS: Makefile install-suid-programs: @foo='$(bin_SUIDS)'; \ for file in $$foo; do \ x=$(DESTDIR)$(bindir)/$$file; \ if chown 0:0 $$x && chmod u+s $$x; then :; else \ echo "*"; \ echo "* Failed to install $$x setuid root"; \ echo "*"; \ fi; \ done install-exec-local: install-suid-programs codesign-all: @if [ X"$$CODE_SIGN_IDENTITY" != X ] ; then \ foo='$(bin_PROGRAMS) $(sbin_PROGRAMS) $(libexec_PROGRAMS)' ; \ for file in $$foo ; do \ echo "CODESIGN $$file" ; \ codesign -f -s "$$CODE_SIGN_IDENTITY" $$file || exit 1 ; \ done ; \ fi all-local: codesign-all install-build-headers:: $(include_HEADERS) $(dist_include_HEADERS) $(nodist_include_HEADERS) $(build_HEADERZ) $(nobase_include_HEADERS) $(noinst_HEADERS) @foo='$(include_HEADERS) $(dist_include_HEADERS) $(nodist_include_HEADERS) $(build_HEADERZ) $(noinst_HEADERS)'; \ for f in $$foo; do \ f=`basename $$f`; \ if test -f "$(srcdir)/$$f"; then file="$(srcdir)/$$f"; \ else file="$$f"; fi; \ if cmp -s $$file $(buildinclude)/$$f 2> /dev/null ; then \ : ; else \ echo " $(CP) $$file $(buildinclude)/$$f"; \ $(CP) $$file $(buildinclude)/$$f || true; \ fi ; \ done ; \ foo='$(nobase_include_HEADERS)'; \ for f in $$foo; do \ if test -f "$(srcdir)/$$f"; then file="$(srcdir)/$$f"; \ else file="$$f"; fi; \ $(mkdir_p) $(buildinclude)/`dirname $$f` ; \ if cmp -s $$file $(buildinclude)/$$f 2> /dev/null ; then \ : ; else \ echo " $(CP) $$file $(buildinclude)/$$f"; \ $(CP) $$file $(buildinclude)/$$f; \ fi ; \ done all-local: install-build-headers check-local:: @if test '$(CHECK_LOCAL)' = "no-check-local"; then \ foo=''; elif test '$(CHECK_LOCAL)'; then \ foo='$(CHECK_LOCAL)'; else \ foo='$(PROGRAMS)'; fi; \ if test "$$foo"; then \ failed=0; all=0; \ for i in $$foo; do \ all=`expr $$all + 1`; \ if (./$$i --version && ./$$i --help) > /dev/null 2>&1; then \ echo "PASS: $$i"; \ else \ echo "FAIL: $$i"; \ failed=`expr $$failed + 1`; \ fi; \ done; \ if test "$$failed" -eq 0; then \ banner="All $$all tests passed"; \ else \ banner="$$failed of $$all tests failed"; \ fi; \ dashes=`echo "$$banner" | sed s/./=/g`; \ echo "$$dashes"; \ echo "$$banner"; \ echo "$$dashes"; \ test "$$failed" -eq 0 || exit 1; \ fi .x.c: @cmp -s $< $@ 2> /dev/null || cp $< $@ .hx.h: @cmp -s $< $@ 2> /dev/null || cp $< $@ #NROFF_MAN = nroff -man .1.cat1: $(NROFF_MAN) $< > $@ .3.cat3: $(NROFF_MAN) $< > $@ .5.cat5: $(NROFF_MAN) $< > $@ .7.cat7: $(NROFF_MAN) $< > $@ .8.cat8: $(NROFF_MAN) $< > $@ dist-cat1-mans: @foo='$(man1_MANS)'; \ bar='$(man_MANS)'; \ for i in $$bar; do \ case $$i in \ *.1) foo="$$foo $$i";; \ esac; done ;\ for i in $$foo; do \ x=`echo $$i | sed 's/\.[^.]*$$/.cat1/'`; \ echo "$(NROFF_MAN) $(srcdir)/$$i > $(distdir)/$$x"; \ $(NROFF_MAN) $(srcdir)/$$i > $(distdir)/$$x; \ done dist-cat3-mans: @foo='$(man3_MANS)'; \ bar='$(man_MANS)'; \ for i in $$bar; do \ case $$i in \ *.3) foo="$$foo $$i";; \ esac; done ;\ for i in $$foo; do \ x=`echo $$i | sed 's/\.[^.]*$$/.cat3/'`; \ echo "$(NROFF_MAN) $(srcdir)/$$i > $(distdir)/$$x"; \ $(NROFF_MAN) $(srcdir)/$$i > $(distdir)/$$x; \ done dist-cat5-mans: @foo='$(man5_MANS)'; \ bar='$(man_MANS)'; \ for i in $$bar; do \ case $$i in \ *.5) foo="$$foo $$i";; \ esac; done ;\ for i in $$foo; do \ x=`echo $$i | sed 's/\.[^.]*$$/.cat5/'`; \ echo "$(NROFF_MAN) $(srcdir)/$$i > $(distdir)/$$x"; \ $(NROFF_MAN) $(srcdir)/$$i > $(distdir)/$$x; \ done dist-cat7-mans: @foo='$(man7_MANS)'; \ bar='$(man_MANS)'; \ for i in $$bar; do \ case $$i in \ *.7) foo="$$foo $$i";; \ esac; done ;\ for i in $$foo; do \ x=`echo $$i | sed 's/\.[^.]*$$/.cat7/'`; \ echo "$(NROFF_MAN) $(srcdir)/$$i > $(distdir)/$$x"; \ $(NROFF_MAN) $(srcdir)/$$i > $(distdir)/$$x; \ done dist-cat8-mans: @foo='$(man8_MANS)'; \ bar='$(man_MANS)'; \ for i in $$bar; do \ case $$i in \ *.8) foo="$$foo $$i";; \ esac; done ;\ for i in $$foo; do \ x=`echo $$i | sed 's/\.[^.]*$$/.cat8/'`; \ echo "$(NROFF_MAN) $(srcdir)/$$i > $(distdir)/$$x"; \ $(NROFF_MAN) $(srcdir)/$$i > $(distdir)/$$x; \ done dist-hook: dist-cat1-mans dist-cat3-mans dist-cat5-mans dist-cat7-mans dist-cat8-mans install-cat-mans: $(SHELL) $(top_srcdir)/cf/install-catman.sh install "$(INSTALL_DATA)" "$(mkinstalldirs)" "$(srcdir)" "$(DESTDIR)$(mandir)" '$(CATMANEXT)' $(man_MANS) $(man1_MANS) $(man3_MANS) $(man5_MANS) $(man7_MANS) $(man8_MANS) uninstall-cat-mans: $(SHELL) $(top_srcdir)/cf/install-catman.sh uninstall "$(INSTALL_DATA)" "$(mkinstalldirs)" "$(srcdir)" "$(DESTDIR)$(mandir)" '$(CATMANEXT)' $(man_MANS) $(man1_MANS) $(man3_MANS) $(man5_MANS) $(man7_MANS) $(man8_MANS) install-data-hook: install-cat-mans uninstall-hook: uninstall-cat-mans .et.h: $(COMPILE_ET) $< .et.c: $(COMPILE_ET) $< # # Useful target for debugging # check-valgrind: tobjdir=`cd $(top_builddir) && pwd` ; \ tsrcdir=`cd $(top_srcdir) && pwd` ; \ env TESTS_ENVIRONMENT="$${tsrcdir}/cf/maybe-valgrind.sh -s $${tsrcdir} -o $${tobjdir}" make check # # Target to please samba build farm, builds distfiles in-tree. # Will break when automake changes... # distdir-in-tree: $(DISTFILES) $(INFO_DEPS) list='$(DIST_SUBDIRS)'; for subdir in $$list; do \ if test "$$subdir" != .; then \ (cd $$subdir && $(MAKE) $(AM_MAKEFLAGS) distdir-in-tree) ; \ fi ; \ done $(srcdir)/kcm-protos.h: $(kcm_SOURCES) cd $(srcdir); perl ../cf/make-proto.pl -o kcm-protos.h -q -P comment $(kcm_SOURCES) || rm -f kcm-protos.h $(kcm_OBJECTS): $(srcdir)/kcm-protos.h # Tell versions [3.59,3.63) of GNU make to not export all variables. # Otherwise a system limit (for SysV at least) may be exceeded. .NOEXPORT: heimdal-7.5.0/kcm/kcm.80000644000175000017500000001145213062303006012663 0ustar niknik.\" Copyright (c) 2005 Kungliga Tekniska Högskolan .\" (Royal Institute of Technology, Stockholm, Sweden). .\" All rights reserved. .\" .\" Redistribution and use in source and binary forms, with or without .\" modification, are permitted provided that the following conditions .\" are met: .\" .\" 1. Redistributions of source code must retain the above copyright .\" notice, this list of conditions and the following disclaimer. .\" .\" 2. Redistributions in binary form must reproduce the above copyright .\" notice, this list of conditions and the following disclaimer in the .\" documentation and/or other materials provided with the distribution. .\" .\" 3. Neither the name of the Institute nor the names of its contributors .\" may be used to endorse or promote products derived from this software .\" without specific prior written permission. .\" .\" THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND .\" ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE .\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE .\" ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE .\" FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL .\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS .\" OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) .\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT .\" LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF .\" SUCH DAMAGE. .\" .\" $Id$ .\" .Dd May 29, 2005 .Dt KCM 8 .Os .Sh NAME .Nm kcm .Nd process-based credential cache for Kerberos tickets. .Sh SYNOPSIS .Nm .Op Fl Fl cache-name= Ns Ar cachename .Oo Fl c Ar file \*(Ba Xo .Fl Fl config-file= Ns Ar file .Xc .Oc .Oo Fl g Ar group \*(Ba Xo .Fl Fl group= Ns Ar group .Xc .Oc .Op Fl Fl max-request= Ns Ar size .Op Fl Fl disallow-getting-krbtgt .Op Fl Fl detach .Op Fl h | Fl Fl help .Oo Fl k Ar principal \*(Ba Xo .Fl Fl system-principal= Ns Ar principal .Xc .Oc .Oo Fl l Ar time \*(Ba Xo .Fl Fl lifetime= Ns Ar time .Xc .Oc .Oo Fl m Ar mode \*(Ba Xo .Fl Fl mode= Ns Ar mode .Xc .Oc .Op Fl n | Fl Fl no-name-constraints .Oo Fl r Ar time \*(Ba Xo .Fl Fl renewable-life= Ns Ar time .Xc .Oc .Oo Fl s Ar path \*(Ba Xo .Fl Fl socket-path= Ns Ar path .Xc .Oc .Oo Xo .Fl Fl door-path= Ns Ar path .Xc .Oc .Oo Fl S Ar principal \*(Ba Xo .Fl Fl server= Ns Ar principal .Xc .Oc .Oo Fl t Ar keytab \*(Ba Xo .Fl Fl keytab= Ns Ar keytab .Xc .Oc .Oo Fl u Ar user \*(Ba Xo .Fl Fl user= Ns Ar user .Xc .Oc .Op Fl v | Fl Fl version .Sh DESCRIPTION .Nm is a process based credential cache. To use it, set the .Ev KRB5CCNAME environment variable to .Ql KCM: Ns Ar uid or add the stanza .Bd -literal [libdefaults] default_cc_name = KCM:%{uid} .Ed to the .Pa /etc/krb5.conf configuration file and make sure .Nm kcm is started in the system startup files. .Pp The .Nm daemon can hold the credentials for all users in the system. Access control is done with Unix-like permissions. The daemon checks the access on all operations based on the uid and gid of the user. The tickets are renewed as long as is permitted by the KDC's policy. .Pp The .Nm daemon can also keep a SYSTEM credential that server processes can use to access services. One example of usage might be an nss_ldap module that quickly needs to get credentials and doesn't want to renew the ticket itself. .Pp Supported options: .Bl -tag -width Ds .It Fl Fl cache-name= Ns Ar cachename system cache name .It Fl c Ar file , Fl Fl config-file= Ns Ar file location of config file .It Fl g Ar group , Fl Fl group= Ns Ar group system cache group .It Fl Fl max-request= Ns Ar size max size for a kcm-request .It Fl Fl disallow-getting-krbtgt disallow extracting any krbtgt from the .Nm kcm daemon. .It Fl Fl detach detach from console .It Fl h , Fl Fl help .It Fl k Ar principal , Fl Fl system-principal= Ns Ar principal system principal name .It Fl l Ar time , Fl Fl lifetime= Ns Ar time lifetime of system tickets .It Fl m Ar mode , Fl Fl mode= Ns Ar mode octal mode of system cache .It Fl n , Fl Fl no-name-constraints disable credentials cache name constraints .It Fl r Ar time , Fl Fl renewable-life= Ns Ar time renewable lifetime of system tickets .It Fl s Ar path , Fl Fl socket-path= Ns Ar path path to kcm domain socket .It Fl Fl door-path= Ns Ar path path to kcm door socket .It Fl S Ar principal , Fl Fl server= Ns Ar principal server to get system ticket for .It Fl t Ar keytab , Fl Fl keytab= Ns Ar keytab system keytab name .It Fl u Ar user , Fl Fl user= Ns Ar user system cache owner .It Fl v , Fl Fl version .El .\".Sh ENVIRONMENT .\".Sh FILES .\".Sh EXAMPLES .\".Sh DIAGNOSTICS .\".Sh SEE ALSO .\".Sh STANDARDS .\".Sh HISTORY .\".Sh AUTHORS .\".Sh BUGS heimdal-7.5.0/kcm/NTMakefile0000644000175000017500000000272112136107747013740 0ustar niknik######################################################################## # # Copyright (c) 2009, Secure Endpoints Inc. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # - Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # # - Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in # the documentation and/or other materials provided with the # distribution. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS # FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE # COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, # BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN # ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. # RELDIR=kcm !include ../windows/NTMakefile.w32 heimdal-7.5.0/kcm/log.c0000644000175000017500000000525213026237312012754 0ustar niknik/* * Copyright (c) 1997, 1998, 2002 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "kcm_locl.h" RCSID("$Id$"); static krb5_log_facility *logfac; void kcm_openlog(void) { char **s = NULL, **p; krb5_initlog(kcm_context, "kcm", &logfac); s = krb5_config_get_strings(kcm_context, NULL, "kcm", "logging", NULL); if(s == NULL) s = krb5_config_get_strings(kcm_context, NULL, "logging", "kcm", NULL); if(s){ for(p = s; *p; p++) krb5_addlog_dest(kcm_context, logfac, *p); krb5_config_free_strings(s); }else krb5_addlog_dest(kcm_context, logfac, DEFAULT_LOG_DEST); krb5_set_warn_dest(kcm_context, logfac); } char* kcm_log_msg_va(int level, const char *fmt, va_list ap) { char *msg; krb5_vlog_msg(kcm_context, logfac, &msg, level, fmt, ap); return msg; } char* kcm_log_msg(int level, const char *fmt, ...) { va_list ap; char *s; va_start(ap, fmt); s = kcm_log_msg_va(level, fmt, ap); va_end(ap); return s; } void kcm_log(int level, const char *fmt, ...) { va_list ap; char *s; va_start(ap, fmt); s = kcm_log_msg_va(level, fmt, ap); if(s) free(s); va_end(ap); } heimdal-7.5.0/kcm/kcm_locl.h0000644000175000017500000001245013026237312013761 0ustar niknik/* * Copyright (c) 2005, PADL Software Pty Ltd. * All rights reserved. * * Portions Copyright (c) 2009 Apple Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of PADL Software nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY PADL SOFTWARE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL PADL SOFTWARE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ /* * $Id$ */ #ifndef __KCM_LOCL_H__ #define __KCM_LOCL_H__ #include "headers.h" #include #define KCM_LOG_REQUEST(_context, _client, _opcode) do { \ kcm_log(1, "%s request by process %d/uid %d", \ kcm_op2string(_opcode), (_client)->pid, (_client)->uid); \ } while (0) #define KCM_LOG_REQUEST_NAME(_context, _client, _opcode, _name) do { \ kcm_log(1, "%s request for cache %s by process %d/uid %d", \ kcm_op2string(_opcode), (_name), (_client)->pid, (_client)->uid); \ } while (0) /* Cache management */ #define KCM_FLAGS_VALID 0x0001 #define KCM_FLAGS_USE_KEYTAB 0x0002 #define KCM_FLAGS_RENEWABLE 0x0004 #define KCM_FLAGS_OWNER_IS_SYSTEM 0x0008 #define KCM_FLAGS_USE_CACHED_KEY 0x0010 #define KCM_MASK_KEY_PRESENT ( KCM_FLAGS_USE_KEYTAB | \ KCM_FLAGS_USE_CACHED_KEY ) struct kcm_ccache_data; struct kcm_creds; struct kcm_default_cache { uid_t uid; pid_t session; /* really au_asid_t */ char *name; struct kcm_default_cache *next; }; extern struct kcm_default_cache *default_caches; struct kcm_creds { kcmuuid_t uuid; krb5_creds cred; struct kcm_creds *next; }; typedef struct kcm_ccache_data { char *name; kcmuuid_t uuid; unsigned refcnt; uint16_t flags; uint16_t mode; uid_t uid; gid_t gid; pid_t session; /* really au_asid_t */ krb5_principal client; /* primary client principal */ krb5_principal server; /* primary server principal (TGS if NULL) */ struct kcm_creds *creds; krb5_deltat tkt_life; krb5_deltat renew_life; int32_t kdc_offset; union { krb5_keytab keytab; krb5_keyblock keyblock; } key; HEIMDAL_MUTEX mutex; struct kcm_ccache_data *next; } kcm_ccache_data; #define KCM_ASSERT_VALID(_ccache) do { \ if (((_ccache)->flags & KCM_FLAGS_VALID) == 0) \ krb5_abortx(context, "kcm_free_ccache_data: ccache invalid"); \ else if ((_ccache)->refcnt == 0) \ krb5_abortx(context, "kcm_free_ccache_data: ccache refcnt == 0"); \ } while (0) typedef kcm_ccache_data *kcm_ccache; /* Event management */ typedef struct kcm_event { int valid; time_t fire_time; unsigned fire_count; time_t expire_time; time_t backoff_time; enum { KCM_EVENT_NONE = 0, KCM_EVENT_ACQUIRE_CREDS, KCM_EVENT_RENEW_CREDS, KCM_EVENT_DESTROY_CREDS, KCM_EVENT_DESTROY_EMPTY_CACHE } action; kcm_ccache ccache; struct kcm_event *next; } kcm_event; /* wakeup interval for event queue */ #define KCM_EVENT_QUEUE_INTERVAL 60 #define KCM_EVENT_DEFAULT_BACKOFF_TIME 5 #define KCM_EVENT_MAX_BACKOFF_TIME (12 * 60 * 60) /* Request format is LENGTH | MAJOR | MINOR | OPERATION | request */ /* Response format is LENGTH | STATUS | response */ typedef struct kcm_client { pid_t pid; uid_t uid; gid_t gid; pid_t session; } kcm_client; #define CLIENT_IS_ROOT(client) ((client)->uid == 0) /* Dispatch table */ /* passed in OPERATION | ... ; returns STATUS | ... */ typedef krb5_error_code (*kcm_method)(krb5_context, kcm_client *, kcm_operation, krb5_storage *, krb5_storage *); struct kcm_op { const char *name; kcm_method method; }; #define DEFAULT_LOG_DEST "0/FILE:" LOCALSTATEDIR "/log/kcmd.log" #define _PATH_KCM_CONF SYSCONFDIR "/kcm.conf" extern krb5_context kcm_context; extern char *socket_path; extern char *door_path; extern size_t max_request; extern sig_atomic_t exit_flag; extern int name_constraints; extern int detach_from_console; extern int daemon_child; extern int launchd_flag; extern int disallow_getting_krbtgt; #if 0 extern const krb5_cc_ops krb5_kcmss_ops; #endif void kcm_service(void *, const heim_idata *, const heim_icred, heim_ipc_complete, heim_sipc_call); #include #endif /* __KCM_LOCL_H__ */ heimdal-7.5.0/ChangeLog.20060000644000175000017500000017000712136107746013426 0ustar niknik2006-12-28 Love Hörnquist Åstrand * kdc/process.c: Handle kx509 requests. * kdc/connect.c: Listen to 9878 if kca is turned on. * kdc/headers.h: Include . * kdc/config.c: code to parse [kdc]enable-kx509 * kdc/kdc.h: add enable_kx509 * kdc/Makefile.am: add kx509.c * kdc/kx509.c: Kx509server (external certificate genration). * lib/krb5/ticket.c: add krb5_ticket_get_endtime * lib/krb5/krb5_ticket.3: Document krb5_ticket_get_endtime * kdc/digest.c: Remove , its already included in headers.h * kdc/digest.c: Return session key for the NTLMv2 case too * lib/krb5/digest.c (krb5_ntlm_rep_get_sessionkey): return value is krb5_error_code 2006-12-27 Love Hörnquist Åstrand * lib/krb5/mk_req_ext.c (_krb5_mk_req_internal): use md5 for des-cbc-md4 and des-cbc-md5. This is for (older) windows that will be unhappy anything else. From Inna Bort-Shatsky 2006-12-26 Love Hörnquist Åstrand * kdc/digest.c: Prefix internal symbol with _kdc_. * kdc/kdc.h: add digests_allowed * kdc/digest.c: return NTLM2 targetinfo structure. * lib/krb5/digest.c: Add krb5_ntlm_init_get_targetinfo. * kdc/config.c: Parse digest acl's * kdc/kdc_locl.h: forward decl; * kdc/digest.c: Add digest acl's 2006-12-22 Love Hörnquist Åstrand * fix-export: build ntlm-private.h 2006-12-20 Love Hörnquist Åstrand * include/make_crypto.c: Include <.../hmac.h>. * kdc/digest.c: reorder to show slot here ntlmv2 code will be placed. * kdc/digest.c: Announce that we support key exchange and add bits to detect when it wasn't used. * kdc/digest.c: Add support for generating NTLM2 session security answer. 2006-12-19 Love Hörnquist Åstrand * lib/krb5/digest.c: Add sessionkey accessor functions. 2006-12-18 Love Hörnquist Åstrand * kdc/digest.c: Unwrap the NTLM session key and return it to the server. 2006-12-17 Love Hörnquist Åstrand * lib/krb5/store.c (krb5_ret_principal): Fix a bug in the malloc failure part, noticed by Arnaud Lacombe in NetBSD coverity scan. 2006-12-15 Love Hörnquist Åstrand * lib/krb5/fcache.c (fcc_get_cache_next): avoid const warning. * kdc/digest.c: Support NTLM verification, note that the KDC does no NTLM packet parsing, its all done by the client side, the KDC just calculate and verify the digest and return the result to the service. * kuser/kdigest.c: add ntlm-server-init * kuser/Makefile.am: kdigest depends on libheimntlm.la * kdc/headers.h: Include . * kdc/Makefile.am: libkdc needs libheimntlm.la * autogen.sh: just run autoreconf -i -f * lib/Makefile.am: hook in ntlm * configure.in (AC_CONFIG_FILES): add lib/ntlm/Makefile * lib/krb5/digest.c: API to authenticate ntlm requests. * lib/krb5/fcache.c: Support "iteration" of file credential caches by giving the user back the default file credential cache and only that. * lib/krb5/krb5_locl.h: Expand the default root for some of the cc type names. 2006-12-14 Love Hörnquist Åstrand * lib/krb5/init_creds_pw.c (free_paid): free the krb5_data structure too. Bug report from Stefan Metzmacher. 2006-12-12 Love Hörnquist Åstrand * kuser/kinit.c: Read the appdefault configration before we try to use the flags. Bug reported by Ingemar Nilsson. * kuser/kdigest.c: prefix digest commands with digest_ * kuser/kdigest-commands.in: prefix digest commands with digest- 2006-12-10 Love Hörnquist Åstrand * kdc/hprop.c: Return error codes on failure, improve error reporting. 2006-12-08 Love Hörnquist Åstrand * lib/krb5/pkinit.c: sprinkle more _krb5_pk_copy_error * lib/krb5/pkinit.c: Copy more hx509 error strings to krb5 error strings 2006-12-07 Love Hörnquist Åstrand * include/Makefile.am: CLEANFILES += vis.h 2006-12-06 Love Hörnquist Åstrand * kdc/kerberos5.c (_kdc_as_rep): add AD-INITAL-VERIFIED-CAS to the encrypted ticket * kdc/pkinit.c (_kdc_add_inital_verified_cas): new function, adds an empty (for now) AD_INITIAL_VERIFIED_CAS to tell the clients that we vouches for the CA. * kdc/kerberos5.c (_kdc_tkt_add_if_relevant_ad): new function. * lib/Makefile.am: Make the directories test automake conditional so automake can include directories in make dist step. * kdc/pkinit.c (_kdc_pk_rd_padata): leak less memory for ExternalPrincipalIdentifiers * kdc/pkinit.c: Parse and use PA-PK-AS-REQ.trustedCertifiers * kdc/pkinit.c: Add comment that the anchors in the signed data really should be the trust anchors of the client. * kuser/generate-requests.c: Use strcspn to remove \n from string returned by fgets. From Björn Sandell * kpasswd/kpasswd-generator.c: Use strcspn to remove \n from string returned by fgets. From Björn Sandell 2006-12-05 Love Hörnquist Åstrand * lib/hdb/hdb-ldap.c: Clear errno before calling the strtol functions. From Paul Stoeber to OpenBSD by Ray Lai and Björn Sandell. * lib/krb5/config_file.c: Use strcspn to remove \n from fgets result. Prompted by change by Ray Lai of OpenBSD via Björn Sandell. * kdc/string2key.c: Use strcspn to remove \n from fgets result. Prompted by change by Ray Lai of OpenBSD via Björn Sandell. 2006-11-30 Love Hörnquist Åstrand * lib/krb5/krbhst.c (plugin_get_hosts): be more paranoid and pass in a NULLed plugin list 2006-11-29 Love Hörnquist Åstrand * lib/krb5/verify_krb5_conf.c: add more pkinit options. * lib/krb5/pkinit.c: Store what PK-INIT type we used to know reply to expect, this avoids overwriting the real PK-INIT error from just a failed requeat with a Windows PK-INIT error (that always failes). * kdc/Makefile.am: Add LIB_pkinit to pacify AIX * lib/hdb/Makefile.am: Add LIB_com_err to pacify AIX 2006-11-28 Love Hörnquist Åstrand * lib/hdb/hdb-ldap.c: Make build again from the hdb_entry wrapping. Patch from Andreas Hasenack. * kdc/pkinit.c: Need better code in the DH parameter rejection case, add comment to that effect. 2006-11-27 Love Hörnquist Åstrand * kdc/krb5tgs.c: Reply KRB5KRB_ERR_RESPONSE_TOO_BIG for too large packets when using datagram based transports. * kdc/process.c: Pass down datagram_reply to _kdc_tgs_rep. * lib/krb5/pkinit.c (build_auth_pack): set supportedCMSTypes. 2006-11-26 Love Hörnquist Åstrand * lib/krb5/pkinit.c: Pass down hx509_peer_info. * kdc/pkinit.c (_kdc_pk_rd_padata): Pick up supportedCMSTypes and pass in into hx509_cms_create_signed_1 via hx509_peer_info blob. * kdc/pkinit.c (_kdc_pk_rd_padata): Pick up supportedCMSTypes and pass in into hx509_cms_create_signed_1 via hx509_peer_info blob. 2006-11-24 Love Hörnquist Åstrand * lib/krb5/send_to_kdc.c: Set the large_msg_size to 1400, lets not fragment packets and avoid stupid linklayers that doesn't allow fragmented packets (unix dgram sockets on Mac OS X) 2006-11-23 Love Hörnquist Åstrand * lib/krb5/pkinit.c (_krb5_pk_create_sign): stuff down the users certs in the pool to make sure a path is returned, without this proxy certificates wont work. 2006-11-21 Love Hörnquist Åstrand * kdc/config.c: Make all pkinit options prefixed with pkinit_ * lib/krb5/log.c (krb5_get_warn_dest): return warn_dest from krb5_context * lib/krb5/krb5_warn.3: document krb5_[gs]et_warn_dest * lib/krb5/krb5.h: Drop KRB5_KU_TGS_IMPERSONATE. * kdc/krb5tgs.c: Use KRB5_KU_OTHER_CKSUM for the impersonate checksum. * lib/krb5/get_cred.c: Use KRB5_KU_OTHER_CKSUM for the impersonate checksum. 2006-11-20 Love Hörnquist Åstrand * lib/krb5/verify_user.c: Make krb5_get_init_creds_opt_free take a context argument. * lib/krb5/krb5_get_init_creds.3: Make krb5_get_init_creds_opt_free take a context argument. * lib/krb5/init_creds_pw.c: Make krb5_get_init_creds_opt_free take a context argument. * kuser/kinit.c: Make krb5_get_init_creds_opt_free take a context argument. * kpasswd/kpasswd.c: Make krb5_get_init_creds_opt_free take a context argument. * kpasswd/kpasswd-generator.c: Make krb5_get_init_creds_opt_free take a context argument. * kdc/hprop.c: Make krb5_get_init_creds_opt_free take a context argument. * lib/krb5/init_creds.c: Make krb5_get_init_creds_opt_free take a context argument. * appl/gssmask/gssmask.c: Make krb5_get_init_creds_opt_free take a context argument. 2006-11-19 Love Hörnquist Åstrand * doc/setup.texi: fix pkinit option (s/-/_/) * kdc/config.c: revert the enable-pkinit change, and make it consistant with all other other enable- options 2006-11-17 Love Hörnquist Åstrand * doc/setup.texi: Make all pkinit options prefixed with pkinit_ * kdc/config.c: Make all pkinit options prefixed with pkinit_ * kdc/pkinit.c: Make app pkinit options prefixed with pkinit_ * lib/krb5/pkinit.c: Make app pkinit options prefixed with pkinit_ * lib/krb5/mit_glue.c (krb5_c_keylengths): make compile again. * lib/krb5/mit_glue.c (krb5_c_keylengths): rename. * lib/krb5/mit_glue.c (krb5_c_keylength): mit changed the api, deal. 2006-11-13 Love Hörnquist Åstrand * lib/krb5/pac.c (fill_zeros): stop using MIN. * kuser/kinit.c: Forward decl * lib/krb5/test_plugin.c: Use NOTHERE.H5L.SE. * lib/krb5/krbhst.c: Fill in hints for picky getaddrinfo()s. * lib/krb5/test_plugin.c: Set sin_len if it exists. * lib/krb5/krbhst.c: Use plugin for the other realm locate types too. 2006-11-12 Love Hörnquist Åstrand * lib/krb5/krb5_locl.h: Add plugin api * lib/krb5/Makefile.am: Add plugin api. * lib/krb5/krbhst.c: Use the resolve plugin interface. * lib/krb5/locate_plugin.h: Add plugin interface for resolving that is API compatible with MITs version. * lib/krb5/plugin.c: Add first version of the plugin interface. * lib/krb5/test_pac.c: Test signing. * lib/krb5/pac.c: Add code to sign PACs, only arcfour for now. * lib/krb5/krb5.h: Add struct krb5_pac. 2006-11-09 Love Hörnquist Åstrand * lib/krb5/test_pac.c: PAC testing. * lib/krb5/pac.c: Sprinkle error strings. * lib/krb5/pac.c: Verify LOGON_NAME. * kdc/pkinit.c (_kdc_pk_check_client): drop client_princ as an argument * kdc/kerberos5.c (_kdc_as_rep): drop client_princ from _kdc_pk_check_client since its not valid in canonicalize case * lib/krb5/krb5_c_make_checksum.3: Document krb5_c_keylength. * lib/krb5/mit_glue.c: Add krb5_c_keylength. 2006-11-08 Love Hörnquist Åstrand * lib/krb5/pac.c: Almost enough code to do PAC parsing and verification, missing in the unix2NTTIME and ucs2 corner. The later will be adressed by finally adding libwind. * lib/krb5/krb5_init_context.3: document krb5_[gs]et_max_time_skew * kdc/hpropd.c: Remove support dumping to a kerberos 4 database. 2006-11-07 Love Hörnquist Åstrand * lib/krb5/context.c: rename krb5_[gs]et_time_wrap to krb5_[gs]et_max_time_skew * kdc/pkinit.c: Catch error string from hx509_cms_verify_signed. Check for id-pKKdcEkuOID and warn if its not there. * lib/krb5/rd_req.c: Add more krb5_rd_req_out_get functions. 2006-11-06 Love Hörnquist Åstrand * lib/krb5/krb5.h: krb5_rd_req{,_in,_out}_ctx. * lib/krb5/rd_req.c (krb5_rd_req_ctx): Add context all singing-all dancing version of the krb5_rd_req and implement krb5_rd_req and krb5_rd_req_with_keyblock using it. 2006-11-04 Love Hörnquist Åstrand * kdc/kerberos5.c (_kdc_as_rep): More verbose time skew logging. 2006-11-03 Love Hörnquist Åstrand * lib/krb5/expand_hostname.c: Rename various routines and constants from canonize to canonicalize. From Andrew Bartlett * lib/krb5/context.c: Add krb5_[gs]et_time_wrap * lib/krb5/krb5_locl.h: Rename various routines and constants from canonize to canonicalize. From Andrew Bartlett * appl/gssmask/common.c (add_list): fix alloc statement. From Alex Deiter 2006-10-25 Love Hörnquist Åstrand * include/Makefile.am: Move version.h and version.h.in to DISTCLEANFILES. 2006-10-24 Love Hörnquist Åstrand * appl/gssmask/gssmask.c: Only log when there are resources left. * appl/gssmask/gssmask.c: make compile * appl/gssmask/gssmask.c (AcquireCreds): free krb5_get_init_creds_opt 2006-10-23 Love Hörnquist Åstrand * configure.in: heimdal 0.8-RC1 2006-10-22 Love Hörnquist Åstrand * lib/krb5/digest.c: Try to not leak memory. * kdc/digest.c: Try to not leak memory. * Makefile.am: remove valgrind target, it doesn't belong here. * kuser/kinit.c: Try to not leak memory. * kuser/kgetcred.c: Try to not leak memory. * kdc/krb5tgs.c (check_KRB5SignedPath): free KRB5SignedPath on successful completion too, not just the error cases. * fix-export: Make make fix-export less verbose. * kuser/kgetcred.c: Try to not leak memory. * lib/hdb/keys.c (hdb_generate_key_set): free list of enctype when done. * lib/krb5/crypto.c: Allocate the memory we later use. * lib/krb5/test_princ.c: Try to not leak memory. * lib/krb5/test_crypto_wrapping.c: Try to not leak memory. * lib/krb5/test_cc.c: Try to not leak memory. * lib/krb5/addr_families.c (arange_free): Try to not leak memory. * lib/krb5/crypto.c (AES_string_to_key): Try to not leak memory. 2006-10-21 Love Hörnquist Åstrand * tools/heimdal-build.sh: Add --test-environment * tools/heimdal-build.sh: Add --ccache-dir * lib/hdb/Makefile.am: remove dependency on et files covert_db that now is removed 2006-10-20 Love Hörnquist Åstrand * include/Makefile.am: add gssapi to subdirs * lib/hdb/hdb-ldap.c: Make compile. * configure.in: add include/gssapi/Makefile. * include/Makefile.am: clean more files * include/make_crypto.c: Avoid creating a file called --version. * include/bits.c: Avoid creating a file called --version. * appl/test/Makefile.am: add nt_gss_common.h * doc/Makefile.am: Disable TEXI2DVI for now. * tools/Makefile.am: more files * lib/krb5/context.c (krb5_free_context): free send_to_kdc context * doc/heimdal.texi: Put Heimdal in the dircategory Security. * lib/krb5/send_to_kdc.c: Add sent_to_kdc hook, from Andrew Bartlet. * lib/krb5/krb5_locl.h: Add send_to_kdc hook. * lib/krb5/krb5.h: Add krb5_send_to_kdc_func prototype. * kcm/Makefile.am: more files * kdc/Makefile.am: more files * lib/hdb/Makefile.am: more files * lib/krb5/Makefile.am: add more files 2006-10-19 Love Hörnquist Åstrand * tools/Makefile.am: Add heimdal-build.sh to EXTRA_DIST. * configure.in: Don't check for timegm, libroken provides it for us. * lib/krb5/acache.c: Does function typecasts instead of void * type-casts. * lib/krb5/krb5.h: Remove bonus , that Love sneeked in. * configure.in: make --disable-pk-init help text also negative 2006-10-18 Love Hörnquist Åstrand * kuser/kgetcred.c: Avoid memory leak. * tools/heimdal-build.sh: Add more verbose logging, add version of script and heimdal to the mail. * lib/hdb/db3.c: Wrap function call pointer calls in (*func) to avoid macros rewriting open and close. * lib/krb5/Makefile.am: Add test_princ. * lib/krb5/principal.c: More error strings, handle realm-less printing. * lib/krb5/test_princ.c: Test principal parsing and unparsing. 2006-10-17 Love Hörnquist Åstrand * lib/krb5/get_host_realm.c (krb5_get_host_realm): make sure we don't recurse * lib/krb5/get_host_realm.c (krb5_get_host_realm): no components -> no dns. no mapping, try local realm and hope KDC knows better. * lib/krb5/krb5.h: Add flags for krb5_unparse_name_flags * lib/krb5/krb5_principal.3: Document krb5_unparse_name{_fixed,}_flags. * lib/krb5/principal.c: Add krb5_unparse_name_flags and krb5_unparse_name_fixed_flags. * lib/krb5/krb5_principal.3: Document krb5_parse_name_flags. * lib/krb5/principal.c: Add krb5_parse_name_flags. * lib/krb5/principal.c: Add krb5_parse_name_flags. * lib/krb5/krb5.h: Add krb5_parse_name_flags flags. * lib/krb5/krb5_locl.h: Hide krb5_context_data from public exposure. * lib/krb5/krb5.h: Hide krb5_context_data from public exposure. * kuser/klist.c: Use krb5_get_kdc_sec_offset. * lib/krb5/context.c: Document krb5_get_kdc_sec_offset() * lib/krb5/krb5_init_context.3: Add krb5_get_kdc_sec_offset() * lib/krb5/krb5_init_context.3: Add krb5_set_dns_canonize_hostname and krb5_get_dns_canonize_hostname * lib/krb5/verify_krb5_conf.c: add [libdefaults]dns_canonize_hostname * lib/krb5/expand_hostname.c: use dns_canonize_hostname to determin if we should talk to dns to find the canonical name of the host. * lib/krb5/krb5.h (krb5_context): add dns_canonize_hostname. * tools/heimdal-build.sh: Set status. * appl/gssmask/gssmask.c: handle more bits * kdc/kerberos5.c: Prefix asn1 primitives with der_. 2006-10-16 Love Hörnquist Åstrand * fix-export: Build lib/asn1/der-protos.h. 2006-10-14 Love Hörnquist Åstrand * appl/gssmask/Makefile.am: Add explit depenency on libroken. * kdc/krb5tgs.c: Prefix der primitives with der_. * kdc/pkinit.c: Prefix der primitives with der_. * lib/hdb/ext.c: Prefix der primitives with der_. * lib/hdb/ext.c: Prefix der primitives with der_. * lib/krb5/crypto.c: Remove workaround from when there wasn't always aes. * lib/krb5/ticket.c: Prefix der primitives with der_. * lib/krb5/digest.c: Prefix der primitives with der_. * lib/krb5/crypto.c: Prefix der primitives with der_. * lib/krb5/data.c: Prefix der primitives with der_. 2006-10-12 Love Hörnquist Åstrand * kdc/pkinit.c (pk_mk_pa_reply_enckey): add missing break. From Olga Kornievskaia. * kdc/kdc.8: document max-kdc-datagram-reply-length * include/bits.c: Include Xint64 types. 2006-10-10 Love Hörnquist Åstrand * tools/heimdal-build.sh: Add socketwrapper and cputime limit. * kdc/connect.c (loop): Log that the kdc have started. 2006-10-09 Love Hörnquist Åstrand * kdc/connect.c (do_request): tell krb5_kdc_process_request if its a datagram reply or not * kdc/kerberos5.c: Reply KRB5KRB_ERR_RESPONSE_TOO_BIG error if its a datagram reply and the datagram reply length limit is reached. * kdc/process.c: Rename krb5_kdc_process_generic_request to krb5_kdc_process_request Add datagram_reply argument. * kdc/config.c: check for [kdc]max-kdc-datagram-reply-length * kdc/kdc.h (krb5_kdc_config): Add max_datagram_reply_length. * lib/hdb/keytab.c: Change || to |, From metze. * lib/hdb/keytab.c: Add back :file to sample format. * lib/hdb/keytab.c: Add more HDB_F flags to hdb_fetch. Pointed out by Andrew Bartlet. * kdc/krb5tgs.c (tgs_parse_request): set cusec, not csec from auth->cusec. 2006-10-08 Love Hörnquist Åstrand * fix-export: dist_-ify libkadm5clnt_la_SOURCES too * doc/heimdal.texi: Update (c) years. * appl/gssmask/protocol.h: Clarify protocol. * kdc/hpropd.c: Adapt to signature change of _krb5_principalname2krb5_principal. * kdc/kerberos4.c: Adapt to signature change of _krb5_principalname2krb5_principal. * kdc/connect.c (handle_vanilla_tcp): shorten length when we shorten the buffer, this matter im the PK-INIT encKey case where a checksum is done over the whole packet. Reported by Olga Kornievskaia 2006-10-07 Love Hörnquist Åstrand * include/Makefile.am: crypto-headers.h is a nodist header * lib/krb5/aes-test.c: Make argument to PKCS5_PBKDF2_HMAC_SHA1 unsigned char to make OpenSSL happy. * appl/kf/Makefile.am: Add man_MANS to EXTRA_DIST * kuser/Makefile.am: split build files into dist_ and noinst_ SOURCES * lib/hdb/Makefile.am: split build files into dist_ and noinst_ SOURCES * lib/krb5/Makefile.am: split build files into dist_ and noinst_ SOURCES * kdc/kerberos5.c: Adapt to signature change of _krb5_principalname2krb5_principal. 2006-10-06 Love Hörnquist Åstrand * lib/krb5/krbhst.c (common_init): don't try DNS when there is realm w/o a dot. * kdc/524.c: Adapt to signature change of _krb5_principalname2krb5_principal. * kdc/krb5tgs.c: Adapt to signature change of _krb5_principalname2krb5_principal. * lib/krb5/get_in_tkt.c: Adapt to signature change of _krb5_principalname2krb5_principal. * lib/krb5/rd_cred.c: Adapt to signature change of _krb5_principalname2krb5_principal. * lib/krb5/rd_req.c: Adapt to signature change of _krb5_principalname2krb5_principal. * lib/krb5/asn1_glue.c (_krb5_principalname2krb5_principal): add krb5_context to signature. * kdc/524.c (_krb5_principalname2krb5_principal): adapt to signature change * lib/hdb/keytab.c (hdb_get_entry): close and destroy the database later, the hdb_entry_ex might still contain links to the database that it expects to use. * kdc/digest.c: Make digest argument o MD5_final unsigned char to help OpenSSL. * kuser/kdigest.c: Make digest argument o MD5_final unsigned char to help OpenSSL. * appl/gssmask/common.h: Maybe include . 2006-10-05 Love Hörnquist Åstrand * appl/gssmask/common.h: disable ENABLE_PTHREAD_SUPPORT and explain why * tools/heimdal-build.sh: Another mail header. * tools/heimdal-build.sh: small fixes * fix-export: More liberal parsing of AC_INIT * tools/heimdal-build.sh: first cut 2006-10-04 Love Hörnquist Åstrand * configure.in: Call AB_INIT. * kuser/kinit.c: Add flag --pk-use-enckey. * kdc/pkinit.c: Sign the request in the encKey case. Bug reported by Olga Kornievskaia of Umich. * lib/krb5/Makefile.am: man_MANS += krb5_digest.3 * lib/krb5/krb5_digest.3: Add all protos 2006-10-03 Love Hörnquist Åstrand * lib/krb5/krb5_digest.3: Basic krb5_digest manpage. 2006-10-02 Love Hörnquist Åstrand * fix-export: build gssapi mech private files * lib/krb5/init_creds_pw.c: minimize layering and remove krb5_kdc_flags * lib/krb5/get_in_tkt.c: Always use the kdc_flags in the right bit order. * lib/krb5/init_creds_pw.c: Always use the kdc_flags in the right bit order. * kuser/kdigest.c: Don't require --kerberos-realm. * lib/krb5/digest.c (digest_request): if NULL is passed in as realm, use default realm. * fix-export: build gssapi mech private files 2006-09-26 Love Hörnquist Åstrand * appl/gssmask/gssmaestro.c: Handle FIRST_CALL in the context building, better error handling. * appl/gssmask/gssmaestro.c: switch from wrap/unwrap to encrypt/decrypt * appl/gssmask/gssmask.c: Don't announce spn if there is none. * appl/gssmask/gssmaestro.c: Check that the pre-wrapped data is the same as afterward. 2006-09-25 Love Hörnquist Åstrand * appl/gssmask/gssmaestro.c: Remove stray GSS_C_DCE_STYLE. * appl/gssmask/gssmaestro.c: Add logsocket support. 2006-09-22 Love Hörnquist Åstrand * appl/gssmask/gssmaestro.c (build_context): print the step the context exchange. 2006-09-21 Love Hörnquist Åstrand * appl/gssmask/gssmaestro.c: Add GSS_C_INTEG_FLAG|GSS_C_CONF_FLAG to all context flags * appl/gssmask/gssmaestro.c: Add wrap and mic tests for all elements * appl/gssmask/gssmask.c: Add mic tests * appl/gssmask/gssmaestro.c: dont exit early then when context is half built. * lib/krb5/rd_req.c: disable ETypeList parsing usage for now, cfx seems broken and its not good to upgrade to a broken enctype. 2006-09-20 Love Hörnquist Åstrand * appl/gssmask/gssmask.c: Add wrap/unwrap ops * appl/gssmask/protocol.h: Add eGetVersionAndCapabilities flags * appl/gssmask/common.c: Add permutate_all (and support functions). * appl/gssmask/common.h: Add permutate_all * appl/gssmask/gssmask.c: use new flags, return moniker * appl/gssmask/gssmaestro.c: test self context building and all permutation of clients 2006-09-19 Love Hörnquist Åstrand * appl/gssmask/gssmask.c: add --logfile option, use htons() on port number * appl/gssmask/gssmaestro.c: Log port in connection message. * configure.in: Make pk-init turned on by default. 2006-09-18 Love Hörnquist Åstrand * fix-export: Build lib/hx509/{hx509-protos.h,hx509-private.h}. * kuser/Makefile.am: Add tool for printing tickets. * kuser/kimpersonate.1: Add tool for printing tickets. * kuser/kimpersonate.c: Add tool for printing tickets. * kdc/krb5tgs.c: Check the adtkt in the constrained delegation case too. 2006-09-16 Love Hörnquist Åstrand * kdc/main.c (sigterm): don't _exit, let loop() catch the signal instead. * lib/krb5/krb5_timeofday.3: Fixes from Björn Sandell. * lib/krb5/krb5_get_init_creds.3: Fixes from Björn Sandell. 2006-09-15 Love Hörnquist Åstrand * tools/krb5-config.in: Add "kafs" option. 2006-09-12 Love Hörnquist Åstrand * lib/hdb/db.c: By using full function calling conversion (*func) we avoid problem when close(fd) is overridden using a macro. * lib/krb5/cache.c: By using full function calling conversion (*func) we avoid problem when close(fd) is overridden using a macro. 2006-09-11 Love Hörnquist Åstrand * kdc/kerberos5.c: Signing outgoing tickets. * kdc/krb5tgs.c: Add signing and checking of tickets to s4u2self works securely. * lib/krb5/pkinit.c: Adapt to new signature of hx509_cms_unenvelope. 2006-09-09 Love Hörnquist Åstrand * lib/krb5/pkinit.c (pk_verify_host): set errorstrings in a sensable way 2006-09-08 Love Hörnquist Åstrand * lib/krb5/krb5_init_context.3: Prevent a font generation warning, from Jason McIntyre. 2006-09-06 Love Hörnquist Åstrand * lib/krb5/context.c (krb5_init_ets): Add the hx errortable * lib/krb5/krb5_locl.h: Include hx509_err.h. * lib/krb5/pkinit.c (_krb5_pk_verify_sign): catch the error string from the hx509 lib 2006-09-04 Love Hörnquist Åstrand * lib/krb5/init_creds.c (krb5_get_init_creds_opt_set_default_flags): fix argument to krb5_get_init_creds_opt_set_addressless. * lib/krb5/init_creds_pw.c (init_cred_loop): try to catch the error when we actually have an error to catch. * lib/krb5/init_creds_pw.c: Remove debug printfs. * kuser/kinit.c: Remove debug printf * lib/krb5/krb5_get_init_creds.3: Document krb5_get_init_creds_opt_set_addressless. * kuser/kinit.c: Use new function krb5_get_init_creds_opt_set_addressless. * lib/krb5/krb5_locl.h: use new addressless, convert pa-pac option to use the same tri-state option as the new addressless option. * lib/krb5/init_creds_pw.c: use new addressless, convert pa-pac option to use the same tri-state option as the new addressless option. * lib/krb5/init_creds.c (krb5_get_init_creds_opt_set_addressless): used to control the address-lessness of the initial tickets instead of passing in the empty set of address into krb5_get_init_creds_opt_set_addresses. 2006-09-01 Love Hörnquist Åstrand * kuser/kinit.c (renew_validate): inherit the proxiable and forwardable from the orignal ticket, pointed out by Bernard Antoine of CERN. * doc/setup.texi: More text about the acl_file entry and hdb-ldap-structural-object. From Rüdiger Ranft. * lib/krb5/krbhst.c (fallback_get_hosts): limit the fallback lookups to 5. Patch from Wesley Craig, umich.edu * configure.in: Add special tests for , include test for sys/param.h and sys/types.h * appl/test/tcp_server.c (proto): use keytab for krb5_recvauth Patch from Ingemar Nilsson 2006-08-28 Love Hörnquist Åstrand * kuser/kdigest.c (help): use sl_slc_help(). * kdc/digest.c: Catch more error, add SASL DIGEST MD5. * lib/krb5/digest.c: Catch more error. 2006-08-25 Love Hörnquist Åstrand * doc/setup.texi: language. * doc/heimdal.texi: Add last updated text. * doc/heimdal.css: make box around heimdal title * doc/heimdal.css: Inital Heimdal css for the info manual * lib/krb5/digest.c: In the case where we get a DigestError back, save the error string and code. 2006-08-24 Love Hörnquist Åstrand * kdc/kerberos5.c: Remove _kdc_find_etype(), its no longer used. * kdc/digest.c: Remove local error label and have just one exit label, set error strings properly. * kdc/digest.c: Simply the disabled-service case. Check the allow-digest flag in the HDB entry for the client. * kdc/process.c (krb5_kdc_process_generic_request): check if we got a digest request and process it. * kdc/main.c: Register hdb keytab operations. * kdc/kdc.8: document [kdc]enable-digest=boolean * kdc/Makefile.am: add digest to libkdc * kdc/digest.c: Make a return a goto to avoid freeing un-inited memory in cleanup code. * kdc/default_config.c (krb5_kdc_default_config): default to all bits set to zero. * kdc/kdc.h (krb5_kdc_configuration): Add enable_digest * kdc/headers.h: Include . * lib/krb5/context.c (krb5_kerberos_enctypes): new function, returns the list of Kerberos encryption types sorted in order of most preferred to least preferred encryption type. * kdc/misc.c (_kdc_get_preferred_key): new function, Use the order list of preferred encryption types and sort the available keys and return the most preferred key. * kdc/krb5tgs.c: Adapt to the new sigature of _kdc_find_keys(). * kdc/kerberos5.c: Handle session key etype separately from the tgt etype, now the krbtgt can be a aes-only key without the need to support not-as-good etypes for the krbtgt. 2006-08-23 Love Hörnquist Åstrand * kdc/misc.c: Change _kdc_db_fetch() to return the database pointer to if needed by the consumer. * kdc/krb5tgs.c: Change _kdc_db_fetch() to return the database pointer to if needed by the consumer. * kdc/kerberos5.c: Change _kdc_db_fetch() to return the database pointer to if needed by the consumer. * kdc/kerberos4.c: Change _kdc_db_fetch() to return the database pointer to if needed by the consumer. * kdc/kaserver.c: Change _kdc_db_fetch() to return the database pointer to if needed by the consumer. * kdc/524.c: Change _kdc_db_fetch() to return the database pointer to if needed by the consumer. * kuser/kdigest-commands.in: Add --kerberos-realm, add client request command. * lib/krb5/Makefile.am: digest.c * lib/krb5/krb5.h: Add digest glue. * lib/krb5/digest.c (krb5_digest_set_authentication_user): use krb5_principal * lib/krb5/digest.c: Add digest support to the client side. 2006-08-21 Love Hörnquist Åstrand * lib/krb5/rd_rep.c (krb5_rd_rep): free krb5_ap_rep_enc_part on error and set return pointer to NULL (krb5_free_ap_rep_enc_part): permit freeing of NULL 2006-08-18 Love Hörnquist Åstrand * kdc/{Makefile.am,kdigest.c,kdigest-commands.in}: Frontend for remote digest service in KDC * lib/krb5/krb5_storage.3: Document krb5_{ret,store}_stringnl functions. * lib/krb5/store.c: Add krb5_{ret,store}_stringnl functions, stores/retrieves a \n terminated string. * lib/krb5/krb5_locl.h: Default to address-less tickets. * lib/krb5/init_creds.c (krb5_get_init_creds_opt_get_error): clear error string on error. 2006-07-20 Love Hörnquist Åstrand * lib/krb5/crypto.c: remove aes-192 (CMS) * lib/krb5/crypto.c: Remove more CMS bits. * lib/krb5/crypto.c: Remove CMS symmetric encryption support. 2006-07-13 Love Hörnquist Åstrand * kdc/pkinit.c (_kdc_pk_check_client): make it not crash when there are no acl * kdc/pkinit.c (_kdc_pk_check_client): use the acl in the kerberos database * lib/hdb/hdb.asn1: Rename HDB-Ext-PKINIT-certificate to HDB-Ext-PKINIT-hash. Add trust anchor to HDB-Ext-PKINIT-acl. * lib/hdb/Makefile.am: rename asn1_HDB_Ext_PKINIT_certificate to asn1_HDB_Ext_PKINIT_hash * lib/hdb/ext.c: Add hdb_entry_get_pkinit_hash(). 2006-07-10 Love Hörnquist Åstrand * kuser/kinit.c: If --password-file gets STDIN, read the password from the standard input. * kuser/kinit.1: Document --password-file=STDIN. * lib/krb5/krb5_string_to_key.3: Remove duplicate to. 2006-07-06 Love Hörnquist Åstrand * kdc/krb5tgs.c: (tgs_build_reply): when checking for removed principals, check the second component of the krbtgt, otherwise cross realm wont work. Prompted by report from Mattias Amnefelt. 2006-07-05 Love Hörnquist Åstrand * kdc/connect.c (handle_vanilla_tcp): use unsigned integer for for length (handle_tcp): if the high bit it set in the unknown case, send back a KRB_ERR_FIELD_TOOLONG 2006-07-03 Love Hörnquist Åstrand * appl/gssmask/gssmaestro.c: Add get_version_capa, cache target_name. * appl/gssmask/gssmask.c: use utname() to find the local hostname and version of operatingsystem * appl/gssmask/common.h: include * appl/gssmask/gssmask.c: break out creation of a client and make handleServer pthread_create compatible * appl/gssmask/gssmaestro.c: break out out the build context function 2006-07-01 Love Hörnquist Åstrand * appl/gssmask/gssmaestro.c: externalize slave handling, add GetTargetName glue * appl/gssmask/gssmaestro.c: externalize principal/password handling * lib/krb5/principal.c (krb5_parse_name): set *principal to NULL the first thing we do, so that on failure its set to a known value * appl/gssmask/gssmask.c: AcquireCreds: set principal to NULL to avoid memory corruption GetTargetName: always send a string, even though we don't have a targetname * appl/gssmask: break out common function; add gssmaestro (that only tests one context for now) 2006-06-30 Love Hörnquist Åstrand * lib/krb5/store_fd.c (krb5_storage_from_fd): don't leak fd on malloc failure * appl/gssmask/gssmask.c: split out fetching of credentials for easier reuse for pk-init testing * appl/gssmask: maggot replacement, handles context testing * lib/krb5/cache.c (krb5_cc_new_unique): use KRB5_DEFAULT_CCNAME as the default prefix 2006-06-28 Love Hörnquist Åstrand * doc/heimdal.texi: Add Doug Rabson's license 2006-06-22 Love Hörnquist Åstrand * lib/krb5/init_creds.c: Add storing and getting KRB-ERROR in the krb5_get_init_creds_opt structure. * lib/krb5/init_creds_pw.c: Save KRB-ERROR on error. * lib/krb5/krb5_locl.h (_krb5_get_init_creds_opt_private): add KRB-ERROR 2006-06-21 Love Hörnquist Åstrand * doc/setup.texi: section about verify_krb5_conf and kadmin check 2006-06-15 Love Hörnquist Åstrand * lib/krb5/init_creds_pw.c (get_init_creds_common): drop cred argument, its unused * lib/krb5/Makefile.am: install krb5_get_creds.3 * lib/krb5/krb5_get_creds.3: new file 2006-06-14 Love Hörnquist Åstrand * lib/hdb/hdb-ldap.c: don't use the sambaNTPassword if there is ARCFOUR key already. Idea from Andreas Hasenack. While here, set pw change time using sambaPwdLastSet * kdc/kerberos4.c: Use enable_v4_per_principal and check the new hdb flag. * kdc/kdc.h: Add enable_v4_per_principal 2006-06-12 Love Hörnquist Åstrand * kdc/kerberos5.c (_kdc_as_rep): if kdc_time + config->kdc_warn_pwexpire is past pw_end, add expiration message. From Bernard Antoine. * kdc/default_config.c (krb5_kdc_default_config): set kdc_warn_pwexpire to 0 * kdc/kerberos5.c: indent. 2006-06-07 Love Hörnquist Åstrand * kdc/kerberos5.c: constify 2006-06-06 Love Hörnquist Åstrand * lib/krb5/get_cred.c: Allow setting additional tickets in the tgs-req * kuser/kgetcred.c: add --delegation-credential-cache * kdc/krb5tgs.c (tgs_build_reply): add constrained delegation. * kdc/krb5tgs.c: Add impersonation. * kuser/kgetcred.c: use new krb5_get_creds interface, add impersonation. * lib/krb5/get_cred.c (krb5_get_creds): add KRB5_GC_NO_TRANSIT_CHECK * lib/krb5/misc.c: Add impersonate support functions. * lib/krb5/get_cred.c: Add impersonate and new krb5_get_creds interface. * lib/hdb/hdb.asn1 (HDBFlags): add trusted-for-delegation * lib/krb5/krb5.h: Add krb5_get_creds_opt_data and some more KRB5_GC flags. 2006-06-01 Love Hörnquist Åstrand * lib/hdb/ext.c (hdb_entry_get_ConstrainedDelegACL): new function. * lib/krb5/pkinit.c: Avoid more shadowing. * kdc/connect.c (do_request): clean reply with krb5_data_zero * kdc/krb5tgs.c: Split up the reverse cross krbtgt check and local clien must exists test. * kdc/krb5tgs.c: Plug old memory leaks, unify all goto's. * kdc/krb5tgs.c: Split tgs_rep2 into tgs_parse_request and tgs_build_reply. * kdc/kerberos5.c: split out krb5 tgs req to make it easier to reorganize the code. 2006-05-29 Love Hörnquist Åstrand * lib/krb5/krb5_get_init_creds.3: spelling Björn Sandell * lib/krb5/krb5_get_in_cred.3: spelling Björn Sandell 2006-05-13 Love Hörnquist Åstrand * kpasswd/kpasswdd.c (change): select the realm based on the target principal From Gabor Gombas * lib/krb5/krb5_get_init_creds.3: Add KRB5_PROMPT_TYPE_INFO * lib/krb5/krb5.h: Add KRB5_PROMPT_TYPE_INFO 2006-05-12 Love Hörnquist Åstrand * lib/krb5/pkinit.c: Hidden field of hx509 prompter is removed. Fix a warning. * doc/setup.texi: Point to more examples, hint that you have to use openssl 0.9.8a or later. * doc/setup.texi: DIR now handles both PEM and DER. * kuser/kinit.c: Pass down prompter and password to krb5_get_init_creds_opt_set_pkinit. * lib/krb5/pkinit.c (_krb5_pk_load_id): only use password if its longer then 0 * doc/ack.texi: Add Jason McIntyre. * lib/krb5/krb5_acl_match_file.3: Various tweaks, from Jason McIntyre. 2006-05-11 Love Hörnquist Åstrand * kuser/kinit.c: Move parsing of the PK-INIT configuration file to the library so application doesn't need to deal with it. * lib/krb5/pkinit.c (krb5_get_init_creds_opt_set_pkinit): move parsing of the configuration file to the library so application doesn't need to deal with it. * lib/krb5/pkinit.c (_krb5_pk_load_id): pass the hx509_lock to when trying to read the user certificate. * lib/krb5/pkinit.c (hx_pass_prompter): return 0 on success and 1 on failure. Pointed out by Douglas E. Engert. 2006-05-08 Love Hörnquist Åstrand * lib/krb5/crypto.c: Catches both keyed checkout w/o crypto context cases and doesn't reset the string, and corrects the grammar. * lib/krb5/crypto.c: Drop aes-cbc, rc2 and CMS padding support, its all containted in libhcrypto and libhx509 now. 2006-05-07 Love Hörnquist Åstrand * lib/krb5/pkinit.c (_krb5_pk_verify_sign): Use hx509_get_one_cert. * lib/krb5/crypto.c (create_checksum): provide a error message that a key checksum needs a key. From Andew Bartlett. 2006-05-06 Love Hörnquist Åstrand * lib/krb5/pkinit.c: Now that hcrypto supports DH, remove check for hx509 null DH. * kdc/pkinit.c: Don't call DH_check_pubkey, it doesn't exists in older OpenSSL. * doc/heimdal.texi: Add blob about imath. * doc/ack.texi: Add blob about imath. * include/make_crypto.c: Move up evp.h to please OpenSSL, from Douglas E. Engert. * kcm/acl.c: Multicache kcm interation isn't done yet, let wait with this enum. 2006-05-05 Love Hörnquist Åstrand * lib/krb5/krb5_set_default_realm.3: Spelling/mdoc from Björn Sandell * lib/krb5/krb5_rcache.3: Spelling/mdoc from Björn Sandell * lib/krb5/krb5_keytab.3: Spelling/mdoc from Björn Sandell * lib/krb5/krb5_get_in_cred.3: Spelling/mdoc from Björn Sandell * lib/krb5/krb5_expand_hostname.3: Spelling/mdoc from Björn Sandell * lib/krb5/krb5_c_make_checksum.3: Spelling/mdoc from Björn Sandell * lib/krb5/keytab_file.c (fkt_next_entry_int): read the 32 bit kvno if the reset of the data is longer then 4 bytes in hope to be forward compatible. Pointed out by Michael B Allen. * doc/programming.texi: Add fileformats. * appl/test: Rename u_intXX_t to uintXX_t * kuser: Rename u_intXX_t to uintXX_t * kdc: Rename u_intXX_t to uintXX_t * lib/hdb: Rename u_intXX_t to uintXX_t * lib/45]: Rename u_intXX_t to uintXX_t * lib/krb5: Rename u_intXX_t to uintXX_t * lib/krb5/Makefile.am: Add test_store to TESTS * lib/krb5/pkinit.c: Catch using hx509 null DH and print a more useful error message. * lib/krb5/store.c: Rewrite the krb5_ret_u as proposed by Johan. 2006-05-04 Love Hörnquist Åstrand * kdc/kerberos4.c: Use the new unsigned integer storage types. * kdc/kaserver.c: Use the new unsigned integer storage types. Sprinkle some error handling. * lib/krb5/krb5_storage.3: Document ret and store function for the unsigned fixed size integer types. * lib/krb5/v4_glue.c: Use the new unsigned integer storage types. Fail that the address doesn't match, not the reverse. * lib/krb5/store.c: Add ret and store function for the unsigned fixed size integer types. * lib/krb5/test_store.c: Test the integer storage types. 2006-05-03 Love Hörnquist Åstrand * lib/krb5/store.c (krb5_store_principal): make it take a krb5_const_principal, indent * lib/krb5/krb5_storage.3: krb5_store_principal takes a krb5_const_principal * lib/krb5/pkinit.c: Deal with that hx509_prompt.reply is no longer a pointer. * kdc/kdc.h (krb5_kdc_configuration): add pkinit_kdc_ocsp_file * kdc/config.c: read [kdc]pki-kdc-ocsp 2006-05-02 Love Hörnquist Åstrand * kdc/pkinit.c (_kdc_pk_mk_pa_reply): send back ocsp response if it seems to be valid, simplfy the pkinit-windows DH case (it doesn't exists). 2006-05-01 Love Hörnquist Åstrand * lib/krb5/krb5_warn.3: Spelling/mdoc changes, from Björn Sandell. * lib/krb5/krb5_verify_user.3: Spelling/mdoc changes, from Björn Sandell. * lib/krb5/krb5_verify_init_creds.3: Spelling/mdoc changes, from Björn Sandell. * lib/krb5/krb5_timeofday.3: Spelling/mdoc changes, from Björn Sandell. * lib/krb5/krb5_ticket.3: Spelling/mdoc changes, from Björn Sandell. * lib/krb5/krb5_rd_safe.3: Spelling/mdoc changes, from Björn Sandell. * lib/krb5/krb5_rcache.3: Spelling/mdoc changes, from Björn Sandell. * lib/krb5/krb5_principal.3: Spelling/mdoc changes, from Björn Sandell. * lib/krb5/krb5_parse_name.3: Spelling/mdoc changes, from Björn Sandell. * lib/krb5/krb5_mk_safe.3: Spelling/mdoc changes, from Björn Sandell. * lib/krb5/krb5_keyblock.3: Spelling/mdoc changes, from Björn Sandell. * lib/krb5/krb5_is_thread_safe.3: Spelling/mdoc changes, from Björn Sandell. * lib/krb5/krb5_generate_random_block.3: Spelling/mdoc changes, from Björn Sandell. * lib/krb5/krb5_generate_random_block.3: Spelling/mdoc changes, from Björn Sandell. * lib/krb5/krb5_expand_hostname.3: Spelling/mdoc changes, from Björn Sandell. * lib/krb5/krb5_check_transited.3: Spelling/mdoc changes, from Björn Sandell. * lib/krb5/krb5_c_make_checksum.3: Spelling/mdoc changes, from Björn Sandell. * lib/krb5/krb5_address.3: Spelling/mdoc changes, from Björn Sandell. * lib/krb5/krb5_acl_match_file.3: Spelling/mdoc changes, from Björn Sandell. * lib/krb5/krb5.3: Spelling, from Björn Sandell. * doc/ack.texi: add Björn 2006-04-30 Love Hörnquist Åstrand * lib/krb5/pkinit.c (cert2epi): don't include subject if its null 2006-04-29 Love Hörnquist Åstrand * lib/krb5/pkinit.c: Send over what trust anchors the client have configured. * lib/krb5/pkinit.c (pk_verify_host): set better error string, only check kdc name/address when we got a hostname/address passed in the the function. * kdc/pkinit.c (_kdc_pk_check_client): reorganize and make log when a SAN matches. 2006-04-28 Love Hörnquist Åstrand * doc/setup.texi: More options and some text about windows clients, certificate and KDCs. * doc/setup.texi: notice about pki-mappings file space sensitive * doc/setup.texi: Example pki-mapping file. * lib/krb5/pkinit.c (pk_verify_host): verify hostname/address * lib/hdb/hdb.h: Bump hdb interface version to 4. 2006-04-27 Love Hörnquist Åstrand * kuser/kdestroy.1: Document --credential=principal. * kdc/kerberos5.c (tgs_rep2): check that the client exists in the kerberos database if its local request. * kdc/{misc.c,524.c,kaserver.c,kerberos5.c}: pass down HDB_F_GET_ flags as appropriate * kdc/kerberos4.c (_kdc_db_fetch4): pass down flags though krb5_425_conv_principal_ext2 * kdc/misc.c (_kdc_db_fetch): Break out the that we request from principal from the entry and pass it in as a seprate argument. * lib/hdb/keytab.c (hdb_get_entry): Break out the that we request from principal from the entry and pass it in as a seprate argument. * lib/hdb/common.c: Break out the that we request from principal from the entry and pass it in as a seprate argument. * lib/hdb/hdb.h: Break out the that we request from principal from the entry and pass it in as a seprate argument. Add more flags to ->hdb_get(). Re-indent. 2006-04-26 Love Hörnquist Åstrand * doc/setup.texi: document pki-allow-proxy-certificate * kdc/pkinit.c: Add option [kdc]pki-allow-proxy-certificate=bool to allow using proxy certificate. * lib/krb5/pkinit.c (_krb5_pk_allow_proxy_certificates): expose hx509_verify_set_proxy_certificate * kdc/pkinit.c (_kdc_pk_check_client): Use hx509_cert_get_base_subject to get subject name of the certificate, needed for proxy certificates. * kdc/kerberos5.c: Now that find_keys speaks for it self, remove extra logging. * kdc/kerberos5.c (find_keys): add client_name and server_name argument and use them, and adapt callers. 2006-04-25 Love Hörnquist Åstrand * kuser/kinit.1: document option password-file * kuser/kinit.c: Add option password-file, read password from the first line of a file. * configure.in: make tests/kdc/Makefile * kdc/kerberos5.c: Catch the case where the client sends no encryption types or no pa-types. * lib/hdb/ext.c (hdb_replace_extension): set error message on failure, not success. * lib/hdb/keys.c (parse_key_set): handle error case better (hdb_generate_key_set): return better error 2006-04-24 Love Hörnquist Åstrand * lib/hdb/hdb.c (hdb_create): print out what we don't support * lib/krb5/principal.c: Remove a double free introduced in 1.93 * lib/krb5/log.c (log_file): reset pointer to freed memory * lib/krb5/keytab_keyfile.c (get_cell_and_realm): reset d->cell to make sure its not refereced * tools/krb5-config.in: libhcrypto might depend on libasn1, switch order * lib/krb5/recvauth.c: indent * doc/heimdal.texi: Add Setting up PK-INIT to Detailed Node Listing. * lib/krb5/pkinit.c: Pass down realm to pk_verify_host so the function can verify the certificate is from the right realm. * lib/krb5/init_creds_pw.c: Pass down realm to _krb5_pk_rd_pa_reply 2006-04-23 Love Hörnquist Åstrand * lib/krb5/pkinit.c (pk_verify_host): Add begining of finding subjectAltName_otherName pk-init-san and verifing it. * lib/krb5/sendauth.c: reindent * doc/Makefile.am: use --no-split to make one large file, mostly for html * doc/setup.texi: "document" pkinit_require_eku and pkinit_require_krbtgt_otherName * lib/krb5/pkinit.c: Add pkinit_require_eku and pkinit_require_krbtgt_otherName * doc/setup.texi: Add text about pk-init * tools/kdc-log-analyze.pl: count v5 cross realms too 2006-04-22 Love Hörnquist Åstrand * kdc/pkinit.c: Adapt to change in hx509_cms_create_signed_1. * lib/krb5/pkinit.c: Adapt to change in hx509_cms_create_signed_1. 2006-04-20 Love Hörnquist Åstrand * kdc/pkinit.c (_kdc_pk_rd_padata): use hx509_cms_unwrap_ContentInfo. * kdc/config.c: unbreak * lib/krb5/pkinit.c: Handle diffrences between libhcrypto and libcrypto. * kdc/config.c: Rename pki-chain to pki-pool to match rest of code. 2006-04-12 Love Hörnquist Åstrand * lib/krb5/rd_priv.c: Fix argument to krb5_data_zero. * kdc/config.c: Added certificate revoke information from configuration file. * kdc/pkinit.c: Added certificate revoke information. * kuser/kinit.c: Added certificate revoke information from configuration file. * lib/krb5/pkinit.c (_krb5_pk_load_id): Added certificate revoke information, ie CRL's 2006-04-10 Love Hörnquist Åstrand * lib/krb5/replay.c (krb5_rc_resolve_full): make compile again. * lib/krb5/keytab_krb4.c (krb4_kt_start_seq_get_int): make compile again. * lib/krb5/transited.c (make_path): make sure we return allocated memory Coverity, NetBSD CID#1892 * lib/krb5/transited.c (make_path): make sure we return allocated memory Coverity, NetBSD CID#1892 * lib/krb5/rd_req.c (krb5_verify_authenticator_checksum): on protocol failure, avoid leaking memory Coverity, NetBSD CID#1900 * lib/krb5/principal.c (krb5_parse_name): remember to free realm in case of error Coverity, NetBSD CID#1883 * lib/krb5/principal.c (krb5_425_conv_principal_ext2): remove memory leak in case of weird formated dns replys. Coverity, NetBSD CID#1885 * lib/krb5/replay.c (krb5_rc_resolve_full): don't return pointer to a allocated krb5_rcache in case of error. * lib/krb5/log.c (krb5_addlog_dest): free fn in case of error Coverity, NetBSD CID#1882 * lib/krb5/keytab_krb4.c: Fix deref before NULL check, fix error handling. Coverity, NetBSD CID#2369 * lib/krb5/get_for_creds.c (krb5_get_forwarded_creds): in_creds->client should always be set, assume so. * lib/krb5/keytab_any.c (any_next_entry): restructure to make it easier to read Fixes Coverity, NetBSD CID#625 * lib/krb5/crypto.c (krb5_string_to_key_derived): deref after NULL check. Coverity NetBSD CID#2367 * lib/krb5/build_auth.c (krb5_build_authenticator): use calloc. removed check that was never really used. Coverity NetBSD CID#2370 2006-04-09 Love Hörnquist Åstrand * lib/krb5/rd_req.c (krb5_verify_ap_req2): make sure `ticket´ points to NULL in case of error, add error handling, use calloc. * kpasswd/kpasswdd.c (doit): when done, close all fd in the sockets array and free it. Coverity NetBSD CID#1916 2006-04-08 Love Hörnquist Åstrand * lib/krb5/store.c (krb5_ret_principal): fix memory leak Coverity, NetBSD CID#1695 * kdc/524.c (_kdc_do_524): Handle memory allocation failure Coverity, NetBSD CID#2752 2006-04-07 Love Hörnquist Åstrand * lib/krb5/keytab_file.c (krb5_kt_ret_principal): plug a memory leak Coverity NetBSD CID#1890 * kdc/hprop.c (main): make sure type doesn't need to be set * kdc/mit_dump.c (mit_prop_dump): close fd when done processing Coverity NetBSD CID#1955 * kdc/string2key.c (tokey): catch warnings, free memory after use. Based on Coverity NetBSD CID#1894 * kdc/hprop.c (main): remove dead code. Coverity NetBSD CID#633 2006-04-04 Love Hörnquist Åstrand * kpasswd/kpasswd-generator.c (read_words): catch empty file case, will cause PBE (division by zero) later. From Tobias Stoeckmann. 2006-04-02 Love Hörnquist Åstrand * lib/hdb/keytab.c: Remove a delta from last revision that should have gone in later. * lib/krb5/krbhst.c: fix spelling * lib/krb5/send_to_kdc.c (send_and_recv_http): don't expose freed pointer, found by IBM checker. * lib/krb5/rd_cred.c (krb5_rd_cred): don't expose freed pointer, found by IBM checker. * lib/krb5/addr_families.c (krb5_make_addrport): clear return value on error, found by IBM checker. * kdc/kerberos5.c (check_addresses): treat netbios as no addresses * kdc/{kerberos4,kaserver}.c: _kdc_check_flags takes hdb_entry_ex * kdc/kerberos5.c (_kdc_check_flags): make it take hdb_entry_ex to avoid ?:'s at callers * lib/krb5/v4_glue.c: Avoid using free memory, found by IBM checker. * lib/krb5/transited.c (expand_realm): avoid passing NULL to strlen, found by IBM checker. * lib/krb5/rd_cred.c (krb5_rd_cred): avoid a memory leak on malloc failure, found by IBM checker. * lib/krb5/krbhst.c (_krb5_krbhost_info_move): replace a strcpy with a memcpy * lib/krb5/keytab_keyfile.c (get_cell_and_realm): plug a memory leak, found by IBM checker. * lib/krb5/keytab_file.c (fkt_next_entry_int): remove a dereferencing NULL pointer, found by IBM checker. * lib/krb5/init_creds_pw.c (init_creds_init_as_req): in AS-REQ the cname must always be given, don't avoid that fact and remove a cname == NULL case. Plugs a memory leak found by IBM checker. * lib/krb5/init_creds_pw.c (default_s2k_func): avoid exposing free-ed memory on error. Found by IBM checker. * lib/krb5/init_creds.c (_krb5_get_init_creds_opt_copy): use calloc to avoid uninitialized memory problem. * lib/krb5/data.c (krb5_copy_data): avoid exposing free-ed memory on error. Found by IBM checker. * lib/krb5/fcache.c (fcc_gen_new): fix a use after free, found by IBM checker. * lib/krb5/config_file.c (krb5_config_vget_strings): IBM checker thought it found a memory leak, it didn't, but there was another error in the code, lets fix that instead. * lib/krb5/cache.c (_krb5_expand_default_cc_name): plug memory leak. Found by IBM checker. * lib/krb5/cache.c (_krb5_expand_default_cc_name): avoid return pointer to freed memory in the error case. Found by IBM checker. * lib/hdb/keytab.c (hdb_resolve): off by one, found by IBM checker. * lib/hdb/keys.c (hdb_generate_key_set): set ret_key_set before going into the error clause and freeing key_set. Found by IBM checker. Make sure ret == 0 after of parse error, we catch the "no entries parsed" case later. * lib/krb5/log.c (krb5_addlog_dest): make string length match strings in strcasecmp. Found by IBM checker. 2006-03-30 Love Hörnquist Åstrand * lib/hdb/hdb-ldap.c (LDAP_message2entry): in declaration set variable_name as "hdb_entry_ex" (hdb_ldap_common): change "arg" in condition (if) to "search_base" (hdb_ldapi_create): change "serach_base" to "search_base" From Alex V. Labuta. * lib/krb5/pkinit.c (krb5_get_init_creds_opt_set_pkinit); fix prototype * kuser/kinit.c: Add pool of certificates to help certificate path building for clients sending incomplete path in the signedData. 2006-03-28 Love Hörnquist Åstrand * kdc/pkinit.c: Add pool of certificates to help certificate path building for clients sending incomplete path in the signedData. * lib/krb5/pkinit.c: Add pool of certificates to help certificate path building for clients sending incomplete path in the signedData. 2006-03-27 Love Hörnquist Åstrand * kdc/config.c: Allow passing in related certificates used to build the chain. * kdc/pkinit.c: Allow passing in related certificates used to build the chain. * kdc/kerberos5.c (log_patype): Add case for KRB5_PADATA_PA_PK_OCSP_RESPONSE. * tools/Makefile.am: Spelling * tools/krb5-config.in: Add hx509 when using PK-INIT. * tools/Makefile.am: Add hx509 when using PK-INIT. 2006-03-26 Love Hörnquist Åstrand * lib/krb5/acache.c: Use ticket flags definition, might fix Mac OS X Kerberos.app problems. * lib/krb5/krb5_ccapi.h: Add ticket flags definitions * lib/krb5/pkinit.c: Use less openssl, spell chelling. * kdc/pkinit.c (pk_mk_pa_reply_dh): encode the DH public key with asn1 wrapping * configure.in (AC_CONFIG_FILES): add lib/hx509/Makefile * lib/Makefile.am: Add hx509. * lib/krb5/Makefile.am: Add libhx509.la when PKINIT is used. * configure.in: define automake PKINIT variable * kdc/pkinit.c: Switch to hx509. * lib/krb5/pkinit.c: Switch to hx509. 2006-03-24 Love Hörnquist Åstrand * kdc/kerberos5.c (log_patypes): log the patypes requested by the client 2006-03-23 Love Hörnquist Åstrand * lib/krb5/pkinit.c (_krb5_pk_rd_pa_reply): pass down the req_buffer in the w2k case too. From Douglas E. Engert. 2006-03-19 Love Hörnquist Åstrand * lib/krb5/mk_req_ext.c (_krb5_mk_req_internal): on failure, goto error handling. Fixes Coverity NetBSD CID 2591 by catching a failing krb5_copy_keyblock() 2006-03-17 Love Hörnquist Åstrand * lib/krb5/addr_families.c (krb5_free_addresses): reset val,len in address when free-ing. Fixes Coverity NetBSD bug #2605 (krb5_parse_address): reset val,len before possibly return errors Fixes Coverity NetBSD bug #2605 2006-03-07 Love Hörnquist Åstrand * lib/krb5/send_to_kdc.c (recv_loop): it should never happen, but make sure nbytes > 0 * lib/krb5/get_for_creds.c (add_addrs): handle the case where addr->len == 0 and n == 0, then realloc might return NULL. * lib/krb5/crypto.c (decrypt_*): handle the case where the plaintext is 0 bytes long, realloc might then return NULL. 2006-02-28 Love Hörnquist Åstrand * lib/krb5/krb5_string_to_key.3: Drop krb5_string_to_key_derived. * lib/krb5/krb5.3: Remove krb5_string_to_key_derived. * lib/krb5/crypto.c (AES_string_to_key): drop _krb5_PKCS5_PBKDF2 and use PKCS5_PBKDF2_HMAC_SHA1 instead. * lib/krb5/aes-test.c: reformat, avoid free-ing un-init'd memory * lib/krb5/aes-test.c: Only use PKCS5_PBKDF2_HMAC_SHA1. 2006-02-27 Johan Danielsson * doc/setup.texi: remove cartouches - we don't use them anywhere else, they should be around the example, not inside it, and probably shouldn't be used in html at all 2006-02-18 Love Hörnquist Åstrand * lib/krb5/krb5_warn.3: Document that applications want to use krb5_get_error_message, add example. 2006-02-16 Love Hörnquist Åstrand * lib/krb5/crypto.c (krb5_generate_random_block): check return value from RAND_bytes * lib/krb5/error_string.c: Change indentation, update (c) 2006-02-14 Love Hörnquist Åstrand * lib/krb5/pkinit.c: Make struct krb5_dh_moduli available when compiling w/o pkinit. 2006-02-13 Love Hörnquist Åstrand * lib/krb5/pkinit.c: update to new paChecksum definition, update the dhgroup handling * kdc/pkinit.c: update to new paChecksum definition, use hdb_entry_ex 2006-02-09 Love Hörnquist Åstrand * lib/krb5/krb5_locl.h: Move Configurable options to last in the file. * lib/krb5/krb5_locl.h: Wrap KRB5_ADDRESSLESS_DEFAULT with #ifndef 2006-02-03 Love Hörnquist Åstrand * kpasswd/kpasswdd.c: Send back a better error-message to the client in case the password change was rejected. * lib/krb5/krb5_warn.3: Document krb5_get_error_message. * lib/krb5/error_string.c (krb5_get_error_message): new function, and combination of krb5_get_error_string and krb5_get_err_text * lib/krb5/krb5.3: sort, and krb5_get_error_message * lib/hdb/hdb-ldap.c: Log the filter string to the error message when doing searches. * lib/krb5/init_creds.c (krb5_get_init_creds_opt_set_default_flags): Use KRB5_ADDRESSLESS_DEFAULT when checking [appdefault]no-addresses. * lib/krb5/get_cred.c (get_cred_from_kdc_flags): Use KRB5_ADDRESSLESS_DEFAULT when checking [appdefault]no-addresses. * lib/krb5/get_for_creds.c (krb5_get_forwarded_creds): Use [appdefault]no-addresses before checking if the krbtgt is address-less, use KRB5_ADDRESSLESS_DEFAULT. * lib/krb5/krb5_locl.h: Introduce KRB5_ADDRESSLESS_DEFAULT that controlls all address-less behavior. Defaults to false. 2006-02-01 Love Hörnquist Åstrand * lib/krb5/n-fold-test.c: main is not a KRB5_LIB_FUNCTION * lib/krb5/mk_priv.c (krb5_mk_priv): abort if ASN1_MALLOC_ENCODE failes to produce the matching lenghts. 2006-01-27 Love Hörnquist Åstrand * kcm/protocol.c (kcm_op_retrieve): remove unused variable 2006-01-15 Love Hörnquist Åstrand * tools/krb5-config.in: Move depenency on @LIB_dbopen@ to kadm-server, kerberos library doesn't depend on db-library. 2006-01-13 Love Hörnquist Åstrand * include/Makefile.am: Don't clean crypto headers, they now live in hcrypto/. Add hcrypto to SUBDIRS. * include/hcrypto/Makefile.am: clean installed headers * include/make_crypto.c: include crypto headers from hcrypto/ * include/make_crypto.c: Include more crypto headerfiles. Remove support for old hash names. 2006-01-02 Love Hörnquist Åstrand * kdc/misc.c (_kdc_db_fetch): use calloc to allocate the entry, from Andrew Bartlet. * Happy New Year. heimdal-7.5.0/ChangeLog.20010000644000175000017500000010613312136107746013420 0ustar niknik2001-12-20 Johan Danielsson * lib/krb5/crypto.c: use our own des string-to-key function, since the one from openssl sometimes generates wrong output 2001-12-05 Jacques Vidrine * lib/hdb/mkey.c: fix a bug in which kstash would crash if there were no /etc/krb5.conf 2001-11-09 Johan Danielsson * lib/krb5/krb5_verify_user.3: sort references (from Thomas Klausner) * lib/krb5/krb5_principal_get_realm.3: add section to reference (from Thomas Klausner) * lib/krb5/krb5_krbhst_init.3: sort references (from Thomas Klausner) * lib/krb5/krb5_keytab.3: white space fixes (from Thomas Klausner) * lib/krb5/krb5_get_krbhst.3: remove extra white space (from Thomas Klausner) * lib/krb5/krb5_get_all_client_addrs.3: add section to reference (from Thomas Klausner) 2001-10-29 Jacques Vidrine * admin/get.c: fix a bug in which a reference to a data structure on the stack was being kept after the containing function's lifetime, resulting in a segfault during `ktutil get'. 2001-10-22 Assar Westerlund * lib/krb5/crypto.c: make all high-level encrypting and decrypting functions check the return value of the underlying function and handle errors more consistently. noted by Sam Hartman 2001-10-21 Assar Westerlund * lib/krb5/crypto.c (enctype_arcfour_hmac_md5): actually use a non-keyed checksum when it should be non-keyed 2001-09-29 Assar Westerlund * kuser/kinit.1: add the kauth alias * kuser/kinit.c: allow specification of afslog in krb5.conf, noted by jhutz@cs.cmu.edu 2001-09-27 Assar Westerlund * lib/asn1/gen.c: remove the need for libasn1.h, also make generated files include all files from IMPORTed modules * lib/krb5/krb5.h (KRB5_KPASSWD_*): set correct values * kpasswd/kpasswd.c: improve error message printing * lib/krb5/changepw.c (krb5_passwd_result_to_string): add change to use sequence numbers connect the udp socket so that we can figure out the local address 2001-09-25 Assar Westerlund * lib/asn1: implement OBJECT IDENTIFIER and ENUMERATED 2001-09-20 Johan Danielsson * lib/krb5/principal.c (krb5_425_conv_principal_ext): try using lower case realm as domain, but only when given a verification function 2001-09-20 Assar Westerlund * lib/asn1/der_put.c (der_put_length): do not even try writing anything when len == 0 2001-09-18 Johan Danielsson * kdc/hpropd.c: add realm override option * lib/krb5/set_default_realm.c (krb5_set_default_realm): make realm parameter const * kdc/hprop.c: more free's * lib/krb5/init_creds_pw.c (krb5_get_init_creds_keytab): free key proc data * lib/krb5/expand_hostname.c (krb5_expand_hostname_realms): free addrinfo * lib/hdb/mkey.c (hdb_set_master_keyfile): clear error string when not returning error 2001-09-16 Assar Westerlund * lib/krb5/appdefault.c (krb5_appdefault_{boolean,string,time): make realm const * lib/krb5/crypto.c: use des functions to avoid generating warnings with openssl's prototypes 2001-09-05 Johan Danielsson * configure.in: check for termcap.h * lib/asn1/lex.l: add another undef ECHO to keep AIX lex happy 2001-09-03 Assar Westerlund * lib/krb5/addr_families.c (krb5_print_address): handle snprintf returning < 0. noticed by hin@stacken.kth.se 2001-09-03 Assar Westerlund * Release 0.4e 2001-09-02 Johan Danielsson * kuser/Makefile.am: install kauth as a symlink to kinit * kuser/kinit.c: get v4_tickets by default * lib/asn1/Makefile.am: fix for broken automake 2001-08-31 Johan Danielsson * lib/hdb/hdb-ldap.c: some pretty much untested changes from Luke Howard * kuser/kinit.1: remove references to kauth * kuser/Makefile.am: kauth is no more * kuser/kinit.c: use appdefaults for everything. defaults are now as in kauth. * lib/krb5/appdefault.c: also check libdefaults, and realms/realm * lib/krb5/context.c (krb5_free_context): free more stuff 2001-08-30 Johan Danielsson * lib/krb5/verify_krb5_conf.c: do some checks of the values in the file * lib/krb5/krb5.conf.5: remove srv_try_txt, fix spelling * lib/krb5/context.c: don't init srv_try_txt, since it isn't used anymore 2001-08-29 Jacques Vidrine * configure.in: Check for already-installed com_err. 2001-08-28 Assar Westerlund * lib/krb5/Makefile.am (libkrb5_la_LDFLAGS): set versoin to 18:2:1 2001-08-24 Assar Westerlund * kuser/Makefile.am: remove CHECK_LOCAL - non bin programs require no special treatment now * kuser/generate-requests.c: parse arguments in a useful way * kuser/kverify.c: add --help/--verify 2001-08-22 Assar Westerlund * configure.in: bump prereq to 2.52 remove unused test_LIB_KRB4 * configure.in: re-write the handling of crypto libraries. try to use the one of openssl's libcrypto or krb4's libdes that has all the required functionality (md4, md5, sha1, des, rc4). if there is no such library, the included lib/des is built. * kdc/headers.h: include libutil.h if it exists * kpasswd/kpasswd_locl.h: include libutil.h if it exists * kdc/kerberos4.c (get_des_key): check for null keys even if is_server 2001-08-21 Assar Westerlund * lib/asn1/asn1_print.c: print some size_t correctly * configure.in: remove extra space after -L check for libutil.h 2001-08-17 Johan Danielsson * kdc/kdc_locl.h: fix prototype for get_des_key * kdc/kaserver.c: fix call to get_des_key * kdc/524.c: fix call to get_des_key * kdc/kerberos4.c (get_des_key): if getting a key for a server, return any des-key not just keys that can be string-to-keyed by the client 2001-08-10 Assar Westerlund * Release 0.4d 2001-08-10 Assar Westerlund * configure.in: check for openpty * lib/hdb/Makefile.am (libhdb_la_LDFLAGS): update to 7:4:0 2001-08-08 Assar Westerlund * configure.in: just add -L (if required) from krb4 when testing for libdes/libcrypto 2001-08-04 Assar Westerlund * lib/krb5/Makefile.am (man_MANS): add some missing man pages * fix-export: fix the sed expression for finding the man pages 2001-07-31 Assar Westerlund * kpasswd/kpasswd-generator.c (main): implement --version and --help * lib/krb5/Makefile.am (libkrb5_la_LDFLAGS): update version to 18:1:1 2001-07-27 Assar Westerlund * lib/krb5/context.c (init_context_from_config_file): check parsing of addresses 2001-07-26 Assar Westerlund * lib/krb5/sock_principal.c (krb5_sock_to_principal): rename sa_len -> salen to avoid the macro that's defined on irix. noted by "Jacques A. Vidrine" 2001-07-24 Johan Danielsson * lib/krb5/addr_families.c: add support for type KRB5_ADDRESS_ADDRPORT * lib/krb5/addr_families.c (krb5_address_order): complain about unsuppored address types 2001-07-23 Johan Danielsson * admin/get.c: don't open connection to server until we loop over the principals, at that time we know the realm of the (first) principal and we can default to that admin server * admin: add a rename command 2001-07-19 Assar Westerlund * kdc/hprop.c (usage): clarify a tiny bit 2001-07-19 Assar Westerlund * Release 0.4c 2001-07-19 Assar Westerlund * lib/krb5/Makefile.am (libkrb5_la_LDFLAGS): bump version to 18:0:1 * lib/krb5/get_for_creds.c (krb5_fwd_tgt_creds): make it behave the same way as the MIT function * lib/hdb/Makefile.am (libhdb_la_LDFLAGS): update to 7:3:0 * lib/krb5/sock_principal.c (krb5_sock_to_principal): use getnameinfo * lib/krb5/krbhst.c (srv_find_realm): handle port numbers consistenly in local byte order * lib/krb5/get_default_realm.c (krb5_get_default_realm): set an error string * kuser/kinit.c (renew_validate): invert condition correctly. get v4 tickets if we succeed renewing * lib/krb5/principal.c (krb5_principal_get_type): add (default_v4_name_convert): add "smtp" 2001-07-13 Assar Westerlund * configure.in: remove make-print-version from LIBOBJS, it's no longer in lib/roken but always built in lib/vers 2001-07-12 Johan Danielsson * lib/hdb/mkey.c: more set_error_string 2001-07-12 Assar Westerlund * lib/hdb/Makefile.am (libhdb_la_LIBADD): add required library dependencies * lib/asn1/Makefile.am (libasn1_la_LIBADD): add required library dependencies 2001-07-11 Johan Danielsson * kdc/hprop.c: remove v4 master key handling; remove old v4-db and ka-db flags; add defaults for v4_realm and afs_cell 2001-07-09 Assar Westerlund * lib/krb5/sock_principal.c (krb5_sock_to_principal): copy hname before calling krb5_sname_to_principal. from "Jacques A. Vidrine" 2001-07-08 Johan Danielsson * lib/krb5/context.c: use krb5_copy_addresses instead of copy_HostAddresses 2001-07-06 Assar Westerlund * configure.in (LIB_des_a, LIB_des_so): add these so that they can be used by lib/auth/sia * kuser/kinit.c: re-do some of the v4 fallbacks: look at get-tokens flag do not print extra errors do not try to do 524 if we got tickets from a v4 server 2001-07-03 Assar Westerlund * lib/krb5/replay.c (krb5_get_server_rcache): cast argument to printf * lib/krb5/get_addrs.c (find_all_addresses): call free_addresses on ignore_addresses correctly * lib/krb5/init_creds.c (krb5_get_init_creds_opt_set_default_flags): change to take a const realm * lib/krb5/principal.c (krb5_425_conv_principal_ext): if the instance is the first component of the local hostname, the converted host should be the long hostname. from 2001-07-02 Johan Danielsson * lib/krb5/Makefile.am: address.c is no more; add a couple of manpages * lib/krb5/krb5_timeofday.3: new manpage * lib/krb5/krb5_get_all_client_addrs.3: new manpage * lib/krb5/get_in_tkt.c (init_as_req): treat no addresses as wildcard * lib/krb5/get_cred.c (get_cred_kdc_la): treat no addresses as wildcard * lib/krb5/get_addrs.c: don't include client addresses that match ignore_addresses * lib/krb5/context.c: initialise ignore_addresses * lib/krb5/addr_families.c: add new `arange' fake address type, that matches more than one address; this required some internal changes to many functions, so all of address.c got moved here (wasn't much left there) * lib/krb5/krb5.h: add list of ignored addresses to context 2001-07-03 Assar Westerlund * Release 0.4b 2001-07-03 Assar Westerlund * lib/krb5/Makefile.am (libkrb5_la_LDFLAGS): set version to 17:0:0 * lib/hdb/Makefile.am (libhdb_la_LDFLAGS): set version to 7:2:0 2001-07-03 Assar Westerlund * Release 0.4a 2001-07-02 Johan Danielsson * kuser/kinit.c: make this compile without krb4 support * lib/krb5/write_message.c: remove priv parameter from write_safe_message; don't know why it was there in the first place * doc/install.texi: remove kaserver switches, it's always compiled in now * kdc/hprop.c: always include kadb support * kdc/kaserver.c: always include kaserver support 2001-07-02 Assar Westerlund * kpasswd/kpasswdd.c (doit): make failing to bind a socket a non-fatal error, and abort if no sockets were bound 2001-07-01 Assar Westerlund * lib/krb5/krbhst.c: remember the real port number when falling back from kpasswd -> kadmin, and krb524 -> kdc 2001-06-29 Assar Westerlund * lib/krb5/get_for_creds.c (krb5_get_forwarded_creds): if no_addresses is set, do not add any local addresses to KRB_CRED * kuser/kinit.c: remove extra clearing of password and some redundant code 2001-06-29 Johan Danielsson * kuser/kinit.c: move ticket conversion code to separate function, and call that from a couple of places, like when renewing a ticket; also add a flag for just converting a ticket * lib/krb5/init_creds_pw.c: set renew-life to some sane value * kdc/524.c: don't send more data than required 2001-06-24 Assar Westerlund * lib/krb5/store_fd.c (krb5_storage_from_fd): check malloc returns * lib/krb5/keytab_any.c (any_resolve); improving parsing of ANY: (any_start_seq_get): remove a double free (any_next_entry): iterate over all (sub) keytabs and avoid leave data around to be freed again * kdc/kdc_locl.h: add a define for des_new_random_key when using openssl's libcrypto * configure.in: move v6 tests down * lib/krb5/krb5.h (krb5_context_data): remove srv_try_rfc2052 * update to libtool 1.4 and autoconf 2.50 2001-06-22 Johan Danielsson * lib/hdb/hdb.c: use krb5_add_et_list 2001-06-21 Johan Danielsson * lib/hdb/Makefile.am: add generation number * lib/hdb/common.c: add generation number code * lib/hdb/hdb.asn1: add generation number * lib/hdb/print.c: use krb5_storage to make it more dynamic 2001-06-21 Assar Westerlund * lib/krb5/krb5.conf.5: update to changed names used by krb5_get_init_creds_opt_set_default_flags * lib/krb5/init_creds.c (krb5_get_init_creds_opt_set_default_flags): make the appdefault keywords have the same names * configure.in: only add -L and -R to the krb4 libdir if we are actually using it * lib/krb5/krbhst.c (fallback_get_hosts): do not copy trailing dot of hostname add some comments * lib/krb5/krbhst.c: use getaddrinfo instead of dns_lookup when testing for kerberos.REALM. this allows reusing that information when actually contacting the server and thus avoids one DNS lookup 2001-06-20 Johan Danielsson * lib/krb5/krb5.h: include k524_err.h * lib/krb5/convert_creds.c (krb524_convert_creds_kdc): don't test for keytype, the server will do this for us if it has anything to complain about * lib/krb5/context.c: add protocol compatible krb524 error codes * lib/krb5/Makefile.am: add protocol compatible krb524 error codes * lib/krb5/k524_err.et: add protocol compatible krb524 error codes * lib/krb5/krb5_principal_get_realm.3: manpage * lib/krb5/principal.c: add functions `krb5_principal_get_realm' and `krb5_principal_get_comp_string' that returns parts of a principal; this is a replacement for the internal `krb5_princ_realm' and `krb5_princ_component' macros that everyone seem to use 2001-06-19 Assar Westerlund * kuser/kinit.c (main): dereference result from krb5_princ_realm. from Thomas Nystrom 2001-06-18 Johan Danielsson * lib/krb5/mk_req.c (krb5_mk_req_exact): free creds when done * lib/krb5/crypto.c (krb5_string_to_key_derived): fix memory leak * lib/krb5/krbhst.c (config_get_hosts): free hostlist * kuser/kinit.c: free principal 2001-06-18 Assar Westerlund * lib/krb5/send_to_kdc.c (krb5_sendto): remove an extra freeaddrinfo * lib/krb5/convert_creds.c (krb524_convert_creds_kdc_ccache): remove some unused variables * lib/krb5/krbhst.c (admin_get_next): spell kerberos correctly * kdc/kerberos5.c: update to new krb5_auth_con* names * kdc/hpropd.c: update to new krb5_auth_con* names * lib/krb5/rd_req.c (krb5_rd_req): use krb5_auth_con* functions and remove some comments * lib/krb5/rd_safe.c (krb5_rd_safe): pick the keys in the right order: remote - local - session * lib/krb5/rd_rep.c (krb5_rd_rep): save the remote sub key in the auth_context * lib/krb5/rd_priv.c (krb5_rd_priv): pick keys in the correct order: remote - local - session * lib/krb5/mk_safe.c (krb5_mk_safe): pick keys in the right order, local - remote - session 2001-06-18 Johan Danielsson * lib/krb5/convert_creds.c: use starttime instead of authtime, from Chris Chiappa * lib/krb5/convert_creds.c: make krb524_convert_creds_kdc match the MIT function by the same name; add krb524_convert_creds_kdc_ccache that does what the old version did * admin/list.c (do_list): make sure list of keys is NULL terminated; similar to patch sent by Chris Chiappa 2001-06-18 Assar Westerlund * lib/krb5/mcache.c (mcc_remove_cred): use krb5_free_creds_contents * lib/krb5/auth_context.c: name function krb5_auth_con more consistenly * lib/krb5/rd_req.c (krb5_verify_authenticator_checksum): use renamed krb5_auth_con_getauthenticator * lib/krb5/convert_creds.c (krb524_convert_creds_kdc): update to use krb5_krbhst API * lib/krb5/changepw.c (krb5_change_password): update to use krb5_krbhst API * lib/krb5/send_to_kdc.c: update to use krb5_krbhst API * lib/krb5/krbhst.c (krb5_krbhst_get_addrinfo): add set def_port in krb5_krbhst_info (krb5_krbhst_free): free everything * lib/krb5/krb5.h (KRB5_VERIFY_NO_ADDRESSES): add (krb5_krbhst_info): add def_port (default port for this service) * lib/krb5/krbhst-test.c: make it more verbose and useful * lib/krb5/krbhst.c: remove some more memory leaks do not try any dns operations if there is local configuration admin: fallback to kerberos.REALM 524: fallback to kdcs kpasswd: fallback to admin add some comments * configure.in: remove initstate and setstate, they should be in cf/roken-frag.m4 * lib/krb5/Makefile.am (noinst_PROGRAMS): add krbhst-test * lib/krb5/krbhst-test.c: new program for testing krbhst * lib/krb5/krbhst.c (common_init): remove memory leak (main): move test program into krbhst-test 2001-06-17 Johan Danielsson * lib/krb5/krb5_krbhst_init.3: manpage * lib/krb5/krb5_get_krbhst.3: manpage 2001-06-16 Johan Danielsson * lib/krb5/krb5.h: add opaque krb5_krbhst_handle type * lib/krb5/krbhst.c: change void* to krb5_krbhst_handle * lib/krb5/krb5.h: types for new krbhst api * lib/krb5/krbhst.c: implement a new api that looks up one host at a time, instead of making a list of hosts 2001-06-09 Johan Danielsson * configure.in: test for initstate and setstate * lib/krb5/krbhst.c: remove rfc2052 support 2001-06-08 Johan Danielsson * fix some manpages for broken mdoc.old grog test 2001-05-28 Assar Westerlund * lib/krb5/krb5.conf.5: add [appdefaults] * lib/krb5/init_creds_pw.c: remove configuration reading that is now done in krb5_get_init_creds_opt_set_default_flags * lib/krb5/init_creds.c (krb5_get_init_creds_opt_set_default_flags): add reading of libdefaults versions of these and add no_addresses * lib/krb5/get_in_tkt.c (krb5_get_in_cred): clear error string when preauth was required and we retry 2001-05-25 Assar Westerlund * lib/krb5/convert_creds.c (krb524_convert_creds_kdc): call krb5_get_krb524hst * lib/krb5/krbhst.c (krb5_get_krb524hst): add and restructure the support functions 2001-05-22 Assar Westerlund * kdc/kerberos5.c (tgs_rep2): alloc and free csec and cusec properly 2001-05-17 Assar Westerlund * Release 0.3f 2001-05-17 Assar Westerlund * lib/krb5/Makefile.am: bump version to 16:0:0 * lib/hdb/Makefile.am: bump version to 7:1:0 * lib/asn1/Makefile.am: bump version to 5:0:0 * lib/krb5/keytab_krb4.c: add SRVTAB as an alias for krb4 * lib/krb5/codec.c: remove dead code 2001-05-17 Johan Danielsson * kdc/config.c: actually check the ticket addresses 2001-05-15 Assar Westerlund * lib/krb5/rd_error.c (krb5_error_from_rd_error): use correct parenthesis * lib/krb5/eai_to_heim_errno.c (krb5_eai_to_heim_errno): add `errno' (called system_error) to allow callers to make sure they pass the current and relevant value. update callers 2001-05-14 Johan Danielsson * lib/krb5/verify_user.c: krb5_verify_user_opt * lib/krb5/krb5.h: verify_opt * kdc/kerberos5.c: pass context to krb5_domain_x500_decode 2001-05-14 Assar Westerlund * kpasswd/kpasswdd.c: adapt to new address functions * kdc/kerberos5.c: adapt to changing address functions use LR_TYPE * kdc/connect.c: adapt to changing address functions * kdc/config.c: new krb5_config_parse_file * kdc/524.c: new krb5_sockaddr2address * lib/krb5/*: add some krb5_{set,clear}_error_string * lib/asn1/k5.asn1 (LR_TYPE): add * lib/asn1/Makefile.am (gen_files): add asn1_LR_TYPE.x 2001-05-11 Assar Westerlund * kdc/kerberos5.c (tsg_rep): fix typo in variable name * kpasswd/kpasswd-generator.c (nop_prompter): update prototype * lib/krb5/init_creds_pw.c: update to new prompter, use prompter types and send two prompts at once when changning password * lib/krb5/prompter_posix.c (krb5_prompter_posix): add name * lib/krb5/krb5.h (krb5_prompt): add type (krb5_prompter_fct): add anem * lib/krb5/cache.c (krb5_cc_next_cred): transpose last two paramaters to krb5_cc_next_cred (as MIT does, and not as they document). From "Jacques A. Vidrine" 2001-05-11 Johan Danielsson * lib/krb5/Makefile.am: store-test * lib/krb5/store-test.c: simple bit storage test * lib/krb5/store.c: add more byteorder storage flags * lib/krb5/krb5.h: add more byteorder storage flags * kdc/kerberos5.c: don't use NULL where we mean 0 * kdc/kerberos5.c: put referral test code in separate function, and test for KRB5_NT_SRV_INST 2001-05-10 Assar Westerlund * admin/list.c (do_list): do not close the keytab if opening it failed * admin/list.c (do_list): always print complete names. print everything to stdout. * admin/list.c: print both v5 and v4 list by default * admin/remove.c (kt_remove): reorganize some. open the keytab (defaulting to the modify one). * admin/purge.c (kt_purge): reorganize some. open the keytab (defaulting to the modify one). correct usage strings * admin/list.c (kt_list): reorganize some. open the keytab * admin/get.c (kt_get): reorganize some. open the keytab (defaulting to the modify one) * admin/copy.c (kt_copy): default to modify key name. re-organise * admin/change.c (kt_change): reorganize some. open the keytab (defaulting to the modify one) * admin/add.c (kt_add): reorganize some. open the keytab (defaulting to the modify one) * admin/ktutil.c (main): do not open the keytab, let every sub-function handle it * kdc/config.c (configure): call free_getarg_strings * lib/krb5/get_in_tkt.c (krb5_get_in_cred): set error strings for a few more errors * lib/krb5/get_host_realm.c (krb5_get_host_realm_int): make `use_dns' parameter boolean * lib/krb5/krb5.h (krb5_context_data): add default_keytab_modify * lib/krb5/context.c (init_context_from_config_file): set default_keytab_modify * lib/krb5/krb5_locl.h (KEYTAB_DEFAULT): change to ANY:FILE:/etc/krb5.keytab,krb4:/etc/srvtab (KEYTAB_DEFAULT_MODIFY): add * lib/krb5/keytab.c (krb5_kt_default_modify_name): add (krb5_kt_resolve): set error string for failed keytab type 2001-05-08 Assar Westerlund * lib/krb5/crypto.c (encryption_type): make field names more consistent (create_checksum): separate usage and type (krb5_create_checksum): add a separate type parameter (encrypt_internal): only free once on mismatched checksum length * lib/krb5/send_to_kdc.c (krb5_sendto_kdc2): try to tell what realm we didn't manage to reach any KDC for in the error string * lib/krb5/generate_seq_number.c (krb5_generate_seq_number): free the entire subkey. from 2001-05-07 Johan Danielsson * lib/krb5/keytab_keyfile.c (akf_start_seq_get): return KT_NOTFOUND if the file is empty 2001-05-07 Assar Westerlund * lib/krb5/fcache.c: call krb5_set_error_string when open fails fatally * lib/krb5/keytab_file.c: call krb5_set_error_string when open fails fatally * lib/krb5/warn.c (_warnerr): print error_string in context in preference to error string derived from error code * kuser/kinit.c (main): try to print the error string * lib/krb5/get_in_tkt.c (krb5_get_in_cred): set some sensible error strings for errors * lib/krb5/krb5.h (krb5_context_data): add error_string and error_buf * lib/krb5/Makefile.am (libkrb5_la_SOURCES): add error_string.c * lib/krb5/error_string.c: new file 2001-05-02 Johan Danielsson * lib/krb5/time.c: krb5_string_to_deltat * lib/krb5/sock_principal.c: one less data copy * lib/krb5/eai_to_heim_errno.c: conversion function for h_errno's * lib/krb5/get_default_principal.c: change this slightly * lib/krb5/crypto.c: make checksum_types into an array of pointers * lib/krb5/convert_creds.c: make sure we always use a des-cbc-crc ticket 2001-04-29 Assar Westerlund * kdc/kerberos5.c (tgs_rep2): return a reference to a krbtgt for the right realm if we fail to find a non-krbtgt service in the database and the second component does a succesful non-dns lookup to get the real realm (which has to be different from the originally-supplied realm). this should help windows 2000 clients that always start their lookups in `their' realm and do not have any idea of how to map hostnames into realms * kdc/kerberos5.c (is_krbtgt): rename to get_krbtgt_realm 2001-04-27 Johan Danielsson * lib/krb5/get_host_realm.c (krb5_get_host_realm_int): add extra parameter to request use of dns or not 2001-04-25 Assar Westerlund * admin/get.c (kt_get): allow specification of encryption types * lib/krb5/verify_init.c (krb5_verify_init_creds): do not try to close an unopened ccache, noted by * lib/krb5/krb5.h (krb5_any_ops): add declaration * lib/krb5/context.c (init_context_from_config_file): register krb5_any_ops * lib/krb5/keytab_any.c: new file, implementing union of keytabs * lib/krb5/Makefile.am (libkrb5_la_SOURCES): add keytab_any.c * lib/krb5/init_creds_pw.c (get_init_creds_common): handle options == NULL. noted by 2001-04-19 Johan Danielsson * lib/krb5/rd_cred.c: set ret_creds to NULL before doing anything else, from Jacques Vidrine 2001-04-18 Johan Danielsson * lib/hdb/libasn1.h: asn1.h -> krb5_asn1.h * lib/asn1/Makefile.am: add asn1_ENCTYPE.x * lib/krb5/krb5.h: adapt to asn1 changes * lib/asn1/k5.asn1: move enctypes here * lib/asn1/libasn1.h: rename asn1.h to krb5_asn1.h to avoid conflicts * lib/asn1/Makefile.am: rename asn1.h to krb5_asn1.h to avoid conflicts * lib/asn1/lex.l: use strtol to parse constants 2001-04-06 Johan Danielsson * kuser/kinit.c: add simple support for running commands 2001-03-26 Assar Westerlund * lib/hdb/hdb-ldap.c: change order of includes to allow it to work with more versions of openldap * kdc/kerberos5.c (tgs_rep2): try to set sec and usec in error replies (*): update callers of krb5_km_error (check_tgs_flags): handle renews requesting non-renewable tickets * lib/krb5/mk_error.c (krb5_mk_error): allow specifying both ctime and cusec * lib/krb5/krb5.h (krb5_checksum, krb5_keyusage): add compatibility names * lib/krb5/crypto.c (create_checksum): change so that `type == 0' means pick from the `crypto' (context) and otherwise use that type. this is not a large change in practice and allows callers to specify the exact checksum algorithm to use 2001-03-13 Assar Westerlund * lib/krb5/get_cred.c (get_cred_kdc): add support for falling back to KRB5_KU_AP_REQ_AUTH when KRB5_KU_TGS_REQ_AUTH gives `bad integrity'. this helps for talking to old (pre 0.3d) KDCs 2001-03-12 Assar Westerlund * lib/krb5/crypto.c (krb5_derive_key): new function, used by derived-key-test.c * lib/krb5/string-to-key-test.c: add new test vectors posted by Ken Raeburn in to ietf-krb-wg@anl.gov * lib/krb5/n-fold-test.c: more test vectors from same source * lib/krb5/derived-key-test.c: more tests from same source 2001-03-06 Assar Westerlund * acconfig.h: include roken_rename.h when appropriate 2001-03-06 Assar Westerlund * lib/krb5/krb5.h (krb5_enctype): remove trailing comma 2001-03-04 Assar Westerlund * lib/krb5/krb5.h (krb5_enctype): add ENCTYPE_* aliases for compatibility with MIT krb5 2001-03-02 Assar Westerlund * kuser/kinit.c (main): only request a renewable ticket when explicitly requested. it still gets a renewable one if the renew life is specified * kuser/kinit.c (renew_validate): treat -1 as flags not being set 2001-02-28 Johan Danielsson * lib/krb5/context.c (krb5_init_ets): use krb5_add_et_list 2001-02-27 Johan Danielsson * lib/krb5/get_cred.c: implement krb5_get_cred_from_kdc_opt 2001-02-25 Assar Westerlund * configure.in: do not use -R when testing for des functions 2001-02-14 Assar Westerlund * configure.in: test for lber.h when trying to link against openldap to handle openldap v1, from Sumit Bose 2001-02-19 Assar Westerlund * lib/asn1/libasn1.h: add string.h (for memset) 2001-02-15 Assar Westerlund * lib/krb5/warn.c (_warnerr): add printf attributes * lib/krb5/send_to_kdc.c (krb5_sendto): loop over all address returned by getaddrinfo before trying the next kdc. from thorpej@netbsd.org * lib/krb5/krb5.conf.5: fix default_realm in example * kdc/connect.c: fix a few kdc_log format types * configure.in: try to handle libdes/libcrypto ont requiring -L 2001-02-10 Assar Westerlund * lib/asn1/gen_decode.c (generate_type_decode): zero the data at the beginning of the generated function, and add a label `fail' that the code jumps to in case of errors that frees all allocated data 2001-02-07 Assar Westerlund * configure.in: aix dce: fix misquotes, from Ake Sandgren * configure.in (dpagaix_LDFLAGS): try to add export file 2001-02-05 Assar Westerlund * lib/krb5/krb5_keytab.3: new man page, contributed by * kdc/kaserver.c: update to new db_fetch4 2001-02-05 Assar Westerlund * Release 0.3e 2001-01-30 Assar Westerlund * kdc/hprop.c (v4_get_masterkey): check kdb_verify_master_key properly (kdb_prop): decrypt key properly * kdc/hprop.c: handle building with KRB4 always try to decrypt v4 data with the master key leave it up to the v5 how to encrypt with that master key * kdc/kstash.c: include file name in error messages * kdc/hprop.c: fix a typo and check some more return values * lib/hdb/hdb-ldap.c (LDAP__lookup_princ): call ldap_search_s correctly. From Jacques Vidrine * kdc/misc.c (db_fetch): HDB_ERR_NOENTRY makes more sense than ENOENT * lib/krb5/Makefile.am (libkrb5_la_LDFLAGS): bump version to 15:0:0 * lib/hdb/Makefile.am (libhdb_la_LDFLAGS): bump version to 7:0:0 * lib/asn1/Makefile.am (libasn1_la_LDFLAGS): bump version to 4:0:2 * kdc/misc.c (db_fetch): return an error code. change callers to look at this and try to print it in log messages * lib/krb5/crypto.c (decrypt_internal_derived): check that there's enough data 2001-01-29 Assar Westerlund * kdc/hprop.c (realm_buf): move it so it becomes properly conditional on KRB4 * lib/hdb/mkey.c (hdb_unseal_keys_mkey, hdb_seal_keys_mkey, hdb_unseal_keys, hdb_seal_keys): check that we have the correct master key and that we manage to decrypt the key properly, returning an error code. fix all callers to check return value. * tools/krb5-config.in: use @LIB_des_appl@ * tools/Makefile.am (krb5-config): add LIB_des_appl * configure.in (LIB_des): set correctly (LIB_des_appl): add for the use by krb5-config.in * lib/krb5/store_fd.c (fd_fetch, fd_store): use net_{read,write} to make sure of not dropping data when doing it over a socket. (this might break when used with ordinary files on win32) * lib/hdb/hdb_err.et (NO_MKEY): add * kdc/kerberos5.c (as_rep): be paranoid and check krb5_enctype_to_string for failure, noted by * lib/krb5/krb5_init_context.3, lib/krb5/krb5_context.3, lib/krb5/krb5_auth_context.3: add new man pages, contributed by * use the openssl api for md4/md5/sha and handle openssl/*.h * kdc/kaserver.c (do_getticket): check length of ticket. noted by 2001-01-28 Assar Westerlund * configure.in: send -R instead of -rpath to libtool to set runtime library paths * lib/krb5/Makefile.am: remove all dependencies on libkrb 2001-01-27 Assar Westerlund * appl/rcp: add port of bsd rcp changed to use existing rsh, contributed by Richard Nyberg 2001-01-27 Johan Danielsson * lib/krb5/get_port.c: don't warn if the port name can't be found, nobody cares anyway 2001-01-26 Johan Danielsson * kdc/hprop.c: make it possible to convert a v4 dump file without having any v4 libraries; the kdb backend still require them * kdc/v4_dump.c: include shadow definition of kdb Principal, so we don't have to depend on any v4 libraries * kdc/hprop.h: include shadow definition of kdb Principal, so we don't have to depend on any v4 libraries * lib/hdb/print.c: reduce number of memory allocations * lib/hdb/mkey.c: add support for reading krb4 /.k files 2001-01-19 Assar Westerlund * lib/krb5/krb5.conf.5: document admin_server and kpasswd_server for realms document capath better * lib/krb5/krbhst.c (krb5_get_krb_changepw_hst): preferably look at kpasswd_server before admin_server * lib/krb5/get_cred.c (get_cred_from_kdc_flags): look in [libdefaults]capath for better hint of realm to send request to. this allows the client to specify `realm routing information' in case it cannot be done at the server (which is preferred) * lib/krb5/rd_priv.c (krb5_rd_priv): handle no sequence number as zero when we were expecting a sequence number. MIT krb5 cannot generate a sequence number of zero, instead generating no sequence number * lib/krb5/rd_safe.c (krb5_rd_safe): dito 2001-01-11 Assar Westerlund * kpasswd/kpasswdd.c: add --port option 2001-01-10 Assar Westerlund * lib/krb5/appdefault.c (krb5_appdefault_string): fix condition just before returning 2001-01-09 Assar Westerlund * appl/kf/kfd.c (proto): use krb5_rd_cred2 instead of krb5_rd_cred 2001-01-05 Johan Danielsson * kuser/kinit.c: call a time `time', and not `seconds' * lib/krb5/init_creds.c: not much point in setting the anonymous flag here * lib/krb5/krb5_appdefault.3: document appdefault_time 2001-01-04 Johan Danielsson * lib/krb5/verify_user.c: use krb5_get_init_creds_opt_set_default_flags * kuser/kinit.c: use krb5_get_init_creds_opt_set_default_flags * lib/krb5/init_creds.c: new function krb5_get_init_creds_opt_set_default_flags to set options from krb5.conf * lib/krb5/rd_cred.c: make this match the MIT function * lib/krb5/appdefault.c (krb5_appdefault_string): handle NULL def_val (krb5_appdefault_time): new function 2001-01-03 Assar Westerlund * kdc/hpropd.c (main): handle EOF when reading from stdin heimdal-7.5.0/autogen.sh0000755000175000017500000000064513026237312013257 0ustar niknik#!/bin/sh # to really generate all files you need to run "make distcheck" in a # object tree, but this will do if you have all parts of the required # tool-chain installed set -e autoreconf -f -i || { echo "autoreconf failed: $?"; exit 1; } find . \( -name '*-private.h' -o -name '*-protos.h' \) | xargs rm -f perl -MJSON -e 'print foo;' || \ { echo "you must install JSON perl module (cpan install JSON)"; exit 1; } heimdal-7.5.0/ChangeLog.20000000644000175000017500000012145012136107746013416 0ustar niknik2000-12-31 Assar Westerlund * lib/krb5/test_get_addrs.c (main): handle krb5_init_context failure consistently * lib/krb5/string-to-key-test.c (main): handle krb5_init_context failure consistently * lib/krb5/prog_setup.c (krb5_program_setup): handle krb5_init_context failure consistently * lib/hdb/convert_db.c (main): handle krb5_init_context failure consistently * kuser/kverify.c (main): handle krb5_init_context failure consistently * kuser/klist.c (main): handle krb5_init_context failure consistently * kuser/kinit.c (main): handle krb5_init_context failure consistently * kuser/kgetcred.c (main): handle krb5_init_context failure consistently * kuser/kdestroy.c (main): handle krb5_init_context failure consistently * kuser/kdecode_ticket.c (main): handle krb5_init_context failure consistently * kuser/generate-requests.c (generate_requests): handle krb5_init_context failure consistently * kpasswd/kpasswd.c (main): handle krb5_init_context failure consistently * kpasswd/kpasswd-generator.c (generate_requests): handle krb5_init_context failure consistently * kdc/main.c (main): handle krb5_init_context failure consistently * appl/test/uu_client.c (proto): handle krb5_init_context failure consistently * appl/kf/kf.c (main): handle krb5_init_context failure consistently * admin/ktutil.c (main): handle krb5_init_context failure consistently * admin/get.c (kt_get): more error checking 2000-12-29 Assar Westerlund * lib/asn1/asn1_print.c (loop): check for length longer than data. inspired by lha@stacken.kth.se 2000-12-16 Johan Danielsson * admin/ktutil.8: reflect recent changes * admin/copy.c: don't copy an entry that already exists in the keytab, and warn if the keyblock differs 2000-12-15 Johan Danielsson * admin/Makefile.am: merge srvconvert and srvcreate with copy * admin/copy.c: merge srvconvert and srvcreate with copy * lib/krb5/Makefile.am: always build keytab_krb4.c * lib/krb5/context.c: always register the krb4 keytab functions * lib/krb5/krb5.h: declare krb4_ftk_ops * lib/krb5/keytab_krb4.c: We don't really need to include krb.h here, since we only use the principal size macros, so define these here. Theoretically someone could have a krb4 system where these values are != 40, but this is unlikely, and krb5_524_conv_principal also assume they are 40. 2000-12-13 Johan Danielsson * lib/krb5/krb5.h: s/krb5_donot_reply/krb5_donot_replay/ * lib/krb5/replay.c: fix query-replace-o from MD5 API change, and the struct is called krb5_donot_replay 2000-12-12 Assar Westerlund * admin/srvconvert.c (srvconvert): do not use data after free:ing it 2000-12-11 Assar Westerlund * Release 0.3d 2000-12-11 Assar Westerlund * lib/krb5/Makefile.am (libkrb5_la_LDFLAGS): set version to 14:0:0 * lib/hdb/Makefile.am (libhdb_la_LDFLAGS): update to 6:3:0 * lib/krb5/Makefile.am (libkrb5_la_LIBADD): add library dependencies 2000-12-10 Johan Danielsson * lib/krb5/auth_context.c: implement krb5_auth_con_{get,set}rcache 2000-12-08 Assar Westerlund * lib/krb5/krb5.h (krb5_enctype): add ETYPE_DES3_CBC_NONE_IVEC as a new pseudo-type * lib/krb5/crypto.c (DES_AFS3_CMU_string_to_key): always treat cell names as lower case (krb5_encrypt_ivec, krb5_decrypt_ivec): new functions that allow an explicit ivec to be specified. fix all sub-functions. (DES3_CBC_encrypt_ivec): new function that takes an explicit ivec 2000-12-06 Johan Danielsson * lib/krb5/Makefile.am: actually build replay cache code * lib/krb5/replay.c: implement krb5_get_server_rcache * kpasswd/kpasswdd.c: de-pointerise auth_context parameter to krb5_mk_rep * lib/krb5/recvauth.c: de-pointerise auth_context parameter to krb5_mk_rep * lib/krb5/mk_rep.c: auth_context should not be a pointer * lib/krb5/auth_context.c: implement krb5_auth_con_genaddrs, and make setaddrs_from_fd use that * lib/krb5/krb5.h: add some more KRB5_AUTH_CONTEXT_* flags 2000-12-05 Johan Danielsson * lib/krb5/Makefile.am: add kerberos.8 manpage * lib/krb5/cache.c: check for NULL remove_cred function * lib/krb5/fcache.c: pretend that empty files are non-existant * lib/krb5/get_addrs.c (find_all_addresses): use getifaddrs, from Jason Thorpe 2000-12-01 Assar Westerlund * configure.in: remove configure-time generation of krb5-config * tools/Makefile.am: add generation of krb5-config at make-time instead of configure-time * tools/krb5-config.in: add --prefix and --exec-prefix 2000-11-30 Assar Westerlund * tools/Makefile.am: add krb5-config.1 * tools/krb5-config.in: add kadm-client and kadm5-server as libraries 2000-11-29 Assar Westerlund * tools/krb5-config.in: add --prefix, --exec-prefix and gssapi 2000-11-29 Johan Danielsson * configure.in: add roken/Makefile here, since it can't live in rk_ROKEN 2000-11-16 Assar Westerlund * configure.in: use the libtool -rpath, do not rely on ld understanding -rpath * configure.in: fix the -Wl stuff for krb4 linking add some gratuitous extra options when linking with an existing libdes 2000-11-15 Assar Westerlund * lib/hdb/hdb.c (hdb_next_enctype2key): const-ize a little bit * lib/Makefile.am (SUBDIRS): try to only build des when needed * kuser/klist.c: print key versions numbers of v4 tickets in verbose mode * kdc/kerberos5.c (tgs_rep2): adapt to new krb5_verify_ap_req2 * appl/test/gss_common.c (read_token): remove unused variable * configure.in (krb4): add -Wl (MD4Init et al): look for these in more libraries (getmsg): only run test if we have the function (AC_OUTPUT): create tools/krb5-config * tools/krb5-config.in: new script for storing flags to use * Makefile.am (SUBDIRS): add tools * lib/krb5/get_cred.c (make_pa_tgs_req): update to new krb5_mk_req_internal * lib/krb5/mk_req_ext.c (krb5_mk_req_internal): allow different usages for the encryption. change callers * lib/krb5/rd_req.c (decrypt_authenticator): add an encryption `usage'. also try the old (and wrong) usage of KRB5_KU_AP_REQ_AUTH for backwards compatibility (krb5_verify_ap_req2): new function for specifying the usage different from the default (KRB5_KU_AP_REQ_AUTH) * lib/krb5/build_auth.c (krb5_build_authenticator): add a `usage' parameter to permit the generation of authenticators with different crypto usage * lib/krb5/mk_req.c (krb5_mk_req_exact): new function that takes a krb5_principal (krb5_mk_req): use krb5_mk_req_exact * lib/krb5/mcache.c (mcc_close): free data (mcc_destroy): don't free data 2000-11-13 Assar Westerlund * lib/hdb/ndbm.c: handle both ndbm.h and gdbm/ndbm.h * lib/hdb/hdb.c: handle both ndbm.h and gdbm/ndbm.h 2000-11-12 Johan Danielsson * kdc/hpropd.8: remove extra .Xc 2000-10-27 Johan Danielsson * kuser/kinit.c: fix v4 fallback lifetime calculation 2000-10-10 Johan Danielsson * kdc/524.c: fix log messge 2000-10-08 Assar Westerlund * lib/krb5/changepw.c (krb5_change_password): check for fd's being too large to select on * kpasswd/kpasswdd.c (add_new_tcp): check for the socket fd being too large to select on * kdc/connect.c (add_new_tcp): check for the socket fd being too large to selct on * kdc/connect.c (loop): check that the socket fd is not too large to select on * lib/krb5/send_to_kdc.c (recv_loop): check `fd' for being too large to be able to select on * kdc/kaserver.c (do_authenticate): check for time skew 2000-10-01 Assar Westerlund * kdc/524.c (set_address): allocate memory for storing addresses in if the original request had an empty set of addresses * kdc/524.c (set_address): fix bad return of pointer to automatic data * config.sub: update to version 2000-09-11 (aka 1.181) from subversions.gnu.org * config.guess: update to version 2000-09-05 (aka 1.156) from subversions.gnu.org plus some minor tweaks 2000-09-20 Assar Westerlund * Release 0.3c 2000-09-19 Assar Westerlund * lib/krb5/Makefile.am (libkrb5_la_LDFLAGS): bump version to 13:1:0 * lib/hdb/Makefile.am (libhdb_la_LDFLAGS): bump version to 6:2:0 2000-09-17 Assar Westerlund * lib/krb5/rd_req.c (krb5_decrypt_ticket): plug some memory leak (krb5_rd_req): try not to return an allocated auth_context on error * lib/krb5/log.c (krb5_vlog_msg): fix const-ness 2000-09-10 Assar Westerlund * kdc/524.c: re-organize * kdc/kerberos5.c (tgs_rep2): try to avoid leaking auth_context * kdc/kerberos4.c (valid_princ): check return value of functions (encode_v4_ticket): add some const * kdc/misc.c (db_fetch): check malloc (free_ent): new function * lib/krb5/log.c (krb5_vlog_msg): log just the format string it we fail to allocate the actual string to log, should at least provide some hint as to where things went wrong 2000-09-10 Johan Danielsson * kdc/log.c: use DEFAULT_LOG_DEST * kdc/config.c: use _PATH_KDC_CONF * kdc/kdc_locl.h: add macro constants for kdc.conf, and kdc.log 2000-09-09 Assar Westerlund * lib/krb5/crypto.c (_key_schedule): re-use an existing schedule 2000-09-06 Johan Danielsson * configure.in: fix dpagaix test 2000-09-05 Assar Westerlund * configure.in: with_dce -> enable_dce. noticed by Ake Sandgren 2000-09-01 Johan Danielsson * kdc/kstash.8: update manual page * kdc/kstash.c: fix typo, and remove unused option * lib/krb5/kerberos.7: short kerberos intro page 2000-08-27 Assar Westerlund * include/bits.c: add __attribute__ for gcc's pleasure * lib/hdb/keytab.c: re-write to delay the opening of the database till it's known which principal is being sought, thereby allowing the usage of multiple databases, however they need to be specified in /etc/krb5.conf since all the programs using this keytab do not read kdc.conf * appl/test/test_locl.h (keytab): add * appl/test/common.c: add --keytab * lib/krb5/crypto.c: remove trailing commas (KRB5_KU_USAGE_SEQ): renamed from KRB5_KU_USAGE_MIC 2000-08-26 Assar Westerlund * lib/krb5/send_to_kdc.c (send_via_proxy): handle `http://' at the beginning of the proxy specification. use getaddrinfo correctly (krb5_sendto): always return a return code * lib/krb5/krb5.h (KRB5_KU_USAGE_MIC): rename to KRB5_KU_USAGE_SEQ * lib/krb5/auth_context.c (krb5_auth_con_free): handle auth_context == NULL 2000-08-23 Assar Westerlund * kdc/kerberos5.c (find_type): make sure of always setting `ret_etype' correctly. clean-up structure some 2000-08-23 Johan Danielsson * lib/krb5/mcache.c: implement resolve 2000-08-18 Assar Westerlund * kuser/kdecode_ticket.c: check return value from krb5_crypto_init * kdc/kerberos5.c, kdc/524.c: check return value from krb5_crypto_init * lib/krb5/*.c: check return value from krb5_crypto_init 2000-08-16 Assar Westerlund * Release 0.3b 2000-08-16 Assar Westerlund * lib/krb5/Makefile.am: bump version to 13:0:0 * lib/hdb/Makefile.am: set version to 6:1:0 * configure.in: do getmsg testing the same way as in krb4 * lib/krb5/config_file.c (krb5_config_parse_file_debug): make sure of closing the file on error * lib/krb5/crypto.c (encrypt_internal_derived): free the checksum after use * lib/krb5/warn.c (_warnerr): initialize args to make third, purify et al happy 2000-08-13 Assar Westerlund * kdc/kerberos5.c: re-write search for keys code. loop over all supported enctypes in order, looping over all keys of each type, and picking the one with the v5 default salt preferably 2000-08-10 Assar Westerlund * appl/test/gss_common.c (enet_read): add and use * lib/krb5/krb5.h (heimdal_version, heimdal_long_version): make const * lib/krb5/mk_req_ext.c (krb5_mk_req_internal): add comment on checksum type selection * lib/krb5/context.c (krb5_init_context): do not leak memory on failure (default_etypes): prefer arcfour-hmac-md5 to des-cbc-md5 * lib/krb5/principal.c: add fnmatch.h 2000-08-09 Assar Westerlund * configure.in: call AC_PROG_CC and AC_PROG_CPP to make sure later checks that should require them don't fail * acconfig.h: add HAVE_UINT17_T 2000-08-09 Johan Danielsson * kdc/mit_dump.c: handle all sorts of weird MIT salt types 2000-08-08 Johan Danielsson * doc/setup.texi: port 212 -> 2121 * lib/krb5/principal.c: krb5_principal_match 2000-08-04 Johan Danielsson * lib/asn1/der_get.c: add comment on *why* DCE sometimes used BER encoding * kpasswd/Makefile.am: link with pidfile library * kpasswd/kpasswdd.c: write a pid file * kpasswd/kpasswd_locl.h: util.h * kdc/Makefile.am: link with pidfile library * kdc/main.c: write a pid file * kdc/headers.h: util.h 2000-08-04 Assar Westerlund * lib/krb5/principal.c (krb5_425_conv_principal_ext): always put hostnames in lower case (default_v4_name_convert): add imap 2000-08-03 Assar Westerlund * lib/krb5/crc.c (_krb5_crc_update): const-ize (finally) 2000-07-31 Johan Danielsson * configure.in: check for uint*_t * include/bits.c: define uint*_t 2000-07-29 Assar Westerlund * kdc/kerberos5.c (check_tgs_flags): set endtime correctly when renewing, From Derrick J Brashear 2000-07-28 Assar Westerlund * Release 0.3a 2000-07-27 Assar Westerlund * kdc/hprop.c (dump_database): write an empty message to signal end of dump 2000-07-26 Assar Westerlund * lib/krb5/changepw.c (krb5_change_password): try to be more careful when not to resend * lib/hdb/db3.c: always create a cursor with db3. From Derrick J Brashear 2000-07-25 Johan Danielsson * lib/hdb/Makefile.am: bump version to 6:0:0 * lib/asn1/Makefile.am: bump version to 3:0:1 * lib/krb5/Makefile.am: bump version to 12:0:1 * lib/krb5/krb5_config.3: manpage * lib/krb5/krb5_appdefault.3: manpage * lib/krb5/appdefault.c: implementation of the krb5_appdefault set of functions 2000-07-23 Assar Westerlund * lib/krb5/init_creds_pw.c (change_password): reset forwardable and proxiable. copy preauthentication list correctly from supplied options * kdc/hpropd.c (main): check that the ticket was for `hprop/' for paranoid reasons * lib/krb5/sock_principal.c (krb5_sock_to_principal): look in aliases for the real name 2000-07-22 Johan Danielsson * doc/setup.texi: say something about starting kadmind from the command line 2000-07-22 Assar Westerlund * kpasswd/kpasswdd.c: use kadm5_s_chpass_principal_cond instead of mis-doing it here * lib/krb5/changepw.c (krb5_change_password): make timeout 1 + 2^{0,1,...}. also keep track if we got an old packet back and then just wait without sending a new packet * lib/krb5/changepw.c: use a datagram socket and remove the sequence numbers * lib/krb5/changepw.c (krb5_change_password): clarify an expression, avoiding a warning 2000-07-22 Johan Danielsson * kuser/klist.c: make -a and -n aliases for -v * lib/krb5/write_message.c: ws * kdc/hprop-common.c: nuke extra definitions of krb5_read_priv_message et.al * lib/krb5/read_message.c (krb5_read_message): return error if EOF 2000-07-20 Assar Westerlund * kpasswd/kpasswd.c: print usage consistently * kdc/hprop.h (HPROP_KEYTAB): use HDB for the keytab * kdc/hpropd.c: add --keytab * kdc/hpropd.c: don't care what principal we recvauth as * lib/krb5/get_cred.c: be more careful of not returning creds at all when an error is returned * lib/krb5/fcache.c (fcc_gen_new): do mkstemp correctly 2000-07-19 Johan Danielsson * fix-export: use autoreconf * configure.in: remove stuff that belong in roken, and remove some obsolete constructs 2000-07-18 Johan Danielsson * configure.in: fix some typos * appl/Makefile.am: dceutil*s* * missing: update to missing from automake 1.4a 2000-07-17 Johan Danielsson * configure.in: try to get xlc flags from ibmcxx.cfg use conditional for X use readline cf macro * configure.in: subst AIX compiler flags 2000-07-15 Johan Danielsson * configure.in: pass sixth parameter to test-package; use some newer autoconf constructs * ltmain.sh: update to libtool 1.3c * ltconfig: update to libtool 1.3c * configure.in: update this to newer auto*/libtool * appl/Makefile.am: use conditional for dce * lib/Makefile.am: use conditional for dce 2000-07-11 Johan Danielsson * lib/krb5/write_message.c: krb5_write_{priv,save}_message * lib/krb5/read_message.c: krb5_read_{priv,save}_message * lib/krb5/convert_creds.c: try port kerberos/88 if no response on krb524/4444 * lib/krb5/convert_creds.c: use krb5_sendto * lib/krb5/send_to_kdc.c: add more generic krb5_sendto that send to a port at arbitrary list of hosts 2000-07-10 Johan Danielsson * doc/misc.texi: language; say something about kadmin del_enctype 2000-07-10 Assar Westerlund * appl/kf/Makefile.am: actually install 2000-07-08 Assar Westerlund * configure.in (AM_INIT_AUTOMAKE): bump to 0.3a-pre (AC_ROKEN): roken is now at 10 * lib/krb5/string-to-key-test.c: add a arcfour-hmac-md5 test case * kdc/Makefile.am (INCLUDES): add ../lib/krb5 * configure.in: update for standalone roken * lib/Makefile.am (SUBDIRS): make roken conditional * kdc/hprop.c: update to new hdb_seal_keys_mkey * lib/hdb/mkey.c (_hdb_unseal_keys_int, _hdb_seal_keys_int): rename and export them * kdc/headers.h: add krb5_locl.h (since we just use some stuff from there) 2000-07-08 Johan Danielsson * kuser/klist.1: update for -f and add some more text for -v * kuser/klist.c: use rtbl to format cred listing, add -f and -s * lib/krb5/crypto.c: fix type in des3-cbc-none * lib/hdb/mkey.c: add key usage * kdc/kstash.c: remove writing of old keyfile, and treat --convert-file as just reading and writing the keyfile without asking for a new key * lib/hdb/mkey.c (read_master_encryptionkey): handle old keytype based files, and convert the key to cfb64 * lib/hdb/mkey.c (hdb_read_master_key): set mkey to NULL before doing anything else * lib/krb5/send_to_kdc.c: use krb5_eai_to_heim_errno * lib/krb5/get_for_creds.c: use krb5_eai_to_heim_errno * lib/krb5/changepw.c: use krb5_eai_to_heim_errno * lib/krb5/addr_families.c: use krb5_eai_to_heim_errno * lib/krb5/eai_to_heim_errno.c: convert getaddrinfo error codes to something that can be passed to get_err_text 2000-07-07 Assar Westerlund * lib/hdb/hdb.c (hdb_next_enctype2key): make sure of skipping `*key' * kdc/kerberos4.c (get_des_key): rewrite some, be more careful 2000-07-06 Assar Westerlund * kdc/kerberos5.c (as_rep): be careful as to now overflowing when calculating the end of lifetime of a ticket. * lib/krb5/context.c (default_etypes): add ETYPE_ARCFOUR_HMAC_MD5 * lib/hdb/db3.c: only use a cursor when needed, from Derrick J Brashear * lib/krb5/crypto.c: introduce the `special' encryption methods that are not like all other encryption methods and implement arcfour-hmac-md5 2000-07-05 Johan Danielsson * kdc/mit_dump.c: set initial master key version number to 0 instead of 1; if we lated bump the mkvno we don't risk using the wrong key to decrypt * kdc/hprop.c: only get master key if we're actually going to use it; enable reading of MIT krb5 dump files * kdc/mit_dump.c: read MIT krb5 dump files * lib/hdb/mkey.c (read_master_mit): fix this * kdc/kstash.c: make this work with the new mkey code * lib/hdb/Makefile.am: add mkey.c, and bump version number * lib/hdb/hdb.h: rewrite master key handling * lib/hdb/mkey.c: rewrite master key handling * lib/krb5/crypto.c: add some more pseudo crypto types * lib/krb5/krb5.h: change some funny etypes to use negative numbers, and add some more 2000-07-04 Assar Westerlund * lib/krb5/krbhst.c (get_krbhst): only try SRV lookup if there are none in the configuration file 2000-07-02 Assar Westerlund * lib/krb5/keytab_keyfile.c (akf_add_entry): remove unused variable * kpasswd/kpasswd-generator.c: new test program * kpasswd/Makefile.am: add kpasswd-generator * include/Makefile.am (CLEANFILES): add rc4.h * kuser/generate-requests.c: new test program * kuser/Makefile.am (noinst_PROGRAMS): add generate-requests 2000-07-01 Assar Westerlund * configure.in: add --enable-dce and related stuff * appl/Makefile.am (SUBDIRS): add $(APPL_dce) 2000-06-29 Assar Westerlund * kdc/kerberos4.c (get_des_key): fix thinkos/typos 2000-06-29 Johan Danielsson * admin/purge.c: use parse_time to parse age * lib/krb5/log.c (krb5_vlog_msg): use krb5_format_time * admin/list.c: add printing of timestamp and key data; some cleanup * lib/krb5/time.c (krb5_format_time): new function to format time * lib/krb5/context.c (init_context_from_config_file): init date_fmt, also do some cleanup * lib/krb5/krb5.h: add date_fmt to context 2000-06-28 Johan Danielsson * kdc/{kerberos4,kaserver,524}.c (get_des_key): change to return v4 or afs keys if possible 2000-06-25 Johan Danielsson * kdc/hprop.c (ka_convert): allow using null salt, and treat 0 pw_expire as never (from Derrick Brashear) 2000-06-24 Johan Danielsson * kdc/connect.c (add_standard_ports): only listen to port 750 if serving v4 requests 2000-06-22 Assar Westerlund * lib/asn1/lex.l: fix includes, and lex stuff * lib/asn1/lex.h (error_message): update prototype (yylex): add * lib/asn1/gen_length.c (length_type): fail on malloc error * lib/asn1/gen_decode.c (decode_type): fail on malloc error 2000-06-21 Assar Westerlund * lib/krb5/get_for_creds.c: be more compatible with MIT code. From Daniel Kouril * lib/krb5/rd_cred.c: be more compatible with MIT code. From Daniel Kouril * kdc/kerberos5.c (get_pa_etype_info): do not set salttype if it's vanilla pw-salt, that keeps win2k happy. also do the malloc check correctly. From Daniel Kouril 2000-06-21 Johan Danielsson * kdc/hprop.c: add hdb keytabs 2000-06-20 Johan Danielsson * lib/krb5/principal.c: back out rev. 1.64 2000-06-19 Johan Danielsson * kdc/kerberos5.c: pa_* -> KRB5_PADATA_* * kdc/hpropd.c: add realm override flag * kdc/v4_dump.c: code for reading krb4 dump files * kdc/hprop.c: generalize source database handing, add support for non-standard local realms (from by Daniel Kouril and Miroslav Ruda ), and support for using different ports (requested by the Czechs, but implemented differently) * lib/krb5/get_cred.c: pa_* -> KRB5_PADATA_* * lib/krb5/get_in_tkt.c: pa_* -> KRB5_PADATA_* * lib/krb5/krb5.h: use some definitions from asn1.h * lib/hdb/hdb.asn1: use new import syntax * lib/asn1/k5.asn1: use distinguished value integers * lib/asn1/gen_length.c: support for distinguished value integers * lib/asn1/gen_encode.c: support for distinguished value integers * lib/asn1/gen_decode.c: support for distinguished value integers * lib/asn1/gen.c: support for distinguished value integers * lib/asn1/lex.l: add support for more standards like import statements * lib/asn1/parse.y: add support for more standards like import statements, and distinguished value integers 2000-06-11 Assar Westerlund * lib/krb5/get_for_creds.c (add_addrs): ignore addresses of unknown type * lib/krb5/get_for_creds.c (add_addrs): zero memory before starting to copy memory 2000-06-10 Assar Westerlund * lib/krb5/test_get_addrs.c: test program for get_addrs * lib/krb5/get_addrs.c (find_all_addresses): remember to add in the size of ifr->ifr_name when using SA_LEN. noticed by Ken Raeburn 2000-06-07 Assar Westerlund * configure.in: add db3 detection stuff do not use streamsptys on HP-UX 11 * lib/hdb/hdb.h (HDB): add dbc for db3 * kdc/connect.c (add_standard_ports): also listen on krb524 aka 4444 * etc/services.append (krb524): add * lib/hdb/db3.c: add berkeley db3 interface. contributed by Derrick J Brashear * lib/hdb/hdb.h (struct HDB): add 2000-06-07 Johan Danielsson * kdc/524.c: if 524 is not enabled, just generate error reply and exit * kdc/kerberos4.c: if v4 is not enabled, just generate error reply and exit * kdc/connect.c: only listen to port 4444 if 524 is enabled * kdc/config.c: add options to enable/disable v4 and 524 requests 2000-06-06 Johan Danielsson * kdc/524.c: handle non-existant server principals (from Daniel Kouril) 2000-06-03 Assar Westerlund * admin/ktutil.c: print name when failing to open keytab * kuser/kinit.c: try also to fallback to v4 when no KDC is found 2000-05-28 Assar Westerlund * kuser/klist.c: continue even we have no v5 ccache. make showing your krb4 tickets the default (if build with krb4 support) * kuser/kinit.c: add a fallback that tries to get a v4 ticket if built with krb4 support and we got back a version error from the KDC 2000-05-23 Johan Danielsson * lib/krb5/keytab_keyfile.c: make this actually work 2000-05-19 Assar Westerlund * lib/krb5/store_emem.c (emem_store): make it write-compatible * lib/krb5/store_fd.c (fd_store): make it write-compatible * lib/krb5/store_mem.c (mem_store): make it write-compatible * lib/krb5/krb5.h (krb5_storage): make store write-compatible 2000-05-18 Assar Westerlund * configure.in: add stdio.h in dbopen test 2000-05-16 Assar Westerlund * Release 0.2t 2000-05-16 Assar Westerlund * lib/krb5/Makefile.am (libkrb5_la_LDFLAGS): set version to 11:1:0 * lib/krb5/fcache.c: fix second lseek * lib/krb5/principal.c (krb5_524_conv_principal): fix typo 2000-05-15 Assar Westerlund * Release 0.2s 2000-05-15 Assar Westerlund * lib/krb5/Makefile.am (libkrb5_la_LDFLAGS): set version to 11:0:0 * lib/hdb/Makefile.am (libhdb_la_LDFLAGS): set version to 4:2:1 * lib/asn1/Makefile.am (libasn1_la_LDFLAGS): bump to 2:0:0 * lib/krb5/principal.c (krb5_524_conv_principal): comment-ize, and simplify string copying 2000-05-12 Assar Westerlund * lib/krb5/fcache.c (scrub_file): new function (erase_file): re-write, use scrub_file * lib/krb5/krb5.h (KRB5_DEFAULT_CCFILE_ROOT): add * configure.in (dbopen): add header files * lib/krb5/krb5.h (krb5_key_usage): add some more * lib/krb5/fcache.c (erase_file): try to detect symlink games. also call revoke. * lib/krb5/changepw.c (krb5_change_password): remember to close the socket on error * kdc/main.c (main): also call sigterm on SIGTERM 2000-05-06 Assar Westerlund * lib/krb5/config_file.c (krb5_config_vget_string_default, krb5_config_get_string_default): add 2000-04-25 Assar Westerlund * lib/krb5/fcache.c (fcc_initialize): just forget about over-writing the old cred cache. it's too much of a hazzle trying to do this safely. 2000-04-11 Assar Westerlund * lib/krb5/crypto.c (krb5_get_wrapped_length): rewrite into different parts for the derived and non-derived cases * lib/krb5/crypto.c (krb5_get_wrapped_length): the padding should be done after having added confounder and checksum 2000-04-09 Assar Westerlund * lib/krb5/get_addrs.c (find_all_addresses): apperently solaris can return EINVAL when the buffer is too small. cope. * lib/asn1/Makefile.am (gen_files): add asn1_UNSIGNED.x * lib/asn1/gen_locl.h (filename): add prototype (init_generate): const-ize * lib/asn1/gen.c (filename): new function clean-up a little bit. * lib/asn1/parse.y: be more tolerant in ranges * lib/asn1/lex.l: count lines correctly. (error_message): print filename in messages 2000-04-08 Assar Westerlund * lib/krb5/rd_safe.c (krb5_rd_safe): increment sequence number after comparing * lib/krb5/rd_priv.c (krb5_rd_priv): increment sequence number after comparing * lib/krb5/mk_safe.c (krb5_mk_safe): make `tmp_seq' unsigned * lib/krb5/mk_priv.c (krb5_mk_priv): make `tmp_seq' unsigned * lib/krb5/generate_seq_number.c (krb5_generate_seq_number): make `seqno' be unsigned * lib/krb5/mk_safe.c (krb5_mk_safe): increment local sequence number after the fact and only increment it if we were successful * lib/krb5/mk_priv.c (krb5_mk_priv): increment local sequence number after the fact and only increment it if we were successful * lib/krb5/krb5.h (krb5_auth_context_data): make sequence number unsigned * lib/krb5/init_creds_pw.c (krb5_get_init_creds_password): `in_tkt_service' can be NULL 2000-04-06 Assar Westerlund * lib/asn1/parse.y: regonize INTEGER (0..UNIT_MAX). (DOTDOT): add * lib/asn1/lex.l (DOTDOT): add * lib/asn1/k5.asn1 (UNSIGNED): add. use UNSIGNED for all sequence numbers. * lib/asn1/gen_length.c (length_type): add TUInteger * lib/asn1/gen_free.c (free_type): add TUInteger * lib/asn1/gen_encode.c (encode_type, generate_type_encode): add TUInteger * lib/asn1/gen_decode.c (decode_type, generate_type_decode): add TUInteger * lib/asn1/gen_copy.c (copy_type): add TUInteger * lib/asn1/gen.c (define_asn1): add TUInteger * lib/asn1/der_put.c (encode_unsigned): add * lib/asn1/der_length.c (length_unsigned): add * lib/asn1/der_get.c (decode_unsigned): add * lib/asn1/der.h (decode_unsigned, encode_unsigned, length_unsigned): add prototypes * lib/asn1/k5.asn1: update pre-authentication types * lib/krb5/krb5_err.et: add some error codes from pkinit 2000-04-05 Assar Westerlund * lib/hdb/hdb.c: add support for hdb methods (aka back-ends). include ldap. * lib/hdb/hdb-ldap.c: tweak the ifdef to OPENLDAP * lib/hdb/Makefile.am: add hdb-ldap.c and openldap * kdc/Makefile.am, kpasswd/Makefile.am, kadmin/Makefile.am: add * configure.in: bump version to 0.2s-pre add options and testing for (open)ldap 2000-04-04 Assar Westerlund * configure.in (krb4): fix the krb_mk_req test 2000-04-03 Assar Westerlund * configure.in (krb4): add test for const arguments to krb_mk_req * lib/45/mk_req.c (krb_mk_req): conditionalize const-ness of arguments 2000-04-03 Assar Westerlund * Release 0.2r 2000-04-03 Assar Westerlund * lib/krb5/Makefile.am: set version to 10:0:0 * lib/45/mk_req.c (krb_mk_req): const-ize the arguments 2000-03-30 Assar Westerlund * lib/krb5/principal.c (krb5_425_conv_principal_ext): add some comments. add fall-back on adding the realm name in lower case. 2000-03-29 Assar Westerlund * kdc/connect.c: remember to repoint all descr->sa to _ss after realloc as this might have moved the memory around. problem discovered and diagnosed by Brandon S. Allbery 2000-03-27 Assar Westerlund * configure.in: recognize solaris 2.8 * config.guess, config.sub: update to current version from :pserver:anoncvs@subversions.gnu.org:/home/cvs * lib/krb5/init_creds_pw.c (print_expire): do not assume anything about the size of time_t, i.e. make it 64-bit happy 2000-03-13 Assar Westerlund * kuser/klist.c: add support for display v4 tickets 2000-03-11 Assar Westerlund * kdc/kaserver.c (do_authenticate, do_getticket): call check_flags * kdc/kerberos4.c (do_version4): call check_flags. * kdc/kerberos5.c (check_flags): make global 2000-03-10 Assar Westerlund * lib/krb5/init_creds_pw.c (krb5_get_init_creds_password): evil hack to avoid recursion 2000-03-04 Assar Westerlund * kuser/kinit.c: add `krb4_get_tickets' per realm. add --anonymous * lib/krb5/krb5.h (krb5_get_init_creds_opt): add `anonymous' and KRB5_GET_INIT_CREDS_OPT_ANONYMOUS * lib/krb5/init_creds_pw.c (get_init_creds_common): set request_anonymous flag appropriatly * lib/krb5/init_creds.c (krb5_get_init_creds_opt_set_anonymous): add * lib/krb5/get_in_tkt.c (_krb5_extract_ticket): new parameter to determine whetever to ignore client name of not. always copy client name from kdc. fix callers. * kdc: add support for anonymous tickets * kdc/string2key.8: add man-page for string2key 2000-03-03 Assar Westerlund * kdc/hpropd.c (dump_krb4): get expiration date from `valid_end' and not `pw_end' * kdc/kadb.h (ka_entry): fix name pw_end -> valid_end. add some more fields * kdc/hprop.c (v4_prop): set the `valid_end' from the v4 expiration date instead of the `pw_expire' (ka_convert): set `valid_end' from ka expiration data and `pw_expire' from pw_change + pw_expire (main): add a default database for ka dumping 2000-02-28 Assar Westerlund * lib/krb5/context.c (init_context_from_config_file): change rfc2052 default to no. 2782 says that underscore should be used. 2000-02-24 Assar Westerlund * lib/krb5/fcache.c (fcc_initialize, fcc_store_cred): verify that stores and close succeed * lib/krb5/store.c (krb5_store_creds): check to see that the stores are succesful. 2000-02-23 Assar Westerlund * Release 0.2q 2000-02-22 Assar Westerlund * lib/krb5/Makefile.am: set version to 9:2:0 * lib/krb5/expand_hostname.c (krb5_expand_hostname_realms): copy the correct hostname * kdc/connect.c (add_new_tcp): use the correct entries in the descriptor table * kdc/connect.c: initialize `descr' uniformly and correctly 2000-02-20 Assar Westerlund * Release 0.2p 2000-02-19 Assar Westerlund * lib/krb5/Makefile.am: set version to 9:1:0 * lib/krb5/expand_hostname.c (krb5_expand_hostname): make sure that realms is filled in even when getaddrinfo fails or does not return any canonical name * kdc/connect.c (descr): add sockaddr and string representation (*): re-write to use the above mentioned 2000-02-16 Assar Westerlund * lib/krb5/addr_families.c (krb5_parse_address): use krb5_sockaddr2address to copy the result from getaddrinfo. 2000-02-14 Assar Westerlund * Release 0.2o 2000-02-13 Assar Westerlund * lib/krb5/Makefile.am: set version to 9:0:0 * kdc/kaserver.c (do_authenticate): return the kvno of the server and not the client. Thanks to Brandon S. Allbery KF8NH and Chaskiel M Grundman for debugging. * kdc/kerberos4.c (do_version4): if an tgs-req is received with an old kvno, return an error reply and write a message in the log. 2000-02-12 Assar Westerlund * appl/test/gssapi_server.c (proto): with `--fork', create a child and send over/receive creds with export/import_sec_context * appl/test/gssapi_client.c (proto): with `--fork', create a child and send over/receive creds with export/import_sec_context * appl/test/common.c: add `--fork' / `-f' (only used by gssapi) 2000-02-11 Assar Westerlund * kdc/kdc_locl.h: remove keyfile add explicit_addresses * kdc/connect.c (init_sockets): pay attention to explicit_addresses some more comments. better error messages. * kdc/config.c: add some comments. remove --key-file. add --addresses. * lib/krb5/context.c (krb5_set_extra_addresses): const-ize and use proper abstraction 2000-02-07 Johan Danielsson * lib/krb5/changepw.c: use roken_getaddrinfo_hostspec 2000-02-07 Assar Westerlund * Release 0.2n 2000-02-07 Assar Westerlund * lib/krb5/Makefile.am: set version to 8:0:0 * lib/krb5/keytab.c (krb5_kt_default_name): use strlcpy (krb5_kt_add_entry): set timestamp 2000-02-06 Assar Westerlund * lib/krb5/krb5.h: add macros for accessing krb5_realm * lib/krb5/time.c (krb5_timeofday): use `krb5_timestamp' instead of `int32_t' * lib/krb5/replay.c (checksum_authenticator): update to new API for md5 * lib/krb5/krb5.h: remove des.h, it's not needed and applications should not have to make sure to find it. 2000-02-03 Assar Westerlund * lib/krb5/rd_req.c (get_key_from_keytab): rename parameter to `out_key' to avoid conflicting with label. reported by Sean Doran 2000-02-02 Assar Westerlund * lib/krb5/expand_hostname.c: remember to lower-case host names. bug reported by * kdc/kerberos4.c (do_version4): look at check_ticket_addresses and emulate that by setting krb_ignore_ip_address (not a great interface but it doesn't seem like the time to go around fixing libkrb stuff now) 2000-02-01 Johan Danielsson * kuser/kinit.c: change --noaddresses into --no-addresses 2000-01-28 Assar Westerlund * kpasswd/kpasswd.c (main): make sure the ticket is not forwardable and not proxiable 2000-01-26 Assar Westerlund * lib/krb5/crypto.c: update to pseudo-standard APIs for md4,md5,sha. some changes to libdes calls to make them more portable. 2000-01-21 Assar Westerlund * lib/krb5/verify_init.c (krb5_verify_init_creds): make sure to clean up the correct creds. 2000-01-16 Assar Westerlund * lib/krb5/principal.c (append_component): change parameter to `const char *'. check malloc * lib/krb5/principal.c (append_component, va_ext_princ, va_princ): const-ize * lib/krb5/mk_req.c (krb5_mk_req): make `service' and `hostname' const * lib/krb5/principal.c (replace_chars): also add space here * lib/krb5/principal.c: (quotable_chars): add space 2000-01-12 Assar Westerlund * kdc/kerberos4.c (do_version4): check if preauth was required and bail-out if so since there's no way that could be done in v4. Return NULL_KEY as an error to the client (which is non-obvious, but what can you do?) 2000-01-09 Assar Westerlund * lib/krb5/principal.c (krb5_sname_to_principal): use krb5_expand_hostname_realms * lib/krb5/mk_req.c (krb5_km_req): use krb5_expand_hostname_realms * lib/krb5/expand_hostname.c (krb5_expand_hostname_realms): new variant of krb5_expand_hostname that tries until it expands into something that's digestable by krb5_get_host_realm, returning also the result from that function. 2000-01-08 Assar Westerlund * Release 0.2m 2000-01-08 Assar Westerlund * configure.in: replace AC_C_BIGENDIAN with KRB_C_BIGENDIAN * lib/krb5/Makefile.am: bump version to 7:1:0 * lib/krb5/principal.c (krb5_sname_to_principal): use krb5_expand_hostname * lib/krb5/expand_hostname.c (krb5_expand_hostname): handle ai_canonname being set in any of the addresses returnedby getaddrinfo. glibc apparently returns the reverse lookup of every address in ai_canonname. 2000-01-06 Assar Westerlund * Release 0.2l 2000-01-06 Assar Westerlund * lib/krb5/Makefile.am: set version to 7:0:0 * lib/krb5/principal.c (krb5_sname_to_principal): remove `hp' * lib/hdb/Makefile.am: set version to 4:1:1 * kdc/hpropd.c (dump_krb4): use `krb5_get_default_realms' * lib/krb5/get_in_tkt.c (add_padata): change types to make everything work out (krb5_get_in_cred): remove const to make types match * lib/krb5/crypto.c (ARCFOUR_string_to_key): correct signature * lib/krb5/principal.c (krb5_sname_to_principal): handle not getting back a canonname 2000-01-06 Assar Westerlund * Release 0.2k 2000-01-06 Assar Westerlund * lib/krb5/send_to_kdc.c (krb5_sendto_kdc): advance colon so that we actually parse the port number. based on a patch from Leif Johansson 2000-01-02 Assar Westerlund * admin/purge.c: remove all non-current and old entries from a keytab * admin: break up ktutil.c into files * admin/ktutil.c (list): support --verbose (also listning time stamps) (kt_add, kt_get): set timestamp in newly created entries (kt_change): add `change' command * admin/srvconvert.c (srvconv): set timestamp in newly created entries * lib/krb5/keytab_keyfile.c (akf_next_entry): set timetsamp, always go the a predicatble position on error * lib/krb5/keytab.c (krb5_kt_copy_entry_contents): copy timestamp * lib/krb5/keytab_file.c (fkt_add_entry): store timestamp (fkt_next_entry_int): return timestamp * lib/krb5/krb5.h (krb5_keytab_entry): add timestamp heimdal-7.5.0/aclocal.m40000644000175000017500000013242413212444512013116 0ustar niknik# generated automatically by aclocal 1.15.1 -*- Autoconf -*- # Copyright (C) 1996-2017 Free Software Foundation, Inc. # This file is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, # with or without modifications, as long as this notice is preserved. # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY, to the extent permitted by law; without # even the implied warranty of MERCHANTABILITY or FITNESS FOR A # PARTICULAR PURPOSE. m4_ifndef([AC_CONFIG_MACRO_DIRS], [m4_defun([_AM_CONFIG_MACRO_DIRS], [])m4_defun([AC_CONFIG_MACRO_DIRS], [_AM_CONFIG_MACRO_DIRS($@)])]) m4_ifndef([AC_AUTOCONF_VERSION], [m4_copy([m4_PACKAGE_VERSION], [AC_AUTOCONF_VERSION])])dnl m4_if(m4_defn([AC_AUTOCONF_VERSION]), [2.69],, [m4_warning([this file was generated for autoconf 2.69. You have another version of autoconf. It may work, but is not guaranteed to. If you have problems, you may need to regenerate the build system entirely. To do so, use the procedure documented by the package, typically 'autoreconf'.])]) # Copyright (C) 2002-2017 Free Software Foundation, Inc. # # This file is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, # with or without modifications, as long as this notice is preserved. # AM_AUTOMAKE_VERSION(VERSION) # ---------------------------- # Automake X.Y traces this macro to ensure aclocal.m4 has been # generated from the m4 files accompanying Automake X.Y. # (This private macro should not be called outside this file.) AC_DEFUN([AM_AUTOMAKE_VERSION], [am__api_version='1.15' dnl Some users find AM_AUTOMAKE_VERSION and mistake it for a way to dnl require some minimum version. Point them to the right macro. m4_if([$1], [1.15.1], [], [AC_FATAL([Do not call $0, use AM_INIT_AUTOMAKE([$1]).])])dnl ]) # _AM_AUTOCONF_VERSION(VERSION) # ----------------------------- # aclocal traces this macro to find the Autoconf version. # This is a private macro too. Using m4_define simplifies # the logic in aclocal, which can simply ignore this definition. m4_define([_AM_AUTOCONF_VERSION], []) # AM_SET_CURRENT_AUTOMAKE_VERSION # ------------------------------- # Call AM_AUTOMAKE_VERSION and AM_AUTOMAKE_VERSION so they can be traced. # This function is AC_REQUIREd by AM_INIT_AUTOMAKE. AC_DEFUN([AM_SET_CURRENT_AUTOMAKE_VERSION], [AM_AUTOMAKE_VERSION([1.15.1])dnl m4_ifndef([AC_AUTOCONF_VERSION], [m4_copy([m4_PACKAGE_VERSION], [AC_AUTOCONF_VERSION])])dnl _AM_AUTOCONF_VERSION(m4_defn([AC_AUTOCONF_VERSION]))]) # AM_AUX_DIR_EXPAND -*- Autoconf -*- # Copyright (C) 2001-2017 Free Software Foundation, Inc. # # This file is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, # with or without modifications, as long as this notice is preserved. # For projects using AC_CONFIG_AUX_DIR([foo]), Autoconf sets # $ac_aux_dir to '$srcdir/foo'. In other projects, it is set to # '$srcdir', '$srcdir/..', or '$srcdir/../..'. # # Of course, Automake must honor this variable whenever it calls a # tool from the auxiliary directory. The problem is that $srcdir (and # therefore $ac_aux_dir as well) can be either absolute or relative, # depending on how configure is run. This is pretty annoying, since # it makes $ac_aux_dir quite unusable in subdirectories: in the top # source directory, any form will work fine, but in subdirectories a # relative path needs to be adjusted first. # # $ac_aux_dir/missing # fails when called from a subdirectory if $ac_aux_dir is relative # $top_srcdir/$ac_aux_dir/missing # fails if $ac_aux_dir is absolute, # fails when called from a subdirectory in a VPATH build with # a relative $ac_aux_dir # # The reason of the latter failure is that $top_srcdir and $ac_aux_dir # are both prefixed by $srcdir. In an in-source build this is usually # harmless because $srcdir is '.', but things will broke when you # start a VPATH build or use an absolute $srcdir. # # So we could use something similar to $top_srcdir/$ac_aux_dir/missing, # iff we strip the leading $srcdir from $ac_aux_dir. That would be: # am_aux_dir='\$(top_srcdir)/'`expr "$ac_aux_dir" : "$srcdir//*\(.*\)"` # and then we would define $MISSING as # MISSING="\${SHELL} $am_aux_dir/missing" # This will work as long as MISSING is not called from configure, because # unfortunately $(top_srcdir) has no meaning in configure. # However there are other variables, like CC, which are often used in # configure, and could therefore not use this "fixed" $ac_aux_dir. # # Another solution, used here, is to always expand $ac_aux_dir to an # absolute PATH. The drawback is that using absolute paths prevent a # configured tree to be moved without reconfiguration. AC_DEFUN([AM_AUX_DIR_EXPAND], [AC_REQUIRE([AC_CONFIG_AUX_DIR_DEFAULT])dnl # Expand $ac_aux_dir to an absolute path. am_aux_dir=`cd "$ac_aux_dir" && pwd` ]) # AM_CONDITIONAL -*- Autoconf -*- # Copyright (C) 1997-2017 Free Software Foundation, Inc. # # This file is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, # with or without modifications, as long as this notice is preserved. # AM_CONDITIONAL(NAME, SHELL-CONDITION) # ------------------------------------- # Define a conditional. AC_DEFUN([AM_CONDITIONAL], [AC_PREREQ([2.52])dnl m4_if([$1], [TRUE], [AC_FATAL([$0: invalid condition: $1])], [$1], [FALSE], [AC_FATAL([$0: invalid condition: $1])])dnl AC_SUBST([$1_TRUE])dnl AC_SUBST([$1_FALSE])dnl _AM_SUBST_NOTMAKE([$1_TRUE])dnl _AM_SUBST_NOTMAKE([$1_FALSE])dnl m4_define([_AM_COND_VALUE_$1], [$2])dnl if $2; then $1_TRUE= $1_FALSE='#' else $1_TRUE='#' $1_FALSE= fi AC_CONFIG_COMMANDS_PRE( [if test -z "${$1_TRUE}" && test -z "${$1_FALSE}"; then AC_MSG_ERROR([[conditional "$1" was never defined. Usually this means the macro was only invoked conditionally.]]) fi])]) # Copyright (C) 1999-2017 Free Software Foundation, Inc. # # This file is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, # with or without modifications, as long as this notice is preserved. # There are a few dirty hacks below to avoid letting 'AC_PROG_CC' be # written in clear, in which case automake, when reading aclocal.m4, # will think it sees a *use*, and therefore will trigger all it's # C support machinery. Also note that it means that autoscan, seeing # CC etc. in the Makefile, will ask for an AC_PROG_CC use... # _AM_DEPENDENCIES(NAME) # ---------------------- # See how the compiler implements dependency checking. # NAME is "CC", "CXX", "OBJC", "OBJCXX", "UPC", or "GJC". # We try a few techniques and use that to set a single cache variable. # # We don't AC_REQUIRE the corresponding AC_PROG_CC since the latter was # modified to invoke _AM_DEPENDENCIES(CC); we would have a circular # dependency, and given that the user is not expected to run this macro, # just rely on AC_PROG_CC. AC_DEFUN([_AM_DEPENDENCIES], [AC_REQUIRE([AM_SET_DEPDIR])dnl AC_REQUIRE([AM_OUTPUT_DEPENDENCY_COMMANDS])dnl AC_REQUIRE([AM_MAKE_INCLUDE])dnl AC_REQUIRE([AM_DEP_TRACK])dnl m4_if([$1], [CC], [depcc="$CC" am_compiler_list=], [$1], [CXX], [depcc="$CXX" am_compiler_list=], [$1], [OBJC], [depcc="$OBJC" am_compiler_list='gcc3 gcc'], [$1], [OBJCXX], [depcc="$OBJCXX" am_compiler_list='gcc3 gcc'], [$1], [UPC], [depcc="$UPC" am_compiler_list=], [$1], [GCJ], [depcc="$GCJ" am_compiler_list='gcc3 gcc'], [depcc="$$1" am_compiler_list=]) AC_CACHE_CHECK([dependency style of $depcc], [am_cv_$1_dependencies_compiler_type], [if test -z "$AMDEP_TRUE" && test -f "$am_depcomp"; then # We make a subdir and do the tests there. Otherwise we can end up # making bogus files that we don't know about and never remove. For # instance it was reported that on HP-UX the gcc test will end up # making a dummy file named 'D' -- because '-MD' means "put the output # in D". rm -rf conftest.dir mkdir conftest.dir # Copy depcomp to subdir because otherwise we won't find it if we're # using a relative directory. cp "$am_depcomp" conftest.dir cd conftest.dir # We will build objects and dependencies in a subdirectory because # it helps to detect inapplicable dependency modes. For instance # both Tru64's cc and ICC support -MD to output dependencies as a # side effect of compilation, but ICC will put the dependencies in # the current directory while Tru64 will put them in the object # directory. mkdir sub am_cv_$1_dependencies_compiler_type=none if test "$am_compiler_list" = ""; then am_compiler_list=`sed -n ['s/^#*\([a-zA-Z0-9]*\))$/\1/p'] < ./depcomp` fi am__universal=false m4_case([$1], [CC], [case " $depcc " in #( *\ -arch\ *\ -arch\ *) am__universal=true ;; esac], [CXX], [case " $depcc " in #( *\ -arch\ *\ -arch\ *) am__universal=true ;; esac]) for depmode in $am_compiler_list; do # Setup a source with many dependencies, because some compilers # like to wrap large dependency lists on column 80 (with \), and # we should not choose a depcomp mode which is confused by this. # # We need to recreate these files for each test, as the compiler may # overwrite some of them when testing with obscure command lines. # This happens at least with the AIX C compiler. : > sub/conftest.c for i in 1 2 3 4 5 6; do echo '#include "conftst'$i'.h"' >> sub/conftest.c # Using ": > sub/conftst$i.h" creates only sub/conftst1.h with # Solaris 10 /bin/sh. echo '/* dummy */' > sub/conftst$i.h done echo "${am__include} ${am__quote}sub/conftest.Po${am__quote}" > confmf # We check with '-c' and '-o' for the sake of the "dashmstdout" # mode. It turns out that the SunPro C++ compiler does not properly # handle '-M -o', and we need to detect this. Also, some Intel # versions had trouble with output in subdirs. am__obj=sub/conftest.${OBJEXT-o} am__minus_obj="-o $am__obj" case $depmode in gcc) # This depmode causes a compiler race in universal mode. test "$am__universal" = false || continue ;; nosideeffect) # After this tag, mechanisms are not by side-effect, so they'll # only be used when explicitly requested. if test "x$enable_dependency_tracking" = xyes; then continue else break fi ;; msvc7 | msvc7msys | msvisualcpp | msvcmsys) # This compiler won't grok '-c -o', but also, the minuso test has # not run yet. These depmodes are late enough in the game, and # so weak that their functioning should not be impacted. am__obj=conftest.${OBJEXT-o} am__minus_obj= ;; none) break ;; esac if depmode=$depmode \ source=sub/conftest.c object=$am__obj \ depfile=sub/conftest.Po tmpdepfile=sub/conftest.TPo \ $SHELL ./depcomp $depcc -c $am__minus_obj sub/conftest.c \ >/dev/null 2>conftest.err && grep sub/conftst1.h sub/conftest.Po > /dev/null 2>&1 && grep sub/conftst6.h sub/conftest.Po > /dev/null 2>&1 && grep $am__obj sub/conftest.Po > /dev/null 2>&1 && ${MAKE-make} -s -f confmf > /dev/null 2>&1; then # icc doesn't choke on unknown options, it will just issue warnings # or remarks (even with -Werror). So we grep stderr for any message # that says an option was ignored or not supported. # When given -MP, icc 7.0 and 7.1 complain thusly: # icc: Command line warning: ignoring option '-M'; no argument required # The diagnosis changed in icc 8.0: # icc: Command line remark: option '-MP' not supported if (grep 'ignoring option' conftest.err || grep 'not supported' conftest.err) >/dev/null 2>&1; then :; else am_cv_$1_dependencies_compiler_type=$depmode break fi fi done cd .. rm -rf conftest.dir else am_cv_$1_dependencies_compiler_type=none fi ]) AC_SUBST([$1DEPMODE], [depmode=$am_cv_$1_dependencies_compiler_type]) AM_CONDITIONAL([am__fastdep$1], [ test "x$enable_dependency_tracking" != xno \ && test "$am_cv_$1_dependencies_compiler_type" = gcc3]) ]) # AM_SET_DEPDIR # ------------- # Choose a directory name for dependency files. # This macro is AC_REQUIREd in _AM_DEPENDENCIES. AC_DEFUN([AM_SET_DEPDIR], [AC_REQUIRE([AM_SET_LEADING_DOT])dnl AC_SUBST([DEPDIR], ["${am__leading_dot}deps"])dnl ]) # AM_DEP_TRACK # ------------ AC_DEFUN([AM_DEP_TRACK], [AC_ARG_ENABLE([dependency-tracking], [dnl AS_HELP_STRING( [--enable-dependency-tracking], [do not reject slow dependency extractors]) AS_HELP_STRING( [--disable-dependency-tracking], [speeds up one-time build])]) if test "x$enable_dependency_tracking" != xno; then am_depcomp="$ac_aux_dir/depcomp" AMDEPBACKSLASH='\' am__nodep='_no' fi AM_CONDITIONAL([AMDEP], [test "x$enable_dependency_tracking" != xno]) AC_SUBST([AMDEPBACKSLASH])dnl _AM_SUBST_NOTMAKE([AMDEPBACKSLASH])dnl AC_SUBST([am__nodep])dnl _AM_SUBST_NOTMAKE([am__nodep])dnl ]) # Generate code to set up dependency tracking. -*- Autoconf -*- # Copyright (C) 1999-2017 Free Software Foundation, Inc. # # This file is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, # with or without modifications, as long as this notice is preserved. # _AM_OUTPUT_DEPENDENCY_COMMANDS # ------------------------------ AC_DEFUN([_AM_OUTPUT_DEPENDENCY_COMMANDS], [{ # Older Autoconf quotes --file arguments for eval, but not when files # are listed without --file. Let's play safe and only enable the eval # if we detect the quoting. case $CONFIG_FILES in *\'*) eval set x "$CONFIG_FILES" ;; *) set x $CONFIG_FILES ;; esac shift for mf do # Strip MF so we end up with the name of the file. mf=`echo "$mf" | sed -e 's/:.*$//'` # Check whether this is an Automake generated Makefile or not. # We used to match only the files named 'Makefile.in', but # some people rename them; so instead we look at the file content. # Grep'ing the first line is not enough: some people post-process # each Makefile.in and add a new line on top of each file to say so. # Grep'ing the whole file is not good either: AIX grep has a line # limit of 2048, but all sed's we know have understand at least 4000. if sed -n 's,^#.*generated by automake.*,X,p' "$mf" | grep X >/dev/null 2>&1; then dirpart=`AS_DIRNAME("$mf")` else continue fi # Extract the definition of DEPDIR, am__include, and am__quote # from the Makefile without running 'make'. DEPDIR=`sed -n 's/^DEPDIR = //p' < "$mf"` test -z "$DEPDIR" && continue am__include=`sed -n 's/^am__include = //p' < "$mf"` test -z "$am__include" && continue am__quote=`sed -n 's/^am__quote = //p' < "$mf"` # Find all dependency output files, they are included files with # $(DEPDIR) in their names. We invoke sed twice because it is the # simplest approach to changing $(DEPDIR) to its actual value in the # expansion. for file in `sed -n " s/^$am__include $am__quote\(.*(DEPDIR).*\)$am__quote"'$/\1/p' <"$mf" | \ sed -e 's/\$(DEPDIR)/'"$DEPDIR"'/g'`; do # Make sure the directory exists. test -f "$dirpart/$file" && continue fdir=`AS_DIRNAME(["$file"])` AS_MKDIR_P([$dirpart/$fdir]) # echo "creating $dirpart/$file" echo '# dummy' > "$dirpart/$file" done done } ])# _AM_OUTPUT_DEPENDENCY_COMMANDS # AM_OUTPUT_DEPENDENCY_COMMANDS # ----------------------------- # This macro should only be invoked once -- use via AC_REQUIRE. # # This code is only required when automatic dependency tracking # is enabled. FIXME. This creates each '.P' file that we will # need in order to bootstrap the dependency handling code. AC_DEFUN([AM_OUTPUT_DEPENDENCY_COMMANDS], [AC_CONFIG_COMMANDS([depfiles], [test x"$AMDEP_TRUE" != x"" || _AM_OUTPUT_DEPENDENCY_COMMANDS], [AMDEP_TRUE="$AMDEP_TRUE" ac_aux_dir="$ac_aux_dir"]) ]) # Do all the work for Automake. -*- Autoconf -*- # Copyright (C) 1996-2017 Free Software Foundation, Inc. # # This file is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, # with or without modifications, as long as this notice is preserved. # This macro actually does too much. Some checks are only needed if # your package does certain things. But this isn't really a big deal. dnl Redefine AC_PROG_CC to automatically invoke _AM_PROG_CC_C_O. m4_define([AC_PROG_CC], m4_defn([AC_PROG_CC]) [_AM_PROG_CC_C_O ]) # AM_INIT_AUTOMAKE(PACKAGE, VERSION, [NO-DEFINE]) # AM_INIT_AUTOMAKE([OPTIONS]) # ----------------------------------------------- # The call with PACKAGE and VERSION arguments is the old style # call (pre autoconf-2.50), which is being phased out. PACKAGE # and VERSION should now be passed to AC_INIT and removed from # the call to AM_INIT_AUTOMAKE. # We support both call styles for the transition. After # the next Automake release, Autoconf can make the AC_INIT # arguments mandatory, and then we can depend on a new Autoconf # release and drop the old call support. AC_DEFUN([AM_INIT_AUTOMAKE], [AC_PREREQ([2.65])dnl dnl Autoconf wants to disallow AM_ names. We explicitly allow dnl the ones we care about. m4_pattern_allow([^AM_[A-Z]+FLAGS$])dnl AC_REQUIRE([AM_SET_CURRENT_AUTOMAKE_VERSION])dnl AC_REQUIRE([AC_PROG_INSTALL])dnl if test "`cd $srcdir && pwd`" != "`pwd`"; then # Use -I$(srcdir) only when $(srcdir) != ., so that make's output # is not polluted with repeated "-I." AC_SUBST([am__isrc], [' -I$(srcdir)'])_AM_SUBST_NOTMAKE([am__isrc])dnl # test to see if srcdir already configured if test -f $srcdir/config.status; then AC_MSG_ERROR([source directory already configured; run "make distclean" there first]) fi fi # test whether we have cygpath if test -z "$CYGPATH_W"; then if (cygpath --version) >/dev/null 2>/dev/null; then CYGPATH_W='cygpath -w' else CYGPATH_W=echo fi fi AC_SUBST([CYGPATH_W]) # Define the identity of the package. dnl Distinguish between old-style and new-style calls. m4_ifval([$2], [AC_DIAGNOSE([obsolete], [$0: two- and three-arguments forms are deprecated.]) m4_ifval([$3], [_AM_SET_OPTION([no-define])])dnl AC_SUBST([PACKAGE], [$1])dnl AC_SUBST([VERSION], [$2])], [_AM_SET_OPTIONS([$1])dnl dnl Diagnose old-style AC_INIT with new-style AM_AUTOMAKE_INIT. m4_if( m4_ifdef([AC_PACKAGE_NAME], [ok]):m4_ifdef([AC_PACKAGE_VERSION], [ok]), [ok:ok],, [m4_fatal([AC_INIT should be called with package and version arguments])])dnl AC_SUBST([PACKAGE], ['AC_PACKAGE_TARNAME'])dnl AC_SUBST([VERSION], ['AC_PACKAGE_VERSION'])])dnl _AM_IF_OPTION([no-define],, [AC_DEFINE_UNQUOTED([PACKAGE], ["$PACKAGE"], [Name of package]) AC_DEFINE_UNQUOTED([VERSION], ["$VERSION"], [Version number of package])])dnl # Some tools Automake needs. AC_REQUIRE([AM_SANITY_CHECK])dnl AC_REQUIRE([AC_ARG_PROGRAM])dnl AM_MISSING_PROG([ACLOCAL], [aclocal-${am__api_version}]) AM_MISSING_PROG([AUTOCONF], [autoconf]) AM_MISSING_PROG([AUTOMAKE], [automake-${am__api_version}]) AM_MISSING_PROG([AUTOHEADER], [autoheader]) AM_MISSING_PROG([MAKEINFO], [makeinfo]) AC_REQUIRE([AM_PROG_INSTALL_SH])dnl AC_REQUIRE([AM_PROG_INSTALL_STRIP])dnl AC_REQUIRE([AC_PROG_MKDIR_P])dnl # For better backward compatibility. To be removed once Automake 1.9.x # dies out for good. For more background, see: # # AC_SUBST([mkdir_p], ['$(MKDIR_P)']) # We need awk for the "check" target (and possibly the TAP driver). The # system "awk" is bad on some platforms. AC_REQUIRE([AC_PROG_AWK])dnl AC_REQUIRE([AC_PROG_MAKE_SET])dnl AC_REQUIRE([AM_SET_LEADING_DOT])dnl _AM_IF_OPTION([tar-ustar], [_AM_PROG_TAR([ustar])], [_AM_IF_OPTION([tar-pax], [_AM_PROG_TAR([pax])], [_AM_PROG_TAR([v7])])]) _AM_IF_OPTION([no-dependencies],, [AC_PROVIDE_IFELSE([AC_PROG_CC], [_AM_DEPENDENCIES([CC])], [m4_define([AC_PROG_CC], m4_defn([AC_PROG_CC])[_AM_DEPENDENCIES([CC])])])dnl AC_PROVIDE_IFELSE([AC_PROG_CXX], [_AM_DEPENDENCIES([CXX])], [m4_define([AC_PROG_CXX], m4_defn([AC_PROG_CXX])[_AM_DEPENDENCIES([CXX])])])dnl AC_PROVIDE_IFELSE([AC_PROG_OBJC], [_AM_DEPENDENCIES([OBJC])], [m4_define([AC_PROG_OBJC], m4_defn([AC_PROG_OBJC])[_AM_DEPENDENCIES([OBJC])])])dnl AC_PROVIDE_IFELSE([AC_PROG_OBJCXX], [_AM_DEPENDENCIES([OBJCXX])], [m4_define([AC_PROG_OBJCXX], m4_defn([AC_PROG_OBJCXX])[_AM_DEPENDENCIES([OBJCXX])])])dnl ]) AC_REQUIRE([AM_SILENT_RULES])dnl dnl The testsuite driver may need to know about EXEEXT, so add the dnl 'am__EXEEXT' conditional if _AM_COMPILER_EXEEXT was seen. This dnl macro is hooked onto _AC_COMPILER_EXEEXT early, see below. AC_CONFIG_COMMANDS_PRE(dnl [m4_provide_if([_AM_COMPILER_EXEEXT], [AM_CONDITIONAL([am__EXEEXT], [test -n "$EXEEXT"])])])dnl # POSIX will say in a future version that running "rm -f" with no argument # is OK; and we want to be able to make that assumption in our Makefile # recipes. So use an aggressive probe to check that the usage we want is # actually supported "in the wild" to an acceptable degree. # See automake bug#10828. # To make any issue more visible, cause the running configure to be aborted # by default if the 'rm' program in use doesn't match our expectations; the # user can still override this though. if rm -f && rm -fr && rm -rf; then : OK; else cat >&2 <<'END' Oops! Your 'rm' program seems unable to run without file operands specified on the command line, even when the '-f' option is present. This is contrary to the behaviour of most rm programs out there, and not conforming with the upcoming POSIX standard: Please tell bug-automake@gnu.org about your system, including the value of your $PATH and any error possibly output before this message. This can help us improve future automake versions. END if test x"$ACCEPT_INFERIOR_RM_PROGRAM" = x"yes"; then echo 'Configuration will proceed anyway, since you have set the' >&2 echo 'ACCEPT_INFERIOR_RM_PROGRAM variable to "yes"' >&2 echo >&2 else cat >&2 <<'END' Aborting the configuration process, to ensure you take notice of the issue. You can download and install GNU coreutils to get an 'rm' implementation that behaves properly: . If you want to complete the configuration process using your problematic 'rm' anyway, export the environment variable ACCEPT_INFERIOR_RM_PROGRAM to "yes", and re-run configure. END AC_MSG_ERROR([Your 'rm' program is bad, sorry.]) fi fi dnl The trailing newline in this macro's definition is deliberate, for dnl backward compatibility and to allow trailing 'dnl'-style comments dnl after the AM_INIT_AUTOMAKE invocation. See automake bug#16841. ]) dnl Hook into '_AC_COMPILER_EXEEXT' early to learn its expansion. Do not dnl add the conditional right here, as _AC_COMPILER_EXEEXT may be further dnl mangled by Autoconf and run in a shell conditional statement. m4_define([_AC_COMPILER_EXEEXT], m4_defn([_AC_COMPILER_EXEEXT])[m4_provide([_AM_COMPILER_EXEEXT])]) # When config.status generates a header, we must update the stamp-h file. # This file resides in the same directory as the config header # that is generated. The stamp files are numbered to have different names. # Autoconf calls _AC_AM_CONFIG_HEADER_HOOK (when defined) in the # loop where config.status creates the headers, so we can generate # our stamp files there. AC_DEFUN([_AC_AM_CONFIG_HEADER_HOOK], [# Compute $1's index in $config_headers. _am_arg=$1 _am_stamp_count=1 for _am_header in $config_headers :; do case $_am_header in $_am_arg | $_am_arg:* ) break ;; * ) _am_stamp_count=`expr $_am_stamp_count + 1` ;; esac done echo "timestamp for $_am_arg" >`AS_DIRNAME(["$_am_arg"])`/stamp-h[]$_am_stamp_count]) # Copyright (C) 2001-2017 Free Software Foundation, Inc. # # This file is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, # with or without modifications, as long as this notice is preserved. # AM_PROG_INSTALL_SH # ------------------ # Define $install_sh. AC_DEFUN([AM_PROG_INSTALL_SH], [AC_REQUIRE([AM_AUX_DIR_EXPAND])dnl if test x"${install_sh+set}" != xset; then case $am_aux_dir in *\ * | *\ *) install_sh="\${SHELL} '$am_aux_dir/install-sh'" ;; *) install_sh="\${SHELL} $am_aux_dir/install-sh" esac fi AC_SUBST([install_sh])]) # Copyright (C) 2003-2017 Free Software Foundation, Inc. # # This file is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, # with or without modifications, as long as this notice is preserved. # Check whether the underlying file-system supports filenames # with a leading dot. For instance MS-DOS doesn't. AC_DEFUN([AM_SET_LEADING_DOT], [rm -rf .tst 2>/dev/null mkdir .tst 2>/dev/null if test -d .tst; then am__leading_dot=. else am__leading_dot=_ fi rmdir .tst 2>/dev/null AC_SUBST([am__leading_dot])]) # Copyright (C) 1998-2017 Free Software Foundation, Inc. # # This file is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, # with or without modifications, as long as this notice is preserved. # AM_PROG_LEX # ----------- # Autoconf leaves LEX=: if lex or flex can't be found. Change that to a # "missing" invocation, for better error output. AC_DEFUN([AM_PROG_LEX], [AC_PREREQ([2.50])dnl AC_REQUIRE([AM_MISSING_HAS_RUN])dnl AC_REQUIRE([AC_PROG_LEX])dnl if test "$LEX" = :; then LEX=${am_missing_run}flex fi]) # Add --enable-maintainer-mode option to configure. -*- Autoconf -*- # From Jim Meyering # Copyright (C) 1996-2017 Free Software Foundation, Inc. # # This file is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, # with or without modifications, as long as this notice is preserved. # AM_MAINTAINER_MODE([DEFAULT-MODE]) # ---------------------------------- # Control maintainer-specific portions of Makefiles. # Default is to disable them, unless 'enable' is passed literally. # For symmetry, 'disable' may be passed as well. Anyway, the user # can override the default with the --enable/--disable switch. AC_DEFUN([AM_MAINTAINER_MODE], [m4_case(m4_default([$1], [disable]), [enable], [m4_define([am_maintainer_other], [disable])], [disable], [m4_define([am_maintainer_other], [enable])], [m4_define([am_maintainer_other], [enable]) m4_warn([syntax], [unexpected argument to AM@&t@_MAINTAINER_MODE: $1])]) AC_MSG_CHECKING([whether to enable maintainer-specific portions of Makefiles]) dnl maintainer-mode's default is 'disable' unless 'enable' is passed AC_ARG_ENABLE([maintainer-mode], [AS_HELP_STRING([--]am_maintainer_other[-maintainer-mode], am_maintainer_other[ make rules and dependencies not useful (and sometimes confusing) to the casual installer])], [USE_MAINTAINER_MODE=$enableval], [USE_MAINTAINER_MODE=]m4_if(am_maintainer_other, [enable], [no], [yes])) AC_MSG_RESULT([$USE_MAINTAINER_MODE]) AM_CONDITIONAL([MAINTAINER_MODE], [test $USE_MAINTAINER_MODE = yes]) MAINT=$MAINTAINER_MODE_TRUE AC_SUBST([MAINT])dnl ] ) # Check to see how 'make' treats includes. -*- Autoconf -*- # Copyright (C) 2001-2017 Free Software Foundation, Inc. # # This file is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, # with or without modifications, as long as this notice is preserved. # AM_MAKE_INCLUDE() # ----------------- # Check to see how make treats includes. AC_DEFUN([AM_MAKE_INCLUDE], [am_make=${MAKE-make} cat > confinc << 'END' am__doit: @echo this is the am__doit target .PHONY: am__doit END # If we don't find an include directive, just comment out the code. AC_MSG_CHECKING([for style of include used by $am_make]) am__include="#" am__quote= _am_result=none # First try GNU make style include. echo "include confinc" > confmf # Ignore all kinds of additional output from 'make'. case `$am_make -s -f confmf 2> /dev/null` in #( *the\ am__doit\ target*) am__include=include am__quote= _am_result=GNU ;; esac # Now try BSD make style include. if test "$am__include" = "#"; then echo '.include "confinc"' > confmf case `$am_make -s -f confmf 2> /dev/null` in #( *the\ am__doit\ target*) am__include=.include am__quote="\"" _am_result=BSD ;; esac fi AC_SUBST([am__include]) AC_SUBST([am__quote]) AC_MSG_RESULT([$_am_result]) rm -f confinc confmf ]) # Fake the existence of programs that GNU maintainers use. -*- Autoconf -*- # Copyright (C) 1997-2017 Free Software Foundation, Inc. # # This file is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, # with or without modifications, as long as this notice is preserved. # AM_MISSING_PROG(NAME, PROGRAM) # ------------------------------ AC_DEFUN([AM_MISSING_PROG], [AC_REQUIRE([AM_MISSING_HAS_RUN]) $1=${$1-"${am_missing_run}$2"} AC_SUBST($1)]) # AM_MISSING_HAS_RUN # ------------------ # Define MISSING if not defined so far and test if it is modern enough. # If it is, set am_missing_run to use it, otherwise, to nothing. AC_DEFUN([AM_MISSING_HAS_RUN], [AC_REQUIRE([AM_AUX_DIR_EXPAND])dnl AC_REQUIRE_AUX_FILE([missing])dnl if test x"${MISSING+set}" != xset; then case $am_aux_dir in *\ * | *\ *) MISSING="\${SHELL} \"$am_aux_dir/missing\"" ;; *) MISSING="\${SHELL} $am_aux_dir/missing" ;; esac fi # Use eval to expand $SHELL if eval "$MISSING --is-lightweight"; then am_missing_run="$MISSING " else am_missing_run= AC_MSG_WARN(['missing' script is too old or missing]) fi ]) # Helper functions for option handling. -*- Autoconf -*- # Copyright (C) 2001-2017 Free Software Foundation, Inc. # # This file is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, # with or without modifications, as long as this notice is preserved. # _AM_MANGLE_OPTION(NAME) # ----------------------- AC_DEFUN([_AM_MANGLE_OPTION], [[_AM_OPTION_]m4_bpatsubst($1, [[^a-zA-Z0-9_]], [_])]) # _AM_SET_OPTION(NAME) # -------------------- # Set option NAME. Presently that only means defining a flag for this option. AC_DEFUN([_AM_SET_OPTION], [m4_define(_AM_MANGLE_OPTION([$1]), [1])]) # _AM_SET_OPTIONS(OPTIONS) # ------------------------ # OPTIONS is a space-separated list of Automake options. AC_DEFUN([_AM_SET_OPTIONS], [m4_foreach_w([_AM_Option], [$1], [_AM_SET_OPTION(_AM_Option)])]) # _AM_IF_OPTION(OPTION, IF-SET, [IF-NOT-SET]) # ------------------------------------------- # Execute IF-SET if OPTION is set, IF-NOT-SET otherwise. AC_DEFUN([_AM_IF_OPTION], [m4_ifset(_AM_MANGLE_OPTION([$1]), [$2], [$3])]) # Copyright (C) 1999-2017 Free Software Foundation, Inc. # # This file is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, # with or without modifications, as long as this notice is preserved. # _AM_PROG_CC_C_O # --------------- # Like AC_PROG_CC_C_O, but changed for automake. We rewrite AC_PROG_CC # to automatically call this. AC_DEFUN([_AM_PROG_CC_C_O], [AC_REQUIRE([AM_AUX_DIR_EXPAND])dnl AC_REQUIRE_AUX_FILE([compile])dnl AC_LANG_PUSH([C])dnl AC_CACHE_CHECK( [whether $CC understands -c and -o together], [am_cv_prog_cc_c_o], [AC_LANG_CONFTEST([AC_LANG_PROGRAM([])]) # Make sure it works both with $CC and with simple cc. # Following AC_PROG_CC_C_O, we do the test twice because some # compilers refuse to overwrite an existing .o file with -o, # though they will create one. am_cv_prog_cc_c_o=yes for am_i in 1 2; do if AM_RUN_LOG([$CC -c conftest.$ac_ext -o conftest2.$ac_objext]) \ && test -f conftest2.$ac_objext; then : OK else am_cv_prog_cc_c_o=no break fi done rm -f core conftest* unset am_i]) if test "$am_cv_prog_cc_c_o" != yes; then # Losing compiler, so override with the script. # FIXME: It is wrong to rewrite CC. # But if we don't then we get into trouble of one sort or another. # A longer-term fix would be to have automake use am__CC in this case, # and then we could set am__CC="\$(top_srcdir)/compile \$(CC)" CC="$am_aux_dir/compile $CC" fi AC_LANG_POP([C])]) # For backward compatibility. AC_DEFUN_ONCE([AM_PROG_CC_C_O], [AC_REQUIRE([AC_PROG_CC])]) # Copyright (C) 2001-2017 Free Software Foundation, Inc. # # This file is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, # with or without modifications, as long as this notice is preserved. # AM_RUN_LOG(COMMAND) # ------------------- # Run COMMAND, save the exit status in ac_status, and log it. # (This has been adapted from Autoconf's _AC_RUN_LOG macro.) AC_DEFUN([AM_RUN_LOG], [{ echo "$as_me:$LINENO: $1" >&AS_MESSAGE_LOG_FD ($1) >&AS_MESSAGE_LOG_FD 2>&AS_MESSAGE_LOG_FD ac_status=$? echo "$as_me:$LINENO: \$? = $ac_status" >&AS_MESSAGE_LOG_FD (exit $ac_status); }]) # Check to make sure that the build environment is sane. -*- Autoconf -*- # Copyright (C) 1996-2017 Free Software Foundation, Inc. # # This file is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, # with or without modifications, as long as this notice is preserved. # AM_SANITY_CHECK # --------------- AC_DEFUN([AM_SANITY_CHECK], [AC_MSG_CHECKING([whether build environment is sane]) # Reject unsafe characters in $srcdir or the absolute working directory # name. Accept space and tab only in the latter. am_lf=' ' case `pwd` in *[[\\\"\#\$\&\'\`$am_lf]]*) AC_MSG_ERROR([unsafe absolute working directory name]);; esac case $srcdir in *[[\\\"\#\$\&\'\`$am_lf\ \ ]]*) AC_MSG_ERROR([unsafe srcdir value: '$srcdir']);; esac # Do 'set' in a subshell so we don't clobber the current shell's # arguments. Must try -L first in case configure is actually a # symlink; some systems play weird games with the mod time of symlinks # (eg FreeBSD returns the mod time of the symlink's containing # directory). if ( am_has_slept=no for am_try in 1 2; do echo "timestamp, slept: $am_has_slept" > conftest.file set X `ls -Lt "$srcdir/configure" conftest.file 2> /dev/null` if test "$[*]" = "X"; then # -L didn't work. set X `ls -t "$srcdir/configure" conftest.file` fi if test "$[*]" != "X $srcdir/configure conftest.file" \ && test "$[*]" != "X conftest.file $srcdir/configure"; then # If neither matched, then we have a broken ls. This can happen # if, for instance, CONFIG_SHELL is bash and it inherits a # broken ls alias from the environment. This has actually # happened. Such a system could not be considered "sane". AC_MSG_ERROR([ls -t appears to fail. Make sure there is not a broken alias in your environment]) fi if test "$[2]" = conftest.file || test $am_try -eq 2; then break fi # Just in case. sleep 1 am_has_slept=yes done test "$[2]" = conftest.file ) then # Ok. : else AC_MSG_ERROR([newly created file is older than distributed files! Check your system clock]) fi AC_MSG_RESULT([yes]) # If we didn't sleep, we still need to ensure time stamps of config.status and # generated files are strictly newer. am_sleep_pid= if grep 'slept: no' conftest.file >/dev/null 2>&1; then ( sleep 1 ) & am_sleep_pid=$! fi AC_CONFIG_COMMANDS_PRE( [AC_MSG_CHECKING([that generated files are newer than configure]) if test -n "$am_sleep_pid"; then # Hide warnings about reused PIDs. wait $am_sleep_pid 2>/dev/null fi AC_MSG_RESULT([done])]) rm -f conftest.file ]) # Copyright (C) 2009-2017 Free Software Foundation, Inc. # # This file is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, # with or without modifications, as long as this notice is preserved. # AM_SILENT_RULES([DEFAULT]) # -------------------------- # Enable less verbose build rules; with the default set to DEFAULT # ("yes" being less verbose, "no" or empty being verbose). AC_DEFUN([AM_SILENT_RULES], [AC_ARG_ENABLE([silent-rules], [dnl AS_HELP_STRING( [--enable-silent-rules], [less verbose build output (undo: "make V=1")]) AS_HELP_STRING( [--disable-silent-rules], [verbose build output (undo: "make V=0")])dnl ]) case $enable_silent_rules in @%:@ ((( yes) AM_DEFAULT_VERBOSITY=0;; no) AM_DEFAULT_VERBOSITY=1;; *) AM_DEFAULT_VERBOSITY=m4_if([$1], [yes], [0], [1]);; esac dnl dnl A few 'make' implementations (e.g., NonStop OS and NextStep) dnl do not support nested variable expansions. dnl See automake bug#9928 and bug#10237. am_make=${MAKE-make} AC_CACHE_CHECK([whether $am_make supports nested variables], [am_cv_make_support_nested_variables], [if AS_ECHO([['TRUE=$(BAR$(V)) BAR0=false BAR1=true V=1 am__doit: @$(TRUE) .PHONY: am__doit']]) | $am_make -f - >/dev/null 2>&1; then am_cv_make_support_nested_variables=yes else am_cv_make_support_nested_variables=no fi]) if test $am_cv_make_support_nested_variables = yes; then dnl Using '$V' instead of '$(V)' breaks IRIX make. AM_V='$(V)' AM_DEFAULT_V='$(AM_DEFAULT_VERBOSITY)' else AM_V=$AM_DEFAULT_VERBOSITY AM_DEFAULT_V=$AM_DEFAULT_VERBOSITY fi AC_SUBST([AM_V])dnl AM_SUBST_NOTMAKE([AM_V])dnl AC_SUBST([AM_DEFAULT_V])dnl AM_SUBST_NOTMAKE([AM_DEFAULT_V])dnl AC_SUBST([AM_DEFAULT_VERBOSITY])dnl AM_BACKSLASH='\' AC_SUBST([AM_BACKSLASH])dnl _AM_SUBST_NOTMAKE([AM_BACKSLASH])dnl ]) # Copyright (C) 2001-2017 Free Software Foundation, Inc. # # This file is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, # with or without modifications, as long as this notice is preserved. # AM_PROG_INSTALL_STRIP # --------------------- # One issue with vendor 'install' (even GNU) is that you can't # specify the program used to strip binaries. This is especially # annoying in cross-compiling environments, where the build's strip # is unlikely to handle the host's binaries. # Fortunately install-sh will honor a STRIPPROG variable, so we # always use install-sh in "make install-strip", and initialize # STRIPPROG with the value of the STRIP variable (set by the user). AC_DEFUN([AM_PROG_INSTALL_STRIP], [AC_REQUIRE([AM_PROG_INSTALL_SH])dnl # Installed binaries are usually stripped using 'strip' when the user # run "make install-strip". However 'strip' might not be the right # tool to use in cross-compilation environments, therefore Automake # will honor the 'STRIP' environment variable to overrule this program. dnl Don't test for $cross_compiling = yes, because it might be 'maybe'. if test "$cross_compiling" != no; then AC_CHECK_TOOL([STRIP], [strip], :) fi INSTALL_STRIP_PROGRAM="\$(install_sh) -c -s" AC_SUBST([INSTALL_STRIP_PROGRAM])]) # Copyright (C) 2006-2017 Free Software Foundation, Inc. # # This file is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, # with or without modifications, as long as this notice is preserved. # _AM_SUBST_NOTMAKE(VARIABLE) # --------------------------- # Prevent Automake from outputting VARIABLE = @VARIABLE@ in Makefile.in. # This macro is traced by Automake. AC_DEFUN([_AM_SUBST_NOTMAKE]) # AM_SUBST_NOTMAKE(VARIABLE) # -------------------------- # Public sister of _AM_SUBST_NOTMAKE. AC_DEFUN([AM_SUBST_NOTMAKE], [_AM_SUBST_NOTMAKE($@)]) # Check how to create a tarball. -*- Autoconf -*- # Copyright (C) 2004-2017 Free Software Foundation, Inc. # # This file is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, # with or without modifications, as long as this notice is preserved. # _AM_PROG_TAR(FORMAT) # -------------------- # Check how to create a tarball in format FORMAT. # FORMAT should be one of 'v7', 'ustar', or 'pax'. # # Substitute a variable $(am__tar) that is a command # writing to stdout a FORMAT-tarball containing the directory # $tardir. # tardir=directory && $(am__tar) > result.tar # # Substitute a variable $(am__untar) that extract such # a tarball read from stdin. # $(am__untar) < result.tar # AC_DEFUN([_AM_PROG_TAR], [# Always define AMTAR for backward compatibility. Yes, it's still used # in the wild :-( We should find a proper way to deprecate it ... AC_SUBST([AMTAR], ['$${TAR-tar}']) # We'll loop over all known methods to create a tar archive until one works. _am_tools='gnutar m4_if([$1], [ustar], [plaintar]) pax cpio none' m4_if([$1], [v7], [am__tar='$${TAR-tar} chof - "$$tardir"' am__untar='$${TAR-tar} xf -'], [m4_case([$1], [ustar], [# The POSIX 1988 'ustar' format is defined with fixed-size fields. # There is notably a 21 bits limit for the UID and the GID. In fact, # the 'pax' utility can hang on bigger UID/GID (see automake bug#8343 # and bug#13588). am_max_uid=2097151 # 2^21 - 1 am_max_gid=$am_max_uid # The $UID and $GID variables are not portable, so we need to resort # to the POSIX-mandated id(1) utility. Errors in the 'id' calls # below are definitely unexpected, so allow the users to see them # (that is, avoid stderr redirection). am_uid=`id -u || echo unknown` am_gid=`id -g || echo unknown` AC_MSG_CHECKING([whether UID '$am_uid' is supported by ustar format]) if test $am_uid -le $am_max_uid; then AC_MSG_RESULT([yes]) else AC_MSG_RESULT([no]) _am_tools=none fi AC_MSG_CHECKING([whether GID '$am_gid' is supported by ustar format]) if test $am_gid -le $am_max_gid; then AC_MSG_RESULT([yes]) else AC_MSG_RESULT([no]) _am_tools=none fi], [pax], [], [m4_fatal([Unknown tar format])]) AC_MSG_CHECKING([how to create a $1 tar archive]) # Go ahead even if we have the value already cached. We do so because we # need to set the values for the 'am__tar' and 'am__untar' variables. _am_tools=${am_cv_prog_tar_$1-$_am_tools} for _am_tool in $_am_tools; do case $_am_tool in gnutar) for _am_tar in tar gnutar gtar; do AM_RUN_LOG([$_am_tar --version]) && break done am__tar="$_am_tar --format=m4_if([$1], [pax], [posix], [$1]) -chf - "'"$$tardir"' am__tar_="$_am_tar --format=m4_if([$1], [pax], [posix], [$1]) -chf - "'"$tardir"' am__untar="$_am_tar -xf -" ;; plaintar) # Must skip GNU tar: if it does not support --format= it doesn't create # ustar tarball either. (tar --version) >/dev/null 2>&1 && continue am__tar='tar chf - "$$tardir"' am__tar_='tar chf - "$tardir"' am__untar='tar xf -' ;; pax) am__tar='pax -L -x $1 -w "$$tardir"' am__tar_='pax -L -x $1 -w "$tardir"' am__untar='pax -r' ;; cpio) am__tar='find "$$tardir" -print | cpio -o -H $1 -L' am__tar_='find "$tardir" -print | cpio -o -H $1 -L' am__untar='cpio -i -H $1 -d' ;; none) am__tar=false am__tar_=false am__untar=false ;; esac # If the value was cached, stop now. We just wanted to have am__tar # and am__untar set. test -n "${am_cv_prog_tar_$1}" && break # tar/untar a dummy directory, and stop if the command works. rm -rf conftest.dir mkdir conftest.dir echo GrepMe > conftest.dir/file AM_RUN_LOG([tardir=conftest.dir && eval $am__tar_ >conftest.tar]) rm -rf conftest.dir if test -s conftest.tar; then AM_RUN_LOG([$am__untar /dev/null 2>&1 && break fi done rm -rf conftest.dir AC_CACHE_VAL([am_cv_prog_tar_$1], [am_cv_prog_tar_$1=$_am_tool]) AC_MSG_RESULT([$am_cv_prog_tar_$1])]) AC_SUBST([am__tar]) AC_SUBST([am__untar]) ]) # _AM_PROG_TAR m4_include([cf/aix.m4]) m4_include([cf/auth-modules.m4]) m4_include([cf/broken-getaddrinfo.m4]) m4_include([cf/broken-glob.m4]) m4_include([cf/broken-realloc.m4]) m4_include([cf/broken-snprintf.m4]) m4_include([cf/broken.m4]) m4_include([cf/broken2.m4]) m4_include([cf/c-attribute.m4]) m4_include([cf/capabilities.m4]) m4_include([cf/check-compile-et.m4]) m4_include([cf/check-getpwnam_r-posix.m4]) m4_include([cf/check-man.m4]) m4_include([cf/check-netinet-ip-and-tcp.m4]) m4_include([cf/check-type-extra.m4]) m4_include([cf/check-var.m4]) m4_include([cf/crypto.m4]) m4_include([cf/db.m4]) m4_include([cf/destdirs.m4]) m4_include([cf/dispatch.m4]) m4_include([cf/dlopen.m4]) m4_include([cf/find-func-no-libs.m4]) m4_include([cf/find-func-no-libs2.m4]) m4_include([cf/find-func.m4]) m4_include([cf/find-if-not-broken.m4]) m4_include([cf/framework-security.m4]) m4_include([cf/have-struct-field.m4]) m4_include([cf/have-type.m4]) m4_include([cf/irix.m4]) m4_include([cf/krb-bigendian.m4]) m4_include([cf/krb-func-getlogin.m4]) m4_include([cf/krb-ipv6.m4]) m4_include([cf/krb-prog-ln-s.m4]) m4_include([cf/krb-prog-perl.m4]) m4_include([cf/krb-readline.m4]) m4_include([cf/krb-struct-spwd.m4]) m4_include([cf/krb-struct-winsize.m4]) m4_include([cf/largefile.m4]) m4_include([cf/libtool.m4]) m4_include([cf/ltoptions.m4]) m4_include([cf/ltsugar.m4]) m4_include([cf/ltversion.m4]) m4_include([cf/lt~obsolete.m4]) m4_include([cf/mips-abi.m4]) m4_include([cf/misc.m4]) m4_include([cf/need-proto.m4]) m4_include([cf/osfc2.m4]) m4_include([cf/otp.m4]) m4_include([cf/pkg.m4]) m4_include([cf/proto-compat.m4]) m4_include([cf/pthreads.m4]) m4_include([cf/resolv.m4]) m4_include([cf/retsigtype.m4]) m4_include([cf/roken-frag.m4]) m4_include([cf/socket-wrapper.m4]) m4_include([cf/sunos.m4]) m4_include([cf/telnet.m4]) m4_include([cf/test-package.m4]) m4_include([cf/version-script.m4]) m4_include([cf/wflags.m4]) m4_include([cf/win32.m4]) m4_include([cf/with-all.m4]) m4_include([acinclude.m4]) heimdal-7.5.0/kadmin/0000755000175000017500000000000013214604041012510 5ustar niknikheimdal-7.5.0/kadmin/kadmin.cat10000644000175000017500000002400013212450763014531 0ustar niknik KADMIN(1) BSD General Commands Manual KADMIN(1) NNAAMMEE kkaaddmmiinn -- Kerberos administration utility SSYYNNOOPPSSIISS kkaaddmmiinn [--pp _s_t_r_i_n_g | ----pprriinncciippaall==_s_t_r_i_n_g] [--KK _s_t_r_i_n_g | ----kkeeyyttaabb==_s_t_r_i_n_g] [--cc _f_i_l_e | ----ccoonnffiigg--ffiillee==_f_i_l_e] [--kk _f_i_l_e | ----kkeeyy--ffiillee==_f_i_l_e] [--rr _r_e_a_l_m | ----rreeaallmm==_r_e_a_l_m] [--aa _h_o_s_t | ----aaddmmiinn--sseerrvveerr==_h_o_s_t] [--ss _p_o_r_t _n_u_m_b_e_r | ----sseerrvveerr--ppoorrtt==_p_o_r_t _n_u_m_b_e_r] [--ll | ----llooccaall] [--hh | ----hheellpp] [--vv | ----vveerrssiioonn] [_c_o_m_m_a_n_d] DDEESSCCRRIIPPTTIIOONN The kkaaddmmiinn program is used to make modifications to the Kerberos data- base, either remotely via the kadmind(8) daemon, or locally (with the --ll option). Supported options: --pp _s_t_r_i_n_g, ----pprriinncciippaall==_s_t_r_i_n_g principal to authenticate as --KK _s_t_r_i_n_g, ----kkeeyyttaabb==_s_t_r_i_n_g keytab for authentication principal --cc _f_i_l_e, ----ccoonnffiigg--ffiillee==_f_i_l_e location of config file --kk _f_i_l_e, ----kkeeyy--ffiillee==_f_i_l_e location of master key file --rr _r_e_a_l_m, ----rreeaallmm==_r_e_a_l_m realm to use --aa _h_o_s_t, ----aaddmmiinn--sseerrvveerr==_h_o_s_t server to contact --ss _p_o_r_t _n_u_m_b_e_r, ----sseerrvveerr--ppoorrtt==_p_o_r_t _n_u_m_b_e_r port to use --ll, ----llooccaall local admin mode If no _c_o_m_m_a_n_d is given on the command line, kkaaddmmiinn will prompt for com- mands to process. Some of the commands that take one or more principals as argument (ddeelleettee, eexxtt__kkeeyyttaabb, ggeett, mmooddiiffyy, and ppaasssswwdd) will accept a glob style wildcard, and perform the operation on all matching princi- pals. Commands include: aadddd [--rr | ----rraannddoomm--kkeeyy] [----rraannddoomm--ppaasssswwoorrdd] [--pp _s_t_r_i_n_g | ----ppaasssswwoorrdd==_s_t_r_i_n_g] [----kkeeyy==_s_t_r_i_n_g] [----mmaaxx--ttiicckkeett--lliiffee==_l_i_f_e_t_i_m_e] [----mmaaxx--rreenneewwaabbllee--lliiffee==_l_i_f_e_t_i_m_e] [----aattttrriibbuutteess==_a_t_t_r_i_b_u_t_e_s] [----eexxppiirraattiioonn--ttiimmee==_t_i_m_e] [----ppww--eexxppiirraattiioonn--ttiimmee==_t_i_m_e] [----ppoolliiccyy==_p_o_l_i_c_y_-_n_a_m_e] _p_r_i_n_c_i_p_a_l_._._. Adds a new principal to the database. The options not passed on the command line will be promped for. The only policy supported by Heimdal servers is `default'. aadddd__eennccttyyppee [--rr | ----rraannddoomm--kkeeyy] _p_r_i_n_c_i_p_a_l _e_n_c_t_y_p_e_s_._._. Adds a new encryption type to the principal, only random key are supported. ddeelleettee _p_r_i_n_c_i_p_a_l_._._. Removes a principal. ddeell__eennccttyyppee _p_r_i_n_c_i_p_a_l _e_n_c_t_y_p_e_s_._._. Removes some enctypes from a principal; this can be useful if the service belonging to the principal is known to not handle certain enctypes. eexxtt__kkeeyyttaabb [--kk _s_t_r_i_n_g | ----kkeeyyttaabb==_s_t_r_i_n_g] _p_r_i_n_c_i_p_a_l_._._. Creates a keytab with the keys of the specified principals. Requires get-keys rights, otherwise the principal's keys are changed and saved in the keytab. ggeett [--ll | ----lloonngg] [--ss | ----sshhoorrtt] [--tt | ----tteerrssee] [--oo _s_t_r_i_n_g | ----ccoolluummnn--iinnffoo==_s_t_r_i_n_g] _p_r_i_n_c_i_p_a_l_._._. Lists the matching principals, short prints the result as a table, while long format produces a more verbose output. Which columns to print can be selected with the --oo option. The argument is a comma separated list of column names optionally appended with an equal sign (`=') and a column header. Which columns are printed by default differ slightly between short and long output. The default terse output format is similar to --ss --oo _p_r_i_n_c_i_p_a_l_=, just printing the names of matched principals. Possible column names include: principal, princ_expire_time, pw_expiration, last_pwd_change, max_life, max_rlife, mod_time, mod_name, attributes, kvno, mkvno, last_success, last_failed, fail_auth_count, policy, and keytypes. mmooddiiffyy [--aa _a_t_t_r_i_b_u_t_e_s | ----aattttrriibbuutteess==_a_t_t_r_i_b_u_t_e_s] [----mmaaxx--ttiicckkeett--lliiffee==_l_i_f_e_t_i_m_e] [----mmaaxx--rreenneewwaabbllee--lliiffee==_l_i_f_e_t_i_m_e] [----eexxppiirraattiioonn--ttiimmee==_t_i_m_e] [----ppww--eexxppiirraattiioonn--ttiimmee==_t_i_m_e] [----kkvvnnoo==_n_u_m_b_e_r] [----ppoolliiccyy==_p_o_l_i_c_y_-_n_a_m_e] _p_r_i_n_c_i_p_a_l_._._. Modifies certain attributes of a principal. If run without command line options, you will be prompted. With command line options, it will only change the ones specified. Only policy supported by Heimdal is `default'. Possible attributes are: new-princ, support-desmd5, pwchange-service, disallow-svr, requires-pw-change, requires-hw-auth, requires-pre-auth, disallow-all-tix, disallow-dup-skey, disallow-proxiable, disallow-renewable, disallow-tgt-based, disallow-forwardable, disallow-postdated Attributes may be negated with a "-", e.g., kadmin -l modify -a -disallow-proxiable user ppaasssswwdd [----kkeeeeppoolldd] [--rr | ----rraannddoomm--kkeeyy] [----rraannddoomm--ppaasssswwoorrdd] [--pp _s_t_r_i_n_g | ----ppaasssswwoorrdd==_s_t_r_i_n_g] [----kkeeyy==_s_t_r_i_n_g] _p_r_i_n_c_i_p_a_l_._._. Changes the password of an existing principal. ppaasssswwoorrdd--qquuaalliittyy _p_r_i_n_c_i_p_a_l _p_a_s_s_w_o_r_d Run the password quality check function locally. You can run this on the host that is configured to run the kadmind process to verify that your configuration file is correct. The verification is done locally, if kadmin is run in remote mode, no rpc call is done to the server. pprriivviilleeggeess Lists the operations you are allowed to perform. These include add, add_enctype, change-password, delete, del_enctype, get, get-keys, list, and modify. rreennaammee _f_r_o_m _t_o Renames a principal. This is normally transparent, but since keys are salted with the principal name, they will have a non-standard salt, and clients which are unable to cope with this will fail. Kerberos 4 suffers from this. cchheecckk [_r_e_a_l_m] Check database for strange configurations on important principals. If no realm is given, the default realm is used. When running in local mode, the following commands can also be used: dduummpp [--dd | ----ddeeccrryypptt] [--ff_f_o_r_m_a_t | ----ffoorrmmaatt==_f_o_r_m_a_t] [_d_u_m_p_-_f_i_l_e] Writes the database in ``machine readable text'' form to the speci- fied file, or standard out. If the database is encrypted, the dump will also have encrypted keys, unless ----ddeeccrryypptt is used. If ----ffoorrmmaatt==MMIITT is used then the dump will be in MIT format. Other- wise it will be in Heimdal format. iinniitt [----rreeaallmm--mmaaxx--ttiicckkeett--lliiffee==_s_t_r_i_n_g] [----rreeaallmm--mmaaxx--rreenneewwaabbllee--lliiffee==_s_t_r_i_n_g] _r_e_a_l_m Initializes the Kerberos database with entries for a new realm. It's possible to have more than one realm served by one server. llooaadd _f_i_l_e Reads a previously dumped database, and re-creates that database from scratch. mmeerrggee _f_i_l_e Similar to llooaadd but just modifies the database with the entries in the dump file. ssttaasshh [--ee _e_n_c_t_y_p_e | ----eennccttyyppee==_e_n_c_t_y_p_e] [--kk _k_e_y_f_i_l_e | ----kkeeyy--ffiillee==_k_e_y_f_i_l_e] [----ccoonnvveerrtt--ffiillee] [----mmaasstteerr--kkeeyy--ffdd==_f_d] Writes the Kerberos master key to a file used by the KDC. SSEEEE AALLSSOO kadmind(8), kdc(8) HEIMDAL Feb 22, 2007 HEIMDAL heimdal-7.5.0/kadmin/kadmin.c0000644000175000017500000002000513026237312014120 0ustar niknik/* * Copyright (c) 1997 - 2004 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "kadmin_locl.h" #include "kadmin-commands.h" #include static char *config_file; static char *keyfile; int local_flag; static int ad_flag; static int help_flag; static int version_flag; static char *realm; static char *admin_server; static int server_port = 0; static char *client_name; static char *keytab; static char *check_library = NULL; static char *check_function = NULL; static getarg_strings policy_libraries = { 0, NULL }; static struct getargs args[] = { { "principal", 'p', arg_string, &client_name, "principal to authenticate as", NULL }, { "keytab", 'K', arg_string, &keytab, "keytab for authentication principal", NULL }, { "config-file", 'c', arg_string, &config_file, "location of config file", "file" }, { "key-file", 'k', arg_string, &keyfile, "location of master key file", "file" }, { "realm", 'r', arg_string, &realm, "realm to use", "realm" }, { "admin-server", 'a', arg_string, &admin_server, "server to contact", "host" }, { "server-port", 's', arg_integer, &server_port, "port to use", "port number" }, { "ad", 0, arg_flag, &ad_flag, "active directory admin mode", NULL }, #ifdef HAVE_DLOPEN { "check-library", 0, arg_string, &check_library, "library to load password check function from", "library" }, { "check-function", 0, arg_string, &check_function, "password check function to load", "function" }, { "policy-libraries", 0, arg_strings, &policy_libraries, "password check function to load", "function" }, #endif { "local", 'l', arg_flag, &local_flag, "local admin mode", NULL }, { "help", 'h', arg_flag, &help_flag, NULL, NULL }, { "version", 'v', arg_flag, &version_flag, NULL, NULL } }; static int num_args = sizeof(args) / sizeof(args[0]); krb5_context context; void *kadm_handle; int help(void *opt, int argc, char **argv) { sl_slc_help(commands, argc, argv); return 0; } static int exit_seen = 0; int exit_kadmin (void *opt, int argc, char **argv) { exit_seen = 1; return 0; } int lock(void *opt, int argc, char **argv) { return kadm5_lock(kadm_handle); } int unlock(void *opt, int argc, char **argv) { return kadm5_unlock(kadm_handle); } static void usage(int ret) { arg_printusage (args, num_args, NULL, "[command]"); exit (ret); } int get_privs(void *opt, int argc, char **argv) { uint32_t privs; char str[128]; kadm5_ret_t ret; ret = kadm5_get_privs(kadm_handle, &privs); if(ret) krb5_warn(context, ret, "kadm5_get_privs"); else{ ret =_kadm5_privs_to_string(privs, str, sizeof(str)); if (ret == 0) printf("%s\n", str); else printf("privs: 0x%x\n", (unsigned int)privs); } return 0; } int main(int argc, char **argv) { krb5_error_code ret; char **files; kadm5_config_params conf; int optidx = 0; int exit_status = 0; int aret; setprogname(argv[0]); ret = krb5_init_context(&context); if (ret) errx (1, "krb5_init_context failed: %d", ret); if(getarg(args, num_args, argc, argv, &optidx)) usage(1); if (help_flag) usage (0); if (version_flag) { print_version(NULL); exit(0); } argc -= optidx; argv += optidx; if (config_file == NULL) { aret = asprintf(&config_file, "%s/kdc.conf", hdb_db_dir(context)); if (aret == -1) errx(1, "out of memory"); } ret = krb5_prepend_config_files_default(config_file, &files); if (ret) krb5_err(context, 1, ret, "getting configuration files"); ret = krb5_set_config_files(context, files); krb5_free_config_files(files); if(ret) krb5_err(context, 1, ret, "reading configuration files"); memset(&conf, 0, sizeof(conf)); if(realm) { krb5_set_default_realm(context, realm); /* XXX should be fixed some other way */ conf.realm = realm; conf.mask |= KADM5_CONFIG_REALM; } if (admin_server) { conf.admin_server = admin_server; conf.mask |= KADM5_CONFIG_ADMIN_SERVER; } if (server_port) { conf.kadmind_port = htons(server_port); conf.mask |= KADM5_CONFIG_KADMIND_PORT; } if (keyfile) { conf.stash_file = keyfile; conf.mask |= KADM5_CONFIG_STASH_FILE; } if(local_flag) { int i; kadm5_setup_passwd_quality_check (context, check_library, check_function); for (i = 0; i < policy_libraries.num_strings; i++) { ret = kadm5_add_passwd_quality_verifier(context, policy_libraries.strings[i]); if (ret) krb5_err(context, 1, ret, "kadm5_add_passwd_quality_verifier"); } ret = kadm5_add_passwd_quality_verifier(context, NULL); if (ret) krb5_err(context, 1, ret, "kadm5_add_passwd_quality_verifier"); ret = kadm5_s_init_with_password_ctx(context, KADM5_ADMIN_SERVICE, NULL, KADM5_ADMIN_SERVICE, &conf, 0, 0, &kadm_handle); } else if (ad_flag) { if (client_name == NULL) krb5_errx(context, 1, "keytab mode require principal name"); ret = kadm5_ad_init_with_password_ctx(context, client_name, NULL, KADM5_ADMIN_SERVICE, &conf, 0, 0, &kadm_handle); } else if (keytab) { if (client_name == NULL) krb5_errx(context, 1, "keytab mode require principal name"); ret = kadm5_c_init_with_skey_ctx(context, client_name, keytab, KADM5_ADMIN_SERVICE, &conf, 0, 0, &kadm_handle); } else ret = kadm5_c_init_with_password_ctx(context, client_name, NULL, KADM5_ADMIN_SERVICE, &conf, 0, 0, &kadm_handle); if(ret) krb5_err(context, 1, ret, "kadm5_init_with_password"); signal(SIGINT, SIG_IGN); /* ignore signals for now, the sl command parser will handle SIGINT its own way; we should really take care of this in each function, f.i `get' might be interruptable, but not `create' */ if (argc != 0) { ret = sl_command (commands, argc, argv); if(ret == -1) sl_did_you_mean(commands, argv[0]); else if (ret == -2) ret = 0; if(ret != 0) exit_status = 1; } else { while(!exit_seen) { ret = sl_command_loop(commands, "kadmin> ", NULL); if (ret == -2) exit_seen = 1; else if (ret != 0) exit_status = 1; } } kadm5_destroy(kadm_handle); krb5_free_context(context); return exit_status; } heimdal-7.5.0/kadmin/del_enctype.c0000644000175000017500000000764513026237312015167 0ustar niknik/* * Copyright (c) 1999-2006 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "kadmin_locl.h" #include "kadmin-commands.h" /* * del_enctype principal enctypes... */ int del_enctype(void *opt, int argc, char **argv) { kadm5_principal_ent_rec princ; krb5_principal princ_ent = NULL; krb5_error_code ret; const char *princ_name; int i, j, k; krb5_key_data *new_key_data; int n_etypes; krb5_enctype *etypes; krb5_key_data *key; memset (&princ, 0, sizeof(princ)); princ_name = argv[0]; n_etypes = argc - 1; etypes = malloc (n_etypes * sizeof(*etypes)); if (etypes == NULL) { krb5_warnx (context, "out of memory"); return 0; } argv++; for (i = 0; i < n_etypes; ++i) { ret = krb5_string_to_enctype (context, argv[i], &etypes[i]); if (ret) { krb5_warnx (context, "bad enctype \"%s\"", argv[i]); goto out2; } } ret = krb5_parse_name(context, princ_name, &princ_ent); if (ret) { krb5_warn (context, ret, "krb5_parse_name %s", princ_name); goto out2; } ret = kadm5_get_principal(kadm_handle, princ_ent, &princ, KADM5_PRINCIPAL | KADM5_KEY_DATA); if (ret) { krb5_free_principal (context, princ_ent); krb5_warnx (context, "no such principal: %s", princ_name); goto out2; } if (kadm5_all_keys_are_bogus(princ.n_key_data, princ.key_data)) { krb5_warnx(context, "user lacks get-keys privilege"); goto out; } new_key_data = malloc(princ.n_key_data * sizeof(*new_key_data)); if (new_key_data == NULL && princ.n_key_data != 0) { krb5_warnx (context, "out of memory"); goto out; } for (i = 0, j = 0; i < princ.n_key_data; ++i) { int docopy = 1; key = &princ.key_data[i]; for (k = 0; k < n_etypes; ++k) { if (etypes[k] == key->key_data_type[0]) { docopy = 0; break; } } if (docopy) { new_key_data[j++] = *key; } else { int16_t ignore = 1; kadm5_free_key_data (kadm_handle, &ignore, key); } } free (princ.key_data); if (j == 0) { free(new_key_data); new_key_data = NULL; } princ.n_key_data = j; princ.key_data = new_key_data; ret = kadm5_modify_principal (kadm_handle, &princ, KADM5_KEY_DATA); if (ret) krb5_warn(context, ret, "kadm5_modify_principal"); out: krb5_free_principal (context, princ_ent); kadm5_free_principal_ent(kadm_handle, &princ); out2: free (etypes); return ret != 0; } heimdal-7.5.0/kadmin/random_password.c0000644000175000017500000001120313212137553016062 0ustar niknik/* * Copyright (c) 1998, 1999 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "kadmin_locl.h" /* This file defines some a function that generates a random password, that can be used when creating a large amount of principals (such as for a batch of students). Since this is a political matter, you should think about how secure generated passwords has to be. Both methods defined here will give you at least 55 bits of entropy. */ /* If you want OTP-style passwords, define OTP_STYLE */ #ifdef OTP_STYLE #include #else static void generate_password(char **pw, int num_classes, ...); #endif void random_password(char *pw, size_t len) { #ifdef OTP_STYLE { OtpKey newkey; krb5_generate_random_block(&newkey, sizeof(newkey)); otp_print_stddict (newkey, pw, len); strlwr(pw); } #else char *pass; generate_password(&pass, 3, "abcdefghijklmnopqrstuvwxyz", 7, "ABCDEFGHIJKLMNOPQRSTUVWXYZ", 2, "@$%&*()-+=:,/<>1234567890", 1); strlcpy(pw, pass, len); memset(pass, 0, strlen(pass)); free(pass); #endif } /* some helper functions */ #ifndef OTP_STYLE /* return a random value in range 0-127 */ static int RND(unsigned char *key, int keylen, int *left) { if(*left == 0){ krb5_generate_random_block(key, keylen); *left = keylen; } (*left)--; return ((unsigned char*)key)[*left]; } /* This a helper function that generates a random password with a number of characters from a set of character classes. If there are n classes, and the size of each class is Pi, and the number of characters from each class is Ni, the number of possible passwords are (given that the character classes are disjoint): n n ----- / ---- \ | | Ni | \ | | | Pi | \ Ni| ! | | ---- * | / | | | Ni! | /___ | i=1 \ i=1 / Since it uses the RND function above, neither the size of each class, nor the total length of the generated password should be larger than 127 (without fixing RND). */ static void generate_password(char **pw, int num_classes, ...) { struct { const char *str; int len; int freq; } *classes; va_list ap; int len, i; unsigned char rbuf[8]; /* random buffer */ int rleft = 0; *pw = NULL; classes = malloc(num_classes * sizeof(*classes)); if(classes == NULL) return; va_start(ap, num_classes); len = 0; for(i = 0; i < num_classes; i++){ classes[i].str = va_arg(ap, const char*); classes[i].len = strlen(classes[i].str); classes[i].freq = va_arg(ap, int); len += classes[i].freq; } va_end(ap); *pw = malloc(len + 1); if(*pw == NULL) { free(classes); return; } for(i = 0; i < len; i++) { int j; int x = RND(rbuf, sizeof(rbuf), &rleft) % (len - i); int t = 0; for(j = 0; j < num_classes; j++) { if(x < t + classes[j].freq) { (*pw)[i] = classes[j].str[RND(rbuf, sizeof(rbuf), &rleft) % classes[j].len]; classes[j].freq--; break; } t += classes[j].freq; } } (*pw)[len] = '\0'; memset(rbuf, 0, sizeof(rbuf)); free(classes); } #endif heimdal-7.5.0/kadmin/stash.c0000644000175000017500000001106213026237312014002 0ustar niknik/* * Copyright (c) 2004 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Portions Copyright (c) 2009 Apple Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "kadmin_locl.h" #include "kadmin-commands.h" extern int local_flag; int stash(struct stash_options *opt, int argc, char **argv) { char buf[1024+1]; krb5_error_code ret; krb5_enctype enctype; hdb_master_key mkey; int aret; if(!local_flag) { krb5_warnx(context, "stash is only available in local (-l) mode"); return 0; } ret = krb5_string_to_enctype(context, opt->enctype_string, &enctype); if(ret) { krb5_warn(context, ret, "%s", opt->enctype_string); return 0; } if(opt->key_file_string == NULL) { aret = asprintf(&opt->key_file_string, "%s/m-key", hdb_db_dir(context)); if (aret == -1) errx(1, "out of memory"); } ret = hdb_read_master_key(context, opt->key_file_string, &mkey); if(ret && ret != ENOENT) { krb5_warn(context, ret, "reading master key from %s", opt->key_file_string); return 0; } if (opt->convert_file_flag) { if (ret) krb5_warn(context, ret, "reading master key from %s", opt->key_file_string); hdb_free_master_key(context, mkey); return 0; } else { krb5_keyblock key; krb5_salt salt; salt.salttype = KRB5_PW_SALT; /* XXX better value? */ salt.saltvalue.data = NULL; salt.saltvalue.length = 0; if(opt->master_key_fd_integer != -1) { ssize_t n; n = read(opt->master_key_fd_integer, buf, sizeof(buf)-1); if(n == 0) krb5_warnx(context, "end of file reading passphrase"); else if(n < 0) { krb5_warn(context, errno, "reading passphrase"); n = 0; } buf[n] = '\0'; buf[strcspn(buf, "\r\n")] = '\0'; } else if (opt->random_password_flag) { random_password (buf, sizeof(buf)); printf("Using random master stash password: %s\n", buf); } else { if(UI_UTIL_read_pw_string(buf, sizeof(buf), "Master key: ", 1)) { hdb_free_master_key(context, mkey); return 0; } } ret = krb5_string_to_key_salt(context, enctype, buf, salt, &key); ret = hdb_add_master_key(context, &key, &mkey); krb5_free_keyblock_contents(context, &key); } { char *new = NULL, *old = NULL; aret = asprintf(&old, "%s.old", opt->key_file_string); if (aret == -1) { ret = ENOMEM; goto out; } aret = asprintf(&new, "%s.new", opt->key_file_string); if (aret == -1) { ret = ENOMEM; goto out; } if(unlink(new) < 0 && errno != ENOENT) { ret = errno; goto out; } krb5_warnx(context, "writing key to \"%s\"", opt->key_file_string); ret = hdb_write_master_key(context, new, mkey); if(ret) unlink(new); else { unlink(old); #ifndef NO_POSIX_LINKS if(link(opt->key_file_string, old) < 0 && errno != ENOENT) { ret = errno; unlink(new); } else { #endif if(rename(new, opt->key_file_string) < 0) { ret = errno; } #ifndef NO_POSIX_LINKS } #endif } out: free(old); free(new); if(ret) krb5_warn(context, errno, "writing master key file"); } hdb_free_master_key(context, mkey); return 0; } heimdal-7.5.0/kadmin/kadmind-version.rc0000644000175000017500000000323712136107747016152 0ustar niknik/*********************************************************************** * Copyright (c) 2010, Secure Endpoints Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * - Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. * **********************************************************************/ #define RC_FILE_TYPE VFT_APP #define RC_FILE_DESC_0409 "Kerberos Administration Server" #define RC_FILE_ORIG_0409 "kadmind.exe" #include "../windows/version.rc" heimdal-7.5.0/kadmin/load.c0000644000175000017500000003475313212137553013616 0ustar niknik/* * Copyright (c) 1997-2005 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include #include "kadmin_locl.h" #include "kadmin-commands.h" #include struct entry { char *principal; char *key; char *max_life; char *max_renew; char *created; char *modified; char *valid_start; char *valid_end; char *pw_end; char *flags; char *generation; char *extensions; }; static char * skip_next(char *p) { while(*p && !isspace((unsigned char)*p)) p++; *p++ = 0; while(*p && isspace((unsigned char)*p)) p++; return p; } /* * Parse the time in `s', returning: * -1 if error parsing * 0 if none present * 1 if parsed ok */ static int parse_time_string(time_t *t, const char *s) { int year, month, date, hour, minute, second; struct tm tm; if(strcmp(s, "-") == 0) return 0; if(sscanf(s, "%04d%02d%02d%02d%02d%02d", &year, &month, &date, &hour, &minute, &second) != 6) return -1; tm.tm_year = year - 1900; tm.tm_mon = month - 1; tm.tm_mday = date; tm.tm_hour = hour; tm.tm_min = minute; tm.tm_sec = second; tm.tm_isdst = 0; *t = timegm(&tm); return 1; } /* * parse time, allocating space in *t if it's there */ static int parse_time_string_alloc (time_t **t, const char *s) { time_t tmp; int ret; *t = NULL; ret = parse_time_string (&tmp, s); if (ret == 1) { *t = malloc (sizeof (**t)); if (*t == NULL) krb5_errx (context, 1, "malloc: out of memory"); **t = tmp; } return ret; } /* * see parse_time_string for calling convention */ static int parse_integer(unsigned int *u, const char *s) { if(strcmp(s, "-") == 0) return 0; if (sscanf(s, "%u", u) != 1) return -1; return 1; } static int parse_integer_alloc (unsigned int **u, const char *s) { unsigned int tmp; int ret; *u = NULL; ret = parse_integer (&tmp, s); if (ret == 1) { *u = malloc (sizeof (**u)); if (*u == NULL) krb5_errx (context, 1, "malloc: out of memory"); **u = tmp; } return ret; } /* * Parse dumped keys in `str' and store them in `ent' * return -1 if parsing failed */ static int parse_keys(hdb_entry *ent, char *str) { krb5_error_code ret; int tmp; char *p; size_t i; p = strsep(&str, ":"); if (sscanf(p, "%d", &tmp) != 1) return 1; ent->kvno = tmp; p = strsep(&str, ":"); while(p){ Key *key; key = realloc(ent->keys.val, (ent->keys.len + 1) * sizeof(*ent->keys.val)); if(key == NULL) krb5_errx (context, 1, "realloc: out of memory"); ent->keys.val = key; key = ent->keys.val + ent->keys.len; ent->keys.len++; memset(key, 0, sizeof(*key)); if(sscanf(p, "%d", &tmp) == 1) { key->mkvno = malloc(sizeof(*key->mkvno)); *key->mkvno = tmp; } else key->mkvno = NULL; p = strsep(&str, ":"); if (sscanf(p, "%d", &tmp) != 1) return 1; key->key.keytype = tmp; p = strsep(&str, ":"); ret = krb5_data_alloc(&key->key.keyvalue, (strlen(p) - 1) / 2 + 1); if (ret) krb5_err (context, 1, ret, "krb5_data_alloc"); for(i = 0; i < strlen(p); i += 2) { if(sscanf(p + i, "%02x", &tmp) != 1) return 1; ((u_char*)key->key.keyvalue.data)[i / 2] = tmp; } p = strsep(&str, ":"); if(strcmp(p, "-") != 0){ unsigned type; size_t p_len; if(sscanf(p, "%u/", &type) != 1) return 1; p = strchr(p, '/'); if(p == NULL) return 1; p++; p_len = strlen(p); key->salt = calloc(1, sizeof(*key->salt)); if (key->salt == NULL) krb5_errx (context, 1, "malloc: out of memory"); key->salt->type = type; if (p_len) { if(*p == '\"') { ret = krb5_data_copy(&key->salt->salt, p + 1, p_len - 2); if (ret) krb5_err (context, 1, ret, "krb5_data_copy"); } else { ret = krb5_data_alloc(&key->salt->salt, (p_len - 1) / 2 + 1); if (ret) krb5_err (context, 1, ret, "krb5_data_alloc"); for(i = 0; i < p_len; i += 2){ if (sscanf(p + i, "%02x", &tmp) != 1) return 1; ((u_char*)key->salt->salt.data)[i / 2] = tmp; } } } else krb5_data_zero (&key->salt->salt); } p = strsep(&str, ":"); } return 0; } /* * see parse_time_string for calling convention */ static int parse_event(Event *ev, char *s) { krb5_error_code ret; char *p; if(strcmp(s, "-") == 0) return 0; memset(ev, 0, sizeof(*ev)); p = strsep(&s, ":"); if(parse_time_string(&ev->time, p) != 1) return -1; p = strsep(&s, ":"); ret = krb5_parse_name(context, p, &ev->principal); if (ret) return -1; return 1; } static int parse_event_alloc (Event **ev, char *s) { Event tmp; int ret; *ev = NULL; ret = parse_event (&tmp, s); if (ret == 1) { *ev = malloc (sizeof (**ev)); if (*ev == NULL) krb5_errx (context, 1, "malloc: out of memory"); **ev = tmp; } return ret; } static int parse_hdbflags2int(HDBFlags *f, const char *s) { int ret; unsigned int tmp; ret = parse_integer (&tmp, s); if (ret == 1) *f = int2HDBFlags (tmp); return ret; } static int parse_generation(char *str, GENERATION **gen) { char *p; int v; if(strcmp(str, "-") == 0 || *str == '\0') { *gen = NULL; return 0; } *gen = calloc(1, sizeof(**gen)); p = strsep(&str, ":"); if(parse_time_string(&(*gen)->time, p) != 1) return -1; p = strsep(&str, ":"); if(sscanf(p, "%d", &v) != 1) return -1; (*gen)->usec = v; p = strsep(&str, ":"); if(sscanf(p, "%d", &v) != 1) return -1; (*gen)->gen = v - 1; /* XXX gets bumped in _hdb_store */ return 0; } /* On error modify strp to point to the problem element */ static int parse_extensions(char **strp, HDB_extensions **e) { char *str = *strp; char *p; int ret; if(strcmp(str, "-") == 0 || *str == '\0') { *e = NULL; return 0; } *e = calloc(1, sizeof(**e)); p = strsep(&str, ":"); while (p) { HDB_extension ext; ssize_t len; void *d; len = strlen(p); d = emalloc(len); len = hex_decode(p, d, len); if (len < 0) { free(d); *strp = p; return -1; } ret = decode_HDB_extension(d, len, &ext, NULL); free(d); if (ret) { *strp = p; return -1; } d = realloc((*e)->val, ((*e)->len + 1) * sizeof((*e)->val[0])); if (d == NULL) abort(); (*e)->val = d; (*e)->val[(*e)->len] = ext; (*e)->len++; p = strsep(&str, ":"); } return 0; } /* XXX: Principal names with '\n' cannot be dumped or loaded */ static int my_fgetln(FILE *f, char **bufp, size_t *szp, size_t *lenp) { size_t len; size_t sz = *szp; char *buf = *bufp; char *p, *n; if (!buf) { buf = malloc(sz ? sz : 8192); if (!buf) return ENOMEM; if (!sz) sz = 8192; } len = 0; while ((p = fgets(&buf[len], sz-len, f)) != NULL) { len += strlen(&buf[len]); if (buf[len-1] == '\n') break; if (feof(f)) break; if (sz > SIZE_MAX/2 || (n = realloc(buf, sz += 1 + (sz >> 1))) == NULL) { free(buf); *bufp = NULL; *szp = 0; *lenp = 0; return ENOMEM; } buf = n; } *bufp = buf; *szp = sz; *lenp = len; return 0; /* *len == 0 || no EOL -> EOF */ } /* * Parse the dump file in `filename' and create the database (merging * iff merge) */ static int doit(const char *filename, int mergep) { krb5_error_code ret = 0; krb5_error_code ret2 = 0; FILE *f; char *line = NULL; size_t linesz = 0; size_t linelen = 0; char *p; int lineno; int flags = O_RDWR; struct entry e; hdb_entry_ex ent; HDB *db = _kadm5_s_get_db(kadm_handle); f = fopen(filename, "r"); if (f == NULL) { krb5_warn(context, errno, "fopen(%s)", filename); return 1; } /* * We don't have a version number in the dump, so we don't know which iprop * log entries to keep, if any. We throw the log away. * * We could merge the ipropd-master/slave dump/load here as an option, in * which case we would first load the dump. * * If we're merging, first recover unconfirmed records in the existing log. */ if (mergep) ret = kadm5_log_init(kadm_handle); if (ret == 0) ret = kadm5_log_reinit(kadm_handle, 0); if (ret) { fclose (f); krb5_warn(context, ret, "kadm5_log_reinit"); return 1; } if (!mergep) flags |= O_CREAT | O_TRUNC; ret = db->hdb_open(context, db, flags, 0600); if (ret){ krb5_warn(context, ret, "hdb_open"); fclose(f); return 1; } for (lineno = 1; (ret2 = my_fgetln(f, &line, &linesz, &linelen)) == 0 && linelen > 0; ++lineno) { p = line; while (isspace((unsigned char)*p)) p++; e.principal = p; for (p = line; *p; p++){ if (*p == '\\') /* Support '\n' escapes??? */ p++; else if (isspace((unsigned char)*p)) { *p = 0; break; } } p = skip_next(p); e.key = p; p = skip_next(p); e.created = p; p = skip_next(p); e.modified = p; p = skip_next(p); e.valid_start = p; p = skip_next(p); e.valid_end = p; p = skip_next(p); e.pw_end = p; p = skip_next(p); e.max_life = p; p = skip_next(p); e.max_renew = p; p = skip_next(p); e.flags = p; p = skip_next(p); e.generation = p; p = skip_next(p); e.extensions = p; skip_next(p); memset(&ent, 0, sizeof(ent)); ret2 = krb5_parse_name(context, e.principal, &ent.entry.principal); if (ret2) { const char *msg = krb5_get_error_message(context, ret); fprintf(stderr, "%s:%d:%s (%s)\n", filename, lineno, msg, e.principal); krb5_free_error_message(context, msg); ret = 1; continue; } if (parse_keys(&ent.entry, e.key)) { fprintf (stderr, "%s:%d:error parsing keys (%s)\n", filename, lineno, e.key); hdb_free_entry (context, &ent); ret = 1; continue; } if (parse_event(&ent.entry.created_by, e.created) == -1) { fprintf (stderr, "%s:%d:error parsing created event (%s)\n", filename, lineno, e.created); hdb_free_entry (context, &ent); ret = 1; continue; } if (parse_event_alloc (&ent.entry.modified_by, e.modified) == -1) { fprintf (stderr, "%s:%d:error parsing event (%s)\n", filename, lineno, e.modified); hdb_free_entry (context, &ent); ret = 1; continue; } if (parse_time_string_alloc (&ent.entry.valid_start, e.valid_start) == -1) { fprintf (stderr, "%s:%d:error parsing time (%s)\n", filename, lineno, e.valid_start); hdb_free_entry (context, &ent); ret = 1; continue; } if (parse_time_string_alloc (&ent.entry.valid_end, e.valid_end) == -1) { fprintf (stderr, "%s:%d:error parsing time (%s)\n", filename, lineno, e.valid_end); hdb_free_entry (context, &ent); ret = 1; continue; } if (parse_time_string_alloc (&ent.entry.pw_end, e.pw_end) == -1) { fprintf (stderr, "%s:%d:error parsing time (%s)\n", filename, lineno, e.pw_end); hdb_free_entry (context, &ent); ret = 1; continue; } if (parse_integer_alloc (&ent.entry.max_life, e.max_life) == -1) { fprintf (stderr, "%s:%d:error parsing lifetime (%s)\n", filename, lineno, e.max_life); hdb_free_entry (context, &ent); ret = 1; continue; } if (parse_integer_alloc (&ent.entry.max_renew, e.max_renew) == -1) { fprintf (stderr, "%s:%d:error parsing lifetime (%s)\n", filename, lineno, e.max_renew); hdb_free_entry (context, &ent); ret = 1; continue; } if (parse_hdbflags2int (&ent.entry.flags, e.flags) != 1) { fprintf (stderr, "%s:%d:error parsing flags (%s)\n", filename, lineno, e.flags); hdb_free_entry (context, &ent); ret = 1; continue; } if(parse_generation(e.generation, &ent.entry.generation) == -1) { fprintf (stderr, "%s:%d:error parsing generation (%s)\n", filename, lineno, e.generation); hdb_free_entry (context, &ent); ret = 1; continue; } if (parse_extensions(&e.extensions, &ent.entry.extensions) == -1) { fprintf (stderr, "%s:%d:error parsing extension (%s)\n", filename, lineno, e.extensions); hdb_free_entry (context, &ent); ret = 1; continue; } ret2 = db->hdb_store(context, db, HDB_F_REPLACE, &ent); hdb_free_entry (context, &ent); if (ret2) { krb5_warn(context, ret2, "db_store"); break; } } free(line); if (ret2) ret = ret2; (void) kadm5_log_end(kadm_handle); ret2 = db->hdb_close(context, db); if (ret2) ret = ret2; fclose(f); return ret != 0; } extern int local_flag; static int loadit(int mergep, const char *name, int argc, char **argv) { if(!local_flag) { krb5_warnx(context, "%s is only available in local (-l) mode", name); return 0; } return doit(argv[0], mergep); } int load(void *opt, int argc, char **argv) { return loadit(0, "load", argc, argv); } int merge(void *opt, int argc, char **argv) { return loadit(1, "merge", argc, argv); } heimdal-7.5.0/kadmin/kadmin_locl.h0000644000175000017500000001063213026237312015143 0ustar niknik/* * Copyright (c) 1997-2004 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ /* * $Id$ */ #ifndef __ADMIN_LOCL_H__ #define __ADMIN_LOCL_H__ #include #include #include #include #include #include #include #ifdef HAVE_SYS_TYPES_H #include #endif #ifdef HAVE_SYS_SELECT_H #include #endif #ifdef HAVE_FCNTL_H #include #endif #ifdef HAVE_SYS_SOCKET_H #include #endif #ifdef HAVE_SYS_SELECT_H #include #endif #ifdef HAVE_NETINET_IN_H #include #endif #ifdef HAVE_NETINET_IN6_H #include #endif #ifdef HAVE_NETINET6_IN6_H #include #endif #ifdef HAVE_UTIL_H #include #endif #ifdef HAVE_LIBUTIL_H #include #endif #ifdef HAVE_NETDB_H #include #endif #ifdef HAVE_SYS_UN_H #include #endif #include #include #include #include #include #include #include #include #include #include #include #include extern krb5_context context; extern void * kadm_handle; #undef ALLOC #define ALLOC(X) ((X) = malloc(sizeof(*(X)))) /* util.c */ void attributes2str(krb5_flags, char *, size_t); int str2attributes(const char *, krb5_flags *); int parse_attributes (const char *, krb5_flags *, int *, int); int edit_attributes (const char *, krb5_flags *, int *, int); int parse_policy (const char *, char **, int *, int); int edit_policy (const char *, char **, int *, int); void time_t2str(time_t, char *, size_t, int); int str2time_t (const char *, time_t *); int parse_timet (const char *, krb5_timestamp *, int *, int); int edit_timet (const char *, krb5_timestamp *, int *, int); void deltat2str(unsigned, char *, size_t); int str2deltat(const char *, krb5_deltat *); int parse_deltat (const char *, krb5_deltat *, int *, int); int edit_deltat (const char *, krb5_deltat *, int *, int); int edit_entry(kadm5_principal_ent_t, int *, kadm5_principal_ent_t, int); void set_defaults(kadm5_principal_ent_t, int *, kadm5_principal_ent_t, int); int set_entry(krb5_context, kadm5_principal_ent_t, int *, const char *, const char *, const char *, const char *, const char *, const char *); int foreach_principal(const char *, int (*)(krb5_principal, void*), const char *, void *); int parse_des_key (const char *, krb5_key_data *, const char **); /* random_password.c */ void random_password(char *, size_t); /* kadm_conn.c */ extern sig_atomic_t term_flag, doing_useful_work; void parse_ports(krb5_context, const char*); void start_server(krb5_context, const char*); /* server.c */ krb5_error_code kadmind_loop (krb5_context, krb5_keytab, int); /* rpc.c */ int handle_mit(krb5_context, void *, size_t, int); #endif /* __ADMIN_LOCL_H__ */ heimdal-7.5.0/kadmin/cpw.c0000644000175000017500000001215113212137553013454 0ustar niknik/* * Copyright (c) 1997 - 2004 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "kadmin_locl.h" #include "kadmin-commands.h" struct cpw_entry_data { int keepold; int random_key; int random_password; char *password; krb5_key_data *key_data; }; static int set_random_key (krb5_principal principal, int keepold) { krb5_error_code ret; int i; krb5_keyblock *keys; int num_keys; ret = kadm5_randkey_principal_3(kadm_handle, principal, keepold, 0, NULL, &keys, &num_keys); if(ret) return ret; for(i = 0; i < num_keys; i++) krb5_free_keyblock_contents(context, &keys[i]); free(keys); return 0; } static int set_random_password (krb5_principal principal, int keepold) { krb5_error_code ret; char pw[128]; random_password (pw, sizeof(pw)); ret = kadm5_chpass_principal_3(kadm_handle, principal, keepold, 0, NULL, pw); if (ret == 0) { char *princ_name; krb5_unparse_name(context, principal, &princ_name); printf ("%s's password set to \"%s\"\n", princ_name, pw); free (princ_name); } memset (pw, 0, sizeof(pw)); return ret; } static int set_password (krb5_principal principal, char *password, int keepold) { krb5_error_code ret = 0; char pwbuf[128]; int aret; if(password == NULL) { char *princ_name; char *prompt; ret = krb5_unparse_name(context, principal, &princ_name); if (ret) return ret; aret = asprintf(&prompt, "%s's Password: ", princ_name); free (princ_name); if (aret == -1) return ENOMEM; ret = UI_UTIL_read_pw_string(pwbuf, sizeof(pwbuf), prompt, 1); free (prompt); if(ret){ return 0; /* XXX error code? */ } password = pwbuf; } if(ret == 0) ret = kadm5_chpass_principal_3(kadm_handle, principal, keepold, 0, NULL, password); memset(pwbuf, 0, sizeof(pwbuf)); return ret; } static int set_key_data (krb5_principal principal, krb5_key_data *key_data, int keepold) { krb5_error_code ret; ret = kadm5_chpass_principal_with_key_3(kadm_handle, principal, keepold, 3, key_data); return ret; } static int do_cpw_entry(krb5_principal principal, void *data) { struct cpw_entry_data *e = data; if (e->random_key) return set_random_key (principal, e->keepold); else if (e->random_password) return set_random_password (principal, e->keepold); else if (e->key_data) return set_key_data (principal, e->key_data, e->keepold); else return set_password (principal, e->password, e->keepold); } int cpw_entry(struct passwd_options *opt, int argc, char **argv) { krb5_error_code ret = 0; int i; struct cpw_entry_data data; int num; krb5_key_data key_data[3]; data.keepold = opt->keepold_flag; data.random_key = opt->random_key_flag; data.random_password = opt->random_password_flag; data.password = opt->password_string; data.key_data = NULL; num = 0; if (data.random_key) ++num; if (data.random_password) ++num; if (data.password) ++num; if (opt->key_string) ++num; if (num > 1) { fprintf (stderr, "give only one of " "--random-key, --random-password, --password, --key\n"); return 1; } if (opt->key_string) { const char *error; if (parse_des_key (opt->key_string, key_data, &error)) { fprintf (stderr, "failed parsing key \"%s\": %s\n", opt->key_string, error); return 1; } data.key_data = key_data; } for(i = 0; i < argc; i++) ret = foreach_principal(argv[i], do_cpw_entry, "cpw", &data); if (data.key_data) { int16_t dummy; kadm5_free_key_data (kadm_handle, &dummy, key_data); } return ret != 0; } heimdal-7.5.0/kadmin/kadmin-version.rc0000644000175000017500000000323412136107747016003 0ustar niknik/*********************************************************************** * Copyright (c) 2010, Secure Endpoints Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * - Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. * **********************************************************************/ #define RC_FILE_TYPE VFT_APP #define RC_FILE_DESC_0409 "Kerberos Administration Tool" #define RC_FILE_ORIG_0409 "kadmin.exe" #include "../windows/version.rc" heimdal-7.5.0/kadmin/dump.c0000644000175000017500000000556613026237312013641 0ustar niknik/* * Copyright (c) 1997-2004 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "kadmin_locl.h" #include "kadmin-commands.h" #include extern int local_flag; int dump(struct dump_options *opt, int argc, char **argv) { krb5_error_code ret; FILE *f; struct hdb_print_entry_arg parg; HDB *db = NULL; if (!local_flag) { krb5_warnx(context, "dump is only available in local (-l) mode"); return 0; } db = _kadm5_s_get_db(kadm_handle); if (argc == 0) f = stdout; else f = fopen(argv[0], "w"); if (f == NULL) { krb5_warn(context, errno, "open: %s", argv[0]); goto out; } ret = db->hdb_open(context, db, O_RDONLY, 0600); if (ret) { krb5_warn(context, ret, "hdb_open"); goto out; } if (!opt->format_string || strcmp(opt->format_string, "Heimdal") == 0) { parg.fmt = HDB_DUMP_HEIMDAL; } else if (opt->format_string && strcmp(opt->format_string, "MIT") == 0) { parg.fmt = HDB_DUMP_MIT; fprintf(f, "kdb5_util load_dump version 5\n"); /* 5||6, either way */ } else { krb5_errx(context, 1, "Supported dump formats: Heimdal and MIT"); } parg.out = f; hdb_foreach(context, db, opt->decrypt_flag ? HDB_F_DECRYPT : 0, hdb_print_entry, &parg); db->hdb_close(context, db); out: if(f && f != stdout) fclose(f); return 0; } heimdal-7.5.0/kadmin/add_enctype.c0000644000175000017500000001245413026237312015145 0ustar niknik/* * Copyright (c) 1999-2006 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "kadmin_locl.h" #include "kadmin-commands.h" /* * del_enctype principal enctypes... */ int add_enctype(struct add_enctype_options*opt, int argc, char **argv) { kadm5_principal_ent_rec princ; krb5_principal princ_ent = NULL; krb5_error_code ret; const char *princ_name; int i, j; krb5_key_data *new_key_data; int n_etypes; krb5_enctype *etypes; if (!opt->random_key_flag) { krb5_warnx (context, "only random key is supported now"); return 0; } memset(&princ, 0, sizeof(princ)); princ_name = argv[0]; n_etypes = argc - 1; etypes = malloc (n_etypes * sizeof(*etypes)); if (etypes == NULL) { krb5_warnx (context, "out of memory"); return 0; } argv++; for (i = 0; i < n_etypes; ++i) { ret = krb5_string_to_enctype(context, argv[i], &etypes[i]); if (ret) { krb5_warnx (context, "bad enctype \"%s\"", argv[i]); goto out2; } } ret = krb5_parse_name(context, princ_name, &princ_ent); if (ret) { krb5_warn(context, ret, "krb5_parse_name %s", princ_name); goto out2; } /* The principal might have zero keys, but it will still have a kvno! */ ret = kadm5_get_principal(kadm_handle, princ_ent, &princ, KADM5_KVNO | KADM5_PRINCIPAL | KADM5_KEY_DATA); if (ret) { krb5_free_principal(context, princ_ent); krb5_warnx(context, "no such principal: %s", princ_name); goto out2; } /* Check that we got key data */ if (kadm5_all_keys_are_bogus(princ.n_key_data, princ.key_data)) { krb5_warnx(context, "user lacks get-keys privilege"); goto out; } new_key_data = calloc(princ.n_key_data + n_etypes, sizeof(*new_key_data)); if (new_key_data == NULL) { krb5_warnx (context, "out of memory"); goto out; } for (i = 0; i < princ.n_key_data; ++i) { krb5_key_data *key = &princ.key_data[i]; for (j = 0; j < n_etypes; ++j) { if (etypes[j] == key->key_data_type[0]) { /* XXX Should this be an error? The admin can del_enctype... */ krb5_warnx(context, "enctype %d already exists", (int)etypes[j]); free(new_key_data); goto out; } } new_key_data[i] = *key; } for (i = 0; i < n_etypes; ++i) { int n = princ.n_key_data + i; krb5_keyblock keyblock; memset(&new_key_data[n], 0, sizeof(new_key_data[n])); new_key_data[n].key_data_ver = 2; new_key_data[n].key_data_kvno = princ.kvno; ret = krb5_generate_random_keyblock (context, etypes[i], &keyblock); if (ret) { krb5_warnx(context, "genernate enctype %d failed", (int)etypes[i]); while (--i >= 0) free(new_key_data[--n].key_data_contents[0]); goto out; } /* key */ new_key_data[n].key_data_type[0] = etypes[i]; new_key_data[n].key_data_contents[0] = malloc(keyblock.keyvalue.length); if (new_key_data[n].key_data_contents[0] == NULL) { ret = ENOMEM; krb5_warn(context, ret, "out of memory"); while (--i >= 0) free(new_key_data[--n].key_data_contents[0]); goto out; } new_key_data[n].key_data_length[0] = keyblock.keyvalue.length; memcpy(new_key_data[n].key_data_contents[0], keyblock.keyvalue.data, keyblock.keyvalue.length); krb5_free_keyblock_contents(context, &keyblock); /* salt */ new_key_data[n].key_data_type[1] = KRB5_PW_SALT; new_key_data[n].key_data_length[1] = 0; new_key_data[n].key_data_contents[1] = NULL; } free (princ.key_data); princ.n_key_data += n_etypes; princ.key_data = new_key_data; new_key_data = NULL; ret = kadm5_modify_principal (kadm_handle, &princ, KADM5_KEY_DATA); if (ret) krb5_warn(context, ret, "kadm5_modify_principal"); out: krb5_free_principal (context, princ_ent); kadm5_free_principal_ent(kadm_handle, &princ); out2: free (etypes); return ret != 0; } heimdal-7.5.0/kadmin/ChangeLog0000644000175000017500000007042212136107747014304 0ustar niknik2008-04-07 Love Hörnquist Åstrand * kadm_conn.c: Use unsigned where appropriate. 2007-12-09 Love Hörnquist Åstrand * kadmin.c: Use hdb_db_dir(). * kadmind.c: Use hdb_db_dir(). 2007-07-26 Love Hörnquist Åstrand * util.c: Clear error string, just to be sure. 2007-05-10 Love Hörnquist Åstrand * kadmin-commands.in: modify --pkinit-acl * mod.c: add pk-init command 2007-02-22 Love Hörnquist Åstrand * kadmin.8: document kadmin add_enctype functionallity. * Makefile.am: Add new command, add_enctype. * kadmin-commands.in: Add new command, add_enctype. * add_enctype.c: Add support for adding a random key enctype to a principal. 2007-02-17 Love Hörnquist Åstrand * mod.c: add setting and displaying aliases * get.c: add setting and displaying aliases * kadmin-commands.in: add setting and displaying aliases 2006-12-22 Love Hörnquist Åstrand * util.c: Make str2time_t parser more robust. * Makefile.am: Add test_util test program. * test_util.c: Test str2time_t parser. 2006-12-05 Love Hörnquist Åstrand * add-random-users.c: Use strcspn to remove \n from fgets result. Prompted by change by Ray Lai of OpenBSD via Björn Sandell. 2006-10-22 Love Hörnquist Åstrand * mod.c: Try to not leak memory. * check.c: Try to not leak memory. 2006-10-07 Love Hörnquist Åstrand * Makefile.am: split build files into dist_ and noinst_ SOURCES 2006-08-28 Love Hörnquist Åstrand * kadmin.c (help): use sl_slc_help(). 2006-08-24 Love Hörnquist Åstrand * util.c: Add KRB5_KDB_ALLOW_DIGEST 2006-07-14 Love Hörnquist Åstrand * get.c (format_field): optionally print issuer and anchor. 2006-06-21 Love Hörnquist Åstrand * check.c: Check if afs@REALM and afs/cellname@REALM both exists. 2006-06-14 Love Hörnquist Åstrand * util.c (kdb_attrs): Add KRB5_KDB_ALLOW_KERBEROS4 2006-06-07 Love Hörnquist Åstrand * mod.c (do_mod_entry): Add setting 1 delegation entry 2006-06-01 Love Hörnquist Åstrand * server.c: Less shadowing. 2006-05-13 Love Hörnquist Åstrand * Makefile.am: kadmin_SOURCES += add check.c * kadmin_locl.h: Avoid shadowing. * kadmin.8: Document the new check command. * kadmin-commands.in: Add check command * check.c: Check database for strange configurations on default principals. 2006-05-08 Love Hörnquist Åstrand * server.c (kadm_get_privs): one less "pointer targets in passing argument differ in signedness" warning. 2006-05-05 Love Hörnquist Åstrand * dump-format.txt: Moved to info documentation. * Rename u_intXX_t to uintXX_t 2006-05-01 Love Hörnquist Åstrand * kadmin.8: spelling, update .Dd 2006-04-12 Love Hörnquist Åstrand * add-random-users.c: Catch empty file case. From Tobias Stoeckmann. 2006-04-07 Love Hörnquist Åstrand * random_password.c (generate_password): memory leak in error condition case From Coverity NetBSD CID#1887 2006-02-19 Love Hörnquist Åstrand * cpw.c (cpw_entry): make sure ret have a defined value * del.c (del_entry): make sure ret have a defined value * mod.c: Return error code so that toplevel function can catch them. 2006-01-25 Love Hörnquist Åstrand * cpw.c (cpw_entry): return 1 on failure. * rename.c (rename_entry): return 1 on failure. * del.c (del_entry): return 1 on failure. * ank.c (add_new_key): return 1 on failure. * get.c: Add printing of pkinit-acls. Don't print password by default. Return 1 on failure processing any of the principals. * util.c (foreach_principal): If any of calls to `func' failes, the first error is returned when all principals are processed. 2005-12-01 Love Hörnquist Åstrand * kadmin-commands.in: Add ank as an alias to add, it lost in transition to slc, from Måns Nilsson. 2005-09-14 Love Hörquist Åstrand * dump-format.txt: Add extensions, fill in missing fields. 2005-09-08 Love Hörquist Åstrand * init.c (create_random_entry): create principal with random password even though its disabled. From Andrew Bartlet 2005-09-01 Love Hörquist Åstrand * kadm_conn.c: Use socket_set_reuseaddr and socket_set_ipv6only. 2005-08-11 Love Hörquist Åstrand * get.c: Remove structure that is never used (sneaked in the large TL_DATA patch). * kadmin-commands.in: Rename password-quality to verify-password-quality. * get.c: Indent. * server.c: Avoid shadowing exp(). * load.c: Parse extensions. * kadmin_locl.h: Include . * get.c: Extend struct field_name to have a subvalue and a extra_mask. Use that to implement printing of KADM5_TL_DATA options and fix a dependency bug (keys needed principal to print the salting). 2005-07-08 Love Hörquist Åstrand * lower amount of shadow and const warnings 2005-06-07 David Love * dump-format.txt: Clarify, spelling and add examples. 2005-05-30 Love Hörquist Åstrand * util.c (kdb_attrs): add ok-as-delegate * get.c (getit): init data.mask to 0. Problem found by Andrew Bartlett 2005-05-09 Love Hörquist Åstrand * kadmin.c (main): catch -2 as EOF 2005-05-03 Dave Love * init.c (init): Don't disable forwardable for kadmin/changepw. 2005-05-02 Dave Love * kadmin.c (help): Don't use non-constant initializer for `fake'. 2005-04-20 Love Hörquist Åstrand * util.c (foreach_principal): initialize ret to make sure it have a value 2005-04-04 Love Hörquist Åstrand * kadmind.c: add verifier libraries with kadm5_add_passwd_quality_verifier * kadmin.c: add verifier libraries with kadm5_add_passwd_quality_verifier * load.c: max-life and max-renew is of unsigned int in asn1 compiler, use that for the parser too 2005-03-26 Love Hörquist Åstrand * kadmin.8: List of attributes, from James F. Hranicky 2005-01-19 Love Hörquist Åstrand * dump.c (dump): handle errors 2005-01-08 Love Hörquist Åstrand * dump-format.txt: text dump format 2004-12-08 Love Hörquist Åstrand * kadmind.8: use keeps around options, from OpenBSD * kadmin.8: use keeps around options, "improve" spelling, from openbsd 2004-11-01 Love Hörquist Åstrand * get.c (getit): always free columns * ank.c (add_one_principal): catch error from UI_UTIL_read_pw_string 2004-10-31 Love Hörquist Åstrand * del_enctype.c (del_enctype): fix off-by-one error in del_enctype From: 2004-08-13 Love Hörquist Åstrand * get.c: print keytypes on long format 2004-07-06 Love Hörquist Åstrand * get.c (format_field): allow mod_name to be optional * ext.c (do_ext_keytab): if there isn't any keydata, try using kadm5_randkey_principal 2004-07-02 Love Hörquist Åstrand * load.c: make merge/load work again * del.c: fix usage string * ank.c: fix slc lossage 2004-06-28 Love Hörquist Åstrand * kadmin.c: use kadm5_ad_init_with_password_ctx 2004-06-27 Johan Danielsson * kadmin.8: document get -o and stash * get.c: implement output column selection, similar to ps -o * kadmin-commands.in: make get -l the default again, and add column selection flag; sync list with get 2004-06-24 Johan Danielsson * kadmin-commands.in: mod needs default kvno of -1 2004-06-21 Johan Danielsson * kadmin: convert to use slc; also add stash subcommand 2004-06-15 Love Hörquist Åstrand * kadmin.c (main): keytab mode requires principal name 2004-06-12 Love Hörquist Åstrand * kadmind.c: drop keyfile, not used, found by Elrond * kadmin.c: if keyfile is set, pass in to libkadm5 bug pointed out by Elrond 2004-05-31 Love Hörquist Åstrand * kadmin.c: add --ad flag, XXX rewrite the init kadm5 interface 2004-05-13 Johan Danielsson * nuke kerberos 4 kadmin goo 2004-05-07 Johan Danielsson * util.c (str2time_t): fix end-of-day logic, from Duncan McEwan/Mark Davies. 2004-04-29 Love Hörquist Åstrand * version4.c (handle_v4): make sure length is longer then 2, Pointed out by Evgeny Demidov * kadmind.c: make kerberos4 support default turned off 2004-03-24 Johan Danielsson * kadmin.8: update manpage * mod.c: allow wildcarding principals, and make parameters a work same as if prompted 2004-03-08 Love Hörquist Åstrand * kadmin.8: document password-quality * kadmin_locl.h: add prototype for password_quality * kadmin.c: add password-quality/pwq command * Makefile.am: kadmin_SOURCES += pw_quality.c * pw_quality.c: test run the password quality function 2004-03-07 Love Hörquist Åstrand * ank.c (add_one_principal): even though the principal is disabled (creation of random key/keydata), create it with a random password 2003-12-07 Love Hörquist Åstrand * init.c (create_random_entry): print error message on failure * ank.c (add_one_principal): pass right argument to kadm5_free_principal_ent From Panasas, Inc 2003-11-18 Love Hörquist Åstrand * kadmind.c (main): move opening the logfile to after reading kdc.conf move the loading of hdb keytab ops closer to where its used From: Jeffrey Hutzelman 2003-10-04 Love Hörquist Åstrand * util.c (str2time_t): allow whitespace between date and time From: Bob Beck and adharw@yahoo.com 2003-09-03 Love Hörquist Åstrand * ank.c: s/des_read_pw_string/UI_UTIL_read_pw_string/ * cpw.c: s/des_read_pw_string/UI_UTIL_read_pw_string/ 2003-08-21 Love Hörquist Åstrand * get.c (print_entry_terse): handle error when unparsing name 2003-08-18 Love Hörquist Åstrand * kadmind.c (main): use krb5_prepend_config_files_default, now all options in kdc.conf is parsed, not just [kdc]key-file= * kadmin.c (main): use krb5_prepend_config_files_default, now all options in kdc.conf is parsed, not just [kdc]key-file= 2003-04-14 Love Hörquist Åstrand * util.c: cast argument to tolower to unsigned char, from Christian Biere via NetBSD 2003-04-06 Love Hörquist Åstrand * kadmind.8: s/kerberos/Kerberos/ 2003-03-31 Love Hörquist Åstrand * kadmin.8: initialises -> initializes, from Perry E. Metzger" * kadmin.c: principal, not pricipal. From Thomas Klausner 2003-02-04 Love Hörquist Åstrand * kadmind.8: spelling, from jmc * kadmin.8: spelling, from jmc 2003-01-29 Love Hörquist Åstrand * server.c (kadmind_dispatch): kadm_chpass: require the password to pass the password quality check in case the user changes the user's own password kadm_chpass_with_key: disallow the user to change it own password to a key, since that password might violate the password quality check. 2002-12-03 Johan Danielsson * util.c (get_response): print a newline if interrupted * mod.c (mod_entry): check return value from edit_entry * ank.c (add_one_principal): check return value from edit_entry * ank.c (add_one_principal): don't continue if create_principal fails * init.c: check return value from edit_deltat * init.c: add --help 2002-10-29 Johan Danielsson * version4.c: speling (from Tomas Olsson) 2002-10-23 Assar Westerlund * version4.c (decode_packet): check the length of the version string and that rlen has a reasonable value 2002-10-21 Johan Danielsson * version4.c: check size of rlen 2002-09-10 Johan Danielsson * server.c: constify match_appl_version() * version4.c: change some lingering krb_err_base 2002-09-09 Jacques Vidrine * server.c (kadmind_dispatch): while decoding arguments for kadm_chpass_with_key, sanity check the number of keys given. Potential problem pointed out by Sebastian Krahmer . 2002-09-04 Johan Danielsson * load.c (parse_generation): return if there is no generation (spotted by Daniel Kouril) 2002-06-07 Jacques Vidrine * ank.c: do not attempt to free uninitialized pointer when kadm5_randkey_principal fails. 2002-06-07 Johan Danielsson * util.c: remove unused variable; reported by Hans Insulander 2002-03-05 Johan Danielsson * kadmind.8: clarify some acl wording, and add an example file 2002-02-11 Johan Danielsson * ext.c: no need to use the "modify" keytab anymore 2001-09-20 Assar Westerlund * add-random-users.c: allocate several buffers for the list of words, instead of one strdup per word (running under efence does not work very well otherwise) 2001-09-13 Assar Westerlund * add-random-users.c: allow specifying the number of users to create 2001-08-24 Assar Westerlund * Makefile.am: rename variable name to avoid error from current automake 2001-08-22 Assar Westerlund * kadmin_locl.h: include libutil.h if it exists 2001-08-10 Johan Danielsson * util.c: do something to handle C-c in prompts * load.c: remove unused etypes code, and add parsing of the generation field * ank.c: add a --use-defaults option to just use default values without questions * kadmin.c: add "del" alias for delete * cpw.c: call this operation "passwd" in usage * kadmin_locl.h: prototype for set_defaults * util.c (edit_entry): move setting of default values to a separate function, set_defaults 2001-08-01 Johan Danielsson * kadmin.c: print help message on bad options 2001-07-31 Assar Westerlund * add-random-users.c (main): handle --version 2001-07-30 Johan Danielsson * load.c: increase line buffer to 8k 2001-06-12 Assar Westerlund * ext.c (ext_keytab): use the default modify keytab per default 2001-05-17 Assar Westerlund * kadm_conn.c (start_server): fix krb5_eai_to_heim_errno call 2001-05-15 Assar Westerlund * kadmin.c (main): some error cleaning required 2001-05-14 Assar Westerlund * kadmind.c: new krb5_config_parse_file * kadmin.c: new krb5_config_parse_file * kadm_conn.c: update to new krb5_sockaddr2address 2001-05-07 Assar Westerlund * kadmin_locl.h (foreach_principal): update prototype * get.c (getit): new foreach_principal * ext.c (ext_keytab): new foreach_principal * del.c (del_entry): new foreach_principal * cpw.c (cpw_entry): new foreach_principal * util.c (foreach_principal): add `funcname' and try printing the error string 2001-05-04 Johan Danielsson * rename.c: fix argument number test 2001-04-19 Johan Danielsson * del_enctype.c: fix argument count check after getarg change; spotted by mark@MCS.VUW.AC.NZ 2001-02-15 Assar Westerlund * kadmind.c (main): use a `struct sockaddr_storage' to be able to store all types of addresses 2001-02-07 Assar Westerlund * kadmin.c: add --keytab / _K, from Leif Johansson 2001-01-29 Assar Westerlund * kadm_conn.c (spawn_child): close the newly created socket in the packet, it's not used. from * version4.c (decode_packet): check success of krb5_425_conv_principal. from 2001-01-12 Assar Westerlund * util.c (parse_attributes): make empty string mean no attributes, specifying the empty string at the command line should give you no attributes, but just pressing return at the prompt gives you default attributes (edit_entry): only pick up values from the default principal if they aren't set in the principal being edited 2001-01-04 Assar Westerlund * load.c (doit): print an error and bail out if storing an entry in the database fails. The most likely reason for it failing is out-of-space. 2000-12-31 Assar Westerlund * kadmind.c (main): handle krb5_init_context failure consistently * kadmin.c (main): handle krb5_init_context failure consistently * add-random-users.c (add_user): handle krb5_init_context failure consistently * kadm_conn.c (spawn_child): use a struct sockaddr_storage 2000-12-15 Johan Danielsson * get.c: avoid asprintf'ing NULL strings 2000-12-14 Johan Danielsson * load.c: fix option parsing 2000-11-16 Assar Westerlund * kadm_conn.c (wait_for_connection): check for fd's being too large to select on 2000-11-09 Johan Danielsson * get.c: don't try to print modifier name if it isn't set (from Jacques A. Vidrine" ) 2000-09-19 Assar Westerlund * server.c (kadmind_loop): send in keytab to v4 handling function * version4.c: allow the specification of what keytab to use * get.c (print_entry_long): actually print the actual saltvalue used if it's not the default 2000-09-10 Johan Danielsson * kadmin.c: add option parsing, and add `privs' as an alias for `privileges' * init.c: complain if there's no realm name specified * rename.c: add option parsing * load.c: add option parsing * get.c: make `get' and `list' aliases to each other, but with different defaults * del_enctype.c: add option parsing * del.c: add option parsing * ank.c: calling the command `add' make more sense from an english pov * Makefile.am: add kadmin manpage * kadmin.8: short manpage * kadmin.c: `quit' should be a alias for `exit', not `help' 2000-08-27 Assar Westerlund * server.c (handle_v5): do not try to perform stupid stunts when printing errors 2000-08-19 Assar Westerlund * util.c (str2time_t): add alias for `now'. 2000-08-18 Assar Westerlund * server.c (handle_v5): accept any kadmin/admin@* principal as the server * kadmind.c: remove extra prototype of kadmind_loop * kadmin_locl.h (kadmind_loop): add prototype * init.c (usage): print init-usage and not add-dito 2000-08-07 Johan Danielsson * kadmind.c: use roken_getsockname 2000-08-07 Assar Westerlund * kadmind.c, kadm_conn.c: use socklen_t instead of int where appropriate. From 2000-08-04 Johan Danielsson * Makefile.am: link with pidfile library * kadmind.c: write a pid file, and setup password quality functions * kadmin_locl.h: util.h 2000-07-27 Assar Westerlund * version4.c (decode_packet): be totally consistent with the prototype of des_cbc_cksum * kadmind.c: use sa_size instead of sa_len, some systems define this to emulate anonymous unions * kadm_conn.c: use sa_size instead of sa_len, some systems define this to emulate anonymous unions 2000-07-24 Assar Westerlund * kadmin.c (commands): add quit * load.c (doit): truncate the log since there's no way of knowing what changes are going to be added 2000-07-23 Assar Westerlund * util.c (str2time_t): be more careful with strptime that might zero out the `struct tm' 2000-07-22 Johan Danielsson * kadm_conn.c: make the parent process wait for children and terminate after receiving a signal, also terminate on SIGINT 2000-07-22 Assar Westerlund * version4.c: map both princ_expire_time and pw_expiration to v4 principal expiration 2000-07-22 Johan Danielsson * version4.c (handle_v4): check for termination * server.c (v5_loop): check for termination * kadm_conn.c (wait_term): if we're doing something, set just set a flag otherwise exit rightaway * server.c: use krb5_read_priv_message; (v5_loop): check for EOF 2000-07-21 Assar Westerlund * kadm_conn.c: remove sys/select.h. make signal handlers type-correct and static * kadmin_locl.h: add limits.h and sys/select.h 2000-07-20 Assar Westerlund * init.c (init): also create `kadmin/hprop' * kadmind.c: ports is a string argument * kadm_conn.c (start_server): fix printf format * kadmin_locl.h: add * kadm_conn.c: remove sys/select.h. make signal handlers type-correct and static * kadmin_locl.h: add limits.h and sys/select.h 2000-07-17 Johan Danielsson * kadm_conn.c: put all processes in a new process group * server.c (v5_loop): use krb5_{read,write}_priv_message 2000-07-11 Johan Danielsson * version4.c: change log strings to match the v5 counterparts * mod.c: allow setting kvno * kadmind.c: if stdin is not a socket create and listen to sockets * kadm_conn.c: socket creation functions * util.c (deltat2str): treat 0 and INT_MAX as never 2000-07-08 Assar Westerlund * Makefile.am (INCLUDES): add ../lib/krb5 * kadmin_locl.h: add krb5_locl.h (since we just use some stuff from there) 2000-06-07 Assar Westerlund * add-random-users.c: new testing program that adds a number of randomly generated users 2000-04-12 Assar Westerlund * cpw.c (do_cpw_entry): call set_password if no argument is given, it will prompt for the password. * kadmin.c: make help only print the commands that are actually available. 2000-04-03 Assar Westerlund * del_enctype.c (del_enctype): set ignore correctly 2000-04-02 Assar Westerlund * kadmin.c (main): make parse errors a fatal error * init.c (init): create changepw/kerberos with disallow-tgt and pwchange attributes 2000-03-23 Assar Westerlund * util.c (hex2n, parse_des_key): add * server.c (kadmind_dispatch): add kadm_chpass_with_key * cpw.c: add --key * ank.c: add --key 2000-02-16 Assar Westerlund * load.c (doit): check return value from parse_hdbflags2int correctly 2000-01-25 Assar Westerlund * load.c: checking all parsing for errors and all memory allocations also 2000-01-02 Assar Westerlund * server.c: check initial flag in ticket and allow users to change their own password if it's set * ext.c (do_ext_keytab): set timestamp 1999-12-14 Assar Westerlund * del_enctype.c (usage): don't use arg_printusage 1999-11-25 Assar Westerlund * del_enctype.c (del_enctype): try not to leak memory * version4.c (kadm_ser_mod): use kadm5_s_modify_principal (no _with_key) * kadmin.c: add `del_enctype' * del_enctype.c (del_enctype): new function for deleting enctypes from a principal * Makefile.am (kadmin_SOURCES): add del_enctype.c 1999-11-09 Johan Danielsson * server.c: cope with old clients * kadmin_locl.h: remove version string 1999-10-17 Assar Westerlund * Makefile.am (kadmin_LDADD): add LIB_dlopen 1999-10-01 Assar Westerlund * ank.c (add_one_principal): `password' can cactually be NULL in the overwrite code, check for it. 1999-09-20 Assar Westerlund * mod.c (mod_entry): print the correct principal name in error messages. From Love 1999-09-10 Assar Westerlund * init.c (init): also create `changepw/kerberos' * version4.c: only create you loose packets when we fail decoding and not when an operation is not performed for some reason (decode_packet): read the service key from the hdb (dispatch, decode_packet): return proper error messages * version4.c (kadm_ser_cpw): add password quality functions 1999-08-27 Johan Danielsson * server.c (handle_v5): give more informative message if KRB5_KT_NOTFOUND 1999-08-26 Johan Danielsson * kadmind.c: use HDB keytabs 1999-08-25 Assar Westerlund * cpw.c (set_password): use correct variable. From Love * server.c (v5_loop): use correct error code * ank.c (add_one_principal): initialize `default_ent' 1999-08-21 Assar Westerlund * random_password.c: new file, stolen from krb4 * kadmin_locl.h: add prototype for random_password * cpw.c: add support for --random-password * ank.c: add support for --random-password * Makefile.am (kadmin_SOURCES): add random_password.c 1999-08-19 Assar Westerlund * util.c (edit_timet): break when we manage to parse the time not the inverse. * mod.c: add parsing of lots of options. From Love * ank.c: add setting of expiration and password expiration * kadmin_locl.h: update util.c prototypes * util.c: move-around. clean-up, rename, make consistent (and some other weird stuff). based on patches from Love * version4.c (kadm_ser_cpw): initialize password (handle_v4): remove unused variable `ret' 1999-08-16 Assar Westerlund * version4.c (handle_v4): more error checking and more correct error messages * server.c (v5_loop, kadmind_loop): more error checking and more correct error messages 1999-07-24 Assar Westerlund * util.c (str2timeval, edit_time): functions for parsing and editing times. Based on patches from Love . (edit_entry): call new functions * mod.c (mod_entry): allow modifying expiration times * kadmin_locl.h (str2timeval): add prototype * ank.c (add_one_principal): allow setting expiration times 1999-07-03 Assar Westerlund * server.c (v5_loop): handle data allocation with krb5_data_alloc and check return value 1999-06-23 Assar Westerlund * version4.c (kadm_ser_cpw): read the key in the strange order it's sent * util.c (edit_entry): look at default (edit_time): always set mask even if value == 0 * kadmin_locl.h (edit_entry): update * ank.c: make ank use the values of the default principal for prompting * version4.c (values_to_ent): convert key data correctly 1999-05-23 Assar Westerlund * init.c (create_random_entry): more correct setting of mask 1999-05-21 Assar Westerlund * server.c (handle_v5): read sendauth version correctly. 1999-05-14 Assar Westerlund * version4.c (error_code): try to handle really old krb4 distributions 1999-05-11 Assar Westerlund * init.c (init): initialize realm_max_life and realm_max_rlife 1999-05-07 Assar Westerlund * ank.c (add_new_key): initialize more variables 1999-05-04 Assar Westerlund * version4.c (kadm_ser_cpw): always allow a user to change her password (kadm_ser_*): make logging work clean-up and restructure * kadmin_locl.h (set_entry): add prototype * kadmin.c (usage): update usage string * init.c (init): new arguments realm-max-ticket-life and realm-max-renewable-life * util.c (edit_time, edit_attributes): don't do anything if it's already set (set_entry): new function * ank.c (add_new_key): new options for setting max-ticket-life, max-renewable-life, and attributes * server.c (v5_loop): remove unused variable * kadmin_locl.h: add prototypes * version4.c: re-insert krb_err.h and other miss * server.c (kadmind_loop): break-up and restructure * version4.c: add ACL checks more error code checks restructure 1999-05-03 Johan Danielsson * load.c: check for (un-)encrypted keys * dump.c: use hdb_print_entry * version4.c: version 4 support * Makefile.am: link with krb4 * kadmin_locl.h: include * server.c: move from lib/kadm5, and add basic support for krb4 kadmin protocol * kadmind.c: move recvauth to kadmind_loop() heimdal-7.5.0/kadmin/kadmind.80000644000175000017500000001073213026237312014217 0ustar niknik.\" Copyright (c) 2002 - 2004 Kungliga Tekniska Högskolan .\" (Royal Institute of Technology, Stockholm, Sweden). .\" All rights reserved. .\" .\" Redistribution and use in source and binary forms, with or without .\" modification, are permitted provided that the following conditions .\" are met: .\" .\" 1. Redistributions of source code must retain the above copyright .\" notice, this list of conditions and the following disclaimer. .\" .\" 2. Redistributions in binary form must reproduce the above copyright .\" notice, this list of conditions and the following disclaimer in the .\" documentation and/or other materials provided with the distribution. .\" .\" 3. Neither the name of the Institute nor the names of its contributors .\" may be used to endorse or promote products derived from this software .\" without specific prior written permission. .\" .\" THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND .\" ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE .\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE .\" ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE .\" FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL .\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS .\" OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) .\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT .\" LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF .\" SUCH DAMAGE. .\" .\" $Id$ .\" .Dd December 8, 2004 .Dt KADMIND 8 .Os HEIMDAL .Sh NAME .Nm kadmind .Nd "server for administrative access to Kerberos database" .Sh SYNOPSIS .Nm .Bk -words .Oo Fl c Ar file \*(Ba Xo .Fl Fl config-file= Ns Ar file .Xc .Oc .Oo Fl k Ar file \*(Ba Xo .Fl Fl key-file= Ns Ar file .Xc .Oc .Op Fl Fl keytab= Ns Ar keytab .Oo Fl r Ar realm \*(Ba Xo .Fl Fl realm= Ns Ar realm .Xc .Oc .Op Fl d | Fl Fl debug .Oo Fl p Ar port \*(Ba Xo .Fl Fl ports= Ns Ar port .Xc .Oc .Ek .Sh DESCRIPTION .Nm listens for requests for changes to the Kerberos database and performs these, subject to permissions. When starting, if stdin is a socket it assumes that it has been started by .Xr inetd 8 , otherwise it behaves as a daemon, forking processes for each new connection. The .Fl Fl debug option causes .Nm to accept exactly one connection, which is useful for debugging. .Pp The .Xr kpasswdd 8 daemon is responsible for the Kerberos 5 password changing protocol (used by .Xr kpasswd 1 ) . .Pp This daemon should only be run on the master server, and not on any slaves. .Pp Principals are always allowed to change their own password and list their own principal. Apart from that, doing any operation requires permission explicitly added in the ACL file .Pa /var/heimdal/kadmind.acl . The format of this file is: .Bd -ragged .Va principal .Va rights .Op Va principal-pattern .Ed .Pp Where rights is any (comma separated) combination of: .Bl -bullet -compact .It change-password or cpw .It list .It delete .It modify .It add .It get .It get-keys .It all .El .Pp And the optional .Ar principal-pattern restricts the rights to operations on principals that match the glob-style pattern. .Pp Supported options: .Bl -tag -width Ds .It Fl c Ar file , Fl Fl config-file= Ns Ar file location of config file .It Fl k Ar file , Fl Fl key-file= Ns Ar file location of master key file .It Fl Fl keytab= Ns Ar keytab what keytab to use .It Fl r Ar realm , Fl Fl realm= Ns Ar realm realm to use .It Fl d , Fl Fl debug enable debugging .It Fl p Ar port , Fl Fl ports= Ns Ar port ports to listen to. By default, if run as a daemon, it listens to port 749, but you can add any number of ports with this option. The port string is a whitespace separated list of port specifications, with the special string .Dq + representing the default port. .El .\".Sh ENVIRONMENT .Sh FILES .Pa /var/heimdal/kadmind.acl .Sh EXAMPLES This will cause .Nm to listen to port 4711 in addition to any compiled in defaults: .Pp .D1 Nm Fl Fl ports Ns Li "=\*[q]+ 4711\*[q] &" .Pp This acl file will grant Joe all rights, and allow Mallory to view and add host principals, as well as extract host principal keys (e.g., into keytabs). .Bd -literal -offset indent joe/admin@EXAMPLE.COM all mallory/admin@EXAMPLE.COM add,get-keys host/*@EXAMPLE.COM .Ed .\".Sh DIAGNOSTICS .Sh SEE ALSO .Xr kpasswd 1 , .Xr kadmin 1 , .Xr kdc 8 , .Xr kpasswdd 8 heimdal-7.5.0/kadmin/server.c0000644000175000017500000006051413026237312014174 0ustar niknik/* * Copyright (c) 1997 - 2005 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "kadmin_locl.h" #include static kadm5_ret_t check_aliases(kadm5_server_context *, kadm5_principal_ent_rec *, kadm5_principal_ent_rec *); static kadm5_ret_t kadmind_dispatch(void *kadm_handlep, krb5_boolean initial, krb5_data *in, krb5_data *out) { kadm5_ret_t ret; int32_t cmd, mask, tmp; kadm5_server_context *contextp = kadm_handlep; char client[128], name[128], name2[128]; const char *op = ""; krb5_principal princ, princ2; kadm5_principal_ent_rec ent, ent_prev; char *password = NULL, *expression; krb5_keyblock *new_keys; krb5_key_salt_tuple *ks_tuple = NULL; krb5_boolean keepold = FALSE; int n_ks_tuple = 0; int n_keys; char **princs; int n_princs; int keys_ok = 0; krb5_storage *sp; int len; krb5_unparse_name_fixed(contextp->context, contextp->caller, client, sizeof(client)); sp = krb5_storage_from_data(in); if (sp == NULL) krb5_errx(contextp->context, 1, "out of memory"); krb5_ret_int32(sp, &cmd); switch(cmd){ case kadm_get:{ op = "GET"; ret = krb5_ret_principal(sp, &princ); if(ret) goto fail; ret = krb5_ret_int32(sp, &mask); if(ret){ krb5_free_principal(contextp->context, princ); goto fail; } mask |= KADM5_PRINCIPAL; krb5_unparse_name_fixed(contextp->context, princ, name, sizeof(name)); krb5_warnx(contextp->context, "%s: %s %s", client, op, name); /* If the caller doesn't have KADM5_PRIV_GET, we're done. */ ret = _kadm5_acl_check_permission(contextp, KADM5_PRIV_GET, princ); if (ret) { krb5_free_principal(contextp->context, princ); goto fail; } /* Then check to see if it is ok to return keys */ if ((mask & KADM5_KEY_DATA) != 0) { ret = _kadm5_acl_check_permission(contextp, KADM5_PRIV_GET_KEYS, princ); if (ret == 0) { keys_ok = 1; } else if ((mask == (KADM5_PRINCIPAL|KADM5_KEY_DATA)) || (mask == (KADM5_PRINCIPAL|KADM5_KVNO|KADM5_KEY_DATA))) { /* * Requests for keys will get bogus keys, which is useful if * the client just wants to see what (kvno, enctype)s the * principal has keys for, but terrible if the client wants to * write the keys into a keytab or modify the principal and * write the bogus keys back to the server. * * We use a heuristic to detect which case we're handling here. * If the client only asks for the flags in the above * condition, then it's very likely a kadmin ext_keytab, * add_enctype, or other request that should not see bogus * keys. We deny them. * * The kadmin get command can be coaxed into making a request * with the same mask. But the default long and terse output * modes request other things too, so in all likelihood this * heuristic will not hurt any kadmin get uses. */ krb5_free_principal(contextp->context, princ); goto fail; } } ret = kadm5_get_principal(kadm_handlep, princ, &ent, mask); krb5_storage_free(sp); sp = krb5_storage_emem(); krb5_store_int32(sp, ret); if (ret == 0){ if (keys_ok) kadm5_store_principal_ent(sp, &ent); else kadm5_store_principal_ent_nokeys(sp, &ent); kadm5_free_principal_ent(kadm_handlep, &ent); } krb5_free_principal(contextp->context, princ); break; } case kadm_delete:{ op = "DELETE"; ret = krb5_ret_principal(sp, &princ); if(ret) goto fail; krb5_unparse_name_fixed(contextp->context, princ, name, sizeof(name)); krb5_warnx(contextp->context, "%s: %s %s", client, op, name); ret = _kadm5_acl_check_permission(contextp, KADM5_PRIV_DELETE, princ); if(ret){ krb5_free_principal(contextp->context, princ); goto fail; } /* * There's no need to check that the caller has permission to * delete the victim principal's aliases. */ ret = kadm5_delete_principal(kadm_handlep, princ); krb5_free_principal(contextp->context, princ); krb5_storage_free(sp); sp = krb5_storage_emem(); krb5_store_int32(sp, ret); break; } case kadm_create:{ op = "CREATE"; ret = kadm5_ret_principal_ent(sp, &ent); if(ret) goto fail; ret = krb5_ret_int32(sp, &mask); if(ret){ kadm5_free_principal_ent(kadm_handlep, &ent); goto fail; } ret = krb5_ret_string(sp, &password); if(ret){ kadm5_free_principal_ent(kadm_handlep, &ent); goto fail; } krb5_unparse_name_fixed(contextp->context, ent.principal, name, sizeof(name)); krb5_warnx(contextp->context, "%s: %s %s", client, op, name); ret = _kadm5_acl_check_permission(contextp, KADM5_PRIV_ADD, ent.principal); if(ret){ kadm5_free_principal_ent(kadm_handlep, &ent); goto fail; } if ((mask & KADM5_TL_DATA)) { /* * Also check that the caller can create the aliases, if the * new principal has any. */ ret = check_aliases(contextp, &ent, NULL); if (ret) { kadm5_free_principal_ent(kadm_handlep, &ent); goto fail; } } ret = kadm5_create_principal(kadm_handlep, &ent, mask, password); kadm5_free_principal_ent(kadm_handlep, &ent); krb5_storage_free(sp); sp = krb5_storage_emem(); krb5_store_int32(sp, ret); break; } case kadm_modify:{ op = "MODIFY"; ret = kadm5_ret_principal_ent(sp, &ent); if(ret) goto fail; ret = krb5_ret_int32(sp, &mask); if(ret){ kadm5_free_principal_ent(contextp, &ent); goto fail; } krb5_unparse_name_fixed(contextp->context, ent.principal, name, sizeof(name)); krb5_warnx(contextp->context, "%s: %s %s", client, op, name); ret = _kadm5_acl_check_permission(contextp, KADM5_PRIV_MODIFY, ent.principal); if(ret){ kadm5_free_principal_ent(contextp, &ent); goto fail; } if ((mask & KADM5_TL_DATA)) { /* * Also check that the caller can create aliases that are in * the new entry but not the old one. There's no need to * check that the caller can delete aliases it wants to * drop. See also handling of rename. */ ret = kadm5_get_principal(kadm_handlep, ent.principal, &ent_prev, mask); if (ret) { kadm5_free_principal_ent(contextp, &ent); goto fail; } ret = check_aliases(contextp, &ent, &ent_prev); kadm5_free_principal_ent(contextp, &ent_prev); if (ret) { kadm5_free_principal_ent(contextp, &ent); goto fail; } } ret = kadm5_modify_principal(kadm_handlep, &ent, mask); kadm5_free_principal_ent(kadm_handlep, &ent); krb5_storage_free(sp); sp = krb5_storage_emem(); krb5_store_int32(sp, ret); break; } case kadm_rename:{ op = "RENAME"; ret = krb5_ret_principal(sp, &princ); if(ret) goto fail; ret = krb5_ret_principal(sp, &princ2); if(ret){ krb5_free_principal(contextp->context, princ); goto fail; } krb5_unparse_name_fixed(contextp->context, princ, name, sizeof(name)); krb5_unparse_name_fixed(contextp->context, princ2, name2, sizeof(name2)); krb5_warnx(contextp->context, "%s: %s %s -> %s", client, op, name, name2); ret = _kadm5_acl_check_permission(contextp, KADM5_PRIV_ADD, princ2); if (ret == 0) { /* * Also require modify for the principal. For backwards * compatibility, allow delete permission on the old name to * cure lack of modify permission on the old name. */ ret = _kadm5_acl_check_permission(contextp, KADM5_PRIV_MODIFY, princ); if (ret) { ret = _kadm5_acl_check_permission(contextp, KADM5_PRIV_DELETE, princ); } } if(ret){ krb5_free_principal(contextp->context, princ); krb5_free_principal(contextp->context, princ2); goto fail; } ret = kadm5_rename_principal(kadm_handlep, princ, princ2); krb5_free_principal(contextp->context, princ); krb5_free_principal(contextp->context, princ2); krb5_storage_free(sp); sp = krb5_storage_emem(); krb5_store_int32(sp, ret); break; } case kadm_chpass:{ op = "CHPASS"; ret = krb5_ret_principal(sp, &princ); if (ret) goto fail; ret = krb5_ret_string(sp, &password); if (ret) { krb5_free_principal(contextp->context, princ); goto fail; } ret = krb5_ret_int32(sp, &keepold); if (ret && ret != HEIM_ERR_EOF) { krb5_free_principal(contextp->context, princ); goto fail; } krb5_unparse_name_fixed(contextp->context, princ, name, sizeof(name)); krb5_warnx(contextp->context, "%s: %s %s", client, op, name); /* * The change is allowed if at least one of: * * a) allowed by sysadmin * b) it's for the principal him/herself and this was an * initial ticket, but then, check with the password quality * function. * c) the user is on the CPW ACL. */ if (krb5_config_get_bool_default(contextp->context, NULL, TRUE, "kadmin", "allow_self_change_password", NULL) && initial && krb5_principal_compare (contextp->context, contextp->caller, princ)) { krb5_data pwd_data; const char *pwd_reason; pwd_data.data = password; pwd_data.length = strlen(password); pwd_reason = kadm5_check_password_quality (contextp->context, princ, &pwd_data); if (pwd_reason != NULL) ret = KADM5_PASS_Q_DICT; else ret = 0; } else ret = _kadm5_acl_check_permission(contextp, KADM5_PRIV_CPW, princ); if(ret) { krb5_free_principal(contextp->context, princ); goto fail; } ret = kadm5_chpass_principal_3(kadm_handlep, princ, keepold, 0, NULL, password); krb5_free_principal(contextp->context, princ); krb5_storage_free(sp); sp = krb5_storage_emem(); krb5_store_int32(sp, ret); break; } case kadm_chpass_with_key:{ int i; krb5_key_data *key_data; int n_key_data; op = "CHPASS_WITH_KEY"; ret = krb5_ret_principal(sp, &princ); if(ret) goto fail; ret = krb5_ret_int32(sp, &n_key_data); if (ret) { krb5_free_principal(contextp->context, princ); goto fail; } ret = krb5_ret_int32(sp, &keepold); if (ret && ret != HEIM_ERR_EOF) { krb5_free_principal(contextp->context, princ); goto fail; } /* n_key_data will be squeezed into an int16_t below. */ if (n_key_data < 0 || n_key_data >= 1 << 16 || (size_t)n_key_data > UINT_MAX/sizeof(*key_data)) { ret = ERANGE; krb5_free_principal(contextp->context, princ); goto fail; } key_data = malloc (n_key_data * sizeof(*key_data)); if (key_data == NULL && n_key_data != 0) { ret = ENOMEM; krb5_free_principal(contextp->context, princ); goto fail; } for (i = 0; i < n_key_data; ++i) { ret = kadm5_ret_key_data (sp, &key_data[i]); if (ret) { int16_t dummy = i; kadm5_free_key_data (contextp, &dummy, key_data); free (key_data); krb5_free_principal(contextp->context, princ); goto fail; } } krb5_unparse_name_fixed(contextp->context, princ, name, sizeof(name)); krb5_warnx(contextp->context, "%s: %s %s", client, op, name); /* * The change is only allowed if the user is on the CPW ACL, * this it to force password quality check on the user. */ ret = _kadm5_acl_check_permission(contextp, KADM5_PRIV_CPW, princ); if(ret) { int16_t dummy = n_key_data; kadm5_free_key_data (contextp, &dummy, key_data); free (key_data); krb5_free_principal(contextp->context, princ); goto fail; } ret = kadm5_chpass_principal_with_key_3(kadm_handlep, princ, keepold, n_key_data, key_data); { int16_t dummy = n_key_data; kadm5_free_key_data (contextp, &dummy, key_data); } free (key_data); krb5_free_principal(contextp->context, princ); krb5_storage_free(sp); sp = krb5_storage_emem(); krb5_store_int32(sp, ret); break; } case kadm_randkey:{ op = "RANDKEY"; ret = krb5_ret_principal(sp, &princ); if(ret) goto fail; krb5_unparse_name_fixed(contextp->context, princ, name, sizeof(name)); krb5_warnx(contextp->context, "%s: %s %s", client, op, name); /* * The change is allowed if at least one of: * a) it's for the principal him/herself and this was an initial ticket * b) the user is on the CPW ACL. */ if (initial && krb5_principal_compare (contextp->context, contextp->caller, princ)) ret = 0; else ret = _kadm5_acl_check_permission(contextp, KADM5_PRIV_CPW, princ); if(ret) { krb5_free_principal(contextp->context, princ); goto fail; } /* * See comments in kadm5_c_randkey_principal() regarding the * protocol. */ ret = krb5_ret_int32(sp, &keepold); if (ret != 0 && ret != HEIM_ERR_EOF) { krb5_free_principal(contextp->context, princ); goto fail; } ret = krb5_ret_int32(sp, &n_ks_tuple); if (ret != 0 && ret != HEIM_ERR_EOF) { krb5_free_principal(contextp->context, princ); goto fail; } else if (ret == 0) { size_t i; if (n_ks_tuple < 0) { ret = EOVERFLOW; krb5_free_principal(contextp->context, princ); goto fail; } if ((ks_tuple = calloc(n_ks_tuple, sizeof (*ks_tuple))) == NULL) { ret = errno; krb5_free_principal(contextp->context, princ); goto fail; } for (i = 0; i < n_ks_tuple; i++) { ret = krb5_ret_int32(sp, &ks_tuple[i].ks_enctype); if (ret != 0) { krb5_free_principal(contextp->context, princ); free(ks_tuple); goto fail; } ret = krb5_ret_int32(sp, &ks_tuple[i].ks_salttype); if (ret != 0) { krb5_free_principal(contextp->context, princ); free(ks_tuple); goto fail; } } } ret = kadm5_randkey_principal_3(kadm_handlep, princ, keepold, n_ks_tuple, ks_tuple, &new_keys, &n_keys); krb5_free_principal(contextp->context, princ); free(ks_tuple); krb5_storage_free(sp); sp = krb5_storage_emem(); krb5_store_int32(sp, ret); if(ret == 0){ int i; krb5_store_int32(sp, n_keys); for(i = 0; i < n_keys; i++){ if (ret == 0) ret = krb5_store_keyblock(sp, new_keys[i]); krb5_free_keyblock_contents(contextp->context, &new_keys[i]); } free(new_keys); } break; } case kadm_get_privs:{ uint32_t privs; ret = kadm5_get_privs(kadm_handlep, &privs); krb5_storage_free(sp); sp = krb5_storage_emem(); krb5_store_int32(sp, ret); if(ret == 0) krb5_store_uint32(sp, privs); break; } case kadm_get_princs:{ op = "LIST"; ret = krb5_ret_int32(sp, &tmp); if(ret) goto fail; if(tmp){ ret = krb5_ret_string(sp, &expression); if(ret) goto fail; }else expression = NULL; krb5_warnx(contextp->context, "%s: %s %s", client, op, expression ? expression : "*"); ret = _kadm5_acl_check_permission(contextp, KADM5_PRIV_LIST, NULL); if(ret){ free(expression); goto fail; } ret = kadm5_get_principals(kadm_handlep, expression, &princs, &n_princs); free(expression); krb5_storage_free(sp); sp = krb5_storage_emem(); krb5_store_int32(sp, ret); if(ret == 0){ int i; krb5_store_int32(sp, n_princs); for(i = 0; i < n_princs; i++) krb5_store_string(sp, princs[i]); kadm5_free_name_list(kadm_handlep, princs, &n_princs); } break; } default: krb5_warnx(contextp->context, "%s: UNKNOWN OP %d", client, cmd); krb5_storage_free(sp); sp = krb5_storage_emem(); krb5_store_int32(sp, KADM5_FAILURE); break; } if (password != NULL) { len = strlen(password); memset_s(password, len, 0, len); free(password); } krb5_storage_to_data(sp, out); krb5_storage_free(sp); return 0; fail: if (password != NULL) { len = strlen(password); memset_s(password, len, 0, len); free(password); } krb5_warn(contextp->context, ret, "%s", op); krb5_storage_seek(sp, 0, SEEK_SET); krb5_store_int32(sp, ret); krb5_storage_to_data(sp, out); krb5_storage_free(sp); return 0; } struct iter_aliases_ctx { HDB_Ext_Aliases aliases; krb5_tl_data *tl; int alias_idx; int done; }; static kadm5_ret_t iter_aliases(kadm5_principal_ent_rec *from, struct iter_aliases_ctx *ctx, krb5_principal *out) { HDB_extension ext; kadm5_ret_t ret; size_t size; *out = NULL; if (ctx->done > 0) return 0; if (ctx->done == 0) { if (ctx->alias_idx < ctx->aliases.aliases.len) { *out = &ctx->aliases.aliases.val[ctx->alias_idx++]; return 0; } /* Out of aliases in this TL, step to next TL */ ctx->tl = ctx->tl->tl_data_next; } else if (ctx->done < 0) { /* Setup iteration context */ memset(ctx, 0, sizeof(*ctx)); ctx->done = 0; ctx->aliases.aliases.val = NULL; ctx->aliases.aliases.len = 0; ctx->tl = from->tl_data; } free_HDB_Ext_Aliases(&ctx->aliases); ctx->alias_idx = 0; /* Find TL with aliases */ for (; ctx->tl != NULL; ctx->tl = ctx->tl->tl_data_next) { if (ctx->tl->tl_data_type != KRB5_TL_EXTENSION) continue; ret = decode_HDB_extension(ctx->tl->tl_data_contents, ctx->tl->tl_data_length, &ext, &size); if (ret) return ret; if (ext.data.element == choice_HDB_extension_data_aliases && ext.data.u.aliases.aliases.len > 0) { ctx->aliases = ext.data.u.aliases; break; } free_HDB_extension(&ext); } if (ctx->tl != NULL && ctx->aliases.aliases.len > 0) { *out = &ctx->aliases.aliases.val[ctx->alias_idx++]; return 0; } ctx->done = 1; return 0; } static kadm5_ret_t check_aliases(kadm5_server_context *contextp, kadm5_principal_ent_rec *add_princ, kadm5_principal_ent_rec *del_princ) { kadm5_ret_t ret; struct iter_aliases_ctx iter; struct iter_aliases_ctx iter_del; krb5_principal new_name, old_name; int match; /* * Yeah, this is O(N^2). Gathering and sorting all the aliases * would be a bit of a pain; if we ever have principals with enough * aliases for this to be a problem, we can fix it then. */ for (iter.done = -1; iter.done != 1;) { match = 0; ret = iter_aliases(add_princ, &iter, &new_name); if (ret) return ret; if (iter.done == 1) break; for (iter_del.done = -1; iter_del.done != 1;) { ret = iter_aliases(del_princ, &iter_del, &old_name); if (ret) return ret; if (iter_del.done == 1) break; if (!krb5_principal_compare(contextp->context, new_name, old_name)) continue; free_HDB_Ext_Aliases(&iter_del.aliases); match = 1; break; } if (match) continue; ret = _kadm5_acl_check_permission(contextp, KADM5_PRIV_ADD, new_name); if (ret) { free_HDB_Ext_Aliases(&iter.aliases); return ret; } } return 0; } static void v5_loop (krb5_context contextp, krb5_auth_context ac, krb5_boolean initial, void *kadm_handlep, krb5_socket_t fd) { krb5_error_code ret; krb5_data in, out; for (;;) { doing_useful_work = 0; if(term_flag) exit(0); ret = krb5_read_priv_message(contextp, ac, &fd, &in); if(ret == HEIM_ERR_EOF) exit(0); if(ret) krb5_err(contextp, 1, ret, "krb5_read_priv_message"); doing_useful_work = 1; kadmind_dispatch(kadm_handlep, initial, &in, &out); krb5_data_free(&in); ret = krb5_write_priv_message(contextp, ac, &fd, &out); if(ret) krb5_err(contextp, 1, ret, "krb5_write_priv_message"); } } static krb5_boolean match_appl_version(const void *data, const char *appl_version) { unsigned minor; if(sscanf(appl_version, "KADM0.%u", &minor) != 1) return 0; /*XXX*/ *(unsigned*)(intptr_t)data = minor; return 1; } static void handle_v5(krb5_context contextp, krb5_keytab keytab, krb5_socket_t fd) { krb5_error_code ret; krb5_ticket *ticket; char *server_name; char *client; void *kadm_handlep; krb5_boolean initial; krb5_auth_context ac = NULL; unsigned kadm_version = 1; kadm5_config_params realm_params; ret = krb5_recvauth_match_version(contextp, &ac, &fd, match_appl_version, &kadm_version, NULL, KRB5_RECVAUTH_IGNORE_VERSION, keytab, &ticket); if (ret) krb5_err(contextp, 1, ret, "krb5_recvauth"); ret = krb5_unparse_name (contextp, ticket->server, &server_name); if (ret) krb5_err (contextp, 1, ret, "krb5_unparse_name"); if (strncmp (server_name, KADM5_ADMIN_SERVICE, strlen(KADM5_ADMIN_SERVICE)) != 0) krb5_errx (contextp, 1, "ticket for strange principal (%s)", server_name); free (server_name); memset(&realm_params, 0, sizeof(realm_params)); if(kadm_version == 1) { krb5_data params; ret = krb5_read_priv_message(contextp, ac, &fd, ¶ms); if(ret) krb5_err(contextp, 1, ret, "krb5_read_priv_message"); _kadm5_unmarshal_params(contextp, ¶ms, &realm_params); } initial = ticket->ticket.flags.initial; ret = krb5_unparse_name(contextp, ticket->client, &client); if (ret) krb5_err (contextp, 1, ret, "krb5_unparse_name"); krb5_free_ticket (contextp, ticket); ret = kadm5_s_init_with_password_ctx(contextp, client, NULL, KADM5_ADMIN_SERVICE, &realm_params, 0, 0, &kadm_handlep); if(ret) krb5_err (contextp, 1, ret, "kadm5_init_with_password_ctx"); v5_loop (contextp, ac, initial, kadm_handlep, fd); } krb5_error_code kadmind_loop(krb5_context contextp, krb5_keytab keytab, krb5_socket_t sock) { u_char buf[sizeof(KRB5_SENDAUTH_VERSION) + 4]; ssize_t n; unsigned long len; n = krb5_net_read(contextp, &sock, buf, 4); if(n == 0) exit(0); if(n < 0) krb5_err(contextp, 1, errno, "read"); _krb5_get_int(buf, &len, 4); if (len == sizeof(KRB5_SENDAUTH_VERSION)) { n = krb5_net_read(contextp, &sock, buf + 4, len); if (n < 0) krb5_err (contextp, 1, errno, "reading sendauth version"); if (n == 0) krb5_errx (contextp, 1, "EOF reading sendauth version"); if(memcmp(buf + 4, KRB5_SENDAUTH_VERSION, len) == 0) { handle_v5(contextp, keytab, sock); return 0; } len += 4; } else len = 4; handle_mit(contextp, buf, len, sock); return 0; } heimdal-7.5.0/kadmin/get.c0000644000175000017500000003660013026237312013444 0ustar niknik/* * Copyright (c) 1997-2006 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "kadmin_locl.h" #include "kadmin-commands.h" #include #include static struct field_name { const char *fieldname; unsigned int fieldvalue; unsigned int subvalue; uint32_t extra_mask; const char *default_header; const char *def_longheader; unsigned int flags; } field_names[] = { { "principal", KADM5_PRINCIPAL, 0, 0, "Principal", "Principal", 0 }, { "princ_expire_time", KADM5_PRINC_EXPIRE_TIME, 0, 0, "Expiration", "Principal expires", 0 }, { "pw_expiration", KADM5_PW_EXPIRATION, 0, 0, "PW-exp", "Password expires", 0 }, { "last_pwd_change", KADM5_LAST_PWD_CHANGE, 0, 0, "PW-change", "Last password change", 0 }, { "max_life", KADM5_MAX_LIFE, 0, 0, "Max life", "Max ticket life", 0 }, { "max_rlife", KADM5_MAX_RLIFE, 0, 0, "Max renew", "Max renewable life", 0 }, { "mod_time", KADM5_MOD_TIME, 0, 0, "Mod time", "Last modified", 0 }, { "mod_name", KADM5_MOD_NAME, 0, 0, "Modifier", "Modifier", 0 }, { "attributes", KADM5_ATTRIBUTES, 0, 0, "Attributes", "Attributes", 0 }, { "kvno", KADM5_KVNO, 0, 0, "Kvno", "Kvno", RTBL_ALIGN_RIGHT }, { "mkvno", KADM5_MKVNO, 0, 0, "Mkvno", "Mkvno", RTBL_ALIGN_RIGHT }, { "last_success", KADM5_LAST_SUCCESS, 0, 0, "Last login", "Last successful login", 0 }, { "last_failed", KADM5_LAST_FAILED, 0, 0, "Last fail", "Last failed login", 0 }, { "fail_auth_count", KADM5_FAIL_AUTH_COUNT, 0, 0, "Fail count", "Failed login count", RTBL_ALIGN_RIGHT }, { "policy", KADM5_POLICY, 0, 0, "Policy", "Policy", 0 }, { "keytypes", KADM5_KEY_DATA, 0, KADM5_PRINCIPAL | KADM5_KVNO, "Keytypes", "Keytypes", 0 }, { "password", KADM5_TL_DATA, KRB5_TL_PASSWORD, KADM5_KEY_DATA, "Password", "Password", 0 }, { "pkinit-acl", KADM5_TL_DATA, KRB5_TL_PKINIT_ACL, 0, "PK-INIT ACL", "PK-INIT ACL", 0 }, { "aliases", KADM5_TL_DATA, KRB5_TL_ALIASES, 0, "Aliases", "Aliases", 0 }, { "hist-kvno-diff-clnt", KADM5_TL_DATA, KRB5_TL_HIST_KVNO_DIFF_CLNT, 0, "Clnt hist keys", "Historic keys allowed for client", 0 }, { "hist-kvno-diff-svc", KADM5_TL_DATA, KRB5_TL_HIST_KVNO_DIFF_SVC, 0, "Svc hist keys", "Historic keys allowed for service", 0 }, { NULL, 0, 0, 0, NULL, NULL, 0 } }; struct field_info { struct field_name *ff; char *header; struct field_info *next; }; struct get_entry_data { void (*format)(struct get_entry_data*, kadm5_principal_ent_t); rtbl_t table; uint32_t mask; uint32_t extra_mask; struct field_info *chead, **ctail; }; static int add_column(struct get_entry_data *data, struct field_name *ff, const char *header) { struct field_info *f = malloc(sizeof(*f)); if (f == NULL) return ENOMEM; f->ff = ff; if(header) f->header = strdup(header); else f->header = NULL; f->next = NULL; *data->ctail = f; data->ctail = &f->next; data->mask |= ff->fieldvalue; data->extra_mask |= ff->extra_mask; if(data->table != NULL) rtbl_add_column_by_id(data->table, ff->fieldvalue, header ? header : ff->default_header, ff->flags); return 0; } /* * return 0 iff `salt' actually is the same as the current salt in `k' */ static int cmp_salt (const krb5_salt *salt, const krb5_key_data *k) { if (salt->salttype != (size_t)k->key_data_type[1]) return 1; if (salt->saltvalue.length != (size_t)k->key_data_length[1]) return 1; return memcmp (salt->saltvalue.data, k->key_data_contents[1], salt->saltvalue.length); } static void format_keytype(krb5_key_data *k, krb5_salt *def_salt, char *buf, size_t buf_len) { krb5_error_code ret; char *s; int aret; buf[0] = '\0'; ret = krb5_enctype_to_string (context, k->key_data_type[0], &s); if (ret) { aret = asprintf (&s, "unknown(%d)", k->key_data_type[0]); if (aret == -1) return; /* Nothing to do here, we have no way to pass the err */ } strlcpy(buf, s, buf_len); free(s); strlcat(buf, "(", buf_len); ret = krb5_salttype_to_string (context, k->key_data_type[0], k->key_data_type[1], &s); if (ret) { aret = asprintf (&s, "unknown(%d)", k->key_data_type[1]); if (aret == -1) return; /* Again, nothing else to do... */ } strlcat(buf, s, buf_len); free(s); aret = 0; if (cmp_salt(def_salt, k) == 0) s = strdup(""); else if(k->key_data_length[1] == 0) s = strdup("()"); else aret = asprintf (&s, "(%.*s)", k->key_data_length[1], (char *)k->key_data_contents[1]); if (aret == -1 || s == NULL) return; /* Again, nothing else we can do... */ strlcat(buf, s, buf_len); free(s); aret = asprintf (&s, "[%d]", k->key_data_kvno); if (aret == -1) return; strlcat(buf, ")", buf_len); strlcat(buf, s, buf_len); free(s); } static void format_field(kadm5_principal_ent_t princ, unsigned int field, unsigned int subfield, char *buf, size_t buf_len, int condensed) { switch(field) { case KADM5_PRINCIPAL: if(condensed) krb5_unparse_name_fixed_short(context, princ->principal, buf, buf_len); else krb5_unparse_name_fixed(context, princ->principal, buf, buf_len); break; case KADM5_PRINC_EXPIRE_TIME: time_t2str(princ->princ_expire_time, buf, buf_len, !condensed); break; case KADM5_PW_EXPIRATION: time_t2str(princ->pw_expiration, buf, buf_len, !condensed); break; case KADM5_LAST_PWD_CHANGE: time_t2str(princ->last_pwd_change, buf, buf_len, !condensed); break; case KADM5_MAX_LIFE: deltat2str(princ->max_life, buf, buf_len); break; case KADM5_MAX_RLIFE: deltat2str(princ->max_renewable_life, buf, buf_len); break; case KADM5_MOD_TIME: time_t2str(princ->mod_date, buf, buf_len, !condensed); break; case KADM5_MOD_NAME: if (princ->mod_name == NULL) strlcpy(buf, "unknown", buf_len); else if(condensed) krb5_unparse_name_fixed_short(context, princ->mod_name, buf, buf_len); else krb5_unparse_name_fixed(context, princ->mod_name, buf, buf_len); break; case KADM5_ATTRIBUTES: attributes2str (princ->attributes, buf, buf_len); break; case KADM5_KVNO: snprintf(buf, buf_len, "%d", princ->kvno); break; case KADM5_MKVNO: /* XXX libkadm5srv decrypts the keys, so mkvno is always 0. */ strlcpy(buf, "unknown", buf_len); break; case KADM5_LAST_SUCCESS: time_t2str(princ->last_success, buf, buf_len, !condensed); break; case KADM5_LAST_FAILED: time_t2str(princ->last_failed, buf, buf_len, !condensed); break; case KADM5_FAIL_AUTH_COUNT: snprintf(buf, buf_len, "%d", princ->fail_auth_count); break; case KADM5_POLICY: if(princ->policy != NULL) strlcpy(buf, princ->policy, buf_len); else strlcpy(buf, "none", buf_len); break; case KADM5_KEY_DATA:{ krb5_salt def_salt; int i; char buf2[1024]; krb5_get_pw_salt (context, princ->principal, &def_salt); *buf = '\0'; for (i = 0; i < princ->n_key_data; ++i) { format_keytype(&princ->key_data[i], &def_salt, buf2, sizeof(buf2)); if(i > 0) strlcat(buf, ", ", buf_len); strlcat(buf, buf2, buf_len); } krb5_free_salt (context, def_salt); break; } case KADM5_TL_DATA: { krb5_tl_data *tl; for (tl = princ->tl_data; tl != NULL; tl = tl->tl_data_next) if ((unsigned)tl->tl_data_type == subfield) break; if (tl == NULL) { strlcpy(buf, "", buf_len); break; } switch (subfield) { case KRB5_TL_PASSWORD: snprintf(buf, buf_len, "\"%.*s\"", (int)tl->tl_data_length, (const char *)tl->tl_data_contents); break; case KRB5_TL_PKINIT_ACL: { HDB_Ext_PKINIT_acl acl; size_t size; int ret; size_t i; ret = decode_HDB_Ext_PKINIT_acl(tl->tl_data_contents, tl->tl_data_length, &acl, &size); if (ret) { snprintf(buf, buf_len, "failed to decode ACL"); break; } buf[0] = '\0'; for (i = 0; i < acl.len; i++) { strlcat(buf, "subject: ", buf_len); strlcat(buf, acl.val[i].subject, buf_len); if (acl.val[i].issuer) { strlcat(buf, " issuer:", buf_len); strlcat(buf, *acl.val[i].issuer, buf_len); } if (acl.val[i].anchor) { strlcat(buf, " anchor:", buf_len); strlcat(buf, *acl.val[i].anchor, buf_len); } if (i + 1 < acl.len) strlcat(buf, ", ", buf_len); } free_HDB_Ext_PKINIT_acl(&acl); break; } case KRB5_TL_ALIASES: { HDB_Ext_Aliases alias; size_t size; int ret; size_t i; ret = decode_HDB_Ext_Aliases(tl->tl_data_contents, tl->tl_data_length, &alias, &size); if (ret) { snprintf(buf, buf_len, "failed to decode alias"); break; } buf[0] = '\0'; for (i = 0; i < alias.aliases.len; i++) { char *p; ret = krb5_unparse_name(context, &alias.aliases.val[i], &p); if (ret) break; if (i > 0) strlcat(buf, " ", buf_len); strlcat(buf, p, buf_len); free(p); } free_HDB_Ext_Aliases(&alias); break; } default: snprintf(buf, buf_len, "unknown type %d", subfield); break; } break; } default: strlcpy(buf, "", buf_len); break; } } static void print_entry_short(struct get_entry_data *data, kadm5_principal_ent_t princ) { char buf[1024]; struct field_info *f; for(f = data->chead; f != NULL; f = f->next) { format_field(princ, f->ff->fieldvalue, f->ff->subvalue, buf, sizeof(buf), 1); rtbl_add_column_entry_by_id(data->table, f->ff->fieldvalue, buf); } } static void print_entry_long(struct get_entry_data *data, kadm5_principal_ent_t princ) { char buf[1024]; struct field_info *f; int width = 0; for(f = data->chead; f != NULL; f = f->next) { int w = strlen(f->header ? f->header : f->ff->def_longheader); if(w > width) width = w; } for(f = data->chead; f != NULL; f = f->next) { format_field(princ, f->ff->fieldvalue, f->ff->subvalue, buf, sizeof(buf), 0); printf("%*s: %s\n", width, f->header ? f->header : f->ff->def_longheader, buf); } printf("\n"); } static int do_get_entry(krb5_principal principal, void *data) { kadm5_principal_ent_rec princ; krb5_error_code ret; struct get_entry_data *e = data; memset(&princ, 0, sizeof(princ)); ret = kadm5_get_principal(kadm_handle, principal, &princ, e->mask | e->extra_mask); if(ret) return ret; else { (e->format)(e, &princ); kadm5_free_principal_ent(kadm_handle, &princ); } return 0; } static void free_columns(struct get_entry_data *data) { struct field_info *f, *next; for(f = data->chead; f != NULL; f = next) { free(f->header); next = f->next; free(f); } data->chead = NULL; data->ctail = &data->chead; } static int setup_columns(struct get_entry_data *data, const char *column_info) { char buf[1024], *q; char *field, *header; struct field_name *f; while(strsep_copy(&column_info, ",", buf, sizeof(buf)) != -1) { q = buf; field = strsep(&q, "="); header = strsep(&q, "="); for(f = field_names; f->fieldname != NULL; f++) { if(strcasecmp(field, f->fieldname) == 0) { add_column(data, f, header); break; } } if(f->fieldname == NULL) { krb5_warnx(context, "unknown field name \"%s\"", field); free_columns(data); return -1; } } return 0; } static int do_list_entry(krb5_principal principal, void *data) { char buf[1024]; krb5_error_code ret; ret = krb5_unparse_name_fixed_short(context, principal, buf, sizeof(buf)); if (ret != 0) return ret; printf("%s\n", buf); return 0; } static int listit(const char *funcname, int argc, char **argv) { int i; krb5_error_code ret, saved_ret = 0; for (i = 0; i < argc; i++) { ret = foreach_principal(argv[i], do_list_entry, funcname, NULL); if (saved_ret == 0 && ret != 0) saved_ret = ret; } return saved_ret != 0; } #define DEFAULT_COLUMNS_SHORT "principal,princ_expire_time,pw_expiration,last_pwd_change,max_life,max_rlife" #define DEFAULT_COLUMNS_LONG "principal,princ_expire_time,pw_expiration,last_pwd_change,max_life,max_rlife,kvno,mkvno,last_success,last_failed,fail_auth_count,mod_time,mod_name,attributes,keytypes,pkinit-acl,aliases" static int getit(struct get_options *opt, const char *name, int argc, char **argv) { int i; krb5_error_code ret; struct get_entry_data data; if(opt->long_flag == -1 && (opt->short_flag == 1 || opt->terse_flag == 1)) opt->long_flag = 0; if(opt->short_flag == -1 && (opt->long_flag == 1 || opt->terse_flag == 1)) opt->short_flag = 0; if(opt->terse_flag == -1 && (opt->long_flag == 1 || opt->short_flag == 1)) opt->terse_flag = 0; if(opt->long_flag == 0 && opt->short_flag == 0 && opt->terse_flag == 0) opt->short_flag = 1; if (opt->terse_flag) return listit(name, argc, argv); data.table = NULL; data.chead = NULL; data.ctail = &data.chead; data.mask = 0; data.extra_mask = 0; if(opt->short_flag) { data.table = rtbl_create(); rtbl_set_separator(data.table, " "); data.format = print_entry_short; } else data.format = print_entry_long; if(opt->column_info_string == NULL) { if(opt->long_flag) ret = setup_columns(&data, DEFAULT_COLUMNS_LONG); else ret = setup_columns(&data, DEFAULT_COLUMNS_SHORT); } else ret = setup_columns(&data, opt->column_info_string); if(ret != 0) { if(data.table != NULL) rtbl_destroy(data.table); return 0; } for(i = 0; i < argc; i++) ret = foreach_principal(argv[i], do_get_entry, name, &data); if(data.table != NULL) { rtbl_format(data.table, stdout); rtbl_destroy(data.table); } free_columns(&data); return ret != 0; } int get_entry(struct get_options *opt, int argc, char **argv) { return getit(opt, "get", argc, argv); } int list_princs(struct list_options *opt, int argc, char **argv) { if(sizeof(struct get_options) != sizeof(struct list_options)) { krb5_warnx(context, "programmer error: sizeof(struct get_options) != sizeof(struct list_options)"); return 0; } return getit((struct get_options*)opt, "list", argc, argv); } heimdal-7.5.0/kadmin/test_util.c0000644000175000017500000000475112136107747014714 0ustar niknik/* * Copyright (c) 2006 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of KTH nor the names of its contributors may be * used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY KTH AND ITS CONTRIBUTORS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL KTH OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "kadmin_locl.h" krb5_context context; void *kadm_handle; struct { const char *str; int ret; time_t t; } ts[] = { { "2006-12-22 18:09:00", 0, 1166810940 }, { "2006-12-22", 0, 1166831999 }, { "2006-12-22 23:59:59", 0, 1166831999 } }; static int test_time(void) { int i, errors = 0; for (i = 0; i < sizeof(ts)/sizeof(ts[0]); i++) { time_t t; int ret; ret = str2time_t (ts[i].str, &t); if (ret != ts[i].ret) { printf("%d: %d is wrong ret\n", i, ret); errors++; } else if (t != ts[i].t) { printf("%d: %d is wrong time\n", i, (int)t); errors++; } } return errors; } int main(int argc, char **argv) { krb5_error_code ret; setprogname(argv[0]); ret = krb5_init_context(&context); if (ret) errx (1, "krb5_init_context failed: %d", ret); ret = 0; ret += test_time(); krb5_free_context(context); return ret; } heimdal-7.5.0/kadmin/kadmin.10000644000175000017500000002304313026237312014043 0ustar niknik.\" Copyright (c) 2000 - 2007 Kungliga Tekniska Högskolan .\" (Royal Institute of Technology, Stockholm, Sweden). .\" All rights reserved. .\" .\" Redistribution and use in source and binary forms, with or without .\" modification, are permitted provided that the following conditions .\" are met: .\" .\" 1. Redistributions of source code must retain the above copyright .\" notice, this list of conditions and the following disclaimer. .\" .\" 2. Redistributions in binary form must reproduce the above copyright .\" notice, this list of conditions and the following disclaimer in the .\" documentation and/or other materials provided with the distribution. .\" .\" 3. Neither the name of the Institute nor the names of its contributors .\" may be used to endorse or promote products derived from this software .\" without specific prior written permission. .\" .\" THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND .\" ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE .\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE .\" ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE .\" FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL .\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS .\" OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) .\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT .\" LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF .\" SUCH DAMAGE. .\" .\" $Id$ .\" .Dd Feb 22, 2007 .Dt KADMIN 1 .Os HEIMDAL .Sh NAME .Nm kadmin .Nd Kerberos administration utility .Sh SYNOPSIS .Nm .Bk -words .Op Fl p Ar string \*(Ba Fl Fl principal= Ns Ar string .Op Fl K Ar string \*(Ba Fl Fl keytab= Ns Ar string .Op Fl c Ar file \*(Ba Fl Fl config-file= Ns Ar file .Op Fl k Ar file \*(Ba Fl Fl key-file= Ns Ar file .Op Fl r Ar realm \*(Ba Fl Fl realm= Ns Ar realm .Op Fl a Ar host \*(Ba Fl Fl admin-server= Ns Ar host .Op Fl s Ar port number \*(Ba Fl Fl server-port= Ns Ar port number .Op Fl l | Fl Fl local .Op Fl h | Fl Fl help .Op Fl v | Fl Fl version .Op Ar command .Ek .Sh DESCRIPTION The .Nm program is used to make modifications to the Kerberos database, either remotely via the .Xr kadmind 8 daemon, or locally (with the .Fl l option). .Pp Supported options: .Bl -tag -width Ds .It Fl p Ar string , Fl Fl principal= Ns Ar string principal to authenticate as .It Fl K Ar string , Fl Fl keytab= Ns Ar string keytab for authentication principal .It Fl c Ar file , Fl Fl config-file= Ns Ar file location of config file .It Fl k Ar file , Fl Fl key-file= Ns Ar file location of master key file .It Fl r Ar realm , Fl Fl realm= Ns Ar realm realm to use .It Fl a Ar host , Fl Fl admin-server= Ns Ar host server to contact .It Fl s Ar port number , Fl Fl server-port= Ns Ar port number port to use .It Fl l , Fl Fl local local admin mode .El .Pp If no .Ar command is given on the command line, .Nm will prompt for commands to process. Some of the commands that take one or more principals as argument .Ns ( Nm delete , .Nm ext_keytab , .Nm get , .Nm modify , and .Nm passwd ) will accept a glob style wildcard, and perform the operation on all matching principals. .Pp Commands include: .\" not using a list here, since groff apparently gets confused .\" with nested Xo/Xc .Pp .Nm add .Op Fl r | Fl Fl random-key .Op Fl Fl random-password .Op Fl p Ar string \*(Ba Fl Fl password= Ns Ar string .Op Fl Fl key= Ns Ar string .Op Fl Fl max-ticket-life= Ns Ar lifetime .Op Fl Fl max-renewable-life= Ns Ar lifetime .Op Fl Fl attributes= Ns Ar attributes .Op Fl Fl expiration-time= Ns Ar time .Op Fl Fl pw-expiration-time= Ns Ar time .Op Fl Fl policy= Ns Ar policy-name .Ar principal... .Bd -ragged -offset indent Adds a new principal to the database. The options not passed on the command line will be promped for. The only policy supported by Heimdal servers is .Ql default . .Ed .Pp .Nm add_enctype .Op Fl r | Fl Fl random-key .Ar principal enctypes... .Pp .Bd -ragged -offset indent Adds a new encryption type to the principal, only random key are supported. .Ed .Pp .Nm delete .Ar principal... .Bd -ragged -offset indent Removes a principal. .Ed .Pp .Nm del_enctype .Ar principal enctypes... .Bd -ragged -offset indent Removes some enctypes from a principal; this can be useful if the service belonging to the principal is known to not handle certain enctypes. .Ed .Pp .Nm ext_keytab .Oo Fl k Ar string \*(Ba Xo .Fl Fl keytab= Ns Ar string .Xc .Oc .Ar principal... .Bd -ragged -offset indent Creates a keytab with the keys of the specified principals. Requires get-keys rights, otherwise the principal's keys are changed and saved in the keytab. .Ed .Pp .Nm get .Op Fl l | Fl Fl long .Op Fl s | Fl Fl short .Op Fl t | Fl Fl terse .Op Fl o Ar string | Fl Fl column-info= Ns Ar string .Ar principal... .Bd -ragged -offset indent Lists the matching principals, short prints the result as a table, while long format produces a more verbose output. Which columns to print can be selected with the .Fl o option. The argument is a comma separated list of column names optionally appended with an equal sign .Pq Sq = and a column header. Which columns are printed by default differ slightly between short and long output. .Pp The default terse output format is similar to .Fl s o Ar principal= , just printing the names of matched principals. .Pp Possible column names include: .Li principal , .Li princ_expire_time , .Li pw_expiration , .Li last_pwd_change , .Li max_life , .Li max_rlife , .Li mod_time , .Li mod_name , .Li attributes , .Li kvno , .Li mkvno , .Li last_success , .Li last_failed , .Li fail_auth_count , .Li policy , and .Li keytypes . .Ed .Pp .Nm modify .Oo Fl a Ar attributes \*(Ba Xo .Fl Fl attributes= Ns Ar attributes .Xc .Oc .Op Fl Fl max-ticket-life= Ns Ar lifetime .Op Fl Fl max-renewable-life= Ns Ar lifetime .Op Fl Fl expiration-time= Ns Ar time .Op Fl Fl pw-expiration-time= Ns Ar time .Op Fl Fl kvno= Ns Ar number .Op Fl Fl policy= Ns Ar policy-name .Ar principal... .Bd -ragged -offset indent Modifies certain attributes of a principal. If run without command line options, you will be prompted. With command line options, it will only change the ones specified. .Pp Only policy supported by Heimdal is .Ql default . .Pp Possible attributes are: .Li new-princ , .Li support-desmd5 , .Li pwchange-service , .Li disallow-svr , .Li requires-pw-change , .Li requires-hw-auth , .Li requires-pre-auth , .Li disallow-all-tix , .Li disallow-dup-skey , .Li disallow-proxiable , .Li disallow-renewable , .Li disallow-tgt-based , .Li disallow-forwardable , .Li disallow-postdated .Pp Attributes may be negated with a "-", e.g., .Pp kadmin -l modify -a -disallow-proxiable user .Ed .Pp .Nm passwd .Op Fl Fl keepold .Op Fl r | Fl Fl random-key .Op Fl Fl random-password .Oo Fl p Ar string \*(Ba Xo .Fl Fl password= Ns Ar string .Xc .Oc .Op Fl Fl key= Ns Ar string .Ar principal... .Bd -ragged -offset indent Changes the password of an existing principal. .Ed .Pp .Nm password-quality .Ar principal .Ar password .Bd -ragged -offset indent Run the password quality check function locally. You can run this on the host that is configured to run the kadmind process to verify that your configuration file is correct. The verification is done locally, if kadmin is run in remote mode, no rpc call is done to the server. .Ed .Pp .Nm privileges .Bd -ragged -offset indent Lists the operations you are allowed to perform. These include .Li add , .Li add_enctype , .Li change-password , .Li delete , .Li del_enctype , .Li get , .Li get-keys , .Li list , and .Li modify . .Ed .Pp .Nm rename .Ar from to .Bd -ragged -offset indent Renames a principal. This is normally transparent, but since keys are salted with the principal name, they will have a non-standard salt, and clients which are unable to cope with this will fail. Kerberos 4 suffers from this. .Ed .Pp .Nm check .Op Ar realm .Pp .Bd -ragged -offset indent Check database for strange configurations on important principals. If no realm is given, the default realm is used. .Ed .Pp When running in local mode, the following commands can also be used: .Pp .Nm dump .Op Fl d | Fl Fl decrypt .Op Fl f Ns Ar format | Fl Fl format= Ns Ar format .Op Ar dump-file .Bd -ragged -offset indent Writes the database in .Dq machine readable text form to the specified file, or standard out. If the database is encrypted, the dump will also have encrypted keys, unless .Fl Fl decrypt is used. If .Fl Fl format=MIT is used then the dump will be in MIT format. Otherwise it will be in Heimdal format. .Ed .Pp .Nm init .Op Fl Fl realm-max-ticket-life= Ns Ar string .Op Fl Fl realm-max-renewable-life= Ns Ar string .Ar realm .Bd -ragged -offset indent Initializes the Kerberos database with entries for a new realm. It's possible to have more than one realm served by one server. .Ed .Pp .Nm load .Ar file .Bd -ragged -offset indent Reads a previously dumped database, and re-creates that database from scratch. .Ed .Pp .Nm merge .Ar file .Bd -ragged -offset indent Similar to .Nm load but just modifies the database with the entries in the dump file. .Ed .Pp .Nm stash .Oo Fl e Ar enctype \*(Ba Xo .Fl Fl enctype= Ns Ar enctype .Xc .Oc .Oo Fl k Ar keyfile \*(Ba Xo .Fl Fl key-file= Ns Ar keyfile .Xc .Oc .Op Fl Fl convert-file .Op Fl Fl master-key-fd= Ns Ar fd .Bd -ragged -offset indent Writes the Kerberos master key to a file used by the KDC. .Ed .\".Sh ENVIRONMENT .\".Sh FILES .\".Sh EXAMPLES .\".Sh DIAGNOSTICS .Sh SEE ALSO .Xr kadmind 8 , .Xr kdc 8 .\".Sh STANDARDS .\".Sh HISTORY .\".Sh AUTHORS .\".Sh BUGS heimdal-7.5.0/kadmin/ank.c0000644000175000017500000002010513026237312013427 0ustar niknik/* * Copyright (c) 1997-2006 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "kadmin_locl.h" #include "kadmin-commands.h" /* * fetch the default principal corresponding to `princ' */ static krb5_error_code get_default (kadm5_server_context *contextp, krb5_principal princ, kadm5_principal_ent_t default_ent) { krb5_error_code ret; krb5_principal def_principal; krb5_const_realm realm = krb5_principal_get_realm(contextp->context, princ); ret = krb5_make_principal (contextp->context, &def_principal, realm, "default", NULL); if (ret) return ret; ret = kadm5_get_principal (contextp, def_principal, default_ent, KADM5_PRINCIPAL_NORMAL_MASK); krb5_free_principal (contextp->context, def_principal); return ret; } /* * Add the principal `name' to the database. * Prompt for all data not given by the input parameters. */ static krb5_error_code add_one_principal (const char *name, int rand_key, int rand_password, int use_defaults, char *password, char *policy, krb5_key_data *key_data, const char *max_ticket_life, const char *max_renewable_life, const char *attributes, const char *expiration, const char *pw_expiration) { krb5_error_code ret; kadm5_principal_ent_rec princ, defrec; kadm5_principal_ent_rec *default_ent = NULL; krb5_principal princ_ent = NULL; int mask = 0; int default_mask = 0; char pwbuf[1024]; memset(&princ, 0, sizeof(princ)); ret = krb5_parse_name(context, name, &princ_ent); if (ret) { krb5_warn(context, ret, "krb5_parse_name"); return ret; } princ.principal = princ_ent; mask |= KADM5_PRINCIPAL; ret = set_entry(context, &princ, &mask, max_ticket_life, max_renewable_life, expiration, pw_expiration, attributes, policy); if (ret) goto out; default_ent = &defrec; ret = get_default (kadm_handle, princ_ent, default_ent); if (ret) { default_ent = NULL; default_mask = 0; } else { default_mask = KADM5_ATTRIBUTES | KADM5_MAX_LIFE | KADM5_MAX_RLIFE | KADM5_PRINC_EXPIRE_TIME | KADM5_PW_EXPIRATION; } if(use_defaults) set_defaults(&princ, &mask, default_ent, default_mask); else if(edit_entry(&princ, &mask, default_ent, default_mask)) goto out; if(rand_key || key_data) { princ.attributes |= KRB5_KDB_DISALLOW_ALL_TIX; mask |= KADM5_ATTRIBUTES; random_password (pwbuf, sizeof(pwbuf)); password = pwbuf; } else if (rand_password) { random_password (pwbuf, sizeof(pwbuf)); password = pwbuf; } else if(password == NULL) { char *princ_name; char *prompt; int aret; ret = krb5_unparse_name(context, princ_ent, &princ_name); if (ret) goto out; aret = asprintf (&prompt, "%s's Password: ", princ_name); free (princ_name); if (aret == -1) { ret = ENOMEM; krb5_set_error_message(context, ret, "out of memory"); goto out; } ret = UI_UTIL_read_pw_string (pwbuf, sizeof(pwbuf), prompt, 1); free (prompt); if (ret) { ret = KRB5_LIBOS_BADPWDMATCH; krb5_set_error_message(context, ret, "failed to verify password"); goto out; } password = pwbuf; } ret = kadm5_create_principal(kadm_handle, &princ, mask, password); if(ret) { krb5_warn(context, ret, "kadm5_create_principal"); goto out; } if(rand_key) { krb5_keyblock *new_keys; int n_keys, i; ret = kadm5_randkey_principal(kadm_handle, princ_ent, &new_keys, &n_keys); if(ret){ krb5_warn(context, ret, "kadm5_randkey_principal"); n_keys = 0; } for(i = 0; i < n_keys; i++) krb5_free_keyblock_contents(context, &new_keys[i]); if (n_keys > 0) free(new_keys); kadm5_get_principal(kadm_handle, princ_ent, &princ, KADM5_PRINCIPAL | KADM5_KVNO | KADM5_ATTRIBUTES); krb5_free_principal(context, princ_ent); princ_ent = princ.principal; princ.attributes &= (~KRB5_KDB_DISALLOW_ALL_TIX); /* * Updating kvno w/o key data and vice-versa gives _kadm5_setup_entry() * and _kadm5_set_keys2() headaches. But we used to, so we handle * this in in those two functions. Might as well leave this code as * it was then. */ princ.kvno = 1; kadm5_modify_principal(kadm_handle, &princ, KADM5_ATTRIBUTES | KADM5_KVNO); } else if (key_data) { ret = kadm5_chpass_principal_with_key (kadm_handle, princ_ent, 3, key_data); if (ret) { krb5_warn(context, ret, "kadm5_chpass_principal_with_key"); } kadm5_get_principal(kadm_handle, princ_ent, &princ, KADM5_PRINCIPAL | KADM5_ATTRIBUTES); krb5_free_principal(context, princ_ent); princ_ent = princ.principal; princ.attributes &= (~KRB5_KDB_DISALLOW_ALL_TIX); kadm5_modify_principal(kadm_handle, &princ, KADM5_ATTRIBUTES); } else if (rand_password) { char *princ_name; krb5_unparse_name(context, princ_ent, &princ_name); printf ("added %s with password \"%s\"\n", princ_name, password); free (princ_name); } out: kadm5_free_principal_ent(kadm_handle, &princ); /* frees princ_ent */ if(default_ent) kadm5_free_principal_ent (kadm_handle, default_ent); if (password != NULL) memset (password, 0, strlen(password)); return ret; } /* * parse the string `key_string' into `key', returning 0 iff succesful. */ /* * the ank command */ /* * Parse arguments and add all the principals. */ int add_new_key(struct add_options *opt, int argc, char **argv) { krb5_error_code ret = 0; int i; int num; krb5_key_data key_data[3]; krb5_key_data *kdp = NULL; num = 0; if (opt->random_key_flag) ++num; if (opt->random_password_flag) ++num; if (opt->password_string) ++num; if (opt->key_string) ++num; if (num > 1) { fprintf (stderr, "give only one of " "--random-key, --random-password, --password, --key\n"); return 1; } if (opt->key_string) { const char *error; if (parse_des_key (opt->key_string, key_data, &error)) { fprintf (stderr, "failed parsing key \"%s\": %s\n", opt->key_string, error); return 1; } kdp = key_data; } for(i = 0; i < argc; i++) { ret = add_one_principal (argv[i], opt->random_key_flag, opt->random_password_flag, opt->use_defaults_flag, opt->password_string, opt->policy_string, kdp, opt->max_ticket_life_string, opt->max_renewable_life_string, opt->attributes_string, opt->expiration_time_string, opt->pw_expiration_time_string); if (ret) { krb5_warn (context, ret, "adding %s", argv[i]); break; } } if (kdp) { int16_t dummy = 3; kadm5_free_key_data (kadm_handle, &dummy, key_data); } return ret != 0; } heimdal-7.5.0/kadmin/Makefile.am0000644000175000017500000000360713026237312014556 0ustar niknik# $Id$ include $(top_srcdir)/Makefile.am.common AM_CPPFLAGS += $(INCLUDE_libintl) $(INCLUDE_readline) -I$(srcdir)/../lib/krb5 -I$(top_builddir)/include/gssapi bin_PROGRAMS = kadmin libexec_PROGRAMS = kadmind man_MANS = kadmin.1 kadmind.8 noinst_PROGRAMS = add_random_users dist_kadmin_SOURCES = \ ank.c \ add_enctype.c \ check.c \ cpw.c \ del.c \ del_enctype.c \ dump.c \ ext.c \ get.c \ init.c \ kadmin.c \ load.c \ mod.c \ rename.c \ stash.c \ util.c \ pw_quality.c \ random_password.c \ kadmin_locl.h nodist_kadmin_SOURCES = \ kadmin-commands.c \ kadmin-commands.h $(kadmin_OBJECTS): kadmin-commands.h CLEANFILES = kadmin-commands.h kadmin-commands.c kadmin-commands.c kadmin-commands.h: kadmin-commands.in $(SLC) $(srcdir)/kadmin-commands.in kadmind_SOURCES = \ rpc.c \ server.c \ kadmind.c \ kadmin_locl.h \ kadm_conn.c add_random_users_SOURCES = add-random-users.c test_util_SOURCES = test_util.c util.c TESTS = test_util check_PROGRAMS = $(TESTS) LDADD_common = \ $(top_builddir)/lib/hdb/libhdb.la \ $(top_builddir)/lib/krb5/libkrb5.la \ $(LIB_hcrypto) \ $(top_builddir)/lib/asn1/libasn1.la \ $(LIB_roken) \ $(DB3LIB) $(DB1LIB) $(LMDBLIB) $(NDBMLIB) kadmind_LDADD = $(top_builddir)/lib/kadm5/libkadm5srv.la \ ../lib/gssapi/libgssapi.la \ $(LDADD_common) \ $(LIB_pidfile) \ $(LIB_dlopen) kadmin_LDADD = \ $(top_builddir)/lib/kadm5/libkadm5clnt.la \ $(top_builddir)/lib/kadm5/libkadm5srv.la \ $(top_builddir)/lib/sl/libsl.la \ $(LIB_readline) \ $(LDADD_common) \ $(LIB_dlopen) add_random_users_LDADD = \ $(top_builddir)/lib/kadm5/libkadm5clnt.la \ $(top_builddir)/lib/kadm5/libkadm5srv.la \ $(LDADD_common) \ $(LIB_dlopen) test_util_LDADD = $(kadmin_LDADD) EXTRA_DIST = \ NTMakefile \ kadmin-version.rc \ kadmind-version.rc \ $(man_MANS) \ kadmin-commands.in heimdal-7.5.0/kadmin/del.c0000644000175000017500000000401712136107747013437 0ustar niknik/* * Copyright (c) 1997 - 2004 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "kadmin_locl.h" #include "kadmin-commands.h" static int do_del_entry(krb5_principal principal, void *data) { return kadm5_delete_principal(kadm_handle, principal); } int del_entry(void *opt, int argc, char **argv) { int i; krb5_error_code ret = 0; for(i = 0; i < argc; i++) { ret = foreach_principal(argv[i], do_del_entry, "del", NULL); if (ret) break; } return ret != 0; } heimdal-7.5.0/kadmin/kadm_conn.c0000644000175000017500000001655413026237312014624 0ustar niknik/* * Copyright (c) 2000 - 2004 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "kadmin_locl.h" #ifdef HAVE_SYS_WAIT_H #include #endif extern int daemon_child; struct kadm_port { char *port; unsigned short def_port; struct kadm_port *next; } *kadm_ports; static void add_kadm_port(krb5_context contextp, const char *service, unsigned int port) { struct kadm_port *p; p = malloc(sizeof(*p)); if(p == NULL) { krb5_warnx(contextp, "failed to allocate %lu bytes\n", (unsigned long)sizeof(*p)); return; } p->port = strdup(service); p->def_port = port; p->next = kadm_ports; kadm_ports = p; } static void add_standard_ports (krb5_context contextp) { add_kadm_port(contextp, "kerberos-adm", 749); } /* * parse the set of space-delimited ports in `str' and add them. * "+" => all the standard ones * otherwise it's port|service[/protocol] */ void parse_ports(krb5_context contextp, const char *str) { char p[128]; while(strsep_copy(&str, " \t", p, sizeof(p)) != -1) { if(strcmp(p, "+") == 0) add_standard_ports(contextp); else add_kadm_port(contextp, p, 0); } } static pid_t pgrp; sig_atomic_t term_flag, doing_useful_work; static RETSIGTYPE sigchld(int sig) { int status; /* * waitpid() is async safe. will return -1 or 0 on no more zombie * children */ while ((waitpid(-1, &status, WNOHANG)) > 0) ; SIGRETURN(0); } static RETSIGTYPE terminate(int sig) { if(getpid() == pgrp) { /* parent */ term_flag = 1; signal(sig, SIG_IGN); killpg(pgrp, sig); } else { /* child */ if(doing_useful_work) term_flag = 1; else exit(0); } SIGRETURN(0); } static int spawn_child(krb5_context contextp, int *socks, unsigned int num_socks, int this_sock) { int e; size_t i; struct sockaddr_storage __ss; struct sockaddr *sa = (struct sockaddr *)&__ss; socklen_t sa_size = sizeof(__ss); krb5_socket_t s; pid_t pid; krb5_address addr; char buf[128]; size_t buf_len; s = accept(socks[this_sock], sa, &sa_size); if(rk_IS_BAD_SOCKET(s)) { krb5_warn(contextp, rk_SOCK_ERRNO, "accept"); return 1; } e = krb5_sockaddr2address(contextp, sa, &addr); if(e) krb5_warn(contextp, e, "krb5_sockaddr2address"); else { e = krb5_print_address (&addr, buf, sizeof(buf), &buf_len); if(e) krb5_warn(contextp, e, "krb5_print_address"); else krb5_warnx(contextp, "connection from %s", buf); krb5_free_address(contextp, &addr); } pid = fork(); if(pid == 0) { for(i = 0; i < num_socks; i++) rk_closesocket(socks[i]); dup2(s, STDIN_FILENO); dup2(s, STDOUT_FILENO); if(s != STDIN_FILENO && s != STDOUT_FILENO) rk_closesocket(s); return 0; } else { rk_closesocket(s); } return 1; } static void wait_for_connection(krb5_context contextp, krb5_socket_t *socks, unsigned int num_socks) { unsigned int i; int e; fd_set orig_read_set, read_set; int status, max_fd = -1; FD_ZERO(&orig_read_set); for(i = 0; i < num_socks; i++) { #ifdef FD_SETSIZE if (socks[i] >= FD_SETSIZE) errx (1, "fd too large"); #endif FD_SET(socks[i], &orig_read_set); max_fd = max(max_fd, socks[i]); } pgrp = getpid(); /* systemd may cause setpgid to fail with EPERM */ if(setpgid(0, pgrp) < 0 && errno != EPERM) err(1, "setpgid"); signal(SIGTERM, terminate); signal(SIGINT, terminate); signal(SIGCHLD, sigchld); while (term_flag == 0) { read_set = orig_read_set; e = select(max_fd + 1, &read_set, NULL, NULL, NULL); if(rk_IS_SOCKET_ERROR(e)) { if(rk_SOCK_ERRNO != EINTR) krb5_warn(contextp, rk_SOCK_ERRNO, "select"); } else if(e == 0) krb5_warnx(contextp, "select returned 0"); else { for(i = 0; i < num_socks; i++) { if(FD_ISSET(socks[i], &read_set)) if(spawn_child(contextp, socks, num_socks, i) == 0) return; } } } signal(SIGCHLD, SIG_IGN); while ((waitpid(-1, &status, WNOHANG)) > 0) ; exit(0); } void start_server(krb5_context contextp, const char *port_str) { int e; struct kadm_port *p; krb5_socket_t *socks = NULL, *tmp; unsigned int num_socks = 0; int i; if (port_str == NULL) port_str = "+"; parse_ports(contextp, port_str); for(p = kadm_ports; p; p = p->next) { struct addrinfo hints, *ai, *ap; char portstr[32]; memset (&hints, 0, sizeof(hints)); hints.ai_flags = AI_PASSIVE; hints.ai_socktype = SOCK_STREAM; e = getaddrinfo(NULL, p->port, &hints, &ai); if(e) { snprintf(portstr, sizeof(portstr), "%u", p->def_port); e = getaddrinfo(NULL, portstr, &hints, &ai); } if(e) { krb5_warn(contextp, krb5_eai_to_heim_errno(e, errno), "%s", portstr); continue; } i = 0; for(ap = ai; ap; ap = ap->ai_next) i++; tmp = realloc(socks, (num_socks + i) * sizeof(*socks)); if(tmp == NULL) { krb5_warnx(contextp, "failed to reallocate %lu bytes", (unsigned long)(num_socks + i) * sizeof(*socks)); freeaddrinfo(ai); continue; } socks = tmp; for(ap = ai; ap; ap = ap->ai_next) { krb5_socket_t s = socket(ap->ai_family, ap->ai_socktype, ap->ai_protocol); if(rk_IS_BAD_SOCKET(s)) { krb5_warn(contextp, rk_SOCK_ERRNO, "socket"); continue; } socket_set_reuseaddr(s, 1); socket_set_ipv6only(s, 1); if (rk_IS_SOCKET_ERROR(bind (s, ap->ai_addr, ap->ai_addrlen))) { krb5_warn(contextp, rk_SOCK_ERRNO, "bind"); rk_closesocket(s); continue; } if (rk_IS_SOCKET_ERROR(listen (s, SOMAXCONN))) { krb5_warn(contextp, rk_SOCK_ERRNO, "listen"); rk_closesocket(s); continue; } socks[num_socks++] = s; } freeaddrinfo (ai); } if(num_socks == 0) krb5_errx(contextp, 1, "no sockets to listen to - exiting"); roken_detach_finish(NULL, daemon_child); wait_for_connection(contextp, socks, num_socks); free(socks); } heimdal-7.5.0/kadmin/init.c0000644000175000017500000002051513026237312013626 0ustar niknik/* * Copyright (c) 1997-2004 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Portions Copyright (c) 2009 Apple Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "kadmin_locl.h" #include "kadmin-commands.h" #include #define CRE_DUP_OK 1 static kadm5_ret_t create_random_entry(krb5_principal princ, unsigned max_life, unsigned max_rlife, uint32_t attributes, unsigned flags) { kadm5_principal_ent_rec ent; kadm5_ret_t ret; int mask = 0; krb5_keyblock *keys; int n_keys, i; char *name; const char *password; char pwbuf[512]; random_password(pwbuf, sizeof(pwbuf)); password = pwbuf; ret = krb5_unparse_name(context, princ, &name); if (ret) { krb5_warn(context, ret, "failed to unparse principal name"); return ret; } memset(&ent, 0, sizeof(ent)); ent.principal = princ; mask |= KADM5_PRINCIPAL; if (max_life) { ent.max_life = max_life; mask |= KADM5_MAX_LIFE; } if (max_rlife) { ent.max_renewable_life = max_rlife; mask |= KADM5_MAX_RLIFE; } ent.attributes |= attributes | KRB5_KDB_DISALLOW_ALL_TIX; mask |= KADM5_ATTRIBUTES; /* Create the entry with a random password */ ret = kadm5_create_principal(kadm_handle, &ent, mask, password); if(ret) { if (ret == KADM5_DUP && (flags & CRE_DUP_OK)) goto out; krb5_warn(context, ret, "create_random_entry(%s): randkey failed", name); goto out; } /* Replace the string2key based keys with real random bytes */ ret = kadm5_randkey_principal(kadm_handle, princ, &keys, &n_keys); if(ret) { krb5_warn(context, ret, "create_random_entry(%s): randkey failed", name); goto out; } for(i = 0; i < n_keys; i++) krb5_free_keyblock_contents(context, &keys[i]); free(keys); ret = kadm5_get_principal(kadm_handle, princ, &ent, KADM5_PRINCIPAL | KADM5_ATTRIBUTES); if(ret) { krb5_warn(context, ret, "create_random_entry(%s): " "unable to get principal", name); goto out; } ent.attributes &= (~KRB5_KDB_DISALLOW_ALL_TIX); ent.kvno = 1; ret = kadm5_modify_principal(kadm_handle, &ent, KADM5_ATTRIBUTES|KADM5_KVNO); kadm5_free_principal_ent (kadm_handle, &ent); if(ret) { krb5_warn(context, ret, "create_random_entry(%s): " "unable to modify principal", name); goto out; } out: free(name); return ret; } extern int local_flag; int init(struct init_options *opt, int argc, char **argv) { kadm5_ret_t ret; int i; HDB *db; krb5_deltat max_life = 0, max_rlife = 0; if (!local_flag) { krb5_warnx(context, "init is only available in local (-l) mode"); return 0; } if (opt->realm_max_ticket_life_string) { if (str2deltat (opt->realm_max_ticket_life_string, &max_life) != 0) { krb5_warnx (context, "unable to parse \"%s\"", opt->realm_max_ticket_life_string); return 0; } } if (opt->realm_max_renewable_life_string) { if (str2deltat (opt->realm_max_renewable_life_string, &max_rlife) != 0) { krb5_warnx (context, "unable to parse \"%s\"", opt->realm_max_renewable_life_string); return 0; } } db = _kadm5_s_get_db(kadm_handle); ret = db->hdb_open(context, db, O_RDWR | O_CREAT, 0600); if(ret){ krb5_warn(context, ret, "hdb_open"); return 0; } ret = kadm5_log_reinit(kadm_handle, 0); if (ret) krb5_err(context, 1, ret, "Failed iprop log initialization"); kadm5_log_end(kadm_handle); db->hdb_close(context, db); for(i = 0; i < argc; i++){ krb5_principal princ; const char *realm = argv[i]; if (opt->realm_max_ticket_life_string == NULL) { max_life = 0; if(edit_deltat ("Realm max ticket life", &max_life, NULL, 0)) { return 0; } } if (opt->realm_max_renewable_life_string == NULL) { max_rlife = 0; if(edit_deltat("Realm max renewable ticket life", &max_rlife, NULL, 0)) { return 0; } } /* Create `krbtgt/REALM' */ ret = krb5_make_principal(context, &princ, realm, KRB5_TGS_NAME, realm, NULL); if(ret) return 0; create_random_entry(princ, max_life, max_rlife, 0, 0); krb5_free_principal(context, princ); if (opt->bare_flag) continue; /* Create `kadmin/changepw' */ krb5_make_principal(context, &princ, realm, "kadmin", "changepw", NULL); /* * The Windows XP (at least) password changing protocol * request the `kadmin/changepw' ticket with `renewable_ok, * renewable, forwardable' and so fails if we disallow * forwardable here. */ create_random_entry(princ, 5*60, 5*60, KRB5_KDB_DISALLOW_TGT_BASED| KRB5_KDB_PWCHANGE_SERVICE| KRB5_KDB_DISALLOW_POSTDATED| KRB5_KDB_DISALLOW_RENEWABLE| KRB5_KDB_DISALLOW_PROXIABLE| KRB5_KDB_REQUIRES_PRE_AUTH, 0); krb5_free_principal(context, princ); /* Create `kadmin/admin' */ krb5_make_principal(context, &princ, realm, "kadmin", "admin", NULL); create_random_entry(princ, 60*60, 60*60, KRB5_KDB_REQUIRES_PRE_AUTH, 0); krb5_free_principal(context, princ); /* Create `changepw/kerberos' (for v4 compat) */ krb5_make_principal(context, &princ, realm, "changepw", "kerberos", NULL); create_random_entry(princ, 60*60, 60*60, KRB5_KDB_DISALLOW_TGT_BASED| KRB5_KDB_PWCHANGE_SERVICE, 0); krb5_free_principal(context, princ); /* Create `kadmin/hprop' for database propagation */ krb5_make_principal(context, &princ, realm, "kadmin", "hprop", NULL); create_random_entry(princ, 60*60, 60*60, KRB5_KDB_REQUIRES_PRE_AUTH| KRB5_KDB_DISALLOW_TGT_BASED, 0); krb5_free_principal(context, princ); /* Create `WELLKNOWN/ANONYMOUS' for anonymous as-req */ krb5_make_principal(context, &princ, realm, KRB5_WELLKNOWN_NAME, KRB5_ANON_NAME, NULL); create_random_entry(princ, 60*60, 60*60, KRB5_KDB_REQUIRES_PRE_AUTH, 0); krb5_free_principal(context, princ); /* Create `WELLKNONW/org.h5l.fast-cookie@WELLKNOWN:ORG.H5L' for FAST cookie */ krb5_make_principal(context, &princ, KRB5_WELLKNOWN_ORG_H5L_REALM, KRB5_WELLKNOWN_NAME, "org.h5l.fast-cookie", NULL); create_random_entry(princ, 60*60, 60*60, KRB5_KDB_REQUIRES_PRE_AUTH| KRB5_KDB_DISALLOW_TGT_BASED| KRB5_KDB_DISALLOW_ALL_TIX, CRE_DUP_OK); krb5_free_principal(context, princ); /* Create `default' */ { kadm5_principal_ent_rec ent; int mask = 0; memset (&ent, 0, sizeof(ent)); mask |= KADM5_PRINCIPAL; krb5_make_principal(context, &ent.principal, realm, "default", NULL); mask |= KADM5_MAX_LIFE; ent.max_life = 24 * 60 * 60; mask |= KADM5_MAX_RLIFE; ent.max_renewable_life = 7 * ent.max_life; ent.attributes = KRB5_KDB_DISALLOW_ALL_TIX; mask |= KADM5_ATTRIBUTES; ret = kadm5_create_principal(kadm_handle, &ent, mask, ""); if (ret) krb5_err (context, 1, ret, "kadm5_create_principal"); krb5_free_principal(context, ent.principal); } } return 0; } heimdal-7.5.0/kadmin/ext.c0000644000175000017500000001304713026237312013465 0ustar niknik/* * Copyright (c) 1997 - 2006 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "kadmin_locl.h" #include "kadmin-commands.h" struct ext_keytab_data { krb5_keytab keytab; int random_key_flag; }; static int do_ext_keytab(krb5_principal principal, void *data) { krb5_error_code ret; kadm5_principal_ent_rec princ; struct ext_keytab_data *e = data; krb5_keytab_entry *keys = NULL; krb5_keyblock *k = NULL; size_t i; int n_k = 0; uint32_t mask; char *unparsed = NULL; mask = KADM5_PRINCIPAL; if (!e->random_key_flag) mask |= KADM5_KVNO | KADM5_KEY_DATA; ret = kadm5_get_principal(kadm_handle, principal, &princ, mask); if (ret) return ret; ret = krb5_unparse_name(context, principal, &unparsed); if (ret) goto out; if (!e->random_key_flag) { if (princ.n_key_data == 0) { krb5_warnx(context, "principal has no keys, or user lacks " "get-keys privilege for %s", unparsed); goto out; } /* * kadmin clients and servers from master between 1.5 and 1.6 * can have corrupted a principal's keys in the HDB. If some * are bogus but not all are, then that must have happened. * * If all keys are bogus then the server may be a pre-1.6, * post-1.5 server and the client lacks get-keys privilege, or * the keys are corrupted. We can't tell here. */ if (kadm5_all_keys_are_bogus(princ.n_key_data, princ.key_data)) { krb5_warnx(context, "user lacks get-keys privilege for %s", unparsed); goto out; } if (kadm5_some_keys_are_bogus(princ.n_key_data, princ.key_data)) { krb5_warnx(context, "some keys for %s are corrupted in the HDB", unparsed); } keys = calloc(sizeof(*keys), princ.n_key_data); if (keys == NULL) { ret = krb5_enomem(context); goto out; } for (i = 0; i < princ.n_key_data; i++) { krb5_key_data *kd = &princ.key_data[i]; /* Don't extract bogus keys */ if (kadm5_all_keys_are_bogus(1, kd)) continue; keys[i].principal = princ.principal; keys[i].vno = kd->key_data_kvno; keys[i].keyblock.keytype = kd->key_data_type[0]; keys[i].keyblock.keyvalue.length = kd->key_data_length[0]; keys[i].keyblock.keyvalue.data = kd->key_data_contents[0]; keys[i].timestamp = time(NULL); n_k++; } } else if (e->random_key_flag) { ret = kadm5_randkey_principal(kadm_handle, principal, &k, &n_k); if (ret) goto out; keys = calloc(sizeof(*keys), n_k); if (keys == NULL) { ret = krb5_enomem(context); goto out; } for (i = 0; i < n_k; i++) { keys[i].principal = principal; keys[i].vno = princ.kvno + 1; /* XXX get entry again */ keys[i].keyblock = k[i]; keys[i].timestamp = time(NULL); } } if (n_k == 0) krb5_warn(context, ret, "no keys written to keytab for %s", unparsed); for (i = 0; i < n_k; i++) { ret = krb5_kt_add_entry(context, e->keytab, &keys[i]); if (ret) krb5_warn(context, ret, "krb5_kt_add_entry(%lu)", (unsigned long)i); } out: kadm5_free_principal_ent(kadm_handle, &princ); if (k) { for (i = 0; i < n_k; i++) memset(k[i].keyvalue.data, 0, k[i].keyvalue.length); free(k); } free(unparsed); free(keys); return 0; } int ext_keytab(struct ext_keytab_options *opt, int argc, char **argv) { krb5_error_code ret; int i; struct ext_keytab_data data; if (opt->keytab_string == NULL) ret = krb5_kt_default(context, &data.keytab); else ret = krb5_kt_resolve(context, opt->keytab_string, &data.keytab); if(ret){ krb5_warn(context, ret, "krb5_kt_resolve"); return 1; } data.random_key_flag = opt->random_key_flag; for(i = 0; i < argc; i++) { ret = foreach_principal(argv[i], do_ext_keytab, "ext", &data); if (ret) break; } krb5_kt_close(context, data.keytab); return ret != 0; } heimdal-7.5.0/kadmin/mod.c0000644000175000017500000002133313026237312013441 0ustar niknik/* * Copyright (c) 1997 - 2006 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "kadmin_locl.h" #include "kadmin-commands.h" static void add_tl(kadm5_principal_ent_rec *princ, int type, krb5_data *data) { krb5_tl_data *tl, **ptl; tl = ecalloc(1, sizeof(*tl)); tl->tl_data_next = NULL; tl->tl_data_type = type; tl->tl_data_length = data->length; tl->tl_data_contents = data->data; princ->n_tl_data++; ptl = &princ->tl_data; while (*ptl != NULL) ptl = &(*ptl)->tl_data_next; *ptl = tl; return; } static void add_constrained_delegation(krb5_context contextp, kadm5_principal_ent_rec *princ, struct getarg_strings *strings) { krb5_error_code ret; HDB_extension ext; krb5_data buf; size_t size = 0; memset(&ext, 0, sizeof(ext)); ext.mandatory = FALSE; ext.data.element = choice_HDB_extension_data_allowed_to_delegate_to; if (strings->num_strings == 1 && strings->strings[0][0] == '\0') { ext.data.u.allowed_to_delegate_to.val = NULL; ext.data.u.allowed_to_delegate_to.len = 0; } else { krb5_principal p; int i; ext.data.u.allowed_to_delegate_to.val = calloc(strings->num_strings, sizeof(ext.data.u.allowed_to_delegate_to.val[0])); ext.data.u.allowed_to_delegate_to.len = strings->num_strings; for (i = 0; i < strings->num_strings; i++) { ret = krb5_parse_name(contextp, strings->strings[i], &p); if (ret) abort(); ret = copy_Principal(p, &ext.data.u.allowed_to_delegate_to.val[i]); if (ret) abort(); krb5_free_principal(contextp, p); } } ASN1_MALLOC_ENCODE(HDB_extension, buf.data, buf.length, &ext, &size, ret); free_HDB_extension(&ext); if (ret) abort(); if (buf.length != size) abort(); add_tl(princ, KRB5_TL_EXTENSION, &buf); } static void add_aliases(krb5_context contextp, kadm5_principal_ent_rec *princ, struct getarg_strings *strings) { krb5_error_code ret; HDB_extension ext; krb5_data buf; krb5_principal p; size_t size = 0; int i; memset(&ext, 0, sizeof(ext)); ext.mandatory = FALSE; ext.data.element = choice_HDB_extension_data_aliases; ext.data.u.aliases.case_insensitive = 0; if (strings->num_strings == 1 && strings->strings[0][0] == '\0') { ext.data.u.aliases.aliases.val = NULL; ext.data.u.aliases.aliases.len = 0; } else { ext.data.u.aliases.aliases.val = calloc(strings->num_strings, sizeof(ext.data.u.aliases.aliases.val[0])); ext.data.u.aliases.aliases.len = strings->num_strings; for (i = 0; i < strings->num_strings; i++) { ret = krb5_parse_name(contextp, strings->strings[i], &p); ret = copy_Principal(p, &ext.data.u.aliases.aliases.val[i]); krb5_free_principal(contextp, p); } } ASN1_MALLOC_ENCODE(HDB_extension, buf.data, buf.length, &ext, &size, ret); free_HDB_extension(&ext); if (ret) abort(); if (buf.length != size) abort(); add_tl(princ, KRB5_TL_EXTENSION, &buf); } static void add_pkinit_acl(krb5_context contextp, kadm5_principal_ent_rec *princ, struct getarg_strings *strings) { krb5_error_code ret; HDB_extension ext; krb5_data buf; size_t size = 0; int i; memset(&ext, 0, sizeof(ext)); ext.mandatory = FALSE; ext.data.element = choice_HDB_extension_data_pkinit_acl; ext.data.u.aliases.case_insensitive = 0; if (strings->num_strings == 1 && strings->strings[0][0] == '\0') { ext.data.u.pkinit_acl.val = NULL; ext.data.u.pkinit_acl.len = 0; } else { ext.data.u.pkinit_acl.val = calloc(strings->num_strings, sizeof(ext.data.u.pkinit_acl.val[0])); ext.data.u.pkinit_acl.len = strings->num_strings; for (i = 0; i < strings->num_strings; i++) { ext.data.u.pkinit_acl.val[i].subject = estrdup(strings->strings[i]); } } ASN1_MALLOC_ENCODE(HDB_extension, buf.data, buf.length, &ext, &size, ret); free_HDB_extension(&ext); if (ret) abort(); if (buf.length != size) abort(); add_tl(princ, KRB5_TL_EXTENSION, &buf); } static void add_kvno_diff(krb5_context contextp, kadm5_principal_ent_rec *princ, int is_svc_diff, krb5_kvno kvno_diff) { krb5_error_code ret; HDB_extension ext; krb5_data buf; size_t size = 0; if (kvno_diff < 0) return; if (kvno_diff > 2048) kvno_diff = 2048; if (is_svc_diff) { ext.data.element = choice_HDB_extension_data_hist_kvno_diff_svc; ext.data.u.hist_kvno_diff_svc = (unsigned int)kvno_diff; } else { ext.data.element = choice_HDB_extension_data_hist_kvno_diff_clnt; ext.data.u.hist_kvno_diff_clnt = (unsigned int)kvno_diff; } ASN1_MALLOC_ENCODE(HDB_extension, buf.data, buf.length, &ext, &size, ret); if (ret) abort(); if (buf.length != size) abort(); add_tl(princ, KRB5_TL_EXTENSION, &buf); } static int do_mod_entry(krb5_principal principal, void *data) { krb5_error_code ret; kadm5_principal_ent_rec princ; int mask = 0; struct modify_options *e = data; memset (&princ, 0, sizeof(princ)); ret = kadm5_get_principal(kadm_handle, principal, &princ, KADM5_PRINCIPAL | KADM5_ATTRIBUTES | KADM5_MAX_LIFE | KADM5_MAX_RLIFE | KADM5_PRINC_EXPIRE_TIME | KADM5_PW_EXPIRATION); if(ret) return ret; if(e->max_ticket_life_string || e->max_renewable_life_string || e->expiration_time_string || e->pw_expiration_time_string || e->attributes_string || e->policy_string || e->kvno_integer != -1 || e->constrained_delegation_strings.num_strings || e->alias_strings.num_strings || e->pkinit_acl_strings.num_strings || e->hist_kvno_diff_clnt_integer != -1 || e->hist_kvno_diff_svc_integer != -1) { ret = set_entry(context, &princ, &mask, e->max_ticket_life_string, e->max_renewable_life_string, e->expiration_time_string, e->pw_expiration_time_string, e->attributes_string, e->policy_string); if(e->kvno_integer != -1) { princ.kvno = e->kvno_integer; mask |= KADM5_KVNO; } if (e->constrained_delegation_strings.num_strings) { add_constrained_delegation(context, &princ, &e->constrained_delegation_strings); mask |= KADM5_TL_DATA; } if (e->alias_strings.num_strings) { add_aliases(context, &princ, &e->alias_strings); mask |= KADM5_TL_DATA; } if (e->pkinit_acl_strings.num_strings) { add_pkinit_acl(context, &princ, &e->pkinit_acl_strings); mask |= KADM5_TL_DATA; } if (e->hist_kvno_diff_clnt_integer != -1) { add_kvno_diff(context, &princ, 0, e->hist_kvno_diff_clnt_integer); mask |= KADM5_TL_DATA; } if (e->hist_kvno_diff_svc_integer != -1) { add_kvno_diff(context, &princ, 1, e->hist_kvno_diff_svc_integer); mask |= KADM5_TL_DATA; } } else ret = edit_entry(&princ, &mask, NULL, 0); if(ret == 0) { ret = kadm5_modify_principal(kadm_handle, &princ, mask); if(ret) krb5_warn(context, ret, "kadm5_modify_principal"); } kadm5_free_principal_ent(kadm_handle, &princ); return ret; } int mod_entry(struct modify_options *opt, int argc, char **argv) { krb5_error_code ret = 0; int i; for(i = 0; i < argc; i++) { ret = foreach_principal(argv[i], do_mod_entry, "mod", opt); if (ret) break; } return ret != 0; } heimdal-7.5.0/kadmin/Makefile.in0000644000175000017500000016133413212444520014567 0ustar niknik# Makefile.in generated by automake 1.15.1 from Makefile.am. # @configure_input@ # Copyright (C) 1994-2017 Free Software Foundation, Inc. # This Makefile.in is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, # with or without modifications, as long as this notice is preserved. # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY, to the extent permitted by law; without # even the implied warranty of MERCHANTABILITY or FITNESS FOR A # PARTICULAR PURPOSE. @SET_MAKE@ # $Id$ # $Id$ # $Id$ VPATH = @srcdir@ am__is_gnu_make = { \ if test -z '$(MAKELEVEL)'; then \ false; \ elif test -n '$(MAKE_HOST)'; then \ true; \ elif test -n '$(MAKE_VERSION)' && test -n '$(CURDIR)'; then \ true; \ else \ false; \ fi; \ } am__make_running_with_option = \ case $${target_option-} in \ ?) ;; \ *) echo "am__make_running_with_option: internal error: invalid" \ "target option '$${target_option-}' specified" >&2; \ exit 1;; \ esac; \ has_opt=no; \ sane_makeflags=$$MAKEFLAGS; \ if $(am__is_gnu_make); then \ sane_makeflags=$$MFLAGS; \ else \ case $$MAKEFLAGS in \ *\\[\ \ ]*) \ bs=\\; \ sane_makeflags=`printf '%s\n' "$$MAKEFLAGS" \ | sed "s/$$bs$$bs[$$bs $$bs ]*//g"`;; \ esac; \ fi; \ skip_next=no; \ strip_trailopt () \ { \ flg=`printf '%s\n' "$$flg" | sed "s/$$1.*$$//"`; \ }; \ for flg in $$sane_makeflags; do \ test $$skip_next = yes && { skip_next=no; continue; }; \ case $$flg in \ *=*|--*) continue;; \ -*I) strip_trailopt 'I'; skip_next=yes;; \ -*I?*) strip_trailopt 'I';; \ -*O) strip_trailopt 'O'; skip_next=yes;; \ -*O?*) strip_trailopt 'O';; \ -*l) strip_trailopt 'l'; skip_next=yes;; \ -*l?*) strip_trailopt 'l';; \ -[dEDm]) skip_next=yes;; \ -[JT]) skip_next=yes;; \ esac; \ case $$flg in \ *$$target_option*) has_opt=yes; break;; \ esac; \ done; \ test $$has_opt = yes am__make_dryrun = (target_option=n; $(am__make_running_with_option)) am__make_keepgoing = (target_option=k; $(am__make_running_with_option)) pkgdatadir = $(datadir)/@PACKAGE@ pkgincludedir = $(includedir)/@PACKAGE@ pkglibdir = $(libdir)/@PACKAGE@ pkglibexecdir = $(libexecdir)/@PACKAGE@ am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd install_sh_DATA = $(install_sh) -c -m 644 install_sh_PROGRAM = $(install_sh) -c install_sh_SCRIPT = $(install_sh) -c INSTALL_HEADER = $(INSTALL_DATA) transform = $(program_transform_name) NORMAL_INSTALL = : PRE_INSTALL = : POST_INSTALL = : NORMAL_UNINSTALL = : PRE_UNINSTALL = : POST_UNINSTALL = : build_triplet = @build@ host_triplet = @host@ bin_PROGRAMS = kadmin$(EXEEXT) libexec_PROGRAMS = kadmind$(EXEEXT) noinst_PROGRAMS = add_random_users$(EXEEXT) TESTS = test_util$(EXEEXT) check_PROGRAMS = $(am__EXEEXT_1) subdir = kadmin ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 am__aclocal_m4_deps = $(top_srcdir)/cf/aix.m4 \ $(top_srcdir)/cf/auth-modules.m4 \ $(top_srcdir)/cf/broken-getaddrinfo.m4 \ $(top_srcdir)/cf/broken-glob.m4 \ $(top_srcdir)/cf/broken-realloc.m4 \ $(top_srcdir)/cf/broken-snprintf.m4 $(top_srcdir)/cf/broken.m4 \ $(top_srcdir)/cf/broken2.m4 $(top_srcdir)/cf/c-attribute.m4 \ $(top_srcdir)/cf/capabilities.m4 \ $(top_srcdir)/cf/check-compile-et.m4 \ $(top_srcdir)/cf/check-getpwnam_r-posix.m4 \ $(top_srcdir)/cf/check-man.m4 \ $(top_srcdir)/cf/check-netinet-ip-and-tcp.m4 \ $(top_srcdir)/cf/check-type-extra.m4 \ $(top_srcdir)/cf/check-var.m4 $(top_srcdir)/cf/crypto.m4 \ $(top_srcdir)/cf/db.m4 $(top_srcdir)/cf/destdirs.m4 \ $(top_srcdir)/cf/dispatch.m4 $(top_srcdir)/cf/dlopen.m4 \ $(top_srcdir)/cf/find-func-no-libs.m4 \ $(top_srcdir)/cf/find-func-no-libs2.m4 \ $(top_srcdir)/cf/find-func.m4 \ $(top_srcdir)/cf/find-if-not-broken.m4 \ $(top_srcdir)/cf/framework-security.m4 \ $(top_srcdir)/cf/have-struct-field.m4 \ $(top_srcdir)/cf/have-type.m4 $(top_srcdir)/cf/irix.m4 \ $(top_srcdir)/cf/krb-bigendian.m4 \ $(top_srcdir)/cf/krb-func-getlogin.m4 \ $(top_srcdir)/cf/krb-ipv6.m4 $(top_srcdir)/cf/krb-prog-ln-s.m4 \ $(top_srcdir)/cf/krb-prog-perl.m4 \ $(top_srcdir)/cf/krb-readline.m4 \ $(top_srcdir)/cf/krb-struct-spwd.m4 \ $(top_srcdir)/cf/krb-struct-winsize.m4 \ $(top_srcdir)/cf/largefile.m4 $(top_srcdir)/cf/libtool.m4 \ $(top_srcdir)/cf/ltoptions.m4 $(top_srcdir)/cf/ltsugar.m4 \ $(top_srcdir)/cf/ltversion.m4 $(top_srcdir)/cf/lt~obsolete.m4 \ $(top_srcdir)/cf/mips-abi.m4 $(top_srcdir)/cf/misc.m4 \ $(top_srcdir)/cf/need-proto.m4 $(top_srcdir)/cf/osfc2.m4 \ $(top_srcdir)/cf/otp.m4 $(top_srcdir)/cf/pkg.m4 \ $(top_srcdir)/cf/proto-compat.m4 $(top_srcdir)/cf/pthreads.m4 \ $(top_srcdir)/cf/resolv.m4 $(top_srcdir)/cf/retsigtype.m4 \ $(top_srcdir)/cf/roken-frag.m4 \ $(top_srcdir)/cf/socket-wrapper.m4 $(top_srcdir)/cf/sunos.m4 \ $(top_srcdir)/cf/telnet.m4 $(top_srcdir)/cf/test-package.m4 \ $(top_srcdir)/cf/version-script.m4 $(top_srcdir)/cf/wflags.m4 \ $(top_srcdir)/cf/win32.m4 $(top_srcdir)/cf/with-all.m4 \ $(top_srcdir)/acinclude.m4 $(top_srcdir)/configure.ac am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \ $(ACLOCAL_M4) DIST_COMMON = $(srcdir)/Makefile.am $(am__DIST_COMMON) mkinstalldirs = $(install_sh) -d CONFIG_HEADER = $(top_builddir)/include/config.h CONFIG_CLEAN_FILES = CONFIG_CLEAN_VPATH_FILES = am__installdirs = "$(DESTDIR)$(bindir)" "$(DESTDIR)$(libexecdir)" \ "$(DESTDIR)$(man1dir)" "$(DESTDIR)$(man8dir)" am__EXEEXT_1 = test_util$(EXEEXT) PROGRAMS = $(bin_PROGRAMS) $(libexec_PROGRAMS) $(noinst_PROGRAMS) am_add_random_users_OBJECTS = add-random-users.$(OBJEXT) add_random_users_OBJECTS = $(am_add_random_users_OBJECTS) am__DEPENDENCIES_1 = am__DEPENDENCIES_2 = $(top_builddir)/lib/hdb/libhdb.la \ $(top_builddir)/lib/krb5/libkrb5.la $(am__DEPENDENCIES_1) \ $(top_builddir)/lib/asn1/libasn1.la $(am__DEPENDENCIES_1) \ $(am__DEPENDENCIES_1) $(am__DEPENDENCIES_1) \ $(am__DEPENDENCIES_1) $(am__DEPENDENCIES_1) add_random_users_DEPENDENCIES = \ $(top_builddir)/lib/kadm5/libkadm5clnt.la \ $(top_builddir)/lib/kadm5/libkadm5srv.la $(am__DEPENDENCIES_2) \ $(am__DEPENDENCIES_1) AM_V_lt = $(am__v_lt_@AM_V@) am__v_lt_ = $(am__v_lt_@AM_DEFAULT_V@) am__v_lt_0 = --silent am__v_lt_1 = dist_kadmin_OBJECTS = ank.$(OBJEXT) add_enctype.$(OBJEXT) \ check.$(OBJEXT) cpw.$(OBJEXT) del.$(OBJEXT) \ del_enctype.$(OBJEXT) dump.$(OBJEXT) ext.$(OBJEXT) \ get.$(OBJEXT) init.$(OBJEXT) kadmin.$(OBJEXT) load.$(OBJEXT) \ mod.$(OBJEXT) rename.$(OBJEXT) stash.$(OBJEXT) util.$(OBJEXT) \ pw_quality.$(OBJEXT) random_password.$(OBJEXT) nodist_kadmin_OBJECTS = kadmin-commands.$(OBJEXT) kadmin_OBJECTS = $(dist_kadmin_OBJECTS) $(nodist_kadmin_OBJECTS) kadmin_DEPENDENCIES = $(top_builddir)/lib/kadm5/libkadm5clnt.la \ $(top_builddir)/lib/kadm5/libkadm5srv.la \ $(top_builddir)/lib/sl/libsl.la $(am__DEPENDENCIES_1) \ $(am__DEPENDENCIES_2) $(am__DEPENDENCIES_1) am_kadmind_OBJECTS = rpc.$(OBJEXT) server.$(OBJEXT) kadmind.$(OBJEXT) \ kadm_conn.$(OBJEXT) kadmind_OBJECTS = $(am_kadmind_OBJECTS) kadmind_DEPENDENCIES = $(top_builddir)/lib/kadm5/libkadm5srv.la \ ../lib/gssapi/libgssapi.la $(am__DEPENDENCIES_2) \ $(am__DEPENDENCIES_1) $(am__DEPENDENCIES_1) am_test_util_OBJECTS = test_util.$(OBJEXT) util.$(OBJEXT) test_util_OBJECTS = $(am_test_util_OBJECTS) am__DEPENDENCIES_3 = $(top_builddir)/lib/kadm5/libkadm5clnt.la \ $(top_builddir)/lib/kadm5/libkadm5srv.la \ $(top_builddir)/lib/sl/libsl.la $(am__DEPENDENCIES_1) \ $(am__DEPENDENCIES_2) $(am__DEPENDENCIES_1) test_util_DEPENDENCIES = $(am__DEPENDENCIES_3) AM_V_P = $(am__v_P_@AM_V@) am__v_P_ = $(am__v_P_@AM_DEFAULT_V@) am__v_P_0 = false am__v_P_1 = : AM_V_GEN = $(am__v_GEN_@AM_V@) am__v_GEN_ = $(am__v_GEN_@AM_DEFAULT_V@) am__v_GEN_0 = @echo " GEN " $@; am__v_GEN_1 = AM_V_at = $(am__v_at_@AM_V@) am__v_at_ = $(am__v_at_@AM_DEFAULT_V@) am__v_at_0 = @ am__v_at_1 = depcomp = $(SHELL) $(top_srcdir)/depcomp am__depfiles_maybe = depfiles am__mv = mv -f COMPILE = $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) \ $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) LTCOMPILE = $(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) \ $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) \ $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) \ $(AM_CFLAGS) $(CFLAGS) AM_V_CC = $(am__v_CC_@AM_V@) am__v_CC_ = $(am__v_CC_@AM_DEFAULT_V@) am__v_CC_0 = @echo " CC " $@; am__v_CC_1 = CCLD = $(CC) LINK = $(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) \ $(LIBTOOLFLAGS) --mode=link $(CCLD) $(AM_CFLAGS) $(CFLAGS) \ $(AM_LDFLAGS) $(LDFLAGS) -o $@ AM_V_CCLD = $(am__v_CCLD_@AM_V@) am__v_CCLD_ = $(am__v_CCLD_@AM_DEFAULT_V@) am__v_CCLD_0 = @echo " CCLD " $@; am__v_CCLD_1 = SOURCES = $(add_random_users_SOURCES) $(dist_kadmin_SOURCES) \ $(nodist_kadmin_SOURCES) $(kadmind_SOURCES) \ $(test_util_SOURCES) DIST_SOURCES = $(add_random_users_SOURCES) $(dist_kadmin_SOURCES) \ $(kadmind_SOURCES) $(test_util_SOURCES) am__can_run_installinfo = \ case $$AM_UPDATE_INFO_DIR in \ n|no|NO) false;; \ *) (install-info --version) >/dev/null 2>&1;; \ esac am__vpath_adj_setup = srcdirstrip=`echo "$(srcdir)" | sed 's|.|.|g'`; am__vpath_adj = case $$p in \ $(srcdir)/*) f=`echo "$$p" | sed "s|^$$srcdirstrip/||"`;; \ *) f=$$p;; \ esac; am__strip_dir = f=`echo $$p | sed -e 's|^.*/||'`; am__install_max = 40 am__nobase_strip_setup = \ srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*|]/\\\\&/g'` am__nobase_strip = \ for p in $$list; do echo "$$p"; done | sed -e "s|$$srcdirstrip/||" am__nobase_list = $(am__nobase_strip_setup); \ for p in $$list; do echo "$$p $$p"; done | \ sed "s| $$srcdirstrip/| |;"' / .*\//!s/ .*/ ./; s,\( .*\)/[^/]*$$,\1,' | \ $(AWK) 'BEGIN { files["."] = "" } { files[$$2] = files[$$2] " " $$1; \ if (++n[$$2] == $(am__install_max)) \ { print $$2, files[$$2]; n[$$2] = 0; files[$$2] = "" } } \ END { for (dir in files) print dir, files[dir] }' am__base_list = \ sed '$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;s/\n/ /g' | \ sed '$$!N;$$!N;$$!N;$$!N;s/\n/ /g' am__uninstall_files_from_dir = { \ test -z "$$files" \ || { test ! -d "$$dir" && test ! -f "$$dir" && test ! -r "$$dir"; } \ || { echo " ( cd '$$dir' && rm -f" $$files ")"; \ $(am__cd) "$$dir" && rm -f $$files; }; \ } man1dir = $(mandir)/man1 man8dir = $(mandir)/man8 MANS = $(man_MANS) am__tagged_files = $(HEADERS) $(SOURCES) $(TAGS_FILES) $(LISP) # Read a list of newline-separated strings from the standard input, # and print each of them once, without duplicates. Input order is # *not* preserved. am__uniquify_input = $(AWK) '\ BEGIN { nonempty = 0; } \ { items[$$0] = 1; nonempty = 1; } \ END { if (nonempty) { for (i in items) print i; }; } \ ' # Make sure the list of sources is unique. This is necessary because, # e.g., the same source file might be shared among _SOURCES variables # for different programs/libraries. am__define_uniq_tagged_files = \ list='$(am__tagged_files)'; \ unique=`for i in $$list; do \ if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ done | $(am__uniquify_input)` ETAGS = etags CTAGS = ctags am__tty_colors_dummy = \ mgn= red= grn= lgn= blu= brg= std=; \ am__color_tests=no am__tty_colors = { \ $(am__tty_colors_dummy); \ if test "X$(AM_COLOR_TESTS)" = Xno; then \ am__color_tests=no; \ elif test "X$(AM_COLOR_TESTS)" = Xalways; then \ am__color_tests=yes; \ elif test "X$$TERM" != Xdumb && { test -t 1; } 2>/dev/null; then \ am__color_tests=yes; \ fi; \ if test $$am__color_tests = yes; then \ red=''; \ grn=''; \ lgn=''; \ blu=''; \ mgn=''; \ brg=''; \ std=''; \ fi; \ } am__recheck_rx = ^[ ]*:recheck:[ ]* am__global_test_result_rx = ^[ ]*:global-test-result:[ ]* am__copy_in_global_log_rx = ^[ ]*:copy-in-global-log:[ ]* # A command that, given a newline-separated list of test names on the # standard input, print the name of the tests that are to be re-run # upon "make recheck". am__list_recheck_tests = $(AWK) '{ \ recheck = 1; \ while ((rc = (getline line < ($$0 ".trs"))) != 0) \ { \ if (rc < 0) \ { \ if ((getline line2 < ($$0 ".log")) < 0) \ recheck = 0; \ break; \ } \ else if (line ~ /$(am__recheck_rx)[nN][Oo]/) \ { \ recheck = 0; \ break; \ } \ else if (line ~ /$(am__recheck_rx)[yY][eE][sS]/) \ { \ break; \ } \ }; \ if (recheck) \ print $$0; \ close ($$0 ".trs"); \ close ($$0 ".log"); \ }' # A command that, given a newline-separated list of test names on the # standard input, create the global log from their .trs and .log files. am__create_global_log = $(AWK) ' \ function fatal(msg) \ { \ print "fatal: making $@: " msg | "cat >&2"; \ exit 1; \ } \ function rst_section(header) \ { \ print header; \ len = length(header); \ for (i = 1; i <= len; i = i + 1) \ printf "="; \ printf "\n\n"; \ } \ { \ copy_in_global_log = 1; \ global_test_result = "RUN"; \ while ((rc = (getline line < ($$0 ".trs"))) != 0) \ { \ if (rc < 0) \ fatal("failed to read from " $$0 ".trs"); \ if (line ~ /$(am__global_test_result_rx)/) \ { \ sub("$(am__global_test_result_rx)", "", line); \ sub("[ ]*$$", "", line); \ global_test_result = line; \ } \ else if (line ~ /$(am__copy_in_global_log_rx)[nN][oO]/) \ copy_in_global_log = 0; \ }; \ if (copy_in_global_log) \ { \ rst_section(global_test_result ": " $$0); \ while ((rc = (getline line < ($$0 ".log"))) != 0) \ { \ if (rc < 0) \ fatal("failed to read from " $$0 ".log"); \ print line; \ }; \ printf "\n"; \ }; \ close ($$0 ".trs"); \ close ($$0 ".log"); \ }' # Restructured Text title. am__rst_title = { sed 's/.*/ & /;h;s/./=/g;p;x;s/ *$$//;p;g' && echo; } # Solaris 10 'make', and several other traditional 'make' implementations, # pass "-e" to $(SHELL), and POSIX 2008 even requires this. Work around it # by disabling -e (using the XSI extension "set +e") if it's set. am__sh_e_setup = case $$- in *e*) set +e;; esac # Default flags passed to test drivers. am__common_driver_flags = \ --color-tests "$$am__color_tests" \ --enable-hard-errors "$$am__enable_hard_errors" \ --expect-failure "$$am__expect_failure" # To be inserted before the command running the test. Creates the # directory for the log if needed. Stores in $dir the directory # containing $f, in $tst the test, in $log the log. Executes the # developer- defined test setup AM_TESTS_ENVIRONMENT (if any), and # passes TESTS_ENVIRONMENT. Set up options for the wrapper that # will run the test scripts (or their associated LOG_COMPILER, if # thy have one). am__check_pre = \ $(am__sh_e_setup); \ $(am__vpath_adj_setup) $(am__vpath_adj) \ $(am__tty_colors); \ srcdir=$(srcdir); export srcdir; \ case "$@" in \ */*) am__odir=`echo "./$@" | sed 's|/[^/]*$$||'`;; \ *) am__odir=.;; \ esac; \ test "x$$am__odir" = x"." || test -d "$$am__odir" \ || $(MKDIR_P) "$$am__odir" || exit $$?; \ if test -f "./$$f"; then dir=./; \ elif test -f "$$f"; then dir=; \ else dir="$(srcdir)/"; fi; \ tst=$$dir$$f; log='$@'; \ if test -n '$(DISABLE_HARD_ERRORS)'; then \ am__enable_hard_errors=no; \ else \ am__enable_hard_errors=yes; \ fi; \ case " $(XFAIL_TESTS) " in \ *[\ \ ]$$f[\ \ ]* | *[\ \ ]$$dir$$f[\ \ ]*) \ am__expect_failure=yes;; \ *) \ am__expect_failure=no;; \ esac; \ $(AM_TESTS_ENVIRONMENT) $(TESTS_ENVIRONMENT) # A shell command to get the names of the tests scripts with any registered # extension removed (i.e., equivalently, the names of the test logs, with # the '.log' extension removed). The result is saved in the shell variable # '$bases'. This honors runtime overriding of TESTS and TEST_LOGS. Sadly, # we cannot use something simpler, involving e.g., "$(TEST_LOGS:.log=)", # since that might cause problem with VPATH rewrites for suffix-less tests. # See also 'test-harness-vpath-rewrite.sh' and 'test-trs-basic.sh'. am__set_TESTS_bases = \ bases='$(TEST_LOGS)'; \ bases=`for i in $$bases; do echo $$i; done | sed 's/\.log$$//'`; \ bases=`echo $$bases` RECHECK_LOGS = $(TEST_LOGS) AM_RECURSIVE_TARGETS = check recheck TEST_SUITE_LOG = test-suite.log TEST_EXTENSIONS = @EXEEXT@ .test LOG_DRIVER = $(SHELL) $(top_srcdir)/test-driver LOG_COMPILE = $(LOG_COMPILER) $(AM_LOG_FLAGS) $(LOG_FLAGS) am__set_b = \ case '$@' in \ */*) \ case '$*' in \ */*) b='$*';; \ *) b=`echo '$@' | sed 's/\.log$$//'`; \ esac;; \ *) \ b='$*';; \ esac am__test_logs1 = $(TESTS:=.log) am__test_logs2 = $(am__test_logs1:@EXEEXT@.log=.log) TEST_LOGS = $(am__test_logs2:.test.log=.log) TEST_LOG_DRIVER = $(SHELL) $(top_srcdir)/test-driver TEST_LOG_COMPILE = $(TEST_LOG_COMPILER) $(AM_TEST_LOG_FLAGS) \ $(TEST_LOG_FLAGS) am__DIST_COMMON = $(srcdir)/Makefile.in \ $(top_srcdir)/Makefile.am.common \ $(top_srcdir)/cf/Makefile.am.common $(top_srcdir)/depcomp \ $(top_srcdir)/test-driver ChangeLog DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST) ACLOCAL = @ACLOCAL@ AIX_EXTRA_KAFS = @AIX_EXTRA_KAFS@ AMTAR = @AMTAR@ AM_DEFAULT_VERBOSITY = @AM_DEFAULT_VERBOSITY@ AR = @AR@ AS = @AS@ ASN1_COMPILE = @ASN1_COMPILE@ ASN1_COMPILE_DEP = @ASN1_COMPILE_DEP@ AUTOCONF = @AUTOCONF@ AUTOHEADER = @AUTOHEADER@ AUTOMAKE = @AUTOMAKE@ AWK = @AWK@ CANONICAL_HOST = @CANONICAL_HOST@ CAPNG_CFLAGS = @CAPNG_CFLAGS@ CAPNG_LIBS = @CAPNG_LIBS@ CATMAN = @CATMAN@ CATMANEXT = @CATMANEXT@ CC = @CC@ CCDEPMODE = @CCDEPMODE@ CFLAGS = @CFLAGS@ COMPILE_ET = @COMPILE_ET@ CPP = @CPP@ CPPFLAGS = @CPPFLAGS@ CYGPATH_W = @CYGPATH_W@ DB1LIB = @DB1LIB@ DB3LIB = @DB3LIB@ DBHEADER = @DBHEADER@ DEFS = @DEFS@ DEPDIR = @DEPDIR@ DIR_com_err = @DIR_com_err@ DIR_hdbdir = @DIR_hdbdir@ DIR_roken = @DIR_roken@ DLLTOOL = @DLLTOOL@ DSYMUTIL = @DSYMUTIL@ DUMPBIN = @DUMPBIN@ ECHO_C = @ECHO_C@ ECHO_N = @ECHO_N@ ECHO_T = @ECHO_T@ EGREP = @EGREP@ ENABLE_AFS_STRING_TO_KEY = @ENABLE_AFS_STRING_TO_KEY@ EXEEXT = @EXEEXT@ FGREP = @FGREP@ GCD_MIG = @GCD_MIG@ GREP = @GREP@ GROFF = @GROFF@ INCLUDES_roken = @INCLUDES_roken@ INCLUDE_libedit = @INCLUDE_libedit@ INCLUDE_libintl = @INCLUDE_libintl@ INCLUDE_openldap = @INCLUDE_openldap@ INCLUDE_openssl_crypto = @INCLUDE_openssl_crypto@ INCLUDE_readline = @INCLUDE_readline@ INCLUDE_sqlite3 = @INCLUDE_sqlite3@ INSTALL = @INSTALL@ INSTALL_DATA = @INSTALL_DATA@ INSTALL_PROGRAM = @INSTALL_PROGRAM@ INSTALL_SCRIPT = @INSTALL_SCRIPT@ INSTALL_STRIP_PROGRAM = @INSTALL_STRIP_PROGRAM@ LD = @LD@ LDFLAGS = @LDFLAGS@ LDFLAGS_VERSION_SCRIPT = @LDFLAGS_VERSION_SCRIPT@ LEX = @LEX@ LEXLIB = @LEXLIB@ LEX_OUTPUT_ROOT = @LEX_OUTPUT_ROOT@ LIBADD_roken = @LIBADD_roken@ LIBOBJS = @LIBOBJS@ LIBS = @LIBS@ LIBTOOL = @LIBTOOL@ LIB_AUTH_SUBDIRS = @LIB_AUTH_SUBDIRS@ LIB_bswap16 = @LIB_bswap16@ LIB_bswap32 = @LIB_bswap32@ LIB_bswap64 = @LIB_bswap64@ LIB_com_err = @LIB_com_err@ LIB_com_err_a = @LIB_com_err_a@ LIB_com_err_so = @LIB_com_err_so@ LIB_crypt = @LIB_crypt@ LIB_db_create = @LIB_db_create@ LIB_dbm_firstkey = @LIB_dbm_firstkey@ LIB_dbopen = @LIB_dbopen@ LIB_dispatch_async_f = @LIB_dispatch_async_f@ LIB_dladdr = @LIB_dladdr@ LIB_dlopen = @LIB_dlopen@ LIB_dn_expand = @LIB_dn_expand@ LIB_dns_search = @LIB_dns_search@ LIB_door_create = @LIB_door_create@ LIB_freeaddrinfo = @LIB_freeaddrinfo@ LIB_gai_strerror = @LIB_gai_strerror@ LIB_getaddrinfo = @LIB_getaddrinfo@ LIB_gethostbyname = @LIB_gethostbyname@ LIB_gethostbyname2 = @LIB_gethostbyname2@ LIB_getnameinfo = @LIB_getnameinfo@ LIB_getpwnam_r = @LIB_getpwnam_r@ LIB_getsockopt = @LIB_getsockopt@ LIB_hcrypto = @LIB_hcrypto@ LIB_hcrypto_a = @LIB_hcrypto_a@ LIB_hcrypto_appl = @LIB_hcrypto_appl@ LIB_hcrypto_so = @LIB_hcrypto_so@ LIB_hstrerror = @LIB_hstrerror@ LIB_kdb = @LIB_kdb@ LIB_libedit = @LIB_libedit@ LIB_libintl = @LIB_libintl@ LIB_loadquery = @LIB_loadquery@ LIB_logout = @LIB_logout@ LIB_logwtmp = @LIB_logwtmp@ LIB_openldap = @LIB_openldap@ LIB_openpty = @LIB_openpty@ LIB_openssl_crypto = @LIB_openssl_crypto@ LIB_otp = @LIB_otp@ LIB_pidfile = @LIB_pidfile@ LIB_readline = @LIB_readline@ LIB_res_ndestroy = @LIB_res_ndestroy@ LIB_res_nsearch = @LIB_res_nsearch@ LIB_res_search = @LIB_res_search@ LIB_roken = @LIB_roken@ LIB_security = @LIB_security@ LIB_setsockopt = @LIB_setsockopt@ LIB_socket = @LIB_socket@ LIB_sqlite3 = @LIB_sqlite3@ LIB_syslog = @LIB_syslog@ LIB_tgetent = @LIB_tgetent@ LIPO = @LIPO@ LMDBLIB = @LMDBLIB@ LN_S = @LN_S@ LTLIBOBJS = @LTLIBOBJS@ LT_SYS_LIBRARY_PATH = @LT_SYS_LIBRARY_PATH@ MAINT = @MAINT@ MAKEINFO = @MAKEINFO@ MANIFEST_TOOL = @MANIFEST_TOOL@ MKDIR_P = @MKDIR_P@ NDBMLIB = @NDBMLIB@ NM = @NM@ NMEDIT = @NMEDIT@ NO_AFS = @NO_AFS@ NROFF = @NROFF@ OBJDUMP = @OBJDUMP@ OBJEXT = @OBJEXT@ OTOOL = @OTOOL@ OTOOL64 = @OTOOL64@ PACKAGE = @PACKAGE@ PACKAGE_BUGREPORT = @PACKAGE_BUGREPORT@ PACKAGE_NAME = @PACKAGE_NAME@ PACKAGE_STRING = @PACKAGE_STRING@ PACKAGE_TARNAME = @PACKAGE_TARNAME@ PACKAGE_URL = @PACKAGE_URL@ PACKAGE_VERSION = @PACKAGE_VERSION@ PATH_SEPARATOR = @PATH_SEPARATOR@ PERL = @PERL@ PKG_CONFIG = @PKG_CONFIG@ PTHREAD_CFLAGS = @PTHREAD_CFLAGS@ PTHREAD_LDADD = @PTHREAD_LDADD@ PTHREAD_LIBADD = @PTHREAD_LIBADD@ RANLIB = @RANLIB@ SED = @SED@ SET_MAKE = @SET_MAKE@ SHELL = @SHELL@ SLC = @SLC@ SLC_DEP = @SLC_DEP@ STRIP = @STRIP@ VERSION = @VERSION@ VERSIONING = @VERSIONING@ WFLAGS = @WFLAGS@ WFLAGS_LITE = @WFLAGS_LITE@ YACC = @YACC@ YFLAGS = @YFLAGS@ abs_builddir = @abs_builddir@ abs_srcdir = @abs_srcdir@ abs_top_builddir = @abs_top_builddir@ abs_top_srcdir = @abs_top_srcdir@ ac_ct_AR = @ac_ct_AR@ ac_ct_CC = @ac_ct_CC@ ac_ct_DUMPBIN = @ac_ct_DUMPBIN@ am__include = @am__include@ am__leading_dot = @am__leading_dot@ am__quote = @am__quote@ am__tar = @am__tar@ am__untar = @am__untar@ bindir = @bindir@ build = @build@ build_alias = @build_alias@ build_cpu = @build_cpu@ build_os = @build_os@ build_vendor = @build_vendor@ builddir = @builddir@ datadir = @datadir@ datarootdir = @datarootdir@ db_type = @db_type@ db_type_preference = @db_type_preference@ docdir = @docdir@ dpagaix_cflags = @dpagaix_cflags@ dpagaix_ldadd = @dpagaix_ldadd@ dpagaix_ldflags = @dpagaix_ldflags@ dvidir = @dvidir@ exec_prefix = @exec_prefix@ host = @host@ host_alias = @host_alias@ host_cpu = @host_cpu@ host_os = @host_os@ host_vendor = @host_vendor@ htmldir = @htmldir@ includedir = @includedir@ infodir = @infodir@ install_sh = @install_sh@ libdir = @libdir@ libexecdir = @libexecdir@ localedir = @localedir@ localstatedir = @localstatedir@ mandir = @mandir@ mkdir_p = @mkdir_p@ oldincludedir = @oldincludedir@ pdfdir = @pdfdir@ prefix = @prefix@ program_transform_name = @program_transform_name@ psdir = @psdir@ sbindir = @sbindir@ sharedstatedir = @sharedstatedir@ srcdir = @srcdir@ subdirs = @subdirs@ sysconfdir = @sysconfdir@ target_alias = @target_alias@ top_build_prefix = @top_build_prefix@ top_builddir = @top_builddir@ top_srcdir = @top_srcdir@ SUFFIXES = .et .h .pc.in .pc .x .z .hx .1 .3 .5 .7 .8 .cat1 .cat3 \ .cat5 .cat7 .cat8 DEFAULT_INCLUDES = -I. -I$(srcdir) -I$(top_builddir)/include -I$(top_srcdir)/include AM_CPPFLAGS = $(INCLUDES_roken) $(INCLUDE_libintl) $(INCLUDE_readline) \ -I$(srcdir)/../lib/krb5 -I$(top_builddir)/include/gssapi @do_roken_rename_TRUE@ROKEN_RENAME = -DROKEN_RENAME AM_CFLAGS = $(WFLAGS) CP = cp buildinclude = $(top_builddir)/include LIB_XauReadAuth = @LIB_XauReadAuth@ LIB_el_init = @LIB_el_init@ LIB_getattr = @LIB_getattr@ LIB_getpwent_r = @LIB_getpwent_r@ LIB_odm_initialize = @LIB_odm_initialize@ LIB_setpcred = @LIB_setpcred@ INCLUDE_krb4 = @INCLUDE_krb4@ LIB_krb4 = @LIB_krb4@ libexec_heimdaldir = $(libexecdir)/heimdal NROFF_MAN = groff -mandoc -Tascii @NO_AFS_FALSE@LIB_kafs = $(top_builddir)/lib/kafs/libkafs.la $(AIX_EXTRA_KAFS) @NO_AFS_TRUE@LIB_kafs = @KRB5_TRUE@LIB_krb5 = $(top_builddir)/lib/krb5/libkrb5.la \ @KRB5_TRUE@ $(top_builddir)/lib/asn1/libasn1.la @KRB5_TRUE@LIB_gssapi = $(top_builddir)/lib/gssapi/libgssapi.la LIB_heimbase = $(top_builddir)/lib/base/libheimbase.la @DCE_TRUE@LIB_kdfs = $(top_builddir)/lib/kdfs/libkdfs.la #silent-rules heim_verbose = $(heim_verbose_$(V)) heim_verbose_ = $(heim_verbose_$(AM_DEFAULT_VERBOSITY)) heim_verbose_0 = @echo " GEN "$@; man_MANS = kadmin.1 kadmind.8 dist_kadmin_SOURCES = \ ank.c \ add_enctype.c \ check.c \ cpw.c \ del.c \ del_enctype.c \ dump.c \ ext.c \ get.c \ init.c \ kadmin.c \ load.c \ mod.c \ rename.c \ stash.c \ util.c \ pw_quality.c \ random_password.c \ kadmin_locl.h nodist_kadmin_SOURCES = \ kadmin-commands.c \ kadmin-commands.h CLEANFILES = kadmin-commands.h kadmin-commands.c kadmind_SOURCES = \ rpc.c \ server.c \ kadmind.c \ kadmin_locl.h \ kadm_conn.c add_random_users_SOURCES = add-random-users.c test_util_SOURCES = test_util.c util.c LDADD_common = \ $(top_builddir)/lib/hdb/libhdb.la \ $(top_builddir)/lib/krb5/libkrb5.la \ $(LIB_hcrypto) \ $(top_builddir)/lib/asn1/libasn1.la \ $(LIB_roken) \ $(DB3LIB) $(DB1LIB) $(LMDBLIB) $(NDBMLIB) kadmind_LDADD = $(top_builddir)/lib/kadm5/libkadm5srv.la \ ../lib/gssapi/libgssapi.la \ $(LDADD_common) \ $(LIB_pidfile) \ $(LIB_dlopen) kadmin_LDADD = \ $(top_builddir)/lib/kadm5/libkadm5clnt.la \ $(top_builddir)/lib/kadm5/libkadm5srv.la \ $(top_builddir)/lib/sl/libsl.la \ $(LIB_readline) \ $(LDADD_common) \ $(LIB_dlopen) add_random_users_LDADD = \ $(top_builddir)/lib/kadm5/libkadm5clnt.la \ $(top_builddir)/lib/kadm5/libkadm5srv.la \ $(LDADD_common) \ $(LIB_dlopen) test_util_LDADD = $(kadmin_LDADD) EXTRA_DIST = \ NTMakefile \ kadmin-version.rc \ kadmind-version.rc \ $(man_MANS) \ kadmin-commands.in all: all-am .SUFFIXES: .SUFFIXES: .et .h .pc.in .pc .x .z .hx .1 .3 .5 .7 .8 .cat1 .cat3 .cat5 .cat7 .cat8 .c .lo .log .o .obj .test .test$(EXEEXT) .trs $(srcdir)/Makefile.in: @MAINTAINER_MODE_TRUE@ $(srcdir)/Makefile.am $(top_srcdir)/Makefile.am.common $(top_srcdir)/cf/Makefile.am.common $(am__configure_deps) @for dep in $?; do \ case '$(am__configure_deps)' in \ *$$dep*) \ ( cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh ) \ && { if test -f $@; then exit 0; else break; fi; }; \ exit 1;; \ esac; \ done; \ echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign kadmin/Makefile'; \ $(am__cd) $(top_srcdir) && \ $(AUTOMAKE) --foreign kadmin/Makefile Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status @case '$?' in \ *config.status*) \ cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh;; \ *) \ echo ' cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe)'; \ cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe);; \ esac; $(top_srcdir)/Makefile.am.common $(top_srcdir)/cf/Makefile.am.common $(am__empty): $(top_builddir)/config.status: $(top_srcdir)/configure $(CONFIG_STATUS_DEPENDENCIES) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(top_srcdir)/configure: @MAINTAINER_MODE_TRUE@ $(am__configure_deps) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(ACLOCAL_M4): @MAINTAINER_MODE_TRUE@ $(am__aclocal_m4_deps) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(am__aclocal_m4_deps): install-binPROGRAMS: $(bin_PROGRAMS) @$(NORMAL_INSTALL) @list='$(bin_PROGRAMS)'; test -n "$(bindir)" || list=; \ if test -n "$$list"; then \ echo " $(MKDIR_P) '$(DESTDIR)$(bindir)'"; \ $(MKDIR_P) "$(DESTDIR)$(bindir)" || exit 1; \ fi; \ for p in $$list; do echo "$$p $$p"; done | \ sed 's/$(EXEEXT)$$//' | \ while read p p1; do if test -f $$p \ || test -f $$p1 \ ; then echo "$$p"; echo "$$p"; else :; fi; \ done | \ sed -e 'p;s,.*/,,;n;h' \ -e 's|.*|.|' \ -e 'p;x;s,.*/,,;s/$(EXEEXT)$$//;$(transform);s/$$/$(EXEEXT)/' | \ sed 'N;N;N;s,\n, ,g' | \ $(AWK) 'BEGIN { files["."] = ""; dirs["."] = 1 } \ { d=$$3; if (dirs[d] != 1) { print "d", d; dirs[d] = 1 } \ if ($$2 == $$4) files[d] = files[d] " " $$1; \ else { print "f", $$3 "/" $$4, $$1; } } \ END { for (d in files) print "f", d, files[d] }' | \ while read type dir files; do \ if test "$$dir" = .; then dir=; else dir=/$$dir; fi; \ test -z "$$files" || { \ echo " $(INSTALL_PROGRAM_ENV) $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=install $(INSTALL_PROGRAM) $$files '$(DESTDIR)$(bindir)$$dir'"; \ $(INSTALL_PROGRAM_ENV) $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=install $(INSTALL_PROGRAM) $$files "$(DESTDIR)$(bindir)$$dir" || exit $$?; \ } \ ; done uninstall-binPROGRAMS: @$(NORMAL_UNINSTALL) @list='$(bin_PROGRAMS)'; test -n "$(bindir)" || list=; \ files=`for p in $$list; do echo "$$p"; done | \ sed -e 'h;s,^.*/,,;s/$(EXEEXT)$$//;$(transform)' \ -e 's/$$/$(EXEEXT)/' \ `; \ test -n "$$list" || exit 0; \ echo " ( cd '$(DESTDIR)$(bindir)' && rm -f" $$files ")"; \ cd "$(DESTDIR)$(bindir)" && rm -f $$files clean-binPROGRAMS: @list='$(bin_PROGRAMS)'; test -n "$$list" || exit 0; \ echo " rm -f" $$list; \ rm -f $$list || exit $$?; \ test -n "$(EXEEXT)" || exit 0; \ list=`for p in $$list; do echo "$$p"; done | sed 's/$(EXEEXT)$$//'`; \ echo " rm -f" $$list; \ rm -f $$list clean-checkPROGRAMS: @list='$(check_PROGRAMS)'; test -n "$$list" || exit 0; \ echo " rm -f" $$list; \ rm -f $$list || exit $$?; \ test -n "$(EXEEXT)" || exit 0; \ list=`for p in $$list; do echo "$$p"; done | sed 's/$(EXEEXT)$$//'`; \ echo " rm -f" $$list; \ rm -f $$list install-libexecPROGRAMS: $(libexec_PROGRAMS) @$(NORMAL_INSTALL) @list='$(libexec_PROGRAMS)'; test -n "$(libexecdir)" || list=; \ if test -n "$$list"; then \ echo " $(MKDIR_P) '$(DESTDIR)$(libexecdir)'"; \ $(MKDIR_P) "$(DESTDIR)$(libexecdir)" || exit 1; \ fi; \ for p in $$list; do echo "$$p $$p"; done | \ sed 's/$(EXEEXT)$$//' | \ while read p p1; do if test -f $$p \ || test -f $$p1 \ ; then echo "$$p"; echo "$$p"; else :; fi; \ done | \ sed -e 'p;s,.*/,,;n;h' \ -e 's|.*|.|' \ -e 'p;x;s,.*/,,;s/$(EXEEXT)$$//;$(transform);s/$$/$(EXEEXT)/' | \ sed 'N;N;N;s,\n, ,g' | \ $(AWK) 'BEGIN { files["."] = ""; dirs["."] = 1 } \ { d=$$3; if (dirs[d] != 1) { print "d", d; dirs[d] = 1 } \ if ($$2 == $$4) files[d] = files[d] " " $$1; \ else { print "f", $$3 "/" $$4, $$1; } } \ END { for (d in files) print "f", d, files[d] }' | \ while read type dir files; do \ if test "$$dir" = .; then dir=; else dir=/$$dir; fi; \ test -z "$$files" || { \ echo " $(INSTALL_PROGRAM_ENV) $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=install $(INSTALL_PROGRAM) $$files '$(DESTDIR)$(libexecdir)$$dir'"; \ $(INSTALL_PROGRAM_ENV) $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=install $(INSTALL_PROGRAM) $$files "$(DESTDIR)$(libexecdir)$$dir" || exit $$?; \ } \ ; done uninstall-libexecPROGRAMS: @$(NORMAL_UNINSTALL) @list='$(libexec_PROGRAMS)'; test -n "$(libexecdir)" || list=; \ files=`for p in $$list; do echo "$$p"; done | \ sed -e 'h;s,^.*/,,;s/$(EXEEXT)$$//;$(transform)' \ -e 's/$$/$(EXEEXT)/' \ `; \ test -n "$$list" || exit 0; \ echo " ( cd '$(DESTDIR)$(libexecdir)' && rm -f" $$files ")"; \ cd "$(DESTDIR)$(libexecdir)" && rm -f $$files clean-libexecPROGRAMS: @list='$(libexec_PROGRAMS)'; test -n "$$list" || exit 0; \ echo " rm -f" $$list; \ rm -f $$list || exit $$?; \ test -n "$(EXEEXT)" || exit 0; \ list=`for p in $$list; do echo "$$p"; done | sed 's/$(EXEEXT)$$//'`; \ echo " rm -f" $$list; \ rm -f $$list clean-noinstPROGRAMS: @list='$(noinst_PROGRAMS)'; test -n "$$list" || exit 0; \ echo " rm -f" $$list; \ rm -f $$list || exit $$?; \ test -n "$(EXEEXT)" || exit 0; \ list=`for p in $$list; do echo "$$p"; done | sed 's/$(EXEEXT)$$//'`; \ echo " rm -f" $$list; \ rm -f $$list add_random_users$(EXEEXT): $(add_random_users_OBJECTS) $(add_random_users_DEPENDENCIES) $(EXTRA_add_random_users_DEPENDENCIES) @rm -f add_random_users$(EXEEXT) $(AM_V_CCLD)$(LINK) $(add_random_users_OBJECTS) $(add_random_users_LDADD) $(LIBS) kadmin$(EXEEXT): $(kadmin_OBJECTS) $(kadmin_DEPENDENCIES) $(EXTRA_kadmin_DEPENDENCIES) @rm -f kadmin$(EXEEXT) $(AM_V_CCLD)$(LINK) $(kadmin_OBJECTS) $(kadmin_LDADD) $(LIBS) kadmind$(EXEEXT): $(kadmind_OBJECTS) $(kadmind_DEPENDENCIES) $(EXTRA_kadmind_DEPENDENCIES) @rm -f kadmind$(EXEEXT) $(AM_V_CCLD)$(LINK) $(kadmind_OBJECTS) $(kadmind_LDADD) $(LIBS) test_util$(EXEEXT): $(test_util_OBJECTS) $(test_util_DEPENDENCIES) $(EXTRA_test_util_DEPENDENCIES) @rm -f test_util$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_util_OBJECTS) $(test_util_LDADD) $(LIBS) mostlyclean-compile: -rm -f *.$(OBJEXT) distclean-compile: -rm -f *.tab.c @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/add-random-users.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/add_enctype.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/ank.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/check.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/cpw.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/del.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/del_enctype.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/dump.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/ext.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/get.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/init.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/kadm_conn.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/kadmin-commands.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/kadmin.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/kadmind.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/load.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/mod.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/pw_quality.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/random_password.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/rename.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/rpc.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/server.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/stash.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_util.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/util.Po@am__quote@ .c.o: @am__fastdepCC_TRUE@ $(AM_V_CC)$(COMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o $@ $< @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='$<' object='$@' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(COMPILE) -c -o $@ $< .c.obj: @am__fastdepCC_TRUE@ $(AM_V_CC)$(COMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o $@ `$(CYGPATH_W) '$<'` @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='$<' object='$@' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(COMPILE) -c -o $@ `$(CYGPATH_W) '$<'` .c.lo: @am__fastdepCC_TRUE@ $(AM_V_CC)$(LTCOMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o $@ $< @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='$<' object='$@' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LTCOMPILE) -c -o $@ $< mostlyclean-libtool: -rm -f *.lo clean-libtool: -rm -rf .libs _libs install-man1: $(man_MANS) @$(NORMAL_INSTALL) @list1=''; \ list2='$(man_MANS)'; \ test -n "$(man1dir)" \ && test -n "`echo $$list1$$list2`" \ || exit 0; \ echo " $(MKDIR_P) '$(DESTDIR)$(man1dir)'"; \ $(MKDIR_P) "$(DESTDIR)$(man1dir)" || exit 1; \ { for i in $$list1; do echo "$$i"; done; \ if test -n "$$list2"; then \ for i in $$list2; do echo "$$i"; done \ | sed -n '/\.1[a-z]*$$/p'; \ fi; \ } | while read p; do \ if test -f $$p; then d=; else d="$(srcdir)/"; fi; \ echo "$$d$$p"; echo "$$p"; \ done | \ sed -e 'n;s,.*/,,;p;h;s,.*\.,,;s,^[^1][0-9a-z]*$$,1,;x' \ -e 's,\.[0-9a-z]*$$,,;$(transform);G;s,\n,.,' | \ sed 'N;N;s,\n, ,g' | { \ list=; while read file base inst; do \ if test "$$base" = "$$inst"; then list="$$list $$file"; else \ echo " $(INSTALL_DATA) '$$file' '$(DESTDIR)$(man1dir)/$$inst'"; \ $(INSTALL_DATA) "$$file" "$(DESTDIR)$(man1dir)/$$inst" || exit $$?; \ fi; \ done; \ for i in $$list; do echo "$$i"; done | $(am__base_list) | \ while read files; do \ test -z "$$files" || { \ echo " $(INSTALL_DATA) $$files '$(DESTDIR)$(man1dir)'"; \ $(INSTALL_DATA) $$files "$(DESTDIR)$(man1dir)" || exit $$?; }; \ done; } uninstall-man1: @$(NORMAL_UNINSTALL) @list=''; test -n "$(man1dir)" || exit 0; \ files=`{ for i in $$list; do echo "$$i"; done; \ l2='$(man_MANS)'; for i in $$l2; do echo "$$i"; done | \ sed -n '/\.1[a-z]*$$/p'; \ } | sed -e 's,.*/,,;h;s,.*\.,,;s,^[^1][0-9a-z]*$$,1,;x' \ -e 's,\.[0-9a-z]*$$,,;$(transform);G;s,\n,.,'`; \ dir='$(DESTDIR)$(man1dir)'; $(am__uninstall_files_from_dir) install-man8: $(man_MANS) @$(NORMAL_INSTALL) @list1=''; \ list2='$(man_MANS)'; \ test -n "$(man8dir)" \ && test -n "`echo $$list1$$list2`" \ || exit 0; \ echo " $(MKDIR_P) '$(DESTDIR)$(man8dir)'"; \ $(MKDIR_P) "$(DESTDIR)$(man8dir)" || exit 1; \ { for i in $$list1; do echo "$$i"; done; \ if test -n "$$list2"; then \ for i in $$list2; do echo "$$i"; done \ | sed -n '/\.8[a-z]*$$/p'; \ fi; \ } | while read p; do \ if test -f $$p; then d=; else d="$(srcdir)/"; fi; \ echo "$$d$$p"; echo "$$p"; \ done | \ sed -e 'n;s,.*/,,;p;h;s,.*\.,,;s,^[^8][0-9a-z]*$$,8,;x' \ -e 's,\.[0-9a-z]*$$,,;$(transform);G;s,\n,.,' | \ sed 'N;N;s,\n, ,g' | { \ list=; while read file base inst; do \ if test "$$base" = "$$inst"; then list="$$list $$file"; else \ echo " $(INSTALL_DATA) '$$file' '$(DESTDIR)$(man8dir)/$$inst'"; \ $(INSTALL_DATA) "$$file" "$(DESTDIR)$(man8dir)/$$inst" || exit $$?; \ fi; \ done; \ for i in $$list; do echo "$$i"; done | $(am__base_list) | \ while read files; do \ test -z "$$files" || { \ echo " $(INSTALL_DATA) $$files '$(DESTDIR)$(man8dir)'"; \ $(INSTALL_DATA) $$files "$(DESTDIR)$(man8dir)" || exit $$?; }; \ done; } uninstall-man8: @$(NORMAL_UNINSTALL) @list=''; test -n "$(man8dir)" || exit 0; \ files=`{ for i in $$list; do echo "$$i"; done; \ l2='$(man_MANS)'; for i in $$l2; do echo "$$i"; done | \ sed -n '/\.8[a-z]*$$/p'; \ } | sed -e 's,.*/,,;h;s,.*\.,,;s,^[^8][0-9a-z]*$$,8,;x' \ -e 's,\.[0-9a-z]*$$,,;$(transform);G;s,\n,.,'`; \ dir='$(DESTDIR)$(man8dir)'; $(am__uninstall_files_from_dir) ID: $(am__tagged_files) $(am__define_uniq_tagged_files); mkid -fID $$unique tags: tags-am TAGS: tags tags-am: $(TAGS_DEPENDENCIES) $(am__tagged_files) set x; \ here=`pwd`; \ $(am__define_uniq_tagged_files); \ shift; \ if test -z "$(ETAGS_ARGS)$$*$$unique"; then :; else \ test -n "$$unique" || unique=$$empty_fix; \ if test $$# -gt 0; then \ $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ "$$@" $$unique; \ else \ $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ $$unique; \ fi; \ fi ctags: ctags-am CTAGS: ctags ctags-am: $(TAGS_DEPENDENCIES) $(am__tagged_files) $(am__define_uniq_tagged_files); \ test -z "$(CTAGS_ARGS)$$unique" \ || $(CTAGS) $(CTAGSFLAGS) $(AM_CTAGSFLAGS) $(CTAGS_ARGS) \ $$unique GTAGS: here=`$(am__cd) $(top_builddir) && pwd` \ && $(am__cd) $(top_srcdir) \ && gtags -i $(GTAGS_ARGS) "$$here" cscopelist: cscopelist-am cscopelist-am: $(am__tagged_files) list='$(am__tagged_files)'; \ case "$(srcdir)" in \ [\\/]* | ?:[\\/]*) sdir="$(srcdir)" ;; \ *) sdir=$(subdir)/$(srcdir) ;; \ esac; \ for i in $$list; do \ if test -f "$$i"; then \ echo "$(subdir)/$$i"; \ else \ echo "$$sdir/$$i"; \ fi; \ done >> $(top_builddir)/cscope.files distclean-tags: -rm -f TAGS ID GTAGS GRTAGS GSYMS GPATH tags # Recover from deleted '.trs' file; this should ensure that # "rm -f foo.log; make foo.trs" re-run 'foo.test', and re-create # both 'foo.log' and 'foo.trs'. Break the recipe in two subshells # to avoid problems with "make -n". .log.trs: rm -f $< $@ $(MAKE) $(AM_MAKEFLAGS) $< # Leading 'am--fnord' is there to ensure the list of targets does not # expand to empty, as could happen e.g. with make check TESTS=''. am--fnord $(TEST_LOGS) $(TEST_LOGS:.log=.trs): $(am__force_recheck) am--force-recheck: @: $(TEST_SUITE_LOG): $(TEST_LOGS) @$(am__set_TESTS_bases); \ am__f_ok () { test -f "$$1" && test -r "$$1"; }; \ redo_bases=`for i in $$bases; do \ am__f_ok $$i.trs && am__f_ok $$i.log || echo $$i; \ done`; \ if test -n "$$redo_bases"; then \ redo_logs=`for i in $$redo_bases; do echo $$i.log; done`; \ redo_results=`for i in $$redo_bases; do echo $$i.trs; done`; \ if $(am__make_dryrun); then :; else \ rm -f $$redo_logs && rm -f $$redo_results || exit 1; \ fi; \ fi; \ if test -n "$$am__remaking_logs"; then \ echo "fatal: making $(TEST_SUITE_LOG): possible infinite" \ "recursion detected" >&2; \ elif test -n "$$redo_logs"; then \ am__remaking_logs=yes $(MAKE) $(AM_MAKEFLAGS) $$redo_logs; \ fi; \ if $(am__make_dryrun); then :; else \ st=0; \ errmsg="fatal: making $(TEST_SUITE_LOG): failed to create"; \ for i in $$redo_bases; do \ test -f $$i.trs && test -r $$i.trs \ || { echo "$$errmsg $$i.trs" >&2; st=1; }; \ test -f $$i.log && test -r $$i.log \ || { echo "$$errmsg $$i.log" >&2; st=1; }; \ done; \ test $$st -eq 0 || exit 1; \ fi @$(am__sh_e_setup); $(am__tty_colors); $(am__set_TESTS_bases); \ ws='[ ]'; \ results=`for b in $$bases; do echo $$b.trs; done`; \ test -n "$$results" || results=/dev/null; \ all=` grep "^$$ws*:test-result:" $$results | wc -l`; \ pass=` grep "^$$ws*:test-result:$$ws*PASS" $$results | wc -l`; \ fail=` grep "^$$ws*:test-result:$$ws*FAIL" $$results | wc -l`; \ skip=` grep "^$$ws*:test-result:$$ws*SKIP" $$results | wc -l`; \ xfail=`grep "^$$ws*:test-result:$$ws*XFAIL" $$results | wc -l`; \ xpass=`grep "^$$ws*:test-result:$$ws*XPASS" $$results | wc -l`; \ error=`grep "^$$ws*:test-result:$$ws*ERROR" $$results | wc -l`; \ if test `expr $$fail + $$xpass + $$error` -eq 0; then \ success=true; \ else \ success=false; \ fi; \ br='==================='; br=$$br$$br$$br$$br; \ result_count () \ { \ if test x"$$1" = x"--maybe-color"; then \ maybe_colorize=yes; \ elif test x"$$1" = x"--no-color"; then \ maybe_colorize=no; \ else \ echo "$@: invalid 'result_count' usage" >&2; exit 4; \ fi; \ shift; \ desc=$$1 count=$$2; \ if test $$maybe_colorize = yes && test $$count -gt 0; then \ color_start=$$3 color_end=$$std; \ else \ color_start= color_end=; \ fi; \ echo "$${color_start}# $$desc $$count$${color_end}"; \ }; \ create_testsuite_report () \ { \ result_count $$1 "TOTAL:" $$all "$$brg"; \ result_count $$1 "PASS: " $$pass "$$grn"; \ result_count $$1 "SKIP: " $$skip "$$blu"; \ result_count $$1 "XFAIL:" $$xfail "$$lgn"; \ result_count $$1 "FAIL: " $$fail "$$red"; \ result_count $$1 "XPASS:" $$xpass "$$red"; \ result_count $$1 "ERROR:" $$error "$$mgn"; \ }; \ { \ echo "$(PACKAGE_STRING): $(subdir)/$(TEST_SUITE_LOG)" | \ $(am__rst_title); \ create_testsuite_report --no-color; \ echo; \ echo ".. contents:: :depth: 2"; \ echo; \ for b in $$bases; do echo $$b; done \ | $(am__create_global_log); \ } >$(TEST_SUITE_LOG).tmp || exit 1; \ mv $(TEST_SUITE_LOG).tmp $(TEST_SUITE_LOG); \ if $$success; then \ col="$$grn"; \ else \ col="$$red"; \ test x"$$VERBOSE" = x || cat $(TEST_SUITE_LOG); \ fi; \ echo "$${col}$$br$${std}"; \ echo "$${col}Testsuite summary for $(PACKAGE_STRING)$${std}"; \ echo "$${col}$$br$${std}"; \ create_testsuite_report --maybe-color; \ echo "$$col$$br$$std"; \ if $$success; then :; else \ echo "$${col}See $(subdir)/$(TEST_SUITE_LOG)$${std}"; \ if test -n "$(PACKAGE_BUGREPORT)"; then \ echo "$${col}Please report to $(PACKAGE_BUGREPORT)$${std}"; \ fi; \ echo "$$col$$br$$std"; \ fi; \ $$success || exit 1 check-TESTS: @list='$(RECHECK_LOGS)'; test -z "$$list" || rm -f $$list @list='$(RECHECK_LOGS:.log=.trs)'; test -z "$$list" || rm -f $$list @test -z "$(TEST_SUITE_LOG)" || rm -f $(TEST_SUITE_LOG) @set +e; $(am__set_TESTS_bases); \ log_list=`for i in $$bases; do echo $$i.log; done`; \ trs_list=`for i in $$bases; do echo $$i.trs; done`; \ log_list=`echo $$log_list`; trs_list=`echo $$trs_list`; \ $(MAKE) $(AM_MAKEFLAGS) $(TEST_SUITE_LOG) TEST_LOGS="$$log_list"; \ exit $$?; recheck: all $(check_PROGRAMS) @test -z "$(TEST_SUITE_LOG)" || rm -f $(TEST_SUITE_LOG) @set +e; $(am__set_TESTS_bases); \ bases=`for i in $$bases; do echo $$i; done \ | $(am__list_recheck_tests)` || exit 1; \ log_list=`for i in $$bases; do echo $$i.log; done`; \ log_list=`echo $$log_list`; \ $(MAKE) $(AM_MAKEFLAGS) $(TEST_SUITE_LOG) \ am__force_recheck=am--force-recheck \ TEST_LOGS="$$log_list"; \ exit $$? test_util.log: test_util$(EXEEXT) @p='test_util$(EXEEXT)'; \ b='test_util'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) .test.log: @p='$<'; \ $(am__set_b); \ $(am__check_pre) $(TEST_LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_TEST_LOG_DRIVER_FLAGS) $(TEST_LOG_DRIVER_FLAGS) -- $(TEST_LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) @am__EXEEXT_TRUE@.test$(EXEEXT).log: @am__EXEEXT_TRUE@ @p='$<'; \ @am__EXEEXT_TRUE@ $(am__set_b); \ @am__EXEEXT_TRUE@ $(am__check_pre) $(TEST_LOG_DRIVER) --test-name "$$f" \ @am__EXEEXT_TRUE@ --log-file $$b.log --trs-file $$b.trs \ @am__EXEEXT_TRUE@ $(am__common_driver_flags) $(AM_TEST_LOG_DRIVER_FLAGS) $(TEST_LOG_DRIVER_FLAGS) -- $(TEST_LOG_COMPILE) \ @am__EXEEXT_TRUE@ "$$tst" $(AM_TESTS_FD_REDIRECT) distdir: $(DISTFILES) @srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ topsrcdirstrip=`echo "$(top_srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ list='$(DISTFILES)'; \ dist_files=`for file in $$list; do echo $$file; done | \ sed -e "s|^$$srcdirstrip/||;t" \ -e "s|^$$topsrcdirstrip/|$(top_builddir)/|;t"`; \ case $$dist_files in \ */*) $(MKDIR_P) `echo "$$dist_files" | \ sed '/\//!d;s|^|$(distdir)/|;s,/[^/]*$$,,' | \ sort -u` ;; \ esac; \ for file in $$dist_files; do \ if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \ if test -d $$d/$$file; then \ dir=`echo "/$$file" | sed -e 's,/[^/]*$$,,'`; \ if test -d "$(distdir)/$$file"; then \ find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ fi; \ if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \ cp -fpR $(srcdir)/$$file "$(distdir)$$dir" || exit 1; \ find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ fi; \ cp -fpR $$d/$$file "$(distdir)$$dir" || exit 1; \ else \ test -f "$(distdir)/$$file" \ || cp -p $$d/$$file "$(distdir)/$$file" \ || exit 1; \ fi; \ done $(MAKE) $(AM_MAKEFLAGS) \ top_distdir="$(top_distdir)" distdir="$(distdir)" \ dist-hook check-am: all-am $(MAKE) $(AM_MAKEFLAGS) $(check_PROGRAMS) $(MAKE) $(AM_MAKEFLAGS) check-TESTS check-local check: check-am all-am: Makefile $(PROGRAMS) $(MANS) all-local installdirs: for dir in "$(DESTDIR)$(bindir)" "$(DESTDIR)$(libexecdir)" "$(DESTDIR)$(man1dir)" "$(DESTDIR)$(man8dir)"; do \ test -z "$$dir" || $(MKDIR_P) "$$dir"; \ done install: install-am install-exec: install-exec-am install-data: install-data-am uninstall: uninstall-am install-am: all-am @$(MAKE) $(AM_MAKEFLAGS) install-exec-am install-data-am installcheck: installcheck-am install-strip: if test -z '$(STRIP)'; then \ $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ install; \ else \ $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'" install; \ fi mostlyclean-generic: -test -z "$(TEST_LOGS)" || rm -f $(TEST_LOGS) -test -z "$(TEST_LOGS:.log=.trs)" || rm -f $(TEST_LOGS:.log=.trs) -test -z "$(TEST_SUITE_LOG)" || rm -f $(TEST_SUITE_LOG) clean-generic: -test -z "$(CLEANFILES)" || rm -f $(CLEANFILES) distclean-generic: -test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES) -test . = "$(srcdir)" || test -z "$(CONFIG_CLEAN_VPATH_FILES)" || rm -f $(CONFIG_CLEAN_VPATH_FILES) maintainer-clean-generic: @echo "This command is intended for maintainers to use" @echo "it deletes files that may require special tools to rebuild." clean: clean-am clean-am: clean-binPROGRAMS clean-checkPROGRAMS clean-generic \ clean-libexecPROGRAMS clean-libtool clean-noinstPROGRAMS \ mostlyclean-am distclean: distclean-am -rm -rf ./$(DEPDIR) -rm -f Makefile distclean-am: clean-am distclean-compile distclean-generic \ distclean-tags dvi: dvi-am dvi-am: html: html-am html-am: info: info-am info-am: install-data-am: install-man @$(NORMAL_INSTALL) $(MAKE) $(AM_MAKEFLAGS) install-data-hook install-dvi: install-dvi-am install-dvi-am: install-exec-am: install-binPROGRAMS install-exec-local \ install-libexecPROGRAMS install-html: install-html-am install-html-am: install-info: install-info-am install-info-am: install-man: install-man1 install-man8 install-pdf: install-pdf-am install-pdf-am: install-ps: install-ps-am install-ps-am: installcheck-am: maintainer-clean: maintainer-clean-am -rm -rf ./$(DEPDIR) -rm -f Makefile maintainer-clean-am: distclean-am maintainer-clean-generic mostlyclean: mostlyclean-am mostlyclean-am: mostlyclean-compile mostlyclean-generic \ mostlyclean-libtool pdf: pdf-am pdf-am: ps: ps-am ps-am: uninstall-am: uninstall-binPROGRAMS uninstall-libexecPROGRAMS \ uninstall-man @$(NORMAL_INSTALL) $(MAKE) $(AM_MAKEFLAGS) uninstall-hook uninstall-man: uninstall-man1 uninstall-man8 .MAKE: check-am install-am install-data-am install-strip uninstall-am .PHONY: CTAGS GTAGS TAGS all all-am all-local check check-TESTS \ check-am check-local clean clean-binPROGRAMS \ clean-checkPROGRAMS clean-generic clean-libexecPROGRAMS \ clean-libtool clean-noinstPROGRAMS cscopelist-am ctags \ ctags-am dist-hook distclean distclean-compile \ distclean-generic distclean-libtool distclean-tags distdir dvi \ dvi-am html html-am info info-am install install-am \ install-binPROGRAMS install-data install-data-am \ install-data-hook install-dvi install-dvi-am install-exec \ install-exec-am install-exec-local install-html \ install-html-am install-info install-info-am \ install-libexecPROGRAMS install-man install-man1 install-man8 \ install-pdf install-pdf-am install-ps install-ps-am \ install-strip installcheck installcheck-am installdirs \ maintainer-clean maintainer-clean-generic mostlyclean \ mostlyclean-compile mostlyclean-generic mostlyclean-libtool \ pdf pdf-am ps ps-am recheck tags tags-am uninstall \ uninstall-am uninstall-binPROGRAMS uninstall-hook \ uninstall-libexecPROGRAMS uninstall-man uninstall-man1 \ uninstall-man8 .PRECIOUS: Makefile install-suid-programs: @foo='$(bin_SUIDS)'; \ for file in $$foo; do \ x=$(DESTDIR)$(bindir)/$$file; \ if chown 0:0 $$x && chmod u+s $$x; then :; else \ echo "*"; \ echo "* Failed to install $$x setuid root"; \ echo "*"; \ fi; \ done install-exec-local: install-suid-programs codesign-all: @if [ X"$$CODE_SIGN_IDENTITY" != X ] ; then \ foo='$(bin_PROGRAMS) $(sbin_PROGRAMS) $(libexec_PROGRAMS)' ; \ for file in $$foo ; do \ echo "CODESIGN $$file" ; \ codesign -f -s "$$CODE_SIGN_IDENTITY" $$file || exit 1 ; \ done ; \ fi all-local: codesign-all install-build-headers:: $(include_HEADERS) $(dist_include_HEADERS) $(nodist_include_HEADERS) $(build_HEADERZ) $(nobase_include_HEADERS) $(noinst_HEADERS) @foo='$(include_HEADERS) $(dist_include_HEADERS) $(nodist_include_HEADERS) $(build_HEADERZ) $(noinst_HEADERS)'; \ for f in $$foo; do \ f=`basename $$f`; \ if test -f "$(srcdir)/$$f"; then file="$(srcdir)/$$f"; \ else file="$$f"; fi; \ if cmp -s $$file $(buildinclude)/$$f 2> /dev/null ; then \ : ; else \ echo " $(CP) $$file $(buildinclude)/$$f"; \ $(CP) $$file $(buildinclude)/$$f || true; \ fi ; \ done ; \ foo='$(nobase_include_HEADERS)'; \ for f in $$foo; do \ if test -f "$(srcdir)/$$f"; then file="$(srcdir)/$$f"; \ else file="$$f"; fi; \ $(mkdir_p) $(buildinclude)/`dirname $$f` ; \ if cmp -s $$file $(buildinclude)/$$f 2> /dev/null ; then \ : ; else \ echo " $(CP) $$file $(buildinclude)/$$f"; \ $(CP) $$file $(buildinclude)/$$f; \ fi ; \ done all-local: install-build-headers check-local:: @if test '$(CHECK_LOCAL)' = "no-check-local"; then \ foo=''; elif test '$(CHECK_LOCAL)'; then \ foo='$(CHECK_LOCAL)'; else \ foo='$(PROGRAMS)'; fi; \ if test "$$foo"; then \ failed=0; all=0; \ for i in $$foo; do \ all=`expr $$all + 1`; \ if (./$$i --version && ./$$i --help) > /dev/null 2>&1; then \ echo "PASS: $$i"; \ else \ echo "FAIL: $$i"; \ failed=`expr $$failed + 1`; \ fi; \ done; \ if test "$$failed" -eq 0; then \ banner="All $$all tests passed"; \ else \ banner="$$failed of $$all tests failed"; \ fi; \ dashes=`echo "$$banner" | sed s/./=/g`; \ echo "$$dashes"; \ echo "$$banner"; \ echo "$$dashes"; \ test "$$failed" -eq 0 || exit 1; \ fi .x.c: @cmp -s $< $@ 2> /dev/null || cp $< $@ .hx.h: @cmp -s $< $@ 2> /dev/null || cp $< $@ #NROFF_MAN = nroff -man .1.cat1: $(NROFF_MAN) $< > $@ .3.cat3: $(NROFF_MAN) $< > $@ .5.cat5: $(NROFF_MAN) $< > $@ .7.cat7: $(NROFF_MAN) $< > $@ .8.cat8: $(NROFF_MAN) $< > $@ dist-cat1-mans: @foo='$(man1_MANS)'; \ bar='$(man_MANS)'; \ for i in $$bar; do \ case $$i in \ *.1) foo="$$foo $$i";; \ esac; done ;\ for i in $$foo; do \ x=`echo $$i | sed 's/\.[^.]*$$/.cat1/'`; \ echo "$(NROFF_MAN) $(srcdir)/$$i > $(distdir)/$$x"; \ $(NROFF_MAN) $(srcdir)/$$i > $(distdir)/$$x; \ done dist-cat3-mans: @foo='$(man3_MANS)'; \ bar='$(man_MANS)'; \ for i in $$bar; do \ case $$i in \ *.3) foo="$$foo $$i";; \ esac; done ;\ for i in $$foo; do \ x=`echo $$i | sed 's/\.[^.]*$$/.cat3/'`; \ echo "$(NROFF_MAN) $(srcdir)/$$i > $(distdir)/$$x"; \ $(NROFF_MAN) $(srcdir)/$$i > $(distdir)/$$x; \ done dist-cat5-mans: @foo='$(man5_MANS)'; \ bar='$(man_MANS)'; \ for i in $$bar; do \ case $$i in \ *.5) foo="$$foo $$i";; \ esac; done ;\ for i in $$foo; do \ x=`echo $$i | sed 's/\.[^.]*$$/.cat5/'`; \ echo "$(NROFF_MAN) $(srcdir)/$$i > $(distdir)/$$x"; \ $(NROFF_MAN) $(srcdir)/$$i > $(distdir)/$$x; \ done dist-cat7-mans: @foo='$(man7_MANS)'; \ bar='$(man_MANS)'; \ for i in $$bar; do \ case $$i in \ *.7) foo="$$foo $$i";; \ esac; done ;\ for i in $$foo; do \ x=`echo $$i | sed 's/\.[^.]*$$/.cat7/'`; \ echo "$(NROFF_MAN) $(srcdir)/$$i > $(distdir)/$$x"; \ $(NROFF_MAN) $(srcdir)/$$i > $(distdir)/$$x; \ done dist-cat8-mans: @foo='$(man8_MANS)'; \ bar='$(man_MANS)'; \ for i in $$bar; do \ case $$i in \ *.8) foo="$$foo $$i";; \ esac; done ;\ for i in $$foo; do \ x=`echo $$i | sed 's/\.[^.]*$$/.cat8/'`; \ echo "$(NROFF_MAN) $(srcdir)/$$i > $(distdir)/$$x"; \ $(NROFF_MAN) $(srcdir)/$$i > $(distdir)/$$x; \ done dist-hook: dist-cat1-mans dist-cat3-mans dist-cat5-mans dist-cat7-mans dist-cat8-mans install-cat-mans: $(SHELL) $(top_srcdir)/cf/install-catman.sh install "$(INSTALL_DATA)" "$(mkinstalldirs)" "$(srcdir)" "$(DESTDIR)$(mandir)" '$(CATMANEXT)' $(man_MANS) $(man1_MANS) $(man3_MANS) $(man5_MANS) $(man7_MANS) $(man8_MANS) uninstall-cat-mans: $(SHELL) $(top_srcdir)/cf/install-catman.sh uninstall "$(INSTALL_DATA)" "$(mkinstalldirs)" "$(srcdir)" "$(DESTDIR)$(mandir)" '$(CATMANEXT)' $(man_MANS) $(man1_MANS) $(man3_MANS) $(man5_MANS) $(man7_MANS) $(man8_MANS) install-data-hook: install-cat-mans uninstall-hook: uninstall-cat-mans .et.h: $(COMPILE_ET) $< .et.c: $(COMPILE_ET) $< # # Useful target for debugging # check-valgrind: tobjdir=`cd $(top_builddir) && pwd` ; \ tsrcdir=`cd $(top_srcdir) && pwd` ; \ env TESTS_ENVIRONMENT="$${tsrcdir}/cf/maybe-valgrind.sh -s $${tsrcdir} -o $${tobjdir}" make check # # Target to please samba build farm, builds distfiles in-tree. # Will break when automake changes... # distdir-in-tree: $(DISTFILES) $(INFO_DEPS) list='$(DIST_SUBDIRS)'; for subdir in $$list; do \ if test "$$subdir" != .; then \ (cd $$subdir && $(MAKE) $(AM_MAKEFLAGS) distdir-in-tree) ; \ fi ; \ done $(kadmin_OBJECTS): kadmin-commands.h kadmin-commands.c kadmin-commands.h: kadmin-commands.in $(SLC) $(srcdir)/kadmin-commands.in # Tell versions [3.59,3.63) of GNU make to not export all variables. # Otherwise a system limit (for SysV at least) may be exceeded. .NOEXPORT: heimdal-7.5.0/kadmin/check.c0000644000175000017500000001444613026237312013746 0ustar niknik/* * Copyright (c) 2005 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ /* * Check database for strange configurations on default principals */ #include "kadmin_locl.h" #include "kadmin-commands.h" static int get_check_entry(const char *name, kadm5_principal_ent_rec *ent) { krb5_error_code ret; krb5_principal principal; ret = krb5_parse_name(context, name, &principal); if (ret) { krb5_warn(context, ret, "krb5_unparse_name: %s", name); return 1; } memset(ent, 0, sizeof(*ent)); ret = kadm5_get_principal(kadm_handle, principal, ent, KADM5_ATTRIBUTES); krb5_free_principal(context, principal); if(ret) return 1; return 0; } static int do_check_entry(krb5_principal principal, void *data) { krb5_error_code ret; kadm5_principal_ent_rec princ; char *name; int i; ret = krb5_unparse_name(context, principal, &name); if (ret) return 1; memset (&princ, 0, sizeof(princ)); ret = kadm5_get_principal(kadm_handle, principal, &princ, KADM5_PRINCIPAL | KADM5_KEY_DATA); if(ret) { krb5_warn(context, ret, "Failed to get principal: %s", name); free(name); return 0; } for (i = 0; i < princ.n_key_data; i++) { size_t keysize; ret = krb5_enctype_keysize(context, princ.key_data[i].key_data_type[0], &keysize); if (ret == 0 && keysize != (size_t)princ.key_data[i].key_data_length[0]) { krb5_warnx(context, "Principal %s enctype %d, wrong length: %lu\n", name, princ.key_data[i].key_data_type[0], (unsigned long)princ.key_data[i].key_data_length); } } free(name); kadm5_free_principal_ent(kadm_handle, &princ); return 0; } int check(void *opt, int argc, char **argv) { kadm5_principal_ent_rec ent; krb5_error_code ret; char *realm = NULL, *p, *p2; int found; if (argc == 0) { ret = krb5_get_default_realm(context, &realm); if (ret) { krb5_warn(context, ret, "krb5_get_default_realm"); goto fail; } } else { realm = strdup(argv[0]); if (realm == NULL) { krb5_warnx(context, "malloc"); goto fail; } } /* * Check krbtgt/REALM@REALM * * For now, just check existance */ if (asprintf(&p, "%s/%s@%s", KRB5_TGS_NAME, realm, realm) == -1) { krb5_warn(context, errno, "asprintf"); goto fail; } ret = get_check_entry(p, &ent); if (ret) { printf("%s doesn't exist, are you sure %s is a realm in your database", p, realm); free(p); goto fail; } free(p); kadm5_free_principal_ent(kadm_handle, &ent); /* * Check kadmin/admin@REALM */ if (asprintf(&p, "kadmin/admin@%s", realm) == -1) { krb5_warn(context, errno, "asprintf"); goto fail; } ret = get_check_entry(p, &ent); if (ret) { printf("%s doesn't exist, " "there is no way to do remote administration", p); free(p); goto fail; } free(p); kadm5_free_principal_ent(kadm_handle, &ent); /* * Check kadmin/changepw@REALM */ if (asprintf(&p, "kadmin/changepw@%s", realm) == -1) { krb5_warn(context, errno, "asprintf"); goto fail; } ret = get_check_entry(p, &ent); if (ret) { printf("%s doesn't exist, " "there is no way to do change password", p); free(p); goto fail; } free(p); kadm5_free_principal_ent(kadm_handle, &ent); /* * Check default@REALM * * Check that disallow-all-tix is set on the default principal * (or that the entry doesn't exists) */ if (asprintf(&p, "default@%s", realm) == -1) { krb5_warn(context, errno, "asprintf"); goto fail; } ret = get_check_entry(p, &ent); if (ret == 0) { if ((ent.attributes & KRB5_KDB_DISALLOW_ALL_TIX) == 0) { printf("default template entry is not disabled\n"); ret = EINVAL; } kadm5_free_principal_ent(kadm_handle, &ent); } else { ret = 0; } free(p); if (ret) goto fail; /* * Check for duplicate afs keys */ p2 = strdup(realm); if (p2 == NULL) { krb5_warn(context, errno, "malloc"); goto fail; } strlwr(p2); if (asprintf(&p, "afs/%s@%s", p2, realm) == -1) { krb5_warn(context, errno, "asprintf"); free(p2); goto fail; } free(p2); ret = get_check_entry(p, &ent); free(p); if (ret == 0) { kadm5_free_principal_ent(kadm_handle, &ent); found = 1; } else found = 0; if (asprintf(&p, "afs@%s", realm) == -1) { krb5_warn(context, errno, "asprintf"); goto fail; } ret = get_check_entry(p, &ent); free(p); if (ret == 0) { kadm5_free_principal_ent(kadm_handle, &ent); if (found) { krb5_warnx(context, "afs@REALM and afs/cellname@REALM both exists"); goto fail; } } foreach_principal("*", do_check_entry, "check", NULL); free(realm); return 0; fail: free(realm); return 1; } heimdal-7.5.0/kadmin/rename.c0000644000175000017500000000450112136107747014140 0ustar niknik/* * Copyright (c) 1997-2006 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "kadmin_locl.h" #include "kadmin-commands.h" int rename_entry(void *opt, int argc, char **argv) { krb5_error_code ret; krb5_principal princ1, princ2; ret = krb5_parse_name(context, argv[0], &princ1); if(ret){ krb5_warn(context, ret, "krb5_parse_name(%s)", argv[0]); return ret != 0; } ret = krb5_parse_name(context, argv[1], &princ2); if(ret){ krb5_free_principal(context, princ1); krb5_warn(context, ret, "krb5_parse_name(%s)", argv[1]); return ret != 0; } ret = kadm5_rename_principal(kadm_handle, princ1, princ2); if(ret) krb5_warn(context, ret, "rename"); krb5_free_principal(context, princ1); krb5_free_principal(context, princ2); return ret != 0; } heimdal-7.5.0/kadmin/pw_quality.c0000644000175000017500000000433612136107747015075 0ustar niknik/* * Copyright (c) 2003-2004 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "kadmin_locl.h" #include "kadmin-commands.h" int password_quality(void *opt, int argc, char **argv) { krb5_error_code ret; krb5_principal principal; krb5_data pw_data; const char *s; ret = krb5_parse_name(context, argv[0], &principal); if(ret){ krb5_warn(context, ret, "krb5_parse_name(%s)", argv[0]); return 0; } pw_data.data = argv[1]; pw_data.length = strlen(argv[1]); s = kadm5_check_password_quality (context, principal, &pw_data); if (s) krb5_warnx(context, "kadm5_check_password_quality: %s", s); krb5_free_principal(context, principal); return 0; } heimdal-7.5.0/kadmin/kadmin-commands.in0000644000175000017500000002511113026237312016106 0ustar niknik/* * Copyright (c) 2004 - 2007 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ /* $Id$ */ command = { name = "stash" name = "kstash" option = { long = "enctype" short = "e" type = "string" help = "encryption type" default = "des3-cbc-sha1" } option = { long = "key-file" short = "k" type = "string" argument = "file" help = "master key file" } option = { long = "convert-file" type = "flag" help = "just convert keyfile to new format" } option = { long = "random-password" type = "flag" help = "use a random password (and print the password to stdout)" } option = { long = "master-key-fd" type = "integer" argument = "fd" help = "filedescriptor to read passphrase from" default = "-1" } help = "Writes the Kerberos master key to a file used by the KDC. \nLocal (-l) mode only." } command = { name = "dump" option = { long = "decrypt" short = "d" type = "flag" help = "decrypt keys" } option = { long = "format" short = "f" type = "string" help = "dump format, mit or heimdal (default: heimdal)" } argument = "[dump-file]" min_args = "0" max_args = "1" help = "Dumps the database in a human readable format to the specified file, \nor the standard out. Local (-l) mode only." } command = { name = "init" option = { long = "realm-max-ticket-life" type = "string" help = "realm max ticket lifetime" } option = { long = "realm-max-renewable-life" type = "string" help = "realm max renewable lifetime" } option = { long = "bare" type = "flag" help = "only create krbtgt for realm" } argument = "realm..." min_args = "1" help = "Initializes the default principals for a realm. Creates the database\nif necessary. Local (-l) mode only." } command = { name = "load" argument = "file" min_args = "1" max_args = "1" help = "Loads a previously dumped file. Local (-l) mode only." } command = { name = "merge" argument = "file" min_args = "1" max_args = "1" help = "Merges the contents of a dump file into the database. Local (-l) mode only." } command = { name = "add" name = "ank" name = "add_new_key" function = "add_new_key" option = { long = "random-key" short = "r" type = "flag" help = "set random key" } option = { long = "random-password" type = "flag" help = "set random password" } option = { long = "password" short = "p" type = "string" help = "principal's password" } option = { long = "key" type = "string" help = "DES-key in hex" } option = { long = "max-ticket-life" type = "string" argument ="lifetime" help = "max ticket lifetime" } option = { long = "max-renewable-life" type = "string" argument = "lifetime" help = "max renewable life" } option = { long = "attributes" type = "string" argument = "attributes" help = "principal attributes" } option = { long = "expiration-time" type = "string" argument = "time" help = "principal expiration time" } option = { long = "pw-expiration-time" type = "string" argument = "time" help = "password expiration time" } option = { long = "hist-kvno-diff-clnt" type = "integer" argument = "kvno diff" help = "historic keys allowed for client" default = "-1" } option = { long = "hist-kvno-diff-svc" type = "integer" argument = "kvno diff" help = "historic keys allowed for service" default = "-1" } option = { long = "use-defaults" type = "flag" help = "use default values" } option = { long = "policy" type = "string" argument = "policy" help = "policy name" } argument = "principal..." min_args = "1" help = "Adds a principal to the database." } command = { name = "passwd" name = "cpw" name = "change_password" function = "cpw_entry" option = { long = "random-key" short = "r" type = "flag" help = "set random key" } option = { long = "random-password" type = "flag" help = "set random password" } option = { long = "password" short = "p" type = "string" help = "princial's password" } option = { long = "key" type = "string" help = "DES key in hex" } option = { long = "keepold" type = "flag" help = "keep old keys/password" } argument = "principal..." min_args = "1" help = "Changes the password of one or more principals matching the expressions." } command = { name = "delete" name = "del" name = "del_entry" function = "del_entry" argument = "principal..." min_args = "1" help = "Deletes all principals matching the expressions." } command = { name = "del_enctype" argument = "principal enctype..." min_args = "2" help = "Delete all the mentioned enctypes for principal." } command = { name = "add_enctype" option = { long = "random-key" short = "r" type = "flag" help = "set random key" } argument = "principal enctype..." min_args = "2" help = "Add new enctypes for principal." } command = { name = "ext_keytab" option = { long = "keytab" short = "k" type = "string" help = "keytab to use" } option = { long = "random-key" short = "r" type = "flag" help = "set random key" } argument = "principal..." min_args = "1" help = "Extracts the keys of all principals matching the expressions, and stores them in a keytab." } command = { name = "get" name = "get_entry" function = "get_entry" /* XXX sync options with "list" */ option = { long = "long" short = "l" type = "flag" help = "long format" default = "-1" } option = { long = "short" short = "s" type = "flag" help = "short format" } option = { long = "terse" short = "t" type = "flag" help = "terse format" } option = { long = "column-info" short = "o" type = "string" help = "columns to print for short output" } argument = "principal..." min_args = "1" help = "Shows information about principals matching the expressions." } command = { name = "rename" function = "rename_entry" argument = "from to" min_args = "2" max_args = "2" help = "Renames a principal." } command = { name = "modify" function = "mod_entry" option = { long = "max-ticket-life" type = "string" argument ="lifetime" help = "max ticket lifetime" } option = { long = "max-renewable-life" type = "string" argument = "lifetime" help = "max renewable life" } option = { long = "attributes" short = "a" type = "string" argument = "attributes" help = "principal attributes" } option = { long = "expiration-time" type = "string" argument = "time" help = "principal expiration time" } option = { long = "pw-expiration-time" type = "string" argument = "time" help = "password expiration time" } option = { long = "kvno" type = "integer" help = "key version number" default = "-1" } option = { long = "constrained-delegation" type = "strings" argument = "principal" help = "allowed target principals" } option = { long = "alias" type = "strings" argument = "principal" help = "aliases" } option = { long = "pkinit-acl" type = "strings" argument = "subject dn" help = "aliases" } option = { long = "policy" type = "string" argument = "policy" help = "policy name" } option = { long = "hist-kvno-diff-clnt" type = "integer" argument = "kvno diff" help = "historic keys allowed for client" default = "-1" } option = { long = "hist-kvno-diff-svc" type = "integer" argument = "kvno diff" help = "historic keys allowed for service" default = "-1" } argument = "principal" min_args = "1" max_args = "1" help = "Modifies some attributes of the specified principal." } command = { name = "privileges" name = "privs" function = "get_privs" help = "Shows which operations you are allowed to perform." } command = { name = "list" function = "list_princs" /* XXX sync options with "get" */ option = { long = "long" short = "l" type = "flag" help = "long format" } option = { long = "short" short = "s" type = "flag" help = "short format" } option = { long = "terse" short = "t" type = "flag" help = "terse format" default = "-1" } option = { long = "column-info" short = "o" type = "string" help = "columns to print for short output" } argument = "principal..." min_args = "1" help = "Lists principals in a terse format. Equivalent to \"get -t\"." } command = { name = "verify-password-quality" name = "pwq" function = "password_quality" argument = "principal password" min_args = "2" max_args = "2" help = "Try run the password quality function locally (not doing RPC out to server)." } command = { name = "check" function = "check" argument = "[realm]" min_args = "0" max_args = "1" help = "Check the realm (if not given, the default realm) for configuration errors." } command = { name = "lock" function = "lock" argument = "" min_args = "0" max_args = "0" help = "Lock the database for writing (use with care)." } command = { name = "unlock" function = "unlock" argument = "" min_args = "0" max_args = "0" help = "Unlock the database." } command = { name = "help" name = "?" argument = "[command]" min_args = "0" max_args = "1" help = "Help! I need somebody." } command = { name = "exit" name = "quit" function = "exit_kadmin" help = "Quits." } heimdal-7.5.0/kadmin/util.c0000644000175000017500000004233413026237312013643 0ustar niknik/* * Copyright (c) 1997 - 2006 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "kadmin_locl.h" #include /* * util.c - functions for parsing, unparsing, and editing different * types of data used in kadmin. */ static int get_response(const char *prompt, const char *def, char *buf, size_t len); /* * attributes */ struct units kdb_attrs[] = { { "allow-digest", KRB5_KDB_ALLOW_DIGEST }, { "allow-kerberos4", KRB5_KDB_ALLOW_KERBEROS4 }, { "trusted-for-delegation", KRB5_KDB_TRUSTED_FOR_DELEGATION }, { "ok-as-delegate", KRB5_KDB_OK_AS_DELEGATE }, { "new-princ", KRB5_KDB_NEW_PRINC }, { "support-desmd5", KRB5_KDB_SUPPORT_DESMD5 }, { "pwchange-service", KRB5_KDB_PWCHANGE_SERVICE }, { "disallow-svr", KRB5_KDB_DISALLOW_SVR }, { "requires-pw-change", KRB5_KDB_REQUIRES_PWCHANGE }, { "requires-hw-auth", KRB5_KDB_REQUIRES_HW_AUTH }, { "requires-pre-auth", KRB5_KDB_REQUIRES_PRE_AUTH }, { "disallow-all-tix", KRB5_KDB_DISALLOW_ALL_TIX }, { "disallow-dup-skey", KRB5_KDB_DISALLOW_DUP_SKEY }, { "disallow-proxiable", KRB5_KDB_DISALLOW_PROXIABLE }, { "disallow-renewable", KRB5_KDB_DISALLOW_RENEWABLE }, { "disallow-tgt-based", KRB5_KDB_DISALLOW_TGT_BASED }, { "disallow-forwardable", KRB5_KDB_DISALLOW_FORWARDABLE }, { "disallow-postdated", KRB5_KDB_DISALLOW_POSTDATED }, { NULL, 0 } }; /* * convert the attributes in `attributes' into a printable string * in `str, len' */ void attributes2str(krb5_flags attributes, char *str, size_t len) { unparse_flags (attributes, kdb_attrs, str, len); } /* * convert the string in `str' into attributes in `flags' * return 0 if parsed ok, else -1. */ int str2attributes(const char *str, krb5_flags *flags) { int res; res = parse_flags (str, kdb_attrs, *flags); if (res < 0) return res; else { *flags = res; return 0; } } /* * try to parse the string `resp' into attributes in `attr', also * setting the `bit' in `mask' if attributes are given and valid. */ int parse_attributes (const char *resp, krb5_flags *attr, int *mask, int bit) { krb5_flags tmp = *attr; if (str2attributes(resp, &tmp) == 0) { *attr = tmp; if (mask) *mask |= bit; return 0; } else if(*resp == '?') { print_flags_table (kdb_attrs, stderr); } else { fprintf (stderr, "Unable to parse \"%s\"\n", resp); } return -1; } /* * allow the user to edit the attributes in `attr', prompting with `prompt' */ int edit_attributes (const char *prompt, krb5_flags *attr, int *mask, int bit) { char buf[1024], resp[1024]; if (mask && (*mask & bit)) return 0; attributes2str(*attr, buf, sizeof(buf)); for (;;) { if(get_response("Attributes", buf, resp, sizeof(resp)) != 0) return 1; if (resp[0] == '\0') break; if (parse_attributes (resp, attr, mask, bit) == 0) break; } return 0; } /* * try to parse the string `resp' into policy in `attr', also * setting the `bit' in `mask' if attributes are given and valid. */ #define VALID_POLICY_NAME_CHARS \ "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_" int parse_policy (const char *resp, char **policy, int *mask, int bit) { if (strspn(resp, VALID_POLICY_NAME_CHARS) == strlen(resp) && *resp != '\0') { *policy = strdup(resp); if (*policy == NULL) { fprintf (stderr, "Out of memory"); return -1; } if (mask) *mask |= bit; return 0; } else if(*resp == '?') { print_flags_table (kdb_attrs, stderr); } else { fprintf (stderr, "Unable to parse \"%s\"\n", resp); } return -1; } /* * allow the user to edit the attributes in `attr', prompting with `prompt' */ int edit_policy (const char *prompt, char **policy, int *mask, int bit) { char buf[1024], resp[1024]; if (mask && (*mask & bit)) return 0; buf[0] = '\0'; strlcpy(buf, "default", sizeof (buf)); for (;;) { if(get_response("Policy", buf, resp, sizeof(resp)) != 0) return 1; if (resp[0] == '\0') break; if (parse_policy (resp, policy, mask, bit) == 0) break; } return 0; } /* * time_t * the special value 0 means ``never'' */ /* * Convert the time `t' to a string representation in `str' (of max * size `len'). If include_time also include time, otherwise just * date. */ void time_t2str(time_t t, char *str, size_t len, int include_time) { if(t) { if(include_time) strftime(str, len, "%Y-%m-%d %H:%M:%S UTC", gmtime(&t)); else strftime(str, len, "%Y-%m-%d", gmtime(&t)); } else snprintf(str, len, "never"); } /* * Convert the time representation in `str' to a time in `time'. * Return 0 if succesful, else -1. */ int str2time_t (const char *str, time_t *t) { const char *p; struct tm tm, tm2; memset (&tm, 0, sizeof (tm)); memset (&tm2, 0, sizeof (tm2)); while(isspace((unsigned char)*str)) str++; if (str[0] == '+') { str++; *t = parse_time(str, "month"); if (*t < 0) return -1; *t += time(NULL); return 0; } if(strcasecmp(str, "never") == 0) { *t = 0; return 0; } if(strcasecmp(str, "now") == 0) { *t = time(NULL); return 0; } p = strptime (str, "%Y-%m-%d", &tm); if (p == NULL) return -1; while(isspace((unsigned char)*p)) p++; /* XXX this is really a bit optimistic, we should really complain if there was a problem parsing the time */ if(p[0] != '\0' && strptime (p, "%H:%M:%S", &tm2) != NULL) { tm.tm_hour = tm2.tm_hour; tm.tm_min = tm2.tm_min; tm.tm_sec = tm2.tm_sec; } else { /* Do it on the end of the day */ tm.tm_hour = 23; tm.tm_min = 59; tm.tm_sec = 59; } *t = tm2time (tm, 0); return 0; } /* * try to parse the time in `resp' storing it in `value' */ int parse_timet (const char *resp, krb5_timestamp *value, int *mask, int bit) { time_t tmp; if (str2time_t(resp, &tmp) == 0) { *value = tmp; if(mask) *mask |= bit; return 0; } if(*resp != '?') fprintf (stderr, "Unable to parse time \"%s\"\n", resp); fprintf (stderr, "Print date on format YYYY-mm-dd [hh:mm:ss]\n"); return -1; } /* * allow the user to edit the time in `value' */ int edit_timet (const char *prompt, krb5_timestamp *value, int *mask, int bit) { char buf[1024], resp[1024]; if (mask && (*mask & bit)) return 0; time_t2str (*value, buf, sizeof (buf), 0); for (;;) { if(get_response(prompt, buf, resp, sizeof(resp)) != 0) return 1; if (parse_timet (resp, value, mask, bit) == 0) break; } return 0; } /* * deltat * the special value 0 means ``unlimited'' */ /* * convert the delta_t value in `t' into a printable form in `str, len' */ void deltat2str(unsigned t, char *str, size_t len) { if(t == 0 || t == INT_MAX) snprintf(str, len, "unlimited"); else unparse_time(t, str, len); } /* * parse the delta value in `str', storing result in `*delta' * return 0 if ok, else -1 */ int str2deltat(const char *str, krb5_deltat *delta) { int res; if(strcasecmp(str, "unlimited") == 0) { *delta = 0; return 0; } res = parse_time(str, "day"); if (res < 0) return res; else { *delta = res; return 0; } } /* * try to parse the string in `resp' into a deltad in `value' * `mask' will get the bit `bit' set if a value was given. */ int parse_deltat (const char *resp, krb5_deltat *value, int *mask, int bit) { krb5_deltat tmp; if (str2deltat(resp, &tmp) == 0) { *value = tmp; if (mask) *mask |= bit; return 0; } else if(*resp == '?') { print_time_table (stderr); } else { fprintf (stderr, "Unable to parse time \"%s\"\n", resp); } return -1; } /* * allow the user to edit the deltat in `value' */ int edit_deltat (const char *prompt, krb5_deltat *value, int *mask, int bit) { char buf[1024], resp[1024]; if (mask && (*mask & bit)) return 0; deltat2str(*value, buf, sizeof(buf)); for (;;) { if(get_response(prompt, buf, resp, sizeof(resp)) != 0) return 1; if (parse_deltat (resp, value, mask, bit) == 0) break; } return 0; } /* * allow the user to edit `ent' */ void set_defaults(kadm5_principal_ent_t ent, int *mask, kadm5_principal_ent_t default_ent, int default_mask) { if (default_ent && (default_mask & KADM5_MAX_LIFE) && !(*mask & KADM5_MAX_LIFE)) ent->max_life = default_ent->max_life; if (default_ent && (default_mask & KADM5_MAX_RLIFE) && !(*mask & KADM5_MAX_RLIFE)) ent->max_renewable_life = default_ent->max_renewable_life; if (default_ent && (default_mask & KADM5_PRINC_EXPIRE_TIME) && !(*mask & KADM5_PRINC_EXPIRE_TIME)) ent->princ_expire_time = default_ent->princ_expire_time; if (default_ent && (default_mask & KADM5_PW_EXPIRATION) && !(*mask & KADM5_PW_EXPIRATION)) ent->pw_expiration = default_ent->pw_expiration; if (default_ent && (default_mask & KADM5_ATTRIBUTES) && !(*mask & KADM5_ATTRIBUTES)) ent->attributes = default_ent->attributes & ~KRB5_KDB_DISALLOW_ALL_TIX; if (default_ent && (default_mask & KADM5_POLICY) && !(*mask & KADM5_POLICY)) { ent->policy = strdup(default_ent->policy); if (ent->policy == NULL) abort(); } } int edit_entry(kadm5_principal_ent_t ent, int *mask, kadm5_principal_ent_t default_ent, int default_mask) { set_defaults(ent, mask, default_ent, default_mask); if(edit_deltat ("Max ticket life", &ent->max_life, mask, KADM5_MAX_LIFE) != 0) return 1; if(edit_deltat ("Max renewable life", &ent->max_renewable_life, mask, KADM5_MAX_RLIFE) != 0) return 1; if(edit_timet ("Principal expiration time", &ent->princ_expire_time, mask, KADM5_PRINC_EXPIRE_TIME) != 0) return 1; if(edit_timet ("Password expiration time", &ent->pw_expiration, mask, KADM5_PW_EXPIRATION) != 0) return 1; if(edit_attributes ("Attributes", &ent->attributes, mask, KADM5_ATTRIBUTES) != 0) return 1; if(edit_policy ("Policy", &ent->policy, mask, KADM5_POLICY) != 0) return 1; return 0; } /* * Parse the arguments, set the fields in `ent' and the `mask' for the * entries having been set. * Return 1 on failure and 0 on success. */ int set_entry(krb5_context contextp, kadm5_principal_ent_t ent, int *mask, const char *max_ticket_life, const char *max_renewable_life, const char *expiration, const char *pw_expiration, const char *attributes, const char *policy) { if (max_ticket_life != NULL) { if (parse_deltat (max_ticket_life, &ent->max_life, mask, KADM5_MAX_LIFE)) { krb5_warnx (contextp, "unable to parse `%s'", max_ticket_life); return 1; } } if (max_renewable_life != NULL) { if (parse_deltat (max_renewable_life, &ent->max_renewable_life, mask, KADM5_MAX_RLIFE)) { krb5_warnx (contextp, "unable to parse `%s'", max_renewable_life); return 1; } } if (expiration) { if (parse_timet (expiration, &ent->princ_expire_time, mask, KADM5_PRINC_EXPIRE_TIME)) { krb5_warnx (contextp, "unable to parse `%s'", expiration); return 1; } } if (pw_expiration) { if (parse_timet (pw_expiration, &ent->pw_expiration, mask, KADM5_PW_EXPIRATION)) { krb5_warnx (contextp, "unable to parse `%s'", pw_expiration); return 1; } } if (attributes != NULL) { if (parse_attributes (attributes, &ent->attributes, mask, KADM5_ATTRIBUTES)) { krb5_warnx (contextp, "unable to parse `%s'", attributes); return 1; } } if (policy != NULL) { if (parse_policy (policy, &ent->policy, mask, KADM5_POLICY)) { krb5_warnx (contextp, "unable to parse `%s'", attributes); return 1; } } return 0; } /* * Does `string' contain any globing characters? */ static int is_expression(const char *string) { const char *p; int quote = 0; for(p = string; *p; p++) { if(quote) { quote = 0; continue; } if(*p == '\\') quote++; else if(strchr("[]*?", *p) != NULL) return 1; } return 0; } /* * Loop over all principals matching exp. If any of calls to `func' * failes, the first error is returned when all principals are * processed. */ int foreach_principal(const char *exp_str, int (*func)(krb5_principal, void*), const char *funcname, void *data) { char **princs = NULL; int num_princs = 0; int i; krb5_error_code saved_ret = 0, ret = 0; krb5_principal princ_ent; int is_expr; /* if this isn't an expression, there is no point in wading through the whole database looking for matches */ is_expr = is_expression(exp_str); if(is_expr) ret = kadm5_get_principals(kadm_handle, exp_str, &princs, &num_princs); if(!is_expr || ret == KADM5_AUTH_LIST) { /* we might be able to perform the requested opreration even if we're not allowed to list principals */ num_princs = 1; princs = malloc(sizeof(*princs)); if(princs == NULL) return ENOMEM; princs[0] = strdup(exp_str); if(princs[0] == NULL){ free(princs); return ENOMEM; } } else if(ret) { krb5_warn(context, ret, "kadm5_get_principals"); return ret; } for(i = 0; i < num_princs; i++) { ret = krb5_parse_name(context, princs[i], &princ_ent); if(ret){ krb5_warn(context, ret, "krb5_parse_name(%s)", princs[i]); continue; } ret = (*func)(princ_ent, data); if(ret) { krb5_clear_error_message(context); krb5_warn(context, ret, "%s %s", funcname, princs[i]); if (saved_ret == 0) saved_ret = ret; } krb5_free_principal(context, princ_ent); } if (ret == 0 && saved_ret != 0) ret = saved_ret; kadm5_free_name_list(kadm_handle, princs, &num_princs); return ret; } /* * prompt with `prompt' and default value `def', and store the reply * in `buf, len' */ #include static jmp_buf jmpbuf; static void interrupt(int sig) { longjmp(jmpbuf, 1); } static int get_response(const char *prompt, const char *def, char *buf, size_t len) { char *p; void (*osig)(int); osig = signal(SIGINT, interrupt); if(setjmp(jmpbuf)) { signal(SIGINT, osig); fprintf(stderr, "\n"); return 1; } fprintf(stderr, "%s [%s]:", prompt, def); if(fgets(buf, len, stdin) == NULL) { int save_errno = errno; if(ferror(stdin)) krb5_err(context, 1, save_errno, ""); signal(SIGINT, osig); return 1; } p = strchr(buf, '\n'); if(p) *p = '\0'; if(strcmp(buf, "") == 0) strlcpy(buf, def, len); signal(SIGINT, osig); return 0; } /* * return [0, 16) or -1 */ static int hex2n (char c) { static char hexdigits[] = "0123456789abcdef"; const char *p; p = strchr (hexdigits, tolower((unsigned char)c)); if (p == NULL) return -1; else return p - hexdigits; } /* * convert a key in a readable format into a keyblock. * return 0 iff succesful, otherwise `err' should point to an error message */ int parse_des_key (const char *key_string, krb5_key_data *key_data, const char **error) { const char *p = key_string; unsigned char bits[8]; int i; if (strlen (key_string) != 16) { *error = "bad length, should be 16 for DES key"; return 1; } for (i = 0; i < 8; ++i) { int d1, d2; d1 = hex2n(p[2 * i]); d2 = hex2n(p[2 * i + 1]); if (d1 < 0 || d2 < 0) { *error = "non-hex character"; return 1; } bits[i] = (d1 << 4) | d2; } for (i = 0; i < 3; ++i) { key_data[i].key_data_ver = 2; key_data[i].key_data_kvno = 0; /* key */ key_data[i].key_data_type[0] = ETYPE_DES_CBC_CRC; key_data[i].key_data_length[0] = 8; key_data[i].key_data_contents[0] = malloc(8); if (key_data[i].key_data_contents[0] == NULL) { *error = "malloc"; return ENOMEM; } memcpy (key_data[i].key_data_contents[0], bits, 8); /* salt */ key_data[i].key_data_type[1] = KRB5_PW_SALT; key_data[i].key_data_length[1] = 0; key_data[i].key_data_contents[1] = NULL; } key_data[0].key_data_type[0] = ETYPE_DES_CBC_MD5; key_data[1].key_data_type[0] = ETYPE_DES_CBC_MD4; return 0; } heimdal-7.5.0/kadmin/NTMakefile0000644000175000017500000000672213026237312014425 0ustar niknik######################################################################## # # Copyright (c) 2009, Secure Endpoints Inc. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # - Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # # - Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in # the documentation and/or other materials provided with the # distribution. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS # FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE # COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, # BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN # ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. # RELDIR=kadmin cincdirs=-I$(OBJ) -I$(INCDIR)\gssapi !include ../windows/NTMakefile.w32 SBIN_PROGRAMS=$(SBINDIR)\kadmin.exe # Disable kadmind.exe since currently it doesn't build #LIBEXEC_PROGRAMS=$(LIBEXECDIR)\kadmind.exe # COMMON_LIBS= \ $(LIBHDB) \ $(LIBHEIMDAL) \ $(LIBROKEN) KADMIN_OBJS= \ $(OBJ)\ank.obj \ $(OBJ)\add_enctype.obj \ $(OBJ)\check.obj \ $(OBJ)\cpw.obj \ $(OBJ)\del.obj \ $(OBJ)\del_enctype.obj \ $(OBJ)\dump.obj \ $(OBJ)\ext.obj \ $(OBJ)\get.obj \ $(OBJ)\init.obj \ $(OBJ)\kadmin.obj \ $(OBJ)\load.obj \ $(OBJ)\mod.obj \ $(OBJ)\rename.obj \ $(OBJ)\stash.obj \ $(OBJ)\util.obj \ $(OBJ)\pw_quality.obj \ $(OBJ)\random_password.obj \ $(OBJ)\kadmin-commands.obj \ $(OBJ)\kadmin-version.res KADMIN_LIBS= \ $(LIBKADM5CLNT) \ $(LIBKADM5SRV) \ $(LIBSL) \ $(COMMON_LIBS) \ $(LIBVERS) \ $(LIBCOMERR) INCFILES=$(OBJ)\kadmin-commands.h $(OBJ)\kadmin-commands.c $(OBJ)\kadmin-commands.h: kadmin-commands.in cd $(OBJ) $(CP) $(SRCDIR)\kadmin-commands.in $(OBJ) $(BINDIR)\slc.exe kadmin-commands.in cd $(SRCDIR) $(SBINDIR)\kadmin.exe: $(KADMIN_OBJS) $(KADMIN_LIBS) $(EXECONLINK) $(EXEPREP) KADMIND_OBJS= \ $(OBJ)\rpc.obj \ $(OBJ)\server.obj \ $(OBJ)\kadmind.obj \ $(OBJ)\kadm_conn.obj \ $(OBJ)\kadmind-version.res KADMIND_LIBS=\ $(LIBKADM5SRV) \ $(LIBGSSAPI) \ $(COMMON_LIBS) $(LIBEXECDIR)\kadmind.exe: $(KADMIND_OBJS) $(KADMIND_LIBS) $(EXECONLINK) $(EXEPREP) all:: $(INCFILES) $(SBIN_PROGRAMS) $(LIBEXEC_PROGRAMS) clean:: -$(RM) $(SBIN_PROGRAMS:.exe=.*) -$(RM) $(LIBEXEC_PROGRAMS:.exe=.*) NOINST_PROGRAMS=$(OBJ)\add_random_users.exe $(OBJ)\add_random_users.exe: $(OBJ)\add_random_users.obj $(LIBKADM5SRV) $(LIBKADM5CLNT) $(COMMON_LIBS) $(EXECONLINK) $(EXEPREP_NODIST) TEST_BINARIES=$(OBJ)\test_util.exe $(OBJ)\test_util.exe: $(OBJ)\test_util.obj $(OBJ)\util.obj $(KADMIN_LIBS) $(EXECONLINK) $(EXEPREP_NODIST) test-binaries: $(TEST_BINARIES) test-run: cd $(OBJ) test_util.exe cd $(SRCDIR) test:: test-binaries test-run heimdal-7.5.0/kadmin/rpc.c0000644000175000017500000006512613026237312013456 0ustar niknik/* * Copyright (c) 2008 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "kadmin_locl.h" #include #include #include #define CHECK(x) \ do { \ int __r; \ if ((__r = (x))) { \ krb5_errx(dcontext, 1, "Failed (%d) on %s:%d", \ __r, __FILE__, __LINE__); \ } \ } while(0) static krb5_context dcontext; #define INSIST(x) CHECK(!(x)) #define VERSION2 0x12345702 #define LAST_FRAGMENT 0x80000000 #define RPC_VERSION 2 #define KADM_SERVER 2112 #define VVERSION 2 #define FLAVOR_GSS 6 #define FLAVOR_GSS_VERSION 1 struct opaque_auth { uint32_t flavor; krb5_data data; }; struct call_header { uint32_t xid; uint32_t rpcvers; uint32_t prog; uint32_t vers; uint32_t proc; struct opaque_auth cred; struct opaque_auth verf; }; enum { RPG_DATA = 0, RPG_INIT = 1, RPG_CONTINUE_INIT = 2, RPG_DESTROY = 3 }; enum { rpg_privacy = 3 }; /* struct chrand_ret { krb5_ui_4 api_version; kadm5_ret_t ret; int n_keys; krb5_keyblock *keys; }; */ struct gcred { uint32_t version; uint32_t proc; uint32_t seq_num; uint32_t service; krb5_data handle; }; static int parse_name(const unsigned char *p, size_t len, const gss_OID oid, char **name) { size_t l; if (len < 4) return 1; /* TOK_ID */ if (memcmp(p, "\x04\x01", 2) != 0) return 1; len -= 2; p += 2; /* MECH_LEN */ l = (p[0] << 8) | p[1]; len -= 2; p += 2; if (l < 2 || len < l) return 1; /* oid wrapping */ if (p[0] != 6 || p[1] != l - 2) return 1; p += 2; l -= 2; len -= 2; /* MECH */ if (l != oid->length || memcmp(p, oid->elements, oid->length) != 0) return 1; len -= l; p += l; /* MECHNAME_LEN */ if (len < 4) return 1; l = p[0] << 24 | p[1] << 16 | p[2] << 8 | p[3]; len -= 4; p += 4; /* MECH NAME */ if (len != l) return 1; *name = malloc(l + 1); INSIST(*name != NULL); memcpy(*name, p, l); (*name)[l] = '\0'; return 0; } static void gss_error(krb5_context contextp, gss_OID mech, OM_uint32 type, OM_uint32 error) { OM_uint32 new_stat; OM_uint32 msg_ctx = 0; gss_buffer_desc status_string; OM_uint32 ret; do { ret = gss_display_status (&new_stat, error, type, mech, &msg_ctx, &status_string); krb5_warnx(contextp, "%.*s", (int)status_string.length, (char *)status_string.value); gss_release_buffer (&new_stat, &status_string); } while (!GSS_ERROR(ret) && msg_ctx != 0); } static void gss_print_errors (krb5_context contextp, OM_uint32 maj_stat, OM_uint32 min_stat) { gss_error(contextp, GSS_C_NO_OID, GSS_C_GSS_CODE, maj_stat); gss_error(contextp, GSS_C_NO_OID, GSS_C_MECH_CODE, min_stat); } static int read_data(krb5_storage *sp, krb5_storage *msg, size_t len) { char buf[1024]; while (len) { size_t tlen = len; ssize_t slen; if (tlen > sizeof(buf)) tlen = sizeof(buf); slen = krb5_storage_read(sp, buf, tlen); INSIST((size_t)slen == tlen); slen = krb5_storage_write(msg, buf, tlen); INSIST((size_t)slen == tlen); len -= tlen; } return 0; } static int collect_framents(krb5_storage *sp, krb5_storage *msg) { krb5_error_code ret; uint32_t len; int last_fragment; size_t total_len = 0; do { ret = krb5_ret_uint32(sp, &len); if (ret) return ret; last_fragment = (len & LAST_FRAGMENT); len &= ~LAST_FRAGMENT; CHECK(read_data(sp, msg, len)); total_len += len; } while(!last_fragment || total_len == 0); return 0; } static krb5_error_code store_data_xdr(krb5_storage *sp, krb5_data data) { krb5_error_code ret; size_t res; ret = krb5_store_data(sp, data); if (ret) return ret; res = 4 - (data.length % 4); if (res != 4) { static const char zero[4] = { 0, 0, 0, 0 }; ret = krb5_storage_write(sp, zero, res); if((size_t)ret != res) return (ret < 0)? errno : krb5_storage_get_eof_code(sp); } return 0; } static krb5_error_code ret_data_xdr(krb5_storage *sp, krb5_data *data) { krb5_error_code ret; ret = krb5_ret_data(sp, data); if (ret) return ret; if ((data->length % 4) != 0) { char buf[4]; size_t res; res = 4 - (data->length % 4); if (res != 4) { ret = krb5_storage_read(sp, buf, res); if((size_t)ret != res) return (ret < 0)? errno : krb5_storage_get_eof_code(sp); } } return 0; } static krb5_error_code ret_auth_opaque(krb5_storage *msg, struct opaque_auth *ao) { krb5_error_code ret; ret = krb5_ret_uint32(msg, &ao->flavor); if (ret) return ret; ret = ret_data_xdr(msg, &ao->data); return ret; } static int ret_gcred(krb5_data *data, struct gcred *gcred) { krb5_storage *sp; memset(gcred, 0, sizeof(*gcred)); sp = krb5_storage_from_data(data); INSIST(sp != NULL); CHECK(krb5_ret_uint32(sp, &gcred->version)); CHECK(krb5_ret_uint32(sp, &gcred->proc)); CHECK(krb5_ret_uint32(sp, &gcred->seq_num)); CHECK(krb5_ret_uint32(sp, &gcred->service)); CHECK(ret_data_xdr(sp, &gcred->handle)); krb5_storage_free(sp); return 0; } static krb5_error_code store_gss_init_res(krb5_storage *sp, krb5_data handle, OM_uint32 maj_stat, OM_uint32 min_stat, uint32_t seq_window, gss_buffer_t gout) { krb5_error_code ret; krb5_data out; out.data = gout->value; out.length = gout->length; ret = store_data_xdr(sp, handle); if (ret) return ret; ret = krb5_store_uint32(sp, maj_stat); if (ret) return ret; ret = krb5_store_uint32(sp, min_stat); if (ret) return ret; ret = store_data_xdr(sp, out); return ret; } static int store_string_xdr(krb5_storage *sp, const char *str) { krb5_data c; if (str) { c.data = rk_UNCONST(str); c.length = strlen(str) + 1; } else krb5_data_zero(&c); return store_data_xdr(sp, c); } static int ret_string_xdr(krb5_storage *sp, char **str) { krb5_data c; *str = NULL; CHECK(ret_data_xdr(sp, &c)); if (c.length) { *str = malloc(c.length + 1); INSIST(*str != NULL); memcpy(*str, c.data, c.length); (*str)[c.length] = '\0'; } krb5_data_free(&c); return 0; } static int store_principal_xdr(krb5_context contextp, krb5_storage *sp, krb5_principal p) { char *str; CHECK(krb5_unparse_name(contextp, p, &str)); CHECK(store_string_xdr(sp, str)); free(str); return 0; } static int ret_principal_xdr(krb5_context contextp, krb5_storage *sp, krb5_principal *p) { char *str; *p = NULL; CHECK(ret_string_xdr(sp, &str)); if (str) { CHECK(krb5_parse_name(contextp, str, p)); free(str); } return 0; } static int store_principal_ent(krb5_context contextp, krb5_storage *sp, kadm5_principal_ent_rec *ent) { int i; CHECK(store_principal_xdr(contextp, sp, ent->principal)); CHECK(krb5_store_uint32(sp, ent->princ_expire_time)); CHECK(krb5_store_uint32(sp, ent->pw_expiration)); CHECK(krb5_store_uint32(sp, ent->last_pwd_change)); CHECK(krb5_store_uint32(sp, ent->max_life)); CHECK(krb5_store_int32(sp, ent->mod_name == NULL)); if (ent->mod_name) CHECK(store_principal_xdr(contextp, sp, ent->mod_name)); CHECK(krb5_store_uint32(sp, ent->mod_date)); CHECK(krb5_store_uint32(sp, ent->attributes)); CHECK(krb5_store_uint32(sp, ent->kvno)); CHECK(krb5_store_uint32(sp, ent->mkvno)); CHECK(store_string_xdr(sp, ent->policy)); CHECK(krb5_store_int32(sp, ent->aux_attributes)); CHECK(krb5_store_int32(sp, ent->max_renewable_life)); CHECK(krb5_store_int32(sp, ent->last_success)); CHECK(krb5_store_int32(sp, ent->last_failed)); CHECK(krb5_store_int32(sp, ent->fail_auth_count)); CHECK(krb5_store_int32(sp, ent->n_key_data)); CHECK(krb5_store_int32(sp, ent->n_tl_data)); CHECK(krb5_store_int32(sp, ent->n_tl_data == 0)); if (ent->n_tl_data) { krb5_tl_data *tp; for (tp = ent->tl_data; tp; tp = tp->tl_data_next) { krb5_data c; c.length = tp->tl_data_length; c.data = tp->tl_data_contents; CHECK(krb5_store_int32(sp, 0)); /* last item */ CHECK(krb5_store_int32(sp, tp->tl_data_type)); CHECK(store_data_xdr(sp, c)); } CHECK(krb5_store_int32(sp, 1)); /* last item */ } CHECK(krb5_store_int32(sp, ent->n_key_data)); for (i = 0; i < ent->n_key_data; i++) { CHECK(krb5_store_uint32(sp, 2)); CHECK(krb5_store_uint32(sp, ent->kvno)); CHECK(krb5_store_uint32(sp, ent->key_data[i].key_data_type[0])); CHECK(krb5_store_uint32(sp, ent->key_data[i].key_data_type[1])); } return 0; } static int ret_principal_ent(krb5_context contextp, krb5_storage *sp, kadm5_principal_ent_rec *ent) { uint32_t flag, num; size_t i; memset(ent, 0, sizeof(*ent)); CHECK(ret_principal_xdr(contextp, sp, &ent->principal)); CHECK(krb5_ret_uint32(sp, &flag)); ent->princ_expire_time = flag; CHECK(krb5_ret_uint32(sp, &flag)); ent->pw_expiration = flag; CHECK(krb5_ret_uint32(sp, &flag)); ent->last_pwd_change = flag; CHECK(krb5_ret_uint32(sp, &flag)); ent->max_life = flag; CHECK(krb5_ret_uint32(sp, &flag)); if (flag == 0) CHECK(ret_principal_xdr(contextp, sp, &ent->mod_name)); CHECK(krb5_ret_uint32(sp, &flag)); ent->mod_date = flag; CHECK(krb5_ret_uint32(sp, &flag)); ent->attributes = flag; CHECK(krb5_ret_uint32(sp, &flag)); ent->kvno = flag; CHECK(krb5_ret_uint32(sp, &flag)); ent->mkvno = flag; CHECK(ret_string_xdr(sp, &ent->policy)); CHECK(krb5_ret_uint32(sp, &flag)); ent->aux_attributes = flag; CHECK(krb5_ret_uint32(sp, &flag)); ent->max_renewable_life = flag; CHECK(krb5_ret_uint32(sp, &flag)); ent->last_success = flag; CHECK(krb5_ret_uint32(sp, &flag)); ent->last_failed = flag; CHECK(krb5_ret_uint32(sp, &flag)); ent->fail_auth_count = flag; CHECK(krb5_ret_uint32(sp, &flag)); ent->n_key_data = flag; CHECK(krb5_ret_uint32(sp, &flag)); ent->n_tl_data = flag; CHECK(krb5_ret_uint32(sp, &flag)); if (flag == 0) { krb5_tl_data **tp = &ent->tl_data; size_t count = 0; while(1) { krb5_data c; CHECK(krb5_ret_uint32(sp, &flag)); /* last item */ if (flag) break; *tp = calloc(1, sizeof(**tp)); INSIST(*tp != NULL); CHECK(krb5_ret_uint32(sp, &flag)); (*tp)->tl_data_type = flag; CHECK(ret_data_xdr(sp, &c)); (*tp)->tl_data_length = c.length; (*tp)->tl_data_contents = c.data; tp = &(*tp)->tl_data_next; count++; } INSIST((size_t)ent->n_tl_data == count); } else { INSIST(ent->n_tl_data == 0); } CHECK(krb5_ret_uint32(sp, &num)); INSIST(num == (uint32_t)ent->n_key_data); ent->key_data = calloc(num, sizeof(ent->key_data[0])); INSIST(ent->key_data != NULL); for (i = 0; i < num; i++) { CHECK(krb5_ret_uint32(sp, &flag)); /* data version */ INSIST(flag > 1); CHECK(krb5_ret_uint32(sp, &flag)); ent->kvno = flag; CHECK(krb5_ret_uint32(sp, &flag)); ent->key_data[i].key_data_type[0] = flag; CHECK(krb5_ret_uint32(sp, &flag)); ent->key_data[i].key_data_type[1] = flag; } return 0; } /* * */ static void proc_create_principal(kadm5_server_context *contextp, krb5_storage *in, krb5_storage *out) { uint32_t version, mask; kadm5_principal_ent_rec ent; krb5_error_code ret; char *password; memset(&ent, 0, sizeof(ent)); CHECK(krb5_ret_uint32(in, &version)); INSIST(version == VERSION2); CHECK(ret_principal_ent(contextp->context, in, &ent)); CHECK(krb5_ret_uint32(in, &mask)); CHECK(ret_string_xdr(in, &password)); INSIST(ent.principal); ret = _kadm5_acl_check_permission(contextp, KADM5_PRIV_ADD, ent.principal); if (ret) goto fail; ret = kadm5_create_principal(contextp, &ent, mask, password); fail: krb5_warn(contextp->context, ret, "create principal"); CHECK(krb5_store_uint32(out, VERSION2)); /* api version */ CHECK(krb5_store_uint32(out, ret)); /* code */ free(password); kadm5_free_principal_ent(contextp, &ent); } static void proc_delete_principal(kadm5_server_context *contextp, krb5_storage *in, krb5_storage *out) { uint32_t version; krb5_principal princ; krb5_error_code ret; CHECK(krb5_ret_uint32(in, &version)); INSIST(version == VERSION2); CHECK(ret_principal_xdr(contextp->context, in, &princ)); ret = _kadm5_acl_check_permission(contextp, KADM5_PRIV_DELETE, princ); if (ret) goto fail; ret = kadm5_delete_principal(contextp, princ); fail: krb5_warn(contextp->context, ret, "delete principal"); CHECK(krb5_store_uint32(out, VERSION2)); /* api version */ CHECK(krb5_store_uint32(out, ret)); /* code */ krb5_free_principal(contextp->context, princ); } static void proc_get_principal(kadm5_server_context *contextp, krb5_storage *in, krb5_storage *out) { uint32_t version, mask; krb5_principal princ; kadm5_principal_ent_rec ent; krb5_error_code ret; memset(&ent, 0, sizeof(ent)); CHECK(krb5_ret_uint32(in, &version)); INSIST(version == VERSION2); CHECK(ret_principal_xdr(contextp->context, in, &princ)); CHECK(krb5_ret_uint32(in, &mask)); ret = _kadm5_acl_check_permission(contextp, KADM5_PRIV_GET, princ); if(ret) goto fail; ret = kadm5_get_principal(contextp, princ, &ent, mask); fail: krb5_warn(contextp->context, ret, "get principal principal"); CHECK(krb5_store_uint32(out, VERSION2)); /* api version */ CHECK(krb5_store_uint32(out, ret)); /* code */ if (ret == 0) { CHECK(store_principal_ent(contextp->context, out, &ent)); } krb5_free_principal(contextp->context, princ); kadm5_free_principal_ent(contextp, &ent); } static void proc_chrand_principal_v2(kadm5_server_context *contextp, krb5_storage *in, krb5_storage *out) { krb5_error_code ret; krb5_principal princ; uint32_t version; krb5_keyblock *new_keys; int n_keys; CHECK(krb5_ret_uint32(in, &version)); INSIST(version == VERSION2); CHECK(ret_principal_xdr(contextp->context, in, &princ)); ret = _kadm5_acl_check_permission(contextp, KADM5_PRIV_CPW, princ); if(ret) goto fail; ret = kadm5_randkey_principal(contextp, princ, &new_keys, &n_keys); fail: krb5_warn(contextp->context, ret, "rand key principal"); CHECK(krb5_store_uint32(out, VERSION2)); /* api version */ CHECK(krb5_store_uint32(out, ret)); if (ret == 0) { int i; CHECK(krb5_store_int32(out, n_keys)); for(i = 0; i < n_keys; i++){ CHECK(krb5_store_uint32(out, new_keys[i].keytype)); CHECK(store_data_xdr(out, new_keys[i].keyvalue)); krb5_free_keyblock_contents(contextp->context, &new_keys[i]); } free(new_keys); } krb5_free_principal(contextp->context, princ); } static void proc_init(kadm5_server_context *contextp, krb5_storage *in, krb5_storage *out) { CHECK(krb5_store_uint32(out, VERSION2)); /* api version */ CHECK(krb5_store_uint32(out, 0)); /* code */ CHECK(krb5_store_uint32(out, 0)); /* code */ } struct krb5_proc { const char *name; void (*func)(kadm5_server_context *, krb5_storage *, krb5_storage *); } procs[] = { { "NULL", NULL }, { "create principal", proc_create_principal }, { "delete principal", proc_delete_principal }, { "modify principal", NULL }, { "rename principal", NULL }, { "get principal", proc_get_principal }, { "chpass principal", NULL }, { "chrand principal", proc_chrand_principal_v2 }, { "create policy", NULL }, { "delete policy", NULL }, { "modify policy", NULL }, { "get policy", NULL }, { "get privs", NULL }, { "init", proc_init }, { "get principals", NULL }, { "get polices", NULL }, { "setkey principal", NULL }, { "setkey principal v4", NULL }, { "create principal v3", NULL }, { "chpass principal v3", NULL }, { "chrand principal v3", NULL }, { "setkey principal v3", NULL } }; static krb5_error_code copyheader(krb5_storage *sp, krb5_data *data) { off_t off; ssize_t sret; off = krb5_storage_seek(sp, 0, SEEK_CUR); CHECK(krb5_data_alloc(data, off)); INSIST((size_t)off == data->length); krb5_storage_seek(sp, 0, SEEK_SET); sret = krb5_storage_read(sp, data->data, data->length); INSIST(sret == off); INSIST(off == krb5_storage_seek(sp, 0, SEEK_CUR)); return 0; } struct gctx { krb5_data handle; gss_ctx_id_t ctx; uint32_t seq_num; int done; int inprogress; }; static int process_stream(krb5_context contextp, unsigned char *buf, size_t ilen, krb5_storage *sp) { krb5_error_code ret; krb5_storage *msg, *reply, *dreply; OM_uint32 maj_stat, min_stat; gss_buffer_desc gin, gout; struct gctx gctx; void *server_handle = NULL; memset(&gctx, 0, sizeof(gctx)); msg = krb5_storage_emem(); reply = krb5_storage_emem(); dreply = krb5_storage_emem(); /* * First packet comes partly from the caller */ INSIST(ilen >= 4); while (1) { struct call_header chdr; struct gcred gcred; uint32_t mtype; krb5_data headercopy; krb5_storage_truncate(dreply, 0); krb5_storage_truncate(reply, 0); krb5_storage_truncate(msg, 0); krb5_data_zero(&headercopy); memset(&chdr, 0, sizeof(chdr)); memset(&gcred, 0, sizeof(gcred)); /* * This is very icky to handle the the auto-detection between * the Heimdal protocol and the MIT ONC-RPC based protocol. */ if (ilen) { int last_fragment; unsigned long len; ssize_t slen; unsigned char tmp[4]; if (ilen < 4) { memcpy(tmp, buf, ilen); slen = krb5_storage_read(sp, tmp + ilen, sizeof(tmp) - ilen); INSIST((size_t)slen == sizeof(tmp) - ilen); ilen = sizeof(tmp); buf = tmp; } INSIST(ilen >= 4); _krb5_get_int(buf, &len, 4); last_fragment = (len & LAST_FRAGMENT) != 0; len &= ~LAST_FRAGMENT; ilen -= 4; buf += 4; if (ilen) { if (len < ilen) { slen = krb5_storage_write(msg, buf, len); INSIST((size_t)slen == len); ilen -= len; len = 0; } else { slen = krb5_storage_write(msg, buf, ilen); INSIST((size_t)slen == ilen); len -= ilen; } } CHECK(read_data(sp, msg, len)); if (!last_fragment) { ret = collect_framents(sp, msg); if (ret == HEIM_ERR_EOF) krb5_errx(contextp, 0, "client disconnected"); INSIST(ret == 0); } } else { ret = collect_framents(sp, msg); if (ret == HEIM_ERR_EOF) krb5_errx(contextp, 0, "client disconnected"); INSIST(ret == 0); } krb5_storage_seek(msg, 0, SEEK_SET); CHECK(krb5_ret_uint32(msg, &chdr.xid)); CHECK(krb5_ret_uint32(msg, &mtype)); CHECK(krb5_ret_uint32(msg, &chdr.rpcvers)); CHECK(krb5_ret_uint32(msg, &chdr.prog)); CHECK(krb5_ret_uint32(msg, &chdr.vers)); CHECK(krb5_ret_uint32(msg, &chdr.proc)); CHECK(ret_auth_opaque(msg, &chdr.cred)); CHECK(copyheader(msg, &headercopy)); CHECK(ret_auth_opaque(msg, &chdr.verf)); INSIST(chdr.rpcvers == RPC_VERSION); INSIST(chdr.prog == KADM_SERVER); INSIST(chdr.vers == VVERSION); INSIST(chdr.cred.flavor == FLAVOR_GSS); CHECK(ret_gcred(&chdr.cred.data, &gcred)); INSIST(gcred.version == FLAVOR_GSS_VERSION); if (gctx.done) { INSIST(chdr.verf.flavor == FLAVOR_GSS); /* from first byte to last of credential */ gin.value = headercopy.data; gin.length = headercopy.length; gout.value = chdr.verf.data.data; gout.length = chdr.verf.data.length; maj_stat = gss_verify_mic(&min_stat, gctx.ctx, &gin, &gout, NULL); INSIST(maj_stat == GSS_S_COMPLETE); } switch(gcred.proc) { case RPG_DATA: { krb5_data data; int conf_state; uint32_t seq; krb5_storage *sp1; INSIST(gcred.service == rpg_privacy); INSIST(gctx.done); INSIST(krb5_data_cmp(&gcred.handle, &gctx.handle) == 0); CHECK(ret_data_xdr(msg, &data)); gin.value = data.data; gin.length = data.length; maj_stat = gss_unwrap(&min_stat, gctx.ctx, &gin, &gout, &conf_state, NULL); krb5_data_free(&data); INSIST(maj_stat == GSS_S_COMPLETE); INSIST(conf_state != 0); sp1 = krb5_storage_from_mem(gout.value, gout.length); INSIST(sp1 != NULL); CHECK(krb5_ret_uint32(sp1, &seq)); INSIST (seq == gcred.seq_num); /* * Check sequence number */ INSIST(seq > gctx.seq_num); gctx.seq_num = seq; /* * If contextp is setup, priv data have the seq_num stored * first in the block, so add it here before users data is * added. */ CHECK(krb5_store_uint32(dreply, gctx.seq_num)); if (chdr.proc >= sizeof(procs)/sizeof(procs[0])) { krb5_warnx(contextp, "proc number out of array"); } else if (procs[chdr.proc].func == NULL) { krb5_warnx(contextp, "proc '%s' never implemented", procs[chdr.proc].name); } else { krb5_warnx(contextp, "proc %s", procs[chdr.proc].name); INSIST(server_handle != NULL); (*procs[chdr.proc].func)(server_handle, sp, dreply); } krb5_storage_free(sp); gss_release_buffer(&min_stat, &gout); break; } case RPG_INIT: INSIST(gctx.inprogress == 0); INSIST(gctx.ctx == NULL); gctx.inprogress = 1; /* FALL THOUGH */ case RPG_CONTINUE_INIT: { gss_name_t src_name = GSS_C_NO_NAME; krb5_data in; INSIST(gctx.inprogress); CHECK(ret_data_xdr(msg, &in)); gin.value = in.data; gin.length = in.length; gout.value = NULL; gout.length = 0; maj_stat = gss_accept_sec_context(&min_stat, &gctx.ctx, GSS_C_NO_CREDENTIAL, &gin, GSS_C_NO_CHANNEL_BINDINGS, &src_name, NULL, &gout, NULL, NULL, NULL); if (GSS_ERROR(maj_stat)) { gss_print_errors(contextp, maj_stat, min_stat); krb5_errx(contextp, 1, "gss error, exit"); } if ((maj_stat & GSS_S_CONTINUE_NEEDED) == 0) { kadm5_config_params realm_params; gss_buffer_desc bufp; char *client; gctx.done = 1; memset(&realm_params, 0, sizeof(realm_params)); maj_stat = gss_export_name(&min_stat, src_name, &bufp); INSIST(maj_stat == GSS_S_COMPLETE); CHECK(parse_name(bufp.value, bufp.length, GSS_KRB5_MECHANISM, &client)); gss_release_buffer(&min_stat, &bufp); krb5_warnx(contextp, "%s connected", client); ret = kadm5_s_init_with_password_ctx(contextp, client, NULL, KADM5_ADMIN_SERVICE, &realm_params, 0, 0, &server_handle); INSIST(ret == 0); } INSIST(gctx.ctx != GSS_C_NO_CONTEXT); CHECK(krb5_store_uint32(dreply, 0)); CHECK(store_gss_init_res(dreply, gctx.handle, maj_stat, min_stat, 1, &gout)); if (gout.value) gss_release_buffer(&min_stat, &gout); if (src_name) gss_release_name(&min_stat, &src_name); break; } case RPG_DESTROY: krb5_errx(contextp, 1, "client destroyed gss contextp"); default: krb5_errx(contextp, 1, "client sent unknown gsscode %d", (int)gcred.proc); } krb5_data_free(&gcred.handle); krb5_data_free(&chdr.cred.data); krb5_data_free(&chdr.verf.data); krb5_data_free(&headercopy); CHECK(krb5_store_uint32(reply, chdr.xid)); CHECK(krb5_store_uint32(reply, 1)); /* REPLY */ CHECK(krb5_store_uint32(reply, 0)); /* MSG_ACCEPTED */ if (!gctx.done) { krb5_data data; CHECK(krb5_store_uint32(reply, 0)); /* flavor_none */ CHECK(krb5_store_uint32(reply, 0)); /* length */ CHECK(krb5_store_uint32(reply, 0)); /* SUCCESS */ CHECK(krb5_storage_to_data(dreply, &data)); INSIST((size_t)krb5_storage_write(reply, data.data, data.length) == data.length); krb5_data_free(&data); } else { uint32_t seqnum = htonl(gctx.seq_num); krb5_data data; gin.value = &seqnum; gin.length = sizeof(seqnum); maj_stat = gss_get_mic(&min_stat, gctx.ctx, 0, &gin, &gout); INSIST(maj_stat == GSS_S_COMPLETE); data.data = gout.value; data.length = gout.length; CHECK(krb5_store_uint32(reply, FLAVOR_GSS)); CHECK(store_data_xdr(reply, data)); gss_release_buffer(&min_stat, &gout); CHECK(krb5_store_uint32(reply, 0)); /* SUCCESS */ CHECK(krb5_storage_to_data(dreply, &data)); if (gctx.inprogress) { ssize_t sret; gctx.inprogress = 0; sret = krb5_storage_write(reply, data.data, data.length); INSIST((size_t)sret == data.length); krb5_data_free(&data); } else { int conf_state; gin.value = data.data; gin.length = data.length; maj_stat = gss_wrap(&min_stat, gctx.ctx, 1, 0, &gin, &conf_state, &gout); INSIST(maj_stat == GSS_S_COMPLETE); INSIST(conf_state != 0); krb5_data_free(&data); data.data = gout.value; data.length = gout.length; store_data_xdr(reply, data); gss_release_buffer(&min_stat, &gout); } } { krb5_data data; ssize_t sret; CHECK(krb5_storage_to_data(reply, &data)); CHECK(krb5_store_uint32(sp, data.length | LAST_FRAGMENT)); sret = krb5_storage_write(sp, data.data, data.length); INSIST((size_t)sret == data.length); krb5_data_free(&data); } } } int handle_mit(krb5_context contextp, void *buf, size_t len, krb5_socket_t sock) { krb5_storage *sp; dcontext = contextp; sp = krb5_storage_from_socket(sock); INSIST(sp != NULL); process_stream(contextp, buf, len, sp); return 0; } heimdal-7.5.0/kadmin/kadmind.c0000644000175000017500000001422013026237312014266 0ustar niknik/* * Copyright (c) 1997-2004 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "kadmin_locl.h" static char *check_library = NULL; static char *check_function = NULL; static getarg_strings policy_libraries = { 0, NULL }; static char *config_file; static char sHDB[] = "HDBGET:"; static char *keytab_str = sHDB; static int help_flag; static int version_flag; static int debug_flag; static char *port_str; char *realm; static int detach_from_console = -1; int daemon_child = -1; static struct getargs args[] = { { "config-file", 'c', arg_string, &config_file, "location of config file", "file" }, { "keytab", 0, arg_string, &keytab_str, "what keytab to use", "keytab" }, { "realm", 'r', arg_string, &realm, "realm to use", "realm" }, #ifdef HAVE_DLOPEN { "check-library", 0, arg_string, &check_library, "library to load password check function from", "library" }, { "check-function", 0, arg_string, &check_function, "password check function to load", "function" }, { "policy-libraries", 0, arg_strings, &policy_libraries, "password check function to load", "function" }, #endif { "debug", 'd', arg_flag, &debug_flag, "enable debugging", NULL }, { "detach", 0 , arg_flag, &detach_from_console, "detach from console", NULL }, { "daemon-child", 0 , arg_integer, &daemon_child, "private argument, do not use", NULL }, { "ports", 'p', arg_string, &port_str, "ports to listen to", "port" }, { "help", 'h', arg_flag, &help_flag, NULL, NULL }, { "version", 'v', arg_flag, &version_flag, NULL, NULL } }; static int num_args = sizeof(args) / sizeof(args[0]); krb5_context context; static void usage(int ret) { arg_printusage (args, num_args, NULL, ""); exit (ret); } int main(int argc, char **argv) { krb5_error_code ret; char **files; int optidx = 0; int i; krb5_log_facility *logfacility; krb5_keytab keytab; krb5_socket_t sfd = rk_INVALID_SOCKET; setprogname(argv[0]); if (getarg(args, num_args, argc, argv, &optidx)) { warnx("error at argument `%s'", argv[optidx]); usage(1); } if (help_flag) usage (0); if (version_flag) { print_version(NULL); exit(0); } if (detach_from_console > 0 && daemon_child == -1) roken_detach_prep(argc, argv, "--daemon-child"); ret = krb5_init_context(&context); if (ret) errx (1, "krb5_init_context failed: %d", ret); argc -= optidx; argv += optidx; if (config_file == NULL) { int aret; aret = asprintf(&config_file, "%s/kdc.conf", hdb_db_dir(context)); if (aret == -1) errx(1, "out of memory"); } ret = krb5_prepend_config_files_default(config_file, &files); if (ret) krb5_err(context, 1, ret, "getting configuration files"); ret = krb5_set_config_files(context, files); krb5_free_config_files(files); if(ret) krb5_err(context, 1, ret, "reading configuration files"); ret = krb5_openlog(context, "kadmind", &logfacility); if (ret) krb5_err(context, 1, ret, "krb5_openlog"); ret = krb5_set_warn_dest(context, logfacility); if (ret) krb5_err(context, 1, ret, "krb5_set_warn_dest"); ret = krb5_kt_register(context, &hdb_get_kt_ops); if(ret) krb5_err(context, 1, ret, "krb5_kt_register"); ret = krb5_kt_resolve(context, keytab_str, &keytab); if(ret) krb5_err(context, 1, ret, "krb5_kt_resolve"); kadm5_setup_passwd_quality_check (context, check_library, check_function); for (i = 0; i < policy_libraries.num_strings; i++) { ret = kadm5_add_passwd_quality_verifier(context, policy_libraries.strings[i]); if (ret) krb5_err(context, 1, ret, "kadm5_add_passwd_quality_verifier"); } ret = kadm5_add_passwd_quality_verifier(context, NULL); if (ret) krb5_err(context, 1, ret, "kadm5_add_passwd_quality_verifier"); if(debug_flag) { int debug_port; if(port_str == NULL) debug_port = krb5_getportbyname (context, "kerberos-adm", "tcp", 749); else debug_port = htons(atoi(port_str)); mini_inetd(debug_port, &sfd); } else { #ifdef _WIN32 start_server(context, port_str); #else struct sockaddr_storage __ss; struct sockaddr *sa = (struct sockaddr *)&__ss; socklen_t sa_size = sizeof(__ss); /* * Check if we are running inside inetd or not, if not, start * our own server. */ if(roken_getsockname(STDIN_FILENO, sa, &sa_size) < 0 && rk_SOCK_ERRNO == ENOTSOCK) { start_server(context, port_str); } #endif /* _WIN32 */ sfd = STDIN_FILENO; } if(realm) krb5_set_default_realm(context, realm); /* XXX */ kadmind_loop(context, keytab, sfd); return 0; } heimdal-7.5.0/kadmin/kadmind.cat80000644000175000017500000000725013212450763014714 0ustar niknik KADMIND(8) BSD System Manager's Manual KADMIND(8) NNAAMMEE kkaaddmmiinndd -- server for administrative access to Kerberos database SSYYNNOOPPSSIISS kkaaddmmiinndd [--cc _f_i_l_e | ----ccoonnffiigg--ffiillee==_f_i_l_e] [--kk _f_i_l_e | ----kkeeyy--ffiillee==_f_i_l_e] [----kkeeyyttaabb==_k_e_y_t_a_b] [--rr _r_e_a_l_m | ----rreeaallmm==_r_e_a_l_m] [--dd | ----ddeebbuugg] [--pp _p_o_r_t | ----ppoorrttss==_p_o_r_t] DDEESSCCRRIIPPTTIIOONN kkaaddmmiinndd listens for requests for changes to the Kerberos database and performs these, subject to permissions. When starting, if stdin is a socket it assumes that it has been started by inetd(8), otherwise it behaves as a daemon, forking processes for each new connection. The ----ddeebbuugg option causes kkaaddmmiinndd to accept exactly one connection, which is useful for debugging. The kpasswdd(8) daemon is responsible for the Kerberos 5 password chang- ing protocol (used by kpasswd(1)). This daemon should only be run on the master server, and not on any slaves. Principals are always allowed to change their own password and list their own principal. Apart from that, doing any operation requires permission explicitly added in the ACL file _/_v_a_r_/_h_e_i_m_d_a_l_/_k_a_d_m_i_n_d_._a_c_l. The format of this file is: _p_r_i_n_c_i_p_a_l _r_i_g_h_t_s [_p_r_i_n_c_i_p_a_l_-_p_a_t_t_e_r_n] Where rights is any (comma separated) combination of: ++oo change-password or cpw ++oo list ++oo delete ++oo modify ++oo add ++oo get ++oo get-keys ++oo all And the optional _p_r_i_n_c_i_p_a_l_-_p_a_t_t_e_r_n restricts the rights to operations on principals that match the glob-style pattern. Supported options: --cc _f_i_l_e, ----ccoonnffiigg--ffiillee==_f_i_l_e location of config file --kk _f_i_l_e, ----kkeeyy--ffiillee==_f_i_l_e location of master key file ----kkeeyyttaabb==_k_e_y_t_a_b what keytab to use --rr _r_e_a_l_m, ----rreeaallmm==_r_e_a_l_m realm to use --dd, ----ddeebbuugg enable debugging --pp _p_o_r_t, ----ppoorrttss==_p_o_r_t ports to listen to. By default, if run as a daemon, it listens to port 749, but you can add any number of ports with this option. The port string is a whitespace separated list of port specifica- tions, with the special string ``+'' representing the default port. FFIILLEESS _/_v_a_r_/_h_e_i_m_d_a_l_/_k_a_d_m_i_n_d_._a_c_l EEXXAAMMPPLLEESS This will cause kkaaddmmiinndd to listen to port 4711 in addition to any com- piled in defaults: kkaaddmmiinndd ----ppoorrttss="+ 4711" & This acl file will grant Joe all rights, and allow Mallory to view and add host principals, as well as extract host principal keys (e.g., into keytabs). joe/admin@EXAMPLE.COM all mallory/admin@EXAMPLE.COM add,get-keys host/*@EXAMPLE.COM SSEEEE AALLSSOO kpasswd(1), kadmin(1), kdc(8), kpasswdd(8) HEIMDAL December 8, 2004 HEIMDAL heimdal-7.5.0/kadmin/add-random-users.c0000644000175000017500000001132613026237312016030 0ustar niknik/* * Copyright (c) 2000 - 2001 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "kadmin_locl.h" #define WORDS_FILENAME "/usr/share/dict/words" #define NUSERS 1000 #define WORDBUF_SIZE 65535 static unsigned read_words (const char *filename, char ***ret_w) { unsigned n, alloc; FILE *f; char buf[256]; char **w = NULL; char *wbuf = NULL, *wptr = NULL, *wend = NULL; f = fopen (filename, "r"); if (f == NULL) err (1, "cannot open %s", filename); alloc = n = 0; while (fgets (buf, sizeof(buf), f) != NULL) { size_t len; buf[strcspn(buf, "\r\n")] = '\0'; if (n >= alloc) { alloc = max(alloc + 16, alloc * 2); w = erealloc (w, alloc * sizeof(char **)); } len = strlen(buf); if (wptr + len + 1 >= wend) { wptr = wbuf = emalloc (WORDBUF_SIZE); wend = wbuf + WORDBUF_SIZE; } memmove (wptr, buf, len + 1); w[n++] = wptr; wptr += len + 1; } if (n == 0) errx(1, "%s is an empty file, no words to try", filename); *ret_w = w; fclose(f); return n; } static void add_user (krb5_context ctx, void *hndl, unsigned nwords, char **words) { kadm5_principal_ent_rec princ; char name[64]; int r1, r2; krb5_error_code ret; int mask; r1 = rand(); r2 = rand(); snprintf (name, sizeof(name), "%s%d", words[r1 % nwords], r2 % 1000); mask = KADM5_PRINCIPAL; memset(&princ, 0, sizeof(princ)); ret = krb5_parse_name(ctx, name, &princ.principal); if (ret) krb5_err(ctx, 1, ret, "krb5_parse_name"); ret = kadm5_create_principal (hndl, &princ, mask, name); if (ret) krb5_err (ctx, 1, ret, "kadm5_create_principal"); kadm5_free_principal_ent(hndl, &princ); printf ("%s\n", name); } static void add_users (const char *filename, unsigned n) { krb5_error_code ret; int i; void *hndl; krb5_context ctx; unsigned nwords; char **words; ret = krb5_init_context(&ctx); if (ret) errx (1, "krb5_init_context failed: %d", ret); ret = kadm5_s_init_with_password_ctx(ctx, KADM5_ADMIN_SERVICE, NULL, KADM5_ADMIN_SERVICE, NULL, 0, 0, &hndl); if(ret) krb5_err(ctx, 1, ret, "kadm5_init_with_password"); nwords = read_words (filename, &words); for (i = 0; i < n; ++i) add_user (ctx, hndl, nwords, words); kadm5_destroy(hndl); krb5_free_context(ctx); free(words); } static int version_flag = 0; static int help_flag = 0; static struct getargs args[] = { { "version", 0, arg_flag, &version_flag, NULL, NULL }, { "help", 0, arg_flag, &help_flag, NULL, NULL } }; static void usage (int ret) { arg_printusage (args, sizeof(args)/sizeof(*args), NULL, "[filename [n]]"); exit (ret); } int main(int argc, char **argv) { int optidx = 0; int n = NUSERS; const char *filename = WORDS_FILENAME; setprogname(argv[0]); if(getarg(args, sizeof(args) / sizeof(args[0]), argc, argv, &optidx)) usage(1); if (help_flag) usage (0); if (version_flag) { print_version(NULL); return 0; } srand (0); argc -= optidx; argv += optidx; if (argc > 0) { if (argc > 1) n = atoi(argv[1]); filename = argv[0]; } add_users (filename, n); return 0; } heimdal-7.5.0/windows/0000755000175000017500000000000013214604041012737 5ustar niknikheimdal-7.5.0/windows/version.rc0000644000175000017500000001063613026237312014764 0ustar niknik/*********************************************************************** * Copyright (c) 2010, Secure Endpoints Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * - Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. * **********************************************************************/ /* * This version script is not meant to be used as-is. It requires the * following parameters that must be supplied using preprocessor * macros: * * RC_FILE_TYPE (Set to either VFT_DLL or VFT_APP) * RC_FILE_DESC_0409 (File description (English)) * RC_FILE_ORIG_0409 (Original file name (English)) * * The following macros are optional: * * RC_FILE_SUBTYPE (File subtype. See MSDN.) * RC_FILEVER_C (Comma separated file version, if different from * product version) * RC_FILE_COMMENT_0409 (File comment (English)) */ #include #include LANGUAGE LANG_ENGLISH, SUBLANG_ENGLISH_US #pragma code_page(1252) #ifdef VER_PRIVATE #define P_PRIVATE VS_FF_PRIVATEBUILD #else #define P_PRIVATE 0 #endif #ifdef VER_SPECIAL #define P_SPECIAL VS_FF_SPECIALBUILD #else #define P_SPECIAL 0 #endif #ifdef VER_PRERELEASE #define P_PRE VS_FF_PRERELEASE #else #define P_PRE 0 #endif #ifdef VER_DEBUG #define P_DEBUG VS_FF_DEBUG #else #define P_DEBUG 0 #endif /* If some per-file values aren't specified, we use the application values as a substitute */ #ifndef RC_FILEVER_C #define RC_FILEVER_C RC_PRODVER_C #define RC_FILE_VER_0409 RC_PRODUCT_VER_0409 #endif #ifndef RC_FILE_INTERNAL_0409 #define RC_FILE_INTERNAL_0409 RC_FILE_ORIG_0409 #endif #ifndef RC_FILE_PRODUCT_NAME_0409 #define RC_FILE_PRODUCT_NAME_0409 RC_PRODUCT_NAME_0409 #endif #ifndef RC_FILE_PRODUCT_VER_0409 #define RC_FILE_PRODUCT_VER_0409 RC_PRODUCT_VER_0409 #endif #ifndef RC_FILE_COMPANY_0409 #define RC_FILE_COMPANY_0409 RC_COMPANY_0409 #endif #ifndef RC_FILE_COPYRIGHT_0409 #define RC_FILE_COPYRIGHT_0409 RC_COPYRIGHT_0409 #endif 1 VERSIONINFO FILEVERSION RC_FILEVER_C PRODUCTVERSION RC_PRODVER_C FILEFLAGSMASK (VS_FF_DEBUG|VS_FF_PRERELEASE|VS_FF_PRIVATEBUILD|VS_FF_SPECIALBUILD) FILEFLAGS (P_DEBUG|P_PRE|P_PRIVATE|P_SPECIAL) FILEOS VOS_NT FILETYPE RC_FILE_TYPE #ifdef RC_FILE_SUBTYPE FILESUBTYPE RC_FILE_SUBTYPE #endif BEGIN BLOCK "StringFileInfo" BEGIN BLOCK "040904E4" BEGIN VALUE "ProductName", RC_FILE_PRODUCT_NAME_0409 VALUE "ProductVersion", RC_FILE_PRODUCT_VER_0409 VALUE "CompanyName", RC_FILE_COMPANY_0409 VALUE "LegalCopyright", RC_FILE_COPYRIGHT_0409 #ifdef RC_FILE_TRADEMARK_0409 VALUE "LegalTrademark", RC_FILE_TRADEMARK_0409 #endif #ifdef RC_FILE_COMMENT_0409 VALUE "Comments", RC_FILE_COMMENT_0409 #endif VALUE "FileDescription", RC_FILE_DESC_0409 VALUE "FileVersion", RC_FILE_VER_0409 VALUE "InternalName", RC_FILE_INTERNAL_0409 VALUE "OriginalFilename", RC_FILE_ORIG_0409 #ifdef VER_PRIVATE VALUE "PrivateBuild", VER_PRIVATE #endif #ifdef VER_SPECIAL VALUE "SpecialBuild", VER_SPECIAL #endif END END BLOCK "VarFileInfo" BEGIN VALUE "Translation", 0x0409 /* US English */, 1252 /* Multilingual */ END END heimdal-7.5.0/windows/NTMakefile.w320000644000175000017500000004015213062057075015267 0ustar niknik######################################################################## # # Copyright (c) 2009-2011, Secure Endpoints Inc. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # - Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # # - Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in # the documentation and/or other materials provided with the # distribution. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS # FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE # COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, # BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN # ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. # all:: clean:: test:: prep:: all:: prep !include !ifdef NODEBUG BUILD=rel !else BUILD=dbg !endif !if exist($(MAKEDIR)\windows\NTMakefile.w32) SRC=$(MAKEDIR) !elseif exist($(MAKEDIR)\..\windows\NTMakefile.w32) SRC=$(MAKEDIR)\.. !elseif exist($(MAKEDIR)\..\..\windows\NTMakefile.w32) SRC=$(MAKEDIR)\..\.. !elseif exist($(MAKEDIR)\..\..\..\windows\NTMakefile.w32) SRC=$(MAKEDIR)\..\..\.. !elseif exist($(MAKEDIR)\..\..\..\..\windows\NTMakefile.w32) SRC=$(MAKEDIR)\..\..\..\.. !else ! error Cant determine source directory !endif ! if "$(CPU)"=="i386" || "$(CPU)"=="x86" MCPU=x86 ! elseif "$(CPU)"=="AMD64" MCPU=amd64 ! else ! error Unknown CPU ! endif !include "NTMakefile.config" #---------------------------------------------------------------- # Directory macros DESTDIR =$(SRC)\out\dest_$(CPU) OBJDIR =$(SRC)\out\obj_$(CPU) INCDIR =$(DESTDIR)\inc LIBDIR =$(DESTDIR)\lib BINDIR =$(DESTDIR)\bin PLUGINDIR =$(BINDIR) DOCDIR =$(DESTDIR)\doc SBINDIR =$(BINDIR) LIBEXECDIR =$(BINDIR) ASMDIR =$(BINDIR) INSTDIR =$(DESTDIR)\install SDKDIR =$(SRC)\out\sdk SDKINCDIR =$(SDKDIR)\inc SDKLIBDIR =$(SDKDIR)\lib\$(CPU) SDKSRCDIR =$(SDKDIR)\src SDKREDISTDIR =$(SDKDIR)\redist\$(CPU) !ifdef RELDIR SRCDIR =$(SRC)\$(RELDIR) OBJ =$(OBJDIR)\$(RELDIR) !else OBJ =$(OBJDIR) !endif # For tests: PATH=$(PATH);$(BINDIR) #---------------------------------------------------------------- # Command macros RMAKE=nmake /nologo /f NTMakefile RECURSE=1 MKDIR=md CP=copy /Y LINK=link LM=lib RM=del /q ECHO=echo RC=rc #---------------------------------------------------------------- # Program macros AWK_CMD=gawk.exe YACC_CMD=bison.exe LEX_CMD=flex.exe PYTHON=python.exe PERL=perl.exe CMP=cmp.exe MAKECAT=makecat.exe HHC=hhc.exe MAKEINFO=makeinfo.exe SED=sed.exe CANDLE_CMD=candle.exe LIGHT_CMD=light.exe # Only used for tests SH=sh.exe # Commands AWK=$(AWK_CMD) YACC=$(YACC_CMD) -y LEX=$(LEX_CMD) CANDLE=$(CANDLE_CMD) -nologo LIGHT=$(LIGHT_CMD) -nologo #---------------------------------------------------------------- # External dependencies # For pthread support to be enabled, both PTHREAD_INC and PTHREAD_LIB # should be defined. PTHREAD_INC should be the include directory # where pthread.h is to be found (i.e. $(PTHREAD_INC)\pthread.h should # exist), and PTHREAD_LIB is the full path to the pthread import # library. # # Note that both paths should not contain any whitespace. !ifdef PTHREAD_INC pthreadinc= -I$(PTHREAD_INC) !endif #---------------------------------------------------------------- # Build options cincdirs=$(cincdirs) -I$(INCDIR) -I$(INCDIR)\krb5 $(pthreadinc) cdefines=$(cdefines) -DHAVE_CONFIG_H # Windows CNG provider cdefines=$(cdefines) -DHCRYPTO_DEF_PROVIDER=w32crypto cdebug=$(cdebug) /Zi ldebug=$(ldebug) /DEBUG localcflags=$(localcflags) /Oy- # Disable warnings: # # C4996: 'function' was declared deprecated # C4127: Conditional expression is constant # C4244: Conversion from 'type1' to 'type2', possible loss of data # C4100: 'identifier': unreferenced formal parameter # C4706: Assignment within conditional expression # C4214: Nonstandard extension used # C4267: '': Conversion from 'type1' to 'type2', possible loss of data # C4018: '': Signed/unsigned mismatch # C4204: Nonstandard extension used: non-constant aggregate initializer # C4221: Nonstandard extension used: 'v1': cannot be initialized using address of automatic variable 'v2' # C4295: '': Array is too small to include a terminating null character # C4146: Unary minus operator applied to unsigned type, result still unsigned. # cwarn=$(cwarn) -D_CRT_SECURE_NO_WARNINGS -wd4996 -wd4127 -wd4244 -wd4100 -wd4706 cwarn=$(cwarn) -wd4214 -wd4267 -wd4018 -wd4389 -wd4204 -wd4221 -wd4295 -wd4146 !if "$(CPU)"=="i386" libmach=/machine:X86 !elseif "$(CPU)"=="AMD64" libmach=/machine:X64 !else ! error Unknown CPU value !endif !ifdef NO_MP MPOPT= !else MPOPT=/MP !endif !ifndef STATICRUNTIME C2OBJ_C = $(CC) $(cdebug) $(cflags) $(cvarsdll) $(AUXCFLAGS) $(intcflags) $(cdefines) $(cincdirs) $(cwarn) EXECONLINK_C = $(LINK) $(ldebug) $(conlflags) $(conlibsdll) $(libmach) EXEGUILINK_C = $(LINK) $(ldebug) $(guilflags) $(guilibsdll) $(libmach) DLLCONLINK_C = $(LINK) $(ldebug) $(dlllflags) $(conlibsdll) $(libmach) DLLGUILINK_C = $(LINK) $(ldebug) $(dlllflags) $(guilibsdll) $(libmach) !else # STATICRUNTIME C2OBJ_C = $(CC) $(cdebug) $(cflags) $(cvarsmt) $(AUXCFLAGS) $(intcflags) $(cdefines) $(cincdirs) $(cwarn) EXECONLINK_C = $(LINK) $(ldebug) $(conlflags) $(conlibsmt) $(libmach) EXEGUILINK_C = $(LINK) $(ldebug) $(guilflags) $(guilibsmt) $(libmach) DLLCONLINK_C = $(LINK) $(ldebug) $(dlllflags) $(conlibsmt) $(libmach) DLLGUILINK_C = $(LINK) $(ldebug) $(dlllflags) $(guilibsmt) $(libmach) !endif LIBGUI_C = $(LM) /nologo $(libmach) /SUBSYSTEM:WINDOWS LIBCON_C = $(LM) /nologo $(libmach) /SUBSYSTEM:CONSOLE C2OBJ = $(C2OBJ_C) -Fo$@ -Fd$(@D)\ $** C2OBJ_NP = $(C2OBJ_C) $(MPOPT) $< C2OBJ_P = $(C2OBJ_NP) -Fo$(OBJ)\ -Fd$(OBJ)\ # EXECONLINK = $(EXECONLINK_C) -OUT:$@ $** EXEGUILINK = $(EXEGUILINK_C) -OUT:$@ $** DLLCONLINK = $(DLLCONLINK_C) -OUT:$@ $** DLLGUILINK = $(DLLGUILINK_C) -OUT:$@ $** LIBGUI = $(LIBGUI_C) /OUT:$@ $** LIBCON = $(LIBCON_C) /OUT:$@ $** # Preprocess files to stdout using config.h CPREPROCESSOUT = $(CC) /EP /FI$(INCDIR)\config.h /TC /DCPP_ONLY=1 # Resources RC2RES_C = $(RC) $(cincdirs) $(AUXRCFLAGS) RC2RES = $(RC2RES_C) -fo $@ $** #---------------------------------------------------------------------- # If this is the initial invocation, we check if all the build # utilities are there. Also show the commands macros. !ifndef RECURSE REQUIRED_TOOLS= \ "$(AWK_CMD)" "$(YACC_CMD)" "$(LEX_CMD)" "$(PYTHON)" "$(PERL)" \ "$(CMP)" "$(SED)" "$(MAKECAT)" "$(MAKEINFO)" "$(HHC)" !ifdef BUILD_INSTALLERS REQUIRED_TOOLS=$(REQUIRED_TOOLS) "$(CANDLE_CMD)" "$(LIGHT_CMD)" !endif OPTIONAL_TOOLS="$(SH)" check-utils: @for %%g in ( $(REQUIRED_TOOLS) ) do @( \ for /f %%f in ( "%%g" ) do @( \ if exist %%f @( \ echo Found %%f \ ) else if "%%~$$PATH:f"=="" @( \ echo Could not find %%f in PATH && \ exit /b 1 \ ) else @( \ echo Found %%~$$PATH:f \ ) \ ) \ ) @for %%g in ( $(OPTIONAL_TOOLS) ) do @( \ for /f %%f in ( "%%g" ) do @( \ if exist %%f @( \ echo Found %%f \ ) else if "%%~$$PATH:f"=="" @( \ echo Could not find %%f in PATH && \ echo Optional targets may fail. \ ) else @( \ echo Found %%~$$PATH:f \ ) \ ) \ ) prep:: check-utils show-cmds: @$(ECHO) C2OBJ=$(C2OBJ_C:\=\\) @$(ECHO). @$(ECHO) EXECONLINK=$(EXECONLINK_C) @$(ECHO). @$(ECHO) EXEGUILINK=$(EXEGUILINK_C) @$(ECHO). @$(ECHO) DLLCONLINK=$(DLLCONLINK_C) @$(ECHO). @$(ECHO) DLLGUILINK=$(DLLGUILINK_C) @$(ECHO). @$(ECHO) LIBGUI=$(LIBGUI_C) @$(ECHO). @$(ECHO) LIBCON=$(LIBCON_C) prep:: show-cmds !endif # RECURSE {}.c{$(OBJ)}.obj:: $(C2OBJ_C) /Fd$(OBJ)\ /Fo$(OBJ)\ $(localcflags) $(MPOPT) @<< $< << {$(OBJ)}.c{$(OBJ)}.obj:: $(C2OBJ_C) /Fd$(OBJ)\ /Fo$(OBJ)\ $(extcflags) $(MPOPT) @<< $< << {}.cpp{$(OBJ)}.obj:: $(C2OBJ_C) /Fd$(OBJ)\ /Fo$(OBJ)\ $(localcflags) $(MPOPT) @<< $< << {$(OBJ)}.cpp{$(OBJ)}.obj:: $(C2OBJ_C) /Fd$(OBJ)\ /Fo$(OBJ)\ $(extcflags) $(MPOPT) @<< $< << {}.hin{$(INCDIR)}.h: $(CP) $< $@ {}.h{$(INCDIR)}.h: $(CP) $< $@ {}.h{$(INCDIR)\krb5}.h: $(CP) $< $@ {$(OBJ)}.h{$(INCDIR)}.h: $(CP) $< $@ {$(OBJ)}.x{$(OBJ)}.c: $(CP) $< $@ {$(OBJ)}.hx{$(INCDIR)}.h: $(CP) $< $@ {$(OBJ)}.hx{$(OBJ)}.h: $(CP) $< $@ {}.rc{$(OBJ)}.res: $(RC2RES) #---------------------------------------------------------------------- # Announce the build directory !ifdef RELDIR all:: announce all-tools:: announce-tools test:: announce clean:: announce announce: @echo. @echo --------- Entering $(RELDIR:\= ): announce-tools: @echo. @echo --------- Entering $(RELDIR:\= ) tools: !endif #---------------------------------------------------------------------- # Create any required directories if they don't already exist prep:: mkdirs mkdirs: ! if !exist("$(OBJ)") -$(MKDIR) "$(OBJ)" ! endif ! if !exist("$(DESTDIR)") -$(MKDIR) "$(DESTDIR)" ! endif ! if !exist("$(LIBDIR)") -$(MKDIR) "$(LIBDIR)" ! endif ! if !exist("$(BINDIR)") -$(MKDIR) "$(BINDIR)" ! endif ! if !exist("$(PLUGINDIR)") -$(MKDIR) "$(PLUGINDIR)" ! endif ! if !exist("$(INCDIR)") -$(MKDIR) "$(INCDIR)" ! endif ! if !exist("$(DOCDIR)") -$(MKDIR) "$(DOCDIR)" ! endif ! if !exist("$(INCDIR)\gssapi") -$(MKDIR) "$(INCDIR)\gssapi" ! endif ! if !exist("$(INCDIR)\hcrypto") -$(MKDIR) "$(INCDIR)\hcrypto" ! endif ! if !exist("$(INCDIR)\kadm5") -$(MKDIR) "$(INCDIR)\kadm5" ! endif ! if !exist("$(INCDIR)\krb5") -$(MKDIR) "$(INCDIR)\krb5" ! endif #---------------------------------------------------------------------- # If SUBDIRS is defined, we should recurse into the subdirectories !ifdef SUBDIRS subdirs: @for %%f in ( $(SUBDIRS) ) do @ (pushd %%f && $(RMAKE) && popd) || exit /b 1 clean-subdirs: @for %%f in ( $(SUBDIRS) ) do @ (pushd %%f && $(RMAKE) clean && popd) || exit /b 1 test-subdirs: @for %%f in ( $(SUBDIRS) ) do @ (pushd %%f && $(RMAKE) test && popd) || exit /b 1 all:: subdirs clean:: clean-subdirs test:: test-subdirs !endif #---------------------------------------------------------------------- # Clean targets !ifdef CLEANFILES clean:: -$(RM) $(CLEANFILES) !endif !ifdef RELDIR clean:: -$(RM) $(OBJ)\*.* !endif .SUFFIXES: .c .cpp .hin .h .x .hx #---------------------------------------------------------------------- # Manifest handling # # Starting with Visual Studio 8, the C compiler and the linker # generate manifests so that the applications will link with the # correct side-by-side DLLs at run-time. These are required for # correct operation under Windows XP and later. We also have custom # manifests which need to be merged with the manifests that VS # creates. # # The syntax for invoking the _VC_MANIFEST_EMBED_FOO macro is: # $(_VC_MANIFEST_EMBED_???) # MT=mt.exe -nologo _VC_MANIFEST_EMBED_EXE= \ ( if exist $@.manifest $(MT) -outputresource:$@;1 -manifest $@.manifest $(APPMANIFEST) ) _VC_MANIFEST_EMBED_EXE_NOHEIM= \ ( if exist $@.manifest $(MT) -outputresource:$@;1 -manifest $@.manifest ) _VC_MANIFEST_EMBED_DLL= \ ( if exist $@.manifest $(MT) -outputresource:$@;2 -manifest $@.manifest ) _MERGE_MANIFEST_DLL= \ ( $(MT) -inputresource:$@;2 -manifest $(APPMANIFEST) -outputresource:$@;2 ) _INSERT_APPMANIFEST_DLL= \ ( $(MT) -manifest $(APPMANIFEST) -outputresource:$@;2 ) # Note that if you are merging manifests, then the VS generated # manifest should be cleaned up after calling _VC_MANIFEST_EMBED_???. # This ensures that even if the DLL or EXE is executed in-place, the # embedded manifest will be used. Otherwise the $@.manifest file will # be used. _VC_MANIFEST_CLEAN= \ ( if exist $@.manifest $(RM) $@.manifest ) # End of manifest handling #---------------------------------------------------------------------- # Code and assembly signing # # # SIGNTOOL is fullpath to signtool.exe from Windows v8.1 or later SDK # (earlier versions do not support SHA-2 signatures) # # SIGNTOOL_C is any set of options required for certificate/private # key selection for code signging. # # SIGNTOOL_O is any set of additional options to signtool.exe # # SIGNTOOL_T is the timestamp option !ifdef CODESIGN _CODESIGN=( $(CODESIGN) $@ ) _CODESIGN_SHA256=( $(CODESIGN_SHA256) $@ ) !else !ifndef SIGNTOOL SIGNTOOL=signtool.exe !endif !ifdef SIGNTOOL_C !ifndef SIGNTOOL_T SIGNTOOL_T=http://timestamp.verisign.com/scripts/timstamp.dll !endif !ifndef SIGNTOOL_T_SHA256 SIGNTOOL_T_SHA256=http://sha256timestamp.ws.symantec.com/sha256/timestamp !endif _CODESIGN=( $(SIGNTOOL) sign /fd sha1 $(SIGNTOOL_O) /t $(SIGNTOOL_T) $(SIGNTOOL_C) /v $@ ) _CODESIGN_SHA256=( $(SIGNTOOL) sign /as /fd sha256 $(SIGNTOOL_O) /tr $(SIGNTOOL_T_SHA256) $(SIGNTOOL_C) /v $@ ) !else _CODESIGN=( echo Skipping code sign ) _CODESIGN_SHA256=( echo Skipping sha256 code sign ) !endif !endif #---------------------------------------------------------------------- # Symbol Store Support # # SYMSTORE_EXE is full path to symstore.exe # # SYMSTORE_ROOT is full path to root directory of symbol store # # SYMSTORE_COMMENT is optional comment to include in symbol store catalog entry # !IF DEFINED(SYMSTORE_EXE) && DEFINED(SYMSTORE_ROOT) !IF "$(SYMSTORE_COMMENT)" != "" SYMSTORE_COMMENT = |$(SYMSTORE_COMMENT) !ENDIF SYMSTORE_IMPORT= \ $(SYMSTORE_EXE) add /s $(SYMSTORE_ROOT) /t "Heimdal" /v "$(BUILD)-$(CPU)-$(VER_PACKAGE_VERSION)" /c "$(@F)$(SYMSTORE_COMMENT)" /f $*.* !ELSE SYMSTORE_IMPORT=@echo No symbol store !ENDIF #---------------------------------------------------------------------- # Convenience macros for preparing EXEs and DLLs. These are multiline # macros that deal with manifests and code signing. Unless we need to # include custom manifests, these are what we should be using to # prepare binaries. EXEPREP=\ ( $(_VC_MANIFEST_EMBED_EXE) && $(_VC_MANIFEST_CLEAN) && $(SYMSTORE_IMPORT) && $(_CODESIGN) && $(_CODESIGN_SHA256) ) || ( $(RM) $@ && exit /b 1 ) EXEPREP_NOHEIM=\ ( $(_VC_MANIFEST_EMBED_EXE_NOHEIM) && $(_VC_MANIFEST_CLEAN) && $(SYMSTORE_IMPORT) && $(_CODESIGN) && $(_CODESIGN_SHA256) ) || ( $(RM) $@ && exit /b 1 ) EXEPREP_NODIST=\ ( $(_VC_MANIFEST_EMBED_EXE_NOHEIM) && $(_VC_MANIFEST_CLEAN) && $(SYMSTORE_IMPORT) ) || ( $(RM) $@ && exit /b 1 ) DLLPREP=\ ( $(_VC_MANIFEST_EMBED_DLL) && $(_VC_MANIFEST_CLEAN) && $(SYMSTORE_IMPORT) && $(_CODESIGN) && $(_CODESIGN_SHA256) ) || ( $(RM) $@ && exit /b 1 ) DLLPREP_NODIST=\ ( $(_VC_MANIFEST_EMBED_DLL) && $(_VC_MANIFEST_CLEAN) && $(SYMSTORE_IMPORT) ) || ( $(RM) $@ && exit /b 1 ) DLLPREP_MERGE=\ ( ( $(_MERGE_MANIFEST_DLL) || $(_INSERT_APPMANIFEST_DLL) && $(SYMSTORE_IMPORT) ) && $(_CODESIGN) && $(_CODESIGN_SHA256) ) || ( $(RM) $@ && exit /b 1 ) #---------------------------------------------------------------------- # Convenience macros for import libraries and assemblies # LIBASN1 =$(LIBDIR)\libasn1.lib LIBCOMERR =$(LIBDIR)\libcom_err.lib LIBEDITLINE =$(LIBDIR)\libeditline.lib LIBGSSAPI =$(LIBDIR)\libgssapi.lib LIBHCRYPTO =$(LIBDIR)\libhcrypto.lib LIBHDB =$(LIBDIR)\libhdb.lib LIBHEIMBASE =$(LIBDIR)\libheimbase.lib LIBHEIMDAL =$(LIBDIR)\heimdal.lib LIBHEIMIPCC =$(LIBDIR)\libheim-ipcc.lib LIBHEIMIPCS =$(LIBDIR)\libheim-ipcs.lib LIBHEIMNTLM =$(LIBDIR)\libheimntlm.lib LIBHX509 =$(LIBDIR)\libhx509.lib LIBKADM5CLNT=$(LIBDIR)\libkadm5clnt.lib LIBKADM5SRV =$(LIBDIR)\libkadm5srv.lib LIBKDC =$(LIBDIR)\libkdc.lib LIBLTM =$(LIBDIR)\libltm.lib LIBKRB5 =$(LIBDIR)\libkrb5.lib LIBRFC3961 =$(LIBDIR)\librfc3961.lib LIBROKEN =$(LIBDIR)\libroken.lib LIBSL =$(LIBDIR)\libsl.lib LIBSQLITE =$(LIBDIR)\libsqlite.lib LIBVERS =$(LIBDIR)\libvers.lib LIBWIND =$(LIBDIR)\libwind.lib !ifdef VER_DEBUG ASM_DBG=.Debug !endif !ifdef VER_PRERELEASE ASM_PRE=.Pre !endif !ifdef VER_PRIVATE ASM_PVT=.Private !endif !ifdef VER_SPECIAL ASM_SPC=.Special !endif ASMKRBNAME =Heimdal.Kerberos$(ASM_SPC)$(ASM_PVT)$(ASM_PRE)$(ASM_DBG) APPMANIFEST =$(INCDIR)\Heimdal.Application.$(MCPU).manifest heimdal-7.5.0/windows/README.md0000644000175000017500000001345013026237312014225 0ustar niknikBuilding Heimdal for Windows =================== 1. Introduction --------------- Heimdal can be built and run on Windows XP or later. Older OSs may work, but have not been tested. 2. Prerequisites ---------------- * __Microsoft Visual C++ Compiler__: Heimdal has been tested with Microsoft Visual C/C++ compiler version 15.x. This corresponds to Microsoft Visual Studio version 2008. The compiler and tools that are included with Microsoft Windows SDK versions 6.1 and later can also be used for building Heimdal. If you have a recent Windows SDK, then you already have a compatible compiler. * __Microsoft Windows SDK__: Heimdal has been tested with Microsoft Windows SDK version 6.1 and 7.0. * __Microsoft HTML Help Compiler__: Needed for building documentation. * __Perl__: A recent version of Perl. Tested with ActiveState ActivePerl. * __Python__: Tested with Python 2.5 and 2.6. * __WiX__: The Windows [Installer XML toolkit (WiX)][1] Version 3.x is used to build the installers. * __Cygwin__: The Heimdal build system requires a number of additional tools: `awk`, `yacc`, `lex`, `cmp`, `sed`, `makeinfo`, `sh` (Required for running tests). These can be found in the Cygwin distribution. MinGW or GnuWin32 may also be used instead of Cygwin. However, a recent build of `makeinfo` is required for building the documentation. Cygwin makeinfo 4.7 is known to work. * __Certificate for code-signing__: The Heimdal build produces a number of Assemblies that should be signed if they are to be installed via Windows Installer. In addition, all executable binaries produced by the build including installers can be signed and timestamped if a code-signing certificate is available. As of 1 January 2016 Windows 7 and above require the use of sha256 signatures. The signtool.exe provided with Windows SDK 8.1 or later must be used. [1]: http://wix.sourceforge.net/ 3. Setting up the build environment ----------------------------------- * Start with a Windows SDK or Visual Studio build environment. The target platform, OS and build type (debug / release) is determined by the build environment. E.g.: If you are using the Windows SDK, you can use the `SetEnv.Cmd` script to set up a build environment targetting 64-bit Windows XP or later with: SetEnv.Cmd /xp /x64 /Debug The build will produce debug binaries. If you specify SetEnv.Cmd /xp /x64 /Release the build will produce release binaries. * Add any directories to `PATH` as necessary for tools required by the build to be found. The build scripts will check for build tools at the start of the build and will indicate which ones are missing. In general, adding Perl, Python, WiX, HTML Help Compiler and Cygwin binary directories to the path should be sufficient. * Set up environment variables for code signing. This can be done in one of two ways. By specifying options for `signtool` or by specifying the code-signing command directly. To use `signtool`, define `SIGNTOOL_C` and optionally, `SIGNTOOL_O` and `SIGNTOOL_T`. - `SIGNTOOL_C`: Certificate selection and private key selection options for `signtool`. E.g.: set SIGNTOOL_C=/f c:\mycerts\codesign.pfx set SIGNTOOL_C=/n "Certificate Subject Name" /a - `SIGNTOOL_O`: Signing parameter options for `signtool`. Optional. E.g.: set SIGNTOOL_O=/du http://example.com/myheimdal - `SIGNTOOL_T`: SHA1 Timestamp URL for `signtool`. If not specified, defaults to `http://timestamp.verisign.com/scripts/timstamp.dll`. - `SIGNTOOL_T_SHA256`: SHA256 Timestamp URL for `signtool`. If not specified, defaults to `http://timestamp.geotrust.com/tsa`. - `CODESIGN`: SHA1 Code signer command. This environment variable, if defined, overrides the `SIGNTOOL_*` variables. It should be defined to be a command that takes one parameter: the binary to be signed. - `CODESIGN_SHA256`: SHA256 Code signer command. This environment variable, if defined, applies a second SHA256 signature to the parameter. It should be defined to be a command that takes one parameter: the binary to be signed. E.g.: set CODESIGN=c:\scripts\mycodesigner.cmd set CODESIGN_SHA256=c:\scripts\mycodesigner256.cmd * Define the code sign public key token. This is contained in the environment variable `CODESIGN_PKT` and is needed to build the Heimdal assemblies. If you are not using a code-sign certificate, set this to `0000000000000000`. You can use the `pktextract` tool to determine the public key token corresponding to your code signing certificate as follows (assuming your code signing certificate is in `c:\mycerts\codesign.cer`: pktextract c:\mycerts\codesign.cer The above command will output the certificate name, key size and the public key token. Set the `CODESIGN_PKT` variable to the `publicKeyToken` value (excluding quotes). E.g.: set CODESIGN_PKT=abcdef0123456789 4. Running the build -------------------- Change the current directory to the root of the Heimdal source tree and run: nmake /f NTMakefile This should build the binaries, assemblies and the installers. The build can also be invoked from any subdirectory that contains an `NTMakefile` using the same command. Keep in mind that there are inter-dependencies between directories and therefore it is recommended that a full build be invoked from the root of the source tree. Tests can be invoked, after a full build, by executing: nmake /f NTMakefile test The build tree can be cleaned with: nmake /f NTMakefile clean It is recommended that both AMD64 and X86 builds take place on the same machine. This permits a multi-platform installer package to be built. First build for X86 and then build AMD64 nmake /f NTMakefile MULTIPLATFORM_INSTALLER=1 The build must be executed under cmd.exe. heimdal-7.5.0/windows/NTMakefile.config0000644000175000017500000000462713062055136016124 0ustar niknik!if exist (..\..\..\thirdparty\NTMakefile.version) ! include <..\..\..\thirdparty\NTMakefile.version> !elseif exist (..\..\thirdparty\NTMakefile.version) ! include <..\..\thirdparty\NTMakefile.version> !elseif exist (..\thirdparty\NTMakefile.version) ! include <..\thirdparty\NTMakefile.version> !elseif exist (thirdparty\NTMakefile.version) ! include !elseif exist (..\..\..\windows\NTMakefile.version) ! include <..\..\..\windows\NTMakefile.version> !elseif exist (..\..\windows\NTMakefile.version) ! include <..\..\windows\NTMakefile.version> !elseif exist (..\windows\NTMakefile.version) ! include <..\windows\NTMakefile.version> !else ! include !endif !if [ $(PERL) $(SRC)\cf\w32-detect-vc-version.pl $(CC) ]==16 HAVE_STDINT_H=1 HAVE_INT64_T=1 !endif # ------------------------------------------------------------ # Features # # For each feature enabled here, a corresponding line must exist in # the inline Perl script in include\NTMakefile. # Enable Kerberos v5 support in applications KRB5=1 # Enable KX509 support in the KDC KX509=1 # Enable PKINIT PKINIT=1 # Disable AFS support NO_AFS=1 # OpenSSL (mostly not needed on Windows, but should work) # INCLUDE_openssl_crypto= # LIB_openssl_crypto= # OpenLDAP package is available # OPENLDAP=1 # OpenLDAP include directory # OPENLDAP_INC= # OpenLDAP library to link against # OPENLDAP_LIB= # Support HDB LDAP module # OPENLDAP_MODULE=1 # OTP support in applications OTP=1 # Authentication support in telnet AUTHENTICATION=1 # Enable diagnostics in telnet DIAGNOSTICS=1 # Enable encryption support in telnet ENCRYPTION=1 # Use the weak AFS string to key functions # ENABLE_AFS_STRING_TO_KEY=1 !ifdef PTHREAD_INC !ifdef PTHREAD_LIB # We have HAVE_PTHREAD_H=1 # Make thread-safe libraries ENABLE_PTHREAD_SUPPORT=1 !endif !endif # Support for broken ENV_{VAR,VAL} telnets # ENV_HACK=1 # Use the Kerberos Credentials Manager # HAVE_KCM=1 # Use the sqlite backend HAVE_SCC=1 DIR_hdbdir=%{COMMON_APPDATA}/heimdal/hdb # Disable weak crypto WEAK_CRYPTO=0 # Enable hcrypt fallback mechanisms HCRYPTO_FALLBACK=1 # Disable use of GSS LOCALNAME support NO_LOCALNAME=1 # Windows CRT mkdir does not have the mode parameter MKDIR_DOES_NOT_HAVE_MODE=1 # Windows CRT rename does not unlink the target RENAME_DOES_NOT_UNLINK=1 # Disable build of installers !ifndef NO_INSTALLERS BUILD_INSTALLERS=1 !endif heimdal-7.5.0/windows/NTMakefile.version0000644000175000017500000000271313212440570016333 0ustar niknik# Version strings VER_PACKAGE=heimdal VER_PACKAGE_NAME=Heimdal VER_PACKAGE_BUGREPORT=https://github.com/heimdal/heimdal/issues VER_PACKAGE_COPYRIGHT=Copyright (C) 1995-2016 Royal Institute of Technology, Stockholm, Sweden VER_PACKAGE_COMPANY=www.h5l.org VER_PRODUCT_MAJOR=7 VER_PRODUCT_MINOR=5 VER_PRODUCT_AUX=0 VER_PRODUCT_PATCH=0 # ------------------------------------------------------------ # The VER_OLD_BEGIN and VER_OLD_END version values are used in # constructing the assembly publisher configuration. The end # must be less than the VER_PRODUCT value. If the current # version is 1.5.100.0 then VER_OLD_END version is # 1.5.99.65535. VER_OLD_BEGIN_MAJOR=7 VER_OLD_BEGIN_MINOR=2 VER_OLD_BEGIN_AUX=0 VER_OLD_BEGIN_PATCH=0 VER_OLD_END_MAJOR=7 VER_OLD_END_MINOR=4 VER_OLD_END_AUX=65535 VER_OLD_END_PATCH=65535 VER_PACKAGE_VERSION=$(VER_PRODUCT_MAJOR).$(VER_PRODUCT_MINOR).$(VER_PRODUCT_AUX) # Debug build flag !ifndef NODEBUG VER_DEBUG=1 !endif # Define to 1 if this is a pre-release build. Undefine otherwise VER_PRERELEASE=1 # Define to a valid string if this build DOES NOT follow normal # release procedures. I.e. this is a private build whose version # numbers are not co-ordinated with mainline development. #VER_PRIVATE=Private build for MyCompany # Define to a valid string if this build DOES follow normal release # procedures, but is a variation of the standard files of the same # version numbers. #VER_SPECIAL=Special build for testing ticket 12345 heimdal-7.5.0/krb5.conf0000644000175000017500000000040113026237312012756 0ustar niknik[libdefaults] default_realm = MY.REALM clockskew = 300 [realms] MY.REALM = { kdc = MY.COMPUTER } OTHER.REALM = { v4_instance_convert = { kerberos = kerberos computer = computer.some.other.domain } } [domain_realm] .my.domain = MY.REALM heimdal-7.5.0/doc/0000755000175000017500000000000013214604041012012 5ustar niknikheimdal-7.5.0/doc/win2k.texi0000644000175000017500000003137113026237312013750 0ustar niknik@c $Id$ @node Windows compatibility, Programming with Kerberos, Kerberos 4 issues, Top @comment node-name, next, previous, up @chapter Windows compatibility Microsoft Windows, starting from version 2000 (formerly known as Windows NT 5), implements Kerberos 5. Their implementation, however, has some quirks, peculiarities, and bugs. This chapter is a short summary of the compatibility issues between Heimdal and various Windows versions. The big problem with the Kerberos implementation in Windows is that the available documentation is more focused on getting things to work rather than how they work, and not that useful in figuring out how things really work. It's of course subject to change all the time and mostly consists of our not so inspired guesses. Hopefully it's still somewhat useful. @menu * Configuring Windows to use a Heimdal KDC:: * Inter-Realm keys (trust) between Windows and a Heimdal KDC:: * Create account mappings:: * Encryption types:: * Authorisation data:: * Quirks of Windows 2000 KDC:: * Useful links when reading about the Windows:: @end menu @node Configuring Windows to use a Heimdal KDC, Inter-Realm keys (trust) between Windows and a Heimdal KDC, Windows compatibility, Windows compatibility @comment node-name, next, precious, up @section Configuring Windows to use a Heimdal KDC You need the command line program called @command{ksetup.exe}. This program comes with the Windows Support Tools, available from either the installation CD-ROM (@file{SUPPORT/TOOLS/SUPPORT.CAB}), or from Microsoft web site. Starting from Windows 2008, it is already installed. This program is used to configure the Kerberos settings on a Workstation. @command{Ksetup} store the domain information under the registry key: @code{HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\LSA\Kerberos\Domains}. Use the @command{kadmin} program in Heimdal to create a host principal in the Kerberos realm. @example unix% kadmin kadmin> ank --password=password host/datan.example.com @end example The name @samp{datan.example.com} should be replaced with DNS name of the workstation. You must configure the workstation as a member of a workgroup, as opposed to a member in an NT domain, and specify the KDC server of the realm as follows: @example C:> ksetup /setdomain EXAMPLE.COM C:> ksetup /addkdc EXAMPLE.COM kdc.example.com @end example Set the machine password, i.e.@: create the local keytab: @example C:> ksetup /SetComputerPassword password @end example The password used in @kbd{ksetup /setmachpassword} must be the same as the password used in the @kbd{kadmin ank} command. The workstation must now be rebooted. A mapping between local NT users and Kerberos principals must be specified. You have two choices. First: @example C:> ksetup /mapuser user@@MY.REALM nt_user @end example This will map a user to a specific principal; this allows you to have other usernames in the realm than in your NT user database. (Don't ask me why on earth you would want that@enddots{}) You can also say: @example C:> ksetup /mapuser * * @end example The Windows machine will now map any user to the corresponding principal, for example @samp{nisse} to the principal @samp{nisse@@MY.REALM}. (This is most likely what you want.) @node Inter-Realm keys (trust) between Windows and a Heimdal KDC, Create account mappings, Configuring Windows to use a Heimdal KDC, Windows compatibility @comment node-name, next, precious, up @section Inter-Realm keys (trust) between Windows and a Heimdal KDC See also the Step-by-Step guide from Microsoft, referenced below. Install Windows, and create a new controller (Active Directory Server) for the domain. By default the trust will be non-transitive. This means that only users directly from the trusted domain may authenticate. This can be changed to transitive by using the @command{netdom.exe} tool. @command{netdom.exe} can also be used to add the trust between two realms. You need to tell Windows on what hosts to find the KDCs for the non-Windows realm with @command{ksetup}, see @xref{Configuring Windows to use a Heimdal KDC}. This needs to be done on all computers that want enable cross-realm login with @code{Mapped Names}. @c XXX probably shouldn't be @code Then you need to add the inter-realm keys on the Windows KDC@. Start the Domain Tree Management tool (found in Programs, Administrative tools, Active Directory Domains and Trusts). Right click on Properties of your domain, select the Trust tab. Press Add on the appropriate trust windows and enter domain name and password. When prompted if this is a non-Windows Kerberos realm, press OK. Do not forget to add trusts in both directions (if that's what you want). If you want to use @command{netdom.exe} instead of the Domain Tree Management tool, you do it like this: @example netdom trust NT.REALM.EXAMPLE.COM /Domain:EXAMPLE.COM /add /realm /passwordt:TrustPassword @end example You also need to add the inter-realm keys to the Heimdal KDC. But take care to the encryption types and salting used for those keys. There should be no encryption type stronger than the one configured on Windows side for this relationship, itself limited to the ones supported by this specific version of Windows, nor any Kerberos 4 salted hashes, as Windows does not seem to understand them. Otherwise, the trust will not works. Here are the version-specific needed information: @enumerate @item Windows 2000: maximum encryption type is DES @item Windows 2003: maximum encryption type is DES @item Windows 2003RC2: maximum encryption type is RC4, relationship defaults to DES @item Windows 2008: maximum encryption type is AES, relationship defaults to RC4 @end enumerate For Windows 2003RC2, to change the trust encryption type, you have to use the @command{ktpass}, from the Windows 2003 Resource kit *service pack2*, available from Microsoft web site. @example C:> ktpass /MITRealmName UNIX.EXAMPLE.COM /TrustEncryp RC4 @end example For Windows 2008, the same operation can be done with the @command{ksetup}, installed by default. @example C:> ksetup /SetEncTypeAttre EXAMPLE.COM AES256-SHA1 @end example Once the relationship is correctly configured, you can add the required inter-realm keys, using heimdal default encryption types: @example kadmin add krbtgt/NT.REALM.EXAMPLE.COM@@EXAMPLE.COM kadmin add krbtgt/REALM.EXAMPLE.COM@@NT.EXAMPLE.COM @end example Use the same passwords for both keys. And if needed, to remove unsupported encryptions, such as the following ones for a Windows 2003RC2 server. @example kadmin del_enctype krbtgt/REALM.EXAMPLE.COM@@NT.EXAMPLE.COM aes256-cts-hmac-sha1-96 kadmin del_enctype krbtgt/REALM.EXAMPLE.COM@@NT.EXAMPLE.COM des3-cbc-sha1 kadmin del_enctype krbtgt/NT.EXAMPLE.COM@@EXAMPLE.COM aes256-cts-hmac-sha1-96 kadmin del_enctype krbtgt/NT.EXAMPLE.COM@@EXAMPLE.COM des3-cbc-sha1 @end example Do not forget to reboot before trying the new realm-trust (after running @command{ksetup}). It looks like it might work, but packets are never sent to the non-Windows KDC. @node Create account mappings, Encryption types, Inter-Realm keys (trust) between Windows and a Heimdal KDC, Windows compatibility @comment node-name, next, precious, up @section Create account mappings Start the @code{Active Directory Users and Computers} tool. Select the View menu, that is in the left corner just below the real menu (or press Alt-V), and select Advanced Features. Right click on the user that you are going to do a name mapping for and choose Name mapping. Click on the Kerberos Names tab and add a new principal from the non-Windows domain. @c XXX check entry name then I have network again This adds @samp{authorizationNames} entry to the users LDAP entry to the Active Directory LDAP catalog. When you create users by script you can add this entry instead. @node Encryption types, Authorisation data, Create account mappings, Windows compatibility @comment node-name, next, previous, up @section Encryption types Windows 2000 supports both the standard DES encryptions (@samp{des-cbc-crc} and @samp{des-cbc-md5}) and its own proprietary encryption that is based on MD4 and RC4 that is documented in and is supposed to be described in @file{draft-brezak-win2k-krb-rc4-hmac-03.txt}. New users will get both MD4 and DES keys. Users that are converted from a NT4 database, will only have MD4 passwords and will need a password change to get a DES key. @node Authorisation data, Quirks of Windows 2000 KDC, Encryption types, Windows compatibility @comment node-name, next, previous, up @section Authorisation data The Windows 2000 KDC also adds extra authorisation data in tickets. It is at this point unclear what triggers it to do this. The format of this data is only available under a ``secret'' license from Microsoft, which prohibits you implementing it. A simple way of getting hold of the data to be able to understand it better is described here. @enumerate @item Find the client example on using the SSPI in the SDK documentation. @item Change ``AuthSamp'' in the source code to lowercase. @item Build the program. @item Add the ``authsamp'' principal with a known password to the database. Make sure it has a DES key. @item Run @kbd{ktutil add} to add the key for that principal to a keytab. @item Run @kbd{appl/test/nt_gss_server -p 2000 -s authsamp @kbd{--dump-auth}=@var{file}} where @var{file} is an appropriate file. @item It should authenticate and dump for you the authorisation data in the file. @item The tool @kbd{lib/asn1/asn1_print} is somewhat useful for analysing the data. @end enumerate @node Quirks of Windows 2000 KDC, Useful links when reading about the Windows, Authorisation data, Windows compatibility @comment node-name, next, previous, up @section Quirks of Windows 2000 KDC There are some issues with salts and Windows 2000. Using an empty salt---which is the only one that Kerberos 4 supported, and is therefore known as a Kerberos 4 compatible salt---does not work, as far as we can tell from out experiments and users' reports. Therefore, you have to make sure you keep around keys with all the different types of salts that are required. Microsoft have fixed this issue post Windows 2003. Microsoft seems also to have forgotten to implement the checksum algorithms @samp{rsa-md4-des} and @samp{rsa-md5-des}. This can make Name mapping (@pxref{Create account mappings}) fail if a @samp{des-cbc-md5} key is used. To make the KDC return only @samp{des-cbc-crc} you must delete the @samp{des-cbc-md5} key from the kdc using the @kbd{kadmin del_enctype} command. @example kadmin del_enctype lha des-cbc-md5 @end example You should also add the following entries to the @file{krb5.conf} file: @example [libdefaults] default_etypes = des-cbc-crc default_etypes_des = des-cbc-crc @end example These configuration options will make sure that no checksums of the unsupported types are generated. @node Useful links when reading about the Windows, , Quirks of Windows 2000 KDC, Windows compatibility @comment node-name, next, previous, up @section Useful links when reading about the Windows See also our paper presented at the 2001 Usenix Annual Technical Conference, available in the proceedings or at @uref{http://www.usenix.org/publications/library/proceedings/usenix01/freenix01/westerlund.html}. There are lots of texts about Kerberos on Microsoft's web site, here is a short list of the interesting documents that we have managed to find. @itemize @bullet @item Step-by-Step Guide to Kerberos 5 (krb5 1.0) Interoperability: @uref{http://www.microsoft.com/technet/prodtechnol/windows2000serv/howto/kerbstep.mspx}. Kerberos GSS-API (in Windows-eze SSPI), Windows as a client in a non-Windows KDC realm, adding unix clients to a Windows 2000 KDC, and adding cross-realm trust (@pxref{Inter-Realm keys (trust) between Windows and a Heimdal KDC}). @item Windows 2000 Kerberos Authentication: @uref{www.microsoft.com/technet/prodtechnol/windows2000serv/deploy/confeat/kerberos.mspx}. White paper that describes how Kerberos is used in Windows 2000. @item Overview of Kerberos: @uref{http://support.microsoft.com/support/kb/articles/Q248/7/58.ASP}. Links to useful other links. @c @item Klist for Windows: @c @uref{http://msdn.microsoft.com/library/periodic/period00/security0500.htm}. @c Describes where to get a klist for Windows 2000. @item Event logging for Kerberos: @uref{http://support.microsoft.com/support/kb/articles/Q262/1/77.ASP}. Basically it say that you can add a registry key @code{HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Lsa\Kerberos\Parameters\LogLevel} with value DWORD equal to 1, and then you'll get logging in the Event Logger. @c @item Access to the Active Directory through LDAP: @c @uref{http://msdn.microsoft.com/library/techart/kerberossamp.htm} @end itemize Other useful programs include these: @itemize @bullet @item pwdump2 @uref{http://www.bindview.com/Support/RAZOR/Utilities/Windows/pwdump2_readme.cfm} @end itemize heimdal-7.5.0/doc/whatis.texi0000644000175000017500000001373713026237312014223 0ustar niknik@c $Id$ @node What is Kerberos?, Building and Installing, Introduction, Top @chapter What is Kerberos? @quotation @flushleft Now this Cerberus had three heads of dogs, the tail of a dragon, and on his back the heads of all sorts of snakes. --- Pseudo-Apollodorus Library 2.5.12 @end flushleft @end quotation Kerberos is a system for authenticating users and services on a network. It is built upon the assumption that the network is ``unsafe''. For example, data sent over the network can be eavesdropped and altered, and addresses can also be faked. Therefore they cannot be used for authentication purposes. @cindex authentication Kerberos is a trusted third-party service. That means that there is a third party (the kerberos server) that is trusted by all the entities on the network (users and services, usually called @dfn{principals}). All principals share a secret password (or key) with the kerberos server and this enables principals to verify that the messages from the kerberos server are authentic. Thus trusting the kerberos server, users and services can authenticate each other. @section Basic mechanism @ifinfo @macro sub{arg} <\arg\> @end macro @end ifinfo @iftex @macro sub{arg} @textsubscript{\arg\} @end macro @end iftex @ifhtml @macro sub{arg} @html \arg\ @end html @end macro @end ifhtml @c ifdocbook @c macro sub{arg} @c docbook @c \arg\ @c end docbook @c end macro @c end ifdocbook @quotation @strong{Note} This discussion is about Kerberos version 4, but version 5 works similarly. @end quotation In Kerberos, principals use @dfn{tickets} to prove that they are who they claim to be. In the following example, @var{A} is the initiator of the authentication exchange, usually a user, and @var{B} is the service that @var{A} wishes to use. To obtain a ticket for a specific service, @var{A} sends a ticket request to the kerberos server. The request contains @var{A}'s and @var{B}'s names (along with some other fields). The kerberos server checks that both @var{A} and @var{B} are valid principals. Having verified the validity of the principals, it creates a packet containing @var{A}'s and @var{B}'s names, @var{A}'s network address (@var{A@sub{addr}}), the current time (@var{t@sub{issue}}), the lifetime of the ticket (@var{life}), and a secret @dfn{session key} @cindex session key (@var{K@sub{AB}}). This packet is encrypted with @var{B}'s secret key (@var{K@sub{B}}). The actual ticket (@var{T@sub{AB}}) looks like this: (@{@var{A}, @var{B}, @var{A@sub{addr}}, @var{t@sub{issue}}, @var{life}, @var{K@sub{AB}}@}@var{K@sub{B}}). The reply to @var{A} consists of the ticket (@var{T@sub{AB}}), @var{B}'s name, the current time, the lifetime of the ticket, and the session key, all encrypted in @var{A}'s secret key (@{@var{B}, @var{t@sub{issue}}, @var{life}, @var{K@sub{AB}}, @var{T@sub{AB}}@}@var{K@sub{A}}). @var{A} decrypts the reply and retains it for later use. @sp 1 Before sending a message to @var{B}, @var{A} creates an authenticator consisting of @var{A}'s name, @var{A}'s address, the current time, and a ``checksum'' chosen by @var{A}, all encrypted with the secret session key (@{@var{A}, @var{A@sub{addr}}, @var{t@sub{current}}, @var{checksum}@}@var{K@sub{AB}}). This is sent together with the ticket received from the kerberos server to @var{B}. Upon reception, @var{B} decrypts the ticket using @var{B}'s secret key. Since the ticket contains the session key that the authenticator was encrypted with, @var{B} can now also decrypt the authenticator. To verify that @var{A} really is @var{A}, @var{B} now has to compare the contents of the ticket with that of the authenticator. If everything matches, @var{B} now considers @var{A} as properly authenticated. @c (here we should have some more explanations) @section Different attacks @subheading Impersonating A An impostor, @var{C} could steal the authenticator and the ticket as it is transmitted across the network, and use them to impersonate @var{A}. The address in the ticket and the authenticator was added to make it more difficult to perform this attack. To succeed @var{C} will have to either use the same machine as @var{A} or fake the source addresses of the packets. By including the time stamp in the authenticator, @var{C} does not have much time in which to mount the attack. @subheading Impersonating B @var{C} can hijack @var{B}'s network address, and when @var{A} sends her credentials, @var{C} just pretend to verify them. @var{C} can't be sure that she is talking to @var{A}. @section Defence strategies It would be possible to add a @dfn{replay cache} @cindex replay cache to the server side. The idea is to save the authenticators sent during the last few minutes, so that @var{B} can detect when someone is trying to retransmit an already used message. This is somewhat impractical (mostly regarding efficiency), and is not part of Kerberos 4; MIT Kerberos 5 contains it. To authenticate @var{B}, @var{A} might request that @var{B} sends something back that proves that @var{B} has access to the session key. An example of this is the checksum that @var{A} sent as part of the authenticator. One typical procedure is to add one to the checksum, encrypt it with the session key and send it back to @var{A}. This is called @dfn{mutual authentication}. The session key can also be used to add cryptographic checksums to the messages sent between @var{A} and @var{B} (known as @dfn{message integrity}). Encryption can also be added (@dfn{message confidentiality}). This is probably the best approach in all cases. @cindex integrity @cindex confidentiality @section Further reading The original paper on Kerberos from 1988 is @cite{Kerberos: An Authentication Service for Open Network Systems}, by Jennifer Steiner, Clifford Neuman and Jeffrey I. Schiller. A less technical description can be found in @cite{Designing an Authentication System: a Dialogue in Four Scenes} by Bill Bryant, also from 1988. These documents can be found on our web-page at @url{http://www.pdc.kth.se/kth-krb/}. heimdal-7.5.0/doc/mdate-sh0000644000175000017500000000516712136107747013465 0ustar niknik#!/bin/sh # Get modification time of a file or directory and pretty-print it. # Copyright (C) 1995, 1996, 1997 Free Software Foundation, Inc. # written by Ulrich Drepper , June 1995 # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2, or (at your option) # any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software Foundation, # Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. # Prevent date giving response in another language. LANG=C export LANG LC_ALL=C export LC_ALL LC_TIME=C export LC_TIME # Get the extended ls output of the file or directory. # On HPUX /bin/sh, "set" interprets "-rw-r--r--" as options, so the "x" below. if ls -L /dev/null 1>/dev/null 2>&1; then set - x`ls -L -l -d $1` else set - x`ls -l -d $1` fi # The month is at least the fourth argument # (3 shifts here, the next inside the loop). shift shift shift # Find the month. Next argument is day, followed by the year or time. month= until test $month do shift case $1 in Jan) month=January; nummonth=1;; Feb) month=February; nummonth=2;; Mar) month=March; nummonth=3;; Apr) month=April; nummonth=4;; May) month=May; nummonth=5;; Jun) month=June; nummonth=6;; Jul) month=July; nummonth=7;; Aug) month=August; nummonth=8;; Sep) month=September; nummonth=9;; Oct) month=October; nummonth=10;; Nov) month=November; nummonth=11;; Dec) month=December; nummonth=12;; esac done day=$2 # Here we have to deal with the problem that the ls output gives either # the time of day or the year. case $3 in *:*) set `date`; eval year=\$$# case $2 in Jan) nummonthtod=1;; Feb) nummonthtod=2;; Mar) nummonthtod=3;; Apr) nummonthtod=4;; May) nummonthtod=5;; Jun) nummonthtod=6;; Jul) nummonthtod=7;; Aug) nummonthtod=8;; Sep) nummonthtod=9;; Oct) nummonthtod=10;; Nov) nummonthtod=11;; Dec) nummonthtod=12;; esac # For the first six month of the year the time notation can also # be used for files modified in the last year. if (expr $nummonth \> $nummonthtod) > /dev/null; then year=`expr $year - 1` fi;; *) year=$3;; esac # The result. echo $day $month $year heimdal-7.5.0/doc/krb5.din0000644000175000017500000000060312136107747013365 0ustar niknik# Doxyfile 1.5.3 PROJECT_NAME = Heimdal Kerberos 5 library PROJECT_NUMBER = @PACKAGE_VERSION@ OUTPUT_DIRECTORY = @srcdir@/doxyout/krb5 INPUT = @srcdir@/../lib/krb5 WARN_IF_UNDOCUMENTED = NO PERL_PATH = /usr/bin/perl HTML_HEADER = "@srcdir@/header.html" HTML_FOOTER = "@srcdir@/footer.html" @INCLUDE = "@srcdir@/doxytmpl.dxy" heimdal-7.5.0/doc/vars.tin0000644000175000017500000000017613026237312013511 0ustar niknik @c @c Variables depending on installation @c @set dbdir @dbdir@ @set dbtype @dbtype@ @set PACKAGE_VERSION @PACKAGE_VERSION@ heimdal-7.5.0/doc/header.html0000644000175000017500000000071012136107747014143 0ustar niknik $title

keyhole logo

heimdal-7.5.0/doc/programming.texi0000644000175000017500000000030212136107747015237 0ustar niknik@c $Id$ @node Programming with Kerberos, Migration, Windows compatibility, Top @chapter Programming with Kerberos See the Kerberos 5 API introduction and documentation on the Heimdal webpage. heimdal-7.5.0/doc/footer.html0000644000175000017500000000041312136107747014211 0ustar niknik
Generated on $datetime for $projectname by doxygen $doxygenversion
heimdal-7.5.0/doc/hx509.din0000644000175000017500000000057712136107747013411 0ustar niknik# Doxyfile 1.5.3 PROJECT_NAME = Heimdal x509 library PROJECT_NUMBER = @PACKAGE_VERSION@ OUTPUT_DIRECTORY = @srcdir@/doxyout/hx509 INPUT = @srcdir@/../lib/hx509 WARN_IF_UNDOCUMENTED = YES PERL_PATH = /usr/bin/perl HTML_HEADER = "@srcdir@/header.html" HTML_FOOTER = "@srcdir@/footer.html" @INCLUDE = "@srcdir@/doxytmpl.dxy" heimdal-7.5.0/doc/intro.texi0000644000175000017500000000550613026237312014052 0ustar niknik@c $Id$ @node Introduction, What is Kerberos?, Top, Top @c @node Introduction, What is Kerberos?, Top, Top @comment node-name, next, previous, up @chapter Introduction @heading What is Heimdal? Heimdal is a free implementation of Kerberos 5. The goals are to: @itemize @bullet @item have an implementation that can be freely used by anyone @item be protocol compatible with existing implementations and, if not in conflict, with RFC 4120 (and any future updated RFC). RFC 4120 replaced RFC 1510. @item be reasonably compatible with the M.I.T Kerberos V5 API @item have support for Kerberos V5 over GSS-API (RFC1964) @item include the most important and useful application programs (rsh, telnet, popper, etc.) @item include enough backwards compatibility with Kerberos V4 @end itemize @heading Status Heimdal has the following features (this does not mean any of this works): @itemize @bullet @item a stub generator and a library to encode/decode/whatever ASN.1/DER stuff @item a @code{libkrb5} library that should be possible to get to work with simple applications @item a GSS-API library @item @file{kinit}, @file{klist}, @file{kdestroy} @item @file{telnet}, @file{telnetd} @item @file{rsh}, @file{rshd} @item @file{popper}, @file{push} (a movemail equivalent) @item @file{ftp}, and @file{ftpd} @item a library @file{libkafs} for authenticating to AFS and a program @file{afslog} that uses it @item some simple test programs @item a KDC that supports most things, @item simple programs for distributing databases between a KDC master and slaves @item a password changing daemon @file{kpasswdd}, library functions for changing passwords and a simple client @item some kind of administration system @item Kerberos V4 support in many of the applications. @end itemize @heading Bug reports If you find bugs in this software, make sure it is a genuine bug and not just a part of the code that isn't implemented. Bug reports should be sent to @email{heimdal-bugs@@h5l.org}. Please include information on what machine and operating system (including version) you are running, what you are trying to do, what happens, what you think should have happened, an example for us to repeat, the output you get when trying the example, and a patch for the problem if you have one. Please make any patches with @code{diff -u} or @code{diff -c}. Suggestions, comments and other non bug reports are also welcome. @heading Mailing list There are two mailing lists with talk about Heimdal. @email{heimdal-announce@@sics.se} is a low-volume announcement list, while @email{heimdal-discuss@@sics.se} is for general discussion. Send a message to @email{majordomo@@sics.se} to subscribe. @heading Heimdal source code, binaries and the manual The source code for heimdal, links to binaries and the manual (this document) can be found on our web-page at @url{http://www.pdc.kth.se/heimdal/}. heimdal-7.5.0/doc/install.texi0000644000175000017500000000047412136107747014375 0ustar niknik@node Building and Installing, Setting up a realm, What is Kerberos?, Top @comment node-name, next, previous, up @chapter Building and Installing Build and install instructions are located here: @url{http://www.h5l.org/compile.html} Prebuilt packages is located here: @url{http://www.h5l.org/binaries.html} heimdal-7.5.0/doc/latin1.tex0000644000175000017500000001213112136107747013737 0ustar niknik% ISO Latin 1 (ISO 8859/1) encoding for Computer Modern fonts. % Jan Michael Rynning 1990-10-12 \def\inmathmode#1{\relax\ifmmode#1\else$#1$\fi} \global\catcode`\^^a0=\active \global\let^^a0=~ % no-break space \global\catcode`\^^a1=\active \global\def^^a1{!`} % inverted exclamation mark \global\catcode`\^^a2=\active \global\def^^a2{{\rm\rlap/c}} % cent sign \global\catcode`\^^a3=\active \global\def^^a3{{\it\$}} % pound sign % currency sign, yen sign, broken bar \global\catcode`\^^a7=\active \global\let^^a7=\S % section sign \global\catcode`\^^a8=\active \global\def^^a8{\"{}} % diaeresis \global\catcode`\^^a9=\active \global\let^^a9=\copyright % copyright sign % feminine ordinal indicator, left angle quotation mark \global\catcode`\^^ac=\active \global\def^^ac{\inmathmode\neg}% not sign \global\catcode`\^^ad=\active \global\let^^ad=\- % soft hyphen % registered trade mark sign \global\catcode`\^^af=\active \global\def^^af{\={}} % macron % ... \global\catcode`\^^b1=\active \global\def^^b1{\inmathmode\pm} % plus minus \global\catcode`\^^b2=\active \global\def^^b2{\inmathmode{{^2}}} \global\catcode`\^^b3=\active \global\def^^b3{\inmathmode{{^3}}} \global\catcode`\^^b4=\active \global\def^^b4{\'{}} % acute accent \global\catcode`\^^b5=\active \global\def^^b5{\inmathmode\mu} % mu \global\catcode`\^^b6=\active \global\let^^b6=\P % pilcroy \global\catcode`\^^b7=\active \global\def^^b7{\inmathmode{{\cdot}}} \global\catcode`\^^b8=\active \global\def^^b8{\c{}} % cedilla \global\catcode`\^^b9=\active \global\def^^b9{\inmathmode{{^1}}} % ... \global\catcode`\^^bc=\active \global\def^^bc{\inmathmode{{1\over4}}} \global\catcode`\^^bd=\active \global\def^^bd{\inmathmode{{1\over2}}} \global\catcode`\^^be=\active \global\def^^be{\inmathmode{{3\over4}}} \global\catcode`\^^bf=\active \global\def^^bf{?`} % inverted question mark \global\catcode`\^^c0=\active \global\def^^c0{\`A} \global\catcode`\^^c1=\active \global\def^^c1{\'A} \global\catcode`\^^c2=\active \global\def^^c2{\^A} \global\catcode`\^^c3=\active \global\def^^c3{\~A} \global\catcode`\^^c4=\active \global\def^^c4{\"A} % capital a with diaeresis \global\catcode`\^^c5=\active \global\let^^c5=\AA % capital a with ring above \global\catcode`\^^c6=\active \global\let^^c6=\AE \global\catcode`\^^c7=\active \global\def^^c7{\c C} \global\catcode`\^^c8=\active \global\def^^c8{\`E} \global\catcode`\^^c9=\active \global\def^^c9{\'E} \global\catcode`\^^ca=\active \global\def^^ca{\^E} \global\catcode`\^^cb=\active \global\def^^cb{\"E} \global\catcode`\^^cc=\active \global\def^^cc{\`I} \global\catcode`\^^cd=\active \global\def^^cd{\'I} \global\catcode`\^^ce=\active \global\def^^ce{\^I} \global\catcode`\^^cf=\active \global\def^^cf{\"I} % capital eth \global\catcode`\^^d1=\active \global\def^^d1{\~N} \global\catcode`\^^d2=\active \global\def^^d2{\`O} \global\catcode`\^^d3=\active \global\def^^d3{\'O} \global\catcode`\^^d4=\active \global\def^^d4{\^O} \global\catcode`\^^d5=\active \global\def^^d5{\~O} \global\catcode`\^^d6=\active \global\def^^d6{\"O} % capital o with diaeresis \global\catcode`\^^d7=\active \global\def^^d7{\inmathmode\times}% multiplication sign \global\catcode`\^^d8=\active \global\let^^d8=\O \global\catcode`\^^d9=\active \global\def^^d9{\`U} \global\catcode`\^^da=\active \global\def^^da{\'U} \global\catcode`\^^db=\active \global\def^^db{\^U} \global\catcode`\^^dc=\active \global\def^^dc{\"U} \global\catcode`\^^dd=\active \global\def^^dd{\'Y} % capital thorn \global\catcode`\^^df=\active \global\def^^df{\ss} \global\catcode`\^^e0=\active \global\def^^e0{\`a} \global\catcode`\^^e1=\active \global\def^^e1{\'a} \global\catcode`\^^e2=\active \global\def^^e2{\^a} \global\catcode`\^^e3=\active \global\def^^e3{\~a} \global\catcode`\^^e4=\active \global\def^^e4{\"a} % small a with diaeresis \global\catcode`\^^e5=\active \global\let^^e5=\aa % small a with ring above \global\catcode`\^^e6=\active \global\let^^e6=\ae \global\catcode`\^^e7=\active \global\def^^e7{\c c} \global\catcode`\^^e8=\active \global\def^^e8{\`e} \global\catcode`\^^e9=\active \global\def^^e9{\'e} \global\catcode`\^^ea=\active \global\def^^ea{\^e} \global\catcode`\^^eb=\active \global\def^^eb{\"e} \global\catcode`\^^ec=\active \global\def^^ec{\`\i} \global\catcode`\^^ed=\active \global\def^^ed{\'\i} \global\catcode`\^^ee=\active \global\def^^ee{\^\i} \global\catcode`\^^ef=\active \global\def^^ef{\"\i} % small eth \global\catcode`\^^f1=\active \global\def^^f1{\~n} \global\catcode`\^^f2=\active \global\def^^f2{\`o} \global\catcode`\^^f3=\active \global\def^^f3{\'o} \global\catcode`\^^f4=\active \global\def^^f4{\^o} \global\catcode`\^^f5=\active \global\def^^f5{\~o} \global\catcode`\^^f6=\active \global\def^^f6{\"o} % small o with diaeresis \global\catcode`\^^f7=\active \global\def^^f7{\inmathmode\div}% division sign \global\catcode`\^^f8=\active \global\let^^f8=\o \global\catcode`\^^f9=\active \global\def^^f9{\`u} \global\catcode`\^^fa=\active \global\def^^fa{\'u} \global\catcode`\^^fb=\active \global\def^^fb{\^u} \global\catcode`\^^fc=\active \global\def^^fc{\"u} \global\catcode`\^^fd=\active \global\def^^fd{\'y} % capital thorn \global\catcode`\^^ff=\active \global\def^^ff{\"y} heimdal-7.5.0/doc/wind.din0000644000175000017500000000057513024443740013464 0ustar niknik# Doxyfile 1.5.3 PROJECT_NAME = Heimdal wind library PROJECT_NUMBER = @PACKAGE_VERSION@ OUTPUT_DIRECTORY = @srcdir@/doxyout/wind INPUT = @srcdir@/../lib/wind WARN_IF_UNDOCUMENTED = YES PERL_PATH = /usr/bin/perl HTML_HEADER = "@srcdir@/header.html" HTML_FOOTER = "@srcdir@/footer.html" @INCLUDE = "@srcdir@/doxytmpl.dxy" heimdal-7.5.0/doc/doxytmpl.dxy0000644000175000017500000002215313026237312014427 0ustar niknik#--------------------------------------------------------------------------- # Project related configuration options #--------------------------------------------------------------------------- DOXYFILE_ENCODING = UTF-8 CREATE_SUBDIRS = NO OUTPUT_LANGUAGE = English BRIEF_MEMBER_DESC = YES REPEAT_BRIEF = YES ABBREVIATE_BRIEF = "The $name class " \ "The $name widget " \ "The $name file " \ is \ provides \ specifies \ contains \ represents \ a \ an \ the ALWAYS_DETAILED_SEC = NO INLINE_INHERITED_MEMB = NO FULL_PATH_NAMES = YES STRIP_FROM_PATH = /Applications/ STRIP_FROM_INC_PATH = SHORT_NAMES = NO JAVADOC_AUTOBRIEF = NO QT_AUTOBRIEF = NO MULTILINE_CPP_IS_BRIEF = NO INHERIT_DOCS = YES SEPARATE_MEMBER_PAGES = NO TAB_SIZE = 8 ALIASES = OPTIMIZE_OUTPUT_FOR_C = YES OPTIMIZE_OUTPUT_JAVA = NO BUILTIN_STL_SUPPORT = NO CPP_CLI_SUPPORT = NO DISTRIBUTE_GROUP_DOC = NO SUBGROUPING = YES #--------------------------------------------------------------------------- # Build related configuration options #--------------------------------------------------------------------------- EXTRACT_ALL = NO EXTRACT_PRIVATE = NO EXTRACT_STATIC = NO EXTRACT_LOCAL_CLASSES = YES EXTRACT_LOCAL_METHODS = NO EXTRACT_ANON_NSPACES = NO HIDE_UNDOC_MEMBERS = YES HIDE_UNDOC_CLASSES = YES HIDE_FRIEND_COMPOUNDS = NO HIDE_IN_BODY_DOCS = NO INTERNAL_DOCS = NO CASE_SENSE_NAMES = NO HIDE_SCOPE_NAMES = NO SHOW_INCLUDE_FILES = YES INLINE_INFO = YES SORT_MEMBER_DOCS = YES SORT_BRIEF_DOCS = NO SORT_BY_SCOPE_NAME = NO GENERATE_TODOLIST = YES GENERATE_TESTLIST = YES GENERATE_BUGLIST = YES GENERATE_DEPRECATEDLIST= YES ENABLED_SECTIONS = MAX_INITIALIZER_LINES = 30 SHOW_USED_FILES = YES FILE_VERSION_FILTER = #--------------------------------------------------------------------------- # configuration options related to warning and progress messages #--------------------------------------------------------------------------- QUIET = YES WARNINGS = YES WARN_IF_DOC_ERROR = YES WARN_NO_PARAMDOC = YES WARN_FORMAT = "$file:$line: $text " WARN_LOGFILE = #--------------------------------------------------------------------------- # configuration options related to the input files #--------------------------------------------------------------------------- INPUT_ENCODING = UTF-8 FILE_PATTERNS = *.c \ *.cc \ *.cxx \ *.cpp \ *.c++ \ *.d \ *.java \ *.ii \ *.ixx \ *.ipp \ *.i++ \ *.inl \ *.h \ *.hh \ *.hxx \ *.hpp \ *.h++ \ *.idl \ *.odl \ *.cs \ *.php \ *.php3 \ *.inc \ *.m \ *.mm \ *.dox RECURSIVE = YES EXCLUDE = EXCLUDE_SYMLINKS = NO EXCLUDE_PATTERNS = */.svn EXCLUDE_SYMBOLS = EXAMPLE_PATTERNS = * EXAMPLE_RECURSIVE = NO IMAGE_PATH = INPUT_FILTER = FILTER_PATTERNS = FILTER_SOURCE_FILES = NO #--------------------------------------------------------------------------- # configuration options related to source browsing #--------------------------------------------------------------------------- SOURCE_BROWSER = NO INLINE_SOURCES = NO STRIP_CODE_COMMENTS = YES REFERENCED_BY_RELATION = NO REFERENCES_RELATION = NO REFERENCES_LINK_SOURCE = YES USE_HTAGS = NO VERBATIM_HEADERS = NO #--------------------------------------------------------------------------- # configuration options related to the alphabetical class index #--------------------------------------------------------------------------- ALPHABETICAL_INDEX = NO COLS_IN_ALPHA_INDEX = 5 IGNORE_PREFIX = #--------------------------------------------------------------------------- # configuration options related to the HTML output #--------------------------------------------------------------------------- GENERATE_HTML = YES HTML_OUTPUT = html HTML_FILE_EXTENSION = .html HTML_STYLESHEET = GENERATE_HTMLHELP = NO HTML_DYNAMIC_SECTIONS = NO CHM_FILE = HHC_LOCATION = GENERATE_CHI = NO BINARY_TOC = NO TOC_EXPAND = NO DISABLE_INDEX = NO ENUM_VALUES_PER_LINE = 4 GENERATE_TREEVIEW = NO TREEVIEW_WIDTH = 250 #--------------------------------------------------------------------------- # configuration options related to the LaTeX output #--------------------------------------------------------------------------- GENERATE_LATEX = NO LATEX_OUTPUT = latex LATEX_CMD_NAME = latex MAKEINDEX_CMD_NAME = makeindex COMPACT_LATEX = NO PAPER_TYPE = a4wide EXTRA_PACKAGES = LATEX_HEADER = PDF_HYPERLINKS = NO USE_PDFLATEX = NO LATEX_BATCHMODE = NO LATEX_HIDE_INDICES = NO #--------------------------------------------------------------------------- # configuration options related to the RTF output #--------------------------------------------------------------------------- GENERATE_RTF = NO RTF_OUTPUT = rtf COMPACT_RTF = NO RTF_HYPERLINKS = NO RTF_STYLESHEET_FILE = RTF_EXTENSIONS_FILE = #--------------------------------------------------------------------------- # configuration options related to the man page output #--------------------------------------------------------------------------- GENERATE_MAN = YES MAN_OUTPUT = man MAN_EXTENSION = .3 MAN_LINKS = YES #--------------------------------------------------------------------------- # configuration options related to the XML output #--------------------------------------------------------------------------- GENERATE_XML = NO XML_OUTPUT = xml XML_PROGRAMLISTING = YES #--------------------------------------------------------------------------- # configuration options for the AutoGen Definitions output #--------------------------------------------------------------------------- GENERATE_AUTOGEN_DEF = NO #--------------------------------------------------------------------------- # configuration options related to the Perl module output #--------------------------------------------------------------------------- GENERATE_PERLMOD = NO PERLMOD_LATEX = NO PERLMOD_PRETTY = YES PERLMOD_MAKEVAR_PREFIX = #--------------------------------------------------------------------------- # Configuration options related to the preprocessor #--------------------------------------------------------------------------- ENABLE_PREPROCESSING = YES MACRO_EXPANSION = NO EXPAND_ONLY_PREDEF = NO SEARCH_INCLUDES = YES INCLUDE_PATH = INCLUDE_FILE_PATTERNS = PREDEFINED = DOXY EXPAND_AS_DEFINED = SKIP_FUNCTION_MACROS = YES #--------------------------------------------------------------------------- # Configuration::additions related to external references #--------------------------------------------------------------------------- TAGFILES = GENERATE_TAGFILE = ALLEXTERNALS = NO EXTERNAL_GROUPS = YES #--------------------------------------------------------------------------- # Configuration options related to the dot tool #--------------------------------------------------------------------------- CLASS_DIAGRAMS = NO HIDE_UNDOC_RELATIONS = YES HAVE_DOT = YES CLASS_GRAPH = YES COLLABORATION_GRAPH = YES GROUP_GRAPHS = YES UML_LOOK = NO TEMPLATE_RELATIONS = NO INCLUDE_GRAPH = YES INCLUDED_BY_GRAPH = YES CALL_GRAPH = NO CALLER_GRAPH = NO GRAPHICAL_HIERARCHY = YES DIRECTORY_GRAPH = YES DOT_IMAGE_FORMAT = png DOTFILE_DIRS = DOT_GRAPH_MAX_NODES = 50 MAX_DOT_GRAPH_DEPTH = 1000 DOT_TRANSPARENT = NO DOT_MULTI_TARGETS = NO GENERATE_LEGEND = YES DOT_CLEANUP = YES #--------------------------------------------------------------------------- # Configuration::additions related to the search engine #--------------------------------------------------------------------------- SEARCHENGINE = NO heimdal-7.5.0/doc/copyright.texi0000644000175000017500000004705313026237312014732 0ustar niknik @macro copynext{} @vskip 20pt plus 1fil @end macro @macro copyrightstart{} @end macro @macro copyrightend{} @end macro @node Copyrights and Licenses, , Acknowledgments, Top @comment node-name, next, previous, up @appendix Copyrights and Licenses @heading Kungliga Tekniska Högskolan @copyrightstart @verbatim Copyright (c) 1997-2011 Kungliga Tekniska Högskolan (Royal Institute of Technology, Stockholm, Sweden). All rights reserved. Portions Copyright (c) 2009 Apple Inc. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the Institute nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. @end verbatim @copynext @heading Massachusetts Institute of Technology The parts of the libtelnet that handle Kerberos. @verbatim Copyright (C) 1990 by the Massachusetts Institute of Technology Export of this software from the United States of America may require a specific license from the United States Government. It is the responsibility of any person or organization contemplating export to obtain such a license before exporting. WITHIN THAT CONSTRAINT, permission to use, copy, modify, and distribute this software and its documentation for any purpose and without fee is hereby granted, provided that the above copyright notice appear in all copies and that both that copyright notice and this permission notice appear in supporting documentation, and that the name of M.I.T. not be used in advertising or publicity pertaining to distribution of the software without specific, written prior permission. M.I.T. makes no representations about the suitability of this software for any purpose. It is provided "as is" without express or implied warranty. @end verbatim @copynext @heading The Regents of the University of California The parts of the libroken, most of libtelnet, telnet, ftp, and popper. @verbatim Copyright (c) 1988, 1990, 1993 The Regents of the University of California. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the University nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. @end verbatim @copynext @heading The Regents of the University of California. libedit @verbatim Copyright (c) 1992, 1993 The Regents of the University of California. All rights reserved. This code is derived from software contributed to Berkeley by Christos Zoulas of Cornell University. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the University nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. @end verbatim @copynext @heading TomsFastMath / LibTomMath Tom's fast math (bignum support) and LibTomMath @verbatim LibTomMath is hereby released into the Public Domain. @end verbatim @copynext @heading Doug Rabson GSS-API mechglue layer. @verbatim Copyright (c) 2005 Doug Rabson All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. @end verbatim @copynext @heading PADL Software Pty Ltd @table @asis @item GSS-API CFX, SPNEGO, naming extensions, API extensions. @item KCM credential cache. @item HDB LDAP backend. @end table @verbatim Copyright (c) 2003-2011, PADL Software Pty Ltd. Copyright (c) 2004, Andrew Bartlett. Copyright (c) 2003 - 2008, Kungliga Tekniska Högskolan Copyright (c) 2015, Timothy Pearson. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of PADL Software nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY PADL SOFTWARE AND CONTRIBUTORS ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL PADL SOFTWARE OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. @end verbatim @copynext @heading Marko Kreen Fortuna in libhcrypto @verbatim Copyright (c) 2005 Marko Kreen All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. @end verbatim @copynext @heading NTT (Nippon Telegraph and Telephone Corporation) Camellia in libhcrypto @verbatim Copyright (c) 2006,2007 NTT (Nippon Telegraph and Telephone Corporation) . All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer as the first lines of this file unmodified. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY NTT ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL NTT BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. @end verbatim @copynext @heading The NetBSD Foundation, Inc. vis.c in libroken @verbatim Copyright (c) 1999, 2005 The NetBSD Foundation, Inc. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. @end verbatim @copynext @heading Vincent Rijmen, Antoon Bosselaers, Paulo Barreto AES in libhcrypto @verbatim rijndael-alg-fst.c @version 3.0 (December 2000) Optimised ANSI C code for the Rijndael cipher (now AES) @author Vincent Rijmen @author Antoon Bosselaers @author Paulo Barreto This code is hereby placed in the public domain. THIS SOFTWARE IS PROVIDED BY THE AUTHORS ''AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. @end verbatim @copynext @heading Apple, Inc kdc/announce.c @verbatim Copyright (c) 2008 Apple Inc. All Rights Reserved. Export of this software from the United States of America may require a specific license from the United States Government. It is the responsibility of any person or organization contemplating export to obtain such a license before exporting. WITHIN THAT CONSTRAINT, permission to use, copy, modify, and distribute this software and its documentation for any purpose and without fee is hereby granted, provided that the above copyright notice appear in all copies and that both that copyright notice and this permission notice appear in supporting documentation, and that the name of Apple Inc. not be used in advertising or publicity pertaining to distribution of the software without specific, written prior permission. Apple Inc. makes no representations about the suitability of this software for any purpose. It is provided "as is" without express or implied warranty. THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE. @end verbatim @copynext @heading Richard Outerbridge DES core in libhcrypto @verbatim D3DES (V5.09) - A portable, public domain, version of the Data Encryption Standard. Written with Symantec's THINK (Lightspeed) C by Richard Outerbridge. Thanks to: Dan Hoey for his excellent Initial and Inverse permutation code; Jim Gillogly & Phil Karn for the DES key schedule code; Dennis Ferguson, Eric Young and Dana How for comparing notes; and Ray Lau, for humouring me on. Copyright (c) 1988,1989,1990,1991,1992 by Richard Outerbridge. (GEnie : OUTER; CIS : [71755,204]) Graven Imagery, 1992. @end verbatim @copynext @heading Secure Endpoints Inc Windows support @verbatim Copyright (c) 2009-2015, Secure Endpoints Inc. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. @end verbatim @copynext @heading Novell, Inc lib/hcrypto/test_dh.c @verbatim Copyright (c) 2007, Novell, Inc. Author: Matthias Koenig All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the Novell nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. @end verbatim @copyrightend heimdal-7.5.0/doc/apps.texi0000644000175000017500000002415212136107747013671 0ustar niknik@c $Id$ @node Applications, Things in search for a better place, Setting up a realm, Top @chapter Applications @menu * Authentication modules:: * AFS:: @end menu @node Authentication modules, AFS, Applications, Applications @section Authentication modules The problem of having different authentication mechanisms has been recognised by several vendors, and several solutions have appeared. In most cases these solutions involve some kind of shared modules that are loaded at run-time. Modules for some of these systems can be found in @file{lib/auth}. Presently there are modules for Digital's SIA, and IRIX' @code{login} and @code{xdm} (in @file{lib/auth/afskauthlib}). @menu * Digital SIA:: * IRIX:: @end menu @node Digital SIA, IRIX, Authentication modules, Authentication modules @subsection Digital SIA How to install the SIA module depends on which OS version you're running. Tru64 5.0 has a new command, @file{siacfg}, which makes this process quite simple. If you have this program, you should just be able to run: @example siacfg -a KRB5 /usr/athena/lib/libsia_krb5.so @end example On older versions, or if you want to do it by hand, you have to do the following (not tested by us on Tru64 5.0): @itemize @bullet @item Make sure @file{libsia_krb5.so} is available in @file{/usr/athena/lib}. If @file{/usr/athena} is not on local disk, you might want to put it in @file{/usr/shlib} or someplace else. If you do, you'll have to edit @file{krb5_matrix.conf} to reflect the new location (you will also have to do this if you installed in some other directory than @file{/usr/athena}). If you built with shared libraries, you will have to copy the shared @file{libkrb.so}, @file{libdes.so}, @file{libkadm.so}, and @file{libkafs.so} to a place where the loader can find them (such as @file{/usr/shlib}). @item Copy (your possibly edited) @file{krb5_matrix.conf} to @file{/etc/sia}. @item Apply @file{security.patch} to @file{/sbin/init.d/security}. @item Turn on KRB5 security by issuing @kbd{rcmgr set SECURITY KRB5} and @kbd{rcmgr set KRB5_MATRIX_CONF krb5_matrix.conf}. @item Digital thinks you should reboot your machine, but that really shouldn't be necessary. It's usually sufficient just to run @kbd{/sbin/init.d/security start} (and restart any applications that use SIA, like @code{xdm}.) @end itemize Users with local passwords (like @samp{root}) should be able to login safely. When using Digital's xdm the @samp{KRB5CCNAME} environment variable isn't passed along as it should (since xdm zaps the environment). Instead you have to set @samp{KRB5CCNAME} to the correct value in @file{/usr/lib/X11/xdm/Xsession}. Add a line similar to @example KRB5CCNAME=FILE:/tmp/krb5cc`id -u`_`ps -o ppid= -p $$`; export KRB5CCNAME @end example If you use CDE, @code{dtlogin} allows you to specify which additional environment variables it should export. To add @samp{KRB5CCNAME} to this list, edit @file{/usr/dt/config/Xconfig}, and look for the definition of @samp{exportList}. You want to add something like: @example Dtlogin.exportList: KRB5CCNAME @end example @subsubheading Notes to users with Enhanced security Digital's @samp{ENHANCED} (C2) security, and Kerberos solve two different problems. C2 deals with local security, adds better control of who can do what, auditing, and similar things. Kerberos deals with network security. To make C2 security work with Kerberos you will have to do the following. @itemize @bullet @item Replace all occurrences of @file{krb5_matrix.conf} with @file{krb5+c2_matrix.conf} in the directions above. @item You must enable ``vouching'' in the @samp{default} database. This will make the OSFC2 module trust other SIA modules, so you can login without giving your C2 password. To do this use @samp{edauth} to edit the default entry @kbd{/usr/tcb/bin/edauth -dd default}, and add a @samp{d_accept_alternate_vouching} capability, if not already present. @item For each user who does @emph{not} have a local C2 password, you should set the password expiration field to zero. You can do this for each user, or in the @samp{default} table. To do this use @samp{edauth} to set (or change) the @samp{u_exp} capability to @samp{u_exp#0}. @item You also need to be aware that the shipped @file{login}, @file{rcp}, and @file{rshd}, don't do any particular C2 magic (such as checking for various forms of disabled accounts), so if you rely on those features, you shouldn't use those programs. If you configure with @samp{--enable-osfc2}, these programs will, however, set the login UID. Still: use at your own risk. @end itemize At present @samp{su} does not accept the vouching flag, so it will not work as expected. Also, kerberised ftp will not work with C2 passwords. You can solve this by using both Digital's ftpd and our on different ports. @strong{Remember}, if you do these changes you will get a system that most certainly does @emph{not} fulfil the requirements of a C2 system. If C2 is what you want, for instance if someone else is forcing you to use it, you're out of luck. If you use enhanced security because you want a system that is more secure than it would otherwise be, you probably got an even more secure system. Passwords will not be sent in the clear, for instance. @node IRIX, , Digital SIA, Authentication modules @subsection IRIX The IRIX support is a module that is compatible with Transarc's @file{afskauthlib.so}. It should work with all programs that use this library. This should include @command{login} and @command{xdm}. The interface is not very documented but it seems that you have to copy @file{libkafs.so}, @file{libkrb.so}, and @file{libdes.so} to @file{/usr/lib}, or build your @file{afskauthlib.so} statically. The @file{afskauthlib.so} itself is able to reside in @file{/usr/vice/etc}, @file{/usr/afsws/lib}, or the current directory (wherever that is). IRIX 6.4 and newer seem to have all programs (including @command{xdm} and @command{login}) in the N32 object format, whereas in older versions they were O32. For it to work, the @file{afskauthlib.so} library has to be in the same object format as the program that tries to load it. This might require that you have to configure and build for O32 in addition to the default N32. Apart from this it should ``just work''; there are no configuration files. Note that recent Irix 6.5 versions (at least 6.5.22) have PAM, including a @file{pam_krb5.so} module. Not all relevant programs use PAM, though, e.g.@: @command{ssh}. In particular, for console graphical login you need to turn off @samp{visuallogin} and turn on @samp{xdm} with @command{chkconfig}. @node AFS, , Authentication modules, Applications @section AFS @cindex AFS AFS is a distributed filesystem that uses Kerberos for authentication. @cindex OpenAFS @cindex Arla For more information about AFS see OpenAFS @url{http://www.openafs.org/} and Arla @url{http://www.stacken.kth.se/projekt/arla/}. @subsection kafs and afslog @cindex afslog @manpage{afslog,1} will obtains AFS tokens for a number of cells. What cells to get tokens for can either be specified as an explicit list, as file paths to get tokens for, or be left unspecified, in which case will use whatever magic @manpage{kafs,3} decides upon. If not told what cell to get credentials for, @manpage{kafs,3} will search for the files ThisCell and TheseCells in the locations specified in @manpage{kafs,3} and try to get tokens for these cells and the cells specified in $HOME/.TheseCells. More usefully it will look at and ~/.TheseCells in your home directory and for each line which is a cell get afs token for these cells. The TheseCells file defines the the cells to which applications on the local client machine should try to aquire tokens for. It must reside in the directories searched by @manpage{kafs,3} on every AFS client machine. The file is in ASCII format and contains one character string, the cell name, per line. Cell names are case sensitive, but most cell names are lower case. See manpage for @manpage{kafs,3} for search locations of ThisCell and TheseCells. @subsection How to get a KeyFile @file{ktutil -k AFSKEYFILE:KeyFile get afs@@MY.REALM} or you can extract it with kadmin @example kadmin> ext -k AFSKEYFILE:/usr/afs/etc/KeyFile afs@@My.CELL.NAME @end example You have to make sure you have a @code{des-cbc-md5} encryption type since that is the enctype that will be converted. @subsection How to convert a srvtab to a KeyFile You need a @file{/usr/vice/etc/ThisCell} containing the cellname of your AFS-cell. @file{ktutil copy krb4:/root/afs-srvtab AFSKEYFILE:/usr/afs/etc/KeyFile}. If keyfile already exists, this will add the new key in afs-srvtab to KeyFile. @section Using 2b tokens with AFS @subsection What is 2b ? 2b is the name of the proposal that was implemented to give basic Kerberos 5 support to AFS in rxkad. It's not real Kerberos 5 support since it still uses fcrypt for data encryption and not Kerberos encryption types. Its only possible (in all cases) to do this for DES encryption types because only then the token (the AFS equivalent of a ticket) will be smaller than the maximum size that can fit in the token cache in the OpenAFS/Transarc client. It is a so tight fit that some extra wrapping on the ASN1/DER encoding is removed from the Kerberos ticket. 2b uses a Kerberos 5 EncTicketPart instead of a Kerberos 4 ditto for the part of the ticket that is encrypted with the service's key. The client doesn't know what's inside the encrypted data so to the client it doesn't matter. To differentiate between Kerberos 4 tickets and Kerberos 5 tickets, 2b uses a special kvno, 213 for 2b tokens and 255 for Kerberos 5 tokens. Its a requirement that all AFS servers that support 2b also support native Kerberos 5 in rxkad. @subsection Configuring a Heimdal kdc to use 2b tokens Support for 2b tokens in the kdc are turned on for specific principals by adding them to the string list option @code{[kdc]use_2b} in the kdc's @file{krb5.conf} file. @example [kdc] use_2b = @{ afs@@SU.SE = yes afs/it.su.se@@SU.SE = yes @} @end example @subsection Configuring AFS clients for 2b support There is no need to configure AFS clients for 2b support. The only software that needs to be installed/upgrade is a Kerberos 5 enabled @file{afslog}. heimdal-7.5.0/doc/hcrypto.din0000644000175000017500000000066512136107747014222 0ustar niknik# Doxyfile 1.5.3 PROJECT_NAME = "Heimdal crypto library" PROJECT_NUMBER = @PACKAGE_VERSION@ OUTPUT_DIRECTORY = @srcdir@/doxyout/hcrypto INPUT = @srcdir@/../lib/hcrypto EXAMPLE_PATH = @srcdir@/../lib/hcrypto WARN_IF_UNDOCUMENTED = YES PERL_PATH = /usr/bin/perl HTML_HEADER = "@srcdir@/header.html" HTML_FOOTER = "@srcdir@/footer.html" @INCLUDE = "@srcdir@/doxytmpl.dxy" heimdal-7.5.0/doc/base.hhp0000644000175000017500000000030513026237312013427 0ustar niknik[OPTIONS] Compatibility=1.1 or later Compiled file=heimbase.chm Contents file=toc.hhc Default topic=index.html Display compile progress=No Language=0x409 English (United States) Title=Heimdal Base heimdal-7.5.0/doc/heimdal.texi0000644000175000017500000000625613026237312014325 0ustar niknik\input texinfo @c -*- texinfo -*- @c %**start of header @c $Id$ @setfilename heimdal.info @settitle HEIMDAL @iftex @afourpaper @end iftex @c some sensible characters, please? @tex \input latin1.tex @end tex @setchapternewpage on @syncodeindex pg cp @c %**end of header @include vars.texi @set VERSION @value{PACKAGE_VERSION} @set EDITION 1.0 @ifinfo @dircategory Security @direntry * Heimdal: (heimdal). The Kerberos 5 distribution from KTH @end direntry @end ifinfo @c title page @titlepage @title Heimdal @subtitle Kerberos 5 from KTH @subtitle Edition @value{EDITION}, for version @value{VERSION} @subtitle 2008 @author Johan Danielsson @author Love Hörnquist Åstrand @author Assar Westerlund @end titlepage @macro manpage{man, section} @cite{\man\(\section\)} @end macro @c Less filling! Tastes great! @iftex @parindent=0pt @global@parskip 6pt plus 1pt @global@chapheadingskip = 15pt plus 4pt minus 2pt @global@secheadingskip = 12pt plus 3pt minus 2pt @global@subsecheadingskip = 9pt plus 2pt minus 2pt @end iftex @ifinfo @paragraphindent 0 @end ifinfo @ifnottex @node Top, Introduction, (dir), (dir) @top Heimdal @end ifnottex This manual for version @value{VERSION} of Heimdal. @menu * Introduction:: * What is Kerberos?:: * Building and Installing:: * Setting up a realm:: * Applications:: * Things in search for a better place:: * Kerberos 4 issues:: * Windows compatibility:: * Programming with Kerberos:: * Migration:: * Acknowledgments:: * Copyrights and Licenses:: @detailmenu --- The Detailed Node Listing --- Setting up a realm * Configuration file:: * Creating the database:: * Modifying the database:: * keytabs:: * Remote administration:: * Password changing:: * Testing clients and servers:: * Slave Servers:: * Incremental propagation:: * Encryption types and salting:: * Credential cache server - KCM:: * Cross realm:: * Transit policy:: * Setting up DNS:: * Using LDAP to store the database:: * Providing Kerberos credentials to servers and programs:: * Setting up PK-INIT:: * Debugging Kerberos problems:: Applications * Authentication modules:: * AFS:: Authentication modules * Digital SIA:: * IRIX:: Kerberos 4 issues * Principal conversion issues:: * Converting a version 4 database:: Windows compatibility * Configuring Windows to use a Heimdal KDC:: * Inter-Realm keys (trust) between Windows and a Heimdal KDC:: * Create account mappings:: * Encryption types:: * Authorisation data:: * Quirks of Windows 2000 KDC:: * Useful links when reading about the Windows:: Programming with Kerberos @end detailmenu @end menu @include intro.texi @include whatis.texi @include install.texi @include setup.texi @include apps.texi @include misc.texi @include kerberos4.texi @include win2k.texi @include programming.texi @include migration.texi @include ack.texi @include copyright.texi @c @shortcontents @contents @bye heimdal-7.5.0/doc/base.din0000644000175000017500000000057513026237312013433 0ustar niknik# Doxyfile 1.5.3 PROJECT_NAME = Heimdal base library PROJECT_NUMBER = @PACKAGE_VERSION@ OUTPUT_DIRECTORY = @srcdir@/doxyout/base INPUT = @srcdir@/../lib/base WARN_IF_UNDOCUMENTED = YES PERL_PATH = /usr/bin/perl HTML_HEADER = "@srcdir@/header.html" HTML_FOOTER = "@srcdir@/footer.html" @INCLUDE = "@srcdir@/doxytmpl.dxy" heimdal-7.5.0/doc/init-creds0000644000175000017500000003574412136107747014030 0ustar niknikCurrently, getting an initial ticket for a user involves many function calls, especially when a full set of features including password expiration and challenge preauthentication is desired. In order to solve this problem, a new api is proposed. typedef struct _krb5_prompt { char *prompt; int hidden; krb5_data *reply; } krb5_prompt; typedef int (*krb5_prompter_fct)(krb5_context context, void *data, const char *banner, int num_prompts, krb5_prompt prompts[]); typedef struct _krb5_get_init_creds_opt { krb5_flags flags; krb5_deltat tkt_life; krb5_deltat renew_life; int forwardable; int proxiable; krb5_enctype *etype_list; int etype_list_length; krb5_address **address_list; /* XXX the next three should not be used, as they may be removed later */ krb5_preauthtype *preauth_list; int preauth_list_length; krb5_data *salt; } krb5_get_init_creds_opt; #define KRB5_GET_INIT_CREDS_OPT_TKT_LIFE 0x0001 #define KRB5_GET_INIT_CREDS_OPT_RENEW_LIFE 0x0002 #define KRB5_GET_INIT_CREDS_OPT_FORWARDABLE 0x0004 #define KRB5_GET_INIT_CREDS_OPT_PROXIABLE 0x0008 #define KRB5_GET_INIT_CREDS_OPT_ETYPE_LIST 0x0010 #define KRB5_GET_INIT_CREDS_OPT_ADDRESS_LIST 0x0020 #define KRB5_GET_INIT_CREDS_OPT_PREAUTH_LIST 0x0040 #define KRB5_GET_INIT_CREDS_OPT_SALT 0x0080 void krb5_get_init_creds_opt_init(krb5_get_init_creds_opt *opt); void krb5_get_init_creds_opt_set_tkt_life(krb5_get_init_creds_opt *opt, krb5_deltat tkt_life); void krb5_get_init_creds_opt_set_renew_life(krb5_get_init_creds_opt *opt, krb5_deltat renew_life); void krb5_get_init_creds_opt_set_forwardable(krb5_get_init_creds_opt *opt, int forwardable); void krb5_get_init_creds_opt_set_proxiable(krb5_get_init_creds_opt *opt, int proxiable); void krb5_get_init_creds_opt_set_etype_list(krb5_get_init_creds_opt *opt, krb5_enctype *etype_list, int etype_list_length); void krb5_get_init_creds_opt_set_address_list(krb5_get_init_creds_opt *opt, krb5_address **addresses); void krb5_get_init_creds_opt_set_preauth_list(krb5_get_init_creds_opt *opt, krb5_preauthtype *preauth_list, int preauth_list_length); void krb5_get_init_creds_opt_set_salt(krb5_get_init_creds_opt *opt, krb5_data *salt); krb5_error_code krb5_get_init_creds_password(krb5_context context, krb5_creds *creds, krb5_principal client, char *password, krb5_prompter_fct prompter, void *data, krb5_deltat start_time, char *in_tkt_service, krb5_get_init_creds_opt *options); This function will attempt to acquire an initial ticket. The function will perform whatever tasks are necessary to do so. This may include changing an expired password, preauthentication. The arguments divide into two types. Some arguments are basically invariant and arbitrary across all initial tickets, and if not specified are determined by configuration or library defaults. Some arguments are different for each execution or application, and if not specified can be determined correctly from system configuration or environment. The former arguments are contained in a structure whose pointer is passed to the function. A bitmask specifies which elements of the structure should be used. In most cases, a NULL pointer can be used. The latter arguments are specified as individual arguments to the function. If a pointer to a credential is specified, the initial credential is filled in. If the caller only wishes to do a simple password check and will not be doing any other kerberos functions, then a NULL pointer may be specified, and the credential will be destroyed. If the client name is non-NULL, the initial ticket requested will be for that principal. Otherwise, the principal will be the username specified by the USER environment variable, or if the USER environment variable is not set, the username corresponding to the real user id of the caller. If the password is non-NULL, then this string is used as the password. Otherwise, the prompter function will be used to prompt the user for the password. If a prompter function is non-NULL, it will be used if additional user input is required, such as if the user's password has expired and needs to be changed, or if input preauthentication is necessary. If no function is specified and input is required, then the login will fail. The context argument is the same as that passed to krb5_login. The data argument is passed unmodified to the prompter function and is intended to be used to pass application data (such as a display handle) to the prompter function. The banner argument, if non-NULL, will indicate what sort of input is expected from the user (for example, "Password has expired and must be changed" or "Enter Activcard response for challenge 012345678"), and should be displayed accordingly. The num_prompts argument indicates the number of values which should be prompted for. If num_prompts == 0, then the banner contains an informational message which should be displayed to the user. The prompts argument contains an array describing the values for which the user should be prompted. The prompt member indicates the prompt for each value ("Enter new password"/"Enter it again", or "Challenge response"). The hidden member is nonzero if the response should not be displayed back to the user. The reply member is a pointer to krb5_data structure which has already been allocated. The prompter should fill in the structure with the NUL-terminated response from the user. If the response data does not fit, or if any other error occurs, then the prompter function should return a non-zero value which will be returned by the krb5_get_init_creds function. Otherwise, zero should be returned. The library function krb5_prompter_posix() implements a prompter using a posix terminal for user in. This function does not use the data argument. If the start_time is zero, then the requested ticket will be valid beginning immediately. Otherwise, the start_time indicates how far in the future the ticket should be postdated. If the in_tkt_service name is non-NULL, that principal name will be used as the server name for the initial ticket request. The realm of the name specified will be ignored and will be set to the realm of the client name. If no in_tkt_service name is specified, krbtgt/CLIENT-REALM@CLIENT-REALM will be used. For the rest of arguments, a configuration or library default will be used if no value is specified in the options structure. If a tkt_life is specified, that will be the lifetime of the ticket. The library default is 10 hours; there is no configuration variable (there should be, but it's not there now). If a renew_life is specified and non-zero, then the RENEWABLE option on the ticket will be set, and the value of the argument will be the the renewable lifetime. The configuration variable [libdefaults] "renew_lifetime" is the renewable lifetime if none is passed in. The library default is not to set the RENEWABLE option. If forwardable is specified, the FORWARDABLE option on the ticket will be set if and only if forwardable is non-zero. The configuration variable [libdefaults] "forwardable" is used if no value is passed in. The option will be set if and only if the variable is "y", "yes", "true", "t", "1", or "on", case insensitive. The library default is not to set the FORWARDABLE option. If proxiable is specified, the PROXIABLE option on the ticket will be set if and only if proxiable is non-zero. The configuration variable [libdefaults] "proxiable" is used if no value is passed in. The option will be set if and only if the variable is "y", "yes", "true", "t", "1", or "on", case insensitive. The library default is not to set the PROXIABLE option. If etype_list is specified, it will be used as the list of desired encryption algorithms in the request. The configuration variable [libdefaults] "default_tkt_enctypes" is used if no value is passed in. The library default is "des-cbc-md5 des-cbc-crc". If address_list is specified, it will be used as the list of addresses for which the ticket will be valid. The library default is to use all local non-loopback addresses. There is no configuration variable. If preauth_list is specified, it names preauth data types which will be included in the request. The library default is to interact with the kdc to determine the required preauth types. There is no configuration variable. If salt is specified, it specifies the salt which will be used when converting the password to a key. The library default is to interact with the kdc to determine the correct salt. There is no configuration variable. ================================================================ typedef struct _krb5_verify_init_creds_opt { krb5_flags flags; int ap_req_nofail; } krb5_verify_init_creds_opt; #define KRB5_VERIFY_INIT_CREDS_OPT_AP_REQ_NOFAIL 0x0001 void krb5_verify_init_creds_opt_init(krb5_init_creds_opt *options); void krb5_verify_init_creds_opt_set_ap_req_nofail(krb5_init_creds_opt *options, int ap_req_nofail); krb5_error_code krb5_verify_init_creds(krb5_context context, krb5_creds *creds, krb5_principal ap_req_server, krb5_keytab ap_req_keytab, krb5_ccache *ccache, krb5_verify_init_creds_opt *options); This function will use the initial ticket in creds to make an AP_REQ and verify it to insure that the AS_REP has not been spoofed. If the ap_req_server name is non-NULL, then this service name will be used for the AP_REQ; otherwise, the default host key (host/hostname.domain@LOCAL-REALM) will be used. If ap_req_keytab is non-NULL, the service key for the verification will be read from that keytab; otherwise, the service key will be read from the default keytab. If the service of the ticket in creds is the same as the service name for the AP_REQ, then this ticket will be used directly. If the ticket is a tgt, then it will be used to obtain credentials for the service. Otherwise, the verification will fail, and return an error. Other failures of the AP_REQ verification may or may not be considered errors, as described below. If a pointer to a credential cache handle is specified, and the handle is NULL, a credential cache handle referring to all credentials obtained in the course of verifying the user will be returned. In order to avoid potential setuid race conditions and other problems related to file system access, this handle will refer to a memory credential cache. If the handle is non-NULL, then the credentials will be added to the existing ccache. If the caller only wishes to verify the password and will not be doing any other kerberos functions, then a NULL pointer may be specified, and the credentials will be deleted before the function returns. If ap_req_nofail is specified, then failures of the AP_REQ verification are considered errors if and only if ap_req_nofail is non-zero. Whether or not AP_REQ validation is performed and what failures mean depends on these inputs: A) The appropriate keytab exists and contains the named key. B) An AP_REQ request to the kdc succeeds, and the resulting AP_REQ can be decrypted and verified. C) The administrator has specified in a configuration file that AP_REQ validation must succeed. This is basically a paranoid bit, and can be overridden by the application based on a command line flag or other application-specific info. This flag is especially useful if the admin is concerned that DNS might be spoofed while determining the host/FQDN name. The configuration variable [libdefaults] "verify_ap_req_nofail" is used if no value is passed in. The library default is not to set this option. Initial ticket verification will succeed if and only if: - A && B or - !A && !C ================================================================ For illustrative purposes, here's the invocations I expect some programs will use. Of course, error checking needs to be added. kinit: /* Fill in client from the command line || existing ccache, and, start_time, and options.{tkt_life,renew_life,forwardable,proxiable} from the command line. Some or all may remain unset. */ krb5_get_init_creds(context, &creds, client, krb5_initial_prompter_posix, NULL, start_time, NULL, &options); krb5_cc_store_cred(context, ccache, &creds); krb5_free_cred_contents(context, &creds); login: krb5_get_init_creds(context, &creds, client, krb5_initial_prompter_posix, NULL, 0, NULL, NULL); krb5_verify_init_creds(context, &creds, NULL, NULL, &vcc, NULL); /* setuid */ krb5_cc_store_cred(context, ccache, &creds); krb5_cc_copy(context, vcc, ccache); krb5_free_cred_contents(context, &creds); krb5_cc_destroy(context, vcc); xdm: krb5_get_initial_creds(context, &creds, client, krb5_initial_prompter_xt, (void *) &xtstuff, 0, NULL, NULL); krb5_verify_init_creds(context, &creds, NULL, NULL, &vcc, NULL); /* setuid */ krb5_cc_store_cred(context, ccache, &creds); krb5_free_cred_contents(context, &creds); krb5_cc_copy(context, vcc, ccache); krb5_cc_destroy(context, vcc); passwd: krb5_init_creds_opt_init(&options); krb5_init_creds_opt_set_tkt_life = 300; krb5_get_initial_creds(context, &creds, client, krb5_initial_prompter_posix, NULL, 0, "kadmin/changepw", &options); /* change password */ krb5_free_cred_contents(context, &creds); pop3d (simple password validator when no user interation possible): krb5_get_initial_creds(context, &creds, client, NULL, NULL, 0, NULL, NULL); krb5_verify_init_creds(context, &creds, NULL, NULL, &vcc, NULL); krb5_cc_destroy(context, vcc); ================================================================ password expiration has a subtlety. When a password expires and is changed, there is a delay between when the master gets the new key (immediately), and the slaves (propogation interval). So, when getting an in_tkt, if the password is expired, the request should be reissued to the master (this kind of sucks if you have SAM, oh well). If this says expired, too, then the password should be changed, and then the initial ticket request should be issued to the master again. If the master times out, then a message that the password has expired and cannot be changed due to the master being unreachable should be displayed. ================================================================ get_init_creds reads config stuff from: [libdefaults] varname1 = defvalue REALM = { varname1 = value varname2 = value } typedef struct _krb5_get_init_creds_opt { krb5_flags flags; krb5_deltat tkt_life; /* varname = "ticket_lifetime" */ krb5_deltat renew_life; /* varname = "renew_lifetime" */ int forwardable; /* varname = "forwardable" */ int proxiable; /* varname = "proxiable" */ krb5_enctype *etype_list; /* varname = "default_tkt_enctypes" */ int etype_list_length; krb5_address **address_list; /* no varname */ krb5_preauthtype *preauth_list; /* no varname */ int preauth_list_length; krb5_data *salt; } krb5_get_init_creds_opt; heimdal-7.5.0/doc/hdb.din0000644000175000017500000000057212136107747013264 0ustar niknik# Doxyfile 1.5.3 PROJECT_NAME = Heimdal hdb library PROJECT_NUMBER = @PACKAGE_VERSION@ OUTPUT_DIRECTORY = @srcdir@/doxyout/hdb INPUT = @srcdir@/../lib/hdb WARN_IF_UNDOCUMENTED = YES PERL_PATH = /usr/bin/perl HTML_HEADER = "@srcdir@/header.html" HTML_FOOTER = "@srcdir@/footer.html" @INCLUDE = "@srcdir@/doxytmpl.dxy" heimdal-7.5.0/doc/setup.texi0000644000175000017500000017043713212137553014070 0ustar niknik@c $Id$ @node Setting up a realm, Applications, Building and Installing, Top @chapter Setting up a realm A @cindex realm realm is an administrative domain. The name of a Kerberos realm is usually the Internet domain name in uppercase. Call your realm the same as your Internet domain name if you do not have strong reasons for not doing so. It will make life easier for you and everyone else. @menu * Configuration file:: * Creating the database:: * Modifying the database:: * Checking the setup:: * keytabs:: * Remote administration:: * Password changing:: * Testing clients and servers:: * Slave Servers:: * Incremental propagation:: * Encryption types and salting:: * Credential cache server - KCM:: * Cross realm:: * Transit policy:: * Setting up DNS:: * Using LDAP to store the database:: * Providing Kerberos credentials to servers and programs:: * Setting up PK-INIT:: * Debugging Kerberos problems:: @end menu @node Configuration file, Creating the database, Setting up a realm, Setting up a realm @section Configuration file To setup a realm you will first have to create a configuration file: @file{/etc/krb5.conf}. The @file{krb5.conf} file can contain many configuration options, some of which are described here. There is a sample @file{krb5.conf} supplied with the distribution. The configuration file is a hierarchical structure consisting of sections, each containing a list of bindings (either variable assignments or subsections). A section starts with @samp{[@samp{section-name}]}. A binding consists of a left hand side, an equal sign (@samp{=}) and a right hand side (the left hand side tag must be separated from the equal sign with some whitespace). Subsections have a @samp{@{} as the first non-whitespace character after the equal sign. All other bindings are treated as variable assignments. The value of a variable extends to the end of the line. @example [section1] a-subsection = @{ var = value1 other-var = value with @{@} sub-sub-section = @{ var = 123 @} @} var = some other value [section2] var = yet another value @end example In this manual, names of sections and bindings will be given as strings separated by slashes (@samp{/}). The @samp{other-var} variable will thus be @samp{section1/a-subsection/other-var}. For in-depth information about the contents of the configuration file, refer to the @file{krb5.conf} manual page. Some of the more important sections are briefly described here. The @samp{libdefaults} section contains a list of library configuration parameters, such as the default realm and the timeout for KDC responses. The @samp{realms} section contains information about specific realms, such as where they hide their KDC@. This section serves the same purpose as the Kerberos 4 @file{krb.conf} file, but can contain more information. Finally the @samp{domain_realm} section contains a list of mappings from domains to realms, equivalent to the Kerberos 4 @file{krb.realms} file. To continue with the realm setup, you will have to create a configuration file, with contents similar to the following. @example [libdefaults] default_realm = MY.REALM [realms] MY.REALM = @{ kdc = my.kdc my.slave.kdc kdc = my.third.kdc kdc = 130.237.237.17 kdc = [2001:6b0:1:ea::100]:88 @} [domain_realm] .my.domain = MY.REALM @end example If you use a realm name equal to your domain name, you can omit the @samp{libdefaults}, and @samp{domain_realm}, sections. If you have a DNS SRV-record for your realm, or your Kerberos server has DNS CNAME @samp{kerberos.my.realm}, you can omit the @samp{realms} section too. @cindex KRB5_CONFIG If you want to use a different configuration file then the default you can point a file with the environment variable @samp{KRB5_CONFIG}. @example env KRB5_CONFIG=$HOME/etc/krb5.conf kinit user@@REALM @end example @node Creating the database, Modifying the database, Configuration file, Setting up a realm @section Creating the database The database library will look for the database in the directory @file{@value{dbdir}}, so you should probably create that directory. Make sure the directory has restrictive permissions. @example # mkdir /var/heimdal # chmod og-rwx /var/heimdal @end example Heimdal supports various database backends: lmdb (LMDB), db3 (Berkeley DB 3.x, 4.x, or 5.x), db1 (Berkeley DB 2.x), sqlite (SQLite3), and ldap (LDAP). The default is @value{dbtype}, and is selected at build time from one of lmdb, db3, or db1. These defaults can be overriden in the 'database' key in the @samp{kdc} section of the configuration. @example [kdc] database = @{ dbname = lmdb:/path/to/db-file realm = REALM acl_file = /path/to/kadmind.acl mkey_file = /path/to/mkey log_file = /path/to/iprop-log-file @} @end example To use LDAP, see @xref{Using LDAP to store the database}. The keys of all the principals are stored in the database. If you choose to, these can be encrypted with a master key. You do not have to remember this key (or password), but just to enter it once and it will be stored in a file (@file{/var/heimdal/m-key}). If you want to have a master key, run @samp{kstash} to create this master key: @example # kstash Master key: Verifying password - Master key: @end example If you want to generate a random master key you can use the @kbd{--random-key} flag to kstash. This will make sure you have a good key on which attackers can't do a dictionary attack. If you have a master key, make sure you make a backup of your master key file; without it backups of the database are of no use. To initialise the database use the @command{kadmin} program, with the @kbd{-l} option (to enable local database mode). First issue a @kbd{init MY.REALM} command. This will create the database and insert default principals for that realm. You can have more than one realm in one database, so @samp{init} does not destroy any old database. Before creating the database, @samp{init} will ask you some questions about maximum ticket lifetimes. After creating the database you should probably add yourself to it. You do this with the @samp{add} command. It takes as argument the name of a principal. The principal should contain a realm, so if you haven't set up a default realm, you will need to explicitly include the realm. @example # kadmin -l kadmin> init MY.REALM Realm max ticket life [unlimited]: Realm max renewable ticket life [unlimited]: kadmin> add me Max ticket life [unlimited]: Max renewable life [unlimited]: Attributes []: Password: Verifying password - Password: @end example Now start the KDC and try getting a ticket. @example # kdc & # kinit me me@@MY.REALMS's Password: # klist Credentials cache: /tmp/krb5cc_0 Principal: me@@MY.REALM Issued Expires Principal Aug 25 07:25:55 Aug 25 17:25:55 krbtgt/MY.REALM@@MY.REALM @end example If you are curious you can use the @samp{dump} command to list all the entries in the database. It should look something similar to the following example (note that the entries here are truncated for typographical reasons): @smallexample kadmin> dump me@@MY.REALM 1:0:1:0b01d3cb7c293b57:-:0:7:8aec316b9d1629e3baf8 ... kadmin/admin@@MY.REALM 1:0:1:e5c8a2675b37a443:-:0:7:cb913ebf85 ... krbtgt/MY.REALM@@MY.REALM 1:0:1:52b53b61c875ce16:-:0:7:c8943be ... kadmin/changepw@@MY.REALM 1:0:1:f48c8af2b340e9fb:-:0:7:e3e6088 ... @end smallexample @node Modifying the database, Checking the setup, Creating the database, Setting up a realm @section Modifying the database All modifications of principals are done with with kadmin. A principal has several attributes and lifetimes associated with it. Principals are added, renamed, modified, and deleted with the kadmin commands @samp{add}, @samp{rename}, @samp{modify}, @samp{delete}. Both interactive editing and command line flags can be used (use --help to list the available options). There are different kinds of types for the fields in the database; attributes, absolute time times and relative times. @subsection Attributes When doing interactive editing, attributes are listed with @samp{?}. The attributes are given in a comma (@samp{,}) separated list. Attributes are removed from the list by prefixing them with @samp{-}. @smallexample kadmin> modify me Max ticket life [1 day]: Max renewable life [1 week]: Principal expiration time [never]: Password expiration time [never]: Attributes [disallow-renewable]: requires-pre-auth,-disallow-renewable kadmin> get me Principal: me@@MY.REALM [...] Attributes: requires-pre-auth @end smallexample @subsection Absolute times The format for absolute times are any of the following: @smallexample never now YYYY-mm-dd YYYY-mm-dd HH:MM:SS @end smallexample @subsection Relative times The format for relative times are any of the following combined: @smallexample N year M month O day P hour Q minute R second @end smallexample @c Describe more of kadmin commands here... @node Checking the setup, keytabs, Modifying the database, Setting up a realm @section Checking the setup There are two tools that can check the consistency of the Kerberos configuration file and the Kerberos database. The Kerberos configuration file is checked using @command{verify_krb5_conf}. The tool checks for common errors, but commonly there are several uncommon configuration entries that are never added to the tool and thus generates ``unknown entry'' warnings. This is usually nothing to worry about. The database check is built into the kadmin tool. It will check for common configuration error that will cause problems later. Common check are for existence and flags on important principals. The database check by run by the following command : @example kadmin -l check REALM.EXAMPLE.ORG @end example @node keytabs, Remote administration, Checking the setup, Setting up a realm @section keytabs To extract a service ticket from the database and put it in a keytab, you need to first create the principal in the database with @samp{add} (using the @kbd{--random-key} flag to get a random key) and then extract it with @samp{ext_keytab}. @example kadmin> add --random-key host/my.host.name Max ticket life [unlimited]: Max renewable life [unlimited]: Attributes []: kadmin> ext host/my.host.name kadmin> exit # ktutil list Version Type Principal 1 des-cbc-md5 host/my.host.name@@MY.REALM 1 des-cbc-md4 host/my.host.name@@MY.REALM 1 des-cbc-crc host/my.host.name@@MY.REALM 1 des3-cbc-sha1 host/my.host.name@@MY.REALM @end example @node Remote administration, Password changing, keytabs, Setting up a realm @section Remote administration The administration server, @command{kadmind}, can be started by @command{inetd} (which isn't recommended) or run as a normal daemon. If you want to start it from @command{inetd} you should add a line similar to the one below to your @file{/etc/inetd.conf}. @example kerberos-adm stream tcp nowait root /usr/heimdal/libexec/kadmind kadmind @end example You might need to add @samp{kerberos-adm} to your @file{/etc/services} as @samp{749/tcp}. Access to the administration server is controlled by an ACL file, (default @file{/var/heimdal/kadmind.acl}.) The file has the following syntax: @smallexample principal [priv1,priv2,...] [glob-pattern] @end smallexample The matching is from top to bottom for matching principals (and if given, glob-pattern). When there is a match, the access rights of that line are applied. The privileges you can assign to a principal are: @samp{add}, @samp{change-password} (or @samp{cpw} for short), @samp{delete}, @samp{get}, @samp{list}, and @samp{modify}, or the special privilege @samp{all}. All of these roughly correspond to the different commands in @command{kadmin}. If a @var{glob-pattern} is given on a line, it restricts the access rights for the principal to only apply for subjects that match the pattern. The patterns are of the same type as those used in shell globbing, see @url{none,,fnmatch(3)}. In the example below @samp{lha/admin} can change every principal in the database. @samp{jimmy/admin} can only modify principals that belong to the realm @samp{E.KTH.SE}. @samp{mille/admin} is working at the help desk, so he should only be able to change the passwords for single component principals (ordinary users). He will not be able to change any @samp{/admin} principal. @example lha/admin@@E.KTH.SE all jimmy/admin@@E.KTH.SE all *@@E.KTH.SE jimmy/admin@@E.KTH.SE all */*@@E.KTH.SE mille/admin@@E.KTH.SE change-password *@@E.KTH.SE @end example @node Password changing, Testing clients and servers, Remote administration, Setting up a realm @section Password changing To allow users to change their passwords, you should run @command{kpasswdd}. It is not run from @command{inetd}. You might need to add @samp{kpasswd} to your @file{/etc/services} as @samp{464/udp}. If your realm is not setup to use DNS, you might also need to add a @samp{kpasswd_server} entry to the realm configuration in @file{/etc/krb5.conf} on client machines: @example [realms] MY.REALM = @{ kdc = my.kdc my.slave.kdc kpasswd_server = my.kdc @} @end example @subsection Password quality assurance It is important that users have good passwords, both to make it harder to guess them and to avoid off-line attacks (although pre-authentication provides some defence against off-line attacks). To ensure that the users choose good passwords, you can enable password quality controls in @command{kpasswdd} and @command{kadmind}. The controls themselves are done in a shared library or an external program that is used by @command{kpasswdd}. To configure in these controls, add lines similar to the following to your @file{/etc/krb5.conf}: @example [password_quality] policies = external-check builtin:minimum-length modulename:policyname external_program = /bin/false policy_libraries = @var{library1.so} @var{library2.so} @end example In @samp{[password_quality]policies} the module name is optional if the policy name is unique in all modules (members of @samp{policy_libraries}). All built-in policies can be qualified with a module name of @samp{builtin} to unambiguously specify the built-in policy and not a policy by the same name from a loaded module. The built-in policies are @itemize @bullet @item external-check Executes the program specified by @samp{[password_quality]external_program}. A number of key/value pairs are passed as input to the program, one per line, ending with the string @samp{end}. The key/value lines are of the form @example principal: @var{principal} new-password: @var{password} @end example where @var{password} is the password to check for the previous @var{principal}. If the external application approves the password, it should return @samp{APPROVED} on standard out and exit with exit code 0. If it doesn't approve the password, an one line error message explaining the problem should be returned on standard error and the application should exit with exit code 0. In case of a fatal error, the application should, if possible, print an error message on standard error and exit with a non-zero error code. @item minimum-length The minimum length password quality check reads the configuration file stanza @samp{[password_quality]min_length} and requires the password to be at least this length. @item character-class The character-class password quality check reads the configuration file stanza @samp{[password_quality]min_classes}. The policy requires the password to have characters from at least that many character classes. Default value if not given is 3. The four different characters classes are, uppercase, lowercase, number, special characters. @end itemize If you want to write your own shared object to check password policies, see the manual page @manpage{kadm5_pwcheck,3}. Code for a password quality checking function that uses the cracklib library can be found in @file{lib/kadm5/sample_password_check.c} in the source code distribution. It requires that the cracklib library be built with the patch available at @url{ftp://ftp.pdc.kth.se/pub/krb/src/cracklib.patch}. A sample policy external program is included in @file{lib/kadm5/check-cracklib.pl}. If no password quality checking function is configured, the only check performed is that the password is at least six characters long. To check the password policy settings, use the command @command{verify-password-quality} in @command{kadmin} program. The password verification is only performed locally, on the client. It may be convenient to set the environment variable @samp{KRB5_CONFIG} to point to a test version of @file{krb5.conf} while you're testing the @samp{[password_quality]} stanza that way. @node Testing clients and servers, Slave Servers, Password changing, Setting up a realm @section Testing clients and servers Now you should be able to run all the clients and servers. Refer to the appropriate man pages for information on how to use them. @node Slave Servers, Incremental propagation, Testing clients and servers, Setting up a realm @section Slave servers, Incremental propagation, Testing clients and servers, Setting up a realm It is desirable to have at least one backup (slave) server in case the master server fails. It is possible to have any number of such slave servers but more than three usually doesn't buy much more redundancy. All Kerberos servers for a realm must have the same database so that they present the same service to the users. The @pindex hprop @command{hprop} program, running on the master, will propagate the database to the slaves, running @pindex hpropd @command{hpropd} processes. Every slave needs a database directory, the master key (if it was used for the database) and a keytab with the principal @samp{hprop/@var{hostname}}. Add the principal with the @pindex ktutil @command{ktutil} command and start @pindex hpropd @command{hpropd}, as follows: @example slave# ktutil get -p foo/admin hprop/`hostname` slave# mkdir /var/heimdal slave# hpropd @end example The master will use the principal @samp{kadmin/hprop} to authenticate to the slaves. This principal should be added when running @kbd{kadmin -l init} but if you do not have it in your database for whatever reason, please add it with @kbd{kadmin -l add}. Then run @pindex hprop @code{hprop} on the master: @example master# hprop slave @end example This was just an hands-on example to make sure that everything was working properly. Doing it manually is of course the wrong way, and to automate this you will want to start @pindex hpropd @command{hpropd} from @command{inetd} on the slave(s) and regularly run @pindex hprop @command{hprop} on the master to regularly propagate the database. Starting the propagation once an hour from @command{cron} is probably a good idea. @node Incremental propagation, Encryption types and salting, Slave Servers, Setting up a realm @section Incremental propagation There is also a newer mechanism for doing incremental propagation in Heimdal. Instead of sending the whole database regularly, it sends the changes as they happen on the master to the slaves. The master keeps track of all the changes by assigning a version number to every change to the database. The slaves know which was the latest version they saw and in this way it can be determined if they are in sync or not. A log of all the changes is kept on the master, and when a slave is at an older version than the oldest one in the log, the whole database has to be sent. Protocol-wise, all the slaves connect to the master and as a greeting tell it the latest version that they have (@samp{IHAVE} message). The master then responds by sending all the changes between that version and the current version at the master (a series of @samp{FORYOU} messages) or the whole database in a @samp{TELLYOUEVERYTHING} message. There is also a keep-alive protocol that makes sure all slaves are up and running. In addition on listening on the network to get connection from new slaves, the ipropd-master also listens on a status unix socket. kadmind and kpasswdd both open that socket when a transation is done and written a notification to the socket. That cause ipropd-master to check for new version in the log file. As a fallback in case a notification is lost by the unix socket, the log file is checked after 30 seconds of no event. @subsection Configuring incremental propagation The program that runs on the master is @command{ipropd-master} and all clients run @command{ipropd-slave}. Create the file @file{/var/heimdal/slaves} on the master containing all the slaves that the database should be propagated to. Each line contains the full name of the principal (for example @samp{iprop/hemligare.foo.se@@FOO.SE}). You should already have @samp{iprop/tcp} defined as 2121, in your @file{/etc/services}. Otherwise, or if you need to use a different port for some peculiar reason, you can use the @kbd{--port} option. This is useful when you have multiple realms to distribute from one server. Then you need to create those principals that you added in the configuration file. Create one @samp{iprop/hostname} for the master and for every slave. @example master# /usr/heimdal/sbin/ktutil get iprop/`hostname` @end example @example slave# /usr/heimdal/sbin/ktutil get iprop/`hostname` @end example The next step is to start the @command{ipropd-master} process on the master server. The @command{ipropd-master} listens on the UNIX domain socket @file{/var/heimdal/signal} to know when changes have been made to the database so they can be propagated to the slaves. There is also a safety feature of testing the version number regularly (every 30 seconds) to see if it has been modified by some means that do not raise this signal. Then, start @command{ipropd-slave} on all the slaves: @example master# /usr/heimdal/libexec/ipropd-master & slave# /usr/heimdal/libexec/ipropd-slave master & @end example To manage the iprop log file you should use the @command{iprop-log} command. With it you can dump, truncate and replay the logfile. @subsection Status of iprop master and slave Both the master and slave provides status of the world as they see it. The master write outs the current status of the slaves, last seen and their version number in @file{/var/heimdal/slaves-stats}. The slave write out the current status in @file{/var/heimdal/ipropd-slave-status}. These locations can be changed with command line options, and in the case of @command{ipropd_master}, the configuration file. @node Encryption types and salting, Credential cache server - KCM, Incremental propagation, Setting up a realm @section Encryption types and salting @cindex Salting @cindex Encryption types The encryption types that the KDC is going to assign by default is possible to change. Since the keys used for user authentication is salted the encryption types are described together with the salt strings. Salting is used to make it harder to pre-calculate all possible keys. Using a salt increases the search space to make it almost impossible to pre-calculate all keys. Salting is the process of mixing a public string (the salt) with the password, then sending it through an encryption type specific string-to-key function that will output the fixed size encryption key. In Kerberos 5 the salt is determined by the encryption type, except in some special cases. In @code{des} there is the Kerberos 4 salt (none at all) or the afs-salt (using the cell (realm in AFS lingo)). In @code{arcfour} (the encryption type that Microsoft Windows 2000 uses) there is no salt. This is to be compatible with NTLM keys in Windows NT 4. @code{[kadmin]default_keys} in @file{krb5.conf} controls what salting to use. The syntax of @code{[kadmin]default_keys} is @samp{[etype:]salt-type[:salt-string]}. @samp{etype} is the encryption type (des-cbc-crc, arcfour-hmac-md5, aes256-cts-hmac-sha1-96), @code{salt-type} is the type of salt (pw-salt or afs3-salt), and the salt-string is the string that will be used as salt (remember that if the salt is appended/prepended, the empty salt "" is the same thing as no salt at all). Common types of salting include @itemize @bullet @item @code{v4} (or @code{des:pw-salt:}) The Kerberos 4 salting is using no salt at all. Reason there is colon at the end of the salt string is that it makes the salt the empty string (same as no salt). @item @code{v5} (or @code{pw-salt}) @code{pw-salt} uses the default salt for each encryption type is specified for. If the encryption type @samp{etype} isn't given, all default encryption will be used. @item @code{afs3-salt} @code{afs3-salt} is the salt that is used with Transarc kaserver. It's the cell name appended to the password. @end itemize @node Credential cache server - KCM, Cross realm, Encryption types and salting, Setting up a realm @section Credential cache server - KCM @cindex KCM @cindex Credential cache server When KCM running is easy for users to switch between different kerberos principals using @file{kswitch} or built in support in application, like OpenSSH's GSSAPIClientIdentity. Other advantages are that there is the long term credentials are not written to disk and on reboot the credential is removed when kcm process stopps running. Configure the system startup script to start the kcm process, @file{/usr/heimdal/libexec/kcm} and then configure the system to use kcm in @file{krb5.conf}. @example [libdefaults] default_cc_type = KCM @end example Now when you run @command{kinit} it doesn't overwrite your existing credentials but rather just add them to the set of credentials. @command{klist -l} lists the credentials and the star marks the default credential. @example $ kinit lha@@KTH.SE lha@@KTH.SE's Password: $ klist -l Name Cache name Expires lha@@KTH.SE 0 Nov 22 23:09:40 * lha@@SU.SE Initial default ccache Nov 22 14:14:24 @end example When switching between credentials you can use @command{kswitch}. @example $ kswitch -i Principal 1 lha@@KTH.SE 2 lha@@SU.SE Select number: 2 @end example After switching, a new set of credentials are used as default. @example $ klist -l Name Cache name Expires lha@@SU.SE Initial default ccache Nov 22 14:14:24 * lha@@KTH.SE 0 Nov 22 23:09:40 @end example Som applications, like openssh with Simon Wilkinsons patch applied, support specifiying that credential to use. The example below will login to the host computer.kth.se using lha@@KTH.SE (not the current default credential). @example $ ssh \ -o GSSAPIAuthentication=yes \ -o GSSAPIKeyExchange=yes \ -o GSSAPIClientIdentity=lha@@KTH.SE \ computer.kth.se @end example @node Cross realm, Transit policy, Credential cache server - KCM, Setting up a realm @section Cross realm @cindex Cross realm Suppose you reside in the realm @samp{MY.REALM}, how do you authenticate to a server in @samp{OTHER.REALM}? Having valid tickets in @samp{MY.REALM} allows you to communicate with Kerberised services in that realm. However, the computer in the other realm does not have a secret key shared with the Kerberos server in your realm. It is possible to share keys between two realms that trust each other. When a client program, such as @command{telnet} or @command{ssh}, finds that the other computer is in a different realm, it will try to get a ticket granting ticket for that other realm, but from the local Kerberos server. With that ticket granting ticket, it will then obtain service tickets from the Kerberos server in the other realm. For a two way trust between @samp{MY.REALM} and @samp{OTHER.REALM} add the following principals to each realm. The principals should be @samp{krbtgt/OTHER.REALM@@MY.REALM} and @samp{krbtgt/MY.REALM@@OTHER.REALM} in @samp{MY.REALM}, and @samp{krbtgt/MY.REALM@@OTHER.REALM} and @samp{krbtgt/OTHER.REALM@@MY.REALM}in @samp{OTHER.REALM}. In Kerberos 5 the trust can be configured to be one way. So that users from @samp{MY.REALM} can authenticate to services in @samp{OTHER.REALM}, but not the opposite. In the example above, the @samp{krbtgt/MY.REALM@@OTHER.REALM} then should be removed. The two principals must have the same key, key version number, and the same set of encryption types. Remember to transfer the two keys in a safe manner. @example vr$ klist Credentials cache: FILE:/tmp/krb5cc_913.console Principal: lha@@E.KTH.SE Issued Expires Principal May 3 13:55:52 May 3 23:55:54 krbtgt/E.KTH.SE@@E.KTH.SE vr$ telnet -l lha hummel.it.su.se Trying 2001:6b0:5:1095:250:fcff:fe24:dbf... Connected to hummel.it.su.se. Escape character is '^]'. Waiting for encryption to be negotiated... [ Trying mutual KERBEROS5 (host/hummel.it.su.se@@SU.SE)... ] [ Kerberos V5 accepts you as ``lha@@E.KTH.SE'' ] Encryption negotiated. Last login: Sat May 3 14:11:47 from vr.l.nxs.se hummel$ exit vr$ klist Credentials cache: FILE:/tmp/krb5cc_913.console Principal: lha@@E.KTH.SE Issued Expires Principal May 3 13:55:52 May 3 23:55:54 krbtgt/E.KTH.SE@@E.KTH.SE May 3 13:55:56 May 3 23:55:54 krbtgt/SU.SE@@E.KTH.SE May 3 14:10:54 May 3 23:55:54 host/hummel.it.su.se@@SU.SE @end example @node Transit policy, Setting up DNS, Cross realm, Setting up a realm @section Transit policy @cindex Transit policy Under some circumstances, you may not wish to set up direct cross-realm trust with every realm to which you wish to authenticate or from which you wish to accept authentications. Kerberos supports multi-hop cross-realm trust where a client principal in realm A authenticates to a service in realm C through a realm B with which both A and C have cross-realm trust relationships. In this situation, A and C need not set up cross-realm principals between each other. If you want to use cross-realm authentication through an intermediate realm, it must be explicitly allowed by either the KDCs for the realm to which the client is authenticating (in this case, realm C), or the server receiving the request. This is done in @file{krb5.conf} in the @code{[capaths]} section. In addition, the client in realm A need to be configured to know how to reach realm C via realm B. This can be done either on the client or via KDC configuration in the KDC for realm A. @subsection Allowing cross-realm transits When the ticket transits through a realm to another realm, the destination realm adds its peer to the "transited-realms" field in the ticket. The field is unordered, since there is no way to know if know if one of the transited-realms changed the order of the list. For the authentication to be accepted by the final destination realm, all of the transited realms must be listed as trusted in the @code{[capaths]} configuration, either in the KDC for the destination realm or on the server receiving the authentication. The syntax for @code{[capaths]} section is: @example [capaths] CLIENT-REALM = @{ SERVER-REALM = PERMITTED-CROSS-REALMS ... @} @end example In the following example, the realm @code{STACKEN.KTH.SE} only has direct cross-realm set up with @code{KTH.SE}. @code{KTH.SE} has direct cross-realm set up with @code{STACKEN.KTH.SE} and @code{SU.SE}. @code{DSV.SU.SE} only has direct cross-realm set up with @code{SU.SE}. The goal is to allow principals in the @code{DSV.SU.SE} or @code{SU.SE} realms to authenticate to services in @code{STACKEN.KTH.SE}. This is done with the following @code{[capaths]} entry on either the server accepting authentication or on the KDC for @code{STACKEN.KTH.SE}. @example [capaths] SU.SE = @{ STACKEN.KTH.SE = KTH.SE @} DSV.SU.SE = @{ STACKEN.KTH.SE = SU.SE KTH.SE @} @end example The first entry allows cross-realm authentication from clients in @code{SU.SE} transiting through @code{KTH.SE} to @code{STACKEN.KTH.SE}. The second entry allows cross-realm authentication from clients in @code{DSV.SU.SE} transiting through both @code{SU.SE} and @code{KTH.SE} to @code{STACKEN.KTH.SE}. Be careful of which realm goes where; it's easy to put realms in the wrong place. The block is tagged with the client realm (the realm of the principal authenticating), and the realm before the equal sign is the final destination realm: the realm to which the client is authenticating. After the equal sign go all the realms that the client transits through. The order of the @code{PERMITTED-CROSS-REALMS} is not important when doing transit cross realm verification. @subsection Configuring client cross-realm transits The @code{[capaths]} section is also used for another purpose: to tell clients which realm to transit through to reach a realm with which their local realm does not have cross-realm trust. This can be done by either putting a @code{[capaths]} entry in the configuration of the client or by putting the entry in the configuration of the KDC for the client's local realm. In the latter case, the KDC will then hand back a referral to the client when the client requests a cross-realm ticket to the destination realm, telling the client to try to go through an intermediate realm. For client configuration, the order of @code{PERMITTED-CROSS-REALMS} is significant, since only the first realm in this section (after the equal sign) is used by the client. For example, again consider the @code{[capaths]} entry above for the case of a client in the @code{SU.SE} realm, and assume that the client or the @code{SU.SE} KDC has that @code{[capaths]} entry. If the client attempts to authenticate to a service in the @code{STACKEN.KTH.SE} realm, that entry says to first authenticate cross-realm to the @code{KTH.SE} realm (the first realm listed in the @code{PERMITTED-CROSS-REALMS} section), and then from there to @code{STACKEN.KTH.SE}. Each entry in @code{[capaths]} can only give the next hop, since only the first realm in @code{PERMITTED-CROSS-REALMS} is used. If, for instance, a client in @code{DSV.SU.SE} had a @code{[capaths]} configuration as above but without the first block for @code{SU.SE}, they would not be able to reach @code{STACKEN.KTH.SE}. They would get as far as @code{SU.SE} based on the @code{DSV.SU.SE} entry in @code{[capaths]} and then attempt to go directly from there to @code{STACKEN.KTH.SE} and get stuck (unless, of course, the @code{SU.SE} KDC had the additional entry required to tell the client to go through @code{KTH.SE}). @subsection Active Directory forest example One common place where a @code{[capaths]} configuration is desirable is with Windows Active Directory forests. One common Active Directory configuration is to have one top-level Active Directory realm but then divide systems, services, and users into child realms (perhaps based on organizational unit). One generally establishes cross-realm trust only with the top-level realm, and then uses transit policy to permit authentications to and from the child realms. For example, suppose an organization has a Heimdal realm @code{EXAMPLE.COM}, a Windows Active Directory realm @code{WIN.EXAMPLE.COM}, and then child Active Directory realms @code{ENGR.WIN.EXAMPLE.COM} and @code{SALES.WIN.EXAMPLE.COM}. The goal is to allow users in any of these realms to authenticate to services in any of these realms. The @code{EXAMPLE.COM} KDC (and possibly client) configuration should therefore contain a @code{[capaths]} section as follows: @example [capaths] ENGR.WIN.EXAMPLE.COM = @{ EXAMPLE.COM = WIN.EXAMPLE.COM @} SALES.WIN.EXAMPLE.COM = @{ EXAMPLE.COM = WIN.EXAMPLE.COM @} EXAMPLE.COM = @{ ENGR.WIN.EXAMPLE.COM = WIN.EXAMPLE.COM SALES.WIN.EXAMPLE.COM = WIN.EXAMPLE.COM @} @end example The first two blocks allow clients in the @code{ENGR.WIN.EXAMPLE.COM} and @code{SALES.WIN.EXAMPLE.COM} realms to authenticate to services in the @code{EXAMPLE.COM} realm. The third block tells the client (or tells the KDC to tell the client via referrals) to transit through @code{WIN.EXAMPLE.COM} to reach these realms. Both sides of the configuration are needed for bi-directional transited cross-realm authentication. @c To test the cross realm configuration, use: @c kmumble transit-check client server transit-realms ... @node Setting up DNS, Using LDAP to store the database, Transit policy, Setting up a realm @section Setting up DNS @cindex Setting up DNS @subsection Using DNS to find KDC If there is information about where to find the KDC or kadmind for a realm in the @file{krb5.conf} for a realm, that information will be preferred, and DNS will not be queried. Heimdal will try to use DNS to find the KDCs for a realm. First it will try to find a @code{SRV} resource record (RR) for the realm. If no SRV RRs are found, it will fall back to looking for an @code{A} RR for a machine named kerberos.REALM, and then kerberos-1.REALM, etc Adding this information to DNS minimises the client configuration (in the common case, resulting in no configuration needed) and allows the system administrator to change the number of KDCs and on what machines they are running without caring about clients. The downside of using DNS is that the client might be fooled to use the wrong server if someone fakes DNS replies/data, but storing the IP addresses of the KDC on all the clients makes it very hard to change the infrastructure. An example of the configuration for the realm @code{EXAMPLE.COM}: @example $ORIGIN example.com. _kerberos._tcp SRV 10 1 88 kerberos.example.com. _kerberos._udp SRV 10 1 88 kerberos.example.com. _kerberos._tcp SRV 10 1 88 kerberos-1.example.com. _kerberos._udp SRV 10 1 88 kerberos-1.example.com. _kpasswd._udp SRV 10 1 464 kerberos.example.com. _kerberos-adm._tcp SRV 10 1 749 kerberos.example.com. @end example More information about DNS SRV resource records can be found in RFC-2782 (A DNS RR for specifying the location of services (DNS SRV)). @subsection Using DNS to map hostname to Kerberos realm Heimdal also supports a way to lookup a realm from a hostname. This to minimise configuration needed on clients. Using this has the drawback that clients can be redirected by an attacker to realms within the same cross realm trust and made to believe they are talking to the right server (since Kerberos authentication will succeed). An example configuration that informs clients that for the realms it.example.com and srv.example.com, they should use the realm EXAMPLE.COM: @example $ORIGIN example.com. _kerberos.it TXT "EXAMPLE.COM" _kerberos.srv TXT "EXAMPLE.COM" @end example @node Using LDAP to store the database, Providing Kerberos credentials to servers and programs, Setting up DNS, Setting up a realm @section Using LDAP to store the database @cindex Using the LDAP backend This document describes how to install the LDAP backend for Heimdal. Note that before attempting to configure such an installation, you should be aware of the implications of storing private information (such as users' keys) in a directory service primarily designed for public information. Nonetheless, with a suitable authorisation policy, it is possible to set this up in a secure fashion. A knowledge of LDAP, Kerberos, and C is necessary to install this backend. The HDB schema was devised by Leif Johansson. This assumes, OpenLDAP 2.3 or later. Requirements: @itemize @bullet @item A current release of Heimdal, configured with @code{--with-openldap=/usr/local} (adjust according to where you have installed OpenLDAP). You can verify that you manage to configure LDAP support by running @file{kdc --builtin-hdb}, and checking that @samp{ldap:} is one entry in the list. Its also possible to configure the ldap backend as a shared module, see option --hdb-openldap-module to configure. @item Optionally configure OpenLDAP with @kbd{--enable-local} to enable the local transport. @item Add the hdb schema to the LDAP server, it's included in the source-tree in @file{lib/hdb/hdb.schema}. Example from slapd.conf: @example include /usr/local/etc/openldap/schema/hdb.schema @end example @item Configure the LDAP server ACLs to accept writes from clients. For example: @example access to * by dn.exact="uid=heimdal,dc=services,dc=example,dc=com" write ... authz-regexp "gidNumber=.*\\\+uidNumber=0,cn=peercred,cn=external,cn=auth'' "uid=heimdal,dc=services,dc=example,dc=com" @end example The sasl-regexp is for mapping between the SASL/EXTERNAL and a user in a tree. The user that the key is mapped to should be have a krb5Principal aux object with krb5PrincipalName set so that the ``creator'' and ``modifier'' is right in @file{kadmin}. Another option is to create an admins group and add the dn to that group. If a non-local LDAP connection is used, the authz-regexp is not needed as Heimdal will bind to LDAP over the network using provided credentials. Since Heimdal talks to the LDAP server over a UNIX domain socket when configured for ldapi:///, and uses external sasl authentication, it's not possible to require security layer quality (ssf in cyrus-sasl lingo). So that requirement has to be turned off in OpenLDAP @command{slapd} configuration file @file{slapd.conf}. @example sasl-secprops minssf=0 @end example @item Start @command{slapd} with the local listener (as well as the default TCP/IP listener on port 389) as follows: @example slapd -h "ldapi:/// ldap:///" @end example Note: These is a bug in @command{slapd} where it appears to corrupt the krb5Key binary attribute on shutdown. This may be related to our use of the V3 schema definition syntax instead of the old UMich-style, V2 syntax. @item You should specify the distinguished name under which your principals will be stored in @file{krb5.conf}. Also you need to enter the path to the kadmin acl file: @example [kdc] # Optional configuration hdb-ldap-structural-object = inetOrgPerson hdb-ldap-url = ldapi:/// (default), ldap://hostname or ldaps://hostname hdb-ldap-secret-file = /path/to/file/containing/ldap/credentials hdb-ldap-start-tls = false database = @{ dbname = ldap:ou=KerberosPrincipals,dc=example,dc=com acl_file = /path/to/kadmind.acl mkey_file = /path/to/mkey @} @end example @samp{mkey_file} can be excluded if you feel that you trust your ldap directory to have the raw keys inside it. The hdb-ldap-structural-object is not necessary if you do not need Samba comatibility. If connecting to a server over a non-local transport, the @samp{hdb-ldap-url} and @samp{hdb-ldap-secret-file} options must be provided. The @samp{hdb-ldap-secret-file} must contain the bind credentials: @example [kdc] hdb-ldap-bind-dn = uid=heimdal,dc=services,dc=example,dc=com hdb-ldap-bind-password = secretBindPassword @end example The @samp{hdb-ldap-secret-file} and should be protected with appropriate file permissions @item Once you have built Heimdal and started the LDAP server, run kadmin (as usual) to initialise the database. Note that the instructions for stashing a master key are as per any Heimdal installation. @example kdc# kadmin -l kadmin> init EXAMPLE.COM Realm max ticket life [unlimited]: Realm max renewable ticket life [unlimited]: kadmin> add lukeh Max ticket life [1 day]: Max renewable life [1 week]: Principal expiration time [never]: Password expiration time [never]: Attributes []: lukeh@@EXAMPLE.COM's Password: Verifying password - lukeh@@EXAMPLE.COM's Password: kadmin> exit @end example Verify that the principal database has indeed been stored in the directory with the following command: @example kdc# ldapsearch -L -h localhost -D cn=manager \ -w secret -b ou=KerberosPrincipals,dc=example,dc=com \ 'objectclass=krb5KDCEntry' @end example @item Now consider adding indexes to the database to speed up the access, at least theses should be added to slapd.conf. @example index objectClass eq index cn eq,sub,pres index uid eq,sub,pres index displayName eq,sub,pres index krb5PrincipalName eq @end example @end itemize @subsection smbk5pwd overlay The smbk5pwd overlay, updates the krb5Key and krb5KeyVersionNumber appropriately when it receives an LDAP Password change Extended Operation: @url{http://www.openldap.org/devel/cvsweb.cgi/contrib/slapd-modules/smbk5pwd/README?hideattic=1&sortbydate=0} @subsection Troubleshooting guide @url{https://sec.miljovern.no/bin/view/Info/TroubleshootingGuide} @subsection Using Samba LDAP password database @cindex Samba @c @node Using Samba LDAP password database, Providing Kerberos credentials to servers and programs, Using LDAP to store the database, Setting up a realm @c @section Using Samba LDAP password database The Samba domain and the Kerberos realm can have different names since arcfour's string to key functions principal/realm independent. So now will be your first and only chance name your Kerberos realm without needing to deal with old configuration files. First, you should set up Samba and get that working with LDAP backend. Now you can proceed as in @xref{Using LDAP to store the database}. Heimdal will pick up the Samba LDAP entries if they are in the same search space as the Kerberos entries. @node Providing Kerberos credentials to servers and programs, Setting up PK-INIT, Using LDAP to store the database, Setting up a realm @section Providing Kerberos credentials to servers and programs Some services require Kerberos credentials when they start to make connections to other services or need to use them when they have started. The easiest way to get tickets for a service is to store the key in a keytab. Both ktutil get and kadmin ext can be used to get a keytab. ktutil get is better in that way it changes the key/password for the user. This is also the problem with ktutil. If ktutil is used for the same service principal on several hosts, they keytab will only be useful on the last host. In that case, run the extract command on one host and then securely copy the keytab around to all other hosts that need it. @example host# ktutil -k /etc/krb5-service.keytab \ get -p lha/admin@@EXAMPLE.ORG service-principal@@EXAMPLE.ORG lha/admin@@EXAMPLE.ORG's Password: @end example To get a Kerberos credential file for the service, use kinit in the @kbd{--keytab} mode. This will not ask for a password but instead fetch the key from the keytab. @example service@@host$ kinit --cache=/var/run/service_krb5_cache \ --keytab=/etc/krb5-service.keytab \ service-principal@@EXAMPLE.ORG @end example Long running services might need credentials longer then the expiration time of the tickets. kinit can run in a mode that refreshes the tickets before they expire. This is useful for services that write into AFS and other distributed file systems using Kerberos. To run the long running script, just append the program and arguments (if any) after the principal. kinit will stop refreshing credentials and remove the credentials when the script-to-start-service exits. @example service@@host$ kinit --cache=/var/run/service_krb5_cache \ --keytab=/etc/krb5-service.keytab \ service-principal@@EXAMPLE.ORG \ script-to-start-service argument1 argument2 @end example @node Setting up PK-INIT, Debugging Kerberos problems, Providing Kerberos credentials to servers and programs, Setting up a realm @section Setting up PK-INIT PK-INIT leverages an existing PKI (public key infrastructure), using certificates to get the initial ticket (usually the krbtgt ticket-granting ticket). To use PK-INIT you must first have a PKI. If you don't have one, it is time to create it. You should first read the whole current chapter of the document to see the requirements imposed on the CA software. A mapping between the PKI certificate and what principals that certificate is allowed to use must exist. There are several ways to do this. The administrator can use a configuration file, store the principal in the SubjectAltName extension of the certificate, or store the mapping in the principals entry in the kerberos database. @section Certificates This and following subsection documents the requirements on the KDC and client certificates and the format used in the id-pkinit-san OtherName extension. On how to create certificates, you should read @ref{Use OpenSSL to create certificates}. @subsection KDC certificate The certificate for the KDC has several requirements. First, the certificate should have an Extended Key Usage (EKU) id-pkkdcekuoid (1.3.6.1.5.2.3.5) set. Second, there must be a subjectAltName otherName using OID id-pkinit-san (1.3.6.1.5.2.2) in the type field and a DER encoded KRB5PrincipalName that matches the name of the TGS of the target realm. Also, if the certificate has a nameConstraints extension with a Generalname with dNSName or iPAdress, it must match the hostname or adress of the KDC. The client is not required by the standard to check the server certificate for this information if the client has external information confirming which certificate the KDC is supposed to be using. However, adding this information to the KDC certificate removes the need to specially configure the client to recognize the KDC certificate. Remember that if the client would accept any certificate as the KDC's certificate, the client could be fooled into trusting something that isn't a KDC and thus expose the user to giving away information (like a password or other private information) that it is supposed to keep secret. @subsection Client certificate The client certificate may need to have a EKU id-pkekuoid (1.3.6.1.5.2.3.4) set depending on the configuration on the KDC. It possible to store the principal (if allowed by the KDC) in the certificate and thus delegate responsibility to do the mapping between certificates and principals to the CA. This behavior is controlled by KDC configuration option: @example [kdc] pkinit_principal_in_certificate = yes @end example @subsubsection Using KRB5PrincipalName in id-pkinit-san The OtherName extension in the GeneralName is used to do the mapping between certificate and principal. For the KDC certificate, this stores the krbtgt principal name for that KDC. For the client certificate, this stores the principal for which that certificate is allowed to get tickets. The principal is stored in a SubjectAltName in the certificate using OtherName. The OID in the type is id-pkinit-san. @example id-pkinit-san OBJECT IDENTIFIER ::= @{ iso (1) org (3) dod (6) internet (1) security (5) kerberosv5 (2) 2 @} @end example The data part of the OtherName is filled with the following DER encoded ASN.1 structure: @example KRB5PrincipalName ::= SEQUENCE @{ realm [0] Realm, principalName [1] PrincipalName @} @end example where Realm and PrincipalName is defined by the Kerberos ASN.1 specification. @section Naming certificate using hx509 hx509 is the X.509 software used in Heimdal to handle certificates. hx509 supports several different syntaxes for specifying certificate files or formats. Several formats may be used: PEM, certificates embedded in PKCS#12 files, certificates embedded in PKCS#11 devices, and raw DER encoded certificates. Those formats may be specified as follows: @table @asis @item DIR: DIR specifies a directory which contains certificates in the DER or PEM format. The main feature of DIR is that the directory is read on demand when iterating over certificates. This allows applications, in some situations, to avoid having to store all certificates in memory. It's very useful for tests that iterate over large numbers of certificates. The syntax is: @example DIR:/path/to/der/files @end example @item FILE: FILE: specifies a file that contains a certificate or private key. The file can be either a PEM (openssl) file or a raw DER encoded certificate. If it's a PEM file, it can contain several keys and certificates and the code will try to match the private key and certificate together. Multiple files may be specified, separated by commas. It's useful to have one PEM file that contains all the trust anchors. The syntax is: @example FILE:certificate.pem,private-key.key,other-cert.pem,.... @end example @item PKCS11: PKCS11: is used to handle smartcards via PKCS#11 drivers, such as soft-token, opensc, or muscle. The argument specifies a shared object that implements the PKCS#11 API. The default is to use all slots on the device/token. The syntax is: @example PKCS11:shared-object.so @end example @item PKCS12: PKCS12: is used to handle PKCS#12 files. PKCS#12 files commonly have the extension pfx or p12. The syntax is: @example PKCS12:/path/to/file.pfx @end example @end table @section Configure the Kerberos software First configure the client's trust anchors and what parameters to verify. See the subsections below for how to do that. Then, you can use kinit to get yourself tickets. For example: @example $ kinit -C FILE:$HOME/.certs/lha.crt,$HOME/.certs/lha.key lha@@EXAMPLE.ORG Enter your private key passphrase: : lha@@nutcracker ; klist Credentials cache: FILE:/tmp/krb5cc_19100a Principal: lha@@EXAMPLE.ORG Issued Expires Principal Apr 20 02:08:08 Apr 20 12:08:08 krbtgt/EXAMPLE.ORG@@EXAMPLE.ORG @end example Using PKCS#11 it can look like this instead: @example $ kinit -C PKCS11:/usr/heimdal/lib/hx509.so lha@@EXAMPLE.ORG PIN code for SoftToken (slot): $ klist Credentials cache: API:4 Principal: lha@@EXAMPLE.ORG Issued Expires Principal Mar 26 23:40:10 Mar 27 09:40:10 krbtgt/EXAMPLE.ORG@@EXAMPLE.ORG @end example @section Configure the client @example [appdefaults] pkinit_anchors = FILE:/path/to/trust-anchors.pem [realms] EXAMPLE.COM = @{ pkinit_require_eku = true pkinit_require_krbtgt_otherName = true pkinit_win2k = no pkinit_win2k_require_binding = yes @} @end example @section Configure the KDC Configuration options for the KDC. @table @asis @item enable-pkinit = bool Enable PKINIT for this KDC. @item pkinit_identity = string Identity that the KDC will use when talking to clients. Mandatory. @item pkinit_anchors = string Trust anchors that the KDC will use when evaluating the trust of the client certificate. Mandatory. @item pkinit_pool = strings ... Extra certificate the KDC will use when building trust chains if it can't find enough certificates in the request from the client. @item pkinit_allow_proxy_certificate = bool Allow clients to use proxy certificates. The root certificate of the client's End Entity certificate is used for authorisation. @item pkinit_win2k_require_binding = bool Require windows clients up be upgrade to not allow cut and paste attack on encrypted data, applies to Windows XP and windows 2000 servers. @item pkinit_principal_in_certificate = bool Enable the KDC to use id-pkinit-san to determine to determine the mapping between a certificate and principal. @end table @example [kdc] enable-pkinit = yes pkinit_identity = FILE:/secure/kdc.crt,/secure/kdc.key pkinit_anchors = FILE:/path/to/trust-anchors.pem pkinit_pool = PKCS12:/path/to/useful-intermediate-certs.pfx pkinit_pool = FILE:/path/to/other-useful-intermediate-certs.pem pkinit_allow_proxy_certificate = no pkinit_win2k_require_binding = yes pkinit_principal_in_certificate = no @end example @subsection Using pki-mapping file Note that the file contents are space sensitive. @example # cat /var/heimdal/pki-mapping # comments starts with # lha@@EXAMPLE.ORG:C=SE,O=Stockholm universitet,CN=Love,UID=lha lha@@EXAMPLE.ORG:CN=Love,UID=lha @end example @subsection Using the Kerberos database You can also store the subject of the certificate in the principal entry in the kerberos database. @example kadmin modify --pkinit-acl="CN=baz,DC=test,DC=h5l,DC=se" user@@REALM @end example @section Use hxtool to create certificates @subsection Generate certificates First, you need to generate a CA certificate. This example creates a CA certificate that will be valid for 10 years. You need to change --subject in the command below to something appropriate for your site. @example hxtool issue-certificate \ --self-signed \ --issue-ca \ --generate-key=rsa \ --subject="CN=CA,DC=test,DC=h5l,DC=se" \ --lifetime=10years \ --certificate="FILE:ca.pem" @end example The KDC needs to have a certificate, so generate a certificate of the type ``pkinit-kdc'' and set the PK-INIT specifial SubjectAltName to the name of the krbtgt of the realm. You need to change --subject and --pk-init-principal in the command below to something appropriate for your site. @example hxtool issue-certificate \ --ca-certificate=FILE:ca.pem \ --generate-key=rsa \ --type="pkinit-kdc" \ --pk-init-principal="krbtgt/TEST.H5L.SE@@TEST.H5L.SE" \ --subject="uid=kdc,DC=test,DC=h5l,DC=se" \ --certificate="FILE:kdc.pem" @end example The users also needs to have certificates. For your first client, generate a certificate of type ``pkinit-client''. The client doesn't need to have the PK-INIT SubjectAltName set; you can have the Subject DN in the ACL file (pki-mapping) instead. You need to change --subject and --pk-init-principal in the command below to something appropriate for your site. You can omit --pk-init-principal if you're going to use the ACL file instead. @example hxtool issue-certificate \ --ca-certificate=FILE:ca.pem \ --generate-key=rsa \ --type="pkinit-client" \ --pk-init-principal="lha@@TEST.H5L.SE" \ --subject="uid=lha,DC=test,DC=h5l,DC=se" \ --certificate="FILE:user.pem" @end example @subsection Validate the certificate hxtool also contains a tool that will validate certificates according to rules from the PKIX document. These checks are not complete, but they provide a good test of whether you got all of the basic bits right in your certificates. @example hxtool validate FILE:user.pem @end example @section Use OpenSSL to create certificates @anchor{Use OpenSSL to create certificates} This section tries to give the CA owners hints how to create certificates using OpenSSL (or CA software based on OpenSSL). @subsection Using OpenSSL to create certificates with krb5PrincipalName To make OpenSSL create certificates with krb5PrincipalName, use an @file{openssl.cnf} as described below. To see a complete example of creating client and KDC certificates, see the test-data generation script @file{lib/hx509/data/gen-req.sh} in the source-tree. The certicates it creates are used to test the PK-INIT functionality in @file{tests/kdc/check-kdc.in}. To use this example you have to use OpenSSL 0.9.8a or later. @example [user_certificate] subjectAltName=otherName:1.3.6.1.5.2.2;SEQUENCE:princ_name [princ_name] realm = EXP:0, GeneralString:MY.REALM principal_name = EXP:1, SEQUENCE:principal_seq [principal_seq] name_type = EXP:0, INTEGER:1 name_string = EXP:1, SEQUENCE:principals [principals] princ1 = GeneralString:userid @end example Command usage: @example openssl x509 -extensions user_certificate openssl ca -extensions user_certificate @end example @c --- ms certificate @c @c [ new_oids ] @c msCertificateTemplateName = 1.3.6.1.4.1.311.20.2 @c @c @c [ req_smartcard ] @c keyUsage = digitalSignature, keyEncipherment @c extendedKeyUsage = msSmartcardLogin, clientAuth @c msCertificateTemplateName = ASN1:BMP:SmartcardLogon @c subjectAltName = otherName:msUPN;UTF8:lukeh@dsg.padl.com @c #subjectAltName = email:copy @section Using PK-INIT with Windows @subsection Client configration Clients using a Windows KDC with PK-INIT need configuration since windows uses pre-standard format and this can't be autodetected. The pkinit_win2k_require_binding option requires the reply for the KDC to be of the new, secure, type that binds the request to reply. Before, clients could fake the reply from the KDC. To use this option you have to apply a fix from Microsoft. @example [realms] MY.MS.REALM = @{ pkinit_win2k = yes pkinit_win2k_require_binding = no @} @end example @subsection Certificates The client certificates need to have the extended keyusage ``Microsoft Smartcardlogin'' (openssl has the OID shortname msSmartcardLogin). See Microsoft Knowledge Base Article - 281245 ``Guidelines for Enabling Smart Card Logon with Third-Party Certification Authorities'' for a more extensive description of how set setup an external CA so that it includes all the information required to make a Windows KDC happy. @subsection Configure Windows 2000 CA To enable Microsoft Smartcardlogin for certificates in your Windows 2000 CA, you want to look at Microsoft Knowledge Base Article - 313274 ``HOW TO: Configure a Certification Authority to Issue Smart Card Certificates in Windows''. @node Debugging Kerberos problems, , Setting up PK-INIT, Setting up a realm @section Debugging Kerberos problems To debug Kerberos client and server problems you can enable debug traceing by adding the following to @file{/etc/krb5,conf}. Note that the trace logging is sparse at the moment, but will continue to improve. @example [logging] libkrb5 = 0-/SYSLOG: @end example heimdal-7.5.0/doc/ack.texi0000644000175000017500000000655113026237312013456 0ustar niknik@node Acknowledgments, Copyrights and Licenses, Migration, Top @comment node-name, next, previous, up @appendix Acknowledgments Eric Young wrote ``libdes''. Heimdal used to use libdes, without it kth-krb would never have existed. Since there are no longer any Eric Young code left in the library, we renamed it to libhcrypto. All functions in libhcrypto have been re-implemented or used available public domain code. The core AES function where written by Vincent Rijmen, Antoon Bosselaers and Paulo Barreto. The core DES SBOX transformation was written by Richard Outerbridge. @code{imath} that is used for public key crypto support is written by Michael J. Fromberger. The University of California at Berkeley initially wrote @code{telnet}, and @code{telnetd}. The authentication and encryption code of @code{telnet} and @code{telnetd} was added by David Borman (then of Cray Research, Inc). The encryption code was removed when this was exported and then added back by Juha Eskelinen. The @code{popper} was also a Berkeley program initially. Some of the functions in @file{libroken} also come from Berkeley by way of NetBSD/FreeBSD. @code{editline} was written by Simmule Turner and Rich Salz. Heimdal contains a modifed copy. The @code{getifaddrs} implementation for Linux was written by Hideaki YOSHIFUJI for the Usagi project. The @code{pkcs11.h} headerfile was written by the Scute project. Bugfixes, documentation, encouragement, and code has been contributed by: @table @asis @item Alexander Boström @item Allan McRae @item Andrew Bartlett @item Andrew Cobaugh @item Andrew Tridge @item Anton Lundin @item Asanka Herath @item Björn Grönvall @item Björn Sandell @item Björn Schlögl @item Brandon S. Allbery KF8NH @item Brian A May @item Buck Huppmann @item Cacdric Schieli @item Chaskiel M Grundman @item Christos Zoulas @item Cizzi Storm @item Daniel Kouril @item David Love @item David Markey @item David R Boldt @item Derrick J Brashear @item Donald Norwood @item Douglas E Engert @item Frank van der Linden @item Gabor Gombas @item Guido Günther @item Guillaume Rousse @item Harald Barth @item Ingo Schwarze @item Jacques A. Vidrine @item Jaideep Padhye @item Jan Rekorajski @item Jason McIntyre @item Jeffrey Altman @item Jelmer Vernooij @item Joerg Pulz @item Johan Danielsson @item Johan Gadsjö @item Johan Ihrén @item John Center @item Julian Ospald @item Jun-ichiro itojun Hagino @item KAMADA Ken'ichi @item Kamen Mazdrashki @item Karolin Seeger @item Ken Hornstein @item Love Hörnquist Åstrand @item Luke Howard @item Magnus Ahltorp @item Magnus Holmberg @item Marc Horowitz @item Mario Strasser @item Mark Eichin @item Martin von Gagern @item Matthias Dieter Wallnöfer @item Matthieu Patou @item Mattias Amnefelt @item Michael B Allen @item Michael Fromberger @item Michal Vocu @item Milosz Kmieciak @item Miroslav Ruda @item Mustafa A. Hashmi @item Nicolas Williams @item Patrik Lundin @item Petr Holub @item Phil Fisher @item Rafal Malinowski @item Ragnar Sundblad @item Rainer Toebbicke @item Richard Nyberg @item Roland C. Dowdeswell @item Roman Divacky @item Russ Allbery @item Sho Hosoda, 細田 将 @item Simon Wilkinson @item Stefan Metzmacher @item Ted Percival @item Timothy Pearson @item Tom Payerle @item Victor Guerra @item Zeqing Xia @item Åke Sandgren @item and we hope that those not mentioned here will forgive us. @end table All bugs were introduced by ourselves. heimdal-7.5.0/doc/heimdal.css0000644000175000017500000000133212136107747014143 0ustar niknikbody { color: black; background-color: #fdfdfd; font-family: serif; max-width: 40em; } h1, h2, h3 { font-family: sans-serif; font-weight: bold; } h1 { padding: 0.5em 0 0.5em 5%; color: white; background: #3366cc; border-bottom: solid 1px black; } h1 { font-size: 200%; } h2 { font-size: 150%; } h3 { font-size: 120%; } h4 { font-weight: bold; } pre.example { margin-left: 2em; padding: 1em 0em; border: 2px dashed #c0c0c0; background: #f0f0f0; } a:link { color: blue; text-decoration: none; } a:visited { color: red; text-decoration: none } a:hover { text-decoration: underline } span.literal { font-family: monospace; } hr { border-style: none; background-color: black; height: 1px; } heimdal-7.5.0/doc/Makefile.am0000644000175000017500000000750213063024317014056 0ustar niknik# $Id$ include $(top_srcdir)/Makefile.am.common AUTOMAKE_OPTIONS = no-texinfo.tex MAKEINFOFLAGS = --css-include=$(srcdir)/heimdal.css TEXI2DVI = true # ARGH, make distcheck can't be disabled to not build dvifiles info_TEXINFOS = heimdal.texi hx509.texi dxy_subst = sed -e 's,[@]srcdir[@],$(srcdir),g' \ -e 's,[@]objdir[@],.,g' \ -e 's,[@]PACKAGE_VERSION[@],$(PACKAGE_VERSION),g' hcrypto.dxy: hcrypto.din Makefile $(dxy_subst) < $(srcdir)/hcrypto.din > hcrypto.dxy.tmp chmod +x hcrypto.dxy.tmp mv hcrypto.dxy.tmp hcrypto.dxy hdb.dxy: hdb.din Makefile $(dxy_subst) < $(srcdir)/hdb.din > hdb.dxy.tmp chmod +x hdb.dxy.tmp mv hdb.dxy.tmp hdb.dxy base.dxy: base.din Makefile $(dxy_subst) < $(srcdir)/base.din > base.dxy.tmp chmod +x base.dxy.tmp mv base.dxy.tmp base.dxy hx509.dxy: hx509.din Makefile $(dxy_subst) < $(srcdir)/hx509.din > hx509.dxy.tmp chmod +x hx509.dxy.tmp mv hx509.dxy.tmp hx509.dxy gssapi.dxy: gssapi.din Makefile $(dxy_subst) < $(srcdir)/gssapi.din > gssapi.dxy.tmp chmod +x gssapi.dxy.tmp mv gssapi.dxy.tmp gssapi.dxy krb5.dxy: krb5.din Makefile $(dxy_subst) < $(srcdir)/krb5.din > krb5.dxy.tmp chmod +x krb5.dxy.tmp mv krb5.dxy.tmp krb5.dxy ntlm.dxy: ntlm.din Makefile $(dxy_subst) < $(srcdir)/ntlm.din > ntlm.dxy.tmp chmod +x ntlm.dxy.tmp mv ntlm.dxy.tmp ntlm.dxy wind.dxy: wind.din Makefile $(dxy_subst) < $(srcdir)/wind.din > wind.dxy.tmp chmod +x wind.dxy.tmp mv wind.dxy.tmp wind.dxy texi_subst = sed -e 's,[@]dbdir[@],$(localstatedir),g' \ -e 's,[@]dbtype[@],$(db_type),g' \ -e 's,[@]PACKAGE_VERSION[@],$(PACKAGE_VERSION),g' vars.texi: vars.tin Makefile $(texi_subst) < $(srcdir)/vars.tin > vars.texi.tmp chmod +x vars.texi.tmp mv vars.texi.tmp vars.texi PROJECTS = base hdb hx509 gssapi krb5 ntlm wind PROJECTS += hcrypto doxyout doxygen: base.dxy hdb.dxy hx509.dxy hcrypto.dxy gssapi.dxy krb5.dxy ntlm.dxy wind.dxy @test -d $(srcdir)/doxyout && \ find $(srcdir)/doxyout -type d ! -perm -200 -exec chmod u+w {} ';' ; \ rm -rf $(srcdir)/doxyout ; \ mkdir $(srcdir)/doxyout ; \ for a in $(PROJECTS) ; do \ echo $$a ; \ doxygen $$a.dxy; \ (cd $(srcdir)/doxyout && \ find $$a/man -name '_*' -type f -print | \ perl -lne unlink && \ find $$a/html -name 'dir_*.html' -type f -print | \ perl -lne unlink && \ find $$a/man -type f > $$a/manpages ) ; \ done install-data-hook: install-doxygen-manpage uninstall-hook: uninstall-doxygen-manpage dist-hook: doxygen install-doxygen-manpage: for a in $(PROJECTS) ; do \ f="$(srcdir)/doxyout/$$a/manpages" ; \ test -f $$f || continue ; \ echo "install $$a manual pages $$(wc -l < $$f)" ; \ while read x ; do \ section=`echo "$$x" | sed 's/.*\.\([0-9]\)/\1/'` ; \ $(mkinstalldirs) "$(DESTDIR)$(mandir)/man$$section" ; \ $(INSTALL_DATA) $(srcdir)/doxyout/$$x "$(DESTDIR)$(mandir)/man$$section" ; \ done < $$f ; \ done ; exit 0 uninstall-doxygen-manpage: @for a in $(PROJECTS) ; do \ f="$(srcdir)/doxyout/$$a/manpages" ; \ test -f $$f || continue ; \ echo "removing $$a manual pages" ; \ while read x ; do \ section=`echo "$$x" | sed 's/.*\.\([0-9]\)/\1/'` ; \ base=`basename $$x` ; \ rm "$(DESTDIR)$(mandir)/man$$section/$$base" ; \ done < $$f ; \ done heimdal_TEXINFOS = \ ack.texi \ apps.texi \ copyright.texi \ heimdal.texi \ install.texi \ intro.texi \ kerberos4.texi \ migration.texi \ misc.texi \ programming.texi \ setup.texi \ vars.texi \ whatis.texi \ win2k.texi EXTRA_DIST = \ NTMakefile \ doxyout \ footer.html \ gssapi.din \ hdb.din \ hcrypto.din \ header.html \ heimdal.css \ base.din \ hx509.din \ krb5.din \ ntlm.din \ init-creds \ latin1.tex \ layman.asc \ doxytmpl.dxy \ wind.din \ base.hhp \ heimdal.hhp \ hx509.hhp \ vars.tin CLEANFILES = \ hcrypto.dxy* \ base.dxy* \ hx509.dxy* \ hdb.dxy* \ gssapi.dxy* \ krb5.dxy* \ ntlm.dxy* \ wind.dxy* \ vars.texi* heimdal-7.5.0/doc/kerberos4.texi0000644000175000017500000001551513026237312014620 0ustar niknik@c $Id$ @node Kerberos 4 issues, Windows compatibility, Things in search for a better place, Top @comment node-name, next, previous, up @chapter Kerberos 4 issues Kerberos 4 KDC and KA server have been moved. For more about AFS, see the section @xref{AFS}. @menu * Principal conversion issues:: * Converting a version 4 database:: @end menu @node Principal conversion issues, Converting a version 4 database, Kerberos 4 issues, Kerberos 4 issues @section Principal conversion issues First, Kerberos 4 and Kerberos 5 principals are different. A version 4 principal consists of a name, an instance, and a realm. A version 5 principal has one or more components, and a realm (the terms ``name'' and ``instance'' are still used, for the first and second component, respectively). Also, in some cases the name of a version 4 principal differs from the first component of the corresponding version 5 principal. One notable example is the ``host'' type principals, where the version 4 name is @samp{rcmd} (for ``remote command''), and the version 5 name is @samp{host}. For the class of principals that has a hostname as instance, there is an other major difference, Kerberos 4 uses only the first component of the hostname, whereas Kerberos 5 uses the fully qualified hostname. Because of this it can be hard or impossible to correctly convert a version 4 principal to a version 5 principal @footnote{the other way is not always trivial either, but usually easier}. The biggest problem is to know if the conversion resulted in a valid principal. To give an example, suppose you want to convert the principal @samp{rcmd.foo}. The @samp{rcmd} name suggests that the instance is a hostname (even if there are exceptions to this rule). To correctly convert the instance @samp{foo} to a hostname, you have to know which host it is referring to. You can to this by either guessing (from the realm) which domain name to append, or you have to have a list of possible hostnames. In the simplest cases you can cover most principals with the first rule. If you have several domains sharing a single realm this will not usually work. If the exceptions are few you can probably come by with a lookup table for the exceptions. In a complex scenario you will need some kind of host lookup mechanism. Using DNS for this is tempting, but DNS is error prone, slow and unsafe @footnote{at least until secure DNS is commonly available}. Fortunately, the KDC has a trump on hand: it can easily tell if a principal exists in the database. The KDC will use @code{krb5_425_conv_principal_ext} to convert principals when handling to version 4 requests. @node Converting a version 4 database, , Principal conversion issues, Kerberos 4 issues @section Converting a version 4 database If you want to convert an existing version 4 database, the principal conversion issue arises too. If you decide to convert your database once and for all, you will only have to do this conversion once. It is also possible to run a version 5 KDC as a slave to a version 4 KDC. In this case this conversion will happen every time the database is propagated. When doing this conversion, there are a few things to look out for. If you have stale entries in the database, these entries will not be converted. This might be because these principals are not used anymore, or it might be just because the principal couldn't be converted. You might also see problems with a many-to-one mapping of principals. For instance, if you are using DNS lookups and you have two principals @samp{rcmd.foo} and @samp{rcmd.bar}, where `foo' is a CNAME for `bar', the resulting principals will be the same. Since the conversion function can't tell which is correct, these conflicts will have to be resolved manually. @subsection Conversion example Given the following set of hosts and services: @example foo.se rcmd mail.foo.se rcmd, pop ftp.bar.se rcmd, ftp @end example you have a database that consists of the following principals: @samp{rcmd.foo}, @samp{rcmd.mail}, @samp{pop.mail}, @samp{rcmd.ftp}, and @samp{ftp.ftp}. lets say you also got these extra principals: @samp{rcmd.gone}, @samp{rcmd.old-mail}, where @samp{gone.foo.se} was a machine that has now passed away, and @samp{old-mail.foo.se} was an old mail machine that is now a CNAME for @samp{mail.foo.se}. When you convert this database you want the following conversions to be done: @example rcmd.foo host/foo.se rcmd.mail host/mail.foo.se pop.mail pop/mail.foo.se rcmd.ftp host/ftp.bar.se ftp.ftp ftp/ftp.bar.se rcmd.gone @i{removed} rcmd.old-mail @i{removed} @end example A @file{krb5.conf} that does this looks like: @example [realms] FOO.SE = @{ v4_name_convert = @{ host = @{ ftp = ftp pop = pop rcmd = host @} @} v4_instance_convert = @{ foo = foo.se ftp = ftp.bar.se @} default_domain = foo.se @} @end example The @samp{v4_name_convert} section says which names should be considered having an instance consisting of a hostname, and it also says how the names should be converted (for instance @samp{rcmd} should be converted to @samp{host}). The @samp{v4_instance_convert} section says how a hostname should be qualified (this is just a hosts-file in disguise). Host-instances that aren't covered by @samp{v4_instance_convert} are qualified by appending the contents of the @samp{default_domain}. Actually, this example doesn't work. Or rather, it works to well. Since it has no way of knowing which hostnames are valid and which are not, it will happily convert @samp{rcmd.gone} to @samp{host/gone.foo.se}. This isn't a big problem, but if you have run your kerberos realm for a few years, chances are big that you have quite a few `junk' principals. If you don't want this you can remove the @samp{default_domain} statement, but then you will have to add entries for @emph{all} your hosts in the @samp{v4_instance_convert} section. Instead of doing this you can use DNS to convert instances. This is not a solution without problems, but it is probably easier than adding lots of static host entries. To enable DNS lookup you should turn on @samp{v4_instance_resolve} in the @samp{[libdefaults]} section. @subsection Converting a database The database conversion is done with @samp{hprop}. You can run this command to propagate the database to the machine called @samp{slave-server} (which should be running a @samp{hpropd}). @example hprop --source=krb4-db --master-key=/.m slave-server @end example This command can also be to use for converting the v4 database on the server: @example hprop -n --source=krb4-db -d /var/kerberos/principal --master-key=/.m | hpropd -n @end example heimdal-7.5.0/doc/hx509.texi0000644000175000017500000006330613026237312013576 0ustar niknik\input texinfo @c -*- texinfo -*- @c %**start of header @c $Id$ @setfilename hx509.info @settitle HX509 @iftex @afourpaper @end iftex @c some sensible characters, please? @tex \input latin1.tex @end tex @setchapternewpage on @syncodeindex pg cp @c %**end of header @include vars.texi @set VERSION @value{PACKAGE_VERSION} @set EDITION 1.0 @ifinfo @dircategory Security @direntry * hx509: (hx509). The X.509 distribution from KTH @end direntry @end ifinfo @c title page @titlepage @title HX509 @subtitle X.509 distribution from KTH @subtitle Edition @value{EDITION}, for version @value{VERSION} @subtitle 2008 @author Love Hörnquist Åstrand @iftex @def@copynext{@vskip 20pt plus 1fil} @def@copyrightstart{} @def@copyrightend{} @end iftex @macro copynext @end macro @macro copyrightstart @end macro @macro copyrightend @end macro @page @copyrightstart Copyright (c) 1994-2008 Kungliga Tekniska Högskolan (Royal Institute of Technology, Stockholm, Sweden). All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the Institute nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. @copynext Copyright (c) 1988, 1990, 1993 The Regents of the University of California. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the University nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. @copynext Copyright 1992 Simmule Turner and Rich Salz. All rights reserved. This software is not subject to any license of the American Telephone and Telegraph Company or of the Regents of the University of California. Permission is granted to anyone to use this software for any purpose on any computer system, and to alter it and redistribute it freely, subject to the following restrictions: 1. The authors are not responsible for the consequences of use of this software, no matter how awful, even if they arise from flaws in it. 2. The origin of this software must not be misrepresented, either by explicit claim or by omission. Since few users ever read sources, credits must appear in the documentation. 3. Altered versions must be plainly marked as such, and must not be misrepresented as being the original software. Since few users ever read sources, credits must appear in the documentation. 4. This notice may not be removed or altered. @copynext IMath is Copyright 2002-2005 Michael J. Fromberger You may use it subject to the following Licensing Terms: Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. @copyrightend @end titlepage @macro manpage{man, section} @cite{\man\(\section\)} @end macro @c Less filling! Tastes great! @iftex @parindent=0pt @global@parskip 6pt plus 1pt @global@chapheadingskip = 15pt plus 4pt minus 2pt @global@secheadingskip = 12pt plus 3pt minus 2pt @global@subsecheadingskip = 9pt plus 2pt minus 2pt @end iftex @ifinfo @paragraphindent 0 @end ifinfo @ifnottex @node Top, Introduction, (dir), (dir) @top Heimdal @end ifnottex This manual is for version @value{VERSION} of hx509. @menu * Introduction:: * What is X.509 ?:: * Setting up a CA:: * CMS signing and encryption:: * Certificate matching:: * Software PKCS 11 module:: * Creating a CA certificate:: * Issuing certificates:: * Issuing CRLs:: * Application requirements:: * CMS background:: * Matching syntax:: * How to use the PKCS11 module:: @detailmenu --- The Detailed Node Listing --- Setting up a CA @c * Issuing certificates:: * Creating a CA certificate:: * Issuing certificates:: * Issuing CRLs:: @c * Issuing a proxy certificate:: @c * Creating a user certificate:: @c * Validating a certificate:: @c * Validating a certificate path:: * Application requirements:: CMS signing and encryption * CMS background:: Certificate matching * Matching syntax:: Software PKCS 11 module * How to use the PKCS11 module:: @end detailmenu @end menu @node Introduction, What is X.509 ?, Top, Top @chapter Introduction The goals of a PKI infrastructure (as defined in RFC 3280) is to meet @emph{the needs of deterministic, automated identification, authentication, access control, and authorization}. The administrator should be aware of certain terminologies as explained by the aforementioned RFC before attemping to put in place a PKI infrastructure. Briefly, these are: @itemize @bullet @item CA Certificate Authority @item RA Registration Authority, i.e., an optional system to which a CA delegates certain management functions. @item CRL Issuer An optional system to which a CA delegates the publication of certificate revocation lists. @item Repository A system or collection of distributed systems that stores certificates and CRLs and serves as a means of distributing these certificates and CRLs to end entities @end itemize hx509 (Heimdal x509 support) is a near complete X.509 stack that can handle CMS messages (crypto system used in S/MIME and Kerberos PK-INIT) and basic certificate processing tasks, path construction, path validation, OCSP and CRL validation, PKCS10 message construction, CMS Encrypted (shared secret encrypted), CMS SignedData (certificate signed), and CMS EnvelopedData (certificate encrypted). hx509 can use PKCS11 tokens, PKCS12 files, PEM files, and/or DER encoded files. @node What is X.509 ?, Setting up a CA, Introduction, Top @chapter What is X.509, PKIX, PKCS7 and CMS ? X.509 was created by CCITT (later ITU) for the X.500 directory service. Today, X.509 discussions and implementations commonly reference the IETF's PKIX Certificate and CRL Profile of the X.509 v3 certificate standard, as specified in RFC 3280. ITU continues to develop the X.509 standard together with the IETF in a rather complicated dance. X.509 is a public key based security system that has associated data stored within a so called certificate. Initially, X.509 was a strict hierarchical system with one root. However, ever evolving requiments and technology advancements saw the inclusion of multiple policy roots, bridges and mesh solutions. x.509 can also be used as a peer to peer system, though often seen as a common scenario. @section Type of certificates There are several flavors of certificate in X.509. @itemize @bullet @item Trust anchors Trust anchors are strictly not certificates, but commonly stored in a certificate format as they become easier to manage. Trust anchors are the keys that an end entity would trust to validate other certificates. This is done by building a path from the certificate you want to validate to to any of the trust anchors you have. @item End Entity (EE) certificates End entity certificates are the most common types of certificates. End entity certificates cannot issue (sign) certificate themselves and are generally used to authenticate and authorize users and services. @item Certification Authority (CA) certificates Certificate authority certificates have the right to issue additional certificates (be it sub-ordinate CA certificates to build an trust anchors or end entity certificates). There is no limit to how many certificates a CA may issue, but there might other restrictions, like the maximum path depth. @item Proxy certificates Remember the statement "End Entity certificates cannot issue certificates"? Well that statement is not entirely true. There is an extension called proxy certificates defined in RFC3820, that allows certificates to be issued by end entity certificates. The service that receives the proxy certificates must have explicitly turned on support for proxy certificates, so their use is somewhat limited. Proxy certificates can be limited by policies stored in the certificate to what they can be used for. This allows users to delegate the proxy certificate to services (by sending over the certificate and private key) so the service can access services on behalf of the user. One example of this would be a print service. The user wants to print a large job in the middle of the night when the printer isn't used that much, so the user creates a proxy certificate with the policy that it can only be used to access files related to this print job, creates the print job description and send both the description and proxy certificate with key over to print service. Later at night when the print service initializes (without any user intervention), access to the files for the print job is granted via the proxy certificate. As a result of (in-place) policy limitations, the certificate cannot be used for any other purposes. @end itemize @section Building a path Before validating a certificate path (or chain), the path needs to be constructed. Given a certificate (EE, CA, Proxy, or any other type), the path construction algorithm will try to find a path to one of the trust anchors. The process starts by looking at the issuing CA of the certificate, by Name or Key Identifier, and tries to find that certificate while at the same time evaluting any policies in-place. @node Setting up a CA, Creating a CA certificate, What is X.509 ?, Top @chapter Setting up a CA Do not let information overload scare you off! If you are simply testing or getting started with a PKI infrastructure, skip all this and go to the next chapter (see: @pxref{Creating a CA certificate}). Creating a CA certificate should be more the just creating a certificate, CA's should define a policy. Again, if you are simply testing a PKI, policies do not matter so much. However, when it comes to trust in an organisation, it will probably matter more whom your users and sysadmins will find it acceptable to trust. At the same time, try to keep things simple, it's not very hard to run a Certificate authority and the process to get new certificates should be simple. You may find it helpful to answer the following policy questions for your organization at a later stage: @itemize @bullet @item How do you trust your CA. @item What is the CA responsibility. @item Review of CA activity. @item How much process should it be to issue certificate. @item Who is allowed to issue certificates. @item Who is allowed to requests certificates. @item How to handle certificate revocation, issuing CRLs and maintain OCSP services. @end itemize @node Creating a CA certificate, Issuing certificates, Setting up a CA, Top @section Creating a CA certificate This section describes how to create a CA certificate and what to think about. @subsection Lifetime CA certificate You probably want to create a CA certificate with a long lifetime, 10 years at the very minimum. This is because you don't want to push out the certificate (as a trust anchor) to all you users again when the old CA certificate expires. Although a trust anchor can't really expire, not all software works in accordance with published standards. Keep in mind the security requirements might be different 10-20 years into the future. For example, SHA1 is going to be withdrawn in 2010, so make sure you have enough buffering in your choice of digest/hash algorithms, signature algorithms and key lengths. @subsection Create a CA certificate This command below can be used to generate a self-signed CA certificate. @example hxtool issue-certificate \ --self-signed \ --issue-ca \ --generate-key=rsa \ --subject="CN=CertificateAuthority,DC=test,DC=h5l,DC=se" \ --lifetime=10years \ --certificate="FILE:ca.pem" @end example @subsection Extending the lifetime of a CA certificate You just realised that your CA certificate is going to expire soon and that you need replace it with a new CA. The easiest way to do that is to extend the lifetime of your existing CA certificate. The example below will extend the CA certificate's lifetime by 10 years. You should compare this new certificate if it contains all the special tweaks as the old certificate had. @example hxtool issue-certificate \ --self-signed \ --issue-ca \ --lifetime="10years" \ --template-certificate="FILE:ca.pem" \ --template-fields="serialNumber,notBefore,subject,SPKI" \ --ca-private-key=FILE:ca.pem \ --certificate="FILE:new-ca.pem" @end example @subsection Subordinate CA This example below creates a new subordinate certificate authority. @example hxtool issue-certificate \ --ca-certificate=FILE:ca.pem \ --issue-ca \ --generate-key=rsa \ --subject="CN=CertificateAuthority,DC=dev,DC=test,DC=h5l,DC=se" \ --certificate="FILE:dev-ca.pem" @end example @node Issuing certificates, Issuing CRLs, Creating a CA certificate, Top @section Issuing certificates First you'll create a CA certificate, after that you have to deal with your users and servers and issue certificates to them. @c I think this section needs a bit of clarity. Can I add a separate @c section which explains CSRs as well? @itemize @bullet @item Do all the work themself Generate the key for the user. This has the problme that the the CA knows the private key of the user. For a paranoid user this might leave feeling of disconfort. @item Have the user do part of the work Receive PKCS10 certificate requests fromusers. PKCS10 is a request for a certificate. The user may specify what DN they want as well as provide a certificate signing request (CSR). To prove the user have the key, the whole request is signed by the private key of the user. @end itemize @subsection Name space management @c The explanation given below is slightly unclear. I will re-read the @c RFC and document accordingly What people might want to see. Re-issue certificates just because people moved within the organization. Expose privacy information. Using Sub-component name (+ notation). @subsection Certificate Revocation, CRL and OCSP Certificates that a CA issues may need to be revoked at some stage. As an example, an employee leaves the organization and does not bother handing in his smart card (or even if the smart card is handed back -- the certificate on it must no longer be acceptable to services; the employee has left). You may also want to revoke a certificate for a service which is no longer being offered on your network. Overlooking these scenarios can lead to security holes which will quickly become a nightmare to deal with. There are two primary protocols for dealing with certificate revokation. Namely: @itemize @bullet @item Certificate Revocation List (CRL) @item Online Certificate Status Protocol (OCSP) @end itemize If however the certificate in qeustion has been destroyed, there is no need to revoke the certificate because it can not be used by someone else. This matter since for each certificate you add to CRL, the download time and processing time for clients are longer. CRLs and OCSP responders however greatly help manage compatible services which may authenticate and authorize users (or services) on an on-going basis. As an example, VPN connectivity established via certificates for connecting clients would require your VPN software to make use of a CRL or an OCSP service to ensure revoked certificates belonging to former clients are not allowed access to (formerly subscribed) network services. @node Issuing CRLs, Application requirements, Issuing certificates, Top @section Issuing CRLs Create an empty CRL with no certificates revoked. Default expiration value is one year from now. @example hxtool crl-sign \ --crl-file=crl.der \ --signer=FILE:ca.pem @end example Create a CRL with all certificates in the directory @file{/path/to/revoked/dir} included in the CRL as revoked. Also make it expire one month from now. @example hxtool crl-sign \ --crl-file=crl.der \ --signer=FILE:ca.pem \ --lifetime='1 month' \ DIR:/path/to/revoked/dir @end example @node Application requirements, CMS signing and encryption, Issuing CRLs, Top @section Application requirements Application place different requirements on certificates. This section tries to expand what they are and how to use hxtool to generate certificates for those services. @subsection HTTPS - server @example hxtool issue-certificate \ --subject="CN=www.test.h5l.se,DC=test,DC=h5l,DC=se" \ --type="https-server" \ --hostname="www.test.h5l.se" \ --hostname="www2.test.h5l.se" \ ... @end example @subsection HTTPS - client @example hxtool issue-certificate \ --subject="UID=testus,DC=test,DC=h5l,DC=se" \ --type="https-client" \ ... @end example @subsection S/MIME - email There are two things that should be set in S/MIME certificates, one or more email addresses and an extended eku usage (EKU), emailProtection. The email address format used in S/MIME certificates is defined in RFC2822, section 3.4.1 and it should be an ``addr-spec''. There are two ways to specifify email address in certificates. The old way is in the subject distinguished name, @emph{this should not be used}. The new way is using a Subject Alternative Name (SAN). Even though the email address is stored in certificates, they don't need to be, email reader programs are required to accept certificates that doesn't have either of the two methods of storing email in certificates -- in which case, the email client will try to protect the user by printing the name of the certificate instead. S/MIME certificate can be used in another special way. They can be issued with a NULL subject distinguished name plus the email in SAN, this is a valid certificate. This is used when you wont want to share more information then you need to. hx509 issue-certificate supports adding the email SAN to certificate by using the --email option, --email also gives an implicit emailProtection eku. If you want to create an certificate without an email address, the option --type=email will add the emailProtection EKU. @example hxtool issue-certificate \ --subject="UID=testus-email,DC=test,DC=h5l,DC=se" \ --type=email \ --email="testus@@test.h5l.se" \ ... @end example An example of an certificate without and subject distinguished name with an email address in a SAN. @example hxtool issue-certificate \ --subject="" \ --type=email \ --email="testus@@test.h5l.se" \ ... @end example @subsection PK-INIT A PK-INIT infrastructure allows users and services to pick up kerberos credentials (tickets) based on their certificate. This, for example, allows users to authenticate to their desktops using smartcards while acquiring kerberos tickets in the process. As an example, an office network which offers centrally controlled desktop logins, mail, messaging (xmpp) and openafs would give users single sign-on facilities via smartcard based logins. Once the kerberos ticket has been acquired, all kerberized services would immediately become accessible based on deployed security policies. Let's go over the process of initializing a demo PK-INIT framework: @example hxtool issue-certificate \ --type="pkinit-kdc" \ --pk-init-principal="krbtgt/TEST.H5L.SE@@TEST.H5L.SE" \ --hostname=kerberos.test.h5l.se \ --ca-certificate="FILE:ca.pem,ca.key" \ --generate-key=rsa \ --certificate="FILE:kdc.pem" \ --subject="cn=kdc" @end example How to create a certificate for a user. @example hxtool issue-certificate \ --type="pkinit-client" \ --pk-init-principal="user@@TEST.H5L.SE" \ --ca-certificate="FILE:ca.pem,ca.key" \ --generate-key=rsa \ --subject="cn=Test User" \ --certificate="FILE:user.pem" @end example The --type field can be specified multiple times. The same certificate can hence house extensions for both pkinit-client as well as S/MIME. To use the PKCS11 module, please see the section: @pxref{How to use the PKCS11 module}. More about how to configure the KDC, see the documentation in the Heimdal manual to set up the KDC. @subsection XMPP/Jabber The jabber server certificate should have a dNSname that is the same as the user entered into the application, not the same as the host name of the machine. @example hxtool issue-certificate \ --subject="CN=xmpp1.test.h5l.se,DC=test,DC=h5l,DC=se" \ --hostname="xmpp1.test.h5l.se" \ --hostname="test.h5l.se" \ ... @end example The certificate may also contain a jabber identifier (JID) that, if the receiver allows it, authorises the server or client to use that JID. When storing a JID inside the certificate, both for server and client, it's stored inside a UTF8String within an otherName entity inside the subjectAltName, using the OID id-on-xmppAddr (1.3.6.1.5.5.7.8.5). To read more about the requirements, see RFC3920, Extensible Messaging and Presence Protocol (XMPP): Core. hxtool issue-certificate have support to add jid to the certificate using the option @kbd{--jid}. @example hxtool issue-certificate \ --subject="CN=Love,DC=test,DC=h5l,DC=se" \ --jid="lha@@test.h5l.se" \ ... @end example @node CMS signing and encryption, CMS background, Application requirements, Top @chapter CMS signing and encryption CMS is the Cryptographic Message System that among other, is used by S/MIME (secure email) and Kerberos PK-INIT. It's an extended version of the RSA, Inc standard PKCS7. @node CMS background, Certificate matching, CMS signing and encryption, Top @section CMS background @node Certificate matching, Matching syntax, CMS background, Top @chapter Certificate matching To match certificates hx509 have a special query language to match certifictes in queries and ACLs. @node Matching syntax, Software PKCS 11 module, Certificate matching, Top @section Matching syntax This is the language definitions somewhat slopply descriped: @example expr = TRUE, FALSE, ! expr, expr AND expr, expr OR expr, ( expr ) compare compare = word == word, word != word, word IN ( word [, word ...]) word IN %@{variable.subvariable@} word = STRING, %@{variable@} @end example @node Software PKCS 11 module, How to use the PKCS11 module, Matching syntax, Top @chapter Software PKCS 11 module PKCS11 is a standard created by RSA, Inc to support hardware and software encryption modules. It can be used by smartcard to expose the crypto primitives inside without exposing the crypto keys. Hx509 includes a software implementation of PKCS11 that runs within the memory space of the process and thus exposes the keys to the application. @node How to use the PKCS11 module, , Software PKCS 11 module, Top @section How to use the PKCS11 module @example $ cat > ~/.soft-pkcs11.rc <&2; \ exit 1;; \ esac; \ has_opt=no; \ sane_makeflags=$$MAKEFLAGS; \ if $(am__is_gnu_make); then \ sane_makeflags=$$MFLAGS; \ else \ case $$MAKEFLAGS in \ *\\[\ \ ]*) \ bs=\\; \ sane_makeflags=`printf '%s\n' "$$MAKEFLAGS" \ | sed "s/$$bs$$bs[$$bs $$bs ]*//g"`;; \ esac; \ fi; \ skip_next=no; \ strip_trailopt () \ { \ flg=`printf '%s\n' "$$flg" | sed "s/$$1.*$$//"`; \ }; \ for flg in $$sane_makeflags; do \ test $$skip_next = yes && { skip_next=no; continue; }; \ case $$flg in \ *=*|--*) continue;; \ -*I) strip_trailopt 'I'; skip_next=yes;; \ -*I?*) strip_trailopt 'I';; \ -*O) strip_trailopt 'O'; skip_next=yes;; \ -*O?*) strip_trailopt 'O';; \ -*l) strip_trailopt 'l'; skip_next=yes;; \ -*l?*) strip_trailopt 'l';; \ -[dEDm]) skip_next=yes;; \ -[JT]) skip_next=yes;; \ esac; \ case $$flg in \ *$$target_option*) has_opt=yes; break;; \ esac; \ done; \ test $$has_opt = yes am__make_dryrun = (target_option=n; $(am__make_running_with_option)) am__make_keepgoing = (target_option=k; $(am__make_running_with_option)) pkgdatadir = $(datadir)/@PACKAGE@ pkgincludedir = $(includedir)/@PACKAGE@ pkglibdir = $(libdir)/@PACKAGE@ pkglibexecdir = $(libexecdir)/@PACKAGE@ am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd install_sh_DATA = $(install_sh) -c -m 644 install_sh_PROGRAM = $(install_sh) -c install_sh_SCRIPT = $(install_sh) -c INSTALL_HEADER = $(INSTALL_DATA) transform = $(program_transform_name) NORMAL_INSTALL = : PRE_INSTALL = : POST_INSTALL = : NORMAL_UNINSTALL = : PRE_UNINSTALL = : POST_UNINSTALL = : build_triplet = @build@ host_triplet = @host@ subdir = doc ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 am__aclocal_m4_deps = $(top_srcdir)/cf/aix.m4 \ $(top_srcdir)/cf/auth-modules.m4 \ $(top_srcdir)/cf/broken-getaddrinfo.m4 \ $(top_srcdir)/cf/broken-glob.m4 \ $(top_srcdir)/cf/broken-realloc.m4 \ $(top_srcdir)/cf/broken-snprintf.m4 $(top_srcdir)/cf/broken.m4 \ $(top_srcdir)/cf/broken2.m4 $(top_srcdir)/cf/c-attribute.m4 \ $(top_srcdir)/cf/capabilities.m4 \ $(top_srcdir)/cf/check-compile-et.m4 \ $(top_srcdir)/cf/check-getpwnam_r-posix.m4 \ $(top_srcdir)/cf/check-man.m4 \ $(top_srcdir)/cf/check-netinet-ip-and-tcp.m4 \ $(top_srcdir)/cf/check-type-extra.m4 \ $(top_srcdir)/cf/check-var.m4 $(top_srcdir)/cf/crypto.m4 \ $(top_srcdir)/cf/db.m4 $(top_srcdir)/cf/destdirs.m4 \ $(top_srcdir)/cf/dispatch.m4 $(top_srcdir)/cf/dlopen.m4 \ $(top_srcdir)/cf/find-func-no-libs.m4 \ $(top_srcdir)/cf/find-func-no-libs2.m4 \ $(top_srcdir)/cf/find-func.m4 \ $(top_srcdir)/cf/find-if-not-broken.m4 \ $(top_srcdir)/cf/framework-security.m4 \ $(top_srcdir)/cf/have-struct-field.m4 \ $(top_srcdir)/cf/have-type.m4 $(top_srcdir)/cf/irix.m4 \ $(top_srcdir)/cf/krb-bigendian.m4 \ $(top_srcdir)/cf/krb-func-getlogin.m4 \ $(top_srcdir)/cf/krb-ipv6.m4 $(top_srcdir)/cf/krb-prog-ln-s.m4 \ $(top_srcdir)/cf/krb-prog-perl.m4 \ $(top_srcdir)/cf/krb-readline.m4 \ $(top_srcdir)/cf/krb-struct-spwd.m4 \ $(top_srcdir)/cf/krb-struct-winsize.m4 \ $(top_srcdir)/cf/largefile.m4 $(top_srcdir)/cf/libtool.m4 \ $(top_srcdir)/cf/ltoptions.m4 $(top_srcdir)/cf/ltsugar.m4 \ $(top_srcdir)/cf/ltversion.m4 $(top_srcdir)/cf/lt~obsolete.m4 \ $(top_srcdir)/cf/mips-abi.m4 $(top_srcdir)/cf/misc.m4 \ $(top_srcdir)/cf/need-proto.m4 $(top_srcdir)/cf/osfc2.m4 \ $(top_srcdir)/cf/otp.m4 $(top_srcdir)/cf/pkg.m4 \ $(top_srcdir)/cf/proto-compat.m4 $(top_srcdir)/cf/pthreads.m4 \ $(top_srcdir)/cf/resolv.m4 $(top_srcdir)/cf/retsigtype.m4 \ $(top_srcdir)/cf/roken-frag.m4 \ $(top_srcdir)/cf/socket-wrapper.m4 $(top_srcdir)/cf/sunos.m4 \ $(top_srcdir)/cf/telnet.m4 $(top_srcdir)/cf/test-package.m4 \ $(top_srcdir)/cf/version-script.m4 $(top_srcdir)/cf/wflags.m4 \ $(top_srcdir)/cf/win32.m4 $(top_srcdir)/cf/with-all.m4 \ $(top_srcdir)/acinclude.m4 $(top_srcdir)/configure.ac am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \ $(ACLOCAL_M4) DIST_COMMON = $(srcdir)/Makefile.am $(am__DIST_COMMON) mkinstalldirs = $(install_sh) -d CONFIG_HEADER = $(top_builddir)/include/config.h CONFIG_CLEAN_FILES = CONFIG_CLEAN_VPATH_FILES = AM_V_P = $(am__v_P_@AM_V@) am__v_P_ = $(am__v_P_@AM_DEFAULT_V@) am__v_P_0 = false am__v_P_1 = : AM_V_GEN = $(am__v_GEN_@AM_V@) am__v_GEN_ = $(am__v_GEN_@AM_DEFAULT_V@) am__v_GEN_0 = @echo " GEN " $@; am__v_GEN_1 = AM_V_at = $(am__v_at_@AM_V@) am__v_at_ = $(am__v_at_@AM_DEFAULT_V@) am__v_at_0 = @ am__v_at_1 = SOURCES = DIST_SOURCES = AM_V_DVIPS = $(am__v_DVIPS_@AM_V@) am__v_DVIPS_ = $(am__v_DVIPS_@AM_DEFAULT_V@) am__v_DVIPS_0 = @echo " DVIPS " $@; am__v_DVIPS_1 = AM_V_MAKEINFO = $(am__v_MAKEINFO_@AM_V@) am__v_MAKEINFO_ = $(am__v_MAKEINFO_@AM_DEFAULT_V@) am__v_MAKEINFO_0 = @echo " MAKEINFO" $@; am__v_MAKEINFO_1 = AM_V_INFOHTML = $(am__v_INFOHTML_@AM_V@) am__v_INFOHTML_ = $(am__v_INFOHTML_@AM_DEFAULT_V@) am__v_INFOHTML_0 = @echo " INFOHTML" $@; am__v_INFOHTML_1 = AM_V_TEXI2DVI = $(am__v_TEXI2DVI_@AM_V@) am__v_TEXI2DVI_ = $(am__v_TEXI2DVI_@AM_DEFAULT_V@) am__v_TEXI2DVI_0 = @echo " TEXI2DVI" $@; am__v_TEXI2DVI_1 = AM_V_TEXI2PDF = $(am__v_TEXI2PDF_@AM_V@) am__v_TEXI2PDF_ = $(am__v_TEXI2PDF_@AM_DEFAULT_V@) am__v_TEXI2PDF_0 = @echo " TEXI2PDF" $@; am__v_TEXI2PDF_1 = AM_V_texinfo = $(am__v_texinfo_@AM_V@) am__v_texinfo_ = $(am__v_texinfo_@AM_DEFAULT_V@) am__v_texinfo_0 = -q am__v_texinfo_1 = AM_V_texidevnull = $(am__v_texidevnull_@AM_V@) am__v_texidevnull_ = $(am__v_texidevnull_@AM_DEFAULT_V@) am__v_texidevnull_0 = > /dev/null am__v_texidevnull_1 = INFO_DEPS = $(srcdir)/heimdal.info $(srcdir)/hx509.info am__TEXINFO_TEX_DIR = $(srcdir) DVIS = heimdal.dvi hx509.dvi PDFS = heimdal.pdf hx509.pdf PSS = heimdal.ps hx509.ps HTMLS = heimdal.html hx509.html TEXINFOS = heimdal.texi hx509.texi TEXI2PDF = $(TEXI2DVI) --pdf --batch MAKEINFOHTML = $(MAKEINFO) --html AM_MAKEINFOHTMLFLAGS = $(AM_MAKEINFOFLAGS) DVIPS = dvips am__can_run_installinfo = \ case $$AM_UPDATE_INFO_DIR in \ n|no|NO) false;; \ *) (install-info --version) >/dev/null 2>&1;; \ esac am__installdirs = "$(DESTDIR)$(infodir)" am__vpath_adj_setup = srcdirstrip=`echo "$(srcdir)" | sed 's|.|.|g'`; am__vpath_adj = case $$p in \ $(srcdir)/*) f=`echo "$$p" | sed "s|^$$srcdirstrip/||"`;; \ *) f=$$p;; \ esac; am__strip_dir = f=`echo $$p | sed -e 's|^.*/||'`; am__install_max = 40 am__nobase_strip_setup = \ srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*|]/\\\\&/g'` am__nobase_strip = \ for p in $$list; do echo "$$p"; done | sed -e "s|$$srcdirstrip/||" am__nobase_list = $(am__nobase_strip_setup); \ for p in $$list; do echo "$$p $$p"; done | \ sed "s| $$srcdirstrip/| |;"' / .*\//!s/ .*/ ./; s,\( .*\)/[^/]*$$,\1,' | \ $(AWK) 'BEGIN { files["."] = "" } { files[$$2] = files[$$2] " " $$1; \ if (++n[$$2] == $(am__install_max)) \ { print $$2, files[$$2]; n[$$2] = 0; files[$$2] = "" } } \ END { for (dir in files) print dir, files[dir] }' am__base_list = \ sed '$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;s/\n/ /g' | \ sed '$$!N;$$!N;$$!N;$$!N;s/\n/ /g' am__uninstall_files_from_dir = { \ test -z "$$files" \ || { test ! -d "$$dir" && test ! -f "$$dir" && test ! -r "$$dir"; } \ || { echo " ( cd '$$dir' && rm -f" $$files ")"; \ $(am__cd) "$$dir" && rm -f $$files; }; \ } am__tagged_files = $(HEADERS) $(SOURCES) $(TAGS_FILES) $(LISP) am__DIST_COMMON = $(heimdal_TEXINFOS) $(srcdir)/Makefile.in \ $(top_srcdir)/Makefile.am.common \ $(top_srcdir)/cf/Makefile.am.common mdate-sh DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST) ACLOCAL = @ACLOCAL@ AIX_EXTRA_KAFS = @AIX_EXTRA_KAFS@ AMTAR = @AMTAR@ AM_DEFAULT_VERBOSITY = @AM_DEFAULT_VERBOSITY@ AR = @AR@ AS = @AS@ ASN1_COMPILE = @ASN1_COMPILE@ ASN1_COMPILE_DEP = @ASN1_COMPILE_DEP@ AUTOCONF = @AUTOCONF@ AUTOHEADER = @AUTOHEADER@ AUTOMAKE = @AUTOMAKE@ AWK = @AWK@ CANONICAL_HOST = @CANONICAL_HOST@ CAPNG_CFLAGS = @CAPNG_CFLAGS@ CAPNG_LIBS = @CAPNG_LIBS@ CATMAN = @CATMAN@ CATMANEXT = @CATMANEXT@ CC = @CC@ CCDEPMODE = @CCDEPMODE@ CFLAGS = @CFLAGS@ COMPILE_ET = @COMPILE_ET@ CPP = @CPP@ CPPFLAGS = @CPPFLAGS@ CYGPATH_W = @CYGPATH_W@ DB1LIB = @DB1LIB@ DB3LIB = @DB3LIB@ DBHEADER = @DBHEADER@ DEFS = @DEFS@ DEPDIR = @DEPDIR@ DIR_com_err = @DIR_com_err@ DIR_hdbdir = @DIR_hdbdir@ DIR_roken = @DIR_roken@ DLLTOOL = @DLLTOOL@ DSYMUTIL = @DSYMUTIL@ DUMPBIN = @DUMPBIN@ ECHO_C = @ECHO_C@ ECHO_N = @ECHO_N@ ECHO_T = @ECHO_T@ EGREP = @EGREP@ ENABLE_AFS_STRING_TO_KEY = @ENABLE_AFS_STRING_TO_KEY@ EXEEXT = @EXEEXT@ FGREP = @FGREP@ GCD_MIG = @GCD_MIG@ GREP = @GREP@ GROFF = @GROFF@ INCLUDES_roken = @INCLUDES_roken@ INCLUDE_libedit = @INCLUDE_libedit@ INCLUDE_libintl = @INCLUDE_libintl@ INCLUDE_openldap = @INCLUDE_openldap@ INCLUDE_openssl_crypto = @INCLUDE_openssl_crypto@ INCLUDE_readline = @INCLUDE_readline@ INCLUDE_sqlite3 = @INCLUDE_sqlite3@ INSTALL = @INSTALL@ INSTALL_DATA = @INSTALL_DATA@ INSTALL_PROGRAM = @INSTALL_PROGRAM@ INSTALL_SCRIPT = @INSTALL_SCRIPT@ INSTALL_STRIP_PROGRAM = @INSTALL_STRIP_PROGRAM@ LD = @LD@ LDFLAGS = @LDFLAGS@ LDFLAGS_VERSION_SCRIPT = @LDFLAGS_VERSION_SCRIPT@ LEX = @LEX@ LEXLIB = @LEXLIB@ LEX_OUTPUT_ROOT = @LEX_OUTPUT_ROOT@ LIBADD_roken = @LIBADD_roken@ LIBOBJS = @LIBOBJS@ LIBS = @LIBS@ LIBTOOL = @LIBTOOL@ LIB_AUTH_SUBDIRS = @LIB_AUTH_SUBDIRS@ LIB_bswap16 = @LIB_bswap16@ LIB_bswap32 = @LIB_bswap32@ LIB_bswap64 = @LIB_bswap64@ LIB_com_err = @LIB_com_err@ LIB_com_err_a = @LIB_com_err_a@ LIB_com_err_so = @LIB_com_err_so@ LIB_crypt = @LIB_crypt@ LIB_db_create = @LIB_db_create@ LIB_dbm_firstkey = @LIB_dbm_firstkey@ LIB_dbopen = @LIB_dbopen@ LIB_dispatch_async_f = @LIB_dispatch_async_f@ LIB_dladdr = @LIB_dladdr@ LIB_dlopen = @LIB_dlopen@ LIB_dn_expand = @LIB_dn_expand@ LIB_dns_search = @LIB_dns_search@ LIB_door_create = @LIB_door_create@ LIB_freeaddrinfo = @LIB_freeaddrinfo@ LIB_gai_strerror = @LIB_gai_strerror@ LIB_getaddrinfo = @LIB_getaddrinfo@ LIB_gethostbyname = @LIB_gethostbyname@ LIB_gethostbyname2 = @LIB_gethostbyname2@ LIB_getnameinfo = @LIB_getnameinfo@ LIB_getpwnam_r = @LIB_getpwnam_r@ LIB_getsockopt = @LIB_getsockopt@ LIB_hcrypto = @LIB_hcrypto@ LIB_hcrypto_a = @LIB_hcrypto_a@ LIB_hcrypto_appl = @LIB_hcrypto_appl@ LIB_hcrypto_so = @LIB_hcrypto_so@ LIB_hstrerror = @LIB_hstrerror@ LIB_kdb = @LIB_kdb@ LIB_libedit = @LIB_libedit@ LIB_libintl = @LIB_libintl@ LIB_loadquery = @LIB_loadquery@ LIB_logout = @LIB_logout@ LIB_logwtmp = @LIB_logwtmp@ LIB_openldap = @LIB_openldap@ LIB_openpty = @LIB_openpty@ LIB_openssl_crypto = @LIB_openssl_crypto@ LIB_otp = @LIB_otp@ LIB_pidfile = @LIB_pidfile@ LIB_readline = @LIB_readline@ LIB_res_ndestroy = @LIB_res_ndestroy@ LIB_res_nsearch = @LIB_res_nsearch@ LIB_res_search = @LIB_res_search@ LIB_roken = @LIB_roken@ LIB_security = @LIB_security@ LIB_setsockopt = @LIB_setsockopt@ LIB_socket = @LIB_socket@ LIB_sqlite3 = @LIB_sqlite3@ LIB_syslog = @LIB_syslog@ LIB_tgetent = @LIB_tgetent@ LIPO = @LIPO@ LMDBLIB = @LMDBLIB@ LN_S = @LN_S@ LTLIBOBJS = @LTLIBOBJS@ LT_SYS_LIBRARY_PATH = @LT_SYS_LIBRARY_PATH@ MAINT = @MAINT@ MAKEINFO = @MAKEINFO@ MANIFEST_TOOL = @MANIFEST_TOOL@ MKDIR_P = @MKDIR_P@ NDBMLIB = @NDBMLIB@ NM = @NM@ NMEDIT = @NMEDIT@ NO_AFS = @NO_AFS@ NROFF = @NROFF@ OBJDUMP = @OBJDUMP@ OBJEXT = @OBJEXT@ OTOOL = @OTOOL@ OTOOL64 = @OTOOL64@ PACKAGE = @PACKAGE@ PACKAGE_BUGREPORT = @PACKAGE_BUGREPORT@ PACKAGE_NAME = @PACKAGE_NAME@ PACKAGE_STRING = @PACKAGE_STRING@ PACKAGE_TARNAME = @PACKAGE_TARNAME@ PACKAGE_URL = @PACKAGE_URL@ PACKAGE_VERSION = @PACKAGE_VERSION@ PATH_SEPARATOR = @PATH_SEPARATOR@ PERL = @PERL@ PKG_CONFIG = @PKG_CONFIG@ PTHREAD_CFLAGS = @PTHREAD_CFLAGS@ PTHREAD_LDADD = @PTHREAD_LDADD@ PTHREAD_LIBADD = @PTHREAD_LIBADD@ RANLIB = @RANLIB@ SED = @SED@ SET_MAKE = @SET_MAKE@ SHELL = @SHELL@ SLC = @SLC@ SLC_DEP = @SLC_DEP@ STRIP = @STRIP@ VERSION = @VERSION@ VERSIONING = @VERSIONING@ WFLAGS = @WFLAGS@ WFLAGS_LITE = @WFLAGS_LITE@ YACC = @YACC@ YFLAGS = @YFLAGS@ abs_builddir = @abs_builddir@ abs_srcdir = @abs_srcdir@ abs_top_builddir = @abs_top_builddir@ abs_top_srcdir = @abs_top_srcdir@ ac_ct_AR = @ac_ct_AR@ ac_ct_CC = @ac_ct_CC@ ac_ct_DUMPBIN = @ac_ct_DUMPBIN@ am__include = @am__include@ am__leading_dot = @am__leading_dot@ am__quote = @am__quote@ am__tar = @am__tar@ am__untar = @am__untar@ bindir = @bindir@ build = @build@ build_alias = @build_alias@ build_cpu = @build_cpu@ build_os = @build_os@ build_vendor = @build_vendor@ builddir = @builddir@ datadir = @datadir@ datarootdir = @datarootdir@ db_type = @db_type@ db_type_preference = @db_type_preference@ docdir = @docdir@ dpagaix_cflags = @dpagaix_cflags@ dpagaix_ldadd = @dpagaix_ldadd@ dpagaix_ldflags = @dpagaix_ldflags@ dvidir = @dvidir@ exec_prefix = @exec_prefix@ host = @host@ host_alias = @host_alias@ host_cpu = @host_cpu@ host_os = @host_os@ host_vendor = @host_vendor@ htmldir = @htmldir@ includedir = @includedir@ infodir = @infodir@ install_sh = @install_sh@ libdir = @libdir@ libexecdir = @libexecdir@ localedir = @localedir@ localstatedir = @localstatedir@ mandir = @mandir@ mkdir_p = @mkdir_p@ oldincludedir = @oldincludedir@ pdfdir = @pdfdir@ prefix = @prefix@ program_transform_name = @program_transform_name@ psdir = @psdir@ sbindir = @sbindir@ sharedstatedir = @sharedstatedir@ srcdir = @srcdir@ subdirs = @subdirs@ sysconfdir = @sysconfdir@ target_alias = @target_alias@ top_build_prefix = @top_build_prefix@ top_builddir = @top_builddir@ top_srcdir = @top_srcdir@ SUFFIXES = .et .h .pc.in .pc .x .z .hx .1 .3 .5 .7 .8 .cat1 .cat3 \ .cat5 .cat7 .cat8 DEFAULT_INCLUDES = -I. -I$(srcdir) -I$(top_builddir)/include -I$(top_srcdir)/include AM_CPPFLAGS = $(INCLUDES_roken) @do_roken_rename_TRUE@ROKEN_RENAME = -DROKEN_RENAME AM_CFLAGS = $(WFLAGS) CP = cp buildinclude = $(top_builddir)/include LIB_XauReadAuth = @LIB_XauReadAuth@ LIB_el_init = @LIB_el_init@ LIB_getattr = @LIB_getattr@ LIB_getpwent_r = @LIB_getpwent_r@ LIB_odm_initialize = @LIB_odm_initialize@ LIB_setpcred = @LIB_setpcred@ INCLUDE_krb4 = @INCLUDE_krb4@ LIB_krb4 = @LIB_krb4@ libexec_heimdaldir = $(libexecdir)/heimdal NROFF_MAN = groff -mandoc -Tascii @NO_AFS_FALSE@LIB_kafs = $(top_builddir)/lib/kafs/libkafs.la $(AIX_EXTRA_KAFS) @NO_AFS_TRUE@LIB_kafs = @KRB5_TRUE@LIB_krb5 = $(top_builddir)/lib/krb5/libkrb5.la \ @KRB5_TRUE@ $(top_builddir)/lib/asn1/libasn1.la @KRB5_TRUE@LIB_gssapi = $(top_builddir)/lib/gssapi/libgssapi.la LIB_heimbase = $(top_builddir)/lib/base/libheimbase.la @DCE_TRUE@LIB_kdfs = $(top_builddir)/lib/kdfs/libkdfs.la #silent-rules heim_verbose = $(heim_verbose_$(V)) heim_verbose_ = $(heim_verbose_$(AM_DEFAULT_VERBOSITY)) heim_verbose_0 = @echo " GEN "$@; AUTOMAKE_OPTIONS = no-texinfo.tex MAKEINFOFLAGS = --css-include=$(srcdir)/heimdal.css TEXI2DVI = true # ARGH, make distcheck can't be disabled to not build dvifiles info_TEXINFOS = heimdal.texi hx509.texi dxy_subst = sed -e 's,[@]srcdir[@],$(srcdir),g' \ -e 's,[@]objdir[@],.,g' \ -e 's,[@]PACKAGE_VERSION[@],$(PACKAGE_VERSION),g' texi_subst = sed -e 's,[@]dbdir[@],$(localstatedir),g' \ -e 's,[@]dbtype[@],$(db_type),g' \ -e 's,[@]PACKAGE_VERSION[@],$(PACKAGE_VERSION),g' PROJECTS = base hdb hx509 gssapi krb5 ntlm wind hcrypto heimdal_TEXINFOS = \ ack.texi \ apps.texi \ copyright.texi \ heimdal.texi \ install.texi \ intro.texi \ kerberos4.texi \ migration.texi \ misc.texi \ programming.texi \ setup.texi \ vars.texi \ whatis.texi \ win2k.texi EXTRA_DIST = \ NTMakefile \ doxyout \ footer.html \ gssapi.din \ hdb.din \ hcrypto.din \ header.html \ heimdal.css \ base.din \ hx509.din \ krb5.din \ ntlm.din \ init-creds \ latin1.tex \ layman.asc \ doxytmpl.dxy \ wind.din \ base.hhp \ heimdal.hhp \ hx509.hhp \ vars.tin CLEANFILES = \ hcrypto.dxy* \ base.dxy* \ hx509.dxy* \ hdb.dxy* \ gssapi.dxy* \ krb5.dxy* \ ntlm.dxy* \ wind.dxy* \ vars.texi* all: all-am .SUFFIXES: .SUFFIXES: .et .h .pc.in .pc .x .z .hx .1 .3 .5 .7 .8 .cat1 .cat3 .cat5 .cat7 .cat8 .c .dvi .html .info .pdf .ps .texi $(srcdir)/Makefile.in: @MAINTAINER_MODE_TRUE@ $(srcdir)/Makefile.am $(top_srcdir)/Makefile.am.common $(top_srcdir)/cf/Makefile.am.common $(am__configure_deps) @for dep in $?; do \ case '$(am__configure_deps)' in \ *$$dep*) \ ( cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh ) \ && { if test -f $@; then exit 0; else break; fi; }; \ exit 1;; \ esac; \ done; \ echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign doc/Makefile'; \ $(am__cd) $(top_srcdir) && \ $(AUTOMAKE) --foreign doc/Makefile Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status @case '$?' in \ *config.status*) \ cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh;; \ *) \ echo ' cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe)'; \ cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe);; \ esac; $(top_srcdir)/Makefile.am.common $(top_srcdir)/cf/Makefile.am.common $(am__empty): $(top_builddir)/config.status: $(top_srcdir)/configure $(CONFIG_STATUS_DEPENDENCIES) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(top_srcdir)/configure: @MAINTAINER_MODE_TRUE@ $(am__configure_deps) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(ACLOCAL_M4): @MAINTAINER_MODE_TRUE@ $(am__aclocal_m4_deps) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(am__aclocal_m4_deps): mostlyclean-libtool: -rm -f *.lo clean-libtool: -rm -rf .libs _libs .texi.info: $(AM_V_MAKEINFO)restore=: && backupdir="$(am__leading_dot)am$$$$" && \ am__cwd=`pwd` && $(am__cd) $(srcdir) && \ rm -rf $$backupdir && mkdir $$backupdir && \ if ($(MAKEINFO) --version) >/dev/null 2>&1; then \ for f in $@ $@-[0-9] $@-[0-9][0-9] $(@:.info=).i[0-9] $(@:.info=).i[0-9][0-9]; do \ if test -f $$f; then mv $$f $$backupdir; restore=mv; else :; fi; \ done; \ else :; fi && \ cd "$$am__cwd"; \ if $(MAKEINFO) $(AM_MAKEINFOFLAGS) $(MAKEINFOFLAGS) -I $(srcdir) \ -o $@ $<; \ then \ rc=0; \ $(am__cd) $(srcdir); \ else \ rc=$$?; \ $(am__cd) $(srcdir) && \ $$restore $$backupdir/* `echo "./$@" | sed 's|[^/]*$$||'`; \ fi; \ rm -rf $$backupdir; exit $$rc .texi.dvi: $(AM_V_TEXI2DVI)TEXINPUTS="$(am__TEXINFO_TEX_DIR)$(PATH_SEPARATOR)$$TEXINPUTS" \ MAKEINFO='$(MAKEINFO) $(AM_MAKEINFOFLAGS) $(MAKEINFOFLAGS) -I $(srcdir)' \ $(TEXI2DVI) $(AM_V_texinfo) --build-dir=$(@:.dvi=.t2d) -o $@ $(AM_V_texidevnull) \ $< .texi.pdf: $(AM_V_TEXI2PDF)TEXINPUTS="$(am__TEXINFO_TEX_DIR)$(PATH_SEPARATOR)$$TEXINPUTS" \ MAKEINFO='$(MAKEINFO) $(AM_MAKEINFOFLAGS) $(MAKEINFOFLAGS) -I $(srcdir)' \ $(TEXI2PDF) $(AM_V_texinfo) --build-dir=$(@:.pdf=.t2p) -o $@ $(AM_V_texidevnull) \ $< .texi.html: $(AM_V_MAKEINFO)rm -rf $(@:.html=.htp) $(AM_V_at)if $(MAKEINFOHTML) $(AM_MAKEINFOHTMLFLAGS) $(MAKEINFOFLAGS) -I $(srcdir) \ -o $(@:.html=.htp) $<; \ then \ rm -rf $@ && mv $(@:.html=.htp) $@; \ else \ rm -rf $(@:.html=.htp); exit 1; \ fi $(srcdir)/heimdal.info: heimdal.texi $(heimdal_TEXINFOS) heimdal.dvi: heimdal.texi $(heimdal_TEXINFOS) heimdal.pdf: heimdal.texi $(heimdal_TEXINFOS) heimdal.html: heimdal.texi $(heimdal_TEXINFOS) $(srcdir)/hx509.info: hx509.texi hx509.dvi: hx509.texi hx509.pdf: hx509.texi hx509.html: hx509.texi .dvi.ps: $(AM_V_DVIPS)TEXINPUTS="$(am__TEXINFO_TEX_DIR)$(PATH_SEPARATOR)$$TEXINPUTS" \ $(DVIPS) $(AM_V_texinfo) -o $@ $< uninstall-dvi-am: @$(NORMAL_UNINSTALL) @list='$(DVIS)'; test -n "$(dvidir)" || list=; \ for p in $$list; do \ $(am__strip_dir) \ echo " rm -f '$(DESTDIR)$(dvidir)/$$f'"; \ rm -f "$(DESTDIR)$(dvidir)/$$f"; \ done uninstall-html-am: @$(NORMAL_UNINSTALL) @list='$(HTMLS)'; test -n "$(htmldir)" || list=; \ for p in $$list; do \ $(am__strip_dir) \ echo " rm -rf '$(DESTDIR)$(htmldir)/$$f'"; \ rm -rf "$(DESTDIR)$(htmldir)/$$f"; \ done uninstall-info-am: @$(PRE_UNINSTALL) @if test -d '$(DESTDIR)$(infodir)' && $(am__can_run_installinfo); then \ list='$(INFO_DEPS)'; \ for file in $$list; do \ relfile=`echo "$$file" | sed 's|^.*/||'`; \ echo " install-info --info-dir='$(DESTDIR)$(infodir)' --remove '$(DESTDIR)$(infodir)/$$relfile'"; \ if install-info --info-dir="$(DESTDIR)$(infodir)" --remove "$(DESTDIR)$(infodir)/$$relfile"; \ then :; else test ! -f "$(DESTDIR)$(infodir)/$$relfile" || exit 1; fi; \ done; \ else :; fi @$(NORMAL_UNINSTALL) @list='$(INFO_DEPS)'; \ for file in $$list; do \ relfile=`echo "$$file" | sed 's|^.*/||'`; \ relfile_i=`echo "$$relfile" | sed 's|\.info$$||;s|$$|.i|'`; \ (if test -d "$(DESTDIR)$(infodir)" && cd "$(DESTDIR)$(infodir)"; then \ echo " cd '$(DESTDIR)$(infodir)' && rm -f $$relfile $$relfile-[0-9] $$relfile-[0-9][0-9] $$relfile_i[0-9] $$relfile_i[0-9][0-9]"; \ rm -f $$relfile $$relfile-[0-9] $$relfile-[0-9][0-9] $$relfile_i[0-9] $$relfile_i[0-9][0-9]; \ else :; fi); \ done uninstall-pdf-am: @$(NORMAL_UNINSTALL) @list='$(PDFS)'; test -n "$(pdfdir)" || list=; \ for p in $$list; do \ $(am__strip_dir) \ echo " rm -f '$(DESTDIR)$(pdfdir)/$$f'"; \ rm -f "$(DESTDIR)$(pdfdir)/$$f"; \ done uninstall-ps-am: @$(NORMAL_UNINSTALL) @list='$(PSS)'; test -n "$(psdir)" || list=; \ for p in $$list; do \ $(am__strip_dir) \ echo " rm -f '$(DESTDIR)$(psdir)/$$f'"; \ rm -f "$(DESTDIR)$(psdir)/$$f"; \ done dist-info: $(INFO_DEPS) @srcdirstrip=`echo "$(srcdir)" | sed 's|.|.|g'`; \ list='$(INFO_DEPS)'; \ for base in $$list; do \ case $$base in \ $(srcdir)/*) base=`echo "$$base" | sed "s|^$$srcdirstrip/||"`;; \ esac; \ if test -f $$base; then d=.; else d=$(srcdir); fi; \ base_i=`echo "$$base" | sed 's|\.info$$||;s|$$|.i|'`; \ for file in $$d/$$base $$d/$$base-[0-9] $$d/$$base-[0-9][0-9] $$d/$$base_i[0-9] $$d/$$base_i[0-9][0-9]; do \ if test -f $$file; then \ relfile=`expr "$$file" : "$$d/\(.*\)"`; \ test -f "$(distdir)/$$relfile" || \ cp -p $$file "$(distdir)/$$relfile"; \ else :; fi; \ done; \ done mostlyclean-aminfo: -rm -rf heimdal.t2d heimdal.t2p hx509.t2d hx509.t2p clean-aminfo: -test -z "heimdal.dvi heimdal.pdf heimdal.ps heimdal.html hx509.dvi hx509.pdf \ hx509.ps hx509.html" \ || rm -rf heimdal.dvi heimdal.pdf heimdal.ps heimdal.html hx509.dvi hx509.pdf \ hx509.ps hx509.html maintainer-clean-aminfo: @list='$(INFO_DEPS)'; for i in $$list; do \ i_i=`echo "$$i" | sed 's|\.info$$||;s|$$|.i|'`; \ echo " rm -f $$i $$i-[0-9] $$i-[0-9][0-9] $$i_i[0-9] $$i_i[0-9][0-9]"; \ rm -f $$i $$i-[0-9] $$i-[0-9][0-9] $$i_i[0-9] $$i_i[0-9][0-9]; \ done tags TAGS: ctags CTAGS: cscope cscopelist: distdir: $(DISTFILES) @srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ topsrcdirstrip=`echo "$(top_srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ list='$(DISTFILES)'; \ dist_files=`for file in $$list; do echo $$file; done | \ sed -e "s|^$$srcdirstrip/||;t" \ -e "s|^$$topsrcdirstrip/|$(top_builddir)/|;t"`; \ case $$dist_files in \ */*) $(MKDIR_P) `echo "$$dist_files" | \ sed '/\//!d;s|^|$(distdir)/|;s,/[^/]*$$,,' | \ sort -u` ;; \ esac; \ for file in $$dist_files; do \ if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \ if test -d $$d/$$file; then \ dir=`echo "/$$file" | sed -e 's,/[^/]*$$,,'`; \ if test -d "$(distdir)/$$file"; then \ find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ fi; \ if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \ cp -fpR $(srcdir)/$$file "$(distdir)$$dir" || exit 1; \ find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ fi; \ cp -fpR $$d/$$file "$(distdir)$$dir" || exit 1; \ else \ test -f "$(distdir)/$$file" \ || cp -p $$d/$$file "$(distdir)/$$file" \ || exit 1; \ fi; \ done $(MAKE) $(AM_MAKEFLAGS) \ top_distdir="$(top_distdir)" distdir="$(distdir)" \ dist-info dist-hook check-am: all-am $(MAKE) $(AM_MAKEFLAGS) check-local check: check-am all-am: Makefile $(INFO_DEPS) all-local installdirs: for dir in "$(DESTDIR)$(infodir)"; do \ test -z "$$dir" || $(MKDIR_P) "$$dir"; \ done install: install-am install-exec: install-exec-am install-data: install-data-am uninstall: uninstall-am install-am: all-am @$(MAKE) $(AM_MAKEFLAGS) install-exec-am install-data-am installcheck: installcheck-am install-strip: if test -z '$(STRIP)'; then \ $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ install; \ else \ $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'" install; \ fi mostlyclean-generic: clean-generic: -test -z "$(CLEANFILES)" || rm -f $(CLEANFILES) distclean-generic: -test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES) -test . = "$(srcdir)" || test -z "$(CONFIG_CLEAN_VPATH_FILES)" || rm -f $(CONFIG_CLEAN_VPATH_FILES) maintainer-clean-generic: @echo "This command is intended for maintainers to use" @echo "it deletes files that may require special tools to rebuild." clean: clean-am clean-am: clean-aminfo clean-generic clean-libtool mostlyclean-am distclean: distclean-am -rm -f Makefile distclean-am: clean-am distclean-generic dvi: dvi-am dvi-am: $(DVIS) html: html-am html-am: $(HTMLS) info: info-am info-am: $(INFO_DEPS) install-data-am: install-info-am @$(NORMAL_INSTALL) $(MAKE) $(AM_MAKEFLAGS) install-data-hook install-dvi: install-dvi-am install-dvi-am: $(DVIS) @$(NORMAL_INSTALL) @list='$(DVIS)'; test -n "$(dvidir)" || list=; \ if test -n "$$list"; then \ echo " $(MKDIR_P) '$(DESTDIR)$(dvidir)'"; \ $(MKDIR_P) "$(DESTDIR)$(dvidir)" || exit 1; \ fi; \ for p in $$list; do \ if test -f "$$p"; then d=; else d="$(srcdir)/"; fi; \ echo "$$d$$p"; \ done | $(am__base_list) | \ while read files; do \ echo " $(INSTALL_DATA) $$files '$(DESTDIR)$(dvidir)'"; \ $(INSTALL_DATA) $$files "$(DESTDIR)$(dvidir)" || exit $$?; \ done install-exec-am: install-exec-local install-html: install-html-am install-html-am: $(HTMLS) @$(NORMAL_INSTALL) @list='$(HTMLS)'; list2=; test -n "$(htmldir)" || list=; \ if test -n "$$list"; then \ echo " $(MKDIR_P) '$(DESTDIR)$(htmldir)'"; \ $(MKDIR_P) "$(DESTDIR)$(htmldir)" || exit 1; \ fi; \ for p in $$list; do \ if test -f "$$p" || test -d "$$p"; then d=; else d="$(srcdir)/"; fi; \ $(am__strip_dir) \ d2=$$d$$p; \ if test -d "$$d2"; then \ echo " $(MKDIR_P) '$(DESTDIR)$(htmldir)/$$f'"; \ $(MKDIR_P) "$(DESTDIR)$(htmldir)/$$f" || exit 1; \ echo " $(INSTALL_DATA) '$$d2'/* '$(DESTDIR)$(htmldir)/$$f'"; \ $(INSTALL_DATA) "$$d2"/* "$(DESTDIR)$(htmldir)/$$f" || exit $$?; \ else \ list2="$$list2 $$d2"; \ fi; \ done; \ test -z "$$list2" || { echo "$$list2" | $(am__base_list) | \ while read files; do \ echo " $(INSTALL_DATA) $$files '$(DESTDIR)$(htmldir)'"; \ $(INSTALL_DATA) $$files "$(DESTDIR)$(htmldir)" || exit $$?; \ done; } install-info: install-info-am install-info-am: $(INFO_DEPS) @$(NORMAL_INSTALL) @srcdirstrip=`echo "$(srcdir)" | sed 's|.|.|g'`; \ list='$(INFO_DEPS)'; test -n "$(infodir)" || list=; \ if test -n "$$list"; then \ echo " $(MKDIR_P) '$(DESTDIR)$(infodir)'"; \ $(MKDIR_P) "$(DESTDIR)$(infodir)" || exit 1; \ fi; \ for file in $$list; do \ case $$file in \ $(srcdir)/*) file=`echo "$$file" | sed "s|^$$srcdirstrip/||"`;; \ esac; \ if test -f $$file; then d=.; else d=$(srcdir); fi; \ file_i=`echo "$$file" | sed 's|\.info$$||;s|$$|.i|'`; \ for ifile in $$d/$$file $$d/$$file-[0-9] $$d/$$file-[0-9][0-9] \ $$d/$$file_i[0-9] $$d/$$file_i[0-9][0-9] ; do \ if test -f $$ifile; then \ echo "$$ifile"; \ else : ; fi; \ done; \ done | $(am__base_list) | \ while read files; do \ echo " $(INSTALL_DATA) $$files '$(DESTDIR)$(infodir)'"; \ $(INSTALL_DATA) $$files "$(DESTDIR)$(infodir)" || exit $$?; done @$(POST_INSTALL) @if $(am__can_run_installinfo); then \ list='$(INFO_DEPS)'; test -n "$(infodir)" || list=; \ for file in $$list; do \ relfile=`echo "$$file" | sed 's|^.*/||'`; \ echo " install-info --info-dir='$(DESTDIR)$(infodir)' '$(DESTDIR)$(infodir)/$$relfile'";\ install-info --info-dir="$(DESTDIR)$(infodir)" "$(DESTDIR)$(infodir)/$$relfile" || :;\ done; \ else : ; fi install-man: install-pdf: install-pdf-am install-pdf-am: $(PDFS) @$(NORMAL_INSTALL) @list='$(PDFS)'; test -n "$(pdfdir)" || list=; \ if test -n "$$list"; then \ echo " $(MKDIR_P) '$(DESTDIR)$(pdfdir)'"; \ $(MKDIR_P) "$(DESTDIR)$(pdfdir)" || exit 1; \ fi; \ for p in $$list; do \ if test -f "$$p"; then d=; else d="$(srcdir)/"; fi; \ echo "$$d$$p"; \ done | $(am__base_list) | \ while read files; do \ echo " $(INSTALL_DATA) $$files '$(DESTDIR)$(pdfdir)'"; \ $(INSTALL_DATA) $$files "$(DESTDIR)$(pdfdir)" || exit $$?; done install-ps: install-ps-am install-ps-am: $(PSS) @$(NORMAL_INSTALL) @list='$(PSS)'; test -n "$(psdir)" || list=; \ if test -n "$$list"; then \ echo " $(MKDIR_P) '$(DESTDIR)$(psdir)'"; \ $(MKDIR_P) "$(DESTDIR)$(psdir)" || exit 1; \ fi; \ for p in $$list; do \ if test -f "$$p"; then d=; else d="$(srcdir)/"; fi; \ echo "$$d$$p"; \ done | $(am__base_list) | \ while read files; do \ echo " $(INSTALL_DATA) $$files '$(DESTDIR)$(psdir)'"; \ $(INSTALL_DATA) $$files "$(DESTDIR)$(psdir)" || exit $$?; done installcheck-am: maintainer-clean: maintainer-clean-am -rm -f Makefile maintainer-clean-am: distclean-am maintainer-clean-aminfo \ maintainer-clean-generic mostlyclean: mostlyclean-am mostlyclean-am: mostlyclean-aminfo mostlyclean-generic \ mostlyclean-libtool pdf: pdf-am pdf-am: $(PDFS) ps: ps-am ps-am: $(PSS) uninstall-am: uninstall-dvi-am uninstall-html-am uninstall-info-am \ uninstall-pdf-am uninstall-ps-am @$(NORMAL_INSTALL) $(MAKE) $(AM_MAKEFLAGS) uninstall-hook .MAKE: check-am install-am install-data-am install-strip uninstall-am .PHONY: all all-am all-local check check-am check-local clean \ clean-aminfo clean-generic clean-libtool cscopelist-am \ ctags-am dist-hook dist-info distclean distclean-generic \ distclean-libtool distdir dvi dvi-am html html-am info info-am \ install install-am install-data install-data-am \ install-data-hook install-dvi install-dvi-am install-exec \ install-exec-am install-exec-local install-html \ install-html-am install-info install-info-am install-man \ install-pdf install-pdf-am install-ps install-ps-am \ install-strip installcheck installcheck-am installdirs \ maintainer-clean maintainer-clean-aminfo \ maintainer-clean-generic mostlyclean mostlyclean-aminfo \ mostlyclean-generic mostlyclean-libtool pdf pdf-am ps ps-am \ tags-am uninstall uninstall-am uninstall-dvi-am uninstall-hook \ uninstall-html-am uninstall-info-am uninstall-pdf-am \ uninstall-ps-am .PRECIOUS: Makefile install-suid-programs: @foo='$(bin_SUIDS)'; \ for file in $$foo; do \ x=$(DESTDIR)$(bindir)/$$file; \ if chown 0:0 $$x && chmod u+s $$x; then :; else \ echo "*"; \ echo "* Failed to install $$x setuid root"; \ echo "*"; \ fi; \ done install-exec-local: install-suid-programs codesign-all: @if [ X"$$CODE_SIGN_IDENTITY" != X ] ; then \ foo='$(bin_PROGRAMS) $(sbin_PROGRAMS) $(libexec_PROGRAMS)' ; \ for file in $$foo ; do \ echo "CODESIGN $$file" ; \ codesign -f -s "$$CODE_SIGN_IDENTITY" $$file || exit 1 ; \ done ; \ fi all-local: codesign-all install-build-headers:: $(include_HEADERS) $(dist_include_HEADERS) $(nodist_include_HEADERS) $(build_HEADERZ) $(nobase_include_HEADERS) $(noinst_HEADERS) @foo='$(include_HEADERS) $(dist_include_HEADERS) $(nodist_include_HEADERS) $(build_HEADERZ) $(noinst_HEADERS)'; \ for f in $$foo; do \ f=`basename $$f`; \ if test -f "$(srcdir)/$$f"; then file="$(srcdir)/$$f"; \ else file="$$f"; fi; \ if cmp -s $$file $(buildinclude)/$$f 2> /dev/null ; then \ : ; else \ echo " $(CP) $$file $(buildinclude)/$$f"; \ $(CP) $$file $(buildinclude)/$$f || true; \ fi ; \ done ; \ foo='$(nobase_include_HEADERS)'; \ for f in $$foo; do \ if test -f "$(srcdir)/$$f"; then file="$(srcdir)/$$f"; \ else file="$$f"; fi; \ $(mkdir_p) $(buildinclude)/`dirname $$f` ; \ if cmp -s $$file $(buildinclude)/$$f 2> /dev/null ; then \ : ; else \ echo " $(CP) $$file $(buildinclude)/$$f"; \ $(CP) $$file $(buildinclude)/$$f; \ fi ; \ done all-local: install-build-headers check-local:: @if test '$(CHECK_LOCAL)' = "no-check-local"; then \ foo=''; elif test '$(CHECK_LOCAL)'; then \ foo='$(CHECK_LOCAL)'; else \ foo='$(PROGRAMS)'; fi; \ if test "$$foo"; then \ failed=0; all=0; \ for i in $$foo; do \ all=`expr $$all + 1`; \ if (./$$i --version && ./$$i --help) > /dev/null 2>&1; then \ echo "PASS: $$i"; \ else \ echo "FAIL: $$i"; \ failed=`expr $$failed + 1`; \ fi; \ done; \ if test "$$failed" -eq 0; then \ banner="All $$all tests passed"; \ else \ banner="$$failed of $$all tests failed"; \ fi; \ dashes=`echo "$$banner" | sed s/./=/g`; \ echo "$$dashes"; \ echo "$$banner"; \ echo "$$dashes"; \ test "$$failed" -eq 0 || exit 1; \ fi .x.c: @cmp -s $< $@ 2> /dev/null || cp $< $@ .hx.h: @cmp -s $< $@ 2> /dev/null || cp $< $@ #NROFF_MAN = nroff -man .1.cat1: $(NROFF_MAN) $< > $@ .3.cat3: $(NROFF_MAN) $< > $@ .5.cat5: $(NROFF_MAN) $< > $@ .7.cat7: $(NROFF_MAN) $< > $@ .8.cat8: $(NROFF_MAN) $< > $@ dist-cat1-mans: @foo='$(man1_MANS)'; \ bar='$(man_MANS)'; \ for i in $$bar; do \ case $$i in \ *.1) foo="$$foo $$i";; \ esac; done ;\ for i in $$foo; do \ x=`echo $$i | sed 's/\.[^.]*$$/.cat1/'`; \ echo "$(NROFF_MAN) $(srcdir)/$$i > $(distdir)/$$x"; \ $(NROFF_MAN) $(srcdir)/$$i > $(distdir)/$$x; \ done dist-cat3-mans: @foo='$(man3_MANS)'; \ bar='$(man_MANS)'; \ for i in $$bar; do \ case $$i in \ *.3) foo="$$foo $$i";; \ esac; done ;\ for i in $$foo; do \ x=`echo $$i | sed 's/\.[^.]*$$/.cat3/'`; \ echo "$(NROFF_MAN) $(srcdir)/$$i > $(distdir)/$$x"; \ $(NROFF_MAN) $(srcdir)/$$i > $(distdir)/$$x; \ done dist-cat5-mans: @foo='$(man5_MANS)'; \ bar='$(man_MANS)'; \ for i in $$bar; do \ case $$i in \ *.5) foo="$$foo $$i";; \ esac; done ;\ for i in $$foo; do \ x=`echo $$i | sed 's/\.[^.]*$$/.cat5/'`; \ echo "$(NROFF_MAN) $(srcdir)/$$i > $(distdir)/$$x"; \ $(NROFF_MAN) $(srcdir)/$$i > $(distdir)/$$x; \ done dist-cat7-mans: @foo='$(man7_MANS)'; \ bar='$(man_MANS)'; \ for i in $$bar; do \ case $$i in \ *.7) foo="$$foo $$i";; \ esac; done ;\ for i in $$foo; do \ x=`echo $$i | sed 's/\.[^.]*$$/.cat7/'`; \ echo "$(NROFF_MAN) $(srcdir)/$$i > $(distdir)/$$x"; \ $(NROFF_MAN) $(srcdir)/$$i > $(distdir)/$$x; \ done dist-cat8-mans: @foo='$(man8_MANS)'; \ bar='$(man_MANS)'; \ for i in $$bar; do \ case $$i in \ *.8) foo="$$foo $$i";; \ esac; done ;\ for i in $$foo; do \ x=`echo $$i | sed 's/\.[^.]*$$/.cat8/'`; \ echo "$(NROFF_MAN) $(srcdir)/$$i > $(distdir)/$$x"; \ $(NROFF_MAN) $(srcdir)/$$i > $(distdir)/$$x; \ done dist-hook: dist-cat1-mans dist-cat3-mans dist-cat5-mans dist-cat7-mans dist-cat8-mans install-cat-mans: $(SHELL) $(top_srcdir)/cf/install-catman.sh install "$(INSTALL_DATA)" "$(mkinstalldirs)" "$(srcdir)" "$(DESTDIR)$(mandir)" '$(CATMANEXT)' $(man_MANS) $(man1_MANS) $(man3_MANS) $(man5_MANS) $(man7_MANS) $(man8_MANS) uninstall-cat-mans: $(SHELL) $(top_srcdir)/cf/install-catman.sh uninstall "$(INSTALL_DATA)" "$(mkinstalldirs)" "$(srcdir)" "$(DESTDIR)$(mandir)" '$(CATMANEXT)' $(man_MANS) $(man1_MANS) $(man3_MANS) $(man5_MANS) $(man7_MANS) $(man8_MANS) install-data-hook: install-cat-mans uninstall-hook: uninstall-cat-mans .et.h: $(COMPILE_ET) $< .et.c: $(COMPILE_ET) $< # # Useful target for debugging # check-valgrind: tobjdir=`cd $(top_builddir) && pwd` ; \ tsrcdir=`cd $(top_srcdir) && pwd` ; \ env TESTS_ENVIRONMENT="$${tsrcdir}/cf/maybe-valgrind.sh -s $${tsrcdir} -o $${tobjdir}" make check # # Target to please samba build farm, builds distfiles in-tree. # Will break when automake changes... # distdir-in-tree: $(DISTFILES) $(INFO_DEPS) list='$(DIST_SUBDIRS)'; for subdir in $$list; do \ if test "$$subdir" != .; then \ (cd $$subdir && $(MAKE) $(AM_MAKEFLAGS) distdir-in-tree) ; \ fi ; \ done hcrypto.dxy: hcrypto.din Makefile $(dxy_subst) < $(srcdir)/hcrypto.din > hcrypto.dxy.tmp chmod +x hcrypto.dxy.tmp mv hcrypto.dxy.tmp hcrypto.dxy hdb.dxy: hdb.din Makefile $(dxy_subst) < $(srcdir)/hdb.din > hdb.dxy.tmp chmod +x hdb.dxy.tmp mv hdb.dxy.tmp hdb.dxy base.dxy: base.din Makefile $(dxy_subst) < $(srcdir)/base.din > base.dxy.tmp chmod +x base.dxy.tmp mv base.dxy.tmp base.dxy hx509.dxy: hx509.din Makefile $(dxy_subst) < $(srcdir)/hx509.din > hx509.dxy.tmp chmod +x hx509.dxy.tmp mv hx509.dxy.tmp hx509.dxy gssapi.dxy: gssapi.din Makefile $(dxy_subst) < $(srcdir)/gssapi.din > gssapi.dxy.tmp chmod +x gssapi.dxy.tmp mv gssapi.dxy.tmp gssapi.dxy krb5.dxy: krb5.din Makefile $(dxy_subst) < $(srcdir)/krb5.din > krb5.dxy.tmp chmod +x krb5.dxy.tmp mv krb5.dxy.tmp krb5.dxy ntlm.dxy: ntlm.din Makefile $(dxy_subst) < $(srcdir)/ntlm.din > ntlm.dxy.tmp chmod +x ntlm.dxy.tmp mv ntlm.dxy.tmp ntlm.dxy wind.dxy: wind.din Makefile $(dxy_subst) < $(srcdir)/wind.din > wind.dxy.tmp chmod +x wind.dxy.tmp mv wind.dxy.tmp wind.dxy vars.texi: vars.tin Makefile $(texi_subst) < $(srcdir)/vars.tin > vars.texi.tmp chmod +x vars.texi.tmp mv vars.texi.tmp vars.texi doxyout doxygen: base.dxy hdb.dxy hx509.dxy hcrypto.dxy gssapi.dxy krb5.dxy ntlm.dxy wind.dxy @test -d $(srcdir)/doxyout && \ find $(srcdir)/doxyout -type d ! -perm -200 -exec chmod u+w {} ';' ; \ rm -rf $(srcdir)/doxyout ; \ mkdir $(srcdir)/doxyout ; \ for a in $(PROJECTS) ; do \ echo $$a ; \ doxygen $$a.dxy; \ (cd $(srcdir)/doxyout && \ find $$a/man -name '_*' -type f -print | \ perl -lne unlink && \ find $$a/html -name 'dir_*.html' -type f -print | \ perl -lne unlink && \ find $$a/man -type f > $$a/manpages ) ; \ done install-data-hook: install-doxygen-manpage uninstall-hook: uninstall-doxygen-manpage dist-hook: doxygen install-doxygen-manpage: for a in $(PROJECTS) ; do \ f="$(srcdir)/doxyout/$$a/manpages" ; \ test -f $$f || continue ; \ echo "install $$a manual pages $$(wc -l < $$f)" ; \ while read x ; do \ section=`echo "$$x" | sed 's/.*\.\([0-9]\)/\1/'` ; \ $(mkinstalldirs) "$(DESTDIR)$(mandir)/man$$section" ; \ $(INSTALL_DATA) $(srcdir)/doxyout/$$x "$(DESTDIR)$(mandir)/man$$section" ; \ done < $$f ; \ done ; exit 0 uninstall-doxygen-manpage: @for a in $(PROJECTS) ; do \ f="$(srcdir)/doxyout/$$a/manpages" ; \ test -f $$f || continue ; \ echo "removing $$a manual pages" ; \ while read x ; do \ section=`echo "$$x" | sed 's/.*\.\([0-9]\)/\1/'` ; \ base=`basename $$x` ; \ rm "$(DESTDIR)$(mandir)/man$$section/$$base" ; \ done < $$f ; \ done # Tell versions [3.59,3.63) of GNU make to not export all variables. # Otherwise a system limit (for SysV at least) may be exceeded. .NOEXPORT: heimdal-7.5.0/doc/hx509.hhp0000644000175000017500000000027213026237312013375 0ustar niknik[OPTIONS] Compatibility=1.1 or later Compiled file=hx509.chm Contents file=toc.hhc Default topic=index.html Display compile progress=No Language=0x409 English (United States) Title=HX509heimdal-7.5.0/doc/heimdal.hhp0000644000175000017500000000027613026237312014127 0ustar niknik[OPTIONS] Compatibility=1.1 or later Compiled file=heimdal.chm Contents file=toc.hhc Default topic=index.html Display compile progress=No Language=0x409 English (United States) Title=Heimdalheimdal-7.5.0/doc/heimdal.info0000644000175000017500000040067313212450777014321 0ustar niknikThis is heimdal.info, produced by makeinfo version 6.5 from heimdal.texi. INFO-DIR-SECTION Security START-INFO-DIR-ENTRY * Heimdal: (heimdal). The Kerberos 5 distribution from KTH END-INFO-DIR-ENTRY  File: heimdal.info, Node: Top, Next: Introduction, Prev: (dir), Up: (dir) Heimdal ******* This manual for version 7.5.0 of Heimdal. * Menu: * Introduction:: * What is Kerberos?:: * Building and Installing:: * Setting up a realm:: * Applications:: * Things in search for a better place:: * Kerberos 4 issues:: * Windows compatibility:: * Programming with Kerberos:: * Migration:: * Acknowledgments:: * Copyrights and Licenses:: -- The Detailed Node Listing -- Setting up a realm * Configuration file:: * Creating the database:: * Modifying the database:: * keytabs:: * Remote administration:: * Password changing:: * Testing clients and servers:: * Slave Servers:: * Incremental propagation:: * Encryption types and salting:: * Credential cache server - KCM:: * Cross realm:: * Transit policy:: * Setting up DNS:: * Using LDAP to store the database:: * Providing Kerberos credentials to servers and programs:: * Setting up PK-INIT:: * Debugging Kerberos problems:: Applications * Authentication modules:: * AFS:: Authentication modules * Digital SIA:: * IRIX:: Kerberos 4 issues * Principal conversion issues:: * Converting a version 4 database:: Windows compatibility * Configuring Windows to use a Heimdal KDC:: * Inter-Realm keys (trust) between Windows and a Heimdal KDC:: * Create account mappings:: * Encryption types:: * Authorisation data:: * Quirks of Windows 2000 KDC:: * Useful links when reading about the Windows:: Programming with Kerberos  File: heimdal.info, Node: Introduction, Next: What is Kerberos?, Prev: Top, Up: Top 1 Introduction ************** What is Heimdal? ================ Heimdal is a free implementation of Kerberos 5. The goals are to: * have an implementation that can be freely used by anyone * be protocol compatible with existing implementations and, if not in conflict, with RFC 4120 (and any future updated RFC). RFC 4120 replaced RFC 1510. * be reasonably compatible with the M.I.T Kerberos V5 API * have support for Kerberos V5 over GSS-API (RFC1964) * include the most important and useful application programs (rsh, telnet, popper, etc.) * include enough backwards compatibility with Kerberos V4 Status ====== Heimdal has the following features (this does not mean any of this works): * a stub generator and a library to encode/decode/whatever ASN.1/DER stuff * a 'libkrb5' library that should be possible to get to work with simple applications * a GSS-API library * 'kinit', 'klist', 'kdestroy' * 'telnet', 'telnetd' * 'rsh', 'rshd' * 'popper', 'push' (a movemail equivalent) * 'ftp', and 'ftpd' * a library 'libkafs' for authenticating to AFS and a program 'afslog' that uses it * some simple test programs * a KDC that supports most things, * simple programs for distributing databases between a KDC master and slaves * a password changing daemon 'kpasswdd', library functions for changing passwords and a simple client * some kind of administration system * Kerberos V4 support in many of the applications. Bug reports =========== If you find bugs in this software, make sure it is a genuine bug and not just a part of the code that isn't implemented. Bug reports should be sent to . Please include information on what machine and operating system (including version) you are running, what you are trying to do, what happens, what you think should have happened, an example for us to repeat, the output you get when trying the example, and a patch for the problem if you have one. Please make any patches with 'diff -u' or 'diff -c'. Suggestions, comments and other non bug reports are also welcome. Mailing list ============ There are two mailing lists with talk about Heimdal. is a low-volume announcement list, while is for general discussion. Send a message to to subscribe. Heimdal source code, binaries and the manual ============================================ The source code for heimdal, links to binaries and the manual (this document) can be found on our web-page at .  File: heimdal.info, Node: What is Kerberos?, Next: Building and Installing, Prev: Introduction, Up: Top 2 What is Kerberos? ******************* Now this Cerberus had three heads of dogs, the tail of a dragon, and on his back the heads of all sorts of snakes. -- Pseudo-Apollodorus Library 2.5.12 Kerberos is a system for authenticating users and services on a network. It is built upon the assumption that the network is "unsafe". For example, data sent over the network can be eavesdropped and altered, and addresses can also be faked. Therefore they cannot be used for authentication purposes. Kerberos is a trusted third-party service. That means that there is a third party (the kerberos server) that is trusted by all the entities on the network (users and services, usually called "principals"). All principals share a secret password (or key) with the kerberos server and this enables principals to verify that the messages from the kerberos server are authentic. Thus trusting the kerberos server, users and services can authenticate each other. 2.1 Basic mechanism =================== *Note* This discussion is about Kerberos version 4, but version 5 works similarly. In Kerberos, principals use "tickets" to prove that they are who they claim to be. In the following example, A is the initiator of the authentication exchange, usually a user, and B is the service that A wishes to use. To obtain a ticket for a specific service, A sends a ticket request to the kerberos server. The request contains A's and B's names (along with some other fields). The kerberos server checks that both A and B are valid principals. Having verified the validity of the principals, it creates a packet containing A's and B's names, A's network address (A), the current time (T), the lifetime of the ticket (LIFE), and a secret "session key" (K). This packet is encrypted with B's secret key (K). The actual ticket (T) looks like this: ({A, B, A, T, LIFE, K}K). The reply to A consists of the ticket (T), B's name, the current time, the lifetime of the ticket, and the session key, all encrypted in A's secret key ({B, T, LIFE, K, T}K). A decrypts the reply and retains it for later use. Before sending a message to B, A creates an authenticator consisting of A's name, A's address, the current time, and a "checksum" chosen by A, all encrypted with the secret session key ({A, A, T, CHECKSUM}K). This is sent together with the ticket received from the kerberos server to B. Upon reception, B decrypts the ticket using B's secret key. Since the ticket contains the session key that the authenticator was encrypted with, B can now also decrypt the authenticator. To verify that A really is A, B now has to compare the contents of the ticket with that of the authenticator. If everything matches, B now considers A as properly authenticated. 2.2 Different attacks ===================== Impersonating A --------------- An impostor, C could steal the authenticator and the ticket as it is transmitted across the network, and use them to impersonate A. The address in the ticket and the authenticator was added to make it more difficult to perform this attack. To succeed C will have to either use the same machine as A or fake the source addresses of the packets. By including the time stamp in the authenticator, C does not have much time in which to mount the attack. Impersonating B --------------- C can hijack B's network address, and when A sends her credentials, C just pretend to verify them. C can't be sure that she is talking to A. 2.3 Defence strategies ====================== It would be possible to add a "replay cache" to the server side. The idea is to save the authenticators sent during the last few minutes, so that B can detect when someone is trying to retransmit an already used message. This is somewhat impractical (mostly regarding efficiency), and is not part of Kerberos 4; MIT Kerberos 5 contains it. To authenticate B, A might request that B sends something back that proves that B has access to the session key. An example of this is the checksum that A sent as part of the authenticator. One typical procedure is to add one to the checksum, encrypt it with the session key and send it back to A. This is called "mutual authentication". The session key can also be used to add cryptographic checksums to the messages sent between A and B (known as "message integrity"). Encryption can also be added ("message confidentiality"). This is probably the best approach in all cases. 2.4 Further reading =================== The original paper on Kerberos from 1988 is 'Kerberos: An Authentication Service for Open Network Systems', by Jennifer Steiner, Clifford Neuman and Jeffrey I. Schiller. A less technical description can be found in 'Designing an Authentication System: a Dialogue in Four Scenes' by Bill Bryant, also from 1988. These documents can be found on our web-page at .  File: heimdal.info, Node: Building and Installing, Next: Setting up a realm, Prev: What is Kerberos?, Up: Top 3 Building and Installing ************************* Build and install instructions are located here: Prebuilt packages is located here:  File: heimdal.info, Node: Setting up a realm, Next: Applications, Prev: Building and Installing, Up: Top 4 Setting up a realm ******************** A realm is an administrative domain. The name of a Kerberos realm is usually the Internet domain name in uppercase. Call your realm the same as your Internet domain name if you do not have strong reasons for not doing so. It will make life easier for you and everyone else. * Menu: * Configuration file:: * Creating the database:: * Modifying the database:: * Checking the setup:: * keytabs:: * Remote administration:: * Password changing:: * Testing clients and servers:: * Slave Servers:: * Incremental propagation:: * Encryption types and salting:: * Credential cache server - KCM:: * Cross realm:: * Transit policy:: * Setting up DNS:: * Using LDAP to store the database:: * Providing Kerberos credentials to servers and programs:: * Setting up PK-INIT:: * Debugging Kerberos problems::  File: heimdal.info, Node: Configuration file, Next: Creating the database, Prev: Setting up a realm, Up: Setting up a realm 4.1 Configuration file ====================== To setup a realm you will first have to create a configuration file: '/etc/krb5.conf'. The 'krb5.conf' file can contain many configuration options, some of which are described here. There is a sample 'krb5.conf' supplied with the distribution. The configuration file is a hierarchical structure consisting of sections, each containing a list of bindings (either variable assignments or subsections). A section starts with '['section-name']'. A binding consists of a left hand side, an equal sign ('=') and a right hand side (the left hand side tag must be separated from the equal sign with some whitespace). Subsections have a '{' as the first non-whitespace character after the equal sign. All other bindings are treated as variable assignments. The value of a variable extends to the end of the line. [section1] a-subsection = { var = value1 other-var = value with {} sub-sub-section = { var = 123 } } var = some other value [section2] var = yet another value In this manual, names of sections and bindings will be given as strings separated by slashes ('/'). The 'other-var' variable will thus be 'section1/a-subsection/other-var'. For in-depth information about the contents of the configuration file, refer to the 'krb5.conf' manual page. Some of the more important sections are briefly described here. The 'libdefaults' section contains a list of library configuration parameters, such as the default realm and the timeout for KDC responses. The 'realms' section contains information about specific realms, such as where they hide their KDC. This section serves the same purpose as the Kerberos 4 'krb.conf' file, but can contain more information. Finally the 'domain_realm' section contains a list of mappings from domains to realms, equivalent to the Kerberos 4 'krb.realms' file. To continue with the realm setup, you will have to create a configuration file, with contents similar to the following. [libdefaults] default_realm = MY.REALM [realms] MY.REALM = { kdc = my.kdc my.slave.kdc kdc = my.third.kdc kdc = 130.237.237.17 kdc = [2001:6b0:1:ea::100]:88 } [domain_realm] .my.domain = MY.REALM If you use a realm name equal to your domain name, you can omit the 'libdefaults', and 'domain_realm', sections. If you have a DNS SRV-record for your realm, or your Kerberos server has DNS CNAME 'kerberos.my.realm', you can omit the 'realms' section too. If you want to use a different configuration file then the default you can point a file with the environment variable 'KRB5_CONFIG'. env KRB5_CONFIG=$HOME/etc/krb5.conf kinit user@REALM  File: heimdal.info, Node: Creating the database, Next: Modifying the database, Prev: Configuration file, Up: Setting up a realm 4.2 Creating the database ========================= The database library will look for the database in the directory '/var/heimdal', so you should probably create that directory. Make sure the directory has restrictive permissions. # mkdir /var/heimdal # chmod og-rwx /var/heimdal Heimdal supports various database backends: lmdb (LMDB), db3 (Berkeley DB 3.x, 4.x, or 5.x), db1 (Berkeley DB 2.x), sqlite (SQLite3), and ldap (LDAP). The default is db3, and is selected at build time from one of lmdb, db3, or db1. These defaults can be overriden in the 'database' key in the 'kdc' section of the configuration. [kdc] database = { dbname = lmdb:/path/to/db-file realm = REALM acl_file = /path/to/kadmind.acl mkey_file = /path/to/mkey log_file = /path/to/iprop-log-file } To use LDAP, see *Note Using LDAP to store the database::. The keys of all the principals are stored in the database. If you choose to, these can be encrypted with a master key. You do not have to remember this key (or password), but just to enter it once and it will be stored in a file ('/var/heimdal/m-key'). If you want to have a master key, run 'kstash' to create this master key: # kstash Master key: Verifying password - Master key: If you want to generate a random master key you can use the '--random-key' flag to kstash. This will make sure you have a good key on which attackers can't do a dictionary attack. If you have a master key, make sure you make a backup of your master key file; without it backups of the database are of no use. To initialise the database use the 'kadmin' program, with the '-l' option (to enable local database mode). First issue a 'init MY.REALM' command. This will create the database and insert default principals for that realm. You can have more than one realm in one database, so 'init' does not destroy any old database. Before creating the database, 'init' will ask you some questions about maximum ticket lifetimes. After creating the database you should probably add yourself to it. You do this with the 'add' command. It takes as argument the name of a principal. The principal should contain a realm, so if you haven't set up a default realm, you will need to explicitly include the realm. # kadmin -l kadmin> init MY.REALM Realm max ticket life [unlimited]: Realm max renewable ticket life [unlimited]: kadmin> add me Max ticket life [unlimited]: Max renewable life [unlimited]: Attributes []: Password: Verifying password - Password: Now start the KDC and try getting a ticket. # kdc & # kinit me me@MY.REALMS's Password: # klist Credentials cache: /tmp/krb5cc_0 Principal: me@MY.REALM Issued Expires Principal Aug 25 07:25:55 Aug 25 17:25:55 krbtgt/MY.REALM@MY.REALM If you are curious you can use the 'dump' command to list all the entries in the database. It should look something similar to the following example (note that the entries here are truncated for typographical reasons): kadmin> dump me@MY.REALM 1:0:1:0b01d3cb7c293b57:-:0:7:8aec316b9d1629e3baf8 ... kadmin/admin@MY.REALM 1:0:1:e5c8a2675b37a443:-:0:7:cb913ebf85 ... krbtgt/MY.REALM@MY.REALM 1:0:1:52b53b61c875ce16:-:0:7:c8943be ... kadmin/changepw@MY.REALM 1:0:1:f48c8af2b340e9fb:-:0:7:e3e6088 ...  File: heimdal.info, Node: Modifying the database, Next: Checking the setup, Prev: Creating the database, Up: Setting up a realm 4.3 Modifying the database ========================== All modifications of principals are done with with kadmin. A principal has several attributes and lifetimes associated with it. Principals are added, renamed, modified, and deleted with the kadmin commands 'add', 'rename', 'modify', 'delete'. Both interactive editing and command line flags can be used (use -help to list the available options). There are different kinds of types for the fields in the database; attributes, absolute time times and relative times. 4.3.1 Attributes ---------------- When doing interactive editing, attributes are listed with '?'. The attributes are given in a comma (',') separated list. Attributes are removed from the list by prefixing them with '-'. kadmin> modify me Max ticket life [1 day]: Max renewable life [1 week]: Principal expiration time [never]: Password expiration time [never]: Attributes [disallow-renewable]: requires-pre-auth,-disallow-renewable kadmin> get me Principal: me@MY.REALM [...] Attributes: requires-pre-auth 4.3.2 Absolute times -------------------- The format for absolute times are any of the following: never now YYYY-mm-dd YYYY-mm-dd HH:MM:SS 4.3.3 Relative times -------------------- The format for relative times are any of the following combined: N year M month O day P hour Q minute R second  File: heimdal.info, Node: Checking the setup, Next: keytabs, Prev: Modifying the database, Up: Setting up a realm 4.4 Checking the setup ====================== There are two tools that can check the consistency of the Kerberos configuration file and the Kerberos database. The Kerberos configuration file is checked using 'verify_krb5_conf'. The tool checks for common errors, but commonly there are several uncommon configuration entries that are never added to the tool and thus generates "unknown entry" warnings. This is usually nothing to worry about. The database check is built into the kadmin tool. It will check for common configuration error that will cause problems later. Common check are for existence and flags on important principals. The database check by run by the following command : kadmin -l check REALM.EXAMPLE.ORG  File: heimdal.info, Node: keytabs, Next: Remote administration, Prev: Checking the setup, Up: Setting up a realm 4.5 keytabs =========== To extract a service ticket from the database and put it in a keytab, you need to first create the principal in the database with 'add' (using the '--random-key' flag to get a random key) and then extract it with 'ext_keytab'. kadmin> add --random-key host/my.host.name Max ticket life [unlimited]: Max renewable life [unlimited]: Attributes []: kadmin> ext host/my.host.name kadmin> exit # ktutil list Version Type Principal 1 des-cbc-md5 host/my.host.name@MY.REALM 1 des-cbc-md4 host/my.host.name@MY.REALM 1 des-cbc-crc host/my.host.name@MY.REALM 1 des3-cbc-sha1 host/my.host.name@MY.REALM  File: heimdal.info, Node: Remote administration, Next: Password changing, Prev: keytabs, Up: Setting up a realm 4.6 Remote administration ========================= The administration server, 'kadmind', can be started by 'inetd' (which isn't recommended) or run as a normal daemon. If you want to start it from 'inetd' you should add a line similar to the one below to your '/etc/inetd.conf'. kerberos-adm stream tcp nowait root /usr/heimdal/libexec/kadmind kadmind You might need to add 'kerberos-adm' to your '/etc/services' as '749/tcp'. Access to the administration server is controlled by an ACL file, (default '/var/heimdal/kadmind.acl'.) The file has the following syntax: principal [priv1,priv2,...] [glob-pattern] The matching is from top to bottom for matching principals (and if given, glob-pattern). When there is a match, the access rights of that line are applied. The privileges you can assign to a principal are: 'add', 'change-password' (or 'cpw' for short), 'delete', 'get', 'list', and 'modify', or the special privilege 'all'. All of these roughly correspond to the different commands in 'kadmin'. If a GLOB-PATTERN is given on a line, it restricts the access rights for the principal to only apply for subjects that match the pattern. The patterns are of the same type as those used in shell globbing, see fnmatch(3). In the example below 'lha/admin' can change every principal in the database. 'jimmy/admin' can only modify principals that belong to the realm 'E.KTH.SE'. 'mille/admin' is working at the help desk, so he should only be able to change the passwords for single component principals (ordinary users). He will not be able to change any '/admin' principal. lha/admin@E.KTH.SE all jimmy/admin@E.KTH.SE all *@E.KTH.SE jimmy/admin@E.KTH.SE all */*@E.KTH.SE mille/admin@E.KTH.SE change-password *@E.KTH.SE  File: heimdal.info, Node: Password changing, Next: Testing clients and servers, Prev: Remote administration, Up: Setting up a realm 4.7 Password changing ===================== To allow users to change their passwords, you should run 'kpasswdd'. It is not run from 'inetd'. You might need to add 'kpasswd' to your '/etc/services' as '464/udp'. If your realm is not setup to use DNS, you might also need to add a 'kpasswd_server' entry to the realm configuration in '/etc/krb5.conf' on client machines: [realms] MY.REALM = { kdc = my.kdc my.slave.kdc kpasswd_server = my.kdc } 4.7.1 Password quality assurance -------------------------------- It is important that users have good passwords, both to make it harder to guess them and to avoid off-line attacks (although pre-authentication provides some defence against off-line attacks). To ensure that the users choose good passwords, you can enable password quality controls in 'kpasswdd' and 'kadmind'. The controls themselves are done in a shared library or an external program that is used by 'kpasswdd'. To configure in these controls, add lines similar to the following to your '/etc/krb5.conf': [password_quality] policies = external-check builtin:minimum-length modulename:policyname external_program = /bin/false policy_libraries = LIBRARY1.SO LIBRARY2.SO In '[password_quality]policies' the module name is optional if the policy name is unique in all modules (members of 'policy_libraries'). All built-in policies can be qualified with a module name of 'builtin' to unambiguously specify the built-in policy and not a policy by the same name from a loaded module. The built-in policies are * external-check Executes the program specified by '[password_quality]external_program'. A number of key/value pairs are passed as input to the program, one per line, ending with the string 'end'. The key/value lines are of the form principal: PRINCIPAL new-password: PASSWORD where PASSWORD is the password to check for the previous PRINCIPAL. If the external application approves the password, it should return 'APPROVED' on standard out and exit with exit code 0. If it doesn't approve the password, an one line error message explaining the problem should be returned on standard error and the application should exit with exit code 0. In case of a fatal error, the application should, if possible, print an error message on standard error and exit with a non-zero error code. * minimum-length The minimum length password quality check reads the configuration file stanza '[password_quality]min_length' and requires the password to be at least this length. * character-class The character-class password quality check reads the configuration file stanza '[password_quality]min_classes'. The policy requires the password to have characters from at least that many character classes. Default value if not given is 3. The four different characters classes are, uppercase, lowercase, number, special characters. If you want to write your own shared object to check password policies, see the manual page 'kadm5_pwcheck(3)'. Code for a password quality checking function that uses the cracklib library can be found in 'lib/kadm5/sample_password_check.c' in the source code distribution. It requires that the cracklib library be built with the patch available at . A sample policy external program is included in 'lib/kadm5/check-cracklib.pl'. If no password quality checking function is configured, the only check performed is that the password is at least six characters long. To check the password policy settings, use the command 'verify-password-quality' in 'kadmin' program. The password verification is only performed locally, on the client. It may be convenient to set the environment variable 'KRB5_CONFIG' to point to a test version of 'krb5.conf' while you're testing the '[password_quality]' stanza that way.  File: heimdal.info, Node: Testing clients and servers, Next: Slave Servers, Prev: Password changing, Up: Setting up a realm 4.8 Testing clients and servers =============================== Now you should be able to run all the clients and servers. Refer to the appropriate man pages for information on how to use them.  File: heimdal.info, Node: Slave Servers, Next: Incremental propagation, Prev: Testing clients and servers, Up: Setting up a realm 4.9 Slave servers, Incremental propagation, Testing clients and servers, Setting up a realm =========================================================================================== It is desirable to have at least one backup (slave) server in case the master server fails. It is possible to have any number of such slave servers but more than three usually doesn't buy much more redundancy. All Kerberos servers for a realm must have the same database so that they present the same service to the users. The 'hprop' program, running on the master, will propagate the database to the slaves, running 'hpropd' processes. Every slave needs a database directory, the master key (if it was used for the database) and a keytab with the principal 'hprop/HOSTNAME'. Add the principal with the 'ktutil' command and start 'hpropd', as follows: slave# ktutil get -p foo/admin hprop/`hostname` slave# mkdir /var/heimdal slave# hpropd The master will use the principal 'kadmin/hprop' to authenticate to the slaves. This principal should be added when running 'kadmin -l init' but if you do not have it in your database for whatever reason, please add it with 'kadmin -l add'. Then run 'hprop' on the master: master# hprop slave This was just an hands-on example to make sure that everything was working properly. Doing it manually is of course the wrong way, and to automate this you will want to start 'hpropd' from 'inetd' on the slave(s) and regularly run 'hprop' on the master to regularly propagate the database. Starting the propagation once an hour from 'cron' is probably a good idea.  File: heimdal.info, Node: Incremental propagation, Next: Encryption types and salting, Prev: Slave Servers, Up: Setting up a realm 4.10 Incremental propagation ============================ There is also a newer mechanism for doing incremental propagation in Heimdal. Instead of sending the whole database regularly, it sends the changes as they happen on the master to the slaves. The master keeps track of all the changes by assigning a version number to every change to the database. The slaves know which was the latest version they saw and in this way it can be determined if they are in sync or not. A log of all the changes is kept on the master, and when a slave is at an older version than the oldest one in the log, the whole database has to be sent. Protocol-wise, all the slaves connect to the master and as a greeting tell it the latest version that they have ('IHAVE' message). The master then responds by sending all the changes between that version and the current version at the master (a series of 'FORYOU' messages) or the whole database in a 'TELLYOUEVERYTHING' message. There is also a keep-alive protocol that makes sure all slaves are up and running. In addition on listening on the network to get connection from new slaves, the ipropd-master also listens on a status unix socket. kadmind and kpasswdd both open that socket when a transation is done and written a notification to the socket. That cause ipropd-master to check for new version in the log file. As a fallback in case a notification is lost by the unix socket, the log file is checked after 30 seconds of no event. 4.10.1 Configuring incremental propagation ------------------------------------------ The program that runs on the master is 'ipropd-master' and all clients run 'ipropd-slave'. Create the file '/var/heimdal/slaves' on the master containing all the slaves that the database should be propagated to. Each line contains the full name of the principal (for example 'iprop/hemligare.foo.se@FOO.SE'). You should already have 'iprop/tcp' defined as 2121, in your '/etc/services'. Otherwise, or if you need to use a different port for some peculiar reason, you can use the '--port' option. This is useful when you have multiple realms to distribute from one server. Then you need to create those principals that you added in the configuration file. Create one 'iprop/hostname' for the master and for every slave. master# /usr/heimdal/sbin/ktutil get iprop/`hostname` slave# /usr/heimdal/sbin/ktutil get iprop/`hostname` The next step is to start the 'ipropd-master' process on the master server. The 'ipropd-master' listens on the UNIX domain socket '/var/heimdal/signal' to know when changes have been made to the database so they can be propagated to the slaves. There is also a safety feature of testing the version number regularly (every 30 seconds) to see if it has been modified by some means that do not raise this signal. Then, start 'ipropd-slave' on all the slaves: master# /usr/heimdal/libexec/ipropd-master & slave# /usr/heimdal/libexec/ipropd-slave master & To manage the iprop log file you should use the 'iprop-log' command. With it you can dump, truncate and replay the logfile. 4.10.2 Status of iprop master and slave --------------------------------------- Both the master and slave provides status of the world as they see it. The master write outs the current status of the slaves, last seen and their version number in '/var/heimdal/slaves-stats'. The slave write out the current status in '/var/heimdal/ipropd-slave-status'. These locations can be changed with command line options, and in the case of 'ipropd_master', the configuration file.  File: heimdal.info, Node: Encryption types and salting, Next: Credential cache server - KCM, Prev: Incremental propagation, Up: Setting up a realm 4.11 Encryption types and salting ================================= The encryption types that the KDC is going to assign by default is possible to change. Since the keys used for user authentication is salted the encryption types are described together with the salt strings. Salting is used to make it harder to pre-calculate all possible keys. Using a salt increases the search space to make it almost impossible to pre-calculate all keys. Salting is the process of mixing a public string (the salt) with the password, then sending it through an encryption type specific string-to-key function that will output the fixed size encryption key. In Kerberos 5 the salt is determined by the encryption type, except in some special cases. In 'des' there is the Kerberos 4 salt (none at all) or the afs-salt (using the cell (realm in AFS lingo)). In 'arcfour' (the encryption type that Microsoft Windows 2000 uses) there is no salt. This is to be compatible with NTLM keys in Windows NT 4. '[kadmin]default_keys' in 'krb5.conf' controls what salting to use. The syntax of '[kadmin]default_keys' is '[etype:]salt-type[:salt-string]'. 'etype' is the encryption type (des-cbc-crc, arcfour-hmac-md5, aes256-cts-hmac-sha1-96), 'salt-type' is the type of salt (pw-salt or afs3-salt), and the salt-string is the string that will be used as salt (remember that if the salt is appended/prepended, the empty salt "" is the same thing as no salt at all). Common types of salting include * 'v4' (or 'des:pw-salt:') The Kerberos 4 salting is using no salt at all. Reason there is colon at the end of the salt string is that it makes the salt the empty string (same as no salt). * 'v5' (or 'pw-salt') 'pw-salt' uses the default salt for each encryption type is specified for. If the encryption type 'etype' isn't given, all default encryption will be used. * 'afs3-salt' 'afs3-salt' is the salt that is used with Transarc kaserver. It's the cell name appended to the password.  File: heimdal.info, Node: Credential cache server - KCM, Next: Cross realm, Prev: Encryption types and salting, Up: Setting up a realm 4.12 Credential cache server - KCM ================================== When KCM running is easy for users to switch between different kerberos principals using 'kswitch' or built in support in application, like OpenSSH's GSSAPIClientIdentity. Other advantages are that there is the long term credentials are not written to disk and on reboot the credential is removed when kcm process stopps running. Configure the system startup script to start the kcm process, '/usr/heimdal/libexec/kcm' and then configure the system to use kcm in 'krb5.conf'. [libdefaults] default_cc_type = KCM Now when you run 'kinit' it doesn't overwrite your existing credentials but rather just add them to the set of credentials. 'klist -l' lists the credentials and the star marks the default credential. $ kinit lha@KTH.SE lha@KTH.SE's Password: $ klist -l Name Cache name Expires lha@KTH.SE 0 Nov 22 23:09:40 * lha@SU.SE Initial default ccache Nov 22 14:14:24 When switching between credentials you can use 'kswitch'. $ kswitch -i Principal 1 lha@KTH.SE 2 lha@SU.SE Select number: 2 After switching, a new set of credentials are used as default. $ klist -l Name Cache name Expires lha@SU.SE Initial default ccache Nov 22 14:14:24 * lha@KTH.SE 0 Nov 22 23:09:40 Som applications, like openssh with Simon Wilkinsons patch applied, support specifiying that credential to use. The example below will login to the host computer.kth.se using lha@KTH.SE (not the current default credential). $ ssh \ -o GSSAPIAuthentication=yes \ -o GSSAPIKeyExchange=yes \ -o GSSAPIClientIdentity=lha@KTH.SE \ computer.kth.se  File: heimdal.info, Node: Cross realm, Next: Transit policy, Prev: Credential cache server - KCM, Up: Setting up a realm 4.13 Cross realm ================ Suppose you reside in the realm 'MY.REALM', how do you authenticate to a server in 'OTHER.REALM'? Having valid tickets in 'MY.REALM' allows you to communicate with Kerberised services in that realm. However, the computer in the other realm does not have a secret key shared with the Kerberos server in your realm. It is possible to share keys between two realms that trust each other. When a client program, such as 'telnet' or 'ssh', finds that the other computer is in a different realm, it will try to get a ticket granting ticket for that other realm, but from the local Kerberos server. With that ticket granting ticket, it will then obtain service tickets from the Kerberos server in the other realm. For a two way trust between 'MY.REALM' and 'OTHER.REALM' add the following principals to each realm. The principals should be 'krbtgt/OTHER.REALM@MY.REALM' and 'krbtgt/MY.REALM@OTHER.REALM' in 'MY.REALM', and 'krbtgt/MY.REALM@OTHER.REALM' and 'krbtgt/OTHER.REALM@MY.REALM'in 'OTHER.REALM'. In Kerberos 5 the trust can be configured to be one way. So that users from 'MY.REALM' can authenticate to services in 'OTHER.REALM', but not the opposite. In the example above, the 'krbtgt/MY.REALM@OTHER.REALM' then should be removed. The two principals must have the same key, key version number, and the same set of encryption types. Remember to transfer the two keys in a safe manner. vr$ klist Credentials cache: FILE:/tmp/krb5cc_913.console Principal: lha@E.KTH.SE Issued Expires Principal May 3 13:55:52 May 3 23:55:54 krbtgt/E.KTH.SE@E.KTH.SE vr$ telnet -l lha hummel.it.su.se Trying 2001:6b0:5:1095:250:fcff:fe24:dbf... Connected to hummel.it.su.se. Escape character is '^]'. Waiting for encryption to be negotiated... [ Trying mutual KERBEROS5 (host/hummel.it.su.se@SU.SE)... ] [ Kerberos V5 accepts you as ``lha@E.KTH.SE'' ] Encryption negotiated. Last login: Sat May 3 14:11:47 from vr.l.nxs.se hummel$ exit vr$ klist Credentials cache: FILE:/tmp/krb5cc_913.console Principal: lha@E.KTH.SE Issued Expires Principal May 3 13:55:52 May 3 23:55:54 krbtgt/E.KTH.SE@E.KTH.SE May 3 13:55:56 May 3 23:55:54 krbtgt/SU.SE@E.KTH.SE May 3 14:10:54 May 3 23:55:54 host/hummel.it.su.se@SU.SE  File: heimdal.info, Node: Transit policy, Next: Setting up DNS, Prev: Cross realm, Up: Setting up a realm 4.14 Transit policy =================== Under some circumstances, you may not wish to set up direct cross-realm trust with every realm to which you wish to authenticate or from which you wish to accept authentications. Kerberos supports multi-hop cross-realm trust where a client principal in realm A authenticates to a service in realm C through a realm B with which both A and C have cross-realm trust relationships. In this situation, A and C need not set up cross-realm principals between each other. If you want to use cross-realm authentication through an intermediate realm, it must be explicitly allowed by either the KDCs for the realm to which the client is authenticating (in this case, realm C), or the server receiving the request. This is done in 'krb5.conf' in the '[capaths]' section. In addition, the client in realm A need to be configured to know how to reach realm C via realm B. This can be done either on the client or via KDC configuration in the KDC for realm A. 4.14.1 Allowing cross-realm transits ------------------------------------ When the ticket transits through a realm to another realm, the destination realm adds its peer to the "transited-realms" field in the ticket. The field is unordered, since there is no way to know if know if one of the transited-realms changed the order of the list. For the authentication to be accepted by the final destination realm, all of the transited realms must be listed as trusted in the '[capaths]' configuration, either in the KDC for the destination realm or on the server receiving the authentication. The syntax for '[capaths]' section is: [capaths] CLIENT-REALM = { SERVER-REALM = PERMITTED-CROSS-REALMS ... } In the following example, the realm 'STACKEN.KTH.SE' only has direct cross-realm set up with 'KTH.SE'. 'KTH.SE' has direct cross-realm set up with 'STACKEN.KTH.SE' and 'SU.SE'. 'DSV.SU.SE' only has direct cross-realm set up with 'SU.SE'. The goal is to allow principals in the 'DSV.SU.SE' or 'SU.SE' realms to authenticate to services in 'STACKEN.KTH.SE'. This is done with the following '[capaths]' entry on either the server accepting authentication or on the KDC for 'STACKEN.KTH.SE'. [capaths] SU.SE = { STACKEN.KTH.SE = KTH.SE } DSV.SU.SE = { STACKEN.KTH.SE = SU.SE KTH.SE } The first entry allows cross-realm authentication from clients in 'SU.SE' transiting through 'KTH.SE' to 'STACKEN.KTH.SE'. The second entry allows cross-realm authentication from clients in 'DSV.SU.SE' transiting through both 'SU.SE' and 'KTH.SE' to 'STACKEN.KTH.SE'. Be careful of which realm goes where; it's easy to put realms in the wrong place. The block is tagged with the client realm (the realm of the principal authenticating), and the realm before the equal sign is the final destination realm: the realm to which the client is authenticating. After the equal sign go all the realms that the client transits through. The order of the 'PERMITTED-CROSS-REALMS' is not important when doing transit cross realm verification. 4.14.2 Configuring client cross-realm transits ---------------------------------------------- The '[capaths]' section is also used for another purpose: to tell clients which realm to transit through to reach a realm with which their local realm does not have cross-realm trust. This can be done by either putting a '[capaths]' entry in the configuration of the client or by putting the entry in the configuration of the KDC for the client's local realm. In the latter case, the KDC will then hand back a referral to the client when the client requests a cross-realm ticket to the destination realm, telling the client to try to go through an intermediate realm. For client configuration, the order of 'PERMITTED-CROSS-REALMS' is significant, since only the first realm in this section (after the equal sign) is used by the client. For example, again consider the '[capaths]' entry above for the case of a client in the 'SU.SE' realm, and assume that the client or the 'SU.SE' KDC has that '[capaths]' entry. If the client attempts to authenticate to a service in the 'STACKEN.KTH.SE' realm, that entry says to first authenticate cross-realm to the 'KTH.SE' realm (the first realm listed in the 'PERMITTED-CROSS-REALMS' section), and then from there to 'STACKEN.KTH.SE'. Each entry in '[capaths]' can only give the next hop, since only the first realm in 'PERMITTED-CROSS-REALMS' is used. If, for instance, a client in 'DSV.SU.SE' had a '[capaths]' configuration as above but without the first block for 'SU.SE', they would not be able to reach 'STACKEN.KTH.SE'. They would get as far as 'SU.SE' based on the 'DSV.SU.SE' entry in '[capaths]' and then attempt to go directly from there to 'STACKEN.KTH.SE' and get stuck (unless, of course, the 'SU.SE' KDC had the additional entry required to tell the client to go through 'KTH.SE'). 4.14.3 Active Directory forest example -------------------------------------- One common place where a '[capaths]' configuration is desirable is with Windows Active Directory forests. One common Active Directory configuration is to have one top-level Active Directory realm but then divide systems, services, and users into child realms (perhaps based on organizational unit). One generally establishes cross-realm trust only with the top-level realm, and then uses transit policy to permit authentications to and from the child realms. For example, suppose an organization has a Heimdal realm 'EXAMPLE.COM', a Windows Active Directory realm 'WIN.EXAMPLE.COM', and then child Active Directory realms 'ENGR.WIN.EXAMPLE.COM' and 'SALES.WIN.EXAMPLE.COM'. The goal is to allow users in any of these realms to authenticate to services in any of these realms. The 'EXAMPLE.COM' KDC (and possibly client) configuration should therefore contain a '[capaths]' section as follows: [capaths] ENGR.WIN.EXAMPLE.COM = { EXAMPLE.COM = WIN.EXAMPLE.COM } SALES.WIN.EXAMPLE.COM = { EXAMPLE.COM = WIN.EXAMPLE.COM } EXAMPLE.COM = { ENGR.WIN.EXAMPLE.COM = WIN.EXAMPLE.COM SALES.WIN.EXAMPLE.COM = WIN.EXAMPLE.COM } The first two blocks allow clients in the 'ENGR.WIN.EXAMPLE.COM' and 'SALES.WIN.EXAMPLE.COM' realms to authenticate to services in the 'EXAMPLE.COM' realm. The third block tells the client (or tells the KDC to tell the client via referrals) to transit through 'WIN.EXAMPLE.COM' to reach these realms. Both sides of the configuration are needed for bi-directional transited cross-realm authentication.  File: heimdal.info, Node: Setting up DNS, Next: Using LDAP to store the database, Prev: Transit policy, Up: Setting up a realm 4.15 Setting up DNS =================== 4.15.1 Using DNS to find KDC ---------------------------- If there is information about where to find the KDC or kadmind for a realm in the 'krb5.conf' for a realm, that information will be preferred, and DNS will not be queried. Heimdal will try to use DNS to find the KDCs for a realm. First it will try to find a 'SRV' resource record (RR) for the realm. If no SRV RRs are found, it will fall back to looking for an 'A' RR for a machine named kerberos.REALM, and then kerberos-1.REALM, etc Adding this information to DNS minimises the client configuration (in the common case, resulting in no configuration needed) and allows the system administrator to change the number of KDCs and on what machines they are running without caring about clients. The downside of using DNS is that the client might be fooled to use the wrong server if someone fakes DNS replies/data, but storing the IP addresses of the KDC on all the clients makes it very hard to change the infrastructure. An example of the configuration for the realm 'EXAMPLE.COM': $ORIGIN example.com. _kerberos._tcp SRV 10 1 88 kerberos.example.com. _kerberos._udp SRV 10 1 88 kerberos.example.com. _kerberos._tcp SRV 10 1 88 kerberos-1.example.com. _kerberos._udp SRV 10 1 88 kerberos-1.example.com. _kpasswd._udp SRV 10 1 464 kerberos.example.com. _kerberos-adm._tcp SRV 10 1 749 kerberos.example.com. More information about DNS SRV resource records can be found in RFC-2782 (A DNS RR for specifying the location of services (DNS SRV)). 4.15.2 Using DNS to map hostname to Kerberos realm -------------------------------------------------- Heimdal also supports a way to lookup a realm from a hostname. This to minimise configuration needed on clients. Using this has the drawback that clients can be redirected by an attacker to realms within the same cross realm trust and made to believe they are talking to the right server (since Kerberos authentication will succeed). An example configuration that informs clients that for the realms it.example.com and srv.example.com, they should use the realm EXAMPLE.COM: $ORIGIN example.com. _kerberos.it TXT "EXAMPLE.COM" _kerberos.srv TXT "EXAMPLE.COM"  File: heimdal.info, Node: Using LDAP to store the database, Next: Providing Kerberos credentials to servers and programs, Prev: Setting up DNS, Up: Setting up a realm 4.16 Using LDAP to store the database ===================================== This document describes how to install the LDAP backend for Heimdal. Note that before attempting to configure such an installation, you should be aware of the implications of storing private information (such as users' keys) in a directory service primarily designed for public information. Nonetheless, with a suitable authorisation policy, it is possible to set this up in a secure fashion. A knowledge of LDAP, Kerberos, and C is necessary to install this backend. The HDB schema was devised by Leif Johansson. This assumes, OpenLDAP 2.3 or later. Requirements: * A current release of Heimdal, configured with '--with-openldap=/usr/local' (adjust according to where you have installed OpenLDAP). You can verify that you manage to configure LDAP support by running 'kdc --builtin-hdb', and checking that 'ldap:' is one entry in the list. Its also possible to configure the ldap backend as a shared module, see option -hdb-openldap-module to configure. * Optionally configure OpenLDAP with '--enable-local' to enable the local transport. * Add the hdb schema to the LDAP server, it's included in the source-tree in 'lib/hdb/hdb.schema'. Example from slapd.conf: include /usr/local/etc/openldap/schema/hdb.schema * Configure the LDAP server ACLs to accept writes from clients. For example: access to * by dn.exact="uid=heimdal,dc=services,dc=example,dc=com" write ... authz-regexp "gidNumber=.*\\\+uidNumber=0,cn=peercred,cn=external,cn=auth'' "uid=heimdal,dc=services,dc=example,dc=com" The sasl-regexp is for mapping between the SASL/EXTERNAL and a user in a tree. The user that the key is mapped to should be have a krb5Principal aux object with krb5PrincipalName set so that the "creator" and "modifier" is right in 'kadmin'. Another option is to create an admins group and add the dn to that group. If a non-local LDAP connection is used, the authz-regexp is not needed as Heimdal will bind to LDAP over the network using provided credentials. Since Heimdal talks to the LDAP server over a UNIX domain socket when configured for ldapi:///, and uses external sasl authentication, it's not possible to require security layer quality (ssf in cyrus-sasl lingo). So that requirement has to be turned off in OpenLDAP 'slapd' configuration file 'slapd.conf'. sasl-secprops minssf=0 * Start 'slapd' with the local listener (as well as the default TCP/IP listener on port 389) as follows: slapd -h "ldapi:/// ldap:///" Note: These is a bug in 'slapd' where it appears to corrupt the krb5Key binary attribute on shutdown. This may be related to our use of the V3 schema definition syntax instead of the old UMich-style, V2 syntax. * You should specify the distinguished name under which your principals will be stored in 'krb5.conf'. Also you need to enter the path to the kadmin acl file: [kdc] # Optional configuration hdb-ldap-structural-object = inetOrgPerson hdb-ldap-url = ldapi:/// (default), ldap://hostname or ldaps://hostname hdb-ldap-secret-file = /path/to/file/containing/ldap/credentials hdb-ldap-start-tls = false database = { dbname = ldap:ou=KerberosPrincipals,dc=example,dc=com acl_file = /path/to/kadmind.acl mkey_file = /path/to/mkey } 'mkey_file' can be excluded if you feel that you trust your ldap directory to have the raw keys inside it. The hdb-ldap-structural-object is not necessary if you do not need Samba comatibility. If connecting to a server over a non-local transport, the 'hdb-ldap-url' and 'hdb-ldap-secret-file' options must be provided. The 'hdb-ldap-secret-file' must contain the bind credentials: [kdc] hdb-ldap-bind-dn = uid=heimdal,dc=services,dc=example,dc=com hdb-ldap-bind-password = secretBindPassword The 'hdb-ldap-secret-file' and should be protected with appropriate file permissions * Once you have built Heimdal and started the LDAP server, run kadmin (as usual) to initialise the database. Note that the instructions for stashing a master key are as per any Heimdal installation. kdc# kadmin -l kadmin> init EXAMPLE.COM Realm max ticket life [unlimited]: Realm max renewable ticket life [unlimited]: kadmin> add lukeh Max ticket life [1 day]: Max renewable life [1 week]: Principal expiration time [never]: Password expiration time [never]: Attributes []: lukeh@EXAMPLE.COM's Password: Verifying password - lukeh@EXAMPLE.COM's Password: kadmin> exit Verify that the principal database has indeed been stored in the directory with the following command: kdc# ldapsearch -L -h localhost -D cn=manager \ -w secret -b ou=KerberosPrincipals,dc=example,dc=com \ 'objectclass=krb5KDCEntry' * Now consider adding indexes to the database to speed up the access, at least theses should be added to slapd.conf. index objectClass eq index cn eq,sub,pres index uid eq,sub,pres index displayName eq,sub,pres index krb5PrincipalName eq 4.16.1 smbk5pwd overlay ----------------------- The smbk5pwd overlay, updates the krb5Key and krb5KeyVersionNumber appropriately when it receives an LDAP Password change Extended Operation: 4.16.2 Troubleshooting guide ---------------------------- 4.16.3 Using Samba LDAP password database ----------------------------------------- The Samba domain and the Kerberos realm can have different names since arcfour's string to key functions principal/realm independent. So now will be your first and only chance name your Kerberos realm without needing to deal with old configuration files. First, you should set up Samba and get that working with LDAP backend. Now you can proceed as in *Note Using LDAP to store the database::. Heimdal will pick up the Samba LDAP entries if they are in the same search space as the Kerberos entries.  File: heimdal.info, Node: Providing Kerberos credentials to servers and programs, Next: Setting up PK-INIT, Prev: Using LDAP to store the database, Up: Setting up a realm 4.17 Providing Kerberos credentials to servers and programs =========================================================== Some services require Kerberos credentials when they start to make connections to other services or need to use them when they have started. The easiest way to get tickets for a service is to store the key in a keytab. Both ktutil get and kadmin ext can be used to get a keytab. ktutil get is better in that way it changes the key/password for the user. This is also the problem with ktutil. If ktutil is used for the same service principal on several hosts, they keytab will only be useful on the last host. In that case, run the extract command on one host and then securely copy the keytab around to all other hosts that need it. host# ktutil -k /etc/krb5-service.keytab \ get -p lha/admin@EXAMPLE.ORG service-principal@EXAMPLE.ORG lha/admin@EXAMPLE.ORG's Password: To get a Kerberos credential file for the service, use kinit in the '--keytab' mode. This will not ask for a password but instead fetch the key from the keytab. service@host$ kinit --cache=/var/run/service_krb5_cache \ --keytab=/etc/krb5-service.keytab \ service-principal@EXAMPLE.ORG Long running services might need credentials longer then the expiration time of the tickets. kinit can run in a mode that refreshes the tickets before they expire. This is useful for services that write into AFS and other distributed file systems using Kerberos. To run the long running script, just append the program and arguments (if any) after the principal. kinit will stop refreshing credentials and remove the credentials when the script-to-start-service exits. service@host$ kinit --cache=/var/run/service_krb5_cache \ --keytab=/etc/krb5-service.keytab \ service-principal@EXAMPLE.ORG \ script-to-start-service argument1 argument2  File: heimdal.info, Node: Setting up PK-INIT, Next: Debugging Kerberos problems, Prev: Providing Kerberos credentials to servers and programs, Up: Setting up a realm 4.18 Setting up PK-INIT ======================= PK-INIT leverages an existing PKI (public key infrastructure), using certificates to get the initial ticket (usually the krbtgt ticket-granting ticket). To use PK-INIT you must first have a PKI. If you don't have one, it is time to create it. You should first read the whole current chapter of the document to see the requirements imposed on the CA software. A mapping between the PKI certificate and what principals that certificate is allowed to use must exist. There are several ways to do this. The administrator can use a configuration file, store the principal in the SubjectAltName extension of the certificate, or store the mapping in the principals entry in the kerberos database. 4.19 Certificates ================= This and following subsection documents the requirements on the KDC and client certificates and the format used in the id-pkinit-san OtherName extension. On how to create certificates, you should read *note Use OpenSSL to create certificates::. 4.19.1 KDC certificate ---------------------- The certificate for the KDC has several requirements. First, the certificate should have an Extended Key Usage (EKU) id-pkkdcekuoid (1.3.6.1.5.2.3.5) set. Second, there must be a subjectAltName otherName using OID id-pkinit-san (1.3.6.1.5.2.2) in the type field and a DER encoded KRB5PrincipalName that matches the name of the TGS of the target realm. Also, if the certificate has a nameConstraints extension with a Generalname with dNSName or iPAdress, it must match the hostname or adress of the KDC. The client is not required by the standard to check the server certificate for this information if the client has external information confirming which certificate the KDC is supposed to be using. However, adding this information to the KDC certificate removes the need to specially configure the client to recognize the KDC certificate. Remember that if the client would accept any certificate as the KDC's certificate, the client could be fooled into trusting something that isn't a KDC and thus expose the user to giving away information (like a password or other private information) that it is supposed to keep secret. 4.19.2 Client certificate ------------------------- The client certificate may need to have a EKU id-pkekuoid (1.3.6.1.5.2.3.4) set depending on the configuration on the KDC. It possible to store the principal (if allowed by the KDC) in the certificate and thus delegate responsibility to do the mapping between certificates and principals to the CA. This behavior is controlled by KDC configuration option: [kdc] pkinit_principal_in_certificate = yes 4.19.2.1 Using KRB5PrincipalName in id-pkinit-san ................................................. The OtherName extension in the GeneralName is used to do the mapping between certificate and principal. For the KDC certificate, this stores the krbtgt principal name for that KDC. For the client certificate, this stores the principal for which that certificate is allowed to get tickets. The principal is stored in a SubjectAltName in the certificate using OtherName. The OID in the type is id-pkinit-san. id-pkinit-san OBJECT IDENTIFIER ::= { iso (1) org (3) dod (6) internet (1) security (5) kerberosv5 (2) 2 } The data part of the OtherName is filled with the following DER encoded ASN.1 structure: KRB5PrincipalName ::= SEQUENCE { realm [0] Realm, principalName [1] PrincipalName } where Realm and PrincipalName is defined by the Kerberos ASN.1 specification. 4.20 Naming certificate using hx509 =================================== hx509 is the X.509 software used in Heimdal to handle certificates. hx509 supports several different syntaxes for specifying certificate files or formats. Several formats may be used: PEM, certificates embedded in PKCS#12 files, certificates embedded in PKCS#11 devices, and raw DER encoded certificates. Those formats may be specified as follows: DIR: DIR specifies a directory which contains certificates in the DER or PEM format. The main feature of DIR is that the directory is read on demand when iterating over certificates. This allows applications, in some situations, to avoid having to store all certificates in memory. It's very useful for tests that iterate over large numbers of certificates. The syntax is: DIR:/path/to/der/files FILE: FILE: specifies a file that contains a certificate or private key. The file can be either a PEM (openssl) file or a raw DER encoded certificate. If it's a PEM file, it can contain several keys and certificates and the code will try to match the private key and certificate together. Multiple files may be specified, separated by commas. It's useful to have one PEM file that contains all the trust anchors. The syntax is: FILE:certificate.pem,private-key.key,other-cert.pem,.... PKCS11: PKCS11: is used to handle smartcards via PKCS#11 drivers, such as soft-token, opensc, or muscle. The argument specifies a shared object that implements the PKCS#11 API. The default is to use all slots on the device/token. The syntax is: PKCS11:shared-object.so PKCS12: PKCS12: is used to handle PKCS#12 files. PKCS#12 files commonly have the extension pfx or p12. The syntax is: PKCS12:/path/to/file.pfx 4.21 Configure the Kerberos software ==================================== First configure the client's trust anchors and what parameters to verify. See the subsections below for how to do that. Then, you can use kinit to get yourself tickets. For example: $ kinit -C FILE:$HOME/.certs/lha.crt,$HOME/.certs/lha.key lha@EXAMPLE.ORG Enter your private key passphrase: : lha@nutcracker ; klist Credentials cache: FILE:/tmp/krb5cc_19100a Principal: lha@EXAMPLE.ORG Issued Expires Principal Apr 20 02:08:08 Apr 20 12:08:08 krbtgt/EXAMPLE.ORG@EXAMPLE.ORG Using PKCS#11 it can look like this instead: $ kinit -C PKCS11:/usr/heimdal/lib/hx509.so lha@EXAMPLE.ORG PIN code for SoftToken (slot): $ klist Credentials cache: API:4 Principal: lha@EXAMPLE.ORG Issued Expires Principal Mar 26 23:40:10 Mar 27 09:40:10 krbtgt/EXAMPLE.ORG@EXAMPLE.ORG 4.22 Configure the client ========================= [appdefaults] pkinit_anchors = FILE:/path/to/trust-anchors.pem [realms] EXAMPLE.COM = { pkinit_require_eku = true pkinit_require_krbtgt_otherName = true pkinit_win2k = no pkinit_win2k_require_binding = yes } 4.23 Configure the KDC ====================== Configuration options for the KDC. enable-pkinit = bool Enable PKINIT for this KDC. pkinit_identity = string Identity that the KDC will use when talking to clients. Mandatory. pkinit_anchors = string Trust anchors that the KDC will use when evaluating the trust of the client certificate. Mandatory. pkinit_pool = strings ... Extra certificate the KDC will use when building trust chains if it can't find enough certificates in the request from the client. pkinit_allow_proxy_certificate = bool Allow clients to use proxy certificates. The root certificate of the client's End Entity certificate is used for authorisation. pkinit_win2k_require_binding = bool Require windows clients up be upgrade to not allow cut and paste attack on encrypted data, applies to Windows XP and windows 2000 servers. pkinit_principal_in_certificate = bool Enable the KDC to use id-pkinit-san to determine to determine the mapping between a certificate and principal. [kdc] enable-pkinit = yes pkinit_identity = FILE:/secure/kdc.crt,/secure/kdc.key pkinit_anchors = FILE:/path/to/trust-anchors.pem pkinit_pool = PKCS12:/path/to/useful-intermediate-certs.pfx pkinit_pool = FILE:/path/to/other-useful-intermediate-certs.pem pkinit_allow_proxy_certificate = no pkinit_win2k_require_binding = yes pkinit_principal_in_certificate = no 4.23.1 Using pki-mapping file ----------------------------- Note that the file contents are space sensitive. # cat /var/heimdal/pki-mapping # comments starts with # lha@EXAMPLE.ORG:C=SE,O=Stockholm universitet,CN=Love,UID=lha lha@EXAMPLE.ORG:CN=Love,UID=lha 4.23.2 Using the Kerberos database ---------------------------------- You can also store the subject of the certificate in the principal entry in the kerberos database. kadmin modify --pkinit-acl="CN=baz,DC=test,DC=h5l,DC=se" user@REALM 4.24 Use hxtool to create certificates ====================================== 4.24.1 Generate certificates ---------------------------- First, you need to generate a CA certificate. This example creates a CA certificate that will be valid for 10 years. You need to change -subject in the command below to something appropriate for your site. hxtool issue-certificate \ --self-signed \ --issue-ca \ --generate-key=rsa \ --subject="CN=CA,DC=test,DC=h5l,DC=se" \ --lifetime=10years \ --certificate="FILE:ca.pem" The KDC needs to have a certificate, so generate a certificate of the type "pkinit-kdc" and set the PK-INIT specifial SubjectAltName to the name of the krbtgt of the realm. You need to change -subject and -pk-init-principal in the command below to something appropriate for your site. hxtool issue-certificate \ --ca-certificate=FILE:ca.pem \ --generate-key=rsa \ --type="pkinit-kdc" \ --pk-init-principal="krbtgt/TEST.H5L.SE@TEST.H5L.SE" \ --subject="uid=kdc,DC=test,DC=h5l,DC=se" \ --certificate="FILE:kdc.pem" The users also needs to have certificates. For your first client, generate a certificate of type "pkinit-client". The client doesn't need to have the PK-INIT SubjectAltName set; you can have the Subject DN in the ACL file (pki-mapping) instead. You need to change -subject and -pk-init-principal in the command below to something appropriate for your site. You can omit -pk-init-principal if you're going to use the ACL file instead. hxtool issue-certificate \ --ca-certificate=FILE:ca.pem \ --generate-key=rsa \ --type="pkinit-client" \ --pk-init-principal="lha@TEST.H5L.SE" \ --subject="uid=lha,DC=test,DC=h5l,DC=se" \ --certificate="FILE:user.pem" 4.24.2 Validate the certificate ------------------------------- hxtool also contains a tool that will validate certificates according to rules from the PKIX document. These checks are not complete, but they provide a good test of whether you got all of the basic bits right in your certificates. hxtool validate FILE:user.pem 4.25 Use OpenSSL to create certificates ======================================= This section tries to give the CA owners hints how to create certificates using OpenSSL (or CA software based on OpenSSL). 4.25.1 Using OpenSSL to create certificates with krb5PrincipalName ------------------------------------------------------------------ To make OpenSSL create certificates with krb5PrincipalName, use an 'openssl.cnf' as described below. To see a complete example of creating client and KDC certificates, see the test-data generation script 'lib/hx509/data/gen-req.sh' in the source-tree. The certicates it creates are used to test the PK-INIT functionality in 'tests/kdc/check-kdc.in'. To use this example you have to use OpenSSL 0.9.8a or later. [user_certificate] subjectAltName=otherName:1.3.6.1.5.2.2;SEQUENCE:princ_name [princ_name] realm = EXP:0, GeneralString:MY.REALM principal_name = EXP:1, SEQUENCE:principal_seq [principal_seq] name_type = EXP:0, INTEGER:1 name_string = EXP:1, SEQUENCE:principals [principals] princ1 = GeneralString:userid Command usage: openssl x509 -extensions user_certificate openssl ca -extensions user_certificate 4.26 Using PK-INIT with Windows =============================== 4.26.1 Client configration -------------------------- Clients using a Windows KDC with PK-INIT need configuration since windows uses pre-standard format and this can't be autodetected. The pkinit_win2k_require_binding option requires the reply for the KDC to be of the new, secure, type that binds the request to reply. Before, clients could fake the reply from the KDC. To use this option you have to apply a fix from Microsoft. [realms] MY.MS.REALM = { pkinit_win2k = yes pkinit_win2k_require_binding = no } 4.26.2 Certificates ------------------- The client certificates need to have the extended keyusage "Microsoft Smartcardlogin" (openssl has the OID shortname msSmartcardLogin). See Microsoft Knowledge Base Article - 281245 "Guidelines for Enabling Smart Card Logon with Third-Party Certification Authorities" for a more extensive description of how set setup an external CA so that it includes all the information required to make a Windows KDC happy. 4.26.3 Configure Windows 2000 CA -------------------------------- To enable Microsoft Smartcardlogin for certificates in your Windows 2000 CA, you want to look at Microsoft Knowledge Base Article - 313274 "HOW TO: Configure a Certification Authority to Issue Smart Card Certificates in Windows".  File: heimdal.info, Node: Debugging Kerberos problems, Prev: Setting up PK-INIT, Up: Setting up a realm 4.27 Debugging Kerberos problems ================================ To debug Kerberos client and server problems you can enable debug traceing by adding the following to '/etc/krb5,conf'. Note that the trace logging is sparse at the moment, but will continue to improve. [logging] libkrb5 = 0-/SYSLOG:  File: heimdal.info, Node: Applications, Next: Things in search for a better place, Prev: Setting up a realm, Up: Top 5 Applications ************** * Menu: * Authentication modules:: * AFS::  File: heimdal.info, Node: Authentication modules, Next: AFS, Prev: Applications, Up: Applications 5.1 Authentication modules ========================== The problem of having different authentication mechanisms has been recognised by several vendors, and several solutions have appeared. In most cases these solutions involve some kind of shared modules that are loaded at run-time. Modules for some of these systems can be found in 'lib/auth'. Presently there are modules for Digital's SIA, and IRIX' 'login' and 'xdm' (in 'lib/auth/afskauthlib'). * Menu: * Digital SIA:: * IRIX::  File: heimdal.info, Node: Digital SIA, Next: IRIX, Prev: Authentication modules, Up: Authentication modules 5.1.1 Digital SIA ----------------- How to install the SIA module depends on which OS version you're running. Tru64 5.0 has a new command, 'siacfg', which makes this process quite simple. If you have this program, you should just be able to run: siacfg -a KRB5 /usr/athena/lib/libsia_krb5.so On older versions, or if you want to do it by hand, you have to do the following (not tested by us on Tru64 5.0): * Make sure 'libsia_krb5.so' is available in '/usr/athena/lib'. If '/usr/athena' is not on local disk, you might want to put it in '/usr/shlib' or someplace else. If you do, you'll have to edit 'krb5_matrix.conf' to reflect the new location (you will also have to do this if you installed in some other directory than '/usr/athena'). If you built with shared libraries, you will have to copy the shared 'libkrb.so', 'libdes.so', 'libkadm.so', and 'libkafs.so' to a place where the loader can find them (such as '/usr/shlib'). * Copy (your possibly edited) 'krb5_matrix.conf' to '/etc/sia'. * Apply 'security.patch' to '/sbin/init.d/security'. * Turn on KRB5 security by issuing 'rcmgr set SECURITY KRB5' and 'rcmgr set KRB5_MATRIX_CONF krb5_matrix.conf'. * Digital thinks you should reboot your machine, but that really shouldn't be necessary. It's usually sufficient just to run '/sbin/init.d/security start' (and restart any applications that use SIA, like 'xdm'.) Users with local passwords (like 'root') should be able to login safely. When using Digital's xdm the 'KRB5CCNAME' environment variable isn't passed along as it should (since xdm zaps the environment). Instead you have to set 'KRB5CCNAME' to the correct value in '/usr/lib/X11/xdm/Xsession'. Add a line similar to KRB5CCNAME=FILE:/tmp/krb5cc`id -u`_`ps -o ppid= -p $$`; export KRB5CCNAME If you use CDE, 'dtlogin' allows you to specify which additional environment variables it should export. To add 'KRB5CCNAME' to this list, edit '/usr/dt/config/Xconfig', and look for the definition of 'exportList'. You want to add something like: Dtlogin.exportList: KRB5CCNAME Notes to users with Enhanced security ..................................... Digital's 'ENHANCED' (C2) security, and Kerberos solve two different problems. C2 deals with local security, adds better control of who can do what, auditing, and similar things. Kerberos deals with network security. To make C2 security work with Kerberos you will have to do the following. * Replace all occurrences of 'krb5_matrix.conf' with 'krb5+c2_matrix.conf' in the directions above. * You must enable "vouching" in the 'default' database. This will make the OSFC2 module trust other SIA modules, so you can login without giving your C2 password. To do this use 'edauth' to edit the default entry '/usr/tcb/bin/edauth -dd default', and add a 'd_accept_alternate_vouching' capability, if not already present. * For each user who does _not_ have a local C2 password, you should set the password expiration field to zero. You can do this for each user, or in the 'default' table. To do this use 'edauth' to set (or change) the 'u_exp' capability to 'u_exp#0'. * You also need to be aware that the shipped 'login', 'rcp', and 'rshd', don't do any particular C2 magic (such as checking for various forms of disabled accounts), so if you rely on those features, you shouldn't use those programs. If you configure with '--enable-osfc2', these programs will, however, set the login UID. Still: use at your own risk. At present 'su' does not accept the vouching flag, so it will not work as expected. Also, kerberised ftp will not work with C2 passwords. You can solve this by using both Digital's ftpd and our on different ports. *Remember*, if you do these changes you will get a system that most certainly does _not_ fulfil the requirements of a C2 system. If C2 is what you want, for instance if someone else is forcing you to use it, you're out of luck. If you use enhanced security because you want a system that is more secure than it would otherwise be, you probably got an even more secure system. Passwords will not be sent in the clear, for instance.  File: heimdal.info, Node: IRIX, Prev: Digital SIA, Up: Authentication modules 5.1.2 IRIX ---------- The IRIX support is a module that is compatible with Transarc's 'afskauthlib.so'. It should work with all programs that use this library. This should include 'login' and 'xdm'. The interface is not very documented but it seems that you have to copy 'libkafs.so', 'libkrb.so', and 'libdes.so' to '/usr/lib', or build your 'afskauthlib.so' statically. The 'afskauthlib.so' itself is able to reside in '/usr/vice/etc', '/usr/afsws/lib', or the current directory (wherever that is). IRIX 6.4 and newer seem to have all programs (including 'xdm' and 'login') in the N32 object format, whereas in older versions they were O32. For it to work, the 'afskauthlib.so' library has to be in the same object format as the program that tries to load it. This might require that you have to configure and build for O32 in addition to the default N32. Apart from this it should "just work"; there are no configuration files. Note that recent Irix 6.5 versions (at least 6.5.22) have PAM, including a 'pam_krb5.so' module. Not all relevant programs use PAM, though, e.g. 'ssh'. In particular, for console graphical login you need to turn off 'visuallogin' and turn on 'xdm' with 'chkconfig'.  File: heimdal.info, Node: AFS, Prev: Authentication modules, Up: Applications 5.2 AFS ======= AFS is a distributed filesystem that uses Kerberos for authentication. For more information about AFS see OpenAFS and Arla . 5.2.1 kafs and afslog --------------------- 'afslog(1)' will obtains AFS tokens for a number of cells. What cells to get tokens for can either be specified as an explicit list, as file paths to get tokens for, or be left unspecified, in which case will use whatever magic 'kafs(3)' decides upon. If not told what cell to get credentials for, 'kafs(3)' will search for the files ThisCell and TheseCells in the locations specified in 'kafs(3)' and try to get tokens for these cells and the cells specified in $HOME/.TheseCells. More usefully it will look at and ~/.TheseCells in your home directory and for each line which is a cell get afs token for these cells. The TheseCells file defines the the cells to which applications on the local client machine should try to aquire tokens for. It must reside in the directories searched by 'kafs(3)' on every AFS client machine. The file is in ASCII format and contains one character string, the cell name, per line. Cell names are case sensitive, but most cell names are lower case. See manpage for 'kafs(3)' for search locations of ThisCell and TheseCells. 5.2.2 How to get a KeyFile -------------------------- 'ktutil -k AFSKEYFILE:KeyFile get afs@MY.REALM' or you can extract it with kadmin kadmin> ext -k AFSKEYFILE:/usr/afs/etc/KeyFile afs@My.CELL.NAME You have to make sure you have a 'des-cbc-md5' encryption type since that is the enctype that will be converted. 5.2.3 How to convert a srvtab to a KeyFile ------------------------------------------ You need a '/usr/vice/etc/ThisCell' containing the cellname of your AFS-cell. 'ktutil copy krb4:/root/afs-srvtab AFSKEYFILE:/usr/afs/etc/KeyFile'. If keyfile already exists, this will add the new key in afs-srvtab to KeyFile. 5.3 Using 2b tokens with AFS ============================ 5.3.1 What is 2b ? ------------------ 2b is the name of the proposal that was implemented to give basic Kerberos 5 support to AFS in rxkad. It's not real Kerberos 5 support since it still uses fcrypt for data encryption and not Kerberos encryption types. Its only possible (in all cases) to do this for DES encryption types because only then the token (the AFS equivalent of a ticket) will be smaller than the maximum size that can fit in the token cache in the OpenAFS/Transarc client. It is a so tight fit that some extra wrapping on the ASN1/DER encoding is removed from the Kerberos ticket. 2b uses a Kerberos 5 EncTicketPart instead of a Kerberos 4 ditto for the part of the ticket that is encrypted with the service's key. The client doesn't know what's inside the encrypted data so to the client it doesn't matter. To differentiate between Kerberos 4 tickets and Kerberos 5 tickets, 2b uses a special kvno, 213 for 2b tokens and 255 for Kerberos 5 tokens. Its a requirement that all AFS servers that support 2b also support native Kerberos 5 in rxkad. 5.3.2 Configuring a Heimdal kdc to use 2b tokens ------------------------------------------------ Support for 2b tokens in the kdc are turned on for specific principals by adding them to the string list option '[kdc]use_2b' in the kdc's 'krb5.conf' file. [kdc] use_2b = { afs@SU.SE = yes afs/it.su.se@SU.SE = yes } 5.3.3 Configuring AFS clients for 2b support -------------------------------------------- There is no need to configure AFS clients for 2b support. The only software that needs to be installed/upgrade is a Kerberos 5 enabled 'afslog'.  File: heimdal.info, Node: Things in search for a better place, Next: Kerberos 4 issues, Prev: Applications, Up: Top 6 Things in search for a better place ************************************* 6.1 Making things work on Ciscos ================================ Modern versions of Cisco IOS has some support for authenticating via Kerberos 5. This can be used both by having the router get a ticket when you login (boring), and by using Kerberos authenticated telnet to access your router (less boring). The following has been tested on IOS 11.2(12), things might be different with other versions. Old versions are known to have bugs. To make this work, you will first have to configure your router to use Kerberos (this is explained in the documentation). A sample configuration looks like the following: aaa new-model aaa authentication login default krb5-telnet krb5 enable aaa authorization exec krb5-instance kerberos local-realm FOO.SE kerberos srvtab entry host/router.foo.se 0 891725446 4 1 8 012345678901234567 kerberos server FOO.SE 10.0.0.1 kerberos instance map admin 15 This tells you (among other things) that when logging in, the router should try to authenticate with kerberised telnet, and if that fails try to verify a plain text password via a Kerberos ticket exchange (as opposed to a local database, RADIUS or something similar), and if that fails try the local enable password. If you're not careful when you specify the 'login default' authentication mechanism, you might not be able to login at all. The 'instance map' and 'authorization exec' lines says that people with 'admin' instances should be given 'enabled' shells when logging in. The numbers after the principal on the 'srvtab' line are principal type, time stamp (in seconds since 1970), key version number (4), keytype (1 == des), key length (always 8 with des), and then the key. To make the Heimdal KDC produce tickets that the Cisco can decode you might have to turn on the 'encode_as_rep_as_tgs_rep' flag in the KDC. You will also have to specify that the router can't handle anything but 'des-cbc-crc'. This can be done with the 'del_enctype' command of 'kadmin'. This all fine and so, but unless you have an IOS version with encryption (available only in the U.S) it doesn't really solve any problems. Sure you don't have to send your password over the wire, but since the telnet connection isn't protected it's still possible for someone to steal your session. This won't be fixed until someone adds integrity to the telnet protocol. A working solution would be to hook up a machine with a real operating system to the console of the Cisco and then use it as a backwards terminal server.  File: heimdal.info, Node: Kerberos 4 issues, Next: Windows compatibility, Prev: Things in search for a better place, Up: Top 7 Kerberos 4 issues ******************* Kerberos 4 KDC and KA server have been moved. For more about AFS, see the section *Note AFS::. * Menu: * Principal conversion issues:: * Converting a version 4 database::  File: heimdal.info, Node: Principal conversion issues, Next: Converting a version 4 database, Prev: Kerberos 4 issues, Up: Kerberos 4 issues 7.1 Principal conversion issues =============================== First, Kerberos 4 and Kerberos 5 principals are different. A version 4 principal consists of a name, an instance, and a realm. A version 5 principal has one or more components, and a realm (the terms "name" and "instance" are still used, for the first and second component, respectively). Also, in some cases the name of a version 4 principal differs from the first component of the corresponding version 5 principal. One notable example is the "host" type principals, where the version 4 name is 'rcmd' (for "remote command"), and the version 5 name is 'host'. For the class of principals that has a hostname as instance, there is an other major difference, Kerberos 4 uses only the first component of the hostname, whereas Kerberos 5 uses the fully qualified hostname. Because of this it can be hard or impossible to correctly convert a version 4 principal to a version 5 principal (1). The biggest problem is to know if the conversion resulted in a valid principal. To give an example, suppose you want to convert the principal 'rcmd.foo'. The 'rcmd' name suggests that the instance is a hostname (even if there are exceptions to this rule). To correctly convert the instance 'foo' to a hostname, you have to know which host it is referring to. You can to this by either guessing (from the realm) which domain name to append, or you have to have a list of possible hostnames. In the simplest cases you can cover most principals with the first rule. If you have several domains sharing a single realm this will not usually work. If the exceptions are few you can probably come by with a lookup table for the exceptions. In a complex scenario you will need some kind of host lookup mechanism. Using DNS for this is tempting, but DNS is error prone, slow and unsafe (2). Fortunately, the KDC has a trump on hand: it can easily tell if a principal exists in the database. The KDC will use 'krb5_425_conv_principal_ext' to convert principals when handling to version 4 requests. ---------- Footnotes ---------- (1) the other way is not always trivial either, but usually easier (2) at least until secure DNS is commonly available  File: heimdal.info, Node: Converting a version 4 database, Prev: Principal conversion issues, Up: Kerberos 4 issues 7.2 Converting a version 4 database =================================== If you want to convert an existing version 4 database, the principal conversion issue arises too. If you decide to convert your database once and for all, you will only have to do this conversion once. It is also possible to run a version 5 KDC as a slave to a version 4 KDC. In this case this conversion will happen every time the database is propagated. When doing this conversion, there are a few things to look out for. If you have stale entries in the database, these entries will not be converted. This might be because these principals are not used anymore, or it might be just because the principal couldn't be converted. You might also see problems with a many-to-one mapping of principals. For instance, if you are using DNS lookups and you have two principals 'rcmd.foo' and 'rcmd.bar', where 'foo' is a CNAME for 'bar', the resulting principals will be the same. Since the conversion function can't tell which is correct, these conflicts will have to be resolved manually. 7.2.1 Conversion example ------------------------ Given the following set of hosts and services: foo.se rcmd mail.foo.se rcmd, pop ftp.bar.se rcmd, ftp you have a database that consists of the following principals: 'rcmd.foo', 'rcmd.mail', 'pop.mail', 'rcmd.ftp', and 'ftp.ftp'. lets say you also got these extra principals: 'rcmd.gone', 'rcmd.old-mail', where 'gone.foo.se' was a machine that has now passed away, and 'old-mail.foo.se' was an old mail machine that is now a CNAME for 'mail.foo.se'. When you convert this database you want the following conversions to be done: rcmd.foo host/foo.se rcmd.mail host/mail.foo.se pop.mail pop/mail.foo.se rcmd.ftp host/ftp.bar.se ftp.ftp ftp/ftp.bar.se rcmd.gone removed rcmd.old-mail removed A 'krb5.conf' that does this looks like: [realms] FOO.SE = { v4_name_convert = { host = { ftp = ftp pop = pop rcmd = host } } v4_instance_convert = { foo = foo.se ftp = ftp.bar.se } default_domain = foo.se } The 'v4_name_convert' section says which names should be considered having an instance consisting of a hostname, and it also says how the names should be converted (for instance 'rcmd' should be converted to 'host'). The 'v4_instance_convert' section says how a hostname should be qualified (this is just a hosts-file in disguise). Host-instances that aren't covered by 'v4_instance_convert' are qualified by appending the contents of the 'default_domain'. Actually, this example doesn't work. Or rather, it works to well. Since it has no way of knowing which hostnames are valid and which are not, it will happily convert 'rcmd.gone' to 'host/gone.foo.se'. This isn't a big problem, but if you have run your kerberos realm for a few years, chances are big that you have quite a few 'junk' principals. If you don't want this you can remove the 'default_domain' statement, but then you will have to add entries for _all_ your hosts in the 'v4_instance_convert' section. Instead of doing this you can use DNS to convert instances. This is not a solution without problems, but it is probably easier than adding lots of static host entries. To enable DNS lookup you should turn on 'v4_instance_resolve' in the '[libdefaults]' section. 7.2.2 Converting a database --------------------------- The database conversion is done with 'hprop'. You can run this command to propagate the database to the machine called 'slave-server' (which should be running a 'hpropd'). hprop --source=krb4-db --master-key=/.m slave-server This command can also be to use for converting the v4 database on the server: hprop -n --source=krb4-db -d /var/kerberos/principal --master-key=/.m | hpropd -n  File: heimdal.info, Node: Windows compatibility, Next: Programming with Kerberos, Prev: Kerberos 4 issues, Up: Top 8 Windows compatibility *********************** Microsoft Windows, starting from version 2000 (formerly known as Windows NT 5), implements Kerberos 5. Their implementation, however, has some quirks, peculiarities, and bugs. This chapter is a short summary of the compatibility issues between Heimdal and various Windows versions. The big problem with the Kerberos implementation in Windows is that the available documentation is more focused on getting things to work rather than how they work, and not that useful in figuring out how things really work. It's of course subject to change all the time and mostly consists of our not so inspired guesses. Hopefully it's still somewhat useful. * Menu: * Configuring Windows to use a Heimdal KDC:: * Inter-Realm keys (trust) between Windows and a Heimdal KDC:: * Create account mappings:: * Encryption types:: * Authorisation data:: * Quirks of Windows 2000 KDC:: * Useful links when reading about the Windows::  File: heimdal.info, Node: Configuring Windows to use a Heimdal KDC, Next: Inter-Realm keys (trust) between Windows and a Heimdal KDC, Prev: Windows compatibility, Up: Windows compatibility 8.1 Configuring Windows to use a Heimdal KDC ============================================ You need the command line program called 'ksetup.exe'. This program comes with the Windows Support Tools, available from either the installation CD-ROM ('SUPPORT/TOOLS/SUPPORT.CAB'), or from Microsoft web site. Starting from Windows 2008, it is already installed. This program is used to configure the Kerberos settings on a Workstation. 'Ksetup' store the domain information under the registry key: 'HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\LSA\Kerberos\Domains'. Use the 'kadmin' program in Heimdal to create a host principal in the Kerberos realm. unix% kadmin kadmin> ank --password=password host/datan.example.com The name 'datan.example.com' should be replaced with DNS name of the workstation. You must configure the workstation as a member of a workgroup, as opposed to a member in an NT domain, and specify the KDC server of the realm as follows: C:> ksetup /setdomain EXAMPLE.COM C:> ksetup /addkdc EXAMPLE.COM kdc.example.com Set the machine password, i.e. create the local keytab: C:> ksetup /SetComputerPassword password The password used in 'ksetup /setmachpassword' must be the same as the password used in the 'kadmin ank' command. The workstation must now be rebooted. A mapping between local NT users and Kerberos principals must be specified. You have two choices. First: C:> ksetup /mapuser user@MY.REALM nt_user This will map a user to a specific principal; this allows you to have other usernames in the realm than in your NT user database. (Don't ask me why on earth you would want that...) You can also say: C:> ksetup /mapuser * * The Windows machine will now map any user to the corresponding principal, for example 'nisse' to the principal 'nisse@MY.REALM'. (This is most likely what you want.)  File: heimdal.info, Node: Inter-Realm keys (trust) between Windows and a Heimdal KDC, Next: Create account mappings, Prev: Configuring Windows to use a Heimdal KDC, Up: Windows compatibility 8.2 Inter-Realm keys (trust) between Windows and a Heimdal KDC ============================================================== See also the Step-by-Step guide from Microsoft, referenced below. Install Windows, and create a new controller (Active Directory Server) for the domain. By default the trust will be non-transitive. This means that only users directly from the trusted domain may authenticate. This can be changed to transitive by using the 'netdom.exe' tool. 'netdom.exe' can also be used to add the trust between two realms. You need to tell Windows on what hosts to find the KDCs for the non-Windows realm with 'ksetup', see *Note Configuring Windows to use a Heimdal KDC::. This needs to be done on all computers that want enable cross-realm login with 'Mapped Names'. Then you need to add the inter-realm keys on the Windows KDC. Start the Domain Tree Management tool (found in Programs, Administrative tools, Active Directory Domains and Trusts). Right click on Properties of your domain, select the Trust tab. Press Add on the appropriate trust windows and enter domain name and password. When prompted if this is a non-Windows Kerberos realm, press OK. Do not forget to add trusts in both directions (if that's what you want). If you want to use 'netdom.exe' instead of the Domain Tree Management tool, you do it like this: netdom trust NT.REALM.EXAMPLE.COM /Domain:EXAMPLE.COM /add /realm /passwordt:TrustPassword You also need to add the inter-realm keys to the Heimdal KDC. But take care to the encryption types and salting used for those keys. There should be no encryption type stronger than the one configured on Windows side for this relationship, itself limited to the ones supported by this specific version of Windows, nor any Kerberos 4 salted hashes, as Windows does not seem to understand them. Otherwise, the trust will not works. Here are the version-specific needed information: 1. Windows 2000: maximum encryption type is DES 2. Windows 2003: maximum encryption type is DES 3. Windows 2003RC2: maximum encryption type is RC4, relationship defaults to DES 4. Windows 2008: maximum encryption type is AES, relationship defaults to RC4 For Windows 2003RC2, to change the trust encryption type, you have to use the 'ktpass', from the Windows 2003 Resource kit *service pack2*, available from Microsoft web site. C:> ktpass /MITRealmName UNIX.EXAMPLE.COM /TrustEncryp RC4 For Windows 2008, the same operation can be done with the 'ksetup', installed by default. C:> ksetup /SetEncTypeAttre EXAMPLE.COM AES256-SHA1 Once the relationship is correctly configured, you can add the required inter-realm keys, using heimdal default encryption types: kadmin add krbtgt/NT.REALM.EXAMPLE.COM@EXAMPLE.COM kadmin add krbtgt/REALM.EXAMPLE.COM@NT.EXAMPLE.COM Use the same passwords for both keys. And if needed, to remove unsupported encryptions, such as the following ones for a Windows 2003RC2 server. kadmin del_enctype krbtgt/REALM.EXAMPLE.COM@NT.EXAMPLE.COM aes256-cts-hmac-sha1-96 kadmin del_enctype krbtgt/REALM.EXAMPLE.COM@NT.EXAMPLE.COM des3-cbc-sha1 kadmin del_enctype krbtgt/NT.EXAMPLE.COM@EXAMPLE.COM aes256-cts-hmac-sha1-96 kadmin del_enctype krbtgt/NT.EXAMPLE.COM@EXAMPLE.COM des3-cbc-sha1 Do not forget to reboot before trying the new realm-trust (after running 'ksetup'). It looks like it might work, but packets are never sent to the non-Windows KDC.  File: heimdal.info, Node: Create account mappings, Next: Encryption types, Prev: Inter-Realm keys (trust) between Windows and a Heimdal KDC, Up: Windows compatibility 8.3 Create account mappings =========================== Start the 'Active Directory Users and Computers' tool. Select the View menu, that is in the left corner just below the real menu (or press Alt-V), and select Advanced Features. Right click on the user that you are going to do a name mapping for and choose Name mapping. Click on the Kerberos Names tab and add a new principal from the non-Windows domain. This adds 'authorizationNames' entry to the users LDAP entry to the Active Directory LDAP catalog. When you create users by script you can add this entry instead.  File: heimdal.info, Node: Encryption types, Next: Authorisation data, Prev: Create account mappings, Up: Windows compatibility 8.4 Encryption types ==================== Windows 2000 supports both the standard DES encryptions ('des-cbc-crc' and 'des-cbc-md5') and its own proprietary encryption that is based on MD4 and RC4 that is documented in and is supposed to be described in 'draft-brezak-win2k-krb-rc4-hmac-03.txt'. New users will get both MD4 and DES keys. Users that are converted from a NT4 database, will only have MD4 passwords and will need a password change to get a DES key.  File: heimdal.info, Node: Authorisation data, Next: Quirks of Windows 2000 KDC, Prev: Encryption types, Up: Windows compatibility 8.5 Authorisation data ====================== The Windows 2000 KDC also adds extra authorisation data in tickets. It is at this point unclear what triggers it to do this. The format of this data is only available under a "secret" license from Microsoft, which prohibits you implementing it. A simple way of getting hold of the data to be able to understand it better is described here. 1. Find the client example on using the SSPI in the SDK documentation. 2. Change "AuthSamp" in the source code to lowercase. 3. Build the program. 4. Add the "authsamp" principal with a known password to the database. Make sure it has a DES key. 5. Run 'ktutil add' to add the key for that principal to a keytab. 6. Run 'appl/test/nt_gss_server -p 2000 -s authsamp --dump-auth=FILE' where FILE is an appropriate file. 7. It should authenticate and dump for you the authorisation data in the file. 8. The tool 'lib/asn1/asn1_print' is somewhat useful for analysing the data.  File: heimdal.info, Node: Quirks of Windows 2000 KDC, Next: Useful links when reading about the Windows, Prev: Authorisation data, Up: Windows compatibility 8.6 Quirks of Windows 2000 KDC ============================== There are some issues with salts and Windows 2000. Using an empty salt--which is the only one that Kerberos 4 supported, and is therefore known as a Kerberos 4 compatible salt--does not work, as far as we can tell from out experiments and users' reports. Therefore, you have to make sure you keep around keys with all the different types of salts that are required. Microsoft have fixed this issue post Windows 2003. Microsoft seems also to have forgotten to implement the checksum algorithms 'rsa-md4-des' and 'rsa-md5-des'. This can make Name mapping (*note Create account mappings::) fail if a 'des-cbc-md5' key is used. To make the KDC return only 'des-cbc-crc' you must delete the 'des-cbc-md5' key from the kdc using the 'kadmin del_enctype' command. kadmin del_enctype lha des-cbc-md5 You should also add the following entries to the 'krb5.conf' file: [libdefaults] default_etypes = des-cbc-crc default_etypes_des = des-cbc-crc These configuration options will make sure that no checksums of the unsupported types are generated.  File: heimdal.info, Node: Useful links when reading about the Windows, Prev: Quirks of Windows 2000 KDC, Up: Windows compatibility 8.7 Useful links when reading about the Windows =============================================== See also our paper presented at the 2001 Usenix Annual Technical Conference, available in the proceedings or at . There are lots of texts about Kerberos on Microsoft's web site, here is a short list of the interesting documents that we have managed to find. * Step-by-Step Guide to Kerberos 5 (krb5 1.0) Interoperability: . Kerberos GSS-API (in Windows-eze SSPI), Windows as a client in a non-Windows KDC realm, adding unix clients to a Windows 2000 KDC, and adding cross-realm trust (*note Inter-Realm keys (trust) between Windows and a Heimdal KDC::). * Windows 2000 Kerberos Authentication: . White paper that describes how Kerberos is used in Windows 2000. * Overview of Kerberos: . Links to useful other links. * Event logging for Kerberos: . Basically it say that you can add a registry key 'HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Lsa\Kerberos\Parameters\LogLevel' with value DWORD equal to 1, and then you'll get logging in the Event Logger. Other useful programs include these: * pwdump2  File: heimdal.info, Node: Programming with Kerberos, Next: Migration, Prev: Windows compatibility, Up: Top 9 Programming with Kerberos *************************** See the Kerberos 5 API introduction and documentation on the Heimdal webpage.  File: heimdal.info, Node: Migration, Next: Acknowledgments, Prev: Programming with Kerberos, Up: Top 10 Migration ************ 10.1 Migration from MIT Kerberos to Heimdal =========================================== hpropd can read MIT Kerberos dump in "kdb5_util load_dump version 5" or version 6 format. Simply run: 'kdb5_util dump'. To load the MIT Kerberos dump file, use the following command: '/usr/heimdal/libexec/hprop --database=dump-file --master-key=/var/db/krb5kdc/mit_stash --source=mit-dump --decrypt --stdout | /usr/heimdal/libexec/hpropd --stdin' kadmin can dump in MIT Kerberos format. Simply run: 'kadmin -l dump -f MIT'. The Heimdal KDC and kadmind, as well as kadmin -l and the libkadm5srv library can read and write MIT KDBs, and can read MIT stash files. To build with KDB support requires having a standalone libdb from MIT Kerberos and associated headers, then you can configure Heildal as follows: './configure ... CPPFLAGS=-I/path-to-mit-db-headers LDFLAGS="-L/path-to-mit-db-object -Wl,-rpath -Wl,/path-to-mit-db-object" LDLIBS=-ldb' At this time support for MIT Kerberos KDB dump/load format and direct KDB access does not include support for PKINIT, or K/M key history, constrained delegation, and other advanced features. Heimdal supports using multiple HDBs at once, with all write going to just one HDB. This allows for entries to be moved to a native HDB from an MIT KDB over time as those entries are changed. Or you can use hprop and hpropd. 10.2 General issues =================== When migrating from a Kerberos 4 KDC. 10.3 Order in what to do things: ================================ * Convert the database, check all principals that hprop complains about. 'hprop -n --source=| hpropd -n' Replace with whatever source you have, like krb4-db or krb4-dump. * Run a Kerberos 5 slave for a while. * Figure out if it does everything you want it to. Make sure that all things that you use works for you. * Let a small number of controlled users use Kerberos 5 tools. Find a sample population of your users and check what programs they use, you can also check the kdc-log to check what ticket are checked out. * Burn the bridge and change the master. * Let all users use the Kerberos 5 tools by default. * Turn off services that do not need Kerberos 4 authentication. Things that might be hard to get away is old programs with support for Kerberos 4. Example applications are old Eudora installations using KPOP, and Zephyr. Eudora can use the Kerberos 4 kerberos in the Heimdal kdc.  File: heimdal.info, Node: Acknowledgments, Next: Copyrights and Licenses, Prev: Migration, Up: Top Appendix A Acknowledgments ************************** Eric Young wrote "libdes". Heimdal used to use libdes, without it kth-krb would never have existed. Since there are no longer any Eric Young code left in the library, we renamed it to libhcrypto. All functions in libhcrypto have been re-implemented or used available public domain code. The core AES function where written by Vincent Rijmen, Antoon Bosselaers and Paulo Barreto. The core DES SBOX transformation was written by Richard Outerbridge. 'imath' that is used for public key crypto support is written by Michael J. Fromberger. The University of California at Berkeley initially wrote 'telnet', and 'telnetd'. The authentication and encryption code of 'telnet' and 'telnetd' was added by David Borman (then of Cray Research, Inc). The encryption code was removed when this was exported and then added back by Juha Eskelinen. The 'popper' was also a Berkeley program initially. Some of the functions in 'libroken' also come from Berkeley by way of NetBSD/FreeBSD. 'editline' was written by Simmule Turner and Rich Salz. Heimdal contains a modifed copy. The 'getifaddrs' implementation for Linux was written by Hideaki YOSHIFUJI for the Usagi project. The 'pkcs11.h' headerfile was written by the Scute project. Bugfixes, documentation, encouragement, and code has been contributed by: Alexander Boström Allan McRae Andrew Bartlett Andrew Cobaugh Andrew Tridge Anton Lundin Asanka Herath Björn Grönvall Björn Sandell Björn Schlögl Brandon S. Allbery KF8NH Brian A May Buck Huppmann Cacdric Schieli Chaskiel M Grundman Christos Zoulas Cizzi Storm Daniel Kouril David Love David Markey David R Boldt Derrick J Brashear Donald Norwood Douglas E Engert Frank van der Linden Gabor Gombas Guido Günther Guillaume Rousse Harald Barth Ingo Schwarze Jacques A. Vidrine Jaideep Padhye Jan Rekorajski Jason McIntyre Jeffrey Altman Jelmer Vernooij Joerg Pulz Johan Danielsson Johan Gadsjö Johan Ihrén John Center Julian Ospald Jun-ichiro itojun Hagino KAMADA Ken'ichi Kamen Mazdrashki Karolin Seeger Ken Hornstein Love Hörnquist Åstrand Luke Howard Magnus Ahltorp Magnus Holmberg Marc Horowitz Mario Strasser Mark Eichin Martin von Gagern Matthias Dieter Wallnöfer Matthieu Patou Mattias Amnefelt Michael B Allen Michael Fromberger Michal Vocu Milosz Kmieciak Miroslav Ruda Mustafa A. Hashmi Nicolas Williams Patrik Lundin Petr Holub Phil Fisher Rafal Malinowski Ragnar Sundblad Rainer Toebbicke Richard Nyberg Roland C. Dowdeswell Roman Divacky Russ Allbery Sho Hosoda, 細田 将 Simon Wilkinson Stefan Metzmacher Ted Percival Timothy Pearson Tom Payerle Victor Guerra Zeqing Xia Åke Sandgren and we hope that those not mentioned here will forgive us. All bugs were introduced by ourselves.  File: heimdal.info, Node: Copyrights and Licenses, Prev: Acknowledgments, Up: Top Appendix B Copyrights and Licenses ********************************** Kungliga Tekniska Högskolan ============================ Copyright (c) 1997-2011 Kungliga Tekniska Högskolan (Royal Institute of Technology, Stockholm, Sweden). All rights reserved. Portions Copyright (c) 2009 Apple Inc. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the Institute nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. Massachusetts Institute of Technology ===================================== The parts of the libtelnet that handle Kerberos. Copyright (C) 1990 by the Massachusetts Institute of Technology Export of this software from the United States of America may require a specific license from the United States Government. It is the responsibility of any person or organization contemplating export to obtain such a license before exporting. WITHIN THAT CONSTRAINT, permission to use, copy, modify, and distribute this software and its documentation for any purpose and without fee is hereby granted, provided that the above copyright notice appear in all copies and that both that copyright notice and this permission notice appear in supporting documentation, and that the name of M.I.T. not be used in advertising or publicity pertaining to distribution of the software without specific, written prior permission. M.I.T. makes no representations about the suitability of this software for any purpose. It is provided "as is" without express or implied warranty. The Regents of the University of California =========================================== The parts of the libroken, most of libtelnet, telnet, ftp, and popper. Copyright (c) 1988, 1990, 1993 The Regents of the University of California. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the University nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. The Regents of the University of California. ============================================ libedit Copyright (c) 1992, 1993 The Regents of the University of California. All rights reserved. This code is derived from software contributed to Berkeley by Christos Zoulas of Cornell University. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the University nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. TomsFastMath / LibTomMath ========================= Tom's fast math (bignum support) and LibTomMath LibTomMath is hereby released into the Public Domain. Doug Rabson =========== GSS-API mechglue layer. Copyright (c) 2005 Doug Rabson All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. PADL Software Pty Ltd ===================== GSS-API CFX, SPNEGO, naming extensions, API extensions. KCM credential cache. HDB LDAP backend. Copyright (c) 2003-2011, PADL Software Pty Ltd. Copyright (c) 2004, Andrew Bartlett. Copyright (c) 2003 - 2008, Kungliga Tekniska Högskolan Copyright (c) 2015, Timothy Pearson. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of PADL Software nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY PADL SOFTWARE AND CONTRIBUTORS ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL PADL SOFTWARE OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. Marko Kreen =========== Fortuna in libhcrypto Copyright (c) 2005 Marko Kreen All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. NTT (Nippon Telegraph and Telephone Corporation) ================================================ Camellia in libhcrypto Copyright (c) 2006,2007 NTT (Nippon Telegraph and Telephone Corporation) . All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer as the first lines of this file unmodified. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY NTT ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL NTT BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. The NetBSD Foundation, Inc. =========================== vis.c in libroken Copyright (c) 1999, 2005 The NetBSD Foundation, Inc. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. Vincent Rijmen, Antoon Bosselaers, Paulo Barreto ================================================ AES in libhcrypto rijndael-alg-fst.c @version 3.0 (December 2000) Optimised ANSI C code for the Rijndael cipher (now AES) @author Vincent Rijmen @author Antoon Bosselaers @author Paulo Barreto This code is hereby placed in the public domain. THIS SOFTWARE IS PROVIDED BY THE AUTHORS ''AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. Apple, Inc ========== kdc/announce.c Copyright (c) 2008 Apple Inc. All Rights Reserved. Export of this software from the United States of America may require a specific license from the United States Government. It is the responsibility of any person or organization contemplating export to obtain such a license before exporting. WITHIN THAT CONSTRAINT, permission to use, copy, modify, and distribute this software and its documentation for any purpose and without fee is hereby granted, provided that the above copyright notice appear in all copies and that both that copyright notice and this permission notice appear in supporting documentation, and that the name of Apple Inc. not be used in advertising or publicity pertaining to distribution of the software without specific, written prior permission. Apple Inc. makes no representations about the suitability of this software for any purpose. It is provided "as is" without express or implied warranty. THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE. Richard Outerbridge =================== DES core in libhcrypto D3DES (V5.09) - A portable, public domain, version of the Data Encryption Standard. Written with Symantec's THINK (Lightspeed) C by Richard Outerbridge. Thanks to: Dan Hoey for his excellent Initial and Inverse permutation code; Jim Gillogly & Phil Karn for the DES key schedule code; Dennis Ferguson, Eric Young and Dana How for comparing notes; and Ray Lau, for humouring me on. Copyright (c) 1988,1989,1990,1991,1992 by Richard Outerbridge. (GEnie : OUTER; CIS : [71755,204]) Graven Imagery, 1992. Secure Endpoints Inc ==================== Windows support Copyright (c) 2009-2015, Secure Endpoints Inc. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. Novell, Inc =========== lib/hcrypto/test_dh.c Copyright (c) 2007, Novell, Inc. Author: Matthias Koenig All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the Novell nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.  Tag Table: Node: Top211 Node: Introduction1689 Node: What is Kerberos?4418 Node: Building and Installing9518 Node: Setting up a realm9845 Node: Configuration file10797 Node: Creating the database13877 Node: Modifying the database17536 Node: Checking the setup19129 Node: keytabs19987 Node: Remote administration20845 Node: Password changing22758 Node: Testing clients and servers26949 Node: Slave Servers27277 Node: Incremental propagation29032 Node: Encryption types and salting32754 Node: Credential cache server - KCM34937 Node: Cross realm36922 Node: Transit policy39476 Node: Setting up DNS46258 Node: Using LDAP to store the database48739 Node: Providing Kerberos credentials to servers and programs55598 Node: Setting up PK-INIT57705 Ref: Use OpenSSL to create certificates68970 Node: Debugging Kerberos problems71512 Node: Applications71944 Node: Authentication modules72144 Node: Digital SIA72739 Node: IRIX77134 Node: AFS78428 Node: Things in search for a better place82188 Node: Kerberos 4 issues84926 Node: Principal conversion issues85274 Ref: Principal conversion issues-Footnote-187518 Ref: Principal conversion issues-Footnote-287589 Node: Converting a version 4 database87645 Node: Windows compatibility91968 Node: Configuring Windows to use a Heimdal KDC93057 Node: Inter-Realm keys (trust) between Windows and a Heimdal KDC95132 Node: Create account mappings98807 Node: Encryption types99562 Node: Authorisation data100162 Node: Quirks of Windows 2000 KDC101301 Node: Useful links when reading about the Windows102596 Node: Programming with Kerberos104399 Node: Migration104649 Node: Acknowledgments107290 Node: Copyrights and Licenses110169  End Tag Table heimdal-7.5.0/doc/NTMakefile0000644000175000017500000000727213026237312013730 0ustar niknik######################################################################## # # Copyright (c) 2009, Secure Endpoints Inc. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # - Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # # - Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in # the documentation and/or other materials provided with the # distribution. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS # FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE # COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, # BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN # ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. # RELDIR=doc !include ../windows/NTMakefile.w32 heimdal_TEXINFOS = \ $(OBJ)\ack.texi \ $(OBJ)\apps.texi \ $(OBJ)\copyright.texi \ $(OBJ)\heimdal.texi \ $(OBJ)\install.texi \ $(OBJ)\intro.texi \ $(OBJ)\kerberos4.texi \ $(OBJ)\migration.texi \ $(OBJ)\misc.texi \ $(OBJ)\programming.texi \ $(OBJ)\setup.texi \ $(OBJ)\vars.texi \ $(OBJ)\whatis.texi \ $(OBJ)\win2k.texi hx509_TEXINFOS = \ $(OBJ)\hx509.texi {}.texi{$(OBJ)}.texi: $(CP) $** $@ {}.tin{$(OBJ)}.texi: $(SED) -e "s,[@]dbdir[@],x,g" \ -e "s,[@]dbtype[@],sqlite,g" < $** > $@ \ -e "s,[@]PACKAGE_VERSION[@],$(VER_PACKAGE_VERSION),g" < $** > $@ MAKEINFOFLAGS = --css-include=$(SRCDIR)/heimdal.css !ifdef APPVEYOR MAKEINFO = $(PERL) C:\msys64\usr\bin\makeinfo !endif ###################################################################### # Build heimdal.chm # Copyrights-and-Licenses.html is where the table of contents ends up # when generating HTML output using makeinfo. Same goes for # How-to-use-the-PKCS11-module.html below. $(OBJ)\heimdal\index.html $(OBJ)\heimdal\Copyrights-and-Licenses.html: $(heimdal_TEXINFOS) cd $(OBJ) $(MAKEINFO) $(MAKEINFOFLAGS) --html heimdal.texi cd $(SRCDIR) $(OBJ)\heimdal\toc.hhc: $(OBJ)\heimdal\Copyrights-and-Licenses.html $(PERL) $(SRC)\cf\w32-hh-toc-from-info.pl -o$@ $** $(OBJ)\heimdal\heimdal.hhp: heimdal.hhp $(CP) $** $@ $(DOCDIR)\heimdal.chm: $(OBJ)\heimdal\heimdal.hhp $(OBJ)\heimdal\toc.hhc cd $(OBJ)\heimdal -$(HHC) heimdal.hhp $(CP) heimdal.chm $@ cd $(SRCDIR) ###################################################################### # Build hx509.chm $(OBJ)\hx509\index.html $(OBJ)\hx509\How-to-use-the-PKCS11-module.html: $(hx509_TEXINFOS) cd $(OBJ) $(MAKEINFO) $(MAKEINFOFLAGS) --html hx509.texi cd $(SRCDIR) $(OBJ)\hx509\toc.hhc: $(OBJ)\hx509\How-to-use-the-PKCS11-module.html $(PERL) $(SRC)\cf\w32-hh-toc-from-info.pl -o$@ $** $(OBJ)\hx509\hx509.hhp: hx509.hhp $(CP) $** $@ $(DOCDIR)\hx509.chm: $(OBJ)\hx509\hx509.hhp $(OBJ)\hx509\toc.hhc cd $(OBJ)\hx509 -$(HHC) hx509.hhp $(CP) hx509.chm $@ cd $(SRCDIR) !ifndef NO_DOC all:: $(OBJ)\heimdal\index.html $(OBJ)\hx509\index.html \ $(DOCDIR)\heimdal.chm $(DOCDIR)\hx509.chm !endif clean:: -$(RM) $(OBJ)\heimdal\*.* -$(RM) $(OBJ)\hx509\*.* -$(RM) $(DOCDIR)\heimdal.chm -$(RM) $(DOCDIR)\hx509.chm .SUFFIXES: .texi .tin heimdal-7.5.0/doc/gssapi.din0000644000175000017500000000060412136107747014011 0ustar niknik# Doxyfile 1.5.3 PROJECT_NAME = Heimdal GSS-API library PROJECT_NUMBER = @PACKAGE_VERSION@ OUTPUT_DIRECTORY = @srcdir@/doxyout/gssapi INPUT = @srcdir@/../lib/gssapi WARN_IF_UNDOCUMENTED = NO PERL_PATH = /usr/bin/perl HTML_HEADER = "@srcdir@/header.html" HTML_FOOTER = "@srcdir@/footer.html" @INCLUDE = "@srcdir@/doxytmpl.dxy" heimdal-7.5.0/doc/vars.texi0000755000175000017500000000016213212450770013670 0ustar niknik @c @c Variables depending on installation @c @set dbdir /var/heimdal @set dbtype db3 @set PACKAGE_VERSION 7.5.0 heimdal-7.5.0/doc/hx509.info0000644000175000017500000005144113212445615013561 0ustar niknikThis is hx509.info, produced by makeinfo version 4.8 from hx509.texi. INFO-DIR-SECTION Security START-INFO-DIR-ENTRY * hx509: (hx509). The X.509 distribution from KTH END-INFO-DIR-ENTRY  File: hx509.info, Node: Top, Next: Introduction, Prev: (dir), Up: (dir) Heimdal ******* This manual is for version 7.5.0 of hx509. * Menu: * Introduction:: * What is X.509 ?:: * Setting up a CA:: * CMS signing and encryption:: * Certificate matching:: * Software PKCS 11 module:: * Creating a CA certificate:: * Issuing certificates:: * Issuing CRLs:: * Application requirements:: * CMS background:: * Matching syntax:: * How to use the PKCS11 module:: --- The Detailed Node Listing --- Setting up a CA * Creating a CA certificate:: * Issuing certificates:: * Issuing CRLs:: * Application requirements:: CMS signing and encryption * CMS background:: Certificate matching * Matching syntax:: Software PKCS 11 module * How to use the PKCS11 module::  File: hx509.info, Node: Introduction, Next: What is X.509 ?, Prev: Top, Up: Top 1 Introduction ************** The goals of a PKI infrastructure (as defined in RFC 3280) is to meet _the needs of deterministic, automated identification, authentication, access control, and authorization_. The administrator should be aware of certain terminologies as explained by the aforementioned RFC before attemping to put in place a PKI infrastructure. Briefly, these are: * CA Certificate Authority * RA Registration Authority, i.e., an optional system to which a CA delegates certain management functions. * CRL Issuer An optional system to which a CA delegates the publication of certificate revocation lists. * Repository A system or collection of distributed systems that stores certificates and CRLs and serves as a means of distributing these certificates and CRLs to end entities hx509 (Heimdal x509 support) is a near complete X.509 stack that can handle CMS messages (crypto system used in S/MIME and Kerberos PK-INIT) and basic certificate processing tasks, path construction, path validation, OCSP and CRL validation, PKCS10 message construction, CMS Encrypted (shared secret encrypted), CMS SignedData (certificate signed), and CMS EnvelopedData (certificate encrypted). hx509 can use PKCS11 tokens, PKCS12 files, PEM files, and/or DER encoded files.  File: hx509.info, Node: What is X.509 ?, Next: Setting up a CA, Prev: Introduction, Up: Top 2 What is X.509, PKIX, PKCS7 and CMS ? ************************************** X.509 was created by CCITT (later ITU) for the X.500 directory service. Today, X.509 discussions and implementations commonly reference the IETF's PKIX Certificate and CRL Profile of the X.509 v3 certificate standard, as specified in RFC 3280. ITU continues to develop the X.509 standard together with the IETF in a rather complicated dance. X.509 is a public key based security system that has associated data stored within a so called certificate. Initially, X.509 was a strict hierarchical system with one root. However, ever evolving requiments and technology advancements saw the inclusion of multiple policy roots, bridges and mesh solutions. x.509 can also be used as a peer to peer system, though often seen as a common scenario. 2.1 Type of certificates ======================== There are several flavors of certificate in X.509. * Trust anchors Trust anchors are strictly not certificates, but commonly stored in a certificate format as they become easier to manage. Trust anchors are the keys that an end entity would trust to validate other certificates. This is done by building a path from the certificate you want to validate to to any of the trust anchors you have. * End Entity (EE) certificates End entity certificates are the most common types of certificates. End entity certificates cannot issue (sign) certificate themselves and are generally used to authenticate and authorize users and services. * Certification Authority (CA) certificates Certificate authority certificates have the right to issue additional certificates (be it sub-ordinate CA certificates to build an trust anchors or end entity certificates). There is no limit to how many certificates a CA may issue, but there might other restrictions, like the maximum path depth. * Proxy certificates Remember the statement "End Entity certificates cannot issue certificates"? Well that statement is not entirely true. There is an extension called proxy certificates defined in RFC3820, that allows certificates to be issued by end entity certificates. The service that receives the proxy certificates must have explicitly turned on support for proxy certificates, so their use is somewhat limited. Proxy certificates can be limited by policies stored in the certificate to what they can be used for. This allows users to delegate the proxy certificate to services (by sending over the certificate and private key) so the service can access services on behalf of the user. One example of this would be a print service. The user wants to print a large job in the middle of the night when the printer isn't used that much, so the user creates a proxy certificate with the policy that it can only be used to access files related to this print job, creates the print job description and send both the description and proxy certificate with key over to print service. Later at night when the print service initializes (without any user intervention), access to the files for the print job is granted via the proxy certificate. As a result of (in-place) policy limitations, the certificate cannot be used for any other purposes. 2.2 Building a path =================== Before validating a certificate path (or chain), the path needs to be constructed. Given a certificate (EE, CA, Proxy, or any other type), the path construction algorithm will try to find a path to one of the trust anchors. The process starts by looking at the issuing CA of the certificate, by Name or Key Identifier, and tries to find that certificate while at the same time evaluting any policies in-place.  File: hx509.info, Node: Setting up a CA, Next: Creating a CA certificate, Prev: What is X.509 ?, Up: Top 3 Setting up a CA ***************** Do not let information overload scare you off! If you are simply testing or getting started with a PKI infrastructure, skip all this and go to the next chapter (see: *note Creating a CA certificate::). Creating a CA certificate should be more the just creating a certificate, CA's should define a policy. Again, if you are simply testing a PKI, policies do not matter so much. However, when it comes to trust in an organisation, it will probably matter more whom your users and sysadmins will find it acceptable to trust. At the same time, try to keep things simple, it's not very hard to run a Certificate authority and the process to get new certificates should be simple. You may find it helpful to answer the following policy questions for your organization at a later stage: * How do you trust your CA. * What is the CA responsibility. * Review of CA activity. * How much process should it be to issue certificate. * Who is allowed to issue certificates. * Who is allowed to requests certificates. * How to handle certificate revocation, issuing CRLs and maintain OCSP services.  File: hx509.info, Node: Creating a CA certificate, Next: Issuing certificates, Prev: Setting up a CA, Up: Top 3.1 Creating a CA certificate ============================= This section describes how to create a CA certificate and what to think about. 3.1.1 Lifetime CA certificate ----------------------------- You probably want to create a CA certificate with a long lifetime, 10 years at the very minimum. This is because you don't want to push out the certificate (as a trust anchor) to all you users again when the old CA certificate expires. Although a trust anchor can't really expire, not all software works in accordance with published standards. Keep in mind the security requirements might be different 10-20 years into the future. For example, SHA1 is going to be withdrawn in 2010, so make sure you have enough buffering in your choice of digest/hash algorithms, signature algorithms and key lengths. 3.1.2 Create a CA certificate ----------------------------- This command below can be used to generate a self-signed CA certificate. hxtool issue-certificate \ --self-signed \ --issue-ca \ --generate-key=rsa \ --subject="CN=CertificateAuthority,DC=test,DC=h5l,DC=se" \ --lifetime=10years \ --certificate="FILE:ca.pem" 3.1.3 Extending the lifetime of a CA certificate ------------------------------------------------ You just realised that your CA certificate is going to expire soon and that you need replace it with a new CA. The easiest way to do that is to extend the lifetime of your existing CA certificate. The example below will extend the CA certificate's lifetime by 10 years. You should compare this new certificate if it contains all the special tweaks as the old certificate had. hxtool issue-certificate \ --self-signed \ --issue-ca \ --lifetime="10years" \ --template-certificate="FILE:ca.pem" \ --template-fields="serialNumber,notBefore,subject,SPKI" \ --ca-private-key=FILE:ca.pem \ --certificate="FILE:new-ca.pem" 3.1.4 Subordinate CA -------------------- This example below creates a new subordinate certificate authority. hxtool issue-certificate \ --ca-certificate=FILE:ca.pem \ --issue-ca \ --generate-key=rsa \ --subject="CN=CertificateAuthority,DC=dev,DC=test,DC=h5l,DC=se" \ --certificate="FILE:dev-ca.pem"  File: hx509.info, Node: Issuing certificates, Next: Issuing CRLs, Prev: Creating a CA certificate, Up: Top 3.2 Issuing certificates ======================== First you'll create a CA certificate, after that you have to deal with your users and servers and issue certificates to them. * Do all the work themself Generate the key for the user. This has the problme that the the CA knows the private key of the user. For a paranoid user this might leave feeling of disconfort. * Have the user do part of the work Receive PKCS10 certificate requests fromusers. PKCS10 is a request for a certificate. The user may specify what DN they want as well as provide a certificate signing request (CSR). To prove the user have the key, the whole request is signed by the private key of the user. 3.2.1 Name space management --------------------------- What people might want to see. Re-issue certificates just because people moved within the organization. Expose privacy information. Using Sub-component name (+ notation). 3.2.2 Certificate Revocation, CRL and OCSP ------------------------------------------ Certificates that a CA issues may need to be revoked at some stage. As an example, an employee leaves the organization and does not bother handing in his smart card (or even if the smart card is handed back - the certificate on it must no longer be acceptable to services; the employee has left). You may also want to revoke a certificate for a service which is no longer being offered on your network. Overlooking these scenarios can lead to security holes which will quickly become a nightmare to deal with. There are two primary protocols for dealing with certificate revokation. Namely: * Certificate Revocation List (CRL) * Online Certificate Status Protocol (OCSP) If however the certificate in qeustion has been destroyed, there is no need to revoke the certificate because it can not be used by someone else. This matter since for each certificate you add to CRL, the download time and processing time for clients are longer. CRLs and OCSP responders however greatly help manage compatible services which may authenticate and authorize users (or services) on an on-going basis. As an example, VPN connectivity established via certificates for connecting clients would require your VPN software to make use of a CRL or an OCSP service to ensure revoked certificates belonging to former clients are not allowed access to (formerly subscribed) network services.  File: hx509.info, Node: Issuing CRLs, Next: Application requirements, Prev: Issuing certificates, Up: Top 3.3 Issuing CRLs ================ Create an empty CRL with no certificates revoked. Default expiration value is one year from now. hxtool crl-sign \ --crl-file=crl.der \ --signer=FILE:ca.pem Create a CRL with all certificates in the directory `/path/to/revoked/dir' included in the CRL as revoked. Also make it expire one month from now. hxtool crl-sign \ --crl-file=crl.der \ --signer=FILE:ca.pem \ --lifetime='1 month' \ DIR:/path/to/revoked/dir  File: hx509.info, Node: Application requirements, Next: CMS signing and encryption, Prev: Issuing CRLs, Up: Top 3.4 Application requirements ============================ Application place different requirements on certificates. This section tries to expand what they are and how to use hxtool to generate certificates for those services. 3.4.1 HTTPS - server -------------------- hxtool issue-certificate \ --subject="CN=www.test.h5l.se,DC=test,DC=h5l,DC=se" \ --type="https-server" \ --hostname="www.test.h5l.se" \ --hostname="www2.test.h5l.se" \ ... 3.4.2 HTTPS - client -------------------- hxtool issue-certificate \ --subject="UID=testus,DC=test,DC=h5l,DC=se" \ --type="https-client" \ ... 3.4.3 S/MIME - email -------------------- There are two things that should be set in S/MIME certificates, one or more email addresses and an extended eku usage (EKU), emailProtection. The email address format used in S/MIME certificates is defined in RFC2822, section 3.4.1 and it should be an "addr-spec". There are two ways to specifify email address in certificates. The old way is in the subject distinguished name, _this should not be used_. The new way is using a Subject Alternative Name (SAN). Even though the email address is stored in certificates, they don't need to be, email reader programs are required to accept certificates that doesn't have either of the two methods of storing email in certificates - in which case, the email client will try to protect the user by printing the name of the certificate instead. S/MIME certificate can be used in another special way. They can be issued with a NULL subject distinguished name plus the email in SAN, this is a valid certificate. This is used when you wont want to share more information then you need to. hx509 issue-certificate supports adding the email SAN to certificate by using the -email option, -email also gives an implicit emailProtection eku. If you want to create an certificate without an email address, the option -type=email will add the emailProtection EKU. hxtool issue-certificate \ --subject="UID=testus-email,DC=test,DC=h5l,DC=se" \ --type=email \ --email="testus@test.h5l.se" \ ... An example of an certificate without and subject distinguished name with an email address in a SAN. hxtool issue-certificate \ --subject="" \ --type=email \ --email="testus@test.h5l.se" \ ... 3.4.4 PK-INIT ------------- A PK-INIT infrastructure allows users and services to pick up kerberos credentials (tickets) based on their certificate. This, for example, allows users to authenticate to their desktops using smartcards while acquiring kerberos tickets in the process. As an example, an office network which offers centrally controlled desktop logins, mail, messaging (xmpp) and openafs would give users single sign-on facilities via smartcard based logins. Once the kerberos ticket has been acquired, all kerberized services would immediately become accessible based on deployed security policies. Let's go over the process of initializing a demo PK-INIT framework: hxtool issue-certificate \ --type="pkinit-kdc" \ --pk-init-principal="krbtgt/TEST.H5L.SE@TEST.H5L.SE" \ --hostname=kerberos.test.h5l.se \ --ca-certificate="FILE:ca.pem,ca.key" \ --generate-key=rsa \ --certificate="FILE:kdc.pem" \ --subject="cn=kdc" How to create a certificate for a user. hxtool issue-certificate \ --type="pkinit-client" \ --pk-init-principal="user@TEST.H5L.SE" \ --ca-certificate="FILE:ca.pem,ca.key" \ --generate-key=rsa \ --subject="cn=Test User" \ --certificate="FILE:user.pem" The -type field can be specified multiple times. The same certificate can hence house extensions for both pkinit-client as well as S/MIME. To use the PKCS11 module, please see the section: *note How to use the PKCS11 module::. More about how to configure the KDC, see the documentation in the Heimdal manual to set up the KDC. 3.4.5 XMPP/Jabber ----------------- The jabber server certificate should have a dNSname that is the same as the user entered into the application, not the same as the host name of the machine. hxtool issue-certificate \ --subject="CN=xmpp1.test.h5l.se,DC=test,DC=h5l,DC=se" \ --hostname="xmpp1.test.h5l.se" \ --hostname="test.h5l.se" \ ... The certificate may also contain a jabber identifier (JID) that, if the receiver allows it, authorises the server or client to use that JID. When storing a JID inside the certificate, both for server and client, it's stored inside a UTF8String within an otherName entity inside the subjectAltName, using the OID id-on-xmppAddr (1.3.6.1.5.5.7.8.5). To read more about the requirements, see RFC3920, Extensible Messaging and Presence Protocol (XMPP): Core. hxtool issue-certificate have support to add jid to the certificate using the option `--jid'. hxtool issue-certificate \ --subject="CN=Love,DC=test,DC=h5l,DC=se" \ --jid="lha@test.h5l.se" \ ...  File: hx509.info, Node: CMS signing and encryption, Next: CMS background, Prev: Application requirements, Up: Top 4 CMS signing and encryption **************************** CMS is the Cryptographic Message System that among other, is used by S/MIME (secure email) and Kerberos PK-INIT. It's an extended version of the RSA, Inc standard PKCS7.  File: hx509.info, Node: CMS background, Next: Certificate matching, Prev: CMS signing and encryption, Up: Top 4.1 CMS background ==================  File: hx509.info, Node: Certificate matching, Next: Matching syntax, Prev: CMS background, Up: Top 5 Certificate matching ********************** To match certificates hx509 have a special query language to match certifictes in queries and ACLs.  File: hx509.info, Node: Matching syntax, Next: Software PKCS 11 module, Prev: Certificate matching, Up: Top 5.1 Matching syntax =================== This is the language definitions somewhat slopply descriped: expr = TRUE, FALSE, ! expr, expr AND expr, expr OR expr, ( expr ) compare compare = word == word, word != word, word IN ( word [, word ...]) word IN %{variable.subvariable} word = STRING, %{variable}  File: hx509.info, Node: Software PKCS 11 module, Next: How to use the PKCS11 module, Prev: Matching syntax, Up: Top 6 Software PKCS 11 module ************************* PKCS11 is a standard created by RSA, Inc to support hardware and software encryption modules. It can be used by smartcard to expose the crypto primitives inside without exposing the crypto keys. Hx509 includes a software implementation of PKCS11 that runs within the memory space of the process and thus exposes the keys to the application.  File: hx509.info, Node: How to use the PKCS11 module, Prev: Software PKCS 11 module, Up: Top 6.1 How to use the PKCS11 module ================================ $ cat > ~/.soft-pkcs11.rc <| hpropd -n} Replace with whatever source you have, like krb4-db or krb4-dump. @item Run a Kerberos 5 slave for a while. @c XXX Add you slave first to your kdc list in you kdc. @item Figure out if it does everything you want it to. Make sure that all things that you use works for you. @item Let a small number of controlled users use Kerberos 5 tools. Find a sample population of your users and check what programs they use, you can also check the kdc-log to check what ticket are checked out. @item Burn the bridge and change the master. @item Let all users use the Kerberos 5 tools by default. @item Turn off services that do not need Kerberos 4 authentication. Things that might be hard to get away is old programs with support for Kerberos 4. Example applications are old Eudora installations using KPOP, and Zephyr. Eudora can use the Kerberos 4 kerberos in the Heimdal kdc. @end itemize heimdal-7.5.0/doc/layman.asc0000644000175000017500000017200712136107747014007 0ustar niknikA Layman's Guide to a Subset of ASN.1, BER, and DER An RSA Laboratories Technical Note Burton S. Kaliski Jr. Revised November 1, 1993 Supersedes June 3, 1991 version, which was also published as NIST/OSI Implementors' Workshop document SEC-SIG-91-17. PKCS documents are available by electronic mail to . Copyright (C) 1991-1993 RSA Laboratories, a division of RSA Data Security, Inc. License to copy this document is granted provided that it is identified as "RSA Data Security, Inc. Public-Key Cryptography Standards (PKCS)" in all material mentioning or referencing this document. 003-903015-110-000-000 Abstract. This note gives a layman's introduction to a subset of OSI's Abstract Syntax Notation One (ASN.1), Basic Encoding Rules (BER), and Distinguished Encoding Rules (DER). The particular purpose of this note is to provide background material sufficient for understanding and implementing the PKCS family of standards. 1. Introduction It is a generally accepted design principle that abstraction is a key to managing software development. With abstraction, a designer can specify a part of a system without concern for how the part is actually implemented or represented. Such a practice leaves the implementation open; it simplifies the specification; and it makes it possible to state "axioms" about the part that can be proved when the part is implemented, and assumed when the part is employed in another, higher-level part. Abstraction is the hallmark of most modern software specifications. One of the most complex systems today, and one that also involves a great deal of abstraction, is Open Systems Interconnection (OSI, described in X.200). OSI is an internationally standardized architecture that governs the interconnection of computers from the physical layer up to the user application layer. Objects at higher layers are defined abstractly and intended to be implemented with objects at lower layers. For instance, a service at one layer may require transfer of certain abstract objects between computers; a lower layer may provide transfer services for strings of ones and zeroes, using encoding rules to transform the abstract objects into such strings. OSI is called an open system because it supports many different implementations of the services at each layer. OSI's method of specifying abstract objects is called ASN.1 (Abstract Syntax Notation One, defined in X.208), and one set of rules for representing such objects as strings of ones and zeros is called the BER (Basic Encoding Rules, defined in X.209). ASN.1 is a flexible notation that allows one to define a variety data types, from simple types such as integers and bit strings to structured types such as sets and sequences, as well as complex types defined in terms of others. BER describes how to represent or encode values of each ASN.1 type as a string of eight-bit octets. There is generally more than one way to BER-encode a given value. Another set of rules, called the Distinguished Encoding Rules (DER), which is a subset of BER, gives a unique encoding to each ASN.1 value. The purpose of this note is to describe a subset of ASN.1, BER and DER sufficient to understand and implement one OSI- based application, RSA Data Security, Inc.'s Public-Key Cryptography Standards. The features described include an overview of ASN.1, BER, and DER and an abridged list of ASN.1 types and their BER and DER encodings. Sections 2-4 give an overview of ASN.1, BER, and DER, in that order. Section 5 lists some ASN.1 types, giving their notation, specific encoding rules, examples, and comments about their application to PKCS. Section 6 concludes with an example, X.500 distinguished names. Advanced features of ASN.1, such as macros, are not described in this note, as they are not needed to implement PKCS. For information on the other features, and for more detail generally, the reader is referred to CCITT Recommendations X.208 and X.209, which define ASN.1 and BER. Terminology and notation. In this note, an octet is an eight- bit unsigned integer. Bit 8 of the octet is the most significant and bit 1 is the least significant. The following meta-syntax is used for in describing ASN.1 notation: BIT monospace denotes literal characters in the type and value notation; in examples, it generally denotes an octet value in hexadecimal n1 bold italics denotes a variable [] bold square brackets indicate that a term is optional {} bold braces group related terms | bold vertical bar delimits alternatives with a group ... bold ellipsis indicates repeated occurrences = bold equals sign expresses terms as subterms 2. Abstract Syntax Notation One Abstract Syntax Notation One, abbreviated ASN.1, is a notation for describing abstract types and values. In ASN.1, a type is a set of values. For some types, there are a finite number of values, and for other types there are an infinite number. A value of a given ASN.1 type is an element of the type's set. ASN.1 has four kinds of type: simple types, which are "atomic" and have no components; structured types, which have components; tagged types, which are derived from other types; and other types, which include the CHOICE type and the ANY type. Types and values can be given names with the ASN.1 assignment operator (::=) , and those names can be used in defining other types and values. Every ASN.1 type other than CHOICE and ANY has a tag, which consists of a class and a nonnegative tag number. ASN.1 types are abstractly the same if and only if their tag numbers are the same. In other words, the name of an ASN.1 type does not affect its abstract meaning, only the tag does. There are four classes of tag: Universal, for types whose meaning is the same in all applications; these types are only defined in X.208. Application, for types whose meaning is specific to an application, such as X.500 directory services; types in two different applications may have the same application-specific tag and different meanings. Private, for types whose meaning is specific to a given enterprise. Context-specific, for types whose meaning is specific to a given structured type; context-specific tags are used to distinguish between component types with the same underlying tag within the context of a given structured type, and component types in two different structured types may have the same tag and different meanings. The types with universal tags are defined in X.208, which also gives the types' universal tag numbers. Types with other tags are defined in many places, and are always obtained by implicit or explicit tagging (see Section 2.3). Table 1 lists some ASN.1 types and their universal-class tags. Type Tag number Tag number (decimal) (hexadecimal) INTEGER 2 02 BIT STRING 3 03 OCTET STRING 4 04 NULL 5 05 OBJECT IDENTIFIER 6 06 SEQUENCE and SEQUENCE OF 16 10 SET and SET OF 17 11 PrintableString 19 13 T61String 20 14 IA5String 22 16 UTCTime 23 17 Table 1. Some types and their universal-class tags. ASN.1 types and values are expressed in a flexible, programming-language-like notation, with the following special rules: o Layout is not significant; multiple spaces and line breaks can be considered as a single space. o Comments are delimited by pairs of hyphens (--), or a pair of hyphens and a line break. o Identifiers (names of values and fields) and type references (names of types) consist of upper- and lower-case letters, digits, hyphens, and spaces; identifiers begin with lower-case letters; type references begin with upper-case letters. The following four subsections give an overview of simple types, structured types, implicitly and explicitly tagged types, and other types. Section 5 describes specific types in more detail. 2.1 Simple types Simple types are those not consisting of components; they are the "atomic" types. ASN.1 defines several; the types that are relevant to the PKCS standards are the following: BIT STRING, an arbitrary string of bits (ones and zeroes). IA5String, an arbitrary string of IA5 (ASCII) characters. INTEGER, an arbitrary integer. NULL, a null value. OBJECT IDENTIFIER, an object identifier, which is a sequence of integer components that identify an object such as an algorithm or attribute type. OCTET STRING, an arbitrary string of octets (eight-bit values). PrintableString, an arbitrary string of printable characters. T61String, an arbitrary string of T.61 (eight-bit) characters. UTCTime, a "coordinated universal time" or Greenwich Mean Time (GMT) value. Simple types fall into two categories: string types and non- string types. BIT STRING, IA5String, OCTET STRING, PrintableString, T61String, and UTCTime are string types. String types can be viewed, for the purposes of encoding, as consisting of components, where the components are substrings. This view allows one to encode a value whose length is not known in advance (e.g., an octet string value input from a file stream) with a constructed, indefinite- length encoding (see Section 3). The string types can be given size constraints limiting the length of values. 2.2 Structured types Structured types are those consisting of components. ASN.1 defines four, all of which are relevant to the PKCS standards: SEQUENCE, an ordered collection of one or more types. SEQUENCE OF, an ordered collection of zero or more occurrences of a given type. SET, an unordered collection of one or more types. SET OF, an unordered collection of zero or more occurrences of a given type. The structured types can have optional components, possibly with default values. 2.3 Implicitly and explicitly tagged types Tagging is useful to distinguish types within an application; it is also commonly used to distinguish component types within a structured type. For instance, optional components of a SET or SEQUENCE type are typically given distinct context-specific tags to avoid ambiguity. There are two ways to tag a type: implicitly and explicitly. Implicitly tagged types are derived from other types by changing the tag of the underlying type. Implicit tagging is denoted by the ASN.1 keywords [class number] IMPLICIT (see Section 5.1). Explicitly tagged types are derived from other types by adding an outer tag to the underlying type. In effect, explicitly tagged types are structured types consisting of one component, the underlying type. Explicit tagging is denoted by the ASN.1 keywords [class number] EXPLICIT (see Section 5.2). The keyword [class number] alone is the same as explicit tagging, except when the "module" in which the ASN.1 type is defined has implicit tagging by default. ("Modules" are among the advanced features not described in this note.) For purposes of encoding, an implicitly tagged type is considered the same as the underlying type, except that the tag is different. An explicitly tagged type is considered like a structured type with one component, the underlying type. Implicit tags result in shorter encodings, but explicit tags may be necessary to avoid ambiguity if the tag of the underlying type is indeterminate (e.g., the underlying type is CHOICE or ANY). 2.4 Other types Other types in ASN.1 include the CHOICE and ANY types. The CHOICE type denotes a union of one or more alternatives; the ANY type denotes an arbitrary value of an arbitrary type, where the arbitrary type is possibly defined in the registration of an object identifier or integer value. 3. Basic Encoding Rules The Basic Encoding Rules for ASN.1, abbreviated BER, give one or more ways to represent any ASN.1 value as an octet string. (There are certainly other ways to represent ASN.1 values, but BER is the standard for interchanging such values in OSI.) There are three methods to encode an ASN.1 value under BER, the choice of which depends on the type of value and whether the length of the value is known. The three methods are primitive, definite-length encoding; constructed, definite- length encoding; and constructed, indefinite-length encoding. Simple non-string types employ the primitive, definite-length method; structured types employ either of the constructed methods; and simple string types employ any of the methods, depending on whether the length of the value is known. Types derived by implicit tagging employ the method of the underlying type and types derived by explicit tagging employ the constructed methods. In each method, the BER encoding has three or four parts: Identifier octets. These identify the class and tag number of the ASN.1 value, and indicate whether the method is primitive or constructed. Length octets. For the definite-length methods, these give the number of contents octets. For the constructed, indefinite-length method, these indicate that the length is indefinite. Contents octets. For the primitive, definite-length method, these give a concrete representation of the value. For the constructed methods, these give the concatenation of the BER encodings of the components of the value. End-of-contents octets. For the constructed, indefinite- length method, these denote the end of the contents. For the other methods, these are absent. The three methods of encoding are described in the following sections. 3.1 Primitive, definite-length method This method applies to simple types and types derived from simple types by implicit tagging. It requires that the length of the value be known in advance. The parts of the BER encoding are as follows: Identifier octets. There are two forms: low tag number (for tag numbers between 0 and 30) and high tag number (for tag numbers 31 and greater). Low-tag-number form. One octet. Bits 8 and 7 specify the class (see Table 2), bit 6 has value "0," indicating that the encoding is primitive, and bits 5-1 give the tag number. Class Bit Bit 8 7 universal 0 0 application 0 1 context-specific 1 0 private 1 1 Table 2. Class encoding in identifier octets. High-tag-number form. Two or more octets. First octet is as in low-tag-number form, except that bits 5-1 all have value "1." Second and following octets give the tag number, base 128, most significant digit first, with as few digits as possible, and with the bit 8 of each octet except the last set to "1." Length octets. There are two forms: short (for lengths between 0 and 127), and long definite (for lengths between 0 and 21008-1). Short form. One octet. Bit 8 has value "0" and bits 7-1 give the length. Long form. Two to 127 octets. Bit 8 of first octet has value "1" and bits 7-1 give the number of additional length octets. Second and following octets give the length, base 256, most significant digit first. Contents octets. These give a concrete representation of the value (or the value of the underlying type, if the type is derived by implicit tagging). Details for particular types are given in Section 5. 3.2 Constructed, definite-length method This method applies to simple string types, structured types, types derived simple string types and structured types by implicit tagging, and types derived from anything by explicit tagging. It requires that the length of the value be known in advance. The parts of the BER encoding are as follows: Identifier octets. As described in Section 3.1, except that bit 6 has value "1," indicating that the encoding is constructed. Length octets. As described in Section 3.1. Contents octets. The concatenation of the BER encodings of the components of the value: o For simple string types and types derived from them by implicit tagging, the concatenation of the BER encodings of consecutive substrings of the value (underlying value for implicit tagging). o For structured types and types derived from them by implicit tagging, the concatenation of the BER encodings of components of the value (underlying value for implicit tagging). o For types derived from anything by explicit tagging, the BER encoding of the underlying value. Details for particular types are given in Section 5. 3.3 Constructed, indefinite-length method This method applies to simple string types, structured types, types derived simple string types and structured types by implicit tagging, and types derived from anything by explicit tagging. It does not require that the length of the value be known in advance. The parts of the BER encoding are as follows: Identifier octets. As described in Section 3.2. Length octets. One octet, 80. Contents octets. As described in Section 3.2. End-of-contents octets. Two octets, 00 00. Since the end-of-contents octets appear where an ordinary BER encoding might be expected (e.g., in the contents octets of a sequence value), the 00 and 00 appear as identifier and length octets, respectively. Thus the end-of-contents octets is really the primitive, definite-length encoding of a value with universal class, tag number 0, and length 0. 4. Distinguished Encoding Rules The Distinguished Encoding Rules for ASN.1, abbreviated DER, are a subset of BER, and give exactly one way to represent any ASN.1 value as an octet string. DER is intended for applications in which a unique octet string encoding is needed, as is the case when a digital signature is computed on an ASN.1 value. DER is defined in Section 8.7 of X.509. DER adds the following restrictions to the rules given in Section 3: 1. When the length is between 0 and 127, the short form of length must be used 2. When the length is 128 or greater, the long form of length must be used, and the length must be encoded in the minimum number of octets. 3. For simple string types and implicitly tagged types derived from simple string types, the primitive, definite-length method must be employed. 4. For structured types, implicitly tagged types derived from structured types, and explicitly tagged types derived from anything, the constructed, definite-length method must be employed. Other restrictions are defined for particular types (such as BIT STRING, SEQUENCE, SET, and SET OF), and can be found in Section 5. 5. Notation and encodings for some types This section gives the notation for some ASN.1 types and describes how to encode values of those types under both BER and DER. The types described are those presented in Section 2. They are listed alphabetically here. Each description includes ASN.1 notation, BER encoding, and DER encoding. The focus of the encodings is primarily on the contents octets; the tag and length octets follow Sections 3 and 4. The descriptions also explain where each type is used in PKCS and related standards. ASN.1 notation is generally only for types, although for the type OBJECT IDENTIFIER, value notation is given as well. 5.1 Implicitly tagged types An implicitly tagged type is a type derived from another type by changing the tag of the underlying type. Implicit tagging is used for optional SEQUENCE components with underlying type other than ANY throughout PKCS, and for the extendedCertificate alternative of PKCS #7's ExtendedCertificateOrCertificate type. ASN.1 notation: [[class] number] IMPLICIT Type class = UNIVERSAL | APPLICATION | PRIVATE where Type is a type, class is an optional class name, and number is the tag number within the class, a nonnegative integer. In ASN.1 "modules" whose default tagging method is implicit tagging, the notation [[class] number] Type is also acceptable, and the keyword IMPLICIT is implied. (See Section 2.3.) For definitions stated outside a module, the explicit inclusion of the keyword IMPLICIT is preferable to prevent ambiguity. If the class name is absent, then the tag is context- specific. Context-specific tags can only appear in a component of a structured or CHOICE type. Example: PKCS #8's PrivateKeyInfo type has an optional attributes component with an implicit, context-specific tag: PrivateKeyInfo ::= SEQUENCE { version Version, privateKeyAlgorithm PrivateKeyAlgorithmIdentifier, privateKey PrivateKey, attributes [0] IMPLICIT Attributes OPTIONAL } Here the underlying type is Attributes, the class is absent (i.e., context-specific), and the tag number within the class is 0. BER encoding. Primitive or constructed, depending on the underlying type. Contents octets are as for the BER encoding of the underlying value. Example: The BER encoding of the attributes component of a PrivateKeyInfo value is as follows: o the identifier octets are 80 if the underlying Attributes value has a primitive BER encoding and a0 if the underlying Attributes value has a constructed BER encoding o the length and contents octets are the same as the length and contents octets of the BER encoding of the underlying Attributes value DER encoding. Primitive or constructed, depending on the underlying type. Contents octets are as for the DER encoding of the underlying value. 5.2 Explicitly tagged types Explicit tagging denotes a type derived from another type by adding an outer tag to the underlying type. Explicit tagging is used for optional SEQUENCE components with underlying type ANY throughout PKCS, and for the version component of X.509's Certificate type. ASN.1 notation: [[class] number] EXPLICIT Type class = UNIVERSAL | APPLICATION | PRIVATE where Type is a type, class is an optional class name, and number is the tag number within the class, a nonnegative integer. If the class name is absent, then the tag is context- specific. Context-specific tags can only appear in a component of a SEQUENCE, SET or CHOICE type. In ASN.1 "modules" whose default tagging method is explicit tagging, the notation [[class] number] Type is also acceptable, and the keyword EXPLICIT is implied. (See Section 2.3.) For definitions stated outside a module, the explicit inclusion of the keyword EXPLICIT is preferable to prevent ambiguity. Example 1: PKCS #7's ContentInfo type has an optional content component with an explicit, context-specific tag: ContentInfo ::= SEQUENCE { contentType ContentType, content [0] EXPLICIT ANY DEFINED BY contentType OPTIONAL } Here the underlying type is ANY DEFINED BY contentType, the class is absent (i.e., context-specific), and the tag number within the class is 0. Example 2: X.509's Certificate type has a version component with an explicit, context-specific tag, where the EXPLICIT keyword is omitted: Certificate ::= ... version [0] Version DEFAULT v1988, ... The tag is explicit because the default tagging method for the ASN.1 "module" in X.509 that defines the Certificate type is explicit tagging. BER encoding. Constructed. Contents octets are the BER encoding of the underlying value. Example: the BER encoding of the content component of a ContentInfo value is as follows: o identifier octets are a0 o length octets represent the length of the BER encoding of the underlying ANY DEFINED BY contentType value o contents octets are the BER encoding of the underlying ANY DEFINED BY contentType value DER encoding. Constructed. Contents octets are the DER encoding of the underlying value. 5.3 ANY The ANY type denotes an arbitrary value of an arbitrary type, where the arbitrary type is possibly defined in the registration of an object identifier or associated with an integer index. The ANY type is used for content of a particular content type in PKCS #7's ContentInfo type, for parameters of a particular algorithm in X.509's AlgorithmIdentifier type, and for attribute values in X.501's Attribute and AttributeValueAssertion types. The Attribute type is used by PKCS #6, #7, #8, #9 and #10, and the AttributeValueAssertion type is used in X.501 distinguished names. ASN.1 notation: ANY [DEFINED BY identifier] where identifier is an optional identifier. In the ANY form, the actual type is indeterminate. The ANY DEFINED BY identifier form can only appear in a component of a SEQUENCE or SET type for which identifier identifies some other component, and that other component has type INTEGER or OBJECT IDENTIFIER (or a type derived from either of those by tagging). In that form, the actual type is determined by the value of the other component, either in the registration of the object identifier value, or in a table of integer values. Example: X.509's AlgorithmIdentifier type has a component of type ANY: AlgorithmIdentifier ::= SEQUENCE { algorithm OBJECT IDENTIFIER, parameters ANY DEFINED BY algorithm OPTIONAL } Here the actual type of the parameter component depends on the value of the algorithm component. The actual type would be defined in the registration of object identifier values for the algorithm component. BER encoding. Same as the BER encoding of the actual value. Example: The BER encoding of the value of the parameter component is the BER encoding of the value of the actual type as defined in the registration of object identifier values for the algorithm component. DER encoding. Same as the DER encoding of the actual value. 5.4 BIT STRING The BIT STRING type denotes an arbitrary string of bits (ones and zeroes). A BIT STRING value can have any length, including zero. This type is a string type. The BIT STRING type is used for digital signatures on extended certificates in PKCS #6's ExtendedCertificate type, for digital signatures on certificates in X.509's Certificate type, and for public keys in certificates in X.509's SubjectPublicKeyInfo type. ASN.1 notation: BIT STRING Example: X.509's SubjectPublicKeyInfo type has a component of type BIT STRING: SubjectPublicKeyInfo ::= SEQUENCE { algorithm AlgorithmIdentifier, publicKey BIT STRING } BER encoding. Primitive or constructed. In a primitive encoding, the first contents octet gives the number of bits by which the length of the bit string is less than the next multiple of eight (this is called the "number of unused bits"). The second and following contents octets give the value of the bit string, converted to an octet string. The conversion process is as follows: 1. The bit string is padded after the last bit with zero to seven bits of any value to make the length of the bit string a multiple of eight. If the length of the bit string is a multiple of eight already, no padding is done. 2. The padded bit string is divided into octets. The first eight bits of the padded bit string become the first octet, bit 8 to bit 1, and so on through the last eight bits of the padded bit string. In a constructed encoding, the contents octets give the concatenation of the BER encodings of consecutive substrings of the bit string, where each substring except the last has a length that is a multiple of eight bits. Example: The BER encoding of the BIT STRING value "011011100101110111" can be any of the following, among others, depending on the choice of padding bits, the form of length octets, and whether the encoding is primitive or constructed: 03 04 06 6e 5d c0 DER encoding 03 04 06 6e 5d e0 padded with "100000" 03 81 04 06 6e 5d c0 long form of length octets 23 09 constructed encoding: "0110111001011101" + "11" 03 03 00 6e 5d 03 02 06 c0 DER encoding. Primitive. The contents octects are as for a primitive BER encoding, except that the bit string is padded with zero-valued bits. Example: The DER encoding of the BIT STRING value "011011100101110111" is 03 04 06 6e 5d c0 5.5 CHOICE The CHOICE type denotes a union of one or more alternatives. The CHOICE type is used to represent the union of an extended certificate and an X.509 certificate in PKCS #7's ExtendedCertificateOrCertificate type. ASN.1 notation: CHOICE { [identifier1] Type1, ..., [identifiern] Typen } where identifier1 , ..., identifiern are optional, distinct identifiers for the alternatives, and Type1, ..., Typen are the types of the alternatives. The identifiers are primarily for documentation; they do not affect values of the type or their encodings in any way. The types must have distinct tags. This requirement is typically satisfied with explicit or implicit tagging on some of the alternatives. Example: PKCS #7's ExtendedCertificateOrCertificate type is a CHOICE type: ExtendedCertificateOrCertificate ::= CHOICE { certificate Certificate, -- X.509 extendedCertificate [0] IMPLICIT ExtendedCertificate } Here the identifiers for the alternatives are certificate and extendedCertificate, and the types of the alternatives are Certificate and [0] IMPLICIT ExtendedCertificate. BER encoding. Same as the BER encoding of the chosen alternative. The fact that the alternatives have distinct tags makes it possible to distinguish between their BER encodings. Example: The identifier octets for the BER encoding are 30 if the chosen alternative is certificate, and a0 if the chosen alternative is extendedCertificate. DER encoding. Same as the DER encoding of the chosen alternative. 5.6 IA5String The IA5String type denotes an arbtrary string of IA5 characters. IA5 stands for International Alphabet 5, which is the same as ASCII. The character set includes non- printing control characters. An IA5String value can have any length, including zero. This type is a string type. The IA5String type is used in PKCS #9's electronic-mail address, unstructured-name, and unstructured-address attributes. ASN.1 notation: IA5String BER encoding. Primitive or constructed. In a primitive encoding, the contents octets give the characters in the IA5 string, encoded in ASCII. In a constructed encoding, the contents octets give the concatenation of the BER encodings of consecutive substrings of the IA5 string. Example: The BER encoding of the IA5String value "test1@rsa.com" can be any of the following, among others, depending on the form of length octets and whether the encoding is primitive or constructed: 16 0d 74 65 73 74 31 40 72 73 61 2e 63 6f 6d DER encoding 16 81 0d long form of length octets 74 65 73 74 31 40 72 73 61 2e 63 6f 6d 36 13 constructed encoding: "test1" + "@" + "rsa.com" 16 05 74 65 73 74 31 16 01 40 16 07 72 73 61 2e 63 6f 6d DER encoding. Primitive. Contents octets are as for a primitive BER encoding. Example: The DER encoding of the IA5String value "test1@rsa.com" is 16 0d 74 65 73 74 31 40 72 73 61 2e 63 6f 6d 5.7 INTEGER The INTEGER type denotes an arbitrary integer. INTEGER values can be positive, negative, or zero, and can have any magnitude. The INTEGER type is used for version numbers throughout PKCS, cryptographic values such as modulus, exponent, and primes in PKCS #1's RSAPublicKey and RSAPrivateKey types and PKCS #3's DHParameter type, a message-digest iteration count in PKCS #5's PBEParameter type, and version numbers and serial numbers in X.509's Certificate type. ASN.1 notation: INTEGER [{ identifier1(value1) ... identifiern(valuen) }] where identifier1, ..., identifiern are optional distinct identifiers and value1, ..., valuen are optional integer values. The identifiers, when present, are associated with values of the type. Example: X.509's Version type is an INTEGER type with identified values: Version ::= INTEGER { v1988(0) } The identifier v1988 is associated with the value 0. X.509's Certificate type uses the identifier v1988 to give a default value of 0 for the version component: Certificate ::= ... version Version DEFAULT v1988, ... BER encoding. Primitive. Contents octets give the value of the integer, base 256, in two's complement form, most significant digit first, with the minimum number of octets. The value 0 is encoded as a single 00 octet. Some example BER encodings (which also happen to be DER encodings) are given in Table 3. Integer BER encoding value 0 02 01 00 127 02 01 7F 128 02 02 00 80 256 02 02 01 00 -128 02 01 80 -129 02 02 FF 7F Table 3. Example BER encodings of INTEGER values. DER encoding. Primitive. Contents octets are as for a primitive BER encoding. 5.8 NULL The NULL type denotes a null value. The NULL type is used for algorithm parameters in several places in PKCS. ASN.1 notation: NULL BER encoding. Primitive. Contents octets are empty. Example: The BER encoding of a NULL value can be either of the following, as well as others, depending on the form of the length octets: 05 00 05 81 00 DER encoding. Primitive. Contents octets are empty; the DER encoding of a NULL value is always 05 00. 5.9 OBJECT IDENTIFIER The OBJECT IDENTIFIER type denotes an object identifier, a sequence of integer components that identifies an object such as an algorithm, an attribute type, or perhaps a registration authority that defines other object identifiers. An OBJECT IDENTIFIER value can have any number of components, and components can generally have any nonnegative value. This type is a non-string type. OBJECT IDENTIFIER values are given meanings by registration authorities. Each registration authority is responsible for all sequences of components beginning with a given sequence. A registration authority typically delegates responsibility for subsets of the sequences in its domain to other registration authorities, or for particular types of object. There are always at least two components. The OBJECT IDENTIFIER type is used to identify content in PKCS #7's ContentInfo type, to identify algorithms in X.509's AlgorithmIdentifier type, and to identify attributes in X.501's Attribute and AttributeValueAssertion types. The Attribute type is used by PKCS #6, #7, #8, #9, and #10, and the AttributeValueAssertion type is used in X.501 distinguished names. OBJECT IDENTIFIER values are defined throughout PKCS. ASN.1 notation: OBJECT IDENTIFIER The ASN.1 notation for values of the OBJECT IDENTIFIER type is { [identifier] component1 ... componentn } componenti = identifieri | identifieri (valuei) | valuei where identifier, identifier1, ..., identifiern are identifiers, and value1, ..., valuen are optional integer values. The form without identifier is the "complete" value with all its components; the form with identifier abbreviates the beginning components with another object identifier value. The identifiers identifier1, ..., identifiern are intended primarily for documentation, but they must correspond to the integer value when both are present. These identifiers can appear without integer values only if they are among a small set of identifiers defined in X.208. Example: The following values both refer to the object identifier assigned to RSA Data Security, Inc.: { iso(1) member-body(2) 840 113549 } { 1 2 840 113549 } (In this example, which gives ASN.1 value notation, the object identifier values are decimal, not hexadecimal.) Table 4 gives some other object identifier values and their meanings. Object identifier value Meaning { 1 2 } ISO member bodies { 1 2 840 } US (ANSI) { 1 2 840 113549 } RSA Data Security, Inc. { 1 2 840 113549 1 } RSA Data Security, Inc. PKCS { 2 5 } directory services (X.500) { 2 5 8 } directory services-algorithms Table 4. Some object identifier values and their meanings. BER encoding. Primitive. Contents octets are as follows, where value1, ..., valuen denote the integer values of the components in the complete object identifier: 1. The first octet has value 40 * value1 + value2. (This is unambiguous, since value1 is limited to values 0, 1, and 2; value2 is limited to the range 0 to 39 when value1 is 0 or 1; and, according to X.208, n is always at least 2.) 2. The following octets, if any, encode value3, ..., valuen. Each value is encoded base 128, most significant digit first, with as few digits as possible, and the most significant bit of each octet except the last in the value's encoding set to "1." Example: The first octet of the BER encoding of RSA Data Security, Inc.'s object identifier is 40 * 1 + 2 = 42 = 2a16. The encoding of 840 = 6 * 128 + 4816 is 86 48 and the encoding of 113549 = 6 * 1282 + 7716 * 128 + d16 is 86 f7 0d. This leads to the following BER encoding: 06 06 2a 86 48 86 f7 0d DER encoding. Primitive. Contents octets are as for a primitive BER encoding. 5.10 OCTET STRING The OCTET STRING type denotes an arbitrary string of octets (eight-bit values). An OCTET STRING value can have any length, including zero. This type is a string type. The OCTET STRING type is used for salt values in PKCS #5's PBEParameter type, for message digests, encrypted message digests, and encrypted content in PKCS #7, and for private keys and encrypted private keys in PKCS #8. ASN.1 notation: OCTET STRING [SIZE ({size | size1..size2})] where size, size1, and size2 are optional size constraints. In the OCTET STRING SIZE (size) form, the octet string must have size octets. In the OCTET STRING SIZE (size1..size2) form, the octet string must have between size1 and size2 octets. In the OCTET STRING form, the octet string can have any size. Example: PKCS #5's PBEParameter type has a component of type OCTET STRING: PBEParameter ::= SEQUENCE { salt OCTET STRING SIZE(8), iterationCount INTEGER } Here the size of the salt component is always eight octets. BER encoding. Primitive or constructed. In a primitive encoding, the contents octets give the value of the octet string, first octet to last octet. In a constructed encoding, the contents octets give the concatenation of the BER encodings of substrings of the OCTET STRING value. Example: The BER encoding of the OCTET STRING value 01 23 45 67 89 ab cd ef can be any of the following, among others, depending on the form of length octets and whether the encoding is primitive or constructed: 04 08 01 23 45 67 89 ab cd ef DER encoding 04 81 08 01 23 45 67 89 ab cd ef long form of length octets 24 0c constructed encoding: 01 ... 67 + 89 ... ef 04 04 01 23 45 67 04 04 89 ab cd ef DER encoding. Primitive. Contents octets are as for a primitive BER encoding. Example: The BER encoding of the OCTET STRING value 01 23 45 67 89 ab cd ef is 04 08 01 23 45 67 89 ab cd ef 5.11 PrintableString The PrintableString type denotes an arbitrary string of printable characters from the following character set: A, B, ..., Z a, b, ..., z 0, 1, ..., 9 (space) ' ( ) + , - . / : = ? This type is a string type. The PrintableString type is used in PKCS #9's challenge- password and unstructuerd-address attributes, and in several X.521 distinguished names attributes. ASN.1 notation: PrintableString BER encoding. Primitive or constructed. In a primitive encoding, the contents octets give the characters in the printable string, encoded in ASCII. In a constructed encoding, the contents octets give the concatenation of the BER encodings of consecutive substrings of the string. Example: The BER encoding of the PrintableString value "Test User 1" can be any of the following, among others, depending on the form of length octets and whether the encoding is primitive or constructed: 13 0b 54 65 73 74 20 55 73 65 72 20 31 DER encoding 13 81 0b long form of length octets 54 65 73 74 20 55 73 65 72 20 31 33 0f constructed encoding: "Test " + "User 1" 13 05 54 65 73 74 20 13 06 55 73 65 72 20 31 DER encoding. Primitive. Contents octets are as for a primitive BER encoding. Example: The DER encoding of the PrintableString value "Test User 1" is 13 0b 54 65 73 74 20 55 73 65 72 20 31 5.12 SEQUENCE The SEQUENCE type denotes an ordered collection of one or more types. The SEQUENCE type is used throughout PKCS and related standards. ASN.1 notation: SEQUENCE { [identifier1] Type1 [{OPTIONAL | DEFAULT value1}], ..., [identifiern] Typen [{OPTIONAL | DEFAULT valuen}]} where identifier1 , ..., identifiern are optional, distinct identifiers for the components, Type1, ..., Typen are the types of the components, and value1, ..., valuen are optional default values for the components. The identifiers are primarily for documentation; they do not affect values of the type or their encodings in any way. The OPTIONAL qualifier indicates that the value of a component is optional and need not be present in the sequence. The DEFAULT qualifier also indicates that the value of a component is optional, and assigns a default value to the component when the component is absent. The types of any consecutive series of components with the OPTIONAL or DEFAULT qualifier, as well as of any component immediately following that series, must have distinct tags. This requirement is typically satisfied with explicit or implicit tagging on some of the components. Example: X.509's Validity type is a SEQUENCE type with two components: Validity ::= SEQUENCE { start UTCTime, end UTCTime } Here the identifiers for the components are start and end, and the types of the components are both UTCTime. BER encoding. Constructed. Contents octets are the concatenation of the BER encodings of the values of the components of the sequence, in order of definition, with the following rules for components with the OPTIONAL and DEFAULT qualifiers: o if the value of a component with the OPTIONAL or DEFAULT qualifier is absent from the sequence, then the encoding of that component is not included in the contents octets o if the value of a component with the DEFAULT qualifier is the default value, then the encoding of that component may or may not be included in the contents octets DER encoding. Constructed. Contents octets are the same as the BER encoding, except that if the value of a component with the DEFAULT qualifier is the default value, the encoding of that component is not included in the contents octets. 5.13 SEQUENCE OF The SEQUENCE OF type denotes an ordered collection of zero or more occurrences of a given type. The SEQUENCE OF type is used in X.501 distinguished names. ASN.1 notation: SEQUENCE OF Type where Type is a type. Example: X.501's RDNSequence type consists of zero or more occurences of the RelativeDistinguishedName type, most significant occurrence first: RDNSequence ::= SEQUENCE OF RelativeDistinguishedName BER encoding. Constructed. Contents octets are the concatenation of the BER encodings of the values of the occurrences in the collection, in order of occurence. DER encoding. Constructed. Contents octets are the concatenation of the DER encodings of the values of the occurrences in the collection, in order of occurence. 5.14 SET The SET type denotes an unordered collection of one or more types. The SET type is not used in PKCS. ASN.1 notation: SET { [identifier1] Type1 [{OPTIONAL | DEFAULT value1}], ..., [identifiern] Typen [{OPTIONAL | DEFAULT valuen}]} where identifier1, ..., identifiern are optional, distinct identifiers for the components, Type1, ..., Typen are the types of the components, and value1, ..., valuen are optional default values for the components. The identifiers are primarily for documentation; they do not affect values of the type or their encodings in any way. The OPTIONAL qualifier indicates that the value of a component is optional and need not be present in the set. The DEFAULT qualifier also indicates that the value of a component is optional, and assigns a default value to the component when the component is absent. The types must have distinct tags. This requirement is typically satisfied with explicit or implicit tagging on some of the components. BER encoding. Constructed. Contents octets are the concatenation of the BER encodings of the values of the components of the set, in any order, with the following rules for components with the OPTIONAL and DEFAULT qualifiers: o if the value of a component with the OPTIONAL or DEFAULT qualifier is absent from the set, then the encoding of that component is not included in the contents octets o if the value of a component with the DEFAULT qualifier is the default value, then the encoding of that component may or may not be included in the contents octets DER encoding. Constructed. Contents octets are the same as for the BER encoding, except that: 1. If the value of a component with the DEFAULT qualifier is the default value, the encoding of that component is not included. 2. There is an order to the components, namely ascending order by tag. 5.15 SET OF The SET OF type denotes an unordered collection of zero or more occurrences of a given type. The SET OF type is used for sets of attributes in PKCS #6, #7, #8, #9 and #10, for sets of message-digest algorithm identifiers, signer information, and recipient information in PKCS #7, and in X.501 distinguished names. ASN.1 notation: SET OF Type where Type is a type. Example: X.501's RelativeDistinguishedName type consists of zero or more occurrences of the AttributeValueAssertion type, where the order is unimportant: RelativeDistinguishedName ::= SET OF AttributeValueAssertion BER encoding. Constructed. Contents octets are the concatenation of the BER encodings of the values of the occurrences in the collection, in any order. DER encoding. Constructed. Contents octets are the same as for the BER encoding, except that there is an order, namely ascending lexicographic order of BER encoding. Lexicographic comparison of two different BER encodings is done as follows: Logically pad the shorter BER encoding after the last octet with dummy octets that are smaller in value than any normal octet. Scan the BER encodings from left to right until a difference is found. The smaller-valued BER encoding is the one with the smaller-valued octet at the point of difference. 5.16 T61String The T61String type denotes an arbtrary string of T.61 characters. T.61 is an eight-bit extension to the ASCII character set. Special "escape" sequences specify the interpretation of subsequent character values as, for example, Japanese; the initial interpretation is Latin. The character set includes non-printing control characters. The T61String type allows only the Latin and Japanese character interepretations, and implementors' agreements for directory names exclude control characters [NIST92]. A T61String value can have any length, including zero. This type is a string type. The T61String type is used in PKCS #9's unstructured-address and challenge-password attributes, and in several X.521 attributes. ASN.1 notation: T61String BER encoding. Primitive or constructed. In a primitive encoding, the contents octets give the characters in the T.61 string, encoded in ASCII. In a constructed encoding, the contents octets give the concatenation of the BER encodings of consecutive substrings of the T.61 string. Example: The BER encoding of the T61String value "cl'es publiques" (French for "public keys") can be any of the following, among others, depending on the form of length octets and whether the encoding is primitive or constructed: 14 0f DER encoding 63 6c c2 65 73 20 70 75 62 6c 69 71 75 65 73 14 81 0f long form of length octets 63 6c c2 65 73 20 70 75 62 6c 69 71 75 65 73 34 15 constructed encoding: "cl'es" + " " + "publiques" 14 05 63 6c c2 65 73 14 01 20 14 09 70 75 62 6c 69 71 75 65 73 The eight-bit character c2 is a T.61 prefix that adds an acute accent (') to the next character. DER encoding. Primitive. Contents octets are as for a primitive BER encoding. Example: The DER encoding of the T61String value "cl'es publiques" is 14 0f 63 6c c2 65 73 20 70 75 62 6c 69 71 75 65 73 5.17 UTCTime The UTCTime type denotes a "coordinated universal time" or Greenwich Mean Time (GMT) value. A UTCTime value includes the local time precise to either minutes or seconds, and an offset from GMT in hours and minutes. It takes any of the following forms: YYMMDDhhmmZ YYMMDDhhmm+hh'mm' YYMMDDhhmm-hh'mm' YYMMDDhhmmssZ YYMMDDhhmmss+hh'mm' YYMMDDhhmmss-hh'mm' where: YY is the least significant two digits of the year MM is the month (01 to 12) DD is the day (01 to 31) hh is the hour (00 to 23) mm are the minutes (00 to 59) ss are the seconds (00 to 59) Z indicates that local time is GMT, + indicates that local time is later than GMT, and - indicates that local time is earlier than GMT hh' is the absolute value of the offset from GMT in hours mm' is the absolute value of the offset from GMT in minutes This type is a string type. The UTCTime type is used for signing times in PKCS #9's signing-time attribute and for certificate validity periods in X.509's Validity type. ASN.1 notation: UTCTime BER encoding. Primitive or constructed. In a primitive encoding, the contents octets give the characters in the string, encoded in ASCII. In a constructed encoding, the contents octets give the concatenation of the BER encodings of consecutive substrings of the string. (The constructed encoding is not particularly interesting, since UTCTime values are so short, but the constructed encoding is permitted.) Example: The time this sentence was originally written was 4:45:40 p.m. Pacific Daylight Time on May 6, 1991, which can be represented with either of the following UTCTime values, among others: "910506164540-0700" "910506234540Z" These values have the following BER encodings, among others: 17 0d 39 31 30 35 30 36 32 33 34 35 34 30 5a 17 11 39 31 30 35 30 36 31 36 34 35 34 30 2D 30 37 30 30 DER encoding. Primitive. Contents octets are as for a primitive BER encoding. 6. An example This section gives an example of ASN.1 notation and DER encoding: the X.501 type Name. 6.1 Abstract notation This section gives the ASN.1 notation for the X.501 type Name. Name ::= CHOICE { RDNSequence } RDNSequence ::= SEQUENCE OF RelativeDistinguishedName RelativeDistinguishedName ::= SET OF AttributeValueAssertion AttributeValueAssertion ::= SEQUENCE { AttributeType, AttributeValue } AttributeType ::= OBJECT IDENTIFIER AttributeValue ::= ANY The Name type identifies an object in an X.500 directory. Name is a CHOICE type consisting of one alternative: RDNSequence. (Future revisions of X.500 may have other alternatives.) The RDNSequence type gives a path through an X.500 directory tree starting at the root. RDNSequence is a SEQUENCE OF type consisting of zero or more occurences of RelativeDistinguishedName. The RelativeDistinguishedName type gives a unique name to an object relative to the object superior to it in the directory tree. RelativeDistinguishedName is a SET OF type consisting of zero or more occurrences of AttributeValueAssertion. The AttributeValueAssertion type assigns a value to some attribute of a relative distinguished name, such as country name or common name. AttributeValueAssertion is a SEQUENCE type consisting of two components, an AttributeType type and an AttributeValue type. The AttributeType type identifies an attribute by object identifier. The AttributeValue type gives an arbitrary attribute value. The actual type of the attribute value is determined by the attribute type. 6.2 DER encoding This section gives an example of a DER encoding of a value of type Name, working from the bottom up. The name is that of the Test User 1 from the PKCS examples [Kal93]. The name is represented by the following path: (root) | countryName = "US" | organizationName = "Example Organization" | commonName = "Test User 1" Each level corresponds to one RelativeDistinguishedName value, each of which happens for this name to consist of one AttributeValueAssertion value. The AttributeType value is before the equals sign, and the AttributeValue value (a printable string for the given attribute types) is after the equals sign. The countryName, organizationName, and commonUnitName are attribute types defined in X.520 as: attributeType OBJECT IDENTIFIER ::= { joint-iso-ccitt(2) ds(5) 4 } countryName OBJECT IDENTIFIER ::= { attributeType 6 } organizationName OBJECT IDENTIFIER ::= { attributeType 10 } commonUnitName OBJECT IDENTIFIER ::= { attributeType 3 } 6.2.1 AttributeType The three AttributeType values are OCTET STRING values, so their DER encoding follows the primitive, definite-length method: 06 03 55 04 06 countryName 06 03 55 04 0a organizationName 06 03 55 04 03 commonName The identifier octets follow the low-tag form, since the tag is 6 for OBJECT IDENTIFIER. Bits 8 and 7 have value "0," indicating universal class, and bit 6 has value "0," indicating that the encoding is primitive. The length octets follow the short form. The contents octets are the concatenation of three octet strings derived from subidentifiers (in decimal): 40 * 2 + 5 = 85 = 5516; 4; and 6, 10, or 3. 6.2.2 AttributeValue The three AttributeValue values are PrintableString values, so their encodings follow the primitive, definite-length method: 13 02 55 53 "US" 13 14 "Example Organization" 45 78 61 6d 70 6c 65 20 4f 72 67 61 6e 69 7a 61 74 69 6f 6e 13 0b "Test User 1" 54 65 73 74 20 55 73 65 72 20 31 The identifier octets follow the low-tag-number form, since the tag for PrintableString, 19 (decimal), is between 0 and 30. Bits 8 and 7 have value "0" since PrintableString is in the universal class. Bit 6 has value "0" since the encoding is primitive. The length octets follow the short form, and the contents octets are the ASCII representation of the attribute value. 6.2.3 AttributeValueAssertion The three AttributeValueAssertion values are SEQUENCE values, so their DER encodings follow the constructed, definite-length method: 30 09 countryName = "US" 06 03 55 04 06 13 02 55 53 30 1b organizationName = "Example Organizaiton" 06 03 55 04 0a 13 14 ... 6f 6e 30 12 commonName = "Test User 1" 06 03 55 04 0b 13 0b ... 20 31 The identifier octets follow the low-tag-number form, since the tag for SEQUENCE, 16 (decimal), is between 0 and 30. Bits 8 and 7 have value "0" since SEQUENCE is in the universal class. Bit 6 has value "1" since the encoding is constructed. The length octets follow the short form, and the contents octets are the concatenation of the DER encodings of the attributeType and attributeValue components. 6.2.4 RelativeDistinguishedName The three RelativeDistinguishedName values are SET OF values, so their DER encodings follow the constructed, definite-length method: 31 0b 30 09 ... 55 53 31 1d 30 1b ... 6f 6e 31 14 30 12 ... 20 31 The identifier octets follow the low-tag-number form, since the tag for SET OF, 17 (decimal), is between 0 and 30. Bits 8 and 7 have value "0" since SET OF is in the universal class Bit 6 has value "1" since the encoding is constructed. The lengths octets follow the short form, and the contents octets are the DER encodings of the respective AttributeValueAssertion values, since there is only one value in each set. 6.2.5 RDNSequence The RDNSequence value is a SEQUENCE OF value, so its DER encoding follows the constructed, definite-length method: 30 42 31 0b ... 55 53 31 1d ... 6f 6e 31 14 ... 20 31 The identifier octets follow the low-tag-number form, since the tag for SEQUENCE OF, 16 (decimal), is between 0 and 30. Bits 8 and 7 have value "0" since SEQUENCE OF is in the universal class. Bit 6 has value "1" since the encoding is constructed. The lengths octets follow the short form, and the contents octets are the concatenation of the DER encodings of the three RelativeDistinguishedName values, in order of occurrence. 6.2.6 Name The Name value is a CHOICE value, so its DER encoding is the same as that of the RDNSequence value: 30 42 31 0b 30 09 06 03 55 04 06 attributeType = countryName 13 02 55 53 attributeValue = "US" 31 1d 30 1b 06 03 55 04 0a attributeType = organizationName 13 14 attributeValue = "Example Organization" 45 78 61 6d 70 6c 65 20 4f 72 67 61 6e 69 7a 61 74 69 6f 6e 31 14 30 12 06 03 55 04 03 attributeType = commonName 13 0b attributeValue = "Test User 1" 54 65 73 74 20 55 73 65 72 20 31 References PKCS #1 RSA Laboratories. PKCS #1: RSA Encryption Standard. Version 1.5, November 1993. PKCS #3 RSA Laboratories. PKCS #3: Diffie-Hellman Key- Agreement Standard. Version 1.4, November 1993. PKCS #5 RSA Laboratories. PKCS #5: Password-Based Encryption Standard. Version 1.5, November 1993. PKCS #6 RSA Laboratories. PKCS #6: Extended-Certificate Syntax Standard. Version 1.5, November 1993. PKCS #7 RSA Laboratories. PKCS #7: Cryptographic Message Syntax Standard. Version 1.5, November 1993. PKCS #8 RSA Laboratories. PKCS #8: Private-Key Information Syntax Standard. Version 1.2, November 1993. PKCS #9 RSA Laboratories. PKCS #9: Selected Attribute Types. Version 1.1, November 1993. PKCS #10 RSA Laboratories. PKCS #10: Certification Request Syntax Standard. Version 1.0, November 1993. X.200 CCITT. Recommendation X.200: Reference Model of Open Systems Interconnection for CCITT Applications. 1984. X.208 CCITT. Recommendation X.208: Specification of Abstract Syntax Notation One (ASN.1). 1988. X.209 CCITT. Recommendation X.209: Specification of Basic Encoding Rules for Abstract Syntax Notation One (ASN.1). 1988. X.500 CCITT. Recommendation X.500: The Directory--Overview of Concepts, Models and Services. 1988. X.501 CCITT. Recommendation X.501: The Directory-- Models. 1988. X.509 CCITT. Recommendation X.509: The Directory-- Authentication Framework. 1988. X.520 CCITT. Recommendation X.520: The Directory-- Selected Attribute Types. 1988. [Kal93] Burton S. Kaliski Jr. Some Examples of the PKCS Standards. RSA Laboratories, November 1993. [NIST92] NIST. Special Publication 500-202: Stable Implementation Agreements for Open Systems Interconnection Protocols. Part 11 (Directory Services Protocols). December 1992. Revision history June 3, 1991 version The June 3, 1991 version is part of the initial public release of PKCS. It was published as NIST/OSI Implementors' Workshop document SEC-SIG-91-17. November 1, 1993 version The November 1, 1993 version incorporates several editorial changes, including the addition of a revision history. It is updated to be consistent with the following versions of the PKCS documents: PKCS #1: RSA Encryption Standard. Version 1.5, November 1993. PKCS #3: Diffie-Hellman Key-Agreement Standard. Version 1.4, November 1993. PKCS #5: Password-Based Encryption Standard. Version 1.5, November 1993. PKCS #6: Extended-Certificate Syntax Standard. Version 1.5, November 1993. PKCS #7: Cryptographic Message Syntax Standard. Version 1.5, November 1993. PKCS #8: Private-Key Information Syntax Standard. Version 1.2, November 1993. PKCS #9: Selected Attribute Types. Version 1.1, November 1993. PKCS #10: Certification Request Syntax Standard. Version 1.0, November 1993. The following substantive changes were made: Section 5: Description of T61String type is added. Section 6: Names are changed, consistent with other PKCS examples. Author's address Burton S. Kaliski Jr., Ph.D. Chief Scientist RSA Laboratories (415) 595-7703 100 Marine Parkway (415) 595-4126 (fax) Redwood City, CA 94065 USA burt@rsa.com heimdal-7.5.0/doc/misc.texi0000644000175000017500000000512212136107747013655 0ustar niknik@c $Id$ @node Things in search for a better place, Kerberos 4 issues, Applications, Top @chapter Things in search for a better place @section Making things work on Ciscos Modern versions of Cisco IOS has some support for authenticating via Kerberos 5. This can be used both by having the router get a ticket when you login (boring), and by using Kerberos authenticated telnet to access your router (less boring). The following has been tested on IOS 11.2(12), things might be different with other versions. Old versions are known to have bugs. To make this work, you will first have to configure your router to use Kerberos (this is explained in the documentation). A sample configuration looks like the following: @example aaa new-model aaa authentication login default krb5-telnet krb5 enable aaa authorization exec krb5-instance kerberos local-realm FOO.SE kerberos srvtab entry host/router.foo.se 0 891725446 4 1 8 012345678901234567 kerberos server FOO.SE 10.0.0.1 kerberos instance map admin 15 @end example This tells you (among other things) that when logging in, the router should try to authenticate with kerberised telnet, and if that fails try to verify a plain text password via a Kerberos ticket exchange (as opposed to a local database, RADIUS or something similar), and if that fails try the local enable password. If you're not careful when you specify the `login default' authentication mechanism, you might not be able to login at all. The `instance map' and `authorization exec' lines says that people with `admin' instances should be given `enabled' shells when logging in. The numbers after the principal on the `srvtab' line are principal type, time stamp (in seconds since 1970), key version number (4), keytype (1 == des), key length (always 8 with des), and then the key. To make the Heimdal KDC produce tickets that the Cisco can decode you might have to turn on the @samp{encode_as_rep_as_tgs_rep} flag in the KDC. You will also have to specify that the router can't handle anything but @samp{des-cbc-crc}. This can be done with the @samp{del_enctype} command of @samp{kadmin}. This all fine and so, but unless you have an IOS version with encryption (available only in the U.S) it doesn't really solve any problems. Sure you don't have to send your password over the wire, but since the telnet connection isn't protected it's still possible for someone to steal your session. This won't be fixed until someone adds integrity to the telnet protocol. A working solution would be to hook up a machine with a real operating system to the console of the Cisco and then use it as a backwards terminal server. heimdal-7.5.0/lib/0000755000175000017500000000000013214604041012013 5ustar niknikheimdal-7.5.0/lib/base/0000755000175000017500000000000013212450752012733 5ustar niknikheimdal-7.5.0/lib/base/dll.c0000644000175000017500000002312613026237312013654 0ustar niknik/*********************************************************************** * Copyright (c) 2016 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. * **********************************************************************/ /* * This is an implementation of thread-specific storage with * destructors. WIN32 doesn't quite have this. Instead it has * DllMain(), an entry point in every DLL that gets called to notify the * DLL of thread/process "attach"/"detach" events. * * We use __thread (or __declspec(thread)) for the thread-local itself * and DllMain() DLL_THREAD_DETACH events to drive destruction of * thread-local values. * * When building in maintainer mode on non-Windows pthread systems this * uses a single pthread key instead to implement multiple keys. This * keeps the code from rotting when modified by non-Windows developers. */ #include "baselocl.h" #ifdef WIN32 #include #endif #ifdef HEIM_WIN32_TLS #include #include #include #ifndef WIN32 #include #endif /* Logical array of keys that grows lock-lessly */ typedef struct tls_keys tls_keys; struct tls_keys { void (**keys_dtors)(void *); /* array of destructors */ size_t keys_start_idx; /* index of first destructor */ size_t keys_num; tls_keys *keys_next; }; /* * Well, not quite locklessly. We need synchronization primitives to do * this locklessly. An atomic CAS will do. */ static HEIMDAL_MUTEX tls_key_defs_lock = HEIMDAL_MUTEX_INITIALIZER; static tls_keys *tls_key_defs; /* Logical array of values (per-thread; no locking needed here) */ struct tls_values { void **values; /* realloc()ed */ size_t values_num; }; static HEIMDAL_THREAD_LOCAL struct tls_values values; #define DEAD_KEY ((void *)8) void heim_w32_service_thread_detach(void *unused) { tls_keys *key_defs; void (*dtor)(void*); size_t i; HEIMDAL_MUTEX_lock(&tls_key_defs_lock); key_defs = tls_key_defs; HEIMDAL_MUTEX_unlock(&tls_key_defs_lock); if (key_defs == NULL) return; for (i = 0; i < values.values_num; i++) { assert(i >= key_defs->keys_start_idx); if (i >= key_defs->keys_start_idx + key_defs->keys_num) { HEIMDAL_MUTEX_lock(&tls_key_defs_lock); key_defs = key_defs->keys_next; HEIMDAL_MUTEX_unlock(&tls_key_defs_lock); assert(key_defs != NULL); assert(i >= key_defs->keys_start_idx); assert(i < key_defs->keys_start_idx + key_defs->keys_num); } dtor = key_defs->keys_dtors[i - key_defs->keys_start_idx]; if (values.values[i] != NULL && dtor != NULL && dtor != DEAD_KEY) dtor(values.values[i]); values.values[i] = NULL; } } #if !defined(WIN32) static pthread_key_t pt_key; pthread_once_t pt_once = PTHREAD_ONCE_INIT; static void atexit_del_tls_for_thread(void) { heim_w32_service_thread_detach(NULL); } static void create_pt_key(void) { int ret; /* The main thread may not execute TLS destructors */ atexit(atexit_del_tls_for_thread); ret = pthread_key_create(&pt_key, heim_w32_service_thread_detach); if (ret != 0) err(1, "pthread_key_create() failed"); } #endif int heim_w32_key_create(HEIM_PRIV_thread_key *key, void (*dtor)(void *)) { tls_keys *key_defs, *new_key_defs; size_t i, k; int ret = ENOMEM; #if !defined(WIN32) (void) pthread_once(&pt_once, create_pt_key); (void) pthread_setspecific(pt_key, DEAD_KEY); #endif HEIMDAL_MUTEX_lock(&tls_key_defs_lock); if (tls_key_defs == NULL) { /* First key */ new_key_defs = calloc(1, sizeof(*new_key_defs)); if (new_key_defs == NULL) { HEIMDAL_MUTEX_unlock(&tls_key_defs_lock); return ENOMEM; } new_key_defs->keys_num = 8; new_key_defs->keys_dtors = calloc(new_key_defs->keys_num, sizeof(*new_key_defs->keys_dtors)); if (new_key_defs->keys_dtors == NULL) { HEIMDAL_MUTEX_unlock(&tls_key_defs_lock); free(new_key_defs); return ENOMEM; } tls_key_defs = new_key_defs; new_key_defs->keys_dtors[0] = dtor; for (i = 1; i < new_key_defs->keys_num; i++) new_key_defs->keys_dtors[i] = NULL; HEIMDAL_MUTEX_unlock(&tls_key_defs_lock); return 0; } for (key_defs = tls_key_defs; key_defs != NULL; key_defs = key_defs->keys_next) { k = key_defs->keys_start_idx; for (i = 0; i < key_defs->keys_num; i++, k++) { if (key_defs->keys_dtors[i] == NULL) { /* Found free slot; use it */ key_defs->keys_dtors[i] = dtor; *key = k; HEIMDAL_MUTEX_unlock(&tls_key_defs_lock); return 0; } } if (key_defs->keys_next != NULL) continue; /* Grow the registration array */ /* XXX DRY */ new_key_defs = calloc(1, sizeof(*new_key_defs)); if (new_key_defs == NULL) break; new_key_defs->keys_dtors = calloc(key_defs->keys_num + key_defs->keys_num / 2, sizeof(*new_key_defs->keys_dtors)); if (new_key_defs->keys_dtors == NULL) { free(new_key_defs); break; } new_key_defs->keys_start_idx = key_defs->keys_start_idx + key_defs->keys_num; new_key_defs->keys_num = key_defs->keys_num + key_defs->keys_num / 2; new_key_defs->keys_dtors[i] = dtor; for (i = 1; i < new_key_defs->keys_num; i++) new_key_defs->keys_dtors[i] = NULL; key_defs->keys_next = new_key_defs; ret = 0; break; } HEIMDAL_MUTEX_unlock(&tls_key_defs_lock); return ret; } static void key_lookup(HEIM_PRIV_thread_key key, tls_keys **kd, size_t *dtor_idx, void (**dtor)(void *)) { tls_keys *key_defs; if (kd != NULL) *kd = NULL; if (dtor_idx != NULL) *dtor_idx = 0; if (dtor != NULL) *dtor = NULL; HEIMDAL_MUTEX_lock(&tls_key_defs_lock); key_defs = tls_key_defs; HEIMDAL_MUTEX_unlock(&tls_key_defs_lock); while (key_defs != NULL) { if (key >= key_defs->keys_start_idx && key < key_defs->keys_start_idx + key_defs->keys_num) { if (kd != NULL) *kd = key_defs; if (dtor_idx != NULL) *dtor_idx = key - key_defs->keys_start_idx; if (dtor != NULL) *dtor = key_defs->keys_dtors[key - key_defs->keys_start_idx]; return; } HEIMDAL_MUTEX_lock(&tls_key_defs_lock); key_defs = key_defs->keys_next; HEIMDAL_MUTEX_unlock(&tls_key_defs_lock); assert(key_defs != NULL); assert(key >= key_defs->keys_start_idx); } } int heim_w32_delete_key(HEIM_PRIV_thread_key key) { tls_keys *key_defs; size_t dtor_idx; key_lookup(key, &key_defs, &dtor_idx, NULL); if (key_defs == NULL) return EINVAL; key_defs->keys_dtors[dtor_idx] = DEAD_KEY; return 0; } int heim_w32_setspecific(HEIM_PRIV_thread_key key, void *value) { void **new_values; size_t new_num; void (*dtor)(void *); size_t i; #if !defined(WIN32) (void) pthread_setspecific(pt_key, DEAD_KEY); #endif key_lookup(key, NULL, NULL, &dtor); if (dtor == NULL) return EINVAL; if (key >= values.values_num) { if (values.values_num == 0) { values.values = NULL; new_num = 8; } else { new_num = (values.values_num + values.values_num / 2); } new_values = realloc(values.values, sizeof(void *) * new_num); if (new_values == NULL) return ENOMEM; for (i = values.values_num; i < new_num; i++) new_values[i] = NULL; values.values = new_values; values.values_num = new_num; } assert(key < values.values_num); if (values.values[key] != NULL && dtor != NULL && dtor != DEAD_KEY) dtor(values.values[key]); values.values[key] = value; return 0; } void * heim_w32_getspecific(HEIM_PRIV_thread_key key) { if (key >= values.values_num) return NULL; return values.values[key]; } #else static char dummy; #endif /* HEIM_WIN32_TLS */ heimdal-7.5.0/lib/base/heimqueue.h0000644000175000017500000001502613026237312015075 0ustar niknik/* $NetBSD: queue.h,v 1.38 2004/04/18 14:12:05 lukem Exp $ */ /* $Id$ */ /* * Copyright (c) 1991, 1993 * The Regents of the University of California. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the University nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * * @(#)queue.h 8.5 (Berkeley) 8/20/94 */ #ifndef _HEIM_QUEUE_H_ #define _HEIM_QUEUE_H_ /* * Tail queue definitions. */ #define HEIM_TAILQ_HEAD(name, type) \ struct name { \ struct type *tqh_first; /* first element */ \ struct type **tqh_last; /* addr of last next element */ \ } #define HEIM_TAILQ_HEAD_INITIALIZER(head) \ { NULL, &(head).tqh_first } #define HEIM_TAILQ_ENTRY(type) \ struct { \ struct type *tqe_next; /* next element */ \ struct type **tqe_prev; /* address of previous next element */ \ } /* * Tail queue functions. */ #if defined(_KERNEL) && defined(QUEUEDEBUG) #define QUEUEDEBUG_HEIM_TAILQ_INSERT_HEAD(head, elm, field) \ if ((head)->tqh_first && \ (head)->tqh_first->field.tqe_prev != &(head)->tqh_first) \ panic("HEIM_TAILQ_INSERT_HEAD %p %s:%d", (head), __FILE__, __LINE__); #define QUEUEDEBUG_HEIM_TAILQ_INSERT_TAIL(head, elm, field) \ if (*(head)->tqh_last != NULL) \ panic("HEIM_TAILQ_INSERT_TAIL %p %s:%d", (head), __FILE__, __LINE__); #define QUEUEDEBUG_HEIM_TAILQ_OP(elm, field) \ if ((elm)->field.tqe_next && \ (elm)->field.tqe_next->field.tqe_prev != \ &(elm)->field.tqe_next) \ panic("HEIM_TAILQ_* forw %p %s:%d", (elm), __FILE__, __LINE__);\ if (*(elm)->field.tqe_prev != (elm)) \ panic("HEIM_TAILQ_* back %p %s:%d", (elm), __FILE__, __LINE__); #define QUEUEDEBUG_HEIM_TAILQ_PREREMOVE(head, elm, field) \ if ((elm)->field.tqe_next == NULL && \ (head)->tqh_last != &(elm)->field.tqe_next) \ panic("HEIM_TAILQ_PREREMOVE head %p elm %p %s:%d", \ (head), (elm), __FILE__, __LINE__); #define QUEUEDEBUG_HEIM_TAILQ_POSTREMOVE(elm, field) \ (elm)->field.tqe_next = (void *)1L; \ (elm)->field.tqe_prev = (void *)1L; #else #define QUEUEDEBUG_HEIM_TAILQ_INSERT_HEAD(head, elm, field) #define QUEUEDEBUG_HEIM_TAILQ_INSERT_TAIL(head, elm, field) #define QUEUEDEBUG_HEIM_TAILQ_OP(elm, field) #define QUEUEDEBUG_HEIM_TAILQ_PREREMOVE(head, elm, field) #define QUEUEDEBUG_HEIM_TAILQ_POSTREMOVE(elm, field) #endif #define HEIM_TAILQ_INIT(head) do { \ (head)->tqh_first = NULL; \ (head)->tqh_last = &(head)->tqh_first; \ } while (/*CONSTCOND*/0) #define HEIM_TAILQ_INSERT_HEAD(head, elm, field) do { \ QUEUEDEBUG_HEIM_TAILQ_INSERT_HEAD((head), (elm), field) \ if (((elm)->field.tqe_next = (head)->tqh_first) != NULL) \ (head)->tqh_first->field.tqe_prev = \ &(elm)->field.tqe_next; \ else \ (head)->tqh_last = &(elm)->field.tqe_next; \ (head)->tqh_first = (elm); \ (elm)->field.tqe_prev = &(head)->tqh_first; \ } while (/*CONSTCOND*/0) #define HEIM_TAILQ_INSERT_TAIL(head, elm, field) do { \ QUEUEDEBUG_HEIM_TAILQ_INSERT_TAIL((head), (elm), field) \ (elm)->field.tqe_next = NULL; \ (elm)->field.tqe_prev = (head)->tqh_last; \ *(head)->tqh_last = (elm); \ (head)->tqh_last = &(elm)->field.tqe_next; \ } while (/*CONSTCOND*/0) #define HEIM_TAILQ_INSERT_AFTER(head, listelm, elm, field) do { \ QUEUEDEBUG_HEIM_TAILQ_OP((listelm), field) \ if (((elm)->field.tqe_next = (listelm)->field.tqe_next) != NULL)\ (elm)->field.tqe_next->field.tqe_prev = \ &(elm)->field.tqe_next; \ else \ (head)->tqh_last = &(elm)->field.tqe_next; \ (listelm)->field.tqe_next = (elm); \ (elm)->field.tqe_prev = &(listelm)->field.tqe_next; \ } while (/*CONSTCOND*/0) #define HEIM_TAILQ_INSERT_BEFORE(listelm, elm, field) do { \ QUEUEDEBUG_HEIM_TAILQ_OP((listelm), field) \ (elm)->field.tqe_prev = (listelm)->field.tqe_prev; \ (elm)->field.tqe_next = (listelm); \ *(listelm)->field.tqe_prev = (elm); \ (listelm)->field.tqe_prev = &(elm)->field.tqe_next; \ } while (/*CONSTCOND*/0) #define HEIM_TAILQ_REMOVE(head, elm, field) do { \ QUEUEDEBUG_HEIM_TAILQ_PREREMOVE((head), (elm), field) \ QUEUEDEBUG_HEIM_TAILQ_OP((elm), field) \ if (((elm)->field.tqe_next) != NULL) \ (elm)->field.tqe_next->field.tqe_prev = \ (elm)->field.tqe_prev; \ else \ (head)->tqh_last = (elm)->field.tqe_prev; \ *(elm)->field.tqe_prev = (elm)->field.tqe_next; \ QUEUEDEBUG_HEIM_TAILQ_POSTREMOVE((elm), field); \ } while (/*CONSTCOND*/0) #define HEIM_TAILQ_FOREACH(var, head, field) \ for ((var) = ((head)->tqh_first); \ (var); \ (var) = ((var)->field.tqe_next)) #define HEIM_TAILQ_FOREACH_REVERSE(var, head, headname, field) \ for ((var) = (*(((struct headname *)((head)->tqh_last))->tqh_last)); \ (var); \ (var) = (*(((struct headname *)((var)->field.tqe_prev))->tqh_last))) /* * Tail queue access methods. */ #define HEIM_TAILQ_EMPTY(head) ((head)->tqh_first == NULL) #define HEIM_TAILQ_FIRST(head) ((head)->tqh_first) #define HEIM_TAILQ_NEXT(elm, field) ((elm)->field.tqe_next) #define HEIM_TAILQ_LAST(head, headname) \ (*(((struct headname *)((head)->tqh_last))->tqh_last)) #define HEIM_TAILQ_PREV(elm, headname, field) \ (*(((struct headname *)((elm)->field.tqe_prev))->tqh_last)) #endif /* !_HEIM_QUEUE_H_ */ heimdal-7.5.0/lib/base/db.c0000644000175000017500000012224613026237312013471 0ustar niknik/* * Copyright (c) 2011, Secure Endpoints Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * - Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ /* * This is a pluggable simple DB abstraction, with a simple get/set/ * delete key/value pair interface. * * Plugins may provide any of the following optional features: * * - tables -- multiple attribute/value tables in one DB * - locking * - transactions (i.e., allow any heim_object_t as key or value) * - transcoding of values * * Stackable plugins that provide missing optional features are * possible. * * Any plugin that provides locking will also provide transactions, but * those transactions will not be atomic in the face of failures (a * memory-based rollback log is used). */ #include #include #include #include #include #include #ifdef WIN32 #include #else #include #endif #ifdef HAVE_UNISTD_H #include #endif #include #include "baselocl.h" #include #define HEIM_ENOMEM(ep) \ (((ep) && !*(ep)) ? \ heim_error_get_code((*(ep) = heim_error_create_enomem())) : ENOMEM) #define HEIM_ERROR_HELPER(ep, ec, args) \ (((ep) && !*(ep)) ? \ heim_error_get_code((*(ep) = heim_error_create args)) : (ec)) #define HEIM_ERROR(ep, ec, args) \ (ec == ENOMEM) ? HEIM_ENOMEM(ep) : HEIM_ERROR_HELPER(ep, ec, args); static heim_string_t to_base64(heim_data_t, heim_error_t *); static heim_data_t from_base64(heim_string_t, heim_error_t *); static int open_file(const char *, int , int, int *, heim_error_t *); static int read_json(const char *, heim_object_t *, heim_error_t *); static struct heim_db_type json_dbt; static void db_dealloc(void *ptr); struct heim_type_data db_object = { HEIM_TID_DB, "db-object", NULL, db_dealloc, NULL, NULL, NULL, NULL }; static heim_base_once_t db_plugin_init_once = HEIM_BASE_ONCE_INIT; static heim_dict_t db_plugins; typedef struct db_plugin { heim_string_t name; heim_db_plug_open_f_t openf; heim_db_plug_clone_f_t clonef; heim_db_plug_close_f_t closef; heim_db_plug_lock_f_t lockf; heim_db_plug_unlock_f_t unlockf; heim_db_plug_sync_f_t syncf; heim_db_plug_begin_f_t beginf; heim_db_plug_commit_f_t commitf; heim_db_plug_rollback_f_t rollbackf; heim_db_plug_copy_value_f_t copyf; heim_db_plug_set_value_f_t setf; heim_db_plug_del_key_f_t delf; heim_db_plug_iter_f_t iterf; void *data; } db_plugin_desc, *db_plugin; struct heim_db_data { db_plugin plug; heim_string_t dbtype; heim_string_t dbname; heim_dict_t options; void *db_data; heim_data_t to_release; heim_error_t error; int ret; unsigned int in_transaction:1; unsigned int ro:1; unsigned int ro_tx:1; heim_dict_t set_keys; heim_dict_t del_keys; heim_string_t current_table; }; static int db_do_log_actions(heim_db_t db, heim_error_t *error); static int db_replay_log(heim_db_t db, heim_error_t *error); static HEIMDAL_MUTEX db_type_mutex = HEIMDAL_MUTEX_INITIALIZER; static void db_init_plugins_once(void *arg) { db_plugins = heim_retain(arg); } static void plugin_dealloc(void *arg) { db_plugin plug = arg; heim_release(plug->name); } /** heim_db_register * @brief Registers a DB type for use with heim_db_create(). * * @param dbtype Name of DB type * @param data Private data argument to the dbtype's openf method * @param plugin Structure with DB type methods (function pointers) * * Backends that provide begin/commit/rollback methods must provide ACID * semantics. * * The registered DB type will have ACID semantics for backends that do * not provide begin/commit/rollback methods but do provide lock/unlock * and rdjournal/wrjournal methods (using a replay log journalling * scheme). * * If the registered DB type does not natively provide read vs. write * transaction isolation but does provide a lock method then the DB will * provide read/write transaction isolation. * * @return ENOMEM on failure, else 0. * * @addtogroup heimbase */ int heim_db_register(const char *dbtype, void *data, struct heim_db_type *plugin) { heim_dict_t plugins; heim_string_t s; db_plugin plug, plug2; int ret = 0; if ((plugin->beginf != NULL && plugin->commitf == NULL) || (plugin->beginf != NULL && plugin->rollbackf == NULL) || (plugin->lockf != NULL && plugin->unlockf == NULL) || plugin->copyf == NULL) heim_abort("Invalid DB plugin; make sure methods are paired"); /* Initialize */ plugins = heim_dict_create(11); if (plugins == NULL) return ENOMEM; heim_base_once_f(&db_plugin_init_once, plugins, db_init_plugins_once); heim_release(plugins); heim_assert(db_plugins != NULL, "heim_db plugin table initialized"); s = heim_string_create(dbtype); if (s == NULL) return ENOMEM; plug = heim_alloc(sizeof (*plug), "db_plug", plugin_dealloc); if (plug == NULL) { heim_release(s); return ENOMEM; } plug->name = heim_retain(s); plug->openf = plugin->openf; plug->clonef = plugin->clonef; plug->closef = plugin->closef; plug->lockf = plugin->lockf; plug->unlockf = plugin->unlockf; plug->syncf = plugin->syncf; plug->beginf = plugin->beginf; plug->commitf = plugin->commitf; plug->rollbackf = plugin->rollbackf; plug->copyf = plugin->copyf; plug->setf = plugin->setf; plug->delf = plugin->delf; plug->iterf = plugin->iterf; plug->data = data; HEIMDAL_MUTEX_lock(&db_type_mutex); plug2 = heim_dict_get_value(db_plugins, s); if (plug2 == NULL) ret = heim_dict_set_value(db_plugins, s, plug); HEIMDAL_MUTEX_unlock(&db_type_mutex); heim_release(plug); heim_release(s); return ret; } static void db_dealloc(void *arg) { heim_db_t db = arg; heim_assert(!db->in_transaction, "rollback or commit heim_db_t before releasing it"); if (db->db_data) (void) db->plug->closef(db->db_data, NULL); heim_release(db->to_release); heim_release(db->dbtype); heim_release(db->dbname); heim_release(db->options); heim_release(db->set_keys); heim_release(db->del_keys); heim_release(db->error); } struct dbtype_iter { heim_db_t db; const char *dbname; heim_dict_t options; heim_error_t *error; }; /* * Helper to create a DB handle with the first registered DB type that * can open the given DB. This is useful when the app doesn't know the * DB type a priori. This assumes that DB types can "taste" DBs, either * from the filename extension or from the actual file contents. */ static void dbtype_iter2create_f(heim_object_t dbtype, heim_object_t junk, void *arg) { struct dbtype_iter *iter_ctx = arg; if (iter_ctx->db != NULL) return; iter_ctx->db = heim_db_create(heim_string_get_utf8(dbtype), iter_ctx->dbname, iter_ctx->options, iter_ctx->error); } /** * Open a database of the given dbtype. * * Database type names can be composed of one or more pseudo-DB types * and one concrete DB type joined with a '+' between each. For * example: "transaction+bdb" might be a Berkeley DB with a layer above * that provides transactions. * * Options may be provided via a dict (an associative array). Existing * options include: * * - "create", with any value (create if DB doesn't exist) * - "exclusive", with any value (exclusive create) * - "truncate", with any value (truncate the DB) * - "read-only", with any value (disallow writes) * - "sync", with any value (make transactions durable) * - "journal-name", with a string value naming a journal file name * * @param dbtype Name of DB type * @param dbname Name of DB (likely a file path) * @param options Options dict * @param db Output open DB handle * @param error Output error object * * @return a DB handle * * @addtogroup heimbase */ heim_db_t heim_db_create(const char *dbtype, const char *dbname, heim_dict_t options, heim_error_t *error) { heim_string_t s; char *p; db_plugin plug; heim_db_t db; int ret = 0; if (options == NULL) { options = heim_dict_create(11); if (options == NULL) { if (error) *error = heim_error_create_enomem(); return NULL; } } else { (void) heim_retain(options); } if (db_plugins == NULL) { heim_release(options); return NULL; } if (dbtype == NULL || *dbtype == '\0') { struct dbtype_iter iter_ctx = { NULL, dbname, options, error}; /* Try all dbtypes */ heim_dict_iterate_f(db_plugins, &iter_ctx, dbtype_iter2create_f); heim_release(options); return iter_ctx.db; } else if (strstr(dbtype, "json")) { (void) heim_db_register(dbtype, NULL, &json_dbt); } /* * Allow for dbtypes that are composed from pseudo-dbtypes chained * to a real DB type with '+'. For example a pseudo-dbtype might * add locking, transactions, transcoding of values, ... */ p = strchr(dbtype, '+'); if (p != NULL) s = heim_string_create_with_bytes(dbtype, p - dbtype); else s = heim_string_create(dbtype); if (s == NULL) { heim_release(options); return NULL; } HEIMDAL_MUTEX_lock(&db_type_mutex); plug = heim_dict_get_value(db_plugins, s); HEIMDAL_MUTEX_unlock(&db_type_mutex); heim_release(s); if (plug == NULL) { if (error) *error = heim_error_create(ENOENT, N_("Heimdal DB plugin not found: %s", ""), dbtype); heim_release(options); return NULL; } db = _heim_alloc_object(&db_object, sizeof(*db)); if (db == NULL) { heim_release(options); return NULL; } db->in_transaction = 0; db->ro_tx = 0; db->set_keys = NULL; db->del_keys = NULL; db->plug = plug; db->options = options; ret = plug->openf(plug->data, dbtype, dbname, options, &db->db_data, error); if (ret) { heim_release(db); if (error && *error == NULL) *error = heim_error_create(ENOENT, N_("Heimdal DB could not be opened: %s", ""), dbname); return NULL; } ret = db_replay_log(db, error); if (ret) { heim_release(db); return NULL; } if (plug->clonef == NULL) { db->dbtype = heim_string_create(dbtype); db->dbname = heim_string_create(dbname); if (!db->dbtype || ! db->dbname) { heim_release(db); if (error) *error = heim_error_create_enomem(); return NULL; } } return db; } /** * Clone (duplicate) an open DB handle. * * This is useful for multi-threaded applications. Applications must * synchronize access to any given DB handle. * * Returns EBUSY if there is an open transaction for the input db. * * @param db Open DB handle * @param error Output error object * * @return a DB handle * * @addtogroup heimbase */ heim_db_t heim_db_clone(heim_db_t db, heim_error_t *error) { heim_db_t result; int ret; if (heim_get_tid(db) != HEIM_TID_DB) heim_abort("Expected a database"); if (db->in_transaction) heim_abort("DB handle is busy"); if (db->plug->clonef == NULL) { return heim_db_create(heim_string_get_utf8(db->dbtype), heim_string_get_utf8(db->dbname), db->options, error); } result = _heim_alloc_object(&db_object, sizeof(*result)); if (result == NULL) { if (error) *error = heim_error_create_enomem(); return NULL; } result->set_keys = NULL; result->del_keys = NULL; ret = db->plug->clonef(db->db_data, &result->db_data, error); if (ret) { heim_release(result); if (error && !*error) *error = heim_error_create(ENOENT, N_("Could not re-open DB while cloning", "")); return NULL; } db->db_data = NULL; return result; } /** * Open a transaction on the given db. * * @param db Open DB handle * @param error Output error object * * @return 0 on success, system error otherwise * * @addtogroup heimbase */ int heim_db_begin(heim_db_t db, int read_only, heim_error_t *error) { int ret; if (heim_get_tid(db) != HEIM_TID_DB) return EINVAL; if (db->in_transaction && (read_only || !db->ro_tx || (!read_only && !db->ro_tx))) heim_abort("DB already in transaction"); if (db->plug->setf == NULL || db->plug->delf == NULL) return EINVAL; if (db->plug->beginf) { ret = db->plug->beginf(db->db_data, read_only, error); if (ret) return ret; } else if (!db->in_transaction) { /* Try to emulate transactions */ if (db->plug->lockf == NULL) return EINVAL; /* can't lock? -> no transactions */ /* Assume unlock provides sync/durability */ ret = db->plug->lockf(db->db_data, read_only, error); if (ret) return ret; ret = db_replay_log(db, error); if (ret) { ret = db->plug->unlockf(db->db_data, error); return ret; } db->set_keys = heim_dict_create(11); if (db->set_keys == NULL) return ENOMEM; db->del_keys = heim_dict_create(11); if (db->del_keys == NULL) { heim_release(db->set_keys); db->set_keys = NULL; return ENOMEM; } } else { heim_assert(read_only == 0, "Internal error"); ret = db->plug->lockf(db->db_data, 0, error); if (ret) return ret; } db->in_transaction = 1; db->ro_tx = !!read_only; return 0; } /** * Commit an open transaction on the given db. * * @param db Open DB handle * @param error Output error object * * @return 0 on success, system error otherwise * * @addtogroup heimbase */ int heim_db_commit(heim_db_t db, heim_error_t *error) { int ret, ret2; heim_string_t journal_fname = NULL; if (heim_get_tid(db) != HEIM_TID_DB) return EINVAL; if (!db->in_transaction) return 0; if (db->plug->commitf == NULL && db->plug->lockf == NULL) return EINVAL; if (db->plug->commitf != NULL) { ret = db->plug->commitf(db->db_data, error); if (ret) (void) db->plug->rollbackf(db->db_data, error); db->in_transaction = 0; db->ro_tx = 0; return ret; } if (db->ro_tx) { ret = 0; goto done; } if (db->options == NULL) journal_fname = heim_dict_get_value(db->options, HSTR("journal-filename")); if (journal_fname != NULL) { heim_array_t a; heim_string_t journal_contents; size_t len, bytes; int save_errno; /* Create contents for replay log */ ret = ENOMEM; a = heim_array_create(); if (a == NULL) goto err; ret = heim_array_append_value(a, db->set_keys); if (ret) { heim_release(a); goto err; } ret = heim_array_append_value(a, db->del_keys); if (ret) { heim_release(a); goto err; } journal_contents = heim_json_copy_serialize(a, 0, error); heim_release(a); /* Write replay log */ if (journal_fname != NULL) { int fd; ret = open_file(heim_string_get_utf8(journal_fname), 1, 0, &fd, error); if (ret) { heim_release(journal_contents); goto err; } len = strlen(heim_string_get_utf8(journal_contents)); bytes = write(fd, heim_string_get_utf8(journal_contents), len); save_errno = errno; heim_release(journal_contents); ret = close(fd); if (bytes != len) { /* Truncate replay log */ (void) open_file(heim_string_get_utf8(journal_fname), 1, 0, NULL, error); ret = save_errno; goto err; } if (ret) goto err; } } /* Apply logged actions */ ret = db_do_log_actions(db, error); if (ret) return ret; if (db->plug->syncf != NULL) { /* fsync() or whatever */ ret = db->plug->syncf(db->db_data, error); if (ret) return ret; } /* Truncate replay log and we're done */ if (journal_fname != NULL) { int fd; ret2 = open_file(heim_string_get_utf8(journal_fname), 1, 0, &fd, error); if (ret2 == 0) (void) close(fd); } /* * Clean up; if we failed to remore the replay log that's OK, we'll * handle that again in heim_db_commit() */ done: heim_release(db->set_keys); heim_release(db->del_keys); db->set_keys = NULL; db->del_keys = NULL; db->in_transaction = 0; db->ro_tx = 0; ret2 = db->plug->unlockf(db->db_data, error); if (ret == 0) ret = ret2; return ret; err: return HEIM_ERROR(error, ret, (ret, N_("Error while committing transaction: %s", ""), strerror(ret))); } /** * Rollback an open transaction on the given db. * * @param db Open DB handle * @param error Output error object * * @return 0 on success, system error otherwise * * @addtogroup heimbase */ int heim_db_rollback(heim_db_t db, heim_error_t *error) { int ret = 0; if (heim_get_tid(db) != HEIM_TID_DB) return EINVAL; if (!db->in_transaction) return 0; if (db->plug->rollbackf != NULL) ret = db->plug->rollbackf(db->db_data, error); else if (db->plug->unlockf != NULL) ret = db->plug->unlockf(db->db_data, error); heim_release(db->set_keys); heim_release(db->del_keys); db->set_keys = NULL; db->del_keys = NULL; db->in_transaction = 0; db->ro_tx = 0; return ret; } /** * Get type ID of heim_db_t objects. * * @addtogroup heimbase */ heim_tid_t heim_db_get_type_id(void) { return HEIM_TID_DB; } heim_data_t _heim_db_get_value(heim_db_t db, heim_string_t table, heim_data_t key, heim_error_t *error) { heim_release(db->to_release); db->to_release = heim_db_copy_value(db, table, key, error); return db->to_release; } /** * Lookup a key's value in the DB. * * Returns 0 on success, -1 if the key does not exist in the DB, or a * system error number on failure. * * @param db Open DB handle * @param key Key * @param error Output error object * * @return the value (retained), if there is one for the given key * * @addtogroup heimbase */ heim_data_t heim_db_copy_value(heim_db_t db, heim_string_t table, heim_data_t key, heim_error_t *error) { heim_object_t v; heim_data_t result; if (heim_get_tid(db) != HEIM_TID_DB) return NULL; if (error != NULL) *error = NULL; if (table == NULL) table = HSTR(""); if (db->in_transaction) { heim_string_t key64; key64 = to_base64(key, error); if (key64 == NULL) { if (error) *error = heim_error_create_enomem(); return NULL; } v = heim_path_copy(db->set_keys, error, table, key64, NULL); if (v != NULL) { heim_release(key64); return v; } v = heim_path_copy(db->del_keys, error, table, key64, NULL); /* can't be NULL */ heim_release(key64); if (v != NULL) return NULL; } result = db->plug->copyf(db->db_data, table, key, error); return result; } /** * Set a key's value in the DB. * * @param db Open DB handle * @param key Key * @param value Value (if NULL the key will be deleted, but empty is OK) * @param error Output error object * * @return 0 on success, system error otherwise * * @addtogroup heimbase */ int heim_db_set_value(heim_db_t db, heim_string_t table, heim_data_t key, heim_data_t value, heim_error_t *error) { heim_string_t key64 = NULL; int ret; if (error != NULL) *error = NULL; if (table == NULL) table = HSTR(""); if (value == NULL) /* Use heim_null_t instead of NULL */ return heim_db_delete_key(db, table, key, error); if (heim_get_tid(db) != HEIM_TID_DB) return EINVAL; if (heim_get_tid(key) != HEIM_TID_DATA) return HEIM_ERROR(error, EINVAL, (EINVAL, N_("DB keys must be data", ""))); if (db->plug->setf == NULL) return EBADF; if (!db->in_transaction) { ret = heim_db_begin(db, 0, error); if (ret) goto err; heim_assert(db->in_transaction, "Internal error"); ret = heim_db_set_value(db, table, key, value, error); if (ret) { (void) heim_db_rollback(db, NULL); return ret; } return heim_db_commit(db, error); } /* Transaction emulation */ heim_assert(db->set_keys != NULL, "Internal error"); key64 = to_base64(key, error); if (key64 == NULL) return HEIM_ENOMEM(error); if (db->ro_tx) { ret = heim_db_begin(db, 0, error); if (ret) goto err; } ret = heim_path_create(db->set_keys, 29, value, error, table, key64, NULL); if (ret) goto err; heim_path_delete(db->del_keys, error, table, key64, NULL); heim_release(key64); return 0; err: heim_release(key64); return HEIM_ERROR(error, ret, (ret, N_("Could not set a dict value while while " "setting a DB value", ""))); } /** * Delete a key and its value from the DB * * * @param db Open DB handle * @param key Key * @param error Output error object * * @return 0 on success, system error otherwise * * @addtogroup heimbase */ int heim_db_delete_key(heim_db_t db, heim_string_t table, heim_data_t key, heim_error_t *error) { heim_string_t key64 = NULL; int ret; if (error != NULL) *error = NULL; if (table == NULL) table = HSTR(""); if (heim_get_tid(db) != HEIM_TID_DB) return EINVAL; if (db->plug->delf == NULL) return EBADF; if (!db->in_transaction) { ret = heim_db_begin(db, 0, error); if (ret) goto err; heim_assert(db->in_transaction, "Internal error"); ret = heim_db_delete_key(db, table, key, error); if (ret) { (void) heim_db_rollback(db, NULL); return ret; } return heim_db_commit(db, error); } /* Transaction emulation */ heim_assert(db->set_keys != NULL, "Internal error"); key64 = to_base64(key, error); if (key64 == NULL) return HEIM_ENOMEM(error); if (db->ro_tx) { ret = heim_db_begin(db, 0, error); if (ret) goto err; } ret = heim_path_create(db->del_keys, 29, heim_number_create(1), error, table, key64, NULL); if (ret) goto err; heim_path_delete(db->set_keys, error, table, key64, NULL); heim_release(key64); return 0; err: heim_release(key64); return HEIM_ERROR(error, ret, (ret, N_("Could not set a dict value while while " "deleting a DB value", ""))); } /** * Iterate a callback function over keys and values from a DB. * * @param db Open DB handle * @param iter_data Callback function's private data * @param iter_f Callback function, called once per-key/value pair * @param error Output error object * * @addtogroup heimbase */ void heim_db_iterate_f(heim_db_t db, heim_string_t table, void *iter_data, heim_db_iterator_f_t iter_f, heim_error_t *error) { if (error != NULL) *error = NULL; if (heim_get_tid(db) != HEIM_TID_DB) return; if (!db->in_transaction) db->plug->iterf(db->db_data, table, iter_data, iter_f, error); } static void db_replay_log_table_set_keys_iter(heim_object_t key, heim_object_t value, void *arg) { heim_db_t db = arg; heim_data_t k, v; if (db->ret) return; k = from_base64((heim_string_t)key, &db->error); if (k == NULL) { db->ret = ENOMEM; return; } v = (heim_data_t)value; db->ret = db->plug->setf(db->db_data, db->current_table, k, v, &db->error); heim_release(k); } static void db_replay_log_table_del_keys_iter(heim_object_t key, heim_object_t value, void *arg) { heim_db_t db = arg; heim_data_t k; if (db->ret) { db->ret = ENOMEM; return; } k = from_base64((heim_string_t)key, &db->error); if (k == NULL) return; db->ret = db->plug->delf(db->db_data, db->current_table, k, &db->error); heim_release(k); } static void db_replay_log_set_keys_iter(heim_object_t table, heim_object_t table_dict, void *arg) { heim_db_t db = arg; if (db->ret) return; db->current_table = table; heim_dict_iterate_f(table_dict, db, db_replay_log_table_set_keys_iter); } static void db_replay_log_del_keys_iter(heim_object_t table, heim_object_t table_dict, void *arg) { heim_db_t db = arg; if (db->ret) return; db->current_table = table; heim_dict_iterate_f(table_dict, db, db_replay_log_table_del_keys_iter); } static int db_do_log_actions(heim_db_t db, heim_error_t *error) { int ret; if (error) *error = NULL; db->ret = 0; db->error = NULL; if (db->set_keys != NULL) heim_dict_iterate_f(db->set_keys, db, db_replay_log_set_keys_iter); if (db->del_keys != NULL) heim_dict_iterate_f(db->del_keys, db, db_replay_log_del_keys_iter); ret = db->ret; db->ret = 0; if (error && db->error) { *error = db->error; db->error = NULL; } else { heim_release(db->error); db->error = NULL; } return ret; } static int db_replay_log(heim_db_t db, heim_error_t *error) { int ret; heim_string_t journal_fname = NULL; heim_object_t journal; size_t len; heim_assert(!db->in_transaction, "DB transaction not open"); heim_assert(db->set_keys == NULL && db->set_keys == NULL, "DB transaction not open"); if (error) *error = NULL; if (db->options == NULL) return 0; journal_fname = heim_dict_get_value(db->options, HSTR("journal-filename")); if (journal_fname == NULL) return 0; ret = read_json(heim_string_get_utf8(journal_fname), &journal, error); if (ret == ENOENT) { heim_release(journal_fname); return 0; } if (ret == 0 && journal == NULL) { heim_release(journal_fname); return 0; } if (ret != 0) { heim_release(journal_fname); return ret; } if (heim_get_tid(journal) != HEIM_TID_ARRAY) { heim_release(journal_fname); return HEIM_ERROR(error, EINVAL, (ret, N_("Invalid journal contents; delete journal", ""))); } len = heim_array_get_length(journal); if (len > 0) db->set_keys = heim_array_get_value(journal, 0); if (len > 1) db->del_keys = heim_array_get_value(journal, 1); ret = db_do_log_actions(db, error); if (ret) { heim_release(journal_fname); return ret; } /* Truncate replay log and we're done */ ret = open_file(heim_string_get_utf8(journal_fname), 1, 0, NULL, error); heim_release(journal_fname); if (ret) return ret; heim_release(db->set_keys); heim_release(db->del_keys); db->set_keys = NULL; db->del_keys = NULL; return 0; } static heim_string_t to_base64(heim_data_t data, heim_error_t *error) { char *b64 = NULL; heim_string_t s = NULL; const heim_octet_string *d; int ret; d = heim_data_get_data(data); ret = rk_base64_encode(d->data, d->length, &b64); if (ret < 0 || b64 == NULL) goto enomem; s = heim_string_ref_create(b64, free); if (s == NULL) goto enomem; return s; enomem: free(b64); if (error) *error = heim_error_create_enomem(); return NULL; } static heim_data_t from_base64(heim_string_t s, heim_error_t *error) { void *buf; size_t len; heim_data_t d; buf = malloc(strlen(heim_string_get_utf8(s))); if (buf == NULL) goto enomem; len = rk_base64_decode(heim_string_get_utf8(s), buf); d = heim_data_ref_create(buf, len, free); if (d == NULL) goto enomem; return d; enomem: free(buf); if (error) *error = heim_error_create_enomem(); return NULL; } static int open_file(const char *dbname, int for_write, int excl, int *fd_out, heim_error_t *error) { #ifdef WIN32 HANDLE hFile; int ret = 0; if (fd_out) *fd_out = -1; if (for_write) hFile = CreateFile(dbname, GENERIC_WRITE | GENERIC_READ, 0, NULL, /* we'll close as soon as we read */ CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL); else hFile = CreateFile(dbname, GENERIC_READ, FILE_SHARE_READ, NULL, /* we'll close as soon as we read */ OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); if (hFile == INVALID_HANDLE_VALUE) { ret = GetLastError(); _set_errno(ret); /* CreateFile() does not set errno */ goto err; } if (fd_out == NULL) { (void) CloseHandle(hFile); return 0; } *fd_out = _open_osfhandle((intptr_t) hFile, 0); if (*fd_out < 0) { ret = errno; (void) CloseHandle(hFile); goto err; } /* No need to lock given share deny mode */ return 0; err: if (error != NULL) { char *s = NULL; FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ALLOCATE_BUFFER, 0, ret, 0, (LPTSTR) &s, 0, NULL); *error = heim_error_create(ret, N_("Could not open JSON file %s: %s", ""), dbname, s ? s : ""); LocalFree(s); } return ret; #else int ret = 0; int fd; if (fd_out) *fd_out = -1; if (for_write && excl) fd = open(dbname, O_CREAT | O_EXCL | O_WRONLY, 0600); else if (for_write) fd = open(dbname, O_CREAT | O_TRUNC | O_WRONLY, 0600); else fd = open(dbname, O_RDONLY); if (fd < 0) { if (error != NULL) *error = heim_error_create(ret, N_("Could not open JSON file %s: %s", ""), dbname, strerror(errno)); return errno; } if (fd_out == NULL) { (void) close(fd); return 0; } ret = flock(fd, for_write ? LOCK_EX : LOCK_SH); if (ret == -1) { /* Note that we if O_EXCL we're leaving the [lock] file around */ (void) close(fd); return HEIM_ERROR(error, errno, (errno, N_("Could not lock JSON file %s: %s", ""), dbname, strerror(errno))); } *fd_out = fd; return 0; #endif } static int read_json(const char *dbname, heim_object_t *out, heim_error_t *error) { struct stat st; char *str = NULL; int ret; int fd = -1; ssize_t bytes; *out = NULL; ret = open_file(dbname, 0, 0, &fd, error); if (ret) return ret; ret = fstat(fd, &st); if (ret == -1) { (void) close(fd); return HEIM_ERROR(error, errno, (ret, N_("Could not stat JSON DB %s: %s", ""), dbname, strerror(errno))); } if (st.st_size == 0) { (void) close(fd); return 0; } str = malloc(st.st_size + 1); if (str == NULL) { (void) close(fd); return HEIM_ENOMEM(error); } bytes = read(fd, str, st.st_size); (void) close(fd); if (bytes != st.st_size) { free(str); if (bytes >= 0) errno = EINVAL; /* ?? */ return HEIM_ERROR(error, errno, (ret, N_("Could not read JSON DB %s: %s", ""), dbname, strerror(errno))); } str[st.st_size] = '\0'; *out = heim_json_create(str, 10, 0, error); free(str); if (*out == NULL) return (error && *error) ? heim_error_get_code(*error) : EINVAL; return 0; } typedef struct json_db { heim_dict_t dict; heim_string_t dbname; heim_string_t bkpname; int fd; time_t last_read_time; unsigned int read_only:1; unsigned int locked:1; unsigned int locked_needs_unlink:1; } *json_db_t; static int json_db_open(void *plug, const char *dbtype, const char *dbname, heim_dict_t options, void **db, heim_error_t *error) { json_db_t jsondb; heim_dict_t contents = NULL; heim_string_t dbname_s = NULL; heim_string_t bkpname_s = NULL; if (error) *error = NULL; if (dbtype && *dbtype && strcmp(dbtype, "json")) return HEIM_ERROR(error, EINVAL, (EINVAL, N_("Wrong DB type", ""))); if (dbname && *dbname && strcmp(dbname, "MEMORY") != 0) { char *ext = strrchr(dbname, '.'); char *bkpname; size_t len; int ret; if (ext == NULL || strcmp(ext, ".json") != 0) return HEIM_ERROR(error, EINVAL, (EINVAL, N_("JSON DB files must end in .json", ""))); if (options) { heim_object_t vc, ve, vt; vc = heim_dict_get_value(options, HSTR("create")); ve = heim_dict_get_value(options, HSTR("exclusive")); vt = heim_dict_get_value(options, HSTR("truncate")); if (vc && vt) { ret = open_file(dbname, 1, ve ? 1 : 0, NULL, error); if (ret) return ret; } else if (vc || ve || vt) { return HEIM_ERROR(error, EINVAL, (EINVAL, N_("Invalid JSON DB open options", ""))); } /* * We don't want cloned handles to truncate the DB, eh? * * We should really just create a copy of the options dict * rather than modify the caller's! But for that it'd be * nicer to have copy utilities in heimbase, something like * this: * * heim_object_t heim_copy(heim_object_t src, int depth, * heim_error_t *error); * * so that options = heim_copy(options, 1); means copy the * dict but nothing else (whereas depth == 0 would mean * heim_retain(), and depth > 1 would be copy that many * levels). */ heim_dict_delete_key(options, HSTR("create")); heim_dict_delete_key(options, HSTR("exclusive")); heim_dict_delete_key(options, HSTR("truncate")); } dbname_s = heim_string_create(dbname); if (dbname_s == NULL) return HEIM_ENOMEM(error); len = snprintf(NULL, 0, "%s~", dbname); bkpname = malloc(len + 2); if (bkpname == NULL) { heim_release(dbname_s); return HEIM_ENOMEM(error); } (void) snprintf(bkpname, len + 1, "%s~", dbname); bkpname_s = heim_string_create(bkpname); free(bkpname); if (bkpname_s == NULL) { heim_release(dbname_s); return HEIM_ENOMEM(error); } ret = read_json(dbname, (heim_object_t *)&contents, error); if (ret) { heim_release(bkpname_s); heim_release(dbname_s); return ret; } if (contents != NULL && heim_get_tid(contents) != HEIM_TID_DICT) { heim_release(bkpname_s); heim_release(dbname_s); return HEIM_ERROR(error, EINVAL, (EINVAL, N_("JSON DB contents not valid JSON", ""))); } } jsondb = heim_alloc(sizeof (*jsondb), "json_db", NULL); if (jsondb == NULL) { heim_release(contents); heim_release(dbname_s); heim_release(bkpname_s); return ENOMEM; } jsondb->last_read_time = time(NULL); jsondb->fd = -1; jsondb->dbname = dbname_s; jsondb->bkpname = bkpname_s; jsondb->read_only = 0; if (contents != NULL) jsondb->dict = contents; else { jsondb->dict = heim_dict_create(29); if (jsondb->dict == NULL) { heim_release(jsondb); return ENOMEM; } } *db = jsondb; return 0; } static int json_db_close(void *db, heim_error_t *error) { json_db_t jsondb = db; if (error) *error = NULL; if (jsondb->fd > -1) (void) close(jsondb->fd); jsondb->fd = -1; heim_release(jsondb->dbname); heim_release(jsondb->bkpname); heim_release(jsondb->dict); heim_release(jsondb); return 0; } static int json_db_lock(void *db, int read_only, heim_error_t *error) { json_db_t jsondb = db; int ret; heim_assert(jsondb->fd == -1 || (jsondb->read_only && !read_only), "DB locks are not recursive"); jsondb->read_only = read_only ? 1 : 0; if (jsondb->fd > -1) return 0; ret = open_file(heim_string_get_utf8(jsondb->bkpname), 1, 1, &jsondb->fd, error); if (ret == 0) { jsondb->locked_needs_unlink = 1; jsondb->locked = 1; } return ret; } static int json_db_unlock(void *db, heim_error_t *error) { json_db_t jsondb = db; int ret = 0; heim_assert(jsondb->locked, "DB not locked when unlock attempted"); if (jsondb->fd > -1) ret = close(jsondb->fd); jsondb->fd = -1; jsondb->read_only = 0; jsondb->locked = 0; if (jsondb->locked_needs_unlink) unlink(heim_string_get_utf8(jsondb->bkpname)); jsondb->locked_needs_unlink = 0; return ret; } static int json_db_sync(void *db, heim_error_t *error) { json_db_t jsondb = db; size_t len, bytes; heim_error_t e; heim_string_t json; const char *json_text = NULL; int ret = 0; int fd = -1; #ifdef WIN32 int tries = 3; #endif heim_assert(jsondb->fd > -1, "DB not locked when sync attempted"); json = heim_json_copy_serialize(jsondb->dict, 0, &e); if (json == NULL) { if (error) *error = e; else heim_release(e); return heim_error_get_code(e); } json_text = heim_string_get_utf8(json); len = strlen(json_text); errno = 0; #ifdef WIN32 while (tries--) { ret = open_file(heim_string_get_utf8(jsondb->dbname), 1, 0, &fd, error); if (ret == 0) break; sleep(1); } if (ret) { heim_release(json); return ret; } #else fd = jsondb->fd; #endif /* WIN32 */ bytes = write(fd, json_text, len); heim_release(json); if (bytes != len) return errno ? errno : EIO; ret = fsync(fd); if (ret) return ret; #ifdef WIN32 ret = close(fd); if (ret) return GetLastError(); #else ret = rename(heim_string_get_utf8(jsondb->bkpname), heim_string_get_utf8(jsondb->dbname)); if (ret == 0) { jsondb->locked_needs_unlink = 0; return 0; } #endif /* WIN32 */ return errno; } static heim_data_t json_db_copy_value(void *db, heim_string_t table, heim_data_t key, heim_error_t *error) { json_db_t jsondb = db; heim_string_t key_string; const heim_octet_string *key_data = heim_data_get_data(key); struct stat st; heim_data_t result; if (error) *error = NULL; if (strnlen(key_data->data, key_data->length) != key_data->length) { HEIM_ERROR(error, EINVAL, (EINVAL, N_("JSON DB requires keys that are actually " "strings", ""))); return NULL; } if (stat(heim_string_get_utf8(jsondb->dbname), &st) == -1) { HEIM_ERROR(error, errno, (errno, N_("Could not stat JSON DB file", ""))); return NULL; } if (st.st_mtime > jsondb->last_read_time || st.st_ctime > jsondb->last_read_time) { heim_dict_t contents = NULL; int ret; /* Ignore file is gone (ENOENT) */ ret = read_json(heim_string_get_utf8(jsondb->dbname), (heim_object_t *)&contents, error); if (ret) return NULL; if (contents == NULL) contents = heim_dict_create(29); heim_release(jsondb->dict); jsondb->dict = contents; jsondb->last_read_time = time(NULL); } key_string = heim_string_create_with_bytes(key_data->data, key_data->length); if (key_string == NULL) { (void) HEIM_ENOMEM(error); return NULL; } result = heim_path_copy(jsondb->dict, error, table, key_string, NULL); heim_release(key_string); return result; } static int json_db_set_value(void *db, heim_string_t table, heim_data_t key, heim_data_t value, heim_error_t *error) { json_db_t jsondb = db; heim_string_t key_string; const heim_octet_string *key_data = heim_data_get_data(key); int ret; if (error) *error = NULL; if (strnlen(key_data->data, key_data->length) != key_data->length) return HEIM_ERROR(error, EINVAL, (EINVAL, N_("JSON DB requires keys that are actually strings", ""))); key_string = heim_string_create_with_bytes(key_data->data, key_data->length); if (key_string == NULL) return HEIM_ENOMEM(error); if (table == NULL) table = HSTR(""); ret = heim_path_create(jsondb->dict, 29, value, error, table, key_string, NULL); heim_release(key_string); return ret; } static int json_db_del_key(void *db, heim_string_t table, heim_data_t key, heim_error_t *error) { json_db_t jsondb = db; heim_string_t key_string; const heim_octet_string *key_data = heim_data_get_data(key); if (error) *error = NULL; if (strnlen(key_data->data, key_data->length) != key_data->length) return HEIM_ERROR(error, EINVAL, (EINVAL, N_("JSON DB requires keys that are actually strings", ""))); key_string = heim_string_create_with_bytes(key_data->data, key_data->length); if (key_string == NULL) return HEIM_ENOMEM(error); if (table == NULL) table = HSTR(""); heim_path_delete(jsondb->dict, error, table, key_string, NULL); heim_release(key_string); return 0; } struct json_db_iter_ctx { heim_db_iterator_f_t iter_f; void *iter_ctx; }; static void json_db_iter_f(heim_object_t key, heim_object_t value, void *arg) { struct json_db_iter_ctx *ctx = arg; const char *key_string; heim_data_t key_data; key_string = heim_string_get_utf8((heim_string_t)key); key_data = heim_data_ref_create(key_string, strlen(key_string), NULL); ctx->iter_f(key_data, (heim_object_t)value, ctx->iter_ctx); heim_release(key_data); } static void json_db_iter(void *db, heim_string_t table, void *iter_data, heim_db_iterator_f_t iter_f, heim_error_t *error) { json_db_t jsondb = db; struct json_db_iter_ctx ctx; heim_dict_t table_dict; if (error) *error = NULL; if (table == NULL) table = HSTR(""); table_dict = heim_dict_get_value(jsondb->dict, table); if (table_dict == NULL) return; ctx.iter_ctx = iter_data; ctx.iter_f = iter_f; heim_dict_iterate_f(table_dict, &ctx, json_db_iter_f); } static struct heim_db_type json_dbt = { 1, json_db_open, NULL, json_db_close, json_db_lock, json_db_unlock, json_db_sync, NULL, NULL, NULL, json_db_copy_value, json_db_set_value, json_db_del_key, json_db_iter }; heimdal-7.5.0/lib/base/baselocl.h0000644000175000017500000001164713026237312014677 0ustar niknik/* * Copyright (c) 2010 - 2011 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Portions Copyright (c) 2010 Apple Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "config.h" #include #ifdef HAVE_SYS_SELECT_H #include #endif #define HEIMDAL_TEXTDOMAIN "heimdal_krb5" #ifdef LIBINTL #include #define N_(x,y) dgettext(HEIMDAL_TEXTDOMAIN, x) #else #define N_(x,y) (x) #define bindtextdomain(package, localedir) #endif #include "heimqueue.h" #include "heim_threads.h" #include "heimbase.h" #include "heimbasepriv.h" #ifdef HAVE_DISPATCH_DISPATCH_H #include #endif #if defined(__GNUC__) && defined(HAVE___SYNC_ADD_AND_FETCH) #define heim_base_atomic_inc(x) __sync_add_and_fetch((x), 1) #define heim_base_atomic_dec(x) __sync_sub_and_fetch((x), 1) #define heim_base_atomic_type unsigned int #define heim_base_atomic_max UINT_MAX #ifndef __has_builtin #define __has_builtin(x) 0 #endif #if __has_builtin(__sync_swap) #define heim_base_exchange_pointer(t,v) __sync_swap((t), (v)) #else #define heim_base_exchange_pointer(t,v) __sync_lock_test_and_set((t), (v)) #endif #elif defined(__sun) #include #define heim_base_atomic_inc(x) atomic_inc_uint_nv((volatile uint_t *)(x)) #define heim_base_atomic_dec(x) atomic_dec_uint_nv((volatile uint_t *)(x)) #define heim_base_atomic_type uint_t #define heim_base_atomic_max UINT_MAX #define heim_base_exchange_pointer(t,v) atomic_swap_ptr((volatile void *)(t), (void *)(v)) #elif defined(_AIX) #include #define heim_base_atomic_inc(x) (fetch_and_add((atomic_p)(x)) + 1) #define heim_base_atomic_dec(x) (fetch_and_add((atomic_p)(x)) - 1) #define heim_base_atomic_type unsigned int #define heim_base_atomic_max UINT_MAX static inline void * heim_base_exchange_pointer(void *p, void *newval) { void *val = *(void **)p; while (!compare_and_swaplp((atomic_l)p, (long *)&val, (long)newval)) ; return val; } #elif defined(_WIN32) #define heim_base_atomic_inc(x) InterlockedIncrement(x) #define heim_base_atomic_dec(x) InterlockedDecrement(x) #define heim_base_atomic_type LONG #define heim_base_atomic_max MAXLONG #define heim_base_exchange_pointer(t,v) InterlockedExchangePointer((t),(v)) #else #define HEIM_BASE_NEED_ATOMIC_MUTEX 1 extern HEIMDAL_MUTEX _heim_base_mutex; #define heim_base_atomic_type unsigned int static inline heim_base_atomic_type heim_base_atomic_inc(heim_base_atomic_type *x) { heim_base_atomic_type t; HEIMDAL_MUTEX_lock(&_heim_base_mutex); t = ++(*x); HEIMDAL_MUTEX_unlock(&_heim_base_mutex); return t; } static inline heim_base_atomic_type heim_base_atomic_dec(heim_base_atomic_type *x) { heim_base_atomic_type t; HEIMDAL_MUTEX_lock(&_heim_base_mutex); t = --(*x); HEIMDAL_MUTEX_unlock(&_heim_base_mutex); return t; } #define heim_base_atomic_max UINT_MAX #endif /* tagged strings/object/XXX */ #define heim_base_is_tagged(x) (((uintptr_t)(x)) & 0x3) #define heim_base_is_tagged_object(x) ((((uintptr_t)(x)) & 0x3) == 1) #define heim_base_make_tagged_object(x, tid) \ ((heim_object_t)((((uintptr_t)(x)) << 5) | ((tid) << 2) | 0x1)) #define heim_base_tagged_object_tid(x) ((((uintptr_t)(x)) & 0x1f) >> 2) #define heim_base_tagged_object_value(x) (((uintptr_t)(x)) >> 5) /* * */ #undef HEIMDAL_NORETURN_ATTRIBUTE #define HEIMDAL_NORETURN_ATTRIBUTE #undef HEIMDAL_PRINTF_ATTRIBUTE #define HEIMDAL_PRINTF_ATTRIBUTE(x) heimdal-7.5.0/lib/base/bool.c0000644000175000017500000000402113026237312014025 0ustar niknik/* * Copyright (c) 2010 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Portions Copyright (c) 2010 Apple Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "baselocl.h" struct heim_type_data _heim_bool_object = { HEIM_TID_BOOL, "bool-object", NULL, NULL, NULL, NULL, NULL, NULL }; heim_bool_t heim_bool_create(int val) { return heim_base_make_tagged_object(!!val, HEIM_TID_BOOL); } int heim_bool_val(heim_bool_t ptr) { return heim_base_tagged_object_value(ptr); } heimdal-7.5.0/lib/base/data.c0000644000175000017500000001031313026237312014004 0ustar niknik/* * Copyright (c) 2011 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "baselocl.h" #include static void data_dealloc(void *ptr) { heim_data_t d = ptr; heim_octet_string *os = (heim_octet_string *)d; heim_data_free_f_t *deallocp; heim_data_free_f_t dealloc; if (os->data == NULL) return; /* Possible string ref */ deallocp = _heim_get_isaextra(os, 0); dealloc = *deallocp; if (dealloc != NULL) dealloc(os->data); } static int data_cmp(void *a, void *b) { heim_octet_string *osa = a, *osb = b; if (osa->length != osb->length) return osa->length - osb->length; return memcmp(osa->data, osb->data, osa->length); } static unsigned long data_hash(void *ptr) { heim_octet_string *os = ptr; const unsigned char *s = os->data; if (os->length < 4) return os->length; return s[0] | (s[1] << 8) | (s[os->length - 2] << 16) | (s[os->length - 1] << 24); } struct heim_type_data _heim_data_object = { HEIM_TID_DATA, "data-object", NULL, data_dealloc, NULL, data_cmp, data_hash, NULL }; /** * Create a data object * * @param string the string to create, must be an utf8 string * * @return string object */ heim_data_t heim_data_create(const void *data, size_t length) { heim_octet_string *os; os = _heim_alloc_object(&_heim_data_object, sizeof(*os) + length); if (os) { os->data = (uint8_t *)os + sizeof(*os); os->length = length; memcpy(os->data, data, length); } return (heim_data_t)os; } heim_data_t heim_data_ref_create(const void *data, size_t length, heim_data_free_f_t dealloc) { heim_octet_string *os; heim_data_free_f_t *deallocp; os = _heim_alloc_object(&_heim_data_object, sizeof(*os) + length); if (os) { os->data = (void *)data; os->length = length; deallocp = _heim_get_isaextra(os, 0); *deallocp = dealloc; } return (heim_data_t)os; } /** * Return the type ID of data objects * * @return type id of data objects */ heim_tid_t heim_data_get_type_id(void) { return HEIM_TID_DATA; } /** * Get the data value of the content. * * @param data the data object to get the value from * * @return a heim_octet_string */ const heim_octet_string * heim_data_get_data(heim_data_t data) { /* Note that this works for data and data_ref objects */ return (const heim_octet_string *)data; } const void * heim_data_get_ptr(heim_data_t data) { /* Note that this works for data and data_ref objects */ return ((const heim_octet_string *)data)->data; } size_t heim_data_get_length(heim_data_t data) { /* Note that this works for data and data_ref objects */ return ((const heim_octet_string *)data)->length; } heimdal-7.5.0/lib/base/null.c0000644000175000017500000000366313026237312014057 0ustar niknik/* * Copyright (c) 2010 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Portions Copyright (c) 2010 Apple Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "baselocl.h" struct heim_type_data _heim_null_object = { HEIM_TID_NULL, "null-object", NULL, NULL, NULL, NULL, NULL, NULL }; heim_null_t heim_null_create(void) { return heim_base_make_tagged_object(0, HEIM_TID_NULL); } heimdal-7.5.0/lib/base/bsearch.c0000644000175000017500000006147713026237312014523 0ustar niknik/* * Copyright (c) 2011, Secure Endpoints Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * - Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. * */ #include "baselocl.h" #include #include #ifdef HAVE_IO_H #include #endif #ifdef HAVE_UNISTD_H #include #endif #include #include #include #include #include #ifdef HAVE_STRINGS_H #include #endif #include #include /* * This file contains functions for binary searching flat text in memory * and in text files where each line is a [variable length] record. * Each record has a key and an optional value separated from the key by * unquoted whitespace. Whitespace in the key, and leading whitespace * for the value, can be quoted with backslashes (but CR and LF must be * quoted in such a way that they don't appear in the quoted result). * * Binary searching a tree are normally a dead simple algorithm. It * turns out that binary searching flat text with *variable* length * records is... tricky. There's no indexes to record beginning bytes, * thus any index selected during the search is likely to fall in the * middle of a record. When deciding to search a left sub-tree one * might fail to find the last record in that sub-tree on account of the * right boundary falling in the middle of it -- the chosen solution to * this makes left sub-tree searches slightly less efficient than right * sub-tree searches. * * If binary searching flat text in memory is tricky, using block-wise * I/O instead is trickier! But it's necessary in order to support * large files (which we either can't or wouldn't want to read or map * into memory). Each block we read has to be large enough that the * largest record can fit in it. And each block might start and/or end * in the middle of a record. Here it is the right sub-tree searches * that are less efficient than left sub-tree searches. * * bsearch_common() contains the common text block binary search code. * * _bsearch_text() is the interface for searching in-core text. * _bsearch_file() is the interface for block-wise searching files. */ struct bsearch_file_handle { int fd; /* file descriptor */ char *cache; /* cache bytes */ char *page; /* one double-size page worth of bytes */ size_t file_sz; /* file size */ size_t cache_sz; /* cache size */ size_t page_sz; /* page size */ }; /* Find a new-line */ static const char * find_line(const char *buf, size_t i, size_t right) { if (i == 0) return &buf[i]; for (; i < right; i++) { if (buf[i] == '\n') { if ((i + 1) < right) return &buf[i + 1]; return NULL; } } return NULL; } /* * Common routine for binary searching text in core. * * Perform a binary search of a char array containing a block from a * text file where each line is a record (LF and CRLF supported). Each * record consists of a key followed by an optional value separated from * the key by whitespace. Whitespace can be quoted with backslashes. * It's the caller's responsibility to encode/decode keys/values if * quoting is desired; newlines should be encoded such that a newline * does not appear in the result. * * All output arguments are optional. * * Returns 0 if key is found, -1 if not found, or an error code such as * ENOMEM in case of error. * * Inputs: * * @buf String to search * @sz Size of string to search * @key Key string to search for * @buf_is_start True if the buffer starts with a record, false if it * starts in the middle of a record or if the caller * doesn't know. * * Outputs: * * @value Location to store a copy of the value (caller must free) * @location Record location if found else the location where the * record should be inserted (index into @buf) * @cmp Set to less than or greater than 0 to indicate that a * key not found would have fit in an earlier or later * part of a file. Callers should use this to decide * whether to read a block to the left or to the right and * search that. * @loops Location to store a count of bisections required for * search (useful for confirming logarithmic performance) */ static int bsearch_common(const char *buf, size_t sz, const char *key, int buf_is_start, char **value, size_t *location, int *cmp, size_t *loops) { const char *linep; size_t key_start, key_len; /* key string in buf */ size_t val_start, val_len; /* value string in buf */ int key_cmp = -1; size_t k; size_t l; /* left side of buffer for binary search */ size_t r; /* right side of buffer for binary search */ size_t rmax; /* right side of buffer for binary search */ size_t i; /* index into buffer, typically in the middle of l and r */ size_t loop_count = 0; int ret = -1; if (value) *value = NULL; if (cmp) *cmp = 0; if (loops) *loops = 0; /* Binary search; file should be sorted */ for (l = 0, r = rmax = sz, i = sz >> 1; i >= l && i < rmax; loop_count++) { heim_assert(i < sz, "invalid aname2lname db index"); /* buf[i] is likely in the middle of a line; find the next line */ linep = find_line(buf, i, rmax); k = linep ? linep - buf : i; if (linep == NULL || k >= rmax) { /* * No new line found to the right; search to the left then * but don't change rmax (this isn't optimal, but it's * simple). */ if (i == l) break; r = i; i = l + ((r - l) >> 1); continue; } i = k; heim_assert(i >= l && i < rmax, "invalid aname2lname db index"); /* Got a line; check it */ /* Search for and split on unquoted whitespace */ val_start = 0; for (key_start = i, key_len = 0, val_len = 0, k = i; k < rmax; k++) { if (buf[k] == '\\') { k++; continue; } if (buf[k] == '\r' || buf[k] == '\n') { /* We now know where the key ends, and there's no value */ key_len = k - i; break; } if (!isspace((unsigned char)buf[k])) continue; while (k < rmax && isspace((unsigned char)buf[k])) { key_len = k - i; k++; } if (k < rmax) val_start = k; /* Find end of value */ for (; k < rmax && buf[k] != '\0'; k++) { if (buf[k] == '\r' || buf[k] == '\n') { val_len = k - val_start; break; } } break; } /* * The following logic is for dealing with partial buffers, * which we use for block-wise binary searches of large files */ if (key_start == 0 && !buf_is_start) { /* * We're at the beginning of a block that might have started * in the middle of a record whose "key" might well compare * as greater than the key we're looking for, so we don't * bother comparing -- we know key_cmp must be -1 here. */ key_cmp = -1; break; } if ((val_len && buf[val_start + val_len] != '\n') || (!val_len && buf[key_start + key_len] != '\n')) { /* * We're at the end of a block that ends in the middle of a * record whose "key" might well compare as less than the * key we're looking for, so we don't bother comparing -- we * know key_cmp must be >= 0 but we can't tell. Our caller * will end up reading a double-size block to handle this. */ key_cmp = 1; break; } key_cmp = strncmp(key, &buf[key_start], key_len); if (key_cmp == 0 && strlen(key) != key_len) key_cmp = 1; if (key_cmp < 0) { /* search left */ r = rmax = (linep - buf); i = l + ((r - l) >> 1); if (location) *location = key_start; } else if (key_cmp > 0) { /* search right */ if (l == i) break; /* not found */ l = i; i = l + ((r - l) >> 1); if (location) *location = val_start + val_len; } else { /* match! */ if (location) *location = key_start; ret = 0; if (val_len && value) { /* Avoid strndup() so we don't need libroken here yet */ *value = malloc(val_len + 1); if (!*value) ret = errno; (void) memcpy(*value, &buf[val_start], val_len); (*value)[val_len] = '\0'; } break; } } if (cmp) *cmp = key_cmp; if (loops) *loops = loop_count; return ret; } /* * Binary search a char array containing sorted text records separated * by new-lines (or CRLF). Each record consists of a key and an * optional value following the key, separated from the key by unquoted * whitespace. * * All output arguments are optional. * * Returns 0 if key is found, -1 if not found, or an error code such as * ENOMEM in case of error. * * Inputs: * * @buf Char array pointer * @buf_sz Size of buf * @key Key to search for * * Outputs: * * @value Location where to put the value, if any (caller must free) * @location Record location if found else the location where the record * should be inserted (index into @buf) * @loops Location where to put a number of loops (or comparisons) * needed for the search (useful for benchmarking) */ int _bsearch_text(const char *buf, size_t buf_sz, const char *key, char **value, size_t *location, size_t *loops) { return bsearch_common(buf, buf_sz, key, 1, value, location, NULL, loops); } #define MAX_BLOCK_SIZE (1024 * 1024) #define DEFAULT_MAX_FILE_SIZE (1024 * 1024) /* * Open a file for binary searching. The file will be read in entirely * if it is smaller than @max_sz, else a cache of @max_sz bytes will be * allocated. * * Returns 0 on success, else an error number or -1 if the file is empty. * * Inputs: * * @fname Name of file to open * @max_sz Maximum size of cache to allocate, in bytes (if zero, default) * @page_sz Page size (must be a power of two, larger than 256, smaller * than 1MB; if zero use default) * * Outputs: * * @bfh Handle for use with _bsearch_file() and _bsearch_file_close() * @reads Number of reads performed */ int _bsearch_file_open(const char *fname, size_t max_sz, size_t page_sz, bsearch_file_handle *bfh, size_t *reads) { bsearch_file_handle new_bfh = NULL; struct stat st; size_t i; int fd; int ret; *bfh = NULL; if (reads) *reads = 0; fd = open(fname, O_RDONLY); if (fd == -1) return errno; if (fstat(fd, &st) == -1) { ret = errno; goto err; } if (st.st_size == 0) { ret = -1; /* no data -> no binary search */ goto err; } /* Validate / default arguments */ if (max_sz == 0) max_sz = DEFAULT_MAX_FILE_SIZE; for (i = page_sz; i; i >>= 1) { /* Make sure page_sz is a power of two */ if ((i % 2) && (i >> 1)) { page_sz = 0; break; } } if (page_sz == 0) #ifdef HAVE_STRUCT_STAT_ST_BLKSIZE page_sz = st.st_blksize; #else page_sz = 4096; #endif for (i = page_sz; i; i >>= 1) { /* Make sure page_sz is a power of two */ if ((i % 2) && (i >> 1)) { /* Can't happen! Filesystems always use powers of two! */ page_sz = 4096; break; } } if (page_sz > MAX_BLOCK_SIZE) page_sz = MAX_BLOCK_SIZE; new_bfh = calloc(1, sizeof (*new_bfh)); if (new_bfh == NULL) { ret = ENOMEM; goto err; } new_bfh->fd = fd; new_bfh->page_sz = page_sz; new_bfh->file_sz = st.st_size; if (max_sz >= st.st_size) { /* Whole-file method */ new_bfh->cache = malloc(st.st_size + 1); if (new_bfh->cache) { new_bfh->cache[st.st_size] = '\0'; new_bfh->cache_sz = st.st_size; ret = read(fd, new_bfh->cache, st.st_size); if (ret < 0) { ret = errno; goto err; } if (ret != st.st_size) { ret = EIO; /* XXX ??? */ goto err; } if (reads) *reads = 1; (void) close(fd); new_bfh->fd = -1; *bfh = new_bfh; return 0; } } /* Block-size method, or above malloc() failed */ new_bfh->page = malloc(new_bfh->page_sz << 1); if (new_bfh->page == NULL) { /* Can't even allocate a single double-size page! */ ret = ENOMEM; goto err; } new_bfh->cache_sz = max_sz < st.st_size ? max_sz : st.st_size; new_bfh->cache = malloc(new_bfh->cache_sz); *bfh = new_bfh; /* * malloc() may have failed because we were asking for a lot of * memory, but we may still be able to operate without a cache, * so let's not fail. */ if (new_bfh->cache == NULL) { new_bfh->cache_sz = 0; return 0; } /* Initialize cache */ for (i = 0; i < new_bfh->cache_sz; i += new_bfh->page_sz) new_bfh->cache[i] = '\0'; return 0; err: (void) close(fd); if (new_bfh) { free(new_bfh->page); free(new_bfh->cache); free(new_bfh); } return ret; } /* * Indicate whether the given binary search file handle will be searched * with block-wise method. */ void _bsearch_file_info(bsearch_file_handle bfh, size_t *page_sz, size_t *max_sz, int *blockwise) { if (page_sz) *page_sz = bfh->page_sz; if (max_sz) *max_sz = bfh->cache_sz; if (blockwise) *blockwise = (bfh->file_sz != bfh->cache_sz); } /* * Close the given binary file search handle. * * Inputs: * * @bfh Pointer to variable containing handle to close. */ void _bsearch_file_close(bsearch_file_handle *bfh) { if (!*bfh) return; if ((*bfh)->fd >= 0) (void) close((*bfh)->fd); if ((*bfh)->page) free((*bfh)->page); if ((*bfh)->cache) free((*bfh)->cache); free(*bfh); *bfh = NULL; } /* * Private function to get a page from a cache. The cache is a char * array of 2^n - 1 double-size page worth of bytes, where n is the * number of tree levels that the cache stores. The cache can be * smaller than n implies. * * The page may or may not be valid. If the first byte of it is NUL * then it's not valid, else it is. * * Returns 1 if page is in cache and valid, 0 if the cache is too small * or the page is invalid. The page address is output in @buf if the * cache is large enough to contain it regardless of whether the page is * valid. * * Inputs: * * @bfh Binary search file handle * @level Level in the tree that we want a page for * @page_idx Page number in the given level (0..2^level - 1) * * Outputs: * * @buf Set to address of page if the cache is large enough */ static int get_page_from_cache(bsearch_file_handle bfh, size_t level, size_t page_idx, char **buf) { size_t idx = 0; size_t page_sz; page_sz = bfh->page_sz << 1; /* we use double-size pages in the cache */ *buf = NULL; /* * Compute index into cache. The cache is basically an array of * double-size pages. The first (zeroth) double-size page in the * cache will be the middle page of the file -- the root of the * tree. The next two double-size pages will be the left and right * pages of the second level in the tree. The next four double-size * pages will be the four pages at the next level. And so on for as * many pages as fit in the cache. * * The page index is the number of the page at the given level. We * then compute (2^level - 1 + page index) * 2page size, check that * we have that in the cache, check that the page has been read (it * doesn't start with NUL). */ if (level) idx = (1 << level) - 1 + page_idx; if (((idx + 1) * page_sz * 2) > bfh->cache_sz) return 0; *buf = &bfh->cache[idx * page_sz * 2]; if (bfh->cache[idx * page_sz * 2] == '\0') return 0; /* cache[idx] == NUL -> page not loaded in cache */ return 1; } /* * Private function to read a page of @page_sz from @fd at offset @off * into @buf, outputing the number of bytes read, which will be the same * as @page_sz unless the page being read is the last page, in which * case the number of remaining bytes in the file will be output. * * Returns 0 on success or an errno value otherwise (EIO if reads are * short). * * Inputs: * * @bfh Binary search file handle * @level Level in the binary search tree that we're at * @page_idx Page "index" at the @level of the tree that we want * @page Actual page number that we want * want_double Whether we need a page or double page read * * Outputs: * * @buf Page read or cached * @bytes Bytes read (may be less than page or double page size in * the case of the last page, of course) */ static int read_page(bsearch_file_handle bfh, size_t level, size_t page_idx, size_t page, int want_double, const char **buf, size_t *bytes) { int ret; off_t off; size_t expected; size_t wanted; char *page_buf; /* Figure out where we're reading and how much */ off = page * bfh->page_sz; if (off < 0) return EOVERFLOW; wanted = bfh->page_sz << want_double; expected = ((bfh->file_sz - off) > wanted) ? wanted : bfh->file_sz - off; if (get_page_from_cache(bfh, level, page_idx, &page_buf)) { *buf = page_buf; *bytes = expected; return 0; /* found in cache */ } *bytes = 0; *buf = NULL; /* OK, we have to read a page or double-size page */ if (page_buf) want_double = 1; /* we'll be caching; we cache double-size pages */ else page_buf = bfh->page; /* we won't cache this page */ wanted = bfh->page_sz << want_double; expected = ((bfh->file_sz - off) > wanted) ? wanted : bfh->file_sz - off; #ifdef HAVE_PREAD ret = pread(bfh->fd, page_buf, expected, off); #else if (lseek(bfh->fd, off, SEEK_SET) == (off_t)-1) return errno; ret = read(bfh->fd, page_buf, expected); #endif if (ret < 0) return errno; if (ret != expected) return EIO; /* XXX ??? */ *buf = page_buf; *bytes = expected; return 0; } /* * Perform a binary search of a file where each line is a record (LF and * CRLF supported). Each record consists of a key followed by an * optional value separated from the key by whitespace. Whitespace can * be quoted with backslashes. It's the caller's responsibility to * encode/decode keys/values if quoting is desired; newlines should be * encoded such that a newline does not appear in the result. * * The search is done with block-wise I/O (i.e., the whole file is not * read into memory). * * All output arguments are optional. * * Returns 0 if key is found, -1 if not found, or an error code such as * ENOMEM in case of error. * * NOTE: We could improve this by not freeing the buffer, instead * requiring that the caller provide it. Further, we could cache * the top N levels of [double-size] pages (2^N - 1 pages), which * should speed up most searches by reducing the number of reads * by N. * * Inputs: * * @fd File descriptor (file to search) * @page_sz Page size (if zero then the file's st_blksize will be used) * @key Key string to search for * * Outputs: * * @value Location to store a copy of the value (caller must free) * @location Record location if found else the location where the * record should be inserted (index into @buf) * @loops Location to store a count of bisections required for * search (useful for confirming logarithmic performance) * @reads Location to store a count of pages read during search * (useful for confirming logarithmic performance) */ int _bsearch_file(bsearch_file_handle bfh, const char *key, char **value, size_t *location, size_t *loops, size_t *reads) { int ret; const char *buf; size_t buf_sz; size_t page, l, r; size_t my_reads = 0; size_t my_loops_total = 0; size_t my_loops; size_t level; /* level in the tree */ size_t page_idx = 0; /* page number in the tree level */ size_t buf_location; int cmp; int buf_ends_in_eol = 0; int buf_is_start = 0; if (reads) *reads = 0; /* If whole file is in memory then search that and we're done */ if (bfh->file_sz == bfh->cache_sz) return _bsearch_text(bfh->cache, bfh->cache_sz, key, value, location, loops); /* Else block-wise binary search */ if (value) *value = NULL; if (loops) *loops = 0; l = 0; r = (bfh->file_sz / bfh->page_sz) + 1; for (level = 0, page = r >> 1; page >= l && page < r ; level++) { ret = read_page(bfh, level, page_idx, page, 0, &buf, &buf_sz); if (ret != 0) return ret; my_reads++; if (buf[buf_sz - 1] == '\r' || buf[buf_sz - 1] == '\n') buf_ends_in_eol = 1; else buf_ends_in_eol = 0; buf_is_start = page == 0 ? 1 : 0; ret = bsearch_common(buf, (size_t)buf_sz, key, buf_is_start, value, &buf_location, &cmp, &my_loops); if (ret > 0) return ret; /* Found or no we update stats */ my_loops_total += my_loops; if (loops) *loops = my_loops_total; if (reads) *reads = my_reads; if (location) *location = page * bfh->page_sz + buf_location; if (ret == 0) return 0; /* found! */ /* Not found */ if (cmp < 0) { /* Search left */ page_idx <<= 1; r = page; page = l + ((r - l) >> 1); continue; } else { /* * Search right, but first search the current and next * blocks in case that the record we're looking for either * straddles the boundary between this and the next record, * or in case the record starts exactly at the next page. */ heim_assert(cmp > 0, "cmp > 0"); if (!buf_ends_in_eol || page == l || page == (r - 1)) { ret = read_page(bfh, level, page_idx, page, 1, &buf, &buf_sz); if (ret != 0) return ret; my_reads++; buf_is_start = page == l ? 1 : 0; ret = bsearch_common(buf, (size_t)buf_sz, key, buf_is_start, value, &buf_location, &cmp, &my_loops); if (ret > 0) return ret; my_loops_total += my_loops; if (loops) *loops = my_loops_total; if (reads) *reads = my_reads; if (location) *location = page * bfh->page_sz + buf_location; if (ret == 0) return 0; } /* Oh well, search right */ if (l == page && r == (l + 1)) break; page_idx = (page_idx << 1) + 1; l = page; page = l + ((r - l) >> 1); continue; } } return -1; } static int stdb_open(void *plug, const char *dbtype, const char *dbname, heim_dict_t options, void **db, heim_error_t *error) { bsearch_file_handle bfh; char *p; int ret; if (error) *error = NULL; if (dbname == NULL || *dbname == '\0') { if (error) *error = heim_error_create(EINVAL, N_("DB name required for sorted-text DB " "plugin", "")); return EINVAL; } p = strrchr(dbname, '.'); if (p == NULL || strcmp(p, ".txt") != 0) { if (error) *error = heim_error_create(ENOTSUP, N_("Text file (name ending in .txt) " "required for sorted-text DB plugin", "")); return ENOTSUP; } ret = _bsearch_file_open(dbname, 0, 0, &bfh, NULL); if (ret) return ret; *db = bfh; return 0; } static int stdb_close(void *db, heim_error_t *error) { bsearch_file_handle bfh = db; if (error) *error = NULL; _bsearch_file_close(&bfh); return 0; } static heim_data_t stdb_copy_value(void *db, heim_string_t table, heim_data_t key, heim_error_t *error) { bsearch_file_handle bfh = db; const char *k; char *v; heim_data_t value; int ret; if (error) *error = NULL; if (table == NULL) table = HSTR(""); if (table != HSTR("")) return NULL; if (heim_get_tid(key) == HEIM_TID_STRING) k = heim_string_get_utf8((heim_string_t)key); else k = (const char *)heim_data_get_ptr(key); ret = _bsearch_file(bfh, k, &v, NULL, NULL, NULL); if (ret != 0) { if (ret > 0 && error) *error = heim_error_create(ret, "%s", strerror(ret)); return NULL; } value = heim_data_create(v, strlen(v)); free(v); /* XXX Handle ENOMEM */ return value; } struct heim_db_type heim_sorted_text_file_dbtype = { 1, stdb_open, NULL, stdb_close, NULL, NULL, NULL, NULL, NULL, NULL, stdb_copy_value, NULL, NULL, NULL }; heimdal-7.5.0/lib/base/roken_rename.h0000644000175000017500000000430113026237312015545 0ustar niknik/* * Copyright (c) 1998 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ /* $Id$ */ #ifndef __heimbase_roken_rename_h__ #define __heimbase_roken_rename_h__ #ifndef HAVE_VSNPRINTF #define rk_vsnprintf heimbase_vsnprintf #endif #ifndef HAVE_ASPRINTF #define rk_asprintf heimbase_asprintf #endif #ifndef HAVE_ASNPRINTF #define rk_asnprintf heimbase_asnprintf #endif #ifndef HAVE_VASPRINTF #define rk_vasprintf heimbase_vasprintf #endif #ifndef HAVE_VASNPRINTF #define rk_vasnprintf heimbase_vasnprintf #endif #ifndef HAVE_STRDUP #define rk_strdup heimbase_strdup #endif #ifndef HAVE_STRNDUP #define rk_strndup heimbase_strndup #endif #endif /* __heimbase_roken_rename_h__ */ heimdal-7.5.0/lib/base/version-script.map0000644000175000017500000000372213026237312016423 0ustar niknik HEIMDAL_BASE_1.0 { global: _bsearch_file; _bsearch_file_close; _bsearch_file_info; _bsearch_file_open; _bsearch_text; __heim_string_constant; DllMain; heim_abort; heim_abortv; heim_alloc; heim_array_append_value; heim_array_copy_value; heim_array_create; heim_array_delete_value; heim_array_filter_f; heim_array_get_length; heim_array_get_type_id; heim_array_get_value; heim_array_iterate_f; heim_array_iterate_reverse_f; heim_array_insert_value; heim_array_set_value; heim_auto_release; heim_auto_release_create; heim_auto_release_drain; heim_base_once_f; heim_bool_create; heim_bool_val; heim_cmp; heim_data_create; heim_data_ref_create; heim_data_get_data; heim_data_get_length; heim_data_get_ptr; heim_data_get_type_id; heim_data_ref_get_type_id; heim_db_begin; heim_db_clone; heim_db_commit; heim_db_copy_value; heim_db_delete_key; heim_db_get_type_id; heim_db_iterate_f; heim_db_create; heim_db_register; heim_db_rollback; heim_db_set_value; heim_dict_copy_value; heim_dict_create; heim_dict_delete_key; heim_dict_get_type_id; heim_dict_get_value; heim_dict_iterate_f; heim_dict_set_value; heim_error_append; heim_error_copy_string; heim_error_create_opt; heim_error_create; heim_error_createv; heim_error_create_enomem; heim_error_get_code; heim_get_hash; heim_get_tid; heim_json_create; heim_json_create_with_bytes; heim_json_copy_serialize; heim_null_create; heim_number_create; heim_number_get_int; heim_number_get_type_id; heim_path_create; heim_path_delete; heim_path_get; heim_path_copy; heim_path_vcreate; heim_path_vdelete; heim_path_vget; heim_path_vcopy; heim_release; heim_retain; heim_show; heim_sorted_text_file_dbtype; heim_string_create; heim_string_create_with_bytes; heim_string_create_with_format; heim_string_get_type_id; heim_string_get_utf8; heim_string_ref_create; local: *; }; heimdal-7.5.0/lib/base/error.c0000644000175000017500000001113713212137553014234 0ustar niknik/* * Copyright (c) 2010 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Portions Copyright (c) 2010 Apple Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "baselocl.h" struct heim_error { int error_code; heim_string_t msg; struct heim_error *next; }; static void error_dealloc(void *ptr) { struct heim_error *p = ptr; heim_release(p->msg); heim_release(p->next); } static int error_cmp(void *a, void *b) { struct heim_error *ap = a, *bp = b; if (ap->error_code == ap->error_code) return ap->error_code - ap->error_code; return heim_cmp(ap->msg, bp->msg); } static unsigned long error_hash(void *ptr) { struct heim_error *p = ptr; return p->error_code; } struct heim_type_data _heim_error_object = { HEIM_TID_ERROR, "error-object", NULL, error_dealloc, NULL, error_cmp, error_hash, NULL }; heim_error_t heim_error_create_enomem(void) { /* This is an immediate object; see heim_number_create() */ return (heim_error_t)heim_number_create(ENOMEM); } void heim_error_create_opt(heim_error_t *error, int error_code, const char *fmt, ...) { if (error) { va_list ap; va_start(ap, fmt); *error = heim_error_createv(error_code, fmt, ap); va_end(ap); } } heim_error_t heim_error_create(int error_code, const char *fmt, ...) { heim_error_t e; va_list ap; va_start(ap, fmt); e = heim_error_createv(error_code, fmt, ap); va_end(ap); return e; } heim_error_t heim_error_createv(int error_code, const char *fmt, va_list ap) { heim_error_t e; char *str; int len; int save_errno = errno; str = malloc(1024); errno = save_errno; if (str == NULL) return heim_error_create_enomem(); len = vsnprintf(str, 1024, fmt, ap); errno = save_errno; if (len < 0) { free(str); return NULL; /* XXX We should have a special heim_error_t for this */ } e = _heim_alloc_object(&_heim_error_object, sizeof(struct heim_error)); if (e) { e->msg = heim_string_create(str); e->error_code = error_code; } free(str); errno = save_errno; return e; } heim_string_t heim_error_copy_string(heim_error_t error) { if (heim_get_tid(error) != HEIM_TID_ERROR) { if (heim_get_tid(error) == heim_number_get_type_id()) return __heim_string_constant(strerror(heim_number_get_int((heim_number_t)error))); heim_abort("invalid heim_error_t"); } /* XXX concat all strings */ return heim_retain(error->msg); } int heim_error_get_code(heim_error_t error) { if (error == NULL) return -1; if (heim_get_tid(error) != HEIM_TID_ERROR) { if (heim_get_tid(error) == heim_number_get_type_id()) return heim_number_get_int((heim_number_t)error); heim_abort("invalid heim_error_t"); } return error->error_code; } heim_error_t heim_error_append(heim_error_t top, heim_error_t append) { if (heim_get_tid(top) != HEIM_TID_ERROR) { if (heim_get_tid(top) == heim_number_get_type_id()) return top; heim_abort("invalid heim_error_t"); } if (top->next) heim_release(top->next); top->next = heim_retain(append); return top; } heimdal-7.5.0/lib/base/heimbase.c0000644000175000017500000006046013026237312014660 0ustar niknik/* * Copyright (c) 2010 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Portions Copyright (c) 2010 Apple Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "baselocl.h" #include static heim_base_atomic_type tidglobal = HEIM_TID_USER; struct heim_base { heim_type_t isa; heim_base_atomic_type ref_cnt; HEIM_TAILQ_ENTRY(heim_base) autorel; heim_auto_release_t autorelpool; uintptr_t isaextra[3]; }; /* specialized version of base */ struct heim_base_mem { heim_type_t isa; heim_base_atomic_type ref_cnt; HEIM_TAILQ_ENTRY(heim_base) autorel; heim_auto_release_t autorelpool; const char *name; void (*dealloc)(void *); uintptr_t isaextra[1]; }; #define PTR2BASE(ptr) (((struct heim_base *)ptr) - 1) #define BASE2PTR(ptr) ((void *)(((struct heim_base *)ptr) + 1)) #ifdef HEIM_BASE_NEED_ATOMIC_MUTEX HEIMDAL_MUTEX _heim_base_mutex = HEIMDAL_MUTEX_INITIALIZER; #endif /* * Auto release structure */ struct heim_auto_release { HEIM_TAILQ_HEAD(, heim_base) pool; HEIMDAL_MUTEX pool_mutex; struct heim_auto_release *parent; }; /** * Retain object (i.e., take a reference) * * @param object to be released, NULL is ok * * @return the same object as passed in */ void * heim_retain(void *ptr) { struct heim_base *p = PTR2BASE(ptr); if (ptr == NULL || heim_base_is_tagged(ptr)) return ptr; if (p->ref_cnt == heim_base_atomic_max) return ptr; if ((heim_base_atomic_inc(&p->ref_cnt) - 1) == 0) heim_abort("resurection"); return ptr; } /** * Release object, free if reference count reaches zero * * @param object to be released */ void heim_release(void *ptr) { heim_base_atomic_type old; struct heim_base *p = PTR2BASE(ptr); if (ptr == NULL || heim_base_is_tagged(ptr)) return; if (p->ref_cnt == heim_base_atomic_max) return; old = heim_base_atomic_dec(&p->ref_cnt) + 1; if (old > 1) return; if (old == 1) { heim_auto_release_t ar = p->autorelpool; /* remove from autorel pool list */ if (ar) { p->autorelpool = NULL; HEIMDAL_MUTEX_lock(&ar->pool_mutex); HEIM_TAILQ_REMOVE(&ar->pool, p, autorel); HEIMDAL_MUTEX_unlock(&ar->pool_mutex); } if (p->isa->dealloc) p->isa->dealloc(ptr); free(p); } else heim_abort("over release"); } /** * If used require wrapped in autorelease pool */ heim_string_t heim_description(heim_object_t ptr) { struct heim_base *p = PTR2BASE(ptr); if (p->isa->desc == NULL) return heim_auto_release(heim_string_ref_create(p->isa->name, NULL)); return heim_auto_release(p->isa->desc(ptr)); } void _heim_make_permanent(heim_object_t ptr) { struct heim_base *p = PTR2BASE(ptr); p->ref_cnt = heim_base_atomic_max; } static heim_type_t tagged_isa[9] = { &_heim_number_object, &_heim_null_object, &_heim_bool_object, NULL, NULL, NULL, NULL, NULL, NULL }; heim_type_t _heim_get_isa(heim_object_t ptr) { struct heim_base *p; if (heim_base_is_tagged(ptr)) { if (heim_base_is_tagged_object(ptr)) return tagged_isa[heim_base_tagged_object_tid(ptr)]; heim_abort("not a supported tagged type"); } p = PTR2BASE(ptr); return p->isa; } /** * Get type ID of object * * @param object object to get type id of * * @return type id of object */ heim_tid_t heim_get_tid(heim_object_t ptr) { heim_type_t isa = _heim_get_isa(ptr); return isa->tid; } /** * Get hash value of object * * @param object object to get hash value for * * @return a hash value */ unsigned long heim_get_hash(heim_object_t ptr) { heim_type_t isa = _heim_get_isa(ptr); if (isa->hash) return isa->hash(ptr); return (unsigned long)ptr; } /** * Compare two objects, returns 0 if equal, can use used for qsort() * and friends. * * @param a first object to compare * @param b first object to compare * * @return 0 if objects are equal */ int heim_cmp(heim_object_t a, heim_object_t b) { heim_tid_t ta, tb; heim_type_t isa; ta = heim_get_tid(a); tb = heim_get_tid(b); if (ta != tb) return ta - tb; isa = _heim_get_isa(a); if (isa->cmp) return isa->cmp(a, b); return (uintptr_t)a - (uintptr_t)b; } /* * Private - allocates an memory object */ static void memory_dealloc(void *ptr) { struct heim_base_mem *p = (struct heim_base_mem *)PTR2BASE(ptr); if (p->dealloc) p->dealloc(ptr); } struct heim_type_data memory_object = { HEIM_TID_MEMORY, "memory-object", NULL, memory_dealloc, NULL, NULL, NULL, NULL }; /** * Allocate memory for an object of anonymous type * * @param size size of object to be allocated * @param name name of ad-hoc type * @param dealloc destructor function * * Objects allocated with this interface do not serialize. * * @return allocated object */ void * heim_alloc(size_t size, const char *name, heim_type_dealloc dealloc) { /* XXX use posix_memalign */ struct heim_base_mem *p = calloc(1, size + sizeof(*p)); if (p == NULL) return NULL; p->isa = &memory_object; p->ref_cnt = 1; p->name = name; p->dealloc = dealloc; return BASE2PTR(p); } heim_type_t _heim_create_type(const char *name, heim_type_init init, heim_type_dealloc dealloc, heim_type_copy copy, heim_type_cmp cmp, heim_type_hash hash, heim_type_description desc) { heim_type_t type; type = calloc(1, sizeof(*type)); if (type == NULL) return NULL; type->tid = heim_base_atomic_inc(&tidglobal); type->name = name; type->init = init; type->dealloc = dealloc; type->copy = copy; type->cmp = cmp; type->hash = hash; type->desc = desc; return type; } heim_object_t _heim_alloc_object(heim_type_t type, size_t size) { /* XXX should use posix_memalign */ struct heim_base *p = calloc(1, size + sizeof(*p)); if (p == NULL) return NULL; p->isa = type; p->ref_cnt = 1; return BASE2PTR(p); } void * _heim_get_isaextra(heim_object_t ptr, size_t idx) { struct heim_base *p = (struct heim_base *)PTR2BASE(ptr); heim_assert(ptr != NULL, "internal error"); if (p->isa == &memory_object) return NULL; heim_assert(idx < 3, "invalid private heim_base extra data index"); return &p->isaextra[idx]; } heim_tid_t _heim_type_get_tid(heim_type_t type) { return type->tid; } #if !defined(WIN32) && !defined(HAVE_DISPATCH_DISPATCH_H) && defined(ENABLE_PTHREAD_SUPPORT) static pthread_once_t once_arg_key_once = PTHREAD_ONCE_INIT; static pthread_key_t once_arg_key; static void once_arg_key_once_init(void) { errno = pthread_key_create(&once_arg_key, NULL); if (errno != 0) { fprintf(stderr, "Error: pthread_key_create() failed, cannot continue: %s\n", strerror(errno)); abort(); } } struct once_callback { void (*fn)(void *); void *data; }; static void once_callback_caller(void) { struct once_callback *once_callback = pthread_getspecific(once_arg_key); if (once_callback == NULL) { fprintf(stderr, "Error: pthread_once() calls callback on " "different thread?! Cannot continue.\n"); abort(); } once_callback->fn(once_callback->data); } #endif /** * Call func once and only once * * @param once pointer to a heim_base_once_t * @param ctx context passed to func * @param func function to be called */ void heim_base_once_f(heim_base_once_t *once, void *ctx, void (*func)(void *)) { #if defined(WIN32) /* * With a libroken wrapper for some CAS function and a libroken yield() * wrapper we could make this the default implementation when we have * neither Grand Central nor POSX threads. * * We could also adapt the double-checked lock pattern with CAS * providing the necessary memory barriers in the absence of * portable explicit memory barrier APIs. */ /* * We use CAS operations in large part to provide implied memory * barriers. * * State 0 means that func() has never executed. * State 1 means that func() is executing. * State 2 means that func() has completed execution. */ if (InterlockedCompareExchange(once, 1L, 0L) == 0L) { /* State is now 1 */ (*func)(ctx); (void)InterlockedExchange(once, 2L); /* State is now 2 */ } else { /* * The InterlockedCompareExchange is being used to fetch * the current state under a full memory barrier. As long * as the current state is 1 continue to spin. */ while (InterlockedCompareExchange(once, 2L, 0L) == 1L) SwitchToThread(); } #elif defined(HAVE_DISPATCH_DISPATCH_H) dispatch_once_f(once, ctx, func); #elif defined(ENABLE_PTHREAD_SUPPORT) struct once_callback once_callback; once_callback.fn = func; once_callback.data = ctx; errno = pthread_once(&once_arg_key_once, once_arg_key_once_init); if (errno != 0) { fprintf(stderr, "Error: pthread_once() failed, cannot continue: %s\n", strerror(errno)); abort(); } errno = pthread_setspecific(once_arg_key, &once_callback); if (errno != 0) { fprintf(stderr, "Error: pthread_setspecific() failed, cannot continue: %s\n", strerror(errno)); abort(); } errno = pthread_once(once, once_callback_caller); if (errno != 0) { fprintf(stderr, "Error: pthread_once() failed, cannot continue: %s\n", strerror(errno)); abort(); } #else static HEIMDAL_MUTEX mutex = HEIMDAL_MUTEX_INITIALIZER; HEIMDAL_MUTEX_lock(&mutex); if (*once == 0) { *once = 1; HEIMDAL_MUTEX_unlock(&mutex); func(ctx); HEIMDAL_MUTEX_lock(&mutex); *once = 2; HEIMDAL_MUTEX_unlock(&mutex); } else if (*once == 2) { HEIMDAL_MUTEX_unlock(&mutex); } else { HEIMDAL_MUTEX_unlock(&mutex); while (1) { struct timeval tv = { 0, 1000 }; select(0, NULL, NULL, NULL, &tv); HEIMDAL_MUTEX_lock(&mutex); if (*once == 2) break; HEIMDAL_MUTEX_unlock(&mutex); } HEIMDAL_MUTEX_unlock(&mutex); } #endif } /** * Abort and log the failure (using syslog) */ void heim_abort(const char *fmt, ...) { va_list ap; va_start(ap, fmt); heim_abortv(fmt, ap); va_end(ap); } /** * Abort and log the failure (using syslog) */ void heim_abortv(const char *fmt, va_list ap) { static char str[1024]; vsnprintf(str, sizeof(str), fmt, ap); syslog(LOG_ERR, "heim_abort: %s", str); abort(); } /* * */ static int ar_created = 0; static HEIMDAL_thread_key ar_key; struct ar_tls { struct heim_auto_release *head; struct heim_auto_release *current; HEIMDAL_MUTEX tls_mutex; }; static void ar_tls_delete(void *ptr) { struct ar_tls *tls = ptr; heim_auto_release_t next = NULL; if (tls == NULL) return; for (; tls->current != NULL; tls->current = next) { next = tls->current->parent; heim_release(tls->current); } free(tls); } static void init_ar_tls(void *ptr) { int ret; HEIMDAL_key_create(&ar_key, ar_tls_delete, ret); if (ret == 0) ar_created = 1; } static struct ar_tls * autorel_tls(void) { static heim_base_once_t once = HEIM_BASE_ONCE_INIT; struct ar_tls *arp; int ret; heim_base_once_f(&once, NULL, init_ar_tls); if (!ar_created) return NULL; arp = HEIMDAL_getspecific(ar_key); if (arp == NULL) { arp = calloc(1, sizeof(*arp)); if (arp == NULL) return NULL; HEIMDAL_setspecific(ar_key, arp, ret); if (ret) { free(arp); return NULL; } } return arp; } static void autorel_dealloc(void *ptr) { heim_auto_release_t ar = ptr; struct ar_tls *tls; tls = autorel_tls(); if (tls == NULL) heim_abort("autorelease pool released on thread w/o autorelease inited"); heim_auto_release_drain(ar); if (!HEIM_TAILQ_EMPTY(&ar->pool)) heim_abort("pool not empty after draining"); HEIMDAL_MUTEX_lock(&tls->tls_mutex); if (tls->current != ptr) heim_abort("autorelease not releaseing top pool"); tls->current = ar->parent; HEIMDAL_MUTEX_unlock(&tls->tls_mutex); } static int autorel_cmp(void *a, void *b) { return (a == b); } static unsigned long autorel_hash(void *ptr) { return (unsigned long)ptr; } static struct heim_type_data _heim_autorel_object = { HEIM_TID_AUTORELEASE, "autorelease-pool", NULL, autorel_dealloc, NULL, autorel_cmp, autorel_hash, NULL }; /** * Create thread-specific object auto-release pool * * Objects placed on the per-thread auto-release pool (with * heim_auto_release()) can be released in one fell swoop by calling * heim_auto_release_drain(). */ heim_auto_release_t heim_auto_release_create(void) { struct ar_tls *tls = autorel_tls(); heim_auto_release_t ar; if (tls == NULL) heim_abort("Failed to create/get autorelease head"); ar = _heim_alloc_object(&_heim_autorel_object, sizeof(struct heim_auto_release)); if (ar) { HEIMDAL_MUTEX_lock(&tls->tls_mutex); if (tls->head == NULL) tls->head = ar; ar->parent = tls->current; tls->current = ar; HEIMDAL_MUTEX_unlock(&tls->tls_mutex); } return ar; } /** * Place the current object on the thread's auto-release pool * * @param ptr object */ heim_object_t heim_auto_release(heim_object_t ptr) { struct heim_base *p = PTR2BASE(ptr); struct ar_tls *tls = autorel_tls(); heim_auto_release_t ar; if (ptr == NULL || heim_base_is_tagged(ptr)) return ptr; /* drop from old pool */ if ((ar = p->autorelpool) != NULL) { HEIMDAL_MUTEX_lock(&ar->pool_mutex); HEIM_TAILQ_REMOVE(&ar->pool, p, autorel); p->autorelpool = NULL; HEIMDAL_MUTEX_unlock(&ar->pool_mutex); } if (tls == NULL || (ar = tls->current) == NULL) heim_abort("no auto relase pool in place, would leak"); HEIMDAL_MUTEX_lock(&ar->pool_mutex); HEIM_TAILQ_INSERT_HEAD(&ar->pool, p, autorel); p->autorelpool = ar; HEIMDAL_MUTEX_unlock(&ar->pool_mutex); return ptr; } /** * Release all objects on the given auto-release pool */ void heim_auto_release_drain(heim_auto_release_t autorel) { heim_object_t obj; /* release all elements on the tail queue */ HEIMDAL_MUTEX_lock(&autorel->pool_mutex); while(!HEIM_TAILQ_EMPTY(&autorel->pool)) { obj = HEIM_TAILQ_FIRST(&autorel->pool); HEIMDAL_MUTEX_unlock(&autorel->pool_mutex); heim_release(BASE2PTR(obj)); HEIMDAL_MUTEX_lock(&autorel->pool_mutex); } HEIMDAL_MUTEX_unlock(&autorel->pool_mutex); } /* * Helper for heim_path_vget() and heim_path_delete(). On success * outputs the node named by the path and the parent node and key * (useful for heim_path_delete()). */ static heim_object_t heim_path_vget2(heim_object_t ptr, heim_object_t *parent, heim_object_t *key, heim_error_t *error, va_list ap) { heim_object_t path_element; heim_object_t node, next_node; heim_tid_t node_type; *parent = NULL; *key = NULL; if (ptr == NULL) return NULL; for (node = ptr; node != NULL; ) { path_element = va_arg(ap, heim_object_t); if (path_element == NULL) { *parent = node; *key = path_element; return node; } node_type = heim_get_tid(node); switch (node_type) { case HEIM_TID_ARRAY: case HEIM_TID_DICT: case HEIM_TID_DB: break; default: if (node == ptr) heim_abort("heim_path_get() only operates on container types"); return NULL; } if (node_type == HEIM_TID_DICT) { next_node = heim_dict_get_value(node, path_element); } else if (node_type == HEIM_TID_DB) { next_node = _heim_db_get_value(node, NULL, path_element, NULL); } else if (node_type == HEIM_TID_ARRAY) { int idx = -1; if (heim_get_tid(path_element) == HEIM_TID_NUMBER) idx = heim_number_get_int(path_element); if (idx < 0) { if (error) *error = heim_error_create(EINVAL, "heim_path_get() path elements " "for array nodes must be " "numeric and positive"); return NULL; } next_node = heim_array_get_value(node, idx); } else { if (error) *error = heim_error_create(EINVAL, "heim_path_get() node in path " "not a container type"); return NULL; } node = next_node; } return NULL; } /** * Get a node in a heim_object tree by path * * @param ptr tree * @param error error (output) * @param ap NULL-terminated va_list of heim_object_ts that form a path * * @return object (not retained) if found * * @addtogroup heimbase */ heim_object_t heim_path_vget(heim_object_t ptr, heim_error_t *error, va_list ap) { heim_object_t p, k; return heim_path_vget2(ptr, &p, &k, error, ap); } /** * Get a node in a tree by path, with retained reference * * @param ptr tree * @param error error (output) * @param ap NULL-terminated va_list of heim_object_ts that form a path * * @return retained object if found * * @addtogroup heimbase */ heim_object_t heim_path_vcopy(heim_object_t ptr, heim_error_t *error, va_list ap) { heim_object_t p, k; return heim_retain(heim_path_vget2(ptr, &p, &k, error, ap)); } /** * Get a node in a tree by path * * @param ptr tree * @param error error (output) * @param ... NULL-terminated va_list of heim_object_ts that form a path * * @return object (not retained) if found * * @addtogroup heimbase */ heim_object_t heim_path_get(heim_object_t ptr, heim_error_t *error, ...) { heim_object_t o; heim_object_t p, k; va_list ap; if (ptr == NULL) return NULL; va_start(ap, error); o = heim_path_vget2(ptr, &p, &k, error, ap); va_end(ap); return o; } /** * Get a node in a tree by path, with retained reference * * @param ptr tree * @param error error (output) * @param ... NULL-terminated va_list of heim_object_ts that form a path * * @return retained object if found * * @addtogroup heimbase */ heim_object_t heim_path_copy(heim_object_t ptr, heim_error_t *error, ...) { heim_object_t o; heim_object_t p, k; va_list ap; if (ptr == NULL) return NULL; va_start(ap, error); o = heim_retain(heim_path_vget2(ptr, &p, &k, error, ap)); va_end(ap); return o; } /** * Create a path in a heim_object_t tree * * @param ptr the tree * @param size the size of the heim_dict_t nodes to be created * @param leaf leaf node to be added, if any * @param error error (output) * @param ap NULL-terminated of path component objects * * Create a path of heim_dict_t interior nodes in a given heim_object_t * tree, as necessary, and set/replace a leaf, if given (if leaf is NULL * then the leaf is not deleted). * * @return 0 on success, else a system error * * @addtogroup heimbase */ int heim_path_vcreate(heim_object_t ptr, size_t size, heim_object_t leaf, heim_error_t *error, va_list ap) { heim_object_t path_element = va_arg(ap, heim_object_t); heim_object_t next_path_element = NULL; heim_object_t node = ptr; heim_object_t next_node = NULL; heim_tid_t node_type; int ret = 0; if (ptr == NULL) heim_abort("heim_path_vcreate() does not create root nodes"); while (path_element != NULL) { next_path_element = va_arg(ap, heim_object_t); node_type = heim_get_tid(node); if (node_type == HEIM_TID_DICT) { next_node = heim_dict_get_value(node, path_element); } else if (node_type == HEIM_TID_ARRAY) { int idx = -1; if (heim_get_tid(path_element) == HEIM_TID_NUMBER) idx = heim_number_get_int(path_element); if (idx < 0) { if (error) *error = heim_error_create(EINVAL, "heim_path() path elements for " "array nodes must be numeric " "and positive"); return EINVAL; } if (idx < heim_array_get_length(node)) next_node = heim_array_get_value(node, idx); else next_node = NULL; } else if (node_type == HEIM_TID_DB && next_path_element != NULL) { if (error) *error = heim_error_create(EINVAL, "Interior node is a DB"); return EINVAL; } if (next_path_element == NULL) break; /* Create missing interior node */ if (next_node == NULL) { next_node = heim_dict_create(size); /* no arrays or DBs, just dicts */ if (next_node == NULL) { ret = ENOMEM; goto err; } if (node_type == HEIM_TID_DICT) { ret = heim_dict_set_value(node, path_element, next_node); } else if (node_type == HEIM_TID_ARRAY && heim_number_get_int(path_element) <= heim_array_get_length(node)) { ret = heim_array_insert_value(node, heim_number_get_int(path_element), next_node); } else { ret = EINVAL; if (error) *error = heim_error_create(ret, "Node in path not a " "container"); } heim_release(next_node); if (ret) goto err; } path_element = next_path_element; node = next_node; next_node = NULL; } if (path_element == NULL) goto err; /* Add the leaf */ if (leaf != NULL) { if (node_type == HEIM_TID_DICT) ret = heim_dict_set_value(node, path_element, leaf); else ret = heim_array_insert_value(node, heim_number_get_int(path_element), leaf); } return ret; err: if (error && !*error) { if (ret == ENOMEM) *error = heim_error_create_enomem(); else *error = heim_error_create(ret, "Could not set " "dict value"); } return ret; } /** * Create a path in a heim_object_t tree * * @param ptr the tree * @param size the size of the heim_dict_t nodes to be created * @param leaf leaf node to be added, if any * @param error error (output) * @param ... NULL-terminated list of path component objects * * Create a path of heim_dict_t interior nodes in a given heim_object_t * tree, as necessary, and set/replace a leaf, if given (if leaf is NULL * then the leaf is not deleted). * * @return 0 on success, else a system error * * @addtogroup heimbase */ int heim_path_create(heim_object_t ptr, size_t size, heim_object_t leaf, heim_error_t *error, ...) { va_list ap; int ret; va_start(ap, error); ret = heim_path_vcreate(ptr, size, leaf, error, ap); va_end(ap); return ret; } /** * Delete leaf node named by a path in a heim_object_t tree * * @param ptr the tree * @param error error (output) * @param ap NULL-terminated list of path component objects * * @addtogroup heimbase */ void heim_path_vdelete(heim_object_t ptr, heim_error_t *error, va_list ap) { heim_object_t parent, key, child; child = heim_path_vget2(ptr, &parent, &key, error, ap); if (child != NULL) { if (heim_get_tid(parent) == HEIM_TID_DICT) heim_dict_delete_key(parent, key); else if (heim_get_tid(parent) == HEIM_TID_DB) heim_db_delete_key(parent, NULL, key, error); else if (heim_get_tid(parent) == HEIM_TID_ARRAY) heim_array_delete_value(parent, heim_number_get_int(key)); heim_release(child); } } /** * Delete leaf node named by a path in a heim_object_t tree * * @param ptr the tree * @param error error (output) * @param ap NULL-terminated list of path component objects * * @addtogroup heimbase */ void heim_path_delete(heim_object_t ptr, heim_error_t *error, ...) { va_list ap; va_start(ap, error); heim_path_vdelete(ptr, error, ap); va_end(ap); return; } heimdal-7.5.0/lib/base/string.c0000644000175000017500000001331013026237312014401 0ustar niknik/* * Copyright (c) 2010 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Portions Copyright (c) 2010 Apple Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "baselocl.h" #include static void string_dealloc(void *ptr) { heim_string_t s = ptr; heim_string_free_f_t *deallocp; heim_string_free_f_t dealloc; if (*(const char *)ptr != '\0') return; /* Possible string ref */ deallocp = _heim_get_isaextra(s, 0); dealloc = *deallocp; if (dealloc != NULL) { char **strp = _heim_get_isaextra(s, 1); dealloc(*strp); } } static int string_cmp(void *a, void *b) { if (*(char *)a == '\0') { char **strp = _heim_get_isaextra(a, 1); if (*strp != NULL) a = *strp; /* a is a string ref */ } if (*(char *)b == '\0') { char **strp = _heim_get_isaextra(b, 1); if (*strp != NULL) b = *strp; /* b is a string ref */ } return strcmp(a, b); } static unsigned long string_hash(void *ptr) { const char *s = ptr; unsigned long n; for (n = 0; *s; ++s) n += *s; return n; } struct heim_type_data _heim_string_object = { HEIM_TID_STRING, "string-object", NULL, string_dealloc, NULL, string_cmp, string_hash, NULL }; /** * Create a string object * * @param string the string to create, must be an utf8 string * * @return string object */ heim_string_t heim_string_create(const char *string) { return heim_string_create_with_bytes(string, strlen(string)); } /** * Create a string object without copying the source. * * @param string the string to referenced, must be UTF-8 * @param dealloc the function to use to release the referece to the string * * @return string object */ heim_string_t heim_string_ref_create(const char *string, heim_string_free_f_t dealloc) { heim_string_t s; heim_string_free_f_t *deallocp; s = _heim_alloc_object(&_heim_string_object, 1); if (s) { const char **strp; ((char *)s)[0] = '\0'; deallocp = _heim_get_isaextra(s, 0); *deallocp = dealloc; strp = _heim_get_isaextra(s, 1); *strp = string; } return s; } /** * Create a string object * * @param string the string to create, must be an utf8 string * @param len the length of the string * * @return string object */ heim_string_t heim_string_create_with_bytes(const void *data, size_t len) { heim_string_t s; s = _heim_alloc_object(&_heim_string_object, len + 1); if (s) { memcpy(s, data, len); ((char *)s)[len] = '\0'; } return s; } /** * Create a string object using a format string * * @param fmt format string * @param ... * * @return string object */ heim_string_t heim_string_create_with_format(const char *fmt, ...) { heim_string_t s; char *str = NULL; va_list ap; int ret; va_start(ap, fmt); ret = vasprintf(&str, fmt, ap); va_end(ap); if (ret < 0 || str == NULL) return NULL; s = heim_string_ref_create(str, string_dealloc); if (s == NULL) free(str); return s; } /** * Return the type ID of string objects * * @return type id of string objects */ heim_tid_t heim_string_get_type_id(void) { return HEIM_TID_STRING; } /** * Get the string value of the content. * * @param string the string object to get the value from * * @return a utf8 string */ const char * heim_string_get_utf8(heim_string_t string) { if (*(const char *)string == '\0') { const char **strp; /* String ref */ strp = _heim_get_isaextra(string, 1); if (*strp != NULL) return *strp; } return (const char *)string; } /* * */ static void init_string(void *ptr) { heim_dict_t *dict = ptr; *dict = heim_dict_create(101); heim_assert(*dict != NULL, "__heim_string_constant"); } heim_string_t __heim_string_constant(const char *_str) { static HEIMDAL_MUTEX mutex = HEIMDAL_MUTEX_INITIALIZER; static heim_base_once_t once; static heim_dict_t dict = NULL; heim_string_t s, s2; heim_base_once_f(&once, &dict, init_string); s = heim_string_create(_str); HEIMDAL_MUTEX_lock(&mutex); s2 = heim_dict_get_value(dict, s); if (s2) { heim_release(s); s = s2; } else { _heim_make_permanent(s); heim_dict_set_value(dict, s, s); } HEIMDAL_MUTEX_unlock(&mutex); return s; } heimdal-7.5.0/lib/base/Makefile.am0000644000175000017500000000210113026237312014757 0ustar niknik include $(top_srcdir)/Makefile.am.common if do_roken_rename ES = base64.c endif IMPLEMENT_TLS= if MAINTAINER_MODE IMPLEMENT_TLS += dll.c AM_CPPFLAGS += -DHEIM_BASE_MAINTAINER endif AM_CPPFLAGS += $(ROKEN_RENAME) lib_LTLIBRARIES = libheimbase.la check_PROGRAMS = test_base libheimbase_la_LDFLAGS = -version-info 1:0:0 TESTS = test_base if versionscript libheimbase_la_LDFLAGS += $(LDFLAGS_VERSION_SCRIPT)$(srcdir)/version-script.map endif libheimbase_la_LIBADD = $(PTHREAD_LIBADD) include_HEADERS = heimbase.h dist_libheimbase_la_SOURCES = \ array.c \ baselocl.h \ bsearch.c \ bool.c \ data.c \ db.c \ dict.c \ $(IMPLEMENT_TLS) \ error.c \ heimbase.c \ heimbasepriv.h \ heimqueue.h \ json.c \ null.c \ number.c \ roken_rename.h \ string.c nodist_libheimbase_la_SOURCES = $(ES) # install these? libheimbase_la_DEPENDENCIES = version-script.map test_base_LDADD = libheimbase.la $(LIB_roken) CLEANFILES = base64.c test_db.json EXTRA_DIST = NTMakefile version-script.map base64.c: rm -f base64.c $(LN_S) $(srcdir)/../roken/base64.c . heimdal-7.5.0/lib/base/number.c0000644000175000017500000000631013026237312014365 0ustar niknik/* * Copyright (c) 2010 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Portions Copyright (c) 2010 Apple Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "baselocl.h" static void number_dealloc(void *ptr) { } static int number_cmp(void *a, void *b) { int na, nb; if (heim_base_is_tagged_object(a)) na = heim_base_tagged_object_value(a); else na = *(int *)a; if (heim_base_is_tagged_object(b)) nb = heim_base_tagged_object_value(b); else nb = *(int *)b; return na - nb; } static unsigned long number_hash(void *ptr) { if (heim_base_is_tagged_object(ptr)) return heim_base_tagged_object_value(ptr); return (unsigned long)*(int *)ptr; } struct heim_type_data _heim_number_object = { HEIM_TID_NUMBER, "number-object", NULL, number_dealloc, NULL, number_cmp, number_hash, NULL }; /** * Create a number object * * @param the number to contain in the object * * @return a number object */ heim_number_t heim_number_create(int number) { heim_number_t n; if (number < 0xffffff && number >= 0) return heim_base_make_tagged_object(number, HEIM_TID_NUMBER); n = _heim_alloc_object(&_heim_number_object, sizeof(int)); if (n) *((int *)n) = number; return n; } /** * Return the type ID of number objects * * @return type id of number objects */ heim_tid_t heim_number_get_type_id(void) { return HEIM_TID_NUMBER; } /** * Get the int value of the content * * @param number the number object to get the value from * * @return an int */ int heim_number_get_int(heim_number_t number) { if (heim_base_is_tagged_object(number)) return heim_base_tagged_object_value(number); return *(int *)number; } heimdal-7.5.0/lib/base/Makefile.in0000644000175000017500000014035613212444521015006 0ustar niknik# Makefile.in generated by automake 1.15.1 from Makefile.am. # @configure_input@ # Copyright (C) 1994-2017 Free Software Foundation, Inc. # This Makefile.in is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, # with or without modifications, as long as this notice is preserved. # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY, to the extent permitted by law; without # even the implied warranty of MERCHANTABILITY or FITNESS FOR A # PARTICULAR PURPOSE. @SET_MAKE@ # $Id$ # $Id$ VPATH = @srcdir@ am__is_gnu_make = { \ if test -z '$(MAKELEVEL)'; then \ false; \ elif test -n '$(MAKE_HOST)'; then \ true; \ elif test -n '$(MAKE_VERSION)' && test -n '$(CURDIR)'; then \ true; \ else \ false; \ fi; \ } am__make_running_with_option = \ case $${target_option-} in \ ?) ;; \ *) echo "am__make_running_with_option: internal error: invalid" \ "target option '$${target_option-}' specified" >&2; \ exit 1;; \ esac; \ has_opt=no; \ sane_makeflags=$$MAKEFLAGS; \ if $(am__is_gnu_make); then \ sane_makeflags=$$MFLAGS; \ else \ case $$MAKEFLAGS in \ *\\[\ \ ]*) \ bs=\\; \ sane_makeflags=`printf '%s\n' "$$MAKEFLAGS" \ | sed "s/$$bs$$bs[$$bs $$bs ]*//g"`;; \ esac; \ fi; \ skip_next=no; \ strip_trailopt () \ { \ flg=`printf '%s\n' "$$flg" | sed "s/$$1.*$$//"`; \ }; \ for flg in $$sane_makeflags; do \ test $$skip_next = yes && { skip_next=no; continue; }; \ case $$flg in \ *=*|--*) continue;; \ -*I) strip_trailopt 'I'; skip_next=yes;; \ -*I?*) strip_trailopt 'I';; \ -*O) strip_trailopt 'O'; skip_next=yes;; \ -*O?*) strip_trailopt 'O';; \ -*l) strip_trailopt 'l'; skip_next=yes;; \ -*l?*) strip_trailopt 'l';; \ -[dEDm]) skip_next=yes;; \ -[JT]) skip_next=yes;; \ esac; \ case $$flg in \ *$$target_option*) has_opt=yes; break;; \ esac; \ done; \ test $$has_opt = yes am__make_dryrun = (target_option=n; $(am__make_running_with_option)) am__make_keepgoing = (target_option=k; $(am__make_running_with_option)) pkgdatadir = $(datadir)/@PACKAGE@ pkgincludedir = $(includedir)/@PACKAGE@ pkglibdir = $(libdir)/@PACKAGE@ pkglibexecdir = $(libexecdir)/@PACKAGE@ am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd install_sh_DATA = $(install_sh) -c -m 644 install_sh_PROGRAM = $(install_sh) -c install_sh_SCRIPT = $(install_sh) -c INSTALL_HEADER = $(INSTALL_DATA) transform = $(program_transform_name) NORMAL_INSTALL = : PRE_INSTALL = : POST_INSTALL = : NORMAL_UNINSTALL = : PRE_UNINSTALL = : POST_UNINSTALL = : build_triplet = @build@ host_triplet = @host@ @MAINTAINER_MODE_TRUE@am__append_1 = dll.c @MAINTAINER_MODE_TRUE@am__append_2 = -DHEIM_BASE_MAINTAINER check_PROGRAMS = test_base$(EXEEXT) TESTS = test_base$(EXEEXT) @versionscript_TRUE@am__append_3 = $(LDFLAGS_VERSION_SCRIPT)$(srcdir)/version-script.map subdir = lib/base ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 am__aclocal_m4_deps = $(top_srcdir)/cf/aix.m4 \ $(top_srcdir)/cf/auth-modules.m4 \ $(top_srcdir)/cf/broken-getaddrinfo.m4 \ $(top_srcdir)/cf/broken-glob.m4 \ $(top_srcdir)/cf/broken-realloc.m4 \ $(top_srcdir)/cf/broken-snprintf.m4 $(top_srcdir)/cf/broken.m4 \ $(top_srcdir)/cf/broken2.m4 $(top_srcdir)/cf/c-attribute.m4 \ $(top_srcdir)/cf/capabilities.m4 \ $(top_srcdir)/cf/check-compile-et.m4 \ $(top_srcdir)/cf/check-getpwnam_r-posix.m4 \ $(top_srcdir)/cf/check-man.m4 \ $(top_srcdir)/cf/check-netinet-ip-and-tcp.m4 \ $(top_srcdir)/cf/check-type-extra.m4 \ $(top_srcdir)/cf/check-var.m4 $(top_srcdir)/cf/crypto.m4 \ $(top_srcdir)/cf/db.m4 $(top_srcdir)/cf/destdirs.m4 \ $(top_srcdir)/cf/dispatch.m4 $(top_srcdir)/cf/dlopen.m4 \ $(top_srcdir)/cf/find-func-no-libs.m4 \ $(top_srcdir)/cf/find-func-no-libs2.m4 \ $(top_srcdir)/cf/find-func.m4 \ $(top_srcdir)/cf/find-if-not-broken.m4 \ $(top_srcdir)/cf/framework-security.m4 \ $(top_srcdir)/cf/have-struct-field.m4 \ $(top_srcdir)/cf/have-type.m4 $(top_srcdir)/cf/irix.m4 \ $(top_srcdir)/cf/krb-bigendian.m4 \ $(top_srcdir)/cf/krb-func-getlogin.m4 \ $(top_srcdir)/cf/krb-ipv6.m4 $(top_srcdir)/cf/krb-prog-ln-s.m4 \ $(top_srcdir)/cf/krb-prog-perl.m4 \ $(top_srcdir)/cf/krb-readline.m4 \ $(top_srcdir)/cf/krb-struct-spwd.m4 \ $(top_srcdir)/cf/krb-struct-winsize.m4 \ $(top_srcdir)/cf/largefile.m4 $(top_srcdir)/cf/libtool.m4 \ $(top_srcdir)/cf/ltoptions.m4 $(top_srcdir)/cf/ltsugar.m4 \ $(top_srcdir)/cf/ltversion.m4 $(top_srcdir)/cf/lt~obsolete.m4 \ $(top_srcdir)/cf/mips-abi.m4 $(top_srcdir)/cf/misc.m4 \ $(top_srcdir)/cf/need-proto.m4 $(top_srcdir)/cf/osfc2.m4 \ $(top_srcdir)/cf/otp.m4 $(top_srcdir)/cf/pkg.m4 \ $(top_srcdir)/cf/proto-compat.m4 $(top_srcdir)/cf/pthreads.m4 \ $(top_srcdir)/cf/resolv.m4 $(top_srcdir)/cf/retsigtype.m4 \ $(top_srcdir)/cf/roken-frag.m4 \ $(top_srcdir)/cf/socket-wrapper.m4 $(top_srcdir)/cf/sunos.m4 \ $(top_srcdir)/cf/telnet.m4 $(top_srcdir)/cf/test-package.m4 \ $(top_srcdir)/cf/version-script.m4 $(top_srcdir)/cf/wflags.m4 \ $(top_srcdir)/cf/win32.m4 $(top_srcdir)/cf/with-all.m4 \ $(top_srcdir)/acinclude.m4 $(top_srcdir)/configure.ac am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \ $(ACLOCAL_M4) DIST_COMMON = $(srcdir)/Makefile.am $(include_HEADERS) \ $(am__DIST_COMMON) mkinstalldirs = $(install_sh) -d CONFIG_HEADER = $(top_builddir)/include/config.h CONFIG_CLEAN_FILES = CONFIG_CLEAN_VPATH_FILES = am__vpath_adj_setup = srcdirstrip=`echo "$(srcdir)" | sed 's|.|.|g'`; am__vpath_adj = case $$p in \ $(srcdir)/*) f=`echo "$$p" | sed "s|^$$srcdirstrip/||"`;; \ *) f=$$p;; \ esac; am__strip_dir = f=`echo $$p | sed -e 's|^.*/||'`; am__install_max = 40 am__nobase_strip_setup = \ srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*|]/\\\\&/g'` am__nobase_strip = \ for p in $$list; do echo "$$p"; done | sed -e "s|$$srcdirstrip/||" am__nobase_list = $(am__nobase_strip_setup); \ for p in $$list; do echo "$$p $$p"; done | \ sed "s| $$srcdirstrip/| |;"' / .*\//!s/ .*/ ./; s,\( .*\)/[^/]*$$,\1,' | \ $(AWK) 'BEGIN { files["."] = "" } { files[$$2] = files[$$2] " " $$1; \ if (++n[$$2] == $(am__install_max)) \ { print $$2, files[$$2]; n[$$2] = 0; files[$$2] = "" } } \ END { for (dir in files) print dir, files[dir] }' am__base_list = \ sed '$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;s/\n/ /g' | \ sed '$$!N;$$!N;$$!N;$$!N;s/\n/ /g' am__uninstall_files_from_dir = { \ test -z "$$files" \ || { test ! -d "$$dir" && test ! -f "$$dir" && test ! -r "$$dir"; } \ || { echo " ( cd '$$dir' && rm -f" $$files ")"; \ $(am__cd) "$$dir" && rm -f $$files; }; \ } am__installdirs = "$(DESTDIR)$(libdir)" "$(DESTDIR)$(includedir)" LTLIBRARIES = $(lib_LTLIBRARIES) am__DEPENDENCIES_1 = am__dist_libheimbase_la_SOURCES_DIST = array.c baselocl.h bsearch.c \ bool.c data.c db.c dict.c dll.c error.c heimbase.c \ heimbasepriv.h heimqueue.h json.c null.c number.c \ roken_rename.h string.c @MAINTAINER_MODE_TRUE@am__objects_1 = dll.lo am__objects_2 = $(am__objects_1) dist_libheimbase_la_OBJECTS = array.lo bsearch.lo bool.lo data.lo \ db.lo dict.lo $(am__objects_2) error.lo heimbase.lo json.lo \ null.lo number.lo string.lo @do_roken_rename_TRUE@am__objects_3 = base64.lo nodist_libheimbase_la_OBJECTS = $(am__objects_3) libheimbase_la_OBJECTS = $(dist_libheimbase_la_OBJECTS) \ $(nodist_libheimbase_la_OBJECTS) AM_V_lt = $(am__v_lt_@AM_V@) am__v_lt_ = $(am__v_lt_@AM_DEFAULT_V@) am__v_lt_0 = --silent am__v_lt_1 = libheimbase_la_LINK = $(LIBTOOL) $(AM_V_lt) --tag=CC \ $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=link $(CCLD) \ $(AM_CFLAGS) $(CFLAGS) $(libheimbase_la_LDFLAGS) $(LDFLAGS) -o \ $@ test_base_SOURCES = test_base.c test_base_OBJECTS = test_base.$(OBJEXT) test_base_DEPENDENCIES = libheimbase.la $(am__DEPENDENCIES_1) AM_V_P = $(am__v_P_@AM_V@) am__v_P_ = $(am__v_P_@AM_DEFAULT_V@) am__v_P_0 = false am__v_P_1 = : AM_V_GEN = $(am__v_GEN_@AM_V@) am__v_GEN_ = $(am__v_GEN_@AM_DEFAULT_V@) am__v_GEN_0 = @echo " GEN " $@; am__v_GEN_1 = AM_V_at = $(am__v_at_@AM_V@) am__v_at_ = $(am__v_at_@AM_DEFAULT_V@) am__v_at_0 = @ am__v_at_1 = depcomp = $(SHELL) $(top_srcdir)/depcomp am__depfiles_maybe = depfiles am__mv = mv -f COMPILE = $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) \ $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) LTCOMPILE = $(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) \ $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) \ $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) \ $(AM_CFLAGS) $(CFLAGS) AM_V_CC = $(am__v_CC_@AM_V@) am__v_CC_ = $(am__v_CC_@AM_DEFAULT_V@) am__v_CC_0 = @echo " CC " $@; am__v_CC_1 = CCLD = $(CC) LINK = $(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) \ $(LIBTOOLFLAGS) --mode=link $(CCLD) $(AM_CFLAGS) $(CFLAGS) \ $(AM_LDFLAGS) $(LDFLAGS) -o $@ AM_V_CCLD = $(am__v_CCLD_@AM_V@) am__v_CCLD_ = $(am__v_CCLD_@AM_DEFAULT_V@) am__v_CCLD_0 = @echo " CCLD " $@; am__v_CCLD_1 = SOURCES = $(dist_libheimbase_la_SOURCES) \ $(nodist_libheimbase_la_SOURCES) test_base.c DIST_SOURCES = $(am__dist_libheimbase_la_SOURCES_DIST) test_base.c am__can_run_installinfo = \ case $$AM_UPDATE_INFO_DIR in \ n|no|NO) false;; \ *) (install-info --version) >/dev/null 2>&1;; \ esac HEADERS = $(include_HEADERS) am__tagged_files = $(HEADERS) $(SOURCES) $(TAGS_FILES) $(LISP) # Read a list of newline-separated strings from the standard input, # and print each of them once, without duplicates. Input order is # *not* preserved. am__uniquify_input = $(AWK) '\ BEGIN { nonempty = 0; } \ { items[$$0] = 1; nonempty = 1; } \ END { if (nonempty) { for (i in items) print i; }; } \ ' # Make sure the list of sources is unique. This is necessary because, # e.g., the same source file might be shared among _SOURCES variables # for different programs/libraries. am__define_uniq_tagged_files = \ list='$(am__tagged_files)'; \ unique=`for i in $$list; do \ if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ done | $(am__uniquify_input)` ETAGS = etags CTAGS = ctags am__tty_colors_dummy = \ mgn= red= grn= lgn= blu= brg= std=; \ am__color_tests=no am__tty_colors = { \ $(am__tty_colors_dummy); \ if test "X$(AM_COLOR_TESTS)" = Xno; then \ am__color_tests=no; \ elif test "X$(AM_COLOR_TESTS)" = Xalways; then \ am__color_tests=yes; \ elif test "X$$TERM" != Xdumb && { test -t 1; } 2>/dev/null; then \ am__color_tests=yes; \ fi; \ if test $$am__color_tests = yes; then \ red=''; \ grn=''; \ lgn=''; \ blu=''; \ mgn=''; \ brg=''; \ std=''; \ fi; \ } am__recheck_rx = ^[ ]*:recheck:[ ]* am__global_test_result_rx = ^[ ]*:global-test-result:[ ]* am__copy_in_global_log_rx = ^[ ]*:copy-in-global-log:[ ]* # A command that, given a newline-separated list of test names on the # standard input, print the name of the tests that are to be re-run # upon "make recheck". am__list_recheck_tests = $(AWK) '{ \ recheck = 1; \ while ((rc = (getline line < ($$0 ".trs"))) != 0) \ { \ if (rc < 0) \ { \ if ((getline line2 < ($$0 ".log")) < 0) \ recheck = 0; \ break; \ } \ else if (line ~ /$(am__recheck_rx)[nN][Oo]/) \ { \ recheck = 0; \ break; \ } \ else if (line ~ /$(am__recheck_rx)[yY][eE][sS]/) \ { \ break; \ } \ }; \ if (recheck) \ print $$0; \ close ($$0 ".trs"); \ close ($$0 ".log"); \ }' # A command that, given a newline-separated list of test names on the # standard input, create the global log from their .trs and .log files. am__create_global_log = $(AWK) ' \ function fatal(msg) \ { \ print "fatal: making $@: " msg | "cat >&2"; \ exit 1; \ } \ function rst_section(header) \ { \ print header; \ len = length(header); \ for (i = 1; i <= len; i = i + 1) \ printf "="; \ printf "\n\n"; \ } \ { \ copy_in_global_log = 1; \ global_test_result = "RUN"; \ while ((rc = (getline line < ($$0 ".trs"))) != 0) \ { \ if (rc < 0) \ fatal("failed to read from " $$0 ".trs"); \ if (line ~ /$(am__global_test_result_rx)/) \ { \ sub("$(am__global_test_result_rx)", "", line); \ sub("[ ]*$$", "", line); \ global_test_result = line; \ } \ else if (line ~ /$(am__copy_in_global_log_rx)[nN][oO]/) \ copy_in_global_log = 0; \ }; \ if (copy_in_global_log) \ { \ rst_section(global_test_result ": " $$0); \ while ((rc = (getline line < ($$0 ".log"))) != 0) \ { \ if (rc < 0) \ fatal("failed to read from " $$0 ".log"); \ print line; \ }; \ printf "\n"; \ }; \ close ($$0 ".trs"); \ close ($$0 ".log"); \ }' # Restructured Text title. am__rst_title = { sed 's/.*/ & /;h;s/./=/g;p;x;s/ *$$//;p;g' && echo; } # Solaris 10 'make', and several other traditional 'make' implementations, # pass "-e" to $(SHELL), and POSIX 2008 even requires this. Work around it # by disabling -e (using the XSI extension "set +e") if it's set. am__sh_e_setup = case $$- in *e*) set +e;; esac # Default flags passed to test drivers. am__common_driver_flags = \ --color-tests "$$am__color_tests" \ --enable-hard-errors "$$am__enable_hard_errors" \ --expect-failure "$$am__expect_failure" # To be inserted before the command running the test. Creates the # directory for the log if needed. Stores in $dir the directory # containing $f, in $tst the test, in $log the log. Executes the # developer- defined test setup AM_TESTS_ENVIRONMENT (if any), and # passes TESTS_ENVIRONMENT. Set up options for the wrapper that # will run the test scripts (or their associated LOG_COMPILER, if # thy have one). am__check_pre = \ $(am__sh_e_setup); \ $(am__vpath_adj_setup) $(am__vpath_adj) \ $(am__tty_colors); \ srcdir=$(srcdir); export srcdir; \ case "$@" in \ */*) am__odir=`echo "./$@" | sed 's|/[^/]*$$||'`;; \ *) am__odir=.;; \ esac; \ test "x$$am__odir" = x"." || test -d "$$am__odir" \ || $(MKDIR_P) "$$am__odir" || exit $$?; \ if test -f "./$$f"; then dir=./; \ elif test -f "$$f"; then dir=; \ else dir="$(srcdir)/"; fi; \ tst=$$dir$$f; log='$@'; \ if test -n '$(DISABLE_HARD_ERRORS)'; then \ am__enable_hard_errors=no; \ else \ am__enable_hard_errors=yes; \ fi; \ case " $(XFAIL_TESTS) " in \ *[\ \ ]$$f[\ \ ]* | *[\ \ ]$$dir$$f[\ \ ]*) \ am__expect_failure=yes;; \ *) \ am__expect_failure=no;; \ esac; \ $(AM_TESTS_ENVIRONMENT) $(TESTS_ENVIRONMENT) # A shell command to get the names of the tests scripts with any registered # extension removed (i.e., equivalently, the names of the test logs, with # the '.log' extension removed). The result is saved in the shell variable # '$bases'. This honors runtime overriding of TESTS and TEST_LOGS. Sadly, # we cannot use something simpler, involving e.g., "$(TEST_LOGS:.log=)", # since that might cause problem with VPATH rewrites for suffix-less tests. # See also 'test-harness-vpath-rewrite.sh' and 'test-trs-basic.sh'. am__set_TESTS_bases = \ bases='$(TEST_LOGS)'; \ bases=`for i in $$bases; do echo $$i; done | sed 's/\.log$$//'`; \ bases=`echo $$bases` RECHECK_LOGS = $(TEST_LOGS) AM_RECURSIVE_TARGETS = check recheck TEST_SUITE_LOG = test-suite.log TEST_EXTENSIONS = @EXEEXT@ .test LOG_DRIVER = $(SHELL) $(top_srcdir)/test-driver LOG_COMPILE = $(LOG_COMPILER) $(AM_LOG_FLAGS) $(LOG_FLAGS) am__set_b = \ case '$@' in \ */*) \ case '$*' in \ */*) b='$*';; \ *) b=`echo '$@' | sed 's/\.log$$//'`; \ esac;; \ *) \ b='$*';; \ esac am__test_logs1 = $(TESTS:=.log) am__test_logs2 = $(am__test_logs1:@EXEEXT@.log=.log) TEST_LOGS = $(am__test_logs2:.test.log=.log) TEST_LOG_DRIVER = $(SHELL) $(top_srcdir)/test-driver TEST_LOG_COMPILE = $(TEST_LOG_COMPILER) $(AM_TEST_LOG_FLAGS) \ $(TEST_LOG_FLAGS) am__DIST_COMMON = $(srcdir)/Makefile.in \ $(top_srcdir)/Makefile.am.common \ $(top_srcdir)/cf/Makefile.am.common $(top_srcdir)/depcomp \ $(top_srcdir)/test-driver DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST) ACLOCAL = @ACLOCAL@ AIX_EXTRA_KAFS = @AIX_EXTRA_KAFS@ AMTAR = @AMTAR@ AM_DEFAULT_VERBOSITY = @AM_DEFAULT_VERBOSITY@ AR = @AR@ AS = @AS@ ASN1_COMPILE = @ASN1_COMPILE@ ASN1_COMPILE_DEP = @ASN1_COMPILE_DEP@ AUTOCONF = @AUTOCONF@ AUTOHEADER = @AUTOHEADER@ AUTOMAKE = @AUTOMAKE@ AWK = @AWK@ CANONICAL_HOST = @CANONICAL_HOST@ CAPNG_CFLAGS = @CAPNG_CFLAGS@ CAPNG_LIBS = @CAPNG_LIBS@ CATMAN = @CATMAN@ CATMANEXT = @CATMANEXT@ CC = @CC@ CCDEPMODE = @CCDEPMODE@ CFLAGS = @CFLAGS@ COMPILE_ET = @COMPILE_ET@ CPP = @CPP@ CPPFLAGS = @CPPFLAGS@ CYGPATH_W = @CYGPATH_W@ DB1LIB = @DB1LIB@ DB3LIB = @DB3LIB@ DBHEADER = @DBHEADER@ DEFS = @DEFS@ DEPDIR = @DEPDIR@ DIR_com_err = @DIR_com_err@ DIR_hdbdir = @DIR_hdbdir@ DIR_roken = @DIR_roken@ DLLTOOL = @DLLTOOL@ DSYMUTIL = @DSYMUTIL@ DUMPBIN = @DUMPBIN@ ECHO_C = @ECHO_C@ ECHO_N = @ECHO_N@ ECHO_T = @ECHO_T@ EGREP = @EGREP@ ENABLE_AFS_STRING_TO_KEY = @ENABLE_AFS_STRING_TO_KEY@ EXEEXT = @EXEEXT@ FGREP = @FGREP@ GCD_MIG = @GCD_MIG@ GREP = @GREP@ GROFF = @GROFF@ INCLUDES_roken = @INCLUDES_roken@ INCLUDE_libedit = @INCLUDE_libedit@ INCLUDE_libintl = @INCLUDE_libintl@ INCLUDE_openldap = @INCLUDE_openldap@ INCLUDE_openssl_crypto = @INCLUDE_openssl_crypto@ INCLUDE_readline = @INCLUDE_readline@ INCLUDE_sqlite3 = @INCLUDE_sqlite3@ INSTALL = @INSTALL@ INSTALL_DATA = @INSTALL_DATA@ INSTALL_PROGRAM = @INSTALL_PROGRAM@ INSTALL_SCRIPT = @INSTALL_SCRIPT@ INSTALL_STRIP_PROGRAM = @INSTALL_STRIP_PROGRAM@ LD = @LD@ LDFLAGS = @LDFLAGS@ LDFLAGS_VERSION_SCRIPT = @LDFLAGS_VERSION_SCRIPT@ LEX = @LEX@ LEXLIB = @LEXLIB@ LEX_OUTPUT_ROOT = @LEX_OUTPUT_ROOT@ LIBADD_roken = @LIBADD_roken@ LIBOBJS = @LIBOBJS@ LIBS = @LIBS@ LIBTOOL = @LIBTOOL@ LIB_AUTH_SUBDIRS = @LIB_AUTH_SUBDIRS@ LIB_bswap16 = @LIB_bswap16@ LIB_bswap32 = @LIB_bswap32@ LIB_bswap64 = @LIB_bswap64@ LIB_com_err = @LIB_com_err@ LIB_com_err_a = @LIB_com_err_a@ LIB_com_err_so = @LIB_com_err_so@ LIB_crypt = @LIB_crypt@ LIB_db_create = @LIB_db_create@ LIB_dbm_firstkey = @LIB_dbm_firstkey@ LIB_dbopen = @LIB_dbopen@ LIB_dispatch_async_f = @LIB_dispatch_async_f@ LIB_dladdr = @LIB_dladdr@ LIB_dlopen = @LIB_dlopen@ LIB_dn_expand = @LIB_dn_expand@ LIB_dns_search = @LIB_dns_search@ LIB_door_create = @LIB_door_create@ LIB_freeaddrinfo = @LIB_freeaddrinfo@ LIB_gai_strerror = @LIB_gai_strerror@ LIB_getaddrinfo = @LIB_getaddrinfo@ LIB_gethostbyname = @LIB_gethostbyname@ LIB_gethostbyname2 = @LIB_gethostbyname2@ LIB_getnameinfo = @LIB_getnameinfo@ LIB_getpwnam_r = @LIB_getpwnam_r@ LIB_getsockopt = @LIB_getsockopt@ LIB_hcrypto = @LIB_hcrypto@ LIB_hcrypto_a = @LIB_hcrypto_a@ LIB_hcrypto_appl = @LIB_hcrypto_appl@ LIB_hcrypto_so = @LIB_hcrypto_so@ LIB_hstrerror = @LIB_hstrerror@ LIB_kdb = @LIB_kdb@ LIB_libedit = @LIB_libedit@ LIB_libintl = @LIB_libintl@ LIB_loadquery = @LIB_loadquery@ LIB_logout = @LIB_logout@ LIB_logwtmp = @LIB_logwtmp@ LIB_openldap = @LIB_openldap@ LIB_openpty = @LIB_openpty@ LIB_openssl_crypto = @LIB_openssl_crypto@ LIB_otp = @LIB_otp@ LIB_pidfile = @LIB_pidfile@ LIB_readline = @LIB_readline@ LIB_res_ndestroy = @LIB_res_ndestroy@ LIB_res_nsearch = @LIB_res_nsearch@ LIB_res_search = @LIB_res_search@ LIB_roken = @LIB_roken@ LIB_security = @LIB_security@ LIB_setsockopt = @LIB_setsockopt@ LIB_socket = @LIB_socket@ LIB_sqlite3 = @LIB_sqlite3@ LIB_syslog = @LIB_syslog@ LIB_tgetent = @LIB_tgetent@ LIPO = @LIPO@ LMDBLIB = @LMDBLIB@ LN_S = @LN_S@ LTLIBOBJS = @LTLIBOBJS@ LT_SYS_LIBRARY_PATH = @LT_SYS_LIBRARY_PATH@ MAINT = @MAINT@ MAKEINFO = @MAKEINFO@ MANIFEST_TOOL = @MANIFEST_TOOL@ MKDIR_P = @MKDIR_P@ NDBMLIB = @NDBMLIB@ NM = @NM@ NMEDIT = @NMEDIT@ NO_AFS = @NO_AFS@ NROFF = @NROFF@ OBJDUMP = @OBJDUMP@ OBJEXT = @OBJEXT@ OTOOL = @OTOOL@ OTOOL64 = @OTOOL64@ PACKAGE = @PACKAGE@ PACKAGE_BUGREPORT = @PACKAGE_BUGREPORT@ PACKAGE_NAME = @PACKAGE_NAME@ PACKAGE_STRING = @PACKAGE_STRING@ PACKAGE_TARNAME = @PACKAGE_TARNAME@ PACKAGE_URL = @PACKAGE_URL@ PACKAGE_VERSION = @PACKAGE_VERSION@ PATH_SEPARATOR = @PATH_SEPARATOR@ PERL = @PERL@ PKG_CONFIG = @PKG_CONFIG@ PTHREAD_CFLAGS = @PTHREAD_CFLAGS@ PTHREAD_LDADD = @PTHREAD_LDADD@ PTHREAD_LIBADD = @PTHREAD_LIBADD@ RANLIB = @RANLIB@ SED = @SED@ SET_MAKE = @SET_MAKE@ SHELL = @SHELL@ SLC = @SLC@ SLC_DEP = @SLC_DEP@ STRIP = @STRIP@ VERSION = @VERSION@ VERSIONING = @VERSIONING@ WFLAGS = @WFLAGS@ WFLAGS_LITE = @WFLAGS_LITE@ YACC = @YACC@ YFLAGS = @YFLAGS@ abs_builddir = @abs_builddir@ abs_srcdir = @abs_srcdir@ abs_top_builddir = @abs_top_builddir@ abs_top_srcdir = @abs_top_srcdir@ ac_ct_AR = @ac_ct_AR@ ac_ct_CC = @ac_ct_CC@ ac_ct_DUMPBIN = @ac_ct_DUMPBIN@ am__include = @am__include@ am__leading_dot = @am__leading_dot@ am__quote = @am__quote@ am__tar = @am__tar@ am__untar = @am__untar@ bindir = @bindir@ build = @build@ build_alias = @build_alias@ build_cpu = @build_cpu@ build_os = @build_os@ build_vendor = @build_vendor@ builddir = @builddir@ datadir = @datadir@ datarootdir = @datarootdir@ db_type = @db_type@ db_type_preference = @db_type_preference@ docdir = @docdir@ dpagaix_cflags = @dpagaix_cflags@ dpagaix_ldadd = @dpagaix_ldadd@ dpagaix_ldflags = @dpagaix_ldflags@ dvidir = @dvidir@ exec_prefix = @exec_prefix@ host = @host@ host_alias = @host_alias@ host_cpu = @host_cpu@ host_os = @host_os@ host_vendor = @host_vendor@ htmldir = @htmldir@ includedir = @includedir@ infodir = @infodir@ install_sh = @install_sh@ libdir = @libdir@ libexecdir = @libexecdir@ localedir = @localedir@ localstatedir = @localstatedir@ mandir = @mandir@ mkdir_p = @mkdir_p@ oldincludedir = @oldincludedir@ pdfdir = @pdfdir@ prefix = @prefix@ program_transform_name = @program_transform_name@ psdir = @psdir@ sbindir = @sbindir@ sharedstatedir = @sharedstatedir@ srcdir = @srcdir@ subdirs = @subdirs@ sysconfdir = @sysconfdir@ target_alias = @target_alias@ top_build_prefix = @top_build_prefix@ top_builddir = @top_builddir@ top_srcdir = @top_srcdir@ SUFFIXES = .et .h .pc.in .pc .x .z .hx .1 .3 .5 .7 .8 .cat1 .cat3 \ .cat5 .cat7 .cat8 DEFAULT_INCLUDES = -I. -I$(srcdir) -I$(top_builddir)/include -I$(top_srcdir)/include AM_CPPFLAGS = $(INCLUDES_roken) $(am__append_2) $(ROKEN_RENAME) @do_roken_rename_TRUE@ROKEN_RENAME = -DROKEN_RENAME AM_CFLAGS = $(WFLAGS) CP = cp buildinclude = $(top_builddir)/include LIB_XauReadAuth = @LIB_XauReadAuth@ LIB_el_init = @LIB_el_init@ LIB_getattr = @LIB_getattr@ LIB_getpwent_r = @LIB_getpwent_r@ LIB_odm_initialize = @LIB_odm_initialize@ LIB_setpcred = @LIB_setpcred@ INCLUDE_krb4 = @INCLUDE_krb4@ LIB_krb4 = @LIB_krb4@ libexec_heimdaldir = $(libexecdir)/heimdal NROFF_MAN = groff -mandoc -Tascii @NO_AFS_FALSE@LIB_kafs = $(top_builddir)/lib/kafs/libkafs.la $(AIX_EXTRA_KAFS) @NO_AFS_TRUE@LIB_kafs = @KRB5_TRUE@LIB_krb5 = $(top_builddir)/lib/krb5/libkrb5.la \ @KRB5_TRUE@ $(top_builddir)/lib/asn1/libasn1.la @KRB5_TRUE@LIB_gssapi = $(top_builddir)/lib/gssapi/libgssapi.la LIB_heimbase = $(top_builddir)/lib/base/libheimbase.la @DCE_TRUE@LIB_kdfs = $(top_builddir)/lib/kdfs/libkdfs.la #silent-rules heim_verbose = $(heim_verbose_$(V)) heim_verbose_ = $(heim_verbose_$(AM_DEFAULT_VERBOSITY)) heim_verbose_0 = @echo " GEN "$@; @do_roken_rename_TRUE@ES = base64.c IMPLEMENT_TLS = $(am__append_1) lib_LTLIBRARIES = libheimbase.la libheimbase_la_LDFLAGS = -version-info 1:0:0 $(am__append_3) libheimbase_la_LIBADD = $(PTHREAD_LIBADD) include_HEADERS = heimbase.h dist_libheimbase_la_SOURCES = \ array.c \ baselocl.h \ bsearch.c \ bool.c \ data.c \ db.c \ dict.c \ $(IMPLEMENT_TLS) \ error.c \ heimbase.c \ heimbasepriv.h \ heimqueue.h \ json.c \ null.c \ number.c \ roken_rename.h \ string.c nodist_libheimbase_la_SOURCES = $(ES) # install these? libheimbase_la_DEPENDENCIES = version-script.map test_base_LDADD = libheimbase.la $(LIB_roken) CLEANFILES = base64.c test_db.json EXTRA_DIST = NTMakefile version-script.map all: all-am .SUFFIXES: .SUFFIXES: .et .h .pc.in .pc .x .z .hx .1 .3 .5 .7 .8 .cat1 .cat3 .cat5 .cat7 .cat8 .c .lo .log .o .obj .test .test$(EXEEXT) .trs $(srcdir)/Makefile.in: @MAINTAINER_MODE_TRUE@ $(srcdir)/Makefile.am $(top_srcdir)/Makefile.am.common $(top_srcdir)/cf/Makefile.am.common $(am__configure_deps) @for dep in $?; do \ case '$(am__configure_deps)' in \ *$$dep*) \ ( cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh ) \ && { if test -f $@; then exit 0; else break; fi; }; \ exit 1;; \ esac; \ done; \ echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign lib/base/Makefile'; \ $(am__cd) $(top_srcdir) && \ $(AUTOMAKE) --foreign lib/base/Makefile Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status @case '$?' in \ *config.status*) \ cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh;; \ *) \ echo ' cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe)'; \ cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe);; \ esac; $(top_srcdir)/Makefile.am.common $(top_srcdir)/cf/Makefile.am.common $(am__empty): $(top_builddir)/config.status: $(top_srcdir)/configure $(CONFIG_STATUS_DEPENDENCIES) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(top_srcdir)/configure: @MAINTAINER_MODE_TRUE@ $(am__configure_deps) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(ACLOCAL_M4): @MAINTAINER_MODE_TRUE@ $(am__aclocal_m4_deps) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(am__aclocal_m4_deps): install-libLTLIBRARIES: $(lib_LTLIBRARIES) @$(NORMAL_INSTALL) @list='$(lib_LTLIBRARIES)'; test -n "$(libdir)" || list=; \ list2=; for p in $$list; do \ if test -f $$p; then \ list2="$$list2 $$p"; \ else :; fi; \ done; \ test -z "$$list2" || { \ echo " $(MKDIR_P) '$(DESTDIR)$(libdir)'"; \ $(MKDIR_P) "$(DESTDIR)$(libdir)" || exit 1; \ echo " $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=install $(INSTALL) $(INSTALL_STRIP_FLAG) $$list2 '$(DESTDIR)$(libdir)'"; \ $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=install $(INSTALL) $(INSTALL_STRIP_FLAG) $$list2 "$(DESTDIR)$(libdir)"; \ } uninstall-libLTLIBRARIES: @$(NORMAL_UNINSTALL) @list='$(lib_LTLIBRARIES)'; test -n "$(libdir)" || list=; \ for p in $$list; do \ $(am__strip_dir) \ echo " $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=uninstall rm -f '$(DESTDIR)$(libdir)/$$f'"; \ $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=uninstall rm -f "$(DESTDIR)$(libdir)/$$f"; \ done clean-libLTLIBRARIES: -test -z "$(lib_LTLIBRARIES)" || rm -f $(lib_LTLIBRARIES) @list='$(lib_LTLIBRARIES)'; \ locs=`for p in $$list; do echo $$p; done | \ sed 's|^[^/]*$$|.|; s|/[^/]*$$||; s|$$|/so_locations|' | \ sort -u`; \ test -z "$$locs" || { \ echo rm -f $${locs}; \ rm -f $${locs}; \ } libheimbase.la: $(libheimbase_la_OBJECTS) $(libheimbase_la_DEPENDENCIES) $(EXTRA_libheimbase_la_DEPENDENCIES) $(AM_V_CCLD)$(libheimbase_la_LINK) -rpath $(libdir) $(libheimbase_la_OBJECTS) $(libheimbase_la_LIBADD) $(LIBS) clean-checkPROGRAMS: @list='$(check_PROGRAMS)'; test -n "$$list" || exit 0; \ echo " rm -f" $$list; \ rm -f $$list || exit $$?; \ test -n "$(EXEEXT)" || exit 0; \ list=`for p in $$list; do echo "$$p"; done | sed 's/$(EXEEXT)$$//'`; \ echo " rm -f" $$list; \ rm -f $$list test_base$(EXEEXT): $(test_base_OBJECTS) $(test_base_DEPENDENCIES) $(EXTRA_test_base_DEPENDENCIES) @rm -f test_base$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_base_OBJECTS) $(test_base_LDADD) $(LIBS) mostlyclean-compile: -rm -f *.$(OBJEXT) distclean-compile: -rm -f *.tab.c @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/array.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/base64.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/bool.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/bsearch.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/data.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/db.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/dict.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/dll.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/error.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/heimbase.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/json.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/null.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/number.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/string.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_base.Po@am__quote@ .c.o: @am__fastdepCC_TRUE@ $(AM_V_CC)$(COMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o $@ $< @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='$<' object='$@' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(COMPILE) -c -o $@ $< .c.obj: @am__fastdepCC_TRUE@ $(AM_V_CC)$(COMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o $@ `$(CYGPATH_W) '$<'` @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='$<' object='$@' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(COMPILE) -c -o $@ `$(CYGPATH_W) '$<'` .c.lo: @am__fastdepCC_TRUE@ $(AM_V_CC)$(LTCOMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o $@ $< @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='$<' object='$@' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LTCOMPILE) -c -o $@ $< mostlyclean-libtool: -rm -f *.lo clean-libtool: -rm -rf .libs _libs install-includeHEADERS: $(include_HEADERS) @$(NORMAL_INSTALL) @list='$(include_HEADERS)'; test -n "$(includedir)" || list=; \ if test -n "$$list"; then \ echo " $(MKDIR_P) '$(DESTDIR)$(includedir)'"; \ $(MKDIR_P) "$(DESTDIR)$(includedir)" || exit 1; \ fi; \ for p in $$list; do \ if test -f "$$p"; then d=; else d="$(srcdir)/"; fi; \ echo "$$d$$p"; \ done | $(am__base_list) | \ while read files; do \ echo " $(INSTALL_HEADER) $$files '$(DESTDIR)$(includedir)'"; \ $(INSTALL_HEADER) $$files "$(DESTDIR)$(includedir)" || exit $$?; \ done uninstall-includeHEADERS: @$(NORMAL_UNINSTALL) @list='$(include_HEADERS)'; test -n "$(includedir)" || list=; \ files=`for p in $$list; do echo $$p; done | sed -e 's|^.*/||'`; \ dir='$(DESTDIR)$(includedir)'; $(am__uninstall_files_from_dir) ID: $(am__tagged_files) $(am__define_uniq_tagged_files); mkid -fID $$unique tags: tags-am TAGS: tags tags-am: $(TAGS_DEPENDENCIES) $(am__tagged_files) set x; \ here=`pwd`; \ $(am__define_uniq_tagged_files); \ shift; \ if test -z "$(ETAGS_ARGS)$$*$$unique"; then :; else \ test -n "$$unique" || unique=$$empty_fix; \ if test $$# -gt 0; then \ $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ "$$@" $$unique; \ else \ $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ $$unique; \ fi; \ fi ctags: ctags-am CTAGS: ctags ctags-am: $(TAGS_DEPENDENCIES) $(am__tagged_files) $(am__define_uniq_tagged_files); \ test -z "$(CTAGS_ARGS)$$unique" \ || $(CTAGS) $(CTAGSFLAGS) $(AM_CTAGSFLAGS) $(CTAGS_ARGS) \ $$unique GTAGS: here=`$(am__cd) $(top_builddir) && pwd` \ && $(am__cd) $(top_srcdir) \ && gtags -i $(GTAGS_ARGS) "$$here" cscopelist: cscopelist-am cscopelist-am: $(am__tagged_files) list='$(am__tagged_files)'; \ case "$(srcdir)" in \ [\\/]* | ?:[\\/]*) sdir="$(srcdir)" ;; \ *) sdir=$(subdir)/$(srcdir) ;; \ esac; \ for i in $$list; do \ if test -f "$$i"; then \ echo "$(subdir)/$$i"; \ else \ echo "$$sdir/$$i"; \ fi; \ done >> $(top_builddir)/cscope.files distclean-tags: -rm -f TAGS ID GTAGS GRTAGS GSYMS GPATH tags # Recover from deleted '.trs' file; this should ensure that # "rm -f foo.log; make foo.trs" re-run 'foo.test', and re-create # both 'foo.log' and 'foo.trs'. Break the recipe in two subshells # to avoid problems with "make -n". .log.trs: rm -f $< $@ $(MAKE) $(AM_MAKEFLAGS) $< # Leading 'am--fnord' is there to ensure the list of targets does not # expand to empty, as could happen e.g. with make check TESTS=''. am--fnord $(TEST_LOGS) $(TEST_LOGS:.log=.trs): $(am__force_recheck) am--force-recheck: @: $(TEST_SUITE_LOG): $(TEST_LOGS) @$(am__set_TESTS_bases); \ am__f_ok () { test -f "$$1" && test -r "$$1"; }; \ redo_bases=`for i in $$bases; do \ am__f_ok $$i.trs && am__f_ok $$i.log || echo $$i; \ done`; \ if test -n "$$redo_bases"; then \ redo_logs=`for i in $$redo_bases; do echo $$i.log; done`; \ redo_results=`for i in $$redo_bases; do echo $$i.trs; done`; \ if $(am__make_dryrun); then :; else \ rm -f $$redo_logs && rm -f $$redo_results || exit 1; \ fi; \ fi; \ if test -n "$$am__remaking_logs"; then \ echo "fatal: making $(TEST_SUITE_LOG): possible infinite" \ "recursion detected" >&2; \ elif test -n "$$redo_logs"; then \ am__remaking_logs=yes $(MAKE) $(AM_MAKEFLAGS) $$redo_logs; \ fi; \ if $(am__make_dryrun); then :; else \ st=0; \ errmsg="fatal: making $(TEST_SUITE_LOG): failed to create"; \ for i in $$redo_bases; do \ test -f $$i.trs && test -r $$i.trs \ || { echo "$$errmsg $$i.trs" >&2; st=1; }; \ test -f $$i.log && test -r $$i.log \ || { echo "$$errmsg $$i.log" >&2; st=1; }; \ done; \ test $$st -eq 0 || exit 1; \ fi @$(am__sh_e_setup); $(am__tty_colors); $(am__set_TESTS_bases); \ ws='[ ]'; \ results=`for b in $$bases; do echo $$b.trs; done`; \ test -n "$$results" || results=/dev/null; \ all=` grep "^$$ws*:test-result:" $$results | wc -l`; \ pass=` grep "^$$ws*:test-result:$$ws*PASS" $$results | wc -l`; \ fail=` grep "^$$ws*:test-result:$$ws*FAIL" $$results | wc -l`; \ skip=` grep "^$$ws*:test-result:$$ws*SKIP" $$results | wc -l`; \ xfail=`grep "^$$ws*:test-result:$$ws*XFAIL" $$results | wc -l`; \ xpass=`grep "^$$ws*:test-result:$$ws*XPASS" $$results | wc -l`; \ error=`grep "^$$ws*:test-result:$$ws*ERROR" $$results | wc -l`; \ if test `expr $$fail + $$xpass + $$error` -eq 0; then \ success=true; \ else \ success=false; \ fi; \ br='==================='; br=$$br$$br$$br$$br; \ result_count () \ { \ if test x"$$1" = x"--maybe-color"; then \ maybe_colorize=yes; \ elif test x"$$1" = x"--no-color"; then \ maybe_colorize=no; \ else \ echo "$@: invalid 'result_count' usage" >&2; exit 4; \ fi; \ shift; \ desc=$$1 count=$$2; \ if test $$maybe_colorize = yes && test $$count -gt 0; then \ color_start=$$3 color_end=$$std; \ else \ color_start= color_end=; \ fi; \ echo "$${color_start}# $$desc $$count$${color_end}"; \ }; \ create_testsuite_report () \ { \ result_count $$1 "TOTAL:" $$all "$$brg"; \ result_count $$1 "PASS: " $$pass "$$grn"; \ result_count $$1 "SKIP: " $$skip "$$blu"; \ result_count $$1 "XFAIL:" $$xfail "$$lgn"; \ result_count $$1 "FAIL: " $$fail "$$red"; \ result_count $$1 "XPASS:" $$xpass "$$red"; \ result_count $$1 "ERROR:" $$error "$$mgn"; \ }; \ { \ echo "$(PACKAGE_STRING): $(subdir)/$(TEST_SUITE_LOG)" | \ $(am__rst_title); \ create_testsuite_report --no-color; \ echo; \ echo ".. contents:: :depth: 2"; \ echo; \ for b in $$bases; do echo $$b; done \ | $(am__create_global_log); \ } >$(TEST_SUITE_LOG).tmp || exit 1; \ mv $(TEST_SUITE_LOG).tmp $(TEST_SUITE_LOG); \ if $$success; then \ col="$$grn"; \ else \ col="$$red"; \ test x"$$VERBOSE" = x || cat $(TEST_SUITE_LOG); \ fi; \ echo "$${col}$$br$${std}"; \ echo "$${col}Testsuite summary for $(PACKAGE_STRING)$${std}"; \ echo "$${col}$$br$${std}"; \ create_testsuite_report --maybe-color; \ echo "$$col$$br$$std"; \ if $$success; then :; else \ echo "$${col}See $(subdir)/$(TEST_SUITE_LOG)$${std}"; \ if test -n "$(PACKAGE_BUGREPORT)"; then \ echo "$${col}Please report to $(PACKAGE_BUGREPORT)$${std}"; \ fi; \ echo "$$col$$br$$std"; \ fi; \ $$success || exit 1 check-TESTS: @list='$(RECHECK_LOGS)'; test -z "$$list" || rm -f $$list @list='$(RECHECK_LOGS:.log=.trs)'; test -z "$$list" || rm -f $$list @test -z "$(TEST_SUITE_LOG)" || rm -f $(TEST_SUITE_LOG) @set +e; $(am__set_TESTS_bases); \ log_list=`for i in $$bases; do echo $$i.log; done`; \ trs_list=`for i in $$bases; do echo $$i.trs; done`; \ log_list=`echo $$log_list`; trs_list=`echo $$trs_list`; \ $(MAKE) $(AM_MAKEFLAGS) $(TEST_SUITE_LOG) TEST_LOGS="$$log_list"; \ exit $$?; recheck: all $(check_PROGRAMS) @test -z "$(TEST_SUITE_LOG)" || rm -f $(TEST_SUITE_LOG) @set +e; $(am__set_TESTS_bases); \ bases=`for i in $$bases; do echo $$i; done \ | $(am__list_recheck_tests)` || exit 1; \ log_list=`for i in $$bases; do echo $$i.log; done`; \ log_list=`echo $$log_list`; \ $(MAKE) $(AM_MAKEFLAGS) $(TEST_SUITE_LOG) \ am__force_recheck=am--force-recheck \ TEST_LOGS="$$log_list"; \ exit $$? test_base.log: test_base$(EXEEXT) @p='test_base$(EXEEXT)'; \ b='test_base'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) .test.log: @p='$<'; \ $(am__set_b); \ $(am__check_pre) $(TEST_LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_TEST_LOG_DRIVER_FLAGS) $(TEST_LOG_DRIVER_FLAGS) -- $(TEST_LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) @am__EXEEXT_TRUE@.test$(EXEEXT).log: @am__EXEEXT_TRUE@ @p='$<'; \ @am__EXEEXT_TRUE@ $(am__set_b); \ @am__EXEEXT_TRUE@ $(am__check_pre) $(TEST_LOG_DRIVER) --test-name "$$f" \ @am__EXEEXT_TRUE@ --log-file $$b.log --trs-file $$b.trs \ @am__EXEEXT_TRUE@ $(am__common_driver_flags) $(AM_TEST_LOG_DRIVER_FLAGS) $(TEST_LOG_DRIVER_FLAGS) -- $(TEST_LOG_COMPILE) \ @am__EXEEXT_TRUE@ "$$tst" $(AM_TESTS_FD_REDIRECT) distdir: $(DISTFILES) @srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ topsrcdirstrip=`echo "$(top_srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ list='$(DISTFILES)'; \ dist_files=`for file in $$list; do echo $$file; done | \ sed -e "s|^$$srcdirstrip/||;t" \ -e "s|^$$topsrcdirstrip/|$(top_builddir)/|;t"`; \ case $$dist_files in \ */*) $(MKDIR_P) `echo "$$dist_files" | \ sed '/\//!d;s|^|$(distdir)/|;s,/[^/]*$$,,' | \ sort -u` ;; \ esac; \ for file in $$dist_files; do \ if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \ if test -d $$d/$$file; then \ dir=`echo "/$$file" | sed -e 's,/[^/]*$$,,'`; \ if test -d "$(distdir)/$$file"; then \ find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ fi; \ if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \ cp -fpR $(srcdir)/$$file "$(distdir)$$dir" || exit 1; \ find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ fi; \ cp -fpR $$d/$$file "$(distdir)$$dir" || exit 1; \ else \ test -f "$(distdir)/$$file" \ || cp -p $$d/$$file "$(distdir)/$$file" \ || exit 1; \ fi; \ done $(MAKE) $(AM_MAKEFLAGS) \ top_distdir="$(top_distdir)" distdir="$(distdir)" \ dist-hook check-am: all-am $(MAKE) $(AM_MAKEFLAGS) $(check_PROGRAMS) $(MAKE) $(AM_MAKEFLAGS) check-TESTS check-local check: check-am all-am: Makefile $(LTLIBRARIES) $(HEADERS) all-local installdirs: for dir in "$(DESTDIR)$(libdir)" "$(DESTDIR)$(includedir)"; do \ test -z "$$dir" || $(MKDIR_P) "$$dir"; \ done install: install-am install-exec: install-exec-am install-data: install-data-am uninstall: uninstall-am install-am: all-am @$(MAKE) $(AM_MAKEFLAGS) install-exec-am install-data-am installcheck: installcheck-am install-strip: if test -z '$(STRIP)'; then \ $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ install; \ else \ $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'" install; \ fi mostlyclean-generic: -test -z "$(TEST_LOGS)" || rm -f $(TEST_LOGS) -test -z "$(TEST_LOGS:.log=.trs)" || rm -f $(TEST_LOGS:.log=.trs) -test -z "$(TEST_SUITE_LOG)" || rm -f $(TEST_SUITE_LOG) clean-generic: -test -z "$(CLEANFILES)" || rm -f $(CLEANFILES) distclean-generic: -test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES) -test . = "$(srcdir)" || test -z "$(CONFIG_CLEAN_VPATH_FILES)" || rm -f $(CONFIG_CLEAN_VPATH_FILES) maintainer-clean-generic: @echo "This command is intended for maintainers to use" @echo "it deletes files that may require special tools to rebuild." clean: clean-am clean-am: clean-checkPROGRAMS clean-generic clean-libLTLIBRARIES \ clean-libtool mostlyclean-am distclean: distclean-am -rm -rf ./$(DEPDIR) -rm -f Makefile distclean-am: clean-am distclean-compile distclean-generic \ distclean-tags dvi: dvi-am dvi-am: html: html-am html-am: info: info-am info-am: install-data-am: install-includeHEADERS @$(NORMAL_INSTALL) $(MAKE) $(AM_MAKEFLAGS) install-data-hook install-dvi: install-dvi-am install-dvi-am: install-exec-am: install-exec-local install-libLTLIBRARIES install-html: install-html-am install-html-am: install-info: install-info-am install-info-am: install-man: install-pdf: install-pdf-am install-pdf-am: install-ps: install-ps-am install-ps-am: installcheck-am: maintainer-clean: maintainer-clean-am -rm -rf ./$(DEPDIR) -rm -f Makefile maintainer-clean-am: distclean-am maintainer-clean-generic mostlyclean: mostlyclean-am mostlyclean-am: mostlyclean-compile mostlyclean-generic \ mostlyclean-libtool pdf: pdf-am pdf-am: ps: ps-am ps-am: uninstall-am: uninstall-includeHEADERS uninstall-libLTLIBRARIES @$(NORMAL_INSTALL) $(MAKE) $(AM_MAKEFLAGS) uninstall-hook .MAKE: check-am install-am install-data-am install-strip uninstall-am .PHONY: CTAGS GTAGS TAGS all all-am all-local check check-TESTS \ check-am check-local clean clean-checkPROGRAMS clean-generic \ clean-libLTLIBRARIES clean-libtool cscopelist-am ctags \ ctags-am dist-hook distclean distclean-compile \ distclean-generic distclean-libtool distclean-tags distdir dvi \ dvi-am html html-am info info-am install install-am \ install-data install-data-am install-data-hook install-dvi \ install-dvi-am install-exec install-exec-am install-exec-local \ install-html install-html-am install-includeHEADERS \ install-info install-info-am install-libLTLIBRARIES \ install-man install-pdf install-pdf-am install-ps \ install-ps-am install-strip installcheck installcheck-am \ installdirs maintainer-clean maintainer-clean-generic \ mostlyclean mostlyclean-compile mostlyclean-generic \ mostlyclean-libtool pdf pdf-am ps ps-am recheck tags tags-am \ uninstall uninstall-am uninstall-hook uninstall-includeHEADERS \ uninstall-libLTLIBRARIES .PRECIOUS: Makefile install-suid-programs: @foo='$(bin_SUIDS)'; \ for file in $$foo; do \ x=$(DESTDIR)$(bindir)/$$file; \ if chown 0:0 $$x && chmod u+s $$x; then :; else \ echo "*"; \ echo "* Failed to install $$x setuid root"; \ echo "*"; \ fi; \ done install-exec-local: install-suid-programs codesign-all: @if [ X"$$CODE_SIGN_IDENTITY" != X ] ; then \ foo='$(bin_PROGRAMS) $(sbin_PROGRAMS) $(libexec_PROGRAMS)' ; \ for file in $$foo ; do \ echo "CODESIGN $$file" ; \ codesign -f -s "$$CODE_SIGN_IDENTITY" $$file || exit 1 ; \ done ; \ fi all-local: codesign-all install-build-headers:: $(include_HEADERS) $(dist_include_HEADERS) $(nodist_include_HEADERS) $(build_HEADERZ) $(nobase_include_HEADERS) $(noinst_HEADERS) @foo='$(include_HEADERS) $(dist_include_HEADERS) $(nodist_include_HEADERS) $(build_HEADERZ) $(noinst_HEADERS)'; \ for f in $$foo; do \ f=`basename $$f`; \ if test -f "$(srcdir)/$$f"; then file="$(srcdir)/$$f"; \ else file="$$f"; fi; \ if cmp -s $$file $(buildinclude)/$$f 2> /dev/null ; then \ : ; else \ echo " $(CP) $$file $(buildinclude)/$$f"; \ $(CP) $$file $(buildinclude)/$$f || true; \ fi ; \ done ; \ foo='$(nobase_include_HEADERS)'; \ for f in $$foo; do \ if test -f "$(srcdir)/$$f"; then file="$(srcdir)/$$f"; \ else file="$$f"; fi; \ $(mkdir_p) $(buildinclude)/`dirname $$f` ; \ if cmp -s $$file $(buildinclude)/$$f 2> /dev/null ; then \ : ; else \ echo " $(CP) $$file $(buildinclude)/$$f"; \ $(CP) $$file $(buildinclude)/$$f; \ fi ; \ done all-local: install-build-headers check-local:: @if test '$(CHECK_LOCAL)' = "no-check-local"; then \ foo=''; elif test '$(CHECK_LOCAL)'; then \ foo='$(CHECK_LOCAL)'; else \ foo='$(PROGRAMS)'; fi; \ if test "$$foo"; then \ failed=0; all=0; \ for i in $$foo; do \ all=`expr $$all + 1`; \ if (./$$i --version && ./$$i --help) > /dev/null 2>&1; then \ echo "PASS: $$i"; \ else \ echo "FAIL: $$i"; \ failed=`expr $$failed + 1`; \ fi; \ done; \ if test "$$failed" -eq 0; then \ banner="All $$all tests passed"; \ else \ banner="$$failed of $$all tests failed"; \ fi; \ dashes=`echo "$$banner" | sed s/./=/g`; \ echo "$$dashes"; \ echo "$$banner"; \ echo "$$dashes"; \ test "$$failed" -eq 0 || exit 1; \ fi .x.c: @cmp -s $< $@ 2> /dev/null || cp $< $@ .hx.h: @cmp -s $< $@ 2> /dev/null || cp $< $@ #NROFF_MAN = nroff -man .1.cat1: $(NROFF_MAN) $< > $@ .3.cat3: $(NROFF_MAN) $< > $@ .5.cat5: $(NROFF_MAN) $< > $@ .7.cat7: $(NROFF_MAN) $< > $@ .8.cat8: $(NROFF_MAN) $< > $@ dist-cat1-mans: @foo='$(man1_MANS)'; \ bar='$(man_MANS)'; \ for i in $$bar; do \ case $$i in \ *.1) foo="$$foo $$i";; \ esac; done ;\ for i in $$foo; do \ x=`echo $$i | sed 's/\.[^.]*$$/.cat1/'`; \ echo "$(NROFF_MAN) $(srcdir)/$$i > $(distdir)/$$x"; \ $(NROFF_MAN) $(srcdir)/$$i > $(distdir)/$$x; \ done dist-cat3-mans: @foo='$(man3_MANS)'; \ bar='$(man_MANS)'; \ for i in $$bar; do \ case $$i in \ *.3) foo="$$foo $$i";; \ esac; done ;\ for i in $$foo; do \ x=`echo $$i | sed 's/\.[^.]*$$/.cat3/'`; \ echo "$(NROFF_MAN) $(srcdir)/$$i > $(distdir)/$$x"; \ $(NROFF_MAN) $(srcdir)/$$i > $(distdir)/$$x; \ done dist-cat5-mans: @foo='$(man5_MANS)'; \ bar='$(man_MANS)'; \ for i in $$bar; do \ case $$i in \ *.5) foo="$$foo $$i";; \ esac; done ;\ for i in $$foo; do \ x=`echo $$i | sed 's/\.[^.]*$$/.cat5/'`; \ echo "$(NROFF_MAN) $(srcdir)/$$i > $(distdir)/$$x"; \ $(NROFF_MAN) $(srcdir)/$$i > $(distdir)/$$x; \ done dist-cat7-mans: @foo='$(man7_MANS)'; \ bar='$(man_MANS)'; \ for i in $$bar; do \ case $$i in \ *.7) foo="$$foo $$i";; \ esac; done ;\ for i in $$foo; do \ x=`echo $$i | sed 's/\.[^.]*$$/.cat7/'`; \ echo "$(NROFF_MAN) $(srcdir)/$$i > $(distdir)/$$x"; \ $(NROFF_MAN) $(srcdir)/$$i > $(distdir)/$$x; \ done dist-cat8-mans: @foo='$(man8_MANS)'; \ bar='$(man_MANS)'; \ for i in $$bar; do \ case $$i in \ *.8) foo="$$foo $$i";; \ esac; done ;\ for i in $$foo; do \ x=`echo $$i | sed 's/\.[^.]*$$/.cat8/'`; \ echo "$(NROFF_MAN) $(srcdir)/$$i > $(distdir)/$$x"; \ $(NROFF_MAN) $(srcdir)/$$i > $(distdir)/$$x; \ done dist-hook: dist-cat1-mans dist-cat3-mans dist-cat5-mans dist-cat7-mans dist-cat8-mans install-cat-mans: $(SHELL) $(top_srcdir)/cf/install-catman.sh install "$(INSTALL_DATA)" "$(mkinstalldirs)" "$(srcdir)" "$(DESTDIR)$(mandir)" '$(CATMANEXT)' $(man_MANS) $(man1_MANS) $(man3_MANS) $(man5_MANS) $(man7_MANS) $(man8_MANS) uninstall-cat-mans: $(SHELL) $(top_srcdir)/cf/install-catman.sh uninstall "$(INSTALL_DATA)" "$(mkinstalldirs)" "$(srcdir)" "$(DESTDIR)$(mandir)" '$(CATMANEXT)' $(man_MANS) $(man1_MANS) $(man3_MANS) $(man5_MANS) $(man7_MANS) $(man8_MANS) install-data-hook: install-cat-mans uninstall-hook: uninstall-cat-mans .et.h: $(COMPILE_ET) $< .et.c: $(COMPILE_ET) $< # # Useful target for debugging # check-valgrind: tobjdir=`cd $(top_builddir) && pwd` ; \ tsrcdir=`cd $(top_srcdir) && pwd` ; \ env TESTS_ENVIRONMENT="$${tsrcdir}/cf/maybe-valgrind.sh -s $${tsrcdir} -o $${tobjdir}" make check # # Target to please samba build farm, builds distfiles in-tree. # Will break when automake changes... # distdir-in-tree: $(DISTFILES) $(INFO_DEPS) list='$(DIST_SUBDIRS)'; for subdir in $$list; do \ if test "$$subdir" != .; then \ (cd $$subdir && $(MAKE) $(AM_MAKEFLAGS) distdir-in-tree) ; \ fi ; \ done base64.c: rm -f base64.c $(LN_S) $(srcdir)/../roken/base64.c . # Tell versions [3.59,3.63) of GNU make to not export all variables. # Otherwise a system limit (for SysV at least) may be exceeded. .NOEXPORT: heimdal-7.5.0/lib/base/array.c0000644000175000017500000002635313026237312014224 0ustar niknik/* * Copyright (c) 2010 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Portions Copyright (c) 2010 Apple Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "baselocl.h" /* * */ struct heim_array_data { size_t len; heim_object_t *val; size_t allocated_len; heim_object_t *allocated; }; static void array_dealloc(heim_object_t ptr) { heim_array_t array = ptr; size_t n; for (n = 0; n < array->len; n++) heim_release(array->val[n]); free(array->allocated); } struct heim_type_data array_object = { HEIM_TID_ARRAY, "dict-object", NULL, array_dealloc, NULL, NULL, NULL, NULL }; /** * Allocate an array * * @return A new allocated array, free with heim_release() */ heim_array_t heim_array_create(void) { heim_array_t array; array = _heim_alloc_object(&array_object, sizeof(*array)); if (array == NULL) return NULL; array->allocated = NULL; array->allocated_len = 0; array->val = NULL; array->len = 0; return array; } /** * Get type id of an dict * * @return the type id */ heim_tid_t heim_array_get_type_id(void) { return HEIM_TID_ARRAY; } /** * Append object to array * * @param array array to add too * @param object the object to add * * @return zero if added, errno otherwise */ int heim_array_append_value(heim_array_t array, heim_object_t object) { heim_object_t *ptr; size_t leading = array->val - array->allocated; /* unused leading slots */ size_t trailing = array->allocated_len - array->len - leading; size_t new_len; if (trailing > 0) { /* We have pre-allocated space; use it */ array->val[array->len++] = heim_retain(object); return 0; } if (leading > (array->len + 1)) { /* * We must have appending to, and deleting at index 0 from this * array a lot; don't want to grow forever! */ (void) memmove(&array->allocated[0], &array->val[0], array->len * sizeof(array->val[0])); array->val = array->allocated; /* We have pre-allocated space; use it */ array->val[array->len++] = heim_retain(object); return 0; } /* Pre-allocate extra .5 times number of used slots */ new_len = leading + array->len + 1 + (array->len >> 1); ptr = realloc(array->allocated, new_len * sizeof(array->val[0])); if (ptr == NULL) return ENOMEM; array->allocated = ptr; array->allocated_len = new_len; array->val = &ptr[leading]; array->val[array->len++] = heim_retain(object); return 0; } /* * Internal function to insert at index 0, taking care to optimize the * case where we're always inserting at index 0, particularly the case * where we insert at index 0 and delete from the right end. */ static int heim_array_prepend_value(heim_array_t array, heim_object_t object) { heim_object_t *ptr; size_t leading = array->val - array->allocated; /* unused leading slots */ size_t trailing = array->allocated_len - array->len - leading; size_t new_len; if (leading > 0) { /* We have pre-allocated space; use it */ array->val--; array->val[0] = heim_retain(object); array->len++; return 0; } if (trailing > (array->len + 1)) { /* * We must have prepending to, and deleting at index * array->len - 1 from this array a lot; don't want to grow * forever! */ (void) memmove(&array->allocated[array->len], &array->val[0], array->len * sizeof(array->val[0])); array->val = &array->allocated[array->len]; /* We have pre-allocated space; use it */ array->val--; array->val[0] = heim_retain(object); array->len++; return 0; } /* Pre-allocate extra .5 times number of used slots */ new_len = array->len + 1 + trailing + (array->len >> 1); ptr = realloc(array->allocated, new_len * sizeof(array->val[0])); if (ptr == NULL) return ENOMEM; (void) memmove(&ptr[1], &ptr[0], array->len * sizeof (array->val[0])); array->allocated = ptr; array->allocated_len = new_len; array->val = &ptr[0]; array->val[0] = heim_retain(object); array->len++; return 0; } /** * Insert an object at a given index in an array * * @param array array to add too * @param idx index where to add element (-1 == append, -2 next to last, ...) * @param object the object to add * * @return zero if added, errno otherwise */ int heim_array_insert_value(heim_array_t array, size_t idx, heim_object_t object) { int ret; if (idx == 0) return heim_array_prepend_value(array, object); else if (idx > array->len) heim_abort("index too large"); /* * We cheat: append this element then rotate elements around so we * have this new element at the desired location, unless we're truly * appending the new element. This means reusing array growth in * heim_array_append_value() instead of duplicating that here. */ ret = heim_array_append_value(array, object); if (ret != 0 || idx == (array->len - 1)) return ret; /* * Shift to the right by one all the elements after idx, then set * [idx] to the new object. */ (void) memmove(&array->val[idx + 1], &array->val[idx], (array->len - idx - 1) * sizeof(array->val[0])); array->val[idx] = heim_retain(object); return 0; } /** * Iterate over all objects in array * * @param array array to iterate over * @param ctx context passed to fn * @param fn function to call on each object */ void heim_array_iterate_f(heim_array_t array, void *ctx, heim_array_iterator_f_t fn) { size_t n; int stop = 0; for (n = 0; n < array->len; n++) { fn(array->val[n], ctx, &stop); if (stop) return; } } #ifdef __BLOCKS__ /** * Iterate over all objects in array * * @param array array to iterate over * @param fn block to call on each object */ void heim_array_iterate(heim_array_t array, void (^fn)(heim_object_t, int *)) { size_t n; int stop = 0; for (n = 0; n < array->len; n++) { fn(array->val[n], &stop); if (stop) return; } } #endif /** * Iterate over all objects in array, backwards * * @param array array to iterate over * @param ctx context passed to fn * @param fn function to call on each object */ void heim_array_iterate_reverse_f(heim_array_t array, void *ctx, heim_array_iterator_f_t fn) { size_t n; int stop = 0; for (n = array->len; n > 0; n--) { fn(array->val[n - 1], ctx, &stop); if (stop) return; } } #ifdef __BLOCKS__ /** * Iterate over all objects in array, backwards * * @param array array to iterate over * @param fn block to call on each object */ void heim_array_iterate_reverse(heim_array_t array, void (^fn)(heim_object_t, int *)) { size_t n; int stop = 0; for (n = array->len; n > 0; n--) { fn(array->val[n - 1], &stop); if (stop) return; } } #endif /** * Get length of array * * @param array array to get length of * * @return length of array */ size_t heim_array_get_length(heim_array_t array) { return array->len; } /** * Get value of element at array index * * @param array array copy object from * @param idx index of object, 0 based, must be smaller then * heim_array_get_length() * * @return a not-retained copy of the object */ heim_object_t heim_array_get_value(heim_array_t array, size_t idx) { if (idx >= array->len) heim_abort("index too large"); return array->val[idx]; } /** * Get value of element at array index * * @param array array copy object from * @param idx index of object, 0 based, must be smaller then * heim_array_get_length() * * @return a retained copy of the object */ heim_object_t heim_array_copy_value(heim_array_t array, size_t idx) { if (idx >= array->len) heim_abort("index too large"); return heim_retain(array->val[idx]); } /** * Set value at array index * * @param array array copy object from * @param idx index of object, 0 based, must be smaller then * heim_array_get_length() * @param value value to set * */ void heim_array_set_value(heim_array_t array, size_t idx, heim_object_t value) { if (idx >= array->len) heim_abort("index too large"); heim_release(array->val[idx]); array->val[idx] = heim_retain(value); } /** * Delete value at idx * * @param array the array to modify * @param idx the key to delete */ void heim_array_delete_value(heim_array_t array, size_t idx) { heim_object_t obj; if (idx >= array->len) heim_abort("index too large"); obj = array->val[idx]; array->len--; /* * Deleting the first or last elements is cheap, as we leave * allocated space for opportunistic reuse later; no realloc(), no * memmove(). All others require a memmove(). * * If we ever need to optimize deletion of non-last/ non-first * element we can use a tagged object type to signify "deleted * value" so we can leave holes in the array, avoid memmove()s on * delete, and opportunistically re-use those holes on insert. */ if (idx == 0) array->val++; else if (idx < array->len) (void) memmove(&array->val[idx], &array->val[idx + 1], (array->len - idx) * sizeof(array->val[0])); heim_release(obj); } /** * Filter out entres of array when function return true * * @param array the array to modify * @param fn filter function */ void heim_array_filter_f(heim_array_t array, void *ctx, heim_array_filter_f_t fn) { size_t n = 0; while (n < array->len) { if (fn(array->val[n], ctx)) { heim_array_delete_value(array, n); } else { n++; } } } #ifdef __BLOCKS__ /** * Filter out entres of array when block return true * * @param array the array to modify * @param block filter block */ void heim_array_filter(heim_array_t array, int (^block)(heim_object_t)) { size_t n = 0; while (n < array->len) { if (block(array->val[n])) { heim_array_delete_value(array, n); } else { n++; } } } #endif /* __BLOCKS__ */ heimdal-7.5.0/lib/base/heimbasepriv.h0000644000175000017500000000735413026237312015571 0ustar niknik/* * Copyright (c) 2010 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Portions Copyright (c) 2010 Apple Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #if defined(HEIM_BASE_MAINTAINER) && defined(ENABLE_PTHREAD_SUPPORT) #define HEIM_WIN32_TLS #elif defined(WIN32) #define HEIM_WIN32_TLS #endif typedef void (*heim_type_init)(void *); typedef heim_object_t (*heim_type_copy)(void *); typedef int (*heim_type_cmp)(void *, void *); typedef unsigned long (*heim_type_hash)(void *); typedef heim_string_t (*heim_type_description)(void *); typedef struct heim_type_data *heim_type_t; enum { HEIM_TID_NUMBER = 0, HEIM_TID_NULL = 1, HEIM_TID_BOOL = 2, HEIM_TID_TAGGED_UNUSED2 = 3, /* reserved for tagged object types */ HEIM_TID_TAGGED_UNUSED3 = 4, /* reserved for tagged object types */ HEIM_TID_TAGGED_UNUSED4 = 5, /* reserved for tagged object types */ HEIM_TID_TAGGED_UNUSED5 = 6, /* reserved for tagged object types */ HEIM_TID_TAGGED_UNUSED6 = 7, /* reserved for tagged object types */ HEIM_TID_MEMORY = 128, HEIM_TID_ARRAY = 129, HEIM_TID_DICT = 130, HEIM_TID_STRING = 131, HEIM_TID_AUTORELEASE = 132, HEIM_TID_ERROR = 133, HEIM_TID_DATA = 134, HEIM_TID_DB = 135, HEIM_TID_USER = 255 }; struct heim_type_data { heim_tid_t tid; const char *name; heim_type_init init; heim_type_dealloc dealloc; heim_type_copy copy; heim_type_cmp cmp; heim_type_hash hash; heim_type_description desc; }; heim_type_t _heim_get_isa(heim_object_t); heim_type_t _heim_create_type(const char *name, heim_type_init init, heim_type_dealloc dealloc, heim_type_copy copy, heim_type_cmp cmp, heim_type_hash hash, heim_type_description desc); heim_object_t _heim_alloc_object(heim_type_t type, size_t size); void * _heim_get_isaextra(heim_object_t o, size_t idx); heim_tid_t _heim_type_get_tid(heim_type_t type); void _heim_make_permanent(heim_object_t ptr); heim_data_t _heim_db_get_value(heim_db_t, heim_string_t, heim_data_t, heim_error_t *); /* tagged tid */ extern struct heim_type_data _heim_null_object; extern struct heim_type_data _heim_bool_object; extern struct heim_type_data _heim_number_object; extern struct heim_type_data _heim_string_object; heimdal-7.5.0/lib/base/NTMakefile0000644000175000017500000000443613026237312014642 0ustar niknik######################################################################## # # Copyright (c) 2010, Secure Endpoints Inc. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # - Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # # - Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in # the documentation and/or other materials provided with the # distribution. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS # FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE # COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, # BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN # ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. # RELDIR=lib\base intcflags=-I$(SRCDIR) -I$(OBJ) !include ../../windows/NTMakefile.w32 INCFILES=$(INCDIR)\heimbase.h test_binaries = $(OBJ)\test_base.exe libheimbase_OBJS = \ $(OBJ)\array.obj \ $(OBJ)\bool.obj \ $(OBJ)\bsearch.obj \ $(OBJ)\data.obj \ $(OBJ)\db.obj \ $(OBJ)\dict.obj \ $(OBJ)\dll.obj \ $(OBJ)\error.obj \ $(OBJ)\heimbase.obj \ $(OBJ)\json.obj \ $(OBJ)\null.obj \ $(OBJ)\number.obj \ $(OBJ)\string.obj $(LIBHEIMBASE): $(libheimbase_OBJS) $(LIBCON_C) -OUT:$@ $(LIBROKEN) @<< $(libheimbase_OBJS: = ) << test:: test-binaries test-run test-run: cd $(OBJ) -test_base.exe cd $(SRCDIR) all:: $(INCFILES) $(LIBHEIMBASE) clean:: -$(RM) $(INCFILES) test-binaries: $(test_binaries) $(test_binaries): $$(@R).obj $(LIBHEIMBASE) $(LIBVERS) $(LIBROKEN) $(EXECONLINK) $(EXEPREP_NODIST) $(test_binaries:.exe=.obj): $$(@B).c $(C2OBJ_C) -Fo$@ -Fd$(@D)\ $** -DBlah heimdal-7.5.0/lib/base/test_base.c0000644000175000017500000006375713026237312015070 0ustar niknik/* * Copyright (c) 2010-2016 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Portions Copyright (c) 2010 Apple Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ /* * This is a test of libheimbase functionality. If you make any changes * to libheimbase or to this test you should run it under valgrind with * the following options: * * -v --track-fds=yes --num-callers=30 --leak-check=full * * and make sure that there are no leaks that don't have * __heim_string_constant() or heim_db_register() in their stack trace. */ #include #include #include #include #include #include #include #ifndef WIN32 #include #endif #ifdef HAVE_IO_H #include #endif #ifdef HAVE_UNISTD_H #include #endif #include #include "baselocl.h" static void memory_free(heim_object_t obj) { } static int test_memory(void) { void *ptr; ptr = heim_alloc(10, "memory", memory_free); heim_retain(ptr); heim_release(ptr); heim_retain(ptr); heim_release(ptr); heim_release(ptr); ptr = heim_alloc(10, "memory", NULL); heim_release(ptr); return 0; } static int test_mutex(void) { HEIMDAL_MUTEX m = HEIMDAL_MUTEX_INITIALIZER; HEIMDAL_MUTEX_lock(&m); HEIMDAL_MUTEX_unlock(&m); HEIMDAL_MUTEX_destroy(&m); HEIMDAL_MUTEX_init(&m); HEIMDAL_MUTEX_lock(&m); HEIMDAL_MUTEX_unlock(&m); HEIMDAL_MUTEX_destroy(&m); return 0; } static int test_rwlock(void) { HEIMDAL_RWLOCK l = HEIMDAL_RWLOCK_INITIALIZER; HEIMDAL_RWLOCK_rdlock(&l); HEIMDAL_RWLOCK_unlock(&l); HEIMDAL_RWLOCK_wrlock(&l); HEIMDAL_RWLOCK_unlock(&l); if (HEIMDAL_RWLOCK_trywrlock(&l) != 0) err(1, "HEIMDAL_RWLOCK_trywrlock() failed with lock not held"); HEIMDAL_RWLOCK_unlock(&l); if (HEIMDAL_RWLOCK_tryrdlock(&l)) err(1, "HEIMDAL_RWLOCK_tryrdlock() failed with lock not held"); HEIMDAL_RWLOCK_unlock(&l); HEIMDAL_RWLOCK_destroy(&l); HEIMDAL_RWLOCK_init(&l); HEIMDAL_RWLOCK_rdlock(&l); HEIMDAL_RWLOCK_unlock(&l); HEIMDAL_RWLOCK_wrlock(&l); HEIMDAL_RWLOCK_unlock(&l); if (HEIMDAL_RWLOCK_trywrlock(&l)) err(1, "HEIMDAL_RWLOCK_trywrlock() failed with lock not held"); HEIMDAL_RWLOCK_unlock(&l); if (HEIMDAL_RWLOCK_tryrdlock(&l)) err(1, "HEIMDAL_RWLOCK_tryrdlock() failed with lock not held"); HEIMDAL_RWLOCK_unlock(&l); HEIMDAL_RWLOCK_destroy(&l); return 0; } static int test_dict(void) { heim_dict_t dict; heim_number_t a1 = heim_number_create(1); heim_string_t a2 = heim_string_create("hejsan"); heim_number_t a3 = heim_number_create(3); heim_string_t a4 = heim_string_create("foosan"); dict = heim_dict_create(10); heim_dict_set_value(dict, a1, a2); heim_dict_set_value(dict, a3, a4); heim_dict_delete_key(dict, a3); heim_dict_delete_key(dict, a1); heim_release(a1); heim_release(a2); heim_release(a3); heim_release(a4); heim_release(dict); return 0; } static int test_auto_release(void) { heim_auto_release_t ar1, ar2; heim_number_t n1; heim_string_t s1; ar1 = heim_auto_release_create(); s1 = heim_string_create("hejsan"); heim_auto_release(s1); n1 = heim_number_create(1); heim_auto_release(n1); ar2 = heim_auto_release_create(); n1 = heim_number_create(1); heim_auto_release(n1); heim_release(ar2); heim_release(ar1); return 0; } static int test_string(void) { heim_string_t s1, s2; const char *string = "hejsan"; s1 = heim_string_create(string); s2 = heim_string_create(string); if (heim_cmp(s1, s2) != 0) { printf("the same string is not the same\n"); exit(1); } heim_release(s1); heim_release(s2); return 0; } static int test_error(void) { heim_error_t e; heim_string_t s; e = heim_error_create(10, "foo: %s", "bar"); heim_assert(heim_error_get_code(e) == 10, "error_code != 10"); s = heim_error_copy_string(e); heim_assert(strcmp(heim_string_get_utf8(s), "foo: bar") == 0, "msg wrong"); heim_release(s); heim_release(e); return 0; } static int test_json(void) { static char *j[] = { "{ \"k1\" : \"s1\", \"k2\" : \"s2\" }", "{ \"k1\" : [\"s1\", \"s2\", \"s3\"], \"k2\" : \"s3\" }", "{ \"k1\" : {\"k2\":\"s1\",\"k3\":\"s2\",\"k4\":\"s3\"}, \"k5\" : \"s4\" }", "[ \"v1\", \"v2\", [\"v3\",\"v4\",[\"v 5\",\" v 7 \"]], -123456789, " "null, true, false, 123456789, \"\"]", " -1" }; char *s; size_t i, k; heim_object_t o, o2; heim_string_t k1 = heim_string_create("k1"); o = heim_json_create("\"string\"", 10, 0, NULL); heim_assert(o != NULL, "string"); heim_assert(heim_get_tid(o) == heim_string_get_type_id(), "string-tid"); heim_assert(strcmp("string", heim_string_get_utf8(o)) == 0, "wrong string"); heim_release(o); o = heim_json_create(" \"foo\\\"bar\" ]", 10, 0, NULL); heim_assert(o != NULL, "string"); heim_assert(heim_get_tid(o) == heim_string_get_type_id(), "string-tid"); heim_assert(strcmp("foo\"bar", heim_string_get_utf8(o)) == 0, "wrong string"); heim_release(o); o = heim_json_create(" { \"key\" : \"value\" }", 10, 0, NULL); heim_assert(o != NULL, "dict"); heim_assert(heim_get_tid(o) == heim_dict_get_type_id(), "dict-tid"); heim_release(o); o = heim_json_create("{ { \"k1\" : \"s1\", \"k2\" : \"s2\" } : \"s3\", " "{ \"k3\" : \"s4\" } : -1 }", 10, 0, NULL); heim_assert(o != NULL, "dict"); heim_assert(heim_get_tid(o) == heim_dict_get_type_id(), "dict-tid"); heim_release(o); o = heim_json_create("{ { \"k1\" : \"s1\", \"k2\" : \"s2\" } : \"s3\", " "{ \"k3\" : \"s4\" } : -1 }", 10, HEIM_JSON_F_STRICT_DICT, NULL); heim_assert(o == NULL, "dict"); o = heim_json_create(" { \"k1\" : \"s1\", \"k2\" : \"s2\" }", 10, 0, NULL); heim_assert(o != NULL, "dict"); heim_assert(heim_get_tid(o) == heim_dict_get_type_id(), "dict-tid"); o2 = heim_dict_copy_value(o, k1); heim_assert(heim_get_tid(o2) == heim_string_get_type_id(), "string-tid"); heim_release(o2); heim_release(o); o = heim_json_create(" { \"k1\" : { \"k2\" : \"s2\" } }", 10, 0, NULL); heim_assert(o != NULL, "dict"); heim_assert(heim_get_tid(o) == heim_dict_get_type_id(), "dict-tid"); o2 = heim_dict_copy_value(o, k1); heim_assert(heim_get_tid(o2) == heim_dict_get_type_id(), "dict-tid"); heim_release(o2); heim_release(o); o = heim_json_create("{ \"k1\" : 1 }", 10, 0, NULL); heim_assert(o != NULL, "array"); heim_assert(heim_get_tid(o) == heim_dict_get_type_id(), "dict-tid"); o2 = heim_dict_copy_value(o, k1); heim_assert(heim_get_tid(o2) == heim_number_get_type_id(), "number-tid"); heim_release(o2); heim_release(o); o = heim_json_create("-10", 10, 0, NULL); heim_assert(o != NULL, "number"); heim_assert(heim_get_tid(o) == heim_number_get_type_id(), "number-tid"); heim_release(o); o = heim_json_create("99", 10, 0, NULL); heim_assert(o != NULL, "number"); heim_assert(heim_get_tid(o) == heim_number_get_type_id(), "number-tid"); heim_release(o); o = heim_json_create(" [ 1 ]", 10, 0, NULL); heim_assert(o != NULL, "array"); heim_assert(heim_get_tid(o) == heim_array_get_type_id(), "array-tid"); heim_release(o); o = heim_json_create(" [ -1 ]", 10, 0, NULL); heim_assert(o != NULL, "array"); heim_assert(heim_get_tid(o) == heim_array_get_type_id(), "array-tid"); heim_release(o); for (i = 0; i < (sizeof (j) / sizeof (j[0])); i++) { o = heim_json_create(j[i], 10, 0, NULL); if (o == NULL) { fprintf(stderr, "Failed to parse this JSON: %s\n", j[i]); return 1; } heim_release(o); /* Simple fuzz test */ for (k = strlen(j[i]) - 1; k > 0; k--) { o = heim_json_create_with_bytes(j[i], k, 10, 0, NULL); if (o != NULL) { fprintf(stderr, "Invalid JSON parsed: %.*s\n", (int)k, j[i]); return EINVAL; } } /* Again, but this time make it so valgrind can find invalid accesses */ for (k = strlen(j[i]) - 1; k > 0; k--) { s = strndup(j[i], k); if (s == NULL) return ENOMEM; o = heim_json_create(s, 10, 0, NULL); free(s); if (o != NULL) { fprintf(stderr, "Invalid JSON parsed: %s\n", j[i]); return EINVAL; } } /* Again, but with no NUL termination */ for (k = strlen(j[i]) - 1; k > 0; k--) { s = malloc(k); if (s == NULL) return ENOMEM; memcpy(s, j[i], k); o = heim_json_create_with_bytes(s, k, 10, 0, NULL); free(s); if (o != NULL) { fprintf(stderr, "Invalid JSON parsed: %s\n", j[i]); return EINVAL; } } } heim_release(k1); return 0; } static int test_path(void) { heim_dict_t dict = heim_dict_create(11); heim_string_t p1 = heim_string_create("abc"); heim_string_t p2a = heim_string_create("def"); heim_string_t p2b = heim_string_create("DEF"); heim_number_t p3 = heim_number_create(0); heim_string_t p4a = heim_string_create("ghi"); heim_string_t p4b = heim_string_create("GHI"); heim_array_t a = heim_array_create(); heim_number_t l1 = heim_number_create(42); heim_number_t l2 = heim_number_create(813); heim_number_t l3 = heim_number_create(1234); heim_string_t k1 = heim_string_create("k1"); heim_string_t k2 = heim_string_create("k2"); heim_string_t k3 = heim_string_create("k3"); heim_string_t k2_1 = heim_string_create("k2-1"); heim_string_t k2_2 = heim_string_create("k2-2"); heim_string_t k2_3 = heim_string_create("k2-3"); heim_string_t k2_4 = heim_string_create("k2-4"); heim_string_t k2_5 = heim_string_create("k2-5"); heim_string_t k2_5_1 = heim_string_create("k2-5-1"); heim_object_t o; heim_object_t neg_num; int ret; if (!dict || !p1 || !p2a || !p2b || !p4a || !p4b) return ENOMEM; ret = heim_path_create(dict, 11, a, NULL, p1, p2a, NULL); heim_release(a); if (ret) return ret; ret = heim_path_create(dict, 11, l3, NULL, p1, p2b, NULL); if (ret) return ret; o = heim_path_get(dict, NULL, p1, p2b, NULL); if (o != l3) return 1; ret = heim_path_create(dict, 11, NULL, NULL, p1, p2a, p3, NULL); if (ret) return ret; ret = heim_path_create(dict, 11, l1, NULL, p1, p2a, p3, p4a, NULL); if (ret) return ret; ret = heim_path_create(dict, 11, l2, NULL, p1, p2a, p3, p4b, NULL); if (ret) return ret; o = heim_path_get(dict, NULL, p1, p2a, p3, p4a, NULL); if (o != l1) return 1; o = heim_path_get(dict, NULL, p1, p2a, p3, p4b, NULL); if (o != l2) return 1; heim_release(dict); /* Test that JSON parsing works right by using heim_path_get() */ dict = heim_json_create("{\"k1\":1," "\"k2\":{\"k2-1\":21," "\"k2-2\":null," "\"k2-3\":true," "\"k2-4\":false," "\"k2-5\":[1,2,3,{\"k2-5-1\":-1},-2]}," "\"k3\":[true,false,0,42]}", 10, 0, NULL); heim_assert(dict != NULL, "dict"); o = heim_path_get(dict, NULL, k1, NULL); if (heim_cmp(o, heim_number_create(1))) return 1; o = heim_path_get(dict, NULL, k2, NULL); if (heim_get_tid(o) != heim_dict_get_type_id()) return 1; o = heim_path_get(dict, NULL, k2, k2_1, NULL); if (heim_cmp(o, heim_number_create(21))) return 1; o = heim_path_get(dict, NULL, k2, k2_2, NULL); if (heim_cmp(o, heim_null_create())) return 1; o = heim_path_get(dict, NULL, k2, k2_3, NULL); if (heim_cmp(o, heim_bool_create(1))) return 1; o = heim_path_get(dict, NULL, k2, k2_4, NULL); if (heim_cmp(o, heim_bool_create(0))) return 1; o = heim_path_get(dict, NULL, k2, k2_5, NULL); if (heim_get_tid(o) != heim_array_get_type_id()) return 1; o = heim_path_get(dict, NULL, k2, k2_5, heim_number_create(0), NULL); if (heim_cmp(o, heim_number_create(1))) return 1; o = heim_path_get(dict, NULL, k2, k2_5, heim_number_create(1), NULL); if (heim_cmp(o, heim_number_create(2))) return 1; o = heim_path_get(dict, NULL, k2, k2_5, heim_number_create(3), k2_5_1, NULL); if (heim_cmp(o, neg_num = heim_number_create(-1))) return 1; heim_release(neg_num); o = heim_path_get(dict, NULL, k2, k2_5, heim_number_create(4), NULL); if (heim_cmp(o, neg_num = heim_number_create(-2))) return 1; heim_release(neg_num); o = heim_path_get(dict, NULL, k3, heim_number_create(3), NULL); if (heim_cmp(o, heim_number_create(42))) return 1; heim_release(dict); heim_release(p1); heim_release(p2a); heim_release(p2b); heim_release(p4a); heim_release(p4b); heim_release(k1); heim_release(k2); heim_release(k3); heim_release(k2_1); heim_release(k2_2); heim_release(k2_3); heim_release(k2_4); heim_release(k2_5); heim_release(k2_5_1); return 0; } typedef struct dict_db { heim_dict_t dict; int locked; } *dict_db_t; static int dict_db_open(void *plug, const char *dbtype, const char *dbname, heim_dict_t options, void **db, heim_error_t *error) { dict_db_t dictdb; heim_dict_t contents = NULL; if (error) *error = NULL; if (dbtype && *dbtype && strcmp(dbtype, "dictdb")) return EINVAL; if (dbname && *dbname && strcmp(dbname, "MEMORY") != 0) return EINVAL; dictdb = heim_alloc(sizeof (*dictdb), "dict_db", NULL); if (dictdb == NULL) return ENOMEM; if (contents != NULL) dictdb->dict = contents; else { dictdb->dict = heim_dict_create(29); if (dictdb->dict == NULL) { heim_release(dictdb); return ENOMEM; } } *db = dictdb; return 0; } static int dict_db_close(void *db, heim_error_t *error) { dict_db_t dictdb = db; if (error) *error = NULL; heim_release(dictdb->dict); heim_release(dictdb); return 0; } static int dict_db_lock(void *db, int read_only, heim_error_t *error) { dict_db_t dictdb = db; if (error) *error = NULL; if (dictdb->locked) return EWOULDBLOCK; dictdb->locked = 1; return 0; } static int dict_db_unlock(void *db, heim_error_t *error) { dict_db_t dictdb = db; if (error) *error = NULL; dictdb->locked = 0; return 0; } static heim_data_t dict_db_copy_value(void *db, heim_string_t table, heim_data_t key, heim_error_t *error) { dict_db_t dictdb = db; if (error) *error = NULL; return heim_retain(heim_path_get(dictdb->dict, error, table, key, NULL)); } static int dict_db_set_value(void *db, heim_string_t table, heim_data_t key, heim_data_t value, heim_error_t *error) { dict_db_t dictdb = db; if (error) *error = NULL; if (table == NULL) table = HSTR(""); return heim_path_create(dictdb->dict, 29, value, error, table, key, NULL); } static int dict_db_del_key(void *db, heim_string_t table, heim_data_t key, heim_error_t *error) { dict_db_t dictdb = db; if (error) *error = NULL; if (table == NULL) table = HSTR(""); heim_path_delete(dictdb->dict, error, table, key, NULL); return 0; } struct dict_db_iter_ctx { heim_db_iterator_f_t iter_f; void *iter_ctx; }; static void dict_db_iter_f(heim_object_t key, heim_object_t value, void *arg) { struct dict_db_iter_ctx *ctx = arg; ctx->iter_f((heim_object_t)key, (heim_object_t)value, ctx->iter_ctx); } static void dict_db_iter(void *db, heim_string_t table, void *iter_data, heim_db_iterator_f_t iter_f, heim_error_t *error) { dict_db_t dictdb = db; struct dict_db_iter_ctx ctx; heim_dict_t table_dict; if (error) *error = NULL; if (table == NULL) table = HSTR(""); table_dict = heim_dict_copy_value(dictdb->dict, table); if (table_dict == NULL) return; ctx.iter_ctx = iter_data; ctx.iter_f = iter_f; heim_dict_iterate_f(table_dict, &ctx, dict_db_iter_f); heim_release(table_dict); } static void test_db_iter(heim_data_t k, heim_data_t v, void *arg) { int *ret = arg; const void *kptr, *vptr; size_t klen, vlen; heim_assert(heim_get_tid(k) == heim_data_get_type_id(), "..."); kptr = heim_data_get_ptr(k); klen = heim_data_get_length(k); vptr = heim_data_get_ptr(v); vlen = heim_data_get_length(v); if (klen == strlen("msg") && !strncmp(kptr, "msg", strlen("msg")) && vlen == strlen("abc") && !strncmp(vptr, "abc", strlen("abc"))) *ret &= ~(1); else if (klen == strlen("msg2") && !strncmp(kptr, "msg2", strlen("msg2")) && vlen == strlen("FooBar") && !strncmp(vptr, "FooBar", strlen("FooBar"))) *ret &= ~(2); else *ret |= 4; } static struct heim_db_type dbt = { 1, dict_db_open, NULL, dict_db_close, dict_db_lock, dict_db_unlock, NULL, NULL, NULL, NULL, dict_db_copy_value, dict_db_set_value, dict_db_del_key, dict_db_iter }; static int test_db(const char *dbtype, const char *dbname) { heim_data_t k1, k2, v, v1, v2, v3; heim_db_t db; int ret; if (dbtype == NULL) { ret = heim_db_register("dictdb", NULL, &dbt); heim_assert(!ret, "..."); db = heim_db_create("dictdb", "foo", NULL, NULL); heim_assert(!db, "..."); db = heim_db_create("foobar", "MEMORY", NULL, NULL); heim_assert(!db, "..."); db = heim_db_create("dictdb", "MEMORY", NULL, NULL); heim_assert(db, "..."); } else { heim_dict_t options; options = heim_dict_create(11); if (options == NULL) return ENOMEM; if (heim_dict_set_value(options, HSTR("journal-filename"), HSTR("json-journal"))) return ENOMEM; if (heim_dict_set_value(options, HSTR("create"), heim_null_create())) return ENOMEM; if (heim_dict_set_value(options, HSTR("truncate"), heim_null_create())) return ENOMEM; db = heim_db_create(dbtype, dbname, options, NULL); heim_assert(db, "..."); heim_release(options); } k1 = heim_data_create("msg", strlen("msg")); k2 = heim_data_create("msg2", strlen("msg2")); v1 = heim_data_create("Hello world!", strlen("Hello world!")); v2 = heim_data_create("FooBar", strlen("FooBar")); v3 = heim_data_create("abc", strlen("abc")); ret = heim_db_set_value(db, NULL, k1, v1, NULL); heim_assert(!ret, "..."); v = heim_db_copy_value(db, NULL, k1, NULL); heim_assert(v && !heim_cmp(v, v1), "..."); heim_release(v); ret = heim_db_set_value(db, NULL, k2, v2, NULL); heim_assert(!ret, "..."); v = heim_db_copy_value(db, NULL, k2, NULL); heim_assert(v && !heim_cmp(v, v2), "..."); heim_release(v); ret = heim_db_set_value(db, NULL, k1, v3, NULL); heim_assert(!ret, "..."); v = heim_db_copy_value(db, NULL, k1, NULL); heim_assert(v && !heim_cmp(v, v3), "..."); heim_release(v); ret = 3; heim_db_iterate_f(db, NULL, &ret, test_db_iter, NULL); heim_assert(!ret, "..."); ret = heim_db_begin(db, 0, NULL); heim_assert(!ret, "..."); ret = heim_db_commit(db, NULL); heim_assert(!ret, "..."); ret = heim_db_begin(db, 0, NULL); heim_assert(!ret, "..."); ret = heim_db_rollback(db, NULL); heim_assert(!ret, "..."); ret = heim_db_begin(db, 0, NULL); heim_assert(!ret, "..."); ret = heim_db_set_value(db, NULL, k1, v1, NULL); heim_assert(!ret, "..."); v = heim_db_copy_value(db, NULL, k1, NULL); heim_assert(v && !heim_cmp(v, v1), "..."); heim_release(v); ret = heim_db_rollback(db, NULL); heim_assert(!ret, "..."); v = heim_db_copy_value(db, NULL, k1, NULL); heim_assert(v && !heim_cmp(v, v3), "..."); heim_release(v); ret = heim_db_begin(db, 0, NULL); heim_assert(!ret, "..."); ret = heim_db_set_value(db, NULL, k1, v1, NULL); heim_assert(!ret, "..."); v = heim_db_copy_value(db, NULL, k1, NULL); heim_assert(v && !heim_cmp(v, v1), "..."); heim_release(v); ret = heim_db_commit(db, NULL); heim_assert(!ret, "..."); v = heim_db_copy_value(db, NULL, k1, NULL); heim_assert(v && !heim_cmp(v, v1), "..."); heim_release(v); ret = heim_db_begin(db, 0, NULL); heim_assert(!ret, "..."); ret = heim_db_delete_key(db, NULL, k1, NULL); heim_assert(!ret, "..."); v = heim_db_copy_value(db, NULL, k1, NULL); heim_assert(v == NULL, "..."); heim_release(v); ret = heim_db_rollback(db, NULL); heim_assert(!ret, "..."); v = heim_db_copy_value(db, NULL, k1, NULL); heim_assert(v && !heim_cmp(v, v1), "..."); heim_release(v); if (dbtype != NULL) { heim_data_t k3 = heim_data_create("value-is-a-dict", strlen("value-is-a-dict")); heim_dict_t vdict = heim_dict_create(11); heim_db_t db2; heim_assert(k3 && vdict, "..."); ret = heim_dict_set_value(vdict, HSTR("vdict-k1"), heim_number_create(11)); heim_assert(!ret, "..."); ret = heim_dict_set_value(vdict, HSTR("vdict-k2"), heim_null_create()); heim_assert(!ret, "..."); ret = heim_dict_set_value(vdict, HSTR("vdict-k3"), HSTR("a value")); heim_assert(!ret, "..."); ret = heim_db_set_value(db, NULL, k3, (heim_data_t)vdict, NULL); heim_assert(!ret, "..."); heim_release(vdict); db2 = heim_db_create(dbtype, dbname, NULL, NULL); heim_assert(db2, "..."); vdict = (heim_dict_t)heim_db_copy_value(db2, NULL, k3, NULL); heim_release(db2); heim_release(k3); heim_assert(vdict, "..."); heim_assert(heim_get_tid(vdict) == heim_dict_get_type_id(), "..."); v = heim_dict_copy_value(vdict, HSTR("vdict-k1")); heim_assert(v && !heim_cmp(v, heim_number_create(11)), "..."); heim_release(v); v = heim_dict_copy_value(vdict, HSTR("vdict-k2")); heim_assert(v && !heim_cmp(v, heim_null_create()), "..."); heim_release(v); v = heim_dict_copy_value(vdict, HSTR("vdict-k3")); heim_assert(v && !heim_cmp(v, HSTR("a value")), "..."); heim_release(v); heim_release(vdict); } heim_release(db); heim_release(k1); heim_release(k2); heim_release(v1); heim_release(v2); heim_release(v3); return 0; } struct test_array_iter_ctx { char buf[256]; }; static void test_array_iter(heim_object_t elt, void *arg, int *stop) { struct test_array_iter_ctx *iter_ctx = arg; strcat(iter_ctx->buf, heim_string_get_utf8((heim_string_t)elt)); } static int test_array() { struct test_array_iter_ctx iter_ctx; heim_string_t s1 = heim_string_create("abc"); heim_string_t s2 = heim_string_create("def"); heim_string_t s3 = heim_string_create("ghi"); heim_string_t s4 = heim_string_create("jkl"); heim_string_t s5 = heim_string_create("mno"); heim_string_t s6 = heim_string_create("pqr"); heim_array_t a = heim_array_create(); if (!s1 || !s2 || !s3 || !s4 || !s5 || !s6 || !a) return ENOMEM; heim_array_append_value(a, s4); heim_array_append_value(a, s5); heim_array_insert_value(a, 0, s3); heim_array_insert_value(a, 0, s2); heim_array_append_value(a, s6); heim_array_insert_value(a, 0, s1); iter_ctx.buf[0] = '\0'; heim_array_iterate_f(a, &iter_ctx, test_array_iter); if (strcmp(iter_ctx.buf, "abcdefghijklmnopqr") != 0) return 1; iter_ctx.buf[0] = '\0'; heim_array_delete_value(a, 2); heim_array_iterate_f(a, &iter_ctx, test_array_iter); if (strcmp(iter_ctx.buf, "abcdefjklmnopqr") != 0) return 1; iter_ctx.buf[0] = '\0'; heim_array_delete_value(a, 2); heim_array_iterate_f(a, &iter_ctx, test_array_iter); if (strcmp(iter_ctx.buf, "abcdefmnopqr") != 0) return 1; iter_ctx.buf[0] = '\0'; heim_array_delete_value(a, 0); heim_array_iterate_f(a, &iter_ctx, test_array_iter); if (strcmp(iter_ctx.buf, "defmnopqr") != 0) return 1; iter_ctx.buf[0] = '\0'; heim_array_delete_value(a, 2); heim_array_iterate_f(a, &iter_ctx, test_array_iter); if (strcmp(iter_ctx.buf, "defmno") != 0) return 1; heim_array_insert_value(a, 0, s1); iter_ctx.buf[0] = '\0'; heim_array_iterate_f(a, &iter_ctx, test_array_iter); if (strcmp(iter_ctx.buf, "abcdefmno") != 0) return 1; heim_array_insert_value(a, 0, s2); iter_ctx.buf[0] = '\0'; heim_array_iterate_f(a, &iter_ctx, test_array_iter); if (strcmp(iter_ctx.buf, "defabcdefmno") != 0) return 1; heim_array_append_value(a, s3); iter_ctx.buf[0] = '\0'; heim_array_iterate_f(a, &iter_ctx, test_array_iter); if (strcmp(iter_ctx.buf, "defabcdefmnoghi") != 0) return 1; heim_array_append_value(a, s6); iter_ctx.buf[0] = '\0'; heim_array_iterate_f(a, &iter_ctx, test_array_iter); if (strcmp(iter_ctx.buf, "defabcdefmnoghipqr") != 0) return 1; heim_release(s1); heim_release(s2); heim_release(s3); heim_release(s4); heim_release(s5); heim_release(s6); heim_release(a); return 0; } int main(int argc, char **argv) { int res = 0; res |= test_memory(); res |= test_mutex(); res |= test_rwlock(); res |= test_dict(); res |= test_auto_release(); res |= test_string(); res |= test_error(); res |= test_json(); res |= test_path(); res |= test_db(NULL, NULL); res |= test_db("json", argc > 1 ? argv[1] : "test_db.json"); res |= test_array(); return res ? 1 : 0; } heimdal-7.5.0/lib/base/heimbase.h0000644000175000017500000003260613062303006014660 0ustar niknik/* * Copyright (c) 2010 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Portions Copyright (c) 2010 Apple Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #ifndef HEIM_BASE_H #define HEIM_BASE_H 1 #include #if !defined(WIN32) && !defined(HAVE_DISPATCH_DISPATCH_H) && defined(ENABLE_PTHREAD_SUPPORT) #include #endif #include #include #ifdef HAVE_STDBOOL_H #include #else #ifndef false #define false 0 #endif #ifndef true #define true 1 #endif #endif #define HEIM_BASE_API_VERSION 20130210 typedef void * heim_object_t; typedef unsigned int heim_tid_t; typedef heim_object_t heim_bool_t; typedef heim_object_t heim_null_t; #ifdef WIN32 typedef LONG heim_base_once_t; #define HEIM_BASE_ONCE_INIT 0 #elif defined(HAVE_DISPATCH_DISPATCH_H) typedef long heim_base_once_t; /* XXX arch dependant */ #define HEIM_BASE_ONCE_INIT 0 #elif defined(ENABLE_PTHREAD_SUPPORT) typedef pthread_once_t heim_base_once_t; #define HEIM_BASE_ONCE_INIT PTHREAD_ONCE_INIT #else typedef long heim_base_once_t; /* XXX arch dependant */ #define HEIM_BASE_ONCE_INIT 0 #endif #if !defined(__has_extension) #define __has_extension(x) 0 #endif #define HEIM_REQUIRE_GNUC(m,n,p) \ (((__GNUC__ * 10000) + (__GNUC_MINOR__ * 100) + __GNUC_PATCHLEVEL__) >= \ (((m) * 10000) + ((n) * 100) + (p))) #if __has_extension(__builtin_expect) || HEIM_REQUIRE_GNUC(3,0,0) #define heim_builtin_expect(_op,_res) __builtin_expect(_op,_res) #else #define heim_builtin_expect(_op,_res) (_op) #endif void * heim_retain(heim_object_t); void heim_release(heim_object_t); void heim_show(heim_object_t); typedef void (*heim_type_dealloc)(void *); void * heim_alloc(size_t size, const char *name, heim_type_dealloc dealloc); heim_tid_t heim_get_tid(heim_object_t object); int heim_cmp(heim_object_t a, heim_object_t b); unsigned long heim_get_hash(heim_object_t ptr); void heim_base_once_f(heim_base_once_t *, void *, void (*)(void *)); void heim_abort(const char *fmt, ...) HEIMDAL_NORETURN_ATTRIBUTE HEIMDAL_PRINTF_ATTRIBUTE((__printf__, 1, 2)); void heim_abortv(const char *fmt, va_list ap) HEIMDAL_NORETURN_ATTRIBUTE HEIMDAL_PRINTF_ATTRIBUTE((__printf__, 1, 0)); #define heim_assert(e,t) \ (heim_builtin_expect(!(e), 0) ? heim_abort(t ":" #e) : (void)0) /* * */ heim_null_t heim_null_create(void); heim_bool_t heim_bool_create(int); int heim_bool_val(heim_bool_t); /* * Array */ typedef struct heim_array_data *heim_array_t; heim_array_t heim_array_create(void); heim_tid_t heim_array_get_type_id(void); typedef void (*heim_array_iterator_f_t)(heim_object_t, void *, int *); typedef int (*heim_array_filter_f_t)(heim_object_t, void *); int heim_array_append_value(heim_array_t, heim_object_t); int heim_array_insert_value(heim_array_t, size_t idx, heim_object_t); void heim_array_iterate_f(heim_array_t, void *, heim_array_iterator_f_t); void heim_array_iterate_reverse_f(heim_array_t, void *, heim_array_iterator_f_t); #ifdef __BLOCKS__ void heim_array_iterate(heim_array_t, void (^)(heim_object_t, int *)); void heim_array_iterate_reverse(heim_array_t, void (^)(heim_object_t, int *)); #endif size_t heim_array_get_length(heim_array_t); heim_object_t heim_array_get_value(heim_array_t, size_t); heim_object_t heim_array_copy_value(heim_array_t, size_t); void heim_array_set_value(heim_array_t, size_t, heim_object_t); void heim_array_delete_value(heim_array_t, size_t); void heim_array_filter_f(heim_array_t, void *, heim_array_filter_f_t); #ifdef __BLOCKS__ void heim_array_filter(heim_array_t, int (^)(heim_object_t)); #endif /* * Dict */ typedef struct heim_dict_data *heim_dict_t; heim_dict_t heim_dict_create(size_t size); heim_tid_t heim_dict_get_type_id(void); typedef void (*heim_dict_iterator_f_t)(heim_object_t, heim_object_t, void *); int heim_dict_set_value(heim_dict_t, heim_object_t, heim_object_t); void heim_dict_iterate_f(heim_dict_t, void *, heim_dict_iterator_f_t); #ifdef __BLOCKS__ void heim_dict_iterate(heim_dict_t, void (^)(heim_object_t, heim_object_t)); #endif heim_object_t heim_dict_get_value(heim_dict_t, heim_object_t); heim_object_t heim_dict_copy_value(heim_dict_t, heim_object_t); void heim_dict_delete_key(heim_dict_t, heim_object_t); /* * String */ typedef struct heim_string_data *heim_string_t; typedef void (*heim_string_free_f_t)(void *); heim_string_t heim_string_create(const char *); heim_string_t heim_string_ref_create(const char *, heim_string_free_f_t); heim_string_t heim_string_create_with_bytes(const void *, size_t); heim_string_t heim_string_ref_create_with_bytes(const void *, size_t, heim_string_free_f_t); heim_string_t heim_string_create_with_format(const char *, ...); heim_tid_t heim_string_get_type_id(void); const char * heim_string_get_utf8(heim_string_t); #define HSTR(_str) (__heim_string_constant("" _str "")) heim_string_t __heim_string_constant(const char *); /* * Errors */ typedef struct heim_error * heim_error_t; heim_error_t heim_error_create_enomem(void); heim_error_t heim_error_create(int, const char *, ...) HEIMDAL_PRINTF_ATTRIBUTE((__printf__, 2, 3)); void heim_error_create_opt(heim_error_t *error, int error_code, const char *fmt, ...) HEIMDAL_PRINTF_ATTRIBUTE((__printf__, 3, 4)); heim_error_t heim_error_createv(int, const char *, va_list) HEIMDAL_PRINTF_ATTRIBUTE((__printf__, 2, 0)); heim_string_t heim_error_copy_string(heim_error_t); int heim_error_get_code(heim_error_t); heim_error_t heim_error_append(heim_error_t, heim_error_t); /* * Path */ heim_object_t heim_path_get(heim_object_t ptr, heim_error_t *error, ...); heim_object_t heim_path_copy(heim_object_t ptr, heim_error_t *error, ...); heim_object_t heim_path_vget(heim_object_t ptr, heim_error_t *error, va_list ap); heim_object_t heim_path_vcopy(heim_object_t ptr, heim_error_t *error, va_list ap); int heim_path_vcreate(heim_object_t ptr, size_t size, heim_object_t leaf, heim_error_t *error, va_list ap); int heim_path_create(heim_object_t ptr, size_t size, heim_object_t leaf, heim_error_t *error, ...); void heim_path_vdelete(heim_object_t ptr, heim_error_t *error, va_list ap); void heim_path_delete(heim_object_t ptr, heim_error_t *error, ...); /* * Data (octet strings) */ #ifndef __HEIM_BASE_DATA__ #define __HEIM_BASE_DATA__ struct heim_base_data { size_t length; void *data; }; typedef struct heim_base_data heim_octet_string; #endif typedef struct heim_base_data * heim_data_t; typedef void (*heim_data_free_f_t)(void *); heim_data_t heim_data_create(const void *, size_t); heim_data_t heim_data_ref_create(const void *, size_t, heim_data_free_f_t); heim_tid_t heim_data_get_type_id(void); const heim_octet_string * heim_data_get_data(heim_data_t); const void * heim_data_get_ptr(heim_data_t); size_t heim_data_get_length(heim_data_t); /* * DB */ typedef struct heim_db_data *heim_db_t; typedef void (*heim_db_iterator_f_t)(heim_data_t, heim_data_t, void *); typedef int (*heim_db_plug_open_f_t)(void *, const char *, const char *, heim_dict_t, void **, heim_error_t *); typedef int (*heim_db_plug_clone_f_t)(void *, void **, heim_error_t *); typedef int (*heim_db_plug_close_f_t)(void *, heim_error_t *); typedef int (*heim_db_plug_lock_f_t)(void *, int, heim_error_t *); typedef int (*heim_db_plug_unlock_f_t)(void *, heim_error_t *); typedef int (*heim_db_plug_sync_f_t)(void *, heim_error_t *); typedef int (*heim_db_plug_begin_f_t)(void *, int, heim_error_t *); typedef int (*heim_db_plug_commit_f_t)(void *, heim_error_t *); typedef int (*heim_db_plug_rollback_f_t)(void *, heim_error_t *); typedef heim_data_t (*heim_db_plug_copy_value_f_t)(void *, heim_string_t, heim_data_t, heim_error_t *); typedef int (*heim_db_plug_set_value_f_t)(void *, heim_string_t, heim_data_t, heim_data_t, heim_error_t *); typedef int (*heim_db_plug_del_key_f_t)(void *, heim_string_t, heim_data_t, heim_error_t *); typedef void (*heim_db_plug_iter_f_t)(void *, heim_string_t, void *, heim_db_iterator_f_t, heim_error_t *); struct heim_db_type { int version; heim_db_plug_open_f_t openf; heim_db_plug_clone_f_t clonef; heim_db_plug_close_f_t closef; heim_db_plug_lock_f_t lockf; heim_db_plug_unlock_f_t unlockf; heim_db_plug_sync_f_t syncf; heim_db_plug_begin_f_t beginf; heim_db_plug_commit_f_t commitf; heim_db_plug_rollback_f_t rollbackf; heim_db_plug_copy_value_f_t copyf; heim_db_plug_set_value_f_t setf; heim_db_plug_del_key_f_t delf; heim_db_plug_iter_f_t iterf; }; extern struct heim_db_type heim_sorted_text_file_dbtype; #define HEIM_DB_TYPE_VERSION_01 1 int heim_db_register(const char *dbtype, void *data, struct heim_db_type *plugin); heim_db_t heim_db_create(const char *dbtype, const char *dbname, heim_dict_t options, heim_error_t *error); heim_db_t heim_db_clone(heim_db_t, heim_error_t *); int heim_db_begin(heim_db_t, int, heim_error_t *); int heim_db_commit(heim_db_t, heim_error_t *); int heim_db_rollback(heim_db_t, heim_error_t *); heim_tid_t heim_db_get_type_id(void); int heim_db_set_value(heim_db_t, heim_string_t, heim_data_t, heim_data_t, heim_error_t *); heim_data_t heim_db_copy_value(heim_db_t, heim_string_t, heim_data_t, heim_error_t *); int heim_db_delete_key(heim_db_t, heim_string_t, heim_data_t, heim_error_t *); void heim_db_iterate_f(heim_db_t, heim_string_t, void *, heim_db_iterator_f_t, heim_error_t *); #ifdef __BLOCKS__ void heim_db_iterate(heim_db_t, heim_string_t, void (^)(heim_data_t, heim_data_t), heim_error_t *); #endif /* * Number */ typedef struct heim_number_data *heim_number_t; heim_number_t heim_number_create(int); heim_tid_t heim_number_get_type_id(void); int heim_number_get_int(heim_number_t); /* * */ typedef struct heim_auto_release * heim_auto_release_t; heim_auto_release_t heim_auto_release_create(void); void heim_auto_release_drain(heim_auto_release_t); heim_object_t heim_auto_release(heim_object_t); /* * JSON */ typedef enum heim_json_flags { HEIM_JSON_F_NO_C_NULL = 1, HEIM_JSON_F_STRICT_STRINGS = 2, HEIM_JSON_F_NO_DATA = 4, HEIM_JSON_F_NO_DATA_DICT = 8, HEIM_JSON_F_STRICT_DICT = 16, HEIM_JSON_F_STRICT = 31, HEIM_JSON_F_CNULL2JSNULL = 32, HEIM_JSON_F_TRY_DECODE_DATA = 64, HEIM_JSON_F_ONE_LINE = 128 } heim_json_flags_t; heim_object_t heim_json_create(const char *, size_t, heim_json_flags_t, heim_error_t *); heim_object_t heim_json_create_with_bytes(const void *, size_t, size_t, heim_json_flags_t, heim_error_t *); heim_string_t heim_json_copy_serialize(heim_object_t, heim_json_flags_t, heim_error_t *); /* * Debug */ heim_string_t heim_description(heim_object_t ptr); /* * Binary search. * * Note: these are private until integrated into the heimbase object system. */ typedef struct bsearch_file_handle *bsearch_file_handle; int _bsearch_text(const char *buf, size_t buf_sz, const char *key, char **value, size_t *location, size_t *loops); int _bsearch_file_open(const char *fname, size_t max_sz, size_t page_sz, bsearch_file_handle *bfh, size_t *reads); int _bsearch_file(bsearch_file_handle bfh, const char *key, char **value, size_t *location, size_t *loops, size_t *reads); void _bsearch_file_info(bsearch_file_handle bfh, size_t *page_sz, size_t *max_sz, int *blockwise); void _bsearch_file_close(bsearch_file_handle *bfh); /* * Thread-specific keys */ int heim_w32_key_create(unsigned long *, void (*)(void *)); int heim_w32_delete_key(unsigned long); int heim_w32_setspecific(unsigned long, void *); void *heim_w32_getspecific(unsigned long); void heim_w32_service_thread_detach(void *); #endif /* HEIM_BASE_H */ heimdal-7.5.0/lib/base/json.c0000644000175000017500000004311513026237312014052 0ustar niknik/* * Copyright (c) 2010 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Portions Copyright (c) 2010 Apple Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "baselocl.h" #include #include static heim_base_once_t heim_json_once = HEIM_BASE_ONCE_INIT; static heim_string_t heim_tid_data_uuid_key = NULL; static const char base64_chars[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; static void json_init_once(void *arg) { heim_tid_data_uuid_key = __heim_string_constant("heimdal-type-data-76d7fca2-d0da-4b20-a126-1a10f8a0eae6"); } struct twojson { void *ctx; void (*out)(void *, const char *); size_t indent; heim_json_flags_t flags; int ret; int first; }; struct heim_strbuf { char *str; size_t len; size_t alloced; int enomem; heim_json_flags_t flags; }; static int base2json(heim_object_t, struct twojson *); static void indent(struct twojson *j) { size_t i = j->indent; if (j->flags & HEIM_JSON_F_ONE_LINE) return; while (i--) j->out(j->ctx, "\t"); } static void array2json(heim_object_t value, void *ctx, int *stop) { struct twojson *j = ctx; if (j->ret) return; if (j->first) { j->first = 0; } else { j->out(j->ctx, NULL); /* eat previous '\n' if possible */ j->out(j->ctx, ",\n"); } j->ret = base2json(value, j); } static void dict2json(heim_object_t key, heim_object_t value, void *ctx) { struct twojson *j = ctx; if (j->ret) return; if (j->first) { j->first = 0; } else { j->out(j->ctx, NULL); /* eat previous '\n' if possible */ j->out(j->ctx, ",\n"); } j->ret = base2json(key, j); if (j->ret) return; j->out(j->ctx, " : \n"); j->indent++; j->ret = base2json(value, j); if (j->ret) return; j->indent--; } static int base2json(heim_object_t obj, struct twojson *j) { heim_tid_t type; int first = 0; if (obj == NULL) { if (j->flags & HEIM_JSON_F_CNULL2JSNULL) { obj = heim_null_create(); } else if (j->flags & HEIM_JSON_F_NO_C_NULL) { return EINVAL; } else { indent(j); j->out(j->ctx, "\n"); /* This is NOT valid JSON! */ return 0; } } type = heim_get_tid(obj); switch (type) { case HEIM_TID_ARRAY: indent(j); j->out(j->ctx, "[\n"); j->indent++; first = j->first; j->first = 1; heim_array_iterate_f(obj, j, array2json); j->indent--; if (!j->first) j->out(j->ctx, "\n"); indent(j); j->out(j->ctx, "]\n"); j->first = first; break; case HEIM_TID_DICT: indent(j); j->out(j->ctx, "{\n"); j->indent++; first = j->first; j->first = 1; heim_dict_iterate_f(obj, j, dict2json); j->indent--; if (!j->first) j->out(j->ctx, "\n"); indent(j); j->out(j->ctx, "}\n"); j->first = first; break; case HEIM_TID_STRING: indent(j); j->out(j->ctx, "\""); j->out(j->ctx, heim_string_get_utf8(obj)); j->out(j->ctx, "\""); break; case HEIM_TID_DATA: { heim_dict_t d; heim_string_t v; const heim_octet_string *data; char *b64 = NULL; int ret; if (j->flags & HEIM_JSON_F_NO_DATA) return EINVAL; /* JSON doesn't do binary */ data = heim_data_get_data(obj); ret = rk_base64_encode(data->data, data->length, &b64); if (ret < 0 || b64 == NULL) return ENOMEM; if (j->flags & HEIM_JSON_F_NO_DATA_DICT) { indent(j); j->out(j->ctx, "\""); j->out(j->ctx, b64); /* base64-encode; hope there's no aliasing */ j->out(j->ctx, "\""); free(b64); } else { /* * JSON has no way to represent binary data, therefore the * following is a Heimdal-specific convention. * * We encode binary data as a dict with a single very magic * key with a base64-encoded value. The magic key includes * a uuid, so we're not likely to alias accidentally. */ d = heim_dict_create(2); if (d == NULL) { free(b64); return ENOMEM; } v = heim_string_ref_create(b64, free); if (v == NULL) { free(b64); heim_release(d); return ENOMEM; } ret = heim_dict_set_value(d, heim_tid_data_uuid_key, v); heim_release(v); if (ret) { heim_release(d); return ENOMEM; } ret = base2json(d, j); heim_release(d); if (ret) return ret; } break; } case HEIM_TID_NUMBER: { char num[32]; indent(j); snprintf(num, sizeof (num), "%d", heim_number_get_int(obj)); j->out(j->ctx, num); break; } case HEIM_TID_NULL: indent(j); j->out(j->ctx, "null"); break; case HEIM_TID_BOOL: indent(j); j->out(j->ctx, heim_bool_val(obj) ? "true" : "false"); break; default: return 1; } return 0; } static int heim_base2json(heim_object_t obj, void *ctx, heim_json_flags_t flags, void (*out)(void *, const char *)) { struct twojson j; if (flags & HEIM_JSON_F_STRICT_STRINGS) return ENOTSUP; /* Sorry, not yet! */ heim_base_once_f(&heim_json_once, NULL, json_init_once); j.indent = 0; j.ctx = ctx; j.out = out; j.flags = flags; j.ret = 0; j.first = 1; return base2json(obj, &j); } /* * */ struct parse_ctx { unsigned long lineno; const uint8_t *p; const uint8_t *pstart; const uint8_t *pend; heim_error_t error; size_t depth; heim_json_flags_t flags; }; static heim_object_t parse_value(struct parse_ctx *ctx); /* * This function eats whitespace, but, critically, it also succeeds * only if there's anything left to parse. */ static int white_spaces(struct parse_ctx *ctx) { while (ctx->p < ctx->pend) { uint8_t c = *ctx->p; if (c == ' ' || c == '\t' || c == '\r') { } else if (c == '\n') { ctx->lineno++; } else return 0; (ctx->p)++; } return -1; } static int is_number(uint8_t n) { return ('0' <= n && n <= '9'); } static heim_number_t parse_number(struct parse_ctx *ctx) { int number = 0, neg = 1; if (ctx->p >= ctx->pend) return NULL; if (*ctx->p == '-') { if (ctx->p + 1 >= ctx->pend) return NULL; neg = -1; ctx->p += 1; } while (ctx->p < ctx->pend) { if (is_number(*ctx->p)) { number = (number * 10) + (*ctx->p - '0'); } else { break; } ctx->p += 1; } return heim_number_create(number * neg); } static heim_string_t parse_string(struct parse_ctx *ctx) { const uint8_t *start; int quote = 0; if (ctx->flags & HEIM_JSON_F_STRICT_STRINGS) { ctx->error = heim_error_create(EINVAL, "Strict JSON string encoding " "not yet supported"); return NULL; } if (*ctx->p != '"') { ctx->error = heim_error_create(EINVAL, "Expected a JSON string but " "found something else at line %lu", ctx->lineno); return NULL; } start = ++ctx->p; while (ctx->p < ctx->pend) { if (*ctx->p == '\n') { ctx->lineno++; } else if (*ctx->p == '\\') { if (ctx->p + 1 == ctx->pend) goto out; ctx->p++; quote = 1; } else if (*ctx->p == '"') { heim_object_t o; if (quote) { char *p0, *p; p = p0 = malloc(ctx->p - start); if (p == NULL) goto out; while (start < ctx->p) { if (*start == '\\') { start++; /* XXX validate quoted char */ } *p++ = *start++; } o = heim_string_create_with_bytes(p0, p - p0); free(p0); } else { o = heim_string_create_with_bytes(start, ctx->p - start); if (o == NULL) { ctx->error = heim_error_create_enomem(); return NULL; } /* If we can decode as base64, then let's */ if (ctx->flags & HEIM_JSON_F_TRY_DECODE_DATA) { void *buf; size_t len; const char *s; s = heim_string_get_utf8(o); len = strlen(s); if (len >= 4 && strspn(s, base64_chars) >= len - 2) { buf = malloc(len); if (buf == NULL) { heim_release(o); ctx->error = heim_error_create_enomem(); return NULL; } len = rk_base64_decode(s, buf); if (len == -1) { free(buf); return o; } heim_release(o); o = heim_data_ref_create(buf, len, free); } } } ctx->p += 1; return o; } ctx->p += 1; } out: ctx->error = heim_error_create(EINVAL, "ran out of string"); return NULL; } static int parse_pair(heim_dict_t dict, struct parse_ctx *ctx) { heim_string_t key; heim_object_t value; if (white_spaces(ctx)) return -1; if (*ctx->p == '}') { ctx->p++; return 0; } if (ctx->flags & HEIM_JSON_F_STRICT_DICT) /* JSON allows only string keys */ key = parse_string(ctx); else /* heim_dict_t allows any heim_object_t as key */ key = parse_value(ctx); if (key == NULL) /* Even heim_dict_t does not allow C NULLs as keys though! */ return -1; if (white_spaces(ctx)) { heim_release(key); return -1; } if (*ctx->p != ':') { heim_release(key); return -1; } ctx->p += 1; /* safe because we call white_spaces() next */ if (white_spaces(ctx)) { heim_release(key); return -1; } value = parse_value(ctx); if (value == NULL && (ctx->error != NULL || (ctx->flags & HEIM_JSON_F_NO_C_NULL))) { if (ctx->error == NULL) ctx->error = heim_error_create(EINVAL, "Invalid JSON encoding"); heim_release(key); return -1; } heim_dict_set_value(dict, key, value); heim_release(key); heim_release(value); if (white_spaces(ctx)) return -1; if (*ctx->p == '}') { /* * Return 1 but don't consume the '}' so we can count the one * pair in a one-pair dict */ return 1; } else if (*ctx->p == ',') { ctx->p++; return 1; } return -1; } static heim_dict_t parse_dict(struct parse_ctx *ctx) { heim_dict_t dict; size_t count = 0; int ret; heim_assert(*ctx->p == '{', "string doesn't start with {"); dict = heim_dict_create(11); if (dict == NULL) { ctx->error = heim_error_create_enomem(); return NULL; } ctx->p += 1; /* safe because parse_pair() calls white_spaces() first */ while ((ret = parse_pair(dict, ctx)) > 0) count++; if (ret < 0) { heim_release(dict); return NULL; } if (count == 1 && !(ctx->flags & HEIM_JSON_F_NO_DATA_DICT)) { heim_object_t v = heim_dict_copy_value(dict, heim_tid_data_uuid_key); /* * Binary data encoded as a dict with a single magic key with * base64-encoded value? Decode as heim_data_t. */ if (v != NULL && heim_get_tid(v) == HEIM_TID_STRING) { void *buf; size_t len; buf = malloc(strlen(heim_string_get_utf8(v))); if (buf == NULL) { heim_release(dict); heim_release(v); ctx->error = heim_error_create_enomem(); return NULL; } len = rk_base64_decode(heim_string_get_utf8(v), buf); heim_release(v); if (len == -1) { free(buf); return dict; /* assume aliasing accident */ } heim_release(dict); return (heim_dict_t)heim_data_ref_create(buf, len, free); } } return dict; } static int parse_item(heim_array_t array, struct parse_ctx *ctx) { heim_object_t value; if (white_spaces(ctx)) return -1; if (*ctx->p == ']') { ctx->p++; /* safe because parse_value() calls white_spaces() first */ return 0; } value = parse_value(ctx); if (value == NULL && (ctx->error || (ctx->flags & HEIM_JSON_F_NO_C_NULL))) return -1; heim_array_append_value(array, value); heim_release(value); if (white_spaces(ctx)) return -1; if (*ctx->p == ']') { ctx->p++; return 0; } else if (*ctx->p == ',') { ctx->p++; return 1; } return -1; } static heim_array_t parse_array(struct parse_ctx *ctx) { heim_array_t array = heim_array_create(); int ret; heim_assert(*ctx->p == '[', "array doesn't start with ["); ctx->p += 1; while ((ret = parse_item(array, ctx)) > 0) ; if (ret < 0) { heim_release(array); return NULL; } return array; } static heim_object_t parse_value(struct parse_ctx *ctx) { size_t len; heim_object_t o; if (white_spaces(ctx)) return NULL; if (*ctx->p == '"') { return parse_string(ctx); } else if (*ctx->p == '{') { if (ctx->depth-- == 1) { ctx->error = heim_error_create(EINVAL, "JSON object too deep"); return NULL; } o = parse_dict(ctx); ctx->depth++; return o; } else if (*ctx->p == '[') { if (ctx->depth-- == 1) { ctx->error = heim_error_create(EINVAL, "JSON object too deep"); return NULL; } o = parse_array(ctx); ctx->depth++; return o; } else if (is_number(*ctx->p) || *ctx->p == '-') { return parse_number(ctx); } len = ctx->pend - ctx->p; if ((ctx->flags & HEIM_JSON_F_NO_C_NULL) == 0 && len >= 6 && memcmp(ctx->p, "", 6) == 0) { ctx->p += 6; return heim_null_create(); } else if (len >= 4 && memcmp(ctx->p, "null", 4) == 0) { ctx->p += 4; return heim_null_create(); } else if (len >= 4 && strncasecmp((char *)ctx->p, "true", 4) == 0) { ctx->p += 4; return heim_bool_create(1); } else if (len >= 5 && strncasecmp((char *)ctx->p, "false", 5) == 0) { ctx->p += 5; return heim_bool_create(0); } ctx->error = heim_error_create(EINVAL, "unknown char %c at %lu line %lu", (char)*ctx->p, (unsigned long)(ctx->p - ctx->pstart), ctx->lineno); return NULL; } heim_object_t heim_json_create(const char *string, size_t max_depth, heim_json_flags_t flags, heim_error_t *error) { return heim_json_create_with_bytes(string, strlen(string), max_depth, flags, error); } heim_object_t heim_json_create_with_bytes(const void *data, size_t length, size_t max_depth, heim_json_flags_t flags, heim_error_t *error) { struct parse_ctx ctx; heim_object_t o; heim_base_once_f(&heim_json_once, NULL, json_init_once); ctx.lineno = 1; ctx.p = data; ctx.pstart = data; ctx.pend = ((uint8_t *)data) + length; ctx.error = NULL; ctx.flags = flags; ctx.depth = max_depth; o = parse_value(&ctx); if (o == NULL && error) { *error = ctx.error; } else if (ctx.error) { heim_release(ctx.error); } return o; } static void show_printf(void *ctx, const char *str) { if (str == NULL) return; fprintf(ctx, "%s", str); } /** * Dump a heimbase object to stderr (useful from the debugger!) * * @param obj object to dump using JSON or JSON-like format * * @addtogroup heimbase */ void heim_show(heim_object_t obj) { heim_base2json(obj, stderr, HEIM_JSON_F_NO_DATA_DICT, show_printf); } static void strbuf_add(void *ctx, const char *str) { struct heim_strbuf *strbuf = ctx; size_t len; if (strbuf->enomem) return; if (str == NULL) { /* * Eat the last '\n'; this is used when formatting dict pairs * and array items so that the ',' separating them is never * preceded by a '\n'. */ if (strbuf->len > 0 && strbuf->str[strbuf->len - 1] == '\n') strbuf->len--; return; } len = strlen(str); if ((len + 1) > (strbuf->alloced - strbuf->len)) { size_t new_len = strbuf->alloced + (strbuf->alloced >> 2) + len + 1; char *s; s = realloc(strbuf->str, new_len); if (s == NULL) { strbuf->enomem = 1; return; } strbuf->str = s; strbuf->alloced = new_len; } /* +1 so we copy the NUL */ (void) memcpy(strbuf->str + strbuf->len, str, len + 1); strbuf->len += len; if (strbuf->str[strbuf->len - 1] == '\n' && strbuf->flags & HEIM_JSON_F_ONE_LINE) strbuf->len--; } #define STRBUF_INIT_SZ 64 heim_string_t heim_json_copy_serialize(heim_object_t obj, heim_json_flags_t flags, heim_error_t *error) { heim_string_t str; struct heim_strbuf strbuf; int ret; if (error) *error = NULL; memset(&strbuf, 0, sizeof (strbuf)); strbuf.str = malloc(STRBUF_INIT_SZ); if (strbuf.str == NULL) { if (error) *error = heim_error_create_enomem(); return NULL; } strbuf.len = 0; strbuf.alloced = STRBUF_INIT_SZ; strbuf.str[0] = '\0'; strbuf.flags = flags; ret = heim_base2json(obj, &strbuf, flags, strbuf_add); if (ret || strbuf.enomem) { if (error) { if (strbuf.enomem || ret == ENOMEM) *error = heim_error_create_enomem(); else *error = heim_error_create(1, "Impossible to JSON-encode " "object"); } free(strbuf.str); return NULL; } if (flags & HEIM_JSON_F_ONE_LINE) { strbuf.flags &= ~HEIM_JSON_F_ONE_LINE; strbuf_add(&strbuf, "\n"); } str = heim_string_ref_create(strbuf.str, free); if (str == NULL) { if (error) *error = heim_error_create_enomem(); free(strbuf.str); } return str; } heimdal-7.5.0/lib/base/dict.c0000644000175000017500000001423713026237312014027 0ustar niknik/* * Copyright (c) 2002, 1997 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Portions Copyright (c) 2010 Apple Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "baselocl.h" struct hashentry { struct hashentry **prev; struct hashentry *next; heim_object_t key; heim_object_t value; }; struct heim_dict_data { size_t size; struct hashentry **tab; }; static void dict_dealloc(void *ptr) { heim_dict_t dict = ptr; struct hashentry **h, *g, *i; for (h = dict->tab; h < &dict->tab[dict->size]; ++h) { for (g = h[0]; g; g = i) { i = g->next; heim_release(g->key); heim_release(g->value); free(g); } } free(dict->tab); } struct heim_type_data dict_object = { HEIM_TID_DICT, "dict-object", NULL, dict_dealloc, NULL, NULL, NULL, NULL }; static size_t isprime(size_t p) { size_t q, i; for(i = 2 ; i < p; i++) { q = p / i; if (i * q == p) return 0; if (i * i > p) return 1; } return 1; } static size_t findprime(size_t p) { if (p % 2 == 0) p++; while (isprime(p) == 0) p += 2; return p; } /** * Allocate an array * * @return A new allocated array, free with heim_release() */ heim_dict_t heim_dict_create(size_t size) { heim_dict_t dict; dict = _heim_alloc_object(&dict_object, sizeof(*dict)); dict->size = findprime(size); if (dict->size == 0) { heim_release(dict); return NULL; } dict->tab = calloc(dict->size, sizeof(dict->tab[0])); if (dict->tab == NULL) { dict->size = 0; heim_release(dict); return NULL; } return dict; } /** * Get type id of an dict * * @return the type id */ heim_tid_t heim_dict_get_type_id(void) { return HEIM_TID_DICT; } /* Intern search function */ static struct hashentry * _search(heim_dict_t dict, heim_object_t ptr) { unsigned long v = heim_get_hash(ptr); struct hashentry *p; for (p = dict->tab[v % dict->size]; p != NULL; p = p->next) if (heim_cmp(ptr, p->key) == 0) return p; return NULL; } /** * Search for element in hash table * * @value dict the dict to search in * @value key the key to search for * * @return a not-retained copy of the value for key or NULL if not found */ heim_object_t heim_dict_get_value(heim_dict_t dict, heim_object_t key) { struct hashentry *p; p = _search(dict, key); if (p == NULL) return NULL; return p->value; } /** * Search for element in hash table * * @value dict the dict to search in * @value key the key to search for * * @return a retained copy of the value for key or NULL if not found */ heim_object_t heim_dict_copy_value(heim_dict_t dict, heim_object_t key) { struct hashentry *p; p = _search(dict, key); if (p == NULL) return NULL; return heim_retain(p->value); } /** * Add key and value to dict * * @value dict the dict to add too * @value key the key to add * @value value the value to add * * @return 0 if added, errno if not */ int heim_dict_set_value(heim_dict_t dict, heim_object_t key, heim_object_t value) { struct hashentry **tabptr, *h; h = _search(dict, key); if (h) { heim_release(h->value); h->value = heim_retain(value); } else { unsigned long v; h = malloc(sizeof(*h)); if (h == NULL) return ENOMEM; h->key = heim_retain(key); h->value = heim_retain(value); v = heim_get_hash(key); tabptr = &dict->tab[v % dict->size]; h->next = *tabptr; *tabptr = h; h->prev = tabptr; if (h->next) h->next->prev = &h->next; } return 0; } /** * Delete element with key key * * @value dict the dict to delete from * @value key the key to delete */ void heim_dict_delete_key(heim_dict_t dict, heim_object_t key) { struct hashentry *h = _search(dict, key); if (h == NULL) return; heim_release(h->key); heim_release(h->value); if ((*(h->prev) = h->next) != NULL) h->next->prev = h->prev; free(h); } /** * Do something for each element * * @value dict the dict to interate over * @value func the function to search for * @value arg argument to func */ void heim_dict_iterate_f(heim_dict_t dict, void *arg, heim_dict_iterator_f_t func) { struct hashentry **h, *g; for (h = dict->tab; h < &dict->tab[dict->size]; ++h) for (g = *h; g; g = g->next) func(g->key, g->value, arg); } #ifdef __BLOCKS__ /** * Do something for each element * * @value dict the dict to interate over * @value func the function to search for */ void heim_dict_iterate(heim_dict_t dict, void (^func)(heim_object_t, heim_object_t)) { struct hashentry **h, *g; for (h = dict->tab; h < &dict->tab[dict->size]; ++h) for (g = *h; g; g = g->next) func(g->key, g->value); } #endif heimdal-7.5.0/lib/gssapi/0000755000175000017500000000000013214604041013301 5ustar niknikheimdal-7.5.0/lib/gssapi/test_acquire_cred.c0000644000175000017500000002101413026237312017134 0ustar niknik/* * Copyright (c) 2003-2007 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of KTH nor the names of its contributors may be * used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY KTH AND ITS CONTRIBUTORS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL KTH OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifdef HAVE_CONFIG_H #include #endif #include #include #include #include #include #include #include #include #include #include #include "test_common.h" static void print_time(OM_uint32 time_rec) { if (time_rec == GSS_C_INDEFINITE) { printf("cred never expire\n"); } else { time_t t = time_rec + time(NULL); printf("expiration time: %s", ctime(&t)); } } #if 0 static void test_add(gss_cred_id_t cred_handle) { OM_uint32 major_status, minor_status; gss_cred_id_t copy_cred; OM_uint32 time_rec; major_status = gss_add_cred (&minor_status, cred_handle, GSS_C_NO_NAME, GSS_KRB5_MECHANISM, GSS_C_INITIATE, 0, 0, ©_cred, NULL, &time_rec, NULL); if (GSS_ERROR(major_status)) errx(1, "add_cred failed"); print_time(time_rec); major_status = gss_release_cred(&minor_status, ©_cred); if (GSS_ERROR(major_status)) errx(1, "release_cred failed"); } static void copy_cred(void) { OM_uint32 major_status, minor_status; gss_cred_id_t cred_handle; OM_uint32 time_rec; major_status = gss_acquire_cred(&minor_status, GSS_C_NO_NAME, 0, NULL, GSS_C_INITIATE, &cred_handle, NULL, &time_rec); if (GSS_ERROR(major_status)) errx(1, "acquire_cred failed"); print_time(time_rec); test_add(cred_handle); test_add(cred_handle); test_add(cred_handle); major_status = gss_release_cred(&minor_status, &cred_handle); if (GSS_ERROR(major_status)) errx(1, "release_cred failed"); } #endif static gss_cred_id_t acquire_cred_service(const char *service, gss_OID nametype, gss_OID_set oidset, int flags) { OM_uint32 major_status, minor_status; gss_cred_id_t cred_handle; OM_uint32 time_rec; gss_buffer_desc name_buffer; gss_name_t name = GSS_C_NO_NAME; if (service) { name_buffer.value = rk_UNCONST(service); name_buffer.length = strlen(service); major_status = gss_import_name(&minor_status, &name_buffer, nametype, &name); if (GSS_ERROR(major_status)) errx(1, "import_name failed"); } major_status = gss_acquire_cred(&minor_status, name, 0, oidset, flags, &cred_handle, NULL, &time_rec); if (GSS_ERROR(major_status)) { warnx("acquire_cred failed: %s", gssapi_err(major_status, minor_status, GSS_C_NO_OID)); } else { print_time(time_rec); gss_release_cred(&minor_status, &cred_handle); } if (name != GSS_C_NO_NAME) gss_release_name(&minor_status, &name); if (GSS_ERROR(major_status)) exit(1); return cred_handle; } static int version_flag = 0; static int help_flag = 0; static int kerberos_flag = 0; static int enctype = 0; static char *acquire_name; static char *acquire_type; static char *target_name; static char *name_type; static char *ccache; static int num_loops = 1; static struct getargs args[] = { {"acquire-name", 0, arg_string, &acquire_name, "name", NULL }, {"acquire-type", 0, arg_string, &acquire_type, "type", NULL }, {"enctype", 0, arg_integer, &enctype, "enctype-num", NULL }, {"loops", 0, arg_integer, &num_loops, "enctype-num", NULL }, {"kerberos", 0, arg_flag, &kerberos_flag, "enctype-num", NULL }, {"target-name", 0, arg_string, &target_name, "name", NULL }, {"ccache", 0, arg_string, &ccache, "name", NULL }, {"name-type", 0, arg_string, &name_type, "type", NULL }, {"version", 0, arg_flag, &version_flag, "print version", NULL }, {"help", 0, arg_flag, &help_flag, NULL, NULL } }; static void usage (int ret) { arg_printusage (args, sizeof(args)/sizeof(*args), NULL, ""); exit (ret); } int main(int argc, char **argv) { gss_OID_set oidset = GSS_C_NULL_OID_SET; gss_OID mechoid = GSS_C_NO_OID; OM_uint32 maj_stat, min_stat; gss_cred_id_t cred; gss_name_t target = GSS_C_NO_NAME; int i, optidx = 0; OM_uint32 flag; gss_OID type; setprogname(argv[0]); if(getarg(args, sizeof(args) / sizeof(args[0]), argc, argv, &optidx)) usage(1); if (help_flag) usage (0); if(version_flag){ print_version(NULL); exit(0); } argc -= optidx; argv += optidx; if (argc != 0) usage(1); if (acquire_type) { if (strcasecmp(acquire_type, "both") == 0) flag = GSS_C_BOTH; else if (strcasecmp(acquire_type, "accept") == 0) flag = GSS_C_ACCEPT; else if (strcasecmp(acquire_type, "initiate") == 0) flag = GSS_C_INITIATE; else errx(1, "unknown type %s", acquire_type); } else flag = GSS_C_ACCEPT; if (name_type) { if (strcasecmp("hostbased-service", name_type) == 0) type = GSS_C_NT_HOSTBASED_SERVICE; else if (strcasecmp("user-name", name_type) == 0) type = GSS_C_NT_USER_NAME; else errx(1, "unknown name type %s", name_type); } else type = GSS_C_NT_HOSTBASED_SERVICE; if (ccache) { maj_stat = gss_krb5_ccache_name(&min_stat, ccache, NULL); if (GSS_ERROR(maj_stat)) errx(1, "gss_krb5_ccache_name %s", gssapi_err(maj_stat, min_stat, GSS_C_NO_OID)); } if (kerberos_flag) { mechoid = GSS_KRB5_MECHANISM; maj_stat = gss_create_empty_oid_set(&min_stat, &oidset); if (maj_stat != GSS_S_COMPLETE) errx(1, "gss_create_empty_oid_set: %s", gssapi_err(maj_stat, min_stat, GSS_C_NO_OID)); maj_stat = gss_add_oid_set_member(&min_stat, GSS_KRB5_MECHANISM, &oidset); if (maj_stat != GSS_S_COMPLETE) errx(1, "gss_add_oid_set_member: %s", gssapi_err(maj_stat, min_stat, GSS_C_NO_OID)); } if (target_name) { gss_buffer_desc name; name.value = target_name; name.length = strlen(target_name); maj_stat = gss_import_name(&min_stat, &name, GSS_C_NT_HOSTBASED_SERVICE, &target); if (maj_stat != GSS_S_COMPLETE) errx(1, "gss_import_name: %s", gssapi_err(maj_stat, min_stat, GSS_C_NO_OID)); } for (i = 0; i < num_loops; i++) { cred = acquire_cred_service(acquire_name, type, oidset, flag); if (enctype) { int32_t enctypelist = enctype; maj_stat = gss_krb5_set_allowable_enctypes(&min_stat, cred, 1, &enctypelist); if (maj_stat) errx(1, "gss_krb5_set_allowable_enctypes: %s", gssapi_err(maj_stat, min_stat, GSS_C_NO_OID)); } if (target) { gss_ctx_id_t context = GSS_C_NO_CONTEXT; gss_buffer_desc out; out.length = 0; out.value = NULL; maj_stat = gss_init_sec_context(&min_stat, cred, &context, target, mechoid, GSS_C_MUTUAL_FLAG, 0, NULL, GSS_C_NO_BUFFER, NULL, &out, NULL, NULL); if (maj_stat != GSS_S_COMPLETE && maj_stat != GSS_S_CONTINUE_NEEDED) errx(1, "init_sec_context failed: %s", gssapi_err(maj_stat, min_stat, GSS_C_NO_OID)); gss_release_buffer(&min_stat, &out); gss_delete_sec_context(&min_stat, &context, NULL); } gss_release_cred(&min_stat, &cred); } return 0; } heimdal-7.5.0/lib/gssapi/gsstool.c0000644000175000017500000001531513026237312015150 0ustar niknik/* * Copyright (c) 2006 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Portions Copyright (c) 2009 - 2010 Apple Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of KTH nor the names of its contributors may be * used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY KTH AND ITS CONTRIBUTORS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL KTH OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include #include #include #include #include #include #include #include #include #include #include static int version_flag = 0; static int help_flag = 0; static struct getargs args[] = { {"version", 0, arg_flag, &version_flag, "print version", NULL }, {"help", 0, arg_flag, &help_flag, NULL, NULL } }; static void usage (int ret) { arg_printusage (args, sizeof(args)/sizeof(*args), NULL, "service@host"); exit (ret); } #define COL_OID "OID" #define COL_NAME "Name" #define COL_DESC "Description" #define COL_VALUE "Value" #define COL_MECH "Mech" #define COL_EXPIRE "Expire" #define COL_SASL "SASL" int mechanisms(void *argptr, int argc, char **argv) { OM_uint32 maj_stat, min_stat; gss_OID_set mechs; rtbl_t ct; size_t i; maj_stat = gss_indicate_mechs(&min_stat, &mechs); if (maj_stat != GSS_S_COMPLETE) errx(1, "gss_indicate_mechs failed"); printf("Supported mechanisms:\n"); ct = rtbl_create(); if (ct == NULL) errx(1, "rtbl_create"); rtbl_set_separator(ct, " "); rtbl_add_column(ct, COL_OID, 0); rtbl_add_column(ct, COL_NAME, 0); rtbl_add_column(ct, COL_DESC, 0); rtbl_add_column(ct, COL_SASL, 0); for (i = 0; i < mechs->count; i++) { gss_buffer_desc str, sasl_name, mech_name, mech_desc; maj_stat = gss_oid_to_str(&min_stat, &mechs->elements[i], &str); if (maj_stat != GSS_S_COMPLETE) errx(1, "gss_oid_to_str failed"); rtbl_add_column_entryv(ct, COL_OID, "%.*s", (int)str.length, (char *)str.value); gss_release_buffer(&min_stat, &str); (void)gss_inquire_saslname_for_mech(&min_stat, &mechs->elements[i], &sasl_name, &mech_name, &mech_desc); rtbl_add_column_entryv(ct, COL_NAME, "%.*s", (int)mech_name.length, (char *)mech_name.value); rtbl_add_column_entryv(ct, COL_DESC, "%.*s", (int)mech_desc.length, (char *)mech_desc.value); rtbl_add_column_entryv(ct, COL_SASL, "%.*s", (int)sasl_name.length, (char *)sasl_name.value); gss_release_buffer(&min_stat, &mech_name); gss_release_buffer(&min_stat, &mech_desc); gss_release_buffer(&min_stat, &sasl_name); } gss_release_oid_set(&min_stat, &mechs); rtbl_format(ct, stdout); rtbl_destroy(ct); return 0; } static void print_mech_attr(const char *mechname, gss_const_OID mech, gss_OID_set set) { gss_buffer_desc name, desc; OM_uint32 major, minor; rtbl_t ct; size_t n; ct = rtbl_create(); if (ct == NULL) errx(1, "rtbl_create"); rtbl_set_separator(ct, " "); rtbl_add_column(ct, COL_OID, 0); rtbl_add_column(ct, COL_DESC, 0); if (mech) rtbl_add_column(ct, COL_VALUE, 0); for (n = 0; n < set->count; n++) { major = gss_display_mech_attr(&minor, &set->elements[n], &name, &desc, NULL); if (major) continue; rtbl_add_column_entryv(ct, COL_OID, "%.*s", (int)name.length, (char *)name.value); rtbl_add_column_entryv(ct, COL_DESC, "%.*s", (int)desc.length, (char *)desc.value); if (mech) { gss_buffer_desc value; if (gss_mo_get(mech, &set->elements[n], &value) != 0) value.length = 0; if (value.length) rtbl_add_column_entryv(ct, COL_VALUE, "%.*s", (int)value.length, (char *)value.value); else rtbl_add_column_entryv(ct, COL_VALUE, "<>"); gss_release_buffer(&minor, &value); } gss_release_buffer(&minor, &name); gss_release_buffer(&minor, &desc); } printf("attributes for: %s\n", mechname); rtbl_format(ct, stdout); rtbl_destroy(ct); } int attributes(struct attributes_options *opt, int argc, char **argv) { gss_OID_set mech_attr = NULL, known_mech_attrs = NULL; gss_OID mech = GSS_C_NO_OID; OM_uint32 major, minor; if (opt->mech_string) { mech = gss_name_to_oid(opt->mech_string); if (mech == NULL) errx(1, "mech %s is unknown", opt->mech_string); } major = gss_inquire_attrs_for_mech(&minor, mech, &mech_attr, &known_mech_attrs); if (major) errx(1, "gss_inquire_attrs_for_mech"); if (mech) { print_mech_attr(opt->mech_string, mech, mech_attr); } if (opt->all_flag) { print_mech_attr("all mechs", NULL, known_mech_attrs); } gss_release_oid_set(&minor, &mech_attr); gss_release_oid_set(&minor, &known_mech_attrs); return 0; } /* * */ int help(void *opt, int argc, char **argv) { sl_slc_help(commands, argc, argv); return 0; } int main(int argc, char **argv) { int exit_status = 0, ret, optidx = 0; setprogname(argv[0]); if(getarg(args, sizeof(args) / sizeof(args[0]), argc, argv, &optidx)) usage(1); if (help_flag) usage (0); if(version_flag){ print_version(NULL); exit(0); } argc -= optidx; argv += optidx; if (argc != 0) { ret = sl_command(commands, argc, argv); if(ret == -1) sl_did_you_mean(commands, argv[0]); else if (ret == -2) ret = 0; if(ret != 0) exit_status = 1; } else { sl_slc_help(commands, argc, argv); exit_status = 1; } return exit_status; } heimdal-7.5.0/lib/gssapi/gen-oid.pl0000644000175000017500000000743713026237312015177 0ustar niknik#!/usr/bin/perl # # Copyright (c) 2010 Kungliga Tekniska Högskolan # (Royal Institute of Technology, Stockholm, Sweden). # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # 1. Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # # 3. Neither the name of the Institute nor the names of its contributors # may be used to endorse or promote products derived from this software # without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE # ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS # OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) # HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY # OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF # SUCH DAMAGE. use Getopt::Std; my $output; my $CFILE, $HFILE; my $onlybase; my $header = 0; getopts('b:h') || die "USAGE: ./gen-oid [-b BASE] [-h HEADER]"; if($opt_b) { $onlybase = $opt_b; } $header = 1 if ($opt_h); printf "/* Generated file */\n"; if ($header) { printf "#ifndef GSSAPI_GSSAPI_OID\n"; printf "#define GSSAPI_GSSAPI_OID 1\n\n"; } else { printf "#include \"mech_locl.h\"\n\n"; } my %tables; my %types; while(<>) { if (/^\w*#(.*)/) { my $comment = $1; if ($header) { printf("$comment\n"); } } elsif (/^oid\s+([\w\.]+)\s+(\w+)\s+([\w\.]+)/) { my ($base, $name, $oid) = ($1, $2, $3); next if (defined $onlybase and $onlybase ne $base); my $store = "__" . lc($name) . "_oid_desc"; # encode oid my @array = split(/\./, $oid); my $length = 0; my $data = ""; my $num; $n = $#array; while ($n > 1) { $num = $array[$n]; my $p = int($num % 128); $data = sprintf("\\x%02x", $p) . $data; $num = int($num / 128); $length += 1; while ($num > 0) { $p = int($num % 128) + 128; $num = int($num / 128); $data = sprintf("\\x%02x", $p) . $data; $length += 1; } $n--; } $num = int($array[0] * 40 + $array[1]); $data = sprintf("\\x%x", $num) . $data; $length += 1; if ($header) { printf "extern GSSAPI_LIB_VARIABLE gss_OID_desc $store;\n"; printf "#define $name (&$store)\n\n"; } else { printf "/* $name - $oid */\n"; printf "gss_OID_desc GSSAPI_LIB_VARIABLE $store = { $length, rk_UNCONST(\"$data\") };\n\n"; } } elsif (/^desc\s+([\w]+)\s+(\w+)\s+(\"[^\"]*\")\s+(\"[^\"]*\")/) { my ($type, $oid, $short, $long) = ($1, $2, $3, $4); my $object = { type=> $type, oid => $oid, short => $short, long => $long }; $tables{$oid} = \$object; $types{$type} = 1; } } foreach my $k (sort keys %types) { if (!$header) { print "struct _gss_oid_name_table _gss_ont_" . $k . "[] = {\n"; foreach my $m (sort {$$a->{oid} cmp $$b->{oid}} values %tables) { if ($$m->{type} eq $k) { printf " { %s, \"%s\", %s, %s },\n", $$m->{oid}, $$m->{oid}, $$m->{short}, $$m->{long}; } } printf " { NULL, NULL, NULL, NULL }\n"; printf "};\n\n"; } } if ($header) { printf "#endif /* GSSAPI_GSSAPI_OID */\n"; } heimdal-7.5.0/lib/gssapi/mech/0000755000175000017500000000000013214604041014215 5ustar niknikheimdal-7.5.0/lib/gssapi/mech/gss_add_cred_with_password.c0000644000175000017500000001131713026237312021746 0ustar niknik/*- * Copyright (c) 2005 Doug Rabson * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * * $FreeBSD: src/lib/libgssapi/gss_add_cred.c,v 1.1 2005/12/29 14:40:20 dfr Exp $ */ #include "mech_locl.h" GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL gss_add_cred_with_password(OM_uint32 *minor_status, gss_const_cred_id_t input_cred_handle, gss_const_name_t desired_name, const gss_OID desired_mech, const gss_buffer_t password, gss_cred_usage_t cred_usage, OM_uint32 initiator_time_req, OM_uint32 acceptor_time_req, gss_cred_id_t *output_cred_handle, gss_OID_set *actual_mechs, OM_uint32 *initiator_time_rec, OM_uint32 *acceptor_time_rec) { OM_uint32 major_status; gssapi_mech_interface m; struct _gss_cred *cred = (struct _gss_cred *) input_cred_handle; struct _gss_cred *new_cred; struct _gss_mechanism_cred *mc; struct _gss_mechanism_name *mn = NULL; OM_uint32 junk, time_req; *minor_status = 0; *output_cred_handle = GSS_C_NO_CREDENTIAL; if (initiator_time_rec) *initiator_time_rec = 0; if (acceptor_time_rec) *acceptor_time_rec = 0; if (actual_mechs) *actual_mechs = GSS_C_NO_OID_SET; m = __gss_get_mechanism(desired_mech); if (m == NULL) { *minor_status = 0; return (GSS_S_BAD_MECH); } new_cred = calloc(1, sizeof(struct _gss_cred)); if (new_cred == NULL) { *minor_status = ENOMEM; return (GSS_S_FAILURE); } HEIM_SLIST_INIT(&new_cred->gc_mc); /* * Copy credentials from un-desired mechanisms to the new credential. */ if (cred) { HEIM_SLIST_FOREACH(mc, &cred->gc_mc, gmc_link) { struct _gss_mechanism_cred *copy_mc; if (gss_oid_equal(mc->gmc_mech_oid, desired_mech)) { continue; } copy_mc = _gss_copy_cred(mc); if (copy_mc == NULL) { gss_release_cred(&junk, (gss_cred_id_t *)&new_cred); *minor_status = ENOMEM; return (GSS_S_FAILURE); } HEIM_SLIST_INSERT_HEAD(&new_cred->gc_mc, copy_mc, gmc_link); } } /* * Figure out a suitable mn, if any. */ if (desired_name != GSS_C_NO_NAME) { major_status = _gss_find_mn(minor_status, (struct _gss_name *) desired_name, desired_mech, &mn); if (major_status != GSS_S_COMPLETE) { gss_release_cred(&junk, (gss_cred_id_t *)&new_cred); return (major_status); } } if (cred_usage == GSS_C_BOTH) time_req = initiator_time_req > acceptor_time_req ? acceptor_time_req : initiator_time_req; else if (cred_usage == GSS_C_INITIATE) time_req = initiator_time_req; else time_req = acceptor_time_req; major_status = _gss_acquire_mech_cred(minor_status, m, mn, GSS_C_CRED_PASSWORD, password, time_req, desired_mech, cred_usage, &mc); if (major_status != GSS_S_COMPLETE) { gss_release_cred(&junk, (gss_cred_id_t *)&new_cred); return (major_status); } HEIM_SLIST_INSERT_HEAD(&new_cred->gc_mc, mc, gmc_link); if (actual_mechs || initiator_time_rec || acceptor_time_rec) { OM_uint32 time_rec; major_status = gss_inquire_cred(minor_status, (gss_cred_id_t)new_cred, NULL, &time_rec, NULL, actual_mechs); if (GSS_ERROR(major_status)) { gss_release_cred(&junk, (gss_cred_id_t *)&new_cred); return (major_status); } if (initiator_time_rec && (cred_usage == GSS_C_INITIATE || cred_usage == GSS_C_BOTH)) *initiator_time_rec = time_rec; if (acceptor_time_rec && (cred_usage == GSS_C_ACCEPT || cred_usage == GSS_C_BOTH)) *acceptor_time_rec = time_rec; } *output_cred_handle = (gss_cred_id_t) new_cred; return (GSS_S_COMPLETE); } heimdal-7.5.0/lib/gssapi/mech/gss_acquire_cred_ext.c0000644000175000017500000001320713026237312020552 0ustar niknik/*- * Copyright (c) 2005 Doug Rabson * All rights reserved. * * Portions Copyright (c) 2011 PADL Software Pty Ltd. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * * $FreeBSD: src/lib/libgssapi/gss_acquire_cred.c,v 1.1 2005/12/29 14:40:20 dfr Exp $ */ #include "mech_locl.h" OM_uint32 _gss_acquire_mech_cred(OM_uint32 *minor_status, gssapi_mech_interface m, const struct _gss_mechanism_name *mn, gss_const_OID credential_type, const void *credential_data, OM_uint32 time_req, gss_const_OID desired_mech, gss_cred_usage_t cred_usage, struct _gss_mechanism_cred **output_cred_handle) { OM_uint32 major_status; struct _gss_mechanism_cred *mc; gss_OID_set_desc set2; *output_cred_handle = NULL; mc = calloc(1, sizeof(struct _gss_mechanism_cred)); if (mc == NULL) { *minor_status = ENOMEM; return GSS_S_FAILURE; } mc->gmc_mech = m; mc->gmc_mech_oid = &m->gm_mech_oid; set2.count = 1; set2.elements = mc->gmc_mech_oid; if (m->gm_acquire_cred_ext) { major_status = m->gm_acquire_cred_ext(minor_status, mn->gmn_name, credential_type, credential_data, time_req, mc->gmc_mech_oid, cred_usage, &mc->gmc_cred); } else if (gss_oid_equal(credential_type, GSS_C_CRED_PASSWORD) && m->gm_compat && m->gm_compat->gmc_acquire_cred_with_password) { /* * Shim for mechanisms that adhere to API-as-SPI and do not * implement gss_acquire_cred_ext(). */ major_status = m->gm_compat->gmc_acquire_cred_with_password(minor_status, mn->gmn_name, (const gss_buffer_t)credential_data, time_req, &set2, cred_usage, &mc->gmc_cred, NULL, NULL); } else if (credential_type == GSS_C_NO_OID) { major_status = m->gm_acquire_cred(minor_status, mn->gmn_name, time_req, &set2, cred_usage, &mc->gmc_cred, NULL, NULL); } else { major_status = GSS_S_UNAVAILABLE; free(mc); mc= NULL; } if (major_status != GSS_S_COMPLETE) free(mc); else *output_cred_handle = mc; return major_status; } /** * This function is not a public interface and is deprecated anyways, do * not use. Use gss_acquire_cred_with_password() instead for now. * * @deprecated */ OM_uint32 _gss_acquire_cred_ext(OM_uint32 *minor_status, gss_const_name_t desired_name, gss_const_OID credential_type, const void *credential_data, OM_uint32 time_req, gss_const_OID desired_mech, gss_cred_usage_t cred_usage, gss_cred_id_t *output_cred_handle) { OM_uint32 major_status; struct _gss_name *name = (struct _gss_name *) desired_name; gssapi_mech_interface m; struct _gss_cred *cred; gss_OID_set_desc set, *mechs; size_t i; *minor_status = 0; if (output_cred_handle == NULL) return GSS_S_CALL_INACCESSIBLE_READ; _gss_load_mech(); if (desired_mech != GSS_C_NO_OID) { int match = 0; gss_test_oid_set_member(minor_status, (gss_OID)desired_mech, _gss_mech_oids, &match); if (!match) return GSS_S_BAD_MECH; set.count = 1; set.elements = (gss_OID)desired_mech; mechs = &set; } else mechs = _gss_mech_oids; cred = calloc(1, sizeof(*cred)); if (cred == NULL) { *minor_status = ENOMEM; return GSS_S_FAILURE; } HEIM_SLIST_INIT(&cred->gc_mc); for (i = 0; i < mechs->count; i++) { struct _gss_mechanism_name *mn = NULL; struct _gss_mechanism_cred *mc = NULL; m = __gss_get_mechanism(&mechs->elements[i]); if (!m) continue; if (desired_name != GSS_C_NO_NAME) { major_status = _gss_find_mn(minor_status, name, &mechs->elements[i], &mn); if (major_status != GSS_S_COMPLETE) continue; } major_status = _gss_acquire_mech_cred(minor_status, m, mn, credential_type, credential_data, time_req, desired_mech, cred_usage, &mc); if (GSS_ERROR(major_status)) { if (mechs->count == 1) _gss_mg_error(m, major_status, *minor_status); continue; } HEIM_SLIST_INSERT_HEAD(&cred->gc_mc, mc, gmc_link); } /* * If we didn't manage to create a single credential, return * an error. */ if (!HEIM_SLIST_FIRST(&cred->gc_mc)) { free(cred); if (mechs->count > 1) *minor_status = 0; return GSS_S_NO_CRED; } *output_cred_handle = (gss_cred_id_t) cred; *minor_status = 0; return GSS_S_COMPLETE; } heimdal-7.5.0/lib/gssapi/mech/gss_decapsulate_token.c0000644000175000017500000000476513026237312020747 0ustar niknik/* * Copyright (c) 2006 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "mech_locl.h" GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL gss_decapsulate_token(gss_const_buffer_t input_token, gss_const_OID oid, gss_buffer_t output_token) { GSSAPIContextToken ct; heim_oid o; OM_uint32 status; int ret; size_t size; _mg_buffer_zero(output_token); ret = der_get_oid (oid->elements, oid->length, &o, &size); if (ret) return GSS_S_FAILURE; ret = decode_GSSAPIContextToken(input_token->value, input_token->length, &ct, NULL); if (ret) { der_free_oid(&o); return GSS_S_FAILURE; } if (der_heim_oid_cmp(&ct.thisMech, &o) == 0) { status = GSS_S_COMPLETE; output_token->value = ct.innerContextToken.data; output_token->length = ct.innerContextToken.length; der_free_oid(&ct.thisMech); } else { free_GSSAPIContextToken(&ct); status = GSS_S_FAILURE; } der_free_oid(&o); return status; } heimdal-7.5.0/lib/gssapi/mech/gss_release_name.c0000644000175000017500000000504513026237312017665 0ustar niknik/*- * Copyright (c) 2005 Doug Rabson * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * * $FreeBSD: src/lib/libgssapi/gss_release_name.c,v 1.1 2005/12/29 14:40:20 dfr Exp $ */ #include "mech_locl.h" /** * Free a name * * import_name can point to NULL or be NULL, or a pointer to a * gss_name_t structure. If it was a pointer to gss_name_t, the * pointer will be set to NULL on success and failure. * * @param minor_status minor status code * @param input_name name to free * * @returns a gss_error code, see gss_display_status() about printing * the error code. * * @ingroup gssapi */ GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL gss_release_name(OM_uint32 *minor_status, gss_name_t *input_name) { struct _gss_name *name; *minor_status = 0; if (input_name == NULL || *input_name == NULL) return GSS_S_COMPLETE; name = (struct _gss_name *) *input_name; if (name->gn_type.elements) free(name->gn_type.elements); while (HEIM_SLIST_FIRST(&name->gn_mn)) { struct _gss_mechanism_name *mn; mn = HEIM_SLIST_FIRST(&name->gn_mn); HEIM_SLIST_REMOVE_HEAD(&name->gn_mn, gmn_link); mn->gmn_mech->gm_release_name(minor_status, &mn->gmn_name); free(mn); } gss_release_buffer(minor_status, &name->gn_value); free(name); *input_name = GSS_C_NO_NAME; return (GSS_S_COMPLETE); } heimdal-7.5.0/lib/gssapi/mech/gss_set_name_attribute.c0000644000175000017500000000515513026237312021125 0ustar niknik/* * Copyright (c) 2010, PADL Software Pty Ltd. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of PADL Software nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY PADL SOFTWARE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL PADL SOFTWARE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "mech_locl.h" GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL gss_set_name_attribute(OM_uint32 *minor_status, gss_name_t input_name, int complete, gss_buffer_t attr, gss_buffer_t value) { OM_uint32 major_status = GSS_S_UNAVAILABLE; struct _gss_name *name = (struct _gss_name *) input_name; struct _gss_mechanism_name *mn; *minor_status = 0; if (input_name == GSS_C_NO_NAME) return GSS_S_BAD_NAME; HEIM_SLIST_FOREACH(mn, &name->gn_mn, gmn_link) { gssapi_mech_interface m = mn->gmn_mech; if (!m->gm_set_name_attribute) continue; major_status = m->gm_set_name_attribute(minor_status, mn->gmn_name, complete, attr, value); if (GSS_ERROR(major_status)) _gss_mg_error(m, major_status, *minor_status); else break; } return major_status; } heimdal-7.5.0/lib/gssapi/mech/gss_verify.c0000644000175000017500000000337312136107747016564 0ustar niknik/*- * Copyright (c) 2005 Doug Rabson * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * * $FreeBSD: src/lib/libgssapi/gss_verify.c,v 1.1 2005/12/29 14:40:20 dfr Exp $ */ #include "mech_locl.h" GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL gss_verify(OM_uint32 *minor_status, gss_ctx_id_t context_handle, gss_buffer_t message_buffer, gss_buffer_t token_buffer, int *qop_state) { return (gss_verify_mic(minor_status, context_handle, message_buffer, token_buffer, (gss_qop_t *)qop_state)); } heimdal-7.5.0/lib/gssapi/mech/gss_release_oid.c0000644000175000017500000000401312136107747017523 0ustar niknik/* * Copyright (c) 2006 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "mech_locl.h" GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL gss_release_oid(OM_uint32 *minor_status, gss_OID *oid) { gss_OID o = *oid; *oid = GSS_C_NO_OID; if (minor_status != NULL) *minor_status = 0; if (o == GSS_C_NO_OID) return GSS_S_COMPLETE; if (o->elements != NULL) { free(o->elements); o->elements = NULL; } o->length = 0; free(o); return GSS_S_COMPLETE; } heimdal-7.5.0/lib/gssapi/mech/gss_set_sec_context_option.c0000644000175000017500000000455612136107747022045 0ustar niknik/* * Copyright (c) 2004, PADL Software Pty Ltd. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of PADL Software nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY PADL SOFTWARE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL PADL SOFTWARE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "mech_locl.h" GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL gss_set_sec_context_option (OM_uint32 *minor_status, gss_ctx_id_t *context_handle, const gss_OID object, const gss_buffer_t value) { struct _gss_context *ctx; OM_uint32 major_status; gssapi_mech_interface m; *minor_status = 0; if (context_handle == NULL) return GSS_S_NO_CONTEXT; ctx = (struct _gss_context *) *context_handle; if (ctx == NULL) return GSS_S_NO_CONTEXT; m = ctx->gc_mech; if (m == NULL) return GSS_S_BAD_MECH; if (m->gm_set_sec_context_option != NULL) { major_status = m->gm_set_sec_context_option(minor_status, &ctx->gc_ctx, object, value); if (major_status != GSS_S_COMPLETE) _gss_mg_error(m, major_status, *minor_status); } else major_status = GSS_S_BAD_MECH; return major_status; } heimdal-7.5.0/lib/gssapi/mech/gss_test_oid_set_member.c0000644000175000017500000000343113026237312021256 0ustar niknik/*- * Copyright (c) 2005 Doug Rabson * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * * $FreeBSD: src/lib/libgssapi/gss_test_oid_set_member.c,v 1.1 2005/12/29 14:40:20 dfr Exp $ */ #include "mech_locl.h" GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL gss_test_oid_set_member(OM_uint32 *minor_status, const gss_OID member, const gss_OID_set set, int *present) { size_t i; *present = 0; for (i = 0; i < set->count; i++) if (gss_oid_equal(member, &set->elements[i])) *present = 1; *minor_status = 0; return (GSS_S_COMPLETE); } heimdal-7.5.0/lib/gssapi/mech/gssapi.asn10000644000175000017500000000030712136107747016304 0ustar niknik-- $Id$ GSS-API DEFINITIONS ::= BEGIN IMPORTS heim_any_set FROM heim; GSSAPIContextToken ::= [APPLICATION 0] IMPLICIT SEQUENCE { thisMech OBJECT IDENTIFIER, innerContextToken heim_any_set } ENDheimdal-7.5.0/lib/gssapi/mech/gss_get_name_attribute.c0000644000175000017500000000604413026237312021107 0ustar niknik/* * Copyright (c) 2010, PADL Software Pty Ltd. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of PADL Software nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY PADL SOFTWARE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL PADL SOFTWARE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "mech_locl.h" GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL gss_get_name_attribute(OM_uint32 *minor_status, gss_name_t input_name, gss_buffer_t attr, int *authenticated, int *complete, gss_buffer_t value, gss_buffer_t display_value, int *more) { OM_uint32 major_status = GSS_S_UNAVAILABLE; struct _gss_name *name = (struct _gss_name *) input_name; struct _gss_mechanism_name *mn; *minor_status = 0; if (authenticated != NULL) *authenticated = 0; if (complete != NULL) *complete = 0; _mg_buffer_zero(value); _mg_buffer_zero(display_value); if (input_name == GSS_C_NO_NAME) return GSS_S_BAD_NAME; HEIM_SLIST_FOREACH(mn, &name->gn_mn, gmn_link) { gssapi_mech_interface m = mn->gmn_mech; if (!m->gm_get_name_attribute) continue; major_status = m->gm_get_name_attribute(minor_status, mn->gmn_name, attr, authenticated, complete, value, display_value, more); if (GSS_ERROR(major_status)) _gss_mg_error(m, major_status, *minor_status); else break; } return major_status; } heimdal-7.5.0/lib/gssapi/mech/gss_delete_name_attribute.c0000644000175000017500000000473513026237312021577 0ustar niknik/* * Copyright (c) 2010, PADL Software Pty Ltd. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of PADL Software nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY PADL SOFTWARE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL PADL SOFTWARE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "mech_locl.h" GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL gss_delete_name_attribute(OM_uint32 *minor_status, gss_name_t input_name, gss_buffer_t attr) { OM_uint32 major_status = GSS_S_UNAVAILABLE; struct _gss_name *name = (struct _gss_name *) input_name; struct _gss_mechanism_name *mn; *minor_status = 0; if (input_name == GSS_C_NO_NAME) return GSS_S_BAD_NAME; HEIM_SLIST_FOREACH(mn, &name->gn_mn, gmn_link) { gssapi_mech_interface m = mn->gmn_mech; if (!m->gm_delete_name_attribute) continue; major_status = m->gm_delete_name_attribute(minor_status, mn->gmn_name, attr); if (GSS_ERROR(major_status)) _gss_mg_error(m, major_status, *minor_status); else break; } return major_status; } heimdal-7.5.0/lib/gssapi/mech/gss_inquire_sec_context_by_oid.c0000644000175000017500000000477313026237312022653 0ustar niknik/* * Copyright (c) 2004, PADL Software Pty Ltd. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of PADL Software nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY PADL SOFTWARE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL PADL SOFTWARE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "mech_locl.h" GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL gss_inquire_sec_context_by_oid (OM_uint32 *minor_status, gss_const_ctx_id_t context_handle, const gss_OID desired_object, gss_buffer_set_t *data_set) { struct _gss_context *ctx = (struct _gss_context *) context_handle; OM_uint32 major_status; gssapi_mech_interface m; *minor_status = 0; *data_set = GSS_C_NO_BUFFER_SET; if (ctx == NULL) return GSS_S_NO_CONTEXT; /* * select the approprate underlying mechanism routine and * call it. */ m = ctx->gc_mech; if (m == NULL) return GSS_S_BAD_MECH; if (m->gm_inquire_sec_context_by_oid != NULL) { major_status = m->gm_inquire_sec_context_by_oid(minor_status, ctx->gc_ctx, desired_object, data_set); if (major_status != GSS_S_COMPLETE) _gss_mg_error(m, major_status, *minor_status); } else major_status = GSS_S_BAD_MECH; return major_status; } heimdal-7.5.0/lib/gssapi/mech/gss_accept_sec_context.c0000644000175000017500000002040613026237312021100 0ustar niknik/*- * Copyright (c) 2005 Doug Rabson * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * * $FreeBSD: src/lib/libgssapi/gss_accept_sec_context.c,v 1.1 2005/12/29 14:40:20 dfr Exp $ */ #include "mech_locl.h" static OM_uint32 parse_header(const gss_buffer_t input_token, gss_OID mech_oid) { unsigned char *p = input_token->value; size_t len = input_token->length; size_t a, b; /* * Token must start with [APPLICATION 0] SEQUENCE. * But if it doesn't assume it is DCE-STYLE Kerberos! */ if (len == 0) return (GSS_S_DEFECTIVE_TOKEN); p++; len--; /* * Decode the length and make sure it agrees with the * token length. */ if (len == 0) return (GSS_S_DEFECTIVE_TOKEN); if ((*p & 0x80) == 0) { a = *p; p++; len--; } else { b = *p & 0x7f; p++; len--; if (len < b) return (GSS_S_DEFECTIVE_TOKEN); a = 0; while (b) { a = (a << 8) | *p; p++; len--; b--; } } if (a != len) return (GSS_S_DEFECTIVE_TOKEN); /* * Decode the OID for the mechanism. Simplify life by * assuming that the OID length is less than 128 bytes. */ if (len < 2 || *p != 0x06) return (GSS_S_DEFECTIVE_TOKEN); if ((p[1] & 0x80) || p[1] > (len - 2)) return (GSS_S_DEFECTIVE_TOKEN); mech_oid->length = p[1]; p += 2; len -= 2; mech_oid->elements = p; return GSS_S_COMPLETE; } static gss_OID_desc krb5_mechanism = {9, rk_UNCONST("\x2a\x86\x48\x86\xf7\x12\x01\x02\x02")}; static gss_OID_desc ntlm_mechanism = {10, rk_UNCONST("\x2b\x06\x01\x04\x01\x82\x37\x02\x02\x0a")}; static gss_OID_desc spnego_mechanism = {6, rk_UNCONST("\x2b\x06\x01\x05\x05\x02")}; static OM_uint32 choose_mech(const gss_buffer_t input, gss_OID mech_oid) { OM_uint32 status; /* * First try to parse the gssapi token header and see if it's a * correct header, use that in the first hand. */ status = parse_header(input, mech_oid); if (status == GSS_S_COMPLETE) return GSS_S_COMPLETE; /* * Lets guess what mech is really is, callback function to mech ?? */ if (input->length > 8 && memcmp((const char *)input->value, "NTLMSSP\x00", 8) == 0) { *mech_oid = ntlm_mechanism; return GSS_S_COMPLETE; } else if (input->length != 0 && ((const char *)input->value)[0] == 0x6E) { /* Could be a raw AP-REQ (check for APPLICATION tag) */ *mech_oid = krb5_mechanism; return GSS_S_COMPLETE; } else if (input->length == 0) { /* * There is the a wierd mode of SPNEGO (in CIFS and * SASL GSS-SPENGO where the first token is zero * length and the acceptor returns a mech_list, lets * hope that is what is happening now. * * http://msdn.microsoft.com/en-us/library/cc213114.aspx * "NegTokenInit2 Variation for Server-Initiation" */ *mech_oid = spnego_mechanism; return GSS_S_COMPLETE; } return status; } GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL gss_accept_sec_context(OM_uint32 *minor_status, gss_ctx_id_t *context_handle, gss_const_cred_id_t acceptor_cred_handle, const gss_buffer_t input_token, const gss_channel_bindings_t input_chan_bindings, gss_name_t *src_name, gss_OID *mech_type, gss_buffer_t output_token, OM_uint32 *ret_flags, OM_uint32 *time_rec, gss_cred_id_t *delegated_cred_handle) { OM_uint32 major_status, mech_ret_flags, junk; gssapi_mech_interface m; struct _gss_context *ctx = (struct _gss_context *) *context_handle; struct _gss_cred *cred = (struct _gss_cred *) acceptor_cred_handle; struct _gss_mechanism_cred *mc; gss_cred_id_t acceptor_mc, delegated_mc; gss_name_t src_mn; gss_OID mech_ret_type = NULL; *minor_status = 0; if (src_name) *src_name = GSS_C_NO_NAME; if (mech_type) *mech_type = GSS_C_NO_OID; if (ret_flags) *ret_flags = 0; if (time_rec) *time_rec = 0; if (delegated_cred_handle) *delegated_cred_handle = GSS_C_NO_CREDENTIAL; _mg_buffer_zero(output_token); /* * If this is the first call (*context_handle is NULL), we must * parse the input token to figure out the mechanism to use. */ if (*context_handle == GSS_C_NO_CONTEXT) { gss_OID_desc mech_oid; major_status = choose_mech(input_token, &mech_oid); if (major_status != GSS_S_COMPLETE) return major_status; /* * Now that we have a mechanism, we can find the * implementation. */ ctx = malloc(sizeof(struct _gss_context)); if (!ctx) { *minor_status = ENOMEM; return (GSS_S_DEFECTIVE_TOKEN); } memset(ctx, 0, sizeof(struct _gss_context)); m = ctx->gc_mech = __gss_get_mechanism(&mech_oid); if (!m) { free(ctx); return (GSS_S_BAD_MECH); } *context_handle = (gss_ctx_id_t) ctx; } else { m = ctx->gc_mech; } if (cred) { HEIM_SLIST_FOREACH(mc, &cred->gc_mc, gmc_link) if (mc->gmc_mech == m) break; if (!mc) { gss_delete_sec_context(&junk, context_handle, NULL); return (GSS_S_BAD_MECH); } acceptor_mc = mc->gmc_cred; } else { acceptor_mc = GSS_C_NO_CREDENTIAL; } delegated_mc = GSS_C_NO_CREDENTIAL; mech_ret_flags = 0; major_status = m->gm_accept_sec_context(minor_status, &ctx->gc_ctx, acceptor_mc, input_token, input_chan_bindings, &src_mn, &mech_ret_type, output_token, &mech_ret_flags, time_rec, &delegated_mc); if (major_status != GSS_S_COMPLETE && major_status != GSS_S_CONTINUE_NEEDED) { _gss_mg_error(m, major_status, *minor_status); gss_delete_sec_context(&junk, context_handle, NULL); return (major_status); } if (mech_type) *mech_type = mech_ret_type; if (src_name && src_mn) { /* * Make a new name and mark it as an MN. */ struct _gss_name *name = _gss_make_name(m, src_mn); if (!name) { m->gm_release_name(minor_status, &src_mn); gss_delete_sec_context(&junk, context_handle, NULL); return (GSS_S_FAILURE); } *src_name = (gss_name_t) name; } else if (src_mn) { m->gm_release_name(minor_status, &src_mn); } if (mech_ret_flags & GSS_C_DELEG_FLAG) { if (!delegated_cred_handle) { m->gm_release_cred(minor_status, &delegated_mc); mech_ret_flags &= ~(GSS_C_DELEG_FLAG|GSS_C_DELEG_POLICY_FLAG); } else if (gss_oid_equal(mech_ret_type, &m->gm_mech_oid) == 0) { /* * If the returned mech_type is not the same * as the mech, assume its pseudo mech type * and the returned type is already a * mech-glue object */ *delegated_cred_handle = delegated_mc; } else if (delegated_mc) { struct _gss_cred *dcred; struct _gss_mechanism_cred *dmc; dcred = malloc(sizeof(struct _gss_cred)); if (!dcred) { *minor_status = ENOMEM; gss_delete_sec_context(&junk, context_handle, NULL); return (GSS_S_FAILURE); } HEIM_SLIST_INIT(&dcred->gc_mc); dmc = malloc(sizeof(struct _gss_mechanism_cred)); if (!dmc) { free(dcred); *minor_status = ENOMEM; gss_delete_sec_context(&junk, context_handle, NULL); return (GSS_S_FAILURE); } dmc->gmc_mech = m; dmc->gmc_mech_oid = &m->gm_mech_oid; dmc->gmc_cred = delegated_mc; HEIM_SLIST_INSERT_HEAD(&dcred->gc_mc, dmc, gmc_link); *delegated_cred_handle = (gss_cred_id_t) dcred; } } if (ret_flags) *ret_flags = mech_ret_flags; return (major_status); } heimdal-7.5.0/lib/gssapi/mech/context.c0000644000175000017500000000723713026237312016062 0ustar niknik#include "mech_locl.h" #include "heim_threads.h" struct mg_thread_ctx { gss_OID mech; OM_uint32 maj_stat; OM_uint32 min_stat; gss_buffer_desc maj_error; gss_buffer_desc min_error; }; static HEIMDAL_MUTEX context_mutex = HEIMDAL_MUTEX_INITIALIZER; static int created_key; static HEIMDAL_thread_key context_key; static void destroy_context(void *ptr) { struct mg_thread_ctx *mg = ptr; OM_uint32 junk; if (mg == NULL) return; gss_release_buffer(&junk, &mg->maj_error); gss_release_buffer(&junk, &mg->min_error); free(mg); } static struct mg_thread_ctx * _gss_mechglue_thread(void) { struct mg_thread_ctx *ctx; int ret = 0; HEIMDAL_MUTEX_lock(&context_mutex); if (!created_key) { HEIMDAL_key_create(&context_key, destroy_context, ret); if (ret) { HEIMDAL_MUTEX_unlock(&context_mutex); return NULL; } created_key = 1; } HEIMDAL_MUTEX_unlock(&context_mutex); ctx = HEIMDAL_getspecific(context_key); if (ctx == NULL) { ctx = calloc(1, sizeof(*ctx)); if (ctx == NULL) return NULL; HEIMDAL_setspecific(context_key, ctx, ret); if (ret) { free(ctx); return NULL; } } return ctx; } OM_uint32 _gss_mg_get_error(const gss_OID mech, OM_uint32 type, OM_uint32 value, gss_buffer_t string) { struct mg_thread_ctx *mg; mg = _gss_mechglue_thread(); if (mg == NULL) return GSS_S_BAD_STATUS; #if 0 /* * We cant check the mech here since a pseudo-mech might have * called an lower layer and then the mech info is all broken */ if (mech != NULL && gss_oid_equal(mg->mech, mech) == 0) return GSS_S_BAD_STATUS; #endif switch (type) { case GSS_C_GSS_CODE: { if (value != mg->maj_stat || mg->maj_error.length == 0) break; string->value = malloc(mg->maj_error.length + 1); string->length = mg->maj_error.length; memcpy(string->value, mg->maj_error.value, mg->maj_error.length); ((char *) string->value)[string->length] = '\0'; return GSS_S_COMPLETE; } case GSS_C_MECH_CODE: { if (value != mg->min_stat || mg->min_error.length == 0) break; string->value = malloc(mg->min_error.length + 1); string->length = mg->min_error.length; memcpy(string->value, mg->min_error.value, mg->min_error.length); ((char *) string->value)[string->length] = '\0'; return GSS_S_COMPLETE; } } string->value = NULL; string->length = 0; return GSS_S_BAD_STATUS; } void _gss_mg_error(gssapi_mech_interface m, OM_uint32 maj, OM_uint32 min) { OM_uint32 major_status, minor_status; OM_uint32 message_content; struct mg_thread_ctx *mg; /* * Mechs without gss_display_status() does * gss_mg_collect_error() by themself. */ if (m->gm_display_status == NULL) return ; mg = _gss_mechglue_thread(); if (mg == NULL) return; gss_release_buffer(&minor_status, &mg->maj_error); gss_release_buffer(&minor_status, &mg->min_error); mg->mech = &m->gm_mech_oid; mg->maj_stat = maj; mg->min_stat = min; major_status = m->gm_display_status(&minor_status, maj, GSS_C_GSS_CODE, &m->gm_mech_oid, &message_content, &mg->maj_error); if (GSS_ERROR(major_status)) { mg->maj_error.value = NULL; mg->maj_error.length = 0; } major_status = m->gm_display_status(&minor_status, min, GSS_C_MECH_CODE, &m->gm_mech_oid, &message_content, &mg->min_error); if (GSS_ERROR(major_status)) { mg->min_error.value = NULL; mg->min_error.length = 0; } } void gss_mg_collect_error(gss_OID mech, OM_uint32 maj, OM_uint32 min) { gssapi_mech_interface m = __gss_get_mechanism(mech); if (m == NULL) return; _gss_mg_error(m, maj, min); } heimdal-7.5.0/lib/gssapi/mech/gss_encapsulate_token.c0000644000175000017500000000462313026237312020752 0ustar niknik/* * Copyright (c) 2006 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "mech_locl.h" GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL gss_encapsulate_token(gss_const_buffer_t input_token, gss_const_OID oid, gss_buffer_t output_token) { GSSAPIContextToken ct; int ret; size_t size; ret = der_get_oid (oid->elements, oid->length, &ct.thisMech, &size); if (ret) { _mg_buffer_zero(output_token); return GSS_S_FAILURE; } ct.innerContextToken.data = input_token->value; ct.innerContextToken.length = input_token->length; ASN1_MALLOC_ENCODE(GSSAPIContextToken, output_token->value, output_token->length, &ct, &size, ret); der_free_oid(&ct.thisMech); if (ret) { _mg_buffer_zero(output_token); return GSS_S_FAILURE; } if (output_token->length != size) abort(); return GSS_S_COMPLETE; } heimdal-7.5.0/lib/gssapi/mech/gss_krb5.c0000644000175000017500000005264213026237312016115 0ustar niknik/*- * Copyright (c) 2005 Doug Rabson * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * * $FreeBSD: src/lib/libgssapi/gss_krb5.c,v 1.1 2005/12/29 14:40:20 dfr Exp $ */ #include "mech_locl.h" #include #include GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL gss_krb5_copy_ccache(OM_uint32 *minor_status, gss_cred_id_t cred, krb5_ccache out) { gss_buffer_set_t data_set = GSS_C_NO_BUFFER_SET; krb5_context context; krb5_error_code kret; krb5_ccache id; OM_uint32 ret; char *str = NULL; ret = gss_inquire_cred_by_oid(minor_status, cred, GSS_KRB5_COPY_CCACHE_X, &data_set); if (ret) return ret; if (data_set == GSS_C_NO_BUFFER_SET || data_set->count < 1) { gss_release_buffer_set(minor_status, &data_set); *minor_status = EINVAL; return GSS_S_FAILURE; } kret = krb5_init_context(&context); if (kret) { *minor_status = kret; gss_release_buffer_set(minor_status, &data_set); return GSS_S_FAILURE; } kret = asprintf(&str, "%.*s", (int)data_set->elements[0].length, (char *)data_set->elements[0].value); gss_release_buffer_set(minor_status, &data_set); if (kret < 0 || str == NULL) { *minor_status = ENOMEM; return GSS_S_FAILURE; } kret = krb5_cc_resolve(context, str, &id); free(str); if (kret) { *minor_status = kret; return GSS_S_FAILURE; } kret = krb5_cc_copy_cache(context, id, out); krb5_cc_close(context, id); krb5_free_context(context); if (kret) { *minor_status = kret; return GSS_S_FAILURE; } return ret; } GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL gss_krb5_import_cred(OM_uint32 *minor_status, krb5_ccache id, krb5_principal keytab_principal, krb5_keytab keytab, gss_cred_id_t *cred) { gss_buffer_desc buffer; OM_uint32 major_status; krb5_context context; krb5_error_code ret; krb5_storage *sp; krb5_data data; char *str; *cred = GSS_C_NO_CREDENTIAL; ret = krb5_init_context(&context); if (ret) { *minor_status = ret; return GSS_S_FAILURE; } sp = krb5_storage_emem(); if (sp == NULL) { *minor_status = ENOMEM; major_status = GSS_S_FAILURE; goto out; } if (id) { ret = krb5_cc_get_full_name(context, id, &str); if (ret == 0) { ret = krb5_store_string(sp, str); free(str); } } else ret = krb5_store_string(sp, ""); if (ret) { *minor_status = ret; major_status = GSS_S_FAILURE; goto out; } if (keytab_principal) { ret = krb5_unparse_name(context, keytab_principal, &str); if (ret == 0) { ret = krb5_store_string(sp, str); free(str); } } else krb5_store_string(sp, ""); if (ret) { *minor_status = ret; major_status = GSS_S_FAILURE; goto out; } if (keytab) { ret = krb5_kt_get_full_name(context, keytab, &str); if (ret == 0) { ret = krb5_store_string(sp, str); free(str); } } else krb5_store_string(sp, ""); if (ret) { *minor_status = ret; major_status = GSS_S_FAILURE; goto out; } ret = krb5_storage_to_data(sp, &data); if (ret) { *minor_status = ret; major_status = GSS_S_FAILURE; goto out; } buffer.value = data.data; buffer.length = data.length; major_status = gss_set_cred_option(minor_status, cred, GSS_KRB5_IMPORT_CRED_X, &buffer); krb5_data_free(&data); out: if (sp) krb5_storage_free(sp); krb5_free_context(context); return major_status; } GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL gsskrb5_register_acceptor_identity(const char *identity) { gssapi_mech_interface m; gss_buffer_desc buffer; OM_uint32 junk; _gss_load_mech(); buffer.value = rk_UNCONST(identity); buffer.length = strlen(identity); m = __gss_get_mechanism(GSS_KRB5_MECHANISM); if (m == NULL || m->gm_set_sec_context_option == NULL) return GSS_S_FAILURE; return m->gm_set_sec_context_option(&junk, NULL, GSS_KRB5_REGISTER_ACCEPTOR_IDENTITY_X, &buffer); } GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL krb5_gss_register_acceptor_identity(const char *identity) { return gsskrb5_register_acceptor_identity(identity); } GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL gsskrb5_set_dns_canonicalize(int flag) { struct _gss_mech_switch *m; gss_buffer_desc buffer; OM_uint32 junk; char b = (flag != 0); _gss_load_mech(); buffer.value = &b; buffer.length = sizeof(b); HEIM_SLIST_FOREACH(m, &_gss_mechs, gm_link) { if (m->gm_mech.gm_set_sec_context_option == NULL) continue; m->gm_mech.gm_set_sec_context_option(&junk, NULL, GSS_KRB5_SET_DNS_CANONICALIZE_X, &buffer); } return (GSS_S_COMPLETE); } static krb5_error_code set_key(krb5_keyblock *keyblock, gss_krb5_lucid_key_t *key) { key->type = keyblock->keytype; key->length = keyblock->keyvalue.length; key->data = malloc(key->length); if (key->data == NULL && key->length != 0) return ENOMEM; memcpy(key->data, keyblock->keyvalue.data, key->length); return 0; } static void free_key(gss_krb5_lucid_key_t *key) { memset(key->data, 0, key->length); free(key->data); memset(key, 0, sizeof(*key)); } GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL gss_krb5_export_lucid_sec_context(OM_uint32 *minor_status, gss_ctx_id_t *context_handle, OM_uint32 version, void **rctx) { krb5_context context = NULL; krb5_error_code ret; gss_buffer_set_t data_set = GSS_C_NO_BUFFER_SET; OM_uint32 major_status; gss_krb5_lucid_context_v1_t *ctx = NULL; krb5_storage *sp = NULL; uint32_t num; if (context_handle == NULL || *context_handle == GSS_C_NO_CONTEXT || version != 1) { *minor_status = EINVAL; return GSS_S_FAILURE; } major_status = gss_inquire_sec_context_by_oid (minor_status, *context_handle, GSS_KRB5_EXPORT_LUCID_CONTEXT_V1_X, &data_set); if (major_status) return major_status; if (data_set == GSS_C_NO_BUFFER_SET || data_set->count != 1) { gss_release_buffer_set(minor_status, &data_set); *minor_status = EINVAL; return GSS_S_FAILURE; } ret = krb5_init_context(&context); if (ret) goto out; ctx = calloc(1, sizeof(*ctx)); if (ctx == NULL) { ret = ENOMEM; goto out; } sp = krb5_storage_from_mem(data_set->elements[0].value, data_set->elements[0].length); if (sp == NULL) { ret = ENOMEM; goto out; } ret = krb5_ret_uint32(sp, &num); if (ret) goto out; if (num != 1) { ret = EINVAL; goto out; } ctx->version = 1; /* initiator */ ret = krb5_ret_uint32(sp, &ctx->initiate); if (ret) goto out; /* endtime */ ret = krb5_ret_uint32(sp, &ctx->endtime); if (ret) goto out; /* send_seq */ ret = krb5_ret_uint32(sp, &num); if (ret) goto out; ctx->send_seq = ((uint64_t)num) << 32; ret = krb5_ret_uint32(sp, &num); if (ret) goto out; ctx->send_seq |= num; /* recv_seq */ ret = krb5_ret_uint32(sp, &num); if (ret) goto out; ctx->recv_seq = ((uint64_t)num) << 32; ret = krb5_ret_uint32(sp, &num); if (ret) goto out; ctx->recv_seq |= num; /* protocol */ ret = krb5_ret_uint32(sp, &ctx->protocol); if (ret) goto out; if (ctx->protocol == 0) { krb5_keyblock key; /* sign_alg */ ret = krb5_ret_uint32(sp, &ctx->rfc1964_kd.sign_alg); if (ret) goto out; /* seal_alg */ ret = krb5_ret_uint32(sp, &ctx->rfc1964_kd.seal_alg); if (ret) goto out; /* ctx_key */ ret = krb5_ret_keyblock(sp, &key); if (ret) goto out; ret = set_key(&key, &ctx->rfc1964_kd.ctx_key); krb5_free_keyblock_contents(context, &key); if (ret) goto out; } else if (ctx->protocol == 1) { krb5_keyblock key; /* acceptor_subkey */ ret = krb5_ret_uint32(sp, &ctx->cfx_kd.have_acceptor_subkey); if (ret) goto out; /* ctx_key */ ret = krb5_ret_keyblock(sp, &key); if (ret) goto out; ret = set_key(&key, &ctx->cfx_kd.ctx_key); krb5_free_keyblock_contents(context, &key); if (ret) goto out; /* acceptor_subkey */ if (ctx->cfx_kd.have_acceptor_subkey) { ret = krb5_ret_keyblock(sp, &key); if (ret) goto out; ret = set_key(&key, &ctx->cfx_kd.acceptor_subkey); krb5_free_keyblock_contents(context, &key); if (ret) goto out; } } else { ret = EINVAL; goto out; } *rctx = ctx; out: gss_release_buffer_set(minor_status, &data_set); if (sp) krb5_storage_free(sp); if (context) krb5_free_context(context); if (ret) { if (ctx) gss_krb5_free_lucid_sec_context(NULL, ctx); *minor_status = ret; return GSS_S_FAILURE; } *minor_status = 0; return GSS_S_COMPLETE; } GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL gss_krb5_free_lucid_sec_context(OM_uint32 *minor_status, void *c) { gss_krb5_lucid_context_v1_t *ctx = c; if (ctx->version != 1) { if (minor_status) *minor_status = 0; return GSS_S_FAILURE; } if (ctx->protocol == 0) { free_key(&ctx->rfc1964_kd.ctx_key); } else if (ctx->protocol == 1) { free_key(&ctx->cfx_kd.ctx_key); if (ctx->cfx_kd.have_acceptor_subkey) free_key(&ctx->cfx_kd.acceptor_subkey); } free(ctx); if (minor_status) *minor_status = 0; return GSS_S_COMPLETE; } /* * */ GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL gss_krb5_set_allowable_enctypes(OM_uint32 *minor_status, gss_cred_id_t cred, OM_uint32 num_enctypes, int32_t *enctypes) { krb5_error_code ret; OM_uint32 maj_status; gss_buffer_desc buffer; krb5_storage *sp; krb5_data data; size_t i; sp = krb5_storage_emem(); if (sp == NULL) { *minor_status = ENOMEM; maj_status = GSS_S_FAILURE; goto out; } for (i = 0; i < num_enctypes; i++) { ret = krb5_store_int32(sp, enctypes[i]); if (ret) { *minor_status = ret; maj_status = GSS_S_FAILURE; goto out; } } ret = krb5_storage_to_data(sp, &data); if (ret) { *minor_status = ret; maj_status = GSS_S_FAILURE; goto out; } buffer.value = data.data; buffer.length = data.length; maj_status = gss_set_cred_option(minor_status, &cred, GSS_KRB5_SET_ALLOWABLE_ENCTYPES_X, &buffer); krb5_data_free(&data); out: if (sp) krb5_storage_free(sp); return maj_status; } /* * */ GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL gsskrb5_set_send_to_kdc(struct gsskrb5_send_to_kdc *c) { struct _gss_mech_switch *m; gss_buffer_desc buffer; OM_uint32 junk; _gss_load_mech(); if (c) { buffer.value = c; buffer.length = sizeof(*c); } else { buffer.value = NULL; buffer.length = 0; } HEIM_SLIST_FOREACH(m, &_gss_mechs, gm_link) { if (m->gm_mech.gm_set_sec_context_option == NULL) continue; m->gm_mech.gm_set_sec_context_option(&junk, NULL, GSS_KRB5_SEND_TO_KDC_X, &buffer); } return (GSS_S_COMPLETE); } /* * */ GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL gss_krb5_ccache_name(OM_uint32 *minor_status, const char *name, const char **out_name) { struct _gss_mech_switch *m; gss_buffer_desc buffer; OM_uint32 junk; _gss_load_mech(); if (out_name) *out_name = NULL; buffer.value = rk_UNCONST(name); buffer.length = strlen(name); HEIM_SLIST_FOREACH(m, &_gss_mechs, gm_link) { if (m->gm_mech.gm_set_sec_context_option == NULL) continue; m->gm_mech.gm_set_sec_context_option(&junk, NULL, GSS_KRB5_CCACHE_NAME_X, &buffer); } return (GSS_S_COMPLETE); } /* * */ GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL gsskrb5_extract_authtime_from_sec_context(OM_uint32 *minor_status, gss_ctx_id_t context_handle, time_t *authtime) { gss_buffer_set_t data_set = GSS_C_NO_BUFFER_SET; OM_uint32 maj_stat; if (context_handle == GSS_C_NO_CONTEXT) { *minor_status = EINVAL; return GSS_S_FAILURE; } maj_stat = gss_inquire_sec_context_by_oid (minor_status, context_handle, GSS_KRB5_GET_AUTHTIME_X, &data_set); if (maj_stat) return maj_stat; if (data_set == GSS_C_NO_BUFFER_SET) { gss_release_buffer_set(minor_status, &data_set); *minor_status = EINVAL; return GSS_S_FAILURE; } if (data_set->count != 1) { gss_release_buffer_set(minor_status, &data_set); *minor_status = EINVAL; return GSS_S_FAILURE; } if (data_set->elements[0].length != 4) { gss_release_buffer_set(minor_status, &data_set); *minor_status = EINVAL; return GSS_S_FAILURE; } { unsigned char *buf = data_set->elements[0].value; *authtime = (buf[3] <<24) | (buf[2] << 16) | (buf[1] << 8) | (buf[0] << 0); } gss_release_buffer_set(minor_status, &data_set); *minor_status = 0; return GSS_S_COMPLETE; } /* * */ GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL gsskrb5_extract_authz_data_from_sec_context(OM_uint32 *minor_status, gss_ctx_id_t context_handle, int ad_type, gss_buffer_t ad_data) { gss_buffer_set_t data_set = GSS_C_NO_BUFFER_SET; OM_uint32 maj_stat; gss_OID_desc oid_flat; heim_oid baseoid, oid; size_t size; if (context_handle == GSS_C_NO_CONTEXT) { *minor_status = EINVAL; return GSS_S_FAILURE; } /* All this to append an integer to an oid... */ if (der_get_oid(GSS_KRB5_EXTRACT_AUTHZ_DATA_FROM_SEC_CONTEXT_X->elements, GSS_KRB5_EXTRACT_AUTHZ_DATA_FROM_SEC_CONTEXT_X->length, &baseoid, NULL) != 0) { *minor_status = EINVAL; return GSS_S_FAILURE; } oid.length = baseoid.length + 1; oid.components = calloc(oid.length, sizeof(*oid.components)); if (oid.components == NULL) { der_free_oid(&baseoid); *minor_status = ENOMEM; return GSS_S_FAILURE; } memcpy(oid.components, baseoid.components, baseoid.length * sizeof(*baseoid.components)); der_free_oid(&baseoid); oid.components[oid.length - 1] = ad_type; oid_flat.length = der_length_oid(&oid); oid_flat.elements = malloc(oid_flat.length); if (oid_flat.elements == NULL) { free(oid.components); *minor_status = ENOMEM; return GSS_S_FAILURE; } if (der_put_oid((unsigned char *)oid_flat.elements + oid_flat.length - 1, oid_flat.length, &oid, &size) != 0) { free(oid.components); free(oid_flat.elements); *minor_status = EINVAL; return GSS_S_FAILURE; } if (oid_flat.length != size) abort(); free(oid.components); /* FINALLY, we have the OID */ maj_stat = gss_inquire_sec_context_by_oid (minor_status, context_handle, &oid_flat, &data_set); free(oid_flat.elements); if (maj_stat) return maj_stat; if (data_set == GSS_C_NO_BUFFER_SET || data_set->count != 1) { gss_release_buffer_set(minor_status, &data_set); *minor_status = EINVAL; return GSS_S_FAILURE; } ad_data->value = malloc(data_set->elements[0].length); if (ad_data->value == NULL) { gss_release_buffer_set(minor_status, &data_set); *minor_status = ENOMEM; return GSS_S_FAILURE; } ad_data->length = data_set->elements[0].length; memcpy(ad_data->value, data_set->elements[0].value, ad_data->length); gss_release_buffer_set(minor_status, &data_set); *minor_status = 0; return GSS_S_COMPLETE; } /* * */ static OM_uint32 gsskrb5_extract_key(OM_uint32 *minor_status, gss_ctx_id_t context_handle, const gss_OID oid, krb5_keyblock **keyblock) { krb5_error_code ret; gss_buffer_set_t data_set = GSS_C_NO_BUFFER_SET; OM_uint32 major_status; krb5_context context = NULL; krb5_storage *sp = NULL; if (context_handle == GSS_C_NO_CONTEXT) { *minor_status = EINVAL; return GSS_S_FAILURE; } ret = krb5_init_context(&context); if(ret) { *minor_status = ret; return GSS_S_FAILURE; } major_status = gss_inquire_sec_context_by_oid (minor_status, context_handle, oid, &data_set); if (major_status) return major_status; if (data_set == GSS_C_NO_BUFFER_SET || data_set->count != 1) { gss_release_buffer_set(minor_status, &data_set); *minor_status = EINVAL; return GSS_S_FAILURE; } sp = krb5_storage_from_mem(data_set->elements[0].value, data_set->elements[0].length); if (sp == NULL) { ret = ENOMEM; goto out; } *keyblock = calloc(1, sizeof(**keyblock)); if (keyblock == NULL) { ret = ENOMEM; goto out; } ret = krb5_ret_keyblock(sp, *keyblock); out: gss_release_buffer_set(minor_status, &data_set); if (sp) krb5_storage_free(sp); if (ret && keyblock) { krb5_free_keyblock(context, *keyblock); *keyblock = NULL; } if (context) krb5_free_context(context); *minor_status = ret; if (ret) return GSS_S_FAILURE; return GSS_S_COMPLETE; } /* * */ GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL gsskrb5_extract_service_keyblock(OM_uint32 *minor_status, gss_ctx_id_t context_handle, krb5_keyblock **keyblock) { return gsskrb5_extract_key(minor_status, context_handle, GSS_KRB5_GET_SERVICE_KEYBLOCK_X, keyblock); } GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL gsskrb5_get_initiator_subkey(OM_uint32 *minor_status, gss_ctx_id_t context_handle, krb5_keyblock **keyblock) { return gsskrb5_extract_key(minor_status, context_handle, GSS_KRB5_GET_INITIATOR_SUBKEY_X, keyblock); } GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL gsskrb5_get_subkey(OM_uint32 *minor_status, gss_ctx_id_t context_handle, krb5_keyblock **keyblock) { return gsskrb5_extract_key(minor_status, context_handle, GSS_KRB5_GET_SUBKEY_X, keyblock); } GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL gsskrb5_set_default_realm(const char *realm) { struct _gss_mech_switch *m; gss_buffer_desc buffer; OM_uint32 junk; _gss_load_mech(); buffer.value = rk_UNCONST(realm); buffer.length = strlen(realm); HEIM_SLIST_FOREACH(m, &_gss_mechs, gm_link) { if (m->gm_mech.gm_set_sec_context_option == NULL) continue; m->gm_mech.gm_set_sec_context_option(&junk, NULL, GSS_KRB5_SET_DEFAULT_REALM_X, &buffer); } return (GSS_S_COMPLETE); } GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL gss_krb5_get_tkt_flags(OM_uint32 *minor_status, gss_ctx_id_t context_handle, OM_uint32 *tkt_flags) { OM_uint32 major_status; gss_buffer_set_t data_set = GSS_C_NO_BUFFER_SET; if (context_handle == GSS_C_NO_CONTEXT) { *minor_status = EINVAL; return GSS_S_FAILURE; } major_status = gss_inquire_sec_context_by_oid (minor_status, context_handle, GSS_KRB5_GET_TKT_FLAGS_X, &data_set); if (major_status) return major_status; if (data_set == GSS_C_NO_BUFFER_SET || data_set->count != 1 || data_set->elements[0].length < 4) { gss_release_buffer_set(minor_status, &data_set); *minor_status = EINVAL; return GSS_S_FAILURE; } { const u_char *p = data_set->elements[0].value; *tkt_flags = (p[0] << 0) | (p[1] << 8) | (p[2] << 16) | (p[3] << 24); } gss_release_buffer_set(minor_status, &data_set); return GSS_S_COMPLETE; } GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL gsskrb5_set_time_offset(int offset) { struct _gss_mech_switch *m; gss_buffer_desc buffer; OM_uint32 junk; int32_t o = offset; _gss_load_mech(); buffer.value = &o; buffer.length = sizeof(o); HEIM_SLIST_FOREACH(m, &_gss_mechs, gm_link) { if (m->gm_mech.gm_set_sec_context_option == NULL) continue; m->gm_mech.gm_set_sec_context_option(&junk, NULL, GSS_KRB5_SET_TIME_OFFSET_X, &buffer); } return (GSS_S_COMPLETE); } GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL gsskrb5_get_time_offset(int *offset) { struct _gss_mech_switch *m; gss_buffer_desc buffer; OM_uint32 maj_stat, junk; int32_t o; _gss_load_mech(); buffer.value = &o; buffer.length = sizeof(o); HEIM_SLIST_FOREACH(m, &_gss_mechs, gm_link) { if (m->gm_mech.gm_set_sec_context_option == NULL) continue; maj_stat = m->gm_mech.gm_set_sec_context_option(&junk, NULL, GSS_KRB5_GET_TIME_OFFSET_X, &buffer); if (maj_stat == GSS_S_COMPLETE) { *offset = o; return maj_stat; } } return (GSS_S_UNAVAILABLE); } GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL gsskrb5_plugin_register(struct gsskrb5_krb5_plugin *c) { struct _gss_mech_switch *m; gss_buffer_desc buffer; OM_uint32 junk; _gss_load_mech(); buffer.value = c; buffer.length = sizeof(*c); HEIM_SLIST_FOREACH(m, &_gss_mechs, gm_link) { if (m->gm_mech.gm_set_sec_context_option == NULL) continue; m->gm_mech.gm_set_sec_context_option(&junk, NULL, GSS_KRB5_PLUGIN_REGISTER_X, &buffer); } return (GSS_S_COMPLETE); } heimdal-7.5.0/lib/gssapi/mech/gss_compare_name.c0000644000175000017500000000527113026237312017674 0ustar niknik/*- * Copyright (c) 2005 Doug Rabson * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * * $FreeBSD: src/lib/libgssapi/gss_compare_name.c,v 1.1 2005/12/29 14:40:20 dfr Exp $ */ #include "mech_locl.h" GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL gss_compare_name(OM_uint32 *minor_status, gss_const_name_t name1_arg, gss_const_name_t name2_arg, int *name_equal) { struct _gss_name *name1 = (struct _gss_name *) name1_arg; struct _gss_name *name2 = (struct _gss_name *) name2_arg; /* * First check the implementation-independant name if both * names have one. Otherwise, try to find common mechanism * names and compare them. */ if (name1->gn_value.value && name2->gn_value.value) { *name_equal = 1; if (!gss_oid_equal(&name1->gn_type, &name2->gn_type)) { *name_equal = 0; } else if (name1->gn_value.length != name2->gn_value.length || memcmp(name1->gn_value.value, name2->gn_value.value, name1->gn_value.length)) { *name_equal = 0; } } else { struct _gss_mechanism_name *mn1; struct _gss_mechanism_name *mn2; HEIM_SLIST_FOREACH(mn1, &name1->gn_mn, gmn_link) { OM_uint32 major_status; major_status = _gss_find_mn(minor_status, name2, mn1->gmn_mech_oid, &mn2); if (major_status == GSS_S_COMPLETE) { return (mn1->gmn_mech->gm_compare_name( minor_status, mn1->gmn_name, mn2->gmn_name, name_equal)); } } *name_equal = 0; } *minor_status = 0; return (GSS_S_COMPLETE); } heimdal-7.5.0/lib/gssapi/mech/gss_context_time.c0000644000175000017500000000341013026237312017741 0ustar niknik/*- * Copyright (c) 2005 Doug Rabson * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * * $FreeBSD: src/lib/libgssapi/gss_context_time.c,v 1.1 2005/12/29 14:40:20 dfr Exp $ */ #include "mech_locl.h" GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL gss_context_time(OM_uint32 *minor_status, gss_const_ctx_id_t context_handle, OM_uint32 *time_rec) { struct _gss_context *ctx = (struct _gss_context *) context_handle; gssapi_mech_interface m = ctx->gc_mech; return (m->gm_context_time(minor_status, ctx->gc_ctx, time_rec)); } heimdal-7.5.0/lib/gssapi/mech/mechqueue.h0000644000175000017500000000664213026237312016363 0ustar niknik/* $NetBSD: queue.h,v 1.39 2004/04/18 14:25:34 lukem Exp $ */ /* * Copyright (c) 1991, 1993 * The Regents of the University of California. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the University nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * * @(#)queue.h 8.5 (Berkeley) 8/20/94 */ #ifndef _MECHQUEUE_H_ #define _MECHQUEUE_H_ /* * Singly-linked List definitions. */ #define HEIM_SLIST_HEAD(name, type) \ struct name { \ struct type *slh_first; /* first element */ \ } #define HEIM_SLIST_HEAD_INITIALIZER(head) \ { NULL } #define HEIM_SLIST_ENTRY(type) \ struct { \ struct type *sle_next; /* next element */ \ } /* * Singly-linked List functions. */ #define HEIM_SLIST_INIT(head) do { \ (head)->slh_first = NULL; \ } while (/*CONSTCOND*/0) #define HEIM_SLIST_INSERT_AFTER(slistelm, elm, field) do { \ (elm)->field.sle_next = (slistelm)->field.sle_next; \ (slistelm)->field.sle_next = (elm); \ } while (/*CONSTCOND*/0) #define HEIM_SLIST_INSERT_HEAD(head, elm, field) do { \ (elm)->field.sle_next = (head)->slh_first; \ (head)->slh_first = (elm); \ } while (/*CONSTCOND*/0) #define HEIM_SLIST_REMOVE_HEAD(head, field) do { \ (head)->slh_first = (head)->slh_first->field.sle_next; \ } while (/*CONSTCOND*/0) #define HEIM_SLIST_REMOVE(head, elm, type, field) do { \ if ((head)->slh_first == (elm)) { \ HEIM_SLIST_REMOVE_HEAD((head), field); \ } \ else { \ struct type *curelm = (head)->slh_first; \ while(curelm->field.sle_next != (elm)) \ curelm = curelm->field.sle_next; \ curelm->field.sle_next = \ curelm->field.sle_next->field.sle_next; \ } \ } while (/*CONSTCOND*/0) #define HEIM_SLIST_FOREACH(var, head, field) \ for((var) = (head)->slh_first; (var); (var) = (var)->field.sle_next) /* * Singly-linked List access methods. */ #define HEIM_SLIST_EMPTY(head) ((head)->slh_first == NULL) #define HEIM_SLIST_FIRST(head) ((head)->slh_first) #define HEIM_SLIST_NEXT(elm, field) ((elm)->field.sle_next) #endif /* !_MECHQUEUE_H_ */ heimdal-7.5.0/lib/gssapi/mech/gss_get_mic.c0000644000175000017500000000372613026237312016660 0ustar niknik/*- * Copyright (c) 2005 Doug Rabson * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * * $FreeBSD: src/lib/libgssapi/gss_get_mic.c,v 1.1 2005/12/29 14:40:20 dfr Exp $ */ #include "mech_locl.h" GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL gss_get_mic(OM_uint32 *minor_status, gss_const_ctx_id_t context_handle, gss_qop_t qop_req, const gss_buffer_t message_buffer, gss_buffer_t message_token) { struct _gss_context *ctx = (struct _gss_context *) context_handle; gssapi_mech_interface m; _mg_buffer_zero(message_token); if (ctx == NULL) { *minor_status = 0; return GSS_S_NO_CONTEXT; } m = ctx->gc_mech; return (m->gm_get_mic(minor_status, ctx->gc_ctx, qop_req, message_buffer, message_token)); } heimdal-7.5.0/lib/gssapi/mech/gss_export_name_composite.c0000644000175000017500000000504213026237312021645 0ustar niknik/* * Copyright (c) 2010, PADL Software Pty Ltd. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of PADL Software nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY PADL SOFTWARE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL PADL SOFTWARE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "mech_locl.h" GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL gss_export_name_composite(OM_uint32 *minor_status, gss_name_t input_name, gss_buffer_t exp_composite_name) { OM_uint32 major_status = GSS_S_UNAVAILABLE; struct _gss_name *name = (struct _gss_name *) input_name; struct _gss_mechanism_name *mn; *minor_status = 0; _mg_buffer_zero(exp_composite_name); if (input_name == GSS_C_NO_NAME) return GSS_S_BAD_NAME; HEIM_SLIST_FOREACH(mn, &name->gn_mn, gmn_link) { gssapi_mech_interface m = mn->gmn_mech; if (!m->gm_export_name_composite) continue; major_status = m->gm_export_name_composite(minor_status, mn->gmn_name, exp_composite_name); if (GSS_ERROR(major_status)) _gss_mg_error(m, major_status, *minor_status); else break; } return major_status; } heimdal-7.5.0/lib/gssapi/mech/gss_sign.c0000644000175000017500000000333312136107747016214 0ustar niknik/*- * Copyright (c) 2005 Doug Rabson * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * * $FreeBSD: src/lib/libgssapi/gss_sign.c,v 1.1 2005/12/29 14:40:20 dfr Exp $ */ #include "mech_locl.h" GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL gss_sign(OM_uint32 *minor_status, gss_ctx_id_t context_handle, int qop_req, gss_buffer_t message_buffer, gss_buffer_t message_token) { return gss_get_mic(minor_status, context_handle, qop_req, message_buffer, message_token); } heimdal-7.5.0/lib/gssapi/mech/gss_buffer_set.c0000644000175000017500000000675413026237312017401 0ustar niknik/* * Copyright (c) 2004, PADL Software Pty Ltd. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of PADL Software nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY PADL SOFTWARE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL PADL SOFTWARE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "mech_locl.h" GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL gss_create_empty_buffer_set (OM_uint32 * minor_status, gss_buffer_set_t *buffer_set) { gss_buffer_set_t set; set = (gss_buffer_set_desc *) malloc(sizeof(*set)); if (set == GSS_C_NO_BUFFER_SET) { *minor_status = ENOMEM; return GSS_S_FAILURE; } set->count = 0; set->elements = NULL; *buffer_set = set; *minor_status = 0; return GSS_S_COMPLETE; } GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL gss_add_buffer_set_member (OM_uint32 * minor_status, const gss_buffer_t member_buffer, gss_buffer_set_t *buffer_set) { gss_buffer_set_t set; gss_buffer_t p; OM_uint32 ret; if (*buffer_set == GSS_C_NO_BUFFER_SET) { ret = gss_create_empty_buffer_set(minor_status, buffer_set); if (ret) { return ret; } } set = *buffer_set; set->elements = realloc(set->elements, (set->count + 1) * sizeof(set->elements[0])); if (set->elements == NULL) { *minor_status = ENOMEM; return GSS_S_FAILURE; } p = &set->elements[set->count]; p->value = malloc(member_buffer->length); if (p->value == NULL) { *minor_status = ENOMEM; return GSS_S_FAILURE; } memcpy(p->value, member_buffer->value, member_buffer->length); p->length = member_buffer->length; set->count++; *minor_status = 0; return GSS_S_COMPLETE; } GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL gss_release_buffer_set(OM_uint32 * minor_status, gss_buffer_set_t *buffer_set) { size_t i; OM_uint32 minor; *minor_status = 0; if (*buffer_set == GSS_C_NO_BUFFER_SET) return GSS_S_COMPLETE; for (i = 0; i < (*buffer_set)->count; i++) gss_release_buffer(&minor, &((*buffer_set)->elements[i])); free((*buffer_set)->elements); (*buffer_set)->elements = NULL; (*buffer_set)->count = 0; free(*buffer_set); *buffer_set = GSS_C_NO_BUFFER_SET; return GSS_S_COMPLETE; } heimdal-7.5.0/lib/gssapi/mech/compat.h0000644000175000017500000001011413026237312015652 0ustar niknik/* * Copyright (c) 2010, PADL Software Pty Ltd. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of PADL Software nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY PADL SOFTWARE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL PADL SOFTWARE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ typedef OM_uint32 GSSAPI_CALLCONV _gss_inquire_saslname_for_mech_t ( OM_uint32 *, /* minor_status */ const gss_OID, /* desired_mech */ gss_buffer_t, /* sasl_mech_name */ gss_buffer_t, /* mech_name */ gss_buffer_t /* mech_description */ ); typedef OM_uint32 GSSAPI_CALLCONV _gss_inquire_mech_for_saslname_t ( OM_uint32 *, /* minor_status */ const gss_buffer_t, /* sasl_mech_name */ gss_OID * /* mech_type */ ); typedef OM_uint32 GSSAPI_CALLCONV _gss_inquire_attrs_for_mech_t ( OM_uint32 *, /* minor_status */ gss_const_OID, /* mech */ gss_OID_set *, /* mech_attrs */ gss_OID_set * /* known_mech_attrs */ ); typedef OM_uint32 GSSAPI_CALLCONV _gss_acquire_cred_with_password_t (OM_uint32 *, /* minor_status */ gss_const_name_t, /* desired_name */ const gss_buffer_t, /* password */ OM_uint32, /* time_req */ const gss_OID_set, /* desired_mechs */ gss_cred_usage_t, /* cred_usage */ gss_cred_id_t *, /* output_cred_handle */ gss_OID_set *, /* actual_mechs */ OM_uint32 * /* time_rec */ ); typedef OM_uint32 GSSAPI_CALLCONV _gss_add_cred_with_password_t ( OM_uint32 *, /* minor_status */ gss_const_cred_id_t, /* input_cred_handle */ gss_const_name_t, /* desired_name */ const gss_OID, /* desired_mech */ const gss_buffer_t, /* password */ gss_cred_usage_t, /* cred_usage */ OM_uint32, /* initiator_time_req */ OM_uint32, /* acceptor_time_req */ gss_cred_id_t *, /* output_cred_handle */ gss_OID_set *, /* actual_mechs */ OM_uint32 *, /* initiator_time_rec */ OM_uint32 * /* acceptor_time_rec */ ); /* * API-as-SPI compatibility for compatibility with MIT mechanisms; * native Heimdal mechanisms should not use these. */ struct gss_mech_compat_desc_struct { _gss_inquire_saslname_for_mech_t *gmc_inquire_saslname_for_mech; _gss_inquire_mech_for_saslname_t *gmc_inquire_mech_for_saslname; _gss_inquire_attrs_for_mech_t *gmc_inquire_attrs_for_mech; _gss_acquire_cred_with_password_t *gmc_acquire_cred_with_password; #if 0 _gss_add_cred_with_password_t *gmc_add_cred_with_password; #endif }; heimdal-7.5.0/lib/gssapi/mech/gss_release_cred.c0000644000175000017500000000501713026237312017661 0ustar niknik/*- * Copyright (c) 2005 Doug Rabson * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * * $FreeBSD: src/lib/libgssapi/gss_release_cred.c,v 1.1 2005/12/29 14:40:20 dfr Exp $ */ #include "mech_locl.h" /** * Release a credentials * * Its ok to release the GSS_C_NO_CREDENTIAL/NULL credential, it will * return a GSS_S_COMPLETE error code. On return cred_handle is set ot * GSS_C_NO_CREDENTIAL. * * Example: * * @code * gss_cred_id_t cred = GSS_C_NO_CREDENTIAL; * major = gss_release_cred(&minor, &cred); * @endcode * * @param minor_status minor status return code, mech specific * @param cred_handle a pointer to the credential too release * * @return an gssapi error code * * @ingroup gssapi */ GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL gss_release_cred(OM_uint32 *minor_status, gss_cred_id_t *cred_handle) { struct _gss_cred *cred = (struct _gss_cred *) *cred_handle; struct _gss_mechanism_cred *mc; if (*cred_handle == GSS_C_NO_CREDENTIAL) return (GSS_S_COMPLETE); while (HEIM_SLIST_FIRST(&cred->gc_mc)) { mc = HEIM_SLIST_FIRST(&cred->gc_mc); HEIM_SLIST_REMOVE_HEAD(&cred->gc_mc, gmc_link); mc->gmc_mech->gm_release_cred(minor_status, &mc->gmc_cred); free(mc); } free(cred); *minor_status = 0; *cred_handle = GSS_C_NO_CREDENTIAL; return (GSS_S_COMPLETE); } heimdal-7.5.0/lib/gssapi/mech/gss_canonicalize_name.c0000644000175000017500000000724713026237312020712 0ustar niknik/*- * Copyright (c) 2005 Doug Rabson * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * * $FreeBSD: src/lib/libgssapi/gss_canonicalize_name.c,v 1.1 2005/12/29 14:40:20 dfr Exp $ */ #include "mech_locl.h" /** * gss_canonicalize_name takes a Internal Name (IN) and converts in into a * mechanism specific Mechanism Name (MN). * * The input name may multiple name, or generic name types. * * If the input_name if of the GSS_C_NT_USER_NAME, and the Kerberos * mechanism is specified, the resulting MN type is a * GSS_KRB5_NT_PRINCIPAL_NAME. * * For more information about @ref internalVSmechname. * * @param minor_status minor status code. * @param input_name name to covert, unchanged by gss_canonicalize_name(). * @param mech_type the type to convert Name too. * @param output_name the resulting type, release with * gss_release_name(), independent of input_name. * * @returns a gss_error code, see gss_display_status() about printing * the error code. * * @ingroup gssapi */ GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL gss_canonicalize_name(OM_uint32 *minor_status, gss_const_name_t input_name, const gss_OID mech_type, gss_name_t *output_name) { OM_uint32 major_status; struct _gss_name *name = (struct _gss_name *) input_name; struct _gss_mechanism_name *mn; gssapi_mech_interface m; gss_name_t new_canonical_name; *minor_status = 0; *output_name = 0; major_status = _gss_find_mn(minor_status, name, mech_type, &mn); if (major_status) return major_status; m = mn->gmn_mech; major_status = m->gm_canonicalize_name(minor_status, mn->gmn_name, mech_type, &new_canonical_name); if (major_status) { _gss_mg_error(m, major_status, *minor_status); return (major_status); } /* * Now we make a new name and mark it as an MN. */ *minor_status = 0; name = malloc(sizeof(struct _gss_name)); if (!name) { m->gm_release_name(minor_status, &new_canonical_name); *minor_status = ENOMEM; return (GSS_S_FAILURE); } memset(name, 0, sizeof(struct _gss_name)); mn = malloc(sizeof(struct _gss_mechanism_name)); if (!mn) { m->gm_release_name(minor_status, &new_canonical_name); free(name); *minor_status = ENOMEM; return (GSS_S_FAILURE); } HEIM_SLIST_INIT(&name->gn_mn); mn->gmn_mech = m; mn->gmn_mech_oid = &m->gm_mech_oid; mn->gmn_name = new_canonical_name; HEIM_SLIST_INSERT_HEAD(&name->gn_mn, mn, gmn_link); *output_name = (gss_name_t) name; return (GSS_S_COMPLETE); } heimdal-7.5.0/lib/gssapi/mech/gss_release_buffer.c0000644000175000017500000000325212136107747020225 0ustar niknik/*- * Copyright (c) 2005 Doug Rabson * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * * $FreeBSD: src/lib/libgssapi/gss_release_buffer.c,v 1.1 2005/12/29 14:40:20 dfr Exp $ */ #include "mech_locl.h" GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL gss_release_buffer(OM_uint32 *minor_status, gss_buffer_t buffer) { *minor_status = 0; if (buffer->value) free(buffer->value); _mg_buffer_zero(buffer); return (GSS_S_COMPLETE); } heimdal-7.5.0/lib/gssapi/mech/gss_wrap_size_limit.c0000644000175000017500000000400213026237312020436 0ustar niknik/*- * Copyright (c) 2005 Doug Rabson * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * * $FreeBSD: src/lib/libgssapi/gss_wrap_size_limit.c,v 1.1 2005/12/29 14:40:20 dfr Exp $ */ #include "mech_locl.h" GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL gss_wrap_size_limit(OM_uint32 *minor_status, gss_const_ctx_id_t context_handle, int conf_req_flag, gss_qop_t qop_req, OM_uint32 req_output_size, OM_uint32 *max_input_size) { struct _gss_context *ctx = (struct _gss_context *) context_handle; gssapi_mech_interface m; *max_input_size = 0; if (ctx == NULL) { *minor_status = 0; return GSS_S_NO_CONTEXT; } m = ctx->gc_mech; return (m->gm_wrap_size_limit(minor_status, ctx->gc_ctx, conf_req_flag, qop_req, req_output_size, max_input_size)); } heimdal-7.5.0/lib/gssapi/mech/gss_wrap.c0000644000175000017500000000526413026237312016221 0ustar niknik/*- * Copyright (c) 2005 Doug Rabson * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * * $FreeBSD: src/lib/libgssapi/gss_wrap.c,v 1.1 2005/12/29 14:40:20 dfr Exp $ */ #include "mech_locl.h" /** * Wrap a message using either confidentiality (encryption + * signature) or sealing (signature). * * @param minor_status minor status code. * @param context_handle context handle. * @param conf_req_flag if non zero, confidentiality is requestd. * @param qop_req type of protection needed, in most cases it GSS_C_QOP_DEFAULT should be passed in. * @param input_message_buffer messages to wrap * @param conf_state returns non zero if confidentiality was honoured. * @param output_message_buffer the resulting buffer, release with gss_release_buffer(). * * @ingroup gssapi */ GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL gss_wrap(OM_uint32 *minor_status, gss_const_ctx_id_t context_handle, int conf_req_flag, gss_qop_t qop_req, const gss_buffer_t input_message_buffer, int *conf_state, gss_buffer_t output_message_buffer) { struct _gss_context *ctx = (struct _gss_context *) context_handle; gssapi_mech_interface m; if (conf_state) *conf_state = 0; _mg_buffer_zero(output_message_buffer); if (ctx == NULL) { *minor_status = 0; return GSS_S_NO_CONTEXT; } m = ctx->gc_mech; return (m->gm_wrap(minor_status, ctx->gc_ctx, conf_req_flag, qop_req, input_message_buffer, conf_state, output_message_buffer)); } heimdal-7.5.0/lib/gssapi/mech/gss_display_status.c0000644000175000017500000001671313026237312020321 0ustar niknik/*- * Copyright (c) 2005 Doug Rabson * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * * $FreeBSD: src/lib/libgssapi/gss_display_status.c,v 1.1 2005/12/29 14:40:20 dfr Exp $ */ /* * Copyright (c) 1998 - 2005 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "mech_locl.h" static const char * calling_error(OM_uint32 v) { static const char *msgs[] = { NULL, /* 0 */ "A required input parameter could not be read.", /* */ "A required output parameter could not be written.", /* */ "A parameter was malformed" }; v >>= GSS_C_CALLING_ERROR_OFFSET; if (v == 0) return ""; else if (v >= sizeof(msgs)/sizeof(*msgs)) return "unknown calling error"; else return msgs[v]; } static const char * routine_error(OM_uint32 v) { static const char *msgs[] = { "Function completed successfully", /* 0 */ "An unsupported mechanism was requested", "An invalid name was supplied", "A supplied name was of an unsupported type", "Incorrect channel bindings were supplied", "An invalid status code was supplied", "A token had an invalid MIC", "No credentials were supplied, " "or the credentials were unavailable or inaccessible.", "No context has been established", "A token was invalid", "A credential was invalid", "The referenced credentials have expired", "The context has expired", "Miscellaneous failure (see text)", "The quality-of-protection requested could not be provide", "The operation is forbidden by local security policy", "The operation or option is not available", "The requested credential element already exists", "The provided name was not a mechanism name.", }; v >>= GSS_C_ROUTINE_ERROR_OFFSET; if (v >= sizeof(msgs)/sizeof(*msgs)) return "unknown routine error"; else return msgs[v]; } static const char * supplementary_error(OM_uint32 v) { static const char *msgs[] = { "normal completion", "continuation call to routine required", "duplicate per-message token detected", "timed-out per-message token detected", "reordered (early) per-message token detected", "skipped predecessor token(s) detected" }; v >>= GSS_C_SUPPLEMENTARY_OFFSET; if (v >= sizeof(msgs)/sizeof(*msgs)) return "unknown routine error"; else return msgs[v]; } /** * Convert a GSS-API status code to text * * @param minor_status minor status code * @param status_value status value to convert * @param status_type One of: * GSS_C_GSS_CODE - status_value is a GSS status code, * GSS_C_MECH_CODE - status_value is a mechanism status code * @param mech_type underlying mechanism. Use GSS_C_NO_OID to obtain the * system default. * @param message_context state information to extract further messages from the * status_value * @param status_string the allocated text representation. Release with * gss_release_buffer() * * @returns a gss_error code. * * @ingroup gssapi */ GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL gss_display_status(OM_uint32 *minor_status, OM_uint32 status_value, int status_type, const gss_OID mech_type, OM_uint32 *message_context, gss_buffer_t status_string) { OM_uint32 major_status; _mg_buffer_zero(status_string); *message_context = 0; major_status = _gss_mg_get_error(mech_type, status_type, status_value, status_string); if (major_status == GSS_S_COMPLETE) { *message_context = 0; *minor_status = 0; return GSS_S_COMPLETE; } *minor_status = 0; switch (status_type) { case GSS_C_GSS_CODE: { char *buf = NULL; int e; if (GSS_SUPPLEMENTARY_INFO(status_value)) e = asprintf(&buf, "%s", supplementary_error( GSS_SUPPLEMENTARY_INFO(status_value))); else e = asprintf (&buf, "%s %s", calling_error(GSS_CALLING_ERROR(status_value)), routine_error(GSS_ROUTINE_ERROR(status_value))); if (e < 0 || buf == NULL) break; status_string->length = strlen(buf); status_string->value = buf; return GSS_S_COMPLETE; } case GSS_C_MECH_CODE: { OM_uint32 maj_junk, min_junk; gss_buffer_desc oid; char *buf = NULL; int e; maj_junk = gss_oid_to_str(&min_junk, mech_type, &oid); if (maj_junk != GSS_S_COMPLETE) { oid.value = rk_UNCONST("unknown"); oid.length = 7; } e = asprintf (&buf, "unknown mech-code %lu for mech %.*s", (unsigned long)status_value, (int)oid.length, (char *)oid.value); if (maj_junk == GSS_S_COMPLETE) gss_release_buffer(&min_junk, &oid); if (e < 0 || buf == NULL) break; status_string->length = strlen(buf); status_string->value = buf; return GSS_S_COMPLETE; } } _mg_buffer_zero(status_string); return (GSS_S_BAD_STATUS); } heimdal-7.5.0/lib/gssapi/mech/mech_locl.h0000644000175000017500000000456213026237312016326 0ustar niknik/* * Copyright (c) 2006 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ /* $Id$ */ #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include "mechqueue.h" #include "context.h" #include "cred.h" #include "mech_switch.h" #include "name.h" #include "utils.h" #include "compat.h" #define _mg_buffer_zero(buffer) \ do { \ if (buffer) { \ (buffer)->value = NULL; \ (buffer)->length = 0; \ } \ } while(0) #define _mg_oid_set_zero(oid_set) \ do { \ if (oid_set) { \ (oid_set)->elements = NULL; \ (oid_set)->count = 0; \ } \ } while(0) heimdal-7.5.0/lib/gssapi/mech/gss_display_name_ext.c0000644000175000017500000000512613026237312020572 0ustar niknik/* * Copyright (c) 2010, PADL Software Pty Ltd. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of PADL Software nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY PADL SOFTWARE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL PADL SOFTWARE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "mech_locl.h" GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL gss_display_name_ext(OM_uint32 *minor_status, gss_name_t input_name, gss_OID display_as_name_type, gss_buffer_t display_name) { OM_uint32 major_status = GSS_S_UNAVAILABLE; struct _gss_name *name = (struct _gss_name *) input_name; struct _gss_mechanism_name *mn; *minor_status = 0; _mg_buffer_zero(display_name); if (input_name == GSS_C_NO_NAME) return GSS_S_BAD_NAME; HEIM_SLIST_FOREACH(mn, &name->gn_mn, gmn_link) { gssapi_mech_interface m = mn->gmn_mech; if (!m->gm_display_name_ext) continue; major_status = m->gm_display_name_ext(minor_status, mn->gmn_name, display_as_name_type, display_name); if (GSS_ERROR(major_status)) _gss_mg_error(m, major_status, *minor_status); else break; } return major_status; } heimdal-7.5.0/lib/gssapi/mech/gss_inquire_mechs_for_name.c0000644000175000017500000000526413026237312021751 0ustar niknik/*- * Copyright (c) 2005 Doug Rabson * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * * $FreeBSD: src/lib/libgssapi/gss_inquire_mechs_for_name.c,v 1.1 2005/12/29 14:40:20 dfr Exp $ */ #include "mech_locl.h" GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL gss_inquire_mechs_for_name(OM_uint32 *minor_status, gss_const_name_t input_name, gss_OID_set *mech_types) { OM_uint32 major_status; struct _gss_name *name = (struct _gss_name *) input_name; struct _gss_mech_switch *m; gss_OID_set name_types; int present; *minor_status = 0; _gss_load_mech(); major_status = gss_create_empty_oid_set(minor_status, mech_types); if (major_status) return (major_status); /* * We go through all the loaded mechanisms and see if this * name's type is supported by the mechanism. If it is, add * the mechanism to the set. */ HEIM_SLIST_FOREACH(m, &_gss_mechs, gm_link) { major_status = gss_inquire_names_for_mech(minor_status, &m->gm_mech_oid, &name_types); if (major_status) { gss_release_oid_set(minor_status, mech_types); return (major_status); } gss_test_oid_set_member(minor_status, &name->gn_type, name_types, &present); gss_release_oid_set(minor_status, &name_types); if (present) { major_status = gss_add_oid_set_member(minor_status, &m->gm_mech_oid, mech_types); if (major_status) { gss_release_oid_set(minor_status, mech_types); return (major_status); } } } return (GSS_S_COMPLETE); } heimdal-7.5.0/lib/gssapi/mech/gss_oid_equal.c0000644000175000017500000000431013026237312017201 0ustar niknik/* * Copyright (c) 2006 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "mech_locl.h" /** * Compare two GSS-API OIDs with each other. * * GSS_C_NO_OID matches nothing, not even it-self. * * @param a first oid to compare * @param b second oid to compare * * @return non-zero when both oid are the same OID, zero when they are * not the same. * * @ingroup gssapi */ GSSAPI_LIB_FUNCTION int GSSAPI_LIB_CALL gss_oid_equal(gss_const_OID a, gss_const_OID b) { if (a == b && a != GSS_C_NO_OID) return 1; if (a == GSS_C_NO_OID || b == GSS_C_NO_OID || a->length != b->length) return 0; return memcmp(a->elements, b->elements, a->length) == 0; } heimdal-7.5.0/lib/gssapi/mech/mech.cat50000644000175000017500000000457313212450760015725 0ustar niknik MECH(5) BSD File Formats Manual MECH(5) NNAAMMEE mmeecchh, qqoopp -- GSS-API Mechanism and QOP files SSYYNNOOPPSSIISS _/_e_t_c_/_g_s_s_/_m_e_c_h _/_e_t_c_/_g_s_s_/_q_o_p DDEESSCCRRIIPPTTIIOONN The _/_e_t_c_/_g_s_s_/_m_e_c_h file contains a list of installed GSS-API security mechanisms. Each line of the file either contains a comment if the first character is '#' or it contains five fields with the following meanings: Name The name of this GSS-API mechanism. Object identifier The OID for this mechanism. Library A shared library containing the implementation of this mechanism. Kernel module (optional) A kernel module containing the implementation of this mech- anism (not yet supported in FreeBSD). Library options (optional) Optionsal parameters interpreted by the mechanism. Library options must be enclosed in brackets ([ ]) to differentiate them from the optional kernel module entry. The _/_e_t_c_/_g_s_s_/_q_o_p file contains a list of Quality of Protection values for use with GSS-API. Each line of the file either contains a comment if the first character is '#' or it contains three fields with the following meanings: QOP string The name of this Quality of Protection algorithm. QOP value The numeric value used to select this algorithm for use with GSS-API functions such as gss_get_mic(3). Mechanism name The GSS-API mechanism name that corresponds to this algo- rithm. EEXXAAMMPPLLEESS This is a typical entry from _/_e_t_c_/_g_s_s_/_m_e_c_h: kerberosv5 1.2.840.113554.1.2.2 /usr/lib/libgssapi_krb5.so.8 - This is a typical entry from _/_e_t_c_/_g_s_s_/_q_o_p: GSS_KRB5_CONF_C_QOP_DES 0x0100 kerberosv5 HHIISSTTOORRYY The mmeecchh manual page example first appeared in FreeBSD 7.0. AAUUTTHHOORRSS This manual page was written by Doug Rabson <_d_f_r_@_F_r_e_e_B_S_D_._o_r_g>. BSD November 14, 2005 BSD heimdal-7.5.0/lib/gssapi/mech/gss_delete_sec_context.c0000644000175000017500000000413313026237312021102 0ustar niknik/*- * Copyright (c) 2005 Doug Rabson * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * * $FreeBSD: src/lib/libgssapi/gss_delete_sec_context.c,v 1.1 2005/12/29 14:40:20 dfr Exp $ */ #include "mech_locl.h" GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL gss_delete_sec_context(OM_uint32 *minor_status, gss_ctx_id_t *context_handle, gss_buffer_t output_token) { OM_uint32 major_status = GSS_S_COMPLETE; struct _gss_context *ctx = (struct _gss_context *) *context_handle; if (output_token) _mg_buffer_zero(output_token); *minor_status = 0; if (ctx) { /* * If we have an implementation ctx, delete it, * otherwise fake an empty token. */ if (ctx->gc_ctx) { major_status = ctx->gc_mech->gm_delete_sec_context( minor_status, &ctx->gc_ctx, output_token); } free(ctx); *context_handle = GSS_C_NO_CONTEXT; } return (major_status); } heimdal-7.5.0/lib/gssapi/mech/gss_names.c0000644000175000017500000000613313026237312016347 0ustar niknik/*- * Copyright (c) 2005 Doug Rabson * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * * $FreeBSD: src/lib/libgssapi/gss_names.c,v 1.1 2005/12/29 14:40:20 dfr Exp $ */ #include "mech_locl.h" OM_uint32 _gss_find_mn(OM_uint32 *minor_status, struct _gss_name *name, gss_OID mech, struct _gss_mechanism_name **output_mn) { OM_uint32 major_status; gssapi_mech_interface m; struct _gss_mechanism_name *mn; *output_mn = NULL; HEIM_SLIST_FOREACH(mn, &name->gn_mn, gmn_link) { if (gss_oid_equal(mech, mn->gmn_mech_oid)) break; } if (!mn) { /* * If this name is canonical (i.e. there is only an * MN but it is from a different mech), give up now. */ if (!name->gn_value.value) return GSS_S_BAD_NAME; m = __gss_get_mechanism(mech); if (!m) return (GSS_S_BAD_MECH); mn = malloc(sizeof(struct _gss_mechanism_name)); if (!mn) return GSS_S_FAILURE; major_status = m->gm_import_name(minor_status, &name->gn_value, (name->gn_type.elements ? &name->gn_type : GSS_C_NO_OID), &mn->gmn_name); if (major_status != GSS_S_COMPLETE) { _gss_mg_error(m, major_status, *minor_status); free(mn); return major_status; } mn->gmn_mech = m; mn->gmn_mech_oid = &m->gm_mech_oid; HEIM_SLIST_INSERT_HEAD(&name->gn_mn, mn, gmn_link); } *output_mn = mn; return 0; } /* * Make a name from an MN. */ struct _gss_name * _gss_make_name(gssapi_mech_interface m, gss_name_t new_mn) { struct _gss_name *name; struct _gss_mechanism_name *mn; name = malloc(sizeof(struct _gss_name)); if (!name) return (0); memset(name, 0, sizeof(struct _gss_name)); mn = malloc(sizeof(struct _gss_mechanism_name)); if (!mn) { free(name); return (0); } HEIM_SLIST_INIT(&name->gn_mn); mn->gmn_mech = m; mn->gmn_mech_oid = &m->gm_mech_oid; mn->gmn_name = new_mn; HEIM_SLIST_INSERT_HEAD(&name->gn_mn, mn, gmn_link); return (name); } heimdal-7.5.0/lib/gssapi/mech/gss_release_oid_set.c0000644000175000017500000000332512136107747020403 0ustar niknik/*- * Copyright (c) 2005 Doug Rabson * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * * $FreeBSD: src/lib/libgssapi/gss_release_oid_set.c,v 1.1 2005/12/29 14:40:20 dfr Exp $ */ #include "mech_locl.h" GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL gss_release_oid_set(OM_uint32 *minor_status, gss_OID_set *set) { *minor_status = 0; if (set && *set) { if ((*set)->elements) free((*set)->elements); free(*set); *set = GSS_C_NO_OID_SET; } return (GSS_S_COMPLETE); } heimdal-7.5.0/lib/gssapi/mech/gss_import_name.c0000644000175000017500000001572013026237312017560 0ustar niknik/*- * Copyright (c) 2005 Doug Rabson * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * * $FreeBSD: src/lib/libgssapi/gss_import_name.c,v 1.1 2005/12/29 14:40:20 dfr Exp $ */ #include "mech_locl.h" static OM_uint32 _gss_import_export_name(OM_uint32 *minor_status, const gss_buffer_t input_name_buffer, gss_name_t *output_name) { OM_uint32 major_status; unsigned char *p = input_name_buffer->value; size_t len = input_name_buffer->length; size_t t; gss_OID_desc mech_oid; gssapi_mech_interface m; struct _gss_name *name; gss_name_t new_canonical_name; int composite = 0; *minor_status = 0; *output_name = 0; /* * Make sure that TOK_ID is {4, 1}. */ if (len < 2) return (GSS_S_BAD_NAME); if (p[0] != 4) return (GSS_S_BAD_NAME); switch (p[1]) { case 1: /* non-composite name */ break; case 2: /* composite name */ composite = 1; break; default: return (GSS_S_BAD_NAME); } p += 2; len -= 2; /* * Get the mech length and the name length and sanity * check the size of of the buffer. */ if (len < 2) return (GSS_S_BAD_NAME); t = (p[0] << 8) + p[1]; p += 2; len -= 2; /* * Check the DER encoded OID to make sure it agrees with the * length we just decoded. */ if (p[0] != 6) /* 6=OID */ return (GSS_S_BAD_NAME); p++; len--; t--; if (p[0] & 0x80) { int digits = p[0]; p++; len--; t--; mech_oid.length = 0; while (digits--) { mech_oid.length = (mech_oid.length << 8) | p[0]; p++; len--; t--; } } else { mech_oid.length = p[0]; p++; len--; t--; } if (mech_oid.length != t) return (GSS_S_BAD_NAME); mech_oid.elements = p; if (len < t + 4) return (GSS_S_BAD_NAME); p += t; len -= t; t = (p[0] << 24) | (p[1] << 16) | (p[2] << 8) | p[3]; p += 4; len -= 4; if (!composite && len != t) return (GSS_S_BAD_NAME); m = __gss_get_mechanism(&mech_oid); if (!m) return (GSS_S_BAD_MECH); /* * Ask the mechanism to import the name. */ major_status = m->gm_import_name(minor_status, input_name_buffer, GSS_C_NT_EXPORT_NAME, &new_canonical_name); if (major_status != GSS_S_COMPLETE) { _gss_mg_error(m, major_status, *minor_status); return major_status; } /* * Now we make a new name and mark it as an MN. */ name = _gss_make_name(m, new_canonical_name); if (!name) { m->gm_release_name(minor_status, &new_canonical_name); return (GSS_S_FAILURE); } *output_name = (gss_name_t) name; *minor_status = 0; return (GSS_S_COMPLETE); } /** * Convert a GGS-API name from contiguous string to internal form. * * Type of name and their format: * - GSS_C_NO_OID * - GSS_C_NT_USER_NAME * - GSS_C_NT_HOSTBASED_SERVICE * - GSS_C_NT_EXPORT_NAME * - GSS_C_NT_ANONYMOUS * - GSS_KRB5_NT_PRINCIPAL_NAME * * @sa gss_export_name(), @ref internalVSmechname. * * @param minor_status minor status code * @param input_name_buffer import name buffer * @param input_name_type type of the import name buffer * @param output_name the resulting type, release with * gss_release_name(), independent of input_name * * @returns a gss_error code, see gss_display_status() about printing * the error code. * * @ingroup gssapi */ GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL gss_import_name(OM_uint32 *minor_status, const gss_buffer_t input_name_buffer, const gss_OID input_name_type, gss_name_t *output_name) { struct _gss_mechanism_name *mn; gss_OID name_type = input_name_type; OM_uint32 major_status, ms; struct _gss_name *name; struct _gss_mech_switch *m; gss_name_t rname; *output_name = GSS_C_NO_NAME; if (input_name_buffer->length == 0) { *minor_status = 0; return (GSS_S_BAD_NAME); } _gss_load_mech(); /* * Use GSS_NT_USER_NAME as default name type. */ if (name_type == GSS_C_NO_OID) name_type = GSS_C_NT_USER_NAME; /* * If this is an exported name, we need to parse it to find * the mechanism and then import it as an MN. See RFC 2743 * section 3.2 for a description of the format. */ if (gss_oid_equal(name_type, GSS_C_NT_EXPORT_NAME)) { return _gss_import_export_name(minor_status, input_name_buffer, output_name); } *minor_status = 0; name = calloc(1, sizeof(struct _gss_name)); if (!name) { *minor_status = ENOMEM; return (GSS_S_FAILURE); } HEIM_SLIST_INIT(&name->gn_mn); major_status = _gss_copy_oid(minor_status, name_type, &name->gn_type); if (major_status) { free(name); return (GSS_S_FAILURE); } major_status = _gss_copy_buffer(minor_status, input_name_buffer, &name->gn_value); if (major_status) goto out; /* * Walk over the mechs and import the name into a mech name * for those supported this nametype. */ HEIM_SLIST_FOREACH(m, &_gss_mechs, gm_link) { int present = 0; major_status = gss_test_oid_set_member(minor_status, name_type, m->gm_name_types, &present); if (major_status || present == 0) continue; mn = malloc(sizeof(struct _gss_mechanism_name)); if (!mn) { *minor_status = ENOMEM; major_status = GSS_S_FAILURE; goto out; } major_status = (*m->gm_mech.gm_import_name)(minor_status, &name->gn_value, (name->gn_type.elements ? &name->gn_type : GSS_C_NO_OID), &mn->gmn_name); if (major_status != GSS_S_COMPLETE) { _gss_mg_error(&m->gm_mech, major_status, *minor_status); free(mn); goto out; } mn->gmn_mech = &m->gm_mech; mn->gmn_mech_oid = &m->gm_mech_oid; HEIM_SLIST_INSERT_HEAD(&name->gn_mn, mn, gmn_link); } /* * If we can't find a mn for the name, bail out already here. */ mn = HEIM_SLIST_FIRST(&name->gn_mn); if (!mn) { *minor_status = 0; major_status = GSS_S_NAME_NOT_MN; goto out; } *output_name = (gss_name_t) name; return (GSS_S_COMPLETE); out: rname = (gss_name_t)name; gss_release_name(&ms, &rname); return major_status; } heimdal-7.5.0/lib/gssapi/mech/gss_unseal.c0000644000175000017500000000346612136107747016552 0ustar niknik/*- * Copyright (c) 2005 Doug Rabson * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * * $FreeBSD: src/lib/libgssapi/gss_unseal.c,v 1.1 2005/12/29 14:40:20 dfr Exp $ */ #include "mech_locl.h" GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL gss_unseal(OM_uint32 *minor_status, gss_ctx_id_t context_handle, gss_buffer_t input_message_buffer, gss_buffer_t output_message_buffer, int *conf_state, int *qop_state) { return (gss_unwrap(minor_status, context_handle, input_message_buffer, output_message_buffer, conf_state, (gss_qop_t *)qop_state)); } heimdal-7.5.0/lib/gssapi/mech/gss_inquire_cred_by_oid.c0000644000175000017500000000552013026237312021241 0ustar niknik/* * Copyright (c) 2004, PADL Software Pty Ltd. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of PADL Software nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY PADL SOFTWARE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL PADL SOFTWARE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "mech_locl.h" GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL gss_inquire_cred_by_oid (OM_uint32 *minor_status, gss_const_cred_id_t cred_handle, const gss_OID desired_object, gss_buffer_set_t *data_set) { struct _gss_cred *cred = (struct _gss_cred *) cred_handle; OM_uint32 status = GSS_S_COMPLETE; struct _gss_mechanism_cred *mc; gssapi_mech_interface m; gss_buffer_set_t set = GSS_C_NO_BUFFER_SET; *minor_status = 0; *data_set = GSS_C_NO_BUFFER_SET; if (cred == NULL) return GSS_S_NO_CRED; HEIM_SLIST_FOREACH(mc, &cred->gc_mc, gmc_link) { gss_buffer_set_t rset = GSS_C_NO_BUFFER_SET; size_t i; m = mc->gmc_mech; if (m == NULL) { gss_release_buffer_set(minor_status, &set); *minor_status = 0; return GSS_S_BAD_MECH; } if (m->gm_inquire_cred_by_oid == NULL) continue; status = m->gm_inquire_cred_by_oid(minor_status, mc->gmc_cred, desired_object, &rset); if (status != GSS_S_COMPLETE) continue; for (i = 0; i < rset->count; i++) { status = gss_add_buffer_set_member(minor_status, &rset->elements[i], &set); if (status != GSS_S_COMPLETE) break; } gss_release_buffer_set(minor_status, &rset); } if (set == GSS_C_NO_BUFFER_SET) status = GSS_S_FAILURE; *data_set = set; *minor_status = 0; return status; } heimdal-7.5.0/lib/gssapi/mech/gss_indicate_mechs.c0000644000175000017500000000447713026237312020214 0ustar niknik/*- * Copyright (c) 2005 Doug Rabson * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * * $FreeBSD: src/lib/libgssapi/gss_indicate_mechs.c,v 1.1 2005/12/29 14:40:20 dfr Exp $ */ #include "mech_locl.h" GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL gss_indicate_mechs(OM_uint32 *minor_status, gss_OID_set *mech_set) { struct _gss_mech_switch *m; OM_uint32 major_status; gss_OID_set set; size_t i; _gss_load_mech(); major_status = gss_create_empty_oid_set(minor_status, mech_set); if (major_status) return (major_status); /* XXX We ignore ENOMEM from gss_add_oid_set_member() */ HEIM_SLIST_FOREACH(m, &_gss_mechs, gm_link) { if (m->gm_mech.gm_indicate_mechs) { major_status = m->gm_mech.gm_indicate_mechs( minor_status, &set); if (major_status) continue; for (i = 0; i < set->count; i++) gss_add_oid_set_member( minor_status, &set->elements[i], mech_set); gss_release_oid_set(minor_status, &set); } else { gss_add_oid_set_member( minor_status, &m->gm_mech_oid, mech_set); } } *minor_status = 0; return (GSS_S_COMPLETE); } heimdal-7.5.0/lib/gssapi/mech/gss_store_cred.c0000644000175000017500000000671413026237312017402 0ustar niknik/* * Copyright (c) 2009 Kungliga Tekniska Hgskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "mech_locl.h" GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL gss_store_cred(OM_uint32 *minor_status, gss_cred_id_t input_cred_handle, gss_cred_usage_t cred_usage, const gss_OID desired_mech, OM_uint32 overwrite_cred, OM_uint32 default_cred, gss_OID_set *elements_stored, gss_cred_usage_t *cred_usage_stored) { struct _gss_cred *cred = (struct _gss_cred *) input_cred_handle; struct _gss_mechanism_cred *mc; OM_uint32 maj = GSS_S_FAILURE; OM_uint32 junk; size_t successes = 0; if (minor_status == NULL) return GSS_S_FAILURE; if (elements_stored) *elements_stored = NULL; if (cred_usage_stored) *cred_usage_stored = 0; if (cred == NULL) return GSS_S_NO_CONTEXT; if (elements_stored) { maj = gss_create_empty_oid_set(minor_status, elements_stored); if (maj != GSS_S_COMPLETE) return maj; } HEIM_SLIST_FOREACH(mc, &cred->gc_mc, gmc_link) { gssapi_mech_interface m = mc->gmc_mech; if (m == NULL || m->gm_store_cred == NULL) continue; if (desired_mech != GSS_C_NO_OID && !gss_oid_equal(&m->gm_mech_oid, desired_mech)) continue; maj = (m->gm_store_cred)(minor_status, mc->gmc_cred, cred_usage, desired_mech, overwrite_cred, default_cred, NULL, cred_usage_stored); if (maj == GSS_S_COMPLETE) { if (elements_stored) gss_add_oid_set_member(&junk, desired_mech, elements_stored); successes++; } else if (desired_mech != GSS_C_NO_OID) { gss_release_oid_set(&junk, elements_stored); return maj; } } if (successes == 0) { if (maj != GSS_S_COMPLETE) return maj; /* last failure */ return GSS_S_FAILURE; } *minor_status = 0; return GSS_S_COMPLETE; } heimdal-7.5.0/lib/gssapi/mech/gss_inquire_name.c0000644000175000017500000000561513026237312017724 0ustar niknik/* * Copyright (c) 2010, PADL Software Pty Ltd. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of PADL Software nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY PADL SOFTWARE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL PADL SOFTWARE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "mech_locl.h" GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL gss_inquire_name(OM_uint32 *minor_status, gss_name_t input_name, int *name_is_MN, gss_OID *MN_mech, gss_buffer_set_t *attrs) { OM_uint32 major_status = GSS_S_UNAVAILABLE; struct _gss_name *name = (struct _gss_name *) input_name; struct _gss_mechanism_name *mn; *minor_status = 0; if (name_is_MN != NULL) *name_is_MN = 0; if (MN_mech != NULL) *MN_mech = GSS_C_NO_OID; if (attrs != NULL) *attrs = GSS_C_NO_BUFFER_SET; if (input_name == GSS_C_NO_NAME) return GSS_S_BAD_NAME; HEIM_SLIST_FOREACH(mn, &name->gn_mn, gmn_link) { gssapi_mech_interface m = mn->gmn_mech; if (!m->gm_inquire_name) continue; major_status = m->gm_inquire_name(minor_status, mn->gmn_name, NULL, MN_mech, attrs); if (major_status == GSS_S_COMPLETE) { if (name_is_MN != NULL) *name_is_MN = 1; if (MN_mech != NULL && *MN_mech == GSS_C_NO_OID) *MN_mech = &m->gm_mech_oid; break; } _gss_mg_error(m, major_status, *minor_status); } return major_status; } heimdal-7.5.0/lib/gssapi/mech/mech_switch.h0000644000175000017500000000344413026237312016674 0ustar niknik/*- * Copyright (c) 2005 Doug Rabson * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * * $FreeBSD: src/lib/libgssapi/mech_switch.h,v 1.1 2005/12/29 14:40:20 dfr Exp $ * $Id$ */ #include struct _gss_mech_switch { HEIM_SLIST_ENTRY(_gss_mech_switch) gm_link; gss_OID_desc gm_mech_oid; gss_OID_set gm_name_types; void *gm_so; gssapi_mech_interface_desc gm_mech; }; HEIM_SLIST_HEAD(_gss_mech_switch_list, _gss_mech_switch); extern struct _gss_mech_switch_list _gss_mechs; extern gss_OID_set _gss_mech_oids; void _gss_load_mech(void); heimdal-7.5.0/lib/gssapi/mech/gss_acquire_cred_with_password.c0000644000175000017500000000736413026237312022656 0ustar niknik/* * Copyright (c) 2011, PADL Software Pty Ltd. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of PADL Software nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY PADL SOFTWARE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL PADL SOFTWARE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "mech_locl.h" GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL gss_acquire_cred_with_password(OM_uint32 *minor_status, gss_const_name_t desired_name, const gss_buffer_t password, OM_uint32 time_req, const gss_OID_set desired_mechs, gss_cred_usage_t cred_usage, gss_cred_id_t *output_cred_handle, gss_OID_set *actual_mechs, OM_uint32 *time_rec) { OM_uint32 major_status, tmp_minor; if (desired_mechs == GSS_C_NO_OID_SET) { major_status = _gss_acquire_cred_ext(minor_status, desired_name, GSS_C_CRED_PASSWORD, password, time_req, GSS_C_NO_OID, cred_usage, output_cred_handle); if (GSS_ERROR(major_status)) return major_status; } else { size_t i; struct _gss_cred *new_cred; new_cred = calloc(1, sizeof(*new_cred)); if (new_cred == NULL) { *minor_status = ENOMEM; return GSS_S_FAILURE; } HEIM_SLIST_INIT(&new_cred->gc_mc); for (i = 0; i < desired_mechs->count; i++) { struct _gss_cred *tmp_cred = NULL; struct _gss_mechanism_cred *mc; major_status = _gss_acquire_cred_ext(minor_status, desired_name, GSS_C_CRED_PASSWORD, password, time_req, &desired_mechs->elements[i], cred_usage, (gss_cred_id_t *)&tmp_cred); if (GSS_ERROR(major_status)) continue; mc = HEIM_SLIST_FIRST(&tmp_cred->gc_mc); if (mc) { HEIM_SLIST_REMOVE_HEAD(&tmp_cred->gc_mc, gmc_link); HEIM_SLIST_INSERT_HEAD(&new_cred->gc_mc, mc, gmc_link); } gss_release_cred(&tmp_minor, (gss_cred_id_t *)&tmp_cred); } if (!HEIM_SLIST_FIRST(&new_cred->gc_mc)) { free(new_cred); if (desired_mechs->count > 1) *minor_status = 0; return GSS_S_NO_CRED; } *output_cred_handle = (gss_cred_id_t)new_cred; } if (actual_mechs != NULL || time_rec != NULL) { major_status = gss_inquire_cred(minor_status, *output_cred_handle, NULL, time_rec, NULL, actual_mechs); if (GSS_ERROR(major_status)) { gss_release_cred(&tmp_minor, output_cred_handle); return major_status; } } *minor_status = 0; return GSS_S_COMPLETE; } heimdal-7.5.0/lib/gssapi/mech/mech.50000644000175000017500000000631013062303006015215 0ustar niknik.\" Copyright (c) 2005 Doug Rabson .\" All rights reserved. .\" .\" Redistribution and use in source and binary forms, with or without .\" modification, are permitted provided that the following conditions .\" are met: .\" 1. Redistributions of source code must retain the above copyright .\" notice, this list of conditions and the following disclaimer. .\" 2. Redistributions in binary form must reproduce the above copyright .\" notice, this list of conditions and the following disclaimer in the .\" documentation and/or other materials provided with the distribution. .\" .\" THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND .\" ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE .\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE .\" ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE .\" FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL .\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS .\" OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) .\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT .\" LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF .\" SUCH DAMAGE. .\" .\" $FreeBSD: src/lib/libgssapi/mech.5,v 1.1 2005/12/29 14:40:20 dfr Exp $ .Dd November 14, 2005 .Dt MECH 5 .Os .Sh NAME .Nm mech , .Nm qop .Nd "GSS-API Mechanism and QOP files" .Sh SYNOPSIS .Pa "/etc/gss/mech" .Pa "/etc/gss/qop" .Sh DESCRIPTION The .Pa "/etc/gss/mech" file contains a list of installed GSS-API security mechanisms. Each line of the file either contains a comment if the first character is '#' or it contains five fields with the following meanings: .Bl -tag .It Name The name of this GSS-API mechanism. .It Object identifier The OID for this mechanism. .It Library A shared library containing the implementation of this mechanism. .It Kernel module (optional) A kernel module containing the implementation of this mechanism (not yet supported in FreeBSD). .It Library options (optional) Optionsal parameters interpreted by the mechanism. Library options must be enclosed in brackets ([ ]) to differentiate them from the optional kernel module entry. .El .Pp The .Pa "/etc/gss/qop" file contains a list of Quality of Protection values for use with GSS-API. Each line of the file either contains a comment if the first character is '#' or it contains three fields with the following meanings: .Bl -tag .It QOP string The name of this Quality of Protection algorithm. .It QOP value The numeric value used to select this algorithm for use with GSS-API functions such as .Xr gss_get_mic 3 . .It Mechanism name The GSS-API mechanism name that corresponds to this algorithm. .El .Sh EXAMPLES This is a typical entry from .Pa "/etc/gss/mech" : .Bd -literal kerberosv5 1.2.840.113554.1.2.2 /usr/lib/libgssapi_krb5.so.8 - .Ed .Pp This is a typical entry from .Pa "/etc/gss/qop" : .Bd -literal GSS_KRB5_CONF_C_QOP_DES 0x0100 kerberosv5 .Ed .Sh HISTORY The .Nm manual page example first appeared in .Fx 7.0 . .Sh AUTHORS This manual page was written by .An Doug Rabson Aq Mt dfr@FreeBSD.org . heimdal-7.5.0/lib/gssapi/mech/gss_export_name.c0000644000175000017500000000470513026237312017570 0ustar niknik/*- * Copyright (c) 2005 Doug Rabson * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * * $FreeBSD: src/lib/libgssapi/gss_export_name.c,v 1.1 2005/12/29 14:40:20 dfr Exp $ */ #include "mech_locl.h" /** * Convert a GGS-API name from internal form to contiguous string. * * @sa gss_import_name(), @ref internalVSmechname. * * @param minor_status minor status code * @param input_name input name in internal name form * @param exported_name output name in contiguos string form * * @returns a gss_error code, see gss_display_status() about printing * the error code. * * @ingroup gssapi */ GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL gss_export_name(OM_uint32 *minor_status, gss_const_name_t input_name, gss_buffer_t exported_name) { struct _gss_name *name = (struct _gss_name *) input_name; struct _gss_mechanism_name *mn; _mg_buffer_zero(exported_name); /* * If this name already has any attached MNs, export the first * one, otherwise export based on the first mechanism in our * list. */ mn = HEIM_SLIST_FIRST(&name->gn_mn); if (!mn) { *minor_status = 0; return (GSS_S_NAME_NOT_MN); } return mn->gmn_mech->gm_export_name(minor_status, mn->gmn_name, exported_name); } heimdal-7.5.0/lib/gssapi/mech/gss_init_sec_context.c0000644000175000017500000001543213026237312020607 0ustar niknik/*- * Copyright (c) 2005 Doug Rabson * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * * $FreeBSD: src/lib/libgssapi/gss_init_sec_context.c,v 1.1 2005/12/29 14:40:20 dfr Exp $ */ #include "mech_locl.h" static gss_cred_id_t _gss_mech_cred_find(gss_const_cred_id_t cred_handle, gss_OID mech_type) { struct _gss_cred *cred = (struct _gss_cred *)cred_handle; struct _gss_mechanism_cred *mc; if (cred == NULL) return GSS_C_NO_CREDENTIAL; HEIM_SLIST_FOREACH(mc, &cred->gc_mc, gmc_link) { if (gss_oid_equal(mech_type, mc->gmc_mech_oid)) return mc->gmc_cred; } return GSS_C_NO_CREDENTIAL; } /** * As the initiator build a context with an acceptor. * * Returns in the major * - GSS_S_COMPLETE - if the context if build * - GSS_S_CONTINUE_NEEDED - if the caller needs to continue another * round of gss_i nit_sec_context * - error code - any other error code * * @param minor_status minor status code. * * @param initiator_cred_handle the credential to use when building * the context, if GSS_C_NO_CREDENTIAL is passed, the default * credential for the mechanism will be used. * * @param context_handle a pointer to a context handle, will be * returned as long as there is not an error. * * @param target_name the target name of acceptor, created using * gss_import_name(). The name is can be of any name types the * mechanism supports, check supported name types with * gss_inquire_names_for_mech(). * * @param input_mech_type mechanism type to use, if GSS_C_NO_OID is * used, Kerberos (GSS_KRB5_MECHANISM) will be tried. Other * available mechanism are listed in the @ref gssapi_mechs_intro * section. * * @param req_flags flags using when building the context, see @ref * gssapi_context_flags * * @param time_req time requested this context should be valid in * seconds, common used value is GSS_C_INDEFINITE * * @param input_chan_bindings Channel bindings used, if not exepected * otherwise, used GSS_C_NO_CHANNEL_BINDINGS * * @param input_token input token sent from the acceptor, for the * initial packet the buffer of { NULL, 0 } should be used. * * @param actual_mech_type the actual mech used, MUST NOT be freed * since it pointing to static memory. * * @param output_token if there is an output token, regardless of * complete, continue_needed, or error it should be sent to the * acceptor * * @param ret_flags return what flags was negotitated, caller should * check if they are accetable. For example, if * GSS_C_MUTUAL_FLAG was negotiated with the acceptor or not. * * @param time_rec amount of time this context is valid for * * @returns a gss_error code, see gss_display_status() about printing * the error code. * * @ingroup gssapi */ GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL gss_init_sec_context(OM_uint32 * minor_status, gss_const_cred_id_t initiator_cred_handle, gss_ctx_id_t * context_handle, gss_const_name_t target_name, const gss_OID input_mech_type, OM_uint32 req_flags, OM_uint32 time_req, const gss_channel_bindings_t input_chan_bindings, const gss_buffer_t input_token, gss_OID * actual_mech_type, gss_buffer_t output_token, OM_uint32 * ret_flags, OM_uint32 * time_rec) { OM_uint32 major_status; gssapi_mech_interface m; struct _gss_name *name = (struct _gss_name *) target_name; struct _gss_mechanism_name *mn; struct _gss_context *ctx = (struct _gss_context *) *context_handle; gss_const_cred_id_t cred_handle; int allocated_ctx; gss_OID mech_type = input_mech_type; *minor_status = 0; _mg_buffer_zero(output_token); if (actual_mech_type) *actual_mech_type = GSS_C_NO_OID; if (ret_flags) *ret_flags = 0; if (time_rec) *time_rec = 0; /* * If we haven't allocated a context yet, do so now and lookup * the mechanism switch table. If we have one already, make * sure we use the same mechanism switch as before. */ if (!ctx) { if (mech_type == NULL) mech_type = GSS_KRB5_MECHANISM; ctx = malloc(sizeof(struct _gss_context)); if (!ctx) { *minor_status = ENOMEM; return (GSS_S_FAILURE); } memset(ctx, 0, sizeof(struct _gss_context)); m = ctx->gc_mech = __gss_get_mechanism(mech_type); if (!m) { free(ctx); return (GSS_S_BAD_MECH); } allocated_ctx = 1; } else { m = ctx->gc_mech; mech_type = &ctx->gc_mech->gm_mech_oid; allocated_ctx = 0; } /* * Find the MN for this mechanism. */ major_status = _gss_find_mn(minor_status, name, mech_type, &mn); if (major_status != GSS_S_COMPLETE) { if (allocated_ctx) free(ctx); return major_status; } /* * If we have a cred, find the cred for this mechanism. */ if (m->gm_flags & GM_USE_MG_CRED) cred_handle = initiator_cred_handle; else cred_handle = _gss_mech_cred_find(initiator_cred_handle, mech_type); if (initiator_cred_handle != GSS_C_NO_CREDENTIAL && cred_handle == NULL) { if (allocated_ctx) free(ctx); return GSS_S_NO_CRED; } major_status = m->gm_init_sec_context(minor_status, cred_handle, &ctx->gc_ctx, mn->gmn_name, mech_type, req_flags, time_req, input_chan_bindings, input_token, actual_mech_type, output_token, ret_flags, time_rec); if (major_status != GSS_S_COMPLETE && major_status != GSS_S_CONTINUE_NEEDED) { if (allocated_ctx) free(ctx); _mg_buffer_zero(output_token); _gss_mg_error(m, major_status, *minor_status); } else { *context_handle = (gss_ctx_id_t) ctx; } return (major_status); } heimdal-7.5.0/lib/gssapi/mech/gss_pseudo_random.c0000644000175000017500000000466412136107747020123 0ustar niknik/* * Copyright (c) 2007 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ /* $Id$ */ #include "mech_locl.h" GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL gss_pseudo_random(OM_uint32 *minor_status, gss_ctx_id_t context, int prf_key, const gss_buffer_t prf_in, ssize_t desired_output_len, gss_buffer_t prf_out) { struct _gss_context *ctx = (struct _gss_context *) context; gssapi_mech_interface m; OM_uint32 major_status; _mg_buffer_zero(prf_out); *minor_status = 0; if (ctx == NULL) { *minor_status = 0; return GSS_S_NO_CONTEXT; } m = ctx->gc_mech; if (m->gm_pseudo_random == NULL) return GSS_S_UNAVAILABLE; major_status = (*m->gm_pseudo_random)(minor_status, ctx->gc_ctx, prf_key, prf_in, desired_output_len, prf_out); if (major_status != GSS_S_COMPLETE) _gss_mg_error(m, major_status, *minor_status); return major_status; } heimdal-7.5.0/lib/gssapi/mech/gss_process_context_token.c0000644000175000017500000000347113026237312021670 0ustar niknik/*- * Copyright (c) 2005 Doug Rabson * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * * $FreeBSD: src/lib/libgssapi/gss_process_context_token.c,v 1.1 2005/12/29 14:40:20 dfr Exp $ */ #include "mech_locl.h" GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL gss_process_context_token(OM_uint32 *minor_status, gss_const_ctx_id_t context_handle, const gss_buffer_t token_buffer) { struct _gss_context *ctx = (struct _gss_context *) context_handle; gssapi_mech_interface m = ctx->gc_mech; return (m->gm_process_context_token(minor_status, ctx->gc_ctx, token_buffer)); } heimdal-7.5.0/lib/gssapi/mech/cred.h0000644000175000017500000000436613026237312015320 0ustar niknik/*- * Copyright (c) 2005 Doug Rabson * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * * $FreeBSD: src/lib/libgssapi/cred.h,v 1.1 2005/12/29 14:40:20 dfr Exp $ * $Id$ */ struct _gss_mechanism_cred { HEIM_SLIST_ENTRY(_gss_mechanism_cred) gmc_link; gssapi_mech_interface gmc_mech; /* mechanism ops for MC */ gss_OID gmc_mech_oid; /* mechanism oid for MC */ gss_cred_id_t gmc_cred; /* underlying MC */ }; HEIM_SLIST_HEAD(_gss_mechanism_cred_list, _gss_mechanism_cred); struct _gss_cred { struct _gss_mechanism_cred_list gc_mc; }; struct _gss_mechanism_cred * _gss_copy_cred(struct _gss_mechanism_cred *mc); struct _gss_mechanism_name; OM_uint32 _gss_acquire_mech_cred(OM_uint32 *minor_status, gssapi_mech_interface m, const struct _gss_mechanism_name *mn, gss_const_OID credential_type, const void *credential_data, OM_uint32 time_req, gss_const_OID desired_mech, gss_cred_usage_t cred_usage, struct _gss_mechanism_cred **output_cred_handle); heimdal-7.5.0/lib/gssapi/mech/context.h0000644000175000017500000000323712136107747016074 0ustar niknik/*- * Copyright (c) 2005 Doug Rabson * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * * $FreeBSD: src/lib/libgssapi/context.h,v 1.1 2005/12/29 14:40:20 dfr Exp $ * $Id$ */ #include struct _gss_context { gssapi_mech_interface gc_mech; gss_ctx_id_t gc_ctx; }; void _gss_mg_error(gssapi_mech_interface, OM_uint32, OM_uint32); OM_uint32 _gss_mg_get_error(const gss_OID, OM_uint32, OM_uint32, gss_buffer_t); heimdal-7.5.0/lib/gssapi/mech/gss_add_cred.c0000644000175000017500000001271313026237312016772 0ustar niknik/*- * Copyright (c) 2005 Doug Rabson * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * * $FreeBSD: src/lib/libgssapi/gss_add_cred.c,v 1.1 2005/12/29 14:40:20 dfr Exp $ */ #include "mech_locl.h" struct _gss_mechanism_cred * _gss_copy_cred(struct _gss_mechanism_cred *mc) { struct _gss_mechanism_cred *new_mc; gssapi_mech_interface m = mc->gmc_mech; OM_uint32 major_status, minor_status; gss_name_t name; gss_cred_id_t cred; OM_uint32 initiator_lifetime, acceptor_lifetime; gss_cred_usage_t cred_usage; major_status = m->gm_inquire_cred_by_mech(&minor_status, mc->gmc_cred, mc->gmc_mech_oid, &name, &initiator_lifetime, &acceptor_lifetime, &cred_usage); if (major_status) { _gss_mg_error(m, major_status, minor_status); return (0); } major_status = m->gm_add_cred(&minor_status, GSS_C_NO_CREDENTIAL, name, mc->gmc_mech_oid, cred_usage, initiator_lifetime, acceptor_lifetime, &cred, 0, 0, 0); m->gm_release_name(&minor_status, &name); if (major_status) { _gss_mg_error(m, major_status, minor_status); return (0); } new_mc = malloc(sizeof(struct _gss_mechanism_cred)); if (!new_mc) { m->gm_release_cred(&minor_status, &cred); return (0); } new_mc->gmc_mech = m; new_mc->gmc_mech_oid = &m->gm_mech_oid; new_mc->gmc_cred = cred; return (new_mc); } GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL gss_add_cred(OM_uint32 *minor_status, gss_const_cred_id_t input_cred_handle, gss_const_name_t desired_name, const gss_OID desired_mech, gss_cred_usage_t cred_usage, OM_uint32 initiator_time_req, OM_uint32 acceptor_time_req, gss_cred_id_t *output_cred_handle, gss_OID_set *actual_mechs, OM_uint32 *initiator_time_rec, OM_uint32 *acceptor_time_rec) { OM_uint32 major_status; gssapi_mech_interface m; struct _gss_cred *cred = (struct _gss_cred *) input_cred_handle; struct _gss_cred *new_cred; gss_cred_id_t release_cred; struct _gss_mechanism_cred *mc, *target_mc, *copy_mc; struct _gss_mechanism_name *mn; OM_uint32 junk; *minor_status = 0; *output_cred_handle = GSS_C_NO_CREDENTIAL; if (initiator_time_rec) *initiator_time_rec = 0; if (acceptor_time_rec) *acceptor_time_rec = 0; if (actual_mechs) *actual_mechs = GSS_C_NO_OID_SET; new_cred = malloc(sizeof(struct _gss_cred)); if (!new_cred) { *minor_status = ENOMEM; return (GSS_S_FAILURE); } HEIM_SLIST_INIT(&new_cred->gc_mc); /* * We go through all the mc attached to the input_cred_handle * and check the mechanism. If it matches, we call * gss_add_cred for that mechanism, otherwise we copy the mc * to new_cred. */ target_mc = 0; if (cred) { HEIM_SLIST_FOREACH(mc, &cred->gc_mc, gmc_link) { if (gss_oid_equal(mc->gmc_mech_oid, desired_mech)) { target_mc = mc; } copy_mc = _gss_copy_cred(mc); if (!copy_mc) { release_cred = (gss_cred_id_t)new_cred; gss_release_cred(&junk, &release_cred); *minor_status = ENOMEM; return (GSS_S_FAILURE); } HEIM_SLIST_INSERT_HEAD(&new_cred->gc_mc, copy_mc, gmc_link); } } /* * Figure out a suitable mn, if any. */ if (desired_name) { major_status = _gss_find_mn(minor_status, (struct _gss_name *) desired_name, desired_mech, &mn); if (major_status != GSS_S_COMPLETE) { free(new_cred); return major_status; } } else { mn = 0; } m = __gss_get_mechanism(desired_mech); mc = malloc(sizeof(struct _gss_mechanism_cred)); if (!mc) { release_cred = (gss_cred_id_t)new_cred; gss_release_cred(&junk, &release_cred); *minor_status = ENOMEM; return (GSS_S_FAILURE); } mc->gmc_mech = m; mc->gmc_mech_oid = &m->gm_mech_oid; major_status = m->gm_add_cred(minor_status, target_mc ? target_mc->gmc_cred : GSS_C_NO_CREDENTIAL, desired_name ? mn->gmn_name : GSS_C_NO_NAME, desired_mech, cred_usage, initiator_time_req, acceptor_time_req, &mc->gmc_cred, actual_mechs, initiator_time_rec, acceptor_time_rec); if (major_status) { _gss_mg_error(m, major_status, *minor_status); release_cred = (gss_cred_id_t)new_cred; gss_release_cred(&junk, &release_cred); free(mc); return (major_status); } HEIM_SLIST_INSERT_HEAD(&new_cred->gc_mc, mc, gmc_link); *output_cred_handle = (gss_cred_id_t) new_cred; return (GSS_S_COMPLETE); } heimdal-7.5.0/lib/gssapi/mech/gss_authorize_localname.c0000644000175000017500000001374513026237312021300 0ustar niknik/* * Copyright (c) 2011, PADL Software Pty Ltd. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of PADL Software nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY PADL SOFTWARE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL PADL SOFTWARE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "mech_locl.h" gss_buffer_desc GSSAPI_LIB_VARIABLE __gss_c_attr_local_login_user = { sizeof("local-login-user") - 1, "local-login-user" }; static OM_uint32 mech_authorize_localname(OM_uint32 *minor_status, const struct _gss_name *name, const struct _gss_name *user) { OM_uint32 major_status = GSS_S_NAME_NOT_MN; struct _gss_mechanism_name *mn; HEIM_SLIST_FOREACH(mn, &name->gn_mn, gmn_link) { gssapi_mech_interface m = mn->gmn_mech; if (m->gm_authorize_localname == NULL) { major_status = GSS_S_UNAVAILABLE; continue; } major_status = m->gm_authorize_localname(minor_status, mn->gmn_name, &user->gn_value, &user->gn_type); if (major_status != GSS_S_UNAUTHORIZED) break; } return major_status; } /* * Naming extensions based local login authorization. */ static OM_uint32 attr_authorize_localname(OM_uint32 *minor_status, const struct _gss_name *name, const struct _gss_name *user) { OM_uint32 major_status = GSS_S_UNAVAILABLE; int more = -1; if (!gss_oid_equal(&user->gn_type, GSS_C_NT_USER_NAME)) return GSS_S_BAD_NAMETYPE; while (more != 0 && major_status != GSS_S_COMPLETE) { OM_uint32 tmpMajor, tmpMinor; gss_buffer_desc value; gss_buffer_desc display_value; int authenticated = 0, complete = 0; tmpMajor = gss_get_name_attribute(minor_status, (gss_name_t)name, GSS_C_ATTR_LOCAL_LOGIN_USER, &authenticated, &complete, &value, &display_value, &more); if (GSS_ERROR(tmpMajor)) { major_status = tmpMajor; break; } /* If attribute is present, return an authoritative error code. */ if (authenticated && value.length == user->gn_value.length && memcmp(value.value, user->gn_value.value, user->gn_value.length) == 0) major_status = GSS_S_COMPLETE; else major_status = GSS_S_UNAUTHORIZED; gss_release_buffer(&tmpMinor, &value); gss_release_buffer(&tmpMinor, &display_value); } return major_status; } GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL gss_authorize_localname(OM_uint32 *minor_status, gss_const_name_t gss_name, gss_const_name_t gss_user) { OM_uint32 major_status; const struct _gss_name *name = (const struct _gss_name *) gss_name; const struct _gss_name *user = (const struct _gss_name *) gss_user; int mechAvailable = 0; *minor_status = 0; if (gss_name == GSS_C_NO_NAME || gss_user == GSS_C_NO_NAME) return GSS_S_CALL_INACCESSIBLE_READ; /* * We should check that the user name is not a mechanism name, but * as Heimdal always calls the mechanism's gss_import_name(), it's * not possible to make this check. */ #if 0 if (HEIM_SLIST_FIRST(&user->gn_mn) != NULL) return GSS_S_BAD_NAME; #endif /* If mech returns yes, we return yes */ major_status = mech_authorize_localname(minor_status, name, user); if (major_status == GSS_S_COMPLETE) return GSS_S_COMPLETE; else if (major_status != GSS_S_UNAVAILABLE) mechAvailable = 1; /* If attribute exists, it is authoritative */ major_status = attr_authorize_localname(minor_status, name, user); if (major_status == GSS_S_COMPLETE || major_status == GSS_S_UNAUTHORIZED) return major_status; /* If mechanism did not implement SPI, compare the local name */ if (mechAvailable == 0) { int match = 0; major_status = gss_compare_name(minor_status, gss_name, gss_user, &match); if (major_status == GSS_S_COMPLETE && match == 0) major_status = GSS_S_UNAUTHORIZED; } return major_status; } GSSAPI_LIB_FUNCTION int GSSAPI_LIB_CALL gss_userok(gss_const_name_t name, const char *user) { OM_uint32 major_status, minor_status; gss_buffer_desc userBuf; gss_name_t userName; userBuf.value = (void *)user; userBuf.length = strlen(user); major_status = gss_import_name(&minor_status, &userBuf, GSS_C_NT_USER_NAME, &userName); if (GSS_ERROR(major_status)) return 0; major_status = gss_authorize_localname(&minor_status, name, userName); gss_release_name(&minor_status, &userName); return (major_status == GSS_S_COMPLETE); } heimdal-7.5.0/lib/gssapi/mech/gss_oid_to_str.c0000644000175000017500000000574613026237312017422 0ustar niknik/* * Copyright (c) 2006 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "mech_locl.h" GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL gss_oid_to_str(OM_uint32 *minor_status, gss_OID oid, gss_buffer_t oid_str) { int ret; size_t size; heim_oid o; char *p; _mg_buffer_zero(oid_str); if (oid == GSS_C_NULL_OID) return GSS_S_FAILURE; ret = der_get_oid (oid->elements, oid->length, &o, &size); if (ret) { *minor_status = ret; return GSS_S_FAILURE; } ret = der_print_heim_oid(&o, ' ', &p); der_free_oid(&o); if (ret) { *minor_status = ret; return GSS_S_FAILURE; } oid_str->value = p; oid_str->length = strlen(p); *minor_status = 0; return GSS_S_COMPLETE; } GSSAPI_LIB_FUNCTION const char * GSSAPI_LIB_CALL gss_oid_to_name(gss_const_OID oid) { size_t i; for (i = 0; _gss_ont_mech[i].oid; i++) { if (gss_oid_equal(oid, _gss_ont_mech[i].oid)) return _gss_ont_mech[i].name; } return NULL; } GSSAPI_LIB_FUNCTION gss_OID GSSAPI_LIB_CALL gss_name_to_oid(const char *name) { size_t i, partial = (size_t)-1; for (i = 0; _gss_ont_mech[i].oid; i++) { if (strcasecmp(name, _gss_ont_mech[i].short_desc) == 0) return _gss_ont_mech[i].oid; if (strncasecmp(name, _gss_ont_mech[i].short_desc, strlen(name)) == 0) { if (partial != (size_t)-1) return NULL; partial = i; } } if (partial != (size_t)-1) return _gss_ont_mech[partial].oid; return NULL; } heimdal-7.5.0/lib/gssapi/mech/gss_inquire_context.c0000644000175000017500000000622013026237312020461 0ustar niknik/*- * Copyright (c) 2005 Doug Rabson * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * * $FreeBSD: src/lib/libgssapi/gss_inquire_context.c,v 1.1 2005/12/29 14:40:20 dfr Exp $ */ #include "mech_locl.h" GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL gss_inquire_context(OM_uint32 *minor_status, gss_const_ctx_id_t context_handle, gss_name_t *src_name, gss_name_t *targ_name, OM_uint32 *lifetime_rec, gss_OID *mech_type, OM_uint32 *ctx_flags, int *locally_initiated, int *xopen) { OM_uint32 major_status; struct _gss_context *ctx = (struct _gss_context *) context_handle; gssapi_mech_interface m = ctx->gc_mech; struct _gss_name *name; gss_name_t src_mn, targ_mn; if (locally_initiated) *locally_initiated = 0; if (xopen) *xopen = 0; if (lifetime_rec) *lifetime_rec = 0; if (src_name) *src_name = GSS_C_NO_NAME; if (targ_name) *targ_name = GSS_C_NO_NAME; if (mech_type) *mech_type = GSS_C_NO_OID; src_mn = targ_mn = GSS_C_NO_NAME; major_status = m->gm_inquire_context(minor_status, ctx->gc_ctx, src_name ? &src_mn : NULL, targ_name ? &targ_mn : NULL, lifetime_rec, mech_type, ctx_flags, locally_initiated, xopen); if (major_status != GSS_S_COMPLETE) { _gss_mg_error(m, major_status, *minor_status); return (major_status); } if (src_name) { name = _gss_make_name(m, src_mn); if (!name) { if (mech_type) *mech_type = GSS_C_NO_OID; m->gm_release_name(minor_status, &src_mn); *minor_status = 0; return (GSS_S_FAILURE); } *src_name = (gss_name_t) name; } if (targ_name) { name = _gss_make_name(m, targ_mn); if (!name) { if (mech_type) *mech_type = GSS_C_NO_OID; if (src_name) gss_release_name(minor_status, src_name); m->gm_release_name(minor_status, &targ_mn); *minor_status = 0; return (GSS_S_FAILURE); } *targ_name = (gss_name_t) name; } return (GSS_S_COMPLETE); } heimdal-7.5.0/lib/gssapi/mech/gss_aeap.c0000644000175000017500000002212513026237312016151 0ustar niknik/* * AEAD support */ #include "mech_locl.h" /** * Encrypts or sign the data. * * This is a more complicated version of gss_wrap(), it allows the * caller to use AEAD data (signed header/trailer) and allow greater * controll over where the encrypted data is placed. * * The maximum packet size is gss_context_stream_sizes.max_msg_size. * * The caller needs provide the folloing buffers when using in conf_req_flag=1 mode: * * - HEADER (of size gss_context_stream_sizes.header) * { DATA or SIGN_ONLY } (optional, zero or more) * PADDING (of size gss_context_stream_sizes.blocksize, if zero padding is zero, can be omitted) * TRAILER (of size gss_context_stream_sizes.trailer) * * - on DCE-RPC mode, the caller can skip PADDING and TRAILER if the * DATA elements is padded to a block bountry and header is of at * least size gss_context_stream_sizes.header + gss_context_stream_sizes.trailer. * * HEADER, PADDING, TRAILER will be shrunken to the size required to transmit any of them too large. * * To generate gss_wrap() compatible packets, use: HEADER | DATA | PADDING | TRAILER * * When used in conf_req_flag=0, * * - HEADER (of size gss_context_stream_sizes.header) * { DATA or SIGN_ONLY } (optional, zero or more) * PADDING (of size gss_context_stream_sizes.blocksize, if zero padding is zero, can be omitted) * TRAILER (of size gss_context_stream_sizes.trailer) * * * The input sizes of HEADER, PADDING and TRAILER can be fetched using gss_wrap_iov_length() or * gss_context_query_attributes(). * * @ingroup gssapi */ GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL gss_wrap_iov(OM_uint32 * minor_status, gss_ctx_id_t context_handle, int conf_req_flag, gss_qop_t qop_req, int * conf_state, gss_iov_buffer_desc *iov, int iov_count) { struct _gss_context *ctx = (struct _gss_context *) context_handle; gssapi_mech_interface m; if (minor_status) *minor_status = 0; if (conf_state) *conf_state = 0; if (ctx == NULL) return GSS_S_NO_CONTEXT; if (iov == NULL && iov_count != 0) return GSS_S_CALL_INACCESSIBLE_READ; m = ctx->gc_mech; if (m->gm_wrap_iov == NULL) return GSS_S_UNAVAILABLE; return (m->gm_wrap_iov)(minor_status, ctx->gc_ctx, conf_req_flag, qop_req, conf_state, iov, iov_count); } /** * Decrypt or verifies the signature on the data. * * * @ingroup gssapi */ GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL gss_unwrap_iov(OM_uint32 *minor_status, gss_ctx_id_t context_handle, int *conf_state, gss_qop_t *qop_state, gss_iov_buffer_desc *iov, int iov_count) { struct _gss_context *ctx = (struct _gss_context *) context_handle; gssapi_mech_interface m; if (minor_status) *minor_status = 0; if (conf_state) *conf_state = 0; if (qop_state) *qop_state = 0; if (ctx == NULL) return GSS_S_NO_CONTEXT; if (iov == NULL && iov_count != 0) return GSS_S_CALL_INACCESSIBLE_READ; m = ctx->gc_mech; if (m->gm_unwrap_iov == NULL) return GSS_S_UNAVAILABLE; return (m->gm_unwrap_iov)(minor_status, ctx->gc_ctx, conf_state, qop_state, iov, iov_count); } /** * Update the length fields in iov buffer for the types: * - GSS_IOV_BUFFER_TYPE_HEADER * - GSS_IOV_BUFFER_TYPE_PADDING * - GSS_IOV_BUFFER_TYPE_TRAILER * * Consider using gss_context_query_attributes() to fetch the data instead. * * @ingroup gssapi */ GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL gss_wrap_iov_length(OM_uint32 * minor_status, gss_ctx_id_t context_handle, int conf_req_flag, gss_qop_t qop_req, int *conf_state, gss_iov_buffer_desc *iov, int iov_count) { struct _gss_context *ctx = (struct _gss_context *) context_handle; gssapi_mech_interface m; if (minor_status) *minor_status = 0; if (conf_state) *conf_state = 0; if (ctx == NULL) return GSS_S_NO_CONTEXT; if (iov == NULL && iov_count != 0) return GSS_S_CALL_INACCESSIBLE_READ; m = ctx->gc_mech; if (m->gm_wrap_iov_length == NULL) return GSS_S_UNAVAILABLE; return (m->gm_wrap_iov_length)(minor_status, ctx->gc_ctx, conf_req_flag, qop_req, conf_state, iov, iov_count); } /** * Free all buffer allocated by gss_wrap_iov() or gss_unwrap_iov() by * looking at the GSS_IOV_BUFFER_FLAG_ALLOCATED flag. * * @ingroup gssapi */ GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL gss_release_iov_buffer(OM_uint32 *minor_status, gss_iov_buffer_desc *iov, int iov_count) { OM_uint32 junk; int i; if (minor_status) *minor_status = 0; if (iov == NULL && iov_count != 0) return GSS_S_CALL_INACCESSIBLE_READ; for (i = 0; i < iov_count; i++) { if ((iov[i].type & GSS_IOV_BUFFER_FLAG_ALLOCATED) == 0) continue; gss_release_buffer(&junk, &iov[i].buffer); iov[i].type &= ~GSS_IOV_BUFFER_FLAG_ALLOCATED; } return GSS_S_COMPLETE; } /** * Query the context for parameters. * * SSPI equivalent if this function is QueryContextAttributes. * * - GSS_C_ATTR_STREAM_SIZES data is a gss_context_stream_sizes. * * @ingroup gssapi */ gss_OID_desc GSSAPI_LIB_FUNCTION __gss_c_attr_stream_sizes_oid_desc = {10, rk_UNCONST("\x2a\x86\x48\x86\xf7\x12\x01\x02\x01\x03")}; GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL gss_context_query_attributes(OM_uint32 *minor_status, gss_const_ctx_id_t context_handle, const gss_OID attribute, void *data, size_t len) { if (minor_status) *minor_status = 0; if (gss_oid_equal(GSS_C_ATTR_STREAM_SIZES, attribute)) { memset(data, 0, len); return GSS_S_COMPLETE; } return GSS_S_FAILURE; } /* * AEAD wrap API for a single piece of associated data, for compatibility * with MIT and as specified by draft-howard-gssapi-aead-00.txt. * * @ingroup gssapi */ GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL gss_wrap_aead(OM_uint32 *minor_status, gss_ctx_id_t context_handle, int conf_req_flag, gss_qop_t qop_req, gss_buffer_t input_assoc_buffer, gss_buffer_t input_payload_buffer, int *conf_state, gss_buffer_t output_message_buffer) { OM_uint32 major_status, tmp, flags = 0; gss_iov_buffer_desc iov[5]; size_t i; unsigned char *p; memset(iov, 0, sizeof(iov)); iov[0].type = GSS_IOV_BUFFER_TYPE_HEADER; iov[1].type = GSS_IOV_BUFFER_TYPE_SIGN_ONLY; if (input_assoc_buffer) iov[1].buffer = *input_assoc_buffer; iov[2].type = GSS_IOV_BUFFER_TYPE_DATA; if (input_payload_buffer) iov[2].buffer.length = input_payload_buffer->length; gss_inquire_context(minor_status, context_handle, NULL, NULL, NULL, NULL, &flags, NULL, NULL); /* krb5 mech rejects padding/trailer if DCE-style is set */ iov[3].type = (flags & GSS_C_DCE_STYLE) ? GSS_IOV_BUFFER_TYPE_EMPTY : GSS_IOV_BUFFER_TYPE_PADDING; iov[4].type = (flags & GSS_C_DCE_STYLE) ? GSS_IOV_BUFFER_TYPE_EMPTY : GSS_IOV_BUFFER_TYPE_TRAILER; major_status = gss_wrap_iov_length(minor_status, context_handle, conf_req_flag, qop_req, conf_state, iov, 5); if (GSS_ERROR(major_status)) return major_status; for (i = 0, output_message_buffer->length = 0; i < 5; i++) { if (GSS_IOV_BUFFER_TYPE(iov[i].type) == GSS_IOV_BUFFER_TYPE_SIGN_ONLY) continue; output_message_buffer->length += iov[i].buffer.length; } output_message_buffer->value = malloc(output_message_buffer->length); if (output_message_buffer->value == NULL) { *minor_status = ENOMEM; return GSS_S_FAILURE; } for (i = 0, p = output_message_buffer->value; i < 5; i++) { if (GSS_IOV_BUFFER_TYPE(iov[i].type) == GSS_IOV_BUFFER_TYPE_SIGN_ONLY) continue; else if (GSS_IOV_BUFFER_TYPE(iov[i].type) == GSS_IOV_BUFFER_TYPE_DATA) memcpy(p, input_payload_buffer->value, input_payload_buffer->length); iov[i].buffer.value = p; p += iov[i].buffer.length; } major_status = gss_wrap_iov(minor_status, context_handle, conf_req_flag, qop_req, conf_state, iov, 5); if (GSS_ERROR(major_status)) gss_release_buffer(&tmp, output_message_buffer); return major_status; } /* * AEAD unwrap for a single piece of associated data, for compatibility * with MIT and as specified by draft-howard-gssapi-aead-00.txt. * * @ingroup gssapi */ GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL gss_unwrap_aead(OM_uint32 *minor_status, gss_ctx_id_t context_handle, gss_buffer_t input_message_buffer, gss_buffer_t input_assoc_buffer, gss_buffer_t output_payload_buffer, int *conf_state, gss_qop_t *qop_state) { OM_uint32 major_status, tmp; gss_iov_buffer_desc iov[3]; memset(iov, 0, sizeof(iov)); iov[0].type = GSS_IOV_BUFFER_TYPE_STREAM; iov[0].buffer = *input_message_buffer; iov[1].type = GSS_IOV_BUFFER_TYPE_SIGN_ONLY; if (input_assoc_buffer) iov[1].buffer = *input_assoc_buffer; iov[2].type = GSS_IOV_BUFFER_TYPE_DATA | GSS_IOV_BUFFER_FLAG_ALLOCATE; major_status = gss_unwrap_iov(minor_status, context_handle, conf_state, qop_state, iov, 3); if (GSS_ERROR(major_status)) gss_release_iov_buffer(&tmp, &iov[2], 1); else *output_payload_buffer = iov[2].buffer; return major_status; } heimdal-7.5.0/lib/gssapi/mech/gss_inquire_cred_by_mech.c0000644000175000017500000000570713026237312021411 0ustar niknik/*- * Copyright (c) 2005 Doug Rabson * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * * $FreeBSD: src/lib/libgssapi/gss_inquire_cred_by_mech.c,v 1.1 2005/12/29 14:40:20 dfr Exp $ */ #include "mech_locl.h" GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL gss_inquire_cred_by_mech(OM_uint32 *minor_status, gss_const_cred_id_t cred_handle, const gss_OID mech_type, gss_name_t *cred_name, OM_uint32 *initiator_lifetime, OM_uint32 *acceptor_lifetime, gss_cred_usage_t *cred_usage) { OM_uint32 major_status; gssapi_mech_interface m; struct _gss_mechanism_cred *mcp; gss_cred_id_t mc; gss_name_t mn; struct _gss_name *name; *minor_status = 0; if (cred_name) *cred_name = GSS_C_NO_NAME; if (initiator_lifetime) *initiator_lifetime = 0; if (acceptor_lifetime) *acceptor_lifetime = 0; if (cred_usage) *cred_usage = 0; m = __gss_get_mechanism(mech_type); if (!m) return (GSS_S_NO_CRED); if (cred_handle != GSS_C_NO_CREDENTIAL) { struct _gss_cred *cred = (struct _gss_cred *) cred_handle; HEIM_SLIST_FOREACH(mcp, &cred->gc_mc, gmc_link) if (mcp->gmc_mech == m) break; if (!mcp) return (GSS_S_NO_CRED); mc = mcp->gmc_cred; } else { mc = GSS_C_NO_CREDENTIAL; } major_status = m->gm_inquire_cred_by_mech(minor_status, mc, mech_type, &mn, initiator_lifetime, acceptor_lifetime, cred_usage); if (major_status != GSS_S_COMPLETE) { _gss_mg_error(m, major_status, *minor_status); return (major_status); } if (cred_name) { name = _gss_make_name(m, mn); if (!name) { m->gm_release_name(minor_status, &mn); return (GSS_S_NO_CRED); } *cred_name = (gss_name_t) name; } else m->gm_release_name(minor_status, &mn); return (GSS_S_COMPLETE); } heimdal-7.5.0/lib/gssapi/mech/doxygen.c0000644000175000017500000001053713026237312016050 0ustar niknik/* * Copyright (c) 2009 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ /*! @mainpage Heimdal GSS-API Library * * Heimdal implements the following mechanisms: * * - Kerberos 5 * - SPNEGO * - NTLM * * @sa * * - @ref gssapi_services_intro * - @ref gssapi_mechs * - @ref gssapi_api_INvsMN * - The project web page: http://www.h5l.org/ */ /** * @page gssapi_services_intro Introduction to GSS-API services * @section gssapi_services GSS-API services * * @subsection gssapi_services_context Context creation * * - delegation * - mutual authentication * - anonymous * - use per message before context creation has completed * * return status: * - support conf * - support int * * @subsection gssapi_context_flags Context creation flags * * - GSS_C_DELEG_FLAG * - GSS_C_MUTUAL_FLAG * - GSS_C_REPLAY_FLAG * - GSS_C_SEQUENCE_FLAG * - GSS_C_CONF_FLAG * - GSS_C_INTEG_FLAG * - GSS_C_ANON_FLAG * - GSS_C_PROT_READY_FLAG * - GSS_C_TRANS_FLAG * - GSS_C_DCE_STYLE * - GSS_C_IDENTIFY_FLAG * - GSS_C_EXTENDED_ERROR_FLAG * - GSS_C_DELEG_POLICY_FLAG * * * @subsection gssapi_services_permessage Per-message services * * - conf * - int * - message integrity * - replay detection * - out of sequence * */ /** * @page gssapi_mechs_intro GSS-API mechanisms * @section gssapi_mechs GSS-API mechanisms * * - Kerberos 5 - GSS_KRB5_MECHANISM * - SPNEGO - GSS_SPNEGO_MECHANISM * - NTLM - GSS_NTLM_MECHANISM */ /** * @page internalVSmechname Internal names and mechanism names * @section gssapi_api_INvsMN Name forms * * There are two name representations in GSS-API: Internal form and * Contiguous string ("flat") form. Functions gss_export_name() and * gss_import_name() can be used to convert between the two forms. * * - The contiguous string form is described by an oid specificing the * type and an octet string. A special form of the contiguous * string form is the exported name object. The exported name * defined for each mechanism, is something that can be stored and * compared later. The exported name is what should be used for * ACLs comparisons. * * - The Internal form is opaque to the application programmer and * is implementation-dependent. * * - There is also a special form of the Internal Name (IN), and that is * the Mechanism Name (MN). In the mechanism name all the generic * information is stripped of and only contain the information for * one mechanism. In GSS-API some function return MN and some * require MN as input. Each of these function is marked up as such. * * @FIXME Describe relationship between import_name, canonicalize_name, * export_name and friends. Also, update for RFC2743 language * ("contiguous" and "flat" are gone, leaving just "exported name * token", "internal", and "MN"). */ /** @defgroup gssapi Heimdal GSS-API functions */ heimdal-7.5.0/lib/gssapi/mech/gss_import_sec_context.c0000644000175000017500000000527513026237312021162 0ustar niknik/*- * Copyright (c) 2005 Doug Rabson * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * * $FreeBSD: src/lib/libgssapi/gss_import_sec_context.c,v 1.1 2005/12/29 14:40:20 dfr Exp $ */ #include "mech_locl.h" GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL gss_import_sec_context(OM_uint32 *minor_status, const gss_buffer_t interprocess_token, gss_ctx_id_t *context_handle) { OM_uint32 major_status; gssapi_mech_interface m; struct _gss_context *ctx; gss_OID_desc mech_oid; gss_buffer_desc buf; unsigned char *p; size_t len; *minor_status = 0; *context_handle = GSS_C_NO_CONTEXT; /* * We added an oid to the front of the token in * gss_export_sec_context. */ p = interprocess_token->value; len = interprocess_token->length; if (len < 2) return (GSS_S_DEFECTIVE_TOKEN); mech_oid.length = (p[0] << 8) | p[1]; if (len < mech_oid.length + 2) return (GSS_S_DEFECTIVE_TOKEN); mech_oid.elements = p + 2; buf.length = len - 2 - mech_oid.length; buf.value = p + 2 + mech_oid.length; m = __gss_get_mechanism(&mech_oid); if (!m) return (GSS_S_DEFECTIVE_TOKEN); ctx = malloc(sizeof(struct _gss_context)); if (!ctx) { *minor_status = ENOMEM; return (GSS_S_FAILURE); } ctx->gc_mech = m; major_status = m->gm_import_sec_context(minor_status, &buf, &ctx->gc_ctx); if (major_status != GSS_S_COMPLETE) { _gss_mg_error(m, major_status, *minor_status); free(ctx); } else { *context_handle = (gss_ctx_id_t) ctx; } return (major_status); } heimdal-7.5.0/lib/gssapi/mech/gss_duplicate_name.c0000644000175000017500000000622113026237312020214 0ustar niknik/*- * Copyright (c) 2005 Doug Rabson * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * * $FreeBSD: src/lib/libgssapi/gss_duplicate_name.c,v 1.1 2005/12/29 14:40:20 dfr Exp $ */ #include "mech_locl.h" GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL gss_duplicate_name(OM_uint32 *minor_status, gss_const_name_t src_name, gss_name_t *dest_name) { OM_uint32 major_status; struct _gss_name *name = (struct _gss_name *) src_name; struct _gss_name *new_name; struct _gss_mechanism_name *mn; *minor_status = 0; *dest_name = GSS_C_NO_NAME; /* * If this name has a value (i.e. it didn't come from * gss_canonicalize_name(), we re-import the thing. Otherwise, * we make copy of each mech names. */ if (name->gn_value.value) { major_status = gss_import_name(minor_status, &name->gn_value, &name->gn_type, dest_name); if (major_status != GSS_S_COMPLETE) return (major_status); new_name = (struct _gss_name *) *dest_name; HEIM_SLIST_FOREACH(mn, &name->gn_mn, gmn_link) { struct _gss_mechanism_name *mn2; _gss_find_mn(minor_status, new_name, mn->gmn_mech_oid, &mn2); } } else { new_name = malloc(sizeof(struct _gss_name)); if (!new_name) { *minor_status = ENOMEM; return (GSS_S_FAILURE); } memset(new_name, 0, sizeof(struct _gss_name)); HEIM_SLIST_INIT(&new_name->gn_mn); *dest_name = (gss_name_t) new_name; HEIM_SLIST_FOREACH(mn, &name->gn_mn, gmn_link) { struct _gss_mechanism_name *new_mn; new_mn = malloc(sizeof(*new_mn)); if (!new_mn) { *minor_status = ENOMEM; return GSS_S_FAILURE; } new_mn->gmn_mech = mn->gmn_mech; new_mn->gmn_mech_oid = mn->gmn_mech_oid; major_status = mn->gmn_mech->gm_duplicate_name(minor_status, mn->gmn_name, &new_mn->gmn_name); if (major_status != GSS_S_COMPLETE) { free(new_mn); continue; } HEIM_SLIST_INSERT_HEAD(&new_name->gn_mn, new_mn, gmn_link); } } return (GSS_S_COMPLETE); } heimdal-7.5.0/lib/gssapi/mech/gss_add_oid_set_member.c0000644000175000017500000000561413026237312021034 0ustar niknik/* * Copyright (c) 1997 - 2001, 2003 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "mech_locl.h" /** * Add a oid to the oid set, function does not make a copy of the oid, * so the pointer to member_oid needs to be stable for the whole time * oid_set is used. * * If there is a duplicate member of the oid, the new member is not * added to to the set. * * @param minor_status minor status code. * @param member_oid member to add to the oid set * @param oid_set oid set to add the member too * * @returns a gss_error code, see gss_display_status() about printing * the error code. * * @ingroup gssapi */ GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL gss_add_oid_set_member (OM_uint32 * minor_status, const gss_OID member_oid, gss_OID_set * oid_set) { gss_OID tmp; size_t n; OM_uint32 res; int present; res = gss_test_oid_set_member(minor_status, member_oid, *oid_set, &present); if (res != GSS_S_COMPLETE) return res; if (present) { *minor_status = 0; return GSS_S_COMPLETE; } n = (*oid_set)->count + 1; tmp = realloc ((*oid_set)->elements, n * sizeof(gss_OID_desc)); if (tmp == NULL) { *minor_status = ENOMEM; return GSS_S_FAILURE; } (*oid_set)->elements = tmp; (*oid_set)->count = n; (*oid_set)->elements[n-1] = *member_oid; *minor_status = 0; return GSS_S_COMPLETE; } heimdal-7.5.0/lib/gssapi/mech/gss_display_name.c0000644000175000017500000000546313026237312017716 0ustar niknik/*- * Copyright (c) 2005 Doug Rabson * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * * $FreeBSD: src/lib/libgssapi/gss_display_name.c,v 1.1 2005/12/29 14:40:20 dfr Exp $ */ #include "mech_locl.h" GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL gss_display_name(OM_uint32 *minor_status, gss_const_name_t input_name, gss_buffer_t output_name_buffer, gss_OID *output_name_type) { OM_uint32 major_status; struct _gss_name *name = (struct _gss_name *) input_name; struct _gss_mechanism_name *mn; _mg_buffer_zero(output_name_buffer); if (output_name_type) *output_name_type = GSS_C_NO_OID; if (name == NULL) { *minor_status = 0; return (GSS_S_BAD_NAME); } /* * If we know it, copy the buffer used to import the name in * the first place. Otherwise, ask all the MNs in turn if * they can display the thing. */ if (name->gn_value.value) { output_name_buffer->value = malloc(name->gn_value.length); if (!output_name_buffer->value) { *minor_status = ENOMEM; return (GSS_S_FAILURE); } output_name_buffer->length = name->gn_value.length; memcpy(output_name_buffer->value, name->gn_value.value, output_name_buffer->length); if (output_name_type) *output_name_type = &name->gn_type; *minor_status = 0; return (GSS_S_COMPLETE); } else { HEIM_SLIST_FOREACH(mn, &name->gn_mn, gmn_link) { major_status = mn->gmn_mech->gm_display_name( minor_status, mn->gmn_name, output_name_buffer, output_name_type); if (major_status == GSS_S_COMPLETE) return (GSS_S_COMPLETE); } } *minor_status = 0; return (GSS_S_FAILURE); } heimdal-7.5.0/lib/gssapi/mech/gss_set_cred_option.c0000644000175000017500000000657313026237312020434 0ustar niknik/* * Copyright (c) 2004, PADL Software Pty Ltd. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of PADL Software nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY PADL SOFTWARE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL PADL SOFTWARE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "mech_locl.h" GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL gss_set_cred_option (OM_uint32 *minor_status, gss_cred_id_t *cred_handle, const gss_OID object, const gss_buffer_t value) { struct _gss_cred *cred = (struct _gss_cred *) *cred_handle; OM_uint32 major_status = GSS_S_COMPLETE; struct _gss_mechanism_cred *mc; int one_ok = 0; *minor_status = 0; _gss_load_mech(); if (cred == NULL) { struct _gss_mech_switch *m; cred = malloc(sizeof(*cred)); if (cred == NULL) return GSS_S_FAILURE; HEIM_SLIST_INIT(&cred->gc_mc); HEIM_SLIST_FOREACH(m, &_gss_mechs, gm_link) { if (m->gm_mech.gm_set_cred_option == NULL) continue; mc = malloc(sizeof(*mc)); if (mc == NULL) { *cred_handle = (gss_cred_id_t)cred; gss_release_cred(minor_status, cred_handle); *minor_status = ENOMEM; return GSS_S_FAILURE; } mc->gmc_mech = &m->gm_mech; mc->gmc_mech_oid = &m->gm_mech_oid; mc->gmc_cred = GSS_C_NO_CREDENTIAL; major_status = m->gm_mech.gm_set_cred_option( minor_status, &mc->gmc_cred, object, value); if (major_status) { free(mc); continue; } one_ok = 1; HEIM_SLIST_INSERT_HEAD(&cred->gc_mc, mc, gmc_link); } *cred_handle = (gss_cred_id_t)cred; if (!one_ok) { OM_uint32 junk; gss_release_cred(&junk, cred_handle); } } else { gssapi_mech_interface m; HEIM_SLIST_FOREACH(mc, &cred->gc_mc, gmc_link) { m = mc->gmc_mech; if (m == NULL) return GSS_S_BAD_MECH; if (m->gm_set_cred_option == NULL) continue; major_status = m->gm_set_cred_option(minor_status, &mc->gmc_cred, object, value); if (major_status == GSS_S_COMPLETE) one_ok = 1; else _gss_mg_error(m, major_status, *minor_status); } } if (one_ok) { *minor_status = 0; return GSS_S_COMPLETE; } return major_status; } heimdal-7.5.0/lib/gssapi/mech/gss_cred.c0000644000175000017500000001257013212137553016166 0ustar niknik/* * Copyright (c) 2009 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of KTH nor the names of its contributors may be * used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY KTH AND ITS CONTRIBUTORS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL KTH OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "mech_locl.h" #include /* * format: any number of: * mech-len: int32 * mech-data: char * (not alligned) * cred-len: int32 * cred-data char * (not alligned) */ GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL gss_export_cred(OM_uint32 * minor_status, gss_cred_id_t cred_handle, gss_buffer_t token) { struct _gss_cred *cred = (struct _gss_cred *)cred_handle; struct _gss_mechanism_cred *mc; gss_buffer_desc buffer; krb5_error_code ret; krb5_storage *sp; OM_uint32 major; krb5_data data; _mg_buffer_zero(token); if (cred == NULL) { *minor_status = 0; return GSS_S_NO_CRED; } HEIM_SLIST_FOREACH(mc, &cred->gc_mc, gmc_link) { if (mc->gmc_mech->gm_export_cred == NULL) { *minor_status = 0; return GSS_S_NO_CRED; } } sp = krb5_storage_emem(); if (sp == NULL) { *minor_status = ENOMEM; return GSS_S_FAILURE; } HEIM_SLIST_FOREACH(mc, &cred->gc_mc, gmc_link) { major = mc->gmc_mech->gm_export_cred(minor_status, mc->gmc_cred, &buffer); if (major) { krb5_storage_free(sp); return major; } ret = krb5_storage_write(sp, buffer.value, buffer.length); if (ret < 0 || (size_t)ret != buffer.length) { gss_release_buffer(minor_status, &buffer); krb5_storage_free(sp); *minor_status = EINVAL; return GSS_S_FAILURE; } gss_release_buffer(minor_status, &buffer); } ret = krb5_storage_to_data(sp, &data); krb5_storage_free(sp); if (ret) { *minor_status = ret; return GSS_S_FAILURE; } token->value = data.data; token->length = data.length; return GSS_S_COMPLETE; } GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL gss_import_cred(OM_uint32 * minor_status, gss_buffer_t token, gss_cred_id_t * cred_handle) { gssapi_mech_interface m; krb5_error_code ret; struct _gss_cred *cred; krb5_storage *sp = NULL; OM_uint32 major, junk; krb5_data data; *cred_handle = GSS_C_NO_CREDENTIAL; if (token->length == 0) { *minor_status = ENOMEM; return GSS_S_FAILURE; } sp = krb5_storage_from_readonly_mem(token->value, token->length); if (sp == NULL) { *minor_status = ENOMEM; return GSS_S_FAILURE; } cred = calloc(1, sizeof(struct _gss_cred)); if (cred == NULL) { krb5_storage_free(sp); *minor_status = ENOMEM; return GSS_S_FAILURE; } HEIM_SLIST_INIT(&cred->gc_mc); *cred_handle = (gss_cred_id_t)cred; while(1) { struct _gss_mechanism_cred *mc; gss_buffer_desc buffer; gss_cred_id_t mcred; gss_OID_desc oid; ret = krb5_ret_data(sp, &data); if (ret == HEIM_ERR_EOF) { break; } else if (ret) { *minor_status = ret; major = GSS_S_FAILURE; goto out; } oid.elements = data.data; oid.length = data.length; m = __gss_get_mechanism(&oid); krb5_data_free(&data); if (!m) { *minor_status = 0; major = GSS_S_BAD_MECH; goto out; } if (m->gm_import_cred == NULL) { *minor_status = 0; major = GSS_S_BAD_MECH; goto out; } ret = krb5_ret_data(sp, &data); if (ret) { *minor_status = ret; major = GSS_S_FAILURE; goto out; } buffer.value = data.data; buffer.length = data.length; major = m->gm_import_cred(minor_status, &buffer, &mcred); krb5_data_free(&data); if (major) { goto out; } mc = malloc(sizeof(struct _gss_mechanism_cred)); if (mc == NULL) { *minor_status = EINVAL; major = GSS_S_FAILURE; goto out; } mc->gmc_mech = m; mc->gmc_mech_oid = &m->gm_mech_oid; mc->gmc_cred = mcred; HEIM_SLIST_INSERT_HEAD(&cred->gc_mc, mc, gmc_link); } krb5_storage_free(sp); sp = NULL; if (HEIM_SLIST_EMPTY(&cred->gc_mc)) { major = GSS_S_NO_CRED; goto out; } return GSS_S_COMPLETE; out: if (sp) krb5_storage_free(sp); gss_release_cred(&junk, cred_handle); return major; } heimdal-7.5.0/lib/gssapi/mech/gss_verify_mic.c0000644000175000017500000000375413026237312017406 0ustar niknik/*- * Copyright (c) 2005 Doug Rabson * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * * $FreeBSD: src/lib/libgssapi/gss_verify_mic.c,v 1.1 2005/12/29 14:40:20 dfr Exp $ */ #include "mech_locl.h" GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL gss_verify_mic(OM_uint32 *minor_status, gss_const_ctx_id_t context_handle, const gss_buffer_t message_buffer, const gss_buffer_t token_buffer, gss_qop_t *qop_state) { struct _gss_context *ctx = (struct _gss_context *) context_handle; gssapi_mech_interface m; if (qop_state) *qop_state = 0; if (ctx == NULL) { *minor_status = 0; return GSS_S_NO_CONTEXT; } m = ctx->gc_mech; return (m->gm_verify_mic(minor_status, ctx->gc_ctx, message_buffer, token_buffer, qop_state)); } heimdal-7.5.0/lib/gssapi/mech/gss_inquire_cred.c0000644000175000017500000001227413026237312017720 0ustar niknik/*- * Copyright (c) 2005 Doug Rabson * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * * $FreeBSD: src/lib/libgssapi/gss_inquire_cred.c,v 1.1 2005/12/29 14:40:20 dfr Exp $ */ #include "mech_locl.h" #define AUSAGE 1 #define IUSAGE 2 static void updateusage(gss_cred_usage_t usage, int *usagemask) { if (usage == GSS_C_BOTH) *usagemask |= AUSAGE | IUSAGE; else if (usage == GSS_C_ACCEPT) *usagemask |= AUSAGE; else if (usage == GSS_C_INITIATE) *usagemask |= IUSAGE; } GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL gss_inquire_cred(OM_uint32 *minor_status, gss_const_cred_id_t cred_handle, gss_name_t *name_ret, OM_uint32 *lifetime, gss_cred_usage_t *cred_usage, gss_OID_set *mechanisms) { OM_uint32 major_status; struct _gss_mech_switch *m; struct _gss_cred *cred = (struct _gss_cred *) cred_handle; struct _gss_name *name; struct _gss_mechanism_name *mn; OM_uint32 min_lifetime; int found = 0; int usagemask = 0; gss_cred_usage_t usage; _gss_load_mech(); *minor_status = 0; if (name_ret) *name_ret = GSS_C_NO_NAME; if (lifetime) *lifetime = 0; if (cred_usage) *cred_usage = 0; if (mechanisms) *mechanisms = GSS_C_NO_OID_SET; if (name_ret) { name = calloc(1, sizeof(*name)); if (name == NULL) { *minor_status = ENOMEM; return (GSS_S_FAILURE); } HEIM_SLIST_INIT(&name->gn_mn); } else { name = NULL; } if (mechanisms) { major_status = gss_create_empty_oid_set(minor_status, mechanisms); if (major_status) { if (name) free(name); return (major_status); } } min_lifetime = GSS_C_INDEFINITE; if (cred) { struct _gss_mechanism_cred *mc; HEIM_SLIST_FOREACH(mc, &cred->gc_mc, gmc_link) { gss_name_t mc_name; OM_uint32 mc_lifetime; major_status = mc->gmc_mech->gm_inquire_cred(minor_status, mc->gmc_cred, &mc_name, &mc_lifetime, &usage, NULL); if (major_status) continue; updateusage(usage, &usagemask); if (name) { mn = malloc(sizeof(struct _gss_mechanism_name)); if (!mn) { mc->gmc_mech->gm_release_name(minor_status, &mc_name); continue; } mn->gmn_mech = mc->gmc_mech; mn->gmn_mech_oid = mc->gmc_mech_oid; mn->gmn_name = mc_name; HEIM_SLIST_INSERT_HEAD(&name->gn_mn, mn, gmn_link); } else { mc->gmc_mech->gm_release_name(minor_status, &mc_name); } if (mc_lifetime < min_lifetime) min_lifetime = mc_lifetime; if (mechanisms) gss_add_oid_set_member(minor_status, mc->gmc_mech_oid, mechanisms); found++; } } else { HEIM_SLIST_FOREACH(m, &_gss_mechs, gm_link) { gss_name_t mc_name; OM_uint32 mc_lifetime; major_status = m->gm_mech.gm_inquire_cred(minor_status, GSS_C_NO_CREDENTIAL, &mc_name, &mc_lifetime, &usage, NULL); if (major_status) continue; updateusage(usage, &usagemask); if (name && mc_name) { mn = malloc( sizeof(struct _gss_mechanism_name)); if (!mn) { m->gm_mech.gm_release_name( minor_status, &mc_name); continue; } mn->gmn_mech = &m->gm_mech; mn->gmn_mech_oid = &m->gm_mech_oid; mn->gmn_name = mc_name; HEIM_SLIST_INSERT_HEAD(&name->gn_mn, mn, gmn_link); } else if (mc_name) { m->gm_mech.gm_release_name(minor_status, &mc_name); } if (mc_lifetime < min_lifetime) min_lifetime = mc_lifetime; if (mechanisms) gss_add_oid_set_member(minor_status, &m->gm_mech_oid, mechanisms); found++; } } if (found == 0) { gss_name_t n = (gss_name_t)name; if (n) gss_release_name(minor_status, &n); gss_release_oid_set(minor_status, mechanisms); *minor_status = 0; return (GSS_S_NO_CRED); } *minor_status = 0; if (name_ret) *name_ret = (gss_name_t) name; if (lifetime) *lifetime = min_lifetime; if (cred_usage) { if ((usagemask & (AUSAGE|IUSAGE)) == (AUSAGE|IUSAGE)) *cred_usage = GSS_C_BOTH; else if (usagemask & IUSAGE) *cred_usage = GSS_C_INITIATE; else if (usagemask & AUSAGE) *cred_usage = GSS_C_ACCEPT; } return (GSS_S_COMPLETE); } heimdal-7.5.0/lib/gssapi/mech/gss_acquire_cred.c0000644000175000017500000001110413026237312017664 0ustar niknik/*- * Copyright (c) 2005 Doug Rabson * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * * $FreeBSD: src/lib/libgssapi/gss_acquire_cred.c,v 1.1 2005/12/29 14:40:20 dfr Exp $ */ #include "mech_locl.h" GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL gss_acquire_cred(OM_uint32 *minor_status, gss_const_name_t desired_name, OM_uint32 time_req, const gss_OID_set desired_mechs, gss_cred_usage_t cred_usage, gss_cred_id_t *output_cred_handle, gss_OID_set *actual_mechs, OM_uint32 *time_rec) { OM_uint32 major_status; gss_OID_set mechs = desired_mechs; gss_OID_set_desc set; struct _gss_name *name = (struct _gss_name *) desired_name; gssapi_mech_interface m; struct _gss_cred *cred; struct _gss_mechanism_cred *mc; OM_uint32 min_time, cred_time; size_t i; *minor_status = 0; if (output_cred_handle == NULL) return GSS_S_CALL_INACCESSIBLE_READ; if (actual_mechs) *actual_mechs = GSS_C_NO_OID_SET; if (time_rec) *time_rec = 0; _gss_load_mech(); /* * First make sure that at least one of the requested * mechanisms is one that we support. */ if (mechs) { for (i = 0; i < mechs->count; i++) { int t; gss_test_oid_set_member(minor_status, &mechs->elements[i], _gss_mech_oids, &t); if (t) break; } if (i == mechs->count) { *minor_status = 0; return (GSS_S_BAD_MECH); } } if (actual_mechs) { major_status = gss_create_empty_oid_set(minor_status, actual_mechs); if (major_status) return (major_status); } cred = malloc(sizeof(struct _gss_cred)); if (!cred) { if (actual_mechs) gss_release_oid_set(minor_status, actual_mechs); *minor_status = ENOMEM; return (GSS_S_FAILURE); } HEIM_SLIST_INIT(&cred->gc_mc); if (mechs == GSS_C_NO_OID_SET) mechs = _gss_mech_oids; set.count = 1; min_time = GSS_C_INDEFINITE; for (i = 0; i < mechs->count; i++) { struct _gss_mechanism_name *mn = NULL; m = __gss_get_mechanism(&mechs->elements[i]); if (!m) continue; if (desired_name != GSS_C_NO_NAME) { major_status = _gss_find_mn(minor_status, name, &mechs->elements[i], &mn); if (major_status != GSS_S_COMPLETE) continue; } mc = malloc(sizeof(struct _gss_mechanism_cred)); if (!mc) { continue; } mc->gmc_mech = m; mc->gmc_mech_oid = &m->gm_mech_oid; /* * XXX Probably need to do something with actual_mechs. */ set.elements = &mechs->elements[i]; major_status = m->gm_acquire_cred(minor_status, (desired_name != GSS_C_NO_NAME ? mn->gmn_name : GSS_C_NO_NAME), time_req, &set, cred_usage, &mc->gmc_cred, NULL, &cred_time); if (major_status) { free(mc); continue; } if (cred_time < min_time) min_time = cred_time; if (actual_mechs) { major_status = gss_add_oid_set_member(minor_status, mc->gmc_mech_oid, actual_mechs); if (major_status) { m->gm_release_cred(minor_status, &mc->gmc_cred); free(mc); continue; } } HEIM_SLIST_INSERT_HEAD(&cred->gc_mc, mc, gmc_link); } /* * If we didn't manage to create a single credential, return * an error. */ if (!HEIM_SLIST_FIRST(&cred->gc_mc)) { free(cred); if (actual_mechs) gss_release_oid_set(minor_status, actual_mechs); *minor_status = 0; return (GSS_S_NO_CRED); } if (time_rec) *time_rec = min_time; *output_cred_handle = (gss_cred_id_t) cred; *minor_status = 0; return (GSS_S_COMPLETE); } heimdal-7.5.0/lib/gssapi/mech/gss_inquire_names_for_mech.c0000644000175000017500000000506612136107747021762 0ustar niknik/*- * Copyright (c) 2005 Doug Rabson * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * * $FreeBSD: src/lib/libgssapi/gss_inquire_names_for_mech.c,v 1.1 2005/12/29 14:40:20 dfr Exp $ */ #include "mech_locl.h" GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL gss_inquire_names_for_mech(OM_uint32 *minor_status, const gss_OID mechanism, gss_OID_set *name_types) { OM_uint32 major_status; gssapi_mech_interface m = __gss_get_mechanism(mechanism); *minor_status = 0; *name_types = GSS_C_NO_OID_SET; if (!m) return (GSS_S_BAD_MECH); /* * If the implementation can do it, ask it for a list of * names, otherwise fake it. */ if (m->gm_inquire_names_for_mech) { return (m->gm_inquire_names_for_mech(minor_status, mechanism, name_types)); } else { major_status = gss_create_empty_oid_set(minor_status, name_types); if (major_status) return (major_status); major_status = gss_add_oid_set_member(minor_status, GSS_C_NT_HOSTBASED_SERVICE, name_types); if (major_status) { OM_uint32 junk; gss_release_oid_set(&junk, name_types); return (major_status); } major_status = gss_add_oid_set_member(minor_status, GSS_C_NT_USER_NAME, name_types); if (major_status) { OM_uint32 junk; gss_release_oid_set(&junk, name_types); return (major_status); } } return (GSS_S_COMPLETE); } heimdal-7.5.0/lib/gssapi/mech/gss_mech_switch.c0000644000175000017500000002473713026237312017553 0ustar niknik/*- * Copyright (c) 2005 Doug Rabson * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * * $FreeBSD: src/lib/libgssapi/gss_mech_switch.c,v 1.2 2006/02/04 09:40:21 dfr Exp $ */ #include "mech_locl.h" #include #ifndef _PATH_GSS_MECH #define _PATH_GSS_MECH "/etc/gss/mech" #endif struct _gss_mech_switch_list _gss_mechs = { NULL } ; gss_OID_set _gss_mech_oids; static HEIMDAL_MUTEX _gss_mech_mutex = HEIMDAL_MUTEX_INITIALIZER; /* * Convert a string containing an OID in 'dot' form * (e.g. 1.2.840.113554.1.2.2) to a gss_OID. */ static int _gss_string_to_oid(const char* s, gss_OID oid) { int number_count, i, j; size_t byte_count; const char *p, *q; char *res; oid->length = 0; oid->elements = NULL; /* * First figure out how many numbers in the oid, then * calculate the compiled oid size. */ number_count = 0; for (p = s; p; p = q) { q = strchr(p, '.'); if (q) q = q + 1; number_count++; } /* * The first two numbers are in the first byte and each * subsequent number is encoded in a variable byte sequence. */ if (number_count < 2) return (EINVAL); /* * We do this in two passes. The first pass, we just figure * out the size. Second time around, we actually encode the * number. */ res = 0; for (i = 0; i < 2; i++) { byte_count = 0; for (p = s, j = 0; p; p = q, j++) { unsigned int number = 0; /* * Find the end of this number. */ q = strchr(p, '.'); if (q) q = q + 1; /* * Read the number of of the string. Don't * bother with anything except base ten. */ while (*p && *p != '.') { number = 10 * number + (*p - '0'); p++; } /* * Encode the number. The first two numbers * are packed into the first byte. Subsequent * numbers are encoded in bytes seven bits at * a time with the last byte having the high * bit set. */ if (j == 0) { if (res) *res = number * 40; } else if (j == 1) { if (res) { *res += number; res++; } byte_count++; } else if (j >= 2) { /* * The number is encoded in seven bit chunks. */ unsigned int t; unsigned int bytes; bytes = 0; for (t = number; t; t >>= 7) bytes++; if (bytes == 0) bytes = 1; while (bytes) { if (res) { int bit = 7*(bytes-1); *res = (number >> bit) & 0x7f; if (bytes != 1) *res |= 0x80; res++; } byte_count++; bytes--; } } } if (!res) { res = malloc(byte_count); if (!res) return (ENOMEM); oid->length = byte_count; oid->elements = res; } } return (0); } #define SYM(name) \ do { \ m->gm_mech.gm_ ## name = dlsym(so, "gss_" #name); \ if (!m->gm_mech.gm_ ## name || \ m->gm_mech.gm_ ##name == gss_ ## name) { \ fprintf(stderr, "can't find symbol gss_" #name "\n"); \ goto bad; \ } \ } while (0) #define OPTSYM(name) \ do { \ m->gm_mech.gm_ ## name = dlsym(so, "gss_" #name); \ if (m->gm_mech.gm_ ## name == gss_ ## name) \ m->gm_mech.gm_ ## name = NULL; \ } while (0) #define OPTSPISYM(name) \ do { \ m->gm_mech.gm_ ## name = dlsym(so, "gssspi_" #name); \ } while (0) #define COMPATSYM(name) \ do { \ m->gm_mech.gm_compat->gmc_ ## name = dlsym(so, "gss_" #name); \ if (m->gm_mech.gm_compat->gmc_ ## name == gss_ ## name) \ m->gm_mech.gm_compat->gmc_ ## name = NULL; \ } while (0) #define COMPATSPISYM(name) \ do { \ m->gm_mech.gm_compat->gmc_ ## name = dlsym(so, "gssspi_" #name);\ if (m->gm_mech.gm_compat->gmc_ ## name == gss_ ## name) \ m->gm_mech.gm_compat->gmc_ ## name = NULL; \ } while (0) /* * */ static int add_builtin(gssapi_mech_interface mech) { struct _gss_mech_switch *m; OM_uint32 minor_status; /* not registering any mech is ok */ if (mech == NULL) return 0; m = calloc(1, sizeof(*m)); if (m == NULL) return ENOMEM; m->gm_so = NULL; m->gm_mech = *mech; m->gm_mech_oid = mech->gm_mech_oid; /* XXX */ gss_add_oid_set_member(&minor_status, &m->gm_mech.gm_mech_oid, &_gss_mech_oids); /* pick up the oid sets of names */ if (m->gm_mech.gm_inquire_names_for_mech) (*m->gm_mech.gm_inquire_names_for_mech)(&minor_status, &m->gm_mech.gm_mech_oid, &m->gm_name_types); if (m->gm_name_types == NULL) gss_create_empty_oid_set(&minor_status, &m->gm_name_types); HEIM_SLIST_INSERT_HEAD(&_gss_mechs, m, gm_link); return 0; } /* * Load the mechanisms file (/etc/gss/mech). */ void _gss_load_mech(void) { OM_uint32 major_status, minor_status; FILE *fp; char buf[256]; char *p; char *name, *oid, *lib, *kobj; struct _gss_mech_switch *m; void *so; gss_OID_desc mech_oid; int found; HEIMDAL_MUTEX_lock(&_gss_mech_mutex); if (HEIM_SLIST_FIRST(&_gss_mechs)) { HEIMDAL_MUTEX_unlock(&_gss_mech_mutex); return; } major_status = gss_create_empty_oid_set(&minor_status, &_gss_mech_oids); if (major_status) { HEIMDAL_MUTEX_unlock(&_gss_mech_mutex); return; } add_builtin(__gss_krb5_initialize()); add_builtin(__gss_spnego_initialize()); add_builtin(__gss_ntlm_initialize()); #ifdef HAVE_DLOPEN fp = fopen(_PATH_GSS_MECH, "r"); if (!fp) { HEIMDAL_MUTEX_unlock(&_gss_mech_mutex); return; } rk_cloexec_file(fp); while (fgets(buf, sizeof(buf), fp)) { _gss_mo_init *mi; if (*buf == '#') continue; p = buf; name = strsep(&p, "\t\n "); if (p) while (isspace((unsigned char)*p)) p++; oid = strsep(&p, "\t\n "); if (p) while (isspace((unsigned char)*p)) p++; lib = strsep(&p, "\t\n "); if (p) while (isspace((unsigned char)*p)) p++; kobj = strsep(&p, "\t\n "); if (!name || !oid || !lib || !kobj) continue; if (_gss_string_to_oid(oid, &mech_oid)) continue; /* * Check for duplicates, already loaded mechs. */ found = 0; HEIM_SLIST_FOREACH(m, &_gss_mechs, gm_link) { if (gss_oid_equal(&m->gm_mech.gm_mech_oid, &mech_oid)) { found = 1; free(mech_oid.elements); break; } } if (found) continue; #ifndef RTLD_LOCAL #define RTLD_LOCAL 0 #endif #ifndef RTLD_GROUP #define RTLD_GROUP 0 #endif so = dlopen(lib, RTLD_LAZY | RTLD_LOCAL | RTLD_GROUP); if (so == NULL) { /* fprintf(stderr, "dlopen: %s\n", dlerror()); */ goto bad; } m = calloc(1, sizeof(*m)); if (m == NULL) goto bad; m->gm_so = so; m->gm_mech_oid = mech_oid; m->gm_mech.gm_name = strdup(name); m->gm_mech.gm_mech_oid = mech_oid; m->gm_mech.gm_flags = 0; m->gm_mech.gm_compat = calloc(1, sizeof(struct gss_mech_compat_desc_struct)); if (m->gm_mech.gm_compat == NULL) goto bad; major_status = gss_add_oid_set_member(&minor_status, &m->gm_mech.gm_mech_oid, &_gss_mech_oids); if (GSS_ERROR(major_status)) goto bad; SYM(acquire_cred); SYM(release_cred); SYM(init_sec_context); SYM(accept_sec_context); SYM(process_context_token); SYM(delete_sec_context); SYM(context_time); SYM(get_mic); SYM(verify_mic); SYM(wrap); SYM(unwrap); SYM(display_status); SYM(indicate_mechs); SYM(compare_name); SYM(display_name); SYM(import_name); SYM(export_name); SYM(release_name); SYM(inquire_cred); SYM(inquire_context); SYM(wrap_size_limit); SYM(add_cred); SYM(inquire_cred_by_mech); SYM(export_sec_context); SYM(import_sec_context); SYM(inquire_names_for_mech); SYM(inquire_mechs_for_name); SYM(canonicalize_name); SYM(duplicate_name); OPTSYM(inquire_cred_by_oid); OPTSYM(inquire_sec_context_by_oid); OPTSYM(set_sec_context_option); OPTSPISYM(set_cred_option); OPTSYM(pseudo_random); OPTSYM(wrap_iov); OPTSYM(unwrap_iov); OPTSYM(wrap_iov_length); OPTSYM(store_cred); OPTSYM(export_cred); OPTSYM(import_cred); #if 0 OPTSYM(acquire_cred_ext); OPTSYM(iter_creds); OPTSYM(destroy_cred); OPTSYM(cred_hold); OPTSYM(cred_unhold); OPTSYM(cred_label_get); OPTSYM(cred_label_set); #endif OPTSYM(display_name_ext); OPTSYM(inquire_name); OPTSYM(get_name_attribute); OPTSYM(set_name_attribute); OPTSYM(delete_name_attribute); OPTSYM(export_name_composite); OPTSYM(localname); OPTSPISYM(authorize_localname); mi = dlsym(so, "gss_mo_init"); if (mi != NULL) { major_status = mi(&minor_status, &mech_oid, &m->gm_mech.gm_mo, &m->gm_mech.gm_mo_num); if (GSS_ERROR(major_status)) goto bad; } else { /* API-as-SPI compatibility */ COMPATSYM(inquire_saslname_for_mech); COMPATSYM(inquire_mech_for_saslname); COMPATSYM(inquire_attrs_for_mech); COMPATSPISYM(acquire_cred_with_password); } /* pick up the oid sets of names */ if (m->gm_mech.gm_inquire_names_for_mech) (*m->gm_mech.gm_inquire_names_for_mech)(&minor_status, &m->gm_mech.gm_mech_oid, &m->gm_name_types); if (m->gm_name_types == NULL) gss_create_empty_oid_set(&minor_status, &m->gm_name_types); HEIM_SLIST_INSERT_HEAD(&_gss_mechs, m, gm_link); continue; bad: if (m != NULL) { free(m->gm_mech.gm_compat); free(m->gm_mech.gm_mech_oid.elements); free((char *)m->gm_mech.gm_name); free(m); } dlclose(so); continue; } fclose(fp); #endif HEIMDAL_MUTEX_unlock(&_gss_mech_mutex); } gssapi_mech_interface __gss_get_mechanism(gss_const_OID mech) { struct _gss_mech_switch *m; _gss_load_mech(); HEIM_SLIST_FOREACH(m, &_gss_mechs, gm_link) { if (gss_oid_equal(&m->gm_mech.gm_mech_oid, mech)) return &m->gm_mech; } return NULL; } heimdal-7.5.0/lib/gssapi/mech/gss_pname_to_uid.c0000644000175000017500000001426513026237312017714 0ustar niknik/* * Copyright (c) 2011, PADL Software Pty Ltd. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of PADL Software nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY PADL SOFTWARE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL PADL SOFTWARE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "mech_locl.h" static OM_uint32 mech_localname(OM_uint32 *minor_status, struct _gss_mechanism_name *mn, gss_buffer_t localname) { OM_uint32 major_status = GSS_S_UNAVAILABLE; *minor_status = 0; if (mn->gmn_mech->gm_localname == NULL) return GSS_S_UNAVAILABLE; major_status = mn->gmn_mech->gm_localname(minor_status, mn->gmn_name, mn->gmn_mech_oid, localname); if (GSS_ERROR(major_status)) _gss_mg_error(mn->gmn_mech, major_status, *minor_status); return major_status; } static OM_uint32 attr_localname(OM_uint32 *minor_status, struct _gss_mechanism_name *mn, gss_buffer_t localname) { OM_uint32 major_status = GSS_S_UNAVAILABLE; OM_uint32 tmpMinor; gss_buffer_desc value = GSS_C_EMPTY_BUFFER; gss_buffer_desc display_value = GSS_C_EMPTY_BUFFER; int authenticated = 0, complete = 0; int more = -1; *minor_status = 0; localname->length = 0; localname->value = NULL; if (mn->gmn_mech->gm_get_name_attribute == NULL) return GSS_S_UNAVAILABLE; major_status = mn->gmn_mech->gm_get_name_attribute(minor_status, mn->gmn_name, GSS_C_ATTR_LOCAL_LOGIN_USER, &authenticated, &complete, &value, &display_value, &more); if (GSS_ERROR(major_status)) { _gss_mg_error(mn->gmn_mech, major_status, *minor_status); return major_status; } if (authenticated) { *localname = value; } else { major_status = GSS_S_UNAVAILABLE; gss_release_buffer(&tmpMinor, &value); } gss_release_buffer(&tmpMinor, &display_value); return major_status; } GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL gss_localname(OM_uint32 *minor_status, gss_const_name_t pname, const gss_OID mech_type, gss_buffer_t localname) { OM_uint32 major_status = GSS_S_UNAVAILABLE; struct _gss_name *name = (struct _gss_name *) pname; struct _gss_mechanism_name *mn = NULL; *minor_status = 0; if (mech_type != GSS_C_NO_OID) { major_status = _gss_find_mn(minor_status, name, mech_type, &mn); if (GSS_ERROR(major_status)) return major_status; major_status = mech_localname(minor_status, mn, localname); if (major_status != GSS_S_COMPLETE) major_status = attr_localname(minor_status, mn, localname); } else { HEIM_SLIST_FOREACH(mn, &name->gn_mn, gmn_link) { major_status = mech_localname(minor_status, mn, localname); if (major_status != GSS_S_COMPLETE) major_status = attr_localname(minor_status, mn, localname); if (major_status != GSS_S_UNAVAILABLE) break; } } if (major_status != GSS_S_COMPLETE && mn != NULL) _gss_mg_error(mn->gmn_mech, major_status, *minor_status); return major_status; } GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL gss_pname_to_uid(OM_uint32 *minor_status, gss_const_name_t pname, const gss_OID mech_type, uid_t *uidp) { #ifdef NO_LOCALNAME return GSS_S_UNAVAILABLE; #else OM_uint32 major, tmpMinor; gss_buffer_desc localname = GSS_C_EMPTY_BUFFER; char *szLocalname; #ifdef POSIX_GETPWNAM_R char pwbuf[2048]; struct passwd pw, *pwd; #else struct passwd *pwd; #endif major = gss_localname(minor_status, pname, mech_type, &localname); if (GSS_ERROR(major)) return major; szLocalname = malloc(localname.length + 1); if (szLocalname == NULL) { gss_release_buffer(&tmpMinor, &localname); *minor_status = ENOMEM; return GSS_S_FAILURE; } memcpy(szLocalname, localname.value, localname.length); szLocalname[localname.length] = '\0'; #ifdef POSIX_GETPWNAM_R if (getpwnam_r(szLocalname, &pw, pwbuf, sizeof(pwbuf), &pwd) != 0) pwd = NULL; #else pwd = getpwnam(szLocalname); #endif gss_release_buffer(&tmpMinor, &localname); free(szLocalname); *minor_status = 0; if (pwd != NULL) { *uidp = pwd->pw_uid; major = GSS_S_COMPLETE; } else { major = GSS_S_UNAVAILABLE; } return major; #endif } heimdal-7.5.0/lib/gssapi/mech/gss_unwrap.c0000644000175000017500000000364713026237312016567 0ustar niknik/*- * Copyright (c) 2005 Doug Rabson * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * * $FreeBSD: src/lib/libgssapi/gss_unwrap.c,v 1.1 2005/12/29 14:40:20 dfr Exp $ */ #include "mech_locl.h" GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL gss_unwrap(OM_uint32 *minor_status, gss_const_ctx_id_t context_handle, const gss_buffer_t input_message_buffer, gss_buffer_t output_message_buffer, int *conf_state, gss_qop_t *qop_state) { struct _gss_context *ctx = (struct _gss_context *) context_handle; gssapi_mech_interface m = ctx->gc_mech; return (m->gm_unwrap(minor_status, ctx->gc_ctx, input_message_buffer, output_message_buffer, conf_state, qop_state)); } heimdal-7.5.0/lib/gssapi/mech/name.h0000644000175000017500000000406713026237312015321 0ustar niknik/*- * Copyright (c) 2005 Doug Rabson * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * * $FreeBSD: src/lib/libgssapi/name.h,v 1.1 2005/12/29 14:40:20 dfr Exp $ * $Id$ */ struct _gss_mechanism_name { HEIM_SLIST_ENTRY(_gss_mechanism_name) gmn_link; gssapi_mech_interface gmn_mech; /* mechanism ops for MN */ gss_OID gmn_mech_oid; /* mechanism oid for MN */ gss_name_t gmn_name; /* underlying MN */ }; HEIM_SLIST_HEAD(_gss_mechanism_name_list, _gss_mechanism_name); struct _gss_name { gss_OID_desc gn_type; /* type of name */ gss_buffer_desc gn_value; /* value (as imported) */ struct _gss_mechanism_name_list gn_mn; /* list of MNs */ }; OM_uint32 _gss_find_mn(OM_uint32 *, struct _gss_name *, gss_OID, struct _gss_mechanism_name **); struct _gss_name * _gss_make_name(gssapi_mech_interface m, gss_name_t new_mn); heimdal-7.5.0/lib/gssapi/mech/gss_create_empty_oid_set.c0000644000175000017500000000350612136107747021445 0ustar niknik/*- * Copyright (c) 2005 Doug Rabson * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * * $FreeBSD: src/lib/libgssapi/gss_create_empty_oid_set.c,v 1.1 2005/12/29 14:40:20 dfr Exp $ */ #include "mech_locl.h" GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL gss_create_empty_oid_set(OM_uint32 *minor_status, gss_OID_set *oid_set) { gss_OID_set set; *minor_status = 0; *oid_set = GSS_C_NO_OID_SET; set = malloc(sizeof(gss_OID_set_desc)); if (!set) { *minor_status = ENOMEM; return (GSS_S_FAILURE); } set->count = 0; set->elements = 0; *oid_set = set; return (GSS_S_COMPLETE); } heimdal-7.5.0/lib/gssapi/mech/gss_export_sec_context.c0000644000175000017500000000551013026237312021161 0ustar niknik/*- * Copyright (c) 2005 Doug Rabson * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * * $FreeBSD: src/lib/libgssapi/gss_export_sec_context.c,v 1.1 2005/12/29 14:40:20 dfr Exp $ */ #include "mech_locl.h" GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL gss_export_sec_context(OM_uint32 *minor_status, gss_ctx_id_t *context_handle, gss_buffer_t interprocess_token) { OM_uint32 major_status; struct _gss_context *ctx = (struct _gss_context *) *context_handle; gssapi_mech_interface m = ctx->gc_mech; gss_buffer_desc buf; _mg_buffer_zero(interprocess_token); major_status = m->gm_export_sec_context(minor_status, &ctx->gc_ctx, &buf); if (major_status == GSS_S_COMPLETE) { unsigned char *p; free(ctx); *context_handle = GSS_C_NO_CONTEXT; interprocess_token->length = buf.length + 2 + m->gm_mech_oid.length; interprocess_token->value = malloc(interprocess_token->length); if (!interprocess_token->value) { /* * We are in trouble here - the context is * already gone. This is allowed as long as we * set the caller's context_handle to * GSS_C_NO_CONTEXT, which we did above. * Return GSS_S_FAILURE. */ _mg_buffer_zero(interprocess_token); *minor_status = ENOMEM; return (GSS_S_FAILURE); } p = interprocess_token->value; p[0] = m->gm_mech_oid.length >> 8; p[1] = m->gm_mech_oid.length; memcpy(p + 2, m->gm_mech_oid.elements, m->gm_mech_oid.length); memcpy(p + 2 + m->gm_mech_oid.length, buf.value, buf.length); gss_release_buffer(minor_status, &buf); } else { _gss_mg_error(m, major_status, *minor_status); } return (major_status); } heimdal-7.5.0/lib/gssapi/mech/gss_utils.c0000644000175000017500000000461612136107747016421 0ustar niknik/*- * Copyright (c) 2005 Doug Rabson * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * * $FreeBSD: src/lib/libgssapi/gss_utils.c,v 1.1 2005/12/29 14:40:20 dfr Exp $ */ #include "mech_locl.h" OM_uint32 _gss_copy_oid(OM_uint32 *minor_status, const gss_OID from_oid, gss_OID to_oid) { size_t len = from_oid->length; *minor_status = 0; to_oid->elements = malloc(len); if (!to_oid->elements) { to_oid->length = 0; *minor_status = ENOMEM; return GSS_S_FAILURE; } to_oid->length = len; memcpy(to_oid->elements, from_oid->elements, len); return (GSS_S_COMPLETE); } OM_uint32 _gss_free_oid(OM_uint32 *minor_status, gss_OID oid) { *minor_status = 0; if (oid->elements) { free(oid->elements); oid->elements = NULL; oid->length = 0; } return (GSS_S_COMPLETE); } OM_uint32 _gss_copy_buffer(OM_uint32 *minor_status, const gss_buffer_t from_buf, gss_buffer_t to_buf) { size_t len = from_buf->length; *minor_status = 0; to_buf->value = malloc(len); if (!to_buf->value) { *minor_status = ENOMEM; to_buf->length = 0; return GSS_S_FAILURE; } to_buf->length = len; memcpy(to_buf->value, from_buf->value, len); return (GSS_S_COMPLETE); } heimdal-7.5.0/lib/gssapi/mech/gss_mo.c0000644000175000017500000004357413026237312015671 0ustar niknik/* * Copyright (c) 2010 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Portions Copyright (c) 2010 Apple Inc. All rights reserved. * Portions Copyright (c) 2010 PADL Software Pty Ltd. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "mech_locl.h" #include static int get_option_def(int def, gss_const_OID mech, gss_mo_desc *mo, gss_buffer_t value) { return def; } int _gss_mo_get_option_1(gss_const_OID mech, gss_mo_desc *mo, gss_buffer_t value) { return get_option_def(1, mech, mo, value); } int _gss_mo_get_option_0(gss_const_OID mech, gss_mo_desc *mo, gss_buffer_t value) { return get_option_def(0, mech, mo, value); } int _gss_mo_get_ctx_as_string(gss_const_OID mech, gss_mo_desc *mo, gss_buffer_t value) { if (value) { value->value = strdup((char *)mo->ctx); if (value->value == NULL) return GSS_S_FAILURE; value->length = strlen((char *)mo->ctx); } return GSS_S_COMPLETE; } GSSAPI_LIB_FUNCTION int GSSAPI_LIB_CALL gss_mo_set(gss_const_OID mech, gss_const_OID option, int enable, gss_buffer_t value) { gssapi_mech_interface m; size_t n; if ((m = __gss_get_mechanism(mech)) == NULL) return GSS_S_BAD_MECH; for (n = 0; n < m->gm_mo_num; n++) if (gss_oid_equal(option, m->gm_mo[n].option) && m->gm_mo[n].set) return m->gm_mo[n].set(mech, &m->gm_mo[n], enable, value); return GSS_S_UNAVAILABLE; } GSSAPI_LIB_FUNCTION int GSSAPI_LIB_CALL gss_mo_get(gss_const_OID mech, gss_const_OID option, gss_buffer_t value) { gssapi_mech_interface m; size_t n; _mg_buffer_zero(value); if ((m = __gss_get_mechanism(mech)) == NULL) return GSS_S_BAD_MECH; for (n = 0; n < m->gm_mo_num; n++) if (gss_oid_equal(option, m->gm_mo[n].option) && m->gm_mo[n].get) return m->gm_mo[n].get(mech, &m->gm_mo[n], value); return GSS_S_UNAVAILABLE; } static void add_all_mo(gssapi_mech_interface m, gss_OID_set *options, OM_uint32 mask) { OM_uint32 minor; size_t n; for (n = 0; n < m->gm_mo_num; n++) if ((m->gm_mo[n].flags & mask) == mask) gss_add_oid_set_member(&minor, m->gm_mo[n].option, options); } GSSAPI_LIB_FUNCTION void GSSAPI_LIB_CALL gss_mo_list(gss_const_OID mech, gss_OID_set *options) { gssapi_mech_interface m; OM_uint32 major, minor; if (options == NULL) return; *options = GSS_C_NO_OID_SET; if ((m = __gss_get_mechanism(mech)) == NULL) return; major = gss_create_empty_oid_set(&minor, options); if (major != GSS_S_COMPLETE) return; add_all_mo(m, options, 0); } GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL gss_mo_name(gss_const_OID mech, gss_const_OID option, gss_buffer_t name) { gssapi_mech_interface m; size_t n; if (name == NULL) return GSS_S_BAD_NAME; if ((m = __gss_get_mechanism(mech)) == NULL) return GSS_S_BAD_MECH; for (n = 0; n < m->gm_mo_num; n++) { if (gss_oid_equal(option, m->gm_mo[n].option)) { /* * If there is no name, its because its a GSS_C_MA and * there is already a table for that. */ if (m->gm_mo[n].name) { name->value = strdup(m->gm_mo[n].name); if (name->value == NULL) return GSS_S_BAD_NAME; name->length = strlen(m->gm_mo[n].name); return GSS_S_COMPLETE; } else { OM_uint32 junk; return gss_display_mech_attr(&junk, option, NULL, name, NULL); } } } return GSS_S_BAD_NAME; } /* * Helper function to allow NULL name */ static OM_uint32 mo_value(const gss_const_OID mech, gss_const_OID option, gss_buffer_t name) { if (name == NULL) return GSS_S_COMPLETE; return gss_mo_get(mech, option, name); } /* code derived from draft-ietf-cat-sasl-gssapi-01 */ static char basis_32[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"; static OM_uint32 make_sasl_name(OM_uint32 *minor, const gss_OID mech, char sasl_name[16]) { EVP_MD_CTX *ctx; char *p = sasl_name; u_char hdr[2], hash[20], *h = hash; if (mech->length > 127) return GSS_S_BAD_MECH; hdr[0] = 0x06; hdr[1] = mech->length; ctx = EVP_MD_CTX_create(); EVP_DigestInit_ex(ctx, EVP_sha1(), NULL); EVP_DigestUpdate(ctx, hdr, 2); EVP_DigestUpdate(ctx, mech->elements, mech->length); EVP_DigestFinal_ex(ctx, hash, NULL); EVP_MD_CTX_destroy(ctx); memcpy(p, "GS2-", 4); p += 4; *p++ = basis_32[(h[0] >> 3)]; *p++ = basis_32[((h[0] & 7) << 2) | (h[1] >> 6)]; *p++ = basis_32[(h[1] & 0x3f) >> 1]; *p++ = basis_32[((h[1] & 1) << 4) | (h[2] >> 4)]; *p++ = basis_32[((h[2] & 0xf) << 1) | (h[3] >> 7)]; *p++ = basis_32[(h[3] & 0x7f) >> 2]; *p++ = basis_32[((h[3] & 3) << 3) | (h[4] >> 5)]; *p++ = basis_32[(h[4] & 0x1f)]; *p++ = basis_32[(h[5] >> 3)]; *p++ = basis_32[((h[5] & 7) << 2) | (h[6] >> 6)]; *p++ = basis_32[(h[6] & 0x3f) >> 1]; *p = '\0'; return GSS_S_COMPLETE; } /* * gss_inquire_saslname_for_mech() wrapper that uses MIT SPI */ static OM_uint32 inquire_saslname_for_mech_compat(OM_uint32 *minor, const gss_OID desired_mech, gss_buffer_t sasl_mech_name, gss_buffer_t mech_name, gss_buffer_t mech_description) { struct gss_mech_compat_desc_struct *gmc; gssapi_mech_interface m; OM_uint32 major; m = __gss_get_mechanism(desired_mech); if (m == NULL) return GSS_S_BAD_MECH; gmc = m->gm_compat; if (gmc != NULL && gmc->gmc_inquire_saslname_for_mech != NULL) { major = gmc->gmc_inquire_saslname_for_mech(minor, desired_mech, sasl_mech_name, mech_name, mech_description); } else { major = GSS_S_UNAVAILABLE; } return major; } /** * Returns different protocol names and description of the mechanism. * * @param minor_status minor status code * @param desired_mech mech list query * @param sasl_mech_name SASL GS2 protocol name * @param mech_name gssapi protocol name * @param mech_description description of gssapi mech * * @return returns GSS_S_COMPLETE or a error code. * * @ingroup gssapi */ GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL gss_inquire_saslname_for_mech(OM_uint32 *minor_status, const gss_OID desired_mech, gss_buffer_t sasl_mech_name, gss_buffer_t mech_name, gss_buffer_t mech_description) { OM_uint32 major; _mg_buffer_zero(sasl_mech_name); _mg_buffer_zero(mech_name); _mg_buffer_zero(mech_description); if (minor_status) *minor_status = 0; if (desired_mech == NULL) return GSS_S_BAD_MECH; major = mo_value(desired_mech, GSS_C_MA_SASL_MECH_NAME, sasl_mech_name); if (major == GSS_S_COMPLETE) { /* Native SPI */ major = mo_value(desired_mech, GSS_C_MA_MECH_NAME, mech_name); if (GSS_ERROR(major)) return major; major = mo_value(desired_mech, GSS_C_MA_MECH_DESCRIPTION, mech_description); if (GSS_ERROR(major)) return major; } if (GSS_ERROR(major)) { /* API-as-SPI compatibility */ major = inquire_saslname_for_mech_compat(minor_status, desired_mech, sasl_mech_name, mech_name, mech_description); } if (GSS_ERROR(major)) { /* Algorithmically dervied SASL mechanism name */ char buf[16]; gss_buffer_desc tmp = { sizeof(buf) - 1, buf }; major = make_sasl_name(minor_status, desired_mech, buf); if (GSS_ERROR(major)) return major; major = _gss_copy_buffer(minor_status, &tmp, sasl_mech_name); if (GSS_ERROR(major)) return major; } return major; } /** * Find a mech for a sasl name * * @param minor_status minor status code * @param sasl_mech_name * @param mech_type * * @return returns GSS_S_COMPLETE or an error code. */ GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL gss_inquire_mech_for_saslname(OM_uint32 *minor_status, const gss_buffer_t sasl_mech_name, gss_OID *mech_type) { struct _gss_mech_switch *m; gss_buffer_desc name; OM_uint32 major, junk; char buf[16]; _gss_load_mech(); *mech_type = NULL; HEIM_SLIST_FOREACH(m, &_gss_mechs, gm_link) { struct gss_mech_compat_desc_struct *gmc; /* Native SPI */ major = mo_value(&m->gm_mech_oid, GSS_C_MA_SASL_MECH_NAME, &name); if (major == GSS_S_COMPLETE && name.length == sasl_mech_name->length && memcmp(name.value, sasl_mech_name->value, name.length) == 0) { gss_release_buffer(&junk, &name); *mech_type = &m->gm_mech_oid; return GSS_S_COMPLETE; } gss_release_buffer(&junk, &name); if (GSS_ERROR(major)) { /* API-as-SPI compatibility */ gmc = m->gm_mech.gm_compat; if (gmc && gmc->gmc_inquire_mech_for_saslname) { major = gmc->gmc_inquire_mech_for_saslname(minor_status, sasl_mech_name, mech_type); if (major == GSS_S_COMPLETE) return GSS_S_COMPLETE; } } if (GSS_ERROR(major)) { /* Algorithmically dervied SASL mechanism name */ if (sasl_mech_name->length == 16 && make_sasl_name(minor_status, &m->gm_mech_oid, buf) == GSS_S_COMPLETE && memcmp(buf, sasl_mech_name->value, 16) == 0) { *mech_type = &m->gm_mech_oid; return GSS_S_COMPLETE; } } } return GSS_S_BAD_MECH; } /* * Test mechanism against indicated attributes using both Heimdal and * MIT SPIs. */ static int test_mech_attrs(gssapi_mech_interface mi, gss_const_OID_set mech_attrs, gss_const_OID_set against_attrs, int except) { size_t n, m; int eq = 0; if (against_attrs == GSS_C_NO_OID_SET) return 1; for (n = 0; n < against_attrs->count; n++) { for (m = 0; m < mi->gm_mo_num; m++) { eq = gss_oid_equal(mi->gm_mo[m].option, &against_attrs->elements[n]); if (eq) break; } if (mech_attrs != GSS_C_NO_OID_SET) { for (m = 0; m < mech_attrs->count; m++) { eq = gss_oid_equal(&mech_attrs->elements[m], &against_attrs->elements[n]); if (eq) break; } } if (!eq ^ except) return 0; } return 1; } /** * Return set of mechanism that fullfill the criteria * * @param minor_status minor status code * @param desired_mech_attrs * @param except_mech_attrs * @param critical_mech_attrs * @param mechs returned mechs, free with gss_release_oid_set(). * * @return returns GSS_S_COMPLETE or an error code. */ GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL gss_indicate_mechs_by_attrs(OM_uint32 * minor_status, gss_const_OID_set desired_mech_attrs, gss_const_OID_set except_mech_attrs, gss_const_OID_set critical_mech_attrs, gss_OID_set *mechs) { struct _gss_mech_switch *ms; gss_OID_set mech_attrs = GSS_C_NO_OID_SET; gss_OID_set known_mech_attrs = GSS_C_NO_OID_SET; OM_uint32 major; major = gss_create_empty_oid_set(minor_status, mechs); if (GSS_ERROR(major)) return major; _gss_load_mech(); HEIM_SLIST_FOREACH(ms, &_gss_mechs, gm_link) { gssapi_mech_interface mi = &ms->gm_mech; struct gss_mech_compat_desc_struct *gmc = mi->gm_compat; OM_uint32 tmp; if (gmc && gmc->gmc_inquire_attrs_for_mech) { major = gmc->gmc_inquire_attrs_for_mech(minor_status, &mi->gm_mech_oid, &mech_attrs, &known_mech_attrs); if (GSS_ERROR(major)) continue; } /* * Test mechanism supports all of desired_mech_attrs; * none of except_mech_attrs; * and knows of all critical_mech_attrs. */ if (test_mech_attrs(mi, mech_attrs, desired_mech_attrs, 0) && test_mech_attrs(mi, mech_attrs, except_mech_attrs, 1) && test_mech_attrs(mi, known_mech_attrs, critical_mech_attrs, 0)) { major = gss_add_oid_set_member(minor_status, &mi->gm_mech_oid, mechs); } gss_release_oid_set(&tmp, &mech_attrs); gss_release_oid_set(&tmp, &known_mech_attrs); if (GSS_ERROR(major)) break; } return major; } /** * List support attributes for a mech and/or all mechanisms. * * @param minor_status minor status code * @param mech given together with mech_attr will return the list of * attributes for mechanism, can optionally be GSS_C_NO_OID. * @param mech_attr see mech parameter, can optionally be NULL, * release with gss_release_oid_set(). * @param known_mech_attrs all attributes for mechanisms supported, * release with gss_release_oid_set(). * * @ingroup gssapi */ GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL gss_inquire_attrs_for_mech(OM_uint32 * minor_status, gss_const_OID mech, gss_OID_set *mech_attr, gss_OID_set *known_mech_attrs) { OM_uint32 major, junk; if (known_mech_attrs) *known_mech_attrs = GSS_C_NO_OID_SET; if (mech_attr && mech) { gssapi_mech_interface m; struct gss_mech_compat_desc_struct *gmc; if ((m = __gss_get_mechanism(mech)) == NULL) { *minor_status = 0; return GSS_S_BAD_MECH; } gmc = m->gm_compat; if (gmc && gmc->gmc_inquire_attrs_for_mech) { major = gmc->gmc_inquire_attrs_for_mech(minor_status, mech, mech_attr, known_mech_attrs); } else { major = gss_create_empty_oid_set(minor_status, mech_attr); if (major == GSS_S_COMPLETE) add_all_mo(m, mech_attr, GSS_MO_MA); } if (GSS_ERROR(major)) return major; } if (known_mech_attrs) { struct _gss_mech_switch *m; if (*known_mech_attrs == GSS_C_NO_OID_SET) { major = gss_create_empty_oid_set(minor_status, known_mech_attrs); if (GSS_ERROR(major)) { if (mech_attr) gss_release_oid_set(&junk, mech_attr); return major; } } _gss_load_mech(); HEIM_SLIST_FOREACH(m, &_gss_mechs, gm_link) add_all_mo(&m->gm_mech, known_mech_attrs, GSS_MO_MA); } return GSS_S_COMPLETE; } /** * Return names and descriptions of mech attributes * * @param minor_status minor status code * @param mech_attr * @param name * @param short_desc * @param long_desc * * @return returns GSS_S_COMPLETE or an error code. */ GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL gss_display_mech_attr(OM_uint32 * minor_status, gss_const_OID mech_attr, gss_buffer_t name, gss_buffer_t short_desc, gss_buffer_t long_desc) { struct _gss_oid_name_table *ma = NULL; OM_uint32 major; size_t n; _mg_buffer_zero(name); _mg_buffer_zero(short_desc); _mg_buffer_zero(long_desc); if (minor_status) *minor_status = 0; for (n = 0; ma == NULL && _gss_ont_ma[n].oid; n++) if (gss_oid_equal(mech_attr, _gss_ont_ma[n].oid)) ma = &_gss_ont_ma[n]; if (ma == NULL) return GSS_S_BAD_MECH_ATTR; if (name) { gss_buffer_desc bd; bd.value = rk_UNCONST(ma->name); bd.length = strlen(ma->name); major = _gss_copy_buffer(minor_status, &bd, name); if (major != GSS_S_COMPLETE) return major; } if (short_desc) { gss_buffer_desc bd; bd.value = rk_UNCONST(ma->short_desc); bd.length = strlen(ma->short_desc); major = _gss_copy_buffer(minor_status, &bd, short_desc); if (major != GSS_S_COMPLETE) return major; } if (long_desc) { gss_buffer_desc bd; bd.value = rk_UNCONST(ma->long_desc); bd.length = strlen(ma->long_desc); major = _gss_copy_buffer(minor_status, &bd, long_desc); if (major != GSS_S_COMPLETE) return major; } return GSS_S_COMPLETE; } heimdal-7.5.0/lib/gssapi/mech/utils.h0000644000175000017500000000317012136107747015544 0ustar niknik/*- * Copyright (c) 2005 Doug Rabson * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * * $FreeBSD: src/lib/libgssapi/utils.h,v 1.1 2005/12/29 14:40:20 dfr Exp $ * $Id$ */ OM_uint32 _gss_free_oid(OM_uint32 *, gss_OID); OM_uint32 _gss_copy_oid(OM_uint32 *, const gss_OID, gss_OID); OM_uint32 _gss_copy_buffer(OM_uint32 *minor_status, const gss_buffer_t from_buf, gss_buffer_t to_buf); heimdal-7.5.0/lib/gssapi/mech/gss_seal.c0000644000175000017500000000351212136107747016177 0ustar niknik/*- * Copyright (c) 2005 Doug Rabson * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * * $FreeBSD: src/lib/libgssapi/gss_seal.c,v 1.1 2005/12/29 14:40:20 dfr Exp $ */ #include "mech_locl.h" GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL gss_seal(OM_uint32 *minor_status, gss_ctx_id_t context_handle, int conf_req_flag, int qop_req, gss_buffer_t input_message_buffer, int *conf_state, gss_buffer_t output_message_buffer) { return (gss_wrap(minor_status, context_handle, conf_req_flag, qop_req, input_message_buffer, conf_state, output_message_buffer)); } heimdal-7.5.0/lib/gssapi/mech/gss_duplicate_oid.c0000644000175000017500000000457412136107747020071 0ustar niknik/* * Copyright (c) 1997 - 2003 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "mech_locl.h" GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL gss_duplicate_oid ( OM_uint32 *minor_status, gss_OID src_oid, gss_OID *dest_oid ) { *minor_status = 0; if (src_oid == GSS_C_NO_OID) { *dest_oid = GSS_C_NO_OID; return GSS_S_COMPLETE; } *dest_oid = malloc(sizeof(**dest_oid)); if (*dest_oid == GSS_C_NO_OID) { *minor_status = ENOMEM; return GSS_S_FAILURE; } (*dest_oid)->elements = malloc(src_oid->length); if ((*dest_oid)->elements == NULL) { free(*dest_oid); *dest_oid = GSS_C_NO_OID; *minor_status = ENOMEM; return GSS_S_FAILURE; } memcpy((*dest_oid)->elements, src_oid->elements, src_oid->length); (*dest_oid)->length = src_oid->length; *minor_status = 0; return GSS_S_COMPLETE; } heimdal-7.5.0/lib/gssapi/mech/gss_oid.c0000644000175000017500000003575113026237312016027 0ustar niknik/* Generated file */ #include "mech_locl.h" /* GSS_KRB5_COPY_CCACHE_X - 1.2.752.43.13.1 */ gss_OID_desc GSSAPI_LIB_VARIABLE __gss_krb5_copy_ccache_x_oid_desc = { 6, rk_UNCONST("\x2a\x85\x70\x2b\x0d\x01") }; /* GSS_KRB5_GET_TKT_FLAGS_X - 1.2.752.43.13.2 */ gss_OID_desc GSSAPI_LIB_VARIABLE __gss_krb5_get_tkt_flags_x_oid_desc = { 6, rk_UNCONST("\x2a\x85\x70\x2b\x0d\x02") }; /* GSS_KRB5_EXTRACT_AUTHZ_DATA_FROM_SEC_CONTEXT_X - 1.2.752.43.13.3 */ gss_OID_desc GSSAPI_LIB_VARIABLE __gss_krb5_extract_authz_data_from_sec_context_x_oid_desc = { 6, rk_UNCONST("\x2a\x85\x70\x2b\x0d\x03") }; /* GSS_KRB5_COMPAT_DES3_MIC_X - 1.2.752.43.13.4 */ gss_OID_desc GSSAPI_LIB_VARIABLE __gss_krb5_compat_des3_mic_x_oid_desc = { 6, rk_UNCONST("\x2a\x85\x70\x2b\x0d\x04") }; /* GSS_KRB5_REGISTER_ACCEPTOR_IDENTITY_X - 1.2.752.43.13.5 */ gss_OID_desc GSSAPI_LIB_VARIABLE __gss_krb5_register_acceptor_identity_x_oid_desc = { 6, rk_UNCONST("\x2a\x85\x70\x2b\x0d\x05") }; /* GSS_KRB5_EXPORT_LUCID_CONTEXT_X - 1.2.752.43.13.6 */ gss_OID_desc GSSAPI_LIB_VARIABLE __gss_krb5_export_lucid_context_x_oid_desc = { 6, rk_UNCONST("\x2a\x85\x70\x2b\x0d\x06") }; /* GSS_KRB5_EXPORT_LUCID_CONTEXT_V1_X - 1.2.752.43.13.6.1 */ gss_OID_desc GSSAPI_LIB_VARIABLE __gss_krb5_export_lucid_context_v1_x_oid_desc = { 7, rk_UNCONST("\x2a\x85\x70\x2b\x0d\x06\x01") }; /* GSS_KRB5_SET_DNS_CANONICALIZE_X - 1.2.752.43.13.7 */ gss_OID_desc GSSAPI_LIB_VARIABLE __gss_krb5_set_dns_canonicalize_x_oid_desc = { 6, rk_UNCONST("\x2a\x85\x70\x2b\x0d\x07") }; /* GSS_KRB5_GET_SUBKEY_X - 1.2.752.43.13.8 */ gss_OID_desc GSSAPI_LIB_VARIABLE __gss_krb5_get_subkey_x_oid_desc = { 6, rk_UNCONST("\x2a\x85\x70\x2b\x0d\x08") }; /* GSS_KRB5_GET_INITIATOR_SUBKEY_X - 1.2.752.43.13.9 */ gss_OID_desc GSSAPI_LIB_VARIABLE __gss_krb5_get_initiator_subkey_x_oid_desc = { 6, rk_UNCONST("\x2a\x85\x70\x2b\x0d\x09") }; /* GSS_KRB5_GET_ACCEPTOR_SUBKEY_X - 1.2.752.43.13.10 */ gss_OID_desc GSSAPI_LIB_VARIABLE __gss_krb5_get_acceptor_subkey_x_oid_desc = { 6, rk_UNCONST("\x2a\x85\x70\x2b\x0d\x0a") }; /* GSS_KRB5_SEND_TO_KDC_X - 1.2.752.43.13.11 */ gss_OID_desc GSSAPI_LIB_VARIABLE __gss_krb5_send_to_kdc_x_oid_desc = { 6, rk_UNCONST("\x2a\x85\x70\x2b\x0d\x0b") }; /* GSS_KRB5_GET_AUTHTIME_X - 1.2.752.43.13.12 */ gss_OID_desc GSSAPI_LIB_VARIABLE __gss_krb5_get_authtime_x_oid_desc = { 6, rk_UNCONST("\x2a\x85\x70\x2b\x0d\x0c") }; /* GSS_KRB5_GET_SERVICE_KEYBLOCK_X - 1.2.752.43.13.13 */ gss_OID_desc GSSAPI_LIB_VARIABLE __gss_krb5_get_service_keyblock_x_oid_desc = { 6, rk_UNCONST("\x2a\x85\x70\x2b\x0d\x0d") }; /* GSS_KRB5_SET_ALLOWABLE_ENCTYPES_X - 1.2.752.43.13.14 */ gss_OID_desc GSSAPI_LIB_VARIABLE __gss_krb5_set_allowable_enctypes_x_oid_desc = { 6, rk_UNCONST("\x2a\x85\x70\x2b\x0d\x0e") }; /* GSS_KRB5_SET_DEFAULT_REALM_X - 1.2.752.43.13.15 */ gss_OID_desc GSSAPI_LIB_VARIABLE __gss_krb5_set_default_realm_x_oid_desc = { 6, rk_UNCONST("\x2a\x85\x70\x2b\x0d\x0f") }; /* GSS_KRB5_CCACHE_NAME_X - 1.2.752.43.13.16 */ gss_OID_desc GSSAPI_LIB_VARIABLE __gss_krb5_ccache_name_x_oid_desc = { 6, rk_UNCONST("\x2a\x85\x70\x2b\x0d\x10") }; /* GSS_KRB5_SET_TIME_OFFSET_X - 1.2.752.43.13.17 */ gss_OID_desc GSSAPI_LIB_VARIABLE __gss_krb5_set_time_offset_x_oid_desc = { 6, rk_UNCONST("\x2a\x85\x70\x2b\x0d\x11") }; /* GSS_KRB5_GET_TIME_OFFSET_X - 1.2.752.43.13.18 */ gss_OID_desc GSSAPI_LIB_VARIABLE __gss_krb5_get_time_offset_x_oid_desc = { 6, rk_UNCONST("\x2a\x85\x70\x2b\x0d\x12") }; /* GSS_KRB5_PLUGIN_REGISTER_X - 1.2.752.43.13.19 */ gss_OID_desc GSSAPI_LIB_VARIABLE __gss_krb5_plugin_register_x_oid_desc = { 6, rk_UNCONST("\x2a\x85\x70\x2b\x0d\x13") }; /* GSS_NTLM_GET_SESSION_KEY_X - 1.2.752.43.13.20 */ gss_OID_desc GSSAPI_LIB_VARIABLE __gss_ntlm_get_session_key_x_oid_desc = { 6, rk_UNCONST("\x2a\x85\x70\x2b\x0d\x14") }; /* GSS_C_NT_NTLM - 1.2.752.43.13.21 */ gss_OID_desc GSSAPI_LIB_VARIABLE __gss_c_nt_ntlm_oid_desc = { 6, rk_UNCONST("\x2a\x85\x70\x2b\x0d\x15") }; /* GSS_C_NT_DN - 1.2.752.43.13.22 */ gss_OID_desc GSSAPI_LIB_VARIABLE __gss_c_nt_dn_oid_desc = { 6, rk_UNCONST("\x2a\x85\x70\x2b\x0d\x16") }; /* GSS_KRB5_NT_PRINCIPAL_NAME_REFERRAL - 1.2.752.43.13.23 */ gss_OID_desc GSSAPI_LIB_VARIABLE __gss_krb5_nt_principal_name_referral_oid_desc = { 6, rk_UNCONST("\x2a\x85\x70\x2b\x0d\x17") }; /* GSS_C_NTLM_AVGUEST - 1.2.752.43.13.24 */ gss_OID_desc GSSAPI_LIB_VARIABLE __gss_c_ntlm_avguest_oid_desc = { 6, rk_UNCONST("\x2a\x85\x70\x2b\x0d\x18") }; /* GSS_C_NTLM_V1 - 1.2.752.43.13.25 */ gss_OID_desc GSSAPI_LIB_VARIABLE __gss_c_ntlm_v1_oid_desc = { 6, rk_UNCONST("\x2a\x85\x70\x2b\x0d\x19") }; /* GSS_C_NTLM_V2 - 1.2.752.43.13.26 */ gss_OID_desc GSSAPI_LIB_VARIABLE __gss_c_ntlm_v2_oid_desc = { 6, rk_UNCONST("\x2a\x85\x70\x2b\x0d\x1a") }; /* GSS_C_NTLM_SESSION_KEY - 1.2.752.43.13.27 */ gss_OID_desc GSSAPI_LIB_VARIABLE __gss_c_ntlm_session_key_oid_desc = { 6, rk_UNCONST("\x2a\x85\x70\x2b\x0d\x1b") }; /* GSS_C_NTLM_FORCE_V1 - 1.2.752.43.13.28 */ gss_OID_desc GSSAPI_LIB_VARIABLE __gss_c_ntlm_force_v1_oid_desc = { 6, rk_UNCONST("\x2a\x85\x70\x2b\x0d\x1c") }; /* GSS_KRB5_CRED_NO_CI_FLAGS_X - 1.2.752.43.13.29 */ gss_OID_desc GSSAPI_LIB_VARIABLE __gss_krb5_cred_no_ci_flags_x_oid_desc = { 6, rk_UNCONST("\x2a\x85\x70\x2b\x0d\x1d") }; /* GSS_KRB5_IMPORT_CRED_X - 1.2.752.43.13.30 */ gss_OID_desc GSSAPI_LIB_VARIABLE __gss_krb5_import_cred_x_oid_desc = { 6, rk_UNCONST("\x2a\x85\x70\x2b\x0d\x1e") }; /* GSS_C_MA_SASL_MECH_NAME - 1.2.752.43.13.100 */ gss_OID_desc GSSAPI_LIB_VARIABLE __gss_c_ma_sasl_mech_name_oid_desc = { 6, rk_UNCONST("\x2a\x85\x70\x2b\x0d\x64") }; /* GSS_C_MA_MECH_NAME - 1.2.752.43.13.101 */ gss_OID_desc GSSAPI_LIB_VARIABLE __gss_c_ma_mech_name_oid_desc = { 6, rk_UNCONST("\x2a\x85\x70\x2b\x0d\x65") }; /* GSS_C_MA_MECH_DESCRIPTION - 1.2.752.43.13.102 */ gss_OID_desc GSSAPI_LIB_VARIABLE __gss_c_ma_mech_description_oid_desc = { 6, rk_UNCONST("\x2a\x85\x70\x2b\x0d\x66") }; /* GSS_C_CRED_PASSWORD - 1.2.752.43.13.200 */ gss_OID_desc GSSAPI_LIB_VARIABLE __gss_c_cred_password_oid_desc = { 7, rk_UNCONST("\x2a\x85\x70\x2b\x0d\x81\x48") }; /* GSS_C_CRED_CERTIFICATE - 1.2.752.43.13.201 */ gss_OID_desc GSSAPI_LIB_VARIABLE __gss_c_cred_certificate_oid_desc = { 7, rk_UNCONST("\x2a\x85\x70\x2b\x0d\x81\x49") }; /* GSS_SASL_DIGEST_MD5_MECHANISM - 1.2.752.43.14.1 */ gss_OID_desc GSSAPI_LIB_VARIABLE __gss_sasl_digest_md5_mechanism_oid_desc = { 6, rk_UNCONST("\x2a\x85\x70\x2b\x0e\x01") }; /* GSS_NETLOGON_MECHANISM - 1.2.752.43.14.2 */ gss_OID_desc GSSAPI_LIB_VARIABLE __gss_netlogon_mechanism_oid_desc = { 6, rk_UNCONST("\x2a\x85\x70\x2b\x0e\x02") }; /* GSS_NETLOGON_SET_SESSION_KEY_X - 1.2.752.43.14.3 */ gss_OID_desc GSSAPI_LIB_VARIABLE __gss_netlogon_set_session_key_x_oid_desc = { 6, rk_UNCONST("\x2a\x85\x70\x2b\x0e\x03") }; /* GSS_NETLOGON_SET_SIGN_ALGORITHM_X - 1.2.752.43.14.4 */ gss_OID_desc GSSAPI_LIB_VARIABLE __gss_netlogon_set_sign_algorithm_x_oid_desc = { 6, rk_UNCONST("\x2a\x85\x70\x2b\x0e\x04") }; /* GSS_NETLOGON_NT_NETBIOS_DNS_NAME - 1.2.752.43.14.5 */ gss_OID_desc GSSAPI_LIB_VARIABLE __gss_netlogon_nt_netbios_dns_name_oid_desc = { 6, rk_UNCONST("\x2a\x85\x70\x2b\x0e\x05") }; /* GSS_C_INQ_WIN2K_PAC_X - 1.2.752.43.13.3.128 */ gss_OID_desc GSSAPI_LIB_VARIABLE __gss_c_inq_win2k_pac_x_oid_desc = { 8, rk_UNCONST("\x2a\x85\x70\x2b\x0d\x03\x81\x00") }; /* GSS_C_INQ_SSPI_SESSION_KEY - 1.2.840.113554.1.2.2.5.5 */ gss_OID_desc GSSAPI_LIB_VARIABLE __gss_c_inq_sspi_session_key_oid_desc = { 11, rk_UNCONST("\x2a\x86\x48\x86\xf7\x12\x01\x02\x02\x05\x05") }; /* GSS_KRB5_MECHANISM - 1.2.840.113554.1.2.2 */ gss_OID_desc GSSAPI_LIB_VARIABLE __gss_krb5_mechanism_oid_desc = { 9, rk_UNCONST("\x2a\x86\x48\x86\xf7\x12\x01\x02\x02") }; /* GSS_NTLM_MECHANISM - 1.3.6.1.4.1.311.2.2.10 */ gss_OID_desc GSSAPI_LIB_VARIABLE __gss_ntlm_mechanism_oid_desc = { 10, rk_UNCONST("\x2b\x06\x01\x04\x01\x82\x37\x02\x02\x0a") }; /* GSS_SPNEGO_MECHANISM - 1.3.6.1.5.5.2 */ gss_OID_desc GSSAPI_LIB_VARIABLE __gss_spnego_mechanism_oid_desc = { 6, rk_UNCONST("\x2b\x06\x01\x05\x05\x02") }; /* GSS_C_PEER_HAS_UPDATED_SPNEGO - 1.3.6.1.4.1.5322.19.5 */ gss_OID_desc GSSAPI_LIB_VARIABLE __gss_c_peer_has_updated_spnego_oid_desc = { 9, rk_UNCONST("\x2b\x06\x01\x04\x01\xa9\x4a\x13\x05") }; /* GSS_C_MA_MECH_CONCRETE - 1.3.6.1.5.5.13.1 */ gss_OID_desc GSSAPI_LIB_VARIABLE __gss_c_ma_mech_concrete_oid_desc = { 7, rk_UNCONST("\x2b\x06\x01\x05\x05\x0d\x01") }; /* GSS_C_MA_MECH_PSEUDO - 1.3.6.1.5.5.13.2 */ gss_OID_desc GSSAPI_LIB_VARIABLE __gss_c_ma_mech_pseudo_oid_desc = { 7, rk_UNCONST("\x2b\x06\x01\x05\x05\x0d\x02") }; /* GSS_C_MA_MECH_COMPOSITE - 1.3.6.1.5.5.13.3 */ gss_OID_desc GSSAPI_LIB_VARIABLE __gss_c_ma_mech_composite_oid_desc = { 7, rk_UNCONST("\x2b\x06\x01\x05\x05\x0d\x03") }; /* GSS_C_MA_MECH_NEGO - 1.3.6.1.5.5.13.4 */ gss_OID_desc GSSAPI_LIB_VARIABLE __gss_c_ma_mech_nego_oid_desc = { 7, rk_UNCONST("\x2b\x06\x01\x05\x05\x0d\x04") }; /* GSS_C_MA_MECH_GLUE - 1.3.6.1.5.5.13.5 */ gss_OID_desc GSSAPI_LIB_VARIABLE __gss_c_ma_mech_glue_oid_desc = { 7, rk_UNCONST("\x2b\x06\x01\x05\x05\x0d\x05") }; /* GSS_C_MA_NOT_MECH - 1.3.6.1.5.5.13.6 */ gss_OID_desc GSSAPI_LIB_VARIABLE __gss_c_ma_not_mech_oid_desc = { 7, rk_UNCONST("\x2b\x06\x01\x05\x05\x0d\x06") }; /* GSS_C_MA_DEPRECATED - 1.3.6.1.5.5.13.7 */ gss_OID_desc GSSAPI_LIB_VARIABLE __gss_c_ma_deprecated_oid_desc = { 7, rk_UNCONST("\x2b\x06\x01\x05\x05\x0d\x07") }; /* GSS_C_MA_NOT_DFLT_MECH - 1.3.6.1.5.5.13.8 */ gss_OID_desc GSSAPI_LIB_VARIABLE __gss_c_ma_not_dflt_mech_oid_desc = { 7, rk_UNCONST("\x2b\x06\x01\x05\x05\x0d\x08") }; /* GSS_C_MA_ITOK_FRAMED - 1.3.6.1.5.5.13.9 */ gss_OID_desc GSSAPI_LIB_VARIABLE __gss_c_ma_itok_framed_oid_desc = { 7, rk_UNCONST("\x2b\x06\x01\x05\x05\x0d\x09") }; /* GSS_C_MA_AUTH_INIT - 1.3.6.1.5.5.13.10 */ gss_OID_desc GSSAPI_LIB_VARIABLE __gss_c_ma_auth_init_oid_desc = { 7, rk_UNCONST("\x2b\x06\x01\x05\x05\x0d\x0a") }; /* GSS_C_MA_AUTH_TARG - 1.3.6.1.5.5.13.11 */ gss_OID_desc GSSAPI_LIB_VARIABLE __gss_c_ma_auth_targ_oid_desc = { 7, rk_UNCONST("\x2b\x06\x01\x05\x05\x0d\x0b") }; /* GSS_C_MA_AUTH_INIT_INIT - 1.3.6.1.5.5.13.12 */ gss_OID_desc GSSAPI_LIB_VARIABLE __gss_c_ma_auth_init_init_oid_desc = { 7, rk_UNCONST("\x2b\x06\x01\x05\x05\x0d\x0c") }; /* GSS_C_MA_AUTH_TARG_INIT - 1.3.6.1.5.5.13.13 */ gss_OID_desc GSSAPI_LIB_VARIABLE __gss_c_ma_auth_targ_init_oid_desc = { 7, rk_UNCONST("\x2b\x06\x01\x05\x05\x0d\x0d") }; /* GSS_C_MA_AUTH_INIT_ANON - 1.3.6.1.5.5.13.14 */ gss_OID_desc GSSAPI_LIB_VARIABLE __gss_c_ma_auth_init_anon_oid_desc = { 7, rk_UNCONST("\x2b\x06\x01\x05\x05\x0d\x0e") }; /* GSS_C_MA_AUTH_TARG_ANON - 1.3.6.1.5.5.13.15 */ gss_OID_desc GSSAPI_LIB_VARIABLE __gss_c_ma_auth_targ_anon_oid_desc = { 7, rk_UNCONST("\x2b\x06\x01\x05\x05\x0d\x0f") }; /* GSS_C_MA_DELEG_CRED - 1.3.6.1.5.5.13.16 */ gss_OID_desc GSSAPI_LIB_VARIABLE __gss_c_ma_deleg_cred_oid_desc = { 7, rk_UNCONST("\x2b\x06\x01\x05\x05\x0d\x10") }; /* GSS_C_MA_INTEG_PROT - 1.3.6.1.5.5.13.17 */ gss_OID_desc GSSAPI_LIB_VARIABLE __gss_c_ma_integ_prot_oid_desc = { 7, rk_UNCONST("\x2b\x06\x01\x05\x05\x0d\x11") }; /* GSS_C_MA_CONF_PROT - 1.3.6.1.5.5.13.18 */ gss_OID_desc GSSAPI_LIB_VARIABLE __gss_c_ma_conf_prot_oid_desc = { 7, rk_UNCONST("\x2b\x06\x01\x05\x05\x0d\x12") }; /* GSS_C_MA_MIC - 1.3.6.1.5.5.13.19 */ gss_OID_desc GSSAPI_LIB_VARIABLE __gss_c_ma_mic_oid_desc = { 7, rk_UNCONST("\x2b\x06\x01\x05\x05\x0d\x13") }; /* GSS_C_MA_WRAP - 1.3.6.1.5.5.13.20 */ gss_OID_desc GSSAPI_LIB_VARIABLE __gss_c_ma_wrap_oid_desc = { 7, rk_UNCONST("\x2b\x06\x01\x05\x05\x0d\x14") }; /* GSS_C_MA_PROT_READY - 1.3.6.1.5.5.13.21 */ gss_OID_desc GSSAPI_LIB_VARIABLE __gss_c_ma_prot_ready_oid_desc = { 7, rk_UNCONST("\x2b\x06\x01\x05\x05\x0d\x15") }; /* GSS_C_MA_REPLAY_DET - 1.3.6.1.5.5.13.22 */ gss_OID_desc GSSAPI_LIB_VARIABLE __gss_c_ma_replay_det_oid_desc = { 7, rk_UNCONST("\x2b\x06\x01\x05\x05\x0d\x16") }; /* GSS_C_MA_OOS_DET - 1.3.6.1.5.5.13.23 */ gss_OID_desc GSSAPI_LIB_VARIABLE __gss_c_ma_oos_det_oid_desc = { 7, rk_UNCONST("\x2b\x06\x01\x05\x05\x0d\x17") }; /* GSS_C_MA_CBINDINGS - 1.3.6.1.5.5.13.24 */ gss_OID_desc GSSAPI_LIB_VARIABLE __gss_c_ma_cbindings_oid_desc = { 7, rk_UNCONST("\x2b\x06\x01\x05\x05\x0d\x18") }; /* GSS_C_MA_PFS - 1.3.6.1.5.5.13.25 */ gss_OID_desc GSSAPI_LIB_VARIABLE __gss_c_ma_pfs_oid_desc = { 7, rk_UNCONST("\x2b\x06\x01\x05\x05\x0d\x19") }; /* GSS_C_MA_COMPRESS - 1.3.6.1.5.5.13.26 */ gss_OID_desc GSSAPI_LIB_VARIABLE __gss_c_ma_compress_oid_desc = { 7, rk_UNCONST("\x2b\x06\x01\x05\x05\x0d\x1a") }; /* GSS_C_MA_CTX_TRANS - 1.3.6.1.5.5.13.27 */ gss_OID_desc GSSAPI_LIB_VARIABLE __gss_c_ma_ctx_trans_oid_desc = { 7, rk_UNCONST("\x2b\x06\x01\x05\x05\x0d\x1b") }; struct _gss_oid_name_table _gss_ont_ma[] = { { GSS_C_MA_AUTH_INIT, "GSS_C_MA_AUTH_INIT", "auth-init-princ", "" }, { GSS_C_MA_AUTH_INIT_ANON, "GSS_C_MA_AUTH_INIT_ANON", "auth-init-princ-anon", "" }, { GSS_C_MA_AUTH_INIT_INIT, "GSS_C_MA_AUTH_INIT_INIT", "auth-init-princ-initial", "" }, { GSS_C_MA_AUTH_TARG, "GSS_C_MA_AUTH_TARG", "auth-targ-princ", "" }, { GSS_C_MA_AUTH_TARG_ANON, "GSS_C_MA_AUTH_TARG_ANON", "auth-targ-princ-anon", "" }, { GSS_C_MA_AUTH_TARG_INIT, "GSS_C_MA_AUTH_TARG_INIT", "auth-targ-princ-initial", "" }, { GSS_C_MA_CBINDINGS, "GSS_C_MA_CBINDINGS", "channel-bindings", "" }, { GSS_C_MA_COMPRESS, "GSS_C_MA_COMPRESS", "compress", "" }, { GSS_C_MA_CONF_PROT, "GSS_C_MA_CONF_PROT", "conf-prot", "" }, { GSS_C_MA_CTX_TRANS, "GSS_C_MA_CTX_TRANS", "context-transfer", "" }, { GSS_C_MA_DELEG_CRED, "GSS_C_MA_DELEG_CRED", "deleg-cred", "" }, { GSS_C_MA_DEPRECATED, "GSS_C_MA_DEPRECATED", "mech-deprecated", "" }, { GSS_C_MA_INTEG_PROT, "GSS_C_MA_INTEG_PROT", "integ-prot", "" }, { GSS_C_MA_ITOK_FRAMED, "GSS_C_MA_ITOK_FRAMED", "initial-is-framed", "" }, { GSS_C_MA_MECH_COMPOSITE, "GSS_C_MA_MECH_COMPOSITE", "composite-mech", "" }, { GSS_C_MA_MECH_CONCRETE, "GSS_C_MA_MECH_CONCRETE", "concrete-mech", "Indicates that a mech is neither a pseudo-mechanism nor a composite mechanism" }, { GSS_C_MA_MECH_DESCRIPTION, "GSS_C_MA_MECH_DESCRIPTION", "Mech description", "The long description of the mechanism" }, { GSS_C_MA_MECH_GLUE, "GSS_C_MA_MECH_GLUE", "mech-glue", "" }, { GSS_C_MA_MECH_NAME, "GSS_C_MA_MECH_NAME", "GSS mech name", "The name of the GSS-API mechanism" }, { GSS_C_MA_MECH_NEGO, "GSS_C_MA_MECH_NEGO", "mech-negotiation-mech", "" }, { GSS_C_MA_MECH_PSEUDO, "GSS_C_MA_MECH_PSEUDO", "pseudo-mech", "" }, { GSS_C_MA_MIC, "GSS_C_MA_MIC", "mic", "" }, { GSS_C_MA_NOT_DFLT_MECH, "GSS_C_MA_NOT_DFLT_MECH", "mech-not-default", "" }, { GSS_C_MA_NOT_MECH, "GSS_C_MA_NOT_MECH", "not-mech", "" }, { GSS_C_MA_OOS_DET, "GSS_C_MA_OOS_DET", "oos-detection", "" }, { GSS_C_MA_PFS, "GSS_C_MA_PFS", "pfs", "" }, { GSS_C_MA_PROT_READY, "GSS_C_MA_PROT_READY", "prot-ready", "" }, { GSS_C_MA_REPLAY_DET, "GSS_C_MA_REPLAY_DET", "replay-detection", "" }, { GSS_C_MA_SASL_MECH_NAME, "GSS_C_MA_SASL_MECH_NAME", "SASL mechanism name", "The name of the SASL mechanism" }, { GSS_C_MA_WRAP, "GSS_C_MA_WRAP", "wrap", "" }, { NULL, NULL, NULL, NULL } }; struct _gss_oid_name_table _gss_ont_mech[] = { { GSS_KRB5_MECHANISM, "GSS_KRB5_MECHANISM", "Kerberos 5", "Heimdal Kerberos 5 mechanism" }, { GSS_NTLM_MECHANISM, "GSS_NTLM_MECHANISM", "NTLM", "Heimdal NTLM mechanism" }, { GSS_SPNEGO_MECHANISM, "GSS_SPNEGO_MECHANISM", "SPNEGO", "Heimdal SPNEGO mechanism" }, { NULL, NULL, NULL, NULL } }; heimdal-7.5.0/lib/gssapi/libgssapi-exports.def0000644000175000017500000001327513026237312017454 0ustar niknikEXPORTS __gss_c_nt_anonymous_oid_desc DATA __gss_c_nt_export_name_oid_desc DATA __gss_c_nt_hostbased_service_oid_desc DATA __gss_c_nt_hostbased_service_x_oid_desc DATA __gss_c_nt_machine_uid_name_oid_desc DATA __gss_c_nt_string_uid_name_oid_desc DATA __gss_c_nt_user_name_oid_desc DATA __gss_krb5_nt_principal_name_oid_desc DATA __gss_c_attr_stream_sizes_oid_desc DATA __gss_c_attr_local_login_user DATA __gss_c_cred_certificate_oid_desc DATA __gss_c_cred_password_oid_desc DATA gss_accept_sec_context gss_acquire_cred gss_acquire_cred_with_password gss_add_buffer_set_member gss_add_cred gss_add_cred_with_password gss_add_oid_set_member gss_authorize_localname gss_canonicalize_name gss_compare_name gss_context_query_attributes gss_context_time gss_create_empty_buffer_set gss_create_empty_oid_set gss_decapsulate_token gss_delete_name_attribute gss_delete_sec_context gss_display_mech_attr gss_display_name gss_display_name_ext gss_display_status gss_duplicate_name gss_duplicate_oid gss_encapsulate_token gss_export_cred gss_export_name gss_export_name_composite gss_export_sec_context gss_get_mic gss_get_name_attribute gss_import_cred gss_import_name gss_import_sec_context gss_indicate_mechs gss_indicate_mechs_by_attrs gss_init_sec_context gss_inquire_attrs_for_mech gss_inquire_context gss_inquire_cred gss_inquire_cred_by_mech gss_inquire_cred_by_oid gss_inquire_mech_for_saslname gss_inquire_mechs_for_name gss_inquire_name gss_inquire_names_for_mech gss_inquire_saslname_for_mech gss_inquire_sec_context_by_oid ;! gss_krb5_ccache_name gss_krb5_copy_ccache gss_krb5_export_lucid_sec_context gss_krb5_free_lucid_sec_context gss_krb5_get_tkt_flags gss_krb5_import_cred gss_krb5_set_allowable_enctypes gss_localname gss_mg_collect_error gss_mo_get gss_mo_set gss_mo_list gss_mo_name gss_name_to_oid gss_oid_to_name gss_oid_equal gss_oid_to_str gss_pname_to_uid gss_process_context_token gss_pseudo_random gss_release_buffer gss_release_buffer_set gss_release_cred gss_release_iov_buffer gss_release_name gss_release_oid gss_release_oid_set gss_seal gss_set_cred_option gss_set_name_attribute gss_set_sec_context_option gss_sign gss_store_cred gss_test_oid_set_member gss_unseal gss_unwrap gss_unwrap_aead gss_unwrap_iov gss_userok gss_verify gss_verify_mic gss_wrap gss_wrap_aead gss_wrap_iov gss_wrap_iov_length gss_wrap_size_limit gsskrb5_extract_authtime_from_sec_context gsskrb5_extract_authz_data_from_sec_context gsskrb5_extract_service_keyblock gsskrb5_get_initiator_subkey gsskrb5_get_subkey gsskrb5_get_time_offset gsskrb5_register_acceptor_identity gsskrb5_set_default_realm gsskrb5_set_dns_canonicalize gsskrb5_set_send_to_kdc gsskrb5_set_time_offset krb5_gss_register_acceptor_identity ; _gsskrb5cfx_ are really internal symbols, but export ; then now to make testing easier. _gsskrb5cfx_wrap_length_cfx _gssapi_wrap_size_cfx initialize_gk5_error_table_r ;! __gss_krb5_copy_ccache_x_oid_desc DATA __gss_krb5_get_tkt_flags_x_oid_desc DATA __gss_krb5_extract_authz_data_from_sec_context_x_oid_desc DATA __gss_krb5_compat_des3_mic_x_oid_desc DATA __gss_krb5_register_acceptor_identity_x_oid_desc DATA __gss_krb5_export_lucid_context_x_oid_desc DATA __gss_krb5_export_lucid_context_v1_x_oid_desc DATA __gss_krb5_set_dns_canonicalize_x_oid_desc DATA __gss_krb5_get_subkey_x_oid_desc DATA __gss_krb5_get_initiator_subkey_x_oid_desc DATA __gss_krb5_get_acceptor_subkey_x_oid_desc DATA __gss_krb5_send_to_kdc_x_oid_desc DATA __gss_krb5_get_authtime_x_oid_desc DATA __gss_krb5_get_service_keyblock_x_oid_desc DATA __gss_krb5_set_allowable_enctypes_x_oid_desc DATA __gss_krb5_set_default_realm_x_oid_desc DATA __gss_krb5_ccache_name_x_oid_desc DATA __gss_krb5_set_time_offset_x_oid_desc DATA __gss_krb5_get_time_offset_x_oid_desc DATA __gss_krb5_plugin_register_x_oid_desc DATA __gss_ntlm_get_session_key_x_oid_desc DATA __gss_c_nt_ntlm_oid_desc DATA __gss_c_nt_dn_oid_desc DATA __gss_krb5_nt_principal_name_referral_oid_desc DATA __gss_c_ntlm_avguest_oid_desc DATA __gss_c_ntlm_v1_oid_desc DATA __gss_c_ntlm_v2_oid_desc DATA __gss_c_ntlm_session_key_oid_desc DATA __gss_c_ntlm_force_v1_oid_desc DATA __gss_krb5_cred_no_ci_flags_x_oid_desc DATA __gss_krb5_import_cred_x_oid_desc DATA __gss_c_ma_sasl_mech_name_oid_desc DATA __gss_c_ma_mech_name_oid_desc DATA __gss_c_ma_mech_description_oid_desc DATA __gss_sasl_digest_md5_mechanism_oid_desc DATA __gss_krb5_mechanism_oid_desc DATA __gss_ntlm_mechanism_oid_desc DATA __gss_spnego_mechanism_oid_desc DATA __gss_c_peer_has_updated_spnego_oid_desc DATA __gss_c_ma_mech_concrete_oid_desc DATA __gss_c_ma_mech_pseudo_oid_desc DATA __gss_c_ma_mech_composite_oid_desc DATA __gss_c_ma_mech_nego_oid_desc DATA __gss_c_ma_mech_glue_oid_desc DATA __gss_c_ma_not_mech_oid_desc DATA __gss_c_ma_deprecated_oid_desc DATA __gss_c_ma_not_dflt_mech_oid_desc DATA __gss_c_ma_itok_framed_oid_desc DATA __gss_c_ma_auth_init_oid_desc DATA __gss_c_ma_auth_targ_oid_desc DATA __gss_c_ma_auth_init_init_oid_desc DATA __gss_c_ma_auth_targ_init_oid_desc DATA __gss_c_ma_auth_init_anon_oid_desc DATA __gss_c_ma_auth_targ_anon_oid_desc DATA __gss_c_ma_deleg_cred_oid_desc DATA __gss_c_ma_integ_prot_oid_desc DATA __gss_c_ma_conf_prot_oid_desc DATA __gss_c_ma_mic_oid_desc DATA __gss_c_ma_wrap_oid_desc DATA __gss_c_ma_prot_ready_oid_desc DATA __gss_c_ma_replay_det_oid_desc DATA __gss_c_ma_oos_det_oid_desc DATA __gss_c_ma_cbindings_oid_desc DATA __gss_c_ma_pfs_oid_desc DATA __gss_c_ma_compress_oid_desc DATA __gss_c_ma_ctx_trans_oid_desc DATA heimdal-7.5.0/lib/gssapi/gssapi/0000755000175000017500000000000013214604041014567 5ustar niknikheimdal-7.5.0/lib/gssapi/gssapi/gssapi_netlogon.h0000644000175000017500000000402213026237312020135 0ustar niknik/* * Copyright (c) 2006 - 2009 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ /* $Id$ */ #ifndef GSSAPI_NETLOGON_H_ #define GSSAPI_NETLOGON_H_ #include GSSAPI_CPP_START extern GSSAPI_LIB_VARIABLE gss_OID GSS_NETLOGON_MECHANISM; extern GSSAPI_LIB_VARIABLE gss_OID GSS_NETLOGON_NT_NETBIOS_DNS_NAME; extern GSSAPI_LIB_VARIABLE gss_OID GSS_NETLOGON_SET_SESSION_KEY_X; extern GSSAPI_LIB_VARIABLE gss_OID GSS_NETLOGON_SET_SIGN_ALGORITHM_X; GSSAPI_CPP_END #endif /* GSSAPI_NETLOGON_H_ */ heimdal-7.5.0/lib/gssapi/gssapi/gssapi.h0000644000175000017500000011227313026237312016240 0ustar niknik/* * Copyright (c) 1997 - 2007 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #ifndef GSSAPI_GSSAPI_H_ #define GSSAPI_GSSAPI_H_ /* * First, include stddef.h to get size_t defined. */ #include #include #ifndef BUILD_GSSAPI_LIB #if defined(_WIN32) #define GSSAPI_LIB_FUNCTION __declspec(dllimport) #define GSSAPI_LIB_CALL __stdcall #define GSSAPI_LIB_VARIABLE __declspec(dllimport) #else #define GSSAPI_LIB_FUNCTION #define GSSAPI_LIB_CALL #define GSSAPI_LIB_VARIABLE #endif #endif #ifndef GSSAPI_DEPRECATED_FUNCTION #if defined(__GNUC__) && ((__GNUC__ > 3) || ((__GNUC__ == 3) && (__GNUC_MINOR__ >= 1 ))) #define GSSAPI_DEPRECATED_FUNCTION(X) __attribute__((deprecated)) #else #define GSSAPI_DEPRECATED_FUNCTION(X) #endif #endif /* Compatiblity with MIT Kerberos on the Mac */ #if defined(__APPLE__) && (defined(__ppc__) || defined(__ppc64__) || defined(__i386__) || defined(__x86_64__)) #pragma pack(push,2) #endif #ifdef __cplusplus #define GSSAPI_CPP_START extern "C" { #define GSSAPI_CPP_END } #else #define GSSAPI_CPP_START #define GSSAPI_CPP_END #endif #ifdef _WIN32 #define GSSAPI_CALLCONV __stdcall #else #define GSSAPI_CALLCONV #endif /* * Now define the three implementation-dependent types. */ typedef uint32_t OM_uint32; typedef uint64_t OM_uint64; typedef uint32_t gss_uint32; struct gss_name_t_desc_struct; typedef struct gss_name_t_desc_struct *gss_name_t; typedef const struct gss_name_t_desc_struct *gss_const_name_t; struct gss_ctx_id_t_desc_struct; typedef struct gss_ctx_id_t_desc_struct *gss_ctx_id_t; typedef const struct gss_ctx_id_t_desc_struct *gss_const_ctx_id_t; typedef struct gss_OID_desc_struct { OM_uint32 length; void *elements; } gss_OID_desc, *gss_OID; typedef const gss_OID_desc * gss_const_OID; typedef struct gss_OID_set_desc_struct { size_t count; gss_OID elements; } gss_OID_set_desc, *gss_OID_set; typedef const gss_OID_set_desc * gss_const_OID_set; typedef int gss_cred_usage_t; struct gss_cred_id_t_desc_struct; typedef struct gss_cred_id_t_desc_struct *gss_cred_id_t; typedef const struct gss_cred_id_t_desc_struct *gss_const_cred_id_t; typedef struct gss_buffer_desc_struct { size_t length; void *value; } gss_buffer_desc, *gss_buffer_t; typedef const gss_buffer_desc * gss_const_buffer_t; typedef struct gss_channel_bindings_struct { OM_uint32 initiator_addrtype; gss_buffer_desc initiator_address; OM_uint32 acceptor_addrtype; gss_buffer_desc acceptor_address; gss_buffer_desc application_data; } *gss_channel_bindings_t; typedef const struct gss_channel_bindings_struct *gss_const_channel_bindings_t; /* GGF extension data types */ typedef struct gss_buffer_set_desc_struct { size_t count; gss_buffer_desc *elements; } gss_buffer_set_desc, *gss_buffer_set_t; typedef struct gss_iov_buffer_desc_struct { OM_uint32 type; gss_buffer_desc buffer; } gss_iov_buffer_desc, *gss_iov_buffer_t; /* * For now, define a QOP-type as an OM_uint32 */ typedef OM_uint32 gss_qop_t; /* * Flag bits for context-level services. */ #define GSS_C_DELEG_FLAG 1 #define GSS_C_MUTUAL_FLAG 2 #define GSS_C_REPLAY_FLAG 4 #define GSS_C_SEQUENCE_FLAG 8 #define GSS_C_CONF_FLAG 16 #define GSS_C_INTEG_FLAG 32 #define GSS_C_ANON_FLAG 64 #define GSS_C_PROT_READY_FLAG 128 #define GSS_C_TRANS_FLAG 256 #define GSS_C_DCE_STYLE 4096 #define GSS_C_IDENTIFY_FLAG 8192 #define GSS_C_EXTENDED_ERROR_FLAG 16384 #define GSS_C_DELEG_POLICY_FLAG 32768 /* * Credential usage options */ #define GSS_C_BOTH 0 #define GSS_C_INITIATE 1 #define GSS_C_ACCEPT 2 /* * Status code types for gss_display_status */ #define GSS_C_GSS_CODE 1 #define GSS_C_MECH_CODE 2 /* * The constant definitions for channel-bindings address families */ #define GSS_C_AF_UNSPEC 0 #define GSS_C_AF_LOCAL 1 #define GSS_C_AF_INET 2 #define GSS_C_AF_IMPLINK 3 #define GSS_C_AF_PUP 4 #define GSS_C_AF_CHAOS 5 #define GSS_C_AF_NS 6 #define GSS_C_AF_NBS 7 #define GSS_C_AF_ECMA 8 #define GSS_C_AF_DATAKIT 9 #define GSS_C_AF_CCITT 10 #define GSS_C_AF_SNA 11 #define GSS_C_AF_DECnet 12 #define GSS_C_AF_DLI 13 #define GSS_C_AF_LAT 14 #define GSS_C_AF_HYLINK 15 #define GSS_C_AF_APPLETALK 16 #define GSS_C_AF_BSC 17 #define GSS_C_AF_DSS 18 #define GSS_C_AF_OSI 19 #define GSS_C_AF_X25 21 #define GSS_C_AF_INET6 24 #define GSS_C_AF_NULLADDR 255 /* * Various Null values */ #define GSS_C_NO_NAME ((gss_name_t) 0) #define GSS_C_NO_BUFFER ((gss_buffer_t) 0) #define GSS_C_NO_BUFFER_SET ((gss_buffer_set_t) 0) #define GSS_C_NO_OID ((gss_OID) 0) #define GSS_C_NO_OID_SET ((gss_OID_set) 0) #define GSS_C_NO_CONTEXT ((gss_ctx_id_t) 0) #define GSS_C_NO_CREDENTIAL ((gss_cred_id_t) 0) #define GSS_C_NO_CHANNEL_BINDINGS ((gss_channel_bindings_t) 0) #define GSS_C_EMPTY_BUFFER {0, NULL} #define GSS_C_NO_IOV_BUFFER ((gss_iov_buffer_t)0) /* * Some alternate names for a couple of the above * values. These are defined for V1 compatibility. */ #define GSS_C_NULL_OID GSS_C_NO_OID #define GSS_C_NULL_OID_SET GSS_C_NO_OID_SET /* * Define the default Quality of Protection for per-message * services. Note that an implementation that offers multiple * levels of QOP may define GSS_C_QOP_DEFAULT to be either zero * (as done here) to mean "default protection", or to a specific * explicit QOP value. However, a value of 0 should always be * interpreted by a GSSAPI implementation as a request for the * default protection level. */ #define GSS_C_QOP_DEFAULT 0 #define GSS_KRB5_CONF_C_QOP_DES 0x0100 #define GSS_KRB5_CONF_C_QOP_DES3_KD 0x0200 /* * Expiration time of 2^32-1 seconds means infinite lifetime for a * credential or security context */ #define GSS_C_INDEFINITE 0xfffffffful /* * Type of gss_wrap_iov()/gss_unwrap_iov(). */ #define GSS_IOV_BUFFER_TYPE_EMPTY 0 #define GSS_IOV_BUFFER_TYPE_DATA 1 #define GSS_IOV_BUFFER_TYPE_HEADER 2 #define GSS_IOV_BUFFER_TYPE_MECH_PARAMS 3 #define GSS_IOV_BUFFER_TYPE_TRAILER 7 #define GSS_IOV_BUFFER_TYPE_PADDING 9 #define GSS_IOV_BUFFER_TYPE_STREAM 10 #define GSS_IOV_BUFFER_TYPE_SIGN_ONLY 11 #define GSS_IOV_BUFFER_TYPE_FLAG_MASK 0xffff0000 #define GSS_IOV_BUFFER_FLAG_ALLOCATE 0x00010000 #define GSS_IOV_BUFFER_FLAG_ALLOCATED 0x00020000 #define GSS_IOV_BUFFER_TYPE_FLAG_ALLOCATE 0x00010000 /* old name */ #define GSS_IOV_BUFFER_TYPE_FLAG_ALLOCATED 0x00020000 /* old name */ #define GSS_IOV_BUFFER_TYPE(_t) ((_t) & ~GSS_IOV_BUFFER_TYPE_FLAG_MASK) #define GSS_IOV_BUFFER_FLAGS(_t) ((_t) & GSS_IOV_BUFFER_TYPE_FLAG_MASK) GSSAPI_CPP_START #include /* * The implementation must reserve static storage for a * gss_OID_desc object containing the value * {10, (void *)"\x2a\x86\x48\x86\xf7\x12" * "\x01\x02\x01\x01"}, * corresponding to an object-identifier value of * {iso(1) member-body(2) United States(840) mit(113554) * infosys(1) gssapi(2) generic(1) user_name(1)}. The constant * GSS_C_NT_USER_NAME should be initialized to point * to that gss_OID_desc. */ extern GSSAPI_LIB_VARIABLE gss_OID_desc __gss_c_nt_user_name_oid_desc; #define GSS_C_NT_USER_NAME (&__gss_c_nt_user_name_oid_desc) /* * The implementation must reserve static storage for a * gss_OID_desc object containing the value * {10, (void *)"\x2a\x86\x48\x86\xf7\x12" * "\x01\x02\x01\x02"}, * corresponding to an object-identifier value of * {iso(1) member-body(2) United States(840) mit(113554) * infosys(1) gssapi(2) generic(1) machine_uid_name(2)}. * The constant GSS_C_NT_MACHINE_UID_NAME should be * initialized to point to that gss_OID_desc. */ extern GSSAPI_LIB_VARIABLE gss_OID_desc __gss_c_nt_machine_uid_name_oid_desc; #define GSS_C_NT_MACHINE_UID_NAME (&__gss_c_nt_machine_uid_name_oid_desc) /* * The implementation must reserve static storage for a * gss_OID_desc object containing the value * {10, (void *)"\x2a\x86\x48\x86\xf7\x12" * "\x01\x02\x01\x03"}, * corresponding to an object-identifier value of * {iso(1) member-body(2) United States(840) mit(113554) * infosys(1) gssapi(2) generic(1) string_uid_name(3)}. * The constant GSS_C_NT_STRING_UID_NAME should be * initialized to point to that gss_OID_desc. */ extern GSSAPI_LIB_VARIABLE gss_OID_desc __gss_c_nt_string_uid_name_oid_desc; #define GSS_C_NT_STRING_UID_NAME (&__gss_c_nt_string_uid_name_oid_desc) /* * The implementation must reserve static storage for a * gss_OID_desc object containing the value * {6, (void *)"\x2b\x06\x01\x05\x06\x02"}, * corresponding to an object-identifier value of * {iso(1) org(3) dod(6) internet(1) security(5) * nametypes(6) gss-host-based-services(2)). The constant * GSS_C_NT_HOSTBASED_SERVICE_X should be initialized to point * to that gss_OID_desc. This is a deprecated OID value, and * implementations wishing to support hostbased-service names * should instead use the GSS_C_NT_HOSTBASED_SERVICE OID, * defined below, to identify such names; * GSS_C_NT_HOSTBASED_SERVICE_X should be accepted a synonym * for GSS_C_NT_HOSTBASED_SERVICE when presented as an input * parameter, but should not be emitted by GSS-API * implementations */ extern GSSAPI_LIB_VARIABLE gss_OID_desc __gss_c_nt_hostbased_service_x_oid_desc; #define GSS_C_NT_HOSTBASED_SERVICE_X (&__gss_c_nt_hostbased_service_x_oid_desc) /* * The implementation must reserve static storage for a * gss_OID_desc object containing the value * {10, (void *)"\x2a\x86\x48\x86\xf7\x12" * "\x01\x02\x01\x04"}, corresponding to an * object-identifier value of {iso(1) member-body(2) * Unites States(840) mit(113554) infosys(1) gssapi(2) * generic(1) service_name(4)}. The constant * GSS_C_NT_HOSTBASED_SERVICE should be initialized * to point to that gss_OID_desc. */ extern GSSAPI_LIB_VARIABLE gss_OID_desc __gss_c_nt_hostbased_service_oid_desc; #define GSS_C_NT_HOSTBASED_SERVICE (&__gss_c_nt_hostbased_service_oid_desc) /* * The implementation must reserve static storage for a * gss_OID_desc object containing the value * {6, (void *)"\x2b\x06\01\x05\x06\x03"}, * corresponding to an object identifier value of * {1(iso), 3(org), 6(dod), 1(internet), 5(security), * 6(nametypes), 3(gss-anonymous-name)}. The constant * and GSS_C_NT_ANONYMOUS should be initialized to point * to that gss_OID_desc. */ extern GSSAPI_LIB_VARIABLE gss_OID_desc __gss_c_nt_anonymous_oid_desc; #define GSS_C_NT_ANONYMOUS (&__gss_c_nt_anonymous_oid_desc) /* * The implementation must reserve static storage for a * gss_OID_desc object containing the value * {6, (void *)"\x2b\x06\x01\x05\x06\x04"}, * corresponding to an object-identifier value of * {1(iso), 3(org), 6(dod), 1(internet), 5(security), * 6(nametypes), 4(gss-api-exported-name)}. The constant * GSS_C_NT_EXPORT_NAME should be initialized to point * to that gss_OID_desc. */ extern GSSAPI_LIB_VARIABLE gss_OID_desc __gss_c_nt_export_name_oid_desc; #define GSS_C_NT_EXPORT_NAME (&__gss_c_nt_export_name_oid_desc) /* Major status codes */ #define GSS_S_COMPLETE 0 /* * Some "helper" definitions to make the status code macros obvious. */ #define GSS_C_CALLING_ERROR_OFFSET 24 #define GSS_C_ROUTINE_ERROR_OFFSET 16 #define GSS_C_SUPPLEMENTARY_OFFSET 0 #define GSS_C_CALLING_ERROR_MASK 0377ul #define GSS_C_ROUTINE_ERROR_MASK 0377ul #define GSS_C_SUPPLEMENTARY_MASK 0177777ul /* * The macros that test status codes for error conditions. * Note that the GSS_ERROR() macro has changed slightly from * the V1 GSSAPI so that it now evaluates its argument * only once. */ #define GSS_CALLING_ERROR(x) \ (x & (GSS_C_CALLING_ERROR_MASK << GSS_C_CALLING_ERROR_OFFSET)) #define GSS_ROUTINE_ERROR(x) \ (x & (GSS_C_ROUTINE_ERROR_MASK << GSS_C_ROUTINE_ERROR_OFFSET)) #define GSS_SUPPLEMENTARY_INFO(x) \ (x & (GSS_C_SUPPLEMENTARY_MASK << GSS_C_SUPPLEMENTARY_OFFSET)) #define GSS_ERROR(x) \ (x & ((GSS_C_CALLING_ERROR_MASK << GSS_C_CALLING_ERROR_OFFSET) | \ (GSS_C_ROUTINE_ERROR_MASK << GSS_C_ROUTINE_ERROR_OFFSET))) /* * Now the actual status code definitions */ /* * Calling errors: */ #define GSS_S_CALL_INACCESSIBLE_READ \ (1ul << GSS_C_CALLING_ERROR_OFFSET) #define GSS_S_CALL_INACCESSIBLE_WRITE \ (2ul << GSS_C_CALLING_ERROR_OFFSET) #define GSS_S_CALL_BAD_STRUCTURE \ (3ul << GSS_C_CALLING_ERROR_OFFSET) /* * Routine errors: */ #define GSS_S_BAD_MECH (1ul << GSS_C_ROUTINE_ERROR_OFFSET) #define GSS_S_BAD_NAME (2ul << GSS_C_ROUTINE_ERROR_OFFSET) #define GSS_S_BAD_NAMETYPE (3ul << GSS_C_ROUTINE_ERROR_OFFSET) #define GSS_S_BAD_BINDINGS (4ul << GSS_C_ROUTINE_ERROR_OFFSET) #define GSS_S_BAD_STATUS (5ul << GSS_C_ROUTINE_ERROR_OFFSET) #define GSS_S_BAD_SIG (6ul << GSS_C_ROUTINE_ERROR_OFFSET) #define GSS_S_BAD_MIC GSS_S_BAD_SIG #define GSS_S_NO_CRED (7ul << GSS_C_ROUTINE_ERROR_OFFSET) #define GSS_S_NO_CONTEXT (8ul << GSS_C_ROUTINE_ERROR_OFFSET) #define GSS_S_DEFECTIVE_TOKEN (9ul << GSS_C_ROUTINE_ERROR_OFFSET) #define GSS_S_DEFECTIVE_CREDENTIAL (10ul << GSS_C_ROUTINE_ERROR_OFFSET) #define GSS_S_CREDENTIALS_EXPIRED (11ul << GSS_C_ROUTINE_ERROR_OFFSET) #define GSS_S_CONTEXT_EXPIRED (12ul << GSS_C_ROUTINE_ERROR_OFFSET) #define GSS_S_FAILURE (13ul << GSS_C_ROUTINE_ERROR_OFFSET) #define GSS_S_BAD_QOP (14ul << GSS_C_ROUTINE_ERROR_OFFSET) #define GSS_S_UNAUTHORIZED (15ul << GSS_C_ROUTINE_ERROR_OFFSET) #define GSS_S_UNAVAILABLE (16ul << GSS_C_ROUTINE_ERROR_OFFSET) #define GSS_S_DUPLICATE_ELEMENT (17ul << GSS_C_ROUTINE_ERROR_OFFSET) #define GSS_S_NAME_NOT_MN (18ul << GSS_C_ROUTINE_ERROR_OFFSET) #define GSS_S_BAD_MECH_ATTR (19ul << GSS_C_ROUTINE_ERROR_OFFSET) /* * Apparently awating spec fix. */ #define GSS_S_CRED_UNAVAIL GSS_S_FAILURE /* * Supplementary info bits: */ #define GSS_S_CONTINUE_NEEDED (1ul << (GSS_C_SUPPLEMENTARY_OFFSET + 0)) #define GSS_S_DUPLICATE_TOKEN (1ul << (GSS_C_SUPPLEMENTARY_OFFSET + 1)) #define GSS_S_OLD_TOKEN (1ul << (GSS_C_SUPPLEMENTARY_OFFSET + 2)) #define GSS_S_UNSEQ_TOKEN (1ul << (GSS_C_SUPPLEMENTARY_OFFSET + 3)) #define GSS_S_GAP_TOKEN (1ul << (GSS_C_SUPPLEMENTARY_OFFSET + 4)) /* * Finally, function prototypes for the GSS-API routines. */ #define GSS_C_OPTION_MASK 0xffff #define GSS_C_CRED_NO_UI 0x10000 GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL gss_acquire_cred (OM_uint32 * /*minor_status*/, gss_const_name_t /*desired_name*/, OM_uint32 /*time_req*/, const gss_OID_set /*desired_mechs*/, gss_cred_usage_t /*cred_usage*/, gss_cred_id_t * /*output_cred_handle*/, gss_OID_set * /*actual_mechs*/, OM_uint32 * /*time_rec*/ ); GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL gss_release_cred (OM_uint32 * /*minor_status*/, gss_cred_id_t * /*cred_handle*/ ); GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL gss_init_sec_context (OM_uint32 * /*minor_status*/, gss_const_cred_id_t /*initiator_cred_handle*/, gss_ctx_id_t * /*context_handle*/, gss_const_name_t /*target_name*/, const gss_OID /*mech_type*/, OM_uint32 /*req_flags*/, OM_uint32 /*time_req*/, const gss_channel_bindings_t /*input_chan_bindings*/, const gss_buffer_t /*input_token*/, gss_OID * /*actual_mech_type*/, gss_buffer_t /*output_token*/, OM_uint32 * /*ret_flags*/, OM_uint32 * /*time_rec*/ ); GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL gss_accept_sec_context (OM_uint32 * /*minor_status*/, gss_ctx_id_t * /*context_handle*/, gss_const_cred_id_t /*acceptor_cred_handle*/, const gss_buffer_t /*input_token_buffer*/, const gss_channel_bindings_t /*input_chan_bindings*/, gss_name_t * /*src_name*/, gss_OID * /*mech_type*/, gss_buffer_t /*output_token*/, OM_uint32 * /*ret_flags*/, OM_uint32 * /*time_rec*/, gss_cred_id_t * /*delegated_cred_handle*/ ); GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL gss_process_context_token (OM_uint32 * /*minor_status*/, gss_const_ctx_id_t /*context_handle*/, const gss_buffer_t /*token_buffer*/ ); GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL gss_delete_sec_context (OM_uint32 * /*minor_status*/, gss_ctx_id_t * /*context_handle*/, gss_buffer_t /*output_token*/ ); GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL gss_context_time (OM_uint32 * /*minor_status*/, gss_const_ctx_id_t /*context_handle*/, OM_uint32 * /*time_rec*/ ); GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL gss_get_mic (OM_uint32 * /*minor_status*/, gss_const_ctx_id_t /*context_handle*/, gss_qop_t /*qop_req*/, const gss_buffer_t /*message_buffer*/, gss_buffer_t /*message_token*/ ); GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL gss_verify_mic (OM_uint32 * /*minor_status*/, gss_const_ctx_id_t /*context_handle*/, const gss_buffer_t /*message_buffer*/, const gss_buffer_t /*token_buffer*/, gss_qop_t * /*qop_state*/ ); GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL gss_wrap (OM_uint32 * /*minor_status*/, gss_const_ctx_id_t /*context_handle*/, int /*conf_req_flag*/, gss_qop_t /*qop_req*/, const gss_buffer_t /*input_message_buffer*/, int * /*conf_state*/, gss_buffer_t /*output_message_buffer*/ ); GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL gss_unwrap (OM_uint32 * /*minor_status*/, gss_const_ctx_id_t /*context_handle*/, const gss_buffer_t /*input_message_buffer*/, gss_buffer_t /*output_message_buffer*/, int * /*conf_state*/, gss_qop_t * /*qop_state*/ ); GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL gss_display_status (OM_uint32 * /*minor_status*/, OM_uint32 /*status_value*/, int /*status_type*/, const gss_OID /*mech_type*/, OM_uint32 * /*message_context*/, gss_buffer_t /*status_string*/ ); GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL gss_indicate_mechs (OM_uint32 * /*minor_status*/, gss_OID_set * /*mech_set*/ ); GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL gss_compare_name (OM_uint32 * /*minor_status*/, gss_const_name_t /*name1*/, gss_const_name_t /*name2*/, int * /*name_equal*/ ); GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL gss_display_name (OM_uint32 * /*minor_status*/, gss_const_name_t /*input_name*/, gss_buffer_t /*output_name_buffer*/, gss_OID * /*output_name_type*/ ); GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL gss_import_name (OM_uint32 * /*minor_status*/, const gss_buffer_t /*input_name_buffer*/, const gss_OID /*input_name_type*/, gss_name_t * /*output_name*/ ); GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL gss_export_name (OM_uint32 * /*minor_status*/, gss_const_name_t /*input_name*/, gss_buffer_t /*exported_name*/ ); GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL gss_release_name (OM_uint32 * /*minor_status*/, gss_name_t * /*input_name*/ ); GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL gss_release_buffer (OM_uint32 * /*minor_status*/, gss_buffer_t /*buffer*/ ); GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL gss_release_oid_set (OM_uint32 * /*minor_status*/, gss_OID_set * /*set*/ ); GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL gss_inquire_cred (OM_uint32 * /*minor_status*/, gss_const_cred_id_t /*cred_handle*/, gss_name_t * /*name*/, OM_uint32 * /*lifetime*/, gss_cred_usage_t * /*cred_usage*/, gss_OID_set * /*mechanisms*/ ); GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL gss_inquire_context ( OM_uint32 * /*minor_status*/, gss_const_ctx_id_t /*context_handle*/, gss_name_t * /*src_name*/, gss_name_t * /*targ_name*/, OM_uint32 * /*lifetime_rec*/, gss_OID * /*mech_type*/, OM_uint32 * /*ctx_flags*/, int * /*locally_initiated*/, int * /*open_context*/ ); GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL gss_wrap_size_limit ( OM_uint32 * /*minor_status*/, gss_const_ctx_id_t /*context_handle*/, int /*conf_req_flag*/, gss_qop_t /*qop_req*/, OM_uint32 /*req_output_size*/, OM_uint32 * /*max_input_size*/ ); GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL gss_add_cred ( OM_uint32 * /*minor_status*/, gss_const_cred_id_t /*input_cred_handle*/, gss_const_name_t /*desired_name*/, const gss_OID /*desired_mech*/, gss_cred_usage_t /*cred_usage*/, OM_uint32 /*initiator_time_req*/, OM_uint32 /*acceptor_time_req*/, gss_cred_id_t * /*output_cred_handle*/, gss_OID_set * /*actual_mechs*/, OM_uint32 * /*initiator_time_rec*/, OM_uint32 * /*acceptor_time_rec*/ ); GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL gss_inquire_cred_by_mech ( OM_uint32 * /*minor_status*/, gss_const_cred_id_t /*cred_handle*/, const gss_OID /*mech_type*/, gss_name_t * /*name*/, OM_uint32 * /*initiator_lifetime*/, OM_uint32 * /*acceptor_lifetime*/, gss_cred_usage_t * /*cred_usage*/ ); GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL gss_export_sec_context ( OM_uint32 * /*minor_status*/, gss_ctx_id_t * /*context_handle*/, gss_buffer_t /*interprocess_token*/ ); GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL gss_import_sec_context ( OM_uint32 * /*minor_status*/, const gss_buffer_t /*interprocess_token*/, gss_ctx_id_t * /*context_handle*/ ); GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL gss_create_empty_oid_set ( OM_uint32 * /*minor_status*/, gss_OID_set * /*oid_set*/ ); GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL gss_add_oid_set_member ( OM_uint32 * /*minor_status*/, const gss_OID /*member_oid*/, gss_OID_set * /*oid_set*/ ); GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL gss_test_oid_set_member ( OM_uint32 * /*minor_status*/, const gss_OID /*member*/, const gss_OID_set /*set*/, int * /*present*/ ); GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL gss_inquire_names_for_mech ( OM_uint32 * /*minor_status*/, const gss_OID /*mechanism*/, gss_OID_set * /*name_types*/ ); GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL gss_inquire_mechs_for_name ( OM_uint32 * /*minor_status*/, gss_const_name_t /*input_name*/, gss_OID_set * /*mech_types*/ ); GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL gss_canonicalize_name ( OM_uint32 * /*minor_status*/, gss_const_name_t /*input_name*/, const gss_OID /*mech_type*/, gss_name_t * /*output_name*/ ); GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL gss_duplicate_name ( OM_uint32 * /*minor_status*/, gss_const_name_t /*src_name*/, gss_name_t * /*dest_name*/ ); GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL gss_duplicate_oid ( OM_uint32 * /* minor_status */, gss_OID /* src_oid */, gss_OID * /* dest_oid */ ); GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL gss_release_oid (OM_uint32 * /*minor_status*/, gss_OID * /* oid */ ); GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL gss_oid_to_str( OM_uint32 * /*minor_status*/, gss_OID /* oid */, gss_buffer_t /* str */ ); GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL gss_inquire_sec_context_by_oid( OM_uint32 * minor_status, gss_const_ctx_id_t context_handle, const gss_OID desired_object, gss_buffer_set_t *data_set ); GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL gss_set_sec_context_option (OM_uint32 *minor_status, gss_ctx_id_t *context_handle, const gss_OID desired_object, const gss_buffer_t value); GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL gss_set_cred_option (OM_uint32 *minor_status, gss_cred_id_t *cred_handle, const gss_OID object, const gss_buffer_t value); GSSAPI_LIB_FUNCTION int GSSAPI_LIB_CALL gss_oid_equal(gss_const_OID a, gss_const_OID b); GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL gss_create_empty_buffer_set (OM_uint32 * minor_status, gss_buffer_set_t *buffer_set); GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL gss_add_buffer_set_member (OM_uint32 * minor_status, const gss_buffer_t member_buffer, gss_buffer_set_t *buffer_set); GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL gss_release_buffer_set (OM_uint32 * minor_status, gss_buffer_set_t *buffer_set); GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL gss_inquire_cred_by_oid(OM_uint32 *minor_status, gss_const_cred_id_t cred_handle, const gss_OID desired_object, gss_buffer_set_t *data_set); /* * RFC 4401 */ #define GSS_C_PRF_KEY_FULL 0 #define GSS_C_PRF_KEY_PARTIAL 1 GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL gss_pseudo_random (OM_uint32 *minor_status, gss_ctx_id_t context, int prf_key, const gss_buffer_t prf_in, ssize_t desired_output_len, gss_buffer_t prf_out ); GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL gss_store_cred(OM_uint32 * /* minor_status */, gss_cred_id_t /* input_cred_handle */, gss_cred_usage_t /* cred_usage */, const gss_OID /* desired_mech */, OM_uint32 /* overwrite_cred */, OM_uint32 /* default_cred */, gss_OID_set * /* elements_stored */, gss_cred_usage_t * /* cred_usage_stored */); /* * Query functions */ typedef struct { size_t header; /**< size of header */ size_t trailer; /**< size of trailer */ size_t max_msg_size; /**< maximum message size */ size_t buffers; /**< extra GSS_IOV_BUFFER_TYPE_EMPTY buffer to pass */ size_t blocksize; /**< Specificed optimal size of messages, also is the maximum padding size (GSS_IOV_BUFFER_TYPE_PADDING) */ } gss_context_stream_sizes; extern gss_OID_desc GSSAPI_LIB_VARIABLE __gss_c_attr_stream_sizes_oid_desc; #define GSS_C_ATTR_STREAM_SIZES (&__gss_c_attr_stream_sizes_oid_desc) GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL gss_context_query_attributes(OM_uint32 * /* minor_status */, gss_const_ctx_id_t /* context_handle */, const gss_OID /* attribute */, void * /*data*/, size_t /* len */); /* * The following routines are obsolete variants of gss_get_mic, * gss_verify_mic, gss_wrap and gss_unwrap. They should be * provided by GSSAPI V2 implementations for backwards * compatibility with V1 applications. Distinct entrypoints * (as opposed to #defines) should be provided, both to allow * GSSAPI V1 applications to link against GSSAPI V2 implementations, * and to retain the slight parameter type differences between the * obsolete versions of these routines and their current forms. */ GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL gss_sign (OM_uint32 * /*minor_status*/, gss_ctx_id_t /*context_handle*/, int /*qop_req*/, gss_buffer_t /*message_buffer*/, gss_buffer_t /*message_token*/ ) GSSAPI_DEPRECATED_FUNCTION("Use gss_get_mic"); GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL gss_verify (OM_uint32 * /*minor_status*/, gss_ctx_id_t /*context_handle*/, gss_buffer_t /*message_buffer*/, gss_buffer_t /*token_buffer*/, int * /*qop_state*/ ) GSSAPI_DEPRECATED_FUNCTION("Use gss_verify_mic"); GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL gss_seal (OM_uint32 * /*minor_status*/, gss_ctx_id_t /*context_handle*/, int /*conf_req_flag*/, int /*qop_req*/, gss_buffer_t /*input_message_buffer*/, int * /*conf_state*/, gss_buffer_t /*output_message_buffer*/ ) GSSAPI_DEPRECATED_FUNCTION("Use gss_wrap"); GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL gss_unseal (OM_uint32 * /*minor_status*/, gss_ctx_id_t /*context_handle*/, gss_buffer_t /*input_message_buffer*/, gss_buffer_t /*output_message_buffer*/, int * /*conf_state*/, int * /*qop_state*/ ) GSSAPI_DEPRECATED_FUNCTION("Use gss_unwrap"); /** * */ GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL gss_encapsulate_token(gss_const_buffer_t /* input_token */, gss_const_OID /* oid */, gss_buffer_t /* output_token */); GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL gss_decapsulate_token(gss_const_buffer_t /* input_token */, gss_const_OID /* oid */, gss_buffer_t /* output_token */); /* * AEAD support */ /* * GSS_IOV */ GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL gss_wrap_iov(OM_uint32 *, gss_ctx_id_t, int, gss_qop_t, int *, gss_iov_buffer_desc *, int); GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL gss_unwrap_iov(OM_uint32 *, gss_ctx_id_t, int *, gss_qop_t *, gss_iov_buffer_desc *, int); GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL gss_wrap_iov_length(OM_uint32 *, gss_ctx_id_t, int, gss_qop_t, int *, gss_iov_buffer_desc *, int); GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL gss_release_iov_buffer(OM_uint32 *, gss_iov_buffer_desc *, int); GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL gss_wrap_aead(OM_uint32 *, gss_ctx_id_t, int, gss_qop_t, gss_buffer_t, gss_buffer_t, int *, gss_buffer_t); GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL gss_unwrap_aead(OM_uint32 *, gss_ctx_id_t, gss_buffer_t, gss_buffer_t, gss_buffer_t, int *, gss_qop_t *); GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL gss_export_cred(OM_uint32 * /* minor_status */, gss_cred_id_t /* cred_handle */, gss_buffer_t /* cred_token */); GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL gss_import_cred(OM_uint32 * /* minor_status */, gss_buffer_t /* cred_token */, gss_cred_id_t * /* cred_handle */); /* * mech option */ GSSAPI_LIB_FUNCTION int GSSAPI_LIB_CALL gss_mo_set(gss_const_OID mech, gss_const_OID option, int enable, gss_buffer_t value); GSSAPI_LIB_FUNCTION int GSSAPI_LIB_CALL gss_mo_get(gss_const_OID mech, gss_const_OID option, gss_buffer_t value); GSSAPI_LIB_FUNCTION void GSSAPI_LIB_CALL gss_mo_list(gss_const_OID mech, gss_OID_set *options); GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL gss_mo_name(gss_const_OID mech, gss_const_OID options, gss_buffer_t name); /* * SASL glue functions and mech inquire */ GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL gss_inquire_saslname_for_mech(OM_uint32 *minor_status, const gss_OID desired_mech, gss_buffer_t sasl_mech_name, gss_buffer_t mech_name, gss_buffer_t mech_description); GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL gss_inquire_mech_for_saslname(OM_uint32 *minor_status, const gss_buffer_t sasl_mech_name, gss_OID *mech_type); GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL gss_indicate_mechs_by_attrs(OM_uint32 * minor_status, gss_const_OID_set desired_mech_attrs, gss_const_OID_set except_mech_attrs, gss_const_OID_set critical_mech_attrs, gss_OID_set *mechs); GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL gss_inquire_attrs_for_mech(OM_uint32 * minor_status, gss_const_OID mech, gss_OID_set *mech_attr, gss_OID_set *known_mech_attrs); GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL gss_display_mech_attr(OM_uint32 * minor_status, gss_const_OID mech_attr, gss_buffer_t name, gss_buffer_t short_desc, gss_buffer_t long_desc); /* * Solaris compat */ GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL gss_acquire_cred_with_password (OM_uint32 * /*minor_status*/, gss_const_name_t /*desired_name*/, const gss_buffer_t /*password*/, OM_uint32 /*time_req*/, const gss_OID_set /*desired_mechs*/, gss_cred_usage_t /*cred_usage*/, gss_cred_id_t * /*output_cred_handle*/, gss_OID_set * /*actual_mechs*/, OM_uint32 * /*time_rec*/ ); GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL gss_add_cred_with_password ( OM_uint32 * /*minor_status*/, gss_const_cred_id_t /*input_cred_handle*/, gss_const_name_t /*desired_name*/, const gss_OID /*desired_mech*/, const gss_buffer_t /*password*/, gss_cred_usage_t /*cred_usage*/, OM_uint32 /*initiator_time_req*/, OM_uint32 /*acceptor_time_req*/, gss_cred_id_t * /*output_cred_handle*/, gss_OID_set * /*actual_mechs*/, OM_uint32 * /*initiator_time_rec*/, OM_uint32 * /*acceptor_time_rec*/ ); GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL gss_localname( OM_uint32 *minor, gss_const_name_t name, const gss_OID mech_type, gss_buffer_t localname); GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL gss_pname_to_uid( OM_uint32 *minor, gss_const_name_t name, const gss_OID mech_type, uid_t *uidOut); GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL gss_authorize_localname( OM_uint32 *minor, gss_const_name_t name, gss_const_name_t user); GSSAPI_LIB_FUNCTION int GSSAPI_LIB_CALL gss_userok(gss_const_name_t name, const char *user); extern GSSAPI_LIB_VARIABLE gss_buffer_desc __gss_c_attr_local_login_user; #define GSS_C_ATTR_LOCAL_LOGIN_USER (&__gss_c_attr_local_login_user) /* * Naming extensions */ GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL gss_display_name_ext ( OM_uint32 *, /* minor_status */ gss_name_t, /* name */ gss_OID, /* display_as_name_type */ gss_buffer_t /* display_name */ ); GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL gss_inquire_name ( OM_uint32 *, /* minor_status */ gss_name_t, /* name */ int *, /* name_is_MN */ gss_OID *, /* MN_mech */ gss_buffer_set_t * /* attrs */ ); GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL gss_get_name_attribute ( OM_uint32 *, /* minor_status */ gss_name_t, /* name */ gss_buffer_t, /* attr */ int *, /* authenticated */ int *, /* complete */ gss_buffer_t, /* value */ gss_buffer_t, /* display_value */ int * /* more */ ); GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL gss_set_name_attribute ( OM_uint32 *, /* minor_status */ gss_name_t, /* name */ int, /* complete */ gss_buffer_t, /* attr */ gss_buffer_t /* value */ ); GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL gss_delete_name_attribute ( OM_uint32 *, /* minor_status */ gss_name_t, /* name */ gss_buffer_t /* attr */ ); GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL gss_export_name_composite ( OM_uint32 *, /* minor_status */ gss_name_t, /* name */ gss_buffer_t /* exp_composite_name */ ); /* * */ GSSAPI_LIB_FUNCTION const char * GSSAPI_LIB_CALL gss_oid_to_name(gss_const_OID oid); GSSAPI_LIB_FUNCTION gss_OID GSSAPI_LIB_CALL gss_name_to_oid(const char *name); GSSAPI_CPP_END #if defined(__APPLE__) && (defined(__ppc__) || defined(__ppc64__) || defined(__i386__) || defined(__x86_64__)) #pragma pack(pop) #endif #undef GSSAPI_DEPRECATED_FUNCTION #endif /* GSSAPI_GSSAPI_H_ */ heimdal-7.5.0/lib/gssapi/gssapi/gssapi_krb5.h0000644000175000017500000001505613026237312017164 0ustar niknik/* * Copyright (c) 1997 - 2006 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ /* $Id$ */ #ifndef GSSAPI_KRB5_H_ #define GSSAPI_KRB5_H_ #include #include GSSAPI_CPP_START #if !defined(__GNUC__) && !defined(__attribute__) #define __attribute__(x) #endif #ifndef GSSKRB5_FUNCTION_DEPRECATED #define GSSKRB5_FUNCTION_DEPRECATED __attribute__((deprecated)) #endif /* * This is for kerberos5 names. */ extern gss_OID_desc GSSAPI_LIB_VARIABLE __gss_krb5_nt_principal_name_oid_desc; #define GSS_KRB5_NT_PRINCIPAL_NAME (&__gss_krb5_nt_principal_name_oid_desc) #define GSS_KRB5_NT_USER_NAME (&__gss_c_nt_user_name_oid_desc) #define GSS_KRB5_NT_MACHINE_UID_NAME (&__gss_c_nt_machine_uid_name_oid_desc) #define GSS_KRB5_NT_STRING_UID_NAME (&__gss_c_nt_string_uid_name_oid_desc) /* for compatibility with MIT api */ #define gss_mech_krb5 GSS_KRB5_MECHANISM #define gss_krb5_nt_general_name GSS_KRB5_NT_PRINCIPAL_NAME /* * kerberos mechanism specific functions */ struct krb5_keytab_data; struct krb5_ccache_data; struct Principal; GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL gss_krb5_ccache_name(OM_uint32 * /*minor_status*/, const char * /*name */, const char ** /*out_name */); GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL gsskrb5_register_acceptor_identity (const char * /*identity*/); GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL krb5_gss_register_acceptor_identity (const char * /*identity*/); GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL gss_krb5_copy_ccache (OM_uint32 * /*minor*/, gss_cred_id_t /*cred*/, struct krb5_ccache_data * /*out*/); GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL gss_krb5_import_cred(OM_uint32 * /*minor*/, struct krb5_ccache_data * /*in*/, struct Principal * /*keytab_principal*/, struct krb5_keytab_data * /*keytab*/, gss_cred_id_t * /*out*/); GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL gss_krb5_get_tkt_flags (OM_uint32 * /*minor*/, gss_ctx_id_t /*context_handle*/, OM_uint32 * /*tkt_flags*/); GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL gsskrb5_extract_authz_data_from_sec_context (OM_uint32 * /*minor_status*/, gss_ctx_id_t /*context_handle*/, int /*ad_type*/, gss_buffer_t /*ad_data*/); GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL gsskrb5_set_dns_canonicalize(int); struct gsskrb5_send_to_kdc { void *func; void *ptr; }; GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL gsskrb5_set_send_to_kdc(struct gsskrb5_send_to_kdc *) GSSKRB5_FUNCTION_DEPRECATED; GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL gsskrb5_set_default_realm(const char *); GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL gsskrb5_extract_authtime_from_sec_context(OM_uint32 *, gss_ctx_id_t, time_t *); struct EncryptionKey; GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL gsskrb5_extract_service_keyblock(OM_uint32 *minor_status, gss_ctx_id_t context_handle, struct EncryptionKey **out); GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL gsskrb5_get_initiator_subkey(OM_uint32 *minor_status, gss_ctx_id_t context_handle, struct EncryptionKey **out); GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL gsskrb5_get_subkey(OM_uint32 *minor_status, gss_ctx_id_t context_handle, struct EncryptionKey **out); GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL gsskrb5_set_time_offset(int); GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL gsskrb5_get_time_offset(int *); struct gsskrb5_krb5_plugin { int type; char *name; void *symbol; }; GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL gsskrb5_plugin_register(struct gsskrb5_krb5_plugin *); /* * Lucid - NFSv4 interface to GSS-API KRB5 to expose key material to * do GSS content token handling in-kernel. */ typedef struct gss_krb5_lucid_key { OM_uint32 type; OM_uint32 length; void * data; } gss_krb5_lucid_key_t; typedef struct gss_krb5_rfc1964_keydata { OM_uint32 sign_alg; OM_uint32 seal_alg; gss_krb5_lucid_key_t ctx_key; } gss_krb5_rfc1964_keydata_t; typedef struct gss_krb5_cfx_keydata { OM_uint32 have_acceptor_subkey; gss_krb5_lucid_key_t ctx_key; gss_krb5_lucid_key_t acceptor_subkey; } gss_krb5_cfx_keydata_t; typedef struct gss_krb5_lucid_context_v1 { OM_uint32 version; OM_uint32 initiate; OM_uint32 endtime; OM_uint64 send_seq; OM_uint64 recv_seq; OM_uint32 protocol; gss_krb5_rfc1964_keydata_t rfc1964_kd; gss_krb5_cfx_keydata_t cfx_kd; } gss_krb5_lucid_context_v1_t; typedef struct gss_krb5_lucid_context_version { OM_uint32 version; /* Structure version number */ } gss_krb5_lucid_context_version_t; /* * Function declarations */ GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL gss_krb5_export_lucid_sec_context(OM_uint32 *minor_status, gss_ctx_id_t *context_handle, OM_uint32 version, void **kctx); GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL gss_krb5_free_lucid_sec_context(OM_uint32 *minor_status, void *kctx); GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL gss_krb5_set_allowable_enctypes(OM_uint32 *minor_status, gss_cred_id_t cred, OM_uint32 num_enctypes, int32_t *enctypes); GSSAPI_CPP_END #endif /* GSSAPI_SPNEGO_H_ */ heimdal-7.5.0/lib/gssapi/gssapi/gssapi_spnego.h0000644000175000017500000000417612136107747017626 0ustar niknik/* * Copyright (c) 1997 - 2006 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ /* $Id$ */ #ifndef GSSAPI_SPNEGO_H_ #define GSSAPI_SPNEGO_H_ #include GSSAPI_CPP_START /* * RFC2478, SPNEGO: * The security mechanism of the initial * negotiation token is identified by the Object Identifier * iso.org.dod.internet.security.mechanism.snego (1.3.6.1.5.5.2). */ extern GSSAPI_LIB_VARIABLE gss_OID_desc __gss_spnego_mechanism_oid_desc; #define GSS_SPNEGO_MECHANISM (&__gss_spnego_mechanism_oid_desc) #define gss_mech_spnego GSS_SPNEGO_MECHANISM GSSAPI_CPP_END #endif /* GSSAPI_SPNEGO_H_ */ heimdal-7.5.0/lib/gssapi/gssapi/gssapi_oid.h0000644000175000017500000002615713026237312017100 0ustar niknik/* Generated file */ #ifndef GSSAPI_GSSAPI_OID #define GSSAPI_GSSAPI_OID 1 /* contact Love Hörnquist Åstrand for new oid arcs */ /* * 1.2.752.43.13 Heimdal GSS-API Extentions */ extern GSSAPI_LIB_VARIABLE gss_OID_desc __gss_krb5_copy_ccache_x_oid_desc; #define GSS_KRB5_COPY_CCACHE_X (&__gss_krb5_copy_ccache_x_oid_desc) extern GSSAPI_LIB_VARIABLE gss_OID_desc __gss_krb5_get_tkt_flags_x_oid_desc; #define GSS_KRB5_GET_TKT_FLAGS_X (&__gss_krb5_get_tkt_flags_x_oid_desc) extern GSSAPI_LIB_VARIABLE gss_OID_desc __gss_krb5_extract_authz_data_from_sec_context_x_oid_desc; #define GSS_KRB5_EXTRACT_AUTHZ_DATA_FROM_SEC_CONTEXT_X (&__gss_krb5_extract_authz_data_from_sec_context_x_oid_desc) extern GSSAPI_LIB_VARIABLE gss_OID_desc __gss_krb5_compat_des3_mic_x_oid_desc; #define GSS_KRB5_COMPAT_DES3_MIC_X (&__gss_krb5_compat_des3_mic_x_oid_desc) extern GSSAPI_LIB_VARIABLE gss_OID_desc __gss_krb5_register_acceptor_identity_x_oid_desc; #define GSS_KRB5_REGISTER_ACCEPTOR_IDENTITY_X (&__gss_krb5_register_acceptor_identity_x_oid_desc) extern GSSAPI_LIB_VARIABLE gss_OID_desc __gss_krb5_export_lucid_context_x_oid_desc; #define GSS_KRB5_EXPORT_LUCID_CONTEXT_X (&__gss_krb5_export_lucid_context_x_oid_desc) extern GSSAPI_LIB_VARIABLE gss_OID_desc __gss_krb5_export_lucid_context_v1_x_oid_desc; #define GSS_KRB5_EXPORT_LUCID_CONTEXT_V1_X (&__gss_krb5_export_lucid_context_v1_x_oid_desc) extern GSSAPI_LIB_VARIABLE gss_OID_desc __gss_krb5_set_dns_canonicalize_x_oid_desc; #define GSS_KRB5_SET_DNS_CANONICALIZE_X (&__gss_krb5_set_dns_canonicalize_x_oid_desc) extern GSSAPI_LIB_VARIABLE gss_OID_desc __gss_krb5_get_subkey_x_oid_desc; #define GSS_KRB5_GET_SUBKEY_X (&__gss_krb5_get_subkey_x_oid_desc) extern GSSAPI_LIB_VARIABLE gss_OID_desc __gss_krb5_get_initiator_subkey_x_oid_desc; #define GSS_KRB5_GET_INITIATOR_SUBKEY_X (&__gss_krb5_get_initiator_subkey_x_oid_desc) extern GSSAPI_LIB_VARIABLE gss_OID_desc __gss_krb5_get_acceptor_subkey_x_oid_desc; #define GSS_KRB5_GET_ACCEPTOR_SUBKEY_X (&__gss_krb5_get_acceptor_subkey_x_oid_desc) extern GSSAPI_LIB_VARIABLE gss_OID_desc __gss_krb5_send_to_kdc_x_oid_desc; #define GSS_KRB5_SEND_TO_KDC_X (&__gss_krb5_send_to_kdc_x_oid_desc) extern GSSAPI_LIB_VARIABLE gss_OID_desc __gss_krb5_get_authtime_x_oid_desc; #define GSS_KRB5_GET_AUTHTIME_X (&__gss_krb5_get_authtime_x_oid_desc) extern GSSAPI_LIB_VARIABLE gss_OID_desc __gss_krb5_get_service_keyblock_x_oid_desc; #define GSS_KRB5_GET_SERVICE_KEYBLOCK_X (&__gss_krb5_get_service_keyblock_x_oid_desc) extern GSSAPI_LIB_VARIABLE gss_OID_desc __gss_krb5_set_allowable_enctypes_x_oid_desc; #define GSS_KRB5_SET_ALLOWABLE_ENCTYPES_X (&__gss_krb5_set_allowable_enctypes_x_oid_desc) extern GSSAPI_LIB_VARIABLE gss_OID_desc __gss_krb5_set_default_realm_x_oid_desc; #define GSS_KRB5_SET_DEFAULT_REALM_X (&__gss_krb5_set_default_realm_x_oid_desc) extern GSSAPI_LIB_VARIABLE gss_OID_desc __gss_krb5_ccache_name_x_oid_desc; #define GSS_KRB5_CCACHE_NAME_X (&__gss_krb5_ccache_name_x_oid_desc) extern GSSAPI_LIB_VARIABLE gss_OID_desc __gss_krb5_set_time_offset_x_oid_desc; #define GSS_KRB5_SET_TIME_OFFSET_X (&__gss_krb5_set_time_offset_x_oid_desc) extern GSSAPI_LIB_VARIABLE gss_OID_desc __gss_krb5_get_time_offset_x_oid_desc; #define GSS_KRB5_GET_TIME_OFFSET_X (&__gss_krb5_get_time_offset_x_oid_desc) extern GSSAPI_LIB_VARIABLE gss_OID_desc __gss_krb5_plugin_register_x_oid_desc; #define GSS_KRB5_PLUGIN_REGISTER_X (&__gss_krb5_plugin_register_x_oid_desc) extern GSSAPI_LIB_VARIABLE gss_OID_desc __gss_ntlm_get_session_key_x_oid_desc; #define GSS_NTLM_GET_SESSION_KEY_X (&__gss_ntlm_get_session_key_x_oid_desc) extern GSSAPI_LIB_VARIABLE gss_OID_desc __gss_c_nt_ntlm_oid_desc; #define GSS_C_NT_NTLM (&__gss_c_nt_ntlm_oid_desc) extern GSSAPI_LIB_VARIABLE gss_OID_desc __gss_c_nt_dn_oid_desc; #define GSS_C_NT_DN (&__gss_c_nt_dn_oid_desc) extern GSSAPI_LIB_VARIABLE gss_OID_desc __gss_krb5_nt_principal_name_referral_oid_desc; #define GSS_KRB5_NT_PRINCIPAL_NAME_REFERRAL (&__gss_krb5_nt_principal_name_referral_oid_desc) extern GSSAPI_LIB_VARIABLE gss_OID_desc __gss_c_ntlm_avguest_oid_desc; #define GSS_C_NTLM_AVGUEST (&__gss_c_ntlm_avguest_oid_desc) extern GSSAPI_LIB_VARIABLE gss_OID_desc __gss_c_ntlm_v1_oid_desc; #define GSS_C_NTLM_V1 (&__gss_c_ntlm_v1_oid_desc) extern GSSAPI_LIB_VARIABLE gss_OID_desc __gss_c_ntlm_v2_oid_desc; #define GSS_C_NTLM_V2 (&__gss_c_ntlm_v2_oid_desc) extern GSSAPI_LIB_VARIABLE gss_OID_desc __gss_c_ntlm_session_key_oid_desc; #define GSS_C_NTLM_SESSION_KEY (&__gss_c_ntlm_session_key_oid_desc) extern GSSAPI_LIB_VARIABLE gss_OID_desc __gss_c_ntlm_force_v1_oid_desc; #define GSS_C_NTLM_FORCE_V1 (&__gss_c_ntlm_force_v1_oid_desc) extern GSSAPI_LIB_VARIABLE gss_OID_desc __gss_krb5_cred_no_ci_flags_x_oid_desc; #define GSS_KRB5_CRED_NO_CI_FLAGS_X (&__gss_krb5_cred_no_ci_flags_x_oid_desc) extern GSSAPI_LIB_VARIABLE gss_OID_desc __gss_krb5_import_cred_x_oid_desc; #define GSS_KRB5_IMPORT_CRED_X (&__gss_krb5_import_cred_x_oid_desc) /* glue for gss_inquire_saslname_for_mech */ extern GSSAPI_LIB_VARIABLE gss_OID_desc __gss_c_ma_sasl_mech_name_oid_desc; #define GSS_C_MA_SASL_MECH_NAME (&__gss_c_ma_sasl_mech_name_oid_desc) extern GSSAPI_LIB_VARIABLE gss_OID_desc __gss_c_ma_mech_name_oid_desc; #define GSS_C_MA_MECH_NAME (&__gss_c_ma_mech_name_oid_desc) extern GSSAPI_LIB_VARIABLE gss_OID_desc __gss_c_ma_mech_description_oid_desc; #define GSS_C_MA_MECH_DESCRIPTION (&__gss_c_ma_mech_description_oid_desc) /* credential types */ extern GSSAPI_LIB_VARIABLE gss_OID_desc __gss_c_cred_password_oid_desc; #define GSS_C_CRED_PASSWORD (&__gss_c_cred_password_oid_desc) extern GSSAPI_LIB_VARIABLE gss_OID_desc __gss_c_cred_certificate_oid_desc; #define GSS_C_CRED_CERTIFICATE (&__gss_c_cred_certificate_oid_desc) /* Heimdal mechanisms - 1.2.752.43.14 */ extern GSSAPI_LIB_VARIABLE gss_OID_desc __gss_sasl_digest_md5_mechanism_oid_desc; #define GSS_SASL_DIGEST_MD5_MECHANISM (&__gss_sasl_digest_md5_mechanism_oid_desc) extern GSSAPI_LIB_VARIABLE gss_OID_desc __gss_netlogon_mechanism_oid_desc; #define GSS_NETLOGON_MECHANISM (&__gss_netlogon_mechanism_oid_desc) extern GSSAPI_LIB_VARIABLE gss_OID_desc __gss_netlogon_set_session_key_x_oid_desc; #define GSS_NETLOGON_SET_SESSION_KEY_X (&__gss_netlogon_set_session_key_x_oid_desc) extern GSSAPI_LIB_VARIABLE gss_OID_desc __gss_netlogon_set_sign_algorithm_x_oid_desc; #define GSS_NETLOGON_SET_SIGN_ALGORITHM_X (&__gss_netlogon_set_sign_algorithm_x_oid_desc) extern GSSAPI_LIB_VARIABLE gss_OID_desc __gss_netlogon_nt_netbios_dns_name_oid_desc; #define GSS_NETLOGON_NT_NETBIOS_DNS_NAME (&__gss_netlogon_nt_netbios_dns_name_oid_desc) /* GSS_KRB5_EXTRACT_AUTHZ_DATA_FROM_SEC_CONTEXT_X.128 */ extern GSSAPI_LIB_VARIABLE gss_OID_desc __gss_c_inq_win2k_pac_x_oid_desc; #define GSS_C_INQ_WIN2K_PAC_X (&__gss_c_inq_win2k_pac_x_oid_desc) extern GSSAPI_LIB_VARIABLE gss_OID_desc __gss_c_inq_sspi_session_key_oid_desc; #define GSS_C_INQ_SSPI_SESSION_KEY (&__gss_c_inq_sspi_session_key_oid_desc) /* * "Standard" mechs */ extern GSSAPI_LIB_VARIABLE gss_OID_desc __gss_krb5_mechanism_oid_desc; #define GSS_KRB5_MECHANISM (&__gss_krb5_mechanism_oid_desc) extern GSSAPI_LIB_VARIABLE gss_OID_desc __gss_ntlm_mechanism_oid_desc; #define GSS_NTLM_MECHANISM (&__gss_ntlm_mechanism_oid_desc) extern GSSAPI_LIB_VARIABLE gss_OID_desc __gss_spnego_mechanism_oid_desc; #define GSS_SPNEGO_MECHANISM (&__gss_spnego_mechanism_oid_desc) /* From Luke Howard */ extern GSSAPI_LIB_VARIABLE gss_OID_desc __gss_c_peer_has_updated_spnego_oid_desc; #define GSS_C_PEER_HAS_UPDATED_SPNEGO (&__gss_c_peer_has_updated_spnego_oid_desc) /* * OID mappings with name and short description and and slightly longer description */ /* * RFC5587 */ extern GSSAPI_LIB_VARIABLE gss_OID_desc __gss_c_ma_mech_concrete_oid_desc; #define GSS_C_MA_MECH_CONCRETE (&__gss_c_ma_mech_concrete_oid_desc) extern GSSAPI_LIB_VARIABLE gss_OID_desc __gss_c_ma_mech_pseudo_oid_desc; #define GSS_C_MA_MECH_PSEUDO (&__gss_c_ma_mech_pseudo_oid_desc) extern GSSAPI_LIB_VARIABLE gss_OID_desc __gss_c_ma_mech_composite_oid_desc; #define GSS_C_MA_MECH_COMPOSITE (&__gss_c_ma_mech_composite_oid_desc) extern GSSAPI_LIB_VARIABLE gss_OID_desc __gss_c_ma_mech_nego_oid_desc; #define GSS_C_MA_MECH_NEGO (&__gss_c_ma_mech_nego_oid_desc) extern GSSAPI_LIB_VARIABLE gss_OID_desc __gss_c_ma_mech_glue_oid_desc; #define GSS_C_MA_MECH_GLUE (&__gss_c_ma_mech_glue_oid_desc) extern GSSAPI_LIB_VARIABLE gss_OID_desc __gss_c_ma_not_mech_oid_desc; #define GSS_C_MA_NOT_MECH (&__gss_c_ma_not_mech_oid_desc) extern GSSAPI_LIB_VARIABLE gss_OID_desc __gss_c_ma_deprecated_oid_desc; #define GSS_C_MA_DEPRECATED (&__gss_c_ma_deprecated_oid_desc) extern GSSAPI_LIB_VARIABLE gss_OID_desc __gss_c_ma_not_dflt_mech_oid_desc; #define GSS_C_MA_NOT_DFLT_MECH (&__gss_c_ma_not_dflt_mech_oid_desc) extern GSSAPI_LIB_VARIABLE gss_OID_desc __gss_c_ma_itok_framed_oid_desc; #define GSS_C_MA_ITOK_FRAMED (&__gss_c_ma_itok_framed_oid_desc) extern GSSAPI_LIB_VARIABLE gss_OID_desc __gss_c_ma_auth_init_oid_desc; #define GSS_C_MA_AUTH_INIT (&__gss_c_ma_auth_init_oid_desc) extern GSSAPI_LIB_VARIABLE gss_OID_desc __gss_c_ma_auth_targ_oid_desc; #define GSS_C_MA_AUTH_TARG (&__gss_c_ma_auth_targ_oid_desc) extern GSSAPI_LIB_VARIABLE gss_OID_desc __gss_c_ma_auth_init_init_oid_desc; #define GSS_C_MA_AUTH_INIT_INIT (&__gss_c_ma_auth_init_init_oid_desc) extern GSSAPI_LIB_VARIABLE gss_OID_desc __gss_c_ma_auth_targ_init_oid_desc; #define GSS_C_MA_AUTH_TARG_INIT (&__gss_c_ma_auth_targ_init_oid_desc) extern GSSAPI_LIB_VARIABLE gss_OID_desc __gss_c_ma_auth_init_anon_oid_desc; #define GSS_C_MA_AUTH_INIT_ANON (&__gss_c_ma_auth_init_anon_oid_desc) extern GSSAPI_LIB_VARIABLE gss_OID_desc __gss_c_ma_auth_targ_anon_oid_desc; #define GSS_C_MA_AUTH_TARG_ANON (&__gss_c_ma_auth_targ_anon_oid_desc) extern GSSAPI_LIB_VARIABLE gss_OID_desc __gss_c_ma_deleg_cred_oid_desc; #define GSS_C_MA_DELEG_CRED (&__gss_c_ma_deleg_cred_oid_desc) extern GSSAPI_LIB_VARIABLE gss_OID_desc __gss_c_ma_integ_prot_oid_desc; #define GSS_C_MA_INTEG_PROT (&__gss_c_ma_integ_prot_oid_desc) extern GSSAPI_LIB_VARIABLE gss_OID_desc __gss_c_ma_conf_prot_oid_desc; #define GSS_C_MA_CONF_PROT (&__gss_c_ma_conf_prot_oid_desc) extern GSSAPI_LIB_VARIABLE gss_OID_desc __gss_c_ma_mic_oid_desc; #define GSS_C_MA_MIC (&__gss_c_ma_mic_oid_desc) extern GSSAPI_LIB_VARIABLE gss_OID_desc __gss_c_ma_wrap_oid_desc; #define GSS_C_MA_WRAP (&__gss_c_ma_wrap_oid_desc) extern GSSAPI_LIB_VARIABLE gss_OID_desc __gss_c_ma_prot_ready_oid_desc; #define GSS_C_MA_PROT_READY (&__gss_c_ma_prot_ready_oid_desc) extern GSSAPI_LIB_VARIABLE gss_OID_desc __gss_c_ma_replay_det_oid_desc; #define GSS_C_MA_REPLAY_DET (&__gss_c_ma_replay_det_oid_desc) extern GSSAPI_LIB_VARIABLE gss_OID_desc __gss_c_ma_oos_det_oid_desc; #define GSS_C_MA_OOS_DET (&__gss_c_ma_oos_det_oid_desc) extern GSSAPI_LIB_VARIABLE gss_OID_desc __gss_c_ma_cbindings_oid_desc; #define GSS_C_MA_CBINDINGS (&__gss_c_ma_cbindings_oid_desc) extern GSSAPI_LIB_VARIABLE gss_OID_desc __gss_c_ma_pfs_oid_desc; #define GSS_C_MA_PFS (&__gss_c_ma_pfs_oid_desc) extern GSSAPI_LIB_VARIABLE gss_OID_desc __gss_c_ma_compress_oid_desc; #define GSS_C_MA_COMPRESS (&__gss_c_ma_compress_oid_desc) extern GSSAPI_LIB_VARIABLE gss_OID_desc __gss_c_ma_ctx_trans_oid_desc; #define GSS_C_MA_CTX_TRANS (&__gss_c_ma_ctx_trans_oid_desc) #endif /* GSSAPI_GSSAPI_OID */ heimdal-7.5.0/lib/gssapi/gssapi/gssapi_ntlm.h0000644000175000017500000000333213026237312017265 0ustar niknik/* * Copyright (c) 2006 - 2009 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ /* $Id$ */ #ifndef GSSAPI_NTLM_H_ #define GSSAPI_NTLM_H_ #include #endif /* GSSAPI_NTLM_H_ */ heimdal-7.5.0/lib/gssapi/test_cred.c0000644000175000017500000001407313026237312015432 0ustar niknik/* * Copyright (c) 2003-2004 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of KTH nor the names of its contributors may be * used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY KTH AND ITS CONTRIBUTORS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL KTH OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifdef HAVE_CONFIG_H #include #endif #include #include #include #include #include #include #include #include #include #include static void gss_print_errors (int min_stat) { OM_uint32 new_stat; OM_uint32 msg_ctx = 0; gss_buffer_desc status_string; OM_uint32 ret; do { ret = gss_display_status (&new_stat, min_stat, GSS_C_MECH_CODE, GSS_C_NO_OID, &msg_ctx, &status_string); if (!GSS_ERROR(ret)) { fprintf (stderr, "%.*s\n", (int)status_string.length, (char *)status_string.value); gss_release_buffer (&new_stat, &status_string); } } while (!GSS_ERROR(ret) && msg_ctx != 0); } static void gss_err(int exitval, int status, const char *fmt, ...) { va_list args; va_start(args, fmt); vwarnx (fmt, args); gss_print_errors (status); va_end(args); exit (exitval); } static void acquire_release_loop(gss_name_t name, int counter, gss_cred_usage_t usage) { OM_uint32 maj_stat, min_stat; gss_cred_id_t cred; int i; for (i = 0; i < counter; i++) { maj_stat = gss_acquire_cred(&min_stat, name, GSS_C_INDEFINITE, GSS_C_NO_OID_SET, usage, &cred, NULL, NULL); if (maj_stat != GSS_S_COMPLETE) gss_err(1, min_stat, "aquire %d %d != GSS_S_COMPLETE", i, (int)maj_stat); maj_stat = gss_release_cred(&min_stat, &cred); if (maj_stat != GSS_S_COMPLETE) gss_err(1, min_stat, "release %d %d != GSS_S_COMPLETE", i, (int)maj_stat); } } static void acquire_add_release_add(gss_name_t name, gss_cred_usage_t usage) { OM_uint32 maj_stat, min_stat; gss_cred_id_t cred, cred2, cred3; maj_stat = gss_acquire_cred(&min_stat, name, GSS_C_INDEFINITE, GSS_C_NO_OID_SET, usage, &cred, NULL, NULL); if (maj_stat != GSS_S_COMPLETE) gss_err(1, min_stat, "aquire %d != GSS_S_COMPLETE", (int)maj_stat); maj_stat = gss_add_cred(&min_stat, cred, GSS_C_NO_NAME, GSS_KRB5_MECHANISM, usage, GSS_C_INDEFINITE, GSS_C_INDEFINITE, &cred2, NULL, NULL, NULL); if (maj_stat != GSS_S_COMPLETE) gss_err(1, min_stat, "add_cred %d != GSS_S_COMPLETE", (int)maj_stat); maj_stat = gss_release_cred(&min_stat, &cred); if (maj_stat != GSS_S_COMPLETE) gss_err(1, min_stat, "release %d != GSS_S_COMPLETE", (int)maj_stat); maj_stat = gss_add_cred(&min_stat, cred2, GSS_C_NO_NAME, GSS_KRB5_MECHANISM, GSS_C_BOTH, GSS_C_INDEFINITE, GSS_C_INDEFINITE, &cred3, NULL, NULL, NULL); if (maj_stat != GSS_S_COMPLETE) gss_err(1, min_stat, "add_cred 2 %d != GSS_S_COMPLETE", (int)maj_stat); maj_stat = gss_release_cred(&min_stat, &cred2); if (maj_stat != GSS_S_COMPLETE) gss_err(1, min_stat, "release 2 %d != GSS_S_COMPLETE", (int)maj_stat); maj_stat = gss_release_cred(&min_stat, &cred3); if (maj_stat != GSS_S_COMPLETE) gss_err(1, min_stat, "release 3 %d != GSS_S_COMPLETE", (int)maj_stat); } static int version_flag = 0; static int help_flag = 0; static struct getargs args[] = { {"version", 0, arg_flag, &version_flag, "print version", NULL }, {"help", 0, arg_flag, &help_flag, NULL, NULL } }; static void usage (int ret) { arg_printusage (args, sizeof(args)/sizeof(*args), NULL, "service@host"); exit (ret); } int main(int argc, char **argv) { struct gss_buffer_desc_struct name_buffer; OM_uint32 maj_stat, min_stat; gss_name_t name; int optidx = 0; setprogname(argv[0]); if(getarg(args, sizeof(args) / sizeof(args[0]), argc, argv, &optidx)) usage(1); if (help_flag) usage (0); if(version_flag){ print_version(NULL); exit(0); } argc -= optidx; argv += optidx; if (argc < 1) errx(1, "argc < 1"); name_buffer.value = argv[0]; name_buffer.length = strlen(argv[0]); maj_stat = gss_import_name(&min_stat, &name_buffer, GSS_C_NT_HOSTBASED_SERVICE, &name); if (maj_stat != GSS_S_COMPLETE) errx(1, "import name error"); acquire_release_loop(name, 100, GSS_C_ACCEPT); acquire_release_loop(name, 100, GSS_C_INITIATE); acquire_release_loop(name, 100, GSS_C_BOTH); acquire_add_release_add(name, GSS_C_ACCEPT); acquire_add_release_add(name, GSS_C_INITIATE); acquire_add_release_add(name, GSS_C_BOTH); gss_release_name(&min_stat, &name); return 0; } heimdal-7.5.0/lib/gssapi/version-script.map0000644000175000017500000001312413026237312016774 0ustar niknik# $Id$ HEIMDAL_GSS_2.0 { global: # __gss_c_nt_anonymous; __gss_c_nt_anonymous_oid_desc; __gss_c_nt_export_name_oid_desc; __gss_c_nt_hostbased_service_oid_desc; __gss_c_nt_hostbased_service_x_oid_desc; __gss_c_nt_machine_uid_name_oid_desc; __gss_c_nt_string_uid_name_oid_desc; __gss_c_nt_user_name_oid_desc; __gss_krb5_nt_principal_name_oid_desc; __gss_c_attr_stream_sizes_oid_desc; __gss_c_cred_password_oid_desc; __gss_c_cred_certificate_oid_desc; __gss_c_attr_local_login_user; gss_accept_sec_context; gss_acquire_cred; gss_acquire_cred_with_password; gss_add_buffer_set_member; gss_add_cred; gss_add_cred_with_password; gss_add_oid_set_member; gss_authorize_localname; gss_canonicalize_name; gss_compare_name; gss_context_query_attributes; gss_context_time; gss_create_empty_buffer_set; gss_create_empty_oid_set; gss_decapsulate_token; gss_delete_name_attribute; gss_delete_sec_context; gss_display_name; gss_display_name_ext; gss_display_status; gss_duplicate_name; gss_duplicate_oid; gss_encapsulate_token; gss_export_cred; gss_export_name; gss_export_name_composite; gss_export_sec_context; gss_get_mic; gss_get_name_attribute; gss_import_cred; gss_import_name; gss_import_sec_context; gss_indicate_mechs; gss_init_sec_context; gss_inquire_context; gss_inquire_cred; gss_inquire_cred_by_mech; gss_inquire_cred_by_oid; gss_inquire_mechs_for_name; gss_inquire_name; gss_inquire_names_for_mech; gss_inquire_sec_context_by_oid; gss_inquire_sec_context_by_oid; gss_krb5_ccache_name; gss_krb5_copy_ccache; gss_krb5_export_lucid_sec_context; gss_krb5_free_lucid_sec_context; gss_krb5_get_tkt_flags; gss_krb5_import_cred; gss_krb5_set_allowable_enctypes; gss_localname; gss_mg_collect_error; gss_oid_equal; gss_oid_to_str; gss_pname_to_uid; gss_process_context_token; gss_pseudo_random; gss_release_buffer; gss_release_buffer_set; gss_release_cred; gss_release_iov_buffer; gss_release_name; gss_release_oid; gss_release_oid_set; gss_seal; gss_set_cred_option; gss_set_name_attribute; gss_set_sec_context_option; gss_sign; gss_store_cred; gss_test_oid_set_member; gss_unseal; gss_unwrap; gss_unwrap_aead; gss_unwrap_iov; gss_userok; gss_verify; gss_verify_mic; gss_wrap; gss_wrap_aead; gss_wrap_iov; gss_wrap_iov_length; gss_wrap_size_limit; gsskrb5_extract_authtime_from_sec_context; gsskrb5_extract_authz_data_from_sec_context; gsskrb5_extract_service_keyblock; gsskrb5_get_initiator_subkey; gsskrb5_get_subkey; gsskrb5_get_time_offset; gsskrb5_register_acceptor_identity; gsskrb5_set_default_realm; gsskrb5_set_dns_canonicalize; gsskrb5_set_send_to_kdc; gsskrb5_set_time_offset; krb5_gss_register_acceptor_identity; gss_display_mech_attr; gss_inquire_attrs_for_mech; gss_indicate_mechs_by_attrs; gss_inquire_mech_for_saslname; gss_inquire_saslname_for_mech; gss_mo_get; gss_mo_set; gss_mo_list; gss_mo_name; gss_name_to_oid; gss_oid_to_name; # _gsskrb5cfx_ are really internal symbols, but export # then now to make testing easier. _gsskrb5cfx_wrap_length_cfx; _gssapi_wrap_size_cfx; __gss_krb5_copy_ccache_x_oid_desc; __gss_krb5_get_tkt_flags_x_oid_desc; __gss_krb5_extract_authz_data_from_sec_context_x_oid_desc; __gss_krb5_compat_des3_mic_x_oid_desc; __gss_krb5_register_acceptor_identity_x_oid_desc; __gss_krb5_export_lucid_context_x_oid_desc; __gss_krb5_export_lucid_context_v1_x_oid_desc; __gss_krb5_set_dns_canonicalize_x_oid_desc; __gss_krb5_get_subkey_x_oid_desc; __gss_krb5_get_initiator_subkey_x_oid_desc; __gss_krb5_get_acceptor_subkey_x_oid_desc; __gss_krb5_send_to_kdc_x_oid_desc; __gss_krb5_get_authtime_x_oid_desc; __gss_krb5_get_service_keyblock_x_oid_desc; __gss_krb5_set_allowable_enctypes_x_oid_desc; __gss_krb5_set_default_realm_x_oid_desc; __gss_krb5_ccache_name_x_oid_desc; __gss_krb5_set_time_offset_x_oid_desc; __gss_krb5_get_time_offset_x_oid_desc; __gss_krb5_plugin_register_x_oid_desc; __gss_ntlm_get_session_key_x_oid_desc; __gss_c_nt_ntlm_oid_desc; __gss_c_nt_dn_oid_desc; __gss_krb5_nt_principal_name_referral_oid_desc; __gss_c_ntlm_avguest_oid_desc; __gss_c_ntlm_v1_oid_desc; __gss_c_ntlm_v2_oid_desc; __gss_c_ntlm_session_key_oid_desc; __gss_c_ntlm_force_v1_oid_desc; __gss_krb5_cred_no_ci_flags_x_oid_desc; __gss_krb5_import_cred_x_oid_desc; __gss_c_ma_sasl_mech_name_oid_desc; __gss_c_ma_mech_name_oid_desc; __gss_c_ma_mech_description_oid_desc; __gss_sasl_digest_md5_mechanism_oid_desc; __gss_krb5_mechanism_oid_desc; __gss_ntlm_mechanism_oid_desc; __gss_spnego_mechanism_oid_desc; __gss_c_peer_has_updated_spnego_oid_desc; __gss_c_ma_mech_concrete_oid_desc; __gss_c_ma_mech_pseudo_oid_desc; __gss_c_ma_mech_composite_oid_desc; __gss_c_ma_mech_nego_oid_desc; __gss_c_ma_mech_glue_oid_desc; __gss_c_ma_not_mech_oid_desc; __gss_c_ma_deprecated_oid_desc; __gss_c_ma_not_dflt_mech_oid_desc; __gss_c_ma_itok_framed_oid_desc; __gss_c_ma_auth_init_oid_desc; __gss_c_ma_auth_targ_oid_desc; __gss_c_ma_auth_init_init_oid_desc; __gss_c_ma_auth_targ_init_oid_desc; __gss_c_ma_auth_init_anon_oid_desc; __gss_c_ma_auth_targ_anon_oid_desc; __gss_c_ma_deleg_cred_oid_desc; __gss_c_ma_integ_prot_oid_desc; __gss_c_ma_conf_prot_oid_desc; __gss_c_ma_mic_oid_desc; __gss_c_ma_wrap_oid_desc; __gss_c_ma_prot_ready_oid_desc; __gss_c_ma_replay_det_oid_desc; __gss_c_ma_oos_det_oid_desc; __gss_c_ma_cbindings_oid_desc; __gss_c_ma_pfs_oid_desc; __gss_c_ma_compress_oid_desc; __gss_c_ma_ctx_trans_oid_desc; local: *; }; heimdal-7.5.0/lib/gssapi/test_oid.c0000644000175000017500000000466513026237312015276 0ustar niknik/* * Copyright (c) 2006 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #ifdef HAVE_CONFIG_H #include #endif #include #include #include #include #include #include int main(int argc, char **argv) { OM_uint32 minor_status, maj_stat; gss_buffer_desc data; int ret; maj_stat = gss_oid_to_str(&minor_status, GSS_KRB5_MECHANISM, &data); if (GSS_ERROR(maj_stat)) errx(1, "gss_oid_to_str failed"); ret = strncmp(data.value, "1 2 840 113554 1 2 2", data.length); gss_release_buffer(&maj_stat, &data); if (ret) return 1; maj_stat = gss_oid_to_str(&minor_status, GSS_C_NT_EXPORT_NAME, &data); if (GSS_ERROR(maj_stat)) errx(1, "gss_oid_to_str failed"); ret = strncmp(data.value, "1 3 6 1 5 6 4", data.length); gss_release_buffer(&maj_stat, &data); if (ret) return 1; return 0; } heimdal-7.5.0/lib/gssapi/test_kcred.c0000644000175000017500000001231213026237312015577 0ustar niknik/* * Copyright (c) 2003-2004 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of KTH nor the names of its contributors may be * used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY KTH AND ITS CONTRIBUTORS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL KTH OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifdef HAVE_CONFIG_H #include #endif #include #include #include #include #include #include #include #include #include #include #include static int version_flag = 0; static int help_flag = 0; static void copy_import(void) { gss_cred_id_t cred1, cred2; OM_uint32 maj_stat, min_stat; gss_name_t name1, name2; OM_uint32 lifetime1, lifetime2; gss_cred_usage_t usage1, usage2; gss_OID_set mechs1, mechs2; krb5_ccache id; krb5_error_code ret; krb5_context context; int equal; maj_stat = gss_acquire_cred(&min_stat, GSS_C_NO_NAME, GSS_C_INDEFINITE, GSS_C_NO_OID_SET, GSS_C_INITIATE, &cred1, NULL, NULL); if (maj_stat != GSS_S_COMPLETE) errx(1, "gss_acquire_cred"); maj_stat = gss_inquire_cred(&min_stat, cred1, &name1, &lifetime1, &usage1, &mechs1); if (maj_stat != GSS_S_COMPLETE) errx(1, "gss_inquire_cred"); ret = krb5_init_context(&context); if (ret) errx(1, "krb5_init_context"); ret = krb5_cc_new_unique(context, krb5_cc_type_memory, NULL, &id); if (ret) krb5_err(context, 1, ret, "krb5_cc_new_unique"); maj_stat = gss_krb5_copy_ccache(&min_stat, cred1, id); if (maj_stat != GSS_S_COMPLETE) errx(1, "gss_krb5_copy_ccache"); maj_stat = gss_krb5_import_cred(&min_stat, id, NULL, NULL, &cred2); if (maj_stat != GSS_S_COMPLETE) errx(1, "gss_krb5_import_cred"); maj_stat = gss_inquire_cred(&min_stat, cred2, &name2, &lifetime2, &usage2, &mechs2); if (maj_stat != GSS_S_COMPLETE) errx(1, "gss_inquire_cred 2"); maj_stat = gss_compare_name(&min_stat, name1, name2, &equal); if (maj_stat != GSS_S_COMPLETE) errx(1, "gss_compare_name"); if (!equal) errx(1, "names not equal"); if (lifetime1 != lifetime2) errx(1, "lifetime not equal %lu != %lu", (unsigned long)lifetime1, (unsigned long)lifetime2); if (usage1 != usage2) { /* as long any of them is both are everything it ok */ if (usage1 != GSS_C_BOTH && usage2 != GSS_C_BOTH) errx(1, "usages disjoined"); } gss_release_name(&min_stat, &name2); gss_release_oid_set(&min_stat, &mechs2); maj_stat = gss_inquire_cred(&min_stat, cred2, &name2, &lifetime2, &usage2, &mechs2); if (maj_stat != GSS_S_COMPLETE) errx(1, "gss_inquire_cred"); maj_stat = gss_compare_name(&min_stat, name1, name2, &equal); if (maj_stat != GSS_S_COMPLETE) errx(1, "gss_compare_name"); if (!equal) errx(1, "names not equal"); if (lifetime1 != lifetime2) errx(1, "lifetime not equal %lu != %lu", (unsigned long)lifetime1, (unsigned long)lifetime2); gss_release_cred(&min_stat, &cred1); gss_release_cred(&min_stat, &cred2); gss_release_name(&min_stat, &name1); gss_release_name(&min_stat, &name2); #if 0 compare(mechs1, mechs2); #endif gss_release_oid_set(&min_stat, &mechs1); gss_release_oid_set(&min_stat, &mechs2); krb5_cc_destroy(context, id); krb5_free_context(context); } static struct getargs args[] = { {"version", 0, arg_flag, &version_flag, "print version", NULL }, {"help", 0, arg_flag, &help_flag, NULL, NULL } }; static void usage (int ret) { arg_printusage (args, sizeof(args)/sizeof(*args), NULL, ""); exit (ret); } int main(int argc, char **argv) { int optidx = 0; setprogname(argv[0]); if(getarg(args, sizeof(args) / sizeof(args[0]), argc, argv, &optidx)) usage(1); if (help_flag) usage (0); if(version_flag){ print_version(NULL); exit(0); } argc -= optidx; argv += optidx; copy_import(); return 0; } heimdal-7.5.0/lib/gssapi/gssapi.h0000644000175000017500000000327312136107747014762 0ustar niknik/* * Copyright (c) 2006 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ /* $Id$ */ #ifndef GSSAPI_H_ #define GSSAPI_H_ #include #endif heimdal-7.5.0/lib/gssapi/krb5/0000755000175000017500000000000013214604041014144 5ustar niknikheimdal-7.5.0/lib/gssapi/krb5/encapsulate.c0000644000175000017500000001006613026237312016623 0ustar niknik/* * Copyright (c) 1997 - 2003 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "gsskrb5_locl.h" void _gssapi_encap_length (size_t data_len, size_t *len, size_t *total_len, const gss_OID mech) { size_t len_len; *len = 1 + 1 + mech->length + data_len; len_len = der_length_len(*len); *total_len = 1 + len_len + *len; } void _gsskrb5_encap_length (size_t data_len, size_t *len, size_t *total_len, const gss_OID mech) { _gssapi_encap_length(data_len + 2, len, total_len, mech); } void * _gsskrb5_make_header (void *ptr, size_t len, const void *type, const gss_OID mech) { u_char *p = ptr; p = _gssapi_make_mech_header(p, len, mech); memcpy (p, type, 2); p += 2; return p; } void * _gssapi_make_mech_header(void *ptr, size_t len, const gss_OID mech) { u_char *p = ptr; int e; size_t len_len, foo; *p++ = 0x60; len_len = der_length_len(len); e = der_put_length (p + len_len - 1, len_len, len, &foo); if(e || foo != len_len) abort (); p += len_len; *p++ = 0x06; *p++ = mech->length; memcpy (p, mech->elements, mech->length); p += mech->length; return p; } /* * Give it a krb5_data and it will encapsulate with extra GSS-API wrappings. */ OM_uint32 _gssapi_encapsulate( OM_uint32 *minor_status, const krb5_data *in_data, gss_buffer_t output_token, const gss_OID mech ) { size_t len, outer_len; void *p; _gssapi_encap_length (in_data->length, &len, &outer_len, mech); output_token->length = outer_len; output_token->value = malloc (outer_len); if (output_token->value == NULL) { *minor_status = ENOMEM; return GSS_S_FAILURE; } p = _gssapi_make_mech_header (output_token->value, len, mech); memcpy (p, in_data->data, in_data->length); return GSS_S_COMPLETE; } /* * Give it a krb5_data and it will encapsulate with extra GSS-API krb5 * wrappings. */ OM_uint32 _gsskrb5_encapsulate( OM_uint32 *minor_status, const krb5_data *in_data, gss_buffer_t output_token, const void *type, const gss_OID mech ) { size_t len, outer_len; u_char *p; _gsskrb5_encap_length (in_data->length, &len, &outer_len, mech); output_token->length = outer_len; output_token->value = malloc (outer_len); if (output_token->value == NULL) { *minor_status = ENOMEM; return GSS_S_FAILURE; } p = _gsskrb5_make_header (output_token->value, len, type, mech); memcpy (p, in_data->data, in_data->length); return GSS_S_COMPLETE; } heimdal-7.5.0/lib/gssapi/krb5/verify_mic.c0000644000175000017500000002314313212137553016456 0ustar niknik/* * Copyright (c) 1997 - 2003 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "gsskrb5_locl.h" #ifdef HEIM_WEAK_CRYPTO static OM_uint32 verify_mic_des (OM_uint32 * minor_status, const gsskrb5_ctx context_handle, krb5_context context, const gss_buffer_t message_buffer, const gss_buffer_t token_buffer, gss_qop_t * qop_state, krb5_keyblock *key, const char *type ) { u_char *p; EVP_MD_CTX *md5; u_char hash[16], *seq; DES_key_schedule schedule; EVP_CIPHER_CTX des_ctx; DES_cblock zero; DES_cblock deskey; uint32_t seq_number; OM_uint32 ret; int cmp; p = token_buffer->value; ret = _gsskrb5_verify_header (&p, token_buffer->length, type, GSS_KRB5_MECHANISM); if (ret) return ret; if (memcmp(p, "\x00\x00", 2) != 0) return GSS_S_BAD_SIG; p += 2; if (memcmp (p, "\xff\xff\xff\xff", 4) != 0) return GSS_S_BAD_MIC; p += 4; p += 16; /* verify checksum */ md5 = EVP_MD_CTX_create(); EVP_DigestInit_ex(md5, EVP_md5(), NULL); EVP_DigestUpdate(md5, p - 24, 8); EVP_DigestUpdate(md5, message_buffer->value, message_buffer->length); EVP_DigestFinal_ex(md5, hash, NULL); EVP_MD_CTX_destroy(md5); memset (&zero, 0, sizeof(zero)); memcpy (&deskey, key->keyvalue.data, sizeof(deskey)); DES_set_key_unchecked (&deskey, &schedule); DES_cbc_cksum ((void *)hash, (void *)hash, sizeof(hash), &schedule, &zero); if (ct_memcmp (p - 8, hash, 8) != 0) { memset (deskey, 0, sizeof(deskey)); memset (&schedule, 0, sizeof(schedule)); return GSS_S_BAD_MIC; } /* verify sequence number */ HEIMDAL_MUTEX_lock(&context_handle->ctx_id_mutex); p -= 16; EVP_CIPHER_CTX_init(&des_ctx); EVP_CipherInit_ex(&des_ctx, EVP_des_cbc(), NULL, key->keyvalue.data, hash, 0); EVP_Cipher(&des_ctx, p, p, 8); EVP_CIPHER_CTX_cleanup(&des_ctx); memset (deskey, 0, sizeof(deskey)); memset (&schedule, 0, sizeof(schedule)); seq = p; _gsskrb5_decode_om_uint32(seq, &seq_number); if (context_handle->more_flags & LOCAL) cmp = ct_memcmp(&seq[4], "\xff\xff\xff\xff", 4); else cmp = ct_memcmp(&seq[4], "\x00\x00\x00\x00", 4); if (cmp != 0) { HEIMDAL_MUTEX_unlock(&context_handle->ctx_id_mutex); return GSS_S_BAD_MIC; } ret = _gssapi_msg_order_check(context_handle->order, seq_number); if (ret) { HEIMDAL_MUTEX_unlock(&context_handle->ctx_id_mutex); return ret; } HEIMDAL_MUTEX_unlock(&context_handle->ctx_id_mutex); return GSS_S_COMPLETE; } #endif static OM_uint32 verify_mic_des3 (OM_uint32 * minor_status, const gsskrb5_ctx context_handle, krb5_context context, const gss_buffer_t message_buffer, const gss_buffer_t token_buffer, gss_qop_t * qop_state, krb5_keyblock *key, const char *type ) { u_char *p; u_char *seq; uint32_t seq_number; OM_uint32 ret; krb5_crypto crypto; krb5_data seq_data; int cmp, docompat; Checksum csum; char *tmp; char ivec[8]; p = token_buffer->value; ret = _gsskrb5_verify_header (&p, token_buffer->length, type, GSS_KRB5_MECHANISM); if (ret) return ret; if (memcmp(p, "\x04\x00", 2) != 0) /* SGN_ALG = HMAC SHA1 DES3-KD */ return GSS_S_BAD_SIG; p += 2; if (memcmp (p, "\xff\xff\xff\xff", 4) != 0) return GSS_S_BAD_MIC; p += 4; ret = krb5_crypto_init(context, key, ETYPE_DES3_CBC_NONE, &crypto); if (ret){ *minor_status = ret; return GSS_S_FAILURE; } /* verify sequence number */ docompat = 0; retry: if (docompat) memset(ivec, 0, 8); else memcpy(ivec, p + 8, 8); ret = krb5_decrypt_ivec (context, crypto, KRB5_KU_USAGE_SEQ, p, 8, &seq_data, ivec); if (ret) { if (docompat++) { krb5_crypto_destroy (context, crypto); *minor_status = ret; return GSS_S_FAILURE; } else goto retry; } if (seq_data.length != 8) { krb5_data_free (&seq_data); if (docompat++) { krb5_crypto_destroy (context, crypto); return GSS_S_BAD_MIC; } else goto retry; } HEIMDAL_MUTEX_lock(&context_handle->ctx_id_mutex); seq = seq_data.data; _gsskrb5_decode_om_uint32(seq, &seq_number); if (context_handle->more_flags & LOCAL) cmp = ct_memcmp(&seq[4], "\xff\xff\xff\xff", 4); else cmp = ct_memcmp(&seq[4], "\x00\x00\x00\x00", 4); krb5_data_free (&seq_data); if (cmp != 0) { krb5_crypto_destroy (context, crypto); *minor_status = 0; HEIMDAL_MUTEX_unlock(&context_handle->ctx_id_mutex); return GSS_S_BAD_MIC; } ret = _gssapi_msg_order_check(context_handle->order, seq_number); if (ret) { krb5_crypto_destroy (context, crypto); *minor_status = 0; HEIMDAL_MUTEX_unlock(&context_handle->ctx_id_mutex); return ret; } /* verify checksum */ tmp = malloc (message_buffer->length + 8); if (tmp == NULL) { krb5_crypto_destroy (context, crypto); HEIMDAL_MUTEX_unlock(&context_handle->ctx_id_mutex); *minor_status = ENOMEM; return GSS_S_FAILURE; } memcpy (tmp, p - 8, 8); memcpy (tmp + 8, message_buffer->value, message_buffer->length); csum.cksumtype = CKSUMTYPE_HMAC_SHA1_DES3; csum.checksum.length = 20; csum.checksum.data = p + 8; krb5_crypto_destroy (context, crypto); ret = krb5_crypto_init(context, key, ETYPE_DES3_CBC_SHA1, &crypto); if (ret == 0) ret = krb5_verify_checksum(context, crypto, KRB5_KU_USAGE_SIGN, tmp, message_buffer->length + 8, &csum); free (tmp); if (ret) { krb5_crypto_destroy (context, crypto); *minor_status = ret; HEIMDAL_MUTEX_unlock(&context_handle->ctx_id_mutex); return GSS_S_BAD_MIC; } HEIMDAL_MUTEX_unlock(&context_handle->ctx_id_mutex); krb5_crypto_destroy (context, crypto); return GSS_S_COMPLETE; } OM_uint32 _gsskrb5_verify_mic_internal (OM_uint32 * minor_status, const gsskrb5_ctx ctx, krb5_context context, const gss_buffer_t message_buffer, const gss_buffer_t token_buffer, gss_qop_t * qop_state, const char * type ) { krb5_keyblock *key; OM_uint32 ret; if (ctx->more_flags & IS_CFX) return _gssapi_verify_mic_cfx (minor_status, ctx, context, message_buffer, token_buffer, qop_state); HEIMDAL_MUTEX_lock(&ctx->ctx_id_mutex); ret = _gsskrb5i_get_token_key(ctx, context, &key); HEIMDAL_MUTEX_unlock(&ctx->ctx_id_mutex); if (ret) { *minor_status = ret; return GSS_S_FAILURE; } *minor_status = 0; switch (key->keytype) { case KRB5_ENCTYPE_DES_CBC_CRC : case KRB5_ENCTYPE_DES_CBC_MD4 : case KRB5_ENCTYPE_DES_CBC_MD5 : #ifdef HEIM_WEAK_CRYPTO ret = verify_mic_des (minor_status, ctx, context, message_buffer, token_buffer, qop_state, key, type); #else ret = GSS_S_FAILURE; #endif break; case KRB5_ENCTYPE_DES3_CBC_MD5 : case KRB5_ENCTYPE_DES3_CBC_SHA1 : ret = verify_mic_des3 (minor_status, ctx, context, message_buffer, token_buffer, qop_state, key, type); break; case KRB5_ENCTYPE_ARCFOUR_HMAC_MD5: case KRB5_ENCTYPE_ARCFOUR_HMAC_MD5_56: ret = _gssapi_verify_mic_arcfour (minor_status, ctx, context, message_buffer, token_buffer, qop_state, key, type); break; default : abort(); } krb5_free_keyblock (context, key); return ret; } OM_uint32 GSSAPI_CALLCONV _gsskrb5_verify_mic (OM_uint32 * minor_status, gss_const_ctx_id_t context_handle, const gss_buffer_t message_buffer, const gss_buffer_t token_buffer, gss_qop_t * qop_state ) { krb5_context context; OM_uint32 ret; GSSAPI_KRB5_INIT (&context); if (qop_state != NULL) *qop_state = GSS_C_QOP_DEFAULT; ret = _gsskrb5_verify_mic_internal(minor_status, (gsskrb5_ctx)context_handle, context, message_buffer, token_buffer, qop_state, (void *)(intptr_t)"\x01\x01"); return ret; } heimdal-7.5.0/lib/gssapi/krb5/inquire_sec_context_by_oid.c0000644000175000017500000003712113026237312021717 0ustar niknik/* * Copyright (c) 2004, PADL Software Pty Ltd. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of PADL Software nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY PADL SOFTWARE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL PADL SOFTWARE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "gsskrb5_locl.h" static int oid_prefix_equal(gss_OID oid_enc, gss_OID prefix_enc, unsigned *suffix) { int ret; heim_oid oid; heim_oid prefix; *suffix = 0; ret = der_get_oid(oid_enc->elements, oid_enc->length, &oid, NULL); if (ret) { return 0; } ret = der_get_oid(prefix_enc->elements, prefix_enc->length, &prefix, NULL); if (ret) { der_free_oid(&oid); return 0; } ret = 0; if (oid.length - 1 == prefix.length) { *suffix = oid.components[oid.length - 1]; oid.length--; ret = (der_heim_oid_cmp(&oid, &prefix) == 0); oid.length++; } der_free_oid(&oid); der_free_oid(&prefix); return ret; } static OM_uint32 inquire_sec_context_tkt_flags (OM_uint32 *minor_status, const gsskrb5_ctx context_handle, gss_buffer_set_t *data_set) { OM_uint32 tkt_flags; unsigned char buf[4]; gss_buffer_desc value; HEIMDAL_MUTEX_lock(&context_handle->ctx_id_mutex); if (context_handle->ticket == NULL) { HEIMDAL_MUTEX_unlock(&context_handle->ctx_id_mutex); _gsskrb5_set_status(EINVAL, "No ticket from which to obtain flags"); *minor_status = EINVAL; return GSS_S_BAD_MECH; } tkt_flags = TicketFlags2int(context_handle->ticket->ticket.flags); HEIMDAL_MUTEX_unlock(&context_handle->ctx_id_mutex); _gsskrb5_encode_om_uint32(tkt_flags, buf); value.length = sizeof(buf); value.value = buf; return gss_add_buffer_set_member(minor_status, &value, data_set); } enum keytype { ACCEPTOR_KEY, INITIATOR_KEY, TOKEN_KEY }; static OM_uint32 inquire_sec_context_get_subkey (OM_uint32 *minor_status, const gsskrb5_ctx context_handle, krb5_context context, enum keytype keytype, gss_buffer_set_t *data_set) { krb5_keyblock *key = NULL; krb5_storage *sp = NULL; krb5_data data; OM_uint32 maj_stat = GSS_S_COMPLETE; krb5_error_code ret; krb5_data_zero(&data); sp = krb5_storage_emem(); if (sp == NULL) { _gsskrb5_clear_status(); ret = ENOMEM; goto out; } HEIMDAL_MUTEX_lock(&context_handle->ctx_id_mutex); switch(keytype) { case ACCEPTOR_KEY: ret = _gsskrb5i_get_acceptor_subkey(context_handle, context, &key); break; case INITIATOR_KEY: ret = _gsskrb5i_get_initiator_subkey(context_handle, context, &key); break; case TOKEN_KEY: ret = _gsskrb5i_get_token_key(context_handle, context, &key); break; default: _gsskrb5_set_status(EINVAL, "%d is not a valid subkey type", keytype); ret = EINVAL; break; } HEIMDAL_MUTEX_unlock(&context_handle->ctx_id_mutex); if (ret) goto out; if (key == NULL) { _gsskrb5_set_status(EINVAL, "have no subkey of type %d", keytype); ret = EINVAL; goto out; } ret = krb5_store_keyblock(sp, *key); if (ret) goto out; ret = krb5_storage_to_data(sp, &data); if (ret) goto out; { gss_buffer_desc value; value.length = data.length; value.value = data.data; maj_stat = gss_add_buffer_set_member(minor_status, &value, data_set); } out: krb5_free_keyblock(context, key); krb5_data_free(&data); if (sp) krb5_storage_free(sp); if (ret) { *minor_status = ret; maj_stat = GSS_S_FAILURE; } return maj_stat; } static OM_uint32 inquire_sec_context_get_sspi_session_key (OM_uint32 *minor_status, const gsskrb5_ctx context_handle, krb5_context context, gss_buffer_set_t *data_set) { krb5_keyblock *key; OM_uint32 maj_stat = GSS_S_COMPLETE; krb5_error_code ret; gss_buffer_desc value; HEIMDAL_MUTEX_lock(&context_handle->ctx_id_mutex); ret = _gsskrb5i_get_token_key(context_handle, context, &key); HEIMDAL_MUTEX_unlock(&context_handle->ctx_id_mutex); if (ret) goto out; if (key == NULL) { ret = EINVAL; goto out; } value.length = key->keyvalue.length; value.value = key->keyvalue.data; maj_stat = gss_add_buffer_set_member(minor_status, &value, data_set); krb5_free_keyblock(context, key); /* MIT also returns the enctype encoded as an OID in data_set[1] */ out: if (ret) { *minor_status = ret; maj_stat = GSS_S_FAILURE; } return maj_stat; } static OM_uint32 inquire_sec_context_authz_data (OM_uint32 *minor_status, const gsskrb5_ctx context_handle, krb5_context context, unsigned ad_type, gss_buffer_set_t *data_set) { krb5_data data; gss_buffer_desc ad_data; OM_uint32 ret; *minor_status = 0; *data_set = GSS_C_NO_BUFFER_SET; HEIMDAL_MUTEX_lock(&context_handle->ctx_id_mutex); if (context_handle->ticket == NULL) { HEIMDAL_MUTEX_unlock(&context_handle->ctx_id_mutex); *minor_status = EINVAL; _gsskrb5_set_status(EINVAL, "No ticket to obtain authz data from"); return GSS_S_NO_CONTEXT; } ret = krb5_ticket_get_authorization_data_type(context, context_handle->ticket, ad_type, &data); HEIMDAL_MUTEX_unlock(&context_handle->ctx_id_mutex); if (ret) { *minor_status = ret; return GSS_S_FAILURE; } ad_data.value = data.data; ad_data.length = data.length; ret = gss_add_buffer_set_member(minor_status, &ad_data, data_set); krb5_data_free(&data); return ret; } static OM_uint32 inquire_sec_context_has_updated_spnego (OM_uint32 *minor_status, const gsskrb5_ctx context_handle, gss_buffer_set_t *data_set) { int is_updated = 0; *minor_status = 0; *data_set = GSS_C_NO_BUFFER_SET; /* * For Windows SPNEGO implementations, both the initiator and the * acceptor are assumed to have been updated if a "newer" [CLAR] or * different enctype is negotiated for use by the Kerberos GSS-API * mechanism. */ HEIMDAL_MUTEX_lock(&context_handle->ctx_id_mutex); is_updated = (context_handle->more_flags & IS_CFX); if (is_updated == 0) { krb5_keyblock *acceptor_subkey; if (context_handle->more_flags & LOCAL) acceptor_subkey = context_handle->auth_context->remote_subkey; else acceptor_subkey = context_handle->auth_context->local_subkey; if (acceptor_subkey != NULL) is_updated = (acceptor_subkey->keytype != context_handle->auth_context->keyblock->keytype); } HEIMDAL_MUTEX_unlock(&context_handle->ctx_id_mutex); return is_updated ? GSS_S_COMPLETE : GSS_S_FAILURE; } /* * */ static OM_uint32 export_lucid_sec_context_v1(OM_uint32 *minor_status, gsskrb5_ctx context_handle, krb5_context context, gss_buffer_set_t *data_set) { krb5_storage *sp = NULL; OM_uint32 major_status = GSS_S_COMPLETE; krb5_error_code ret; krb5_keyblock *key = NULL; int32_t number; int is_cfx; krb5_data data; *minor_status = 0; HEIMDAL_MUTEX_lock(&context_handle->ctx_id_mutex); is_cfx = (context_handle->more_flags & IS_CFX); sp = krb5_storage_emem(); if (sp == NULL) { _gsskrb5_clear_status(); ret = ENOMEM; goto out; } ret = krb5_store_int32(sp, 1); if (ret) goto out; ret = krb5_store_int32(sp, (context_handle->more_flags & LOCAL) ? 1 : 0); if (ret) goto out; /* XXX need krb5_store_int64() */ ret = krb5_store_int32(sp, context_handle->endtime); if (ret) goto out; krb5_auth_con_getlocalseqnumber (context, context_handle->auth_context, &number); ret = krb5_store_uint32(sp, (uint32_t)0); /* store top half as zero */ if (ret) goto out; ret = krb5_store_uint32(sp, (uint32_t)number); if (ret) goto out; krb5_auth_con_getremoteseqnumber (context, context_handle->auth_context, &number); ret = krb5_store_uint32(sp, (uint32_t)0); /* store top half as zero */ if (ret) goto out; ret = krb5_store_uint32(sp, (uint32_t)number); if (ret) goto out; ret = krb5_store_int32(sp, (is_cfx) ? 1 : 0); if (ret) goto out; ret = _gsskrb5i_get_token_key(context_handle, context, &key); if (ret) goto out; if (is_cfx == 0) { int sign_alg, seal_alg; switch (key->keytype) { case ETYPE_DES_CBC_CRC: case ETYPE_DES_CBC_MD4: case ETYPE_DES_CBC_MD5: sign_alg = 0; seal_alg = 0; break; case ETYPE_DES3_CBC_MD5: case ETYPE_DES3_CBC_SHA1: sign_alg = 4; seal_alg = 2; break; case ETYPE_ARCFOUR_HMAC_MD5: case ETYPE_ARCFOUR_HMAC_MD5_56: sign_alg = 17; seal_alg = 16; break; default: sign_alg = -1; seal_alg = -1; break; } ret = krb5_store_int32(sp, sign_alg); if (ret) goto out; ret = krb5_store_int32(sp, seal_alg); if (ret) goto out; /* ctx_key */ ret = krb5_store_keyblock(sp, *key); if (ret) goto out; } else { int subkey_p = (context_handle->more_flags & ACCEPTOR_SUBKEY) ? 1 : 0; /* have_acceptor_subkey */ ret = krb5_store_int32(sp, subkey_p); if (ret) goto out; /* ctx_key */ ret = krb5_store_keyblock(sp, *key); if (ret) goto out; /* acceptor_subkey */ if (subkey_p) { ret = krb5_store_keyblock(sp, *key); if (ret) goto out; } } ret = krb5_storage_to_data(sp, &data); if (ret) goto out; { gss_buffer_desc ad_data; ad_data.value = data.data; ad_data.length = data.length; ret = gss_add_buffer_set_member(minor_status, &ad_data, data_set); krb5_data_free(&data); if (ret) goto out; } out: if (key) krb5_free_keyblock (context, key); if (sp) krb5_storage_free(sp); if (ret) { *minor_status = ret; major_status = GSS_S_FAILURE; } HEIMDAL_MUTEX_unlock(&context_handle->ctx_id_mutex); return major_status; } static OM_uint32 get_authtime(OM_uint32 *minor_status, gsskrb5_ctx ctx, gss_buffer_set_t *data_set) { gss_buffer_desc value; unsigned char buf[4]; OM_uint32 authtime; HEIMDAL_MUTEX_lock(&ctx->ctx_id_mutex); if (ctx->ticket == NULL) { HEIMDAL_MUTEX_unlock(&ctx->ctx_id_mutex); _gsskrb5_set_status(EINVAL, "No ticket to obtain auth time from"); *minor_status = EINVAL; return GSS_S_FAILURE; } authtime = ctx->ticket->ticket.authtime; HEIMDAL_MUTEX_unlock(&ctx->ctx_id_mutex); _gsskrb5_encode_om_uint32(authtime, buf); value.length = sizeof(buf); value.value = buf; return gss_add_buffer_set_member(minor_status, &value, data_set); } static OM_uint32 get_service_keyblock (OM_uint32 *minor_status, gsskrb5_ctx ctx, gss_buffer_set_t *data_set) { krb5_storage *sp = NULL; krb5_data data; OM_uint32 maj_stat = GSS_S_COMPLETE; krb5_error_code ret = EINVAL; sp = krb5_storage_emem(); if (sp == NULL) { _gsskrb5_clear_status(); *minor_status = ENOMEM; return GSS_S_FAILURE; } HEIMDAL_MUTEX_lock(&ctx->ctx_id_mutex); if (ctx->service_keyblock == NULL) { HEIMDAL_MUTEX_unlock(&ctx->ctx_id_mutex); krb5_storage_free(sp); _gsskrb5_set_status(EINVAL, "No service keyblock on gssapi context"); *minor_status = EINVAL; return GSS_S_FAILURE; } krb5_data_zero(&data); ret = krb5_store_keyblock(sp, *ctx->service_keyblock); HEIMDAL_MUTEX_unlock(&ctx->ctx_id_mutex); if (ret) goto out; ret = krb5_storage_to_data(sp, &data); if (ret) goto out; { gss_buffer_desc value; value.length = data.length; value.value = data.data; maj_stat = gss_add_buffer_set_member(minor_status, &value, data_set); } out: krb5_data_free(&data); if (sp) krb5_storage_free(sp); if (ret) { *minor_status = ret; maj_stat = GSS_S_FAILURE; } return maj_stat; } /* * */ OM_uint32 GSSAPI_CALLCONV _gsskrb5_inquire_sec_context_by_oid (OM_uint32 *minor_status, gss_const_ctx_id_t context_handle, const gss_OID desired_object, gss_buffer_set_t *data_set) { krb5_context context; const gsskrb5_ctx ctx = (const gsskrb5_ctx) context_handle; unsigned suffix; if (ctx == NULL) { *minor_status = EINVAL; return GSS_S_NO_CONTEXT; } GSSAPI_KRB5_INIT (&context); if (gss_oid_equal(desired_object, GSS_KRB5_GET_TKT_FLAGS_X)) { return inquire_sec_context_tkt_flags(minor_status, ctx, data_set); } else if (gss_oid_equal(desired_object, GSS_C_PEER_HAS_UPDATED_SPNEGO)) { return inquire_sec_context_has_updated_spnego(minor_status, ctx, data_set); } else if (gss_oid_equal(desired_object, GSS_KRB5_GET_SUBKEY_X)) { return inquire_sec_context_get_subkey(minor_status, ctx, context, TOKEN_KEY, data_set); } else if (gss_oid_equal(desired_object, GSS_KRB5_GET_INITIATOR_SUBKEY_X)) { return inquire_sec_context_get_subkey(minor_status, ctx, context, INITIATOR_KEY, data_set); } else if (gss_oid_equal(desired_object, GSS_KRB5_GET_ACCEPTOR_SUBKEY_X)) { return inquire_sec_context_get_subkey(minor_status, ctx, context, ACCEPTOR_KEY, data_set); } else if (gss_oid_equal(desired_object, GSS_C_INQ_SSPI_SESSION_KEY)) { return inquire_sec_context_get_sspi_session_key(minor_status, ctx, context, data_set); } else if (gss_oid_equal(desired_object, GSS_KRB5_GET_AUTHTIME_X)) { return get_authtime(minor_status, ctx, data_set); } else if (oid_prefix_equal(desired_object, GSS_KRB5_EXTRACT_AUTHZ_DATA_FROM_SEC_CONTEXT_X, &suffix)) { return inquire_sec_context_authz_data(minor_status, ctx, context, suffix, data_set); } else if (oid_prefix_equal(desired_object, GSS_KRB5_EXPORT_LUCID_CONTEXT_X, &suffix)) { if (suffix == 1) return export_lucid_sec_context_v1(minor_status, ctx, context, data_set); *minor_status = 0; return GSS_S_FAILURE; } else if (gss_oid_equal(desired_object, GSS_KRB5_GET_SERVICE_KEYBLOCK_X)) { return get_service_keyblock(minor_status, ctx, data_set); } else { *minor_status = 0; return GSS_S_FAILURE; } } heimdal-7.5.0/lib/gssapi/krb5/test_acquire_cred.c0000644000175000017500000001023213026237312017777 0ustar niknik/* * Copyright (c) 2003-2005 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of KTH nor the names of its contributors may be * used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY KTH AND ITS CONTRIBUTORS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL KTH OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "gsskrb5_locl.h" #include static void print_time(OM_uint32 time_rec) { if (time_rec == GSS_C_INDEFINITE) { printf("cred never expire\n"); } else { time_t t = time_rec + time(NULL); printf("expiration time: %s", ctime(&t)); } } static void test_add(gss_cred_id_t cred_handle) { OM_uint32 major_status, minor_status; gss_cred_id_t copy_cred; OM_uint32 time_rec; major_status = gss_add_cred (&minor_status, cred_handle, GSS_C_NO_NAME, GSS_KRB5_MECHANISM, GSS_C_INITIATE, 0, 0, ©_cred, NULL, &time_rec, NULL); if (GSS_ERROR(major_status)) errx(1, "add_cred failed"); print_time(time_rec); major_status = gss_release_cred(&minor_status, ©_cred); if (GSS_ERROR(major_status)) errx(1, "release_cred failed"); } static void copy_cred(void) { OM_uint32 major_status, minor_status; gss_cred_id_t cred_handle; OM_uint32 time_rec; major_status = gss_acquire_cred(&minor_status, GSS_C_NO_NAME, 0, NULL, GSS_C_INITIATE, &cred_handle, NULL, &time_rec); if (GSS_ERROR(major_status)) errx(1, "acquire_cred failed"); print_time(time_rec); test_add(cred_handle); test_add(cred_handle); test_add(cred_handle); major_status = gss_release_cred(&minor_status, &cred_handle); if (GSS_ERROR(major_status)) errx(1, "release_cred failed"); } static void acquire_cred_service(const char *service) { OM_uint32 major_status, minor_status; gss_cred_id_t cred_handle; OM_uint32 time_rec; gss_buffer_desc name_buffer; gss_name_t name; name_buffer.value = rk_UNCONST(service); name_buffer.length = strlen(service); major_status = gss_import_name(&minor_status, &name_buffer, GSS_C_NT_HOSTBASED_SERVICE, &name); if (GSS_ERROR(major_status)) errx(1, "import_name failed"); major_status = gss_acquire_cred(&minor_status, name, 0, NULL, GSS_C_ACCEPT, &cred_handle, NULL, &time_rec); if (GSS_ERROR(major_status)) errx(1, "acquire_cred failed"); print_time(time_rec); major_status = gss_release_cred(&minor_status, &cred_handle); if (GSS_ERROR(major_status)) errx(1, "release_cred failed"); major_status = gss_release_name(&minor_status, &name); if (GSS_ERROR(major_status)) errx(1, "release_name failed"); } int main(int argc, char **argv) { copy_cred(); acquire_cred_service("host@xen2-heimdal-linux.lab.it.su.se"); return 0; } heimdal-7.5.0/lib/gssapi/krb5/accept_sec_context.c0000644000175000017500000005602313026237312020157 0ustar niknik/* * Copyright (c) 1997 - 2006 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "gsskrb5_locl.h" HEIMDAL_MUTEX gssapi_keytab_mutex = HEIMDAL_MUTEX_INITIALIZER; krb5_keytab _gsskrb5_keytab; static krb5_error_code validate_keytab(krb5_context context, const char *name, krb5_keytab *id) { krb5_error_code ret; ret = krb5_kt_resolve(context, name, id); if (ret) return ret; ret = krb5_kt_have_content(context, *id); if (ret) { krb5_kt_close(context, *id); *id = NULL; } return ret; } OM_uint32 _gsskrb5_register_acceptor_identity(OM_uint32 *min_stat, const char *identity) { krb5_context context; krb5_error_code ret; *min_stat = 0; ret = _gsskrb5_init(&context); if(ret) return GSS_S_FAILURE; HEIMDAL_MUTEX_lock(&gssapi_keytab_mutex); if(_gsskrb5_keytab != NULL) { krb5_kt_close(context, _gsskrb5_keytab); _gsskrb5_keytab = NULL; } if (identity == NULL) { ret = krb5_kt_default(context, &_gsskrb5_keytab); } else { /* * First check if we can the keytab as is and if it has content... */ ret = validate_keytab(context, identity, &_gsskrb5_keytab); /* * if it doesn't, lets prepend FILE: and try again */ if (ret) { char *p = NULL; ret = asprintf(&p, "FILE:%s", identity); if(ret < 0 || p == NULL) { HEIMDAL_MUTEX_unlock(&gssapi_keytab_mutex); return GSS_S_FAILURE; } ret = validate_keytab(context, p, &_gsskrb5_keytab); free(p); } } HEIMDAL_MUTEX_unlock(&gssapi_keytab_mutex); if(ret) { *min_stat = ret; return GSS_S_FAILURE; } return GSS_S_COMPLETE; } void _gsskrb5i_is_cfx(krb5_context context, gsskrb5_ctx ctx, int acceptor) { krb5_keyblock *key; if (acceptor) { if (ctx->auth_context->local_subkey) key = ctx->auth_context->local_subkey; else key = ctx->auth_context->remote_subkey; } else { if (ctx->auth_context->remote_subkey) key = ctx->auth_context->remote_subkey; else key = ctx->auth_context->local_subkey; } if (key == NULL) key = ctx->auth_context->keyblock; if (key == NULL) return; switch (key->keytype) { case ETYPE_DES_CBC_CRC: case ETYPE_DES_CBC_MD4: case ETYPE_DES_CBC_MD5: case ETYPE_DES3_CBC_MD5: case ETYPE_OLD_DES3_CBC_SHA1: case ETYPE_DES3_CBC_SHA1: case ETYPE_ARCFOUR_HMAC_MD5: case ETYPE_ARCFOUR_HMAC_MD5_56: break; default : ctx->more_flags |= IS_CFX; if ((acceptor && ctx->auth_context->local_subkey) || (!acceptor && ctx->auth_context->remote_subkey)) ctx->more_flags |= ACCEPTOR_SUBKEY; break; } if (ctx->crypto) krb5_crypto_destroy(context, ctx->crypto); /* XXX We really shouldn't ignore this; will come back to this */ (void) krb5_crypto_init(context, key, 0, &ctx->crypto); } static OM_uint32 gsskrb5_accept_delegated_token (OM_uint32 * minor_status, gsskrb5_ctx ctx, krb5_context context, gss_cred_id_t * delegated_cred_handle ) { krb5_ccache ccache = NULL; krb5_error_code kret; int32_t ac_flags, ret = GSS_S_COMPLETE; *minor_status = 0; /* XXX Create a new delegated_cred_handle? */ if (delegated_cred_handle == NULL) { ret = GSS_S_COMPLETE; goto out; } *delegated_cred_handle = NULL; kret = krb5_cc_new_unique (context, krb5_cc_type_memory, NULL, &ccache); if (kret) { ctx->flags &= ~GSS_C_DELEG_FLAG; goto out; } kret = krb5_cc_initialize(context, ccache, ctx->source); if (kret) { ctx->flags &= ~GSS_C_DELEG_FLAG; goto out; } krb5_auth_con_removeflags(context, ctx->auth_context, KRB5_AUTH_CONTEXT_DO_TIME, &ac_flags); kret = krb5_rd_cred2(context, ctx->auth_context, ccache, &ctx->fwd_data); krb5_auth_con_setflags(context, ctx->auth_context, ac_flags); if (kret) { ctx->flags &= ~GSS_C_DELEG_FLAG; ret = GSS_S_FAILURE; *minor_status = kret; goto out; } if (delegated_cred_handle) { gsskrb5_cred handle; ret = _gsskrb5_krb5_import_cred(minor_status, ccache, NULL, NULL, delegated_cred_handle); if (ret != GSS_S_COMPLETE) goto out; handle = (gsskrb5_cred) *delegated_cred_handle; handle->cred_flags |= GSS_CF_DESTROY_CRED_ON_RELEASE; krb5_cc_close(context, ccache); ccache = NULL; } out: if (ccache) { /* Don't destroy the default cred cache */ if (delegated_cred_handle == NULL) krb5_cc_close(context, ccache); else krb5_cc_destroy(context, ccache); } return ret; } static OM_uint32 gsskrb5_acceptor_ready(OM_uint32 * minor_status, gsskrb5_ctx ctx, krb5_context context, gss_cred_id_t *delegated_cred_handle) { OM_uint32 ret; int32_t seq_number; int is_cfx = 0; krb5_auth_con_getremoteseqnumber (context, ctx->auth_context, &seq_number); _gsskrb5i_is_cfx(context, ctx, 1); is_cfx = (ctx->more_flags & IS_CFX); ret = _gssapi_msg_order_create(minor_status, &ctx->order, _gssapi_msg_order_f(ctx->flags), seq_number, 0, is_cfx); if (ret) return ret; /* * If requested, set local sequence num to remote sequence if this * isn't a mutual authentication context */ if (!(ctx->flags & GSS_C_MUTUAL_FLAG) && _gssapi_msg_order_f(ctx->flags)) { krb5_auth_con_setlocalseqnumber(context, ctx->auth_context, seq_number); } /* * We should handle the delegation ticket, in case it's there */ if (ctx->fwd_data.length > 0 && (ctx->flags & GSS_C_DELEG_FLAG)) { ret = gsskrb5_accept_delegated_token(minor_status, ctx, context, delegated_cred_handle); if (ret != GSS_S_COMPLETE) return ret; } else { /* Well, looks like it wasn't there after all */ ctx->flags &= ~GSS_C_DELEG_FLAG; } ctx->state = ACCEPTOR_READY; ctx->more_flags |= OPEN; return GSS_S_COMPLETE; } static OM_uint32 send_error_token(OM_uint32 *minor_status, krb5_context context, krb5_error_code kret, krb5_principal server, krb5_data *indata, gss_buffer_t output_token) { krb5_principal ap_req_server = NULL; krb5_error_code ret; krb5_data outbuf; /* this e_data value encodes KERB_AP_ERR_TYPE_SKEW_RECOVERY which tells windows to try again with the corrected timestamp. See [MS-KILE] 2.2.1 KERB-ERROR-DATA */ krb5_data e_data = { 7, rk_UNCONST("\x30\x05\xa1\x03\x02\x01\x02") }; /* build server from request if the acceptor had not selected one */ if (server == NULL) { AP_REQ ap_req; ret = krb5_decode_ap_req(context, indata, &ap_req); if (ret) { *minor_status = ret; return GSS_S_FAILURE; } ret = _krb5_principalname2krb5_principal(context, &ap_req_server, ap_req.ticket.sname, ap_req.ticket.realm); free_AP_REQ(&ap_req); if (ret) { *minor_status = ret; return GSS_S_FAILURE; } server = ap_req_server; } ret = krb5_mk_error(context, kret, NULL, &e_data, NULL, server, NULL, NULL, &outbuf); if (ap_req_server) krb5_free_principal(context, ap_req_server); if (ret) { *minor_status = ret; return GSS_S_FAILURE; } ret = _gsskrb5_encapsulate(minor_status, &outbuf, output_token, "\x03\x00", GSS_KRB5_MECHANISM); krb5_data_free (&outbuf); if (ret) return ret; *minor_status = 0; return GSS_S_CONTINUE_NEEDED; } static OM_uint32 gsskrb5_acceptor_start(OM_uint32 * minor_status, gsskrb5_ctx ctx, krb5_context context, gss_const_cred_id_t acceptor_cred_handle, const gss_buffer_t input_token_buffer, const gss_channel_bindings_t input_chan_bindings, gss_name_t * src_name, gss_OID * mech_type, gss_buffer_t output_token, OM_uint32 * ret_flags, OM_uint32 * time_rec, gss_cred_id_t * delegated_cred_handle) { krb5_error_code kret; OM_uint32 ret = GSS_S_COMPLETE; krb5_data indata; krb5_flags ap_options; krb5_keytab keytab = NULL; int is_cfx = 0; int close_kt = 0; const gsskrb5_cred acceptor_cred = (gsskrb5_cred)acceptor_cred_handle; /* * We may, or may not, have an escapsulation. */ ret = _gsskrb5_decapsulate (minor_status, input_token_buffer, &indata, "\x01\x00", GSS_KRB5_MECHANISM); if (ret) { /* Assume that there is no OID wrapping. */ indata.length = input_token_buffer->length; indata.data = input_token_buffer->value; } /* * We need to get our keytab */ if (acceptor_cred == NULL) { HEIMDAL_MUTEX_lock(&gssapi_keytab_mutex); if (_gsskrb5_keytab != NULL) { char *name = NULL; kret = krb5_kt_get_full_name(context, _gsskrb5_keytab, &name); if (kret == 0) { kret = krb5_kt_resolve(context, name, &keytab); krb5_xfree(name); } if (kret == 0) close_kt = 1; else keytab = NULL; } HEIMDAL_MUTEX_unlock(&gssapi_keytab_mutex); } else if (acceptor_cred->keytab != NULL) { keytab = acceptor_cred->keytab; } /* * We need to check the ticket and create the AP-REP packet */ { krb5_rd_req_in_ctx in = NULL; krb5_rd_req_out_ctx out = NULL; krb5_principal server = NULL; if (acceptor_cred) server = acceptor_cred->principal; kret = krb5_rd_req_in_ctx_alloc(context, &in); if (kret == 0) kret = krb5_rd_req_in_set_keytab(context, in, keytab); if (kret) { if (in) krb5_rd_req_in_ctx_free(context, in); if (close_kt) krb5_kt_close(context, keytab); *minor_status = kret; return GSS_S_FAILURE; } kret = krb5_rd_req_ctx(context, &ctx->auth_context, &indata, server, in, &out); krb5_rd_req_in_ctx_free(context, in); if (close_kt) krb5_kt_close(context, keytab); if (kret == KRB5KRB_AP_ERR_SKEW || kret == KRB5KRB_AP_ERR_TKT_NYV) { /* * No reply in non-MUTUAL mode, but we don't know that its * non-MUTUAL mode yet, thats inside the 8003 checksum, so * lets only send the error token on clock skew, that * limit when send error token for non-MUTUAL. */ return send_error_token(minor_status, context, kret, server, &indata, output_token); } else if (kret) { *minor_status = kret; return GSS_S_FAILURE; } /* * we need to remember some data on the context_handle. */ kret = krb5_rd_req_out_get_ap_req_options(context, out, &ap_options); if (kret == 0) kret = krb5_rd_req_out_get_ticket(context, out, &ctx->ticket); if (kret == 0) kret = krb5_rd_req_out_get_keyblock(context, out, &ctx->service_keyblock); ctx->endtime = ctx->ticket->ticket.endtime; krb5_rd_req_out_ctx_free(context, out); if (kret) { ret = GSS_S_FAILURE; *minor_status = kret; return ret; } } /* * We need to copy the principal names to the context and the * calling layer. */ kret = krb5_copy_principal(context, ctx->ticket->client, &ctx->source); if (kret) { ret = GSS_S_FAILURE; *minor_status = kret; return ret; } kret = krb5_copy_principal(context, ctx->ticket->server, &ctx->target); if (kret) { ret = GSS_S_FAILURE; *minor_status = kret; return ret; } /* * We need to setup some compat stuff, this assumes that * context_handle->target is already set. */ ret = _gss_DES3_get_mic_compat(minor_status, ctx, context); if (ret) return ret; if (src_name != NULL) { kret = krb5_copy_principal (context, ctx->ticket->client, (gsskrb5_name*)src_name); if (kret) { ret = GSS_S_FAILURE; *minor_status = kret; return ret; } } /* * We need to get the flags out of the 8003 checksum. */ { krb5_authenticator authenticator; kret = krb5_auth_con_getauthenticator(context, ctx->auth_context, &authenticator); if(kret) { ret = GSS_S_FAILURE; *minor_status = kret; return ret; } if (authenticator->cksum != NULL && authenticator->cksum->cksumtype == CKSUMTYPE_GSSAPI) { ret = _gsskrb5_verify_8003_checksum(minor_status, input_chan_bindings, authenticator->cksum, &ctx->flags, &ctx->fwd_data); if (ret) { krb5_free_authenticator(context, &authenticator); return ret; } } else { if (authenticator->cksum != NULL) { krb5_crypto crypto; kret = krb5_crypto_init(context, ctx->auth_context->keyblock, 0, &crypto); if (kret) { krb5_free_authenticator(context, &authenticator); ret = GSS_S_FAILURE; *minor_status = kret; return ret; } /* * Windows accepts Samba3's use of a kerberos, rather than * GSSAPI checksum here */ kret = krb5_verify_checksum(context, crypto, KRB5_KU_AP_REQ_AUTH_CKSUM, NULL, 0, authenticator->cksum); krb5_crypto_destroy(context, crypto); if (kret) { krb5_free_authenticator(context, &authenticator); ret = GSS_S_BAD_SIG; *minor_status = kret; return ret; } } /* * If there is no checksum or a kerberos checksum (which Windows * and Samba accept), we use the ap_options to guess the mutual * flag. */ ctx->flags = GSS_C_REPLAY_FLAG | GSS_C_SEQUENCE_FLAG; if (ap_options & AP_OPTS_MUTUAL_REQUIRED) ctx->flags |= GSS_C_MUTUAL_FLAG; } krb5_free_authenticator(context, &authenticator); } if(ctx->flags & GSS_C_MUTUAL_FLAG) { krb5_data outbuf; int use_subkey = 0; _gsskrb5i_is_cfx(context, ctx, 1); is_cfx = (ctx->more_flags & IS_CFX); if (is_cfx || (ap_options & AP_OPTS_USE_SUBKEY)) { use_subkey = 1; } else { krb5_keyblock *rkey; /* * If there is a initiator subkey, copy that to acceptor * subkey to match Windows behavior */ kret = krb5_auth_con_getremotesubkey(context, ctx->auth_context, &rkey); if (kret == 0) { kret = krb5_auth_con_setlocalsubkey(context, ctx->auth_context, rkey); if (kret == 0) use_subkey = 1; } krb5_free_keyblock(context, rkey); } if (use_subkey) { ctx->more_flags |= ACCEPTOR_SUBKEY; krb5_auth_con_addflags(context, ctx->auth_context, KRB5_AUTH_CONTEXT_USE_SUBKEY, NULL); } kret = krb5_mk_rep(context, ctx->auth_context, &outbuf); if (kret) { *minor_status = kret; return GSS_S_FAILURE; } if (IS_DCE_STYLE(ctx)) { output_token->length = outbuf.length; output_token->value = outbuf.data; } else { ret = _gsskrb5_encapsulate(minor_status, &outbuf, output_token, "\x02\x00", GSS_KRB5_MECHANISM); krb5_data_free (&outbuf); if (ret) return ret; } } ctx->flags |= GSS_C_TRANS_FLAG; /* Remember the flags */ ctx->endtime = ctx->ticket->ticket.endtime; ctx->more_flags |= OPEN; if (mech_type) *mech_type = GSS_KRB5_MECHANISM; if (time_rec) { ret = _gsskrb5_lifetime_left(minor_status, context, ctx->endtime, time_rec); if (ret) { return ret; } } /* * When GSS_C_DCE_STYLE is in use, we need ask for a AP-REP from * the client. */ if (IS_DCE_STYLE(ctx)) { /* * Return flags to caller, but we haven't processed * delgations yet */ if (ret_flags) *ret_flags = (ctx->flags & ~GSS_C_DELEG_FLAG); ctx->state = ACCEPTOR_WAIT_FOR_DCESTYLE; return GSS_S_CONTINUE_NEEDED; } ret = gsskrb5_acceptor_ready(minor_status, ctx, context, delegated_cred_handle); if (ret_flags) *ret_flags = ctx->flags; return ret; } static OM_uint32 acceptor_wait_for_dcestyle(OM_uint32 * minor_status, gsskrb5_ctx ctx, krb5_context context, gss_const_cred_id_t acceptor_cred_handle, const gss_buffer_t input_token_buffer, const gss_channel_bindings_t input_chan_bindings, gss_name_t * src_name, gss_OID * mech_type, gss_buffer_t output_token, OM_uint32 * ret_flags, OM_uint32 * time_rec, gss_cred_id_t * delegated_cred_handle) { OM_uint32 ret; krb5_error_code kret; krb5_data inbuf; int32_t r_seq_number, l_seq_number; /* * We know it's GSS_C_DCE_STYLE so we don't need to decapsulate the AP_REP */ inbuf.length = input_token_buffer->length; inbuf.data = input_token_buffer->value; /* * We need to remeber the old remote seq_number, then check if the * client has replied with our local seq_number, and then reset * the remote seq_number to the old value */ { kret = krb5_auth_con_getlocalseqnumber(context, ctx->auth_context, &l_seq_number); if (kret) { *minor_status = kret; return GSS_S_FAILURE; } kret = krb5_auth_con_getremoteseqnumber(context, ctx->auth_context, &r_seq_number); if (kret) { *minor_status = kret; return GSS_S_FAILURE; } kret = krb5_auth_con_setremoteseqnumber(context, ctx->auth_context, l_seq_number); if (kret) { *minor_status = kret; return GSS_S_FAILURE; } } /* * We need to verify the AP_REP, but we need to flag that this is * DCE_STYLE, so don't check the timestamps this time, but put the * flag DO_TIME back afterward. */ { krb5_ap_rep_enc_part *repl; int32_t auth_flags; krb5_auth_con_removeflags(context, ctx->auth_context, KRB5_AUTH_CONTEXT_DO_TIME, &auth_flags); kret = krb5_rd_rep(context, ctx->auth_context, &inbuf, &repl); if (kret) { *minor_status = kret; return GSS_S_FAILURE; } krb5_free_ap_rep_enc_part(context, repl); krb5_auth_con_setflags(context, ctx->auth_context, auth_flags); } /* We need to check the liftime */ { OM_uint32 lifetime_rec; ret = _gsskrb5_lifetime_left(minor_status, context, ctx->endtime, &lifetime_rec); if (ret) { return ret; } if (lifetime_rec == 0) { return GSS_S_CONTEXT_EXPIRED; } if (time_rec) *time_rec = lifetime_rec; } /* We need to give the caller the flags which are in use */ if (ret_flags) *ret_flags = ctx->flags; if (src_name) { kret = krb5_copy_principal(context, ctx->source, (gsskrb5_name*)src_name); if (kret) { *minor_status = kret; return GSS_S_FAILURE; } } /* * After the krb5_rd_rep() the remote and local seq_number should * be the same, because the client just replies the seq_number * from our AP-REP in its AP-REP, but then the client uses the * seq_number from its AP-REQ for GSS_wrap() */ { int32_t tmp_r_seq_number, tmp_l_seq_number; kret = krb5_auth_con_getremoteseqnumber(context, ctx->auth_context, &tmp_r_seq_number); if (kret) { *minor_status = kret; return GSS_S_FAILURE; } kret = krb5_auth_con_getlocalseqnumber(context, ctx->auth_context, &tmp_l_seq_number); if (kret) { *minor_status = kret; return GSS_S_FAILURE; } /* * Here we check if the client has responsed with our local seq_number, */ if (tmp_r_seq_number != tmp_l_seq_number) { return GSS_S_UNSEQ_TOKEN; } } /* * We need to reset the remote seq_number, because the client will use, * the old one for the GSS_wrap() calls */ { kret = krb5_auth_con_setremoteseqnumber(context, ctx->auth_context, r_seq_number); if (kret) { *minor_status = kret; return GSS_S_FAILURE; } } return gsskrb5_acceptor_ready(minor_status, ctx, context, delegated_cred_handle); } OM_uint32 GSSAPI_CALLCONV _gsskrb5_accept_sec_context(OM_uint32 * minor_status, gss_ctx_id_t * context_handle, gss_const_cred_id_t acceptor_cred_handle, const gss_buffer_t input_token_buffer, const gss_channel_bindings_t input_chan_bindings, gss_name_t * src_name, gss_OID * mech_type, gss_buffer_t output_token, OM_uint32 * ret_flags, OM_uint32 * time_rec, gss_cred_id_t * delegated_cred_handle) { krb5_context context; OM_uint32 ret; gsskrb5_ctx ctx; GSSAPI_KRB5_INIT(&context); output_token->length = 0; output_token->value = NULL; if (src_name != NULL) *src_name = NULL; if (mech_type) *mech_type = GSS_KRB5_MECHANISM; if (*context_handle == GSS_C_NO_CONTEXT) { ret = _gsskrb5_create_ctx(minor_status, context_handle, context, input_chan_bindings, ACCEPTOR_START); if (ret) return ret; } ctx = (gsskrb5_ctx)*context_handle; /* * TODO: check the channel_bindings * (above just sets them to krb5 layer) */ HEIMDAL_MUTEX_lock(&ctx->ctx_id_mutex); switch (ctx->state) { case ACCEPTOR_START: ret = gsskrb5_acceptor_start(minor_status, ctx, context, acceptor_cred_handle, input_token_buffer, input_chan_bindings, src_name, mech_type, output_token, ret_flags, time_rec, delegated_cred_handle); break; case ACCEPTOR_WAIT_FOR_DCESTYLE: ret = acceptor_wait_for_dcestyle(minor_status, ctx, context, acceptor_cred_handle, input_token_buffer, input_chan_bindings, src_name, mech_type, output_token, ret_flags, time_rec, delegated_cred_handle); break; case ACCEPTOR_READY: /* * If we get there, the caller have called * gss_accept_sec_context() one time too many. */ ret = GSS_S_BAD_STATUS; break; default: /* TODO: is this correct here? --metze */ ret = GSS_S_BAD_STATUS; break; } HEIMDAL_MUTEX_unlock(&ctx->ctx_id_mutex); if (GSS_ERROR(ret)) { OM_uint32 min2; _gsskrb5_delete_sec_context(&min2, context_handle, GSS_C_NO_BUFFER); } return ret; } heimdal-7.5.0/lib/gssapi/krb5/display_name.c0000644000175000017500000000523713026237312016770 0ustar niknik/* * Copyright (c) 1997 - 2003 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "gsskrb5_locl.h" OM_uint32 GSSAPI_CALLCONV _gsskrb5_display_name (OM_uint32 * minor_status, gss_const_name_t input_name, gss_buffer_t output_name_buffer, gss_OID * output_name_type ) { krb5_context context; krb5_const_principal name = (krb5_const_principal)input_name; krb5_error_code kret; char *buf; size_t len; GSSAPI_KRB5_INIT (&context); kret = krb5_unparse_name_flags (context, name, KRB5_PRINCIPAL_UNPARSE_DISPLAY, &buf); if (kret) { *minor_status = kret; return GSS_S_FAILURE; } len = strlen (buf); output_name_buffer->length = len; output_name_buffer->value = malloc(len + 1); if (output_name_buffer->value == NULL) { free (buf); *minor_status = ENOMEM; return GSS_S_FAILURE; } memcpy (output_name_buffer->value, buf, len); ((char *)output_name_buffer->value)[len] = '\0'; free (buf); if (output_name_type) *output_name_type = GSS_KRB5_NT_PRINCIPAL_NAME; *minor_status = 0; return GSS_S_COMPLETE; } heimdal-7.5.0/lib/gssapi/krb5/inquire_names_for_mech.c0000644000175000017500000000510613026237312021017 0ustar niknik/* * Copyright (c) 2003 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "gsskrb5_locl.h" static gss_OID name_list[] = { GSS_C_NT_HOSTBASED_SERVICE, GSS_C_NT_USER_NAME, GSS_KRB5_NT_PRINCIPAL_NAME, GSS_C_NT_EXPORT_NAME, NULL }; OM_uint32 GSSAPI_CALLCONV _gsskrb5_inquire_names_for_mech ( OM_uint32 * minor_status, const gss_OID mechanism, gss_OID_set * name_types ) { OM_uint32 ret; int i; *minor_status = 0; if (gss_oid_equal(mechanism, GSS_KRB5_MECHANISM) == 0 && gss_oid_equal(mechanism, GSS_C_NULL_OID) == 0) { *name_types = GSS_C_NO_OID_SET; return GSS_S_BAD_MECH; } ret = gss_create_empty_oid_set(minor_status, name_types); if (ret != GSS_S_COMPLETE) return ret; for (i = 0; name_list[i] != NULL; i++) { ret = gss_add_oid_set_member(minor_status, name_list[i], name_types); if (ret != GSS_S_COMPLETE) break; } if (ret != GSS_S_COMPLETE) gss_release_oid_set(NULL, name_types); return GSS_S_COMPLETE; } heimdal-7.5.0/lib/gssapi/krb5/copy_ccache.c0000644000175000017500000001174413026237312016563 0ustar niknik/* * Copyright (c) 2000 - 2001, 2003 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "gsskrb5_locl.h" #if 0 OM_uint32 gss_krb5_copy_ccache(OM_uint32 *minor_status, krb5_context context, gss_cred_id_t cred, krb5_ccache out) { krb5_error_code kret; HEIMDAL_MUTEX_lock(&cred->cred_id_mutex); if (cred->ccache == NULL) { HEIMDAL_MUTEX_unlock(&cred->cred_id_mutex); *minor_status = EINVAL; return GSS_S_FAILURE; } kret = krb5_cc_copy_cache(context, cred->ccache, out); HEIMDAL_MUTEX_unlock(&cred->cred_id_mutex); if (kret) { *minor_status = kret; return GSS_S_FAILURE; } *minor_status = 0; return GSS_S_COMPLETE; } #endif OM_uint32 _gsskrb5_krb5_import_cred(OM_uint32 *minor_status, krb5_ccache id, krb5_principal keytab_principal, krb5_keytab keytab, gss_cred_id_t *cred) { krb5_context context; krb5_error_code kret; gsskrb5_cred handle; OM_uint32 ret; *cred = NULL; GSSAPI_KRB5_INIT (&context); handle = calloc(1, sizeof(*handle)); if (handle == NULL) { _gsskrb5_clear_status (); *minor_status = ENOMEM; return (GSS_S_FAILURE); } HEIMDAL_MUTEX_init(&handle->cred_id_mutex); handle->usage = 0; if (id) { time_t now; OM_uint32 left; char *str; handle->usage |= GSS_C_INITIATE; kret = krb5_cc_get_principal(context, id, &handle->principal); if (kret) { free(handle); *minor_status = kret; return GSS_S_FAILURE; } if (keytab_principal) { krb5_boolean match; match = krb5_principal_compare(context, handle->principal, keytab_principal); if (match == FALSE) { krb5_free_principal(context, handle->principal); free(handle); _gsskrb5_clear_status (); *minor_status = EINVAL; return GSS_S_FAILURE; } } krb5_timeofday(context, &now); ret = __gsskrb5_ccache_lifetime(minor_status, context, id, handle->principal, &left); if (ret != GSS_S_COMPLETE) { krb5_free_principal(context, handle->principal); free(handle); return ret; } handle->endtime = now + left; kret = krb5_cc_get_full_name(context, id, &str); if (kret) goto out; kret = krb5_cc_resolve(context, str, &handle->ccache); free(str); if (kret) goto out; } if (keytab) { char *str; handle->usage |= GSS_C_ACCEPT; if (keytab_principal && handle->principal == NULL) { kret = krb5_copy_principal(context, keytab_principal, &handle->principal); if (kret) goto out; } kret = krb5_kt_get_full_name(context, keytab, &str); if (kret) goto out; kret = krb5_kt_resolve(context, str, &handle->keytab); free(str); if (kret) goto out; } if (id || keytab) { ret = gss_create_empty_oid_set(minor_status, &handle->mechanisms); if (ret == GSS_S_COMPLETE) ret = gss_add_oid_set_member(minor_status, GSS_KRB5_MECHANISM, &handle->mechanisms); if (ret != GSS_S_COMPLETE) { kret = *minor_status; goto out; } } *minor_status = 0; *cred = (gss_cred_id_t)handle; return GSS_S_COMPLETE; out: gss_release_oid_set(minor_status, &handle->mechanisms); if (handle->ccache) krb5_cc_close(context, handle->ccache); if (handle->keytab) krb5_kt_close(context, handle->keytab); if (handle->principal) krb5_free_principal(context, handle->principal); HEIMDAL_MUTEX_destroy(&handle->cred_id_mutex); free(handle); *minor_status = kret; return GSS_S_FAILURE; } heimdal-7.5.0/lib/gssapi/krb5/test_cred.c0000644000175000017500000001335113026237312016273 0ustar niknik/* * Copyright (c) 2003-2004 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of KTH nor the names of its contributors may be * used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY KTH AND ITS CONTRIBUTORS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL KTH OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "gsskrb5_locl.h" #include #include static void gss_print_errors (int min_stat) { OM_uint32 new_stat; OM_uint32 msg_ctx = 0; gss_buffer_desc status_string; OM_uint32 ret; do { ret = gss_display_status (&new_stat, min_stat, GSS_C_MECH_CODE, GSS_C_NO_OID, &msg_ctx, &status_string); fprintf (stderr, "%.*s\n", (int)status_string.length, (char *)status_string.value); gss_release_buffer (&new_stat, &status_string); } while (!GSS_ERROR(ret) && msg_ctx != 0); } static void gss_err(int exitval, int status, const char *fmt, ...) { va_list args; va_start(args, fmt); vwarnx (fmt, args); gss_print_errors (status); va_end(args); exit (exitval); } static void acquire_release_loop(gss_name_t name, int counter, gss_cred_usage_t usage) { OM_uint32 maj_stat, min_stat; gss_cred_id_t cred; int i; for (i = 0; i < counter; i++) { maj_stat = gss_acquire_cred(&min_stat, name, GSS_C_INDEFINITE, GSS_C_NO_OID_SET, usage, &cred, NULL, NULL); if (maj_stat != GSS_S_COMPLETE) gss_err(1, min_stat, "aquire %d %d != GSS_S_COMPLETE", i, (int)maj_stat); maj_stat = gss_release_cred(&min_stat, &cred); if (maj_stat != GSS_S_COMPLETE) gss_err(1, min_stat, "release %d %d != GSS_S_COMPLETE", i, (int)maj_stat); } } static void acquire_add_release_add(gss_name_t name, gss_cred_usage_t usage) { OM_uint32 maj_stat, min_stat; gss_cred_id_t cred, cred2, cred3; maj_stat = gss_acquire_cred(&min_stat, name, GSS_C_INDEFINITE, GSS_C_NO_OID_SET, usage, &cred, NULL, NULL); if (maj_stat != GSS_S_COMPLETE) gss_err(1, min_stat, "aquire %d != GSS_S_COMPLETE", (int)maj_stat); maj_stat = gss_add_cred(&min_stat, cred, GSS_C_NO_NAME, GSS_KRB5_MECHANISM, usage, GSS_C_INDEFINITE, GSS_C_INDEFINITE, &cred2, NULL, NULL, NULL); if (maj_stat != GSS_S_COMPLETE) gss_err(1, min_stat, "add_cred %d != GSS_S_COMPLETE", (int)maj_stat); maj_stat = gss_release_cred(&min_stat, &cred); if (maj_stat != GSS_S_COMPLETE) gss_err(1, min_stat, "release %d != GSS_S_COMPLETE", (int)maj_stat); maj_stat = gss_add_cred(&min_stat, cred2, GSS_C_NO_NAME, GSS_KRB5_MECHANISM, GSS_C_BOTH, GSS_C_INDEFINITE, GSS_C_INDEFINITE, &cred3, NULL, NULL, NULL); maj_stat = gss_release_cred(&min_stat, &cred2); if (maj_stat != GSS_S_COMPLETE) gss_err(1, min_stat, "release 2 %d != GSS_S_COMPLETE", (int)maj_stat); maj_stat = gss_release_cred(&min_stat, &cred3); if (maj_stat != GSS_S_COMPLETE) gss_err(1, min_stat, "release 2 %d != GSS_S_COMPLETE", (int)maj_stat); } static int version_flag = 0; static int help_flag = 0; static struct getargs args[] = { {"version", 0, arg_flag, &version_flag, "print version", NULL }, {"help", 0, arg_flag, &help_flag, NULL, NULL } }; static void usage (int ret) { arg_printusage (args, sizeof(args)/sizeof(*args), NULL, "service@host"); exit (ret); } int main(int argc, char **argv) { struct gss_buffer_desc_struct name_buffer; OM_uint32 maj_stat, min_stat; gss_name_t name; int optidx = 0; setprogname(argv[0]); if(getarg(args, sizeof(args) / sizeof(args[0]), argc, argv, &optidx)) usage(1); if (help_flag) usage (0); if(version_flag){ print_version(NULL); exit(0); } argc -= optidx; argv += optidx; if (argc < 1) errx(1, "argc < 1"); name_buffer.value = argv[0]; name_buffer.length = strlen(argv[0]); maj_stat = gss_import_name(&min_stat, &name_buffer, GSS_C_NT_HOSTBASED_SERVICE, &name); if (maj_stat != GSS_S_COMPLETE) errx(1, "import name error"); acquire_release_loop(name, 100, GSS_C_ACCEPT); acquire_release_loop(name, 100, GSS_C_INITIATE); acquire_release_loop(name, 100, GSS_C_BOTH); acquire_add_release_add(name, GSS_C_ACCEPT); acquire_add_release_add(name, GSS_C_INITIATE); acquire_add_release_add(name, GSS_C_BOTH); gss_release_name(&min_stat, &name); return 0; } heimdal-7.5.0/lib/gssapi/krb5/delete_sec_context.c0000644000175000017500000000567513026237312020171 0ustar niknik/* * Copyright (c) 1997 - 2003 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "gsskrb5_locl.h" OM_uint32 GSSAPI_CALLCONV _gsskrb5_delete_sec_context(OM_uint32 * minor_status, gss_ctx_id_t * context_handle, gss_buffer_t output_token) { krb5_context context; gsskrb5_ctx ctx; GSSAPI_KRB5_INIT (&context); *minor_status = 0; if (output_token) { output_token->length = 0; output_token->value = NULL; } if (*context_handle == GSS_C_NO_CONTEXT) return GSS_S_COMPLETE; ctx = (gsskrb5_ctx) *context_handle; *context_handle = GSS_C_NO_CONTEXT; HEIMDAL_MUTEX_lock(&ctx->ctx_id_mutex); krb5_auth_con_free (context, ctx->auth_context); krb5_auth_con_free (context, ctx->deleg_auth_context); if (ctx->kcred) krb5_free_creds(context, ctx->kcred); if(ctx->source) krb5_free_principal (context, ctx->source); if(ctx->target) krb5_free_principal (context, ctx->target); if (ctx->ticket) krb5_free_ticket (context, ctx->ticket); if(ctx->order) _gssapi_msg_order_destroy(&ctx->order); if (ctx->service_keyblock) krb5_free_keyblock (context, ctx->service_keyblock); krb5_data_free(&ctx->fwd_data); if (ctx->crypto) krb5_crypto_destroy(context, ctx->crypto); HEIMDAL_MUTEX_unlock(&ctx->ctx_id_mutex); HEIMDAL_MUTEX_destroy(&ctx->ctx_id_mutex); memset(ctx, 0, sizeof(*ctx)); free (ctx); return GSS_S_COMPLETE; } heimdal-7.5.0/lib/gssapi/krb5/store_cred.c0000644000175000017500000001235213026237312016450 0ustar niknik/* * Copyright (c) 2003 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "gsskrb5_locl.h" OM_uint32 GSSAPI_CALLCONV _gsskrb5_store_cred(OM_uint32 *minor_status, gss_cred_id_t input_cred_handle, gss_cred_usage_t cred_usage, const gss_OID desired_mech, OM_uint32 overwrite_cred, OM_uint32 default_cred, gss_OID_set *elements_stored, gss_cred_usage_t *cred_usage_stored) { krb5_context context; krb5_error_code ret; gsskrb5_cred cred; krb5_ccache id = NULL; krb5_ccache def_ccache = NULL; const char *def_type = NULL; time_t exp_current; time_t exp_new; *minor_status = 0; if (cred_usage != GSS_C_INITIATE) { *minor_status = GSS_KRB5_S_G_BAD_USAGE; return GSS_S_FAILURE; } if (desired_mech != GSS_C_NO_OID && gss_oid_equal(desired_mech, GSS_KRB5_MECHANISM) == 0) return GSS_S_BAD_MECH; cred = (gsskrb5_cred)input_cred_handle; if (cred == NULL) return GSS_S_NO_CRED; GSSAPI_KRB5_INIT (&context); HEIMDAL_MUTEX_lock(&cred->cred_id_mutex); if (cred->usage != cred_usage && cred->usage != GSS_C_BOTH) { HEIMDAL_MUTEX_unlock(&cred->cred_id_mutex); *minor_status = GSS_KRB5_S_G_BAD_USAGE; return GSS_S_FAILURE; } ret = krb5_cc_get_lifetime(context, cred->ccache, &exp_new); if (ret) { HEIMDAL_MUTEX_unlock(&cred->cred_id_mutex); *minor_status = ret; return GSS_S_NO_CRED; } if (cred->principal == NULL) { HEIMDAL_MUTEX_unlock(&cred->cred_id_mutex); *minor_status = GSS_KRB5_S_KG_TGT_MISSING; return GSS_S_FAILURE; } ret = krb5_cc_default(context, &def_ccache); if (ret == 0) { def_type = krb5_cc_get_type(context, def_ccache); krb5_cc_close(context, def_ccache); } def_ccache = NULL; /* write out cred to credential cache */ ret = krb5_cc_cache_match(context, cred->principal, &id); if (ret) { if (default_cred) { ret = krb5_cc_default(context, &id); if (ret) { HEIMDAL_MUTEX_unlock(&cred->cred_id_mutex); *minor_status = ret; return GSS_S_FAILURE; } } else { if (def_type == NULL || !krb5_cc_support_switch(context, def_type)) { HEIMDAL_MUTEX_unlock(&cred->cred_id_mutex); *minor_status = 0; /* XXX */ return GSS_S_NO_CRED; /* XXX */ } ret = krb5_cc_new_unique(context, def_type, NULL, &id); if (ret) { HEIMDAL_MUTEX_unlock(&cred->cred_id_mutex); *minor_status = ret; return GSS_S_FAILURE; } overwrite_cred = 1; } } if (!overwrite_cred) { /* If current creds are expired or near it, overwrite */ ret = krb5_cc_get_lifetime(context, id, &exp_current); if (ret != 0 || exp_new > exp_current) overwrite_cred = 1; } if (!overwrite_cred) { /* Nothing to do */ krb5_cc_close(context, id); HEIMDAL_MUTEX_unlock(&cred->cred_id_mutex); *minor_status = 0; return GSS_S_DUPLICATE_ELEMENT; } ret = krb5_cc_initialize(context, id, cred->principal); if (ret == 0) ret = krb5_cc_copy_match_f(context, cred->ccache, id, NULL, NULL, NULL); if (ret) { krb5_cc_close(context, id); HEIMDAL_MUTEX_unlock(&cred->cred_id_mutex); *minor_status = ret; return(GSS_S_FAILURE); } if (default_cred && def_type != NULL && krb5_cc_support_switch(context, def_type)) krb5_cc_switch(context, id); krb5_cc_close(context, id); HEIMDAL_MUTEX_unlock(&cred->cred_id_mutex); *minor_status = 0; return GSS_S_COMPLETE; } heimdal-7.5.0/lib/gssapi/krb5/pname_to_uid.c0000644000175000017500000000476713026237312016775 0ustar niknik/* * Copyright (c) 2011, PADL Software Pty Ltd. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of PADL Software nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY PADL SOFTWARE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL PADL SOFTWARE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "gsskrb5_locl.h" OM_uint32 GSSAPI_CALLCONV _gsskrb5_localname(OM_uint32 *minor_status, gss_const_name_t pname, const gss_OID mech_type, gss_buffer_t localname) { krb5_error_code ret; krb5_context context; krb5_const_principal princ = (krb5_const_principal)pname; char lnamebuf[256]; GSSAPI_KRB5_INIT(&context); *minor_status = 0; ret = krb5_aname_to_localname(context, princ, sizeof(lnamebuf), lnamebuf); if (ret != 0) { *minor_status = ret; return GSS_S_FAILURE; } localname->length = strlen(lnamebuf); localname->value = malloc(localname->length + 1); if (localname->value == NULL) { localname->length = 0; *minor_status = ENOMEM; return GSS_S_FAILURE; } memcpy(localname->value, lnamebuf, localname->length + 1); *minor_status = 0; return GSS_S_COMPLETE; } heimdal-7.5.0/lib/gssapi/krb5/test_oid.c0000644000175000017500000000402112136107747016134 0ustar niknik/* * Copyright (c) 2006 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "gsskrb5_locl.h" int main(int argc, char **argv) { OM_uint32 minor_status, maj_stat; gss_buffer_desc data; int ret; maj_stat = gss_oid_to_str(&minor_status, GSS_KRB5_MECHANISM, &data); if (GSS_ERROR(maj_stat)) errx(1, "gss_oid_to_str failed"); ret = strncmp(data.value, "1 2 840 113554 1 2 2", data.length); gss_release_buffer(&maj_stat, &data); if (ret) return 1; return 0; } heimdal-7.5.0/lib/gssapi/krb5/unwrap.c0000644000175000017500000002760413026237312015641 0ustar niknik/* * Copyright (c) 1997 - 2004 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "gsskrb5_locl.h" #ifdef HEIM_WEAK_CRYPTO static OM_uint32 unwrap_des (OM_uint32 * minor_status, const gsskrb5_ctx context_handle, const gss_buffer_t input_message_buffer, gss_buffer_t output_message_buffer, int * conf_state, gss_qop_t * qop_state, krb5_keyblock *key ) { u_char *p, *seq; size_t len; EVP_MD_CTX *md5; u_char hash[16]; EVP_CIPHER_CTX des_ctx; DES_key_schedule schedule; DES_cblock deskey; DES_cblock zero; size_t i; uint32_t seq_number; size_t padlength; OM_uint32 ret; int cstate; int cmp; int token_len; if (IS_DCE_STYLE(context_handle)) { token_len = 22 + 8 + 15; /* 45 */ } else { token_len = input_message_buffer->length; } p = input_message_buffer->value; ret = _gsskrb5_verify_header (&p, token_len, "\x02\x01", GSS_KRB5_MECHANISM); if (ret) return ret; if (memcmp (p, "\x00\x00", 2) != 0) return GSS_S_BAD_SIG; p += 2; if (memcmp (p, "\x00\x00", 2) == 0) { cstate = 1; } else if (memcmp (p, "\xFF\xFF", 2) == 0) { cstate = 0; } else return GSS_S_BAD_MIC; p += 2; if(conf_state != NULL) *conf_state = cstate; if (memcmp (p, "\xff\xff", 2) != 0) return GSS_S_DEFECTIVE_TOKEN; p += 2; p += 16; len = p - (u_char *)input_message_buffer->value; if(cstate) { /* decrypt data */ memcpy (&deskey, key->keyvalue.data, sizeof(deskey)); memset (&zero, 0, sizeof(zero)); for (i = 0; i < sizeof(deskey); ++i) deskey[i] ^= 0xf0; EVP_CIPHER_CTX_init(&des_ctx); EVP_CipherInit_ex(&des_ctx, EVP_des_cbc(), NULL, deskey, zero, 0); EVP_Cipher(&des_ctx, p, p, input_message_buffer->length - len); EVP_CIPHER_CTX_cleanup(&des_ctx); memset (&schedule, 0, sizeof(schedule)); } if (IS_DCE_STYLE(context_handle)) { padlength = 0; } else { /* check pad */ ret = _gssapi_verify_pad(input_message_buffer, input_message_buffer->length - len, &padlength); if (ret) return ret; } md5 = EVP_MD_CTX_create(); EVP_DigestInit_ex(md5, EVP_md5(), NULL); EVP_DigestUpdate(md5, p - 24, 8); EVP_DigestUpdate(md5, p, input_message_buffer->length - len); EVP_DigestFinal_ex(md5, hash, NULL); EVP_MD_CTX_destroy(md5); memset (&zero, 0, sizeof(zero)); memcpy (&deskey, key->keyvalue.data, sizeof(deskey)); DES_set_key_unchecked (&deskey, &schedule); DES_cbc_cksum ((void *)hash, (void *)hash, sizeof(hash), &schedule, &zero); if (ct_memcmp (p - 8, hash, 8) != 0) return GSS_S_BAD_MIC; /* verify sequence number */ HEIMDAL_MUTEX_lock(&context_handle->ctx_id_mutex); p -= 16; EVP_CIPHER_CTX_init(&des_ctx); EVP_CipherInit_ex(&des_ctx, EVP_des_cbc(), NULL, key->keyvalue.data, hash, 0); EVP_Cipher(&des_ctx, p, p, 8); EVP_CIPHER_CTX_cleanup(&des_ctx); memset (deskey, 0, sizeof(deskey)); memset (&schedule, 0, sizeof(schedule)); seq = p; _gsskrb5_decode_om_uint32(seq, &seq_number); if (context_handle->more_flags & LOCAL) cmp = ct_memcmp(&seq[4], "\xff\xff\xff\xff", 4); else cmp = ct_memcmp(&seq[4], "\x00\x00\x00\x00", 4); if (cmp != 0) { HEIMDAL_MUTEX_unlock(&context_handle->ctx_id_mutex); return GSS_S_BAD_MIC; } ret = _gssapi_msg_order_check(context_handle->order, seq_number); if (ret) { HEIMDAL_MUTEX_unlock(&context_handle->ctx_id_mutex); return ret; } HEIMDAL_MUTEX_unlock(&context_handle->ctx_id_mutex); /* copy out data */ output_message_buffer->length = input_message_buffer->length - len - padlength - 8; output_message_buffer->value = malloc(output_message_buffer->length); if(output_message_buffer->length != 0 && output_message_buffer->value == NULL) return GSS_S_FAILURE; memcpy (output_message_buffer->value, p + 24, output_message_buffer->length); return GSS_S_COMPLETE; } #endif static OM_uint32 unwrap_des3 (OM_uint32 * minor_status, const gsskrb5_ctx context_handle, krb5_context context, const gss_buffer_t input_message_buffer, gss_buffer_t output_message_buffer, int * conf_state, gss_qop_t * qop_state, krb5_keyblock *key ) { u_char *p; size_t len; u_char *seq; krb5_data seq_data; u_char cksum[20]; uint32_t seq_number; size_t padlength; OM_uint32 ret; int cstate; krb5_crypto crypto; Checksum csum; int cmp; int token_len; if (IS_DCE_STYLE(context_handle)) { token_len = 34 + 8 + 15; /* 57 */ } else { token_len = input_message_buffer->length; } p = input_message_buffer->value; ret = _gsskrb5_verify_header (&p, token_len, "\x02\x01", GSS_KRB5_MECHANISM); if (ret) return ret; if (memcmp (p, "\x04\x00", 2) != 0) /* HMAC SHA1 DES3_KD */ return GSS_S_BAD_SIG; p += 2; if (ct_memcmp (p, "\x02\x00", 2) == 0) { cstate = 1; } else if (ct_memcmp (p, "\xff\xff", 2) == 0) { cstate = 0; } else return GSS_S_BAD_MIC; p += 2; if(conf_state != NULL) *conf_state = cstate; if (ct_memcmp (p, "\xff\xff", 2) != 0) return GSS_S_DEFECTIVE_TOKEN; p += 2; p += 28; len = p - (u_char *)input_message_buffer->value; if(cstate) { /* decrypt data */ krb5_data tmp; ret = krb5_crypto_init(context, key, ETYPE_DES3_CBC_NONE, &crypto); if (ret) { *minor_status = ret; return GSS_S_FAILURE; } ret = krb5_decrypt(context, crypto, KRB5_KU_USAGE_SEAL, p, input_message_buffer->length - len, &tmp); krb5_crypto_destroy(context, crypto); if (ret) { *minor_status = ret; return GSS_S_FAILURE; } assert (tmp.length == input_message_buffer->length - len); memcpy (p, tmp.data, tmp.length); krb5_data_free(&tmp); } if (IS_DCE_STYLE(context_handle)) { padlength = 0; } else { /* check pad */ ret = _gssapi_verify_pad(input_message_buffer, input_message_buffer->length - len, &padlength); if (ret) return ret; } /* verify sequence number */ HEIMDAL_MUTEX_lock(&context_handle->ctx_id_mutex); p -= 28; ret = krb5_crypto_init(context, key, ETYPE_DES3_CBC_NONE, &crypto); if (ret) { *minor_status = ret; HEIMDAL_MUTEX_unlock(&context_handle->ctx_id_mutex); return GSS_S_FAILURE; } { DES_cblock ivec; memcpy(&ivec, p + 8, 8); ret = krb5_decrypt_ivec (context, crypto, KRB5_KU_USAGE_SEQ, p, 8, &seq_data, &ivec); } krb5_crypto_destroy (context, crypto); if (ret) { *minor_status = ret; HEIMDAL_MUTEX_unlock(&context_handle->ctx_id_mutex); return GSS_S_FAILURE; } if (seq_data.length != 8) { krb5_data_free (&seq_data); *minor_status = 0; HEIMDAL_MUTEX_unlock(&context_handle->ctx_id_mutex); return GSS_S_BAD_MIC; } seq = seq_data.data; _gsskrb5_decode_om_uint32(seq, &seq_number); if (context_handle->more_flags & LOCAL) cmp = ct_memcmp(&seq[4], "\xff\xff\xff\xff", 4); else cmp = ct_memcmp(&seq[4], "\x00\x00\x00\x00", 4); krb5_data_free (&seq_data); if (cmp != 0) { *minor_status = 0; HEIMDAL_MUTEX_unlock(&context_handle->ctx_id_mutex); return GSS_S_BAD_MIC; } ret = _gssapi_msg_order_check(context_handle->order, seq_number); if (ret) { *minor_status = 0; HEIMDAL_MUTEX_unlock(&context_handle->ctx_id_mutex); return ret; } HEIMDAL_MUTEX_unlock(&context_handle->ctx_id_mutex); /* verify checksum */ memcpy (cksum, p + 8, 20); memcpy (p + 20, p - 8, 8); csum.cksumtype = CKSUMTYPE_HMAC_SHA1_DES3; csum.checksum.length = 20; csum.checksum.data = cksum; ret = krb5_crypto_init(context, key, 0, &crypto); if (ret) { *minor_status = ret; return GSS_S_FAILURE; } ret = krb5_verify_checksum (context, crypto, KRB5_KU_USAGE_SIGN, p + 20, input_message_buffer->length - len + 8, &csum); krb5_crypto_destroy (context, crypto); if (ret) { *minor_status = ret; return GSS_S_FAILURE; } /* copy out data */ output_message_buffer->length = input_message_buffer->length - len - padlength - 8; output_message_buffer->value = malloc(output_message_buffer->length); if(output_message_buffer->length != 0 && output_message_buffer->value == NULL) return GSS_S_FAILURE; memcpy (output_message_buffer->value, p + 36, output_message_buffer->length); return GSS_S_COMPLETE; } OM_uint32 GSSAPI_CALLCONV _gsskrb5_unwrap (OM_uint32 * minor_status, gss_const_ctx_id_t context_handle, const gss_buffer_t input_message_buffer, gss_buffer_t output_message_buffer, int * conf_state, gss_qop_t * qop_state ) { krb5_keyblock *key; krb5_context context; OM_uint32 ret; gsskrb5_ctx ctx = (gsskrb5_ctx) context_handle; output_message_buffer->value = NULL; output_message_buffer->length = 0; if (qop_state != NULL) *qop_state = GSS_C_QOP_DEFAULT; GSSAPI_KRB5_INIT (&context); if (ctx->more_flags & IS_CFX) return _gssapi_unwrap_cfx (minor_status, ctx, context, input_message_buffer, output_message_buffer, conf_state, qop_state); HEIMDAL_MUTEX_lock(&ctx->ctx_id_mutex); ret = _gsskrb5i_get_token_key(ctx, context, &key); HEIMDAL_MUTEX_unlock(&ctx->ctx_id_mutex); if (ret) { *minor_status = ret; return GSS_S_FAILURE; } *minor_status = 0; switch (key->keytype) { case KRB5_ENCTYPE_DES_CBC_CRC : case KRB5_ENCTYPE_DES_CBC_MD4 : case KRB5_ENCTYPE_DES_CBC_MD5 : #ifdef HEIM_WEAK_CRYPTO ret = unwrap_des (minor_status, ctx, input_message_buffer, output_message_buffer, conf_state, qop_state, key); #else ret = GSS_S_FAILURE; #endif break; case KRB5_ENCTYPE_DES3_CBC_MD5 : case KRB5_ENCTYPE_DES3_CBC_SHA1 : ret = unwrap_des3 (minor_status, ctx, context, input_message_buffer, output_message_buffer, conf_state, qop_state, key); break; case KRB5_ENCTYPE_ARCFOUR_HMAC_MD5: case KRB5_ENCTYPE_ARCFOUR_HMAC_MD5_56: ret = _gssapi_unwrap_arcfour (minor_status, ctx, context, input_message_buffer, output_message_buffer, conf_state, qop_state, key); break; default : abort(); break; } krb5_free_keyblock (context, key); return ret; } heimdal-7.5.0/lib/gssapi/krb5/test_kcred.c0000644000175000017500000001042413026237312016444 0ustar niknik/* * Copyright (c) 2003-2004 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of KTH nor the names of its contributors may be * used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY KTH AND ITS CONTRIBUTORS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL KTH OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "gsskrb5_locl.h" #include #include static int version_flag = 0; static int help_flag = 0; static void copy_import(void) { gss_cred_id_t cred1, cred2; OM_uint32 maj_stat, min_stat; gss_name_t name1, name2; OM_uint32 lifetime1, lifetime2; gss_cred_usage_t usage1, usage2; gss_OID_set mechs1, mechs2; krb5_ccache id; krb5_error_code ret; krb5_context context; int equal; maj_stat = gss_acquire_cred(&min_stat, GSS_C_NO_NAME, GSS_C_INDEFINITE, GSS_C_NO_OID_SET, GSS_C_INITIATE, &cred1, NULL, NULL); if (maj_stat != GSS_S_COMPLETE) errx(1, "gss_acquire_cred"); maj_stat = gss_inquire_cred(&min_stat, cred1, &name1, &lifetime1, &usage1, &mechs1); if (maj_stat != GSS_S_COMPLETE) errx(1, "gss_inquire_cred"); ret = krb5_init_context(&context); if (ret) errx(1, "krb5_init_context"); ret = krb5_cc_new_unique(context, krb5_cc_type_memory, NULL, &id); if (ret) krb5_err(context, 1, ret, "krb5_cc_new_unique"); maj_stat = gss_krb5_copy_ccache(&min_stat, context, cred1, id); if (maj_stat != GSS_S_COMPLETE) errx(1, "gss_krb5_copy_ccache"); maj_stat = gss_krb5_import_cred(&min_stat, id, NULL, NULL, &cred2); if (maj_stat != GSS_S_COMPLETE) errx(1, "gss_krb5_import_cred"); maj_stat = gss_inquire_cred(&min_stat, cred2, &name2, &lifetime2, &usage2, &mechs2); if (maj_stat != GSS_S_COMPLETE) errx(1, "gss_inquire_cred 2"); maj_stat = gss_compare_name(&min_stat, name1, name2, &equal); if (maj_stat != GSS_S_COMPLETE) errx(1, "gss_compare_name"); if (!equal) errx(1, "names not equal"); if (lifetime1 != lifetime1) errx(1, "lifetime not equal"); if (usage1 != usage1) errx(1, "usage not equal"); gss_release_cred(&min_stat, &cred1); gss_release_cred(&min_stat, &cred2); gss_release_name(&min_stat, &name1); gss_release_name(&min_stat, &name2); #if 0 compare(mechs1, mechs2); #endif gss_release_oid_set(&min_stat, &mechs1); gss_release_oid_set(&min_stat, &mechs2); krb5_cc_destroy(context, id); krb5_free_context(context); } static struct getargs args[] = { {"version", 0, arg_flag, &version_flag, "print version", NULL }, {"help", 0, arg_flag, &help_flag, NULL, NULL } }; static void usage (int ret) { arg_printusage (args, sizeof(args)/sizeof(*args), NULL, ""); exit (ret); } int main(int argc, char **argv) { int optidx = 0; setprogname(argv[0]); if(getarg(args, sizeof(args) / sizeof(args[0]), argc, argv, &optidx)) usage(1); if (help_flag) usage (0); if(version_flag){ print_version(NULL); exit(0); } argc -= optidx; argv += optidx; copy_import(); return 0; } heimdal-7.5.0/lib/gssapi/krb5/export_name.c0000644000175000017500000000610213026237312016634 0ustar niknik/* * Copyright (c) 1997, 1999, 2003 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "gsskrb5_locl.h" OM_uint32 GSSAPI_CALLCONV _gsskrb5_export_name (OM_uint32 * minor_status, gss_const_name_t input_name, gss_buffer_t exported_name ) { krb5_context context; krb5_const_principal princ = (krb5_const_principal)input_name; krb5_error_code kret; char *buf, *name; size_t len; GSSAPI_KRB5_INIT (&context); kret = krb5_unparse_name (context, princ, &name); if (kret) { *minor_status = kret; return GSS_S_FAILURE; } len = strlen (name); exported_name->length = 10 + len + GSS_KRB5_MECHANISM->length; exported_name->value = malloc(exported_name->length); if (exported_name->value == NULL) { free (name); *minor_status = ENOMEM; return GSS_S_FAILURE; } /* TOK, MECH_OID_LEN, DER(MECH_OID), NAME_LEN, NAME */ buf = exported_name->value; memcpy(buf, "\x04\x01", 2); buf += 2; buf[0] = ((GSS_KRB5_MECHANISM->length + 2) >> 8) & 0xff; buf[1] = (GSS_KRB5_MECHANISM->length + 2) & 0xff; buf+= 2; buf[0] = 0x06; buf[1] = (GSS_KRB5_MECHANISM->length) & 0xFF; buf+= 2; memcpy(buf, GSS_KRB5_MECHANISM->elements, GSS_KRB5_MECHANISM->length); buf += GSS_KRB5_MECHANISM->length; buf[0] = (len >> 24) & 0xff; buf[1] = (len >> 16) & 0xff; buf[2] = (len >> 8) & 0xff; buf[3] = (len) & 0xff; buf += 4; memcpy (buf, name, len); free (name); *minor_status = 0; return GSS_S_COMPLETE; } heimdal-7.5.0/lib/gssapi/krb5/inquire_cred_by_oid.c0000644000175000017500000000523513026237312020317 0ustar niknik/* * Copyright (c) 2004, PADL Software Pty Ltd. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of PADL Software nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY PADL SOFTWARE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL PADL SOFTWARE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "gsskrb5_locl.h" OM_uint32 GSSAPI_CALLCONV _gsskrb5_inquire_cred_by_oid (OM_uint32 * minor_status, gss_const_cred_id_t cred_handle, const gss_OID desired_object, gss_buffer_set_t *data_set) { krb5_context context; gsskrb5_cred cred = (gsskrb5_cred)cred_handle; krb5_error_code ret; gss_buffer_desc buffer; char *str; GSSAPI_KRB5_INIT (&context); if (gss_oid_equal(desired_object, GSS_KRB5_COPY_CCACHE_X) == 0) { *minor_status = EINVAL; return GSS_S_FAILURE; } HEIMDAL_MUTEX_lock(&cred->cred_id_mutex); if (cred->ccache == NULL) { HEIMDAL_MUTEX_unlock(&cred->cred_id_mutex); *minor_status = EINVAL; return GSS_S_FAILURE; } ret = krb5_cc_get_full_name(context, cred->ccache, &str); HEIMDAL_MUTEX_unlock(&cred->cred_id_mutex); if (ret) { *minor_status = ret; return GSS_S_FAILURE; } buffer.value = str; buffer.length = strlen(str); ret = gss_add_buffer_set_member(minor_status, &buffer, data_set); if (ret != GSS_S_COMPLETE) _gsskrb5_clear_status (); free(str); *minor_status = 0; return GSS_S_COMPLETE; } heimdal-7.5.0/lib/gssapi/krb5/inquire_cred.c0000644000175000017500000002101413026237312016763 0ustar niknik/* * Copyright (c) 1997, 2003 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "gsskrb5_locl.h" OM_uint32 GSSAPI_CALLCONV _gsskrb5_inquire_cred (OM_uint32 * minor_status, gss_const_cred_id_t cred_handle, gss_name_t * output_name, OM_uint32 * lifetime, gss_cred_usage_t * cred_usage, gss_OID_set * mechanisms ) { krb5_context context; gss_cred_id_t aqcred_init = GSS_C_NO_CREDENTIAL; gss_cred_id_t aqcred_accept = GSS_C_NO_CREDENTIAL; gsskrb5_cred cred = (gsskrb5_cred)cred_handle; gss_OID_set amechs = GSS_C_NO_OID_SET; gss_OID_set imechs = GSS_C_NO_OID_SET; OM_uint32 junk; OM_uint32 aminor; OM_uint32 ret; OM_uint32 aret; OM_uint32 alife = GSS_C_INDEFINITE; OM_uint32 ilife = GSS_C_INDEFINITE; /* * XXX This function is more complex than it has to be. It should call * _gsskrb5_inquire_cred_by_mech() twice and merge the results in the * cred_handle == GSS_C_NO_CREDENTIAL case, but since * _gsskrb5_inquire_cred_by_mech() is implemented in terms of this * function, first we must fix _gsskrb5_inquire_cred_by_mech(). */ *minor_status = 0; if (output_name) *output_name = GSS_C_NO_NAME; if (cred_usage) *cred_usage = GSS_C_BOTH; /* There's no NONE */ if (mechanisms) *mechanisms = GSS_C_NO_OID_SET; GSSAPI_KRB5_INIT (&context); if (cred_handle == GSS_C_NO_CREDENTIAL) { /* * From here to the end of this if we should refactor into a separate * function. */ /* Get the info for the default ACCEPT credential */ aret = _gsskrb5_acquire_cred(&aminor, GSS_C_NO_NAME, GSS_C_INDEFINITE, GSS_C_NO_OID_SET, GSS_C_ACCEPT, &aqcred_accept, NULL, NULL); if (aret == GSS_S_COMPLETE) { aret = _gsskrb5_inquire_cred(&aminor, aqcred_accept, output_name, &alife, NULL, &amechs); (void) _gsskrb5_release_cred(&junk, &aqcred_accept); if (aret == GSS_S_COMPLETE) { output_name = NULL; /* Can't merge names; output only one */ if (cred_usage) *cred_usage = GSS_C_ACCEPT; if (lifetime) *lifetime = alife; if (mechanisms) { *mechanisms = amechs; amechs = GSS_C_NO_OID_SET; } (void) gss_release_oid_set(&junk, &amechs); } else if (aret != GSS_S_NO_CRED) { *minor_status = aminor; return aret; } else { alife = GSS_C_INDEFINITE; } } /* Get the info for the default INITIATE credential */ ret = _gsskrb5_acquire_cred(minor_status, GSS_C_NO_NAME, GSS_C_INDEFINITE, GSS_C_NO_OID_SET, GSS_C_INITIATE, &aqcred_init, NULL, NULL); if (ret == GSS_S_COMPLETE) { ret = _gsskrb5_inquire_cred(minor_status, aqcred_init, output_name, &ilife, NULL, &imechs); (void) _gsskrb5_release_cred(&junk, &aqcred_init); if (ret == GSS_S_COMPLETE) { /* * Merge results for INITIATE with ACCEPT if we had ACCEPT and * for those outputs that are desired. */ if (cred_usage) { *cred_usage = (*cred_usage == GSS_C_ACCEPT) ? GSS_C_BOTH : GSS_C_INITIATE; } if (lifetime) *lifetime = min(alife, ilife); if (mechanisms) { /* * This is just one mechanism (IAKERB and such would live * elsewhere). imechs will be equal to amechs, though not * ==. */ if (aret != GSS_S_COMPLETE) { *mechanisms = imechs; imechs = GSS_C_NO_OID_SET; } } (void) gss_release_oid_set(&junk, &amechs); } else if (ret != GSS_S_NO_CRED) { *minor_status = aminor; return aret; } } if (aret != GSS_S_COMPLETE && ret != GSS_S_COMPLETE) { *minor_status = aminor; return aret; } *minor_status = 0; /* Even though 0 is not specified to be special */ return GSS_S_COMPLETE; } HEIMDAL_MUTEX_lock(&cred->cred_id_mutex); if (output_name != NULL) { if (cred->principal != NULL) { gss_name_t name = (gss_name_t)cred->principal; ret = _gsskrb5_duplicate_name(minor_status, name, output_name); if (ret) goto out; } else if (cred->usage == GSS_C_ACCEPT) { /* * Keytab case, princ may not be set (yet, ever, whatever). * * We used to unconditionally output the krb5_sname_to_principal() * of the host service for the hostname, but we didn't know if we * had keytab entries for it, so it was incorrect. We can't be * breaking anything in tree by outputting GSS_C_NO_NAME, but we * might be breaking other callers. */ *output_name = GSS_C_NO_NAME; } else { /* This shouldn't happen */ *minor_status = KRB5_NOCREDS_SUPPLIED; /* XXX */ ret = GSS_S_NO_CRED; goto out; } } if (lifetime != NULL) { ret = _gsskrb5_lifetime_left(minor_status, context, cred->endtime, lifetime); if (ret) goto out; } if (cred_usage != NULL) *cred_usage = cred->usage; if (mechanisms != NULL) { ret = gss_create_empty_oid_set(minor_status, mechanisms); if (ret) goto out; ret = gss_add_oid_set_member(minor_status, &cred->mechanisms->elements[0], mechanisms); if (ret) goto out; } ret = GSS_S_COMPLETE; out: HEIMDAL_MUTEX_unlock(&cred->cred_id_mutex); return ret; } heimdal-7.5.0/lib/gssapi/krb5/acquire_cred.c0000644000175000017500000004443513026237312016754 0ustar niknik/* * Copyright (c) 1997 - 2005 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "gsskrb5_locl.h" OM_uint32 __gsskrb5_ccache_lifetime(OM_uint32 *minor_status, krb5_context context, krb5_ccache id, krb5_principal principal, OM_uint32 *lifetime) { krb5_error_code kret; time_t left; kret = krb5_cc_get_lifetime(context, id, &left); if (kret) { *minor_status = kret; return GSS_S_FAILURE; } *lifetime = left; return GSS_S_COMPLETE; } static krb5_error_code get_keytab(krb5_context context, krb5_keytab *keytab) { krb5_error_code kret; HEIMDAL_MUTEX_lock(&gssapi_keytab_mutex); if (_gsskrb5_keytab != NULL) { char *name = NULL; kret = krb5_kt_get_full_name(context, _gsskrb5_keytab, &name); if (kret == 0) { kret = krb5_kt_resolve(context, name, keytab); krb5_xfree(name); } } else kret = krb5_kt_default(context, keytab); HEIMDAL_MUTEX_unlock(&gssapi_keytab_mutex); return (kret); } /* * This function produces a cred with a MEMORY ccache containing a TGT * acquired with a password. */ static OM_uint32 acquire_cred_with_password(OM_uint32 *minor_status, krb5_context context, const char *password, OM_uint32 time_req, gss_const_OID desired_mech, gss_cred_usage_t cred_usage, gsskrb5_cred handle) { OM_uint32 ret = GSS_S_FAILURE; krb5_creds cred; krb5_get_init_creds_opt *opt; krb5_ccache ccache = NULL; krb5_error_code kret; time_t now; OM_uint32 left; if (cred_usage == GSS_C_ACCEPT) { /* * TODO: Here we should eventually support user2user (when we get * support for that via an extension to the mechanism * allowing for more than two security context tokens), * and/or new unique MEMORY keytabs (we have MEMORY keytab * support, but we don't have a keytab equivalent of * krb5_cc_new_unique()). Either way, for now we can't * support this. */ *minor_status = ENOTSUP; /* XXX Better error? */ return GSS_S_FAILURE; } memset(&cred, 0, sizeof(cred)); if (handle->principal == NULL) { kret = krb5_get_default_principal(context, &handle->principal); if (kret) goto end; } kret = krb5_get_init_creds_opt_alloc(context, &opt); if (kret) goto end; /* * Get the current time before the AS exchange so we don't * accidentally end up returning a value that puts advertised * expiration past the real expiration. * * We need to do this because krb5_cc_get_lifetime() returns a * relative time that we need to add to the current time. We ought * to have a version of krb5_cc_get_lifetime() that returns absolute * time... */ krb5_timeofday(context, &now); kret = krb5_get_init_creds_password(context, &cred, handle->principal, password, NULL, NULL, 0, NULL, opt); krb5_get_init_creds_opt_free(context, opt); if (kret) goto end; kret = krb5_cc_new_unique(context, krb5_cc_type_memory, NULL, &ccache); if (kret) goto end; kret = krb5_cc_initialize(context, ccache, cred.client); if (kret) goto end; kret = krb5_cc_store_cred(context, ccache, &cred); if (kret) goto end; handle->cred_flags |= GSS_CF_DESTROY_CRED_ON_RELEASE; ret = __gsskrb5_ccache_lifetime(minor_status, context, ccache, handle->principal, &left); if (ret != GSS_S_COMPLETE) goto end; handle->endtime = now + left; handle->ccache = ccache; ccache = NULL; ret = GSS_S_COMPLETE; kret = 0; end: if (ccache != NULL) krb5_cc_destroy(context, ccache); if (cred.client != NULL) krb5_free_cred_contents(context, &cred); if (ret != GSS_S_COMPLETE && kret != 0) *minor_status = kret; return (ret); } /* * Acquires an initiator credential from a ccache or using a keytab. */ static OM_uint32 acquire_initiator_cred(OM_uint32 *minor_status, krb5_context context, OM_uint32 time_req, gss_const_OID desired_mech, gss_cred_usage_t cred_usage, gsskrb5_cred handle) { OM_uint32 ret = GSS_S_FAILURE; krb5_creds cred; krb5_get_init_creds_opt *opt; krb5_principal def_princ = NULL; krb5_ccache def_ccache = NULL; krb5_ccache ccache = NULL; /* we may store into this ccache */ krb5_keytab keytab = NULL; krb5_error_code kret = 0; OM_uint32 left; time_t lifetime = 0; time_t now; memset(&cred, 0, sizeof(cred)); /* * Get current time early so we can set handle->endtime to a value that * cannot accidentally be past the real endtime. We need a variant of * krb5_cc_get_lifetime() that returns absolute endtime. */ krb5_timeofday(context, &now); /* * First look for a ccache that has the desired_name (which may be * the default credential name). * * If we don't have an unexpired credential, acquire one with a * keytab. * * If we acquire one with a keytab, save it in the ccache we found * with the expired credential, if any. * * If we don't have any such ccache, then use a MEMORY ccache. */ if (handle->principal != NULL) { /* * Not default credential case. See if we can find a ccache in * the cccol for the desired_name. */ kret = krb5_cc_cache_match(context, handle->principal, &ccache); if (kret == 0) { kret = krb5_cc_get_lifetime(context, ccache, &lifetime); if (kret == 0) { if (lifetime > 0) goto found; else goto try_keytab; } } /* * Fall through. We shouldn't find this in the default ccache * either, but we'll give it a try, then we'll try using a keytab. */ } /* * Either desired_name was GSS_C_NO_NAME (default cred) or * krb5_cc_cache_match() failed (or found expired). */ kret = krb5_cc_default(context, &def_ccache); if (kret != 0) goto try_keytab; kret = krb5_cc_get_lifetime(context, def_ccache, &lifetime); if (kret != 0) lifetime = 0; kret = krb5_cc_get_principal(context, def_ccache, &def_princ); if (kret != 0) goto try_keytab; /* * Have a default ccache; see if it matches desired_name. */ if (handle->principal == NULL || krb5_principal_compare(context, handle->principal, def_princ) == TRUE) { /* * It matches. * * If we end up trying a keytab then we can write the result to * the default ccache. */ if (handle->principal == NULL) { kret = krb5_copy_principal(context, def_princ, &handle->principal); if (kret) goto end; } if (ccache != NULL) krb5_cc_close(context, ccache); ccache = def_ccache; def_ccache = NULL; if (lifetime > 0) goto found; /* else we fall through and try using a keytab */ } try_keytab: if (handle->principal == NULL) { /* We need to know what client principal to use */ kret = krb5_get_default_principal(context, &handle->principal); if (kret) goto end; } kret = get_keytab(context, &keytab); if (kret) goto end; kret = krb5_get_init_creds_opt_alloc(context, &opt); if (kret) goto end; krb5_timeofday(context, &now); kret = krb5_get_init_creds_keytab(context, &cred, handle->principal, keytab, 0, NULL, opt); krb5_get_init_creds_opt_free(context, opt); if (kret) goto end; /* * We got a credential with a keytab. Save it if we can. */ if (ccache == NULL) { /* * There's no ccache we can overwrite with the credentials we acquired * with a keytab. We'll use a MEMORY ccache then. * * Note that an application that falls into this repeatedly will do an * AS exchange every time it acquires a credential handle. Hopefully * this doesn't happen much. A workaround is to kinit -k once so that * we always re-initialize the matched/default ccache here. I.e., once * there's a FILE/DIR ccache, we'll keep it frash automatically if we * have a keytab, but if there's no FILE/DIR ccache, then we'll * get a fresh credential *every* time we're asked. */ kret = krb5_cc_new_unique(context, krb5_cc_type_memory, NULL, &ccache); if (kret) goto end; handle->cred_flags |= GSS_CF_DESTROY_CRED_ON_RELEASE; } /* else we'll re-initialize whichever ccache we matched above */ kret = krb5_cc_initialize(context, ccache, cred.client); if (kret) goto end; kret = krb5_cc_store_cred(context, ccache, &cred); if (kret) goto end; found: assert(handle->principal != NULL); ret = __gsskrb5_ccache_lifetime(minor_status, context, ccache, handle->principal, &left); if (ret != GSS_S_COMPLETE) goto end; handle->endtime = now + left; handle->ccache = ccache; ccache = NULL; ret = GSS_S_COMPLETE; kret = 0; end: if (ccache != NULL) { if ((handle->cred_flags & GSS_CF_DESTROY_CRED_ON_RELEASE) != 0) krb5_cc_destroy(context, ccache); else krb5_cc_close(context, ccache); } if (def_ccache != NULL) krb5_cc_close(context, def_ccache); if (cred.client != NULL) krb5_free_cred_contents(context, &cred); if (def_princ != NULL) krb5_free_principal(context, def_princ); if (keytab != NULL) krb5_kt_close(context, keytab); if (ret != GSS_S_COMPLETE && kret != 0) *minor_status = kret; return (ret); } static OM_uint32 acquire_acceptor_cred(OM_uint32 * minor_status, krb5_context context, OM_uint32 time_req, gss_const_OID desired_mech, gss_cred_usage_t cred_usage, gsskrb5_cred handle) { OM_uint32 ret; krb5_error_code kret; ret = GSS_S_FAILURE; kret = get_keytab(context, &handle->keytab); if (kret) goto end; /* check that the requested principal exists in the keytab */ if (handle->principal) { krb5_keytab_entry entry; kret = krb5_kt_get_entry(context, handle->keytab, handle->principal, 0, 0, &entry); if (kret) goto end; krb5_kt_free_entry(context, &entry); ret = GSS_S_COMPLETE; } else { /* * Check if there is at least one entry in the keytab before * declaring it as an useful keytab. */ krb5_keytab_entry tmp; krb5_kt_cursor c; kret = krb5_kt_start_seq_get (context, handle->keytab, &c); if (kret) goto end; if (krb5_kt_next_entry(context, handle->keytab, &tmp, &c) == 0) { krb5_kt_free_entry(context, &tmp); ret = GSS_S_COMPLETE; /* ok found one entry */ } krb5_kt_end_seq_get (context, handle->keytab, &c); } end: if (ret != GSS_S_COMPLETE) { if (handle->keytab != NULL) krb5_kt_close(context, handle->keytab); if (kret != 0) { *minor_status = kret; } } return (ret); } OM_uint32 GSSAPI_CALLCONV _gsskrb5_acquire_cred (OM_uint32 * minor_status, gss_const_name_t desired_name, OM_uint32 time_req, const gss_OID_set desired_mechs, gss_cred_usage_t cred_usage, gss_cred_id_t * output_cred_handle, gss_OID_set * actual_mechs, OM_uint32 * time_rec ) { OM_uint32 ret; if (desired_mechs) { int present = 0; ret = gss_test_oid_set_member(minor_status, GSS_KRB5_MECHANISM, desired_mechs, &present); if (ret) return ret; if (!present) { *minor_status = 0; return GSS_S_BAD_MECH; } } ret = _gsskrb5_acquire_cred_ext(minor_status, desired_name, GSS_C_NO_OID, NULL, time_req, GSS_KRB5_MECHANISM, cred_usage, output_cred_handle); if (ret) return ret; ret = _gsskrb5_inquire_cred(minor_status, *output_cred_handle, NULL, time_rec, NULL, actual_mechs); if (ret) { OM_uint32 tmp; _gsskrb5_release_cred(&tmp, output_cred_handle); } return ret; } OM_uint32 GSSAPI_CALLCONV _gsskrb5_acquire_cred_ext (OM_uint32 * minor_status, gss_const_name_t desired_name, gss_const_OID credential_type, const void *credential_data, OM_uint32 time_req, gss_const_OID desired_mech, gss_cred_usage_t cred_usage, gss_cred_id_t * output_cred_handle ) { krb5_context context; gsskrb5_cred handle; OM_uint32 ret; cred_usage &= GSS_C_OPTION_MASK; if (cred_usage != GSS_C_ACCEPT && cred_usage != GSS_C_INITIATE && cred_usage != GSS_C_BOTH) { *minor_status = GSS_KRB5_S_G_BAD_USAGE; return GSS_S_FAILURE; } GSSAPI_KRB5_INIT(&context); *output_cred_handle = GSS_C_NO_CREDENTIAL; handle = calloc(1, sizeof(*handle)); if (handle == NULL) { *minor_status = ENOMEM; return GSS_S_FAILURE; } HEIMDAL_MUTEX_init(&handle->cred_id_mutex); if (desired_name != GSS_C_NO_NAME) { ret = _gsskrb5_canon_name(minor_status, context, desired_name, &handle->principal); if (ret) { HEIMDAL_MUTEX_destroy(&handle->cred_id_mutex); free(handle); return ret; } } if (credential_type != GSS_C_NO_OID && gss_oid_equal(credential_type, GSS_C_CRED_PASSWORD)) { /* Acquire a cred with a password */ gss_const_buffer_t pwbuf = credential_data; char *pw; if (pwbuf == NULL) { HEIMDAL_MUTEX_destroy(&handle->cred_id_mutex); free(handle); *minor_status = KRB5_NOCREDS_SUPPLIED; /* see below */ return GSS_S_CALL_INACCESSIBLE_READ; } /* NUL-terminate the password, if it wasn't already */ pw = strndup(pwbuf->value, pwbuf->length); if (pw == NULL) { HEIMDAL_MUTEX_destroy(&handle->cred_id_mutex); free(handle); *minor_status = krb5_enomem(context); return GSS_S_CALL_INACCESSIBLE_READ; } ret = acquire_cred_with_password(minor_status, context, pw, time_req, desired_mech, cred_usage, handle); free(pw); if (ret != GSS_S_COMPLETE) { HEIMDAL_MUTEX_destroy(&handle->cred_id_mutex); krb5_free_principal(context, handle->principal); free(handle); return (ret); } } else if (credential_type != GSS_C_NO_OID) { /* * _gss_acquire_cred_ext() called with something other than a password. * * Not supported. * * _gss_acquire_cred_ext() is not a supported public interface, so * we don't have to try too hard as to minor status codes here. */ HEIMDAL_MUTEX_destroy(&handle->cred_id_mutex); free(handle); *minor_status = ENOTSUP; return GSS_S_FAILURE; } else { /* * Acquire a credential from the background credential store (ccache, * keytab). */ if (cred_usage == GSS_C_INITIATE || cred_usage == GSS_C_BOTH) { ret = acquire_initiator_cred(minor_status, context, time_req, desired_mech, cred_usage, handle); if (ret != GSS_S_COMPLETE) { HEIMDAL_MUTEX_destroy(&handle->cred_id_mutex); krb5_free_principal(context, handle->principal); free(handle); return (ret); } } if (cred_usage == GSS_C_ACCEPT || cred_usage == GSS_C_BOTH) { ret = acquire_acceptor_cred(minor_status, context, time_req, desired_mech, cred_usage, handle); if (ret != GSS_S_COMPLETE) { HEIMDAL_MUTEX_destroy(&handle->cred_id_mutex); krb5_free_principal(context, handle->principal); free(handle); return (ret); } } } ret = gss_create_empty_oid_set(minor_status, &handle->mechanisms); if (ret == GSS_S_COMPLETE) ret = gss_add_oid_set_member(minor_status, GSS_KRB5_MECHANISM, &handle->mechanisms); if (ret != GSS_S_COMPLETE) { if (handle->mechanisms != NULL) gss_release_oid_set(NULL, &handle->mechanisms); HEIMDAL_MUTEX_destroy(&handle->cred_id_mutex); krb5_free_principal(context, handle->principal); free(handle); return (ret); } handle->usage = cred_usage; *minor_status = 0; *output_cred_handle = (gss_cred_id_t)handle; return (GSS_S_COMPLETE); } heimdal-7.5.0/lib/gssapi/krb5/cfx.h0000644000175000017500000000440312136107747015113 0ustar niknik/* * Copyright (c) 2003, PADL Software Pty Ltd. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of PADL Software nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY PADL SOFTWARE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL PADL SOFTWARE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ /* $Id$ */ #ifndef GSSAPI_CFX_H_ #define GSSAPI_CFX_H_ 1 /* * Implementation of draft-ietf-krb-wg-gssapi-cfx-01.txt */ typedef struct gss_cfx_mic_token_desc_struct { u_char TOK_ID[2]; /* 04 04 */ u_char Flags; u_char Filler[5]; u_char SND_SEQ[8]; } gss_cfx_mic_token_desc, *gss_cfx_mic_token; typedef struct gss_cfx_wrap_token_desc_struct { u_char TOK_ID[2]; /* 04 05 */ u_char Flags; u_char Filler; u_char EC[2]; u_char RRC[2]; u_char SND_SEQ[8]; } gss_cfx_wrap_token_desc, *gss_cfx_wrap_token; typedef struct gss_cfx_delete_token_desc_struct { u_char TOK_ID[2]; /* 05 04 */ u_char Flags; u_char Filler[5]; u_char SND_SEQ[8]; } gss_cfx_delete_token_desc, *gss_cfx_delete_token; #endif /* GSSAPI_CFX_H_ */ heimdal-7.5.0/lib/gssapi/krb5/external.c0000644000175000017500000002446613026237312016152 0ustar niknik/* * Copyright (c) 1997 - 2000 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "gsskrb5_locl.h" #include /* * The implementation must reserve static storage for a * gss_OID_desc object containing the value * {10, (void *)"\x2a\x86\x48\x86\xf7\x12" * "\x01\x02\x01\x01"}, * corresponding to an object-identifier value of * {iso(1) member-body(2) United States(840) mit(113554) * infosys(1) gssapi(2) generic(1) user_name(1)}. The constant * GSS_C_NT_USER_NAME should be initialized to point * to that gss_OID_desc. */ gss_OID_desc GSSAPI_LIB_VARIABLE __gss_c_nt_user_name_oid_desc = {10, rk_UNCONST("\x2a\x86\x48\x86\xf7\x12" "\x01\x02\x01\x01")}; /* * The implementation must reserve static storage for a * gss_OID_desc object containing the value * {10, (void *)"\x2a\x86\x48\x86\xf7\x12" * "\x01\x02\x01\x02"}, * corresponding to an object-identifier value of * {iso(1) member-body(2) United States(840) mit(113554) * infosys(1) gssapi(2) generic(1) machine_uid_name(2)}. * The constant GSS_C_NT_MACHINE_UID_NAME should be * initialized to point to that gss_OID_desc. */ gss_OID_desc GSSAPI_LIB_VARIABLE __gss_c_nt_machine_uid_name_oid_desc = {10, rk_UNCONST("\x2a\x86\x48\x86\xf7\x12" "\x01\x02\x01\x02")}; /* * The implementation must reserve static storage for a * gss_OID_desc object containing the value * {10, (void *)"\x2a\x86\x48\x86\xf7\x12" * "\x01\x02\x01\x03"}, * corresponding to an object-identifier value of * {iso(1) member-body(2) United States(840) mit(113554) * infosys(1) gssapi(2) generic(1) string_uid_name(3)}. * The constant GSS_C_NT_STRING_UID_NAME should be * initialized to point to that gss_OID_desc. */ gss_OID_desc GSSAPI_LIB_VARIABLE __gss_c_nt_string_uid_name_oid_desc = {10, rk_UNCONST("\x2a\x86\x48\x86\xf7\x12" "\x01\x02\x01\x03")}; /* * The implementation must reserve static storage for a * gss_OID_desc object containing the value * {6, (void *)"\x2b\x06\x01\x05\x06\x02"}, * corresponding to an object-identifier value of * {iso(1) org(3) dod(6) internet(1) security(5) * nametypes(6) gss-host-based-services(2)). The constant * GSS_C_NT_HOSTBASED_SERVICE_X should be initialized to point * to that gss_OID_desc. This is a deprecated OID value, and * implementations wishing to support hostbased-service names * should instead use the GSS_C_NT_HOSTBASED_SERVICE OID, * defined below, to identify such names; * GSS_C_NT_HOSTBASED_SERVICE_X should be accepted a synonym * for GSS_C_NT_HOSTBASED_SERVICE when presented as an input * parameter, but should not be emitted by GSS-API * implementations */ gss_OID_desc GSSAPI_LIB_VARIABLE __gss_c_nt_hostbased_service_x_oid_desc = {6, rk_UNCONST("\x2b\x06\x01\x05\x06\x02")}; /* * The implementation must reserve static storage for a * gss_OID_desc object containing the value * {10, (void *)"\x2a\x86\x48\x86\xf7\x12" * "\x01\x02\x01\x04"}, corresponding to an * object-identifier value of {iso(1) member-body(2) * Unites States(840) mit(113554) infosys(1) gssapi(2) * generic(1) service_name(4)}. The constant * GSS_C_NT_HOSTBASED_SERVICE should be initialized * to point to that gss_OID_desc. */ gss_OID_desc GSSAPI_LIB_VARIABLE __gss_c_nt_hostbased_service_oid_desc = {10, rk_UNCONST("\x2a\x86\x48\x86\xf7\x12" "\x01\x02\x01\x04")}; /* * The implementation must reserve static storage for a * gss_OID_desc object containing the value * {6, (void *)"\x2b\x06\01\x05\x06\x03"}, * corresponding to an object identifier value of * {1(iso), 3(org), 6(dod), 1(internet), 5(security), * 6(nametypes), 3(gss-anonymous-name)}. The constant * and GSS_C_NT_ANONYMOUS should be initialized to point * to that gss_OID_desc. */ gss_OID_desc GSSAPI_LIB_VARIABLE __gss_c_nt_anonymous_oid_desc = {6, rk_UNCONST("\x2b\x06\01\x05\x06\x03")}; /* * The implementation must reserve static storage for a * gss_OID_desc object containing the value * {6, (void *)"\x2b\x06\x01\x05\x06\x04"}, * corresponding to an object-identifier value of * {1(iso), 3(org), 6(dod), 1(internet), 5(security), * 6(nametypes), 4(gss-api-exported-name)}. The constant * GSS_C_NT_EXPORT_NAME should be initialized to point * to that gss_OID_desc. */ gss_OID_desc GSSAPI_LIB_VARIABLE __gss_c_nt_export_name_oid_desc = {6, rk_UNCONST("\x2b\x06\x01\x05\x06\x04") }; /* * This name form shall be represented by the Object Identifier {iso(1) * member-body(2) United States(840) mit(113554) infosys(1) gssapi(2) * krb5(2) krb5_name(1)}. The recommended symbolic name for this type * is "GSS_KRB5_NT_PRINCIPAL_NAME". */ gss_OID_desc GSSAPI_LIB_VARIABLE __gss_krb5_nt_principal_name_oid_desc = {10, rk_UNCONST("\x2a\x86\x48\x86\xf7\x12\x01\x02\x02\x01") }; /* * draft-ietf-cat-iakerb-09, IAKERB: * The mechanism ID for IAKERB proxy GSS-API Kerberos, in accordance * with the mechanism proposed by SPNEGO [7] for negotiating protocol * variations, is: {iso(1) org(3) dod(6) internet(1) security(5) * mechanisms(5) iakerb(10) iakerbProxyProtocol(1)}. The proposed * mechanism ID for IAKERB minimum messages GSS-API Kerberos, in * accordance with the mechanism proposed by SPNEGO for negotiating * protocol variations, is: {iso(1) org(3) dod(6) internet(1) * security(5) mechanisms(5) iakerb(10) * iakerbMinimumMessagesProtocol(2)}. */ gss_OID_desc GSSAPI_LIB_VARIABLE __gss_iakerb_proxy_mechanism_oid_desc = {7, rk_UNCONST("\x2b\x06\x01\x05\x05\x0a\x01")}; gss_OID_desc GSSAPI_LIB_VARIABLE __gss_iakerb_min_msg_mechanism_oid_desc = {7, rk_UNCONST("\x2b\x06\x01\x05\x05\x0a\x02") }; /* * Context for krb5 calls. */ static gss_mo_desc krb5_mo[] = { { GSS_C_MA_SASL_MECH_NAME, GSS_MO_MA, "SASL mech name", rk_UNCONST("GS2-KRB5"), _gss_mo_get_ctx_as_string, NULL }, { GSS_C_MA_MECH_NAME, GSS_MO_MA, "Mechanism name", rk_UNCONST("KRB5"), _gss_mo_get_ctx_as_string, NULL }, { GSS_C_MA_MECH_DESCRIPTION, GSS_MO_MA, "Mechanism description", rk_UNCONST("Heimdal Kerberos 5 mech"), _gss_mo_get_ctx_as_string, NULL }, { GSS_C_MA_MECH_CONCRETE, GSS_MO_MA, NULL, NULL, NULL, NULL }, { GSS_C_MA_ITOK_FRAMED, GSS_MO_MA, NULL, NULL, NULL, NULL }, { GSS_C_MA_AUTH_INIT, GSS_MO_MA, NULL, NULL, NULL, NULL }, { GSS_C_MA_AUTH_TARG, GSS_MO_MA, NULL, NULL, NULL, NULL }, { GSS_C_MA_AUTH_INIT_ANON, GSS_MO_MA, NULL, NULL, NULL, NULL }, { GSS_C_MA_DELEG_CRED, GSS_MO_MA, NULL, NULL, NULL, NULL }, { GSS_C_MA_INTEG_PROT, GSS_MO_MA, NULL, NULL, NULL, NULL }, { GSS_C_MA_CONF_PROT, GSS_MO_MA, NULL, NULL, NULL, NULL }, { GSS_C_MA_MIC, GSS_MO_MA, NULL, NULL, NULL, NULL }, { GSS_C_MA_WRAP, GSS_MO_MA, NULL, NULL, NULL, NULL }, { GSS_C_MA_PROT_READY, GSS_MO_MA, NULL, NULL, NULL, NULL }, { GSS_C_MA_REPLAY_DET, GSS_MO_MA, NULL, NULL, NULL, NULL }, { GSS_C_MA_OOS_DET, GSS_MO_MA, NULL, NULL, NULL, NULL }, { GSS_C_MA_CBINDINGS, GSS_MO_MA, NULL, NULL, NULL, NULL }, { GSS_C_MA_PFS, GSS_MO_MA, NULL, NULL, NULL, NULL }, { GSS_C_MA_CTX_TRANS, GSS_MO_MA, NULL, NULL, NULL, NULL } }; /* * */ static gssapi_mech_interface_desc krb5_mech = { GMI_VERSION, "kerberos 5", {9, rk_UNCONST("\x2a\x86\x48\x86\xf7\x12\x01\x02\x02") }, 0, _gsskrb5_acquire_cred, _gsskrb5_release_cred, _gsskrb5_init_sec_context, _gsskrb5_accept_sec_context, _gsskrb5_process_context_token, _gsskrb5_delete_sec_context, _gsskrb5_context_time, _gsskrb5_get_mic, _gsskrb5_verify_mic, _gsskrb5_wrap, _gsskrb5_unwrap, _gsskrb5_display_status, _gsskrb5_indicate_mechs, _gsskrb5_compare_name, _gsskrb5_display_name, _gsskrb5_import_name, _gsskrb5_export_name, _gsskrb5_release_name, _gsskrb5_inquire_cred, _gsskrb5_inquire_context, _gsskrb5_wrap_size_limit, _gsskrb5_add_cred, _gsskrb5_inquire_cred_by_mech, _gsskrb5_export_sec_context, _gsskrb5_import_sec_context, _gsskrb5_inquire_names_for_mech, _gsskrb5_inquire_mechs_for_name, _gsskrb5_canonicalize_name, _gsskrb5_duplicate_name, _gsskrb5_inquire_sec_context_by_oid, _gsskrb5_inquire_cred_by_oid, _gsskrb5_set_sec_context_option, _gsskrb5_set_cred_option, _gsskrb5_pseudo_random, _gk_wrap_iov, _gk_unwrap_iov, _gk_wrap_iov_length, _gsskrb5_store_cred, _gsskrb5_export_cred, _gsskrb5_import_cred, _gsskrb5_acquire_cred_ext, NULL, NULL, NULL, NULL, NULL, NULL, krb5_mo, sizeof(krb5_mo) / sizeof(krb5_mo[0]), _gsskrb5_localname, _gsskrb5_authorize_localname, NULL, NULL, NULL, NULL, NULL, NULL, NULL }; gssapi_mech_interface __gss_krb5_initialize(void) { return &krb5_mech; } heimdal-7.5.0/lib/gssapi/krb5/aeap.c0000644000175000017500000001214113026237312015221 0ustar niknik/* * Copyright (c) 2008 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "gsskrb5_locl.h" #include OM_uint32 GSSAPI_CALLCONV _gk_wrap_iov(OM_uint32 * minor_status, gss_ctx_id_t context_handle, int conf_req_flag, gss_qop_t qop_req, int * conf_state, gss_iov_buffer_desc *iov, int iov_count) { const gsskrb5_ctx ctx = (const gsskrb5_ctx) context_handle; krb5_context context; OM_uint32 ret; krb5_keyblock *key; krb5_keytype keytype; GSSAPI_KRB5_INIT (&context); if (ctx->more_flags & IS_CFX) return _gssapi_wrap_cfx_iov(minor_status, ctx, context, conf_req_flag, conf_state, iov, iov_count); HEIMDAL_MUTEX_lock(&ctx->ctx_id_mutex); ret = _gsskrb5i_get_token_key(ctx, context, &key); HEIMDAL_MUTEX_unlock(&ctx->ctx_id_mutex); if (ret) { *minor_status = ret; return GSS_S_FAILURE; } krb5_enctype_to_keytype(context, key->keytype, &keytype); switch (keytype) { case KEYTYPE_ARCFOUR: case KEYTYPE_ARCFOUR_56: ret = _gssapi_wrap_iov_arcfour(minor_status, ctx, context, conf_req_flag, conf_state, iov, iov_count, key); break; default: ret = GSS_S_FAILURE; break; } krb5_free_keyblock(context, key); return ret; } OM_uint32 GSSAPI_CALLCONV _gk_unwrap_iov(OM_uint32 *minor_status, gss_ctx_id_t context_handle, int *conf_state, gss_qop_t *qop_state, gss_iov_buffer_desc *iov, int iov_count) { const gsskrb5_ctx ctx = (const gsskrb5_ctx) context_handle; krb5_context context; OM_uint32 ret; krb5_keytype keytype; krb5_keyblock *key; GSSAPI_KRB5_INIT (&context); if (ctx->more_flags & IS_CFX) return _gssapi_unwrap_cfx_iov(minor_status, ctx, context, conf_state, qop_state, iov, iov_count); HEIMDAL_MUTEX_lock(&ctx->ctx_id_mutex); ret = _gsskrb5i_get_token_key(ctx, context, &key); HEIMDAL_MUTEX_unlock(&ctx->ctx_id_mutex); if (ret) { *minor_status = ret; return GSS_S_FAILURE; } krb5_enctype_to_keytype(context, key->keytype, &keytype); switch (keytype) { case KEYTYPE_ARCFOUR: case KEYTYPE_ARCFOUR_56: ret = _gssapi_unwrap_iov_arcfour(minor_status, ctx, context, conf_state, qop_state, iov, iov_count, key); break; default: ret = GSS_S_FAILURE; break; } krb5_free_keyblock(context, key); return ret; } OM_uint32 GSSAPI_CALLCONV _gk_wrap_iov_length(OM_uint32 * minor_status, gss_ctx_id_t context_handle, int conf_req_flag, gss_qop_t qop_req, int *conf_state, gss_iov_buffer_desc *iov, int iov_count) { const gsskrb5_ctx ctx = (const gsskrb5_ctx) context_handle; krb5_context context; OM_uint32 ret; krb5_keytype keytype; krb5_keyblock *key; GSSAPI_KRB5_INIT (&context); if (ctx->more_flags & IS_CFX) return _gssapi_wrap_iov_length_cfx(minor_status, ctx, context, conf_req_flag, qop_req, conf_state, iov, iov_count); HEIMDAL_MUTEX_lock(&ctx->ctx_id_mutex); ret = _gsskrb5i_get_token_key(ctx, context, &key); HEIMDAL_MUTEX_unlock(&ctx->ctx_id_mutex); if (ret) { *minor_status = ret; return GSS_S_FAILURE; } krb5_enctype_to_keytype(context, key->keytype, &keytype); switch (keytype) { case KEYTYPE_ARCFOUR: case KEYTYPE_ARCFOUR_56: ret = _gssapi_wrap_iov_length_arcfour(minor_status, ctx, context, conf_req_flag, qop_req, conf_state, iov, iov_count); break; default: ret = GSS_S_FAILURE; break; } krb5_free_keyblock(context, key); return ret; } heimdal-7.5.0/lib/gssapi/krb5/add_cred.c0000644000175000017500000001764213026237312016053 0ustar niknik/* * Copyright (c) 2003 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "gsskrb5_locl.h" OM_uint32 GSSAPI_CALLCONV _gsskrb5_add_cred ( OM_uint32 *minor_status, gss_const_cred_id_t input_cred_handle, gss_const_name_t desired_name, const gss_OID desired_mech, gss_cred_usage_t cred_usage, OM_uint32 initiator_time_req, OM_uint32 acceptor_time_req, gss_cred_id_t *output_cred_handle, gss_OID_set *actual_mechs, OM_uint32 *initiator_time_rec, OM_uint32 *acceptor_time_rec) { krb5_context context; OM_uint32 major, lifetime; gsskrb5_cred cred, handle; krb5_const_principal dname; handle = NULL; cred = (gsskrb5_cred)input_cred_handle; dname = (krb5_const_principal)desired_name; if (cred == NULL && output_cred_handle == NULL) { *minor_status = EINVAL; return GSS_S_CALL_INACCESSIBLE_WRITE; } GSSAPI_KRB5_INIT (&context); if (desired_mech != GSS_C_NO_OID && gss_oid_equal(desired_mech, GSS_KRB5_MECHANISM) == 0) { *minor_status = 0; return GSS_S_BAD_MECH; } if (cred == NULL) { /* * Acquire a credential; output_cred_handle can't be NULL, see above. */ heim_assert(output_cred_handle != NULL, "internal error in _gsskrb5_add_cred()"); major = _gsskrb5_acquire_cred(minor_status, desired_name, min(initiator_time_req, acceptor_time_req), GSS_C_NO_OID_SET, cred_usage, output_cred_handle, actual_mechs, &lifetime); if (major != GSS_S_COMPLETE) goto failure; } else { /* * Check that we're done or copy input to output if * output_cred_handle != NULL. */ HEIMDAL_MUTEX_lock(&cred->cred_id_mutex); /* Check if requested output usage is compatible with output usage */ if (cred->usage != cred_usage && cred->usage != GSS_C_BOTH) { HEIMDAL_MUTEX_unlock(&cred->cred_id_mutex); *minor_status = GSS_KRB5_S_G_BAD_USAGE; return(GSS_S_FAILURE); } /* Check that we have the same name */ if (dname != NULL && krb5_principal_compare(context, dname, cred->principal) != FALSE) { HEIMDAL_MUTEX_unlock(&cred->cred_id_mutex); *minor_status = 0; return GSS_S_BAD_NAME; } if (output_cred_handle == NULL) { /* * This case is basically useless as we implement a single * mechanism here, so we can't add elements to the * input_cred_handle. */ HEIMDAL_MUTEX_unlock(&cred->cred_id_mutex); *minor_status = 0; return GSS_S_COMPLETE; } /* * Copy input to output -- this works as if we were a * GSS_Duplicate_cred() for one mechanism element. */ handle = calloc(1, sizeof(*handle)); if (handle == NULL) { if (cred != NULL) HEIMDAL_MUTEX_unlock(&cred->cred_id_mutex); *minor_status = ENOMEM; return (GSS_S_FAILURE); } handle->usage = cred_usage; handle->endtime = cred->endtime; handle->principal = NULL; handle->keytab = NULL; handle->ccache = NULL; handle->mechanisms = NULL; HEIMDAL_MUTEX_init(&handle->cred_id_mutex); major = GSS_S_FAILURE; *minor_status = krb5_copy_principal(context, cred->principal, &handle->principal); if (*minor_status) { HEIMDAL_MUTEX_unlock(&cred->cred_id_mutex); free(handle); return GSS_S_FAILURE; } if (cred->keytab) { char *name = NULL; *minor_status = krb5_kt_get_full_name(context, cred->keytab, &name); if (*minor_status) goto failure; *minor_status = krb5_kt_resolve(context, name, &handle->keytab); krb5_xfree(name); if (*minor_status) goto failure; } if (cred->ccache) { const char *type, *name; char *type_name = NULL; type = krb5_cc_get_type(context, cred->ccache); if (type == NULL){ *minor_status = ENOMEM; goto failure; } if (strcmp(type, "MEMORY") == 0) { *minor_status = krb5_cc_new_unique(context, type, NULL, &handle->ccache); if (*minor_status) goto failure; *minor_status = krb5_cc_copy_cache(context, cred->ccache, handle->ccache); if (*minor_status) goto failure; } else { name = krb5_cc_get_name(context, cred->ccache); if (name == NULL) { *minor_status = ENOMEM; goto failure; } if (asprintf(&type_name, "%s:%s", type, name) == -1 || type_name == NULL) { *minor_status = ENOMEM; goto failure; } *minor_status = krb5_cc_resolve(context, type_name, &handle->ccache); free(type_name); if (*minor_status) goto failure; } } major = gss_create_empty_oid_set(minor_status, &handle->mechanisms); if (major != GSS_S_COMPLETE) goto failure; major = gss_add_oid_set_member(minor_status, GSS_KRB5_MECHANISM, &handle->mechanisms); if (major != GSS_S_COMPLETE) goto failure; HEIMDAL_MUTEX_unlock(&cred->cred_id_mutex); major = _gsskrb5_inquire_cred(minor_status, (gss_cred_id_t)cred, NULL, &lifetime, NULL, actual_mechs); if (major != GSS_S_COMPLETE) goto failure; *output_cred_handle = (gss_cred_id_t)handle; } if (initiator_time_rec) *initiator_time_rec = lifetime; if (acceptor_time_rec) *acceptor_time_rec = lifetime; *minor_status = 0; return major; failure: if (handle) { if (handle->principal) krb5_free_principal(context, handle->principal); if (handle->keytab) krb5_kt_close(context, handle->keytab); if (handle->ccache) krb5_cc_destroy(context, handle->ccache); if (handle->mechanisms) gss_release_oid_set(NULL, &handle->mechanisms); free(handle); } if (cred && output_cred_handle) HEIMDAL_MUTEX_unlock(&cred->cred_id_mutex); return major; } heimdal-7.5.0/lib/gssapi/krb5/set_cred_option.c0000644000175000017500000001377513026237312017511 0ustar niknik/* * Copyright (c) 2004, PADL Software Pty Ltd. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of PADL Software nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY PADL SOFTWARE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL PADL SOFTWARE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "gsskrb5_locl.h" static OM_uint32 import_cred(OM_uint32 *minor_status, krb5_context context, gss_cred_id_t *cred_handle, const gss_buffer_t value) { OM_uint32 major_stat; krb5_error_code ret; krb5_principal keytab_principal = NULL; krb5_keytab keytab = NULL; krb5_storage *sp = NULL; krb5_ccache id = NULL; char *str; if (cred_handle == NULL || *cred_handle != GSS_C_NO_CREDENTIAL) { *minor_status = 0; return GSS_S_FAILURE; } sp = krb5_storage_from_mem(value->value, value->length); if (sp == NULL) { *minor_status = 0; return GSS_S_FAILURE; } /* credential cache name */ ret = krb5_ret_string(sp, &str); if (ret) { *minor_status = ret; major_stat = GSS_S_FAILURE; goto out; } if (str[0]) { ret = krb5_cc_resolve(context, str, &id); if (ret) { *minor_status = ret; major_stat = GSS_S_FAILURE; goto out; } } free(str); str = NULL; /* keytab principal name */ ret = krb5_ret_string(sp, &str); if (ret == 0 && str[0]) ret = krb5_parse_name(context, str, &keytab_principal); if (ret) { *minor_status = ret; major_stat = GSS_S_FAILURE; goto out; } free(str); str = NULL; /* keytab principal */ ret = krb5_ret_string(sp, &str); if (ret) { *minor_status = ret; major_stat = GSS_S_FAILURE; goto out; } if (str[0]) { ret = krb5_kt_resolve(context, str, &keytab); if (ret) { *minor_status = ret; major_stat = GSS_S_FAILURE; goto out; } } free(str); str = NULL; major_stat = _gsskrb5_krb5_import_cred(minor_status, id, keytab_principal, keytab, cred_handle); out: if (id) krb5_cc_close(context, id); if (keytab_principal) krb5_free_principal(context, keytab_principal); if (keytab) krb5_kt_close(context, keytab); if (str) free(str); if (sp) krb5_storage_free(sp); return major_stat; } static OM_uint32 allowed_enctypes(OM_uint32 *minor_status, krb5_context context, gss_cred_id_t *cred_handle, const gss_buffer_t value) { OM_uint32 major_stat; krb5_error_code ret; size_t len, i; krb5_enctype *enctypes = NULL; krb5_storage *sp = NULL; gsskrb5_cred cred; if (cred_handle == NULL || *cred_handle == GSS_C_NO_CREDENTIAL) { *minor_status = 0; return GSS_S_FAILURE; } cred = (gsskrb5_cred)*cred_handle; if ((value->length % 4) != 0) { *minor_status = 0; major_stat = GSS_S_FAILURE; goto out; } len = value->length / 4; enctypes = malloc((len + 1) * 4); if (enctypes == NULL) { *minor_status = ENOMEM; major_stat = GSS_S_FAILURE; goto out; } sp = krb5_storage_from_mem(value->value, value->length); if (sp == NULL) { *minor_status = ENOMEM; major_stat = GSS_S_FAILURE; goto out; } for (i = 0; i < len; i++) { uint32_t e; ret = krb5_ret_uint32(sp, &e); if (ret) { *minor_status = ret; major_stat = GSS_S_FAILURE; goto out; } enctypes[i] = e; } enctypes[i] = 0; if (cred->enctypes) free(cred->enctypes); cred->enctypes = enctypes; krb5_storage_free(sp); return GSS_S_COMPLETE; out: if (sp) krb5_storage_free(sp); if (enctypes) free(enctypes); return major_stat; } static OM_uint32 no_ci_flags(OM_uint32 *minor_status, krb5_context context, gss_cred_id_t *cred_handle, const gss_buffer_t value) { gsskrb5_cred cred; if (cred_handle == NULL || *cred_handle == GSS_C_NO_CREDENTIAL) { *minor_status = 0; return GSS_S_FAILURE; } cred = (gsskrb5_cred)*cred_handle; cred->cred_flags |= GSS_CF_NO_CI_FLAGS; *minor_status = 0; return GSS_S_COMPLETE; } OM_uint32 GSSAPI_CALLCONV _gsskrb5_set_cred_option (OM_uint32 *minor_status, gss_cred_id_t *cred_handle, const gss_OID desired_object, const gss_buffer_t value) { krb5_context context; GSSAPI_KRB5_INIT (&context); if (value == GSS_C_NO_BUFFER) { *minor_status = EINVAL; return GSS_S_FAILURE; } if (gss_oid_equal(desired_object, GSS_KRB5_IMPORT_CRED_X)) return import_cred(minor_status, context, cred_handle, value); if (gss_oid_equal(desired_object, GSS_KRB5_SET_ALLOWABLE_ENCTYPES_X)) return allowed_enctypes(minor_status, context, cred_handle, value); if (gss_oid_equal(desired_object, GSS_KRB5_CRED_NO_CI_FLAGS_X)) { return no_ci_flags(minor_status, context, cred_handle, value); } *minor_status = EINVAL; return GSS_S_FAILURE; } heimdal-7.5.0/lib/gssapi/krb5/process_context_token.c0000644000175000017500000000461713026237312020746 0ustar niknik/* * Copyright (c) 2003 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "gsskrb5_locl.h" OM_uint32 GSSAPI_CALLCONV _gsskrb5_process_context_token ( OM_uint32 *minor_status, gss_const_ctx_id_t context_handle, const gss_buffer_t token_buffer ) { krb5_context context; OM_uint32 ret = GSS_S_FAILURE; gss_buffer_desc empty_buffer; empty_buffer.length = 0; empty_buffer.value = NULL; GSSAPI_KRB5_INIT (&context); ret = _gsskrb5_verify_mic_internal(minor_status, (gsskrb5_ctx)context_handle, context, token_buffer, &empty_buffer, GSS_C_QOP_DEFAULT, "\x01\x02"); if (ret == GSS_S_COMPLETE) ret = _gsskrb5_delete_sec_context(minor_status, rk_UNCONST(&context_handle), GSS_C_NO_BUFFER); if (ret == GSS_S_COMPLETE) *minor_status = 0; return ret; } heimdal-7.5.0/lib/gssapi/krb5/duplicate_name.c0000644000175000017500000000430013026237312017263 0ustar niknik/* * Copyright (c) 1997 - 2003 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "gsskrb5_locl.h" OM_uint32 GSSAPI_CALLCONV _gsskrb5_duplicate_name ( OM_uint32 * minor_status, gss_const_name_t src_name, gss_name_t * dest_name ) { krb5_const_principal src = (krb5_const_principal)src_name; krb5_context context; krb5_principal dest; krb5_error_code kret; GSSAPI_KRB5_INIT (&context); kret = krb5_copy_principal (context, src, &dest); if (kret) { *minor_status = kret; return GSS_S_FAILURE; } else { *dest_name = (gss_name_t)dest; *minor_status = 0; return GSS_S_COMPLETE; } } heimdal-7.5.0/lib/gssapi/krb5/decapsulate.c0000644000175000017500000001206413026237312016611 0ustar niknik/* * Copyright (c) 1997 - 2001 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "gsskrb5_locl.h" /* * return the length of the mechanism in token or -1 * (which implies that the token was bad - GSS_S_DEFECTIVE_TOKEN */ ssize_t _gsskrb5_get_mech (const u_char *ptr, size_t total_len, const u_char **mech_ret) { size_t len, len_len, mech_len, foo; const u_char *p = ptr; int e; if (total_len < 1) return -1; if (*p++ != 0x60) return -1; e = der_get_length (p, total_len - 1, &len, &len_len); if (e || 1 + len_len + len != total_len) return -1; p += len_len; if (*p++ != 0x06) return -1; e = der_get_length (p, total_len - 1 - len_len - 1, &mech_len, &foo); if (e) return -1; p += foo; *mech_ret = p; return mech_len; } OM_uint32 _gssapi_verify_mech_header(u_char **str, size_t total_len, gss_OID mech) { const u_char *p; ssize_t mech_len; mech_len = _gsskrb5_get_mech (*str, total_len, &p); if (mech_len < 0) return GSS_S_DEFECTIVE_TOKEN; if (mech_len != mech->length) return GSS_S_BAD_MECH; if (ct_memcmp(p, mech->elements, mech->length) != 0) return GSS_S_BAD_MECH; p += mech_len; *str = rk_UNCONST(p); return GSS_S_COMPLETE; } OM_uint32 _gsskrb5_verify_header(u_char **str, size_t total_len, const void *type, gss_OID oid) { OM_uint32 ret; size_t len; u_char *p = *str; ret = _gssapi_verify_mech_header(str, total_len, oid); if (ret) return ret; len = total_len - (*str - p); if (len < 2) return GSS_S_DEFECTIVE_TOKEN; if (ct_memcmp (*str, type, 2) != 0) return GSS_S_DEFECTIVE_TOKEN; *str += 2; return 0; } /* * Remove the GSS-API wrapping from `in_token' giving `out_data. * Does not copy data, so just free `in_token'. */ OM_uint32 _gssapi_decapsulate( OM_uint32 *minor_status, gss_buffer_t input_token_buffer, krb5_data *out_data, const gss_OID mech ) { u_char *p; OM_uint32 ret; p = input_token_buffer->value; ret = _gssapi_verify_mech_header(&p, input_token_buffer->length, mech); if (ret) { *minor_status = 0; return ret; } out_data->length = input_token_buffer->length - (p - (u_char *)input_token_buffer->value); out_data->data = p; return GSS_S_COMPLETE; } /* * Remove the GSS-API wrapping from `in_token' giving `out_data. * Does not copy data, so just free `in_token'. */ OM_uint32 _gsskrb5_decapsulate(OM_uint32 *minor_status, gss_buffer_t input_token_buffer, krb5_data *out_data, const void *type, gss_OID oid) { u_char *p; OM_uint32 ret; p = input_token_buffer->value; ret = _gsskrb5_verify_header(&p, input_token_buffer->length, type, oid); if (ret) { *minor_status = 0; return ret; } out_data->length = input_token_buffer->length - (p - (u_char *)input_token_buffer->value); out_data->data = p; return GSS_S_COMPLETE; } /* * Verify padding of a gss wrapped message and return its length. */ OM_uint32 _gssapi_verify_pad(gss_buffer_t wrapped_token, size_t datalen, size_t *padlen) { u_char *pad; size_t padlength; int i; if (wrapped_token->length < 1) return GSS_S_BAD_MECH; pad = (u_char *)wrapped_token->value + wrapped_token->length - 1; padlength = *pad; if (padlength > datalen) return GSS_S_BAD_MECH; for (i = padlength; i > 0 && *pad == padlength; i--, pad--) ; if (i != 0) return GSS_S_BAD_MIC; *padlen = padlength; return 0; } heimdal-7.5.0/lib/gssapi/krb5/inquire_context.c0000644000175000017500000000627313026237312017544 0ustar niknik/* * Copyright (c) 1997, 2003 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "gsskrb5_locl.h" OM_uint32 GSSAPI_CALLCONV _gsskrb5_inquire_context ( OM_uint32 * minor_status, gss_const_ctx_id_t context_handle, gss_name_t * src_name, gss_name_t * targ_name, OM_uint32 * lifetime_rec, gss_OID * mech_type, OM_uint32 * ctx_flags, int * locally_initiated, int * open_context ) { krb5_context context; OM_uint32 ret; gsskrb5_ctx ctx = (gsskrb5_ctx)context_handle; gss_name_t name; if (src_name) *src_name = GSS_C_NO_NAME; if (targ_name) *targ_name = GSS_C_NO_NAME; GSSAPI_KRB5_INIT (&context); HEIMDAL_MUTEX_lock(&ctx->ctx_id_mutex); if (src_name) { name = (gss_name_t)ctx->source; ret = _gsskrb5_duplicate_name (minor_status, name, src_name); if (ret) goto failed; } if (targ_name) { name = (gss_name_t)ctx->target; ret = _gsskrb5_duplicate_name (minor_status, name, targ_name); if (ret) goto failed; } if (lifetime_rec) { ret = _gsskrb5_lifetime_left(minor_status, context, ctx->endtime, lifetime_rec); if (ret) goto failed; } if (mech_type) *mech_type = GSS_KRB5_MECHANISM; if (ctx_flags) *ctx_flags = ctx->flags; if (locally_initiated) *locally_initiated = ctx->more_flags & LOCAL; if (open_context) *open_context = ctx->more_flags & OPEN; *minor_status = 0; HEIMDAL_MUTEX_unlock(&ctx->ctx_id_mutex); return GSS_S_COMPLETE; failed: if (src_name) _gsskrb5_release_name(NULL, src_name); if (targ_name) _gsskrb5_release_name(NULL, targ_name); HEIMDAL_MUTEX_unlock(&ctx->ctx_id_mutex); return ret; } heimdal-7.5.0/lib/gssapi/krb5/import_sec_context.c0000644000175000017500000001462713026237312020236 0ustar niknik/* * Copyright (c) 1999 - 2003 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "gsskrb5_locl.h" OM_uint32 GSSAPI_CALLCONV _gsskrb5_import_sec_context ( OM_uint32 * minor_status, const gss_buffer_t interprocess_token, gss_ctx_id_t * context_handle ) { OM_uint32 ret = GSS_S_FAILURE; krb5_context context; krb5_error_code kret; krb5_storage *sp; krb5_auth_context ac; krb5_address local, remote; krb5_address *localp, *remotep; krb5_data data; gss_buffer_desc buffer; krb5_keyblock keyblock; int32_t flags, tmp; gsskrb5_ctx ctx; gss_name_t name; GSSAPI_KRB5_INIT (&context); *context_handle = GSS_C_NO_CONTEXT; localp = remotep = NULL; sp = krb5_storage_from_mem (interprocess_token->value, interprocess_token->length); if (sp == NULL) { *minor_status = ENOMEM; return GSS_S_FAILURE; } ctx = calloc(1, sizeof(*ctx)); if (ctx == NULL) { *minor_status = ENOMEM; krb5_storage_free (sp); return GSS_S_FAILURE; } HEIMDAL_MUTEX_init(&ctx->ctx_id_mutex); kret = krb5_auth_con_init (context, &ctx->auth_context); if (kret) { *minor_status = kret; ret = GSS_S_FAILURE; goto failure; } /* flags */ *minor_status = 0; if (krb5_ret_int32 (sp, &flags) != 0) goto failure; /* retrieve the auth context */ ac = ctx->auth_context; if (krb5_ret_int32 (sp, &tmp) != 0) goto failure; ac->flags = tmp; if (flags & SC_LOCAL_ADDRESS) { if (krb5_ret_address (sp, localp = &local) != 0) goto failure; } if (flags & SC_REMOTE_ADDRESS) { if (krb5_ret_address (sp, remotep = &remote) != 0) goto failure; } krb5_auth_con_setaddrs (context, ac, localp, remotep); if (localp) krb5_free_address (context, localp); if (remotep) krb5_free_address (context, remotep); localp = remotep = NULL; if (krb5_ret_int16 (sp, &ac->local_port) != 0) goto failure; if (krb5_ret_int16 (sp, &ac->remote_port) != 0) goto failure; if (flags & SC_KEYBLOCK) { if (krb5_ret_keyblock (sp, &keyblock) != 0) goto failure; krb5_auth_con_setkey (context, ac, &keyblock); krb5_free_keyblock_contents (context, &keyblock); } if (flags & SC_LOCAL_SUBKEY) { if (krb5_ret_keyblock (sp, &keyblock) != 0) goto failure; krb5_auth_con_setlocalsubkey (context, ac, &keyblock); krb5_free_keyblock_contents (context, &keyblock); } if (flags & SC_REMOTE_SUBKEY) { if (krb5_ret_keyblock (sp, &keyblock) != 0) goto failure; krb5_auth_con_setremotesubkey (context, ac, &keyblock); krb5_free_keyblock_contents (context, &keyblock); } if (krb5_ret_uint32 (sp, &ac->local_seqnumber)) goto failure; if (krb5_ret_uint32 (sp, &ac->remote_seqnumber)) goto failure; if (krb5_ret_int32 (sp, &tmp) != 0) goto failure; ac->keytype = tmp; if (krb5_ret_int32 (sp, &tmp) != 0) goto failure; ac->cksumtype = tmp; /* names */ if (krb5_ret_data (sp, &data)) goto failure; buffer.value = data.data; buffer.length = data.length; ret = _gsskrb5_import_name (minor_status, &buffer, GSS_C_NT_EXPORT_NAME, &name); if (ret) { ret = _gsskrb5_import_name (minor_status, &buffer, GSS_C_NO_OID, &name); if (ret) { krb5_data_free (&data); goto failure; } } ctx->source = (krb5_principal)name; krb5_data_free (&data); if (krb5_ret_data (sp, &data) != 0) goto failure; buffer.value = data.data; buffer.length = data.length; ret = _gsskrb5_import_name (minor_status, &buffer, GSS_C_NT_EXPORT_NAME, &name); if (ret) { ret = _gsskrb5_import_name (minor_status, &buffer, GSS_C_NO_OID, &name); if (ret) { krb5_data_free (&data); goto failure; } } ctx->target = (krb5_principal)name; krb5_data_free (&data); if (krb5_ret_int32 (sp, &tmp)) goto failure; ctx->flags = tmp; if (krb5_ret_int32 (sp, &tmp)) goto failure; ctx->more_flags = tmp; /* * XXX endtime should be a 64-bit int, but we don't have * krb5_ret_int64() yet. */ if (krb5_ret_int32 (sp, &tmp)) goto failure; ctx->endtime = tmp; ret = _gssapi_msg_order_import(minor_status, sp, &ctx->order); if (ret) goto failure; krb5_storage_free (sp); _gsskrb5i_is_cfx(context, ctx, (ctx->more_flags & LOCAL) == 0); *context_handle = (gss_ctx_id_t)ctx; return GSS_S_COMPLETE; failure: krb5_auth_con_free (context, ctx->auth_context); if (ctx->source != NULL) krb5_free_principal(context, ctx->source); if (ctx->target != NULL) krb5_free_principal(context, ctx->target); if (localp) krb5_free_address (context, localp); if (remotep) krb5_free_address (context, remotep); if(ctx->order) _gssapi_msg_order_destroy(&ctx->order); HEIMDAL_MUTEX_destroy(&ctx->ctx_id_mutex); krb5_storage_free (sp); free (ctx); *context_handle = GSS_C_NO_CONTEXT; return ret; } heimdal-7.5.0/lib/gssapi/krb5/gsskrb5-private.h0000644000175000017500000004636613212445601017367 0ustar niknik/* This is a generated file */ #ifndef __gsskrb5_private_h__ #define __gsskrb5_private_h__ #include gssapi_mech_interface __gss_krb5_initialize (void); OM_uint32 __gsskrb5_ccache_lifetime ( OM_uint32 */*minor_status*/, krb5_context /*context*/, krb5_ccache /*id*/, krb5_principal /*principal*/, OM_uint32 */*lifetime*/); OM_uint32 _gk_allocate_buffer ( OM_uint32 */*minor_status*/, gss_iov_buffer_desc */*buffer*/, size_t /*size*/); gss_iov_buffer_desc * _gk_find_buffer ( gss_iov_buffer_desc */*iov*/, int /*iov_count*/, OM_uint32 /*type*/); OM_uint32 GSSAPI_CALLCONV _gk_unwrap_iov ( OM_uint32 */*minor_status*/, gss_ctx_id_t /*context_handle*/, int */*conf_state*/, gss_qop_t */*qop_state*/, gss_iov_buffer_desc */*iov*/, int /*iov_count*/); OM_uint32 _gk_verify_buffers ( OM_uint32 */*minor_status*/, const gsskrb5_ctx /*ctx*/, const gss_iov_buffer_desc */*header*/, const gss_iov_buffer_desc */*padding*/, const gss_iov_buffer_desc */*trailer*/); OM_uint32 GSSAPI_CALLCONV _gk_wrap_iov ( OM_uint32 * /*minor_status*/, gss_ctx_id_t /*context_handle*/, int /*conf_req_flag*/, gss_qop_t /*qop_req*/, int * /*conf_state*/, gss_iov_buffer_desc */*iov*/, int /*iov_count*/); OM_uint32 GSSAPI_CALLCONV _gk_wrap_iov_length ( OM_uint32 * /*minor_status*/, gss_ctx_id_t /*context_handle*/, int /*conf_req_flag*/, gss_qop_t /*qop_req*/, int */*conf_state*/, gss_iov_buffer_desc */*iov*/, int /*iov_count*/); OM_uint32 _gss_DES3_get_mic_compat ( OM_uint32 */*minor_status*/, gsskrb5_ctx /*ctx*/, krb5_context /*context*/); OM_uint32 _gssapi_decapsulate ( OM_uint32 */*minor_status*/, gss_buffer_t /*input_token_buffer*/, krb5_data */*out_data*/, const gss_OID mech ); void _gssapi_encap_length ( size_t /*data_len*/, size_t */*len*/, size_t */*total_len*/, const gss_OID /*mech*/); OM_uint32 _gssapi_encapsulate ( OM_uint32 */*minor_status*/, const krb5_data */*in_data*/, gss_buffer_t /*output_token*/, const gss_OID mech ); OM_uint32 _gssapi_get_mic_arcfour ( OM_uint32 * /*minor_status*/, const gsskrb5_ctx /*context_handle*/, krb5_context /*context*/, gss_qop_t /*qop_req*/, const gss_buffer_t /*message_buffer*/, gss_buffer_t /*message_token*/, krb5_keyblock */*key*/); void * _gssapi_make_mech_header ( void */*ptr*/, size_t /*len*/, const gss_OID /*mech*/); OM_uint32 _gssapi_mic_cfx ( OM_uint32 */*minor_status*/, const gsskrb5_ctx /*ctx*/, krb5_context /*context*/, gss_qop_t /*qop_req*/, const gss_buffer_t /*message_buffer*/, gss_buffer_t /*message_token*/); OM_uint32 _gssapi_msg_order_check ( struct gss_msg_order */*o*/, OM_uint32 /*seq_num*/); OM_uint32 _gssapi_msg_order_create ( OM_uint32 */*minor_status*/, struct gss_msg_order **/*o*/, OM_uint32 /*flags*/, OM_uint32 /*seq_num*/, OM_uint32 /*jitter_window*/, int /*use_64*/); OM_uint32 _gssapi_msg_order_destroy (struct gss_msg_order **/*m*/); krb5_error_code _gssapi_msg_order_export ( krb5_storage */*sp*/, struct gss_msg_order */*o*/); OM_uint32 _gssapi_msg_order_f (OM_uint32 /*flags*/); OM_uint32 _gssapi_msg_order_import ( OM_uint32 */*minor_status*/, krb5_storage */*sp*/, struct gss_msg_order **/*o*/); OM_uint32 _gssapi_unwrap_arcfour ( OM_uint32 */*minor_status*/, const gsskrb5_ctx /*context_handle*/, krb5_context /*context*/, const gss_buffer_t /*input_message_buffer*/, gss_buffer_t /*output_message_buffer*/, int */*conf_state*/, gss_qop_t */*qop_state*/, krb5_keyblock */*key*/); OM_uint32 _gssapi_unwrap_cfx ( OM_uint32 */*minor_status*/, const gsskrb5_ctx /*ctx*/, krb5_context /*context*/, const gss_buffer_t /*input_message_buffer*/, gss_buffer_t /*output_message_buffer*/, int */*conf_state*/, gss_qop_t */*qop_state*/); OM_uint32 _gssapi_unwrap_cfx_iov ( OM_uint32 */*minor_status*/, gsskrb5_ctx /*ctx*/, krb5_context /*context*/, int */*conf_state*/, gss_qop_t */*qop_state*/, gss_iov_buffer_desc */*iov*/, int /*iov_count*/); OM_uint32 _gssapi_unwrap_iov_arcfour ( OM_uint32 */*minor_status*/, gsskrb5_ctx /*ctx*/, krb5_context /*context*/, int */*pconf_state*/, gss_qop_t */*pqop_state*/, gss_iov_buffer_desc */*iov*/, int /*iov_count*/, krb5_keyblock */*key*/); OM_uint32 _gssapi_verify_mech_header ( u_char **/*str*/, size_t /*total_len*/, gss_OID /*mech*/); OM_uint32 _gssapi_verify_mic_arcfour ( OM_uint32 * /*minor_status*/, const gsskrb5_ctx /*context_handle*/, krb5_context /*context*/, const gss_buffer_t /*message_buffer*/, const gss_buffer_t /*token_buffer*/, gss_qop_t * /*qop_state*/, krb5_keyblock */*key*/, const char */*type*/); OM_uint32 _gssapi_verify_mic_cfx ( OM_uint32 */*minor_status*/, const gsskrb5_ctx /*ctx*/, krb5_context /*context*/, const gss_buffer_t /*message_buffer*/, const gss_buffer_t /*token_buffer*/, gss_qop_t */*qop_state*/); OM_uint32 _gssapi_verify_pad ( gss_buffer_t /*wrapped_token*/, size_t /*datalen*/, size_t */*padlen*/); OM_uint32 _gssapi_wrap_arcfour ( OM_uint32 * /*minor_status*/, const gsskrb5_ctx /*context_handle*/, krb5_context /*context*/, int /*conf_req_flag*/, gss_qop_t /*qop_req*/, const gss_buffer_t /*input_message_buffer*/, int * /*conf_state*/, gss_buffer_t /*output_message_buffer*/, krb5_keyblock */*key*/); OM_uint32 _gssapi_wrap_cfx ( OM_uint32 */*minor_status*/, const gsskrb5_ctx /*ctx*/, krb5_context /*context*/, int /*conf_req_flag*/, const gss_buffer_t /*input_message_buffer*/, int */*conf_state*/, gss_buffer_t /*output_message_buffer*/); OM_uint32 _gssapi_wrap_cfx_iov ( OM_uint32 */*minor_status*/, gsskrb5_ctx /*ctx*/, krb5_context /*context*/, int /*conf_req_flag*/, int */*conf_state*/, gss_iov_buffer_desc */*iov*/, int /*iov_count*/); OM_uint32 _gssapi_wrap_iov_arcfour ( OM_uint32 */*minor_status*/, gsskrb5_ctx /*ctx*/, krb5_context /*context*/, int /*conf_req_flag*/, int */*conf_state*/, gss_iov_buffer_desc */*iov*/, int /*iov_count*/, krb5_keyblock */*key*/); OM_uint32 _gssapi_wrap_iov_length_arcfour ( OM_uint32 */*minor_status*/, gsskrb5_ctx /*ctx*/, krb5_context /*context*/, int /*conf_req_flag*/, gss_qop_t /*qop_req*/, int */*conf_state*/, gss_iov_buffer_desc */*iov*/, int /*iov_count*/); OM_uint32 _gssapi_wrap_iov_length_cfx ( OM_uint32 */*minor_status*/, gsskrb5_ctx /*ctx*/, krb5_context /*context*/, int /*conf_req_flag*/, gss_qop_t /*qop_req*/, int */*conf_state*/, gss_iov_buffer_desc */*iov*/, int /*iov_count*/); OM_uint32 _gssapi_wrap_size_arcfour ( OM_uint32 */*minor_status*/, const gsskrb5_ctx /*ctx*/, krb5_context /*context*/, int /*conf_req_flag*/, gss_qop_t /*qop_req*/, OM_uint32 /*req_output_size*/, OM_uint32 */*max_input_size*/, krb5_keyblock */*key*/); OM_uint32 _gssapi_wrap_size_cfx ( OM_uint32 */*minor_status*/, const gsskrb5_ctx /*ctx*/, krb5_context /*context*/, int /*conf_req_flag*/, gss_qop_t /*qop_req*/, OM_uint32 /*req_output_size*/, OM_uint32 */*max_input_size*/); OM_uint32 GSSAPI_CALLCONV _gsskrb5_accept_sec_context ( OM_uint32 * /*minor_status*/, gss_ctx_id_t * /*context_handle*/, gss_const_cred_id_t /*acceptor_cred_handle*/, const gss_buffer_t /*input_token_buffer*/, const gss_channel_bindings_t /*input_chan_bindings*/, gss_name_t * /*src_name*/, gss_OID * /*mech_type*/, gss_buffer_t /*output_token*/, OM_uint32 * /*ret_flags*/, OM_uint32 * /*time_rec*/, gss_cred_id_t * /*delegated_cred_handle*/); OM_uint32 GSSAPI_CALLCONV _gsskrb5_acquire_cred ( OM_uint32 * /*minor_status*/, gss_const_name_t /*desired_name*/, OM_uint32 /*time_req*/, const gss_OID_set /*desired_mechs*/, gss_cred_usage_t /*cred_usage*/, gss_cred_id_t * /*output_cred_handle*/, gss_OID_set * /*actual_mechs*/, OM_uint32 * time_rec ); OM_uint32 GSSAPI_CALLCONV _gsskrb5_acquire_cred_ext ( OM_uint32 * /*minor_status*/, gss_const_name_t /*desired_name*/, gss_const_OID /*credential_type*/, const void */*credential_data*/, OM_uint32 /*time_req*/, gss_const_OID /*desired_mech*/, gss_cred_usage_t /*cred_usage*/, gss_cred_id_t * output_cred_handle ); OM_uint32 GSSAPI_CALLCONV _gsskrb5_add_cred ( OM_uint32 */*minor_status*/, gss_const_cred_id_t /*input_cred_handle*/, gss_const_name_t /*desired_name*/, const gss_OID /*desired_mech*/, gss_cred_usage_t /*cred_usage*/, OM_uint32 /*initiator_time_req*/, OM_uint32 /*acceptor_time_req*/, gss_cred_id_t */*output_cred_handle*/, gss_OID_set */*actual_mechs*/, OM_uint32 */*initiator_time_rec*/, OM_uint32 */*acceptor_time_rec*/); OM_uint32 GSSAPI_CALLCONV _gsskrb5_authorize_localname ( OM_uint32 */*minor_status*/, gss_const_name_t /*input_name*/, gss_const_buffer_t /*user_name*/, gss_const_OID /*user_name_type*/); OM_uint32 _gsskrb5_canon_name ( OM_uint32 */*minor_status*/, krb5_context /*context*/, gss_const_name_t /*targetname*/, krb5_principal */*out*/); OM_uint32 GSSAPI_CALLCONV _gsskrb5_canonicalize_name ( OM_uint32 * /*minor_status*/, gss_const_name_t /*input_name*/, const gss_OID /*mech_type*/, gss_name_t * output_name ); void _gsskrb5_clear_status (void); OM_uint32 GSSAPI_CALLCONV _gsskrb5_compare_name ( OM_uint32 * /*minor_status*/, gss_const_name_t /*name1*/, gss_const_name_t /*name2*/, int * name_equal ); OM_uint32 GSSAPI_CALLCONV _gsskrb5_context_time ( OM_uint32 * /*minor_status*/, gss_const_ctx_id_t /*context_handle*/, OM_uint32 * time_rec ); OM_uint32 _gsskrb5_create_8003_checksum ( OM_uint32 */*minor_status*/, const gss_channel_bindings_t /*input_chan_bindings*/, OM_uint32 /*flags*/, const krb5_data */*fwd_data*/, Checksum */*result*/); OM_uint32 _gsskrb5_create_ctx ( OM_uint32 * /*minor_status*/, gss_ctx_id_t * /*context_handle*/, krb5_context /*context*/, const gss_channel_bindings_t /*input_chan_bindings*/, enum gss_ctx_id_t_state /*state*/); OM_uint32 _gsskrb5_decapsulate ( OM_uint32 */*minor_status*/, gss_buffer_t /*input_token_buffer*/, krb5_data */*out_data*/, const void */*type*/, gss_OID /*oid*/); krb5_error_code _gsskrb5_decode_be_om_uint32 ( const void */*ptr*/, OM_uint32 */*n*/); krb5_error_code _gsskrb5_decode_om_uint32 ( const void */*ptr*/, OM_uint32 */*n*/); OM_uint32 GSSAPI_CALLCONV _gsskrb5_delete_sec_context ( OM_uint32 * /*minor_status*/, gss_ctx_id_t * /*context_handle*/, gss_buffer_t /*output_token*/); OM_uint32 GSSAPI_CALLCONV _gsskrb5_display_name ( OM_uint32 * /*minor_status*/, gss_const_name_t /*input_name*/, gss_buffer_t /*output_name_buffer*/, gss_OID * output_name_type ); OM_uint32 GSSAPI_CALLCONV _gsskrb5_display_status ( OM_uint32 */*minor_status*/, OM_uint32 /*status_value*/, int /*status_type*/, const gss_OID /*mech_type*/, OM_uint32 */*message_context*/, gss_buffer_t /*status_string*/); OM_uint32 GSSAPI_CALLCONV _gsskrb5_duplicate_name ( OM_uint32 * /*minor_status*/, gss_const_name_t /*src_name*/, gss_name_t * dest_name ); void _gsskrb5_encap_length ( size_t /*data_len*/, size_t */*len*/, size_t */*total_len*/, const gss_OID /*mech*/); OM_uint32 _gsskrb5_encapsulate ( OM_uint32 */*minor_status*/, const krb5_data */*in_data*/, gss_buffer_t /*output_token*/, const void */*type*/, const gss_OID mech ); krb5_error_code _gsskrb5_encode_be_om_uint32 ( OM_uint32 /*n*/, u_char */*p*/); krb5_error_code _gsskrb5_encode_om_uint32 ( OM_uint32 /*n*/, u_char */*p*/); OM_uint32 GSSAPI_CALLCONV _gsskrb5_export_cred ( OM_uint32 */*minor_status*/, gss_cred_id_t /*cred_handle*/, gss_buffer_t /*cred_token*/); OM_uint32 GSSAPI_CALLCONV _gsskrb5_export_name ( OM_uint32 * /*minor_status*/, gss_const_name_t /*input_name*/, gss_buffer_t exported_name ); OM_uint32 GSSAPI_CALLCONV _gsskrb5_export_sec_context ( OM_uint32 */*minor_status*/, gss_ctx_id_t */*context_handle*/, gss_buffer_t interprocess_token ); ssize_t _gsskrb5_get_mech ( const u_char */*ptr*/, size_t /*total_len*/, const u_char **/*mech_ret*/); OM_uint32 GSSAPI_CALLCONV _gsskrb5_get_mic ( OM_uint32 * /*minor_status*/, gss_const_ctx_id_t /*context_handle*/, gss_qop_t /*qop_req*/, const gss_buffer_t /*message_buffer*/, gss_buffer_t message_token ); OM_uint32 _gsskrb5_get_tkt_flags ( OM_uint32 */*minor_status*/, gsskrb5_ctx /*ctx*/, OM_uint32 */*tkt_flags*/); OM_uint32 GSSAPI_CALLCONV _gsskrb5_import_cred ( OM_uint32 * /*minor_status*/, gss_buffer_t /*cred_token*/, gss_cred_id_t * /*cred_handle*/); OM_uint32 GSSAPI_CALLCONV _gsskrb5_import_name ( OM_uint32 * /*minor_status*/, const gss_buffer_t /*input_name_buffer*/, const gss_OID /*input_name_type*/, gss_name_t * output_name ); OM_uint32 GSSAPI_CALLCONV _gsskrb5_import_sec_context ( OM_uint32 * /*minor_status*/, const gss_buffer_t /*interprocess_token*/, gss_ctx_id_t * context_handle ); OM_uint32 GSSAPI_CALLCONV _gsskrb5_indicate_mechs ( OM_uint32 * /*minor_status*/, gss_OID_set * mech_set ); krb5_error_code _gsskrb5_init (krb5_context */*context*/); OM_uint32 GSSAPI_CALLCONV _gsskrb5_init_sec_context ( OM_uint32 * /*minor_status*/, gss_const_cred_id_t /*cred_handle*/, gss_ctx_id_t * /*context_handle*/, gss_const_name_t /*target_name*/, const gss_OID /*mech_type*/, OM_uint32 /*req_flags*/, OM_uint32 /*time_req*/, const gss_channel_bindings_t /*input_chan_bindings*/, const gss_buffer_t /*input_token*/, gss_OID * /*actual_mech_type*/, gss_buffer_t /*output_token*/, OM_uint32 * /*ret_flags*/, OM_uint32 * time_rec ); OM_uint32 GSSAPI_CALLCONV _gsskrb5_inquire_context ( OM_uint32 * /*minor_status*/, gss_const_ctx_id_t /*context_handle*/, gss_name_t * /*src_name*/, gss_name_t * /*targ_name*/, OM_uint32 * /*lifetime_rec*/, gss_OID * /*mech_type*/, OM_uint32 * /*ctx_flags*/, int * /*locally_initiated*/, int * open_context ); OM_uint32 GSSAPI_CALLCONV _gsskrb5_inquire_cred ( OM_uint32 * /*minor_status*/, gss_const_cred_id_t /*cred_handle*/, gss_name_t * /*output_name*/, OM_uint32 * /*lifetime*/, gss_cred_usage_t * /*cred_usage*/, gss_OID_set * mechanisms ); OM_uint32 GSSAPI_CALLCONV _gsskrb5_inquire_cred_by_mech ( OM_uint32 * /*minor_status*/, gss_const_cred_id_t /*cred_handle*/, const gss_OID /*mech_type*/, gss_name_t * /*name*/, OM_uint32 * /*initiator_lifetime*/, OM_uint32 * /*acceptor_lifetime*/, gss_cred_usage_t * cred_usage ); OM_uint32 GSSAPI_CALLCONV _gsskrb5_inquire_cred_by_oid ( OM_uint32 * /*minor_status*/, gss_const_cred_id_t /*cred_handle*/, const gss_OID /*desired_object*/, gss_buffer_set_t */*data_set*/); OM_uint32 GSSAPI_CALLCONV _gsskrb5_inquire_mechs_for_name ( OM_uint32 * /*minor_status*/, gss_const_name_t /*input_name*/, gss_OID_set * mech_types ); OM_uint32 GSSAPI_CALLCONV _gsskrb5_inquire_names_for_mech ( OM_uint32 * /*minor_status*/, const gss_OID /*mechanism*/, gss_OID_set * name_types ); OM_uint32 GSSAPI_CALLCONV _gsskrb5_inquire_sec_context_by_oid ( OM_uint32 */*minor_status*/, gss_const_ctx_id_t /*context_handle*/, const gss_OID /*desired_object*/, gss_buffer_set_t */*data_set*/); OM_uint32 _gsskrb5_krb5_ccache_name ( OM_uint32 */*minor_status*/, const char */*name*/, const char **/*out_name*/); OM_uint32 _gsskrb5_krb5_import_cred ( OM_uint32 */*minor_status*/, krb5_ccache /*id*/, krb5_principal /*keytab_principal*/, krb5_keytab /*keytab*/, gss_cred_id_t */*cred*/); OM_uint32 _gsskrb5_lifetime_left ( OM_uint32 */*minor_status*/, krb5_context /*context*/, OM_uint32 /*endtime*/, OM_uint32 */*lifetime_rec*/); OM_uint32 GSSAPI_CALLCONV _gsskrb5_localname ( OM_uint32 */*minor_status*/, gss_const_name_t /*pname*/, const gss_OID /*mech_type*/, gss_buffer_t /*localname*/); void * _gsskrb5_make_header ( void */*ptr*/, size_t /*len*/, const void */*type*/, const gss_OID /*mech*/); OM_uint32 GSSAPI_CALLCONV _gsskrb5_process_context_token ( OM_uint32 */*minor_status*/, gss_const_ctx_id_t /*context_handle*/, const gss_buffer_t token_buffer ); OM_uint32 GSSAPI_CALLCONV _gsskrb5_pseudo_random ( OM_uint32 */*minor_status*/, gss_ctx_id_t /*context_handle*/, int /*prf_key*/, const gss_buffer_t /*prf_in*/, ssize_t /*desired_output_len*/, gss_buffer_t /*prf_out*/); OM_uint32 _gsskrb5_register_acceptor_identity ( OM_uint32 */*min_stat*/, const char */*identity*/); OM_uint32 _gsskrb5_release_buffer ( OM_uint32 * /*minor_status*/, gss_buffer_t buffer ); OM_uint32 GSSAPI_CALLCONV _gsskrb5_release_cred ( OM_uint32 * /*minor_status*/, gss_cred_id_t * cred_handle ); OM_uint32 GSSAPI_CALLCONV _gsskrb5_release_name ( OM_uint32 * /*minor_status*/, gss_name_t * input_name ); OM_uint32 GSSAPI_CALLCONV _gsskrb5_set_cred_option ( OM_uint32 */*minor_status*/, gss_cred_id_t */*cred_handle*/, const gss_OID /*desired_object*/, const gss_buffer_t /*value*/); OM_uint32 GSSAPI_CALLCONV _gsskrb5_set_sec_context_option ( OM_uint32 */*minor_status*/, gss_ctx_id_t */*context_handle*/, const gss_OID /*desired_object*/, const gss_buffer_t /*value*/); void _gsskrb5_set_status ( int /*ret*/, const char */*fmt*/, ...); OM_uint32 GSSAPI_CALLCONV _gsskrb5_store_cred ( OM_uint32 */*minor_status*/, gss_cred_id_t /*input_cred_handle*/, gss_cred_usage_t /*cred_usage*/, const gss_OID /*desired_mech*/, OM_uint32 /*overwrite_cred*/, OM_uint32 /*default_cred*/, gss_OID_set */*elements_stored*/, gss_cred_usage_t */*cred_usage_stored*/); OM_uint32 GSSAPI_CALLCONV _gsskrb5_unwrap ( OM_uint32 * /*minor_status*/, gss_const_ctx_id_t /*context_handle*/, const gss_buffer_t /*input_message_buffer*/, gss_buffer_t /*output_message_buffer*/, int * /*conf_state*/, gss_qop_t * qop_state ); OM_uint32 _gsskrb5_verify_8003_checksum ( OM_uint32 */*minor_status*/, const gss_channel_bindings_t /*input_chan_bindings*/, const Checksum */*cksum*/, OM_uint32 */*flags*/, krb5_data */*fwd_data*/); OM_uint32 _gsskrb5_verify_header ( u_char **/*str*/, size_t /*total_len*/, const void */*type*/, gss_OID /*oid*/); OM_uint32 GSSAPI_CALLCONV _gsskrb5_verify_mic ( OM_uint32 * /*minor_status*/, gss_const_ctx_id_t /*context_handle*/, const gss_buffer_t /*message_buffer*/, const gss_buffer_t /*token_buffer*/, gss_qop_t * qop_state ); OM_uint32 _gsskrb5_verify_mic_internal ( OM_uint32 * /*minor_status*/, const gsskrb5_ctx /*ctx*/, krb5_context /*context*/, const gss_buffer_t /*message_buffer*/, const gss_buffer_t /*token_buffer*/, gss_qop_t * /*qop_state*/, const char * type ); OM_uint32 GSSAPI_CALLCONV _gsskrb5_wrap ( OM_uint32 * /*minor_status*/, gss_const_ctx_id_t /*context_handle*/, int /*conf_req_flag*/, gss_qop_t /*qop_req*/, const gss_buffer_t /*input_message_buffer*/, int * /*conf_state*/, gss_buffer_t output_message_buffer ); OM_uint32 GSSAPI_CALLCONV _gsskrb5_wrap_size_limit ( OM_uint32 * /*minor_status*/, gss_const_ctx_id_t /*context_handle*/, int /*conf_req_flag*/, gss_qop_t /*qop_req*/, OM_uint32 /*req_output_size*/, OM_uint32 * max_input_size ); krb5_error_code _gsskrb5cfx_wrap_length_cfx ( krb5_context /*context*/, krb5_crypto /*crypto*/, int /*conf_req_flag*/, int /*dce_style*/, size_t /*input_length*/, size_t */*output_length*/, size_t */*cksumsize*/, uint16_t */*padlength*/); krb5_error_code _gsskrb5i_address_to_krb5addr ( krb5_context /*context*/, OM_uint32 /*gss_addr_type*/, gss_buffer_desc */*gss_addr*/, int16_t /*port*/, krb5_address */*address*/); krb5_error_code _gsskrb5i_get_acceptor_subkey ( const gsskrb5_ctx /*ctx*/, krb5_context /*context*/, krb5_keyblock **/*key*/); krb5_error_code _gsskrb5i_get_initiator_subkey ( const gsskrb5_ctx /*ctx*/, krb5_context /*context*/, krb5_keyblock **/*key*/); OM_uint32 _gsskrb5i_get_token_key ( const gsskrb5_ctx /*ctx*/, krb5_context /*context*/, krb5_keyblock **/*key*/); void _gsskrb5i_is_cfx ( krb5_context /*context*/, gsskrb5_ctx /*ctx*/, int /*acceptor*/); #endif /* __gsskrb5_private_h__ */ heimdal-7.5.0/lib/gssapi/krb5/inquire_mechs_for_name.c0000644000175000017500000000412013026237312021012 0ustar niknik/* * Copyright (c) 2003 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "gsskrb5_locl.h" OM_uint32 GSSAPI_CALLCONV _gsskrb5_inquire_mechs_for_name ( OM_uint32 * minor_status, gss_const_name_t input_name, gss_OID_set * mech_types ) { OM_uint32 ret; ret = gss_create_empty_oid_set(minor_status, mech_types); if (ret) return ret; ret = gss_add_oid_set_member(minor_status, GSS_KRB5_MECHANISM, mech_types); if (ret) gss_release_oid_set(NULL, mech_types); return ret; } heimdal-7.5.0/lib/gssapi/krb5/display_status.c0000644000175000017500000001277312136107747017407 0ustar niknik/* * Copyright (c) 1998 - 2006 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "gsskrb5_locl.h" static const char * calling_error(OM_uint32 v) { static const char *msgs[] = { NULL, /* 0 */ "A required input parameter could not be read.", /* */ "A required output parameter could not be written.", /* */ "A parameter was malformed" }; v >>= GSS_C_CALLING_ERROR_OFFSET; if (v == 0) return ""; else if (v >= sizeof(msgs)/sizeof(*msgs)) return "unknown calling error"; else return msgs[v]; } static const char * routine_error(OM_uint32 v) { static const char *msgs[] = { NULL, /* 0 */ "An unsupported mechanism was requested", "An invalid name was supplied", "A supplied name was of an unsupported type", "Incorrect channel bindings were supplied", "An invalid status code was supplied", "A token had an invalid MIC", "No credentials were supplied, " "or the credentials were unavailable or inaccessible.", "No context has been established", "A token was invalid", "A credential was invalid", "The referenced credentials have expired", "The context has expired", "Miscellaneous failure (see text)", "The quality-of-protection requested could not be provide", "The operation is forbidden by local security policy", "The operation or option is not available", "The requested credential element already exists", "The provided name was not a mechanism name.", }; v >>= GSS_C_ROUTINE_ERROR_OFFSET; if (v == 0) return ""; else if (v >= sizeof(msgs)/sizeof(*msgs)) return "unknown routine error"; else return msgs[v]; } static const char * supplementary_error(OM_uint32 v) { static const char *msgs[] = { "normal completion", "continuation call to routine required", "duplicate per-message token detected", "timed-out per-message token detected", "reordered (early) per-message token detected", "skipped predecessor token(s) detected" }; v >>= GSS_C_SUPPLEMENTARY_OFFSET; if (v >= sizeof(msgs)/sizeof(*msgs)) return "unknown routine error"; else return msgs[v]; } void _gsskrb5_clear_status (void) { krb5_context context; if (_gsskrb5_init (&context) != 0) return; krb5_clear_error_message(context); } void _gsskrb5_set_status (int ret, const char *fmt, ...) { krb5_context context; va_list args; char *str; int e; if (_gsskrb5_init (&context) != 0) return; va_start(args, fmt); e = vasprintf(&str, fmt, args); va_end(args); if (e >= 0 && str) { krb5_set_error_message(context, ret, "%s", str); free(str); } } OM_uint32 GSSAPI_CALLCONV _gsskrb5_display_status (OM_uint32 *minor_status, OM_uint32 status_value, int status_type, const gss_OID mech_type, OM_uint32 *message_context, gss_buffer_t status_string) { krb5_context context; char *buf = NULL; int e = 0; GSSAPI_KRB5_INIT (&context); status_string->length = 0; status_string->value = NULL; if (gss_oid_equal(mech_type, GSS_C_NO_OID) == 0 && gss_oid_equal(mech_type, GSS_KRB5_MECHANISM) == 0) { *minor_status = 0; return GSS_C_GSS_CODE; } if (status_type == GSS_C_GSS_CODE) { if (GSS_SUPPLEMENTARY_INFO(status_value)) e = asprintf(&buf, "%s", supplementary_error(GSS_SUPPLEMENTARY_INFO(status_value))); else e = asprintf (&buf, "%s %s", calling_error(GSS_CALLING_ERROR(status_value)), routine_error(GSS_ROUTINE_ERROR(status_value))); } else if (status_type == GSS_C_MECH_CODE) { const char *buf2 = krb5_get_error_message(context, status_value); if (buf2) { buf = strdup(buf2); krb5_free_error_message(context, buf2); } else { e = asprintf(&buf, "unknown mech error-code %u", (unsigned)status_value); } } else { *minor_status = EINVAL; return GSS_S_BAD_STATUS; } if (e < 0 || buf == NULL) { *minor_status = ENOMEM; return GSS_S_FAILURE; } *message_context = 0; *minor_status = 0; status_string->length = strlen(buf); status_string->value = buf; return GSS_S_COMPLETE; } heimdal-7.5.0/lib/gssapi/krb5/gsskrb5_locl.h0000644000175000017500000000735013026237312016717 0ustar niknik/* * Copyright (c) 1997 - 2008 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ /* $Id$ */ #ifndef GSSKRB5_LOCL_H #define GSSKRB5_LOCL_H #include #include #include #include #include #include #include #include "cfx.h" /* * */ struct gss_msg_order; typedef struct gsskrb5_ctx { struct krb5_auth_context_data *auth_context; struct krb5_auth_context_data *deleg_auth_context; krb5_principal source, target; #define IS_DCE_STYLE(ctx) (((ctx)->flags & GSS_C_DCE_STYLE) != 0) OM_uint32 flags; enum { LOCAL = 1, OPEN = 2, COMPAT_OLD_DES3 = 4, COMPAT_OLD_DES3_SELECTED = 8, ACCEPTOR_SUBKEY = 16, RETRIED = 32, CLOSE_CCACHE = 64, IS_CFX = 128 } more_flags; enum gss_ctx_id_t_state { /* initiator states */ INITIATOR_START, INITIATOR_RESTART, INITIATOR_WAIT_FOR_MUTAL, INITIATOR_READY, /* acceptor states */ ACCEPTOR_START, ACCEPTOR_WAIT_FOR_DCESTYLE, ACCEPTOR_READY } state; krb5_creds *kcred; krb5_ccache ccache; struct krb5_ticket *ticket; time_t endtime; HEIMDAL_MUTEX ctx_id_mutex; struct gss_msg_order *order; krb5_keyblock *service_keyblock; krb5_data fwd_data; krb5_crypto crypto; } *gsskrb5_ctx; typedef struct { krb5_principal principal; int cred_flags; #define GSS_CF_DESTROY_CRED_ON_RELEASE 1 #define GSS_CF_NO_CI_FLAGS 2 struct krb5_keytab_data *keytab; time_t endtime; gss_cred_usage_t usage; gss_OID_set mechanisms; struct krb5_ccache_data *ccache; HEIMDAL_MUTEX cred_id_mutex; krb5_enctype *enctypes; } *gsskrb5_cred; typedef struct Principal *gsskrb5_name; /* * */ extern krb5_keytab _gsskrb5_keytab; extern HEIMDAL_MUTEX gssapi_keytab_mutex; /* * Prototypes */ #include #define GSSAPI_KRB5_INIT(ctx) do { \ krb5_error_code kret_gss_init; \ if((kret_gss_init = _gsskrb5_init (ctx)) != 0) { \ *minor_status = kret_gss_init; \ return GSS_S_FAILURE; \ } \ } while (0) /* sec_context flags */ #define SC_LOCAL_ADDRESS 0x01 #define SC_REMOTE_ADDRESS 0x02 #define SC_KEYBLOCK 0x04 #define SC_LOCAL_SUBKEY 0x08 #define SC_REMOTE_SUBKEY 0x10 #endif heimdal-7.5.0/lib/gssapi/krb5/release_name.c0000644000175000017500000000400612136107747016745 0ustar niknik/* * Copyright (c) 1997 - 2003 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "gsskrb5_locl.h" OM_uint32 GSSAPI_CALLCONV _gsskrb5_release_name (OM_uint32 * minor_status, gss_name_t * input_name ) { krb5_context context; krb5_principal name = (krb5_principal)*input_name; *minor_status = 0; GSSAPI_KRB5_INIT (&context); *input_name = GSS_C_NO_NAME; krb5_free_principal(context, name); return GSS_S_COMPLETE; } heimdal-7.5.0/lib/gssapi/krb5/address_to_krb5addr.c0000644000175000017500000000524412136107747020237 0ustar niknik/* * Copyright (c) 2000 - 2001 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "gsskrb5_locl.h" #include krb5_error_code _gsskrb5i_address_to_krb5addr(krb5_context context, OM_uint32 gss_addr_type, gss_buffer_desc *gss_addr, int16_t port, krb5_address *address) { int addr_type; struct sockaddr sa; krb5_socklen_t sa_size = sizeof(sa); krb5_error_code problem; if (gss_addr == NULL) return GSS_S_FAILURE; switch (gss_addr_type) { #ifdef HAVE_IPV6 case GSS_C_AF_INET6: addr_type = AF_INET6; break; #endif /* HAVE_IPV6 */ case GSS_C_AF_INET: addr_type = AF_INET; break; default: return GSS_S_FAILURE; } problem = krb5_h_addr2sockaddr (context, addr_type, gss_addr->value, &sa, &sa_size, port); if (problem) return GSS_S_FAILURE; problem = krb5_sockaddr2address (context, &sa, address); return problem; } heimdal-7.5.0/lib/gssapi/krb5/release_buffer.c0000644000175000017500000000357512136107747017310 0ustar niknik/* * Copyright (c) 1997 - 2000, 2003 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "gsskrb5_locl.h" OM_uint32 _gsskrb5_release_buffer (OM_uint32 * minor_status, gss_buffer_t buffer ) { *minor_status = 0; free (buffer->value); buffer->value = NULL; buffer->length = 0; return GSS_S_COMPLETE; } heimdal-7.5.0/lib/gssapi/krb5/authorize_localname.c0000644000175000017500000000466613026237312020355 0ustar niknik/* * Copyright (c) 2011, PADL Software Pty Ltd. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of PADL Software nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY PADL SOFTWARE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL PADL SOFTWARE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "gsskrb5_locl.h" OM_uint32 GSSAPI_CALLCONV _gsskrb5_authorize_localname(OM_uint32 *minor_status, gss_const_name_t input_name, gss_const_buffer_t user_name, gss_const_OID user_name_type) { krb5_context context; krb5_principal princ = (krb5_principal)input_name; char *user; int user_ok; if (!gss_oid_equal(user_name_type, GSS_C_NT_USER_NAME)) return GSS_S_BAD_NAMETYPE; GSSAPI_KRB5_INIT(&context); user = malloc(user_name->length + 1); if (user == NULL) { *minor_status = ENOMEM; return GSS_S_FAILURE; } memcpy(user, user_name->value, user_name->length); user[user_name->length] = '\0'; *minor_status = 0; user_ok = krb5_kuserok(context, princ, user); free(user); return user_ok ? GSS_S_COMPLETE : GSS_S_UNAUTHORIZED; } heimdal-7.5.0/lib/gssapi/krb5/init_sec_context.c0000644000175000017500000005633413026237312017670 0ustar niknik/* * Copyright (c) 1997 - 2008 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "gsskrb5_locl.h" /* * copy the addresses from `input_chan_bindings' (if any) to * the auth context `ac' */ static OM_uint32 set_addresses (krb5_context context, krb5_auth_context ac, const gss_channel_bindings_t input_chan_bindings) { /* Port numbers are expected to be in application_data.value, * initator's port first */ krb5_address initiator_addr, acceptor_addr; krb5_error_code kret; if (input_chan_bindings == GSS_C_NO_CHANNEL_BINDINGS || input_chan_bindings->application_data.length != 2 * sizeof(ac->local_port)) return 0; memset(&initiator_addr, 0, sizeof(initiator_addr)); memset(&acceptor_addr, 0, sizeof(acceptor_addr)); ac->local_port = *(int16_t *) input_chan_bindings->application_data.value; ac->remote_port = *((int16_t *) input_chan_bindings->application_data.value + 1); kret = _gsskrb5i_address_to_krb5addr(context, input_chan_bindings->acceptor_addrtype, &input_chan_bindings->acceptor_address, ac->remote_port, &acceptor_addr); if (kret) return kret; kret = _gsskrb5i_address_to_krb5addr(context, input_chan_bindings->initiator_addrtype, &input_chan_bindings->initiator_address, ac->local_port, &initiator_addr); if (kret) { krb5_free_address (context, &acceptor_addr); return kret; } kret = krb5_auth_con_setaddrs(context, ac, &initiator_addr, /* local address */ &acceptor_addr); /* remote address */ krb5_free_address (context, &initiator_addr); krb5_free_address (context, &acceptor_addr); #if 0 free(input_chan_bindings->application_data.value); input_chan_bindings->application_data.value = NULL; input_chan_bindings->application_data.length = 0; #endif return kret; } OM_uint32 _gsskrb5_create_ctx( OM_uint32 * minor_status, gss_ctx_id_t * context_handle, krb5_context context, const gss_channel_bindings_t input_chan_bindings, enum gss_ctx_id_t_state state) { krb5_error_code kret; gsskrb5_ctx ctx; *context_handle = NULL; ctx = malloc(sizeof(*ctx)); if (ctx == NULL) { *minor_status = ENOMEM; return GSS_S_FAILURE; } ctx->auth_context = NULL; ctx->deleg_auth_context = NULL; ctx->source = NULL; ctx->target = NULL; ctx->kcred = NULL; ctx->ccache = NULL; ctx->state = state; ctx->flags = 0; ctx->more_flags = 0; ctx->service_keyblock = NULL; ctx->ticket = NULL; krb5_data_zero(&ctx->fwd_data); ctx->endtime = 0; ctx->order = NULL; ctx->crypto = NULL; HEIMDAL_MUTEX_init(&ctx->ctx_id_mutex); kret = krb5_auth_con_init (context, &ctx->auth_context); if (kret) { *minor_status = kret; HEIMDAL_MUTEX_destroy(&ctx->ctx_id_mutex); free(ctx); return GSS_S_FAILURE; } kret = krb5_auth_con_init (context, &ctx->deleg_auth_context); if (kret) { *minor_status = kret; krb5_auth_con_free(context, ctx->auth_context); HEIMDAL_MUTEX_destroy(&ctx->ctx_id_mutex); free(ctx); return GSS_S_FAILURE; } kret = set_addresses(context, ctx->auth_context, input_chan_bindings); if (kret) { *minor_status = kret; krb5_auth_con_free(context, ctx->auth_context); krb5_auth_con_free(context, ctx->deleg_auth_context); HEIMDAL_MUTEX_destroy(&ctx->ctx_id_mutex); free(ctx); return GSS_S_BAD_BINDINGS; } kret = set_addresses(context, ctx->deleg_auth_context, input_chan_bindings); if (kret) { *minor_status = kret; krb5_auth_con_free(context, ctx->auth_context); krb5_auth_con_free(context, ctx->deleg_auth_context); HEIMDAL_MUTEX_destroy(&ctx->ctx_id_mutex); free(ctx); return GSS_S_BAD_BINDINGS; } /* * We need a sequence number */ krb5_auth_con_addflags(context, ctx->auth_context, KRB5_AUTH_CONTEXT_DO_SEQUENCE | KRB5_AUTH_CONTEXT_CLEAR_FORWARDED_CRED, NULL); /* * We need a sequence number */ krb5_auth_con_addflags(context, ctx->deleg_auth_context, KRB5_AUTH_CONTEXT_DO_SEQUENCE | KRB5_AUTH_CONTEXT_CLEAR_FORWARDED_CRED, NULL); *context_handle = (gss_ctx_id_t)ctx; return GSS_S_COMPLETE; } static OM_uint32 gsskrb5_get_creds( OM_uint32 * minor_status, krb5_context context, krb5_ccache ccache, gsskrb5_ctx ctx, gss_const_name_t target_name, OM_uint32 time_req, OM_uint32 * time_rec) { OM_uint32 ret; krb5_error_code kret; krb5_creds this_cred; OM_uint32 lifetime_rec; if (ctx->target) { krb5_free_principal(context, ctx->target); ctx->target = NULL; } if (ctx->kcred) { krb5_free_creds(context, ctx->kcred); ctx->kcred = NULL; } ret = _gsskrb5_canon_name(minor_status, context, target_name, &ctx->target); if (ret) return ret; memset(&this_cred, 0, sizeof(this_cred)); this_cred.client = ctx->source; this_cred.server = ctx->target; if (time_req && time_req != GSS_C_INDEFINITE) { krb5_timestamp ts; krb5_timeofday (context, &ts); this_cred.times.endtime = ts + time_req; } else { this_cred.times.endtime = 0; } this_cred.session.keytype = KEYTYPE_NULL; kret = krb5_get_credentials(context, 0, ccache, &this_cred, &ctx->kcred); if (kret) { *minor_status = kret; return GSS_S_FAILURE; } ctx->endtime = ctx->kcred->times.endtime; ret = _gsskrb5_lifetime_left(minor_status, context, ctx->endtime, &lifetime_rec); if (ret) return ret; if (lifetime_rec == 0) { *minor_status = 0; return GSS_S_CONTEXT_EXPIRED; } if (time_rec) *time_rec = lifetime_rec; return GSS_S_COMPLETE; } static OM_uint32 gsskrb5_initiator_ready( OM_uint32 * minor_status, gsskrb5_ctx ctx, krb5_context context) { OM_uint32 ret; int32_t seq_number; int is_cfx = 0; OM_uint32 flags = ctx->flags; krb5_free_creds(context, ctx->kcred); ctx->kcred = NULL; if (ctx->more_flags & CLOSE_CCACHE) krb5_cc_close(context, ctx->ccache); ctx->ccache = NULL; krb5_auth_con_getremoteseqnumber (context, ctx->auth_context, &seq_number); _gsskrb5i_is_cfx(context, ctx, 0); is_cfx = (ctx->more_flags & IS_CFX); ret = _gssapi_msg_order_create(minor_status, &ctx->order, _gssapi_msg_order_f(flags), seq_number, 0, is_cfx); if (ret) return ret; ctx->state = INITIATOR_READY; ctx->more_flags |= OPEN; return GSS_S_COMPLETE; } /* * handle delegated creds in init-sec-context */ static void do_delegation (krb5_context context, krb5_auth_context ac, krb5_ccache ccache, krb5_creds *cred, krb5_const_principal name, krb5_data *fwd_data, uint32_t flagmask, uint32_t *flags) { krb5_creds creds; KDCOptions fwd_flags; krb5_error_code kret; memset (&creds, 0, sizeof(creds)); krb5_data_zero (fwd_data); kret = krb5_cc_get_principal(context, ccache, &creds.client); if (kret) goto out; kret = krb5_make_principal(context, &creds.server, creds.client->realm, KRB5_TGS_NAME, creds.client->realm, NULL); if (kret) goto out; creds.times.endtime = 0; memset(&fwd_flags, 0, sizeof(fwd_flags)); fwd_flags.forwarded = 1; fwd_flags.forwardable = 1; if (name->name.name_string.len < 2) goto out; kret = krb5_get_forwarded_creds(context, ac, ccache, KDCOptions2int(fwd_flags), name->name.name_string.val[1], &creds, fwd_data); out: if (kret) *flags &= ~flagmask; else *flags |= flagmask; if (creds.client) krb5_free_principal(context, creds.client); if (creds.server) krb5_free_principal(context, creds.server); } /* * first stage of init-sec-context */ static OM_uint32 init_auth (OM_uint32 * minor_status, gsskrb5_cred cred, gsskrb5_ctx ctx, krb5_context context, gss_const_name_t name, const gss_OID mech_type, OM_uint32 req_flags, OM_uint32 time_req, const gss_buffer_t input_token, gss_OID * actual_mech_type, gss_buffer_t output_token, OM_uint32 * ret_flags, OM_uint32 * time_rec ) { OM_uint32 ret = GSS_S_FAILURE; krb5_error_code kret; krb5_data fwd_data; OM_uint32 lifetime_rec; krb5_data_zero(&fwd_data); *minor_status = 0; if (actual_mech_type) *actual_mech_type = GSS_KRB5_MECHANISM; if (cred == NULL) { kret = krb5_cc_default (context, &ctx->ccache); if (kret) { *minor_status = kret; ret = GSS_S_FAILURE; goto failure; } ctx->more_flags |= CLOSE_CCACHE; } else ctx->ccache = cred->ccache; kret = krb5_cc_get_principal (context, ctx->ccache, &ctx->source); if (kret) { *minor_status = kret; ret = GSS_S_FAILURE; goto failure; } /* * This is hideous glue for (NFS) clients that wants to limit the * available enctypes to what it can support (encryption in * kernel). */ if (cred && cred->enctypes) krb5_set_default_in_tkt_etypes(context, cred->enctypes); ret = gsskrb5_get_creds(minor_status, context, ctx->ccache, ctx, name, time_req, time_rec); if (ret) goto failure; ctx->endtime = ctx->kcred->times.endtime; ret = _gss_DES3_get_mic_compat(minor_status, ctx, context); if (ret) goto failure; ret = _gsskrb5_lifetime_left(minor_status, context, ctx->endtime, &lifetime_rec); if (ret) goto failure; if (lifetime_rec == 0) { *minor_status = 0; ret = GSS_S_CONTEXT_EXPIRED; goto failure; } krb5_auth_con_setkey(context, ctx->auth_context, &ctx->kcred->session); kret = krb5_auth_con_generatelocalsubkey(context, ctx->auth_context, &ctx->kcred->session); if(kret) { *minor_status = kret; ret = GSS_S_FAILURE; goto failure; } return GSS_S_COMPLETE; failure: if (ctx->ccache && (ctx->more_flags & CLOSE_CCACHE)) krb5_cc_close(context, ctx->ccache); ctx->ccache = NULL; return ret; } static OM_uint32 init_auth_restart (OM_uint32 * minor_status, gsskrb5_cred cred, gsskrb5_ctx ctx, krb5_context context, OM_uint32 req_flags, const gss_channel_bindings_t input_chan_bindings, const gss_buffer_t input_token, gss_OID * actual_mech_type, gss_buffer_t output_token, OM_uint32 * ret_flags, OM_uint32 * time_rec ) { OM_uint32 ret = GSS_S_FAILURE; krb5_error_code kret; krb5_flags ap_options; krb5_data outbuf; uint32_t flags; krb5_data authenticator; Checksum cksum; krb5_enctype enctype; krb5_data fwd_data, timedata; int32_t offset = 0, oldoffset = 0; uint32_t flagmask; krb5_data_zero(&outbuf); krb5_data_zero(&fwd_data); *minor_status = 0; /* * If the credential doesn't have ok-as-delegate, check if there * is a realm setting and use that. */ if (!ctx->kcred->flags.b.ok_as_delegate) { krb5_data data; ret = krb5_cc_get_config(context, ctx->ccache, NULL, "realm-config", &data); if (ret == 0) { /* XXX 1 is use ok-as-delegate */ if (data.length < 1 || ((((unsigned char *)data.data)[0]) & 1) == 0) req_flags &= ~(GSS_C_DELEG_FLAG|GSS_C_DELEG_POLICY_FLAG); krb5_data_free(&data); } } flagmask = 0; /* if we used GSS_C_DELEG_POLICY_FLAG, trust KDC */ if ((req_flags & GSS_C_DELEG_POLICY_FLAG) && ctx->kcred->flags.b.ok_as_delegate) flagmask |= GSS_C_DELEG_FLAG | GSS_C_DELEG_POLICY_FLAG; /* if there still is a GSS_C_DELEG_FLAG, use that */ if (req_flags & GSS_C_DELEG_FLAG) flagmask |= GSS_C_DELEG_FLAG; flags = 0; ap_options = 0; if (flagmask & GSS_C_DELEG_FLAG) { do_delegation (context, ctx->deleg_auth_context, ctx->ccache, ctx->kcred, ctx->target, &fwd_data, flagmask, &flags); } if (req_flags & GSS_C_MUTUAL_FLAG) { flags |= GSS_C_MUTUAL_FLAG; ap_options |= AP_OPTS_MUTUAL_REQUIRED; } if (req_flags & GSS_C_REPLAY_FLAG) flags |= GSS_C_REPLAY_FLAG; if (req_flags & GSS_C_SEQUENCE_FLAG) flags |= GSS_C_SEQUENCE_FLAG; #if 0 if (req_flags & GSS_C_ANON_FLAG) ; /* XXX */ #endif if (req_flags & GSS_C_DCE_STYLE) { /* GSS_C_DCE_STYLE implies GSS_C_MUTUAL_FLAG */ flags |= GSS_C_DCE_STYLE | GSS_C_MUTUAL_FLAG; ap_options |= AP_OPTS_MUTUAL_REQUIRED; } if (req_flags & GSS_C_IDENTIFY_FLAG) flags |= GSS_C_IDENTIFY_FLAG; if (req_flags & GSS_C_EXTENDED_ERROR_FLAG) flags |= GSS_C_EXTENDED_ERROR_FLAG; if (req_flags & GSS_C_CONF_FLAG) { flags |= GSS_C_CONF_FLAG; } if (req_flags & GSS_C_INTEG_FLAG) { flags |= GSS_C_INTEG_FLAG; } if (cred == NULL || !(cred->cred_flags & GSS_CF_NO_CI_FLAGS)) { flags |= GSS_C_CONF_FLAG; flags |= GSS_C_INTEG_FLAG; } flags |= GSS_C_TRANS_FLAG; if (ret_flags) *ret_flags = flags; ctx->flags = flags; ctx->more_flags |= LOCAL; ret = _gsskrb5_create_8003_checksum (minor_status, input_chan_bindings, flags, &fwd_data, &cksum); krb5_data_free (&fwd_data); if (ret) goto failure; enctype = ctx->auth_context->keyblock->keytype; ret = krb5_cc_get_config(context, ctx->ccache, ctx->target, "time-offset", &timedata); if (ret == 0) { if (timedata.length == 4) { const u_char *p = timedata.data; offset = (p[0] <<24) | (p[1] << 16) | (p[2] << 8) | (p[3] << 0); } krb5_data_free(&timedata); } if (offset) { krb5_get_kdc_sec_offset (context, &oldoffset, NULL); krb5_set_kdc_sec_offset (context, offset, -1); } kret = _krb5_build_authenticator(context, ctx->auth_context, enctype, ctx->kcred, &cksum, &authenticator, KRB5_KU_AP_REQ_AUTH); if (kret) { if (offset) krb5_set_kdc_sec_offset (context, oldoffset, -1); *minor_status = kret; ret = GSS_S_FAILURE; goto failure; } kret = krb5_build_ap_req (context, enctype, ctx->kcred, ap_options, authenticator, &outbuf); if (offset) krb5_set_kdc_sec_offset (context, oldoffset, -1); if (kret) { *minor_status = kret; ret = GSS_S_FAILURE; goto failure; } if (flags & GSS_C_DCE_STYLE) { output_token->value = outbuf.data; output_token->length = outbuf.length; } else { ret = _gsskrb5_encapsulate (minor_status, &outbuf, output_token, (u_char *)(intptr_t)"\x01\x00", GSS_KRB5_MECHANISM); krb5_data_free (&outbuf); if (ret) goto failure; } free_Checksum(&cksum); if (flags & GSS_C_MUTUAL_FLAG) { ctx->state = INITIATOR_WAIT_FOR_MUTAL; return GSS_S_CONTINUE_NEEDED; } return gsskrb5_initiator_ready(minor_status, ctx, context); failure: if (ctx->ccache && (ctx->more_flags & CLOSE_CCACHE)) krb5_cc_close(context, ctx->ccache); ctx->ccache = NULL; return ret; } static krb5_error_code handle_error_packet(krb5_context context, gsskrb5_ctx ctx, krb5_data indata) { krb5_error_code kret; KRB_ERROR error; kret = krb5_rd_error(context, &indata, &error); if (kret == 0) { kret = krb5_error_from_rd_error(context, &error, NULL); /* save the time skrew for this host */ if (kret == KRB5KRB_AP_ERR_SKEW) { krb5_data timedata; unsigned char p[4]; int32_t t = error.stime - time(NULL); p[0] = (t >> 24) & 0xFF; p[1] = (t >> 16) & 0xFF; p[2] = (t >> 8) & 0xFF; p[3] = (t >> 0) & 0xFF; timedata.data = p; timedata.length = sizeof(p); krb5_cc_set_config(context, ctx->ccache, ctx->target, "time-offset", &timedata); if ((ctx->more_flags & RETRIED) == 0) ctx->state = INITIATOR_RESTART; ctx->more_flags |= RETRIED; } free_KRB_ERROR (&error); } return kret; } static OM_uint32 repl_mutual (OM_uint32 * minor_status, gsskrb5_ctx ctx, krb5_context context, const gss_OID mech_type, OM_uint32 req_flags, OM_uint32 time_req, const gss_channel_bindings_t input_chan_bindings, const gss_buffer_t input_token, gss_OID * actual_mech_type, gss_buffer_t output_token, OM_uint32 * ret_flags, OM_uint32 * time_rec ) { OM_uint32 ret; krb5_error_code kret; krb5_data indata; krb5_ap_rep_enc_part *repl; output_token->length = 0; output_token->value = NULL; if (actual_mech_type) *actual_mech_type = GSS_KRB5_MECHANISM; if (IS_DCE_STYLE(ctx)) { /* There is no OID wrapping. */ indata.length = input_token->length; indata.data = input_token->value; kret = krb5_rd_rep(context, ctx->auth_context, &indata, &repl); if (kret) { ret = _gsskrb5_decapsulate(minor_status, input_token, &indata, "\x03\x00", GSS_KRB5_MECHANISM); if (ret == GSS_S_COMPLETE) { *minor_status = handle_error_packet(context, ctx, indata); } else { *minor_status = kret; } return GSS_S_FAILURE; } } else { ret = _gsskrb5_decapsulate (minor_status, input_token, &indata, "\x02\x00", GSS_KRB5_MECHANISM); if (ret == GSS_S_DEFECTIVE_TOKEN) { /* check if there is an error token sent instead */ ret = _gsskrb5_decapsulate (minor_status, input_token, &indata, "\x03\x00", GSS_KRB5_MECHANISM); if (ret == GSS_S_COMPLETE) { *minor_status = handle_error_packet(context, ctx, indata); return GSS_S_FAILURE; } } kret = krb5_rd_rep (context, ctx->auth_context, &indata, &repl); if (kret) { *minor_status = kret; return GSS_S_FAILURE; } } krb5_free_ap_rep_enc_part (context, repl); *minor_status = 0; if (time_rec) _gsskrb5_lifetime_left(minor_status, context, ctx->endtime, time_rec); if (ret_flags) *ret_flags = ctx->flags; if (req_flags & GSS_C_DCE_STYLE) { int32_t local_seq, remote_seq; krb5_data outbuf; /* * So DCE_STYLE is strange. The client echos the seq number * that the server used in the server's mk_rep in its own * mk_rep(). After when done, it resets to it's own seq number * for the gss_wrap calls. */ krb5_auth_con_getremoteseqnumber(context, ctx->auth_context, &remote_seq); krb5_auth_con_getlocalseqnumber(context, ctx->auth_context, &local_seq); krb5_auth_con_setlocalseqnumber(context, ctx->auth_context, remote_seq); kret = krb5_mk_rep(context, ctx->auth_context, &outbuf); if (kret) { *minor_status = kret; return GSS_S_FAILURE; } /* reset local seq number */ krb5_auth_con_setlocalseqnumber(context, ctx->auth_context, local_seq); output_token->length = outbuf.length; output_token->value = outbuf.data; } return gsskrb5_initiator_ready(minor_status, ctx, context); } /* * gss_init_sec_context */ OM_uint32 GSSAPI_CALLCONV _gsskrb5_init_sec_context (OM_uint32 * minor_status, gss_const_cred_id_t cred_handle, gss_ctx_id_t * context_handle, gss_const_name_t target_name, const gss_OID mech_type, OM_uint32 req_flags, OM_uint32 time_req, const gss_channel_bindings_t input_chan_bindings, const gss_buffer_t input_token, gss_OID * actual_mech_type, gss_buffer_t output_token, OM_uint32 * ret_flags, OM_uint32 * time_rec ) { krb5_context context; gsskrb5_cred cred = (gsskrb5_cred)cred_handle; gsskrb5_ctx ctx; OM_uint32 ret; GSSAPI_KRB5_INIT (&context); output_token->length = 0; output_token->value = NULL; if (context_handle == NULL) { *minor_status = 0; return GSS_S_FAILURE | GSS_S_CALL_BAD_STRUCTURE; } if (ret_flags) *ret_flags = 0; if (time_rec) *time_rec = 0; if (target_name == GSS_C_NO_NAME) { if (actual_mech_type) *actual_mech_type = GSS_C_NO_OID; *minor_status = 0; return GSS_S_BAD_NAME; } if (mech_type != GSS_C_NO_OID && !gss_oid_equal(mech_type, GSS_KRB5_MECHANISM)) return GSS_S_BAD_MECH; if (input_token == GSS_C_NO_BUFFER || input_token->length == 0) { OM_uint32 ret1; if (*context_handle != GSS_C_NO_CONTEXT) { *minor_status = 0; return GSS_S_FAILURE | GSS_S_CALL_BAD_STRUCTURE; } ret1 = _gsskrb5_create_ctx(minor_status, context_handle, context, input_chan_bindings, INITIATOR_START); if (ret1) return ret1; } if (*context_handle == GSS_C_NO_CONTEXT) { *minor_status = 0; return GSS_S_FAILURE | GSS_S_CALL_BAD_STRUCTURE; } ctx = (gsskrb5_ctx) *context_handle; HEIMDAL_MUTEX_lock(&ctx->ctx_id_mutex); again: switch (ctx->state) { case INITIATOR_START: ret = init_auth(minor_status, cred, ctx, context, target_name, mech_type, req_flags, time_req, input_token, actual_mech_type, output_token, ret_flags, time_rec); if (ret != GSS_S_COMPLETE) break; /* FALL THOUGH */ case INITIATOR_RESTART: ret = init_auth_restart(minor_status, cred, ctx, context, req_flags, input_chan_bindings, input_token, actual_mech_type, output_token, ret_flags, time_rec); break; case INITIATOR_WAIT_FOR_MUTAL: ret = repl_mutual(minor_status, ctx, context, mech_type, req_flags, time_req, input_chan_bindings, input_token, actual_mech_type, output_token, ret_flags, time_rec); if (ctx->state == INITIATOR_RESTART) goto again; break; case INITIATOR_READY: /* * If we get there, the caller have called * gss_init_sec_context() one time too many. */ _gsskrb5_set_status(EINVAL, "init_sec_context " "called one time too many"); *minor_status = EINVAL; ret = GSS_S_BAD_STATUS; break; default: _gsskrb5_set_status(EINVAL, "init_sec_context " "invalid state %d for client", (int)ctx->state); *minor_status = EINVAL; ret = GSS_S_BAD_STATUS; break; } HEIMDAL_MUTEX_unlock(&ctx->ctx_id_mutex); /* destroy context in case of error */ if (GSS_ERROR(ret)) { OM_uint32 min2; _gsskrb5_delete_sec_context(&min2, context_handle, GSS_C_NO_BUFFER); } return ret; } heimdal-7.5.0/lib/gssapi/krb5/arcfour.c0000644000175000017500000010247013212137553015764 0ustar niknik/* * Copyright (c) 2003 - 2006 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "gsskrb5_locl.h" /* * Implements draft-brezak-win2k-krb-rc4-hmac-04.txt * * The arcfour message have the following formats: * * MIC token * TOK_ID[2] = 01 01 * SGN_ALG[2] = 11 00 * Filler[4] * SND_SEQ[8] * SGN_CKSUM[8] * * WRAP token * TOK_ID[2] = 02 01 * SGN_ALG[2]; * SEAL_ALG[2] * Filler[2] * SND_SEQ[2] * SGN_CKSUM[8] * Confounder[8] */ /* * WRAP in DCE-style have a fixed size header, the oid and length over * the WRAP header is a total of * GSS_ARCFOUR_WRAP_TOKEN_DCE_DER_HEADER_SIZE + * GSS_ARCFOUR_WRAP_TOKEN_SIZE byte (ie total of 45 bytes overhead, * remember the 2 bytes from APPL [0] SEQ). */ #define GSS_ARCFOUR_WRAP_TOKEN_SIZE 32 #define GSS_ARCFOUR_WRAP_TOKEN_DCE_DER_HEADER_SIZE 13 static krb5_error_code arcfour_mic_key(krb5_context context, krb5_keyblock *key, const void *cksum_data, size_t cksum_size, void *key6_data, size_t key6_size) { krb5_error_code ret; Checksum cksum_k5; krb5_keyblock key5; char k5_data[16]; Checksum cksum_k6; char T[4]; memset(T, 0, 4); cksum_k5.checksum.data = k5_data; cksum_k5.checksum.length = sizeof(k5_data); if (key->keytype == KRB5_ENCTYPE_ARCFOUR_HMAC_MD5_56) { char L40[14] = "fortybits"; memcpy(L40 + 10, T, sizeof(T)); ret = krb5_hmac(context, CKSUMTYPE_RSA_MD5, L40, 14, 0, key, &cksum_k5); memset(&k5_data[7], 0xAB, 9); } else { ret = krb5_hmac(context, CKSUMTYPE_RSA_MD5, T, 4, 0, key, &cksum_k5); } if (ret) return ret; key5.keytype = KRB5_ENCTYPE_ARCFOUR_HMAC_MD5; key5.keyvalue = cksum_k5.checksum; cksum_k6.checksum.data = key6_data; cksum_k6.checksum.length = key6_size; return krb5_hmac(context, CKSUMTYPE_RSA_MD5, cksum_data, cksum_size, 0, &key5, &cksum_k6); } static krb5_error_code arcfour_mic_cksum_iov(krb5_context context, krb5_keyblock *key, unsigned usage, u_char *sgn_cksum, size_t sgn_cksum_sz, const u_char *v1, size_t l1, const void *v2, size_t l2, const gss_iov_buffer_desc *iov, int iov_count, const gss_iov_buffer_desc *padding) { Checksum CKSUM; u_char *ptr; size_t len; size_t ofs = 0; int i; krb5_crypto crypto; krb5_error_code ret; assert(sgn_cksum_sz == 8); len = l1 + l2; for (i=0; i < iov_count; i++) { switch (GSS_IOV_BUFFER_TYPE(iov[i].type)) { case GSS_IOV_BUFFER_TYPE_DATA: case GSS_IOV_BUFFER_TYPE_SIGN_ONLY: break; default: continue; } len += iov[i].buffer.length; } if (padding) { len += padding->buffer.length; } ptr = malloc(len); if (ptr == NULL) return ENOMEM; memcpy(ptr + ofs, v1, l1); ofs += l1; memcpy(ptr + ofs, v2, l2); ofs += l2; for (i=0; i < iov_count; i++) { switch (GSS_IOV_BUFFER_TYPE(iov[i].type)) { case GSS_IOV_BUFFER_TYPE_DATA: case GSS_IOV_BUFFER_TYPE_SIGN_ONLY: break; default: continue; } memcpy(ptr + ofs, iov[i].buffer.value, iov[i].buffer.length); ofs += iov[i].buffer.length; } if (padding) { memcpy(ptr + ofs, padding->buffer.value, padding->buffer.length); ofs += padding->buffer.length; } ret = krb5_crypto_init(context, key, 0, &crypto); if (ret) { free(ptr); return ret; } ret = krb5_create_checksum(context, crypto, usage, 0, ptr, len, &CKSUM); memset(ptr, 0, len); free(ptr); if (ret == 0) { memcpy(sgn_cksum, CKSUM.checksum.data, sgn_cksum_sz); free_Checksum(&CKSUM); } krb5_crypto_destroy(context, crypto); return ret; } static krb5_error_code arcfour_mic_cksum(krb5_context context, krb5_keyblock *key, unsigned usage, u_char *sgn_cksum, size_t sgn_cksum_sz, const u_char *v1, size_t l1, const void *v2, size_t l2, const void *v3, size_t l3) { gss_iov_buffer_desc iov; iov.type = GSS_IOV_BUFFER_TYPE_SIGN_ONLY; iov.buffer.value = rk_UNCONST(v3); iov.buffer.length = l3; return arcfour_mic_cksum_iov(context, key, usage, sgn_cksum, sgn_cksum_sz, v1, l1, v2, l2, &iov, 1, NULL); } OM_uint32 _gssapi_get_mic_arcfour(OM_uint32 * minor_status, const gsskrb5_ctx context_handle, krb5_context context, gss_qop_t qop_req, const gss_buffer_t message_buffer, gss_buffer_t message_token, krb5_keyblock *key) { krb5_error_code ret; int32_t seq_number; size_t len, total_len; u_char k6_data[16], *p0, *p; EVP_CIPHER_CTX rc4_key; _gsskrb5_encap_length (22, &len, &total_len, GSS_KRB5_MECHANISM); message_token->length = total_len; message_token->value = malloc (total_len); if (message_token->value == NULL) { *minor_status = ENOMEM; return GSS_S_FAILURE; } p0 = _gssapi_make_mech_header(message_token->value, len, GSS_KRB5_MECHANISM); p = p0; *p++ = 0x01; /* TOK_ID */ *p++ = 0x01; *p++ = 0x11; /* SGN_ALG */ *p++ = 0x00; *p++ = 0xff; /* Filler */ *p++ = 0xff; *p++ = 0xff; *p++ = 0xff; p = NULL; ret = arcfour_mic_cksum(context, key, KRB5_KU_USAGE_SIGN, p0 + 16, 8, /* SGN_CKSUM */ p0, 8, /* TOK_ID, SGN_ALG, Filer */ message_buffer->value, message_buffer->length, NULL, 0); if (ret) { _gsskrb5_release_buffer(minor_status, message_token); *minor_status = ret; return GSS_S_FAILURE; } ret = arcfour_mic_key(context, key, p0 + 16, 8, /* SGN_CKSUM */ k6_data, sizeof(k6_data)); if (ret) { _gsskrb5_release_buffer(minor_status, message_token); *minor_status = ret; return GSS_S_FAILURE; } HEIMDAL_MUTEX_lock(&context_handle->ctx_id_mutex); krb5_auth_con_getlocalseqnumber (context, context_handle->auth_context, &seq_number); p = p0 + 8; /* SND_SEQ */ _gsskrb5_encode_be_om_uint32(seq_number, p); krb5_auth_con_setlocalseqnumber (context, context_handle->auth_context, ++seq_number); HEIMDAL_MUTEX_unlock(&context_handle->ctx_id_mutex); memset (p + 4, (context_handle->more_flags & LOCAL) ? 0 : 0xff, 4); EVP_CIPHER_CTX_init(&rc4_key); EVP_CipherInit_ex(&rc4_key, EVP_rc4(), NULL, k6_data, NULL, 1); EVP_Cipher(&rc4_key, p, p, 8); EVP_CIPHER_CTX_cleanup(&rc4_key); memset(k6_data, 0, sizeof(k6_data)); *minor_status = 0; return GSS_S_COMPLETE; } OM_uint32 _gssapi_verify_mic_arcfour(OM_uint32 * minor_status, const gsskrb5_ctx context_handle, krb5_context context, const gss_buffer_t message_buffer, const gss_buffer_t token_buffer, gss_qop_t * qop_state, krb5_keyblock *key, const char *type) { krb5_error_code ret; uint32_t seq_number; OM_uint32 omret; u_char SND_SEQ[8], cksum_data[8], *p; char k6_data[16]; int cmp; if (qop_state) *qop_state = 0; p = token_buffer->value; omret = _gsskrb5_verify_header (&p, token_buffer->length, type, GSS_KRB5_MECHANISM); if (omret) return omret; if (memcmp(p, "\x11\x00", 2) != 0) /* SGN_ALG = HMAC MD5 ARCFOUR */ return GSS_S_BAD_SIG; p += 2; if (memcmp (p, "\xff\xff\xff\xff", 4) != 0) return GSS_S_BAD_MIC; p += 4; ret = arcfour_mic_cksum(context, key, KRB5_KU_USAGE_SIGN, cksum_data, sizeof(cksum_data), p - 8, 8, message_buffer->value, message_buffer->length, NULL, 0); if (ret) { *minor_status = ret; return GSS_S_FAILURE; } ret = arcfour_mic_key(context, key, cksum_data, sizeof(cksum_data), k6_data, sizeof(k6_data)); if (ret) { *minor_status = ret; return GSS_S_FAILURE; } cmp = ct_memcmp(cksum_data, p + 8, 8); if (cmp) { *minor_status = 0; return GSS_S_BAD_MIC; } { EVP_CIPHER_CTX rc4_key; EVP_CIPHER_CTX_init(&rc4_key); EVP_CipherInit_ex(&rc4_key, EVP_rc4(), NULL, (void *)k6_data, NULL, 0); EVP_Cipher(&rc4_key, SND_SEQ, p, 8); EVP_CIPHER_CTX_cleanup(&rc4_key); memset(k6_data, 0, sizeof(k6_data)); } _gsskrb5_decode_be_om_uint32(SND_SEQ, &seq_number); if (context_handle->more_flags & LOCAL) cmp = memcmp(&SND_SEQ[4], "\xff\xff\xff\xff", 4); else cmp = memcmp(&SND_SEQ[4], "\x00\x00\x00\x00", 4); memset(SND_SEQ, 0, sizeof(SND_SEQ)); if (cmp != 0) { *minor_status = 0; return GSS_S_BAD_MIC; } HEIMDAL_MUTEX_lock(&context_handle->ctx_id_mutex); omret = _gssapi_msg_order_check(context_handle->order, seq_number); HEIMDAL_MUTEX_unlock(&context_handle->ctx_id_mutex); if (omret) return omret; *minor_status = 0; return GSS_S_COMPLETE; } OM_uint32 _gssapi_wrap_arcfour(OM_uint32 * minor_status, const gsskrb5_ctx context_handle, krb5_context context, int conf_req_flag, gss_qop_t qop_req, const gss_buffer_t input_message_buffer, int * conf_state, gss_buffer_t output_message_buffer, krb5_keyblock *key) { u_char Klocaldata[16], k6_data[16], *p, *p0; size_t len, total_len, datalen; krb5_keyblock Klocal; krb5_error_code ret; int32_t seq_number; if (conf_state) *conf_state = 0; datalen = input_message_buffer->length; if (IS_DCE_STYLE(context_handle)) { len = GSS_ARCFOUR_WRAP_TOKEN_SIZE; _gssapi_encap_length(len, &len, &total_len, GSS_KRB5_MECHANISM); total_len += datalen; } else { datalen += 1; /* padding */ len = datalen + GSS_ARCFOUR_WRAP_TOKEN_SIZE; _gssapi_encap_length(len, &len, &total_len, GSS_KRB5_MECHANISM); } output_message_buffer->length = total_len; output_message_buffer->value = malloc (total_len); if (output_message_buffer->value == NULL) { *minor_status = ENOMEM; return GSS_S_FAILURE; } p0 = _gssapi_make_mech_header(output_message_buffer->value, len, GSS_KRB5_MECHANISM); p = p0; *p++ = 0x02; /* TOK_ID */ *p++ = 0x01; *p++ = 0x11; /* SGN_ALG */ *p++ = 0x00; if (conf_req_flag) { *p++ = 0x10; /* SEAL_ALG */ *p++ = 0x00; } else { *p++ = 0xff; /* SEAL_ALG */ *p++ = 0xff; } *p++ = 0xff; /* Filler */ *p++ = 0xff; p = NULL; HEIMDAL_MUTEX_lock(&context_handle->ctx_id_mutex); krb5_auth_con_getlocalseqnumber (context, context_handle->auth_context, &seq_number); _gsskrb5_encode_be_om_uint32(seq_number, p0 + 8); krb5_auth_con_setlocalseqnumber (context, context_handle->auth_context, ++seq_number); HEIMDAL_MUTEX_unlock(&context_handle->ctx_id_mutex); memset (p0 + 8 + 4, (context_handle->more_flags & LOCAL) ? 0 : 0xff, 4); krb5_generate_random_block(p0 + 24, 8); /* fill in Confounder */ /* p points to data */ p = p0 + GSS_ARCFOUR_WRAP_TOKEN_SIZE; memcpy(p, input_message_buffer->value, input_message_buffer->length); if (!IS_DCE_STYLE(context_handle)) p[input_message_buffer->length] = 1; /* padding */ ret = arcfour_mic_cksum(context, key, KRB5_KU_USAGE_SEAL, p0 + 16, 8, /* SGN_CKSUM */ p0, 8, /* TOK_ID, SGN_ALG, SEAL_ALG, Filler */ p0 + 24, 8, /* Confounder */ p0 + GSS_ARCFOUR_WRAP_TOKEN_SIZE, datalen); if (ret) { *minor_status = ret; _gsskrb5_release_buffer(minor_status, output_message_buffer); return GSS_S_FAILURE; } { int i; Klocal.keytype = key->keytype; Klocal.keyvalue.data = Klocaldata; Klocal.keyvalue.length = sizeof(Klocaldata); for (i = 0; i < 16; i++) Klocaldata[i] = ((u_char *)key->keyvalue.data)[i] ^ 0xF0; } ret = arcfour_mic_key(context, &Klocal, p0 + 8, 4, /* SND_SEQ */ k6_data, sizeof(k6_data)); memset(Klocaldata, 0, sizeof(Klocaldata)); if (ret) { _gsskrb5_release_buffer(minor_status, output_message_buffer); *minor_status = ret; return GSS_S_FAILURE; } if(conf_req_flag) { EVP_CIPHER_CTX rc4_key; EVP_CIPHER_CTX_init(&rc4_key); EVP_CipherInit_ex(&rc4_key, EVP_rc4(), NULL, k6_data, NULL, 1); EVP_Cipher(&rc4_key, p0 + 24, p0 + 24, 8 + datalen); EVP_CIPHER_CTX_cleanup(&rc4_key); } memset(k6_data, 0, sizeof(k6_data)); ret = arcfour_mic_key(context, key, p0 + 16, 8, /* SGN_CKSUM */ k6_data, sizeof(k6_data)); if (ret) { _gsskrb5_release_buffer(minor_status, output_message_buffer); *minor_status = ret; return GSS_S_FAILURE; } { EVP_CIPHER_CTX rc4_key; EVP_CIPHER_CTX_init(&rc4_key); EVP_CipherInit_ex(&rc4_key, EVP_rc4(), NULL, k6_data, NULL, 1); EVP_Cipher(&rc4_key, p0 + 8, p0 + 8 /* SND_SEQ */, 8); EVP_CIPHER_CTX_cleanup(&rc4_key); memset(k6_data, 0, sizeof(k6_data)); } if (conf_state) *conf_state = conf_req_flag; *minor_status = 0; return GSS_S_COMPLETE; } OM_uint32 _gssapi_unwrap_arcfour(OM_uint32 *minor_status, const gsskrb5_ctx context_handle, krb5_context context, const gss_buffer_t input_message_buffer, gss_buffer_t output_message_buffer, int *conf_state, gss_qop_t *qop_state, krb5_keyblock *key) { u_char Klocaldata[16]; krb5_keyblock Klocal; krb5_error_code ret; uint32_t seq_number; size_t datalen; OM_uint32 omret; u_char k6_data[16], SND_SEQ[8], Confounder[8]; u_char cksum_data[8]; u_char *p, *p0; int cmp; int conf_flag; size_t padlen = 0, len; if (conf_state) *conf_state = 0; if (qop_state) *qop_state = 0; p0 = input_message_buffer->value; if (IS_DCE_STYLE(context_handle)) { len = GSS_ARCFOUR_WRAP_TOKEN_SIZE + GSS_ARCFOUR_WRAP_TOKEN_DCE_DER_HEADER_SIZE; if (input_message_buffer->length < len) return GSS_S_BAD_MECH; } else { len = input_message_buffer->length; } omret = _gssapi_verify_mech_header(&p0, len, GSS_KRB5_MECHANISM); if (omret) return omret; /* length of mech header */ len = (p0 - (u_char *)input_message_buffer->value) + GSS_ARCFOUR_WRAP_TOKEN_SIZE; if (len > input_message_buffer->length) return GSS_S_BAD_MECH; /* length of data */ datalen = input_message_buffer->length - len; p = p0; if (memcmp(p, "\x02\x01", 2) != 0) return GSS_S_BAD_SIG; p += 2; if (memcmp(p, "\x11\x00", 2) != 0) /* SGN_ALG = HMAC MD5 ARCFOUR */ return GSS_S_BAD_SIG; p += 2; if (memcmp (p, "\x10\x00", 2) == 0) conf_flag = 1; else if (memcmp (p, "\xff\xff", 2) == 0) conf_flag = 0; else return GSS_S_BAD_SIG; p += 2; if (memcmp (p, "\xff\xff", 2) != 0) return GSS_S_BAD_MIC; p = NULL; ret = arcfour_mic_key(context, key, p0 + 16, 8, /* SGN_CKSUM */ k6_data, sizeof(k6_data)); if (ret) { *minor_status = ret; return GSS_S_FAILURE; } { EVP_CIPHER_CTX rc4_key; EVP_CIPHER_CTX_init(&rc4_key); EVP_CipherInit_ex(&rc4_key, EVP_rc4(), NULL, k6_data, NULL, 1); EVP_Cipher(&rc4_key, SND_SEQ, p0 + 8, 8); EVP_CIPHER_CTX_cleanup(&rc4_key); memset(k6_data, 0, sizeof(k6_data)); } _gsskrb5_decode_be_om_uint32(SND_SEQ, &seq_number); if (context_handle->more_flags & LOCAL) cmp = memcmp(&SND_SEQ[4], "\xff\xff\xff\xff", 4); else cmp = memcmp(&SND_SEQ[4], "\x00\x00\x00\x00", 4); if (cmp != 0) { *minor_status = 0; return GSS_S_BAD_MIC; } { int i; Klocal.keytype = key->keytype; Klocal.keyvalue.data = Klocaldata; Klocal.keyvalue.length = sizeof(Klocaldata); for (i = 0; i < 16; i++) Klocaldata[i] = ((u_char *)key->keyvalue.data)[i] ^ 0xF0; } ret = arcfour_mic_key(context, &Klocal, SND_SEQ, 4, k6_data, sizeof(k6_data)); memset(Klocaldata, 0, sizeof(Klocaldata)); if (ret) { *minor_status = ret; return GSS_S_FAILURE; } output_message_buffer->value = malloc(datalen); if (output_message_buffer->value == NULL) { *minor_status = ENOMEM; return GSS_S_FAILURE; } output_message_buffer->length = datalen; if(conf_flag) { EVP_CIPHER_CTX rc4_key; EVP_CIPHER_CTX_init(&rc4_key); EVP_CipherInit_ex(&rc4_key, EVP_rc4(), NULL, k6_data, NULL, 1); EVP_Cipher(&rc4_key, Confounder, p0 + 24, 8); EVP_Cipher(&rc4_key, output_message_buffer->value, p0 + GSS_ARCFOUR_WRAP_TOKEN_SIZE, datalen); EVP_CIPHER_CTX_cleanup(&rc4_key); } else { memcpy(Confounder, p0 + 24, 8); /* Confounder */ memcpy(output_message_buffer->value, p0 + GSS_ARCFOUR_WRAP_TOKEN_SIZE, datalen); } memset(k6_data, 0, sizeof(k6_data)); if (!IS_DCE_STYLE(context_handle)) { ret = _gssapi_verify_pad(output_message_buffer, datalen, &padlen); if (ret) { _gsskrb5_release_buffer(minor_status, output_message_buffer); *minor_status = 0; return ret; } output_message_buffer->length -= padlen; } ret = arcfour_mic_cksum(context, key, KRB5_KU_USAGE_SEAL, cksum_data, sizeof(cksum_data), p0, 8, Confounder, sizeof(Confounder), output_message_buffer->value, output_message_buffer->length + padlen); if (ret) { _gsskrb5_release_buffer(minor_status, output_message_buffer); *minor_status = ret; return GSS_S_FAILURE; } cmp = ct_memcmp(cksum_data, p0 + 16, 8); /* SGN_CKSUM */ if (cmp) { _gsskrb5_release_buffer(minor_status, output_message_buffer); *minor_status = 0; return GSS_S_BAD_MIC; } HEIMDAL_MUTEX_lock(&context_handle->ctx_id_mutex); omret = _gssapi_msg_order_check(context_handle->order, seq_number); HEIMDAL_MUTEX_unlock(&context_handle->ctx_id_mutex); if (omret) return omret; if (conf_state) *conf_state = conf_flag; *minor_status = 0; return GSS_S_COMPLETE; } static OM_uint32 max_wrap_length_arcfour(const gsskrb5_ctx ctx, krb5_crypto crypto, size_t input_length, OM_uint32 *max_input_size) { /* * if GSS_C_DCE_STYLE is in use: * - we only need to encapsulate the WRAP token * However, since this is a fixed since, we just */ if (IS_DCE_STYLE(ctx)) { size_t len, total_len; len = GSS_ARCFOUR_WRAP_TOKEN_SIZE; _gssapi_encap_length(len, &len, &total_len, GSS_KRB5_MECHANISM); if (input_length < len) *max_input_size = 0; else *max_input_size = input_length - len; } else { size_t extrasize = GSS_ARCFOUR_WRAP_TOKEN_SIZE; size_t blocksize = 8; size_t len, total_len; len = 8 + input_length + blocksize + extrasize; _gsskrb5_encap_length(len, &len, &total_len, GSS_KRB5_MECHANISM); total_len -= input_length; /* token length */ if (total_len < input_length) { *max_input_size = (input_length - total_len); (*max_input_size) &= (~(OM_uint32)(blocksize - 1)); } else { *max_input_size = 0; } } return GSS_S_COMPLETE; } OM_uint32 _gssapi_wrap_size_arcfour(OM_uint32 *minor_status, const gsskrb5_ctx ctx, krb5_context context, int conf_req_flag, gss_qop_t qop_req, OM_uint32 req_output_size, OM_uint32 *max_input_size, krb5_keyblock *key) { krb5_error_code ret; krb5_crypto crypto; ret = krb5_crypto_init(context, key, 0, &crypto); if (ret != 0) { *minor_status = ret; return GSS_S_FAILURE; } ret = max_wrap_length_arcfour(ctx, crypto, req_output_size, max_input_size); if (ret != 0) { *minor_status = ret; krb5_crypto_destroy(context, crypto); return GSS_S_FAILURE; } krb5_crypto_destroy(context, crypto); return GSS_S_COMPLETE; } OM_uint32 _gssapi_wrap_iov_length_arcfour(OM_uint32 *minor_status, gsskrb5_ctx ctx, krb5_context context, int conf_req_flag, gss_qop_t qop_req, int *conf_state, gss_iov_buffer_desc *iov, int iov_count) { OM_uint32 major_status; size_t data_len = 0; int i; gss_iov_buffer_desc *header = NULL; gss_iov_buffer_desc *padding = NULL; gss_iov_buffer_desc *trailer = NULL; *minor_status = 0; for (i = 0; i < iov_count; i++) { switch(GSS_IOV_BUFFER_TYPE(iov[i].type)) { case GSS_IOV_BUFFER_TYPE_EMPTY: break; case GSS_IOV_BUFFER_TYPE_DATA: data_len += iov[i].buffer.length; break; case GSS_IOV_BUFFER_TYPE_HEADER: if (header != NULL) { *minor_status = EINVAL; return GSS_S_FAILURE; } header = &iov[i]; break; case GSS_IOV_BUFFER_TYPE_TRAILER: if (trailer != NULL) { *minor_status = EINVAL; return GSS_S_FAILURE; } trailer = &iov[i]; break; case GSS_IOV_BUFFER_TYPE_PADDING: if (padding != NULL) { *minor_status = EINVAL; return GSS_S_FAILURE; } padding = &iov[i]; break; case GSS_IOV_BUFFER_TYPE_SIGN_ONLY: break; default: *minor_status = EINVAL; return GSS_S_FAILURE; } } major_status = _gk_verify_buffers(minor_status, ctx, header, padding, trailer); if (major_status != GSS_S_COMPLETE) { return major_status; } if (IS_DCE_STYLE(ctx)) { size_t len = GSS_ARCFOUR_WRAP_TOKEN_SIZE; size_t total_len; _gssapi_encap_length(len, &len, &total_len, GSS_KRB5_MECHANISM); header->buffer.length = total_len; } else { size_t len; size_t total_len; if (padding) { data_len += 1; /* padding */ } len = data_len + GSS_ARCFOUR_WRAP_TOKEN_SIZE; _gssapi_encap_length(len, &len, &total_len, GSS_KRB5_MECHANISM); header->buffer.length = total_len - data_len; } if (trailer) { trailer->buffer.length = 0; } if (padding) { padding->buffer.length = 1; } return GSS_S_COMPLETE; } OM_uint32 _gssapi_wrap_iov_arcfour(OM_uint32 *minor_status, gsskrb5_ctx ctx, krb5_context context, int conf_req_flag, int *conf_state, gss_iov_buffer_desc *iov, int iov_count, krb5_keyblock *key) { OM_uint32 major_status, junk; gss_iov_buffer_desc *header, *padding, *trailer; krb5_error_code kret; int32_t seq_number; u_char Klocaldata[16], k6_data[16], *p, *p0; size_t make_len = 0; size_t header_len = 0; size_t data_len = 0; krb5_keyblock Klocal; int i; header = _gk_find_buffer(iov, iov_count, GSS_IOV_BUFFER_TYPE_HEADER); padding = _gk_find_buffer(iov, iov_count, GSS_IOV_BUFFER_TYPE_PADDING); trailer = _gk_find_buffer(iov, iov_count, GSS_IOV_BUFFER_TYPE_TRAILER); major_status = _gk_verify_buffers(minor_status, ctx, header, padding, trailer); if (major_status != GSS_S_COMPLETE) { return major_status; } for (i = 0; i < iov_count; i++) { switch (GSS_IOV_BUFFER_TYPE(iov[i].type)) { case GSS_IOV_BUFFER_TYPE_DATA: break; default: continue; } data_len += iov[i].buffer.length; } if (padding) { data_len += 1; } if (IS_DCE_STYLE(ctx)) { size_t unwrapped_len; unwrapped_len = GSS_ARCFOUR_WRAP_TOKEN_SIZE; _gssapi_encap_length(unwrapped_len, &make_len, &header_len, GSS_KRB5_MECHANISM); } else { size_t unwrapped_len; unwrapped_len = GSS_ARCFOUR_WRAP_TOKEN_SIZE + data_len; _gssapi_encap_length(unwrapped_len, &make_len, &header_len, GSS_KRB5_MECHANISM); header_len -= data_len; } if (GSS_IOV_BUFFER_FLAGS(header->type) & GSS_IOV_BUFFER_TYPE_FLAG_ALLOCATE) { major_status = _gk_allocate_buffer(minor_status, header, header_len); if (major_status != GSS_S_COMPLETE) goto failure; } else if (header->buffer.length < header_len) { *minor_status = KRB5_BAD_MSIZE; major_status = GSS_S_FAILURE; goto failure; } else { header->buffer.length = header_len; } if (padding) { if (GSS_IOV_BUFFER_FLAGS(padding->type) & GSS_IOV_BUFFER_TYPE_FLAG_ALLOCATE) { major_status = _gk_allocate_buffer(minor_status, padding, 1); if (major_status != GSS_S_COMPLETE) goto failure; } else if (padding->buffer.length < 1) { *minor_status = KRB5_BAD_MSIZE; major_status = GSS_S_FAILURE; goto failure; } else { padding->buffer.length = 1; } memset(padding->buffer.value, 1, 1); } if (trailer) { trailer->buffer.length = 0; trailer->buffer.value = NULL; } p0 = _gssapi_make_mech_header(header->buffer.value, make_len, GSS_KRB5_MECHANISM); p = p0; *p++ = 0x02; /* TOK_ID */ *p++ = 0x01; *p++ = 0x11; /* SGN_ALG */ *p++ = 0x00; if (conf_req_flag) { *p++ = 0x10; /* SEAL_ALG */ *p++ = 0x00; } else { *p++ = 0xff; /* SEAL_ALG */ *p++ = 0xff; } *p++ = 0xff; /* Filler */ *p++ = 0xff; p = NULL; HEIMDAL_MUTEX_lock(&ctx->ctx_id_mutex); krb5_auth_con_getlocalseqnumber(context, ctx->auth_context, &seq_number); _gsskrb5_encode_be_om_uint32(seq_number, p0 + 8); krb5_auth_con_setlocalseqnumber(context, ctx->auth_context, ++seq_number); HEIMDAL_MUTEX_unlock(&ctx->ctx_id_mutex); memset(p0 + 8 + 4, (ctx->more_flags & LOCAL) ? 0 : 0xff, 4); krb5_generate_random_block(p0 + 24, 8); /* fill in Confounder */ /* Sign Data */ kret = arcfour_mic_cksum_iov(context, key, KRB5_KU_USAGE_SEAL, p0 + 16, 8, /* SGN_CKSUM */ p0, 8, /* TOK_ID, SGN_ALG, SEAL_ALG, Filler */ p0 + 24, 8, /* Confounder */ iov, iov_count, /* Data + SignOnly */ padding); /* padding */ if (kret) { *minor_status = kret; major_status = GSS_S_FAILURE; goto failure; } Klocal.keytype = key->keytype; Klocal.keyvalue.data = Klocaldata; Klocal.keyvalue.length = sizeof(Klocaldata); for (i = 0; i < 16; i++) { Klocaldata[i] = ((u_char *)key->keyvalue.data)[i] ^ 0xF0; } kret = arcfour_mic_key(context, &Klocal, p0 + 8, 4, /* SND_SEQ */ k6_data, sizeof(k6_data)); memset(Klocaldata, 0, sizeof(Klocaldata)); if (kret) { *minor_status = kret; major_status = GSS_S_FAILURE; goto failure; } if (conf_req_flag) { EVP_CIPHER_CTX rc4_key; EVP_CIPHER_CTX_init(&rc4_key); EVP_CipherInit_ex(&rc4_key, EVP_rc4(), NULL, k6_data, NULL, 1); /* Confounder */ EVP_Cipher(&rc4_key, p0 + 24, p0 + 24, 8); /* Seal Data */ for (i=0; i < iov_count; i++) { switch (GSS_IOV_BUFFER_TYPE(iov[i].type)) { case GSS_IOV_BUFFER_TYPE_DATA: break; default: continue; } EVP_Cipher(&rc4_key, iov[i].buffer.value, iov[i].buffer.value, iov[i].buffer.length); } /* Padding */ if (padding) { EVP_Cipher(&rc4_key, padding->buffer.value, padding->buffer.value, padding->buffer.length); } EVP_CIPHER_CTX_cleanup(&rc4_key); } memset(k6_data, 0, sizeof(k6_data)); kret = arcfour_mic_key(context, key, p0 + 16, 8, /* SGN_CKSUM */ k6_data, sizeof(k6_data)); if (kret) { *minor_status = kret; major_status = GSS_S_FAILURE; return major_status; } { EVP_CIPHER_CTX rc4_key; EVP_CIPHER_CTX_init(&rc4_key); EVP_CipherInit_ex(&rc4_key, EVP_rc4(), NULL, k6_data, NULL, 1); EVP_Cipher(&rc4_key, p0 + 8, p0 + 8, 8); /* SND_SEQ */ EVP_CIPHER_CTX_cleanup(&rc4_key); memset(k6_data, 0, sizeof(k6_data)); } if (conf_state) *conf_state = conf_req_flag; *minor_status = 0; return GSS_S_COMPLETE; failure: gss_release_iov_buffer(&junk, iov, iov_count); return major_status; } OM_uint32 _gssapi_unwrap_iov_arcfour(OM_uint32 *minor_status, gsskrb5_ctx ctx, krb5_context context, int *pconf_state, gss_qop_t *pqop_state, gss_iov_buffer_desc *iov, int iov_count, krb5_keyblock *key) { OM_uint32 major_status; gss_iov_buffer_desc *header, *padding, *trailer; krb5_keyblock Klocal; uint8_t Klocaldata[16]; uint8_t k6_data[16], snd_seq[8], Confounder[8]; uint8_t cksum_data[8]; uint8_t *_p = NULL; const uint8_t *p, *p0; size_t verify_len = 0; uint32_t seq_number; size_t hlen = 0; int conf_state; int cmp; size_t i; krb5_error_code kret; OM_uint32 ret; if (pconf_state != NULL) { *pconf_state = 0; } if (pqop_state != NULL) { *pqop_state = 0; } header = _gk_find_buffer(iov, iov_count, GSS_IOV_BUFFER_TYPE_HEADER); padding = _gk_find_buffer(iov, iov_count, GSS_IOV_BUFFER_TYPE_PADDING); trailer = _gk_find_buffer(iov, iov_count, GSS_IOV_BUFFER_TYPE_TRAILER); /* Check if the packet is correct */ major_status = _gk_verify_buffers(minor_status, ctx, header, padding, trailer); if (major_status != GSS_S_COMPLETE) { return major_status; } if (padding != NULL && padding->buffer.length != 1) { *minor_status = EINVAL; return GSS_S_FAILURE; } if (IS_DCE_STYLE(context)) { verify_len = GSS_ARCFOUR_WRAP_TOKEN_SIZE + GSS_ARCFOUR_WRAP_TOKEN_DCE_DER_HEADER_SIZE; if (header->buffer.length > verify_len) { return GSS_S_BAD_MECH; } } else { verify_len = header->buffer.length; } _p = header->buffer.value; ret = _gssapi_verify_mech_header(&_p, verify_len, GSS_KRB5_MECHANISM); if (ret) { return ret; } p0 = _p; /* length of mech header */ hlen = (p0 - (uint8_t *)header->buffer.value); hlen += GSS_ARCFOUR_WRAP_TOKEN_SIZE; if (hlen > header->buffer.length) { return GSS_S_BAD_MECH; } p = p0; if (memcmp(p, "\x02\x01", 2) != 0) return GSS_S_BAD_SIG; p += 2; if (memcmp(p, "\x11\x00", 2) != 0) /* SGN_ALG = HMAC MD5 ARCFOUR */ return GSS_S_BAD_SIG; p += 2; if (memcmp (p, "\x10\x00", 2) == 0) conf_state = 1; else if (memcmp (p, "\xff\xff", 2) == 0) conf_state = 0; else return GSS_S_BAD_SIG; p += 2; if (memcmp (p, "\xff\xff", 2) != 0) return GSS_S_BAD_MIC; p = NULL; kret = arcfour_mic_key(context, key, p0 + 16, /* SGN_CKSUM */ 8, /* SGN_CKSUM_LEN */ k6_data, sizeof(k6_data)); if (kret) { *minor_status = kret; return GSS_S_FAILURE; } { EVP_CIPHER_CTX rc4_key; EVP_CIPHER_CTX_init(&rc4_key); EVP_CipherInit_ex(&rc4_key, EVP_rc4(), NULL, k6_data, NULL, 1); EVP_Cipher(&rc4_key, snd_seq, p0 + 8, 8); /* SND_SEQ */ EVP_CIPHER_CTX_cleanup(&rc4_key); memset(k6_data, 0, sizeof(k6_data)); } _gsskrb5_decode_be_om_uint32(snd_seq, &seq_number); if (ctx->more_flags & LOCAL) { cmp = memcmp(&snd_seq[4], "\xff\xff\xff\xff", 4); } else { cmp = memcmp(&snd_seq[4], "\x00\x00\x00\x00", 4); } if (cmp != 0) { *minor_status = 0; return GSS_S_BAD_MIC; } if (ctx->more_flags & LOCAL) { cmp = memcmp(&snd_seq[4], "\xff\xff\xff\xff", 4); } else { cmp = memcmp(&snd_seq[4], "\x00\x00\x00\x00", 4); } if (cmp != 0) { *minor_status = 0; return GSS_S_BAD_MIC; } /* keyblock */ Klocal.keytype = key->keytype; Klocal.keyvalue.data = Klocaldata; Klocal.keyvalue.length = sizeof(Klocaldata); for (i = 0; i < 16; i++) { Klocaldata[i] = ((u_char *)key->keyvalue.data)[i] ^ 0xF0; } kret = arcfour_mic_key(context, &Klocal, snd_seq, 4, k6_data, sizeof(k6_data)); memset(Klocaldata, 0, sizeof(Klocaldata)); if (kret) { *minor_status = kret; return GSS_S_FAILURE; } if (conf_state == 1) { EVP_CIPHER_CTX rc4_key; EVP_CIPHER_CTX_init(&rc4_key); EVP_CipherInit_ex(&rc4_key, EVP_rc4(), NULL, k6_data, NULL, 1); /* Confounder */ EVP_Cipher(&rc4_key, Confounder, p0 + 24, 8); /* Data */ for (i = 0; i < iov_count; i++) { switch (GSS_IOV_BUFFER_TYPE(iov[i].type)) { case GSS_IOV_BUFFER_TYPE_DATA: break; default: continue; } EVP_Cipher(&rc4_key, iov[i].buffer.value, iov[i].buffer.value, iov[i].buffer.length); } /* Padding */ if (padding) { EVP_Cipher(&rc4_key, padding->buffer.value, padding->buffer.value, padding->buffer.length); } EVP_CIPHER_CTX_cleanup(&rc4_key); } else { /* Confounder */ memcpy(Confounder, p0 + 24, 8); } memset(k6_data, 0, sizeof(k6_data)); /* Prepare the buffer for signing */ kret = arcfour_mic_cksum_iov(context, key, KRB5_KU_USAGE_SEAL, cksum_data, sizeof(cksum_data), p0, 8, Confounder, sizeof(Confounder), iov, iov_count, padding); if (kret) { *minor_status = kret; return GSS_S_FAILURE; } cmp = memcmp(cksum_data, p0 + 16, 8); /* SGN_CKSUM */ if (cmp != 0) { *minor_status = 0; return GSS_S_BAD_MIC; } if (padding) { size_t plen; ret = _gssapi_verify_pad(&padding->buffer, 1, &plen); if (ret) { *minor_status = 0; return ret; } } HEIMDAL_MUTEX_lock(&ctx->ctx_id_mutex); ret = _gssapi_msg_order_check(ctx->order, seq_number); HEIMDAL_MUTEX_unlock(&ctx->ctx_id_mutex); if (ret != 0) { return ret; } if (pconf_state) { *pconf_state = conf_state; } *minor_status = 0; return GSS_S_COMPLETE; } heimdal-7.5.0/lib/gssapi/krb5/wrap.c0000644000175000017500000003775313026237312015304 0ustar niknik/* * Copyright (c) 1997 - 2003 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "gsskrb5_locl.h" /* * Return initiator subkey, or if that doesn't exists, the subkey. */ krb5_error_code _gsskrb5i_get_initiator_subkey(const gsskrb5_ctx ctx, krb5_context context, krb5_keyblock **key) { krb5_error_code ret; *key = NULL; if (ctx->more_flags & LOCAL) { ret = krb5_auth_con_getlocalsubkey(context, ctx->auth_context, key); } else { ret = krb5_auth_con_getremotesubkey(context, ctx->auth_context, key); } if (ret == 0 && *key == NULL) ret = krb5_auth_con_getkey(context, ctx->auth_context, key); if (ret == 0 && *key == NULL) { krb5_set_error_message(context, 0, "No initiator subkey available"); return GSS_KRB5_S_KG_NO_SUBKEY; } return ret; } krb5_error_code _gsskrb5i_get_acceptor_subkey(const gsskrb5_ctx ctx, krb5_context context, krb5_keyblock **key) { krb5_error_code ret; *key = NULL; if (ctx->more_flags & LOCAL) { ret = krb5_auth_con_getremotesubkey(context, ctx->auth_context, key); } else { ret = krb5_auth_con_getlocalsubkey(context, ctx->auth_context, key); } if (ret == 0 && *key == NULL) { krb5_set_error_message(context, 0, "No acceptor subkey available"); return GSS_KRB5_S_KG_NO_SUBKEY; } return ret; } OM_uint32 _gsskrb5i_get_token_key(const gsskrb5_ctx ctx, krb5_context context, krb5_keyblock **key) { _gsskrb5i_get_acceptor_subkey(ctx, context, key); if(*key == NULL) { /* * Only use the initiator subkey or ticket session key if an * acceptor subkey was not required. */ if ((ctx->more_flags & ACCEPTOR_SUBKEY) == 0) _gsskrb5i_get_initiator_subkey(ctx, context, key); } if (*key == NULL) { krb5_set_error_message(context, 0, "No token key available"); return GSS_KRB5_S_KG_NO_SUBKEY; } return 0; } static OM_uint32 sub_wrap_size ( OM_uint32 req_output_size, OM_uint32 * max_input_size, int blocksize, int extrasize ) { size_t len, total_len; len = 8 + req_output_size + blocksize + extrasize; _gsskrb5_encap_length(len, &len, &total_len, GSS_KRB5_MECHANISM); total_len -= req_output_size; /* token length */ if (total_len < req_output_size) { *max_input_size = (req_output_size - total_len); (*max_input_size) &= (~(OM_uint32)(blocksize - 1)); } else { *max_input_size = 0; } return GSS_S_COMPLETE; } OM_uint32 GSSAPI_CALLCONV _gsskrb5_wrap_size_limit ( OM_uint32 * minor_status, gss_const_ctx_id_t context_handle, int conf_req_flag, gss_qop_t qop_req, OM_uint32 req_output_size, OM_uint32 * max_input_size ) { krb5_context context; krb5_keyblock *key; OM_uint32 ret; const gsskrb5_ctx ctx = (const gsskrb5_ctx) context_handle; GSSAPI_KRB5_INIT (&context); if (ctx->more_flags & IS_CFX) return _gssapi_wrap_size_cfx(minor_status, ctx, context, conf_req_flag, qop_req, req_output_size, max_input_size); HEIMDAL_MUTEX_lock(&ctx->ctx_id_mutex); ret = _gsskrb5i_get_token_key(ctx, context, &key); HEIMDAL_MUTEX_unlock(&ctx->ctx_id_mutex); if (ret) { *minor_status = ret; return GSS_S_FAILURE; } switch (key->keytype) { case KRB5_ENCTYPE_DES_CBC_CRC : case KRB5_ENCTYPE_DES_CBC_MD4 : case KRB5_ENCTYPE_DES_CBC_MD5 : #ifdef HEIM_WEAK_CRYPTO ret = sub_wrap_size(req_output_size, max_input_size, 8, 22); #else ret = GSS_S_FAILURE; #endif break; case KRB5_ENCTYPE_ARCFOUR_HMAC_MD5: case KRB5_ENCTYPE_ARCFOUR_HMAC_MD5_56: ret = _gssapi_wrap_size_arcfour(minor_status, ctx, context, conf_req_flag, qop_req, req_output_size, max_input_size, key); break; case KRB5_ENCTYPE_DES3_CBC_MD5 : case KRB5_ENCTYPE_DES3_CBC_SHA1 : ret = sub_wrap_size(req_output_size, max_input_size, 8, 34); break; default : abort(); break; } krb5_free_keyblock (context, key); *minor_status = 0; return ret; } #ifdef HEIM_WEAK_CRYPTO static OM_uint32 wrap_des (OM_uint32 * minor_status, const gsskrb5_ctx ctx, krb5_context context, int conf_req_flag, gss_qop_t qop_req, const gss_buffer_t input_message_buffer, int * conf_state, gss_buffer_t output_message_buffer, krb5_keyblock *key ) { u_char *p; EVP_MD_CTX *md5; u_char hash[16]; DES_key_schedule schedule; EVP_CIPHER_CTX des_ctx; DES_cblock deskey; DES_cblock zero; size_t i; int32_t seq_number; size_t len, total_len, padlength, datalen; if (IS_DCE_STYLE(ctx)) { padlength = 0; datalen = input_message_buffer->length; len = 22 + 8; _gsskrb5_encap_length (len, &len, &total_len, GSS_KRB5_MECHANISM); total_len += datalen; datalen += 8; } else { padlength = 8 - (input_message_buffer->length % 8); datalen = input_message_buffer->length + padlength + 8; len = datalen + 22; _gsskrb5_encap_length (len, &len, &total_len, GSS_KRB5_MECHANISM); } output_message_buffer->length = total_len; output_message_buffer->value = malloc (total_len); if (output_message_buffer->value == NULL) { output_message_buffer->length = 0; *minor_status = ENOMEM; return GSS_S_FAILURE; } p = _gsskrb5_make_header(output_message_buffer->value, len, "\x02\x01", /* TOK_ID */ GSS_KRB5_MECHANISM); /* SGN_ALG */ memcpy (p, "\x00\x00", 2); p += 2; /* SEAL_ALG */ if(conf_req_flag) memcpy (p, "\x00\x00", 2); else memcpy (p, "\xff\xff", 2); p += 2; /* Filler */ memcpy (p, "\xff\xff", 2); p += 2; /* fill in later */ memset (p, 0, 16); p += 16; /* confounder + data + pad */ krb5_generate_random_block(p, 8); memcpy (p + 8, input_message_buffer->value, input_message_buffer->length); memset (p + 8 + input_message_buffer->length, padlength, padlength); /* checksum */ md5 = EVP_MD_CTX_create(); EVP_DigestInit_ex(md5, EVP_md5(), NULL); EVP_DigestUpdate(md5, p - 24, 8); EVP_DigestUpdate(md5, p, datalen); EVP_DigestFinal_ex(md5, hash, NULL); EVP_MD_CTX_destroy(md5); memset (&zero, 0, sizeof(zero)); memcpy (&deskey, key->keyvalue.data, sizeof(deskey)); DES_set_key_unchecked (&deskey, &schedule); DES_cbc_cksum ((void *)hash, (void *)hash, sizeof(hash), &schedule, &zero); memcpy (p - 8, hash, 8); /* sequence number */ HEIMDAL_MUTEX_lock(&ctx->ctx_id_mutex); krb5_auth_con_getlocalseqnumber (context, ctx->auth_context, &seq_number); p -= 16; p[0] = (seq_number >> 0) & 0xFF; p[1] = (seq_number >> 8) & 0xFF; p[2] = (seq_number >> 16) & 0xFF; p[3] = (seq_number >> 24) & 0xFF; memset (p + 4, (ctx->more_flags & LOCAL) ? 0 : 0xFF, 4); EVP_CIPHER_CTX_init(&des_ctx); EVP_CipherInit_ex(&des_ctx, EVP_des_cbc(), NULL, key->keyvalue.data, p + 8, 1); EVP_Cipher(&des_ctx, p, p, 8); EVP_CIPHER_CTX_cleanup(&des_ctx); krb5_auth_con_setlocalseqnumber (context, ctx->auth_context, ++seq_number); HEIMDAL_MUTEX_unlock(&ctx->ctx_id_mutex); /* encrypt the data */ p += 16; if(conf_req_flag) { memcpy (&deskey, key->keyvalue.data, sizeof(deskey)); for (i = 0; i < sizeof(deskey); ++i) deskey[i] ^= 0xf0; EVP_CIPHER_CTX_init(&des_ctx); EVP_CipherInit_ex(&des_ctx, EVP_des_cbc(), NULL, deskey, zero, 1); EVP_Cipher(&des_ctx, p, p, datalen); EVP_CIPHER_CTX_cleanup(&des_ctx); } memset (deskey, 0, sizeof(deskey)); memset (&schedule, 0, sizeof(schedule)); if(conf_state != NULL) *conf_state = conf_req_flag; *minor_status = 0; return GSS_S_COMPLETE; } #endif static OM_uint32 wrap_des3 (OM_uint32 * minor_status, const gsskrb5_ctx ctx, krb5_context context, int conf_req_flag, gss_qop_t qop_req, const gss_buffer_t input_message_buffer, int * conf_state, gss_buffer_t output_message_buffer, krb5_keyblock *key ) { u_char *p; u_char seq[8]; int32_t seq_number; size_t len, total_len, padlength, datalen; uint32_t ret; krb5_crypto crypto; Checksum cksum; krb5_data encdata; if (IS_DCE_STYLE(ctx)) { padlength = 0; datalen = input_message_buffer->length; len = 34 + 8; _gsskrb5_encap_length (len, &len, &total_len, GSS_KRB5_MECHANISM); total_len += datalen; datalen += 8; } else { padlength = 8 - (input_message_buffer->length % 8); datalen = input_message_buffer->length + padlength + 8; len = datalen + 34; _gsskrb5_encap_length (len, &len, &total_len, GSS_KRB5_MECHANISM); } output_message_buffer->length = total_len; output_message_buffer->value = malloc (total_len); if (output_message_buffer->value == NULL) { output_message_buffer->length = 0; *minor_status = ENOMEM; return GSS_S_FAILURE; } p = _gsskrb5_make_header(output_message_buffer->value, len, "\x02\x01", /* TOK_ID */ GSS_KRB5_MECHANISM); /* SGN_ALG */ memcpy (p, "\x04\x00", 2); /* HMAC SHA1 DES3-KD */ p += 2; /* SEAL_ALG */ if(conf_req_flag) memcpy (p, "\x02\x00", 2); /* DES3-KD */ else memcpy (p, "\xff\xff", 2); p += 2; /* Filler */ memcpy (p, "\xff\xff", 2); p += 2; /* calculate checksum (the above + confounder + data + pad) */ memcpy (p + 20, p - 8, 8); krb5_generate_random_block(p + 28, 8); memcpy (p + 28 + 8, input_message_buffer->value, input_message_buffer->length); memset (p + 28 + 8 + input_message_buffer->length, padlength, padlength); ret = krb5_crypto_init(context, key, 0, &crypto); if (ret) { free (output_message_buffer->value); output_message_buffer->length = 0; output_message_buffer->value = NULL; *minor_status = ret; return GSS_S_FAILURE; } ret = krb5_create_checksum (context, crypto, KRB5_KU_USAGE_SIGN, 0, p + 20, datalen + 8, &cksum); krb5_crypto_destroy (context, crypto); if (ret) { free (output_message_buffer->value); output_message_buffer->length = 0; output_message_buffer->value = NULL; *minor_status = ret; return GSS_S_FAILURE; } /* zero out SND_SEQ + SGN_CKSUM in case */ memset (p, 0, 28); memcpy (p + 8, cksum.checksum.data, cksum.checksum.length); free_Checksum (&cksum); HEIMDAL_MUTEX_lock(&ctx->ctx_id_mutex); /* sequence number */ krb5_auth_con_getlocalseqnumber (context, ctx->auth_context, &seq_number); seq[0] = (seq_number >> 0) & 0xFF; seq[1] = (seq_number >> 8) & 0xFF; seq[2] = (seq_number >> 16) & 0xFF; seq[3] = (seq_number >> 24) & 0xFF; memset (seq + 4, (ctx->more_flags & LOCAL) ? 0 : 0xFF, 4); ret = krb5_crypto_init(context, key, ETYPE_DES3_CBC_NONE, &crypto); if (ret) { free (output_message_buffer->value); output_message_buffer->length = 0; output_message_buffer->value = NULL; *minor_status = ret; return GSS_S_FAILURE; } { DES_cblock ivec; memcpy (&ivec, p + 8, 8); ret = krb5_encrypt_ivec (context, crypto, KRB5_KU_USAGE_SEQ, seq, 8, &encdata, &ivec); } krb5_crypto_destroy (context, crypto); if (ret) { free (output_message_buffer->value); output_message_buffer->length = 0; output_message_buffer->value = NULL; *minor_status = ret; return GSS_S_FAILURE; } assert (encdata.length == 8); memcpy (p, encdata.data, encdata.length); krb5_data_free (&encdata); krb5_auth_con_setlocalseqnumber (context, ctx->auth_context, ++seq_number); HEIMDAL_MUTEX_unlock(&ctx->ctx_id_mutex); /* encrypt the data */ p += 28; if(conf_req_flag) { krb5_data tmp; ret = krb5_crypto_init(context, key, ETYPE_DES3_CBC_NONE, &crypto); if (ret) { free (output_message_buffer->value); output_message_buffer->length = 0; output_message_buffer->value = NULL; *minor_status = ret; return GSS_S_FAILURE; } ret = krb5_encrypt(context, crypto, KRB5_KU_USAGE_SEAL, p, datalen, &tmp); krb5_crypto_destroy(context, crypto); if (ret) { free (output_message_buffer->value); output_message_buffer->length = 0; output_message_buffer->value = NULL; *minor_status = ret; return GSS_S_FAILURE; } assert (tmp.length == datalen); memcpy (p, tmp.data, datalen); krb5_data_free(&tmp); } if(conf_state != NULL) *conf_state = conf_req_flag; *minor_status = 0; return GSS_S_COMPLETE; } OM_uint32 GSSAPI_CALLCONV _gsskrb5_wrap (OM_uint32 * minor_status, gss_const_ctx_id_t context_handle, int conf_req_flag, gss_qop_t qop_req, const gss_buffer_t input_message_buffer, int * conf_state, gss_buffer_t output_message_buffer ) { krb5_context context; krb5_keyblock *key; OM_uint32 ret; const gsskrb5_ctx ctx = (const gsskrb5_ctx) context_handle; output_message_buffer->value = NULL; output_message_buffer->length = 0; GSSAPI_KRB5_INIT (&context); if (ctx->more_flags & IS_CFX) return _gssapi_wrap_cfx (minor_status, ctx, context, conf_req_flag, input_message_buffer, conf_state, output_message_buffer); HEIMDAL_MUTEX_lock(&ctx->ctx_id_mutex); ret = _gsskrb5i_get_token_key(ctx, context, &key); HEIMDAL_MUTEX_unlock(&ctx->ctx_id_mutex); if (ret) { *minor_status = ret; return GSS_S_FAILURE; } switch (key->keytype) { case KRB5_ENCTYPE_DES_CBC_CRC : case KRB5_ENCTYPE_DES_CBC_MD4 : case KRB5_ENCTYPE_DES_CBC_MD5 : #ifdef HEIM_WEAK_CRYPTO ret = wrap_des (minor_status, ctx, context, conf_req_flag, qop_req, input_message_buffer, conf_state, output_message_buffer, key); #else ret = GSS_S_FAILURE; #endif break; case KRB5_ENCTYPE_DES3_CBC_MD5 : case KRB5_ENCTYPE_DES3_CBC_SHA1 : ret = wrap_des3 (minor_status, ctx, context, conf_req_flag, qop_req, input_message_buffer, conf_state, output_message_buffer, key); break; case KRB5_ENCTYPE_ARCFOUR_HMAC_MD5: case KRB5_ENCTYPE_ARCFOUR_HMAC_MD5_56: ret = _gssapi_wrap_arcfour (minor_status, ctx, context, conf_req_flag, qop_req, input_message_buffer, conf_state, output_message_buffer, key); break; default : abort(); break; } krb5_free_keyblock (context, key); return ret; } heimdal-7.5.0/lib/gssapi/krb5/8003.c0000644000175000017500000001576713026237312014726 0ustar niknik/* * Copyright (c) 1997 - 2003 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "gsskrb5_locl.h" krb5_error_code _gsskrb5_encode_om_uint32(OM_uint32 n, u_char *p) { p[0] = (n >> 0) & 0xFF; p[1] = (n >> 8) & 0xFF; p[2] = (n >> 16) & 0xFF; p[3] = (n >> 24) & 0xFF; return 0; } krb5_error_code _gsskrb5_encode_be_om_uint32(OM_uint32 n, u_char *p) { p[0] = (n >> 24) & 0xFF; p[1] = (n >> 16) & 0xFF; p[2] = (n >> 8) & 0xFF; p[3] = (n >> 0) & 0xFF; return 0; } krb5_error_code _gsskrb5_decode_om_uint32(const void *ptr, OM_uint32 *n) { const u_char *p = ptr; *n = (p[0] << 0) | (p[1] << 8) | (p[2] << 16) | (p[3] << 24); return 0; } krb5_error_code _gsskrb5_decode_be_om_uint32(const void *ptr, OM_uint32 *n) { const u_char *p = ptr; *n = (p[0] <<24) | (p[1] << 16) | (p[2] << 8) | (p[3] << 0); return 0; } static krb5_error_code hash_input_chan_bindings (const gss_channel_bindings_t b, u_char *p) { u_char num[4]; EVP_MD_CTX *ctx; ctx = EVP_MD_CTX_create(); EVP_DigestInit_ex(ctx, EVP_md5(), NULL); _gsskrb5_encode_om_uint32 (b->initiator_addrtype, num); EVP_DigestUpdate(ctx, num, sizeof(num)); _gsskrb5_encode_om_uint32 (b->initiator_address.length, num); EVP_DigestUpdate(ctx, num, sizeof(num)); if (b->initiator_address.length) EVP_DigestUpdate(ctx, b->initiator_address.value, b->initiator_address.length); _gsskrb5_encode_om_uint32 (b->acceptor_addrtype, num); EVP_DigestUpdate(ctx, num, sizeof(num)); _gsskrb5_encode_om_uint32 (b->acceptor_address.length, num); EVP_DigestUpdate(ctx, num, sizeof(num)); if (b->acceptor_address.length) EVP_DigestUpdate(ctx, b->acceptor_address.value, b->acceptor_address.length); _gsskrb5_encode_om_uint32 (b->application_data.length, num); EVP_DigestUpdate(ctx, num, sizeof(num)); if (b->application_data.length) EVP_DigestUpdate(ctx, b->application_data.value, b->application_data.length); EVP_DigestFinal_ex(ctx, p, NULL); EVP_MD_CTX_destroy(ctx); return 0; } /* * create a checksum over the chanel bindings in * `input_chan_bindings', `flags' and `fwd_data' and return it in * `result' */ OM_uint32 _gsskrb5_create_8003_checksum ( OM_uint32 *minor_status, const gss_channel_bindings_t input_chan_bindings, OM_uint32 flags, const krb5_data *fwd_data, Checksum *result) { u_char *p; /* * see rfc1964 (section 1.1.1 (Initial Token), and the checksum value * field's format) */ result->cksumtype = CKSUMTYPE_GSSAPI; if (fwd_data->length > 0 && (flags & GSS_C_DELEG_FLAG)) result->checksum.length = 24 + 4 + fwd_data->length; else result->checksum.length = 24; result->checksum.data = malloc (result->checksum.length); if (result->checksum.data == NULL) { *minor_status = ENOMEM; return GSS_S_FAILURE; } p = result->checksum.data; _gsskrb5_encode_om_uint32 (16, p); p += 4; if (input_chan_bindings == GSS_C_NO_CHANNEL_BINDINGS) { memset (p, 0, 16); } else { hash_input_chan_bindings (input_chan_bindings, p); } p += 16; _gsskrb5_encode_om_uint32 (flags, p); p += 4; if (fwd_data->length > 0 && (flags & GSS_C_DELEG_FLAG)) { *p++ = (1 >> 0) & 0xFF; /* DlgOpt */ /* == 1 */ *p++ = (1 >> 8) & 0xFF; /* DlgOpt */ /* == 0 */ *p++ = (fwd_data->length >> 0) & 0xFF; /* Dlgth */ *p++ = (fwd_data->length >> 8) & 0xFF; /* Dlgth */ memcpy(p, (unsigned char *) fwd_data->data, fwd_data->length); /* p += fwd_data->length; */ /* commented out to quiet warning */ } return GSS_S_COMPLETE; } /* * verify the checksum in `cksum' over `input_chan_bindings' * returning `flags' and `fwd_data' */ OM_uint32 _gsskrb5_verify_8003_checksum( OM_uint32 *minor_status, const gss_channel_bindings_t input_chan_bindings, const Checksum *cksum, OM_uint32 *flags, krb5_data *fwd_data) { unsigned char hash[16]; unsigned char *p; OM_uint32 length; int DlgOpt; static unsigned char zeros[16]; /* XXX should handle checksums > 24 bytes */ if(cksum->cksumtype != CKSUMTYPE_GSSAPI || cksum->checksum.length < 24) { *minor_status = 0; return GSS_S_BAD_BINDINGS; } p = cksum->checksum.data; _gsskrb5_decode_om_uint32(p, &length); if(length != sizeof(hash)) { *minor_status = 0; return GSS_S_BAD_BINDINGS; } p += 4; if (input_chan_bindings != GSS_C_NO_CHANNEL_BINDINGS && memcmp(p, zeros, sizeof(zeros)) != 0) { if(hash_input_chan_bindings(input_chan_bindings, hash) != 0) { *minor_status = 0; return GSS_S_BAD_BINDINGS; } if(ct_memcmp(hash, p, sizeof(hash)) != 0) { *minor_status = 0; return GSS_S_BAD_BINDINGS; } } p += sizeof(hash); _gsskrb5_decode_om_uint32(p, flags); p += 4; if (cksum->checksum.length > 24 && (*flags & GSS_C_DELEG_FLAG)) { if(cksum->checksum.length < 28) { *minor_status = 0; return GSS_S_BAD_BINDINGS; } DlgOpt = (p[0] << 0) | (p[1] << 8); p += 2; if (DlgOpt != 1) { *minor_status = 0; return GSS_S_BAD_BINDINGS; } fwd_data->length = (p[0] << 0) | (p[1] << 8); p += 2; if(cksum->checksum.length < 28 + fwd_data->length) { *minor_status = 0; return GSS_S_BAD_BINDINGS; } fwd_data->data = malloc(fwd_data->length); if (fwd_data->data == NULL) { *minor_status = ENOMEM; return GSS_S_FAILURE; } memcpy(fwd_data->data, p, fwd_data->length); } return GSS_S_COMPLETE; } heimdal-7.5.0/lib/gssapi/krb5/canonicalize_name.c0000644000175000017500000000421313026237312017753 0ustar niknik/* * Copyright (c) 1997 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "gsskrb5_locl.h" OM_uint32 GSSAPI_CALLCONV _gsskrb5_canonicalize_name ( OM_uint32 * minor_status, gss_const_name_t input_name, const gss_OID mech_type, gss_name_t * output_name ) { krb5_context context; krb5_principal name; OM_uint32 ret; *output_name = NULL; GSSAPI_KRB5_INIT (&context); ret = _gsskrb5_canon_name(minor_status, context, input_name, &name); if (ret) return ret; *output_name = (gss_name_t)name; return GSS_S_COMPLETE; } heimdal-7.5.0/lib/gssapi/krb5/indicate_mechs.c0000644000175000017500000000412512136107747017266 0ustar niknik/* * Copyright (c) 1997 - 2001, 2003 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "gsskrb5_locl.h" OM_uint32 GSSAPI_CALLCONV _gsskrb5_indicate_mechs (OM_uint32 * minor_status, gss_OID_set * mech_set ) { OM_uint32 ret, junk; ret = gss_create_empty_oid_set(minor_status, mech_set); if (ret) return ret; ret = gss_add_oid_set_member(minor_status, GSS_KRB5_MECHANISM, mech_set); if (ret) { gss_release_oid_set(&junk, mech_set); return ret; } *minor_status = 0; return GSS_S_COMPLETE; } heimdal-7.5.0/lib/gssapi/krb5/import_name.c0000644000175000017500000001561513026237312016636 0ustar niknik/* * Copyright (c) 1997 - 2003 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "gsskrb5_locl.h" static OM_uint32 parse_krb5_name (OM_uint32 *minor_status, krb5_context context, const char *name, gss_name_t *output_name) { krb5_principal princ; krb5_error_code kerr; kerr = krb5_parse_name (context, name, &princ); if (kerr == 0) { *output_name = (gss_name_t)princ; return GSS_S_COMPLETE; } *minor_status = kerr; if (kerr == KRB5_PARSE_ILLCHAR || kerr == KRB5_PARSE_MALFORMED) return GSS_S_BAD_NAME; return GSS_S_FAILURE; } static OM_uint32 import_krb5_name (OM_uint32 *minor_status, krb5_context context, const gss_buffer_t input_name_buffer, gss_name_t *output_name) { OM_uint32 ret; char *tmp; tmp = malloc (input_name_buffer->length + 1); if (tmp == NULL) { *minor_status = ENOMEM; return GSS_S_FAILURE; } memcpy (tmp, input_name_buffer->value, input_name_buffer->length); tmp[input_name_buffer->length] = '\0'; ret = parse_krb5_name(minor_status, context, tmp, output_name); free(tmp); return ret; } OM_uint32 _gsskrb5_canon_name(OM_uint32 *minor_status, krb5_context context, gss_const_name_t targetname, krb5_principal *out) { krb5_const_principal p = (krb5_const_principal)targetname; krb5_error_code ret; char *hostname = NULL, *service; int type; const char *comp; *minor_status = 0; /* If its not a hostname */ type = krb5_principal_get_type(context, p); comp = krb5_principal_get_comp_string(context, p, 0); if (type == KRB5_NT_SRV_HST || type == KRB5_NT_SRV_HST_NEEDS_CANON || (type == KRB5_NT_UNKNOWN && comp != NULL && strcmp(comp, "host") == 0)) { if (p->name.name_string.len == 0) return GSS_S_BAD_NAME; else if (p->name.name_string.len > 1) hostname = p->name.name_string.val[1]; service = p->name.name_string.val[0]; ret = krb5_sname_to_principal(context, hostname, service, KRB5_NT_SRV_HST, out); } else { ret = krb5_copy_principal(context, p, out); } if (ret) { *minor_status = ret; return GSS_S_FAILURE; } return 0; } static OM_uint32 import_hostbased_name(OM_uint32 *minor_status, krb5_context context, const gss_buffer_t input_name_buffer, gss_name_t *output_name) { krb5_principal princ = NULL; krb5_error_code kerr; char *tmp, *p, *host = NULL; tmp = malloc (input_name_buffer->length + 1); if (tmp == NULL) { *minor_status = ENOMEM; return GSS_S_FAILURE; } memcpy (tmp, input_name_buffer->value, input_name_buffer->length); tmp[input_name_buffer->length] = '\0'; p = strchr (tmp, '@'); if (p != NULL) { *p = '\0'; host = p + 1; } kerr = krb5_make_principal(context, &princ, "", tmp, host, NULL); free (tmp); *minor_status = kerr; if (kerr == KRB5_PARSE_ILLCHAR || kerr == KRB5_PARSE_MALFORMED) return GSS_S_BAD_NAME; else if (kerr) return GSS_S_FAILURE; krb5_principal_set_type(context, princ, KRB5_NT_SRV_HST); *output_name = (gss_name_t)princ; return 0; } static OM_uint32 import_export_name (OM_uint32 *minor_status, krb5_context context, const gss_buffer_t input_name_buffer, gss_name_t *output_name) { unsigned char *p; uint32_t length; OM_uint32 ret; char *name; if (input_name_buffer->length < 10 + GSS_KRB5_MECHANISM->length) return GSS_S_BAD_NAME; /* TOK, MECH_OID_LEN, DER(MECH_OID), NAME_LEN, NAME */ p = input_name_buffer->value; if (memcmp(&p[0], "\x04\x01\x00", 3) != 0 || p[3] != GSS_KRB5_MECHANISM->length + 2 || p[4] != 0x06 || p[5] != GSS_KRB5_MECHANISM->length || memcmp(&p[6], GSS_KRB5_MECHANISM->elements, GSS_KRB5_MECHANISM->length) != 0) return GSS_S_BAD_NAME; p += 6 + GSS_KRB5_MECHANISM->length; length = p[0] << 24 | p[1] << 16 | p[2] << 8 | p[3]; p += 4; if (length > input_name_buffer->length - 10 - GSS_KRB5_MECHANISM->length) return GSS_S_BAD_NAME; name = malloc(length + 1); if (name == NULL) { *minor_status = ENOMEM; return GSS_S_FAILURE; } memcpy(name, p, length); name[length] = '\0'; ret = parse_krb5_name(minor_status, context, name, output_name); free(name); return ret; } OM_uint32 GSSAPI_CALLCONV _gsskrb5_import_name (OM_uint32 * minor_status, const gss_buffer_t input_name_buffer, const gss_OID input_name_type, gss_name_t * output_name ) { krb5_context context; *minor_status = 0; *output_name = GSS_C_NO_NAME; GSSAPI_KRB5_INIT (&context); if (gss_oid_equal(input_name_type, GSS_C_NT_HOSTBASED_SERVICE) || gss_oid_equal(input_name_type, GSS_C_NT_HOSTBASED_SERVICE_X)) return import_hostbased_name (minor_status, context, input_name_buffer, output_name); else if (input_name_type == GSS_C_NO_OID || gss_oid_equal(input_name_type, GSS_C_NT_USER_NAME) || gss_oid_equal(input_name_type, GSS_KRB5_NT_PRINCIPAL_NAME)) /* default printable syntax */ return import_krb5_name (minor_status, context, input_name_buffer, output_name); else if (gss_oid_equal(input_name_type, GSS_C_NT_EXPORT_NAME)) { return import_export_name(minor_status, context, input_name_buffer, output_name); } else { *minor_status = 0; return GSS_S_BAD_NAMETYPE; } } heimdal-7.5.0/lib/gssapi/krb5/ticket_flags.c0000644000175000017500000000422612136107747016770 0ustar niknik/* * Copyright (c) 2004 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "gsskrb5_locl.h" OM_uint32 _gsskrb5_get_tkt_flags(OM_uint32 *minor_status, gsskrb5_ctx ctx, OM_uint32 *tkt_flags) { if (ctx == NULL) { *minor_status = EINVAL; return GSS_S_NO_CONTEXT; } HEIMDAL_MUTEX_lock(&ctx->ctx_id_mutex); if (ctx->ticket == NULL) { HEIMDAL_MUTEX_unlock(&ctx->ctx_id_mutex); *minor_status = EINVAL; return GSS_S_BAD_MECH; } *tkt_flags = TicketFlags2int(ctx->ticket->ticket.flags); HEIMDAL_MUTEX_unlock(&ctx->ctx_id_mutex); *minor_status = 0; return GSS_S_COMPLETE; } heimdal-7.5.0/lib/gssapi/krb5/ccache_name.c0000644000175000017500000000461212136107747016536 0ustar niknik/* * Copyright (c) 2004 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "gsskrb5_locl.h" char *last_out_name; OM_uint32 _gsskrb5_krb5_ccache_name(OM_uint32 *minor_status, const char *name, const char **out_name) { krb5_context context; krb5_error_code kret; *minor_status = 0; GSSAPI_KRB5_INIT(&context); if (out_name) { const char *n; if (last_out_name) { free(last_out_name); last_out_name = NULL; } n = krb5_cc_default_name(context); if (n == NULL) { *minor_status = ENOMEM; return GSS_S_FAILURE; } last_out_name = strdup(n); if (last_out_name == NULL) { *minor_status = ENOMEM; return GSS_S_FAILURE; } *out_name = last_out_name; } kret = krb5_cc_set_default_name(context, name); if (kret) { *minor_status = kret; return GSS_S_FAILURE; } return GSS_S_COMPLETE; } heimdal-7.5.0/lib/gssapi/krb5/init.c0000644000175000017500000000503712136107747015275 0ustar niknik/* * Copyright (c) 1997 - 2001, 2003, 2006 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "gsskrb5_locl.h" static HEIMDAL_MUTEX context_mutex = HEIMDAL_MUTEX_INITIALIZER; static int created_key; static HEIMDAL_thread_key context_key; static void destroy_context(void *ptr) { krb5_context context = ptr; if (context == NULL) return; krb5_free_context(context); } krb5_error_code _gsskrb5_init (krb5_context *context) { krb5_error_code ret = 0; HEIMDAL_MUTEX_lock(&context_mutex); if (!created_key) { HEIMDAL_key_create(&context_key, destroy_context, ret); if (ret) { HEIMDAL_MUTEX_unlock(&context_mutex); return ret; } created_key = 1; } HEIMDAL_MUTEX_unlock(&context_mutex); *context = HEIMDAL_getspecific(context_key); if (*context == NULL) { ret = krb5_init_context(context); if (ret == 0) { HEIMDAL_setspecific(context_key, *context, ret); if (ret) { krb5_free_context(*context); *context = NULL; } } } return ret; } heimdal-7.5.0/lib/gssapi/krb5/sequence.c0000644000175000017500000001564513026237312016137 0ustar niknik/* * Copyright (c) 2003 - 2006 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "gsskrb5_locl.h" #define DEFAULT_JITTER_WINDOW 20 struct gss_msg_order { OM_uint32 flags; OM_uint32 start; OM_uint32 length; OM_uint32 jitter_window; OM_uint32 first_seq; OM_uint32 elem[1]; }; /* * */ static OM_uint32 msg_order_alloc(OM_uint32 *minor_status, struct gss_msg_order **o, OM_uint32 jitter_window) { size_t len; len = jitter_window * sizeof((*o)->elem[0]); len += sizeof(**o); len -= sizeof((*o)->elem[0]); *o = calloc(1, len); if (*o == NULL) { *minor_status = ENOMEM; return GSS_S_FAILURE; } *minor_status = 0; return GSS_S_COMPLETE; } /* * */ OM_uint32 _gssapi_msg_order_create(OM_uint32 *minor_status, struct gss_msg_order **o, OM_uint32 flags, OM_uint32 seq_num, OM_uint32 jitter_window, int use_64) { OM_uint32 ret; if (jitter_window == 0) jitter_window = DEFAULT_JITTER_WINDOW; ret = msg_order_alloc(minor_status, o, jitter_window); if(ret != GSS_S_COMPLETE) return ret; (*o)->flags = flags; (*o)->length = 0; (*o)->first_seq = seq_num; (*o)->jitter_window = jitter_window; (*o)->elem[0] = seq_num - 1; *minor_status = 0; return GSS_S_COMPLETE; } OM_uint32 _gssapi_msg_order_destroy(struct gss_msg_order **m) { free(*m); *m = NULL; return GSS_S_COMPLETE; } static void elem_set(struct gss_msg_order *o, unsigned int slot, OM_uint32 val) { o->elem[slot % o->jitter_window] = val; } static void elem_insert(struct gss_msg_order *o, unsigned int after_slot, OM_uint32 seq_num) { assert(o->jitter_window > after_slot); if (o->length > after_slot) memmove(&o->elem[after_slot + 1], &o->elem[after_slot], (o->length - after_slot - 1) * sizeof(o->elem[0])); elem_set(o, after_slot, seq_num); if (o->length < o->jitter_window) o->length++; } /* rule 1: expected sequence number */ /* rule 2: > expected sequence number */ /* rule 3: seqnum < seqnum(first) */ /* rule 4+5: seqnum in [seqnum(first),seqnum(last)] */ OM_uint32 _gssapi_msg_order_check(struct gss_msg_order *o, OM_uint32 seq_num) { OM_uint32 r; size_t i; if (o == NULL) return GSS_S_COMPLETE; if ((o->flags & (GSS_C_REPLAY_FLAG|GSS_C_SEQUENCE_FLAG)) == 0) return GSS_S_COMPLETE; /* check if the packet is the next in order */ if (o->elem[0] == seq_num - 1) { elem_insert(o, 0, seq_num); return GSS_S_COMPLETE; } r = (o->flags & (GSS_C_REPLAY_FLAG|GSS_C_SEQUENCE_FLAG))==GSS_C_REPLAY_FLAG; /* sequence number larger then largest sequence number * or smaller then the first sequence number */ if (seq_num > o->elem[0] || seq_num < o->first_seq || o->length == 0) { elem_insert(o, 0, seq_num); if (r) { return GSS_S_COMPLETE; } else { return GSS_S_GAP_TOKEN; } } assert(o->length > 0); /* sequence number smaller the first sequence number */ if (seq_num < o->elem[o->length - 1]) { if (r) return(GSS_S_OLD_TOKEN); else return(GSS_S_UNSEQ_TOKEN); } if (seq_num == o->elem[o->length - 1]) { return GSS_S_DUPLICATE_TOKEN; } for (i = 0; i < o->length - 1; i++) { if (o->elem[i] == seq_num) return GSS_S_DUPLICATE_TOKEN; if (o->elem[i + 1] < seq_num && o->elem[i] < seq_num) { elem_insert(o, i, seq_num); if (r) return GSS_S_COMPLETE; else return GSS_S_UNSEQ_TOKEN; } } return GSS_S_FAILURE; } OM_uint32 _gssapi_msg_order_f(OM_uint32 flags) { return flags & (GSS_C_SEQUENCE_FLAG|GSS_C_REPLAY_FLAG); } /* * Translate `o` into inter-process format and export in to `sp'. */ krb5_error_code _gssapi_msg_order_export(krb5_storage *sp, struct gss_msg_order *o) { krb5_error_code kret; OM_uint32 i; kret = krb5_store_int32(sp, o->flags); if (kret) return kret; kret = krb5_store_int32(sp, o->start); if (kret) return kret; kret = krb5_store_int32(sp, o->length); if (kret) return kret; kret = krb5_store_int32(sp, o->jitter_window); if (kret) return kret; kret = krb5_store_int32(sp, o->first_seq); if (kret) return kret; for (i = 0; i < o->jitter_window; i++) { kret = krb5_store_int32(sp, o->elem[i]); if (kret) return kret; } return 0; } OM_uint32 _gssapi_msg_order_import(OM_uint32 *minor_status, krb5_storage *sp, struct gss_msg_order **o) { OM_uint32 ret; krb5_error_code kret; int32_t i, flags, start, length, jitter_window, first_seq; kret = krb5_ret_int32(sp, &flags); if (kret) goto failed; kret = krb5_ret_int32(sp, &start); if (kret) goto failed; kret = krb5_ret_int32(sp, &length); if (kret) goto failed; kret = krb5_ret_int32(sp, &jitter_window); if (kret) goto failed; kret = krb5_ret_int32(sp, &first_seq); if (kret) goto failed; ret = msg_order_alloc(minor_status, o, jitter_window); if (ret != GSS_S_COMPLETE) return ret; (*o)->flags = flags; (*o)->start = start; (*o)->length = length; (*o)->jitter_window = jitter_window; (*o)->first_seq = first_seq; for( i = 0; i < jitter_window; i++ ) { kret = krb5_ret_int32(sp, (int32_t*)&((*o)->elem[i])); if (kret) goto failed; } *minor_status = 0; return GSS_S_COMPLETE; failed: _gssapi_msg_order_destroy(o); *minor_status = kret; return GSS_S_FAILURE; } heimdal-7.5.0/lib/gssapi/krb5/cfx.c0000644000175000017500000013110613026237312015076 0ustar niknik/* * Copyright (c) 2003, PADL Software Pty Ltd. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of PADL Software nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY PADL SOFTWARE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL PADL SOFTWARE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "gsskrb5_locl.h" /* * Implementation of RFC 4121 */ #define CFXSentByAcceptor (1 << 0) #define CFXSealed (1 << 1) #define CFXAcceptorSubkey (1 << 2) krb5_error_code _gsskrb5cfx_wrap_length_cfx(krb5_context context, krb5_crypto crypto, int conf_req_flag, int dce_style, size_t input_length, size_t *output_length, size_t *cksumsize, uint16_t *padlength) { krb5_error_code ret; krb5_cksumtype type; /* 16-byte header is always first */ *output_length = sizeof(gss_cfx_wrap_token_desc); *padlength = 0; ret = krb5_crypto_get_checksum_type(context, crypto, &type); if (ret) return ret; ret = krb5_checksumsize(context, type, cksumsize); if (ret) return ret; if (conf_req_flag) { size_t padsize; /* Header is concatenated with data before encryption */ input_length += sizeof(gss_cfx_wrap_token_desc); if (dce_style) { ret = krb5_crypto_getblocksize(context, crypto, &padsize); } else { ret = krb5_crypto_getpadsize(context, crypto, &padsize); } if (ret) { return ret; } if (padsize > 1) { /* XXX check this */ *padlength = padsize - (input_length % padsize); /* We add the pad ourselves (noted here for completeness only) */ input_length += *padlength; } *output_length += krb5_get_wrapped_length(context, crypto, input_length); } else { /* Checksum is concatenated with data */ *output_length += input_length + *cksumsize; } assert(*output_length > input_length); return 0; } OM_uint32 _gssapi_wrap_size_cfx(OM_uint32 *minor_status, const gsskrb5_ctx ctx, krb5_context context, int conf_req_flag, gss_qop_t qop_req, OM_uint32 req_output_size, OM_uint32 *max_input_size) { krb5_error_code ret; *max_input_size = 0; /* 16-byte header is always first */ if (req_output_size < 16) return 0; req_output_size -= 16; if (conf_req_flag) { size_t wrapped_size, sz; wrapped_size = req_output_size + 1; do { wrapped_size--; sz = krb5_get_wrapped_length(context, ctx->crypto, wrapped_size); } while (wrapped_size && sz > req_output_size); if (wrapped_size == 0) return 0; /* inner header */ if (wrapped_size < 16) return 0; wrapped_size -= 16; *max_input_size = wrapped_size; } else { krb5_cksumtype type; size_t cksumsize; ret = krb5_crypto_get_checksum_type(context, ctx->crypto, &type); if (ret) return ret; ret = krb5_checksumsize(context, type, &cksumsize); if (ret) return ret; if (req_output_size < cksumsize) return 0; /* Checksum is concatenated with data */ *max_input_size = req_output_size - cksumsize; } return 0; } /* * Rotate "rrc" bytes to the front or back */ static krb5_error_code rrc_rotate(void *data, size_t len, uint16_t rrc, krb5_boolean unrotate) { u_char *tmp, buf[256]; size_t left; if (len == 0) return 0; rrc %= len; if (rrc == 0) return 0; left = len - rrc; if (rrc <= sizeof(buf)) { tmp = buf; } else { tmp = malloc(rrc); if (tmp == NULL) return ENOMEM; } if (unrotate) { memcpy(tmp, data, rrc); memmove(data, (u_char *)data + rrc, left); memcpy((u_char *)data + left, tmp, rrc); } else { memcpy(tmp, (u_char *)data + left, rrc); memmove((u_char *)data + rrc, data, left); memcpy(data, tmp, rrc); } if (rrc > sizeof(buf)) free(tmp); return 0; } gss_iov_buffer_desc * _gk_find_buffer(gss_iov_buffer_desc *iov, int iov_count, OM_uint32 type) { int i; for (i = 0; i < iov_count; i++) if (type == GSS_IOV_BUFFER_TYPE(iov[i].type)) return &iov[i]; return NULL; } OM_uint32 _gk_allocate_buffer(OM_uint32 *minor_status, gss_iov_buffer_desc *buffer, size_t size) { if (buffer->type & GSS_IOV_BUFFER_FLAG_ALLOCATED) { if (buffer->buffer.length == size) return GSS_S_COMPLETE; free(buffer->buffer.value); } buffer->buffer.value = malloc(size); buffer->buffer.length = size; if (buffer->buffer.value == NULL) { *minor_status = ENOMEM; return GSS_S_FAILURE; } buffer->type |= GSS_IOV_BUFFER_FLAG_ALLOCATED; return GSS_S_COMPLETE; } OM_uint32 _gk_verify_buffers(OM_uint32 *minor_status, const gsskrb5_ctx ctx, const gss_iov_buffer_desc *header, const gss_iov_buffer_desc *padding, const gss_iov_buffer_desc *trailer) { if (header == NULL) { *minor_status = EINVAL; return GSS_S_FAILURE; } if (IS_DCE_STYLE(ctx)) { /* * In DCE style mode we reject having a padding or trailer buffer */ if (padding) { *minor_status = EINVAL; return GSS_S_FAILURE; } if (trailer) { *minor_status = EINVAL; return GSS_S_FAILURE; } } else { /* * In non-DCE style mode we require having a padding buffer */ if (padding == NULL) { *minor_status = EINVAL; return GSS_S_FAILURE; } } *minor_status = 0; return GSS_S_COMPLETE; } OM_uint32 _gssapi_wrap_cfx_iov(OM_uint32 *minor_status, gsskrb5_ctx ctx, krb5_context context, int conf_req_flag, int *conf_state, gss_iov_buffer_desc *iov, int iov_count) { OM_uint32 major_status, junk; gss_iov_buffer_desc *header, *trailer, *padding; size_t gsshsize, k5hsize; size_t gsstsize, k5tsize; size_t rrc = 0, ec = 0; int i; gss_cfx_wrap_token token; krb5_error_code ret; int32_t seq_number; unsigned usage; krb5_crypto_iov *data = NULL; header = _gk_find_buffer(iov, iov_count, GSS_IOV_BUFFER_TYPE_HEADER); if (header == NULL) { *minor_status = EINVAL; return GSS_S_FAILURE; } padding = _gk_find_buffer(iov, iov_count, GSS_IOV_BUFFER_TYPE_PADDING); if (padding != NULL) { padding->buffer.length = 0; } trailer = _gk_find_buffer(iov, iov_count, GSS_IOV_BUFFER_TYPE_TRAILER); major_status = _gk_verify_buffers(minor_status, ctx, header, padding, trailer); if (major_status != GSS_S_COMPLETE) { return major_status; } if (conf_req_flag) { size_t k5psize = 0; size_t k5pbase = 0; size_t k5bsize = 0; size_t size = 0; for (i = 0; i < iov_count; i++) { switch (GSS_IOV_BUFFER_TYPE(iov[i].type)) { case GSS_IOV_BUFFER_TYPE_DATA: size += iov[i].buffer.length; break; default: break; } } size += sizeof(gss_cfx_wrap_token_desc); *minor_status = krb5_crypto_length(context, ctx->crypto, KRB5_CRYPTO_TYPE_HEADER, &k5hsize); if (*minor_status) return GSS_S_FAILURE; *minor_status = krb5_crypto_length(context, ctx->crypto, KRB5_CRYPTO_TYPE_TRAILER, &k5tsize); if (*minor_status) return GSS_S_FAILURE; *minor_status = krb5_crypto_length(context, ctx->crypto, KRB5_CRYPTO_TYPE_PADDING, &k5pbase); if (*minor_status) return GSS_S_FAILURE; if (k5pbase > 1) { k5psize = k5pbase - (size % k5pbase); } else { k5psize = 0; } if (k5psize == 0 && IS_DCE_STYLE(ctx)) { *minor_status = krb5_crypto_getblocksize(context, ctx->crypto, &k5bsize); if (*minor_status) return GSS_S_FAILURE; ec = k5bsize; } else { ec = k5psize; } gsshsize = sizeof(gss_cfx_wrap_token_desc) + k5hsize; gsstsize = sizeof(gss_cfx_wrap_token_desc) + ec + k5tsize; } else { if (IS_DCE_STYLE(ctx)) { *minor_status = EINVAL; return GSS_S_FAILURE; } k5hsize = 0; *minor_status = krb5_crypto_length(context, ctx->crypto, KRB5_CRYPTO_TYPE_CHECKSUM, &k5tsize); if (*minor_status) return GSS_S_FAILURE; gsshsize = sizeof(gss_cfx_wrap_token_desc); gsstsize = k5tsize; } /* * */ if (trailer == NULL) { rrc = gsstsize; if (IS_DCE_STYLE(ctx)) rrc -= ec; gsshsize += gsstsize; } else if (GSS_IOV_BUFFER_FLAGS(trailer->type) & GSS_IOV_BUFFER_FLAG_ALLOCATE) { major_status = _gk_allocate_buffer(minor_status, trailer, gsstsize); if (major_status) goto failure; } else if (trailer->buffer.length < gsstsize) { *minor_status = KRB5_BAD_MSIZE; major_status = GSS_S_FAILURE; goto failure; } else trailer->buffer.length = gsstsize; /* * */ if (GSS_IOV_BUFFER_FLAGS(header->type) & GSS_IOV_BUFFER_FLAG_ALLOCATE) { major_status = _gk_allocate_buffer(minor_status, header, gsshsize); if (major_status != GSS_S_COMPLETE) goto failure; } else if (header->buffer.length < gsshsize) { *minor_status = KRB5_BAD_MSIZE; major_status = GSS_S_FAILURE; goto failure; } else header->buffer.length = gsshsize; token = (gss_cfx_wrap_token)header->buffer.value; token->TOK_ID[0] = 0x05; token->TOK_ID[1] = 0x04; token->Flags = 0; token->Filler = 0xFF; if ((ctx->more_flags & LOCAL) == 0) token->Flags |= CFXSentByAcceptor; if (ctx->more_flags & ACCEPTOR_SUBKEY) token->Flags |= CFXAcceptorSubkey; if (ctx->more_flags & LOCAL) usage = KRB5_KU_USAGE_INITIATOR_SEAL; else usage = KRB5_KU_USAGE_ACCEPTOR_SEAL; if (conf_req_flag) { /* * In Wrap tokens with confidentiality, the EC field is * used to encode the size (in bytes) of the random filler. */ token->Flags |= CFXSealed; token->EC[0] = (ec >> 8) & 0xFF; token->EC[1] = (ec >> 0) & 0xFF; } else { /* * In Wrap tokens without confidentiality, the EC field is * used to encode the size (in bytes) of the trailing * checksum. * * This is not used in the checksum calcuation itself, * because the checksum length could potentially vary * depending on the data length. */ token->EC[0] = 0; token->EC[1] = 0; } /* * In Wrap tokens that provide for confidentiality, the RRC * field in the header contains the hex value 00 00 before * encryption. * * In Wrap tokens that do not provide for confidentiality, * both the EC and RRC fields in the appended checksum * contain the hex value 00 00 for the purpose of calculating * the checksum. */ token->RRC[0] = 0; token->RRC[1] = 0; HEIMDAL_MUTEX_lock(&ctx->ctx_id_mutex); krb5_auth_con_getlocalseqnumber(context, ctx->auth_context, &seq_number); _gsskrb5_encode_be_om_uint32(0, &token->SND_SEQ[0]); _gsskrb5_encode_be_om_uint32(seq_number, &token->SND_SEQ[4]); krb5_auth_con_setlocalseqnumber(context, ctx->auth_context, ++seq_number); HEIMDAL_MUTEX_unlock(&ctx->ctx_id_mutex); data = calloc(iov_count + 3, sizeof(data[0])); if (data == NULL) { *minor_status = ENOMEM; major_status = GSS_S_FAILURE; goto failure; } if (conf_req_flag) { /* plain packet: {"header" | encrypt(plaintext-data | ec-padding | E"header")} Expanded, this is with with RRC = 0: {"header" | krb5-header | plaintext-data | ec-padding | E"header" | krb5-trailer } In DCE-RPC mode == no trailer: RRC = gss "trailer" == length(ec-padding | E"header" | krb5-trailer) {"header" | ec-padding | E"header" | krb5-trailer | krb5-header | plaintext-data } */ i = 0; data[i].flags = KRB5_CRYPTO_TYPE_HEADER; data[i].data.data = ((uint8_t *)header->buffer.value) + header->buffer.length - k5hsize; data[i].data.length = k5hsize; for (i = 1; i < iov_count + 1; i++) { switch (GSS_IOV_BUFFER_TYPE(iov[i - 1].type)) { case GSS_IOV_BUFFER_TYPE_DATA: data[i].flags = KRB5_CRYPTO_TYPE_DATA; break; case GSS_IOV_BUFFER_TYPE_SIGN_ONLY: data[i].flags = KRB5_CRYPTO_TYPE_SIGN_ONLY; break; default: data[i].flags = KRB5_CRYPTO_TYPE_EMPTY; break; } data[i].data.length = iov[i - 1].buffer.length; data[i].data.data = iov[i - 1].buffer.value; } /* * Any necessary padding is added here to ensure that the * encrypted token header is always at the end of the * ciphertext. */ /* encrypted CFX header in trailer (or after the header if in DCE mode). Copy in header into E"header" */ data[i].flags = KRB5_CRYPTO_TYPE_DATA; if (trailer) data[i].data.data = trailer->buffer.value; else data[i].data.data = ((uint8_t *)header->buffer.value) + sizeof(*token); data[i].data.length = ec + sizeof(*token); memset(data[i].data.data, 0xFF, ec); memcpy(((uint8_t *)data[i].data.data) + ec, token, sizeof(*token)); i++; /* Kerberos trailer comes after the gss trailer */ data[i].flags = KRB5_CRYPTO_TYPE_TRAILER; data[i].data.data = ((uint8_t *)data[i-1].data.data) + ec + sizeof(*token); data[i].data.length = k5tsize; i++; ret = krb5_encrypt_iov_ivec(context, ctx->crypto, usage, data, i, NULL); if (ret != 0) { *minor_status = ret; major_status = GSS_S_FAILURE; goto failure; } if (rrc) { token->RRC[0] = (rrc >> 8) & 0xFF; token->RRC[1] = (rrc >> 0) & 0xFF; } } else { /* plain packet: {data | "header" | gss-trailer (krb5 checksum) don't do RRC != 0 */ for (i = 0; i < iov_count; i++) { switch (GSS_IOV_BUFFER_TYPE(iov[i].type)) { case GSS_IOV_BUFFER_TYPE_DATA: data[i].flags = KRB5_CRYPTO_TYPE_DATA; break; case GSS_IOV_BUFFER_TYPE_SIGN_ONLY: data[i].flags = KRB5_CRYPTO_TYPE_SIGN_ONLY; break; default: data[i].flags = KRB5_CRYPTO_TYPE_EMPTY; break; } data[i].data.length = iov[i].buffer.length; data[i].data.data = iov[i].buffer.value; } data[i].flags = KRB5_CRYPTO_TYPE_DATA; data[i].data.data = header->buffer.value; data[i].data.length = sizeof(gss_cfx_wrap_token_desc); i++; data[i].flags = KRB5_CRYPTO_TYPE_CHECKSUM; if (trailer) { data[i].data.data = trailer->buffer.value; } else { data[i].data.data = (uint8_t *)header->buffer.value + sizeof(gss_cfx_wrap_token_desc); } data[i].data.length = k5tsize; i++; ret = krb5_create_checksum_iov(context, ctx->crypto, usage, data, i, NULL); if (ret) { *minor_status = ret; major_status = GSS_S_FAILURE; goto failure; } if (rrc) { token->RRC[0] = (rrc >> 8) & 0xFF; token->RRC[1] = (rrc >> 0) & 0xFF; } token->EC[0] = (k5tsize >> 8) & 0xFF; token->EC[1] = (k5tsize >> 0) & 0xFF; } if (conf_state != NULL) *conf_state = conf_req_flag; free(data); *minor_status = 0; return GSS_S_COMPLETE; failure: if (data) free(data); gss_release_iov_buffer(&junk, iov, iov_count); return major_status; } /* This is slowpath */ static OM_uint32 unrotate_iov(OM_uint32 *minor_status, size_t rrc, gss_iov_buffer_desc *iov, int iov_count) { uint8_t *p, *q; size_t len = 0, skip; int i; for (i = 0; i < iov_count; i++) if (GSS_IOV_BUFFER_TYPE(iov[i].type) == GSS_IOV_BUFFER_TYPE_DATA || GSS_IOV_BUFFER_TYPE(iov[i].type) == GSS_IOV_BUFFER_TYPE_PADDING || GSS_IOV_BUFFER_TYPE(iov[i].type) == GSS_IOV_BUFFER_TYPE_TRAILER) len += iov[i].buffer.length; p = malloc(len); if (p == NULL) { *minor_status = ENOMEM; return GSS_S_FAILURE; } q = p; /* copy up */ for (i = 0; i < iov_count; i++) { if (GSS_IOV_BUFFER_TYPE(iov[i].type) == GSS_IOV_BUFFER_TYPE_DATA || GSS_IOV_BUFFER_TYPE(iov[i].type) == GSS_IOV_BUFFER_TYPE_PADDING || GSS_IOV_BUFFER_TYPE(iov[i].type) == GSS_IOV_BUFFER_TYPE_TRAILER) { memcpy(q, iov[i].buffer.value, iov[i].buffer.length); q += iov[i].buffer.length; } } assert((size_t)(q - p) == len); /* unrotate first part */ q = p + rrc; skip = rrc; for (i = 0; i < iov_count; i++) { if (GSS_IOV_BUFFER_TYPE(iov[i].type) == GSS_IOV_BUFFER_TYPE_DATA || GSS_IOV_BUFFER_TYPE(iov[i].type) == GSS_IOV_BUFFER_TYPE_PADDING || GSS_IOV_BUFFER_TYPE(iov[i].type) == GSS_IOV_BUFFER_TYPE_TRAILER) { if (iov[i].buffer.length <= skip) { skip -= iov[i].buffer.length; } else { /* copy back to original buffer */ memcpy(((uint8_t *)iov[i].buffer.value) + skip, q, iov[i].buffer.length - skip); q += iov[i].buffer.length - skip; skip = 0; } } } /* copy trailer */ q = p; skip = rrc; for (i = 0; i < iov_count; i++) { if (GSS_IOV_BUFFER_TYPE(iov[i].type) == GSS_IOV_BUFFER_TYPE_DATA || GSS_IOV_BUFFER_TYPE(iov[i].type) == GSS_IOV_BUFFER_TYPE_PADDING || GSS_IOV_BUFFER_TYPE(iov[i].type) == GSS_IOV_BUFFER_TYPE_TRAILER) { memcpy(iov[i].buffer.value, q, min(iov[i].buffer.length, skip)); if (iov[i].buffer.length > skip) break; skip -= iov[i].buffer.length; q += iov[i].buffer.length; } } free(p); return GSS_S_COMPLETE; } OM_uint32 _gssapi_unwrap_cfx_iov(OM_uint32 *minor_status, gsskrb5_ctx ctx, krb5_context context, int *conf_state, gss_qop_t *qop_state, gss_iov_buffer_desc *iov, int iov_count) { OM_uint32 seq_number_lo, seq_number_hi, major_status, junk; gss_iov_buffer_desc *header, *trailer, *padding; gss_cfx_wrap_token token, ttoken; u_char token_flags; krb5_error_code ret; unsigned usage; uint16_t ec, rrc; krb5_crypto_iov *data = NULL; int i, j; *minor_status = 0; header = _gk_find_buffer(iov, iov_count, GSS_IOV_BUFFER_TYPE_HEADER); if (header == NULL) { *minor_status = EINVAL; return GSS_S_FAILURE; } if (header->buffer.length < sizeof(*token)) /* we check exact below */ return GSS_S_DEFECTIVE_TOKEN; padding = _gk_find_buffer(iov, iov_count, GSS_IOV_BUFFER_TYPE_PADDING); if (padding != NULL && padding->buffer.length != 0) { *minor_status = EINVAL; return GSS_S_FAILURE; } trailer = _gk_find_buffer(iov, iov_count, GSS_IOV_BUFFER_TYPE_TRAILER); major_status = _gk_verify_buffers(minor_status, ctx, header, padding, trailer); if (major_status != GSS_S_COMPLETE) { return major_status; } token = (gss_cfx_wrap_token)header->buffer.value; if (token->TOK_ID[0] != 0x05 || token->TOK_ID[1] != 0x04) return GSS_S_DEFECTIVE_TOKEN; /* Ignore unknown flags */ token_flags = token->Flags & (CFXSentByAcceptor | CFXSealed | CFXAcceptorSubkey); if (token_flags & CFXSentByAcceptor) { if ((ctx->more_flags & LOCAL) == 0) return GSS_S_DEFECTIVE_TOKEN; } if (ctx->more_flags & ACCEPTOR_SUBKEY) { if ((token_flags & CFXAcceptorSubkey) == 0) return GSS_S_DEFECTIVE_TOKEN; } else { if (token_flags & CFXAcceptorSubkey) return GSS_S_DEFECTIVE_TOKEN; } if (token->Filler != 0xFF) return GSS_S_DEFECTIVE_TOKEN; if (conf_state != NULL) *conf_state = (token_flags & CFXSealed) ? 1 : 0; ec = (token->EC[0] << 8) | token->EC[1]; rrc = (token->RRC[0] << 8) | token->RRC[1]; /* * Check sequence number */ _gsskrb5_decode_be_om_uint32(&token->SND_SEQ[0], &seq_number_hi); _gsskrb5_decode_be_om_uint32(&token->SND_SEQ[4], &seq_number_lo); if (seq_number_hi) { /* no support for 64-bit sequence numbers */ *minor_status = ERANGE; return GSS_S_UNSEQ_TOKEN; } HEIMDAL_MUTEX_lock(&ctx->ctx_id_mutex); ret = _gssapi_msg_order_check(ctx->order, seq_number_lo); if (ret != 0) { *minor_status = 0; HEIMDAL_MUTEX_unlock(&ctx->ctx_id_mutex); return ret; } HEIMDAL_MUTEX_unlock(&ctx->ctx_id_mutex); /* * Decrypt and/or verify checksum */ if (ctx->more_flags & LOCAL) { usage = KRB5_KU_USAGE_ACCEPTOR_SEAL; } else { usage = KRB5_KU_USAGE_INITIATOR_SEAL; } data = calloc(iov_count + 3, sizeof(data[0])); if (data == NULL) { *minor_status = ENOMEM; major_status = GSS_S_FAILURE; goto failure; } if (token_flags & CFXSealed) { size_t k5tsize, k5hsize; krb5_crypto_length(context, ctx->crypto, KRB5_CRYPTO_TYPE_HEADER, &k5hsize); krb5_crypto_length(context, ctx->crypto, KRB5_CRYPTO_TYPE_TRAILER, &k5tsize); /* Rotate by RRC; bogus to do this in-place XXX */ /* Check RRC */ if (trailer == NULL) { size_t gsstsize = k5tsize + sizeof(*token); size_t gsshsize = k5hsize + sizeof(*token); if (rrc != gsstsize) { major_status = GSS_S_DEFECTIVE_TOKEN; goto failure; } if (IS_DCE_STYLE(ctx)) gsstsize += ec; gsshsize += gsstsize; if (header->buffer.length != gsshsize) { major_status = GSS_S_DEFECTIVE_TOKEN; goto failure; } } else if (trailer->buffer.length != sizeof(*token) + k5tsize) { major_status = GSS_S_DEFECTIVE_TOKEN; goto failure; } else if (header->buffer.length != sizeof(*token) + k5hsize) { major_status = GSS_S_DEFECTIVE_TOKEN; goto failure; } else if (rrc != 0) { /* go though slowpath */ major_status = unrotate_iov(minor_status, rrc, iov, iov_count); if (major_status) goto failure; } i = 0; data[i].flags = KRB5_CRYPTO_TYPE_HEADER; data[i].data.data = ((uint8_t *)header->buffer.value) + header->buffer.length - k5hsize; data[i].data.length = k5hsize; i++; for (j = 0; j < iov_count; i++, j++) { switch (GSS_IOV_BUFFER_TYPE(iov[j].type)) { case GSS_IOV_BUFFER_TYPE_DATA: data[i].flags = KRB5_CRYPTO_TYPE_DATA; break; case GSS_IOV_BUFFER_TYPE_SIGN_ONLY: data[i].flags = KRB5_CRYPTO_TYPE_SIGN_ONLY; break; default: data[i].flags = KRB5_CRYPTO_TYPE_EMPTY; break; } data[i].data.length = iov[j].buffer.length; data[i].data.data = iov[j].buffer.value; } /* encrypted CFX header in trailer (or after the header if in DCE mode). Copy in header into E"header" */ data[i].flags = KRB5_CRYPTO_TYPE_DATA; if (trailer) { data[i].data.data = trailer->buffer.value; } else { data[i].data.data = ((uint8_t *)header->buffer.value) + header->buffer.length - k5hsize - k5tsize - ec- sizeof(*token); } data[i].data.length = ec + sizeof(*token); ttoken = (gss_cfx_wrap_token)(((uint8_t *)data[i].data.data) + ec); i++; /* Kerberos trailer comes after the gss trailer */ data[i].flags = KRB5_CRYPTO_TYPE_TRAILER; data[i].data.data = ((uint8_t *)data[i-1].data.data) + ec + sizeof(*token); data[i].data.length = k5tsize; i++; ret = krb5_decrypt_iov_ivec(context, ctx->crypto, usage, data, i, NULL); if (ret != 0) { *minor_status = ret; major_status = GSS_S_FAILURE; goto failure; } ttoken->RRC[0] = token->RRC[0]; ttoken->RRC[1] = token->RRC[1]; /* Check the integrity of the header */ if (ct_memcmp(ttoken, token, sizeof(*token)) != 0) { major_status = GSS_S_BAD_MIC; goto failure; } } else { size_t gsstsize = ec; size_t gsshsize = sizeof(*token); if (trailer == NULL) { /* Check RRC */ if (rrc != gsstsize) { *minor_status = EINVAL; major_status = GSS_S_FAILURE; goto failure; } gsshsize += gsstsize; } else if (trailer->buffer.length != gsstsize) { major_status = GSS_S_DEFECTIVE_TOKEN; goto failure; } else if (rrc != 0) { /* Check RRC */ *minor_status = EINVAL; major_status = GSS_S_FAILURE; goto failure; } if (header->buffer.length != gsshsize) { major_status = GSS_S_DEFECTIVE_TOKEN; goto failure; } for (i = 0; i < iov_count; i++) { switch (GSS_IOV_BUFFER_TYPE(iov[i].type)) { case GSS_IOV_BUFFER_TYPE_DATA: data[i].flags = KRB5_CRYPTO_TYPE_DATA; break; case GSS_IOV_BUFFER_TYPE_SIGN_ONLY: data[i].flags = KRB5_CRYPTO_TYPE_SIGN_ONLY; break; default: data[i].flags = KRB5_CRYPTO_TYPE_EMPTY; break; } data[i].data.length = iov[i].buffer.length; data[i].data.data = iov[i].buffer.value; } data[i].flags = KRB5_CRYPTO_TYPE_DATA; data[i].data.data = header->buffer.value; data[i].data.length = sizeof(*token); i++; data[i].flags = KRB5_CRYPTO_TYPE_CHECKSUM; if (trailer) { data[i].data.data = trailer->buffer.value; } else { data[i].data.data = (uint8_t *)header->buffer.value + sizeof(*token); } data[i].data.length = ec; i++; token = (gss_cfx_wrap_token)header->buffer.value; token->EC[0] = 0; token->EC[1] = 0; token->RRC[0] = 0; token->RRC[1] = 0; ret = krb5_verify_checksum_iov(context, ctx->crypto, usage, data, i, NULL); if (ret) { *minor_status = ret; major_status = GSS_S_FAILURE; goto failure; } } if (qop_state != NULL) { *qop_state = GSS_C_QOP_DEFAULT; } free(data); *minor_status = 0; return GSS_S_COMPLETE; failure: if (data) free(data); gss_release_iov_buffer(&junk, iov, iov_count); return major_status; } OM_uint32 _gssapi_wrap_iov_length_cfx(OM_uint32 *minor_status, gsskrb5_ctx ctx, krb5_context context, int conf_req_flag, gss_qop_t qop_req, int *conf_state, gss_iov_buffer_desc *iov, int iov_count) { OM_uint32 major_status; size_t size; int i; gss_iov_buffer_desc *header = NULL; gss_iov_buffer_desc *padding = NULL; gss_iov_buffer_desc *trailer = NULL; size_t gsshsize = 0; size_t gsstsize = 0; size_t k5hsize = 0; size_t k5tsize = 0; GSSAPI_KRB5_INIT (&context); *minor_status = 0; for (size = 0, i = 0; i < iov_count; i++) { switch(GSS_IOV_BUFFER_TYPE(iov[i].type)) { case GSS_IOV_BUFFER_TYPE_EMPTY: break; case GSS_IOV_BUFFER_TYPE_DATA: size += iov[i].buffer.length; break; case GSS_IOV_BUFFER_TYPE_HEADER: if (header != NULL) { *minor_status = 0; return GSS_S_FAILURE; } header = &iov[i]; break; case GSS_IOV_BUFFER_TYPE_TRAILER: if (trailer != NULL) { *minor_status = 0; return GSS_S_FAILURE; } trailer = &iov[i]; break; case GSS_IOV_BUFFER_TYPE_PADDING: if (padding != NULL) { *minor_status = 0; return GSS_S_FAILURE; } padding = &iov[i]; break; case GSS_IOV_BUFFER_TYPE_SIGN_ONLY: break; default: *minor_status = EINVAL; return GSS_S_FAILURE; } } major_status = _gk_verify_buffers(minor_status, ctx, header, padding, trailer); if (major_status != GSS_S_COMPLETE) { return major_status; } if (conf_req_flag) { size_t k5psize = 0; size_t k5pbase = 0; size_t k5bsize = 0; size_t ec = 0; size += sizeof(gss_cfx_wrap_token_desc); *minor_status = krb5_crypto_length(context, ctx->crypto, KRB5_CRYPTO_TYPE_HEADER, &k5hsize); if (*minor_status) return GSS_S_FAILURE; *minor_status = krb5_crypto_length(context, ctx->crypto, KRB5_CRYPTO_TYPE_TRAILER, &k5tsize); if (*minor_status) return GSS_S_FAILURE; *minor_status = krb5_crypto_length(context, ctx->crypto, KRB5_CRYPTO_TYPE_PADDING, &k5pbase); if (*minor_status) return GSS_S_FAILURE; if (k5pbase > 1) { k5psize = k5pbase - (size % k5pbase); } else { k5psize = 0; } if (k5psize == 0 && IS_DCE_STYLE(ctx)) { *minor_status = krb5_crypto_getblocksize(context, ctx->crypto, &k5bsize); if (*minor_status) return GSS_S_FAILURE; ec = k5bsize; } else { ec = k5psize; } gsshsize = sizeof(gss_cfx_wrap_token_desc) + k5hsize; gsstsize = sizeof(gss_cfx_wrap_token_desc) + ec + k5tsize; } else { *minor_status = krb5_crypto_length(context, ctx->crypto, KRB5_CRYPTO_TYPE_CHECKSUM, &k5tsize); if (*minor_status) return GSS_S_FAILURE; gsshsize = sizeof(gss_cfx_wrap_token_desc); gsstsize = k5tsize; } if (trailer != NULL) { trailer->buffer.length = gsstsize; } else { gsshsize += gsstsize; } header->buffer.length = gsshsize; if (padding) { /* padding is done via EC and is contained in the header or trailer */ padding->buffer.length = 0; } if (conf_state) { *conf_state = conf_req_flag; } return GSS_S_COMPLETE; } OM_uint32 _gssapi_wrap_cfx(OM_uint32 *minor_status, const gsskrb5_ctx ctx, krb5_context context, int conf_req_flag, const gss_buffer_t input_message_buffer, int *conf_state, gss_buffer_t output_message_buffer) { gss_cfx_wrap_token token; krb5_error_code ret; unsigned usage; krb5_data cipher; size_t wrapped_len, cksumsize; uint16_t padlength, rrc = 0; int32_t seq_number; u_char *p; ret = _gsskrb5cfx_wrap_length_cfx(context, ctx->crypto, conf_req_flag, IS_DCE_STYLE(ctx), input_message_buffer->length, &wrapped_len, &cksumsize, &padlength); if (ret != 0) { *minor_status = ret; return GSS_S_FAILURE; } /* Always rotate encrypted token (if any) and checksum to header */ rrc = (conf_req_flag ? sizeof(*token) : 0) + (uint16_t)cksumsize; output_message_buffer->length = wrapped_len; output_message_buffer->value = malloc(output_message_buffer->length); if (output_message_buffer->value == NULL) { *minor_status = ENOMEM; return GSS_S_FAILURE; } p = output_message_buffer->value; token = (gss_cfx_wrap_token)p; token->TOK_ID[0] = 0x05; token->TOK_ID[1] = 0x04; token->Flags = 0; token->Filler = 0xFF; if ((ctx->more_flags & LOCAL) == 0) token->Flags |= CFXSentByAcceptor; if (ctx->more_flags & ACCEPTOR_SUBKEY) token->Flags |= CFXAcceptorSubkey; if (conf_req_flag) { /* * In Wrap tokens with confidentiality, the EC field is * used to encode the size (in bytes) of the random filler. */ token->Flags |= CFXSealed; token->EC[0] = (padlength >> 8) & 0xFF; token->EC[1] = (padlength >> 0) & 0xFF; } else { /* * In Wrap tokens without confidentiality, the EC field is * used to encode the size (in bytes) of the trailing * checksum. * * This is not used in the checksum calcuation itself, * because the checksum length could potentially vary * depending on the data length. */ token->EC[0] = 0; token->EC[1] = 0; } /* * In Wrap tokens that provide for confidentiality, the RRC * field in the header contains the hex value 00 00 before * encryption. * * In Wrap tokens that do not provide for confidentiality, * both the EC and RRC fields in the appended checksum * contain the hex value 00 00 for the purpose of calculating * the checksum. */ token->RRC[0] = 0; token->RRC[1] = 0; HEIMDAL_MUTEX_lock(&ctx->ctx_id_mutex); krb5_auth_con_getlocalseqnumber(context, ctx->auth_context, &seq_number); _gsskrb5_encode_be_om_uint32(0, &token->SND_SEQ[0]); _gsskrb5_encode_be_om_uint32(seq_number, &token->SND_SEQ[4]); krb5_auth_con_setlocalseqnumber(context, ctx->auth_context, ++seq_number); HEIMDAL_MUTEX_unlock(&ctx->ctx_id_mutex); /* * If confidentiality is requested, the token header is * appended to the plaintext before encryption; the resulting * token is {"header" | encrypt(plaintext | pad | "header")}. * * If no confidentiality is requested, the checksum is * calculated over the plaintext concatenated with the * token header. */ if (ctx->more_flags & LOCAL) { usage = KRB5_KU_USAGE_INITIATOR_SEAL; } else { usage = KRB5_KU_USAGE_ACCEPTOR_SEAL; } if (conf_req_flag) { /* * Any necessary padding is added here to ensure that the * encrypted token header is always at the end of the * ciphertext. * * The specification does not require that the padding * bytes are initialized. */ p += sizeof(*token); memcpy(p, input_message_buffer->value, input_message_buffer->length); memset(p + input_message_buffer->length, 0xFF, padlength); memcpy(p + input_message_buffer->length + padlength, token, sizeof(*token)); ret = krb5_encrypt(context, ctx->crypto, usage, p, input_message_buffer->length + padlength + sizeof(*token), &cipher); if (ret != 0) { *minor_status = ret; _gsskrb5_release_buffer(minor_status, output_message_buffer); return GSS_S_FAILURE; } assert(sizeof(*token) + cipher.length == wrapped_len); token->RRC[0] = (rrc >> 8) & 0xFF; token->RRC[1] = (rrc >> 0) & 0xFF; /* * this is really ugly, but needed against windows * for DCERPC, as windows rotates by EC+RRC. */ if (IS_DCE_STYLE(ctx)) { ret = rrc_rotate(cipher.data, cipher.length, rrc+padlength, FALSE); } else { ret = rrc_rotate(cipher.data, cipher.length, rrc, FALSE); } if (ret != 0) { *minor_status = ret; _gsskrb5_release_buffer(minor_status, output_message_buffer); return GSS_S_FAILURE; } memcpy(p, cipher.data, cipher.length); krb5_data_free(&cipher); } else { char *buf; Checksum cksum; buf = malloc(input_message_buffer->length + sizeof(*token)); if (buf == NULL) { *minor_status = ENOMEM; _gsskrb5_release_buffer(minor_status, output_message_buffer); return GSS_S_FAILURE; } memcpy(buf, input_message_buffer->value, input_message_buffer->length); memcpy(buf + input_message_buffer->length, token, sizeof(*token)); ret = krb5_create_checksum(context, ctx->crypto, usage, 0, buf, input_message_buffer->length + sizeof(*token), &cksum); if (ret != 0) { *minor_status = ret; _gsskrb5_release_buffer(minor_status, output_message_buffer); free(buf); return GSS_S_FAILURE; } free(buf); assert(cksum.checksum.length == cksumsize); token->EC[0] = (cksum.checksum.length >> 8) & 0xFF; token->EC[1] = (cksum.checksum.length >> 0) & 0xFF; token->RRC[0] = (rrc >> 8) & 0xFF; token->RRC[1] = (rrc >> 0) & 0xFF; p += sizeof(*token); memcpy(p, input_message_buffer->value, input_message_buffer->length); memcpy(p + input_message_buffer->length, cksum.checksum.data, cksum.checksum.length); ret = rrc_rotate(p, input_message_buffer->length + cksum.checksum.length, rrc, FALSE); if (ret != 0) { *minor_status = ret; _gsskrb5_release_buffer(minor_status, output_message_buffer); free_Checksum(&cksum); return GSS_S_FAILURE; } free_Checksum(&cksum); } if (conf_state != NULL) { *conf_state = conf_req_flag; } *minor_status = 0; return GSS_S_COMPLETE; } OM_uint32 _gssapi_unwrap_cfx(OM_uint32 *minor_status, const gsskrb5_ctx ctx, krb5_context context, const gss_buffer_t input_message_buffer, gss_buffer_t output_message_buffer, int *conf_state, gss_qop_t *qop_state) { gss_cfx_wrap_token token; u_char token_flags; krb5_error_code ret; unsigned usage; krb5_data data; uint16_t ec, rrc; OM_uint32 seq_number_lo, seq_number_hi; size_t len; u_char *p; *minor_status = 0; if (input_message_buffer->length < sizeof(*token)) { return GSS_S_DEFECTIVE_TOKEN; } p = input_message_buffer->value; token = (gss_cfx_wrap_token)p; if (token->TOK_ID[0] != 0x05 || token->TOK_ID[1] != 0x04) { return GSS_S_DEFECTIVE_TOKEN; } /* Ignore unknown flags */ token_flags = token->Flags & (CFXSentByAcceptor | CFXSealed | CFXAcceptorSubkey); if (token_flags & CFXSentByAcceptor) { if ((ctx->more_flags & LOCAL) == 0) return GSS_S_DEFECTIVE_TOKEN; } if (ctx->more_flags & ACCEPTOR_SUBKEY) { if ((token_flags & CFXAcceptorSubkey) == 0) return GSS_S_DEFECTIVE_TOKEN; } else { if (token_flags & CFXAcceptorSubkey) return GSS_S_DEFECTIVE_TOKEN; } if (token->Filler != 0xFF) { return GSS_S_DEFECTIVE_TOKEN; } if (conf_state != NULL) { *conf_state = (token_flags & CFXSealed) ? 1 : 0; } ec = (token->EC[0] << 8) | token->EC[1]; rrc = (token->RRC[0] << 8) | token->RRC[1]; /* * Check sequence number */ _gsskrb5_decode_be_om_uint32(&token->SND_SEQ[0], &seq_number_hi); _gsskrb5_decode_be_om_uint32(&token->SND_SEQ[4], &seq_number_lo); if (seq_number_hi) { /* no support for 64-bit sequence numbers */ *minor_status = ERANGE; return GSS_S_UNSEQ_TOKEN; } HEIMDAL_MUTEX_lock(&ctx->ctx_id_mutex); ret = _gssapi_msg_order_check(ctx->order, seq_number_lo); if (ret != 0) { *minor_status = 0; HEIMDAL_MUTEX_unlock(&ctx->ctx_id_mutex); _gsskrb5_release_buffer(minor_status, output_message_buffer); return ret; } HEIMDAL_MUTEX_unlock(&ctx->ctx_id_mutex); /* * Decrypt and/or verify checksum */ if (ctx->more_flags & LOCAL) { usage = KRB5_KU_USAGE_ACCEPTOR_SEAL; } else { usage = KRB5_KU_USAGE_INITIATOR_SEAL; } p += sizeof(*token); len = input_message_buffer->length; len -= (p - (u_char *)input_message_buffer->value); if (token_flags & CFXSealed) { /* * this is really ugly, but needed against windows * for DCERPC, as windows rotates by EC+RRC. */ if (IS_DCE_STYLE(ctx)) { *minor_status = rrc_rotate(p, len, rrc+ec, TRUE); } else { *minor_status = rrc_rotate(p, len, rrc, TRUE); } if (*minor_status != 0) { return GSS_S_FAILURE; } ret = krb5_decrypt(context, ctx->crypto, usage, p, len, &data); if (ret != 0) { *minor_status = ret; return GSS_S_BAD_MIC; } /* Check that there is room for the pad and token header */ if (data.length < ec + sizeof(*token)) { krb5_data_free(&data); return GSS_S_DEFECTIVE_TOKEN; } p = data.data; p += data.length - sizeof(*token); /* RRC is unprotected; don't modify input buffer */ ((gss_cfx_wrap_token)p)->RRC[0] = token->RRC[0]; ((gss_cfx_wrap_token)p)->RRC[1] = token->RRC[1]; /* Check the integrity of the header */ if (ct_memcmp(p, token, sizeof(*token)) != 0) { krb5_data_free(&data); return GSS_S_BAD_MIC; } output_message_buffer->value = data.data; output_message_buffer->length = data.length - ec - sizeof(*token); } else { Checksum cksum; /* Rotate by RRC; bogus to do this in-place XXX */ *minor_status = rrc_rotate(p, len, rrc, TRUE); if (*minor_status != 0) { return GSS_S_FAILURE; } /* Determine checksum type */ ret = krb5_crypto_get_checksum_type(context, ctx->crypto, &cksum.cksumtype); if (ret != 0) { *minor_status = ret; return GSS_S_FAILURE; } cksum.checksum.length = ec; /* Check we have at least as much data as the checksum */ if (len < cksum.checksum.length) { *minor_status = ERANGE; return GSS_S_BAD_MIC; } /* Length now is of the plaintext only, no checksum */ len -= cksum.checksum.length; cksum.checksum.data = p + len; output_message_buffer->length = len; /* for later */ output_message_buffer->value = malloc(len + sizeof(*token)); if (output_message_buffer->value == NULL) { *minor_status = ENOMEM; return GSS_S_FAILURE; } /* Checksum is over (plaintext-data | "header") */ memcpy(output_message_buffer->value, p, len); memcpy((u_char *)output_message_buffer->value + len, token, sizeof(*token)); /* EC is not included in checksum calculation */ token = (gss_cfx_wrap_token)((u_char *)output_message_buffer->value + len); token->EC[0] = 0; token->EC[1] = 0; token->RRC[0] = 0; token->RRC[1] = 0; ret = krb5_verify_checksum(context, ctx->crypto, usage, output_message_buffer->value, len + sizeof(*token), &cksum); if (ret != 0) { *minor_status = ret; _gsskrb5_release_buffer(minor_status, output_message_buffer); return GSS_S_BAD_MIC; } } if (qop_state != NULL) { *qop_state = GSS_C_QOP_DEFAULT; } *minor_status = 0; return GSS_S_COMPLETE; } OM_uint32 _gssapi_mic_cfx(OM_uint32 *minor_status, const gsskrb5_ctx ctx, krb5_context context, gss_qop_t qop_req, const gss_buffer_t message_buffer, gss_buffer_t message_token) { gss_cfx_mic_token token; krb5_error_code ret; unsigned usage; Checksum cksum; u_char *buf; size_t len; int32_t seq_number; len = message_buffer->length + sizeof(*token); buf = malloc(len); if (buf == NULL) { *minor_status = ENOMEM; return GSS_S_FAILURE; } memcpy(buf, message_buffer->value, message_buffer->length); token = (gss_cfx_mic_token)(buf + message_buffer->length); token->TOK_ID[0] = 0x04; token->TOK_ID[1] = 0x04; token->Flags = 0; if ((ctx->more_flags & LOCAL) == 0) token->Flags |= CFXSentByAcceptor; if (ctx->more_flags & ACCEPTOR_SUBKEY) token->Flags |= CFXAcceptorSubkey; memset(token->Filler, 0xFF, 5); HEIMDAL_MUTEX_lock(&ctx->ctx_id_mutex); krb5_auth_con_getlocalseqnumber(context, ctx->auth_context, &seq_number); _gsskrb5_encode_be_om_uint32(0, &token->SND_SEQ[0]); _gsskrb5_encode_be_om_uint32(seq_number, &token->SND_SEQ[4]); krb5_auth_con_setlocalseqnumber(context, ctx->auth_context, ++seq_number); HEIMDAL_MUTEX_unlock(&ctx->ctx_id_mutex); if (ctx->more_flags & LOCAL) { usage = KRB5_KU_USAGE_INITIATOR_SIGN; } else { usage = KRB5_KU_USAGE_ACCEPTOR_SIGN; } ret = krb5_create_checksum(context, ctx->crypto, usage, 0, buf, len, &cksum); if (ret != 0) { *minor_status = ret; free(buf); return GSS_S_FAILURE; } /* Determine MIC length */ message_token->length = sizeof(*token) + cksum.checksum.length; message_token->value = malloc(message_token->length); if (message_token->value == NULL) { *minor_status = ENOMEM; free_Checksum(&cksum); free(buf); return GSS_S_FAILURE; } /* Token is { "header" | get_mic("header" | plaintext-data) } */ memcpy(message_token->value, token, sizeof(*token)); memcpy((u_char *)message_token->value + sizeof(*token), cksum.checksum.data, cksum.checksum.length); free_Checksum(&cksum); free(buf); *minor_status = 0; return GSS_S_COMPLETE; } OM_uint32 _gssapi_verify_mic_cfx(OM_uint32 *minor_status, const gsskrb5_ctx ctx, krb5_context context, const gss_buffer_t message_buffer, const gss_buffer_t token_buffer, gss_qop_t *qop_state) { gss_cfx_mic_token token; u_char token_flags; krb5_error_code ret; unsigned usage; OM_uint32 seq_number_lo, seq_number_hi; u_char *buf, *p; Checksum cksum; *minor_status = 0; if (token_buffer->length < sizeof(*token)) { return GSS_S_DEFECTIVE_TOKEN; } p = token_buffer->value; token = (gss_cfx_mic_token)p; if (token->TOK_ID[0] != 0x04 || token->TOK_ID[1] != 0x04) { return GSS_S_DEFECTIVE_TOKEN; } /* Ignore unknown flags */ token_flags = token->Flags & (CFXSentByAcceptor | CFXAcceptorSubkey); if (token_flags & CFXSentByAcceptor) { if ((ctx->more_flags & LOCAL) == 0) return GSS_S_DEFECTIVE_TOKEN; } if (ctx->more_flags & ACCEPTOR_SUBKEY) { if ((token_flags & CFXAcceptorSubkey) == 0) return GSS_S_DEFECTIVE_TOKEN; } else { if (token_flags & CFXAcceptorSubkey) return GSS_S_DEFECTIVE_TOKEN; } if (ct_memcmp(token->Filler, "\xff\xff\xff\xff\xff", 5) != 0) { return GSS_S_DEFECTIVE_TOKEN; } /* * Check sequence number */ _gsskrb5_decode_be_om_uint32(&token->SND_SEQ[0], &seq_number_hi); _gsskrb5_decode_be_om_uint32(&token->SND_SEQ[4], &seq_number_lo); if (seq_number_hi) { *minor_status = ERANGE; return GSS_S_UNSEQ_TOKEN; } HEIMDAL_MUTEX_lock(&ctx->ctx_id_mutex); ret = _gssapi_msg_order_check(ctx->order, seq_number_lo); if (ret != 0) { *minor_status = 0; HEIMDAL_MUTEX_unlock(&ctx->ctx_id_mutex); return ret; } HEIMDAL_MUTEX_unlock(&ctx->ctx_id_mutex); /* * Verify checksum */ ret = krb5_crypto_get_checksum_type(context, ctx->crypto, &cksum.cksumtype); if (ret != 0) { *minor_status = ret; return GSS_S_FAILURE; } cksum.checksum.data = p + sizeof(*token); cksum.checksum.length = token_buffer->length - sizeof(*token); if (ctx->more_flags & LOCAL) { usage = KRB5_KU_USAGE_ACCEPTOR_SIGN; } else { usage = KRB5_KU_USAGE_INITIATOR_SIGN; } buf = malloc(message_buffer->length + sizeof(*token)); if (buf == NULL) { *minor_status = ENOMEM; return GSS_S_FAILURE; } memcpy(buf, message_buffer->value, message_buffer->length); memcpy(buf + message_buffer->length, token, sizeof(*token)); ret = krb5_verify_checksum(context, ctx->crypto, usage, buf, sizeof(*token) + message_buffer->length, &cksum); if (ret != 0) { *minor_status = ret; free(buf); return GSS_S_BAD_MIC; } free(buf); if (qop_state != NULL) { *qop_state = GSS_C_QOP_DEFAULT; } return GSS_S_COMPLETE; } heimdal-7.5.0/lib/gssapi/krb5/release_cred.c0000644000175000017500000000527712136107747016755 0ustar niknik/* * Copyright (c) 1997-2003 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "gsskrb5_locl.h" OM_uint32 GSSAPI_CALLCONV _gsskrb5_release_cred (OM_uint32 * minor_status, gss_cred_id_t * cred_handle ) { krb5_context context; gsskrb5_cred cred; OM_uint32 junk; *minor_status = 0; if (*cred_handle == NULL) return GSS_S_COMPLETE; cred = (gsskrb5_cred)*cred_handle; *cred_handle = GSS_C_NO_CREDENTIAL; GSSAPI_KRB5_INIT (&context); HEIMDAL_MUTEX_lock(&cred->cred_id_mutex); if (cred->principal != NULL) krb5_free_principal(context, cred->principal); if (cred->keytab != NULL) krb5_kt_close(context, cred->keytab); if (cred->ccache != NULL) { if (cred->cred_flags & GSS_CF_DESTROY_CRED_ON_RELEASE) krb5_cc_destroy(context, cred->ccache); else krb5_cc_close(context, cred->ccache); } gss_release_oid_set(&junk, &cred->mechanisms); if (cred->enctypes) free(cred->enctypes); HEIMDAL_MUTEX_unlock(&cred->cred_id_mutex); HEIMDAL_MUTEX_destroy(&cred->cred_id_mutex); memset(cred, 0, sizeof(*cred)); free(cred); return GSS_S_COMPLETE; } heimdal-7.5.0/lib/gssapi/krb5/gkrb5_err.et0000644000175000017500000000231312136107747016374 0ustar niknik# # extended gss krb5 error messages # id "$Id$" error_table gk5 prefix GSS_KRB5_S error_code G_BAD_SERVICE_NAME, "No @ in SERVICE-NAME name string" error_code G_BAD_STRING_UID, "STRING-UID-NAME contains nondigits" error_code G_NOUSER, "UID does not resolve to username" error_code G_VALIDATE_FAILED, "Validation error" error_code G_BUFFER_ALLOC, "Couldn't allocate gss_buffer_t data" error_code G_BAD_MSG_CTX, "Message context invalid" error_code G_WRONG_SIZE, "Buffer is the wrong size" error_code G_BAD_USAGE, "Credential usage type is unknown" error_code G_UNKNOWN_QOP, "Unknown quality of protection specified" index 128 error_code KG_CCACHE_NOMATCH, "Principal in credential cache does not match desired name" error_code KG_KEYTAB_NOMATCH, "No principal in keytab matches desired name" error_code KG_TGT_MISSING, "Credential cache has no TGT" error_code KG_NO_SUBKEY, "Authenticator has no subkey" error_code KG_CONTEXT_ESTABLISHED, "Context is already fully established" error_code KG_BAD_SIGN_TYPE, "Unknown signature type in token" error_code KG_BAD_LENGTH, "Invalid field length in token" error_code KG_CTX_INCOMPLETE, "Attempt to use incomplete security context" error_code KG_INPUT_TOO_LONG, "Input too long" heimdal-7.5.0/lib/gssapi/krb5/prf.c0000644000175000017500000001063313026237312015106 0ustar niknik/* * Copyright (c) 2007 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "gsskrb5_locl.h" OM_uint32 GSSAPI_CALLCONV _gsskrb5_pseudo_random(OM_uint32 *minor_status, gss_ctx_id_t context_handle, int prf_key, const gss_buffer_t prf_in, ssize_t desired_output_len, gss_buffer_t prf_out) { gsskrb5_ctx ctx = (gsskrb5_ctx)context_handle; krb5_context context; krb5_error_code ret; krb5_crypto crypto; krb5_data input, output; uint32_t num; OM_uint32 junk; unsigned char *p; krb5_keyblock *key = NULL; size_t dol; if (ctx == NULL) { *minor_status = 0; return GSS_S_NO_CONTEXT; } if (desired_output_len <= 0 || prf_in->length + 4 < prf_in->length) { *minor_status = 0; return GSS_S_FAILURE; } dol = desired_output_len; GSSAPI_KRB5_INIT (&context); switch(prf_key) { case GSS_C_PRF_KEY_FULL: _gsskrb5i_get_acceptor_subkey(ctx, context, &key); break; case GSS_C_PRF_KEY_PARTIAL: _gsskrb5i_get_initiator_subkey(ctx, context, &key); break; default: _gsskrb5_set_status(EINVAL, "unknown kerberos prf_key"); *minor_status = EINVAL; return GSS_S_FAILURE; } if (key == NULL) { _gsskrb5_set_status(EINVAL, "no prf_key found"); *minor_status = EINVAL; return GSS_S_FAILURE; } ret = krb5_crypto_init(context, key, 0, &crypto); krb5_free_keyblock (context, key); if (ret) { *minor_status = ret; return GSS_S_FAILURE; } prf_out->value = malloc(dol); if (prf_out->value == NULL) { _gsskrb5_set_status(GSS_KRB5_S_KG_INPUT_TOO_LONG, "Out of memory"); *minor_status = GSS_KRB5_S_KG_INPUT_TOO_LONG; krb5_crypto_destroy(context, crypto); return GSS_S_FAILURE; } prf_out->length = dol; HEIMDAL_MUTEX_lock(&ctx->ctx_id_mutex); input.length = prf_in->length + 4; input.data = malloc(prf_in->length + 4); if (input.data == NULL) { _gsskrb5_set_status(GSS_KRB5_S_KG_INPUT_TOO_LONG, "Out of memory"); *minor_status = GSS_KRB5_S_KG_INPUT_TOO_LONG; gss_release_buffer(&junk, prf_out); krb5_crypto_destroy(context, crypto); HEIMDAL_MUTEX_unlock(&ctx->ctx_id_mutex); return GSS_S_FAILURE; } memcpy(((uint8_t *)input.data) + 4, prf_in->value, prf_in->length); num = 0; p = prf_out->value; while(dol > 0) { size_t tsize; _gsskrb5_encode_be_om_uint32(num, input.data); ret = krb5_crypto_prf(context, crypto, &input, &output); if (ret) { *minor_status = ret; free(input.data); gss_release_buffer(&junk, prf_out); krb5_crypto_destroy(context, crypto); HEIMDAL_MUTEX_unlock(&ctx->ctx_id_mutex); return GSS_S_FAILURE; } tsize = min(dol, output.length); memcpy(p, output.data, tsize); p += tsize; dol -= tsize; krb5_data_free(&output); num++; } free(input.data); krb5_crypto_destroy(context, crypto); HEIMDAL_MUTEX_unlock(&ctx->ctx_id_mutex); return GSS_S_COMPLETE; } heimdal-7.5.0/lib/gssapi/krb5/export_sec_context.c0000644000175000017500000001437313026237312020243 0ustar niknik/* * Copyright (c) 1999 - 2003 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "gsskrb5_locl.h" OM_uint32 GSSAPI_CALLCONV _gsskrb5_export_sec_context( OM_uint32 *minor_status, gss_ctx_id_t *context_handle, gss_buffer_t interprocess_token ) { krb5_context context; const gsskrb5_ctx ctx = (const gsskrb5_ctx) *context_handle; krb5_storage *sp; krb5_auth_context ac; OM_uint32 ret = GSS_S_COMPLETE; krb5_data data; gss_buffer_desc buffer; int flags; OM_uint32 minor; krb5_error_code kret; GSSAPI_KRB5_INIT (&context); HEIMDAL_MUTEX_lock(&ctx->ctx_id_mutex); if (!(ctx->flags & GSS_C_TRANS_FLAG)) { HEIMDAL_MUTEX_unlock(&ctx->ctx_id_mutex); *minor_status = 0; return GSS_S_UNAVAILABLE; } sp = krb5_storage_emem (); if (sp == NULL) { HEIMDAL_MUTEX_unlock(&ctx->ctx_id_mutex); *minor_status = ENOMEM; return GSS_S_FAILURE; } ac = ctx->auth_context; /* flagging included fields */ flags = 0; if (ac->local_address) flags |= SC_LOCAL_ADDRESS; if (ac->remote_address) flags |= SC_REMOTE_ADDRESS; if (ac->keyblock) flags |= SC_KEYBLOCK; if (ac->local_subkey) flags |= SC_LOCAL_SUBKEY; if (ac->remote_subkey) flags |= SC_REMOTE_SUBKEY; kret = krb5_store_int32 (sp, flags); if (kret) { *minor_status = kret; goto failure; } /* marshall auth context */ kret = krb5_store_int32 (sp, ac->flags); if (kret) { *minor_status = kret; goto failure; } if (ac->local_address) { kret = krb5_store_address (sp, *ac->local_address); if (kret) { *minor_status = kret; goto failure; } } if (ac->remote_address) { kret = krb5_store_address (sp, *ac->remote_address); if (kret) { *minor_status = kret; goto failure; } } kret = krb5_store_int16 (sp, ac->local_port); if (kret) { *minor_status = kret; goto failure; } kret = krb5_store_int16 (sp, ac->remote_port); if (kret) { *minor_status = kret; goto failure; } if (ac->keyblock) { kret = krb5_store_keyblock (sp, *ac->keyblock); if (kret) { *minor_status = kret; goto failure; } } if (ac->local_subkey) { kret = krb5_store_keyblock (sp, *ac->local_subkey); if (kret) { *minor_status = kret; goto failure; } } if (ac->remote_subkey) { kret = krb5_store_keyblock (sp, *ac->remote_subkey); if (kret) { *minor_status = kret; goto failure; } } kret = krb5_store_int32 (sp, ac->local_seqnumber); if (kret) { *minor_status = kret; goto failure; } kret = krb5_store_int32 (sp, ac->remote_seqnumber); if (kret) { *minor_status = kret; goto failure; } kret = krb5_store_int32 (sp, ac->keytype); if (kret) { *minor_status = kret; goto failure; } kret = krb5_store_int32 (sp, ac->cksumtype); if (kret) { *minor_status = kret; goto failure; } /* names */ ret = _gsskrb5_export_name (minor_status, (gss_name_t)ctx->source, &buffer); if (ret) goto failure; data.data = buffer.value; data.length = buffer.length; kret = krb5_store_data (sp, data); _gsskrb5_release_buffer (&minor, &buffer); if (kret) { *minor_status = kret; goto failure; } ret = _gsskrb5_export_name (minor_status, (gss_name_t)ctx->target, &buffer); if (ret) goto failure; data.data = buffer.value; data.length = buffer.length; ret = GSS_S_FAILURE; kret = krb5_store_data (sp, data); _gsskrb5_release_buffer (&minor, &buffer); if (kret) { *minor_status = kret; goto failure; } kret = krb5_store_int32 (sp, ctx->flags); if (kret) { *minor_status = kret; goto failure; } kret = krb5_store_int32 (sp, ctx->more_flags); if (kret) { *minor_status = kret; goto failure; } /* * XXX We should put a 64-bit int here, but we don't have a * krb5_store_int64() yet. */ kret = krb5_store_int32 (sp, ctx->endtime); if (kret) { *minor_status = kret; goto failure; } kret = _gssapi_msg_order_export(sp, ctx->order); if (kret ) { *minor_status = kret; goto failure; } kret = krb5_storage_to_data (sp, &data); krb5_storage_free (sp); if (kret) { HEIMDAL_MUTEX_unlock(&ctx->ctx_id_mutex); *minor_status = kret; return GSS_S_FAILURE; } interprocess_token->length = data.length; interprocess_token->value = data.data; HEIMDAL_MUTEX_unlock(&ctx->ctx_id_mutex); ret = _gsskrb5_delete_sec_context (minor_status, context_handle, GSS_C_NO_BUFFER); if (ret != GSS_S_COMPLETE) _gsskrb5_release_buffer (NULL, interprocess_token); *minor_status = 0; return ret; failure: HEIMDAL_MUTEX_unlock(&ctx->ctx_id_mutex); krb5_storage_free (sp); return ret; } heimdal-7.5.0/lib/gssapi/krb5/compat.c0000644000175000017500000000675413026237312015613 0ustar niknik/* * Copyright (c) 2003 - 2005 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "gsskrb5_locl.h" static krb5_error_code check_compat(OM_uint32 *minor_status, krb5_context context, krb5_const_principal name, const char *option, krb5_boolean *compat, krb5_boolean match_val) { krb5_error_code ret = 0; char **p, **q; krb5_principal match; p = krb5_config_get_strings(context, NULL, "gssapi", option, NULL); if(p == NULL) return 0; match = NULL; for(q = p; *q; q++) { ret = krb5_parse_name(context, *q, &match); if (ret) break; if (krb5_principal_match(context, name, match)) { *compat = match_val; break; } krb5_free_principal(context, match); match = NULL; } if (match) krb5_free_principal(context, match); krb5_config_free_strings(p); if (ret) { if (minor_status) *minor_status = ret; return GSS_S_FAILURE; } return 0; } /* * ctx->ctx_id_mutex is assumed to be locked */ OM_uint32 _gss_DES3_get_mic_compat(OM_uint32 *minor_status, gsskrb5_ctx ctx, krb5_context context) { krb5_boolean use_compat = FALSE; OM_uint32 ret; if ((ctx->more_flags & COMPAT_OLD_DES3_SELECTED) == 0) { ret = check_compat(minor_status, context, ctx->target, "broken_des3_mic", &use_compat, TRUE); if (ret) return ret; ret = check_compat(minor_status, context, ctx->target, "correct_des3_mic", &use_compat, FALSE); if (ret) return ret; if (use_compat) ctx->more_flags |= COMPAT_OLD_DES3; ctx->more_flags |= COMPAT_OLD_DES3_SELECTED; } return 0; } #if 0 OM_uint32 gss_krb5_compat_des3_mic(OM_uint32 *minor_status, gss_ctx_id_t ctx, int on) { *minor_status = 0; HEIMDAL_MUTEX_lock(&ctx->ctx_id_mutex); if (on) { ctx->more_flags |= COMPAT_OLD_DES3; } else { ctx->more_flags &= ~COMPAT_OLD_DES3; } ctx->more_flags |= COMPAT_OLD_DES3_SELECTED; HEIMDAL_MUTEX_unlock(&ctx->ctx_id_mutex); return 0; } #endif heimdal-7.5.0/lib/gssapi/krb5/inquire_cred_by_mech.c0000644000175000017500000000525413026237312020461 0ustar niknik/* * Copyright (c) 2003, 2006, 2007 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "gsskrb5_locl.h" OM_uint32 GSSAPI_CALLCONV _gsskrb5_inquire_cred_by_mech ( OM_uint32 * minor_status, gss_const_cred_id_t cred_handle, const gss_OID mech_type, gss_name_t * name, OM_uint32 * initiator_lifetime, OM_uint32 * acceptor_lifetime, gss_cred_usage_t * cred_usage ) { gss_cred_usage_t usage; OM_uint32 maj_stat; OM_uint32 lifetime; /* * XXX This is busted. _gsskrb5_inquire_cred() should be implemented in * terms of _gsskrb5_inquire_cred_by_mech(), NOT the other way around. */ maj_stat = _gsskrb5_inquire_cred (minor_status, cred_handle, name, &lifetime, &usage, NULL); if (maj_stat) return maj_stat; if (initiator_lifetime) { if (usage == GSS_C_INITIATE || usage == GSS_C_BOTH) *initiator_lifetime = lifetime; else *initiator_lifetime = 0; } if (acceptor_lifetime) { if (usage == GSS_C_ACCEPT || usage == GSS_C_BOTH) *acceptor_lifetime = lifetime; else *acceptor_lifetime = 0; } if (cred_usage) *cred_usage = usage; return GSS_S_COMPLETE; } heimdal-7.5.0/lib/gssapi/krb5/context_time.c0000644000175000017500000000562113026237312017022 0ustar niknik/* * Copyright (c) 1997 - 2003 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "gsskrb5_locl.h" OM_uint32 _gsskrb5_lifetime_left(OM_uint32 *minor_status, krb5_context context, OM_uint32 endtime, OM_uint32 *lifetime_rec) { krb5_timestamp now; krb5_error_code kret; if (endtime == 0) { *lifetime_rec = GSS_C_INDEFINITE; return GSS_S_COMPLETE; } kret = krb5_timeofday(context, &now); if (kret) { *lifetime_rec = 0; *minor_status = kret; return GSS_S_FAILURE; } if (endtime < now) *lifetime_rec = 0; else *lifetime_rec = endtime - now; return GSS_S_COMPLETE; } OM_uint32 GSSAPI_CALLCONV _gsskrb5_context_time (OM_uint32 * minor_status, gss_const_ctx_id_t context_handle, OM_uint32 * time_rec ) { krb5_context context; OM_uint32 endtime; OM_uint32 major_status; const gsskrb5_ctx ctx = (const gsskrb5_ctx) context_handle; GSSAPI_KRB5_INIT (&context); HEIMDAL_MUTEX_lock(&ctx->ctx_id_mutex); endtime = ctx->endtime; HEIMDAL_MUTEX_unlock(&ctx->ctx_id_mutex); major_status = _gsskrb5_lifetime_left(minor_status, context, endtime, time_rec); if (major_status != GSS_S_COMPLETE) return major_status; *minor_status = 0; if (*time_rec == 0) return GSS_S_CONTEXT_EXPIRED; return GSS_S_COMPLETE; } heimdal-7.5.0/lib/gssapi/krb5/compare_name.c0000644000175000017500000000421213026237312016741 0ustar niknik/* * Copyright (c) 1997-2003 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "gsskrb5_locl.h" OM_uint32 GSSAPI_CALLCONV _gsskrb5_compare_name (OM_uint32 * minor_status, gss_const_name_t name1, gss_const_name_t name2, int * name_equal ) { krb5_const_principal princ1 = (krb5_const_principal)name1; krb5_const_principal princ2 = (krb5_const_principal)name2; krb5_context context; GSSAPI_KRB5_INIT(&context); *name_equal = krb5_principal_compare (context, princ1, princ2); *minor_status = 0; return GSS_S_COMPLETE; } heimdal-7.5.0/lib/gssapi/krb5/test_cfx.c0000644000175000017500000001115513026237312016136 0ustar niknik/* * Copyright (c) 2006 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of KTH nor the names of its contributors may be * used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY KTH AND ITS CONTRIBUTORS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL KTH OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "gsskrb5_locl.h" struct range { size_t lower; size_t upper; }; struct range tests[] = { { 0, 1040 }, { 2040, 2080 }, { 4080, 5000 }, { 8180, 8292 }, { 9980, 10010 } }; static void test_range(const struct range *r, int integ, krb5_context context, krb5_crypto crypto) { krb5_error_code ret; size_t size, rsize; struct gsskrb5_ctx ctx; for (size = r->lower; size < r->upper; size++) { size_t cksumsize; uint16_t padsize; OM_uint32 minor; OM_uint32 max_wrap_size; ctx.crypto = crypto; ret = _gssapi_wrap_size_cfx(&minor, &ctx, context, integ, 0, size, &max_wrap_size); if (ret) krb5_errx(context, 1, "_gsskrb5cfx_max_wrap_length_cfx: %d", ret); if (max_wrap_size == 0) continue; ret = _gsskrb5cfx_wrap_length_cfx(context, crypto, integ, 0, max_wrap_size, &rsize, &cksumsize, &padsize); if (ret) krb5_errx(context, 1, "_gsskrb5cfx_wrap_length_cfx: %d", ret); if (size < rsize) krb5_errx(context, 1, "size (%d) < rsize (%d) for max_wrap_size %d", (int)size, (int)rsize, (int)max_wrap_size); } } static void test_special(krb5_context context, krb5_crypto crypto, int integ, size_t testsize) { krb5_error_code ret; size_t rsize; OM_uint32 max_wrap_size; size_t cksumsize; uint16_t padsize; struct gsskrb5_ctx ctx; OM_uint32 minor; ctx.crypto = crypto; ret = _gssapi_wrap_size_cfx(&minor, &ctx, context, integ, 0, testsize, &max_wrap_size); if (ret) krb5_errx(context, 1, "_gsskrb5cfx_max_wrap_length_cfx: %d", ret); if (ret) krb5_errx(context, 1, "_gsskrb5cfx_max_wrap_length_cfx: %d", ret); ret = _gsskrb5cfx_wrap_length_cfx(context, crypto, integ, 0, max_wrap_size, &rsize, &cksumsize, &padsize); if (ret) krb5_errx(context, 1, "_gsskrb5cfx_wrap_length_cfx: %d", ret); if (testsize < rsize) krb5_errx(context, 1, "testsize (%d) < rsize (%d) for max_wrap_size %d", (int)testsize, (int)rsize, (int)max_wrap_size); } int main(int argc, char **argv) { krb5_keyblock keyblock; krb5_error_code ret; krb5_context context; krb5_crypto crypto; int i; ret = krb5_init_context(&context); if (ret) errx(1, "krb5_context_init: %d", ret); ret = krb5_generate_random_keyblock(context, KRB5_ENCTYPE_AES256_CTS_HMAC_SHA1_96, &keyblock); if (ret) krb5_err(context, 1, ret, "krb5_generate_random_keyblock"); ret = krb5_crypto_init(context, &keyblock, 0, &crypto); if (ret) krb5_err(context, 1, ret, "krb5_crypto_init"); test_special(context, crypto, 1, 60); test_special(context, crypto, 0, 60); for (i = 0; i < sizeof(tests)/sizeof(tests[0]); i++) { test_range(&tests[i], 1, context, crypto); test_range(&tests[i], 0, context, crypto); } krb5_free_keyblock_contents(context, &keyblock); krb5_crypto_destroy(context, crypto); krb5_free_context(context); return 0; } heimdal-7.5.0/lib/gssapi/krb5/set_sec_context_option.c0000644000175000017500000001460613026237312021104 0ustar niknik/* * Copyright (c) 2004, PADL Software Pty Ltd. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of PADL Software nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY PADL SOFTWARE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL PADL SOFTWARE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ /* * glue routine for _gsskrb5_inquire_sec_context_by_oid */ #include "gsskrb5_locl.h" static OM_uint32 get_bool(OM_uint32 *minor_status, const gss_buffer_t value, int *flag) { if (value->value == NULL || value->length != 1) { *minor_status = EINVAL; return GSS_S_FAILURE; } *flag = *((const char *)value->value) != 0; return GSS_S_COMPLETE; } static OM_uint32 get_string(OM_uint32 *minor_status, const gss_buffer_t value, char **str) { if (value == NULL || value->length == 0) { *str = NULL; } else { *str = malloc(value->length + 1); if (*str == NULL) { *minor_status = 0; return GSS_S_UNAVAILABLE; } memcpy(*str, value->value, value->length); (*str)[value->length] = '\0'; } return GSS_S_COMPLETE; } static OM_uint32 get_int32(OM_uint32 *minor_status, const gss_buffer_t value, OM_uint32 *ret) { *minor_status = 0; if (value == NULL || value->length == 0) *ret = 0; else if (value->length == sizeof(*ret)) memcpy(ret, value->value, sizeof(*ret)); else return GSS_S_UNAVAILABLE; return GSS_S_COMPLETE; } static OM_uint32 set_int32(OM_uint32 *minor_status, const gss_buffer_t value, OM_uint32 set) { *minor_status = 0; if (value->length == sizeof(set)) memcpy(value->value, &set, sizeof(set)); else return GSS_S_UNAVAILABLE; return GSS_S_COMPLETE; } OM_uint32 GSSAPI_CALLCONV _gsskrb5_set_sec_context_option (OM_uint32 *minor_status, gss_ctx_id_t *context_handle, const gss_OID desired_object, const gss_buffer_t value) { krb5_context context; OM_uint32 maj_stat; GSSAPI_KRB5_INIT (&context); if (value == GSS_C_NO_BUFFER) { *minor_status = EINVAL; return GSS_S_FAILURE; } if (gss_oid_equal(desired_object, GSS_KRB5_COMPAT_DES3_MIC_X)) { gsskrb5_ctx ctx; int flag; if (*context_handle == GSS_C_NO_CONTEXT) { *minor_status = EINVAL; return GSS_S_NO_CONTEXT; } maj_stat = get_bool(minor_status, value, &flag); if (maj_stat != GSS_S_COMPLETE) return maj_stat; ctx = (gsskrb5_ctx)*context_handle; HEIMDAL_MUTEX_lock(&ctx->ctx_id_mutex); if (flag) ctx->more_flags |= COMPAT_OLD_DES3; else ctx->more_flags &= ~COMPAT_OLD_DES3; ctx->more_flags |= COMPAT_OLD_DES3_SELECTED; HEIMDAL_MUTEX_unlock(&ctx->ctx_id_mutex); return GSS_S_COMPLETE; } else if (gss_oid_equal(desired_object, GSS_KRB5_SET_DNS_CANONICALIZE_X)) { int flag; maj_stat = get_bool(minor_status, value, &flag); if (maj_stat != GSS_S_COMPLETE) return maj_stat; krb5_set_dns_canonicalize_hostname(context, flag); return GSS_S_COMPLETE; } else if (gss_oid_equal(desired_object, GSS_KRB5_REGISTER_ACCEPTOR_IDENTITY_X)) { char *str; maj_stat = get_string(minor_status, value, &str); if (maj_stat != GSS_S_COMPLETE) return maj_stat; maj_stat = _gsskrb5_register_acceptor_identity(minor_status, str); free(str); return maj_stat; } else if (gss_oid_equal(desired_object, GSS_KRB5_SET_DEFAULT_REALM_X)) { char *str; maj_stat = get_string(minor_status, value, &str); if (maj_stat != GSS_S_COMPLETE) return maj_stat; if (str == NULL) { *minor_status = 0; return GSS_S_CALL_INACCESSIBLE_READ; } krb5_set_default_realm(context, str); free(str); *minor_status = 0; return GSS_S_COMPLETE; } else if (gss_oid_equal(desired_object, GSS_KRB5_SEND_TO_KDC_X)) { *minor_status = EINVAL; return GSS_S_FAILURE; } else if (gss_oid_equal(desired_object, GSS_KRB5_CCACHE_NAME_X)) { char *str; maj_stat = get_string(minor_status, value, &str); if (maj_stat != GSS_S_COMPLETE) return maj_stat; if (str == NULL) { *minor_status = 0; return GSS_S_CALL_INACCESSIBLE_READ; } *minor_status = krb5_cc_set_default_name(context, str); free(str); if (*minor_status) return GSS_S_FAILURE; return GSS_S_COMPLETE; } else if (gss_oid_equal(desired_object, GSS_KRB5_SET_TIME_OFFSET_X)) { OM_uint32 offset; time_t t; maj_stat = get_int32(minor_status, value, &offset); if (maj_stat != GSS_S_COMPLETE) return maj_stat; t = time(NULL) + offset; krb5_set_real_time(context, t, 0); *minor_status = 0; return GSS_S_COMPLETE; } else if (gss_oid_equal(desired_object, GSS_KRB5_GET_TIME_OFFSET_X)) { krb5_timestamp sec; int32_t usec; time_t t; t = time(NULL); krb5_us_timeofday (context, &sec, &usec); maj_stat = set_int32(minor_status, value, sec - t); if (maj_stat != GSS_S_COMPLETE) return maj_stat; *minor_status = 0; return GSS_S_COMPLETE; } else if (gss_oid_equal(desired_object, GSS_KRB5_PLUGIN_REGISTER_X)) { struct gsskrb5_krb5_plugin c; if (value->length != sizeof(c)) { *minor_status = EINVAL; return GSS_S_FAILURE; } memcpy(&c, value->value, sizeof(c)); krb5_plugin_register(context, c.type, c.name, c.symbol); *minor_status = 0; return GSS_S_COMPLETE; } *minor_status = EINVAL; return GSS_S_FAILURE; } heimdal-7.5.0/lib/gssapi/krb5/creds.c0000644000175000017500000001533613026237312015424 0ustar niknik/* * Copyright (c) 2009 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "gsskrb5_locl.h" OM_uint32 GSSAPI_CALLCONV _gsskrb5_export_cred(OM_uint32 *minor_status, gss_cred_id_t cred_handle, gss_buffer_t cred_token) { gsskrb5_cred handle = (gsskrb5_cred)cred_handle; krb5_context context; krb5_error_code ret; krb5_storage *sp; krb5_data data, mech; const char *type; char *str; GSSAPI_KRB5_INIT (&context); if (handle->usage != GSS_C_INITIATE && handle->usage != GSS_C_BOTH) { *minor_status = GSS_KRB5_S_G_BAD_USAGE; return GSS_S_FAILURE; } sp = krb5_storage_emem(); if (sp == NULL) { *minor_status = ENOMEM; return GSS_S_FAILURE; } type = krb5_cc_get_type(context, handle->ccache); if (strcmp(type, "MEMORY") == 0) { krb5_creds *creds; krb5_data config_start_realm; char *start_realm; ret = krb5_store_uint32(sp, 0); if (ret) { krb5_storage_free(sp); *minor_status = ret; return GSS_S_FAILURE; } ret = krb5_cc_get_config(context, handle->ccache, NULL, "start_realm", &config_start_realm); if (ret == 0) { start_realm = strndup(config_start_realm.data, config_start_realm.length); krb5_data_free(&config_start_realm); } else { start_realm = strdup(krb5_principal_get_realm(context, handle->principal)); } if (start_realm == NULL) { *minor_status = krb5_enomem(context); krb5_storage_free(sp); return GSS_S_FAILURE; } ret = _krb5_get_krbtgt(context, handle->ccache, start_realm, &creds); free(start_realm); start_realm = NULL; if (ret) { krb5_storage_free(sp); *minor_status = ret; return GSS_S_FAILURE; } ret = krb5_store_creds(sp, creds); krb5_free_creds(context, creds); if (ret) { krb5_storage_free(sp); *minor_status = ret; return GSS_S_FAILURE; } } else { ret = krb5_store_uint32(sp, 1); if (ret) { krb5_storage_free(sp); *minor_status = ret; return GSS_S_FAILURE; } ret = krb5_cc_get_full_name(context, handle->ccache, &str); if (ret) { krb5_storage_free(sp); *minor_status = ret; return GSS_S_FAILURE; } ret = krb5_store_string(sp, str); free(str); if (ret) { krb5_storage_free(sp); *minor_status = ret; return GSS_S_FAILURE; } } ret = krb5_storage_to_data(sp, &data); krb5_storage_free(sp); if (ret) { *minor_status = ret; return GSS_S_FAILURE; } sp = krb5_storage_emem(); if (sp == NULL) { krb5_data_free(&data); *minor_status = ENOMEM; return GSS_S_FAILURE; } mech.data = GSS_KRB5_MECHANISM->elements; mech.length = GSS_KRB5_MECHANISM->length; ret = krb5_store_data(sp, mech); if (ret) { krb5_data_free(&data); krb5_storage_free(sp); *minor_status = ret; return GSS_S_FAILURE; } ret = krb5_store_data(sp, data); krb5_data_free(&data); if (ret) { krb5_storage_free(sp); *minor_status = ret; return GSS_S_FAILURE; } ret = krb5_storage_to_data(sp, &data); krb5_storage_free(sp); if (ret) { *minor_status = ret; return GSS_S_FAILURE; } cred_token->value = data.data; cred_token->length = data.length; return GSS_S_COMPLETE; } OM_uint32 GSSAPI_CALLCONV _gsskrb5_import_cred(OM_uint32 * minor_status, gss_buffer_t cred_token, gss_cred_id_t * cred_handle) { krb5_context context; krb5_error_code ret; gsskrb5_cred handle; krb5_ccache id; krb5_storage *sp; char *str; uint32_t type; int flags = 0; *cred_handle = GSS_C_NO_CREDENTIAL; GSSAPI_KRB5_INIT (&context); sp = krb5_storage_from_mem(cred_token->value, cred_token->length); if (sp == NULL) { *minor_status = ENOMEM; return GSS_S_FAILURE; } ret = krb5_ret_uint32(sp, &type); if (ret) { krb5_storage_free(sp); *minor_status = ret; return GSS_S_FAILURE; } switch (type) { case 0: { krb5_creds creds; ret = krb5_ret_creds(sp, &creds); krb5_storage_free(sp); if (ret) { *minor_status = ret; return GSS_S_FAILURE; } ret = krb5_cc_new_unique(context, "MEMORY", NULL, &id); if (ret) { *minor_status = ret; return GSS_S_FAILURE; } ret = krb5_cc_initialize(context, id, creds.client); if (ret) { krb5_cc_destroy(context, id); *minor_status = ret; return GSS_S_FAILURE; } ret = krb5_cc_store_cred(context, id, &creds); krb5_free_cred_contents(context, &creds); if (ret) { *minor_status = ret; return GSS_S_FAILURE; } flags |= GSS_CF_DESTROY_CRED_ON_RELEASE; break; } case 1: ret = krb5_ret_string(sp, &str); krb5_storage_free(sp); if (ret) { *minor_status = ret; return GSS_S_FAILURE; } ret = krb5_cc_resolve(context, str, &id); krb5_xfree(str); if (ret) { *minor_status = ret; return GSS_S_FAILURE; } break; default: krb5_storage_free(sp); *minor_status = 0; return GSS_S_NO_CRED; } handle = calloc(1, sizeof(*handle)); if (handle == NULL) { krb5_cc_close(context, id); *minor_status = ENOMEM; return GSS_S_FAILURE; } handle->usage = GSS_C_INITIATE; krb5_cc_get_principal(context, id, &handle->principal); handle->ccache = id; handle->cred_flags = flags; *cred_handle = (gss_cred_id_t)handle; return GSS_S_COMPLETE; } heimdal-7.5.0/lib/gssapi/krb5/get_mic.c0000644000175000017500000002203213212137553015725 0ustar niknik/* * Copyright (c) 1997 - 2003 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "gsskrb5_locl.h" #ifdef HEIM_WEAK_CRYPTO static OM_uint32 mic_des (OM_uint32 * minor_status, const gsskrb5_ctx ctx, krb5_context context, gss_qop_t qop_req, const gss_buffer_t message_buffer, gss_buffer_t message_token, krb5_keyblock *key ) { u_char *p; EVP_MD_CTX *md5; u_char hash[16]; DES_key_schedule schedule; EVP_CIPHER_CTX des_ctx; DES_cblock deskey; DES_cblock zero; int32_t seq_number; size_t len, total_len; _gsskrb5_encap_length (22, &len, &total_len, GSS_KRB5_MECHANISM); message_token->length = total_len; message_token->value = malloc (total_len); if (message_token->value == NULL) { message_token->length = 0; *minor_status = ENOMEM; return GSS_S_FAILURE; } p = _gsskrb5_make_header(message_token->value, len, "\x01\x01", /* TOK_ID */ GSS_KRB5_MECHANISM); memcpy (p, "\x00\x00", 2); /* SGN_ALG = DES MAC MD5 */ p += 2; memcpy (p, "\xff\xff\xff\xff", 4); /* Filler */ p += 4; /* Fill in later (SND-SEQ) */ memset (p, 0, 16); p += 16; /* checksum */ md5 = EVP_MD_CTX_create(); EVP_DigestInit_ex(md5, EVP_md5(), NULL); EVP_DigestUpdate(md5, p - 24, 8); EVP_DigestUpdate(md5, message_buffer->value, message_buffer->length); EVP_DigestFinal_ex(md5, hash, NULL); EVP_MD_CTX_destroy(md5); memset (&zero, 0, sizeof(zero)); memcpy (&deskey, key->keyvalue.data, sizeof(deskey)); DES_set_key_unchecked (&deskey, &schedule); DES_cbc_cksum ((void *)hash, (void *)hash, sizeof(hash), &schedule, &zero); memcpy (p - 8, hash, 8); /* SGN_CKSUM */ HEIMDAL_MUTEX_lock(&ctx->ctx_id_mutex); /* sequence number */ krb5_auth_con_getlocalseqnumber (context, ctx->auth_context, &seq_number); p -= 16; /* SND_SEQ */ p[0] = (seq_number >> 0) & 0xFF; p[1] = (seq_number >> 8) & 0xFF; p[2] = (seq_number >> 16) & 0xFF; p[3] = (seq_number >> 24) & 0xFF; memset (p + 4, (ctx->more_flags & LOCAL) ? 0 : 0xFF, 4); EVP_CIPHER_CTX_init(&des_ctx); EVP_CipherInit_ex(&des_ctx, EVP_des_cbc(), NULL, key->keyvalue.data, p + 8, 1); EVP_Cipher(&des_ctx, p, p, 8); EVP_CIPHER_CTX_cleanup(&des_ctx); krb5_auth_con_setlocalseqnumber (context, ctx->auth_context, ++seq_number); HEIMDAL_MUTEX_unlock(&ctx->ctx_id_mutex); memset (deskey, 0, sizeof(deskey)); memset (&schedule, 0, sizeof(schedule)); *minor_status = 0; return GSS_S_COMPLETE; } #endif static OM_uint32 mic_des3 (OM_uint32 * minor_status, const gsskrb5_ctx ctx, krb5_context context, gss_qop_t qop_req, const gss_buffer_t message_buffer, gss_buffer_t message_token, krb5_keyblock *key ) { u_char *p; Checksum cksum; u_char seq[8]; int32_t seq_number; size_t len, total_len; krb5_crypto crypto; krb5_error_code kret; krb5_data encdata; char *tmp; char ivec[8]; _gsskrb5_encap_length (36, &len, &total_len, GSS_KRB5_MECHANISM); message_token->length = total_len; message_token->value = malloc (total_len); if (message_token->value == NULL) { message_token->length = 0; *minor_status = ENOMEM; return GSS_S_FAILURE; } p = _gsskrb5_make_header(message_token->value, len, "\x01\x01", /* TOK-ID */ GSS_KRB5_MECHANISM); memcpy (p, "\x04\x00", 2); /* SGN_ALG = HMAC SHA1 DES3-KD */ p += 2; memcpy (p, "\xff\xff\xff\xff", 4); /* filler */ p += 4; /* this should be done in parts */ tmp = malloc (message_buffer->length + 8); if (tmp == NULL) { free (message_token->value); message_token->value = NULL; message_token->length = 0; *minor_status = ENOMEM; return GSS_S_FAILURE; } memcpy (tmp, p - 8, 8); memcpy (tmp + 8, message_buffer->value, message_buffer->length); kret = krb5_crypto_init(context, key, 0, &crypto); if (kret) { free (message_token->value); message_token->value = NULL; message_token->length = 0; free (tmp); *minor_status = kret; return GSS_S_FAILURE; } kret = krb5_create_checksum (context, crypto, KRB5_KU_USAGE_SIGN, 0, tmp, message_buffer->length + 8, &cksum); free (tmp); krb5_crypto_destroy (context, crypto); if (kret) { free (message_token->value); message_token->value = NULL; message_token->length = 0; *minor_status = kret; return GSS_S_FAILURE; } memcpy (p + 8, cksum.checksum.data, cksum.checksum.length); HEIMDAL_MUTEX_lock(&ctx->ctx_id_mutex); /* sequence number */ krb5_auth_con_getlocalseqnumber (context, ctx->auth_context, &seq_number); seq[0] = (seq_number >> 0) & 0xFF; seq[1] = (seq_number >> 8) & 0xFF; seq[2] = (seq_number >> 16) & 0xFF; seq[3] = (seq_number >> 24) & 0xFF; memset (seq + 4, (ctx->more_flags & LOCAL) ? 0 : 0xFF, 4); kret = krb5_crypto_init(context, key, ETYPE_DES3_CBC_NONE, &crypto); if (kret) { free (message_token->value); message_token->value = NULL; message_token->length = 0; *minor_status = kret; return GSS_S_FAILURE; } if (ctx->more_flags & COMPAT_OLD_DES3) memset(ivec, 0, 8); else memcpy(ivec, p + 8, 8); kret = krb5_encrypt_ivec (context, crypto, KRB5_KU_USAGE_SEQ, seq, 8, &encdata, ivec); krb5_crypto_destroy (context, crypto); if (kret) { free (message_token->value); message_token->value = NULL; message_token->length = 0; *minor_status = kret; return GSS_S_FAILURE; } assert (encdata.length == 8); memcpy (p, encdata.data, encdata.length); krb5_data_free (&encdata); krb5_auth_con_setlocalseqnumber (context, ctx->auth_context, ++seq_number); HEIMDAL_MUTEX_unlock(&ctx->ctx_id_mutex); free_Checksum (&cksum); *minor_status = 0; return GSS_S_COMPLETE; } OM_uint32 GSSAPI_CALLCONV _gsskrb5_get_mic (OM_uint32 * minor_status, gss_const_ctx_id_t context_handle, gss_qop_t qop_req, const gss_buffer_t message_buffer, gss_buffer_t message_token ) { krb5_context context; const gsskrb5_ctx ctx = (const gsskrb5_ctx) context_handle; krb5_keyblock *key; OM_uint32 ret; GSSAPI_KRB5_INIT (&context); if (ctx->more_flags & IS_CFX) return _gssapi_mic_cfx (minor_status, ctx, context, qop_req, message_buffer, message_token); HEIMDAL_MUTEX_lock(&ctx->ctx_id_mutex); ret = _gsskrb5i_get_token_key(ctx, context, &key); HEIMDAL_MUTEX_unlock(&ctx->ctx_id_mutex); if (ret) { *minor_status = ret; return GSS_S_FAILURE; } switch (key->keytype) { case KRB5_ENCTYPE_DES_CBC_CRC : case KRB5_ENCTYPE_DES_CBC_MD4 : case KRB5_ENCTYPE_DES_CBC_MD5 : #ifdef HEIM_WEAK_CRYPTO ret = mic_des (minor_status, ctx, context, qop_req, message_buffer, message_token, key); #else ret = GSS_S_FAILURE; #endif break; case KRB5_ENCTYPE_DES3_CBC_MD5 : case KRB5_ENCTYPE_DES3_CBC_SHA1 : ret = mic_des3 (minor_status, ctx, context, qop_req, message_buffer, message_token, key); break; case KRB5_ENCTYPE_ARCFOUR_HMAC_MD5: case KRB5_ENCTYPE_ARCFOUR_HMAC_MD5_56: ret = _gssapi_get_mic_arcfour (minor_status, ctx, context, qop_req, message_buffer, message_token, key); break; default : abort(); break; } krb5_free_keyblock (context, key); return ret; } heimdal-7.5.0/lib/gssapi/gss-commands.in0000644000175000017500000000412413026237312016231 0ustar niknik/* * Copyright (c) 2006 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ /* $Id$ */ command = { name = "mechanisms" name = "supported-mechanisms" help = "Print the supported mechanisms" } command = { name = "attributes" name = "attrs-for-mech" help = "Print the attributes for mechs" option = { long = "all" type = "flag" } option = { long = "mech" type = "string" argument = "mechanism" } } command = { name = "help" name = "?" argument = "[command]" min_args = "0" max_args = "1" help = "Help! I need somebody." } heimdal-7.5.0/lib/gssapi/ChangeLog0000644000175000017500000026065112136107747015102 0ustar niknik2008-08-14 Love Hornquist Astrand * krb5/accept_sec_context.c: If there is a initiator subkey, copy that to acceptor subkey to match windows behavior. From Metze. 2008-08-02 Love Hörnquist Åstrand * ntlm/init_sec_context.c: Catch error * krb5/inquire_sec_context_by_oid.c: Catch store failure. * mech/gss_canonicalize_name.c: Not init m, return never used (overwritten later). 2008-07-25 Love Hörnquist Åstrand * ntlm/init_sec_context.c: Use krb5_cc_get_config. 2008-07-25 Love Hörnquist Åstrand * krb5/init_sec_context.c: Match the orignal patch I got from metze, seems that DCE-STYLE is even more weirer then what I though when I merged the patch. 2008-06-02 Love Hörnquist Åstrand * krb5/init_sec_context.c: Don't add asn1 wrapping to token when using DCE_STYLE. Patch from Stefan Metzmacher. 2008-05-27 Love Hörnquist Åstrand * ntlm/init_sec_context.c: use krb5_get_error_message 2008-05-05 Love Hörnquist Åstrand * spnego/spnego_locl.h: Add back "mech/utils.h", its needed for oid/buffer functions. 2008-05-02 Love Hörnquist Åstrand * spnego: Changes from doug barton to make spnego indepedant of the heimdal version of the plugin system. 2008-04-27 Love Hörnquist Åstrand * krb5: use DES_set_key_unchecked() 2008-04-17 Love Hörnquist Åstrand * add __declspec() for windows. 2008-04-15 Love Hörnquist Åstrand * krb5/import_sec_context.c: Use tmp to read ac->flags value to avoid warning. 2008-04-07 Love Hörnquist Åstrand * mech/gss_mech_switch.c: Use unsigned where appropriate. 2008-03-14 Love Hörnquist Åstrand * test_context.c: Add test for gsskrb5_register_acceptor_identity. 2008-03-09 Love Hörnquist Åstrand * krb5/init_sec_context.c (init_auth): use right variable to detect if we want to free or not. 2008-02-26 Love Hörnquist Åstrand * Makefile.am: add missing \ * Makefile.am: reshuffle depenencies * Add flag to krb5 to not add GSS-API INT|CONF to the negotiation 2008-02-21 Love Hörnquist Åstrand * make the SPNEGO mech store the error itself instead, works for everything except other stackable mechs 2008-02-18 Love Hörnquist Åstrand * spnego/init_sec_context.c (spnego_reply): if the reply token was of length 0, make it the same as no token. Pointed out by Zeqing Xia. * krb5/acquire_cred.c (acquire_initiator_cred): handle the credential cache better, use destroy/close when appriate and for all cases. Thanks to Michael Allen for point out the memory-leak that I also fixed. 2008-02-03 Love Hörnquist Åstrand * spnego/accept_sec_context.c: Make error reporting somewhat more correct for SPNEGO. 2008-01-27 Love Hörnquist Åstrand * test_common.c: Improve the error message. 2008-01-24 Love Hörnquist Åstrand * ntlm/accept_sec_context.c: Avoid free-ing type1 message before its allocated. 2008-01-13 Love Hörnquist Åstrand * test_ntlm.c: Test source name (and make the acceptor in ntlm gss mech useful). 2007-12-30 Love Hörnquist Åstrand * ntlm/init_sec_context.c: Don't confuse target name and source name, make regressiont tests pass again. 2007-12-29 Love Hörnquist Åstrand * ntlm: clean up name handling 2007-12-04 Love Hörnquist Åstrand * ntlm/init_sec_context.c: Use credential if it was passed in. * ntlm/acquire_cred.c: Check if there is initial creds with _gss_ntlm_get_user_cred(). * ntlm/init_sec_context.c: Add _gss_ntlm_get_user_info() that return the user info so it can be used by external modules. * ntlm/inquire_cred.c: use the right error code. * ntlm/inquire_cred.c: Return GSS_C_NO_CREDENTIAL if there is no credential, ntlm have (not yet) a default credential. * mech/gss_release_oid_set.c: Avoid trying to deref NULL, from Phil Fisher. 2007-12-03 Love Hörnquist Åstrand * test_acquire_cred.c: Always try to fetch cred (even with GSS_C_NO_NAME). 2007-08-09 Love Hörnquist Åstrand * mech/gss_krb5.c: Readd gss_krb5_get_tkt_flags. 2007-08-08 Love Hörnquist Åstrand * spnego/compat.c (_gss_spnego_internal_delete_sec_context): release ctx->target_name too From Rafal Malinowski. 2007-07-26 Love Hörnquist Åstrand * mech/gss_mech_switch.c: Don't try to do dlopen if system doesn't have dlopen. From Rune of Chalmers. 2007-07-10 Love Hörnquist Åstrand * mech/gss_duplicate_name.c: New signature of _gss_find_mn. * mech/gss_init_sec_context.c: New signature of _gss_find_mn. * mech/gss_acquire_cred.c: New signature of _gss_find_mn. * mech/name.h: New signature of _gss_find_mn. * mech/gss_canonicalize_name.c: New signature of _gss_find_mn. * mech/gss_compare_name.c: New signature of _gss_find_mn. * mech/gss_add_cred.c: New signature of _gss_find_mn. * mech/gss_names.c (_gss_find_mn): Return an error code for caller. * spnego/accept_sec_context.c: remove checks that are done by the previous function. * Makefile.am: New library version. 2007-07-04 Love Hörnquist Åstrand * mech/gss_oid_to_str.c: Refuse to print GSS_C_NULL_OID, from Rafal Malinowski. * spnego/spnego.asn1: Indent and make NegTokenInit and NegTokenResp extendable. 2007-06-21 Love Hörnquist Åstrand * ntlm/inquire_cred.c: Implement _gss_ntlm_inquire_cred. * mech/gss_display_status.c: Provide message for GSS_S_COMPLETE. * mech/context.c: If the canned string is "", its no use to the user, make it fall back to the default error string. 2007-06-20 Love Hörnquist Åstrand * mech/gss_display_name.c (gss_display_name): no name -> fail. From Rafal Malinswski. * spnego/accept_sec_context.c: Wrap name in a spnego_name instead of just a copy of the underlaying object. From Rafal Malinswski. * spnego/accept_sec_context.c: Handle underlaying mech not returning mn. * mech/gss_accept_sec_context.c: Handle underlaying mech not returning mn. * spnego/accept_sec_context.c: Make sure src_name is always set to GSS_C_NO_NAME when returning. * krb5/acquire_cred.c (acquire_acceptor_cred): don't claim everything is well on failure. From Phil Fisher. * mech/gss_duplicate_name.c: catch error (and ignore it) * ntlm/init_sec_context.c: Use heim_ntlm_calculate_ntlm2_sess. * mech/gss_accept_sec_context.c: Only wrap the delegated cred if we got a delegated mech cred. From Rafal Malinowski. * spnego/accept_sec_context.c: Only wrap the delegated cred if we are going to return it to the consumer. From Rafal Malinowski. * spnego/accept_sec_context.c: Fixed memory leak pointed out by Rafal Malinowski, also while here moved to use NegotiationToken for decoding. 2007-06-18 Love Hörnquist Åstrand * krb5/prf.c (_gsskrb5_pseudo_random): add missing break. * krb5/release_name.c: Set *minor_status unconditionallty, its done later anyway. * spnego/accept_sec_context.c: Init get_mic to 0. * mech/gss_set_cred_option.c: Free memory in failure case, found by beam. * mech/gss_inquire_context.c: Handle mech_type being NULL. * mech/gss_inquire_cred_by_mech.c: Handle cred_name being NULL. * mech/gss_krb5.c: Free memory in error case, found by beam. 2007-06-12 Love Hörnquist Åstrand * ntlm/inquire_context.c: Use ctx->gssflags for flags. * krb5/display_name.c: Use KRB5_PRINCIPAL_UNPARSE_DISPLAY, this is not ment for machine consumption. 2007-06-09 Love Hörnquist Åstrand * ntlm/digest.c (kdc_alloc): free memory on failure, pointed out by Rafal Malinowski. * ntlm/digest.c (kdc_destroy): free context when done, pointed out by Rafal Malinowski. * spnego/context_stubs.c (_gss_spnego_display_name): if input_name is null, fail. From Rafal Malinowski. 2007-06-04 Love Hörnquist Åstrand * ntlm/digest.c: Free memory when done. 2007-06-02 Love Hörnquist Åstrand * test_ntlm.c: Test both with and without keyex. * ntlm/digest.c: If we didn't set session key, don't expect one back. * test_ntlm.c: Set keyex flag and calculate session key. 2007-05-31 Love Hörnquist Åstrand * spnego/accept_sec_context.c: Use the return value before is overwritten by later calls. From Rafal Malinowski * krb5/release_cred.c: Give an minor_status argument to gss_release_oid_set. From Rafal Malinowski 2007-05-30 Love Hörnquist Åstrand * ntlm/accept_sec_context.c: Catch errors and return the up the stack. * test_kcred.c: more testing of lifetimes 2007-05-17 Love Hörnquist Åstrand * Makefile.am: Drop the gss oid_set function for the krb5 mech, use the mech glue versions instead. Pointed out by Rafal Malinowski. * krb5: Use gss oid_set functions from mechglue 2007-05-14 Love Hörnquist Åstrand * ntlm/accept_sec_context.c: Set session key only if we are returned a session key. Found by David Love. 2007-05-13 Love Hörnquist Åstrand * krb5/prf.c: switched MIN to min to make compile on solaris, pointed out by David Love. 2007-05-09 Love Hörnquist Åstrand * krb5/inquire_cred_by_mech.c: Fill in all of the variables if they are passed in. Pointed out by Phil Fisher. 2007-05-08 Love Hörnquist Åstrand * krb5/inquire_cred.c: Fix copy and paste error, bug spotted by from Phil Fisher. * mech: dont keep track of gc_usage, just figure it out at gss_inquire_cred() time * mech/gss_mech_switch.c (add_builtin): ok for __gss_mech_initialize() to return NULL * test_kcred.c: more correct tests * spnego/cred_stubs.c (gss_inquire_cred*): wrap the name with a spnego_name. * ntlm/inquire_cred.c: make ntlm gss_inquire_cred fail for now, need to find default cred and friends. * krb5/inquire_cred_by_mech.c: reimplement 2007-05-07 Love Hörnquist Åstrand * ntlm/acquire_cred.c: drop unused variable. * ntlm/acquire_cred.c: Reimplement. * Makefile.am: add ntlm/digest.c * ntlm: split out backend ntlm server processing 2007-04-24 Love Hörnquist Åstrand * ntlm/delete_sec_context.c (_gss_ntlm_delete_sec_context): free credcache when done 2007-04-22 Love Hörnquist Åstrand * ntlm/init_sec_context.c: ntlm-key credential entry is prefix with @ * ntlm/init_sec_context.c (get_user_ccache): pick up the ntlm creds from the krb5 credential cache. 2007-04-21 Love Hörnquist Åstrand * ntlm/delete_sec_context.c: free the key stored in the context * ntlm/ntlm.h: switch password for a key * test_oid.c: Switch oid to one that is exported. 2007-04-20 Love Hörnquist Åstrand * ntlm/init_sec_context.c: move where hash is calculated to make it easier to add ccache support. * Makefile.am: Add version-script.map to EXTRA_DIST. 2007-04-19 Love Hörnquist Åstrand * Makefile.am: Unconfuse newer versions of automake that doesn't know the diffrence between depenences and setting variables. foo: vs foo=. * test_ntlm.c: delete sec context when done. * version-script.map: export more symbols. * Makefile.am: add version script if ld supports it * version-script.map: add version script if ld supports it 2007-04-18 Love Hörnquist Åstrand * Makefile.am: test_acquire_cred need test_common.[ch] * test_acquire_cred.c: add more test options. * krb5/external.c: add GSS_KRB5_CCACHE_NAME_X * gssapi/gssapi_krb5.h: add GSS_KRB5_CCACHE_NAME_X * krb5/set_sec_context_option.c: refactor code, implement GSS_KRB5_CCACHE_NAME_X * mech/gss_krb5.c: reimplement gss_krb5_ccache_name 2007-04-17 Love Hörnquist Åstrand * spnego/cred_stubs.c: Need to import spnego name before we can use it as a gss_name_t. * test_acquire_cred.c: use this test as part of the regression suite. * mech/gss_acquire_cred.c (gss_acquire_cred): dont init cred->gc_mc every time in the loop. 2007-04-15 Love Hörnquist Åstrand * Makefile.am: add test_common.h 2007-02-16 Love Hörnquist Åstrand * gss_acquire_cred.3: Add link for gsskrb5_register_acceptor_identity. 2007-02-08 Love Hörnquist Åstrand * krb5/copy_ccache.c: Try to leak less memory in the failure case. 2007-01-31 Love Hörnquist Åstrand * mech/gss_display_status.c: Use right printf formater. * test_*.[ch]: split out the error printing function and try to return better errors 2007-01-30 Love Hörnquist Åstrand * krb5/init_sec_context.c: revert 1.75: (init_auth): only turn on GSS_C_CONF_FLAG and GSS_C_INT_FLAG if the caller requseted it. This is because Kerberos always support INT|CONF, matches behavior with MS and MIT. The creates problems for the GSS-SPNEGO mech. 2007-01-24 Love Hörnquist Åstrand * krb5/prf.c: constrain desired_output_len * krb5/external.c (krb5_mech): add _gsskrb5_pseudo_random * mech/gss_pseudo_random.c: Catch error from underlaying mech on failure. * Makefile.am: Add krb5/prf.c * krb5/prf.c: gss_pseudo_random for krb5 * test_context.c: Checks for gss_pseudo_random. * krb5/gkrb5_err.et: add KG_INPUT_TOO_LONG * Makefile.am: Add mech/gss_pseudo_random.c * gssapi/gssapi.h: try to load pseudo_random * mech/gss_mech_switch.c: try to load pseudo_random * mech/gss_pseudo_random.c: Add gss_pseudo_random. * gssapi_mech.h: Add hook for gm_pseudo_random. 2007-01-17 Love Hörnquist Åstrand * test_context.c: Don't assume bufer from gss_display_status is ok. * mech/gss_wrap_size_limit.c: Reset out variables. * mech/gss_wrap.c: Reset out variables. * mech/gss_verify_mic.c: Reset out variables. * mech/gss_utils.c: Reset out variables. * mech/gss_release_oid_set.c: Reset out variables. * mech/gss_release_cred.c: Reset out variables. * mech/gss_release_buffer.c: Reset variables. * mech/gss_oid_to_str.c: Reset out variables. * mech/gss_inquire_sec_context_by_oid.c: Fix reset out variables. * mech/gss_mech_switch.c: Reset out variables. * mech/gss_inquire_sec_context_by_oid.c: Reset out variables. * mech/gss_inquire_names_for_mech.c: Reset out variables. * mech/gss_inquire_cred_by_oid.c: Reset out variables. * mech/gss_inquire_cred_by_oid.c: Reset out variables. * mech/gss_inquire_cred_by_mech.c: Reset out variables. * mech/gss_inquire_cred.c: Reset out variables, fix memory leak. * mech/gss_inquire_context.c: Reset out variables. * mech/gss_init_sec_context.c: Zero out outbuffer on failure. * mech/gss_import_name.c: Reset out variables. * mech/gss_import_name.c: Reset out variables. * mech/gss_get_mic.c: Reset out variables. * mech/gss_export_name.c: Reset out variables. * mech/gss_encapsulate_token.c: Reset out variables. * mech/gss_duplicate_oid.c: Reset out variables. * mech/gss_duplicate_oid.c: Reset out variables. * mech/gss_duplicate_name.c: Reset out variables. * mech/gss_display_status.c: Reset out variables. * mech/gss_display_name.c: Reset out variables. * mech/gss_delete_sec_context.c: Reset out variables using propper macros. * mech/gss_decapsulate_token.c: Reset out variables using propper macros. * mech/gss_add_cred.c: Reset out variables. * mech/gss_acquire_cred.c: Reset out variables. * mech/gss_accept_sec_context.c: Reset out variables using propper macros. * mech/gss_init_sec_context.c: Reset out variables. * mech/mech_locl.h (_mg_buffer_zero): new macro that zaps a gss_buffer_t 2007-01-16 Love Hörnquist Åstrand * mech: sprinkel _gss_mg_error * mech/gss_display_status.c (gss_display_status): use _gss_mg_get_error to fetch the error from underlaying mech, if it failes, let do the regular dance for GSS-CODE version and a generic print-the-error code for MECH-CODE. * mech/gss_oid_to_str.c: Don't include the NUL in the length of the string. * mech/context.h: Protoypes for _gss_mg_. * mech/context.c: Glue to catch the error from the lower gss-api layer and save that for later so gss_display_status() can show the error. * gss.c: Detect NTLM. 2007-01-11 Love Hörnquist Åstrand * mech/gss_accept_sec_context.c: spelling 2007-01-04 Love Hörnquist Åstrand * Makefile.am: Include build (private) prototypes header files. * Makefile.am (ntlmsrc): add ntlm/ntlm-private.h 2006-12-28 Love Hörnquist Åstrand * ntlm/accept_sec_context.c: Pass signseal argument to _gss_ntlm_set_key. * ntlm/init_sec_context.c: Pass signseal argument to _gss_ntlm_set_key. * ntlm/crypto.c (_gss_ntlm_set_key): add signseal argument * test_ntlm.c: add ntlmv2 test * ntlm/ntlm.h: break out struct ntlmv2_key; * ntlm/crypto.c (_gss_ntlm_set_key): set ntlm v2 keys. * ntlm/accept_sec_context.c: Set dummy ntlmv2 keys and Check TI. * ntlm/ntlm.h: NTLMv2 keys. * ntlm/crypto.c: NTLMv2 sign and verify. 2006-12-20 Love Hörnquist Åstrand * ntlm/accept_sec_context.c: Don't send targetinfo now. * ntlm/init_sec_context.c: Build ntlmv2 answer buffer. * ntlm/init_sec_context.c: Leak less memory. * ntlm/init_sec_context.c: Announce that we support key exchange. * ntlm/init_sec_context.c: Add NTLM_NEG_NTLM2_SESSION, NTLMv2 session security (disable because missing sign and seal). 2006-12-19 Love Hörnquist Åstrand * ntlm/accept_sec_context.c: split RC4 send and recv keystreams * ntlm/init_sec_context.c: split RC4 send and recv keystreams * ntlm/ntlm.h: split RC4 send and recv keystreams * ntlm/crypto.c: Implement SEAL. * ntlm/crypto.c: move gss_wrap/gss_unwrap here * test_context.c: request INT and CONF from the gss layer, test get and verify MIC. * ntlm/ntlm.h: add crypto bits. * ntlm/accept_sec_context.c: Save session master key. * Makefile.am: Move get and verify mic to the same file (crypto.c) since they share code. * ntlm/crypto.c: Move get and verify mic to the same file since they share code, implement NTLM v1 and dummy signatures. * ntlm/init_sec_context.c: pass on GSS_C_CONF_FLAG and GSS_C_INTEG_FLAG, save the session master key * spnego/accept_sec_context.c: try using gss_accept_sec_context() on the opportunistic token instead of guessing the acceptor name and do gss_acquire_cred, this make SPNEGO work like before. 2006-12-18 Love Hörnquist Åstrand * ntlm/init_sec_context.c: Calculate the NTLM version 1 "master" key. * spnego/accept_sec_context.c: Resurect negHints for the acceptor sends first packet. * Makefile.am: Add "windows" versions of the NegTokenInitWin and friends. * test_context.c: add --wrapunwrap flag * spnego/compat.c: move _gss_spnego_indicate_mechtypelist() to compat.c, use the sequence types of MechTypeList, make add_mech_type() static. * spnego/accept_sec_context.c: move _gss_spnego_indicate_mechtypelist() to compat.c * Makefile.am: Generate sequence code for MechTypeList * spnego: check that the generated acceptor mechlist is acceptable too * spnego/init_sec_context.c: Abstract out the initiator filter function, it will be needed for the acceptor too. * spnego/accept_sec_context.c: Abstract out the initiator filter function, it will be needed for the acceptor too. Remove negHints. * test_context.c: allow asserting return mech * ntlm/accept_sec_context.c: add _gss_ntlm_allocate_ctx * ntlm/acquire_cred.c: Check that the KDC seem to there and answering us, we can't do better then that wen checking if we will accept the credential. * ntlm/get_mic.c: return GSS_S_UNAVAILABLE * mech/utils.h: add _gss_free_oid, reverse of _gss_copy_oid * mech/gss_utils.c: add _gss_free_oid, reverse of _gss_copy_oid * spnego/spnego.asn1: Its very sad, but NegHints its are not part of the NegTokenInit, this makes SPNEGO acceptor life a lot harder. * spnego: try harder to handle names better. handle missing acceptor and initator creds better (ie dont propose/accept mech that there are no credentials for) split NegTokenInit and NegTokenResp in acceptor 2006-12-16 Love Hörnquist Åstrand * ntlm/import_name.c: Allocate the buffer from the right length. 2006-12-15 Love Hörnquist Åstrand * ntlm/init_sec_context.c (init_sec_context): Tell the other side what domain we think we are talking to. * ntlm/delete_sec_context.c: free username and password * ntlm/release_name.c (_gss_ntlm_release_name): free name. * ntlm/import_name.c (_gss_ntlm_import_name): add support for GSS_C_NT_HOSTBASED_SERVICE names * ntlm/ntlm.h: Add ntlm_name. * test_context.c: allow testing of ntlm. * gssapi_mech.h: add __gss_ntlm_initialize * ntlm/accept_sec_context.c (handle_type3): verify that the kdc approved of the ntlm exchange too * mech/gss_mech_switch.c: Add the builtin ntlm mech * test_ntlm.c: NTLM test app. * mech/gss_accept_sec_context.c: Add detection of NTLMSSP. * gssapi/gssapi.h: add ntlm mech oid * ntlm/external.c: Switch OID to the ms ntlmssp oid * Makefile.am: Add ntlm gss-api module. * ntlm/accept_sec_context.c: Catch more error errors. * ntlm/accept_sec_context.c: Check after a credential to use. 2006-12-14 Love Hörnquist Åstrand * krb5/set_sec_context_option.c (GSS_KRB5_SET_DEFAULT_REALM_X): don't fail on success. Bug report from Stefan Metzmacher. 2006-12-13 Love Hörnquist Åstrand * krb5/init_sec_context.c (init_auth): only turn on GSS_C_CONF_FLAG and GSS_C_INT_FLAG if the caller requseted it. From Stefan Metzmacher. 2006-12-11 Love Hörnquist Åstrand * Makefile.am (libgssapi_la_OBJECTS): depends on gssapi_asn1.h spnego_asn1.h. 2006-11-20 Love Hörnquist Åstrand * krb5/acquire_cred.c: Make krb5_get_init_creds_opt_free take a context argument. 2006-11-16 Love Hörnquist Åstrand * test_context.c: Test that token keys are the same, return actual_mech. 2006-11-15 Love Hörnquist Åstrand * spnego/spnego_locl.h: Make bitfields unsigned, add maybe_open. * spnego/accept_sec_context.c: Use ASN.1 encoder functions to encode CHOICE structure now that we can handle it. * spnego/init_sec_context.c: Use ASN.1 encoder functions to encode CHOICE structure now that we can handle it. * spnego/accept_sec_context.c (_gss_spnego_accept_sec_context): send back ad accept_completed when the security context is ->open, w/o this the client doesn't know that the server have completed the transaction. * test_context.c: Add delegate flag and check that the delegated cred works. * spnego/init_sec_context.c: Keep track of the opportunistic token in the inital message, it might be a complete gss-api context, in that case we'll get back accept_completed without any token. With this change, krb5 w/o mutual authentication works. * spnego/accept_sec_context.c: Use ASN.1 encoder functions to encode CHOICE structure now that we can handle it. * spnego/accept_sec_context.c: Filter out SPNEGO from the out supported mechs list and make sure we don't select that for the preferred mechamism. 2006-11-14 Love Hörnquist Åstrand * mech/gss_init_sec_context.c (_gss_mech_cred_find): break out the cred finding to its own function * krb5/wrap.c: Better error strings, from Andrew Bartlet. 2006-11-13 Love Hörnquist Åstrand * test_context.c: Create our own krb5_context. * krb5: Switch from using a specific error message context in the TLS to have a whole krb5_context in TLS. This have some interestion side-effekts for the configruration setting options since they operate on per-thread basis now. * mech/gss_set_cred_option.c: When calling ->gm_set_cred_option and checking for success, use GSS_S_COMPLETE. From Andrew Bartlet. 2006-11-12 Love Hörnquist Åstrand * Makefile.am: Help solaris make even more. * Makefile.am: Help solaris make. 2006-11-09 Love Hörnquist Åstrand * Makefile.am: remove include $(srcdir)/Makefile-digest.am for now * mech/gss_accept_sec_context.c: Try better guessing what is mech we are going to select by looking harder at the input_token, idea from Luke Howard's mechglue branch. * Makefile.am: libgssapi_la_OBJECTS: add depency on gkrb5_err.h * gssapi/gssapi_krb5.h: add GSS_KRB5_SET_ALLOWABLE_ENCTYPES_X * mech/gss_krb5.c: implement gss_krb5_set_allowable_enctypes * gssapi/gssapi.h: GSS_KRB5_S_ * krb5/gsskrb5_locl.h: Include . * gssapi/gssapi_krb5.h: Add gss_krb5_set_allowable_enctypes. * Makefile.am: Build and install gkrb5_err.h * krb5/gkrb5_err.et: Move the GSS_KRB5_S error here. 2006-11-08 Love Hörnquist Åstrand * mech/gss_krb5.c: Add gsskrb5_set_default_realm. * krb5/set_sec_context_option.c: Support GSS_KRB5_SET_DEFAULT_REALM_X. * gssapi/gssapi_krb5.h: add GSS_KRB5_SET_DEFAULT_REALM_X * krb5/external.c: add GSS_KRB5_SET_DEFAULT_REALM_X 2006-11-07 Love Hörnquist Åstrand * test_context.c: rename krb5_[gs]et_time_wrap to krb5_[gs]et_max_time_skew * krb5/copy_ccache.c: _gsskrb5_extract_authz_data_from_sec_context no longer used, bye bye * mech/gss_krb5.c: No depenency of the krb5 gssapi mech. * mech/gss_krb5.c (gsskrb5_extract_authtime_from_sec_context): use _gsskrb5_decode_om_uint32. From Andrew Bartlet. * mech/gss_krb5.c: Add dummy gss_krb5_set_allowable_enctypes for now. * spnego/spnego_locl.h: Include for compatiblity. * krb5/arcfour.c: Use IS_DCE_STYLE flag. There is no padding in DCE-STYLE, don't try to use to. From Andrew Bartlett. * test_context.c: test wrap/unwrap, add flag for dce-style and mutual auth, also support multi-roundtrip sessions * krb5/gsskrb5_locl.h: Add IS_DCE_STYLE macro. * krb5/accept_sec_context.c (gsskrb5_acceptor_start): use krb5_rd_req_ctx * mech/gss_krb5.c (gsskrb5_get_subkey): return the per message token subkey * krb5/inquire_sec_context_by_oid.c: check if there is any key at all 2006-11-06 Love Hörnquist Åstrand * krb5/inquire_sec_context_by_oid.c: Set more error strings, use right enum for acceptor subkey. From Andrew Bartlett. 2006-11-04 Love Hörnquist Åstrand * test_context.c: Test gsskrb5_extract_service_keyblock, needed in PAC valication. From Andrew Bartlett * mech/gss_krb5.c: Add gsskrb5_extract_authz_data_from_sec_context and keyblock extraction functions. * gssapi/gssapi_krb5.h: Add extraction of keyblock function, from Andrew Bartlett. * krb5/external.c: Add GSS_KRB5_GET_SERVICE_KEYBLOCK_X 2006-11-03 Love Hörnquist Åstrand * test_context.c: Rename various routines and constants from canonize to canonicalize. From Andrew Bartlett * mech/gss_krb5.c: Rename various routines and constants from canonize to canonicalize. From Andrew Bartlett * krb5/set_sec_context_option.c: Rename various routines and constants from canonize to canonicalize. From Andrew Bartlett * krb5/external.c: Rename various routines and constants from canonize to canonicalize. From Andrew Bartlett * gssapi/gssapi_krb5.h: Rename various routines and constants from canonize to canonicalize. From Andrew Bartlett 2006-10-25 Love Hörnquist Åstrand * krb5/accept_sec_context.c (gsskrb5_accept_delegated_token): need to free ccache 2006-10-24 Love Hörnquist Åstrand * test_context.c (loop): free target_name * mech/gss_accept_sec_context.c: SLIST_INIT the ->gc_mc' * mech/gss_acquire_cred.c : SLIST_INIT the ->gc_mc' * krb5/init_sec_context.c: Avoid leaking memory. * mech/gss_buffer_set.c (gss_release_buffer_set): don't leak the ->elements memory. * test_context.c: make compile * krb5/cfx.c (_gssapi_verify_mic_cfx): always free crypto context. * krb5/set_cred_option.c (import_cred): free sp 2006-10-22 Love Hörnquist Åstrand * mech/gss_add_oid_set_member.c: Use old implementation of gss_add_oid_set_member, it leaks less memory. * krb5/test_cfx.c: free krb5_crypto. * krb5/test_cfx.c: free krb5_context * mech/gss_release_name.c (gss_release_name): free input_name it-self. 2006-10-21 Love Hörnquist Åstrand * test_context.c: Call setprogname. * mech/gss_krb5.c: Add gsskrb5_extract_authtime_from_sec_context. * gssapi/gssapi_krb5.h: add gsskrb5_extract_authtime_from_sec_context 2006-10-20 Love Hörnquist Åstrand * krb5/inquire_sec_context_by_oid.c: Add get_authtime. * krb5/external.c: add GSS_KRB5_GET_AUTHTIME_X * gssapi/gssapi_krb5.h: add GSS_KRB5_GET_AUTHTIME_X * krb5/set_sec_context_option.c: Implement GSS_KRB5_SEND_TO_KDC_X. * mech/gss_krb5.c: Add gsskrb5_set_send_to_kdc * gssapi/gssapi_krb5.h: Add GSS_KRB5_SEND_TO_KDC_X and gsskrb5_set_send_to_kdc * krb5/external.c: add GSS_KRB5_SEND_TO_KDC_X * Makefile.am: more files 2006-10-19 Love Hörnquist Åstrand * Makefile.am: remove spnego/gssapi_spnego.h, its now in gssapi/ * test_context.c: Allow specifing mech. * krb5/external.c: add GSS_SASL_DIGEST_MD5_MECHANISM (for now) * gssapi/gssapi.h: Rename GSS_DIGEST_MECHANISM to GSS_SASL_DIGEST_MD5_MECHANISM 2006-10-18 Love Hörnquist Åstrand * mech/gssapi.asn1: Make it into a heim_any_set, its doesn't except a tag. * mech/gssapi.asn1: GSSAPIContextToken is IMPLICIT SEQUENCE * gssapi/gssapi_krb5.h: add GSS_KRB5_GET_ACCEPTOR_SUBKEY_X * krb5/external.c: Add GSS_KRB5_GET_ACCEPTOR_SUBKEY_X. * gssapi/gssapi_krb5.h: add GSS_KRB5_GET_INITIATOR_SUBKEY_X and GSS_KRB5_GET_SUBKEY_X * krb5/external.c: add GSS_KRB5_GET_INITIATOR_SUBKEY_X, GSS_KRB5_GET_SUBKEY_X 2006-10-17 Love Hörnquist Åstrand * test_context.c: Support switching on name type oid's * test_context.c: add test for dns canon flag * mech/gss_krb5.c: Add gsskrb5_set_dns_canonlize. * gssapi/gssapi_krb5.h: remove gss_krb5_compat_des3_mic * gssapi/gssapi_krb5.h: Add gsskrb5_set_dns_canonlize. * krb5/set_sec_context_option.c: implement GSS_KRB5_SET_DNS_CANONIZE_X * gssapi/gssapi_krb5.h: add GSS_KRB5_SET_DNS_CANONIZE_X * krb5/external.c: add GSS_KRB5_SET_DNS_CANONIZE_X * mech/gss_krb5.c: add bits to make lucid context work 2006-10-14 Love Hörnquist Åstrand * mech/gss_oid_to_str.c: Prefix der primitives with der_. * krb5/inquire_sec_context_by_oid.c: Prefix der primitives with der_. * krb5/encapsulate.c: Prefix der primitives with der_. * mech/gss_oid_to_str.c: New der_print_heim_oid signature. 2006-10-12 Love Hörnquist Åstrand * Makefile.am: add test_context * krb5/inquire_sec_context_by_oid.c: Make it work. * test_oid.c: Test lucid oid. * gssapi/gssapi.h: Add OM_uint64_t. * krb5/inquire_sec_context_by_oid.c: Add lucid interface. * krb5/external.c: Add lucid interface, renumber oids to my delegated space. * mech/gss_krb5.c: Add lucid interface. * gssapi/gssapi_krb5.h: Add lucid interface. * spnego/spnego_locl.h: Maybe include . 2006-10-09 Love Hörnquist Åstrand * mech/gss_mech_switch.c: define RTLD_LOCAL to 0 if not defined. 2006-10-08 Love Hörnquist Åstrand * Makefile.am: install gssapi_krb5.H and gssapi_spnego.h * gssapi/gssapi_krb5.h: Move krb5 stuff to . * gssapi/gssapi.h: Move krb5 stuff to . * Makefile.am: Drop some -I no longer needed. * gssapi/gssapi_spnego.h: Move gssapi_spengo.h over here. * krb5: reference all include files using 'krb5/' 2006-10-07 Love Hörnquist Åstrand * gssapi.h: Add file inclusion protection. * gssapi/gssapi.h: Correct header file inclusion protection. * gssapi/gssapi.h: Move the gssapi.h from lib/gssapi/ to lib/gssapi/gssapi/ to please automake. * spnego/spnego_locl.h: Maybe include . * mech/mech_locl.h: Include . * Makefile.am: split build files into dist_ and noinst_ SOURCES 2006-10-06 Love Hörnquist Åstrand * gss.c: #if 0 out unused code. * mech/gss_mech_switch.c: Cast argument to ctype(3) functions to (unsigned char). 2006-10-05 Love Hörnquist Åstrand * mech/name.h: remove * mech/mech_switch.h: remove * mech/cred.h: remove 2006-10-02 Love Hörnquist Åstrand * krb5/arcfour.c: Thinker more with header lengths. * krb5/arcfour.c: Improve the calcucation of header lengths. DCE-STYLE data is also padded so remove if (1 || ...) code. * krb5/wrap.c (_gsskrb5_wrap_size_limit): use _gssapi_wrap_size_arcfour for arcfour * krb5/arcfour.c: Move _gssapi_wrap_size_arcfour here. * Makefile.am: Split all mech to diffrent mechsrc variables. * spnego/context_stubs.c: Make internal function static (and rename). 2006-10-01 Love Hörnquist Åstrand * krb5/inquire_cred.c: Fix "if (x) lock(y)" bug. From Harald Barth. * spnego/spnego_locl.h: Include for MAXHOSTNAMELEN. 2006-09-25 Love Hörnquist Åstrand * krb5/arcfour.c: Add wrap support, interrop with itself but not w2k3s-sp1 * krb5/gsskrb5_locl.h: move the arcfour specific stuff to the arcfour header. * krb5/arcfour.c: Support DCE-style unwrap, tested with w2k3server-sp1. * mech/gss_accept_sec_context.c (gss_accept_sec_context): if the token doesn't start with [APPLICATION 0] SEQUENCE, lets assume its a DCE-style kerberos 5 connection. XXX this needs to be made better in cause we get another GSS-API protocol violating protocol. It should be possible to detach the Kerberos DCE-style since it starts with a AP-REQ PDU, but that have to wait for now. 2006-09-22 Love Hörnquist Åstrand * gssapi.h: Add GSS_C flags from draft-brezak-win2k-krb-rc4-hmac-04.txt. * krb5/delete_sec_context.c: Free service_keyblock and fwd_data, indent. * krb5/accept_sec_context.c: Merge of the acceptor part from the samba patch by Stefan Metzmacher and Andrew Bartlet. * krb5/init_sec_context.c: Add GSS_C_DCE_STYLE. * krb5/{init_sec_context.c,gsskrb5_locl.h}: merge most of the initiator part from the samba patch by Stefan Metzmacher and Andrew Bartlet (still missing DCE/RPC support) 2006-08-28 Love Hörnquist Åstrand * gss.c (help): use sl_slc_help(). 2006-07-22 Love Hörnquist Åstrand * gss-commands.in: rename command to supported-mechanisms * Makefile.am: Make gss objects depend on the slc built gss-commands.h 2006-07-20 Love Hörnquist Åstrand * gss-commands.in: add slc commands for gss * krb5/gsskrb5_locl.h: Remove dup prototype of _gsskrb5_init() * Makefile.am: Add test_cfx * krb5/external.c: add GSS_KRB5_REGISTER_ACCEPTOR_IDENTITY_X * krb5/set_sec_context_option.c: catch GSS_KRB5_REGISTER_ACCEPTOR_IDENTITY_X * krb5/accept_sec_context.c: reimplement gsskrb5_register_acceptor_identity * mech/gss_krb5.c: implement gsskrb5_register_acceptor_identity * mech/gss_inquire_mechs_for_name.c: call _gss_load_mech * mech/gss_inquire_cred.c (gss_inquire_cred): call _gss_load_mech * mech/gss_mech_switch.c: Make _gss_load_mech() atomic and run only once, this have the side effect that _gss_mechs and _gss_mech_oids is only initialized once, so if just the users of these two global variables calls _gss_load_mech() first, it will act as a barrier and make sure the variables are never changed and we don't need to lock them. * mech/utils.h: no need to mark functions extern. * mech/name.h: no need to mark _gss_find_mn extern. 2006-07-19 Love Hörnquist Åstrand * krb5/cfx.c: Redo the wrap length calculations. * krb5/test_cfx.c: test max_wrap_size in cfx.c * mech/gss_display_status.c: Handle more error codes. 2006-07-07 Love Hörnquist Åstrand * mech/mech_locl.h: Include and "mechqueue.h" * mech/mechqueue.h: Add SLIST macros. * krb5/inquire_context.c: Don't free return values on success. * krb5/inquire_cred.c (_gsskrb5_inquire_cred): When cred provided is the default cred, acquire the acceptor cred and initator cred in two diffrent steps and then query them for the information, this way, the code wont fail if there are no keytab, but there is a credential cache. * mech/gss_inquire_cred.c: move the check if we found any cred where it matter for both cases (default cred and provided cred) * mech/gss_init_sec_context.c: If the desired mechanism can't convert the name to a MN, fail with GSS_S_BAD_NAME rather then a NULL de-reference. 2006-07-06 Love Hörnquist Åstrand * spnego/external.c: readd gss_spnego_inquire_names_for_mech * spnego/spnego_locl.h: reimplement gss_spnego_inquire_names_for_mech add support function _gss_spnego_supported_mechs * spnego/context_stubs.h: reimplement gss_spnego_inquire_names_for_mech add support function _gss_spnego_supported_mechs * spnego/context_stubs.c: drop gss_spnego_indicate_mechs * mech/gss_indicate_mechs.c: if the underlaying mech doesn't support gss_indicate_mechs, use the oid in the mechswitch structure * spnego/external.c: let the mech glue layer implement gss_indicate_mechs * spnego/cred_stubs.c (gss_spnego_acquire_cred): don't care about desired_mechs, get our own list with indicate_mechs and remove ourself. 2006-07-05 Love Hörnquist Åstrand * spnego/external.c: remove gss_spnego_inquire_names_for_mech, let the mechglue layer implement it * spnego/context_stubs.c: remove gss_spnego_inquire_names_for_mech, let the mechglue layer implement it * spnego/spnego_locl.c: remove gss_spnego_inquire_names_for_mech, let the mechglue layer implement it 2006-07-01 Love Hörnquist Åstrand * mech/gss_set_cred_option.c: fix argument to gss_release_cred 2006-06-30 Love Hörnquist Åstrand * krb5/init_sec_context.c: Make work on compilers that are somewhat more picky then gcc4 (like gcc2.95) * krb5/init_sec_context.c (do_delegation): use KDCOptions2int to convert fwd_flags to an integer, since otherwise int2KDCOptions in krb5_get_forwarded_creds wont do the right thing. * mech/gss_set_cred_option.c (gss_set_cred_option): free memory on failure * krb5/set_sec_context_option.c (_gsskrb5_set_sec_context_option): init global kerberos context * krb5/set_cred_option.c (_gsskrb5_set_cred_option): init global kerberos context * mech/gss_accept_sec_context.c: Insert the delegated sub cred on the delegated cred handle, not cred handle * mech/gss_accept_sec_context.c (gss_accept_sec_context): handle the case where ret_flags == NULL * mech/gss_mech_switch.c (add_builtin): set _gss_mech_switch->gm_mech_oid * mech/gss_set_cred_option.c (gss_set_cred_option): laod mechs * test_cred.c (gss_print_errors): don't try to print error when gss_display_status failed * Makefile.am: Add mech/gss_release_oid.c * mech/gss_release_oid.c: Add gss_release_oid, reverse of gss_duplicate_oid * spnego/compat.c: preferred_mech_type was allocated with gss_duplicate_oid in one place and assigned static varianbles a the second place. change that static assignement to gss_duplicate_oid and bring back gss_release_oid. * spnego/compat.c (_gss_spnego_delete_sec_context): don't release preferred_mech_type and negotiated_mech_type, they where never allocated from the begining. 2006-06-29 Love Hörnquist Åstrand * mech/gss_import_name.c (gss_import_name): avoid type-punned/strict aliasing rules * mech/gss_add_cred.c: avoid type-punned/strict aliasing rules * gssapi.h: Make gss_name_t an opaque type. * krb5: make gss_name_t an opaque type * krb5/set_cred_option.c: Add * mech/gss_set_cred_option.c (gss_set_cred_option): support the case where *cred_handle == NULL * mech/gss_krb5.c (gss_krb5_import_cred): make sure cred is GSS_C_NO_CREDENTIAL on failure. * mech/gss_acquire_cred.c (gss_acquire_cred): if desired_mechs is NO_OID_SET, there is a need to load the mechs, so always do that. 2006-06-28 Love Hörnquist Åstrand * krb5/inquire_cred_by_oid.c: Reimplement GSS_KRB5_COPY_CCACHE_X to instead pass a fullname to the credential, then resolve and copy out the content, and then close the cred. * mech/gss_krb5.c: Reimplement GSS_KRB5_COPY_CCACHE_X to instead pass a fullname to the credential, then resolve and copy out the content, and then close the cred. * krb5/inquire_cred_by_oid.c: make "work", GSS_KRB5_COPY_CCACHE_X interface needs to be re-done, currently its utterly broken. * mech/gss_set_cred_option.c: Make work. * krb5/external.c: Add _gsskrb5_set_{sec_context,cred}_option * mech/gss_krb5.c (gss_krb5_import_cred): implement * Makefile.am: Add gss_set_{sec_context,cred}_option and sort * mech/gss_set_{sec_context,cred}_option.c: add * gssapi.h: Add GSS_KRB5_IMPORT_CRED_X * test_*.c: make compile again * Makefile.am: Add lib dependencies and test programs * spnego: remove dependency on libkrb5 * mech: Bug fixes, cleanup, compiler warnings, restructure code. * spnego: Rename gss_context_id_t and gss_cred_id_t to local names * krb5: repro copy the krb5 files here * mech: import Doug Rabson mechglue from freebsd * spnego: Import Luke Howard's SPNEGO from the mechglue branch 2006-06-22 Love Hörnquist Åstrand * gssapi.h: Add oid_to_str. * Makefile.am: add oid_to_str and test_oid * oid_to_str.c: Add gss_oid_to_str * test_oid.c: Add test for gss_oid_to_str() 2006-05-13 Love Hörnquist Åstrand * verify_mic.c: Less pointer signedness warnings. * unwrap.c: Less pointer signedness warnings. * arcfour.c: Less pointer signedness warnings. * gssapi_locl.h: Use const void * to instead of unsigned char * to avoid pointer signedness warnings. * encapsulate.c: Use const void * to instead of unsigned char * to avoid pointer signedness warnings. * decapsulate.c: Use const void * to instead of unsigned char * to avoid pointer signedness warnings. * decapsulate.c: Less pointer signedness warnings. * cfx.c: Less pointer signedness warnings. * init_sec_context.c: Less pointer signedness warnings (partly by using the new asn.1 CHOICE decoder) * import_sec_context.c: Less pointer signedness warnings. 2006-05-09 Love Hörnquist Åstrand * accept_sec_context.c (gsskrb5_is_cfx): always set is_cfx. From Andrew Abartlet. 2006-05-08 Love Hörnquist Åstrand * get_mic.c (mic_des3): make sure message_buffer doesn't point to free()ed memory on failure. Pointed out by IBM checker. 2006-05-05 Love Hörnquist Åstrand * Rename u_intXX_t to uintXX_t 2006-05-04 Love Hörnquist Åstrand * cfx.c: Less pointer signedness warnings. * arcfour.c: Avoid pointer signedness warnings. * gssapi_locl.h (gssapi_decode_*): make data argument const void * * 8003.c (gssapi_decode_*): make data argument const void * 2006-04-12 Love Hörnquist Åstrand * export_sec_context.c: Export sequence order element. From Wynn Wilkes . * import_sec_context.c: Import sequence order element. From Wynn Wilkes . * sequence.c (_gssapi_msg_order_import,_gssapi_msg_order_export): New functions, used by {import,export}_sec_context. From Wynn Wilkes . * test_sequence.c: Add test for import/export sequence. 2006-04-09 Love Hörnquist Åstrand * add_cred.c: Check that cred != GSS_C_NO_CREDENTIAL, this is a standard conformance failure, but much better then a crash. 2006-04-02 Love Hörnquist Åstrand * get_mic.c (get_mic*)_: make sure message_token is cleaned on error, found by IBM checker. * wrap.c (wrap*): Reset output_buffer on error, found by IBM checker. 2006-02-15 Love Hörnquist Åstrand * import_name.c: Accept both GSS_C_NT_HOSTBASED_SERVICE and GSS_C_NT_HOSTBASED_SERVICE_X as nametype for hostbased names. 2006-01-16 Love Hörnquist Åstrand * delete_sec_context.c (gss_delete_sec_context): if the context handle is GSS_C_NO_CONTEXT, don't fall over. 2005-12-12 Love Hörnquist Åstrand * gss_acquire_cred.3: Replace gss_krb5_import_ccache with gss_krb5_import_cred and add more references 2005-12-05 Love Hörnquist Åstrand * gssapi.h: Change gss_krb5_import_ccache to gss_krb5_import_cred, it can handle keytabs too. * add_cred.c (gss_add_cred): avoid deadlock * context_time.c (gssapi_lifetime_left): define the 0 lifetime as GSS_C_INDEFINITE. 2005-12-01 Love Hörnquist Åstrand * acquire_cred.c (acquire_acceptor_cred): only check if principal exists if we got called with principal as an argument. * acquire_cred.c (acquire_acceptor_cred): check that the acceptor exists in the keytab before returning ok. 2005-11-29 Love Hörnquist Åstrand * copy_ccache.c (gss_krb5_import_cred): fix buglet, from Andrew Bartlett. 2005-11-25 Love Hörnquist Åstrand * test_kcred.c: Rename gss_krb5_import_ccache to gss_krb5_import_cred. * copy_ccache.c: Rename gss_krb5_import_ccache to gss_krb5_import_cred and let it grow code to handle keytabs too. 2005-11-02 Love Hörnquist Åstrand * init_sec_context.c: Change sematics of ok-as-delegate to match windows if [gssapi]realm/ok-as-delegate=true is set, otherwise keep old sematics. * release_cred.c (gss_release_cred): use GSS_CF_DESTROY_CRED_ON_RELEASE to decide if the cache should be krb5_cc_destroy-ed * acquire_cred.c (acquire_initiator_cred): GSS_CF_DESTROY_CRED_ON_RELEASE on created credentials. * accept_sec_context.c (gsskrb5_accept_delegated_token): rewrite to use gss_krb5_import_ccache 2005-11-01 Love Hörnquist Åstrand * arcfour.c: Remove signedness warnings. 2005-10-31 Love Hörnquist Åstrand * gss_acquire_cred.3: Document that gss_krb5_import_ccache is copy by reference. * copy_ccache.c (gss_krb5_import_ccache): Instead of making a copy of the ccache, make a reference by getting the name and resolving the name. This way the cache is shared, this flipp side is of course that if someone calls krb5_cc_destroy the cache is lost for everyone. * test_kcred.c: Remove memory leaks. 2005-10-26 Love Hörnquist Åstrand * Makefile.am: build test_kcred * gss_acquire_cred.3: Document gss_krb5_import_ccache * gssapi.3: Sort and add gss_krb5_import_ccache. * acquire_cred.c (_gssapi_krb5_ccache_lifetime): break out code used to extract lifetime from a credential cache * gssapi_locl.h: Add _gssapi_krb5_ccache_lifetime, used to extract lifetime from a credential cache. * gssapi.h: add gss_krb5_import_ccache, reverse of gss_krb5_copy_ccache * copy_ccache.c: add gss_krb5_import_ccache, reverse of gss_krb5_copy_ccache * test_kcred.c: test gss_krb5_import_ccache 2005-10-21 Love Hörnquist Åstrand * acquire_cred.c (acquire_initiator_cred): use krb5_cc_cache_match to find a matching creditial cache, if that failes, fallback to the default cache. 2005-10-12 Love Hörnquist Åstrand * gssapi_locl.h: Add gssapi_krb5_set_status and gssapi_krb5_clear_status * init_sec_context.c (spnego_reply): Don't pass back raw Kerberos errors, use GSS-API errors instead. From Michael B Allen. * display_status.c: Add gssapi_krb5_clear_status, gssapi_krb5_set_status for handling error messages. 2005-08-23 Love Hörnquist Åstrand * external.c: Use rk_UNCONST to avoid const warning. * display_status.c: Constify strings to avoid warnings. 2005-08-11 Love Hörnquist Åstrand * init_sec_context.c: avoid warnings, update (c) 2005-07-13 Love Hörnquist Åstrand * init_sec_context.c (spnego_initial): use NegotiationToken encoder now that we have one with the new asn1. compiler. * Makefile.am: the new asn.1 compiler includes the modules name in the depend file 2005-06-16 Love Hörnquist Åstrand * decapsulate.c: use rk_UNCONST * ccache_name.c: rename to avoid shadowing * gssapi_locl.h: give kret in GSSAPI_KRB5_INIT a more unique name * process_context_token.c: use rk_UNCONST to unconstify * test_cred.c: rename optind to optidx 2005-05-30 Love Hörnquist Åstrand * init_sec_context.c (init_auth): honor ok-as-delegate if local configuration approves * gssapi_locl.h: prototype for _gss_check_compat * compat.c: export check_compat as _gss_check_compat 2005-05-29 Love Hörnquist Åstrand * init_sec_context.c: Prefix Der_class with ASN1_C_ to avoid problems with system headerfiles that pollute the name space. * accept_sec_context.c: Prefix Der_class with ASN1_C_ to avoid problems with system headerfiles that pollute the name space. 2005-05-17 Love Hörnquist Åstrand * init_sec_context.c (init_auth): set KRB5_AUTH_CONTEXT_CLEAR_FORWARDED_CRED (for java compatibility), also while here, use krb5_auth_con_addflags 2005-05-06 Love Hörnquist Åstrand * arcfour.c (_gssapi_wrap_arcfour): fix calculating the encap length. From: Tom Maher 2005-05-02 Dave Love * test_cred.c (main): Call setprogname. 2005-04-27 Love Hörnquist Åstrand * prefix all sequence symbols with _, they are not part of the GSS-API api. By comment from Wynn Wilkes 2005-04-10 Love Hörnquist Åstrand * accept_sec_context.c: break out the processing of the delegated credential to a separate function to make error handling easier, move the credential handling to after other setup is done * test_sequence.c: make less verbose in case of success * Makefile.am: add test_sequence to TESTS 2005-04-01 Love Hörnquist Åstrand * 8003.c (gssapi_krb5_verify_8003_checksum): check that cksum isn't NULL From: Nicolas Pouvesle 2005-03-21 Love Hörnquist Åstrand * Makefile.am: use $(LIB_roken) 2005-03-16 Love Hörnquist Åstrand * display_status.c (gssapi_krb5_set_error_string): pass in the krb5_context to krb5_free_error_string 2005-03-15 Love Hörnquist Åstrand * display_status.c (gssapi_krb5_set_error_string): don't misuse the krb5_get_error_string api 2005-03-01 Love Hörnquist Åstrand * compat.c (_gss_DES3_get_mic_compat): don't unlock mutex here. Bug reported by Stefan Metzmacher 2005-02-21 Luke Howard * init_sec_context.c: don't call krb5_get_credentials() with KRB5_TC_MATCH_KEYTYPE, it can lead to the credentials cache growing indefinitely as no key is found with KEYTYPE_NULL * compat.c: remove GSS_C_EXPECTING_MECH_LIST_MIC_FLAG, it is no longer used (however the mechListMIC behaviour is broken, rfc2478bis support requires the code in the mechglue branch) * init_sec_context.c: remove GSS_C_EXPECTING_MECH_LIST_MIC_FLAG * gssapi.h: remove GSS_C_EXPECTING_MECH_LIST_MIC_FLAG 2005-01-05 Luke Howard * 8003.c: use symbolic name for checksum type * accept_sec_context.c: allow client to indicate that subkey should be used * acquire_cred.c: plug leak * get_mic.c: use gss_krb5_get_subkey() instead of gss_krb5_get_{local,remote}key(), support KEYTYPE_ARCFOUR_56 * gssapi_local.c: use gss_krb5_get_subkey(), support KEYTYPE_ARCFOUR_56 * import_sec_context.c: plug leak * unwrap.c: use gss_krb5_get_subkey(), support KEYTYPE_ARCFOUR_56 * verify_mic.c: use gss_krb5_get_subkey(), support KEYTYPE_ARCFOUR_56 * wrap.c: use gss_krb5_get_subkey(), support KEYTYPE_ARCFOUR_56 2004-11-30 Love Hörnquist Åstrand * inquire_cred.c: Reverse order of HEIMDAL_MUTEX_unlock and gss_release_cred to avoid deadlock, from Luke Howard . 2004-09-06 Love Hörnquist Åstrand * gss_acquire_cred.3: gss_krb5_extract_authz_data_from_sec_context was renamed to gsskrb5_extract_authz_data_from_sec_context 2004-08-07 Love Hörnquist Åstrand * unwrap.c: mutex buglet, From: Luke Howard * arcfour.c: mutex buglet, From: Luke Howard 2004-05-06 Love Hörnquist Åstrand * gssapi.3: spelling from Josef El-Rayes while here, write some text about the SPNEGO situation 2004-04-08 Love Hörnquist Åstrand * cfx.c: s/CTXAcceptorSubkey/CFXAcceptorSubkey/ 2004-04-07 Love Hörnquist Åstrand * gssapi.h: add GSS_C_EXPECTING_MECH_LIST_MIC_FLAG From: Luke Howard * init_sec_context.c (spnego_reply): use _gss_spnego_require_mechlist_mic to figure out if we need to check MechListMIC; From: Luke Howard * accept_sec_context.c (send_accept): use _gss_spnego_require_mechlist_mic to figure out if we need to send MechListMIC; From: Luke Howard * gssapi_locl.h: add _gss_spnego_require_mechlist_mic From: Luke Howard * compat.c: add _gss_spnego_require_mechlist_mic for compatibility with MS SPNEGO, From: Luke Howard 2004-04-05 Love Hörnquist Åstrand * accept_sec_context.c (gsskrb5_is_cfx): krb5_keyblock->keytype is an enctype, not keytype * accept_sec_context.c: use ASN1_MALLOC_ENCODE * init_sec_context.c: avoid the malloc loop and just allocate the propper amount of data * init_sec_context.c (spnego_initial): handle mech_token better 2004-03-19 Love Hörnquist Åstrand * gssapi.h: add gss_krb5_get_tkt_flags * Makefile.am: add ticket_flags.c * ticket_flags.c: Get ticket-flags from acceptor ticket From: Luke Howard * gss_acquire_cred.3: document gss_krb5_get_tkt_flags 2004-03-14 Love Hörnquist Åstrand * acquire_cred.c (gss_acquire_cred): check usage before even bothering to process it, add both keytab and initial tgt if requested * wrap.c: support cfx, try to handle acceptor asserted subkey * unwrap.c: support cfx, try to handle acceptor asserted subkey * verify_mic.c: support cfx * get_mic.c: support cfx * test_sequence.c: handle changed signature of gssapi_msg_order_create * import_sec_context.c: handle acceptor asserted subkey * init_sec_context.c: handle acceptor asserted subkey * accept_sec_context.c: handle acceptor asserted subkey * sequence.c: add dummy use_64 argument to gssapi_msg_order_create * gssapi_locl.h: add partial support for CFX * Makefile.am (noinst_PROGRAMS) += test_cred * test_cred.c: gssapi credential testing * test_acquire_cred.c: fix comment 2004-03-07 Love Hörnquist Åstrand * arcfour.h: drop structures for message formats, no longer used * arcfour.c: comment describing message formats * accept_sec_context.c (spnego_accept_sec_context): make sure the length of the choice element doesn't overrun us * init_sec_context.c (spnego_reply): make sure the length of the choice element doesn't overrun us * spnego.asn1: move NegotiationToken to avoid warning * spnego.asn1: uncomment NegotiationToken * Makefile.am: spnego_files += asn1_NegotiationToken.x 2004-01-25 Love Hörnquist Åstrand * gssapi.h: add gss_krb5_ccache_name * Makefile.am (libgssapi_la_SOURCES): += ccache_name.c * ccache_name.c (gss_krb5_ccache_name): help function enable to set krb5 name, using out_name argument makes function no longer thread-safe * gssapi.3: add missing gss_krb5_ references * gss_acquire_cred.3: document gss_krb5_ccache_name 2003-12-12 Love Hörnquist Åstrand * cfx.c: make rrc a modulus operation if its longer then the length of the message, noticed by Sam Hartman 2003-12-07 Love Hörnquist Åstrand * accept_sec_context.c: use krb5_auth_con_addflags 2003-12-05 Love Hörnquist Åstrand * cfx.c: Wrap token id was in wrong order, found by Sam Hartman 2003-12-04 Love Hörnquist Åstrand * cfx.c: add AcceptorSubkey (but no code understand it yet) ignore unknown token flags 2003-11-22 Love Hörnquist Åstrand * accept_sec_context.c: Don't require timestamp to be set on delegated token, its already protected by the outer token (and windows doesn't alway send it) Pointed out by Zi-Bin Yang on heimdal-discuss 2003-11-14 Love Hörnquist Åstrand * cfx.c: fix {} error, pointed out by Liqiang Zhu 2003-11-10 Love Hörnquist Åstrand * cfx.c: Sequence number should be stored in bigendian order From: Luke Howard 2003-11-09 Love Hörnquist Åstrand * delete_sec_context.c (gss_delete_sec_context): don't free ticket, krb5_free_ticket does that now 2003-11-06 Love Hörnquist Åstrand * cfx.c: checksum the header last in MIC token, update to -03 From: Luke Howard 2003-10-07 Love Hörnquist Åstrand * add_cred.c: If its a MEMORY cc, make a copy. We need to do this since now gss_release_cred will destroy the cred. This should be really be solved a better way. * acquire_cred.c (gss_release_cred): if its a mcc, destroy it rather the just release it Found by: "Zi-Bin Yang" * acquire_cred.c (acquire_initiator_cred): use kret instead of ret where appropriate 2003-09-30 Love Hörnquist Åstrand * gss_acquire_cred.3: spelling From: jmc 2003-09-23 Love Hörnquist Åstrand * cfx.c: - EC and RRC are big-endian, not little-endian - The default is now to rotate regardless of GSS_C_DCE_STYLE. There are no longer any references to GSS_C_DCE_STYLE. - rrc_rotate() avoids allocating memory on the heap if rrc <= 256 From: Luke Howard 2003-09-22 Love Hörnquist Åstrand * cfx.[ch]: rrc_rotate() was untested and broken, fix it. Set and verify wrap Token->Filler. Correct token ID for wrap tokens, were accidentally swapped with delete tokens. From: Luke Howard 2003-09-21 Love Hörnquist Åstrand * cfx.[ch]: no ASN.1-ish header on per-message tokens From: Luke Howard 2003-09-19 Love Hörnquist Åstrand * arcfour.h: remove depenency on gss_arcfour_mic_token and gss_arcfour_warp_token * arcfour.c: remove depenency on gss_arcfour_mic_token and gss_arcfour_warp_token 2003-09-18 Love Hörnquist Åstrand * 8003.c: remove #if 0'ed code 2003-09-17 Love Hörnquist Åstrand * accept_sec_context.c (gsskrb5_accept_sec_context): set sequence number when not requesting mutual auth From: Luke Howard * init_sec_context.c (init_auth): set sequence number when not requesting mutual auth From: Luke Howard 2003-09-16 Love Hörnquist Åstrand * arcfour.c (*): set minor_status (gss_wrap): set conf_state to conf_req_flags on success From: Luke Howard * wrap.c (gss_wrap_size_limit): use existing function From: Luke Howard 2003-09-12 Love Hörnquist Åstrand * indicate_mechs.c (gss_indicate_mechs): in case of error, free mech_set * indicate_mechs.c (gss_indicate_mechs): add SPNEGO 2003-09-10 Love Hörnquist Åstrand * init_sec_context.c (spnego_initial): catch errors and return them * init_sec_context.c (spnego_initial): add #if 0 out version of the CHOICE branch encoding, also where here, free no longer used memory 2003-09-09 Love Hörnquist Åstrand * gss_acquire_cred.3: support GSS_SPNEGO_MECHANISM * accept_sec_context.c: SPNEGO doesn't include gss wrapping on SubsequentContextToken like the Kerberos 5 mech does. * init_sec_context.c (spnego_reply): SPNEGO doesn't include gss wrapping on SubsequentContextToken like the Kerberos 5 mech does. Lets check for it anyway. * accept_sec_context.c: Add support for SPNEGO on the initator side. Implementation initially from Assar Westerlund, passes though quite a lot of hands before I commited it. * init_sec_context.c: Add support for SPNEGO on the initator side. Tested with ldap server on a Windows 2000 DC. Implementation initially from Assar Westerlund, passes though quite a lot of hands before I commited it. * gssapi.h: export GSS_SPNEGO_MECHANISM * gssapi_locl.h: include spnego_as.h add prototype for gssapi_krb5_get_mech * decapsulate.c (gssapi_krb5_get_mech): make non static * Makefile.am: build SPNEGO file 2003-09-08 Love Hörnquist Åstrand * external.c: SPENGO and IAKERB oids * spnego.asn1: SPENGO ASN1 2003-09-05 Love Hörnquist Åstrand * cfx.c: RRC also need to be zero before wraping them From: Luke Howard 2003-09-04 Love Hörnquist Åstrand * encapsulate.c (gssapi_krb5_encap_length): don't return void 2003-09-03 Love Hörnquist Åstrand * verify_mic.c: switch from the des_ to the DES_ api * get_mic.c: switch from the des_ to the DES_ api * unwrap.c: switch from the des_ to the DES_ api * wrap.c: switch from the des_ to the DES_ api * cfx.c: EC is not included in the checksum since the length might change depending on the data. From: Luke Howard * acquire_cred.c: use krb5_get_init_creds_opt_alloc/krb5_get_init_creds_opt_free 2003-09-01 Love Hörnquist Åstrand * copy_ccache.c: rename gss_krb5_extract_authz_data_from_sec_context to gsskrb5_extract_authz_data_from_sec_context * gssapi.h: rename gss_krb5_extract_authz_data_from_sec_context to gsskrb5_extract_authz_data_from_sec_context 2003-08-31 Love Hörnquist Åstrand * copy_ccache.c (gss_krb5_extract_authz_data_from_sec_context): check that we have a ticket before we start to use it * gss_acquire_cred.3: document gss_krb5_extract_authz_data_from_sec_context * gssapi.h (gss_krb5_extract_authz_data_from_sec_context): return the kerberos authorizationdata, from idea of Luke Howard * copy_ccache.c (gss_krb5_extract_authz_data_from_sec_context): return the kerberos authorizationdata, from idea of Luke Howard * verify_mic.c (gss_verify_mic_internal): switch type and key argument 2003-08-30 Love Hörnquist Åstrand * cfx.[ch]: draft-ietf-krb-wg-gssapi-cfx-01.txt implemetation From: Luke Howard 2003-08-28 Love Hörnquist Åstrand * arcfour.c (arcfour_mic_cksum): use free_Checksum to free the checksum * arcfour.h: swap two last arguments to verify_mic for consistency with des3 * wrap.c,unwrap.c,get_mic.c,verify_mic.c,cfx.c,cfx.h: prefix cfx symbols with _gssapi_ * arcfour.c: release the right buffer * arcfour.c: rename token structure in consistency with rest of GSS-API From: Luke Howard * unwrap.c (unwrap_des3): use _gssapi_verify_pad (unwrap_des): use _gssapi_verify_pad * arcfour.c (_gssapi_wrap_arcfour): set the correct padding (_gssapi_unwrap_arcfour): verify and strip padding * gssapi_locl.h: added _gssapi_verify_pad * decapsulate.c (_gssapi_verify_pad): verify padding of a gss wrapped message and return its length * arcfour.c: support KEYTYPE_ARCFOUR_56 keys, from Luke Howard * arcfour.c: use right seal alg, inherit keytype from parent key * arcfour.c: include the confounder in the checksum use the right key usage number for warped/unwraped tokens * gssapi.h: add gss_krb5_nt_general_name as an mit compat glue (same as GSS_KRB5_NT_PRINCIPAL_NAME) * unwrap.c: hook in arcfour unwrap * wrap.c: hook in arcfour wrap * verify_mic.c: hook in arcfour verify_mic * get_mic.c: hook in arcfour get_mic * arcfour.c: implement wrap/unwarp * gssapi_locl.h: add gssapi_{en,de}code_be_om_uint32 * 8003.c: add gssapi_{en,de}code_be_om_uint32 2003-08-27 Love Hörnquist Åstrand * arcfour.c (_gssapi_verify_mic_arcfour): Do the checksum on right area. Swap filler check, it was reversed. * Makefile.am (libgssapi_la_SOURCES): += arcfour.c * gssapi_locl.h: include "arcfour.h" * arcfour.c: arcfour gss-api mech, get_mic/verify_mic working * arcfour.h: arcfour gss-api mech, get_mic/verify_mic working 2003-08-26 Love Hörnquist Åstrand * gssapi_locl.h: always include cfx.h add prototype for _gssapi_decapsulate * cfx.[ch]: Implementation of draft-ietf-krb-wg-gssapi-cfx-00.txt from Luke Howard * decapsulate.c: add _gssapi_decapsulate, from Luke Howard 2003-08-25 Love Hörnquist Åstrand * unwrap.c: encap/decap now takes a oid if the enctype/keytype is arcfour, return error add hook for cfx * verify_mic.c: encap/decap now takes a oid if the enctype/keytype is arcfour, return error add hook for cfx * get_mic.c: encap/decap now takes a oid if the enctype/keytype is arcfour, return error add hook for cfx * accept_sec_context.c: encap/decap now takes a oid * init_sec_context.c: encap/decap now takes a oid * gssapi_locl.h: include cfx.h if we need it lifetime is a OM_uint32, depend on gssapi interface add all new encap/decap functions * decapsulate.c: add decap functions that doesn't take the token type also make all decap function take the oid mech that they should use * encapsulate.c: add encap functions that doesn't take the token type also make all encap function take the oid mech that they should use * sequence.c (elem_insert): fix a off by one index counter * inquire_cred.c (gss_inquire_cred): handle cred_handle being GSS_C_NO_CREDENTIAL and use the default cred then. 2003-08-19 Love Hörnquist Åstrand * gss_acquire_cred.3: break out extensions and document gsskrb5_register_acceptor_identity 2003-08-18 Love Hörnquist Åstrand * test_acquire_cred.c (print_time): time is returned in seconds from now, not unix time 2003-08-17 Love Hörnquist Åstrand * compat.c (check_compat): avoid leaking principal when finding a match * address_to_krb5addr.c: sa_size argument to krb5_addr2sockaddr is a krb5_socklen_t * acquire_cred.c (gss_acquire_cred): 4th argument to gss_test_oid_set_member is a int 2003-07-22 Love Hörnquist Åstrand * init_sec_context.c (repl_mutual): don't set kerberos error where there was no kerberos error * gssapi_locl.h: Add destruction/creation prototypes and structure for the thread specific storage. * display_status.c: use thread specific storage to set/get the kerberos error message * init.c: Provide locking around the creation of the global krb5_context. Add destruction/creation functions for the thread specific storage that the error string handling is using. 2003-07-20 Love Hörnquist Åstrand * gss_acquire_cred.3: add missing prototype and missing .Ft arguments 2003-06-17 Love Hörnquist Åstrand * verify_mic.c: reorder code so sequence numbers can can be used * unwrap.c: reorder code so sequence numbers can can be used * sequence.c: remove unused function, indent, add gssapi_msg_order_f that filter gss flags to gss_msg_order flags * gssapi_locl.h: prototypes for gssapi_{encode_om_uint32,decode_om_uint32} add sequence number verifier prototypes * delete_sec_context.c: destroy sequence number verifier * init_sec_context.c: remember to free data use sequence number verifier * accept_sec_context.c: don't clear output_token twice remember to free data use sequence number verifier * 8003.c: export and rename encode_om_uint32/decode_om_uint32 and start to use them 2003-06-09 Johan Danielsson * Makefile.am: can't have sequence.c in two different places 2003-06-06 Love Hörnquist Åstrand * test_sequence.c: check rollover, print summery * wrap.c (sub_wrap_size): gss_wrap_size_limit() has req_output_size and max_input_size around the wrong way -- it returns the output token size for a given input size, rather than the maximum input size for a given output token size. From: Luke Howard 2003-06-05 Love Hörnquist Åstrand * gssapi_locl.h: add prototypes for sequence.c * Makefile.am (libgssapi_la_SOURCES): add sequence.c (test_sequence): build * sequence.c: sequence number checks, order and replay * test_sequence.c: sequence number checks, order and replay 2003-06-03 Love Hörnquist Åstrand * accept_sec_context.c (gss_accept_sec_context): make sure time is returned in seconds from now, not in kerberos time * acquire_cred.c (gss_aquire_cred): make sure time is returned in seconds from now, not in kerberos time * init_sec_context.c (init_auth): if the cred is expired before we tries to create a token, fail so the peer doesn't need reject us (*): make sure time is returned in seconds from now, not in kerberos time (repl_mutual): remember to unlock the context mutex * context_time.c (gss_context_time): remove unused variable * verify_mic.c: make sure minor_status is always set, pointed out by Luke Howard 2003-05-21 Love Hörnquist Åstrand * *.[ch]: do some basic locking (no reference counting so contexts can be removed while still used) - don't export gss_ctx_id_t_desc_struct and gss_cred_id_t_desc_struct - make sure all lifetime are returned in seconds left until expired, not in unix epoch * gss_acquire_cred.3: document argument lifetime_rec to function gss_inquire_context 2003-05-17 Love Hörnquist Åstrand * test_acquire_cred.c: test gss_add_cred more then once 2003-05-06 Love Hörnquist Åstrand * gssapi.h: if __cplusplus, wrap the extern variable (just to be safe) and functions in extern "C" { } 2003-04-30 Love Hörnquist Åstrand * gssapi.3: more about the des3 mic mess * verify_mic.c (verify_mic_des3): always check if the mic is the correct mic or the mic that old heimdal would have generated 2003-04-28 Jacques Vidrine * verify_mic.c (verify_mic_des3): If MIC verification fails, retry using the `old' MIC computation (with zero IV). 2003-04-26 Love Hörnquist Åstrand * gss_acquire_cred.3: more about difference between comparing IN and MN * gss_acquire_cred.3: more about name type and access control 2003-04-25 Love Hörnquist Åstrand * gss_acquire_cred.3: document gss_context_time * context_time.c: if lifetime of context have expired, set time_rec to 0 and return GSS_S_CONTEXT_EXPIRED * gssapi.3: document [gssapi]correct_des3_mic [gssapi]broken_des3_mic * gss_acquire_cred.3: document gss_krb5_compat_des3_mic * compat.c (gss_krb5_compat_des3_mic): enable turning on/off des3 mic compat (_gss_DES3_get_mic_compat): handle [gssapi]correct_des3_mic too * gssapi.h (gss_krb5_compat_des3_mic): new function, turn on/off des3 mic compat (GSS_C_KRB5_COMPAT_DES3_MIC): cpp symbol that exists if gss_krb5_compat_des3_mic exists 2003-04-24 Love Hörnquist Åstrand * Makefile.am: (libgssapi_la_LDFLAGS): update major version of gssapi for incompatiblity in 3des getmic support 2003-04-23 Love Hörnquist Åstrand * Makefile.am: test_acquire_cred_LDADD: use libgssapi.la not ./libgssapi.la (make make -jN work) 2003-04-16 Love Hörnquist Åstrand * gssapi.3: spelling * gss_acquire_cred.3: Change .Fd #include to .In header.h, from Thomas Klausner 2003-04-06 Love Hörnquist Åstrand * gss_acquire_cred.3: spelling * Makefile.am: remove stuff that sneaked in with last commit * acquire_cred.c (acquire_initiator_cred): if the requested name isn't in the ccache, also check keytab. Extact the krbtgt for the default realm to check how long the credentials will last. * add_cred.c (gss_add_cred): don't create a new ccache, just open the old one; better check if output handle is compatible with new (copied) handle * test_acquire_cred.c: test gss_add_cred too 2003-04-03 Love Hörnquist Åstrand * Makefile.am: build test_acquire_cred * test_acquire_cred.c: simple gss_acquire_cred test 2003-04-02 Love Hörnquist Åstrand * gss_acquire_cred.3: s/gssapi/GSS-API/ 2003-03-19 Love Hörnquist Åstrand * gss_acquire_cred.3: document v1 interface (and that they are obsolete) 2003-03-18 Love Hörnquist Åstrand * gss_acquire_cred.3: list supported mechanism and nametypes 2003-03-16 Love Hörnquist Åstrand * gss_acquire_cred.3: text about gss_display_name * Makefile.am (libgssapi_la_LDFLAGS): bump to 3:6:2 (libgssapi_la_SOURCES): add all new functions * gssapi.3: now that we have a functions, uncomment the missing ones * gss_acquire_cred.3: now that we have a functions, uncomment the missing ones * process_context_token.c: implement gss_process_context_token * inquire_names_for_mech.c: implement gss_inquire_names_for_mech * inquire_mechs_for_name.c: implement gss_inquire_mechs_for_name * inquire_cred_by_mech.c: implement gss_inquire_cred_by_mech * add_cred.c: implement gss_add_cred * acquire_cred.c (gss_acquire_cred): more testing of input argument, make sure output arguments are ok, since we don't know the time_rec (for now), set it to time_req * export_sec_context.c: send lifetime, also set minor_status * get_mic.c: set minor_status * import_sec_context.c (gss_import_sec_context): add error checking, pick up lifetime (if there is no lifetime, use GSS_C_INDEFINITE) * init_sec_context.c: take care to set export value to something sane before we start so caller will have harmless values in them if then function fails * release_buffer.c (gss_release_buffer): set minor_status * wrap.c: make sure minor_status get set * verify_mic.c (gss_verify_mic_internal): rename verify_mic to gss_verify_mic_internal and let it take the type as an argument, (gss_verify_mic): call gss_verify_mic_internal set minor_status * unwrap.c: set minor_status * test_oid_set_member.c (gss_test_oid_set_member): use gss_oid_equal * release_oid_set.c (gss_release_oid_set): set minor_status * release_name.c (gss_release_name): set minor_status * release_cred.c (gss_release_cred): set minor_status * add_oid_set_member.c (gss_add_oid_set_member): set minor_status * compare_name.c (gss_compare_name): set minor_status * compat.c (check_compat): make sure ret have a defined value * context_time.c (gss_context_time): set minor_status * copy_ccache.c (gss_krb5_copy_ccache): set minor_status * create_emtpy_oid_set.c (gss_create_empty_oid_set): set minor_status * delete_sec_context.c (gss_delete_sec_context): set minor_status * display_name.c (gss_display_name): set minor_status * display_status.c (gss_display_status): use gss_oid_equal, handle supplementary errors * duplicate_name.c (gss_duplicate_name): set minor_status * inquire_context.c (gss_inquire_context): set lifetime_rec now when we know it, set minor_status * inquire_cred.c (gss_inquire_cred): take care to set export value to something sane before we start so caller will have harmless values in them if the function fails * accept_sec_context.c (gss_accept_sec_context): take care to set export value to something sane before we start so caller will have harmless values in them if then function fails, set lifetime from ticket expiration date * indicate_mechs.c (gss_indicate_mechs): use gss_create_empty_oid_set and gss_add_oid_set_member * gssapi.h (gss_ctx_id_t_desc): store the lifetime in the cred, since there is no ticket transfered in the exported context * export_name.c (gss_export_name): export name with GSS_C_NT_EXPORT_NAME wrapping, not just the principal * import_name.c (import_export_name): new function, parses a GSS_C_NT_EXPORT_NAME (import_krb5_name): factor out common code of parsing krb5 name (gss_oid_equal): rename from oid_equal * gssapi_locl.h: add prototypes for gss_oid_equal and gss_verify_mic_internal * gssapi.h: comment out the argument names 2003-03-15 Love Hörnquist Åstrand * gssapi.3: add LIST OF FUNCTIONS and copyright/license * Makefile.am: s/gss_aquire_cred.3/gss_acquire_cred.3/ * Makefile.am: man_MANS += gss_aquire_cred.3 2003-03-14 Love Hörnquist Åstrand * gss_aquire_cred.3: the gssapi api manpage 2003-03-03 Love Hörnquist Åstrand * inquire_context.c: (gss_inquire_context): rename argument open to open_context * gssapi.h (gss_inquire_context): rename argument open to open_context 2003-02-27 Love Hörnquist Åstrand * init_sec_context.c (do_delegation): remove unused variable subkey * gssapi.3: all 0.5.x version had broken token delegation 2003-02-21 Love Hörnquist Åstrand * (init_auth): only generate one subkey 2003-01-27 Love Hörnquist Åstrand * verify_mic.c (verify_mic_des3): fix 3des verify_mic to conform to rfc (and mit kerberos), provide backward compat hook * get_mic.c (mic_des3): fix 3des get_mic to conform to rfc (and mit kerberos), provide backward compat hook * init_sec_context.c (init_auth): check if we need compat for older get_mic/verify_mic * gssapi_locl.h: add prototype for _gss_DES3_get_mic_compat * gssapi.h (more_flags): add COMPAT_OLD_DES3 * Makefile.am: add gssapi.3 and compat.c * gssapi.3: add gssapi COMPATIBILITY documentation * accept_sec_context.c (gss_accept_sec_context): check if we need compat for older get_mic/verify_mic * compat.c: check for compatiblity with other heimdal's 3des get_mic/verify_mic 2002-10-31 Johan Danielsson * check return value from gssapi_krb5_init * 8003.c (gssapi_krb5_verify_8003_checksum): check size of input 2002-09-03 Johan Danielsson * wrap.c (wrap_des3): use ETYPE_DES3_CBC_NONE * unwrap.c (unwrap_des3): use ETYPE_DES3_CBC_NONE 2002-09-02 Johan Danielsson * init_sec_context.c: we need to generate a local subkey here 2002-08-20 Jacques Vidrine * acquire_cred.c, inquire_cred.c, release_cred.c: Use default credential resolution if gss_acquire_cred is called with GSS_C_NO_NAME. 2002-06-20 Jacques Vidrine * import_name.c: Compare name types by value if pointers do not match. Reported by: "Douglas E. Engert" 2002-05-20 Jacques Vidrine * verify_mic.c (gss_verify_mic), unwrap.c (gss_unwrap): initialize the qop_state parameter. from Doug Rabson 2002-05-09 Jacques Vidrine * acquire_cred.c: handle GSS_C_INITIATE/GSS_C_ACCEPT/GSS_C_BOTH 2002-05-08 Jacques Vidrine * acquire_cred.c: initialize gssapi; handle null desired_name 2002-03-22 Johan Danielsson * Makefile.am: remove non-functional stuff accidentally committed 2002-03-11 Assar Westerlund * Makefile.am (libgssapi_la_LDFLAGS): bump version to 3:5:2 * 8003.c (gssapi_krb5_verify_8003_checksum): handle zero channel bindings 2001-10-31 Jacques Vidrine * get_mic.c (mic_des3): MIC computation using DES3/SHA1 was bogusly appending the message buffer to the result, overwriting a heap buffer in the process. 2001-08-29 Assar Westerlund * 8003.c (gssapi_krb5_verify_8003_checksum, gssapi_krb5_create_8003_checksum): make more consistent by always returning an gssapi error and setting minor status. update callers 2001-08-28 Jacques Vidrine * accept_sec_context.c: Create a cache for delegated credentials when needed. 2001-08-28 Assar Westerlund * Makefile.am (libgssapi_la_LDFLAGS): set version to 3:4:2 2001-08-23 Assar Westerlund * *.c: handle minor_status more consistently * display_status.c (gss_display_status): handle krb5_get_err_text failing 2001-08-15 Johan Danielsson * gssapi_locl.h: fix prototype for gssapi_krb5_init 2001-08-13 Johan Danielsson * accept_sec_context.c (gsskrb5_register_acceptor_identity): init context and check return value from kt_resolve * init.c: return error code 2001-07-19 Assar Westerlund * Makefile.am (libgssapi_la_LDFLAGS): update to 3:3:2 2001-07-12 Assar Westerlund * Makefile.am (libgssapi_la_LIBADD): add required library dependencies 2001-07-06 Assar Westerlund * accept_sec_context.c (gsskrb5_register_acceptor_identity): set the keytab to be used for gss_acquire_cred too' 2001-07-03 Assar Westerlund * Makefile.am (libgssapi_la_LDFLAGS): set version to 3:2:2 2001-06-18 Assar Westerlund * wrap.c: replace gss_krb5_getsomekey with gss_krb5_get_localkey and gss_krb5_get_remotekey * verify_mic.c: update krb5_auth_con function names use gss_krb5_get_remotekey * unwrap.c: replace gss_krb5_getsomekey with gss_krb5_get_localkey and gss_krb5_get_remotekey * gssapi_locl.h (gss_krb5_get_remotekey, gss_krb5_get_localkey): add prototypes * get_mic.c: update krb5_auth_con function names. use gss_krb5_get_localkey * accept_sec_context.c: update krb5_auth_con function names 2001-05-17 Assar Westerlund * Makefile.am: bump version to 3:1:2 2001-05-14 Assar Westerlund * address_to_krb5addr.c: adapt to new address functions 2001-05-11 Assar Westerlund * try to return the error string from libkrb5 where applicable 2001-05-08 Assar Westerlund * delete_sec_context.c (gss_delete_sec_context): remember to free the memory used by the ticket itself. from 2001-05-04 Assar Westerlund * gssapi_locl.h: add config.h for completeness * gssapi.h: remove config.h, this is an installed header file sys/types.h is not needed either 2001-03-12 Assar Westerlund * acquire_cred.c (gss_acquire_cred): remove memory leaks. from Jason R Thorpe 2001-02-18 Assar Westerlund * accept_sec_context.c (gss_accept_sec_context): either return gss_name NULL-ed or set * import_name.c: set minor_status in some cases where it was not done 2001-02-15 Assar Westerlund * wrap.c: use krb5_generate_random_block for the confounders 2001-01-30 Assar Westerlund * Makefile.am (libgssapi_la_LDFLAGS): bump version to 3:0:2 * acquire_cred.c, init_sec_context.c, release_cred.c: add support for getting creds from a keytab, from fvdl@netbsd.org * copy_ccache.c: add gss_krb5_copy_ccache 2001-01-27 Assar Westerlund * get_mic.c: cast parameters to des function to non-const pointers to handle the case where these functions actually take non-const des_cblock * 2001-01-09 Assar Westerlund * accept_sec_context.c (gss_accept_sec_context): use krb5_rd_cred2 instead of krb5_rd_cred 2000-12-11 Assar Westerlund * Makefile.am (libgssapi_la_LDFLAGS): bump to 2:3:1 2000-12-08 Assar Westerlund * wrap.c (wrap_des3): use the checksum as ivec when encrypting the sequence number * unwrap.c (unwrap_des3): use the checksum as ivec when encrypting the sequence number * init_sec_context.c (init_auth): always zero fwd_data 2000-12-06 Johan Danielsson * accept_sec_context.c: de-pointerise auth_context parameter to krb5_mk_rep 2000-11-15 Assar Westerlund * init_sec_context.c (init_auth): update to new krb5_build_authenticator 2000-09-19 Assar Westerlund * Makefile.am (libgssapi_la_LDFLAGS): bump to 2:2:1 2000-08-27 Assar Westerlund * init_sec_context.c: actually pay attention to `time_req' * init_sec_context.c: re-organize. leak less memory. * gssapi_locl.h (gssapi_krb5_encapsulate, gss_krb5_getsomekey): update prototypes add assert.h * gssapi.h (GSS_KRB5_CONF_C_QOP_DES, GSS_KRB5_CONF_C_QOP_DES3_KD): add * verify_mic.c: re-organize and add 3DES code * wrap.c: re-organize and add 3DES code * unwrap.c: re-organize and add 3DES code * get_mic.c: re-organize and add 3DES code * encapsulate.c (gssapi_krb5_encapsulate): do not free `in_data', let the caller do that. fix the callers. 2000-08-16 Assar Westerlund * Makefile.am: bump version to 2:1:1 2000-07-29 Assar Westerlund * decapsulate.c (gssapi_krb5_verify_header): sanity-check length 2000-07-25 Johan Danielsson * Makefile.am: bump version to 2:0:1 2000-07-22 Assar Westerlund * gssapi.h: update OID for GSS_C_NT_HOSTBASED_SERVICE and other details from rfc2744 2000-06-29 Assar Westerlund * address_to_krb5addr.c (gss_address_to_krb5addr): actually use `int' instead of `sa_family_t' for the address family. 2000-06-21 Assar Westerlund * add support for token delegation. From Daniel Kouril and Miroslav Ruda 2000-05-15 Assar Westerlund * Makefile.am (libgssapi_la_LDFLAGS): set version to 1:1:1 2000-04-12 Assar Westerlund * release_oid_set.c (gss_release_oid_set): clear set for robustness. From GOMBAS Gabor * release_name.c (gss_release_name): reset input_name for robustness. From GOMBAS Gabor * release_buffer.c (gss_release_buffer): set value to NULL to be more robust. From GOMBAS Gabor * add_oid_set_member.c (gss_add_oid_set_member): actually check if the oid is a member first. leave the oid_set unchanged if realloc fails. 2000-02-13 Assar Westerlund * Makefile.am: set version to 1:0:1 2000-02-12 Assar Westerlund * gssapi_locl.h: add flags for import/export * import_sec_context.c (import_sec_context: add flags for what fields are included. do not include the authenticator for now. * export_sec_context.c (export_sec_context: add flags for what fields are included. do not include the authenticator for now. * accept_sec_context.c (gss_accept_sec_context): set target in context_handle 2000-02-11 Assar Westerlund * delete_sec_context.c (gss_delete_sec_context): set context to GSS_C_NO_CONTEXT * Makefile.am: add {export,import}_sec_context.c * export_sec_context.c: new file * import_sec_context.c: new file * accept_sec_context.c (gss_accept_sec_context): set trans flag 2000-02-07 Assar Westerlund * Makefile.am: set version to 0:5:0 2000-01-26 Assar Westerlund * delete_sec_context.c (gss_delete_sec_context): handle a NULL output_token * wrap.c: update to pseudo-standard APIs for md4,md5,sha. some changes to libdes calls to make them more portable. * verify_mic.c: update to pseudo-standard APIs for md4,md5,sha. some changes to libdes calls to make them more portable. * unwrap.c: update to pseudo-standard APIs for md4,md5,sha. some changes to libdes calls to make them more portable. * get_mic.c: update to pseudo-standard APIs for md4,md5,sha. some changes to libdes calls to make them more portable. * 8003.c: update to pseudo-standard APIs for md4,md5,sha. 2000-01-06 Assar Westerlund * Makefile.am: set version to 0:4:0 1999-12-26 Assar Westerlund * accept_sec_context.c (gss_accept_sec_context): always set `output_token' * init_sec_context.c (init_auth): always initialize `output_token' * delete_sec_context.c (gss_delete_sec_context): always set `output_token' 1999-12-06 Assar Westerlund * Makefile.am: bump version to 0:3:0 1999-10-20 Assar Westerlund * Makefile.am: set version to 0:2:0 1999-09-21 Assar Westerlund * init_sec_context.c (gss_init_sec_context): initialize `ticket' * gssapi.h (gss_ctx_id_t_desc): add ticket in here. ick. * delete_sec_context.c (gss_delete_sec_context): free ticket * accept_sec_context.c (gss_accept_sec_context): stove away `krb5_ticket' in context so that ugly programs such as gss_nt_server can get at it. uck. 1999-09-20 Johan Danielsson * accept_sec_context.c: set minor_status 1999-08-04 Assar Westerlund * display_status.c (calling_error, routine_error): right shift the code to make it possible to index into the arrays 1999-07-28 Assar Westerlund * gssapi.h (GSS_C_AF_INET6): add * import_name.c (import_hostbased_name): set minor_status 1999-07-26 Assar Westerlund * Makefile.am: set version to 0:1:0 Wed Apr 7 14:05:15 1999 Johan Danielsson * display_status.c: set minor_status * init_sec_context.c: set minor_status * lib/gssapi/init.c: remove donep (check gssapi_krb5_context directly) heimdal-7.5.0/lib/gssapi/test_common.c0000644000175000017500000000525113026237312016003 0ustar niknik/* * Copyright (c) 2006 - 2008 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of KTH nor the names of its contributors may be * used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY KTH AND ITS CONTRIBUTORS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL KTH OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "krb5/gsskrb5_locl.h" #include #include "test_common.h" char * gssapi_err(OM_uint32 maj_stat, OM_uint32 min_stat, gss_OID mech) { OM_uint32 disp_min_stat; gss_buffer_desc maj_error_message; gss_buffer_desc min_error_message; OM_uint32 msg_ctx = 0; char *ret = NULL; maj_error_message.length = 0; maj_error_message.value = NULL; min_error_message.length = 0; min_error_message.value = NULL; (void) gss_display_status(&disp_min_stat, maj_stat, GSS_C_GSS_CODE, mech, &msg_ctx, &maj_error_message); (void) gss_display_status(&disp_min_stat, min_stat, GSS_C_MECH_CODE, mech, &msg_ctx, &min_error_message); if (asprintf(&ret, "gss-code: %lu %.*s -- mech-code: %lu %.*s", (unsigned long)maj_stat, (int)maj_error_message.length, (char *)maj_error_message.value, (unsigned long)min_stat, (int)min_error_message.length, (char *)min_error_message.value) < 0 || ret == NULL) errx(1, "malloc"); gss_release_buffer(&disp_min_stat, &maj_error_message); gss_release_buffer(&disp_min_stat, &min_error_message); return ret; } heimdal-7.5.0/lib/gssapi/oid.txt0000644000175000017500000001414313026237312014624 0ustar niknik# /* contact Love Hörnquist Åstrand for new oid arcs */ # /* # * 1.2.752.43.13 Heimdal GSS-API Extentions # */ oid base GSS_KRB5_COPY_CCACHE_X 1.2.752.43.13.1 oid base GSS_KRB5_GET_TKT_FLAGS_X 1.2.752.43.13.2 oid base GSS_KRB5_EXTRACT_AUTHZ_DATA_FROM_SEC_CONTEXT_X 1.2.752.43.13.3 oid base GSS_KRB5_COMPAT_DES3_MIC_X 1.2.752.43.13.4 oid base GSS_KRB5_REGISTER_ACCEPTOR_IDENTITY_X 1.2.752.43.13.5 oid base GSS_KRB5_EXPORT_LUCID_CONTEXT_X 1.2.752.43.13.6 oid base GSS_KRB5_EXPORT_LUCID_CONTEXT_V1_X 1.2.752.43.13.6.1 oid base GSS_KRB5_SET_DNS_CANONICALIZE_X 1.2.752.43.13.7 oid base GSS_KRB5_GET_SUBKEY_X 1.2.752.43.13.8 oid base GSS_KRB5_GET_INITIATOR_SUBKEY_X 1.2.752.43.13.9 oid base GSS_KRB5_GET_ACCEPTOR_SUBKEY_X 1.2.752.43.13.10 oid base GSS_KRB5_SEND_TO_KDC_X 1.2.752.43.13.11 oid base GSS_KRB5_GET_AUTHTIME_X 1.2.752.43.13.12 oid base GSS_KRB5_GET_SERVICE_KEYBLOCK_X 1.2.752.43.13.13 oid base GSS_KRB5_SET_ALLOWABLE_ENCTYPES_X 1.2.752.43.13.14 oid base GSS_KRB5_SET_DEFAULT_REALM_X 1.2.752.43.13.15 oid base GSS_KRB5_CCACHE_NAME_X 1.2.752.43.13.16 oid base GSS_KRB5_SET_TIME_OFFSET_X 1.2.752.43.13.17 oid base GSS_KRB5_GET_TIME_OFFSET_X 1.2.752.43.13.18 oid base GSS_KRB5_PLUGIN_REGISTER_X 1.2.752.43.13.19 oid base GSS_NTLM_GET_SESSION_KEY_X 1.2.752.43.13.20 oid base GSS_C_NT_NTLM 1.2.752.43.13.21 oid base GSS_C_NT_DN 1.2.752.43.13.22 oid base GSS_KRB5_NT_PRINCIPAL_NAME_REFERRAL 1.2.752.43.13.23 oid base GSS_C_NTLM_AVGUEST 1.2.752.43.13.24 oid base GSS_C_NTLM_V1 1.2.752.43.13.25 oid base GSS_C_NTLM_V2 1.2.752.43.13.26 oid base GSS_C_NTLM_SESSION_KEY 1.2.752.43.13.27 oid base GSS_C_NTLM_FORCE_V1 1.2.752.43.13.28 oid base GSS_KRB5_CRED_NO_CI_FLAGS_X 1.2.752.43.13.29 oid base GSS_KRB5_IMPORT_CRED_X 1.2.752.43.13.30 # /* glue for gss_inquire_saslname_for_mech */ oid base GSS_C_MA_SASL_MECH_NAME 1.2.752.43.13.100 oid base GSS_C_MA_MECH_NAME 1.2.752.43.13.101 oid base GSS_C_MA_MECH_DESCRIPTION 1.2.752.43.13.102 # /* credential types */ oid base GSS_C_CRED_PASSWORD 1.2.752.43.13.200 oid base GSS_C_CRED_CERTIFICATE 1.2.752.43.13.201 #/* Heimdal mechanisms - 1.2.752.43.14 */ oid base GSS_SASL_DIGEST_MD5_MECHANISM 1.2.752.43.14.1 oid base GSS_NETLOGON_MECHANISM 1.2.752.43.14.2 oid base GSS_NETLOGON_SET_SESSION_KEY_X 1.2.752.43.14.3 oid base GSS_NETLOGON_SET_SIGN_ALGORITHM_X 1.2.752.43.14.4 oid base GSS_NETLOGON_NT_NETBIOS_DNS_NAME 1.2.752.43.14.5 #/* GSS_KRB5_EXTRACT_AUTHZ_DATA_FROM_SEC_CONTEXT_X.128 */ oid base GSS_C_INQ_WIN2K_PAC_X 1.2.752.43.13.3.128 oid base GSS_C_INQ_SSPI_SESSION_KEY 1.2.840.113554.1.2.2.5.5 #/* # * "Standard" mechs # */ oid base GSS_KRB5_MECHANISM 1.2.840.113554.1.2.2 oid base GSS_NTLM_MECHANISM 1.3.6.1.4.1.311.2.2.10 oid base GSS_SPNEGO_MECHANISM 1.3.6.1.5.5.2 # /* From Luke Howard */ oid base GSS_C_PEER_HAS_UPDATED_SPNEGO 1.3.6.1.4.1.5322.19.5 #/* # * OID mappings with name and short description and and slightly longer description # */ desc mech GSS_KRB5_MECHANISM "Kerberos 5" "Heimdal Kerberos 5 mechanism" desc mech GSS_NTLM_MECHANISM "NTLM" "Heimdal NTLM mechanism" desc mech GSS_SPNEGO_MECHANISM "SPNEGO" "Heimdal SPNEGO mechanism" desc ma GSS_C_MA_MECH_NAME "GSS mech name" "The name of the GSS-API mechanism" desc ma GSS_C_MA_SASL_MECH_NAME "SASL mechanism name" "The name of the SASL mechanism" desc ma GSS_C_MA_MECH_DESCRIPTION "Mech description" "The long description of the mechanism" #/* # * RFC5587 # */ oid base GSS_C_MA_MECH_CONCRETE 1.3.6.1.5.5.13.1 oid base GSS_C_MA_MECH_PSEUDO 1.3.6.1.5.5.13.2 oid base GSS_C_MA_MECH_COMPOSITE 1.3.6.1.5.5.13.3 oid base GSS_C_MA_MECH_NEGO 1.3.6.1.5.5.13.4 oid base GSS_C_MA_MECH_GLUE 1.3.6.1.5.5.13.5 oid base GSS_C_MA_NOT_MECH 1.3.6.1.5.5.13.6 oid base GSS_C_MA_DEPRECATED 1.3.6.1.5.5.13.7 oid base GSS_C_MA_NOT_DFLT_MECH 1.3.6.1.5.5.13.8 oid base GSS_C_MA_ITOK_FRAMED 1.3.6.1.5.5.13.9 oid base GSS_C_MA_AUTH_INIT 1.3.6.1.5.5.13.10 oid base GSS_C_MA_AUTH_TARG 1.3.6.1.5.5.13.11 oid base GSS_C_MA_AUTH_INIT_INIT 1.3.6.1.5.5.13.12 oid base GSS_C_MA_AUTH_TARG_INIT 1.3.6.1.5.5.13.13 oid base GSS_C_MA_AUTH_INIT_ANON 1.3.6.1.5.5.13.14 oid base GSS_C_MA_AUTH_TARG_ANON 1.3.6.1.5.5.13.15 oid base GSS_C_MA_DELEG_CRED 1.3.6.1.5.5.13.16 oid base GSS_C_MA_INTEG_PROT 1.3.6.1.5.5.13.17 oid base GSS_C_MA_CONF_PROT 1.3.6.1.5.5.13.18 oid base GSS_C_MA_MIC 1.3.6.1.5.5.13.19 oid base GSS_C_MA_WRAP 1.3.6.1.5.5.13.20 oid base GSS_C_MA_PROT_READY 1.3.6.1.5.5.13.21 oid base GSS_C_MA_REPLAY_DET 1.3.6.1.5.5.13.22 oid base GSS_C_MA_OOS_DET 1.3.6.1.5.5.13.23 oid base GSS_C_MA_CBINDINGS 1.3.6.1.5.5.13.24 oid base GSS_C_MA_PFS 1.3.6.1.5.5.13.25 oid base GSS_C_MA_COMPRESS 1.3.6.1.5.5.13.26 oid base GSS_C_MA_CTX_TRANS 1.3.6.1.5.5.13.27 desc ma GSS_C_MA_MECH_CONCRETE "concrete-mech" "Indicates that a mech is neither a pseudo-mechanism nor a composite mechanism" desc ma GSS_C_MA_MECH_PSEUDO "pseudo-mech" "" desc ma GSS_C_MA_MECH_COMPOSITE "composite-mech" "" desc ma GSS_C_MA_MECH_NEGO "mech-negotiation-mech" "" desc ma GSS_C_MA_MECH_GLUE "mech-glue" "" desc ma GSS_C_MA_NOT_MECH "not-mech" "" desc ma GSS_C_MA_DEPRECATED "mech-deprecated" "" desc ma GSS_C_MA_NOT_DFLT_MECH "mech-not-default" "" desc ma GSS_C_MA_ITOK_FRAMED "initial-is-framed" "" desc ma GSS_C_MA_AUTH_INIT "auth-init-princ" "" desc ma GSS_C_MA_AUTH_TARG "auth-targ-princ" "" desc ma GSS_C_MA_AUTH_INIT_INIT "auth-init-princ-initial" "" desc ma GSS_C_MA_AUTH_TARG_INIT "auth-targ-princ-initial" "" desc ma GSS_C_MA_AUTH_INIT_ANON "auth-init-princ-anon" "" desc ma GSS_C_MA_AUTH_TARG_ANON "auth-targ-princ-anon" "" desc ma GSS_C_MA_DELEG_CRED "deleg-cred" "" desc ma GSS_C_MA_INTEG_PROT "integ-prot" "" desc ma GSS_C_MA_CONF_PROT "conf-prot" "" desc ma GSS_C_MA_MIC "mic" "" desc ma GSS_C_MA_WRAP "wrap" "" desc ma GSS_C_MA_PROT_READY "prot-ready" "" desc ma GSS_C_MA_REPLAY_DET "replay-detection" "" desc ma GSS_C_MA_OOS_DET "oos-detection" "" desc ma GSS_C_MA_CBINDINGS "channel-bindings" "" desc ma GSS_C_MA_PFS "pfs" "" desc ma GSS_C_MA_COMPRESS "compress" "" desc ma GSS_C_MA_CTX_TRANS "context-transfer" "" heimdal-7.5.0/lib/gssapi/spnego/0000755000175000017500000000000013214604041014574 5ustar niknikheimdal-7.5.0/lib/gssapi/spnego/context_stubs.c0000644000175000017500000004737713026237312017672 0ustar niknik/* * Copyright (c) 2004, PADL Software Pty Ltd. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of PADL Software nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY PADL SOFTWARE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL PADL SOFTWARE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "spnego_locl.h" static OM_uint32 spnego_supported_mechs(OM_uint32 *minor_status, gss_OID_set *mechs) { OM_uint32 ret, junk; gss_OID_set m; size_t i; ret = gss_indicate_mechs(minor_status, &m); if (ret != GSS_S_COMPLETE) return ret; ret = gss_create_empty_oid_set(minor_status, mechs); if (ret != GSS_S_COMPLETE) { gss_release_oid_set(&junk, &m); return ret; } for (i = 0; i < m->count; i++) { if (gss_oid_equal(&m->elements[i], GSS_SPNEGO_MECHANISM)) continue; ret = gss_add_oid_set_member(minor_status, &m->elements[i], mechs); if (ret) { gss_release_oid_set(&junk, &m); gss_release_oid_set(&junk, mechs); return ret; } } gss_release_oid_set(&junk, &m); return ret; } OM_uint32 GSSAPI_CALLCONV _gss_spnego_process_context_token (OM_uint32 *minor_status, gss_const_ctx_id_t context_handle, const gss_buffer_t token_buffer ) { gss_ctx_id_t context; gssspnego_ctx ctx; OM_uint32 ret; if (context_handle == GSS_C_NO_CONTEXT) return GSS_S_NO_CONTEXT; context = (gss_ctx_id_t)context_handle; ctx = (gssspnego_ctx)context_handle; HEIMDAL_MUTEX_lock(&ctx->ctx_id_mutex); ret = gss_process_context_token(minor_status, ctx->negotiated_ctx_id, token_buffer); if (ret != GSS_S_COMPLETE) { HEIMDAL_MUTEX_unlock(&ctx->ctx_id_mutex); return ret; } ctx->negotiated_ctx_id = GSS_C_NO_CONTEXT; return _gss_spnego_internal_delete_sec_context(minor_status, &context, GSS_C_NO_BUFFER); } OM_uint32 GSSAPI_CALLCONV _gss_spnego_delete_sec_context (OM_uint32 *minor_status, gss_ctx_id_t *context_handle, gss_buffer_t output_token ) { gssspnego_ctx ctx; if (context_handle == NULL || *context_handle == GSS_C_NO_CONTEXT) return GSS_S_NO_CONTEXT; ctx = (gssspnego_ctx)*context_handle; HEIMDAL_MUTEX_lock(&ctx->ctx_id_mutex); return _gss_spnego_internal_delete_sec_context(minor_status, context_handle, output_token); } OM_uint32 GSSAPI_CALLCONV _gss_spnego_context_time (OM_uint32 *minor_status, gss_const_ctx_id_t context_handle, OM_uint32 *time_rec ) { gssspnego_ctx ctx; *minor_status = 0; if (context_handle == GSS_C_NO_CONTEXT) { return GSS_S_NO_CONTEXT; } ctx = (gssspnego_ctx)context_handle; if (ctx->negotiated_ctx_id == GSS_C_NO_CONTEXT) { return GSS_S_NO_CONTEXT; } return gss_context_time(minor_status, ctx->negotiated_ctx_id, time_rec); } OM_uint32 GSSAPI_CALLCONV _gss_spnego_get_mic (OM_uint32 *minor_status, gss_const_ctx_id_t context_handle, gss_qop_t qop_req, const gss_buffer_t message_buffer, gss_buffer_t message_token ) { gssspnego_ctx ctx; *minor_status = 0; if (context_handle == GSS_C_NO_CONTEXT) { return GSS_S_NO_CONTEXT; } ctx = (gssspnego_ctx)context_handle; if (ctx->negotiated_ctx_id == GSS_C_NO_CONTEXT) { return GSS_S_NO_CONTEXT; } return gss_get_mic(minor_status, ctx->negotiated_ctx_id, qop_req, message_buffer, message_token); } OM_uint32 GSSAPI_CALLCONV _gss_spnego_verify_mic (OM_uint32 * minor_status, gss_const_ctx_id_t context_handle, const gss_buffer_t message_buffer, const gss_buffer_t token_buffer, gss_qop_t * qop_state ) { gssspnego_ctx ctx; *minor_status = 0; if (context_handle == GSS_C_NO_CONTEXT) { return GSS_S_NO_CONTEXT; } ctx = (gssspnego_ctx)context_handle; if (ctx->negotiated_ctx_id == GSS_C_NO_CONTEXT) { return GSS_S_NO_CONTEXT; } return gss_verify_mic(minor_status, ctx->negotiated_ctx_id, message_buffer, token_buffer, qop_state); } OM_uint32 GSSAPI_CALLCONV _gss_spnego_wrap (OM_uint32 * minor_status, gss_const_ctx_id_t context_handle, int conf_req_flag, gss_qop_t qop_req, const gss_buffer_t input_message_buffer, int * conf_state, gss_buffer_t output_message_buffer ) { gssspnego_ctx ctx; *minor_status = 0; if (context_handle == GSS_C_NO_CONTEXT) { return GSS_S_NO_CONTEXT; } ctx = (gssspnego_ctx)context_handle; if (ctx->negotiated_ctx_id == GSS_C_NO_CONTEXT) { return GSS_S_NO_CONTEXT; } return gss_wrap(minor_status, ctx->negotiated_ctx_id, conf_req_flag, qop_req, input_message_buffer, conf_state, output_message_buffer); } OM_uint32 GSSAPI_CALLCONV _gss_spnego_unwrap (OM_uint32 * minor_status, gss_const_ctx_id_t context_handle, const gss_buffer_t input_message_buffer, gss_buffer_t output_message_buffer, int * conf_state, gss_qop_t * qop_state ) { gssspnego_ctx ctx; *minor_status = 0; if (context_handle == GSS_C_NO_CONTEXT) { return GSS_S_NO_CONTEXT; } ctx = (gssspnego_ctx)context_handle; if (ctx->negotiated_ctx_id == GSS_C_NO_CONTEXT) { return GSS_S_NO_CONTEXT; } return gss_unwrap(minor_status, ctx->negotiated_ctx_id, input_message_buffer, output_message_buffer, conf_state, qop_state); } OM_uint32 GSSAPI_CALLCONV _gss_spnego_compare_name (OM_uint32 *minor_status, gss_const_name_t name1, gss_const_name_t name2, int * name_equal ) { spnego_name n1 = (spnego_name)name1; spnego_name n2 = (spnego_name)name2; *name_equal = 0; if (!gss_oid_equal(&n1->type, &n2->type)) return GSS_S_COMPLETE; if (n1->value.length != n2->value.length) return GSS_S_COMPLETE; if (memcmp(n1->value.value, n2->value.value, n2->value.length) != 0) return GSS_S_COMPLETE; *name_equal = 1; return GSS_S_COMPLETE; } OM_uint32 GSSAPI_CALLCONV _gss_spnego_display_name (OM_uint32 * minor_status, gss_const_name_t input_name, gss_buffer_t output_name_buffer, gss_OID * output_name_type ) { spnego_name name = (spnego_name)input_name; *minor_status = 0; if (name == NULL || name->mech == GSS_C_NO_NAME) return GSS_S_FAILURE; return gss_display_name(minor_status, name->mech, output_name_buffer, output_name_type); } OM_uint32 GSSAPI_CALLCONV _gss_spnego_import_name (OM_uint32 * minor_status, const gss_buffer_t name_buffer, const gss_OID name_type, gss_name_t * output_name ) { spnego_name name; OM_uint32 maj_stat; *minor_status = 0; name = calloc(1, sizeof(*name)); if (name == NULL) { *minor_status = ENOMEM; return GSS_S_FAILURE; } maj_stat = _gss_copy_oid(minor_status, name_type, &name->type); if (maj_stat) { free(name); return GSS_S_FAILURE; } maj_stat = _gss_copy_buffer(minor_status, name_buffer, &name->value); if (maj_stat) { gss_name_t rname = (gss_name_t)name; _gss_spnego_release_name(minor_status, &rname); return GSS_S_FAILURE; } name->mech = GSS_C_NO_NAME; *output_name = (gss_name_t)name; return GSS_S_COMPLETE; } OM_uint32 GSSAPI_CALLCONV _gss_spnego_export_name (OM_uint32 * minor_status, gss_const_name_t input_name, gss_buffer_t exported_name ) { spnego_name name; *minor_status = 0; if (input_name == GSS_C_NO_NAME) return GSS_S_BAD_NAME; name = (spnego_name)input_name; if (name->mech == GSS_C_NO_NAME) return GSS_S_BAD_NAME; return gss_export_name(minor_status, name->mech, exported_name); } OM_uint32 GSSAPI_CALLCONV _gss_spnego_release_name (OM_uint32 * minor_status, gss_name_t * input_name ) { *minor_status = 0; if (*input_name != GSS_C_NO_NAME) { OM_uint32 junk; spnego_name name = (spnego_name)*input_name; _gss_free_oid(&junk, &name->type); gss_release_buffer(&junk, &name->value); if (name->mech != GSS_C_NO_NAME) gss_release_name(&junk, &name->mech); free(name); *input_name = GSS_C_NO_NAME; } return GSS_S_COMPLETE; } OM_uint32 GSSAPI_CALLCONV _gss_spnego_inquire_context ( OM_uint32 * minor_status, gss_const_ctx_id_t context_handle, gss_name_t * src_name, gss_name_t * targ_name, OM_uint32 * lifetime_rec, gss_OID * mech_type, OM_uint32 * ctx_flags, int * locally_initiated, int * open_context ) { gssspnego_ctx ctx; OM_uint32 maj_stat, junk; gss_name_t src_mn, targ_mn; *minor_status = 0; if (context_handle == GSS_C_NO_CONTEXT) return GSS_S_NO_CONTEXT; ctx = (gssspnego_ctx)context_handle; if (ctx->negotiated_ctx_id == GSS_C_NO_CONTEXT) return GSS_S_NO_CONTEXT; maj_stat = gss_inquire_context(minor_status, ctx->negotiated_ctx_id, &src_mn, &targ_mn, lifetime_rec, mech_type, ctx_flags, locally_initiated, open_context); if (maj_stat != GSS_S_COMPLETE) return maj_stat; if (src_name) { spnego_name name = calloc(1, sizeof(*name)); if (name == NULL) goto enomem; name->mech = src_mn; *src_name = (gss_name_t)name; } else gss_release_name(&junk, &src_mn); if (targ_name) { spnego_name name = calloc(1, sizeof(*name)); if (name == NULL) { gss_release_name(minor_status, src_name); goto enomem; } name->mech = targ_mn; *targ_name = (gss_name_t)name; } else gss_release_name(&junk, &targ_mn); return GSS_S_COMPLETE; enomem: gss_release_name(&junk, &targ_mn); gss_release_name(&junk, &src_mn); *minor_status = ENOMEM; return GSS_S_FAILURE; } OM_uint32 GSSAPI_CALLCONV _gss_spnego_wrap_size_limit ( OM_uint32 * minor_status, gss_const_ctx_id_t context_handle, int conf_req_flag, gss_qop_t qop_req, OM_uint32 req_output_size, OM_uint32 * max_input_size ) { gssspnego_ctx ctx; *minor_status = 0; if (context_handle == GSS_C_NO_CONTEXT) { return GSS_S_NO_CONTEXT; } ctx = (gssspnego_ctx)context_handle; if (ctx->negotiated_ctx_id == GSS_C_NO_CONTEXT) { return GSS_S_NO_CONTEXT; } return gss_wrap_size_limit(minor_status, ctx->negotiated_ctx_id, conf_req_flag, qop_req, req_output_size, max_input_size); } OM_uint32 GSSAPI_CALLCONV _gss_spnego_export_sec_context ( OM_uint32 * minor_status, gss_ctx_id_t * context_handle, gss_buffer_t interprocess_token ) { gssspnego_ctx ctx; OM_uint32 ret; *minor_status = 0; if (context_handle == NULL) { return GSS_S_NO_CONTEXT; } ctx = (gssspnego_ctx)*context_handle; if (ctx == NULL) return GSS_S_NO_CONTEXT; HEIMDAL_MUTEX_lock(&ctx->ctx_id_mutex); if (ctx->negotiated_ctx_id == GSS_C_NO_CONTEXT) { HEIMDAL_MUTEX_unlock(&ctx->ctx_id_mutex); return GSS_S_NO_CONTEXT; } ret = gss_export_sec_context(minor_status, &ctx->negotiated_ctx_id, interprocess_token); if (ret == GSS_S_COMPLETE) { ret = _gss_spnego_internal_delete_sec_context(minor_status, context_handle, GSS_C_NO_BUFFER); if (ret == GSS_S_COMPLETE) return GSS_S_COMPLETE; } HEIMDAL_MUTEX_unlock(&ctx->ctx_id_mutex); return ret; } OM_uint32 GSSAPI_CALLCONV _gss_spnego_import_sec_context ( OM_uint32 * minor_status, const gss_buffer_t interprocess_token, gss_ctx_id_t *context_handle ) { OM_uint32 ret, minor; gss_ctx_id_t context; gssspnego_ctx ctx; *context_handle = GSS_C_NO_CONTEXT; ret = _gss_spnego_alloc_sec_context(minor_status, &context); if (ret != GSS_S_COMPLETE) { return ret; } ctx = (gssspnego_ctx)context; HEIMDAL_MUTEX_lock(&ctx->ctx_id_mutex); ret = gss_import_sec_context(minor_status, interprocess_token, &ctx->negotiated_ctx_id); if (ret != GSS_S_COMPLETE) { _gss_spnego_internal_delete_sec_context(&minor, &context, GSS_C_NO_BUFFER); return ret; } ctx->open = 1; /* don't bother filling in the rest of the fields */ HEIMDAL_MUTEX_unlock(&ctx->ctx_id_mutex); *context_handle = (gss_ctx_id_t)ctx; return GSS_S_COMPLETE; } OM_uint32 GSSAPI_CALLCONV _gss_spnego_inquire_names_for_mech ( OM_uint32 * minor_status, const gss_OID mechanism, gss_OID_set * name_types ) { gss_OID_set mechs, names, n; OM_uint32 ret, junk; size_t i, j; *name_types = NULL; ret = spnego_supported_mechs(minor_status, &mechs); if (ret != GSS_S_COMPLETE) return ret; ret = gss_create_empty_oid_set(minor_status, &names); if (ret != GSS_S_COMPLETE) goto out; for (i = 0; i < mechs->count; i++) { ret = gss_inquire_names_for_mech(minor_status, &mechs->elements[i], &n); if (ret) continue; for (j = 0; j < n->count; j++) gss_add_oid_set_member(minor_status, &n->elements[j], &names); gss_release_oid_set(&junk, &n); } ret = GSS_S_COMPLETE; *name_types = names; out: gss_release_oid_set(&junk, &mechs); return ret; } OM_uint32 GSSAPI_CALLCONV _gss_spnego_inquire_mechs_for_name ( OM_uint32 * minor_status, gss_const_name_t input_name, gss_OID_set * mech_types ) { OM_uint32 ret, junk; ret = gss_create_empty_oid_set(minor_status, mech_types); if (ret) return ret; ret = gss_add_oid_set_member(minor_status, GSS_SPNEGO_MECHANISM, mech_types); if (ret) gss_release_oid_set(&junk, mech_types); return ret; } OM_uint32 GSSAPI_CALLCONV _gss_spnego_canonicalize_name ( OM_uint32 * minor_status, gss_const_name_t input_name, const gss_OID mech_type, gss_name_t * output_name ) { /* XXX */ return gss_duplicate_name(minor_status, input_name, output_name); } OM_uint32 GSSAPI_CALLCONV _gss_spnego_duplicate_name ( OM_uint32 * minor_status, gss_const_name_t src_name, gss_name_t * dest_name ) { return gss_duplicate_name(minor_status, src_name, dest_name); } OM_uint32 GSSAPI_CALLCONV _gss_spnego_wrap_iov(OM_uint32 * minor_status, gss_ctx_id_t context_handle, int conf_req_flag, gss_qop_t qop_req, int * conf_state, gss_iov_buffer_desc *iov, int iov_count) { gssspnego_ctx ctx = (gssspnego_ctx)context_handle; *minor_status = 0; if (ctx == NULL || ctx->negotiated_ctx_id == GSS_C_NO_CONTEXT) return GSS_S_NO_CONTEXT; return gss_wrap_iov(minor_status, ctx->negotiated_ctx_id, conf_req_flag, qop_req, conf_state, iov, iov_count); } OM_uint32 GSSAPI_CALLCONV _gss_spnego_unwrap_iov(OM_uint32 *minor_status, gss_ctx_id_t context_handle, int *conf_state, gss_qop_t *qop_state, gss_iov_buffer_desc *iov, int iov_count) { gssspnego_ctx ctx = (gssspnego_ctx)context_handle; *minor_status = 0; if (ctx == NULL || ctx->negotiated_ctx_id == GSS_C_NO_CONTEXT) return GSS_S_NO_CONTEXT; return gss_unwrap_iov(minor_status, ctx->negotiated_ctx_id, conf_state, qop_state, iov, iov_count); } OM_uint32 GSSAPI_CALLCONV _gss_spnego_wrap_iov_length(OM_uint32 * minor_status, gss_ctx_id_t context_handle, int conf_req_flag, gss_qop_t qop_req, int *conf_state, gss_iov_buffer_desc *iov, int iov_count) { gssspnego_ctx ctx = (gssspnego_ctx)context_handle; *minor_status = 0; if (ctx == NULL || ctx->negotiated_ctx_id == GSS_C_NO_CONTEXT) return GSS_S_NO_CONTEXT; return gss_wrap_iov_length(minor_status, ctx->negotiated_ctx_id, conf_req_flag, qop_req, conf_state, iov, iov_count); } #if 0 OM_uint32 GSSAPI_CALLCONV _gss_spnego_complete_auth_token (OM_uint32 * minor_status, gss_const_ctx_id_t context_handle, gss_buffer_t input_message_buffer) { gssspnego_ctx ctx; *minor_status = 0; if (context_handle == GSS_C_NO_CONTEXT) { return GSS_S_NO_CONTEXT; } ctx = (gssspnego_ctx)context_handle; if (ctx->negotiated_ctx_id == GSS_C_NO_CONTEXT) { return GSS_S_NO_CONTEXT; } return gss_complete_auth_token(minor_status, ctx->negotiated_ctx_id, input_message_buffer); } #endif OM_uint32 GSSAPI_CALLCONV _gss_spnego_inquire_sec_context_by_oid (OM_uint32 * minor_status, gss_const_ctx_id_t context_handle, const gss_OID desired_object, gss_buffer_set_t *data_set) { gssspnego_ctx ctx; *minor_status = 0; if (context_handle == GSS_C_NO_CONTEXT) { return GSS_S_NO_CONTEXT; } ctx = (gssspnego_ctx)context_handle; if (ctx->negotiated_ctx_id == GSS_C_NO_CONTEXT) { return GSS_S_NO_CONTEXT; } return gss_inquire_sec_context_by_oid(minor_status, ctx->negotiated_ctx_id, desired_object, data_set); } OM_uint32 GSSAPI_CALLCONV _gss_spnego_set_sec_context_option (OM_uint32 * minor_status, gss_ctx_id_t * context_handle, const gss_OID desired_object, const gss_buffer_t value) { gssspnego_ctx ctx; *minor_status = 0; if (context_handle == NULL || *context_handle == GSS_C_NO_CONTEXT) { return GSS_S_NO_CONTEXT; } ctx = (gssspnego_ctx)*context_handle; if (ctx->negotiated_ctx_id == GSS_C_NO_CONTEXT) { return GSS_S_NO_CONTEXT; } return gss_set_sec_context_option(minor_status, &ctx->negotiated_ctx_id, desired_object, value); } OM_uint32 GSSAPI_CALLCONV _gss_spnego_pseudo_random(OM_uint32 *minor_status, gss_ctx_id_t context_handle, int prf_key, const gss_buffer_t prf_in, ssize_t desired_output_len, gss_buffer_t prf_out) { gssspnego_ctx ctx; *minor_status = 0; if (context_handle == GSS_C_NO_CONTEXT) return GSS_S_NO_CONTEXT; ctx = (gssspnego_ctx)context_handle; if (ctx->negotiated_ctx_id == GSS_C_NO_CONTEXT) return GSS_S_NO_CONTEXT; return gss_pseudo_random(minor_status, ctx->negotiated_ctx_id, prf_key, prf_in, desired_output_len, prf_out); } heimdal-7.5.0/lib/gssapi/spnego/accept_sec_context.c0000644000175000017500000005601413212137553020612 0ustar niknik/* * Copyright (c) 1997 - 2006 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * Portions Copyright (c) 2004 PADL Software Pty Ltd. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "spnego_locl.h" static OM_uint32 send_reject (OM_uint32 *minor_status, gss_buffer_t output_token) { NegotiationToken nt; size_t size; nt.element = choice_NegotiationToken_negTokenResp; ALLOC(nt.u.negTokenResp.negResult, 1); if (nt.u.negTokenResp.negResult == NULL) { *minor_status = ENOMEM; return GSS_S_FAILURE; } *(nt.u.negTokenResp.negResult) = reject; nt.u.negTokenResp.supportedMech = NULL; nt.u.negTokenResp.responseToken = NULL; nt.u.negTokenResp.mechListMIC = NULL; ASN1_MALLOC_ENCODE(NegotiationToken, output_token->value, output_token->length, &nt, &size, *minor_status); free_NegotiationToken(&nt); if (*minor_status != 0) return GSS_S_FAILURE; return GSS_S_BAD_MECH; } static OM_uint32 acceptor_approved(gss_name_t target_name, gss_OID mech) { gss_cred_id_t cred = GSS_C_NO_CREDENTIAL; gss_OID_set oidset; OM_uint32 junk, ret; if (target_name == GSS_C_NO_NAME) return GSS_S_COMPLETE; gss_create_empty_oid_set(&junk, &oidset); gss_add_oid_set_member(&junk, mech, &oidset); ret = gss_acquire_cred(&junk, target_name, GSS_C_INDEFINITE, oidset, GSS_C_ACCEPT, &cred, NULL, NULL); gss_release_oid_set(&junk, &oidset); if (ret != GSS_S_COMPLETE) return ret; gss_release_cred(&junk, &cred); return GSS_S_COMPLETE; } static OM_uint32 send_supported_mechs (OM_uint32 *minor_status, gss_buffer_t output_token) { NegotiationTokenWin nt; size_t buf_len = 0; gss_buffer_desc data; OM_uint32 ret; memset(&nt, 0, sizeof(nt)); nt.element = choice_NegotiationTokenWin_negTokenInit; nt.u.negTokenInit.reqFlags = NULL; nt.u.negTokenInit.mechToken = NULL; nt.u.negTokenInit.negHints = NULL; ret = _gss_spnego_indicate_mechtypelist(minor_status, GSS_C_NO_NAME, acceptor_approved, 1, NULL, &nt.u.negTokenInit.mechTypes, NULL); if (ret != GSS_S_COMPLETE) { return ret; } ALLOC(nt.u.negTokenInit.negHints, 1); if (nt.u.negTokenInit.negHints == NULL) { *minor_status = ENOMEM; free_NegotiationTokenWin(&nt); return GSS_S_FAILURE; } ALLOC(nt.u.negTokenInit.negHints->hintName, 1); if (nt.u.negTokenInit.negHints->hintName == NULL) { *minor_status = ENOMEM; free_NegotiationTokenWin(&nt); return GSS_S_FAILURE; } *nt.u.negTokenInit.negHints->hintName = strdup("not_defined_in_RFC4178@please_ignore"); nt.u.negTokenInit.negHints->hintAddress = NULL; ASN1_MALLOC_ENCODE(NegotiationTokenWin, data.value, data.length, &nt, &buf_len, ret); free_NegotiationTokenWin(&nt); if (ret) { *minor_status = ret; return GSS_S_FAILURE; } if (data.length != buf_len) { abort(); UNREACHABLE(return GSS_S_FAILURE); } ret = gss_encapsulate_token(&data, GSS_SPNEGO_MECHANISM, output_token); free (data.value); if (ret != GSS_S_COMPLETE) return ret; *minor_status = 0; return GSS_S_CONTINUE_NEEDED; } static OM_uint32 send_accept (OM_uint32 *minor_status, gssspnego_ctx context_handle, gss_buffer_t mech_token, int initial_response, gss_buffer_t mech_buf, gss_buffer_t output_token) { NegotiationToken nt; OM_uint32 ret; gss_buffer_desc mech_mic_buf; size_t size; memset(&nt, 0, sizeof(nt)); nt.element = choice_NegotiationToken_negTokenResp; ALLOC(nt.u.negTokenResp.negResult, 1); if (nt.u.negTokenResp.negResult == NULL) { *minor_status = ENOMEM; return GSS_S_FAILURE; } if (context_handle->open) { if (mech_token != GSS_C_NO_BUFFER && mech_token->length != 0 && mech_buf != GSS_C_NO_BUFFER) *(nt.u.negTokenResp.negResult) = accept_incomplete; else *(nt.u.negTokenResp.negResult) = accept_completed; } else { if (initial_response && context_handle->require_mic) *(nt.u.negTokenResp.negResult) = request_mic; else *(nt.u.negTokenResp.negResult) = accept_incomplete; } if (initial_response) { ALLOC(nt.u.negTokenResp.supportedMech, 1); if (nt.u.negTokenResp.supportedMech == NULL) { free_NegotiationToken(&nt); *minor_status = ENOMEM; return GSS_S_FAILURE; } ret = der_get_oid(context_handle->preferred_mech_type->elements, context_handle->preferred_mech_type->length, nt.u.negTokenResp.supportedMech, NULL); if (ret) { free_NegotiationToken(&nt); *minor_status = ENOMEM; return GSS_S_FAILURE; } } else { nt.u.negTokenResp.supportedMech = NULL; } if (mech_token != GSS_C_NO_BUFFER && mech_token->length != 0) { ALLOC(nt.u.negTokenResp.responseToken, 1); if (nt.u.negTokenResp.responseToken == NULL) { free_NegotiationToken(&nt); *minor_status = ENOMEM; return GSS_S_FAILURE; } nt.u.negTokenResp.responseToken->length = mech_token->length; nt.u.negTokenResp.responseToken->data = mech_token->value; mech_token->length = 0; mech_token->value = NULL; } else { nt.u.negTokenResp.responseToken = NULL; } if (mech_buf != GSS_C_NO_BUFFER) { ret = gss_get_mic(minor_status, context_handle->negotiated_ctx_id, 0, mech_buf, &mech_mic_buf); if (ret == GSS_S_COMPLETE) { ALLOC(nt.u.negTokenResp.mechListMIC, 1); if (nt.u.negTokenResp.mechListMIC == NULL) { gss_release_buffer(minor_status, &mech_mic_buf); free_NegotiationToken(&nt); *minor_status = ENOMEM; return GSS_S_FAILURE; } nt.u.negTokenResp.mechListMIC->length = mech_mic_buf.length; nt.u.negTokenResp.mechListMIC->data = mech_mic_buf.value; } else if (ret == GSS_S_UNAVAILABLE) { nt.u.negTokenResp.mechListMIC = NULL; } else { free_NegotiationToken(&nt); return ret; } } else nt.u.negTokenResp.mechListMIC = NULL; ASN1_MALLOC_ENCODE(NegotiationToken, output_token->value, output_token->length, &nt, &size, ret); if (ret) { free_NegotiationToken(&nt); *minor_status = ret; return GSS_S_FAILURE; } /* * The response should not be encapsulated, because * it is a SubsequentContextToken (note though RFC 1964 * specifies encapsulation for all _Kerberos_ tokens). */ if (*(nt.u.negTokenResp.negResult) == accept_completed) ret = GSS_S_COMPLETE; else ret = GSS_S_CONTINUE_NEEDED; free_NegotiationToken(&nt); return ret; } static OM_uint32 verify_mechlist_mic (OM_uint32 *minor_status, gssspnego_ctx context_handle, gss_buffer_t mech_buf, heim_octet_string *mechListMIC ) { OM_uint32 ret; gss_buffer_desc mic_buf; if (context_handle->verified_mic) { /* This doesn't make sense, we've already verified it? */ *minor_status = 0; return GSS_S_DUPLICATE_TOKEN; } if (mechListMIC == NULL) { *minor_status = 0; return GSS_S_DEFECTIVE_TOKEN; } mic_buf.length = mechListMIC->length; mic_buf.value = mechListMIC->data; ret = gss_verify_mic(minor_status, context_handle->negotiated_ctx_id, mech_buf, &mic_buf, NULL); if (ret != GSS_S_COMPLETE) ret = GSS_S_DEFECTIVE_TOKEN; return ret; } static OM_uint32 select_mech(OM_uint32 *minor_status, MechType *mechType, int verify_p, gss_OID *mech_p) { char mechbuf[64]; size_t mech_len; gss_OID_desc oid; gss_OID oidp; gss_OID_set mechs; size_t i; OM_uint32 ret, junk; ret = der_put_oid ((unsigned char *)mechbuf + sizeof(mechbuf) - 1, sizeof(mechbuf), mechType, &mech_len); if (ret) { return GSS_S_DEFECTIVE_TOKEN; } oid.length = mech_len; oid.elements = mechbuf + sizeof(mechbuf) - mech_len; if (gss_oid_equal(&oid, GSS_SPNEGO_MECHANISM)) { return GSS_S_BAD_MECH; } *minor_status = 0; /* Translate broken MS Kebreros OID */ if (gss_oid_equal(&oid, &_gss_spnego_mskrb_mechanism_oid_desc)) oidp = &_gss_spnego_krb5_mechanism_oid_desc; else oidp = &oid; ret = gss_indicate_mechs(&junk, &mechs); if (ret) return (ret); for (i = 0; i < mechs->count; i++) if (gss_oid_equal(&mechs->elements[i], oidp)) break; if (i == mechs->count) { gss_release_oid_set(&junk, &mechs); return GSS_S_BAD_MECH; } gss_release_oid_set(&junk, &mechs); ret = gss_duplicate_oid(minor_status, &oid, /* possibly this should be oidp */ mech_p); if (verify_p) { gss_name_t name = GSS_C_NO_NAME; gss_buffer_desc namebuf; char *str = NULL, *host, hostname[MAXHOSTNAMELEN]; host = getenv("GSSAPI_SPNEGO_NAME"); if (host == NULL || issuid()) { int rv; if (gethostname(hostname, sizeof(hostname)) != 0) { *minor_status = errno; return GSS_S_FAILURE; } rv = asprintf(&str, "host@%s", hostname); if (rv < 0 || str == NULL) { *minor_status = ENOMEM; return GSS_S_FAILURE; } host = str; } namebuf.length = strlen(host); namebuf.value = host; ret = gss_import_name(minor_status, &namebuf, GSS_C_NT_HOSTBASED_SERVICE, &name); if (str) free(str); if (ret != GSS_S_COMPLETE) return ret; ret = acceptor_approved(name, *mech_p); gss_release_name(&junk, &name); } return ret; } static OM_uint32 acceptor_complete(OM_uint32 * minor_status, gssspnego_ctx ctx, int *get_mic, gss_buffer_t mech_buf, gss_buffer_t mech_input_token, gss_buffer_t mech_output_token, heim_octet_string *mic, gss_buffer_t output_token) { OM_uint32 ret; int require_mic, verify_mic; ret = _gss_spnego_require_mechlist_mic(minor_status, ctx, &require_mic); if (ret) return ret; ctx->require_mic = require_mic; if (mic != NULL) require_mic = 1; if (ctx->open && require_mic) { if (mech_input_token == GSS_C_NO_BUFFER) { /* Even/One */ verify_mic = 1; *get_mic = 0; } else if (mech_output_token != GSS_C_NO_BUFFER && mech_output_token->length == 0) { /* Odd */ *get_mic = verify_mic = 1; } else { /* Even/One */ verify_mic = 0; *get_mic = 1; } if (verify_mic || *get_mic) { int eret; size_t buf_len = 0; ASN1_MALLOC_ENCODE(MechTypeList, mech_buf->value, mech_buf->length, &ctx->initiator_mech_types, &buf_len, eret); if (eret) { *minor_status = eret; return GSS_S_FAILURE; } heim_assert(mech_buf->length == buf_len, "Internal ASN.1 error"); UNREACHABLE(return GSS_S_FAILURE); } if (verify_mic) { ret = verify_mechlist_mic(minor_status, ctx, mech_buf, mic); if (ret) { if (*get_mic) send_reject (minor_status, output_token); return ret; } ctx->verified_mic = 1; } } else *get_mic = 0; return GSS_S_COMPLETE; } static OM_uint32 GSSAPI_CALLCONV acceptor_start (OM_uint32 * minor_status, gss_ctx_id_t * context_handle, gss_const_cred_id_t acceptor_cred_handle, const gss_buffer_t input_token_buffer, const gss_channel_bindings_t input_chan_bindings, gss_name_t * src_name, gss_OID * mech_type, gss_buffer_t output_token, OM_uint32 * ret_flags, OM_uint32 * time_rec, gss_cred_id_t *delegated_cred_handle ) { OM_uint32 ret, junk; NegotiationToken nt; size_t nt_len; NegTokenInit *ni; gss_buffer_desc data; gss_buffer_t mech_input_token = GSS_C_NO_BUFFER; gss_buffer_desc mech_output_token; gss_buffer_desc mech_buf; gss_OID preferred_mech_type = GSS_C_NO_OID; gssspnego_ctx ctx; int get_mic = 0; int first_ok = 0; mech_output_token.value = NULL; mech_output_token.length = 0; mech_buf.value = NULL; if (input_token_buffer->length == 0) return send_supported_mechs (minor_status, output_token); ret = _gss_spnego_alloc_sec_context(minor_status, context_handle); if (ret != GSS_S_COMPLETE) return ret; ctx = (gssspnego_ctx)*context_handle; /* * The GSS-API encapsulation is only present on the initial * context token (negTokenInit). */ ret = gss_decapsulate_token (input_token_buffer, GSS_SPNEGO_MECHANISM, &data); if (ret) return ret; ret = decode_NegotiationToken(data.value, data.length, &nt, &nt_len); gss_release_buffer(minor_status, &data); if (ret) { *minor_status = ret; return GSS_S_DEFECTIVE_TOKEN; } if (nt.element != choice_NegotiationToken_negTokenInit) { *minor_status = 0; return GSS_S_DEFECTIVE_TOKEN; } ni = &nt.u.negTokenInit; if (ni->mechTypes.len < 1) { free_NegotiationToken(&nt); *minor_status = 0; return GSS_S_DEFECTIVE_TOKEN; } HEIMDAL_MUTEX_lock(&ctx->ctx_id_mutex); ret = copy_MechTypeList(&ni->mechTypes, &ctx->initiator_mech_types); if (ret) { HEIMDAL_MUTEX_unlock(&ctx->ctx_id_mutex); free_NegotiationToken(&nt); *minor_status = ret; return GSS_S_FAILURE; } /* * First we try the opportunistic token if we have support for it, * don't try to verify we have credential for the token, * gss_accept_sec_context() will (hopefully) tell us that. * If that failes, */ ret = select_mech(minor_status, &ni->mechTypes.val[0], 0, &preferred_mech_type); if (ret == 0 && ni->mechToken != NULL) { gss_buffer_desc ibuf; ibuf.length = ni->mechToken->length; ibuf.value = ni->mechToken->data; mech_input_token = &ibuf; if (ctx->mech_src_name != GSS_C_NO_NAME) gss_release_name(&junk, &ctx->mech_src_name); ret = gss_accept_sec_context(minor_status, &ctx->negotiated_ctx_id, acceptor_cred_handle, mech_input_token, input_chan_bindings, &ctx->mech_src_name, &ctx->negotiated_mech_type, &mech_output_token, &ctx->mech_flags, &ctx->mech_time_rec, delegated_cred_handle); if (ret == GSS_S_COMPLETE || ret == GSS_S_CONTINUE_NEEDED) { ctx->preferred_mech_type = preferred_mech_type; if (ret == GSS_S_COMPLETE) ctx->open = 1; ret = acceptor_complete(minor_status, ctx, &get_mic, &mech_buf, mech_input_token, &mech_output_token, ni->mechListMIC, output_token); if (ret != GSS_S_COMPLETE) goto out; first_ok = 1; } else { gss_mg_collect_error(preferred_mech_type, ret, *minor_status); } } /* * If opportunistic token failed, lets try the other mechs. */ if (!first_ok && ni->mechToken != NULL) { size_t j; preferred_mech_type = GSS_C_NO_OID; /* Call glue layer to find first mech we support */ for (j = 1; j < ni->mechTypes.len; ++j) { ret = select_mech(minor_status, &ni->mechTypes.val[j], 1, &preferred_mech_type); if (ret == 0) break; } if (preferred_mech_type == GSS_C_NO_OID) { HEIMDAL_MUTEX_unlock(&ctx->ctx_id_mutex); free_NegotiationToken(&nt); return ret; } ctx->preferred_mech_type = preferred_mech_type; } /* * The initial token always have a response */ ret = send_accept (minor_status, ctx, &mech_output_token, 1, get_mic ? &mech_buf : NULL, output_token); if (ret) goto out; out: if (mech_output_token.value != NULL) gss_release_buffer(&junk, &mech_output_token); if (mech_buf.value != NULL) { free(mech_buf.value); mech_buf.value = NULL; } free_NegotiationToken(&nt); if (ret == GSS_S_COMPLETE) { if (src_name != NULL && ctx->mech_src_name != NULL) { spnego_name name; name = calloc(1, sizeof(*name)); if (name) { name->mech = ctx->mech_src_name; ctx->mech_src_name = NULL; *src_name = (gss_name_t)name; } } } if (mech_type != NULL) *mech_type = ctx->negotiated_mech_type; if (ret_flags != NULL) *ret_flags = ctx->mech_flags; if (time_rec != NULL) *time_rec = ctx->mech_time_rec; if (ret == GSS_S_COMPLETE || ret == GSS_S_CONTINUE_NEEDED) { HEIMDAL_MUTEX_unlock(&ctx->ctx_id_mutex); return ret; } _gss_spnego_internal_delete_sec_context(&junk, context_handle, GSS_C_NO_BUFFER); return ret; } static OM_uint32 GSSAPI_CALLCONV acceptor_continue (OM_uint32 * minor_status, gss_ctx_id_t * context_handle, gss_const_cred_id_t acceptor_cred_handle, const gss_buffer_t input_token_buffer, const gss_channel_bindings_t input_chan_bindings, gss_name_t * src_name, gss_OID * mech_type, gss_buffer_t output_token, OM_uint32 * ret_flags, OM_uint32 * time_rec, gss_cred_id_t *delegated_cred_handle ) { OM_uint32 ret, ret2, minor; NegotiationToken nt; size_t nt_len; NegTokenResp *na; unsigned int negResult = accept_incomplete; gss_buffer_t mech_input_token = GSS_C_NO_BUFFER; gss_buffer_t mech_output_token = GSS_C_NO_BUFFER; gss_buffer_desc mech_buf; gssspnego_ctx ctx; mech_buf.value = NULL; ctx = (gssspnego_ctx)*context_handle; /* * The GSS-API encapsulation is only present on the initial * context token (negTokenInit). */ ret = decode_NegotiationToken(input_token_buffer->value, input_token_buffer->length, &nt, &nt_len); if (ret) { *minor_status = ret; return GSS_S_DEFECTIVE_TOKEN; } if (nt.element != choice_NegotiationToken_negTokenResp) { *minor_status = 0; return GSS_S_DEFECTIVE_TOKEN; } na = &nt.u.negTokenResp; if (na->negResult != NULL) { negResult = *(na->negResult); } HEIMDAL_MUTEX_lock(&ctx->ctx_id_mutex); { gss_buffer_desc ibuf, obuf; int require_mic, get_mic = 0; int require_response; heim_octet_string *mic; if (na->responseToken != NULL) { ibuf.length = na->responseToken->length; ibuf.value = na->responseToken->data; mech_input_token = &ibuf; } else { ibuf.value = NULL; ibuf.length = 0; } if (mech_input_token != GSS_C_NO_BUFFER) { if (ctx->mech_src_name != GSS_C_NO_NAME) gss_release_name(&minor, &ctx->mech_src_name); ret = gss_accept_sec_context(&minor, &ctx->negotiated_ctx_id, acceptor_cred_handle, mech_input_token, input_chan_bindings, &ctx->mech_src_name, &ctx->negotiated_mech_type, &obuf, &ctx->mech_flags, &ctx->mech_time_rec, delegated_cred_handle); if (ret == GSS_S_COMPLETE || ret == GSS_S_CONTINUE_NEEDED) { mech_output_token = &obuf; } if (ret != GSS_S_COMPLETE && ret != GSS_S_CONTINUE_NEEDED) { free_NegotiationToken(&nt); gss_mg_collect_error(ctx->negotiated_mech_type, ret, minor); send_reject (minor_status, output_token); HEIMDAL_MUTEX_unlock(&ctx->ctx_id_mutex); return ret; } if (ret == GSS_S_COMPLETE) ctx->open = 1; } else ret = GSS_S_COMPLETE; ret2 = _gss_spnego_require_mechlist_mic(minor_status, ctx, &require_mic); if (ret2) goto out; ctx->require_mic = require_mic; mic = na->mechListMIC; if (mic != NULL) require_mic = 1; if (ret == GSS_S_COMPLETE) ret = acceptor_complete(minor_status, ctx, &get_mic, &mech_buf, mech_input_token, mech_output_token, na->mechListMIC, output_token); if (ctx->mech_flags & GSS_C_DCE_STYLE) require_response = (negResult != accept_completed); else require_response = 0; /* * Check whether we need to send a result: there should be only * one accept_completed response sent in the entire negotiation */ if ((mech_output_token != GSS_C_NO_BUFFER && mech_output_token->length != 0) || (ctx->open && negResult == accept_incomplete) || require_response || get_mic) { ret2 = send_accept (minor_status, ctx, mech_output_token, 0, get_mic ? &mech_buf : NULL, output_token); if (ret2) goto out; } out: if (ret2 != GSS_S_COMPLETE) ret = ret2; if (mech_output_token != NULL) gss_release_buffer(&minor, mech_output_token); if (mech_buf.value != NULL) free(mech_buf.value); free_NegotiationToken(&nt); } if (ret == GSS_S_COMPLETE) { if (src_name != NULL && ctx->mech_src_name != NULL) { spnego_name name; name = calloc(1, sizeof(*name)); if (name) { name->mech = ctx->mech_src_name; ctx->mech_src_name = NULL; *src_name = (gss_name_t)name; } } } if (mech_type != NULL) *mech_type = ctx->negotiated_mech_type; if (ret_flags != NULL) *ret_flags = ctx->mech_flags; if (time_rec != NULL) *time_rec = ctx->mech_time_rec; if (ret == GSS_S_COMPLETE || ret == GSS_S_CONTINUE_NEEDED) { HEIMDAL_MUTEX_unlock(&ctx->ctx_id_mutex); return ret; } _gss_spnego_internal_delete_sec_context(&minor, context_handle, GSS_C_NO_BUFFER); return ret; } OM_uint32 GSSAPI_CALLCONV _gss_spnego_accept_sec_context (OM_uint32 * minor_status, gss_ctx_id_t * context_handle, gss_const_cred_id_t acceptor_cred_handle, const gss_buffer_t input_token_buffer, const gss_channel_bindings_t input_chan_bindings, gss_name_t * src_name, gss_OID * mech_type, gss_buffer_t output_token, OM_uint32 * ret_flags, OM_uint32 * time_rec, gss_cred_id_t *delegated_cred_handle ) { _gss_accept_sec_context_t *func; *minor_status = 0; output_token->length = 0; output_token->value = NULL; if (src_name != NULL) *src_name = GSS_C_NO_NAME; if (mech_type != NULL) *mech_type = GSS_C_NO_OID; if (ret_flags != NULL) *ret_flags = 0; if (time_rec != NULL) *time_rec = 0; if (delegated_cred_handle != NULL) *delegated_cred_handle = GSS_C_NO_CREDENTIAL; if (*context_handle == GSS_C_NO_CONTEXT) func = acceptor_start; else func = acceptor_continue; return (*func)(minor_status, context_handle, acceptor_cred_handle, input_token_buffer, input_chan_bindings, src_name, mech_type, output_token, ret_flags, time_rec, delegated_cred_handle); } heimdal-7.5.0/lib/gssapi/spnego/spnego.asn10000644000175000017500000000321512136107747016671 0ustar niknik-- $Id$ SPNEGO DEFINITIONS ::= BEGIN MechType::= OBJECT IDENTIFIER MechTypeList ::= SEQUENCE OF MechType ContextFlags ::= BIT STRING { delegFlag (0), mutualFlag (1), replayFlag (2), sequenceFlag (3), anonFlag (4), confFlag (5), integFlag (6) } NegHints ::= SEQUENCE { hintName [0] GeneralString OPTIONAL, hintAddress [1] OCTET STRING OPTIONAL } NegTokenInitWin ::= SEQUENCE { mechTypes [0] MechTypeList, reqFlags [1] ContextFlags OPTIONAL, mechToken [2] OCTET STRING OPTIONAL, negHints [3] NegHints OPTIONAL } NegTokenInit ::= SEQUENCE { mechTypes [0] MechTypeList, reqFlags [1] ContextFlags OPTIONAL, mechToken [2] OCTET STRING OPTIONAL, mechListMIC [3] OCTET STRING OPTIONAL, ... } -- NB: negResult is not OPTIONAL in the new SPNEGO spec but -- Windows clients do not always send it NegTokenResp ::= SEQUENCE { negResult [0] ENUMERATED { accept_completed (0), accept_incomplete (1), reject (2), request-mic (3) } OPTIONAL, supportedMech [1] MechType OPTIONAL, responseToken [2] OCTET STRING OPTIONAL, mechListMIC [3] OCTET STRING OPTIONAL, ... } NegotiationToken ::= CHOICE { negTokenInit[0] NegTokenInit, negTokenResp[1] NegTokenResp } NegotiationTokenWin ::= CHOICE { negTokenInit[0] NegTokenInitWin } END heimdal-7.5.0/lib/gssapi/spnego/spnego_locl.h0000644000175000017500000000573413026237312017266 0ustar niknik/* * Copyright (c) 2004, PADL Software Pty Ltd. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of PADL Software nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY PADL SOFTWARE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL PADL SOFTWARE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ /* $Id$ */ #ifndef SPNEGO_LOCL_H #define SPNEGO_LOCL_H #include #ifdef HAVE_SYS_TYPES_H #include #endif #ifdef HAVE_SYS_PARAM_H #include #endif #include #ifdef HAVE_PTHREAD_H #include #endif #include #include #include #include #include #include #include #include #ifdef HAVE_NETDB_H #include #endif #include #include #include #include "spnego_asn1.h" #include "utils.h" #include #include #define ALLOC(X, N) (X) = calloc((N), sizeof(*(X))) typedef struct { MechTypeList initiator_mech_types; gss_OID preferred_mech_type; gss_OID negotiated_mech_type; gss_ctx_id_t negotiated_ctx_id; OM_uint32 mech_flags; OM_uint32 mech_time_rec; gss_name_t mech_src_name; unsigned int open : 1; unsigned int local : 1; unsigned int require_mic : 1; unsigned int verified_mic : 1; unsigned int maybe_open : 1; HEIMDAL_MUTEX ctx_id_mutex; gss_name_t target_name; u_char oidbuf[17]; size_t oidlen; } *gssspnego_ctx; typedef struct { gss_OID_desc type; gss_buffer_desc value; gss_name_t mech; } *spnego_name; extern gss_OID_desc _gss_spnego_mskrb_mechanism_oid_desc; extern gss_OID_desc _gss_spnego_krb5_mechanism_oid_desc; #include #endif /* SPNEGO_LOCL_H */ heimdal-7.5.0/lib/gssapi/spnego/external.c0000644000175000017500000001004113026237312016562 0ustar niknik/* * Copyright (c) 2004, PADL Software Pty Ltd. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of PADL Software nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY PADL SOFTWARE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL PADL SOFTWARE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "spnego_locl.h" #include /* * RFC2478, SPNEGO: * The security mechanism of the initial * negotiation token is identified by the Object Identifier * iso.org.dod.internet.security.mechanism.snego (1.3.6.1.5.5.2). */ static gss_mo_desc spnego_mo[] = { { GSS_C_MA_SASL_MECH_NAME, GSS_MO_MA, "SASL mech name", rk_UNCONST("SPNEGO"), _gss_mo_get_ctx_as_string, NULL }, { GSS_C_MA_MECH_NAME, GSS_MO_MA, "Mechanism name", rk_UNCONST("SPNEGO"), _gss_mo_get_ctx_as_string, NULL }, { GSS_C_MA_MECH_DESCRIPTION, GSS_MO_MA, "Mechanism description", rk_UNCONST("Heimdal SPNEGO Mechanism"), _gss_mo_get_ctx_as_string, NULL }, { GSS_C_MA_MECH_NEGO, GSS_MO_MA, NULL, NULL, NULL, NULL }, { GSS_C_MA_MECH_PSEUDO, GSS_MO_MA, NULL, NULL, NULL, NULL } }; static gssapi_mech_interface_desc spnego_mech = { GMI_VERSION, "spnego", {6, rk_UNCONST("\x2b\x06\x01\x05\x05\x02") }, 0, _gss_spnego_acquire_cred, _gss_spnego_release_cred, _gss_spnego_init_sec_context, _gss_spnego_accept_sec_context, _gss_spnego_process_context_token, _gss_spnego_delete_sec_context, _gss_spnego_context_time, _gss_spnego_get_mic, _gss_spnego_verify_mic, _gss_spnego_wrap, _gss_spnego_unwrap, NULL, /* gm_display_status */ NULL, /* gm_indicate_mechs */ _gss_spnego_compare_name, _gss_spnego_display_name, _gss_spnego_import_name, _gss_spnego_export_name, _gss_spnego_release_name, _gss_spnego_inquire_cred, _gss_spnego_inquire_context, _gss_spnego_wrap_size_limit, gss_add_cred, _gss_spnego_inquire_cred_by_mech, _gss_spnego_export_sec_context, _gss_spnego_import_sec_context, NULL /* _gss_spnego_inquire_names_for_mech */, _gss_spnego_inquire_mechs_for_name, _gss_spnego_canonicalize_name, _gss_spnego_duplicate_name, _gss_spnego_inquire_sec_context_by_oid, _gss_spnego_inquire_cred_by_oid, _gss_spnego_set_sec_context_option, _gss_spnego_set_cred_option, _gss_spnego_pseudo_random, _gss_spnego_wrap_iov, _gss_spnego_unwrap_iov, _gss_spnego_wrap_iov_length, NULL, _gss_spnego_export_cred, _gss_spnego_import_cred, NULL, NULL, NULL, NULL, NULL, NULL, NULL, spnego_mo, sizeof(spnego_mo) / sizeof(spnego_mo[0]), NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, }; gssapi_mech_interface __gss_spnego_initialize(void) { return &spnego_mech; } heimdal-7.5.0/lib/gssapi/spnego/init_sec_context.c0000644000175000017500000004353513026237312020317 0ustar niknik/* * Copyright (c) 1997 - 2004 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * Portions Copyright (c) 2004 PADL Software Pty Ltd. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "spnego_locl.h" /* * Is target_name an sane target for `mech´. */ static OM_uint32 initiator_approved(gss_name_t target_name, gss_OID mech) { OM_uint32 min_stat, maj_stat; gss_ctx_id_t ctx = GSS_C_NO_CONTEXT; gss_buffer_desc out; maj_stat = gss_init_sec_context(&min_stat, GSS_C_NO_CREDENTIAL, &ctx, target_name, mech, 0, GSS_C_INDEFINITE, GSS_C_NO_CHANNEL_BINDINGS, GSS_C_NO_BUFFER, NULL, &out, NULL, NULL); if (GSS_ERROR(maj_stat)) { gss_mg_collect_error(mech, maj_stat, min_stat); return GSS_S_BAD_MECH; } gss_release_buffer(&min_stat, &out); gss_delete_sec_context(&min_stat, &ctx, NULL); return GSS_S_COMPLETE; } /* * Send a reply. Note that we only need to send a reply if we * need to send a MIC or a mechanism token. Otherwise, we can * return an empty buffer. * * The return value of this will be returned to the API, so it * must return GSS_S_CONTINUE_NEEDED if a token was generated. */ static OM_uint32 spnego_reply_internal(OM_uint32 *minor_status, gssspnego_ctx context_handle, const gss_buffer_t mech_buf, gss_buffer_t mech_token, gss_buffer_t output_token) { NegotiationToken nt; gss_buffer_desc mic_buf; OM_uint32 ret; size_t size; if (mech_buf == GSS_C_NO_BUFFER && mech_token->length == 0) { output_token->length = 0; output_token->value = NULL; return context_handle->open ? GSS_S_COMPLETE : GSS_S_FAILURE; } memset(&nt, 0, sizeof(nt)); nt.element = choice_NegotiationToken_negTokenResp; ALLOC(nt.u.negTokenResp.negResult, 1); if (nt.u.negTokenResp.negResult == NULL) { *minor_status = ENOMEM; return GSS_S_FAILURE; } nt.u.negTokenResp.supportedMech = NULL; output_token->length = 0; output_token->value = NULL; if (mech_token->length == 0) { nt.u.negTokenResp.responseToken = NULL; *(nt.u.negTokenResp.negResult) = accept_completed; } else { ALLOC(nt.u.negTokenResp.responseToken, 1); if (nt.u.negTokenResp.responseToken == NULL) { free_NegotiationToken(&nt); *minor_status = ENOMEM; return GSS_S_FAILURE; } nt.u.negTokenResp.responseToken->length = mech_token->length; nt.u.negTokenResp.responseToken->data = mech_token->value; mech_token->length = 0; mech_token->value = NULL; *(nt.u.negTokenResp.negResult) = accept_incomplete; } if (mech_buf != GSS_C_NO_BUFFER) { ret = gss_get_mic(minor_status, context_handle->negotiated_ctx_id, 0, mech_buf, &mic_buf); if (ret == GSS_S_COMPLETE) { ALLOC(nt.u.negTokenResp.mechListMIC, 1); if (nt.u.negTokenResp.mechListMIC == NULL) { gss_release_buffer(minor_status, &mic_buf); free_NegotiationToken(&nt); *minor_status = ENOMEM; return GSS_S_FAILURE; } nt.u.negTokenResp.mechListMIC->length = mic_buf.length; nt.u.negTokenResp.mechListMIC->data = mic_buf.value; } else if (ret == GSS_S_UNAVAILABLE) { nt.u.negTokenResp.mechListMIC = NULL; } if (ret) { free_NegotiationToken(&nt); *minor_status = ENOMEM; return GSS_S_FAILURE; } } else { nt.u.negTokenResp.mechListMIC = NULL; } ASN1_MALLOC_ENCODE(NegotiationToken, output_token->value, output_token->length, &nt, &size, ret); if (ret) { free_NegotiationToken(&nt); *minor_status = ret; return GSS_S_FAILURE; } if (*(nt.u.negTokenResp.negResult) == accept_completed) ret = GSS_S_COMPLETE; else ret = GSS_S_CONTINUE_NEEDED; free_NegotiationToken(&nt); return ret; } static OM_uint32 spnego_initial (OM_uint32 * minor_status, gss_const_cred_id_t cred, gss_ctx_id_t * context_handle, gss_const_name_t target_name, const gss_OID mech_type, OM_uint32 req_flags, OM_uint32 time_req, const gss_channel_bindings_t input_chan_bindings, const gss_buffer_t input_token, gss_OID * actual_mech_type, gss_buffer_t output_token, OM_uint32 * ret_flags, OM_uint32 * time_rec ) { NegTokenInit ni; int ret; OM_uint32 sub, minor; gss_buffer_desc mech_token; u_char *buf; size_t buf_size, buf_len; gss_buffer_desc data; size_t ni_len; gss_ctx_id_t context; gssspnego_ctx ctx; spnego_name name = (spnego_name)target_name; *minor_status = 0; memset (&ni, 0, sizeof(ni)); *context_handle = GSS_C_NO_CONTEXT; if (target_name == GSS_C_NO_NAME) return GSS_S_BAD_NAME; sub = _gss_spnego_alloc_sec_context(&minor, &context); if (GSS_ERROR(sub)) { *minor_status = minor; return sub; } ctx = (gssspnego_ctx)context; HEIMDAL_MUTEX_lock(&ctx->ctx_id_mutex); ctx->local = 1; sub = gss_import_name(&minor, &name->value, &name->type, &ctx->target_name); if (GSS_ERROR(sub)) { *minor_status = minor; _gss_spnego_internal_delete_sec_context(&minor, &context, GSS_C_NO_BUFFER); return sub; } sub = _gss_spnego_indicate_mechtypelist(&minor, ctx->target_name, initiator_approved, 0, cred, &ni.mechTypes, &ctx->preferred_mech_type); if (GSS_ERROR(sub)) { *minor_status = minor; _gss_spnego_internal_delete_sec_context(&minor, &context, GSS_C_NO_BUFFER); return sub; } ni.reqFlags = NULL; /* * If we have a credential handle, use it to select the mechanism * that we will use */ /* generate optimistic token */ sub = gss_init_sec_context(&minor, cred, &ctx->negotiated_ctx_id, ctx->target_name, ctx->preferred_mech_type, req_flags, time_req, input_chan_bindings, input_token, &ctx->negotiated_mech_type, &mech_token, &ctx->mech_flags, &ctx->mech_time_rec); if (GSS_ERROR(sub)) { free_NegTokenInit(&ni); *minor_status = minor; gss_mg_collect_error(ctx->preferred_mech_type, sub, minor); _gss_spnego_internal_delete_sec_context(&minor, &context, GSS_C_NO_BUFFER); return sub; } if (sub == GSS_S_COMPLETE) ctx->maybe_open = 1; if (mech_token.length != 0) { ALLOC(ni.mechToken, 1); if (ni.mechToken == NULL) { free_NegTokenInit(&ni); gss_release_buffer(&minor, &mech_token); _gss_spnego_internal_delete_sec_context(&minor, &context, GSS_C_NO_BUFFER); *minor_status = ENOMEM; return GSS_S_FAILURE; } ni.mechToken->length = mech_token.length; ni.mechToken->data = malloc(mech_token.length); if (ni.mechToken->data == NULL && mech_token.length != 0) { free_NegTokenInit(&ni); gss_release_buffer(&minor, &mech_token); *minor_status = ENOMEM; _gss_spnego_internal_delete_sec_context(&minor, &context, GSS_C_NO_BUFFER); return GSS_S_FAILURE; } memcpy(ni.mechToken->data, mech_token.value, mech_token.length); gss_release_buffer(&minor, &mech_token); } else ni.mechToken = NULL; ni.mechListMIC = NULL; ni_len = length_NegTokenInit(&ni); buf_size = 1 + der_length_len(ni_len) + ni_len; buf = malloc(buf_size); if (buf == NULL) { free_NegTokenInit(&ni); *minor_status = ENOMEM; _gss_spnego_internal_delete_sec_context(&minor, &context, GSS_C_NO_BUFFER); return GSS_S_FAILURE; } ret = encode_NegTokenInit(buf + buf_size - 1, ni_len, &ni, &buf_len); if (ret == 0 && ni_len != buf_len) abort(); if (ret == 0) { size_t tmp; ret = der_put_length_and_tag(buf + buf_size - buf_len - 1, buf_size - buf_len, buf_len, ASN1_C_CONTEXT, CONS, 0, &tmp); if (ret == 0 && tmp + buf_len != buf_size) abort(); } if (ret) { *minor_status = ret; free(buf); free_NegTokenInit(&ni); _gss_spnego_internal_delete_sec_context(&minor, &context, GSS_C_NO_BUFFER); return GSS_S_FAILURE; } data.value = buf; data.length = buf_size; ctx->initiator_mech_types.len = ni.mechTypes.len; ctx->initiator_mech_types.val = ni.mechTypes.val; ni.mechTypes.len = 0; ni.mechTypes.val = NULL; free_NegTokenInit(&ni); sub = gss_encapsulate_token(&data, GSS_SPNEGO_MECHANISM, output_token); free (buf); if (sub) { _gss_spnego_internal_delete_sec_context(&minor, &context, GSS_C_NO_BUFFER); return sub; } if (actual_mech_type) *actual_mech_type = ctx->negotiated_mech_type; if (ret_flags) *ret_flags = ctx->mech_flags; if (time_rec) *time_rec = ctx->mech_time_rec; HEIMDAL_MUTEX_unlock(&ctx->ctx_id_mutex); *context_handle = context; return GSS_S_CONTINUE_NEEDED; } static OM_uint32 spnego_reply (OM_uint32 * minor_status, gss_const_cred_id_t cred, gss_ctx_id_t * context_handle, gss_const_name_t target_name, const gss_OID mech_type, OM_uint32 req_flags, OM_uint32 time_req, const gss_channel_bindings_t input_chan_bindings, const gss_buffer_t input_token, gss_OID * actual_mech_type, gss_buffer_t output_token, OM_uint32 * ret_flags, OM_uint32 * time_rec ) { OM_uint32 ret, minor; NegotiationToken resp; gss_OID_desc mech; int require_mic; size_t buf_len = 0; gss_buffer_desc mic_buf, mech_buf; gss_buffer_desc mech_output_token; gssspnego_ctx ctx; *minor_status = 0; ctx = (gssspnego_ctx)*context_handle; output_token->length = 0; output_token->value = NULL; mech_output_token.length = 0; mech_output_token.value = NULL; mech_buf.value = NULL; mech_buf.length = 0; ret = decode_NegotiationToken(input_token->value, input_token->length, &resp, NULL); if (ret) return ret; if (resp.element != choice_NegotiationToken_negTokenResp) { free_NegotiationToken(&resp); *minor_status = 0; return GSS_S_BAD_MECH; } if (resp.u.negTokenResp.negResult == NULL || *(resp.u.negTokenResp.negResult) == reject /* || resp.u.negTokenResp.supportedMech == NULL */ ) { free_NegotiationToken(&resp); return GSS_S_BAD_MECH; } /* * Pick up the mechanism that the acceptor selected, only allow it * to be sent in packet. */ HEIMDAL_MUTEX_lock(&ctx->ctx_id_mutex); if (resp.u.negTokenResp.supportedMech) { if (ctx->oidlen) { free_NegotiationToken(&resp); HEIMDAL_MUTEX_unlock(&ctx->ctx_id_mutex); return GSS_S_BAD_MECH; } ret = der_put_oid(ctx->oidbuf + sizeof(ctx->oidbuf) - 1, sizeof(ctx->oidbuf), resp.u.negTokenResp.supportedMech, &ctx->oidlen); /* Avoid recursively embedded SPNEGO */ if (ret || (ctx->oidlen == GSS_SPNEGO_MECHANISM->length && memcmp(ctx->oidbuf + sizeof(ctx->oidbuf) - ctx->oidlen, GSS_SPNEGO_MECHANISM->elements, ctx->oidlen) == 0)) { free_NegotiationToken(&resp); HEIMDAL_MUTEX_unlock(&ctx->ctx_id_mutex); return GSS_S_BAD_MECH; } /* check if the acceptor took our optimistic token */ if (ctx->oidlen != ctx->preferred_mech_type->length || memcmp(ctx->oidbuf + sizeof(ctx->oidbuf) - ctx->oidlen, ctx->preferred_mech_type->elements, ctx->oidlen) != 0) { gss_delete_sec_context(&minor, &ctx->negotiated_ctx_id, GSS_C_NO_BUFFER); ctx->negotiated_ctx_id = GSS_C_NO_CONTEXT; } } else if (ctx->oidlen == 0) { free_NegotiationToken(&resp); HEIMDAL_MUTEX_unlock(&ctx->ctx_id_mutex); return GSS_S_BAD_MECH; } /* if a token (of non zero length), or no context, pass to underlaying mech */ if ((resp.u.negTokenResp.responseToken != NULL && resp.u.negTokenResp.responseToken->length) || ctx->negotiated_ctx_id == GSS_C_NO_CONTEXT) { gss_buffer_desc mech_input_token; if (resp.u.negTokenResp.responseToken) { mech_input_token.length = resp.u.negTokenResp.responseToken->length; mech_input_token.value = resp.u.negTokenResp.responseToken->data; } else { mech_input_token.length = 0; mech_input_token.value = NULL; } mech.length = ctx->oidlen; mech.elements = ctx->oidbuf + sizeof(ctx->oidbuf) - ctx->oidlen; /* Fall through as if the negotiated mechanism was requested explicitly */ ret = gss_init_sec_context(&minor, cred, &ctx->negotiated_ctx_id, ctx->target_name, &mech, req_flags, time_req, input_chan_bindings, &mech_input_token, &ctx->negotiated_mech_type, &mech_output_token, &ctx->mech_flags, &ctx->mech_time_rec); if (GSS_ERROR(ret)) { HEIMDAL_MUTEX_unlock(&ctx->ctx_id_mutex); free_NegotiationToken(&resp); gss_mg_collect_error(&mech, ret, minor); *minor_status = minor; return ret; } if (ret == GSS_S_COMPLETE) { ctx->open = 1; } } else if (*(resp.u.negTokenResp.negResult) == accept_completed) { if (ctx->maybe_open) ctx->open = 1; } if (*(resp.u.negTokenResp.negResult) == request_mic) { ctx->require_mic = 1; } if (ctx->open) { /* * Verify the mechListMIC if one was provided or CFX was * used and a non-preferred mechanism was selected */ if (resp.u.negTokenResp.mechListMIC != NULL) { require_mic = 1; } else { ret = _gss_spnego_require_mechlist_mic(minor_status, ctx, &require_mic); if (ret) { HEIMDAL_MUTEX_unlock(&ctx->ctx_id_mutex); free_NegotiationToken(&resp); gss_release_buffer(&minor, &mech_output_token); return ret; } } } else { require_mic = 0; } if (require_mic) { ASN1_MALLOC_ENCODE(MechTypeList, mech_buf.value, mech_buf.length, &ctx->initiator_mech_types, &buf_len, ret); if (ret) { HEIMDAL_MUTEX_unlock(&ctx->ctx_id_mutex); free_NegotiationToken(&resp); gss_release_buffer(&minor, &mech_output_token); *minor_status = ret; return GSS_S_FAILURE; } if (mech_buf.length != buf_len) { abort(); UNREACHABLE(return GSS_S_FAILURE); } if (resp.u.negTokenResp.mechListMIC == NULL) { HEIMDAL_MUTEX_unlock(&ctx->ctx_id_mutex); free(mech_buf.value); free_NegotiationToken(&resp); *minor_status = 0; return GSS_S_DEFECTIVE_TOKEN; } mic_buf.length = resp.u.negTokenResp.mechListMIC->length; mic_buf.value = resp.u.negTokenResp.mechListMIC->data; if (mech_output_token.length == 0) { ret = gss_verify_mic(minor_status, ctx->negotiated_ctx_id, &mech_buf, &mic_buf, NULL); if (ret) { HEIMDAL_MUTEX_unlock(&ctx->ctx_id_mutex); free(mech_buf.value); gss_release_buffer(&minor, &mech_output_token); free_NegotiationToken(&resp); return GSS_S_DEFECTIVE_TOKEN; } ctx->verified_mic = 1; } } ret = spnego_reply_internal(minor_status, ctx, require_mic ? &mech_buf : NULL, &mech_output_token, output_token); if (mech_buf.value != NULL) free(mech_buf.value); free_NegotiationToken(&resp); gss_release_buffer(&minor, &mech_output_token); if (actual_mech_type) *actual_mech_type = ctx->negotiated_mech_type; if (ret_flags) *ret_flags = ctx->mech_flags; if (time_rec) *time_rec = ctx->mech_time_rec; HEIMDAL_MUTEX_unlock(&ctx->ctx_id_mutex); return ret; } OM_uint32 GSSAPI_CALLCONV _gss_spnego_init_sec_context (OM_uint32 * minor_status, gss_const_cred_id_t initiator_cred_handle, gss_ctx_id_t * context_handle, gss_const_name_t target_name, const gss_OID mech_type, OM_uint32 req_flags, OM_uint32 time_req, const gss_channel_bindings_t input_chan_bindings, const gss_buffer_t input_token, gss_OID * actual_mech_type, gss_buffer_t output_token, OM_uint32 * ret_flags, OM_uint32 * time_rec ) { if (*context_handle == GSS_C_NO_CONTEXT) return spnego_initial (minor_status, initiator_cred_handle, context_handle, target_name, mech_type, req_flags, time_req, input_chan_bindings, input_token, actual_mech_type, output_token, ret_flags, time_rec); else return spnego_reply (minor_status, initiator_cred_handle, context_handle, target_name, mech_type, req_flags, time_req, input_chan_bindings, input_token, actual_mech_type, output_token, ret_flags, time_rec); } heimdal-7.5.0/lib/gssapi/spnego/cred_stubs.c0000644000175000017500000001564313026237312017112 0ustar niknik/* * Copyright (c) 2004, PADL Software Pty Ltd. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of PADL Software nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY PADL SOFTWARE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL PADL SOFTWARE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "spnego_locl.h" OM_uint32 GSSAPI_CALLCONV _gss_spnego_release_cred(OM_uint32 *minor_status, gss_cred_id_t *cred_handle) { OM_uint32 ret; *minor_status = 0; if (cred_handle == NULL || *cred_handle == GSS_C_NO_CREDENTIAL) return GSS_S_COMPLETE; ret = gss_release_cred(minor_status, cred_handle); *cred_handle = GSS_C_NO_CREDENTIAL; return ret; } /* * For now, just a simple wrapper that avoids recursion. When * we support gss_{get,set}_neg_mechs() we will need to expose * more functionality. */ OM_uint32 GSSAPI_CALLCONV _gss_spnego_acquire_cred (OM_uint32 *minor_status, gss_const_name_t desired_name, OM_uint32 time_req, const gss_OID_set desired_mechs, gss_cred_usage_t cred_usage, gss_cred_id_t * output_cred_handle, gss_OID_set * actual_mechs, OM_uint32 * time_rec ) { const spnego_name dname = (const spnego_name)desired_name; gss_name_t name = GSS_C_NO_NAME; OM_uint32 ret, tmp; gss_OID_set_desc actual_desired_mechs; gss_OID_set mechs; size_t i, j; *output_cred_handle = GSS_C_NO_CREDENTIAL; if (dname) { ret = gss_import_name(minor_status, &dname->value, &dname->type, &name); if (ret) { return ret; } } ret = gss_indicate_mechs(minor_status, &mechs); if (ret != GSS_S_COMPLETE) { gss_release_name(minor_status, &name); return ret; } /* Remove ourselves from this list */ actual_desired_mechs.count = mechs->count; actual_desired_mechs.elements = malloc(actual_desired_mechs.count * sizeof(gss_OID_desc)); if (actual_desired_mechs.elements == NULL) { *minor_status = ENOMEM; ret = GSS_S_FAILURE; goto out; } for (i = 0, j = 0; i < mechs->count; i++) { if (gss_oid_equal(&mechs->elements[i], GSS_SPNEGO_MECHANISM)) continue; actual_desired_mechs.elements[j] = mechs->elements[i]; j++; } actual_desired_mechs.count = j; ret = gss_acquire_cred(minor_status, name, time_req, &actual_desired_mechs, cred_usage, output_cred_handle, actual_mechs, time_rec); if (ret != GSS_S_COMPLETE) goto out; out: gss_release_name(minor_status, &name); gss_release_oid_set(&tmp, &mechs); if (actual_desired_mechs.elements != NULL) { free(actual_desired_mechs.elements); } if (ret != GSS_S_COMPLETE) { _gss_spnego_release_cred(&tmp, output_cred_handle); } return ret; } OM_uint32 GSSAPI_CALLCONV _gss_spnego_inquire_cred (OM_uint32 * minor_status, gss_const_cred_id_t cred_handle, gss_name_t * name, OM_uint32 * lifetime, gss_cred_usage_t * cred_usage, gss_OID_set * mechanisms ) { spnego_name sname = NULL; OM_uint32 ret; if (cred_handle == GSS_C_NO_CREDENTIAL) { *minor_status = 0; return GSS_S_NO_CRED; } if (name) { sname = calloc(1, sizeof(*sname)); if (sname == NULL) { *minor_status = ENOMEM; return GSS_S_FAILURE; } } ret = gss_inquire_cred(minor_status, cred_handle, sname ? &sname->mech : NULL, lifetime, cred_usage, mechanisms); if (ret) { if (sname) free(sname); return ret; } if (name) *name = (gss_name_t)sname; return ret; } OM_uint32 GSSAPI_CALLCONV _gss_spnego_inquire_cred_by_mech ( OM_uint32 * minor_status, gss_const_cred_id_t cred_handle, const gss_OID mech_type, gss_name_t * name, OM_uint32 * initiator_lifetime, OM_uint32 * acceptor_lifetime, gss_cred_usage_t * cred_usage ) { spnego_name sname = NULL; OM_uint32 ret; if (cred_handle == GSS_C_NO_CREDENTIAL) { *minor_status = 0; return GSS_S_NO_CRED; } if (name) { sname = calloc(1, sizeof(*sname)); if (sname == NULL) { *minor_status = ENOMEM; return GSS_S_FAILURE; } } ret = gss_inquire_cred_by_mech(minor_status, cred_handle, mech_type, sname ? &sname->mech : NULL, initiator_lifetime, acceptor_lifetime, cred_usage); if (ret) { if (sname) free(sname); return ret; } if (name) *name = (gss_name_t)sname; return GSS_S_COMPLETE; } OM_uint32 GSSAPI_CALLCONV _gss_spnego_inquire_cred_by_oid (OM_uint32 * minor_status, gss_const_cred_id_t cred_handle, const gss_OID desired_object, gss_buffer_set_t *data_set) { OM_uint32 ret; if (cred_handle == GSS_C_NO_CREDENTIAL) { *minor_status = 0; return GSS_S_NO_CRED; } ret = gss_inquire_cred_by_oid(minor_status, cred_handle, desired_object, data_set); return ret; } OM_uint32 GSSAPI_CALLCONV _gss_spnego_set_cred_option (OM_uint32 *minor_status, gss_cred_id_t *cred_handle, const gss_OID object, const gss_buffer_t value) { if (cred_handle == NULL || *cred_handle == GSS_C_NO_CREDENTIAL) { *minor_status = 0; return GSS_S_NO_CRED; } return gss_set_cred_option(minor_status, cred_handle, object, value); } OM_uint32 GSSAPI_CALLCONV _gss_spnego_export_cred (OM_uint32 *minor_status, gss_cred_id_t cred_handle, gss_buffer_t value) { return gss_export_cred(minor_status, cred_handle, value); } OM_uint32 GSSAPI_CALLCONV _gss_spnego_import_cred (OM_uint32 *minor_status, gss_buffer_t value, gss_cred_id_t *cred_handle) { return gss_import_cred(minor_status, value, cred_handle); } heimdal-7.5.0/lib/gssapi/spnego/spnego.opt0000644000175000017500000000003012136107747016621 0ustar niknik--sequence=MechTypeList heimdal-7.5.0/lib/gssapi/spnego/spnego-private.h0000644000175000017500000002065413212445601017722 0ustar niknik/* This is a generated file */ #ifndef __spnego_private_h__ #define __spnego_private_h__ #include gssapi_mech_interface __gss_spnego_initialize (void); OM_uint32 GSSAPI_CALLCONV _gss_spnego_accept_sec_context ( OM_uint32 * /*minor_status*/, gss_ctx_id_t * /*context_handle*/, gss_const_cred_id_t /*acceptor_cred_handle*/, const gss_buffer_t /*input_token_buffer*/, const gss_channel_bindings_t /*input_chan_bindings*/, gss_name_t * /*src_name*/, gss_OID * /*mech_type*/, gss_buffer_t /*output_token*/, OM_uint32 * /*ret_flags*/, OM_uint32 * /*time_rec*/, gss_cred_id_t *delegated_cred_handle ); OM_uint32 GSSAPI_CALLCONV _gss_spnego_acquire_cred ( OM_uint32 */*minor_status*/, gss_const_name_t /*desired_name*/, OM_uint32 /*time_req*/, const gss_OID_set /*desired_mechs*/, gss_cred_usage_t /*cred_usage*/, gss_cred_id_t * /*output_cred_handle*/, gss_OID_set * /*actual_mechs*/, OM_uint32 * time_rec ); OM_uint32 GSSAPI_CALLCONV _gss_spnego_alloc_sec_context ( OM_uint32 * /*minor_status*/, gss_ctx_id_t */*context_handle*/); OM_uint32 GSSAPI_CALLCONV _gss_spnego_canonicalize_name ( OM_uint32 * /*minor_status*/, gss_const_name_t /*input_name*/, const gss_OID /*mech_type*/, gss_name_t * output_name ); OM_uint32 GSSAPI_CALLCONV _gss_spnego_compare_name ( OM_uint32 */*minor_status*/, gss_const_name_t /*name1*/, gss_const_name_t /*name2*/, int * name_equal ); OM_uint32 GSSAPI_CALLCONV _gss_spnego_context_time ( OM_uint32 */*minor_status*/, gss_const_ctx_id_t /*context_handle*/, OM_uint32 *time_rec ); OM_uint32 GSSAPI_CALLCONV _gss_spnego_delete_sec_context ( OM_uint32 */*minor_status*/, gss_ctx_id_t */*context_handle*/, gss_buffer_t output_token ); OM_uint32 GSSAPI_CALLCONV _gss_spnego_display_name ( OM_uint32 * /*minor_status*/, gss_const_name_t /*input_name*/, gss_buffer_t /*output_name_buffer*/, gss_OID * output_name_type ); OM_uint32 GSSAPI_CALLCONV _gss_spnego_duplicate_name ( OM_uint32 * /*minor_status*/, gss_const_name_t /*src_name*/, gss_name_t * dest_name ); OM_uint32 GSSAPI_CALLCONV _gss_spnego_export_cred ( OM_uint32 */*minor_status*/, gss_cred_id_t /*cred_handle*/, gss_buffer_t /*value*/); OM_uint32 GSSAPI_CALLCONV _gss_spnego_export_name ( OM_uint32 * /*minor_status*/, gss_const_name_t /*input_name*/, gss_buffer_t exported_name ); OM_uint32 GSSAPI_CALLCONV _gss_spnego_export_sec_context ( OM_uint32 * /*minor_status*/, gss_ctx_id_t * /*context_handle*/, gss_buffer_t interprocess_token ); OM_uint32 GSSAPI_CALLCONV _gss_spnego_get_mic ( OM_uint32 */*minor_status*/, gss_const_ctx_id_t /*context_handle*/, gss_qop_t /*qop_req*/, const gss_buffer_t /*message_buffer*/, gss_buffer_t message_token ); OM_uint32 GSSAPI_CALLCONV _gss_spnego_import_cred ( OM_uint32 */*minor_status*/, gss_buffer_t /*value*/, gss_cred_id_t */*cred_handle*/); OM_uint32 GSSAPI_CALLCONV _gss_spnego_import_name ( OM_uint32 * /*minor_status*/, const gss_buffer_t /*name_buffer*/, const gss_OID /*name_type*/, gss_name_t * output_name ); OM_uint32 GSSAPI_CALLCONV _gss_spnego_import_sec_context ( OM_uint32 * /*minor_status*/, const gss_buffer_t /*interprocess_token*/, gss_ctx_id_t *context_handle ); OM_uint32 GSSAPI_CALLCONV _gss_spnego_indicate_mechtypelist ( OM_uint32 */*minor_status*/, gss_name_t /*target_name*/, OM_uint32 (*/*func*/)(gss_name_t, gss_OID), int /*includeMSCompatOID*/, gss_const_cred_id_t /*cred_handle*/, MechTypeList */*mechtypelist*/, gss_OID */*preferred_mech*/); OM_uint32 GSSAPI_CALLCONV _gss_spnego_init_sec_context ( OM_uint32 * /*minor_status*/, gss_const_cred_id_t /*initiator_cred_handle*/, gss_ctx_id_t * /*context_handle*/, gss_const_name_t /*target_name*/, const gss_OID /*mech_type*/, OM_uint32 /*req_flags*/, OM_uint32 /*time_req*/, const gss_channel_bindings_t /*input_chan_bindings*/, const gss_buffer_t /*input_token*/, gss_OID * /*actual_mech_type*/, gss_buffer_t /*output_token*/, OM_uint32 * /*ret_flags*/, OM_uint32 * time_rec ); OM_uint32 GSSAPI_CALLCONV _gss_spnego_inquire_context ( OM_uint32 * /*minor_status*/, gss_const_ctx_id_t /*context_handle*/, gss_name_t * /*src_name*/, gss_name_t * /*targ_name*/, OM_uint32 * /*lifetime_rec*/, gss_OID * /*mech_type*/, OM_uint32 * /*ctx_flags*/, int * /*locally_initiated*/, int * open_context ); OM_uint32 GSSAPI_CALLCONV _gss_spnego_inquire_cred ( OM_uint32 * /*minor_status*/, gss_const_cred_id_t /*cred_handle*/, gss_name_t * /*name*/, OM_uint32 * /*lifetime*/, gss_cred_usage_t * /*cred_usage*/, gss_OID_set * mechanisms ); OM_uint32 GSSAPI_CALLCONV _gss_spnego_inquire_cred_by_mech ( OM_uint32 * /*minor_status*/, gss_const_cred_id_t /*cred_handle*/, const gss_OID /*mech_type*/, gss_name_t * /*name*/, OM_uint32 * /*initiator_lifetime*/, OM_uint32 * /*acceptor_lifetime*/, gss_cred_usage_t * cred_usage ); OM_uint32 GSSAPI_CALLCONV _gss_spnego_inquire_cred_by_oid ( OM_uint32 * /*minor_status*/, gss_const_cred_id_t /*cred_handle*/, const gss_OID /*desired_object*/, gss_buffer_set_t */*data_set*/); OM_uint32 GSSAPI_CALLCONV _gss_spnego_inquire_mechs_for_name ( OM_uint32 * /*minor_status*/, gss_const_name_t /*input_name*/, gss_OID_set * mech_types ); OM_uint32 GSSAPI_CALLCONV _gss_spnego_inquire_names_for_mech ( OM_uint32 * /*minor_status*/, const gss_OID /*mechanism*/, gss_OID_set * name_types ); OM_uint32 GSSAPI_CALLCONV _gss_spnego_inquire_sec_context_by_oid ( OM_uint32 * /*minor_status*/, gss_const_ctx_id_t /*context_handle*/, const gss_OID /*desired_object*/, gss_buffer_set_t */*data_set*/); OM_uint32 GSSAPI_CALLCONV _gss_spnego_internal_delete_sec_context ( OM_uint32 */*minor_status*/, gss_ctx_id_t */*context_handle*/, gss_buffer_t output_token ); OM_uint32 GSSAPI_CALLCONV _gss_spnego_process_context_token ( OM_uint32 */*minor_status*/, gss_const_ctx_id_t /*context_handle*/, const gss_buffer_t token_buffer ); OM_uint32 GSSAPI_CALLCONV _gss_spnego_pseudo_random ( OM_uint32 */*minor_status*/, gss_ctx_id_t /*context_handle*/, int /*prf_key*/, const gss_buffer_t /*prf_in*/, ssize_t /*desired_output_len*/, gss_buffer_t /*prf_out*/); OM_uint32 GSSAPI_CALLCONV _gss_spnego_release_cred ( OM_uint32 */*minor_status*/, gss_cred_id_t */*cred_handle*/); OM_uint32 GSSAPI_CALLCONV _gss_spnego_release_name ( OM_uint32 * /*minor_status*/, gss_name_t * input_name ); OM_uint32 GSSAPI_CALLCONV _gss_spnego_require_mechlist_mic ( OM_uint32 */*minor_status*/, gssspnego_ctx /*ctx*/, int */*require_mic*/); OM_uint32 GSSAPI_CALLCONV _gss_spnego_set_cred_option ( OM_uint32 */*minor_status*/, gss_cred_id_t */*cred_handle*/, const gss_OID /*object*/, const gss_buffer_t /*value*/); OM_uint32 GSSAPI_CALLCONV _gss_spnego_set_sec_context_option ( OM_uint32 * /*minor_status*/, gss_ctx_id_t * /*context_handle*/, const gss_OID /*desired_object*/, const gss_buffer_t /*value*/); OM_uint32 GSSAPI_CALLCONV _gss_spnego_unwrap ( OM_uint32 * /*minor_status*/, gss_const_ctx_id_t /*context_handle*/, const gss_buffer_t /*input_message_buffer*/, gss_buffer_t /*output_message_buffer*/, int * /*conf_state*/, gss_qop_t * qop_state ); OM_uint32 GSSAPI_CALLCONV _gss_spnego_unwrap_iov ( OM_uint32 */*minor_status*/, gss_ctx_id_t /*context_handle*/, int */*conf_state*/, gss_qop_t */*qop_state*/, gss_iov_buffer_desc */*iov*/, int /*iov_count*/); OM_uint32 GSSAPI_CALLCONV _gss_spnego_verify_mic ( OM_uint32 * /*minor_status*/, gss_const_ctx_id_t /*context_handle*/, const gss_buffer_t /*message_buffer*/, const gss_buffer_t /*token_buffer*/, gss_qop_t * qop_state ); OM_uint32 GSSAPI_CALLCONV _gss_spnego_wrap ( OM_uint32 * /*minor_status*/, gss_const_ctx_id_t /*context_handle*/, int /*conf_req_flag*/, gss_qop_t /*qop_req*/, const gss_buffer_t /*input_message_buffer*/, int * /*conf_state*/, gss_buffer_t output_message_buffer ); OM_uint32 GSSAPI_CALLCONV _gss_spnego_wrap_iov ( OM_uint32 * /*minor_status*/, gss_ctx_id_t /*context_handle*/, int /*conf_req_flag*/, gss_qop_t /*qop_req*/, int * /*conf_state*/, gss_iov_buffer_desc */*iov*/, int /*iov_count*/); OM_uint32 GSSAPI_CALLCONV _gss_spnego_wrap_iov_length ( OM_uint32 * /*minor_status*/, gss_ctx_id_t /*context_handle*/, int /*conf_req_flag*/, gss_qop_t /*qop_req*/, int */*conf_state*/, gss_iov_buffer_desc */*iov*/, int /*iov_count*/); OM_uint32 GSSAPI_CALLCONV _gss_spnego_wrap_size_limit ( OM_uint32 * /*minor_status*/, gss_const_ctx_id_t /*context_handle*/, int /*conf_req_flag*/, gss_qop_t /*qop_req*/, OM_uint32 /*req_output_size*/, OM_uint32 * max_input_size ); #endif /* __spnego_private_h__ */ heimdal-7.5.0/lib/gssapi/spnego/compat.c0000644000175000017500000002122613026237312016232 0ustar niknik/* * Copyright (c) 2004, PADL Software Pty Ltd. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of PADL Software nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY PADL SOFTWARE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL PADL SOFTWARE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "spnego_locl.h" /* * Apparently Microsoft got the OID wrong, and used * 1.2.840.48018.1.2.2 instead. We need both this and * the correct Kerberos OID here in order to deal with * this. Because this is manifest in SPNEGO only I'd * prefer to deal with this here rather than inside the * Kerberos mechanism. */ gss_OID_desc _gss_spnego_mskrb_mechanism_oid_desc = {9, rk_UNCONST("\x2a\x86\x48\x82\xf7\x12\x01\x02\x02")}; gss_OID_desc _gss_spnego_krb5_mechanism_oid_desc = {9, rk_UNCONST("\x2a\x86\x48\x86\xf7\x12\x01\x02\x02")}; /* * Allocate a SPNEGO context handle */ OM_uint32 GSSAPI_CALLCONV _gss_spnego_alloc_sec_context (OM_uint32 * minor_status, gss_ctx_id_t *context_handle) { gssspnego_ctx ctx; ctx = calloc(1, sizeof(*ctx)); if (ctx == NULL) { *minor_status = ENOMEM; return GSS_S_FAILURE; } ctx->initiator_mech_types.len = 0; ctx->initiator_mech_types.val = NULL; ctx->preferred_mech_type = GSS_C_NO_OID; ctx->negotiated_mech_type = GSS_C_NO_OID; ctx->negotiated_ctx_id = GSS_C_NO_CONTEXT; /* * Cache these so we can return them before returning * GSS_S_COMPLETE, even if the mechanism has itself * completed earlier */ ctx->mech_flags = 0; ctx->mech_time_rec = 0; ctx->mech_src_name = GSS_C_NO_NAME; ctx->open = 0; ctx->local = 0; ctx->require_mic = 0; ctx->verified_mic = 0; HEIMDAL_MUTEX_init(&ctx->ctx_id_mutex); *context_handle = (gss_ctx_id_t)ctx; return GSS_S_COMPLETE; } /* * Free a SPNEGO context handle. The caller must have acquired * the lock before this is called. */ OM_uint32 GSSAPI_CALLCONV _gss_spnego_internal_delete_sec_context (OM_uint32 *minor_status, gss_ctx_id_t *context_handle, gss_buffer_t output_token ) { gssspnego_ctx ctx; OM_uint32 ret, minor; *minor_status = 0; if (context_handle == NULL) { return GSS_S_NO_CONTEXT; } if (output_token != GSS_C_NO_BUFFER) { output_token->length = 0; output_token->value = NULL; } ctx = (gssspnego_ctx)*context_handle; *context_handle = GSS_C_NO_CONTEXT; if (ctx == NULL) { return GSS_S_NO_CONTEXT; } if (ctx->initiator_mech_types.val != NULL) free_MechTypeList(&ctx->initiator_mech_types); gss_release_oid(&minor, &ctx->preferred_mech_type); ctx->negotiated_mech_type = GSS_C_NO_OID; gss_release_name(&minor, &ctx->target_name); gss_release_name(&minor, &ctx->mech_src_name); if (ctx->negotiated_ctx_id != GSS_C_NO_CONTEXT) { ret = gss_delete_sec_context(minor_status, &ctx->negotiated_ctx_id, output_token); ctx->negotiated_ctx_id = GSS_C_NO_CONTEXT; } else { ret = GSS_S_COMPLETE; } HEIMDAL_MUTEX_unlock(&ctx->ctx_id_mutex); HEIMDAL_MUTEX_destroy(&ctx->ctx_id_mutex); free(ctx); return ret; } /* * For compatability with the Windows SPNEGO implementation, the * default is to ignore the mechListMIC unless CFX is used and * a non-preferred mechanism was negotiated */ OM_uint32 GSSAPI_CALLCONV _gss_spnego_require_mechlist_mic(OM_uint32 *minor_status, gssspnego_ctx ctx, int *require_mic) { gss_buffer_set_t buffer_set = GSS_C_NO_BUFFER_SET; OM_uint32 minor; *minor_status = 0; *require_mic = 0; if (ctx == NULL) { return GSS_S_COMPLETE; } if (ctx->require_mic) { /* Acceptor requested it: mandatory to honour */ *require_mic = 1; return GSS_S_COMPLETE; } /* * Check whether peer indicated implicit support for updated SPNEGO * (eg. in the Kerberos case by using CFX) */ if (gss_inquire_sec_context_by_oid(&minor, ctx->negotiated_ctx_id, GSS_C_PEER_HAS_UPDATED_SPNEGO, &buffer_set) == GSS_S_COMPLETE) { *require_mic = 1; gss_release_buffer_set(&minor, &buffer_set); } /* Safe-to-omit MIC rules follow */ if (*require_mic) { if (gss_oid_equal(ctx->negotiated_mech_type, ctx->preferred_mech_type)) { *require_mic = 0; } else if (gss_oid_equal(ctx->negotiated_mech_type, &_gss_spnego_krb5_mechanism_oid_desc) && gss_oid_equal(ctx->preferred_mech_type, &_gss_spnego_mskrb_mechanism_oid_desc)) { *require_mic = 0; } } return GSS_S_COMPLETE; } static int add_mech_type(gss_OID mech_type, int includeMSCompatOID, MechTypeList *mechtypelist) { MechType mech; int ret; if (gss_oid_equal(mech_type, GSS_SPNEGO_MECHANISM)) return 0; if (includeMSCompatOID && gss_oid_equal(mech_type, &_gss_spnego_krb5_mechanism_oid_desc)) { ret = der_get_oid(_gss_spnego_mskrb_mechanism_oid_desc.elements, _gss_spnego_mskrb_mechanism_oid_desc.length, &mech, NULL); if (ret) return ret; ret = add_MechTypeList(mechtypelist, &mech); free_MechType(&mech); if (ret) return ret; } ret = der_get_oid(mech_type->elements, mech_type->length, &mech, NULL); if (ret) return ret; ret = add_MechTypeList(mechtypelist, &mech); free_MechType(&mech); return ret; } OM_uint32 GSSAPI_CALLCONV _gss_spnego_indicate_mechtypelist (OM_uint32 *minor_status, gss_name_t target_name, OM_uint32 (*func)(gss_name_t, gss_OID), int includeMSCompatOID, gss_const_cred_id_t cred_handle, MechTypeList *mechtypelist, gss_OID *preferred_mech) { gss_OID_set supported_mechs = GSS_C_NO_OID_SET; gss_OID first_mech = GSS_C_NO_OID; OM_uint32 ret; size_t i; mechtypelist->len = 0; mechtypelist->val = NULL; if (cred_handle) { ret = gss_inquire_cred(minor_status, cred_handle, NULL, NULL, NULL, &supported_mechs); } else { ret = gss_indicate_mechs(minor_status, &supported_mechs); } if (ret != GSS_S_COMPLETE) { return ret; } if (supported_mechs->count == 0) { *minor_status = ENOENT; gss_release_oid_set(minor_status, &supported_mechs); return GSS_S_FAILURE; } ret = (*func)(target_name, GSS_KRB5_MECHANISM); if (ret == GSS_S_COMPLETE) { ret = add_mech_type(GSS_KRB5_MECHANISM, includeMSCompatOID, mechtypelist); if (!GSS_ERROR(ret)) first_mech = GSS_KRB5_MECHANISM; } ret = GSS_S_COMPLETE; for (i = 0; i < supported_mechs->count; i++) { OM_uint32 subret; if (gss_oid_equal(&supported_mechs->elements[i], GSS_SPNEGO_MECHANISM)) continue; if (gss_oid_equal(&supported_mechs->elements[i], GSS_KRB5_MECHANISM)) continue; subret = (*func)(target_name, &supported_mechs->elements[i]); if (subret != GSS_S_COMPLETE) continue; ret = add_mech_type(&supported_mechs->elements[i], includeMSCompatOID, mechtypelist); if (ret != 0) { *minor_status = ret; ret = GSS_S_FAILURE; break; } if (first_mech == GSS_C_NO_OID) first_mech = &supported_mechs->elements[i]; } if (mechtypelist->len == 0) { gss_release_oid_set(minor_status, &supported_mechs); *minor_status = 0; return GSS_S_BAD_MECH; } if (preferred_mech != NULL) { ret = gss_duplicate_oid(minor_status, first_mech, preferred_mech); if (ret != GSS_S_COMPLETE) free_MechTypeList(mechtypelist); } gss_release_oid_set(minor_status, &supported_mechs); return ret; } heimdal-7.5.0/lib/gssapi/gssapi.cat30000644000175000017500000001126213212450760015352 0ustar niknik GSSAPI(3) BSD Library Functions Manual GSSAPI(3) NNAAMMEE ggssssaappii -- Generic Security Service Application Program Interface library LLIIBBRRAARRYY GSS-API Library (libgssapi, -lgssapi) DDEESSCCRRIIPPTTIIOONN The Generic Security Service Application Program Interface (GSS-API) pro- vides security services to callers in a generic fashion, supportable with a range of underlying mechanisms and technologies and hence allowing source-level portability of applications to different environments. The GSS-API implementation in Heimdal implements the Kerberos 5 and the SPNEGO GSS-API security mechanisms. LLIISSTT OOFF FFUUNNCCTTIIOONNSS These functions constitute the gssapi library, _l_i_b_g_s_s_a_p_i. Declarations for these functions may be obtained from the include file _g_s_s_a_p_i_._h. NNaammee//PPaaggee gss_accept_sec_context(3) gss_acquire_cred(3) gss_add_cred(3) gss_add_oid_set_member(3) gss_canonicalize_name(3) gss_compare_name(3) gss_context_time(3) gss_create_empty_oid_set(3) gss_delete_sec_context(3) gss_display_name(3) gss_display_status(3) gss_duplicate_name(3) gss_export_name(3) gss_export_sec_context(3) gss_get_mic(3) gss_import_name(3) gss_import_sec_context(3) gss_indicate_mechs(3) gss_init_sec_context(3) gss_inquire_context(3) gss_inquire_cred(3) gss_inquire_cred_by_mech(3) gss_inquire_mechs_for_name(3) gss_inquire_names_for_mech(3) gss_krb5_ccache_name(3) gss_krb5_compat_des3_mic(3) gss_krb5_copy_ccache(3) gss_krb5_extract_authz_data_from_sec_context(3) gss_krb5_import_ccache(3) gss_process_context_token(3) gss_release_buffer(3) gss_release_cred(3) gss_release_name(3) gss_release_oid_set(3) gss_seal(3) gss_sign(3) gss_test_oid_set_member(3) gss_unseal(3) gss_unwrap(3) gss_verify(3) gss_verify_mic(3) gss_wrap(3) gss_wrap_size_limit(3) CCOOMMPPAATTIIBBIILLIITTYY The HHeeiimmddaall GSS-API implementation had a bug in releases before 0.6 that made it fail to inter-operate when using DES3 with other GSS-API imple- mentations when using ggssss__ggeett__mmiicc() / ggssss__vveerriiffyy__mmiicc(). It is possible to modify the behavior of the generator of the MIC with the _k_r_b_5_._c_o_n_f configuration file so that old clients/servers will still work. New clients/servers will try both the old and new MIC in Heimdal 0.6. In 0.7 it will check only if configured - the compatibility code will be removed in 0.8. Heimdal 0.6 still generates by default the broken GSS-API DES3 mic, this will change in 0.7 to generate correct des3 mic. To turn on compatibility with older clients and servers, change the [[ggssssaappii]] _b_r_o_k_e_n___d_e_s_3___m_i_c in _k_r_b_5_._c_o_n_f that contains a list of globbing expressions that will be matched against the server name. To turn off generation of the old (incompatible) mic of the MIC use [[ggssssaappii]] _c_o_r_r_e_c_t___d_e_s_3___m_i_c. If a match for a entry is in both [[ggssssaappii]] _c_o_r_r_e_c_t___d_e_s_3___m_i_c and [[ggssssaappii]] _b_r_o_k_e_n___d_e_s_3___m_i_c, the later will override. This config option modifies behaviour for both clients and servers. Microsoft implemented SPNEGO to Windows2000, however, they managed to get it wrong, their implementation didn't fill in the MechListMIC in the reply token with the right content. There is a work around for this problem, but not all implementation support it. Heimdal defaults to correct SPNEGO when the the kerberos implementation uses CFX, or when it is configured by the user. To turn on compatibility with peers, use option [[ggssssaappii]] _r_e_q_u_i_r_e___m_e_c_h_l_i_s_t___m_i_c. EEXXAAMMPPLLEESS [gssapi] broken_des3_mic = cvs/*@SU.SE broken_des3_mic = host/*@E.KTH.SE correct_des3_mic = host/*@SU.SE require_mechlist_mic = host/*@SU.SE BBUUGGSS All of 0.5.x versions of hheeiimmddaall had broken token delegations in the client side, the server side was correct. SSEEEE AALLSSOO krb5(3), krb5.conf(5), kerberos(8) BSD April 20, 2005 BSD heimdal-7.5.0/lib/gssapi/gssapi_mech.h0000644000175000017500000005313113026237312015743 0ustar niknik/*- * Copyright (c) 2005 Doug Rabson * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * * $FreeBSD: src/lib/libgssapi/mech_switch.h,v 1.1 2005/12/29 14:40:20 dfr Exp $ */ #ifndef GSSAPI_MECH_H #define GSSAPI_MECH_H 1 #include typedef OM_uint32 GSSAPI_CALLCONV _gss_acquire_cred_t (OM_uint32 *, /* minor_status */ gss_const_name_t, /* desired_name */ OM_uint32, /* time_req */ const gss_OID_set, /* desired_mechs */ gss_cred_usage_t, /* cred_usage */ gss_cred_id_t *, /* output_cred_handle */ gss_OID_set *, /* actual_mechs */ OM_uint32 * /* time_rec */ ); typedef OM_uint32 GSSAPI_CALLCONV _gss_release_cred_t (OM_uint32 *, /* minor_status */ gss_cred_id_t * /* cred_handle */ ); typedef OM_uint32 GSSAPI_CALLCONV _gss_init_sec_context_t (OM_uint32 *, /* minor_status */ gss_const_cred_id_t, /* initiator_cred_handle */ gss_ctx_id_t *, /* context_handle */ gss_const_name_t, /* target_name */ const gss_OID, /* mech_type */ OM_uint32, /* req_flags */ OM_uint32, /* time_req */ const gss_channel_bindings_t, /* input_chan_bindings */ const gss_buffer_t, /* input_token */ gss_OID *, /* actual_mech_type */ gss_buffer_t, /* output_token */ OM_uint32 *, /* ret_flags */ OM_uint32 * /* time_rec */ ); typedef OM_uint32 GSSAPI_CALLCONV _gss_accept_sec_context_t (OM_uint32 *, /* minor_status */ gss_ctx_id_t *, /* context_handle */ gss_const_cred_id_t, /* acceptor_cred_handle */ const gss_buffer_t, /* input_token_buffer */ const gss_channel_bindings_t, /* input_chan_bindings */ gss_name_t *, /* src_name */ gss_OID *, /* mech_type */ gss_buffer_t, /* output_token */ OM_uint32 *, /* ret_flags */ OM_uint32 *, /* time_rec */ gss_cred_id_t * /* delegated_cred_handle */ ); typedef OM_uint32 GSSAPI_CALLCONV _gss_process_context_token_t (OM_uint32 *, /* minor_status */ gss_const_ctx_id_t, /* context_handle */ const gss_buffer_t /* token_buffer */ ); typedef OM_uint32 GSSAPI_CALLCONV _gss_delete_sec_context_t (OM_uint32 *, /* minor_status */ gss_ctx_id_t *, /* context_handle */ gss_buffer_t /* output_token */ ); typedef OM_uint32 GSSAPI_CALLCONV _gss_context_time_t (OM_uint32 *, /* minor_status */ gss_const_ctx_id_t, /* context_handle */ OM_uint32 * /* time_rec */ ); typedef OM_uint32 GSSAPI_CALLCONV _gss_get_mic_t (OM_uint32 *, /* minor_status */ gss_const_ctx_id_t, /* context_handle */ gss_qop_t, /* qop_req */ const gss_buffer_t, /* message_buffer */ gss_buffer_t /* message_token */ ); typedef OM_uint32 GSSAPI_CALLCONV _gss_verify_mic_t (OM_uint32 *, /* minor_status */ gss_const_ctx_id_t, /* context_handle */ const gss_buffer_t, /* message_buffer */ const gss_buffer_t, /* token_buffer */ gss_qop_t * /* qop_state */ ); typedef OM_uint32 GSSAPI_CALLCONV _gss_wrap_t (OM_uint32 *, /* minor_status */ gss_const_ctx_id_t, /* context_handle */ int, /* conf_req_flag */ gss_qop_t, /* qop_req */ const gss_buffer_t, /* input_message_buffer */ int *, /* conf_state */ gss_buffer_t /* output_message_buffer */ ); typedef OM_uint32 GSSAPI_CALLCONV _gss_unwrap_t (OM_uint32 *, /* minor_status */ gss_const_ctx_id_t, /* context_handle */ const gss_buffer_t, /* input_message_buffer */ gss_buffer_t, /* output_message_buffer */ int *, /* conf_state */ gss_qop_t * /* qop_state */ ); typedef OM_uint32 GSSAPI_CALLCONV _gss_display_status_t (OM_uint32 *, /* minor_status */ OM_uint32, /* status_value */ int, /* status_type */ const gss_OID, /* mech_type */ OM_uint32 *, /* message_context */ gss_buffer_t /* status_string */ ); typedef OM_uint32 GSSAPI_CALLCONV _gss_indicate_mechs_t (OM_uint32 *, /* minor_status */ gss_OID_set * /* mech_set */ ); typedef OM_uint32 GSSAPI_CALLCONV _gss_compare_name_t (OM_uint32 *, /* minor_status */ gss_const_name_t, /* name1 */ gss_const_name_t, /* name2 */ int * /* name_equal */ ); typedef OM_uint32 GSSAPI_CALLCONV _gss_display_name_t (OM_uint32 *, /* minor_status */ gss_const_name_t, /* input_name */ gss_buffer_t, /* output_name_buffer */ gss_OID * /* output_name_type */ ); typedef OM_uint32 GSSAPI_CALLCONV _gss_import_name_t (OM_uint32 *, /* minor_status */ const gss_buffer_t, /* input_name_buffer */ const gss_OID, /* input_name_type */ gss_name_t * /* output_name */ ); typedef OM_uint32 GSSAPI_CALLCONV _gss_export_name_t (OM_uint32 *, /* minor_status */ gss_const_name_t, /* input_name */ gss_buffer_t /* exported_name */ ); typedef OM_uint32 GSSAPI_CALLCONV _gss_release_name_t (OM_uint32 *, /* minor_status */ gss_name_t * /* input_name */ ); typedef OM_uint32 GSSAPI_CALLCONV _gss_inquire_cred_t (OM_uint32 *, /* minor_status */ gss_const_cred_id_t, /* cred_handle */ gss_name_t *, /* name */ OM_uint32 *, /* lifetime */ gss_cred_usage_t *, /* cred_usage */ gss_OID_set * /* mechanisms */ ); typedef OM_uint32 GSSAPI_CALLCONV _gss_inquire_context_t (OM_uint32 *, /* minor_status */ gss_const_ctx_id_t, /* context_handle */ gss_name_t *, /* src_name */ gss_name_t *, /* targ_name */ OM_uint32 *, /* lifetime_rec */ gss_OID *, /* mech_type */ OM_uint32 *, /* ctx_flags */ int *, /* locally_initiated */ int * /* open */ ); typedef OM_uint32 GSSAPI_CALLCONV _gss_wrap_size_limit_t (OM_uint32 *, /* minor_status */ gss_const_ctx_id_t, /* context_handle */ int, /* conf_req_flag */ gss_qop_t, /* qop_req */ OM_uint32, /* req_output_size */ OM_uint32 * /* max_input_size */ ); typedef OM_uint32 GSSAPI_CALLCONV _gss_add_cred_t ( OM_uint32 *, /* minor_status */ gss_const_cred_id_t, /* input_cred_handle */ gss_const_name_t, /* desired_name */ const gss_OID, /* desired_mech */ gss_cred_usage_t, /* cred_usage */ OM_uint32, /* initiator_time_req */ OM_uint32, /* acceptor_time_req */ gss_cred_id_t *, /* output_cred_handle */ gss_OID_set *, /* actual_mechs */ OM_uint32 *, /* initiator_time_rec */ OM_uint32 * /* acceptor_time_rec */ ); typedef OM_uint32 GSSAPI_CALLCONV _gss_inquire_cred_by_mech_t ( OM_uint32 *, /* minor_status */ gss_const_cred_id_t, /* cred_handle */ const gss_OID, /* mech_type */ gss_name_t *, /* name */ OM_uint32 *, /* initiator_lifetime */ OM_uint32 *, /* acceptor_lifetime */ gss_cred_usage_t * /* cred_usage */ ); typedef OM_uint32 GSSAPI_CALLCONV _gss_export_sec_context_t ( OM_uint32 *, /* minor_status */ gss_ctx_id_t *, /* context_handle */ gss_buffer_t /* interprocess_token */ ); typedef OM_uint32 GSSAPI_CALLCONV _gss_import_sec_context_t ( OM_uint32 *, /* minor_status */ const gss_buffer_t, /* interprocess_token */ gss_ctx_id_t * /* context_handle */ ); typedef OM_uint32 GSSAPI_CALLCONV _gss_inquire_names_for_mech_t ( OM_uint32 *, /* minor_status */ const gss_OID, /* mechanism */ gss_OID_set * /* name_types */ ); typedef OM_uint32 GSSAPI_CALLCONV _gss_inquire_mechs_for_name_t ( OM_uint32 *, /* minor_status */ gss_const_name_t, /* input_name */ gss_OID_set * /* mech_types */ ); typedef OM_uint32 GSSAPI_CALLCONV _gss_canonicalize_name_t ( OM_uint32 *, /* minor_status */ gss_const_name_t, /* input_name */ const gss_OID, /* mech_type */ gss_name_t * /* output_name */ ); typedef OM_uint32 GSSAPI_CALLCONV _gss_duplicate_name_t ( OM_uint32 *, /* minor_status */ gss_const_name_t, /* src_name */ gss_name_t * /* dest_name */ ); typedef OM_uint32 GSSAPI_CALLCONV _gss_inquire_sec_context_by_oid ( OM_uint32 *minor_status, gss_const_ctx_id_t context_handle, const gss_OID desired_object, gss_buffer_set_t *data_set ); typedef OM_uint32 GSSAPI_CALLCONV _gss_inquire_cred_by_oid ( OM_uint32 *minor_status, gss_const_cred_id_t cred, const gss_OID desired_object, gss_buffer_set_t *data_set ); typedef OM_uint32 GSSAPI_CALLCONV _gss_set_sec_context_option ( OM_uint32 *minor_status, gss_ctx_id_t *cred_handle, const gss_OID desired_object, const gss_buffer_t value ); typedef OM_uint32 GSSAPI_CALLCONV _gss_set_cred_option ( OM_uint32 *minor_status, gss_cred_id_t *cred_handle, const gss_OID desired_object, const gss_buffer_t value ); typedef OM_uint32 GSSAPI_CALLCONV _gss_pseudo_random( OM_uint32 *minor_status, gss_ctx_id_t context, int prf_key, const gss_buffer_t prf_in, ssize_t desired_output_len, gss_buffer_t prf_out ); typedef OM_uint32 GSSAPI_CALLCONV _gss_wrap_iov_t(OM_uint32 *minor_status, gss_ctx_id_t context_handle, int conf_req_flag, gss_qop_t qop_req, int * conf_state, gss_iov_buffer_desc *iov, int iov_count); typedef OM_uint32 GSSAPI_CALLCONV _gss_unwrap_iov_t(OM_uint32 *minor_status, gss_ctx_id_t context_handle, int *conf_state, gss_qop_t *qop_state, gss_iov_buffer_desc *iov, int iov_count); typedef OM_uint32 GSSAPI_CALLCONV _gss_wrap_iov_length_t(OM_uint32 * minor_status, gss_ctx_id_t context_handle, int conf_req_flag, gss_qop_t qop_req, int *conf_state, gss_iov_buffer_desc *iov, int iov_count); typedef OM_uint32 GSSAPI_CALLCONV _gss_store_cred_t(OM_uint32 *minor_status, gss_cred_id_t input_cred_handle, gss_cred_usage_t cred_usage, const gss_OID desired_mech, OM_uint32 overwrite_cred, OM_uint32 default_cred, gss_OID_set *elements_stored, gss_cred_usage_t *cred_usage_stored); typedef OM_uint32 GSSAPI_CALLCONV _gss_export_cred_t(OM_uint32 *minor_status, gss_cred_id_t cred_handle, gss_buffer_t cred_token); typedef OM_uint32 GSSAPI_CALLCONV _gss_import_cred_t(OM_uint32 * minor_status, gss_buffer_t cred_token, gss_cred_id_t * cred_handle); typedef OM_uint32 GSSAPI_CALLCONV _gss_acquire_cred_ext_t(OM_uint32 * /*minor_status */, gss_const_name_t /* desired_name */, gss_const_OID /* credential_type */, const void * /* credential_data */, OM_uint32 /* time_req */, gss_const_OID /* desired_mech */, gss_cred_usage_t /* cred_usage */, gss_cred_id_t * /* output_cred_handle */); typedef void GSSAPI_CALLCONV _gss_iter_creds_t(OM_uint32 /* flags */, void * /* userctx */, void (* /*cred_iter */ )(void *, gss_OID, gss_cred_id_t)); typedef OM_uint32 GSSAPI_CALLCONV _gss_destroy_cred_t(OM_uint32 * /* minor_status */, gss_cred_id_t * /* cred */); typedef OM_uint32 GSSAPI_CALLCONV _gss_cred_hold_t(OM_uint32 * /* minor_status */, gss_cred_id_t /* cred */); typedef OM_uint32 GSSAPI_CALLCONV _gss_cred_unhold_t(OM_uint32 * /* minor_status */, gss_cred_id_t /* cred */); typedef OM_uint32 GSSAPI_CALLCONV _gss_cred_label_set_t(OM_uint32 * /* minor_status */, gss_cred_id_t /* cred */, const char * /* label */, gss_buffer_t /* value */); typedef OM_uint32 GSSAPI_CALLCONV _gss_cred_label_get_t(OM_uint32 * /* minor_status */, gss_cred_id_t /* cred */, const char * /* label */, gss_buffer_t /* value */); typedef OM_uint32 GSSAPI_CALLCONV _gss_display_name_ext_t ( OM_uint32 *, /* minor_status */ gss_name_t, /* name */ gss_OID, /* display_as_name_type */ gss_buffer_t /* display_name */ ); typedef OM_uint32 GSSAPI_CALLCONV _gss_inquire_name_t ( OM_uint32 *, /* minor_status */ gss_name_t, /* name */ int *, /* name_is_MN */ gss_OID *, /* MN_mech */ gss_buffer_set_t * /* attrs */ ); typedef OM_uint32 GSSAPI_CALLCONV _gss_get_name_attribute_t ( OM_uint32 *, /* minor_status */ gss_name_t, /* name */ gss_buffer_t, /* attr */ int *, /* authenticated */ int *, /* complete */ gss_buffer_t, /* value */ gss_buffer_t, /* display_value */ int * /* more */ ); typedef OM_uint32 GSSAPI_CALLCONV _gss_set_name_attribute_t ( OM_uint32 *, /* minor_status */ gss_name_t, /* name */ int, /* complete */ gss_buffer_t, /* attr */ gss_buffer_t /* value */ ); typedef OM_uint32 GSSAPI_CALLCONV _gss_delete_name_attribute_t ( OM_uint32 *, /* minor_status */ gss_name_t, /* name */ gss_buffer_t /* attr */ ); typedef OM_uint32 GSSAPI_CALLCONV _gss_export_name_composite_t ( OM_uint32 *, /* minor_status */ gss_name_t, /* name */ gss_buffer_t /* exp_composite_name */ ); /* * */ typedef struct gss_mo_desc_struct gss_mo_desc; typedef OM_uint32 GSSAPI_CALLCONV _gss_mo_init (OM_uint32 *, gss_OID, gss_mo_desc **, size_t *); struct gss_mo_desc_struct { gss_OID option; OM_uint32 flags; #define GSS_MO_MA 1 #define GSS_MO_MA_CRITICAL 2 const char *name; void *ctx; int (*get)(gss_const_OID, gss_mo_desc *, gss_buffer_t); int (*set)(gss_const_OID, gss_mo_desc *, int, gss_buffer_t); }; typedef OM_uint32 GSSAPI_CALLCONV _gss_localname_t ( OM_uint32 *, /* minor_status */ gss_const_name_t, /* name */ const gss_OID, /* mech_type */ gss_buffer_t /* localname */ ); typedef OM_uint32 GSSAPI_CALLCONV _gss_authorize_localname_t ( OM_uint32 *, /* minor_status */ gss_const_name_t, /* name */ gss_const_buffer_t, /* user */ gss_const_OID /* user_name_type */ ); /* mechglue internal */ struct gss_mech_compat_desc_struct; #define GMI_VERSION 5 /* gm_flags */ #define GM_USE_MG_CRED 1 /* uses mech glue credentials */ typedef struct gssapi_mech_interface_desc { unsigned gm_version; const char *gm_name; gss_OID_desc gm_mech_oid; unsigned gm_flags; _gss_acquire_cred_t *gm_acquire_cred; _gss_release_cred_t *gm_release_cred; _gss_init_sec_context_t *gm_init_sec_context; _gss_accept_sec_context_t *gm_accept_sec_context; _gss_process_context_token_t *gm_process_context_token; _gss_delete_sec_context_t *gm_delete_sec_context; _gss_context_time_t *gm_context_time; _gss_get_mic_t *gm_get_mic; _gss_verify_mic_t *gm_verify_mic; _gss_wrap_t *gm_wrap; _gss_unwrap_t *gm_unwrap; _gss_display_status_t *gm_display_status; _gss_indicate_mechs_t *gm_indicate_mechs; _gss_compare_name_t *gm_compare_name; _gss_display_name_t *gm_display_name; _gss_import_name_t *gm_import_name; _gss_export_name_t *gm_export_name; _gss_release_name_t *gm_release_name; _gss_inquire_cred_t *gm_inquire_cred; _gss_inquire_context_t *gm_inquire_context; _gss_wrap_size_limit_t *gm_wrap_size_limit; _gss_add_cred_t *gm_add_cred; _gss_inquire_cred_by_mech_t *gm_inquire_cred_by_mech; _gss_export_sec_context_t *gm_export_sec_context; _gss_import_sec_context_t *gm_import_sec_context; _gss_inquire_names_for_mech_t *gm_inquire_names_for_mech; _gss_inquire_mechs_for_name_t *gm_inquire_mechs_for_name; _gss_canonicalize_name_t *gm_canonicalize_name; _gss_duplicate_name_t *gm_duplicate_name; _gss_inquire_sec_context_by_oid *gm_inquire_sec_context_by_oid; _gss_inquire_cred_by_oid *gm_inquire_cred_by_oid; _gss_set_sec_context_option *gm_set_sec_context_option; _gss_set_cred_option *gm_set_cred_option; _gss_pseudo_random *gm_pseudo_random; _gss_wrap_iov_t *gm_wrap_iov; _gss_unwrap_iov_t *gm_unwrap_iov; _gss_wrap_iov_length_t *gm_wrap_iov_length; _gss_store_cred_t *gm_store_cred; _gss_export_cred_t *gm_export_cred; _gss_import_cred_t *gm_import_cred; _gss_acquire_cred_ext_t *gm_acquire_cred_ext; _gss_iter_creds_t *gm_iter_creds; _gss_destroy_cred_t *gm_destroy_cred; _gss_cred_hold_t *gm_cred_hold; _gss_cred_unhold_t *gm_cred_unhold; _gss_cred_label_get_t *gm_cred_label_get; _gss_cred_label_set_t *gm_cred_label_set; gss_mo_desc *gm_mo; size_t gm_mo_num; _gss_localname_t *gm_localname; _gss_authorize_localname_t *gm_authorize_localname; _gss_display_name_ext_t *gm_display_name_ext; _gss_inquire_name_t *gm_inquire_name; _gss_get_name_attribute_t *gm_get_name_attribute; _gss_set_name_attribute_t *gm_set_name_attribute; _gss_delete_name_attribute_t *gm_delete_name_attribute; _gss_export_name_composite_t *gm_export_name_composite; struct gss_mech_compat_desc_struct *gm_compat; } gssapi_mech_interface_desc, *gssapi_mech_interface; gssapi_mech_interface __gss_get_mechanism(gss_const_OID /* oid */); gssapi_mech_interface __gss_spnego_initialize(void); gssapi_mech_interface __gss_krb5_initialize(void); gssapi_mech_interface __gss_ntlm_initialize(void); void gss_mg_collect_error(gss_OID, OM_uint32, OM_uint32); int _gss_mo_get_option_1(gss_const_OID, gss_mo_desc *, gss_buffer_t); int _gss_mo_get_option_0(gss_const_OID, gss_mo_desc *, gss_buffer_t); int _gss_mo_get_ctx_as_string(gss_const_OID, gss_mo_desc *, gss_buffer_t); struct _gss_oid_name_table { gss_OID oid; const char *name; const char *short_desc; const char *long_desc; }; extern struct _gss_oid_name_table _gss_ont_mech[]; extern struct _gss_oid_name_table _gss_ont_ma[]; /* * Extended credentials acqusition API, not to be exported until * it or something equivalent has been standardised. */ extern gss_OID_desc GSSAPI_LIB_VARIABLE __gss_c_cred_password_oid_desc; #define GSS_C_CRED_PASSWORD (&__gss_c_cred_password_oid_desc) extern gss_OID_desc GSSAPI_LIB_VARIABLE __gss_c_cred_certificate_oid_desc; #define GSS_C_CRED_CERTIFICATE (&__gss_c_cred_certificate_oid_desc) OM_uint32 _gss_acquire_cred_ext (OM_uint32 * /*minor_status*/, gss_const_name_t /*desired_name*/, gss_const_OID /*credential_type*/, const void * /*credential_data*/, OM_uint32 /*time_req*/, gss_const_OID /*desired_mech*/, gss_cred_usage_t /*cred_usage*/, gss_cred_id_t * /*output_cred_handle*/ ); #endif /* GSSAPI_MECH_H */ heimdal-7.5.0/lib/gssapi/Makefile.am0000644000175000017500000002245613026237312015352 0ustar niknik# $Id$ include $(top_srcdir)/Makefile.am.common AUTOMAKE_OPTIONS = subdir-objects AM_CPPFLAGS += \ -I$(srcdir)/../krb5 \ -I$(srcdir) \ -I$(srcdir)/gssapi \ -I$(srcdir)/mech \ -I$(srcdir)/ntlm \ -I$(srcdir)/krb5 \ -I$(srcdir)/spnego \ $(INCLUDE_libintl) lib_LTLIBRARIES = libgssapi.la krb5src = \ krb5/8003.c \ krb5/accept_sec_context.c \ krb5/acquire_cred.c \ krb5/add_cred.c \ krb5/address_to_krb5addr.c \ krb5/aeap.c \ krb5/arcfour.c \ krb5/canonicalize_name.c \ krb5/creds.c \ krb5/ccache_name.c \ krb5/cfx.c \ krb5/cfx.h \ krb5/compare_name.c \ krb5/compat.c \ krb5/context_time.c \ krb5/copy_ccache.c \ krb5/decapsulate.c \ krb5/delete_sec_context.c \ krb5/display_name.c \ krb5/display_status.c \ krb5/duplicate_name.c \ krb5/encapsulate.c \ krb5/export_name.c \ krb5/export_sec_context.c \ krb5/external.c \ krb5/get_mic.c \ krb5/gsskrb5_locl.h \ $(srcdir)/krb5/gsskrb5-private.h \ krb5/import_name.c \ krb5/import_sec_context.c \ krb5/indicate_mechs.c \ krb5/init.c \ krb5/init_sec_context.c \ krb5/inquire_context.c \ krb5/inquire_cred.c \ krb5/inquire_cred_by_mech.c \ krb5/inquire_cred_by_oid.c \ krb5/inquire_mechs_for_name.c \ krb5/inquire_names_for_mech.c \ krb5/inquire_sec_context_by_oid.c \ krb5/pname_to_uid.c \ krb5/process_context_token.c \ krb5/prf.c \ krb5/release_buffer.c \ krb5/release_cred.c \ krb5/release_name.c \ krb5/sequence.c \ krb5/store_cred.c \ krb5/set_cred_option.c \ krb5/set_sec_context_option.c \ krb5/ticket_flags.c \ krb5/unwrap.c \ krb5/authorize_localname.c \ krb5/verify_mic.c \ krb5/wrap.c mechsrc = \ mech/context.h \ mech/context.c \ mech/cred.h \ mech/compat.h \ mech/doxygen.c \ mech/gss_accept_sec_context.c \ mech/gss_acquire_cred.c \ mech/gss_acquire_cred_ext.c \ mech/gss_acquire_cred_with_password.c \ mech/gss_add_cred.c \ mech/gss_add_cred_with_password.c \ mech/gss_add_oid_set_member.c \ mech/gss_aeap.c \ mech/gss_buffer_set.c \ mech/gss_canonicalize_name.c \ mech/gss_compare_name.c \ mech/gss_context_time.c \ mech/gss_create_empty_oid_set.c \ mech/gss_cred.c \ mech/gss_decapsulate_token.c \ mech/gss_delete_name_attribute.c \ mech/gss_delete_sec_context.c \ mech/gss_display_name.c \ mech/gss_display_name_ext.c \ mech/gss_display_status.c \ mech/gss_duplicate_name.c \ mech/gss_duplicate_oid.c \ mech/gss_encapsulate_token.c \ mech/gss_export_name.c \ mech/gss_export_name_composite.c \ mech/gss_export_sec_context.c \ mech/gss_get_mic.c \ mech/gss_get_name_attribute.c \ mech/gss_import_name.c \ mech/gss_import_sec_context.c \ mech/gss_indicate_mechs.c \ mech/gss_init_sec_context.c \ mech/gss_inquire_context.c \ mech/gss_inquire_cred.c \ mech/gss_inquire_cred_by_mech.c \ mech/gss_inquire_cred_by_oid.c \ mech/gss_inquire_mechs_for_name.c \ mech/gss_inquire_name.c \ mech/gss_inquire_names_for_mech.c \ mech/gss_krb5.c \ mech/gss_mech_switch.c \ mech/gss_mo.c \ mech/gss_names.c \ mech/gss_oid.c \ mech/gss_oid_equal.c \ mech/gss_oid_to_str.c \ mech/gss_pname_to_uid.c \ mech/gss_process_context_token.c \ mech/gss_pseudo_random.c \ mech/gss_release_buffer.c \ mech/gss_release_cred.c \ mech/gss_release_name.c \ mech/gss_release_oid.c \ mech/gss_release_oid_set.c \ mech/gss_seal.c \ mech/gss_set_cred_option.c \ mech/gss_set_name_attribute.c \ mech/gss_set_sec_context_option.c \ mech/gss_sign.c \ mech/gss_store_cred.c \ mech/gss_test_oid_set_member.c \ mech/gss_unseal.c \ mech/gss_unwrap.c \ mech/gss_authorize_localname.c \ mech/gss_utils.c \ mech/gss_verify.c \ mech/gss_verify_mic.c \ mech/gss_wrap.c \ mech/gss_wrap_size_limit.c \ mech/gss_inquire_sec_context_by_oid.c \ mech/mech_switch.h \ mech/mechqueue.h \ mech/mech_locl.h \ mech/name.h \ mech/utils.h spnegosrc = \ spnego/accept_sec_context.c \ spnego/compat.c \ spnego/context_stubs.c \ spnego/cred_stubs.c \ spnego/external.c \ spnego/init_sec_context.c \ spnego/spnego_locl.h \ $(srcdir)/spnego/spnego-private.h ntlmsrc = \ ntlm/accept_sec_context.c \ ntlm/acquire_cred.c \ ntlm/add_cred.c \ ntlm/canonicalize_name.c \ ntlm/compare_name.c \ ntlm/context_time.c \ ntlm/creds.c \ ntlm/crypto.c \ ntlm/delete_sec_context.c \ ntlm/display_name.c \ ntlm/display_status.c \ ntlm/duplicate_name.c \ ntlm/export_name.c \ ntlm/export_sec_context.c \ ntlm/external.c \ ntlm/ntlm.h \ ntlm/import_name.c \ ntlm/import_sec_context.c \ ntlm/indicate_mechs.c \ ntlm/init_sec_context.c \ ntlm/inquire_context.c \ ntlm/inquire_cred_by_mech.c \ ntlm/inquire_mechs_for_name.c \ ntlm/inquire_names_for_mech.c \ ntlm/inquire_sec_context_by_oid.c \ ntlm/iter_cred.c \ ntlm/process_context_token.c \ ntlm/release_cred.c \ ntlm/release_name.c \ ntlm/kdc.c $(srcdir)/ntlm/ntlm-private.h: $(ntlmsrc) cd $(srcdir) && perl ../../cf/make-proto.pl -q -P comment -p ntlm/ntlm-private.h $(ntlmsrc) || rm -f ntlm/ntlm-private.h dist_libgssapi_la_SOURCES = \ $(krb5src) \ $(mechsrc) \ $(ntlmsrc) \ $(spnegosrc) nodist_libgssapi_la_SOURCES = \ gkrb5_err.c \ gkrb5_err.h \ $(BUILT_SOURCES) libgssapi_la_DEPENDENCIES = version-script.map libgssapi_la_LDFLAGS = -version-info 3:0:0 if versionscript libgssapi_la_LDFLAGS += $(LDFLAGS_VERSION_SCRIPT)$(srcdir)/version-script.map endif libgssapi_la_LIBADD = \ $(top_builddir)/lib/ntlm/libheimntlm.la \ $(top_builddir)/lib/krb5/libkrb5.la \ $(top_builddir)/lib/asn1/libasn1.la \ $(LIB_com_err) \ $(LIB_hcrypto) \ $(LIBADD_roken) man_MANS = gssapi.3 gss_acquire_cred.3 mech/mech.5 include_HEADERS = gssapi.h noinst_HEADERS = \ gssapi_mech.h \ $(srcdir)/ntlm/ntlm-private.h \ $(srcdir)/spnego/spnego-private.h \ $(srcdir)/krb5/gsskrb5-private.h nobase_include_HEADERS = \ gssapi/gssapi.h \ gssapi/gssapi_krb5.h \ gssapi/gssapi_ntlm.h \ gssapi/gssapi_oid.h \ gssapi/gssapi_spnego.h gssapidir = $(includedir)/gssapi nodist_gssapi_HEADERS = gkrb5_err.h gssapi_files = asn1_GSSAPIContextToken.x spnego_files = \ asn1_ContextFlags.x \ asn1_MechType.x \ asn1_MechTypeList.x \ asn1_NegotiationToken.x \ asn1_NegotiationTokenWin.x \ asn1_NegHints.x \ asn1_NegTokenInit.x \ asn1_NegTokenInitWin.x \ asn1_NegTokenResp.x BUILTHEADERS = \ $(srcdir)/krb5/gsskrb5-private.h \ $(srcdir)/spnego/spnego-private.h \ $(srcdir)/ntlm/ntlm-private.h $(libgssapi_la_OBJECTS): $(BUILTHEADERS) $(test_context_OBJECTS): $(BUILTHEADERS) $(libgssapi_la_OBJECTS): $(srcdir)/version-script.map BUILT_SOURCES = $(spnego_files:.x=.c) $(gssapi_files:.x=.c) $(libgssapi_la_OBJECTS): gkrb5_err.h gkrb5_err.h: $(srcdir)/krb5/gkrb5_err.et CLEANFILES = $(BUILT_SOURCES) \ gkrb5_err.h gkrb5_err.c \ $(spnego_files) spnego_asn1*.h* spnego_asn1_files spnego_asn1-template.[cx] \ $(gssapi_files) gssapi_asn1*.h* gssapi_asn1_files gssapi_asn1-template.[cx] \ gss-commands.h gss-commands.c $(spnego_files) spnego_asn1.hx spnego_asn1-priv.hx: spnego_asn1_files $(gssapi_files) gssapi_asn1.hx gssapi_asn1-priv.hx: gssapi_asn1_files spnego_asn1_files: $(ASN1_COMPILE_DEP) $(srcdir)/spnego/spnego.asn1 $(srcdir)/spnego/spnego.opt $(ASN1_COMPILE) --option-file=$(srcdir)/spnego/spnego.opt $(srcdir)/spnego/spnego.asn1 spnego_asn1 gssapi_asn1_files: $(ASN1_COMPILE_DEP) $(srcdir)/mech/gssapi.asn1 $(ASN1_COMPILE) $(srcdir)/mech/gssapi.asn1 gssapi_asn1 $(srcdir)/krb5/gsskrb5-private.h: cd $(srcdir) && perl ../../cf/make-proto.pl -q -P comment -p krb5/gsskrb5-private.h $(krb5src) || rm -f krb5/gsskrb5-private.h $(srcdir)/spnego/spnego-private.h: cd $(srcdir) && perl ../../cf/make-proto.pl -q -P comment -p spnego/spnego-private.h $(spnegosrc) || rm -f spnego/spnego-private.h TESTS = test_oid test_names test_cfx # test_sequence test_cfx_SOURCES = krb5/test_cfx.c check_PROGRAMS = test_acquire_cred $(TESTS) bin_PROGRAMS = gsstool noinst_PROGRAMS = test_cred test_kcred test_context test_ntlm test_add_store_cred test_context_SOURCES = test_context.c test_common.c test_common.h test_ntlm_SOURCES = test_ntlm.c test_common.c test_common.h test_acquire_cred_SOURCES = test_acquire_cred.c test_common.c test_common.h test_add_store_cred_SOURCES = test_add_store_cred.c test_ntlm_LDADD = \ $(top_builddir)/lib/ntlm/libheimntlm.la \ $(LDADD) LDADD = libgssapi.la \ $(top_builddir)/lib/krb5/libkrb5.la \ $(LIB_roken) # gss dist_gsstool_SOURCES = gsstool.c nodist_gsstool_SOURCES = gss-commands.c gss-commands.h gsstool_LDADD = libgssapi.la \ $(top_builddir)/lib/sl/libsl.la \ $(top_builddir)/lib/krb5/libkrb5.la \ $(LIB_readline) \ $(LIB_roken) gss-commands.c gss-commands.h: gss-commands.in $(SLC) $(srcdir)/gss-commands.in $(gsstool_OBJECTS): gss-commands.h EXTRA_DIST = \ NTMakefile \ libgssapi-version.rc \ libgssapi-exports.def \ $(man_MANS) \ gen-oid.pl \ gssapi/gssapi_netlogon.h \ krb5/test_acquire_cred.c \ krb5/test_cred.c \ krb5/test_kcred.c \ krb5/test_oid.c \ oid.txt \ krb5/gkrb5_err.et \ mech/gssapi.asn1 \ spnego/spnego.asn1 \ spnego/spnego.opt \ version-script.map \ gss-commands.in $(libgssapi_la_OBJECTS): gkrb5_err.h gssapi_asn1.h gssapi_asn1-priv.h $(libgssapi_la_OBJECTS): spnego_asn1.h spnego_asn1-priv.h $(libgssapi_la_OBJECTS): $(srcdir)/gssapi/gssapi_oid.h gkrb5_err.h gkrb5_err.c: $(srcdir)/krb5/gkrb5_err.et $(COMPILE_ET) $(srcdir)/krb5/gkrb5_err.et $(srcdir)/gssapi/gssapi_oid.h $(srcdir)/mech/gss_oid.c: perl $(srcdir)/gen-oid.pl -b base -h $(srcdir)/oid.txt > $(srcdir)/gssapi/gssapi_oid.h perl $(srcdir)/gen-oid.pl -b base $(srcdir)/oid.txt > $(srcdir)/mech/gss_oid.c heimdal-7.5.0/lib/gssapi/test_ntlm.c0000644000175000017500000002041513026237312015464 0ustar niknik/* * Copyright (c) 2006 - 2008 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of KTH nor the names of its contributors may be * used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY KTH AND ITS CONTRIBUTORS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL KTH OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "config.h" #include #include #include #include #include #include "test_common.h" #include #include static int test_libntlm_v1(int flags) { const char *user = "foo", *domain = "mydomain", *password = "digestpassword"; OM_uint32 maj_stat, min_stat; gss_ctx_id_t ctx = GSS_C_NO_CONTEXT; gss_buffer_desc input, output; struct ntlm_type1 type1; struct ntlm_type2 type2; struct ntlm_type3 type3; struct ntlm_buf data; krb5_error_code ret; gss_name_t src_name = GSS_C_NO_NAME; memset(&type1, 0, sizeof(type1)); memset(&type2, 0, sizeof(type2)); memset(&type3, 0, sizeof(type3)); type1.flags = NTLM_NEG_UNICODE|NTLM_NEG_TARGET|NTLM_NEG_NTLM|flags; type1.domain = strdup(domain); type1.hostname = NULL; type1.os[0] = 0; type1.os[1] = 0; ret = heim_ntlm_encode_type1(&type1, &data); if (ret) errx(1, "heim_ntlm_encode_type1"); input.value = data.data; input.length = data.length; output.length = 0; output.value = NULL; maj_stat = gss_accept_sec_context(&min_stat, &ctx, GSS_C_NO_CREDENTIAL, &input, GSS_C_NO_CHANNEL_BINDINGS, NULL, NULL, &output, NULL, NULL, NULL); free(data.data); if (GSS_ERROR(maj_stat)) errx(1, "accept_sec_context v1: %s", gssapi_err(maj_stat, min_stat, GSS_C_NO_OID)); if (output.length == 0) errx(1, "output.length == 0"); data.data = output.value; data.length = output.length; ret = heim_ntlm_decode_type2(&data, &type2); if (ret) errx(1, "heim_ntlm_decode_type2"); gss_release_buffer(&min_stat, &output); type3.flags = type2.flags; type3.username = rk_UNCONST(user); type3.targetname = type2.targetname; type3.ws = rk_UNCONST("workstation"); { struct ntlm_buf key; heim_ntlm_nt_key(password, &key); heim_ntlm_calculate_ntlm1(key.data, key.length, type2.challenge, &type3.ntlm); if (flags & NTLM_NEG_KEYEX) { struct ntlm_buf sessionkey; heim_ntlm_build_ntlm1_master(key.data, key.length, &sessionkey, &type3.sessionkey); free(sessionkey.data); } free(key.data); } ret = heim_ntlm_encode_type3(&type3, &data, NULL); if (ret) errx(1, "heim_ntlm_encode_type3"); input.length = data.length; input.value = data.data; maj_stat = gss_accept_sec_context(&min_stat, &ctx, GSS_C_NO_CREDENTIAL, &input, GSS_C_NO_CHANNEL_BINDINGS, &src_name, NULL, &output, NULL, NULL, NULL); free(input.value); if (maj_stat != GSS_S_COMPLETE) errx(1, "accept_sec_context v1 2 %s", gssapi_err(maj_stat, min_stat, GSS_C_NO_OID)); gss_release_buffer(&min_stat, &output); gss_delete_sec_context(&min_stat, &ctx, NULL); if (src_name == GSS_C_NO_NAME) errx(1, "no source name!"); gss_display_name(&min_stat, src_name, &output, NULL); printf("src_name: %.*s\n", (int)output.length, (char*)output.value); gss_release_name(&min_stat, &src_name); gss_release_buffer(&min_stat, &output); return 0; } static int test_libntlm_v2(int flags) { const char *user = "foo", *domain = "mydomain", *password = "digestpassword"; OM_uint32 maj_stat, min_stat; gss_ctx_id_t ctx = GSS_C_NO_CONTEXT; gss_buffer_desc input, output; struct ntlm_type1 type1; struct ntlm_type2 type2; struct ntlm_type3 type3; struct ntlm_buf data; krb5_error_code ret; memset(&type1, 0, sizeof(type1)); memset(&type2, 0, sizeof(type2)); memset(&type3, 0, sizeof(type3)); type1.flags = NTLM_NEG_UNICODE|NTLM_NEG_NTLM|flags; type1.domain = strdup(domain); type1.hostname = NULL; type1.os[0] = 0; type1.os[1] = 0; ret = heim_ntlm_encode_type1(&type1, &data); if (ret) errx(1, "heim_ntlm_encode_type1"); input.value = data.data; input.length = data.length; output.length = 0; output.value = NULL; maj_stat = gss_accept_sec_context(&min_stat, &ctx, GSS_C_NO_CREDENTIAL, &input, GSS_C_NO_CHANNEL_BINDINGS, NULL, NULL, &output, NULL, NULL, NULL); free(data.data); if (GSS_ERROR(maj_stat)) errx(1, "accept_sec_context v2 %s", gssapi_err(maj_stat, min_stat, GSS_C_NO_OID)); if (output.length == 0) errx(1, "output.length == 0"); data.data = output.value; data.length = output.length; ret = heim_ntlm_decode_type2(&data, &type2); if (ret) errx(1, "heim_ntlm_decode_type2"); type3.flags = type2.flags; type3.username = rk_UNCONST(user); type3.targetname = type2.targetname; type3.ws = rk_UNCONST("workstation"); { struct ntlm_buf key; unsigned char ntlmv2[16]; heim_ntlm_nt_key(password, &key); heim_ntlm_calculate_ntlm2(key.data, key.length, user, type2.targetname, type2.challenge, &type2.targetinfo, ntlmv2, &type3.ntlm); free(key.data); if (flags & NTLM_NEG_KEYEX) { struct ntlm_buf sessionkey; heim_ntlm_build_ntlm1_master(ntlmv2, sizeof(ntlmv2), &sessionkey, &type3.sessionkey); free(sessionkey.data); } } ret = heim_ntlm_encode_type3(&type3, &data, NULL); if (ret) errx(1, "heim_ntlm_encode_type3"); input.length = data.length; input.value = data.data; maj_stat = gss_accept_sec_context(&min_stat, &ctx, GSS_C_NO_CREDENTIAL, &input, GSS_C_NO_CHANNEL_BINDINGS, NULL, NULL, &output, NULL, NULL, NULL); free(input.value); if (maj_stat != GSS_S_COMPLETE) errx(1, "accept_sec_context v2 2 %s", gssapi_err(maj_stat, min_stat, GSS_C_NO_OID)); gss_delete_sec_context(&min_stat, &ctx, NULL); return 0; } static int version_flag = 0; static int help_flag = 0; static struct getargs args[] = { {"version", 0, arg_flag, &version_flag, "print version", NULL }, {"help", 0, arg_flag, &help_flag, NULL, NULL } }; static void usage (int ret) { arg_printusage (args, sizeof(args)/sizeof(*args), NULL, ""); exit (ret); } int main(int argc, char **argv) { int ret = 0, optidx = 0; setprogname(argv[0]); if(getarg(args, sizeof(args) / sizeof(args[0]), argc, argv, &optidx)) usage(1); if (help_flag) usage (0); if(version_flag){ print_version(NULL); exit(0); } argc -= optidx; argv += optidx; ret += test_libntlm_v1(0); ret += test_libntlm_v1(NTLM_NEG_KEYEX); ret += test_libntlm_v2(0); ret += test_libntlm_v2(NTLM_NEG_KEYEX); return ret; } heimdal-7.5.0/lib/gssapi/libgssapi-version.rc0000644000175000017500000000330112136107747017301 0ustar niknik/*********************************************************************** * Copyright (c) 2010, Secure Endpoints Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * - Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. * **********************************************************************/ #define RC_FILE_TYPE VFT_DLL #define RC_FILE_DESC_0409 "Generic Security Service Application Program Interface library" #define RC_FILE_ORIG_0409 "gssapi.dll" #include "../../windows/version.rc" heimdal-7.5.0/lib/gssapi/gss_acquire_cred.cat30000644000175000017500000007672013212450760017400 0ustar niknik GSS_ACQUIRE_CRED(3) BSD Library Functions Manual GSS_ACQUIRE_CRED(3) NNAAMMEE ggssss__aacccceepptt__sseecc__ccoonntteexxtt, ggssss__aaccqquuiirree__ccrreedd, ggssss__aadddd__ccrreedd, ggssss__aadddd__ooiidd__sseett__mmeemmbbeerr, ggssss__ccaannoonniiccaalliizzee__nnaammee, ggssss__ccoommppaarree__nnaammee, ggssss__ccoonntteexxtt__ttiimmee, ggssss__ccrreeaattee__eemmppttyy__ooiidd__sseett, ggssss__ddeelleettee__sseecc__ccoonntteexxtt, ggssss__ddiissppllaayy__nnaammee, ggssss__ddiissppllaayy__ssttaattuuss, ggssss__dduupplliiccaattee__nnaammee, ggssss__eexxppoorrtt__nnaammee, ggssss__eexxppoorrtt__sseecc__ccoonntteexxtt, ggssss__ggeett__mmiicc, ggssss__iimmppoorrtt__nnaammee, ggssss__iimmppoorrtt__sseecc__ccoonntteexxtt, ggssss__iinnddiiccaattee__mmeecchhss, ggssss__iinniitt__sseecc__ccoonntteexxtt, ggssss__iinnqquuiirree__ccoonntteexxtt, ggssss__iinnqquuiirree__ccrreedd, ggssss__iinnqquuiirree__ccrreedd__bbyy__mmeecchh, ggssss__iinnqquuiirree__mmeecchhss__ffoorr__nnaammee, ggssss__iinnqquuiirree__nnaammeess__ffoorr__mmeecchh, ggssss__kkrrbb55__ccccaacchhee__nnaammee, ggssss__kkrrbb55__ccoommppaatt__ddeess33__mmiicc, ggssss__kkrrbb55__ccooppyy__ccccaacchhee, ggssss__kkrrbb55__iimmppoorrtt__ccrreedd ggsssskkrrbb55__eexxttrraacctt__aauutthhzz__ddaattaa__ffrroomm__sseecc__ccoonntteexxtt, ggsssskkrrbb55__rreeggiisstteerr__aacccceeppttoorr__iiddeennttiittyy, ggssss__kkrrbb55__iimmppoorrtt__ccccaacchhee, ggssss__kkrrbb55__ggeett__ttkktt__ffllaaggss, ggssss__pprroocceessss__ccoonntteexxtt__ttookkeenn, ggssss__rreelleeaassee__bbuuffffeerr, ggssss__rreelleeaassee__ccrreedd, ggssss__rreelleeaassee__nnaammee, ggssss__rreelleeaassee__ooiidd__sseett, ggssss__sseeaall, ggssss__ssiiggnn, ggssss__tteesstt__ooiidd__sseett__mmeemmbbeerr, ggssss__uunnsseeaall, ggssss__uunnwwrraapp, ggssss__vveerriiffyy, ggssss__vveerriiffyy__mmiicc, ggssss__wwrraapp, ggssss__wwrraapp__ssiizzee__lliimmiitt -- Generic Security Service Application Program Interface library LLIIBBRRAARRYY GSS-API library (libgssapi, -lgssapi) SSYYNNOOPPSSIISS ##iinncclluuddee <> _O_M___u_i_n_t_3_2 ggssss__aacccceepptt__sseecc__ccoonntteexxtt(_O_M___u_i_n_t_3_2 _* _m_i_n_o_r___s_t_a_t_u_s, _g_s_s___c_t_x___i_d___t _* _c_o_n_t_e_x_t___h_a_n_d_l_e, _g_s_s___c_o_n_s_t___c_r_e_d___i_d___t _a_c_c_e_p_t_o_r___c_r_e_d___h_a_n_d_l_e, _c_o_n_s_t _g_s_s___b_u_f_f_e_r___t _i_n_p_u_t___t_o_k_e_n___b_u_f_f_e_r, _c_o_n_s_t _g_s_s___c_h_a_n_n_e_l___b_i_n_d_i_n_g_s___t _i_n_p_u_t___c_h_a_n___b_i_n_d_i_n_g_s, _g_s_s___n_a_m_e___t _* _s_r_c___n_a_m_e, _g_s_s___O_I_D _* _m_e_c_h___t_y_p_e, _g_s_s___b_u_f_f_e_r___t _o_u_t_p_u_t___t_o_k_e_n, _O_M___u_i_n_t_3_2 _* _r_e_t___f_l_a_g_s, _O_M___u_i_n_t_3_2 _* _t_i_m_e___r_e_c, _g_s_s___c_r_e_d___i_d___t _* _d_e_l_e_g_a_t_e_d___c_r_e_d___h_a_n_d_l_e); _O_M___u_i_n_t_3_2 ggssss__aaccqquuiirree__ccrreedd(_O_M___u_i_n_t_3_2 _* _m_i_n_o_r___s_t_a_t_u_s, _g_s_s___c_o_n_s_t___n_a_m_e___t _d_e_s_i_r_e_d___n_a_m_e, _O_M___u_i_n_t_3_2 _t_i_m_e___r_e_q, _c_o_n_s_t _g_s_s___O_I_D___s_e_t _d_e_s_i_r_e_d___m_e_c_h_s, _g_s_s___c_r_e_d___u_s_a_g_e___t _c_r_e_d___u_s_a_g_e, _g_s_s___c_r_e_d___i_d___t _* _o_u_t_p_u_t___c_r_e_d___h_a_n_d_l_e, _g_s_s___O_I_D___s_e_t _* _a_c_t_u_a_l___m_e_c_h_s, _O_M___u_i_n_t_3_2 _* _t_i_m_e___r_e_c); _O_M___u_i_n_t_3_2 ggssss__aadddd__ccrreedd(_O_M___u_i_n_t_3_2 _*_m_i_n_o_r___s_t_a_t_u_s, _g_s_s___c_o_n_s_t___c_r_e_d___i_d___t _i_n_p_u_t___c_r_e_d___h_a_n_d_l_e, _g_s_s___c_o_n_s_t___n_a_m_e___t _d_e_s_i_r_e_d___n_a_m_e, _c_o_n_s_t _g_s_s___O_I_D _d_e_s_i_r_e_d___m_e_c_h, _g_s_s___c_r_e_d___u_s_a_g_e___t _c_r_e_d___u_s_a_g_e, _O_M___u_i_n_t_3_2 _i_n_i_t_i_a_t_o_r___t_i_m_e___r_e_q, _O_M___u_i_n_t_3_2 _a_c_c_e_p_t_o_r___t_i_m_e___r_e_q, _g_s_s___c_r_e_d___i_d___t _*_o_u_t_p_u_t___c_r_e_d___h_a_n_d_l_e, _g_s_s___O_I_D___s_e_t _*_a_c_t_u_a_l___m_e_c_h_s, _O_M___u_i_n_t_3_2 _*_i_n_i_t_i_a_t_o_r___t_i_m_e___r_e_c, _O_M___u_i_n_t_3_2 _*_a_c_c_e_p_t_o_r___t_i_m_e___r_e_c); _O_M___u_i_n_t_3_2 ggssss__aadddd__ooiidd__sseett__mmeemmbbeerr(_O_M___u_i_n_t_3_2 _* _m_i_n_o_r___s_t_a_t_u_s, _c_o_n_s_t _g_s_s___O_I_D _m_e_m_b_e_r___o_i_d, _g_s_s___O_I_D___s_e_t _* _o_i_d___s_e_t); _O_M___u_i_n_t_3_2 ggssss__ccaannoonniiccaalliizzee__nnaammee(_O_M___u_i_n_t_3_2 _* _m_i_n_o_r___s_t_a_t_u_s, _g_s_s___c_o_n_s_t___n_a_m_e___t _i_n_p_u_t___n_a_m_e, _c_o_n_s_t _g_s_s___O_I_D _m_e_c_h___t_y_p_e, _g_s_s___n_a_m_e___t _* _o_u_t_p_u_t___n_a_m_e); _O_M___u_i_n_t_3_2 ggssss__ccoommppaarree__nnaammee(_O_M___u_i_n_t_3_2 _* _m_i_n_o_r___s_t_a_t_u_s, _g_s_s___c_o_n_s_t___n_a_m_e___t _n_a_m_e_1, _g_s_s___c_o_n_s_t___n_a_m_e___t _n_a_m_e_2, _i_n_t _* _n_a_m_e___e_q_u_a_l); _O_M___u_i_n_t_3_2 ggssss__ccoonntteexxtt__ttiimmee(_O_M___u_i_n_t_3_2 _* _m_i_n_o_r___s_t_a_t_u_s, _g_s_s___c_o_n_s_t___c_t_x___i_d___t _c_o_n_t_e_x_t___h_a_n_d_l_e, _O_M___u_i_n_t_3_2 _* _t_i_m_e___r_e_c); _O_M___u_i_n_t_3_2 ggssss__ccrreeaattee__eemmppttyy__ooiidd__sseett(_O_M___u_i_n_t_3_2 _* _m_i_n_o_r___s_t_a_t_u_s, _g_s_s___O_I_D___s_e_t _* _o_i_d___s_e_t); _O_M___u_i_n_t_3_2 ggssss__ddeelleettee__sseecc__ccoonntteexxtt(_O_M___u_i_n_t_3_2 _* _m_i_n_o_r___s_t_a_t_u_s, _g_s_s___c_t_x___i_d___t _* _c_o_n_t_e_x_t___h_a_n_d_l_e, _g_s_s___b_u_f_f_e_r___t _o_u_t_p_u_t___t_o_k_e_n); _O_M___u_i_n_t_3_2 ggssss__ddiissppllaayy__nnaammee(_O_M___u_i_n_t_3_2 _* _m_i_n_o_r___s_t_a_t_u_s, _g_s_s___c_o_n_s_t___n_a_m_e___t _i_n_p_u_t___n_a_m_e, _g_s_s___b_u_f_f_e_r___t _o_u_t_p_u_t___n_a_m_e___b_u_f_f_e_r, _g_s_s___O_I_D _* _o_u_t_p_u_t___n_a_m_e___t_y_p_e); _O_M___u_i_n_t_3_2 ggssss__ddiissppllaayy__ssttaattuuss(_O_M___u_i_n_t_3_2 _*_m_i_n_o_r___s_t_a_t_u_s, _O_M___u_i_n_t_3_2 _s_t_a_t_u_s___v_a_l_u_e, _i_n_t _s_t_a_t_u_s___t_y_p_e, _c_o_n_s_t _g_s_s___O_I_D _m_e_c_h___t_y_p_e, _O_M___u_i_n_t_3_2 _*_m_e_s_s_a_g_e___c_o_n_t_e_x_t, _g_s_s___b_u_f_f_e_r___t _s_t_a_t_u_s___s_t_r_i_n_g); _O_M___u_i_n_t_3_2 ggssss__dduupplliiccaattee__nnaammee(_O_M___u_i_n_t_3_2 _* _m_i_n_o_r___s_t_a_t_u_s, _g_s_s___c_o_n_s_t___n_a_m_e___t _s_r_c___n_a_m_e, _g_s_s___n_a_m_e___t _* _d_e_s_t___n_a_m_e); _O_M___u_i_n_t_3_2 ggssss__eexxppoorrtt__nnaammee(_O_M___u_i_n_t_3_2 _* _m_i_n_o_r___s_t_a_t_u_s, _g_s_s___c_o_n_s_t___n_a_m_e___t _i_n_p_u_t___n_a_m_e, _g_s_s___b_u_f_f_e_r___t _e_x_p_o_r_t_e_d___n_a_m_e); _O_M___u_i_n_t_3_2 ggssss__eexxppoorrtt__sseecc__ccoonntteexxtt(_O_M___u_i_n_t_3_2 _* _m_i_n_o_r___s_t_a_t_u_s, _g_s_s___c_t_x___i_d___t _* _c_o_n_t_e_x_t___h_a_n_d_l_e, _g_s_s___b_u_f_f_e_r___t _i_n_t_e_r_p_r_o_c_e_s_s___t_o_k_e_n); _O_M___u_i_n_t_3_2 ggssss__ggeett__mmiicc(_O_M___u_i_n_t_3_2 _* _m_i_n_o_r___s_t_a_t_u_s, _g_s_s___c_o_n_s_t___c_t_x___i_d___t _c_o_n_t_e_x_t___h_a_n_d_l_e, _g_s_s___q_o_p___t _q_o_p___r_e_q, _c_o_n_s_t _g_s_s___b_u_f_f_e_r___t _m_e_s_s_a_g_e___b_u_f_f_e_r, _g_s_s___b_u_f_f_e_r___t _m_e_s_s_a_g_e___t_o_k_e_n); _O_M___u_i_n_t_3_2 ggssss__iimmppoorrtt__nnaammee(_O_M___u_i_n_t_3_2 _* _m_i_n_o_r___s_t_a_t_u_s, _c_o_n_s_t _g_s_s___b_u_f_f_e_r___t _i_n_p_u_t___n_a_m_e___b_u_f_f_e_r, _c_o_n_s_t _g_s_s___O_I_D _i_n_p_u_t___n_a_m_e___t_y_p_e, _g_s_s___n_a_m_e___t _* _o_u_t_p_u_t___n_a_m_e); _O_M___u_i_n_t_3_2 ggssss__iimmppoorrtt__sseecc__ccoonntteexxtt(_O_M___u_i_n_t_3_2 _* _m_i_n_o_r___s_t_a_t_u_s, _c_o_n_s_t _g_s_s___b_u_f_f_e_r___t _i_n_t_e_r_p_r_o_c_e_s_s___t_o_k_e_n, _g_s_s___c_t_x___i_d___t _* _c_o_n_t_e_x_t___h_a_n_d_l_e); _O_M___u_i_n_t_3_2 ggssss__iinnddiiccaattee__mmeecchhss(_O_M___u_i_n_t_3_2 _* _m_i_n_o_r___s_t_a_t_u_s, _g_s_s___O_I_D___s_e_t _* _m_e_c_h___s_e_t); _O_M___u_i_n_t_3_2 ggssss__iinniitt__sseecc__ccoonntteexxtt(_O_M___u_i_n_t_3_2 _* _m_i_n_o_r___s_t_a_t_u_s, _g_s_s___c_o_n_s_t___c_r_e_d___i_d___t _i_n_i_t_i_a_t_o_r___c_r_e_d___h_a_n_d_l_e, _g_s_s___c_t_x___i_d___t _* _c_o_n_t_e_x_t___h_a_n_d_l_e, _g_s_s___c_o_n_s_t___n_a_m_e___t _t_a_r_g_e_t___n_a_m_e, _c_o_n_s_t _g_s_s___O_I_D _m_e_c_h___t_y_p_e, _O_M___u_i_n_t_3_2 _r_e_q___f_l_a_g_s, _O_M___u_i_n_t_3_2 _t_i_m_e___r_e_q, _c_o_n_s_t _g_s_s___c_h_a_n_n_e_l___b_i_n_d_i_n_g_s___t _i_n_p_u_t___c_h_a_n___b_i_n_d_i_n_g_s, _c_o_n_s_t _g_s_s___b_u_f_f_e_r___t _i_n_p_u_t___t_o_k_e_n, _g_s_s___O_I_D _* _a_c_t_u_a_l___m_e_c_h___t_y_p_e, _g_s_s___b_u_f_f_e_r___t _o_u_t_p_u_t___t_o_k_e_n, _O_M___u_i_n_t_3_2 _* _r_e_t___f_l_a_g_s, _O_M___u_i_n_t_3_2 _* _t_i_m_e___r_e_c); _O_M___u_i_n_t_3_2 ggssss__iinnqquuiirree__ccoonntteexxtt(_O_M___u_i_n_t_3_2 _* _m_i_n_o_r___s_t_a_t_u_s, _g_s_s___c_o_n_s_t___c_t_x___i_d___t _c_o_n_t_e_x_t___h_a_n_d_l_e, _g_s_s___n_a_m_e___t _* _s_r_c___n_a_m_e, _g_s_s___n_a_m_e___t _* _t_a_r_g___n_a_m_e, _O_M___u_i_n_t_3_2 _* _l_i_f_e_t_i_m_e___r_e_c, _g_s_s___O_I_D _* _m_e_c_h___t_y_p_e, _O_M___u_i_n_t_3_2 _* _c_t_x___f_l_a_g_s, _i_n_t _* _l_o_c_a_l_l_y___i_n_i_t_i_a_t_e_d, _i_n_t _* _o_p_e_n___c_o_n_t_e_x_t); _O_M___u_i_n_t_3_2 ggssss__iinnqquuiirree__ccrreedd(_O_M___u_i_n_t_3_2 _* _m_i_n_o_r___s_t_a_t_u_s, _g_s_s___c_o_n_s_t___c_r_e_d___i_d___t _c_r_e_d___h_a_n_d_l_e, _g_s_s___n_a_m_e___t _* _n_a_m_e, _O_M___u_i_n_t_3_2 _* _l_i_f_e_t_i_m_e, _g_s_s___c_r_e_d___u_s_a_g_e___t _* _c_r_e_d___u_s_a_g_e, _g_s_s___O_I_D___s_e_t _* _m_e_c_h_a_n_i_s_m_s); _O_M___u_i_n_t_3_2 ggssss__iinnqquuiirree__ccrreedd__bbyy__mmeecchh(_O_M___u_i_n_t_3_2 _* _m_i_n_o_r___s_t_a_t_u_s, _g_s_s___c_o_n_s_t___c_r_e_d___i_d___t _c_r_e_d___h_a_n_d_l_e, _c_o_n_s_t _g_s_s___O_I_D _m_e_c_h___t_y_p_e, _g_s_s___n_a_m_e___t _* _n_a_m_e, _O_M___u_i_n_t_3_2 _* _i_n_i_t_i_a_t_o_r___l_i_f_e_t_i_m_e, _O_M___u_i_n_t_3_2 _* _a_c_c_e_p_t_o_r___l_i_f_e_t_i_m_e, _g_s_s___c_r_e_d___u_s_a_g_e___t _* _c_r_e_d___u_s_a_g_e); _O_M___u_i_n_t_3_2 ggssss__iinnqquuiirree__mmeecchhss__ffoorr__nnaammee(_O_M___u_i_n_t_3_2 _* _m_i_n_o_r___s_t_a_t_u_s, _g_s_s___c_o_n_s_t___n_a_m_e___t _i_n_p_u_t___n_a_m_e, _g_s_s___O_I_D___s_e_t _* _m_e_c_h___t_y_p_e_s); _O_M___u_i_n_t_3_2 ggssss__iinnqquuiirree__nnaammeess__ffoorr__mmeecchh(_O_M___u_i_n_t_3_2 _* _m_i_n_o_r___s_t_a_t_u_s, _c_o_n_s_t _g_s_s___O_I_D _m_e_c_h_a_n_i_s_m, _g_s_s___O_I_D___s_e_t _* _n_a_m_e___t_y_p_e_s); _O_M___u_i_n_t_3_2 ggssss__kkrrbb55__ccccaacchhee__nnaammee(_O_M___u_i_n_t_3_2 _*_m_i_n_o_r, _c_o_n_s_t _c_h_a_r _*_n_a_m_e, _c_o_n_s_t _c_h_a_r _*_*_o_l_d___n_a_m_e); _O_M___u_i_n_t_3_2 ggssss__kkrrbb55__ccooppyy__ccccaacchhee(_O_M___u_i_n_t_3_2 _*_m_i_n_o_r, _g_s_s___c_r_e_d___i_d___t _c_r_e_d, _k_r_b_5___c_c_a_c_h_e _o_u_t); _O_M___u_i_n_t_3_2 ggssss__kkrrbb55__iimmppoorrtt__ccrreedd(_O_M___u_i_n_t_3_2 _*_m_i_n_o_r___s_t_a_t_u_s, _k_r_b_5___c_c_a_c_h_e _i_d, _k_r_b_5___p_r_i_n_c_i_p_a_l _k_e_y_t_a_b___p_r_i_n_c_i_p_a_l, _k_r_b_5___k_e_y_t_a_b _k_e_y_t_a_b, _g_s_s___c_r_e_d___i_d___t _*_c_r_e_d); _O_M___u_i_n_t_3_2 ggssss__kkrrbb55__ccoommppaatt__ddeess33__mmiicc(_O_M___u_i_n_t_3_2 _* _m_i_n_o_r___s_t_a_t_u_s, _g_s_s___c_t_x___i_d___t _c_o_n_t_e_x_t___h_a_n_d_l_e, _i_n_t _o_n_o_f_f); _O_M___u_i_n_t_3_2 ggsssskkrrbb55__eexxttrraacctt__aauutthhzz__ddaattaa__ffrroomm__sseecc__ccoonntteexxtt(_O_M___u_i_n_t_3_2 _*_m_i_n_o_r___s_t_a_t_u_s, _g_s_s___c_t_x___i_d___t _c_o_n_t_e_x_t___h_a_n_d_l_e, _i_n_t _a_d___t_y_p_e, _g_s_s___b_u_f_f_e_r___t _a_d___d_a_t_a); _O_M___u_i_n_t_3_2 ggsssskkrrbb55__rreeggiisstteerr__aacccceeppttoorr__iiddeennttiittyy(_c_o_n_s_t _c_h_a_r _*_i_d_e_n_t_i_t_y); _O_M___u_i_n_t_3_2 ggssss__kkrrbb55__iimmppoorrtt__ccaacchhee(_O_M___u_i_n_t_3_2 _*_m_i_n_o_r, _k_r_b_5___c_c_a_c_h_e _i_d, _k_r_b_5___k_e_y_t_a_b _k_e_y_t_a_b, _g_s_s___c_r_e_d___i_d___t _*_c_r_e_d); _O_M___u_i_n_t_3_2 ggssss__kkrrbb55__ggeett__ttkktt__ffllaaggss(_O_M___u_i_n_t_3_2 _*_m_i_n_o_r___s_t_a_t_u_s, _g_s_s___c_t_x___i_d___t _c_o_n_t_e_x_t___h_a_n_d_l_e, _O_M___u_i_n_t_3_2 _*_t_k_t___f_l_a_g_s); _O_M___u_i_n_t_3_2 ggssss__pprroocceessss__ccoonntteexxtt__ttookkeenn(_O_M___u_i_n_t_3_2 _* _m_i_n_o_r___s_t_a_t_u_s, _g_s_s___c_o_n_s_t___c_t_x___i_d___t _c_o_n_t_e_x_t___h_a_n_d_l_e, _c_o_n_s_t _g_s_s___b_u_f_f_e_r___t _t_o_k_e_n___b_u_f_f_e_r); _O_M___u_i_n_t_3_2 ggssss__rreelleeaassee__bbuuffffeerr(_O_M___u_i_n_t_3_2 _* _m_i_n_o_r___s_t_a_t_u_s, _g_s_s___b_u_f_f_e_r___t _b_u_f_f_e_r); _O_M___u_i_n_t_3_2 ggssss__rreelleeaassee__ccrreedd(_O_M___u_i_n_t_3_2 _* _m_i_n_o_r___s_t_a_t_u_s, _g_s_s___c_r_e_d___i_d___t _* _c_r_e_d___h_a_n_d_l_e); _O_M___u_i_n_t_3_2 ggssss__rreelleeaassee__nnaammee(_O_M___u_i_n_t_3_2 _* _m_i_n_o_r___s_t_a_t_u_s, _g_s_s___n_a_m_e___t _* _i_n_p_u_t___n_a_m_e); _O_M___u_i_n_t_3_2 ggssss__rreelleeaassee__ooiidd__sseett(_O_M___u_i_n_t_3_2 _* _m_i_n_o_r___s_t_a_t_u_s, _g_s_s___O_I_D___s_e_t _* _s_e_t); _O_M___u_i_n_t_3_2 ggssss__sseeaall(_O_M___u_i_n_t_3_2 _* _m_i_n_o_r___s_t_a_t_u_s, _g_s_s___c_t_x___i_d___t _c_o_n_t_e_x_t___h_a_n_d_l_e, _i_n_t _c_o_n_f___r_e_q___f_l_a_g, _i_n_t _q_o_p___r_e_q, _g_s_s___b_u_f_f_e_r___t _i_n_p_u_t___m_e_s_s_a_g_e___b_u_f_f_e_r, _i_n_t _* _c_o_n_f___s_t_a_t_e, _g_s_s___b_u_f_f_e_r___t _o_u_t_p_u_t___m_e_s_s_a_g_e___b_u_f_f_e_r); _O_M___u_i_n_t_3_2 ggssss__ssiiggnn(_O_M___u_i_n_t_3_2 _* _m_i_n_o_r___s_t_a_t_u_s, _g_s_s___c_t_x___i_d___t _c_o_n_t_e_x_t___h_a_n_d_l_e, _i_n_t _q_o_p___r_e_q, _g_s_s___b_u_f_f_e_r___t _m_e_s_s_a_g_e___b_u_f_f_e_r, _g_s_s___b_u_f_f_e_r___t _m_e_s_s_a_g_e___t_o_k_e_n); _O_M___u_i_n_t_3_2 ggssss__tteesstt__ooiidd__sseett__mmeemmbbeerr(_O_M___u_i_n_t_3_2 _* _m_i_n_o_r___s_t_a_t_u_s, _c_o_n_s_t _g_s_s___O_I_D _m_e_m_b_e_r, _c_o_n_s_t _g_s_s___O_I_D___s_e_t _s_e_t, _i_n_t _* _p_r_e_s_e_n_t); _O_M___u_i_n_t_3_2 ggssss__uunnsseeaall(_O_M___u_i_n_t_3_2 _* _m_i_n_o_r___s_t_a_t_u_s, _g_s_s___c_t_x___i_d___t _c_o_n_t_e_x_t___h_a_n_d_l_e, _g_s_s___b_u_f_f_e_r___t _i_n_p_u_t___m_e_s_s_a_g_e___b_u_f_f_e_r, _g_s_s___b_u_f_f_e_r___t _o_u_t_p_u_t___m_e_s_s_a_g_e___b_u_f_f_e_r, _i_n_t _* _c_o_n_f___s_t_a_t_e, _i_n_t _* _q_o_p___s_t_a_t_e); _O_M___u_i_n_t_3_2 ggssss__uunnwwrraapp(_O_M___u_i_n_t_3_2 _* _m_i_n_o_r___s_t_a_t_u_s, _g_s_s___c_o_n_s_t___c_t_x___i_d___t _c_o_n_t_e_x_t___h_a_n_d_l_e, _c_o_n_s_t _g_s_s___b_u_f_f_e_r___t _i_n_p_u_t___m_e_s_s_a_g_e___b_u_f_f_e_r, _g_s_s___b_u_f_f_e_r___t _o_u_t_p_u_t___m_e_s_s_a_g_e___b_u_f_f_e_r, _i_n_t _* _c_o_n_f___s_t_a_t_e, _g_s_s___q_o_p___t _* _q_o_p___s_t_a_t_e); _O_M___u_i_n_t_3_2 ggssss__vveerriiffyy(_O_M___u_i_n_t_3_2 _* _m_i_n_o_r___s_t_a_t_u_s, _g_s_s___c_t_x___i_d___t _c_o_n_t_e_x_t___h_a_n_d_l_e, _g_s_s___b_u_f_f_e_r___t _m_e_s_s_a_g_e___b_u_f_f_e_r, _g_s_s___b_u_f_f_e_r___t _t_o_k_e_n___b_u_f_f_e_r, _i_n_t _* _q_o_p___s_t_a_t_e); _O_M___u_i_n_t_3_2 ggssss__vveerriiffyy__mmiicc(_O_M___u_i_n_t_3_2 _* _m_i_n_o_r___s_t_a_t_u_s, _g_s_s___c_o_n_s_t___c_t_x___i_d___t _c_o_n_t_e_x_t___h_a_n_d_l_e, _c_o_n_s_t _g_s_s___b_u_f_f_e_r___t _m_e_s_s_a_g_e___b_u_f_f_e_r, _c_o_n_s_t _g_s_s___b_u_f_f_e_r___t _t_o_k_e_n___b_u_f_f_e_r, _g_s_s___q_o_p___t _* _q_o_p___s_t_a_t_e); _O_M___u_i_n_t_3_2 ggssss__wwrraapp(_O_M___u_i_n_t_3_2 _* _m_i_n_o_r___s_t_a_t_u_s, _g_s_s___c_o_n_s_t___c_t_x___i_d___t _c_o_n_t_e_x_t___h_a_n_d_l_e, _i_n_t _c_o_n_f___r_e_q___f_l_a_g, _g_s_s___q_o_p___t _q_o_p___r_e_q, _c_o_n_s_t _g_s_s___b_u_f_f_e_r___t _i_n_p_u_t___m_e_s_s_a_g_e___b_u_f_f_e_r, _i_n_t _* _c_o_n_f___s_t_a_t_e, _g_s_s___b_u_f_f_e_r___t _o_u_t_p_u_t___m_e_s_s_a_g_e___b_u_f_f_e_r); _O_M___u_i_n_t_3_2 ggssss__wwrraapp__ssiizzee__lliimmiitt(_O_M___u_i_n_t_3_2 _* _m_i_n_o_r___s_t_a_t_u_s, _g_s_s___c_o_n_s_t___c_t_x___i_d___t _c_o_n_t_e_x_t___h_a_n_d_l_e, _i_n_t _c_o_n_f___r_e_q___f_l_a_g, _g_s_s___q_o_p___t _q_o_p___r_e_q, _O_M___u_i_n_t_3_2 _r_e_q___o_u_t_p_u_t___s_i_z_e, _O_M___u_i_n_t_3_2 _* _m_a_x___i_n_p_u_t___s_i_z_e); DDEESSCCRRIIPPTTIIOONN Generic Security Service API (GSS-API) version 2, and its C binding, is described in RFC2743 and RFC2744. Version 1 (deprecated) of the C bind- ing is described in RFC1509. Heimdals GSS-API implementation supports the following mechanisms ++oo GSS_KRB5_MECHANISM ++oo GSS_SPNEGO_MECHANISM GSS-API have generic name types that all mechanism are supposed to imple- ment (if possible): ++oo GSS_C_NT_USER_NAME ++oo GSS_C_NT_MACHINE_UID_NAME ++oo GSS_C_NT_STRING_UID_NAME ++oo GSS_C_NT_HOSTBASED_SERVICE ++oo GSS_C_NT_ANONYMOUS ++oo GSS_C_NT_EXPORT_NAME GSS-API implementations that supports Kerberos 5 have some additional name types: ++oo GSS_KRB5_NT_PRINCIPAL_NAME ++oo GSS_KRB5_NT_USER_NAME ++oo GSS_KRB5_NT_MACHINE_UID_NAME ++oo GSS_KRB5_NT_STRING_UID_NAME In GSS-API, names have two forms, internal names and contiguous string names. ++oo Internal name and mechanism name Internal names are implementation specific representation of a GSS- API name. Mechanism names special form of internal names corresponds to one and only one mechanism. In GSS-API an internal name is stored in a gss_name_t. ++oo Contiguous string name and exported name Contiguous string names are gssapi names stored in a OCTET STRING that together with a name type identifier (OID) uniquely specifies a gss-name. A special form of the contiguous string name is the exported name that have a OID embedded in the string to make it unique. Exported name have the nametype GSS_C_NT_EXPORT_NAME. In GSS-API an contiguous string name is stored in a gss_buffer_t. Exported names also have the property that they are specified by the mechanism itself and compatible between different GSS-API implementa- tions. AACCCCEESSSS CCOONNTTRROOLL There are two ways of comparing GSS-API names, either comparing two internal names with each other or two contiguous string names with either other. To compare two internal names with each other, import (if needed) the names with ggssss__iimmppoorrtt__nnaammee() into the GSS-API implementation and the com- pare the imported name with ggssss__ccoommppaarree__nnaammee(). Importing names can be slow, so when its possible to store exported names in the access control list, comparing contiguous string name might be better. when comparing contiguous string name, first export them into a GSS_C_NT_EXPORT_NAME name with ggssss__eexxppoorrtt__nnaammee() and then compare with memcmp(3). Note that there are might be a difference between the two methods of com- paring names. The first (using ggssss__ccoommppaarree__nnaammee()) will compare to (unauthenticated) names are the same. The second will compare if a mech- anism will authenticate them as the same principal. For example, if ggssss__iimmppoorrtt__nnaammee() name was used with GSS_C_NO_OID the default syntax is used for all mechanism the GSS-API implementation sup- ports. When compare the imported name of GSS_C_NO_OID it may match sev- eral mechanism names (MN). The resulting name from ggssss__ddiissppllaayy__nnaammee() must not be used for acccess control. FFUUNNCCTTIIOONNSS ggssss__ddiissppllaayy__nnaammee() takes the gss name in _i_n_p_u_t___n_a_m_e and puts a printable form in _o_u_t_p_u_t___n_a_m_e___b_u_f_f_e_r. _o_u_t_p_u_t___n_a_m_e___b_u_f_f_e_r should be freed when done using ggssss__rreelleeaassee__bbuuffffeerr(). _o_u_t_p_u_t___n_a_m_e___t_y_p_e can either be NULL or a pointer to a gss_OID and will in the latter case contain the OID type of the name. The name must only be used for printing. If access control is needed, see section _A_C_C_E_S_S _C_O_N_T_R_O_L. ggssss__iinnqquuiirree__ccoonntteexxtt() returns information about the context. Information is available even after the context have expired. _l_i_f_e_t_i_m_e___r_e_c argument is set to GSS_C_INDEFINITE (don't expire) or the number of seconds that the context is still valid. A value of 0 means that the context is expired. _m_e_c_h___t_y_p_e argument should be considered readonly and must not be released. _s_r_c___n_a_m_e and ddeesstt__nnaammee() are both mechanims names and must be released with ggssss__rreelleeaassee__nnaammee() when no longer used. ggssss__ccoonntteexxtt__ttiimmee will return the amount of time (in seconds) of the con- text is still valid. If its expired _t_i_m_e___r_e_c will be set to 0 and GSS_S_CONTEXT_EXPIRED returned. ggssss__ssiiggnn(), ggssss__vveerriiffyy(), ggssss__sseeaall(), and ggssss__uunnsseeaall() are part of the GSS-API V1 interface and are obsolete. The functions should not be used for new applications. They are provided so that version 1 applications can link against the library. EEXXTTEENNSSIIOONNSS ggssss__kkrrbb55__ccccaacchhee__nnaammee() sets the internal kerberos 5 credential cache name to _n_a_m_e. The old name is returned in _o_l_d___n_a_m_e, and must not be freed. The data allocated for _o_l_d___n_a_m_e is free upon next call to ggssss__kkrrbb55__ccccaacchhee__nnaammee(). This function is not threadsafe if _o_l_d___n_a_m_e argument is used. ggssss__kkrrbb55__ccooppyy__ccccaacchhee() will extract the krb5 credentials that are trans- ferred from the initiator to the acceptor when using token delegation in the Kerberos mechanism. The acceptor receives the delegated token in the last argument to ggssss__aacccceepptt__sseecc__ccoonntteexxtt(). ggssss__kkrrbb55__iimmppoorrtt__ccrreedd() will import the krb5 credentials (both keytab and/or credential cache) into gss credential so it can be used withing GSS-API. The _c_c_a_c_h_e is copied by reference and thus shared, so if the credential is destroyed with _k_r_b_5___c_c___d_e_s_t_r_o_y, all users of thep _g_s_s___c_r_e_d___i_d___t returned by ggssss__kkrrbb55__iimmppoorrtt__ccccaacchhee() will fail. ggsssskkrrbb55__rreeggiisstteerr__aacccceeppttoorr__iiddeennttiittyy() sets the Kerberos 5 filebased keytab that the acceptor will use. The _i_d_e_n_t_i_f_i_e_r is the file name. ggsssskkrrbb55__eexxttrraacctt__aauutthhzz__ddaattaa__ffrroomm__sseecc__ccoonntteexxtt() extracts the Kerberos authorizationdata that may be stored within the context. Tha caller must free the returned buffer _a_d___d_a_t_a with ggssss__rreelleeaassee__bbuuffffeerr() upon success. ggssss__kkrrbb55__ggeett__ttkktt__ffllaaggss() return the ticket flags for the kerberos ticket receive when authenticating the initiator. Only valid on the acceptor context. ggssss__kkrrbb55__ccoommppaatt__ddeess33__mmiicc() turns on or off the compatibility with older version of Heimdal using des3 get and verify mic, this is way to program- matically set the [gssapi]broken_des3_mic and [gssapi]correct_des3_mic flags (see COMPATIBILITY section in gssapi(3)). If the CPP symbol GSS_C_KRB5_COMPAT_DES3_MIC is present, ggssss__kkrrbb55__ccoommppaatt__ddeess33__mmiicc() exists. ggssss__kkrrbb55__ccoommppaatt__ddeess33__mmiicc() will be removed in a later version of the GSS- API library. SSEEEE AALLSSOO gssapi(3), krb5(3), krb5_ccache(3), kerberos(8) HEIMDAL October 26, 2005 HEIMDAL heimdal-7.5.0/lib/gssapi/ntlm/0000755000175000017500000000000013214604041014253 5ustar niknikheimdal-7.5.0/lib/gssapi/ntlm/inquire_sec_context_by_oid.c0000644000175000017500000000567013026237312022032 0ustar niknik/* * Copyright (c) 2006 Kungliga Tekniska Hgskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Portions Copyright (c) 2009 Apple Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "ntlm.h" OM_uint32 GSSAPI_CALLCONV _gss_ntlm_inquire_sec_context_by_oid(OM_uint32 *minor_status, gss_const_ctx_id_t context_handle, const gss_OID desired_object, gss_buffer_set_t *data_set) { ntlm_ctx ctx = (ntlm_ctx)context_handle; if (ctx == NULL) { *minor_status = 0; return GSS_S_NO_CONTEXT; } if (gss_oid_equal(desired_object, GSS_NTLM_GET_SESSION_KEY_X) || gss_oid_equal(desired_object, GSS_C_INQ_SSPI_SESSION_KEY)) { gss_buffer_desc value; value.length = ctx->sessionkey.length; value.value = ctx->sessionkey.data; return gss_add_buffer_set_member(minor_status, &value, data_set); } else if (gss_oid_equal(desired_object, GSS_C_INQ_WIN2K_PAC_X)) { if (ctx->pac.length == 0) { *minor_status = ENOENT; return GSS_S_FAILURE; } return gss_add_buffer_set_member(minor_status, &ctx->pac, data_set); } else if (gss_oid_equal(desired_object, GSS_C_NTLM_AVGUEST)) { gss_buffer_desc value; uint32_t num; if (ctx->kcmflags & KCM_NTLM_FLAG_AV_GUEST) num = 1; else num = 0; value.length = sizeof(num); value.value = # return gss_add_buffer_set_member(minor_status, &value, data_set); } else { *minor_status = 0; return GSS_S_FAILURE; } } heimdal-7.5.0/lib/gssapi/ntlm/accept_sec_context.c0000644000175000017500000001624013026237312020263 0ustar niknik/* * Copyright (c) 2006 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "ntlm.h" /* * */ OM_uint32 _gss_ntlm_allocate_ctx(OM_uint32 *minor_status, ntlm_ctx *ctx) { OM_uint32 maj_stat; struct ntlm_server_interface *ns_interface = NULL; #ifdef DIGEST ns_interface = &ntlmsspi_kdc_digest; #endif if (ns_interface == NULL) return GSS_S_FAILURE; *ctx = calloc(1, sizeof(**ctx)); (*ctx)->server = ns_interface; maj_stat = (*(*ctx)->server->nsi_init)(minor_status, &(*ctx)->ictx); if (maj_stat != GSS_S_COMPLETE) return maj_stat; return GSS_S_COMPLETE; } /* * */ OM_uint32 GSSAPI_CALLCONV _gss_ntlm_accept_sec_context (OM_uint32 * minor_status, gss_ctx_id_t * context_handle, gss_const_cred_id_t acceptor_cred_handle, const gss_buffer_t input_token_buffer, const gss_channel_bindings_t input_chan_bindings, gss_name_t * src_name, gss_OID * mech_type, gss_buffer_t output_token, OM_uint32 * ret_flags, OM_uint32 * time_rec, gss_cred_id_t * delegated_cred_handle ) { krb5_error_code ret; struct ntlm_buf data; OM_uint32 junk; ntlm_ctx ctx; output_token->value = NULL; output_token->length = 0; *minor_status = 0; if (context_handle == NULL) return GSS_S_FAILURE; if (input_token_buffer == GSS_C_NO_BUFFER) return GSS_S_FAILURE; if (src_name) *src_name = GSS_C_NO_NAME; if (mech_type) *mech_type = GSS_C_NO_OID; if (ret_flags) *ret_flags = 0; if (time_rec) *time_rec = 0; if (delegated_cred_handle) *delegated_cred_handle = GSS_C_NO_CREDENTIAL; if (*context_handle == GSS_C_NO_CONTEXT) { struct ntlm_type1 type1; OM_uint32 major_status; OM_uint32 retflags; struct ntlm_buf out; major_status = _gss_ntlm_allocate_ctx(minor_status, &ctx); if (major_status) return major_status; *context_handle = (gss_ctx_id_t)ctx; /* check if the mechs is allowed by remote service */ major_status = (*ctx->server->nsi_probe)(minor_status, ctx->ictx, NULL); if (major_status) { _gss_ntlm_delete_sec_context(minor_status, context_handle, NULL); return major_status; } data.data = input_token_buffer->value; data.length = input_token_buffer->length; ret = heim_ntlm_decode_type1(&data, &type1); if (ret) { _gss_ntlm_delete_sec_context(minor_status, context_handle, NULL); *minor_status = ret; return GSS_S_FAILURE; } if ((type1.flags & NTLM_NEG_UNICODE) == 0) { heim_ntlm_free_type1(&type1); _gss_ntlm_delete_sec_context(minor_status, context_handle, NULL); *minor_status = EINVAL; return GSS_S_FAILURE; } if (type1.flags & NTLM_NEG_SIGN) ctx->gssflags |= GSS_C_CONF_FLAG; if (type1.flags & NTLM_NEG_SIGN) ctx->gssflags |= GSS_C_INTEG_FLAG; major_status = (*ctx->server->nsi_type2)(minor_status, ctx->ictx, type1.flags, type1.hostname, type1.domain, &retflags, &out); heim_ntlm_free_type1(&type1); if (major_status != GSS_S_COMPLETE) { OM_uint32 gunk; _gss_ntlm_delete_sec_context(&gunk, context_handle, NULL); return major_status; } output_token->value = malloc(out.length); if (output_token->value == NULL && out.length != 0) { OM_uint32 gunk; _gss_ntlm_delete_sec_context(&gunk, context_handle, NULL); *minor_status = ENOMEM; return GSS_S_FAILURE; } memcpy(output_token->value, out.data, out.length); output_token->length = out.length; ctx->flags = retflags; return GSS_S_CONTINUE_NEEDED; } else { OM_uint32 maj_stat; struct ntlm_type3 type3; struct ntlm_buf session; ctx = (ntlm_ctx)*context_handle; data.data = input_token_buffer->value; data.length = input_token_buffer->length; ret = heim_ntlm_decode_type3(&data, 1, &type3); if (ret) { _gss_ntlm_delete_sec_context(minor_status, context_handle, NULL); *minor_status = ret; return GSS_S_FAILURE; } maj_stat = (*ctx->server->nsi_type3)(minor_status, ctx->ictx, &type3, &session); if (maj_stat) { heim_ntlm_free_type3(&type3); _gss_ntlm_delete_sec_context(minor_status, context_handle, NULL); return maj_stat; } if (src_name) { ntlm_name n = calloc(1, sizeof(*n)); if (n) { n->user = strdup(type3.username); n->domain = strdup(type3.targetname); } if (n == NULL || n->user == NULL || n->domain == NULL) { gss_name_t tempn = (gss_name_t)n; _gss_ntlm_release_name(&junk, &tempn); heim_ntlm_free_type3(&type3); _gss_ntlm_delete_sec_context(minor_status, context_handle, NULL); return maj_stat; } *src_name = (gss_name_t)n; } heim_ntlm_free_type3(&type3); ret = krb5_data_copy(&ctx->sessionkey, session.data, session.length); if (ret) { if (src_name) _gss_ntlm_release_name(&junk, src_name); _gss_ntlm_delete_sec_context(minor_status, context_handle, NULL); *minor_status = ret; return GSS_S_FAILURE; } if (session.length != 0) { ctx->status |= STATUS_SESSIONKEY; if (ctx->flags & NTLM_NEG_NTLM2_SESSION) { _gss_ntlm_set_key(&ctx->u.v2.send, 1, (ctx->flags & NTLM_NEG_KEYEX), ctx->sessionkey.data, ctx->sessionkey.length); _gss_ntlm_set_key(&ctx->u.v2.recv, 0, (ctx->flags & NTLM_NEG_KEYEX), ctx->sessionkey.data, ctx->sessionkey.length); } else { RC4_set_key(&ctx->u.v1.crypto_send.key, ctx->sessionkey.length, ctx->sessionkey.data); RC4_set_key(&ctx->u.v1.crypto_recv.key, ctx->sessionkey.length, ctx->sessionkey.data); } } if (mech_type) *mech_type = GSS_NTLM_MECHANISM; if (time_rec) *time_rec = GSS_C_INDEFINITE; ctx->status |= STATUS_OPEN; if (ret_flags) *ret_flags = ctx->gssflags; return GSS_S_COMPLETE; } } heimdal-7.5.0/lib/gssapi/ntlm/crypto.c0000644000175000017500000003420613026237312015750 0ustar niknik/* * Copyright (c) 2006-2016 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "ntlm.h" struct hx509_certs_data; struct krb5_pk_identity; struct krb5_pk_cert; struct ContentInfo; struct AlgorithmIdentifier; struct _krb5_krb_auth_data; struct krb5_dh_moduli; struct _krb5_key_data; struct _krb5_encryption_type; struct _krb5_key_type; #include "krb5_locl.h" /* * */ static void encode_le_uint32(uint32_t n, unsigned char *p) { p[0] = (n >> 0) & 0xFF; p[1] = (n >> 8) & 0xFF; p[2] = (n >> 16) & 0xFF; p[3] = (n >> 24) & 0xFF; } static void decode_le_uint32(const void *ptr, uint32_t *n) { const unsigned char *p = ptr; *n = (p[0] << 0) | (p[1] << 8) | (p[2] << 16) | (p[3] << 24); } /* * */ const char a2i_signmagic[] = "session key to server-to-client signing key magic constant"; const char a2i_sealmagic[] = "session key to server-to-client sealing key magic constant"; const char i2a_signmagic[] = "session key to client-to-server signing key magic constant"; const char i2a_sealmagic[] = "session key to client-to-server sealing key magic constant"; void _gss_ntlm_set_key(struct ntlmv2_key *key, int acceptor, int sealsign, unsigned char *data, size_t len) { unsigned char out[16]; EVP_MD_CTX *ctx; const char *signmagic; const char *sealmagic; if (acceptor) { signmagic = a2i_signmagic; sealmagic = a2i_sealmagic; } else { signmagic = i2a_signmagic; sealmagic = i2a_sealmagic; } key->seq = 0; ctx = EVP_MD_CTX_create(); EVP_DigestInit_ex(ctx, EVP_md5(), NULL); EVP_DigestUpdate(ctx, data, len); EVP_DigestUpdate(ctx, signmagic, strlen(signmagic) + 1); EVP_DigestFinal_ex(ctx, key->signkey, NULL); EVP_DigestInit_ex(ctx, EVP_md5(), NULL); EVP_DigestUpdate(ctx, data, len); EVP_DigestUpdate(ctx, sealmagic, strlen(sealmagic) + 1); EVP_DigestFinal_ex(ctx, out, NULL); EVP_MD_CTX_destroy(ctx); RC4_set_key(&key->sealkey, 16, out); if (sealsign) key->signsealkey = &key->sealkey; } /* * */ static OM_uint32 v1_sign_message(gss_buffer_t in, RC4_KEY *signkey, uint32_t seq, unsigned char out[16]) { unsigned char sigature[12]; uint32_t crc; _krb5_crc_init_table(); crc = _krb5_crc_update(in->value, in->length, 0); encode_le_uint32(0, &sigature[0]); encode_le_uint32(crc, &sigature[4]); encode_le_uint32(seq, &sigature[8]); encode_le_uint32(1, out); /* version */ RC4(signkey, sizeof(sigature), sigature, out + 4); if (RAND_bytes(out + 4, 4) != 1) return GSS_S_UNAVAILABLE; return 0; } static OM_uint32 v2_sign_message(gss_buffer_t in, unsigned char signkey[16], RC4_KEY *sealkey, uint32_t seq, unsigned char out[16]) { unsigned char hmac[16]; unsigned int hmaclen; HMAC_CTX c; HMAC_CTX_init(&c); HMAC_Init_ex(&c, signkey, 16, EVP_md5(), NULL); encode_le_uint32(seq, hmac); HMAC_Update(&c, hmac, 4); HMAC_Update(&c, in->value, in->length); HMAC_Final(&c, hmac, &hmaclen); HMAC_CTX_cleanup(&c); encode_le_uint32(1, &out[0]); if (sealkey) RC4(sealkey, 8, hmac, &out[4]); else memcpy(&out[4], hmac, 8); memset(&out[12], 0, 4); return GSS_S_COMPLETE; } static OM_uint32 v2_verify_message(gss_buffer_t in, unsigned char signkey[16], RC4_KEY *sealkey, uint32_t seq, const unsigned char checksum[16]) { OM_uint32 ret; unsigned char out[16]; ret = v2_sign_message(in, signkey, sealkey, seq, out); if (ret) return ret; if (memcmp(checksum, out, 16) != 0) return GSS_S_BAD_MIC; return GSS_S_COMPLETE; } static OM_uint32 v2_seal_message(const gss_buffer_t in, unsigned char signkey[16], uint32_t seq, RC4_KEY *sealkey, gss_buffer_t out) { unsigned char *p; OM_uint32 ret; if (in->length + 16 < in->length) return EINVAL; p = malloc(in->length + 16); if (p == NULL) return ENOMEM; RC4(sealkey, in->length, in->value, p); ret = v2_sign_message(in, signkey, sealkey, seq, &p[in->length]); if (ret) { free(p); return ret; } out->value = p; out->length = in->length + 16; return 0; } static OM_uint32 v2_unseal_message(gss_buffer_t in, unsigned char signkey[16], uint32_t seq, RC4_KEY *sealkey, gss_buffer_t out) { OM_uint32 ret; if (in->length < 16) return GSS_S_BAD_MIC; out->length = in->length - 16; out->value = malloc(out->length); if (out->value == NULL) return GSS_S_BAD_MIC; RC4(sealkey, out->length, in->value, out->value); ret = v2_verify_message(out, signkey, sealkey, seq, ((const unsigned char *)in->value) + out->length); if (ret) { OM_uint32 junk; gss_release_buffer(&junk, out); } return ret; } /* * */ #define CTX_FLAGS_ISSET(_ctx,_flags) \ (((_ctx)->flags & (_flags)) == (_flags)) /* * */ OM_uint32 GSSAPI_CALLCONV _gss_ntlm_get_mic (OM_uint32 * minor_status, gss_const_ctx_id_t context_handle, gss_qop_t qop_req, const gss_buffer_t message_buffer, gss_buffer_t message_token ) { ntlm_ctx ctx = (ntlm_ctx)context_handle; OM_uint32 junk; *minor_status = 0; message_token->value = malloc(16); message_token->length = 16; if (message_token->value == NULL) { *minor_status = ENOMEM; return GSS_S_FAILURE; } if (CTX_FLAGS_ISSET(ctx, NTLM_NEG_SIGN|NTLM_NEG_NTLM2_SESSION)) { OM_uint32 ret; if ((ctx->status & STATUS_SESSIONKEY) == 0) { gss_release_buffer(&junk, message_token); return GSS_S_UNAVAILABLE; } ret = v2_sign_message(message_buffer, ctx->u.v2.send.signkey, ctx->u.v2.send.signsealkey, ctx->u.v2.send.seq++, message_token->value); if (ret) gss_release_buffer(&junk, message_token); return ret; } else if (CTX_FLAGS_ISSET(ctx, NTLM_NEG_SIGN)) { OM_uint32 ret; if ((ctx->status & STATUS_SESSIONKEY) == 0) { gss_release_buffer(&junk, message_token); return GSS_S_UNAVAILABLE; } ret = v1_sign_message(message_buffer, &ctx->u.v1.crypto_send.key, ctx->u.v1.crypto_send.seq++, message_token->value); if (ret) gss_release_buffer(&junk, message_token); return ret; } else if (CTX_FLAGS_ISSET(ctx, NTLM_NEG_ALWAYS_SIGN)) { unsigned char *sigature; sigature = message_token->value; encode_le_uint32(1, &sigature[0]); /* version */ encode_le_uint32(0, &sigature[4]); encode_le_uint32(0, &sigature[8]); encode_le_uint32(0, &sigature[12]); return GSS_S_COMPLETE; } gss_release_buffer(&junk, message_token); return GSS_S_UNAVAILABLE; } /* * */ OM_uint32 GSSAPI_CALLCONV _gss_ntlm_verify_mic (OM_uint32 * minor_status, gss_const_ctx_id_t context_handle, const gss_buffer_t message_buffer, const gss_buffer_t token_buffer, gss_qop_t * qop_state ) { ntlm_ctx ctx = (ntlm_ctx)context_handle; if (qop_state != NULL) *qop_state = GSS_C_QOP_DEFAULT; *minor_status = 0; if (token_buffer->length != 16) return GSS_S_BAD_MIC; if (CTX_FLAGS_ISSET(ctx, NTLM_NEG_SIGN|NTLM_NEG_NTLM2_SESSION)) { OM_uint32 ret; if ((ctx->status & STATUS_SESSIONKEY) == 0) return GSS_S_UNAVAILABLE; ret = v2_verify_message(message_buffer, ctx->u.v2.recv.signkey, ctx->u.v2.recv.signsealkey, ctx->u.v2.recv.seq++, token_buffer->value); if (ret) return ret; return GSS_S_COMPLETE; } else if (CTX_FLAGS_ISSET(ctx, NTLM_NEG_SIGN)) { unsigned char sigature[12]; uint32_t crc, num; if ((ctx->status & STATUS_SESSIONKEY) == 0) return GSS_S_UNAVAILABLE; decode_le_uint32(token_buffer->value, &num); if (num != 1) return GSS_S_BAD_MIC; RC4(&ctx->u.v1.crypto_recv.key, sizeof(sigature), ((unsigned char *)token_buffer->value) + 4, sigature); _krb5_crc_init_table(); crc = _krb5_crc_update(message_buffer->value, message_buffer->length, 0); /* skip first 4 bytes in the encrypted checksum */ decode_le_uint32(&sigature[4], &num); if (num != crc) return GSS_S_BAD_MIC; decode_le_uint32(&sigature[8], &num); if (ctx->u.v1.crypto_recv.seq != num) return GSS_S_BAD_MIC; ctx->u.v1.crypto_recv.seq++; return GSS_S_COMPLETE; } else if (ctx->flags & NTLM_NEG_ALWAYS_SIGN) { uint32_t num; unsigned char *p; p = (unsigned char*)(token_buffer->value); decode_le_uint32(&p[0], &num); /* version */ if (num != 1) return GSS_S_BAD_MIC; decode_le_uint32(&p[4], &num); if (num != 0) return GSS_S_BAD_MIC; decode_le_uint32(&p[8], &num); if (num != 0) return GSS_S_BAD_MIC; decode_le_uint32(&p[12], &num); if (num != 0) return GSS_S_BAD_MIC; return GSS_S_COMPLETE; } return GSS_S_UNAVAILABLE; } /* * */ OM_uint32 GSSAPI_CALLCONV _gss_ntlm_wrap_size_limit ( OM_uint32 * minor_status, gss_const_ctx_id_t context_handle, int conf_req_flag, gss_qop_t qop_req, OM_uint32 req_output_size, OM_uint32 * max_input_size ) { ntlm_ctx ctx = (ntlm_ctx)context_handle; *minor_status = 0; if(ctx->flags & NTLM_NEG_SEAL) { if (req_output_size < 16) *max_input_size = 0; else *max_input_size = req_output_size - 16; return GSS_S_COMPLETE; } return GSS_S_UNAVAILABLE; } /* * */ OM_uint32 GSSAPI_CALLCONV _gss_ntlm_wrap (OM_uint32 * minor_status, gss_const_ctx_id_t context_handle, int conf_req_flag, gss_qop_t qop_req, const gss_buffer_t input_message_buffer, int * conf_state, gss_buffer_t output_message_buffer ) { ntlm_ctx ctx = (ntlm_ctx)context_handle; OM_uint32 ret; *minor_status = 0; if (conf_state) *conf_state = 0; if (output_message_buffer == GSS_C_NO_BUFFER) return GSS_S_FAILURE; if (CTX_FLAGS_ISSET(ctx, NTLM_NEG_SEAL|NTLM_NEG_NTLM2_SESSION)) { return v2_seal_message(input_message_buffer, ctx->u.v2.send.signkey, ctx->u.v2.send.seq++, &ctx->u.v2.send.sealkey, output_message_buffer); } else if (CTX_FLAGS_ISSET(ctx, NTLM_NEG_SEAL)) { gss_buffer_desc trailer; OM_uint32 junk; output_message_buffer->length = input_message_buffer->length + 16; output_message_buffer->value = malloc(output_message_buffer->length); if (output_message_buffer->value == NULL) { output_message_buffer->length = 0; return GSS_S_FAILURE; } RC4(&ctx->u.v1.crypto_send.key, input_message_buffer->length, input_message_buffer->value, output_message_buffer->value); ret = _gss_ntlm_get_mic(minor_status, context_handle, 0, input_message_buffer, &trailer); if (ret) { gss_release_buffer(&junk, output_message_buffer); return ret; } if (trailer.length != 16) { gss_release_buffer(&junk, output_message_buffer); gss_release_buffer(&junk, &trailer); return GSS_S_FAILURE; } memcpy(((unsigned char *)output_message_buffer->value) + input_message_buffer->length, trailer.value, trailer.length); gss_release_buffer(&junk, &trailer); return GSS_S_COMPLETE; } return GSS_S_UNAVAILABLE; } /* * */ OM_uint32 GSSAPI_CALLCONV _gss_ntlm_unwrap (OM_uint32 * minor_status, gss_const_ctx_id_t context_handle, const gss_buffer_t input_message_buffer, gss_buffer_t output_message_buffer, int * conf_state, gss_qop_t * qop_state ) { ntlm_ctx ctx = (ntlm_ctx)context_handle; OM_uint32 ret; *minor_status = 0; output_message_buffer->value = NULL; output_message_buffer->length = 0; if (conf_state) *conf_state = 0; if (qop_state) *qop_state = 0; if (CTX_FLAGS_ISSET(ctx, NTLM_NEG_SEAL|NTLM_NEG_NTLM2_SESSION)) { return v2_unseal_message(input_message_buffer, ctx->u.v2.recv.signkey, ctx->u.v2.recv.seq++, &ctx->u.v2.recv.sealkey, output_message_buffer); } else if (CTX_FLAGS_ISSET(ctx, NTLM_NEG_SEAL)) { gss_buffer_desc trailer; OM_uint32 junk; if (input_message_buffer->length < 16) return GSS_S_BAD_MIC; output_message_buffer->length = input_message_buffer->length - 16; output_message_buffer->value = malloc(output_message_buffer->length); if (output_message_buffer->value == NULL) { output_message_buffer->length = 0; return GSS_S_FAILURE; } RC4(&ctx->u.v1.crypto_recv.key, output_message_buffer->length, input_message_buffer->value, output_message_buffer->value); trailer.value = ((unsigned char *)input_message_buffer->value) + output_message_buffer->length; trailer.length = 16; ret = _gss_ntlm_verify_mic(minor_status, context_handle, output_message_buffer, &trailer, NULL); if (ret) { gss_release_buffer(&junk, output_message_buffer); return ret; } return GSS_S_COMPLETE; } return GSS_S_UNAVAILABLE; } heimdal-7.5.0/lib/gssapi/ntlm/display_name.c0000644000175000017500000000464713026237312017103 0ustar niknik/* * Copyright (c) 1997 - 2003 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "ntlm.h" OM_uint32 GSSAPI_CALLCONV _gss_ntlm_display_name (OM_uint32 * minor_status, gss_const_name_t input_name, gss_buffer_t output_name_buffer, gss_OID * output_name_type ) { *minor_status = 0; if (output_name_type) *output_name_type = GSS_NTLM_MECHANISM; if (output_name_buffer) { ntlm_name n = (ntlm_name)input_name; char *str = NULL; int len; output_name_buffer->length = 0; output_name_buffer->value = NULL; if (n == NULL) { *minor_status = 0; return GSS_S_BAD_NAME; } len = asprintf(&str, "%s@%s", n->user, n->domain); if (len < 0 || str == NULL) { *minor_status = ENOMEM; return GSS_S_FAILURE; } output_name_buffer->length = len; output_name_buffer->value = str; } return GSS_S_COMPLETE; } heimdal-7.5.0/lib/gssapi/ntlm/inquire_names_for_mech.c0000644000175000017500000000375112136107747021143 0ustar niknik/* * Copyright (c) 2006 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "ntlm.h" OM_uint32 GSSAPI_CALLCONV _gss_ntlm_inquire_names_for_mech ( OM_uint32 * minor_status, const gss_OID mechanism, gss_OID_set * name_types ) { OM_uint32 ret; ret = gss_create_empty_oid_set(minor_status, name_types); if (ret != GSS_S_COMPLETE) return ret; *minor_status = 0; return GSS_S_COMPLETE; } heimdal-7.5.0/lib/gssapi/ntlm/delete_sec_context.c0000644000175000017500000000441612136107747020301 0ustar niknik/* * Copyright (c) 1997 - 2003 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "ntlm.h" OM_uint32 GSSAPI_CALLCONV _gss_ntlm_delete_sec_context (OM_uint32 * minor_status, gss_ctx_id_t * context_handle, gss_buffer_t output_token ) { if (context_handle) { ntlm_ctx ctx = (ntlm_ctx)*context_handle; gss_cred_id_t cred = (gss_cred_id_t)ctx->client; *context_handle = GSS_C_NO_CONTEXT; if (ctx->server) (*ctx->server->nsi_destroy)(minor_status, ctx->ictx); _gss_ntlm_release_cred(NULL, &cred); memset(ctx, 0, sizeof(*ctx)); free(ctx); } if (output_token) { output_token->length = 0; output_token->value = NULL; } *minor_status = 0; return GSS_S_COMPLETE; } heimdal-7.5.0/lib/gssapi/ntlm/iter_cred.c0000644000175000017500000000574513026237312016376 0ustar niknik/* * Copyright (c) 2006 Kungliga Tekniska Hgskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Portions Copyright (c) 2009 Apple Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "ntlm.h" void GSSAPI_CALLCONV _gss_ntlm_iter_creds_f(OM_uint32 flags, void *userctx , void (*cred_iter)(void *, gss_OID, gss_cred_id_t)) { #ifdef HAVE_KCM krb5_error_code ret; krb5_context context = NULL; krb5_storage *request, *response; krb5_data response_data; ret = krb5_init_context(&context); if (ret) goto done; ret = krb5_kcm_storage_request(context, KCM_OP_GET_NTLM_USER_LIST, &request); if (ret) goto done; ret = krb5_kcm_call(context, request, &response, &response_data); krb5_storage_free(request); if (ret) goto done; while (1) { uint32_t morep; char *user = NULL, *domain = NULL; ntlm_cred dn; ret = krb5_ret_uint32(response, &morep); if (ret) goto out; if (!morep) goto out; ret = krb5_ret_stringz(response, &user); if (ret) goto out; ret = krb5_ret_stringz(response, &domain); if (ret) { free(user); goto out; } dn = calloc(1, sizeof(*dn)); if (dn == NULL) { free(user); free(domain); goto out; } dn->username = user; dn->domain = domain; cred_iter(userctx, GSS_NTLM_MECHANISM, (gss_cred_id_t)dn); } out: krb5_storage_free(response); krb5_data_free(&response_data); done: if (context) krb5_free_context(context); #endif /* HAVE_KCM */ (*cred_iter)(userctx, NULL, NULL); } heimdal-7.5.0/lib/gssapi/ntlm/export_name.c0000644000175000017500000000373413026237312016753 0ustar niknik/* * Copyright (c) 1997, 1999, 2003 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "ntlm.h" OM_uint32 GSSAPI_CALLCONV _gss_ntlm_export_name (OM_uint32 * minor_status, gss_const_name_t input_name, gss_buffer_t exported_name ) { if (minor_status) *minor_status = 0; if (exported_name) { exported_name->length = 0; exported_name->value = NULL; } return GSS_S_COMPLETE; } heimdal-7.5.0/lib/gssapi/ntlm/acquire_cred.c0000644000175000017500000000621113026237312017051 0ustar niknik/* * Copyright (c) 1997 - 2004 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "ntlm.h" OM_uint32 GSSAPI_CALLCONV _gss_ntlm_acquire_cred(OM_uint32 *min_stat, gss_const_name_t desired_name, OM_uint32 time_req, const gss_OID_set desired_mechs, gss_cred_usage_t cred_usage, gss_cred_id_t *output_cred_handle, gss_OID_set *actual_mechs, OM_uint32 *time_rec) { ntlm_name name = (ntlm_name) desired_name; const char *domain = NULL; OM_uint32 maj_stat; ntlm_ctx ctx; *min_stat = 0; *output_cred_handle = GSS_C_NO_CREDENTIAL; if (actual_mechs) *actual_mechs = GSS_C_NO_OID_SET; if (time_rec) *time_rec = GSS_C_INDEFINITE; if (cred_usage == GSS_C_BOTH || cred_usage == GSS_C_ACCEPT) { maj_stat = _gss_ntlm_allocate_ctx(min_stat, &ctx); if (maj_stat != GSS_S_COMPLETE) return maj_stat; domain = name != NULL ? name->domain : NULL; maj_stat = (*ctx->server->nsi_probe)(min_stat, ctx->ictx, domain); { gss_ctx_id_t context = (gss_ctx_id_t)ctx; OM_uint32 junk; _gss_ntlm_delete_sec_context(&junk, &context, NULL); } if (maj_stat) return maj_stat; } if (cred_usage == GSS_C_BOTH || cred_usage == GSS_C_INITIATE) { ntlm_cred cred; *min_stat = _gss_ntlm_get_user_cred(name, &cred); if (*min_stat) return GSS_S_NO_CRED; cred->usage = cred_usage; *output_cred_handle = (gss_cred_id_t)cred; } return (GSS_S_COMPLETE); } heimdal-7.5.0/lib/gssapi/ntlm/external.c0000644000175000017500000000675613026237312016263 0ustar niknik/* * Copyright (c) 2006 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "ntlm.h" static gss_mo_desc ntlm_mo[] = { { GSS_C_MA_SASL_MECH_NAME, GSS_MO_MA, "SASL mech name", rk_UNCONST("NTLM"), _gss_mo_get_ctx_as_string, NULL }, { GSS_C_MA_MECH_NAME, GSS_MO_MA, "Mechanism name", rk_UNCONST("NTLMSPP"), _gss_mo_get_ctx_as_string, NULL }, { GSS_C_MA_MECH_DESCRIPTION, GSS_MO_MA, "Mechanism description", rk_UNCONST("Heimdal NTLMSSP Mechanism"), _gss_mo_get_ctx_as_string, NULL } }; static gssapi_mech_interface_desc ntlm_mech = { GMI_VERSION, "ntlm", {10, rk_UNCONST("\x2b\x06\x01\x04\x01\x82\x37\x02\x02\x0a") }, 0, _gss_ntlm_acquire_cred, _gss_ntlm_release_cred, _gss_ntlm_init_sec_context, _gss_ntlm_accept_sec_context, _gss_ntlm_process_context_token, _gss_ntlm_delete_sec_context, _gss_ntlm_context_time, _gss_ntlm_get_mic, _gss_ntlm_verify_mic, _gss_ntlm_wrap, _gss_ntlm_unwrap, _gss_ntlm_display_status, NULL, _gss_ntlm_compare_name, _gss_ntlm_display_name, _gss_ntlm_import_name, _gss_ntlm_export_name, _gss_ntlm_release_name, _gss_ntlm_inquire_cred, _gss_ntlm_inquire_context, _gss_ntlm_wrap_size_limit, _gss_ntlm_add_cred, _gss_ntlm_inquire_cred_by_mech, _gss_ntlm_export_sec_context, _gss_ntlm_import_sec_context, _gss_ntlm_inquire_names_for_mech, _gss_ntlm_inquire_mechs_for_name, _gss_ntlm_canonicalize_name, _gss_ntlm_duplicate_name, _gss_ntlm_inquire_sec_context_by_oid, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, _gss_ntlm_iter_creds_f, _gss_ntlm_destroy_cred, NULL, NULL, NULL, NULL, ntlm_mo, sizeof(ntlm_mo) / sizeof(ntlm_mo[0]), NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, }; gssapi_mech_interface __gss_ntlm_initialize(void) { return &ntlm_mech; } heimdal-7.5.0/lib/gssapi/ntlm/add_cred.c0000644000175000017500000000465613026237312016163 0ustar niknik/* * Copyright (c) 2006 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "ntlm.h" OM_uint32 GSSAPI_CALLCONV _gss_ntlm_add_cred ( OM_uint32 *minor_status, gss_const_cred_id_t input_cred_handle, gss_const_name_t desired_name, const gss_OID desired_mech, gss_cred_usage_t cred_usage, OM_uint32 initiator_time_req, OM_uint32 acceptor_time_req, gss_cred_id_t *output_cred_handle, gss_OID_set *actual_mechs, OM_uint32 *initiator_time_rec, OM_uint32 *acceptor_time_rec) { if (minor_status) *minor_status = 0; if (output_cred_handle) *output_cred_handle = GSS_C_NO_CREDENTIAL; if (actual_mechs) *actual_mechs = GSS_C_NO_OID_SET; if (initiator_time_rec) *initiator_time_rec = 0; if (acceptor_time_rec) *acceptor_time_rec = 0; return GSS_S_COMPLETE; } heimdal-7.5.0/lib/gssapi/ntlm/process_context_token.c0000644000175000017500000000353213026237312021050 0ustar niknik/* * Copyright (c) 2006 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "ntlm.h" OM_uint32 GSSAPI_CALLCONV _gss_ntlm_process_context_token ( OM_uint32 *minor_status, gss_const_ctx_id_t context_handle, const gss_buffer_t token_buffer ) { *minor_status = 0; return GSS_S_COMPLETE; } heimdal-7.5.0/lib/gssapi/ntlm/duplicate_name.c0000644000175000017500000000363413026237312017403 0ustar niknik/* * Copyright (c) 2006 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "ntlm.h" OM_uint32 GSSAPI_CALLCONV _gss_ntlm_duplicate_name ( OM_uint32 * minor_status, gss_const_name_t src_name, gss_name_t * dest_name ) { if (minor_status) *minor_status = 0; if (dest_name) *dest_name = NULL; return GSS_S_COMPLETE; } heimdal-7.5.0/lib/gssapi/ntlm/ntlm.h0000644000175000017500000000731313026237312015406 0ustar niknik/* * Copyright (c) 2006 - 2007 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ /* $Id$ */ #ifndef NTLM_NTLM_H #define NTLM_NTLM_H #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #define HC_DEPRECATED_CRYPTO #include "crypto-headers.h" typedef OM_uint32 (*ntlm_interface_init)(OM_uint32 *, void **); typedef OM_uint32 (*ntlm_interface_destroy)(OM_uint32 *, void *); typedef int (*ntlm_interface_probe)(OM_uint32 *, void *, const char *); typedef OM_uint32 (*ntlm_interface_type2)(OM_uint32 *, void *, uint32_t, const char *, const char *, uint32_t *, struct ntlm_buf *); typedef OM_uint32 (*ntlm_interface_type3)(OM_uint32 *, void *, const struct ntlm_type3 *, struct ntlm_buf *); typedef void (*ntlm_interface_free_buffer)(struct ntlm_buf *); struct ntlm_server_interface { ntlm_interface_init nsi_init; ntlm_interface_destroy nsi_destroy; ntlm_interface_probe nsi_probe; ntlm_interface_type2 nsi_type2; ntlm_interface_type3 nsi_type3; ntlm_interface_free_buffer nsi_free_buffer; }; struct ntlmv2_key { uint32_t seq; RC4_KEY sealkey; RC4_KEY *signsealkey; unsigned char signkey[16]; }; extern struct ntlm_server_interface ntlmsspi_kdc_digest; typedef struct ntlm_cred { gss_cred_usage_t usage; char *username; char *domain; struct ntlm_buf key; } *ntlm_cred; typedef struct { struct ntlm_server_interface *server; void *ictx; ntlm_cred client; OM_uint32 gssflags; uint32_t kcmflags; uint32_t flags; uint32_t status; #define STATUS_OPEN 1 #define STATUS_CLIENT 2 #define STATUS_SESSIONKEY 4 krb5_data sessionkey; gss_buffer_desc pac; union { struct { struct { uint32_t seq; RC4_KEY key; } crypto_send, crypto_recv; } v1; struct { struct ntlmv2_key send, recv; } v2; } u; } *ntlm_ctx; typedef struct { char *user; char *domain; } *ntlm_name; #include #endif /* NTLM_NTLM_H */ heimdal-7.5.0/lib/gssapi/ntlm/inquire_context.c0000644000175000017500000000501413026237312017643 0ustar niknik/* * Copyright (c) 2006 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "ntlm.h" OM_uint32 GSSAPI_CALLCONV _gss_ntlm_inquire_context ( OM_uint32 * minor_status, gss_const_ctx_id_t context_handle, gss_name_t * src_name, gss_name_t * targ_name, OM_uint32 * lifetime_rec, gss_OID * mech_type, OM_uint32 * ctx_flags, int * locally_initiated, int * open_context ) { ntlm_ctx ctx = (ntlm_ctx)context_handle; *minor_status = 0; if (src_name) *src_name = GSS_C_NO_NAME; if (targ_name) *targ_name = GSS_C_NO_NAME; if (lifetime_rec) *lifetime_rec = GSS_C_INDEFINITE; if (mech_type) *mech_type = GSS_NTLM_MECHANISM; if (ctx_flags) *ctx_flags = ctx->gssflags; if (locally_initiated) *locally_initiated = (ctx->status & STATUS_CLIENT) ? 1 : 0; if (open_context) *open_context = (ctx->status & STATUS_OPEN) ? 1 : 0; return GSS_S_COMPLETE; } heimdal-7.5.0/lib/gssapi/ntlm/import_sec_context.c0000644000175000017500000000366012136107747020351 0ustar niknik/* * Copyright (c) 1999 - 2003 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "ntlm.h" OM_uint32 GSSAPI_CALLCONV _gss_ntlm_import_sec_context ( OM_uint32 * minor_status, const gss_buffer_t interprocess_token, gss_ctx_id_t * context_handle ) { if (minor_status) *minor_status = 0; if (context_handle) *context_handle = GSS_C_NO_CONTEXT; return GSS_S_FAILURE; } heimdal-7.5.0/lib/gssapi/ntlm/inquire_mechs_for_name.c0000644000175000017500000000366613026237312021137 0ustar niknik/* * Copyright (c) 2006 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "ntlm.h" OM_uint32 GSSAPI_CALLCONV _gss_ntlm_inquire_mechs_for_name ( OM_uint32 * minor_status, gss_const_name_t input_name, gss_OID_set * mech_types ) { if (minor_status) *minor_status = 0; if (mech_types) *mech_types = GSS_C_NO_OID_SET; return GSS_S_COMPLETE; } heimdal-7.5.0/lib/gssapi/ntlm/display_status.c0000644000175000017500000000410712136107747017506 0ustar niknik/* * Copyright (c) 1998 - 2005 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "ntlm.h" OM_uint32 GSSAPI_CALLCONV _gss_ntlm_display_status (OM_uint32 *minor_status, OM_uint32 status_value, int status_type, const gss_OID mech_type, OM_uint32 *message_context, gss_buffer_t status_string) { if (minor_status) *minor_status = 0; if (status_string) { status_string->length = 0; status_string->value = NULL; } if (message_context) *message_context = 0; return GSS_S_COMPLETE; } heimdal-7.5.0/lib/gssapi/ntlm/release_name.c0000644000175000017500000000373712136107747017066 0ustar niknik/* * Copyright (c) 1997 - 2003 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "ntlm.h" OM_uint32 GSSAPI_CALLCONV _gss_ntlm_release_name (OM_uint32 * minor_status, gss_name_t * input_name ) { if (minor_status) *minor_status = 0; if (input_name) { ntlm_name n = (ntlm_name)*input_name; *input_name = GSS_C_NO_NAME; free(n->user); free(n->domain); free(n); } return GSS_S_COMPLETE; } heimdal-7.5.0/lib/gssapi/ntlm/init_sec_context.c0000644000175000017500000003230313212137553017770 0ustar niknik/* * Copyright (c) 2006 - 2008 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "ntlm.h" static int from_file(const char *fn, const char *target_domain, char **domainp, char **usernamep, struct ntlm_buf *key) { char *str, buf[1024]; FILE *f; *domainp = NULL; f = fopen(fn, "r"); if (f == NULL) return ENOENT; rk_cloexec_file(f); while (fgets(buf, sizeof(buf), f) != NULL) { char *d, *u, *p; buf[strcspn(buf, "\r\n")] = '\0'; if (buf[0] == '#') continue; str = NULL; d = strtok_r(buf, ":", &str); free(*domainp); *domainp = NULL; if (d && target_domain != NULL && strcasecmp(target_domain, d) != 0) continue; *domainp = strdup(d); if (*domainp == NULL) return ENOMEM; u = strtok_r(NULL, ":", &str); p = strtok_r(NULL, ":", &str); if (u == NULL || p == NULL) continue; *usernamep = strdup(u); if (*usernamep == NULL) return ENOMEM; heim_ntlm_nt_key(p, key); memset(buf, 0, sizeof(buf)); fclose(f); return 0; } memset(buf, 0, sizeof(buf)); fclose(f); return ENOENT; } static int get_user_file(const ntlm_name target_name, char **domainp, char **usernamep, struct ntlm_buf *key) { const char *domain; const char *fn; *domainp = NULL; if (issuid()) return ENOENT; domain = target_name != NULL ? target_name->domain : NULL; fn = getenv("NTLM_USER_FILE"); if (fn == NULL) return ENOENT; if (from_file(fn, domain, domainp, usernamep, key) == 0) return 0; return ENOENT; } /* * Pick up the ntlm cred from the default krb5 credential cache. */ static int get_user_ccache(const ntlm_name name, char **domainp, char **usernamep, struct ntlm_buf *key) { krb5_context context = NULL; krb5_principal client; krb5_ccache id = NULL; krb5_error_code ret; char *confname; krb5_data data; int aret; *domainp = NULL; *usernamep = NULL; krb5_data_zero(&data); key->length = 0; key->data = NULL; ret = krb5_init_context(&context); if (ret) return ret; ret = krb5_cc_default(context, &id); if (ret) goto out; ret = krb5_cc_get_principal(context, id, &client); if (ret) goto out; ret = krb5_unparse_name_flags(context, client, KRB5_PRINCIPAL_UNPARSE_NO_REALM, usernamep); krb5_free_principal(context, client); if (ret) goto out; if (name != NULL) { *domainp = strdup(name->domain); } else { krb5_data data_domain; krb5_data_zero(&data_domain); ret = krb5_cc_get_config(context, id, NULL, "default-ntlm-domain", &data_domain); if (ret) goto out; *domainp = strndup(data_domain.data, data_domain.length); krb5_data_free(&data_domain); } if (*domainp == NULL) { ret = krb5_enomem(context); goto out; } aret = asprintf(&confname, "ntlm-key-%s", *domainp); if (aret == -1) { ret = krb5_enomem(context); goto out; } ret = krb5_cc_get_config(context, id, NULL, confname, &data); if (ret) goto out; key->data = malloc(data.length); if (key->data == NULL) { ret = ENOMEM; goto out; } key->length = data.length; memcpy(key->data, data.data, data.length); out: krb5_data_free(&data); if (id) krb5_cc_close(context, id); krb5_free_context(context); return ret; } int _gss_ntlm_get_user_cred(const ntlm_name target_name, ntlm_cred *rcred) { ntlm_cred cred; int ret; cred = calloc(1, sizeof(*cred)); if (cred == NULL) return ENOMEM; ret = get_user_file(target_name, &cred->domain, &cred->username, &cred->key); if (ret) ret = get_user_ccache(target_name, &cred->domain, &cred->username, &cred->key); if (ret) { free(cred); return ret; } *rcred = cred; return ret; } static int _gss_copy_cred(ntlm_cred from, ntlm_cred *to) { *to = calloc(1, sizeof(**to)); if (*to == NULL) return ENOMEM; (*to)->username = strdup(from->username); if ((*to)->username == NULL) { free(*to); return ENOMEM; } (*to)->domain = strdup(from->domain); if ((*to)->domain == NULL) { free((*to)->username); free(*to); return ENOMEM; } (*to)->key.data = malloc(from->key.length); if ((*to)->key.data == NULL) { free((*to)->domain); free((*to)->username); free(*to); return ENOMEM; } memcpy((*to)->key.data, from->key.data, from->key.length); (*to)->key.length = from->key.length; return 0; } OM_uint32 GSSAPI_CALLCONV _gss_ntlm_init_sec_context (OM_uint32 * minor_status, gss_const_cred_id_t initiator_cred_handle, gss_ctx_id_t * context_handle, gss_const_name_t target_name, const gss_OID mech_type, OM_uint32 req_flags, OM_uint32 time_req, const gss_channel_bindings_t input_chan_bindings, const gss_buffer_t input_token, gss_OID * actual_mech_type, gss_buffer_t output_token, OM_uint32 * ret_flags, OM_uint32 * time_rec ) { ntlm_ctx ctx; ntlm_name name = (ntlm_name)target_name; *minor_status = 0; if (ret_flags) *ret_flags = 0; if (time_rec) *time_rec = 0; if (actual_mech_type) *actual_mech_type = GSS_C_NO_OID; if (*context_handle == GSS_C_NO_CONTEXT) { struct ntlm_type1 type1; struct ntlm_buf data; uint32_t flags = 0; int ret; ctx = calloc(1, sizeof(*ctx)); if (ctx == NULL) { *minor_status = EINVAL; return GSS_S_FAILURE; } *context_handle = (gss_ctx_id_t)ctx; if (initiator_cred_handle != GSS_C_NO_CREDENTIAL) { ntlm_cred cred = (ntlm_cred)initiator_cred_handle; ret = _gss_copy_cred(cred, &ctx->client); } else ret = _gss_ntlm_get_user_cred(name, &ctx->client); if (ret) { _gss_ntlm_delete_sec_context(minor_status, context_handle, NULL); *minor_status = ret; return GSS_S_FAILURE; } if (req_flags & GSS_C_CONF_FLAG) flags |= NTLM_NEG_SEAL; if (req_flags & GSS_C_INTEG_FLAG) flags |= NTLM_NEG_SIGN; else flags |= NTLM_NEG_ALWAYS_SIGN; flags |= NTLM_NEG_UNICODE; flags |= NTLM_NEG_NTLM; flags |= NTLM_NEG_NTLM2_SESSION; flags |= NTLM_NEG_KEYEX; memset(&type1, 0, sizeof(type1)); type1.flags = flags; type1.domain = name->domain; type1.hostname = NULL; type1.os[0] = 0; type1.os[1] = 0; ret = heim_ntlm_encode_type1(&type1, &data); if (ret) { _gss_ntlm_delete_sec_context(minor_status, context_handle, NULL); *minor_status = ret; return GSS_S_FAILURE; } output_token->value = data.data; output_token->length = data.length; return GSS_S_CONTINUE_NEEDED; } else { krb5_error_code ret; struct ntlm_type2 type2; struct ntlm_type3 type3; struct ntlm_buf data; ctx = (ntlm_ctx)*context_handle; data.data = input_token->value; data.length = input_token->length; ret = heim_ntlm_decode_type2(&data, &type2); if (ret) { _gss_ntlm_delete_sec_context(minor_status, context_handle, NULL); *minor_status = ret; return GSS_S_FAILURE; } ctx->flags = type2.flags; /* XXX check that type2.targetinfo matches `target_name´ */ /* XXX check verify targetinfo buffer */ memset(&type3, 0, sizeof(type3)); type3.username = ctx->client->username; type3.flags = type2.flags; type3.targetname = type2.targetname; type3.ws = rk_UNCONST("workstation"); /* * NTLM Version 1 if no targetinfo buffer. */ if (1 || type2.targetinfo.length == 0) { struct ntlm_buf sessionkey; if (type2.flags & NTLM_NEG_NTLM2_SESSION) { unsigned char nonce[8]; if (RAND_bytes(nonce, sizeof(nonce)) != 1) { _gss_ntlm_delete_sec_context(minor_status, context_handle, NULL); *minor_status = EINVAL; return GSS_S_FAILURE; } ret = heim_ntlm_calculate_ntlm2_sess(nonce, type2.challenge, ctx->client->key.data, &type3.lm, &type3.ntlm); } else { ret = heim_ntlm_calculate_ntlm1(ctx->client->key.data, ctx->client->key.length, type2.challenge, &type3.ntlm); } if (ret) { _gss_ntlm_delete_sec_context(minor_status,context_handle,NULL); *minor_status = ret; return GSS_S_FAILURE; } ret = heim_ntlm_build_ntlm1_master(ctx->client->key.data, ctx->client->key.length, &sessionkey, &type3.sessionkey); if (ret) { if (type3.lm.data) free(type3.lm.data); if (type3.ntlm.data) free(type3.ntlm.data); _gss_ntlm_delete_sec_context(minor_status,context_handle,NULL); *minor_status = ret; return GSS_S_FAILURE; } ret = krb5_data_copy(&ctx->sessionkey, sessionkey.data, sessionkey.length); free(sessionkey.data); if (ret) { if (type3.lm.data) free(type3.lm.data); if (type3.ntlm.data) free(type3.ntlm.data); _gss_ntlm_delete_sec_context(minor_status,context_handle,NULL); *minor_status = ret; return GSS_S_FAILURE; } ctx->status |= STATUS_SESSIONKEY; } else { struct ntlm_buf sessionkey; unsigned char ntlmv2[16]; struct ntlm_targetinfo ti; /* verify infotarget */ ret = heim_ntlm_decode_targetinfo(&type2.targetinfo, 1, &ti); if(ret) { _gss_ntlm_delete_sec_context(minor_status, context_handle, NULL); *minor_status = ret; return GSS_S_FAILURE; } if (ti.domainname && strcmp(ti.domainname, name->domain) != 0) { _gss_ntlm_delete_sec_context(minor_status, context_handle, NULL); *minor_status = EINVAL; return GSS_S_FAILURE; } ret = heim_ntlm_calculate_ntlm2(ctx->client->key.data, ctx->client->key.length, ctx->client->username, name->domain, type2.challenge, &type2.targetinfo, ntlmv2, &type3.ntlm); if (ret) { _gss_ntlm_delete_sec_context(minor_status, context_handle, NULL); *minor_status = ret; return GSS_S_FAILURE; } ret = heim_ntlm_build_ntlm1_master(ntlmv2, sizeof(ntlmv2), &sessionkey, &type3.sessionkey); memset(ntlmv2, 0, sizeof(ntlmv2)); if (ret) { _gss_ntlm_delete_sec_context(minor_status, context_handle, NULL); *minor_status = ret; return GSS_S_FAILURE; } ctx->flags |= NTLM_NEG_NTLM2_SESSION; ret = krb5_data_copy(&ctx->sessionkey, sessionkey.data, sessionkey.length); free(sessionkey.data); if (ret) { _gss_ntlm_delete_sec_context(minor_status, context_handle, NULL); *minor_status = ret; return GSS_S_FAILURE; } } if (ctx->flags & NTLM_NEG_NTLM2_SESSION) { ctx->status |= STATUS_SESSIONKEY; _gss_ntlm_set_key(&ctx->u.v2.send, 0, (ctx->flags & NTLM_NEG_KEYEX), ctx->sessionkey.data, ctx->sessionkey.length); _gss_ntlm_set_key(&ctx->u.v2.recv, 1, (ctx->flags & NTLM_NEG_KEYEX), ctx->sessionkey.data, ctx->sessionkey.length); } else { ctx->status |= STATUS_SESSIONKEY; RC4_set_key(&ctx->u.v1.crypto_recv.key, ctx->sessionkey.length, ctx->sessionkey.data); RC4_set_key(&ctx->u.v1.crypto_send.key, ctx->sessionkey.length, ctx->sessionkey.data); } ret = heim_ntlm_encode_type3(&type3, &data, NULL); free(type3.sessionkey.data); if (type3.lm.data) free(type3.lm.data); if (type3.ntlm.data) free(type3.ntlm.data); if (ret) { _gss_ntlm_delete_sec_context(minor_status, context_handle, NULL); *minor_status = ret; return GSS_S_FAILURE; } output_token->length = data.length; output_token->value = data.data; if (actual_mech_type) *actual_mech_type = GSS_NTLM_MECHANISM; if (ret_flags) *ret_flags = 0; if (time_rec) *time_rec = GSS_C_INDEFINITE; ctx->status |= STATUS_OPEN; return GSS_S_COMPLETE; } } heimdal-7.5.0/lib/gssapi/ntlm/canonicalize_name.c0000644000175000017500000000364313026237312020070 0ustar niknik/* * Copyright (c) 1997 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "ntlm.h" OM_uint32 GSSAPI_CALLCONV _gss_ntlm_canonicalize_name ( OM_uint32 * minor_status, gss_const_name_t input_name, const gss_OID mech_type, gss_name_t * output_name ) { return gss_duplicate_name (minor_status, input_name, output_name); } heimdal-7.5.0/lib/gssapi/ntlm/indicate_mechs.c0000644000175000017500000000352012136107747017373 0ustar niknik/* * Copyright (c) 2006 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "ntlm.h" OM_uint32 _gss_ntlm_indicate_mechs (OM_uint32 * minor_status, gss_OID_set * mech_set ) { if (minor_status) *minor_status = 0; if (mech_set) *mech_set = GSS_C_NO_OID_SET; return GSS_S_COMPLETE; } heimdal-7.5.0/lib/gssapi/ntlm/import_name.c0000644000175000017500000000640113026237312016736 0ustar niknik/* * Copyright (c) 1997 - 2003 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "ntlm.h" OM_uint32 GSSAPI_CALLCONV _gss_ntlm_import_name (OM_uint32 * minor_status, const gss_buffer_t input_name_buffer, const gss_OID input_name_type, gss_name_t * output_name ) { char *name, *p, *p2; int is_hostnamed; int is_username; ntlm_name n; *minor_status = 0; if (output_name == NULL) return GSS_S_CALL_INACCESSIBLE_WRITE; *output_name = GSS_C_NO_NAME; is_hostnamed = gss_oid_equal(input_name_type, GSS_C_NT_HOSTBASED_SERVICE); is_username = gss_oid_equal(input_name_type, GSS_C_NT_USER_NAME); if (!is_hostnamed && !is_username) return GSS_S_BAD_NAMETYPE; name = malloc(input_name_buffer->length + 1); if (name == NULL) { *minor_status = ENOMEM; return GSS_S_FAILURE; } memcpy(name, input_name_buffer->value, input_name_buffer->length); name[input_name_buffer->length] = '\0'; /* find "domain" part of the name and uppercase it */ p = strchr(name, '@'); if (p == NULL) { free(name); return GSS_S_BAD_NAME; } p[0] = '\0'; p++; p2 = strchr(p, '.'); if (p2 && p2[1] != '\0') { if (is_hostnamed) { p = p2 + 1; p2 = strchr(p, '.'); } if (p2) *p2 = '\0'; } strupr(p); n = calloc(1, sizeof(*n)); if (n == NULL) { free(name); *minor_status = ENOMEM; return GSS_S_FAILURE; } n->user = strdup(name); n->domain = strdup(p); free(name); if (n->user == NULL || n->domain == NULL) { free(n->user); free(n->domain); free(n); *minor_status = ENOMEM; return GSS_S_FAILURE; } *output_name = (gss_name_t)n; return GSS_S_COMPLETE; } heimdal-7.5.0/lib/gssapi/ntlm/kdc.c0000644000175000017500000002221313212137553015167 0ustar niknik/* * Copyright (c) 2006 - 2007 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "ntlm.h" #ifdef DIGEST /* * */ struct ntlmkrb5 { krb5_context context; krb5_ntlm ntlm; krb5_realm kerberos_realm; krb5_ccache id; krb5_data opaque; int destroy; OM_uint32 flags; struct ntlm_buf key; krb5_data sessionkey; }; static OM_uint32 kdc_destroy(OM_uint32 *, void *); /* * Get credential cache that the ntlm code can use to talk to the KDC * using the digest API. */ static krb5_error_code get_ccache(krb5_context context, int *destroy, krb5_ccache *id) { krb5_principal principal = NULL; krb5_error_code ret; krb5_keytab kt = NULL; *id = NULL; if (!issuid()) { const char *cache; cache = getenv("NTLM_ACCEPTOR_CCACHE"); if (cache) { ret = krb5_cc_resolve(context, cache, id); if (ret) goto out; return 0; } } ret = krb5_sname_to_principal(context, NULL, "host", KRB5_NT_SRV_HST, &principal); if (ret) goto out; ret = krb5_cc_cache_match(context, principal, id); if (ret == 0) return 0; /* did not find in default credcache, lets try default keytab */ ret = krb5_kt_default(context, &kt); if (ret) goto out; /* XXX check in keytab */ { krb5_get_init_creds_opt *opt; krb5_creds cred; memset(&cred, 0, sizeof(cred)); ret = krb5_cc_new_unique(context, "MEMORY", NULL, id); if (ret) goto out; *destroy = 1; ret = krb5_get_init_creds_opt_alloc(context, &opt); if (ret) goto out; ret = krb5_get_init_creds_keytab (context, &cred, principal, kt, 0, NULL, opt); krb5_get_init_creds_opt_free(context, opt); if (ret) goto out; ret = krb5_cc_initialize (context, *id, cred.client); if (ret) { krb5_free_cred_contents (context, &cred); goto out; } ret = krb5_cc_store_cred (context, *id, &cred); krb5_free_cred_contents (context, &cred); if (ret) goto out; } krb5_kt_close(context, kt); return 0; out: if (*id) { if (*destroy) krb5_cc_destroy(context, *id); else krb5_cc_close(context, *id); *id = NULL; } if (kt) krb5_kt_close(context, kt); if (principal) krb5_free_principal(context, principal); return ret; } /* * */ static OM_uint32 kdc_alloc(OM_uint32 *minor, void **ctx) { krb5_error_code ret; struct ntlmkrb5 *c; OM_uint32 junk; c = calloc(1, sizeof(*c)); if (c == NULL) { *minor = ENOMEM; return GSS_S_FAILURE; } ret = krb5_init_context(&c->context); if (ret) { kdc_destroy(&junk, c); *minor = ret; return GSS_S_FAILURE; } ret = get_ccache(c->context, &c->destroy, &c->id); if (ret) { kdc_destroy(&junk, c); *minor = ret; return GSS_S_FAILURE; } ret = krb5_ntlm_alloc(c->context, &c->ntlm); if (ret) { kdc_destroy(&junk, c); *minor = ret; return GSS_S_FAILURE; } *ctx = c; return GSS_S_COMPLETE; } static int kdc_probe(OM_uint32 *minor, void *ctx, const char *realm) { struct ntlmkrb5 *c = ctx; krb5_error_code ret; unsigned flags; ret = krb5_digest_probe(c->context, rk_UNCONST(realm), c->id, &flags); if (ret) return ret; if ((flags & (1|2|4)) == 0) return EINVAL; return 0; } /* * */ static OM_uint32 kdc_destroy(OM_uint32 *minor, void *ctx) { struct ntlmkrb5 *c = ctx; krb5_data_free(&c->opaque); krb5_data_free(&c->sessionkey); if (c->ntlm) krb5_ntlm_free(c->context, c->ntlm); if (c->id) { if (c->destroy) krb5_cc_destroy(c->context, c->id); else krb5_cc_close(c->context, c->id); } if (c->context) krb5_free_context(c->context); memset(c, 0, sizeof(*c)); free(c); return GSS_S_COMPLETE; } /* * */ static OM_uint32 kdc_type2(OM_uint32 *minor_status, void *ctx, uint32_t flags, const char *hostname, const char *domain, uint32_t *ret_flags, struct ntlm_buf *out) { struct ntlmkrb5 *c = ctx; krb5_error_code ret; struct ntlm_type2 type2; krb5_data challenge; struct ntlm_buf data; krb5_data ti; memset(&type2, 0, sizeof(type2)); /* * Request data for type 2 packet from the KDC. */ ret = krb5_ntlm_init_request(c->context, c->ntlm, NULL, c->id, flags, hostname, domain); if (ret) { *minor_status = ret; return GSS_S_FAILURE; } /* * */ ret = krb5_ntlm_init_get_opaque(c->context, c->ntlm, &c->opaque); if (ret) { *minor_status = ret; return GSS_S_FAILURE; } /* * */ ret = krb5_ntlm_init_get_flags(c->context, c->ntlm, &type2.flags); if (ret) { *minor_status = ret; return GSS_S_FAILURE; } *ret_flags = type2.flags; ret = krb5_ntlm_init_get_challenge(c->context, c->ntlm, &challenge); if (ret) { *minor_status = ret; return GSS_S_FAILURE; } if (challenge.length != sizeof(type2.challenge)) { *minor_status = EINVAL; return GSS_S_FAILURE; } memcpy(type2.challenge, challenge.data, sizeof(type2.challenge)); krb5_data_free(&challenge); ret = krb5_ntlm_init_get_targetname(c->context, c->ntlm, &type2.targetname); if (ret) { *minor_status = ret; return GSS_S_FAILURE; } ret = krb5_ntlm_init_get_targetinfo(c->context, c->ntlm, &ti); if (ret) { free(type2.targetname); *minor_status = ret; return GSS_S_FAILURE; } type2.targetinfo.data = ti.data; type2.targetinfo.length = ti.length; ret = heim_ntlm_encode_type2(&type2, &data); free(type2.targetname); krb5_data_free(&ti); if (ret) { *minor_status = ret; return GSS_S_FAILURE; } out->data = data.data; out->length = data.length; return GSS_S_COMPLETE; } /* * */ static OM_uint32 kdc_type3(OM_uint32 *minor_status, void *ctx, const struct ntlm_type3 *type3, struct ntlm_buf *sessionkey) { struct ntlmkrb5 *c = ctx; krb5_error_code ret; sessionkey->data = NULL; sessionkey->length = 0; ret = krb5_ntlm_req_set_flags(c->context, c->ntlm, type3->flags); if (ret) goto out; ret = krb5_ntlm_req_set_username(c->context, c->ntlm, type3->username); if (ret) goto out; ret = krb5_ntlm_req_set_targetname(c->context, c->ntlm, type3->targetname); if (ret) goto out; ret = krb5_ntlm_req_set_lm(c->context, c->ntlm, type3->lm.data, type3->lm.length); if (ret) goto out; ret = krb5_ntlm_req_set_ntlm(c->context, c->ntlm, type3->ntlm.data, type3->ntlm.length); if (ret) goto out; ret = krb5_ntlm_req_set_opaque(c->context, c->ntlm, &c->opaque); if (ret) goto out; if (type3->sessionkey.length) { ret = krb5_ntlm_req_set_session(c->context, c->ntlm, type3->sessionkey.data, type3->sessionkey.length); if (ret) goto out; } /* * Verify with the KDC the type3 packet is ok */ ret = krb5_ntlm_request(c->context, c->ntlm, NULL, c->id); if (ret) goto out; if (krb5_ntlm_rep_get_status(c->context, c->ntlm) != TRUE) { ret = EINVAL; goto out; } if (type3->sessionkey.length) { ret = krb5_ntlm_rep_get_sessionkey(c->context, c->ntlm, &c->sessionkey); if (ret) goto out; sessionkey->data = c->sessionkey.data; sessionkey->length = c->sessionkey.length; } return 0; out: *minor_status = ret; return GSS_S_FAILURE; } /* * */ static void kdc_free_buffer(struct ntlm_buf *sessionkey) { if (sessionkey->data) free(sessionkey->data); sessionkey->data = NULL; sessionkey->length = 0; } /* * */ struct ntlm_server_interface ntlmsspi_kdc_digest = { kdc_alloc, kdc_destroy, kdc_probe, kdc_type2, kdc_type3, kdc_free_buffer }; #endif /* DIGEST */ heimdal-7.5.0/lib/gssapi/ntlm/release_cred.c0000644000175000017500000000432013212137553017042 0ustar niknik/* * Copyright (c) 2006 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "ntlm.h" OM_uint32 GSSAPI_CALLCONV _gss_ntlm_release_cred (OM_uint32 * minor_status, gss_cred_id_t * cred_handle ) { ntlm_cred cred; if (minor_status) *minor_status = 0; if (cred_handle == NULL || *cred_handle == GSS_C_NO_CREDENTIAL) return GSS_S_COMPLETE; cred = (ntlm_cred)*cred_handle; *cred_handle = GSS_C_NO_CREDENTIAL; if (cred->username) free(cred->username); if (cred->domain) free(cred->domain); if (cred->key.data) { memset(cred->key.data, 0, cred->key.length); free(cred->key.data); } return GSS_S_COMPLETE; } heimdal-7.5.0/lib/gssapi/ntlm/export_sec_context.c0000644000175000017500000000372612136107747020363 0ustar niknik/* * Copyright (c) 1999 - 2003 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "ntlm.h" OM_uint32 GSSAPI_CALLCONV _gss_ntlm_export_sec_context ( OM_uint32 * minor_status, gss_ctx_id_t * context_handle, gss_buffer_t interprocess_token ) { if (minor_status) *minor_status = 0; if (interprocess_token) { interprocess_token->length = 0; interprocess_token->value = NULL; } return GSS_S_COMPLETE; } heimdal-7.5.0/lib/gssapi/ntlm/inquire_cred_by_mech.c0000644000175000017500000000432513026237312020566 0ustar niknik/* * Copyright (c) 2006 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "ntlm.h" OM_uint32 GSSAPI_CALLCONV _gss_ntlm_inquire_cred_by_mech ( OM_uint32 * minor_status, gss_const_cred_id_t cred_handle, const gss_OID mech_type, gss_name_t * name, OM_uint32 * initiator_lifetime, OM_uint32 * acceptor_lifetime, gss_cred_usage_t * cred_usage ) { if (minor_status) *minor_status = 0; if (name) *name = GSS_C_NO_NAME; if (initiator_lifetime) *initiator_lifetime = 0; if (acceptor_lifetime) *acceptor_lifetime = 0; if (cred_usage) *cred_usage = 0; return GSS_S_UNAVAILABLE; } heimdal-7.5.0/lib/gssapi/ntlm/context_time.c0000644000175000017500000000360513026237312017131 0ustar niknik/* * Copyright (c) 1997 - 2003 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "ntlm.h" OM_uint32 GSSAPI_CALLCONV _gss_ntlm_context_time (OM_uint32 * minor_status, gss_const_ctx_id_t context_handle, OM_uint32 * time_rec ) { if (time_rec) *time_rec = GSS_C_INDEFINITE; return GSS_S_COMPLETE; } heimdal-7.5.0/lib/gssapi/ntlm/compare_name.c0000644000175000017500000000357613026237312017064 0ustar niknik/* * Copyright (c) 1997-2003 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "ntlm.h" OM_uint32 GSSAPI_CALLCONV _gss_ntlm_compare_name (OM_uint32 * minor_status, gss_const_name_t name1, gss_const_name_t name2, int * name_equal ) { *minor_status = 0; return GSS_S_COMPLETE; } heimdal-7.5.0/lib/gssapi/ntlm/ntlm-private.h0000644000175000017500000001634413212445601017061 0ustar niknik/* This is a generated file */ #ifndef __ntlm_private_h__ #define __ntlm_private_h__ #include gssapi_mech_interface __gss_ntlm_initialize (void); OM_uint32 GSSAPI_CALLCONV _gss_ntlm_accept_sec_context ( OM_uint32 * /*minor_status*/, gss_ctx_id_t * /*context_handle*/, gss_const_cred_id_t /*acceptor_cred_handle*/, const gss_buffer_t /*input_token_buffer*/, const gss_channel_bindings_t /*input_chan_bindings*/, gss_name_t * /*src_name*/, gss_OID * /*mech_type*/, gss_buffer_t /*output_token*/, OM_uint32 * /*ret_flags*/, OM_uint32 * /*time_rec*/, gss_cred_id_t * delegated_cred_handle ); OM_uint32 GSSAPI_CALLCONV _gss_ntlm_acquire_cred ( OM_uint32 */*min_stat*/, gss_const_name_t /*desired_name*/, OM_uint32 /*time_req*/, const gss_OID_set /*desired_mechs*/, gss_cred_usage_t /*cred_usage*/, gss_cred_id_t */*output_cred_handle*/, gss_OID_set */*actual_mechs*/, OM_uint32 */*time_rec*/); OM_uint32 GSSAPI_CALLCONV _gss_ntlm_add_cred ( OM_uint32 */*minor_status*/, gss_const_cred_id_t /*input_cred_handle*/, gss_const_name_t /*desired_name*/, const gss_OID /*desired_mech*/, gss_cred_usage_t /*cred_usage*/, OM_uint32 /*initiator_time_req*/, OM_uint32 /*acceptor_time_req*/, gss_cred_id_t */*output_cred_handle*/, gss_OID_set */*actual_mechs*/, OM_uint32 */*initiator_time_rec*/, OM_uint32 */*acceptor_time_rec*/); OM_uint32 _gss_ntlm_allocate_ctx ( OM_uint32 */*minor_status*/, ntlm_ctx */*ctx*/); OM_uint32 GSSAPI_CALLCONV _gss_ntlm_canonicalize_name ( OM_uint32 * /*minor_status*/, gss_const_name_t /*input_name*/, const gss_OID /*mech_type*/, gss_name_t * output_name ); OM_uint32 GSSAPI_CALLCONV _gss_ntlm_compare_name ( OM_uint32 * /*minor_status*/, gss_const_name_t /*name1*/, gss_const_name_t /*name2*/, int * name_equal ); OM_uint32 GSSAPI_CALLCONV _gss_ntlm_context_time ( OM_uint32 * /*minor_status*/, gss_const_ctx_id_t /*context_handle*/, OM_uint32 * time_rec ); OM_uint32 GSSAPI_CALLCONV _gss_ntlm_delete_sec_context ( OM_uint32 * /*minor_status*/, gss_ctx_id_t * /*context_handle*/, gss_buffer_t output_token ); OM_uint32 GSSAPI_CALLCONV _gss_ntlm_destroy_cred ( OM_uint32 */*minor_status*/, gss_cred_id_t */*cred_handle*/); OM_uint32 GSSAPI_CALLCONV _gss_ntlm_display_name ( OM_uint32 * /*minor_status*/, gss_const_name_t /*input_name*/, gss_buffer_t /*output_name_buffer*/, gss_OID * output_name_type ); OM_uint32 GSSAPI_CALLCONV _gss_ntlm_display_status ( OM_uint32 */*minor_status*/, OM_uint32 /*status_value*/, int /*status_type*/, const gss_OID /*mech_type*/, OM_uint32 */*message_context*/, gss_buffer_t /*status_string*/); OM_uint32 GSSAPI_CALLCONV _gss_ntlm_duplicate_name ( OM_uint32 * /*minor_status*/, gss_const_name_t /*src_name*/, gss_name_t * dest_name ); OM_uint32 GSSAPI_CALLCONV _gss_ntlm_export_name ( OM_uint32 * /*minor_status*/, gss_const_name_t /*input_name*/, gss_buffer_t exported_name ); OM_uint32 GSSAPI_CALLCONV _gss_ntlm_export_sec_context ( OM_uint32 * /*minor_status*/, gss_ctx_id_t * /*context_handle*/, gss_buffer_t interprocess_token ); OM_uint32 GSSAPI_CALLCONV _gss_ntlm_get_mic ( OM_uint32 * /*minor_status*/, gss_const_ctx_id_t /*context_handle*/, gss_qop_t /*qop_req*/, const gss_buffer_t /*message_buffer*/, gss_buffer_t message_token ); int _gss_ntlm_get_user_cred ( const ntlm_name /*target_name*/, ntlm_cred */*rcred*/); OM_uint32 GSSAPI_CALLCONV _gss_ntlm_import_name ( OM_uint32 * /*minor_status*/, const gss_buffer_t /*input_name_buffer*/, const gss_OID /*input_name_type*/, gss_name_t * output_name ); OM_uint32 GSSAPI_CALLCONV _gss_ntlm_import_sec_context ( OM_uint32 * /*minor_status*/, const gss_buffer_t /*interprocess_token*/, gss_ctx_id_t * context_handle ); OM_uint32 _gss_ntlm_indicate_mechs ( OM_uint32 * /*minor_status*/, gss_OID_set * mech_set ); OM_uint32 GSSAPI_CALLCONV _gss_ntlm_init_sec_context ( OM_uint32 * /*minor_status*/, gss_const_cred_id_t /*initiator_cred_handle*/, gss_ctx_id_t * /*context_handle*/, gss_const_name_t /*target_name*/, const gss_OID /*mech_type*/, OM_uint32 /*req_flags*/, OM_uint32 /*time_req*/, const gss_channel_bindings_t /*input_chan_bindings*/, const gss_buffer_t /*input_token*/, gss_OID * /*actual_mech_type*/, gss_buffer_t /*output_token*/, OM_uint32 * /*ret_flags*/, OM_uint32 * time_rec ); OM_uint32 GSSAPI_CALLCONV _gss_ntlm_inquire_context ( OM_uint32 * /*minor_status*/, gss_const_ctx_id_t /*context_handle*/, gss_name_t * /*src_name*/, gss_name_t * /*targ_name*/, OM_uint32 * /*lifetime_rec*/, gss_OID * /*mech_type*/, OM_uint32 * /*ctx_flags*/, int * /*locally_initiated*/, int * open_context ); OM_uint32 GSSAPI_CALLCONV _gss_ntlm_inquire_cred ( OM_uint32 * /*minor_status*/, gss_const_cred_id_t /*cred_handle*/, gss_name_t * /*name*/, OM_uint32 * /*lifetime*/, gss_cred_usage_t * /*cred_usage*/, gss_OID_set * mechanisms ); OM_uint32 GSSAPI_CALLCONV _gss_ntlm_inquire_cred_by_mech ( OM_uint32 * /*minor_status*/, gss_const_cred_id_t /*cred_handle*/, const gss_OID /*mech_type*/, gss_name_t * /*name*/, OM_uint32 * /*initiator_lifetime*/, OM_uint32 * /*acceptor_lifetime*/, gss_cred_usage_t * cred_usage ); OM_uint32 GSSAPI_CALLCONV _gss_ntlm_inquire_mechs_for_name ( OM_uint32 * /*minor_status*/, gss_const_name_t /*input_name*/, gss_OID_set * mech_types ); OM_uint32 GSSAPI_CALLCONV _gss_ntlm_inquire_names_for_mech ( OM_uint32 * /*minor_status*/, const gss_OID /*mechanism*/, gss_OID_set * name_types ); OM_uint32 GSSAPI_CALLCONV _gss_ntlm_inquire_sec_context_by_oid ( OM_uint32 */*minor_status*/, gss_const_ctx_id_t /*context_handle*/, const gss_OID /*desired_object*/, gss_buffer_set_t */*data_set*/); void GSSAPI_CALLCONV _gss_ntlm_iter_creds_f ( OM_uint32 /*flags*/, void *userctx , void (*/*cred_iter*/)(void *, gss_OID, gss_cred_id_t)); OM_uint32 GSSAPI_CALLCONV _gss_ntlm_process_context_token ( OM_uint32 */*minor_status*/, gss_const_ctx_id_t /*context_handle*/, const gss_buffer_t token_buffer ); OM_uint32 GSSAPI_CALLCONV _gss_ntlm_release_cred ( OM_uint32 * /*minor_status*/, gss_cred_id_t * cred_handle ); OM_uint32 GSSAPI_CALLCONV _gss_ntlm_release_name ( OM_uint32 * /*minor_status*/, gss_name_t * input_name ); void _gss_ntlm_set_key ( struct ntlmv2_key */*key*/, int /*acceptor*/, int /*sealsign*/, unsigned char */*data*/, size_t /*len*/); OM_uint32 GSSAPI_CALLCONV _gss_ntlm_unwrap ( OM_uint32 * /*minor_status*/, gss_const_ctx_id_t /*context_handle*/, const gss_buffer_t /*input_message_buffer*/, gss_buffer_t /*output_message_buffer*/, int * /*conf_state*/, gss_qop_t * qop_state ); OM_uint32 GSSAPI_CALLCONV _gss_ntlm_verify_mic ( OM_uint32 * /*minor_status*/, gss_const_ctx_id_t /*context_handle*/, const gss_buffer_t /*message_buffer*/, const gss_buffer_t /*token_buffer*/, gss_qop_t * qop_state ); OM_uint32 GSSAPI_CALLCONV _gss_ntlm_wrap ( OM_uint32 * /*minor_status*/, gss_const_ctx_id_t /*context_handle*/, int /*conf_req_flag*/, gss_qop_t /*qop_req*/, const gss_buffer_t /*input_message_buffer*/, int * /*conf_state*/, gss_buffer_t output_message_buffer ); OM_uint32 GSSAPI_CALLCONV _gss_ntlm_wrap_size_limit ( OM_uint32 * /*minor_status*/, gss_const_ctx_id_t /*context_handle*/, int /*conf_req_flag*/, gss_qop_t /*qop_req*/, OM_uint32 /*req_output_size*/, OM_uint32 * max_input_size ); #endif /* __ntlm_private_h__ */ heimdal-7.5.0/lib/gssapi/ntlm/creds.c0000644000175000017500000001046613062303006015524 0ustar niknik/* * Copyright (c) 2006 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Portions Copyright (c) 2009 Apple Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "ntlm.h" OM_uint32 GSSAPI_CALLCONV _gss_ntlm_inquire_cred (OM_uint32 * minor_status, gss_const_cred_id_t cred_handle, gss_name_t * name, OM_uint32 * lifetime, gss_cred_usage_t * cred_usage, gss_OID_set * mechanisms ) { OM_uint32 ret, junk; *minor_status = 0; if (cred_handle == NULL) return GSS_S_NO_CRED; if (name) { ntlm_name n = calloc(1, sizeof(*n)); ntlm_cred c = (ntlm_cred)cred_handle; if (n) { n->user = strdup(c->username); n->domain = strdup(c->domain); } if (n == NULL || n->user == NULL || n->domain == NULL) { if (n) { free(n->user); free(n->domain); free(n); } *minor_status = ENOMEM; return GSS_S_FAILURE; } *name = (gss_name_t)n; } if (lifetime) *lifetime = GSS_C_INDEFINITE; if (cred_usage) *cred_usage = 0; if (mechanisms) *mechanisms = GSS_C_NO_OID_SET; if (cred_handle == GSS_C_NO_CREDENTIAL) return GSS_S_NO_CRED; if (mechanisms) { ret = gss_create_empty_oid_set(minor_status, mechanisms); if (ret) goto out; ret = gss_add_oid_set_member(minor_status, GSS_NTLM_MECHANISM, mechanisms); if (ret) goto out; } return GSS_S_COMPLETE; out: gss_release_oid_set(&junk, mechanisms); return ret; } #ifdef HAVE_KCM static OM_uint32 _gss_ntlm_destroy_kcm_cred(gss_cred_id_t *cred_handle) { krb5_storage *request, *response; krb5_data response_data; krb5_context context; krb5_error_code ret; ntlm_cred cred; cred = (ntlm_cred)*cred_handle; ret = krb5_init_context(&context); if (ret) return ret; ret = krb5_kcm_storage_request(context, KCM_OP_DEL_NTLM_CRED, &request); if (ret) goto out; ret = krb5_store_stringz(request, cred->username); if (ret) goto out; ret = krb5_store_stringz(request, cred->domain); if (ret) goto out; ret = krb5_kcm_call(context, request, &response, &response_data); if (ret) goto out; krb5_storage_free(request); krb5_storage_free(response); krb5_data_free(&response_data); out: krb5_free_context(context); return ret; } #endif /* HAVE_KCM */ OM_uint32 GSSAPI_CALLCONV _gss_ntlm_destroy_cred(OM_uint32 *minor_status, gss_cred_id_t *cred_handle) { #ifdef HAVE_KCM krb5_error_code ret; #endif if (cred_handle == NULL || *cred_handle == GSS_C_NO_CREDENTIAL) return GSS_S_COMPLETE; #ifdef HAVE_KCM ret = _gss_ntlm_destroy_kcm_cred(cred_handle); if (ret) { *minor_status = ret; return GSS_S_FAILURE; } #endif return _gss_ntlm_release_cred(minor_status, cred_handle); } heimdal-7.5.0/lib/gssapi/test_context.c0000644000175000017500000010404213212137553016200 0ustar niknik/* * Copyright (c) 2006 - 2008 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of KTH nor the names of its contributors may be * used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY KTH AND ITS CONTRIBUTORS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL KTH OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "krb5/gsskrb5_locl.h" #include #include #include #include #include #include #include "test_common.h" static char *type_string; static char *mech_string; static char *mechs_string; static char *ret_mech_string; static char *client_name; static char *client_password; static int dns_canon_flag = -1; static int mutual_auth_flag = 0; static int dce_style_flag = 0; static int wrapunwrap_flag = 0; static int iov_flag = 0; static int aead_flag = 0; static int getverifymic_flag = 0; static int deleg_flag = 0; static int policy_deleg_flag = 0; static int server_no_deleg_flag = 0; static int ei_flag = 0; static char *gsskrb5_acceptor_identity = NULL; static char *session_enctype_string = NULL; static int client_time_offset = 0; static int server_time_offset = 0; static int max_loops = 0; static char *limit_enctype_string = NULL; static int version_flag = 0; static int verbose_flag = 0; static int help_flag = 0; static krb5_context context; static krb5_enctype limit_enctype = 0; static struct { const char *name; gss_OID oid; } o2n[] = { { "krb5", NULL /* GSS_KRB5_MECHANISM */ }, { "spnego", NULL /* GSS_SPNEGO_MECHANISM */ }, { "ntlm", NULL /* GSS_NTLM_MECHANISM */ }, { "sasl-digest-md5", NULL /* GSS_SASL_DIGEST_MD5_MECHANISM */ } }; static void init_o2n(void) { o2n[0].oid = GSS_KRB5_MECHANISM; o2n[1].oid = GSS_SPNEGO_MECHANISM; o2n[2].oid = GSS_NTLM_MECHANISM; o2n[3].oid = GSS_SASL_DIGEST_MD5_MECHANISM; } static gss_OID string_to_oid(const char *name) { size_t i; for (i = 0; i < sizeof(o2n)/sizeof(o2n[0]); i++) if (strcasecmp(name, o2n[i].name) == 0) return o2n[i].oid; errx(1, "name '%s' not unknown", name); } static void string_to_oids(gss_OID_set *oidsetp, gss_OID_set oidset, gss_OID_desc *oidarray, size_t oidarray_len, char *names) { char *name; char *s; if (names[0] == '\0') { *oidsetp = GSS_C_NO_OID_SET; return; } oidset->elements = &oidarray[0]; if (strcasecmp(names, "all") == 0) { if (sizeof(o2n)/sizeof(o2n[0]) > oidarray_len) errx(1, "internal error: oidarray must be enlarged"); for (oidset->count = 0; oidset->count < oidarray_len; oidset->count++) oidset->elements[oidset->count] = *o2n[oidset->count].oid; } else { for (oidset->count = 0, name = strtok_r(names, ", ", &s); name != NULL; oidset->count++, name = strtok_r(NULL, ", ", &s)) { if (oidset->count >= oidarray_len) errx(1, "too many mech names given"); oidset->elements[oidset->count] = *string_to_oid(name); } oidset->count = oidset->count; } *oidsetp = oidset; } static const char * oid_to_string(const gss_OID oid) { size_t i; for (i = 0; i < sizeof(o2n)/sizeof(o2n[0]); i++) if (gss_oid_equal(oid, o2n[i].oid)) return o2n[i].name; return "unknown oid"; } static void loop(gss_OID mechoid, gss_OID nameoid, const char *target, gss_cred_id_t init_cred, gss_ctx_id_t *sctx, gss_ctx_id_t *cctx, gss_OID *actual_mech, gss_cred_id_t *deleg_cred) { int server_done = 0, client_done = 0; int num_loops = 0; OM_uint32 maj_stat, min_stat; gss_name_t gss_target_name; gss_buffer_desc input_token, output_token; OM_uint32 flags = 0, ret_cflags, ret_sflags; gss_OID actual_mech_client; gss_OID actual_mech_server; *actual_mech = GSS_C_NO_OID; flags |= GSS_C_INTEG_FLAG; flags |= GSS_C_CONF_FLAG; if (mutual_auth_flag) flags |= GSS_C_MUTUAL_FLAG; if (dce_style_flag) flags |= GSS_C_DCE_STYLE; if (deleg_flag) flags |= GSS_C_DELEG_FLAG; if (policy_deleg_flag) flags |= GSS_C_DELEG_POLICY_FLAG; input_token.value = rk_UNCONST(target); input_token.length = strlen(target); maj_stat = gss_import_name(&min_stat, &input_token, nameoid, &gss_target_name); if (GSS_ERROR(maj_stat)) err(1, "import name creds failed with: %d", maj_stat); input_token.length = 0; input_token.value = NULL; while (!server_done || !client_done) { num_loops++; gsskrb5_set_time_offset(client_time_offset); maj_stat = gss_init_sec_context(&min_stat, init_cred, cctx, gss_target_name, mechoid, flags, 0, NULL, &input_token, &actual_mech_client, &output_token, &ret_cflags, NULL); if (GSS_ERROR(maj_stat)) errx(1, "init_sec_context: %s", gssapi_err(maj_stat, min_stat, mechoid)); if (maj_stat & GSS_S_CONTINUE_NEEDED) ; else client_done = 1; gsskrb5_get_time_offset(&client_time_offset); if (client_done && server_done) break; if (input_token.length != 0) gss_release_buffer(&min_stat, &input_token); gsskrb5_set_time_offset(server_time_offset); maj_stat = gss_accept_sec_context(&min_stat, sctx, GSS_C_NO_CREDENTIAL, &output_token, GSS_C_NO_CHANNEL_BINDINGS, NULL, &actual_mech_server, &input_token, &ret_sflags, NULL, deleg_cred); if (GSS_ERROR(maj_stat)) errx(1, "accept_sec_context: %s", gssapi_err(maj_stat, min_stat, actual_mech_server)); gsskrb5_get_time_offset(&server_time_offset); if (output_token.length != 0) gss_release_buffer(&min_stat, &output_token); if (maj_stat & GSS_S_CONTINUE_NEEDED) ; else server_done = 1; } if (output_token.length != 0) gss_release_buffer(&min_stat, &output_token); if (input_token.length != 0) gss_release_buffer(&min_stat, &input_token); gss_release_name(&min_stat, &gss_target_name); if (deleg_flag || policy_deleg_flag) { if (server_no_deleg_flag) { if (*deleg_cred != GSS_C_NO_CREDENTIAL) errx(1, "got delegated cred but didn't expect one"); } else if (*deleg_cred == GSS_C_NO_CREDENTIAL) errx(1, "asked for delegarated cred but did get one"); } else if (*deleg_cred != GSS_C_NO_CREDENTIAL) errx(1, "got deleg_cred cred but didn't ask"); if (gss_oid_equal(actual_mech_server, actual_mech_client) == 0) errx(1, "mech mismatch"); *actual_mech = actual_mech_server; if (max_loops && num_loops > max_loops) errx(1, "num loops %d was lager then max loops %d", num_loops, max_loops); if (verbose_flag) { printf("server time offset: %d\n", server_time_offset); printf("client time offset: %d\n", client_time_offset); printf("num loops %d\n", num_loops); } } static void wrapunwrap(gss_ctx_id_t cctx, gss_ctx_id_t sctx, int flags, gss_OID mechoid) { gss_buffer_desc input_token, output_token, output_token2; OM_uint32 min_stat, maj_stat; gss_qop_t qop_state; int conf_state; input_token.value = "foo"; input_token.length = 3; maj_stat = gss_wrap(&min_stat, cctx, flags, 0, &input_token, &conf_state, &output_token); if (maj_stat != GSS_S_COMPLETE) errx(1, "gss_wrap failed: %s", gssapi_err(maj_stat, min_stat, mechoid)); maj_stat = gss_unwrap(&min_stat, sctx, &output_token, &output_token2, &conf_state, &qop_state); if (maj_stat != GSS_S_COMPLETE) errx(1, "gss_unwrap failed: %s", gssapi_err(maj_stat, min_stat, mechoid)); gss_release_buffer(&min_stat, &output_token); gss_release_buffer(&min_stat, &output_token2); #if 0 /* doesn't work for NTLM yet */ if (!!conf_state != !!flags) errx(1, "conf_state mismatch"); #endif } #define USE_CONF 1 #define USE_HEADER_ONLY 2 #define USE_SIGN_ONLY 4 #define FORCE_IOV 8 static void wrapunwrap_iov(gss_ctx_id_t cctx, gss_ctx_id_t sctx, int flags, gss_OID mechoid) { krb5_data token, header, trailer; OM_uint32 min_stat, maj_stat; gss_qop_t qop_state; int conf_state, conf_state2; gss_iov_buffer_desc iov[6]; unsigned char *p; int iov_len; char header_data[9] = "ABCheader"; char trailer_data[10] = "trailerXYZ"; char token_data[16] = "0123456789abcdef"; memset(&iov, 0, sizeof(iov)); if (flags & USE_SIGN_ONLY) { header.data = header_data; header.length = 9; trailer.data = trailer_data; trailer.length = 10; } else { header.data = NULL; header.length = 0; trailer.data = NULL; trailer.length = 0; } token.data = token_data; token.length = 16; iov_len = sizeof(iov)/sizeof(iov[0]); memset(iov, 0, sizeof(iov)); iov[0].type = GSS_IOV_BUFFER_TYPE_HEADER | GSS_IOV_BUFFER_TYPE_FLAG_ALLOCATE; if (header.length != 0) { iov[1].type = GSS_IOV_BUFFER_TYPE_SIGN_ONLY; iov[1].buffer.length = header.length; iov[1].buffer.value = header.data; } else { iov[1].type = GSS_IOV_BUFFER_TYPE_EMPTY; iov[1].buffer.length = 0; iov[1].buffer.value = NULL; } iov[2].type = GSS_IOV_BUFFER_TYPE_DATA; iov[2].buffer.length = token.length; iov[2].buffer.value = token.data; if (trailer.length != 0) { iov[3].type = GSS_IOV_BUFFER_TYPE_SIGN_ONLY; iov[3].buffer.length = trailer.length; iov[3].buffer.value = trailer.data; } else { iov[3].type = GSS_IOV_BUFFER_TYPE_EMPTY; iov[3].buffer.length = 0; iov[3].buffer.value = NULL; } if (dce_style_flag) { iov[4].type = GSS_IOV_BUFFER_TYPE_EMPTY; } else { iov[4].type = GSS_IOV_BUFFER_TYPE_PADDING | GSS_IOV_BUFFER_TYPE_FLAG_ALLOCATE; } iov[4].buffer.length = 0; iov[4].buffer.value = 0; if (dce_style_flag) { iov[5].type = GSS_IOV_BUFFER_TYPE_EMPTY; } else if (flags & USE_HEADER_ONLY) { iov[5].type = GSS_IOV_BUFFER_TYPE_EMPTY; } else { iov[5].type = GSS_IOV_BUFFER_TYPE_TRAILER | GSS_IOV_BUFFER_TYPE_FLAG_ALLOCATE; } iov[5].buffer.length = 0; iov[5].buffer.value = 0; maj_stat = gss_wrap_iov(&min_stat, cctx, dce_style_flag || flags & USE_CONF, 0, &conf_state, iov, iov_len); if (maj_stat != GSS_S_COMPLETE) errx(1, "gss_wrap_iov failed"); token.length = iov[0].buffer.length + iov[1].buffer.length + iov[2].buffer.length + iov[3].buffer.length + iov[4].buffer.length + iov[5].buffer.length; token.data = emalloc(token.length); p = token.data; memcpy(p, iov[0].buffer.value, iov[0].buffer.length); p += iov[0].buffer.length; memcpy(p, iov[1].buffer.value, iov[1].buffer.length); p += iov[1].buffer.length; memcpy(p, iov[2].buffer.value, iov[2].buffer.length); p += iov[2].buffer.length; memcpy(p, iov[3].buffer.value, iov[3].buffer.length); p += iov[3].buffer.length; memcpy(p, iov[4].buffer.value, iov[4].buffer.length); p += iov[4].buffer.length; memcpy(p, iov[5].buffer.value, iov[5].buffer.length); p += iov[5].buffer.length; assert(p - ((unsigned char *)token.data) == token.length); if ((flags & (USE_SIGN_ONLY|FORCE_IOV)) == 0) { gss_buffer_desc input, output; input.value = token.data; input.length = token.length; maj_stat = gss_unwrap(&min_stat, sctx, &input, &output, &conf_state2, &qop_state); if (maj_stat != GSS_S_COMPLETE) errx(1, "gss_unwrap from gss_wrap_iov failed: %s", gssapi_err(maj_stat, min_stat, mechoid)); gss_release_buffer(&min_stat, &output); } else { maj_stat = gss_unwrap_iov(&min_stat, sctx, &conf_state2, &qop_state, iov, iov_len); if (maj_stat != GSS_S_COMPLETE) errx(1, "gss_unwrap_iov failed: %x %s", flags, gssapi_err(maj_stat, min_stat, mechoid)); } if (conf_state2 != conf_state) errx(1, "conf state wrong for iov: %x", flags); gss_release_iov_buffer(&min_stat, iov, iov_len); free(token.data); } static void wrapunwrap_aead(gss_ctx_id_t cctx, gss_ctx_id_t sctx, int flags, gss_OID mechoid) { gss_buffer_desc token, assoc, message = GSS_C_EMPTY_BUFFER; gss_buffer_desc output; OM_uint32 min_stat, maj_stat; gss_qop_t qop_state; int conf_state, conf_state2; char assoc_data[9] = "ABCheader"; char token_data[16] = "0123456789abcdef"; if (flags & USE_SIGN_ONLY) { assoc.value = assoc_data; assoc.length = 9; } else { assoc.value = NULL; assoc.length = 0; } token.value = token_data; token.length = 16; maj_stat = gss_wrap_aead(&min_stat, cctx, dce_style_flag || flags & USE_CONF, GSS_C_QOP_DEFAULT, &assoc, &token, &conf_state, &message); if (maj_stat != GSS_S_COMPLETE) errx(1, "gss_wrap_aead failed"); if ((flags & (USE_SIGN_ONLY|FORCE_IOV)) == 0) { maj_stat = gss_unwrap(&min_stat, sctx, &message, &output, &conf_state2, &qop_state); if (maj_stat != GSS_S_COMPLETE) errx(1, "gss_unwrap from gss_wrap_aead failed: %s", gssapi_err(maj_stat, min_stat, mechoid)); } else { maj_stat = gss_unwrap_aead(&min_stat, sctx, &message, &assoc, &output, &conf_state2, &qop_state); if (maj_stat != GSS_S_COMPLETE) errx(1, "gss_unwrap_aead failed: %x %s", flags, gssapi_err(maj_stat, min_stat, mechoid)); } if (output.length != token.length) errx(1, "plaintext length wrong for aead"); else if (memcmp(output.value, token.value, token.length) != 0) errx(1, "plaintext wrong for aead"); if (conf_state2 != conf_state) errx(1, "conf state wrong for aead: %x", flags); gss_release_buffer(&min_stat, &message); gss_release_buffer(&min_stat, &output); } static void getverifymic(gss_ctx_id_t cctx, gss_ctx_id_t sctx, gss_OID mechoid) { gss_buffer_desc input_token, output_token; OM_uint32 min_stat, maj_stat; gss_qop_t qop_state; input_token.value = "bar"; input_token.length = 3; maj_stat = gss_get_mic(&min_stat, cctx, 0, &input_token, &output_token); if (maj_stat != GSS_S_COMPLETE) errx(1, "gss_get_mic failed: %s", gssapi_err(maj_stat, min_stat, mechoid)); maj_stat = gss_verify_mic(&min_stat, sctx, &input_token, &output_token, &qop_state); if (maj_stat != GSS_S_COMPLETE) errx(1, "gss_verify_mic failed: %s", gssapi_err(maj_stat, min_stat, mechoid)); gss_release_buffer(&min_stat, &output_token); } static void empty_release(void) { gss_ctx_id_t ctx = GSS_C_NO_CONTEXT; gss_cred_id_t cred = GSS_C_NO_CREDENTIAL; gss_name_t name = GSS_C_NO_NAME; gss_OID_set oidset = GSS_C_NO_OID_SET; OM_uint32 junk; gss_delete_sec_context(&junk, &ctx, NULL); gss_release_cred(&junk, &cred); gss_release_name(&junk, &name); gss_release_oid_set(&junk, &oidset); } /* * */ static struct getargs args[] = { {"name-type",0, arg_string, &type_string, "type of name", NULL }, {"mech-type",0, arg_string, &mech_string, "mech type (name)", NULL }, {"mech-types",0, arg_string, &mechs_string, "mech types (names)", NULL }, {"ret-mech-type",0, arg_string, &ret_mech_string, "type of return mech", NULL }, {"dns-canonicalize",0,arg_negative_flag, &dns_canon_flag, "use dns to canonicalize", NULL }, {"mutual-auth",0, arg_flag, &mutual_auth_flag,"mutual auth", NULL }, {"client-name", 0, arg_string, &client_name, "client name", NULL }, {"client-password", 0, arg_string, &client_password, "client password", NULL }, {"limit-enctype",0, arg_string, &limit_enctype_string, "enctype", NULL }, {"dce-style",0, arg_flag, &dce_style_flag, "dce-style", NULL }, {"wrapunwrap",0, arg_flag, &wrapunwrap_flag, "wrap/unwrap", NULL }, {"iov", 0, arg_flag, &iov_flag, "wrap/unwrap iov", NULL }, {"aead", 0, arg_flag, &aead_flag, "wrap/unwrap aead", NULL }, {"getverifymic",0, arg_flag, &getverifymic_flag, "get and verify mic", NULL }, {"delegate",0, arg_flag, &deleg_flag, "delegate credential", NULL }, {"policy-delegate",0, arg_flag, &policy_deleg_flag, "policy delegate credential", NULL }, {"server-no-delegate",0, arg_flag, &server_no_deleg_flag, "server should get a credential", NULL }, {"export-import-cred",0, arg_flag, &ei_flag, "test export/import cred", NULL }, {"gsskrb5-acceptor-identity", 0, arg_string, &gsskrb5_acceptor_identity, "keytab", NULL }, {"session-enctype", 0, arg_string, &session_enctype_string, "enctype", NULL }, {"client-time-offset", 0, arg_integer, &client_time_offset, "time", NULL }, {"server-time-offset", 0, arg_integer, &server_time_offset, "time", NULL }, {"max-loops", 0, arg_integer, &max_loops, "time", NULL }, {"version", 0, arg_flag, &version_flag, "print version", NULL }, {"verbose", 'v', arg_flag, &verbose_flag, "verbose", NULL }, {"help", 0, arg_flag, &help_flag, NULL, NULL } }; static void usage (int ret) { arg_printusage (args, sizeof(args)/sizeof(*args), NULL, "service@host"); exit (ret); } int main(int argc, char **argv) { int optidx = 0; OM_uint32 min_stat, maj_stat; gss_ctx_id_t cctx, sctx; void *ctx; gss_OID nameoid, mechoid, actual_mech, actual_mech2; gss_cred_id_t client_cred = GSS_C_NO_CREDENTIAL, deleg_cred = GSS_C_NO_CREDENTIAL; gss_name_t cname = GSS_C_NO_NAME; gss_buffer_desc credential_data = GSS_C_EMPTY_BUFFER; gss_OID_desc oids[4]; gss_OID_set_desc mechoid_descs; gss_OID_set mechoids = GSS_C_NO_OID_SET; setprogname(argv[0]); init_o2n(); if (krb5_init_context(&context)) errx(1, "krb5_init_context"); cctx = sctx = GSS_C_NO_CONTEXT; if(getarg(args, sizeof(args) / sizeof(args[0]), argc, argv, &optidx)) usage(1); if (help_flag) usage (0); if(version_flag){ print_version(NULL); exit(0); } argc -= optidx; argv += optidx; if (argc != 1) usage(1); if (dns_canon_flag != -1) gsskrb5_set_dns_canonicalize(dns_canon_flag); if (type_string == NULL) nameoid = GSS_C_NT_HOSTBASED_SERVICE; else if (strcmp(type_string, "hostbased-service") == 0) nameoid = GSS_C_NT_HOSTBASED_SERVICE; else if (strcmp(type_string, "krb5-principal-name") == 0) nameoid = GSS_KRB5_NT_PRINCIPAL_NAME; else errx(1, "%s not supported", type_string); if (mech_string == NULL) mechoid = GSS_KRB5_MECHANISM; else mechoid = string_to_oid(mech_string); if (mechs_string == NULL) { /* * We ought to be able to use the OID set of the one mechanism * OID given. But there's some breakage that conspires to make * that fail though it should succeed: * * - the NTLM gss_acquire_cred() refuses to work with * desired_name == GSS_C_NO_NAME * - gss_acquire_cred() with desired_mechs == GSS_C_NO_OID_SET * does work here because we happen to have Kerberos * credentials in check-ntlm, and the subsequent * gss_init_sec_context() call finds no cred element for NTLM * but plows on anyways, surprisingly enough, and then the * NTLM gss_init_sec_context() just works. * * In summary, there's some breakage in gss_init_sec_context() * and some breakage in NTLM that conspires against us here. * * We work around this in check-ntlm and check-spnego by adding * --client-name=user1@${R} to the invocations of this test * program that require it. */ oids[0] = *mechoid; mechoid_descs.elements = &oids[0]; mechoid_descs.count = 1; mechoids = &mechoid_descs; } else { string_to_oids(&mechoids, &mechoid_descs, oids, sizeof(oids)/sizeof(oids[0]), mechs_string); } if (gsskrb5_acceptor_identity) { maj_stat = gsskrb5_register_acceptor_identity(gsskrb5_acceptor_identity); if (maj_stat) errx(1, "gsskrb5_acceptor_identity: %s", gssapi_err(maj_stat, 0, GSS_C_NO_OID)); } if (client_password) { credential_data.value = client_password; credential_data.length = strlen(client_password); } if (client_name) { gss_buffer_desc cn; cn.value = client_name; cn.length = strlen(client_name); maj_stat = gss_import_name(&min_stat, &cn, GSS_C_NT_USER_NAME, &cname); if (maj_stat) errx(1, "gss_import_name: %s", gssapi_err(maj_stat, min_stat, GSS_C_NO_OID)); } if (client_password) { maj_stat = gss_acquire_cred_with_password(&min_stat, cname, &credential_data, GSS_C_INDEFINITE, mechoids, GSS_C_INITIATE, &client_cred, NULL, NULL); if (GSS_ERROR(maj_stat)) { if (mechoids != GSS_C_NO_OID_SET && mechoids->count == 1) mechoid = &mechoids->elements[0]; else mechoid = GSS_C_NO_OID; errx(1, "gss_acquire_cred_with_password: %s", gssapi_err(maj_stat, min_stat, mechoid)); } } else { maj_stat = gss_acquire_cred(&min_stat, cname, GSS_C_INDEFINITE, mechoids, GSS_C_INITIATE, &client_cred, NULL, NULL); if (GSS_ERROR(maj_stat)) errx(1, "gss_acquire_cred: %s", gssapi_err(maj_stat, min_stat, GSS_C_NO_OID)); } if (limit_enctype_string) { krb5_error_code ret; ret = krb5_string_to_enctype(context, limit_enctype_string, &limit_enctype); if (ret) krb5_err(context, 1, ret, "krb5_string_to_enctype"); } if (limit_enctype) { if (client_cred == NULL) errx(1, "client_cred missing"); maj_stat = gss_krb5_set_allowable_enctypes(&min_stat, client_cred, 1, &limit_enctype); if (maj_stat) errx(1, "gss_krb5_set_allowable_enctypes: %s", gssapi_err(maj_stat, min_stat, GSS_C_NO_OID)); } loop(mechoid, nameoid, argv[0], client_cred, &sctx, &cctx, &actual_mech, &deleg_cred); if (verbose_flag) printf("resulting mech: %s\n", oid_to_string(actual_mech)); if (ret_mech_string) { gss_OID retoid; retoid = string_to_oid(ret_mech_string); if (gss_oid_equal(retoid, actual_mech) == 0) errx(1, "actual_mech mech is not the expected type %s", ret_mech_string); } /* XXX should be actual_mech */ if (gss_oid_equal(mechoid, GSS_KRB5_MECHANISM)) { time_t sc_time; gss_buffer_desc authz_data; gss_buffer_desc in, out1, out2; krb5_keyblock *keyblock, *keyblock2; krb5_timestamp now; krb5_error_code ret; ret = krb5_timeofday(context, &now); if (ret) errx(1, "krb5_timeofday failed"); /* client */ maj_stat = gss_krb5_export_lucid_sec_context(&min_stat, &cctx, 1, /* version */ &ctx); if (maj_stat != GSS_S_COMPLETE) errx(1, "gss_krb5_export_lucid_sec_context failed: %s", gssapi_err(maj_stat, min_stat, actual_mech)); maj_stat = gss_krb5_free_lucid_sec_context(&maj_stat, ctx); if (maj_stat != GSS_S_COMPLETE) errx(1, "gss_krb5_free_lucid_sec_context failed: %s", gssapi_err(maj_stat, min_stat, actual_mech)); /* server */ maj_stat = gss_krb5_export_lucid_sec_context(&min_stat, &sctx, 1, /* version */ &ctx); if (maj_stat != GSS_S_COMPLETE) errx(1, "gss_krb5_export_lucid_sec_context failed: %s", gssapi_err(maj_stat, min_stat, actual_mech)); maj_stat = gss_krb5_free_lucid_sec_context(&min_stat, ctx); if (maj_stat != GSS_S_COMPLETE) errx(1, "gss_krb5_free_lucid_sec_context failed: %s", gssapi_err(maj_stat, min_stat, actual_mech)); maj_stat = gsskrb5_extract_authtime_from_sec_context(&min_stat, sctx, &sc_time); if (maj_stat != GSS_S_COMPLETE) errx(1, "gsskrb5_extract_authtime_from_sec_context failed: %s", gssapi_err(maj_stat, min_stat, actual_mech)); if (sc_time > now) errx(1, "gsskrb5_extract_authtime_from_sec_context failed: " "time authtime is before now: %ld %ld", (long)sc_time, (long)now); maj_stat = gsskrb5_extract_service_keyblock(&min_stat, sctx, &keyblock); if (maj_stat != GSS_S_COMPLETE) errx(1, "gsskrb5_export_service_keyblock failed: %s", gssapi_err(maj_stat, min_stat, actual_mech)); krb5_free_keyblock(context, keyblock); maj_stat = gsskrb5_get_subkey(&min_stat, sctx, &keyblock); if (maj_stat != GSS_S_COMPLETE && (!(maj_stat == GSS_S_FAILURE && min_stat == GSS_KRB5_S_KG_NO_SUBKEY))) errx(1, "gsskrb5_get_subkey server failed: %s", gssapi_err(maj_stat, min_stat, actual_mech)); if (maj_stat != GSS_S_COMPLETE) keyblock = NULL; else if (limit_enctype && keyblock->keytype != limit_enctype) errx(1, "gsskrb5_get_subkey wrong enctype"); maj_stat = gsskrb5_get_subkey(&min_stat, cctx, &keyblock2); if (maj_stat != GSS_S_COMPLETE && (!(maj_stat == GSS_S_FAILURE && min_stat == GSS_KRB5_S_KG_NO_SUBKEY))) errx(1, "gsskrb5_get_subkey client failed: %s", gssapi_err(maj_stat, min_stat, actual_mech)); if (maj_stat != GSS_S_COMPLETE) keyblock2 = NULL; else if (limit_enctype && keyblock->keytype != limit_enctype) errx(1, "gsskrb5_get_subkey wrong enctype"); if (keyblock || keyblock2) { if (keyblock == NULL) errx(1, "server missing token keyblock"); if (keyblock2 == NULL) errx(1, "client missing token keyblock"); if (keyblock->keytype != keyblock2->keytype) errx(1, "enctype mismatch"); if (keyblock->keyvalue.length != keyblock2->keyvalue.length) errx(1, "key length mismatch"); if (memcmp(keyblock->keyvalue.data, keyblock2->keyvalue.data, keyblock2->keyvalue.length) != 0) errx(1, "key data mismatch"); } if (session_enctype_string) { krb5_enctype enctype; ret = krb5_string_to_enctype(context, session_enctype_string, &enctype); if (ret) krb5_err(context, 1, ret, "krb5_string_to_enctype"); if (enctype != keyblock->keytype) errx(1, "keytype is not the expected %d != %d", (int)enctype, (int)keyblock2->keytype); } if (keyblock) krb5_free_keyblock(context, keyblock); if (keyblock2) krb5_free_keyblock(context, keyblock2); maj_stat = gsskrb5_get_initiator_subkey(&min_stat, sctx, &keyblock); if (maj_stat != GSS_S_COMPLETE && (!(maj_stat == GSS_S_FAILURE && min_stat == GSS_KRB5_S_KG_NO_SUBKEY))) errx(1, "gsskrb5_get_initiator_subkey failed: %s", gssapi_err(maj_stat, min_stat, actual_mech)); if (maj_stat == GSS_S_COMPLETE) { if (limit_enctype && keyblock->keytype != limit_enctype) errx(1, "gsskrb5_get_initiator_subkey wrong enctype"); krb5_free_keyblock(context, keyblock); } maj_stat = gsskrb5_extract_authz_data_from_sec_context(&min_stat, sctx, 128, &authz_data); if (maj_stat == GSS_S_COMPLETE) gss_release_buffer(&min_stat, &authz_data); memset(&out1, 0, sizeof(out1)); memset(&out2, 0, sizeof(out2)); in.value = "foo"; in.length = 3; gss_pseudo_random(&min_stat, sctx, GSS_C_PRF_KEY_FULL, &in, 100, &out1); gss_pseudo_random(&min_stat, cctx, GSS_C_PRF_KEY_FULL, &in, 100, &out2); if (out1.length != out2.length) errx(1, "prf len mismatch"); if (memcmp(out1.value, out2.value, out1.length) != 0) errx(1, "prf data mismatch"); gss_release_buffer(&min_stat, &out1); gss_pseudo_random(&min_stat, sctx, GSS_C_PRF_KEY_FULL, &in, 100, &out1); if (out1.length != out2.length) errx(1, "prf len mismatch"); if (memcmp(out1.value, out2.value, out1.length) != 0) errx(1, "prf data mismatch"); gss_release_buffer(&min_stat, &out1); gss_release_buffer(&min_stat, &out2); in.value = "bar"; in.length = 3; gss_pseudo_random(&min_stat, sctx, GSS_C_PRF_KEY_PARTIAL, &in, 100, &out1); gss_pseudo_random(&min_stat, cctx, GSS_C_PRF_KEY_PARTIAL, &in, 100, &out2); if (out1.length != out2.length) errx(1, "prf len mismatch"); if (memcmp(out1.value, out2.value, out1.length) != 0) errx(1, "prf data mismatch"); gss_release_buffer(&min_stat, &out1); gss_release_buffer(&min_stat, &out2); wrapunwrap_flag = 1; getverifymic_flag = 1; } if (wrapunwrap_flag) { wrapunwrap(cctx, sctx, 0, actual_mech); wrapunwrap(cctx, sctx, 1, actual_mech); wrapunwrap(sctx, cctx, 0, actual_mech); wrapunwrap(sctx, cctx, 1, actual_mech); } if (iov_flag) { wrapunwrap_iov(cctx, sctx, 0, actual_mech); wrapunwrap_iov(cctx, sctx, USE_HEADER_ONLY|FORCE_IOV, actual_mech); wrapunwrap_iov(cctx, sctx, USE_HEADER_ONLY, actual_mech); wrapunwrap_iov(cctx, sctx, USE_CONF, actual_mech); wrapunwrap_iov(cctx, sctx, USE_CONF|USE_HEADER_ONLY, actual_mech); wrapunwrap_iov(cctx, sctx, FORCE_IOV, actual_mech); wrapunwrap_iov(cctx, sctx, USE_CONF|FORCE_IOV, actual_mech); wrapunwrap_iov(cctx, sctx, USE_HEADER_ONLY|FORCE_IOV, actual_mech); wrapunwrap_iov(cctx, sctx, USE_CONF|USE_HEADER_ONLY|FORCE_IOV, actual_mech); wrapunwrap_iov(cctx, sctx, USE_SIGN_ONLY|FORCE_IOV, actual_mech); wrapunwrap_iov(cctx, sctx, USE_CONF|USE_SIGN_ONLY|FORCE_IOV, actual_mech); wrapunwrap_iov(cctx, sctx, USE_CONF|USE_HEADER_ONLY|USE_SIGN_ONLY|FORCE_IOV, actual_mech); /* works */ wrapunwrap_iov(cctx, sctx, 0, actual_mech); wrapunwrap_iov(cctx, sctx, FORCE_IOV, actual_mech); wrapunwrap_iov(cctx, sctx, USE_CONF, actual_mech); wrapunwrap_iov(cctx, sctx, USE_CONF|FORCE_IOV, actual_mech); wrapunwrap_iov(cctx, sctx, USE_SIGN_ONLY, actual_mech); wrapunwrap_iov(cctx, sctx, USE_SIGN_ONLY|FORCE_IOV, actual_mech); wrapunwrap_iov(cctx, sctx, USE_CONF|USE_SIGN_ONLY, actual_mech); wrapunwrap_iov(cctx, sctx, USE_CONF|USE_SIGN_ONLY|FORCE_IOV, actual_mech); wrapunwrap_iov(cctx, sctx, USE_HEADER_ONLY, actual_mech); wrapunwrap_iov(cctx, sctx, USE_HEADER_ONLY|FORCE_IOV, actual_mech); wrapunwrap_iov(cctx, sctx, USE_CONF|USE_HEADER_ONLY, actual_mech); wrapunwrap_iov(cctx, sctx, USE_CONF|USE_HEADER_ONLY|FORCE_IOV, actual_mech); } if (aead_flag) { wrapunwrap_aead(cctx, sctx, 0, actual_mech); wrapunwrap_aead(cctx, sctx, USE_CONF, actual_mech); wrapunwrap_aead(cctx, sctx, FORCE_IOV, actual_mech); wrapunwrap_aead(cctx, sctx, USE_CONF|FORCE_IOV, actual_mech); wrapunwrap_aead(cctx, sctx, USE_SIGN_ONLY|FORCE_IOV, actual_mech); wrapunwrap_aead(cctx, sctx, USE_CONF|USE_SIGN_ONLY|FORCE_IOV, actual_mech); wrapunwrap_aead(cctx, sctx, 0, actual_mech); wrapunwrap_aead(cctx, sctx, FORCE_IOV, actual_mech); wrapunwrap_aead(cctx, sctx, USE_CONF, actual_mech); wrapunwrap_aead(cctx, sctx, USE_CONF|FORCE_IOV, actual_mech); wrapunwrap_aead(cctx, sctx, USE_SIGN_ONLY, actual_mech); wrapunwrap_aead(cctx, sctx, USE_SIGN_ONLY|FORCE_IOV, actual_mech); wrapunwrap_aead(cctx, sctx, USE_CONF|USE_SIGN_ONLY, actual_mech); wrapunwrap_aead(cctx, sctx, USE_CONF|USE_SIGN_ONLY|FORCE_IOV, actual_mech); } if (getverifymic_flag) { getverifymic(cctx, sctx, actual_mech); getverifymic(cctx, sctx, actual_mech); getverifymic(sctx, cctx, actual_mech); getverifymic(sctx, cctx, actual_mech); } gss_delete_sec_context(&min_stat, &cctx, NULL); gss_delete_sec_context(&min_stat, &sctx, NULL); if (deleg_cred != GSS_C_NO_CREDENTIAL) { gss_cred_id_t cred2 = GSS_C_NO_CREDENTIAL; gss_buffer_desc cb; if (verbose_flag) printf("checking actual mech (%s) on delegated cred\n", oid_to_string(actual_mech)); loop(actual_mech, nameoid, argv[0], deleg_cred, &sctx, &cctx, &actual_mech2, &cred2); gss_delete_sec_context(&min_stat, &cctx, NULL); gss_delete_sec_context(&min_stat, &sctx, NULL); gss_release_cred(&min_stat, &cred2); #if 0 /* * XXX We can't do this. Delegated credentials only work with * the actual_mech. We could gss_store_cred the delegated * credentials *then* gss_add/acquire_cred() with SPNEGO, then * we could try loop() with those credentials. */ /* try again using SPNEGO */ if (verbose_flag) printf("checking spnego on delegated cred\n"); loop(GSS_SPNEGO_MECHANISM, nameoid, argv[0], deleg_cred, &sctx, &cctx, &actual_mech2, &cred2); gss_delete_sec_context(&min_stat, &cctx, NULL); gss_delete_sec_context(&min_stat, &sctx, NULL); gss_release_cred(&min_stat, &cred2); #endif /* check export/import */ if (ei_flag) { maj_stat = gss_export_cred(&min_stat, deleg_cred, &cb); if (maj_stat != GSS_S_COMPLETE) errx(1, "export failed: %s", gssapi_err(maj_stat, min_stat, NULL)); maj_stat = gss_import_cred(&min_stat, &cb, &cred2); if (maj_stat != GSS_S_COMPLETE) errx(1, "import failed: %s", gssapi_err(maj_stat, min_stat, NULL)); gss_release_buffer(&min_stat, &cb); gss_release_cred(&min_stat, &deleg_cred); if (verbose_flag) printf("checking actual mech (%s) on export/imported cred\n", oid_to_string(actual_mech)); loop(actual_mech, nameoid, argv[0], cred2, &sctx, &cctx, &actual_mech2, &deleg_cred); gss_release_cred(&min_stat, &deleg_cred); gss_delete_sec_context(&min_stat, &cctx, NULL); gss_delete_sec_context(&min_stat, &sctx, NULL); #if 0 /* XXX See above */ /* try again using SPNEGO */ if (verbose_flag) printf("checking SPNEGO on export/imported cred\n"); loop(GSS_SPNEGO_MECHANISM, nameoid, argv[0], cred2, &sctx, &cctx, &actual_mech2, &deleg_cred); gss_release_cred(&min_stat, &deleg_cred); gss_delete_sec_context(&min_stat, &cctx, NULL); gss_delete_sec_context(&min_stat, &sctx, NULL); #endif gss_release_cred(&min_stat, &cred2); } else { gss_release_cred(&min_stat, &deleg_cred); } } empty_release(); krb5_free_context(context); return 0; } heimdal-7.5.0/lib/gssapi/Makefile.in0000644000175000017500000031325213212444521015357 0ustar niknik# Makefile.in generated by automake 1.15.1 from Makefile.am. # @configure_input@ # Copyright (C) 1994-2017 Free Software Foundation, Inc. # This Makefile.in is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, # with or without modifications, as long as this notice is preserved. # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY, to the extent permitted by law; without # even the implied warranty of MERCHANTABILITY or FITNESS FOR A # PARTICULAR PURPOSE. @SET_MAKE@ # $Id$ # $Id$ # $Id$ VPATH = @srcdir@ am__is_gnu_make = { \ if test -z '$(MAKELEVEL)'; then \ false; \ elif test -n '$(MAKE_HOST)'; then \ true; \ elif test -n '$(MAKE_VERSION)' && test -n '$(CURDIR)'; then \ true; \ else \ false; \ fi; \ } am__make_running_with_option = \ case $${target_option-} in \ ?) ;; \ *) echo "am__make_running_with_option: internal error: invalid" \ "target option '$${target_option-}' specified" >&2; \ exit 1;; \ esac; \ has_opt=no; \ sane_makeflags=$$MAKEFLAGS; \ if $(am__is_gnu_make); then \ sane_makeflags=$$MFLAGS; \ else \ case $$MAKEFLAGS in \ *\\[\ \ ]*) \ bs=\\; \ sane_makeflags=`printf '%s\n' "$$MAKEFLAGS" \ | sed "s/$$bs$$bs[$$bs $$bs ]*//g"`;; \ esac; \ fi; \ skip_next=no; \ strip_trailopt () \ { \ flg=`printf '%s\n' "$$flg" | sed "s/$$1.*$$//"`; \ }; \ for flg in $$sane_makeflags; do \ test $$skip_next = yes && { skip_next=no; continue; }; \ case $$flg in \ *=*|--*) continue;; \ -*I) strip_trailopt 'I'; skip_next=yes;; \ -*I?*) strip_trailopt 'I';; \ -*O) strip_trailopt 'O'; skip_next=yes;; \ -*O?*) strip_trailopt 'O';; \ -*l) strip_trailopt 'l'; skip_next=yes;; \ -*l?*) strip_trailopt 'l';; \ -[dEDm]) skip_next=yes;; \ -[JT]) skip_next=yes;; \ esac; \ case $$flg in \ *$$target_option*) has_opt=yes; break;; \ esac; \ done; \ test $$has_opt = yes am__make_dryrun = (target_option=n; $(am__make_running_with_option)) am__make_keepgoing = (target_option=k; $(am__make_running_with_option)) pkgdatadir = $(datadir)/@PACKAGE@ pkgincludedir = $(includedir)/@PACKAGE@ pkglibdir = $(libdir)/@PACKAGE@ pkglibexecdir = $(libexecdir)/@PACKAGE@ am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd install_sh_DATA = $(install_sh) -c -m 644 install_sh_PROGRAM = $(install_sh) -c install_sh_SCRIPT = $(install_sh) -c INSTALL_HEADER = $(INSTALL_DATA) transform = $(program_transform_name) NORMAL_INSTALL = : PRE_INSTALL = : POST_INSTALL = : NORMAL_UNINSTALL = : PRE_UNINSTALL = : POST_UNINSTALL = : build_triplet = @build@ host_triplet = @host@ @versionscript_TRUE@am__append_1 = $(LDFLAGS_VERSION_SCRIPT)$(srcdir)/version-script.map TESTS = test_oid$(EXEEXT) test_names$(EXEEXT) test_cfx$(EXEEXT) check_PROGRAMS = test_acquire_cred$(EXEEXT) $(am__EXEEXT_1) bin_PROGRAMS = gsstool$(EXEEXT) noinst_PROGRAMS = test_cred$(EXEEXT) test_kcred$(EXEEXT) \ test_context$(EXEEXT) test_ntlm$(EXEEXT) \ test_add_store_cred$(EXEEXT) subdir = lib/gssapi ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 am__aclocal_m4_deps = $(top_srcdir)/cf/aix.m4 \ $(top_srcdir)/cf/auth-modules.m4 \ $(top_srcdir)/cf/broken-getaddrinfo.m4 \ $(top_srcdir)/cf/broken-glob.m4 \ $(top_srcdir)/cf/broken-realloc.m4 \ $(top_srcdir)/cf/broken-snprintf.m4 $(top_srcdir)/cf/broken.m4 \ $(top_srcdir)/cf/broken2.m4 $(top_srcdir)/cf/c-attribute.m4 \ $(top_srcdir)/cf/capabilities.m4 \ $(top_srcdir)/cf/check-compile-et.m4 \ $(top_srcdir)/cf/check-getpwnam_r-posix.m4 \ $(top_srcdir)/cf/check-man.m4 \ $(top_srcdir)/cf/check-netinet-ip-and-tcp.m4 \ $(top_srcdir)/cf/check-type-extra.m4 \ $(top_srcdir)/cf/check-var.m4 $(top_srcdir)/cf/crypto.m4 \ $(top_srcdir)/cf/db.m4 $(top_srcdir)/cf/destdirs.m4 \ $(top_srcdir)/cf/dispatch.m4 $(top_srcdir)/cf/dlopen.m4 \ $(top_srcdir)/cf/find-func-no-libs.m4 \ $(top_srcdir)/cf/find-func-no-libs2.m4 \ $(top_srcdir)/cf/find-func.m4 \ $(top_srcdir)/cf/find-if-not-broken.m4 \ $(top_srcdir)/cf/framework-security.m4 \ $(top_srcdir)/cf/have-struct-field.m4 \ $(top_srcdir)/cf/have-type.m4 $(top_srcdir)/cf/irix.m4 \ $(top_srcdir)/cf/krb-bigendian.m4 \ $(top_srcdir)/cf/krb-func-getlogin.m4 \ $(top_srcdir)/cf/krb-ipv6.m4 $(top_srcdir)/cf/krb-prog-ln-s.m4 \ $(top_srcdir)/cf/krb-prog-perl.m4 \ $(top_srcdir)/cf/krb-readline.m4 \ $(top_srcdir)/cf/krb-struct-spwd.m4 \ $(top_srcdir)/cf/krb-struct-winsize.m4 \ $(top_srcdir)/cf/largefile.m4 $(top_srcdir)/cf/libtool.m4 \ $(top_srcdir)/cf/ltoptions.m4 $(top_srcdir)/cf/ltsugar.m4 \ $(top_srcdir)/cf/ltversion.m4 $(top_srcdir)/cf/lt~obsolete.m4 \ $(top_srcdir)/cf/mips-abi.m4 $(top_srcdir)/cf/misc.m4 \ $(top_srcdir)/cf/need-proto.m4 $(top_srcdir)/cf/osfc2.m4 \ $(top_srcdir)/cf/otp.m4 $(top_srcdir)/cf/pkg.m4 \ $(top_srcdir)/cf/proto-compat.m4 $(top_srcdir)/cf/pthreads.m4 \ $(top_srcdir)/cf/resolv.m4 $(top_srcdir)/cf/retsigtype.m4 \ $(top_srcdir)/cf/roken-frag.m4 \ $(top_srcdir)/cf/socket-wrapper.m4 $(top_srcdir)/cf/sunos.m4 \ $(top_srcdir)/cf/telnet.m4 $(top_srcdir)/cf/test-package.m4 \ $(top_srcdir)/cf/version-script.m4 $(top_srcdir)/cf/wflags.m4 \ $(top_srcdir)/cf/win32.m4 $(top_srcdir)/cf/with-all.m4 \ $(top_srcdir)/acinclude.m4 $(top_srcdir)/configure.ac am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \ $(ACLOCAL_M4) DIST_COMMON = $(srcdir)/Makefile.am $(include_HEADERS) \ $(nobase_include_HEADERS) $(noinst_HEADERS) $(am__DIST_COMMON) mkinstalldirs = $(install_sh) -d CONFIG_HEADER = $(top_builddir)/include/config.h CONFIG_CLEAN_FILES = CONFIG_CLEAN_VPATH_FILES = am__vpath_adj_setup = srcdirstrip=`echo "$(srcdir)" | sed 's|.|.|g'`; am__vpath_adj = case $$p in \ $(srcdir)/*) f=`echo "$$p" | sed "s|^$$srcdirstrip/||"`;; \ *) f=$$p;; \ esac; am__strip_dir = f=`echo $$p | sed -e 's|^.*/||'`; am__install_max = 40 am__nobase_strip_setup = \ srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*|]/\\\\&/g'` am__nobase_strip = \ for p in $$list; do echo "$$p"; done | sed -e "s|$$srcdirstrip/||" am__nobase_list = $(am__nobase_strip_setup); \ for p in $$list; do echo "$$p $$p"; done | \ sed "s| $$srcdirstrip/| |;"' / .*\//!s/ .*/ ./; s,\( .*\)/[^/]*$$,\1,' | \ $(AWK) 'BEGIN { files["."] = "" } { files[$$2] = files[$$2] " " $$1; \ if (++n[$$2] == $(am__install_max)) \ { print $$2, files[$$2]; n[$$2] = 0; files[$$2] = "" } } \ END { for (dir in files) print dir, files[dir] }' am__base_list = \ sed '$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;s/\n/ /g' | \ sed '$$!N;$$!N;$$!N;$$!N;s/\n/ /g' am__uninstall_files_from_dir = { \ test -z "$$files" \ || { test ! -d "$$dir" && test ! -f "$$dir" && test ! -r "$$dir"; } \ || { echo " ( cd '$$dir' && rm -f" $$files ")"; \ $(am__cd) "$$dir" && rm -f $$files; }; \ } am__installdirs = "$(DESTDIR)$(libdir)" "$(DESTDIR)$(bindir)" \ "$(DESTDIR)$(man3dir)" "$(DESTDIR)$(man5dir)" \ "$(DESTDIR)$(includedir)" "$(DESTDIR)$(includedir)" \ "$(DESTDIR)$(gssapidir)" LTLIBRARIES = $(lib_LTLIBRARIES) am__DEPENDENCIES_1 = am__dirstamp = $(am__leading_dot)dirstamp am__objects_1 = krb5/8003.lo krb5/accept_sec_context.lo \ krb5/acquire_cred.lo krb5/add_cred.lo \ krb5/address_to_krb5addr.lo krb5/aeap.lo krb5/arcfour.lo \ krb5/canonicalize_name.lo krb5/creds.lo krb5/ccache_name.lo \ krb5/cfx.lo krb5/compare_name.lo krb5/compat.lo \ krb5/context_time.lo krb5/copy_ccache.lo krb5/decapsulate.lo \ krb5/delete_sec_context.lo krb5/display_name.lo \ krb5/display_status.lo krb5/duplicate_name.lo \ krb5/encapsulate.lo krb5/export_name.lo \ krb5/export_sec_context.lo krb5/external.lo krb5/get_mic.lo \ krb5/import_name.lo krb5/import_sec_context.lo \ krb5/indicate_mechs.lo krb5/init.lo krb5/init_sec_context.lo \ krb5/inquire_context.lo krb5/inquire_cred.lo \ krb5/inquire_cred_by_mech.lo krb5/inquire_cred_by_oid.lo \ krb5/inquire_mechs_for_name.lo krb5/inquire_names_for_mech.lo \ krb5/inquire_sec_context_by_oid.lo krb5/pname_to_uid.lo \ krb5/process_context_token.lo krb5/prf.lo \ krb5/release_buffer.lo krb5/release_cred.lo \ krb5/release_name.lo krb5/sequence.lo krb5/store_cred.lo \ krb5/set_cred_option.lo krb5/set_sec_context_option.lo \ krb5/ticket_flags.lo krb5/unwrap.lo \ krb5/authorize_localname.lo krb5/verify_mic.lo krb5/wrap.lo am__objects_2 = mech/context.lo mech/doxygen.lo \ mech/gss_accept_sec_context.lo mech/gss_acquire_cred.lo \ mech/gss_acquire_cred_ext.lo \ mech/gss_acquire_cred_with_password.lo mech/gss_add_cred.lo \ mech/gss_add_cred_with_password.lo \ mech/gss_add_oid_set_member.lo mech/gss_aeap.lo \ mech/gss_buffer_set.lo mech/gss_canonicalize_name.lo \ mech/gss_compare_name.lo mech/gss_context_time.lo \ mech/gss_create_empty_oid_set.lo mech/gss_cred.lo \ mech/gss_decapsulate_token.lo \ mech/gss_delete_name_attribute.lo \ mech/gss_delete_sec_context.lo mech/gss_display_name.lo \ mech/gss_display_name_ext.lo mech/gss_display_status.lo \ mech/gss_duplicate_name.lo mech/gss_duplicate_oid.lo \ mech/gss_encapsulate_token.lo mech/gss_export_name.lo \ mech/gss_export_name_composite.lo \ mech/gss_export_sec_context.lo mech/gss_get_mic.lo \ mech/gss_get_name_attribute.lo mech/gss_import_name.lo \ mech/gss_import_sec_context.lo mech/gss_indicate_mechs.lo \ mech/gss_init_sec_context.lo mech/gss_inquire_context.lo \ mech/gss_inquire_cred.lo mech/gss_inquire_cred_by_mech.lo \ mech/gss_inquire_cred_by_oid.lo \ mech/gss_inquire_mechs_for_name.lo mech/gss_inquire_name.lo \ mech/gss_inquire_names_for_mech.lo mech/gss_krb5.lo \ mech/gss_mech_switch.lo mech/gss_mo.lo mech/gss_names.lo \ mech/gss_oid.lo mech/gss_oid_equal.lo mech/gss_oid_to_str.lo \ mech/gss_pname_to_uid.lo mech/gss_process_context_token.lo \ mech/gss_pseudo_random.lo mech/gss_release_buffer.lo \ mech/gss_release_cred.lo mech/gss_release_name.lo \ mech/gss_release_oid.lo mech/gss_release_oid_set.lo \ mech/gss_seal.lo mech/gss_set_cred_option.lo \ mech/gss_set_name_attribute.lo \ mech/gss_set_sec_context_option.lo mech/gss_sign.lo \ mech/gss_store_cred.lo mech/gss_test_oid_set_member.lo \ mech/gss_unseal.lo mech/gss_unwrap.lo \ mech/gss_authorize_localname.lo mech/gss_utils.lo \ mech/gss_verify.lo mech/gss_verify_mic.lo mech/gss_wrap.lo \ mech/gss_wrap_size_limit.lo \ mech/gss_inquire_sec_context_by_oid.lo am__objects_3 = ntlm/accept_sec_context.lo ntlm/acquire_cred.lo \ ntlm/add_cred.lo ntlm/canonicalize_name.lo \ ntlm/compare_name.lo ntlm/context_time.lo ntlm/creds.lo \ ntlm/crypto.lo ntlm/delete_sec_context.lo ntlm/display_name.lo \ ntlm/display_status.lo ntlm/duplicate_name.lo \ ntlm/export_name.lo ntlm/export_sec_context.lo \ ntlm/external.lo ntlm/import_name.lo \ ntlm/import_sec_context.lo ntlm/indicate_mechs.lo \ ntlm/init_sec_context.lo ntlm/inquire_context.lo \ ntlm/inquire_cred_by_mech.lo ntlm/inquire_mechs_for_name.lo \ ntlm/inquire_names_for_mech.lo \ ntlm/inquire_sec_context_by_oid.lo ntlm/iter_cred.lo \ ntlm/process_context_token.lo ntlm/release_cred.lo \ ntlm/release_name.lo ntlm/kdc.lo am__objects_4 = spnego/accept_sec_context.lo spnego/compat.lo \ spnego/context_stubs.lo spnego/cred_stubs.lo \ spnego/external.lo spnego/init_sec_context.lo dist_libgssapi_la_OBJECTS = $(am__objects_1) $(am__objects_2) \ $(am__objects_3) $(am__objects_4) am__objects_5 = asn1_ContextFlags.lo asn1_MechType.lo \ asn1_MechTypeList.lo asn1_NegotiationToken.lo \ asn1_NegotiationTokenWin.lo asn1_NegHints.lo \ asn1_NegTokenInit.lo asn1_NegTokenInitWin.lo \ asn1_NegTokenResp.lo am__objects_6 = asn1_GSSAPIContextToken.lo am__objects_7 = $(am__objects_5) $(am__objects_6) nodist_libgssapi_la_OBJECTS = gkrb5_err.lo $(am__objects_7) libgssapi_la_OBJECTS = $(dist_libgssapi_la_OBJECTS) \ $(nodist_libgssapi_la_OBJECTS) AM_V_lt = $(am__v_lt_@AM_V@) am__v_lt_ = $(am__v_lt_@AM_DEFAULT_V@) am__v_lt_0 = --silent am__v_lt_1 = libgssapi_la_LINK = $(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) \ $(LIBTOOLFLAGS) --mode=link $(CCLD) $(AM_CFLAGS) $(CFLAGS) \ $(libgssapi_la_LDFLAGS) $(LDFLAGS) -o $@ am__EXEEXT_1 = test_oid$(EXEEXT) test_names$(EXEEXT) test_cfx$(EXEEXT) PROGRAMS = $(bin_PROGRAMS) $(noinst_PROGRAMS) dist_gsstool_OBJECTS = gsstool.$(OBJEXT) nodist_gsstool_OBJECTS = gss-commands.$(OBJEXT) gsstool_OBJECTS = $(dist_gsstool_OBJECTS) $(nodist_gsstool_OBJECTS) gsstool_DEPENDENCIES = libgssapi.la $(top_builddir)/lib/sl/libsl.la \ $(top_builddir)/lib/krb5/libkrb5.la $(am__DEPENDENCIES_1) \ $(am__DEPENDENCIES_1) am_test_acquire_cred_OBJECTS = test_acquire_cred.$(OBJEXT) \ test_common.$(OBJEXT) test_acquire_cred_OBJECTS = $(am_test_acquire_cred_OBJECTS) test_acquire_cred_LDADD = $(LDADD) test_acquire_cred_DEPENDENCIES = libgssapi.la \ $(top_builddir)/lib/krb5/libkrb5.la $(am__DEPENDENCIES_1) am_test_add_store_cred_OBJECTS = test_add_store_cred.$(OBJEXT) test_add_store_cred_OBJECTS = $(am_test_add_store_cred_OBJECTS) test_add_store_cred_LDADD = $(LDADD) test_add_store_cred_DEPENDENCIES = libgssapi.la \ $(top_builddir)/lib/krb5/libkrb5.la $(am__DEPENDENCIES_1) am_test_cfx_OBJECTS = krb5/test_cfx.$(OBJEXT) test_cfx_OBJECTS = $(am_test_cfx_OBJECTS) test_cfx_LDADD = $(LDADD) test_cfx_DEPENDENCIES = libgssapi.la \ $(top_builddir)/lib/krb5/libkrb5.la $(am__DEPENDENCIES_1) am_test_context_OBJECTS = test_context.$(OBJEXT) test_common.$(OBJEXT) test_context_OBJECTS = $(am_test_context_OBJECTS) test_context_LDADD = $(LDADD) test_context_DEPENDENCIES = libgssapi.la \ $(top_builddir)/lib/krb5/libkrb5.la $(am__DEPENDENCIES_1) test_cred_SOURCES = test_cred.c test_cred_OBJECTS = test_cred.$(OBJEXT) test_cred_LDADD = $(LDADD) test_cred_DEPENDENCIES = libgssapi.la \ $(top_builddir)/lib/krb5/libkrb5.la $(am__DEPENDENCIES_1) test_kcred_SOURCES = test_kcred.c test_kcred_OBJECTS = test_kcred.$(OBJEXT) test_kcred_LDADD = $(LDADD) test_kcred_DEPENDENCIES = libgssapi.la \ $(top_builddir)/lib/krb5/libkrb5.la $(am__DEPENDENCIES_1) test_names_SOURCES = test_names.c test_names_OBJECTS = test_names.$(OBJEXT) test_names_LDADD = $(LDADD) test_names_DEPENDENCIES = libgssapi.la \ $(top_builddir)/lib/krb5/libkrb5.la $(am__DEPENDENCIES_1) am_test_ntlm_OBJECTS = test_ntlm.$(OBJEXT) test_common.$(OBJEXT) test_ntlm_OBJECTS = $(am_test_ntlm_OBJECTS) am__DEPENDENCIES_2 = libgssapi.la $(top_builddir)/lib/krb5/libkrb5.la \ $(am__DEPENDENCIES_1) test_ntlm_DEPENDENCIES = $(top_builddir)/lib/ntlm/libheimntlm.la \ $(am__DEPENDENCIES_2) test_oid_SOURCES = test_oid.c test_oid_OBJECTS = test_oid.$(OBJEXT) test_oid_LDADD = $(LDADD) test_oid_DEPENDENCIES = libgssapi.la \ $(top_builddir)/lib/krb5/libkrb5.la $(am__DEPENDENCIES_1) AM_V_P = $(am__v_P_@AM_V@) am__v_P_ = $(am__v_P_@AM_DEFAULT_V@) am__v_P_0 = false am__v_P_1 = : AM_V_GEN = $(am__v_GEN_@AM_V@) am__v_GEN_ = $(am__v_GEN_@AM_DEFAULT_V@) am__v_GEN_0 = @echo " GEN " $@; am__v_GEN_1 = AM_V_at = $(am__v_at_@AM_V@) am__v_at_ = $(am__v_at_@AM_DEFAULT_V@) am__v_at_0 = @ am__v_at_1 = depcomp = $(SHELL) $(top_srcdir)/depcomp am__depfiles_maybe = depfiles am__mv = mv -f COMPILE = $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) \ $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) LTCOMPILE = $(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) \ $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) \ $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) \ $(AM_CFLAGS) $(CFLAGS) AM_V_CC = $(am__v_CC_@AM_V@) am__v_CC_ = $(am__v_CC_@AM_DEFAULT_V@) am__v_CC_0 = @echo " CC " $@; am__v_CC_1 = CCLD = $(CC) LINK = $(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) \ $(LIBTOOLFLAGS) --mode=link $(CCLD) $(AM_CFLAGS) $(CFLAGS) \ $(AM_LDFLAGS) $(LDFLAGS) -o $@ AM_V_CCLD = $(am__v_CCLD_@AM_V@) am__v_CCLD_ = $(am__v_CCLD_@AM_DEFAULT_V@) am__v_CCLD_0 = @echo " CCLD " $@; am__v_CCLD_1 = SOURCES = $(dist_libgssapi_la_SOURCES) $(nodist_libgssapi_la_SOURCES) \ $(dist_gsstool_SOURCES) $(nodist_gsstool_SOURCES) \ $(test_acquire_cred_SOURCES) $(test_add_store_cred_SOURCES) \ $(test_cfx_SOURCES) $(test_context_SOURCES) test_cred.c \ test_kcred.c test_names.c $(test_ntlm_SOURCES) test_oid.c DIST_SOURCES = $(dist_libgssapi_la_SOURCES) $(dist_gsstool_SOURCES) \ $(test_acquire_cred_SOURCES) $(test_add_store_cred_SOURCES) \ $(test_cfx_SOURCES) $(test_context_SOURCES) test_cred.c \ test_kcred.c test_names.c $(test_ntlm_SOURCES) test_oid.c am__can_run_installinfo = \ case $$AM_UPDATE_INFO_DIR in \ n|no|NO) false;; \ *) (install-info --version) >/dev/null 2>&1;; \ esac man3dir = $(mandir)/man3 man5dir = $(mandir)/man5 MANS = $(man_MANS) HEADERS = $(include_HEADERS) $(nobase_include_HEADERS) \ $(nodist_gssapi_HEADERS) $(noinst_HEADERS) am__tagged_files = $(HEADERS) $(SOURCES) $(TAGS_FILES) $(LISP) # Read a list of newline-separated strings from the standard input, # and print each of them once, without duplicates. Input order is # *not* preserved. am__uniquify_input = $(AWK) '\ BEGIN { nonempty = 0; } \ { items[$$0] = 1; nonempty = 1; } \ END { if (nonempty) { for (i in items) print i; }; } \ ' # Make sure the list of sources is unique. This is necessary because, # e.g., the same source file might be shared among _SOURCES variables # for different programs/libraries. am__define_uniq_tagged_files = \ list='$(am__tagged_files)'; \ unique=`for i in $$list; do \ if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ done | $(am__uniquify_input)` ETAGS = etags CTAGS = ctags am__tty_colors_dummy = \ mgn= red= grn= lgn= blu= brg= std=; \ am__color_tests=no am__tty_colors = { \ $(am__tty_colors_dummy); \ if test "X$(AM_COLOR_TESTS)" = Xno; then \ am__color_tests=no; \ elif test "X$(AM_COLOR_TESTS)" = Xalways; then \ am__color_tests=yes; \ elif test "X$$TERM" != Xdumb && { test -t 1; } 2>/dev/null; then \ am__color_tests=yes; \ fi; \ if test $$am__color_tests = yes; then \ red=''; \ grn=''; \ lgn=''; \ blu=''; \ mgn=''; \ brg=''; \ std=''; \ fi; \ } am__recheck_rx = ^[ ]*:recheck:[ ]* am__global_test_result_rx = ^[ ]*:global-test-result:[ ]* am__copy_in_global_log_rx = ^[ ]*:copy-in-global-log:[ ]* # A command that, given a newline-separated list of test names on the # standard input, print the name of the tests that are to be re-run # upon "make recheck". am__list_recheck_tests = $(AWK) '{ \ recheck = 1; \ while ((rc = (getline line < ($$0 ".trs"))) != 0) \ { \ if (rc < 0) \ { \ if ((getline line2 < ($$0 ".log")) < 0) \ recheck = 0; \ break; \ } \ else if (line ~ /$(am__recheck_rx)[nN][Oo]/) \ { \ recheck = 0; \ break; \ } \ else if (line ~ /$(am__recheck_rx)[yY][eE][sS]/) \ { \ break; \ } \ }; \ if (recheck) \ print $$0; \ close ($$0 ".trs"); \ close ($$0 ".log"); \ }' # A command that, given a newline-separated list of test names on the # standard input, create the global log from their .trs and .log files. am__create_global_log = $(AWK) ' \ function fatal(msg) \ { \ print "fatal: making $@: " msg | "cat >&2"; \ exit 1; \ } \ function rst_section(header) \ { \ print header; \ len = length(header); \ for (i = 1; i <= len; i = i + 1) \ printf "="; \ printf "\n\n"; \ } \ { \ copy_in_global_log = 1; \ global_test_result = "RUN"; \ while ((rc = (getline line < ($$0 ".trs"))) != 0) \ { \ if (rc < 0) \ fatal("failed to read from " $$0 ".trs"); \ if (line ~ /$(am__global_test_result_rx)/) \ { \ sub("$(am__global_test_result_rx)", "", line); \ sub("[ ]*$$", "", line); \ global_test_result = line; \ } \ else if (line ~ /$(am__copy_in_global_log_rx)[nN][oO]/) \ copy_in_global_log = 0; \ }; \ if (copy_in_global_log) \ { \ rst_section(global_test_result ": " $$0); \ while ((rc = (getline line < ($$0 ".log"))) != 0) \ { \ if (rc < 0) \ fatal("failed to read from " $$0 ".log"); \ print line; \ }; \ printf "\n"; \ }; \ close ($$0 ".trs"); \ close ($$0 ".log"); \ }' # Restructured Text title. am__rst_title = { sed 's/.*/ & /;h;s/./=/g;p;x;s/ *$$//;p;g' && echo; } # Solaris 10 'make', and several other traditional 'make' implementations, # pass "-e" to $(SHELL), and POSIX 2008 even requires this. Work around it # by disabling -e (using the XSI extension "set +e") if it's set. am__sh_e_setup = case $$- in *e*) set +e;; esac # Default flags passed to test drivers. am__common_driver_flags = \ --color-tests "$$am__color_tests" \ --enable-hard-errors "$$am__enable_hard_errors" \ --expect-failure "$$am__expect_failure" # To be inserted before the command running the test. Creates the # directory for the log if needed. Stores in $dir the directory # containing $f, in $tst the test, in $log the log. Executes the # developer- defined test setup AM_TESTS_ENVIRONMENT (if any), and # passes TESTS_ENVIRONMENT. Set up options for the wrapper that # will run the test scripts (or their associated LOG_COMPILER, if # thy have one). am__check_pre = \ $(am__sh_e_setup); \ $(am__vpath_adj_setup) $(am__vpath_adj) \ $(am__tty_colors); \ srcdir=$(srcdir); export srcdir; \ case "$@" in \ */*) am__odir=`echo "./$@" | sed 's|/[^/]*$$||'`;; \ *) am__odir=.;; \ esac; \ test "x$$am__odir" = x"." || test -d "$$am__odir" \ || $(MKDIR_P) "$$am__odir" || exit $$?; \ if test -f "./$$f"; then dir=./; \ elif test -f "$$f"; then dir=; \ else dir="$(srcdir)/"; fi; \ tst=$$dir$$f; log='$@'; \ if test -n '$(DISABLE_HARD_ERRORS)'; then \ am__enable_hard_errors=no; \ else \ am__enable_hard_errors=yes; \ fi; \ case " $(XFAIL_TESTS) " in \ *[\ \ ]$$f[\ \ ]* | *[\ \ ]$$dir$$f[\ \ ]*) \ am__expect_failure=yes;; \ *) \ am__expect_failure=no;; \ esac; \ $(AM_TESTS_ENVIRONMENT) $(TESTS_ENVIRONMENT) # A shell command to get the names of the tests scripts with any registered # extension removed (i.e., equivalently, the names of the test logs, with # the '.log' extension removed). The result is saved in the shell variable # '$bases'. This honors runtime overriding of TESTS and TEST_LOGS. Sadly, # we cannot use something simpler, involving e.g., "$(TEST_LOGS:.log=)", # since that might cause problem with VPATH rewrites for suffix-less tests. # See also 'test-harness-vpath-rewrite.sh' and 'test-trs-basic.sh'. am__set_TESTS_bases = \ bases='$(TEST_LOGS)'; \ bases=`for i in $$bases; do echo $$i; done | sed 's/\.log$$//'`; \ bases=`echo $$bases` RECHECK_LOGS = $(TEST_LOGS) AM_RECURSIVE_TARGETS = check recheck TEST_SUITE_LOG = test-suite.log TEST_EXTENSIONS = @EXEEXT@ .test LOG_DRIVER = $(SHELL) $(top_srcdir)/test-driver LOG_COMPILE = $(LOG_COMPILER) $(AM_LOG_FLAGS) $(LOG_FLAGS) am__set_b = \ case '$@' in \ */*) \ case '$*' in \ */*) b='$*';; \ *) b=`echo '$@' | sed 's/\.log$$//'`; \ esac;; \ *) \ b='$*';; \ esac am__test_logs1 = $(TESTS:=.log) am__test_logs2 = $(am__test_logs1:@EXEEXT@.log=.log) TEST_LOGS = $(am__test_logs2:.test.log=.log) TEST_LOG_DRIVER = $(SHELL) $(top_srcdir)/test-driver TEST_LOG_COMPILE = $(TEST_LOG_COMPILER) $(AM_TEST_LOG_FLAGS) \ $(TEST_LOG_FLAGS) am__DIST_COMMON = $(srcdir)/Makefile.in \ $(top_srcdir)/Makefile.am.common \ $(top_srcdir)/cf/Makefile.am.common $(top_srcdir)/depcomp \ $(top_srcdir)/test-driver ChangeLog DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST) ACLOCAL = @ACLOCAL@ AIX_EXTRA_KAFS = @AIX_EXTRA_KAFS@ AMTAR = @AMTAR@ AM_DEFAULT_VERBOSITY = @AM_DEFAULT_VERBOSITY@ AR = @AR@ AS = @AS@ ASN1_COMPILE = @ASN1_COMPILE@ ASN1_COMPILE_DEP = @ASN1_COMPILE_DEP@ AUTOCONF = @AUTOCONF@ AUTOHEADER = @AUTOHEADER@ AUTOMAKE = @AUTOMAKE@ AWK = @AWK@ CANONICAL_HOST = @CANONICAL_HOST@ CAPNG_CFLAGS = @CAPNG_CFLAGS@ CAPNG_LIBS = @CAPNG_LIBS@ CATMAN = @CATMAN@ CATMANEXT = @CATMANEXT@ CC = @CC@ CCDEPMODE = @CCDEPMODE@ CFLAGS = @CFLAGS@ COMPILE_ET = @COMPILE_ET@ CPP = @CPP@ CPPFLAGS = @CPPFLAGS@ CYGPATH_W = @CYGPATH_W@ DB1LIB = @DB1LIB@ DB3LIB = @DB3LIB@ DBHEADER = @DBHEADER@ DEFS = @DEFS@ DEPDIR = @DEPDIR@ DIR_com_err = @DIR_com_err@ DIR_hdbdir = @DIR_hdbdir@ DIR_roken = @DIR_roken@ DLLTOOL = @DLLTOOL@ DSYMUTIL = @DSYMUTIL@ DUMPBIN = @DUMPBIN@ ECHO_C = @ECHO_C@ ECHO_N = @ECHO_N@ ECHO_T = @ECHO_T@ EGREP = @EGREP@ ENABLE_AFS_STRING_TO_KEY = @ENABLE_AFS_STRING_TO_KEY@ EXEEXT = @EXEEXT@ FGREP = @FGREP@ GCD_MIG = @GCD_MIG@ GREP = @GREP@ GROFF = @GROFF@ INCLUDES_roken = @INCLUDES_roken@ INCLUDE_libedit = @INCLUDE_libedit@ INCLUDE_libintl = @INCLUDE_libintl@ INCLUDE_openldap = @INCLUDE_openldap@ INCLUDE_openssl_crypto = @INCLUDE_openssl_crypto@ INCLUDE_readline = @INCLUDE_readline@ INCLUDE_sqlite3 = @INCLUDE_sqlite3@ INSTALL = @INSTALL@ INSTALL_DATA = @INSTALL_DATA@ INSTALL_PROGRAM = @INSTALL_PROGRAM@ INSTALL_SCRIPT = @INSTALL_SCRIPT@ INSTALL_STRIP_PROGRAM = @INSTALL_STRIP_PROGRAM@ LD = @LD@ LDFLAGS = @LDFLAGS@ LDFLAGS_VERSION_SCRIPT = @LDFLAGS_VERSION_SCRIPT@ LEX = @LEX@ LEXLIB = @LEXLIB@ LEX_OUTPUT_ROOT = @LEX_OUTPUT_ROOT@ LIBADD_roken = @LIBADD_roken@ LIBOBJS = @LIBOBJS@ LIBS = @LIBS@ LIBTOOL = @LIBTOOL@ LIB_AUTH_SUBDIRS = @LIB_AUTH_SUBDIRS@ LIB_bswap16 = @LIB_bswap16@ LIB_bswap32 = @LIB_bswap32@ LIB_bswap64 = @LIB_bswap64@ LIB_com_err = @LIB_com_err@ LIB_com_err_a = @LIB_com_err_a@ LIB_com_err_so = @LIB_com_err_so@ LIB_crypt = @LIB_crypt@ LIB_db_create = @LIB_db_create@ LIB_dbm_firstkey = @LIB_dbm_firstkey@ LIB_dbopen = @LIB_dbopen@ LIB_dispatch_async_f = @LIB_dispatch_async_f@ LIB_dladdr = @LIB_dladdr@ LIB_dlopen = @LIB_dlopen@ LIB_dn_expand = @LIB_dn_expand@ LIB_dns_search = @LIB_dns_search@ LIB_door_create = @LIB_door_create@ LIB_freeaddrinfo = @LIB_freeaddrinfo@ LIB_gai_strerror = @LIB_gai_strerror@ LIB_getaddrinfo = @LIB_getaddrinfo@ LIB_gethostbyname = @LIB_gethostbyname@ LIB_gethostbyname2 = @LIB_gethostbyname2@ LIB_getnameinfo = @LIB_getnameinfo@ LIB_getpwnam_r = @LIB_getpwnam_r@ LIB_getsockopt = @LIB_getsockopt@ LIB_hcrypto = @LIB_hcrypto@ LIB_hcrypto_a = @LIB_hcrypto_a@ LIB_hcrypto_appl = @LIB_hcrypto_appl@ LIB_hcrypto_so = @LIB_hcrypto_so@ LIB_hstrerror = @LIB_hstrerror@ LIB_kdb = @LIB_kdb@ LIB_libedit = @LIB_libedit@ LIB_libintl = @LIB_libintl@ LIB_loadquery = @LIB_loadquery@ LIB_logout = @LIB_logout@ LIB_logwtmp = @LIB_logwtmp@ LIB_openldap = @LIB_openldap@ LIB_openpty = @LIB_openpty@ LIB_openssl_crypto = @LIB_openssl_crypto@ LIB_otp = @LIB_otp@ LIB_pidfile = @LIB_pidfile@ LIB_readline = @LIB_readline@ LIB_res_ndestroy = @LIB_res_ndestroy@ LIB_res_nsearch = @LIB_res_nsearch@ LIB_res_search = @LIB_res_search@ LIB_roken = @LIB_roken@ LIB_security = @LIB_security@ LIB_setsockopt = @LIB_setsockopt@ LIB_socket = @LIB_socket@ LIB_sqlite3 = @LIB_sqlite3@ LIB_syslog = @LIB_syslog@ LIB_tgetent = @LIB_tgetent@ LIPO = @LIPO@ LMDBLIB = @LMDBLIB@ LN_S = @LN_S@ LTLIBOBJS = @LTLIBOBJS@ LT_SYS_LIBRARY_PATH = @LT_SYS_LIBRARY_PATH@ MAINT = @MAINT@ MAKEINFO = @MAKEINFO@ MANIFEST_TOOL = @MANIFEST_TOOL@ MKDIR_P = @MKDIR_P@ NDBMLIB = @NDBMLIB@ NM = @NM@ NMEDIT = @NMEDIT@ NO_AFS = @NO_AFS@ NROFF = @NROFF@ OBJDUMP = @OBJDUMP@ OBJEXT = @OBJEXT@ OTOOL = @OTOOL@ OTOOL64 = @OTOOL64@ PACKAGE = @PACKAGE@ PACKAGE_BUGREPORT = @PACKAGE_BUGREPORT@ PACKAGE_NAME = @PACKAGE_NAME@ PACKAGE_STRING = @PACKAGE_STRING@ PACKAGE_TARNAME = @PACKAGE_TARNAME@ PACKAGE_URL = @PACKAGE_URL@ PACKAGE_VERSION = @PACKAGE_VERSION@ PATH_SEPARATOR = @PATH_SEPARATOR@ PERL = @PERL@ PKG_CONFIG = @PKG_CONFIG@ PTHREAD_CFLAGS = @PTHREAD_CFLAGS@ PTHREAD_LDADD = @PTHREAD_LDADD@ PTHREAD_LIBADD = @PTHREAD_LIBADD@ RANLIB = @RANLIB@ SED = @SED@ SET_MAKE = @SET_MAKE@ SHELL = @SHELL@ SLC = @SLC@ SLC_DEP = @SLC_DEP@ STRIP = @STRIP@ VERSION = @VERSION@ VERSIONING = @VERSIONING@ WFLAGS = @WFLAGS@ WFLAGS_LITE = @WFLAGS_LITE@ YACC = @YACC@ YFLAGS = @YFLAGS@ abs_builddir = @abs_builddir@ abs_srcdir = @abs_srcdir@ abs_top_builddir = @abs_top_builddir@ abs_top_srcdir = @abs_top_srcdir@ ac_ct_AR = @ac_ct_AR@ ac_ct_CC = @ac_ct_CC@ ac_ct_DUMPBIN = @ac_ct_DUMPBIN@ am__include = @am__include@ am__leading_dot = @am__leading_dot@ am__quote = @am__quote@ am__tar = @am__tar@ am__untar = @am__untar@ bindir = @bindir@ build = @build@ build_alias = @build_alias@ build_cpu = @build_cpu@ build_os = @build_os@ build_vendor = @build_vendor@ builddir = @builddir@ datadir = @datadir@ datarootdir = @datarootdir@ db_type = @db_type@ db_type_preference = @db_type_preference@ docdir = @docdir@ dpagaix_cflags = @dpagaix_cflags@ dpagaix_ldadd = @dpagaix_ldadd@ dpagaix_ldflags = @dpagaix_ldflags@ dvidir = @dvidir@ exec_prefix = @exec_prefix@ host = @host@ host_alias = @host_alias@ host_cpu = @host_cpu@ host_os = @host_os@ host_vendor = @host_vendor@ htmldir = @htmldir@ includedir = @includedir@ infodir = @infodir@ install_sh = @install_sh@ libdir = @libdir@ libexecdir = @libexecdir@ localedir = @localedir@ localstatedir = @localstatedir@ mandir = @mandir@ mkdir_p = @mkdir_p@ oldincludedir = @oldincludedir@ pdfdir = @pdfdir@ prefix = @prefix@ program_transform_name = @program_transform_name@ psdir = @psdir@ sbindir = @sbindir@ sharedstatedir = @sharedstatedir@ srcdir = @srcdir@ subdirs = @subdirs@ sysconfdir = @sysconfdir@ target_alias = @target_alias@ top_build_prefix = @top_build_prefix@ top_builddir = @top_builddir@ top_srcdir = @top_srcdir@ SUFFIXES = .et .h .pc.in .pc .x .z .hx .1 .3 .5 .7 .8 .cat1 .cat3 \ .cat5 .cat7 .cat8 DEFAULT_INCLUDES = -I. -I$(srcdir) -I$(top_builddir)/include -I$(top_srcdir)/include AM_CPPFLAGS = $(INCLUDES_roken) -I$(srcdir)/../krb5 -I$(srcdir) \ -I$(srcdir)/gssapi -I$(srcdir)/mech -I$(srcdir)/ntlm \ -I$(srcdir)/krb5 -I$(srcdir)/spnego $(INCLUDE_libintl) @do_roken_rename_TRUE@ROKEN_RENAME = -DROKEN_RENAME AM_CFLAGS = $(WFLAGS) CP = cp buildinclude = $(top_builddir)/include LIB_XauReadAuth = @LIB_XauReadAuth@ LIB_el_init = @LIB_el_init@ LIB_getattr = @LIB_getattr@ LIB_getpwent_r = @LIB_getpwent_r@ LIB_odm_initialize = @LIB_odm_initialize@ LIB_setpcred = @LIB_setpcred@ INCLUDE_krb4 = @INCLUDE_krb4@ LIB_krb4 = @LIB_krb4@ libexec_heimdaldir = $(libexecdir)/heimdal NROFF_MAN = groff -mandoc -Tascii @NO_AFS_FALSE@LIB_kafs = $(top_builddir)/lib/kafs/libkafs.la $(AIX_EXTRA_KAFS) @NO_AFS_TRUE@LIB_kafs = @KRB5_TRUE@LIB_krb5 = $(top_builddir)/lib/krb5/libkrb5.la \ @KRB5_TRUE@ $(top_builddir)/lib/asn1/libasn1.la @KRB5_TRUE@LIB_gssapi = $(top_builddir)/lib/gssapi/libgssapi.la LIB_heimbase = $(top_builddir)/lib/base/libheimbase.la @DCE_TRUE@LIB_kdfs = $(top_builddir)/lib/kdfs/libkdfs.la #silent-rules heim_verbose = $(heim_verbose_$(V)) heim_verbose_ = $(heim_verbose_$(AM_DEFAULT_VERBOSITY)) heim_verbose_0 = @echo " GEN "$@; AUTOMAKE_OPTIONS = subdir-objects lib_LTLIBRARIES = libgssapi.la krb5src = \ krb5/8003.c \ krb5/accept_sec_context.c \ krb5/acquire_cred.c \ krb5/add_cred.c \ krb5/address_to_krb5addr.c \ krb5/aeap.c \ krb5/arcfour.c \ krb5/canonicalize_name.c \ krb5/creds.c \ krb5/ccache_name.c \ krb5/cfx.c \ krb5/cfx.h \ krb5/compare_name.c \ krb5/compat.c \ krb5/context_time.c \ krb5/copy_ccache.c \ krb5/decapsulate.c \ krb5/delete_sec_context.c \ krb5/display_name.c \ krb5/display_status.c \ krb5/duplicate_name.c \ krb5/encapsulate.c \ krb5/export_name.c \ krb5/export_sec_context.c \ krb5/external.c \ krb5/get_mic.c \ krb5/gsskrb5_locl.h \ $(srcdir)/krb5/gsskrb5-private.h \ krb5/import_name.c \ krb5/import_sec_context.c \ krb5/indicate_mechs.c \ krb5/init.c \ krb5/init_sec_context.c \ krb5/inquire_context.c \ krb5/inquire_cred.c \ krb5/inquire_cred_by_mech.c \ krb5/inquire_cred_by_oid.c \ krb5/inquire_mechs_for_name.c \ krb5/inquire_names_for_mech.c \ krb5/inquire_sec_context_by_oid.c \ krb5/pname_to_uid.c \ krb5/process_context_token.c \ krb5/prf.c \ krb5/release_buffer.c \ krb5/release_cred.c \ krb5/release_name.c \ krb5/sequence.c \ krb5/store_cred.c \ krb5/set_cred_option.c \ krb5/set_sec_context_option.c \ krb5/ticket_flags.c \ krb5/unwrap.c \ krb5/authorize_localname.c \ krb5/verify_mic.c \ krb5/wrap.c mechsrc = \ mech/context.h \ mech/context.c \ mech/cred.h \ mech/compat.h \ mech/doxygen.c \ mech/gss_accept_sec_context.c \ mech/gss_acquire_cred.c \ mech/gss_acquire_cred_ext.c \ mech/gss_acquire_cred_with_password.c \ mech/gss_add_cred.c \ mech/gss_add_cred_with_password.c \ mech/gss_add_oid_set_member.c \ mech/gss_aeap.c \ mech/gss_buffer_set.c \ mech/gss_canonicalize_name.c \ mech/gss_compare_name.c \ mech/gss_context_time.c \ mech/gss_create_empty_oid_set.c \ mech/gss_cred.c \ mech/gss_decapsulate_token.c \ mech/gss_delete_name_attribute.c \ mech/gss_delete_sec_context.c \ mech/gss_display_name.c \ mech/gss_display_name_ext.c \ mech/gss_display_status.c \ mech/gss_duplicate_name.c \ mech/gss_duplicate_oid.c \ mech/gss_encapsulate_token.c \ mech/gss_export_name.c \ mech/gss_export_name_composite.c \ mech/gss_export_sec_context.c \ mech/gss_get_mic.c \ mech/gss_get_name_attribute.c \ mech/gss_import_name.c \ mech/gss_import_sec_context.c \ mech/gss_indicate_mechs.c \ mech/gss_init_sec_context.c \ mech/gss_inquire_context.c \ mech/gss_inquire_cred.c \ mech/gss_inquire_cred_by_mech.c \ mech/gss_inquire_cred_by_oid.c \ mech/gss_inquire_mechs_for_name.c \ mech/gss_inquire_name.c \ mech/gss_inquire_names_for_mech.c \ mech/gss_krb5.c \ mech/gss_mech_switch.c \ mech/gss_mo.c \ mech/gss_names.c \ mech/gss_oid.c \ mech/gss_oid_equal.c \ mech/gss_oid_to_str.c \ mech/gss_pname_to_uid.c \ mech/gss_process_context_token.c \ mech/gss_pseudo_random.c \ mech/gss_release_buffer.c \ mech/gss_release_cred.c \ mech/gss_release_name.c \ mech/gss_release_oid.c \ mech/gss_release_oid_set.c \ mech/gss_seal.c \ mech/gss_set_cred_option.c \ mech/gss_set_name_attribute.c \ mech/gss_set_sec_context_option.c \ mech/gss_sign.c \ mech/gss_store_cred.c \ mech/gss_test_oid_set_member.c \ mech/gss_unseal.c \ mech/gss_unwrap.c \ mech/gss_authorize_localname.c \ mech/gss_utils.c \ mech/gss_verify.c \ mech/gss_verify_mic.c \ mech/gss_wrap.c \ mech/gss_wrap_size_limit.c \ mech/gss_inquire_sec_context_by_oid.c \ mech/mech_switch.h \ mech/mechqueue.h \ mech/mech_locl.h \ mech/name.h \ mech/utils.h spnegosrc = \ spnego/accept_sec_context.c \ spnego/compat.c \ spnego/context_stubs.c \ spnego/cred_stubs.c \ spnego/external.c \ spnego/init_sec_context.c \ spnego/spnego_locl.h \ $(srcdir)/spnego/spnego-private.h ntlmsrc = \ ntlm/accept_sec_context.c \ ntlm/acquire_cred.c \ ntlm/add_cred.c \ ntlm/canonicalize_name.c \ ntlm/compare_name.c \ ntlm/context_time.c \ ntlm/creds.c \ ntlm/crypto.c \ ntlm/delete_sec_context.c \ ntlm/display_name.c \ ntlm/display_status.c \ ntlm/duplicate_name.c \ ntlm/export_name.c \ ntlm/export_sec_context.c \ ntlm/external.c \ ntlm/ntlm.h \ ntlm/import_name.c \ ntlm/import_sec_context.c \ ntlm/indicate_mechs.c \ ntlm/init_sec_context.c \ ntlm/inquire_context.c \ ntlm/inquire_cred_by_mech.c \ ntlm/inquire_mechs_for_name.c \ ntlm/inquire_names_for_mech.c \ ntlm/inquire_sec_context_by_oid.c \ ntlm/iter_cred.c \ ntlm/process_context_token.c \ ntlm/release_cred.c \ ntlm/release_name.c \ ntlm/kdc.c dist_libgssapi_la_SOURCES = \ $(krb5src) \ $(mechsrc) \ $(ntlmsrc) \ $(spnegosrc) nodist_libgssapi_la_SOURCES = \ gkrb5_err.c \ gkrb5_err.h \ $(BUILT_SOURCES) libgssapi_la_DEPENDENCIES = version-script.map libgssapi_la_LDFLAGS = -version-info 3:0:0 $(am__append_1) libgssapi_la_LIBADD = \ $(top_builddir)/lib/ntlm/libheimntlm.la \ $(top_builddir)/lib/krb5/libkrb5.la \ $(top_builddir)/lib/asn1/libasn1.la \ $(LIB_com_err) \ $(LIB_hcrypto) \ $(LIBADD_roken) man_MANS = gssapi.3 gss_acquire_cred.3 mech/mech.5 include_HEADERS = gssapi.h noinst_HEADERS = \ gssapi_mech.h \ $(srcdir)/ntlm/ntlm-private.h \ $(srcdir)/spnego/spnego-private.h \ $(srcdir)/krb5/gsskrb5-private.h nobase_include_HEADERS = \ gssapi/gssapi.h \ gssapi/gssapi_krb5.h \ gssapi/gssapi_ntlm.h \ gssapi/gssapi_oid.h \ gssapi/gssapi_spnego.h gssapidir = $(includedir)/gssapi nodist_gssapi_HEADERS = gkrb5_err.h gssapi_files = asn1_GSSAPIContextToken.x spnego_files = \ asn1_ContextFlags.x \ asn1_MechType.x \ asn1_MechTypeList.x \ asn1_NegotiationToken.x \ asn1_NegotiationTokenWin.x \ asn1_NegHints.x \ asn1_NegTokenInit.x \ asn1_NegTokenInitWin.x \ asn1_NegTokenResp.x BUILTHEADERS = \ $(srcdir)/krb5/gsskrb5-private.h \ $(srcdir)/spnego/spnego-private.h \ $(srcdir)/ntlm/ntlm-private.h BUILT_SOURCES = $(spnego_files:.x=.c) $(gssapi_files:.x=.c) CLEANFILES = $(BUILT_SOURCES) \ gkrb5_err.h gkrb5_err.c \ $(spnego_files) spnego_asn1*.h* spnego_asn1_files spnego_asn1-template.[cx] \ $(gssapi_files) gssapi_asn1*.h* gssapi_asn1_files gssapi_asn1-template.[cx] \ gss-commands.h gss-commands.c # test_sequence test_cfx_SOURCES = krb5/test_cfx.c test_context_SOURCES = test_context.c test_common.c test_common.h test_ntlm_SOURCES = test_ntlm.c test_common.c test_common.h test_acquire_cred_SOURCES = test_acquire_cred.c test_common.c test_common.h test_add_store_cred_SOURCES = test_add_store_cred.c test_ntlm_LDADD = \ $(top_builddir)/lib/ntlm/libheimntlm.la \ $(LDADD) LDADD = libgssapi.la \ $(top_builddir)/lib/krb5/libkrb5.la \ $(LIB_roken) # gss dist_gsstool_SOURCES = gsstool.c nodist_gsstool_SOURCES = gss-commands.c gss-commands.h gsstool_LDADD = libgssapi.la \ $(top_builddir)/lib/sl/libsl.la \ $(top_builddir)/lib/krb5/libkrb5.la \ $(LIB_readline) \ $(LIB_roken) EXTRA_DIST = \ NTMakefile \ libgssapi-version.rc \ libgssapi-exports.def \ $(man_MANS) \ gen-oid.pl \ gssapi/gssapi_netlogon.h \ krb5/test_acquire_cred.c \ krb5/test_cred.c \ krb5/test_kcred.c \ krb5/test_oid.c \ oid.txt \ krb5/gkrb5_err.et \ mech/gssapi.asn1 \ spnego/spnego.asn1 \ spnego/spnego.opt \ version-script.map \ gss-commands.in all: $(BUILT_SOURCES) $(MAKE) $(AM_MAKEFLAGS) all-am .SUFFIXES: .SUFFIXES: .et .h .pc.in .pc .x .z .hx .1 .3 .5 .7 .8 .cat1 .cat3 .cat5 .cat7 .cat8 .c .lo .log .o .obj .test .test$(EXEEXT) .trs $(srcdir)/Makefile.in: @MAINTAINER_MODE_TRUE@ $(srcdir)/Makefile.am $(top_srcdir)/Makefile.am.common $(top_srcdir)/cf/Makefile.am.common $(am__configure_deps) @for dep in $?; do \ case '$(am__configure_deps)' in \ *$$dep*) \ ( cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh ) \ && { if test -f $@; then exit 0; else break; fi; }; \ exit 1;; \ esac; \ done; \ echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign lib/gssapi/Makefile'; \ $(am__cd) $(top_srcdir) && \ $(AUTOMAKE) --foreign lib/gssapi/Makefile Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status @case '$?' in \ *config.status*) \ cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh;; \ *) \ echo ' cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe)'; \ cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe);; \ esac; $(top_srcdir)/Makefile.am.common $(top_srcdir)/cf/Makefile.am.common $(am__empty): $(top_builddir)/config.status: $(top_srcdir)/configure $(CONFIG_STATUS_DEPENDENCIES) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(top_srcdir)/configure: @MAINTAINER_MODE_TRUE@ $(am__configure_deps) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(ACLOCAL_M4): @MAINTAINER_MODE_TRUE@ $(am__aclocal_m4_deps) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(am__aclocal_m4_deps): install-libLTLIBRARIES: $(lib_LTLIBRARIES) @$(NORMAL_INSTALL) @list='$(lib_LTLIBRARIES)'; test -n "$(libdir)" || list=; \ list2=; for p in $$list; do \ if test -f $$p; then \ list2="$$list2 $$p"; \ else :; fi; \ done; \ test -z "$$list2" || { \ echo " $(MKDIR_P) '$(DESTDIR)$(libdir)'"; \ $(MKDIR_P) "$(DESTDIR)$(libdir)" || exit 1; \ echo " $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=install $(INSTALL) $(INSTALL_STRIP_FLAG) $$list2 '$(DESTDIR)$(libdir)'"; \ $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=install $(INSTALL) $(INSTALL_STRIP_FLAG) $$list2 "$(DESTDIR)$(libdir)"; \ } uninstall-libLTLIBRARIES: @$(NORMAL_UNINSTALL) @list='$(lib_LTLIBRARIES)'; test -n "$(libdir)" || list=; \ for p in $$list; do \ $(am__strip_dir) \ echo " $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=uninstall rm -f '$(DESTDIR)$(libdir)/$$f'"; \ $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=uninstall rm -f "$(DESTDIR)$(libdir)/$$f"; \ done clean-libLTLIBRARIES: -test -z "$(lib_LTLIBRARIES)" || rm -f $(lib_LTLIBRARIES) @list='$(lib_LTLIBRARIES)'; \ locs=`for p in $$list; do echo $$p; done | \ sed 's|^[^/]*$$|.|; s|/[^/]*$$||; s|$$|/so_locations|' | \ sort -u`; \ test -z "$$locs" || { \ echo rm -f $${locs}; \ rm -f $${locs}; \ } krb5/$(am__dirstamp): @$(MKDIR_P) krb5 @: > krb5/$(am__dirstamp) krb5/$(DEPDIR)/$(am__dirstamp): @$(MKDIR_P) krb5/$(DEPDIR) @: > krb5/$(DEPDIR)/$(am__dirstamp) krb5/8003.lo: krb5/$(am__dirstamp) krb5/$(DEPDIR)/$(am__dirstamp) krb5/accept_sec_context.lo: krb5/$(am__dirstamp) \ krb5/$(DEPDIR)/$(am__dirstamp) krb5/acquire_cred.lo: krb5/$(am__dirstamp) \ krb5/$(DEPDIR)/$(am__dirstamp) krb5/add_cred.lo: krb5/$(am__dirstamp) krb5/$(DEPDIR)/$(am__dirstamp) krb5/address_to_krb5addr.lo: krb5/$(am__dirstamp) \ krb5/$(DEPDIR)/$(am__dirstamp) krb5/aeap.lo: krb5/$(am__dirstamp) krb5/$(DEPDIR)/$(am__dirstamp) krb5/arcfour.lo: krb5/$(am__dirstamp) krb5/$(DEPDIR)/$(am__dirstamp) krb5/canonicalize_name.lo: krb5/$(am__dirstamp) \ krb5/$(DEPDIR)/$(am__dirstamp) krb5/creds.lo: krb5/$(am__dirstamp) krb5/$(DEPDIR)/$(am__dirstamp) krb5/ccache_name.lo: krb5/$(am__dirstamp) \ krb5/$(DEPDIR)/$(am__dirstamp) krb5/cfx.lo: krb5/$(am__dirstamp) krb5/$(DEPDIR)/$(am__dirstamp) krb5/compare_name.lo: krb5/$(am__dirstamp) \ krb5/$(DEPDIR)/$(am__dirstamp) krb5/compat.lo: krb5/$(am__dirstamp) krb5/$(DEPDIR)/$(am__dirstamp) krb5/context_time.lo: krb5/$(am__dirstamp) \ krb5/$(DEPDIR)/$(am__dirstamp) krb5/copy_ccache.lo: krb5/$(am__dirstamp) \ krb5/$(DEPDIR)/$(am__dirstamp) krb5/decapsulate.lo: krb5/$(am__dirstamp) \ krb5/$(DEPDIR)/$(am__dirstamp) krb5/delete_sec_context.lo: krb5/$(am__dirstamp) \ krb5/$(DEPDIR)/$(am__dirstamp) krb5/display_name.lo: krb5/$(am__dirstamp) \ krb5/$(DEPDIR)/$(am__dirstamp) krb5/display_status.lo: krb5/$(am__dirstamp) \ krb5/$(DEPDIR)/$(am__dirstamp) krb5/duplicate_name.lo: krb5/$(am__dirstamp) \ krb5/$(DEPDIR)/$(am__dirstamp) krb5/encapsulate.lo: krb5/$(am__dirstamp) \ krb5/$(DEPDIR)/$(am__dirstamp) krb5/export_name.lo: krb5/$(am__dirstamp) \ krb5/$(DEPDIR)/$(am__dirstamp) krb5/export_sec_context.lo: krb5/$(am__dirstamp) \ krb5/$(DEPDIR)/$(am__dirstamp) krb5/external.lo: krb5/$(am__dirstamp) krb5/$(DEPDIR)/$(am__dirstamp) krb5/get_mic.lo: krb5/$(am__dirstamp) krb5/$(DEPDIR)/$(am__dirstamp) krb5/import_name.lo: krb5/$(am__dirstamp) \ krb5/$(DEPDIR)/$(am__dirstamp) krb5/import_sec_context.lo: krb5/$(am__dirstamp) \ krb5/$(DEPDIR)/$(am__dirstamp) krb5/indicate_mechs.lo: krb5/$(am__dirstamp) \ krb5/$(DEPDIR)/$(am__dirstamp) krb5/init.lo: krb5/$(am__dirstamp) krb5/$(DEPDIR)/$(am__dirstamp) krb5/init_sec_context.lo: krb5/$(am__dirstamp) \ krb5/$(DEPDIR)/$(am__dirstamp) krb5/inquire_context.lo: krb5/$(am__dirstamp) \ krb5/$(DEPDIR)/$(am__dirstamp) krb5/inquire_cred.lo: krb5/$(am__dirstamp) \ krb5/$(DEPDIR)/$(am__dirstamp) krb5/inquire_cred_by_mech.lo: krb5/$(am__dirstamp) \ krb5/$(DEPDIR)/$(am__dirstamp) krb5/inquire_cred_by_oid.lo: krb5/$(am__dirstamp) \ krb5/$(DEPDIR)/$(am__dirstamp) krb5/inquire_mechs_for_name.lo: krb5/$(am__dirstamp) \ krb5/$(DEPDIR)/$(am__dirstamp) krb5/inquire_names_for_mech.lo: krb5/$(am__dirstamp) \ krb5/$(DEPDIR)/$(am__dirstamp) krb5/inquire_sec_context_by_oid.lo: krb5/$(am__dirstamp) \ krb5/$(DEPDIR)/$(am__dirstamp) krb5/pname_to_uid.lo: krb5/$(am__dirstamp) \ krb5/$(DEPDIR)/$(am__dirstamp) krb5/process_context_token.lo: krb5/$(am__dirstamp) \ krb5/$(DEPDIR)/$(am__dirstamp) krb5/prf.lo: krb5/$(am__dirstamp) krb5/$(DEPDIR)/$(am__dirstamp) krb5/release_buffer.lo: krb5/$(am__dirstamp) \ krb5/$(DEPDIR)/$(am__dirstamp) krb5/release_cred.lo: krb5/$(am__dirstamp) \ krb5/$(DEPDIR)/$(am__dirstamp) krb5/release_name.lo: krb5/$(am__dirstamp) \ krb5/$(DEPDIR)/$(am__dirstamp) krb5/sequence.lo: krb5/$(am__dirstamp) krb5/$(DEPDIR)/$(am__dirstamp) krb5/store_cred.lo: krb5/$(am__dirstamp) \ krb5/$(DEPDIR)/$(am__dirstamp) krb5/set_cred_option.lo: krb5/$(am__dirstamp) \ krb5/$(DEPDIR)/$(am__dirstamp) krb5/set_sec_context_option.lo: krb5/$(am__dirstamp) \ krb5/$(DEPDIR)/$(am__dirstamp) krb5/ticket_flags.lo: krb5/$(am__dirstamp) \ krb5/$(DEPDIR)/$(am__dirstamp) krb5/unwrap.lo: krb5/$(am__dirstamp) krb5/$(DEPDIR)/$(am__dirstamp) krb5/authorize_localname.lo: krb5/$(am__dirstamp) \ krb5/$(DEPDIR)/$(am__dirstamp) krb5/verify_mic.lo: krb5/$(am__dirstamp) \ krb5/$(DEPDIR)/$(am__dirstamp) krb5/wrap.lo: krb5/$(am__dirstamp) krb5/$(DEPDIR)/$(am__dirstamp) mech/$(am__dirstamp): @$(MKDIR_P) mech @: > mech/$(am__dirstamp) mech/$(DEPDIR)/$(am__dirstamp): @$(MKDIR_P) mech/$(DEPDIR) @: > mech/$(DEPDIR)/$(am__dirstamp) mech/context.lo: mech/$(am__dirstamp) mech/$(DEPDIR)/$(am__dirstamp) mech/doxygen.lo: mech/$(am__dirstamp) mech/$(DEPDIR)/$(am__dirstamp) mech/gss_accept_sec_context.lo: mech/$(am__dirstamp) \ mech/$(DEPDIR)/$(am__dirstamp) mech/gss_acquire_cred.lo: mech/$(am__dirstamp) \ mech/$(DEPDIR)/$(am__dirstamp) mech/gss_acquire_cred_ext.lo: mech/$(am__dirstamp) \ mech/$(DEPDIR)/$(am__dirstamp) mech/gss_acquire_cred_with_password.lo: mech/$(am__dirstamp) \ mech/$(DEPDIR)/$(am__dirstamp) mech/gss_add_cred.lo: mech/$(am__dirstamp) \ mech/$(DEPDIR)/$(am__dirstamp) mech/gss_add_cred_with_password.lo: mech/$(am__dirstamp) \ mech/$(DEPDIR)/$(am__dirstamp) mech/gss_add_oid_set_member.lo: mech/$(am__dirstamp) \ mech/$(DEPDIR)/$(am__dirstamp) mech/gss_aeap.lo: mech/$(am__dirstamp) mech/$(DEPDIR)/$(am__dirstamp) mech/gss_buffer_set.lo: mech/$(am__dirstamp) \ mech/$(DEPDIR)/$(am__dirstamp) mech/gss_canonicalize_name.lo: mech/$(am__dirstamp) \ mech/$(DEPDIR)/$(am__dirstamp) mech/gss_compare_name.lo: mech/$(am__dirstamp) \ mech/$(DEPDIR)/$(am__dirstamp) mech/gss_context_time.lo: mech/$(am__dirstamp) \ mech/$(DEPDIR)/$(am__dirstamp) mech/gss_create_empty_oid_set.lo: mech/$(am__dirstamp) \ mech/$(DEPDIR)/$(am__dirstamp) mech/gss_cred.lo: mech/$(am__dirstamp) mech/$(DEPDIR)/$(am__dirstamp) mech/gss_decapsulate_token.lo: mech/$(am__dirstamp) \ mech/$(DEPDIR)/$(am__dirstamp) mech/gss_delete_name_attribute.lo: mech/$(am__dirstamp) \ mech/$(DEPDIR)/$(am__dirstamp) mech/gss_delete_sec_context.lo: mech/$(am__dirstamp) \ mech/$(DEPDIR)/$(am__dirstamp) mech/gss_display_name.lo: mech/$(am__dirstamp) \ mech/$(DEPDIR)/$(am__dirstamp) mech/gss_display_name_ext.lo: mech/$(am__dirstamp) \ mech/$(DEPDIR)/$(am__dirstamp) mech/gss_display_status.lo: mech/$(am__dirstamp) \ mech/$(DEPDIR)/$(am__dirstamp) mech/gss_duplicate_name.lo: mech/$(am__dirstamp) \ mech/$(DEPDIR)/$(am__dirstamp) mech/gss_duplicate_oid.lo: mech/$(am__dirstamp) \ mech/$(DEPDIR)/$(am__dirstamp) mech/gss_encapsulate_token.lo: mech/$(am__dirstamp) \ mech/$(DEPDIR)/$(am__dirstamp) mech/gss_export_name.lo: mech/$(am__dirstamp) \ mech/$(DEPDIR)/$(am__dirstamp) mech/gss_export_name_composite.lo: mech/$(am__dirstamp) \ mech/$(DEPDIR)/$(am__dirstamp) mech/gss_export_sec_context.lo: mech/$(am__dirstamp) \ mech/$(DEPDIR)/$(am__dirstamp) mech/gss_get_mic.lo: mech/$(am__dirstamp) \ mech/$(DEPDIR)/$(am__dirstamp) mech/gss_get_name_attribute.lo: mech/$(am__dirstamp) \ mech/$(DEPDIR)/$(am__dirstamp) mech/gss_import_name.lo: mech/$(am__dirstamp) \ mech/$(DEPDIR)/$(am__dirstamp) mech/gss_import_sec_context.lo: mech/$(am__dirstamp) \ mech/$(DEPDIR)/$(am__dirstamp) mech/gss_indicate_mechs.lo: mech/$(am__dirstamp) \ mech/$(DEPDIR)/$(am__dirstamp) mech/gss_init_sec_context.lo: mech/$(am__dirstamp) \ mech/$(DEPDIR)/$(am__dirstamp) mech/gss_inquire_context.lo: mech/$(am__dirstamp) \ mech/$(DEPDIR)/$(am__dirstamp) mech/gss_inquire_cred.lo: mech/$(am__dirstamp) \ mech/$(DEPDIR)/$(am__dirstamp) mech/gss_inquire_cred_by_mech.lo: mech/$(am__dirstamp) \ mech/$(DEPDIR)/$(am__dirstamp) mech/gss_inquire_cred_by_oid.lo: mech/$(am__dirstamp) \ mech/$(DEPDIR)/$(am__dirstamp) mech/gss_inquire_mechs_for_name.lo: mech/$(am__dirstamp) \ mech/$(DEPDIR)/$(am__dirstamp) mech/gss_inquire_name.lo: mech/$(am__dirstamp) \ mech/$(DEPDIR)/$(am__dirstamp) mech/gss_inquire_names_for_mech.lo: mech/$(am__dirstamp) \ mech/$(DEPDIR)/$(am__dirstamp) mech/gss_krb5.lo: mech/$(am__dirstamp) mech/$(DEPDIR)/$(am__dirstamp) mech/gss_mech_switch.lo: mech/$(am__dirstamp) \ mech/$(DEPDIR)/$(am__dirstamp) mech/gss_mo.lo: mech/$(am__dirstamp) mech/$(DEPDIR)/$(am__dirstamp) mech/gss_names.lo: mech/$(am__dirstamp) mech/$(DEPDIR)/$(am__dirstamp) mech/gss_oid.lo: mech/$(am__dirstamp) mech/$(DEPDIR)/$(am__dirstamp) mech/gss_oid_equal.lo: mech/$(am__dirstamp) \ mech/$(DEPDIR)/$(am__dirstamp) mech/gss_oid_to_str.lo: mech/$(am__dirstamp) \ mech/$(DEPDIR)/$(am__dirstamp) mech/gss_pname_to_uid.lo: mech/$(am__dirstamp) \ mech/$(DEPDIR)/$(am__dirstamp) mech/gss_process_context_token.lo: mech/$(am__dirstamp) \ mech/$(DEPDIR)/$(am__dirstamp) mech/gss_pseudo_random.lo: mech/$(am__dirstamp) \ mech/$(DEPDIR)/$(am__dirstamp) mech/gss_release_buffer.lo: mech/$(am__dirstamp) \ mech/$(DEPDIR)/$(am__dirstamp) mech/gss_release_cred.lo: mech/$(am__dirstamp) \ mech/$(DEPDIR)/$(am__dirstamp) mech/gss_release_name.lo: mech/$(am__dirstamp) \ mech/$(DEPDIR)/$(am__dirstamp) mech/gss_release_oid.lo: mech/$(am__dirstamp) \ mech/$(DEPDIR)/$(am__dirstamp) mech/gss_release_oid_set.lo: mech/$(am__dirstamp) \ mech/$(DEPDIR)/$(am__dirstamp) mech/gss_seal.lo: mech/$(am__dirstamp) mech/$(DEPDIR)/$(am__dirstamp) mech/gss_set_cred_option.lo: mech/$(am__dirstamp) \ mech/$(DEPDIR)/$(am__dirstamp) mech/gss_set_name_attribute.lo: mech/$(am__dirstamp) \ mech/$(DEPDIR)/$(am__dirstamp) mech/gss_set_sec_context_option.lo: mech/$(am__dirstamp) \ mech/$(DEPDIR)/$(am__dirstamp) mech/gss_sign.lo: mech/$(am__dirstamp) mech/$(DEPDIR)/$(am__dirstamp) mech/gss_store_cred.lo: mech/$(am__dirstamp) \ mech/$(DEPDIR)/$(am__dirstamp) mech/gss_test_oid_set_member.lo: mech/$(am__dirstamp) \ mech/$(DEPDIR)/$(am__dirstamp) mech/gss_unseal.lo: mech/$(am__dirstamp) \ mech/$(DEPDIR)/$(am__dirstamp) mech/gss_unwrap.lo: mech/$(am__dirstamp) \ mech/$(DEPDIR)/$(am__dirstamp) mech/gss_authorize_localname.lo: mech/$(am__dirstamp) \ mech/$(DEPDIR)/$(am__dirstamp) mech/gss_utils.lo: mech/$(am__dirstamp) mech/$(DEPDIR)/$(am__dirstamp) mech/gss_verify.lo: mech/$(am__dirstamp) \ mech/$(DEPDIR)/$(am__dirstamp) mech/gss_verify_mic.lo: mech/$(am__dirstamp) \ mech/$(DEPDIR)/$(am__dirstamp) mech/gss_wrap.lo: mech/$(am__dirstamp) mech/$(DEPDIR)/$(am__dirstamp) mech/gss_wrap_size_limit.lo: mech/$(am__dirstamp) \ mech/$(DEPDIR)/$(am__dirstamp) mech/gss_inquire_sec_context_by_oid.lo: mech/$(am__dirstamp) \ mech/$(DEPDIR)/$(am__dirstamp) ntlm/$(am__dirstamp): @$(MKDIR_P) ntlm @: > ntlm/$(am__dirstamp) ntlm/$(DEPDIR)/$(am__dirstamp): @$(MKDIR_P) ntlm/$(DEPDIR) @: > ntlm/$(DEPDIR)/$(am__dirstamp) ntlm/accept_sec_context.lo: ntlm/$(am__dirstamp) \ ntlm/$(DEPDIR)/$(am__dirstamp) ntlm/acquire_cred.lo: ntlm/$(am__dirstamp) \ ntlm/$(DEPDIR)/$(am__dirstamp) ntlm/add_cred.lo: ntlm/$(am__dirstamp) ntlm/$(DEPDIR)/$(am__dirstamp) ntlm/canonicalize_name.lo: ntlm/$(am__dirstamp) \ ntlm/$(DEPDIR)/$(am__dirstamp) ntlm/compare_name.lo: ntlm/$(am__dirstamp) \ ntlm/$(DEPDIR)/$(am__dirstamp) ntlm/context_time.lo: ntlm/$(am__dirstamp) \ ntlm/$(DEPDIR)/$(am__dirstamp) ntlm/creds.lo: ntlm/$(am__dirstamp) ntlm/$(DEPDIR)/$(am__dirstamp) ntlm/crypto.lo: ntlm/$(am__dirstamp) ntlm/$(DEPDIR)/$(am__dirstamp) ntlm/delete_sec_context.lo: ntlm/$(am__dirstamp) \ ntlm/$(DEPDIR)/$(am__dirstamp) ntlm/display_name.lo: ntlm/$(am__dirstamp) \ ntlm/$(DEPDIR)/$(am__dirstamp) ntlm/display_status.lo: ntlm/$(am__dirstamp) \ ntlm/$(DEPDIR)/$(am__dirstamp) ntlm/duplicate_name.lo: ntlm/$(am__dirstamp) \ ntlm/$(DEPDIR)/$(am__dirstamp) ntlm/export_name.lo: ntlm/$(am__dirstamp) \ ntlm/$(DEPDIR)/$(am__dirstamp) ntlm/export_sec_context.lo: ntlm/$(am__dirstamp) \ ntlm/$(DEPDIR)/$(am__dirstamp) ntlm/external.lo: ntlm/$(am__dirstamp) ntlm/$(DEPDIR)/$(am__dirstamp) ntlm/import_name.lo: ntlm/$(am__dirstamp) \ ntlm/$(DEPDIR)/$(am__dirstamp) ntlm/import_sec_context.lo: ntlm/$(am__dirstamp) \ ntlm/$(DEPDIR)/$(am__dirstamp) ntlm/indicate_mechs.lo: ntlm/$(am__dirstamp) \ ntlm/$(DEPDIR)/$(am__dirstamp) ntlm/init_sec_context.lo: ntlm/$(am__dirstamp) \ ntlm/$(DEPDIR)/$(am__dirstamp) ntlm/inquire_context.lo: ntlm/$(am__dirstamp) \ ntlm/$(DEPDIR)/$(am__dirstamp) ntlm/inquire_cred_by_mech.lo: ntlm/$(am__dirstamp) \ ntlm/$(DEPDIR)/$(am__dirstamp) ntlm/inquire_mechs_for_name.lo: ntlm/$(am__dirstamp) \ ntlm/$(DEPDIR)/$(am__dirstamp) ntlm/inquire_names_for_mech.lo: ntlm/$(am__dirstamp) \ ntlm/$(DEPDIR)/$(am__dirstamp) ntlm/inquire_sec_context_by_oid.lo: ntlm/$(am__dirstamp) \ ntlm/$(DEPDIR)/$(am__dirstamp) ntlm/iter_cred.lo: ntlm/$(am__dirstamp) ntlm/$(DEPDIR)/$(am__dirstamp) ntlm/process_context_token.lo: ntlm/$(am__dirstamp) \ ntlm/$(DEPDIR)/$(am__dirstamp) ntlm/release_cred.lo: ntlm/$(am__dirstamp) \ ntlm/$(DEPDIR)/$(am__dirstamp) ntlm/release_name.lo: ntlm/$(am__dirstamp) \ ntlm/$(DEPDIR)/$(am__dirstamp) ntlm/kdc.lo: ntlm/$(am__dirstamp) ntlm/$(DEPDIR)/$(am__dirstamp) spnego/$(am__dirstamp): @$(MKDIR_P) spnego @: > spnego/$(am__dirstamp) spnego/$(DEPDIR)/$(am__dirstamp): @$(MKDIR_P) spnego/$(DEPDIR) @: > spnego/$(DEPDIR)/$(am__dirstamp) spnego/accept_sec_context.lo: spnego/$(am__dirstamp) \ spnego/$(DEPDIR)/$(am__dirstamp) spnego/compat.lo: spnego/$(am__dirstamp) \ spnego/$(DEPDIR)/$(am__dirstamp) spnego/context_stubs.lo: spnego/$(am__dirstamp) \ spnego/$(DEPDIR)/$(am__dirstamp) spnego/cred_stubs.lo: spnego/$(am__dirstamp) \ spnego/$(DEPDIR)/$(am__dirstamp) spnego/external.lo: spnego/$(am__dirstamp) \ spnego/$(DEPDIR)/$(am__dirstamp) spnego/init_sec_context.lo: spnego/$(am__dirstamp) \ spnego/$(DEPDIR)/$(am__dirstamp) libgssapi.la: $(libgssapi_la_OBJECTS) $(libgssapi_la_DEPENDENCIES) $(EXTRA_libgssapi_la_DEPENDENCIES) $(AM_V_CCLD)$(libgssapi_la_LINK) -rpath $(libdir) $(libgssapi_la_OBJECTS) $(libgssapi_la_LIBADD) $(LIBS) install-binPROGRAMS: $(bin_PROGRAMS) @$(NORMAL_INSTALL) @list='$(bin_PROGRAMS)'; test -n "$(bindir)" || list=; \ if test -n "$$list"; then \ echo " $(MKDIR_P) '$(DESTDIR)$(bindir)'"; \ $(MKDIR_P) "$(DESTDIR)$(bindir)" || exit 1; \ fi; \ for p in $$list; do echo "$$p $$p"; done | \ sed 's/$(EXEEXT)$$//' | \ while read p p1; do if test -f $$p \ || test -f $$p1 \ ; then echo "$$p"; echo "$$p"; else :; fi; \ done | \ sed -e 'p;s,.*/,,;n;h' \ -e 's|.*|.|' \ -e 'p;x;s,.*/,,;s/$(EXEEXT)$$//;$(transform);s/$$/$(EXEEXT)/' | \ sed 'N;N;N;s,\n, ,g' | \ $(AWK) 'BEGIN { files["."] = ""; dirs["."] = 1 } \ { d=$$3; if (dirs[d] != 1) { print "d", d; dirs[d] = 1 } \ if ($$2 == $$4) files[d] = files[d] " " $$1; \ else { print "f", $$3 "/" $$4, $$1; } } \ END { for (d in files) print "f", d, files[d] }' | \ while read type dir files; do \ if test "$$dir" = .; then dir=; else dir=/$$dir; fi; \ test -z "$$files" || { \ echo " $(INSTALL_PROGRAM_ENV) $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=install $(INSTALL_PROGRAM) $$files '$(DESTDIR)$(bindir)$$dir'"; \ $(INSTALL_PROGRAM_ENV) $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=install $(INSTALL_PROGRAM) $$files "$(DESTDIR)$(bindir)$$dir" || exit $$?; \ } \ ; done uninstall-binPROGRAMS: @$(NORMAL_UNINSTALL) @list='$(bin_PROGRAMS)'; test -n "$(bindir)" || list=; \ files=`for p in $$list; do echo "$$p"; done | \ sed -e 'h;s,^.*/,,;s/$(EXEEXT)$$//;$(transform)' \ -e 's/$$/$(EXEEXT)/' \ `; \ test -n "$$list" || exit 0; \ echo " ( cd '$(DESTDIR)$(bindir)' && rm -f" $$files ")"; \ cd "$(DESTDIR)$(bindir)" && rm -f $$files clean-binPROGRAMS: @list='$(bin_PROGRAMS)'; test -n "$$list" || exit 0; \ echo " rm -f" $$list; \ rm -f $$list || exit $$?; \ test -n "$(EXEEXT)" || exit 0; \ list=`for p in $$list; do echo "$$p"; done | sed 's/$(EXEEXT)$$//'`; \ echo " rm -f" $$list; \ rm -f $$list clean-checkPROGRAMS: @list='$(check_PROGRAMS)'; test -n "$$list" || exit 0; \ echo " rm -f" $$list; \ rm -f $$list || exit $$?; \ test -n "$(EXEEXT)" || exit 0; \ list=`for p in $$list; do echo "$$p"; done | sed 's/$(EXEEXT)$$//'`; \ echo " rm -f" $$list; \ rm -f $$list clean-noinstPROGRAMS: @list='$(noinst_PROGRAMS)'; test -n "$$list" || exit 0; \ echo " rm -f" $$list; \ rm -f $$list || exit $$?; \ test -n "$(EXEEXT)" || exit 0; \ list=`for p in $$list; do echo "$$p"; done | sed 's/$(EXEEXT)$$//'`; \ echo " rm -f" $$list; \ rm -f $$list gsstool$(EXEEXT): $(gsstool_OBJECTS) $(gsstool_DEPENDENCIES) $(EXTRA_gsstool_DEPENDENCIES) @rm -f gsstool$(EXEEXT) $(AM_V_CCLD)$(LINK) $(gsstool_OBJECTS) $(gsstool_LDADD) $(LIBS) test_acquire_cred$(EXEEXT): $(test_acquire_cred_OBJECTS) $(test_acquire_cred_DEPENDENCIES) $(EXTRA_test_acquire_cred_DEPENDENCIES) @rm -f test_acquire_cred$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_acquire_cred_OBJECTS) $(test_acquire_cred_LDADD) $(LIBS) test_add_store_cred$(EXEEXT): $(test_add_store_cred_OBJECTS) $(test_add_store_cred_DEPENDENCIES) $(EXTRA_test_add_store_cred_DEPENDENCIES) @rm -f test_add_store_cred$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_add_store_cred_OBJECTS) $(test_add_store_cred_LDADD) $(LIBS) krb5/test_cfx.$(OBJEXT): krb5/$(am__dirstamp) \ krb5/$(DEPDIR)/$(am__dirstamp) test_cfx$(EXEEXT): $(test_cfx_OBJECTS) $(test_cfx_DEPENDENCIES) $(EXTRA_test_cfx_DEPENDENCIES) @rm -f test_cfx$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_cfx_OBJECTS) $(test_cfx_LDADD) $(LIBS) test_context$(EXEEXT): $(test_context_OBJECTS) $(test_context_DEPENDENCIES) $(EXTRA_test_context_DEPENDENCIES) @rm -f test_context$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_context_OBJECTS) $(test_context_LDADD) $(LIBS) test_cred$(EXEEXT): $(test_cred_OBJECTS) $(test_cred_DEPENDENCIES) $(EXTRA_test_cred_DEPENDENCIES) @rm -f test_cred$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_cred_OBJECTS) $(test_cred_LDADD) $(LIBS) test_kcred$(EXEEXT): $(test_kcred_OBJECTS) $(test_kcred_DEPENDENCIES) $(EXTRA_test_kcred_DEPENDENCIES) @rm -f test_kcred$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_kcred_OBJECTS) $(test_kcred_LDADD) $(LIBS) test_names$(EXEEXT): $(test_names_OBJECTS) $(test_names_DEPENDENCIES) $(EXTRA_test_names_DEPENDENCIES) @rm -f test_names$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_names_OBJECTS) $(test_names_LDADD) $(LIBS) test_ntlm$(EXEEXT): $(test_ntlm_OBJECTS) $(test_ntlm_DEPENDENCIES) $(EXTRA_test_ntlm_DEPENDENCIES) @rm -f test_ntlm$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_ntlm_OBJECTS) $(test_ntlm_LDADD) $(LIBS) test_oid$(EXEEXT): $(test_oid_OBJECTS) $(test_oid_DEPENDENCIES) $(EXTRA_test_oid_DEPENDENCIES) @rm -f test_oid$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_oid_OBJECTS) $(test_oid_LDADD) $(LIBS) mostlyclean-compile: -rm -f *.$(OBJEXT) -rm -f krb5/*.$(OBJEXT) -rm -f krb5/*.lo -rm -f mech/*.$(OBJEXT) -rm -f mech/*.lo -rm -f ntlm/*.$(OBJEXT) -rm -f ntlm/*.lo -rm -f spnego/*.$(OBJEXT) -rm -f spnego/*.lo distclean-compile: -rm -f *.tab.c @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/asn1_ContextFlags.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/asn1_GSSAPIContextToken.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/asn1_MechType.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/asn1_MechTypeList.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/asn1_NegHints.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/asn1_NegTokenInit.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/asn1_NegTokenInitWin.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/asn1_NegTokenResp.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/asn1_NegotiationToken.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/asn1_NegotiationTokenWin.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/gkrb5_err.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/gss-commands.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/gsstool.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_acquire_cred.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_add_store_cred.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_common.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_context.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_cred.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_kcred.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_names.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_ntlm.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_oid.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@krb5/$(DEPDIR)/8003.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@krb5/$(DEPDIR)/accept_sec_context.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@krb5/$(DEPDIR)/acquire_cred.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@krb5/$(DEPDIR)/add_cred.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@krb5/$(DEPDIR)/address_to_krb5addr.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@krb5/$(DEPDIR)/aeap.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@krb5/$(DEPDIR)/arcfour.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@krb5/$(DEPDIR)/authorize_localname.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@krb5/$(DEPDIR)/canonicalize_name.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@krb5/$(DEPDIR)/ccache_name.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@krb5/$(DEPDIR)/cfx.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@krb5/$(DEPDIR)/compare_name.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@krb5/$(DEPDIR)/compat.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@krb5/$(DEPDIR)/context_time.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@krb5/$(DEPDIR)/copy_ccache.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@krb5/$(DEPDIR)/creds.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@krb5/$(DEPDIR)/decapsulate.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@krb5/$(DEPDIR)/delete_sec_context.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@krb5/$(DEPDIR)/display_name.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@krb5/$(DEPDIR)/display_status.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@krb5/$(DEPDIR)/duplicate_name.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@krb5/$(DEPDIR)/encapsulate.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@krb5/$(DEPDIR)/export_name.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@krb5/$(DEPDIR)/export_sec_context.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@krb5/$(DEPDIR)/external.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@krb5/$(DEPDIR)/get_mic.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@krb5/$(DEPDIR)/import_name.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@krb5/$(DEPDIR)/import_sec_context.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@krb5/$(DEPDIR)/indicate_mechs.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@krb5/$(DEPDIR)/init.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@krb5/$(DEPDIR)/init_sec_context.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@krb5/$(DEPDIR)/inquire_context.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@krb5/$(DEPDIR)/inquire_cred.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@krb5/$(DEPDIR)/inquire_cred_by_mech.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@krb5/$(DEPDIR)/inquire_cred_by_oid.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@krb5/$(DEPDIR)/inquire_mechs_for_name.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@krb5/$(DEPDIR)/inquire_names_for_mech.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@krb5/$(DEPDIR)/inquire_sec_context_by_oid.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@krb5/$(DEPDIR)/pname_to_uid.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@krb5/$(DEPDIR)/prf.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@krb5/$(DEPDIR)/process_context_token.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@krb5/$(DEPDIR)/release_buffer.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@krb5/$(DEPDIR)/release_cred.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@krb5/$(DEPDIR)/release_name.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@krb5/$(DEPDIR)/sequence.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@krb5/$(DEPDIR)/set_cred_option.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@krb5/$(DEPDIR)/set_sec_context_option.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@krb5/$(DEPDIR)/store_cred.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@krb5/$(DEPDIR)/test_cfx.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@krb5/$(DEPDIR)/ticket_flags.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@krb5/$(DEPDIR)/unwrap.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@krb5/$(DEPDIR)/verify_mic.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@krb5/$(DEPDIR)/wrap.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@mech/$(DEPDIR)/context.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@mech/$(DEPDIR)/doxygen.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@mech/$(DEPDIR)/gss_accept_sec_context.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@mech/$(DEPDIR)/gss_acquire_cred.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@mech/$(DEPDIR)/gss_acquire_cred_ext.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@mech/$(DEPDIR)/gss_acquire_cred_with_password.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@mech/$(DEPDIR)/gss_add_cred.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@mech/$(DEPDIR)/gss_add_cred_with_password.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@mech/$(DEPDIR)/gss_add_oid_set_member.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@mech/$(DEPDIR)/gss_aeap.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@mech/$(DEPDIR)/gss_authorize_localname.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@mech/$(DEPDIR)/gss_buffer_set.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@mech/$(DEPDIR)/gss_canonicalize_name.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@mech/$(DEPDIR)/gss_compare_name.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@mech/$(DEPDIR)/gss_context_time.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@mech/$(DEPDIR)/gss_create_empty_oid_set.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@mech/$(DEPDIR)/gss_cred.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@mech/$(DEPDIR)/gss_decapsulate_token.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@mech/$(DEPDIR)/gss_delete_name_attribute.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@mech/$(DEPDIR)/gss_delete_sec_context.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@mech/$(DEPDIR)/gss_display_name.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@mech/$(DEPDIR)/gss_display_name_ext.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@mech/$(DEPDIR)/gss_display_status.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@mech/$(DEPDIR)/gss_duplicate_name.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@mech/$(DEPDIR)/gss_duplicate_oid.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@mech/$(DEPDIR)/gss_encapsulate_token.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@mech/$(DEPDIR)/gss_export_name.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@mech/$(DEPDIR)/gss_export_name_composite.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@mech/$(DEPDIR)/gss_export_sec_context.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@mech/$(DEPDIR)/gss_get_mic.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@mech/$(DEPDIR)/gss_get_name_attribute.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@mech/$(DEPDIR)/gss_import_name.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@mech/$(DEPDIR)/gss_import_sec_context.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@mech/$(DEPDIR)/gss_indicate_mechs.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@mech/$(DEPDIR)/gss_init_sec_context.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@mech/$(DEPDIR)/gss_inquire_context.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@mech/$(DEPDIR)/gss_inquire_cred.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@mech/$(DEPDIR)/gss_inquire_cred_by_mech.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@mech/$(DEPDIR)/gss_inquire_cred_by_oid.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@mech/$(DEPDIR)/gss_inquire_mechs_for_name.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@mech/$(DEPDIR)/gss_inquire_name.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@mech/$(DEPDIR)/gss_inquire_names_for_mech.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@mech/$(DEPDIR)/gss_inquire_sec_context_by_oid.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@mech/$(DEPDIR)/gss_krb5.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@mech/$(DEPDIR)/gss_mech_switch.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@mech/$(DEPDIR)/gss_mo.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@mech/$(DEPDIR)/gss_names.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@mech/$(DEPDIR)/gss_oid.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@mech/$(DEPDIR)/gss_oid_equal.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@mech/$(DEPDIR)/gss_oid_to_str.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@mech/$(DEPDIR)/gss_pname_to_uid.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@mech/$(DEPDIR)/gss_process_context_token.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@mech/$(DEPDIR)/gss_pseudo_random.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@mech/$(DEPDIR)/gss_release_buffer.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@mech/$(DEPDIR)/gss_release_cred.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@mech/$(DEPDIR)/gss_release_name.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@mech/$(DEPDIR)/gss_release_oid.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@mech/$(DEPDIR)/gss_release_oid_set.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@mech/$(DEPDIR)/gss_seal.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@mech/$(DEPDIR)/gss_set_cred_option.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@mech/$(DEPDIR)/gss_set_name_attribute.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@mech/$(DEPDIR)/gss_set_sec_context_option.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@mech/$(DEPDIR)/gss_sign.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@mech/$(DEPDIR)/gss_store_cred.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@mech/$(DEPDIR)/gss_test_oid_set_member.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@mech/$(DEPDIR)/gss_unseal.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@mech/$(DEPDIR)/gss_unwrap.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@mech/$(DEPDIR)/gss_utils.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@mech/$(DEPDIR)/gss_verify.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@mech/$(DEPDIR)/gss_verify_mic.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@mech/$(DEPDIR)/gss_wrap.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@mech/$(DEPDIR)/gss_wrap_size_limit.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@ntlm/$(DEPDIR)/accept_sec_context.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@ntlm/$(DEPDIR)/acquire_cred.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@ntlm/$(DEPDIR)/add_cred.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@ntlm/$(DEPDIR)/canonicalize_name.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@ntlm/$(DEPDIR)/compare_name.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@ntlm/$(DEPDIR)/context_time.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@ntlm/$(DEPDIR)/creds.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@ntlm/$(DEPDIR)/crypto.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@ntlm/$(DEPDIR)/delete_sec_context.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@ntlm/$(DEPDIR)/display_name.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@ntlm/$(DEPDIR)/display_status.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@ntlm/$(DEPDIR)/duplicate_name.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@ntlm/$(DEPDIR)/export_name.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@ntlm/$(DEPDIR)/export_sec_context.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@ntlm/$(DEPDIR)/external.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@ntlm/$(DEPDIR)/import_name.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@ntlm/$(DEPDIR)/import_sec_context.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@ntlm/$(DEPDIR)/indicate_mechs.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@ntlm/$(DEPDIR)/init_sec_context.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@ntlm/$(DEPDIR)/inquire_context.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@ntlm/$(DEPDIR)/inquire_cred_by_mech.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@ntlm/$(DEPDIR)/inquire_mechs_for_name.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@ntlm/$(DEPDIR)/inquire_names_for_mech.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@ntlm/$(DEPDIR)/inquire_sec_context_by_oid.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@ntlm/$(DEPDIR)/iter_cred.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@ntlm/$(DEPDIR)/kdc.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@ntlm/$(DEPDIR)/process_context_token.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@ntlm/$(DEPDIR)/release_cred.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@ntlm/$(DEPDIR)/release_name.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@spnego/$(DEPDIR)/accept_sec_context.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@spnego/$(DEPDIR)/compat.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@spnego/$(DEPDIR)/context_stubs.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@spnego/$(DEPDIR)/cred_stubs.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@spnego/$(DEPDIR)/external.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@spnego/$(DEPDIR)/init_sec_context.Plo@am__quote@ .c.o: @am__fastdepCC_TRUE@ $(AM_V_CC)depbase=`echo $@ | sed 's|[^/]*$$|$(DEPDIR)/&|;s|\.o$$||'`;\ @am__fastdepCC_TRUE@ $(COMPILE) -MT $@ -MD -MP -MF $$depbase.Tpo -c -o $@ $< &&\ @am__fastdepCC_TRUE@ $(am__mv) $$depbase.Tpo $$depbase.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='$<' object='$@' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(COMPILE) -c -o $@ $< .c.obj: @am__fastdepCC_TRUE@ $(AM_V_CC)depbase=`echo $@ | sed 's|[^/]*$$|$(DEPDIR)/&|;s|\.obj$$||'`;\ @am__fastdepCC_TRUE@ $(COMPILE) -MT $@ -MD -MP -MF $$depbase.Tpo -c -o $@ `$(CYGPATH_W) '$<'` &&\ @am__fastdepCC_TRUE@ $(am__mv) $$depbase.Tpo $$depbase.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='$<' object='$@' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(COMPILE) -c -o $@ `$(CYGPATH_W) '$<'` .c.lo: @am__fastdepCC_TRUE@ $(AM_V_CC)depbase=`echo $@ | sed 's|[^/]*$$|$(DEPDIR)/&|;s|\.lo$$||'`;\ @am__fastdepCC_TRUE@ $(LTCOMPILE) -MT $@ -MD -MP -MF $$depbase.Tpo -c -o $@ $< &&\ @am__fastdepCC_TRUE@ $(am__mv) $$depbase.Tpo $$depbase.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='$<' object='$@' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LTCOMPILE) -c -o $@ $< mostlyclean-libtool: -rm -f *.lo clean-libtool: -rm -rf .libs _libs -rm -rf krb5/.libs krb5/_libs -rm -rf mech/.libs mech/_libs -rm -rf ntlm/.libs ntlm/_libs -rm -rf spnego/.libs spnego/_libs install-man3: $(man_MANS) @$(NORMAL_INSTALL) @list1=''; \ list2='$(man_MANS)'; \ test -n "$(man3dir)" \ && test -n "`echo $$list1$$list2`" \ || exit 0; \ echo " $(MKDIR_P) '$(DESTDIR)$(man3dir)'"; \ $(MKDIR_P) "$(DESTDIR)$(man3dir)" || exit 1; \ { for i in $$list1; do echo "$$i"; done; \ if test -n "$$list2"; then \ for i in $$list2; do echo "$$i"; done \ | sed -n '/\.3[a-z]*$$/p'; \ fi; \ } | while read p; do \ if test -f $$p; then d=; else d="$(srcdir)/"; fi; \ echo "$$d$$p"; echo "$$p"; \ done | \ sed -e 'n;s,.*/,,;p;h;s,.*\.,,;s,^[^3][0-9a-z]*$$,3,;x' \ -e 's,\.[0-9a-z]*$$,,;$(transform);G;s,\n,.,' | \ sed 'N;N;s,\n, ,g' | { \ list=; while read file base inst; do \ if test "$$base" = "$$inst"; then list="$$list $$file"; else \ echo " $(INSTALL_DATA) '$$file' '$(DESTDIR)$(man3dir)/$$inst'"; \ $(INSTALL_DATA) "$$file" "$(DESTDIR)$(man3dir)/$$inst" || exit $$?; \ fi; \ done; \ for i in $$list; do echo "$$i"; done | $(am__base_list) | \ while read files; do \ test -z "$$files" || { \ echo " $(INSTALL_DATA) $$files '$(DESTDIR)$(man3dir)'"; \ $(INSTALL_DATA) $$files "$(DESTDIR)$(man3dir)" || exit $$?; }; \ done; } uninstall-man3: @$(NORMAL_UNINSTALL) @list=''; test -n "$(man3dir)" || exit 0; \ files=`{ for i in $$list; do echo "$$i"; done; \ l2='$(man_MANS)'; for i in $$l2; do echo "$$i"; done | \ sed -n '/\.3[a-z]*$$/p'; \ } | sed -e 's,.*/,,;h;s,.*\.,,;s,^[^3][0-9a-z]*$$,3,;x' \ -e 's,\.[0-9a-z]*$$,,;$(transform);G;s,\n,.,'`; \ dir='$(DESTDIR)$(man3dir)'; $(am__uninstall_files_from_dir) install-man5: $(man_MANS) @$(NORMAL_INSTALL) @list1=''; \ list2='$(man_MANS)'; \ test -n "$(man5dir)" \ && test -n "`echo $$list1$$list2`" \ || exit 0; \ echo " $(MKDIR_P) '$(DESTDIR)$(man5dir)'"; \ $(MKDIR_P) "$(DESTDIR)$(man5dir)" || exit 1; \ { for i in $$list1; do echo "$$i"; done; \ if test -n "$$list2"; then \ for i in $$list2; do echo "$$i"; done \ | sed -n '/\.5[a-z]*$$/p'; \ fi; \ } | while read p; do \ if test -f $$p; then d=; else d="$(srcdir)/"; fi; \ echo "$$d$$p"; echo "$$p"; \ done | \ sed -e 'n;s,.*/,,;p;h;s,.*\.,,;s,^[^5][0-9a-z]*$$,5,;x' \ -e 's,\.[0-9a-z]*$$,,;$(transform);G;s,\n,.,' | \ sed 'N;N;s,\n, ,g' | { \ list=; while read file base inst; do \ if test "$$base" = "$$inst"; then list="$$list $$file"; else \ echo " $(INSTALL_DATA) '$$file' '$(DESTDIR)$(man5dir)/$$inst'"; \ $(INSTALL_DATA) "$$file" "$(DESTDIR)$(man5dir)/$$inst" || exit $$?; \ fi; \ done; \ for i in $$list; do echo "$$i"; done | $(am__base_list) | \ while read files; do \ test -z "$$files" || { \ echo " $(INSTALL_DATA) $$files '$(DESTDIR)$(man5dir)'"; \ $(INSTALL_DATA) $$files "$(DESTDIR)$(man5dir)" || exit $$?; }; \ done; } uninstall-man5: @$(NORMAL_UNINSTALL) @list=''; test -n "$(man5dir)" || exit 0; \ files=`{ for i in $$list; do echo "$$i"; done; \ l2='$(man_MANS)'; for i in $$l2; do echo "$$i"; done | \ sed -n '/\.5[a-z]*$$/p'; \ } | sed -e 's,.*/,,;h;s,.*\.,,;s,^[^5][0-9a-z]*$$,5,;x' \ -e 's,\.[0-9a-z]*$$,,;$(transform);G;s,\n,.,'`; \ dir='$(DESTDIR)$(man5dir)'; $(am__uninstall_files_from_dir) install-includeHEADERS: $(include_HEADERS) @$(NORMAL_INSTALL) @list='$(include_HEADERS)'; test -n "$(includedir)" || list=; \ if test -n "$$list"; then \ echo " $(MKDIR_P) '$(DESTDIR)$(includedir)'"; \ $(MKDIR_P) "$(DESTDIR)$(includedir)" || exit 1; \ fi; \ for p in $$list; do \ if test -f "$$p"; then d=; else d="$(srcdir)/"; fi; \ echo "$$d$$p"; \ done | $(am__base_list) | \ while read files; do \ echo " $(INSTALL_HEADER) $$files '$(DESTDIR)$(includedir)'"; \ $(INSTALL_HEADER) $$files "$(DESTDIR)$(includedir)" || exit $$?; \ done uninstall-includeHEADERS: @$(NORMAL_UNINSTALL) @list='$(include_HEADERS)'; test -n "$(includedir)" || list=; \ files=`for p in $$list; do echo $$p; done | sed -e 's|^.*/||'`; \ dir='$(DESTDIR)$(includedir)'; $(am__uninstall_files_from_dir) install-nobase_includeHEADERS: $(nobase_include_HEADERS) @$(NORMAL_INSTALL) @list='$(nobase_include_HEADERS)'; test -n "$(includedir)" || list=; \ if test -n "$$list"; then \ echo " $(MKDIR_P) '$(DESTDIR)$(includedir)'"; \ $(MKDIR_P) "$(DESTDIR)$(includedir)" || exit 1; \ fi; \ $(am__nobase_list) | while read dir files; do \ xfiles=; for file in $$files; do \ if test -f "$$file"; then xfiles="$$xfiles $$file"; \ else xfiles="$$xfiles $(srcdir)/$$file"; fi; done; \ test -z "$$xfiles" || { \ test "x$$dir" = x. || { \ echo " $(MKDIR_P) '$(DESTDIR)$(includedir)/$$dir'"; \ $(MKDIR_P) "$(DESTDIR)$(includedir)/$$dir"; }; \ echo " $(INSTALL_HEADER) $$xfiles '$(DESTDIR)$(includedir)/$$dir'"; \ $(INSTALL_HEADER) $$xfiles "$(DESTDIR)$(includedir)/$$dir" || exit $$?; }; \ done uninstall-nobase_includeHEADERS: @$(NORMAL_UNINSTALL) @list='$(nobase_include_HEADERS)'; test -n "$(includedir)" || list=; \ $(am__nobase_strip_setup); files=`$(am__nobase_strip)`; \ dir='$(DESTDIR)$(includedir)'; $(am__uninstall_files_from_dir) install-nodist_gssapiHEADERS: $(nodist_gssapi_HEADERS) @$(NORMAL_INSTALL) @list='$(nodist_gssapi_HEADERS)'; test -n "$(gssapidir)" || list=; \ if test -n "$$list"; then \ echo " $(MKDIR_P) '$(DESTDIR)$(gssapidir)'"; \ $(MKDIR_P) "$(DESTDIR)$(gssapidir)" || exit 1; \ fi; \ for p in $$list; do \ if test -f "$$p"; then d=; else d="$(srcdir)/"; fi; \ echo "$$d$$p"; \ done | $(am__base_list) | \ while read files; do \ echo " $(INSTALL_HEADER) $$files '$(DESTDIR)$(gssapidir)'"; \ $(INSTALL_HEADER) $$files "$(DESTDIR)$(gssapidir)" || exit $$?; \ done uninstall-nodist_gssapiHEADERS: @$(NORMAL_UNINSTALL) @list='$(nodist_gssapi_HEADERS)'; test -n "$(gssapidir)" || list=; \ files=`for p in $$list; do echo $$p; done | sed -e 's|^.*/||'`; \ dir='$(DESTDIR)$(gssapidir)'; $(am__uninstall_files_from_dir) ID: $(am__tagged_files) $(am__define_uniq_tagged_files); mkid -fID $$unique tags: tags-am TAGS: tags tags-am: $(TAGS_DEPENDENCIES) $(am__tagged_files) set x; \ here=`pwd`; \ $(am__define_uniq_tagged_files); \ shift; \ if test -z "$(ETAGS_ARGS)$$*$$unique"; then :; else \ test -n "$$unique" || unique=$$empty_fix; \ if test $$# -gt 0; then \ $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ "$$@" $$unique; \ else \ $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ $$unique; \ fi; \ fi ctags: ctags-am CTAGS: ctags ctags-am: $(TAGS_DEPENDENCIES) $(am__tagged_files) $(am__define_uniq_tagged_files); \ test -z "$(CTAGS_ARGS)$$unique" \ || $(CTAGS) $(CTAGSFLAGS) $(AM_CTAGSFLAGS) $(CTAGS_ARGS) \ $$unique GTAGS: here=`$(am__cd) $(top_builddir) && pwd` \ && $(am__cd) $(top_srcdir) \ && gtags -i $(GTAGS_ARGS) "$$here" cscopelist: cscopelist-am cscopelist-am: $(am__tagged_files) list='$(am__tagged_files)'; \ case "$(srcdir)" in \ [\\/]* | ?:[\\/]*) sdir="$(srcdir)" ;; \ *) sdir=$(subdir)/$(srcdir) ;; \ esac; \ for i in $$list; do \ if test -f "$$i"; then \ echo "$(subdir)/$$i"; \ else \ echo "$$sdir/$$i"; \ fi; \ done >> $(top_builddir)/cscope.files distclean-tags: -rm -f TAGS ID GTAGS GRTAGS GSYMS GPATH tags # Recover from deleted '.trs' file; this should ensure that # "rm -f foo.log; make foo.trs" re-run 'foo.test', and re-create # both 'foo.log' and 'foo.trs'. Break the recipe in two subshells # to avoid problems with "make -n". .log.trs: rm -f $< $@ $(MAKE) $(AM_MAKEFLAGS) $< # Leading 'am--fnord' is there to ensure the list of targets does not # expand to empty, as could happen e.g. with make check TESTS=''. am--fnord $(TEST_LOGS) $(TEST_LOGS:.log=.trs): $(am__force_recheck) am--force-recheck: @: $(TEST_SUITE_LOG): $(TEST_LOGS) @$(am__set_TESTS_bases); \ am__f_ok () { test -f "$$1" && test -r "$$1"; }; \ redo_bases=`for i in $$bases; do \ am__f_ok $$i.trs && am__f_ok $$i.log || echo $$i; \ done`; \ if test -n "$$redo_bases"; then \ redo_logs=`for i in $$redo_bases; do echo $$i.log; done`; \ redo_results=`for i in $$redo_bases; do echo $$i.trs; done`; \ if $(am__make_dryrun); then :; else \ rm -f $$redo_logs && rm -f $$redo_results || exit 1; \ fi; \ fi; \ if test -n "$$am__remaking_logs"; then \ echo "fatal: making $(TEST_SUITE_LOG): possible infinite" \ "recursion detected" >&2; \ elif test -n "$$redo_logs"; then \ am__remaking_logs=yes $(MAKE) $(AM_MAKEFLAGS) $$redo_logs; \ fi; \ if $(am__make_dryrun); then :; else \ st=0; \ errmsg="fatal: making $(TEST_SUITE_LOG): failed to create"; \ for i in $$redo_bases; do \ test -f $$i.trs && test -r $$i.trs \ || { echo "$$errmsg $$i.trs" >&2; st=1; }; \ test -f $$i.log && test -r $$i.log \ || { echo "$$errmsg $$i.log" >&2; st=1; }; \ done; \ test $$st -eq 0 || exit 1; \ fi @$(am__sh_e_setup); $(am__tty_colors); $(am__set_TESTS_bases); \ ws='[ ]'; \ results=`for b in $$bases; do echo $$b.trs; done`; \ test -n "$$results" || results=/dev/null; \ all=` grep "^$$ws*:test-result:" $$results | wc -l`; \ pass=` grep "^$$ws*:test-result:$$ws*PASS" $$results | wc -l`; \ fail=` grep "^$$ws*:test-result:$$ws*FAIL" $$results | wc -l`; \ skip=` grep "^$$ws*:test-result:$$ws*SKIP" $$results | wc -l`; \ xfail=`grep "^$$ws*:test-result:$$ws*XFAIL" $$results | wc -l`; \ xpass=`grep "^$$ws*:test-result:$$ws*XPASS" $$results | wc -l`; \ error=`grep "^$$ws*:test-result:$$ws*ERROR" $$results | wc -l`; \ if test `expr $$fail + $$xpass + $$error` -eq 0; then \ success=true; \ else \ success=false; \ fi; \ br='==================='; br=$$br$$br$$br$$br; \ result_count () \ { \ if test x"$$1" = x"--maybe-color"; then \ maybe_colorize=yes; \ elif test x"$$1" = x"--no-color"; then \ maybe_colorize=no; \ else \ echo "$@: invalid 'result_count' usage" >&2; exit 4; \ fi; \ shift; \ desc=$$1 count=$$2; \ if test $$maybe_colorize = yes && test $$count -gt 0; then \ color_start=$$3 color_end=$$std; \ else \ color_start= color_end=; \ fi; \ echo "$${color_start}# $$desc $$count$${color_end}"; \ }; \ create_testsuite_report () \ { \ result_count $$1 "TOTAL:" $$all "$$brg"; \ result_count $$1 "PASS: " $$pass "$$grn"; \ result_count $$1 "SKIP: " $$skip "$$blu"; \ result_count $$1 "XFAIL:" $$xfail "$$lgn"; \ result_count $$1 "FAIL: " $$fail "$$red"; \ result_count $$1 "XPASS:" $$xpass "$$red"; \ result_count $$1 "ERROR:" $$error "$$mgn"; \ }; \ { \ echo "$(PACKAGE_STRING): $(subdir)/$(TEST_SUITE_LOG)" | \ $(am__rst_title); \ create_testsuite_report --no-color; \ echo; \ echo ".. contents:: :depth: 2"; \ echo; \ for b in $$bases; do echo $$b; done \ | $(am__create_global_log); \ } >$(TEST_SUITE_LOG).tmp || exit 1; \ mv $(TEST_SUITE_LOG).tmp $(TEST_SUITE_LOG); \ if $$success; then \ col="$$grn"; \ else \ col="$$red"; \ test x"$$VERBOSE" = x || cat $(TEST_SUITE_LOG); \ fi; \ echo "$${col}$$br$${std}"; \ echo "$${col}Testsuite summary for $(PACKAGE_STRING)$${std}"; \ echo "$${col}$$br$${std}"; \ create_testsuite_report --maybe-color; \ echo "$$col$$br$$std"; \ if $$success; then :; else \ echo "$${col}See $(subdir)/$(TEST_SUITE_LOG)$${std}"; \ if test -n "$(PACKAGE_BUGREPORT)"; then \ echo "$${col}Please report to $(PACKAGE_BUGREPORT)$${std}"; \ fi; \ echo "$$col$$br$$std"; \ fi; \ $$success || exit 1 check-TESTS: @list='$(RECHECK_LOGS)'; test -z "$$list" || rm -f $$list @list='$(RECHECK_LOGS:.log=.trs)'; test -z "$$list" || rm -f $$list @test -z "$(TEST_SUITE_LOG)" || rm -f $(TEST_SUITE_LOG) @set +e; $(am__set_TESTS_bases); \ log_list=`for i in $$bases; do echo $$i.log; done`; \ trs_list=`for i in $$bases; do echo $$i.trs; done`; \ log_list=`echo $$log_list`; trs_list=`echo $$trs_list`; \ $(MAKE) $(AM_MAKEFLAGS) $(TEST_SUITE_LOG) TEST_LOGS="$$log_list"; \ exit $$?; recheck: all $(check_PROGRAMS) @test -z "$(TEST_SUITE_LOG)" || rm -f $(TEST_SUITE_LOG) @set +e; $(am__set_TESTS_bases); \ bases=`for i in $$bases; do echo $$i; done \ | $(am__list_recheck_tests)` || exit 1; \ log_list=`for i in $$bases; do echo $$i.log; done`; \ log_list=`echo $$log_list`; \ $(MAKE) $(AM_MAKEFLAGS) $(TEST_SUITE_LOG) \ am__force_recheck=am--force-recheck \ TEST_LOGS="$$log_list"; \ exit $$? test_oid.log: test_oid$(EXEEXT) @p='test_oid$(EXEEXT)'; \ b='test_oid'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_names.log: test_names$(EXEEXT) @p='test_names$(EXEEXT)'; \ b='test_names'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_cfx.log: test_cfx$(EXEEXT) @p='test_cfx$(EXEEXT)'; \ b='test_cfx'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) .test.log: @p='$<'; \ $(am__set_b); \ $(am__check_pre) $(TEST_LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_TEST_LOG_DRIVER_FLAGS) $(TEST_LOG_DRIVER_FLAGS) -- $(TEST_LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) @am__EXEEXT_TRUE@.test$(EXEEXT).log: @am__EXEEXT_TRUE@ @p='$<'; \ @am__EXEEXT_TRUE@ $(am__set_b); \ @am__EXEEXT_TRUE@ $(am__check_pre) $(TEST_LOG_DRIVER) --test-name "$$f" \ @am__EXEEXT_TRUE@ --log-file $$b.log --trs-file $$b.trs \ @am__EXEEXT_TRUE@ $(am__common_driver_flags) $(AM_TEST_LOG_DRIVER_FLAGS) $(TEST_LOG_DRIVER_FLAGS) -- $(TEST_LOG_COMPILE) \ @am__EXEEXT_TRUE@ "$$tst" $(AM_TESTS_FD_REDIRECT) distdir: $(DISTFILES) @srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ topsrcdirstrip=`echo "$(top_srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ list='$(DISTFILES)'; \ dist_files=`for file in $$list; do echo $$file; done | \ sed -e "s|^$$srcdirstrip/||;t" \ -e "s|^$$topsrcdirstrip/|$(top_builddir)/|;t"`; \ case $$dist_files in \ */*) $(MKDIR_P) `echo "$$dist_files" | \ sed '/\//!d;s|^|$(distdir)/|;s,/[^/]*$$,,' | \ sort -u` ;; \ esac; \ for file in $$dist_files; do \ if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \ if test -d $$d/$$file; then \ dir=`echo "/$$file" | sed -e 's,/[^/]*$$,,'`; \ if test -d "$(distdir)/$$file"; then \ find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ fi; \ if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \ cp -fpR $(srcdir)/$$file "$(distdir)$$dir" || exit 1; \ find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ fi; \ cp -fpR $$d/$$file "$(distdir)$$dir" || exit 1; \ else \ test -f "$(distdir)/$$file" \ || cp -p $$d/$$file "$(distdir)/$$file" \ || exit 1; \ fi; \ done $(MAKE) $(AM_MAKEFLAGS) \ top_distdir="$(top_distdir)" distdir="$(distdir)" \ dist-hook check-am: all-am $(MAKE) $(AM_MAKEFLAGS) $(check_PROGRAMS) $(MAKE) $(AM_MAKEFLAGS) check-TESTS check-local check: $(BUILT_SOURCES) $(MAKE) $(AM_MAKEFLAGS) check-am all-am: Makefile $(LTLIBRARIES) $(PROGRAMS) $(MANS) $(HEADERS) \ all-local install-binPROGRAMS: install-libLTLIBRARIES installdirs: for dir in "$(DESTDIR)$(libdir)" "$(DESTDIR)$(bindir)" "$(DESTDIR)$(man3dir)" "$(DESTDIR)$(man5dir)" "$(DESTDIR)$(includedir)" "$(DESTDIR)$(includedir)" "$(DESTDIR)$(gssapidir)"; do \ test -z "$$dir" || $(MKDIR_P) "$$dir"; \ done install: $(BUILT_SOURCES) $(MAKE) $(AM_MAKEFLAGS) install-am install-exec: install-exec-am install-data: install-data-am uninstall: uninstall-am install-am: all-am @$(MAKE) $(AM_MAKEFLAGS) install-exec-am install-data-am installcheck: installcheck-am install-strip: if test -z '$(STRIP)'; then \ $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ install; \ else \ $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'" install; \ fi mostlyclean-generic: -test -z "$(TEST_LOGS)" || rm -f $(TEST_LOGS) -test -z "$(TEST_LOGS:.log=.trs)" || rm -f $(TEST_LOGS:.log=.trs) -test -z "$(TEST_SUITE_LOG)" || rm -f $(TEST_SUITE_LOG) clean-generic: -test -z "$(CLEANFILES)" || rm -f $(CLEANFILES) distclean-generic: -test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES) -test . = "$(srcdir)" || test -z "$(CONFIG_CLEAN_VPATH_FILES)" || rm -f $(CONFIG_CLEAN_VPATH_FILES) -rm -f krb5/$(DEPDIR)/$(am__dirstamp) -rm -f krb5/$(am__dirstamp) -rm -f mech/$(DEPDIR)/$(am__dirstamp) -rm -f mech/$(am__dirstamp) -rm -f ntlm/$(DEPDIR)/$(am__dirstamp) -rm -f ntlm/$(am__dirstamp) -rm -f spnego/$(DEPDIR)/$(am__dirstamp) -rm -f spnego/$(am__dirstamp) maintainer-clean-generic: @echo "This command is intended for maintainers to use" @echo "it deletes files that may require special tools to rebuild." -test -z "$(BUILT_SOURCES)" || rm -f $(BUILT_SOURCES) clean: clean-am clean-am: clean-binPROGRAMS clean-checkPROGRAMS clean-generic \ clean-libLTLIBRARIES clean-libtool clean-noinstPROGRAMS \ mostlyclean-am distclean: distclean-am -rm -rf ./$(DEPDIR) krb5/$(DEPDIR) mech/$(DEPDIR) ntlm/$(DEPDIR) spnego/$(DEPDIR) -rm -f Makefile distclean-am: clean-am distclean-compile distclean-generic \ distclean-tags dvi: dvi-am dvi-am: html: html-am html-am: info: info-am info-am: install-data-am: install-includeHEADERS install-man \ install-nobase_includeHEADERS install-nodist_gssapiHEADERS @$(NORMAL_INSTALL) $(MAKE) $(AM_MAKEFLAGS) install-data-hook install-dvi: install-dvi-am install-dvi-am: install-exec-am: install-binPROGRAMS install-exec-local \ install-libLTLIBRARIES install-html: install-html-am install-html-am: install-info: install-info-am install-info-am: install-man: install-man3 install-man5 install-pdf: install-pdf-am install-pdf-am: install-ps: install-ps-am install-ps-am: installcheck-am: maintainer-clean: maintainer-clean-am -rm -rf ./$(DEPDIR) krb5/$(DEPDIR) mech/$(DEPDIR) ntlm/$(DEPDIR) spnego/$(DEPDIR) -rm -f Makefile maintainer-clean-am: distclean-am maintainer-clean-generic mostlyclean: mostlyclean-am mostlyclean-am: mostlyclean-compile mostlyclean-generic \ mostlyclean-libtool pdf: pdf-am pdf-am: ps: ps-am ps-am: uninstall-am: uninstall-binPROGRAMS uninstall-includeHEADERS \ uninstall-libLTLIBRARIES uninstall-man \ uninstall-nobase_includeHEADERS uninstall-nodist_gssapiHEADERS @$(NORMAL_INSTALL) $(MAKE) $(AM_MAKEFLAGS) uninstall-hook uninstall-man: uninstall-man3 uninstall-man5 .MAKE: all check check-am install install-am install-data-am \ install-strip uninstall-am .PHONY: CTAGS GTAGS TAGS all all-am all-local check check-TESTS \ check-am check-local clean clean-binPROGRAMS \ clean-checkPROGRAMS clean-generic clean-libLTLIBRARIES \ clean-libtool clean-noinstPROGRAMS cscopelist-am ctags \ ctags-am dist-hook distclean distclean-compile \ distclean-generic distclean-libtool distclean-tags distdir dvi \ dvi-am html html-am info info-am install install-am \ install-binPROGRAMS install-data install-data-am \ install-data-hook install-dvi install-dvi-am install-exec \ install-exec-am install-exec-local install-html \ install-html-am install-includeHEADERS install-info \ install-info-am install-libLTLIBRARIES install-man \ install-man3 install-man5 install-nobase_includeHEADERS \ install-nodist_gssapiHEADERS install-pdf install-pdf-am \ install-ps install-ps-am install-strip installcheck \ installcheck-am installdirs maintainer-clean \ maintainer-clean-generic mostlyclean mostlyclean-compile \ mostlyclean-generic mostlyclean-libtool pdf pdf-am ps ps-am \ recheck tags tags-am uninstall uninstall-am \ uninstall-binPROGRAMS uninstall-hook uninstall-includeHEADERS \ uninstall-libLTLIBRARIES uninstall-man uninstall-man3 \ uninstall-man5 uninstall-nobase_includeHEADERS \ uninstall-nodist_gssapiHEADERS .PRECIOUS: Makefile install-suid-programs: @foo='$(bin_SUIDS)'; \ for file in $$foo; do \ x=$(DESTDIR)$(bindir)/$$file; \ if chown 0:0 $$x && chmod u+s $$x; then :; else \ echo "*"; \ echo "* Failed to install $$x setuid root"; \ echo "*"; \ fi; \ done install-exec-local: install-suid-programs codesign-all: @if [ X"$$CODE_SIGN_IDENTITY" != X ] ; then \ foo='$(bin_PROGRAMS) $(sbin_PROGRAMS) $(libexec_PROGRAMS)' ; \ for file in $$foo ; do \ echo "CODESIGN $$file" ; \ codesign -f -s "$$CODE_SIGN_IDENTITY" $$file || exit 1 ; \ done ; \ fi all-local: codesign-all install-build-headers:: $(include_HEADERS) $(dist_include_HEADERS) $(nodist_include_HEADERS) $(build_HEADERZ) $(nobase_include_HEADERS) $(noinst_HEADERS) @foo='$(include_HEADERS) $(dist_include_HEADERS) $(nodist_include_HEADERS) $(build_HEADERZ) $(noinst_HEADERS)'; \ for f in $$foo; do \ f=`basename $$f`; \ if test -f "$(srcdir)/$$f"; then file="$(srcdir)/$$f"; \ else file="$$f"; fi; \ if cmp -s $$file $(buildinclude)/$$f 2> /dev/null ; then \ : ; else \ echo " $(CP) $$file $(buildinclude)/$$f"; \ $(CP) $$file $(buildinclude)/$$f || true; \ fi ; \ done ; \ foo='$(nobase_include_HEADERS)'; \ for f in $$foo; do \ if test -f "$(srcdir)/$$f"; then file="$(srcdir)/$$f"; \ else file="$$f"; fi; \ $(mkdir_p) $(buildinclude)/`dirname $$f` ; \ if cmp -s $$file $(buildinclude)/$$f 2> /dev/null ; then \ : ; else \ echo " $(CP) $$file $(buildinclude)/$$f"; \ $(CP) $$file $(buildinclude)/$$f; \ fi ; \ done all-local: install-build-headers check-local:: @if test '$(CHECK_LOCAL)' = "no-check-local"; then \ foo=''; elif test '$(CHECK_LOCAL)'; then \ foo='$(CHECK_LOCAL)'; else \ foo='$(PROGRAMS)'; fi; \ if test "$$foo"; then \ failed=0; all=0; \ for i in $$foo; do \ all=`expr $$all + 1`; \ if (./$$i --version && ./$$i --help) > /dev/null 2>&1; then \ echo "PASS: $$i"; \ else \ echo "FAIL: $$i"; \ failed=`expr $$failed + 1`; \ fi; \ done; \ if test "$$failed" -eq 0; then \ banner="All $$all tests passed"; \ else \ banner="$$failed of $$all tests failed"; \ fi; \ dashes=`echo "$$banner" | sed s/./=/g`; \ echo "$$dashes"; \ echo "$$banner"; \ echo "$$dashes"; \ test "$$failed" -eq 0 || exit 1; \ fi .x.c: @cmp -s $< $@ 2> /dev/null || cp $< $@ .hx.h: @cmp -s $< $@ 2> /dev/null || cp $< $@ #NROFF_MAN = nroff -man .1.cat1: $(NROFF_MAN) $< > $@ .3.cat3: $(NROFF_MAN) $< > $@ .5.cat5: $(NROFF_MAN) $< > $@ .7.cat7: $(NROFF_MAN) $< > $@ .8.cat8: $(NROFF_MAN) $< > $@ dist-cat1-mans: @foo='$(man1_MANS)'; \ bar='$(man_MANS)'; \ for i in $$bar; do \ case $$i in \ *.1) foo="$$foo $$i";; \ esac; done ;\ for i in $$foo; do \ x=`echo $$i | sed 's/\.[^.]*$$/.cat1/'`; \ echo "$(NROFF_MAN) $(srcdir)/$$i > $(distdir)/$$x"; \ $(NROFF_MAN) $(srcdir)/$$i > $(distdir)/$$x; \ done dist-cat3-mans: @foo='$(man3_MANS)'; \ bar='$(man_MANS)'; \ for i in $$bar; do \ case $$i in \ *.3) foo="$$foo $$i";; \ esac; done ;\ for i in $$foo; do \ x=`echo $$i | sed 's/\.[^.]*$$/.cat3/'`; \ echo "$(NROFF_MAN) $(srcdir)/$$i > $(distdir)/$$x"; \ $(NROFF_MAN) $(srcdir)/$$i > $(distdir)/$$x; \ done dist-cat5-mans: @foo='$(man5_MANS)'; \ bar='$(man_MANS)'; \ for i in $$bar; do \ case $$i in \ *.5) foo="$$foo $$i";; \ esac; done ;\ for i in $$foo; do \ x=`echo $$i | sed 's/\.[^.]*$$/.cat5/'`; \ echo "$(NROFF_MAN) $(srcdir)/$$i > $(distdir)/$$x"; \ $(NROFF_MAN) $(srcdir)/$$i > $(distdir)/$$x; \ done dist-cat7-mans: @foo='$(man7_MANS)'; \ bar='$(man_MANS)'; \ for i in $$bar; do \ case $$i in \ *.7) foo="$$foo $$i";; \ esac; done ;\ for i in $$foo; do \ x=`echo $$i | sed 's/\.[^.]*$$/.cat7/'`; \ echo "$(NROFF_MAN) $(srcdir)/$$i > $(distdir)/$$x"; \ $(NROFF_MAN) $(srcdir)/$$i > $(distdir)/$$x; \ done dist-cat8-mans: @foo='$(man8_MANS)'; \ bar='$(man_MANS)'; \ for i in $$bar; do \ case $$i in \ *.8) foo="$$foo $$i";; \ esac; done ;\ for i in $$foo; do \ x=`echo $$i | sed 's/\.[^.]*$$/.cat8/'`; \ echo "$(NROFF_MAN) $(srcdir)/$$i > $(distdir)/$$x"; \ $(NROFF_MAN) $(srcdir)/$$i > $(distdir)/$$x; \ done dist-hook: dist-cat1-mans dist-cat3-mans dist-cat5-mans dist-cat7-mans dist-cat8-mans install-cat-mans: $(SHELL) $(top_srcdir)/cf/install-catman.sh install "$(INSTALL_DATA)" "$(mkinstalldirs)" "$(srcdir)" "$(DESTDIR)$(mandir)" '$(CATMANEXT)' $(man_MANS) $(man1_MANS) $(man3_MANS) $(man5_MANS) $(man7_MANS) $(man8_MANS) uninstall-cat-mans: $(SHELL) $(top_srcdir)/cf/install-catman.sh uninstall "$(INSTALL_DATA)" "$(mkinstalldirs)" "$(srcdir)" "$(DESTDIR)$(mandir)" '$(CATMANEXT)' $(man_MANS) $(man1_MANS) $(man3_MANS) $(man5_MANS) $(man7_MANS) $(man8_MANS) install-data-hook: install-cat-mans uninstall-hook: uninstall-cat-mans .et.h: $(COMPILE_ET) $< .et.c: $(COMPILE_ET) $< # # Useful target for debugging # check-valgrind: tobjdir=`cd $(top_builddir) && pwd` ; \ tsrcdir=`cd $(top_srcdir) && pwd` ; \ env TESTS_ENVIRONMENT="$${tsrcdir}/cf/maybe-valgrind.sh -s $${tsrcdir} -o $${tobjdir}" make check # # Target to please samba build farm, builds distfiles in-tree. # Will break when automake changes... # distdir-in-tree: $(DISTFILES) $(INFO_DEPS) list='$(DIST_SUBDIRS)'; for subdir in $$list; do \ if test "$$subdir" != .; then \ (cd $$subdir && $(MAKE) $(AM_MAKEFLAGS) distdir-in-tree) ; \ fi ; \ done $(srcdir)/ntlm/ntlm-private.h: $(ntlmsrc) cd $(srcdir) && perl ../../cf/make-proto.pl -q -P comment -p ntlm/ntlm-private.h $(ntlmsrc) || rm -f ntlm/ntlm-private.h $(libgssapi_la_OBJECTS): $(BUILTHEADERS) $(test_context_OBJECTS): $(BUILTHEADERS) $(libgssapi_la_OBJECTS): $(srcdir)/version-script.map $(libgssapi_la_OBJECTS): gkrb5_err.h gkrb5_err.h: $(srcdir)/krb5/gkrb5_err.et $(spnego_files) spnego_asn1.hx spnego_asn1-priv.hx: spnego_asn1_files $(gssapi_files) gssapi_asn1.hx gssapi_asn1-priv.hx: gssapi_asn1_files spnego_asn1_files: $(ASN1_COMPILE_DEP) $(srcdir)/spnego/spnego.asn1 $(srcdir)/spnego/spnego.opt $(ASN1_COMPILE) --option-file=$(srcdir)/spnego/spnego.opt $(srcdir)/spnego/spnego.asn1 spnego_asn1 gssapi_asn1_files: $(ASN1_COMPILE_DEP) $(srcdir)/mech/gssapi.asn1 $(ASN1_COMPILE) $(srcdir)/mech/gssapi.asn1 gssapi_asn1 $(srcdir)/krb5/gsskrb5-private.h: cd $(srcdir) && perl ../../cf/make-proto.pl -q -P comment -p krb5/gsskrb5-private.h $(krb5src) || rm -f krb5/gsskrb5-private.h $(srcdir)/spnego/spnego-private.h: cd $(srcdir) && perl ../../cf/make-proto.pl -q -P comment -p spnego/spnego-private.h $(spnegosrc) || rm -f spnego/spnego-private.h gss-commands.c gss-commands.h: gss-commands.in $(SLC) $(srcdir)/gss-commands.in $(gsstool_OBJECTS): gss-commands.h $(libgssapi_la_OBJECTS): gkrb5_err.h gssapi_asn1.h gssapi_asn1-priv.h $(libgssapi_la_OBJECTS): spnego_asn1.h spnego_asn1-priv.h $(libgssapi_la_OBJECTS): $(srcdir)/gssapi/gssapi_oid.h gkrb5_err.h gkrb5_err.c: $(srcdir)/krb5/gkrb5_err.et $(COMPILE_ET) $(srcdir)/krb5/gkrb5_err.et $(srcdir)/gssapi/gssapi_oid.h $(srcdir)/mech/gss_oid.c: perl $(srcdir)/gen-oid.pl -b base -h $(srcdir)/oid.txt > $(srcdir)/gssapi/gssapi_oid.h perl $(srcdir)/gen-oid.pl -b base $(srcdir)/oid.txt > $(srcdir)/mech/gss_oid.c # Tell versions [3.59,3.63) of GNU make to not export all variables. # Otherwise a system limit (for SysV at least) may be exceeded. .NOEXPORT: heimdal-7.5.0/lib/gssapi/test_names.c0000644000175000017500000001424313026237312015617 0ustar niknik/* * Copyright (c) 2006 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of KTH nor the names of its contributors may be * used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY KTH AND ITS CONTRIBUTORS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL KTH OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifdef HAVE_CONFIG_H #include #endif #include #include #include #include #include #include #include #include #include #include static void gss_print_errors (int min_stat) { OM_uint32 new_stat; OM_uint32 msg_ctx = 0; gss_buffer_desc status_string; OM_uint32 ret; do { ret = gss_display_status (&new_stat, min_stat, GSS_C_MECH_CODE, GSS_C_NO_OID, &msg_ctx, &status_string); if (!GSS_ERROR(ret)) { fprintf (stderr, "%.*s\n", (int)status_string.length, (char *)status_string.value); gss_release_buffer (&new_stat, &status_string); } } while (!GSS_ERROR(ret) && msg_ctx != 0); } static void gss_err(int exitval, int status, const char *fmt, ...) { va_list args; va_start(args, fmt); vwarnx (fmt, args); gss_print_errors (status); va_end(args); exit (exitval); } static int version_flag = 0; static int help_flag = 0; static struct getargs args[] = { {"version", 0, arg_flag, &version_flag, "print version", NULL }, {"help", 0, arg_flag, &help_flag, NULL, NULL } }; static void usage (int ret) { arg_printusage (args, sizeof(args)/sizeof(*args), NULL, "service@host"); exit (ret); } int main(int argc, char **argv) { gss_buffer_desc name_buffer; OM_uint32 maj_stat, min_stat; gss_name_t name, MNname, MNname2; int optidx = 0; char *str; int len, equal; setprogname(argv[0]); if(getarg(args, sizeof(args) / sizeof(args[0]), argc, argv, &optidx)) usage(1); if (help_flag) usage (0); if(version_flag){ print_version(NULL); exit(0); } argc -= optidx; argv += optidx; gsskrb5_set_default_realm("MIT.EDU"); /* * test import/export */ str = NULL; len = asprintf(&str, "ftp@freeze-arrow.mit.edu"); if (len < 0 || str == NULL) errx(1, "asprintf"); name_buffer.value = str; name_buffer.length = len; maj_stat = gss_import_name(&min_stat, &name_buffer, GSS_C_NT_HOSTBASED_SERVICE, &name); if (maj_stat != GSS_S_COMPLETE) gss_err(1, min_stat, "import name error"); free(str); maj_stat = gss_canonicalize_name (&min_stat, name, GSS_KRB5_MECHANISM, &MNname); if (maj_stat != GSS_S_COMPLETE) gss_err(1, min_stat, "canonicalize name error"); maj_stat = gss_export_name(&min_stat, MNname, &name_buffer); if (maj_stat != GSS_S_COMPLETE) gss_err(1, min_stat, "export name error (KRB5)"); /* * Import the exported name and compare */ maj_stat = gss_import_name(&min_stat, &name_buffer, GSS_C_NT_EXPORT_NAME, &MNname2); if (maj_stat != GSS_S_COMPLETE) gss_err(1, min_stat, "import name error (exported KRB5 name)"); maj_stat = gss_compare_name(&min_stat, MNname, MNname2, &equal); if (maj_stat != GSS_S_COMPLETE) errx(1, "gss_compare_name"); if (!equal) errx(1, "names not equal"); gss_release_name(&min_stat, &MNname2); gss_release_buffer(&min_stat, &name_buffer); gss_release_name(&min_stat, &MNname); gss_release_name(&min_stat, &name); /* * Import oid less name and compare to mech name. * Dovecot SASL lib does this. */ str = NULL; len = asprintf(&str, "lha"); if (len < 0 || str == NULL) errx(1, "asprintf"); name_buffer.value = str; name_buffer.length = len; maj_stat = gss_import_name(&min_stat, &name_buffer, GSS_C_NO_OID, &name); if (maj_stat != GSS_S_COMPLETE) gss_err(1, min_stat, "import (no oid) name error"); maj_stat = gss_import_name(&min_stat, &name_buffer, GSS_KRB5_NT_USER_NAME, &MNname); if (maj_stat != GSS_S_COMPLETE) gss_err(1, min_stat, "import (krb5 mn) name error"); free(str); maj_stat = gss_compare_name(&min_stat, name, MNname, &equal); if (maj_stat != GSS_S_COMPLETE) errx(1, "gss_compare_name"); if (!equal) errx(1, "names not equal"); gss_release_name(&min_stat, &MNname); gss_release_name(&min_stat, &name); #if 0 maj_stat = gss_canonicalize_name (&min_stat, name, GSS_SPNEGO_MECHANISM, &MNname); if (maj_stat != GSS_S_COMPLETE) gss_err(1, min_stat, "canonicalize name error"); maj_stat = gss_export_name(&maj_stat, MNname, &name_buffer); if (maj_stat != GSS_S_COMPLETE) gss_err(1, min_stat, "export name error (SPNEGO)"); gss_release_name(&min_stat, &MNname); gss_release_buffer(&min_stat, &name_buffer); #endif return 0; } heimdal-7.5.0/lib/gssapi/gss_acquire_cred.30000644000175000017500000004353413026237312016704 0ustar niknik.\" Copyright (c) 2003 - 2007 Kungliga Tekniska Högskolan .\" (Royal Institute of Technology, Stockholm, Sweden). .\" All rights reserved. .\" .\" Redistribution and use in source and binary forms, with or without .\" modification, are permitted provided that the following conditions .\" are met: .\" .\" 1. Redistributions of source code must retain the above copyright .\" notice, this list of conditions and the following disclaimer. .\" .\" 2. Redistributions in binary form must reproduce the above copyright .\" notice, this list of conditions and the following disclaimer in the .\" documentation and/or other materials provided with the distribution. .\" .\" 3. Neither the name of the Institute nor the names of its contributors .\" may be used to endorse or promote products derived from this software .\" without specific prior written permission. .\" .\" THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND .\" ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE .\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE .\" ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE .\" FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL .\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS .\" OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) .\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT .\" LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF .\" SUCH DAMAGE. .\" .\" $Id$ .\" .Dd October 26, 2005 .Dt GSS_ACQUIRE_CRED 3 .Os HEIMDAL .Sh NAME .Nm gss_accept_sec_context , .Nm gss_acquire_cred , .Nm gss_add_cred , .Nm gss_add_oid_set_member , .Nm gss_canonicalize_name , .Nm gss_compare_name , .Nm gss_context_time , .Nm gss_create_empty_oid_set , .Nm gss_delete_sec_context , .Nm gss_display_name , .Nm gss_display_status , .Nm gss_duplicate_name , .Nm gss_export_name , .Nm gss_export_sec_context , .Nm gss_get_mic , .Nm gss_import_name , .Nm gss_import_sec_context , .Nm gss_indicate_mechs , .Nm gss_init_sec_context , .Nm gss_inquire_context , .Nm gss_inquire_cred , .Nm gss_inquire_cred_by_mech , .Nm gss_inquire_mechs_for_name , .Nm gss_inquire_names_for_mech , .Nm gss_krb5_ccache_name , .Nm gss_krb5_compat_des3_mic , .Nm gss_krb5_copy_ccache , .Nm gss_krb5_import_cred .Nm gsskrb5_extract_authz_data_from_sec_context , .Nm gsskrb5_register_acceptor_identity , .Nm gss_krb5_import_ccache , .Nm gss_krb5_get_tkt_flags , .Nm gss_process_context_token , .Nm gss_release_buffer , .Nm gss_release_cred , .Nm gss_release_name , .Nm gss_release_oid_set , .Nm gss_seal , .Nm gss_sign , .Nm gss_test_oid_set_member , .Nm gss_unseal , .Nm gss_unwrap , .Nm gss_verify , .Nm gss_verify_mic , .Nm gss_wrap , .Nm gss_wrap_size_limit .Nd Generic Security Service Application Program Interface library .Sh LIBRARY GSS-API library (libgssapi, -lgssapi) .Sh SYNOPSIS .In gssapi.h .Pp .Ft OM_uint32 .Fo gss_accept_sec_context .Fa "OM_uint32 * minor_status" .Fa "gss_ctx_id_t * context_handle" .Fa "gss_const_cred_id_t acceptor_cred_handle" .Fa "const gss_buffer_t input_token_buffer" .Fa "const gss_channel_bindings_t input_chan_bindings" .Fa "gss_name_t * src_name" .Fa "gss_OID * mech_type" .Fa "gss_buffer_t output_token" .Fa "OM_uint32 * ret_flags" .Fa "OM_uint32 * time_rec" .Fa "gss_cred_id_t * delegated_cred_handle" .Fc .Pp .Ft OM_uint32 .Fo gss_acquire_cred .Fa "OM_uint32 * minor_status" .Fa "gss_const_name_t desired_name" .Fa "OM_uint32 time_req" .Fa "const gss_OID_set desired_mechs" .Fa "gss_cred_usage_t cred_usage" .Fa "gss_cred_id_t * output_cred_handle" .Fa "gss_OID_set * actual_mechs" .Fa "OM_uint32 * time_rec" .Fc .Ft OM_uint32 .Fo gss_add_cred .Fa "OM_uint32 *minor_status" .Fa "gss_const_cred_id_t input_cred_handle" .Fa "gss_const_name_t desired_name" .Fa "const gss_OID desired_mech" .Fa "gss_cred_usage_t cred_usage" .Fa "OM_uint32 initiator_time_req" .Fa "OM_uint32 acceptor_time_req" .Fa "gss_cred_id_t *output_cred_handle" .Fa "gss_OID_set *actual_mechs" .Fa "OM_uint32 *initiator_time_rec" .Fa "OM_uint32 *acceptor_time_rec" .Fc .Ft OM_uint32 .Fo gss_add_oid_set_member .Fa "OM_uint32 * minor_status" .Fa "const gss_OID member_oid" .Fa "gss_OID_set * oid_set" .Fc .Ft OM_uint32 .Fo gss_canonicalize_name .Fa "OM_uint32 * minor_status" .Fa "gss_const_name_t input_name" .Fa "const gss_OID mech_type" .Fa "gss_name_t * output_name" .Fc .Ft OM_uint32 .Fo gss_compare_name .Fa "OM_uint32 * minor_status" .Fa "gss_const_name_t name1" .Fa "gss_const_name_t name2" .Fa "int * name_equal" .Fc .Ft OM_uint32 .Fo gss_context_time .Fa "OM_uint32 * minor_status" .Fa "gss_const_ctx_id_t context_handle" .Fa "OM_uint32 * time_rec" .Fc .Ft OM_uint32 .Fo gss_create_empty_oid_set .Fa "OM_uint32 * minor_status" .Fa "gss_OID_set * oid_set" .Fc .Ft OM_uint32 .Fo gss_delete_sec_context .Fa "OM_uint32 * minor_status" .Fa "gss_ctx_id_t * context_handle" .Fa "gss_buffer_t output_token" .Fc .Ft OM_uint32 .Fo gss_display_name .Fa "OM_uint32 * minor_status" .Fa "gss_const_name_t input_name" .Fa "gss_buffer_t output_name_buffer" .Fa "gss_OID * output_name_type" .Fc .Ft OM_uint32 .Fo gss_display_status .Fa "OM_uint32 *minor_status" .Fa "OM_uint32 status_value" .Fa "int status_type" .Fa "const gss_OID mech_type" .Fa "OM_uint32 *message_context" .Fa "gss_buffer_t status_string" .Fc .Ft OM_uint32 .Fo gss_duplicate_name .Fa "OM_uint32 * minor_status" .Fa "gss_const_name_t src_name" .Fa "gss_name_t * dest_name" .Fc .Ft OM_uint32 .Fo gss_export_name .Fa "OM_uint32 * minor_status" .Fa "gss_const_name_t input_name" .Fa "gss_buffer_t exported_name" .Fc .Ft OM_uint32 .Fo gss_export_sec_context .Fa "OM_uint32 * minor_status" .Fa "gss_ctx_id_t * context_handle" .Fa "gss_buffer_t interprocess_token" .Fc .Ft OM_uint32 .Fo gss_get_mic .Fa "OM_uint32 * minor_status" .Fa "gss_const_ctx_id_t context_handle" .Fa "gss_qop_t qop_req" .Fa "const gss_buffer_t message_buffer" .Fa "gss_buffer_t message_token" .Fc .Ft OM_uint32 .Fo gss_import_name .Fa "OM_uint32 * minor_status" .Fa "const gss_buffer_t input_name_buffer" .Fa "const gss_OID input_name_type" .Fa "gss_name_t * output_name" .Fc .Ft OM_uint32 .Fo gss_import_sec_context .Fa "OM_uint32 * minor_status" .Fa "const gss_buffer_t interprocess_token" .Fa "gss_ctx_id_t * context_handle" .Fc .Ft OM_uint32 .Fo gss_indicate_mechs .Fa "OM_uint32 * minor_status" .Fa "gss_OID_set * mech_set" .Fc .Ft OM_uint32 .Fo gss_init_sec_context .Fa "OM_uint32 * minor_status" .Fa "gss_const_cred_id_t initiator_cred_handle" .Fa "gss_ctx_id_t * context_handle" .Fa "gss_const_name_t target_name" .Fa "const gss_OID mech_type" .Fa "OM_uint32 req_flags" .Fa "OM_uint32 time_req" .Fa "const gss_channel_bindings_t input_chan_bindings" .Fa "const gss_buffer_t input_token" .Fa "gss_OID * actual_mech_type" .Fa "gss_buffer_t output_token" .Fa "OM_uint32 * ret_flags" .Fa "OM_uint32 * time_rec" .Fc .Ft OM_uint32 .Fo gss_inquire_context .Fa "OM_uint32 * minor_status" .Fa "gss_const_ctx_id_t context_handle" .Fa "gss_name_t * src_name" .Fa "gss_name_t * targ_name" .Fa "OM_uint32 * lifetime_rec" .Fa "gss_OID * mech_type" .Fa "OM_uint32 * ctx_flags" .Fa "int * locally_initiated" .Fa "int * open_context" .Fc .Ft OM_uint32 .Fo gss_inquire_cred .Fa "OM_uint32 * minor_status" .Fa "gss_const_cred_id_t cred_handle" .Fa "gss_name_t * name" .Fa "OM_uint32 * lifetime" .Fa "gss_cred_usage_t * cred_usage" .Fa "gss_OID_set * mechanisms" .Fc .Ft OM_uint32 .Fo gss_inquire_cred_by_mech .Fa "OM_uint32 * minor_status" .Fa "gss_const_cred_id_t cred_handle" .Fa "const gss_OID mech_type" .Fa "gss_name_t * name" .Fa "OM_uint32 * initiator_lifetime" .Fa "OM_uint32 * acceptor_lifetime" .Fa "gss_cred_usage_t * cred_usage" .Fc .Ft OM_uint32 .Fo gss_inquire_mechs_for_name .Fa "OM_uint32 * minor_status" .Fa "gss_const_name_t input_name" .Fa "gss_OID_set * mech_types" .Fc .Ft OM_uint32 .Fo gss_inquire_names_for_mech .Fa "OM_uint32 * minor_status" .Fa "const gss_OID mechanism" .Fa "gss_OID_set * name_types" .Fc .Ft OM_uint32 .Fo gss_krb5_ccache_name .Fa "OM_uint32 *minor" .Fa "const char *name" .Fa "const char **old_name" .Fc .Ft OM_uint32 .Fo gss_krb5_copy_ccache .Fa "OM_uint32 *minor" .Fa "gss_cred_id_t cred" .Fa "krb5_ccache out" .Fc .Ft OM_uint32 .Fo gss_krb5_import_cred .Fa "OM_uint32 *minor_status" .Fa "krb5_ccache id" .Fa "krb5_principal keytab_principal" .Fa "krb5_keytab keytab" .Fa "gss_cred_id_t *cred" .Fc .Ft OM_uint32 .Fo gss_krb5_compat_des3_mic .Fa "OM_uint32 * minor_status" .Fa "gss_ctx_id_t context_handle" .Fa "int onoff" .Fc .Ft OM_uint32 .Fo gsskrb5_extract_authz_data_from_sec_context .Fa "OM_uint32 *minor_status" .Fa "gss_ctx_id_t context_handle" .Fa "int ad_type" .Fa "gss_buffer_t ad_data" .Fc .Ft OM_uint32 .Fo gsskrb5_register_acceptor_identity .Fa "const char *identity" .Fc .Ft OM_uint32 .Fo gss_krb5_import_cache .Fa "OM_uint32 *minor" .Fa "krb5_ccache id" .Fa "krb5_keytab keytab" .Fa "gss_cred_id_t *cred" .Fc .Ft OM_uint32 .Fo gss_krb5_get_tkt_flags .Fa "OM_uint32 *minor_status" .Fa "gss_ctx_id_t context_handle" .Fa "OM_uint32 *tkt_flags" .Fc .Ft OM_uint32 .Fo gss_process_context_token .Fa "OM_uint32 * minor_status" .Fa "gss_const_ctx_id_t context_handle" .Fa "const gss_buffer_t token_buffer" .Fc .Ft OM_uint32 .Fo gss_release_buffer .Fa "OM_uint32 * minor_status" .Fa "gss_buffer_t buffer" .Fc .Ft OM_uint32 .Fo gss_release_cred .Fa "OM_uint32 * minor_status" .Fa "gss_cred_id_t * cred_handle" .Fc .Ft OM_uint32 .Fo gss_release_name .Fa "OM_uint32 * minor_status" .Fa "gss_name_t * input_name" .Fc .Ft OM_uint32 .Fo gss_release_oid_set .Fa "OM_uint32 * minor_status" .Fa "gss_OID_set * set" .Fc .Ft OM_uint32 .Fo gss_seal .Fa "OM_uint32 * minor_status" .Fa "gss_ctx_id_t context_handle" .Fa "int conf_req_flag" .Fa "int qop_req" .Fa "gss_buffer_t input_message_buffer" .Fa "int * conf_state" .Fa "gss_buffer_t output_message_buffer" .Fc .Ft OM_uint32 .Fo gss_sign .Fa "OM_uint32 * minor_status" .Fa "gss_ctx_id_t context_handle" .Fa "int qop_req" .Fa "gss_buffer_t message_buffer" .Fa "gss_buffer_t message_token" .Fc .Ft OM_uint32 .Fo gss_test_oid_set_member .Fa "OM_uint32 * minor_status" .Fa "const gss_OID member" .Fa "const gss_OID_set set" .Fa "int * present" .Fc .Ft OM_uint32 .Fo gss_unseal .Fa "OM_uint32 * minor_status" .Fa "gss_ctx_id_t context_handle" .Fa "gss_buffer_t input_message_buffer" .Fa "gss_buffer_t output_message_buffer" .Fa "int * conf_state" .Fa "int * qop_state" .Fc .Ft OM_uint32 .Fo gss_unwrap .Fa "OM_uint32 * minor_status" .Fa "gss_const_ctx_id_t context_handle" .Fa "const gss_buffer_t input_message_buffer" .Fa "gss_buffer_t output_message_buffer" .Fa "int * conf_state" .Fa "gss_qop_t * qop_state" .Fc .Ft OM_uint32 .Fo gss_verify .Fa "OM_uint32 * minor_status" .Fa "gss_ctx_id_t context_handle" .Fa "gss_buffer_t message_buffer" .Fa "gss_buffer_t token_buffer" .Fa "int * qop_state" .Fc .Ft OM_uint32 .Fo gss_verify_mic .Fa "OM_uint32 * minor_status" .Fa "gss_const_ctx_id_t context_handle" .Fa "const gss_buffer_t message_buffer" .Fa "const gss_buffer_t token_buffer" .Fa "gss_qop_t * qop_state" .Fc .Ft OM_uint32 .Fo gss_wrap .Fa "OM_uint32 * minor_status" .Fa "gss_const_ctx_id_t context_handle" .Fa "int conf_req_flag" .Fa "gss_qop_t qop_req" .Fa "const gss_buffer_t input_message_buffer" .Fa "int * conf_state" .Fa "gss_buffer_t output_message_buffer" .Fc .Ft OM_uint32 .Fo gss_wrap_size_limit .Fa "OM_uint32 * minor_status" .Fa "gss_const_ctx_id_t context_handle" .Fa "int conf_req_flag" .Fa "gss_qop_t qop_req" .Fa "OM_uint32 req_output_size" .Fa "OM_uint32 * max_input_size" .Fc .Sh DESCRIPTION Generic Security Service API (GSS-API) version 2, and its C binding, is described in .Li RFC2743 and .Li RFC2744 . Version 1 (deprecated) of the C binding is described in .Li RFC1509 . .Pp Heimdals GSS-API implementation supports the following mechanisms .Bl -bullet .It .Li GSS_KRB5_MECHANISM .It .Li GSS_SPNEGO_MECHANISM .El .Pp GSS-API have generic name types that all mechanism are supposed to implement (if possible): .Bl -bullet .It .Li GSS_C_NT_USER_NAME .It .Li GSS_C_NT_MACHINE_UID_NAME .It .Li GSS_C_NT_STRING_UID_NAME .It .Li GSS_C_NT_HOSTBASED_SERVICE .It .Li GSS_C_NT_ANONYMOUS .It .Li GSS_C_NT_EXPORT_NAME .El .Pp GSS-API implementations that supports Kerberos 5 have some additional name types: .Bl -bullet .It .Li GSS_KRB5_NT_PRINCIPAL_NAME .It .Li GSS_KRB5_NT_USER_NAME .It .Li GSS_KRB5_NT_MACHINE_UID_NAME .It .Li GSS_KRB5_NT_STRING_UID_NAME .El .Pp In GSS-API, names have two forms, internal names and contiguous string names. .Bl -bullet .It .Li Internal name and mechanism name .Pp Internal names are implementation specific representation of a GSS-API name. .Li Mechanism names special form of internal names corresponds to one and only one mechanism. .Pp In GSS-API an internal name is stored in a .Dv gss_name_t . .It .Li Contiguous string name and exported name .Pp Contiguous string names are gssapi names stored in a .Dv OCTET STRING that together with a name type identifier (OID) uniquely specifies a gss-name. A special form of the contiguous string name is the exported name that have a OID embedded in the string to make it unique. Exported name have the nametype .Dv GSS_C_NT_EXPORT_NAME . .Pp In GSS-API an contiguous string name is stored in a .Dv gss_buffer_t . .Pp Exported names also have the property that they are specified by the mechanism itself and compatible between different GSS-API implementations. .El .Sh ACCESS CONTROL There are two ways of comparing GSS-API names, either comparing two internal names with each other or two contiguous string names with either other. .Pp To compare two internal names with each other, import (if needed) the names with .Fn gss_import_name into the GSS-API implementation and the compare the imported name with .Fn gss_compare_name . .Pp Importing names can be slow, so when its possible to store exported names in the access control list, comparing contiguous string name might be better. .Pp when comparing contiguous string name, first export them into a .Dv GSS_C_NT_EXPORT_NAME name with .Fn gss_export_name and then compare with .Xr memcmp 3 . .Pp Note that there are might be a difference between the two methods of comparing names. The first (using .Fn gss_compare_name ) will compare to (unauthenticated) names are the same. The second will compare if a mechanism will authenticate them as the same principal. .Pp For example, if .Fn gss_import_name name was used with .Dv GSS_C_NO_OID the default syntax is used for all mechanism the GSS-API implementation supports. When compare the imported name of .Dv GSS_C_NO_OID it may match several mechanism names (MN). .Pp The resulting name from .Fn gss_display_name must not be used for acccess control. .Sh FUNCTIONS .Fn gss_display_name takes the gss name in .Fa input_name and puts a printable form in .Fa output_name_buffer . .Fa output_name_buffer should be freed when done using .Fn gss_release_buffer . .Fa output_name_type can either be .Dv NULL or a pointer to a .Li gss_OID and will in the latter case contain the OID type of the name. The name must only be used for printing. If access control is needed, see section .Sx ACCESS CONTROL . .Pp .Fn gss_inquire_context returns information about the context. Information is available even after the context have expired. .Fa lifetime_rec argument is set to .Dv GSS_C_INDEFINITE (don't expire) or the number of seconds that the context is still valid. A value of 0 means that the context is expired. .Fa mech_type argument should be considered readonly and must not be released. .Fa src_name and .Fn dest_name are both mechanims names and must be released with .Fn gss_release_name when no longer used. .Pp .Nm gss_context_time will return the amount of time (in seconds) of the context is still valid. If its expired .Fa time_rec will be set to 0 and .Dv GSS_S_CONTEXT_EXPIRED returned. .Pp .Fn gss_sign , .Fn gss_verify , .Fn gss_seal , and .Fn gss_unseal are part of the GSS-API V1 interface and are obsolete. The functions should not be used for new applications. They are provided so that version 1 applications can link against the library. .Sh EXTENSIONS .Fn gss_krb5_ccache_name sets the internal kerberos 5 credential cache name to .Fa name . The old name is returned in .Fa old_name , and must not be freed. The data allocated for .Fa old_name is free upon next call to .Fn gss_krb5_ccache_name . This function is not threadsafe if .Fa old_name argument is used. .Pp .Fn gss_krb5_copy_ccache will extract the krb5 credentials that are transferred from the initiator to the acceptor when using token delegation in the Kerberos mechanism. The acceptor receives the delegated token in the last argument to .Fn gss_accept_sec_context . .Pp .Fn gss_krb5_import_cred will import the krb5 credentials (both keytab and/or credential cache) into gss credential so it can be used withing GSS-API. The .Fa ccache is copied by reference and thus shared, so if the credential is destroyed with .Fa krb5_cc_destroy , all users of thep .Fa gss_cred_id_t returned by .Fn gss_krb5_import_ccache will fail. .Pp .Fn gsskrb5_register_acceptor_identity sets the Kerberos 5 filebased keytab that the acceptor will use. The .Fa identifier is the file name. .Pp .Fn gsskrb5_extract_authz_data_from_sec_context extracts the Kerberos authorizationdata that may be stored within the context. Tha caller must free the returned buffer .Fa ad_data with .Fn gss_release_buffer upon success. .Pp .Fn gss_krb5_get_tkt_flags return the ticket flags for the kerberos ticket receive when authenticating the initiator. Only valid on the acceptor context. .Pp .Fn gss_krb5_compat_des3_mic turns on or off the compatibility with older version of Heimdal using des3 get and verify mic, this is way to programmatically set the [gssapi]broken_des3_mic and [gssapi]correct_des3_mic flags (see COMPATIBILITY section in .Xr gssapi 3 ) . If the CPP symbol .Dv GSS_C_KRB5_COMPAT_DES3_MIC is present, .Fn gss_krb5_compat_des3_mic exists. .Fn gss_krb5_compat_des3_mic will be removed in a later version of the GSS-API library. .Sh SEE ALSO .Xr gssapi 3 , .Xr krb5 3 , .Xr krb5_ccache 3 , .Xr kerberos 8 heimdal-7.5.0/lib/gssapi/gssapi.30000644000175000017500000001316013026237312014660 0ustar niknik.\" Copyright (c) 2003 - 2005 Kungliga Tekniska Högskolan .\" (Royal Institute of Technology, Stockholm, Sweden). .\" All rights reserved. .\" .\" Redistribution and use in source and binary forms, with or without .\" modification, are permitted provided that the following conditions .\" are met: .\" .\" 1. Redistributions of source code must retain the above copyright .\" notice, this list of conditions and the following disclaimer. .\" .\" 2. Redistributions in binary form must reproduce the above copyright .\" notice, this list of conditions and the following disclaimer in the .\" documentation and/or other materials provided with the distribution. .\" .\" 3. Neither the name of the Institute nor the names of its contributors .\" may be used to endorse or promote products derived from this software .\" without specific prior written permission. .\" .\" THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND .\" ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE .\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE .\" ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE .\" FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL .\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS .\" OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) .\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT .\" LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF .\" SUCH DAMAGE. .\" .\" $Id$ .\" .Dd April 20, 2005 .Dt GSSAPI 3 .Os .Sh NAME .Nm gssapi .Nd Generic Security Service Application Program Interface library .Sh LIBRARY GSS-API Library (libgssapi, -lgssapi) .Sh DESCRIPTION The Generic Security Service Application Program Interface (GSS-API) provides security services to callers in a generic fashion, supportable with a range of underlying mechanisms and technologies and hence allowing source-level portability of applications to different environments. .Pp The GSS-API implementation in Heimdal implements the Kerberos 5 and the SPNEGO GSS-API security mechanisms. .Sh LIST OF FUNCTIONS These functions constitute the gssapi library, .Em libgssapi . Declarations for these functions may be obtained from the include file .Pa gssapi.h . .Bl -column -compact .It Sy Name/Page .It Xr gss_accept_sec_context 3 .It Xr gss_acquire_cred 3 .It Xr gss_add_cred 3 .It Xr gss_add_oid_set_member 3 .It Xr gss_canonicalize_name 3 .It Xr gss_compare_name 3 .It Xr gss_context_time 3 .It Xr gss_create_empty_oid_set 3 .It Xr gss_delete_sec_context 3 .It Xr gss_display_name 3 .It Xr gss_display_status 3 .It Xr gss_duplicate_name 3 .It Xr gss_export_name 3 .It Xr gss_export_sec_context 3 .It Xr gss_get_mic 3 .It Xr gss_import_name 3 .It Xr gss_import_sec_context 3 .It Xr gss_indicate_mechs 3 .It Xr gss_init_sec_context 3 .It Xr gss_inquire_context 3 .It Xr gss_inquire_cred 3 .It Xr gss_inquire_cred_by_mech 3 .It Xr gss_inquire_mechs_for_name 3 .It Xr gss_inquire_names_for_mech 3 .It Xr gss_krb5_ccache_name 3 .It Xr gss_krb5_compat_des3_mic 3 .It Xr gss_krb5_copy_ccache 3 .It Xr gss_krb5_extract_authz_data_from_sec_context 3 .It Xr gss_krb5_import_ccache 3 .It Xr gss_process_context_token 3 .It Xr gss_release_buffer 3 .It Xr gss_release_cred 3 .It Xr gss_release_name 3 .It Xr gss_release_oid_set 3 .It Xr gss_seal 3 .It Xr gss_sign 3 .It Xr gss_test_oid_set_member 3 .It Xr gss_unseal 3 .It Xr gss_unwrap 3 .It Xr gss_verify 3 .It Xr gss_verify_mic 3 .It Xr gss_wrap 3 .It Xr gss_wrap_size_limit 3 .El .Sh COMPATIBILITY The .Nm Heimdal GSS-API implementation had a bug in releases before 0.6 that made it fail to inter-operate when using DES3 with other GSS-API implementations when using .Fn gss_get_mic / .Fn gss_verify_mic . It is possible to modify the behavior of the generator of the MIC with the .Pa krb5.conf configuration file so that old clients/servers will still work. .Pp New clients/servers will try both the old and new MIC in Heimdal 0.6. In 0.7 it will check only if configured - the compatibility code will be removed in 0.8. .Pp Heimdal 0.6 still generates by default the broken GSS-API DES3 mic, this will change in 0.7 to generate correct des3 mic. .Pp To turn on compatibility with older clients and servers, change the .Nm [gssapi] .Ar broken_des3_mic in .Pa krb5.conf that contains a list of globbing expressions that will be matched against the server name. To turn off generation of the old (incompatible) mic of the MIC use .Nm [gssapi] .Ar correct_des3_mic . .Pp If a match for a entry is in both .Nm [gssapi] .Ar correct_des3_mic and .Nm [gssapi] .Ar broken_des3_mic , the later will override. .Pp This config option modifies behaviour for both clients and servers. .Pp Microsoft implemented SPNEGO to Windows2000, however, they managed to get it wrong, their implementation didn't fill in the MechListMIC in the reply token with the right content. There is a work around for this problem, but not all implementation support it. .Pp Heimdal defaults to correct SPNEGO when the the kerberos implementation uses CFX, or when it is configured by the user. To turn on compatibility with peers, use option .Nm [gssapi] .Ar require_mechlist_mic . .Sh EXAMPLES .Bd -literal -offset indent [gssapi] broken_des3_mic = cvs/*@SU.SE broken_des3_mic = host/*@E.KTH.SE correct_des3_mic = host/*@SU.SE require_mechlist_mic = host/*@SU.SE .Ed .Sh BUGS All of 0.5.x versions of .Nm heimdal had broken token delegations in the client side, the server side was correct. .Sh SEE ALSO .Xr krb5 3 , .Xr krb5.conf 5 , .Xr kerberos 8 heimdal-7.5.0/lib/gssapi/test_add_store_cred.c0000644000175000017500000001317013026237312017453 0ustar niknik/* * Copyright (c) 2015 Cryptonector LLC. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. The name Cryptonector LLC may not be used to endorse or promote * products derived from this software without specific prior written * permission. * * THIS SOFTWARE IS PROVIDED BY KTH AND ITS CONTRIBUTORS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL KTH OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifdef HAVE_CONFIG_H #include #endif #include #include #include #include #include #include #include #include static void print_gss_err(OM_uint32 stat, int status_type, gss_OID mech) { gss_buffer_desc str; OM_uint32 maj; OM_uint32 min; OM_uint32 msg_ctx = 0; int first = 1; do { maj = gss_display_status(&min, stat, status_type, mech, &msg_ctx, &str); if (maj != GSS_S_COMPLETE) { fprintf(stderr, "Error displaying GSS %s error (%lu): %lu, %lu", status_type == GSS_C_GSS_CODE ? "major" : "minor", (unsigned long)stat, (unsigned long)maj, (unsigned long)min); return; } if (first) { fprintf(stderr, "GSS %s error: %.*s\n", status_type == GSS_C_GSS_CODE ? "major" : "minor", (int)str.length, (char *)str.value); first = 0; } else { fprintf(stderr, "\t%.*s\n", (int)str.length, (char *)str.value); } gss_release_buffer(&min, &str); } while (msg_ctx != 0); } static void print_gss_errs(OM_uint32 major, OM_uint32 minor, gss_OID mech) { print_gss_err(major, GSS_C_GSS_CODE, GSS_C_NO_OID); print_gss_err(major, GSS_C_MECH_CODE, mech); } static void gss_err(int exitval, OM_uint32 major, OM_uint32 minor, gss_OID mech, const char *fmt, ...) { va_list args; va_start(args, fmt); vwarnx(fmt, args); va_end(args); print_gss_errs(major, minor, mech); exit(exitval); } static int version_flag = 0; static int help_flag = 0; static struct getargs args[] = { {"version", 0, arg_flag, &version_flag, "print version", NULL }, {"help", 0, arg_flag, &help_flag, NULL, NULL } }; static void usage(int ret) { arg_printusage(args, sizeof(args)/sizeof(*args), NULL, "from_ccache to_ccache"); exit(ret); } int main(int argc, char **argv) { OM_uint32 major, minor; gss_cred_id_t from_cred = GSS_C_NO_CREDENTIAL; gss_cred_id_t to_cred = GSS_C_NO_CREDENTIAL; gss_cred_id_t cred = GSS_C_NO_CREDENTIAL; char *from_env; char *to_env; int optidx = 0; setprogname(argv[0]); if (getarg(args, sizeof(args) / sizeof(args[0]), argc, argv, &optidx)) usage(1); if (help_flag) usage (0); if (version_flag){ print_version(NULL); exit(0); } argc -= optidx; argv += optidx; if (argc < 2) errx(1, "required arguments missing"); if (argc > 2) errx(1, "too many arguments"); if (asprintf(&from_env, "KRB5CCNAME=%s", argv[0]) == -1 || from_env == NULL) err(1, "out of memory"); if (asprintf(&to_env, "KRB5CCNAME=%s", argv[1]) == -1 || to_env == NULL) err(1, "out of memory"); putenv(from_env); major = gss_add_cred(&minor, GSS_C_NO_CREDENTIAL, GSS_C_NO_NAME, GSS_KRB5_MECHANISM, GSS_C_INITIATE, GSS_C_INDEFINITE, GSS_C_INDEFINITE, &from_cred, NULL, NULL, NULL); if (major != GSS_S_COMPLETE) gss_err(1, major, minor, GSS_KRB5_MECHANISM, "failed to acquire creds from %s", argv[0]); putenv(to_env); major = gss_store_cred(&minor, from_cred, GSS_C_INITIATE, GSS_KRB5_MECHANISM, 1, 1, NULL, NULL); if (major != GSS_S_COMPLETE) gss_err(1, major, minor, GSS_KRB5_MECHANISM, "failed to store creds into %s", argv[1]); (void) gss_release_cred(&minor, &from_cred); (void) gss_release_cred(&minor, &to_cred); major = gss_add_cred(&minor, GSS_C_NO_CREDENTIAL, GSS_C_NO_NAME, GSS_KRB5_MECHANISM, GSS_C_INITIATE, GSS_C_INDEFINITE, GSS_C_INDEFINITE, &cred, NULL, NULL, NULL); if (major != GSS_S_COMPLETE) gss_err(1, major, minor, GSS_KRB5_MECHANISM, "failed to acquire creds from %s", argv[1]); (void) gss_release_cred(&minor, &cred); putenv("KRB5CCNAME"); free(from_env); free(to_env); return 0; } heimdal-7.5.0/lib/gssapi/NTMakefile0000644000175000017500000004364613026237312015224 0ustar niknik######################################################################## # # Copyright (c) 2009-2011, Secure Endpoints Inc. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # - Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # # - Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in # the documentation and/or other materials provided with the # distribution. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS # FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE # COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, # BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN # ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. # RELDIR=lib\gssapi !include ../../windows/NTMakefile.w32 krb5src = \ krb5/8003.c \ krb5/accept_sec_context.c \ krb5/acquire_cred.c \ krb5/add_cred.c \ krb5/address_to_krb5addr.c \ krb5/aeap.c \ krb5/arcfour.c \ krb5/authorize_localname.c \ krb5/canonicalize_name.c \ krb5/creds.c \ krb5/ccache_name.c \ krb5/cfx.c \ krb5/cfx.h \ krb5/compare_name.c \ krb5/compat.c \ krb5/context_time.c \ krb5/copy_ccache.c \ krb5/decapsulate.c \ krb5/delete_sec_context.c \ krb5/display_name.c \ krb5/display_status.c \ krb5/duplicate_name.c \ krb5/encapsulate.c \ krb5/export_name.c \ krb5/export_sec_context.c \ krb5/external.c \ krb5/get_mic.c \ krb5/gsskrb5_locl.h \ krb5/import_name.c \ krb5/import_sec_context.c \ krb5/indicate_mechs.c \ krb5/init.c \ krb5/init_sec_context.c \ krb5/inquire_context.c \ krb5/inquire_cred.c \ krb5/inquire_cred_by_mech.c \ krb5/inquire_cred_by_oid.c \ krb5/inquire_mechs_for_name.c \ krb5/inquire_names_for_mech.c \ krb5/inquire_sec_context_by_oid.c \ krb5/pname_to_uid.c \ krb5/process_context_token.c \ krb5/prf.c \ krb5/release_buffer.c \ krb5/release_cred.c \ krb5/release_name.c \ krb5/sequence.c \ krb5/store_cred.c \ krb5/set_cred_option.c \ krb5/set_sec_context_option.c \ krb5/ticket_flags.c \ krb5/unwrap.c \ krb5/verify_mic.c \ krb5/wrap.c mechsrc = \ mech/context.h \ mech/context.c \ mech/cred.h \ mech/gss_accept_sec_context.c \ mech/gss_acquire_cred.c \ mech/gss_acquire_cred_ext.c \ mech/gss_acquire_cred_with_password.c \ mech/gss_add_cred.c \ mech/gss_add_cred_with_password.c \ mech/gss_add_oid_set_member.c \ mech/gss_aeap.c \ mech/gss_authorize_localname.c \ mech/gss_buffer_set.c \ mech/gss_canonicalize_name.c \ mech/gss_compare_name.c \ mech/gss_context_time.c \ mech/gss_create_empty_oid_set.c \ mech/gss_cred.c \ mech/gss_decapsulate_token.c \ mech/gss_delete_name_attribute.c \ mech/gss_delete_sec_context.c \ mech/gss_display_name.c \ mech/gss_display_name_ext.c \ mech/gss_display_status.c \ mech/gss_duplicate_name.c \ mech/gss_duplicate_oid.c \ mech/gss_encapsulate_token.c \ mech/gss_export_name.c \ mech/gss_export_name_composite.c \ mech/gss_export_sec_context.c \ mech/gss_get_mic.c \ mech/gss_get_name_attribute.c \ mech/gss_import_name.c \ mech/gss_import_sec_context.c \ mech/gss_indicate_mechs.c \ mech/gss_init_sec_context.c \ mech/gss_inquire_context.c \ mech/gss_inquire_cred.c \ mech/gss_inquire_cred_by_mech.c \ mech/gss_inquire_cred_by_oid.c \ mech/gss_inquire_mechs_for_name.c \ mech/gss_inquire_name.c \ mech/gss_inquire_names_for_mech.c \ mech/gss_krb5.c \ mech/gss_mech_switch.c \ mech/gss_mo.c \ mech/gss_names.c \ mech/gss_oid.c \ mech/gss_oid_equal.c \ mech/gss_oid_to_str.c \ mech/gss_pname_to_uid.c \ mech/gss_process_context_token.c \ mech/gss_pseudo_random.c \ mech/gss_release_buffer.c \ mech/gss_release_cred.c \ mech/gss_release_name.c \ mech/gss_release_oid.c \ mech/gss_release_oid_set.c \ mech/gss_seal.c \ mech/gss_set_cred_option.c \ mech/gss_set_name_attribute.c \ mech/gss_set_sec_context_option.c \ mech/gss_sign.c \ mech/gss_store_cred.c \ mech/gss_test_oid_set_member.c \ mech/gss_unseal.c \ mech/gss_unwrap.c \ mech/gss_utils.c \ mech/gss_verify.c \ mech/gss_verify_mic.c \ mech/gss_wrap.c \ mech/gss_wrap_size_limit.c \ mech/gss_inquire_sec_context_by_oid.c \ mech/mech_switch.h \ mech/mechqueue.h \ mech/mech_locl.h \ mech/name.h \ mech/utils.h spnegosrc = \ spnego/accept_sec_context.c \ spnego/compat.c \ spnego/context_stubs.c \ spnego/cred_stubs.c \ spnego/external.c \ spnego/init_sec_context.c \ spnego/spnego_locl.h ntlmsrc = \ ntlm/accept_sec_context.c \ ntlm/acquire_cred.c \ ntlm/add_cred.c \ ntlm/canonicalize_name.c \ ntlm/compare_name.c \ ntlm/context_time.c \ ntlm/creds.c \ ntlm/crypto.c \ ntlm/delete_sec_context.c \ ntlm/display_name.c \ ntlm/display_status.c \ ntlm/duplicate_name.c \ ntlm/export_name.c \ ntlm/export_sec_context.c \ ntlm/external.c \ ntlm/ntlm.h \ ntlm/import_name.c \ ntlm/import_sec_context.c \ ntlm/indicate_mechs.c \ ntlm/init_sec_context.c \ ntlm/inquire_context.c \ ntlm/inquire_cred_by_mech.c \ ntlm/inquire_mechs_for_name.c \ ntlm/inquire_names_for_mech.c \ ntlm/inquire_sec_context_by_oid.c \ ntlm/iter_cred.c \ ntlm/process_context_token.c \ ntlm/release_cred.c \ ntlm/release_name.c \ ntlm/kdc.c $(OBJ)\ntlm\ntlm-private.h: $(ntlmsrc) $(PERL) ../../cf/make-proto.pl -q -P remove -p $@ $(ntlmsrc) $(OBJ)\krb5\gsskrb5-private.h: $(krb5src) $(PERL) ../../cf/make-proto.pl -q -P remove -p $@ $(krb5src) $(OBJ)\spnego\spnego-private.h: $(spnegosrc) $(PERL) ../../cf/make-proto.pl -q -P remove -p $@ $(spnegosrc) gssapi_files = $(OBJ)\gssapi\asn1_gssapi_asn1.x spnego_files = $(OBJ)\spnego\asn1_spnego_asn1.x $(gssapi_files:.x=.c): $$(@R).x $(spnego_files:.x=.c): $$(@R).x $(gssapi_files) $(OBJ)\gssapi\gssapi_asn1.hx $(OBJ)\gssapi\gssapi_asn1-priv.hx: \ $(BINDIR)\asn1_compile.exe mech\gssapi.asn1 cd $(OBJ)\gssapi $(BINDIR)\asn1_compile.exe --one-code-file $(SRCDIR)\mech\gssapi.asn1 gssapi_asn1 \ || ( $(RM) $(OBJ)\gssapi\gssapi_asn1.h ; exit /b 1 ) cd $(SRCDIR) $(spnego_files) $(OBJ)\spnego\spnego_asn1.hx $(OBJ)\spnego\spnego_asn1-priv.hx: \ $(BINDIR)\asn1_compile.exe spnego\spnego.asn1 cd $(OBJ)\spnego $(BINDIR)\asn1_compile --one-code-file --sequence=MechTypeList \ $(SRCDIR)\spnego\spnego.asn1 spnego_asn1 \ || ( $(RM) $(OBJ)\spnego\spnego_asn1.h ; exit /b 1 ) cd $(SRCDIR) $(OBJ)\gkrb5_err.c $(OBJ)\gkrb5_err.h: krb5\gkrb5_err.et cd $(OBJ) $(BINDIR)\compile_et.exe $(SRCDIR)\krb5\gkrb5_err.et cd $(SRCDIR) INCFILES= \ $(INCDIR)\gssapi.h \ $(INCDIR)\gssapi\gssapi.h \ $(INCDIR)\gssapi\gssapi_krb5.h \ $(INCDIR)\gssapi\gssapi_oid.h \ $(INCDIR)\gssapi\gssapi_ntlm.h \ $(INCDIR)\gssapi\gssapi_spnego.h \ $(INCDIR)\gssapi\gkrb5_err.h \ $(OBJ)\ntlm\ntlm-private.h \ $(OBJ)\spnego\spnego-private.h \ $(OBJ)\krb5\gsskrb5-private.h \ $(OBJ)\gkrb5_err.h \ $(OBJ)\gssapi\gssapi_asn1.h \ $(OBJ)\gssapi\gssapi_asn1-priv.h \ $(OBJ)\spnego\spnego_asn1.h \ $(OBJ)\spnego\spnego_asn1-priv.h all:: $(INCFILES) libgssapi_OBJs = \ $(OBJ)\krb5/8003.obj \ $(OBJ)\krb5/accept_sec_context.obj \ $(OBJ)\krb5/acquire_cred.obj \ $(OBJ)\krb5/add_cred.obj \ $(OBJ)\krb5/address_to_krb5addr.obj \ $(OBJ)\krb5/authorize_localname.obj \ $(OBJ)\krb5/aeap.obj \ $(OBJ)\krb5/arcfour.obj \ $(OBJ)\krb5/canonicalize_name.obj \ $(OBJ)\krb5/creds.obj \ $(OBJ)\krb5/ccache_name.obj \ $(OBJ)\krb5/cfx.obj \ $(OBJ)\krb5/compare_name.obj \ $(OBJ)\krb5/compat.obj \ $(OBJ)\krb5/context_time.obj \ $(OBJ)\krb5/copy_ccache.obj \ $(OBJ)\krb5/decapsulate.obj \ $(OBJ)\krb5/delete_sec_context.obj \ $(OBJ)\krb5/display_name.obj \ $(OBJ)\krb5/display_status.obj \ $(OBJ)\krb5/duplicate_name.obj \ $(OBJ)\krb5/encapsulate.obj \ $(OBJ)\krb5/export_name.obj \ $(OBJ)\krb5/export_sec_context.obj \ $(OBJ)\krb5/external.obj \ $(OBJ)\krb5/get_mic.obj \ $(OBJ)\krb5/import_name.obj \ $(OBJ)\krb5/import_sec_context.obj \ $(OBJ)\krb5/indicate_mechs.obj \ $(OBJ)\krb5/init.obj \ $(OBJ)\krb5/init_sec_context.obj \ $(OBJ)\krb5/inquire_context.obj \ $(OBJ)\krb5/inquire_cred.obj \ $(OBJ)\krb5/inquire_cred_by_mech.obj \ $(OBJ)\krb5/inquire_cred_by_oid.obj \ $(OBJ)\krb5/inquire_mechs_for_name.obj \ $(OBJ)\krb5/inquire_names_for_mech.obj \ $(OBJ)\krb5/inquire_sec_context_by_oid.obj \ $(OBJ)\krb5/pname_to_uid.obj \ $(OBJ)\krb5/process_context_token.obj \ $(OBJ)\krb5/prf.obj \ $(OBJ)\krb5/release_buffer.obj \ $(OBJ)\krb5/release_cred.obj \ $(OBJ)\krb5/release_name.obj \ $(OBJ)\krb5/sequence.obj \ $(OBJ)\krb5/store_cred.obj \ $(OBJ)\krb5/set_cred_option.obj \ $(OBJ)\krb5/set_sec_context_option.obj \ $(OBJ)\krb5/ticket_flags.obj \ $(OBJ)\krb5/unwrap.obj \ $(OBJ)\krb5/verify_mic.obj \ $(OBJ)\krb5/wrap.obj \ $(OBJ)\mech/context.obj \ $(OBJ)\mech/gss_accept_sec_context.obj \ $(OBJ)\mech/gss_acquire_cred.obj \ $(OBJ)\mech/gss_acquire_cred_ext.obj \ $(OBJ)\mech/gss_acquire_cred_with_password.obj \ $(OBJ)\mech/gss_add_cred.obj \ $(OBJ)\mech/gss_add_cred_with_password.obj \ $(OBJ)\mech/gss_add_oid_set_member.obj \ $(OBJ)\mech/gss_aeap.obj \ $(OBJ)\mech/gss_authorize_localname.obj \ $(OBJ)\mech/gss_buffer_set.obj \ $(OBJ)\mech/gss_canonicalize_name.obj \ $(OBJ)\mech/gss_compare_name.obj \ $(OBJ)\mech/gss_context_time.obj \ $(OBJ)\mech/gss_create_empty_oid_set.obj \ $(OBJ)\mech/gss_cred.obj \ $(OBJ)\mech/gss_decapsulate_token.obj \ $(OBJ)\mech/gss_delete_name_attribute.obj \ $(OBJ)\mech/gss_delete_sec_context.obj \ $(OBJ)\mech/gss_display_name.obj \ $(OBJ)\mech/gss_display_name_ext.obj \ $(OBJ)\mech/gss_display_status.obj \ $(OBJ)\mech/gss_duplicate_name.obj \ $(OBJ)\mech/gss_duplicate_oid.obj \ $(OBJ)\mech/gss_encapsulate_token.obj \ $(OBJ)\mech/gss_export_name.obj \ $(OBJ)\mech/gss_export_name_composite.obj \ $(OBJ)\mech/gss_export_sec_context.obj \ $(OBJ)\mech/gss_get_mic.obj \ $(OBJ)\mech/gss_get_name_attribute.obj \ $(OBJ)\mech/gss_import_name.obj \ $(OBJ)\mech/gss_import_sec_context.obj \ $(OBJ)\mech/gss_indicate_mechs.obj \ $(OBJ)\mech/gss_init_sec_context.obj \ $(OBJ)\mech/gss_inquire_context.obj \ $(OBJ)\mech/gss_inquire_cred.obj \ $(OBJ)\mech/gss_inquire_cred_by_mech.obj \ $(OBJ)\mech/gss_inquire_cred_by_oid.obj \ $(OBJ)\mech/gss_inquire_mechs_for_name.obj \ $(OBJ)\mech/gss_inquire_name.obj \ $(OBJ)\mech/gss_inquire_names_for_mech.obj \ $(OBJ)\mech/gss_krb5.obj \ $(OBJ)\mech/gss_mech_switch.obj \ $(OBJ)\mech/gss_mo.obj \ $(OBJ)\mech/gss_names.obj \ $(OBJ)\mech/gss_oid.obj \ $(OBJ)\mech/gss_oid_equal.obj \ $(OBJ)\mech/gss_oid_to_str.obj \ $(OBJ)\mech/gss_pname_to_uid.obj \ $(OBJ)\mech/gss_process_context_token.obj \ $(OBJ)\mech/gss_pseudo_random.obj \ $(OBJ)\mech/gss_release_buffer.obj \ $(OBJ)\mech/gss_release_cred.obj \ $(OBJ)\mech/gss_release_name.obj \ $(OBJ)\mech/gss_release_oid.obj \ $(OBJ)\mech/gss_release_oid_set.obj \ $(OBJ)\mech/gss_seal.obj \ $(OBJ)\mech/gss_set_cred_option.obj \ $(OBJ)\mech/gss_set_name_attribute.obj \ $(OBJ)\mech/gss_set_sec_context_option.obj \ $(OBJ)\mech/gss_sign.obj \ $(OBJ)\mech/gss_store_cred.obj \ $(OBJ)\mech/gss_test_oid_set_member.obj \ $(OBJ)\mech/gss_unseal.obj \ $(OBJ)\mech/gss_unwrap.obj \ $(OBJ)\mech/gss_utils.obj \ $(OBJ)\mech/gss_verify.obj \ $(OBJ)\mech/gss_verify_mic.obj \ $(OBJ)\mech/gss_wrap.obj \ $(OBJ)\mech/gss_wrap_size_limit.obj \ $(OBJ)\mech/gss_inquire_sec_context_by_oid.obj \ $(OBJ)\spnego/accept_sec_context.obj \ $(OBJ)\spnego/compat.obj \ $(OBJ)\spnego/context_stubs.obj \ $(OBJ)\spnego/cred_stubs.obj \ $(OBJ)\spnego/external.obj \ $(OBJ)\spnego/init_sec_context.obj \ $(OBJ)\ntlm/accept_sec_context.obj \ $(OBJ)\ntlm/acquire_cred.obj \ $(OBJ)\ntlm/add_cred.obj \ $(OBJ)\ntlm/canonicalize_name.obj \ $(OBJ)\ntlm/compare_name.obj \ $(OBJ)\ntlm/context_time.obj \ $(OBJ)\ntlm/creds.obj \ $(OBJ)\ntlm/crypto.obj \ $(OBJ)\ntlm/delete_sec_context.obj \ $(OBJ)\ntlm/display_name.obj \ $(OBJ)\ntlm/display_status.obj \ $(OBJ)\ntlm/duplicate_name.obj \ $(OBJ)\ntlm/export_name.obj \ $(OBJ)\ntlm/export_sec_context.obj \ $(OBJ)\ntlm/external.obj \ $(OBJ)\ntlm/import_name.obj \ $(OBJ)\ntlm/import_sec_context.obj \ $(OBJ)\ntlm/indicate_mechs.obj \ $(OBJ)\ntlm/init_sec_context.obj \ $(OBJ)\ntlm/inquire_context.obj \ $(OBJ)\ntlm/inquire_cred_by_mech.obj \ $(OBJ)\ntlm/inquire_mechs_for_name.obj \ $(OBJ)\ntlm/inquire_names_for_mech.obj \ $(OBJ)\ntlm/inquire_sec_context_by_oid.obj \ $(OBJ)\ntlm/iter_cred.obj \ $(OBJ)\ntlm/process_context_token.obj \ $(OBJ)\ntlm/release_cred.obj \ $(OBJ)\ntlm/release_name.obj \ $(OBJ)\ntlm/kdc.obj \ $(OBJ)\gkrb5_err.obj \ $(spnego_files:.x=.obj) \ $(gssapi_files:.x=.obj) GCOPTS=-I$(SRCDIR) -I$(OBJ) -Igssapi -DBUILD_GSSAPI_LIB {$(OBJ)\krb5}.c{$(OBJ)\krb5}.obj:: $(C2OBJ_NP) -Fo$(OBJ)\krb5\ -Fd$(OBJ)\krb5\ -I$(OBJ)\krb5 $(GCOPTS) {krb5}.c{$(OBJ)\krb5}.obj:: $(C2OBJ_NP) -Fo$(OBJ)\krb5\ -Fd$(OBJ)\krb5\ -I$(OBJ)\krb5 $(GCOPTS) -DASN1_LIB {$(OBJ)\mech}.c{$(OBJ)\mech}.obj:: $(C2OBJ_NP) -Fo$(OBJ)\mech\ -Fd$(OBJ)\mech\ -I$(OBJ)\mech $(GCOPTS) {mech}.c{$(OBJ)\mech}.obj:: $(C2OBJ_NP) -Fo$(OBJ)\mech\ -Fd$(OBJ)\mech\ -I$(OBJ)\mech -I$(OBJ)\gssapi $(GCOPTS) -DASN1_LIB {$(OBJ)\ntlm}.c{$(OBJ)\ntlm}.obj:: $(C2OBJ_NP) -Fo$(OBJ)\ntlm\ -Fd$(OBJ)\ntlm\ -I$(OBJ)\ntlm $(GCOPTS) {ntlm}.c{$(OBJ)\ntlm}.obj:: $(C2OBJ_NP) -Fo$(OBJ)\ntlm\ -Fd$(OBJ)\ntlm\ -I$(OBJ)\ntlm $(GCOPTS) -DASN1_LIB {$(OBJ)\spnego}.c{$(OBJ)\spnego}.obj:: $(C2OBJ_NP) -Fo$(OBJ)\spnego\ -Fd$(OBJ)\spnego\ -I$(OBJ)\spnego $(GCOPTS) {spnego}.c{$(OBJ)\spnego}.obj:: $(C2OBJ_NP) -Fo$(OBJ)\spnego\ -Fd$(OBJ)\spnego\ -I$(OBJ)\spnego -Imech $(GCOPTS) -DASN1_LIB {$(OBJ)\gssapi}.c{$(OBJ)\gssapi}.obj:: $(C2OBJ_NP) -Fo$(OBJ)\gssapi\ -Fd$(OBJ)\gssapi\ -I$(OBJ)\gssapi $(GCOPTS) {$(OBJ)}.c{$(OBJ)}.obj:: $(C2OBJ_P) $(GCOPTS) {$(OBJ)\spnego}.x{$(OBJ)\spnego}.c: $(CP) $** $@ {$(OBJ)\gssapi}.x{$(OBJ)\gssapi}.c: $(CP) $** $@ {gssapi}.h{$(INCDIR)\gssapi}.h: $(CP) $** $@ {$(OBJ)}.h{$(INCDIR)\gssapi}.h: $(CP) $** $@ {$(OBJ)\gssapi}.hx{$(OBJ)\gssapi}.h: $(CP) $** $@ {$(OBJ)\spnego}.hx{$(OBJ)\spnego}.h: $(CP) $** $@ LIBGSSAPI_LIBS=\ $(LIBHEIMBASE) \ $(LIBROKEN) \ $(LIBHEIMDAL) \ $(LIBHEIMNTLM) \ $(LIBCOMERR) LIBGSSAPI_SDKLIBS=\ $(PTHREAD_LIB) !ifndef STATICLIBS RES=$(OBJ)\libgssapi-version.res $(BINDIR)\gssapi.dll: $(libgssapi_OBJs) $(RES) $(DLLGUILINK_C) -implib:$(LIBGSSAPI) \ -out:$(BINDIR)\gssapi.dll \ -def:libgssapi-exports.def \ $(LIBGSSAPI_LIBS) $(RES) $(LIBGSSAPI_SDKLIBS) @<< $(libgssapi_OBJs: = ) << $(DLLPREP_NODIST) $(LIBGSSAPI): $(BINDIR)\gssapi.dll clean:: -$(RM) $(BINDIR)\gssapi.* !else $(LIBGSSAPI): $(libgssapi_OBJs) $(LIBCON_C) -OUT:$@ $(LIBGSSAPI_LIBS) $(LIBGSSAPI_SDKLIBS) @<< $(libgssapi_OBJs: = ) << !endif all:: $(LIBGSSAPI) clean:: -$(RM) $(LIBGSSAPI) prep:: mkdirs-gss mkdirs-gss: !if !exist($(OBJ)\ntlm) $(MKDIR) $(OBJ)\ntlm !endif !if !exist($(OBJ)\krb5) $(MKDIR) $(OBJ)\krb5 !endif !if !exist($(OBJ)\spnego) $(MKDIR) $(OBJ)\spnego !endif !if !exist($(OBJ)\mech) $(MKDIR) $(OBJ)\mech !endif !if !exist($(OBJ)\gssapi) $(MKDIR) $(OBJ)\gssapi !endif clean:: -$(RM) $(OBJ)\ntlm\*.* -$(RM) $(OBJ)\krb5\*.* -$(RM) $(OBJ)\spnego\*.* -$(RM) $(OBJ)\mech\*.* -$(RM) $(OBJ)\gssapi\*.* all-tools:: $(BINDIR)\gsstool.exe $(BINDIR)\gsstool.exe: $(OBJ)\gsstool.obj $(OBJ)\gss-commands.obj $(LIBGSSAPI) $(LIBROKEN) $(LIBSL) $(LIBVERS) $(EXECONLINK) $(EXEPREP) $(OBJ)\gss-commands.c $(OBJ)\gss-commands.h: gss-commands.in cd $(OBJ) $(CP) $(SRCDIR)\gss-commands.in gss-commands.in $(BINDIR)\slc.exe gss-commands.in cd $(SRCDIR) !ifdef ELISP # This macro invocation is used to update the libgssapi_OBJs # definition below (generate-obj-macro is defined in maint.el): (generate-obj-macro "libgssapi_OBJs" (concat "\t$(OBJ)\\gkrb5_err.obj \\\n" "\t$(spnego_files:.x=.obj) \\\n" "\t$(gssapi_files:.x=.obj)") "krb5src" "mechsrc" "spnegosrc" "ntlmsrc") !endif test-exports: $(PERL) ..\..\cf\w32-check-exported-symbols.pl --vs version-script.map --def libgssapi-exports.def test:: test-exports TEST_BINARIES=\ $(OBJ)\test_oid.exe \ $(OBJ)\test_names.exe \ $(OBJ)\test_cfx.exe \ $(OBJ)\test_acquire_cred.exe \ $(OBJ)\test_cred.exe \ $(OBJ)\test_kcred.exe \ $(OBJ)\test_context.exe \ $(OBJ)\test_ntlm.exe $(OBJ)\test_oid.exe: $(OBJ)\test_oid.obj $(LIBGSSAPI) $(LIBROKEN) $(EXECONLINK) $(EXEPREP_NODIST) $(OBJ)\test_names.exe: $(OBJ)\test_names.obj $(LIBGSSAPI) $(LIBROKEN) $(LIBVERS) $(EXECONLINK) $(EXEPREP_NODIST) $(OBJ)\test_cfx.exe: $(OBJ)\krb5\test_cfx.obj $(LIBHEIMDAL) $(LIBGSSAPI) $(LIBROKEN) $(EXECONLINK) $(EXEPREP_NODIST) $(OBJ)\test_acquire_cred.exe: $(OBJ)\test_acquire_cred.obj $(OBJ)\test_common.obj \ $(LIBGSSAPI) $(LIBROKEN) $(LIBVERS) $(EXECONLINK) $(EXEPREP_NODIST) $(OBJ)\test_cred.exe: $(OBJ)\test_cred.obj $(LIBGSSAPI) $(LIBROKEN) $(LIBVERS) $(EXECONLINK) $(EXEPREP_NODIST) $(OBJ)\test_kcred.exe: $(OBJ)\test_kcred.obj $(LIBGSSAPI) $(LIBHEIMDAL) \ $(LIBROKEN) $(LIBVERS) $(EXECONLINK) $(EXEPREP_NODIST) $(OBJ)\test_context.exe: $(OBJ)\test_context.obj $(OBJ)\test_common.obj \ $(LIBGSSAPI) $(LIBHEIMDAL) $(LIBROKEN) $(LIBVERS) $(EXECONLINK) $(EXEPREP_NODIST) $(OBJ)\test_ntlm.exe: $(OBJ)\test_ntlm.obj $(OBJ)\test_common.obj \ $(LIBGSSAPI) $(LIBHEIMNTLM) $(LIBROKEN) $(LIBVERS) $(EXECONLINK) $(EXEPREP_NODIST) {}.c{$(OBJ)}.obj:: $(C2OBJ_P) -I$(OBJ)\krb5 -I$(OBJ) -I$(SRCDIR) -I$(SRCDIR)\gssapi test-binaries: $(LIBGSSAPI) $(TEST_BINARIES) run-test: cd $(OBJ) -test_oid -test_names -test_cfx -test_kcred cd $(SRCDIR) test:: test-binaries run-test heimdal-7.5.0/lib/gssapi/test_common.h0000644000175000017500000000322512136107747016020 0ustar niknik/* * Copyright (c) 2006 - 2007 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of KTH nor the names of its contributors may be * used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY KTH AND ITS CONTRIBUTORS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL KTH OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /* $Id$ */ char * gssapi_err(OM_uint32, OM_uint32, gss_OID); heimdal-7.5.0/lib/hx509/0000755000175000017500000000000013214604041012670 5ustar niknikheimdal-7.5.0/lib/hx509/sel-gram.c0000644000175000017500000013364613212445575014575 0ustar niknik/* A Bison parser, made by GNU Bison 2.3. */ /* Skeleton implementation for Bison's Yacc-like parsers in C Copyright (C) 1984, 1989, 1990, 2000, 2001, 2002, 2003, 2004, 2005, 2006 Free Software Foundation, Inc. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ /* As a special exception, you may create a larger work that contains part or all of the Bison parser skeleton and distribute that work under terms of your choice, so long as that work isn't itself a parser generator using the skeleton or a modified version thereof as a parser skeleton. Alternatively, if you modify or redistribute the parser skeleton itself, you may (at your option) remove this special exception, which will cause the skeleton and the resulting Bison output files to be licensed under the GNU General Public License without this special exception. This special exception was added by the Free Software Foundation in version 2.2 of Bison. */ /* C LALR(1) parser skeleton written by Richard Stallman, by simplifying the original so-called "semantic" parser. */ /* All symbols defined below should begin with yy or YY, to avoid infringing on user name space. This should be done even for local variables, as they might otherwise be expanded by user macros. There are some unavoidable exceptions within include files to define necessary library symbols; they are noted "INFRINGES ON USER NAME SPACE" below. */ /* Identify Bison output. */ #define YYBISON 1 /* Bison version. */ #define YYBISON_VERSION "2.3" /* Skeleton name. */ #define YYSKELETON_NAME "yacc.c" /* Pure parsers. */ #define YYPURE 0 /* Using locations. */ #define YYLSP_NEEDED 0 /* Tokens. */ #ifndef YYTOKENTYPE # define YYTOKENTYPE /* Put the tokens into the symbol table, so that GDB and other debuggers know about them. */ enum yytokentype { kw_TRUE = 258, kw_FALSE = 259, kw_AND = 260, kw_OR = 261, kw_IN = 262, kw_TAILMATCH = 263, NUMBER = 264, STRING = 265, IDENTIFIER = 266 }; #endif /* Tokens. */ #define kw_TRUE 258 #define kw_FALSE 259 #define kw_AND 260 #define kw_OR 261 #define kw_IN 262 #define kw_TAILMATCH 263 #define NUMBER 264 #define STRING 265 #define IDENTIFIER 266 /* Copy the first part of user declarations. */ #line 34 "sel-gram.y" #ifdef HAVE_CONFIG_H #include #endif #include #include #include #if !defined(yylex) #define yylex _hx509_sel_yylex #define yywrap _hx509_sel_yywrap #endif #if !defined(yyparse) #define yyparse _hx509_sel_yyparse #define yyerror _hx509_sel_yyerror #define yylval _hx509_sel_yylval #define yychar _hx509_sel_yychar #define yydebug _hx509_sel_yydebug #define yynerrs _hx509_sel_yynerrs #endif /* Enabling traces. */ #ifndef YYDEBUG # define YYDEBUG 0 #endif /* Enabling verbose error messages. */ #ifdef YYERROR_VERBOSE # undef YYERROR_VERBOSE # define YYERROR_VERBOSE 1 #else # define YYERROR_VERBOSE 0 #endif /* Enabling the token table. */ #ifndef YYTOKEN_TABLE # define YYTOKEN_TABLE 0 #endif #if ! defined YYSTYPE && ! defined YYSTYPE_IS_DECLARED typedef union YYSTYPE #line 57 "sel-gram.y" { char *string; struct hx_expr *expr; } /* Line 193 of yacc.c. */ #line 146 "sel-gram.c" YYSTYPE; # define yystype YYSTYPE /* obsolescent; will be withdrawn */ # define YYSTYPE_IS_DECLARED 1 # define YYSTYPE_IS_TRIVIAL 1 #endif /* Copy the second part of user declarations. */ /* Line 216 of yacc.c. */ #line 159 "sel-gram.c" #ifdef short # undef short #endif #ifdef YYTYPE_UINT8 typedef YYTYPE_UINT8 yytype_uint8; #else typedef unsigned char yytype_uint8; #endif #ifdef YYTYPE_INT8 typedef YYTYPE_INT8 yytype_int8; #elif (defined __STDC__ || defined __C99__FUNC__ \ || defined __cplusplus || defined _MSC_VER) typedef signed char yytype_int8; #else typedef short int yytype_int8; #endif #ifdef YYTYPE_UINT16 typedef YYTYPE_UINT16 yytype_uint16; #else typedef unsigned short int yytype_uint16; #endif #ifdef YYTYPE_INT16 typedef YYTYPE_INT16 yytype_int16; #else typedef short int yytype_int16; #endif #ifndef YYSIZE_T # ifdef __SIZE_TYPE__ # define YYSIZE_T __SIZE_TYPE__ # elif defined size_t # define YYSIZE_T size_t # elif ! defined YYSIZE_T && (defined __STDC__ || defined __C99__FUNC__ \ || defined __cplusplus || defined _MSC_VER) # include /* INFRINGES ON USER NAME SPACE */ # define YYSIZE_T size_t # else # define YYSIZE_T unsigned int # endif #endif #define YYSIZE_MAXIMUM ((YYSIZE_T) -1) #ifndef YY_ # if defined YYENABLE_NLS && YYENABLE_NLS # if ENABLE_NLS # include /* INFRINGES ON USER NAME SPACE */ # define YY_(msgid) dgettext ("bison-runtime", msgid) # endif # endif # ifndef YY_ # define YY_(msgid) msgid # endif #endif /* Suppress unused-variable warnings by "using" E. */ #if ! defined lint || defined __GNUC__ # define YYUSE(e) ((void) (e)) #else # define YYUSE(e) /* empty */ #endif /* Identity function, used to suppress warnings about constant conditions. */ #ifndef lint # define YYID(n) (n) #else #if (defined __STDC__ || defined __C99__FUNC__ \ || defined __cplusplus || defined _MSC_VER) static int YYID (int i) #else static int YYID (i) int i; #endif { return i; } #endif #if ! defined yyoverflow || YYERROR_VERBOSE /* The parser invokes alloca or malloc; define the necessary symbols. */ # ifdef YYSTACK_USE_ALLOCA # if YYSTACK_USE_ALLOCA # ifdef __GNUC__ # define YYSTACK_ALLOC __builtin_alloca # elif defined __BUILTIN_VA_ARG_INCR # include /* INFRINGES ON USER NAME SPACE */ # elif defined _AIX # define YYSTACK_ALLOC __alloca # elif defined _MSC_VER # include /* INFRINGES ON USER NAME SPACE */ # define alloca _alloca # else # define YYSTACK_ALLOC alloca # if ! defined _ALLOCA_H && ! defined _STDLIB_H && (defined __STDC__ || defined __C99__FUNC__ \ || defined __cplusplus || defined _MSC_VER) # include /* INFRINGES ON USER NAME SPACE */ # ifndef _STDLIB_H # define _STDLIB_H 1 # endif # endif # endif # endif # endif # ifdef YYSTACK_ALLOC /* Pacify GCC's `empty if-body' warning. */ # define YYSTACK_FREE(Ptr) do { /* empty */; } while (YYID (0)) # ifndef YYSTACK_ALLOC_MAXIMUM /* The OS might guarantee only one guard page at the bottom of the stack, and a page size can be as small as 4096 bytes. So we cannot safely invoke alloca (N) if N exceeds 4096. Use a slightly smaller number to allow for a few compiler-allocated temporary stack slots. */ # define YYSTACK_ALLOC_MAXIMUM 4032 /* reasonable circa 2006 */ # endif # else # define YYSTACK_ALLOC YYMALLOC # define YYSTACK_FREE YYFREE # ifndef YYSTACK_ALLOC_MAXIMUM # define YYSTACK_ALLOC_MAXIMUM YYSIZE_MAXIMUM # endif # if (defined __cplusplus && ! defined _STDLIB_H \ && ! ((defined YYMALLOC || defined malloc) \ && (defined YYFREE || defined free))) # include /* INFRINGES ON USER NAME SPACE */ # ifndef _STDLIB_H # define _STDLIB_H 1 # endif # endif # ifndef YYMALLOC # define YYMALLOC malloc # if ! defined malloc && ! defined _STDLIB_H && (defined __STDC__ || defined __C99__FUNC__ \ || defined __cplusplus || defined _MSC_VER) void *malloc (YYSIZE_T); /* INFRINGES ON USER NAME SPACE */ # endif # endif # ifndef YYFREE # define YYFREE free # if ! defined free && ! defined _STDLIB_H && (defined __STDC__ || defined __C99__FUNC__ \ || defined __cplusplus || defined _MSC_VER) void free (void *); /* INFRINGES ON USER NAME SPACE */ # endif # endif # endif #endif /* ! defined yyoverflow || YYERROR_VERBOSE */ #if (! defined yyoverflow \ && (! defined __cplusplus \ || (defined YYSTYPE_IS_TRIVIAL && YYSTYPE_IS_TRIVIAL))) /* A type that is properly aligned for any stack member. */ union yyalloc { yytype_int16 yyss; YYSTYPE yyvs; }; /* The size of the maximum gap between one aligned stack and the next. */ # define YYSTACK_GAP_MAXIMUM (sizeof (union yyalloc) - 1) /* The size of an array large to enough to hold all stacks, each with N elements. */ # define YYSTACK_BYTES(N) \ ((N) * (sizeof (yytype_int16) + sizeof (YYSTYPE)) \ + YYSTACK_GAP_MAXIMUM) /* Copy COUNT objects from FROM to TO. The source and destination do not overlap. */ # ifndef YYCOPY # if defined __GNUC__ && 1 < __GNUC__ # define YYCOPY(To, From, Count) \ __builtin_memcpy (To, From, (Count) * sizeof (*(From))) # else # define YYCOPY(To, From, Count) \ do \ { \ YYSIZE_T yyi; \ for (yyi = 0; yyi < (Count); yyi++) \ (To)[yyi] = (From)[yyi]; \ } \ while (YYID (0)) # endif # endif /* Relocate STACK from its old location to the new one. The local variables YYSIZE and YYSTACKSIZE give the old and new number of elements in the stack, and YYPTR gives the new location of the stack. Advance YYPTR to a properly aligned location for the next stack. */ # define YYSTACK_RELOCATE(Stack) \ do \ { \ YYSIZE_T yynewbytes; \ YYCOPY (&yyptr->Stack, Stack, yysize); \ Stack = &yyptr->Stack; \ yynewbytes = yystacksize * sizeof (*Stack) + YYSTACK_GAP_MAXIMUM; \ yyptr += yynewbytes / sizeof (*yyptr); \ } \ while (YYID (0)) #endif /* YYFINAL -- State number of the termination state. */ #define YYFINAL 21 /* YYLAST -- Last index in YYTABLE. */ #define YYLAST 50 /* YYNTOKENS -- Number of terminals. */ #define YYNTOKENS 21 /* YYNNTS -- Number of nonterminals. */ #define YYNNTS 11 /* YYNRULES -- Number of rules. */ #define YYNRULES 26 /* YYNRULES -- Number of states. */ #define YYNSTATES 50 /* YYTRANSLATE(YYLEX) -- Bison symbol number corresponding to YYLEX. */ #define YYUNDEFTOK 2 #define YYMAXUTOK 266 #define YYTRANSLATE(YYX) \ ((unsigned int) (YYX) <= YYMAXUTOK ? yytranslate[YYX] : YYUNDEFTOK) /* YYTRANSLATE[YYLEX] -- Bison symbol number corresponding to YYLEX. */ static const yytype_uint8 yytranslate[] = { 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 12, 2, 2, 2, 17, 2, 2, 13, 14, 2, 2, 15, 2, 20, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 16, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 18, 2, 19, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 }; #if YYDEBUG /* YYPRHS[YYN] -- Index of the first RHS symbol of rule number YYN in YYRHS. */ static const yytype_uint8 yyprhs[] = { 0, 0, 3, 5, 7, 9, 12, 16, 20, 24, 26, 28, 32, 37, 42, 46, 52, 56, 58, 60, 62, 64, 66, 68, 73, 78, 82 }; /* YYRHS -- A `-1'-separated list of the rules' RHS. */ static const yytype_int8 yyrhs[] = { 22, 0, -1, 23, -1, 3, -1, 4, -1, 12, 23, -1, 23, 5, 23, -1, 23, 6, 23, -1, 13, 23, 14, -1, 25, -1, 26, -1, 26, 15, 24, -1, 26, 16, 16, 26, -1, 26, 12, 16, 26, -1, 26, 8, 26, -1, 26, 7, 13, 24, 14, -1, 26, 7, 30, -1, 27, -1, 28, -1, 29, -1, 30, -1, 9, -1, 10, -1, 11, 13, 24, 14, -1, 17, 18, 31, 19, -1, 11, 20, 31, -1, 11, -1 }; /* YYRLINE[YYN] -- source line where rule number YYN was defined. */ static const yytype_uint8 yyrline[] = { 0, 85, 85, 87, 88, 89, 90, 91, 92, 93, 96, 97, 100, 101, 102, 103, 104, 107, 108, 109, 110, 113, 114, 116, 119, 122, 124 }; #endif #if YYDEBUG || YYERROR_VERBOSE || YYTOKEN_TABLE /* YYTNAME[SYMBOL-NUM] -- String name of the symbol SYMBOL-NUM. First, the terminals, then, starting at YYNTOKENS, nonterminals. */ static const char *const yytname[] = { "$end", "error", "$undefined", "kw_TRUE", "kw_FALSE", "kw_AND", "kw_OR", "kw_IN", "kw_TAILMATCH", "NUMBER", "STRING", "IDENTIFIER", "'!'", "'('", "')'", "','", "'='", "'%'", "'{'", "'}'", "'.'", "$accept", "start", "expr", "words", "comp", "word", "number", "string", "function", "variable", "variables", 0 }; #endif # ifdef YYPRINT /* YYTOKNUM[YYLEX-NUM] -- Internal token number corresponding to token YYLEX-NUM. */ static const yytype_uint16 yytoknum[] = { 0, 256, 257, 258, 259, 260, 261, 262, 263, 264, 265, 266, 33, 40, 41, 44, 61, 37, 123, 125, 46 }; # endif /* YYR1[YYN] -- Symbol number of symbol that rule YYN derives. */ static const yytype_uint8 yyr1[] = { 0, 21, 22, 23, 23, 23, 23, 23, 23, 23, 24, 24, 25, 25, 25, 25, 25, 26, 26, 26, 26, 27, 28, 29, 30, 31, 31 }; /* YYR2[YYN] -- Number of symbols composing right hand side of rule YYN. */ static const yytype_uint8 yyr2[] = { 0, 2, 1, 1, 1, 2, 3, 3, 3, 1, 1, 3, 4, 4, 3, 5, 3, 1, 1, 1, 1, 1, 1, 4, 4, 3, 1 }; /* YYDEFACT[STATE-NAME] -- Default rule to reduce with in state STATE-NUM when YYTABLE doesn't specify something else to do. Zero means the default is an error. */ static const yytype_uint8 yydefact[] = { 0, 3, 4, 21, 22, 0, 0, 0, 0, 0, 2, 9, 0, 17, 18, 19, 20, 0, 5, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 10, 8, 26, 0, 6, 7, 0, 16, 14, 0, 0, 23, 0, 0, 24, 0, 13, 12, 11, 25, 15 }; /* YYDEFGOTO[NTERM-NUM]. */ static const yytype_int8 yydefgoto[] = { -1, 9, 10, 28, 11, 12, 13, 14, 15, 16, 32 }; /* YYPACT[STATE-NUM] -- Index in YYTABLE of the portion describing STATE-NUM. */ #define YYPACT_NINF -31 static const yytype_int8 yypact[] = { 22, -31, -31, -31, -31, -1, 22, 22, -11, 27, 11, -31, -6, -31, -31, -31, -31, 19, 11, 9, 26, -31, 22, 22, -4, 19, 24, 25, 28, 23, -31, 29, 31, 11, 11, 19, -31, -31, 19, 19, -31, 19, 26, -31, 30, -31, -31, -31, -31, -31 }; /* YYPGOTO[NTERM-NUM]. */ static const yytype_int8 yypgoto[] = { -31, -31, -3, -30, -31, -17, -31, -31, -31, 21, 1 }; /* YYTABLE[YYPACT[STATE-NUM]]. What to do in state STATE-NUM. If positive, shift that token. If negative, reduce the rule which number is the opposite. If zero, do what YYDEFACT says. If YYTABLE_NINF, syntax error. */ #define YYTABLE_NINF -1 static const yytype_uint8 yytable[] = { 29, 24, 25, 18, 19, 44, 26, 20, 37, 35, 27, 47, 17, 8, 22, 23, 22, 23, 29, 33, 34, 45, 46, 30, 29, 1, 2, 21, 3, 4, 5, 3, 4, 5, 6, 7, 8, 31, 41, 8, 38, 39, 40, 48, 49, 36, 0, 0, 0, 42, 43 }; static const yytype_int8 yycheck[] = { 17, 7, 8, 6, 7, 35, 12, 18, 25, 13, 16, 41, 13, 17, 5, 6, 5, 6, 35, 22, 23, 38, 39, 14, 41, 3, 4, 0, 9, 10, 11, 9, 10, 11, 12, 13, 17, 11, 15, 17, 16, 16, 14, 42, 14, 24, -1, -1, -1, 20, 19 }; /* YYSTOS[STATE-NUM] -- The (internal number of the) accessing symbol of state STATE-NUM. */ static const yytype_uint8 yystos[] = { 0, 3, 4, 9, 10, 11, 12, 13, 17, 22, 23, 25, 26, 27, 28, 29, 30, 13, 23, 23, 18, 0, 5, 6, 7, 8, 12, 16, 24, 26, 14, 11, 31, 23, 23, 13, 30, 26, 16, 16, 14, 15, 20, 19, 24, 26, 26, 24, 31, 14 }; #define yyerrok (yyerrstatus = 0) #define yyclearin (yychar = YYEMPTY) #define YYEMPTY (-2) #define YYEOF 0 #define YYACCEPT goto yyacceptlab #define YYABORT goto yyabortlab #define YYERROR goto yyerrorlab /* Like YYERROR except do call yyerror. This remains here temporarily to ease the transition to the new meaning of YYERROR, for GCC. Once GCC version 2 has supplanted version 1, this can go. */ #define YYFAIL goto yyerrlab #define YYRECOVERING() (!!yyerrstatus) #define YYBACKUP(Token, Value) \ do \ if (yychar == YYEMPTY && yylen == 1) \ { \ yychar = (Token); \ yylval = (Value); \ yytoken = YYTRANSLATE (yychar); \ YYPOPSTACK (1); \ goto yybackup; \ } \ else \ { \ yyerror (YY_("syntax error: cannot back up")); \ YYERROR; \ } \ while (YYID (0)) #define YYTERROR 1 #define YYERRCODE 256 /* YYLLOC_DEFAULT -- Set CURRENT to span from RHS[1] to RHS[N]. If N is 0, then set CURRENT to the empty location which ends the previous symbol: RHS[0] (always defined). */ #define YYRHSLOC(Rhs, K) ((Rhs)[K]) #ifndef YYLLOC_DEFAULT # define YYLLOC_DEFAULT(Current, Rhs, N) \ do \ if (YYID (N)) \ { \ (Current).first_line = YYRHSLOC (Rhs, 1).first_line; \ (Current).first_column = YYRHSLOC (Rhs, 1).first_column; \ (Current).last_line = YYRHSLOC (Rhs, N).last_line; \ (Current).last_column = YYRHSLOC (Rhs, N).last_column; \ } \ else \ { \ (Current).first_line = (Current).last_line = \ YYRHSLOC (Rhs, 0).last_line; \ (Current).first_column = (Current).last_column = \ YYRHSLOC (Rhs, 0).last_column; \ } \ while (YYID (0)) #endif /* YY_LOCATION_PRINT -- Print the location on the stream. This macro was not mandated originally: define only if we know we won't break user code: when these are the locations we know. */ #ifndef YY_LOCATION_PRINT # if defined YYLTYPE_IS_TRIVIAL && YYLTYPE_IS_TRIVIAL # define YY_LOCATION_PRINT(File, Loc) \ fprintf (File, "%d.%d-%d.%d", \ (Loc).first_line, (Loc).first_column, \ (Loc).last_line, (Loc).last_column) # else # define YY_LOCATION_PRINT(File, Loc) ((void) 0) # endif #endif /* YYLEX -- calling `yylex' with the right arguments. */ #ifdef YYLEX_PARAM # define YYLEX yylex (YYLEX_PARAM) #else # define YYLEX yylex () #endif /* Enable debugging if requested. */ #if YYDEBUG # ifndef YYFPRINTF # include /* INFRINGES ON USER NAME SPACE */ # define YYFPRINTF fprintf # endif # define YYDPRINTF(Args) \ do { \ if (yydebug) \ YYFPRINTF Args; \ } while (YYID (0)) # define YY_SYMBOL_PRINT(Title, Type, Value, Location) \ do { \ if (yydebug) \ { \ YYFPRINTF (stderr, "%s ", Title); \ yy_symbol_print (stderr, \ Type, Value); \ YYFPRINTF (stderr, "\n"); \ } \ } while (YYID (0)) /*--------------------------------. | Print this symbol on YYOUTPUT. | `--------------------------------*/ /*ARGSUSED*/ #if (defined __STDC__ || defined __C99__FUNC__ \ || defined __cplusplus || defined _MSC_VER) static void yy_symbol_value_print (FILE *yyoutput, int yytype, YYSTYPE const * const yyvaluep) #else static void yy_symbol_value_print (yyoutput, yytype, yyvaluep) FILE *yyoutput; int yytype; YYSTYPE const * const yyvaluep; #endif { if (!yyvaluep) return; # ifdef YYPRINT if (yytype < YYNTOKENS) YYPRINT (yyoutput, yytoknum[yytype], *yyvaluep); # else YYUSE (yyoutput); # endif switch (yytype) { default: break; } } /*--------------------------------. | Print this symbol on YYOUTPUT. | `--------------------------------*/ #if (defined __STDC__ || defined __C99__FUNC__ \ || defined __cplusplus || defined _MSC_VER) static void yy_symbol_print (FILE *yyoutput, int yytype, YYSTYPE const * const yyvaluep) #else static void yy_symbol_print (yyoutput, yytype, yyvaluep) FILE *yyoutput; int yytype; YYSTYPE const * const yyvaluep; #endif { if (yytype < YYNTOKENS) YYFPRINTF (yyoutput, "token %s (", yytname[yytype]); else YYFPRINTF (yyoutput, "nterm %s (", yytname[yytype]); yy_symbol_value_print (yyoutput, yytype, yyvaluep); YYFPRINTF (yyoutput, ")"); } /*------------------------------------------------------------------. | yy_stack_print -- Print the state stack from its BOTTOM up to its | | TOP (included). | `------------------------------------------------------------------*/ #if (defined __STDC__ || defined __C99__FUNC__ \ || defined __cplusplus || defined _MSC_VER) static void yy_stack_print (yytype_int16 *bottom, yytype_int16 *top) #else static void yy_stack_print (bottom, top) yytype_int16 *bottom; yytype_int16 *top; #endif { YYFPRINTF (stderr, "Stack now"); for (; bottom <= top; ++bottom) YYFPRINTF (stderr, " %d", *bottom); YYFPRINTF (stderr, "\n"); } # define YY_STACK_PRINT(Bottom, Top) \ do { \ if (yydebug) \ yy_stack_print ((Bottom), (Top)); \ } while (YYID (0)) /*------------------------------------------------. | Report that the YYRULE is going to be reduced. | `------------------------------------------------*/ #if (defined __STDC__ || defined __C99__FUNC__ \ || defined __cplusplus || defined _MSC_VER) static void yy_reduce_print (YYSTYPE *yyvsp, int yyrule) #else static void yy_reduce_print (yyvsp, yyrule) YYSTYPE *yyvsp; int yyrule; #endif { int yynrhs = yyr2[yyrule]; int yyi; unsigned long int yylno = yyrline[yyrule]; YYFPRINTF (stderr, "Reducing stack by rule %d (line %lu):\n", yyrule - 1, yylno); /* The symbols being reduced. */ for (yyi = 0; yyi < yynrhs; yyi++) { fprintf (stderr, " $%d = ", yyi + 1); yy_symbol_print (stderr, yyrhs[yyprhs[yyrule] + yyi], &(yyvsp[(yyi + 1) - (yynrhs)]) ); fprintf (stderr, "\n"); } } # define YY_REDUCE_PRINT(Rule) \ do { \ if (yydebug) \ yy_reduce_print (yyvsp, Rule); \ } while (YYID (0)) /* Nonzero means print parse trace. It is left uninitialized so that multiple parsers can coexist. */ int yydebug; #else /* !YYDEBUG */ # define YYDPRINTF(Args) # define YY_SYMBOL_PRINT(Title, Type, Value, Location) # define YY_STACK_PRINT(Bottom, Top) # define YY_REDUCE_PRINT(Rule) #endif /* !YYDEBUG */ /* YYINITDEPTH -- initial size of the parser's stacks. */ #ifndef YYINITDEPTH # define YYINITDEPTH 200 #endif /* YYMAXDEPTH -- maximum size the stacks can grow to (effective only if the built-in stack extension method is used). Do not make this value too large; the results are undefined if YYSTACK_ALLOC_MAXIMUM < YYSTACK_BYTES (YYMAXDEPTH) evaluated with infinite-precision integer arithmetic. */ #ifndef YYMAXDEPTH # define YYMAXDEPTH 10000 #endif #if YYERROR_VERBOSE # ifndef yystrlen # if defined __GLIBC__ && defined _STRING_H # define yystrlen strlen # else /* Return the length of YYSTR. */ #if (defined __STDC__ || defined __C99__FUNC__ \ || defined __cplusplus || defined _MSC_VER) static YYSIZE_T yystrlen (const char *yystr) #else static YYSIZE_T yystrlen (yystr) const char *yystr; #endif { YYSIZE_T yylen; for (yylen = 0; yystr[yylen]; yylen++) continue; return yylen; } # endif # endif # ifndef yystpcpy # if defined __GLIBC__ && defined _STRING_H && defined _GNU_SOURCE # define yystpcpy stpcpy # else /* Copy YYSRC to YYDEST, returning the address of the terminating '\0' in YYDEST. */ #if (defined __STDC__ || defined __C99__FUNC__ \ || defined __cplusplus || defined _MSC_VER) static char * yystpcpy (char *yydest, const char *yysrc) #else static char * yystpcpy (yydest, yysrc) char *yydest; const char *yysrc; #endif { char *yyd = yydest; const char *yys = yysrc; while ((*yyd++ = *yys++) != '\0') continue; return yyd - 1; } # endif # endif # ifndef yytnamerr /* Copy to YYRES the contents of YYSTR after stripping away unnecessary quotes and backslashes, so that it's suitable for yyerror. The heuristic is that double-quoting is unnecessary unless the string contains an apostrophe, a comma, or backslash (other than backslash-backslash). YYSTR is taken from yytname. If YYRES is null, do not copy; instead, return the length of what the result would have been. */ static YYSIZE_T yytnamerr (char *yyres, const char *yystr) { if (*yystr == '"') { YYSIZE_T yyn = 0; char const *yyp = yystr; for (;;) switch (*++yyp) { case '\'': case ',': goto do_not_strip_quotes; case '\\': if (*++yyp != '\\') goto do_not_strip_quotes; /* Fall through. */ default: if (yyres) yyres[yyn] = *yyp; yyn++; break; case '"': if (yyres) yyres[yyn] = '\0'; return yyn; } do_not_strip_quotes: ; } if (! yyres) return yystrlen (yystr); return yystpcpy (yyres, yystr) - yyres; } # endif /* Copy into YYRESULT an error message about the unexpected token YYCHAR while in state YYSTATE. Return the number of bytes copied, including the terminating null byte. If YYRESULT is null, do not copy anything; just return the number of bytes that would be copied. As a special case, return 0 if an ordinary "syntax error" message will do. Return YYSIZE_MAXIMUM if overflow occurs during size calculation. */ static YYSIZE_T yysyntax_error (char *yyresult, int yystate, int yychar) { int yyn = yypact[yystate]; if (! (YYPACT_NINF < yyn && yyn <= YYLAST)) return 0; else { int yytype = YYTRANSLATE (yychar); YYSIZE_T yysize0 = yytnamerr (0, yytname[yytype]); YYSIZE_T yysize = yysize0; YYSIZE_T yysize1; int yysize_overflow = 0; enum { YYERROR_VERBOSE_ARGS_MAXIMUM = 5 }; char const *yyarg[YYERROR_VERBOSE_ARGS_MAXIMUM]; int yyx; # if 0 /* This is so xgettext sees the translatable formats that are constructed on the fly. */ YY_("syntax error, unexpected %s"); YY_("syntax error, unexpected %s, expecting %s"); YY_("syntax error, unexpected %s, expecting %s or %s"); YY_("syntax error, unexpected %s, expecting %s or %s or %s"); YY_("syntax error, unexpected %s, expecting %s or %s or %s or %s"); # endif char *yyfmt; char const *yyf; static char const yyunexpected[] = "syntax error, unexpected %s"; static char const yyexpecting[] = ", expecting %s"; static char const yyor[] = " or %s"; char yyformat[sizeof yyunexpected + sizeof yyexpecting - 1 + ((YYERROR_VERBOSE_ARGS_MAXIMUM - 2) * (sizeof yyor - 1))]; char const *yyprefix = yyexpecting; /* Start YYX at -YYN if negative to avoid negative indexes in YYCHECK. */ int yyxbegin = yyn < 0 ? -yyn : 0; /* Stay within bounds of both yycheck and yytname. */ int yychecklim = YYLAST - yyn + 1; int yyxend = yychecklim < YYNTOKENS ? yychecklim : YYNTOKENS; int yycount = 1; yyarg[0] = yytname[yytype]; yyfmt = yystpcpy (yyformat, yyunexpected); for (yyx = yyxbegin; yyx < yyxend; ++yyx) if (yycheck[yyx + yyn] == yyx && yyx != YYTERROR) { if (yycount == YYERROR_VERBOSE_ARGS_MAXIMUM) { yycount = 1; yysize = yysize0; yyformat[sizeof yyunexpected - 1] = '\0'; break; } yyarg[yycount++] = yytname[yyx]; yysize1 = yysize + yytnamerr (0, yytname[yyx]); yysize_overflow |= (yysize1 < yysize); yysize = yysize1; yyfmt = yystpcpy (yyfmt, yyprefix); yyprefix = yyor; } yyf = YY_(yyformat); yysize1 = yysize + yystrlen (yyf); yysize_overflow |= (yysize1 < yysize); yysize = yysize1; if (yysize_overflow) return YYSIZE_MAXIMUM; if (yyresult) { /* Avoid sprintf, as that infringes on the user's name space. Don't have undefined behavior even if the translation produced a string with the wrong number of "%s"s. */ char *yyp = yyresult; int yyi = 0; while ((*yyp = *yyf) != '\0') { if (*yyp == '%' && yyf[1] == 's' && yyi < yycount) { yyp += yytnamerr (yyp, yyarg[yyi++]); yyf += 2; } else { yyp++; yyf++; } } } return yysize; } } #endif /* YYERROR_VERBOSE */ /*-----------------------------------------------. | Release the memory associated to this symbol. | `-----------------------------------------------*/ /*ARGSUSED*/ #if (defined __STDC__ || defined __C99__FUNC__ \ || defined __cplusplus || defined _MSC_VER) static void yydestruct (const char *yymsg, int yytype, YYSTYPE *yyvaluep) #else static void yydestruct (yymsg, yytype, yyvaluep) const char *yymsg; int yytype; YYSTYPE *yyvaluep; #endif { YYUSE (yyvaluep); if (!yymsg) yymsg = "Deleting"; YY_SYMBOL_PRINT (yymsg, yytype, yyvaluep, yylocationp); switch (yytype) { default: break; } } /* Prevent warnings from -Wmissing-prototypes. */ #ifdef YYPARSE_PARAM #if defined __STDC__ || defined __cplusplus int yyparse (void *YYPARSE_PARAM); #else int yyparse (); #endif #else /* ! YYPARSE_PARAM */ #if defined __STDC__ || defined __cplusplus int yyparse (void); #else int yyparse (); #endif #endif /* ! YYPARSE_PARAM */ /* The look-ahead symbol. */ int yychar; /* The semantic value of the look-ahead symbol. */ YYSTYPE yylval; /* Number of syntax errors so far. */ int yynerrs; /*----------. | yyparse. | `----------*/ #ifdef YYPARSE_PARAM #if (defined __STDC__ || defined __C99__FUNC__ \ || defined __cplusplus || defined _MSC_VER) int yyparse (void *YYPARSE_PARAM) #else int yyparse (YYPARSE_PARAM) void *YYPARSE_PARAM; #endif #else /* ! YYPARSE_PARAM */ #if (defined __STDC__ || defined __C99__FUNC__ \ || defined __cplusplus || defined _MSC_VER) int yyparse (void) #else int yyparse () #endif #endif { int yystate; int yyn; int yyresult; /* Number of tokens to shift before error messages enabled. */ int yyerrstatus; /* Look-ahead token as an internal (translated) token number. */ int yytoken = 0; #if YYERROR_VERBOSE /* Buffer for error messages, and its allocated size. */ char yymsgbuf[128]; char *yymsg = yymsgbuf; YYSIZE_T yymsg_alloc = sizeof yymsgbuf; #endif /* Three stacks and their tools: `yyss': related to states, `yyvs': related to semantic values, `yyls': related to locations. Refer to the stacks thru separate pointers, to allow yyoverflow to reallocate them elsewhere. */ /* The state stack. */ yytype_int16 yyssa[YYINITDEPTH]; yytype_int16 *yyss = yyssa; yytype_int16 *yyssp; /* The semantic value stack. */ YYSTYPE yyvsa[YYINITDEPTH]; YYSTYPE *yyvs = yyvsa; YYSTYPE *yyvsp; #define YYPOPSTACK(N) (yyvsp -= (N), yyssp -= (N)) YYSIZE_T yystacksize = YYINITDEPTH; /* The variables used to return semantic value and location from the action routines. */ YYSTYPE yyval; /* The number of symbols on the RHS of the reduced rule. Keep to zero when no symbol should be popped. */ int yylen = 0; YYDPRINTF ((stderr, "Starting parse\n")); yystate = 0; yyerrstatus = 0; yynerrs = 0; yychar = YYEMPTY; /* Cause a token to be read. */ /* Initialize stack pointers. Waste one element of value and location stack so that they stay on the same level as the state stack. The wasted elements are never initialized. */ yyssp = yyss; yyvsp = yyvs; goto yysetstate; /*------------------------------------------------------------. | yynewstate -- Push a new state, which is found in yystate. | `------------------------------------------------------------*/ yynewstate: /* In all cases, when you get here, the value and location stacks have just been pushed. So pushing a state here evens the stacks. */ yyssp++; yysetstate: *yyssp = yystate; if (yyss + yystacksize - 1 <= yyssp) { /* Get the current used size of the three stacks, in elements. */ YYSIZE_T yysize = yyssp - yyss + 1; #ifdef yyoverflow { /* Give user a chance to reallocate the stack. Use copies of these so that the &'s don't force the real ones into memory. */ YYSTYPE *yyvs1 = yyvs; yytype_int16 *yyss1 = yyss; /* Each stack pointer address is followed by the size of the data in use in that stack, in bytes. This used to be a conditional around just the two extra args, but that might be undefined if yyoverflow is a macro. */ yyoverflow (YY_("memory exhausted"), &yyss1, yysize * sizeof (*yyssp), &yyvs1, yysize * sizeof (*yyvsp), &yystacksize); yyss = yyss1; yyvs = yyvs1; } #else /* no yyoverflow */ # ifndef YYSTACK_RELOCATE goto yyexhaustedlab; # else /* Extend the stack our own way. */ if (YYMAXDEPTH <= yystacksize) goto yyexhaustedlab; yystacksize *= 2; if (YYMAXDEPTH < yystacksize) yystacksize = YYMAXDEPTH; { yytype_int16 *yyss1 = yyss; union yyalloc *yyptr = (union yyalloc *) YYSTACK_ALLOC (YYSTACK_BYTES (yystacksize)); if (! yyptr) goto yyexhaustedlab; YYSTACK_RELOCATE (yyss); YYSTACK_RELOCATE (yyvs); # undef YYSTACK_RELOCATE if (yyss1 != yyssa) YYSTACK_FREE (yyss1); } # endif #endif /* no yyoverflow */ yyssp = yyss + yysize - 1; yyvsp = yyvs + yysize - 1; YYDPRINTF ((stderr, "Stack size increased to %lu\n", (unsigned long int) yystacksize)); if (yyss + yystacksize - 1 <= yyssp) YYABORT; } YYDPRINTF ((stderr, "Entering state %d\n", yystate)); goto yybackup; /*-----------. | yybackup. | `-----------*/ yybackup: /* Do appropriate processing given the current state. Read a look-ahead token if we need one and don't already have one. */ /* First try to decide what to do without reference to look-ahead token. */ yyn = yypact[yystate]; if (yyn == YYPACT_NINF) goto yydefault; /* Not known => get a look-ahead token if don't already have one. */ /* YYCHAR is either YYEMPTY or YYEOF or a valid look-ahead symbol. */ if (yychar == YYEMPTY) { YYDPRINTF ((stderr, "Reading a token: ")); yychar = YYLEX; } if (yychar <= YYEOF) { yychar = yytoken = YYEOF; YYDPRINTF ((stderr, "Now at end of input.\n")); } else { yytoken = YYTRANSLATE (yychar); YY_SYMBOL_PRINT ("Next token is", yytoken, &yylval, &yylloc); } /* If the proper action on seeing token YYTOKEN is to reduce or to detect an error, take that action. */ yyn += yytoken; if (yyn < 0 || YYLAST < yyn || yycheck[yyn] != yytoken) goto yydefault; yyn = yytable[yyn]; if (yyn <= 0) { if (yyn == 0 || yyn == YYTABLE_NINF) goto yyerrlab; yyn = -yyn; goto yyreduce; } if (yyn == YYFINAL) YYACCEPT; /* Count tokens shifted since error; after three, turn off error status. */ if (yyerrstatus) yyerrstatus--; /* Shift the look-ahead token. */ YY_SYMBOL_PRINT ("Shifting", yytoken, &yylval, &yylloc); /* Discard the shifted token unless it is eof. */ if (yychar != YYEOF) yychar = YYEMPTY; yystate = yyn; *++yyvsp = yylval; goto yynewstate; /*-----------------------------------------------------------. | yydefault -- do the default action for the current state. | `-----------------------------------------------------------*/ yydefault: yyn = yydefact[yystate]; if (yyn == 0) goto yyerrlab; goto yyreduce; /*-----------------------------. | yyreduce -- Do a reduction. | `-----------------------------*/ yyreduce: /* yyn is the number of a rule to reduce with. */ yylen = yyr2[yyn]; /* If YYLEN is nonzero, implement the default value of the action: `$$ = $1'. Otherwise, the following line sets YYVAL to garbage. This behavior is undocumented and Bison users should not rely upon it. Assigning to YYVAL unconditionally makes the parser a bit smaller, and it avoids a GCC warning that YYVAL may be used uninitialized. */ yyval = yyvsp[1-yylen]; YY_REDUCE_PRINT (yyn); switch (yyn) { case 2: #line 85 "sel-gram.y" { _hx509_expr_input.expr = (yyvsp[(1) - (1)].expr); } break; case 3: #line 87 "sel-gram.y" { (yyval.expr) = _hx509_make_expr(op_TRUE, NULL, NULL); } break; case 4: #line 88 "sel-gram.y" { (yyval.expr) = _hx509_make_expr(op_FALSE, NULL, NULL); } break; case 5: #line 89 "sel-gram.y" { (yyval.expr) = _hx509_make_expr(op_NOT, (yyvsp[(2) - (2)].expr), NULL); } break; case 6: #line 90 "sel-gram.y" { (yyval.expr) = _hx509_make_expr(op_AND, (yyvsp[(1) - (3)].expr), (yyvsp[(3) - (3)].expr)); } break; case 7: #line 91 "sel-gram.y" { (yyval.expr) = _hx509_make_expr(op_OR, (yyvsp[(1) - (3)].expr), (yyvsp[(3) - (3)].expr)); } break; case 8: #line 92 "sel-gram.y" { (yyval.expr) = (yyvsp[(2) - (3)].expr); } break; case 9: #line 93 "sel-gram.y" { (yyval.expr) = _hx509_make_expr(op_COMP, (yyvsp[(1) - (1)].expr), NULL); } break; case 10: #line 96 "sel-gram.y" { (yyval.expr) = _hx509_make_expr(expr_WORDS, (yyvsp[(1) - (1)].expr), NULL); } break; case 11: #line 97 "sel-gram.y" { (yyval.expr) = _hx509_make_expr(expr_WORDS, (yyvsp[(1) - (3)].expr), (yyvsp[(3) - (3)].expr)); } break; case 12: #line 100 "sel-gram.y" { (yyval.expr) = _hx509_make_expr(comp_EQ, (yyvsp[(1) - (4)].expr), (yyvsp[(4) - (4)].expr)); } break; case 13: #line 101 "sel-gram.y" { (yyval.expr) = _hx509_make_expr(comp_NE, (yyvsp[(1) - (4)].expr), (yyvsp[(4) - (4)].expr)); } break; case 14: #line 102 "sel-gram.y" { (yyval.expr) = _hx509_make_expr(comp_TAILEQ, (yyvsp[(1) - (3)].expr), (yyvsp[(3) - (3)].expr)); } break; case 15: #line 103 "sel-gram.y" { (yyval.expr) = _hx509_make_expr(comp_IN, (yyvsp[(1) - (5)].expr), (yyvsp[(4) - (5)].expr)); } break; case 16: #line 104 "sel-gram.y" { (yyval.expr) = _hx509_make_expr(comp_IN, (yyvsp[(1) - (3)].expr), (yyvsp[(3) - (3)].expr)); } break; case 17: #line 107 "sel-gram.y" { (yyval.expr) = (yyvsp[(1) - (1)].expr); } break; case 18: #line 108 "sel-gram.y" { (yyval.expr) = (yyvsp[(1) - (1)].expr); } break; case 19: #line 109 "sel-gram.y" { (yyval.expr) = (yyvsp[(1) - (1)].expr); } break; case 20: #line 110 "sel-gram.y" { (yyval.expr) = (yyvsp[(1) - (1)].expr); } break; case 21: #line 113 "sel-gram.y" { (yyval.expr) = _hx509_make_expr(expr_NUMBER, (yyvsp[(1) - (1)].string), NULL); } break; case 22: #line 114 "sel-gram.y" { (yyval.expr) = _hx509_make_expr(expr_STRING, (yyvsp[(1) - (1)].string), NULL); } break; case 23: #line 116 "sel-gram.y" { (yyval.expr) = _hx509_make_expr(expr_FUNCTION, (yyvsp[(1) - (4)].string), (yyvsp[(3) - (4)].expr)); } break; case 24: #line 119 "sel-gram.y" { (yyval.expr) = (yyvsp[(3) - (4)].expr); } break; case 25: #line 122 "sel-gram.y" { (yyval.expr) = _hx509_make_expr(expr_VAR, (yyvsp[(1) - (3)].string), (yyvsp[(3) - (3)].expr)); } break; case 26: #line 124 "sel-gram.y" { (yyval.expr) = _hx509_make_expr(expr_VAR, (yyvsp[(1) - (1)].string), NULL); } break; /* Line 1267 of yacc.c. */ #line 1512 "sel-gram.c" default: break; } YY_SYMBOL_PRINT ("-> $$ =", yyr1[yyn], &yyval, &yyloc); YYPOPSTACK (yylen); yylen = 0; YY_STACK_PRINT (yyss, yyssp); *++yyvsp = yyval; /* Now `shift' the result of the reduction. Determine what state that goes to, based on the state we popped back to and the rule number reduced by. */ yyn = yyr1[yyn]; yystate = yypgoto[yyn - YYNTOKENS] + *yyssp; if (0 <= yystate && yystate <= YYLAST && yycheck[yystate] == *yyssp) yystate = yytable[yystate]; else yystate = yydefgoto[yyn - YYNTOKENS]; goto yynewstate; /*------------------------------------. | yyerrlab -- here on detecting error | `------------------------------------*/ yyerrlab: /* If not already recovering from an error, report this error. */ if (!yyerrstatus) { ++yynerrs; #if ! YYERROR_VERBOSE yyerror (YY_("syntax error")); #else { YYSIZE_T yysize = yysyntax_error (0, yystate, yychar); if (yymsg_alloc < yysize && yymsg_alloc < YYSTACK_ALLOC_MAXIMUM) { YYSIZE_T yyalloc = 2 * yysize; if (! (yysize <= yyalloc && yyalloc <= YYSTACK_ALLOC_MAXIMUM)) yyalloc = YYSTACK_ALLOC_MAXIMUM; if (yymsg != yymsgbuf) YYSTACK_FREE (yymsg); yymsg = (char *) YYSTACK_ALLOC (yyalloc); if (yymsg) yymsg_alloc = yyalloc; else { yymsg = yymsgbuf; yymsg_alloc = sizeof yymsgbuf; } } if (0 < yysize && yysize <= yymsg_alloc) { (void) yysyntax_error (yymsg, yystate, yychar); yyerror (yymsg); } else { yyerror (YY_("syntax error")); if (yysize != 0) goto yyexhaustedlab; } } #endif } if (yyerrstatus == 3) { /* If just tried and failed to reuse look-ahead token after an error, discard it. */ if (yychar <= YYEOF) { /* Return failure if at end of input. */ if (yychar == YYEOF) YYABORT; } else { yydestruct ("Error: discarding", yytoken, &yylval); yychar = YYEMPTY; } } /* Else will try to reuse look-ahead token after shifting the error token. */ goto yyerrlab1; /*---------------------------------------------------. | yyerrorlab -- error raised explicitly by YYERROR. | `---------------------------------------------------*/ yyerrorlab: /* Pacify compilers like GCC when the user code never invokes YYERROR and the label yyerrorlab therefore never appears in user code. */ if (/*CONSTCOND*/ 0) goto yyerrorlab; /* Do not reclaim the symbols of the rule which action triggered this YYERROR. */ YYPOPSTACK (yylen); yylen = 0; YY_STACK_PRINT (yyss, yyssp); yystate = *yyssp; goto yyerrlab1; /*-------------------------------------------------------------. | yyerrlab1 -- common code for both syntax error and YYERROR. | `-------------------------------------------------------------*/ yyerrlab1: yyerrstatus = 3; /* Each real token shifted decrements this. */ for (;;) { yyn = yypact[yystate]; if (yyn != YYPACT_NINF) { yyn += YYTERROR; if (0 <= yyn && yyn <= YYLAST && yycheck[yyn] == YYTERROR) { yyn = yytable[yyn]; if (0 < yyn) break; } } /* Pop the current state because it cannot handle the error token. */ if (yyssp == yyss) YYABORT; yydestruct ("Error: popping", yystos[yystate], yyvsp); YYPOPSTACK (1); yystate = *yyssp; YY_STACK_PRINT (yyss, yyssp); } if (yyn == YYFINAL) YYACCEPT; *++yyvsp = yylval; /* Shift the error token. */ YY_SYMBOL_PRINT ("Shifting", yystos[yyn], yyvsp, yylsp); yystate = yyn; goto yynewstate; /*-------------------------------------. | yyacceptlab -- YYACCEPT comes here. | `-------------------------------------*/ yyacceptlab: yyresult = 0; goto yyreturn; /*-----------------------------------. | yyabortlab -- YYABORT comes here. | `-----------------------------------*/ yyabortlab: yyresult = 1; goto yyreturn; #ifndef yyoverflow /*-------------------------------------------------. | yyexhaustedlab -- memory exhaustion comes here. | `-------------------------------------------------*/ yyexhaustedlab: yyerror (YY_("memory exhausted")); yyresult = 2; /* Fall through. */ #endif yyreturn: if (yychar != YYEOF && yychar != YYEMPTY) yydestruct ("Cleanup: discarding lookahead", yytoken, &yylval); /* Do not reclaim the symbols of the rule which action triggered this YYABORT or YYACCEPT. */ YYPOPSTACK (yylen); YY_STACK_PRINT (yyss, yyssp); while (yyssp != yyss) { yydestruct ("Cleanup: popping", yystos[*yyssp], yyvsp); YYPOPSTACK (1); } #ifndef yyoverflow if (yyss != yyssa) YYSTACK_FREE (yyss); #endif #if YYERROR_VERBOSE if (yymsg != yymsgbuf) YYSTACK_FREE (yymsg); #endif /* Make sure YYID is used. */ return YYID (yyresult); } heimdal-7.5.0/lib/hx509/test_name.c0000644000175000017500000004342513026237312015027 0ustar niknik/* * Copyright (c) 2006 - 2007 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "hx_locl.h" static int test_name(hx509_context context, const char *name) { hx509_name n; char *s; int ret; ret = hx509_parse_name(context, name, &n); if (ret) return 1; ret = hx509_name_to_string(n, &s); if (ret) return 1; if (strcmp(s, name) != 0) return 1; hx509_name_free(&n); free(s); return 0; } static int test_name_fail(hx509_context context, const char *name) { hx509_name n; if (hx509_parse_name(context, name, &n) == HX509_NAME_MALFORMED) return 0; hx509_name_free(&n); return 1; } static int test_expand(hx509_context context, const char *name, const char *expected) { hx509_env env = NULL; hx509_name n; char *s; int ret; hx509_env_add(context, &env, "uid", "lha"); ret = hx509_parse_name(context, name, &n); if (ret) return 1; ret = hx509_name_expand(context, n, env); hx509_env_free(&env); if (ret) return 1; ret = hx509_name_to_string(n, &s); hx509_name_free(&n); if (ret) return 1; ret = strcmp(s, expected) != 0; free(s); if (ret) return 1; return 0; } char certdata1[] = "\x30\x82\x04\x1d\x30\x82\x03\x05\xa0\x03\x02\x01\x02\x02\x10\x4e" "\x81\x2d\x8a\x82\x65\xe0\x0b\x02\xee\x3e\x35\x02\x46\xe5\x3d\x30" "\x0d\x06\x09\x2a\x86\x48\x86\xf7\x0d\x01\x01\x05\x05\x00\x30\x81" "\x81\x31\x0b\x30\x09\x06\x03\x55\x04\x06\x13\x02\x47\x42\x31\x1b" "\x30\x19\x06\x03\x55\x04\x08\x13\x12\x47\x72\x65\x61\x74\x65\x72" "\x20\x4d\x61\x6e\x63\x68\x65\x73\x74\x65\x72\x31\x10\x30\x0e\x06" "\x03\x55\x04\x07\x13\x07\x53\x61\x6c\x66\x6f\x72\x64\x31\x1a\x30" "\x18\x06\x03\x55\x04\x0a\x13\x11\x43\x4f\x4d\x4f\x44\x4f\x20\x43" "\x41\x20\x4c\x69\x6d\x69\x74\x65\x64\x31\x27\x30\x25\x06\x03\x55" "\x04\x03\x13\x1e\x43\x4f\x4d\x4f\x44\x4f\x20\x43\x65\x72\x74\x69" "\x66\x69\x63\x61\x74\x69\x6f\x6e\x20\x41\x75\x74\x68\x6f\x72\x69" "\x74\x79\x30\x1e\x17\x0d\x30\x36\x31\x32\x30\x31\x30\x30\x30\x30" "\x30\x30\x5a\x17\x0d\x32\x39\x31\x32\x33\x31\x32\x33\x35\x39\x35" "\x39\x5a\x30\x81\x81\x31\x0b\x30\x09\x06\x03\x55\x04\x06\x13\x02" "\x47\x42\x31\x1b\x30\x19\x06\x03\x55\x04\x08\x13\x12\x47\x72\x65" "\x61\x74\x65\x72\x20\x4d\x61\x6e\x63\x68\x65\x73\x74\x65\x72\x31" "\x10\x30\x0e\x06\x03\x55\x04\x07\x13\x07\x53\x61\x6c\x66\x6f\x72" "\x64\x31\x1a\x30\x18\x06\x03\x55\x04\x0a\x13\x11\x43\x4f\x4d\x4f" "\x44\x4f\x20\x43\x41\x20\x4c\x69\x6d\x69\x74\x65\x64\x31\x27\x30" "\x25\x06\x03\x55\x04\x03\x13\x1e\x43\x4f\x4d\x4f\x44\x4f\x20\x43" "\x65\x72\x74\x69\x66\x69\x63\x61\x74\x69\x6f\x6e\x20\x41\x75\x74" "\x68\x6f\x72\x69\x74\x79\x30\x82\x01\x22\x30\x0d\x06\x09\x2a\x86" "\x48\x86\xf7\x0d\x01\x01\x01\x05\x00\x03\x82\x01\x0f\x00\x30\x82" "\x01\x0a\x02\x82\x01\x01\x00\xd0\x40\x8b\x8b\x72\xe3\x91\x1b\xf7" "\x51\xc1\x1b\x54\x04\x98\xd3\xa9\xbf\xc1\xe6\x8a\x5d\x3b\x87\xfb" "\xbb\x88\xce\x0d\xe3\x2f\x3f\x06\x96\xf0\xa2\x29\x50\x99\xae\xdb" "\x3b\xa1\x57\xb0\x74\x51\x71\xcd\xed\x42\x91\x4d\x41\xfe\xa9\xc8" "\xd8\x6a\x86\x77\x44\xbb\x59\x66\x97\x50\x5e\xb4\xd4\x2c\x70\x44" "\xcf\xda\x37\x95\x42\x69\x3c\x30\xc4\x71\xb3\x52\xf0\x21\x4d\xa1" "\xd8\xba\x39\x7c\x1c\x9e\xa3\x24\x9d\xf2\x83\x16\x98\xaa\x16\x7c" "\x43\x9b\x15\x5b\xb7\xae\x34\x91\xfe\xd4\x62\x26\x18\x46\x9a\x3f" "\xeb\xc1\xf9\xf1\x90\x57\xeb\xac\x7a\x0d\x8b\xdb\x72\x30\x6a\x66" "\xd5\xe0\x46\xa3\x70\xdc\x68\xd9\xff\x04\x48\x89\x77\xde\xb5\xe9" "\xfb\x67\x6d\x41\xe9\xbc\x39\xbd\x32\xd9\x62\x02\xf1\xb1\xa8\x3d" "\x6e\x37\x9c\xe2\x2f\xe2\xd3\xa2\x26\x8b\xc6\xb8\x55\x43\x88\xe1" "\x23\x3e\xa5\xd2\x24\x39\x6a\x47\xab\x00\xd4\xa1\xb3\xa9\x25\xfe" "\x0d\x3f\xa7\x1d\xba\xd3\x51\xc1\x0b\xa4\xda\xac\x38\xef\x55\x50" "\x24\x05\x65\x46\x93\x34\x4f\x2d\x8d\xad\xc6\xd4\x21\x19\xd2\x8e" "\xca\x05\x61\x71\x07\x73\x47\xe5\x8a\x19\x12\xbd\x04\x4d\xce\x4e" "\x9c\xa5\x48\xac\xbb\x26\xf7\x02\x03\x01\x00\x01\xa3\x81\x8e\x30" "\x81\x8b\x30\x1d\x06\x03\x55\x1d\x0e\x04\x16\x04\x14\x0b\x58\xe5" "\x8b\xc6\x4c\x15\x37\xa4\x40\xa9\x30\xa9\x21\xbe\x47\x36\x5a\x56" "\xff\x30\x0e\x06\x03\x55\x1d\x0f\x01\x01\xff\x04\x04\x03\x02\x01" "\x06\x30\x0f\x06\x03\x55\x1d\x13\x01\x01\xff\x04\x05\x30\x03\x01" "\x01\xff\x30\x49\x06\x03\x55\x1d\x1f\x04\x42\x30\x40\x30\x3e\xa0" "\x3c\xa0\x3a\x86\x38\x68\x74\x74\x70\x3a\x2f\x2f\x63\x72\x6c\x2e" "\x63\x6f\x6d\x6f\x64\x6f\x63\x61\x2e\x63\x6f\x6d\x2f\x43\x4f\x4d" "\x4f\x44\x4f\x43\x65\x72\x74\x69\x66\x69\x63\x61\x74\x69\x6f\x6e" "\x41\x75\x74\x68\x6f\x72\x69\x74\x79\x2e\x63\x72\x6c\x30\x0d\x06" "\x09\x2a\x86\x48\x86\xf7\x0d\x01\x01\x05\x05\x00\x03\x82\x01\x01" "\x00\x3e\x98\x9e\x9b\xf6\x1b\xe9\xd7\x39\xb7\x78\xae\x1d\x72\x18" "\x49\xd3\x87\xe4\x43\x82\xeb\x3f\xc9\xaa\xf5\xa8\xb5\xef\x55\x7c" "\x21\x52\x65\xf9\xd5\x0d\xe1\x6c\xf4\x3e\x8c\x93\x73\x91\x2e\x02" "\xc4\x4e\x07\x71\x6f\xc0\x8f\x38\x61\x08\xa8\x1e\x81\x0a\xc0\x2f" "\x20\x2f\x41\x8b\x91\xdc\x48\x45\xbc\xf1\xc6\xde\xba\x76\x6b\x33" "\xc8\x00\x2d\x31\x46\x4c\xed\xe7\x9d\xcf\x88\x94\xff\x33\xc0\x56" "\xe8\x24\x86\x26\xb8\xd8\x38\x38\xdf\x2a\x6b\xdd\x12\xcc\xc7\x3f" "\x47\x17\x4c\xa2\xc2\x06\x96\x09\xd6\xdb\xfe\x3f\x3c\x46\x41\xdf" "\x58\xe2\x56\x0f\x3c\x3b\xc1\x1c\x93\x35\xd9\x38\x52\xac\xee\xc8" "\xec\x2e\x30\x4e\x94\x35\xb4\x24\x1f\x4b\x78\x69\xda\xf2\x02\x38" "\xcc\x95\x52\x93\xf0\x70\x25\x59\x9c\x20\x67\xc4\xee\xf9\x8b\x57" "\x61\xf4\x92\x76\x7d\x3f\x84\x8d\x55\xb7\xe8\xe5\xac\xd5\xf1\xf5" "\x19\x56\xa6\x5a\xfb\x90\x1c\xaf\x93\xeb\xe5\x1c\xd4\x67\x97\x5d" "\x04\x0e\xbe\x0b\x83\xa6\x17\x83\xb9\x30\x12\xa0\xc5\x33\x15\x05" "\xb9\x0d\xfb\xc7\x05\x76\xe3\xd8\x4a\x8d\xfc\x34\x17\xa3\xc6\x21" "\x28\xbe\x30\x45\x31\x1e\xc7\x78\xbe\x58\x61\x38\xac\x3b\xe2\x01" "\x65"; char certdata2[] = "\x30\x82\x03\x02\x30\x82\x02\x6b\x02\x10\x39\xca\x54\x89\xfe\x50" "\x22\x32\xfe\x32\xd9\xdb\xfb\x1b\x84\x19\x30\x0d\x06\x09\x2a\x86" "\x48\x86\xf7\x0d\x01\x01\x05\x05\x00\x30\x81\xc1\x31\x0b\x30\x09" "\x06\x03\x55\x04\x06\x13\x02\x55\x53\x31\x17\x30\x15\x06\x03\x55" "\x04\x0a\x13\x0e\x56\x65\x72\x69\x53\x69\x67\x6e\x2c\x20\x49\x6e" "\x63\x2e\x31\x3c\x30\x3a\x06\x03\x55\x04\x0b\x13\x33\x43\x6c\x61" "\x73\x73\x20\x31\x20\x50\x75\x62\x6c\x69\x63\x20\x50\x72\x69\x6d" "\x61\x72\x79\x20\x43\x65\x72\x74\x69\x66\x69\x63\x61\x74\x69\x6f" "\x6e\x20\x41\x75\x74\x68\x6f\x72\x69\x74\x79\x20\x2d\x20\x47\x32" "\x31\x3a\x30\x38\x06\x03\x55\x04\x0b\x13\x31\x28\x63\x29\x20\x31" "\x39\x39\x38\x20\x56\x65\x72\x69\x53\x69\x67\x6e\x2c\x20\x49\x6e" "\x63\x2e\x20\x2d\x20\x46\x6f\x72\x20\x61\x75\x74\x68\x6f\x72\x69" "\x7a\x65\x64\x20\x75\x73\x65\x20\x6f\x6e\x6c\x79\x31\x1f\x30\x1d" "\x06\x03\x55\x04\x0b\x13\x16\x56\x65\x72\x69\x53\x69\x67\x6e\x20" "\x54\x72\x75\x73\x74\x20\x4e\x65\x74\x77\x6f\x72\x6b\x30\x1e\x17" "\x0d\x39\x38\x30\x35\x31\x38\x30\x30\x30\x30\x30\x30\x5a\x17\x0d" "\x31\x38\x30\x35\x31\x38\x32\x33\x35\x39\x35\x39\x5a\x30\x81\xc1" "\x31\x0b\x30\x09\x06\x03\x55\x04\x06\x13\x02\x55\x53\x31\x17\x30" "\x15\x06\x03\x55\x04\x0a\x13\x0e\x56\x65\x72\x69\x53\x69\x67\x6e" "\x2c\x20\x49\x6e\x63\x2e\x31\x3c\x30\x3a\x06\x03\x55\x04\x0b\x13" "\x33\x43\x6c\x61\x73\x73\x20\x31\x20\x50\x75\x62\x6c\x69\x63\x20" "\x50\x72\x69\x6d\x61\x72\x79\x20\x43\x65\x72\x74\x69\x66\x69\x63" "\x61\x74\x69\x6f\x6e\x20\x41\x75\x74\x68\x6f\x72\x69\x74\x79\x20" "\x2d\x20\x47\x32\x31\x3a\x30\x38\x06\x03\x55\x04\x0b\x13\x31\x28" "\x63\x29\x20\x31\x39\x39\x38\x20\x56\x65\x72\x69\x53\x69\x67\x6e" "\x2c\x20\x49\x6e\x63\x2e\x20\x2d\x20\x46\x6f\x72\x20\x61\x75\x74" "\x68\x6f\x72\x69\x7a\x65\x64\x20\x75\x73\x65\x20\x6f\x6e\x6c\x79" "\x31\x1f\x30\x1d\x06\x03\x55\x04\x0b\x13\x16\x56\x65\x72\x69\x53" "\x69\x67\x6e\x20\x54\x72\x75\x73\x74\x20\x4e\x65\x74\x77\x6f\x72" "\x6b\x30\x81\x9f\x30\x0d\x06\x09\x2a\x86\x48\x86\xf7\x0d\x01\x01" "\x01\x05\x00\x03\x81\x8d\x00\x30\x81\x89\x02\x81\x81\x00\xaa\xd0" "\xba\xbe\x16\x2d\xb8\x83\xd4\xca\xd2\x0f\xbc\x76\x31\xca\x94\xd8" "\x1d\x93\x8c\x56\x02\xbc\xd9\x6f\x1a\x6f\x52\x36\x6e\x75\x56\x0a" "\x55\xd3\xdf\x43\x87\x21\x11\x65\x8a\x7e\x8f\xbd\x21\xde\x6b\x32" "\x3f\x1b\x84\x34\x95\x05\x9d\x41\x35\xeb\x92\xeb\x96\xdd\xaa\x59" "\x3f\x01\x53\x6d\x99\x4f\xed\xe5\xe2\x2a\x5a\x90\xc1\xb9\xc4\xa6" "\x15\xcf\xc8\x45\xeb\xa6\x5d\x8e\x9c\x3e\xf0\x64\x24\x76\xa5\xcd" "\xab\x1a\x6f\xb6\xd8\x7b\x51\x61\x6e\xa6\x7f\x87\xc8\xe2\xb7\xe5" "\x34\xdc\x41\x88\xea\x09\x40\xbe\x73\x92\x3d\x6b\xe7\x75\x02\x03" "\x01\x00\x01\x30\x0d\x06\x09\x2a\x86\x48\x86\xf7\x0d\x01\x01\x05" "\x05\x00\x03\x81\x81\x00\x8b\xf7\x1a\x10\xce\x76\x5c\x07\xab\x83" "\x99\xdc\x17\x80\x6f\x34\x39\x5d\x98\x3e\x6b\x72\x2c\xe1\xc7\xa2" "\x7b\x40\x29\xb9\x78\x88\xba\x4c\xc5\xa3\x6a\x5e\x9e\x6e\x7b\xe3" "\xf2\x02\x41\x0c\x66\xbe\xad\xfb\xae\xa2\x14\xce\x92\xf3\xa2\x34" "\x8b\xb4\xb2\xb6\x24\xf2\xe5\xd5\xe0\xc8\xe5\x62\x6d\x84\x7b\xcb" "\xbe\xbb\x03\x8b\x7c\x57\xca\xf0\x37\xa9\x90\xaf\x8a\xee\x03\xbe" "\x1d\x28\x9c\xd9\x26\x76\xa0\xcd\xc4\x9d\x4e\xf0\xae\x07\x16\xd5" "\xbe\xaf\x57\x08\x6a\xd0\xa0\x42\x42\x42\x1e\xf4\x20\xcc\xa5\x78" "\x82\x95\x26\x38\x8a\x47"; char certdata3[] = "\x30\x82\x04\x43\x30\x82\x03\x2b\xa0\x03\x02\x01\x02\x02\x01\x01" "\x30\x0d\x06\x09\x2a\x86\x48\x86\xf7\x0d\x01\x01\x05\x05\x00\x30" "\x7f\x31\x0b\x30\x09\x06\x03\x55\x04\x06\x13\x02\x47\x42\x31\x1b" "\x30\x19\x06\x03\x55\x04\x08\x0c\x12\x47\x72\x65\x61\x74\x65\x72" "\x20\x4d\x61\x6e\x63\x68\x65\x73\x74\x65\x72\x31\x10\x30\x0e\x06" "\x03\x55\x04\x07\x0c\x07\x53\x61\x6c\x66\x6f\x72\x64\x31\x1a\x30" "\x18\x06\x03\x55\x04\x0a\x0c\x11\x43\x6f\x6d\x6f\x64\x6f\x20\x43" "\x41\x20\x4c\x69\x6d\x69\x74\x65\x64\x31\x25\x30\x23\x06\x03\x55" "\x04\x03\x0c\x1c\x54\x72\x75\x73\x74\x65\x64\x20\x43\x65\x72\x74" "\x69\x66\x69\x63\x61\x74\x65\x20\x53\x65\x72\x76\x69\x63\x65\x73" "\x30\x1e\x17\x0d\x30\x34\x30\x31\x30\x31\x30\x30\x30\x30\x30\x30" "\x5a\x17\x0d\x32\x38\x31\x32\x33\x31\x32\x33\x35\x39\x35\x39\x5a" "\x30\x7f\x31\x0b\x30\x09\x06\x03\x55\x04\x06\x13\x02\x47\x42\x31" "\x1b\x30\x19\x06\x03\x55\x04\x08\x0c\x12\x47\x72\x65\x61\x74\x65" "\x72\x20\x4d\x61\x6e\x63\x68\x65\x73\x74\x65\x72\x31\x10\x30\x0e" "\x06\x03\x55\x04\x07\x0c\x07\x53\x61\x6c\x66\x6f\x72\x64\x31\x1a" "\x30\x18\x06\x03\x55\x04\x0a\x0c\x11\x43\x6f\x6d\x6f\x64\x6f\x20" "\x43\x41\x20\x4c\x69\x6d\x69\x74\x65\x64\x31\x25\x30\x23\x06\x03" "\x55\x04\x03\x0c\x1c\x54\x72\x75\x73\x74\x65\x64\x20\x43\x65\x72" "\x74\x69\x66\x69\x63\x61\x74\x65\x20\x53\x65\x72\x76\x69\x63\x65" "\x73\x30\x82\x01\x22\x30\x0d\x06\x09\x2a\x86\x48\x86\xf7\x0d\x01" "\x01\x01\x05\x00\x03\x82\x01\x0f\x00\x30\x82\x01\x0a\x02\x82\x01" "\x01\x00\xdf\x71\x6f\x36\x58\x53\x5a\xf2\x36\x54\x57\x80\xc4\x74" "\x08\x20\xed\x18\x7f\x2a\x1d\xe6\x35\x9a\x1e\x25\xac\x9c\xe5\x96" "\x7e\x72\x52\xa0\x15\x42\xdb\x59\xdd\x64\x7a\x1a\xd0\xb8\x7b\xdd" "\x39\x15\xbc\x55\x48\xc4\xed\x3a\x00\xea\x31\x11\xba\xf2\x71\x74" "\x1a\x67\xb8\xcf\x33\xcc\xa8\x31\xaf\xa3\xe3\xd7\x7f\xbf\x33\x2d" "\x4c\x6a\x3c\xec\x8b\xc3\x92\xd2\x53\x77\x24\x74\x9c\x07\x6e\x70" "\xfc\xbd\x0b\x5b\x76\xba\x5f\xf2\xff\xd7\x37\x4b\x4a\x60\x78\xf7" "\xf0\xfa\xca\x70\xb4\xea\x59\xaa\xa3\xce\x48\x2f\xa9\xc3\xb2\x0b" "\x7e\x17\x72\x16\x0c\xa6\x07\x0c\x1b\x38\xcf\xc9\x62\xb7\x3f\xa0" "\x93\xa5\x87\x41\xf2\xb7\x70\x40\x77\xd8\xbe\x14\x7c\xe3\xa8\xc0" "\x7a\x8e\xe9\x63\x6a\xd1\x0f\x9a\xc6\xd2\xf4\x8b\x3a\x14\x04\x56" "\xd4\xed\xb8\xcc\x6e\xf5\xfb\xe2\x2c\x58\xbd\x7f\x4f\x6b\x2b\xf7" "\x60\x24\x58\x24\xce\x26\xef\x34\x91\x3a\xd5\xe3\x81\xd0\xb2\xf0" "\x04\x02\xd7\x5b\xb7\x3e\x92\xac\x6b\x12\x8a\xf9\xe4\x05\xb0\x3b" "\x91\x49\x5c\xb2\xeb\x53\xea\xf8\x9f\x47\x86\xee\xbf\x95\xc0\xc0" "\x06\x9f\xd2\x5b\x5e\x11\x1b\xf4\xc7\x04\x35\x29\xd2\x55\x5c\xe4" "\xed\xeb\x02\x03\x01\x00\x01\xa3\x81\xc9\x30\x81\xc6\x30\x1d\x06" "\x03\x55\x1d\x0e\x04\x16\x04\x14\xc5\x7b\x58\xbd\xed\xda\x25\x69" "\xd2\xf7\x59\x16\xa8\xb3\x32\xc0\x7b\x27\x5b\xf4\x30\x0e\x06\x03" "\x55\x1d\x0f\x01\x01\xff\x04\x04\x03\x02\x01\x06\x30\x0f\x06\x03" "\x55\x1d\x13\x01\x01\xff\x04\x05\x30\x03\x01\x01\xff\x30\x81\x83" "\x06\x03\x55\x1d\x1f\x04\x7c\x30\x7a\x30\x3c\xa0\x3a\xa0\x38\x86" "\x36\x68\x74\x74\x70\x3a\x2f\x2f\x63\x72\x6c\x2e\x63\x6f\x6d\x6f" "\x64\x6f\x63\x61\x2e\x63\x6f\x6d\x2f\x54\x72\x75\x73\x74\x65\x64" "\x43\x65\x72\x74\x69\x66\x69\x63\x61\x74\x65\x53\x65\x72\x76\x69" "\x63\x65\x73\x2e\x63\x72\x6c\x30\x3a\xa0\x38\xa0\x36\x86\x34\x68" "\x74\x74\x70\x3a\x2f\x2f\x63\x72\x6c\x2e\x63\x6f\x6d\x6f\x64\x6f" "\x2e\x6e\x65\x74\x2f\x54\x72\x75\x73\x74\x65\x64\x43\x65\x72\x74" "\x69\x66\x69\x63\x61\x74\x65\x53\x65\x72\x76\x69\x63\x65\x73\x2e" "\x63\x72\x6c\x30\x0d\x06\x09\x2a\x86\x48\x86\xf7\x0d\x01\x01\x05" "\x05\x00\x03\x82\x01\x01\x00\xc8\x93\x81\x3b\x89\xb4\xaf\xb8\x84" "\x12\x4c\x8d\xd2\xf0\xdb\x70\xba\x57\x86\x15\x34\x10\xb9\x2f\x7f" "\x1e\xb0\xa8\x89\x60\xa1\x8a\xc2\x77\x0c\x50\x4a\x9b\x00\x8b\xd8" "\x8b\xf4\x41\xe2\xd0\x83\x8a\x4a\x1c\x14\x06\xb0\xa3\x68\x05\x70" "\x31\x30\xa7\x53\x9b\x0e\xe9\x4a\xa0\x58\x69\x67\x0e\xae\x9d\xf6" "\xa5\x2c\x41\xbf\x3c\x06\x6b\xe4\x59\xcc\x6d\x10\xf1\x96\x6f\x1f" "\xdf\xf4\x04\x02\xa4\x9f\x45\x3e\xc8\xd8\xfa\x36\x46\x44\x50\x3f" "\x82\x97\x91\x1f\x28\xdb\x18\x11\x8c\x2a\xe4\x65\x83\x57\x12\x12" "\x8c\x17\x3f\x94\x36\xfe\x5d\xb0\xc0\x04\x77\x13\xb8\xf4\x15\xd5" "\x3f\x38\xcc\x94\x3a\x55\xd0\xac\x98\xf5\xba\x00\x5f\xe0\x86\x19" "\x81\x78\x2f\x28\xc0\x7e\xd3\xcc\x42\x0a\xf5\xae\x50\xa0\xd1\x3e" "\xc6\xa1\x71\xec\x3f\xa0\x20\x8c\x66\x3a\x89\xb4\x8e\xd4\xd8\xb1" "\x4d\x25\x47\xee\x2f\x88\xc8\xb5\xe1\x05\x45\xc0\xbe\x14\x71\xde" "\x7a\xfd\x8e\x7b\x7d\x4d\x08\x96\xa5\x12\x73\xf0\x2d\xca\x37\x27" "\x74\x12\x27\x4c\xcb\xb6\x97\xe9\xd9\xae\x08\x6d\x5a\x39\x40\xdd" "\x05\x47\x75\x6a\x5a\x21\xb3\xa3\x18\xcf\x4e\xf7\x2e\x57\xb7\x98" "\x70\x5e\xc8\xc4\x78\xb0\x62"; static int compare_subject(hx509_cert c1, hx509_cert c2, int *l) { hx509_name n1, n2; int ret; ret = hx509_cert_get_subject(c1, &n1); if (ret) return 1; ret = hx509_cert_get_subject(c2, &n2); if (ret) return 1; *l = hx509_name_cmp(n1, n2); hx509_name_free(&n1); hx509_name_free(&n2); return 0; } static int test_compare(hx509_context context) { int ret; hx509_cert c1, c2, c3; int l0, l1, l2, l3; /* check transative properties of name compare function */ c1 = hx509_cert_init_data(context, certdata1, sizeof(certdata1) - 1, NULL); if (c1 == NULL) return 1; c2 = hx509_cert_init_data(context, certdata2, sizeof(certdata2) - 1, NULL); if (c2 == NULL) return 1; c3 = hx509_cert_init_data(context, certdata3, sizeof(certdata3) - 1, NULL); if (c3 == NULL) return 1; ret = compare_subject(c1, c1, &l0); if (ret) return 1; ret = compare_subject(c1, c2, &l1); if (ret) return 1; ret = compare_subject(c1, c3, &l2); if (ret) return 1; ret = compare_subject(c2, c3, &l3); if (ret) return 1; if (l0 != 0) return 1; if (l2 < l1) return 1; if (l3 < l2) return 1; if (l3 < l1) return 1; hx509_cert_free(c1); hx509_cert_free(c2); hx509_cert_free(c3); return 0; } int main(int argc, char **argv) { hx509_context context; int ret = 0; ret = hx509_context_init(&context); if (ret) errx(1, "hx509_context_init failed with %d", ret); ret += test_name(context, "CN=foo,C=SE"); ret += test_name(context, "CN=foo,CN=kaka,CN=FOO,DC=ad1,C=SE"); ret += test_name(context, "1.2.3.4=foo,C=SE"); ret += test_name_fail(context, "="); ret += test_name_fail(context, "CN=foo,=foo"); ret += test_name_fail(context, "CN=foo,really-unknown-type=foo"); ret += test_expand(context, "UID=${uid},C=SE", "UID=lha,C=SE"); ret += test_expand(context, "UID=foo${uid},C=SE", "UID=foolha,C=SE"); ret += test_expand(context, "UID=${uid}bar,C=SE", "UID=lhabar,C=SE"); ret += test_expand(context, "UID=f${uid}b,C=SE", "UID=flhab,C=SE"); ret += test_expand(context, "UID=${uid}${uid},C=SE", "UID=lhalha,C=SE"); ret += test_expand(context, "UID=${uid}{uid},C=SE", "UID=lha{uid},C=SE"); ret += test_compare(context); hx509_context_free(&context); return ret; } heimdal-7.5.0/lib/hx509/tst-crypto-available30000644000175000017500000000017212136107750016753 0ustar niknik1.2.840.113549.1.1.11 1.2.840.113549.1.1.5 1.2.840.113549.1.1.5 1.2.840.113549.1.1.4 1.2.840.113549.1.1.2 1.2.752.43.16.1 heimdal-7.5.0/lib/hx509/tst-crypto-select20000644000175000017500000000002612136107750016307 0ustar niknik1.2.840.113549.1.1.11 heimdal-7.5.0/lib/hx509/ocsp.opt0000644000175000017500000000010412136107750014362 0ustar niknik--preserve-binary=OCSPTBSRequest --preserve-binary=OCSPResponseData heimdal-7.5.0/lib/hx509/tst-crypto-select50000644000175000017500000000002612136107750016312 0ustar niknik1.2.840.113549.1.1.11 heimdal-7.5.0/lib/hx509/test_query.in0000644000175000017500000001530112136107750015433 0ustar niknik#!/bin/sh # # Copyright (c) 2005 - 2008 Kungliga Tekniska Högskolan # (Royal Institute of Technology, Stockholm, Sweden). # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # 1. Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # # 3. Neither the name of the Institute nor the names of its contributors # may be used to endorse or promote products derived from this software # without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE # ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS # OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) # HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY # OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF # SUCH DAMAGE. # # $Id$ # srcdir="@srcdir@" objdir="@objdir@" stat="--statistic-file=${objdir}/statfile" hxtool="${TESTS_ENVIRONMENT} ./hxtool ${stat}" echo "try printing" ${hxtool} print \ --pass=PASS:foobar \ --info --content \ PKCS12:$srcdir/data/test.p12 >/dev/null 2>/dev/null || exit 1 echo "try printing" ${hxtool} print \ --pass=PASS:foobar \ --info --content \ FILE:$srcdir/data/kdc.crt >/dev/null 2>/dev/null || exit 1 ${hxtool} print \ --pass=PASS:foobar \ --info \ PKCS12:$srcdir/data/test.p12 >/dev/null 2>/dev/null || exit 1 echo "make sure entry is found (friendlyname)" ${hxtool} query \ --pass=PASS:foobar \ --friendlyname=friendlyname-test \ PKCS12:$srcdir/data/test.p12 >/dev/null 2>/dev/null || exit 1 echo "make sure entry is not found (friendlyname)" ${hxtool} query \ --pass=PASS:foobar \ --friendlyname=friendlyname-test-not \ PKCS12:$srcdir/data/test.p12 >/dev/null 2>/dev/null && exit 1 echo "make sure entry is found (eku)" ${hxtool} query \ --eku=1.3.6.1.5.2.3.5 \ FILE:$srcdir/data/kdc.crt >/dev/null 2>/dev/null || exit 1 echo "make sure entry is not found (eku)" ${hxtool} query \ --eku=1.3.6.1.5.2.3.6 \ FILE:$srcdir/data/kdc.crt >/dev/null 2>/dev/null && exit 1 echo "make sure entry is found (friendlyname, no-pw)" ${hxtool} query \ --friendlyname=friendlyname-cert \ PKCS12:$srcdir/data/test-nopw.p12 >/dev/null 2>/dev/null || exit 1 echo "check for ca cert (friendlyname)" ${hxtool} query \ --pass=PASS:foobar \ --friendlyname=ca \ PKCS12:$srcdir/data/test.p12 >/dev/null 2>/dev/null || exit 1 echo "make sure entry is not found (friendlyname)" ${hxtool} query \ --pass=PASS:foobar \ --friendlyname=friendlyname-test \ PKCS12:$srcdir/data/sub-cert.p12 >/dev/null 2>/dev/null && exit 1 echo "make sure entry is found (friendlyname|private key)" ${hxtool} query \ --pass=PASS:foobar \ --friendlyname=friendlyname-test \ --private-key \ PKCS12:$srcdir/data/test.p12 > /dev/null || exit 1 echo "make sure entry is not found (friendlyname|private key)" ${hxtool} query \ --pass=PASS:foobar \ --friendlyname=ca \ --private-key \ PKCS12:$srcdir/data/test.p12 >/dev/null 2>/dev/null && exit 1 echo "make sure entry is found (cert ds)" ${hxtool} query \ --digitalSignature \ FILE:$srcdir/data/test.crt >/dev/null 2>/dev/null || exit 1 echo "make sure entry is found (cert ke)" ${hxtool} query \ --keyEncipherment \ FILE:$srcdir/data/test.crt >/dev/null 2>/dev/null || exit 1 echo "make sure entry is found (cert ke + ds)" ${hxtool} query \ --digitalSignature \ --keyEncipherment \ FILE:$srcdir/data/test.crt >/dev/null 2>/dev/null || exit 1 echo "make sure entry is found (cert-ds ds)" ${hxtool} query \ --digitalSignature \ FILE:$srcdir/data/test-ds-only.crt >/dev/null 2>/dev/null || exit 1 echo "make sure entry is not found (cert-ds ke)" ${hxtool} query \ --keyEncipherment \ FILE:$srcdir/data/test-ds-only.crt >/dev/null 2>/dev/null && exit 1 echo "make sure entry is not found (cert-ds ke + ds)" ${hxtool} query \ --digitalSignature \ --keyEncipherment \ FILE:$srcdir/data/test-ds-only.crt >/dev/null 2>/dev/null && exit 1 echo "make sure entry is not found (cert-ke ds)" ${hxtool} query \ --digitalSignature \ FILE:$srcdir/data/test-ke-only.crt >/dev/null 2>/dev/null && exit 1 echo "make sure entry is found (cert-ke ke)" ${hxtool} query \ --keyEncipherment \ FILE:$srcdir/data/test-ke-only.crt >/dev/null 2>/dev/null || exit 1 echo "make sure entry is not found (cert-ke ke + ds)" ${hxtool} query \ --digitalSignature \ --keyEncipherment \ FILE:$srcdir/data/test-ke-only.crt >/dev/null 2>/dev/null && exit 1 echo "make sure entry is found (eku) in query language" ${hxtool} query \ --expr='"1.3.6.1.5.2.3.5" IN %{certificate.eku}' \ FILE:$srcdir/data/kdc.crt > /dev/null || exit 1 echo "make sure entry is not found (eku) in query language" ${hxtool} query \ --expr='"1.3.6.1.5.2.3.6" IN %{certificate.eku}' \ FILE:$srcdir/data/kdc.crt > /dev/null && exit 1 echo "make sure entry is found (subject) in query language" ${hxtool} query \ --expr='%{certificate.subject} == "CN=kdc,C=SE"' \ FILE:$srcdir/data/kdc.crt > /dev/null || exit 1 echo "make sure entry is found using TAILMATCH (subject) in query language" ${hxtool} query \ --expr='%{certificate.subject} TAILMATCH "C=SE"' \ FILE:$srcdir/data/kdc.crt > /dev/null || exit 1 echo "make sure entry is not found using TAILMATCH (subject) in query language" ${hxtool} query \ --expr='%{certificate.subject} TAILMATCH "C=FI"' \ FILE:$srcdir/data/kdc.crt > /dev/null && exit 1 echo "make sure entry is found (issuer) in query language" ${hxtool} query \ --expr='%{certificate.issuer} == "C=SE,CN=hx509 Test Root CA"' \ FILE:$srcdir/data/kdc.crt > /dev/null || exit 1 echo "make sure entry match with EKU and TAILMATCH in query language" ${hxtool} query \ --expr='"1.3.6.1.5.2.3.5" IN %{certificate.eku} AND %{certificate.subject} TAILMATCH "C=SE"' \ FILE:$srcdir/data/kdc.crt > /dev/null || exit 1 echo "make sure entry match with hash.sha1" ${hxtool} query \ --expr='"%{certificate.hash.sha1}EQ "412120212A2CBFD777DE5499ECB4724345F33F16"' \ FILE:$srcdir/data/kdc.crt > /dev/null || exit 1 exit 0 heimdal-7.5.0/lib/hx509/tst-crypto-select40000644000175000017500000000002512136107750016310 0ustar niknik1.2.840.113549.1.1.5 heimdal-7.5.0/lib/hx509/test_cert.in0000644000175000017500000000604313026237312015223 0ustar niknik#!/bin/sh # # Copyright (c) 2007 Kungliga Tekniska Högskolan # (Royal Institute of Technology, Stockholm, Sweden). # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # 1. Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # # 3. Neither the name of the Institute nor the names of its contributors # may be used to endorse or promote products derived from this software # without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE # ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS # OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) # HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY # OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF # SUCH DAMAGE. # # $Id: test_chain.in 20809 2007-06-03 03:19:06Z lha $ # srcdir="@srcdir@" objdir="@objdir@" hxtool="${TESTS_ENVIRONMENT} ./hxtool ${stat}" if ${hxtool} info | grep 'rsa: hcrypto null RSA' > /dev/null ; then exit 77 fi if ${hxtool} info | grep 'rand: not available' > /dev/null ; then exit 77 fi echo "print DIR" ${hxtool} print --content DIR:$srcdir/data > /dev/null 2>/dev/null || exit 1 echo "print FILE" for a in $srcdir/data/*.crt; do ${hxtool} print --content FILE:"$a" > /dev/null 2>/dev/null done echo "print NULL" ${hxtool} print --content NULL: > /dev/null || exit 1 echo "copy dance" ${hxtool} certificate-copy \ FILE:${srcdir}/data/test.crt PEM-FILE:cert-pem.tmp || exit 1 ${hxtool} certificate-copy PEM-FILE:cert-pem.tmp DER-FILE:cert-der.tmp || exit 1 ${hxtool} certificate-copy DER-FILE:cert-der.tmp PEM-FILE:cert-pem2.tmp || exit 1 cmp cert-pem.tmp cert-pem2.tmp || exit 1 echo "verify n0ll cert (fail)" ${hxtool} verify --missing-revoke \ --hostname=foo.com \ cert:FILE:$srcdir/data/n0ll.pem \ anchor:FILE:$srcdir/data/n0ll.pem && exit 1 echo "verify n0ll cert (fail)" ${hxtool} verify --missing-revoke \ cert:FILE:$srcdir/data/n0ll.pem \ anchor:FILE:$srcdir/data/n0ll.pem && exit 1 echo "check that windows cert with utf16 in printable string works" ${hxtool} verify --missing-revoke \ cert:FILE:$srcdir/data/win-u16-in-printablestring.der \ anchor:FILE:$srcdir/data/win-u16-in-printablestring.der || exit 1 exit 0 heimdal-7.5.0/lib/hx509/tst-crypto-select30000644000175000017500000000002512136107750016307 0ustar niknik1.2.840.113549.1.1.4 heimdal-7.5.0/lib/hx509/sel-gram.y0000644000175000017500000000755513131326447014616 0ustar niknik/* * Copyright (c) 2017 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ %{ #ifdef HAVE_CONFIG_H #include #endif #include #include #include #if !defined(yylex) #define yylex _hx509_sel_yylex #define yywrap _hx509_sel_yywrap #endif #if !defined(yyparse) #define yyparse _hx509_sel_yyparse #define yyerror _hx509_sel_yyerror #define yylval _hx509_sel_yylval #define yychar _hx509_sel_yychar #define yydebug _hx509_sel_yydebug #define yynerrs _hx509_sel_yynerrs #endif %} %union { char *string; struct hx_expr *expr; } %token kw_TRUE %token kw_FALSE %token kw_AND %token kw_OR %token kw_IN %token kw_TAILMATCH %type expr %type comp %type word words %type number %type string %type function %type variable variables %token NUMBER %token STRING %token IDENTIFIER %start start %% start: expr { _hx509_expr_input.expr = $1; } expr : kw_TRUE { $$ = _hx509_make_expr(op_TRUE, NULL, NULL); } | kw_FALSE { $$ = _hx509_make_expr(op_FALSE, NULL, NULL); } | '!' expr { $$ = _hx509_make_expr(op_NOT, $2, NULL); } | expr kw_AND expr { $$ = _hx509_make_expr(op_AND, $1, $3); } | expr kw_OR expr { $$ = _hx509_make_expr(op_OR, $1, $3); } | '(' expr ')' { $$ = $2; } | comp { $$ = _hx509_make_expr(op_COMP, $1, NULL); } ; words : word { $$ = _hx509_make_expr(expr_WORDS, $1, NULL); } | word ',' words { $$ = _hx509_make_expr(expr_WORDS, $1, $3); } ; comp : word '=' '=' word { $$ = _hx509_make_expr(comp_EQ, $1, $4); } | word '!' '=' word { $$ = _hx509_make_expr(comp_NE, $1, $4); } | word kw_TAILMATCH word { $$ = _hx509_make_expr(comp_TAILEQ, $1, $3); } | word kw_IN '(' words ')' { $$ = _hx509_make_expr(comp_IN, $1, $4); } | word kw_IN variable { $$ = _hx509_make_expr(comp_IN, $1, $3); } ; word : number { $$ = $1; } | string { $$ = $1; } | function { $$ = $1; } | variable { $$ = $1; } ; number : NUMBER { $$ = _hx509_make_expr(expr_NUMBER, $1, NULL); }; string : STRING { $$ = _hx509_make_expr(expr_STRING, $1, NULL); }; function: IDENTIFIER '(' words ')' { $$ = _hx509_make_expr(expr_FUNCTION, $1, $3); } ; variable: '%' '{' variables '}' { $$ = $3; } ; variables: IDENTIFIER '.' variables { $$ = _hx509_make_expr(expr_VAR, $1, $3); } | IDENTIFIER { $$ = _hx509_make_expr(expr_VAR, $1, NULL); } ; heimdal-7.5.0/lib/hx509/tst-crypto-available20000644000175000017500000000014613026237312016750 0ustar niknik2.16.840.1.101.3.4.2.3 2.16.840.1.101.3.4.2.2 2.16.840.1.101.3.4.2.1 1.3.14.3.2.26 1.2.840.113549.2.5 heimdal-7.5.0/lib/hx509/crypto.c0000644000175000017500000020130713026237312014363 0ustar niknik/* * Copyright (c) 2004 - 2016 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "hx_locl.h" /*- * RFC5758 specifies no parameters for ecdsa-with-SHA signatures * RFC5754 specifies NULL parameters for shaWithRSAEncryption signatures * * XXX: Make sure that the parameters are either NULL in both the tbs and the * signature, or absent from both the tbs and the signature. */ static const heim_octet_string null_entry_oid = { 2, rk_UNCONST("\x05\x00") }; static const unsigned sha512_oid_tree[] = { 2, 16, 840, 1, 101, 3, 4, 2, 3 }; const AlgorithmIdentifier _hx509_signature_sha512_data = { { 9, rk_UNCONST(sha512_oid_tree) }, rk_UNCONST(&null_entry_oid) }; static const unsigned sha384_oid_tree[] = { 2, 16, 840, 1, 101, 3, 4, 2, 2 }; const AlgorithmIdentifier _hx509_signature_sha384_data = { { 9, rk_UNCONST(sha384_oid_tree) }, rk_UNCONST(&null_entry_oid) }; static const unsigned sha256_oid_tree[] = { 2, 16, 840, 1, 101, 3, 4, 2, 1 }; const AlgorithmIdentifier _hx509_signature_sha256_data = { { 9, rk_UNCONST(sha256_oid_tree) }, rk_UNCONST(&null_entry_oid) }; static const unsigned sha1_oid_tree[] = { 1, 3, 14, 3, 2, 26 }; const AlgorithmIdentifier _hx509_signature_sha1_data = { { 6, rk_UNCONST(sha1_oid_tree) }, rk_UNCONST(&null_entry_oid) }; static const unsigned md5_oid_tree[] = { 1, 2, 840, 113549, 2, 5 }; const AlgorithmIdentifier _hx509_signature_md5_data = { { 6, rk_UNCONST(md5_oid_tree) }, rk_UNCONST(&null_entry_oid) }; static const unsigned rsa_with_sha512_oid[] ={ 1, 2, 840, 113549, 1, 1, 13 }; const AlgorithmIdentifier _hx509_signature_rsa_with_sha512_data = { { 7, rk_UNCONST(rsa_with_sha512_oid) }, rk_UNCONST(&null_entry_oid) }; static const unsigned rsa_with_sha384_oid[] ={ 1, 2, 840, 113549, 1, 1, 12 }; const AlgorithmIdentifier _hx509_signature_rsa_with_sha384_data = { { 7, rk_UNCONST(rsa_with_sha384_oid) }, rk_UNCONST(&null_entry_oid) }; static const unsigned rsa_with_sha256_oid[] ={ 1, 2, 840, 113549, 1, 1, 11 }; const AlgorithmIdentifier _hx509_signature_rsa_with_sha256_data = { { 7, rk_UNCONST(rsa_with_sha256_oid) }, rk_UNCONST(&null_entry_oid) }; static const unsigned rsa_with_sha1_oid[] ={ 1, 2, 840, 113549, 1, 1, 5 }; const AlgorithmIdentifier _hx509_signature_rsa_with_sha1_data = { { 7, rk_UNCONST(rsa_with_sha1_oid) }, rk_UNCONST(&null_entry_oid) }; static const unsigned rsa_with_md5_oid[] ={ 1, 2, 840, 113549, 1, 1, 4 }; const AlgorithmIdentifier _hx509_signature_rsa_with_md5_data = { { 7, rk_UNCONST(rsa_with_md5_oid) }, rk_UNCONST(&null_entry_oid) }; static const unsigned rsa_oid[] ={ 1, 2, 840, 113549, 1, 1, 1 }; const AlgorithmIdentifier _hx509_signature_rsa_data = { { 7, rk_UNCONST(rsa_oid) }, NULL }; static const unsigned rsa_pkcs1_x509_oid[] ={ 1, 2, 752, 43, 16, 1 }; const AlgorithmIdentifier _hx509_signature_rsa_pkcs1_x509_data = { { 6, rk_UNCONST(rsa_pkcs1_x509_oid) }, NULL }; static const unsigned des_rsdi_ede3_cbc_oid[] ={ 1, 2, 840, 113549, 3, 7 }; const AlgorithmIdentifier _hx509_des_rsdi_ede3_cbc_oid = { { 6, rk_UNCONST(des_rsdi_ede3_cbc_oid) }, NULL }; static const unsigned aes128_cbc_oid[] ={ 2, 16, 840, 1, 101, 3, 4, 1, 2 }; const AlgorithmIdentifier _hx509_crypto_aes128_cbc_data = { { 9, rk_UNCONST(aes128_cbc_oid) }, NULL }; static const unsigned aes256_cbc_oid[] ={ 2, 16, 840, 1, 101, 3, 4, 1, 42 }; const AlgorithmIdentifier _hx509_crypto_aes256_cbc_data = { { 9, rk_UNCONST(aes256_cbc_oid) }, NULL }; /* * */ static BIGNUM * heim_int2BN(const heim_integer *i) { BIGNUM *bn; bn = BN_bin2bn(i->data, i->length, NULL); BN_set_negative(bn, i->negative); return bn; } /* * */ int _hx509_set_digest_alg(DigestAlgorithmIdentifier *id, const heim_oid *oid, const void *param, size_t length) { int ret; if (param) { id->parameters = malloc(sizeof(*id->parameters)); if (id->parameters == NULL) return ENOMEM; id->parameters->data = malloc(length); if (id->parameters->data == NULL) { free(id->parameters); id->parameters = NULL; return ENOMEM; } memcpy(id->parameters->data, param, length); id->parameters->length = length; } else id->parameters = NULL; ret = der_copy_oid(oid, &id->algorithm); if (ret) { if (id->parameters) { free(id->parameters->data); free(id->parameters); id->parameters = NULL; } return ret; } return 0; } /* * */ static int rsa_verify_signature(hx509_context context, const struct signature_alg *sig_alg, const Certificate *signer, const AlgorithmIdentifier *alg, const heim_octet_string *data, const heim_octet_string *sig) { const SubjectPublicKeyInfo *spi; DigestInfo di; unsigned char *to; int tosize, retsize; int ret; RSA *rsa; size_t size; const unsigned char *p; memset(&di, 0, sizeof(di)); spi = &signer->tbsCertificate.subjectPublicKeyInfo; p = spi->subjectPublicKey.data; size = spi->subjectPublicKey.length / 8; rsa = d2i_RSAPublicKey(NULL, &p, size); if (rsa == NULL) { ret = ENOMEM; hx509_set_error_string(context, 0, ret, "out of memory"); goto out; } tosize = RSA_size(rsa); to = malloc(tosize); if (to == NULL) { ret = ENOMEM; hx509_set_error_string(context, 0, ret, "out of memory"); goto out; } retsize = RSA_public_decrypt(sig->length, (unsigned char *)sig->data, to, rsa, RSA_PKCS1_PADDING); if (retsize <= 0) { ret = HX509_CRYPTO_SIG_INVALID_FORMAT; hx509_set_error_string(context, 0, ret, "RSA public decrypt failed: %d", retsize); free(to); goto out; } if (retsize > tosize) _hx509_abort("internal rsa decryption failure: ret > tosize"); if (sig_alg->flags & RA_RSA_USES_DIGEST_INFO) { ret = decode_DigestInfo(to, retsize, &di, &size); free(to); if (ret) { goto out; } /* Check for extra data inside the sigature */ if (size != (size_t)retsize) { ret = HX509_CRYPTO_SIG_INVALID_FORMAT; hx509_set_error_string(context, 0, ret, "size from decryption mismatch"); goto out; } if (sig_alg->digest_alg && der_heim_oid_cmp(&di.digestAlgorithm.algorithm, &sig_alg->digest_alg->algorithm) != 0) { ret = HX509_CRYPTO_OID_MISMATCH; hx509_set_error_string(context, 0, ret, "object identifier in RSA sig mismatch"); goto out; } /* verify that the parameters are NULL or the NULL-type */ if (di.digestAlgorithm.parameters != NULL && (di.digestAlgorithm.parameters->length != 2 || memcmp(di.digestAlgorithm.parameters->data, "\x05\x00", 2) != 0)) { ret = HX509_CRYPTO_SIG_INVALID_FORMAT; hx509_set_error_string(context, 0, ret, "Extra parameters inside RSA signature"); goto out; } ret = _hx509_verify_signature(context, NULL, &di.digestAlgorithm, data, &di.digest); if (ret) goto out; } else { if ((size_t)retsize != data->length || ct_memcmp(to, data->data, retsize) != 0) { ret = HX509_CRYPTO_SIG_INVALID_FORMAT; hx509_set_error_string(context, 0, ret, "RSA Signature incorrect"); goto out; } free(to); ret = 0; } out: free_DigestInfo(&di); if (rsa) RSA_free(rsa); return ret; } static int rsa_create_signature(hx509_context context, const struct signature_alg *sig_alg, const hx509_private_key signer, const AlgorithmIdentifier *alg, const heim_octet_string *data, AlgorithmIdentifier *signatureAlgorithm, heim_octet_string *sig) { const AlgorithmIdentifier *digest_alg; heim_octet_string indata; const heim_oid *sig_oid; size_t size; int ret; if (signer->ops && der_heim_oid_cmp(signer->ops->key_oid, ASN1_OID_ID_PKCS1_RSAENCRYPTION) != 0) return HX509_ALG_NOT_SUPP; if (alg) sig_oid = &alg->algorithm; else sig_oid = signer->signature_alg; if (der_heim_oid_cmp(sig_oid, ASN1_OID_ID_PKCS1_SHA512WITHRSAENCRYPTION) == 0) { digest_alg = hx509_signature_sha512(); } else if (der_heim_oid_cmp(sig_oid, ASN1_OID_ID_PKCS1_SHA384WITHRSAENCRYPTION) == 0) { digest_alg = hx509_signature_sha384(); } else if (der_heim_oid_cmp(sig_oid, ASN1_OID_ID_PKCS1_SHA256WITHRSAENCRYPTION) == 0) { digest_alg = hx509_signature_sha256(); } else if (der_heim_oid_cmp(sig_oid, ASN1_OID_ID_PKCS1_SHA1WITHRSAENCRYPTION) == 0) { digest_alg = hx509_signature_sha1(); } else if (der_heim_oid_cmp(sig_oid, ASN1_OID_ID_PKCS1_MD5WITHRSAENCRYPTION) == 0) { digest_alg = hx509_signature_md5(); } else if (der_heim_oid_cmp(sig_oid, ASN1_OID_ID_PKCS1_MD5WITHRSAENCRYPTION) == 0) { digest_alg = hx509_signature_md5(); } else if (der_heim_oid_cmp(sig_oid, ASN1_OID_ID_DSA_WITH_SHA1) == 0) { digest_alg = hx509_signature_sha1(); } else if (der_heim_oid_cmp(sig_oid, ASN1_OID_ID_PKCS1_RSAENCRYPTION) == 0) { digest_alg = hx509_signature_sha1(); } else if (der_heim_oid_cmp(sig_oid, ASN1_OID_ID_HEIM_RSA_PKCS1_X509) == 0) { digest_alg = NULL; } else return HX509_ALG_NOT_SUPP; if (signatureAlgorithm) { ret = _hx509_set_digest_alg(signatureAlgorithm, sig_oid, "\x05\x00", 2); if (ret) { hx509_clear_error_string(context); return ret; } } if (digest_alg) { DigestInfo di; memset(&di, 0, sizeof(di)); ret = _hx509_create_signature(context, NULL, digest_alg, data, &di.digestAlgorithm, &di.digest); if (ret) return ret; ASN1_MALLOC_ENCODE(DigestInfo, indata.data, indata.length, &di, &size, ret); free_DigestInfo(&di); if (ret) { hx509_set_error_string(context, 0, ret, "out of memory"); return ret; } if (indata.length != size) _hx509_abort("internal ASN.1 encoder error"); } else { indata = *data; } sig->length = RSA_size(signer->private_key.rsa); sig->data = malloc(sig->length); if (sig->data == NULL) { der_free_octet_string(&indata); hx509_set_error_string(context, 0, ENOMEM, "out of memory"); return ENOMEM; } ret = RSA_private_encrypt(indata.length, indata.data, sig->data, signer->private_key.rsa, RSA_PKCS1_PADDING); if (indata.data != data->data) der_free_octet_string(&indata); if (ret <= 0) { ret = HX509_CMS_FAILED_CREATE_SIGATURE; hx509_set_error_string(context, 0, ret, "RSA private encrypt failed: %d", ret); return ret; } if (sig->length > (size_t)ret) { size = sig->length - ret; memmove((uint8_t *)sig->data + size, sig->data, ret); memset(sig->data, 0, size); } else if (sig->length < (size_t)ret) _hx509_abort("RSA signature prelen longer the output len"); return 0; } static int rsa_private_key_import(hx509_context context, const AlgorithmIdentifier *keyai, const void *data, size_t len, hx509_key_format_t format, hx509_private_key private_key) { switch (format) { case HX509_KEY_FORMAT_DER: { const unsigned char *p = data; private_key->private_key.rsa = d2i_RSAPrivateKey(NULL, &p, len); if (private_key->private_key.rsa == NULL) { hx509_set_error_string(context, 0, HX509_PARSING_KEY_FAILED, "Failed to parse RSA key"); return HX509_PARSING_KEY_FAILED; } private_key->signature_alg = ASN1_OID_ID_PKCS1_SHA1WITHRSAENCRYPTION; break; } default: return HX509_CRYPTO_KEY_FORMAT_UNSUPPORTED; } return 0; } static int rsa_private_key2SPKI(hx509_context context, hx509_private_key private_key, SubjectPublicKeyInfo *spki) { int len, ret; memset(spki, 0, sizeof(*spki)); len = i2d_RSAPublicKey(private_key->private_key.rsa, NULL); spki->subjectPublicKey.data = malloc(len); if (spki->subjectPublicKey.data == NULL) { hx509_set_error_string(context, 0, ENOMEM, "malloc - out of memory"); return ENOMEM; } spki->subjectPublicKey.length = len * 8; ret = _hx509_set_digest_alg(&spki->algorithm, ASN1_OID_ID_PKCS1_RSAENCRYPTION, "\x05\x00", 2); if (ret) { hx509_set_error_string(context, 0, ret, "malloc - out of memory"); free(spki->subjectPublicKey.data); spki->subjectPublicKey.data = NULL; spki->subjectPublicKey.length = 0; return ret; } { unsigned char *pp = spki->subjectPublicKey.data; i2d_RSAPublicKey(private_key->private_key.rsa, &pp); } return 0; } static int rsa_generate_private_key(hx509_context context, struct hx509_generate_private_context *ctx, hx509_private_key private_key) { BIGNUM *e; int ret; unsigned long bits; static const int default_rsa_e = 65537; static const int default_rsa_bits = 2048; private_key->private_key.rsa = RSA_new(); if (private_key->private_key.rsa == NULL) { hx509_set_error_string(context, 0, HX509_PARSING_KEY_FAILED, "Failed to generate RSA key"); return HX509_PARSING_KEY_FAILED; } e = BN_new(); BN_set_word(e, default_rsa_e); bits = default_rsa_bits; if (ctx->num_bits) bits = ctx->num_bits; ret = RSA_generate_key_ex(private_key->private_key.rsa, bits, e, NULL); BN_free(e); if (ret != 1) { hx509_set_error_string(context, 0, HX509_PARSING_KEY_FAILED, "Failed to generate RSA key"); return HX509_PARSING_KEY_FAILED; } private_key->signature_alg = ASN1_OID_ID_PKCS1_SHA1WITHRSAENCRYPTION; return 0; } static int rsa_private_key_export(hx509_context context, const hx509_private_key key, hx509_key_format_t format, heim_octet_string *data) { int ret; data->data = NULL; data->length = 0; switch (format) { case HX509_KEY_FORMAT_DER: ret = i2d_RSAPrivateKey(key->private_key.rsa, NULL); if (ret <= 0) { ret = EINVAL; hx509_set_error_string(context, 0, ret, "Private key is not exportable"); return ret; } data->data = malloc(ret); if (data->data == NULL) { ret = ENOMEM; hx509_set_error_string(context, 0, ret, "malloc out of memory"); return ret; } data->length = ret; { unsigned char *p = data->data; i2d_RSAPrivateKey(key->private_key.rsa, &p); } break; default: return HX509_CRYPTO_KEY_FORMAT_UNSUPPORTED; } return 0; } static BIGNUM * rsa_get_internal(hx509_context context, hx509_private_key key, const char *type) { if (strcasecmp(type, "rsa-modulus") == 0) { return BN_dup(key->private_key.rsa->n); } else if (strcasecmp(type, "rsa-exponent") == 0) { return BN_dup(key->private_key.rsa->e); } else return NULL; } static hx509_private_key_ops rsa_private_key_ops = { "RSA PRIVATE KEY", ASN1_OID_ID_PKCS1_RSAENCRYPTION, NULL, rsa_private_key2SPKI, rsa_private_key_export, rsa_private_key_import, rsa_generate_private_key, rsa_get_internal }; /* * */ static int dsa_verify_signature(hx509_context context, const struct signature_alg *sig_alg, const Certificate *signer, const AlgorithmIdentifier *alg, const heim_octet_string *data, const heim_octet_string *sig) { const SubjectPublicKeyInfo *spi; DSAPublicKey pk; DSAParams param; size_t size; DSA *dsa; int ret; spi = &signer->tbsCertificate.subjectPublicKeyInfo; dsa = DSA_new(); if (dsa == NULL) { hx509_set_error_string(context, 0, ENOMEM, "out of memory"); return ENOMEM; } ret = decode_DSAPublicKey(spi->subjectPublicKey.data, spi->subjectPublicKey.length / 8, &pk, &size); if (ret) goto out; dsa->pub_key = heim_int2BN(&pk); free_DSAPublicKey(&pk); if (dsa->pub_key == NULL) { ret = ENOMEM; hx509_set_error_string(context, 0, ret, "out of memory"); goto out; } if (spi->algorithm.parameters == NULL) { ret = HX509_CRYPTO_SIG_INVALID_FORMAT; hx509_set_error_string(context, 0, ret, "DSA parameters missing"); goto out; } ret = decode_DSAParams(spi->algorithm.parameters->data, spi->algorithm.parameters->length, ¶m, &size); if (ret) { hx509_set_error_string(context, 0, ret, "DSA parameters failed to decode"); goto out; } dsa->p = heim_int2BN(¶m.p); dsa->q = heim_int2BN(¶m.q); dsa->g = heim_int2BN(¶m.g); free_DSAParams(¶m); if (dsa->p == NULL || dsa->q == NULL || dsa->g == NULL) { ret = ENOMEM; hx509_set_error_string(context, 0, ret, "out of memory"); goto out; } ret = DSA_verify(-1, data->data, data->length, (unsigned char*)sig->data, sig->length, dsa); if (ret == 1) ret = 0; else if (ret == 0 || ret == -1) { ret = HX509_CRYPTO_BAD_SIGNATURE; hx509_set_error_string(context, 0, ret, "BAD DSA sigature"); } else { ret = HX509_CRYPTO_SIG_INVALID_FORMAT; hx509_set_error_string(context, 0, ret, "Invalid format of DSA sigature"); } out: DSA_free(dsa); return ret; } #if 0 static int dsa_parse_private_key(hx509_context context, const void *data, size_t len, hx509_private_key private_key) { const unsigned char *p = data; private_key->private_key.dsa = d2i_DSAPrivateKey(NULL, &p, len); if (private_key->private_key.dsa == NULL) return EINVAL; private_key->signature_alg = ASN1_OID_ID_DSA_WITH_SHA1; return 0; /* else */ hx509_set_error_string(context, 0, HX509_PARSING_KEY_FAILED, "No support to parse DSA keys"); return HX509_PARSING_KEY_FAILED; } #endif static int evp_md_create_signature(hx509_context context, const struct signature_alg *sig_alg, const hx509_private_key signer, const AlgorithmIdentifier *alg, const heim_octet_string *data, AlgorithmIdentifier *signatureAlgorithm, heim_octet_string *sig) { size_t sigsize = EVP_MD_size(sig_alg->evp_md()); EVP_MD_CTX *ctx; memset(sig, 0, sizeof(*sig)); if (signatureAlgorithm) { int ret; ret = _hx509_set_digest_alg(signatureAlgorithm, sig_alg->sig_oid, "\x05\x00", 2); if (ret) return ret; } sig->data = malloc(sigsize); if (sig->data == NULL) { sig->length = 0; return ENOMEM; } sig->length = sigsize; ctx = EVP_MD_CTX_create(); EVP_DigestInit_ex(ctx, sig_alg->evp_md(), NULL); EVP_DigestUpdate(ctx, data->data, data->length); EVP_DigestFinal_ex(ctx, sig->data, NULL); EVP_MD_CTX_destroy(ctx); return 0; } static int evp_md_verify_signature(hx509_context context, const struct signature_alg *sig_alg, const Certificate *signer, const AlgorithmIdentifier *alg, const heim_octet_string *data, const heim_octet_string *sig) { unsigned char digest[EVP_MAX_MD_SIZE]; EVP_MD_CTX *ctx; size_t sigsize = EVP_MD_size(sig_alg->evp_md()); if (sig->length != sigsize || sigsize > sizeof(digest)) { hx509_set_error_string(context, 0, HX509_CRYPTO_SIG_INVALID_FORMAT, "SHA256 sigature have wrong length"); return HX509_CRYPTO_SIG_INVALID_FORMAT; } ctx = EVP_MD_CTX_create(); EVP_DigestInit_ex(ctx, sig_alg->evp_md(), NULL); EVP_DigestUpdate(ctx, data->data, data->length); EVP_DigestFinal_ex(ctx, digest, NULL); EVP_MD_CTX_destroy(ctx); if (ct_memcmp(digest, sig->data, sigsize) != 0) { hx509_set_error_string(context, 0, HX509_CRYPTO_BAD_SIGNATURE, "Bad %s sigature", sig_alg->name); return HX509_CRYPTO_BAD_SIGNATURE; } return 0; } #ifdef HAVE_HCRYPTO_W_OPENSSL extern const struct signature_alg ecdsa_with_sha512_alg; extern const struct signature_alg ecdsa_with_sha384_alg; extern const struct signature_alg ecdsa_with_sha256_alg; extern const struct signature_alg ecdsa_with_sha1_alg; #endif static const struct signature_alg heim_rsa_pkcs1_x509 = { "rsa-pkcs1-x509", ASN1_OID_ID_HEIM_RSA_PKCS1_X509, &_hx509_signature_rsa_pkcs1_x509_data, ASN1_OID_ID_PKCS1_RSAENCRYPTION, NULL, PROVIDE_CONF|REQUIRE_SIGNER|SIG_PUBLIC_SIG, 0, NULL, rsa_verify_signature, rsa_create_signature, 0 }; static const struct signature_alg pkcs1_rsa_sha1_alg = { "rsa", ASN1_OID_ID_PKCS1_RSAENCRYPTION, &_hx509_signature_rsa_with_sha1_data, ASN1_OID_ID_PKCS1_RSAENCRYPTION, NULL, PROVIDE_CONF|REQUIRE_SIGNER|RA_RSA_USES_DIGEST_INFO|SIG_PUBLIC_SIG|SELF_SIGNED_OK, 0, NULL, rsa_verify_signature, rsa_create_signature, 0 }; static const struct signature_alg rsa_with_sha512_alg = { "rsa-with-sha512", ASN1_OID_ID_PKCS1_SHA512WITHRSAENCRYPTION, &_hx509_signature_rsa_with_sha512_data, ASN1_OID_ID_PKCS1_RSAENCRYPTION, &_hx509_signature_sha512_data, PROVIDE_CONF|REQUIRE_SIGNER|RA_RSA_USES_DIGEST_INFO|SIG_PUBLIC_SIG|SELF_SIGNED_OK, 0, NULL, rsa_verify_signature, rsa_create_signature, 0 }; static const struct signature_alg rsa_with_sha384_alg = { "rsa-with-sha384", ASN1_OID_ID_PKCS1_SHA384WITHRSAENCRYPTION, &_hx509_signature_rsa_with_sha384_data, ASN1_OID_ID_PKCS1_RSAENCRYPTION, &_hx509_signature_sha384_data, PROVIDE_CONF|REQUIRE_SIGNER|RA_RSA_USES_DIGEST_INFO|SIG_PUBLIC_SIG|SELF_SIGNED_OK, 0, NULL, rsa_verify_signature, rsa_create_signature, 0 }; static const struct signature_alg rsa_with_sha256_alg = { "rsa-with-sha256", ASN1_OID_ID_PKCS1_SHA256WITHRSAENCRYPTION, &_hx509_signature_rsa_with_sha256_data, ASN1_OID_ID_PKCS1_RSAENCRYPTION, &_hx509_signature_sha256_data, PROVIDE_CONF|REQUIRE_SIGNER|RA_RSA_USES_DIGEST_INFO|SIG_PUBLIC_SIG|SELF_SIGNED_OK, 0, NULL, rsa_verify_signature, rsa_create_signature, 0 }; static const struct signature_alg rsa_with_sha1_alg = { "rsa-with-sha1", ASN1_OID_ID_PKCS1_SHA1WITHRSAENCRYPTION, &_hx509_signature_rsa_with_sha1_data, ASN1_OID_ID_PKCS1_RSAENCRYPTION, &_hx509_signature_sha1_data, PROVIDE_CONF|REQUIRE_SIGNER|RA_RSA_USES_DIGEST_INFO|SIG_PUBLIC_SIG|SELF_SIGNED_OK, 0, NULL, rsa_verify_signature, rsa_create_signature, 0 }; static const struct signature_alg rsa_with_sha1_alg_secsig = { "rsa-with-sha1", ASN1_OID_ID_SECSIG_SHA_1WITHRSAENCRYPTION, &_hx509_signature_rsa_with_sha1_data, ASN1_OID_ID_PKCS1_RSAENCRYPTION, &_hx509_signature_sha1_data, PROVIDE_CONF|REQUIRE_SIGNER|RA_RSA_USES_DIGEST_INFO|SIG_PUBLIC_SIG|SELF_SIGNED_OK, 0, NULL, rsa_verify_signature, rsa_create_signature, 0 }; static const struct signature_alg rsa_with_md5_alg = { "rsa-with-md5", ASN1_OID_ID_PKCS1_MD5WITHRSAENCRYPTION, &_hx509_signature_rsa_with_md5_data, ASN1_OID_ID_PKCS1_RSAENCRYPTION, &_hx509_signature_md5_data, PROVIDE_CONF|REQUIRE_SIGNER|RA_RSA_USES_DIGEST_INFO|SIG_PUBLIC_SIG|WEAK_SIG_ALG, 1230739889, NULL, rsa_verify_signature, rsa_create_signature, 0 }; static const struct signature_alg dsa_sha1_alg = { "dsa-with-sha1", ASN1_OID_ID_DSA_WITH_SHA1, NULL, ASN1_OID_ID_DSA, &_hx509_signature_sha1_data, PROVIDE_CONF|REQUIRE_SIGNER|SIG_PUBLIC_SIG, 0, NULL, dsa_verify_signature, /* create_signature */ NULL, 0 }; static const struct signature_alg sha512_alg = { "sha-512", ASN1_OID_ID_SHA512, &_hx509_signature_sha512_data, NULL, NULL, SIG_DIGEST, 0, EVP_sha512, evp_md_verify_signature, evp_md_create_signature, 0 }; static const struct signature_alg sha384_alg = { "sha-384", ASN1_OID_ID_SHA512, &_hx509_signature_sha384_data, NULL, NULL, SIG_DIGEST, 0, EVP_sha384, evp_md_verify_signature, evp_md_create_signature, 0 }; static const struct signature_alg sha256_alg = { "sha-256", ASN1_OID_ID_SHA256, &_hx509_signature_sha256_data, NULL, NULL, SIG_DIGEST, 0, EVP_sha256, evp_md_verify_signature, evp_md_create_signature, 0 }; static const struct signature_alg sha1_alg = { "sha1", ASN1_OID_ID_SECSIG_SHA_1, &_hx509_signature_sha1_data, NULL, NULL, SIG_DIGEST, 0, EVP_sha1, evp_md_verify_signature, evp_md_create_signature, 0 }; static const struct signature_alg md5_alg = { "rsa-md5", ASN1_OID_ID_RSA_DIGEST_MD5, &_hx509_signature_md5_data, NULL, NULL, SIG_DIGEST|WEAK_SIG_ALG, 0, EVP_md5, evp_md_verify_signature, NULL, 0 }; /* * Order matter in this structure, "best" first for each "key * compatible" type (type is ECDSA, RSA, DSA, none, etc) */ static const struct signature_alg *sig_algs[] = { #ifdef HAVE_HCRYPTO_W_OPENSSL &ecdsa_with_sha512_alg, &ecdsa_with_sha384_alg, &ecdsa_with_sha256_alg, &ecdsa_with_sha1_alg, #endif &rsa_with_sha512_alg, &rsa_with_sha384_alg, &rsa_with_sha256_alg, &rsa_with_sha1_alg, &rsa_with_sha1_alg_secsig, &pkcs1_rsa_sha1_alg, &rsa_with_md5_alg, &heim_rsa_pkcs1_x509, &dsa_sha1_alg, &sha512_alg, &sha384_alg, &sha256_alg, &sha1_alg, &md5_alg, NULL }; const struct signature_alg * _hx509_find_sig_alg(const heim_oid *oid) { unsigned int i; for (i = 0; sig_algs[i]; i++) if (der_heim_oid_cmp(sig_algs[i]->sig_oid, oid) == 0) return sig_algs[i]; return NULL; } static const AlgorithmIdentifier * alg_for_privatekey(const hx509_private_key pk, int type) { const heim_oid *keytype; unsigned int i; if (pk->ops == NULL) return NULL; keytype = pk->ops->key_oid; for (i = 0; sig_algs[i]; i++) { if (sig_algs[i]->key_oid == NULL) continue; if (der_heim_oid_cmp(sig_algs[i]->key_oid, keytype) != 0) continue; if (pk->ops->available && pk->ops->available(pk, sig_algs[i]->sig_alg) == 0) continue; if (type == HX509_SELECT_PUBLIC_SIG) return sig_algs[i]->sig_alg; if (type == HX509_SELECT_DIGEST) return sig_algs[i]->digest_alg; return NULL; } return NULL; } /* * */ #ifdef HAVE_HCRYPTO_W_OPENSSL extern hx509_private_key_ops ecdsa_private_key_ops; #endif static struct hx509_private_key_ops *private_algs[] = { &rsa_private_key_ops, #ifdef HAVE_HCRYPTO_W_OPENSSL &ecdsa_private_key_ops, #endif NULL }; hx509_private_key_ops * hx509_find_private_alg(const heim_oid *oid) { int i; for (i = 0; private_algs[i]; i++) { if (private_algs[i]->key_oid == NULL) continue; if (der_heim_oid_cmp(private_algs[i]->key_oid, oid) == 0) return private_algs[i]; } return NULL; } /* * Check if the algorithm `alg' have a best before date, and if it * des, make sure the its before the time `t'. */ int _hx509_signature_is_weak(hx509_context context, const AlgorithmIdentifier *alg) { const struct signature_alg *md; md = _hx509_find_sig_alg(&alg->algorithm); if (md == NULL) { hx509_clear_error_string(context); return HX509_SIG_ALG_NO_SUPPORTED; } if (md->flags & WEAK_SIG_ALG) { hx509_set_error_string(context, 0, HX509_CRYPTO_ALGORITHM_BEST_BEFORE, "Algorithm %s is weak", md->name); return HX509_CRYPTO_ALGORITHM_BEST_BEFORE; } return 0; } int _hx509_self_signed_valid(hx509_context context, const AlgorithmIdentifier *alg) { const struct signature_alg *md; md = _hx509_find_sig_alg(&alg->algorithm); if (md == NULL) { hx509_clear_error_string(context); return HX509_SIG_ALG_NO_SUPPORTED; } if ((md->flags & SELF_SIGNED_OK) == 0) { hx509_set_error_string(context, 0, HX509_CRYPTO_ALGORITHM_BEST_BEFORE, "Algorithm %s not trusted for self signatures", md->name); return HX509_CRYPTO_ALGORITHM_BEST_BEFORE; } return 0; } int _hx509_verify_signature(hx509_context context, const hx509_cert cert, const AlgorithmIdentifier *alg, const heim_octet_string *data, const heim_octet_string *sig) { const struct signature_alg *md; const Certificate *signer = NULL; if (cert) signer = _hx509_get_cert(cert); md = _hx509_find_sig_alg(&alg->algorithm); if (md == NULL) { hx509_clear_error_string(context); return HX509_SIG_ALG_NO_SUPPORTED; } if (signer && (md->flags & PROVIDE_CONF) == 0) { hx509_clear_error_string(context); return HX509_CRYPTO_SIG_NO_CONF; } if (signer == NULL && (md->flags & REQUIRE_SIGNER)) { hx509_clear_error_string(context); return HX509_CRYPTO_SIGNATURE_WITHOUT_SIGNER; } if (md->key_oid && signer) { const SubjectPublicKeyInfo *spi; spi = &signer->tbsCertificate.subjectPublicKeyInfo; if (der_heim_oid_cmp(&spi->algorithm.algorithm, md->key_oid) != 0) { hx509_clear_error_string(context); return HX509_SIG_ALG_DONT_MATCH_KEY_ALG; } } return (*md->verify_signature)(context, md, signer, alg, data, sig); } int _hx509_create_signature(hx509_context context, const hx509_private_key signer, const AlgorithmIdentifier *alg, const heim_octet_string *data, AlgorithmIdentifier *signatureAlgorithm, heim_octet_string *sig) { const struct signature_alg *md; md = _hx509_find_sig_alg(&alg->algorithm); if (md == NULL) { hx509_set_error_string(context, 0, HX509_SIG_ALG_NO_SUPPORTED, "algorithm no supported"); return HX509_SIG_ALG_NO_SUPPORTED; } if (signer && (md->flags & PROVIDE_CONF) == 0) { hx509_set_error_string(context, 0, HX509_SIG_ALG_NO_SUPPORTED, "algorithm provides no conf"); return HX509_CRYPTO_SIG_NO_CONF; } return (*md->create_signature)(context, md, signer, alg, data, signatureAlgorithm, sig); } int _hx509_create_signature_bitstring(hx509_context context, const hx509_private_key signer, const AlgorithmIdentifier *alg, const heim_octet_string *data, AlgorithmIdentifier *signatureAlgorithm, heim_bit_string *sig) { heim_octet_string os; int ret; ret = _hx509_create_signature(context, signer, alg, data, signatureAlgorithm, &os); if (ret) return ret; sig->data = os.data; sig->length = os.length * 8; return 0; } int _hx509_public_encrypt(hx509_context context, const heim_octet_string *cleartext, const Certificate *cert, heim_oid *encryption_oid, heim_octet_string *ciphertext) { const SubjectPublicKeyInfo *spi; unsigned char *to; int tosize; int ret; RSA *rsa; size_t size; const unsigned char *p; ciphertext->data = NULL; ciphertext->length = 0; spi = &cert->tbsCertificate.subjectPublicKeyInfo; p = spi->subjectPublicKey.data; size = spi->subjectPublicKey.length / 8; rsa = d2i_RSAPublicKey(NULL, &p, size); if (rsa == NULL) { hx509_set_error_string(context, 0, ENOMEM, "out of memory"); return ENOMEM; } tosize = RSA_size(rsa); to = malloc(tosize); if (to == NULL) { RSA_free(rsa); hx509_set_error_string(context, 0, ENOMEM, "out of memory"); return ENOMEM; } ret = RSA_public_encrypt(cleartext->length, (unsigned char *)cleartext->data, to, rsa, RSA_PKCS1_PADDING); RSA_free(rsa); if (ret <= 0) { free(to); hx509_set_error_string(context, 0, HX509_CRYPTO_RSA_PUBLIC_ENCRYPT, "RSA public encrypt failed with %d", ret); return HX509_CRYPTO_RSA_PUBLIC_ENCRYPT; } if (ret > tosize) _hx509_abort("internal rsa decryption failure: ret > tosize"); ciphertext->length = ret; ciphertext->data = to; ret = der_copy_oid(ASN1_OID_ID_PKCS1_RSAENCRYPTION, encryption_oid); if (ret) { der_free_octet_string(ciphertext); hx509_set_error_string(context, 0, ENOMEM, "out of memory"); return ENOMEM; } return 0; } int hx509_private_key_private_decrypt(hx509_context context, const heim_octet_string *ciphertext, const heim_oid *encryption_oid, hx509_private_key p, heim_octet_string *cleartext) { int ret; cleartext->data = NULL; cleartext->length = 0; if (p->private_key.rsa == NULL) { hx509_set_error_string(context, 0, HX509_PRIVATE_KEY_MISSING, "Private RSA key missing"); return HX509_PRIVATE_KEY_MISSING; } cleartext->length = RSA_size(p->private_key.rsa); cleartext->data = malloc(cleartext->length); if (cleartext->data == NULL) { hx509_set_error_string(context, 0, ENOMEM, "out of memory"); return ENOMEM; } ret = RSA_private_decrypt(ciphertext->length, ciphertext->data, cleartext->data, p->private_key.rsa, RSA_PKCS1_PADDING); if (ret <= 0) { der_free_octet_string(cleartext); hx509_set_error_string(context, 0, HX509_CRYPTO_RSA_PRIVATE_DECRYPT, "Failed to decrypt using private key: %d", ret); return HX509_CRYPTO_RSA_PRIVATE_DECRYPT; } if (cleartext->length < (size_t)ret) _hx509_abort("internal rsa decryption failure: ret > tosize"); cleartext->length = ret; return 0; } int hx509_parse_private_key(hx509_context context, const AlgorithmIdentifier *keyai, const void *data, size_t len, hx509_key_format_t format, hx509_private_key *private_key) { struct hx509_private_key_ops *ops; int ret; *private_key = NULL; ops = hx509_find_private_alg(&keyai->algorithm); if (ops == NULL) { hx509_clear_error_string(context); return HX509_SIG_ALG_NO_SUPPORTED; } ret = hx509_private_key_init(private_key, ops, NULL); if (ret) { hx509_set_error_string(context, 0, ret, "out of memory"); return ret; } ret = (*ops->import)(context, keyai, data, len, format, *private_key); if (ret) hx509_private_key_free(private_key); return ret; } /* * */ int hx509_private_key2SPKI(hx509_context context, hx509_private_key private_key, SubjectPublicKeyInfo *spki) { const struct hx509_private_key_ops *ops = private_key->ops; if (ops == NULL || ops->get_spki == NULL) { hx509_set_error_string(context, 0, HX509_UNIMPLEMENTED_OPERATION, "Private key have no key2SPKI function"); return HX509_UNIMPLEMENTED_OPERATION; } return (*ops->get_spki)(context, private_key, spki); } int _hx509_generate_private_key_init(hx509_context context, const heim_oid *oid, struct hx509_generate_private_context **ctx) { *ctx = NULL; if (der_heim_oid_cmp(oid, ASN1_OID_ID_PKCS1_RSAENCRYPTION) != 0) { hx509_set_error_string(context, 0, EINVAL, "private key not an RSA key"); return EINVAL; } *ctx = calloc(1, sizeof(**ctx)); if (*ctx == NULL) { hx509_set_error_string(context, 0, ENOMEM, "out of memory"); return ENOMEM; } (*ctx)->key_oid = oid; return 0; } int _hx509_generate_private_key_is_ca(hx509_context context, struct hx509_generate_private_context *ctx) { ctx->isCA = 1; return 0; } int _hx509_generate_private_key_bits(hx509_context context, struct hx509_generate_private_context *ctx, unsigned long bits) { ctx->num_bits = bits; return 0; } void _hx509_generate_private_key_free(struct hx509_generate_private_context **ctx) { free(*ctx); *ctx = NULL; } int _hx509_generate_private_key(hx509_context context, struct hx509_generate_private_context *ctx, hx509_private_key *private_key) { struct hx509_private_key_ops *ops; int ret; *private_key = NULL; ops = hx509_find_private_alg(ctx->key_oid); if (ops == NULL) { hx509_clear_error_string(context); return HX509_SIG_ALG_NO_SUPPORTED; } ret = hx509_private_key_init(private_key, ops, NULL); if (ret) { hx509_set_error_string(context, 0, ret, "out of memory"); return ret; } ret = (*ops->generate_private_key)(context, ctx, *private_key); if (ret) hx509_private_key_free(private_key); return ret; } /* * */ const AlgorithmIdentifier * hx509_signature_sha512(void) { return &_hx509_signature_sha512_data; } const AlgorithmIdentifier * hx509_signature_sha384(void) { return &_hx509_signature_sha384_data; } const AlgorithmIdentifier * hx509_signature_sha256(void) { return &_hx509_signature_sha256_data; } const AlgorithmIdentifier * hx509_signature_sha1(void) { return &_hx509_signature_sha1_data; } const AlgorithmIdentifier * hx509_signature_md5(void) { return &_hx509_signature_md5_data; } const AlgorithmIdentifier * hx509_signature_rsa_with_sha512(void) { return &_hx509_signature_rsa_with_sha512_data; } const AlgorithmIdentifier * hx509_signature_rsa_with_sha384(void) { return &_hx509_signature_rsa_with_sha384_data; } const AlgorithmIdentifier * hx509_signature_rsa_with_sha256(void) { return &_hx509_signature_rsa_with_sha256_data; } const AlgorithmIdentifier * hx509_signature_rsa_with_sha1(void) { return &_hx509_signature_rsa_with_sha1_data; } const AlgorithmIdentifier * hx509_signature_rsa_with_md5(void) { return &_hx509_signature_rsa_with_md5_data; } const AlgorithmIdentifier * hx509_signature_rsa(void) { return &_hx509_signature_rsa_data; } const AlgorithmIdentifier * hx509_signature_rsa_pkcs1_x509(void) { return &_hx509_signature_rsa_pkcs1_x509_data; } const AlgorithmIdentifier * hx509_crypto_des_rsdi_ede3_cbc(void) { return &_hx509_des_rsdi_ede3_cbc_oid; } const AlgorithmIdentifier * hx509_crypto_aes128_cbc(void) { return &_hx509_crypto_aes128_cbc_data; } const AlgorithmIdentifier * hx509_crypto_aes256_cbc(void) { return &_hx509_crypto_aes256_cbc_data; } /* * */ const AlgorithmIdentifier * _hx509_crypto_default_sig_alg = &_hx509_signature_rsa_with_sha256_data; const AlgorithmIdentifier * _hx509_crypto_default_digest_alg = &_hx509_signature_sha256_data; const AlgorithmIdentifier * _hx509_crypto_default_secret_alg = &_hx509_crypto_aes128_cbc_data; /* * */ int hx509_private_key_init(hx509_private_key *key, hx509_private_key_ops *ops, void *keydata) { *key = calloc(1, sizeof(**key)); if (*key == NULL) return ENOMEM; (*key)->ref = 1; (*key)->ops = ops; (*key)->private_key.keydata = keydata; return 0; } hx509_private_key _hx509_private_key_ref(hx509_private_key key) { if (key->ref == 0) _hx509_abort("key refcount <= 0 on ref"); key->ref++; if (key->ref == UINT_MAX) _hx509_abort("key refcount == UINT_MAX on ref"); return key; } const char * _hx509_private_pem_name(hx509_private_key key) { return key->ops->pemtype; } int hx509_private_key_free(hx509_private_key *key) { if (key == NULL || *key == NULL) return 0; if ((*key)->ref == 0) _hx509_abort("key refcount == 0 on free"); if (--(*key)->ref > 0) return 0; if ((*key)->ops && der_heim_oid_cmp((*key)->ops->key_oid, ASN1_OID_ID_PKCS1_RSAENCRYPTION) == 0) { if ((*key)->private_key.rsa) RSA_free((*key)->private_key.rsa); } else if ((*key)->ops && der_heim_oid_cmp((*key)->ops->key_oid, ASN1_OID_ID_ECPUBLICKEY) == 0 && (*key)->private_key.ecdsa != NULL) { _hx509_private_eckey_free((*key)->private_key.ecdsa); } (*key)->private_key.rsa = NULL; free(*key); *key = NULL; return 0; } void hx509_private_key_assign_rsa(hx509_private_key key, void *ptr) { if (key->private_key.rsa) RSA_free(key->private_key.rsa); key->private_key.rsa = ptr; key->signature_alg = ASN1_OID_ID_PKCS1_SHA1WITHRSAENCRYPTION; key->md = &pkcs1_rsa_sha1_alg; } int _hx509_private_key_oid(hx509_context context, const hx509_private_key key, heim_oid *data) { int ret; ret = der_copy_oid(key->ops->key_oid, data); if (ret) hx509_set_error_string(context, 0, ret, "malloc out of memory"); return ret; } int _hx509_private_key_exportable(hx509_private_key key) { if (key->ops->export == NULL) return 0; return 1; } BIGNUM * _hx509_private_key_get_internal(hx509_context context, hx509_private_key key, const char *type) { if (key->ops->get_internal == NULL) return NULL; return (*key->ops->get_internal)(context, key, type); } int _hx509_private_key_export(hx509_context context, const hx509_private_key key, hx509_key_format_t format, heim_octet_string *data) { if (key->ops->export == NULL) { hx509_clear_error_string(context); return HX509_UNIMPLEMENTED_OPERATION; } return (*key->ops->export)(context, key, format, data); } /* * */ struct hx509cipher { const char *name; int flags; #define CIPHER_WEAK 1 const heim_oid *oid; const AlgorithmIdentifier *(*ai_func)(void); const EVP_CIPHER *(*evp_func)(void); int (*get_params)(hx509_context, const hx509_crypto, const heim_octet_string *, heim_octet_string *); int (*set_params)(hx509_context, const heim_octet_string *, hx509_crypto, heim_octet_string *); }; struct hx509_crypto_data { char *name; int flags; #define ALLOW_WEAK 1 #define PADDING_NONE 2 #define PADDING_PKCS7 4 #define PADDING_FLAGS (2|4) const struct hx509cipher *cipher; const EVP_CIPHER *c; heim_octet_string key; heim_oid oid; void *param; }; /* * */ static unsigned private_rc2_40_oid_data[] = { 127, 1 }; static heim_oid asn1_oid_private_rc2_40 = { 2, private_rc2_40_oid_data }; /* * */ static int CMSCBCParam_get(hx509_context context, const hx509_crypto crypto, const heim_octet_string *ivec, heim_octet_string *param) { size_t size; int ret; assert(crypto->param == NULL); if (ivec == NULL) return 0; ASN1_MALLOC_ENCODE(CMSCBCParameter, param->data, param->length, ivec, &size, ret); if (ret == 0 && size != param->length) _hx509_abort("Internal asn1 encoder failure"); if (ret) hx509_clear_error_string(context); return ret; } static int CMSCBCParam_set(hx509_context context, const heim_octet_string *param, hx509_crypto crypto, heim_octet_string *ivec) { int ret; if (ivec == NULL) return 0; ret = decode_CMSCBCParameter(param->data, param->length, ivec, NULL); if (ret) hx509_clear_error_string(context); return ret; } struct _RC2_params { int maximum_effective_key; }; static int CMSRC2CBCParam_get(hx509_context context, const hx509_crypto crypto, const heim_octet_string *ivec, heim_octet_string *param) { CMSRC2CBCParameter rc2params; const struct _RC2_params *p = crypto->param; int maximum_effective_key = 128; size_t size; int ret; memset(&rc2params, 0, sizeof(rc2params)); if (p) maximum_effective_key = p->maximum_effective_key; switch(maximum_effective_key) { case 40: rc2params.rc2ParameterVersion = 160; break; case 64: rc2params.rc2ParameterVersion = 120; break; case 128: rc2params.rc2ParameterVersion = 58; break; } rc2params.iv = *ivec; ASN1_MALLOC_ENCODE(CMSRC2CBCParameter, param->data, param->length, &rc2params, &size, ret); if (ret == 0 && size != param->length) _hx509_abort("Internal asn1 encoder failure"); return ret; } static int CMSRC2CBCParam_set(hx509_context context, const heim_octet_string *param, hx509_crypto crypto, heim_octet_string *ivec) { CMSRC2CBCParameter rc2param; struct _RC2_params *p; size_t size; int ret; ret = decode_CMSRC2CBCParameter(param->data, param->length, &rc2param, &size); if (ret) { hx509_clear_error_string(context); return ret; } p = calloc(1, sizeof(*p)); if (p == NULL) { free_CMSRC2CBCParameter(&rc2param); hx509_clear_error_string(context); return ENOMEM; } switch(rc2param.rc2ParameterVersion) { case 160: crypto->c = EVP_rc2_40_cbc(); p->maximum_effective_key = 40; break; case 120: crypto->c = EVP_rc2_64_cbc(); p->maximum_effective_key = 64; break; case 58: crypto->c = EVP_rc2_cbc(); p->maximum_effective_key = 128; break; default: free(p); free_CMSRC2CBCParameter(&rc2param); return HX509_CRYPTO_SIG_INVALID_FORMAT; } if (ivec) ret = der_copy_octet_string(&rc2param.iv, ivec); free_CMSRC2CBCParameter(&rc2param); if (ret) { free(p); hx509_clear_error_string(context); } else crypto->param = p; return ret; } /* * */ static const struct hx509cipher ciphers[] = { { "rc2-cbc", CIPHER_WEAK, ASN1_OID_ID_PKCS3_RC2_CBC, NULL, EVP_rc2_cbc, CMSRC2CBCParam_get, CMSRC2CBCParam_set }, { "rc2-cbc", CIPHER_WEAK, ASN1_OID_ID_RSADSI_RC2_CBC, NULL, EVP_rc2_cbc, CMSRC2CBCParam_get, CMSRC2CBCParam_set }, { "rc2-40-cbc", CIPHER_WEAK, &asn1_oid_private_rc2_40, NULL, EVP_rc2_40_cbc, CMSRC2CBCParam_get, CMSRC2CBCParam_set }, { "des-ede3-cbc", 0, ASN1_OID_ID_PKCS3_DES_EDE3_CBC, NULL, EVP_des_ede3_cbc, CMSCBCParam_get, CMSCBCParam_set }, { "des-ede3-cbc", 0, ASN1_OID_ID_RSADSI_DES_EDE3_CBC, hx509_crypto_des_rsdi_ede3_cbc, EVP_des_ede3_cbc, CMSCBCParam_get, CMSCBCParam_set }, { "aes-128-cbc", 0, ASN1_OID_ID_AES_128_CBC, hx509_crypto_aes128_cbc, EVP_aes_128_cbc, CMSCBCParam_get, CMSCBCParam_set }, { "aes-192-cbc", 0, ASN1_OID_ID_AES_192_CBC, NULL, EVP_aes_192_cbc, CMSCBCParam_get, CMSCBCParam_set }, { "aes-256-cbc", 0, ASN1_OID_ID_AES_256_CBC, hx509_crypto_aes256_cbc, EVP_aes_256_cbc, CMSCBCParam_get, CMSCBCParam_set } }; static const struct hx509cipher * find_cipher_by_oid(const heim_oid *oid) { size_t i; for (i = 0; i < sizeof(ciphers)/sizeof(ciphers[0]); i++) if (der_heim_oid_cmp(oid, ciphers[i].oid) == 0) return &ciphers[i]; return NULL; } static const struct hx509cipher * find_cipher_by_name(const char *name) { size_t i; for (i = 0; i < sizeof(ciphers)/sizeof(ciphers[0]); i++) if (strcasecmp(name, ciphers[i].name) == 0) return &ciphers[i]; return NULL; } const heim_oid * hx509_crypto_enctype_by_name(const char *name) { const struct hx509cipher *cipher; cipher = find_cipher_by_name(name); if (cipher == NULL) return NULL; return cipher->oid; } int hx509_crypto_init(hx509_context context, const char *provider, const heim_oid *enctype, hx509_crypto *crypto) { const struct hx509cipher *cipher; *crypto = NULL; cipher = find_cipher_by_oid(enctype); if (cipher == NULL) { hx509_set_error_string(context, 0, HX509_ALG_NOT_SUPP, "Algorithm not supported"); return HX509_ALG_NOT_SUPP; } *crypto = calloc(1, sizeof(**crypto)); if (*crypto == NULL) { hx509_clear_error_string(context); return ENOMEM; } (*crypto)->flags = PADDING_PKCS7; (*crypto)->cipher = cipher; (*crypto)->c = (*cipher->evp_func)(); if (der_copy_oid(enctype, &(*crypto)->oid)) { hx509_crypto_destroy(*crypto); *crypto = NULL; hx509_clear_error_string(context); return ENOMEM; } return 0; } const char * hx509_crypto_provider(hx509_crypto crypto) { return "unknown"; } void hx509_crypto_destroy(hx509_crypto crypto) { if (crypto->name) free(crypto->name); if (crypto->key.data) free(crypto->key.data); if (crypto->param) free(crypto->param); der_free_oid(&crypto->oid); memset(crypto, 0, sizeof(*crypto)); free(crypto); } int hx509_crypto_set_key_name(hx509_crypto crypto, const char *name) { return 0; } void hx509_crypto_allow_weak(hx509_crypto crypto) { crypto->flags |= ALLOW_WEAK; } void hx509_crypto_set_padding(hx509_crypto crypto, int padding_type) { switch (padding_type) { case HX509_CRYPTO_PADDING_PKCS7: crypto->flags &= ~PADDING_FLAGS; crypto->flags |= PADDING_PKCS7; break; case HX509_CRYPTO_PADDING_NONE: crypto->flags &= ~PADDING_FLAGS; crypto->flags |= PADDING_NONE; break; default: _hx509_abort("Invalid padding"); } } int hx509_crypto_set_key_data(hx509_crypto crypto, const void *data, size_t length) { if (EVP_CIPHER_key_length(crypto->c) > (int)length) return HX509_CRYPTO_INTERNAL_ERROR; if (crypto->key.data) { free(crypto->key.data); crypto->key.data = NULL; crypto->key.length = 0; } crypto->key.data = malloc(length); if (crypto->key.data == NULL) return ENOMEM; memcpy(crypto->key.data, data, length); crypto->key.length = length; return 0; } int hx509_crypto_set_random_key(hx509_crypto crypto, heim_octet_string *key) { if (crypto->key.data) { free(crypto->key.data); crypto->key.length = 0; } crypto->key.length = EVP_CIPHER_key_length(crypto->c); crypto->key.data = malloc(crypto->key.length); if (crypto->key.data == NULL) { crypto->key.length = 0; return ENOMEM; } if (RAND_bytes(crypto->key.data, crypto->key.length) <= 0) { free(crypto->key.data); crypto->key.data = NULL; crypto->key.length = 0; return HX509_CRYPTO_INTERNAL_ERROR; } if (key) return der_copy_octet_string(&crypto->key, key); else return 0; } int hx509_crypto_set_params(hx509_context context, hx509_crypto crypto, const heim_octet_string *param, heim_octet_string *ivec) { return (*crypto->cipher->set_params)(context, param, crypto, ivec); } int hx509_crypto_get_params(hx509_context context, hx509_crypto crypto, const heim_octet_string *ivec, heim_octet_string *param) { return (*crypto->cipher->get_params)(context, crypto, ivec, param); } int hx509_crypto_random_iv(hx509_crypto crypto, heim_octet_string *ivec) { ivec->length = EVP_CIPHER_iv_length(crypto->c); ivec->data = malloc(ivec->length); if (ivec->data == NULL) { ivec->length = 0; return ENOMEM; } if (RAND_bytes(ivec->data, ivec->length) <= 0) { free(ivec->data); ivec->data = NULL; ivec->length = 0; return HX509_CRYPTO_INTERNAL_ERROR; } return 0; } int hx509_crypto_encrypt(hx509_crypto crypto, const void *data, const size_t length, const heim_octet_string *ivec, heim_octet_string **ciphertext) { EVP_CIPHER_CTX evp; size_t padsize, bsize; int ret; *ciphertext = NULL; if ((crypto->cipher->flags & CIPHER_WEAK) && (crypto->flags & ALLOW_WEAK) == 0) return HX509_CRYPTO_ALGORITHM_BEST_BEFORE; assert(EVP_CIPHER_iv_length(crypto->c) == (int)ivec->length); EVP_CIPHER_CTX_init(&evp); ret = EVP_CipherInit_ex(&evp, crypto->c, NULL, crypto->key.data, ivec->data, 1); if (ret != 1) { EVP_CIPHER_CTX_cleanup(&evp); ret = HX509_CRYPTO_INTERNAL_ERROR; goto out; } *ciphertext = calloc(1, sizeof(**ciphertext)); if (*ciphertext == NULL) { ret = ENOMEM; goto out; } assert(crypto->flags & PADDING_FLAGS); bsize = EVP_CIPHER_block_size(crypto->c); padsize = 0; if (crypto->flags & PADDING_NONE) { if (bsize != 1 && (length % bsize) != 0) return HX509_CMS_PADDING_ERROR; } else if (crypto->flags & PADDING_PKCS7) { if (bsize != 1) padsize = bsize - (length % bsize); } (*ciphertext)->length = length + padsize; (*ciphertext)->data = malloc(length + padsize); if ((*ciphertext)->data == NULL) { ret = ENOMEM; goto out; } memcpy((*ciphertext)->data, data, length); if (padsize) { size_t i; unsigned char *p = (*ciphertext)->data; p += length; for (i = 0; i < padsize; i++) *p++ = padsize; } ret = EVP_Cipher(&evp, (*ciphertext)->data, (*ciphertext)->data, length + padsize); if (ret != 1) { ret = HX509_CRYPTO_INTERNAL_ERROR; goto out; } ret = 0; out: if (ret) { if (*ciphertext) { if ((*ciphertext)->data) { free((*ciphertext)->data); } free(*ciphertext); *ciphertext = NULL; } } EVP_CIPHER_CTX_cleanup(&evp); return ret; } int hx509_crypto_decrypt(hx509_crypto crypto, const void *data, const size_t length, heim_octet_string *ivec, heim_octet_string *clear) { EVP_CIPHER_CTX evp; void *idata = NULL; int ret; clear->data = NULL; clear->length = 0; if ((crypto->cipher->flags & CIPHER_WEAK) && (crypto->flags & ALLOW_WEAK) == 0) return HX509_CRYPTO_ALGORITHM_BEST_BEFORE; if (ivec && EVP_CIPHER_iv_length(crypto->c) < (int)ivec->length) return HX509_CRYPTO_INTERNAL_ERROR; if (crypto->key.data == NULL) return HX509_CRYPTO_INTERNAL_ERROR; if (ivec) idata = ivec->data; EVP_CIPHER_CTX_init(&evp); ret = EVP_CipherInit_ex(&evp, crypto->c, NULL, crypto->key.data, idata, 0); if (ret != 1) { EVP_CIPHER_CTX_cleanup(&evp); return HX509_CRYPTO_INTERNAL_ERROR; } clear->length = length; clear->data = malloc(length); if (clear->data == NULL) { EVP_CIPHER_CTX_cleanup(&evp); clear->length = 0; return ENOMEM; } if (EVP_Cipher(&evp, clear->data, data, length) != 1) { return HX509_CRYPTO_INTERNAL_ERROR; } EVP_CIPHER_CTX_cleanup(&evp); if ((crypto->flags & PADDING_PKCS7) && EVP_CIPHER_block_size(crypto->c) > 1) { int padsize; unsigned char *p; int j, bsize = EVP_CIPHER_block_size(crypto->c); if ((int)clear->length < bsize) { ret = HX509_CMS_PADDING_ERROR; goto out; } p = clear->data; p += clear->length - 1; padsize = *p; if (padsize > bsize) { ret = HX509_CMS_PADDING_ERROR; goto out; } clear->length -= padsize; for (j = 0; j < padsize; j++) { if (*p-- != padsize) { ret = HX509_CMS_PADDING_ERROR; goto out; } } } return 0; out: if (clear->data) free(clear->data); clear->data = NULL; clear->length = 0; return ret; } typedef int (*PBE_string2key_func)(hx509_context, const char *, const heim_octet_string *, hx509_crypto *, heim_octet_string *, heim_octet_string *, const heim_oid *, const EVP_MD *); static int PBE_string2key(hx509_context context, const char *password, const heim_octet_string *parameters, hx509_crypto *crypto, heim_octet_string *key, heim_octet_string *iv, const heim_oid *enc_oid, const EVP_MD *md) { PKCS12_PBEParams p12params; int passwordlen; hx509_crypto c; int iter, saltlen, ret; unsigned char *salt; passwordlen = password ? strlen(password) : 0; if (parameters == NULL) return HX509_ALG_NOT_SUPP; ret = decode_PKCS12_PBEParams(parameters->data, parameters->length, &p12params, NULL); if (ret) goto out; if (p12params.iterations) iter = *p12params.iterations; else iter = 1; salt = p12params.salt.data; saltlen = p12params.salt.length; if (!PKCS12_key_gen (password, passwordlen, salt, saltlen, PKCS12_KEY_ID, iter, key->length, key->data, md)) { ret = HX509_CRYPTO_INTERNAL_ERROR; goto out; } if (!PKCS12_key_gen (password, passwordlen, salt, saltlen, PKCS12_IV_ID, iter, iv->length, iv->data, md)) { ret = HX509_CRYPTO_INTERNAL_ERROR; goto out; } ret = hx509_crypto_init(context, NULL, enc_oid, &c); if (ret) goto out; hx509_crypto_allow_weak(c); ret = hx509_crypto_set_key_data(c, key->data, key->length); if (ret) { hx509_crypto_destroy(c); goto out; } *crypto = c; out: free_PKCS12_PBEParams(&p12params); return ret; } static const heim_oid * find_string2key(const heim_oid *oid, const EVP_CIPHER **c, const EVP_MD **md, PBE_string2key_func *s2k) { if (der_heim_oid_cmp(oid, ASN1_OID_ID_PBEWITHSHAAND40BITRC2_CBC) == 0) { *c = EVP_rc2_40_cbc(); if (*c == NULL) return NULL; *md = EVP_sha1(); if (*md == NULL) return NULL; *s2k = PBE_string2key; return &asn1_oid_private_rc2_40; } else if (der_heim_oid_cmp(oid, ASN1_OID_ID_PBEWITHSHAAND128BITRC2_CBC) == 0) { *c = EVP_rc2_cbc(); if (*c == NULL) return NULL; *md = EVP_sha1(); if (*md == NULL) return NULL; *s2k = PBE_string2key; return ASN1_OID_ID_PKCS3_RC2_CBC; #if 0 } else if (der_heim_oid_cmp(oid, ASN1_OID_ID_PBEWITHSHAAND40BITRC4) == 0) { *c = EVP_rc4_40(); if (*c == NULL) return NULL; *md = EVP_sha1(); if (*md == NULL) return NULL; *s2k = PBE_string2key; return NULL; } else if (der_heim_oid_cmp(oid, ASN1_OID_ID_PBEWITHSHAAND128BITRC4) == 0) { *c = EVP_rc4(); if (*c == NULL) return NULL; *md = EVP_sha1(); if (*md == NULL) return NULL; *s2k = PBE_string2key; return ASN1_OID_ID_PKCS3_RC4; #endif } else if (der_heim_oid_cmp(oid, ASN1_OID_ID_PBEWITHSHAAND3_KEYTRIPLEDES_CBC) == 0) { *c = EVP_des_ede3_cbc(); if (*c == NULL) return NULL; *md = EVP_sha1(); if (*md == NULL) return NULL; *s2k = PBE_string2key; return ASN1_OID_ID_PKCS3_DES_EDE3_CBC; } return NULL; } /* * */ int _hx509_pbe_encrypt(hx509_context context, hx509_lock lock, const AlgorithmIdentifier *ai, const heim_octet_string *content, heim_octet_string *econtent) { hx509_clear_error_string(context); return EINVAL; } /* * */ int _hx509_pbe_decrypt(hx509_context context, hx509_lock lock, const AlgorithmIdentifier *ai, const heim_octet_string *econtent, heim_octet_string *content) { const struct _hx509_password *pw; heim_octet_string key, iv; const heim_oid *enc_oid; const EVP_CIPHER *c; const EVP_MD *md; PBE_string2key_func s2k; int ret = 0; size_t i; memset(&key, 0, sizeof(key)); memset(&iv, 0, sizeof(iv)); memset(content, 0, sizeof(*content)); enc_oid = find_string2key(&ai->algorithm, &c, &md, &s2k); if (enc_oid == NULL) { hx509_set_error_string(context, 0, HX509_ALG_NOT_SUPP, "String to key algorithm not supported"); ret = HX509_ALG_NOT_SUPP; goto out; } key.length = EVP_CIPHER_key_length(c); key.data = malloc(key.length); if (key.data == NULL) { ret = ENOMEM; hx509_clear_error_string(context); goto out; } iv.length = EVP_CIPHER_iv_length(c); iv.data = malloc(iv.length); if (iv.data == NULL) { ret = ENOMEM; hx509_clear_error_string(context); goto out; } pw = _hx509_lock_get_passwords(lock); ret = HX509_CRYPTO_INTERNAL_ERROR; for (i = 0; i < pw->len + 1; i++) { hx509_crypto crypto; const char *password; if (i < pw->len) password = pw->val[i]; else if (i < pw->len + 1) password = ""; else password = NULL; ret = (*s2k)(context, password, ai->parameters, &crypto, &key, &iv, enc_oid, md); if (ret) goto out; ret = hx509_crypto_decrypt(crypto, econtent->data, econtent->length, &iv, content); hx509_crypto_destroy(crypto); if (ret == 0) goto out; } out: if (key.data) der_free_octet_string(&key); if (iv.data) der_free_octet_string(&iv); return ret; } /* * */ static int match_keys_rsa(hx509_cert c, hx509_private_key private_key) { const Certificate *cert; const SubjectPublicKeyInfo *spi; RSAPublicKey pk; RSA *rsa; size_t size; int ret; if (private_key->private_key.rsa == NULL) return 0; rsa = private_key->private_key.rsa; if (rsa->d == NULL || rsa->p == NULL || rsa->q == NULL) return 0; cert = _hx509_get_cert(c); spi = &cert->tbsCertificate.subjectPublicKeyInfo; rsa = RSA_new(); if (rsa == NULL) return 0; ret = decode_RSAPublicKey(spi->subjectPublicKey.data, spi->subjectPublicKey.length / 8, &pk, &size); if (ret) { RSA_free(rsa); return 0; } rsa->n = heim_int2BN(&pk.modulus); rsa->e = heim_int2BN(&pk.publicExponent); free_RSAPublicKey(&pk); rsa->d = BN_dup(private_key->private_key.rsa->d); rsa->p = BN_dup(private_key->private_key.rsa->p); rsa->q = BN_dup(private_key->private_key.rsa->q); rsa->dmp1 = BN_dup(private_key->private_key.rsa->dmp1); rsa->dmq1 = BN_dup(private_key->private_key.rsa->dmq1); rsa->iqmp = BN_dup(private_key->private_key.rsa->iqmp); if (rsa->n == NULL || rsa->e == NULL || rsa->d == NULL || rsa->p == NULL|| rsa->q == NULL || rsa->dmp1 == NULL || rsa->dmq1 == NULL) { RSA_free(rsa); return 0; } ret = RSA_check_key(rsa); RSA_free(rsa); return ret == 1; } static int match_keys_ec(hx509_cert c, hx509_private_key private_key) { return 1; /* XXX use EC_KEY_check_key */ } int _hx509_match_keys(hx509_cert c, hx509_private_key key) { if (!key->ops) return 0; if (der_heim_oid_cmp(key->ops->key_oid, ASN1_OID_ID_PKCS1_RSAENCRYPTION) == 0) return match_keys_rsa(c, key); if (der_heim_oid_cmp(key->ops->key_oid, ASN1_OID_ID_ECPUBLICKEY) == 0) return match_keys_ec(c, key); return 0; } static const heim_oid * find_keytype(const hx509_private_key key) { const struct signature_alg *md; if (key == NULL) return NULL; md = _hx509_find_sig_alg(key->signature_alg); if (md == NULL) return NULL; return md->key_oid; } int hx509_crypto_select(const hx509_context context, int type, const hx509_private_key source, hx509_peer_info peer, AlgorithmIdentifier *selected) { const AlgorithmIdentifier *def = NULL; size_t i, j; int ret, bits; memset(selected, 0, sizeof(*selected)); if (type == HX509_SELECT_DIGEST) { bits = SIG_DIGEST; if (source) def = alg_for_privatekey(source, type); if (def == NULL) def = _hx509_crypto_default_digest_alg; } else if (type == HX509_SELECT_PUBLIC_SIG) { bits = SIG_PUBLIC_SIG; /* XXX depend on `source´ and `peer´ */ if (source) def = alg_for_privatekey(source, type); if (def == NULL) def = _hx509_crypto_default_sig_alg; } else if (type == HX509_SELECT_SECRET_ENC) { bits = SIG_SECRET; def = _hx509_crypto_default_secret_alg; } else { hx509_set_error_string(context, 0, EINVAL, "Unknown type %d of selection", type); return EINVAL; } if (peer) { const heim_oid *keytype = NULL; keytype = find_keytype(source); for (i = 0; i < peer->len; i++) { for (j = 0; sig_algs[j]; j++) { if ((sig_algs[j]->flags & bits) != bits) continue; if (der_heim_oid_cmp(sig_algs[j]->sig_oid, &peer->val[i].algorithm) != 0) continue; if (keytype && sig_algs[j]->key_oid && der_heim_oid_cmp(keytype, sig_algs[j]->key_oid)) continue; /* found one, use that */ ret = copy_AlgorithmIdentifier(&peer->val[i], selected); if (ret) hx509_clear_error_string(context); return ret; } if (bits & SIG_SECRET) { const struct hx509cipher *cipher; cipher = find_cipher_by_oid(&peer->val[i].algorithm); if (cipher == NULL) continue; if (cipher->ai_func == NULL) continue; ret = copy_AlgorithmIdentifier(cipher->ai_func(), selected); if (ret) hx509_clear_error_string(context); return ret; } } } /* use default */ ret = copy_AlgorithmIdentifier(def, selected); if (ret) hx509_clear_error_string(context); return ret; } int hx509_crypto_available(hx509_context context, int type, hx509_cert source, AlgorithmIdentifier **val, unsigned int *plen) { const heim_oid *keytype = NULL; unsigned int len, i; void *ptr; int bits, ret; *val = NULL; if (type == HX509_SELECT_ALL) { bits = SIG_DIGEST | SIG_PUBLIC_SIG | SIG_SECRET; } else if (type == HX509_SELECT_DIGEST) { bits = SIG_DIGEST; } else if (type == HX509_SELECT_PUBLIC_SIG) { bits = SIG_PUBLIC_SIG; } else { hx509_set_error_string(context, 0, EINVAL, "Unknown type %d of available", type); return EINVAL; } if (source) keytype = find_keytype(_hx509_cert_private_key(source)); len = 0; for (i = 0; sig_algs[i]; i++) { if ((sig_algs[i]->flags & bits) == 0) continue; if (sig_algs[i]->sig_alg == NULL) continue; if (keytype && sig_algs[i]->key_oid && der_heim_oid_cmp(sig_algs[i]->key_oid, keytype)) continue; /* found one, add that to the list */ ptr = realloc(*val, sizeof(**val) * (len + 1)); if (ptr == NULL) goto out; *val = ptr; ret = copy_AlgorithmIdentifier(sig_algs[i]->sig_alg, &(*val)[len]); if (ret) goto out; len++; } /* Add AES */ if (bits & SIG_SECRET) { for (i = 0; i < sizeof(ciphers)/sizeof(ciphers[0]); i++) { if (ciphers[i].flags & CIPHER_WEAK) continue; if (ciphers[i].ai_func == NULL) continue; ptr = realloc(*val, sizeof(**val) * (len + 1)); if (ptr == NULL) goto out; *val = ptr; ret = copy_AlgorithmIdentifier((ciphers[i].ai_func)(), &(*val)[len]); if (ret) goto out; len++; } } *plen = len; return 0; out: for (i = 0; i < len; i++) free_AlgorithmIdentifier(&(*val)[i]); free(*val); *val = NULL; hx509_set_error_string(context, 0, ENOMEM, "out of memory"); return ENOMEM; } void hx509_crypto_free_algs(AlgorithmIdentifier *val, unsigned int len) { unsigned int i; for (i = 0; i < len; i++) free_AlgorithmIdentifier(&val[i]); free(val); } heimdal-7.5.0/lib/hx509/data/0000755000175000017500000000000013214604041013601 5ustar niknikheimdal-7.5.0/lib/hx509/data/eccurve.pem0000644000175000017500000000011312136107750015742 0ustar niknik-----BEGIN EC PARAMETERS----- BggqhkjOPQMBBw== -----END EC PARAMETERS----- heimdal-7.5.0/lib/hx509/data/ocsp-req1.der0000644000175000017500000000015112136107750016113 0ustar niknik0g0e0>0<0:0 +ڍ+f|-%-ynHܿL0'Yh#0!0 +0ƒ0T<~heimdal-7.5.0/lib/hx509/data/ocsp-resp1-keyhash.der0000644000175000017500000000160412136107750017733 0ustar niknik0 y0u +0f0b0/?5r\QRO_ V/ 20090426202941Z0Q0O0:0 +ڍ+f|-%-ynHܿL0'Yh20090426202941Z#0!0 +0ƒ0T<~0  *H -6~.3AJ_ B74\&xsTFsu:Dy3].Rѣ0d]qmGomu,"oAR_2X&Z;p'0#000  *H 0*10U hx509 Test Root CA1 0 USE0 090426202940Z 190424202940Z0&1 0 USE10U OCSP responder00  *H 08^sW+ W<S( 7-v6\k]"|枂ٗ<{tSn&?*gއGvĿ\, 6-eAG4TE8v?I@qY0W0 U00 U0U%0 +0+ 0U/?5r\QRO_ V/ 0  *H $XMN MK7(y(EJ udc*D4t-HbXiZ=~X9qvlW%zpP  ֊heimdal-7.5.0/lib/hx509/data/PKITS_data.zip0000644000175000017500001014522012136107747016232 0ustar niknikPK aJ/ certpairs/UT ن?;7AUxPK[J/{07certpairs/anyPolicyCACertforwardcrossCertificatePair.cpUT І?;7AUx3hbjY`Tct3#/VGw^FFVVCnN6P6a`C) KX0$D9$3-39$P@$,RT tK/2504014415725DgCb^e@~NfrA|dW320724v2562H|Tbg%_ϚI=h/`E c:IvThk2AXvnX!32v¥;kO_\:Sk@t2 R= Nh>O¿upu e_Gw]溜yoeWjhPK[J/+707certpairs/anyPolicyCACertreversecrossCertificatePair.cpUT І?;7AUx3hbjY`Tct3#/VGw^FFVVCnN6P6a`C) KX0$D9$3-39$P@$,RT tK/2504014415725DgCb^e@~NfrA|dW320724v2562H|Tbg%_ϚI=h/`E c:IvThk2AXvnX!32v¥;kO_\:Sk@t2 R= Nh>O¿upu e_Gw]溜yoeWjhPK[J/ݍ<>certpairs/BadCRLIssuerNameCACertforwardcrossCertificatePair.cpUT І?;7AUx3hbjY`Tct3##/VGw^FFVVCnN6P6a`C) KX0$D9$3-39$P@$,RT tK/2504014415725Dxo,1 "TgGgde`ne0hdjldrXႥq[)hCCn^\\sfk/M4e_&*/*bk(ϻ##lFg 0w-lΪv-hvz\d'o+YړɓιARREexϐqqA<,b "s6;^5wͫY{{REE[/,1t4sσt>4?#` ,|certpairs/BadCRLIssuerNameCACertreversecrossCertificatePair.cpUT І?;7AUx3hbjY`Tct3##/VGw^FFVVCnN6P6a`C) KX0$D9$3-39$P@$,RT tK/2504014415725Dxo,1 "TgGgde`ne0hdjldrXႥq[)hCCn^\\sfk/M4e_&*/*bk(ϻ##lFg 0w-lΪv-hvz\d'o+YړɓιARREexϐqqA<,b "s6;^5wͫY{{REE[/,1t4sσt>4?#` ,|certpairs/BadnotBeforeDateCACertforwardcrossCertificatePair.cpUT І?;7AUx3hbj^ToTmd3##/VGw^FFVVCnN6P6a`C) KX0$D9$3-39$P@$,RT tK/251704044Q@%x d 6:%(8*e #;'m<>O{H駮ĽjO-^*rƙi{1-&yb.T,noCK?/mx'!eG++Z;c.Ê *;96,;'bPK[J/fX@6>certpairs/BadnotBeforeDateCACertreversecrossCertificatePair.cpUT І?;7AUx3hbj^ToTmd3##/VGw^FFVVCnN6P6a`C) KX0$D9$3-39$P@$,RT tK/251704044Q@%x d 6:%(8*e #;'m<>O{H駮ĽjO-^*rƙi{1-&yb.T,noCK?/mx'!eG++Z;c.Ê *;96,;'bPK[J/6#07certpairs/BadSignedCACertforwardcrossCertificatePair.cpUT І?;7AUx3hb^TnTlxg3##/VGw^FFVVCnN6P6a`C) KX0$D9$3-39$P@$,RT tK/2504014415725D8o^gGfde`ne0hdjldOAZL;7 `6z1NA-d>.eQxtF)g-Xsi]ƍ_mR1lׄsk}ϯ0B9BOK{gO3b!*7fs%6Q׿Ľ k nUf0ksEq)yl^,HttnJq͙!À$Yl WBc*P܀р$! Rj *B ʷ {S?п"ޛCdxЛ߶#ා按Bvj_o-㫵{ .uT1uYj[.m3 ffN^cF=Ea.B&PK[J/Xsc07certpairs/BadSignedCACertreversecrossCertificatePair.cpUT І?;7AUx3hb^TnTlxg3##/VGw^FFVVCnN6P6a`C) KX0$D9$3-39$P@$,RT tK/2504014415725D8o^gGfde`ne0hdjldOAZL;7 `6z1NA-d>.eQxtF)g-Xsi]ƍ_mR1lׄsk}ϯ0B9BOK{gO3b!*7fs%6Q׿Ľ k nUf0ksEq)yl^,HttnJq͙!À$Yl WBc*P܀р$! Rj *B ʷ {S?п"ޛCdxЛ߶#ා按Bvj_o-㫵{ .uT1uYj[.m3 ffN^cF=Ea.B&PK[J/۾JGMcertpairs/basicConstraintsCriticalcAFalseCACertforwardcrossCertificatePair.cpUT І?;7AUx3hbǠàf&F&&Fq^6N6, l̡,lLR `HjqsjQIfZfrbIj0HY'(阗_d 'k`h`bhihbjnd%k5$= Iřy%Ey% E%@U9 Ɏ n9ũ Ύ`Ȱ)KfOGձ)%4U(bnf̅IG"4-?DKjõ%Qu減5.w}&&rmBuvEhRY2vO{y_a>[;>gbfd`\\iPn 2X+NW`j֞ dA XXD(5N5e·K%#@W`03aJh`L0y@ aB&fɌ=y-qYm/AJi;~kYke\kƩ%-gL5V PK[J/P&,GMcertpairs/basicConstraintsCriticalcAFalseCACertreversecrossCertificatePair.cpUT І?;7AUx3hbǠàf&F&&Fq^6N6, l̡,lLR `HjqsjQIfZfrbIj0HY'(阗_d 'k`h`bhihbjnd%k5$= Iřy%Ey% E%@U9 Ɏ n9ũ Ύ`Ȱ)KfOGձ)%4U(bnf̅IG"4-?DKjõ%Qu減5.w}&&rmBuvEhRY2vO{y_a>[;>gbfd`\\iPn 2X+NW`j֞ dA XXD(5N5e·K%#@W`03aJh`L0y@ aB&fɌ=y-qYm/AJi;~kYke\kƩ%-gL5V PK[J/BIcertpairs/basicConstraintsNotCriticalCACertforwardcrossCertificatePair.cpUT І?;7AUx3hb^nlf3#/VGw^FFVVCnN6P6a`C) KX0$D9$3-39$P@$,RT tK/2504014415725Do:d⒢̼b|ڢgG>ade`ne0hdjldٹ;K{?^fw~jf_Эl+w2-3 yKw6`.xꩵSWkEv\e`ڑ|)b9Y&2?xySe7JYۣ .9Ya7U֌L&fFŕ@*H5ι8z< 6fi@EEƎDx];cWs~"H? 0 A|>66T#fa5`*Fcf`p-lnZ(fow kɳ~:q i-c K{rNn 0[zc?+;i_J?b]g%Nfgg> lPK[J/BIcertpairs/basicConstraintsNotCriticalCACertreversecrossCertificatePair.cpUT І?;7AUx3hb^nlf3#/VGw^FFVVCnN6P6a`C) KX0$D9$3-39$P@$,RT tK/2504014415725Do:d⒢̼b|ڢgG>ade`ne0hdjldٹ;K{?^fw~jf_Эl+w2-3 yKw6`.xꩵSWkEv\e`ڑ|)b9Y&2?xySe7JYۣ .9Ya7U֌L&fFŕ@*H5ι8z< 6fi@EEƎDx];cWs~"H? 0 A|>66T#fa5`*Fcf`p-lnZ(fow kɳ~:q i-c K{rNn 0[zc?+;i_J?b]g%Nfgg> lPK[J/.dJPcertpairs/basicConstraintsNotCriticalcAFalseCACertforwardcrossCertificatePair.cpUT І?;7AUx3hbנӠf&F&&F ^6N6, l̡,lLR `HjqsjQIfZfrbIj0HY'(阗_d 'k`h`bhihbjnd%k5%# Iřy%Ey% ~@E%@9 Ɏ n9ũ Ύ`Ȱ}֛S>ypdyVozs;cy=mys9˼5ߢnΡ7ڲ<(j@' ν+5&6b^v\>|y5?`{K߫Twy,%PK[J/bJPcertpairs/basicConstraintsNotCriticalcAFalseCACertreversecrossCertificatePair.cpUT І?;7AUx3hbנӠf&F&&F ^6N6, l̡,lLR `HjqsjQIfZfrbIj0HY'(阗_d 'k`h`bhihbjnd%k5%# Iřy%Ey% ~@E%@9 Ɏ n9ũ Ύ`Ȱ}֛S>ypdyVozs;cy=mys9˼5ߢnΡ7ڲ<(j@' ν+5&6b^v\>|y5?`{K߫Twy,%PK[J/HJcertpairs/BasicSelfIssuedCRLSigningKeyCACertforwardcrossCertificatePair.cpUT І?;7AUx3hbϠˠf&F&&FQ^6N6, l̡,lLR `HjqsjQIfZfrbIj0HY'(阗_d 'k`h`bhihbjnd%k5 ]m *Nř 9iť) A> yy ީ Ύ}`0/FA1sQlsI!Q ZkNej\yw*5+.ȭe]$_?FjKO Ou_ 4p\hr'МϞXegj5S9vbR7Yu]To*Ơ@%Ye 9WtRǻլ==_Ȃ𱈱x&=a'זM*hgdC6q_Eπ+̓1(nh)d5`RhQ њ3zҺU_D>z~OrgiGzj!fu'Fwxʟ6 yy ީ Ύ}`0/FA1sQlsI!Q ZkNej\yw*5+.ȭe]$_?FjKO Ou_ 4p\hr'МϞXegj5S9vbR7Yu]To*Ơ@%Ye 9WtRǻլ==_Ȃ𱈱x&=a'זM*hgdC6q_Eπ+̓1(nh)d5`RhQ њ3zҺU_D>z~OrgiGzj!fu'Fwxʟ6^s-x]RgA+BN(g歓gм~Ωf:~yfMGT4V?bd+m_1;r8Cr={%Vh@W`03aJh`L0$A Y Z3CeBvsʝc]wĦb[SRZЧK 7Sf -76_rxzFܓ̈<3[VOyp?BׄF}~_aþ8# urffKνzpOdPK[J/ݰBCcertpairs/BasicSelfIssuedNewKeyCACertreversecrossCertificatePair.cpUT І?;7AUx3hbZfdz3#/VGw^FFVVCnN6P6a`C) KX0$D9$3-39$P@$,RT tK/2504014415725Do2dԜ4]rJgGȾ`de`ne0hdjldآiԴGSU>^s-x]RgA+BN(g歓gм~Ωf:~yfMGT4V?bd+m_1;r8Cr={%Vh@W`03aJh`L0$A Y Z3CeBvsʝc]wĦb[SRZЧK 7Sf -76_rxzFܓ̈<3[VOyp?BׄF}~_aþ8# urffKνzpOdPK[J/Y@Ccertpairs/BasicSelfIssuedOldKeyCACertforwardcrossCertificatePair.cpUT І?;7AUx3hbZfdz3#/VGw^FFVVCnN6P6a`C) KX0$D9$3-39$P@$,RT tK/2504014415725Do2dԜ4]JgGȾ`de`ne0hdjldX}pv?ݫaz̧=+39ŸJGa{=n;nߔ+esh׏=o2RqjHSFPĢъvkGφ={w៫oehwM/^`ck\a K_PZA]ߊ ƁNsG%ֽ;B YPK[J/'@Ccertpairs/BasicSelfIssuedOldKeyCACertreversecrossCertificatePair.cpUT І?;7AUx3hbZfdz3#/VGw^FFVVCnN6P6a`C) KX0$D9$3-39$P@$,RT tK/2504014415725Do2dԜ4]JgGȾ`de`ne0hdjldX}pv?ݫaz̧=+39ŸJGa{=n;nߔ+esh׏=o2RqjHSFPĢъvkGφ={w៫oehwM/^`ck\a K_PZA]ߊ ƁNsG%ֽ;B YPK[J/L(~7certpairs/deltaCRLCA1CertforwardcrossCertificatePair.cpUT І?;7AUx3hbZTfTdx{3#c/VGw^FFVVCnN6P6a`C) KX0$D9$3-39$P@$,RT tK/2504014415725DgCJjNIsA|dW320724v2562Lc̗&,U!u)M示5mXb[^`V]~+<vSƊ n4-ޜMVȋwm=?#=a|lmZ:J2M/+;KqqA<,b "s6;^5wͫY{{2)ccuu kvI^{ր$Wl WBc*P܀р$! Rj Т*3?ht#J̍ V:!.hѓϧ4UEĀSwL)1aQZLog=l=-I{P{FZ_j+V:CTpK~]ωo|PK[J/0\(~7certpairs/deltaCRLCA1CertreversecrossCertificatePair.cpUT І?;7AUx3hbZTfTdx{3#c/VGw^FFVVCnN6P6a`C) KX0$D9$3-39$P@$,RT tK/2504014415725DgCJjNIsA|dW320724v2562Lc̗&,U!u)M示5mXb[^`V]~+<vSƊ n4-ޜMVȋwm=?#=a|lmZ:J2M/+;KqqA<,b "s6;^5wͫY{{2)ccuu kvI^{ր$Wl WBc*P܀р$! Rj Т*3?ht#J̍ V:!.hѓϧ4UEĀSwL)1aQZLog=l=-I{P{FZ_j+V:CTpK~]ωo|PK[J/Xc)~7certpairs/deltaCRLCA2CertforwardcrossCertificatePair.cpUT І?;7AUx3hbZTfTdx{3#c/VGw^FFVVCnN6P6a`C) KX0$D9$3-39$P@$,RT tK/2504014415725DgCJjNIsA|dW320724v2562qT3x |bUe!6ZNo]);#_yE+-`Z,W͠zmwQ!ɾ-ߧ/}9'jӳV21320.12:]VE@Awyԫny5kOW |,b,"'OS-Ӝx֟>gn>4?#`\ ,|+GvU;<{zW6祼?so=};Aq/fmPK[J/j$R)~7certpairs/deltaCRLCA2CertreversecrossCertificatePair.cpUT І?;7AUx3hbZTfTdx{3#c/VGw^FFVVCnN6P6a`C) KX0$D9$3-39$P@$,RT tK/2504014415725DgCJjNIsA|dW320724v2562qT3x |bUe!6ZNo]);#_yE+-`Z,W͠zmwQ!ɾ-ߧ/}9'jӳV21320.12:]VE@Awyԫny5kOW |,b,"'OS-Ӝx֟>gn>4?#`\ ,|+GvU;<{zW6祼?so=};Aq/fmPK[J/h)~7certpairs/deltaCRLCA3CertforwardcrossCertificatePair.cpUT І?;7AUx3hbZTfTdx{3#c/VGw^FFVVCnN6P6a`C) KX0$D9$3-39$P@$,RT tK/2504014415725DgCJjNIsA|dW320724v2562lݟ|}K!=51PS 7ҋ_fZtW˘ӷYRg}/.DZez>{rBf˓ɵgeuU$o4-Xwp]~]/'V&>椵$qqA<,b "s6;^5wͫY{{2)ccy$õƱJaw+kgd+6q_Eπ+̓1(nh)d5`RhQ Go?^nE.2O\+':΅wlgJ9' hPizTssRg6HrW9.'Yp buӊhD܉Xgҩl\5?T83PK[J/ )~7certpairs/deltaCRLCA3CertreversecrossCertificatePair.cpUT І?;7AUx3hbZTfTdx{3#c/VGw^FFVVCnN6P6a`C) KX0$D9$3-39$P@$,RT tK/2504014415725DgCJjNIsA|dW320724v2562lݟ|}K!=51PS 7ҋ_fZtW˘ӷYRg}/.DZez>{rBf˓ɵgeuU$o4-Xwp]~]/'V&>椵$qqA<,b "s6;^5wͫY{{2)ccy$õƱJaw+kgd+6q_Eπ+̓1(nh)d5`RhQ Go?^nE.2O\+':΅wlgJ9' hPizTssRg6HrW9.'Yp buӊhD܉Xgҩl\5?T83PK[J/ ~?Ecertpairs/deltaCRLIndicatorNoBaseCACertforwardcrossCertificatePair.cpUT І?;7AUx3hbZfdz3#c/VGw^FFVVCnN6P6a`C) KX0$D9$3-39$P@$,RT tK/2504014415725Do2ԜD ϼ\~_SbqA|d_020724v2562,clػBBrם?՛n2oe%Bcz:--/$=kݩbg3ynF3_x.PK[J/k?Ecertpairs/deltaCRLIndicatorNoBaseCACertreversecrossCertificatePair.cpUT І?;7AUx3hbZfdz3#c/VGw^FFVVCnN6P6a`C) KX0$D9$3-39$P@$,RT tK/2504014415725Do2ԜD ϼ\~_SbqA|d_020724v2562,clػBBrם?՛n2oe%Bcz:--/$=kݩbg3ynF3_x.PK[J/{E@certpairs/DifferentPoliciesTest7EEforwardcrossCertificatePair.cpUT І?;7AUx3hbZiA f]hƩߐۀ9M)4P@ I-.QpN-*LLN,I-6T1P1 Kd&g++&#`h 'k`h`bhihbjnd%k5&B=.iiEy% p]]+t4G#+sc/Ac'Sc#ê7B7= -]~AMKثo>Vz|WYױCYVA3ӂpGVN;x.q'LmyPK[J/;D@certpairs/DifferentPoliciesTest8EEreversecrossCertificatePair.cpUT І?;7AUx3hbZiA, f^hƩאۀ9M)4P@ I-.QpN-*LLN,I-6T2P1 Kd&g+)&ca8A8!2 x ֩d(-vuEVma8w ̍ L GfI^3">>Vz|WYױCYVA3ӂpGVN;x.q'LmyPK[J/F;@certpairs/distributionPoint1CACertforwardcrossCertificatePair.cpUT І?;7AUx3hbj^ToTmd3#/VGw^FFVVCnN6P6a`C) KX0$D9$3-39$P@$,RT tK/2504014415725Dxo H[X4%(3$3?/ ?3PѠq>Y{ ;^4X=eدC|lfDbfbfd`\\cPe 2X+NW`j֞ dA XXDgKxjAݮ/| i~F,,Hc3X xظ<S aBVf P9l9Mzlͬ+/"uwK-Rfyµ&pwݹm8v= ޲[ okFGaTXlG]7sD7寷x"dsPK[J/P9-;@certpairs/distributionPoint1CACertreversecrossCertificatePair.cpUT І?;7AUx3hbj^ToTmd3#/VGw^FFVVCnN6P6a`C) KX0$D9$3-39$P@$,RT tK/2504014415725Dxo H[X4%(3$3?/ ?3PѠq>Y{ ;^4X=eدC|lfDbfbfd`\\cPe 2X+NW`j֞ dA XXDgKxjAݮ/| i~F,,Hc3X xظ<S aBVf P9l9Mzlͬ+/"uwK-Rfyµ&pwݹm8v= ޲[ okFGaTXlG]7sD7寷x"dsPK[J//'<@certpairs/distributionPoint2CACertforwardcrossCertificatePair.cpUT І?;7AUx3hbj^ToTmd3#/VGw^FFVVCnN6P6a`C) KX0$D9$3-39$P@$,RT tK/2504014415725Dxo H[X4%(3$3?/ ?3HѠq>Y{ ;\3?2&ܷO[ZXk\tS%{^Do A= k5oypUX?6wʪ=qx遷\D}+>a$.-"N|2JͿUW]W{qqA<,b "s6;^5wͫY{{2)cc2f}\qeFmlϚ؝~| i~F,,Hc3X xظ<S aBVf P9 k_[I9Kr7{XqG띒'& il/{1X31t;{ub/.]gNSu'"gb{SYEo[<-=DPK[J/h9<@certpairs/distributionPoint2CACertreversecrossCertificatePair.cpUT І?;7AUx3hbj^ToTmd3#/VGw^FFVVCnN6P6a`C) KX0$D9$3-39$P@$,RT tK/2504014415725Dxo H[X4%(3$3?/ ?3HѠq>Y{ ;\3?2&ܷO[ZXk\tS%{^Do A= k5oypUX?6wʪ=qx遷\D}+>a$.-"N|2JͿUW]W{qqA<,b "s6;^5wͫY{{2)cc2f}\qeFmlϚ؝~| i~F,,Hc3X xظ<S aBVf P9 k_[I9Kr7{XqG띒'& il/{1X31t;{ub/.]gNSu'"gb{SYEo[<-=DPK[J/p CJcertpairs/GeneralizedTimeCRLnextUpdateCACertforwardcrossCertificatePair.cpUT І?;7AUx3hb]ijn3#/VGw^FFVVCnN6P6a`C) KX0$D9$3-39$P@$,RT tK/2504014415725DoyԼԢ̪ԔT ԊЂ:gGade`ne0hdjldXL]>}}D1XJqygg|p.SjfҥV*9>q wd][ djQrqkq?׳?ؐi|NUǹ&{(8bk)D4{*oHYl^OU*PK[J/NCJcertpairs/GeneralizedTimeCRLnextUpdateCACertreversecrossCertificatePair.cpUT І?;7AUx3hb]ijn3#/VGw^FFVVCnN6P6a`C) KX0$D9$3-39$P@$,RT tK/2504014415725DoyԼԢ̪ԔT ԊЂ:gGade`ne0hdjldXL]>}}D1XJqygg|p.SjfҥV*9>q wd][ djQrqkq?׳?ؐi|NUǹ&{(8bk)D4{*oHYl^OU*PK[J/C1*y2certpairs/GoodCACertforwardcrossCertificatePair.cpUT І?;7AUx3hb*]ThĔkxm3#qjy}eddee0p06dceaf 62qCRKSJ22KR E Ar[}5WԆxilxʜ9G]4O-K^DV4O~\bajEjuvN.sN/;lIo^q2?9?UIt6;G@N)PK[J/ˊ15certpairs/GoodsubCACertreversecrossCertificatePair.cpUT І?;7AUx3hbj^ToTmd3#/VGw^FFVVkCnN6P6a`C) KX0$D9$3-39$P$,h 'k`h`bhihbjnd%k5#paA\`ËK7Gv.#+sc/Ac'Sc#MHg54_0kk)^rW*%n ׫V]U 89cş/zYktkŪ/*tlO8ܩ8ZgV%"k;6=nѝ@l/GTy.V۠@tYe z˚N:gEuSD7)ccɬ{"t#^,?#`4 ,7aJh`L0$A Y P(502-30;~gqCq^>[}5WԆxilxʜ9G]4O-K^DV4O~\bajEjuvN.sN/;lIo^q2?9?UIt6;G@N)PK[J/W_Lcertpairs/GoodsubCAPanyPolicyMapping1to2CACertforwardcrossCertificatePair.cpUT І?;7AUx3hbڻiAV [(fƩڐۀ9M)4P@ I-.QpN-*LLN,I-601 (8;ȉZD"s ˆ7\@b$gGļʀJĂ̼tÒ|#`de`ne0hdjld8T[wVcٲ}OX Sߡ0K/ y/nLz"A-Vmoo)6ë˜e]E./\o"^i1!ij;\/=1y,_NaPVqA*ydY$ D-k:}Ğ.Mr@EEd[LqQ~Mjɳ-}l   `R)1/WBc*P#ɀNՀHT@FT Gߝe|WӎaKEgq..-X?cײַ_RW:Oߝٗ,j<}zgOitSYiN/_ᩙb=W3OgRT|PK[J/h_Lcertpairs/GoodsubCAPanyPolicyMapping1to2CACertreversecrossCertificatePair.cpUT І?;7AUx3hbڻiAV [(fƩڐۀ9M)4P@ I-.QpN-*LLN,I-601 (8;ȉZD"s ˆ7\@b$gGļʀJĂ̼tÒ|#`de`ne0hdjld8T[wVcٲ}OX Sߡ0K/ y/nLz"A-Vmoo)6ë˜e]E./\o"^i1!ij;\/=1y,_NaPVqA*ydY$ D-k:}Ğ.Mr@EEd[LqQ~Mjɳ-}l   `R)1/WBc*P#ɀNՀHT@FT Gߝe|WӎaKEgq..-X?cײַ_RW:Oߝٗ,j<}zgOitSYiN/_ᩙb=W3OgRT|PK[J/k-5:certpairs/indirectCRLCA1CertforwardcrossCertificatePair.cpUT І?;7AUx3hb]TiTjxo3#c/VGw^FFVVCnN6P6a`C) KX0$D9$3-39$P@$,RT tK/2504014415725D8o̢̼ gGCgde`ne0hdjld85)Ns* Y^v ؄y+_b@_%Ji4$1xڽ+OV,O&qIC;yO]vUE#S7yt'p21320.12^V9WtRǻլ==_Ȃ𱈱\Ad;U_@W`03aJh`L0$A Y Z2CElui't<%oƟ7-rũ)fX4Y095d䬩|y“Rsѧ}+ٻ mj9>7)٢{*Sd{܉)3a/PK[J/{ (75:certpairs/indirectCRLCA1CertreversecrossCertificatePair.cpUT І?;7AUx3hb]TiTjxo3#c/VGw^FFVVCnN6P6a`C) KX0$D9$3-39$P@$,RT tK/2504014415725D8o̢̼ gGCgde`ne0hdjld85)Ns* Y^v ؄y+_b@_%Ji4$1xڽ+OV,O&qIC;yO]vUE#S7yt'p21320.12^V9WtRǻլ==_Ȃ𱈱\Ad;U_@W`03aJh`L0$A Y Z2CElui't<%oƟ7-rũ)fX4Y095d䬩|y“Rsѧ}+ٻ mj9>7)٢{*Sd{܉)3a/PK[J/ʃ5:certpairs/indirectCRLCA2CertforwardcrossCertificatePair.cpUT І?;7AUx3hb]TiTjxo3#c/VGw^FFVVCnN6P6a`C) KX0$D9$3-39$P@$,RT tK/2504014415725D8o̢̼ gG#gde`ne0hdjld=Ś]4}?&;n}}5O!絑G~zG_Zndz96UoV.. S=а3_6޿vO<oem6ߝniMLnԩ[~s Ss9Ơ@zYe7D~\mwJjW|e R""rp} l":wvhgdb +q%y0рр$! Rj b*w.u>L,5:certpairs/indirectCRLCA2CertreversecrossCertificatePair.cpUT І?;7AUx3hb]TiTjxo3#c/VGw^FFVVCnN6P6a`C) KX0$D9$3-39$P@$,RT tK/2504014415725D8o̢̼ gG#gde`ne0hdjld=Ś]4}?&;n}}5O!絑G~zG_Zndz96UoV.. S=а3_6޿vO<oem6ߝniMLnԩ[~s Ss9Ơ@zYe7D~\mwJjW|e R""rp} l":wvhgdb +q%y0рр$! Rj b*w.u>L,Y{ ;f\nWU}]3Ïw>y{T'ο.nR]QX#2V= =Nͫ\՛siU݅1{AA~ Knİ5O3,N[93#*yeYhsEq)yl^,H4=FO;~t:^k@W`03aJh`L0$A Y Z2C<˃lM&O9)!_Xl˖% )̞Ŕ>G$Gxt9vo|RB|9vMAxU'?_1_{ e?zlή?PK[J/%x6:certpairs/indirectCRLCA3CertreversecrossCertificatePair.cpUT І?;7AUx3hb]TiTjxo3#c/VGw^FFVVCnN6P6a`C) KX0$D9$3-39$P@$,RT tK/2504014415725D8oH[?3/%(59Gؠq>Y{ ;f\nWU}]3Ïw>y{T'ο.nR]QX#2V= =Nͫ\՛siU݅1{AA~ Knİ5O3,N[93#*yeYhsEq)yl^,H4=FO;~t:^k@W`03aJh`L0$A Y Z2C<˃lM&O9)!_Xl˖% )̞Ŕ>G$Gxt9vo|RB|9vMAxU'?_1_{ e?zlή?PK[J/CC8:certpairs/indirectCRLCA4CertforwardcrossCertificatePair.cpUT І?;7AUx3hb]TiTjxo3#c/VGw^FFVVCnN6P6a`C) KX0$D9$3-39$P@$,RT tK/2504014415725D8oH[?3/%(59GĠq>Y{ ;-JZ ;R|qi[ߋWգزښ'w~#=|N2}|juAߕ{~jnɳb|eU/X˱=RMb~+O˰RߓqqA<,@o4ι8z< 6fi@EEd&}+d2 ; @YXX A|>66T`40$A Y Z2C%tӇD.Z}3Ǣ_XyE(|Jܣ?&,[7G-u3tFqn\8LgʛUOwj L=uo`/:_fŬ.6;W9;&uM޲vksPK[J/S\Y8:certpairs/indirectCRLCA4CertreversecrossCertificatePair.cpUT І?;7AUx3hb]TiTjxo3#c/VGw^FFVVCnN6P6a`C) KX0$D9$3-39$P@$,RT tK/2504014415725D8oH[?3/%(59GĠq>Y{ ;-JZ ;R|qi[ߋWգزښ'w~#=|N2}|juAߕ{~jnɳb|eU/X˱=RMb~+O˰RߓqqA<,@o4ι8z< 6fi@EEd&}+d2 ; @YXX A|>66T`40$A Y Z2C%tӇD.Z}3Ǣ_XyE(|Jܣ?&,[7G-u3tFqn\8LgʛUOwj L=uo`/:_fŬ.6;W9;&uM޲vksPK[J/"4:certpairs/indirectCRLCA5CertforwardcrossCertificatePair.cpUT І?;7AUx3hb]TiTjxo3#c/VGw^FFVVCnN6P6a`C) KX0$D9$3-39$P@$,RT tK/2504014415725D8oH[?3/%(59GԠq>Y{ ;6LDRUsڦQBk^5stjll'rq~ 츛55JeR[W.zN_LOGrg:R*AL;V>1Eg^ 6 ^-!n=c[ܟf&fF5U@* ;nSUx7ؼ+Y>1)k.>;67%<׀$]l WBc*P܀р$! Rj b*`Ubf@#{k6S~W gRfU}aφQig7(1f(j{kR3N4}r,!${?L"\•Q +3M4>I<`{| ,PK[J/294:certpairs/indirectCRLCA5CertreversecrossCertificatePair.cpUT І?;7AUx3hb]TiTjxo3#c/VGw^FFVVCnN6P6a`C) KX0$D9$3-39$P@$,RT tK/2504014415725D8oH[?3/%(59GԠq>Y{ ;6LDRUsڦQBk^5stjll'rq~ 츛55JeR[W.zN_LOGrg:R*AL;V>1Eg^ 6 ^-!n=c[ܟf&fF5U@* ;nSUx7ؼ+Y>1)k.>;67%<׀$]l WBc*P܀р$! Rj b*`Ubf@#{k6S~W gRfU}aφQig7(1f(j{kR3N4}r,!${?L"\•Q +3M4>I<`{| ,PK[J/N3:certpairs/indirectCRLCA6CertforwardcrossCertificatePair.cpUT І?;7AUx3hb]TiTjxo3#c/VGw^FFVVCnN6P6a`C) KX0$D9$3-39$P@$,RT tK/2504014415725D8o̢̼ gG3gde`ne0hdjldo۴OͭX4#izK s}rȞX|BDASTϼ3IOL盗|+I>K->ĥ?V4=w2uރf'5f߰%]C\ }.9ܘ|ܱj# ̓21320.12^V9WtRǻլ==_Ȃ𱈱[%wиKjU'ƴE2j @YXf +q%y0  A @ -VWKܒo[;Hq㗅__sq~CnOc.{\w$/9X}clJZnՠ/'P~;L=;D:+BLqIdUOPPK[J/T3:certpairs/indirectCRLCA6CertreversecrossCertificatePair.cpUT І?;7AUx3hb]TiTjxo3#c/VGw^FFVVCnN6P6a`C) KX0$D9$3-39$P@$,RT tK/2504014415725D8o̢̼ gG3gde`ne0hdjldo۴OͭX4#izK s}rȞX|BDASTϼ3IOL盗|+I>K->ĥ?V4=w2uރf'5f߰%]C\ }.9ܘ|ܱj# ̓21320.12^V9WtRǻլ==_Ȃ𱈱[%wиKjU'ƴE2j @YXf +q%y0  A @ -VWKܒo[;Hq㗅__sq~CnOc.{\w$/9X}clJZnՠ/'P~;L=;D:+BLqIdUOPPK[J/ШM?certpairs/inhibitAnyPolicy0CACertforwardcrossCertificatePair.cpUT І?;7AUx3hbZiAL fZhmƩۀ9M)4P@ I-.QpN-*LLN,I-651 %3 y L - ML͍ y  k A$3/#3)12 ?'3@Ѡq>Y{ ;:62f~>K\o]ϳO CoKU5:ۍn^=TǍ}UG#?XV-.x)mW*I44TL'6ORr"pqO5k;3qVvqq,@O*H5ι8z< 6fi@EEdÌg'\ፔ+y>4?#` ,|Y{ ;:62f~>K\o]ϳO CoKU5:ۍn^=TǍ}UG#?XV-.x)mW*I44TL'6ORr"pqO5k;3qVvqq,@O*H5ι8z< 6fi@EEdÌg'\ፔ+y>4?#` ,|Y{ ;WG}C{̴S~h:UgOMKȵuًkszkc/sVXv=EZfegŎ0nzg+m_uD8zVn5;Cj0+QĽ g4N7zBVE@Awyԫny5kOW |,b,"iN9zdĝOmbgd56q_Eπ+̓1(nh)d5`R@i , $ TΈ@jVuL6YMXVuy9UFgʩIt g{]*(PT7Y֣gu%3W[ֻŤmepl 5wz5pDhvؽ9PK[J/`~P?certpairs/inhibitAnyPolicy1CACertreversecrossCertificatePair.cpUT І?;7AUx3hbZiAL fZhcƩۀ9M)4P@ I-.QpN-*LLN,I-651 %3 y L - ML͍ y  k A$3/#3)12 ?'3PѠq>Y{ ;WG}C{̴S~h:UgOMKȵuًkszkc/sVXv=EZfegŎ0nzg+m_uD8zVn5;Cj0+QĽ g4N7zBVE@Awyԫny5kOW |,b,"iN9zdĝOmbgd56q_Eπ+̓1(nh)d5`R@i , $ TΈ@jVuL6YMXVuy9UFgʩIt g{]*(PT7Y֣gu%3W[ֻŤmepl 5wz5pDhvؽ9PK[J/h/Ccertpairs/inhibitAnyPolicy1subCA1CertforwardcrossCertificatePair.cpUT І?;7AUx3hbXb`r3##/VGw^FFVVCnN6P6a`C) KX0$D9$3-39$P@$,,YW\ih 'k`h`bhihbjnd%k5!&EyM6&9;4G #+sc/Ac'Sc#wƳ^Kț/2pءB8=gcS9)2?(uMj;r-ȶGXF^7su)Tr<>~7U+ U\-xzeywŧcc.^̠ Ye [g=N{'V\6q1)ccT2Aɻf5_>hQ>4?#` ,\ll,@&?HHՀHE030`9A9%}=k |Ls8ts~nȽ%߉_ +wZxDݺPK[J/h/Ccertpairs/inhibitAnyPolicy1subCA1CertreversecrossCertificatePair.cpUT І?;7AUx3hbXb`r3##/VGw^FFVVCnN6P6a`C) KX0$D9$3-39$P@$,,YW\ih 'k`h`bhihbjnd%k5!&EyM6&9;4G #+sc/Ac'Sc#wƳ^Kț/2pءB8=gcS9)2?(uMj;r-ȶGXF^7su)Tr<>~7U+ U\-xzeywŧcc.^̠ Ye [g=N{'V\6q1)ccT2Aɻf5_>hQ>4?#` ,\ll,@&?HHՀHE030`9A9%}=k |Ls8ts~nȽ%߉_ +wZxDݺPK[J/2/Ccertpairs/inhibitAnyPolicy1subCA2CertforwardcrossCertificatePair.cpUT І?;7AUx3hbXb`r3##/VGw^FFVVCnN6P6a`C) KX0$D9$3-39$P@$,,YW\ih 'k`h`bhihbjnd%k5!&EyM6&9;4G #+sc/Ac'Sc#ãr_m2 [(tdfa6/[ټȏ*ӮoȬPuۤuot wE_γC?붦-Ұ>yYϽ8˙!"a U@cE,?2)ccY}‘AUgao79tSH? 0 A|.66 $$ Rj ""5a~)[滾%k+m>;㢜4ifTv}l9GgXv#s`v]^bwfc?g>_sj\O+"Toٰ1k;PK[J/St/Ccertpairs/inhibitAnyPolicy1subCA2CertreversecrossCertificatePair.cpUT І?;7AUx3hbXb`r3##/VGw^FFVVCnN6P6a`C) KX0$D9$3-39$P@$,,YW\ih 'k`h`bhihbjnd%k5!&EyM6&9;4G #+sc/Ac'Sc#ãr_m2 [(tdfa6/[ټȏ*ӮoȬPuۤuot wE_γC?붦-Ұ>yYϽ8˙!"a U@cE,?2)ccY}‘AUgao79tSH? 0 A|.66 $$ Rj ""5a~)[滾%k+m>;㢜4ifTv}l9GgXv#s`v]^bwfc?g>_sj\O+"Toٰ1k;PK[J/:eNBFcertpairs/inhibitAnyPolicy1subCAIAP5CertforwardcrossCertificatePair.cpUT І?;7AUx3hbZiA, f^DlZmmyYY < 8٘CY؄B $@.aԢ̴ĒbCYiHf^FfRfc^e@~Nfr8A8!2xT 6IcT\`j83 ̍ L W7{}C]dm 1q7:9;yKƳ5 ly^"v'_mq;Sov %vUY9tȴٳn/˕xư-nuD}zEI–mT4gbfd`\t>qǺzcU:x-ϷkK&^t{^Fv$x; KI^,Ш]2PK[J/1FBFcertpairs/inhibitAnyPolicy1subCAIAP5CertreversecrossCertificatePair.cpUT І?;7AUx3hbZiA, f^DlZmmyYY < 8٘CY؄B $@.aԢ̴ĒbCYiHf^FfRfc^e@~Nfr8A8!2xT 6IcT\`j83 ̍ L W7{}C]dm 1q7:9;yKƳ5 ly^"v'_mq;Sov %vUY9tȴٳn/˕xư-nuD}zEI–mT4gbfd`\t>qǺzcU:x-ϷkK&^t{^Fv$x; KI^,Ш]2PK[J/K6A-Fcertpairs/inhibitAnyPolicy1subsubCA2CertforwardcrossCertificatePair.cpUT І?;7AUx3hb_mna3#qjy}eddee016dceaf 62qCRKSJ22KR  AryI%y9ɕ ťIΎFr&&FQ⼆\mS1P&6=`0)Q!NLWr|| b_=:!Vgg-. y=}3V/ʢK2jocneoDS۲؝FzZ|{X[6Er9OSʻOԮ< /})Mh{̠n,b "O82]L;,#~ 5)ccQ:){Lsugg@W`20`cc2 AB %@ -auK-VηյG/WGxyo3'wd' o^|{Y?.?o iO|id' {x>}*}WEOfnnPK[J/i2-Fcertpairs/inhibitAnyPolicy1subsubCA2CertreversecrossCertificatePair.cpUT І?;7AUx3hb_mna3#qjy}eddee016dceaf 62qCRKSJ22KR  AryI%y9ɕ ťIΎFr&&FQ⼆\mS1P&6=`0)Q!NLWr|| b_=:!Vgg-. y=}3V/ʢK2jocneoDS۲؝FzZ|{X[6Er9OSʻOԮ< /})Mh{̠n,b "O82]L;,#~ 5)ccQ:){Lsugg@W`20`cc2 AB %@ -auK-VηյG/WGxyo3'wd' o^|{Y?.?o iO|id' {x>}*}WEOfnnPK[J/6N?certpairs/inhibitAnyPolicy5CACertforwardcrossCertificatePair.cpUT І?;7AUx3hbZiAL fZhkƩۀ9M)4P@ I-.QpN-*LLN,I-651 %3 y L - ML͍ y  k A$3/#3)12 ?'3TѠq>Y{ ;&|~fwWU٤:K~~yF#NVx~5/dV1tYd`جI'$+/:gy6xٶ}fKvxĕ2m/g};K⾫(ʫڪ`Ľ g4N7zBVE@Awyԫny5kOW |,b,"z LZV)$S)V @YXf +q%y0  A @ ( P䙁YbhuƏO\a=_Շͽ.=e8gϋ?*-5nIB緖[LQx=d!KWv?-/jfJa=N H=\VNPK[J/P_dN?certpairs/inhibitAnyPolicy5CACertreversecrossCertificatePair.cpUT І?;7AUx3hbZiAL fZhkƩۀ9M)4P@ I-.QpN-*LLN,I-651 %3 y L - ML͍ y  k A$3/#3)12 ?'3TѠq>Y{ ;&|~fwWU٤:K~~yF#NVx~5/dV1tYd`جI'$+/:gy6xٶ}fKvxĕ2m/g};K⾫(ʫڪ`Ľ g4N7zBVE@Awyԫny5kOW |,b,"z LZV)$S)V @YXf +q%y0  A @ ( P䙁YbhuƏO\a=_Շͽ.=e8gϋ?*-5nIB緖[LQx=d!KWv?-/jfJa=N H=\VNPK[J/l=Bcertpairs/inhibitAnyPolicy5subCACertforwardcrossCertificatePair.cpUT І?;7AUx3hbiA4&  x8<ھ222xrp1 3JH8\‚!% ΩE%iɉ%ņ 9fa̼̤ǼʀJSgG9q^CCKCSs#(q^Cd76)AlǴ4 hY|d020724v25626U Vwy˟X_uÓ2|wX#$쾭_Wy^=a<돘U9my?dY$ D1.RHQPK[J/[=Bcertpairs/inhibitAnyPolicy5subCACertreversecrossCertificatePair.cpUT І?;7AUx3hbiA4&  x8<ھ222xrp1 3JH8\‚!% ΩE%iɉ%ņ 9fa̼̤ǼʀJSgG9q^CCKCSs#(q^Cd76)AlǴ4 hY|d020724v25626U Vwy˟X_uÓ2|wX#$쾭_Wy^=a<돘U9my?dY$ D1.RHQPK[J/m!4Ecertpairs/inhibitAnyPolicy5subsubCACertforwardcrossCertificatePair.cpUT І?;7AUx3hbߠ۠f&F&&FF^6N6, ކl̡,lLR `HjqsjQIfZfrbIjHYX<3/#3)12 ?'3T4@N JkGeˤZq>wY{ ;zآ.Š1[M\gy)2N7ۿOxUdo&.=|wRmϺ':Ux9vYg) y\tҖoѩO9u~봶[Ľ k Uf0k*OPf_txy2tvN7)cc)`%eΦҽﷇZHrH? 0 A|>66T?HBՀH530TtONZ%ҕwY{ ;zآ.Š1[M\gy)2N7ۿOxUdo&.=|wRmϺ':Ux9vYg) y\tҖoѩO9u~봶[Ľ k Uf0k*OPf_txy2tvN7)cc)`%eΦҽﷇZHrH? 0 A|>66T?HBՀH530TtONZ%ҕeɿe~`^8kn ^xiq"4Ywem˿P~CM+&覄xٯC+7Vdm-[i.FCZWONs ,׈E_qAc#,b "s6;^5wͫY{{2)ccyy炾w/]72I32ga8"`gƕ 7`4I0)! HÀ-ҙauS:u揭,cc&r+K~Ƥ;.qP]w~/1m;}Ցv7). mysFY⋴|5mLr{nY!eɿe~`^8kn ^xiq"4Ywem˿P~CM+&覄xٯC+7Vdm-[i.FCZWONs ,׈E_qAc#,b "s6;^5wͫY{{2)ccyy炾w/]72I32ga8"`gƕ 7`4I0)! HÀ-ҙauS:u揭,cc&r+K~Ƥ;.qP]w~/1m;}Ցv7). mysFY⋴|5mLr{nY!('xl~ݻ9=+4*pUk7פx/bxɲڡBH!3 iݳv&XuEi"ƂY6w47.5h\9Ye ǹ~.{bPu(Y>1כּjrcQE/#@W`03aJh`L0$A e @$f2c5`Rh~+-/=Y-!2u&& 9ӱ(ms f8>7[q)~#U+?9eR]Ryv|$K\/۹_k ą~9xB }H;PK[J/fFFcertpairs/inhibitPolicyMapping0subCACertreversecrossCertificatePair.cpUT І?;7AUx3hbڿiAv VXhƩǐۀ9M)4P@ I-.QpN-*LLN,I-6T41 Kded&ed&W&d(8;ȉZD"s M@ b4vۊK6G#+sc/Ac'Sc#õvYɂ ?g]? >('xl~ݻ9=+4*pUk7פx/bxɲڡBH!3 iݳv&XuEi"ƂY6w47.5h\9Ye ǹ~.{bPu(Y>1כּjrcQE/#@W`03aJh`L0$A e @$f2c5`Rh~+-/=Y-!2u&& 9ӱ(ms f8>7[q)~#U+?9eR]Ryv|$K\/۹_k ą~9xB }H;PK[J/ʞTFcertpairs/inhibitPolicyMapping1P12CACertforwardcrossCertificatePair.cpUT І?;7AUx3hbZiA2 _haƩۀ9M)4P@ I-.QpN-*LLN,I-651 %3 y L - ML͍ y ۠j A&3/#3)$ ?'37 3/P!HѠq>/Y{ ;6dv9gtݱKjރSE=J0eͫ~iY=\\g;xɩZ&:r RZ#3ms7\TbhQ)C6_EDdrg2b)3#b =#"a ;nSUx7ؼ+Y>12ŭDXY @YXf +q%y0 QxL e m@@$0`k`dhddDKr.Hn` UU߻~PħxotsX(d֋<[X=voząárkYPMnsVk1GOm:Pm"*pPK[J/:M#TFcertpairs/inhibitPolicyMapping1P12CACertreversecrossCertificatePair.cpUT І?;7AUx3hbZiA2 _haƩۀ9M)4P@ I-.QpN-*LLN,I-651 %3 y L - ML͍ y ۠j A&3/#3)$ ?'37 3/P!HѠq>/Y{ ;6dv9gtݱKjރSE=J0eͫ~iY=\\g;xɩZ&:r RZ#3ms7\TbhQ)C6_EDdrg2b)3#b =#"a ;nSUx7ؼ+Y>12ŭDXY @YXf +q%y0 QxL e m@@$0`k`dhddDKr.Hn` UU߻~PħxotsX(d֋<[X=voząárkYPMnsVk1GOm:Pm"*pPK[J/rWIcertpairs/inhibitPolicyMapping1P12subCACertforwardcrossCertificatePair.cpUT І?;7AUx3hbzAs XhƩ ۀ9M)4P@ I-.QpN-*LLN,I-6T5P1 ded&ed&W&d*)8;ȉZD"s Q@ bY{ ;<#~~.ӏZuҚ=(p[y卦7yӕMS.u[Sim0?{O2R+-n?k<=9?:rxrqY*zWſ".d\s4ݴPt&3#93 ~Uf0k/3h_=ADڜUA-@EEٽ :o.YSVN)3I32gaF**"g cƕ 7`D1 0) T-i0Cw:Zn~pkQ e^Đy,o;3g+~]p^9Wm~hΐ =RV6\6ѝ&I3nr[v߼\wɋzkM z-Y鼕kPK[J/[LMcertpairs/inhibitPolicyMapping1P12subCAIPM5CertreversecrossCertificatePair.cpUT І?;7AUx3hb:iA. V^DlZmmyYY  8٘CY؄B $@.aԢ̴ĒbCUeLf^FfRfI@~NfrobAAf^B8A8!2 xu 6*㶱43Ԡq>Y{ ;<#~~.ӏZuҚ=(p[y卦7yӕMS.u[Sim0?{O2R+-n?k<=9?:rxrqY*zWſ".d\s4ݴPt&3#93 ~Uf0k/3h_=ADڜUA-@EEٽ :o.YSVN)3I32gaF**"g cƕ 7`D1 0) T-i0Cw:Zn~pkQ e^Đy,o;3g+~]p^9Wm~hΐ =RV6\6ѝ&I3nr[v߼\wɋzkM z-Y鼕kPK[J/SZPLcertpairs/inhibitPolicyMapping1P12subsubCACertforwardcrossCertificatePair.cpUT І?;7AUx3hbAe YDlZmmyYY 8٘CY؄B $@.aԢ̴ĒbC 5|f^FfRfI@~NfrobAAf^BBqi8A8!2 xK 4!*bo|d120724v2562̘ظi=1?K9 ~U^)5UiWTfk wϳ7̥EBy|_tvW2^"Sɓ?W9!xΖg;7n6h` 2XxU۷W1fn߿soә Y>1[g,DB{ѳي| i~F,,he3PX d xظ<S(<p*I%ՀNՀHf`h.;zvk/E?V*&I3P8r>y9,^몷eLi[pSvQ_RL9U/+lL;خMߺ;힋H5d>4GPK[J/`+PLcertpairs/inhibitPolicyMapping1P12subsubCACertreversecrossCertificatePair.cpUT І?;7AUx3hbAe YDlZmmyYY 8٘CY؄B $@.aԢ̴ĒbC 5|f^FfRfI@~NfrobAAf^BBqi8A8!2 xK 4!*bo|d120724v2562̘ظi=1?K9 ~U^)5UiWTfk wϳ7̥EBy|_tvW2^"Sɓ?W9!xΖg;7n6h` 2XxU۷W1fn߿soә Y>1[g,DB{ѳي| i~F,,he3PX d xظ<S(<p*I%ՀNՀHf`h.;zvk/E?V*&I3P8r>y9,^몷eLi[pSvQ_RL9U/+lL;خMߺ;힋H5d>4GPK[J/OVPcertpairs/inhibitPolicyMapping1P12subsubCAIPM5CertforwardcrossCertificatePair.cpUT І?;7AUx3hbzAm vYhƩ ܐۀ9M)4P@ I-.QpN-*LLN,I-611 +ged&ed&W&d*)&9;zȉZD"s X@b^v7G&#+sc/Ac'Sc#lqgoꡲӪLm4)騣ݾˆmmW*wNLqL =SQl̚$,ZG[vL4eO4)f`Tf*q~Yzqqf @o*H5<SGVM9k)v |,b,"*CvOr&n\ fgd^6U_E@ƀ+̓1(nc2P)Si1;J$6?H0H3BK;5{{_ ;bk;۴ ]_̿v,[OebO9)g[pgԵvb߾BqG„S+.x2r iQϾc(^G1rGPK[J/ RVPcertpairs/inhibitPolicyMapping1P12subsubCAIPM5CertreversecrossCertificatePair.cpUT І?;7AUx3hbzAm vYhƩ ܐۀ9M)4P@ I-.QpN-*LLN,I-611 +ged&ed&W&d*)&9;zȉZD"s X@b^v7G&#+sc/Ac'Sc#lqgoꡲӪLm4)騣ݾˆmmW*wNLqL =SQl̚$,ZG[vL4eO4)f`Tf*q~Yzqqf @o*H5<SGVM9k)v |,b,"*CvOr&n\ fgd^6U_E@ƀ+̓1(nc2P)Si1;J$6?H0H3BK;5{{_ ;bk;۴ ]_̿v,[OebO9)g[pgԵvb߾BqG„S+.x2r iQϾc(^G1rGPK[J/QEcertpairs/inhibitPolicyMapping1P1CACertforwardcrossCertificatePair.cpUT І?;7AUx3hbiAt fXheƩۀ9M)4P@ I-.QpN-*LLN,I-651 %3 y L - ML͍ y ۠bA:3/#3)$ ?'37 3/P!PѠq>'Y{ ;=,QACٶS]Y.m/zp"#D7͉:l {n>\ShuħBf~%wM֧]dPk)n=o{ sl=qAc'Y{ ;=,QACٶS]Y.m/zp"#D7͉:l {n>\ShuħBf~%wM֧]dPk)n=o{ sl=qAc;VjB앛2<%.B+zvԒŊ kV5?tBB]eeՄܭ_]"Ŵgퟫ[=HM6X^gw+}Z"+qqRE@*H5;VjB앛2<%.B+zvԒŊ kV5?tBB]eeՄܭ_]"Ŵgퟫ[=HM6X^gw+}Z"+qqRE@*H51zL?_uss䌯>| i~F,,c3X xظ<S aBVf e P p50242E:30uK;XK<,7m;TXQi5tQH_0[ٽ ﭲda:>>|zQ)ű4}^˥N?lzY;gUw[PK[J/ hNCcertpairs/inhibitPolicyMapping5CACertreversecrossCertificatePair.cpUT І?;7AUx3hbiA&ƿ - x8<ھ2228rp1 3JH8\‚!% ΩE%iɉ%ņ 9faRc^rF~8A8!2x !6Hded&ed&W&d楛*8;4G#+sc/Ac'Sc#ò}SVbF[eo RaƱ7vKN(͋wvΓ`VɱNe<-im|c9{G1zL?_uss䌯>| i~F,,c3X xظ<S aBVf e P p50242E:30uK;XK<,7m;TXQi5tQH_0[ٽ ﭲda:>>|zQ)ű4}^˥N?lzY;gUw[PK[J/]>u=Fcertpairs/inhibitPolicyMapping5subCACertforwardcrossCertificatePair.cpUT І?;7AUx3hbZiA \hƩǐۀ9M)4P@ I-.QpN-*LLN,I-6T41 Kded&ed&W&d楛*8;ȉZD"s M@ b4vۊK6G#+sc/Ac'Sc#ٹ 4v^ZsqsG0?٥17c٢!*ʔm;֬ lK7B/X[iܺ9!%2Gn ?Sz~lv5n7UnK8K]74vCNVE@AAlŏmG9㫏,H %{cr]r/9ۀ$l WBc*P܀р$! Rj *PF (i݋;oyz4WԿ~ʩ޶mT/a[WFSvʬb,?qO \[XNMv{)_۳|ӷeoN:GJV4-ihzPK[J/M=Fcertpairs/inhibitPolicyMapping5subCACertreversecrossCertificatePair.cpUT І?;7AUx3hbZiA \hƩǐۀ9M)4P@ I-.QpN-*LLN,I-6T41 Kded&ed&W&d楛*8;ȉZD"s M@ b4vۊK6G#+sc/Ac'Sc#ٹ 4v^ZsqsG0?٥17c٢!*ʔm;֬ lK7B/X[iܺ9!%2Gn ?Sz~lv5n7UnK8K]74vCNVE@AAlŏmG9㫏,H %{cr]r/9ۀ$l WBc*P܀р$! Rj *PF (i݋;oyz4WԿ~ʩ޶mT/a[WFSvʬb,?qO \[XNMv{)_۳|ӷeoN:GJV4-ihzPK[J/4v9Icertpairs/inhibitPolicyMapping5subsubCACertforwardcrossCertificatePair.cpUT І?;7AUx3hbiAd&?  x8<ھ222rp1 3JH8\‚!% ΩE%iɉ%ņ*J 9fa̼̤̒JĂ̼tS$gG9q^CCKCSs#(q^CdAB,i!bde`ne0hdjldKN|Mfrp]βh [޾8RfլOiyo{#^~ -S.ͩyYn2#=ƛ;mc^Zs;֮[Ϛ=-!pKzI||gbfd`\\cPe 2X %{cr]r/9@EE~V\[廾l vʀ$l WBc*P܀р$! Rj *,Û?`~Q̷:{c׽)WXnڽ㜩ϝW=퇶pϾ ^re&W.`nx܊ӯ\^Q@)Iä4Gf+۵KVնwzǷ:'.RNPK[J/X9Icertpairs/inhibitPolicyMapping5subsubCACertreversecrossCertificatePair.cpUT І?;7AUx3hbiAd&?  x8<ھ222rp1 3JH8\‚!% ΩE%iɉ%ņ*J 9fa̼̤̒JĂ̼tS$gG9q^CCKCSs#(q^CdAB,i!bde`ne0hdjldKN|Mfrp]βh [޾8RfլOiyo{#^~ -S.ͩyYn2#=ƛ;mc^Zs;֮[Ϛ=-!pKzI||gbfd`\\cPe 2X %{cr]r/9@EE~V\[廾l vʀ$l WBc*P܀р$! Rj *,Û?`~Q̷:{c׽)WXnڽ㜩ϝW=퇶pϾ ^re&W.`nx܊ӯ\^Q@)Iä4Gf+۵KVնwzǷ:'.RNPK[J/!'KLcertpairs/inhibitPolicyMapping5subsubsubCACertforwardcrossCertificatePair.cpUT І?;7AUx3hb:Aa YhƩ Ȑۀ9M)4P@ I-.QpN-*LLN,I-6T7P1 eed&ed&W&d楛*&8A8!2 x; 4 v*bm|d120724v2562\&biIy'V/ۮY-7姟s(Hy{_۳5j德Y?-&t#!Aw"&\4_z1WUR1+Z>}8&5mI̳oo-һή;qA"ydY$ DXgeeq%][Ȗ )j dA XXDT ?e]ghgdT6q_Eπ+̓1(nhP)12ɀNՀHf`ը߱-w|gJ.%2tW[wdm\zP?Kˮf[5\OÿH-{\|Sش9,^k~bi.I~WĿwyij:W|+׎ϚkκmmPK[J/KLcertpairs/inhibitPolicyMapping5subsubsubCACertreversecrossCertificatePair.cpUT І?;7AUx3hb:Aa YhƩ Ȑۀ9M)4P@ I-.QpN-*LLN,I-6T7P1 eed&ed&W&d楛*&8A8!2 x; 4 v*bm|d120724v2562\&biIy'V/ۮY-7姟s(Hy{_۳5j德Y?-&t#!Aw"&\4_z1WUR1+Z>}8&5mI̳oo-һή;qA"ydY$ DXgeeq%][Ȗ )j dA XXDT ?e]ghgdT6q_Eπ+̓1(nhP)12ɀNՀHf`ը߱-w|gJ.%2tW[wdm\zP?Kˮf[5\OÿH-{\|Sش9,^k~bi.I~WĿwyij:W|+׎ϚkκmmPK[J/FALcertpairs/InvalidonlyContainsUserCertsTest11EEforwardcrossCertificatePair.cpUT І?;7AUx3hbZiAR [hƩǐۀ9M)4P@ I-.QpN-*LLN,I-6T41 KT:$f+8;ȉZD"s ҉ bg^YbNfv[]]) 8٣ ̍ L >yʴ_,w^gY0hi UB5h, [լML, s}1]-O'suTr|-D/vu,KK=k |LۿޤkZزqldbfd`\\cPOYe rfOqA dA XXD*}|F=X$X8"`gƕ 7`4I0)T 9O;Ң3 _h W;ru҄'W2=tv~5M<2Kݯwvrԇug]m`W=uv;|5;¦?%7I0Zޓ}Vw? gld" PK[J/:ALcertpairs/InvalidonlyContainsUserCertsTest11EEreversecrossCertificatePair.cpUT І?;7AUx3hbZiAR [hƩǐۀ9M)4P@ I-.QpN-*LLN,I-6T41 KT:$f+8;ȉZD"s ҉ bg^YbNfv[]]) 8٣ ̍ L >yʴ_,w^gY0hi UB5h, [լML, s}1]-O'suTr|-D/vu,KK=k |LۿޤkZزqldbfd`\\cPOYe rfOqA dA XXD*}|F=X$X8"`gƕ 7`4I0)T 9O;Ң3 _h W;ru҄'W2=tv~5M<2Kݯwvrԇug]m`W=uv;|5;¦?%7I0Zޓ}Vw? gld" PK[J/!FHcertpairs/InvalidpathLenConstraintTest10EEforwardcrossCertificatePair.cpUT І?;7AUx3hbZiA2 _DlZmmyYY  8٘CY؄B $@.aԢ̴ĒbC5lAbIOjs~^qIQbf^Bqi9;ȉZD"s bg^YbNf z@4G)#+sc/Ac'Sc#z x,S7^xị_$ĻYw| z'3)8K$SuP&a ٷ ?[1ŧܢVxo+5;^ Otx+oˢg21320.12NVE@A$QܵRvMw6Į$1,Hno??ԋ ]sŢ}xV8"`gƕ 7`4I0)d yC&%6snxasYau׸<+~^G(s=ͭ$oO^ia5Io{sVf^v{Մwc?hz!8=#PK[J/HeFHcertpairs/InvalidpathLenConstraintTest10EEreversecrossCertificatePair.cpUT І?;7AUx3hbZiA2 _DlZmmyYY  8٘CY؄B $@.aԢ̴ĒbC5lAbIOjs~^qIQbf^Bqi9;ȉZD"s bg^YbNf z@4G)#+sc/Ac'Sc#z x,S7^xị_$ĻYw| z'3)8K$SuP&a ٷ ?[1ŧܢVxo+5;^ Otx+oˢg21320.12NVE@A$QܵRvMw6Į$1,Hno??ԋ ]sŢ}xV8"`gƕ 7`4I0)d yC&%6snxasYau׸<+~^G(s=ͭ$oO^ia5Io{sVf^v{Մwc?hz!8=#PK[J/yGHcertpairs/InvalidpathLenConstraintTest12EEforwardcrossCertificatePair.cpUT І?;7AUx3hbڴiA* ^DlZmmyYY B 8٘CY؄B $@.aԢ̴ĒbC- bAbIOjs~^qIQbf^Bqi9;FȉZD"s bg^YbNf z@4G-#+sc/Ac'Sc#21Nd.oX/CoY 6Pm&[4fʽwşqUo S?$^ڲn[s07^𲤐UKrbJTC+wvM7lq?Lה]dbfd`\\cPe 2XHهR{'р/9d5̏}Ķ@EEDiKVL7G @YXq@W`03aJh`L0$A Y ZR` 룃goՌ(ћe}wnI_9vYU&SM[Or0Ȩi#f^%W^f;U8fA[Y񌰚~&/4` 4.Ws_i鿝1PK[J/e>GHcertpairs/InvalidpathLenConstraintTest12EEreversecrossCertificatePair.cpUT І?;7AUx3hbڴiA* ^DlZmmyYY B 8٘CY؄B $@.aԢ̴ĒbC- bAbIOjs~^qIQbf^Bqi9;FȉZD"s bg^YbNf z@4G-#+sc/Ac'Sc#21Nd.oX/CoY 6Pm&[4fʽwşqUo S?$^ڲn[s07^𲤐UKrbJTC+wvM7lq?Lה]dbfd`\\cPe 2XHهR{'р/9d5̏}Ķ@EEDiKVL7G @YXq@W`03aJh`L0$A Y ZR` 룃goՌ(ћe}wnI_9vYU&SM[Or0Ȩi#f^%W^f;U8fA[Y񌰚~&/4` 4.Ws_i鿝1PK[J/3@Gcertpairs/InvalidpathLenConstraintTest6EEforwardcrossCertificatePair.cpUT І?;7AUx3hbZiA \DlZmmyYY | 8٘CY؄B $@.aԢ̴ĒbCEyDAbIOjs~^qIQbf^Bqi8A8!2 x L!y%d(`تꊬGdA|d?220724v2562B |,b,":6{Y_ ء{ @YX1@W`03aJh`L0$A Y Z`HtǕlKg|aKKxT}HҖӊN,8hx2@PZVEf,Xx*Ab#Vln}ᡖҜ{ʘ{͢E.[vJ|bԪ 1͙\mZPK[J/~B@Gcertpairs/InvalidpathLenConstraintTest6EEreversecrossCertificatePair.cpUT І?;7AUx3hbZiA \DlZmmyYY | 8٘CY؄B $@.aԢ̴ĒbCEyDAbIOjs~^qIQbf^Bqi8A8!2 x L!y%d(`تꊬGdA|d?220724v2562B |,b,":6{Y_ ء{ @YX1@W`03aJh`L0$A Y Z`HtǕlKg|aKKxT}HҖӊN,8hx2@PZVEf,Xx*Ab#Vln}ᡖҜ{ʘ{͢E.[vJ|bԪ 1͙\mZPK[J/Q_TFJcertpairs/keyUsageCriticalcRLSignFalseCACertforwardcrossCertificatePair.cpUT І?;7AUx3hbǠàf&F&&F^6N6, l̡,lLR `HjqsjQIfZfrbIj0HY'(阗_d 'k`h`bhihbjnd%k5#mM J٩ʼn E%@ <ĜbA|d020724v25624?#f&&q_Eπ+̓1 aBVf Pm}dԍ714?#f&&q_Eπ+̓1 aBVf Pm}dԍ71Nϙ6"oӡ+6 kvDY2 I1}7Mz|Ѣal"߯@|ަS۲+WI~TJ{\(PK[J/FNcertpairs/keyUsageCriticalkeyCertSignFalseCACertreversecrossCertificatePair.cpUT І?;7AUx3hbiASALLLlZmmyYY  8٘CY؄B $@.aԢ̴ĒbCQa0OHQ)P1/9#@N JkE ԲS+CS2K9 @<ĜbA|d020724v2562ܧ*`Y?=. \zF Eni}[m{xU Gy rkD?W6,q5v-rU^ OL v\Vu9&oLJ?="p21320.12zJVE@Awyԫny5kOW |,b,"SScb6ߓl[.Yb@W`03aJh`L0$A Y Zd3CSLӴ1J^?mAhB9]=8Q>Nϙ6"oӡ+6 kvDY2 I1}7Mz|Ѣal"߯@|ަS۲+WI~TJ{\(PK[J/>:9Acertpairs/keyUsageNotCriticalCACertforwardcrossCertificatePair.cpUT І?;7AUx3hbj^ToTmd3#/VGw^FFVVCnN6P6a`C) KX0$D9$3-39$P@$,RT tK/2504014415725Do<T|gG>`de`ne0hdjld1h^vKVnп}ӲiNȽy}Υi f[2K[zY^_OR-UDq9dP,dSǹI/Y`SKuv2 [98k239MW!"a ;nSUx7ؼ+Y>1Z uzdXwFC0I#@Q`03aJh`L0$0)eɒ Z>|mOZ?<8iLꩪ29}}Ԇ+'cvU+L]^*^c8V*Ȧ҇Z~"\tK˦`de`ne0hdjld1h^vKVnп}ӲiNȽy}Υi f[2K[zY^_OR-UDq9dP,dSǹI/Y`SKuv2 [98k239MW!"a ;nSUx7ؼ+Y>1Z uzdXwFC0I#@Q`03aJh`L0$0)eɒ Z>|mOZ?<8iLꩪ29}}Ԇ+'cvU+L]^*^c8V*Ȧ҇Z~"\tK˦y n9ũ Ύ`p=iKxj,}LKFy^SdͻGB KL[f^/-S^92+i/{.ͺ(j|3E׮Y`V߆32[E[isk MlqqAy n9ũ Ύ`p=iKxj,}LKFy^SdͻGB KL[f^/-S^92+i/{.ͺ(j|3E׮Y`V߆32[E[isk MlqqA,n4YVpŊVע$11eLs=#8DW>4?#`D ,|@ a9VД}%jًؒ,'[VFI&e΋O_|@rMΑf)Ϳ^%PK[J/oIQcertpairs/keyUsageNotCriticalkeyCertSignFalseCACertforwardcrossCertificatePair.cpUT І?;7AUx3hbiASALLLrlZmmyYY  8٘CY؄B $@.aԢ̴ĒbCQa0OHQ)P1/9#@N JkG S+CSj2K*r y n9ũ Ύ`Ȱ*M)?Ń~y24==_k҉?nYjͪ_ۨݡ7k{ocW׃a?k/x3 :>certpairs/LongSerialNumberCACertforwardcrossCertificatePair.cpUT І?;7AUx3hbj^ToTmd3#/VGw^FFVVCnN6P6a`C) KX0$D9$3-39$P@$,RT tK/2504014415725Dxo QtԢܤ"gGgde`ne0hdjld:C{O6V^`Jyw;&vm^"z|.utj}]z%.y9OwJMu~H? 0 A|>66T?HBՀH-30T'.yCVٸeڹ OٯYx;/Pp~F,RL5ePcϷ9;,pxg9?0C!bS1L}YKe_#Np *PK[J/y:>certpairs/LongSerialNumberCACertreversecrossCertificatePair.cpUT І?;7AUx3hbj^ToTmd3#/VGw^FFVVCnN6P6a`C) KX0$D9$3-39$P@$,RT tK/2504014415725Dxo QtԢܤ"gGgde`ne0hdjld:C{O6V^`Jyw;&vm^"z|.utj}]z%.y9OwJMu~H? 0 A|>66T?HBՀH-30T'.yCVٸeڹ OٯYx;/Pp~F,RL5ePcϷ9;,pxg9?0C!bS1L}YKe_#Np *PK[J/G,O9certpairs/Mapping1to2CACertforwardcrossCertificatePair.cpUT І?;7AUx3hbںiAZ [h`Ʃۀ9M)4P@ I-.QpN-*LLN,I-651 %3 y L - ML͍ y  a 7 3/]$HѠq>Y{ ;4xlvPuhG?yAgVuLrCWbDцKll.,t=RKW|(|0}Q{nf2uM3}Kvb_&fFō 7/H+NW`j֞ dA XXḒ]^2kyz#@W`03aJh`L0$A e @A$f2c5`R@c* ^#Zj`2QމLEf_ޙm{O(.U~굤&qKWorJȞ.ފߧ٢#^}Y\T,F{2tS[=^!(d׻m-zk éx22ɢ- /-PK[J/>_O9certpairs/Mapping1to2CACertreversecrossCertificatePair.cpUT І?;7AUx3hbںiAZ [h`Ʃۀ9M)4P@ I-.QpN-*LLN,I-651 %3 y L - ML͍ y  a 7 3/]$HѠq>Y{ ;4xlvPuhG?yAgVuLrCWbDцKll.,t=RKW|(|0}Q{nf2uM3}Kvb_&fFō 7/H+NW`j֞ dA XXḒ]^2kyz#@W`03aJh`L0$A e @A$f2c5`R@c* ^#Zj`2QމLEf_ޙm{O(.U~굤&qKWorJȞ.ފߧ٢#^}Y\T,F{2tS[=^!(d׻m-zk éx22ɢ- /-PK[J/ ;ZBcertpairs/MappingFromanyPolicyCACertforwardcrossCertificatePair.cpUT І?;7AUx3hbڶiA: _hlƩۀ9M)4P@ I-.QpN-*LLN,I-651 %3 y L - ML͍ y ۠dA7 3/](?W!12 ?'3RѠq>Y{ ;f#+~Ջ~v=p'nO] smĬMԬ[ھ'iKT3:k57Lc</ҟ;N=9HS\^^W&fFō }""a ;nSUx7ؼ+Y>1Woc23?xpI%| i~F,,c3X 8 XLp`*ADٸ<Sz  A*A*X D@*Ȁ9yڌ[ K^ΖVO4z)2W>Ss[PWY-aoZ}QiyElqV 3.+k_bcniu{lS,α3'slyb" PK[J/nZBcertpairs/MappingFromanyPolicyCACertreversecrossCertificatePair.cpUT І?;7AUx3hbڶiA: _hlƩۀ9M)4P@ I-.QpN-*LLN,I-651 %3 y L - ML͍ y ۠dA7 3/](?W!12 ?'3RѠq>Y{ ;f#+~Ջ~v=p'nO] smĬMԬ[ھ'iKT3:k57Lc</ҟ;N=9HS\^^W&fFō }""a ;nSUx7ؼ+Y>1Woc23?xpI%| i~F,,c3X 8 XLp`*ADٸ<Sz  A*A*X D@*Ȁ9yڌ[ K^ΖVO4z)2W>Ss[PWY-aoZ}QiyElqV 3.+k_bcniu{lS,α3'slyb" PK[J/V@certpairs/MappingToanyPolicyCACertforwardcrossCertificatePair.cpUT І?;7AUx3hbڵiA& ^hbƩۀ9M)4P@ I-.QpN-*LLN,I-651 %3 y L - ML͍ y ۠` A7 3/]!$_!12 ?'3RѠq>Y{ ;fM jeϚ9^?T&yV>yr λ7$dT/Y-WuV>fM&KKOܓ?.Ro[McUs rn݉^b'qAZy?dY$ D~\mwJjW|e R""L(~-GC2#@W`03aJh`L0($A D XZ A*A*X D@*Ȁ$AC̩pM3h߰Fc{NGf}f pSIOC]ÅϖL9ٚr>-ѻ8'rݝRQ[r7'>9Qm-J빃Wo!1UHjϊ@PK[J/n [V@certpairs/MappingToanyPolicyCACertreversecrossCertificatePair.cpUT І?;7AUx3hbڵiA& ^hbƩۀ9M)4P@ I-.QpN-*LLN,I-651 %3 y L - ML͍ y ۠` A7 3/]!$_!12 ?'3RѠq>Y{ ;fM jeϚ9^?T&yV>yr λ7$dT/Y-WuV>fM&KKOܓ?.Ro[McUs rn݉^b'qAZy?dY$ D~\mwJjW|e R""L(~-GC2#@W`03aJh`L0($A D XZ A*A*X D@*Ȁ$AC̩pM3h߰Fc{NGf}f pSIOC]ÅϖL9ٚr>-ѻ8'rݝRQ[r7'>9Qm-J빃Wo!1UHjϊ@PK[J/t4|Ecertpairs/MissingbasicConstraintsCACertforwardcrossCertificatePair.cpUT І?;7AUx3hbXTbT`xs3#/VGw^FFVVCnN6P6a`C) KX0$D9$3-39$P@$,RT tK/2504014415725Doi̼td⒢̼bgGȞ`de`ne0hdjld8]i]ewy޺&H;mޔK20?߻ç8ɳm Iܞ+0(h_̃s, ,MomԎa{<[kŰ_oI} Mۋx;D*3Q$ku&3#lLyOdY$ D~\mwJjW|e R"" JVɮk>?+р$ul WBc*P܀-BбCD}|M2pnRdIZE'^h_ E\r^֦ب?+р$ul WBc*P܀-BбCD}|M2pnRdIZE'^h_ E\r^֦بY{ ;]h_v.6uQ\h:Q1t55M2kNaK/9`\v)Gϵfӻ7&cmq\u>*LEϻǽH6 X+4oԍ{70hj 2X+NW`j֞cc[M֎^D*@W`03aJh`L0$A Y A$H@$os+1,H-,)IM .M*)JM5DK9 {jԄekZ&N]{lMkٍį{!{޻MjY>^#NY+jYg긷yi  [=>{!GCv*\gZ7Dי<1rooO?3PK[J/ͬˌg@certpairs/nameConstraintsDN1CACertreversecrossCertificatePair.cpUT І?;7AUx3hbzAM vZhgƩۀ9M)4P@ I-.QpN-*LLN,I-651 %3 y L - ML͍ y ^ o A,/179?(13XPѠq>Y{ ;]h_v.6uQ\h:Q1t55M2kNaK/9`\v)Gϵfӻ7&cmq\u>*LEϻǽH6 X+4oԍ{70hj 2X+NW`j֞cc[M֎^D*@W`03aJh`L0$A Y A$H@$os+1,H-,)IM .M*)JM5DK9 {jԄekZ&N]{lMkٍį{!{޻MjY>^#NY+jYg긷yi  [=>{!GCv*\gZ7Dי<1rooO?3PK[J/7%Tj+Dcertpairs/nameConstraintsDN1subCA1CertforwardcrossCertificatePair.cpUT І?;7AUx3hbV_Ĭl,oԱՀSͣ;/##++!'s( 0Sh%,Z\ZTXZl(o cKMu+.)J+)Vp3Tpv4504014415725DdoT[X (7$5%4(5P@)l(.Mrv44hSFV^NFm3Yy¾.s^]TU=8ZO_]` mA7u/E>,LHGҥ~v/dnPv&aChm#o?(&csӪMfHU|22;-PK[J/tj+Dcertpairs/nameConstraintsDN1subCA1CertreversecrossCertificatePair.cpUT І?;7AUx3hbV_Ĭl,oԱՀSͣ;/##++!'s( 0Sh%,Z\ZTXZl(o cKMu+.)J+)Vp3Tpv4504014415725DdoT[X (7$5%4(5P@)l(.Mrv44hSFV^NFm3Yy¾.s^]TU=8ZO_]` mA7u/E>,LHGҥ~v/dnPv&aChm#o?(&csӪMfHU|22;-PK[J/oSdDcertpairs/nameConstraintsDN1subCA2CertforwardcrossCertificatePair.cpUT І?;7AUx3hb^nlĔ̀Sͣ;/##++!'s( 0Sh%,Z\ZTXZl(o cKMu+.)J+)Vp3Tpv4504014415725DdoT[X (7$5%4(5P@)l(.Mrv42hSFV^NFOQ|>Y3zz<,Blr^vy1ɓxb;lk]򽰢)g5:v9ZpaR2^!ߚc8WS"gߪUr.~lQUfbfd`\xà<+,b "~z߼۽Hp`p򱈱\];wGOK"| i~F,,̠X xظ<S aBVf e  .6\nJ2BKc 5nYɯ?wmxjYİ*s.a0q+ |  s|Mgȓ,<Nc[J8OwTKyoC$^Za:=)_[dצƟPK[J/dDcertpairs/nameConstraintsDN1subCA2CertreversecrossCertificatePair.cpUT І?;7AUx3hb^nlĔ̀Sͣ;/##++!'s( 0Sh%,Z\ZTXZl(o cKMu+.)J+)Vp3Tpv4504014415725DdoT[X (7$5%4(5P@)l(.Mrv42hSFV^NFOQ|>Y3zz<,Blr^vy1ɓxb;lk]򽰢)g5:v9ZpaR2^!ߚc8WS"gߪUr.~lQUfbfd`\xà<+,b "~z߼۽Hp`p򱈱\];wGOK"| i~F,,̠X xظ<S aBVf e  .6\nJ2BKc 5nYɯ?wmxjYİ*s.a0q+ |  s|Mgȓ,<Nc[J8OwTKyoC$^Za:=)_[dצƟPK[J/ ciDcertpairs/nameConstraintsDN1subCA3CertforwardcrossCertificatePair.cpUT І?;7AUx3hbA \eƩːۀ9M)4P@ I-.QpN-*LLN,I-671 %:%f+*8;ȉZD"s *-,XZYR\TRjhlq6w&9;4G)#+sc/Ac'Sc#m$riZ]r}Ϻl7k玍q8,\ܷsI'W$nx3R)q}ͳg#zL,83>:QY=u;?ҧ.qA"yWdY$ D?y{yy5~0cc _cK__mҬmgda6q_Eπ+̓1(nh)d5`Rj 9E!_ zeh ~>o[8Rӎ]?xy}r!a%~Ҕv䐟/pЯh}nh0C_Us8GE7DpVyg{.|Ng2[TZMPK[J/iDcertpairs/nameConstraintsDN1subCA3CertreversecrossCertificatePair.cpUT І?;7AUx3hbA \eƩːۀ9M)4P@ I-.QpN-*LLN,I-671 %:%f+*8;ȉZD"s *-,XZYR\TRjhlq6w&9;4G)#+sc/Ac'Sc#m$riZ]r}Ϻl7k玍q8,\ܷsI'W$nx3R)q}ͳg#zL,83>:QY=u;?ҧ.qA"yWdY$ D?y{yy5~0cc _cK__mҬmgda6q_Eπ+̓1(nh)d5`Rj 9E!_ zeh ~>o[8Rӎ]?xy}r!a%~Ҕv䐟/pЯh}nh0C_Us8GE7DpVyg{.|Ng2[TZMPK[J/1q6@certpairs/nameConstraintsDN2CACertforwardcrossCertificatePair.cpUT І?;7AUx3hb6ZĬgĬe4y3#/VGw^FFVVCnN6P6a`C) KX0$D9$3-39$P@$,RT tK/2504014415725Dxo,T⒢̼b?#gGgde`ne0hdjldswFؽ!E7 .ٴW5{+e䜪piBֱA67f>6;{`Ƥo&=? j߳ K;ԳeImkcrL" v/"3#&F &FyGdY$ D~\mwJjW|,š#՘-XsŤ| i~F,,c3X xظ<S aBVf eи$"ic8sA4%T[X (7$5%4(5ՐzF%Ef`iŭn>J n-6;{`Ƥo&=? j߳ K;ԳeImkcrL" v/"3#&F &FyGdY$ D~\mwJjW|,š#՘-XsŤ| i~F,,c3X xظ<S aBVf eи$"ic8sA4%T[X (7$5%4(5ՐzF%Ef`iŭn>J n-Y{ ;2_kˌ5[8v[PyRe^zՍiϷ~Xzz߭8#Me^h'–Wp\:Pz_H ud5XT&9k(xĽ 4^1zCVE@Awyԫny5kOW`򱈱t?69 vfOo;egd76q_Eπ+̓1(nh)d5`R 9B/%n.ǀ$*naԊҔԔҤTC z<79.y3󇞉-)/,4W{bu'a֕Oq)e7smU+ki9k횝vXʠZ?7d0^gW!݀Y EPK[J/y:h@certpairs/nameConstraintsDN3CACertreversecrossCertificatePair.cpUT І?;7AUx3hbzA v\`Ʃۀ9M)4P@ I-.QpN-*LLN,I-651 %3 y L - ML͍ y ^ o A,/179?(13XXѠq>Y{ ;2_kˌ5[8v[PyRe^zՍiϷ~Xzz߭8#Me^h'–Wp\:Pz_H ud5XT&9k(xĽ 4^1zCVE@Awyԫny5kOW`򱈱t?69 vfOo;egd76q_Eπ+̓1(nh)d5`R 9B/%n.ǀ$*naԊҔԔҤTC z<79.y3󇞉-)/,4W{bu'a֕Oq)e7smU+ki9k횝vXʠZ?7d0^gW!݀Y EPK[J/b{dDcertpairs/nameConstraintsDN3subCA1CertforwardcrossCertificatePair.cpUT І?;7AUx3hbzA3 _lƩːۀ9M)4P@ I-.QpN-*LLN,I-671 %:%f++8;ȉZD"s K@b6K #aY{N۴5NW \ӖZrWFr wV>hoxNoE]H0+zJmn0o<2s}֛v |,b,"k'i_ѵq^]dIH? 0 A|>66T?HBՀHD@~> < `XR+sJSRSKJRSВ30}fKfj)<ڰSuETx/tӺWX_mev _jG7h_O5mp$}Bۻqv{ݽr70]@nsxgPK[J/oWdDcertpairs/nameConstraintsDN3subCA1CertreversecrossCertificatePair.cpUT І?;7AUx3hbzA3 _lƩːۀ9M)4P@ I-.QpN-*LLN,I-671 %:%f++8;ȉZD"s K@b6K #aY{N۴5NW \ӖZrWFr wV>hoxNoE]H0+zJmn0o<2s}֛v |,b,"k'i_ѵq^]dIH? 0 A|>66T?HBՀHD@~> < `XR+sJSRSKJRSВ30}fKfj)<ڰSuETx/tӺWX_mev _jG7h_O5mp$}Bۻqv{ݽr70]@nsxgPK[J/S5NDcertpairs/nameConstraintsDN3subCA2CertforwardcrossCertificatePair.cpUT І?;7AUx3hbAi 6YbƩːۀ9M)4P@ I-.QpN-*LLN,I-671 %:%f++8;ȉZD"s K@b6K #|4S_8Od_oZc"vѓYG.'^ӟflc8m#cRE3ٗr8.?k괳kzEk'vwZ)ח>/3#=; ^Uf0k~#"l>s}֛v |,b,"4 66T?HBՀH؂@ thh hi[$̻6&Yeg6dn{F{ޖkywdٚ<|#RoABʗ'syڹï 箸+gw8e1z^w>yq_ =Sf7PK[J/>4NDcertpairs/nameConstraintsDN3subCA2CertreversecrossCertificatePair.cpUT І?;7AUx3hbAi 6YbƩːۀ9M)4P@ I-.QpN-*LLN,I-671 %:%f++8;ȉZD"s K@b6K #|4S_8Od_oZc"vѓYG.'^ӟflc8m#cRE3ٗr8.?k괳kzEk'vwZ)ח>/3#=; ^Uf0k~#"l>s}֛v |,b,"4 66T?HBՀH؂@ thh hi[$̻6&Yeg6dn{F{ޖkywdٚ<|#RoABʗ'syڹï 箸+gw8e1z^w>yq_ =Sf7PK[J/ȿ8q4@certpairs/nameConstraintsDN4CACertforwardcrossCertificatePair.cpUT І?;7AUx3hb6XĬcĬa4q3#/VGw^FFVVCnN6P6a`C) KX0$D9$3-39$P@$,RT tK/2504014415725Dxo,T⒢̼b?gGgde`ne0hdjld8שv_하9w$r˸[tYJg6ŗz9cr}9p(_-/,]d]/stc٣bZN>`c{u*gbfd`\ĨfĨd 2X+NW`j֞>cc1|lzs*SѧXc@W`03aJh`L0$A Y ARHqAS <`XR+sJSRSKJRS fZBd K3r}nx} W. Xw'4Wv}c:c3N_XqشW}[_Ւ0_X`/py)RɸsrNYW`c{u*gbfd`\ĨfĨd 2X+NW`j֞>cc1|lzs*SѧXc@W`03aJh`L0$A Y ARHqAS <`XR+sJSRSKJRS fZBd K3r}nx} W. Xw'4Wv}c:c3N_XqشW}[_Ւ0_X`/py)RɸsrNYWr‚E%%)I%E R$$P0CIr9))d 嵋WE-HZgWwM}я,>)izU~]vm5xv)P\jyyHay9_w≬|X^Fˇ G5fp8$69zYI_i02' PK[J/gXR@certpairs/nameConstraintsDN5CACertreversecrossCertificatePair.cpUT І?;7AUx3hb[efĴ~3#/VGw^FFVVCnN6P6a`C) KX0$D9$3-39$P@$,RT tK/2504014415725Dxo,T⒢̼b?SgGgde`ne0hdjld8l$tԃ7j)tTgsքfղy~_|.6//hWkkoI\{UFh::-|69S~`pOzs~kmyoګ7141:=""a ;nSUx7ؼ+OeXXDL9scwo|kgd96q_Eπ+̓1(nh)d5`RA"r [xx.q7p%>r‚E%%)I%E R$$P0CIr9))d 嵋WE-HZgWwM}я,>)izU~]vm5xv)P\jyyHay9_w≬|X^Fˇ G5fp8$69zYI_i02' PK[J/U|VAcertpairs/nameConstraintsDNS1CACertforwardcrossCertificatePair.cpUT І?;7AUx3hbZiAr XfƩۀ9M)4P@ I-.QpN-*LLN,I-651 %3 y L - ML͍ y ۠` AY{ ;V6V(.a6kuд xΝRSNa 㒢%խa%L]lq_5eб]ǰƓ@\-e "Vv=CҺ_O,dZy˺Zߏfbfd`\ܸԠq<,b "s6;^5wͫY{{2)cc)}.cGyWŃW#@W`03aJh`L0$A Y H@$ c &`Ж$#^z~Z:`Yʬ*% {G{[cpϹ]ccI?_^E:L. eNSLS9e|7hsۚt skpפhfߓ\fDik'[AGPK[J/vY{ ;V6V(.a6kuд xΝRSNa 㒢%խa%L]lq_5eб]ǰƓ@\-e "Vv=CҺ_O,dZy˺Zߏfbfd`\ܸԠq<,b "s6;^5wͫY{{2)cc)}.cGyWŃW#@W`03aJh`L0$A Y H@$ c &`Ж$#^z~Z:`Yʬ*% {G{[cpϹ]ccI?_^E:L. eNSLS9e|7hsۚt skpפhfߓ\fDik'[AGPK[J/r.C[Acertpairs/nameConstraintsDNS2CACertforwardcrossCertificatePair.cpUT І?;7AUx3hbڴiA* ^nƩۀ9M)4P@ I-.QpN-*LLN,I-651 %3 y L - ML͍ y ۠` AY{ ;nΫi q9sw?Z߯K)w! AH Y_f\lKg^, ?$er3KnT(X97Tɔ-Ϯm )ƾ#ԞGIZ~kqARy?dY$ D~\mwJjW|e R""R7{s.vry_-u6҃-| i~F,,c3X xظ<S aBVf e  .6l+KLIF j2 *ͭg+ryީjی.f<=џ;#;y|:9BѱlTX%?vtz՗UZkl~ԼⴗٳsWyD\[vPUzڗOoV׶}0=/ﺬMεX<PK[J/ +[Acertpairs/nameConstraintsDNS2CACertreversecrossCertificatePair.cpUT І?;7AUx3hbڴiA* ^nƩۀ9M)4P@ I-.QpN-*LLN,I-651 %3 y L - ML͍ y ۠` AY{ ;nΫi q9sw?Z߯K)w! AH Y_f\lKg^, ?$er3KnT(X97Tɔ-Ϯm )ƾ#ԞGIZ~kqARy?dY$ D~\mwJjW|e R""R7{s.vry_-u6҃-| i~F,,c3X xظ<S aBVf e  .6l+KLIF j2 *ͭg+ryީjی.f<=џ;#;y|:9BѱlTX%?vtz՗UZkl~ԼⴗٳsWyD\[vPUzڗOoV׶}0=/ﺬMεX<PK[J/C:[Dcertpairs/nameConstraintsRFC822CA1CertforwardcrossCertificatePair.cpUT І?;7AUx3hbڼiAj YlƩۀ9M)4P@ I-.QpN-*LLN,I-651 %3 y L - ML͍ y ~۠lA*/179?(13X!HРq>Y{ ;'9k1֙U8eBZȸ~=Z -Bt CwV˶oy~~]WϿ^ĩسX'MsV+)qAbyWdY$ D~\mwJjW|e R""򸾵ow;d+W٫ր$wl WBc*P܀р$! Rj Ar Y⍢z-IF k2 2W;ǟtT|a7Cyw{,_[f]-"3˗+r o}y~VvDžۭ0㑃E?ښud=\mٍv[1&f PK[J/%R<[Dcertpairs/nameConstraintsRFC822CA1CertreversecrossCertificatePair.cpUT І?;7AUx3hbڼiAj YlƩۀ9M)4P@ I-.QpN-*LLN,I-651 %3 y L - ML͍ y ~۠lA*/179?(13X!HРq>Y{ ;'9k1֙U8eBZȸ~=Z -Bt CwV˶oy~~]WϿ^ĩسX'MsV+)qAbyWdY$ D~\mwJjW|e R""򸾵ow;d+W٫ր$wl WBc*P܀р$! Rj Ar Y⍢z-IF k2 2W;ǟtT|a7Cyw{,_[f]-"3˗+r o}y~VvDžۭ0㑃E?ښud=\mٍv[1&f PK[J/[zZDcertpairs/nameConstraintsRFC822CA2CertforwardcrossCertificatePair.cpUT І?;7AUx3hbڴiA* ^bƩۀ9M)4P@ I-.QpN-*LLN,I-651 %3 y L - ML͍ y ~۠lA*/179?(13X!HȠq>Y{ ;>߆OO|hzyiEŽO=/7EDmYyTv᫗>v왠UGެb m5v4/ZvYKbӭM5ebB\9WLh|”N&fFōK ""a ;nSUx7ؼ+Y>1imɫ Cۗ6K7=igd;6q_Eπ+̓1(nh)d5`Rj 9E[zehI~N+(XV,CRyWVN~r:_\Ug8T㭏W,{em~jRݺN87±oWpꀵǒY 95Ws'tvpkPK[J/"=ZDcertpairs/nameConstraintsRFC822CA2CertreversecrossCertificatePair.cpUT І?;7AUx3hbڴiA* ^bƩۀ9M)4P@ I-.QpN-*LLN,I-651 %3 y L - ML͍ y ~۠lA*/179?(13X!HȠq>Y{ ;>߆OO|hzyiEŽO=/7EDmYyTv᫗>v왠UGެb m5v4/ZvYKbӭM5ebB\9WLh|”N&fFōK ""a ;nSUx7ؼ+Y>1imɫ Cۗ6K7=igd;6q_Eπ+̓1(nh)d5`Rj 9E[zehI~N+(XV,CRyWVN~r:_\Ug8T㭏W,{em~jRݺN87±oWpꀵǒY 95Ws'tvpkPK[J/4^XDcertpairs/nameConstraintsRFC822CA3CertforwardcrossCertificatePair.cpUT І?;7AUx3hbڴiA* ^jƩۀ9M)4P@ I-.QpN-*LLN,I-651 %3 y L - ML͍ y ~۠lA*/179?(13X!Hؠq>Y{ ;N,jdݵ,Eٺʟ+V_,^M*_x>߁\~zM:}pMٟ6]O%ӛ"2?aϗ{y҅v>+Xs21320.n\jи@Ye 9WtRǻլ==_Ȃ𱈱ڞ7K,=sk-ӥm2| i~F,,c3X xظ<S aBVf e H-:Q%HA_WPQ1}Pׯ䣝 ٷ^)-JQ!{:_>%c':,oT9jIYDXI[}*o@wm^"#Jhw~yJOpFw,PK[J/MXDcertpairs/nameConstraintsRFC822CA3CertreversecrossCertificatePair.cpUT І?;7AUx3hbڴiA* ^jƩۀ9M)4P@ I-.QpN-*LLN,I-651 %3 y L - ML͍ y ~۠lA*/179?(13X!Hؠq>Y{ ;N,jdݵ,Eٺʟ+V_,^M*_x>߁\~zM:}pMٟ6]O%ӛ"2?aϗ{y҅v>+Xs21320.n\jи@Ye 9WtRǻլ==_Ȃ𱈱ڞ7K,=sk-ӥm2| i~F,,c3X xظ<S aBVf e H-:Q%HA_WPQ1}Pׯ䣝 ٷ^)-JQ!{:_>%c':,oT9jIYDXI[}*o@wm^"#Jhw~yJOpFw,PK[J/XAcertpairs/nameConstraintsURI1CACertforwardcrossCertificatePair.cpUT І?;7AUx3hbڰiA \aƩۀ9M)4P@ I-.QpN-*LLN,I-651 %3 y L - ML͍ y ۠` AY{ ;xiv%I~sxJto`()abB怚 lzy>\t9h!"&S){R&{LV2E-/1禓-=}YN9P!s\KĽ 4.6CVE@Awyԫny5kOW |,b,"kdvyq?ړ͔} @YXf +q%y0  A @@$ 5^ i & ےdK/CK,rW~sdT;!/ڸ ǬB~)Nfό;_~.eߧ&1ٯ&%+ʫRR7&\_v|}VqI="~$)ȄtkY{ ;xiv%I~sxJto`()abB怚 lzy>\t9h!"&S){R&{LV2E-/1禓-=}YN9P!s\KĽ 4.6CVE@Awyԫny5kOW |,b,"kdvyq?ړ͔} @YXf +q%y0  A @@$ 5^ i & ےdK/CK,rW~sdT;!/ڸ ǬB~)Nfό;_~.eߧ&1ٯ&%+ʫRR7&\_v|}VqI="~$)ȄtkY{ ;.w5(Fnr`ER\{j:?% +,]UKOeuzj/%|u9XcU>ڢ᫜6>s"_}69_{uD}K;gxskzqq ƥ@*H5ι8z< 6fi@EEmIhǞ˗9*B1(>4?#`ı ,|瑸Dѿ)r?&65,]z5\I;C!C踕be2&e;%REʀЕm5U*=sW!PK[J/[Acertpairs/nameConstraintsURI2CACertreversecrossCertificatePair.cpUT І?;7AUx3hbڴiA* ^iƩۀ9M)4P@ I-.QpN-*LLN,I-651 %3 y L - ML͍ y ۠` AY{ ;.w5(Fnr`ER\{j:?% +,]UKOeuzj/%|u9XcU>ڢ᫜6>s"_}69_{uD}K;gxskzqq ƥ@*H5ι8z< 6fi@EEmIhǞ˗9*B1(>4?#`ı ,|瑸Dѿ)r?&65,]z5\I;C!C踕be2&e;%REʀЕm5U*=sW!PK[J/~]Y:certpairs/NameOrderingCACertforwardcrossCertificatePair.cpUT І?;7AUx3hb:AA ZfƩۀ9M)4P@ I-.QpN-*LLN,I-651 %3 y L - ML͍ y }[l/JOˬJ,KQ,QKMU0$F8ı`Ԣ̼tgGȁ`pQ囲GYԬ[ظ[b˭9B?[_'%w\~&js1 +yJG2i݌{F+־>߳[nLr8V}Y)6aF[7;4^m4]I[f21320.12:_VE@Awyԫny5kOW |,b,"|x Nd$E%0 ,|߳[nLr8V}Y)6aF[7;4^m4]I[f21320.12:_VE@Awyԫny5kOW |,b,"|x Nd$E%0 ,|Bcertpairs/NegativeSerialNumberCACertforwardcrossCertificatePair.cpUT І?;7AUx3hbj_lTob3#/VGw^FFVVCnN6P6a`C) KX0$D9$3-39$P@$,RT tK/2504014415725DoIĒ̲TԢܤ"gG^`de`ne0hdjld8Bcertpairs/NegativeSerialNumberCACertreversecrossCertificatePair.cpUT І?;7AUx3hbj_lTob3#/VGw^FFVVCnN6P6a`C) KX0$D9$3-39$P@$,RT tK/2504014415725DoIĒ̲TԢܤ"gG^`de`ne0hdjld8,n4YVpŊVע$11eLs=#8DW>4?#`D ,|@ a9VД}%jًؒ,'[VFI&e΋O_|@rMΑf)Ϳ^%PK[J/y2EHcertpairs/NoissuingDistributionPointCACertforwardcrossCertificatePair.cpUT І?;7AUx3hbYabv3#/VGw^FFVVCnN6P6a`C) KX0$D9$3-39$P@$,RT tK/2504014415725Do*H[X/_!43/%(3$3?/ ?3Ѡq>?Y{ ;Wv\!&4.bc:ayd34؟}~Ogkԋ{sV>I%4]PK[J/zEHcertpairs/NoissuingDistributionPointCACertreversecrossCertificatePair.cpUT І?;7AUx3hbYabv3#/VGw^FFVVCnN6P6a`C) KX0$D9$3-39$P@$,RT tK/2504014415725Do*H[X/_!43/%(3$3?/ ?3Ѡq>?Y{ ;Wv\!&4.bc:ayd34؟}~Ogkԋ{sV>I%4]PK[J/OUsg8certpairs/NoPoliciesCACertforwardcrossCertificatePair.cpUT І?;7AUx3hbJ^omxd3#/VGw^FFVVCnN6P6a`C) KX0$D9$3-39$P@$,RT tK/2504014415725D8o(>|bgGfde`ne0hdjldXOl\ 6V {e}idi_s7$+zj*C_&,`g5ˮ3Ȕ_r#lM7onSZvYx̗)skV!kO['$/"a ;nSUx7ؼ+Y>1"O'7a^1 @YXf @ -ϖ9sk蝆UE/Px_TV_eWZ nC__qwHU?op $i4w}tNۿ}zNOYvH[mLh<9kT;|2#W;lБ2oH+`PK[J/hg8certpairs/NoPoliciesCACertreversecrossCertificatePair.cpUT І?;7AUx3hbJ^omxd3#/VGw^FFVVCnN6P6a`C) KX0$D9$3-39$P@$,RT tK/2504014415725D8o(>|bgGfde`ne0hdjldXOl\ 6V {e}idi_s7$+zj*C_&,`g5ˮ3Ȕ_r#lM7onSZvYx̗)skV!kO['$/"a ;nSUx7ؼ+Y>1"O'7a^1 @YXf @ -ϖ9sk蝆UE/Px_TV_eWZ nC__qwHU?op $i4w}tNۿ}zNOYvH[mLh<9kT;|2#W;lБ2oH+`PK[J/M78>certpairs/OldCRLnextUpdateCACertforwardcrossCertificatePair.cpUT І?;7AUx3hbj^ToTmd3##/VGw^FFVVCnN6P6a`C) KX0$D9$3-39$P@$,RT tK/2504014415725Dxo Q ԊЂA|d320724v2562l>QaCo s.u|K˾a\bj;ͱݠ|&1};L4wy[I)Y|'^ceo̼\s>q }hQJNtS PK[J/ !XQ8>certpairs/OldCRLnextUpdateCACertreversecrossCertificatePair.cpUT І?;7AUx3hbj^ToTmd3##/VGw^FFVVCnN6P6a`C) KX0$D9$3-39$P@$,RT tK/2504014415725Dxo Q ԊЂA|d320724v2562l>QaCo s.u|K˾a\bj;ͱݠ|&1};L4wy[I)Y|'^ceo̼\s>q }hQJNtS PK[J/×AHcertpairs/onlyContainsAttributeCertsCACertforwardcrossCertificatePair.cpUT І?;7AUx3hb^nlf3#/VGw^FFVVCnN6P6a`C) KX0$D9$3-39$P@$,RT tK/2504014415725Do J̼bǒ̤ҒTbgG`de`ne0hdjldҤYQeʿwִLzZet}Y [3q]>o-oyTCTlYyYu-O1'=γ2Fێ|U!|6I/Mp `2'bJ^SSPnL^S~ՌLgXڱ PK[J/كAHcertpairs/onlyContainsAttributeCertsCACertreversecrossCertificatePair.cpUT І?;7AUx3hb^nlf3#/VGw^FFVVCnN6P6a`C) KX0$D9$3-39$P@$,RT tK/2504014415725Do J̼bǒ̤ҒTbgG`de`ne0hdjldҤYQeʿwִLzZet}Y [3q]>o-oyTCTlYyYu-O1'=γ2Fێ|U!|6I/Mp `2'bJ^SSPnL^S~ՌLgXڱ PK[J/#\9Acertpairs/onlyContainsCACertsCACertforwardcrossCertificatePair.cpUT І?;7AUx3hbjY`Tct3#/VGw^FFVVCnN6P6a`C) KX0$D9$3-39$P@$,RT tK/2504014415725Dxo,J̼bgGbgGgde`ne0hdjldXn~jb补H8_US-E| >sr+fmnnl{sWЙfҋq~o׋9KV~Ki9 k8]6mLJ]w=fbfd`\\cPe 2X+NW`j֞cc-eסmOy]€$kl WBc*P܀р$! Rj "*&UveR)+TW4>)"fYbݛjSޙN٫?4LYy]͒2K˹̐c/:Z񟫿v2EATǓVwtL< PK[J/~w9Acertpairs/onlyContainsCACertsCACertreversecrossCertificatePair.cpUT І?;7AUx3hbjY`Tct3#/VGw^FFVVCnN6P6a`C) KX0$D9$3-39$P@$,RT tK/2504014415725Dxo,J̼bgGbgGgde`ne0hdjldXn~jb补H8_US-E| >sr+fmnnl{sWЙfҋq~o׋9KV~Ki9 k8]6mLJ]w=fbfd`\\cPe 2X+NW`j֞cc-eסmOy]€$kl WBc*P܀р$! Rj "*&UveR)+TW4>)"fYbݛjSޙN٫?4LYy]͒2K˹̐c/:Z񟫿v2EATǓVwtL< PK[J/:Ccertpairs/onlyContainsUserCertsCACertforwardcrossCertificatePair.cpUT І?;7AUx3hbj[dTg|3#/VGw^FFVVCnN6P6a`C) KX0$D9$3-39$P@$,RT tK/2504014415725Do<J̼"bgG>`de`ne0hdjldػ[yFV 3*nea-{T3oGyCԥz^랻}'T걸Gny%!wW2߹_Vfpa3_W]=|#&y/g/nEBbĽ k ސUf0ksEq)yl^,HHisKn3b꿠ZO| i~F,,xc3X xظ<S aBVf PޮpEç=G^U/?q5^wN5͕t]X }3N+[[jfw÷vz̡&卓Orܞ :0JXτ9'R)_"?osx]-HvΊrPK[J/8l6>certpairs/onlySomeReasonsCA1CertforwardcrossCertificatePair.cpUT І?;7AUx3hbj\TkTih3#c/VGw^FFVVCnN6P6a`C) KX0$D9$3-39$P@$,RT tK/2504014415725DoԠbgGCȎgde`ne0hdjldXQ~y’)!I_y6n-#)5v8.} Ny4|x WX$X'/X_zɑ#9+2-XƤ J]?Bs5d餽ebfd`\\cPe 2X+NW`j֞ dA XXD$ͺW?Z߾3w, @YXQf +q%y0  A @ -f2{c1nQKNu_y!WD^Wi[,$L3C-ʶR#qg9`[Kc^Z'CN,i'iWPI 'gwohZ!6-IWfOja~\NPK[J/EH:Ccertpairs/onlyContainsUserCertsCACertreversecrossCertificatePair.cpUT І?;7AUx3hbj[dTg|3#/VGw^FFVVCnN6P6a`C) KX0$D9$3-39$P@$,RT tK/2504014415725Do<J̼"bgG>`de`ne0hdjldػ[yFV 3*nea-{T3oGyCԥz^랻}'T걸Gny%!wW2߹_Vfpa3_W]=|#&y/g/nEBbĽ k ސUf0ksEq)yl^,HHisKn3b꿠ZO| i~F,,xc3X xظ<S aBVf PޮpEç=G^U/?q5^wN5͕t]X }3N+[[jfw÷vz̡&卓Orܞ :0JXτ9'R)_"?osx]-HvΊrPK[J/B6>certpairs/onlySomeReasonsCA1CertreversecrossCertificatePair.cpUT І?;7AUx3hbj\TkTih3#c/VGw^FFVVCnN6P6a`C) KX0$D9$3-39$P@$,RT tK/2504014415725DoԠbgGCȎgde`ne0hdjldXQ~y’)!I_y6n-#)5v8.} Ny4|x WX$X'/X_zɑ#9+2-XƤ J]?Bs5d餽ebfd`\\cPe 2X+NW`j֞ dA XXD$ͺW?Z߾3w, @YXQf +q%y0  A @ -f2{c1nQKNu_y!WD^Wi[,$L3C-ʶR#qg9`[Kc^Z'CN,i'iWPI 'gwohZ!6-IWfOja~\NPK[J/7n9>certpairs/onlySomeReasonsCA2CertforwardcrossCertificatePair.cpUT І?;7AUx3hbj\TkTih3#c/VGw^FFVVCnN6P6a`C) KX0$D9$3-39$P@$,RT tK/2504014415725DoԠbgG#Ȏgde`ne0hdjld8fY9k̑YOIBN7)Wmm/O'*6n.jB7z.skuHԍ%certpairs/onlySomeReasonsCA2CertreversecrossCertificatePair.cpUT І?;7AUx3hbj\TkTih3#c/VGw^FFVVCnN6P6a`C) KX0$D9$3-39$P@$,RT tK/2504014415725DoԠbgG#Ȏgde`ne0hdjld8fY9k̑YOIBN7)Wmm/O'*6n.jB7z.skuHԍ%certpairs/onlySomeReasonsCA3CertforwardcrossCertificatePair.cpUT І?;7AUx3hbj\TkTih3#c/VGw^FFVVCnN6P6a`C) KX0$D9$3-39$P@$,RT tK/2504014415725DoH[X8?/28?75(58?Xؠq>Y{ ;1`ْ{Gly6ǹf;!S'-\u`V]|_{:%M$r]o\XlǥK?Jt]IGx#U]WZ\31320.12@VE@Awyԫny5kOW |,b,"կ3-[y @YXQf +q%y0  A @ -f`q=+̕ {RSΝ['O1uiiݽM[hs tY;%oa4 v|{*/aVw'u :w/5{gMKiަC;PK[J/:>certpairs/onlySomeReasonsCA3CertreversecrossCertificatePair.cpUT І?;7AUx3hbj\TkTih3#c/VGw^FFVVCnN6P6a`C) KX0$D9$3-39$P@$,RT tK/2504014415725DoH[X8?/28?75(58?Xؠq>Y{ ;1`ْ{Gly6ǹf;!S'-\u`V]|_{:%M$r]o\XlǥK?Jt]IGx#U]WZ\31320.12@VE@Awyԫny5kOW |,b,"կ3-[y @YXQf +q%y0  A @ -f`q=+̕ {RSΝ['O1uiiݽM[hs tY;%oa4 v|{*/aVw'u :w/5{gMKiަC;PK[J/tX 9>certpairs/onlySomeReasonsCA4CertforwardcrossCertificatePair.cpUT І?;7AUx3hbj\TkTih3#c/VGw^FFVVCnN6P6a`C) KX0$D9$3-39$P@$,RT tK/2504014415725DoH[X8?/28?75(58?XĠq>Y{ ;1c,p9OۻZ.:q;/:MmrW.x+lOcKAÙoq wp˗'ԝ7v:|Rt.[O‚k:t *]}׻C3_Qfbfd`\\cPe 2X+NW`j֞ dA XXD9|{Ca%Qp4I32gaF8"`gƕ 7`4I0)eSV9<;)-KLi3K5W%|mf^]¼v\;6_ɮ Y6i>g9].7>z*#aV@p7/ NSӻ ~0]y" Λ+PK[J/KE9>certpairs/onlySomeReasonsCA4CertreversecrossCertificatePair.cpUT І?;7AUx3hbj\TkTih3#c/VGw^FFVVCnN6P6a`C) KX0$D9$3-39$P@$,RT tK/2504014415725DoH[X8?/28?75(58?XĠq>Y{ ;1c,p9OۻZ.:q;/:MmrW.x+lOcKAÙoq wp˗'ԝ7v:|Rt.[O‚k:t *]}׻C3_Qfbfd`\\cPe 2X+NW`j֞ dA XXD9|{Ca%Qp4I32gaF8"`gƕ 7`4I0)eSV9<;)-KLi3K5W%|mf^]¼v\;6_ɮ Y6i>g9].7>z*#aV@p7/ NSӻ ~0]y" Λ+PK[J/6,IBcertpairs/OverlappingPoliciesTest6EEforwardcrossCertificatePair.cpUT І?;7AUx3hbZiAB ZhƩ Ȑۀ9M)4P@ I-.QpN-*LLN,I-6T7P1 d&g+(&#r&&FQ⼆\X420ة_ZXPYHA|dO220724v2562l2u=Ǧǟms)͸OgMߠ{3sizE?eu>~f‘5M~Pc%96' #4~6au]ɢ=GϭUs8W>%&MygqqA<_,b "g66T?HBՀHf`pUmxH֋ϝ'EOܱ~f‘5M~Pc%96' #4~6au]ɢ=GϭUs8W>%&MygqqA<_,b "g66T?HBՀHf`pUmxH֋ϝ'EOܱW<certpairs/P12Mapping1to3CACertforwardcrossCertificatePair.cpUT І?;7AUx3hb:A~ XhhƩۀ9M)4P@ I-.QpN-*LLN,I-651 %3 y L - ML͍ y  c A8H7 3/]$XѠq>Y{ ;fԭ{kҟl\7ێfgodܾbvJW3Βi}ڇ'׬ onrLENm)zeL ,}[tw1Neώm74hg 2X+NW`j֞ dA XXD>^X2dgd46U_E@ƀ+̓1(nc2P)Si#0T" AAX  Ȁ>a+2]NtyfQ}oá4>ms|8m{f?P/njYkpN; }ؤ3ꈥ3SUx2R ?tVR;PK[J/#W<certpairs/P12Mapping1to3CACertreversecrossCertificatePair.cpUT І?;7AUx3hb:A~ XhhƩۀ9M)4P@ I-.QpN-*LLN,I-651 %3 y L - ML͍ y  c A8H7 3/]$XѠq>Y{ ;fԭ{kҟl\7ێfgodܾbvJW3Βi}ڇ'׬ onrLENm)zeL ,}[tw1Neώm74hg 2X+NW`j֞ dA XXD>^X2dgd46U_E@ƀ+̓1(nc2P)Si#0T" AAX  Ȁ>a+2]NtyfQ}oá4>ms|8m{f?P/njYkpN; }ؤ3ꈥ3SUx2R ?tVR;PK[J/u^O?certpairs/P12Mapping1to3subCACertforwardcrossCertificatePair.cpUT І?;7AUx3hbAU [hƩݐۀ9M)4P@ I-.QpN-*LLN,I-611 )&d++8;ȉZD"s H@bEťI@#{4ǓK<}bRy~8X:6o{EQӜS^TGCE$cG0v|{sqkzёܮ{9r_d/1=`߳%lJ WA)y7dY$ D>^X2,H]&j/F~Y(dFE>4?#` ,r2^X2,H]&j/F~Y(dFE>4?#` ,r24?#`$ ,r24?#`$ ,r2[>Ju|֜onx:Up#6.ako}uygDN;5=Z~sr-=)\B[fcOMX`wMGĽ 䁾Uf0ksEq)yl^,H%y7 _=_iZw| i~F,,c3hb(419;ٸ<S qhɠqTBK+b *HU(-N-R/LNUH+U(,MPR!8?9) % ~!)-dž4dc3KsRRR2 r+€(#( װ ]=YqB64p7[>Ju|֜onx:Up#6.ako}uygDN;5=Z~sr-=)\B[fcOMX`wMGĽ 䁾Uf0ksEq)yl^,H%y7 _=_iZw| i~F,,c3hb(419;ٸ<S qhɠqTBK+b *HU(-N-R/LNUH+U(,MPR!8?9) % ~!)-dž4dc3KsRRR2 r+€(#( װ ]=YqB64p7Y{ ;ve2*hI?[sU޾|N6x[]mkC;i\r ~xyq%_MOk#mߍ}v=l>"+V_"wgsfLNOwre43Yfsdbfd`\ܠ<,b "s6;^5wͫY{{2)cc9⥶ɬ3ޟ>+ @YXf +q%y0  @ ~pECb3a)b2[d63Z PВ30Ίخj8{/ioR'󿙺3xY[ʓΖ{bh|jD}jw?|}#(޹=F_(_\m\_i vMfҿA5nw| !'Vѯ4mmY{ ;ve2*hI?[sU޾|N6x[]mkC;i\r ~xyq%_MOk#mߍ}v=l>"+V_"wgsfLNOwre43Yfsdbfd`\ܠ<,b "s6;^5wͫY{{2)cc9⥶ɬ3ޟ>+ @YXf +q%y0  @ ~pECb3a)b2[d63Z PВ30Ίخj8{/ioR'󿙺3xY[ʓΖ{bh|jD}jw?|}#(޹=F_(_\m\_i vMfҿA5nw| !'Vѯ4mmRhݹ{_)^U?A;JnǪ }DvŖ#o}ӟzcgcN_wپMl\!Gr6T]%>>Vgbfd`\x֠<,b "g_^1uҧ?p|e,HZ2ᵻ o(LzH? 0 TA|966T LH*ج(2,Hl6~ X Za3jM7>?~e^qUѿyѽ} <*(+C`wd5Z3st,w3և/ 4N r${٣W~o|2wHުG_kxPK[J/}Q@certpairs/P1Mapping1to234subCACertreversecrossCertificatePair.cpUT І?;7AUx3hbAu vXhƩÐۀ9M)4P@ I-.QpN-*LLN,I-651 *&d+(8;ȉZD"s I@b8MťI@#{aQ7'FFN>Rhݹ{_)^U?A;JnǪ }DvŖ#o}ӟzcgcN_wپMl\!Gr6T]%>>Vgbfd`\x֠<,b "g_^1uҧ?p|e,HZ2ᵻ o(LzH? 0 TA|966T LH*ج(2,Hl6~ X Za3jM7>?~e^qUѿyѽ} <*(+C`wd5Z3st,w3և/ 4N r${٣W~o|2wHުG_kxPK[J/JN%^Ccertpairs/PanyPolicyMapping1to2CACertforwardcrossCertificatePair.cpUT І?;7AUx3hbڵiA& ^hjƩۀ9M)4P@ I-.QpN-*LLN,I-651 %3 y L - ML͍ y ~۠lA* 12 ?'3R7 3/]$HѠq>Y{ ;>o~+s_ U9u}o)Rho9|ui?:qk󉗻37HN7;4?#`ܱ ,\ll,@&HHD\ m@Hl&~:a:Vf ePВ30_ 6,4c{珞Aʐ[kM[wu3{O&c1/}=fTM,pZOm}.q]hv ~z N0z;C%kIn[/rps/~7PK[J/r݇^Ccertpairs/PanyPolicyMapping1to2CACertreversecrossCertificatePair.cpUT І?;7AUx3hbڵiA& ^hjƩۀ9M)4P@ I-.QpN-*LLN,I-651 %3 y L - ML͍ y ~۠lA* 12 ?'3R7 3/]$HѠq>Y{ ;>o~+s_ U9u}o)Rho9|ui?:qk󉗻37HN7;4?#`ܱ ,\ll,@&HHD\ m@Hl&~:a:Vf ePВ30_ 6,4c{珞Aʐ[kM[wu3{O&c1/}=fTM,pZOm}.q]hv ~z N0z;C%kIn[/rps/~7PK[J/>#!=@certpairs/pathLenConstraint0CACertforwardcrossCertificatePair.cpUT І?;7AUx3hbj[dTg|3#/VGw^FFVVCnN6P6a`C) KX0$D9$3-39$P@$,RT tK/2504014415725Dxo тĒ <⒢̼gGgde`ne0hdjld8[z>C,>p^_zǔ~kB]N[voGCE /KRpS [ Z"S}n.uwtm3V~fyޠ@Ye 9WtRǻլ==_Ȃ𱈱(le,+YkڟU?][mgd46q_Eπ+̓1(nh )0`RL h k^{g䰖eU2iyR둞בO>lQ)0sH[$;sbզ;NMTض@fϞuϴ\ݭ-Fo{͑xmUܷPK[J/G=@certpairs/pathLenConstraint0CACertreversecrossCertificatePair.cpUT І?;7AUx3hbj[dTg|3#/VGw^FFVVCnN6P6a`C) KX0$D9$3-39$P@$,RT tK/2504014415725Dxo тĒ <⒢̼gGgde`ne0hdjld8[z>C,>p^_zǔ~kB]N[voGCE /KRpS [ Z"S}n.uwtm3V~fyޠ@Ye 9WtRǻլ==_Ȃ𱈱(le,+YkڟU?][mgd46q_Eπ+̓1(nh )0`RL h k^{g䰖eU2iyR둞בO>lQ)0sH[$;sbզ;NMTض@fϞuϴ\ݭ-Fo{͑xmUܷPK[J/@ϥ7Dcertpairs/pathLenConstraint0subCA2CertforwardcrossCertificatePair.cpUT І?;7AUx3hbǠàf&F&&F6^6N6, l̡,lLR `HjqsjQIfZfrbIj HYX $'59?(13@@N JkKUJ $XU\hd8/ ̍ L B"^RU<@iW?eSS8(];ݽ-vL}ײdRk\^XĴznmR::L='Lްy3YKT/?ћCjLŮsr21320.12CVE@Ab /Hq_Eπ+̓1(nh)d5`Rh V]';4*ߵ`w'3MSK'mL?v|ɹM>2k*3rLtN2k*3rLtN!lWr[Y+ǰp[*%3#*7dY$ Dy2]ެFϪe-6)cc_6;ԯ=2I32gaF 8"`gƕ 7`4I0)xf5eν\5\JV~v꭪_U|Sqfc2n̖G=*ۻen ںͮdEF֩1#e)bάc{Q;&ۺ e~?:U<PK[J/X4Ccertpairs/pathLenConstraint0subCACertreversecrossCertificatePair.cpUT І?;7AUx3hb_mna3##/VGw^FFVVOCnN6P6a`C) KX0$D9$3-39$P@$,,ZXᓚ真W\RWbh 'k`h`bhihbjnd%k5!*EyUX*.M8+ ̍ L {O|5'lpHT![?ߌr7wFY3sz#}WS|5ʢ^Tލ;war=o4_]xu>!lWr[Y+ǰp[*%3#*7dY$ Dy2]ެFϪe-6)cc_6;ԯ=2I32gaF 8"`gƕ 7`4I0)xf5eν\5\JV~v꭪_U|Sqfc2n̖G=*ۻen ںͮdEF֩1#e)bάc{Q;&ۺ e~?:U<PK[J/->@certpairs/pathLenConstraint1CACertforwardcrossCertificatePair.cpUT І?;7AUx3hbj[dTg|3#/VGw^FFVVCnN6P6a`C) KX0$D9$3-39$P@$,RT tK/2504014415725Dxo тĒ <⒢̼CgGgde`ne0hdjldɓ2Z T~aO[&ܯ\I|Z0Ng6JkDo=&t_sB/)6#Ľ j ~Uf0ksEq)yl^,Hȭ>ά=71]CH>4?#` ,|L{T]<\PK[J/&>@certpairs/pathLenConstraint1CACertreversecrossCertificatePair.cpUT І?;7AUx3hbj[dTg|3#/VGw^FFVVCnN6P6a`C) KX0$D9$3-39$P@$,RT tK/2504014415725Dxo тĒ <⒢̼CgGgde`ne0hdjldɓ2Z T~aO[&ܯ\I|Z0Ng6JkDo=&t_sB/)6#Ľ j ~Uf0ksEq)yl^,Hȭ>ά=71]CH>4?#` ,|L{T]<\PK[J/W0Ccertpairs/pathLenConstraint1subCACertforwardcrossCertificatePair.cpUT І?;7AUx3hb_mna3#qjy}eddee046dceaf 62qCRKSJ22KR d@r¢%>yy%Ey% Ύr&&FQ⼆\R4X%Ū$m`Ȱj\Cw_eGrI97׾IGҍo5ݞumgy92Oe1 sU߽b޸9)J8~*xh5mwnRqtRwT:k Ks1ۜIY;<оg}ۀ$l WBc*P܀р$! Rj *r*noNX*?{ c/݌=?[3{~.W=q~{Ů 007{aa]! 4g睫 )4SGWU14/EaPPK[J/~(0Ccertpairs/pathLenConstraint1subCACertreversecrossCertificatePair.cpUT І?;7AUx3hb_mna3#qjy}eddee046dceaf 62qCRKSJ22KR d@r¢%>yy%Ey% Ύr&&FQ⼆\R4X%Ū$m`Ȱj\Cw_eGrI97׾IGҍo5ݞumgy92Oe1 sU߽b޸9)J8~*xh5mwnRqtRwT:k Ks1ۜIY;<оg}ۀ$l WBc*P܀р$! Rj *r*noNX*?{ c/݌=?[3{~.W=q~{Ů 007{aa]! 4g睫 )4SGWU14/EaPPK[J/2(Q;@certpairs/pathLenConstraint6CACertforwardcrossCertificatePair.cpUT І?;7AUx3hbj[dTg|3#/VGw^FFVVCnN6P6a`C) KX0$D9$3-39$P@$,RT tK/2504014415725Dxo тĒ <⒢̼3gGgde`ne0hdjld].#-ˬ&dfrGgy#f=Xj}rUcfG*{dHol'" hKgΚFEgoKzh0m_cEJ,NAgu%+>y]$kLΟĽ j ~Uf0ksEq)yl^,H-K/ZliU|^| i~F,,Hc3X xظ<SB aB6 RYd>k&۸Vz[ׇn^/.(mn| ee73QMLRl-;8izunncPK[J/Kl;@certpairs/pathLenConstraint6CACertreversecrossCertificatePair.cpUT І?;7AUx3hbj[dTg|3#/VGw^FFVVCnN6P6a`C) KX0$D9$3-39$P@$,RT tK/2504014415725Dxo тĒ <⒢̼3gGgde`ne0hdjld].#-ˬ&dfrGgy#f=Xj}rUcfG*{dHol'" hKgΚFEgoKzh0m_cEJ,NAgu%+>y]$kLΟĽ j ~Uf0ksEq)yl^,H-K/ZliU|^| i~F,,Hc3X xظ<SB aB6 RYd>k&۸Vz[ׇn^/.(mn| ee73QMLRl-;8izunncPK[J/9Dcertpairs/pathLenConstraint6subCA0CertforwardcrossCertificatePair.cpUT І?;7AUx3hbߠ۠f&F&&FF^6N6, l̡,lLR `HjqsjQIfZfrbIj HYX $'59?(13L@N JkKUJ $XU\͠q>_Y{ ;M|m~\Ge5QwĹhW/86p]SϾY_?}?]0w]ixi>Y/)᥆7$MZS_C,eWo;mK21320.75CVE@Adn%YU|*V/Y>1&g K-L`gdA6q_Eπ+̓1(nh )0`RL hq eiNPr\2X OUԴU&N.x/M~'9^(;Ӿ  <]<4I4WA-%g sj3 {hfuYi%0ˢPK[J/Ԝ9Dcertpairs/pathLenConstraint6subCA0CertreversecrossCertificatePair.cpUT І?;7AUx3hbߠ۠f&F&&FF^6N6, l̡,lLR `HjqsjQIfZfrbIj HYX $'59?(13L@N JkKUJ $XU\͠q>_Y{ ;M|m~\Ge5QwĹhW/86p]SϾY_?}?]0w]ixi>Y/)᥆7$MZS_C,eWo;mK21320.75CVE@Adn%YU|*V/Y>1&g K-L`gdA6q_Eπ+̓1(nh )0`RL hq eiNPr\2X OUԴU&N.x/M~'9^(;Ӿ  <]<4I4WA-%g sj3 {hfuYi%0ˢPK[J/0"8Dcertpairs/pathLenConstraint6subCA1CertforwardcrossCertificatePair.cpUT І?;7AUx3hbߠ۠f&F& 2ejh`im&l(e p (8de&'Ȁ䘅E K2|RK3J y L - ML͍ y [dJUťIΎ`0`!߫g7l1D1;i|J'j-Ib%kEO}B]e>_|Uśm{xKa\ݔoC S^=^9y\s)hU) whp:Oebfd`\\oPk 2X-K/ZliU|^ |,b,".&(ݿXU| i~F,,d3X xظ<SB aB6 Ȉד\h͛l=:rvb;s,`[qR_NcfZ\[ZPK[J/k8Dcertpairs/pathLenConstraint6subCA1CertreversecrossCertificatePair.cpUT І?;7AUx3hbߠ۠f&F& 2ejh`im&l(e p (8de&'Ȁ䘅E K2|RK3J y L - ML͍ y [dJUťIΎ`0`!߫g7l1D1;i|J'j-Ib%kEO}B]e>_|Uśm{xKa\ݔoC S^=^9y\s)hU) whp:Oebfd`\\oPk 2X-K/ZliU|^ |,b,".&(ݿXU| i~F,,d3X xظ<SB aB6 Ȉד\h͛l=:rvb;s,`[qR_NcfZ\[ZPK[J/c-=Dcertpairs/pathLenConstraint6subCA4CertforwardcrossCertificatePair.cpUT І?;7AUx3hbߠ۠f&F&&Ff^6N6, l̡,lLR `HjqsjQIfZfrbIj HYX $'59?(13L@N JkKUJ $XU\hb8/ ̍ L {:r$kA12" O޵AvaU?V5vf M?͗oqvCua]b%3u~wg#-ۥ\g( \XTqBEFsfcޠ@Ye [l_ngV)bKZ dA XXD 21\!0vTPolGfxlzLsՑSl&lPK[J/dv;=Dcertpairs/pathLenConstraint6subCA4CertreversecrossCertificatePair.cpUT І?;7AUx3hbߠ۠f&F&&Ff^6N6, l̡,lLR `HjqsjQIfZfrbIj HYX $'59?(13L@N JkKUJ $XU\hb8/ ̍ L {:r$kA12" O޵AvaU?V5vf M?͗oqvCua]b%3u~wg#-ۥ\g( \XTqBEFsfcޠ@Ye [l_ngV)bKZ dA XXD 21\!0vTPolGfxlzLsՑSl&lPK[J/u;Hcertpairs/pathLenConstraint6subsubCA00CertforwardcrossCertificatePair.cpUT І?;7AUx3hbiAd&?  x8<ھ222rp1 3JH8\‚!% ΩE%iɉ%ņJ 9faɂĒ <⒢̼3$gG9q^CCKCSs#(q^CdA ֩@nF~bde`ne0hdjldؾUWO5%o9}/S9}`HOYarjfͶ->{nm[tO)am"/x_[&[x~U‹l豝Z@rYNtmСlu&fF@*H50yT<hXRoe~er݌Y>1gGsJ5ǀs| i~F,,d3X xظ<SB aB6 Ȁ{nm[tO)am"/x_[&[x~U‹l豝Z@rYNtmСlu&fF@*H50yT<hXRoe~er݌Y>1gGsJ5ǀs| i~F,,d3X xظ<SB aB6 Ȁ2_Ctf^efm+5kZB^Q~ޠ@Ye jmywG*Y>1|thm>4?#`L ,|\txS;'>?aٹm[ugu!e1wԎ2J W̴xY'3W^Jge0ctN+moYͲzj.L]OUU,EDܛPK[J/aKQ7Hcertpairs/pathLenConstraint6subsubCA11CertreversecrossCertificatePair.cpUT І?;7AUx3hbiAd&?  x8<ھ222rp1 3JH8\‚!% ΩE%iɉ%ņJ 9faɂĒ <⒢̼3$gGC9q^CCKCSs#(q^CdA ֩@nFC~bde`ne0hdjld[ߵ<-CMmzFq3ZR$lflob[6S,6KY{]_ɤGڥ t m ^[3>2_Ctf^efm+5kZB^Q~ޠ@Ye jmywG*Y>1|thm>4?#`L ,|\txS;'>?aٹm[ugu!e1wԎ2J W̴xY'3W^Jge0ctN+moYͲzj.L]OUU,EDܛPK[J/G (9Hcertpairs/pathLenConstraint6subsubCA41CertforwardcrossCertificatePair.cpUT І?;7AUx3hbiAd&?  x8<ھ222rp1 3JH8\‚!% ΩE%iɉ%ņJ 9faɂĒ <⒢̼3$gG9q^CCKCSs#(q^CdA ֩@nFC~bde`ne0hdjld82ͯK&F+),Q+&xnhƁTEgtY F`޿yÒ ]{`u6`򂂙c'Z8Ffޏڷ=N,e-qOWN} im~l&3#zZy_dY$ D}3܎P%PK[J/Eq9Hcertpairs/pathLenConstraint6subsubCA41CertreversecrossCertificatePair.cpUT І?;7AUx3hbiAd&?  x8<ھ222rp1 3JH8\‚!% ΩE%iɉ%ņJ 9faɂĒ <⒢̼3$gG9q^CCKCSs#(q^CdA ֩@nFC~bde`ne0hdjld82ͯK&F+),Q+&xnhƁTEgtY F`޿yÒ ]{`u6`򂂙c'Z8Ffޏڷ=N,e-qOWN} im~l&3#zZy_dY$ D}3܎P%PK[J/,]9Lcertpairs/pathLenConstraint6subsubsubCA11XCertforwardcrossCertificatePair.cpUT І?;7AUx3hbZiA f\hƩ Аۀ9M)4P@ I-.QpN-*LLN,I-6T3P1 $d9%f敘)&8A8!2 x+ 4 V*jkA|d120724v2562l=͹X"~QVjEN.W cclӃlR3,5>@(?~L34?#` ,|@(?~L34?#` ,|[vwi=zxqqA8\H? 0F A|>66T?HBՀHE<30Tvg,1ՌgwpO~.\!uSlX;n5>f1_Q/rWLlj{d0G*D>:]k :9W(bt+i> PK[J/gD3:Lcertpairs/pathLenConstraint6subsubsubCA41XCertreversecrossCertificatePair.cpUT І?;7AUx3hbZiA f\hƩ Аۀ9M)4P@ I-.QpN-*LLN,I-6T3P1 $d9%f敘)&8A8!2 x+ 4 V*jkA|d120724v2562y8~)[I)4gUlf[vwi=zxqqA8\H? 0F A|>66T?HBՀHE<30Tvg,1ՌgwpO~.\!uSlX;n5>f1_Q/rWLlj{d0G*D>:]k :9W(bt+i> PK[J/BH;certpairs/PoliciesP1234CACertforwardcrossCertificatePair.cpUT І?;7AUx3hbڹiAF ZĨlƩۀ9M)4P@ I-.QpN-*LLN,I-651 %3 y L - ML͍ y c LL-V0426Qpv4htFV^NFFlyVI|ڷ#MlޟbV0PQGm̑O+,~kxɹݴM]9 Zvk:Mk ЁEZrfq,}YZ)ˌu9dV盖 21320.njи@Ye 9WtRǻլ==_Ȃ𱈱dg$\BB.>4?#`8 ,Vlgyd`eeSv/m|lT}Cvld~gsl6Dg:PK[J/aBH;certpairs/PoliciesP1234CACertreversecrossCertificatePair.cpUT І?;7AUx3hbڹiAF ZĨlƩۀ9M)4P@ I-.QpN-*LLN,I-651 %3 y L - ML͍ y c LL-V0426Qpv4htFV^NFFlyVI|ڷ#MlޟbV0PQGm̑O+,~kxɹݴM]9 Zvk:Mk ЁEZrfq,}YZ)ˌu9dV盖 21320.njи@Ye 9WtRǻլ==_Ȃ𱈱dg$\BB.>4?#`8 ,Vlgyd`eeSv/m|lT}Cvld~gsl6Dg:PK[J/?G4Bcertpairs/PoliciesP1234subCAP123CertforwardcrossCertificatePair.cpUT І?;7AUx3hbZiAB ZhƩՐۀ9M)4P@ I-.QpN-*LLN,I-1 d&g+(8;ȉZD"s |F@b5ťIΎ A|do020724v2562,,ɚr%ڗhU\yeǹ /zcڬ +bNq˨S%ܮY(sKbwmU:u˵{ҺlqJe}&fFō3 =""a bݟ9DsU>  dA XXDU7Kvx6*8٭MH? 0 A|-66T# l$ 2ՀHf`3[qm*'DUktF2>\SoHޑt3ˊSK>AĿ6[Z醎̵GL2xt+|B/)J7L'Ha  dA XXDU7Kvx6*8٭MH? 0 A|-66T# l$ 2ՀHf`3[qm*'DUktF2>\SoHޑt3ˊSK>AĿ6[Z醎̵GL2xt+|B/)J7L'HaseR 7ln^QBzӗ<.6,2Oiwvݿ& wSe>So7_[їک$l" Cʺ ]**hWqgR7v4vOVE@Ad[udgOM>4ZnȂ𱈱seR 7ln^QBzӗ<.6,2Oiwvݿ& wSe>So7_[їک$l" Cʺ ]**hWqgR7v4vOVE@Ad[udgOM>4ZnȂ𱈱Y{ ;vd2ںˎoʅ{<7Rl@-fvdoj.Xa?^bϴ/.;5[ 68'gIjXȟY?$4]pEWi{e&fFō = "a ;nSUx7ؼ+Y>1 ξqߦ(wtH? 0 A|-66T# l$ 2ՀH* ^#Z``hb冟{V+Td;W8(]. OM}5Ǚu.Jbcҍy&M5+GE3n|Y+y_jjQ|/GW 36~wvo╬^OnL2 PK[J/&kE:certpairs/PoliciesP123CACertreversecrossCertificatePair.cpUT І?;7AUx3hbZiA" ^ĨbƩۀ9M)4P@ I-.QpN-*LLN,I-651 %3 y L - ML͍ y . i A ?'393X!XѠq>Y{ ;vd2ںˎoʅ{<7Rl@-fvdoj.Xa?^bϴ/.;5[ 68'gIjXȟY?$4]pEWi{e&fFō = "a ;nSUx7ؼ+Y>1 ξqߦ(wtH? 0 A|-66T# l$ 2ՀH* ^#Z``hb冟{V+Td;W8(]. OM}5Ǚu.Jbcҍy&M5+GE3n|Y+y_jjQ|/GW 36~wvo╬^OnL2 PK[J/~8@certpairs/PoliciesP123subCAP12CertforwardcrossCertificatePair.cpUT І?;7AUx3hbiA&Ɵ  x8<ھ222rp1 3JH8\‚!% ΩE%iɉ%ņ 9fabC#cgG9q^CCKCSs#(q^CdBlC42hFV^NFa9umֹݽ4ʱK չg<e~.@MEǶmJ3x/w\;:҇-. !=9T?5pz6'6[a(3Ecertpairs/PoliciesP123subsubCAP12P1CertreversecrossCertificatePair.cpUT І?;7AUx3hbߠ۠f&F&&FF^6N6, ^l̡,lLR `HjqsjQIfZfrbIj,HYX, ?'393X!X42504014415725Do.i `4G#+sc/Ac'Sc#Ý2'W.6Aѩ5U\9S~%^]څ}W^`3ߠs*tTW*j?FbOUHw)I:[v&X7cX[v3LEy#3#*yOdY$ D9ߙ,;x *""9r iLj2I32gaF"8"`gƕ 7`4I0)fߪ_dgݓ6N|._p֭ t QV$1H^ˁ~LN5U}0w=57)^`N:ٙY< JMmTpVlk,ܕ_1NгxsPK[J/[ k3Ecertpairs/PoliciesP123subsubCAP12P2CertforwardcrossCertificatePair.cpUT І?;7AUx3hbߠ۠f&F& 2ejh`em&l(e p (8de&'Ȃ䘅s23S K,9q^CCKCSs#(q^Cd?v(Aư f]A|d020724v2562$kZZ;s|(AmiĴ6Եwؾ`xڛu'V=' + ༙Txeǫ~g?+w68Z^9GVJε?T}""a ΡdY5dz6fxVY>17˳,H z$l WBc*P܀ɀ$! Rj * v y¹._Wڃo8))lzRۼsU9ڜ<%yFcS{&pe}u /i.rEq;K3ޞ#7!{'GtYYPK[J/\r3Ecertpairs/PoliciesP123subsubCAP12P2CertreversecrossCertificatePair.cpUT І?;7AUx3hbߠ۠f&F& 2ejh`em&l(e p (8de&'Ȃ䘅s23S K,9q^CCKCSs#(q^Cd?v(Aư f]A|d020724v2562$kZZ;s|(AmiĴ6Եwؾ`xڛu'V=' + ༙Txeǫ~g?+w68Z^9GVJε?T}""a ΡdY5dz6fxVY>17˳,H z$l WBc*P܀ɀ$! Rj * v y¹._Wڃo8))lzRۼsU9ڜ<%yFcS{&pe}u /i.rEq;K3ޞ#7!{'GtYYPK[J/pSH:Jcertpairs/PoliciesP123subsubsubCAP12P2P1CertforwardcrossCertificatePair.cpUT І?;7AUx3hbiAT&  x8<ھ222rp1 3JH8\‚!% ΩE%iɉ%ņ*J 9fabC#c$ rvr y L - ML͍ y ![iP; #{^γgWjyaxW;U.RZr__~)JA^:zW^<4>*,~&Vc~IYeST޳եba-?t=8LjrKN8KW*,~&Vc~IYeST޳եba-?t=8LjrKN8KWcertpairs/PoliciesP12subCAP1CertforwardcrossCertificatePair.cpUT І?;7AUx3hbj]hTkl3##/VGw^FFVVgCnN6P6a`C) KX0$D9$3-39$P@ $,Z`hh 'k`h`bhihbjnd%k5 Yi%"(&9;4G#+sc/Ac'Sc#G,/?"GgA>[˗zkOK\fkբ3smQ1OvJl/{zJ t煶u^yRyLsn.vR6. Ľ k ^UfXԗWv}ؒ-GpOY>1۝o1{o[2I32gaF8"`gƕ 7`4I0)eJضW,e&&sJ8vgm } b̜^\uGv,۔,!We3=좞9Yj٣eոw\fN\㙯;Udl4U9[%kGVځ PK[J/g 1>certpairs/PoliciesP12subCAP1CertreversecrossCertificatePair.cpUT І?;7AUx3hbj]hTkl3##/VGw^FFVVgCnN6P6a`C) KX0$D9$3-39$P@ $,Z`hh 'k`h`bhihbjnd%k5 Yi%"(&9;4G#+sc/Ac'Sc#G,/?"GgA>[˗zkOK\fkբ3smQ1OvJl/{zJ t煶u^yRyLsn.vR6. Ľ k ^UfXԗWv}ؒ-GpOY>1۝o1{o[2I32gaF8"`gƕ 7`4I0)eJضW,e&&sJ8vgm } b̜^\uGv,۔,!We3=좞9Yj٣eոw\fN\㙯;Udl4U9[%kGVځ PK[J/2M55Ccertpairs/PoliciesP12subsubCAP1P2CertforwardcrossCertificatePair.cpUT І?;7AUx3hb_mna3##/VGw^FFVVCnN6P6a`C) KX0$D9$3-39$P@$,,Z`hP\`h 'k`h`bhihbjnd%k5%&%M6A- 02hFV^NFu}DPPr ˱Igvo]Psϧhȷr!?UoWWÌoT.ڼW6FW=g[0eNC7E[gsW={J<certpairs/PoliciesP2subCA2CertforwardcrossCertificatePair.cpUT І?;7AUx3hb^nlf3#/VGw^FFVVkCnN6P6a`C) KX0$D9$3-39$P$,h 'k`h`bhihbjnd%k5p#piIB9ə F ťIΎF`Ȱe˹Js;bF\_rHdR:޷1}H|ɧ8jN=/dsF-反R+jwwW\wr_ʊ\}6XıRV~ՑOY 7:O Kx:3#nydY$ D-k:}Ğ.Mr@EE[={jy/d 8|e@W`WBc*P܀ɀ$! Rj @-OYI3rwo3/ ~[ix1ne%',+֐.3kѶ.j<certpairs/PoliciesP2subCA2CertreversecrossCertificatePair.cpUT І?;7AUx3hb^nlf3#/VGw^FFVVkCnN6P6a`C) KX0$D9$3-39$P$,h 'k`h`bhihbjnd%k5p#piIB9ə F ťIΎF`Ȱe˹Js;bF\_rHdR:޷1}H|ɧ8jN=/dsF-反R+jwwW\wr_ʊ\}6XıRV~ՑOY 7:O Kx:3#nydY$ D-k:}Ğ.Mr@EE[={jy/d 8|e@W`WBc*P܀ɀ$! Rj @-OYI3rwo3/ ~[ix1ne%',+֐.3kѶ.jM*)1]9Yp32ga8 u66T?HBՀHE)30T265vn:0N̓v7Yk=a!sn J,;cbß84鿓Ԏll+BM{ͳG ߤLT[nxRS"2AG\^7b1 웹n&PK[J/zJ/~;certpairs/PoliciesP2subCACertreversecrossCertificatePair.cpUT І?;7AUx3hbZTfTdx{3#/VGw^FFVVkCnN6P6a`C) KX0$D9$3-39$P$,h 'k`h`bhihbjnd%k5p%p`@~NfrfjBBqiКȮfde`ne0hdjld8`ŪetXE!Y3w,~ꜩzV=+[VW'xPYudr\3~4HQ4tTjes]SSZ7T_LSU\4qoE&fF5U@*H5l[tЉ=+]ߟ%:币,HȓU7>M*)1]9Yp32ga8 u66T?HBՀHE)30T265vn:0N̓v7Yk=a!sn J,;cbß84鿓Ԏll+BM{ͳG ߤLT[nxRS"2AG\^7b1 웹n&PK[J/X?8certpairs/PoliciesP3CACertforwardcrossCertificatePair.cpUT І?;7AUx3hbYabv3#/VGw^FFVVCnN6P6a`C) KX0$D9$3-39$P@$,RT tK/2504014415725D8o(bcgGfde`ne0hdjldXs͢YJW;k9ܮ}}eY}^nu1Ϭ>Ouy|y]}"Gw vתe{jj=RA׼>Iv ~/{skȳMujVvgt Og21320.n6h0:_VE@Awyԫny5kOW |,b,"}{BS>\vRK.i{ @YXf +q%y0 A @ ( P"JIrrSk͋tf)[W,BK8Iaadz+SvHsoLmly;SAA{oe>a4C)˯Qjܗs3d#׭ZZޞ/PK[J/6JS&?8certpairs/PoliciesP3CACertreversecrossCertificatePair.cpUT І?;7AUx3hbYabv3#/VGw^FFVVCnN6P6a`C) KX0$D9$3-39$P@$,RT tK/2504014415725D8o(bcgGfde`ne0hdjldXs͢YJW;k9ܮ}}eY}^nu1Ϭ>Ouy|y]}"Gw vתe{jj=RA׼>Iv ~/{skȳMujVvgt Og21320.n6h0:_VE@Awyԫny5kOW |,b,"}{BS>\vRK.i{ @YXf +q%y0 A @ ( P"JIrrSk͋tf)[W,BK8Iaadz+SvHsoLmly;SAA{oe>a4C)˯Qjܗs3d#׭ZZޞ/PK[J/}>Bcertpairs/pre2000CRLnextUpdateCACertforwardcrossCertificatePair.cpUT І?;7AUx3hbj_lTob3##/VGw^FFVVCnN6P6a`C) KX0$D9$3-39$P@$,RT tK/2504014415725DoɂT# ԊЂ gG^`de`ne0hdjldr,`/Ef;rܬO/eV3nٷ7? |?=Rz/ovUYƽ?ޚ/ׁN\vD|KGވ\4?#`ı ,|<-PNW 7'sOS#r.19yt%'x_pq~PK[J/JJ>Bcertpairs/pre2000CRLnextUpdateCACertreversecrossCertificatePair.cpUT І?;7AUx3hbj_lTob3##/VGw^FFVVCnN6P6a`C) KX0$D9$3-39$P@$,RT tK/2504014415725DoɂT# ԊЂ gG^`de`ne0hdjldr,`/Ef;rܬO/eV3nٷ7? |?=Rz/ovUYƽ?ޚ/ׁN\vD|KGވ\4?#`ı ,|<-PNW 7'sOS#r.19yt%'x_pq~PK[J/1 sGDcertpairs/requireExplicitPolicy0CACertforwardcrossCertificatePair.cpUT І?;7AUx3hbiA$& u x8<ھ2228rp1 3JH8\‚!% ΩE%iɉ%ņ 9faRc^rF~8A8!2x  6HfVd&gJgG^`de`ne0hdjld㚣s_Z.{.L[luRwMordE,?ֲS3 .bꉵ /0d?୛v$yjpÖ{ڊpu u>4?#`Ա ,|M)X>˿xaoUJ$RQ}o}j;$PK[J/MGDcertpairs/requireExplicitPolicy0CACertreversecrossCertificatePair.cpUT І?;7AUx3hbiA$& u x8<ھ2228rp1 3JH8\‚!% ΩE%iɉ%ņ 9faRc^rF~8A8!2x  6HfVd&gJgG^`de`ne0hdjld㚣s_Z.{.L[luRwMordE,?ֲS3 .bꉵ /0d?୛v$yjpÖ{ڊpu u>4?#`Ա ,|M)X>˿xaoUJ$RQ}o}j;$PK[J/6Gcertpairs/requireExplicitPolicy0subCACertforwardcrossCertificatePair.cpUT І?;7AUx3hbiASALLLlZmmyYY | 8٘CY؄B $@.aԢ̴ĒbC%dQjaifQkEANfrfI@>4Ppv4504014415725Do2:&ml%FV^NF]BW>h ~"c)ܟx[y_^K͜ut%M7Ə*1a3i Q}Re>4?#`t ,|3i Q}Re>4?#`t ,|!/MJk~1 ;]^|O+{bdUĞܷ*<!/MJk~1 ;]^|O+{bdUĞܷ*<5}+.MZ8S ̍ L {o+0ӽ{Yf?U8Ʀ9o灹lDV.*8›tBՏ~ {WʬH\^XYfޥ3;M;LDELN1[]uäC=7lr!BjB&fF5U@*H5|~6s[ۑܰ4όW@EEds*R/956)| i~F,,d3X xظ<S aBVf Pe6hߑh%?ﳤ..2HcWzӰ2\ KPK[J/9Hcertpairs/requireExplicitPolicy10subCACertreversecrossCertificatePair.cpUT І?;7AUx3hbiAD&_  x8<ھ222rp1 3JH8\‚!% ΩE%iɉ%ņ 9fa̢T׊̒| Uihh 'k`h`bhihbjnd%k5$>5}+.MZ8S ̍ L {o+0ӽ{Yf?U8Ʀ9o灹lDV.*8›tBՏ~ {WʬH\^XYfޥ3;M;LDELN1[]uäC=7lr!BjB&fF5U@*H5|~6s[ۑܰ4όW@EEds*R/956)| i~F,,d3X xظ<S aBVf Pe6hߑh%?ﳤ..2HcWzӰ2\ KPK[J/H 8Kcertpairs/requireExplicitPolicy10subsubCACertforwardcrossCertificatePair.cpUT І?;7AUx3hbiAt fXhƩ Аۀ9M)4P@ I-.QpN-*LLN,I-6T3P1 fVd&gJC$gG9q^CCKCSs#(q^CdAVjCTc%^cde`ne0hdjldX):dH _ENZ^;Nl~&b`iI(-(gx;MoEMe%I4;;1XmZ>k˗_]HɗYo-4H}ݿoY2Is<^p?)-u|Se]ӷ퓧ojb=k nPK[J/LY8Kcertpairs/requireExplicitPolicy10subsubCACertreversecrossCertificatePair.cpUT І?;7AUx3hbiAt fXhƩ Аۀ9M)4P@ I-.QpN-*LLN,I-6T3P1 fVd&gJC$gG9q^CCKCSs#(q^CdAVjCTc%^cde`ne0hdjldX):dH _ENZ^;Nl~&b`iI(-(gx;MoEMe%I4;;1XmZ>k˗_]HɗYo-4H}ݿoY2Is<^p?)-u|Se]ӷ퓧ojb=k nPK[J/t69Ncertpairs/requireExplicitPolicy10subsubsubCACertforwardcrossCertificatePair.cpUT І?;7AUx3hbZiA\ f[hƩ Đۀ9M)4P@ I-.QpN-*LLN,I-64P1 +fVd&gJC$ rv4504014415725DoVeB,nAFV^NF]*?E,n)Ko\Z mCJ+Y첓;pBE+1@%3#*ydY$ Dr3 [ˡf3o4)ccrh֕˒_ZaxH? 0Z A|>66T?HBՀH>30T&7?^ƽ~gaHDGJG~|LH\_̅S/tXpa6w16BTG䫻/9[L˼r:Eԝ\_+/{MLĢK[ [1uPK[J/V9Ncertpairs/requireExplicitPolicy10subsubsubCACertreversecrossCertificatePair.cpUT І?;7AUx3hbZiA\ f[hƩ Đۀ9M)4P@ I-.QpN-*LLN,I-64P1 +fVd&gJC$ rv4504014415725DoVeB,nAFV^NF]*?E,n)Ko\Z mCJ+Y첓;pBE+1@%3#*ydY$ Dr3 [ˡf3o4)ccrh֕˒_ZaxH? 0Z A|>66T?HBՀH>30T&7?^ƽ~gaHDGJG~|LH\_̅S/tXpa6w16BTG䫻/9[L˼r:Eԝ\_+/{MLĢK[ [1uPK[J/c)GDcertpairs/requireExplicitPolicy2CACertforwardcrossCertificatePair.cpUT І?;7AUx3hbiA$&  x8<ھ2228rp1 3JH8\‚!% ΩE%iɉ%ņ 9faRc^rF~8A8!2x  6HfVd&gJ#gG^`de`ne0hdjld۩>j>=?٧R,=p3&tsi(k wm*lT3ٵW.:wo 3[_O-}dd}Og_Xa)xE&fFō}@*H5ι8z< 6fi@EE𐍟iw{3Yj>=?٧R,=p3&tsi(k wm*lT3ٵW.:wo 3[_O-}dd}Og_Xa)xE&fFō}@*H5ι8z< 6fi@EE𐍟iw{3Y4Rpv4504014415725Do2:&ml%FV^NF}\=٢Z& ǨL̰kos<>&Ûhkuޒ禟4S~t[,o쓗Μؼ~QS ڬ=I[ٙ?xebfd`\\cPe 2X𳞃>U|(F h1)ccyc+}d`gdH6q_Eπ+̓1(nh)d5`Rh y'3ED{U{|BKgD;я9y U9?M—oeF6?H.{,U/oX;?^ijE"_8;?i-~b͆?0m['wbmKPK[J/:Gcertpairs/requireExplicitPolicy2subCACertreversecrossCertificatePair.cpUT І?;7AUx3hbiASALLLlZmmyYY | 8٘CY؄B $@.aԢ̴ĒbC%dQjaifQkEANfrfI@>4Rpv4504014415725Do2:&ml%FV^NF}\=٢Z& ǨL̰kos<>&Ûhkuޒ禟4S~t[,o쓗Μؼ~QS ڬ=I[ٙ?xebfd`\\cPe 2X𳞃>U|(F h1)ccyc+}d`gdH6q_Eπ+̓1(nh)d5`Rh y'3ED{U{|BKgD;я9y U9?M—oeF6?H.{,U/oX;?^ijE"_8;?i-~b͆?0m['wbmKPK[J/g.GDcertpairs/requireExplicitPolicy4CACertforwardcrossCertificatePair.cpUT І?;7AUx3hbiA$& u x8<ھ2228rp1 3JH8\‚!% ΩE%iɉ%ņ 9faRc^rF~8A8!2x  6HfVd&gJgG^`de`ne0hdjldxMjoMC;MkXɴ@? [40cN7ٕY_&Hu2`*wg-/^X\׻4-CW_W+xAsLM6|ulF?+]6`U:3#>nyOdY$ D~\mwJjW|e R""Z7a M p|o>4?#`Ա ,|qڑPK[J/GDcertpairs/requireExplicitPolicy4CACertreversecrossCertificatePair.cpUT І?;7AUx3hbiA$& u x8<ھ2228rp1 3JH8\‚!% ΩE%iɉ%ņ 9faRc^rF~8A8!2x  6HfVd&gJgG^`de`ne0hdjldxMjoMC;MkXɴ@? [40cN7ٕY_&Hu2`*wg-/^X\׻4-CW_W+xAsLM6|ulF?+]6`U:3#>nyOdY$ D~\mwJjW|e R""Z7a M p|o>4?#`Ա ,|qڑPK[J/ØE8Gcertpairs/requireExplicitPolicy4subCACertforwardcrossCertificatePair.cpUT І?;7AUx3hbiASALLLlZmmyYY | 8٘CY؄B $@.aԢ̴ĒbC%dQjaifQkEANfrfI@>4Qpv4504014415725Do2:&ml%FV^NFe;ٞ*t{9r{h=wɢ!W3vI˭([?a\H>%⽟CI/=0[=kv研qsoG}38ygJ^xqw21320.12zEVE@ADn >vX~3 |,b,"ʉ:~ڍ#@W`03aJh`L0$A Y Z|3ClLřn4Qpv4504014415725Do2:&ml%FV^NFe;ٞ*t{9r{h=wɢ!W3vI˭([?a\H>%⽟CI/=0[=kv研qsoG}38ygJ^xqw21320.12zEVE@ADn >vX~3 |,b,"ʉ:~ڍ#@W`03aJh`L0$A Y Z|3ClLřnth6Gx}۲f,g31320.12FVE@AD9ѢP3qߢ=ׯv^`QY>1}9k8}~rHp| i~F,,d3X xظ<S aBVf PejcmզIWeDvyQ~1LKq}OI;?!niǛOwF'yRvcSG8W?yѳھj bm`sM'e_qف j:VPK[J/B*9Jcertpairs/requireExplicitPolicy4subsubCACertreversecrossCertificatePair.cpUT І?;7AUx3hbiAT&  x8<ھ222rp1 3JH8\‚!% ΩE%iɉ%ņ 9fa̢T׊̒| UiP\h 'k`h`bhihbjnd%k5&F 5mX8c ̍ L nM+R~P.0;*&r/; 28{_Q}p?8ҏ7vQ~^|!V5~C>th6Gx}۲f,g31320.12FVE@AD9ѢP3qߢ=ׯv^`QY>1}9k8}~rHp| i~F,,d3X xظ<S aBVf PejcmզIWeDvyQ~1LKq}OI;?!niǛOwF'yRvcSG8W?yѳھj bm`sM'e_qف j:VPK[J/K9Mcertpairs/requireExplicitPolicy4subsubsubCACertforwardcrossCertificatePair.cpUT І?;7AUx3hbZiAl fYhƩ ؐۀ9M)4P@ I-.QpN-*LLN,I-60P1 fVd&gJ$ rv4504014415725Do&R%Bm=FV^NF7V}wެwW,̧/ڻ8-q_I]75mg5S]321320.n3h6DVE@Awyԫny5kOW |,b,"W~_{Gyһ @YXQf +q%y0  A @ "h`dErf`@.rIOAioZ*Y~rU JU)^&t?6: 3]\[o2q陧{fl{ڥM3ĴSRw5u޿kavV{jީ7APK[J/IwެwW,̧/ڻ8-q_I]75mg5S]321320.n3h6DVE@Awyԫny5kOW |,b,"W~_{Gyһ @YXQf +q%y0  A @ "h`dErf`@.rIOAioZ*Y~rU JU)^&t?6: 3]\[o2q陧{fl{ڥM3ĴSRw5u޿kavV{jީ7APK[J/ks7Gcertpairs/requireExplicitPolicy5subCACertforwardcrossCertificatePair.cpUT І?;7AUx3hbiASALLLlZmmyYY | 8٘CY؄B $@.aԢ̴ĒbC%dQjaifQkEANfrfI@>4Upv4504014415725Do2:&ml%FV^NF5k:׵3ƫHzv/]#\[DomDHЧݜѹ35lUXSP} *ݯLz3:?=~u'϶YBo UDK8Y^/}/_{j!>?nwȂ𱈱Lmh*Q}b; @YXf +q%y0  A @ -y}GI;VW s7׶s͊Ur ndTtz9-54Zzg"oԞŜY{•4Upv4504014415725Do2:&ml%FV^NF5k:׵3ƫHzv/]#\[DomDHЧݜѹ35lUXSP} *ݯLz3:?=~u'϶YBo UDK8Y^/}/_{j!>?nwȂ𱈱Lmh*Q}b; @YXf +q%y0  A @ -y}GI;VW s7׶s͊Ur ndTtz9-54Zzg"oԞŜY{•%NAт2Wd0ߋ5}Ľ k 䁾Uf0k=lwU ]ŲwȂ𱈱p=O[篿}+ݲ@W`03aJh`L0$A Y Z3Ce,붇3;J BsTjxӛCIc[JO^L.%y}&P~w.wu kx'uķyv/{-xϝ[kN=6*1{~{PK[J/U!8Jcertpairs/requireExplicitPolicy5subsubCACertreversecrossCertificatePair.cpUT І?;7AUx3hbiAT&  x8<ھ222rp1 3JH8\‚!% ΩE%iɉ%ņ 9fa̢T׊̒| UiP\h 'k`h`bhihbjnd%k5&F 5mX8c ̍ L M ݗ"=w6ݰ滕-˽[p3}ɢBmDU 9LMYJK;>%NAт2Wd0ߋ5}Ľ k 䁾Uf0k=lwU ]ŲwȂ𱈱p=O[篿}+ݲ@W`03aJh`L0$A Y Z3Ce,붇3;J BsTjxӛCIc[JO^L.%y}&P~w.wu kx'uķyv/{-xϝ[kN=6*1{~{PK[J/:;b8Mcertpairs/requireExplicitPolicy5subsubsubCACertforwardcrossCertificatePair.cpUT І?;7AUx3hbZiAl fYhƩ ؐۀ9M)4P@ I-.QpN-*LLN,I-60P1 fVd&gJS$ rv4504014415725Do&R%Bm=FV^NF=jS%]9,S>:{ 2uQw3Ƅ̑굆Iɛҗ, 48,v;WS|ڝqL&&^EWL,nl7 Cb6G6ymiU]y `-3#*ydY$ D'߾^n dA XXDV/ߢђ~rɢ?;jgdT6q_Eπ+̓1(nh)d5`Rhq uXԵ^= wӟ8 j f̂˯6e|KW@_i59_ 3eMH\[O\h{jlܼع*ك|uKxzU"+I2rg PK[J/ҵ8Mcertpairs/requireExplicitPolicy5subsubsubCACertreversecrossCertificatePair.cpUT І?;7AUx3hbZiAl fYhƩ ؐۀ9M)4P@ I-.QpN-*LLN,I-60P1 fVd&gJS$ rv4504014415725Do&R%Bm=FV^NF=jS%]9,S>:{ 2uQw3Ƅ̑굆Iɛҗ, 48,v;WS|ڝqL&&^EWL,nl7 Cb6G6ymiU]y `-3#*ydY$ D'߾^n dA XXDV/ߢђ~rɢ?;jgdT6q_Eπ+̓1(nh)d5`Rhq uXԵ^= wӟ8 j f̂˯6e|KW@_i59_ 3eMH\[O\h{jlܼع*ك|uKxzU"+I2rg PK[J/GoEDcertpairs/requireExplicitPolicy7CACertforwardcrossCertificatePair.cpUT І?;7AUx3hbiA$&  x8<ھ2228rp1 3JH8\‚!% ΩE%iɉ%ņ 9faRc^rF~8A8!2x  6HfVd&gJsgG^`de`ne0hdjldXp_ SO5 Pzz';Dk$m"Mk^&$fFm_׃L )Odۖ*~CɽbENE2xsu(W*ogbfd`\gm 2X+NW`j֞ dA XXD*>X)Iփg| @YXQf +q%y0  A @ "h`dGrf`@?`Nԝ<WfW=3wg鎾;J)p~BshԿ2ƚVsҥ}x,3ˎ#oɳ}(=dL& oJiT垙ls+'>3zyK`iPK[J/n_EDcertpairs/requireExplicitPolicy7CACertreversecrossCertificatePair.cpUT І?;7AUx3hbiA$&  x8<ھ2228rp1 3JH8\‚!% ΩE%iɉ%ņ 9faRc^rF~8A8!2x  6HfVd&gJsgG^`de`ne0hdjldXp_ SO5 Pzz';Dk$m"Mk^&$fFm_׃L )Odۖ*~CɽbENE2xsu(W*ogbfd`\gm 2X+NW`j֞ dA XXD*>X)Iփg| @YXQf +q%y0  A @ "h`dGrf`@?`Nԝ<WfW=3wg鎾;J)p~BshԿ2ƚVsҥ}x,3ˎ#oɳ}(=dL& oJiT垙ls+'>3zyK`iPK[J// $CJcertpairs/requireExplicitPolicy7subCARE2CertforwardcrossCertificatePair.cpUT І?;7AUx3hbZiAR [hƩאۀ9M)4P@ I-.QpN-*LLN,I-6T2P1 KfVd&gJsgG9q^CCKCSs#(q^CdA0iAa]qicA|d_120724v2562mUc[p7=4?#`l ,|4?#`l ,|dde`ne0hdjldRymerloT^!%p+g[ωs˫U,ڰbϿ\ |T*_E݄޵{dzΪ3;46 yh_)p_+fK@ߒ!^&fFō}@_*H54?#`̲ ,|m:^{XwSBUbԯn?&w */s0N_%*VWLwat_vG>]WyNU;?'3"QH"Mỹkӝ|PK[J/HPcertpairs/requireExplicitPolicy7subsubCARE2RE4CertreversecrossCertificatePair.cpUT І?;7AUx3hbڹiAF ZhƩ ؐۀ9M)4P@ I-.QpN-*LLN,I-60P1 fVd&gJs$g W#9q^CCKCSs#(q^CdA$@,Um) W>dde`ne0hdjldRymerloT^!%p+g[ωs˫U,ڰbϿ\ |T*_E݄޵{dzΪ3;46 yh_)p_+fK@ߒ!^&fFō}@_*H54?#`̲ ,|m:^{XwSBUbԯn?&w */s0N_%*VWLwat_vG>]WyNU;?'3"QH"Mỹkӝ|PK[J/Q6<Scertpairs/requireExplicitPolicy7subsubsubCARE2RE4CertforwardcrossCertificatePair.cpUT І?;7AUx3hbZiAr XhƩ Ґۀ9M)4P@ I-.QpN-*LLN,I-631 fVd&gJs$ rv r5 r51504014415725Do>j V#8٫ ̍ L l"/=Tfx)#gj V#8٫ ̍ L l"/=Tfx)#g2/}3Y^6-Yrp68K׭˺%~{.oЩ̌ij/Nknj ~{Fa|E[PK[J/E+z8certpairs/RevokedsubCACertreversecrossCertificatePair.cpUT І?;7AUx3hb*[TdĔgx}3##/VGw^FFVVkCnN6P6a`C) KX0$D9$3-39$P$,h 'k`h`bhihbjnd%k5p$p1Ae٩) ťI@+#MmNlH&hIɌ^)-.9 Vx 2OѣK-Wye;7'ﹲw̪z޶-'w*.+hpINSUm=R4AvWNo&gnɬjƠ@vYe z˚N:gEuSD7)cc{fgFwlqXY~F,,xb3X!nƕ 7`4I0)dJ@F\^&;}|ɖ77->2/}3Y^6-Yrp68K׭˺%~{.oЩ̌ij/Nknj ~{Fa|E[PK[J/|cLcertpairs/RFC3280MandatoryAttributeTypesCACertforwardcrossCertificatePair.cpUT І?;7AUx3hb:AA ZĘ`Ʃۀ9M)4P@ I-.QpN-*LLN,I-651 %3 y L - ML͍ y }[!l 9Is'FI12C9Aʒddm #99|*sR y @B&0 39;4GFV^NF?ͺcֽ"n.]&[&Y-ذۊs츆%ͳ*jmL;Oe|bR_N;_v]|#0IgZʻn̔3l֑Ơ@`Ye 9WtRǻլ==_Ȃ𱈱,]#IloЉ:| i~F,,g3X xظ<Sࠓ)d5`Rh)*tOyߢ4xC嵟Fw^|攷gNZ7};y&ݿTz41ycx|Cwn. [f'ldgܿYzKje#c{KsA]urūPK[J/+:cLcertpairs/RFC3280MandatoryAttributeTypesCACertreversecrossCertificatePair.cpUT І?;7AUx3hb:AA ZĘ`Ʃۀ9M)4P@ I-.QpN-*LLN,I-651 %3 y L - ML͍ y }[!l 9Is'FI12C9Aʒddm #99|*sR y @B&0 39;4GFV^NF?ͺcֽ"n.]&[&Y-ذۊs츆%ͳ*jmL;Oe|bR_N;_v]|#0IgZʻn̔3l֑Ơ@`Ye 9WtRǻլ==_Ȃ𱈱,]#IloЉ:| i~F,,g3X xظ<Sࠓ)d5`Rh)*tOyߢ4xC嵟Fw^|攷gNZ7};y&ݿTz41ycx|Cwn. [f'ldgܿYzKje#c{KsA]urūPK[J/UtKcertpairs/RFC3280OptionalAttributeTypesCACertforwardcrossCertificatePair.cpUT І?;7AUx3hbAY 6[ĘhƩۀ9M)4P@ I-.QpN-*LLN,I-651 %3 y L - ML͍ y H]=1$#8(ݐ׀$%╟gej 3 ؎\n%%0X y @afOOOQ<,z.z6Ig {۳y\:GL8áKlS?Nqլ S*&wM+fﴺs@6͝}'xGa-Eמ2mnv}Ï`rW0߾aƧt/Ơ@dYe 9WtRǻլ==_Ȃ𱈱oFRGhISxpd| i~F,,df +q%y0  A @ -0C%(_l&o\is[ <ߎg5AnR/jZo6O.,oDUXgVV{?D$4Z3ā־x頵;u~̼+~I:PK[J/~ntKcertpairs/RFC3280OptionalAttributeTypesCACertreversecrossCertificatePair.cpUT І?;7AUx3hbAY 6[ĘhƩۀ9M)4P@ I-.QpN-*LLN,I-651 %3 y L - ML͍ y H]=1$#8(ݐ׀$%╟gej 3 ؎\n%%0X y @afOOOQ<,z.z6Ig {۳y\:GL8áKlS?Nqլ S*&wM+fﴺs@6͝}'xGa-Eמ2mnv}Ï`rW0߾aƧt/Ơ@dYe 9WtRǻլ==_Ȃ𱈱oFRGhISxpd| i~F,,df +q%y0  A @ -0C%(_l&o\is[ <ߎg5AnR/jZo6O.,oDUXgVV{?D$4Z3ā־x頵;u~̼+~I:PK[J/uYKMUcertpairs/RolloverfromPrintableStringtoUTF8StringCACertforwardcrossCertificatePair.cpUT І?;7AUx3hbiA&ƿ  x8<ھ2228rp1 3JH8\‚!% ΩE%iɉ%ņ 9faRc^rF~8A8!2 x L!6䗥)*e$&Y % !nPA|d120724v2562,onAS 2MkeD7<[% Lq"-|ͮK:=a!`G5"Ŏ0N\= (mVEOZ==L_t)z~Ľ k 䁞Uf0ksEq)yl^,H%ҷMBMOn=V-bIH? 06 A|>66T?HBՀHE:30T ;čc K:oTs`FYgw:e{oUOg,s}U&p4~'k$z"dlqmr3^+1;\3&^N7n\PK[J/|MUcertpairs/RolloverfromPrintableStringtoUTF8StringCACertreversecrossCertificatePair.cpUT І?;7AUx3hbiA&ƿ  x8<ھ2228rp1 3JH8\‚!% ΩE%iɉ%ņ 9faRc^rF~8A8!2 x L!6䗥)*e$&Y % !nPA|d120724v2562,onAS 2MkeD7<[% Lq"-|ͮK:=a!`G5"Ŏ0N\= (mVEOZ==L_t)z~Ľ k 䁞Uf0ksEq)yl^,H%ҷMBMOn=V-bIH? 06 A|>66T?HBՀHE:30T ;čc K:oTs`FYgw:e{oUOg,s}U&p4~'k$z"dlqmr3^+1;\3&^N7n\PK[J/Y5{A_certpairs/SeparateCertificateandCRLKeysCA2CertificateSigningCACertforwardcrossCerificatePair.cpUT І?;7AUx3hbߠ۠f&F&&t^6N6, l̡,lLR `HjqsjQIfZfrbIj0HY'(阗_d 'k`h`bhihbjnd%k5$= E@1dyļ bgG#ade`ne0hdjld廈 *0znyN T?I]=P¶CkQdK"'TaV>om겚9.]ߔῂ/kg}fi *8Y dnȈ%LgW zpx YaYɬsf]PK[J/.^@]certpairs/SeparateCertificateandCRLKeysCertificateSigningCACertreversecrossCertificatePair.cpUT І?;7AUx3hbߠ۠f&F&&T^6N6, l̡,lLR `HjqsjQIfZfrbIj0HY'(阗_d 'k`h`bhihbjnd%k5$= E@1dyļ bgGCade`ne0hdjld'傏9ϭ:T&^MvOs~|6y6~%s5oQ'*OmΜzË͊w]Go÷҇k<ޜ;˜+|w3tάr-clrX)*?AqqATaV>om겚9.]ߔῂ/kg}fi *8Y dnȈ%LgW zpx YaYɬsf]PK[J/I50}5certpairs/TwoCRLsCACertforwardcrossCertificatePair.cpUT І?;7AUx3hb\TjThxk3##/VGw^FFVVCnN6P6a`C) KX0$D9$3-39$P@$,RT tK/2504014415725Do| bgGȎfde`ne0hdjldXZrjǮ޴\;+(e{w`mmqv[5ުEe+/6ǯgfnlZvlvf3N:p-\fɭ޿y3#LS?)az3.~8%UYÒESV`Xr+ٚ0Kڗn? Gc ^jdߵ_cRIm:> PK[J/lZq0}5certpairs/TwoCRLsCACertreversecrossCertificatePair.cpUT І?;7AUx3hb\TjThxk3##/VGw^FFVVCnN6P6a`C) KX0$D9$3-39$P@$,RT tK/2504014415725Do| bgGȎfde`ne0hdjldXZrjǮ޴\;+(e{w`mmqv[5ުEe+/6ǯgfnlZvlvf3N:p-\fɭ޿y3#LS?)az3.~8%UYÒESV`Xr+ٚ0Kڗn? Gc ^jdߵ_cRIm:> PK[J/PE0}1certpairs/UIDCACertforwardcrossCertificatePair.cpUT І?;7AUx3hb\TjThxk3#K^6N6, l̡,lLR `HjqsjQIfZfrbIj0HY'(阗_d 'k`h`bhihbjnd%k5"~6z(8;4Gv/#+sc/Ac'Sc#é{l ;l yV.`f|`$7t^H&׋ \qLկĞ.475y}Ջffj/ievSV1[HE5YhY҈7:Ľ ML k Uf0ksEq)yl^,HȥԚC7;\pHLH? 0 A|>66T?HBՀHE(30dT'4W5{C6]~y7o).'_9G˔պcA;ח4>Z n0PK[J/T$0}1certpairs/UIDCACertreversecrossCertificatePair.cpUT І?;7AUx3hb\TjThxk3#K^6N6, l̡,lLR `HjqsjQIfZfrbIj0HY'(阗_d 'k`h`bhihbjnd%k5"~6z(8;4Gv/#+sc/Ac'Sc#é{l ;l yV.`f|`$7t^H&׋ \qLկĞ.475y}Ջffj/ievSV1[HE5YhY҈7:Ľ ML k Uf0ksEq)yl^,HȥԚC7;\pHLH? 0 A|>66T?HBՀHE(30dT'4W5{C6]~y7o).'_9G˔պcA;ח4>Z n0PK[J/D\CFcertpairs/UnknownCRLEntryExtensionCACertforwardcrossCertificatePair.cpUT І?;7AUx3hbYabv3##/VGw^FFVVCnN6P6a`C) KX0$D9$3-39$P@$,RT tK/2504014415725Do*м< ׼J׊Լ|A|d020724v25620/>d s.(+Q"q.9AVDdΉ^u\Ge{C>_>0k+̑}Ş~g6Κ4m;Nn Zˣ<91\o21320.12zFVE@Awyԫny5kOW |,b,"__:7sG)`gd=6q_Eπ+̓1(nh)d5`Rh 6Mn9VqU^%mQ.oV];d= #ɟVĿ!:k>?ԋ>wK-?x:|/m>܉럻e`ڢi+.. ;|j=PK[J/*nCFcertpairs/UnknownCRLEntryExtensionCACertreversecrossCertificatePair.cpUT І?;7AUx3hbYabv3##/VGw^FFVVCnN6P6a`C) KX0$D9$3-39$P@$,RT tK/2504014415725Do*м< ׼J׊Լ|A|d020724v25620/>d s.(+Q"q.9AVDdΉ^u\Ge{C>_>0k+̑}Ş~g6Κ4m;Nn Zˣ<91\o21320.12zFVE@Awyԫny5kOW |,b,"__:7sG)`gd=6q_Eπ+̓1(nh)d5`Rh 6Mn9VqU^%mQ.oV];d= #ɟVĿ!:k>?ԋ>wK-?x:|/m>܉럻e`ڢi+.. ;|j=PK[J/\;Acertpairs/UnknownCRLExtensionCACertforwardcrossCertificatePair.cpUT І?;7AUx3hbj[dTg|3##/VGw^FFVVCnN6P6a`C) KX0$D9$3-39$P@$,RT tK/2504014415725Do<м< ׊Լ| Ѡq>Y{ ;6mW6S]/ A/ݿ:|ayCgP"af7UN Txb7oA'<\{NbGk[k|G~1S8{d],Լ3aۥR/_8\qqA,b "s6;^5wͫY{{2)cc?_/w^$. ݲڀ$ol WBc*P܀р$! Rj Т*QJw Ƚ;1e:=VOf%`9ՔZu 3|s_fkTkF|PK[J/s;Acertpairs/UnknownCRLExtensionCACertreversecrossCertificatePair.cpUT І?;7AUx3hbj[dTg|3##/VGw^FFVVCnN6P6a`C) KX0$D9$3-39$P@$,RT tK/2504014415725Do<м< ׊Լ| Ѡq>Y{ ;6mW6S]/ A/ݿ:|ayCgP"af7UN Txb7oA'<\{NbGk[k|G~1S8{d],Լ3aۥR/_8\qqA,b "s6;^5wͫY{{2)cc?_/w^$. ݲڀ$ol WBc*P܀р$! Rj Т*QJw Ƚ;1e:=VOf%`9ՔZu 3|s_fkTkF|PK[J/TMLcertpairs/UTF8StringCaseInsensitiveMatchCACertforwardcrossCertificatePair.cpUT І?;7AUx3hbϠˠf&F&&^6N6, l̡,lLR `HjqsjQIfZfrbIj0HY'(阗_d 'k`h`bhihbjnd%k5nt 6𨄆Ye+8'*xgd*&$g(8;4G #+sc/Ac'Sc#ìEG>x诼oC_+{+o ߺ$U7\?)t Jv1ڹdAEIʯyHZ$8>8]a󷜹Vn?> VU\egź_nJM geĽ k ^Uf0ksEq)yl^,HYfCZ-SE8ɀ$l WBc*P܀р$! Rj Т*+˾m~*o;>0Y}b֟%-)4lѹYnY޵ u;òw{EAg=ږ3>o,afg nQʶ;ӽ]]7PK[J/MLcertpairs/UTF8StringCaseInsensitiveMatchCACertreversecrossCertificatePair.cpUT І?;7AUx3hbϠˠf&F&&^6N6, l̡,lLR `HjqsjQIfZfrbIj0HY'(阗_d 'k`h`bhihbjnd%k5nt 6𨄆Ye+8'*xgd*&$g(8;4G #+sc/Ac'Sc#ìEG>x诼oC_+{+o ߺ$U7\?)t Jv1ڹdAEIʯyHZ$8>8]a󷜹Vn?> VU\egź_nJM geĽ k ^Uf0ksEq)yl^,HYfCZ-SE8ɀ$l WBc*P܀р$! Rj Т*+˾m~*o;>0Y}b֟%-)4lѹYnY޵ u;òw{EAg=ږ3>o,afg nQʶ;ӽ]]7PK[J/}/!5Dcertpairs/UTF8StringEncodedNamesCACertforwardcrossCertificatePair.cpUT І?;7AUx3hb^TnTlxg3#c/VGw^FFVVCnN6P6a`C) KX0$D9$3-39$P@$,RT tK/2504014415725D8b b"`xxCC,K2 #;eAm;qTIJz5o[twSY?om4TbkaEIo/bִ|tysW:z}`u?EPذJm2T."a ;nSUx7ؼ+Y>1)<1u|y V}He8ۀ$Yl WBc*P܀р$! Rj *ʇ?vK˴){dnt(9]m^K{J1|}& Nzfra,a[ʍCmt:37Ml.<9y;7Z;gq?bۏ?MQ5 PK[J/gAKa5Dcertpairs/UTF8StringEncodedNamesCACertreversecrossCertificatePair.cpUT І?;7AUx3hb^TnTlxg3#c/VGw^FFVVCnN6P6a`C) KX0$D9$3-39$P@$,RT tK/2504014415725D8b b"`xxCC,K2 #;eAm;qTIJz5o[twSY?om4TbkaEIo/bִ|tysW:z}`u?EPذJm2T."a ;nSUx7ؼ+Y>1)<1u|y V}He8ۀ$Yl WBc*P܀р$! Rj *ʇ?vK˴){dnt(9]m^K{J1|}& Nzfra,a[ʍCmt:37Ml.<9y;7Z;gq?bۏ?MQ5 PK[J/%<Hcertpairs/ValidonlyContainsCACertsTest13EEforwardcrossCertificatePair.cpUT І?;7AUx3hbZiA| XDlZmmyYY 8٘CY؄B $@.aԢ̴ĒbCyYX~^Ns~^Ibf^#HQ8A8!2 x, v%d(`YCc^dde`ne0hdjldXZ9Gx+"ʫej.y=ȭA쪭MSz8KQvS;wfCϘH*s[obCɇ%6 n i]lr19ˎ1Stź{7˞pqqA66T?HBՀH?30T>ҹ%f ٰOaxݦ؟;}5}գz}Iv6Kvh|p IWSޥkY, {KGWYO%R>er2[%VW-~w1uc]l{PK[J/װb<Hcertpairs/ValidonlyContainsCACertsTest13EEreversecrossCertificatePair.cpUT І?;7AUx3hbZiA| XDlZmmyYY 8٘CY؄B $@.aԢ̴ĒbCyYX~^Ns~^Ibf^#HQ8A8!2 x, v%d(`YCc^dde`ne0hdjldXZ9Gx+"ʫej.y=ȭA쪭MSz8KQvS;wfCϘH*s[obCɇ%6 n i]lr19ˎ1Stź{7˞pqqA66T?HBՀH?30T>ҹ%f ٰOaxݦ؟;}5}գz}Iv6Kvh|p IWSޥkY, {KGWYO%R>er2[%VW-~w1uc]l{PK[J/HmGFcertpairs/ValidpathLenConstraintTest14EEforwardcrossCertificatePair.cpUT І?;7AUx3hbڰiA \DlZmmyYY B 8٘CY؄B $@.aԢ̴ĒbC- bAbIOjs~^qIQbf^Bqi9;FȉZD"s bnXbNf :@F4G+#+sc/Ac'Sc#bSoj1ac=^G~sάdv(v=_tݧ*1'vMbS*b|%w&,+jjβHSM  zon^/ģ7".Dʾ':%iW&fF5U@*H5L}5͗l+=?e@@EEs]>7Y} []^ր$ A|>66T?HBՀH%f`34ytDm__`Y4Ãiud=">璵>?oJa3̽O#cn-<"x+^WlV-"az 2xz kƏK'?{PK[J/6 GFcertpairs/ValidpathLenConstraintTest14EEreversecrossCertificatePair.cpUT І?;7AUx3hbڰiA \DlZmmyYY B 8٘CY؄B $@.aԢ̴ĒbC- bAbIOjs~^qIQbf^Bqi9;FȉZD"s bnXbNf :@F4G+#+sc/Ac'Sc#bSoj1ac=^G~sάdv(v=_tݧ*1'vMbS*b|%w&,+jjβHSM  zon^/ģ7".Dʾ':%iW&fF5U@*H5L}5͗l+=?e@@EEs]>7Y} []^ր$ A|>66T?HBՀH%f`34ytDm__`Y4Ãiud=">璵>?oJa3̽O#cn-<"x+^WlV-"az 2xz kƏK'?{PK[J/ @Ecertpairs/ValidpathLenConstraintTest8EEforwardcrossCertificatePair.cpUT І?;7AUx3hbZiAl fYlƩӐۀ9M)4P@ I-.QpN-*LLN,I-631 $d9%f(8;ȉZD"s bNXbNf :@FX4G#+sc/Ac'Sc#7Տ!{'Ygo[wۊW=qa5RoN47zeM*+fv5Jpz"ҙj{]Q~Osś̜mak'T*XزqqA5I32gaF7q_Eπ+̓1(nh)d5`Rhq e= ?nۚEtl p_g[+xi S73/>BW| o>;˦,Hխ ӹGy]q/P^x@\oNߣJu\2e¯MyOyPK[J/N@Ecertpairs/ValidpathLenConstraintTest8EEreversecrossCertificatePair.cpUT І?;7AUx3hbZiAl fYlƩӐۀ9M)4P@ I-.QpN-*LLN,I-631 $d9%f(8;ȉZD"s bNXbNf :@FX4G#+sc/Ac'Sc#7Տ!{'Ygo[wۊW=qa5RoN47zeM*+fv5Jpz"ҙj{]Q~Osś̜mak'T*XزqqA5I32gaF7q_Eπ+̓1(nh)d5`Rhq e= ?nۚEtl p_g[+xi S73/>BW| o>;˦,Hխ ӹGy]q/P^x@\oNߣJu\2e¯MyOyPK[J/)~6certpairs/WrongCRLCACertforwardcrossCertificatePair.cpUT І?;7AUx3hbZTfTdx{3##/VGw^FFVVCnN6P6a`C) KX0$D9$3-39$P@$,RT tK/2504014415725DgCxQ~^sA|dW320724v2562)[O5{E[TLuU?jcѿR6tX#]ea7mbi}_0fؐJ\.G$L9HAqǍ\Q폍g8vALsNjnF$ϸ:m>KĹO4*:vqqA<,b "s6;^5wͫY{{2)cckgݍὨ;$|H? 0 A|>66T?HBՀHE)30T-Jy=8|/u$%Y(O_4η8%6b&iF^w^xp;`{jfcx3_t7][ۋ "_ۦ٦qtg'49 :6l5PK[J/z)~6certpairs/WrongCRLCACertreversecrossCertificatePair.cpUT І?;7AUx3hbZTfTdx{3##/VGw^FFVVCnN6P6a`C) KX0$D9$3-39$P@$,RT tK/2504014415725DgCxQ~^sA|dW320724v2562)[O5{E[TLuU?jcѿR6tX#]ea7mbi}_0fؐJ\.G$L9HAqǍ\Q폍g8vALsNjnF$ϸ:m>KĹO4*:vqqA<,b "s6;^5wͫY{{2)cckgݍὨ;$|H? 0 A|>66T?HBՀHE)30T-Jy=8|/u$%Y(O_4η8%6b&iF^w^xp;`{jfcx3_t7][ۋ "_ۦ٦qtg'49 :6l5PK aJ/q;Y1certpairs/DSACACertforwardcrossCertificatePair.cpUT qن?;7AUx3hb[ef~3#E^6N6, l̡,lLR `HjqsjQIfZfrbIj0HY'(阗_d 'k`h`bhihbjnd%k5"~6;*8;41nb6vY09L z-OګZmpp<ę -aBN<>v<~ItfͼUE&&ڲo"̟9;DvmL]fBlkC 6O_Q~{l8/,帯ZrcۅہKw_Ut:-Vp|\gޑoF|k d)""R"zUEfo\jnκW~ ie 9WtRǻլ==_(q%y0ӱH? P̀Y Z*gƋu|ή;oF_bd_opx.҉ vZCѠe[Ǝ9gJV>ȝE-Sk7;#'Jeyȴێ.X‡u9K~]n7/I%h%c]‰$!3PK aJ/MY1certpairs/DSACACertreversecrossCertificatePair.cpUT qن?;7AUx3hb[ef~3#E^6N6, l̡,lLR `HjqsjQIfZfrbIj0HY'(阗_d 'k`h`bhihbjnd%k5"~6;*8;41nb6vY09L z-OګZmpp<ę -aBN<>v<~ItfͼUE&&ڲo"̟9;DvmL]fBlkC 6O_Q~{l8/,帯ZrcۅہKw_Ut:-Vp|\gޑoF|k d)""R"zUEfo\jnκW~ ie 9WtRǻլ==_(q%y0ӱH? P̀Y Z*gƋu|ή;oF_bd_opx.҉ vZCѠe[Ǝ9gJV>ȝE-Sk7;#'Jeyȴێ.X‡u9K~]n7/I%h%c]‰$!3PK aJ/K> Dcertpairs/DSAParametersInheritedCACertforwardcrossCertificatePair.cpUT qن?;7AUx3hbY$a$bxy3#pky`a62rCY؄B $@.aԢ̴ĒbC~^0K8A8!2xU fKH,JM-I-*VH-,IMY8 tFƆ[s9fz7b߆1OhK{DokLf[\cPe t,HʻPONn:&O ie ѫ*2{R;vsտK4)P`03aJh`LƕH? P̀Y RT20227,ߦlkD.ovi2*=MZkqU۔nPK aJ/qKJ Dcertpairs/DSAParametersInheritedCACertreversecrossCertificatePair.cpUT qن?;7AUx3hbY$a$bxy3#pky`a62rCY؄B $@.aԢ̴ĒbC~^0K8A8!2xU fKH,JM-I-*VH-,IMY8 tFƆ[s9fz7b߆1OhK{DokLf[\cPe t,HʻPONn:&O ie ѫ*2{R;vsտK4)P`03aJh`LƕH? P̀Y RT20227,ߦlkD.ovi2*=MZkqU۔nPK aJ/certs/UT ن?;7AUxPK[J/j*certs/AllCertificatesanyPolicyTest11EE.crtUT І?;7AUx3hb7hb|рSͣ;/##++!'s( 0Sh%,Z\ZTXZl(j cI̫ LTpv4504014415725Do9ǜ)2 S6G#+sc/Ac'Sc#ubΜ~%]vجlȒu]9 6ͼh zSo7ͳ)s*B`bVPk޺ i.]تGK'y;vҒGĞ.9.cojU37x?Q9k/xgbfd`\jl 2Xy8Nw0l},mG |,b,"܇V޸ W^fgd@W`20`cc2}5FeO_I?$7ر=Z'ZOnf0OmrzfkO-sAWJooTf>BkV+g~F>߶wpڗ VcT{$~LۇSR_l{ PK[J/Zs*certs/AllCertificatesNoPoliciesTest2EE.crtUT І?;7AUx3hb7hbрSͣ;/##++!'s( 0Sh%,Z\ZTXZl(n cWLL-Vpv4504014415725DoCǜ)dK]]@4G#+sc/Ac'Sc#l"6 lqrM-[Vz^ ʤHǯ׼kIرKZw?Ŗsou)9z'6gc3_'ucEf'E;̼킵klS8eNt8 @?Ye "O'7a^1 dA XXDNO`|}KߪNtUhH? 3d5lf]O˥S97֦ᥫ4f;T+>b9GLz5g3-_}~4Vy+ȶ%Hƾ{/w\+?]T!PK[J/N+-certs/AllCertificatesSamePoliciesTest10EE.crtUT І?;7AUx3hbeļ x8<ھ2228rp1 3JH8\‚!% ΩE%iɉ%ņb 9fabC#gG9q^CCKCSs#(q^CdAXC,1qARNMU[,2q>Y{ ;fm`r`a_8gkW%|jwt<߫5/oģ!Sj+)kƼ E;D ;GHt5yLM?5.9J4b%L~ngvnf'6ǛL;\ʘqqA<Ћ,maxJ?[.i R""ry^PE 3l}H? 3U_E@ƀ+̓1(Y{ ;MCIzn'Խl;qYKn7rmVyQq=8jqu7ig?p:*'o-91v KROTediJ||fcjn/:¯r31320.n0hl5zRVE@A=J{>=c R""5%w&OkoEV+O;ۀ$僁1ceƕ qF --0LMJ~ fHi>pkk7Ju 7: 5u]Ik}'KIA}M`Wjם~ڢ%nQ\]3BݺZ^ߛNPK[J/7d'certs/anyPolicyCACert.crtUT І?;7AUx3hb1hb|Q̀Sͣ;/##++!'s( 0Sh%,Z\ZTXZl(j c )*J:%gȉZD"sɳ!12 ?'3RѠq>Y{ ;Yq}_*sjLgͤޗ[pע1MMu ٤ ;qEOM5 ,;S tf;'/\.L :T_|sH́ 4T1=qn`&6b?gyz\m9ܗ^GY{ ;J+p,_O驛P58I-s6>yzrHa6<؜~3Y^&03oԛ{tk~_Z՜e2t/gFužR^{|ԥQ2R+begd}#"a byޢ'έ ۄgK|v,H|1O*zh݀$僁8"`gƕ VFHe;RߨK}_EI66T?HBՀHE.30Tf4Src1 ۞-/9r*LtE~bW8+0YՓoσ=[gc03ʥ넚wLܹa@~m~Ȟ[],=g%ݲq_ܹeE?{PK[J/])=1~certs/BadCRLSignatureCACert.crtUT І?;7AUx3hb2hb|ÀSͣ;/##++!'s( 0Sh%,Z\ZTXZl(j c )*J:%gȉZD"s 4?#` ,|PK[J/;3~certs/BadnotAfterDateCACert.crtUT І?;7AUx3hb2hb|ՀSͣ;/##++!'s( 0Sh%,Z\ZTXZl(j c )*J:%gȉZDF@CCieA DSKJR\ Ύ]`^ElFsG`!}[t3g/TeK1Zv2.N8s]XfF7id&qvY}+6PXze:JE*)l?|v#213#*ydY$ D~\mwJjW|e R""ˣfg.K@W`03aJh`L0$A Y Z2CR$7;M;e3#*ydY$ D~\mwJjW|e R"""WeCKbVN0I32gaF8"`gƕ 7`4I0)e,L/%勺R㤙r-;E| 1?fy3I]{ܴ }?Pvy{k7áꟗ6kZrw#w1WJaEJ|}Ízf˝?Kp1PK[J/J(wcerts/BadSignedCACert.crtUT І?;7AUx3hb*6hbـSͣ;/##++!'s( 0Sh%,Z\ZTXZl(j c )*J:%gȉZD"s A@bSbBpfz^jA|dg320724v2562\_Ч t~R-vG0fN}Řq2Wx2({:k͏4./}J)^k9{!!٧ }ʳo^pʒI_ܨD&fF5U@*H5ι8z< 6fi@EEI::rAyV˸L萿agd,6q_Eπ+̓1(nh)d5`Rhq LMۄg)Y\@O_Q͡H|1%JMfMyR s| i~F,,Hd3X xظ<S@PBɀ-A2cƤmOEKwqF\Vj|ЦRچĎZx~9 qjIKY1S|MUGs8*|9#OsU<&#$PK[J/ҹ:+certs/basicConstraintsNotCriticalCACert.crtUT І?;7AUx3hbj6hb|QҀSͣ;/##++!'s( 0Sh%,Z\ZTXZl(j c )*J:%gȉZD"s BA@bBRbqfs~^qIQbf^I_>PmQf PeA|d020724v2562\z%~/;?53/Vf;|ؖ%y;o0PmQf PeB[bNqA|d/120724v2562lfԽO8y+Y;8Ugo^ǁ"ſb[~>~\2~M+i婛s獶* x1>(Gsꊧ| >I伍=_z^-/Ϝ0>3#2ydY$ D~\mwJjW|e R""rd]e9wC$MY>4?#`D ,|czq3Sm;=ta9׏4'nO5Avy*U]l9 {PK[J/@,certs/BasicSelfIssuedCRLSigningKeyCACert.crtUT І?;7AUx3hb2hbQԀSͣ;/##++!'s( 0Sh%,Z\ZTXZl(j c )*J:%gȉZD"s "A@bSbqfBpjNgqqijsBpfz^f^wjA|d020724v2562QPf$Fg84RHTE2SW~~J͊?r+vm>9SuS;% \+*?4'GٙZ %Tq򅧘~eAEץ;՛J31320.12zIVE@Awyԫny5kOW |,b,"'lgIbɵr @W`03aJh`L0$A Y ZT3CĒޯg.w-^&xSܭ$YZᄊZ~6Q ]~>5̈́gUfsI\g*=w^wol]j)/+h1{1+J4lͲJ)B}F:"8nvA{lo<_g̚))=cB?f3 ۶jߺt=3W{,[)㹹XiH?ڗ?7~2h|o 2X?ۙms&|rm$ |,b,"EW \|˥?qɗ}| i~F,,5X xظ<S y*e JΐA x"51#gRk2{**XJ\^uڅ+>٪맨ܩBoF\[&_vV|V{Oܕ5{IVk.kXŤ=JPK[J/큐:%certs/BasicSelfIssuedNewKeyCACert.crtUT І?;7AUx3hbj2hb|Q؀Sͣ;/##++!'s( 0Sh%,Z\ZTXZl(j c )*J:%gȉZD"s A@bSbqfBpjNgqqij_jwjA|d_020724v2562l4jZ#f{_gQbeL~XȳuI3Jh^R[BNc{Mkt?UՎe?2_ԝ[F̔)Ľ k ^Uf0kY!W3;-wWrk,H}d4?#`\ ,|8{0s=\̙ǜb\SX]oJ[ n9Ǟ )_s8T5o|)b#(bQhQu޵gÞ߽߻˷2\~&N|M/31320.12zEVE@Awyԫny5kOW |,b,"e|hU=Ob,U @YXqf +q%y0  A @ -Rmw|5;  S=5{2\u^x{kup3Iћ+e=Ty1r5.0/ G ]oņ @^z~PK[J/_R/certs/BasicSelfIssuedOldKeyNewWithOldCACert.crtUT І?;7AUx3hb4hbZhƩ ۀ9M)4P@ I-.QpN-*LLN,I-6T5P1 8%g&+z((xV*8;ȉZD"si`c|d_120724v2562l^+i }]Ҏocmߎsen^G/_9pQMҧݒI'Z&G̗dGZڲ5KzW{`*t~UwqR6>\[Q8l׷Ľ W4.5MVE@Ad޲ӇNYQr,) dA XXDݙTpˣu7XYXX> ,>^l\ m5`42`fF-;NFII~rqQ^^fq^z~__YQ dc-e06湷\kW`c?>݃jr.wm5$\Os1-.M r\sHYi-[},2UjxqO!+/s\_bp;FU/ 7uE.߽09PK[J/1e vcerts/deltaCRLCA1Cert.crtUT І?;7AUx3hb*2hb1ڀSͣ;/##++!'s( 0Sh%,Z\ZTXZl(j c )*J:%gȉZD"sɳ!%5$9GРq>Y{ ;1^KdlY:딦sRݚ o6U,1-/ZGqa.Xm;P@cE]Q g7vv^ktoMѦ\+Ż6ԞdσD0U>Mwwst%聯%Ơ@tYe 9WtRǻլ==_Ȃ𱈱LI::5x=kgd+6q_Eπ+̓1(nh)d5`RhQ I D4vu~?SFN+cc?"b{vg ˻geޔ(E-~ķ6kĤ==k|Չe-P/+^_y!C*%GO䂀Ŀ U>PK[J/Xq%!vcerts/deltaCRLCA2Cert.crtUT І?;7AUx3hb*2hb1ƀSͣ;/##++!'s( 0Sh%,Z\ZTXZl(j c )*J:%gȉZD"sɳ!%5$9GȠq>Y{ ;V8yLX1qcS-7.ߔz|د_-lvfPض 21+՞r*̘-t;c(td_ӗyWYN+T."a ;nSUx7ؼ+Y>1œWYiN]66T?HBՀHE)30T"O0L`QJge}g}6YkT%ixtˬ[ߙYE?R2>٨*)]D#E n=m+ORފ7ZϞ>EJ6PK[J/ܹ.6!vcerts/deltaCRLCA3Cert.crtUT І?;7AUx3hb*2hb1րSͣ;/##++!'s( 0Sh%,Z\ZTXZl(j c )*J:%gȉZD"sɳ!%5$9Gؠq>Y{ ;6OӾD%ۊeϘ~(sE/v3-+~e̋],{2=B\q9?ڳm2u:TFEz;8J.Η+ msZQƠ@tYe 9WtRǻլ==_Ȃ𱈱<`X;5I32ga8"`gƕ 7`4I0)(eܣw/I[l"' WzsB;c6wu%{4msVo|*9{m3QuY$n @⏫,8`iES4"MDz3S T]q*zhPK[J/Z%7'certs/deltaCRLIndicatorNoBaseCACert.crtUT І?;7AUx3hbj2hb|1ʀSͣ;/##++!'s( 0Sh%,Z\ZTXZl(j c )*J:%gȉZD"s A@bLJjNIsg^ H.H/_)8UѠq>/Y{ ;1H]]!ΟMX7|ٻMB{{xccCV!՝8ԅsIZ+l<}o]J{5~k{P|M9T;yçeFO]>ܛBB͗u>\Tebfd`\\cPe 2X+NW`j֞ dA XXDRG.rel*턂/ @YXqf +q%y0  A @ -"䢛&=;1K3#[\}_w%wm:{yY3bx"dExBࢗ{EUcpvdC*sL_|1=sGbG~1ȳs ̴ԢԼmȊ@ #ay{_Fhڑwd&}ш#܆|7eq$u;y_W?T-"lCN_9)sNI:7+gǵ\Y*\Ǿ P*IVZswgd%"a ҷ7/4|e'_@EE=UwZڙ n 8lggd@W`03aJh`Lư Z2njY|WZrK?TqgN-w"Mn 4|UKݞiZ/ z|)3J~j&ތߗϙDzvʍ;z~wsƄOPK[J/86'"certs/DifferentPoliciesTest3EE.crtUT І?;7AUx3hbj4hb|рSͣ;/##++!'s( 0Sh%,Z\ZTXZ c LL-V0R(.Mrv4504014415725DDou̴ԢԼȊ@ #ݒGEY)>5lza"\>N? *겿m,Tq쪙{j(3l+;a;=ůg^yճSY)2ǔ[޼PP2h;E u,Q OغqqA66T`0030T'o04+ Dq1naAѵWngSI{J6<{}F%{%jϵt:qۇ0;~wxBmSZ/<^w-+gd}%"a RY3DF%VMG_Qk R""(?񂢖{<͙2qv>4?#f& WBc*0r Тa ao\n{<R54igftsʥVz =V. d̓9b^R&rGo g+]T&K"as\]ۿVV.PK[J/,"certs/DifferentPoliciesTest5EE.crtUT І?;7AUx3hbj2hb|рSͣ;/##++!'s( 0Sh%,Z\ZTXZl(m c LL-V0R(.Mrv42504014415725DDou̴ԢԼȊ@M #{aCJ]hiWDM-yZK]%֞*ʩ.v1k$Iw /9b7J 5s^-^34g Β(fwݫzswNi-! Ľ 2 䁾Uf0k)|/6pVϞof/f R""rA䢏Z_,HH? 3q_Eπ+̓1Q Ft [\֪|&ڛ龖׏?rٖӭf"|SӒ'-}@%0ҵrU+7gmr!F/"_qi{|gRСoݛy'ĺ1`bW[~Y PK[J/p'?"certs/DifferentPoliciesTest7EE.crtUT І?;7AUx3hbcĺрSͣ;/##++!'s( 0Sh%,Z\ZTXZlbcLL-V042V(.M"gG '@N JkMz ]2RRJV"+V67h?FV^NFUon8z <%[20αWKV.2yVcn9춿~݉sI3iA/X末k'j3#;O{3o-Ytxw- j7Jo:8&o)Ơ@+Ye 9?^HN-f`o\W,H'y>^(_na>4?#`~3X xظ<SL aBVf P;y.oV%#׎e,3_P;v_/ݹ\'NYݢtky:g] xHyXzUee\Z4s3jnPK[J/{I>"certs/DifferentPoliciesTest8EE.crtUT І?;7AUx3hbeļрSͣ;/##++!'s( 0Sh%,Z\ZTXZldc LL-V04R(.M"g#9q^CCKCSs#(q^CdA4ASwLKK-J+Q[ꊬX q>Y{ ;:(gD||(\OyNt}wvԷOp>-~ͶOk6-3T=7Mmktg8Xݘ` IJ:.5m~/wsmX};lbv'fT,gbfd`\\cPe 2XHSޞݡ/VxkwhȂ𱈱<۳_ϗ7m/hgdo WBc*P܀ɀ$! Rj Т** ?߫.{h iWιe>/J;Dms&~d~E4ߔ-wdr}c.ɭ^3 9f=~7͏-v*)\ _O(zPK[J/4"certs/DifferentPoliciesTest9EE.crtUT І?;7AUx3hb`s3##/VGw^FFVVCnN6P6a`C) KX0$D9$3-39$P@$,Z`hdP\AΎ@~Q8A8!2 x[ d wuEVmi8ٓ ̍ L +*7+ hqY7/N`qT,6'pP5X&~EkU6N_$8Tg&VćWMUN"ɽVO6I3:zy׷cy2ٸfbfd`\mi 2Xe;N {~Is1)ccQx3yN_6g_"ogd@W`03aJh`LFz3}V:[xdmÑ7u5Wrj˞=yу; N,IqL\Emr9MkwL>poke:7,Pk =nK=:98/~|yƖ9_x zPK[J/5 L3"certs/distributionPoint1CACert.crtUT І?;7AUx3hb6hb|ˀSͣ;/##++!'s( 0Sh%,Z\ZTXZl(j c )*J:%gȉZD"s j@)S]7[x3]^j9H2pyY63m"1YO31320.12AVE@Awyԫny5kOW |,b,"e³Z4?#` ,|_ߪ+=Ơ@Ye 9WtRǻլ==_Ȃ𱈱Xt>.82NgMN?>4?#` ,|c,8u˼y>oQ[pS`eVO,ߓ{C;1*gno??FJR5xY~p?oݬ1Nw,K:]t*jv-;21320.12FVE@Awyԫny5kOW |,b,""m"z I[t=Z]!E)>4?#` ,|w>qCM^Ω.a^ߌ-Cf?Xl6}f /\ޱz~rZ_fMXת}^H*ۼkG[aUϋF<PK[J/H)certs/GoodsubCACert.crtUT І?;7AUx3hb6hb|QЀSͣ;/##++!'s( 0Sh%,Z\ZTXZl(`cfwOQpv4504014415725Do p.ťI@#;?s3KO~ gxaJNyrErZovϵ}:۵bkXJ'tTP3cen_NY6#*Gվ_Y#N?k=/-ٜR~7d+)hXXϙyQ _'7zղ6N74&o&7ӭexنrebfd`\\cPe t2  "s6;^5wͫY{{2)cc9eI6;Jva4I32gaafbb1X xظ<Shh)d5`Rh ;:fo&Np^JVծui;Bd=Y{*kf_zf7O] (xWbO'UM9p`W?ս{snl|bؚzurէwK~ext٭qqA<,@o4ι8z< 6fi@EEdek#?tpw5 @YXf +q%y0  A @ -VrAyWJ&ό/,e˒fdx_rbJM#[ L#om{:ǷG>Z)!s>[uRvx S*Ón/_f/ѽUU߅2 x6gPK[J//xsE%certs/indirectCRLCA3cRLIssuerCert.crtUT І?;7AUx3hbe伀рSͣ;/##++!'s( 0Sh%,Z\ZTXZl(a K,JM.qQpv46504014415725DoI4K|ԸoTbɷ2|e_moH bgv{:3# >Uf[4=FO;~t:^kȂ𱈱lS$3i6[gB| i~F,,3X xظ<S y8 –Q!^ y A2,@C <ܡ3^YŨWª^~2'{sL[ӗݒcB?efOzGŖB>v_\ 0;2yŏ3IxΒk-֦PK[J/tV0ycerts/indirectCRLCA4Cert.crtUT І?;7AUx3hb*5hb1܀Sͣ;/##++!'s( 0Sh%,Z\ZTXZl(j c )*J:%gȉZD"s A@ $-̟Y\hb8ጬ ̍ L %}~ȝ|~>ȸ4ܭE LfylpPmͻ?]~~>Yz'>>: JJ=?5XYl1f޲H`ꪀeotI؞BU1DfڧeX\Ơ@zYe7D~\mwJjW|e R""vsȾӏr2|Æ| i~F,,LL, WBc*0  A @ -V:C}"-xtcQ/Jp"u>%:rLw:r87.Iu3Ūۧ~;MwRۺj7f/ZbVpnoY;5JŹlPK[J/}Y]%certs/indirectCRLCA4cRLIssuerCert.crtUT І?;7AUx3hb4hb:рSͣ;/##++!'s( 0Sh%,Z\ZTXZl(a K,JM.qQpv41504014415725DoI4K|H9R=&PJݨnj&\_$v{n=]M_PK[J/kv[+ycerts/indirectCRLCA6Cert.crtUT І?;7AUx3hb*5hb1ҀSͣ;/##++!'s( 0Sh%,Z\ZTXZl(j c )*J:%gȉZD"s A@ bf^JfQjrsA|d320724v2562m§_Vr4=w %rĹ>j9dO,>y!)gޙܤQpd$ Ly~R+ZX|:TܚmVoؒ~C>^nzZX5KT]/F+NW`j֞ dA XXDIۭ;h%*ғyc"| i~F,,b3X xظ<S aBVf PQ+vnɷ- //98!RPWL}ӽVһGY{͜KJr1wjЗ`wjl|}M"!_[m h*Y'(_PK[J/*bF!certs/inhibitAnyPolicy0CACert.crtUT І?;7AUx3hbiĴڀSͣ;/##++!'s( 0Sh%,Z\ZTXZl(j c )*J:%gȉZD"s k׊>;6U_欰<{L= Ίaζ Wo/d=p ׭1Q?jvaVә72hn 2X+NW`j֞ dA XXDnorf;;XqWŀ$kl WBc*P܀р$! Rj @X@H-晁6մ0Fmұ[s-덫 S*NpU>Qh롨ozG>Jf|wI M3n55f%k;)kƣ{sPK[J/?+certs/inhibitAnyPolicy1SelfIssuedCACert.crtUT І?;7AUx3hbj2hb|ـSͣ;/##++!'s( 0Sh%,Z\ZTXZl(k cL,q̫ L4Tpv4504014415725DRѦȾ`de`ne0hdjld{S0̷d罟%/kY=rX-ߛ{p bm_$ v4-tWԿuq&fFe%`o*H5>Ƞv37)@EEnܴV]Ҵic˪ @YXqf +pp  !aVf 8aN~+0Ňu;v֬}ڭgݎQ] W7eӇ{yΛ>?1ocewћ翜hJ3|5Ȗy,SY6eSWkY?%IWױPK[J/Gη'%certs/inhibitAnyPolicy1subCA1Cert.crtUT І?;7AUx3hbj0hb|рSͣ;/##++!'s( 0Sh%,Z\ZTXZl(k cL,q̫ L4Tpv4504014415725Do<& LK #;Y_yP^8YqK鉞3˱ KtL&\d[#w#߹VH:o*j?o?ݛՅ~Ƞv37)Ԁ$l   `)a5`Rh ƚ _?ݔ-n]_sյ6~jcqQNմE3L>6z#tr3,N~90.EYie;[ V?13~95WVhç*lؘ5۝PK[J/.;(certs/inhibitAnyPolicy1subCAIAP5Cert.crtUT І?;7AUx3hbeļ x8<ھ222xrp1 3JH8\‚!% ΩE%iɉ%ņ 9fa̼̤ǼʀJCgG9q^CCKCSs#(q^Cd?6(Alƴ41Ԡq>gY{ ;o-h.ubnxmusv򮗌gOkD-oENz vJ,R}sX /r_ig^+a//[VO=60.%-ۨhy_dY$ Dnorf;;XqW@EEU3Y޳CM%<+6g#@W`03aJh`L0$A Y 0xf Vggs޳]\-jt ջl|eP}'}n}uVGv+t;[Noתh; Mh{#)_C׳/HTwjcNXQm%eRPK[J/=%(certs/inhibitAnyPolicy1subsubCA2Cert.crtUT І?;7AUx3hbj7hb x8<ھ222rp1 3JH8\‚!% ΩE%iɉ%ņ 9fa̼̤ǼʀJC$gG#9q^CCKCSs#(q^Cd?(Aljbde`ne0hdjld'+9>>1¯}}wg<ڞzH e%qL}17ѲVmYN#=ҁb=,-"Iʜ'ʂ)]'njWx&4=fbfd`\\fP7Ye '.\y}ӑCw?Ȃ𱈱(jxPw&9:yճ @YXf +pp  !aVf 0}c%l+UZ@Σ 旫գc<7̓;{S{EՓoކt7J/ntνdzI7Ӆ|Zشzc=Sov>+]N 377PK[J/WG!certs/inhibitAnyPolicy5CACert.crtUT І?;7AUx3hbiĴրSͣ;/##++!'s( 0Sh%,Z\ZTXZl(j c )*J:%gȉZD"s gV) 7x-Ňݷ=+ܿ'gS*7c 2X1e3_ r`~Y>1eEw;w-Cg|>4?#` ,|ud67"?V/ !zRyEюkf']RPK[J/-,'certs/inhibitAnyPolicy5subsubCACert.crtUT І?;7AUx3hb6hbрSͣ;/##++!'s( 0Sh%,Z\ZTXZl` cL,q̫ L4U(.Mrv4504014415725Do"2)AkFV^NFhK1hָzdyoYf <Ӻ^Y69["I e_,T+N34ޤdN]}/i6W,n |st*SNj:V23#*yGdY$ Dʓ"x  dA XXDX~|It,\ogdD6q_Eπ+̓1(nh)d5`Rhq 6ݓVme}{;| t%ހ2q9y}lF,4ǟS]SEveׯ&J 9;0Eo^3еC:iy7ϩ&_ީR3v;lܗPK[J/V)!certs/inhibitAnyPolicyTest3EE.crtUT І?;7AUx3hbj3hb|рSͣ;/##++!'s( 0Sh%,Z\ZTXZlh cL,q̫ L4T(.Mrv44504014415725DDo6Ut\]*4G#+sc/Ac'Sc#ói{ߛϬlԨ4 T;FZIncd9{s tUZ ,w6]UM-fMoj~/uo۹\3Ƥk gqqA&8eY$ D4*LtY׬4F@EE$ۓ'w}pÂOX603|0X xظ<Sm@p[_G\UCg^i;҃T%M lk{qjJ_ }.auv:kv:ĚޥC?Vff\2أ.yًf+tnatg٥ݺn~PK[J/AD%certs/inhibitPolicyMapping0CACert.crtUT І?;7AUx3hbbw3#/VGw^FFVVCnN6P6a`C) KX0$D9$3-39$P@$,RT tK/2504014415725Do<̼̤̒JĂ̼tgG>`de`ne0hdjldlSfK9+ѧ,L߫g-/m>"_&?mjo=iݔOB3U{s Y㕬Vz~+:(sH_is^v] Y?7N4h{DVE@Awyԫny5kOW |,b,"9/s1:98~\ŠQ| i~F,,c3X xظ<S aBVf e P p502422E:30.~qYGѿzylD\neϘ6Ur% %]>;fmg1:==%E!->3oEfIٗli21320.n\jиr,b "9/s1:98~\ŠQ |,b,"Yw:u_0I32gaF$8"`gƕ 7`4PI(IdR' Rj 30V>[_{.[FyCdMM6sr~IbC^s2] sꉥ'<֑vlPK[J/tM(certs/inhibitPolicyMapping1P12CACert.crtUT І?;7AUx3hbZfĿ€Sͣ;/##++!'s( 0Sh%,Z\ZTXZl(j c )*J:%gȉZD"s A@bLf^FfRfI@~NfrobAAf^BA|d_020724v2562ln>y)^!s82Qc8N] V>zo`ʚW3mҲ:{|vj%gwMSLt‡k5n9Ff۴noz`wR3 l6( /ߓl|;dR&fF@61zFVE@Awyԫny5kOW |,b,"e['ȱT3*c@W`31aJh`L0 AʄAX H@$aȈ !7 OY 7]T_)UrwwO|ʹ"VvٝzQq &ɬyv{6* C _ײ*9z^kj#bu ^EUZPK[J/P+certs/inhibitPolicyMapping1P12subCACert.crtUT І?;7AUx3hbznрSͣ;/##++A!'s( 0Sh%,Z\ZTXZlj cL, LM,(K7T04Rpv4504014415725DoFy6&-m1FV^NFO;udߤ]R`ggdT6U_E@ƀ+̓1(nc2)ic5`R@##+Z`uv)Ńע1>&%!XޜwAg*ϾW>s֯ڮ*v!=z6,lvݹl;Mf pys_I-^:4[XnE1y+PK[J/I.certs/inhibitPolicyMapping1P12subsubCACert.crtUT І?;7AUx3hbld x8<ھ222rp1 3JH8\‚!% ΩE%iɉ%ņj 9fa̼̤̒JĂ̼tCC#$gG9q^CCKCSs#(q^CdAjhB,Uk)cde`ne0hdjld1qk_ {b~-r:ȽRjS7t?]פ/goyKt勅 ~/:&Q5- 9$db/EΧ'sB6f-w21320.nlи@%Ye .obxݘަ3A |,b,"QOYLm\eg @YXf +q%y0 Qx,Ui19J$6?H0H3BK3\w/2G_~ ULgwpe|6s)YUo#o0>#Wݣ˿*;ܙs^}W:ܕfw/]?cE+u3v=p?kՕ|՛i,PK[J/;O2certs/inhibitPolicyMapping1P12subsubCAIPM5Cert.crtUT І?;7AUx3hbm䲀рSͣ;/##++A!'s( 0Sh%,Z\ZTXZlccVL, LM,(K7T04R(.Mrv 55504014415725DDo.b5#nMFV^NF[CeU-6iSnQGOﻻ} <)>U㡕w~\{~5 ?I=X?#)?7>ũiʂo9 iSpҳ3U?^83# ޒUf0kyv/li򛴋s֔S dA XXDTV3NzuMܸ@̀$l WBc*P܀dR&c w$Hlf~:a:Vf v9k՗6 vwiǫLT7`YFv)fŞ,,sRΞΔkIJ}/d.B W]To&eVZA.)MӢf};Pxycd߭PK[J/×nJ'certs/inhibitPolicyMapping1P1CACert.crtUT І?;7AUx3hbnİʀSͣ;/##++!'s( 0Sh%,Z\ZTXZl(j c )*J:%gȉZD"s A@ btf^FfRfI@~NfrobAAf^BA|dO020724v2562x{X<гm[H]vSf'SO_zUDGvnu ,.|h&-{O{>hK߽vJZO'K?Ƞ2f%S5~{<.,{0<+qqD>y_dY$ D~\mwJjW|e R""*3ekE\\ >g+lbŀ$yl WBc*P܀р$! Rj @* FFFFxgd-NE7q'L0ʭ 9CO憲tqKb!y0_*K4{fk΋sU":+75^7̦N|/IY匿v4PK[J/4V$1certs/inhibitPolicyMapping1P1SelfIssuedCACert.crtUT І?;7AUx3hb`s3##/VGw^FFVVCnN6P6a`C) KX0$D9$3-39$P@ $,,Y\XPn`h 'k`h`bhihbjnd%k̥`0n==!1z0w;e/t]YsVGb[|ciG'T1E:ųݒv?w_X]^QUb R?OPM[i7/|SZ`Of 4ĂT}""a *3ekE\\ >g+lb@EE$'Ҝ脥Y_+mgdI6q_Eπ+̓1(nh)d5`Rh I-7rm tWn,ܼ[z[e1 %eZrgg[s'(d݋]Ͻ*\HgުYYgv}z9uMGlެ_:9S ;3KPK[J/Po74certs/inhibitPolicyMapping1P1SelfIssuedsubCACert.crtUT І?;7AUx3hb:`ĤـSͣ;/##++A!'s( 0Sh%,Z\ZTXZln cL, LM,(K7T0T(.Mrv4504014415725D>cde`ne0hdjld3gW=Z%]rkI ̭ݵS^p&ݬEQ9g-г|sYI+iĀ-TYZŬ/Y"ufڌtϿB$$nYF&fFōK #"a mWM|m_1,H2nz&*ZH? 0F A|>66THBPHrHlf~:a:Vf @h SV0/(>s)\ 3~-l}LǮ'|Vr+|0Fᤡm|_+r |)95$1Chv?KZ -QS}''PK[J/ gC*certs/inhibitPolicyMapping1P1subCACert.crtUT І?;7AUx3hbkĤ x8<ھ222rp1 3JH8\‚!% ΩE%iɉ%ņ*J 9fa̼̤̒JĂ̼tCCgG9q^CCKCSs#(q^CdAB,iaqibde`ne0hdjldx%`WfX}vƭ+7}exJ]2WW̩쬩ϩ%4j)p΋ÅX& [!ӻEi?W,a{jpmn%aVuVDV2qm'3#ƥ ޑUf0kɉy4':arǦJȂ𱈱l[vՁm_XlgdT6q_Eπ+̓1(ndP)12ـNՀHf`mRR&]Kyzugn6-n b|gܮoO8oڔ*%S{dn.ot[3XZ[Xvƞ#L;bXok]nWoPK[J/܈E%certs/inhibitPolicyMapping5CACert.crtUT І?;7AUx3hbbw3#/VGw^FFVVCnN6P6a`C) KX0$D9$3-39$P@$,RT tK/2504014415725Do<̼̤̒JĂ̼tSgG>`de`ne0hdjldXָxʚ;ފ\(}-!W7l86n yyjr19IcWߵ=GE=-p_6zGdY$ D~\mwJjW|e R"" @Ƕˣnnbvǀ$sl WBc*P܀р$! Rj @* FFFVHg.i+]sIßzmrgR{Jk69z 29IZ &}+6~U,{]'\X'O/*Wc8+v;y_8ɳR/KcglݹJ">?w PK[J/l7(certs/inhibitPolicyMapping5subCACert.crtUT І?;7AUx3hbZ`ĹрSͣ;/##++!'s( 0Sh%,Z\ZTXZlh cL, LM,(K7Upv4504014415725Do6i&-l!FV^NF;|'Esh-&㜵_a~K-b.oDzEC^U)1Jb+䖻{_r6H? 0" A|>66T?HBՀHAT PӺwVc+8^iL3\?A1Sm4^¶į"B75YžY~'r567&oSgOnoޜt,rhZ-1j3'/a)8ngkdլ7}o_~ZMGBD&Lhc*fڥ1]cV|:qnMjڒÙg߮Znwյ]wqqRE@*H5ʞ~Kл|׷-AbSNȂ𱈱l+\~{ˬay|Ѐ$l WBc*P܀@ $R(c d$9$6?H0H3BK#Qc[ayr_ϔ\dKve0nY܇ڔ~4]c ;+ͶRk;ZxKsisX0Ă-\X tV+71ۯm5לuNPK[J//-0Z-(certs/InvalidBadCRLIssuerNameTest5EE.crtUT І?;7AUx3hb7hbрSͣ;/##++!'s( 0Sh%,Z\ZTXZl(o csJLQpQ,..M-RKMUpv4504014415725Do9.ϼĜlv"Rcj8ُ ̍ L 3syu)tMͬ?m>v]rIAmg{3C/Q}NP2`;sΙ_K.y& &xnIQ1l-*omܑ'5qqA<{,b "'Ln?ؚ,x1`ѥ?{ZEEdc\-͐ѻȔ~߀$僁8"`gƕ qfB'xN0vnE9yy*qڭ)ۉ?SJ,|Ec42=pqŞYasޝ08;0mrarc9PK[J/}\{D,'certs/InvalidBadCRLSignatureTest4EE.crtUT І?;7AUx3hb6hbрSͣ;/##++!'s( 0Sh%,Z\ZTXZl(k cqJLQpQLK,)-JUpv4504014415725D$o)&=ϼĜL]]( 11h?FV^NF [vlWz,ff+ˈIfh4yq 坵SbT CH'W;\8:A輄pQw]sS#cJ=%OPԟV2\Yxgއ`ז+3#lLydY$ D~sUcfhBhUf9 |,b,"AnLN}W65%ߟ֙j| i~F,,L, A|>66T`l530,M~n֊*^@EMy],SToJ,׋/[׹oO\v}džمmJNL\{oAudRF#a]oʽBv4certs/InvalidBasicSelfIssuedCRLSigningKeyTest7EE.crtUT І?;7AUx3hbZm$ـSͣ;/##++A!'s( 0Sh%,Z\ZTXZlk cVqJ,LVNI,..MMQpQLKWNTpv4504014415725Do+f;ϼĜ.puE6CdA|d320724v2562\_UbZה@wocO+گOrTfD Z5K͔-cڔ Oi}ϐն#-?~~s>wGY~u,6z+)0W98%7NG)?1M8 @YYe ϓ3ۤr1L^RI[ dA XXDnu-Bê;BǶh~f>4?#f& WBc*050f` ~1;; /ً{Kܸޑ&ZǭXv|8?=F努…#*d?7|gdFkyC.dC+_VOf cuPK[J/B>4certs/InvalidBasicSelfIssuedCRLSigningKeyTest8EE.crtUT І?;7AUx3hbZm$ŀSͣ;/##++A!'s( 0Sh%,Z\ZTXZlk cVqJ,LVNI,..MMQpQLKWNTpv4504014415725Do+f;ϼĜ.puE6CdA|d320724v2562~~zNR^Yk.0mVJ^m9cїw/\Y&n icU\ lsVuqb~9/(HaɝʍRGZmK؅J;9Kgbfd`\mi 2X)cGW'riO\e,HH7#~mzmf~mgd@W`03aJh`LF 2•-5|u1k6%'q۪\N2X*"B^'Œk_拼+ڷ^ ;Y 5}7ǮDn,vavtI`/Yja=i_gN^؁P[ݥm> 2~ql0瀢w- ĝ_t%ĉL gd}*"a kQw-]$R@EE$yJW:w;fb | i~F,,L, A|>66T`0`DK@0>ֳ ˫O\aqwpޞCύPX;_ټ}i/?T5h#Z|ΐWlZ@bѺUD %%Nȿ[*r+5d1certs/InvalidBasicSelfIssuedOldWithNewTest2EE.crtUT І?;7AUx3hbZ`ĹـSͣ;/##++A!'s( 0Sh%,Z\ZTXZlj cqJ,LVNI,..MMQK-WNTpv4504014415725DoFkϼĜLsR3K2NpuE6@dA|dO320724v2562O}q {͹gQo<,xQ 8 /T\0+bJ̍LSgd$"a rݿDw¬)3\7ou>\*av@EE=sgG*NuO7I32gaafb` +q%y0c=Ι©RXw,W5n~ǭ|4vf0[w1E->1eW5 #Q;^V/\0{tv 2]۞2́g&ΏMhgNz/2PK[J/Y`jdAcerts/InvalidcAFalseTest3EE.crtUT І?;7AUx3hbnİрSͣ;/##++A!'s( 0Sh%,Z\ZTXZlhd`cLJ,Lv+.)J+)V-,QHvTpK)NUpv4504014415725DDozUϼĜEJ@z #aGƇ?[CQ}-w)_O]Zs.Isbѧn >廴oz g/=ox>_X\ksϛe($y}ү/m4~Ľ 2 ~Uf0k92Ѯw{gur!&,HQ͋NYԻ+ZUKmgd@W`03aJh`LƼz3A}߽*xo|wn~W~XkW0/糌&,eXwpÅï3Nӌ?uX{(g9 8ܓz@=^gN+uaGsÝnn"nPK[J//8C,&certs/InvalidCAnotAfterDateTest5EE.crtUT І?;7AUx3hb2hbрSͣ;/##++!'s( 0Sh%,Z\ZTXZl(k cqJLQ/qL+I-RpJ*8;ȉZD"s bg^YbNf |4 ]](05h=FV^NFiG+'^k^vr;w,5\<9P1:uo&P}KoE>Xva u5Y)O{u>6K*9V/5dv)x Rs=gϖggd&"a ˣfg.KȂ𱈱Dap703|0X xظ<Sm@&z׹oGt.{%|[:3]&IkU'V||w֯:6Jg!hi'L,ٯoh71.}K̻'vo>U}ZZ/PK[J/Z /'certs/InvalidCAnotBeforeDateTest1EE.crtUT І?;7AUx3hb1hbрSͣ;/##++!'s( 0Sh%,Z\ZTXZl(g cuJLQ/qJM/JUp*8;ȉZD"s bg^YbNf |t]]( 14hAFV^NFzx5oddIX8!S*eCI[z:6Og[ߝ7!slpXǂ'15.=vH>QЙmg[M&G.fTnǝvX}ᮉyĽ 2 䁞Uf0k2%1G+Bs'FȂ𱈱dGnNMO;]'t<8>4?#f& WBc*0 #+-2/o|kUK̎4~)hrF?[öfۙ%i;#A:Ǻo\]e2nb'lx{eF;;M+vfmY: S)0@ox-2PK[J/v݅'t#certs/InvalidCASignatureTest2EE.crtUT І?;7AUx3hb*0hbрSͣ;/##++!'s( 0Sh%,Z\ZTXZl(f cuJLQLKMQpv4504014415725Do" )ϼĜL`KJR@ #{aCcϞh?zMaX}y9p&5+gl?|kw57N !Tt\Ԅ;~E.-ܔ%YDt2opN>|{Lwλ/hxԲv )3#lLyGdY$ Ds+Wgk΄ |,b,"51{<2~"_z8>4?#f& WBc*0J # ,:mLdwZݖ;N׹Oٺ_7q;nﱾ#wc}EF2֮x֛Gբ}yli^YSI:{ZŬ=ԟ|Dw_藿mdPK[J/=PS"certs/InvalidcRLIssuerTest27EE.crtUT І?;7AUx3hb:odŀSͣ;/##++!'s( 0Sh%,Z\ZTXZl(a cK,JM.qQpv42504014415725DDouϼĜ "WWd F`pʼ˂<=x+ރk\ewrγ,t^o=R~@>Emuڝ{QA}+e×䟞~on7_uU^zVn~!`uo+72hn 2 0Doz_aMDήs dA XXDgSܦac^| i~F,,L, A|>66T`0$Y\ /5&>=??hY" NsM2sK%z\foMes³`hR~gs}4[#[)ݿ`>TyJ7;o-s?8{9˶-)k<PK[J/* nW"certs/InvalidcRLIssuerTest31EE.crtUT І?;7AUx3hb6hbڳ x8<ھ2228rp1 3JH8\‚!% ΩE%iɉ%ņb 9fa̢̼ gG39q^CCKCSs#(q^CdA4A,Q+KLQH,..M-RpuEVllh8O ̍ L G_ϞFa»{Le[dƇ_1c"vl[MajI^TԕTq^ZwB]xQƆI{ 9tNG {L7xfŠ/RUfc!iUR~VEz2oL[$@EE3z }T R,7I32gaafb` +q%y0cـѠ,HFA! J-)0#9P@A 0TZ~ZXĕi'ZeFl $t0瑞77=V2eM4qò=..4XsM3ܦ6cIJjr6VJ7f`5vՊD^5YxJ|(XY5碮jֶysPK[J/[_nW"certs/InvalidcRLIssuerTest32EE.crtUT І?;7AUx3hb6hbڳӀSͣ;/##++!'s( 0Sh%,Z\ZTXZl(a cK,JM.qQpv43504014415725DDouϼĜ "WWd F`pdm3J$7ozpZ+VYes+-7g۹۴㩝 i-w_h)ls"q f|gλvJf+gbfd`\hkhi 2 0DIۭ;h%*ғyc" |,b,".K\xiH_{[Bʀ$僁8"`gƕ eFƳ yƣ /(YP FkSCMuH)d@RiE hbW2hiJ_Ulޞug-_u(:-`6ǭV7mdے2ӵf*EL] 2{nUȿbz5ywRZM^9sWPK[J/pO"certs/InvalidcRLIssuerTest35EE.crtUT І?;7AUx3hb6hbڲǀSͣ;/##++!'s( 0Sh%,Z\ZTXZl(a K,JM.qQpv45504014415725DDoHYX3,1'3E!9dz4HYHA|d?120724v2562ɼpI6jEKm#'^<{!̼?[^(jfvNMy'/\`7S͚c7={ծA[.H~+{(?YRŭ,DABǒKMyjgn&fFMM@*ñAdZ6v͍lw 5)cc)o="e Bvp|cgd@W`03aJh`LƲAQ"t48{5.{7岭BYR7?qe%*%N\^#ɒʞV2UkٸAl)i/d/?,&fʮm!ݯĽ 2 䁞Uf0kKʕ \6)ccI_U7gJKqO',6I32gaafb` +q%y0c=`9{7m <}CM}J) SXDOʜrUg~.ɲO~Plr[ ;u}GUԟTataucNΡ6"z3/PK[J/2E-!certs/InvaliddeltaCRLTest10EE.crtUT І?;7AUx3hb4hbрSͣ;/##++!'s( 0Sh%,Z\ZTXZl(j cII)ItQpv46504014415725DDo.5ϼĜMJ@z #]?Al(ѽk6WTxpAfigyVK-wә7141 =&"a H=kc:|?W@EE&-)?9{ދ @YXX> ,|wY{ ;Ծg\]Y^LO-~dƩX*֮˹KrbaO2%djl3j~H0霳eW wVe2_`|fꭒWRcl6lvkռE6}g8rD9X6I演AyŶ7Go{$U_HYFPK[J/H C, certs/InvaliddeltaCRLTest4EE.crtUT І?;7AUx3hb0hbـSͣ;/##++!'s( 0Sh%,Z\ZTXZl(j cII)ItQpv44504014415725DDoUϼĜMJ@zM #{aYσOMvrt+)pHm))>F$NOF1EFMj x?ne3=3|Gg~=N64QQYདྷi4?#f& WBc*0  A,>^ ,qB գ elύZg!3;:|fGЦ wh|A;{:EB|}W * >ȿrՍ':Ʈyr͞7?F,~۷4VY}PK[J/pOB, certs/InvaliddeltaCRLTest6EE.crtUT І?;7AUx3hb0hbՀSͣ;/##++!'s( 0Sh%,Z\ZTXZl(j cII)ItQpv44504014415725DDoUϼĜMJ@z #{a㩳mS~SK̢{fe5s|EZN|TI{V;7f1"Փ.nWi2>4?#f& WBc*0  A,>^ ,qB գ ei MwUS@[.JsSċg[n^[le`U)~ Ժt?&E26_>-mC}d><%g4ǔ0YݶKF>Z>p&PK[J/u?, certs/InvaliddeltaCRLTest9EE.crtUT І?;7AUx3hb0hb x8<ھ2228rp1 3JH8\‚!% ΩE%iɉ%ņ 9faԜD gG#9q^CCKCSs#(q^CdA$6@lP+KLQꊬTҠq>wY{ ;vk7t}{"w9/jۖDk [S>mXѬl2Du)GS=n]}WA)bS[ KsWMolC|,O3DٻZo0u轙? 紽c=qqA<_,b "'OS-Ӝx֟>gnY>1OMe7L:{FcSdz @YXX> ,|c*PK[J/ h])certs/InvaliddistributionPointTest2EE.crtUT І?;7AUx3hb5hb[DlZmmyYY < 8٘CY؄B $@.aԢ̴ĒbC9hJfqIQfRiIf~^@~f^8A8!2 x LArzye9) V*"Qbd8ك ̍ L X?>96%6 h/'7h{lW>+?,m7O6~3eiHY;ξ>imҦt_ ^vB۶mu-1=vd9 |K03|0X xظ<Snhg56\PtIA!P@QA> iNw_^z{[ǧ?)`vDr'T\W)~бy{&i0mf3{8z,݆7ߎMjz]i`Hf2MDFg&-[ ZßLdPK[J/3f߫_)certs/InvaliddistributionPointTest3EE.crtUT І?;7AUx3hb5hb[lƩӐۀ9M)4P@ I-.QpN-*LLN,I-63q de&dg*8;ȉZD"s $,Wa+!=`ȰSϻq_/+z7TSUob-FWf1tM,ƧdwF_H? 3q_Eπ+̓1- yZj JR- T %SQഁꘁY{ ;<|go+֫aԿm8ޛ=SEgկot;#@ܳY:;H~ rjřgnp<8:u3Q)S^eZTn{wcR NĽ 4.0zOVE@AʤqYDđvu=kbwȂ𱈱Z:|}Dz Q&03|0X xظ<SnGYy= T +cDM%3;/u鮑/ٞ|:D)X#n}쿊>,PK[J/hTKH)certs/InvaliddistributionPointTest8EE.crtUT І?;7AUx3hbzcŀSͣ;/##++!'s( 0Sh%,Z\ZTXZl(g M,.)L*- +1Rpv4504014415725D$o)HYX3,1'3EJWWd= C, #{a߄7l\qǾn ˖],<!/csmurf^M Ok$},\r RFXLLc}ٗ/gX^kc/Qrr>GWE<١hAqydY$ DLYEDigQ['۳&v,HȆ#wr<gٗU]䰧| i~F,,L, A|>66T`0Ā$YB /]M(GML@kZ1+hNٕ6ls"f^own ٳ8rի,]Q&\?.o*.P]>2_xSligybY*E7O7ss濒ܐ$4PK[J/y0)certs/InvaliddistributionPointTest9EE.crtUT І?;7AUx3hb1hbՀSͣ;/##++!'s( 0Sh%,Z\ZTXZl(g M,.)L*- +1Rpv4504014415725D$o)HYX3,1'3EJWWd= C, #{o:ɒ$<T4N ٲ҃/SqNJdtPώkrk|Ο6Ms=':,r`rf1  O?t0X߇yZ5gd='"a be,"H;ˌ:ٞ5; dA XXD1~7>U t3I32gaafb` +q%y0ۀ- {SaD®߭ޛ)e5}suj{'>h`In_u eܛf`'Y[OtZ&"6wvFrva]m >PK[J/~ش\u 3certs/InvalidDNandRFC822nameConstraintsTest28EE.crtUT І?;7AUx3hbf3hb_DlZmmyYY 8٘CY؄B $@.aԢ̴Ēb`AjQnfIIjJpiRIQj"HYX*/179?(13XP4@N JkMǸ8AcWtBb^B]]VYfda89Y{ ;_VYܿ/jfiUy$e? [덗z=u2A=('<r~W x{)s ևUO1V3աN4ٗUa}SNbOծ>.MY]Ŝɉ¢qw74hf 2XHsO\|*ntflY>1gSϹaސ66T`1`4I(5B!Hq_̘a^p(yۓ/]NNv֙n[U3Vx)'lVnsOR,psg|6ճv? `Si:vuA~sl|bq.51a3<;8zg[K:vgWiN/5^8+1{>qqA<0hdY$ DW~җgW)p4dȂ𱈱ԫ=7vܓ?YmUH? 3q_Eπ+̓1 30*,xw]Cxai㊽ON8{!M|j+u%i%QR+\2=^8jeLOlٲi[va 3+ų(A'߼Hh'OaPK[J/=_rZ*certs/InvalidDNnameConstraintsTest10EE.crtUT І?;7AUx3hb:ndрSͣ;/##++!'s( 0Sh%,Z\ZTXZl(o cKMu+.)J+)Vp3Upv4504014415725D4&2`AjQnfIIjJpiRIQj8DN "94IFϼĜНlrCa`ȰХc*G|,b,"u&umԌ$J @YXX>CRVEπ+̓1R 30tio6Xsv/w|I`+ܱAۏ3_w_!Wn:=殐)͵,g[u#JDlqo>)g9QztŜӭ?)&o ^PK[J/C2N*certs/InvalidDNnameConstraintsTest12EE.crtUT І?;7AUx3hb:cdрSͣ;/##++A!'s( 0Sh%,Z\ZTXZ ,H-,)IM .M*)JM54T6P1 K%:%f+*&9;ȉZD"s Ksc <s2SP@w+  ##+sc/Ac'Sc##*Xus-IX 3Dht{bY((V[DY^Rs0}~'턉gIhdN\}e8:?.i{3 pQle+L{NYőqqA<{,b "vwu2?w"9Ȃ𱈱Fw~u_?5^6I32gaafb` +q%y0zbacIk`] '>x >I -Vrg .{S^ߒ;U֤u,Ջ)ff:^\c?gKloݢ"}ˉ&3lQУnސ PK[J/֣N*certs/InvalidDNnameConstraintsTest13EE.crtUT І?;7AUx3hb:cdрSͣ;/##++A!'s( 0Sh%,Z\ZTXZ ,H-,)IM .M*)JM54T6P1 K%:%f+*&9;ȉZD"s Ksc <s2SP@w+  ##+sc/Ac'Sc#Ú;V9zdC L{Vm+-n_\^I^U޿Λ\{suo>$]Ckmr[wZ&28Er dA XXD??]li'>\̀$僁8"`gƕ L.艅v}+awM.cWuMs%;ϼθ K*=unf/Yݧ{VX+v.QQ ۽ϿD>߶/d+l Nksm31%)PK[J/u P*certs/InvalidDNnameConstraintsTest15EE.crtUT І?;7AUx3hbZg$рSͣ;/##++!'s( 0Sh%,Z\ZTXZllcKMu+.)J+)Vp3V(.Mrv44504014415725Do8H[X "94%5%4(5ϼĜ]lCSA`Ȱ邽ݍi~bb5wl kfwΒsfH1iRw0aضLT}gvLLo3;SKݔKJ<֛|Y3|$$_ \Tbn21320.64zOVE@Ad$Y=?6nWԫ̴1)5)ccY99+"T>H? 3pH*q%y0zr`vןݴ޿/wS%u/tgY)Rm-C%"jZ#k8Lcs>F(}wc6 Ey+;~fs߶=Tg:Hz9=;ļv}:LPK[J/0M*certs/InvalidDNnameConstraintsTest16EE.crtUT І?;7AUx3hbZg$ x8<ھ222rp1 3JH8\‚!% ΩE%iɉ%ņ 9faT⒢̼b?c$gGC9q^CCKCSs#(q^CdA=I丅R+sJSRSKJRS - !N1+KL:AU),043h ̍ L ȵ[CrJw2^-b>˰^k)UG#?^='=տTkoDWlIxh[Zv1O[' L(|ŸkDϵ3Mga!ƁѺykneY2D21320.64zOVE@Ad$Y=?6nWԫ̴1)5)cc.;~Wpg03|WBc*0A0%f` ̎(N9Yt _&V`}f|zv3y iK4˞2*X+*\Q\/ɚNP`n7a(x%Tiu傁f*\qxYOѴs>G^dPK[J//jU߹bV;N7T(K?Ήy,bK>;rKHN.Kξ'혏w$ع1E sT>[9!qνSo'-83#lLydY$ D=ifyp<ª躜{Y>15e>7| 'nM>4?#f&U`03aJh`L& w3E4P7-lٽ:hM+|ӻh8Ewҝ4w?qGxu~.k窾ȉ_^ľ'sf~.[ߍ6e>X"kXdykʸ/cbhPK[J/2y*certs/InvalidDNnameConstraintsTest20EE.crtUT І?;7AUx3hb*5hbӀSͣ;/##++!'s( 0Sh%,Z\ZTXZl(o cKMu+.)J+)Vp3Tpv4504014415725DRծ>ade`ne0hdjldڢT^,_tap䧿nTr#nW/7vuiRaA0KNܚfnb{~kaķ'k~m׍]g=_zŸ7rfbfd`\mi 2X7v/ov:<&R9/KY>14g#W| i~F,,L, A|>66T`0*30xБXgxYͻ{Wm}/6nϩ$e"o L+bx+ٕׄ;ٞ!cngkӷ^~Jt4o*1庱qqA66T`Z0`DK @za7ηx\KGFqJU3.ՌY[jMb|o5>{VoaG<ZK.~ϴ+&=GK7oysѵjTvi4$%7r[:[lͬPK[J/gmmA)certs/InvalidDNnameConstraintsTest3EE.crtUT І?;7AUx3hb5hbZـSͣ;/##++!'s( 0Sh%,Z\ZTXZl(o cKMu+.)J+)Vp3Tpv4504014415725DoT[X (7$5%4(5 }ϼĜ NruE6PdA|d320724v2562tu|]~O*Bwlqhbpgͺi 䝽.ל4!9ƷeLtte#"_Md)7tk::̭Nq%37-,9 n(21320.nk@?Ye ?o^dux^Mr_08"dXXDbeވmr38?>4?#f& WBc*0904dY 46E`cQ$ZSBBMxwqf`Y'eU:MjjG]G~ԡ[t>PK[J/BJ)certs/InvalidDNnameConstraintsTest7EE.crtUT І?;7AUx3hbZi$ x8<ھ222xrp1 3JH8\‚!% ΩE%iɉ%ņ 9faT⒢̼b?cgG9q^CCKCSs#(q^CdAvI丅R+sJSRSKJRS - +KLZ"WWd@4G=#+sc/Ac'Sc#dWtjFޏfv$'jU}:}׽zǤr/V[g.sj϶~ۻ6Tn?\z梗Ƈ:/؇Ko- dvucG.KROebfd`\mi 2XHa`nSXccTX[koZo}rl5I32gaafbHY>66T`Z0`DK @гz;ǯNO/} ~asX|"?fw(ɗ7g -'/ٯvƤwEj_V̵˿ PK[J/G{H)certs/InvalidDNnameConstraintsTest8EE.crtUT І?;7AUx3hbZi$рSͣ;/##++!'s( 0Sh%,Z\ZTXZl(o cKMu+.)J+)Vp3Qpv4504014415725Do8H[X "94%5%4(5 }ϼĜ .ruE6OdA|d320724v2562\M9Say:;y?k{-rc,Ny2͵I].jur&߼4{=צ' 8:?,sM\Â~7;_^/9Xq^s~ ~vFqqAm_̸ǁiB>st\yUػJ;VV>~&L #<1%spS '/͈Zx33#lLydY$ D5_4,[ܫʔ~23XccǑ̹/G^:Ӏ$8 eX xظ<Si-%0!kެsi~ D~kG ϕ=o7U)ٮRҴ>ׂ1^6z T~񑌍6}ؗiT8:o{ٻNj*ֻSфo]WL lit=3OQ PK[J/vS+certs/InvalidDNSnameConstraintsTest31EE.crtUT І?;7AUx3hb:dĤ x8<ھ222xrp1 3JH8\‚!% ΩE%iɉ%ņ r 9faT⒢̼b`CgG9q^CCKCSs#(q^CdA*YX@,3+KLYn+.1Ɔ}`Ȱ'.3Kgr_E (ՏbдoT!O޼T}Ɯ Zp6kSc|3m^;Uφ;M|4:KjEA]Ľ g40PVE@Ay^S\a R""?uGģ3EG,=)C @YXX> ,|K+certs/InvalidDNSnameConstraintsTest33EE.crtUT І?;7AUx3hbnĤ x8<ھ222xrp1 3JH8\‚!% ΩE%iɉ%ņ r 9faT⒢̼b`#gG9q^CCKCSs#(q^CdA*YX@,3+KLYn+.1}`ȰQst2iO./pc MbcTΝ_tC䎯ݔS69в__՛ץUh+u˕z8C>_O+f_'N<@3u=R뙘7N0h5PVE@AnW\Zl^[ dA XXD\V_q߯FP{=r>4?#f& WBc*0  @,M♐LF l2t Wjtnonޗ/oZhC mS\|O8L;{xETL2cF߃[W޸)4_Ow\ޫA}+ dA XXDtڨfy@mQ| i~F,,L, A|>66T`0($Y$[ ޒdK/CKJS>g.fgq)nUu]W'N?h=d?!oXκ_Y:Y7N :۹ꮅsi1+vgGW1m?vi̓p]wPK[J/ڈ+3&certs/InvalidEEnotAfterDateTest6EE.crtUT І?;7AUx3hb5hb|̀Sͣ;/##++!'s( 0Sh%,Z\ZTXZl(`cfwOQpv450401441572r x L z%d(*8)Հ(03h#FV^NFxۖMҧvW9(G][ΊwHbS}SbeǛ5/kt i>a';;2ǿK?Y;qCPm||Rȵ_c2vOS8Z['lw 3#lLydY$ D-k:}Ğ.Mr@EEҒJӲf4?g1p32gaafb` +cĀ+̓1h  9{J0o0"lN;ʻa7(* S=ٝ o:vGΪ3'[^==+&ٯpkdJ=c¤i,ya@I. 5LWݚz7Z}nPK[J/7C*'certs/InvalidEEnotBeforeDateTest2EE.crtUT І?;7AUx3hb3hb|ـSͣ;/##++!'s( 0Sh%,Z\ZTXZl(`cfwOQpv451704044Q@% x L!y%d(*8*D( 12h%FV^NFswFeU}[ޗP@7;_eTJ})*}[@Ulwv~nXϼ.MN7_=#>F[Գ.t-ob\wJхՔ4ߚ^jGV]Zok21320.64zNVE@Ad޲ӇNYQr,) dA XXD/+TBtcaeegd@W`FWBc*0 ѢiFjEzGYdUtǿHp{枮 _KW sqVFU&sjXGk}v_8xoJroa!ɓ]޾[Ǫ٦+J~1ISuD[CKPK[J/ŒJ$n#certs/InvalidEESignatureTest3EE.crtUT І?;7AUx3hb2hb x8<ھ222Xrp1 3JH8\‚!% ΩE%iɉ%ņ| 9favgG9q^CCKCSs#(q^Cd+(B +KLQpuULK,)-JUi06h|FV^NF;tRNf<,zE@1eZӔ/^LHvRosOdqcDžBdh2fvs͏+LWmn^v !F __m %˲yFcOyVu,fbfd`\mi 2XveMسZ庩YSȂ𱈱UpȿmNTn,?#f&  0 xظ<Si@pON-*fOq6'{{zaɍ+bN9Yaՙ?MUtL2Um'_V~ƫj%]e sJ+q~oz;^wf82\PK[J/7(0+certs/InvalidIDPwithindirectCRLTest23EE.crtUT І?;7AUx3hb2hb x8<ھ2228rp1 3JH8\‚!% ΩE%iɉ%ņb 9fa̢̼ gGC9q^CCKCSs#(q^CdAXXB,1+KLQt P(,P@Y#ccde`ne0hdjldRjŵkeG~ݣ*e)Od} SznBg3gϗml3O_^0p;q!bSwM%u%ٓ^og_&wqqA<Ѓ,l9(cɒ1F}&fFō ( ^`dѹdFY>1[Jq26fwbc>4?#f& WBc*0  BA,~>^<`c1!݆hiS~|=i3l'x> MXcno?cqK1'|Mw{kzqu M-w~zfݺ[}+Vtۦf: V Tg9``{xxc#>#sPK[J/'(certs/InvalidinhibitAnyPolicyTest1EE.crtUT І?;7AUx3hbj1hb|рSͣ;/##++!'s( 0Sh%,Z\ZTXZl(k cL,q̫ L4Ppv4504014415725D$o &]ϼĜt\](04h=FV^NFϟYym5?m6~mӺ&[1.x=׍lȢ/k+?9c&}$ٽvg eVip|y}GV? L?scRnt2sAEf3)U31320.N5H6MVE@AdÌg'\ፔ+yY>1/ 80|]y~5i| i~F,,L, A|.66 -n聈M/ 5ku}yv`+3-4Eֿ M:7On:`}ng{ M-] zz?g_V-+'cA˘p&W? PK[J/cO&(certs/InvalidinhibitAnyPolicyTest4EE.crtUT І?;7AUx3hb0hb x8<ھ222rp1 3JH8\‚!% ΩE%iɉ%ņ 9fa̼̤ǼʀJC$gGC9q^CCKCSs#(q^CdA"@l+KLQ@UY ^dde`ne0hdjldX7ugƓaKP=[ȨMsޏGZ~bIxY- ]Xui q sl$ZLlf5dɪإYCTmEcR{iN闙$CRVE@ADSbJ_M'|ZLmD dA XXDZ=-iVTCco| i~F,,L, A|.66 -?Jś7"rF!g64tqwv/;sO~wEv'- <ʯc^ J=lI?]R;ӠeSտbtSmZttӆK%PK[J/Ē.(certs/InvalidinhibitAnyPolicyTest5EE.crtUT І?;7AUx3hb2hbрSͣ;/##++!'s( 0Sh%,Z\ZTXZllcL,q̫ L4U(.M"gG9q^CCKCSs#(q^CdA"@+KLQ@WY SȞdde`ne0hdjldTݻO̷TޖE1cwɉaXl_"qmL5Vg9~j;w}DGN3ks/7sjvLLۜtu}g⳯5L *OEqqA4?#f&   ɀ@栗:SE*۾;vib]Wt'֋2Mhr>H57' ܝ}]eV ̀8r(9cE C՚4׭=-Rvj]S/8pGwmPK[J/Ͼ:,certs/InvalidinhibitPolicyMappingTest3EE.crtUT І?;7AUx3hbcĺрSͣ;/##++A!'s( 0Sh%,Z\ZTXZlm cVL, LM,(K7T04R(.M"gG9q^CCKCSs#(q^CdA*ZX@5+KLQf+69=`Ȱ7ֽ|&:%+s'bahye,~w^ǻKn5ե75ydOgl5ay+VtZ0x@([VC!7ji6cFoJEĽ 2 Uf0k~ڼuvbjK$*=h R"";~DUZ/XL2H? 3q_Eπ+̓1h u>"w;԰_QȞsB c^T<_ VB睛pϼ)hfWMgijŚUzDRbEeW33\?1 Cw7(\iFp0^I݈pPK[J/!YR87,certs/InvalidinhibitPolicyMappingTest5EE.crtUT І?;7AUx3hbmIJрSͣ;/##++A!'s( 0Sh%,Z\ZTXZlecVL, LM,(K7U(.M gG9q^CCKCSs#(q^CdA*ZX@5+KLQf+69`Ȱҷ=S&-HkcV={,,/?831=Oc"ۅVӽY?N+?9O􇄷[V>P*t{jx.{T{i;ke{%gOٕؒ_lF03#lLydY$ DT ?e]gh R""5R'~u OznѼw+ @YXX> ,|0uqr氧wu7[qyaSgL[|,uoz_U jPK[J/R @,certs/InvalidinhibitPolicyMappingTest6EE.crtUT І?;7AUx3hbZ`ĹрSͣ;/##++A!'s( 0Sh%,Z\ZTXZlo cVL, LM,(K7T04R(.M"gG_S9q^CCKCSs#(q^CdA*v[X@6+KLQWWdm s #{Kj2M'3}&}ߡ}?w`qQ{V|"eE{%UsTڿߞ(&ngUi=]LϦWFK.o˶a-OV&Kp8 @?Ye ̡S^gv9~o7.3)ccITߩkԶ%1ogd@W`03aJh`L&f ?OHȼxMNۿ?*k?_=Z&=\̭Vg^zzS:Å};+yUl3f.:NZR%\:;}j~} #vPK[J/94certs/InvalidkeyUsageCriticalcRLSignFalseTest4EE.crtUT І?;7AUx3hbZn$рSͣ;/##++A!'s( 0Sh%,Z\ZTXZlm cVN -NLOUp.,($g)% y L - ML͍ y j 3,1'3E&(41hwFV^NFӻ6\u*fעV\ <\5H:ǧd(&k+}5St!nօ.ܶ#Qs!*9fX]4sQȊ>&}$EC43#lLyWeY$ D4<]@mzKȂ𱈱8ovfn/ @YXX> ,|1[zǦM }<^UT򕎻ï||tuvyO u`l2 {SV;/. lsoa:5Ϸ,"&{ǕE;8' mɝ"g'uaV=Ry>^J*~136)OҏGpiZh+Kw4?#f& WBc*0Ef` T݋[ӗoRR` ^xgyoucll֕FvI;r 020724v2562,_Yr7Ys˃O~KgߧYߜe޳j^~ ^.w߲~vVhjz 1'^\QT_ݦf1%;ۓ=몟YTVL|2W{Yٝ+Ĕ.gbfd`\mi 2X}&'}hTL66T`0@O@,ou뽫ݟp|*k'41w|o1"g'G3XqQ퓅K qeӅ ϟ]]dhŽ k9.+J[-=řm녕57oEPK[J/µC)certs/InvalidLongSerialNumberTest18EE.crtUT І?;7AUx3hbZhĵI_@PH؀Sͣ;/##++!'s( 0Sh%,Z\ZTXZl(g cKWN-LQ+MJ-Rpv4504014415725Do9*ϼĜ,V"kRbha8ً ̍ L }{߳!NΛK^x6m#_=.z-UDn[WZ-MK~m{*-)Z>UeZc嵥V|+Nt'N4>۶x0-UkWm,$siWm&fF@*H5ܷN[o~po>~,HsWq^sh\ю"ـ$僁8"`gƕ Lh 4s6Uw0'@RTݷ Zg<Gt˧Ϙ?rt[H9L8d̷dZOF n)d֤snn'-^e?Vsx_ގuM0PK[J/O3,certs/InvalidMappingFromanyPolicyTest7EE.crtUT І?;7AUx3hbjo3##/VGw^FFVV_CnN6P6a`C) KX0$D9$3-39$P@$,,XPVW\h 'k`h`bhihbjnd%k5H':+uƞye9) 8uuE֨2ܠq>OY{ ;h4]^#K -WmgL/GGiNgX4el;n-\Qv3n}>ųK fޓSBW,ИzIZEymggyAۊ5#s21320.64PVE@Aզ7ۘ#\d,HEhŖtegd@W`03aJh`Lƻz3!v?居uߕh<Me;d^2WM9wU]XM<;O9y >-~_zͣ"5nhHZLb(=jw߯L7(יqMtz*Ygy~מu. gumkw^_b:PK[J/Y5/certs/InvalidMissingbasicConstraintsTest1EE.crtUT І?;7AUx3hbiĴрSͣ;/##++!'s( 0Sh%,Z\ZTXZlbc,.KWHJ,Lv+.)J+)Vpv4504014415725Ddo BSϼĜ"kUeh8ٷ ̍ L ًs|޹|oqi} OO$KCGQ|;EzSgɋ^˘(lN٨ɮ~\eS*}Gb՞r٢U~p{z>)O-ebfd`\mi 2XۂXK+Y'yc87FY>1>1pnG%ϔZagd@W`03aJh`Lƽz3aM6c[LƍIlqxVc{myڲM\>r׮b{WnkTD~=ML[W'ھ75dQʢu1,[¨Ė鲰.PK[J/z5'~"certs/InvalidMissingCRLTest1EE.crtUT І?;7AUx3hb2hb|рSͣ;/##++!'s( 0Sh%,Z\ZTXZl(d cWpQpv4504014415725Do>x ϼĜ̼t]Ȫ@ #{Q-S7X)Ui :C sR?{_ S({G#U/Y?/y{b[݋z\*?JΦK-GNe$u켩X7Ad&fF@o*H5,>Ǐ)c'*쿪Ȃ𱈱LYwOEB̎Wwم| i~F,,L, A|>66T`G-30\Y:98^/e2ٱB*W- 3jʕ'3м77#fֆ.Kwd}x{ucRq6KS[e,:+VՐ2`īf9MוW?b{٭gd'"a ?nDFRT,H1fe}OROMd~Ļsn?*eš&~ 3O/#PK[J/#` 1$certs/InvalidNameChainingTest1EE.crtUT І?;7AUx3hb7hb|ӀSͣ;/##++!'s( 0Sh%,Z\ZTXZl(j cqOQpvT/1504014415725Do!-ϼĜT̼̼tWWd  #a  . ^lU־UӒ+[<9Ï~KPj_)dyA@ɿOEtd09P{0E.^@Xmnɶ?{kWT[ r픗fbfd`\mi 2XveMسZ庩YSȂ𱈱\dt/#UU#^7>4?#f& WBc*0 5E| Wvm=Ny;{GQrcE\UE, zn  MJ8vyUҗ53VU0](}k+ˉg9JN]/5:,Dc _:vxQvSPK[J/^d3-certs/InvalidNegativeSerialNumberTest15EE.crtUT І?;7AUx3hbf3#^6N6, l̡,lLR `HjqsjQIfZfrbIjHYX/5=$,U!8(31G47)H@N JkAuL<s2SpXꊬQdA|d220724v2562\sfyy:ʯ.*lqqA<Ћ,b "z+zpP#N7Ȃ𱈱v<4k ݰ) @YXX> ,|);p߭M扺+1V_y|=ٕ.YnwXmO^Mou@QA䑗?4=%؆9+r/X?v0SL漡+n]zZhwĽ 2 ޓUf0k9rw9C5qg dA XXD͚fbUK32M4I32gaafb` +q%y0#=b榗L6Y')ШZQ\nsBMLg21>e[85n|ʯ2k2E$lqCŧ4ou}ydW[ sߛo`ez7PK[J/ ̷<3certs/InvalidonlyContainsAttributeCertsTest14EE.crtUT І?;7AUx3hbgľрSͣ;/##++A!'s( 0Sh%,Z\ZTXZlfc˩t+I+v,))L*-I-Vpv4504014415725Do=J ϼĜ43J`V"kVfhb8ˌ ̍ L s֩U;YA{ӏS<>cqrd 6lEy)?{Xz}WgWkv댐.FV_Mb{ _y?Ev^==49UØ+lnu 3#lLy7eY$ DjL-ti}v,HHOT/_F~R>4?#f& WBc*0G?302~=sh\_?adDpeϝy- 'ʮ]czxOwꬩuG}ۋWgrD֜W̊g丣ϭ(@}Ȱˎd?b$]W_ePK[J/.,certs/InvalidonlyContainsCACertsTest12EE.crtUT І?;7AUx3hb`s3##/VGw^FFVV/CnN6P6a`C) KX0$D9$3-39$P@$,,S霟WWRTh 'k`h`bhihbjnd%k5H%.+ ]ye9) tuE֥2Ƞq>'Y{ ;.-ߪ%^1X͑ၩ]WbMr5y7-rsT=`ISٖA $_Q՘}LaY?wŭU}Kw^x?9uc",~~]Z뙘gd'"a y![zկC&X$t8eXXDքUvѫ=Gݲb>4?#f& WBc*0 #Q?mq{V^;=Sv^`1j+,zR5Xx}etfs|Щ}1g|T|~7}9W{~2uFo7hYe/ݷ.=}cAPK[J/O p:.certs/InvalidonlyContainsUserCertsTest11EE.crtUT І?;7AUx3hbZjķрSͣ;/##++!'s( 0Sh%,Z\ZTXZlh c˩t+I+-N-)+Vpv4504014415725Do6cϼĜ춺"Sq>GY{ ;}\-aiX65βa2ӪjYC}OY:#2Y}^cZٟ^O&>l[/^Ys%{Xޙ,Iִe=Ơ ,b "Q.͈kE?Ȃ𱈱U{˱H7I32gaF7q_Eπ+̓1(nh)d5`Rh*sf+wEg@мbwH_qj}X +OTRezikyd_ש.{gvFjv6MV[Kn`'\&Zh3m]EPK[J/c,(certs/InvalidonlySomeReasonsTest15EE.crtUT І?;7AUx3hb4hbрSͣ;/##++!'s( 0Sh%,Z\ZTXZl(c c˩ M JM,+Vpv44504014415725D$o "]ϼĜt ]]u(045h;FV^NFig'}/~Q67+.lԐraq.EGL[ӷN6ʧ{Q:L)|2WSdngXuE~OemXr)9g:xuƃ_']K_6-Ggd&"a i}րȞcg R""pˉg~z+7qrH? 3q_Eπ+̓11 >~9Ddz,l{n`fmBomÊvW**#Pѻgrbω:^GynNS~~&w2\|#f҇ݣ/wf)(l}*{PK[J/D+(certs/InvalidonlySomeReasonsTest16EE.crtUT І?;7AUx3hb4hb x8<ھ222rp1 3JH8\‚!% ΩE%iɉ%ņ2R 9faԠbgGC9q^CCKCSs#(q^CdA"@,+KLQ@YȾcde`ne0hdjldlO]l>&?oXI'~\#HhG^op|u6$jZIżz~&vLJ MX4] ~q΃_u)\PaqqAY{ ;[>:n/WN|iq}ˢُYIyK7t|&u8ţm'v;+x&r?5gDZPe LI/Ps(Խl.OT=i4?#f& WBc*0  dY44HZ jIA"ݐ׀S,A>L 4è}~Z"fƯҙY)yg3JN 9Y`QT-2a^cjee765nʧpm䠠)4:Ie3*ns_ۖ}'v5#%r$֜Yl-uPK[J/q2fh(certs/InvalidonlySomeReasonsTest21EE.crtUT І?;7AUx3hbN1hb:ـSͣ;/##++!'s( 0Sh%,Z\ZTXZl(c ˩ M JM,+Vpv41504014415725D$o HYX3,1'3EBWWd # #{ Z͙J&3[a 9T;i*6{uœ¯bd=z<$%0?yJo9G9 :of5x6{sd(뗞jUrJ`<G咃7141:'"a bl"3,z0=㥤,HȏTd^8Y6}E1| i~F,,L, A|>66T`|04^ȳ41hrrY}ŧB#o|mwHzwM.7..OfRvqHXC M 5%2o_s~bOE$9 ,zWj.wHGj{VޖEdbfd`\\cPe 2XH3kl]Ic9nY>1<J$ZEd3I32ga7q_Eπ+̓1(nh)d5`Rhɀ*qtMJ8Wm^z?x.qS9yV05Q>L+#]3{[If- 3n2jT5h=]ͼ4 V{ -;k.4Y:H'3Cq.z=GPK[J/c]6*certs/InvalidpathLenConstraintTest11EE.crtUT І?;7AUx3hbiĴрSͣ;/##++A!'s( 0Sh%,Z\ZTXZlecV,H,Is+.)J+1S(.M gGC9q^CCKCSs#(q^CdA2ZA+KLQ^Y}}`Ȱe;vxl;7Ӵ76[UP7ѢK>= 6fb;v BgxenkcH䎆wo]FKi]iܯy4RY7=c¤KTMgdbfd`\mi 2XHهR{'р/9d5̏}Ķ@EEdfoYfMS۾=>4>4?#f& WBc*0 c .͹wﭷS; #"^iĐl۶+y.[+1VbPQsǀ~Y˷(X4RwV_UU3f񽱩KZ_n}uJNH3Mtki PK[J/@*certs/InvalidpathLenConstraintTest12EE.crtUT І?;7AUx3hbZe$ x8<ھ222rp1 3JH8\‚!% ΩE%iɉ%ņZ 9fałĒ <⒢̼3$rv440504014415725D$oZ}ϼĜ \]( 142h[FV^NFeb6߭87U\ް_5l|Mi\{?R'z:!I|Qeݎ =`oeI!/ fD JW6nذ%#S$9)Ơ@;Ye ,N[_rj]m,H% wE @YXX> ,|Rmw;_h˦'M~~}?d'5yvYM~-o!)ey$PK[J/;&9)certs/InvalidpathLenConstraintTest6EE.crtUT І?;7AUx3hbZ`Ĺ x8<ھ222rp1 3JH8\‚!% ΩE%iɉ%ņ 9faĒ <⒢̼$gG9q^CCKCSs#(q^CdABl+KLQUY3~dde`ne0hdjldX)yZVT3~M=&X/z]}GWL 2m1nt%t>L+׮*(QD‚8X 9P]*\25 ^{q]l)3Wټ% J9qqA8(eY$ DW{4G}?kυ dA XXDtlh0oC#C׏c8"`gƕ 7`4I0) +ٖxG1!9Ö\-gǝbYp6Fe5k; bcX~U?źG؄C-9O1E)\씾'4U5c3yڤPK[J/Ԥ6)certs/InvalidpathLenConstraintTest9EE.crtUT І?;7AUx3hbbw3##/VGw^FFVV@CnN6P6a`C) KX0$D9$3-39$P@$,,[Xᓚ真W\RWbP\DΎr&&FQ⼆\$470XWa+!=`Ȱ*r&UW%Y+vV3{Nݿ}Ǎ,eYonyq/ykv϶׫OeK]z"G-^̹;g;|2cy)CvԸx+ebfd`\mi 2XH3kl]Ic9nY>1+v-箖Tp| i~F,,L, A|>66T`G:30\rcуU".嵄K\m+•.N+5Ό3W5Wa%%Gzo|ǣط~\Tv&9zy6_t,V2'R4LPK[J/rb<&certs/InvalidPolicyMappingTest10EE.crtUT І?;7AUx3hbnİрSͣ;/##++A!'s( 0Sh%,Z\ZTXZlm cVrOQ(.MrvTH̫ LTM,(KW0,72504014415725D$o1^ϼĜ4 ]]5(L040hWFV^NF''EEN hu[Zp29g3v9ܲ79*μPԺﳦ_WmrXwYZOKUDOH>ϕuS5:^Rڗ?1)SUio7zg =9]Ľ 2 ^Uf0kx%8&~\TvSګi,Y>1QZL7lw?6Wj6I32gaafb` +q%y0c=ޙp~Eek " L0wORQ^&KOW:yIų=yzl/2PDj”GKu>yRg^Jc]xGt{m$L{PK[J/0a0%certs/InvalidPolicyMappingTest2EE.crtUT І?;7AUx3hbj6hb| x8<ھ2228rp1 3JH8\‚!% ΩE%iɉ%ņb 9fa~Ă̼tÒ|#gG9q^CCKCSs#(q^CdA<A,+KLQLTꊬAdA|d120724v2562,\ի]k(ah ͽ"mo'νؖqI?=efR+H?2UǶOW,vā}Lz[]/Zw1yҥ'dzR}SUYl&fF@*ñAܺk%fyZwqX,HߋWn5?s׍03|0X xظ<Sl@pڗ6oIsͷ>rkzœ'ER3,-~a;-)79:1IÍG8)Y4F!-۷{?| P:ӣPK[J/5%certs/InvalidPolicyMappingTest4EE.crtUT І?;7AUx3hb5hb x8<ھ222rp1 3JH8\‚!% ΩE%iɉ%ņJ 9faC#Ă̼tÒ|c$ rv4504014415725Do:mϼĜJͮ@&4G!#+sc/Ac'Sc#ìlD5o Wt c߹:/ûoyOjL,ucSh:*糟N_4t8o^uT|qǦ`+.ζckg2Z21320.64LVE@A[M1XWqY>1 F|3,v+Zfgd@W`03aJh`LƷ3Zl3w-Ke ڶ?,gM38䍪,ڏ]~h/^+us}|k3+mf\H~qJU*WYu޺ƛܮXl+t! %gS$q=s7MekPK[J/R++0-certs/Invalidpre2000CRLnextUpdateTest12EE.crtUT І?;7AUx3hbf3##/VGw^FFVV_CnN6P6a`C) KX0$D9$3-39$P@$,,YPjd``䣐ZQZTh 'k`h`bhihbjnd%k5 :[ku&ye9) 8uuE֨2Ƞq>WY{ ;.dNh;cڃݏxW{u/[z&'%x.j!jg܇:&\6)pŷ(=#]sjO-^:5c~bAL" s7&NyoHLdbfd`\mi 2X*3SǮ[fI`B0Y>1\m&͢?Ut~ :mgd@W`03aJh`LFz3ӜUqu'w~oqګФkP]IyBm\*-2}Ɩ/ (Ö!ρm Ϛ~ PK[J/eY{ ;v˔E*^o~}7ӽՊ\[Tt$^wx*68\mMUv’#BٜP?~lWw՛.={^xqQ^!|J3^9Ш8 @OYe z˚N:gEuSD7)ccy>۹vK 僁866T`l0530rhغ۸A@akJfu{^M4XiruT٭gms_Tm_bzΊq>ϸm(ɚ}.!\׌2>;Stv]?k_pfw+;|=Q\YPK[J/ -certs/InvalidrequireExplicitPolicyTest3EE.crtUT І?;7AUx3hbj1hb|рSͣ;/##++A!'s( 0Sh%,Z\ZTXZlm cV*J-,,Ju(L, R& ťIh 'k`h`bhihbjnd%k5H#^kKFye9) XWpuE֧2ؠq>Y{ ;J0{p$3tŞW 9^ݝW:y s+V<8h{![)|v|w>i۰ue/s٪9SIq<{vN sڢDs&fFA@*H5|oѾT]UQI 6i4)ccoWxX4C( ycgd-~!ߛb H8|gb/_\UĔwO_6Y6PgmG7-(/ʮǁ_.JnN3dێi>Lg8zsۤxieP{Sx+gե 3IlPK[J/'-certs/InvalidrequireExplicitPolicyTest5EE.crtUT І?;7AUx3hb2hbрSͣ;/##++A!'s( 0Sh%,Z\ZTXZlhhc(J-,,Ju(L, R ťIjjb 'k`h`bhihbjnd%k5H#vkKFye9) X]ꊬOdA|d320724v2562,`Y΍~X`f_Dicz0{ oOtq$+nwW]7,Ʃ1+N}Q:VݞQxۉ+g7eNӻqW;omEM빦}ebfd`\d` 2Xs4fbɴ\j\p,HH+-kr7pXg8ogd-~e[kzY>`Dm:ӄ<쵩a192 5]";Ǡљ6.6..pZ;S˅ov5Iξ>ޭyniǛn6ķh&gA=5ߺU{1s~oU]}8C:PK[J/&~!certs/InvalidRevokedCATest2EE.crtUT І?;7AUx3hb2hb|рSͣ;/##++!'s( 0Sh%,Z\ZTXZl(f c J-NMQ(.Mrv4504014415725DDo6 ϼĜUΎ*@Z #{J]ZI.{"x/o_Ck8} 4mo%,i66:PdVI_|Y+O}ժ8En-{BkeZ漢uN9h8foQ[qqA ,|žZjM={1yg5g,z}4*|C==w1v_%{?Nx5'PK[J/Hg_Q.certs/InvalidRFC822nameConstraintsTest26EE.crtUT І?;7AUx3hb:lĤ x8<ھ222rp1 3JH8\‚!% ΩE%iɉ%ņ 9faT⒢̼b 7g ##gGc9q^CCKCSs#(q^CdAXC3+KLكn+FIFf`Ȱv]SNH[wsL=>Z}荊PQy vB_,ٖJLJ.5GZIHSEi cwUFv}|yo}Iƨjx31320.nf8@IYe Wfis6gneVB@EEdʞlxaqkYҵ @YXX> ,| r^=ؓx7!}彟r}vUN>cPK[J/)K#3certs/InvalidSelfIssuedinhibitAnyPolicyTest10EE.crtUT І?;7AUx3hbj1hb|ՀSͣ;/##++!'s( 0Sh%,Z\ZTXZlh cL,q̫ L4T(.Mrv42504014415725DRٶȾade`ne0hdjld݋>"Nv>jZ^sv|yƛ/SV>`iagdo   `)a5`Rh  _sR^GLI YxEv1+k%k?옷b~Gw^Ȧq1˛/fJ }uq .v_`޷3V6gde`ne0hdjld0B3gf2w)2oysM']~,gR56R6<9-G"}IWI:IxkvSW~CmxZ*:g8p$DGi>zSsr]l9*??UsR 3#lLygeY$ DCUr+W |YqSYPK[J/LG6certs/InvalidSelfIssuedinhibitPolicyMappingTest8EE.crtUT І?;7AUx3hbZn$рSͣ;/##++A!'s( 0Sh%,Z\ZTXZlecVL, LM,(K7T0T(.M"gG9q^CCKCSs#(q^CdA!ֺ@+KLQNI,..MMQWWd#@fZ4G;#+sc/Ac'Sc#͙necr&km%<Μ%4n W6| /M۹㭓N{Sf8RhGg“vڷ5~Y\>;y+؊*#gd*"a R7y Sԉ撵{|@EEh34?#f& WBc*0%0f` >* A*zS<=_Q;.\pUAn{ nԂGEa{֕_kpNVwb]4׀6dU9ʏ?yRvmήSWtsf}/1PK[J/E6certs/InvalidSelfIssuedinhibitPolicyMappingTest9EE.crtUT І?;7AUx3hbZn$ x8<ھ222rp1 3JH8\‚!% ΩE%iɉ%ņZ 9fa̼̤̒JĂ̼tCC$ rv4504014415725Do Z[ϼĜԜ4]lNQpuE6BdA|d320724v2562sjqcW׭W2iݙ5_O{T|UZ O75oYua3rN]ȓLWxySIW5GpϕT21320.64UVE@An{%k -|a,Hw5:YbQS>4?#f& WBc*0%f` hAyJ,H 4}.9oͿtЃـ$僁8"`gƕ gAE# k&kļ`,n% Na3}|ʤr]r-{=<gZ2wQaIZ"/v3q"=)G=X+:kR3PK[J/]-7certs/InvalidSelfIssuedrequireExplicitPolicyTest7EE.crtUT І?;7AUx3hb2hbрSͣ;/##++A!'s( 0Sh%,Z\ZTXZlj c)J-,,Ju(L, RF ťIΎr&&FQ⼆\"mt7phWY\\ f( 57hoFV^NFgwX[FziIߎus>TR~Bڵy0H uLQa'ETPޱ |З^ۡ&UigB7K ]j5g[L~qo20)ccYӈc[άz3 @YXX>E53ЯA+$Lc/mĩ).?gȾ'd95t޲B)ł/4zyo~b΂yBI\^iFN11e k`7K%?j-xY7+n~;3#lLyoeY$ DfQR7Tr©|sō |,b,"+n/ɰ>MqTdWH? 3q_Eπ+̓1 R30#;uY{ku*s잿ɢ5lB/$rcD٣P]GbeICӺP+=<䖔b=Ekۧ4xΎ^Tֻ}wB,rwHGcUPK[J/P46certs/InvalidSeparateCertificateandCRLKeysTest21EE.crtUT І?;7AUx3hbZk$рSͣ;/##++A!'s( 0Sh%,Z\ZTXZlgcV N-H,!+$(8(xV+8;ȉZD"s bg^YbNfa'ȁ 524h ̍ L ']V nTe%x (to3Ut_ўge.îTǾuΑb o0+=L2)AM;~2l1zV Wz7/0hs53#lLyoeY$ DvHΨ9YaEe_O@EE%83vz]8n1I32gaafb` +q%y0Ӄzj`B)sVou2(bl51]~k> 0!ǎxL/{y9ߟܵE?^.ywe[IqL^ɔ}/Ole\z4u^$Rw?L 61XЛ"l_%u"n&xPK[J/zCN;certs/InvalidUnknownCriticalCertificateExtensionTest2EE.crtUT І?;7AUx3hbZn$1ހSͣ;/##++!'s( 0Sh%,Z\ZTXZl(j c )*J:%gȉZD"s bg^YbNfBh^v^~ysQf PQz׊Լ<WWH#Ⱦdde`ne0hdjldjp4n6֦k3nx]GG=>OH)7dD^8ƛ!WG|w/=eoPT_[pҞ炖786vκ ͘C9}L;3#:y_eY$ D~\mwJjW|e R""Bܬ|w>p wk>4?#f& WBc*0  110E30h55p-o-'J_[r_9EQqQ?mkkѓr_̎}~vUDUqIiױSl#v['[ir«8p/ PK[J/e70certs/InvalidUnknownCRLEntryExtensionTest8EE.crtUT І?;7AUx3hboıрSͣ;/##++A!'s( 0Sh%,Z\ZTXZln c /SpQp+)Tp(I+9ȉZD"s rbg^YbNf>]]u+0hgFV^NFOߧK`Yg[!4RzUA.ɹm7g>)Vo82Bbn\_^.Omu/ۜqn3*V]qWv=quŶ,6e_gd)"a 5SO߯3gə  |,b,"|w = @YXX> ,|^yPK[J/0"0,certs/InvalidUnknownCRLExtensionTest10EE.crtUT І?;7AUx3hbbw3#qjy}eddee016dceaf 62qCRKSJ22KR  Aryyy A> %yř@8A8!2 xl {%d(`Y Cede`ne0hdjldXJ)ܩ !KCiR+*Vs_XlZEsnfuO1I=LPu֗/4I32gaafb` +q%y0݀-ҙГbRrvq_5&3*ޥî`-/|ϝ|==qOv9ޅ1a[OM[ff5f=FۢޘZΏ٘6mŬj Ɠv[.hxqZ]3.צ3?i{VpPK[J/F5& certs/InvalidWrongCRLTest6EE.crtUT І?;7AUx3hb6hb|рSͣ;/##++!'s( 0Sh%,Z\ZTXZl(j c /KWpQpv4504014415725DDo.5ϼĜMj@ #ad]|K*N.ٴz9s?w}lK-/'M8}{_-"票f :z˩3f|[.n#[FƅӮ[sQC1m<3#lLydY$ D>>4ZYwcx/,_a R""r?l>FI{//ͯigd@W`03aJh`LƮz2amܱ*J 9J u8]?L=OsQMn'gEߜ*[PK[J//+certs/InvalidUnknownCRLExtensionTest9EE.crtUT І?;7AUx3hblg3##/VGw^FFVVCnN6P6a`C) KX0$D9$3-39$P@$,,_ZQW9ȉZD"s ҈bg^YbNfv[]]) 4hOFV^NF{6 5a ^LA}L88lO=~u̮|bSoˮ<~p'buVUo+yl/vl ;]3"E zF]K3 _f`8 ,b "Yg|1Enދą[VȂ𱈱OoԚ.|֊#yק3I32gaafb` +q%y0c=Ι`,\K.l6_r_j7%bMI5<]o@k{Nf, cXmW{k7'/Es#D-Pni΅3>I' b. YPK[J/mtxu\+certs/InvalidURInameConstraintsTest35EE.crtUT І?;7AUx3hb:ad x8<ھ222xrp1 3JH8\‚!% ΩE%iɉ%ņ r 9faT⒢̼b OCgG9q^CCKCSs#(q^CdA*YX@,3+KLYn+.1Ʀ}`Ȱp w蔺$%]\<{"7?}X?<}@I4y }EE>ֽ}^/G5.Yob[f6ahW +$qųd21320.n\h8@CYe 5bI\fJT>k |,b,"7t#Y S&~ylgd@W`03aJh`Lƺ1HBE@M#J_%H_ j ;ÙBw9^=u}e?\lmAԲ5<E|n_!ڒ9[f8[#X~npWfWy˷ߺ`tAMu[wY+yPK[J/ Y+certs/InvalidURInameConstraintsTest37EE.crtUT І?;7AUx3hb:ad x8<ھ222xrp1 3JH8\‚!% ΩE%iɉ%ņ r 9faT⒢̼b O#gG9q^CCKCSs#(q^CdA*YX@,3+KLYn+.1}`Ȱۭ1ၸg:)ՑiK4SΧpCZkvlϯ NޱF'zƧVkr\7[b_#c~]GzBͻ+Ҭ@B3+7,.[xw.bVKoebfd`\ܸРq<Ї,b "mKB?,P^|UGȂ𱈱pZфF/v<"| i~F,,L, A|>66T`0$Yt 4J 3!zeVF%@GK(ev+>$.a8:5n7v>j%n⎙zydUԾ/zuۜ|btd߳S7[==A6W̑gܲ]ӚuAo_=ý1_.PK[J//k=,certs/keyUsageCriticalcRLSignFalseCACert.crtUT І?;7AUx3hb0hbQSͣ;/##++!'s( 0Sh%,Z\ZTXZl(j c )*J:%gȉZD"s ˆA@bRvjehqbzsQf P6G!9'83=O-1(h8/ ̍ L tؾz[W={ &Up3gbZWos`q촃77w,5^`}m?^u\7B[nmhʗ݆<5:.EkYInߙn=6m7IgRUZ&fF5U@O*H5ι8z< 6fi@EEd sj_L{m"C?+s>4?#P, ,|U7 ?9w&Tm:`Ŧ{-Ԏ(K_6?]!>)/i_/Zt>̖MUHtzj[v?׏JIAp PK[J/B1#certs/keyUsageNotCriticalCACert.crtUT І?;7AUx3hb6hb|QހSͣ;/##++!'s( 0Sh%,Z\ZTXZl(j c )*J:%gȉZD"s |A@bDvjehqbz_>PMQf PEA|d020724v2562̘T4 U;%J7s>jiY{[c`>״yU~? | ,دv')}*_O8 2(}2ߩ$×ow[Gg;煭X}͙Ľ + ސUf0ksEq)yl^,HyK:=2c;xߡ{npYXf (q%y0  AŒYX Z2dɎB D-KHgm>}u6'Sr 4xTJbϾvjÕٓh~[ުYNN//ıi+udStbC ?_gvvF.:eSK{x'h&PK[J/G+zA/certs/keyUsageNotCriticalcRLSignFalseCACert.crtUT І?;7AUx3hb4hbQрSͣ;/##++!'s( 0Sh%,Z\ZTXZl(j c )*J:%gȉZD"s A@bZvjehqbz_>PMQf PEBrOpfz[bNqA|d020724v2562:7dOÒyyҰQFY{l2VW>K˔E8vNp{ẘzK.Z,_yLѵ_ջ!{ aǹVZ\Z¦}ۥ'.fbfd`\\iPn 2X+NW`j֞ dA XXDf-~5LަJ/0I0318 ,|T19~6SEbW2d[~D]Ϲ^N^Fߥ34PK[J/BfX[A3certs/keyUsageNotCriticalkeyCertSignFalseCACert.crtUT І?;7AUx3hb5hbQ΀Sͣ;/##++!'s( 0Sh%,Z\ZTXZl(j c )*J:%gȉZD"s ∷bVvjehqbz_>PMQf PEP>83=O-18UѠq>Y{ ;V\e=x8O>}}M:ǟ8Kt>Yky;fmm}z0uCH}$j}]r&Owa~K}w(t} Iu?RT}O~]s"=1 a̝*}k[Y?-nWu owjT-*z6ۋ{fPK[J/܇q2 certs/LongSerialNumberCACert.crtUT І?;7AUx3hb6hb|QȀSͣ;/##++!'s( 0Sh%,Z\ZTXZl(j c )*J:%gȉZD"s or::>.^Ւ^<˜'~ƌI:5ZkW2'f]+{s¬7Zdbfd`\\cPe 2X+NW`j֞ dA XXDz~l|ZP7?87̀$il WBc*P܀р$! Rj *EYT<{Pڈs+l`L„׬j<}(8?I{sw)Κ2ٱWƝZK8%/VY'tO†]EJlPK[J/>xHcerts/Mapping1to2CACert.crtUT І?;7AUx3hbZk$Sͣ;/##++!'s( 0Sh%,Z\ZTXZl(j c )*J:%gȉZD"s A@ bobAAf^aIA|d320724v2562\?hx Q:%N+_3+㵷)fX{䆮B ;x\8$IY=z7P`D{%,(.e"E]g,89I`4&k59Ľ 74n0_V9WtRǻլ==_Ȃ𱈱[w-ջd,O+.5I32gaF8"`gƕ 7`4PI(IdR' Rj T@F eT);x%ٽ3&,Q\kIMA ٗƕ=]!OEG"۩Ye覶{BP݃1ׯw۾[vSO'}ReeJUE-6V[D^[PK[J/S$certs/MappingFromanyPolicyCACert.crtUT І?;7AUx3hbZg$؀Sͣ;/##++!'s( 0Sh%,Z\ZTXZl(j c )*J:%gȉZD"s |A@bobAAf^[Q~Bb^e@~NfrA|d/020724v25628GVlz=N|ݖ ۈYYvW}O?8Ӗf+uGkdo %y:_xv;[L>-8}/N_-}?wzrryE9Ľ W4.7DVE@Awyԫny5kOW |,b,"6ef%K< @YXQf +pp U)31q%y00TT0) T-90s2N-ۭt'hb^Sd8 =b}涠ZbU):/?ٴ)g\V}%|mX.3ѝcßgN|3/^EPK[J/PuPO"certs/MappingToanyPolicyCACert.crtUT І?;7AUx3hbd$ĀSͣ;/##++!'s( 0Sh%,Z\ZTXZl(j c )*J:%gȉZD"s A@bobAAf^BHBb^e@~NfrA|d020724v2562zћ8c,5s~HթM.}j?woI22:$}9}$_Ql[6o&g}zL&'-~\߶-tɫT(|/NqqƵ@*H5ι8z< 6fi@EEdWÙ*Q[re5I32gaF8"`gƕ 7`4PI(!˱0TT0) T-I0r̙S>uf>a$.Ow :͸Aᦒ"9f -s5|ZӣwqO$;ZշoO|XsD}\/Zs?8=Brc PK[J/s,t'certs/MissingbasicConstraintsCACert.crtUT І?;7AUx3hb*0hbQ̀Sͣ;/##++!'s( 0Sh%,Z\ZTXZl(j c )*J:%gȉZD"s A@ bofqqf^BRbqfs~^qIQbf^IA|dO020724v25622_>[Vt&Uwd8j]\)`z-n/4ٯt{y.}u/kSlr_<2KnTsxK45v0-*?J&ӣgRZCp|q| PK[J/6-`"certs/nameConstraintsDN1CACert.crtUT І?;7AUx3hbi䴀΀Sͣ;/##++!'s( 0Sh%,Z\ZTXZl(j c )*J:%gȉZD"s A@bX^bns~^qIQbf^IA|d320724v2562ٻѾȃo\ZmRtb ~kz5kd>Ηb_:sع+zK Susk͖woL =~T}:.q58=jU8w={m8Wh921320.nax@ Ye 9WtRǻլ==_)""⧷ͻ˛ϫT 6I32ga8"`gƕ 7`4I0)HHwwWc*-,XZYR\TRjrAԬ ִL_C'wXk|';G-5>SW#4qoҰz?>}BzEj`9UrδnƉ^3 ybB{!~f7PK[J/,certs/nameConstraintsDN1SelfIssuedCACert.crtUT І?;7AUx3hbj3hb|݀Sͣ;/##++!'s( 0Sh%,Z\ZTXZl(o cKMu+.)J+)Vp3Tpv4504014415725DRծ>ade`ne0hdjld8"%.XqG/d=}C>ocmWk[^ܮt>Gsc[,?VjyسɼΜ78{ Ï>l]摨⪜) +Oʟ%gEĽ k 䁞Uf0k[M֎^D*})""} KI O3[| i~F,,c3X xظ<S aBVf PҿfnigR?֪XNy67L_3D6DM%3#/ ^Uf0k[M֎^D*\EENN' nq@?'>4?#`  ,|mUCZN̠ޗXL"~&t#RJl Z[^27(i;V!ɑ7 1iՊs3Y>~hZč ӝV HPK[J/ТF\&certs/nameConstraintsDN1subCA2Cert.crtUT І?;7AUx3hbf6hbYfƩːۀ9M)4P@ I-.QpN-*LLN,I-671 %:%f+*8;ȉZD"s *-,XZYR\TRjhlq6w&9;4G)#+sc/Ac'Sc#' \(>h,s\Cy= u![9GȘtZ< lx.Z^XQe;w-p[~MoͱmvQYJ^oժl9 ?xy31320.nax@Ye ?o^dux^Mr_08eXXD#I N}p>4?#fP ,| 93Iwt?]W-% YNԧ*%O4?#`̱ ,|s}֛vʀ$ol WBc*P܀р$! Rj "@r ?^K \IU,9))I%Eh ;&y7n,q}s#\f=ŭ ZS^$]Y,iFĒ-N<4þK;=+>1Rnڐ?V0s45;A׵~2n`z/n!CT1b,<PK[J/`^&certs/nameConstraintsDN3subCA1Cert.crtUT І?;7AUx3hbzf俀ـSͣ;/##++!'s( 0Sh%,Z\ZTXZl(o cKMu+.)J+)Vp3Vpv4504014415725Do".)lv&9;4G #+sc/Ac'Sc#ò;/ĝXyikB/-ӵ2完F'!&|К-6}aʃkWVL8a^+'ydLR>4?#`, ,|$Vp V$甦&%#f`4FVRxãH_uٿ*&vՎ$ojҿkᒳI:fgxmw)ƻ{ - RQoda:rUKRo7PK[J/kKG&certs/nameConstraintsDN3subCA2Cert.crtUT І?;7AUx3hb:mdŀSͣ;/##++!'s( 0Sh%,Z\ZTXZl(o cKMu+.)J+)Vp3Vpv4504014415725Do".)lv&9;4G #+sc/Ac'Sc#!iE451/xaqoԅ,1d=#B]fE'+Ľ~i]O:Ws٧?U/pD?GRեV)gօ/p]~.zig2NyﴀSreK;/}to_&fFō{ w""a xGD|7ح7=<8\eXXD=ifyp<ª躜{>4?#`, ,|FbނͅJ/?OjsY_=[#]q=VeAqbzY|JznPK[J/*i,"certs/nameConstraintsDN4CACert.crtUT І?;7AUx3hb0hbрSͣ;/##++!'s( 0Sh%,Z\ZTXZl(j c )*J:%gȉZD"s A@bX^bns~^qIQbf^IA|d320724v2562KJ̇Lt_;awe]-,iJEL}G1v?8yu\_uvܗE9yq1]QBr ~'ڱKƈ= ]:31320.nbT3hbT2zDVE@Awyԫny5kOW`򱈱kiYVW)me,g @YX1f +q%y0  A @ʠq)HD$8ˠq)K \Iu,9))I%ET3-!2cpɾ{s7>NM+r ts,;xى+>1Ib/,I{lګ/j b/?aBW]d9^r9sQf+anw="Fw=PK[J/clU~J"certs/nameConstraintsDN5CACert.crtUT І?;7AUx3hbv3hbZɀSͣ;/##++!'s( 0Sh%,Z\ZTXZl(j c )*J:%gȉZD"s A@bX^bns~^qIQbf^IA|d320724v2562K6x[sXzY``\9k E3jټdnԯdmn`BϗtW{Wz7q$[#yUk}f>_)?0G'9kݵ^<7~YĽ ]  Uf0ksEq)yl^ا|,b,"Bܹտ7qF5I32ga8"`gƕ 7`4I0) 9Hƭ < P9naԢ̒ԔҤTÅi)K b$[@9ԊZ2eŏ$N-}~VF~+L&ݾq q4*[ն~<~;(hڼ<򰼜|nDVW~e>a,]wy C#?}8sx=ᬤ?ϴh~{[PK[J/}O#certs/nameConstraintsDNS1CACert.crtUT І?;7AUx3hbZn$̀Sͣ;/##++!'s( 0Sh%,Z\ZTXZl(j c )*J:%gȉZD"s A@bx^bns~^qIQbf^I_A|d020724v2562,(Hm`Q\3m|iJ;;}F%EgKO߫[qJ/8k:cAaˍ'ꭹZo=LDu$߹{u4YW%Xȴu]qA"y?dY$ D~\mwJjW|e R""R<]sǎz)0I32gaF8"`gƕ 7`4I0)5H@@jM"-IF g2t YUJ44s3( ~J}yu\ZAXv;)d?r9o<;1l52 &?>d?IZI̾'?OWjӫ~KהO&PK[J/r2U#certs/nameConstraintsDNS2CACert.crtUT І?;7AUx3hbZe$݀Sͣ;/##++!'s( 0Sh%,Z\ZTXZl(j c )*J:%gȉZD"s A@bx^bns~^qIQbf^I_A|d020724v2562ܜWꡝ%ss~I_RxC@҃lw̸ٖμ*#KYJuMIn3gܖ>P&s95 n)[d]AP7S}G=8 _^׼qq ƥ@*H5ι8z< 6fi@EEnW\Zl^[ @YXf +q%y0  A @@$ 7](m $WzehIU>[.466T?HBՀH@ $ E[zehi3 dv?y^®o*)Yzۿ̞.[vEf/Wwq9*/ۭܿ0툄=y/9!`0s#Aы~^͵5{ܕ)۲k'bnM2ʫ2uPK[J/#S&certs/nameConstraintsRFC822CA2Cert.crtUT І?;7AUx3hbZe$ŀSͣ;/##++!'s( 0Sh%,Z\ZTXZl(j c )*J:%gȉZD"s A@bT^bns~^qIQbf^IBA|d?020724v2562}~ n3%-tjӊ{{Yz<^to'Nj+Z6?س,FW/9}3A╏Y]=ž*j'Vi^윳ņ[oMUjr>)Ľ 4.2zEVE@Awyԫny5kOW |,b,""fi%ޓW/1\mozҀ$wl WBc*P܀р$! Rj @r @4C$)В306<3W(pQyVYM24Zt-q|[!Y Ր.u͟ p nc'߶}k%>rj>%Vwo7Ov#-PK[J/)R&certs/nameConstraintsRFC822CA3Cert.crtUT І?;7AUx3hbZe$ՀSͣ;/##++!'s( 0Sh%,Z\ZTXZl(j c )*J:%gȉZD"s A@bT^bns~^qIQbf^IBA|d?020724v2562Xt@e.k{Y6(:W=qLu?W"6YTZϳ}F;ty!'?mJ_7Ed~/,/R w/F}`W^WUmrl綯ebfd`\ܸԠq<+,b "s6;^5wͫY{{2)ccy=o6gYz[Kl5+d @YXqf +q%y0  A @@ $ 1Zt@0tKZ/= -)0ïXݣb&[Dg_EG;oSL[`Cr;T;u:}~K|?Ou+X&r>|壱"4Z+NTL;7|_%EFו2j*_򤕞>[fC[XPK[J/UoQ#certs/nameConstraintsURI1CACert.crtUT І?;7AUx3hbZa$ÀSͣ;/##++!'s( 0Sh%,Z\ZTXZl(j c )*J:%gȉZD"s A@bx^bns~^qIQbf^IBhA|d020724v2562r3W#K/|Q"S,p5tٞ}(s-CD~M}XSG'9vMxej[_b:8%{M'[^{rB47.3h\l 2X+NW`j֞ dA XXDȊ'qÛ)Q\#@W`03aJh`L0$A Y :H@$ k @@MT%H_Xvu>x\e} C.^ՓqYVSV7X^wN\l˾OMc_MJWWwK=F'ǥn2M8"zDHR 'xm\^078JPK[J/WYFT#certs/nameConstraintsURI2CACert.crtUT І?;7AUx3hbZe$ӀSͣ;/##++!'s( 0Sh%,Z\ZTXZl(j c )*J:%gȉZD"s A@bx^bns~^qIQbf^IBhA|d020724v2562\XjPb\ߥr3ֳ<>%t~ٷKWX(43l՗G/?ʾH>b3^Jm s ~ƪ(}EW9m}EllrlJ]w 73#K Uf0ksEq)yl^,HHے= /s:gUcQ| i~F,,c3X xظ<S aBVf e  .6l+KLIF j2 gge$\Ԟ,`:5-tؾ}#qWS~LljuY#jZ÷:w ,_yB!q+/˺'ƧeM2wJTZ+j$.o4g*KgM*gbfd`\\cPe 2X+NW`j֞ dA XXD&,Wj&.Gn2I32gaF8"`gƕ 7`4I0)eJ;v2].ժT 9ணz8Ҏ&m6,?c`cݝqeE.n?X݊iYoYYň}kv)mDrڥU' ]7sM#ҩW3%N9뒹gPK[J/67/%scerts/NoCRLCACert.crtUT І?;7AUx3hb7hb݀Sͣ;/##++!'s( 0Sh%,Z\ZTXZl(j c )*J:%gȉZD"s lA@b_sA|d'320724v2562L5=wb*W~6x/66T?HBՀH'30TX{Zm6Oi3˼Vɯ^c͹+FUfN;uE0B[wNhJ捾}5sJEVelI^-\$w' zg> G9HJ^Mv3~UPK[J/G =*certs/NoissuingDistributionPointCACert.crtUT І?;7AUx3hbj1hb|ǀSͣ;/##++!'s( 0Sh%,Z\ZTXZl(j c )*J:%gȉZD"s A@$-,痯Y\\Y\RTZh8 ̍ L +;K.qLao11[w?5[K>ɱDz/sWkg ?'6ٱwLrʋ'Rt)31320.12zFVE@Awyԫny5kOW |,b,":Gԕ/^t?eG7| i~F,,c3X xظ<S aBVf Pο)lܻXN򋦶vw]^Z[U`{#-3G%ʤ35k%6i9Й c/X|x S9L+SWڒʃe.PK[J/(y_certs/NoPoliciesCACert.crtUT І?;7AUx3hb6hb=ʧm,~$‭6S&4}ʵby֝ke>ګUSp?s0yPK[J/}-0 certs/OldCRLnextUpdateCACert.crtUT І?;7AUx3hb6hb|πSͣ;/##++!'s( 0Sh%,Z\ZTXZl(j c )*J:%gȉZD"s Y{ ;~!ηMZ:nLs%e0.s15ȝXnPhuOk>MP[ f;w㳅gK],ی'O9~W_'VE2.xWnfbfd`\\cPe 2X+NW`j֞ dA XXDd}w%@9PMav>4?#` ,|v(%]PK[J/܇9*certs/onlyContainsAttributeCertsCACert.crtUT І?;7AUx3hbj6hb|߀Sͣ;/##++!'s( 0Sh%,Z\ZTXZl(j c )*J:%gȉZD"s A@bl~^Ns~^Ibf^cIIQfRiI*HmA|do020724v2562liR߬2; kZxP2Tuޭ8߮C{}id|<[!Oۘ_Ym >nuq>\B"Z<\k7~Z/.fq="33#*y_dY$ D~\mwJjW|e R""rTclLoM~; @YXf +q%y0  A @ -"?Wy͙G<޼fRǡNxDGWW\Ql]SuyTr ;r$ L&F80{%/~RHDs|7xq/R`)wbjFmq&ų,PK[J/ r$1#certs/onlyContainsCACertsCACert.crtUT І?;7AUx3hb1hb|πSͣ;/##++!'s( 0Sh%,Z\ZTXZl(j c )*J:%gȉZD"s A@bX~^Ns~^Ibf^#HQA|d320724v2562o|W?@5\1]JgDl ¿/w۪"k93}K7gOjl|cw_d_нxeL~3aw8Ŝ%+Mۥ}g4ÜBfw_6îq31320.12zBVE@Awyԫny5kOW`_򱈱|^^?rж'< .agd56q_Eπ+̓1(nh)d5`Rh c*;]2aPY Ueeu*_+S]3y,Iq1NMz[)L\'x{Yy]QחX}f!^&fF5U`o*H5ι8z< 6fi@EE$괹%1Sa_a'>4?#` ,|1U ߈aɸd9WG ]ս| i~F,,(c3X xظ<S aBVf PQLqƲ+ΨOM]k׺v27âȅr}9 m/)~*omׄ FT2#IUhq 7uo}k^/[ \7ظzڀsOMPK[J/]1} certs/onlySomeReasonsCA3Cert.crtUT І?;7AUx3hb4hb|1ȀSͣ;/##++!'s( 0Sh%,Z\ZTXZl(j c )*J:%gȉZD"s ܉A@ $-,SXWhl8 ̍ L ׍o_0mlQ֊=#< \w^w쩓.غiw OM.>/un}TWQqRk7.p6xҥ%: y.e$t߇#.TsYz}f-Y.VBkT} "a ;nSUx7ؼ+Y>1߿<{TXm| i~F,,(c3X xظ<S aBVf Pa08䞕]J=Qq]})Nړ'ΘtK:VӴz}`IZZ9m:~xNTK;>=o0T+dz{Ǘ泦4@oӡkPK[J/I!1} certs/onlySomeReasonsCA4Cert.crtUT І?;7AUx3hb4hb|1؀Sͣ;/##++!'s( 0Sh%,Z\ZTXZl(j c )*J:%gȉZD"s ܉A@ $-,SXWhb8 ̍ L K~l ]Z~yͦjIͫUVx)'KaA5c:R!R~yy31320.12@VE@Awyԫny5kOW |,b,">~f!0ÒC8^J@W`03aJh`L0$A Y Z2Cx֩\֜|pF|֖%G&N4Teåϫ}f ߶?3 vqa^];.dW,ݴadz~.r=z0+ 8R)]Ls<{OZnPK[J/"\*B$certs/OverlappingPoliciesTest6EE.crtUT І?;7AUx3hbZhĵрSͣ;/##++A!'s( 0Sh%,Z\ZTXZln c LL-V0426Q(.M"gG y L - ML͍ y id`Sӿ,(' 3/]n+r~3Ȟdde`ne0hdjldCe{~ϽM;?-tSqϟlAf37L*|N~ˬ|v̬?#kJslNsGh )m 6E{[kpf!}^K^55Lxt#3#*ydY$ DlyML\r$@EEpkk;oLS5H? 0j ,|>Ecy|mS)(~ @|صx[V[uӞ.[_K=7twēJ'_q*8t}Mmf:[PK[J/k (Pcerts/P12Mapping1to3CACert.crtUT І?;7AUx3hboĤЀSͣ;/##++!'s( 0Sh%,Z\ZTXZl(j c )*J:%gȉZD"s ܉A@ bpobAAf^aIA|d320724v256244Щ[*פ??v &nZtp)3ȸ}2bW^f%W%Ӭ_/OY]޼ҋu?^m3c=ڲS 5ڵXc9w˞}{;.31320.n 0^Cw?i S},]qf~_{Z_=:嵝wŃwұI/w?"gKg|3i4'dA~^ 鬤+w/z PK[J/!XOH!certs/P12Mapping1to3subCACert.crtUT І?;7AUx3hbjdрSͣ;/##++!'s( 0Sh%,Z\ZTXZl(c c04RM,(KW0,7Vpv4504014415725Dxo,"1 Kv5G#+sc/Ac'Sc#i5/' ؗRydŤ2oYqnulzCY3s99:kܻNeI>`(PY#׹]>?s-+^v#&czg_Kx qqYS@o*H5}%6(Wuٕ3qd-Z OY>1#**M_Qr‹| i~F,,c3PX d xظ<SL(l|Rv1?;nV?™)_ {=-CDU?֔>vF; K\PK[J/s "&certs/P1anyPolicyMapping1to2CACert.crtUT І?;7AUx3hb3hbn_hfƩۀ9M)4P@ I-.QpN-*LLN,I-651 %3 y L - ML͍ y ۠bA:012 ?'3R7 3/]$HѠq>'Y{ ;ެR X~,k-Tec%V:>k΍j 7< Ā_^~gy?Go7}3^"⚞ei?`p _9.`vmK,h;sRQ&fFMLML@*H5ι8z< 6fi@EEDț//дl-;>4?#`41VDXlƝl\ m@iFU8ـQd8KqzBHFfd*)d&**&(jX\ ̒ ?]`ܔcCPj19) I )9@iE a@SkX~bȮ,8Ѐxg`|\5P+BdR' Rj x@* ^#Zc&ٕ:^snHhw?a=[wOuk꽫ǿ?᷹cs~ۥݫy e[޼-mWW+J- 7f\j?O=xa7v PK[J/VLʝVcerts/P1Mapping1to234CACert.crtUT І?;7AUx3hbzf俀ȀSͣ;/##++!'s( 0Sh%,Z\ZTXZl(j c )*J:%gȉZD"s pJ^F{2?\|DE>Vv ND̘0>[hfPAy'dY$ D~\mwJjW|e R""rfKmYg?+}W&c@W`03aJh`L0D$A  $f)ÌSŀd0lVf (502%#f` ĝ]/p|̋_ޤN\3ugb7UǷ'-:f5҉~FQs{Pƿ3."-Ӫ^ 2j?BOr1o_ixrzklPK[J/fJ"certs/P1Mapping1to234subCACert.crtUT І?;7AUx3hbn䰀рSͣ;/##++!'s( 0Sh%,Z\ZTXZl(k c 0TM,(KW0,726Qpv4504014415725Dxo&qLK5G#+sc/Ac'Sc#no.O`W}P]cUкsܿR8~wbFUly ӝ-#Gꙍ?5.(~; Ɯ?v=N?}#VCDl>6cK|*}NnK=N-}A)y?dY$ D,xb2gOY>1ekw5ߞQ|it>4?#` ,r2]u/wgnovɧynx\W~5;yw&6hWyOGN#ìD,uL>vu[۔qqZU@*H5ι8z< 6fi@EE.i g~|֤fy| i~F,,c3X 8 XL5"H(\<S L u u@ʀ$502% f`8zcmXiSt==-}۝;!֚sߍ?fLL:5TMbڗ5^{̨(tXnyF?](ۻa`]wJ֒`=Cf媞ы&>f25rߥYaU*ϕo2*v@3,u{U=>Ůɍ/]V ~bn7_RiLPK[J/>GX/&certs/pathLenConstraint0subCA2Cert.crtUT І?;7AUx3hb0hb̀Sͣ;/##++!'s( 0Sh%,Z\ZTXZl(g c-H,Is+.)J+1Ppv4504014415725Do*I,V&9;4G #+sc/Ac'Sc#ÆTO,POY/> zW(~7ﯳtwoKa~_浬)٥|*1}{fetx|x:l c7qyCufпSĽ k Uf0kXz):K/t/ c R""T٦t0OW`03aJh`L0$A Y ZD3CU׉? t~Jw-Xd nj|TI(}E_rnnr ZE仮̬#O={Li0v侇2DCW7ZfWLh׭LPK[J/?f,%certs/pathLenConstraint0subCACert.crtUT І?;7AUx3hbj7hbрSͣ;/##++!'s( 0Sh%,Z\ZTXZl(g c-H,Is+.)J+1Ppv4504014415725Do<* ,V&mkFV^NFVo zELtThoW;#ٙ9tr=Nˑxye /*F;07ŠVI/ ںhbIjl+cXwO֭[ZhqqA,b "<[.oZg2O{Ȃ𱈱ɯvixמ #@W`03aJh`L0$A Y Z<3CtwtgXw L;V`]E*)831{|b] vqfˣ2{7Mm]fW"gTdzn岔@Cs1g1(Km˄2S*PK[J/S6"certs/pathLenConstraint1CACert.crtUT І?;7AUx3hb3hb|QƀSͣ;/##++!'s( 0Sh%,Z\ZTXZl(j c )*J:%gȉZD"s -S@ZuK'W 3w%v<#F2GE_]O|%{e?[p9]F5}ɯ9!ڗvzs&fF@?*H5ι8z< 6fi@EEVRg޿A^iH? 0 A|>66THBÀ H112E/30`"+=ےioWewyGXdSRy}Iޝ=ga]|R@gW'Md *x^djgX3v äg&\\=.dfo.PK[J/(LI,certs/pathLenConstraint1SelfIssuedCACert.crtUT І?;7AUx3hbj1hb|рSͣ;/##++!'s( 0Sh%,Z\ZTXZl(g c-H,Is+.)J+1Tpv4504014415725DRӪ`de`ne0hdjld8[2al|eց"oq╤Nkfӻ͢^3W`ٙgs^7kwB.rz'=q{UM,=yC_GJhvB[goplN3IOU찺yO'~3`dbfd`\\cPe 2Xȭ>ά=71]CHY>1G˪}0=jڕfwC<ˀ${l WBc*P܀р$! Rj "*6̯7z}4Kٓ3& Ż2=ۙn?|+і}٬Z+9.,r,Г3EjVPK[J/nxN/certs/pathLenConstraint1SelfIssuedsubCACert.crtUT І?;7AUx3hb2hbрSͣ;/##++!'s( 0Sh%,Z\ZTXZlh c(H,Is+.)J+1T(.Mrv4504014415725DRٶȾade`ne0hdjldX?1rKKrˇBl^j='2\\PK9lQ 3Ky'sB[TnE,pיog>Klgo&=v0;V+/YKj`z9!LaĽ k ސUf0kI,͙d#IC{6޷ dA XXDBꏥq~eS=vvYgn0I32ga!8"`gƕ 7`4I0)fd W<7=(1lskMd[O'Z,7dRQ3~ٵbpi/RoПQrº>dTDzWK}{2m)dzs%m[*PK[J/R(%certs/pathLenConstraint1subCACert.crtUT І?;7AUx3hbj7hb x8<ھ222xrp1 3JH8\‚!% ΩE%iɉ%ņr2 9faтĒ <⒢̼CgG9q^CCKCSs#(q^CdV)CbUqiж^ade`ne0hdjldXyqz௲#9ߤfk_~}|ΣXƿ7w͚n:6ѳ_'2ΘS*^1GR bo%x?~9檇N#f276rx%]QgMAh͢%t=4/"vLnm3:l.Z5ti&OY&fF@?*H5ι8z< 6fi@EEdn%YU|*V/>4?#` ,|ݼ>5q. Χ \Ԭ/|eOOL>ݦ8wWu^OEK}rn}x Gӫ~yzKYۦ;baqĽ j Uf0kۿeEvm;-"@EEɣb@ÒzK-C.fd6c@W`03aJh`L0$A 9 ؀#Z\3fGkZ;-{册偻'3'o.=5vɱS8 }'<^8xI{NNrl/~h>g#oR,;}PbKfY%m{ÜL-YdVq{{̲PK[J/p0&certs/pathLenConstraint6subCA1Cert.crtUT І?;7AUx3hb6hb x8<ھ222xrp1 3JH8\‚!% ΩE%iɉ%ņr2 9faтĒ <⒢̼3gG9q^CCKCSs#(q^Cd/V)(@bUqiA|d020724v25626XY [wf>GEN/҉ZK=~XZySCn%EEW_?sdnۥ{-޾,RW7[䐂TWnN^e?#j\ ZU?x#\}pgu!"a 2˒,*wZ>Eli_,H666THBÀ H112530`$Wx1eooQ|s%yrJ;>4?#`  ,|kqtsK⫙/HaNmwkO+cѰ>;an+̬s%f4{mVK;""a b0@2{U?Ze R""@o1tNmgdI6q_Eπ+̓1(nh )0`Rq 3]ʇoV\zjdw'',;xsB.4掘q]FኙO2a; |pӫ] "  fy~2YVO2VKje2T;{PK[J/(71*certs/pathLenConstraint6subsubCA41Cert.crtUT І?;7AUx3hblg3##/VGw^FFVV_CnN6P6a`C) KX0$D9$3-39$P@$,,YXᓚ真W\RWbP\hb 'k`h`bhihbjnd%k5$:5uحhh8O ̍ L G&>7{ihY;e/jt$|ϭS8:?L؛C_= 3^[!4|XYKzL^P0}zD'QVbݳlj%.0iOCY9M/UTdbfd`\\oPk 2X GȲ77g(Q9m,Hȱwm.qv8yaӅ\M @YX1f +q%y0  @ l@ 3ΙS#Mb'϶roF+o͊.kvxq@Wŕ~ .}d%uyזSX/b8ڒl/8ZgQhȱo6&[gSL͇PK[J/ 2.certs/pathLenConstraint6subsubsubCA11XCert.crtUT І?;7AUx3hbaĸрSͣ;/##++A!'s( 0Sh%,Z\ZTXZlfc-H,Is+.)J+1S(.M"gGCC9q^CCKCSs#(q^CdA(Vjh@Ti%~cde`ne0hdjldzvs7v.Ef\k٦LfXj}-󧁚Q aq9=O*gyS_Τ-8g;tۆ 3V]D_ӠR[gi+3#*ydY$ D6("-fN{@Ӊ# dA XXD>;l}!a~t#=| i~F,,e3X xظ<S aBVf P h+kX"δʢ?+mc5M۽K_.,A17n-b_ޜ_r_ͬ2pez?*ҽ!§KҒsHnWjgJYKBJ=~PK[J/Vl3.certs/pathLenConstraint6subsubsubCA41XCert.crtUT І?;7AUx3hbaĸрSͣ;/##++A!'s( 0Sh%,Z\ZTXZlfc-H,Is+.)J+1S(.M"gGC9q^CCKCSs#(q^CdA(Vjh@Ti%~cde`ne0hdjldؙ#qRwSViΪZe%PΣyӢ[.= ݰ̾)sT *|7GGࡃcD̩dX6YbSNM񕶋 \cudӜ3}0,z:3#*ydY$ Dk{w .h%h R"""0y״6_f|py>4?#` ,|U9~[#my"[.irk_8nGajL}3է_˩pVtgmFt3MPK[J/A-$certs/PoliciesP1234subCAP123Cert.crtUT І?;7AUx3hbZhĵрSͣ;/##++!'s( 0Sh%,Z\ZTXZ c LL-V0426Qpv4504014415725Do< 4kKAL`de`ne0hdjldmYX5J/;5\͉ ٳ+8p:s>_uk t3ܥu8\Ľ g4N{DVE@A`w%?s& }:rȂ𱈱lnlTp>[FM>4?#` ,:Zi4)cc9yϫWB7N{2qɑ >4?#`\GVE@ƀ+̓1(nc2)ic5`Rh JZ?uElq-iMrE?M ݻ \rխty4OyY6來|vO޶דԬ=͏:sd_ԶĺȔUe_y6o[5Y&PK[J/>certs/PoliciesP123CACert.crtUT І?;7AUx3hbZdĽQŀSͣ;/##++!'s( 0Sh%,Z\ZTXZl(j c )*J:%gȉZD"s \A@b@@~NfrfjBA|d320724v2562eڵuU x(n90i3bnk[6%85Ȝ&]Pխ0Ĥi^\w.ck/,'&:,lpOΒ.bđ?s~fImi6:;Ľ 4.1z@VE@Awyԫny5kOW |,b,"}ĿMQ'>4?#` ,:Zu}ry/21320.n6h0zCVE@A=J{>=,HT;;rgqژ}?H? 0 TA|966T# ɀLՀHE830:̮Mt]뺈RFGeu(;n^Y9KV{Wm_/RUEjJK>S@dk{d}ϟy˟O^Y kN^JBgPK[J/%C+'certs/PoliciesP123subsubCAP12P1Cert.crtUT І?;7AUx3hb6hbрSͣ;/##++!'s( 0Sh%,Z\ZTXZl(o c LL-V042V(.Mrv y L - ML͍ y ۥbK.u`pgUƻMP|tio̓|4WfԣrɩWzv}sߕ?:{_}o7蜼0=mj;ool~QS]JΖ]I7=4Ve SzQƠ@Ye vw& 91~up򱈱(wBrl1Ӭ={㺚 @YXf +q%y0  A @ -q:=?'nͅ˗e>-uk¯9;C' ;yn r_+SMU_/L,GO \9>, w/WjLS),PK[J/[+'certs/PoliciesP123subsubCAP12P2Cert.crtUT І?;7AUx3hb6hb x8<ھ222xrp1 3JH8\‚!% ΩE%iɉ%ņ 9fabC#c$gG @N JkO]*J1Y`d8; ̍ L y.ɚD>֩Vr>b_.4hysۃVOJP+l31M2u/4^f UIJw8o&վ2^_ُʝ xD4~ѿs-FdO&fF5U@*H5Ds(3Y wwCUEE, R3}C&0I32gaF"8"`gƕ 7`2I0)fʂwBpKmyz'xJ 96\cN6g&OIT` \goo_>yzڭ kkRfL/|Miz ,xz,],{aVߦ{PK[J/* 2,certs/PoliciesP123subsubsubCAP12P2P1Cert.crtUT І?;7AUx3hbjo3##/VGw^FFVVCnN6P6a`C) KX0$D9$3-39$P@ $,,Z`hdP\DΎ@N8A8!2 x 5 !*`agA|d120724v2562yL*_-/~|*CEJZ+K/_v#KgRʋ]Fݞ`_Ŗeݏ{l/: l{T,lγ [m_c g) .jT#"a uy)ھ!tXȂ𱈱\akԠW4`^>4?#`t ,|(x#3#ƙ UfzAwyԫny5kOW |,b," S_6^iy\gcK8? @YXf +q%y0 QxL e m@ ( Pf%4pe?8)ݽNU +T~ʻ1 sV:=.r99՗~b%|C'$/x$c֕ZlwuUK>|~IG/PK[J/p) certs/PoliciesP12subCAP1Cert.crtUT І?;7AUx3hb5hb|рSͣ;/##++!'s( 0Sh%,Z\ZTXZl(a cLL-V04Rpv4504014415725Dxo4KK #{a#aNe~峠GM{ۇ5%qL.}Kcajљ湋Ϩtp%zn=I=% y_^~VuB[:ll#,HSηキyӭ?@W`03aJh`L0$A Y Z2C%aidpl۫p29w%W|>1fi s~l{ʺ#;mjJg+߲{Ts@vQϋm,[tyMjD;|\3G'F*2XoM-ג#+@PK[J/ĥ-%certs/PoliciesP12subsubCAP1P2Cert.crtUT І?;7AUx3hbj7hbрSͣ;/##++!'s( 0Sh%,Z\ZTXZl(k c LL-V04R(.Mrv 04504014415725Do&It4G #+sc/Ac'Sc#ÂS>}((9؊$3;O.ڹS4G[kϪ7ͫ߫|Sa7*Xm+|x  ]-aΛ-ɞ=%vqwݞ_w=yF{-f |=Q53#*y?dY$ D:dVlwŰ~]˟nM@EE$)ooO\JX; @YXf +q%y0 A @ -w‚:*B6i=}fzwpS/Qy,Pp]$(S %'50oj _,0o8_G s;'.zlʾ;*q|-W#/>PK[J/8I6certs/PoliciesP2subCA2Cert.crtUT І?;7AUx3hbj6hb|QȀSͣ;/##++!'s( 0Sh%,Z\ZTXZl(`cfwOQpv4504014415725Do$pb#$gG#fde`ne0hdjldزkw#~/9$2gL)^Ziߘ>@SjbOϞqoVF)+.;/eŌSII  ]mIOCȧ,sZqDFݥ}qqcAc< ,b "5>tbϊjugN9n R""RZ_m=5R߼^2 YXf +ހ+̓1(nd)d5`R@i ȀPZ',ݏ$VpH]l4dDzrkQX5hۃ5u?yڴ歂vufd:a+*?૯ms/4_SWG?uPK[J/H'vcerts/PoliciesP2subCACert.crtUT І?;7AUx3hb*2hbQSͣ;/##++!'s( 0Sh%,Z\ZTXZl(`cfwOQpv4504014415725Do8TYX0 ?'393X!H4 hM|dW320724v2562ebղ w~:s,ߢXwq;J?uS|v-ܫ_fp<(|r[nd2a rd(e:{*]W~DvO9Ӯ)x*eתM._ k "3#*yeY$ D-k:}Ğ.Mr@EEIת&~Ϙʮe,8pe@W`WBc*P܀ɀ$! Rj Т*K; L Wqi'oMI?M97W߅Gc͝1~S^gjG6]6!ݦ̽oR&}o-L7y<)rK)T#?/x\PK[J/ G>7certs/PoliciesP3CACert.crtUT І?;7AUx3hbj1hb|Q݀Sͣ;/##++!'s( 0Sh%,Z\ZTXZl(j c )*J:%gȉZD"s A@b_@~NfrfjBA|dw320724v25629f,vٝ5Zun׾Q>k/Tga'U[<.`]kղ=5{K5ؠk^]$uSo9J٦:Sm+oq\W~WI3R7v4v/"a ;nSUx7ؼ+Y>1i}D.;%=| i~F,,b3X xظ<S aBVf  x h $95^Eh3ɭaqqekƗ"fϿA.+~N`% w$0`ܕ);9lG&6uֽ7Ov0(x5H_׹VF~m|oOPK[J/M6$certs/pre2000CRLnextUpdateCACert.crtUT І?;7AUx3hb7hb|߀Sͣ;/##++!'s( 0Sh%,Z\ZTXZl(j c )*J:%gȉZD"s |A@bdAQsB^jEIhA PA|d/020724v2562L9WI9{Jn֏2ۛx̟q\t |̍x)_=ya{L,UoUx@'K.;}"N%#uo.L뺹*"vw&fF5U@*H5ι8z< 6fi@EEdoXΩc׭~$0Wm}H? 0 A|>66T?HBՀH/30Tj/&certs/requireExplicitPolicy0CACert.crtUT І?;7AUx3hbd{3#/VGw^FFVVCnN6P6a`C) KX0$D9$3-39$P@$,RT tK/2504014415725Doɢ̢T׊̒| Uih8 ̍ L {\st}o:_]_cυ NZ*PM[(ZvjfP¥WVV=v_"|[=߼uӎ#UM2to|_[Qn}g~y(74v}""a ;nSUx7ؼ+Y>1)_7 Mm$Qէngd:6q_Eπ+̓1(nh)d5`R@#Z3*!zCIs=g[>~˷Boo 5XlUf6؞ŀۂ-*]_^xo5c_[͑Kz`ާy!g/>PC*j<;Ym_V\PK[J/.)certs/requireExplicitPolicy0subCACert.crtUT І?;7AUx3hb7hbрSͣ;/##++!'s( 0Sh%,Z\ZTXZldc,J-,,Ju(L, R Ύr&&FQ⼆\S5PX'ú$`ȰKh-!Ydl?%{o6 vk2sNλQ4Fֵ;=K-i6RRrˎjɟ&ݻK8\1gc.ҫlN)=kVE&fF5U@*H5gmNM`nj&:n>uY>1vI].6vb1'WӀ$l WBc*P܀р$! Rj *|^ᙚ`)9{s4ӿj Hגee[S߹׶\dbu7qK|-[x>ח 5\T.쿟j1'>cuћ{zuo3gk=Y@ PK[J/DN .,certs/requireExplicitPolicy0subsubCACert.crtUT І?;7AUx3hbjo3##/VGw^FFVVCnN6P6a`C) KX0$D9$3-39$P@$,,SZXYZQY* K y L - ML͍ y ۨaQK#{ᐟAޝeYT>+%qc\oo9CȶWMOEUV;f-٤xCQYBe]s+SgN7{ĩq|pPK[J/ 4n"1/certs/requireExplicitPolicy0subsubsubCACert.crtUT І?;7AUx3hbmIJрSͣ;/##++A!'s( 0Sh%,Z\ZTXZlac/J-,,Ju(L, R ťI@h 'k`h`bhihbjnd%k5#RmMJx-8{ ̍ L 7M'i:pr"&_9ѷIN n߰Ģyx.. ^ݙQ7UZG>1U6*Wc½ F=,8;Nw/(/,y플 FFLC]*pн\qNbĽ k Uf0kiIlb쳤*;Ȃ𱈱D^(zeASby'= @YXf +q%y0  A @ -v滝oJ&V?wz Gk#J?V<=ˇ9e{6ߊRڍJ\n6Iזzkjiwq1Αs߳ |[c;c^b~_U._ XVXPK[J/ @'certs/requireExplicitPolicy10CACert.crtUT І?;7AUx3hblg3#/VGw^FFVVCnN6P6a`C) KX0$D9$3-39$P@$,RT tK/2504014415725Do"̢T׊̒| Uihh8 ̍ L gZڿ\t'P$EGI]'?[<%3\I_IYso3_#|ˋI7pz}cOV~N/6湶xFe[ͻ7~)_xT&fFō}@*H5ι8z< 6fi@EEKڎ\]Tf熥yf| i~F,,c3X xظ<S aBVf P 40r930tY uցW$9lR܃3MQ&Ϣ>wdLy 2U2iN/L-X6QiӦk˺ ɓښ\ykcif&\YRvZ4W"PK[J/LD1*certs/requireExplicitPolicy10subCACert.crtUT І?;7AUx3hbhk3##/VGw^FFVV?CnN6P6a`C) KX0$D9$3-39$P@$,,UZXYZQY*  y L - ML͍ y ۧfO}ťI@+#{aomfco0] 4<07P」Ee\Gx֒]oaJK+ˬ»]ru]|iɃȺ)f+pP|hCMn?$5_HwXƠ@Ye /fNck;ruQȂ𱈱,vNW%y]Œ=>f5ŀ$l WBc*P܀р$! Rj b*ӟ}V|fRYW+÷$\&{sHenN]fqX)*U?L JD|vRigw;}E_|l^jY{x[揫a)PK[J/h1-certs/requireExplicitPolicy10subsubCACert.crtUT І?;7AUx3hbnİрSͣ;/##++A!'s( 0Sh%,Z\ZTXZlfc-J-,,Ju(L, R ťIΎr&&FQ⼆\4PXJ`ȰSRguzz/"ﵼ6vrMŞ“&/WQ[PμE9 w;mw[JJivvcڴ}f/r߻vݑ/Z~i>yRg;s\/gbfd`\\cPe 2Xb}Uץ^,sklVS dA XXDr3 [ˡf3o4I32gaF(8"`gƕ 7`4I0)xgŖG_EL\񈑯lβ^1O#b6%vBe^G^љʹtgN`|̻-dޓ>4yS[j뤟~o'OzPK[J/ !20certs/requireExplicitPolicy10subsubsubCACert.crtUT І?;7AUx3hbkĶрSͣ;/##++A!'s( 0Sh%,Z\ZTXZlicV(J-,,Ju(L, R ťI@h 'k`h`bhihbjnd%k5'V-mX8ك ̍ L lTXܢSyo\t>[ iu#rz)VWΩ9]kG9uoP|cߜ~[AWV,Xe'wTᄊBgW0[YcJ&fF5U@*H5f-Cfi R""2zB+%*lz>4?#` ,|m:b?lgWw_r8+ytӋ ;.6 sW^jZ1^Efe:0bjPK[J/l?&certs/requireExplicitPolicy2CACert.crtUT І?;7AUx3hbd{3#/VGw^FFVVCnN6P6a`C) KX0$D9$3-39$P@$,RT tK/2504014415725Doɢ̢T׊̒| Uih8 ̍ L ;};G-tGY߻=Ttx.\Svt~ynNW8- żq M% j!reU{aw)V}cTO +6,e>Ϡ@Ye 9WtRǻլ==_Ȃ𱈱6M>bF9%' @YXQf +q%y0  A @ "h`dBrf`@dDWRۭ=fƿ~XMbOw jՖʟȫf%i뽛7޷ɿ9bu ϒ:As ?mn«nZȷf2wrXN^0*{;\? NPK[J/$!0certs/requireExplicitPolicy2SelfIssuedCACert.crtUT І?;7AUx3hb1hbрSͣ;/##++!'s( 0Sh%,Z\ZTXZldc,J-,,Ju(L, RF Ύr&&FQ⼆\j[8? ̍ L ;?vR,Ď/%O_[b[؏M|j.caUaeqSO۽"%䀚>Um2trr -,Vҹ|@k}͜L]* >VᐤxƇG7o︰!qqA<,b "lM߻Qj Y>1g=ӽ}dPRbgdE6q_Eπ+̓1(nh)d5`Rh 6Xiz_On_׈4K+ []UҞ-sKSWs)y͍w=MϽM^yN(s6.=~@uSLy3b_PK[J/,+#3certs/requireExplicitPolicy2SelfIssuedsubCACert.crtUT І?;7AUx3hbd{3#qjy}eddee006dceaf 62qCRKSJ22KR U Ar2EE9ə%@H4@N JK#\ouK}UYLk5ϟiej஖___̲'[zI_8T%scWzh 7Y6}FЙrJ=}M ;$υ8~C53#*yWdY$ Di^{, e|7Ȃ𱈱\)Ě(6_eYzm| i~F,,d3X xظ<S aBVf P5^[w̫Qjd߳gd~Q+΃,w$qGG҉ u$gNw8;wJ&5/o{,sPfjl[QŻYǧoiz7Ge KmPK[J/1)certs/requireExplicitPolicy2subCACert.crtUT І?;7AUx3hb7hbـSͣ;/##++!'s( 0Sh%,Z\ZTXZldc,J-,,Ju(L, RF Ύr&&FQ⼆\S5PX'ú$`0wc'2[qP+D@vMmΒoxs v_9s[Swfʙ߯nKwc}ٙOY>j\{2){k>;S`Ͼ[Ľ k ^Uf0k~sP?ۧJo(- |,b,"4={?]yղWO @YXf +q%y0  A @ -"D{ƼhoOq,H?ss<1G;OyJ<)Vm r)%} ^zy"b k+UñHbU gG?OW 0m6<}Nm~)PK[J/ā?&certs/requireExplicitPolicy4CACert.crtUT І?;7AUx3hbd{3#/VGw^FFVVCnN6P6a`C) KX0$D9$3-39$P@$,RT tK/2504014415725Doɢ̢T׊̒| Uih8 ̍ L OIhiaV+{rgA=zkځ736{4swO,T.[q7d2`E٧1N;2PK[J/7H0)certs/requireExplicitPolicy4subCACert.crtUT І?;7AUx3hb7hbрSͣ;/##++!'s( 0Sh%,Z\ZTXZldc,J-,,Ju(L, R& Ύr&&FQ⼆\S5PX'ú$`Ȱl'SWnor9GN}=;Y<7CrƎ8~7zs 'lK3"Dsc?7fgm;npo;/~Lɋ5os^8N&fF5U@*H5M{a+orzf@EED9ѢP3qߢ=ׯv^`Q>4?#`D ,|ĪƯshǟn\&C>H7or~[l}b&fF5U@*H5('Zp&[k7>j R""/g OO NT^=À$l WBc*P܀р$! Rj b*L[v̾ڔ#*Ȯ5/OT-bxi9Oʮ|,xV*'Y#z6^Wm!WW}[ۣMlγ},qR+==<;0A}YjPK[J/!2/certs/requireExplicitPolicy4subsubsubCACert.crtUT І?;7AUx3hbmIJрSͣ;/##++A!'s( 0Sh%,Z\ZTXZlac/J-,,Ju(L, R& ťI@h 'k`h`bhihbjnd%k5#RmMJx-8{ ̍ L ;nVxnC_'?4,cXʅ:2K>ٰ΅K {qqA+\os|um.iӄۉR]XɂݪՒ;Ƴ 㲺J&ֽՍ|nۖZcwke[6r$PK[J/S|=&certs/requireExplicitPolicy5CACert.crtUT І?;7AUx3hbd{3#/VGw^FFVVCnN6P6a`C) KX0$D9$3-39$P@$,RT tK/2504014415725Doɢ̢T׊̒| Uih8 ̍ L S}g3_&d֕uF{=23(^*"*{M1uSBߓ_& J{3!L\L?V6dFŧ3Λ]{'%z>ksLQRCc~kS&fFō}@*H5ι8z< 6fi@EE6ݏskH9YzH? 0 A|>66T?HBՀHAT hQ >åW7)s|9;m\K%OJYJ<2dܕF]'av-X&.?=xόm1BzO_I]vvqRƠ4w- *o߿];^?ܠPK[J/օ(/)certs/requireExplicitPolicy5subCACert.crtUT І?;7AUx3hb7hbрSͣ;/##++!'s( 0Sh%,Z\ZTXZldc,J-,,Ju(L, R Ύr&&FQ⼆\S5PX'ú$`Ȱp"=v3SSpxiYnsk~k˚m_מh 3:wƹy旭 } ~հodT@wWgկv7KmPja 'Ϲ?ԣk I1mvW?j޵Q],{H? 0" A|>66T?HBՀH730T?2I?t*a&;V~Y*VuҍlܓN/ϹfF˟]Lڳ3k/^R'ȟuA`߭e[d)/)}4~''-k9{gܶPeϽ޵JJINҶ{g$ PK[J//,certs/requireExplicitPolicy5subsubCACert.crtUT І?;7AUx3hbjo3##/VGw^FFVVCnN6P6a`C) KX0$D9$3-39$P@$,,SZXYZQY*MK y L - ML͍ y ۨaQK#{IVZxyvY|2ucE`~~~ nr0YZu(ʠUbU5^<5K):}w7ѧD8])(ZPF {f:w>>qqA<7,b "Sۺ'":kXY>1Ib+W?xe|[r>4?#`t ,|{#_m6cb,c5ksf2˚ޑhįݟ"Ԋf5KyñsU/֢Cuے_Eo(Wp٩ѣWawJĽ   >Uf0ksEq)yl^,H\% :>%z𬀟H? 0 A|>66T?HBՀHAT hQ (̉s^Ygf2cG=Vv-7BXjN[WQsqqD-=1yWӢ̘)zM9*6Q3vNwgZ=6o ,mPK[J/FH2<,certs/requireExplicitPolicy7subCARE2Cert.crtUT І?;7AUx3hbZjķрSͣ;/##++!'s( 0Sh%,Z\ZTXZldc,J-,,Ju(L, R Ύr&&FQ⼆\`0PX'ú$g W#Ⱦbde`ne0hdjld۞ƶc%n{xhx瘇|/(hNK=u$x-eX~:+SY3*WoŨ4dH>~[1O^eex_Xn3=zͻU׵+{/)~2d/3#>nydY$ D*>X)Iփg| dA XXD^gp{3[9| i~F,,d3X xظ<S aBVf P 402f`@)uLc矿Z~n^c=r[뜚]?nT0#|WφOv8~+l{K(&Mk;XWe,:j'I]PK[J/WA2certs/requireExplicitPolicy7subsubCARE2RE4Cert.crtUT І?;7AUx3hbh$рSͣ;/##++A!'s( 0Sh%,Z\ZTXZlac/J-,,Ju(L, R ťIΎAFr&&FQ⼆\H-3ЁXRA&}`Ȱpcu6t=ٸʩ!.:CJVζ~W(uYaGUL%닺 O9kgUgvhlоRVH]yD>-3s.2}͖:%C+Ľ   䁾Uf0kyy\lޛ#XJ{Ȃ𱈱ݵxs# Yj| i~F,,e3X xظ<S aBVf P 40f`@pW$|t6:ڱӷ濾Ĩ_.~M;CxU_8`CoKUt{|;N?w/=OfD4l{0Ez|1=Y/XY-;,PK[J/:P55certs/requireExplicitPolicy7subsubsubCARE2RE4Cert.crtUT І?;7AUx3hbZn$рSͣ;/##++A!'s( 0Sh%,Z\ZTXZlgcV-J-,,Ju(L, R ťI@jjb 'k`h`bhihbjnd%k5!jC}xFq>WY{ ;vD ^zRG?*y0vͼgO1=s@%1.LϽGJ쒚95|ZжՒAD;AG߉jdbfd`\\cPe 2Xi!]'>7r`)f R""i9/X24%,egd`6q_Eπ+̓1(nh)d5`Rh*븊XbmRl13]90oHEr[Xf!8 nXÃ=JN5uqz[q87{M}ϵ7;ȁǝ%mjt;r76Gɲzn>'2%PK[J/"c"rcerts/RevokedsubCACert.crtUT І?;7AUx3hb3hbπSͣ;/##++!'s( 0Sh%,Z\ZTXZl(`cfwOQpv4504014415725D8opޠԲ$]`xڦ6'6$}}$dFy?rtQ\ wѥ տ꼲\;fUu=oꋖRۓ;Oz}Loj$')ӪKk M7n7dV5ebfd`\\cPe t2XveMسZ庩YSȂ𱈱T|=Mz3;p,?#`< ,7aJh`L0$A Y Zt2C% HY ~.OOS>>pd˂I䙬~Q]~_^b[8NUyĥVeK}= t7URTf4|57xiW=zH0>"ODH]-{PK[J/PZx ].certs/RFC3280MandatoryAttributeTypesCACert.crtUT І?;7AUx3hb:hĤ1Sͣ;/##++!'s( 0Sh%,Z\ZTXZl(j c )*J:%gȉZD"s B@sZO:)be r(@% AFrs&U$pXMLafrv4h ̍ L 3~su飻{E^g\޻:LrL,m[a㉷$^O[{q KgGU6&5ۘwĴj!wrF,a}^]JwkX?͙) .6W9f(Uo)ج#qqA<,b "s6;^5wͫY{{2)ccYۻ fEG"ߠOuj @YXQf +q%y0 A'+ Rj R30T/,萟EiJeyk?&\)o#Ϝo!,w'Mic>L$2\B9&;:]?Obْ ZMϸʺ%F|3mٗ6簃~WPK[J/Ռsm-certs/RFC3280OptionalAttributeTypesCACert.crtUT І?;7AUx3hb:kd1рSͣ;/##++!'s( 0Sh%,Z\ZTXZl(j c )*J:%gȉZD"s gl0{bfIFjQqRiQ!7HXK+?#ϐˀf 462K2K2Ka39;p8:̞0xY|\ ##+sc/Ac'Sc#õm9qgz-ts*qJCUٞ=NY'ULViu9Ɓl;+/N8>[7=eĻ7V`}cCÊ+O^AKqqA<ɲ,b "s6;^5wͫY{{2)ccY8ВdR @YXɀ@W`03aJh`L0$A Y ZjaJcQ6oL޸bNo6Yyտjܤ_Դl]X2o߼kwkάǻHi޵g3g}tAk1UMw8zEy+Wn/.t# PK[J/sD7certs/RolloverfromPrintableStringtoUTF8StringCACert.crtUT І?;7AUx3hbbw3#c/VGw^FFVVCnN6P6a`C) KX0$D9$3-39$P@$,RT tK/2504014415725D$o)"\̼Ĥ +]$_!4sv4h/FV^NF-99hAWFiu'~|dAɵ3WUeuSԵ:,$8rp&[։翽wv=1ӓmXIz;CK).1]oׯqqAwY{ ;,`."azuy}cS(1fl`R@sqj.Z3ْ)I7ċg'?Wn~G]t+Of_|_]9)h=3#*ydY$ D~\mwJjW|e R""CrF -*g}ܽި}| i~F,,LL, WBc*0r  A @ -486JԽ]>[BWX;uJ\֚~);}cͣiL 3r[c]-K|Mucyw7=ۛLNW=PK[J/ ,~8certs/SeparateCertificateandCRLKeysCA2CRLSigningCert.crtUT І?;7AUx3hb2hb|1ÀSͣ;/##++!'s( 0Sh%,Z\ZTXZl(j c )*J:%gȉZD"s "A@bjpjAbP Y^!1/E9G;XȠq>wY{ ;&k>ynug}jzSrNoa6uiփ5YW&oy[UߺC7j+j&8\Aojm7JX>eϯ_ xt,}αK..2oƴG5gd$"a ;nSUx7ؼ+Y>1?nN9)|"@W`03aJh`L0E-30~Oܵ#t7ΰ{Uor˖\~8;O]eɼ%'on]|Sr])\vTfl`৆YLi2'o)LyL=C7\vegn`,Is>PK[J/)98?certs/SeparateCertificateandCRLKeysCertificateSigningCACert.crtUT І?;7AUx3hb6hb1ՀSͣ;/##++!'s( 0Sh%,Z\ZTXZl(j c )*J:%gȉZD"s "A@bjpjAbP Y^!1/E9G;XРq>wY{ ;IzcsWӜ_"MEaޟ __Ff\ x[ ʓ{e3gFbs۟72 ߝp;3kDn}qK[uV{Oqfbfd`\\cPe 2X+NW`j֞ dA XXDfQR7Tr©|sō| i~F,,LL, WBc*0r  A @ -:uYʵ5+]^zRԖT?ċO>pOh[ۥfNK7o`˚/q_YpaZ+-NVY2b Yyu2=1\E"^BV~XV2sPK[J/;N)~5certs/SeparateCertificateandCRLKeysCRLSigningCert.crtUT І?;7AUx3hb2hb|1̀Sͣ;/##++!'s( 0Sh%,Z\ZTXZl(j c )*J:%gȉZD"s "A@bjpjAbP Y^!1/E9G;XРq>wY{ ;Mv|WtWʌϽ_,'xۋ ѸsfJ]k4 :42Qn)bŞ^K;nac4O^/wnvI#,:121320.64IVE@Awyԫny5kOW |,b,"]4#+{n?Rص,H? ( A|>66T#Z2aGզ6Lnԝ|g oR}1FqFn6KR}3 PcPhc3ry?A [7sv;Ǜxy|dI%&%+y)PK[J/.<$certs/TrustAnchorRootCertificate.crtUT І?;7AUx3hb0hb\рSͣ;/##++!'s( 0Sh%,Z\ZTXZl(j c )*J:%gȉZD"s`C|dW320724v2562\Ӱy%2>j4?#`T ,|mOɛeM~yg{˄?8s&WbONܼ>E3Qߴ2-X$T,mw4O~,zhiězu^&fF&&V5U@*H5ι8z< 6fi@EERj!oFb$sBԀ$Ul WBc*P܀р$! Rj "2&0Fi4;/|c`L|a׼9.{^3|fɾ-,?!Oe.w7uh/՜ˣebjvډ1ݠtŝK? vg7nPK[J/7z;(certs/UnknownCRLEntryExtensionCACert.crtUT І?;7AUx3hbj1hb|ǀSͣ;/##++!'s( 0Sh%,Z\ZTXZl(j c )*J:%gȉZD"s A@b\h^v^~ysk^IQkEIj^qf>PѠq>?Y{ ;v9[x(ظVp^b GW"i2DK_:.z#2Oν!uz/]b̾bOCQijA~ZgI6WxK 'euXv^C|Ȝ7N?T=#"a ;nSUx7ؼ+Y>1ѯoz~U9Mm0I32ga8"`gƕ 7`4I0)Hf ئt7Ti+ԸKoq/璶_7Z.[{dۆAO+yNuSpWycEz <]ї6D]2yQYm4>PK[J/l3#certs/UnknownCRLExtensionCACert.crtUT І?;7AUx3hb3hb|׀Sͣ;/##++!'s( 0Sh%,Z\ZTXZl(j c )*J:%gȉZD"s |A@bDh^v^~yskEIj^qf>h8 ̍ L p۫p|As_s0!H(x[0*'kzVY*p 훷 UyOk.='1-5_#JA _Θx~Y=2.jޙ0FRp{Ơ Ye 9WtRǻլ==_Ȃ𱈱duֻy/nYmgd76q_Eπ+̓1(nh)d5`Rh (;[Vnhޝa2aV+^Z{֜jJSiwm>9/o3Ype{#W>z|#g~K2y]}a:?4m0uϙBKkPK[J/H%certs/UserNoticeQualifierTest15EE.crtUT І?;7AUx3hbzoQÀSͣ;/##++!'s( 0Sh%,Z\ZTXZl(j c )*J:%gȉZD"s ≷bvhqj_~IfrB`ibP PYCSȞbde`ne0hdjldE|s/jvt Ȯ7d=`y6;[|a/bs7N8еHIM>vZT2Ż])Kzmm[F Z&fFō7 &"a ;nSUx7ؼ+Y>1ٮ  ?uMj\ IPH? 3fKAAWBc*0  28ـd#UhhYD% ̓oZQ~B!< JM/R(EYAiQA~qjB~^N%ZzbgvӌvݞI98Mn2XKe59Չ&Õum;}ȓ?}6_g}ٯ3]dݶt ן_sjzf,KެGnh.*a"̩G%|mPK[J/.@j%certs/UserNoticeQualifierTest16EE.crtUT І?;7AUx3hbN3hb:Q؀Sͣ;/##++!'s( 0Sh%,Z\ZTXZl(`cfwOQpv4504014415725Dop"T+zf`Ȱ` 'H~(wT:= w}`O3'[1Ġ1@;Ye z˚N:gEuSD7)ccqqSXr2+Ǖ; A/A_KWOl\ mH6`42`f/;ATTBHFfd*8iE 6ԃ*MF n 7-HmEũ y9eH63d!%QhDF0g椀x I )9)hɘ߫:3N?穃в2(s'n]#Wk<G?W}~p/nݿ$S=}.TKgGzՙwtWƢ ra<#\ޣ*sjdG;PK[J/u%certs/UserNoticeQualifierTest17EE.crtUT І?;7AUx3hbzl䳀QĀSͣ;/##++!'s( 0Sh%,Z\ZTXZl(`cfwOQpv4504014415725Dop"T+z`ȰqNF?"V~qNi=cݡoB=J=OZMìuEb w?ٴêzGwItbϊjugN9n R""rm}HAO(}!8e03|0X J XL, 6m6`31HE[)(dd+QIFB)(` VP]c=d0rJ@qUPZT_ZSm"M}6;CF2OoI_N#;:>)Ņ|Z8/}}÷=촚ͻ#w{XD sq%柡ok^|ϸe\m?+?PK[J/]%certs/UserNoticeQualifierTest18EE.crtUT І?;7AUx3hb>jĬـSͣ;/##++!'s( 0Sh%,Z\ZTXZl(a cLL-V04Rpv4504014415725Do"T+z`p̹ƣ^Wab e۳_ǿ^]蹬S'KmgSU'6ÂU/O>78ErwGϮ _s߸^ǻBoGGụebfd`\ĸڠqKDl821ɕoNeŝ5Ur6oW`/\]S5PK[J/=o)%certs/UserNoticeQualifierTest19EE.crtUT І?;7AUx3hbc캀QӀSͣ;/##++!'s( 0Sh%,Z\ZTXZl(j c )*J:%gȉZD"s ≷bvhqj_~IfrB`ibP PYCKȞbde`ne0hdjldudje&'LY8@k;Dn>-:o߿ vD2.B˞Oq@<5ɛbqLlӝo9WBrXĽ 414NVE@Awyԫny5kOW |,b,"e^\ggl<l5I32gaafb43$Ę$q WBc*0 | `f6;g%hVhf\`ggg`ldaP\TĊ\̪TԊ̒Ԋb#ĢԢbĢ<T<̼tgb1ɩ)@5@#r2s3KB2JhJ2RGBB:ԴҜJļTTgd(Cs+b Rt L`j44Q,,*m1,{xyK]o̖?R >%1B% U.}{͝}QQo2ᅬ{ٷŠڻm fbN̒PK[J/I:l9R+Wm|n ρ>p:ޢnuERClM6Ľ k nUf0ksEq)yl^,He :ɼa+i2mgd,6q_Eπ+̓1(nh)d5`Rhq  Q G_n%teڔ=L27:ʿӜq6ߥ=raO>q GG Y3B 0-F⡶|:BG6ytmO;rͱwOM;SaGW >STw[_wޟ^6a߲"PK[J/ɖ;2certs/ValidBasicSelfIssuedCRLSigningKeyTest6EE.crtUT І?;7AUx3hbZi$ x8<ھ222Drp1 3JH8\‚!% ΩE%iɉ%ņ 9fadԜ4] ̼tJgG9q^CCKCSs#(q^CdA68Cl KLQ l+ # #a7Xz&ArmK$O[{/?Rha!]&T3kOٵ4\ao5v>19CmD݁uSg=4_w'܏.bPaGk޽ 8 @UYe ϓ3ۤr1L^RI[ dA XXDLLK>_ctΓ֖,!| i~F,,L, A|>66T`Z0`DK @Нgﻖ[th<]I#RIkWc=.ekNy/5Gs- }~_\V⊫gkK\~xxJ9o7 μؓ{X|)ӹd]od4?#f& WBc*00E?30[̺g޲:ވx>WS_)Xt`yfB''8 :'n/certs/ValidBasicSelfIssuedNewWithOldTest4EE.crtUT І?;7AUx3hbgľـSͣ;/##++A!'s( 0Sh%,Z\ZTXZlj cqJ,LVNI,..MMQIQNTpv4504014415725DoF˰ĜL{R3K2puE֮2Ġq>Y{ ;;լ 'cn9wE}3)X{@QOQ”Fu m62Y35T1IOvR{ٟsY:YWXyEM2:.GX>;G}Dp]!3#lLy?eY$ D~-Ѣr{XȂ𱈱T %oaQt:j\i'ˀ$僁8"`gƕ Lh IC:"g =pw,:6Ca;WeMk{E%祶NoXpǩf \:黒/٪KpPK[J/3J=/certs/ValidBasicSelfIssuedOldWithNewTest1EE.crtUT І?;7AUx3hbgľ x8<ھ222rp1 3JH8\‚!% ΩE%iɉ%ņ 9fadԜ4]rJgG9q^CCKCSs#(q^CdA.6:8@l KLQ?'E!<$WWd #{aMo^>2R| )LT[W=0S! iK^LY~ϓ*|AcygUY$*fn5[l*}>j7g\pU&21320.64SVE@Ad>2]vZ,HȦvřJDN򶺡66T`0`D~f` ]^ELϗg{<\N7.P~Rڦg oxT";31320.64zDVE@Ad޲ӇNYQr,) dA XXDLIi]is@c-y,僁8 ~66T`dG%30dZٱ/kL,l @r=')UX~e67Vo*8S&l:imlsmQw3rWp󞔤/geK%ư:PK[J/ ui certs/ValidcRLIssuerTest28EE.crtUT І?;7AUx3hbN5hb: x8<ھ2228rp1 3JH8\‚!% ΩE%iɉ%ņb 9na̢̼ gGc9q^CCKCSs#(q^CdA$䘅Us2S|>pÍo?x$¼WN21320.nb 4hb5KV "4h.[1?]ӭxa R""+Y<ߵ/dΒZ,@̀$僁8"`gƕ cFƇ yƛ //[PʠHP2PĴ$ZL#P@Q 05 EiE h.7hٝ%?x} ʜӦg^dgɞj:=g ]%rBV]}M6|{-v59tSw'ĕ6t?^dˋ3t%\/b~I6LXePK[J/NDm certs/ValidcRLIssuerTest29EE.crtUT І?;7AUx3hb0hb\lƩِۀ9M)4P@ I-.QpN-*LLN,I-60q gd&8(8;ȉZD"s "D@$,Y\\ZꊬRҠq>Y{ ; l欿fg^?feeylnι3r9an_3qHӤ:˧%/rّ^ /k^mp'`K=8@YK-Nޙ5'󙇺ojKA/ydYa 2Mc沵:8 |,b,"wg&:Έ<t @YXX> ,|  IB D%8f`0M> G'7, o՞0Km"O7x#PΥxVd뵍X0"{·Y2s*{qc&ϭmi?5l8KzF)PK[J/Zui certs/ValidcRLIssuerTest30EE.crtUT І?;7AUx3hbN5hb: x8<ھ2228rp1 3JH8\‚!% ΩE%iɉ%ņb 9na̢̼ gG9q^CCKCSs#(q^CdA$䘅Us2S|zaNuY>1 5{g&G&gO @YXX> ,|!ٟiqTV8tҭq3PK[J/7ēkU certs/ValidcRLIssuerTest33EE.crtUT І?;7AUx3hb4hbڵ݀Sͣ;/##++!'s( 0Sh%,Z\ZTXZl(a cK,JM.qQpv43504014415725DDoհĜ "WWd }`p91AD]mףV&Mܧ9}h󎜵rԫfM_5sYTsrY,R>)0w{B}]þ#{VI L^$)2mE*bKyl^vq ._֠@/Ye`(6[%wиKjU'ƴE2j dA XXDj\U8u @YXX> ,|4?#f& WBc*0z  A,>^ ,qB գɐeIWyI9C)wÎOkkNuy|ݥZ9,a1=foB>t~?l7W׶u7SSL.U6%=x ~kU{9?^ҥ䙱PK[J/\;A*certs/ValiddeltaCRLTest5EE.crtUT І?;7AUx3hbV3hb_bƩۀ9M)4P@ I-.QpN-*LLN,I-651 $:(8;ȉZD"s ‰A@ brXbNfWWd =`Ȱ)sNŃ+p['cs_t;Ca}4jh^r>W> +p /Evް(&UV;E?ofx[qwc\Va=*7OyzSqj&fFMM@_*H5LI::5x=k R"""`iI%7E!j6M4I32gaafb` +q%y0׀ $!cem'*D0P=* QZPy3j>|OMmk-lwoewM|LYUټGl_?.8{>r w߽ʳX.οJNdʔ}T4-z.'\ͻ4Rx2~PK[J/TB*certs/ValiddeltaCRLTest7EE.crtUT І?;7AUx3hbV3hb_fƩۀ9M)4P@ I-.QpN-*LLN,I-651 $:(8;ȉZD"s ‰A@ brXbNfWWd =`ȰfQi8t>&N9L{K/2*s_8zѵ)#X{wYr^@dupFq;{F) ,+\#kC]Ʃ }0xc6g_=ӚSf ,.X}κ~M&fFMM@_*H5LI::5x=k R""b@K s/I=8zy\s>4?#f& WBc*0z  A,>^ ,qB գɐe1:svGΫOxh,}i{Ì;N)ܕ&,B&PK[J//0 vB*certs/ValiddeltaCRLTest8EE.crtUT І?;7AUx3hbV3hb_hƩۀ9M)4P@ I-.QpN-*LLN,I-651 $:(8;ȉZD"s ‰A@ brXbNfWWd =`p91ܩ+n>`ȘVu6uC]Hr\f)ݬ{Ju|vҩt҄{wW&!tk gX( ~$PϧJo!bVfs33#&Fq&FaydY$ DO^[d9u?}< |,b,"ki߻>ets|RXU!j]}zy{OIg5xK>{5m6w*8ƨʝ1z,?#PK[J/+-]'certs/ValiddistributionPointTest1EE.crtUT І?;7AUx3hb6hbYhƩӐۀ9M)4P@ I-.QpN-*LLN,I-63q de&dg*8;ȉZD"s $,a+`ponkv_N(yk|tTs3Vt?pب|pnk;ݯ-I+3f\ջ 2?C+l鹦p?b''M4wWLoK31320.nl@9Ye yY?9ƽeP닁,HHVݢ{0O4Ϗ| i~F,,L, A|>66T`t04dYj */(]RlPH7T3PDsB~fDSjcF-}(go_GY)۴s c֜iLa+zܖ]rᙙsTk"_\/t4(ký) cnoNЈV>{NM/8-nPK[J/R'certs/ValiddistributionPointTest4EE.crtUT І?;7AUx3hb:lĤŀSͣ;/##++!'s( 0Sh%,Z\ZTXZl(g M,.)L*- +1Tpv4504014415725D$o1HYX',1'3EBWWd #L #{DŽ5ϔmN? ӵGϺN+_xxȟ-K׬\~V/kJK:嫗myy[vط{BZ'_~+R3&㲣͝Bͳfޱ t;FvNqAydY$ DgKxjAݮ/ |,b,"^Yn5E\7I32gaafb` +q%y0ۀ$!Ϣgc@c $Xe| 0izkqnz5ms}O[!5J 9_eqJ.w"f;m[/x"%W;Y%eվvp7='U'ޏq`0]a`o{{WWm!o}Os7oPK[J/ʐʇR'certs/ValiddistributionPointTest5EE.crtUT І?;7AUx3hb:lĤрSͣ;/##++!'s( 0Sh%,Z\ZTXZl(g M,.)L*- +1Rpv4504014415725D$o1HYX',1'3EBWWd #L #{a ]~M,:vw]~c Sws9NTv~[wguQ%ū%q?o'͘Y6czae:v O;vn;ſH%s2]vt琵2oٷdbfd`\ܸؠq ,|q]}~z&fFō ?='"a be,"H;ˌ:ٞ5; dA XXD&XğRXqE@| i~F,,L, A|>66T`t04dYj */(]RlPH7T3PDsB~fDSjcƆ5:zv="+\wSy=t<)O>ȱMOmotriƆ<%ޯq=*<.2:o[8VgYm߬P«}]rgW>C_z${[6ž]t`NYPK[J/qu1certs/ValidDNandRFC822nameConstraintsTest27EE.crtUT І?;7AUx3hbf4hbZhƩ ːۀ9M)4P@ I-.QpN-*LLN,I-q f&*(䘅sSK3J\ K y L - ML͍ y q1a9)@'($(9[);dUFCBF )sxɄ_k JF۴_~;絓Az^[,+}g9z/f]!S]En^|Z`BZUVc˫`z<3#i >Uf0k _cK__mҬm R""rK n!jL? }ۀ$僁8"`gƕ L9 AEFYH:c$)ZR30Tϳt=XW }+)mnyB+'Nyyryldu@Sß/m>*QiS̍3'*M0SXVگ,ݪ8=x׿mͅKM)PK[J/4J(certs/ValidDNnameConstraintsTest11EE.crtUT І?;7AUx3hb:fĤ x8<ھ222xrp1 3JH8\‚!% ΩE%iɉ%ņ 9faT⒢̼b?SgG9q^CCKCSs#(q^CdA,-q f&324708R/,1'34t׺"[A`03xN΃r<qŧp*ȯ,soٟͧ ;֢a3?+C;|07hh<2Ȩ ]ʨ?su> ]p[ևq7*9Af¶Ľ 2 䁞Uf0k2΅}U7-8dXXDtn__:tm6 @YXX> ,|1/PY,9WλՓY5 @YXX> ,|=[s'~nĢm0| )4b;cL]!뗙V=\t/zmz7s ʼI?gj5PK[J/>I(certs/ValidDNnameConstraintsTest19EE.crtUT І?;7AUx3hbZi$ÀSͣ;/##++!'s( 0Sh%,Z\ZTXZl(o cKMu+.)J+)Vp3Tpv4504014415725DoT[X (7$5%4(5Ĝ ruE6NdA|d320724v2562]Ӽ8sT>j K?+7Y4:YB?R:+ 7~v+}9W߼e+<\3/jMp:RV{a?Ƕ.5WpY#Uأ_,rrgd='"a } KI O3[Xcc T)]g-k+>4?#f& WBc*0-0f` Q@Gܻ9LDkD·1~8ð͙E׶t1_rCƝ=~6:0޸:5R`I;_o86^8!܀y3oUl(VuԲ/nPiPK[J/F'certs/ValidDNnameConstraintsTest1EE.crtUT І?;7AUx3hbZa$рSͣ;/##++!'s( 0Sh%,Z\ZTXZl(o cKMu+.)J+)Vp3Tpv4504014415725DoT[X (7$5%4(5ݰĜ ruE6NdA|d320724v2562lrgKɃVo^KƱlY\/7CA땏Tlߵ+_uOVQgѨG4q헶,~jxⓕR˧*ɇhq,pf^~|x⇩+ZVhgbfd`\mi 2X7v/ov:<&R9/ |,b,"rtU<|^et^5| i~F,,L, A|>66T`R0@O@|Pky.֘C%F?S6Ť,X?/4wS"޳q?{pq{m=!| ,LvX`~D~nmSx03|0X xظ<S$!bhߨ0suuFI2R痡%"f`^?.I;|>zpm g',clK2<7qHs-LX޿ag ϥ/7v+4 f^jU "rE,iZʥo뛫~u~PK[J/@"_='certs/ValidDNnameConstraintsTest5EE.crtUT І?;7AUx3hb4hbZрSͣ;/##++!'s( 0Sh%,Z\ZTXZl(o cKMu+.)J+)Vp3Rpv4504014415725DoT[X (7$5%4(5ݰĜ ruE6NdA|d320724v2562Y]h|oUz[nviPNz`)>7,n7V$4?#f& WBc*0104dY[ S'~ȎԔ a6E7uOV\HmE5K^^ozj&/xʺEo+{|򬂃;vM۵DLK3&PK[J/GE'certs/ValidDNnameConstraintsTest6EE.crtUT І?;7AUx3hbZa$рSͣ;/##++!'s( 0Sh%,Z\ZTXZl(o cKMu+.)J+)Vp3Vpv4504014415725DoT[X (7$5%4(5ݰĜ ruE6NdA|d320724v2562t+3#lLydY$ DϜufvG,ȋٷ 5R6뼓Nّ;/| i~F,,L, A|>66T`R0@O@zQ#j{՛4cݍnw=k1)•.2^ptxr1]#8MjK٦{VuwBRg< Iȣ]fs잻AVՆPK[J/dQ)certs/ValidDNSnameConstraintsTest30EE.crtUT І?;7AUx3hbkĤрSͣ;/##++!'s( 0Sh%,Z\ZTXZl` cKMu+.)J+)Vp 6Tpv4504014415725D$o2Ĝ ֺ"Qbl`8ُ ̍ L l9geuUkOkjvNﴌ㝵)4VOxcO 2Va;su w7)^qCd Qk>VkxOTe iN~Gӊcteӹ&dVqʏ9Ľ g4N5OVE@Ay^S\a R""gR|}B?- x03|0X xظ<SqnhdQ6PlmIqjQYjzehdևp'9oʒ9]ŕ98};ebnݮsJܽA<᧤'k' Jn{Z6AwЋokݘ򰛭B-RkK`h2uGag=O}:Zga?fz掾PK[J/0lpT)certs/ValidDNSnameConstraintsTest32EE.crtUT І?;7AUx3hbkĤрSͣ;/##++!'s( 0Sh%,Z\ZTXZl` cKMu+.)J+)Vp 6Rpv4504014415725D$o2Ĝ ֺ"Qbld8ُ ̍ L iw8&z\5{yþ-\f~bI~A\Ы7B֔yrit>n6^t|Uw+/cUL.?3#S Uf0kpս9f;:?Y>1ZM}w'Ug>.kgd@W`03aJh`LƹHBE@I%ũEeEz f2R痡f` x%l7bv]zuZ/h(xf7jΚuuїy˟Trf~wQ3O:p?錓/7z~pӹ\=g|9]u/,2IkT7PK[J/$:3certs/ValidGeneralizedTimeCRLnextUpdateTest13EE.crtUT І?;7AUx3hbZdĽрSͣ;/##++A!'s( 0Sh%,Z\ZTXZlacwOK-ʬJM MUpQK( -HSpv4504014415725Do#RĜ@]]+346hmFV^NF$?֢RDjuspEJAg-XS]8f"ǻ)t|ml6#]=_> =ᎶuكS= 7Ku9|v+Jb[5>T21320.64zTVE@ADMD/!i˒]+h e R""¶a3ǵK߇|ÄiH? 3q_Eπ+̓1 Г30&7uY2).j{G>;/uJ܅v7g84r3nMc4n<^G_U؝rͪ;[y&bu_ዂBK-vVf[bUnWLkCjJPK[J/^dA1certs/ValidGeneralizedTimenotAfterDateTest8EE.crtUT І?;7AUx3hb2hbÀSͣ;/##++!'s( 0Sh%,Z\ZTXZl(`cfwOQpv4P504014415727205 I(w4oZdUd*8)+"Vga8{ ̍ L {Kx-;+_5WogC"X\yFFӉoX&2|L F9ϴ1*:%'-h}c؂"p6v&tLװwۨF iיgd)"a ]oYC'Vwnj| |,b,"&2mjxT=9Q6 &cA? 3q_=Y{ ;>}ѵ}A n,̾W jKINvgMn_1/#/⑹d,.R(hj.}y۲w,#Aѿy}'洋\̛죕*XJgd)"a ]oYC'Vwnj| |,b,"S}\x҂USr.G,?#f&  0~ xظ<Sm@P#jq{Q (,0<.!2pߝ*%lr ޶`rtK4õ Tx\;ScTI+~NG~zί-̻L \w.,TsWF|PK[J/Ze.)certs/ValidIDPwithindirectCRLTest22EE.crtUT І?;7AUx3hb0hbрSͣ;/##++!'s( 0Sh%,Z\ZTXZl(a cK,JM.qQpv44504014415725Do9ĜO̒ d;]]5)L122h9FV^NFmE4, .|}ɥ`7K3&{[$f-J'8ֆڻe렘 se7m_TҾ)l_,Q,v~V(֎b+г pv櫊gd' "7>h,sj Y>1w;N59gYt @YXX> ,|0gzW.lnѠc7S31320.n{c{V.6}9CiWh1ioZY[vZ•GLDRׯ'u?9qIwU;E#8Oc}[~Ky PK[J/̞A)certs/ValidIDPwithindirectCRLTest25EE.crtUT І?;7AUx3hbz`乀 x8<ھ2228rp1 3JH8\‚!% ΩE%iɉ%ņb 9fa̢̼ gG#9q^CCKCSs#(q^CdA XC,1KLQt P(,P@Y#SȞcde`ne0hdjldA[U,j;w{p=zw\w=%-K(ڛ%~/޿h`fu&y]*p,[ZEpg+;a1_c$KH)7;q[Nyf0ЫĽ 47zPV "7_/0&sgW9 |,b,"ٚ. ,|+7Rl dA XXDv]$aĄ @YXX>@Sgd2q%y0܀-™v.?+^2zK=E.kώ=v<.f֨yB+nZ3dr_WeΙꪺ e[]%" 5VOn>PK[J/]m8*certs/ValidinhibitPolicyMappingTest2EE.crtUT І?;7AUx3hbnİрSͣ;/##++A!'s( 0Sh%,Z\ZTXZlacL, LM,(K7T04R(.Mrv4504014415725D$oRĜlV+"kRbd8ٯ ̍ L 7>Yx0͵Rsxtl逻NhpCݚʂiWjE ۷q人%55~ϩ|ӄ4ލ[ZnTU_%/HRV$kCn%gϓ>|.ů3}=9~,~Ys>21320.64NVE@ADˀ۫3u7߹L,H% E= hggd@W`03aJh`LƼ3Z3a:.Z~//^cɳ 6jjuD?q88`e𶈛gE7}L"cV(Obeb\"w_(bkjrg?J;r7,QcZdF=M8PK[J/&9*certs/ValidinhibitPolicyMappingTest4EE.crtUT І?;7AUx3hbeļ x8<ھ222rp1 3JH8\‚!% ΩE%iɉ%ņ 9fa̼̤̒JĂ̼tCC#$ rv4504014415725D$o^Ĝl+"kRbb8ٻ ̍ L gJJS㛧ܔ+?rn1{hU%r*E~ʮ*LοahtE]>|+W(㝘{vUɫ.3g+Wԛi7 he)ew'4mDno21320.64NVE@A$ji9-^l,HW-&7";'|̀$僁8"`gƕ |gB*S'3Ws}xhΝWNgUޓzy8j_[̲["V9)2=NĎ/SvpPxY [-yvYm_bߺ,[5s~\dm]PK[J/ԥ,)certs/ValidkeyUsageNotCriticalTest3EE.crtUT І?;7AUx3hbhk3##/VGw^FFVVCnN6P6a`C) KX0$D9$3-39$P@$,,ZZTSYTh 'k`h`bhihbjnd%k5H!6Ksma9) tuE֥2ؠq>/Y{ ;&t|ü܌:<&pAYm}U`QǪ-_OMMiSENr)ʖ%^ut{S wnkSéa˓Dw4.}W`2wWJĽ 2)"a r^kҿNk(|w |,b,"|k$]K^.2H? 3q_Eπ+̓11 mew=\ض2',~vvdjwӟMKy9d|yu\3zySZfXİ8R⠾ӂػn*Oj* V(RwfQiaPK[J//B'certs/ValidLongSerialNumberTest16EE.crtUT І?;7AUx3hboıI_@PHȀSͣ;/##++!'s( 0Sh%,Z\ZTXZl(g cKWN-LQ+MJ-Rpv4504014415725D$o)*Ĝ,"kQahf8ك ̍ L \úpnW7I`iϖ"sܗ|hdELEϽbTbu~id;/Nv!ϝ+6ݙwʍQoeS{OmiNl5l[϶(X'3#lLydY$ Dz~l|ZP7?87@EEJiB&Uқ]o3I32gaafb` +q%y0S#Zd3مqz,n)}OK7r|n["-fv1.}}>WYR9K-xVR ž*^Y#8g+5 {jl;3mӓI<ޒdZ/mK}t$PK[J/9+@'certs/ValidLongSerialNumberTest17EE.crtUT І?;7AUx3hboıI_@PH؀Sͣ;/##++!'s( 0Sh%,Z\ZTXZl(g cKWN-LQ+MJ-Rpv4504014415725D$o)*Ĝ,"kQ8ك ̍ L '['X̝!B$+Xe3gU' 6ŵ.f- fчRG]&qh'׳]trᦨYm4"!N+:~NrF&47>[qCu{?cϟOz 3#lLydY$ Dz~l|ZP7?87@EES_-;=~*>4?#f& WBc*00E630W]˚pCOe[W}\t6ݞkNtgb)\H`4iPt?36]n+ {M;7^/#*b5uWǪ_E\;{5/zM[.PK[J/!@80certs/ValidNameChainingCapitalizationTest5EE.crtUT І?;7AUx3hbj7hb׀Sͣ;/##++!'s( 0Sh%,Z\ZTXZl(`cfwwQpv4504014415725DdopĜT̼̼tĂxUbIf~+fi`ȰhJj+V|HxEM/]՞`r'V> 1\Q^ntK ^8`Y΍kWl9]w˞8 @KYe z˚N:gEuSD7)ccyg -GNXUYXX> ,1aJh`Lƴ#Z<3!#\+sS'nthȩu&+VO6y[WMurG./{٭w6\HFù>\{8qiG't-o{p s/`7Ʃ2PK[J/q@,certs/ValidNameChainingWhitespaceTest3EE.crtUT І?;7AUx3hb0hbۀSͣ;/##++!'s( 0Sh$%,Z\ZTXZl(b dvOQgG9q^CCKCSs#(q^CdA: R6X`c`8,1'3E/17U9#13/3/]!<# 19UY$cȞcde`ne0hdjldXj׳ ^[.oZ2_Y+ICyK2&s&if~ Ԏs|([T3h.jWԢ3KvJmW2]s Ľ 2 >Uf0kٮ{VT\75?KtqY>17.]tXQ:3 (%р$僁8"`gƕ jFfB?/yWx<*lP3Ol 3C)Q_:vd:/j R76I{UlAluf؉gyzrw gL-Η<6w|}nACΑ§uPK[J/RC,certs/ValidNameChainingWhitespaceTest4EE.crtUT І?;7AUx3hb4hbǀSͣ;/##++!'s( 0Sh4%,Z\ZTXZ`(l fS y L - ML͍ y VHH@İ bqXbNf_bnsFbf^f^BxF&PQAbr+FI&}`Ȱ%XwkmɽZrbòfƒ݋ػE[sβҘtkJ=G]^u`B 3#lLyeY$ D-k:}Ğ.Mr@EE|ff)Tske~>4?#f& WBc*0 bѓ%Ud'3ry7Ԫ+g_qg+j|[/I[nufzVVϸuiփ'/Nݓ8VSל_}//I0gi1xj#rzCL?E"OPK[J/␄"vcerts/ValidNameUIDsTest6EE.crtUT І?;7AUx3hb*2hbрSͣ;/##++!'s( 0Sh%,Z\ZTXZl cf tQpv4504014415725DolĜ Ȋ@ #{ȕ'"\g}zw&s#)97ݺ,;r0*Ky߻!;>"ȡ\Og} .nËSuLRrT=gE݊d&o.3#c#lLydY$ D.)j,G2g*D dA XXD|nMI+͒ ?y? @YXX> ,| ,|Y^l-;smMr7c~(ftQBW}Ryy?~= /dwK~uhkn,F[{g /w_&qH? 0b ,|1?W]S%͟H? 3q_Eπ+̓1 yDx "R) y Q䃖p®^'O[2":穜aTͶKnl$Cy4&kK/Sz;< ߖV i3>#q +`H[}`?khJoPK[J/%gf&certs/ValidonlySomeReasonsTest19EE.crtUT І?;7AUx3hbN2hb:рSͣ;/##++!'s( 0Sh%,Z\ZTXZl(c ˩ M JM,+Vpv41504014415725DoHYX;,1'3E:WWd  - #=CtjM4ٻ7bNW-G'i~bëe{>7XTXq)7¦޿s(-ՐsNWyn9w7r||ީ% \"WP 1pp <9G_\77141:}'"a bl"3,z0=㥤,H/Woc^Z[6I32gaafb` +q%y0cۀѠ HFAI1 DQ) y !cĚ`LS;7%af`*ͬWϛ6yim'{% iRgL.zެyé3kp*t<}ĮSn6}4eM]ţ5;6}Q2ꥩNZ/4s9{oov?[qv--k_qPK[J/06(certs/ValidpathLenConstraintTest13EE.crtUT І?;7AUx3hbnİрSͣ;/##++A!'s( 0Sh%,Z\ZTXZlecV,H,Is+.)J+1S(.M gG9q^CCKCSs#(q^CdA"֚@ KLQ\YCc~ede`ne0hdjldXKR* S{l͉_W x!R~ʉ)_};7gilL$7mhqgTRFvS|_IOeb-Tl5>i2VI3dX͒gNjqqA#wd K8ʟg˗+ $PK[J/J@(certs/ValidpathLenConstraintTest14EE.crtUT І?;7AUx3hbZa$ x8<ھ222rp1 3JH8\‚!% ΩE%iɉ%ņZ 9fałĒ <⒢̼3$rv410504014415725D$o ZݰĜ \]u(041hWFV^NF:>a(6cԝ{3Lm ,:9YP{trOU]cN<XKTK>MXVȷ.*Ven铧Blܼ^GoEh]ܕ}gOtJҢĽ k ~Uf0kkZO/Vz~>8\,H|o d YOlpkH? 0 ,|~jPK[J/R,'certs/ValidpathLenConstraintTest7EE.crtUT І?;7AUx3hb2hb x8<ھ222xrp1 3JH8\‚!% ΩE%iɉ%ņr2 9faтĒ <⒢̼gG9q^CCKCSs#(q^CdAVC KLQPYscde`ne0hdjldp[MPכ_mۣ/k9,%lYxGj]IַE9B$j0לu.+>{QiYz>3#lLydY$ Dy2]ެFϪe-6)cc)d&}w vͼagd@W`03aJh`LF#ZT3A}EQηY{ts:YV͌Kv?~VnȜVaRG;5ضQ;%XuֳeoJS2̋7p_[S}!"s`Bj˜.SW -jPK[J/%>9'certs/ValidpathLenConstraintTest8EE.crtUT І?;7AUx3hbmIJـSͣ;/##++!'s( 0Sh%,Z\ZTXZl(g c-H,Is+.)J+1Ppv4504014415725D$o1*Ĝ \]u(0h=FV^NFso^13kECNO޶bﲭ{<äknOs}inΗ2'+UV:?:<ݑo;jȵ;Dޥ3r79c} bB?4|OU|upe=3#*ydY$ Dy2]ެFϪe-6)cc ,Xccsa|kgdo WBc*P܀р$! Rj *z6f~ܶ5Ij*3VҦ'>Oog^>}콇=2,>8}wMY[sxBև_|'tߜ&G9^ǕDdڅ_3! ޏPK[J/ fv8$certs/ValidPolicyMappingTest11EE.crtUT І?;7AUx3hbjo3#qjy}eddee036dceaf 62qCRKSJ22KR 4ArJ) ťIΎ y9ɕ y %Fr&&FQ⼆\8560ثf+r~U}`ȰcRsٽ]}i߶R% &+g4k^ }UCw^i׈i #3kcqЦڇ~agӶ-PW1R8#^̯7K[mWUbV63#lLydY$ D&^u4Tj<@EE~oib&q8:6I32gaafb` +q%y0=֙6{fȸ8r\`V_ oG~ ya*$MzvX/zIX*?:AKI<`7o#ݐԮOxLX֞s/}>|z7sVV=PK[J/y,$certs/ValidPolicyMappingTest12EE.crtUT І?;7AUx3hb0hb x8<ھ222rp1 3JH8\‚!% ΩE%iɉ%ņ2R 9faC#Ă̼tÒ|cgG9q^CCKCSs#(q^CdAB, KLQLꊬ\Ƞq>Y{ ;: g9{@$'M\vO)¶Mh‰wv> 9OΜ&zgqjٛ3/r?-<t9l/&d/* `;]]y,Xbhfbfd`\mn 2XG\krUל]9cKڢu dA XXDqƭRf0f| i~F,,L, 7DXW9 oq%y0܀٠A16m6`314jVhnYD% ũE y%ɩ iE O+$'gC;E<$C38DU%5փlLqF~iNBRBJfqANb%H{Fj~C32.M+.)JKM)N-1h<*0b4Az5{SyF_0bDWP3"30Xq;*l?3)jVcV^/cJ9~ Opͼ1`qYylRʿf ̧83#lLydY$ Dt/ϋl_M23)cc;բlFlv]SM}4Ӏ$僁8"`gƕ p&fsev5O.9^}dחY8[Zϼ~];kv| ܽ4zyv-uuUǦK ,R^q#Q;%"޺.>`nis Yg[Yh^ZӗPK[J/1$certs/ValidPolicyMappingTest14EE.crtUT І?;7AUx3hb3hb x8<ھ222rp1 3JH8\‚!% ΩE%iɉ%ņ*J 9faļʀJĂ̼tÒ|#gG9q^CCKCSs#(q^CdAB, KLQ@YHA|d/220724v2562lsls.zf<|fu:,\uMKzq„Okcw{.kn2v>9FWGs;̖1LZ,8xYל O21320.64zLVE@ADț//дl-;Y>1?~?~SV[H? 3q_Eπ+̓1h oWj{-WY`c[CVڑwCݴu6;6%M^kmʊ¿զˊˮxqӷ<&hڼfok:u.u]o IYg׻m{Ā<繯PK[J/do.#certs/ValidPolicyMappingTest1EE.crtUT І?;7AUx3hbj4hb|рSͣ;/##++!'s( 0Sh%,Z\ZTXZl(a cM,(KW0,7Rpv4504014415725DoͰĜJ@ #a?wuU- dԱ㓾dz_]Rpy 7ly?RIۄk&T}oY5< CO/a)=T;Ժb Yg*G|5,$.Ӽr"3#lLydY bnݵpW^_<ӻ8@EE}bOGg{r<ɀ$僁8"`gƕ c&f׆IWU=d8Ule*oд;EX&zk䱱)u7{?}ji)WZXi.6Ng_R?R{f3yPK[J/h+$7#certs/ValidPolicyMappingTest3EE.crtUT І?;7AUx3hb6hbрSͣ;/##++!'s( 0Sh%,Z\ZTXZldc 04RM,(KW0,7V(.M"gG9q^CCKCSs#(q^CdA,@ KLQLꊬ\ؠq>Y{ ;{& 8]sh|UGvD5&veyՄڷ' /)GԞRܭu8T|.s޿e;7}p;buO'7?($`,-/ܟ_yqqA<_,b "t6nܺnjz,Ȃ𱈱MSNʑ2ڢcV_fH? 3q_Eπ+̓1hq ɳ_pӾ33Wkr3aKG|_sY&r-*w)]ܿ˛W"jD٦ju/[[տ7K}<Պ3H^zѵr)ShM!+~PK[J/S7#certs/ValidPolicyMappingTest5EE.crtUT І?;7AUx3hb4hbрSͣ;/##++!'s( 0Sh%,Z\ZTXZl` c0TM,(KW0,726Q(.Mrv4504014415725Do2ͰĜJ@M #anK.DK>.ژ4-׉'G-{r2-nJ>t֟BkI1RS~Tq+O٣R31s' r#ԭ /ߗCm -aB&fF@*H5/#^KˤȂ𱈱."123ݪjgd@W`03aJh`LƵZL3alUˢӞm o)fsk5I-؇dQRߥ[N[dUo.=z*.Mi/GgsMIԫQ K]Ī>)jמGmnPK[J/xJ5#certs/ValidPolicyMappingTest6EE.crtUT І?;7AUx3hb4hb x8<ھ222xrp1 3JH8\‚!% ΩE%iɉ%ņ r 9faCĂ̼tÒ|#c$gG9q^CCKCSs#(q^CdA,@, KLQL[ꊬ\̠q>Y{ ;u LͰĜ4]]+[4G #+sc/Ac'Sc#ÍlW/ w8]E`)?e>VQ 9[\%>4S%PfaHȻ7^İ.FkN|y(#6л&-9-_Y &Sy~XҺ1qVk·Tgd%"a ri]ų ?R]wkzg<Y>1Yf&W -ڸ=waH? 3q>66T`tG630춋|]_ryޞ4&?zRnEotݠYK&ie K^/Ol[56ٓxEw>bl6yʥ*PK[J/(S>-certs/Validpre2000UTCnotBeforeDateTest3EE.crtUT І?;7AUx3hbj5hb|ŀSͣ;/##++!'s( 0Sh%,Z\ZTXZl(`cfwOQpv455004044Q⼆&&FQng`14,1'3E(@!4Y!/)5-(UVY,c>cde`ne0hdjldغZK˳{ܸ,hYeȖݯ1z_W'~2 \ʞt{G&b:\_|=я?5FCoF8RoȒM'8 @GYe z˚N:gEuSD7)ccm³\W7 ^]% 僁866T`<0230&2]l{uuo\])8^T4^+eWM{>)j3;ϱy,9[bSďyBv?pSɷlKo2fb6UWB>ir7TPK[J/l|>!{certs/ValidTwoCRLsTest7EE.crtUT І?;7AUx3hb*7hb|рSͣ;/##++!'s( 0Sh%,Z\ZTXZl(b c)Wp)Vpv4504014415725DoĜ5 @: #3֫}sn̯8$eờ9iBeO_.W9ӥ yzU#$k^u@t7O8Nv^*&^#';?mk?)j~P}æ. gd}$"a bp=g5Gb} dA XXDDIrА뺞߀$僁8"`gƕ YxeB~e.HYk} [ N_;y`w/k_/Χ}l߱OM[TǞǩ,>=l)|=t GS_8l_}[KABfcO"=Վ ,ޒ{_9)/]PK[J/]$~ +certs/ValidrequireExplicitPolicyTest1EE.crtUT І?;7AUx3hbj6hb|рSͣ;/##++A!'s( 0Sh%,Z\ZTXZlccV.J-,,Ju(L, R ťIh 'k`h`bhihbjnd%k5H!bKsa9) XWpuE֥2Рq>Y{ ;Np]X);-Fâ)-:)XkogcMGb*r*[;Ln  0;?*cxʟ[qS߸*!KZqs;(jVe&fFA@*H5L^~Pe/ n0z@EE${v!\+L<H? 38fux[J; VTT-zzϑOeؘ<υݯ6:1ĕx&/͸|0{7Ã~5ݸv{Owğ/ Rk΅j3*ff;›5LPK[J/Z +certs/ValidrequireExplicitPolicyTest2EE.crtUT І?;7AUx3hbj2hb|рSͣ;/##++A!'s( 0Sh%,Z\ZTXZlm cV*J-,,Ju(L, R ťIh 'k`h`bhihbjnd%k5H!^Ksa9) XmWpuE֥2Ƞq>Y{ ;O[ؾ^&eH"l'iz$#APH`[9]eu%5c/8,HyƉ"m73j[~oG"}\tݎ^.ƳvxO*RqqA<{,b "v+ oQhI?vd5)cc1"K˥=ҷNI]kgd-~Mߋ8}Yop$5!%s2*3ee"yǟ=<ž,/?~7G?Hjh{U;nn8w!]oi], PK[J/^u4+certs/ValidrequireExplicitPolicyTest4EE.crtUT І?;7AUx3hbmIJрSͣ;/##++A!'s( 0Sh%,Z\ZTXZlm cV*J-,,Ju(L, R ťIh 'k`h`bhihbjnd%k5H!^Ksa9) XmWpuE֥2Ġq>Y{ ;X UfE^Y-bk_N&{ka.sl)]K[.3['.ōZS{?3esJTЕu=~zV󖢥>ՎAǪ/z(tھwfzgd'"a yţM2Elg2)ccqTۑltxiqv03|0X xظ<So@~h׉1V_\|}ϙ{G^ZyonwNvн?~PNEMSF[|;d.-]RY_K4N-~+oɌPK[J/ֱdut4certs/ValidRFC3280MandatoryAttributeTypesTest7EE.crtUT І?;7AUx3hbz`乀рSͣ;/##++Ac!'s( 0Sh%,Z\ZTXZl(l 9Is'FI12C9Aʒddm #99|*sR y @B&0 39;ȉZD"s w3HY&,1'3E!@ĒJǒ̤ҒTʂbWWd@F4G4FV^`u2562̯py ݑŧ%/]i1Cџ)M\QBp|[;SXޑțW"D^Jқ(NeXtzr86|.r+4ӽRw|sO[}eaCVIq<g31320.64zUVE@AdnMIZf|N< 6)ccru1Y-703|0X xظ<SI=1cvo[lyO˙dJu꟝yƊ#HH[Ǵ$?Y.X/WH:K|۷q?_oמ[!iufo>ս ^reާ&VWwPK[J/b3certs/ValidRFC3280OptionalAttributeTypesTest8EE.crtUT І?;7AUx3hbzmрSͣ;/##++A,CnN6P6a`C) KX0$D9$3-39$P@$.㞘YZTTZnk f32q AlGa.̒b},LΎ<\ 0'(a_==9q^CCKCSs#(q^CdA>nw1p1 [%d(9Y(XRRTZRYZlD NFݽjE5'V.,5GӴ\ÿ_G-N/-7M=o hMΌܪv+7xpEd?=9L}Տnߵj'ݞҘ~<`YT221320.64TVE@Ad}3:BKïK%_4)cc^mowNmbgd@W`03aJh`L& e f,Kڣb@K[S][G7ݒ#淭I"=]>ort/9>oxImiC}Ӹ>Ͱ[,3zK_;柇b}Kwl=PK[J/*(^,certs/ValidRFC822nameConstraintsTest21EE.crtUT І?;7AUx3hb:cdрSͣ;/##++!'s( 0Sh%,Z\ZTXZllcKMu+.)J+)Vrs02Rpv44504014415725Do%>Ĝ-薻"kScdh8٧ ̍ L ؞mr~#ڿVrɿ[9w vf4GwZ&mc~nwΧl 6[~eغN:nT>Ϯ5J;v8vb{!Ľ 43zQVE@Aq}kU"yvV :W/r,H^S__Iw"ֿ @YXX> ,|Nz|}вF~;rϒWL\PK[J/2P,certs/ValidRFC822nameConstraintsTest23EE.crtUT І?;7AUx3hb:hĤрSͣ;/##++!'s( 0Sh%,Z\ZTXZllcKMu+.)J+)Vrs02Rpv42504014415725Do%>Ĝ-薻"kScdl8٧ ̍ L ˞ZxzP7C |oSt*يs4|=gȈ=pVxEmKHgpNk 3yQo홓&s8#wn<9ۊid7N3hl 2XYZՆK W%盞4)ccqR?C%F׳̹H? 3q_Eπ+̓1 AEFYH:$)R30*Lg9eY<}vŃ-&E*~lr=V%Їiq S/pIgj?5i _$OI>U=Ê-OVe>Zfd+9_Su* eU';u.p^{ q^PK[J/ Z,certs/ValidRFC822nameConstraintsTest25EE.crtUT І?;7AUx3hb:cdрSͣ;/##++!'s( 0Sh%,Z\ZTXZllcKMu+.)J+)Vrs02Rpv46504014415725Do%>Ĝ-薻"kScdj8٧ ̍ L }{3Z vU5nwԻ-N1;=)"Bz"bSssqKU&Hf9[C#ˏ-:ӶOz%7mVhHYuFpf"˳͗'y\Pq;-"Q՞r[NZ(W%u9O/EPK[J/|B>certs/ValidRolloverfromPrintableStringtoUTF8StringTest10EE.crtUT І?;7AUx3hbd$рSͣ;/##++A!'s( 0Sh#Z\ZTXZlhn` c /K-RH+U(+ILI .JBC,np1p:,1'3Epu2q>r0020724v2562{hܥT|L*䔫7oyʛqح;޾5R~)~U/U~U7]ܵKرy;ľG~'$W.M^j?{;oiYllxWj*h6>ĪcëĽ 2 >Uf0k1DI)-_,1)cc)̯h%:U6"ӏR1I32gaafb` +q%y0z`-mL.^] jbқ&Lի_/s57s&l)`3K4 ھc ykKܽП[{&.s)6]{ł4>y,iPK[J/i:0certs/ValidSelfIssuedinhibitAnyPolicyTest7EE.crtUT І?;7AUx3hbaĸрSͣ;/##++!'s( 0Sh%,Z\ZTXZlh cL,q̫ L4T(.Mrv42504014415725Ddo6ĜԜ4]t\]5+L37hYFV^NF-5bS.ϛy:| cg^˞]:-{֫ 78(GncyÂo%]ɋ[׬agj{s?jű*ki4xnWz_"qqA&8LeY$ DVpdPpvXMGj R""2+:,Y˟=n03|0X xظ<SQo@Ȕ^_%!vle-eVV{X{3- 2]ku< i1l])oS~z=roy埙uAg!}xrz߯9{fh)Rm]?_E[PK[J/:0certs/ValidSelfIssuedinhibitAnyPolicyTest9EE.crtUT І?;7AUx3hbaĸŀSͣ;/##++!'s( 0Sh%,Z\ZTXZlh cL,q̫ L4T(.Mrv42504014415725Ddo6ĜԜ4]t\]5+L4hYFV^NFURR#V:-rq}7jjjӢs˒SCwHHe槩 eݒSnx.,9lAy'&Xj*~F3.H0dbfd`\m SYe sv>*[qNtIӦK-7)cct>ǚ{~W_1I32gaafb` +q%y0ހ-♁|{Ȝ#A7c tHxnOQ?W 5z~ ڏ՞,bpz2˞ۗNJ23!){rJȽg*y&/p?:1Ugb陎f:5Uz43|i4gUn猐 PK[J/ؚ2F4certs/ValidSelfIssuedinhibitPolicyMappingTest7EE.crtUT І?;7AUx3hbZdĽрSͣ;/##++A!'s( 0Sh%,Z\ZTXZln cL, LM,(K7T0T(.Mrv4504014415725DoNĜԜ4]lPpuE6@dA|do320724v2562lmz0^#of_|SG/;h^+cˋMG^ٙ"З{~9~.ކ(|YkfM48'M Uf0kٶAy>/٘G@EEĵbw{*~GkސRI4I32gaafb` +q%y0Z`oԂ-CON<|%|Ni;&&nSNS 2K>{.3yn;;AΫmvUVh)J-HYz|EL\gͽ?,擶&PK[J/#%W:2certs/ValidSelfIssuedpathLenConstraintTest15EE.crtUT І?;7AUx3hbnİՀSͣ;/##++!'s( 0Sh%,Z\ZTXZl(g c-H,Is+.)J+1Ppv4504014415725Do*˰ĜԜ4] \]u+345hWFV^NFٯ.4>1lo1k2X s~㯽S"5Wێe36O3|rUztKWD5?&:3T&gd2q|ݚrwmxebfd`\mi 2XZNQy_z}x4xIY>1=?t02.SԱ| i~F,,L, A|>66T`0;30).:DڞEu/%h)5|p=ԉ"OV%sg{u֛KF(y+]Xmߚk&Lh=4Y~c˪z"3yرH\ռPK[J/];2certs/ValidSelfIssuedpathLenConstraintTest17EE.crtUT І?;7AUx3hbeļ x8<ھ222rp1 3JH8\‚!% ΩE%iɉ%ņ 9faĒ <⒢̼C$gG9q^CCKCSs#(q^CdA.98@l KLQNI,..MMQ_Y8Csede`ne0hdjld8{2KOowvx틹?!WVG*s#,).@MIsn&Գ3y,xxi/=8{&tYgW1:د '\w̜P\-3#lLp*H52Kʦzha R""bɏ^7Ϙ}-ۀ$僁8"`gƕ |FgM;CL}CS eWN :>\Xs{y -j}U]601J_ܲ)3{]+_{te=8?]_gERl"%Wɪh5nPK[J/kq;$5certs/ValidSelfIssuedrequireExplicitPolicyTest6EE.crtUT І?;7AUx3hbj5hb| x8<ھ222rp1 3JH8\‚!% ΩE%iɉ%ņJ 9faɢ̢T׊̒| Uih 'k`h`bhihbjnd%k5( :Wgu6a9) 9iť) XlH3^fde`ne0hdjldX2p۔'OIӗ_{R @^yq{gyώ[~ORyhǻYޥvvC[5yS\7>tO}N$j(_ٿ҂H>k!إ }[umnrOqqA<Ы,b "zj{Tm;23@EEqJe֮*g3|݀$Z,3*nlӥ )b+ce{ 2^OV޾׮?uҝ F'̯lM{[Iꌝ܅,١>^?d3_9=ᄔw9'd >>fU=lgZqH]"6ʏ}Sboy7O2i+;]D2x"i5ɖE5n"^ϊCW98 @WYe 1{ p?\vq,HȺGY`ލ b| i~F,,L, A|>66T`j0@O @S| ?=ރV^!P0bk8x_C:Rt9jK^{+L/tq>XaFKC{΀ͥV勭;b,y/;)zÉֲ“-lPK[J/]3N<certs/ValidUnknownNotCriticalCertificateExtensionTest1EE.crtUT І?;7AUx3hbZjķ1΀Sͣ;/##++!'s( 0Sh%,Z\ZTXZl(j c )*J:%gȉZD"s b]XbNfBh^v^~y_>PaQf PY׊Լ<WWPCdde`ne0hdjldXĬ3xR͗Z»7o'DW*p<7:I 85.̺ƴ]̗F_q *2]X[/酞v\ߴAek‡ vC)K]< `r 7O|︎U&fFŵ@*H5ι8z< 6fi@EE[`H!eK̏^fɯU| i~F,,L, A|>66T`0qyLElƭ 8jz-\~귗GE>vogķ (^Y٪NoغgVS;cĥ <_h,}ޏbS2|/Lh)=qq*@*H5-hO⺇7S*^3)cc#!vF)r @YXX> ,|1u3^hIMorcoDnT\>4?#f& WBc*0  A,m3())pIqjQYj^f^(_/=L?3/%B/$7-015i#7"ܿ79j֮/0ޖ_EW~Gz0o3Sx~F?7ig8yUoKw by(x}[^zD,*@ucLO,PK[J//l!vcerts/WrongCRLCACert.crtUT І?;7AUx3hb*2hbˀSͣ;/##++!'s( 0Sh%,Z\ZTXZl(j c )*J:%gȉZD"sɳ!(?/]9GѠq>Y{ ;^͔L'-*_)ky~N\I06崾??3lH|cf\RRcɠƸFJ3_ &ԹOE7C#g܋g6%RsO'w;Ơ@tYe 9WtRǻլ==_Ȃ𱈱\}|h^TY€$Wl WBc*P܀р$! Rj Т*%ټHxv{Mq`vjAS_gt1Aӊl #k/z;[i |.37#K5Uؔcc)"7.Ca7g]+IDy2X+NW`j֞ A X xظ<S؀р$(f @ -3ʺH\gם7_e]/7bfM_Zp!E|/9S/X*ݤ9a9wa3a=㋛FoØ'\bz̥=o5rf&3-12:^EE$V]Wԧc'7afiy2XHUq9_Iz%(q%y0ʀр$(f @ )*  tDVDoSxc6w"zE4DrUg-}ȸӪmJ7PKaJ/0;$certs/InvalidDSASignatureTest6EE.crtUT ن?;7AUx3hb67hbـ] !7&l(e p (8de&'䘅\ y L - ML͍ y qěml`1[3,1'3EdGpfz^bIiQ+zfMۀXF Ga*i-NNؐf^+׍tU4XzG~y>[-zsD~]X/liD洹~5(}%9iɳw~]fꏓg"6n~Pw=;xN6y{sc hG;NkVhpmm/\rj3òw^r5_~yz;43?;bDv/F_/b]=)@WkQ )FB[_Iԭ˽k995S_ld{aqA,0eXXDeZ-`uVZ~-u >ȃY$ DJDKYWJ/@@Eπ+̓1  @YX vf]`[ve{ 560$/S~*>/z'PKaJ/6-certs/ValidDSAParameterInheritanceTest5EE.crtUT ن?;7AUx3hb22hbр] !7&l(e p (8de&'(䘅]sSKR<2R2KRS y L - ML͍ y [hk` $,1'3EZyɩ :@F4NFx\ٍfm1u疜nxݹ.mcfiIY.->}|'MfI^ZWrgXĸkTK3L%1=XðE{'i{4a9,GD^/64zKEE((A.1ͷSkȃY$ DbUuJ}:vrӡ]6y[m6)P`03aJh`LFH? 3f6`0eX=[g}}NY+I\;.SWkPKaJ/AG:#certs/ValidDSASignaturesTest4EE.crtUT ن?;7AUx3hb63hbр] !7&l(e p (8de&'䘅\ y L - ML͍ y ěmd`1[3,1'3EdCpfz^bIiQj+r~&m@ ##{Cuۚwӄ2*?5${Vt [K2<%+Lpsas5翐95)F]+سR_Ӱ4s_/wжKZd3g/[w0(C?}ڝ ɹkؐvEKaF/|UEO4oأxw3OskQϜR(ioq~#gf埩)<ӺVm:N]"[ߧq2)V܎'./:w `5.VeB|_K.Y?֑EMUa }{S $[fOX;{ׄ%צns1$k:*bu7RP!)wٙf,WתH;ccl|=p  75I+H5^U!_8HWBc*0y0$03@J Y~+*NY(RI|n7 -9w7WPK aJ/crls/UT ن?;7AUxPK[J/I(&'=crls/anyPolicyCACRL.crlUT І?;7AUx3hb4h\hƩۀ9M)4P@ I-.QpN-*LLN,I-651 $Ud&W*8;ZD"s*H5mst6߶]}dR Œ>Fú?O^SEɆE/hY\ 9i&)F.v=gM*.q̔3~Ͽ 1̭v#ȏ /[no6cvg6z-f{*)C[PK[J/~3Jcrls/BadCRLIssuerNameCACRL.crlUT І?;7AUx3hbt3hhƩאۀ9M)4P@ I-.QpN-*LLN,I-6T2P1 Kz%&(x)%榊ZD"s͐Uf0k9ardK. ݀ @ӱ̍ ZS홻pnRX=co_&'ݷgҘ}]RBDrs=+tOr~ ο3ENNZVT8|_PK[J/o-Ecrls/BadCRLSignatureCACRL.crlUT І?;7AUx3hbt4h\hƩÐۀ9M)4P@ I-.QpN-*LLN,I-651 8%(8(g%*8;ZD"s*H5(фЀr @ DX1ȐQ~z!},N5n饱/r*򝠯vzS4v|xܥ5+uPK[J/I.Fcrls/BadnotBeforeDateCACRL.crlUT І?;7AUx3hbt2h\hƩӐۀ9M)4P@ I-.QpN-*LLN,I-631 :%(8*ey L - ML͍ y t eY$ D䪌(wIPz \ ",̘enldydgT.FLWU s?[.n1xZ{g>9!q2}%w{ͼoUY\|SN-]dƴҏ/;sKy=VZ7+r.\Q||PK[J/f'>crls/BadSignedCACRL.crlUT І?;7AUx3hb2h\hƩѐۀ9M)4P@ I-.QpN-*LLN,I-631 :%(g祦(8;ZD"s*H58IOV?>jל 7 @ DX1 8Vr)IS~M_8pgʧ[Vs~?ifZ[ (oߧJgZ[ܮv;qao',sV}wnUC_su&1y%jn/X6PK[J/P>V-crls/basicConstraintsCriticalcAFalseCACRL.crlUT І?;7AUx3hb 2hhƩ Ґۀ9M)4P@ I-.QpN-*LLN,I-631 &%g&;%f+8eU($;*%*8;ZD"s͓Uf0k9_;a֔:.0;gR ŒpF=B--}t橧ZN2MI[rrcm}Tn%чKsJy wMٳ^,SJ);CWq~T`gtgg鵖M\00m-IM;njyEl s"=~jM\5/YK#6HDϤcǧl V(b.PK[J//BZ0crls/basicConstraintsNotCriticalcAFalseCACRL.crlUT І?;7AUx3hb 3hz~olY;3E?u7[ /,j/?qWJZu2?<:Uvsb}FjfoE%)2 ˎ׶pgm^1~V;-PK[J/op/crls/BasicSelfIssuedCRLSigningKeyCRLCertCRL.crlUT І?;7AUx3hbmhƩ ۀ9M)4P@ I-.QpN-*LLN,I-651 8%g&+z(8(ge+xV*8;ZD"s4n7hb 4PVE@A6\ W>TnVA.f[@F,U ,)2( ۠D%@!-H sc#|YFoU?'{Sj˞f=_f}Tg>Vkݕ5W6^hq%?g_Sg{cݱEs >eψ]#{DpPK[J/]b~Hq#crls/BasicSelfIssuedOldKeyCACRL.crlUT І?;7AUx3hb5hhƩ ۀ9M)4P@ I-.QpN-*LLN,I-6T5P1 8%g&+z((xV*8;ZD"s Ypeabd\ok +H5HQl/fgΛK\haasc#Cҽ=fw7{bdx/Ojϕƺ?i!%F=ͳsL3ygooƒ,;[Ϊ^Az*AKژ6]eqAev_ X<#vk PK[J/?h/crls/BasicSelfIssuedOldKeySelfIssuedCertCRL.crlUT І?;7AUx3hbP1S,g7^w$ÿ~*<m8"|_ИkOI^ϓ61|[`S}*PK[J/| <Lcrls/deltaCRLCA3deltaCRL.crlUT І?;7AUx3hb0hhƩۀ9M)4P@ I-.QpN-*LLN,I-651 $:(8;A8A;y6Ye Gl9\oyG\ ",L@ҌA\&42762d^l{Ev'^LwBtq=wɮzBXV޾JĨ>+/.5BdE'm_ԃ{lW_)sʾPK[J/FK=\%crls/deltaCRLIndicatorNoBaseCACRL.crlUT І?;7AUx3hb0hd(jЍEd3}Iߪ{\&aTPK[J/@q crls/distributionPoint1CACRL.crlUT І?;7AUx3hbhhƩӐۀ9M)4P@ I-.QpN-*LLN,I-63q de&dg*8;ZD"s p͔eabd\иàq.82NgMN?fg@lF,:Z 4,,cթh3+]ZkwuI_N^6i1e:O^ٖNq;kLQ$6xZ5k--Iw߸(UV&vY.;9q)JO-PK[J/:~crls/GoodCACRL.crlUT І?;7AUx3hb2h|hƩڐۀ9M)4P@ I-.QpN-*LLN,I-601 (8;ZD"s \ pMea 2XveMسZ庩YSC40cza7܅s/-oۄ" ?J_(o)>8mij?wvM>rZ1WPK[J/%<S,crls/GoodsubCAPanyPolicyMapping1to2CACRL.crlUT І?;7AUx3hb7hhƩ ̐ۀ9M)4P@ I-.QpN-*LLN,I-661 +(&9;*$Ud&W*&d+ZD"s Uf0kx%8&~\TvSګi,.fLW3762LHϢK|:eQݛ7]}9f27[ӧ/ouٟo) ٥f-wY>>_Rv i|n}lxk!PK[J/ OLucrls/indirectCRLCA1CRL.crlUT І?;7AUx3hb,4hhƩِۀ9M)4P@ I-.QpN-*LLN,I-601 gd&8(8;ZD"s pMeabd\``g +i9(cɒ1ړbMN ˾5gFNM9=UoˣlWn~y aLIڻleMf+y9[E{˦wǗw.sR+$:wz^:/aPK[J/SgPcrls/indirectCRLCA3CRL.crlUT І?;7AUx3hb\n(hƩِۀ9M)4P@ I-.QpN-*LLN,I-60q gd&8(8;ZD"s40hj +4Adek#?tpw5 @ DXALe X$ .550 E A4uwǧ=e}eĮWfk^iWXeb7nz:)x0X)$"u0YeY~R}IFoUMQm5Ӂ/ YcJW~=3mPK[J/6RNh#crls/indirectCRLCA3cRLIssuerCRL.crlUT І?;7AUx3hbkhƩאۀ9M)4P@ I-.QpN-*LLN,I-6T2Pq Kfd&8(8;+$xZD"s41hƙO[e9 -7uO3Yx0[ o[q'c[/ Ew>amV&[~PK[J/;crls/indirectCRLCA5CRL.crlUT І?;7AUx3hb1hbyhƩِۀ9M)4P@ I-.QpN-*LLN,I-60q gd&8(8;ZD"s N(FSfc4OV R&F&t(*AlYF,K\p:3@c0 NgAc#tvNP$0.Z; 3%ƍa 412)jVCûͽms#]s!DXA1ē1ȏ~K rCMuH`+d@RiE hOw͗dQFEpmbɴ?Z 龰䷴Mw\fYjwQ͉ݪ+7>rCܒ"0`y.{[·Զt[7o'+>dyǥWX5uq:>y+ WW :,Ϋ6$_PK[J/ﰳ.Ecrls/inhibitAnyPolicy0CACRL.crlUT І?;7AUx3hbt4h\hƩÐۀ9M)4P@ I-.QpN-*LLN,I-651 ded&e8Ud&W(8;ZD"s*H5uߘ7_1re;oR ŒNFՋ+uT[ 3άVxd,Ì# ̫c<s~08TC~]okۢܧwqF9/yVMoQ%~츼Y;'~]5PK[J/>G-0Ecrls/inhibitAnyPolicy1CACRL.crlUT І?;7AUx3hbt4h\hƩÐۀ9M)4P@ I-.QpN-*LLN,I-651 ded&e8Ud&W*8;ZD"s*H5:8vw?₯H 3;)yp^inKguV|GeYbeSډڭ}Cw]1FX2cB=3YΓ Y*1yӴӦ~ 7ͷý7 N:6XYlPK[J/"/I#crls/inhibitAnyPolicy1subCA1CRL.crlUT І?;7AUx3hbt5h\hƩǐۀ9M)4P@ I-.QpN-*LLN,I-6T41 Kded&e8Ud&W*&9;ZD"s肍Uf0kT2Aɻf5_>hQ.fL2762Z;ջzӑ5-5xJu:e"aR'MT_twJz2OZrߞM.yvכ5T&]!ݛq %BQӛ-{m5.,w񣹢kPK[J/D.j2I#crls/inhibitAnyPolicy1subCA2CRL.crlUT І?;7AUx3hbt5h\hƩǐۀ9M)4P@ I-.QpN-*LLN,I-6T41 Kded&e8Ud&W*&9;ZD"s肍Uf0kY}‘AUgao79tSH 3[Z_3g;S{Lʓ_ݸ; xhq>=sFݽD9rN\|"P3?9w&`NRf_yJnתq f]2ϻGK_TuPK[J/"5L&crls/inhibitAnyPolicy1subCAIAP5CRL.crlUT І?;7AUx3hb0hhƩߐۀ9M)4P@ I-.QpN-*LLN,I-6T1P1 Kged&e8Ud&W*&9;z:ZD"sMUf0kaLPmu| O B\ ",̘enld8Rtct}5RJuV[@F;s]v5Qw[; 1u6 cbTduY﷛qk3Wt-񹎧#5cQ OӝAΦGO>PK[J/_J5L&crls/inhibitAnyPolicy1subsubCA2CRL.crlUT І?;7AUx3hb0hhƩߐۀ9M)4P@ I-.QpN-*LLN,I-6T1P1 Kged&e8Ud&W*&8A8!2w<Ye W *{~Τ?Z'zvH 3sd;lqԔ'RHS=OD>_cd {SCY kOў'*s8\~꼣h+ߔV?0[cPԚ;GO=ܴ;{'ݗL=H|ЙKo3PK[J/6.Ecrls/inhibitAnyPolicy5CACRL.crlUT І?;7AUx3hbt4h\hƩÐۀ9M)4P@ I-.QpN-*LLN,I-651 ded&e8Ud&W*8;ZD"s*H5c)\63iYOy, Z7)aat'sc#qN͊Wt5}zFK-_):(`uidsӘdY8|XrbRO?N_aH.|")psGny٬-xmGE[PK[J/L?%1H"crls/inhibitAnyPolicy5subCACRL.crlUT І?;7AUx3hbt1h\hƩېۀ9M)4P@ I-.QpN-*LLN,I-6T01 ged&e8Ud&W*&9;ZD"sMUf0k*OPf_txy2tvN7)aat*sc#C*&9#tofbh] {‰Eg8zLԕ5S|7|]J?oҗ8_k'ۯݷo^܍0PK[J/M+X0I#crls/inhibitPolicyMapping0CACRL.crlUT І?;7AUx3hbt5h\hƩǐۀ9M)4P@ I-.QpN-*LLN,I-6T41 Kded&ed&W&d(8;ZD"s肍Uf0kyy炾w/]72)aat+sc#ÙŒ^W }K{DK-E"%P {})%-O(f?{u4QvGW%=RO_L\y< Ǭ+7M|+~;lx'tSs{츗3eb~bPK[J/<D4L&crls/inhibitPolicyMapping0subCACRL.crlUT І?;7AUx3hb0hhƩߐۀ9M)4P@ I-.QpN-*LLN,I-6T1P1 Kged&ed&W&d(&9;ZD"sMUf0k1ظκx,=UXH 3s]eAq缋1W~^:ee[g{_gvcqVTZl'=RaR-4/ge>c)W\:.+1om4*)bZᴍEX+1#ꉿVlyoӷnQoPK[J/u5M&crls/inhibitPolicyMapping1P12CACRL.crlUT І?;7AUx3hb4hhƩ ۀ9M)4P@ I-.QpN-*LLN,I-6T5P1 ded&ed&W&d*)8;ZD"sUf0k/3h_=ADڜUA-̀ @ӽ̍ XR|`͞nֶk- kZ(qmu6krycgl%6N /H17u$u[U:uhIEߙ$&^&]gWRLl9*ޘn*VuPK[J/769P)crls/inhibitPolicyMapping1P12subCACRL.crlUT І?;7AUx3hb1hhƩ ؐۀ9M)4P@ I-.QpN-*LLN,I-60P1 ged&ed&W&d*)&9;ZD"sMUf0k2`*́wݍwm:dR ŒdFb+*/*s,V7Wj1.9)~e;Wir̤u?*n%=f?~GbV*,9kUowUN+oҵЖu:Y& R 91?PK[J/^h=T-crls/inhibitPolicyMapping1P12subCAIPM5CRL.crlUT І?;7AUx3hb 0hhƩ ܐۀ9M)4P@ I-.QpN-*LLN,I-611 +ged&ed&W&d*)&9;zZD"sMUf0kyv/li򛴋s֔S @ DX1 2<ԅx &+ Q^Ehmݸ-kݧ9Ydμ/iȉFle]j/X*ՏwWT*?zQa'2qWyfI Z,U5PK[J/&gp^?W0crls/inhibitPolicyMapping1P12subsubCAIPM5CRL.crlUT І?;7AUx3hb 6hhƩ ʐۀ9M)4P@ I-.QpN-*LLN,I-671 eed&ed&W&d*)&g8A8!2w8y,b "*CvOr&n\ fR ŒrF; 71םC/l  Κ'4yuaՓnwL7x-Pg^D5^{J\LfayǠxmoU6Tx6{]n: qs/7WllPK[J/E$K5L%crls/inhibitPolicyMapping1P1CACRL.crlUT І?;7AUx3hb0hhƩߐۀ9M)4P@ I-.QpN-*LLN,I-6T1P1 Kged&ed&W&d**8;ZD"sMUf0kY5d.61_bR Œ\F^FޙۣEVͭxFdqko,{觇d[VmYJNxvƑɟ-T}}ryM2 y_ y^6[$lkWk^ٷAGQ$ S/PK[J/, @9O(crls/inhibitPolicyMapping1P1subCACRL.crlUT І?;7AUx3hb6hhƩ Ȑۀ9M)4P@ I-.QpN-*LLN,I-6T7P1 eed&ed&W&d**&9;ZD"s Uf0kٶAy>/٘GԀ @̍ d\&6?nJ?m„v r5пs\4l~嶛,KaKZ}ʹO* ;Y|[֌m֫7 Wtm ظ~}km7|\ލs\OZ[PK[J/w4L&crls/inhibitPolicyMapping5subCACRL.crlUT І?;7AUx3hb0hhƩߐۀ9M)4P@ I-.QpN-*LLN,I-6T1P1 Kged&ed&W&d楛*&9;ZD"sMUf0ky?$vbLnZ%gsp0c:r鯞?L5Gg߷^*ZTsZ-YA87kJɿb:3X)F3R {a6<@WW.|r4iwV*eES'2QP[y} gx_fAɤǯf|PK[J/C588O)crls/inhibitPolicyMapping5subsubCACRL.crlUT І?;7AUx3hb6hhƩ Ȑۀ9M)4P@ I-.QpN-*LLN,I-6T7P1 eed&ed&W&d楛*&8A8!2w< Ye YsYo z%Hl).fL3762Xrʪ`zۆ}VV}5)Z!ԍ (͟b奍93(~ʮq+ԞD<[%㎀cG/;pQ֥OaK?޻L'?j?;U9 PK[J/ 7R,crls/inhibitPolicyMapping5subsubsubCACRL.crlUT І?;7AUx3hb3hhƩ Ԑۀ9M)4P@ I-.QpN-*LLN,I-621 +fed&ed&W&d楛*&A8A8!2w<,Ye mk|o>l#9p0c:3o[vՏʍf%/2"?,0::? SԞIi^&}jj3ҢL?^ᖟqz4&կT)?9VByOܖe:3hPK[J/xPl9S*crls/keyUsageCriticalcRLSignFalseCACRL.crlUT І?;7AUx3hb7hhƩ ̐ۀ9M)4P@ I-.QpN-*LLN,I-661 +eV'*8ees|3sŽ&&FQ⼆@dY$ D4<]@mzKp0c~K̽!zw$ظYmo}v#wz+K&(=c VuzaƟn3MS]t+w=y *t{~8F6fImPK[J/AODu:W.crls/keyUsageCriticalkeyCertSignFalseCACRL.crlUT І?;7AUx3hb 6hhƩ ʐۀ9M)4P@ I-.QpN-*LLN,I-671 eV'*8ees" y n9@)Gq^CCKCSs#(q^Cdq@eY$ D01Ťm'ٶ\.227)aat9sc#y)_V^ǧ:w޲48SԇN A]Zt8q1m52m;vZ>zȇ %w.(h Y{}C$ݪKE9}kG|.MzPK[J/.I!crls/keyUsageNotCriticalCACRL.crlUT І?;7AUx3hbt5h\hƩǐۀ9M)4P@ I-.QpN-*LLN,I-6T41 KdV'*eU(8;ZD"s肍Uf0k9p_G{|go;t .fL2762X /R.7.&J_L/׫mUV> {t d=qx[릱pեډKz_L=uϻ]}REl> vf>\LH#]y]cj=<Ѳh\K6=rPK[J/X $=W-crls/keyUsageNotCriticalcRLSignFalseCACRL.crlUT І?;7AUx3hb 6hhƩ ʐۀ9M)4P@ I-.QpN-*LLN,I-671 eV'*eU($g)%*8;ZD"s3("a 2[lI%a"65WzH 3˙8/w~%=mOrGklr$$Z}g`ɩE:u?)3c=G~IKrJWPW->|{^^S_,ȺG=kWVQ7O|~y% bZ)]\PK[J/թ@[1crls/keyUsageNotCriticalkeyCertSignFalseCACRL.crlUT І?;7AUx3hb 7h+xKجtGid]%{PK[J/iaU}crls/LongSerialNumberCACRL.crlUT І?;7AUx3hb4h|hƩӐۀ9M)4P@ I-.QpN-*LLN,I-631 +e&(&)8;ZD"s L DYX98yxpeabd\ok +H5ܷN[o~po>~D 3^<|kbb{%{Ԭ8e&d-@WmE&J>gh.YNYAS*o>_k-SSyk8Qz̙n/G?^|PK[J/j'@crls/Mapping1to2CACRL.crlUT І?;7AUx3hb1h\hƩِۀ9M)4P@ I-.QpN-*LLN,I-601 &d+)8;ZD"su*h1ZwyYV]VkR ŒDF%u|g|-^ӊ yӋ)ߺ׶^1}}U*+s7FUo\ؤlz [. ̹eb&r.y۳ZMY&qv?yU?KW-Q2>e*>PK[J/TF74J"crls/MappingFromanyPolicyCACRL.crlUT І?;7AUx3hbt3hhƩאۀ9M)4P@ I-.QpN-*LLN,I-6T2P1 K&d+*$Ud&W*8;ZD"s͐Uf0k~p 6(3.YaR ŒXF 2N.÷SM2\Sn~5p`ʩUG  ]e~.7…Srn?h:Wwamߴ|naJSoJ;>SmY{EWPK[J/ 0H crls/MappingToanyPolicyCACRL.crlUT І?;7AUx3hbt1h\hƩېۀ9M)4P@ I-.QpN-*LLN,I-6T01 &d++$Ud&W*8;ZD"sMUf0kpJgyrj?#\d @ DX10`oTu=F^ն_0gngˌBɜ؟:9aY//V{]SBy8%r0S=WXV7 dQ7OzZJu2*oPK[J/t ي4L%crls/MissingbasicConstraintsCACRL.crlUT І?;7AUx3hb0hhƩߐۀ9M)4P@ I-.QpN-*LLN,I-6T1P1 Kfg+$%g&;%f+8;ZD"sMUf0kq[k~i%d5oc ghR Œ\F)v0Uf-^㊙g0j󰚷X= ^9_ٷ5>vH ⶂg6~r~.QQ_3LKߪ닎rm[Zf`/80[+5Y>,1' a?Wo`f5PK[J/LfJg$crls/nameConstraintsDN1subCA1CRL.crlUT І?;7AUx3hbL6hanldX؝[*gυ2׹ ?Rף>kPghFCJW\xSy22aS=״ʞ蒊nKʽ&@8pq7WNs JT;ec^;}QĞdq˞e> %Lj[W( PK[J/mE1G crls/nameConstraintsDN3CACRL.crlUT І?;7AUx3hbt6h\hƩːۀ9M)4P@ I-.QpN-*LLN,I-671 %:%f++8;ZD"s Uf0k~#"l>s}֛vʀ @ӥ̍ +~5"-Jwӵvv\rl0nQk}]/;c9i.{ഽۿW]/~챖ۃkٗGcųi١[˿eߔg} ~_gxu3Ŋ. t]}?3&uÑطQ{-hչ3g𿹕pNuqN PK[J/o 1G crls/nameConstraintsDN4CACRL.crlUT І?;7AUx3hbt6h\hƩːۀ9M)4P@ I-.QpN-*LLN,I-671 %:%f+(8;ZD"s Uf0k1|lzs*SѧXp0c6\(Gk4i欕X!á,_K'9~fci)~ٸ;Hϛ? 'ښzv}SVfIv߮.F=57vEzDʤzYT_#0~⷇ kxFnU΋Gtך鷌Y?Xmnuڴ3O]<\oIVɹPK[J/Qw2H!crls/nameConstraintsDNS1CACRL.crlUT І?;7AUx3hbt1h\hƩېۀ9M)4P@ I-.QpN-*LLN,I-6T01 %:%f+*8;ZD"sMUf0k)}.cGyWŃWp0c:aBb)}~cN_K^:8k+eQU^!nX0j.#yQU ^M aPnd}trO{Yql߇3{MPK[J/ 2H!crls/nameConstraintsURI1CACRL.crlUT І?;7AUx3hbt1h\hƩېۀ9M)4P@ I-.QpN-*LLN,I-6T01 %:%f+y*8;ZD"sMUf0kY#+[;ўuoDUsfR ŒTFޤ}>ͪ}0횷reכ> iۘ=rɬ(ԕFU}˴nTXƿ'|4 beR ŒBF%NΛxwW﯊;T {Y{ǽZV|1RKI|GKOEOj/XΨ4 v ;{oJS U:ǦIݼqaҖbfyio.PK[J/ܠ2Fcrls/OldCRLnextUpdateCACRL.crlUT І?;7AUx3hbt2h\hƩӐۀ9M)4P@ I-.QpN-*LLN,I-631 (8(Vey L - ML͍ \#!4Zok /"a r  .r΁j ;ϰp0c:Ζi гϛZuJ[Y =Uq7OZqx{ jzҶBas&y+oWHkw'OE͹(d3}~:s.kݦG_7*5]%mʛ_PK[J/rE_(crls/onlyContainsAttributeCertsCACRL.crlUT І?;7AUx3hb6hX!crls/onlyContainsCACertsCACRL.crlUT І?;7AUx3hb 1hhƩːۀ9M)4P@ I-.QpN-*LLN,I-671 T:$f;;+8;ZD"s8 Uf0k-eסmOy]€ @R~[? s43762j^&Zđ[clقwexb.GlCš:`_w SDqFjnXw]͖~_({NGȎr&nMTt3PK[J/+y?Z#crls/onlyContainsUserCertsCACRL.crlUT І?;7AUx3hb 3hk^yh  dܱ̃haayEĖadfĚ9F?rR"fE5wzYti=rsN)M[9|%;uz`99˸a_|4O}uiGsW >uǥ=S_\֖XrRU>kOhNǎ5/PK[J/i([R{*crls/onlySomeReasonsCA1otherreasonsCRL.crlUT І?;7AUx3hb,7h|hƩݐۀ9M)4P@ I-.QpN-*LLN,I-611 T&+8;ZD"s pMeabd[d` +H5Ly#oMy+p)w絟W*S?R['?M"J[5\|PK[J/s@Vcrls/onlySomeReasonsCA2CRL1.crlUT І?;7AUx3hb 2hhƩݐۀ9M)4P@ I-.QpN-*LLN,I-611 T&+8;ZD"s8u*H5ZF M'˹:J\5)aa9SĖadf,pFSg,koS<:1/=54U 8+2)W9 8陵a{v|%oFvv1y]z=6o;Oq[.<)w'0 _p OPK[J/^v=Vcrls/onlySomeReasonsCA2CRL2.crlUT І?;7AUx3hb 2hhƩݐۀ9M)4P@ I-.QpN-*LLN,I-611 T&+8;ZD"s8u*H5ZF M'˹:J\5)aa9SĖadfȆpF +_׫~.q{sٳ1g|ŧ`)w^X'i{N` 9R]3VJzex؋ݺs]3 &v[`C$Ym)788-PK[J/X(crls/onlySomeReasonsCA3compromiseCRL.crlUT І?;7AUx3hbd(hƩݐۀ9M)4P@ I-.QpN-*LLN,I-61q T&+8;ZD"s47hc /"a Y?w'~ @\[?KAK BZCU,A>L h@^qUV~ ,YNﯳ["f]udFG={]iXtJSe W.;5szpdwe5-o~XYޗ M2ヒ#ǧOVPK[J/ZZ*crls/onlySomeReasonsCA3otherreasonsCRL.crlUT І?;7AUx3hbl(hƩݐۀ9M)4P@ I-.QpN-*LLN,I-61q T&+8;ZD"s4.0hk /"a Y?w'~ @<[?KA҂K BZCU,A>FZڤL}W~`z3ϼﭱuw½u93J8ٮe֦jpd VۓRk;p͞vAחE M,>LR喘˛vC<;r3/nܿʽlPK[J/nfc[m(crls/onlySomeReasonsCA4compromiseCRL.crlUT І?;7AUx3hbnhƩݐۀ9M)4P@ I-.QpN-*LLN,I-61q T&+8;ZD"s pMeabd\иqL hs@0嗊d [2k}ҒSLr{gK H2Qڦo/U2~Dpꦆ(Ys&Mc-iTtx=GL9=Ը*,;55KkPK[J/sn*crls/onlySomeReasonsCA4otherreasonsCRL.crlUT І?;7AUx3hbahƩݐۀ9M)4P@ I-.QpN-*LLN,I-61q T&+8;ZD"s pMeabd^иРqFBVVz[<~UMB2NBSWlW9x5&33jX#ğk}+pS۶|;:wYȺwZz _N{| !:s㧨sXPK[J/8 V-Dcrls/P12Mapping1to3CACRL.crlUT І?;7AUx3hbt0h\hƩݐۀ9M)4P@ I-.QpN-*LLN,I-611 )&d++8;ZD"su*H5}%6(Wuٕ3qd-Zɀ @ә̍ SLvnY{=95?=`)7+昫g|-\~N[W,sV SG nQ?v*8f(~k]'8=.NWnYPK[J/?~/Gcrls/P12Mapping1to3subCACRL.crlUT І?;7AUx3hbt6h\hƩːۀ9M)4P@ I-.QpN-*LLN,I-671 )&d++&9;ZD"s Uf0k=DpQ/,(hR ŒRFJժEv/1ޜ\p]X <a@~@&O vGtaAeK Bׇ*sPuW_4t/=d)#PK[J/`X2J"crls/P12Mapping1to3subsubCACRL.crlUT І?;7AUx3hbt3hhƩאۀ9M)4P@ I-.QpN-*LLN,I-6T2P1 K)&d++&8A8!2w< Ye o:kn]7~K`]=~ @ DX1ȐYJ̴x`KgqU_NX/GmJq+kڳ#Ln(!JomO߻^韠U}?8q3O ,̐{?^~ /풪`mɽYPK[J/]`6L$crls/P1anyPolicyMapping1to2CACRL.crlUT І?;7AUx3hb0hhƩߐۀ9M)4P@ I-.QpN-*LLN,I-6T1P1 K&Ud&W*&d+)8;ZD"sMUf0k5d?/}ዾg 4-[΀ @ӹ̍ aA-1~-rt{w6ve6lS?G9*ژQc9'}f\oaCSץZˮ3ʲӓOZn|vVu|gVZ0cW+˗q9 PK[J/C4/Ecrls/P1Mapping1to234CACRL.crlUT І?;7AUx3hbt4h\hƩÐۀ9M)4P@ I-.QpN-*LLN,I-651 *&d+(8;ZD"s*H5Y~R{dJe \ ",̘dnldp.(v#J[.{?5 ^hɮI}`[L . |}UW]h|Ͳ矄D-^73ϴ˪?-c[}wΩw>S;\ PK[J/v"`7crls/UIDCACRL.crlUT І?;7AUx3hb46hhƩʐۀ9M)4P@ I-.QpN-*LLN,I-61 z(8;ZD"s5*H5\J9$SܱYdTp0c!sn{آ__WaNoY'W_ټW*?*IOfޅIҎZxOa%tŌ[/Hg^jޗگݜp#ιFůL&A*kyx3uPK[J/QfXS1H crls/P1Mapping1to234subCACRL.crlUT І?;7AUx3hbt1h\hƩېۀ9M)4P@ I-.QpN-*LLN,I-6T01 *&d+(&9;ZD"sMUf0kY^F1vW{ŗIO7)aat*sc#qZ".bx󅛚J|=嘅-/1kx_}x)1c7Ͽ_x2m8&YN4jZpS*~2Tvz[6C/;DT5mNXyPK[J/73K#crls/PanyPolicyMapping1to2CACRL.crlUT І?;7AUx3hbt7hhƩϐۀ9M)4P@ I-.QpN-*LLN,I-6T6P1 K$Ud&W*&d+)8;ZD"s Uf0k_.ل_5iYH 3k~wUzf 3;+ŧscZZ{z+A{5'^QOt7v=frVGZV!!yF]q~T\uU3>amF3nkN#?,ivPK[J/t+1F crls/pathLenConstraint0CACRL.crlUT І?;7AUx3hbt2h\hƩӐۀ9M)4P@ I-.QpN-*LLN,I-631 $d9%f(8;ZD"s*H5(le,+YkڟU?][mR ŒPFOS S~_]w>}˗/7|̋2|9Xh]k,U;2gc9zOfp{g7;7%*UR$ rnT3IǼx*MSްz qŮKke?*,XpoDo/sczbyy}:YjM^+PK[J/b@L0I#crls/pathLenConstraint0subCACRL.crlUT І?;7AUx3hbt5h\hƩǐۀ9M)4P@ I-.QpN-*LLN,I-6T41 K$d9%f(&9;ZD"s肍Uf0k_6;ԯ=2)aat+sc#C ք dNN3yrϓ{wL!FҲ>_X!cm[&D|>+3wyg'/M/&'{UXej})OǓ5k>=ͷ9 +,Ms]z|/.vE}) ǽ&wWXȰB{_PK[J/KUQ/I#crls/pathLenConstraint1subCACRL.crlUT І?;7AUx3hbt5h\hƩǐۀ9M)4P@ I-.QpN-*LLN,I-6T41 K$d9%f*&9;ZD"s肍Uf0kI,͙d#IC{6޷ @ DX1Ȱ\Ch_?Mt-}/jqjL橳.NNb+REՉuQN/Z ϿXy 3"Qv O5dq.7:OlEo1b~n PK[J//F crls/pathLenConstraint6CACRL.crlUT І?;7AUx3hbt2h\hƩӐۀ9M)4P@ I-.QpN-*LLN,I-631 $d9%f敘)8;ZD"s*H5߲du;˶ʝO[ZeR ŒPFޏ!'d^zY/\9z*8ksy>o\i:e q|.N_~~ؼ%aL?P˴.G93 U> fI\LJD˫/=)^ PK[J/|տ4J$crls/pathLenConstraint6subCA0CRL.crlUT І?;7AUx3hbt3hhƩאۀ9M)4P@ I-.QpN-*LLN,I-6T2P1 K$d9%f敘)&9;ZD"s͐Uf0kay1аR \ ",̘enldp1vw'ONN)ܻfquݦ|`jIsWemX^v+-̂G>0'C'#Yػ{JrԙM&9/>jZ˨3ڥfOPK[J/%1+3J$crls/pathLenConstraint6subCA1CRL.crlUT І?;7AUx3hbt3hhƩאۀ9M)4P@ I-.QpN-*LLN,I-6T2P1 K$d9%f敘)&9;ZD"s͐Uf0kq1yFg~Ǫxt2)aat,sc#Crs˕;yM1Q1դ#WOkrm _4k~,"MG6e >^| /T&C?|߮uCC.GN恺^>F1ƦG;i[#KPK[J/U3J$crls/pathLenConstraint6subCA4CRL.crlUT І?;7AUx3hbt3hhƩאۀ9M)4P@ I-.QpN-*LLN,I-6T2P1 K$d9%f敘)&9;ZD"s͐Uf0k0Y 7W7*翭3)aat,sc#CUܓGb<].ƶǼ{㦃{Zouaݢzf9],{T; R.U Z.̽Ank O'ܻgiU@Y؅k{Ǻ)F^SNPK[J/X=5N(crls/pathLenConstraint6subsubCA00CRL.crlUT І?;7AUx3hb2hhƩ Аۀ9M)4P@ I-.QpN-*LLN,I-6T3P1 $d9%f敘)&8A8!2w<Ye gGsJ5ǀs\ ",̘fnldp(wÖo6gg}PgbL\">L(<֤\pJtꄆU|gY(L-}mºMU-dm>rmP|ʊRݝkpY]:Tӵ%['_Dvq}PK[J/9B&5N(crls/pathLenConstraint6subsubCA11CRL.crlUT І?;7AUx3hb2hhƩ Аۀ9M)4P@ I-.QpN-*LLN,I-6T3P1 $d9%f敘)&8A8!2w<Ye |thm.fL3762.}9y kn:]3CΆLa aןWzL@F'V3FZg[Zwˀ[=kj\9ۢ(B&IsRç4#AU>?s0i^wzތN}=s lPK[J/n6N(crls/pathLenConstraint6subsubCA41CRL.crlUT І?;7AUx3hb2hhƩ Аۀ9M)4P@ I-.QpN-*LLN,I-6T3P1 $d9%f敘)&8A8!2w<Ye cG^]pª 5t p0c:py7Zm*f|Xg9QdTFX%[k-e#$|ݛ|o-$W&b- 5QPK[J/E,+Acrls/PoliciesP123CACRL.crlUT І?;7AUx3hb5h\hƩŐۀ9M)4P@ I-.QpN-*LLN,I-641 d&g++8;ZD"s*H5\v6G {ϧg @ DX1x(ys#3jލgE*ey}mUӕgy<}` oW*Q:Oy9zfOc2V[/+?&-x'o.+8Ctf)|;*'|\PK[J/3Y3&nf—7_fN,vd&/?>(Yo/! E]V)ki+ņ1]7EyE]oV&v󟇧4%hݽ8PK[J/pPB2L$crls/PoliciesP123subsubCAP2P2CRL.crlUT І?;7AUx3hb0hhƩߐۀ9M)4P@ I-.QpN-*LLN,I-6T1P1 Kd&g++&#`$k`h`bhihbjnd%k]ok 4EVE@A, R3}C&0)aat.sc#ìq]Lo>qռqP]cS{%[oTX^sY8Il yկa8I޺?wWP;W)*X>\As PK[J/"5Q*crls/PoliciesP123subsubsubCAP12P2P1CRL.crlUT І?;7AUx3hb5hhƩ Đۀ9M)4P@ I-.QpN-*LLN,I-64P1 +d&g++&A#``(k`h`bhihbjnd%k]ok 4JVE@A[=b9p0c|_c k}'uC:_mW5_P }~Gj<ћ\뢂ϧvyr~ф'N)ݜ)dś]?yvF3[sku~^ӋKDPK[J/v,(@crls/PoliciesP12CACRL.crlUT І?;7AUx3hb1h\hƩِۀ9M)4P@ I-.QpN-*LLN,I-601 d&g+)8;ZD"su*haxJ?[.iR ŒDFEϲgU-}|oGo0ZsfUNopK̾_.-ND{yK1=jN:rpy\4+ o'L]TBr2u,EPK[J/Kț$.Ecrls/PoliciesP12subCAP1CRL.crlUT І?;7AUx3hbt4h\hƩÐۀ9M)4P@ I-.QpN-*LLN,I-651 d&g+)&9;ZD"s*H58u|a{?ݚH 3;,Z7rzk'&x1rF߿UYe9]7X2mᷲ+j5^p1(oά`sRǀCXPK[J/\2J#crls/PoliciesP12subsubCAP1P2CRL.crlUT І?;7AUx3hbt3hhƩאۀ9M)4P@ I-.QpN-*LLN,I-6T2P1 Kd&g+)&ca8A8!2w< Ye =9ZCsu_(b.2)aat,sc#G(rBc}g\2gd7?#j2=zr?WG|2}סy/_y;}u\Ƣ{;dw|w?vXƥ-Wuiޫ;Կ=PK[J/M+Ccrls/PoliciesP2subCA2CRL.crlUT І?;7AUx3hb7h\hƩ͐ۀ9M)4P@ I-.QpN-*LLN,I-661 d&g+)&9;ZD"s5*H5}gO7eLa3)aat%sc#D[/ds[!&[w}9ź|zt㴹XobM_\+ ,:CHH )b 2e/W޳ӵ-Y_wO; K/#EHƣPK[J/-}|'Bcrls/PoliciesP2subCACRL.crlUT І?;7AUx3hb3h\hƩՐۀ9M)4P@ I-.QpN-*LLN,I-1 d&g+)&9;ZD"s*H5?{^;MhQB=O>6y_'tOe>.=W=^1mq.dp/PK[J/zϥ6S-crls/requireExplicitPolicy0subsubsubCACRL.crlUT І?;7AUx3hb7hhƩ ̐ۀ9M)4P@ I-.QpN-*LLN,I-661 +fVd&gJ$rv504014415725D.75&"a yţM2Elg2)aat5sc#Co<%GY)GYowF}ݗj^n#EcLmjVg\wmFO6dz_0\N!yn_v7wҌ}=P.UAPK[J/Mh3K%crls/requireExplicitPolicy10CACRL.crlUT І?;7AUx3hbt7hhƩϐۀ9M)4P@ I-.QpN-*LLN,I-6T6P1 KfVd&gJCgGq^CCKCSs#(q^Cd}]y!,b "_͜v7;7,3u5)aat-sc#OSÙ稇;+RYZg-5kۯ.9a͏_=9FG3TU_t5r:Yss =Kn XYQNPO8U#4Y6T+.iE.^TuIoY>NPK[J/q6N(crls/requireExplicitPolicy10subCACRL.crlUT І?;7AUx3hb2hhƩ Аۀ9M)4P@ I-.QpN-*LLN,I-6T3P1 fVd&gJC$gGq^CCKCSs#(q^Cd}]y9,b "UI|^zdρYM1)aat0sc#ӊ8ͭjan1ld\>BeGjݥW; V8 ;*IgP0Z:͎Z?mͯfU7ŒkٶY\Toֵ")OV%6Ә s]ݡwɒU,_PK[J/R7Q+crls/requireExplicitPolicy10subsubCACRL.crlUT І?;7AUx3hb5hhƩ Đۀ9M)4P@ I-.QpN-*LLN,I-64P1 +fVd&gJC$ rv504014415725D.75%"a ag|z\6y㿦H 3"Nk|ZzOUOg(Zgm_>}0_ԇ9CZ8;=j =9]rlO(K՜'s&i^ሏfgR%8?~^wPK[J/:77T.crls/requireExplicitPolicy10subsubsubCACRL.crlUT І?;7AUx3hb 0hhƩ ܐۀ9M)4P@ I-.QpN-*LLN,I-611 +fVd&gJC$rv504014415725D.75&"a 2zB+%*lz.fLg37629)8>%rόɎo5@|R =N٘~g(_ڎ:Y-_3).q_|{l2#e=~)L'F~ܕ~rEkJ=.pEunwf6iʚPK[J/L3J$crls/requireExplicitPolicy4CACRL.crlUT І?;7AUx3hbt3hhƩאۀ9M)4P@ I-.QpN-*LLN,I-6T2P1 KfVd&gJgGq^CCKCSs#(q^Cd}]y,b "u^6)aat,sc#ÌG|gs441⣗~LM᢫J}2,G;~>AK[sE_brLzW>^%{)֓۳Le"g]Z^ëPK[J/,I*E[8/+Wd<%_KL  dy3M2Nhrـ3] D%PK[J/=86P*crls/requireExplicitPolicy4subsubCACRL.crlUT І?;7AUx3hb1hhƩ ؐۀ9M)4P@ I-.QpN-*LLN,I-60P1 fVd&gJ$ rv504014415725D.75$"a /g OO NT^=À @̍ -8\Qk11\Rf3?lyO~*BZ3+\4_$jGK/ꩿQmZ41̦kTu&7*ˑVduo졌 1=8\<[V»PK[J/ù"v7S-crls/requireExplicitPolicy4subsubsubCACRL.crlUT І?;7AUx3hb7hhƩ ̐ۀ9M)4P@ I-.QpN-*LLN,I-661 +fVd&gJ$rv504014415725D.75&"a ESwUE%=(6ۤuҀ @̍ >(Gmm?pNMkmߊq6 %JLt=7,Iq/~Ulk ̵OX[otU̍aV<vQtn<n2Nr!o|PK[J/B/2J$crls/requireExplicitPolicy5CACRL.crlUT І?;7AUx3hbt3hhƩאۀ9M)4P@ I-.QpN-*LLN,I-6T2P1 KfVd&gJSgGq^CCKCSs#(q^Cd}]y,b "W~_{Gyһ @ DX1`65Snk|6}nȶ}Ojp|3 29gڹJowoۥt6||T^inyشe{}]a*vQ+SCsD, {n:ed:6ּW=p/PK[J/pI)5M'crls/requireExplicitPolicy5subCACRL.crlUT І?;7AUx3hb4hhƩ ۀ9M)4P@ I-.QpN-*LLN,I-6T5P1 fVd&gJS$gGq^CCKCSs#(q^Cd}]y1,b "Sۺ'":kX.fL2762<)_Zl[sa٫&AY=lkY^γi0gߪf-\/v=/:=s1 \ŧ҉6Fh/¯].?)_+ůGn}\~U *PK[J/t|6P*crls/requireExplicitPolicy5subsubCACRL.crlUT І?;7AUx3hb1hhƩ ؐۀ9M)4P@ I-.QpN-*LLN,I-60P1 fVd&gJS$ rv504014415725D.75$"a m6gi郕N3Lզ1Z{CnGgb'_;kϙ:mvUí/R}/h?ϵ֮t-(],?!A72LPK[J/r2J$crls/requireExplicitPolicy7CACRL.crlUT І?;7AUx3hbt3hhƩאۀ9M)4P@ I-.QpN-*LLN,I-6T2P1 KfVd&gJsgGq^CCKCSs#(q^Cd}]y,b "sDf,_pz~\ ",̘enld}K|U:g_5m6v 7[`gQB5ߌx zΥ.M}eEO'_Seޜӊ7ok|"kM{O7ϱ5ZyPK[J/ 8P*crls/requireExplicitPolicy7subCARE2CRL.crlUT І?;7AUx3hb1hhƩ ؐۀ9M)4P@ I-.QpN-*LLN,I-60P1 fVd&gJs$g W#q^CCKCSs#(q^Cd}]yI,b "38=?-{sDK {o.fL'37620QᚽKo nI ζ߯G >Ȣ@.R5f-}UZOve燶ڋ}jƼ`^MhyVYtpO抙']@Y\s:;lPK[J/X\;V0crls/requireExplicitPolicy7subsubCARE2RE4CRL.crlUT І?;7AUx3hb 2hhƩ Ґۀ9M)4P@ I-.QpN-*LLN,I-631 fVd&gJs$ rv r5 r5504014415725D.75'"a rZgwύ\$rfp0c:aYP׎-˓d6Ogf>?y}ԙ1jQc,dV~^u~7H>hQ].*Y;N+bf8woO{zև?_H5+PK[J/Ч;Y3crls/requireExplicitPolicy7subsubsubCARE2RE4CRL.crlUT І?;7AUx3hb 5hhƩ Ɛۀ9M)4P@ I-.QpN-*LLN,I-6441 kfVd&gJs$rv r5 r5504014415725D.75)"a i9/X24%,eR ŒvFFTD{Uk߀f7W?'bPţ|=sٶU,N/ޫΏ,uO>^2^_3qP-HPK[J/&>crls/RevokedsubCACRL.crlUT І?;7AUx3hb2h\hƩѐۀ9M)4P@ I-.QpN-*LLN,I-631 g(&9;ZD"s*H5T|=Mz3;p0)aat sc#p#zf/z..;i#C̸mhխKjeu\i R"Rg|_j&ߪioŋW`ݸvʄ"[2l?g,XUbPK[J/W!V,crls/RFC3280MandatoryAttributeTypesCACRL.crlUT І?;7AUx3hb0hhƩϐۀ9M)4P@ I-.QpN-*LLN,I-66d✤9N sz~PeI26A~E9y)<\ !VafcS􄙜y L - ML͍ y t 䁊eY$ D.Yđe7SZmٲ",̘enldu(|WL'8Is){㚱idZ]:şd(ׇd\Nsm4}_kdaOv~F '< Rߓ_G=%0K-񚝬u)Wo`PK[J/XVl+crls/RFC3280OptionalAttributeTypesCACRL.crlUT І?;7AUx3hbbрSͣ;/##++A,CnN6P6a`C) KX0$D9$3-39$P@$.㞘YZTTZnk f32q AlGa.̒b},LΎ<\ 0'(a_==q^CCKCSs#(q^Cd}]yrYe H-Iv ._|l 3י&v0$و{̠+;wgQ|37q)|>)fMdeez,Nny0V{M(?_T/Z,{?'f1>X#P=;LPK[J/jB_5crls/RolloverfromPrintableStringtoUTF8StringCACRL.crlUT І?;7AUx3hb6h L7Uu3\ucѤk2g%PK[J/Qu4V,crls/SeparateCertificateandCRLKeysCA2CRL.crlUT І?;7AUx3hb 2hhƩ Ґۀ9M)4P@ I-.QpN-*LLN,I-631 $ŐR|S+y L - ML͍ y t *H5tkuM4]8%܀ @̍ ŪNEu.=Ƃ},Y.}-_2*̳]Go4?_ꭽ,bJm*~ {Emde8X`yO#O+ ߲;ergWTu~PK[J/RMGz)crls/SeparateCertificateandCRLKeysCRL.crlUT І?;7AUx3hb,3h|hƩ Ґۀ9M)4P@ I-.QpN-*LLN,I-631 $ŐR|S+ y L - ML͍ y J LLh x vȊ0s12.75Y$ D:iVGVy})~kYmfL1762U 3Fǿd-yGmNI۟~}m&ƺזmh2kK{5[ąR_o9q–a WT.7V;5Sҷk3+OPK[J/lI8acrls/TrustAnchorRootCRL.crlUT І?;7AUx3hb5h; z]fdoA2;E,PK[J/-V4Alcrls/TwoCRLsCABadCRL.crlUT І?;7AUx3hb0hhƩېۀ9M)4P@ I-.QpN-*LLN,I-6T01 ;%(8() Ύ&&FQ⼆\%pMeabd\ok +H5xxYQ'8gx)fL07620^ɵluDv辤!j!PK[J/~T%<crls/TwoCRLsCAGoodCRL.crlUT І?;7AUx3hb0h\hƩސۀ9M)4P@ I-.QpN-*LLN,I-611 s+8+8;ZD"su*H5xxYQ'8gx).fL1762buQ=vwW_wG$;;~N2\1@n7jLRg֬j٭g9u_;e԰O* $v KmqPK[J/l^&crls/UnknownCRLEntryExtensionCACRL.crlUT І?;7AUx3hbl1h|hƩ Ȑۀ9M)4P@ I-.QpN-*LLN,I-6T7P1 ˅e)8(U*Vgy L - ML͍ y @w)2P4.+t0gBc*#Pf&F E,b "__:7sG)1Eݫ̍ neWe|G͊uImwUnrqegry3S'G)se˓o&匴Y{MKf=;O׈Tt}??Toi\#cN<ʙ9gm4,jZPK[J/'V!crls/UnknownCRLExtensionCACRL.crlUT І?;7AUx3hb3h|hƩǐۀ9M)4P@ I-.QpN-*LLN,I-6T41 Ke)8(Vgy&&FQ⼆\% peabd\bFVE@A$_/}{0tjf8<Sy A4O27627,m9jDWyE=lhGw/$ֺnzsy !JJ<m?y)7ǡQ|T][_Z.PS=K{\ r,St-《pPK[J/\ j=U,crls/UTF8StringCaseInsensitiveMatchCACRL.crlUT І?;7AUx3hb 4hhƩ ۀ9M)4P@ I-.QpN-*LLN,I-651󨄆Ye+8'*xgd*&$g(8;ZD"sUf0k1KլYzBbW'p0c(%2]4u%E8V~?~WeJAshnY6%sir6w+Yd^{Aĺ^u$Bw/,S<[)Xp%7X#e[ν ׋= PK[J/'>$crls/UTF8StringEncodedNamesCACRL.crlUT І?;7AUx3hb2h\hƩѐۀ9M)4P@ I-.QpN-*LLN,I-631Ye+8;ZD"s*H5\pLቩfBF*é\ ",̘dnld>>3M3 ,l?U냑S:Yo>j=*.'gǧ$̣K8>gvCgsS^8AmS.f`B|VŦfW˩?6`gK\x]9PKU"1lI8acrls/WrongCRLCACRL.crlUT 07A;7AUx3hb5h; z]fdoA2;E,PKaJ/x{crls/DSACACRL.crlUT ن?;7AUx3ha8р] !7&l(e p (8de&'䘅\y L - ML͍ y t dY$ DJDKYWJ/р @U :L"n 0k% V1u~I%=VPKaJ/)x$crls/DSAParametersInheritedCACRL.crlUT ن?;7AUx3h|gир] !7&l(e p (8de&'(䘅]sSKR<2R2KRSy L - ML͍ y t 䁦*H5Ī tC>l,mR ŒTf]&QN#ҷ]dmΕ眾$s1z\[v_VPK aJ/pkcs12/UT ن?;7AUxPK-\J/*]Q+pkcs12/AllCertificatesanyPolicyTest11EE.p12UT Fц?;7AUxU{8ԉs7qFl㒵 mhmJ31"aqk- 9imrɠi]22us}}? 9@*} Q ܡ" TdRa?Bޡ{{!HP.硔uTj#= /@9xREkw 'RtGHz8ryM<ƨQ\N4[mD];@3F[pj]+ w!OOu,2>񢢍?#E*4Rw)FIB/ʍ^BkV^qlt8=7 ?̴0?.듡vՕ։uvk]_w^ :/gV~KYJFvF_oŁNuUhFIZ4Mӽʨ/| 3s-3KŽxɶ0˃?1y­%<~P3XJOx1FC9(SCynj蚠>. {x\iujvzKșg:K~]ke8_;P}o QѰ4髇ye:!&ǻ /TvnjORni$J6fق? S|FJ()&^o$Ͷ-nǪo4 qqaRjB* mwa/Ҡ8g6ca5n'%8M3ydLuba5ʊl79v%Urb_n0e*yܷ sҊ-1~ tϦ`kN*hR]?Md/fzQA?Iht7. Kͳ@tTɩy`6xtó.p>==0{ʞ IC6Th_(A5n組?(S鯄M/T@nޟ~5؇ a{[Y!ӳ.;1AهWp`,8JhK6wGZo>B e^m[I[.T)p? >p[}*eFk6*?\N8'{ˋPK%\J/,I+pkcs12/AllCertificatesNoPoliciesTest2EE.p12UT 6ц?;7AUxUy8s$Z!CJRTU44 QM1UQ줪G5Ru}2Yuh1ϳ|~2 ˄@ 32䀒2&4 „&X&+h?A@a1 b!R3Ş;  (}ނiªi;}Y ߠ{sنI_ו6w+dѬ}20 Q> )̷+1%Vh ?'r}n~poOc+oCAɊ/= eͦ\Esnu5H~|*fhv;{ "޺B7m tV^ S4:;NA;tkBcDh4J=DZْcg߉6[nӷ:W- v K wg_#]/i .D9a袘3TQ4u@HO[M5ޕgLx.%\@=]rj>U7Y4Ҿx v~S]F0WS|bx`y2&["J@A[#iC^* F׏IuQ"LLτLӽk]8zyx_<}.,:3cQ/ݫݛ=5( N]ф j2O;/2J!1 g=Ȥ\&!y;6M dQ g }a|] TDOAmx ~f ci/9J:Ò;_gPdOe{O$RH`f3( K:Dw:6ĝ#|@_%qA~ ?V/OH!56L,mX]?S][5`9;ŽQYEz PcGYvb>ͼ21 ?uzAeLP% *Tq]?iR)3!PaREh{#H^֕ԋ^LZǪ7>Xѣ]Z{r!pÒ`jjujzbv`\3ʚ4ODd-X8tw3xtcl`VzT -V 58z bQ8gW-Oy6CsQGUN_NU5z&%.&fbN.{tȧ 󌰹9Y G aɉoDz8[_rP WPXU~gz}6I]j z$ѭWܡ#/}1B 6 &:ٗc59Dđe<}2(Ý(/'X6d/+X?8uu 8pbqp@ءBA}(JɃAHݶhv0bطQx-5* n>PK,\J/<.pkcs12/AllCertificatesSamePoliciesTest10EE.p12UT Dц?;7AUxUy8ƿ,;FЎă;UvBDKג-R|:T,vTǔt7(ZS$CΝ?w~h l ! "إh Q' D!8\pl-T  igI0}"eA }^8\eD.m=|G={[(Eܳ]v;2rީD$6ڡ+,I5B:)@5XÖKKrސA✰Ě]yc \T-?Qv.%GR[LIȗ]-^9}AҬEr$K^>ʗd{_Z kQp>ˣSOFSM+d,j*Mi]$cv îW=DVX>7!ڑYK?fZy!)h`\Cat 1tլL8/{|00j&$q\{ѱSγjV XO+ Jփ-9<.(mvʧwYD2Yb>/q0c;N#&iHiu5KZ/QmXd ~jM1^J}{e'Ҕ9Y,63E g!M9;ɹwBOqZ՜k>-^Ͽmf=J.@;-zcPb!7NFrsBm:~ΞQ7{@F(6>bU1**.+MP^5wT{dž"/^=Rs3EDž\]s̩>2:a>d4A cz)3o:K|/nAg} l2yo"Sw!,{Ukʄt4R4zӏiA`ZOpdzt^B W$I\pa,oJMnjy 1JwE.k8Iu$qV`4)uwƣ]*7>I8W7/``Y\ FSwxs^T$8c+Ʒ6Cj-S+&,^_%n֑֞Q%ABJZ_e{q VW }dH\#!?\qTwב FYY p3Pp&IDBhà\ӷFRIE,X|:pA)|PK.\J/nF.pkcs12/AllCertificatesSamePoliciesTest13EE.p12UT Hц?;7AUxUy8g3 5™Qd!rKXl5OLc4F:ьd/'t{x{~hwKFk4?R|yZ°ߤe5;c\gωG~vo~B7L[`焁MM^1[ή{0}/H_:_Iκ;bݱ3j?+R9E~e <7'7-']7<i)$W׭M bG7>ũWDZA'@럗;fL~z0ɦLDfM6gS4[uDJ3WXb471jy{"5G@W)kUu-LXگE`;^ iL)j2_guy DOO bŽ At3DeODCe7IqÌ11nȼ0BI-͏;=]2Z3!˙]n**6 =,K(=U75sГVH{<Ks[_*wWD.(cjJEyb%ɘȤ^.VRD 􏈢Idӓ1V^|If7%՟+ lWĕ?߅9(.'wPcwl l6xHysNRo*hXr_oDƙ-`-kyM[ʥ%Ǵ80ݔ?-h䉎II'Gk29K3}sFv>;Emmn{$߹lV 3fS'b'5ſHT^CeۇGKuw6y,';O}hPFDzUDڅ͚u1#vQBzn;7 q/5,b@S`I|>TAd<F_4֟pE#J3LI~TI}a tScKebAfl1$)_Z̘:[BE.2}Nlga'U'@vj]~[tŖ=F9i|wgq}{{ēn$ߴ~Kl1޸bv;`{OL%uKF+o /eU5TҍUnOW#.m `E9%_J>ZN4\k'QrCІv&e3n!ӟc<)CX7.9&UH 7M)bCE4ӎ)x؛/aLJ-̗*BcY|-.͟u-2y7A!.Bٸw{5HWf:)WL󏾎  KW E{7NįI VqN3o0{inC\Cm*Oă(,J!G[#`e ^z|)V/b}#{W YHw%;i?Q?Xt4xc M9\21< p$Gd-IQk UЇOͲ?BV8#gboW3ѓIC)5b:)`c.W1x+/х3ÂB99=  0BH>GZ AyA<x"=*Z5#H5BR`-PK-\J/-npkcs12/anyPolicyCACert.p12UT Fц?;7AUxUi8ۉYFhP^A.cP[ZR[[4MHUR"U- 6ԖpKJҩ}4<Ͻw|xs{tXaY0sSTL%B;{v9 VL, 0+'/Ug P%ɷ`iFHa8Ns R\(דMTspb|cnQF;Z.RM$xbؾr{ʌu'/`fk)o 3ViqjYǸ aEޤa}0޲)8.RϽ{|/V6C !|L(8:e 'mi5o}{6*9g/F p1FO8tjdߟtA`tVH3h&Sڙ sP>JM OhӝHA/:Z8Զ%VյzCA+r'5`ԥWkw>nлiI0v.FjLFmo}$OTTLt"ZW|˫Ŝ?73N!=$B8N") ͜|yUg P !aZ jw]cvUFٔkVh!#q%CӗwHoe0q؍zܬYlG{5# zPxR2P@aE$M) ʕ/AS[noȕ\Ulߍ  zT/'%6%aʅW\_VNWcIK߼0KGZ)F)O|2.RrX9-U r'@j$^_fʀHtȇ5"R9(0fZӷF30 oy\fOTw]Vʜkqp0HnH;⣣QQO;3S&ۼJh69|*͏( |2Oge|seTpʧ@8֒NAlJ'nG@0'?c ZXFFJPDWj}O .YJ=R?;PK.\J/Q#Mpkcs12/AnyPolicyTest14EE.p12UT Hц?;7AUxUy<ԉǿsce Һc1ƙ/bcK3 ÊA$ұ9r [SxaL6Yz~{y=yϛA^qJ*eSD ^ŀX`pPt"P 8A *[,!*wb@xCȿ[mãF?H_q]k4e&lGe13-dr+fWZ^CWdZi%6;jx)v%ň[E*X*x2-DCoa??GW+Z/dLgBCD&Ws.IO.m3(ܯHRһ7n'9t1+'y $wq&.'Q_D,%~V>VE</|$γ̫ Zݼ .tJMϮR_E-i@ӳCO՜}T7J,k1;#miۇ o~n]= ADӗLT^M NDsv$4l*@HJ4zJ!ɣ!AIT֒n;_h2XN(&aOA5L+F*K%VvrwʐGF?_^7G c=dSիxڇ"vaIrۍq};twO_?I>Cz; b rEf:}r/;eA&fMgv}֞d2~(g#:$3oe1lpR) ϼOyC# ہNOoNS:-= 536ǖ챆de C1®@ VU, ݪmaJ+xU=o5h{Β:VἲY/Ch})]>P+>pxnQa]ϗH0֖/,#}w? 7p+{jF@hZ# m5`Z Q o_ j=CԒ)xʜk|9׵O{:Td8Fkz ͟Þ?9^2EH#lyhY_|;{0Yme6V䗉|a?6ĵ d],1}HBqtVv8wqcTUa~VW6-{n7Vj<``jB{@˜T\cv"B 4j namԷLmWb48?7jEVݠPxIbrF]cQ;-caH:!3m54&w*dDw2Ys4te-ޒWs5Mgom<`cH<,u(8րLPe 䠘wnߺj),nM{Gs1PR@8q@ =>cq8 /+(ҺD4w9[C->524$)ΧPK\J/ԓ !pkcs12/BadCRLIssuerNameCACert.p12UT І?;7AUxUy4 ߬-uTlX^cj+ERuuJ "Ç2j~IT%j>-ZkϹ>>HAB` IEHwNߔ@)48rh'?+d9f{hBb!Ps A))ݡ+(T S`9+ET|mז1>yԩ+ve7`n(W]@ӣ7d}뽶>ps>0\ޯ]*l|,W6+mzt3flR^Zp[^!BidqoI[`e :7t/̊h)&JLRPHQ6A옹x1=ٶT5-EQzIN1Bt)Çϊh" yLO(+I+JMK"LMGNevHx fJ"yZ^wWܖioq.z2qvgCZĕT{]$뻗}'L eAPi73L#ݓ5<^ wW u'QfI ӿFMQ0:*Z\\ثv$Mn Eo֜RvʯtrIKsK1S fO ^k0Tc֧V\:"nf cU"iJp0-N/rW6?!OQ"gYyߍe7Sl\`#^cO%{|u>)v4߲{Nt ޡq9A;6T{ \-W)޳"bUnd!Td|a GΧQTg(~ωsF_-&o?,?ۥk|iY~#55UD@(pP׀Þ Ge{5'/!-.xPK\J/RU pkcs12/BadCRLSignatureCACert.p12UT І?;7AUxU{< w3fcb#!LA9m$uq5!r%̰W{sɴs=lk/Aak.Fu>}{}=狥BA@0 ̈́´iڶ$PȤB!Th́}K_keR18(*A3HX)Xԫ%}CH @Ŭm%;҈ްPt{i67ps'}uG 6pĿ&׭1+_ݧSW#2"lHooܻ|QaE)^N~!" * qsa}~VDWfzKd]UL4 Nf]Oųڼ#{iV{T#)*ڢf# DІ'7lK$*--"ri2,xK0[Jq;{su+ǎ:|\w=8k8[GJ}srƛX焎K2+ǖ%~Src fU\ u6\ mM~90C2Ntn4=~a6Vwr\<e>`zCxmD嗍ELۙIQ>X|[Tt\f9d,PDۻ(ܮ~|GLs1fko˺X؜z ȥN ^[%y!aO(+_ դGO ~:>jtX1`,Ij\ WN 5!/&dzOÆ4j}_-Cε¹b(-<"'YkppOI!6󓫦v8 |B؇8ĤTPIˢtT BQ ϼZAs~ ]8z%) ;|xj~Fl '^.+۰L'NAіlȯ9)/Ϳ 'IKńT_@Ym?.fM9ݿv8(:E1Z{ٞ@K]k狢BwJ`\ıW+]Δ~1\ ?#ZHtf\W՛JzHcD8wx8*!AޥOAO}C im2GvsR%iNi&g&;uW>7E&t8J~S; Gj2E/kժkv|?P,d?9dҘSr!̻4LU$>Idz=\}Ţ-%} $T쬘Yp13u.wAZ8MHH&,~@ZFzX}5LN AB)."*KM@6} O&VAEt EA|zq$R-CJ9b.&8PK[J/n; pkcs12/BadnotAfterDateCACert.p12UT І?;7AUxUy8 g1i4 Xgnx[1e #]!}cj(%[ޑebelի{>9·@z `( ی59hm;@:iPm *A P07&[LDJJD| ,XwS82u_٥8.DcvˀS\ڿ!(xnt @d8"2¾jȟMi8r!dG$C|V|}hފ'h|uc R=$,@I/M2e Hi1ئ,{{|/%O͟=V_7U2J?'_42,.AxeII3v6M/YU $7YƯf-g66*% xf$Md3w:NմR2@F7_'mkX(O#e뱸 ;g9VVNk6?GJ|eB_3˲J2qo+E\/N[-3vk0ԚhQ0_yr(-Nڤ'{ *GqFUǘ\U>$[2gZ+'߹eyJ-`゙/v+٘$5+M4l-Հ3JXxWbLϦ_ےf`d@t~+'nD\~3k;)Nnfj`<yt=]YHhF0gwktyw+ϕSZc,E(g70xg➗R1n׏jy^iHO9%n^6{t*E$p>r8ZpȨQ!F&)vΛWl2#&RԮ>âJqO+kIL.=)Kqv2d.>pGܫ־tr'e'l:%l:!e%L 5z#ꪙҪ8^C]|3xvm gs ' qkkgvv &r.9Ϗi;m\b1\HaEґ 9ЭYMMdQSDvf"59)y4Pen{6xTTL$]Yp̩ Qo "#WbwJ b ?re f Ť]necj+է9ΧGb!4?6;FL\15 䔴㙝dr~଩WZҧ..JIEe4!U5]D ~T 4 Ҝ+'o5H|VNjIo>ЦjWFp8`QɩլLŅR69Ց⌾W$BG0]:{h=/§cdtHY6ADBRUŰmѡ[ng2XAԫ5c)+/r~L״3auWYx6P wXH߁~sLXLLNcy`u|P˂7bKE45#CرZ}WcC{,DXd:4E&I=hC1*ziv4c^ o b|*(oo5l{{:(;kxٺ_+Osa״G*O 5u\^v,i\>ZJt7v-~\ݒG])/ݦ;y-,sTۆtQ{o%-҄Oh3'0z. H_Θ^b0`@gvwGu%x/MX>n^E; Bc}nޝ[ޝ7} S:0ݻs#4~@ +)ൌڔ D̷꬏j_1}^HǯZg> O.ӑh2@0 Rs y NGk7or`cn/γ{,|jf)ɛqmbi-ضvŚβk E{ՒPzjow&~{ueϑZ]] %4A ( *D>)(#ԗ(I,8&*Ύm |`:ʮlˁJ89)PK[J/ mVpkcs12/BadSignedCACert.p12UT І?;7AUxUy8 03#ǨcEHk ;924!wܒ;1fC++6YdVy}πBP<*&4X\ƀoS +XjoA k2+yI d3"3 7G|5v\mӣoD6ZM𸞴=\mS6ibĿ<&MG%_X&e3zK- 3)w*D=duJO/g1 u  `S8.j0GBT8]Tr#ӨRd>p%_Z8Jyw@ PT̥󯁉;_"߃~fmsh5E)XaErNyJh!yCE+֗E*V H L}^5o!1.m慼܍@):3*bR`9ec1.TB~ժ Ϧ%۔0qfeIiaIZ&a3b-q}Q1c$E))qsXwf}ߎUm [?ڕ.F"Wk>ʘWn㜮]IX>"Hxa'MLX 1wj7|^]LT_n g9OgN)f󵼿m_k4:ڟgUD2;(/fؽT.؈AͽHUV|,-[giGX@ӀE+G@>k]k#d[,cK:zE[ zENĎyX\86*%Xt@P|wa^7\Ft'ąwTD]]Aj*YiyDF if*>A} DXs7p;1ÏUVHlh309FAz`ߖݗ$Lo|$2 πT*Tc4JH, `@誡-{Z+ו­kRgF>JEΔmnd A}S׾_u3Q;%f|~޶ٍT t>ub{"c윐ca?}`!X$8هo#߃觧ƻqnNPȣX&o[Nxvh3W,J$?Eh3w#"{=NuyaLHvc9uuפ,b45}Ǹ"ͧ嵼QӉ3wsuveִ @MA .]%ꠐLl2ʹ魐)3 YR[WJ'Hl6*]yK^kGn&7ǏQThl>zݷrnE+z&ɗh?v1\"n6Nl8╬C鞱 dyuբogls$Gp}  rQA@P$ Dx58LD[ QpaЫcV8N 8b6 (BPK\J/"0pkcs12/basicConstraintsCriticalcAFalseCACert.p12UT ц?;7AUxU{< w1b10weIƉqI!wp)¨da'Q亥Jؐ$r}q^ys}h 6NKJE,р;v&khP}, /¡ `' НAUhmB DT I~ۻ l}F|@>.ߤߣ8q7˱*yRIQAŵe;-^>ݮxLe^2QXUr5Pp:Q^JD]kt8%qCmLAND֤>*[yvRz, ezHNf:׃F َÞHÃLe,I)nӂL3[bcd ևPfn5a=2%q:=|z md skXW$O6Я?Y1U .R$,F9ì*Z#y헺8٦WG89<ćAC^5O}x$Ɲxpotz|ktFG^șcTHlڶ{YͤaP\ްRN̮!*5?̱.<+q-|^FhzUV0%߲ 0>X[olBC-IĻ4rSmSR|z^_~f/l7<js38bJcDQ8 p5;yv~Kbq?m`(v۲]M+`n Ơ'/>/S̼6%2[-I-:^SIerW|8(a*(m>J.. ts낪ywbu[e"NXӳ^F #Hǃ} MnI"҇GޘR# fE{kUFXj}:afclVrkat>F)>Hؿ= A}J a 8oA)Y?i PTU;qGLs utH5yqQi66w5XsaX؝v"i Ѣjs a n m<1Fz%A/^{ZrqHK]ltԦiFx;U29SUdkF[F<u?Iݕ9b-lձF}]u?H:ANS4/XDe!Lݾ^:bNA/oJ-/ѫBBGƘO~yLLHY}xC.޻u Y^<5(@_]esmg`x\Z98auC7/χ qvl@zTl-)!iZ Bˉ ο(IY4?)$soB2{7~iʟõJxP) L,.{°m\=Gi7/|ia}}K8e;v߁u rd㬛xJQ+JlVs{1|`\!g~V{)T3|n8ᯒ]-M9Yyb뺓9`@)rAEqE]mOFTiawcHCòǻu8+i~'E_?ğtqAk]T:pA)M#KQH}\ma L(#2a(e CGl/o ;N6fRQ747=t (hCuuȦkMѶ>\;fJavչLu2.eoljTa1ҙuEmsC%_3kxc&d?Fp""IWټZO$Kgr> FImV_K0o]qo6ˈgu_HEP/Z8>4_ԽPd%o4G8/T30@!^ dUtvf㜴~xsAG=/ U`3p@:xG8qZQr0ԍG3WN!O!э'!9’47 @p-[}фMTD(00(Nc}@)*\PjPcD<sBPK\J/[y^3pkcs12/basicConstraintsNotCriticalcAFalseCACert.p12UT ц?;7AUxU{< wci uBker+e G6wIS.dR$|=<{τM`<V C\w!LX ޳LW06gA@^qG  ﭠ $3hj҄^Xf5>, vgh7C qm'럆g~ޘ1S|]qO\u|}?u3&} !YȲFmlMR̆cjRLQɚ#9e4leYSc>S\̌FU;{(B&ѯG9A۹cezo\')+VYょ%7,i=k+i'wROLq%/f,J쮵}frxÖqT}yu4%OL^5^nT#>d-gXrjϽa"mc\@PLΜN0b_t #=ӬRm;҆$|ƭ2g'6+9MZeD-b#ŋ&UGv6[ի]/Q DC 4jYOd:pqMu gnJc \`1HS}~%+==LY\fOew7ڗ+tpM ?Q]Aεps:逳͐j.GWd*e}uJ%~pڋD<$lase?(u,jku{I»4 ͳXmԃ6EtwkWC(15@9!&1oZIpNj+\Z=PNbj,0U'0=fA$gM8~iSO/n# r~I_C`=[vOR0a%  . 6_E6@g~RԾ,.s`سCܠuLg^5p4(ߛPcuO_qpWԨvh{*)SDR|td=5rkaF+f^5#˦I/ZwSN :ryW.Aq'"9r8?xe(q1[?gN,$k;?~V*bnr'rGr /FTƳll. l:qAsqq祥nC)t_ی9n䡰!\/7 sHm:~ݑ$ yIqc`uA[/PZzB^|2*-ɞ99 Rs<$,hQ^/McYUS]գkIP\m#iS%u1$'?_Qj+Xh{-nfDXEI_ GfC.f~?}8:l / IP)Ø;6GZJ v Tad@0nAC/b<0}8ZseHpyf=aˮ[̠ڊp-?*SgSF9%-td#ז 0l:}Z9^w5Yy-(7@ unA(fNKTzH}c0kd#!)Չ3ћ*fjk리K47>t<{^pDed٣:8dtc^ʹ"z[|QI&DŽmQ eQGiLzzd?pC+U4 ezR[dJz#쳕::!aVI=csˤLqD٢mV lbQѲTZU|$X$'u^6(L[Z/y?lVQmI0-΂s+`A[TY5>:]WDiLzZ-16,+h^U7՚3DL}@oΛǹum5Ƕa<Ƃi\ v֓K޽7 %IST|ݽim4G7;iTs\Kӱwp6po &i#T+vRKf4ۭ;9c!U jXjs*PhTu_^IEgGIϠYe֌~zm'ܬ׮^7q0oBZP^ĴZwԓ/Z ~->kh×~U!lsں4 yVk7PkM[F & ul 8A B~\` k :zF 8wkqRAb|^蜹}7Ya(rzZG~wA3[?aSG3*YiS2KbƷ?ѽ5d7|鍔͗ALi1o ŘznxUa{m`1.̩=D_-vHDlU`znYY &8jj v@0p Bʎ;}0NIhA*59;>^e]_|s, CBBHY?Fq۷t_1߷F `~`V? +Cy%^? A wj,_ȧ]=ݭkJ!cN,?*JyukDfuNt1JzHB-:iX̻Q8ϙzcdeT_-@Ne q _lzrS$=)nKPz|͑d=xR"GTQ5_@)r>=mx2 w<}ӒQ.4zHf(Gu5R?:%9$c۽m4eL|pIb>&@zNKm$Vfo\+8ųߙȯe.3q"pn_Dr(->Sߞ v}ZX1Y*nޑ68cq K4ǥ ;N1L4,RQ_-qvU$IQSL ~QGZSS]pvX}nJ{g$V]oܒ-²Μ-ZIߢY7QtIPVS:@6j3N ihh {ܫm!6Gw ?Dtm$G9ٹ,u_AP|I~@OXv ŧEl qYcT:^lא>M56P2x Dޢyf"xԵ&?;P4^y)IT̤KGďڙHmQ/Fm* D(*npDף {p@u~G}Qa;<˂1P!'^L?^忙oCll~Z鹇ɴ Iagd)V7?d%.5ōXZ*5m\lf$gGP\>ٶǖ}ĨjTC8X@ M #uۘZF9i0s?T@/`H1)6ټD'm @:rƊk:DAmI#>1ZvD?j*4h[?0]-j<2wʖc1c TOL+#}`?ak}zhkHT0z%9Xr>cffv՛B -8mɭ4>Î|t eYӆf{!bYSW?xm6J0^CJ}ss|'mN8J.#Յs#@۹1_ƨN^ڏC#>!#ya`bwI2rHwGmZ_oE cFBnwFc\%.:> gɲ9>5oBÂ=)HHA҆7MKu 䪲DprV^Yk-kXSCH&{#XD \^ysN{na;P˶$Gmk).gA]^Tw:txs?WJV w 1e\B`"_#Ȳ-(iy+yup 98`^!*VeO77ϋ[NkZ1b_V|x{JHHx 輸H&W_[ rHZsdpwi{Nf"U"d}zJ_PU0_9pe7;)&_=A>P(//~=âৄ xĨ횦100dͧQ&PK\J/dL&pkcs12/BasicSelfIssuedNewKeyCACert.p12UT  ц?;7AUxUy8ԋ3vc1sTJ3b264,#t0dMÌ(2)t9"Μcd˱=Qe{=|}, Y\JCB$!,DHٵ Qw-k(-?#{EG7P$deY??7?*.tV7URTH7ԉ7UK 7FdSmY>wxR[Y#6J<]).>` 4GM`Z9%|S^ƾXy{󩥇o4 -k"{cC Aȡ#Uxސ[8pd}@p7|ėJjI][eUݧՇwZXy]vq5xԻYGb$e <+JӚ.6KUB47Ee Q oLƝOEˡzRURf`S\Qs!ԿPA)G:ukܫ`U҄D?̝ۖARNL5vܰ ̤N֢W)M'+KOH0`eaN\;mŜh!.T{<UλH4v)>xXh+D Wd?RH03ԂY md3}V,ѫ+{;kumc1+yO9'\$j$}hgs3#_{ZRuW+z&<#{iV~s`<3 ;,6GUccI#mjǙ֜Cb''nx ;~m<rPf/k0P7kQ&-VA<>4؟Ʃ\Xv_y2OĎ IIJN[Y`v~KÂ_<LC fDYn=L$$ )W[HJwهgpM ,ScEw²KSk% UF*T I|=&[B9/~1tQ*pet]kyx]"7W :R6@  4 ]= 5AB'Kp"OiTfJ͑y( L]c˷!PK\J/qڕ0pkcs12/BasicSelfIssuedNewKeyOldWithNewCACert.p12UT  ц?;7AUxUy<2ǚc9\9&&*8#UFÆ]KXִAlSZwF$cۻ>EӠ@@0 ا|%4h!;h8 ZB{ZpX/ ghɗۦ A @" 䰢pqotɎ.a}rDHf䌳=l5mm_FBU%Ot77Y2YZj'"qHm =J/=|] 2+#-UV|[rh8ԑI[J}m3Iջe6.!?\ō⸬خTl",Tt4t#qB˱7(s<_NRO#LdK9]g 2Й qX~G%8݂,Dz}\O|Y`BYOب%*[yV/Y}/d+*Nt*zS5NsXæbnSVv/XO79+ow_i32 =%LTt{JoS_k)4&2)fxQ ª_N~`tɵ͍ޜmn)Gf8Gz8g;4v_P8-bH .eJs|d؍9˫t•;R`i =0Tx A%4P9*uoI/<}B%HvSe{Ҏ F^JK1תj.{J[#X1ǧ]¡p JAE3:vGB݁;iI`Ɂ)ID􈴟׾=N5mGe.}. ,*hPQp34%[s,޾S̯bn&Gǿ%Nk L2g %4T*JKmZ_CE4_оe~vOzUlXWA~E˄Dօ>}46sv'NX`/;:I>=@/ X4h Fo'BiAeUe(ɐ~JXC/yaŸQai0 `xb< `)P,Ď `txbAI1V CPG2i0 4<3?\ JRg%0?PXC%ߑ#ds:qb1:<)E.:skuuiz1.f렸l>$K?g'n>yE}P],ڒw̹t-{14|G=6Bo U|+AX!$׮bo<`66nb Rhk  G 1Q߳;Ëȃ`5Vx9vZͽ7kH d}bU-M{,h܈4y(CXZcvfޤfUFToz#d4~k}ngfJN\](ٲ #=U˔E0uUo˛lxt @-pK=ϔʼ>";nE.Fynhh53)4[ydڵvЭ0yowP qS}RU)pYhL_ᅽO;<22멜a_nG& )[kNGOWAjOyu6-Vor "JG- ܎Sg]'W _9~&/?!bEhs׹L`>IM7~3O6çӟczVgѴhp:Mbn57ɔ'[،XS->h/﫱//;GG""Im1kF"23/"Q0B{=~LtlK 㡈#_l3tfU?3+GPHJAcd=Fb)YX*y8`ޭ*zD_{9[yzhAb q,#?w r"YX}5l U LgRWL V#Q-p@x!|NOzo:ET!`I.*zN[wGͤhn5m(/~PK\J/wP`]f0pkcs12/BasicSelfIssuedOldKeyNewWithOldCACert.p12UT ц?;7AUxUgX I ҋ -HGR"E,SBpRCJUC JБ4 D²sw{}f杙oAPI&R?re`>"@nA3 3k B-.B`AQl n]h@iTxN??a̸h.s~S8GW">&:kwfvsLjXL\V74opՅ?ʎ%LH&:M~J J9Wu,J.K 'Ѽlg-&~d٩Ζp?&*egucEaրA;qĥvrbP@ 9"u!:(* v1b[ЦuHSqgwhRȨz(s Ђ}Gi kjzNkR. ?/h9M}3YΝUHQ>y<̡MSRlw& CĂ:5b%x#q"fUR cSR~In׊[ › }G"<09DwTORҢ=ߋ"#LSn% ;$h0GPUP_ O#rLY~1'I5{Us^mF㖦,dcWr_!N~d29-S_PFyK>ۿ=|[dDUĎg5&La$ӯ[LWujlsvL5J 2I|G"naUtQ{a(4Lw7CY*tn>2 .M1:jew*n/q U>)~sG"KP<:-X}q氾;e}2= Ɛπ2 g6IP(/~Pd_3!$͵f^^4\UYz9'M_vqW‡_͹OtB^o:op%ICFP(N^51v15M 8k$P qFDjF@YN2{ΌS'd3ۺ2,Ҡno?r} C _a[=Y8s"Wɉ#v`m%{_0v@/kc]yIe޴)2RgSw_L{C.iJ=d8"`|E~Vʢ/^&w#ʫeBj +KdT3͹Kf?79>?U`*pzY5COP=dBsȧahB滋+^`㰆B)Eo .dQ < t8@ =4ni]":/= * /s=u/ rYAA4a%X'A!*&['miH8L j>I*O7FN \ӭjP r!FJ}rUX Gm&5<DFCj,-2FuFA.cd?: Xp VK`݋+Ю}Y'Ɣa3w|)rP/a ] TC;;_ҧ3懛g-gًTyfT>=FӶ2&nqnnfM!u>>UI7%Mm0>ߙӛj=ka5W7uS9gYc&f&ZFMd+ɽux5j'/!_0\\?;a;)^ ?/Xe[TAƎw% TȡC> !G NFM bloDIlD98Xx]gʓ}7~X>'2O͒N\nA]B<;@uLwe$mANC"a>f( j_K h,[mR~4Mg=sq@1naw\p{|J-Iګ\IC Ԁz =SeSC*%4ֳܨ),NFpbMҸSwBNmvz,0]~pp6('_ZMۤ&s/wO~jT&ӿ0Mkp (fQ_xER9#[W)Z'^Ot P_MMPNX3&IDM{w2~ (XX(=8QIkq8y!2>J`ASYg/~ qBA@ʾ9RouپJszIX&z1jW 1bTOǓfr+W77ڐ{U,j;NO%dՄ#7*vR]-cas?w9R5GƼ u)k|sLUk~~֍ʉW<$(zCNݒ*|ks+"kCCD"ˉ:q 6-SHDQ2;@8@`B\9ZH$/ !IAQޡfɐe :\+n8h?oPK}\J/J4pkcs12/deltaCRLCA1Cert.p12UT ц?;7AUxUwXƿ5$2-SѠd"T2nd)ȸPFAP1(#)aȐaeX,>O{{ssΏpic7 0 ;6!@0۱0`_00(O2pq Bxz}LJ,4oX=q6qW>bLVm^3gKɖ(:P c{x(kuDFK|y:BÈ,Y~ۛ&a2G,kGdqS#č)^(h n ZX}@郍8l~a>,5:1&Blhr\U(^kʠ 闅]r7sR:YGbaDBUť͎avyo\VJR+Q Wz#|uo<([ƑU4Rxr bq([dB~⧮* ~JK1LI"L&h V q%5j &v!a#P5,V<']}nd[D(XLBKtjITP4'ߊS:5'8pwRӳE)m5l{-Eumf,3\P >CR=l~ɔK!;vnEGK;q=")7 bZb_ƣ)g^t}}uFR=v  3V]Z/9B666&\uzVNgje!{x>'9,s9%Ԭ7}C+x9؍Vp{OZqJ`;jӆZwiUhd疑DcV ^Q3;53) e)k{saTw{G+4|QGB{$AɿA,*W<>U<=*$O|mfS`kٴmFgVAz|]gow}yJ+k|ِIMs8ṸuA 2RTtdx^Bv4c{x{lf[Dykx!RpcrL4)X0uv>ÞtTF %(-b6+)sHA | yr;DRϡOO+ ņOBj&0n 6k A/LDZ7!|9YRH-OФIyX@{Fof"MA@ ;uY= yJCdpGRLSI"|v0!r]Ob"'h yQrκ[FA׊y9F-I!mZec̐%oD[]C׌J?\.EyF{{go]E>w?aB7jJ~758ՠxN׃@OYS#{P#"s06նS-v5/f;jߩ'6̳PnZ7JusXua]P5|]Uqo/.]~~FM[ cP}>^ś+֩<8ֶƵ$9$9GJJ_A@9!)++@4.Gw;E.Q(J!()$wJmA%\w},_a&PK\J/9Npkcs12/deltaCRLCA2Cert.p12UT ц?;7AUxU{< v34s=!l%HdKsۆ[41KaD$C'K3en{z<~7ɀ V[Y `_ ϰOW9+g< H%B}Kق)T<%U>blug#+sC o+L[CS^, 0d` uǕK„`VZՊ6K\kV{B"kpDY!R!OոEZX-o^EՊ$ hKxȢ HLܺ4/[n\gn&:\Q2pǁ6^0l4ٓjIp吮N:` oq>՞΄DzZMND,e {,L\by뻻nYL}1eeCu$da BX0Zu~֑Oy"'xnv7s&cDdE]Dl"3O/zLiaF#.7W>x#/u1P'NMY VX wp%zƇTkgL%:ehn9!Ŏۭ=ʱ ):g]3s㨸ة.dYcE9zXQDVFzژi/UG9HlGT1IGXU$\ k S-bϮw `u舑](ty5!~C^~9gs i\02:VݳS/>2*Tiiw %B4UA O#u P=daC_Nҏ͕M>Y[ E-A=9X2皇;H;m=TTHk/(l\']lxAtD9QQoJHœ}90j|TC V_+v6*JZX ^B=#Fp_ Y_8۳% 2 }2cͺΏR _\o105)m@ g qH`io?b#g;w'mTcr1it!S8/tdt ²x%f6YJqvUxU`ȔU4rpmн_ȢZvj>7hx1`1NԙʌxVjGGzMoZ7.k$wFKE|+aldS lfgSw铫犱|QxhhĨUEkPx3]^Sa>3Lx kJQZNԚD%}(+/zͳBC KqrWܣ@źLV5ɟG(&@$DW6'&@x] jaɇZZ_>ԫo]%t&PK\J/)Ppkcs12/deltaCRLCA3Cert.p12UT ц?;7AUxUy8 2c+gڜ3b3Q($Ǹצ5q񰚵"b"%bc3},C<LKJ`:O}; @m]x2AE?!,. c%aS幄6DD ǑӚ,c FoŎ>Fc{_;7(CPb=2ҦUڢ`WIw Pƒם&+ٟgCZk-HnY,c-!FC_: fY\-@1Wy&dF\wN r} m?ֿ]*ʶy49Y&!3 .jNGׄ ^# }2IE"gС}N8fL/V YtyF6' v&n10ٷd!2A}™evCeJIòPEe2&/Qޅ60בr9S+u՗#׍N1]*$9$UrXm%}Mr:u#Rа*zjOLY= G"w1{س 3U8='eM_O=l~5*@]}ѽ~Q\s|v/fܖo4M)n0b~~eyp\2]dԡW~oڳFYQ4=D%C1'U0B14Fm<"9VwLJne1^UE΅/dҋT[FkR!ɻF)'!blI|+I(S!"᫡`]*s i9C:0NMm%ZU+γbJ^"fħ]{xli| _Q *RTGu_MOm$ _*ˈ ;5AZAdFy_1"^E| dux_84cި? ;ӝTBtML\ v-[޿#$ɂ;=ؗB[xC4Kr2a3>.ʔi)>u.c .lE+y`={TQ+I4̎[X?KV/HbaCحdˀܙ"ҏvJ\QQ]7loZO y͞K5NV-=  clȨDИͩ OULu(oؓN@՗zU(iU /@-7Ans>2t\<5>9cAQ:hQz3$z*r{]#&8ns.";'kBVLI#R NZrͼJ]!oQ xT 34&+Qp>>qr%Rj]Ď,yazYDT-3Njvpȿ26_l[_'g@%E*v寢C!l@'EXBKǎ$NpD@wEO</|sيTa?b,.Äu[SMĨĚMmP䄎BwaxSpJ?tg阮d3mz#j~?X+X:ܺ8d()jrEʨ0u/=৯x囯X&oF{-yUrqKke$|(zTj72oG~*qNRq_ken"J=MEZ%HtNDKy[ML F1H?ґ#MO\m؟$.{HHEE p5b HA(A_aP= ҋ0(וx̼˸  i;PK.\J/)뺪$pkcs12/DifferentPoliciesTest12EE.p12UT Hц?;7AUxUwXƿ >Q+C( #D@eol = a)eS!P a)Q H (d /}{ooxs{ab|e) H9̄v s{aǖ) a$A '! 4SP( ag>Pl)JFTUhv:L˩.߲1VJ7 &[XRL-RЫˎ |6x͆'gږlP kfzhҷ>T]P^3$MYq9 [[HNf(tLsS&!)$ w o|xwֵ<c6Ϭb4nݠǺMb ~)ƻ|c=S>l}GtX o"]gӾ|Tu<[8jX!&"lj D\2=5m0QyV ~-TU:z|8ۼmQS7@pu23Hz 'n^ŷp#TQTˁF%͞è =xeۚ}@sXkZ!ݿ2X|=y (d/S&Ft5qM]@5Q0sU UM~7;*qtDaF{6T|vjLT*sq~jY=Q%tk,mȋ}+֣ ED8xi /[[KͤWR'7{>t˖>|zãF:OEhvӞkskD_=9a2X-#wE6Wa%}ߙk7pq+{ǡRjJGDͰKjJxMzGĩy2Jm;モ>HDDݱ 8AD(C`Q(ƍO28J8y]h^BEnf2˨; }*-炊Ʊ;hH|nB݊r To1rUaT"́H_ {.c3_^qh9fmoswa%v+z. IN{/*_  >^bH4MCh@k屡"M X&ϧrbQ7 1+ }q4 f" [Py%柦.G}C jNң%+?.k}̽qiye&y@_sgB K?Q^)&1Ь3ټ'*yuVw'lXOsoRYCY7+}P4W23636G ڎeِ9Žv}^[V̂I>dlx+eRaP.3B׷O `1Yw"^}];72jY.WI;6OnHcT9%A{b2CO^3tw bd/my~#fa}cG;c soJ|L_g J|S]NZc [A:F_{VC.tުHD[q$`&DA|<*aPq.d&W#EO =oOjҟpć!\ĿPK&\J/W #pkcs12/DifferentPoliciesTest3EE.p12UT 8ц?;7AUxUy<ԉǿf731$?ΠF+m-j9#kr1113afDk:h䨙L9Ir}~y|{ !D 6H A)v,Di$eAA>B#X5=30E \BۈHjsio>}4R,pka%TIގa~Bƾ 6? 2nW.h/z]+ W=n_1.H2recYy~)_29 ӛ}{pod dKՂ q &FʇC7;{|ec<[X{LKF/~ݸJZj荶MҎF(pUμrn!Oovtіt7CŬFaFA_)ʲۭ/c:M3OΗBuu]dHro|:c{]㹖#ߒԍK=(}D$Q 'e]OEN?ԼFK=jBI;z]P7Tɮc !hKxs=e\ZQηȏ떽;ؿjܞ۽ Ԙqxzs/'>\EF٭|w~+i.d-JWw|jnYQKʔz"dOMa<Ґ*<(X?ZD\ Vͽ$ј@}aǖǷFۇnLєϸUFlu d܀'jNA3\M)ZAkb}Rk5;:16'cE)1N%FGVrYwbS֏ vN]YDOȴ5b2K䘱'֯_M_ b6E.Z+sD ?u+wr'4)" ϻ9)\GT5y@m)dJ8)u_2PGNM;MP5E%8Yr'k{XHqãI8o"?T9 ݸGUGSOEj MHOPV kJ K~~,=V@%%a{UGrޤQw,yv]~EtHNO%_\ҕl7]?'yޏ~6%^1qZwnEd<^"V=ϬI?6N2a̷80bȣ*1 |Z1T_` )}$J@ @p 82tBJh8L@W0XtV"B%u'PK&\J/C`#pkcs12/DifferentPoliciesTest4EE.p12UT 8ц?;7AUxU{<Ӌǿ\(r9gu2ܯq/2l5Z&%LrǒKp;?>y>y#( )0̓fg+JHQ k+hlkI!Afխ ,F˲斔}r2xvƘĭFOoh<[ZxZ*fn[McQ֦Ƴ1(ԑJBNSKWnd滯6Jf'Ly;Ab\<^؎g G2b<˻ 0a}{Vͯ[5\w9Ů߾8 viy6B>*z6Fx{(`=k);[Jd]E;)gJR֍́GV|lhT*tץHܵmDe&1&_ѻSf*`C+[RIŝ2x{J-[!g*ІpGrkZ[]h} {o~z(+8geym/Z`qCiY#y#> k?@z G(\oӐ.FƜH#/n>w0 _jfKT*[΀Cm]\lq)iPH[HYW-U_RPb#! 56/^?}^ù4U;# ye )j.QDޘp9|LuJV&%vnK2. y|=5f8`t@a|AT[/6#=Er勻M|rQudԍ>S+K)%jHEsw6 -J #1J&:\_(f9jb= CS]F3ɞn.gR7J3Xut z[lM[.~?=j|i}{HWVV|Iw.i%9G?c/DR73] Z{^LF$-%lm6>ڿlG<ĭe3  |~g]z PBWwTGهњcQsݘpʉ ]g703Ѕv8VzKG1|b=D0LIc; 6H!m3Ze%jnSXo9Mjj}e2j[뙏,5!c'TwvG$.-LP6sW##x?ݘ/YPcamΝ_{R*'E E'@U e62 ~dP;>N\-^3}'0-G})IUp9WgʱTվ+ ʛhcZ}`+$0km& բ2iuaV}"a#U{F+5L;]h}L"S"$۲HeF6턦w! hNbI?+Jt~*hɶbjي$RM/H y``x%_hPi)5 g=SM=0vKГOrK+4oG8qboY7AToY¢dl>1yZLT:65IZ5-q Slwqd&ŪY^R!3mg_yIp]xK.M&93s*FWk ]%GT+,C|Ph%~\d2@F%W]K5O̬"XG%d&XܭMp@ϷHgknLU]ļjݗU \)1y?n җO;fd9C!>Q< -~ÈEzΤ4ֹ T 6mH߾|) qܗV@C/\XSpi,#@#9 t $@4 rOg{9 A# -9Y~2ӻ|L !&4s/PK*\J/#pkcs12/DifferentPoliciesTest7EE.p12UT @ц?;7AUxUy<ԉ2aȑkrAA?WXH8"1Ⱥ23!GX/cDVdb["c0뷻z<7@/CPyU̓vb Fۅ  ^Lz[n08_@pΓ+ϺB < " 1)Jm2lpri%X{VlG5Bde0T>BT(yge&ĢYq8Lߕ}#c="e4ť~)ѻݢphWUc}[mdUW1%cJ瓶iL_%B~jrRf.(\~1+ڱ[xM*O ]wx:8~Er̶G I=nIMu=P v ↆGz=3ߺr~o41v|nuO~c1*#?A j)&4[.rkU6a;9F(<#b9_k2op;SP1ՀK7_6, _XcE#T F B‘aCIr_AMAFٝteu:[_on9:^g,DjZ-an4}q]_)ʃڛ>jU 7:+C,R{crv}՘$4*Eeu+1厞 |/*ԋ*^XF?#ej)X#O%"l2>#6رMT~:tL^tQՎ.v H:SO;!j4y*s5mss[rW8X@{Yy߼! ric^]cDS‹>PSF_Ϲ;ZON _X_V`jथ kPHd c]{_ ¹PP$&-3$#oˡxwkAw<_PK+\J/=2 #pkcs12/DifferentPoliciesTest8EE.p12UT Bц?;7AUxU{< o(փ&L4咻":sKMeі™b%ZkH9$8<9|^~ tPHß8o!:FY: C} PpP\/D g8DaB'N+AeIP@y5vYFľ8V$:hr}˝%Pljvih^eJ8~\.u]^]̈EVz 卿NPjs0,uW`'ڕpdo[GݚwJ3/w$'t?G9K,0v!Ǻ|rE!a3N~=b*w0|1ӝBxsI<Bک(>s(^十PPQ`%Nfj~7=w_ת$Jg0/Qgyj$ esE -s#9@w(;Xہ).M'XF?{'qRv}MNB֯5]VWSx?%8'_MI@w^t;#u|28ˏ{cMI'e-QK4+3ܙ\G#{y'핚=πupvDapPxnGa>.*u)gNW iv|-7jyGQhTJG(9ut M@JSMwY.Gd21Vm!{݉80̏)O~_jTlf?cuUG@2~螆7G1u?ar\fNLt񴵡K@GQ6j"HQM+"_)7n&>ڊeE||E}.j$J+?_vg ī$_WZG؛s,kI-LG׮溵9kA*{**{M4ב+ "y€@p@dAO (puQ*-$k547}oAlՕ[aB4E5|KPK,\J/ #pkcs12/DifferentPoliciesTest9EE.p12UT Dц?;7AUxUy<ԉǿs1#De^&2"ìcиBLQ0v=\u[hB$7o<&  Vmu{t TLAIpʉ}M '  <@p+m-U s $O"=k=qvz}ż q =|?Z\|V_Ӫ1t?-9372vNIFy{/z$ ӿQ0``1*>;Bw)͡T6Tڇ]nNWiYdT1ócz'ք\?oVY?$ªcc`$Ci$Q`S47Jm um6mslQ.4NZe y;j%?cC[ŝ ;pZrWe[}^ܸ|b{]JԎ]v~75^(;Do~V’}yUwfn6, a r4qQ)M[۹(shn_dR+ H^^ ^i-o*\v՞+ <.5?`nhd:$N6}ށg+_eO9:5T&oMXN~…M^s.û1ە27.=fE &SQ=JInvg qNjA^!4~ kbQ⃲IuNV- lx`;F6jv&X\;?XsH_WÏصH{Ah72B,+c$y¿IESs,)P0"̛L@nU l}{ HlG UiL)RXAo;Ԩj-9)]yڒ[Aq{5 #CdkJ;jS)gzd\☗n (D|l4F~}w{{AɈO~kWJ6XHB0CdSmS K+{%Xaf)ol18纳잌FϜ)t#"jger FC(aK.CeWYq~Yz[LK*:Q@!KvI?*x44Fs$DJvL܉I@ˣ05X@EGݦ6.sݾ|ܟ^T,( PKj\J/4~#pkcs12/distributionPoint1CACert.p12UT ц?;7AUxUi8ۉƳ5rLФc=AUJ-M2LS2f,RA6jŴ։KUAZby{>D/ %"7YY`90@\{%kP=H8?AR!syS}]@ZDOML6y*d %u ٭Lb5%ƾ|с.X/L<&Gō'>d'._w;s%dJX1"`s<˖[FL;A8yW;)^ww({8 _s6iI̙6G@%˿WƲ^P0V- h˽HCjeS}~?;0KdSszV m؋0ZeYO[yOӏ̸JI ?a :\!OfQB9j~xLvZvc/jm=LVhj߹4?ʬ5d,:qc0x۪ sn(Ԕ6vY{t}E{0klGTqlp^?:/M}e"_tUpeƄaGC4$?6>ۚjgՂ@)wgX{߲qWQiZ.|OJ0dh={!# 5$R7ҵI |KeQ7hR3.ϽP;ޖuR9wYC;vg!TKՇ}]kDZeGBwZ=2&l;Bidis9#Ed+'uG>BFcᩀ LErC9߻~ pN09qݭ tZt\@p%@~ \a5H̔*SEN)bƕD4a?##1UP u"ǻk`5<.zqZ&!: ^l}Y =c?m}e|)A}SMVʃRMR&[7 AnOvI?_HRW@ _4ϣOOqSݠ/ hu{H K7jwu$Uq?84V$DbO-?y}۞h3+G-O7~),5K5ȯwBzQ !.$"9^ZN,7U#&ϳYF4"f%.SFr1?$tKt }Nb [\;^=D"u&kh@$}btׇ H$y` Z[S3`{Ck0d?PKl\J/a5H#pkcs12/distributionPoint2CACert.p12UT ц?;7AUxUy8?IVrMRFYjIU4D[(Cw¤}jBbEKPӊjRZb+mjp{syy;?,x!\]i1;,x2qdǃ,ſV;,Ցe *p D &љLA k1m=ER3-' .Ѯ<&a"ݓO/ %'/_jii/N@#~:@s'Cc`CZq7<̝ڼn8 42PJo{>Z$-lf~ }jY2h&Joy DorR ) q/1c%刿̊fήن@)L& @"ϬԳ^⸽nuFgF7`Mx$u;n9, sL9T海 :STGB|f/kHʻ[ hyA>;ѻs.u0gYxZ젧HiS +sALF_U 'TZQa+`زϟ<;%]c?{cOQ{:7n9mXGZf wF)=[3k1FbqZ`\)\)ʰZK͊yU yfY R,}h,mC0÷m0<ՋD<8ۨ*0͏#6ҧbƅ?gi!vשPmS4+T;?-IDTMn*Jmx*6+a/9Wq'cp;O|F{\ t ɃRcwq7dˤhb{kϛA콶zY( ul,5,Sܯ>GoAQ0đ-s$)1aA~YIqZNO`,@;fڎ\ޓ _?-FH6]򗘳Խj$jNo(W.hܙ2nf7[Eooy-}6ܠQy [B/>_V?j 1b+= 26@ uo}V֟)o bͿIuZrj(wnd+:kv\p3V$z6D%yNRʚPzlT\;E`Zq (6`V.k\5B]5JFio oQiQf _-!oC(@bڱ91Is,P# h4  |w  %Q.^a׸׺@S:=ao-y'nefs#^@zVj+A#zi&zIF\ċ;/Ͳnp,r,&X5Oի;P%<:tUи^AU| Q#˕"}{q  1lhOV9?|K?*pgxঠnYRt4c̽o~=LL>B49Y:e SRd֤tȯ+1Loc@f|H,3M&?݋b΍kUw QVPm}!`$ )*4T7Ri( B%l.-;<wN$a\w)*f3DXTv?fk9BkK?xEjR1q,ᷘuc:6H|l2JqTUI%s|#q9##;^~T=vM(Ҥ c =U٫ Rmd ,D^!,qm}i757gsatz_fFr0`ūThB?P>7SQ>+>M*4i9mticjq=j LY'FT;,J]olʠDK;'~z]WCy7ֽvY^mvDf͇{ؕ5`eE 3[d=OLaVQѹ^KZci֘,Piv]f:c__91k{T n f=m/7N .v"P߰eEW<3ҷpfr)sv[ muuszSGrcKdDpZtֶ ·E |/+gЛBHXSp7^.UdS(lmLC\،;6y |HZŷi"ͮ{v!g 2S K:%?zK~ؗ]*Sr ߦ{|):b^p^Oӡ/ r8ֆukXJ(J]Q=(#ڼҡT_M^œNX/}~=UH?N=1g"|kQQ AB"a@T&Lڂ &{ bӱsaݘ|*,0$yVL6)›HnYvzi}n0&MeNk:^8>Gɏޗfyl{Hv5Q[{C#Lav'4muW}\lNg13!`a^c(?PO7CMvRpk  opе៹Ϩ @F6( 2 ?l۲ _lve p%/ ijY'Ħ~ &EC}]j0J~ydȵux!Ly~o*o2YڕZ- ]/96 @peYqPB?ˋJ'U["+d NۗN\YXtU.[b_(,Gڍ\x6~FItFh1O{y5;Nѹ khf:s={4 .} \7?Un~"{xٻk3ܛ7.׈,VTXiOi>уS)ʔa;hc4#Y<%7:{c/; Jtoh>NrX3mG\-֢EDv{÷dB"eP|F_yѫrwgTu2ԳQpє1[O9a>3pd(J trflNfIHsǃ]HO":,i8mc#oT {N/^Mzx}l@ti`L떪`axD4֊2Mh+4An{3;;2Hj&^%Z_= -0~;|yd]PE7{9Mɥ{iw-M3:v -RJPE!7ؕ;|폘zl*&)Zhjn @3}I@$# 6Ԭz4Zl.;su/PK&\J/pkcs12/GoodsubCACert.p12UT 8ц?;7AUxUy8ƿ," AZBjJZ*tT,56BK(Ie&3ZSCE"SۍvZK*Dji)z{syy;?B` =BWp@ܤ#tm0Vt˞u @]Ȉ&IP(ȣÐ0*#q]7/갿9)~S;xdUedSHAXNt{lKevޣVANYsG* |y[Ab)8 zLhpT KZ2MfQvSB/6:w,< pijIiFmY/MKuJVYsanW ?*W^}tY](]C9lHr&07 u,3?ʷ|6̜e+\,';fAF\R;ڰTx`8O橳r VӞ^4^~q3dh> : zunF*[YTͭ,/-h5J#3Փ  7RyjbpkޡkN.,!`pfX.&V!) _vl[ak} }XL|wev+]g.Ϛ`?=EIщcc>Ǟx9-D=(F`ylv D雚Ɇ1i"fN8Ė*j01Ak:~%tt$M苔D]Hq4XKL \攳4T TF*KǢu~_udF&wrZaΖposmXxfcSZB>Lk_]}xy!tx{=8 Tl=) <zڿ.F.8-rko >ݎa8v Uf @G"VOtduNmTz__FU/ڽ\6pNۭvO1*.GB@L˓2%b: N_S%e7bIb LӣIYvAwxN.,g$׵ > l`dHUfP{{k\Ckܛą>w0LuI1ۢtk8K1F1k!($CM3:Udh(~ b,KC~&Z\05^0sJmՅP+DW;O0}r54 Bj;ݜ9[|0K݈z_sfT5 &ANLAYFsgb9=Btb=:!TeUqP Ju/"oF;t%A+kZ똱ܔ:۠("ԑXqG)SWBNT(\Ivƕ ^$\,NdRNq{ٍO5Y0h; cn~;tZNWH-f {ѓ_Gjx==]w S4ד@ CȘaPm0!ՠgr \Vh7 PKD\J/TR?e/pkcs12/GoodsubCAPanyPolicyMapping1to2CACert.p12UT pц?;7AUxUy8 m҈dɞ-(lW&37Sila,Cܲe.#C֤uM,ȾFPt!ېys|;v @5IoB@4D3߷9 "-2엟/"3@\a2et bi07. ci| yZch\S |u4zU:Q葻avضk@\UDZݭt+ݣv,Wg[Dj9gSi;2Sk1&̎xqv ̧Hq[YRN噂s 'T5x1Ձ8sup]U/6Le \r9+`3^`wjV)zȎ F{TxgP4ɊůCrQKXB浕xV:ޡshY ]Klfn20!}&\v-3>ӪG?ںч;IWgX-&~ !ܸnQeʳH>TO_d(t<ĄHNap cqQۦU\~&vȔ=JN >X3c?xc#"|Af8vX}3zLr*lE R7jdeZf#,~ C{}z̮b{<6+ܪiHfxzW Om}1YuhI.v%Z?I{2w#+yh5w'_,E xwYdWY0^BLpΩ7NkfW =[v`{eS;!DO,KDaOx5\TfAj*BdU V%(ü U|YP1%Mv{ʛ%$a2@\*!BV\AwE)L NmԾOeҠE Z/*aߩ LON%%%~q*Sǒ/H]idmO%pW lz_dg1xDՏ*D Oڬ‡7r6|Z|7!ilA Olf Kq~ծSys|@Ym$ᑹϧ]b鉩u Ԑ\xEe0d:~y'J벵7ˣ85]Iv:QAxCgvtuj" X "A/YU(IDE!wqnWnjKr>7~[0Rcwl+ 6"znZE]+b0 j dG\Fq҈Kf[;TvREASQn)4੔/c7L47+bK̩qqPڒIB|#VzbI֦ۆlxP_<+ 8t_W*>YWm)ϑ,(p2"DhGDe^hco9 b/\c(0P(7PKu\J/bpkcs12/indirectCRLCA1Cert.p12UT ц?;7AUxUi8ۉ%-Z+ҐtZ4N*TUIqASJm,\-Q%Lbkkd:A">̝;~;?4wPq @oّhVbeGEBh%_C뛄X=)0XH/nlo ðQ'~fW卪>oi⡖H̰J©0W+?QEA&˯ĕZg%}~ɲv8dTh$-pwk,.t`d,C|;z^(̼_\j鿐JՎN#:~SvwCx>x*/qӾtovrIlh%<͜9kobA11oc0 ]Ft .W2 ot-|8Fs]xJsjLO0nhf% iy1h):[[XӣeCi̴c` Q(i8p˜LYє\YoEGN*Ǥ_R65NA#mqFG "-o,HQO } VitD859^ "`TKv=N_7=b۫aQ.Z_ܙ"3[]uZN\9XT "&^YGE_JDrW Ք̛ '_s}CE5pV.Qb_%WeU:T.J gG*&fhӽ9q dz؅c5֚ϧT1Lž I9K$Oc1XKjt2v\SȈSPavʝ.#`4EB> (\LW)Q%*{txBNMf}p8Xܘo*8cJإ Im\B}@|N+l 3?e~T4&5/DZ,~r=M8*$xeW˾,/GgO ?75־NccC8jy$4K}ikq+ㅪS+`kݣL/~ƿx44)ΞEla )jKcVʢzeuwL0;.} ˖v', Oup_ u3}`6]=Q33ڋ3mB rev, 1SʨԲW8!;NUkGzbkr%92KD ;>k1@oy씇PmalqF +ߒ/H d5"*n_g .Iէ\߽y2e.H'9 ޜۙUW.*>S̮- }]I7sXD2&7ɢ47ncwIk!]o!gJCUɟo͂'wkS MUiJz!8o>htxB8W }:QqZ ZD8Df %_1np] ϑn'sQCE:p i/dՕ<%Dx d֦"\=x'PKv\J/'4Xpkcs12/indirectCRLCA2Cert.p12UT ц?;7AUxUy8 3ˬ"1x瘘T w2& (q9ZP}dW ȸby}Z0A%Z g6DahXrPa{a UAYpWtP" PYm LLY OMFqu-F3iTHĵGF^7vK,iߴ\Di1JR*7%0Ry@e/IjzRӊH'\w^.dC5!`^r%vϢw%d ӇC߬WֿD wg&O~ y]DpnLȘe4ި;NuoZ)<}'%7&;]JHhq+u31>-B덵Տ $bvۧɩ3ѮHxX)v̗;H<s (,zqu_Tws~{C9[4<)s)x#mpÆ&Լ8IrB{ܚw0$2hzt;ݑ:\80p=J@np9-cfRVwXi: 죈7tXH+4t>ԾeTFJ ``{nw ?[SbY/Vio' |*9&]MR3fDXUߵSJB~-JC`n)SvoF}^ce"kh(ibTe[)Gڎ]F!d@g  ^ā T!NMO@<+S߿B& 5SϮu_I`%H&—},lC>72YyPP12ˌ/jX/yzj[~8?Z5mwAEƣ7)+]GTj4(uRKvBVE i{$Xa2@` X{*zwa|TaĹ|Qδg+}#PYgzXlc+~OeEYsC K& GD`}s!'xF(nNfwT'F('zon\,^fPtB^VDPȂ6bkL~)nC拯>mjBZGKI'^gG8[ K<6z^R.Nj4Ŭ:~[S~sq,dh5IvU&bҿ8,IХdREPx[Xo @$P5k2wq%}_N(X2ѡ7z>2s,?N ݪm}~!կW͜cU`;!&39}┻.1dA'˅Y`D®6;mZغ'`p*LcFHT/>J( -P Uff NR2"Aů:jG]mӝh6<`/G)%<|8 SV%r]uyz|UM-4w7&o~Έ= VF|5TKg뒾,.;KPjH;/oDKi~+eӦ$*{QIsBqOبT?ēDɐ˻Un{6`(*\$Xxk;*8?tl .-ps7ID64F l"Ji!uFlljs-),3iG]:-{r&J2^P%W>!ӉpcPѤ#͗^HRLNŪ=Cö6}xx)*dRt@md®N̈RB֋qUĚX߼-+9?YjEJ .븒`^8:>.>㲌T+'Ō{~Ne?[Mg|c7ᧇ1oPd`ND.uAwWn+Wn$7.=RrG(@ g az % ޚA?)z}kUwZK o*W˂IfKf3:W+jZk L:12>(q+ٟGHkCC}H\h |'`,0EPLՕ nm]i㺦giJIG}C PKx\J/ÓH$.&pkcs12/indirectCRLCA3cRLIssuerCert.p12UT ц?;7AUxUw<ۉǿI$DjTZ48A"jĞ%ZU5VQ{jr8SROu3s~=o,A$. я9`1($  ܞǒ `rnAyee`U"0T3$5'[껂R#f\a϶nb/6CYtb,}eN|:GznÀGHϻ/T>X֠'~ ErϗJ 0: ĩZ " U7=,<3{Z9a{@Xhh`_ҁtEgI%ՌJb⽫/Q)7BwqGsuj8-1MBդ9Z+DZ߹{pm<-M`TjJ#P_pYzY\n%E8eEZp^i4x'#`HBE5""V_fF 5X{QYp1BQt,8/B>jmoulSV \{hM<_Eezrn+_4Ȕ&ּ7=%@vZt oP |xG9ÞyO1mdXIeTyshQO$|iWnĖfs76r%Z;.qhL˚u\OI}UJJ?G=2( 햍 -[CŎ`Xzs}4p U6x&fR٩6Ɓ؁<͢ѩ~0%c5L+Dx[2:%R=y6虪Ż.gSG)fOfzex P ,p>)NٹJgJҊ wk^wҷ!ħiZ[-~3`U[hg1gtu|cQjV^ea# |T*<)"!Y1d|65:VQh72Iu/)e~e|NLĕZשWwNX(mBWic-;C<(BAKEìOƛ#._nŤu1meCՙ /?A.[4]|3ٴ`gфj|&+5.ϲ,F>pUH_LpqlQMyX2N,NŬ"-&qǧ~vdhXFZL:!!mU1ǛZ7hdkH?MߗuڊZ`Ej8,F ?OWza)B&@0 h. 8.Xi0JBPySeo~3M1,xOowWPKy\J/ jKpkcs12/indirectCRLCA4Cert.p12UT ц?;7AUxUw<ۉ# jU[Dm"Q) 5:HR:șBVдuk5vIkmQi9rny=yMZ4p ږ@ R}gP F>X_B(mn^a Tj?}\.oMxN'ĻP~Bf\i}E${L2TU[NüYoX2'_}LYSp\D@a ߻@Rr E+wrn/ت|Ut$u2SJ[MƩ4H߉3CKNNfמH"Y g72giJ6ʷ2 1s͞ (ªQ2@Jzx׼y;:_`/w}J^TB<_]E@;۹&$]? k42]+_nQ|oSӓ^&|P[7lE7qpZIJRϝA6:zvjӆn˂JƼ/9mߏJ#O,u c-75^2܋%vYr]52~8f`rw& x˅\.}AXIzeNbT4ZTZǯ).EqNӌZAbinT0(uwTtKԵ¡}. o/\j4X⥓V_#}fhm SYVmrԍx͹'dT[I_tᓐ.bWuCIYLW+ǍlhTSv;R47L}Ӌ*(-̲ i(KSk'bN7dDU>0 "@$m}!AK(h  Qrw=Y/p樓)mNc]=k L}f®YH×(떲`lAwƃ>j&1طU?fm$>l& Ӑ&U'I*M> mUm2hL5Qx}ʡhV<ڟquuM5)N Tr]}ެ=ga66AG$SE 3ԎXB 8VB#7s QXv" zHj),(5ꐦԁ/4+<+U_,ISYs‰ È+ TS~B0>YMK5‰'!UgafGJi :!JDqB;j"YC\m^68pTם172 g>-XǾeU[?|Bs&78W CC{6خ+GTNlszC77Llߞ@̏Rjw^_3Njb"n*h%c'n5xyJЁ7D9SR4Mzf&b12^R 6fT+̨iCMӠA`E 4ڮ  !"4,1X4вQ:,,e~nCk?7`blGQlf}uO}WݝK*ǔn·~IcaVфG1]^S$q`UwQ]Aֵ4 <<W"6y1P[_;yc6s3_92*+-*k+mgCn8-]4h5j:\7W`?h1jT:L,~0ӇP-hs~.PKS/Q{79EgIOII1 ˍQm ioۖ*Yh?h@һĮ`1!.,i=Rk_ӀuVGK ó[mlגa"ة}wϘn«Њ';ꅺک=E[VALRts5xTAxCPoQ>gY#plKhxMmAe!MeԦnz_LD$@l?\"r;%{|n*(^P`z%vkÂO<_l!·5ai#]Rƭ( M5{d 2HSn8q U3&k2 Ph@0̮}ZE!A@EQX]ts-J = ۛџPKz\J/pkcs12/indirectCRLCA5Cert.p12UT ц?;7AUxUy8ƿK"%H#MKڃ5Cj(0 b)b2:mRQU[-2*Rm<Ͻw>#PHf#2kΖ,D RFEfZ!J}$ ,C%yCH !.E\1O c86fᜦ#B|kf6=Sji&&Zv>ГPĒ\i&{ h-\}L_ʞL,arKzh~dե4wPZV,tT "poXol>_%_(qn fT& F6 #n +%&y^דӆ7 rG1\HX0t^\w,o}-NZvsS8#s=tpgmP;iID(|1Gu3{䕥+J:8w~^ s[tvVK蘆0O>gp-iD,gJ^X^&FSnct=Hoj{^:qNn" ~abQd-orv%H_ksuE6i{/f5xXDNJQ6@ é |>p\v^ԓ)Rͱ u{S1(FX2lP0S>xTdNc󉵃K E:Iy_q<.P0ܚƧĝ~{ihBEG=FR!+m[CfGn4NLI^V^^Sͫ\4\&=߉_B!) `UcqK9L7S~s;t S7S #dΔw-dAertKvcP\Vb4De^.ɒ\c] 3-Njh,} 7m\VmHIpTa ̃#{漊գnE#>mQ5G2v)q@b"Sy"kx)YT+.cWO mf]w5/;yMN}'n|}jcl^{Ӣ9hZt.N?= vGkwU-.0]F#w"8plIgĄi߿d`M"뵱ȍ'٪v`FzrѢz. ş)cu2 \2Q+eŇѡ~ AF溄GYV&`XeVWA a3\IJ:Fqhs^޵´a.9UX H?_IHn}IqL߮ST9;{2Ls:wMJr(=B~U29Ld['{.|j(hU^5FGbgi| r r(39N`\xJ!VngFʆ.d}5!dJiJFaloY|!$udH  T"@_>}#(\WL {2 "0wag0dX:#PKz\J/ &pkcs12/indirectCRLCA6Cert.p12UT ц?;7AUxUi8ۉY&ڒ!Ծfj(cMB0HQKPI-ciRDjmZ4VM[+A-}TMf:C\<ޙ>Ḱv02`-qQ Kra6Dž^\ɡeE!&A I@ -0\B>+Or(f}B]$쮐k9bjl>{x>%ʧ3&<8W'gru~aZ btkGEmR|4 o޷\pu|X%2 X ܌InDa]7jC_Eyn~ eO3P3 ؝!֬{~FXCpD'fhE+4IۢxX΍w3ﶴ+y>d`#6iL*kam9݁ٹ}a 4@NKGGb6hˁBF4& Wd}or 4}+Տc&IO}?IST - #,o /&x9Z+r€C=7jpJliBV@$46Gx3>:ڮq4WCCjw'c]=d'9B=W6@k)` {\4V|*Mxʙg^埋u[j9wƩwԖ)T*+EmNC)3wIYTF@@#ᮜR/ #J4oݦ$!>/FN41_oߍ+thkm{)eU]LrwkK3B*vՙD$n;LMlQ @k;<2=Y 2\g߉?8F_APP.DЖ<(L|.*_T  ˿rWY@=ozbo|.q7bd8B0S{6pOf%rǞũ>m0A+TN!ny#ٖo?vow)ZL5%gTtI#5j1v9ȳ", -W\座N&ȵ,"F!FL\?j։~K?Gr =iUމTצR c$ lZrkAyXrj4g)dg{Y&+e7ϝP.XJQQΫ{T㽗8(T~Nҟnh9믩; c[JʨknQl\9s?wN8~g?oo}MFqERCc_ҟqg$, ×$^ :M骠`\'7Meq=|.w-(CrۣE~K)DgV@GT\4R]QfQUەPrs˅b˙3+Aq=C7߳eŦJR{ȍJJl >8QuJ:ڔV^#[VΝc=,y6J;GW59x N_#Q<E20,^I 82`08} ;++ȪrzG=oWk&qmPKO\J/`"pkcs12/inhibitAnyPolicy0CACert.p12UT ц?;7AUxUi8ۉYDk5ibѦJDk+a“W+)ZK]d(jVPf;1s;~;?4A &LsL (~f@"^ E!?>ouNU$70$3 ~o- E UJFBgm$j+87ŜCq31U\ÿD&뢻gcnŬn"Mf MMviNX!RGuS!K=kB{D ja o+nJ]q5錘H V\n3j%޹AQ9Ey{׊|@ȃFw7I0R^9C.rC2ŊZJÝ.{?o.5Nŭִ[V35zE`W O|/ٺ_xjf>lQ5\VOni0^Hj/ntz9*EBJ-D:h[Lػ"P}'Ca_Fc2ョUl >luܑh>&$)PN/\)yԖBgI 4`EUy1WdJS)wkԫD~dW.}MHϑ1!dD([3aڸ]G'Vbv4Ȫ3 琑 lF5 )J!}pROAKCe߇}5c,օYI̮DaWe_TLݜg=F9 ]7zZ&wIڪ#Ho}CLÈuaUBnF>P@ BH_VsL+C/1mMYFv?m㤭h_3`\@)7ܡ&mj~f\ &A4?6ᒎ䱥uLxG2lU0?7x7{[l9=ӱ*3G|2/,:Nzl[-^Y8y4 Y=?ܞu+|>cjF}sNqOo =zO$e ◔0g}n4c'#4ܵ Ws: w]kߌX tD!v0ar*i(}4iVM7:x~=+.Dz`!2Mg+=Yh C'\tJW=KIQ3rwU1ɽ}6+cĈQr] Z62&_Ynh^iLFӳicDaxLL{{fš5 E}9n{=K!XBpCC<(J gF)ʕ}V0X䕚 嬨2>D3ט^>YZiQCp7zDog2Bru 03+:´"1$B`RD哗K=)?jdq'iԟ:QJ[fgVqEMwQg~:2F8`G *-4KY7]U )l_5تU3ogx76&WH avNtC@!w6!θ~u$c#**6'/(;uPu?j:1{hQ}$-19UI#`O P &8ՖybsBt5_V2K6u u{ 2럼^VA|(v,̵-s?2*m,ڊ7,p#qi3\%+tCv%~̣.,!{ѥ'-Xk1ۗUo;pn>߻t༶kw'oKu4C:J~^DBhx6RidYh3w6O]!/D#"v[85E\['l|_VGJv חLK﫹O"Pu\S.PD6$  69F۹Wx30l5U!8ʗ86./6䰑gRպK#T7Rvj0ýAYd@D /~x1Wv+Q[ޭQ3$QՍI,pӰpUzۉ*Vem ,ҏܧ&pl UwLy6,L^<[蘽V_-ݜ{/y9ԙ<@zN*qxxVTVMÏNїZ6&k~c8=ܪNeÖ)c9y@/C.XVRg]Ykl:#k+,c@cZڋoJnܼ$ Hsey[qvuOB?I f}bknbY|? L؛VN׻ KӍ!5XU?sνmilE樂AL؝h&/頮I !@kjJ?N09@@8^f׮4":ǤlbxsUHƂ&)?խm#w{MEK kϑC_0>% C"3,5ɼ`1*p 0u.e_{CtA#G(J<2MLuyNk mVjdMOϾ{]=l>ӵ:!bսs *D=90m 8yQYjV!-yݎ4g{Sҿ>Dt13KMHP]JJw S05I:O{6eKS͜&f=F45)ʍvmׁY{MX,Jܓ$vAkc)h)`<<+H:U. e9z7e"z`줗˺?-9a|%vO&}ku|t,6TrR?pKPÎ qBš33qf,Ł3x8zw,.YwzZ`(;VP[CNʞ(2]ծOBy3D|`42+1}ޓ]I@t bv%CF^d1gE/+G;EaFA kGw$jf Lxިp6(q{#2 Eu939{G|))ՉЧZPPԎka5YҜT~0N__-{ WՍvSɓc jT6뿃HS\h@ (r rPao"aF W-c_s0uypNkgPKU\J/( 0pkcs12/inhibitAnyPolicy1SelfIssuedsubCA2Cert.p12UT ц?;7AUxUy8ԋ'X2C&: BdmеwPa; c 1r%1)d߷)c{=|}(`?Q|lY,[ ))p pl(0ǿV`fvl]BrB84Ap7C8gP(A %j3l㋏=?^-jo*f.~>pEu]EߥUUQ&BaM=Ɯ_W5.~\a1k$ݑ0 H YxDBӼDVM,衂8Ѽr?⦜o__&W8وdEDو-9e-{8s2],=tp߰VzeN>;ybA{,3!bR/Tmǥ)|rKp!L JCnii`fXif"ʦ =u9hZΛ ҉NwOd+vuEsڥ{2*:B .yzXTo`uB5]#0/h/0+~ՇEɷJw5kKүFWuud`ФZr242/St%҅yfYift%*+NONkSWǔK9ldwKgt+Ey|Joo<觿QS`cʼn-@ph(Ica'ep 4Qڨ/?G1N MD2_ZFo#-cYK*mz< ~jަi<|Z SJKGxطROa %;`"gY{ +ٚ?H.}bNź!^"yzs.S_Зܾ+[2-jiج\sz$R۔ #ZSYrA@oM' kS3i/ r znP:gqZ9Ĭ_Dߧb% Sq9?-rT%-6<׸TQ)}-~): YUWD}{K"EMF]nîܔPߺњMpR{̺H~PVnJ9=P&e CJʖz40)Wp#8y- ^*^/eFz;pOt/xq_Lrq,}s~IЫhxKKVe[#&q&Of2ɞ?+X>BoP{*<uޗuhw?L:c#1zf'j]'zy!qiDlˎ%0E\švv7DRndYL.[8Ʈ_,oUŔ(_{{tvrC7F + rx7-uIbfy>yc@ Ёġ[`qpHс]CI<:~ײAB5@?4$Fwѡ{XNiĈ.n6 bL},LwʄˌKq^)) ![k>(nd_9g0ӦQ:wCT|"BSa3gU֒@i$ .*r /ycD%#S\I<3[w1ᔮhyS?LiR hQEKaW3"zٱ _-z05d5(lߔ[kz+6[]o~F"nQmBlɧX><*7d.J]?Bh |WSu5dؼׯV!\ݓ`+!fcNX#Uk< &ߞ̊գ33_#aE=,u]{ʇR~ƒO)ake\%czň"+szg N TԪFm={M;Y`VY{5gЍ+!ksb\%57^M,,v2LxNŔ(fcqՑX/SbB !.2:l`]vP*|fm/x~'P+'BퟕhÐLlڀ|f2x3f:(|AE[g&x:֏c_&O\hSI@ gEnnjͧq#: 6D{իO>OHJ FNRWG7^+Frཕdޢ9Jd|K`_\p.@?:2ߵJ /N`HRC Eoʀ;KM}4GIWMMDn}*$ӦI`1"nk%^y^0DC`78@^zi]vcifIH0`ĈS.觠(hwϲ7 N^an71 ql(z$A:kqw8L1iJWC"'>{dK̯MSlstxUg҃$RIei>.g8g3&VShiSUeբŝE9M,YF:?K*'?}Xfx8Cq%7g}y jlm֞KU>U__J f=d&3B<uNp'YXim_sJ˚`ޏu&4ɡ>"/PHՅ'&S#lHbrSYV.]MT.r't6쳾|mӄh 'bs~]m6?pE7`DS, hQ>&`aL7^-S{vԨ4xMn9Dg\w_TOhOlQD_䘚61{yd}o2{BT@*°)98u>И?T[p3#߱5][L@Ag> ݆$ؤXnT'5(,_Xg #S]Gccnv^LrkD5-7̛;J"onŊF@6@bb& AX}_ZˉQmE%e5ifե5ғ2Bm#+>+Svn SeL9yW6*Zf 0뵭xKiBސ,:9ļ ].H!4BʀNc_Qg¿]qp :ފdf͙ǫ` U)jכ?^C+7c2wz+tP8΄CP]]+gOu_GӴ]elF8Zs[]ӦD'(u\ ~[~*?wfz Jy|]H~uSvC956eD쬃^' 3ؓ*;fy67'ƻ33%'x ۧj\V<_3k阵{`Nk~5sHDc޼;f1Ry;}'3hCN31q᫬o^#'-"=q}{#6/^>&!Ro8QniZp EL I7r]RmZ^^\6F*?KZ0.f'! qq?Q'MQ+drh Wt<rCqaʁ:.9bpW˭>?&XVh 1wrsOQ_%k~#ZK,㿒vX!+0ˋ/ I!Cb!k?$  9 G *wLVJ-q؝{#q:)pCPKT\J/M,)pkcs12/inhibitAnyPolicy1subsubCA2Cert.p12UT ц?;7AUxUy<ԉǿs5&b8 10dhې\Mku qFreY第59ʶ` 6qDHV~?>y>y4(i*(6! )!4=;Y!i0={B2BAQpK܃W@H m3K'$ֵBh5c]&!SBʦU;9`a68]}9c)X:,=[:q.t M $0p!PG9)]llCT^I:?ӾP&|:&: {L*рzp\OrØH5fD`ǤƑ sq5M+l*Yyq)S'ћun&eQэ*Q3K]0eHW7Rp[ezfm"oK\ ,O@b ʁ3"Z^VbmTXr.]OtEp?ciÄOIn ]72k:EHN!r.d{bE҈hEi"^wGn|{nַ <$)ɾ6d_= C=+gPْ:Hݼ1C[W\' LONQW6]"J bȫiP͢%NyON=WO(af7ne}`'4_%ި{ݚOX<6~3|vco_(o_quX>b>wA{v=ߎ| Nٹoϛ1ݫ!A"eW5A/gjK1:;fdNunC朗 ! 뙳3^/Ë~X[ i<|Q{S0YZozej3¦97% ~oJs#K/fWXRVNor8o[ڞ~&iE:¨q  C(?PJ/Zŷ2F1>m*yd:l ۓXX8~8ЀU%Q@Z9)_IF$.i+Y+|bx{oྋ6h^*7#-}Hqs,\/[ݾRA>ծB/gԫ#UZӈ?b,9aEŵIo}?p6 hwJdl&C3wtD*s#a_ruBAo$/*zmE˩1 rھPh*P-޺+Lm٪ߍ,2;ב8/?1vگ!Ee6 NI2*kg=?G2ʀ@<\ pO~^(BD*p NI+eKZ8ET. PKQ\J/T F"pkcs12/inhibitAnyPolicy5CACert.p12UT ц?;7AUxUy8?I$]R%*Dt.QZ0-]bZjIGj*Ӣ*bUJgC <Ͻw>#Ep6ˎ頄D/} P}˿/DR#3Ye{k^4B0"ޓl}I(sf 5!ZEDLdSc#Ӿe*\p ~߃ӡs;Jj<Xcs%D9!Cm6 S-ԏ~mlF4̃fyXJ&DHGa(gsm5MdfXxZ``0ogG͇c+>YU/vR rvQCP+Z4K7YB'>_021dمX}gk0Ic&͜a[dJ_,[0 휦QI ;<%\{"9g[K{}Y9<2ٙvԷyv`w/4r=jC7qWE)7E3g FJ!쑱,Sƞ@h2chF( 7Aj:DqK4B` o /fH H)'NS!zYsOS)g- VzO`r~DyAVz}U;p~ N4f&N Wvid4%زS_,X<Y.~[C=0}eE>Mi% i ;6|*.,6e, tgmiqOe\O`Fl9K 'oRlioФC %LŚJfmYhJkyHO5sXʹ_32V$U躷PrTmQY#_=K3pʡ͠:+#yľΪ ]aj^j |DؖP|hچw&?mO pc9wz-J2?0»\%ڈ#^_n3jU!q!wey_,8:>PWyB]M>M ^pHbE(NfƝTPlS*_kݶ{sz/{u'Ux)v 1Z_j?NxRgJ֤.i~z* zY#:sʂ,JC175 C?lE* UF=_S)-hmp^+_?n+D!DKy :̽@"}b/h@u\uH$5.I8(I0LY\ -ť-2қ>V9 np揟w7PKR\J/糳%pkcs12/inhibitAnyPolicy5subCACert.p12UT ц?;7AUxUy8ƿ,Vb zSNc ZұTmcP[ciUE)j6h;J<Ͻw>#Ak8 APȲe) CGB`O@[48 / A a D?.&h BR>!9VAG\@. lZt*unNIuaœGSsCIL=9JݑS; (} xM+B.sjLZW3KL٧V.v3IlΒH췖7)RO U;*hshn'QBl%={deiR}/l67%`ŲqF!\uB'O-7`Zή_5љ*ԏv^++-ILAx5*9*v6!:(lyL>¡{ 1JEdU\%w&x"3% iB\W7_( -B㙻21AA珥L!(SxvkBGVsgU&>ٍ,/)8X/! ~SkG lϤ-v6FOk>]NR ͉zkƺ &bZ FEƺMt(&ՍNMVUw\:=*>1"1XyݤL-0S$#3=;ʄs/xc&CߗsWxj:x*nN3ۘ298Ygѐ#mZjBrW&ddF*lYk/V݈lzm8[G[v55y1*5U=r-|: Hݷeu<_`p AP0GIuH^VC|)yъm478FlwK*ӏvM`uyjH/1{Ō|z4ᙢD%?S&K?XwzB኷;&q$Ogo-I DnRmjAl _~W e]9}Wm+zy*|| <"}R1p2; 6cCkЉaڄ~x~B3^S3O_ZM+y1ӹb e4Mn}!;s+':[ijd#zKH0,'O&QX) AO)G2u!a嬠LjbݷׅdcN,RwP{1p9ymѩˢ LD'S9o%FyTM V}ڝC|i7z׳׆~^H(JXxgjsogBd+=$+f`殬vԋyZgHNa:}-֍pivje=K0L!W@Sg, z&5vr,,( &`-wzmx8Pwu7F78,T+5La% 9v̮b="ͥ:$bP̲)9y?ȾQ`yin |`r]k:BSTV^_Yg,G{q➂@qkBB\X]) N9c? Ld3؜G{=мy~t;򛅖P[כWD_ :O2t~UX{QA6'Dר6vmS~iJENiؐoNAJSCa6W?x wvgnz)͘`s( :TSޚ8ך: Uٟ-E5mjH]e2`gD]1Y H5hB/ 8鮡C͒S&vL£j%.p`nJM ̭\$>KɞE~wp2V5<Ioe 0>~$Q P)*m?ivuD# џFc-@P+^n7vQ| 4[kx8q/S5U/韈~Z>fܷX"ۆNr9>~oB߉ȡA+z5AOqK݃Ev 0q~󵶺%Kch<'y=]&ǎWۘ3ib5(|R]0 fոz?tze0Q\Z[|^ۨ9O;ud?bK~8l:b< |@])_3lG־L.iz)WŶgjW꼖:KٍowTLoC),VfuV8z`0RWwr6"/! 챪ja)i$7cg(1R[jtב"P|HQÞ C鈁Ae:q=zVJu36t?PKQ\J/:0#"pkcs12/inhibitAnyPolicyTest3EE.p12UT ц?;7AUxU{< Ƿf5"6SU czܲ1.&uhSe":<5ێ\rݑjsKq^ys}Ȱ Aa ܔNaP2,kϦȐVR2}rrB(my0 Q242dNED0bYXQ;rsJ.CkXV`j ?z{j\oFZ7W-$~t}8 FޢUv`8kHE-|dW%{:iGn+)!bVζTlr\딛^VG"ƔM<P$0~R\3r9}_{njřїh׍J.k13(֩#9xUdr-iS1w8 Cq7i>$>:z5&͇Y)Nj-W-b'߱o m ȨcNR;o9:#G]GI9`Kd&C!u2S) f"ٓ<+kw+,-~R8Gsɐ`+}6O@Iq=ٷD&W0`mF#BC˔RGsz> е?*\٧6Ee ZRN8-?#q/r58zOoڻ^Qǫ`ޥy=LCk#8_ԧQ?ĥ>* IP|l/cM7yKuG;g!!4\pK*M%,k?f}Y^mVPfZjA@A{ azä!A)Tʳ8vM4 oc{ĥPKF\J/J5&pkcs12/inhibitPolicyMapping0CACert.p12UT tц?;7AUxU{8ԉf4Ƚ1#Pum>V\24R*~6j ܝu ecr\CqIlZ389?~7JupvCa(Ka'аVp9jR{w2jjFcx ׾ڦZSX/ȕTD(x"%/R4dzԅyd28V\ws^Xq$ΊE^\rP,F!0? 6ZYn_X|k*)SEg{eot;W723d2.5HX-0։|PATGُ1\L]I.̳1dHwט*b0gIZtLl;=Xw yt[e/1+O]}zOrsȌuTrn+D\-dc ]1[R4BvalLke'Y˷x2|D;i0z$[7 (QUP[@p%pH%T:mXU?$|<ݜ?{D왨{oV֨{TլHSrIv>]8o5БhO :ߘ5MKHRC: Y~e% uNX]30gπbjjޗ;~UʛN-^O8g{¦O&XcI-rok[|oJ)C4ߴhM٫Բ)g2|۰BAŒ)bJ2G%Pe >ʮ 顼&1AoB4lN ,/۷A ?*O|G؊mH:4\⦐柡&px iwz:r݇&䇷*f\3eqA#EinBFd yb'yGx(vRz{--ilcShޥ2oSFAO)`Fhԯ:NE].bo܏ξqZ`JLٷnZC DGD6? MlX6ӵ;OEHwÇ" ?6wO_E^=>ú0oc@:7nfKSB.䶥nƬg`ߕN'"gNՈ#zHHU>dO'&5QT: "xɆ6W21 y>( |=|mBcҫaWgو viZjD8*"=h}VA2=SB:HdvbK Cr.[91gBU}G)N|+BF@m QenfbvzMHz5^tIs65]KS,+?Q4ϼ,/=o|hR,Bq'Nj`=5Ƈ-aWį,nrlYjF;ZRC[%QuOփ<[2붢Uypi0A( d(uVi8!sœb, [߯6!/$)4W)&Yr~;uN-9g^em4oRtgSްϽ+͍t&R,kmxNfϩ!T\sfN1OI&!7q,w5jh8VR\4y}918: I FAh`{,8_ B GN/:aΊYI@щj\5o sc ;v? {=49t-Q/*"*oRAg}R8q>h}XNPf k7t4mbd:jґL_v%3vs|_qySΜm,,>w$Q3vit>*~5tLj܈gׇ.S eb|idG7{]GƪӊM$WP9rjkg{yK(Nŭ:h\1̑y’?禎q}5D@1;8Ot~M)u$.!Xn$F@xz{TpR8N($Qlxvb?Pz!6Rs=[HByPKG\J/2)pkcs12/inhibitPolicyMapping1P12CACert.p12UT vц?;7AUxUw8Ƨc`5_F/ Y10Ѿ0$>!VFK2\B$L-l- !`{syy;?Dm pDxo|P.h1b @Tձ]P A!BI?/@p~<qCbA8"]d)WIfNog&^8mBB*?ai\C5&nY2tP\*-Du_Ĭko+<=K9<M8.SAi-HM1 XWT^4׼dnJeHQZFu+FQxAv~\c{Tڨ^BTWέ0 TAf3ww4enO$;oI!Кe~QI#Y]8=r QI^ 25~50ډ"5P#-loBj1vGvyR׹Exh #A??;G'JhTnpRi j~Ҡm #X {cA%\…mcaPↆŠAX9JA!/ D8$d_"@XVzM]y%tA@Rc *eދFvh:Ը쟏6,){X'ӵ}kL{k ŝܴK\x3'dvJIճX易[tefܭoNj4y}*7nS\?fʿz!>XjeO,IJ ݓA gMB>\Vys/R%foni-<گvii=S@t# -'[o:kϲ_.HQy!S~`nȃ.aZF}}\~WS_ќ'Bhv*> 3W *- ¦t)*[Ԁ;V\bO{\4!{סxN}LGǥ "PHyiȃ;ntl=t>}04/+x7G=AT.A{\R 9XnӅ[H6W ?%<]M>wMZV@` IvfU+^RT%L;&{!dpRf#寍ه rO !ρkxʲjCڠ@#'!W )1 /H0},qgR& EqRg.|G*KnhW[ PKG\J/W[1>,pkcs12/inhibitPolicyMapping1P12subCACert.p12UT vц?;7AUxUg83(kѢoLh#zAd%bDI`LNdV֪y{99߿ t MQwhH 0;`;hl MWV9*`@ B#O@<u}Hm=$Ic*^D6 e;5DqҊnׂ}jCDtRsܪөlR .!IxqJsH~,cәʊM& ƒ0< PrЅX#I[zvyJTKM7V?kKIOjq)hͲ)[8/~XLwt0Wȍ=;Ncպ[1@ و'Wp}TȧMdt>(Ep yhW1jKB69eL\iEH(XUsfOմmhlFGKxRzcG 81wgi :f82fھ -GKF)"z3 /t +C pr9|np y7\okv~hzh;㜈5`<3)`7o`w E?x &Ul#&F c $L(K|kgp-I*YC;&}6>[l'.T\Cmnb LyJ5"sO}RrXx>_Fg=e(zl凟&~w"SGlPE"|Ѕd5Y4f[ϒe\, lbGZa f6ͦY@[RE`ƿhUсyҺ wj2Z(:`Y۠^_v!y ƴq)r^K[88>p\i~F\6!LCbjަn|[x~r<,_ϴ?W_We)6Iiv>Ê_o#{ٵ9s_#A@91-fZwĚMK10l1{0nwѣ/Wn .{ǥȣ`Ebliz[tFMgSi?.>DÅB,/i#a)fA]FVH9Wi,xJJǓ ynb,edbH0 -mS0k}e#k~~LZnyyd-va?ok.(9o{ow ^D ZG^jI(Ð@սg ̕c9.50IJ~S}ԛsr=~3! pp <nWr8^hi J2ACTUv [ITJL< Y6 %hU"PqAsovz~}_WWdk֩g P$h:qG5tai_a2=}F4S%smՔI`Rd43ʛ\ul Afp\Eꗤyr@pʧ`x*3E#Z*=aL L_o#Vu*-N&5wbSl]ޠM2M'Lg%><&m]A"e?6%ͿTPLv.= 3o2#~{e `E*XȖ:/p E=PA.rrN*(rq=jd|%jE(a]2ZޢyZ(&dIO=@{;6!ѬPrjzupW.cD]ZnTM3t` +^+HD2 Ϟ5efb.83Su&4~;l.B]]B0qZޜ <- se}lfʬjؙ O;0ک<)-uw@TG՚>؇?xcuu$IiRbil:&s|bTӂN;'?͙jZmYvDpRWc6@3q'jb}|r&jNiFs` OIpKB AoKoNI4MjPڻ,\2K#&NmDg_I,)8wmsu`G:?REl-sŅW?@.a`׮'_r& KA~QwF`+tnwWtO 2+75n=}]A|t"v^+ׯaxvi϶`A(;}gV ,CI7aabU`"źhU/W"[0jXAD\Nr}^)* 21?54@,@`Dd# w- "TD"k ~ԀYM3B(HlPKH\J/&/pkcs12/inhibitPolicyMapping1P12subsubCACert.p12UT xц?;7AUxUi8ۉY%K*ԮDEԾfjk hFtPE(ZJ'j-iKh)fu{·9o@P :| ԻjuG$ÅP:hO;tHɡU=T@p x)]$F^K 4i}H>[*h.5[Eپ5-c9F@fď)}8ȱGmA0ZmCySTt (?m~ɒ_<6hc^-:Kb:<˰%~{"& SwP>W7P-ۗS8PSQi?"Cnjw3R?wSx *n kxA\}l}kn]ג5䝽 -att J/ * ٭]bdYĬr:t~Z\X܁t#[QB&4gM{lznse_d9"dŮ>!ŲwP"03OՒCY_t:Cj7 .g,]jƪⷉcc7_8wx}c;2v;КLoa2c9g+YNe%{8,?}Y=>%z "ךr6 cB*qBf `X('o|Ԇtl9 s<1 t,&kp:N}Kat~0_(v+ q["2 `Ғ{HoZp+kKDwvm^Rdp#{彬vI L@lj1-Glq#510 m끰EޏܞJך]$@O#/X՗nV8>9 Q申  ȹ]MkG|vj8RoCt>r(_<%AJ:@WZȟYr]+JF$V* _8C,tSRIw$^D[Fxvw*%)x;JPby̹ۖǴh 27I3 OH$==t%ѹBק *|=p' 0}X @1Ɋ{ekJ>T ]V՝ PKK\J/Y#!.3pkcs12/inhibitPolicyMapping1P12subsubCAIPM5Cert.p12UT ~ц?;7AUxUy4ƓHj]C[{vcRQ-'#hbelwծuJ5ت8mJ1߹~~ģ r!Ij"*,'A$=$qOpZ/CgB`(uM a4XAq$.&va5iY*1M#cGM=Ovh$ŋ2$LBoKxCPHeKg&cMFSuSi/zૄǸXra&^\|A]p-j#.SM~,{!jG |Y@C7G]ٻ+a,/Rj7U.x d8Zms#Ah,S"d^a`Qrl0בǮ6ǓΎi't߬ il TǷZ 4Ji0{ȩR&+-[^&]&YՊDV_cldQI5ԯd;Av^zˋfܷ5S\MbOfbx{zpkr(1xlg-xۻIM8v]k*A?awu ^'4HSK=4{-[18yFMDX¬ԡ֘إޠBz:Z;nP-~d`wʕR} ֘A&٫YR52ghw!|O/R~hޘs"u~/ =k"zN)d_6w4|39_H]s}̡9c8…b5ƒǗoB"+f,2 bq'%ڜTpxl 1Y;g|jbO֐<>ϒtEI(Kr_)Rx썔fUo@Vڸ-Wo[T6"B|,ō?e!y ҿhDNmSBx E@ozwʅ̳*U &<>xKӒpڅI3eo)r@JqK[nBy=Iaê,=pE nsY$}OI 1[ssŃSي7I{'ݱ ?x9xBV@IZhad~^cWEPi 39E5cV'eml߸~/Z@FM-->" bBڂZp'WlwĐkf;nK̏bOA4=ͶzAlc,KaYf.M)&Nf[NM.XbaBTf[:bDDtqgBRC$F~.S@qn:hQÆN:W>曙{Bu1pFi8fUnrB?句`i&T"JN*rDabZ`Q$qnnq:Ds$%+ .`D@(}cȋH!EM| C5~J7,  PKL\J/.(pkcs12/inhibitPolicyMapping1P1CACert.p12UT ц?;7AUxUi8IVڢJJ]K"02D"-cT1L`#mQԒhUڱjVQ7#C*bI<ϽwswXtc:̿.C@6€r, f,*8(ª@a@(ߖH8x8$ HeuJ# J(; 4Wfbjo q,? dk<i-%xzylPK5a6[ n:$B, dkۗtD&m&$̎=I؈\#3 t+6I Ң?ڞѽ8g+qq^:v7VO<_PH+7jyOr-9EPJi6v7GurJO\{}jRe:yZ+\NQOzk "ELxޑgɮIJ7 FͫBv&#o)$Gtogm(k63lXѥwTHEI 辸J%Փ[_fx!sL:ᣦNP(뎵-D_8ǝݵ+sBF 91%10{rx7&H}G{=џGND )@Ov_UB-;iLe*߿zJ`7Xh}HSx/uH] }<7,c, ˋUָ?oߴTS]K}2PjEXs^AZ2MϤ疋*࿒5 Duz fr`E|>| 8_`@2@} 2k/IZ ԏo:\; ꨚ0cG^ϥw%+e#;p!q ?cHxUM-~ <$+e"-\5:d)`bsC > 8fBg`u;;|+e/ 9oJWQBodU[v56]x#a}:8^ōܾ?<f}ge:4ĕzOwdFBkv2B'rcR<:E]{XpW$)tV:Gs2=ί>>~4IQW6)'r@3] [(x,Kͤ(զ|hO;Y<60j8J4):RȪ6#VQ̒5LkõbSi8wZF9-P.ɢ>ܟh=1p$ @  (@;胰X T BK Ƕ}z/gk ɎR!OPKL\J/S2pkcs12/inhibitPolicyMapping1P1SelfIssuedCACert.p12UT ц?;7AUxU{< warkad&-/Jorz+e.2de6䖈ڜ-[eaZq>}{}=狧@A@0@TM)! y F؅x _+;@@Aq^  b2i  FP2]LSH?~^@BXy!λjƄhՊ3C3AI&"Baz5&8Hk$VީBUR{sIzBnXQ=eXkw;)+rBCXTnGs.a3g݈{WwO<.}Z\g ע.pA.2jCYWn$w09B r,ꦋNROߪXbݳd؅.-~00G(t&y+0f>?8{TC>A+&ҡoqug's#;Gz_-=Ed7#}c|>-߶v:}Zh#祧NPLyqrϰ ۙ @iB,w`>/^0 AU) ߨI]_ɱ?yM *~cB/mW[oL84A9H1bYZ 㑌xh-""rtI7`zE.5ѵxCb#Km86! e9ɾ8ni>c61,/+!]wW7݉&1:VֵsJqfqoRV훮1!wӽ6RƐC iqK%UfvMelڱUšcywܞݏȠl ʹ:4d$,sפֿ*ȶJ70?^,]BQ&܁ś ߽Ҙ El>mv$G9B})]/~bRXN=ltFM1"̿_Rِc%q b a8[,yT%%W-T4(lW^$9)9J*ZćK/gqJT槞ˤ# f=4y{1iJkתˬc Updd90]zt"LMar$|4Z`\{9%̸_ƽZq--484}ż2zg"!HQ'˘ɟo.f@@ɏ`fnUo Cx (@d@ p p@AO1x(D\,Kcv*lLNj+GL.TzEPKN\J/ɱT 5pkcs12/inhibitPolicyMapping1P1SelfIssuedsubCACert.p12UT ц?;7AUxUi8ۉYKLұJBSF5ľd\Kk+jTjC,%4NkV\T(ei2yssso" ("l&v*.*Q(6xhD!W "$ÂJ&]')LE(=m$,nJB8 E6t) 3ՈDR0tV^8)GY*Z(]Re2&ݵTOلPyC}B&$- r4ɣ~1ݙ.晙 hFD3r6t6J_еw!VT+4׸=}`cfpo`kk3 8kH'yPUU1u,xf?eR+Ծ]xd&ssDzPZG%O~.uY)&BwWj#g{q2Jվܮf\PDKlmRHEepCPDR{?[˻n6hNL b+JY}Iy+|қ- wPpq4Oǽ-d<ωt؊?X%^@~ɛ5d;,,@jl潶7jH ZH0QpjR\s.EwiI˔Qz[]4 q\}K6 ؃'10#H6mͷɕ.N\|BïZNOs; ~siq/*"ӳsm ]EHZwY6B]Q } /!g9("}hK(q+\J!Q*hrJ=Ŗs*f(%USވI҂H|#%H=0r&~;IK&HNR29XZ>18<{*7efWV )ip ,Or n~^>FӁџ#gJ }xDuC<*ٶyJh#캥yiGΐ F&B_bޗtL,z--bׄ8JTE1HwHdvla@k :J(^mUxG^XV j*@ Ԥ-5 (pęin(0`#_4֙F;3u'<,Us\8Oڋ1NmYksi(m7N{^ʈ3?ϳj y)_d녗Ә^8hqOU|h2/b!W :C.~Qi+ ֟P8&{~O8|sڪ;)-i'4h{cU 0hv, -_HX7h&kwO*aA UC+,f+N =;{ĭ^;eJ >=A=j 1"%/h~@}0TVV*.@"*:/Qj(1= #(km9ZnAEL\̟PKL\J/1UH+pkcs12/inhibitPolicyMapping1P1subCACert.p12UT ц?;7AUxU{<w3-1")R.Q˭%񮚰ٰ4+sɽPsoM\:!B>2ws<{͔h&T6`96@I` ʇ0mh&8 f[t_/Vg//g#H `n1TCܵ92YTM9ư:oOWHܞ{1W4*e.K*Ч}1m/c+{cx;J p0ࡘzCKGڦS{L4$|ʠYzJշvʞ[ڛ`8, (8%1N7I(RRSFS^C"/t]&юnS3HvPevNDHI<8gMeyg'J5NE 5ĬBi(՛cTP ~w86MOyUR}tiHj,YOn>W*Z|}cڌLO [ݶ-v9r3)>mBrCJG[dUZ>>4MgÉò+z*ʸ;ޟ!b 2ve@e0|0>B2_ od*MƥO}fH*ap2hk{/%,&qx| 7rrtod #Heg.r N+3z rkء6.'5bșM?:|:m;yhp7`P]EPkbXc%DѡۖUid?HpNіun u<ݿ FAܾdP*a*LГ Nl$TtB vݜ-"-]55!;D8N +sQ?ucRpJ j8{ '@ؤcRdZ_y0&n7b]1o٦S^WS 5jXe!ʹ n@_;fEe-x;09fhƒ|B~Af/V9NcCwR( aٍA/~~uef?QkHݳg˸϶(#SxvkYHLiD(JQդo|`{}lI0Py$&YmSɸM A!/6n!*[neና:>pUĨ;?74zqF)j]x-rƯ g҇aƖ/*i=sΒۈJ3|-s6k?~wtMh}I+:@+.=$#*h?j@4@"7Fh-4TtHAr26|~G*s {k)xvPPKM\J/Æ.pkcs12/inhibitPolicyMapping1P1subsubCACert.p12UT ц?;7AUxUi8ۉƓ"e#ZumRˈejR!viKZKPAuaaZQډ"EUk-KԘΝsyyz@CpT8 MmKTJ=߷ᨐ[`L*$cߺA%B8U? IA?ʝ q qvwT-DPWfew-\rnYErG.Rdz|9:CT,3 yg2DNL?&9?)!#rED,I6>u4 2ͬ'6O8Ʊ=yfo|R긯dWgEdWTw1'~ɯP64q2l%2[TShngRBF'*^qPrJVkWE3Dզc.S͚JbX- ^WE08yewIꬬkٽ+Sd5&z%QfV3UHy9Vo*HɤQ*jmգ q6O0m v G{_# bxF݇BͤRӓ{D-}hcCɄ-e;Y+ v[z۞u•* ɗLb~ˀyVM˓}vQpo"h̸Z\ QiHUbHɘ 1?V ,{UK]6;e|hNma,l˫df`vmrnt[<6Tb)g,r(3ҌC[~mND&݌,z slޖ)g3\M؇f456^QWžb=YDCTcyșcְۀGV%D#KoJ䌆"| .AV̾(F;H (O]ÃSҟ4jZJIG`R TR_AQ z(R9.@!O5sAvؚA Z>`Ò#^^a6IEƄF5t)傯@AOn.]UhUܢ P:yq1'`Nq$wçoy:Ͳn "-J[[ա)t乍3(G|/ނ# uɛaǰCy.OJu[܉w/dtʜZYrҍy_7j#nڐ>8%ؾX=Dm²ljG|Fή Fh|.bkV[f%"Gs$I-HS'J_?' 9ݲ]tnBV"QU[+1Iri$ӑ]n܎3l:t{A/L'{:3":~D8ɡy0frxMcP]Ͷ75eզj{N2~EᯰuQ+2j )"yy [o6uKTIo{MUb4BdfWEx%6PZcnPWJAk&OVK%GdMo fJE%@0ӌێDjVr gl² yF#R^i],eŀWQ Pź bSp:`0 'P<[ P0(DBup88LLG ( `y4Ul%X(!V9@oDNJPKI\J/>j&pkcs12/inhibitPolicyMapping5CACert.p12UT zц?;7AUxUy8g7ٗ)%!:dٗiKlvl1V8ǖP&cwl&C 2̈{=}}?Q3?-j#Rof"'ڴR#e R@%0FXܠ  Yҥ8Oz4H;aWR݋.S=]RيCpcɇQcց\>mWm]߾(Gj:mobz 7).3ETM4KW] ruOs<=o7{,X,I=s;O8~(0~aX Y$_xOzY4Xi}.!M}g gj8!uvYWfLLAFP|KQ!ut'ln4Lnqkŭu˔#!]'Zkh/)5Ϛ-8. 59Ś)¥};9HQg2,>&u˗$0CdM֧ bY7cE{MUnVEFGM]KmX驍/~c4,4:<[N_o ҕBV) خzБ]ls(|ΌV֗MS :X2Юh Z#w:V 7ghE)éK:Ku`e4TGVT@EÄrqx!(q2`~F|OۏSBS!eLhuԟ<,6d>F|_i}7%}"EKDLbܯsR/XV]e%r6-˳t 15߽͋E+lUm~R:nX夿V!ynKsGx4+{Zc|#rnYH!w%OÞ|1v3ufDuSlR$"Ueh4 8| `aZ& "M]aE""J`@%Umra?* bA_R{ilflY_r#[pY\9%h>Wj]V'o W Hr Fwo_o W-g:D:h1зi/,L^dcT5G͊ JR7B@C?·s:6w6`E`(o ":FhP|Byt%^v@5@-+DsɅܱ(nZ4F5)?^_[_p~Vma=m*с;u`~+9l(j~J>f r='Ƴ(WyZh]9\y!)"F~|i.iK-T*]K<L_TB ̡ ?8L!E }4R/ QGqc@/ $v{c}0G^zi%7K:z g=?v%=q|:pO;Qm;{6OwM\~H {u-Z,<;-c@0Ylx(7ezr9YpsSRIè.;gzXciĵ; U fhNo|Q0׏i[i˯$*-`(颎|,__.?%妷I@hΦ٨huw>=%eUb=^d `*in˃&VaA8 _j:k6ZBəCFϞ5M~Q7㝑Kkx1.I,M1 eH ΛnjX3P{GϋmWII`?iNVjS~l%6{G0L2-{i1b_zL"MfX@ힳ'YnJW & 9n#Bw.\MzXdjDN<_[M|LMg{cJ@NBu:e(u(<0bB- F5A _ȿ.]^2.3}}&.5-y)pM lnG?&I)9edpj;,WRW3I_BZgI@i gdhܒ*v>)c$fAlǶe}Dxc~3IqC2Bs5pP/]14ܣ.=VSreu|8"_\oLC#6Qbkg;$aḥuߛ:-619eL7OCep*jq4aS&Eg8"p P,@D HQ;S! TNI'7us"e/:a.Ä؄PKJ\J/@P1s/pkcs12/inhibitPolicyMapping5subsubsubCACert.p12UT |ц?;7AUxUy8ԋf:K,dIً:91Ld,c/HnBW9hLNXe #y?~T Bǡ$ppQ}*RZAc+@3sApt@:1TcHݢYhe4 tGU=ûy6/Ez[USS]dC0k0/3|mxJXp~$?'|)^ lm8e1C8^Sު3c6.|2y b~Kfb^p1segcoK升Z dReB衽9Vj._6w~/:q/yb~kH=)QN| |Or}w[{Nm= ^U`} X^ɌuzR2Ξ '`Rdb_Yx@!i,''i_5x@ o;3+ŻPᄚbáAAN.2,J!21F9Su6S3$Eajs%'W(bQ*T)@Bi2u)6ZjA Hg!v=9,RqFnz35>o47ѨuB/C}zGW-<5_yL4P {|#"ڤ*$BPmLD%NN_V(ZA_zdm]r,\ŝV7cȡCiǚoYywAqևfJ Dz+#IE_f3 G|؀*;GyDF~*Oqo D-/ =PoԂO@`c[Xp(8q2,T7JROU~U'*(ũ"у~h<̴ z+ҭ]ӰV3?wY/b^87&*Gfƴ RibBUATS]`lx3#tvaٖZ21^ ! ǕoD vXS(30uˆh>/@ӳyj qӐs[f^+ܻ([p^嚞Wv&pQ)tIGiuSMTM/Ցg($DWAޚ '`fcwJ?BwίJ$5gL jK 6\͢kC{R8pr;}*.ml_WZ-Ju7WoCꚷQ1Ek~}H9+F5E+qJIpyq1-|93ܫwZޜ[ ~Xտprr2U @FoXqOc屼PnUA0 @RaV궨l]}Ǘ07S8PK\J/U:)pkcs12/InvalidBadCRLIssuerNameTest5EE.p12UT І?;7AUxUi8ۉIRUV+ O:"k;^VUC(F쵌ZJrKʹZ2TZ'ywf>9=v~2W0!Cpt1m_*#CsO2 = घ#5S\3/`HH|Cu8Ե.!˧7vDNe0C #fy۵Rr9ܧ#Lnz7bt)YSʗTW3ZaG{A |<;^5U5Tm@9ꡄ;js2IVe6{n׭7d#8-sNWZn><8ie P qg}Z"*"ٙtu\-a{^ǽ ͷ j/f-msdbz#BA.Mӓf&Ѱ,c͗L$#ݣ^5ea n)=\lm h$E9\ ag]s3+ﱐFYsղCK:"$\dž荚NRէ[ fF#zGOn-Iַ[wmVX)!\|`ЏF1%V+@f^Af##)3JsUOl ,u{nm L߮TBn ~UƗfPTUՑߗ9 hMDžMH8|Zʹmj/k?s) X[΅9O&t \;K،q?UU!:̑5ˠޯ{1?OmOd6 &Va3N=S{#`\d9-On!KF#yq$CBoDnIQ\܊ `Qn 2$z.?-$@@*@}M/PK\J/i(pkcs12/InvalidBadCRLSignatureTest4EE.p12UT І?;7AUxUy8s(Bj:֢aRіj]ctTC1E$t)C8^<;>~AIpA4ǴQ0?`W:^]GaRnD9$ߞ%ƠnB8(Uq5F(vؔL6=]XG) 7p_q Q6?r\)'܇HLU$| aohZ1u-m{)Tbh֐bOeAvQ'Dn"N[fQY]=67Х2e*l/?"i=#/QVqTͽt8PL-QR>m'u(H䴨#j5Cau6F|k(i!`'?nܣ._Oi({s9e{ii(ƶ0+J캑wDl_r74k` ag oV qN]PԠ@c kӌc0y2 <V2;&/&X!^dz3;Sld#tpUuƒȼ1lm=ai|K;s6ۓy*>al6|pHZwweޏ(җ'׌ W 3.ś#(`> /tńgq|5gHQ>잽mKYXm\1e.D}ī3C!TJB35wzwǷI:-l֡UF=pT5ޡds.33xgY{E;M^R$=3M(ݏʃYyϪRb>hzMQKNvckR?BvtQڕ[xBA¤91K|~Iz/9sՎL3J4"#R &ҢkOOJ_ָ 6({a(~l͵-~\Ӿ= @[ Yn.'0ͽfv/_rF7' EejT5(GgvE>: EA*S I rq#arF7oF߭M7ˈ ~.ؙ0Peh |KOd$2d/~a]7 6m/4j-RH wSG ">O{ÜQ?OND 9=/=?z:Y9mQ;*̰H?+rsY"ē<~"h!dߒm{0d*uM,AS,md2擸{fHp! !G"T{c@JE^nm,)bEoJvtb˾w?O o'FɽXG+4`X E,:m_F4!ji5[U"iu{aIZ@:ڷ[$ixk&FZ$2{{|%6ª[9>G/X▟PqFrvYMlWk|kڋ-ީDUtR [ӛ "hh`A_F<]z$Ϙvh~A^깷Pɧ2y{?x&?}Mrƥ>⒊dhSWpٕ=.T4V3)ܪ'ysfq J:dzm)=BLWjGE& !=TKys++T2p> ؛ n^Ԩq %8 7t4/eDԙH$4`:uTQ2(.(>0H ]0~ tv%Xm3ot%-PK\J/E5pkcs12/InvalidBasicSelfIssuedCRLSigningKeyTest8EE.p12UT ц?;7AUxUi8 g2!-3٦+d_:DΠ!\e)]Kc P&(KܹƒK[6>9rCal$za*0*?#Z02?@@q%?C@8T6]@"X`xB7^J%r11%wDUD |gfL'8Nn.;_4Mu$hB9kvةt+;ꃂΏW7d|%1ܖ2+lѯ `'onj8{Ԩ3,Y^i1=p8<“x(qV\È$dh~?ӥ#-*Ȝ< S럸Y5 4nmTc"G>Rŝ-պۄ!j̚Wſ ]6є/[s>gDC:CQN怽Uԑ1$ڒT=.]XAO,WfzJ(GTuNu ƅ[7 6PKe"j@:j+>Q{G\ߧkދ7P}WuQv()ϚB}ZNXrnm_R8U R:k-jpu?2B_b=*;Ttj $ (Ig6_s 麊i2Q\ԡͭkuLgI=f>dHSb5Z7,hPwp{2\2Uv+75x>:˩fi~eoi1|OWG?Z7 dˆ$y\6)(]j`ˊrS]2\[Na.Bm[o{mgm1寏GrsYP su4 6ﱸaŎ "AH"_41ExQ$o!DP^:Mv;w<&u$qM]=`?ʜjbep~=@Xjʓ ގ3gad4*Y4ZP&dxsZq'qKQyeJi.7 8RXLH IM2@ -tbCPkC4͊aB} *Y:L *s^(<$ًm{%kJQݬ8ڮ T+-+ܭME8dy&:ZtͶ/t wVwOwj>d@ C--σ%ߔv3sςxhK#/JjrG=k([?{b6.=ecIACF$IFUBs{`E.rHY. hxz* pVV/⥪SNtSnǕ}*`+z5=S_K'~glyz-BBÛ1 ߯OC6`M kԤ._^?7*d] o) F;-^küNF!&mVҋ Ok%G 5VQnkPo *u}(S% R!+2~C!R!A 0},qTG 9aPU04[U4>gvю+sUyPK\J/I0t2pkcs12/InvalidBasicSelfIssuedNewWithOldTest5EE.p12UT ц?;7AUxUy8ƿ$|vJbKP]P;TmVC%jVXՖ2%S{QKZk 4ޔZ؋k;wxs{&CVG! @ ED>?KQDÿV`{j݅BrB(i??D rpXѮEB@ 4shv"jO@c]r ĸՏ[ĕ1oZ-h)ݱV)z3I.Ҷvh3wߧ@2~tuP]~%0!~<ȓUsdtc׉m-t)G~L3\^ ֪b3޾~5rMJ TO Qi;eF:~[.D}n`[es_Y,~RE3@G,佴0agwkӳw|ǒ3_TX&˞ELxszg8Zٿg,k^N 2VeIՖUqvސ1߫\ |{ عQ  ৶Щ@ e("o:?) Bc(H,v}{f!mQڝ۸$X}֨0;0/iH 8@3>|x $Y[//ͫEnumXѫO6߽xl=x?mh}-=YoM#+g qt ˂hE:n/^:AHK؉MWZw3j,.W_ǝhP#MO~%18*G.BH{(ɍaW8CLͿ؄i5ybɖMXP f_rq-ue :mn g.d Gн4KltU]ȎHTScskUCm->|AI)y'}>Q'nmB:⥸).S1E6aP˳O*xJFiCچ>0JOk j-ҡ=hS}w7f,+*~PM[ S)Ɩ&6R:A/5 r #H'cn<&3RJ/"uؗK.h'p85F3PPOjʱHo},D:3%kl{,~a>[DaZu :_lJжG)yD8ShĹ޼9p?x[_ͤvGpIف$;Jïѣ8QͰ7 {i< [fѨq67Wƻ]O!5,L7֠R;Z9 ͨfb\8BA^ەZ\,PI<|B;p`XSFcﶳteգ;p GXKZMP'd\<^uK3hV ,0o#%|?֛7%d>*yEC?Pmc ^~[ +[yz^};itU'2Wwh~̒HaϲgʎQ1\˶SBg*D w!b;X=щzNSo{`d+q]ߔ"b~t{B`ɛhsz6jR F)켾pDZp jjV6hՀċSUzU6e66a0za1ӓ_#4]K nnO{@&y6dvMk]pyWTj[{w凃A˥\܂:IK-HUղՊyˆ^RQ."8ZKO Hk,ԋ Mt|7+oL~`q)QR~jգz"g8DKFjN8Bȇʷ"gxsݜb|9O4LjԈd-z,Qf_󹬴徢glڔG /3{Epٍ:6+&b12KAMg_VxQղV V_-x' ǧ{_Mme&`>)( 7% 'd, AgNm~u<Űz|y PK\J/n&, pkcs12/InvalidcAFalseTest2EE.p12UT ц?;7AUxUy<ԉ>c'4cS9"gr5RrF7Cu "SR 1amViYdk_o?>y>ytG m^cWi0| #v)@FBܢCOZ0h+C!V޷@Pt:4u OHiH/a/yc/rRB׉s7zQ 3r$ tK\F݆n!Z91d8skn +~])wדF+WC-/3̖=>kqD{ق'LJPXc[k0UWS.x`{C}U:s3]2 |#ގ'*yϽ$9I?zbJO?RE#ƏlnL|P.29cNj7l.쩮:7W|n {#36bI%~ecnV8Y52BbmR.6+'<g㜳70YPH-'3*z8Sj9c%.pse=4*b~]MSN'39QO?/KL5|uu8ƹj;BrgK>ה&lG Lyp%fͅtp~ -$wQ.yS*.y^ǯV`U&zmkV^ y8A\=[O VI"5G䖒CaVUS a1 &`JqNR (l Z)>.)`TRwYPsKnFD*Kwuo ⁉9K#yTpZGi\;x,J;Pލ0rbbi89-k AHFa/eCSuꒁ)o/be7Z66Up^UӪu2d~CG*_J?Bat®-+ICn!:?A0p7w/`tHc+J-MQ1a6sn!gP̔ΆjEE,fH6}8,ǥk6}l7'|ݿ7^`ORU`m[b#Ax"%Cn/vyߐޕq9}1+}J/pimhXtwUdB齙HPLNᦗ><09{`MlŶr)V o6v|ӎ|L8,U砻<ћȗ3- !/=6'f%5LNjuTӂggPc]|Y%N-UWg=9hk-ԁp 9U;)b̋NVu0pofxȽe\4weGVʰҘVIboUdy^a pb`9'],o91 ' R^4ٜ:zP\J䎦Gq +X~Hcmwu;N5{ ؊c_ϊ(Pxt{V\׻T3#_S^큙[0Jm-+hV .)T$r6}>G`iĺyz/H¸h`ⲺĐEqծ?+f j"I :%ȒvidC&9’45q WP*Aӻ !p} /n?GDe6cw`Wi2OPK\J/lF pkcs12/InvalidcAFalseTest3EE.p12UT ц?;7AUxU{<Ӌg1ۚr\2Ek;[iA9QnE{ ʽ^ґC~nT䒆&3q^w~y|{$X ~4|WX!@XѾ]@ A`urH*0 H1T2e1(`$(h?8]SH8$' + 0*I6$~aq nw#K XyFN,}WḀ1Qԩޛ q_K0O!Mљ6%T,<'ڻ-%+$A(t`eΚD` zEdm/x|O7ӊ;ե9r!Wwڞ{ok2Vw`-REtY 19C}^gb;Uߗr3i쳞yhJzw7N.|Ld@U0=c%[8M m ^ywjk uu0/BmmrDbC}=-uk'}Pe_JLyji*hJe1q!Ikvq_t_=0׆=R7Cn^'3|[S@Uk<}Џ~l\_'%/؅6 yjW75G$~pOѿgD^& uH qwDmvf޽aզN||7{ >R5QDcYt&/Qx^|ӊuFL[|%JnmoyAXQC6z_⿘I p) >_mi5@A}x cZԬ{-ح3O =l#& B0o"Yf}M/E hz1[%VQ3Gw䠥K'ΛI׊zf&wG/[N7x*E'L8 %eK?0{>KMuvhp͵OC9· ~xV&_Cw!ab6YAC_b!xh8nF`P^|Uٷ S}?$9r9dmv*qžb$w(AQ{?**KC3!홲<y8냯.H2۸-[: Y;)ߎ)?yuq ZhukH7}ir%Pۓeױ߷iTZٖ]^Z'w®o]3nP|7SAN xN2*iK%( 2;Qqګ(y]smuwGِϼ ^$F}tiFiq_ՏH}5\,$XYgQER~$GdUU(2yB@7A> }@R'a8*c0zF@v?2 E!Pɬ:EwPK\J/Kr NrAR߲dU;eP8i 783M +  c3g y$ v9͏b~}ݍD쨷j*螑elԚ1٪-/Tp|"APSW_>d|~O!<}x1q:;?4tIZ`v[{jzeIlKS_w'4tGZut(ON%7}Ȗ,:UqXЍe5yGYP?duS \܉ =D\뚪;~g>#,oӅL 67oi}ۦ9gA9?cefkQ?}qQ&`kEqtݦ(*>ŰPN8- 6gœjtRřCҐ} ˩?~T5 A 뀖=f\Q?BzQ{Y=$:.H SdIAs)%⺎TstS1 Vds;)(x֢CO!Ӽ%j\9ln3kӰ|y w#e Aj; j2"zkrOZt ,MEsJ1D|H~WǺOq12-ZkI`&&|d6ӠqE_D'Jy,{h"W ET[NFj rt ӶҽQ '*pؿT̴4.D6\Wp8*Ah(bI,/OMO2[,TASePK[J/ 6@(pkcs12/InvalidCAnotBeforeDateTest1EE.p12UT І?;7AUxUy8ƿD|!*Mc[LmJcI֮HRVX3TEJkZk-NV(<Ͻw>2 (D K@)=5kS"0lطSL1_+sܷl`/U@@A䇦X$* 0bH HtzS݈PԍR?EdqAxRc25̓8|<8LP.3yUOEz-tTvQAHQ c c/k|nDTO\_N\ܡӮeEL{{=k)O&%hm~I{(r,Ĺ!ۖ\avs!sROvB\#.#Ok.v X} NΐuJʿlslx5 GoԥM-Ѧ9IT .{f>& <=YtH!XSo팃kdrT[{0SƏtW[~O CҳL!Y6$OSƮ!:Œϟ~ V YW$$n3T?enh;ҨJZdd+w5|,?DP\+ͮM[*`+Eֳ <ž{&Q8Y+#\fZ}Բgjwឍ }:mWo#9¶@9‚HR@&bGq*j=EXELߕ &F[e5,Gcd:;TXr3SuRo6'yAid0r3EX:=/1a$ܖ- 1%S oK/VpÄaТ&'msluԟPFd3z+ b[|yuPc2) ,2[|+Y@p'o&uvqI+$}/DwóM~\ U\h9mʌUC VWZ  zt!MwBA3'\'JWQ·!CEŸW/&rtzP(ވ𰈗N4!;)V_2􄨁+-JeLGj~-e(ZTYI|14RHmfz_nΗ]+ߝv4ȿxXYE'irk+ln&Vlw#0:Tt46InYLܳ&?z^k"ܬaWs9:2>) M=Bӗ%rL'k7+9ǽ oo\㛔0z|҇p&J5բ ;Ax|$!)5χʺN/žԍ:[nh L{3^2887~MZVx=#gJΑFNiPjhLN1vD8Msv.cفya7^`M\_/ ]ES'dy;[$F}nS) 5=T1Wz@qgHU@ o=+OvUvt~!avz Z¢ '|EjhϢXohx2L"I=X uV2[g?3loA)QRR"[ܺ[zAeA=K>nQraVj0ffX~jʱ縝g$um|HtR; ?[j^-y'9?",*I|˹gSOh]:K,o?S?^t{{o#Y6/դV&ʣMEWŦ = v\q{s2wd55;ZT|N-'F6j٢K8Fo!TBV8Ja|^BQ̲wFJo q'3W|Uhb|5S]]N,zp6^&N:X9DVK0$v29鼊ᩛsfF ݅[8[bpC9Y>{oF;+yWZn ,z9na|Z y`6~Ĵ39BLWɚjPNo{{!cW)¶ΧD2S#D]֙^0p[/i~Z2<߱ւq 7CsKd7+9 #o%jm߽ PqzAlw/ wfS*WЏR+/?7ޟƜt\( 6f묧E#%و跉Q UUw=Še ,I]ןN_Uf>J?}5qDpwf5h(p̊]`rj>>,>D.\Mq2`;?N-wxh[5HcSou!w"fZ6Z&(j*1tZgBm-&Ͽ,&iu0hskxS9!-`VpvӲ_)F^J,cwZg|yrOĻQmUjh;4H1@@ `@~@-P%E"RE+.5)Cʰu GKIPKw\J/&#pkcs12/InvalidcRLIssuerTest27EE.p12UT ц?;7AUxUy<ԉǿsrE}ebM)Cʙ4+ f㨔#6!43Bc4jz~{y=yEU (lƯhTDMCIC{ET 9V& 0 B  + L?" 7|^ u{S/.Z5izcj,@Г}%EhÔuT 75P?}a^NYV2t:#/(=YTg$,}N7{1n]><$Cʏ+PͫJȋ~N}"1{8xq@ϻ/ gAި^C i d٠oWq/Q* 7<+PQxWA/O,e]-yk$ 8Kٵo0(>y%#*Dlz+5xX/LC10><w^_kINGQcIm){ːD[;&t6-eZ֘{j%g̎n Etq;fK|yʬ_S%!'&@ "ME\o{ Wg=)!V0ESRX;ܖؙg(:Q@6r$GXC7rnvՐދxMfLDGԸ.Xwbc7Z+F*[ 8X|zoSдŀʱ)bG[LXdN+N7(RXPr k.P[ᴟ٦1Y%N褙d}+nT]F~d}bs9M-Bri:`U^UeS*"%AmC \DHP FG@ PzD\bO0w <!3T7MPssZgbkWz b sܨ'AU+<ЈbiuثnN; )DZWlv曚[@L"<9S*!waC5[(n7>:=ퟙ5`Yj!5 q CQDqyrfBndѢ#21uΖBT9qd,q7n^Ol4]H\ON81``0 .*@6 h!`*p7W\uJk.|Mk<PK{\J/lʈ#pkcs12/InvalidcRLIssuerTest31EE.p12UT ц?;7AUxU{8 w9m 1"BD%g %WdЪre[g4!9k|JNS!P9&Ĭ{]}=s?sT"q6@E]PawmG, ʢBdw-- aP @( ٰ:  R_.Vn \ ͜ľ~\a9p+%[GDiX:7"P/KF@W*<ܨ]S&O[o<ԨҚEUDݓh_ |VGi󥍸h302M.2v&)2P.}Uu8)J멖o`h{@0fG2lZKKsG%kEͰEu|߇a{ 3*/fbs2@S|dƑJ;N-ߘ(136Y2Ivbd'݊OYXR:65Oi9(7`3'>/&d <=KRŦ*t"tKub{3#VɥZi 6[l-u(otKߊ=1Fjc"g[c6C4 n7QLZ jMįZ'Vĵy:*c f b<F]>ۆb'*۴!u ?Z֯~ŁRq9@_6Юo& (]gyr'Xp'y#-痖xx ID%Y{`lf_n?F{j\xKJ!ÁMr(I6S:ҕTOg*4%1#;lXe&u6eLfn.jRjXBK@ *RAOA _H6Y*nHNDLs/ȶD/Mr2[/Yfi#P*RɟJNҧ6 >0VnR֟#=M qSBOtU_LGt(v7ŖA L'cetGq-w3ݽ*2ܭ;?t~ѕU.pGuN9xssT:}) ٬u BτK]LOR) UT;ȏͤh'Y',(ìɈuX(H"`ٴtsxg݅l)-\vZȻ:NKGOe~Z~t )9nQnU GlaE=㪞HzT/n 6ccU"=IQ{ϱӏ H&?8#G`a {8'NVEA׆VW5"x=ik Srj[R{]; ki=b.I][r냿b'+4Q nTutLLӗWy\sWR %4}YgKt /QiF,xf=^glǪEHCPZߖrY@XvJGQ 8 (pO@  ڕmjc"P!  @P{~0pϮ|@%9yPK{\J/q^#pkcs12/InvalidcRLIssuerTest32EE.p12UT ц?;7AUxUy8 gӔc20S֌]R#&r{11FePHd%T5ciPu}{=}>6:uC.y(|n6T^! )}<ha0 Smgޘ? : .y0K{F_ѹ Q)KzԂғ6ه|Y>4NO (gK/5z.wqE^𕬢~5PAmH'xT0Vn3M8'`4 3*:1hI5 C< lj>j́& Wf/vRJQxWe'G F;AWDY[)flRޏ(&3N#wu: oVWsO -lGW:tF u,RP^Oz!eeqp]9}BMI0SuydSa% `uwZNr_Qb!ֿGw6^F/q=֠stozUF&8snXvJK 5:=ԍ[~G5 IDz,8c+y2k9T)ɭuQ1zNahZ0.kn(fbT|3Fg\Ս䯖RYun0jX3]4ł 5*\r#> τPQ{s<Ac$7*C&.. ?AHq%~nF9b?胉WNޘȋhkiMf4a4w*lD#>7,>#K`_=,]G=v;pG>d Yƌ]]ݲ@ykR/S&?us;Kf/~Q 8;nQҨ\z~?L&Up{ҩ*㠇L b#3Lul$Y~ εS [ btyYҾ.%F95P9[s>]hbd.NWqS}9bDg8jkQH{##_j8IqYe( @vm] !A0)(Q5Gc},aӜ /۪Vng2x0q<" XKK9x1W7xcAs 3uz,bkx8aˆM+ iYVLJ ?pHRm(bBR[1yrxUm 'lGgqi]c1W>%>0w2"(M!_Of@ꐥ%IJM4JB@]^7lcJ?jkbM{ {hff,%H{ ]vjU9툟-Pqi̺OSyEV7AmYV(UT{DM}i8`43rG'o.L)9 $;g|1?B=I f|YpƷ%g@أ!n%ZNR7SZۀGH  rł@@P8 :"< B! 1ͬyh੹x;%Gڟ2PK|\J/@^DN#pkcs12/InvalidcRLIssuerTest34EE.p12UT ц?;7AUxUgT! 00B`BWHGDR42#Ub(BU:"4 ˜}{)` L4 c) PSH`~`+ n8^R! A#@V6jA A@$':q".2ώĈ;ew.09C`oPWt:ޘF/jBHj VfHw+0 QYÿ|ӿa/s%L`tN?J2#sEŚr.GQK˥ |G?߈MBϿ>Yoqu\")$n$Y­ې/˚UαƘ+Lt7JYKӨ6!d%Y7+6laϿ:PhSjb֙ߣ\,Ďfj}$}8x;G(e73 6`*z-̋Z|kЪ%Jǡ{ f;--˹uzN[rPc[V=3 IPh)z*TeJ 6PbʪN"U`S\M ~,sSiNyJ@bпO[rikp:8([7QָUZD^5Hh)ٟ$nQk}K7^sY϶5t]t}ve?HUm;s(T96l_$h2>즳SJwe e;B0 V_t4\ep#ަVmv  [:]pق|Zio >H 5!vt^=OԾͪȿ[']~i1QOL,o &'P;"׆^enݶEF'i;|ڑuz̩`jUIY9&=Em0b2r@+&cR-==&uÝ,/L%R#~J}DJ,aQ!abXL#TMɞ1nIw7}ӣ0R?eZ_t׬N1ḰO}Er֐YbwV_^lRr-PdXj_^{,#"t[Yas [6O,ǏkT!K7?emʘ96֯ƍ̒vUvQom(XqnD4 s׷ 0JvMӿ(p~-Uuy(~4WG5tZNu54[!|u 46/Fe6zcVݟdb>>]Bhw(sFY^ލy!R ;k^ԯ!u>4x2 SvZ)ybx*νtnm {e-A7sypnpEXw+g2 i'6"VZWL:V>@3³v!\v #Dz%rJ?lwXD{B|%ŸbHd9_ 'AIVQ\  QxD22R{ 0\P+uA"` !Poz"K#x D8PK|\J/T>:#pkcs12/InvalidcRLIssuerTest35EE.p12UT ц?;7AUxUy8ԋgX (*BtHؗI`Fe&DVınBH\y{}waP8}P{RS7h(D"@M@_+DX0(d /$3HBQ4B@Ag;FL jR*O*o2!h'$ŕ6 ?piC-' šޙxѦ=ˬ \\+uj-cKbk$WPӿtI-#x[AS; nJ]&=Ⱥ|gR>O.A(^C!|; \yϿYt]Oc§6v==?$&ԮKq5ʙJ>~cݓ),6 x' 45:>އlb4S$ovS FieTӅ4\q*<7ёr SIa.[CQ+S-hݦĽn{]# |e>"`eUs+N~s5\moJzb<ׯy͎\|٦LdVI>ƖֵEզR\,~N&8V?9C: yS_fxwN4~09fb5nUªO i;w!,3tPlF\Ҷa6=oݠ[OqКy[#IG2MN$ R 8zpw[9",# ̛|~Aa׫|Nllܑ&:ao;7Wx1:WFv҄Lo^9j6.z_21#T5/~m8Ox ʫ #Q}-YMiprQgbME>:fY>J0)T5FwSl_T W6,Z 0bxiyq9R83}\`37^۾|tld! T%~wbEmnLǝ^c-<ڕάu-Ɣ}{dE+n-xl^DϪΚ}`|W+HTl=Cwݿ u5&T!$H,DbC"!yC.! p2}ZF 2ԬLQ'BsevdPK}\J/|a?0pkcs12/InvaliddeltaCRLIndicatorNoBaseTest1EE.p12UT ц?;7AUxUy< ǟy1ifH0&2IJHbŵ fW؉R!ٷ$ JJ7#,n(ڮ?~s~F}F5TRLSEhD)B¨m CAP0tzrvYo""-F|e+ 0e}~³ޖD+W(&o/=ytZpgApU_(QIw TDξ/z~d3pKn[OK_4BHnbF 3 ,j2 >/gg: \!&UK`rbdp>meBK" F;5܍dM׋9ĬR_(֜.ydt? ^zp'Bz﵍Ⴤ2ZP `( S@ 2K!>k:vSl.>^:UMىLk>W}r8O-0|sN/+`26]iFqFwBnoKĹV^ʈ+vV*bᾳ*#v$Wk/g ot*4u8aԠ Muŧ wI?(*y]5dmCx*]pT@9?X0W$_=7MJ#^ ԓWhNm3VM2Z,=Tg|?M1N(U#E,pout=KAvV*,y%5iwHr j ^5Ih568Ϛ]f]Enba"iF" ~+VZ٭e<yAVД asp͜/Fth]MA%`.fJE"8g7|<}OFHWIqYoV1gDY}mGofԛJ PCYgM! $n.+fزI͌I,3dտpid#  ƶ Y,GB Bs'6ye?T&m?"ya4.?PK\J/]~s~"pkcs12/InvaliddeltaCRLTest10EE.p12UT ц?;7AUxUy8 f #[C\k\k6քK`l o٥&KȖHȌ]ʾ^KQe \y<9I(MB91,n6#g z"+IGG$։bNH(?)6(-,^8x^ǔ+ED NMveΥyISC ;ڙ\@ri:¢b,ytfL$wUW:mqqVJ /yC &Os0:~UG&7= 6&l*P.tև.S فhZ#LuIZ7vhv+1ΚlJZ[a5 ~{Gq ;_3Gm]IVF -35u#tBRz|*:G##l"~%Oi/wEh&) ́JwE{y~ɩn41==?k9, /$>_ooBd&|ÿ\q}xvujItSpG  Xq"FN쥡\: r*נ2j 6VQ18n5ejb]'1cUJC֪]:;Ll="7}c7Vפ=bP`/Q3U0߰pbt,!'2IpAk{8 T&A_4Qx[ $P|X5LjMmFrv<6Λ*ч1?^Z ʱ=9ܢ0Е\t31 ;Eq LCnMwo ʷM2t>u]>6y"sn?z0Zwm1Aj]BQrz+ˤ%kGZ5U-f潇vF^K1d%I}gH'.Brl;M \3ټrX:Χ4RjYNt:ÖF\jIR)|}Pe4vI5voX^Y~ss3+nzVE4\_OJ&N^NSjv]{J,6BbgKuTVZ@a?(@k+5Zcuna!Ԓ.|vވ3'R5=gwkQ:_d^h;Y ~;WnNɭ=Hɀ1=ɬ/BD܂1̎YJ$pɰx+40~3#k~qVԔ(z?z@3)BoX)he$ʮ3KjH1Ctc[&&OPK\J/&QKu~!pkcs12/InvaliddeltaCRLTest3EE.p12UT ц?;7AUxUi8ۉƓȦj\[PtR댝*&ZgZKU6-E[Tvj4jW[RR<Ͻw|89=|; B!`> 0Z<#y,@`d- wI+0(F~?q0#E㤯@ HP4Wےe) jnƟ<&NFUbsSie+;4z v[ *WlV㋷#lCRU ^ɼK^*^cP\! e^aJ Z+AZ:Zp]{~y`i]?1O''Z(XHfnY|*)j_J]=7e}Yfo~ѧ$N]֧ߎV5Ϝ\xdƲtLpw$ X5޳CSEfH!-MzT#NIh_H^y\Ow*Mh!y786VxM]J)E0:(/pr/zăX֍Xӯe:Y9FUjO^!=璌+%m..*`F5g_P,&O6Y\ckN77_^{iRP)#וs2JazK->k1 /l]kLGfHB%9qP%긎DQ$Ƭ Goҋo`"PԸ>cfD~@iӭ3áԚTl^WDY|Z&2( JepVbDg'*,І'AQC_;o&ջ,ë3>LOvh{};H|:XG^~N9kWʿGIQ& РRԻ̋'[ӝ F7YN$ˤvs vp&jF\l9%+Cr`S3yc\2ŽU쮢99>PF߽kS' mNӐƉ:TtN*z?呾ʙ I] U pNҠIx|dqc`>$@~*͠?)%߇;qaJtW+,裮FnC 'u./ 埽a)|BgPk[^&gFqW|hOЏ;-ا~K UL;oSu=b}=\Ă˼Ս^^ XI W ؈4Zb^0/ceA" &xT{b0J~8LCr _#af\o}qܫPK\J/i㥍v~!pkcs12/InvaliddeltaCRLTest4EE.p12UT ц?;7AUxUy8 g~3f0ֲ fk2\%אAȞAd\F-rKYQd'npyso`ׇ&&K)pU(t*c)FR ˩ Ai(60 ew)~Ɲ̠X MȜDLIsxZއY"WZztd-|g nz[y ̓"&ژo?śg%76Oo!t)=#Ʋp<շCDeD[Υp '3jc.qyOg0իwI6Dxf/$Ş!A76:Nl$FO!$w6BY>P߉WLBmtU'{KA A߲[|`*b8̜*90Wnd=Ka& "yFҫw{s=Qi;Od:w=~" z-~ϝ:V;M@]4vi|8l-BIl+uDo&Ԑ-- bGr335ȡL]:TKp&?M˳{ Ī${բ2l 2酬3s4J=0C1sQz%0 5M^VEF,Q}F&~a e}}OqATό U?ALfir׬^7Z}U]]q:FDEk'ڏk4X]amy)x9wek3htOсdND֗M-dUh(˞ف׮_3Ij#U,GX0RLEEʴ0 -Nlp [x"ad9RuKPD&t xCi蘌|5]˾mr PCie˲#?ۓ<3!ID"E /|4冄|_a0bw2Ҽ(XQ)[K,f/"B;NA&; T_DrFȮ]Íb]_tC)2i `ڞ RX P/@n\Q4RX%Ŷ0@C, |[Pg}t8shGʌʨ"VqREB׶ggƳW֑2]0O=X$gG'Ho E_;l8fBvA'LqJӳ!f>A~EtD־RM5Ŏ^T{UfhdM\YN!Jx_%'/Pd -dl7tr7KPR0g AIV~&ZtDuPq{#]_pP@ԽsDbee0.alm0^yQWc 5Aٚ(?7/R4I"uilg=ѺsVSnJ9 |2 twHwd,oU *d_&w)DH٦'ʯ>786[,9O.&+ɥ0V|ܙKs5nl{\o(M%鿊LrED|[]W g˦_>wrֺ_%F,Wðjdqvc6eGg'gj^%>(+Oeݍ/+眃.{%%aa  €@-4<@n'V+e1L (OQe6V$Kt(Ofc/PK\J/>~v~!pkcs12/InvaliddeltaCRLTest6EE.p12UT ц?;7AUxUy<g5cd>)ČN&^(:LYbҳ!BiRL~)KQ+d$ fw|9sES` MʰFa Bah x@@҇;B+  E!еa L??VW[F2}޸"#LLQ vW5Qo'ā͜+2 ѐocjQw\`S7<8ec܂}e?/ϕjEBQQ l|VݼsRHi6RgK Ꮼ,FD v|TǼUݳ:FӇ}&,1޲An$yQPk&rLqyKO1șW@jɦŰ? `K4)|[V,Z@"1H4ӮI3d#[XWi;~Ke2} ي%jg WUfWNm BgGϾ¿ԀfhJӟDfߘt Ql|-x]ϐ[a&Ldf}ʊDG^CT8FTÉG"u"D[̎E zYbfuͅUSh'72y7fiQRO) .+f?0G쿸k^b>Eȳ-:Rn~L])H,:XgTئN;/>.ּ&I29v(,k=sd LH֮Q\25cw]RwP{A"G\~ P9-S:Ewp ?gvp}z }6O!؂m1zpB']:_#W}]󰲯RVfjϪ%v4ݡv@yZbEsK ^pD1Go9K`V;e)Dlyd Kf\O2FK ~t:uUȮ\s/7tO) ϻJx^<ݷ2 Z_-$ q$5 (~׋>]Ek())  p D FGڢ`<A,DQ!Mͽ9mæAvqPK\J/,s~!pkcs12/InvaliddeltaCRLTest9EE.p12UT ц?;7AUxUw8 DƵb3jFhc6jZx;ZVIzKAXX=w1Q>+T60c0 j򙬀"5b-"ig 8K;BdbEq1D QpCcXtmy C2ȁ/X|d5ë?0E{ErZJ+?b U.ig s/}qro- a`eS| dpTɊI!zeFMK\N5q8cARRAL y2ZГ۵MTECs7|C·oqtyj%Tߺ̨CY<MYy4[S͠S_ZRqLjYbudHO lNg1)?}!iA847^9]pc!êt.Ƶ sXVBnTx|t`)N"6Uf2ÕZ2>Qje,X~klCq ժuBk2Sezu覣7f^k"g%OX.  迼ݟ,Q6c5rA=S\=eO:Xuk''OuC-VzI[J\wDYI@àUd*`C *x˘'&|#eȧ#cN SCe -qsT.r ,2B׉?ɟƸ_22Pl8 tMKS֞J 1-b0"ӏ_Q Ʋ)Uj7q7VJJqG/ \atLKR I"(_,-Wv$=JĘ E\6,C7Eb+.0W|zDrl~!?Z[cGHNfJjɾe~/ڵoZ{m Da9_Ό~t 0g2YprL"* Ѐ1g$W ABeu>|#$!.m!ѹ}gRЃ{OT4qp$ho/o8Fc}4+h-2ІJWdm/'D_LuegՏe}@ ?j70TV"I%u,8p;:9j.k?adPgu-^n'b%V0Ƈ7S;\150jņ:@8WW࣒nU4Q7I)d.&Oô>)MfQ8AݧA9㶫,vU*ym}6h쒴(F%\08nKEM]r>IdԈ9 |{b0(KV7T;iX&gKv{RiA0AGDYB&,F\Y?GfgGOJUP":F;u:S1OP9]a+^(Dg{0q' $F죤5.\Key1hq%LxӊDCS!GyMm31il.Mey-ݖ$O dj|(Smy~,>*gb!O9JϯSgK!IzfrY:CPr-)@gppg3J%qA?|ϥ- ]֥o޶&2>Z;PKk\J/Zf*pkcs12/InvaliddistributionPointTest2EE.p12UT ц?;7AUxUgXCJD"`(!DP MpJCE@@K J'C wof;"f(ݨ P<"TL"h$[c@y% (FRu͵ @ 3O8Sj\s,e51sGi}G&/=1Ƥ\BuV`fd_\8g6a٢U0y򏺺`!&atBZ}kxܸ8~ݮ*ͽ;.* |'iJ*b1`ęHݻLkU =^o_Tp#,\oa~$R$퍄IG[utwXN?fD4O,?DŽKꗱBmʟw0j;]a̧/}0 J7g +^m_*כ ח=2{Qxt[q&ݹ5c;m2iv^}KSꋈ*M/!pTΐU8.uøD-sGg[xSl.k|L㐨Uڇ]ۜ(0s [d/?'ТQUŴf.Fi ;m.1L.QhIzwz Ol0jv3~b7)h C anS}@\WTy*ؠ,LyȈ\Iƨ׎YI Wl!9ߎI٭=sJ.}ϦuI>=V_B>Yks|fN]8٩Z-'pYD=Hy黻3f23j$_тLPsFa~5pe~e>g/kdR}.`2E6^]O[_Ɉ޼P> FVC$?W*lYvwKM5~{);Bz 6YsS|0{ZL;¹YbM䶨NE;{tjoE컸Xu%_E\$ x8Wa|VSx.m K32V8T}\"L 7';FW@O6o \s~M'80|keѽ򩢒# IC p:*k h|8'$|f /P`5Ez_Ի3n[zN"0`C ǷNQ!9jD{|.P|\W4̷Bzް0FK1o[LjahzM:9"TĆRHNΥ@A%>̯ >G*' V:wTi\,V>;TkP;C Ӗ\(Pmon=>e ~}b*:i:cV3oBSչU=!~r0&D:e'8-pzֈA!:B1;p̒¼]BnPZ^uT-#V5e#;VM'Nw%6ܤ XZ3ժ32V;bO=z ^X|#7JR_hpiS~ϛ̊9~{C~C0j_N]wW ݶ^f-i=IA75[Iۅ1xâlhMv:rTE?ty;0bfdJW=)t"G'#K<˥3;Ϊiy[u Nl_K HJoC}-չ}\nc+y-/^6>/R ccsx]Ϯ_7PSYױLcp/P(jKChexLe| bZ.}& 1f'#֨$ž߄~8Ir2]"^ȍry>7DE*FJ."<>[M]G6cph@ W9tJ(Q¾+$b5p#{5fn;4H6#Vo9{B6HhZ:BS$UwOH-%ͳR#{: ȜKcLS_cznovyQpLXIʳ8 PO$ܦPy5{a8wQI{ho-RfSZIC63h%'û犿0F4#NXJa]f|h-a~^Dp {Y&zN8}5\FO*-RwoV9E0^+s$|Q* !Ea'A%r}T gePKn\J/r1>*pkcs12/InvaliddistributionPointTest8EE.p12UT ц?;7AUxUw8 3MZ4j ZTQ۵J>#Pf.Wn{Jڮ/ zZwߢ- +qr[`â6ѠWŅU#q9_V+=&ݘ C=ż8#V`>>˚][Z ;/6i%oo}&cz,<6 yP.R|U9H Jv>\fbJ76,>&{7.ݒ ,1Ïם&nGs6,3;T4 ߭Qďq_^| XIאCmb|Z}f'rKmknZ^$d\Ӗ>m#< (/lAn:/Q2eo/Qљ1aIso?LiOMg άi6zۿ 3m #t[ dWF߆.^>lҪ>X5HԚx#w'i&zS#/c41 qGT~rl{Ž;˽ T*&.K aaV&#xo0yNX4kɓ:)UWeys\؋ {zZ(cХGʞ_>f&Ph\n芻Wy]#[+J=U_ta D0u.6e R$T/,^|I3D**84%,rIbpf,uU23(1uK-Һ@#1^jf5݋fɆ0g =`7z7ۙTDxǺPe24E386PQs l#=S5MyUn̓sAgXNK'~ (}~hDSm>l@sw@juGiU;_!6wW!KFIUע.xnTHdZvQAU\xLbx_bFa ֧0,NoVʧnhڧA|E+y6]~@'|Ϧ c>l h9ɹp %[==~RVp)F+/ L7hirnjλpFJzje^IYJw}CلԷ5փ3RO^m{ss@Qu(IS1P!`R$*޳ 00D{b"!6 A"%ABلNaHs֩{?-ڼs25YAֹ[RYf]xeWb#,[jRB(׾J-[gp .JK𼿲,HdBczdm=#g5r!OK0W˜[a#{SMm!muB]5SlPHFFZ DI9le7vbu\T?6+鰒ak\eZf89"婸2 ȏ'h(nekr$jvbY.W`nnĹ4um 57ಝdrJ}Q~RCҞ-')ԟX 00Xڠ?hþ9٦[mHRf NaywwGd>m$@J\JoNS0XOǓ / w*d%9r U>dƛyJ^i!oσveRto#L: ?z5A=^\] ]pDBƧK|vĭb/ʲ#W6 U&{)"he^JZjX볻ҰxaW ù곺Fot31&s[pyf=h\:\nA6Mŷ~| ƙG7ʨ|OɎu5:VGnlen7cOX`i{0gjcl>rMm dW]UiGO$|ZYw gB.uV&ɂ^zH#Eݧ†ڹ>[0_OLoԯ@^mn~sMɚ_م8 GwwWv=祿#f\/W}uyݿ5w7g?(De*r|j^Wƶ%ÕSS>o={'7֙}yk6tmXji%߾8--!AjPa.N v /ShZs䢿Uݬ #Xcj܃i9qBvO| g)LS9bȖ7eZmZhs^BM$r[a$}E#jAJAݬX9}ZIphS\qgJ&sqH]OO$^+vC JS#So?&Y s=҅aF QĐDz]e晑Wq)bm5W"eo=J#DO@b_z&?Y]$Lz}jLjKETHlԪ6a\BG^!p[kݼ*{]Og2{eJZR ̋Xy:Qɻ@[Zjx.e>M>KZx:VM\A_ʘh %5+!P|5asD!vHl֙Lz})I'*pYX4)toZfSьF9W3XNڵ<GIjLX@K7tPv~/'`$/{ 1雦_vy+5A3G8~68rLy.fv:}s#l?^16.|4L[}~ N֬Z0Z`fG?Ҵ8X_kt ֒9ݾ 7w@KD+I7]$:茏:,'c”]AΜ+YiHok[w{[D6nޢ"EWuh}q`n){ Ÿ(YvGi7Nd@tzL$BD$KiˠEGKm2 D#SG/4>d< 9B&UJvz0^n<fI|{0PTqV6EGd>BQK` ~0>e/@P!TA;/3EjE;?1K=f˪!WD@OtO8>(2페cUeZ ESZGw/,8e-P3R\ACG$խ +s; ؘ[`.ExilbnLX.NCY0>5qU!@,z\fif+Q1)sa^vgF^q9{'*o|%FLV!= 4ܖi {[x=7[i{w6\l&S-T׬uh;c]hY<-wtۛM$IzR{; 4q( v5 eR  >0mщ}pn9#{VvYSt1ě5NgrD` 7{PFoF{aK3Bl=ƄCs[VHrqhs)aOUvld|}M@ɒg*0^@[ռĀΕ+jkvEZx"N_ BH-?'vT 8x!! p |~7s9~=8e!R l߷l$䶤cjoPK[\J/e@+pkcs12/InvalidDNnameConstraintsTest10EE.p12UT ц?;7AUxUy8ԋk:(0N1afI)'[̸ e!a,1 REvg{=|}Ib`M8LvπAT %O>4 Bk iV  %`\x@04/c sQ$CSdg q " ;CY/GӲ"~_s6EkqՏ<#ZF}|}a A @ThpœXGC^;o(rև)ZrqRwZLM1>2;!$g/@5aX|bw;|n^3F3[}Pr&Lqim-*-k #cn^mxCmhr ҃>N-Q;as8yr[n{Jhcx} \/̺:/t~+;brG]U۷Ȃs]M"a^.?Ǫ/ grWV_,Ds>$ MVe:y#먺N@2snV1=/lUxzC;烚 E9k-1%J_n}f9苽/"Dj]i!u*Ti"~֖obKO~/]A%{(Aϴq'd&!L[ɴ2 -ue?BxPՐ~.x3̊ RcHnPkc.鯕kI=3=^7C1jl^< ֈu9!m}_GWqw-,HׯF8|Wy>JTZn*'a)(ՐqLlNׅ_zT} ҽ 7.=xuEFIlNcEk:;$CX0f"o&ubѭ{勞~ sc u/ wRO. :p_KoƇ;OlѕEv`(вWr ~`eA! b0j_ I/R.A~au>۫[OMuRC fGCĊ:ShKJ.`Fqb4s|Զ3iuB+-{*OT1x9ZQgґtH!fBix7qoY?WO+ ]->[s~XkCoPVlx:y?T#QF|~ aSRٿ eFeh{bq$mEwU|Ծg:2RO*2q"9zDfBؽTZ^֯ҌuroqֵWxYIԂOl ºZo] e|;$[# X;nwSTM˛*^EKa0yP V_tE+I5(. Z]O;MwE lٚ;%DL+hQ6%tPͱYl ܶ0)]~! !r7NU3%V0ͱƬ~{}$SP(8ߺQh_Qݠr]U~ЩI %rB%}ԫQ_^[!nY7^Priy+ݭm7S74> B25oԪ S"eGDENkj8RHts>r>OUɊf-3}uz >K}WXc 6=g-r͕ KBxu@ ĠY UUcM5iyLBy'7OPK\\J/1+pkcs12/InvalidDNnameConstraintsTest13EE.p12UT ц?;7AUxUw<#P1B6#%fRT8봗Qh)-ApVbkRR[1 UZ^{<{EPDrN٣llED4?GPDJ;l!8 sf'("1]l>V4H|n  EWH,5Ib*#3֪WAa$I9*W&JMj[c9¦!&EX܇,BXA eЁO:f/M(uA'LGWH&se˻% S={i/,CfBE;o8ǐn3XZ4؆BfBXQjXTbi}8?8A(:_zםϡz}3Rzg]RW/Ϣucg3)N ^0MY $fD船|7ow\0[eK-ԏ'|a (Ic.4);[gTN1բ= cѾ/}t>j|"ZOb]ןvoVmzǏ7ne&꿤 L'*%4#;p̤n3Z'ߋ'wn1s1\jYר3kwr/# UxPux r^_Ҏ\aNp$}'6_dLJr?|Pt~eq}ŽY[KR ٛD^a^aEƛ%\-c0BΨZw7۽}zs0i?]Ag6L\b e("ՒaHiV0gY6WoP48 !YpLۙ> >wlOMrYUSn&m,TQWnt|]eW mZ0$mv$?m6/c$WmJǹ 03{p-VJFTr1{JN.dGmC[[|q".9CXŹH>E*R~_,IF,+}ɨOw&$cGnCf_U#:`~ЁxL%h TAKXns{.E\P($" mRuZeD+w( tKYa9lI͠YԆDkw ԧD͕B [#GJ 58">ijp)bl#L|v"Jmje0 ]ߟR  =/vGK N:(2/<ȨآUyԀDN揋M嗔xSPJU$%Waip x @8=P(9([JJ=iA¾~86D}PK]\J/BcH+pkcs12/InvalidDNnameConstraintsTest15EE.p12UT ц?;7AUxUw<dz$U#5Ħ6 %("GQ$VӣT嬜}QU[VU5.j'xڲ3$4Pt9~Z7M2E2U;neM{\(˪|?SݟKxMth*T 9e#K{Լ6+u.F%GQգt{ a=&٦Rūa"v$v / w:MtE!$w!.(Hr Tјj6|H*~u/!$PWL5%F_95xwB ~Ij>c2woEDcZOyySd75zw}Ix$cPu>_Wq 1VC쾴d[*܈FNԼ[4e/iu\ ܵ+κ׾wmd8#]&ʪƖ$uKbNYOJzsȴy[Ckul =lI3lESVpn|Jد4=Tg"nZ'iΛhc'\J̑}) (䥳 1)^};C>'ѥh[c%rO/e0oumܒ tAcQjaDb"5 a_R?@)}$@)1 ܿ~{TQ((2/g@~~CiXY1Gh{}^v|PK`\J/~u+pkcs12/InvalidDNnameConstraintsTest16EE.p12UT ц?;7AUxUy8 2q_%1rDX["#w۸͌~mŔAa&;HK-r樐-I#syBP UK-p& 7uJw/Aǖ? :.7`8FƓ9c),zK-oZE Ij' &~eiV\=SH ԥ~}ޘaPtuaƄnp^_3Y7u/pn%Hyt}-tJt > ŴarSV| ǎʑ(b.oC} R Ⱦ2V`sSP tV@r =DaѩO4k__+Sab,@]iyA"ȱjZ\PH"+hL{@-d7v0e{3^B/ASP);;>0 1?HPD Oa$}mWwZR^^\\6ojRfh3T>+N{b~0=U@3Fk_;sZ.٩}(g짷2:jqv<>{"<*o? Y;@R"T,-S!~Y ,#cӜK%$`p[]*\-iBJoKQ XLRe*SH%)a/Am۰QaNQL}FYcsHotWc IurG9eY't vhFEj5;3w F5:{^?jr@㒑PovG.雙]$2жQB8;o|zCZIQqʼnuGwy˔2ۍ~( !Tm9quDJذEÝ}@רXϟϋ:F7 [+]N-jWKtQH%kT[ޝ(oFxa)e-#>A@rn>,; MX57'6Wre䠀laQzn=:GYĬq]m/?&?ElN# 7F4uz}5~Ae6v*u4lb 6)佞>+Ҷk,E`g-h.ZV,gG8FJ3b]I|6c`|A]GH{ :2 籈 &F#si.L|ŕGߐvϯC%`<%/_PK`\J/A+pkcs12/InvalidDNnameConstraintsTest17EE.p12UT ц?;7AUxUw<ۉǿB5r[5/5KUКv]. Dj5Ԭ٢ =+GٵGZŖsy=yEAFvA|J՜(V|$ NP?83p`SP8%k< eAU9舖Es͒vJZa.u7Rwn}:O[4j¯~~>~ K,էx{EZ/ZߘO|XlL)P]Gɳ.9Ε8уR{2@Tti[uG9 V=G 7 g3b7@|'g9lp gЌRf9m>:yqM4wV ,nMxKLqVb||91s\+d >3aH 3aۼ/67?q8tG!^ܮ?կݳcƔ,G\qf |[ +7ŋy崞%"B;^ #*:&'[m8D3u_O.,g(9.se4^s c<q;+rb;kXq/ռBH>i/Vx,_jwJ$цBNT.ȧQ䬡R`Tg5жKmEYvy~g(7̳nB]*;,+ivI5:(Yv$~񔖺 ͵pK#}~)m-@,l 2Mv6Vm% g+6LE_O9Ǹ'hb HuZ HQWn62񍃠I`cܕ['l%;JO=ժ j2[zV%zȷ j_ז n\uu(3M{#3%뮝[})}wU~qjG4NV5c01V!?) 2,3 O Pe˯FHQo=$Cr3aiF޶n}}N{fbToDz.0vyi=pN. O m1Qsy'$>W:K؝ejuwHfGU[&g߮ GG` 1~"{wߚ.js" 3d+&MҲ,e8^*4MvegVkQ3jSEB! B-KY"Mi?G?@ \ O^(e cS<PAgz+D _n$&+ 1n5/PKb\J/jƼ+pkcs12/InvalidDNnameConstraintsTest20EE.p12UT ц?;7AUxU{8ԉs5ДKc Z%RRTkeL$Ȓ4ÖKb~[ʭ0c]2e,Qcc眳|}l ld mx:q])a#H} dÜ\!Kذ#;9_B A*pԄAlT0 Eqlѭ32<[ZuҳM+j,m՝i~Kd>$&= 0BuCZne%Uh$]S38 xX'!K{vtC omj) /`V""Dh:l=5ι-[smЎIb {R;[ KZk-2Ȯӎ|; uXTy#˕莅+ 3Ĥގ~ w&Ig/X U1/Ëb F '-s$GNyy= ~AFV'"zjPc+%㊳G8YhK@^Awy;*] `­^m9p}ҥ9zeOؒ{luZV2P0JkˁZQol{׎JG-aC+@6Q*BVMlh!@!@%;9Zv~rLܜX^zF=N77,"d'j.s(|E +Kʯ/sCDbj-u~0F-ҫ F@ݿ %IHK6S+&fy3rN;ou[[ǯyrJ$'R?qZ*]3ƍ9([,;l%۵+?b<#ϩjh('t6\C2~"^sԉڅȆ:2\+ө%9r.5dI x J*s fg~X[H\b6׭@ U/Oԟ=Sߘ*F]:jhXfw_=E洨eR΁봕Ⱦ+ M2ܠ4eɠ/Qc*1}@)ocufl/;P4=emBݦXVhΌ@. - \wDwzHuA4aj!8@q1Ϡ3psYPKW\J/*pkcs12/InvalidDNnameConstraintsTest2EE.p12UT ц?;7AUxUy4ƓlEmF(*6DbXJRkʠڥMڊ) )[K":%xcy͛?s?  P!] :+T/`*ЮPEZATC+  a! @ iki@0@:Uk \s$|Cp;KMUN^4q uTd84Y$ϥMmsX M "eFiRJk:oِk,&Vg3mc(zuT\QbЊAc}u R % w'hw~ZSYohŜFh^= ⎼ fߖldD#w&=uDRj2jG1`)SNuuI_m)(:n:ptG3k{QnʰU-Ba5+Y({`f=͛>fJeK^b*(4M^]+ ^@/Ar@c'txU.Ľ[t`(Kv !O}\qDIiMgeDn"DcIn;2~T[q["ApO}eٸiJ{A%i:״.+CE4JZBny4.lPgU,0BF@㹄La']|RvjJpM9>o/c]2IJˌsFL&HY{V_\~6(PF"c ̗7 J Q#@g|AFNy:l&}]P1ڠQZSP'`Q-C39/x@ݣm"=G~ ΰU{>wٺb}Bv%b z۸iuEaJU[CEc >,'|زUV{fc- Oxez=|kqi7flwwSEdmCAbRA*o4IcQOTPz0E7:O ,)2`\k&n5HޥO⾾]k>oOvx,fQuVf@HWh;k̻rQ=CBPǕ21~kF%b9VSso|SwWZإzвkj_o ^7F_ext8FB%4U_0%~N&]6qNԚE7J}ÿL3-y Gޠv)Ǣyd^+fם˺n,@*Z؟ ,g:YJɢu==v^ )Sx!窥 տ{.{Rb Oʋ_@~ v!L{F Bkhۼ#2zcLyF,q&eARc~C]gT?Hom;SLf O{P[R֞<1]9e&|dHW7[BOqĂFϤґGW|zkKSabA`E}(߳8:,V}z˙r˽e 3ipqq7inRhA0i;Rބp$LJ9DH,QT&^u#6F~Yok(辡3F_ ?j(] wZ 8_x*a61*u PA}ED`Yl#Uu5b98wD0̱SLPKW\J/ם*pkcs12/InvalidDNnameConstraintsTest3EE.p12UT ц?;7AUxUy8 fDB$3\bCJ]B+hC|󇨖~pطTjI4̣ƔoV^T8`4=otp V3T=bdC VyKźy$*r-氜`uqН4v,UxPA뗷g%hZȊçp%:h'AkuJ[ ;$V6p])%uiJؠriʆ{v>0zGWG ns˻ܜ|[drRgrcn<2/%~BO TV# ptI֟oJ|'lu5n[z"^CfS #Gl;t݄Eb`!ۊƓKbN -nSԡ:.dUc=1кrnH T-ֳ 7~9La2@&qi&h2&t9qg08aKjb1@Ah9`?@`/p1tPG!ӧD)N-DXC[Z jb3_bUvfˣ!+6ǝ`]}o %fljd,mHq fB F?lvj f1ͤ ᢮ ;쇚URi) :R/g@jvp+9D dX M{]+𹍮jۯqi:yIwoz -^_1>3?:w:Ot2:Wmǔ &"/HLsXd~GP? s I/rnWO58XL1s8 VW܏e~Ds'gSTT@$ Xd ʮݜƪ`!-qTN#aZ^npILѼ ӄ2PKY\J/S:*pkcs12/InvalidDNnameConstraintsTest7EE.p12UT ц?;7AUxUgXӇƓĀW)AeA42 au `PFCRA"eIQY)aTAi7@@fs9K` ƛ/4x͉]Ab^ hN BX8? Ǣ $-؋P, W5\Rqj:ve4kV||]B2^|༿7feTz@XZJ_q:KOBVT}㧰2i^?FDp XbwS8,Itn7zKmis_OL|[ENW!n4\}A.7uK}y|Afw+^B5)?`,*$TMzq8[GU ~JakO-IU:Wb|UۅR`*ԥg=\=Tn`=\++mĆ"ןCEs~|ܝhx "%w8̖%%ڌq{m*PI "8KRxmg7,JҶwm_C;qMsZz!`C9N,:PRe'O Fj">dK}gW|89)\nfIRnq=jEzhGyƫ{IPbm:޷*R邹d?Ϝҵ'1*lppqqYT2R~AK цe_la4@^*Yf]?r6 h  "'ЉpCPNwI:hҀXppǍ >--4;l-Y]^ldd(E:H2?*vt0?ɨ74֨#(WT+0nƩS. ol *{io2&2%ɳ'%K2|Gbhm-e_ .35%' eu=y Q$IhY_U@ *y I1ݒ.kG|8+=$^*iq}^2;l ӈ[<X/OUK@N# (N趾3<:N4y=;B0~Hn\Q2$gUcv]EefPJjmIlU PUQ6g|1sr@q/縃.,D- mꁿKL^YA_$Ɏ)÷)Au;2=}v'] J!+cg߬izZ ]#H٫%$Pk^,36qbqN<;DG?D LIqЊM;Od^uW$>xXh={ŸErF?ډl| `hpT\ Ĥ4xݡ]An3iˇV0p&S1v47{9IEԄOiH&Y$HԽlzz.L5u&RӮ[i\W~ӓW}7`1d&"voo1+8PCqaHr;*t1i_}HǦ;bkk\U;;еw1I2AyϓGX.I;q`PiUg(-U-_93|5*UfR`s9x ,T/?.Iq;y;f^"$:aSV13Y ȐH\ EhZ=+P>vLTZ+vWabr&&⌍p7=mj -=|zi /^Ex,_CM2\_ܑzk~^-ENg2V:=<9|hK^s`e¾ xX2(hM| MAA(Ѳy/B@:g&cZ]qwVG@f52&7Wo)_o?Y+3Z9ϗ(e NBvtB4-|($ 01Ț4Bi`jsd_e9@k%*!wJnCK_׵jie# (1vVLE`JW>͎4׽0-ײn0Qwg頷+YˠH-Cն-1]r I-%X}7D,Y ?= )6]lqɍ(Di25!|ciz,T]TCZ*I6v`+qq?![5.ElI{B9:Bg'81Y)wԝ2 vk)uyQ(;t }Ec8\suăx}_^< A"[ΏJx^ ` |{'K3S$y[ryVf325<#'7SoG`1Dy5U*^^eUp cKlRs3~܇wfQgz#8~cŨWF:5|98 *Q!ӛ{vr45v&9VS}lWbߺmZ;"(jӒ*nbVZ$ad NNZ㧁a6g ?Z@RT"}zL k-˧hu$Fg ph FeaTb.=,Y~vݦjxӮ/p+P>6;PKZ\J/ג[*pkcs12/InvalidDNnameConstraintsTest9EE.p12UT ц?;7AUxUw8 R,jhU+65jPjUP 5bގpVSZ{V[>Y#}IA$ c0g`P3I 3  ?!CCQRV0&ATVI %VAK|^@`sΙ(K$8MwR= c (bEʼnmX I\gђ6ɶQZBjt8Y-֠3,v{M2c A`x9b=GivD1Ų)uavwz nEό'V;//hc_]u6yc.pM5#YÍ'?gË Rmt*d" ItX[%Ti{&+ %Gzܰw b4EM%Ac?\6]7Z hk;g]Y)͞J8· 籒υ)8ͷ ."pR^wSN^LTaPoJzErP4ʳZQSQP}b0s OFX8Vs^m1S2jJ@z؎_g=wf j( ufs7v p \$ G#O??1jF(  z!X~ -kX}Ap9 1WSǣ763vEXr#f04+X9\η7 ŧo.ևi Udۓ|v$(m=/qS;)O2MHo 櫱~9ƩӴ TCLL/6prӦjM @ w4D2ĐqS ^aS6%(rj vi_^_\}|EԯRSSr&'scאbH&UvXrϳZpԶv <"'ʆ4TdqPKg\J/F!b ,pkcs12/InvalidDNSnameConstraintsTest31EE.p12UT ц?;7AUxUy8ga,Č5C$dP"k#+FFl545llٗe9Rɚ:s=>8FS t*V.'A|a@:O64 AGZ _gB0&V|wy + V|'mHP#bR4``\ܛ{Sδ I UbvCG =K^l7# \ѡbz>IcE,@{}B+ֿ0gTNוXxgl&ϚYD8Ru &0y c4xUbYpX&ogwj+[Q: F.Wj?EЭ$>6fDy 'Nu?5Cb^kw%P7_ؿ=}y:, 3QIo*05]]z TvI?U%M4fۗ^Qw[֨ D.]4<mғUKg* #O'|eDzJ"xF\pB5mBf>]ۧ%^3V\֬|{RFCE1?JG5&sPaGFqVǦ/&5UQV,!:jCw 7QP!1J=&j;=,iqZټj%Rܣe omXrxsXe3u(D e#U[KDoVӖsJfyy&lLMTy^C6< % (z$#Ԗz5|,Ov&n4K 8' hWTv+'@y(sK~rG>?d,Q]H4QBAiZ2"ڙM\W4T<\.8@P gSA!eP@yh (4eH ϏR& (EbsGmB#.^@ ܨ8?c;\^9lu7ȅK^TS$ўttv{5&gRLΛtN;Q)ϢO}K]!sv?9>9.5,ռ7Ps' W6CouN؎I4J,eҝ|6r}5jW uZ*f(Y#:2.qlkX<.X#Gt1hMk/u!5:=y g5[uY^<6N%Mf{3rFA Q#HG傢csR9wp\XۂuCMS.Ҟ{arCrj]Dǫ˂{"wu~ڊRa/~l8*Y<)d"pକYt;nefr*laQis$.&^?ن(y)'4 |Xv"»á8J1Z_+C;+6l nMэr2ȋ _(@@<SY=-CAe``Yfw5waj:q՟u-JoPKh\J/,,pkcs12/InvalidDNSnameConstraintsTest33EE.p12UT ц?;7AUxUgTӈ!BHdIJHqR"0)AChJ 0Д1B AD)˜}{|d(*d- <, C dhǡ݂&3ZA `ҡE!4 pE&<펉@0 İQ|[^{e<';Sj y#G/|ȟ˛`Z~{šV9_yRm%7RX+A _mYfBoT_Tj֑5(ptzu9?ԣp2u7pVD@;Z<$,31OkBA܃Ɓ# OV$9/.퉥I"+ĊÅ_=Mf -#HuKbIJLNװi40QL|9ӉはNx(d^ ~k[Ub=UȽ.;NvV^L;ҳ2IJ+ M{8S*D㇚ BӁ? h#@iWrzE(dTS[lbCwoxTtftQRY-݌ѳ; ^}OGg?f:XJ,ҺhvWi3˦n:5|'ܣ"h8^B}lϛ&2zp˨X(ʷ'nxyB?Oo*#F][kM\O~p,D~=Dy"YD"ksѝAk N){ڪ*SB.;k/˷˝q"ذL*'\ewָ\d^f1 !h?tP^% Ϩx:L 1b7jv.L mUqMCS5 B9e~o{Hd#"2oYr=s&cւE気VFBJ`Y,yhJ*_ @PT&'9?鄐A$۶KéX^sEqX[:{Ͳ 1E0)U`!zrpĻ9^1[li|A&R<3\ZVA {(^O:M'A"(XQ1e{;fBܝ${=Lk.:(iE'O Pjbץs(Xb\7Qtն?vXjn&9.h6t}tȔ[Ń KVV8WE+ΉFWk,+n6hȷ+O3![8ԤQ[9|Nbˈc@5#OGyM tf|z* &zRzxdRMñ簡|*XUp*}&ڡzC:\UV k+Raб4|&0s+91fqgjoK cùkg5W>`_L&|BlKOl䬽F!lxbpX!ū xc\EG*9;U*U+Mőn:NGP(/}Q+)s2ZXݟKx64r0W6vu?So|̴LFuF}O0xZX#`d0Z\=b=Z#)  / uu*ha10HAMiŋxjKYI ?]n/ zÑPK\J/|,pkcs12/InvalidDNSnameConstraintsTest38EE.p12UT ц?;7AUxUy8ԋg~3٣0,24r 2Ⱦߤ=wu#c9&ٗRH±y?~0TnC0T[rA. fPaP*~BbZTc˝ a$` `F#IrJP8.2\'Ѧ&Լ^*,3t=}QG|PU`a#i"K. ̕N}P -2͝헉8bZO =l@W`f.SC!UuR 9WT~ۧ^?,'tCJ"6lvurWn6'onP ̲õid|36;+s1.7آ]L03 8ݨPq]`f=&(_jA+6th|#FÂJ7I/ 1'Dɼ {ʎڦg{eaR CWIu3pcc"hѮ~f|GVRQPPZ,8l3^(J iRKɂG/ ̊;SF/iCn3P?}A"+_0d]pxZ}K°n= F_:+'V渻?Zin,:nO1L{qs@߯ԋĕE/t9Mb}?(BEff$gɇPҖ 0:ڊ6'\uɡA'' P=ttn:s9c{yR=.HD[IoRsnrY" | `ԣ.BV@r̴lz׻uۦWpj)e#X&A̍%4>!gZ2=HzQ>όQx+b>j1Q5`ҠQ(F_`A1T oTB~P=A% 2QVeMuS0װőʒbx֗% qL,DLb\j04J//RQky{qWgw3s&NnMOq~䊍8DHWD$|PzS%6sL'Mb*' _[km":ԃtI-dXoU)bE]e?rf\R[wyʰJX TW礝fŠHGZO& wRD|Skqa:p'266 =`rO>ݿ bH){1wl9i(S҇Ŵ)z\ꉼ']wKaj MN25Zu5j\Ԏ&fQD'Dc,֩$&_pY)Hg9Хi}TZ4j3kЍcx qQTda2:|Z5~IA Mۮ0(P,vM^`޼7vGyӄbIB,({1r} -EWՓi,FJKd1'+7sbzr+FAf&&[-DS{5>CF =EJ5Fz 3jޓXTDR JL/Hu1迎DRR SP0H rAAc\{7*F B @q.Ta۩D,R^pkH*E8PK\J/?'pkcs12/InvalidEEnotAfterDateTest6EE.p12UT І?;7AUxU{< w7C*CeiS_m$fd{35s(^:3Ѣ-9tTVtQ2:ˡy<|lkeaiik @ KaWwD,L{6;)¢` @v>s0,ih}֚F8~fa +$S9ginW|w؊0xWr2|C7sg1J#S5q!B]St>n`AfYfDƮjYecd$>K/ػ}4VWGL`D@.;} zPYZ"3mF3#yν?~p|x \HG,k0og_+8 :[v0hN. `tۧ IPoZl=Ō8:I T2tHP~E͛k}O駽I!zz <;/zBt[Hsvj_'tY/Ȇ<vpjNk.8FsD6A/>_Зg#C:u1lwT3&*\'5G^eT(4{V*۟ aop鳴zZa"LX.u .X{'I^Y^+nz리MjH4~3Tt*rQ8N.oO#6.P9uVE Nl. _>~E㍜'k J>=a׶?EsE]!D}Zx5OZNQT~$TSq[ v37P{ so|cڄq^> .R1p/qFk ?u%cDZJ j%Y4\P*sPSRMPvc=".adSݾkB jd"zԧM,u1+W{q:aKgcA*دNřVaRgR7b_-rN/a轻S 2mEF"kO0|zGcS.`I, ;(3#xG"E;S5WPd~j&\[gIRϓ &EI( jeGXˤp!jdٹJb[QrTW_{]j/p~z2l$`,h-/$_iڿFWg7`$0ပ/r#Fy1v;=R\vGy:3 VHg_&[goxjI 3&xNJCMy&uudU讉nJ"pSf>dwY0agy=lUq(VTU7U NZa۴D|Aγuߑ/"UZ`]j!(P1=̌3%M?d,+FZk|&V*L KEYowN"Y&;nx0JuS38\];܉Mv}uVa2gtCrhI39o&2|y&5(9qޔ A *ce7$HdNpu-8^H|!:Ǎ(8ϼkUú@MO 5Sgע]}XZD&zElpt:ǑV$"Қ䮢pҘoa# &?=Qϰȁ#)310?9xjef4+80 2."Kҩkm).gHG#$;R5GT> 2;3_瓰+ /pFc o rAɠAq ED N'0B0 A-ʺ s$&LAjȞ_bPK[J/ܢc$pkcs12/InvalidEESignatureTest3EE.p12UT І?;7AUxUy<ԉbdɑqL"jXlsRDZG>J:&- ʰJYGdIk7c*Y;k_﷿z<7 CP<'2m3?I *Q6O^ *`@!<@g8HH2XL8 Rυit7/ShtyD+h[ NP[XҩHy9m{E3 ⏹+᳠wd1ke:+cƙavjO⼄?FuQkG_x3DS9#TX~j{IE('B-[pO ' i*u3\~NAw!h!~m-Kx"pjoH:Ҋ4]+6[V;W>D.O\΀ί oZ '4EȽs#7ls˹DdO&rK)g>3oV&xozCxN0Gj@s/fȱ!'(e!_nJc/~rj@MԿMD9NpQs#XWy}8Є1]PVS^H䅯D=>才&}*v'CLQi篖s% FFǜ:b蒳c~V鮴R0i7[(%{X Edl2#zd!>0h:2c!MSaA'ÄY BIBj=|.t׮>g蓾+<`f7H^idž^P!lϥnQl%T'p.e{&4aRQ$bCTH- Mпh*7yC܈_4zö3D52uObP"r10Va.KWuL&^A Ҿʵ]0cu > 92-Eւܻ!wg(>"W+6z9v۲S˔w諸R;X.rB哯 ,ur5gehY2&zV̼a ,JGŹWZ9QStijp_ 'E;z*"\ 4܂[t$$,ϛŶ3!nc=#iDdҫOKehd2yLmJe+?,^#4AEr]@hP,(t 2x BA04Q_Ḵk fLߦ(uXJB'D 0RTDd)Ü}~{?,6AtX> q;ߤA JtEY`Wª$3H`}P8pEff %wVEgj CVċRYuv6K2 lpuZ/堹y~{D(֯(Nu͐7LDUpB%+ob@ 6&x7 .ԉWK2ϳU1eR_[gU%XdI;TSJn&VsN%9D;~MM;37rC9OH!6op&:y+x&:O.`gwpAj;o_$kB㽴gUQ<>|w)11j9K)Ҙ16&(3[LE1aio7DjۉBְOv"jS;ҮZ! ǜ|t9j\p;gpaYP-lj"[]S|E{s"qA%plGiX7)Rv`dOS۲K;9:C;"} y'W;%iWz<ـb:tt% ri\Qfr廢Vwew]!.5kkP^k(HC{̞$aJfX:8oA ri]Ǫ JߪN2`%D|-7B,&m=v)TP(Gj[47Zzg]z{}-j*]l?℟^po/~ֵ)l1r9~7QBq&:}glD#ړWR\O+q*]Ne+k|xB}q1n5LDk_1v@,G`oS( X75wҍ0=Pwq\- N(۾4K6W~?jVj)v6k0O:X~W ҺZz"_ VQʹWnGwio+u-Ä%!:KM3r̐zSv!вCH0ߧ kҭ)!S gs?&B)-`1T*e 8,b`5fr\z11]2rnGC1rG?PKw\J/Yq+6,pkcs12/InvalidIDPwithindirectCRLTest26EE.p12UT ц?;7AUxUgXH #dC#v*C*e# %AYaBXÈFei (P2e#$Hʥsm{99߿H0#"Ap/$ 9WP$p+(9@@a)G% #ZN( .k%lG!:O-2ǯV v/kY=&pU#=d\ _x]uӼ(Yrෂ0Qy=m*y}oon$04# ah&*jV[M#%.(d+2QLHYu+3ݐ$PnD;%@w F@8#b7?/s cv)wrOW  Oivrr;ӿ9j᧰ht*>!MCco&.ŰUBHb;KɽקQN cX;.#Ε$vZvtibjUB]'́SCH%nHމ0ry1FWx`-ӴLBUЭb]]ClN'jl92G^\kq?ΪM*v k.-~.=>Kut%l(|AN;9~h="F7)ou'R)OZ8V*A c=2lqPAqyiU\V7߬C֕1`Pœ[ TH\~-ÌIZ\);hX'@#7Ŏ"-QRN]Jzq{k0w%? JB=߅kͳ&C1J8Y#[d>i4 Ќ#+2 _RPw$V*-ƿh {cӑKǕ?&je{L S-%۟e 9}M{0Ȅ_nAEo['G'ےzk繎?Iɭ!+UpP~9uÜEN*#2yǏΗFS۲_橮'Vs/X=T A >/Qz>v%G=(hJZs կ}*7ǩgF|2RИW8Hm.F4w^= k0!dytLFV˚@-}85ʼ4ӓڐ\޳ YX ?Q=C5w| 6u6΄=ݫ9YJl!&UA8`$ѷb\LH6IU^\k3U$ a7.>3X /d2e l.aP9ˡq{ R gM_#YbIk}+u~ S\﮼> ]2#[!@]Oba?jlVU˯M {ꈢQ|'>cZZ l@=8ce! wT *2pӢnAtl7_j-=PM捭oGs)>vʪ+H2~e *\sbj,1W멉V^9;铲sJqVq#nq ߪ'9.ir8<6s'gui!zu8gtn!OaC7~P "-&LVKFP1hJ#ICEEy PBx@ PaBTPp. @$gv,>-jS/7ڕ!]PKO\J/N)pkcs12/InvalidinhibitAnyPolicyTest1EE.p12UT ц?;7AUxUy<ԉǿsgCĺPMl83u6f!ZD [r9XZG1)GϾ^o=o B`V5;PAD2D$ {0 N Bs | b+) P. P[\Mpz׽N&GtBݚd(7!Kd/Cnc DP"u/bqqRΨ*?.>V\ϛC6WhI~69#cqt @r& a'6xʼnR -e(#? EF2KZ$ƺPJ{; 2;5%pu%5.)`z&_Nat &j.tH?nYI7G`'khł U]UmSċ$pUZ:G(r_FtŬN+jɤt@@I'nydVShV+"+=rkF6E~g~8\dC&qؿAV5d9;SIVoYbie/B?!~ڞ!30FaTeK7 WQ 6;Mv~!ݍJsG-#{!"E 4 WŴM͒ܜǟF딳⒢7`+h:gK^=:HDQrO}0ɲzie~X,â:_M3x'+s}&*`yB#eM%2ڽ9Qzre&oYp]~k<("0h!>W%}/L o> x"zER'"ud;l6"˸41ha>iC@bVY0f(B궘dpnrTW9ckW:oF 5.Z+69yZď/X(ǽGU&nV1rZj2 ?u2!eA S45|=[sx(~ ?(PS[TBpb%Q ?hE[f `E_a!n5pEcX ^z VEDұ#kFaPq-'N-K}Rn5RIo);e?  V/'3YMDiM/d9At59yv5RPZE,9`r߈bBsn^{{3eP@Or݂FVyLf*@TD|ݣ#EfNI$=| )/i2zrR"4$#W2DM}R7F s* WTC3-QoVH jp2fw2rsP8=\iF]9s _&UwªSu2;@Kl.Ӧ#gRcU;gCrCs } wȜ˶8P©X׋N}.9B)ķ{7)aٝCVAXڄ nɮ|T- EX^b~KgsfJ({7Yn^9^2-,f8 ϯk9’bu돰G /uX@;v-GB9LTk ;u/5mgbyo= Jҫ2*|O=RyBN"8);Ȗixcta_G@#I  }R|Aap?|*oi hJO @0˽K{Fs*" aǛXPKR\J/`)pkcs12/InvalidinhibitAnyPolicyTest5EE.p12UT ц?;7AUxUy8 HcɚRC*l؊JMeHbudhJe K},3wv)qej%Z\2Rzyssq>D| 2; ̀gA;ȀPj ǎ;pr 8 E6rt`$ȀI2œbʿ |fL#L*[ 2t7U"f LSHwCK'ߥhW?UO߼%'Q0bP袽)܍TV.?1xrrl?5: M(r*rs( UukFˏz\.uueH9!6v2pwWĪRlO5?fFؔRs0ETߔI;KD_$ūL{K 4pgqZW2բiu`tˉHuY/UKLO$xll 7&(-fyWmpS\ൗ?[U?(rvcKT kN:K?;Roqݲ"9TLӎkiF:۴bf3XzU>Cv*ܨ^W*İffIQ6R*e!şS  )ikk'@@0pyGNH4$b2pVP%"( $0R#"b4 K!!k{=k^3Nإ0p:xlJr%n8)\}АbͲb*l45Sl7Bc]d<)MŔGfLi"0T.9^juzΥ~X#^sA 9}m'6t\o*Tvy3;zX$PZ)C8[N>ISo+'bn }.M=)OLgt2S0TZE ;D0[d#o}re}>]/1"^d4YiM̊8ao!c`cbz{'qJՓgo1C9 ($8R4q^@P@@|ڦ,'R|xUHdWTqOIդ ~Ƹ#Wl!鋩zGh/SG^*~eزd*{ߞO> .5T[Y?_{: ˜ }zkZtY[aPhJ$!7, }۟o R`Z}$5 >ѱCN$Ƥ|#=C;g\g+؊^~bo|S脒l]f[=ٞFF?xaetB?H fOoD7^-!mmgzעԙ3LSlUru|WeE(6II/ oc%/VcZB m ΢nVIJQ{qAđL<y]%7ӚRHڭPdj2Ò.Yz1jEZaeFd892ś24gXz)䝁+<,?CJusF~>b)Wdi8ZPDJ&{TmחA;Gu[ dJ>iM:SwԚg=sn V,G-owЏkb`tp_7Rjw=zۋ`M'<' 8_ D߾|ޗABKà8K(k|a)GޮyR&PKG\J/Ĵ-pkcs12/InvalidinhibitPolicyMappingTest1EE.p12UT vц?;7AUxUi8 R[j%bVZw2[0N(- Z"T1ZJuPZ۠h ]<޹{99߿b-B۠ԓ@&ZBOR L{eR>' adP0oŽ%`̧@fڇXtrkȗi;p͝F?3+7i+*^DUmv7EQ " ~jy64lT~kHχU~)ecgQJؘ:?+\Ǿ0*ɠXETGm:F=2~E2{k&.XOʭ|2DiPPfSm#ӣ'S 3άxx>6q ځ; S'߹UoO%8Wu;=/9Gt }`?U,_ocCcyFQpe}%k kM%) ';fCR9b: \I&OӨ֔77E08RذRL!ԝ/UEqj og\l06Q] ~uDjc=+R# Vͩs*ӏ9ٸa-DeMw*߷!m蚈pǡ%i'yEc.K~,jt+;eqyNr{fʶcKg8Fqө41-*w3<%X+AV8\Tj:v`8v ۸+*m|qe&[*$n@bh׉|c})'z^e,Ddg˵ᣯI 5ݬ*y xy$ξrQߚ:? =x]ti!0!dk(; &>rE;~Hft+ȃC1 :cf;ج+0P Pߝ"' 7~ I=PAE u_Bs7X)]-y}zY9c८3v9k#w0oeuiܘ eT:!5ta9/7s:$ڦqi~ n|\ZkL?Zd ¼%rc(Ba V@PEF^7 u۹{p^>&7*?HTz9.ܮf( 5"7"GG){l~ 2KR)7V%gmjMWDeau};Y\TG[fh*jXH79'֒RHliY,@ɹhezeAVTBwYI:,D6#{9ep:>\s!X#o} ZltvG}17#ƽP,-Na>Y*L@&ZѰ= ` RGLvP6Ĺ1ѝW,_)/30k1tYkwB'.LvۭvzGKB c/ (57JP0aB*{sDFޯ-\Hg1b{ ӥG2<C/2IN=%f 9O_5◂NM(OkK@`)ZSMaR L[^^p 8 0xB_׉T`c~iUsW_I4AQݔDND Юֶ95U=[j.d8fŏ}MBJѸ4-XRrK9lLt\hח{9 ^<+#UjJێ\hpLq ~l s{!A5efd}e؀s:AM fl}ȫ\z CS;j&[6(M M= 3ѣ"or-:" ˘wnhxuQ7~^N?rOIwVV;Y*G?ΙC ՝hj,M|ثYBOxCgrӽ-鳞\e7$u2 ( ml G3E'}?I>$8INr4YeR Ӈd6p*c\H7D 'jYpNݎP{RɤtT̈́o13CJzq`A:dMf_,y,;^WMe b2CIN+&rmB76e|fOa'&5d3=Mnekԁ,mK&+xT/LU2s2Tv6FM>t3sXz9 T~ԑwjnwT|쀦2 ac6ns\Ŧcu;]]xĔBexvw1b5N\7oCȵv:p[{lZ-e&QMP2#`2'(g*WLNF1}㛅+k5\Un+@WE7_z`[bһVLD<$\l56"k_zG몧s.g6O=*S!5EQf y+z? ۵Y3Q6胩m8a{$sJ30âڪO5I8/^_b7~䙩K{hKenYU_GH ]] h 8D1Y d[A@vo0SeX @ 30ڬ"e Ҝ*%tPKJ\J/-pkcs12/InvalidinhibitPolicyMappingTest5EE.p12UT |ц?;7AUxUy8 g7#Kɾ cm&;]B`LY'%ZSy\A#KTdVݡ>}9=42F`B71S(V`r.EV 8`!2L?Y#]+= JsVMd~cu,QŒHg(9F]k!ȋD{&9n+|=3놞0O6܋ - wU ]Agg4A 7G, :fbPW*UU=P͹$<štCM?mR]B!f|YK qm2[{4mh^--ܽ!\\oT] y' N?CAl+J-r*V+7K}u٤(k6 xpWIpe ۸8c.7? ͵I"Xc{ 7#+-LW{`Ձɦ3*wn)/64֏\W.ڪ*.k|}DziYEd>sۍڞg^ hBGʠm|lLHd w/ILyUbx]3͗ѴKxXb;f#)+ވ{5~x{+BJ+,q񐔸q04z\;5ko?+τ#ίYlFjC \.x!V2a4αY6C}n9NE:%ߙ sE)x1[iúpK/ȞQp#:phNܻY>>R)[PExzcV(m:U!Ml?優HyRڂ٘PM_F;9|E1q%-<(nlэK_4 4}[r_`(TA4_1o7qH> x@:&?~ g>,FSXH/L?^٦zl1o\;vpI_T!{JjD#p֓P+ؗMm~ݖt@4BEsX4q *cEܒ`mU.YKb)% -l)?oz Jّ+#xؼjsꖳ}WC0R|_u}A"vۮ8RaE^ l!7K~Ji;'ݑYJJ?QyTp`R$>)WM. ڬ_BZ2ji^kcr68Dޔ1cVj?QH)qFh!c$  G&gShTU5PA~OBTO R < _jpO -PKK\J/԰ݶ-pkcs12/InvalidinhibitPolicyMappingTest6EE.p12UT ~ц?;7AUxUy8 g3f(24XrE3PD(r3$(\2ٷPȒ%3ȸq "۵_=s|* 7pHm>078 ŸE K[!`qo8(rnΧ A¨P`Pf45<ųt 7E+9c|9۠&`㝖~.$ +Eyn ૊n nVX"G-ŏEA,ꒀ>rRh /^7mA뢜d5!8zYye $gք3eHdj.C9Z1m*j $Gy YU _?ڏ={q *ggZZ IWKӓz7~rlf1]ATܲ_Vuq|^w]Wڦ'-Uu3]*=+$Md{bEVe_'܋0∍uvrs4\u XjA;[#}JpI[;:1Do||tS'RWYCMGMl= +zXm!KZŁ)J w;h 6âjoh⯞ D$ֱbB;y\kɷ?j"e;>}j_'#yXMk Ie4cDυgef5^[Õ8A7ծfs=*xts܆P^"S3-Ibb`/g@lD\E*5^/y"u*PF|ڄ#M}JOc r6Y?cIۇ5KgZ8ɰR|$̷]=Df0S_}XA7*;¨PcXpR!/ )MNN! Yif L2i .F]oCDd&SGOU#qO6C 5F'J{G'zKZ8UVl_|:5B"pŸKCՏK"$ʥ;+)hzbҸO{W cMkW,$JAٲOb3F=H!跏j0&{8/_;IF C"FvL8AR]@F۹Yn6٤ʏ Z$ۭ ph~xӃG &xNҙӷ~"]MXGo"PUma$#S_Ԥ%ϟ*y&SSžgD[s״MrZnتqv9H#aỳTҴ8z<ˣؿv㖏_;=Ù8)~깶Xm-E[u֓; 7nL5 C_vvRNfBTfb`Y649e,8Fw x̤ǻ;.'Ma(Lb6~nC>Cs3]q;n<.XC_-Q>.*kjno$bW__ƋUjW}6\F\#!4Dd@; _?z,qPd$ B$@0fB/ֶv l anPK$\J/te)5pkcs12/InvalidkeyUsageCriticalcRLSignFalseTest4EE.p12UT 4ц?;7AUxUy8sAݶuD&A5QRPUF!ҡ*kI5)$[WPgS)T顺<;;|}}?$# >~Kޞ$ !@EơLGYZ8P-BH8I(`l@"7갲~80; i^ j^; qӲ͹q?T 9/Og1XvG& AY*0d>Q<\a木 s4Z&ҏ7mF[eqE1"l1.B\cK7]|jH߱dݹDOi zPvH_܉bH?'ꢼH ~pA{eKZMIж vb5(8YS:*xfɕQD)\ᖪOcjWnuUfPT"24DvP-7~UR/FP{clG$ZNSDeyʼnvR4 V!D؉A5P#FwYY3=i!Oas,mNY)}p#G׫7H8hM-X#kkӛ]h]z"QKnEw|+Ⱦ:!d5З^3إJ>A@aF+_~4 #M??>a3ı52F2Nݹ_đooCc]}EEuZ#w4:.jλ2s6Rjı1-U|Vp|㴖|ŎT4Vn]?.:_E5F;/&4RU,"|0Jݒ6uRulZ =cOCo-ҕ.g${k(cDm$#%a*s cH̬ڼ|>tD`Ͼ {mTgZzx1jq jkQ;Ƞf}l/H@ /=*5n䘫TM=x~1NU׭Byh|Uޜj)e,V ק*rGc+lǤ: Ԃ6fWI\<3[e狁CvjN27ٌi[j54c?r1_qLi-JA=}[u:-{3~AQ`0F`"T]1ĠºTXǑ݊B\T?_ ਄_uv?q %QMԷ$*Z_}rW0y?v}bq6YPNp\ܬ.KdΚ9,B=.wXYOXϛ(}[w&O\ϗ19`4păQgHtZ-i2%MUz)췚S {3QXk7-M5-x엓EOi[ʋj3T$dS.~ vXUt$ e]%c@+2~qww}'%Q~]ފOsj+f [s "8F0)ч]> ܀݈7?=^?K L7;4gA~8V$;[1~+`=n?TE}:-ڔ^ /սh=b7z)N>^o;63C2 +1]<ᒱ+LWY"w4ԥ7&fec ÿt`J v;UӥA~YS] NͲ)},5X9wkR[v{iw|'h.8@A`ZVYT5)E:q^nAaUe]id(.vYIŎrg)#ߞ}5H)0<偡;W_ M(Hn ɗI7LN.VQ[]!FFېk˙%SұMXg..'[uZGPpbVJ"N/BdT}H0w fP(**!ߩt/&q }J'5w>{5s;PS{X<Crς|YɂO0I D&[͸dy'&˶cԇƧoX|FwX enUyzLpj'F J)5=0DŽ号 ] &AIOg$=xUI^SGK|5}[mo'VjyxϬc)eX|P"f HlPZX@fw7&נfٓM SD1zGp??? 뷊oJ_S5NX |D>tEdg|,bdžWoӞP^VQ_~N Jnfh 7R#䈸xa2IJNDP/q5vC,})'Ѱ _hŁTbE؎֖i$?iϸJ1q/k(_(lO 35iDn{!J&7n\.RUQq|DtzVHv*eP d &q(}4ZàU2?3']J#)i (@@~B#QE)D`BraDgW s^+F85C'-cPK$\J/gۯ8pkcs12/InvalidkeyUsageNotCriticalcRLSignFalseTest5EE.p12UT 4ц?;7AUxUgXӇƳe-{DIʦL1B2d"C0KeaVALeE4 *>Ͻ~;?>G(X#}jh+x9}jE@!@  xa,M\8 Pcq8KHN.GMͅ/#A󂲿wMy} NgnE;0[kڞKpKo`7{aSNؚ?UUwݏV~av8ꑶw>?ZڇGh$P&̉ޤuxvد잘d LeHK{ )tE&%Q?s )I~ɝy.en -<)oZ5LR޺fe]hF>L-_/ώЙ۱{ Ly!yE6 )KXiW?--JQ1tJd,^&guCnsq:m>*ѐY:#\5{H {+"u$ʏ֬oLC MÔD6{ʛU24# ǜk+nfGwzL 8?Plo2w²(=wh, .8 vxg7^~?, èEo- 0T-ZС_{jK6!lr::~w' Z+'-p7l 5[W.M-wiQ Ci" ׸GzJ_tMY,K ^OWD:}I9Yd9C&|Kv$)UmE ̵afB {&U.X ڹ#C["siufƚ;^\Pb/$`Fu]XB}jF0>kn0SYf lR08Ϝ _8r @r_cyFb3/SvCrV\idVf[ɠ|=eWN]W`[̿ƸRSދMuHH2$8XGc*̿ 6z;彛rAyV9DJ_2&JoѡlZ S WLETs״xg]y/xɑފ[ujDa]lofF&Lj؉?g@_BỎYN)D],Ǟ_.{Imu޺-:&,3ɇtjνk;dJAQ~hsNK|V"5EU _wRȵ ^"g̘ZQVڸ>xY+虏);*UKew09W ᖗ[ ?D)f=,u]Jש?ʣuIK+1 ch?k`EfA#(Z2ҹ MuyB<K<3..`6'ZͨVh?ŧzoJ|G- b@ǡtVrRU77:MiRF }uT{ )Pظ9-y# F 4:oi吁T>:.!!ŀ@& _P(;w(@@Txl Yi!Jwqd:s^(|W& PK"\J/c<pkcs12/InvalidkeyUsageNotCriticalkeyCertSignFalseTest2EE.p12UT 0ц?;7AUxUi8ۉƳ%$EQDQe$JBPk~I{uҤ4i-3J-]˭~kh%c;ˇ9B `(ŵSlSv`ov=sh̡EA%/!"\$A\鋪wT* 1 K)\E2bN' #yim0zKImH_C`IfXxzHNØЙ/ +mܴʫK'_S࢏i6=؛zpɄ7ф̀o6vddlCkOcuL(xv[-,>22nn:l{9L.)44szKre/FTYlta=)klžV9C V~٣'nbfC㞍1iaA|ޡ{솴sS> ^j<.>Ԧz* #YQb2;t^F%nTtz?e3Ь] 4JvL#FalӨؘq/XW8m/\Ke|!sMS]_ȊOheS紗7ZGv 3o9gZ9j6'"`#Ξ7O\ùڃL]՜&c ]u?aյ-1UF\ZZeyy ]nеt*# mkb^zZBv)- ٤ޏx?[|lľdKH*J!QS*QJM&r.! 2V+97(&!"WXr *TN Y3Ӈح !.U+qJdU‘'CIbuz!곸2Uhʏ /m^}ECj@/N\7iMx̙5Aַ(wRߏo>&Σ @wKĠjo0 mV#8;:2}9 VYYt RY@ :PWAW{?.F#9BD@0}tjz3e.YiW۩ :jPK\J/e+*pkcs12/InvalidLongSerialNumberTest18EE.p12UT  ц?;7AUxUy8Ɠ/Bؗ0v_bBbTrcZ~T)F((ScbD^K)k;wxs{j#@VI0Kt /PHUub"BN,O;)ePNQ 5y`#kK OG<ɊVwE 1>dF?ݖ[3$ epoRQ Y:}&"t񯼇})FO]t(Ғ!JQw-DLJs0m-3b.~b8jlbJj8:]sGG̔gPyG,鬴mFgC"3vg5߲\"w?&\!%;{iǎѫLN9?Ůy XzsGUF 1Ph˟#BT JKfwn.d~/ V֨f\a" 7]tFxߕl=ˏ{s*5"kH UHxJ8$’p+і>|2FAiŤ˞;M{'S'gRVW=eS kz9;^ܯW?hs*vzV=0v\~AOyՁ%91EW45Of?uV˞TzxZkɜ**SLeL& ns )phP3ͧE!0Ul@v{M%H7qbey!_K.Ss}y:ٺا,4$V =걜2BPy_ [VAYr8>Y۸mQYB%B !DNlPō@@З}J"! ~dD6>lvԏo' S̫͍B7"ģq;D̬&~)R }wk!IK_e7H1Κ.1|%z^%4Ik^IŰg s_^L8w뻩2&^,ߤyUhka#1ӊ1ScF.ڍ_ԨKo?~8́Lyng(YS [rt<Qw> um>J R`b!7#JV8K>' VK(E7L4es˂oݟw u!^on/G}_l$oFmԈ{Ffg~.dck%Oz6f3E#E鲭I,D46:X~Yҧ6Hͬ7y zɿ-f0хL=zE4WJSc?+{J:}dlczq~N[EFvb,v_2&miy9 1Zbko!5:(VӜ,Щy& ڈ ,F㩯Z3ɕoY[E| ǪFV3Of.L+-{uڑ7GCIr\٣| P_##E`@Aju-w-U<%,`?0#, y~{ ţA8R,u:$ruh*̌(([mSW+7PKB\J/NZ-pkcs12/InvalidMappingFromanyPolicyTest7EE.p12UT lц?;7AUxUi8ۉYHQTk-kNV, TK-eD)bK)%V-EJ4ӉҢ;*X"-5Ly{>aH%0!abYY#J$< \F&(J&J`mf@* V+zFE &j w&ފko2`0g7;-b ։arm"ta,wܬ~I /7;ѧ:?VvTfRLkV:5e5pK ζ!_>Zriw*:Hh3T)r $NM@xg2!WbG>OFu|R6pd&سc]Q`;Yܫ&~Es;R-2tlRͮ~[mj~+.)Zs}=TՑM*#C42%(\^k ɦSc M8*o!d&L7p, d [(H."#q-;{ 0P>2 tg\H`WS<*;ޜUr>N#?2d:eCX H7 FsW٨RqiUjUt3#MQuȌCXh[ɶ_._ |VueŒ[Ed.s66Uy3ք#=$uckK`E\_9Zem#ɉ 8珸a̙ؑmP'&0%i'9w{Nޡ=\ԉ;"^b;mn2Ѯ[<8_aCߜϕo)F9@._s^S /YZGh(5ղ- Uve@iB<ARK!iAnQ_*_AITMyenH\:q<h6 )eT0fΧ;Fg\gQmʌLW|Y'枰 S ՑvRMB@C5o ymeX#@3 \\#y2Ow*T V~‚շ.칟ܕrBqz +E.}J=@R쵽 Zd'5;A14ZκmYqtZbT׼>͇s~,΄xKdS&:p?^\4.?.mFw*N\e{{ Qj|@>}0&X&q2焥'eS :eB;M]sk)Ġc4muooӶNWuKz\_ VĦS>ڴҴ J647j493yzbރU]dWw=e-_p4bhKFZ]aQWA>yCl@R.D@@ p|{`00b0IXQ"]>9=v~h l )*yP$ bP`EP ;M~[ˉ'w!70 R TFFσbQΩZ+35&1پa_qq9>3rC080E=}i^ }L#aATFSy uYUxm?jACA &>~q}ƪ6%-W"te| /to6?ղ<$Sj\㗨 lڭ;>9:qkk#gFT Y//ݥO Ga݊X n)#QCWiffuՒ%7.څw{*"^Te~b,ث՚j';VgyO?8aԂӕKѠ&OQ[[-X9#ȿ5q̡5iD݉'玾rCyӪk8k@(Dmc/T"op$ddq;W;۽Xex-QXp`U6~P9 \HQrVvY"aꫛjNMx'St`5_ʽkIB1w4롯Xmer`oҺbCnQVNmD Ƃ&Z@B,x k\Q~fP&o |'}ŗK/|}PB52ˇmS3Ꝗ5!̇E،s,X;J/cL^pƶiEPYriTL{Tof!uCȝ(A)[D0c%3(4m_hcx_ٿ NDMf鎉:*cv-rxfg VGY`|""A608ib|/Ωu^ȾrhJܧ-=5Lrύ甐l"T@l);i~~SaUM8Ke50S5MVq6|,w°2}-Nձ1YiCZR\xFXi" tV5Y%_P|./ _ŪoX*loK^O18!"LQժwָϗ]otDbݮUw; ؠ&aDp~j]\|&[J,GhŻoG O*Գ+{%5;Pa=W)v$DڷnNssr:ݰG/qQg=|߭[ ._ss\<ȊcPFVS\qXI V` 7RumtmuoG 8@ @ЉIE#0SUڰ$ټ+k `XIٓX'PK\J/ cg0pkcs12/InvalidMissingbasicConstraintsTest1EE.p12UT ц?;7AUxUw8 Ǔ_"#GRrTi]5Q.rՈq5ST.)zQ+fkҒ}}|s&Ö0M8Upq{`v0 J9h2B8[`qG-w@ah(Ms!Ő!JD/9'n8eWm΅jHVג"&FTx.b-.A׻O~dy1NmZ|_+IEdOh rS0RsOj=hk]@Hx+k[,ȿe9BRvwH|EK ܔoU$^!Ѳ .XXrpv͌Nu ;٣?W&G߻̀;ykcş~6B)MI\+=/%dIiQ;л uLWS1>ˋlQ{f,m8w6p5Φ;;^W3rsR+cQB,SY)#\/ JGMr!ԾÛ|dA1 i',d ݏhȾ)f)1 CTIνn-G#ȹ[c)m/J5<t{ ZqfX@8K""RjN|dMk$Z 5K+3<0Nlx5X)_|1-|'&]ӋZISYU "=1h?áxBGr7jiIk@M-q,+{Y*zꗾܮK1YM4M_<]y3Wx?fǩYD'fD7JBvJ1S)jIvz}e>AF %uO ֺm+jp4/2AYv`)F0 8q38b4(}Ϗ"E ܛQ%۩v0Uu* mgKp犏z" r/|Ԥ^)b6&?{Hڏ9=P4Emu$. ( "d묱A!:~ 6݇kN\vްg,kw, +fy]P,tqYٕ),]?*Хc{^]4TT,(. zrЪMur *`G;Li)W zDQ&ZZ}mP &ˍ'ǀ5#`H7Ϩ*YDq#ܖZ JᖓLC" IB!s3¤rZ0z0H!huv: W$um/][gůxLf}W@W*Ja&ۮMJa脲K*MlФR&>4Uj\&wbbӋco|()hM* U鎱|:!PC^󳘪0Z@Jw/ڻh\%\Pu:ζF]m|XXʌB&u全R NSwZ3:_*LWDs~o/W?/ū](= nJжɰSP-G[%`(L}I\/WVn./ lkq;W0zz>Xժ(ԫeo;OUpAMf:~fYur)Pv: ^gZ$i]O=aJ)Mf #\`܏YkeV^)>H/Ax Vd8M\-B4@fQͼ>xzȡ_Q.#.nm08۳e$/FP$7`u4otA Q1 ξ5!d"v{!)!aZ /ʂxKL{k5eoEs<1jb1WڍR۽R;F@/oPVכ'7X@#o5aǂKz֙-Zco*&-F,ȹ0$ܣU`Ýe?rUGʋ9#Eo7&so޲##MQ̦Ch~(_|F V^Sjz~m)Ԕ+2Et %/|p׏tV%꿆GbgmLD7f/eqr#s$sI{>X~|O 0"l!GiX{U!S&u +vwfZpb>~dTh%yiXyGc>=!lp=DOWH=!\h< hNuZVh$}5<# enr!NV=kL"ub1X*BDA.@B!= {=GR#!bD A GD(-p0c 'WT EPK\J/Ӈ&*pkcs12/InvalidNameChainingOrderTest2EE.p12UT І?;7AUxUw<#=CCCTz5b5U8յw)}5jT)B:*CjUViPι}{y{X  KAa8]^NB t L#X ?+h!rNJH((To DQ@n>rdҒ ƻuՓeXƂR{nܑc7tܤz[u/]% ;8K*g} k 7TseM|l Va Gel?D(lpKCCJ?5 q % x$y"u-87hbŽGVI\nļnvf#f/osS6{\;K،SXDEl;jG&|82J,b\O攴\#4͞ 佺.)Vx?k`|W($1I{mBp(ma.|hļM -ܮ m© aqU[(l6HoW6o[(ɃI ud]_(eEٷ= }`͢&RӳM8?U`|z(5rjvgݯ'}!"ǟ6r@>f\N3Ʊ͌q"TrD4 1-P憘tqR\s|ʁsZHw˹g8pc3:r \$V:gzq7^ԽSfs"q5b[bZ m4+uaK\RnDP5(;8n Ec7nJW3Ϸ^T|rxu i)/D,[$ܑ)b(R |1;W0PwHnmB vm\p$_"8_<9`)ZTfϸM- O:6{Elh !w^o 6B6o37evw T6_/FK% wTv:,͋O]: m^9O t3彟݃/u A҉% ֗:#|$u.DԆWv8-`8f^؃of- G*j"gYni{Xql{\㜲}<ߢ%PA # ?oTn1bEVzElpO:(m 6IկvO/N^s0F8?pǚ %5DN/fJ_ `[bۡh-v-x+iZ5b (+m])>;QKZYl7gΏusz^9AybbޛdErr\om|{dJVSzP!}J2HNBGR6z:`RFSYQ[K`cdb(px^4"~]UĎrS7C~Y_zGg ~Kg8a[&V_ b#/Z˜2Gm^F%B<ca- h.{q<:8owcw5b7~|'/ }J9؛KijԶͪC`U2˯m(Mp`yMDʲϽw1:b5}WuцV x߱jUr]C@ }ǘ*e!T]0C( /]t=W=I_3jb5 E~tn2L][ȑ[^#9.ɤՂ!s&W"X:7f`d=hg$|@p$AŢc-qSMO_i1,^NlJδjNY_cnFG*.zfSQ5 j9$6IwEKHGL*m ^s~ᡣOSyBi F*N=QMŸU=mcIcVÅl+[? E,!=lj9M"=eۦ4{c!lC #l>}S)::W5!FKNK:7efyRhfÝ9~opp|ew M<Ďlϔ>q]F^| F(QzZi -W8GJ(*$ @ *8Jb}DIJz)ѬeԒ"''SW"2PK \J/Ӏ.pkcs12/InvalidNegativeSerialNumberTest15EE.p12UT ц?;7AUxU{<Ӌw33%/ s7G sWNbqrlBh-TDKS/ k\18nm9;=o^KuIJtx!ot(߷!`~!_P#3H 0񴕵[4B P"_jb5MJk"~EL+ %f, X/?`OX<6ЊeP$Y͠9@A,I#.^dF"4\HKiN s;0E}$jJ]Udu82&}ԕ993|^ڮCD}vlM߁ͣBR|WZ2Ǻv&jO$G3ApiG#P3c=.{՝uhL(ՊBImY#;}]X'im|'%&G|98(QA8P*% u].V~-ŷ7=Mn=YZY>ko>c{ `1/&fHDw4g]^} y'`aVT3uA<=&Fi$8l$KrG~}u<7r8xOXR05ϔgMŲ5zD*ik6, A/!CgG ʛ,~i_Q,,$9jjpè iݟH ՙc%pE䞵@pJМYWK4>SՔ abLxS/h5€@ (  EP~ \L` {jyж@: ePK \J/J*pkcs12/InvalidOldCRLnextUpdateTest11EE.p12UT ц?;7AUxUy8?I|ǒ0FeF1(Uj%(Z!{c"ji[1VKiQK%)f\nwڧue3eƟ Кwh+M$5]*)KFzFvLVJ\tYNޘsD A0tfg)BWy眛(b$R?YyՃ^Xa%HYLzGY;G9b <vM F_/hI;HDf:41%LD |h %E:ˎ  ҕND#%<%XUJBjx9o3&5 ~>7F`WDf{E~l\i-]sKB;tk.i~kCZ+:[֊?&?6~]im"|pGNP/J!}2^ lIY1t \B%p"~Bݯ>SoNVyVOI403tx ps욖u1-IZ= B&m 8,xj喔~K^*Jj&tʛ=bkA> *ߨ]ϱPhoK YP@M deyZ|+@l\AKٶ[ŋAhʼnjIXטTn{=wrhHAg~6q$;$02T<_x9 dH5 m?i3,x F†(S!:^pMjǓ2Sfbg2n>nR W¶#Q#uZ9XP#J06vXeatL]>kȆ;uLJF?p"Α|M%M*o oXpsvOKaR_oXBsj/aə ut,Ҝ *kz(Bj5JOs`2]ƪEkaX畯v/% >{pC[6Z˓adT.Z`H`gybd b4]k Q}:jkBǛcՁ%^$J\AEۺx–/$,ݥYlt}0:QJ [7\[P"\1zsSn4+ۯVũD|Te4JkNlcX tSG\I7F'4ȇC}%Wn<\bKz5=YO Jq.?[IkӶx\-䒹׼QPiꜤ LIبJg5;M"1=9s\z25Z_# L?F ⴿL9MVHLCV  :;v{< * `bs 1A:gѶ:+[\1mҽPKq\J/)R4pkcs12/InvalidonlyContainsAttributeCertsTest14EE.p12UT ц?;7AUxUy<ԉǿs̄0Hse- 9NJW&9 ua\1dkC9F~)h|^|iOP !"5I"A(^!4ؕ @ …pC-/PO3y84]`ʋ,qd^UhS1մ=w|[M:+Nȡ+m}<2%Dֲ3( 6RdQ6=TV-Q-bE^khu>~hh.> +c2γA:kۊ-ƣr{4 $=/aC_Z?ځw>$kYW)K7g9R'y jJjnV3qæ#edB4d2E]j<&4b ־m}$P䫋}AevëG󪭹k Y֥zG=axͪS%) {CA̲r~|OEsĻHv|`e/pjQ?ac$c|ZAe~h5&:5}ߘ 2 wx,o `k/ortZ]'ٞ;}j70M&>t{a?,Qݽ+uRh;73 {o{jPoRHJvl+G>+&G #Ӊ RM. l;m.yLe`%$0R%1櫘wNm6oVZ(1_Z nb ^40%k5i*d5Ӄ}.;Vrۿy07EKpdevEZԓS\j.!qj\RS6U(t-\惙V4]^ڙ*h+cK'ňC /Fo~ުH~TE2}TT.7jKW!WbVg'{vzd}QYU÷|ww]wGNR6,b?P⭯_XXRH/hfWze[09M6'B(64*iη3Esu}4= v\^< 55>B**bk 8 $ y= Aa( */doΒ=o"XB`DQδDC! 6Dt" {a^ v* RQqhع@H 9f]aŁ\f }%O6'oKC'6P>æ݋Unf9QdD?M q7<<YüO~혺( Xh˨@u Al<TCĒ7HnEPc^I`y!ByK3=E8SB)R GE=eEr*/ԭ5m[Oh,9 g fDjK5`ZB2Üw))>Z?~'y΍ܐKQMLk:KET-'d]r#P/{L Q+9^H%a w:Īt ϖEWMJ_׵Ҿ&4_,2ص,*\+W8^VU6tս.R_sWOQMP"IgS6ZZlUG 8jp36;[Gr.PPS0][fW(xIB B+A/.kU:8M.>~PM e=ՠ+2K-; 軨TJ~4ƢS:F<ǢOIn'ktTvό!_7Fc2J΢ ڥJ$b*i7ϴ(THGZE{XL,"?7*U 2kZGL[i*{p#~J &)SS9o=2u_x|NPlIsZ'lןjL.&B ۲,N'WՠlPR*`\<4O.Msvї] }y~ucڏ EOzzhj`z36陻zH "Yky {5ZA5N|9# aЛGH-670%:% F%^PR޻${iXGC}%r轆8N&AeYnKu-ۧ@-[2:1zG/L 3Jհ#U6#Hj.oz:A8RO+sCu;h˂L")B>n-!ΚŲ3{J;qZbI鹺Otﷃǟd$r!>R N@<@]Q>KG@aPW Y~h=Ai[h#A#W{8&OPKo\J///pkcs12/InvalidonlyContainsUserCertsTest11EE.p12UT ц?;7AUxUy8s+ĤqFQwζX$fF5!4qfiţI;t"V꾪Et8yvwvx{~dc4#KJY HRla?VL:"@@q F B0Չ 4c"O?%~Z:<KDRl+L6|]&h3gm Y{P{eS|sCx=l_lG- n.N RΜ{@rE)g~B}dI+4=Kʬ?ol?{}EKjn.bd %Ajz)&Y{8kpnvwQD۰cvKkMj{zNZ4aҟ,] >,{.qS[B^KUchI*pgXRhY3xT Z+!\EPymKhI޵[Ա\WwqޖI+ W{2M#d.Hbrg1qKoL,R%32_mcO_~ywOFH1hl8d:\ #t:{ ]Ít넥[9UIkhډu"FN?'drI_l9!ˉYbYWS34AWbĔn\`wz%O&C!cgIJj~l^=qhv=~!?6=wЫJp0Z L4cds}fWs9Ge8`M=ρ)N֤YA6]HQ^rGۋ&i귉^'vy†ۚ¾O71Nh,ڜoIX.A\dS3U J[m3]KGE{@pCC`mUiuU {9fcD%XMV:%/n0 q0 P(N Y; =U‚O A?EC TmdBh µyR+wK +UK BVn'yDJ]5<ӯgVM9ZpKGRнŽWMCA~u1em.,p(lj ]7;Bqp"V ؏;y/h6cIiBsqXdDgyI>p kк-O0⚃P؂"t ZQZzCutXM)E4MDI3;2Q"?= kdr<VE B F>=6o/ԛM}=*óθze"{ }^00@%{I֏K7RqIK4~VަBR+aU~:E#<.k/.,;SqwV TuHr>!W6xy(~ W(Łx_=qt-WCݰͭ>~#VM}atsqr>SE s䘑FQ\/mEE-U5usl}> 4:`@xIrљ!b |G^2dyqCCc={C2&7eOd*{KOj]shLeFS-%BK_I2|(tgy c0>zL`c%F%͘*?Vi+&snjLOK m:Rlt;؟Q&kʭXٴʆưsݸ6"\=;}'ntדz?b";h~^aJ_KVkEi*LdY| MZ! =7՟bu`ֲ Y36ñ [bƸwn)|6LY) Yq>!QR= s1K8c۰F{ڙ+9= r{b*l*Vcqékvd(畋񀔾ʬKc:%lwfFQ8Z"BۖXlk!x4)~f<lf5dsi7ښNphdgǾ .3FDZ. #R=: x'5M dKg3=d[h(BTSPC%GQf"gΞs"Cx]ߧ{}"!=;E@}`q|:+~ A=ƓA 6 7 dPqK봴cV)AAÆȊnpZf&Nn1p!Updץx2U]4`=+B-s>邪 S?<]!)u̗dhک//C2Fhpq5y4 4*%Ŕl)Nt< {'F܊2AO菌{nB`Kb 2g yQ&ԟ A~A~dnYEmauTiiӝp(A4fʮwԼ _iG WUJdWDNcNe/b{4ꥼc{p5J59aSN%؍I1< >,(sO1)]^Qk:+%kt(\\9:l@pæ~C(g*]y&ꇍjF*xUlCQDWW?>?<;lKHdTKʨgzNSW?pMې@uw^;ؕ7P@i%:uLhXݫ9FGoȷ9vIl`➩ΰpd꠷"AϫϛI9ޗrkʩܐ88-w;@y762K8cq0dWE (% jWFYq0)E@0@p#9zW"<ʇN Dj6?eR9t" ^j\SPKr\J/J,)pkcs12/InvalidonlySomeReasonsTest16EE.p12UT ц?;7AUxUgXӇƳ IB(ㆠH*r# HdeCd1e( E6( Me;*CHJXP)繷ssoG0 jTM)@g"gCr!*FaHY>NA>xS)CrYGߺk>KTJ4I&9rYoe-T1,B[QnEzbRL77NT%rK%_Q>jэ J'LgF[!f1 Rg&V W'͍4h|UL8_\3 !FШ ~A ߣqגCrJR3>/O\ 9Q;7ח)(oe)GͺIcp&^459i֚ShÄy)VW9ڶ?Q@C=.tf^Ck]Xz]'kn>{S3a'!Q罬swvl9N[SP']ZĆ"wkSpPaBnǂ@P)/Xv9*gSj.UL7 =ET @l=cC*M2m?i#O̺j[I $9ْɝg_vj:\A0Dn yȺӹ*92C;b^Yx톇fWjXs*^'ع*m(z ~ɩ}Mp(8Bwh5a;l_r\qM<RDQ5#Ub2EgJG͇<8%a|qt 4Crw&кveIJw_--*Q~hv͟5.oVҎ7S{e7*^Ygs^ss|C Yꥺ`]DK{$_n3 MpZ9& 872w /d[d^)BziKbw*+l_M(>~Cd'1hjx_DZ2+O'ܞ}fWh:YEt'MAM7 HB+|C1x-[UxvHs!"1dG\g |F% Ę$?).J=9+1F`a]iG'lN÷bP~#5*zvez6i0KJK|r I2 < ƦCNY`W/Wg`xy/}Z?DR@2Gw.`FYGItי[2$&.iw)(t](w0BU)iuG-`k SᦲVL@L^/nvZ2dBb>?`z[uȂ EY3u|w;{K:4X~EI]ax%չ.9=Y>i_΢J!{1Wr%gD$l5U+ 6gԞ!4ڄ\L[5xpeF*N!T`t?+%4r@z~k7t}6+:~|0GPyVy΄V 7vcf4Ϟ>vmϟ{WcF-arлEAM.~)O~szG US1Mby3}%ѓD[dS yL[7@PO/ ET_Tߥ^4M_!˜s&pTsGUK?R ē8e5EzT]$GZgW7V,qϚt.{R]h2k?ERJx``OIo!r%&:| 1z7 `rWgͬT7TgtDy Ë Do/s Е9. 9p%Q$XE [W:GҶ}Q/]:UWDku͊ycu=I s-Rj^{ yz ň[ٽZȏ%Oi wf1CbaG m5BGJkOZ<>ZIa0hmSEʋo5~Hq (.,9k7u}`Vrh1]ۏ+$VL;ˍ[f`O $w'X׉ oO-vUj?'̓ s&+%c_N9E1{#N?}C9‰ixZYqT-*]ޞjRUKQuO,t7+BZsS+7\3Uv{XSĨ*l=fŎQ; C\WcC/Z\4U뀞,7{O"{oƔj}C8x8VV씭^Q띅w_ x;W&iva&$x1v-ɨQsµ(Lj .Ɠmr:je1'IIFdWeV#~: C5I@rm?gی&>F#!MăNddNAtq/WFh]zS;H\5yCuҁ7?1b4a>s\QJH+ޏKl8p<;afY_5%]kF˭%3y񾏶Ԥ.Y؇ i9"]eFa>&tT(l:\Ҟ0Pl+WBپAGU۰ g8igИ_[zLbn^"\Xʌ.tߞ#zNz[_9Kdu/2 /Yױp5`ݺz9n"p׮l#[fUKdE|wF9K+}U#JIx 5tEBdp)&,ڮֶb_Ѻ*+N $ h=*z +!L̢a ut[YBD|#˺]YPKu\J/f)pkcs12/InvalidonlySomeReasonsTest21EE.p12UT ц?;7AUxU{8 gc4"sS9R^gY )%jC1CҌaY.9>u}~<<C! E$@^#!0k`ӿW""X{ v B" B"( hY;:Z Koc@o ׿o0oiŒM ޷$c'8R"vI"LዹW_;}&_XEK3~rlVEm3?m9\xCc#Ҋ̴EV[B&bFߐӰR@Y_ FO"l*T23"ǠU㬟4sR}X^A{gSijW-n~:m4 >>7ᗬs~bvԫ[ωsw ^V>胩`\+Lg{ -I+>~1t58`..QdFF(vG G]>9tQՂ~~+qbŠZf)zk&R7^h\zDq%PZYXh20Hx3;9?m fa0t?h6g/5xn *&ަ2*|+N+)Lu;|am{des~zoZy&*$P){DSD}0=[D;kk+.)ց_& "Lgh%vȦ ]3ǫT*"t/f ŽIH [1eȟ;a îB6J=0LS3C=1LidkC ˪ :-ܰΉWҬoQO z =5:Oh%(6ZQ;*H\8XU.R.\]\.׮AX?k6qzT!l>C.U:oy=߇\S.wjZ%\k}.scq 8|fA#.]=-dtTdQD?AһD BPD`?("<_7?È"U=}W3i+L }3 ?~KN iTjJb fYP~w"W(D MХLX?*fsccq'T}''ԛ[ zdCNn?0o9ĩ H@kH4?lk7hXks.,™VooIepE̔}luԑ3t5qRsd]$?y:7*-_͗/z l;^۪68ĺVyLcLDYefKB ;.S&7QiUŞ`̰*xfBN;ύ Xқ=L.a J 2~綰 ؋,($|a턕.N̆HĪS.0EYeGbtv_K0Zك DDӯXW'6 Oo(ʵuS5O[z_gfདྷ:еt v#枛ݚ'6;Åx*k XQ7?~Kk5QEW-GM}$c 0`@4 U `FPPC 0,cQLVUt~2ifbr PK\J/+pkcs12/InvalidpathLenConstraintTest10EE.p12UT "ц?;7AUxUi8ۉYV]IPJRKAv-;VTZBI[QQ b(ci--<Ͻw|xs{DAa0Tt>? D!DĮF!wZ(DHЉ'!$> )N+%U@"uR0^ؑ`af&,(sq3˖K> K7eyΡBȃ̯֧:9w#Zk/p¢ɄlUW/)P{;g)9xkD `aGk!w|.+y~|s8"~Hv1ޓwþ HhAe^4X]b^6ZFhڽ\? hGf~B7HN.u,;'j{2 A9)tP7X&HYKl<,sN?n7wrVn;7˭_ yNG@`3-GS<!yF~]r2P;-i]d-oE ̦~XZJN|D_)Ǧ~_(KAnm44\ltyn$lb0-l\feJSUqg11WK^` 57ZfQGqo!-ospQg֨ mWыs`#KIJλwOSsP"D</)D3$\7 !RXW:JU#ϱM"M /PKf-ϥqTҏ5NaJݡOѵϞíhd3n`L?vT9U_g^Ug/\?00R /©o\r̉u}܎VuM,Gmc e SvB#2A'79۴V?9;gu[x,)d%#:%{ @pNtHMvJ]?@M`r$kps=xA"X<\~PK\J/ܼu+pkcs12/InvalidpathLenConstraintTest11EE.p12UT $ц?;7AUxUgT  1TzhBAP4A&Hq(hBQ" PCUPJ\:&.aٝ}~{?4  i:Fe.$ʧACȇ+вP 0- [׏ \ٹV=J2Y*4Ml% ֠ɋS!u MqXÝ= P=Ph[2+24_Iٵs,XI`5f_ k Bhl f d: ҨuA [\Wy96n,(#5t<#!FWCI?ۖۓV&QzX[|Yh)E]FoT4yŲ3H_ ׇ3}+px+Ue#̕ǒ Ɋ~97-L\Lpi1𪳑cSSvh}cǙM~׻/SH ?{.G6k[-k25:VڡºuϘ᩻rrgLD:-Yof&.lOf . Lc.wν'.l&64-sY8^@]:˿ߋ : jYPä3sƑq`k* v®O*UW*2sG 5W u[\]I0ǔSȳ'3oY{lg*%,Ư8j` 9QyTtD2w̱,s06@wN]@Y-=xi~ƭUe[L'[e~@5ߠ0%i΁y}@)BS3X&JkN#F/},D1 9th8 8uz4p1>,8O"N~Nդ ߡzTczT]XGSq]\TЎ{%\ᵥzԴu?|ZotWmF2ǕlnKn]&òR˟wO.G>0vt)Ō]N |LM7X.cKd̵xW{"n'P2<>\߶ *nD\g2At5=zl$!-@+%=<:,*{"?ޢBL9zk?vN,35%vwx@#SKzX9 N5*6j1,Z;Gߞhwպzr[$Un1vN-{RRt9ÒN=`A`˳xpݶ6zeٔE m]zhնt#1E*"ZGPeJ gEgK9f"D3!%[0Yk4\9!@uZ[?艁,0NNۊ>v~2玧B0L:{l$8 +Qw˼z#C:` ,W;J>9'MMNLRڭ{W KJA$Y!8\9{O G pP/ <Z@ Ch  ݸ$r09Z?7#mF\PK\J/`+pkcs12/InvalidpathLenConstraintTest12EE.p12UT $ц?;7AUxUgT œB&4#=ANFLh„(E@DQPH!2TwP\a(ҙ,s·{{1`)6JQ8R`m: k˥@-O :/ aa3paXN(G]Bp D# 漢<-a޺$ZǻYD9j$(8k`̀J bs. 'a]nNrgMȣũ 4I}Y&̨$B<\t^ȿWP&(IJP*[9v܍57H]Of$RTtn^2;WC+Ľ%o'u mid0 )鰰;ċwUĽ27F#F)0vU؂3Ш}gJ/Va1LYiU}_Lgv W^ -׎FX5!3L*D9q ^Vj.0@" D "Vq;n6$([w&:[Kr{-O=砎wyM,dG/mC^% ȇ !/2 8鷙1_ҴžpulUZM&kGa"j?Rݘw6t ~ˎ\0pKN6;sd߭Oʁg_;7C Uٌ'(۷ fr"Cj.u6!l^zi%twgUnΙXG} ^[̢)sHׇPW`󻻦n9,}_ 2Qxs5I{`wdobaډ GH

b#o o;zqDM^PK\J/Q*pkcs12/InvalidpathLenConstraintTest5EE.p12UT ц?;7AUxUy4ۉYD4KC1AN3(K:UJgE-K(mH؊ZZӢ-:xN4:M97o{C {ң;H$ECiC;@hC<{"Žg((|~; gp QGz[vW$OY~nZ\y[tue#)pҜ(9m(dc\uvn&1qeuIwKsrK=bpK%j }ZHy`o ^|i"h(~k ޷FOőĨh:b˰{xfPemMqw>E,1I7b^:Sglv w[ u+"DŽƱҊo]yoo7etՎ8 achk+jsxdfs0Xo 6,泙mXFۆї`[bNm +4s='~k̮27o)'=җYƑ:T6>4Җ䲺kHy*2ɈYezF!QյSqr!PZr J=e!E 4Q:|6RSpj1sOMD]ۆR`ƨ_[ :WS^opX?XD%:n_23c~oJsƜ`"$ҳۛzpktbUEs]vh U .tJk5{pZa7b8J[_ c(D2uQǥl!\ 6#3,MKJ'HsDžO~,7<Q"錁ᤍ(MԕqnR-@Tesl.(<$8XSD,Vp5 @h PK\J/vx'*pkcs12/InvalidpathLenConstraintTest6EE.p12UT ц?;7AUxUy<ԉǿs2fmq *Gu䦖3fr3 ь3Wr$W#bYWHrU1bXz~q u`RJmGٖ=h/ЖpkjaF!W0U).ReC=:W˪[㰣yKl9fdRfqf{s?N {{mn]d5]O5jzyO\횪Z688#~Wv`vK=Wy=牵~F})L˗}OY8DlS8i=A)f+4-3ϮITJGg9vv۳)xymRIwbPY;+شp#9qSVq#\BldwVEDzV଩쬃zz{KeIW9m%eIY  V o\;Aa/*!ǡtđ-r$qCt\/ !S8BqM!=U}KYD`]o'a/ Y/α(= ۙX37)?Bt=#\9%i+K#x,}LV"Gc.KUXFΎm䍣7q:#K+ʷ?:5h[C+u ;D:[MUh+xi5Sw+qa̢2lj5a&N>{A wIB`yğڕhӋ_+($%4Pà io3gODQg[ASM;{- d#1\B+Ws.pnumu݇4 jYҦć[AqD'%" W}/Z!{v2 N )rҳ_JCCFs֯lɎt2D֣ba{ZpRc&Y1V:rG쾁ꉎ ]}g:SS/-R{5Wɋrz RHSWZ8cpVZ.CӅk{ ]9+ w8 V26a}I~䨥G f u>c߂ DuGXW$50Lnrwy^ :4_UN1gj=p?Qv+vU EcDE :Nz9hJ5 ߫B,0\RX5Αn9-hu. :ڕ/A)͘ x^WY8[ҳ$ٵ" 2p %h&mg2՞g_::u$wħÀylrk}8 PWw|QR{DTe}TYrr5P B:dVwɚi^zG =ˍܗ[3mj>oIq)o +o.^(QQ!ԡ%&.tQ:ŖRB{qn{T@<2ΦVص_#~cn.v{Y>Ͽ|_G ;n}Zl d!G4hCuW;'anz.PfUrE<>'<+֩8"9pLJ0X/b,/pK8Í!1<) GZY>9%*)7)2'vF_uE^C)\e>?sցBG=fGªʻ7m>_zHSf|ΨVC\4^!A"b[ l"٭eb%\sZ8 S}[X+j?BQR]$m@*ݞ6?5J_@*e"z=UaJ䂰 @E}=0$:q^5Kf~2y:_w0-:R c9>3e9o1f"5K%TjwܳZY"&?~8Ź`ݛi7qkr^9}=Gqʎ7 ; IW]F-bpJ97ߺdڔ?˴6Bsj/XK djo rYt/ pF!ܩa`~HAsʆqZ(N*w6r0D ,9/[o0He B,AdP$(  :T'I@HB0Tk0t7x[P1䳴 PKD\J/q1t'pkcs12/InvalidPolicyMappingTest10EE.p12UT pц?;7AUxUy8ԋflSXL[N9ֲt1ٷCdR풱NcoBbB"23 K&#HNA1y{} &8B#:/:*«TxŁQ!aT߁u prp 8N*j,Pu.C)m ~R2?߳᳽(P^)~-+,sj|\0n1iɵ57.akS9<{j)ބWU\ێ>[^!aٔ(݀(PSйZaxX#;=lhΌ8ktYE'&q:m]ZBâ$fn~s|;xܾ<(TSd(/8B WDr+[dKd;q ~3l.̺XJ)c[{*<F cܟq;+U,U aSAru^wQ (Y]CektOzם#-H,Î!J1WN\n/ kQ5!u%C9j=n8/f@8 τvz:K;⟹23ȃM_xY.$(|mmͧ2x}^J*5!O"bJSdѱ=G7 jH]BL܆G b ԝ8)[Qk5A\{_>UeB\hzb4}&bd| "&~GgW}oOK;T:R'@elDOv<: O49!H("u>cot$ETn29d>Ũ#UhK FPdmP$@@@(u%аIY1 TAeQDP*D{{ssC vɛRQ =; C} dRav{50߃$HńCz (T̻ynZԸ;]9_o-~g%R3)&MǪ; &p+};xE=<0Atҍ ?9R|) gԱ1U|]$WMǷ~i%Wrx3ꊱHh=ס0VjSN 4"=_&B^eEiDx9:5H ?n/@̙Ȥ w)_Q%Dɼ ZzVofptk@{=6湫#WFTn?4Ujbd33}G;c&g% i{/`p*lߞD' Ia _:r_)SMWLjCN]14S2F}~W7ߜ y@5.O^{xVg_k7SN'+,^q ]'lex-]Ҟ~76+_@- ’\6{ƢM˺HF+tU? A븒F_Fx}SW;o6ޕY[||,夠p7O\ ]sOiQ;ϹY?7]>s^^yM.MgZE%E'{Nx̮$^EîXs.Yx@=^ɡ-%j٧d=Վ0Կ1Qo|DVcid/t䉅J,`?!WV.[Φ" 6?duh p9MFB{Ic낑-ko9êgX`?pH@pe^1Ơ1ȷ0KRzL27V3fg&PK@\J/|1'&pkcs12/InvalidPolicyMappingTest4EE.p12UT hц?;7AUxUy<ԉgs4c1HuMc1$1QS30;C$\?H79BD\k_﷿z<7 ^GbDw 0πc;GicAB818n0"ֵAI XD, y>xP`44 x䔦aЌ~DQ+.淆2 Rgu0 7,e/ގu vRI@p3&< f3N ltt؞>6yA8h42枏@xI ͡7-%Pj_ =j]3gQ%vw59j`+'ХZ^] gʀ)]7kl-kqJYPAA>irҚ<m`x;[']R:| gXzQGmTx/3>jl4;.ޟ^FFbO#(3o|qsJz7cZmsvɺ@7[HO{0xŒ.WԳ28X-e`9QRf(~.|/ G9|,9D>FN1M.ùې!C) fj]C{~R>myFX|ɿ)pp:ˌ%w%q *FܞHB>RDѮpK qnK.Y Ґj魚QkBsUNi=f"i73> D16TF^0Rãۅ(_iE`3$nĠ4!_}TI %#F٘P_}g)Lmc4!p[V$ݯU|I|'P#PD₊A9I_)s4a0o":i,MfsĔ O< V[u[l(zu! e̘$us"reܝz<(ÆI;Uƃ):;_cGRjw=AJ_ܐ!=*Yd;*A5E_e+OۣYgTcٴ*IN@f_zv$gnjiarq#م%4o)x/1&O\fGcF0ns|WICr+X$zՐt oK$P|v C/_${@BQسe! . uߩ.P;uP8A㍲Ҩ%k]; ͬmxnuV]h 6_E s$_9$6 toEl }>3>!?>*r2t\z V 㧂+ڌU)>aw@j7fB!*9*.Nf*Όj G&{kJ+st+m?|UNOo[n|D=n]tgHDٙXOZ)WEYEul_dɓ7~dfHi&h0gYcx Bb"'_Q^ ;9+iG& ^^\j7߸e UA:߁_֨Em{? I(qt*xiB&b@*G%8k Յi8~{\%u[E]=y/[>  Aj5#n Ck&0HxSQ;<:{,Ȟ6t'p"='э#.z5>Hƙ:̏k]ԭZj;\H^,FXܹ[3Wuw)vy+fvؕ}r[6j;whSO@R4EAϞc'=t+ qoSC!MUA$PH E.BA{ AH@* (r{:]Ц^5ǹZ˾LJn+YPK\J/GZ;1pkcs12/Invalidpre2000UTCEEnotAfterDateTest7EE.p12UT І?;7AUxU{<ӋǿY52bcJ'"Kh,s9K#bfGn\"ks)DnI ^9z~;|^|0 )0@aORл4sN0~E =$ aP p)(F"s'9bAdX&Y3dĹt"dĨn^AZk#[;`h@(88|XIR!irQ<|V?E!@*<-7@meQ@CsT@k9BI9~(T9jY˘J3l6]ڈe?Uqp+kvMRɴAԾg7 <853s.9nԙB2k@ál;M^2szH+KupZ僎(KYEbVY;oGkNx.mŘ3Lt>~3 tf&cd}VR|t`-%FY3nvN3u|E<]z7H׎mE$׼DQHoSg%lp$;^ |{uj`7ܣ[ _0BhSkw^O QOC?}._u4د5)~o#ma.2VYbg|T \5bV Y@-Iڸbl 28fȸ_72-Bc%+;^=yre)s'GCaʂ[>A琎Grlfk׳.-wZ&l!;ڧCg솗TJի/w颪׎!4%ۜIG0jlem7'-s0n=@KLJw:.y ?u(Q ?r 5n_ dXyFI*_d@E P 6_m29!b '2$>w3+9N7d,J(j1#9ۭ[M_]>NQhmSO+F:;Kx%dvɮZjnAaC0oas[q"ve-玻By\bڻt:߫nɅ.>MB5h #Ԍ:NOɹLaLE5]T)5x iM1_ޜv̭Q{]5XD.X`]Scntg3M={G+?ZKgI~ymxXV*A/z c,iY5C"s;ƏcZ6x1yv/>f'-?pUy6wX lbl G>"6a 4e΂ W¦^aZN{ ڰxz0 e/CpGߴ?N 'Q УY$ߛ{"o L j? 0蛝)3*3jQYrGx/9SF!/|]>R1Ag2 a@𞂀9Aa`Pi) @Trsi\)bFVDfՋ5 OPK6\J/Nv.pkcs12/InvalidrequireExplicitPolicyTest3EE.p12UT Xц?;7AUxU{< w3r8$h.C*)˛2rɈaDlx\rL#sܶnqJq>}{}=狣@y GCG i8A(д=;G;Q{ TP/.raIo@0@,CL/΅iLXyAd.\JG0;2\햩vȆg9W1kYxy6Nʩ7e+zZ|eWAͼN3G6Pnv[ɍ¼oQ}Kܭ(oȣJIg%JApm0ZqY`5/t/+M31JP5iZV2mU.;j6q25wWesXVt?_Bd!Ailȝ??3j@Iq~9_ׁj#1p5jҷ1p&0e='d+شpJhT˗C4ݲJf/ӳG9'0-{'T;[ִ0en u>ʬpM =vyTgq56nQ2pRȔ [j׈mwjӝ9[,e\mVřYKP|A!&_Vb[/^2ZnB\UG:žJ.oiNQ[-/]PrNl/wK O0 7;:Gk~|}?LԪ[U1¬鱪=ZԓsU"?f#։> B9e PVP{=IB%TFU( ?(E٬ / P!޹V7ݮS*EH"e k]VxWi 1tJj0zNZ883ͨN膷 ,~ V<5rNph tLVtp.Zcqskvn&+#sGj'?!v}6aB8c DYl=_X.:{'SlצoZ4;C iE.k=Ftk[b7ueC<+?:2{2 -݉N*mBۓ>AnVt*ΐLakxNg*k E푧;'VD,K neUBƇ_vXDVPi*f tSE[V #9,LŢaQRmWiK 2ZJ6#/2/*~) F T󑓧 ϲIzWtg*c.a 74 +"tTķ=Xx4u Xڛ|#wB<<נo5SFlnzæ'2 -鯲%8ۧwΙp`v{`kQQiv#u`j`cO([&c9{yX0[;v8"߽lg0WЃoDBN!c( ldTg1tP{Zf 6IᆹYL:ZP1:2wJȘ׈k H]/͕P7n*ƨԒ[[yW `]cQ:?.J˶-TLm0T,vCa\9עk9i ܄Q@'K- ׵r%6s#iCMcNډLlHAk (疘b35*s9pB,*>`I']LDYNHM F  ! a|B,/K4q!p~`xۢ48>Ǯq"ؖ.>^ .뎑9\quLaEW4tR /M'C9`ɛ]/"<~ͬJOB\Ỳ2$BI^~3Tk Ǣ,z!C4/ $~ťnJ]XH1v#fjjՓz y 5Cm=sjfR)'HϺhe"R+xRF[aih*Rw#<z҃e j~sbH:&l#I@$1 B 7m`&"'3o$ *K4>IBFT-jD ʝIuCҷuw汫l&!.|7#g~lc:t' L` -,N;u"; J.%{G{p_}r*RZւp,"+ogZhC,.pاޥU?DԺ\^KP6ݩ=3Dq2NCՠu9*>v=k>WTqyP$/s헨ӝgi#m4<To#jspY# D.ɕHjO&Hu͝Wf`A3پT,kL.p=3a72MWNX" ˜Cn|z$$SU1^(6- =H9t* ϝr:u$*jAI$8Їb}L'w;R1n"yn)ϖ$e0}z9u+ jSM>}&هPҢ1ɪݨRFsZ[ޭzv`?Kx$c#ƝŗLlɔiK~c5I1?ؼ "'X,yH{Fc#صrN{Js^EĽ߽,pGTZM#ܪ  Z9naHVPD,tSVlfS{E:&>|Zq@}:'}<˺ֽ O Oi hF>1 ;Teg9)i?.}az֥Y"ni[fT7R<,!ӒO4HNOT*PSdi (pu:b z]K }[>7Xj?^UE>Z[B:뇌قzjW~7z`R4oo&q|R9be:-8=fڽ yapŚSEywv>:I BwCiQ!lqπr%>rH|` " 07_-w 9{]WJX&81h40.$'' ?Tp'M'rp| @5GM<͕@/;N,@V˟PK\J/Lܼ"pkcs12/InvalidRevokedEETest3EE.p12UT І?;7AUxUwTƳY6R LdaHFabdId&aS&T S,%RA@FdGs{mνhFP0m1 J&B(Лv4{R8,z!DP8Dȉ p%G)`b|H͒B:slV_fh зZY^}/r"G%<g:]ߚ(tq(Y&Zj%Y[0*XM7y(K v]lvi5똻 oT@*N]!ٍHGJK 9Pp7}ZC}-,؟*3rV~/_|Kt%WQ/Wǜ`ҭn0ó|mNcY1LozrGyɽǗZ0>?:6Ko-=& ظOcT]cw1B5ւL O^`Ctz.'p/Y3jl@?=;Mj8$WA==5bܕX?R|h|NPx>Vԥ<ĭA\(/~GUyOLE'ť|-(!> gp>;[]ujW\=apyV"ТRɲV Grvºl$oWZ6N/RJ>yM4O+ųu!+dځ jإ> [3/"GMCG3^'r\_Of|.#hg㧬$>9Z4_#b3Fצ6NjYe?3>,jL_*3naJj*N kB0gXJ* I"xvK3FobkkCL=F_!-q(P*_T![ Bed L{M޹_k%j(К_oOM "Jom [ؒn]""]> ,L~WK$?SvUG*  Rd-2u/z4fURA\D\ }άɺwlbʒ.YTEHLM(r8f/uDUR^q $S6F|jO ٝ FN Ș=Z7ZPb][Nl%j탑1ɀg2RtHSnoq1NqۅO f2)e5 mz:Bɪ~ӓ(gLYSv&&1 }riOKSW5$f4tͽՋg7[+9]6-Jmv_O Ղ˓PF۰oJh P=w' أN,ޢ%K>Τ9Ce}Uꞎ- 9Xw[$1ϥBPշNŹ{q 4Ujvsu[hC˩/Ո+鮶ܭBJJIo MirD'eʅ{t]ͻ 7bԹO1F/m;Tce\ؼ&rcq:wq\a܂BK2RW̪b*\&׎kxWdyz8+̰[tqT}wߐ궅u⅟Pԍ] ijT\6_Ĝ ΃b˟Q=85}5pn|TCpH+|G>;N-EnlbaۚĘ*ԺС$ih+8;8;W^{}sbZ隠ZOsA#]&ʐҜic O q+'lΪ9$g@+t"Ktv4 2[͈HN4{^x).Ju,}* wnd-[UC,2nvi,N Kٍ%@vij][+BISʊZy)3pP9?'ڥW eLL!m%G@Jk1F-XB" GD#$УQ RM]?)@ĩAdjvO~_X}{դUh(vz#fCOEe"#ūSSx|&s KDw_W,RknS_'Cj3Kvi 7DlJ S-s5 A~'07 RL֠V̄~nd]U0@uZlNh֣nʼnj =7C։'-f > Lކ$/.=m$*v-X735.[U2:"п`DimX#Y\ި07=d!3,MŢ;Zx;Z\Ra%7w$FN8꠴-j޻LyOr& *c_Dz,#J (.Z2[<2Sgew/<-KCt*8 1Su#OJ{+m1&s0:1z*2e#K&>h5oN38vK^-m뙂d~_Ex[vO8e13tN31vr^σoE'<J3֫l-Luƅ`A*;?Oacxwmtﺮ/UK4)n|HI/7Xo{\vo,Íj>8=`UWŵ$ H nG<E[e^ta(&RK^pK@ p pj`pT]  })EOP`Hi,lfAp ?PKd\J/4/pkcs12/InvalidRFC822nameConstraintsTest24EE.p12UT ц?;7AUxUy80и%d\X09k͑G 1;dd"g\"D2CKʭMQh09c~{}"ʀ`Flb2=:thVb28J%_!, %2N7?E$2x֙ߺ-dpa)GKGwGś!'r~V%#shju6,Rn0]sT>js:D!{݋9< ŢK\UJO'x FҤ6\!e?嗼#j&' X]PHMNt4[UX kAzlts//R!\p)&cJUPRۆt{V^gL7{g4ow#цs4<*0G~-{ 4xelAC8Ay"DL_ͦ5(m(T@HD鳆 !e Eϲ7ѣ*Y$fC>* +ΛzS;)y"vD r¸RJtX%ix\]8"jk'Np[$󋆏q\gإ}J)ߒs '`egaTl_rR;̟"sĘmG7?96J{V)6&-ܢ7\L 1XM%@C`KQ&xo뻶*Cffk+*iƩX<"ZH9osvsI9\cH,$|4M  1Tv6gUa&+wkL:v^޷6zY#Wg4ǭݭdllGn+GZ7ꙙ`2Ys\"լf~4$6f3 0=:3ԧO4練a*SwJp/ۙ6jJ!,CB K~ *GAhBgQh!HU0-2c,dbYM.Y{)¨녖;4M,K{{ρ=J@-%꧳U% s 1b&F¼y?XeC0G#Uh^x`fg5Z&A:ٙrAcB ꈢl6a KG-ufm<]C]srʃz eSI]_$#T&OXǭ8QNP5E[֥w:43:A?X/xܒ1Li3D.f,Nγb3<1vKaL+#C͕Rzlmgo#XaNGI?Xߥ#Ms1{: u%6wƃȵojGVkrntS4?~2΁S?zvm8i OpP?HAVnWx{G9~H3@cK,<\~L ~'b.F-ha9=v~X0`o`JIfI{ nP9 6FNA, rI9 _+߀PqT0  ^5UK "jwÆزeх$ֺ@Eʦ ўuƴ#x\I}a&k[uTohw/%o` { ƆmeFrV3G݃zMw$W^O  o2֜Y֊m%qeѝⵖCɽ׸sӁ.לة;U\e$~7d2ڼyEuH?K+Q< JlַO {—MF {jKYi抑8N[ǦrsP$ }B3ᄆx)u)~^C /ay){s7j^=gH ],Zj84 osY_4ssb։\1B2Z# 9zSԔm'oEw 1f1CG51KQ[We3M ›Uajo3gTۻ{:t6rE2,עWMf=vYJa,{.kMYY%:I^];ӀbfFNu輩qtetąuW`f--?H"(=+uϺa%`^sWz9ir_AVDcr垑*IN'9Xv ˟{Kj0WVȝu,$݇  fq x>cψ^ (g *1;5B҇<*Wƺ3N夎nMEp Ejl?7__C.}EAr#t*Д! >¹'1( <O‘.k4p(I 蟔Bi`찴ܘ9Χwhľn.6>czc|P.%EK:-#}N7K5]$@o]Cϐ6wLo/Bv.^j4=%x7~1wm( ꌕ)z]D1-6-8ze`NZ.+B]O՘+̶ju1caǣ+H}@5OqmFNkKhaK3SҒ&i^[7߻ՊuY.duP r-!5A Jyr:<~v' |%3CM`.**}#?Yg"2LM<ԠW( jGj`k̄kKRB8{AF*Oq{ݪͲmC2MyxcdBmbOsөGD{s߬o԰+iKܹ}#}>j=d+8@h&ULs?&{z%)$ϷX+t.U}xp_'W)s#ҿxD%$Ң¦XW:?O_h!459k`ЄYj&\xWPs:qbМP+W󊨉BQR%{ F?v?G(5ii) W 7y'= bya\$E]L*w@y5)YV!PKV\J/?4pkcs12/InvalidSelfIssuedinhibitAnyPolicyTest10EE.p12UT ц?;7AUxUy<ԉ5n8FSQ$um ی7B1dB9rΔcGjfFLJAnαD;DȰ6jۺ^Y^|^|ЀQl@J? !Ѐl سS14+Yv0hX#7Ȃ< 8ɍ@$Tq$V4͎ӏpe!_}euX*^NMu6nm{ϣE}\Ѻ*gz JUqˋ= .rA䰝IrmHk ,\l 77 -|w:]s]ON]{wIQf [F*d4ie76g;]3"1 zy2lIxq#tnXӉ.3@j4xazc.UG'v~ֽX~[a#G{C蟼`M? +n6eq1m5wxlg. yb44TFSb흄Ul}gB}5+k_kpckVgfȆj515Of3~L3j orCIs:E2f%ZLlj/*{&{&;R7j)0cR9;0U .a=NXo MN/DD~#ƱDdy~ut7?Škx㫷 &?̯C:z|Mu,͟1kw ^.H 0D)K(~p=}8;o!؍:a;-ɳ痾LoW&ۋxwK;+y:;Z U8g#$YE^R;IB QSǤxf 6 l\HYi}upU_Q+B*NuCp=Al=2I )A*04QJ@X5+e0$ GÝ*i 0πoOV|pG_eR&,gfV1`Г3WߖGޝpd m_sX}65`qw Pon| Ƅ`u+1%!#)Z^1}l{oDAJ߰w]8^_w@̨v3W9;+M@50~:ZGM+Ϝth WYcd$35OƲYGqS!B˚@[=};tTbdw0iFtᾱٻq*|{x˯GpP!H3CR0 mj s}J$|JΜl;"F^>jX$ؖPzB`_ο2VPR4WAKg=q6p9:@[1Ѝ)e>Yw 弬'u"#~`ZU)\ʱtT=""Y?%c*(?A&, 9<8_ 3H@jqdhBH $M۟+俻$[ӳHR8ߌ逾Fv klRF5u lV8Ukߦl|cpK?4!VEmێYz}o/-gӍ$o.ÂDֿ'ŝ^P~f烡׊NiwԢ'֔_/YvgK6̵0O:wV(Aq92d[>`h!L}$XEM2qyjKnbXW9&t0#RDu'pu죤hJ@q>vgoM.);|y^dn̯*$8&GZ3j%Ӡ5iZ*۫?zͻN@ƙ\aˆݬGv1q05贅TQ̩)<ꨋ] >=/>t PyPS[eYFX]!gl%z}⾔m i)-XBث[G=۳dzӗzLm,/|u5-svbu<֋Q\CӨ=L4E<*dufx2hEaxpz n&qOXcI6.SY  ,>jOhyyn .\:6}? ):}d)I[ dduQQ"#".E \OM!7YuWl6%hlɨ6bQ;mGs ͖hG<}*&%ZT)s) '(T!0ö7!7UQ"'pkj=^uEVvQ ٨GFm349I}Mitw]}Izì$mD*e$5r"i _#/ W|C9_*_2U^k+`WUp6T`X[ hό])AVg̖Y-G8e\*tbGpfJG!ztkԉ7x*Fp957tcY/׏>=ב^I р `5 <{*BhKGE\E/L%o?VFp$F,PKN\J/d8pkcs12/InvalidSelfIssuedinhibitPolicyMappingTest10EE.p12UT ц?;7AUxUi8ۉ٥(FEZZ[S˴v 5}ڢ\knqko]JKkaEU锖bJ<Ͻw|xs{p.Q]pRE~TBA)pک]@\K(S Np3@pY(<yD C}J Pth|rAڧDu97btvFd}mb!`L5G`fvnZ%f̦f<{$8ߘXQڌn)U,-lտrjӮA`%.:ëGi5Tsrd׼n YK>QBVT3|̵o,Aoe.o#r̿;;cP7sT,`*u$W˘$'5-?e[ԯhRD+DC]3XX!WCBVEZ2ҭfkeIPѼ#7KgRwIl5y $yei!.s.izYU+=nS4}:(=v͞JA;ef{M k G9l,hPs^~Z;CekoڎS2\ 7߳Y{̪.ޣլa֓3۪Zg=p_, Si5I;<Zf\o֭a員gۚʬh b%-<7!IJJbdL-xb5JҔD1,_(O1# 2QF=1'`DNT_pU`h} $B\}.jYka6MwKYЗ ~15 5^1?ȺP~%ɲlJ}م63ig]152:BP^\j I#HD:]nz+N?X~XR䛭榫?N!Ltso3%$f'µmrNH)3aNQpg ͇~/xqCWp0.n87.\Q+?*Yݲom}V5!81zƧ#.j R+Sؚs+br>C$hoG?PKO\J/W+8pkcs12/InvalidSelfIssuedinhibitPolicyMappingTest11EE.p12UT ц?;7AUxUy8Ɠ/u PKl&]XZ*jt Adڴأ֡bڊԮ%h-喨Zjr9HA|0xW_ NALg(Y(䨸_E9A` $D]>H,\ܛ76z:kܹWFaNit8 +ťm:XmKQʪ-smWV@x.>+M8_//UYxWv/BبQ㬶|mSS:5!/D+.<,B2fF>BCDWs(O*JoY{{C+m}s%fSv6ff=XTZ_  +z}\O\wCX Q?EڙX$߇WVP5+&m‘[| 3~]5'^gF.c|O]!+m~f60܅ʃmtBLG5g>bzd}+~b5L&c  Ḅb3-m OA&.E4/JG5}GSFi0>9?4*hp=+*]nvD\ vV;wT@n]F™b"KoUoWtP6No[L6U6}wL\nm薗3V? sc Yt.+Ru[ ZVW2MRoO/4n{ʑ.%"^D:/<+a#d٬İ]qŬMMD] ׍W)7B&חSZeSv(#Q[07 (@ ze- Awi*f; Q|$tz; ?^ k+pUBCqv{ap⿨)0#ؑ& (@)HE! ~<  VIySv '(уiRk:'B`VJ?>dW@^&֡9Phu:LXϜ,oPU!#\N]Ԙkqb$sut2-tZ1.ןMһ[ZKΫS6rȊQA$k/D(iĪӳKމ)szI/SԈٝ Z{_S!vm^UP,`¬R4OjIX}:Fo]:D>+O`kk.S~U!@Kj:0BX7Y-O1Yf7"T?5}Z ֠o6oȣ~\gsoRxirv[aU)::Liw`S#7{<dScwo,Lddg dx{)VBM2Spp +J)՚53$#υzT9e ~\`ЖC׻w*"=I`td ɑUI%*?bNhk +Xk!-NNuH3!D =M"qsk g׮d1|uMִRpIe4b%z  ӨTHR 9񇐎:}A (#xTE`I\rH*"K,M㴛Jr|q2ʼnnfPKM\J/_77pkcs12/InvalidSelfIssuedinhibitPolicyMappingTest8EE.p12UT ц?;7AUxUy<ԉǿsPƑi̐VmP1K }If. 8rd14$V1c r&Ͼ^ow<獣 %u.&K$@y48Jە8 G[`_©;qH(B=Zg3bhC2_:Ϋ|N oc5dǡn^`v:sHYWZ<;T!T~rymd:{`Hc^pn4zU,cJ-\2q>{beUHlrF97~Q"SgԋmE*aѠZ0wRNPӝ>*]zbPU3>Y,F\-Nr`몲NvdL-Ց?e rvZ@֑֩M[ݏot8dl;IgLF3.gʟKEkzۺJNj8:he\HhԫV]{J}b |ns̴xS/PB0t_w)y~',d XZ!ص*m`oۨ}_Jq}ћd{#~Y}.VP ϭ4qBJ|Y _gI+!tEF;U8 BKSD-gvCoz״\_~6/}ֻ[fU/؈>$mVy-lIU񮯆tnDۭ)%#ʉ+ꁄaaK-£؞b Ӂ[H5lѺ`FðkNxaQ4Ħ'[7 =XqaG3|3I KȀSZmt0[`jnZk@RkspE4&h {nc)ŲhnS 1K=pPs]!DH{"ef&u5Z+Z&߫}0Am}vR p \ E#/oo cJP*2+og=% 6BI.Ec#g%>b׾.W"~^s<`ew?xc˾ sRDf=QS{I\c(7 (:]XڲlK?Kڙ2CPͯR0mP/U@ / :/܎9"V ]&鿙ZKɋ\D/a5Û/(G蝉1'=T1}̒C-M7^gW DJf[h5?TT5r&`&O7{䄾;ͻ g}0ݝigXAo{|ňgx7Ț@{ʝĽsLrDikm.iʈ@h;ꢋ@_)3%.+X ǢvAv1oY)G}~I4QoWK(/eg+Lt6Ei1˳ƝWUU P  ^85$v +(xڬqJEpڻ"&VGXPKN\J/n(?7pkcs12/InvalidSelfIssuedinhibitPolicyMappingTest9EE.p12UT ц?;7AUxU{<ӋǷ}g&K s)N\b5g08rIl"a2)rkbn%[r;?>y>y)-@S`\1Y~0R`{v%P=+Ї`7ah <SCIێAi3c hUf ;YerB$(%,kso w'p S[7RlByNlUƑt-L+Y4;o؜͌&!+|\)/FbL‡4jvJ.Z}YwZe_·)=NneУK]S5j7j Sŕ5QG,OaBy\wr aՆ;:""yi\dX=n!]OTșq%皻/TsSAx.FpUJ%kIl8ls@r^L[y%iPmDhɶƝoۃPm#Dʓ\`ZmJw-`jyddo"t8vƾ(ZNؖs=y' D1y\,!Ey3j8 z(҅@]_ .5ź~fE l{f.Giwrʻ7}̅1Ai/;+74ˢ6 $`~S 읶 z!P7U$Fb`DHVwe1Oy[cR |jq :pCS6*eX}%b_0!l\9||$li^f% BӚ>BNf+bd*A?xGӅrH @b)jMs$y,*R }M+r3@FE/B3<sR'یrs%>q4 (@)̞-'1P %h ?h5ɤMJGZ<,p L)X\&2 %,>EYu=M pҜ)(٭}4Һ /1ZF|0*XC nͼϺP_c [W˱Fe8Ilb%K75w~m$yJ((=bC{9sMaPTL Ywn15 ysfj YwY~vPێZ Y4KUȝD\fINDF~z5JsOmD9RPgJԤ-Q;XVmnkkڼE \OW5zO~ɶ֤A`6*)-Iԝ:m16Sbg I~ՌsJQ4Y\Q5["/_ _N9}&QI, }ݘ@=.}Y(ϓ;{^ +nņ@1vBC @*^v. X\4i֮FT4DexӂY.alʉ^z{ nIT ߾(JLp3HYVkF7rSڍmfˊ}|ZϯӓʊhDxٝ:HZ) Z!@Nhat  *hQ t䁑3ԔljP8juPK\J/k5pkcs12/InvalidSelfIssuedpathLenConstraintTest16EE.p12UT *ц?;7AUxUy8g7cBHFEj%9/هqeK ٚ0&6<#Ǩ%f9dJ:""۠u{}{I&a `v {+#,pP/V5ah$NG 'ԥ'^g \Cx'@_0HȖuyk|7bqvIΙ>>9ZCgU6 " qЅW~59ѳiμ r\U2Uy_lHYSM] ; 7p]T(Bf,53 \ɗot/AZ%Q^׻A'}>w*T@% t;=f|}5TlHu;it@2k3;1>9N`vUtԎ6 a:Azvg/_Rif"}݅}~9|1V(-c]1 5/yZ+>lHv̮1rx/y]")I9zS[FWE?4ȹʙFS̢Cy C,SQ)F|Tn]y`owSdZݔ'D>^h4(,=Nu9\}PqPFXbO1ʠ y'8^yvMRi>AiqLc˫~RS_R? w0laTCaPOn؂m(siS9Nإ$"[]syJ+>{wZDOGt6Oa-0+"v0wi_*lI-6 keWR ~о!d<&Ȧ85'+L\>G[pUxIlxsia=B9GucjCVX,!el(TFUI ?IəN^AH bYnWPsШQe7vqAZ?wTmU{ *M^7vkTq #l@^ޜ4ީ`X>tL3r065qǭ&3t<\1\BlȚ$g[<,w B-NƯ9Daz2Ӷax;"?pCPs ~tPZt58fYA͌T}!ϖqT"@)"*q<<)/|&GNJo ;,RzL>$[d _K`!;34?CzCZitR= e-9ƒ]2Wq!vWJ_Ɍ=o@؄0@S47lݞp@3:zґ}o&,[6pTBv6Օ0rتtJj&#NS 9ù/:&ÑC b_R#%DZ6-Ԟc/Dt9bZw'I/9(V̖ZacsO/d?=Tuja]9,ofR8jD;5o2PXрۀP Z A`("Kޒe411f!p.g[PK;\J/8b8pkcs12/InvalidSelfIssuedrequireExplicitPolicyTest7EE.p12UT bц?;7AUxU{<ӋǿK̊ivhő4יk\rSnc kI6$ri%ZBhnqNPCq^s̢eO]C{ä|+EZەbfݑ(>a$p~k5QÉìxteBB z9<ɏq=HwfުtzRzŞI\E g\oF6S-wS ƫ$'BE() [ QYڈ~x!{m) 3E8hqyƓu_X΅Q -I i{'DXۣv_yYj&$5EKgW>F|,TqP9 gk-c]Yc^F_鼧4%(Sb}sqH3"E4T̯*V12 ]o*^GDJvPѩ1sKY7-{u5o \7% ^<2n*)jⶴYGn)PYhӏʘ^1~0>ٹ ԫ1jo$z$8;np{|02)>ӿ_u ƖmKJPa1@p _B}'ڟA zy3r(.*AqZ}>=;m˳(~i#M6ݲ9Fl=\qNss7K]-'`_Q!EHLj 6y0xvkn8JD庵5)%k<'H"ܓ֎^c*]D%OH]%ک'ڄFOQzՊ6fg[*# Z}D+. A[ʭ9,4`np ;p5m%>;BGc-&(,&gOTy2T !$ƒ;k|]yzJQ5 Ӯ^tnLm4`no#/on  n4ZbK"7~r.*"+Nl\ĻjE-6Ds*+\Jk[L>ģPHHv6@$@B> SʛA;({*Lk4E(ZgA`\L?PK;\J/>w8pkcs12/InvalidSelfIssuedrequireExplicitPolicyTest8EE.p12UT bц?;7AUxUy808nƺ徏c(Dqk]ܐLC3mr1 i-֠1U,# rg}~{?H"t#*(L@ ˈ|"zhSDp?+hvh9bR*AE.y# @KW3dw E09W_?_Jʇ`+5+*R?Vj0 *qGt1J2C -?H[\̳e5HAȍ)ߝf^zUh`|SrÌϒ" V3qs:6AmEԒKn%=vTc$:AmA`D^3QH'3oq|UDUNqp72̀HZ{!lTA7<&@ژЅj.:B:mਈRG[CgGGdn5cŽrT*w4pbi, R93t[R\FN9p"h(G6\#!IX,Qm:)[^0f .w ̉,0O%8V]z4|V2v%ޓX+wΎv~ܝsw K٫16y82;XsE#t4'4H-Sl 玦7T(*I/εXX..mb Ox*ƴybK> I Ԣw)Rԧf2, ~K D"a% A5H"?M#M?i QMkNQbŗ^5ќOηvuMW/Oq5tW}H@0\oK raG]Jh}i^H_\hkB%4rd`1ZS*Ƚ xL zō\ijKq=1? R1dtjA没iJ~y,ÑoIg]fb^wϊci8Mܻ -ӸcM| fR}n]OY&'y2)tә{f=k_sIE>P}H,̻2aOI8\,`3f6)FyҪ1j484AU/PFuE'(/ԢJnG+n1q8E-g'>-hT`\[\Xmzś)/-2Lo| /㽙ِPymh]*+WS@'{]'@.Xכ{ {\,? 8>+GuH 0'(d"& T/oKlV*ز[:@[|rVZUb/ŜjIV?Bw4n,,bf//6rG0IOKt-i?a"u9B)*RJӀP@< ;T0{؇"H d!^ ] YMGUvM:PK\J/ .(7pkcs12/InvalidSeparateCertificateandCRLKeysTest20EE.p12UT ц?;7AUxU{< wk!sYnCcbIS˖ˢ\ZhE'zZ\cfnt\MRQzre]8=>~1"c@PNm&(,a@! h1GgG8 @(V,,R`bE`-v1) p|guN!}UxCvF6L.u .I#JO:-|r7Ն0cklsu <4 k{cbQL$ċr@Ygpηnj15g]5Qњa f`$X(.xeC[#j-k>JfCApE/Ws=Cz1fwi΢WrANQ}+TpӳGFU`yt8"ɾPb9$(Ҟ))2!/407io K ImSΝ_/<?KSQ*?+o uZa׆tv6!>x1^^04TTC8yE\z=ī[L0S~6lbOJϞqpQ)5TYED@Sߪ, >1`Mס!Y- Y'43Ճο `dOl Y)r7K&Z2}K+9G;/U}W2z^$|A0i=e\s5jͣ%5VI\Kvr#[ѫq1Αf0t%G"3:f,d0QQ勼dCXݢuc݆FRתR9GS 85vgV)xH5A`Jp΁8Wܥ߼{ w]=7C4K_K>^eַr#xhT?fh i޳}ެ9eH&JEMD~In]>l7=;̎L,|+Y=-¿w ڂt;9lDH$(F>5)) z2=?)YK! -PjﭟI8& QwNzYP k8KH2 H,!h@, @S^;S0Hi፦Chb` ޖ&PK\J/We7pkcs12/InvalidSeparateCertificateandCRLKeysTest21EE.p12UT ц?;7AUxUy8 31^Y#!l)K7Gd^#t#5d0%JLAD+dɚ!KHB^y}9s߄B@,P?GWÈ=%1yD0hϺ{!4AǢajyF@L5.4f4?MPhFmy+<~eRTFۚ1@-1տkMD+~2r<_N| )xqzPƦH2=6YٟSU}dIb,>K#@9 <̓-gqH'+"λ_}k5sJykҫm"5R%E>ՌQ2Wi2kb8+T$Z4H8L}kV`)a6veYǀ!銾qY*sRR_` PDURRi]f`kj&JR⽐_ IY98$/_Ӛs#$V$N ci]VxI0gpܷ^U5?*S[V9X/إۤn3WA6&I(C-e{Ŏ?} )Z ]<0j*F)Ӻ^mlUg wH1G?9>"WeW?1p99AiZmM- _x#®NBlzǙ,Bol:GS`BEu%6_U=J)xfmhaLc{Ip 53ִu:3[)5Ϗ[k!}g۟<'Ru/pߺnE)~o9Wa Ɋ5(.C uV }?uCI(ft l i!ꗴ؍tx"2Y"o/*aD-'?hZ%BiƟ#B auM3RoEi:.a[[a],4m*2.]m՚8v/8>hϚw59H[$wӍ)R3 PK\J/-"<pkcs12/InvalidUnknownCriticalCertificateExtensionTest2EE.p12UT ц?;7AUxUgT CoEmPH`!HDX4YB OJ80H" -PQiK1!Ü=}0 b a@D7B,bD<Z! ,C!A  A`;ډ]P @a&5޷kGN8v}SshJS mE<[Vu}ԏGuE?b.R$Ė?M]+v}C$k"&!W;)U늺h({ԡv7P2TȊ.TslA90Rs櫧4'ĩQrA M~Z>.e}6;m6E-"̏uJ~jLG'!ܮ9Njæ5$FK.t}J>Q9tAJ rs*Ϝs-QJ+&ԝt?b op?u~R0(Z|k,n`"-DiWPѽqvװ 4% MwϞWUf:4I[._J/f5}J 6+qQGn_5m"5\(Wr{'l)2WVCu*v`^[ 4\1#~Q#a>&-g|Ke8t.̹=:,ݨ'h umwdzeJKD8!\*z vيaէ{Zݽ&wiZ:=u,gO*+DlԯS^P!ċ5-2Z4`3~!۸w(meUe%7Q3?9,LB+ޜL0}_%u(%U%2QqƉ-?W=ʹfBe65G?C7:arp&}`KH!_!P*'Ɉ@ۗDqos5 &^5$ȡ4!D0ϯ&R=cq qGfZ_$(Z!m= >JǍhO$^\k͂fhOC\RيISqiۼt">~bGo7^%YwFr\Oy6ikʵ]h8e`r:t0SrӵGSn{Qom, gz;ڢnH YhV! $2w7W>SX O; ;Eh{WX%3+Bx @ s"so-dr䴍 #(PwGr-R,S@BuhVlJޣLMoن IAg'V#tϴLrvwR^]Vu4d4n8 c]cc]еzH|7nnt9]j1P"=mao;!`P؎/uŨ鉶dH %d%2YCuݿd( H@@k@q*FqHWU<eTo|Ͱ/`m]m\0'ܷ%PK\J/W1pkcs12/InvalidUnknownCRLEntryExtensionTest8EE.p12UT ц?;7AUxUgTS $! J%RP R dJ6F:"UQhhHsRt,T)Ii"Ü;=>< H#v2"a0PXĀT1 61,:8(2 !h22#)b`몾Ro!}ɟ$fF]@-* s!?=xF61zz2Kc~opԼB틷Z>jNv+J)WrU;*wv!%=F5Mjy#glhB@WCڰqKwTT%ۚfz}gID 5!RD5o:;X5{Q[%l(YP"oLnXmk^ЯS4t>_OsY3Ӟ.$ũ@չ?^s<*;- c$ie$c#z\ӻm"^0 z'xwa08t" ˬl-êzW.3H9}UuT@7M7.81`ZڝoYv )nPB8k6N%hWF;#.;V{n&瘲ZvT f ^igHi$6 YakuP]G8A~Zٿ^jPYJOo566CгǯԉW`676 VL5)VfEnN߂(B 8󞧪vHkMմ"E?aI 'AFc_3ݲLh+"r`x5-D="H:w$^ՐZ'_OiKU=DU;]4'[WZ8 t_%8cH;l'2o?YM> *B ā-~ 1q *?(T6:@ B!(³k'f7Ʈ/B` EG &OG_u3)p\ &)U=Q!m ?¢jVu/_Xm1U!.NiV:o鱻C ,V|whr+Y[ǷS;:euuYR9qH7ohzBH=NyxՓB?^ͅDY&)j kf'+Ǯib$f֍gzh_O ^ԼC$ Ȏ(^1bnB<tD"(kԚS5GԘ!AXTh(0UO`Woq:1 ,SV286zaw0+Ҍ[VRk*6Zw_*oLyA8u\ѧ_u&B_?'jp 0]iqŗ%l&&fj$,lɑ =V>+4*-$ϐ_m(3!◘KJGDXN2A,W=$K`SԈ-&VlnB&pd}g6,NsQ:XچPlʺC.#NG>Ys[7~)%PJ~5 I@ !W q7usIE<#ANNpP @nGaa0HJ |*!f7f-PVt%xErPK \J/* -pkcs12/InvalidUnknownCRLExtensionTest10EE.p12UT ц?;7AUxUy8 l dOF+BD ӐQ%,a(w;ink 1$]>9 \4$'x 9h ^@, tPBKo炣<'ޫ&y<8"3QLΉc#XNc"==L7 Av)$Qw8XjI[$&mowW"&;G;R1k%R}g-tes]VkSaB=ۉ'=-(ֽշyT+'\ɱu~#?qWZxCmYQ"̚]yI:D #GHr Ft; jIdW;CY7?v/zpe^xUiS*.oBua {1qͰmI;ytw[{JraaΪ=ڗ{:sƨn*1+dkJ˿C+Vtkb}s5(<xub,)4Soj < ;{.$n ?H:N:RPNo_MR$ԸO8OzTR^MNBUSsR0b*3ߊvyo;5T9 H]W>6Ȁhie4mL6u7u{lu`>(=>;Ŷ"^JU#5l! *""\<'"P,k¬"(*= HzO4ֽwHЏ1/L+ K_'SFj%)̞Z-)=Ibj2=պ|Y>3pPq܋OM0JKY<3,e(ewOȮ Y>$%!s4ڣ@)B/Pr:x` W:Od( |ǐ!)A+8#;1`" l/Tg ʷ"łs+0C\K@wMxIUr6fscTyM 6k0j_^RcO8'!ʓ=I1]J 71yrK1TDC jL1!w=W_02E]O_"#{-Pmy.MEM]S=K]B,qLܦ CvQ9^J]TIF(7zJ7c3#um;u(rJOu㸣 =cǕ2Qڱ~@j&cF{dړ"8yS"/Be7N9h ެƸ=Ĺ8!,[SN᦮:),"-܃8f] -3#m3(n/T/́鍉;K, st `2uXup(@)}fmG)\Y(&@|p?J"W^je9nwX^fxo.}4[2)_5c_MB{M1#<6M︫U~1.[G)M+y! |Vq['aZc}iz5o'_ ;=:a |!NW &ObwǷV\S:RPSLB^Ū_jS[ ou6Q-!qD齂TX³óRm6Y9q۟8MaђFRY۽LY;) #>KӺ`1^K D;8,b*Y  wdTf%{gdT50h{5i#,Yuݪo~L?{Z&g?QOدqkBtY$Y|$0_ˋz䜍z\KR{eB f9W=K6%[ڧ 4q5dÏTĂ/mpؤ?\Z1nU[6B_i%KiS.~|KɨK."^ .Ս{4Yȣ@;R|Za۳IݹbޣpJ|Dzܨr-/05?P8 * cB:1B!Pc$3!rtA묖z Nv']0&$$6hiRi%r3Guzw I5\gɷ+WpCVYfuWB[â|pK,7f>x1cU.^uh)Ld/uP]X3TC⽚nō"dut"~LMTh&f['ntTP.Цx}қxWimQ0Qn(ũJ%T61:L2гPmL砩0g9G :Jl̝iH~íV_c%g@|§T7{wK.NW.!"?&HM;Vy,Ɛ~ Uޏ~V,]JK'#[YUDɎ}p>3˞NGI " ?#&6KdS0 v-n^''9CyL)sBht!j\]Y"`.N )Mjr8/a LJ,֜vr}Rdw=֍ 91h6kxZ?L6 yҥ鹈o|=\G'״@ @BW4SRJܾٔ9)*Qj}鶈پ^3[`"vfR|`tDjVOe&j|t'"ln_/^&އZk XrB}m]O3`C8Q)N@WAtx AhJ(GC!GࠃN)կ`ȊS#w?PK \J/\n,pkcs12/InvalidUnknownCRLExtensionTest9EE.p12UT ц?;7AUxUy8 sƝs4r5Z4 A)[Z(͐GThÖQ=9fXrhX=Ϟ(i0`ډD$hNC)]9 EkǮ?! LECIAIծ0R '_WϕqӴkdxfFSUUXp4lǥħ:`b^oew6E ?w3*eP-ӳfbbz)aܨ!f/Y$mGM Mn%yӖaM % 2SF:YL' Efmhk[NRIF#rWjɖߏP4|&뙬؉%2xz(E4B'ѐBYoiR|tZOt )?L q<@?ۙ4/^!":1 VOnY;hhŧe]t >8z >wޘ;;Ic.6q$iO.ۋ6$j̫̊x.v{̺uH_G= q Uһ@iBJ_-qxt E:W:'7JRctZ^9z+ϒnQ[Et+ A HVnЊSVKSP&%ͨJW=$gup/uiDzn]JIi(W[K)ۘx#]5GPdȜu_^ MI)e=Ek7L7Fᝒȷ9; ΂z12 b[~W.3qfPBv1V aa/$yrP2;U*0Lu౉ݩsDc"L٥f08#beg /zFSO[:9 !9w1™_lǺ[. qcd{#Fw#$DL}ssX&fd$B`%Bȝ¥%nQz]ʞO&K~襜ab}ȓs~CaC#W,+(#cv*ZL˸:_%6>%YUZNg$͛ݹa /6z(Oİ{t:}=\{BB?WE8qOׯ"eV3U&E75VmǷyInn@} ~t"} Vϴ;+nEբ Py#:VyJ)[i㇚Z_Q:@$|0wg_J&##ENBjI¶ia4bdv7OPKi\J/,pkcs12/InvalidURInameConstraintsTest35EE.p12UT ц?;7AUxUy8  C1ٷfCL5kfKYdMck_{4%f,QJIws|; APON{h (Í[=̏yA.E=n; Y xĐ(V1=[k`N[=*rSGeegPx_kR6xX5;9Ro@/Sց_b1uPSr!_7P@o} ˆ5g4{w̵VX/40׳s1/lj[G9kY =?}i];q֡k-h+,:"V+YGl>}BP*3l׌uW"CjwrdiI;Yn&*OK<L.M\' {k;pleD\˞/nM`oMI%O񭖏f&6@p6T1jO;c~"sJX(t'SO>Q_B@)ā-v ai\/Z!*@\Q_^5V(L,Rټysu+ۻY$WQi/.Im=]x]tح0IkA#QfI-0YSW93S\Ut]]ɚM ؔ~}5 m_Rjrp>ߐ`|{c 34B?.P.p+( ntu~+3&Ij\\}' Lܮƺpd9?:&6ԼGe_|/%Gr鯭7?}.\LJ4]'PzOӛn}5Qf̷qSVWeRz:+껑b}fļIClWs&I H{_q<[X#s$+ARL䘾u9H&8~r2VFiնCyrdO~Ի&զfa*Ş@q(+JWt9"PbHjO/gGY#Ohho;qkYAvPv۹Ҧ ٮ\B= R5d#f%@"qٯRmQn9pET曢 &l U,RB E!`$Ω{=% z彶LTN쭤PKj\J/ ʺ,pkcs12/InvalidURInameConstraintsTest37EE.p12UT ц?;7AUxUgT ZB u"c,MC#ތQQta( pF`(   8T A hHYݝ{hbJ`G/'AbB|J}88~Ò! \?BP|`q Jj{b.W"3Ti#+qiw&.|X9i?C?٘k kPC8֢4b@~ZTT$B$u+TO(B"ct̰fⱣ0ag^/!?dέ6>C]`~ۥ _M3|ENNGKϮQ+}J J:*&D_–!ո/wR( g۸Nȓn7ќf^pw*8;eTQVdv*;?Mܐqa:-ʒ:\ aJ8`` wWɂiQ T T (`#flGKzUig돆+ݪv Qh^iN֫ ʍāA. }V g}x #ޜmL9E}_(*` zn)5?|_Gc˜[~ٚϵlkچߢ0f/]:Z=zQ3V4 G=+Wܙ^m((_'\ j(-}m:gԂ(TLUN&SvTn3-ɻ$O3cDZa vkdtL/Lt-b;!WHON ǐyQaE΄m*OoS,lBvPjafLVK8|JmYDcڌ)o,ti`j̟ǦfFf4~!)k7Lcٿ%9yړ\|3O^yjS;|"Dž ܔAqW_fA{q}wu>g 1xĄ'[4_-cMgl֓ؔ5]d}E/&D j-ħzd/ [UmwPӑK/fܮlFo-ݛ 8)tq8#+(yim-21tQʡ4V4PK#\J/2-pkcs12/keyUsageCriticalcRLSignFalseCACert.p12UT 2ц?;7AUxUy< ǷfǑ{Fk#G[=%g)ҲGr43u9f#5ǨqAx7OX2l30/կy}A;Tc՘nh)v_+a~KT ]g A֥ qj+Mh_xkEVUIeG>|J""6 6-sGґ<(`u@Vkn l7r*G ͐g"KpɨTڈZy eGB7_ɅHKq=mqڿ8Գ 5ކ\6Gg,,^xj~wf-Wy'bu50Z$!\s]}v +lfDdԤ/di@*G4C&}^1O!bn9'f|TyZ3F<ݽphz뚮Jy~WWҴTգκuK{M%Dj2#F{>g {&\#~bd2ϦĠ?*4+ ^K0wni2rn.΍Ev𪦇2}OrZKRAURF {J : {86\9V,GV[(̔fewbwA@CwO,hΜWikE^|+-mqakxՌ%[ݶK7KѹkEn7Q~lyɸԯź5z77#%0 smJ`h+)֭Op!o@c CLx1/ \^qUVuizYn@*;fd `jcne%ɉ; >( "cH &7V`P$hIq}tEƟAI$΍>m1tSǝ;aF:W?F;~Os>?]kEt.C[*EeG+H%4Hdu~R7sf _qX7H}!g\e(= i_Ј?b$vtsSih(D~ۍcY߁oJkoZr9ƨ15zִden̗LȤj-ͪ7qɩϟIkCռIsY37GB:U^!)-'@{yN |sjzCkWN\/]n@ͯ*z[(Pn9Tln0;z1&xvfW0xoL,Ϛ}R"Օ&ǔJг>T¡5RR:c,w1ʝGKIubdn>!*z.*ͬ]&]b_gl|LA:|n G>*kˣ܏'e9XkIBJh9J۴Ga"GlC BcAQ׳7{U8/)uè+S8mӿV܇tI*Hɨ6ar &Q'T[)PхE5yt&뎖]Ђy_1)2veVIm6j@LVZ)]׹Mkq{T8+wC-5yB$[HB!d-@တC= k¡Rhy0H] Q>^;2‰= HG8E}7PK#\J/d$U$pkcs12/keyUsageNotCriticalCACert.p12UT 2ц?;7AUxUy<ԉǿ317͸rq̰1},˭\1(5DU?ɑV-H"o< Q>8 Q@ȧj%1)` $ a dR ABB\jN8JA.3T#8 X)TBFWh$#*S_l=wB[7]sxzra *F`EWۋWn9I(S|@"V|m\jIFn*+[CjDǨԠSn*{p-4u,Lbň O|Q`ڕm Ptk*U{8TBXcƕ7-(a t\BC~56F$Nfnv=p MQcLOCW[DSۆ $7QVngXug>OyyrX ;' O߹ņJ.񶡒zQ;vXm^tu$$,)Ľt'_Cwį4mՇ$s\}ˑa[sfaVcZ1Dy~tjHRU+c JTIy\z"JJ7rT>iƫ^+Z7/x`C-$<9seOk?J>|}z/uS[Ӭ _y[L0DVU_ ֎?'E(eaO %2^ Zv8Q. D܎6. `dS;r誖#{#V_eTQm). BF "ƈgR^/Ű^|1EY.. ꮽi5dfnjz.DMsCph|-!^)pNۨ'=K/GvL<)ς ǏF+ yԴ|$zs{:v]nrKWq/5;lGçFKeγv?Oz]mCLHJd,f)|"rForu3pʰ ;%2iSz]%Q6=P"wf"'Z~j\]PD5iKls_◠͜ 7!TIjomȪ{?~1# siGyN$so^%1+\w"$f?dO癃%Xƍnjx9beVsE7u4T6}OZE6O mu.><2Yn;.&nFYgJ R!BĨϪ˭!mҌ}RxyQ.(e9-DeLN:lG٬v{?1z8=;\K=sWˋ_஼էj|6Qb_a+61ֿc%ugOiE.\%ȂsKA&Zj e3O'%^_A5lH'''b.$ ?pȭ).q)'4lbXJ&o/28PK$\J/0pkcs12/keyUsageNotCriticalcRLSignFalseCACert.p12UT 4ц?;7AUxU{< Ƿf C}FLَuNsK.G)F%Fs?>)Wg Ikd*:"$arq^ys}h0>hb݆ sh06cL ơAXtP/D8 bvV?)uC@ O(ӽNJ+ ~ӘMFs=;3)mFu}_kkg1&d0! (F\F < ud !$B]ׅ;i,,Q4/lf;Zuڄ6.t4cN89W–ϛf; 5QQ=)\>}u6{HAhLotH4?c$!Zϱ OO`@ܴL@,ʷte\;yac婬%fdϽ NEtWmPr2b0t}ؾMTRuެ~T1<$Z`9sAa\/jşKqX"hEQC%f^fW b_vdkZqPTV4 22 OMxVùFag[-T8=:/ 0WEg9" *dh$;1G{8Ԗ)Xʦ؍.޵*V4muz}THٔĦҫm…abXai%:yk`) oՖ_nN+G5=z  5%e-0j ^qNRyhj_uNt:h{>cjHq>&8SXEԔ ǵ4YKh^](}F,L}=7L2Obd_/ : y^)mO Gʳ@}( <$/V`CJ47 Җ]ʟAi@<*әWr"ֹ29'ҖZ2p*qT>k‰833h?8fq_Wܨق/iv l9UmwHLLix7b;- y91y@FVRMZI-tYNg?/&_]^yPPybz/bͮG&{o@w}R=XM`sIU5ck R*XL;WW.5+u\ڳD^w2RxeՔ䦿d~%@8?V*S8Z00٤Կ0m? ~ "1iah-{Wjs7(m{<1B6Ɋ6spb26<؅8٭[uĚ&yTA"'/[/ё,bpGʞ[Jw͜y"WoCqE[ vZ%}+ėGouWT'k:zG_F4hk Dd2]uEWP 7g@dӓZ ǖlȗU˙it*]'.++ 4Rn -ICl{_GG@d@ ρA䃞B08LD[ (S+Y:n,)o*ĨyPK"\J/H,4pkcs12/keyUsageNotCriticalkeyCertSignFalseCACert.p12UT 0ц?;7AUxUy8 s2ZG YL8V +G̈B(0nk dHS1㈢Gn6#`GBvy}8| h{p$uq6Gxۂ -,po@pT -LEXd\'3­?xG|yVg΃aT [fe$ӵoSk\>9,vuao@fqD"wfyG|Nb 3@ }z:[睾/HROrWֵ-gv?]뾘ِxG+Avq\hf}\aX[: iY=abE81=Rk觻\!eP%ueth8F?W^"~ {M1MTufy VU`MI}JU^ ǸG^cTlf<Lk&3{?/("wu" \l1>ea^3И:/_YIT'Z=oDsGb[Nʉ;cM噣z2NSñQ=~2lG?$CS"\x%8χi!P|%̚KǂS+ }/wa \N[9? k߈?Od oImH,K'jq2lfq+rzu.ޖp>|HVm[U;lֿ)ytl{!k=xܞ|wG$yzQnLzFR r(PNuBJ7{W,'V+^NBȒc箐.ꎉ~S _~ף6y5Eߙf+p?/d16v`FiPiy],*:ކ6wVCݏIfs_{zy^ ?iƙZvko P {a.r  욳D$=ktGۂiHX@ڜ |ݼv-T7GEEO}=Xp!"'6H)uq9u,@ d  Bœ!0m x? "9NO֏ڧS| 2Ux!?6PK \J/!!pkcs12/LongSerialNumberCACert.p12UT  ц?;7AUxUy8 3 33ɖmd[5YE(.pg$p1N!edh\ERQv|s烡B  ̈́HrIڐ@ET(M ?c0TȹV"*b!2Пa#%"$9>ZqTO-"uL~e_X?IZb'k]sr|dVii=mJCҴx,byWS)c*Fܘty'EDeMٯ4m=5 ц[z>ubNtL|h-߱QK›lzH "DJ r5^Tnw<饔bb)dyfU "6D!~9:vP<ÏHiEɗ#o㝱wWj掮Yn%ױgyx_KL;N.(~:\([L4WMh XE׎!YzEzqʙ;k,ijUkmV~- iʉtBC(QX'T5[̴N{UeاRǐ/>NNn;zi_&?[6U3zOvgHĊ~TO|buQұS ra^FB`\(ѮJ-lZ#,|GaE| +ݓn\n+zX^6=s| [ fL\M> kݴ{ȨwUF'n!JWP:Mc<ߓbh2nSo q!0Ux3s͞d54_ELRzm:]$}:gV1wB䯒ƍxġa~[Ɠ5ŋ!aX-CEô9b{ކr'&UO:Bv)ZNadZwb<5j:)l`K퓉?D| Ql_tABқdh9Z}Dԥf{9ח]ȥ=9lSs& GF~*ϯ~>LlIqHxDbLlٺ=ҭ}O0^B{^z"ɌGEV%V-q##Z-xۃ*'JOLiOjwƴ^aisUC=m5C \CdE*xUEa;͔ߧٞX^ծZRu e+PN``, \5b=޵8`4؆C#bxJIze20dy4OR$o5قk٬D*&kr^>o}u(;Z~8sf'=MxTcѦSYAV3LqUN勇pPWDwsO6{u7L6Պ%XBCZPUv22{ёoZۺY"z)/vPx_g˴R]a:ۡ#n5?Dm eT ѣK+pv?# ؉-t"~(P*hLM:_4B3pu&IPRR޿ԧ:̓*ӜKA`0MFKWS^ uݟǎ] |\HPov׆z5|VC!?M{p$7ͷ(G@SHL&K-ܧ,NM|Qwɢ qt{oMgb ]͒S\./`: WagTgc pӟ]J1旯я Y46sUMDUA5ێ{pGΣdc 6(YMPCIଚY5|#+25w}nnLl4kµipfޞ;}=&Ci$!.ܹVn>7I9л 'ҭ)9I;^mbPإrz)鶓2+3gUr=taFvjYz$=WkӀ[.:̏*SۖS&έY.a~6yIٛh߿ k{ei}] اV4PWEIu<73iG28p{pI9O Tl|=`y,{+{u}ŗFfZ<*Dhfn4/'d4Ⱦ/\ܤ~F)i-mkމv7™HP]x$ut{6uF$:h\0܋zXpp_s-d h*,EOlCT@XBEeq?o1vPgFQ^SqLURYnUzy^*+p}@2 |^0'W:]L{;~HoأZ/_##16/-Nc08_Pzʰz`ܹRWr76Om)#BXW%.s[6sf܋V I_>rɑEfrlry9] $-{*vۛXorP$ w]0U"Z }=~K'-ڳc͹/¥8nr\LJ~UHL8-ёՈ9>~3}_.Av 4) 9Κ%^*U|5K) ֓ޟ7R]w Cã=wyο F_Ri?!LS &Ld]w{0u!SawaQ/>W*ۅqq J""^KJ ,[Bs~ 1~K+)Hf7ZYڢi `@"DDɣ`Pi0HSBPg$72zG|:U?PKB\J/E#pkcs12/MappingToanyPolicyCACert.p12UT lц?;7AUxUy8ƿ|Db'QzEЏPjhڪZZJHmQ{RZRb6)Rc+/5BQBm3ys9DG ё}HN]1 VBG!ȖS^!K+%BAR@IE5=pr8O:?A29 t"gSh2!-7߭EWї\n}6ٝ夢aLT}=^Ωv`B ,?ֱvv-ϐWLKl!5Iq)5+j |Ag&2RN3wY1- *2?WڸΩ> +4I=5/m0-KY4Ιl}]X^0R;b]Wwsp?۸{Hs—zJdЙ6~ qNh_=c5/c76~R^xdR#Թ7){گ5aK}^0VEmĻMפPƮKXZ'ۦim/u|G8ѫթ|h^4XRs$r_mD`ufyt 8lu-kP+oPHeM8b~wtGVm߱ƹ>g_Qx6.E4S>iiԇ\"+I (G̪2[5ܟrVGR+P^y]\Ekͷ(-5W\eu\DcyO)Ue%+Ї c0:(̱; 7 bNV5-4S%dx_5^Ɂ]eHZJsnR#$ddؾ=[ɕĕ\/ޗ_P[-i0fdPhNH|0eh:@nfˢ}1d8$2u91uҰ\w}pZ.el Er2A%/* AZ E%& F*lu'-%MNd|hftAlw,MH> m-h4&|2GNQur.ɺFI<:4ڗ2t5pQZ]?)o&Z .@ѰYeDqFW&MD Hm8_m{o-;bOiQ-D JõWI,# .sƙpm uȎfTsy `pc*rFm}N:/yWl8 5k?Ƌ &n11ekqTקH7KbIMi(yޚ;!ۯ%֩NӜ;Yx+xkYU]z9S>mn7mmR2Jix|ITgxx6œbT]C,$::0JfԘ/3qM?c*%O3)F0+Y)bڼP԰ڴY"t¬۩#;r&{vms*\9d~}sK$4}/QMƵ88@j4KĄJkӇ 06"}5PRR1 p2uBz*F a!Ml~*p•80BqpYPK\J/1(pkcs12/MissingbasicConstraintsCACert.p12UT ц?;7AUxUy4ۉ4tX'$ QҾbV1GuAS sJ4vckB-M,*Z1(hRl5IHW8*B?[CBkfDuY%mؙ(7Vq#hfjX\})RI>img(n*!_kz|}rzUk=dtRYly:/D2'Nljy/ OK{KsX\pn帉`:Sk t i>.2Io <-./ol\Ż ;)]6 xoѡ5rZ9eU7WhSHMb-ggtR}.vU*Nj5I,#xε8`z==96Gr8\* O,nBCL9Dl&H-Rkw6l^:=i~VBD;]+~B}]7 r2ˈ; ۗ~7*If(,3R%[Z K̑f* Є hbBsujڲWU sI/{V|z $A3*n%21Ivv)FG#1R>0|w%zEB%?\Í;~v Uk7@9W8o^] Tִ;ciu7r ]U=Qd_?gǶiطQ ZQ~V]#P#YmuBz_*R,leWb:tLyOW];TҫwlF$O<)8J "*p\$m6V8]!o \w~4{>7avzCBy1އ4CÓ$g54"wy[i eD`^;s jǏ)̡ ٖkJ '^p➽a|3;yr P_ѥfP}ZV;wE06 oqP ;^nʩ;(']7pN?E¤ 댞#hXUb:|nݐBWK*@0s3"LmW!7]eOc 8 @ .-Ce>A =k W guzSPKV\J/|\$.#pkcs12/nameConstraintsDN1CACert.p12UT ц?;7AUxUi8#TKEJ)ZbnR[m]j)Q*FѱRJZ[ciRTKthRua<Ͻwswx)O@T}SBaSMӎSYα!`f'ʌLx2mJH70qcڀ%0z:co7G1]9Sz8x .K%/+;M-!SaIFQ~kD-MO9ݘm70εdlI`?DG1ck;lsˠEqg6y{&-nA4j7 Y7l4UY`M:]$iTKY$BZ_(eB;K]x|݇t*kKJ 66b+'5cyAW|3G%2.-ko>E䪇OLz>y rWWR{,?՚ͧm_nSo;̀1atFhFxH ?qRm-t!ɱ;M8n|=3!ࢊn AW fX5WޔuaUA"ujQoUV(^3\ ?y&zfRn]g5 }h E5X 9g[j/r=M aTeW3K4 .Ԣ.ib=\D~M ⬻_$oKRҦ~Vg'0j(REp,MU;qB͞b90W D9N)XF>œYU+ؿJ}aV*}WIj){7;کen%) Qlwپ2M%߽zp"g{^7wiv Ru(+r҆2Kyn(hJ/z(EtQ^`Q.ߙ`o9PW%`i穢">>(ÇqEW$BRv|k: iQ9`Wtq]4/Ј&7ce?P{Ӕ5cϦj[% i,qc{b~ }-qӋ*ui+"uxnUMwaak+vpU/+I{3(P)=\p~G[*֛AɘH{DZ Q WeV2_dp<ѳBa^WkwGwI|e)$W߄^avdz]Տ8`Ig{DUP1򹾧zRU7<<T" G-=V:}×^*ҙ o>[E/$ (PS{(w͂ F;:/,/5 {'f! Li&1p@nEa)NTc3j ˂K*u7}dRMRR` H.H?D'7^/B`Sڣw_W^X9^PKa\J/O-pkcs12/nameConstraintsDN1SelfIssuedCACert.p12UT ц?;7AUxUy<ԉǿs2fjr;H$0sX 8"MHJ?%r"9 c=o>ALx>A@,&<ʄ'۱&ńX[`p\ "H7a(AX&0TuG:lJ=w^惈m%,_-m"r=ݐtWf8R^V#R=LHA=7\ 25`{! /[ϭ!Rp :vr^+)JܠnlAU"ޥ\Y񿊧v'~Y{XLjo"vk.eaI9ќ^;N   dvް$xmE}Tno[QBhW !l)o {v/[[d딐 0+':ak0 O@xsR49ٝʾ޳FaokF *TEq5z;ߗ3%lT ?IwǥNJ[k eJ. E?]| Kb໠'t[9b"*b]tޘh+ B4 d;@o> zu)Yvz|zrl|{8$h/N*Mb'Er&IAʥ6/ rd냺ot`^\;tXX{6VRx:,) +NKJ542e`mpXmWے~zg"8 oFe[AlwZmtI,o8OڍB7ZcZ НM.ܸ&m8 V=i漾Q(~~0|^gg"&5c+mZ^}'c~ _AP&}l8 \8 ,&2ȟhyI fԓi|gzvS\k(\OLUk281+ۺG{t]]t}NvIN޽xEkחkc)u. QX }d\7ܝ6v1!c<=_Y|whF7JK\[.ޔ\?JnG֠5u64,ߡY,߮(`y=>8ӨXmnCM6: /4H1o4bTd* 'Mcmm+{eBfZE-+mSJWϵ/:JƠRQS!5ErB:+~Pnl:GH2 \}>V%p.2 $9xh(߈=:y{nsCqn1Rtrs9E4N\ imuV>L!YtۆK$6mz"4󦝯anFh* 9ć$Ӟ{5}U Z%BmjznԼ:%jhsCF !=mfbudB5f~t L-z~s+X9`\%Fh] ݴx58Jh$kdH::yϭfju(2[ԲOu>ӛ쌶nJ)2I.gQKv=r!D},AF< psk8ЈtKKGM)) dhñއF% 0aX @1׀q% 2k%"[cPK[\J/ lv'pkcs12/nameConstraintsDN1subCA1Cert.p12UT ц?;7AUxUi8 gd %T֝d0JP#d1d#\kZQ.L5ld2A"3F<ssCG` ~K=M:\w[mNwCad gJйB8؛DnpPzNCP (~aBkQץ 9=^7;64'f6^աag{zָpmoUL||W Pch'<\?x?Z4[Ԉdߞ|o<~FJskٙjC?Rj(,vwWщ}a+O 5VSgPk^2UM"@r9ݛTUe+<"y/Q}Q/ ww: ʕ7 @u(X5\B_CUUiWg; 03 yآ/LS;k^odI\TR"a_O {#^Sz ~" :.XSa^mx߼TWRjҶbxz+[Ǐ`gO&RTGf&3[I9Y,j!\ˁ$q:ATIJh;sUbib)[kMFk$ʂ WUQ3r\T@pRu*w8NR2XjlJ!g ^MrE&m+/p}?ͪ"+6͚4fVDqJ(yY||{`fI~jD@EsSC|p0h!㴵q1Ʃ/+BmEdOURz/ QgCֽA8gcǎ8\[ĜV,2UEcׄ)d탊̜{24 `wE9ٌM HY u)>1!3Tx2gf'{wV}G2lpLFoqqx޹-nL/2:C=RßA{KgUYvJx}?zOW6=$ ?tir"Ǿ^Ew!ƜS M蟍]SZJr./=5^_gK]: UGgumP' ŷd/-ܵhJA߸znF8V[:)ؙMtZ?fs wHt]6Jߥ *[*e175%OG1O4‡Y|ѩ"Crh!G2o3ŀڭkƬN(FY0$zbH%,Z/y_RgI <܅gIw+@` D ߮0M ՗T⎑ ޘ !D-ƥPK\\J/KV'pkcs12/nameConstraintsDN1subCA2Cert.p12UT ц?;7AUxUi8#D":}'jUUEZjNmT Jk"un[ CmVjVmZ%{hh(ysssE@Ԓ,p@9P0 ;9+HD9!A򂹨ΚI- 'ZSM?N6hSDZYZv ZQ,pϜ޸`KXS&w'm#j<-'\St[+2`[DpP ,Z>CNG'g95TEoHDW%ALO+ZqMJxI-8IFaX(70-HtG)r1)}_`Ԉ3ik>5+F0)7>H/4u#b(*&寢c^7dn۟c?2 M8+joʺ0k>XgiygIrLApڲX:$t>Lg6y;\\7o/$cåX%9r÷%}Xw䨌5Tz{S,{*Y47V㛞pQہH)$`zG3L :b@]"d1r֕>$xUXFY13IO84I{U=pH|[27kAhJ?ͅ0~Sfy/|Q7#ES̮!xQm ;‰n"h-"𐫲M?m$kҪaqO7sL FtYZVR-UxN@՛m+ GC]7gXO"XWɲx9(KJ)9Ǝ vgV+}-ke4/g]hv}1[28GB= eo%S3,MPK&4!<H# UFJ~I8yB/d9`P@gOmSqC3XD# PU ?/ >N/O X.qe.69_Ėtg T_`bcsFwn$ T x@Uхce vCUR"oe=Ӕ$БObqxh87-rg> }LG\eX"IAΊ .Ͱ?;sl/FJe.|B>cb%j_c͞ba{&%]h0Q(~JO>GiƢ| />[(0Y-l_5b*Y2rv rG(ѳK=zD{|DZCキG} mbL9:W55rU~66fvby|y$7nbж;mQڤ됰r}bc`T|RN'Yr Ω ǽqQi+C'-aeDD_؜0=c+тaMT-B'\=wڔN}W.rlA^5@כk*YH0QZs+d8IMTbQ7_N xLd1`YS0:#H#R_  6:gr H4(/fA QfOX:.ytXtc yZEJ\\P_uWw݂pBA1&Z"!;$@IR$V4 17:#_I% ڤ< xfQ_ʝUqlj2x'n23L`8&}QqMa1ܳek!ys^Y8u!PE'րBryBXåfK|.13yAf`sm:=S:г-2dUpgKR',:H(TQ^‘CN- IX6zғ^XSxYi31€ PRԋp6 1 PnWdc^qZa'g0Gi*U /įo}5%C6I#?6=@>J+:R̶W/;2F.Z?vЊ3 0tH^.jy E4-_ F;%D?|7OG/^i3.u}L]:vA `2+hvqp߹^HXZ@]gvTiE{zUub-/x'D <3n($I!2j)Ԋ@ 6wPk]dsJP¹M"jr3~muDg gԀ ~-׉bm_ kI)U>ƿ'oV7z~ rɗΗzHͰrr'm\r/6ߴ{5ޥ^}p/"K[+ǒ1_fZ`ReЮNх;oMIMO$J&Y(jhL} {e=';SscŮZU7v3~ye{O°M ?n1LTO7۷̂w~\ߖ9ut$Zpక' phx_|ReU|"0Ȥ6*:D0PWJ\;^涣3[%nҩC|<͒_M }KWn(2mj}5}̛51NJD`;þc"1rYq%`W1^xċúh9?3̾8UG(5¡Id>SVwNk>HB َ<3 %nGvϑPT/~Q>>{S-= ,Fڝ,dsN4堐GjYhcdôOg3O(tҧ?s rG??[T92yՌT@&:\h53]vd]BiB_R级G.OPHv|CO3p!G pܶ89;H`35t-SW%vk3CI6[$Wu BY[So'= JY)Zv*/m U4-ݦcX!J[.{ﳎ58R:a}]aW I5TDI kCtSҰ̹rTQ]1&T=R~^t|mbn.ՠ'9(cW7H,洔wݑ_ *ƌ~\0^}F |J<#|slPZTv 4uᅮtPKX\J/T&.#pkcs12/nameConstraintsDN3CACert.p12UT ц?;7AUxUw8# 5F5zi8M4HՊUإfVT9 J %FLŪWQvV;ZEծ^y?* d](dn> +KL.h"W<"(JBs8Yhn0[lf N\-0D,ZpqrC!aٜ1Ъ ,R8"[tEpkiHhnwR4S?qwuN51. yՒC%Ήy<^sPvi/w{g|&sGG\).昍POͺzb:ޠѪcy]痤bAyϧbc%k7k鍊qp[[d6blaҚNg̊̚^kM LV} IZQYsx~v%6O1?f\*<.qƫ`QBI* +(=߽8WfW5j6bP+unrJ{v/D |;u Îީ4jJLA&77t|R5ipzK⩯Q PWLt 획jIG9*'Ϝ-[%S[E5nu7FFnj| BWuv$u%)L6 T/ŘLkS.-7 Yݸ7 990_١VE<;YL(aG:Po_pMkGBurV%|~VAl4{^gF#tƻ8=ع܄S>֞ېrBRd vazM+@^GˤgS< QOTgfspbRܺ!HݷAbM$PVH Agrs,<"& A//z!y+_Z{{DnǼϹJ9,ɴѤb5һHmɭDםzS\rA LXV:e9Qp}"kp\ M^Vnܚ$G̺mvvA %vtKg>,T+ٙ1P,4iqrO2C)D`uwxi(.f GQ?Tԙ[4:?7u'0S T9'2a'Eע궼'1'Ǘ.hO e'x>3j8;>Y$5Yސɮ@:$.aQ>-SM;h6'^2mⷤa@_.G۽J˻ 3IiS/$~ʨ|iBˇ#B|.M,MpUWl)t,4kԂe|+|wW~jcJϩ:i .]=rF%|wC,oէVo\ ) $N^Tu$ӭ$@ ,KG}8BBZ7!Ɋ A? p=3wAˠhv(D aaZ ԔՁWwܢkAL fȿPK]\J/W()6'pkcs12/nameConstraintsDN3subCA1Cert.p12UT ц?;7AUxUy8g3c#`:MaACA**K"sLЈ,( W:(YZR,c={=}}?F&t*:Z€yL7:oOڿV<&h*h8J@@]G;Y,H:l^'jqOcfl"v_Q),\GBQsmnN Ncħ k\a -Q)DG߰ѝB2ؾ"9Lև5zn爟lO z%0T9T)=܅˷ǣsiUc{p2Jˊ6DdRN#Y5 &Xճ>GA[us:C4mic>X0~Cn";rA^Z }yjT*F5 a%m}@E0Q !に}R abqaVONaF\a]hqN@L?ӦWDۢaIREl(yJ.%%J{1P1 I}5h83dj?ɖ_ xj t J{GC*(2~FV=ۤLk0`I'@]Vyˬ =' / ZQtqxɵ=4_v>rF;׷ ]3GC%-HٯaJ>sIkd|O6pJ9v)P1tΪI#gE*aGAoRĸmCPX<|!EvdB4;Oֲ# 쐽p(hxg5diX+s\ O,.oA+_o4FfmɒqEfy{ UAS&U*fa UsWyB!KvĂ{ W1צ_j۞ݾgݺ"QTgo"XTETIc/bc%f8g$OK>Sq w:W(ЦHО$׻Y0j!i]T[HxgXb!/)@u$8V?@( @P  *! R&O6k~#R4"8NnPK`\J/ԹE'pkcs12/nameConstraintsDN3subCA2Cert.p12UT ц?;7AUxUgTԀ4P HRđ^,EtԈqD1#W]4AÜ}htʡg{ %A $h߉݅&s^AsI+rgB<SM!I`nj˱[s-ksan@yIQ>Xoto^ v9vĊGYCA'Kn;/:`o;K&,/jo^]b94? Sօ>KXk_,fˋmgf0.SVh:+{O ]u$?QSy?%[SKY:98$wGC(ʓ} 9ڵ ~oʽ_jQ\ܷ \<ʵvt2}vwFMIx;JM!)W4;s皿%O c }de)gp(v[tR9k%jl3SFvz_$j,ʑ#PC=D? CH3'6\Œ%$5=y疆h@ 6jU2G?&vkC:us|HVsu 0ˬ{AMEupTp5eZH]Î#Wa Wj1ϲK +(|*FXָ(ySE>r XIrܒI`ᬄ5R+Nn\XO'{ Z#6Ćǐy| l 1/Wu<.t:ç:48"w_7wX*O듓ARHT'f2 2e?$JUwֈʤImΰwR_j;0:u[ʬ5IfM7:'lA¢mU~4|72l"`rƷbFVΉTP M>ek7o\1S`{إ;jODnv6zJ啕GM{L>;q3q'NH]c+5< (ɭ| IPT!5tPU5jd:ζaytpg=Udk%7p\w ~K|:-04qmlEp5PD_+z6H]q7A?}mܴPA_9U 2ҜŹ\π-da$8H.<׉''Z -怲!y 8"zeJllx ~ߪ)=HXPKY\J/M%nw~#pkcs12/nameConstraintsDN4CACert.p12UT ц?;7AUxUgX )$t$D1PB 'l`)B ( MWK1RiH QR.Ǻ(#]˱sw{aygۼ? ApT8Ƨd)p< :qT#Xt$-AQG8iA ' 啋:lzZ ⩐&|!*xUeВ2˭UJ ;!oVn$Zi;s(&@yٌkG 9j1 r nzϳZxN󋩾%s7ok~؎s:Oʉznvċĵ]3 _LX/zFyiM4EG}vjU(V|yFO`!+}V^ѵMxJRzjMlek(SRrw&61z/.me{yIE^7v݊nJOS$ϕ( fGmx.9|GiқưmaFLLKK _cv0ڞ. %* J[O&zXC] ^,4bUG֗1яD ex~Rd=&LbAT\\@˪@ݍ6.DGlUҏrW4 坁ٖ1S<ޤ謲ǩӧD5j*yoF2] i7O3dcw>cXΖ +$a$`L՗ /UM8EӜ9q\=*Oג0%:0lkPerx|[{t Dc my ۥߝi^=IUAsL 3z[?y=kמ^)lVCaګtUB'CȽqg`+Z!DP`+_Ծ^ Uۻܴ6316f.l;N5Ԫ|͞O=YS ܪ_S_v[u>V$vӜPt;NJOG lvgy|RxZYzۺҙebW)c8uST.42nGם >Q{Q|0`}nI+.B@ZS8Y89"g*ǎ %"NPZPdmmI^)"|ۂ:qBp9 ; pũq|00,@ھ-F06B5C4PKZ\J/,#pkcs12/nameConstraintsDN5CACert.p12UT ц?;7AUxUy4gg&˳OFMKÛ{A$icLY̼AMČGcmBY+["Ke-31=Ͻ{>Xc">08&.I "NR! `l*DtA@@ V O#a% h:wZD T;Jkx-N} Kt]Y(˚=P?H%c˞.ܜ\28gk%vc|Ճ#nuc9 ɎЍDMy +ɷ˂H4A)j-2/\ώ;G{k Y3t*]+JURYz+L/w~NנtKmĂo\|c˴|wDPҌ8y ]$XfX~{Y/0l27D,h{fǜ>wrɻSPC nNØ3nVLBTNd/[/l=$ oj#8w AYpt HJK4:oX2땮*vƏLˀ?Op<а Nj[~NͷOzɿꖞ&2rQE2a@IXt朣! vwi woӍ{ c݉vgm{<:v=(6II47UJz,{RC+1S˞S*)&f甚L5=P,΍r w4Uv"qE/.E?j\l-T_Y-fR9$TA]!rU0EIuocG;s 4BHjUұ<U'Co,>'!gPۂm":fp$ ŸtֻG$Kwu!{ O,J?RG7 Q^/c'A1\h пVP2{Xr/`ĦJTP,ώ|W5J*(>HS AQ2FnS[WTxV龷!'OKĽIxhډp354`ަ0#lZggoP[ZT6<[3o*nh }0z)>ĮG0㻺K(_>49xP!Nɱ+mdz~jkZĘ $f>C1/}D锋LݰN*8"xL=5^X 4L+YDo5 $^N- i,E^^Ddj!/o :1Y_<$}pRt]x&(#BmH+QGlFfw)勞%^I4M .'FuI坘 ӇQم2ɧ-9>Kiah2s%KqC9g)?lz :L䧫/0Zha{PKf\J/$pkcs12/nameConstraintsDNS1CACert.p12UT ц?;7AUxUy4# RwZUi;%v6yQE{4ڂCվ%Ri_I,Z$LXQ&-ZT9yw߽ B>@" 3x !z"&B"(;bB! &AHEyغu<( ,4LB$}l+dq^{5b_618qnJy 3).V?dHŘC?耮)D}N)^f{BrJE+ OM>!ϹU^il e]p ,؀ʂ~d%#A}KPE̷yhbJ W'GF-9G_'D E/p; ۫)r:*"QM(K T{FG}h-cjls6v ;5Ã{ d Wm jo=1wdy6st5,)HHW{k_8(dI h;:k/ҏaPE)IJe5F}גĞ}I8n\G+w% -b؀H>+/y&_psҙH@ b=u\q[$) N!~u?]#'yZ^3cEpbیcCf*`?#{oU#Fl"!U0 }QpvpxD@x_8cprEtE6h>Qcz*½QTb_Mueճ\,ڂ3j&p/Ȣqxaäx.'C(cˢ*.5㐩Bz^.njfd,mjAfW@ϟF9Nw=s5ʱ@ƢM7èZX\굧w-y6Lfՙy-ps)oY+d񥶹uУ5[0iHϹ#duHobT8'ni'#%w}g{ V氧gͱG{8Y!Uވh-&ĩ}XftJllcY~ G2&jj*W@@`$H@رBA}(JJ %ʂxk'Qqh}UVoPKg\J/ k$pkcs12/nameConstraintsDNS2CACert.p12UT ц?;7AUxUi8%%UTkI(!j ZR[6FP[TIkI[ZUkS۵b(ZCZ<ϽwswH#I(E9XF/NZ$ |?n!Y(~ )ᡂ/3 Hk_)8m 9IJ^shhX1ȯv?m%ev /RI ]h7A,;OO,ݔ:k2>';em?tl8N-l"z.S]$踼 SwUk;|tİ3wŕvv5T@]3$XI s '&}m"M;se[[Y~L0=np+̈́Y,=֔FMa $T/GizTkZvL}6SH V N@BJyiRrTʼn-|M|1s)ayv5Co&im>B^]椛Yo.A]CN&B24cofl:k+ qrZ,F Vۋw0u)U br N[rz.Ԝ_GFxt^L@9f)9:HUxƒꢸ.*5=ɿ|]P}m^}[r~ ?Ck8=?13g6.ŀRBx2;l6ЛنݼIIA/^ǡ&%tNq!ȈiMV{z jbV + uLڗ`H;m 1lC'/6.&:"slk , ]_l(wEaֳf>H>M{[tGDcED=0EuߴF2Pw~s$b5y=0GgJrpo[)'g~mh jV 󝀦:!$0: /v|@P T$~h-jBwF D4)?egܯH%Sk]<ɧtl=;)}qK%FV|8xwqQ 9ONets6Ԭ{0L ! ?0 *K'Qiipoۿ;Go߮sy~7hbg䎠 \\kYWn<,PɰQ]`J }I# /ҟZ/VW9a`\3wU/8.#zŸPlqN*íIf6yn׏o@ ZykcaA/"M$ )kYav  JldQjCG(f,S %'+_(OX[b+XwwL4 J-(W,ۈXiH0gT_;fMf^n]V)c0qY)Gnwkcҫ=RN ݱe\/bJ-lqג>EɅ퀈*C箝%V%2 ;My L1̝sm3nx3ul,crFCoهkBZjx?+6QH}5J"z*[x0NܩGKdd9)p?}HuI @D]S2sUTl64sh7PKb\J/$'pkcs12/nameConstraintsRFC822CA1Cert.p12UT ц?;7AUxUy<ԉǿsM 9Nn1&B8=Ua> 1"ULJKɑu־^o=o܅B` ٍL&&oA %Ld3l89  Y„Z!PpX/*!3B .( *00SaҷYu"gb!]SGHw+KB |bE S~evGY46ip1;=Νѯ֭FqO?(Tzt;DJP`[ m#Uѣek57ʕ%5Nm~N3Oz5Qaq6]iWq&]CJYrcYg3u %FEutYWfi.hALbo >˃*΍L)^ׂUex,_םu3AزMo =V6}s#]M3\}g7}bW¨'jT Fkĵ۟˝R@k 7<"ԙ*9 Yo)mȗ-:uZ"/jNoU6o|"xZH/ibfQ"IvR j}$`(?p(@|a@PB .#V)+&m ՠ.x_!'PKc\J/.'pkcs12/nameConstraintsRFC822CA2Cert.p12UT ц?;7AUxUi8ۉ44bd,P4J(jAk)*}iJGZki"&Zԍej ŠΝsyy AvlfD S-Q˴ָ3Qnk}_K]QIΨQo=B|Ȝ=Xy{R":5Qص(+П=c=1sL>B6aW{aP2˼9Ɛ[Jpd pҸsd9zF,HP?;;@[KWl_ .fWX3j{VwTo 0S!k,]Զpy14c؅wzgI ZpK>bf?A9Wq6y${ͬ{.1x:)+v}6M޼0dh:XRmkNׄhmN'aveDi3-qޑ}TO/c @#gľkۖ4=#\YBъѸovRȷ&0evh}lHA'慳Gss9y=W:YG d>0,u6}HŮS1 *`6C[=wM/QB?٫ٺkE@Y⟱-fd:j<+CCduՓ}9k>VR`uf GoW;/rL֟8?1 E2r0.:)" mK܌, `&e+ Q{)%`+QXިN9VsmU[JnkSP7[Cq~]uRkZ)Td+RvjVa; }Рژ{"[laFM}g<[(U-Kb'qelKĝiq*_[ԛudkͲnoL6$u;Qԙ*e zY@Wb5Y-RF~[`u]yYNYc֦#>_ M6A$PÞ r,sD7`+S&tD{1à`nhBpX}I(DP!Bxhgwkl󙘕V#aٳR9 H>cy׏{/= =Na}VBb Uvoyi_'PKd\J/ 'pkcs12/nameConstraintsRFC822CA3Cert.p12UT ц?;7AUxUy8 g3=&;5#-?iRuP];n)7]47FW5$nE,}}{>97!`(@7z ;ƺX̡k`t8w~ С :4l AB\?$H&C937!1=V|9@Bg1M9o`_ IM ǎV`#* L yP{4oqU._b̒sӘ2ͦ#Ēk5ɅL8Y#xo&Yw2v~hǜIu^55ݪȻʵ)ZiGv8ISv`trzI>рcx([eC؟$e4BJ ]I܀[C-Z?yj^i0W;?<_YzoWl0mdKjսPuM{M(rq48A!4d8\ז/ ?J+ iuV+;,VU"7]Gr0mwr]Mca;!j/ܼY2/{6S`?@s&tI)v"5<_Tcjw~ VjD*jX⒓sLeqmS"C4Y娕V^g06 Bq) ` A|Ns.;_9,j=Ө&!ο L3]twl5;ެx> G)@fu>y]F} Iq2yU\If=QXh~v`"on D}]* ]†1C2JCM^rLmXk1LĠUtzC1 t\@k<&Zg t3ςPMX Ӛ!v  $ߡmGA[R~F-?*P}[f_pb'pByѸYK::0:[l]yFĎz$E1U\[QǺ2:.|2ϕ Ǯl)%"i9EcH$jہy( k7ymƐ"%r텾%>THh׎ݘ>f!sɤx3_oU 6WlXԡ%>k8Ͻ|{"Kp|S6vdcm .#/stj] V.q%k-jxĈ["jԀ]g6eiVvC'ef3СYGL ibOqc};Dwjƛ'V*fh@d<?5#OG:!xʐT"7Y{MUˢrG;mϪ'Doz])2}_O닄5$Np{ivbmH215Rx=s] 6t``[FyJ#<~PݖQDZYΐ+ՋML5sE}ƪfMRF&`7ufɸx(Rws}KK ųN*b J~0>dcz)>38UwZmcRd h`HE_ok!f!54@P0`P@?`\D_ Qq{0}VZy@Wd V8LS]h,u!OPKh\J/=X$pkcs12/nameConstraintsURI1CACert.p12UT ц?;7AUxUi8ۉYj'$1M,iVuEH!E(n#"SRkͤj-؋6PZSB1s;~;? g0it} IP!j VHY`W/Dd@0,T &NR@ b]m2ypoD>JsiqݭG!NGG>aZpd*Z-syzN,R.'W~! ݶ5SeȜ[ij՜q1yڻTe㸍YҮu=7H1 x6N.%b:o=+FXi Ɍ7ȯҥ875ys~bHDjsyx-"hhG!5_B=_ktү^"/Y;U҂@ѻcww\e/U<(GB"vSD#:V7>qf"Pۘ8*:go~A#ȅwr9ޗ|Rm9qp=A\`_D]|Pr']Ebjflm)J]%5#4AJÀy<Ѷد @kAFy%UtkNcC({ǴP}8|^ ꍁKFRzS/q,, D9ckO/ILb*?xyk ԴDEf?+7o%XƴmƦ;볼54'V9̪L&S3EKOf\Vfw$\aˢp{-ąB_[0X;f;+0kz_Ez2׈JФegi:u%vT?J0=ЎNJ!.tp?hEcnPP:8(H`Lw‡O)v!<@[So\F`Z p|Yi!;&Ւ?2g;]CMj9<ŸBst'+ BQ\q0Pu"o#!]Jj\` be3B@KVBH42waZH%fvg&M#:?e67'y/WO 4 Ѝ E%^Tot7nJ*g*~|o2++dl}}s*Tc;6Ʒcygbea r߅ߜv Bۛ͡ "bc|֣%PB]3Ob5;&D54\R&Ƌ=?q+y"M\sS/UեkBl$$\T '7bw\Rfy̖LdG oj2M*w{q~/pn(zO^&^Gr!#15ߏr5UM"hOFFbЋ,<YߴiqU#JOg&2f%Z:LDӕcC]~iayGN5 +k_n]&R.p_-EC}r$pw .%&)cͿup *%D@0^@& 0 MYMhh}4(z\2ɞF{R7&UPKi\J/$pkcs12/nameConstraintsURI2CACert.p12UT ц?;7AUxUi8؊o-J%RRkeQBIj%2ыZX2je*Cm)n[l<޹{99߿CB:vɻb@A mС v2`KЊP @( Zʌ`|ּ`~l6z9Ei)GݥT)iz=q^Δ*qڃ35?^a2#iކ9]`(=Ua#lOr%_JRl$e\LJz0\l_řa+A/ircXuf]-oԔ"VlwvG UZְ,/ MO"Y0 ?]aWִS{Ipݿ^+8S=f82AsX@>N+]yH_(电t:3eX3Uz"yF)_Xނ򙗘~ 5I(U7Oro_f>N #lW}8h~d:SyFXNiܓţ[AN Bx$н ߌ)XHpQ}&t6}{XFaRęvIe{#EzO%!-.XUGT4Um +kVp6Cˈ T"3>'8K?Hlhh+ڤ:޾53V|- — &u$Z:Mr}ך;lzOBTI Cw˷ɝFswuTbhFolLwe9oL>ơ-mk転 qCD-&tm,~5[u~  N С=%B@Ru cD£g57X#w׫;}!x|g\ܘSKk<=ԵRTA`$:ŏ%/v@BA'[dL?iA4 (kɞnЃ\:.ݎVPW:߃ }"wOr3FYyv1^n{8>H_~At$ dg,/JFW;hV. !q;icѩ}!xHD!Q"e'rG8kZ9TiW=cnCskıLA0tqrQڼ Ww pj!i"BVNqY'$Y[St4#"  PXQh@ X} Z -@SkiW˷śEwڱ!hC5ѓPK\J/A pkcs12/NameOrderingCACert.p12UT І?;7AUxUy8 LFhcdJ]\ӵ{0Lhɞ1A,c%.el5%;}9s)Ap48[!0t iwPn Y4H G! x\MC*nR}"`0H\Z8D";in \>ߒ,#j'ݚ)e ndJiX&'ITqNPyitŕ}?]SI9b5:4'IcYzvsBZ>UVֆ eAbg*>P,.LUs-TTmo{Z\+/ Wz5LD?1=x~Puņ[]< &^/MX&˙q:1poQ&UѪmnF%GIIW=QR5>kc\kzwܑ_oDbb1eF=c*mcӳ2S/yldq1cyu7 W7vT ۧS9*j=y8݉+[b8:Guٷb[W!Ϭ;UFG +G;ෳ=/Ji -9ns: Nb.HDϼ/kT6n;23#<*6[%Wќ _H.OxE*>Ge n}.}+*g(ؠfvwL̢Wx(~B Ct; }Xݷr%|H2.ގ'9yQAF J~e5TDcs6 Τ N~1Sӑ/Nu B\{|Jt&BwMD*Eߥ2^eλ hTP&?Fjcu䤗6ZjU]Sse`jqRVٗ"6'Q|x!+/,tM*'>h֭1,pa^4gET$.(?Ër+AhD{ _4D(.L ZqT* owrpZ^_U@nF4?d3e]aqGkt_AVXbƬ,QGwGIftv3Lg-QWz:V]M; `iޠz]n7-q25 ^ )ܯ?9S)?GH<̀IgȀ'qkQSIaEn(Ts+Fg5" rq{i}PK \J/׋%pkcs12/NegativeSerialNumberCACert.p12UT ц?;7AUxUgXӇ-%&X Ȓ)Ql0"5`2a2P@Ed)+S<~;?  Xp+{@b  eSw$ aAlv`[L/D 8A*00y0 ,޻{4PN'-oVBSSBbZKEN0@ 'G7!ٝW]R"Y!{E Ө Tqr, E,l~Rdf$=<>"jRW)'leAr T=?0=Pڃ!OTp-c'{2[{a~ \7x4ydZpDEfؗٽ5 e靛]lbWzH>&%DR2hʍ;ց]b^4Iƫ Ԋ2.WWCiK դsR"[^["짉sYZV#WCv! nЖw VY}Q;!_tzxwJ6ik0w)S *tu.z4 Y f (o>4WȗڭҎ*f z[Z$^2'Oy:_RIZTK~dH]JV+#O58:N7 &X٭f`'gTE -S|v RiEq:S8~ե穜`c6b15]4EDʂH]ਿpB2H #Pe?%n%HiO_bv8*qҜv_㵩ؑ'w!4LV>az&y{e9< . ҧ1'eXwC[=E2C_%iW&'q8hwPuk|2_桄#komaҒnf{~_iZjpMq+l`pboS/ЦϞ5awՄ=&, oIO7 :45qJ>qD;TCB袩GKV RNo(:9GUˆTl.%h::8bUCo`o3*'y*2;RjǗx.6lU2 . 8t]086D`t*Jrt '5&%u<7o'xt9%*Uc6Ӥw }j[?ǙS$VeFbeo[?ÿ~HX\i+'v._%AeW[_yGϤ_iP?G2Dee\, T pW~n@8@P! 0I 2tUmoעIs1P[IжPK\J/4ɽpkcs12/NoCRLCACert.p12UT І?;7AUxU{8 s1}\Bh 2!6uДJ+Fk5iѸ ܊Xb"ø,1g]x=T(R4fMҎD¤"TDRaW&ft`C!AGTB5B8)B@,uqR9{ָnk[v^˰&^ixc*npc&FGCT1/~#oqU=^1p=Jҽ49S캷7 oiDOA]"~= W}.7e098&}`KH!?|!P&ZRE 'Ud"FOThvitwѪNuAW>ǎ{n,4#|81(1 uij\&aeIkVSI,cRkt4xyBLQfzHB8;EaͼL&\Ď==V@?k\ Ku->!1]3C+UY_)[ΒV{Yxʥ9ͨn-T w[A FTq'UM5#9q%Xui4DsO/@Sʭ+C]Zj][`$: zL -=Wx*GO7-xC'Nؗ!F׬ehGGO(os.T '\ d _ ILQ TPԴ#+Ņ5S]ǖϩ:SZ[jzzI Lr0@o~uBte2/ZEW|! SxP#]4Z p" ` !m ;}ڠ (A N;GO%}SqFWhpPX/PKn\J/˃+pkcs12/NoissuingDistributionPointCACert.p12UT ц?;7AUxUy<ԉǿs3a8ʭ5&xʹ\02hs FVl;h Ɔ¢M G" Cow<獥 {Ch%X% AO(vȎ!W^!VG?BXy_Ϙ8wKp A6H*kHlw_J15~ϤMMl':I:2۬YU۶O`kڡP@i& @ϣ2uslz _PDiBcTTtnCK@FQ,Nӝbci΂J 4(_el tVݺ3;!=w" (Mw>\+[u}o$N>g[2'r[γ*U3&[N;rSU.Ld|Un,.:KNb0=-`D-5s}ݫkуUڽJ/Q,2*E" |r _ZDd/FE҈%L^8\N嚜y" w47*$Levho]ڴj*Z;ڝL.DֽWi0؊*?+z'=f`@}ҽFrJP), I!wp[TCi-U|abc}\tX QhφDؙNqGCW0àEtn &(V:.6ײ2&sgXY)өt=b0;AR#R(D T14{ksVxB=y9ӆ+Zoo/t^v_Jni0E8D,߂^q8H_At= L8 O`eoq\.;/8| JvT)5++^~*3BxrXlT1z wd}./,"GU b! "!tsabuiD 4׽7k8u|2ndc_퇸93^1̰dvV0UD8Nz%'d[j~ d܂ͿǠhWWR'Kj֍6oa,M7z7ŅlI!jEFՓV? p Jߛܴ=-0/CW]#~5c[y }A2a/ig~Θlү*{6-qy~MxmB Y"uz0}0 b%Cߢet2.ӗ{8$1z&1օ[evqH ĩE0?+Jn1cQ7{ kJehf| 5.Q?hBgPoۢd [1ܺDHwkV,`wXxрWuNEdUfu%q4 (P/S uv;~?S?RBG$Jq.bh=I:x|sn^5/VGz<`DJ9@P zS'XO[6=9?AYP}aimPK%\J/%Ħpkcs12/NoPoliciesCACert.p12UT 6ц?;7AUxUi8ۉƳIeaAQFV-\j Ehj)2iҺh ̘NhD:ڂҠ>R<޹}990)pi[0 8PӿWp:4 `AQN a'ܜ˪6>@ Ҡd27 ,&sG>-tt=)4]+~4[Se2>XsN)S5d2C]gOTnjuiQ+mv.%3z+Lr1ަ&Fc N3<'0'!X閘vE 6t}K/ tvx<|H b8E=DRܻ2Nl3 *"(7z}AOPtrޓwF. đTo貸^O|ώZ / *oz_7~nyf?iי:)*>Z#)5I6VF`U2޳V w]ΘBݨn] xu?_4|W3QPlu 7;Z}>>f~E/5 Qr-Sg\]ДaTIa%AY4F`A7&2OĆ0L^^qJj 9WG|ι1?F9sΚΡ}?#} Dx&VX~3(kb !7[>)#qJ'$ &ɗ]yq cy%͒ ߨj=o'g_pS[b"z># T9i=]Ds#Qkva@:[mA6\Pi_+n""C]Yna[)ׄ!&`&aU>$ /&H0@qzѣhCE $Sr&So*n3PK3ˆe>nL0c*_ K^`;F6[9#fp.PqMbLz jz3jB0tT?Oh/6G#1c]{|#O&?Eɓ{ޗ7"w\[혼wHhĦgAU>n8x̝BwKZnӕHqc;c9"ۙ_tVְS J?ld`w+0dNIѶ=:4 R>oW崽CU3oW*4/.prHolZaϱW3-S@jfg'`_iL9tN憘Wu4+?wsڊ cXvɕ?{>{<ǻɖad_F{ʓN"@}SP,(#y^$c-N|ř ˼;-q$acQ*^]Si}f=j1ձThFJoYIF =p} ^:9, OGlՉc PH Q@aH}0KBR *ʭG`kahdm"Zlq ;\'PK \J/!pkcs12/OldCRLnextUpdateCACert.p12UT ц?;7AUxUy8 !~c!Dt1DY2Xfd-eDYrCoQ' 5}=TXPa0aS[bBTX o'T 1߷@B"L? ˗68K$*YRsN@8SoUmʼnWXf ]HLz -)=Ld*-reoK,DokSioA燹:6z<.0Re;C1& @۔d Cr%]/;kʎb..Z\/b47dWPu0n~sail{!x ߖU =Sҏ>JQ~ߣH| :aeQ(Gv%L)[d ?9}W:811%e{+"^;𤋮ÿGrr,]E |h)T)JCy<` ! ǨOQO7y')[ Z/$`nf&1.Cҋr̓5xl^Жȍ/]ʁhob! uhʫ-?^J:6 =[* :g:+M︝)E.UP]%˼dsaZ%h`v j OwIGz~[̋X0ů2g@4gv+BW2檨gOIC<AT1~jv~Wh"3N@@{|ӲU%a_Bx0״]̰~dH Ăs17zZWiX[Z[{~?hA}/Q1WPw*tAoXE N| IMTy.}-M(ǚ=MH랢&?f٤:0N4X Ok * =چ @4-h{N ZUZrb <<μ>W&7FɲU[p#*g 8_{XïsmRY \ 6V@\BxJ6x +BoCz ED0ɈY ~ \;:'*35N#dIopO%1ˡN{u^U&0TVrͳQvGosfׂ+,aAG$]w\$8d&PO 7&wk6|H˫DF[K K=DϨù:yWxKw̓adL%Y6V"zrs=b3еi3$SNΓغǀE'Sb&QH]OLxt!4GüAQe]]UWʭ;W[Dc?$?1Vs_JGgd#y1W=~uD nݬüiHTA=)*kX7%a޸Ԥ/o@Ȼmt>BbhE("@QPPA}pPa:AA{lCk!2'[.zPY93OPKq\J/ +pkcs12/onlyContainsAttributeCertsCACert.p12UT ц?;7AUxUy<ԉǿ߹.#ͬcƑqV6JdNq>qB~ skQgX:4$ *XfK(hkz=o@8@D5RR?" /J)O d -Ar(_$B,m؃DD+ qLݐm4h0lD N|R3pUݗyE|MWvM񼁪ŃW;76+/6VH6$R 0*6ЦZ)z>!fѭ5nY[6Y?gNчmN TS*j^E}5J2{^٢ I6~S?i,4ImjLҾ/'vzDBw^~HT⏉b#Q?yHJO6~HX-CُO_@IJ)W\*2(+63D,/y) |FpƉ(+VN_ f@ܽcqO-rbj\|RU9bIk)p.4]$%cUCv) jER)ɛVyaH7ANYx/!?@G= q6Зp1&<_ٜϬi(Z`zڲwS0vO?|O}GIY{AgL(خ(E+'N[(7P2Aˋ.l`z +VMҢ)z}΄H1n'$jږy%he;{/oIDY2ǼOheVF&?1I\ t% ߥز?,G1숂u$Hǽng\&C=WUQדUƞg(%eT*#èJMyIwoƺ\9=G2zY栫뵨!5>F(3K}7&c VFþ#tCyΕ$ wjJmFꭇPmcN~'gˠFkJa`$plL1au6ո(^Ϋib£^OiM3\ܮ36sr>֣tiq "eT}@_΋U&{BY(&R z Zj3#-1ȘqμQDA|ʲX]Łzw'FĊM:!;P&ΡTt-0E.V)s1?C8]9  s"@O(oSB Bp p tCїw2miK MPKp\J/A?$pkcs12/onlyContainsCACertsCACert.p12UT ц?;7AUxUy< fƘñ4 jGLQ~(ʸrWBQqLC{31m Ґ3h[+IJ#ʵڬg$ܭ}g}RcbC g-,3W_9z18DciF˙>$ :WUQAdq%ӟIq[;MjvLoE*ˣvN Qj$%BǔX;ټ|>ڝ~ SK6s4DRPF6 I3Өmh qp|ҝm)Wzq.)h5\uCJrdܥf]3<5ErFo_xWJgb3痩I|pv;O}:VՍ#L;acü@N,QkD4.8#sx>eN.)qyrdxZ^۬cj*=˒uIC2KjwkœE v@#1ʿj}8ϳws xg!^Ε9=1ݤ(AuJnAfuJ,:#] J|51Z{_6g:=:;^]~ℶ||,p%7o\zˣ0(;׌N􀱺xYq mGZ8Yʞk9fFXP"Mt +7SFL]~K'ʲoo8"n|yN+:0&=%Z"s~\\vJ ImB(ehN(MvIK-EC_]֕d آ0 -Ƶgܟ "= ,Du[z~æVG7y-$M7DP\mG%ˆ 6vòP6n8"|ގ݅9tdztiɵ326j4gr:+Xi~f_I H' @^A4R$ J\D9i , HM)jF D4"PKo\J/R&pkcs12/onlyContainsUserCertsCACert.p12UT ц?;7AUxU{< Fliı035eؘijv29ּȝC$v\{sH),z=s~?τA<^W6u]S)L8 ʄ3m: k0!ۖ=l 1p j 8^~hpA]0d1!| lxgƭ=ba$`&u՟Tu ꝁMA+qwHv碨 \L Kգ+nnH*29_vAk)og33~GE;"23ع$>}~`U< V1#;H$c*jwGOhY-lqx8WFB5ur4.p)b]Gu')^lh:I?z@ެ|iGf'e5mX!_wQל]v5' n9zbn6JЮeaZD鼌G7(3O_ `;-Bh<}.mL5E,-E>i?+<ڕXg'k)騞17?Z%|xMw~&avf?8>QW>Un/Sj4[o-IH)uo{5h,RMoqN*UsF=CɦK-^~bq3P{9YfjM]q%j&8T6`X?^רDҤq\s+g2UKh+!=o#z5(nN-߱iPų2!wKY\ BB 'MO]oO_n$v4vZ,jo]-BWo=G+Gϗ)i0:р N&Ĉ={Tٗ9*-,h ',&L}o'J|ʼnj|C";WҠ bVWwZ^.rD=A &䅫! 7|~@g"" ӫhI'+ \5Q`yoViՖȺAa;Gy{P!ב>, D @V8G+a8 X@?zTsg$VKjr0yrpPKq\J/!pkcs12/onlySomeReasonsCA1Cert.p12UT ц?;7AUxU{<Ӌgߝmfe mrϭ4⤈\m8:rM: 夳ܢr'lj[%~y=yϛȄ"Z?%LسӈL f6{%X WH"b H1(Bչ40ຂG3wɌBG6&SZt,OĦ)]ev ;\6_َQc4WZ*v]{iQVc,M<'|KRKQBDvL 5 v'[aBj4NUٰ|ǢE+Ż;uԡ9!N-Nhnu8V)nOKSa`> -` ; =e韬Y6ZIIJ [\Z>"v&(NII̹=<3`\\oԏD.w(U~8&S$1[C=hWXJgq`m Nfޅr gZ-Z9aK].+DI/a4H|x}GSZdA* 8c\ k[<[⹰~-ThHqdh1!YZDt]z҆ew*g;v.͡(Wn}ulGm_b/|;T֪5)0wJYdg7VuI˻J| ˢٖey^Ad#{|[a^ :I;x/`+2XA̾5biۅIp2m}v(;=p ar{Ԟ$!f3UD&tѥ"EME PN2?toh{޸n\ [V,Ii5#gcas!n|ܺHГUa:u0vb[YF~)t"?4q_AT̞xiZ-Upɧ7KCc0yRu^A5VV7+7d ݧ]{I8lN6Zەg|x?pQLSK-LYAZUJεYkԖϣq%dX2~6ƵaU,^|aȯnY% I%ƀc_7E{o r&x [K.LƱ EHW;:;Ok5#l"쿂P:CD|K˯ Qu#|H?޴A(wof+<)]J4"tO1k</Ń|`vJ.$s/dٌ/Dk>f./p6znSjfV 7}VZOF˪!`V+d'w7ZV wYԫ(R=Mu>-N{k429m:&| o U1weŷcr[ %yֱo-| PڀqZc(AvAF;k_GhC r@P,( : P^B#šw ~G9bs槮] -c{PKr\J/fd!pkcs12/onlySomeReasonsCA2Cert.p12UT ц?;7AUxUy8 g3`,~ e+ $tmK13z5DD,eIٕxe\2I&Q+u.s|; GLsJ" 3?Øpƞ0LeE aBTzi !P *T)m^#׺}o^Nj mȑ͕пSE5-7YCCú;7 ?gzx;q jv K~F3(?D 7ÖG7zkd^Mpjdžy7v,V#YV(sf%b##M^QZ/<o_ )Njl0rl@hoHA.V8:sF׽hcȭ6L"%Ejy|G1[Us 7b͐|a.)-tr(6Ã1듀5/87*]aw^9`A@q  @a=d@Pp-$"/I8)PWoNΗT Z1PKs\J/vY!pkcs12/onlySomeReasonsCA3Cert.p12UT ц?;7AUxUi8_ID41MvRKC,[KQbږ&E:Ci,(ƴUR:Scیy{9sΧs~ AYqْcAlܷ@~L "C2m/)(P@GML rSryF;U n.~(ۭX/PDR QNtMNJM,.MWŦI)sޯe5& N}Keg憲C59?p8LElqM ω80%YנavtMqȪĨlCVF%̟m}NL g'bٗjh1xNkU6,̮q6gZKHfg= >2Q-H6*1 C*'u-NlNԠ\g|r3SzGќٺ_=#m%rb;po~J)~_v tܲZ} YX:! ݔd)q]`>z11>H|EOH9q#Mx+ry5r-K{Ya$~ZraN#I)iSQ=n曓jRL`;XlaMW @b&9j fߟ;T{ Q[ ńz~{! 8fߖ/F`,!؝~:>&Eelغ,\ֿMbk5*ݨ.X7KZY+ч1TSAv9y42dȺXZ_;0) s+E^#Y"@MGErԸ2@q| x:}h)(\ʉ4nWz{"Vh%a̛hJ+~WYLlw<ᒒOP4?we)veU*pEw~+e2SJf\|;i)%~5϶(ep7\h[ 9;dPӎ .Tby<Fn׽({a՚'KQl(LLaћz̘. O|`6qt_N#Q'bj5cі9m^Q> lJp~C ߹o?N!wİ9:$v"AncO9 :WuPS9еgx! W#a1ݶf:hG;u$k ƒA  =)@ @Ű2P&+1XM?`֔]IN($0h9vPK(\J/{7%pkcs12/OverlappingPoliciesTest6EE.p12UT <ц?;7AUxUy<ԉǿsG #2Q̐#.F!1+Ȏ#/*mЌ\(rq;İc"Gg_﷿z<7DpD"Uo[9ᇔZ8>+ ,YPpTNLJ)~a7'I3=oyki(]]a\3nJ|t81N)?JxtcW*:mx?;?Lu-pPP}r՟ьi/D5]:85ɺUZ{gSEVR6mvtA'VbxW˧zS~ݕ줢3ǪkĢ(!1Р$CN\XuM"E,r1bnoˤj=z#J``xu4݉B 82Xf ٤Y|}ޔ#6D [ WabѰsMc[y3b{??,6Olk*ap&vdt q쿸 A%  BA!/ Vz.B8#ɚ$MP*Ƅpᆈ/D$1X‹A'byƌJKڦ虚Eˑrv~h䦕o>e].?b@O{G6ƽ vįJ.( Oriu ANgh"&6_p- Nh'`q^>޲ȜHP(w ycySq y$XA&H>=ߺƽ# y)ޚ%,kV.?XkR&i5RILwP0ZkNZF;HKC7WYS\>N |Su/sij5765q@2o_ ͲWGVRN]^ Z4Mpt5I[gzĝWc+FSjPU{aX')ݐ=!tƣȮ-ɵu%6SؗyX3\*yD!;.E*n"OtДHӧ]JJ\#zq X~%Jb4KWk!k2"^!̀KS%FCU~hZ(#»&[rd`*Y9cfmw,NzL3DB&m\w:~ tD d̷ 0n9|Bpkm(C@vobi: ѴG\"[eL-qC+SƆ+`3zHҐú'+^7u޴wM$[?Qze2SzP(Q`Z._VY^|ӟRɆIĤd~;5S0cfh>wbe?j. WG@ 5oQ=,)IkY}GNESnWe6N}T`,ВطSsS^:-Xͫ?d:50*?3sMJ¹>y@M:DHëИ S"{q#YƋQə2mvy&96)oZ13M=as;]CGCD%kgOq39rǮ­k bxnFfz+h e6 ߷mk[]>.n=z|Eb75 fQo#w;KQU*mݟ,{}Qb0b>yI';$}"'4U8V[FF dɁAdP(&X h s 6+)s CcHҿPK=\J/ㆭ&"pkcs12/P12Mapping1to3subCACert.p12UT fц?;7AUxUw8#Ƒ hhJIhUbSjڪjDZEXGIcTQEpyޫ#z{x{~x TS [CS\P.2MLx FeXO\!<󟁏 Gp:@ r\.Cdۧ:^!V޴>FIGUͫZqն,5c͉E]iG_A #7M8' ݺ^S$|jR2pc ӓ8y"Loo0Kj2fdܪ{NK8 Z|0.Nqky5(еh3O-pC ūrZ3 з[(qɣR\&q8iۿ/%T]e6z9-gq*i(p&XCAػ~)SOL*[2a߃r Q !j~ fةT 騉vÐA8LN!W_Pғ4֞^B%I=E|Xp\uY{rhEm7g>Դx>L9)V`n"aErDoJkBcO3z1B9~^^ud꣡ؗT0#\T8hoi"I[߿],^pQvޠJF?).n^ 'Zduֳ&l@aLc0*ȢWz\$L9>Ɩ)3#t$RU - Dg#zX|A\W5|T_CAvZMĺO1&>g)T$qzqzH]d}J"F7^[簉1m0u\:=_8"lA/|t/'!eΖXOHw6<$|k:,ѱqBhAGV.De|sYwkOz%z;Ls շ * 2 ݽ.l ђS]`u `_ė̮*Dn3#ܔ&e+==ɄLQu\gK~$OcQJȲ\/4pvSWWžhv|OypFsݓ6<@^4Dתgba{IM*t7Da8behUJ63g:AsEBǓ5*BM}bQk,rfh ~ utT ? ;V~28t՗jo6?⸪7¥h!ӫE^=J@K %_ݫDV^y^-GD7=nV(+=1H9~(ڒ7 ՔwI<`'tg: $/osV-p2۰+)YGZ1:sC_-ÚiGy}O$0\YE:;R(\iY?[½LWwGV߯9-8.'^NDTŇL3'Ҋ//k1CV*⩴ݖi\5dOM::*TƘ}K*6^>OeiM$440YbT Cb&ESay+2>9s* P jIVIB@(ʇSm9 w RBO[ `?F"B0νm  Fmxl^k#iթQSd;mf]Y':\L3޼˨Մ N΍1Rk_tm?Y/u%P}ɍC^')c q rQ`-J:9M7WD{8D~FS蠬%M'X=ֈٍs>|KÂ\P! I^*_;hYrl`#=zܠEowzL#iђ3Տ£BWн;4#$<6hk ޮ%}p]3/ V+ 5 CY bԺiaa*QSYF[\sJ&gkU/Q5F'u84v>P3! 9 jVXE7: qrX̗.ޓH;2xRlEС*JC MOPV/];^jUT&PS!H.>#NZ[UnAu^+>Y5Rᑣ^N5嵙TRB W/r%5-T0^=S6? I. b" B~#)*K%:ޝ} *Yhb`ux V; ZM_[mĝ~Wwaf} 7;0 k%KI%DVJ9PDM*[95ӟ8r?l4YK9Jf.x7VGJ3N=d˾JykxìUF厧76L/UwўEFE{dT54?y3$)3Hb݋- G,mX=+{AEwO+4WBDY ;S?-n[5GG$]oh\:LK5=a;P fn'-Gbֲ#yu2d={f4,TE"B+h2сè=tHC^^` Pa /?~Aa1^ua4/|H[h))H9T[8%:!o ma{"PK@\J/'\P+6 pkcs12/P1Mapping1to234CACert.p12UT hц?;7AUxUi8ۉƓ)UD$FKK'R#hJZZ4JK-Ucm˔ĵˠjkߍѪ#R;^<޹}99Ry `K͢<`&WE,{gRֱUK=ap0I]MI|i턜jE!+e EqiXwC_ JϚ}_3[wo: 2w,[XfŞH^ful 1ŵGcu~vrM #m45c&!YCeTXݝZF>NP1@d8ld~TT~yۥ =}0eL~R!ARu( tPBOF?{d [7D@O`  Cw]g.Jz"jȊW5t$S%AW!D86AúPl -2%*ULD.oC4б x[1o(^2+=ywvQ(HNϧHpGH/:"I9L58iB^BX7/Ƽs)S#H@P8'ݙh1`l,XFِe(ڷ[>ijcQѨs1I4BQl)7 C(<^V7yU6NŅgζ[l%j l!y_Ȣ9f%?r%?D/9(͕q.jZ~^ٓ~{GW綟! 0F0UH7M8tւW3ypD `$2Q^2gL87yZJς'Vv9ጐҷOM{lqiQ$x񊺵Q[vdS=PGIj~!ssqk;2'=n5cc/\+xPq[i:`y(c;ah˕{2i@i:k?UE2jDZMLbe=BNoR6B3Q(4$ [Xh [1b+ȱp2/AA9r` k_j.qk&YPJqz#/]IGqNɱTu%+ۤ1@I5g E?O3)Ʃfы]U7[+p)z"+ ޳g-d ~'[K[n:S_}µ~U U;?u>6ux[u1UW}z94IwKup_j>L > !NmS)D"*P?E`֞/z!P!dV7 Kd̎>ؖ1yT5-˙)1蟖`GZp:a#:[oB KWSB| ؈s[rOj<8]pC*]uB(|\e ?Orm*,?MfNj ̈́c9 ==G*MnV0I%[K8ت9bs~ڐ@`lG%J SSNX7u{Wn:$VRaUWLͪT]wʹ#<ܕD͢4ࣇc KtGi6\eEEUy?v>ϵ4ӋXL/.|G}/4GfͰ7$rηgbe^]11YlVzz|CǯN_6a%Ξ6UWN ܗ^LGxlӻsj*;4ڵ++&3u*<¡4FւXPw2Ul}$]pĐ|Sbe-C*ص١p5A?Bah'ÖShs'V_ML D$@ ppT^맽Z-à\`ǾtBjv.2V5Re4k]}67 *b5.=Y%Ғ(zmf\c:@V7;bsn&-& jBT1F1\ősUAb$`"Un9'&ė7ș'4LP&GIG 7s.9c510d#W͂˹ gw|8a%]왥\J )Q[knֹ8DZ QÎj "g^v32U% ?E҅KE\aTDiư?x?<a3쭁/x4i\zev-ObG l*S {A + ?Z. zw+tjsl_`3ۿ +43^_Tg ٽijU0~kRuLtEҶE4Jb, Ǒpgq?W|Ŋx飪)CYynP, !%Ol'Ƞ: D࿩ke(c\B#JKcm],c y<@EeT*sCefM4C-4(1XPpC(qS4M<8G 3T 4ٸ+lM̐{*O2)(w3hP}!=A-'3AT1OS䨵U")^2VBY g(2Qn^wmRyţiW&Skǵ^ !Y_څ "dl, Agv0Pߢ6<kÍf'DTNWzg"\I y/C_kΏc,aY&>NP&m ʊ;ⶁ2]3 ̡Y~H@I p$T6@, DA>Ab`P>tP/.Ci\'*OPK\J/o#pkcs12/pathLenConstraint0CACert.p12UT ц?;7AUxUi8ۉYF }i1B*ZFU+-ePb_AՒk'Պ1h#ecZ!SEkIb <Ͻw|xs{p8Q`apM5 HTMeC)S.qk@,N-S08-D3 @0*'M ` q(eE1Z4jk”ȈV0&SXEfIOlnFq fn: fP/ Cؠjn4(>WꙂנ"~ XUKJ|ga_ДWZi)Șu1M ہ#sT}nƃi*bzi^4޽uv>&H} }%rf;=j&JT8t6_y9g8;wxs{4 4D xcc?D¤!24D}Y!4qrBb!@= @Y̽o4Be$L"074B`4Ru(6/DmW?)f\Tqȟ@8jYç1%T2G+7_LR%yroqZpMkCv9aL;աki5alfn`ӽu}}!R.% vlyi+i̤Nm]k.Fڜo5S49•L5x;1ڶ+kCzLTgqZoFY%o7\QYH]ؼ$Ql+l!'I)4>ea5>K( `qkT|aDv[J- 'y4%bjOЩNl6R1&4ȑuW Vq~݊}o08K?p u08 g @'ʤA@_>SFlZ*} N&9Z_:.ȇHsS/w;rb/-sY Α˒e'Q痃tiwS &,l,,(~ {U/r?O*Z&XkmZ7TɈìAK,SKdE,^Wc>bO>KjZ9vdqqDwzµڻ( eVo}IgՋ⭄)_ڎҮ&:Z 'ق.ק󾆶ƢDٚa5nL͜خd)lnI(+nFyϴr9ArfZ^1\G`$FHax+6 ČZgZ6}1ojCMsQτO>!TZ'@`*+eF*Ig#PYn;KYxkxxvUܙ` e;&x+ӖRC3~m^X/Q814O8$͗(fRWj [ ~Y7#\Anr_1 ̺:j8~`GKmmvv#{4_b?Gc#!ZjA]sJ{[ӆ0# AC T`Q@4)@=o 6A,X `u`9P,s 6% "($@0T2`0eAd|OV5o0xX>r/mE ORT~m拣rVAl|4h:Lx\Jm>NO#' \r8?Xh-?*ѷOFã(B{1=iLf֜vi}o*9=Q}/cw{Bl5r'؇sjdM_f̋iu`x3J~VEԯ(e %\$w}Mzplh藓􊗇ihpH1Em "@`ae{j! yh[Abz@RZ.-o-^\55];8-k7,&Nv2YZ]@/TF0 u:{+SPްPŷ"3uE(p6|UUvP h۪ePBRZ=ԍ?*ZO[eJίr:Lx'6 ;uг7n',5"n"t>ơ[꺏ngDTwm䰲{7{}T^>xU*"ƛez >L^2"Uϩztw&^# mi]&A:9 :}O8=;tW܇S-AR} ڷ C+q.#E mXUVecoyGms:Uc(a zm?N7v$?zy7`=pyzT;Ø83 we-k:F\UyvXXSpEQy_劼Mmˀ}V&WȤj>6_~  '#MΑ'.l7YG+N&.s1e)p '}m>±^Dĥ`fe;n~+Ԩ>ol6g1[M|C~I7MxgqGj-{ 1a _^Jr_ /=Р\B4k^RyWG}_EG3:08U1ZbY$u-8.f`زN9zu]W0SFKԛ2+e:G]|S;=uJtLjC=L3ޒ͗|hDm7vo^kgkxNjJ M;BGl[ڎE['pw g (õԞRUSq=-371ݑ`XpIUҬۨ_2>8'˿څ: y ފ՝ږ򡓚֖f(jF(FM16m!Ոvj4(;4wQF4̋ X 0//{ $LL ˉ#r3 .0Df_vLwC+PK\J/3Ck&pkcs12/pathLenConstraint0subCACert.p12UT ц?;7AUxUy8Ɠ/WK0HJ]J]B<آc )*A ,n*\heel<Ͻw>h;h` (圵)?%HXxh߁h+*|h88_R3 $De w X -{K6m{c^e5Y:VGx3u;ܓ!+. ̬vͬiF)m^zcI)H G-zc]$9|.f)"cV)).[:.]n)L h MZOV}7 ɷv|OVřlD(D曫,N >iW =ł[ ߹j03 %PrM;h^ 8S{2=F7b]!ö_E$<ǵ1QŶZ{BYƞ[ްvvXbA.76简JWR^'avZ諿1V2Visη>8h뗰x as 7mS?k:b( f; iBJsVnqF4sҊгHh|clRwख6] <Kͩ3 %,m1MFq?0 ܶOd?4Sq.4N QLb&HJ0[$7¶vtΟC iC[PҠU4Dw<ɗk  I:-{r7F6$$+''1_e(p@}fX=ׅ7,[OSpZ_sէKaYĉ^rw1]5/ Jk ̣pCܵrt=I#_wۢS~!ܵ3?+z<S.2ElYP j[ؚu]0r)-c'cg'>\|:%$)8JKAo}HzhB[v;իUc1@sU9~#tX60ɍ'9MVƔKrijNLj"H3CaCjt̨RV>k+#ylPbZ7i#ct0:&=4:U1rJ6}66eAO^ih54rE y"5G?紣2C 7EoH2uWދ94ͰhF Lm >~A Z5xU=J5n%rغV3?BmAnto-`IΜ \4XtL]QԎ1 Qi%u7:YuvR\s?]_"`l-edYY (úNLm]p LCZRT[y9ҭK[#%Cuu5 Ӏ`TX,PA>҇4!IEGQ0R2eCWbӃ*S2;h`PK \J/E#pkcs12/pathLenConstraint1CACert.p12UT ,ц?;7AUxU{8 6̝6%c\QrM.\WNQ?gDˌI{*b"rsrDn1<Ϲ}(߁#?!&`p ݵq B-w-3[  pP?C B@ R9s#njahO}.̒ Rλv,lϗ^Y=B4><ưRȆq} , X2voN+)f,|V=kaX_|76k2o9X=* jsٮ[ڬ` $==@w2͚`xQ6~ Kˉ~Fd ($Qy={ԒNOzs$74~=t~LҲNpƾ7z&3|O $d S|'(蕙ޛI4gU2\mN(~Ɂ2ۣnh`v)5pN,j^-w/]\J+O]5Ib hsGKNn"[/7 2_]&%F11Q*>?Sf C3?.6LWw?ЫOK~Od(O+2e5y5~cdwȇlBKJҞGUjp6WmqQa<N,GHX}\wxP}P-Ε}IvF΂ ח?wS:m՝V1欖~;?D8_tq%_1]mQc*(؃rrnrO =,T5)-ƬˮxkŠI"tۧSmԾ:͌iD˛*wt43U34'0M#lnjK,iFT<27/0K pz^ұjcPs7m?jBevAyLX" =qLȕV<&"Aa9! ÁH&D!Q\e;?,Nt"E$=^ΩaS BҥjKRzKj&N^ԙ\a3q)HrB^FD3|L FkWQO-"PWi-Ey^:Lqϖ*Ǵ45WK1[9A|{>3ZVDk%^oWd`Ǯ>i4xS`IB`A^K6 sݎau#P&C[P0q"/ (d&oAH/tU\ɀk$[=JԵ2:?ujŝO/fNMDNqEXp/^k~k& -Q;k$WO4 ߷ǁ\ߝn~">b]*F9t^D! l;ә586K ,<-;@ 13+g$‰˼Y9k]2f.KGkj] =6,M>U!ŲM _XV>PڳlOԷeom Q_xp-I7i[`C:yi=S#Cmȥ2Ι~qҐ)h}6 zF i{4< ?qV56M=qX:Pw/"YKMvթOgC򳰿=Y8^~x-nIe +7*mli\hUp|ǸqD 3ڧ"byr$4(˱9~-aǚ"l^0PxG{\pN:X*B=ڨW,y0jv;WrHGR ZkCkXJ1)C ibm.AjIP2*S],Q3t4y;wxs{  D=BX" a3ppdHl{: B !ǀ @8r3.V< " Ln2?L[o: p~\Hn(6m7o,zݜi6$Pp~܊SDV]2>-6&s zm.]޾G'l;MaaΪ4FYn^1M"; gwQO\ MĬȳ;AЂd7ﲵIC%E6mQ"Mp#,Xk>*'Jow--WšW^<9T[rVf}Ȏ=~;7%[\ 30V9+F$j+AM!g=55iC!:G5Ty_,8AHwq][2iӠ!YvKF'#N0#胩0}[q_r?@ hȀrFwpY[=)i34g(&KD7)`. ̪e iU879=EJY&m3.s~`HĕJT)b Ns42L|[Ue;=4ܭuSrP #ߛw%n쐇f@шTF^$z]z|-5ܐCvls{)?h\X -˥Y 3^HIjZ7S#44"#wO-i8v4>N2H6;r5w&i]F'|zd>gT^Yn@sUbxdc[첕؁_~0y 𢹠!*"rY;Jmwo6fl_* F~oWh2yL(ү_:Oʦ6d^/Bj:ԝxLPZk1y+g;zڵvTu}&k{q+nfU`u,@W^VUE#ᤫU="=Ce2g/ခ۱o[F^^eJIaѢa2G^$d,F9(eO/">0?4qxk0) H"wI ?^@nv֨+NS^Jz=krd2$iM@sN"7;Tiq\H̝)IXhMaYhZxRXX;`m:Rܭ[o }x^6tchUpN!tXW=osLw-,}ՈR)չ7a5;ǶX%dwm!Pä -wI_R{Hcࢴ~γt6jgsAp t~%`IJ7Zj=mP﮺R=*z®:}b!! DFsr%: ٛ 72j=ݤUKګ=wF$6GRd!Sqө-z*,}]2hJF*K} %PM﷚C / Ww`!M[(!8(_E?VwG+i.aQfEL%sKqMj0b"`((qGӃ?D(fLk*,B=Ak]y/3qeeR[Xԛ>At+ԑ*hz7ez_(:dTP5ÔMl}f%anF(О՝њe^}KJOUQ:UEj9j΃(TUqGс<O*7ac/ /O91V/NN[ٜ(qh߮v"af(H;BtQ# po oApY@-dYcOL8ETIaI ʿh!x/$P' \VU ZUYTԪ3ۅ{;KfwD17ExIT캛hV%嶪O*#>diI>y{pjxB*g/Y(ևȤԛl63(C~"GW#ܝJ\}UrƜQNP5c[mcv8)Μ&Yہ=l #ʍG2ኪnnsfⷵ2w-v\b$vX(#¦z47i.gIdo&58]DseS8>B}Xu{iy4lW\ DN :{a$ XʢIxvqm)؅pjʲ(qn]'eMbbFF9;Y-w(_ 5^E# ㍂,DR'Lվj ` 'oV] rӳE W}o EZ^X\YSȣ9]wzePzOΓ=ɲ8fx$&zP6\Ņu9ΗuL/{Sf$[j5myq[:ևxʹ[O㣙#@o.e׺KyX}4XSD :~8X-js$ Kp+gJXAKNH8@S#DЉX_awգ?PK\J/ϔ6#pkcs12/pathLenConstraint6CACert.p12UT ц?;7AUxU{<Ӌw3s YӘH/eI̝V:D60R2T4%l4JHK9KpH8^z<7BPN;.3x* _ٵ V9 - 0pɿi0! Wh!("9BQїi. :y?j W~,[>}!/W<|..Xa*, TaaymjZm*QBk[2y(Dۤ/ՑM=S9b/N7Z}WkbbfF-ZЫYsΔ;yu[bPLYcBC&]#^'2WGBf)w-oz+wꋥxAZ78V)K/JW6rAs)Bfz᪋*8ieG.lAOh0dpy9$=&淉].~o;f[)P_ ~!=ssSkBcڹ#]M!5!ߕ`Wdi5PA1\d|/qr:^S*>\)?aϗz^@b )R:s[c,k-G)\M"0=Vk0q&v^LS@5X]d&㖍8 -}> it8';%x3sŀAAj [P( U>G$b:{%1 nlE+^m%0CV$PK\J/MXR'pkcs12/pathLenConstraint6subCA0Cert.p12UT  ц?;7AUxUy<2Ήa0" K 1rҚbB4;#GKG0hqMmsV1n#WdL4}}y{ 5P,(:d ( dR9 oPYA˾ ab$P7*~ )`_7P!mO-i2wnߒAYuTٖtO-ѥs8a]?ǫ/}XnVx Ʒ+]NvHM~=g7!w=NPO!e|/\q覴zӢozc{JP5g-.J23JkSeRrX3rr{jQTS83 onIY]wZ)2ԆHd5!KR|d| ]?`׈҇;{A f/>"}. k\s%K6#e0b {ɷ%]+6p>WZ_c+6{#KVϗ8iN9iݢ,ٟ]}G#.= У3\ӋŠa.Z)C(Jq}'dtE$Usk <&njR:bVR_ﵰʆKk "ϬLkj=v&8'KG7n dF3JZt_ǢVaђxΟZO1rm7GczSʗ!˳jmT=,g (kGaKS#ɓ^{v7jf6~uųTvJbvhI0q+fz'^M=2,$)EGI]j֜)JcB5.4[!jIBeYAᗤqcDzEA>W&/}f o}^lHsKgs/L }>H,em}CĤ0PhMgjb7m (^/4==vs?V ?5Rq'!Hz~ŢNiiqj3#r\og6Ƿx\vw9//dϳ{8q{ifLðD JHʄviJSUk]iomj>1C~Ub9!-$ٯT-L;ooLj&Wg.^$?{bz(!<%c#0u&TS=I.s2rCٺlEzXS3LV78QWA}ZףcJӀUD"|{   uj$u'OԝL'ADл>7PK\J/ 'pkcs12/pathLenConstraint6subCA1Cert.p12UT "ц?;7AUxU{8#H:#.!B(0FN~o,GV#ڢ{)_b.C.ViKiZ C=y9;}{hG@`Ii`$fh _+r>brB8$D?1,zgS@i0 3I|%Z^fYrFneJg>#b2D5qNnX?YhpˎJԙ$#/MBK4enݶ`*׶V]Q<"X ҌGc\ؿX&hRY d}9㢽~vgـs&7Tl! kk(QTZ mKwڙsֈ`PۛIM&VCNBm㩺2ٝcyҜU͌lg樼bebCX9/;v2PяQXjS |!A7:Fultܢup!fXG6G+ucgҎ[֍r΍X7!oRi%Ypgyp9Y =_Xz{szS=`pU)"^,>H]*K T%+~UEy8jj: !6gxʽpsO*R4P~t1,@Oގxm}{o@k 4b(Qw /mL,X͇5YzDxϖehVŁqڜ[L) )zt?aA2E_򒟡ӧEV +꩞՚n KYW7ګ:֋`fl!7m>U_WUs vmHB?"'3{H _CXo9/E@[הK"{Y#H^zPkͲ:_n %%pge&^M @38󱈻2|)ՀOS۫n9W y_$/TUS!1dtLYԾ3J('_o_ʽH+zz#ǢF ~1(Šݖ- A@4fXȦ-G(8, a#D V .1M4B@" &цlCsQPL"hTTx=aKMFMu ;V"M1NMNʰb#5c#H]hCO4R,?2?gPOl#M"yLY2IznD7g C=nKޥZ^:d}ڊECӀ.߃ |wҴk=r)N|+o1^8Iu~V< jUWF(O2 ;g0`=Ԭ~^/׫2;f,W4sFZ6Zٞ|iH˲׼Nfߴ(bs$% .չMOt[aj5+}{I\<킃6\{#ȽNE%y} d^0ҟ>>12Ę$I"̶q"96]6E'b_sl5a=.کVX4ZkpLY$> $QجʦO͔4as[no:ل !W5\0hu@ǐ5:ݮ74?"k)1тiaY~Kƴ53#&ka=F4k+S=y⁔2 %ٞ~gG[_Y,'i@dZ dž?Q*wʖ_#ҠFOZn43uʗ N&N .̲OI9x6ScH}( lXk2×,8 Y<$I#v9Zg46)bR`g.<U}oM΍ݻ_k~2OzXe|cULcw.W*:!~4 I 8 ~q48]~ jd!s/J~i8(-?a~Ve[ 0IB^2?`k@G ۬+N,2OiHh%o͜mtB58G B2~f4ǥ>3tgUւWN:ڶ&]>k}تLһ; ;TVn~ .7 ZhPwsa o4 M㓪ݔvB]jL?œ9C+Y=]1K,߈Q$;=OC~B-!t EW)͙vcONV}6G3Ƿo5`xWwXw" cٲ v|'% =pmdŀvyt8|m2*g/rs͔ynT.Qz`l;l DC,MmQo(ڈE=[)%Y|(3n rãXA}D.S"\_a%jzKfJ H>rU@hWi2m:/h9wfg=ox28TT ݬB%]m) Tt4z{SE^ɸ9tEEFwWՐy>Oab>E8YԴ^yP\gru9?LAZQ욚 B3+!-McpcpEɻrk#>9rޏH^\u#L\tcͼ2Q@'D#$ !=`q|$ޢ;"R!=u[x!a*蘢&񞫶դ47XsĔ**{V1d-xO2Z۟Q)v^z<9 :þ(Q|G`91zdo*aJaKODuh9_+mf oD~[L}H,վ{O#X| 7\vLbG'#xV'Pw! mu^V39qN6O5fL A*~tb|V1b[\hE,ak=zt/CL۵0U!p̩*)c6a4>㒭_vGSZM.d4DrIk(kSY[&{pۓ?oA/H>#4S߿N*hӁ~q{߫1!&YO3BXweefԷS84>n4/l]ܽEE8L*b^F_:m ıM0ԁg@E쇏)RW`$utoK +-ѹ[ a59&L/LX'wF:10ܬv7ut)}{bs0s5zQHUF%WsB؉ds (p)UB,{" yTPPPNe0HGH&4k>߮i.\=s Ų},cPK\J/ȼ2+pkcs12/pathLenConstraint6subsubCA11Cert.p12UT "ц?;7AUxUy8ƿ,>"(H0H2AUUe,6FlZk FA-XFmI+5Xdc"(y{g}99燥\(,BLB4N|, d`G#?BX(Ab$njO{P@ Ȫf/ 2cƄNG?K#Z.%-&6\;ٺtuVrU㯔,%kjbfy+eJDaڪ;7|4o\&0Rdq⥂ViY4[*VjU;yVE6ѭ]]\y꩷0:02z|=S?][Ypa˃cr&?B MxzFHնm8o2kMOi> $$wns3¢ʺ3caz xmV60ؙH=}HՎW4?+Х`QW`+}CpFft<|Cp;E&L=%kzr<aN*۴{5'F"huqZO\\_G.s$=G؀V#xV슥0"#TUzFC&gr:hn˩qxΌ7%4Zk/3XR2\Ogj;-x;LVIgez2)]y94n16Jy tfI ~Rb&(C_&֢wXkFɞ w=Nfm Q!PVi.}QOt9\Ǖ>G=T+7z9>NhD ?|sgֵ:x"C~7ə9oV?PGq(Xu~5"͉'dP=!MP||`7맆-<.K\CRUP#/M2qv n9*=o DUnPEP> T*jKw?F>fk"L4* prU vq[BBhҲC['Q5ORjqP_Z [H/(9rv[Հk{K=5fS\wݮ ct'u _DطՒ#_k eo-1/3*&N mseTTHt_Lqe'\漪RM8b/GBo%a0^sh$Lx~' ϓ̤/dpQ6ȷet W8^g6!p.q;!a>ɢF{5;M}n)EQG=l&USP '$Y,r͛*s##u/"H/XKMZ#1ZtȞ !QC3j)qO%/]n] ?zt*^vk~#(p%N%xy=0aYs'anZ#翯ݹ[SlX?V Z`iaϨo)Ed_p}Q#!^?u6AU[DW!u%NÆ~ba%$e4rLj@cu5!}XՇ9l;wYCuXmB\kmNr^Ѕ@\=2s MYʚ]OVdK_RwaQARbn'pM@B۵evLX@P:'=8u`:0GTyXLx;쐊K`K6,N-+)JswH?xd~k.Ijۘo֘/nAߨV#O0%,3[8' vغh#yLvLmƙHKC97:2\Y7g*M-j ʆHq"!dv"vzD%9߱XGx꾶RjU_)+HuIGFuR_m\KѳSf8~s _ۡiY'lm=۔_ɒE˽mXd0^ڠ,c96v\H*W-nh(ޒ{|\q*[ \g{Z;Y,%.LP6b6[Jxw",dwd"f/jԺh2 Mُ,4IF#@u+yGDН*,Uu $.3Y Y⿭ G-ҪE/lN0n{$ۋ f\|nŸ"t3YuiZ #Hx{;RvU yzD<_ F:n uXּݒd]yG(UV* 8׮ݞ?Im$ 8,Z<t˨y c?PK\J//pkcs12/pathLenConstraint6subsubsubCA11XCert.p12UT $ц?;7AUxU{< ۘIjbTrlDL`Lt4K!u\H+%_,K,Y7<= r^y}FQs`ECŏ8I@%ThZkV*$`ƒAn a/'\Mj[0BHm@Pt7-XGZAGoxg dd/KcjR^ M %fzl0c3*Iy4̀;h=<ʣD":Zs?Cc_^?CF䳲_~ʨmegЄJj62VQrxHLB)ZlhIma=HS]m06fDc?(iWc۽"5 nHߴjU6J﴾tR'^%o ܚAOUo:2Ǝߔ\^J#%'󃣪A<:A~l¿c3[:vLVJ)qr-;WO[iޫ݉~ o4BV_)xF*!!!|)pI{l 3 3qW`Gj4=*_oNO\};͕L݋SZEҧG7A,uO-ׇ=4~15|opm=.,Xփ08S1+>$mxHF9[ͅG-GemAI:Rؠ^Jj ˌ5)9hoҁma=_Y%xhw4ć/ffq4f#aϳR9@},QBdvJ= p @Q>nphEyOD`Jĺ/Mzx0|߭=4wztZm| b:L^\%r4e^K>"*sH>c2Dh-f!sva{oO$zhdK/oe˨wI7>|$O1uvD~]4di-AHD`%-'#ZuM6_֊ZF<&:L ;8j|z! .fZn-P;@:Z8\< (pYml٬TgWQ:H }mc\}*q+hXlALn˞z0|H>Ƶ "8m=46na R|F<[Yjަ ŞUT4{~ݹqNrW|iD≳݂Ts&5ʚ!|*Kpz'ur> 񟎊nLtNOVavtl<*31y<5s:ŕ̯J2iߏ+Pύ0]5 j&N,%MfrsBf} ,ThC}Wy6>EFP~JA~ hw_-. ^/i(Rt'w~{,XI->I_"D휵]+EnPK\J/p/pkcs12/pathLenConstraint6subsubsubCA41XCert.p12UT &ц?;7AUxUy<j0 "F5CfrkfBXQȑcQ(1 cGJ1 3B}?"Re3f2T}HJ|:< *e I EAhdKZ1ω;]#&V/ L*N}B WE0K7 Zwn[#ʮF9\RyA-(ۆrMSZ& Av"?;iF1jrȹF)с~i~i0~x6nuxCe RnƷh;;-YyUjRe#Bu?[;,q :aΉgER&aXf_D2R V-d MԺxС(ʐ>yd#S!I'2 V)Yw~6,̿hKB`[@p( A%dK/\μ6+o dPCDso۫' vVPtEMS wϭe@2qv_cRJ5&Ђ{+ѱg~bO>~/pzɔg^i$BvYRbb}avE]C)QJ^jzFFg4s)]n(&<^GEpD*t-]A:9W!I3GUDL)8VA`<.#j;+ߴѳݖN9'|24[5%鼒B]!(Lig0;.|Ig RvtH*N}y >iuU.Dxj >xfU1+jТYXxx򷠪V4o]5萁 i e]D{ rf V-g*q9C0m^u(IAd}ܸ5ȿjQ|d5YᾮϹMgGԎ9 rq9 4oKycףO %_#W;Nb:E==c?hy*i;bR Q |v6_s_T2x9>oST(#^/L:Vup?u[̭o@Q}o`@_zSd[r% ΢tK&Æ5ROyr:w̛N2u2>[`0Cs莳=)sd@+B=t{fz8ߒQλ‘O d0$-0A'w ̄I;Ncg@kŗ[YW uM{E~YB\G n%[GyR)t &y?!ΟȮd۬bh}Vۨb,Td%^'7`Vj[i"yا ku(;#{Уh٥;K $ >d 7biSk6w?|yITTDLbDTB~FjUR~`>,ޮ6V Lk{Y|<_> >ZD!J?Y?>M]InGI`i)Б_g{e{I7U)Og*i\LC,/z)%q*|vSVjy݌XFpuWJjaf8VFWtn7첫Ȍm,Cƌ%-go"Oj̉=|OJw+iG`Ʃ8T0l*&å3'չ'/F#~qqQ5( @!P\ a1+pA! &~Brr4-L/FaPK(\J/(m%pkcs12/PoliciesP1234subCAP123Cert.p12UT <ц?;7AUxU{8w33k\1jL"\1M gcaQ2Y VeH*\B<;y ]6 *gu @ZaC+2|TmY ` gPB dIΙUa$ LTUh PL-_h'VLK)YQVq=?}#I|Ez67)i SG"a6=l?A2}q#nݼ)y) *, '+L{=5y)T>q& @ZӖTnhɴn5VfŞ2{jGuSfmy 2^s+<[w@K73``;p}/d#cKmYnLum4=cVƛUj}̞l=n7^a4o5qVCpFƽ(-_>$!畽F|@lL(H; AJ;U.]f% KGq( Jp`uܱnʅNWa=wxChS'}wјR}U k= Ko++=9 3^ anu볨vƝp$ڻ8+EmϰN5rk#̂SK}I0WrzbM_e`_ ?o Q ]d{/^sL訑M ?xrXs5(p7KbgUOm>r4uy4n14}jJꀪڮ&y.;=Ρ_J@kO01?2KXوQl5W!1qāk'HKo۶jT<\Atщ'zt8{_.ʫ `4 Fmي[78$` lP(Ma85UbBؠz'o gHL'wtżcV5'NiXTOA7t\["*T=|2X|O;-4C2{sDP;d D>A9:Jz>$-WkdkGUIeY#נGldtI`COcɋ+_=%1Ǘwcj§ĺxuk}F6 +]Ў꿙2__ՎmRudS'1M~gO FIrX~~'{7OḼ8=w 9iytk|g(O~8\RԔp뺚sW7,Ntb^nֵ0Zro7iF8y-(WAث2*^w I+ԋr,ǯbj a`[on>kv0/Ә 浳ueŶ;jTĖ.Ů[&^N`<^캲i>duTȌh2TB=sgBًXjgSGe Z^)iJ7_~)8F & 1w]ܝKk*/&(~0İݣnC9/IK1IzX.cZNT,q)kb9d_m#eS ,ppр@0 pKg[=`L&Ae AD~^T٨Z~} [ 8*WJLTX +۷KpTHA\ܷ `?g ] @0)D bOhz{]wvTM?X.]B5>b?+[><(W\!TKu]3' kڭ $|Hɣg3lzGeѮhvFCN7ڭ{{#ZXԹ5WwUwKUΤFUK<>WVw'QE37tgqm4nxNXvdTIfǛB*s]{^BIJ ZO!?P19!}z5h`Q oFpq>rJ傣Ul˷d@qÖ<3'.Xl}bF%K%;Tuǣ2YpU,if9.:|ޑqz"q"n~?UzwDIٗ.4$.D[L J ׉ݽxĊH|(WF <{h䐧׵MzUPl9͙C7=9V_[|σ0 -4uyiPX͜ɏS5>J*f[A+ Tk@.&!K&/ GY`-ԫXDAy%,A3gRaɠF{u싳E;vY~-~r[?Ϩ-㬄ܿ!m58R% Od2q H7nzWƴ-@VJCLi`>f5*=3XI[FgEd&|^:a۵ݎS$cóEњ~D4SYufZiӴ[&W >`A4jz$fјa| wF,ܫ2WvA}/? *7\? !)ԧH%|Jnt'XzC/,J[lI?<9ziGBB/0sѶFB4m%`|yY4)A1foKd GPì~Ğ#΅cϼ eAA6͇jwi>5,OW95OI(0|S #pc *<f|),ѝ7/7H/ ]МLXak$)K8 4 GW[*MPv'D)cK}}V_B w+BO~r 39Ì+yȜ,&8vdH{zW(uP6g.QL/~GN2vlD%5wS6Y;{K%`H 3JRw>}%$N+:R#OUn0b'7a)E>: Ɵ;tH6kqT<b+g6ר\Gn WROC;YX;UBR 2Y#/NZ?Rh( BtSv@9+̸wf ҼE9k7V(:-䉺4u+SA@pަ.E>y-'N)ٿ~9Éd svݘ ?#̄=pM(S_M7ltpj8 & qۂ2QB7Nǐ(ǁH@ 0|` |x>8U4Q_*EMIzW8~PEBKPK)\J/Lpkcs12/PoliciesP123CACert.p12UT >ц?;7AUxU{< w3c.˝2r(-5f kܦ0mdsu4R3tT(H:s= 9{?8rg6t(n8SFuoWu֮ó=`="'qk:Ni5?Ngk60bg?t$e<wb4Y?jw}2 :=wc'eϋh/GLvF\WiuǍ}UlMYQc QE{oKzḠ@{E ejL#K+BdtsWi8rUu3#Q#[bSDc)Qyr?bC),bw8[m>p6,ҰLE^N6})ѓU阺C߅Kh;f;?&O6ǐ?0u[fKݕs]<JIz-V]#1jK@y?|$=[!7?OYh.lXYԏaN?໨J\'sFB/a, ȍvc貉Ɉ)I ZZ~3ewx.?i1Ĺ0NINをjWʇ8$3e7͖+ȏatHL{fdT9,;v+ڱZKuT?ݣ*$)y|&Q>9rXq7IW#\6v>%O.YF\5I'\9]40F+΃+0nNhU@vzQيR0EKl4Jα17O s ˭=60m_|+֯T}ă5>FׂS$Ҋl5ZuM.ћ5RFT _KSiX!ʡ,`AAz ,ZB0a*aiqhv!Ӹݣ>ۮžuk*)p`=œ0'+Gn脤 f媓[%!p8ྼ96 &KD^^26uqt'ROת4QƔ{#\ ^'vt;e\~F7x^u:ěy`eR7_|'o]\AkZK\CՖMJTF^Gu7i'RxՏe"h}D!KmLЦP;^-#={X@@ p\vDvz1Z-3a֞_(D#WÿPK)\J/#pkcs12/PoliciesP123subCAP12Cert.p12UT >ц?;7AUxUi8BmRki"b2eF-Ec) \2ЊXJťKtQL$3ysssEѡ ErL}q ȤCBвcEZAt0! T? %U!-t1T:Xe5Tzh#n1SiIvFֶƗgnh{Յ뮗2$?%-2G^oIr)TSmSIb/Z@~ɂWܿqx-?ͯL0<7Q=-Ь~iEƬ{AA;]]i$GpÅ Q @Wjpaw*K?ZJu u/>K׊X " 5ȯr)yp`MӰE#˨<Շ4g1콊ɂrtstKAvroe 5RúPR㝕r6ֺ=U>/ElKbXN=W>\tbXpVT=Sgp^ >_)غ&07m7F;0z:}Vka3@\Wh%R><RJ(UI\Yu2zs3'h$7 5VOssGg5~s1;^Mhz~ǝUnl"৕'YNpмgO-6S#-GeZH&n;AX` 5O^Ǣ"mfCK(gB\Cs4o/Yw@)vUQ ŽLmnMxn,]'LW8@MD}G67cIU`{G]hvы+ ~"*W(Ry2 ELZO\>)-{&f>mXNK ^q)k6w2u5bT֯Y]wKH׆"b{lYcAg6ǾYT#OO8 ~U2[h۟YR6>ŭv5 @\nT|wxӦėYo9+(HhFs\0Ry a{fЬpgrrٳz894ɸ z_lQ gӊ(K֢]2zccf@;44|$^e[7aMDe6߅œ<bFw)SZr»Com3h/־6)DDyVjIopא!ؑI\vlߺlj0Q(2ʹ ȕT]fap$+*ߪi-nf+.0c,+ HagfpsNd'fsI&DstփA)xg~(HlDW#BAdl!nH_Gh$RP;@  \?V A4P$Ⱦ4F P{.63PK)\J/'(pkcs12/PoliciesP123subsubCAP12P1Cert.p12UT >ц?;7AUxUyT$pO45s߲[JEn \熈L-\r _SsgxZh87߹~~ h6 7H|64†ٙh6?WP>Lس@@^%քoBъr|`jOSŸb5rp 32s9ŧ2,C4k 90:6D\3AE#d}]Ln,S)Z*"1wv%җ `'Ni$U4U"w+:+D t ֕+328W M`ɱ6WRsSGۖeTL]DDH;uG׫ogb__|lLv3w㡲kkA$ጙ!JkUWYlgɵ۸tp)#,CkV5׼49/D@"@;)f)<2$sjR%&ҤBC>h޸s3ޑEiˮjhр+phnO?EHm;(mqIiͬ9.Ղ{><=4)lOj}Vd~Rn/St8jv4S)E&|"T/`^֬4pNPZ^pܾkmwDX'c:Xd_MN4 i||ȁHR9d?nL{_f=e ߤ>-V[Bf0ӽxYqBgh*g=ޝ9G+Ӿ{KeүzbW(b 瘟ɦʷͱ@UXZ@F3Q`*act^tٔ!xKcqdd7% vNw){%zР!i^ȓ¦8@唲ok1CΝ] ͏'Y&ey { >س$?V@ f7v] bw l# bP.:MH?/-gӯw7]]0IeJw[U.vLoU_D0K>-pod&D\q>&"{4&r&TX\Pj c&RԽ/f5$ڶįK>鸳?!;j{` I2hiy9\P<|tT4 Ř]ꯧE˳mo1DaV7{\ͫNئ9dKo,n4{LNfUF4RsB)F29JomWw)MDtdAQSM~Yv ))d!흚|BǛV0JSyZ gؖ|um+6(t9}΃<-{;:n*bgP#/:1+1H}a(W޹KB/ً 9Px# j#]x];m%X\@p*Y@E)|*ԡo_ !?6iq&8 p"={} Ce2R_c1+}$fw ^~剰PK+\J/_2(pkcs12/PoliciesP123subsubCAP12P2Cert.p12UT Bц?;7AUxUy8Ƴ5 :BXc-ڮ jQh-uIE14cWpMGCJk%PbS˽ys9"0(eH C#s+q(D!@dp?WH6w=`PQqp3+:lW IJ b3jf6'"dnW`*W3}] ս]Yqa-EgQn"&G[hL5/ )甎 ZoKU77~mdGղ fg{KG+;7~.(4A"o&އ7(F=1zP9nLz;mNC(lq7$=2N]h+Ozէݴ[+O CRfT(DhWC{- U {io7Lܗ854(LƩ>*Zv>~]?Oᦙu.c~N=xwDGx[0WRh l[ ,s[~Fl!5=i73|/i^ҍYSNe Hߙ)7^dDL4*ǚu2:z.lUh>'\qh,yAX+B]E2yVl,}gS5~`"+ltΝ{>`#<`k/ 18~3scso&Q3t:bwwCZu˄  81|`JjJExëxfv.QVv:u\,ďVzIo9Uv%;e?ewW| :[IC:I/1.wd$/VP /Mݚ,(jA%?~MJPzdvUSڴ'q@ 4⮎'R2Czߺ>GFPk|:= q=kyH>k[MCoan?ƽu熒֪/9e>u2X`v%޽pUE,0 `/CϪ$;MGaXUXoƝSq_i(Kk reK~|.H: OyX!* ti2rOo&4L5-S@Ԫ`Nܪp҆QE"oB_JXQfђ31US5\p?!&|(їv.ƅy.woyEamD BZM$pi][?[\Iݴ3'= f -4V!&r6' Gj o,IRFܱ1l~O,˿Y'WkOeK}>h}Y'Ho7d4"RZxT#Mqq~.6C' xwuLf-poaqhM,\΂ u&nZ┉B޻}[`- ^WO?MXU3$ !T s$QO& <ÔAJ1UlUSgk7PK,\J/f-pkcs12/PoliciesP123subsubsubCAP12P2P1Cert.p12UT Dц?;7AUxU{<Ӌgu+ן%cw(-B"Øqf4uj NC2s!!s^w~y|{6 dX-L\ +a%{ {+'C|,oh_8 #Pch? Mt8k2 ̴%  Nڅb8|F\SSƅKh琭Vej9-Ș AerkGH6E(O⵸Ćo[w-vZ?(e7fEgY\l儑ghqF+MJ ޶Mumw&}.Ɵ/<|r͞ؠ}⧟p.O ThVՊJ/ CnmO}is36Tl&iL=`{G32q[ebiif%eO:LXEɀ2/'0cL ;{,Qj %,uzy1Qp` Q{%E9ߟ}hh?gjoZϋ=cN-p+`'EC9aI5WC]s܉܊E"k׀Iʅ-= VUL?TUicV4y;q:uNgD eyff0WN?\݃!)v^4۸TzY @ԋuz$vo4RzN mTRƬei9)vHz]Q#p5>Hޱe%M&k ;o|6+(@M䲃,j7Ch Wӷ1:x׵ %W* t70Hv;+&ߎ` e""?þ{un.Jx5-a~ڸ?((C='iU\ QNvME &圢]{1RYM]766x;@fW҃eգZ&;uXYGAvZlhM6TՋ]L o0Oc;'|Iv1jؚ[ *%duq_ ,NDFV[蚨.*Cr6"UK{ąpkuG_-t*׋ mS]~(pe*2*͕3`w+ O`!C7") T84 f]vgXsc!v:3{ZVҝ uVz+,i88H ǴbC4][ vhAa7kvPY64`b#̍!%cƝ>W4vz@_-Q*J ?yW,!  >RRA {( #A@&Q ̪7`ѕX_nfA%Fk:PK*\J/Rpkcs12/PoliciesP12CACert.p12UT @ц?;7AUxUy<ԉǿsh\cP2dWDUd1,9gD1 :D(W(bmkʢeRyYjCk]e=U R@aaWD &ަ\>Hs<5iQ(7n.>ؠߎ-ÛE:exHuj86ӰGmne7ׯyy\v'Dg}2/41LV_!~ͣV  \BRw#ҼgZBzCor_G/Bdb_G-R3$TѦ`OMp6E[V {c7aUi ~jy}{1a;/΄\lv&d9UJŦKɈXXVJff5h) bb0ʽߡ tKGR]JNK5); @E! g$m}% rP.Ȁ/`R>#'up]Nv[U2б{5Sz]#Dy~G0b̶c"Mv\$to'pcexEC :?$;]3(\LȌTu6豮nQq>8\^yjb01Ͱ}j LJ7 [ks,)n˯9JO\ƒޡ1upYg260YMGȗYiDžwU](2We)T^?J99eE[-wْvm(?Ųh bcYvIIK̗+(p"G~`^ֺz@Ez4v&xۜ–#ɮݸR =f>+ 7ϴφ| 707ڠ8ݹec ) edR7ҕzUƾ']0o@![SU^m~^¥ U\]Hk# XsޅD $Vc\ ,a%QK`/XEGw-m'aG^Cnw JUUE2oXv7?H xMeGZy$'f4;=b9iU0>~?aC4IdƧ{Y(-"xt养GO D('dif]ޒWlURV:LQPkj[P:s뙗 njzeiM ܯ;~ MŮ7i;z"#Y/~WT ڮz4jP^<2JЕs%ӸCYw!=h3)xe _XlMer6+y:jEQu;OOHsCwrEFFl ^۶xVqC,oT4yZ{:XSJh$VpwrG/sn@P L1ܯLz<_;(WL!-K-zVP鱪i1xvxwfn/ǏE`sqVN4P1&ky1 RuaW*8OGQԑj#7jS)U^'jȺC98} P b:ɚd$\AVTRclw+ /t RmDS7ɿPK+\J/kW&pkcs12/PoliciesP12subsubCAP1P2Cert.p12UT Bц?;7AUxUi8 XZHk-C*ԞZ{[TԾk!֪4TP j-4Eik)TŸ33w9M΂h kՄ].. JY'v: J!q'% 8)&B#g炢!F&2bH࿌מJýbll9fWʥW g>6TZA0gzT~@ڔ. ]'O/|[X25i٨i(0@r7| +B8wӦpl)`A*<-K5qYϜӨP0F|\K#^ѩ@3>jFd/4r_c|E*1^i jr.{-Mеԑg@%upONƒ}o`y.!!{j(U|4-o[8BXv?zV݁3?=F;.zԟ&Kjj/D9Hݗ(6o]ӕ M}R(^}<핇kh&Z#l$Tan`f^$uò -Y=zo7)Js~ׁ#0ގZ۲z)DEY~SޔV5އOm̷@׃$Ȩ۩%KNӜ*r›WG8);O9F_Pldkl-0λ|PVJH%SG-6sBWtRKɽd;ic@!Dbѭ%$N9oX rEG L#nte,d)X<I=*0:߸GWr_e^瓍8Ĕ͵925VY t߿^aP:6btV:I2ս2H$qvp$?'Љ|.D@e ;mȢ1sw $P ok ʇ{/TCMYmKygitI$evrj}Zt,>S|!,GS9{kU&ʕ2TYQ1tr75g&@q>[7AUS҈ykafMhKe*7JJWqr3'nN/4L\Eթir2+Q0X׼^a2)쩰+ck4c&le؎PtV:>WfӀ;! f';Bᦊd~4 )ܞo125[vJ4DwUBk $~ m&U8SC"/  ><['PK'\J/D+pkcs12/PoliciesP2subCA2Cert.p12UT :ц?;7AUxUw<dzDTD%Z/1Ί3ƵVZ+Ԭx͢mG[/'SgĬGںqU劫Zsy{&T Lh)Ta+ 1y&4N'0^A˘`# ?B(A %@$$Hes qa <ޙ1 #ݮ[JZO4~?2Vw"7촕'rI۲ I*a:W0- |7.nj&]_$ۨ7M ֝Y$q/4(4Hݖ<+hhCUyb'_6;All+7p]Ɉ=yfsQx~?5]_Wlk8ىi 8+lJ!\#@sQÈoCӜaV(IÂ5pEMS0g"e0ϸ)1r~׫6Gk*}6䯅lw k1<") #.Jh[qΎeCp˳V`T؎TԃQ1j!c3ئ7Poz/7 A!vO.ިzO;MGQ5kYMezF-HЩVM[N NP]I0.Xg~yc( NxU#fʗVO-OKcזXڼ J0op˺sRƸg'`}:.ӵ q^zV;tȴz:|~|+ oHdZ/E/=ĨmI/nBLnxQ|ұ9&byxCP5!ΌwFZ/7s?.cWWp.F'W\M'[ K9uڜ,\pD'__-HDB$u٬|`ADU@<@ ` h@0 H~N%"HBp2`J ATKQ ? soH{=H|i' .X( PK%\J/#(>Zpkcs12/PoliciesP2subCACert.p12UT 6ц?;7AUxUy<ԉǿs.rlc9;r !+vvarfȔRXr4v:3296EÎ+seXz~guꂠspR#69q'|c)",퓕ZIcq!R xG҅g 2(}ߤ'fl:X!% ĮڑYX8y{*rsBF5`az=~s՗JO;߽_)1\C]  }fUv>"_^bt$TZ^L텁g0;_n߈iM>fG~MR%- 6? (36 8H`%oY6 7Lvi^>Docx,S6)7kBۓ7ld+VC؊b1)]Nsc7,%4-+e~#7*&=屢HK'ndsCvP>z+\AuGJ .;!0|SIShjk"F«v9/`pL~ז#Ӡ Z/`SuVy; o4hrR6iPOE =}Mkq Eky];MpC[+ O2Qar%1ԞVFsy3;e$3O0V7Y,ƲfxE3/-e f힖=VfΝAP(^2{O[W~-ػ12" ̇E;0[(4jƵ)4BШ>NQkV{iZ}^f`|^s={Յ͠t&nKn(>G(uF_UV{%hضY̵VlP"냝%{{ 7sfGvƳc3˨[ #;j_tań:J1rXkD2/ⰼL NH=Uizj!ƆVGo0} vZL0^C0ԶnpWKYyz냂^ʃY<6 J:% CBO[fF_{C>A]L~jvkO}=4mekʍs(&e;f 2Q>MY}c m}Vᐎ>C]K,EH%,Fct*۹E3 } ٬JE9RWH+Pc95j4YB)gjM 7.-?$ޒpks?h |Kg 귋3elƪfӅ5~/oZuVD4D0IdȑV{7n 2^a3i?;Wᯚ\y3Z2*ΦB;jUڌJUn*ab#ôRAv/ZDUD3]hKԠiL;6/8>ģY}EQaXB3$TN7cоTO^ 1VSp;NX~Ә 6?S.xoD(IhZJX+JUnBZ(  @ZDTRA`w?Ei-g-nb䦼"\5x۳t8p{~ PU6b_p_R2AIݶjkƷ]1un\IQ #b3I\@&xD&G;G܇CgrT?:WlZ {ZJJ|$9~ʸ)f~ ۰nrJkouMmd%1+Cm^Ovyd\{;85;ʃAWK$*P5ѽcpMG("rŃ0 (  @ a#&A 0BT%@0T?>tMI%5>rF |0R2foPK6\J//!'pkcs12/requireExplicitPolicy0CACert.p12UT Xц?;7AUxUw8ƳDBQE["Tޭ5uĪTUF+FOЪ"T1RԈyCQ*V85iX-| 2ZB`NwiUeh sTlU?{hU?|؎¬{{鏚+:#/<1ar=˼[s"6y\eY5ED"mF{5)sṎ=w͡5aŮi1 u'ɱBl>dVؚQۍj!Cmƞرxb֕1JH28ʜ{laK ?2m|KoegS Hu&(Z"[J7O^CCl{梚eR=kС;N>c=ĄqG \ = ql>K7MԤ\YژG#9E>HV +LU;.z"XqPUy2:FQ_G!:TXc7 p9'{()ʁD8Ζ2tDT5#u,6Xt+ oPK6\J/4S*pkcs12/requireExplicitPolicy0subCACert.p12UT Xц?;7AUxUy<ԉǿsf1 ͌fq&~)r*hD'F"ˬHfg9bC֑#ǠL9 kz<7 D:qgPC,:D:?+xbs`YAA1kP>(vb0COdOrk~UQ0 Eg|uE'&3d@UCnt>‰` D~fFy*?Po>#TEsM%}555٧qm>ᣪɊGO.^ pm9Ƭ NA,:w^qd[4,bdEiLAēyN+'q(5,k_ykW53Μ#%W-hQm>N/Z ?BASNF(/HZx c_%Fx||"8:TJ=[YUhI@|mZ < }Ug9'zvFNeRcp#P\J]`5?u\Jn3kᕞ2!e{MO/b zWNPFԭ_3ayi.mTw0GNc L2)hA>] '',-&hFdºa$Pٵp[$WR9_v>얈i˔%y5`,"!;"5񷶿I7[Qؔ_D1Ξī$gaI[TueQLW#TBEB]4^7g qkW`s  W@NF$qD(KNV޾?m. %P>cb PK7\J/-pkcs12/requireExplicitPolicy0subsubCACert.p12UT Zц?;7AUxUy<ԉǿs40q3F$!W$]wDdP(RqM[՚\#8&r%wzy=yM̀A4ł aT(sb?G!>`Ed'BhIrVJِg2`ND&OQg\vwLq}r| { Hm9SPʱXq8ڲяmvAvh&ek=UKBoWg|{;T&"@{a[Ǥ>Rl/*73'8h,Ey2? VكN^r5.=QkŔ%=>Aal?D.GZCAǒnϯ!ZzIs\b.]""EUN+-, bW]W?7F\+_zSg8j>jY^}>z~bTxJT{ b^uK I;rtΩp~L5IaD))M^dpaO0鵗dExh@xC\NzZU[8O\BAzJQ1F_H.Gd" j“;#& pi!Dz͖nMgVS;*F lT̫;=s#|=X#UY"vrlJ\bڃbGVFP#Z nӢ+|YBA}E=n2t 6o2Y/d%V^ʕv'/p+3ۿAtLʥ(?6*m|xϢB(^@('<*h4y>XE'\UJelOeNwPK7\J/N>0pkcs12/requireExplicitPolicy0subsubsubCACert.p12UT Zц?;7AUxUy8ƿ$/#R/S[< ejE}HՖ -SEQRj "4"Uc{syy;?`B!0hDZr g e$D% Q~j$X+D ujA!i(@g8 A\7{«Pn S/7!P_,O~;JGv 5~9jtQV*d#mWO+įς+6<=zjY lTzV(VUɿ`eqrvJaɭYfv;$~VB H*~jP Ԫ5,P  G1D[:LzM(=VZ~u#g>ܶ`"5'Ӵ~e 1=67Ԛͧ˘kLm a.yKjM7͹l`nV*ks &^O$x?¸6TV\^E\bRXT_ Fuّqbz[?B`AR."<r[8>i2#ި GI+͝ęeJzeF|iFֹ߻|A.Kʿ0tBh>C*TT7x`TzdŎ̓1T6>Κ|lh=i G.̜OܕdMwT~ӚJmÅYX\UH\f< !6F8QԵ2L4X`M,kSe2KPԷ:$iyӷ:N'>ٱ9*/2*8jK?'~*Ws7?$g썶/gTyjrƌ^fuЃ:q1AK^W},nKkv48;+yy ?h"DNmS"x-#A$w#|ϝ(E&J+XUΔc6ҵ)` 3$,@f}J كI`Ќd".uj6 {4 oS4#JNgPrɋ աz2tZp1|4} P,C3bW::kO w}? 5gv5G@*31tҙ}MOدRgU1D8.2'SUb'dF*÷E'w &lǂtBaӮbrtxxCcߕn:u-L +̛*7VsPt'݊v k:Q?&!V-tivqPK2A|5!EMO\ln^ZBd״$? ]&;jIx%Sil `Y^/<´ƀka^!K? `U7CUi%Z0ZNǹܯx?3VdRHF=ٻķ;v0Ŝeqh񶊙һi }#Դ7Zx{,Oo2nlsvFZ}prk s!K3I*Ƹ;~Hc8*ݻd$@ f 潶m{up^OܲcE!!%mc% =$jPDPEݛFz_A s=pNB*=;~X|NNzUlۇ VJQ5D˾TӈA $H=<٧88J'W׵jf)ouI^d* 9щzP-^Hveب0{h3V&O|BP0[9pa8+o05`HRV?}kcB9o(=vBY9:UahPkW0}fR{loetRvkJ -y$Cd#y8?k ׼ !N[蹤SHU,/ٳh7cĉ^U9x:o&=yG>\gKU 08M^ v)n1[RW IKCr'*- qlPMJ#>y (lh@ x,qA)Z`wYXوe!|0Oe˿PK1\J/EM+pkcs12/requireExplicitPolicy10subCACert.p12UT Nц?;7AUxUy8 gg1L72] Ʈd ##=*pڛke=pq_* WDݐL${<{?9{i LR5,nS.#atDСEtC)#` ]OKlEFB Q/$BRg ѯ< +*Ę'V}t#%b[H&i2YH載UcEiE@'ݿء/`nunELu&@<>؄$L˗Z9q N;bcOt mAh\X."\I_eCvqq-Y^kl6us 6)oxi:70%{snc5:s~^Y}X[s eSJ>ɲq{t0͖LW/u'ԱW?ASt;SaӈWlI,yvo%dUkй`}W0= cM2I{RFDRmH]UoFAȖ[ԂxZ u[\?1@J?{9˺LWZm óuG%-]xط )_s 9׎nPm.yh pWɐ{/~oL[JwWgRZ',:+6yNSu-m.`'c6hpI]#Ny3l L#kq_}v[iǧQ3z*Œ@;S;'>-ǰ6ܳ|g_H(.<1z~"4~^wqCc N"54WshxL5ݣ6>̕n ,7iV=e =ed+L{ *;>. {e_PX/9+[#[4E,=lKB.xB!P*CQСNj )C:_AN;X'u0:[,7K M|x[*Uj~#sjCԮO}yz@z1|˰A~ ^ݮqA;78cHLŶ~6?0}tt ۫r"H6.&q! {֖Eν2Ko'6k\dg\2> fT—Q)/]Rg@ >)aKSo1u9Y?(f=YP[2=h8՞_S{rDfcE R* f$/qJ3mLjwtɨGHO;Vi"40OYx6)>8DSi[\OYKq$$J}4rBV<>dL]>(TDۚIf5 d]fDA1FrȽ9OƵcg:r?8[k=Dwn'1ygڋ_8IáK5J{7CCdn.^WM!'7`D:+h"!f`lJ&nӵ-gS)R3>\W񁎖56{9u4TBQ[K8MwqՄr]'~M1)"@ֻmLWo^>Gɡ'] '21*QZ[D}B'J̻hIinÒbAղ3l,Wx+4Ux3V|ؑqw']۟M12.ndD+ 8i#[ʰ$yxcd,kB>?5tuSwExc%aƘH^_> Ș'֚S>t^ɘ8k,aAtv}blu?1ϫeMҙV,CڨbT\ /[ fb‘4VyCo%g_I08_AwoEM G%z^kA$Y$‰{WIԮ(ǿADGX+yȹDԓF$Ob t͏ !mݛ]0lvZYạ>DBfr^/c :ik#d p H ñX4V`! )S!z=+_ m3^(-:ד877PK2\J/H+^1pkcs12/requireExplicitPolicy10subsubsubCACert.p12UT Pц?;7AUxUy<ԉǿsǸrĐ[#R(bM?3F,12rѪʑ(R$ɹXҚ?>y>ych:fPH;6m h`9{_+EZ>PpX\(D! F 0^,Pe EI4\ Қ2OTJU$iv'PfަkѾq(Zj~<-+-Wtʷsj c[pbܓ-q2w(q M|F#֭ㅞNgQHQİ&V|ݑʱB4fKG/fW{.!WAgf4[85Jzn?cpS;zoom[Y^P#uJne9^%Gp}>JYC!IHiO"17u&.Wt=ޯa8K>{4kCc vlBTi@uusTW>J9'<,Hhx֜,0ݢxّEeC{857z{&o l۩20kΥXAE@ʷAn.*A8;Zu^H1Ń y4>\g^̚Ӥ+ɂ׉jy+HK8Ș07>[Fs I3s>8P>"%ReG=V 2AZh0hҀkZPS(, ,r ;ʼh?1ǮPZc_k:KIOtJR t#^y~F+m׿|T6ыMc=@yg75a$>hƢΪ͂&$HtXƚezTי͒={$tI2Gt[0e6#Jq=#Oa$\jG_v+ L4'PO )- yC/SCuӓ =AN!pW ">d2 #*bZu%56UvhdCr%ƫ&\zb)#}' & hߩA"wfUS/T$z~…!l{/<ᚐt=pmQ=!W -wᾓ2~ l ERۊ?=i԰@D8[vFoP:#2KXd,}OH|C&k+tCȭ:QF٦͌?"3sp+ԾiUšN{^UV6"8p>-wXm3IvhNЮ >{AZ}׮QW ¥Ov s4])ͦVe_G("@~+ @aè`@1TGA2cY͜$uY؆~PK9\J/TK#'pkcs12/requireExplicitPolicy2CACert.p12UT ^ц?;7AUxUgX aHaDPCve,*JPD@س 4H   PPF-Ȟa/KsKN`,Z d-<,@i 4Ȧb)Wb xd9BV*A&O2-A  >T{a{ّ9H[hǛ(𖅈(9')d}ĵ&Y&I]k~+|0KCl1a}~!V,#|IՆ-3A1Cq^}*!MFim }殺ys_Rʽ]KϨy%ruv}ɨt6lqߵ]%)П-@U7ݤښZL_Fd\NC-5r6:)Z9dQ(PP#q$!)X Qp̙WsQb-чQ(&~"UFɑ~hޮ#\ +c" T=w.ΒFބ !y]?*әdJK :%)IyYk1 5ܒk\Rl'tTnpa_?LmWm?Sypws]jZPur|"#f2Jo f˙Q/{co m&53IFka)ۛT}_I9"VITj#Ѫ$@Pp .DL9^#fCe"u𯈛h/?IS}[c#b *Xgdb̯~@|Z4ѧ=2&72uz!=eŁar\+Q/eSk?0mFJeikz0!5 <1t6eK+[Mj~5>˹?Wr*6@օ'A"/1S9$ sqA=y.?rcAj YUZ܎w٦+k# 媭aǷF萇mM;^Q0ng^Qe%ܽ#dIɍ7i -TΗys*8)Dn %^|wag^d V# - f?@8 ?j`OcP`J97x#vn 3x8S Lo!koPK:\J/F1pkcs12/requireExplicitPolicy2SelfIssuedCACert.p12UT `ц?;7AUxUy8HEWRc["utdh4eeɒ-&K"R7Fe" }.|sQa8 QBW9Qt$LٳC?+0ٳ,0`+I|a ${aIp8MA^OzQUܿk͒kf\<ͦfwҫmX=`4JɯYyibKrQF'ױ68VRh1~6IT*~.`E }5KcBS *1z¹= ߝ8ː-KQ_O?0Zоt- J<7?w"[Kd|?l8EփĨ5G^/ l {EMK_0xm/}׽j ;}`ߨP>s<+w0C]ै`YnvZXy東*(H&2DJi:"m95.E@ t<n1 $=#W3t vh^yc 6L9ݫ۵bGO.ѧ w(#n J)i;Hl?U=֖xIMmmn8b8~xaFBBoTórMf[#`Iޖo0ZJ*a%n.RhGtf9Ef¹kG3vAm61oku=qE>OuNnclK1VDz݉Z$ՀuD_t0ZRCRT*vuF6!tX꾬{S`g4YL1+=&k.Oy08k|G;ǘ!fG=P\|[LulCSJ94ʤOPTsSd{=mɖ/gq1*T\| 4C۬G} M*800[Wݓ&{ )>(ڳ b GCxhCEQt ӿhCRsT_\ͤYBC?=q1VO2[iރ49ҺV8%-ƞI8k.5He-?QZV_-VVwx9AhS(gWICYۗ ~<ޠ>Ctw?6I/{jLGݓ" z+ϭ h u)=,"RdOa&4/rwJoUuÒsrKT4N|'y黀yL 'dSQ5 pf0sC"8͕⺟OCqL>vIG`5DدKZ AXM0ôJ?@}Zk ZT \;4uEsWDL.9k`gz%}LqDT]zU$b+RUK`Ĕ66C\<޹}99 0cgw`p)Qc < k(e@=, :* J10l77#!QP *Oa^HdCb Uxb}x"i^j4]f\l eKQ8GmZ-m B۱O #߂+w"3S܄2\/ Ɔ4haZ;NJZѵu2M t$OC5Lkg;4/=ާ 3QڂFf%9I(Ւ]á [F]`sh Je,@|aONОQ$OǫFS:l$&njILjv)`3^*_yě71X}ʨ;,n[lVmgEF ]iw#oafbiA)ߥx9*VO.$@` ;}0.iϲr&H+ZlML ϣK}6{8V7Jmsp/{{GI2ٓ`W1 _5x(&JR^*2[}yzB3?|F_3 Zs#iثhQtl+QYxϒ⅗(\|w-,䂴 BGo#h ӽdx/19&^~7qLj9+NQs4vaM]}x;-α>2׮Q˼J,v[$M u ^ֆrOnH۟޾?\sD]}g>6$2Ǐ=ZgH6ѴyfKGSJi洛+`gܢn7+]{pb~;^Z^Jۈ[`৤I8%Cټ7e!%7E.J8ZƋJ{XfM ($R^&dZ5(S10j^y_=)|EXBp3y+WїI;_1Hrix mI뫨(* A!G .p 8kC! pL:\9!UiuX][P7PK:\J/f*pkcs12/requireExplicitPolicy2subCACert.p12UT `ц?;7AUxUy83d:ĨcLʔK15! cɒmXDZKe8 )KYk;SYK{=}}? 2ah*L-r0_ AGv& RD,{ X_#p<-.y<h Ź[FD>C7=cǢѮHiL/o/o Oa0_]in R^Uj~se]$vn5q^wL瘤Õә`%{HZpn 8yl=h#oNnt2:G%=o5*I"ikP4M1'w} :' N4陖ӡߟ~rtlK9ۯڙ }gtN˷rI5 /#VL&F%Mk?ƍVz=oo ς/LIZ:Ph6i)o"CHUi&rOx {W;綪 c\-M% ||_'/Fi5]NJLn x{ZťdNüi9P78XAդYj3fQLXη3"S<ؘ6;ThWMc1HJ?' 9 ;R|@\r<&hPgF!HL"G/A>` C:Пԉ/OPLFŨẉ}v:eBAc]:6*gςzAWn \Oz$ n,cRGur {'iɀ>G*q\/xH9 }_,IӰpLBc _:'7Q<}+lʕ! e5dS%чgϊ^TWc]˃ |1񤝇rwУ\?cq~H!ԶəE/s/ < VB0f錷 k6䑮m]pIF6 <]87&j]FzI%\`׵Q4܈$Nk@\5(a6Z}x,čAI&rCq39HT ̯`g)jla0nK IS>0-v*PƵ!:(>IS ƆE#&oQR?$QOT?VBYI\࢞ʹ0jXb.XX>=]ssςx *`€4‚ؙx8{Xn ࠐ/W$P$Dԋ2ߜBD,jk\?5)Vzێ6ln3s4VmV-^!Q(@֪iUeKof 5܆Re ˙,D/S ahQyaI)M#ٻ4]G}mY]B^;(yn3՘nΑjc[&OZ)c5zwEViܬ('2@|ÊT9=^>$fSPZ,a؇$ /8ax_ԁS7ms@u·TVxܲg/A֙vPԍU\ꔓp->BE!5/m|bܤczSLqOGqʔY8_4, /Yc:ZV sV~nݲ5J urj};3qE  !mM~]{yMOHs[inPHأͲu2[7W?oQFW = rioz Ѵ/vztJkw#djG?N.|n'x?ft.&h3#WS\iA6O've1Juqۗ >>'|͐)?S|χLu.fԯocuyŢz\3Z9 'Kt޲ ē*ҹD׵UdyɾM N}H={PH]Vp{cP 7 ,] 8+,JjФJ!jzHf(m-~aG]?QHTpڥEOTe3bLsw HNq T8S4x,A4ݲ9·Ȁ D8!0,(^o?+x o!"sPB0X3 jWзs~V?s[΍.Au Ϳ+2:c.\D;ܡt˳ q!֣t_S˓<Լӭd@bKe 7T)=IH:vZrs,6}*&IrFiQɓ5 ww,Ԏcy:Kh 5ΎgƆm˝mke>X&{>{-K8!c9~7UxD{~%mmE*B򖿆@9hcΟH]}5=(7S4drwYT<6{vڣƋ+ ګ^D$$0rx-֚CǾwGlپmؚ4aɬqH`w&Sn^tDfLvwd-9JD[5jA( }T_먎N+l-ЗxS!zj[u:-I:L/o~It֫*Q~IXuo8YBj€G]Y &/;ןj^D=xjBnBjpn&c8V *ѝV[X|JiXV L-ƆR?^lfЁzz $}:ݎBV4Im3Ÿ{siT|1 2tjre=%&T)K!3p';W3FeS?g4մ?7J'{5[VIx'ᓴ/|CM_B@}/ _x!A:78J}ӵ Ca\|{RJ);&]IT^&7Ol U4U/' Vi: [N< >tFIg9Ҏ dJ.U ܖz:0+iY*=x]\DeS+h5.1˶VVw|dIh ]ϭ90 _2]|xsI9UW#<م&i9Ĵրuf.aq48}AL^} RX)P 5p0a}%@>_ 2 惓rݘw,|}Y|pdG}zU4Ǟ}0̎Yt d,b=&Oף1sK6Bu눹"t9m쓺"1VҰ M|}7Ƣo aJCfL^$bm ѭA 9KܓԤuM A%Tܬ9Y 53VUQ< ʡ(\c$2eC !y%h9WS1ԫķ0ȋW#ha1#4Gˊ.D?Ghq;v@(@ؾ>OT'"04PR@x .1 =\4ǚRPK5\J/e -pkcs12/requireExplicitPolicy4subsubCACert.p12UT Vц?;7AUxUy4Ƴ0՘)ѢRKwSi-Am}$jmGjKjiTZU6[-J#JϜޛ7|w(lj.ю`Vpl࠿VrB(E "@J "4&3xXvCiv@kHoY6M?HXZM%j[%~ڟidžǘkPֆ6C\ba뷒.@&]7x/o˴C9;'0lC8b)9KOO$t}qc6\Q8q{)Uef1Pl`zOxǾcig"/chaBBw-~SS$TBUQ:bNYLA DµYQ/kޚ5U2\?dԢ4[.)'6Qr=2I&iIZ,s:?S{ѕ;OB_ٸx+*έv쓒No7eh]αZM*j;/q??$"ڹT\e̓Ye[\/D!&;QaFpJЈ10?fQ$5+2 ud }nҹ5[^6G^v]{wԵ+VB;$!zBTg:KuV=.'vSu9 czaJE:-=&ưUӁtEeJ7!r[oGNվ`99j`ͺ NM#Wj_Sz+։v9nOᯟG 2ǟ&3tWh*sVN]SWZRdƈw 7Y ,TZQ%BhΕbԅQܥ`tƎp,%6IxAo3w7L~o #" PX0HTR~+&tQ }|$xvxZ3ž S rl9bI47\95{šZ_jWK*f6^pUL31:sLPvٿEmd$Agg&z͹]mvPDS.by/g%RIB6L jW~ܘ֓ɰr֝*jUm9u4{6'rĩbh&*]vƹW6ʝ+VձrdW T|{; dZT_hy氯Ð*gS:V*3\ͫس0?Xܞ;Zg`ѡ{p|uɦ;<.ɣ@nyb9,mhDbGGl0۹˼2wtJt,wK&ձy@Z 5m|J>F~QdO>}I{4 B?- #T[*20KhJUxɿ1o #؎Vp6!S^7n΢q2~"C>nZK8cx{vï_aLzh97ebI~8Fă[v-ۨAb\F[˸ОD^G JoFdV:(^kV$gcPjF.,f3( ~XwfKr:a&B$U\ip(Jct<ӡPqy@6Z C+R<|MX x_*gPBCf4:X+u{{ҰDOCDD>#ş96*pi%UagOnW̃(ثD:\0{\3|l1_X:Snw:D}7 ziֆ5i܊5LlsHI& -JKg|C:8dҳ7U9%z&8!u6 R_ ~'}`pfs LNp<>؛ڠ PPZs{5E a# e[SKmQ]Z{&K%Zl}f C/'RC LH.rIs;7â|%\%Bft܉:ZU:6 N9Z ,Hh9y!XGKv ʏˆ SΪxfZujqNts}}+wLjwhkgڍ}xZvSkvJzlSbj2fK۽tpZV=a(9/߄'ugNf^(m^/'.&M%Et]9J) =od⣆){T];hYb"|wˏ$YsYab7KѮLdISI ʆ ޢ-._yLὼvUK: {a#ÛՅN1ЋoF * 8e,MAgj ma EANHʽ]( ="ޱ2PMty5n4.I4hs2XNr#/ΚuNYF]K5hHMŠ]e;(O~l  S8L, 6;RL$=VhBF=K= m[Q*]^"ġ߉LSio\{.ہxtbZrRZx6wcl?T׭Wa[*1ɸD_W[ gXޒ)k+[/gPTDS NjYFM;p󿯆4 ֚͝.c’tl39V)y"^*@$Rg8uzx8Ti (U Atx=wI%vsC( p  8Q X``Fh$Ɲ,8vl ŧ߰7Ek*fk(J7(}$շ(VE{}nO%a![0Cn!?Kv֭qxevž6q) M =KW\Ͽ\MҿSzuuƸנ;_oՓc XcvWt.L6ٰ!f N:ZvAϻAy 6$wVl,-ٞK6 /^ p%\CB%%\:(u~ֲAl# y=ɖ * M2n|5>~$Yz HMHpT<(ZChL\;ݾ?XY7xWMx%oVw ~fb"NY9"#$Gv5lLi"&Z+teǖo,:VuOf6aG;Z1>)AI˄„|Gx: gdzw~q[NE|ICA2vI |K>O Gmm2wfpiS^ T"h8YDUW/ Ǐ^q2 N&8+$A'Þr6쓠v2W~۱dы7d&*"{3/x9 *_MO іpaMsSӐ3w>o/qPrtw]d>֌`]')Z"uLK`J)-_oa4nV~VnO:/'BvvycC&".ͅY|fX*CzdLmn<;ehoO"\@N<Nƫt}tH1ţm?>d~%#?]5+鯁.AE3+u|Ok&MҔL#@B4=z`KH/^b`) ::h*793ecSХrs' e37Ո*x7!O}g'eO/8[* )5ִ}@g7%GB[?s}9PP#i5tl|.!t^.6MˈKƷ٢[?WK"mxNYFUr-j 2;iN%ҚEC 9>HiƢ\djyy5N)Z(9Ow|&6Fw`?˳(J3[y ieOS{cn\YXz$jwrF,szH꾟b{7OsXxq*C2ǿg1NU;4m~=휜HNCn^GފE8fI·i ŕψ^+"[VFݖ nާ0!|`џcv9SW&q/Y$`6:梻gjd+LT' okg%]}z*b`~f\q7wI^Me }C*.LuWӒIڡ8ۺbpn\;ב,D)p P0( <0: $PǾ:xԇ@zU!طxHb_{|E6>PK4\J/J:0pkcs12/requireExplicitPolicy5subsubsubCACert.p12UT Tц?;7AUxUy<ۇǿ9IC$FZW*->SGtVŽ8jֵA)ARLG9*>~1v~y|{&| 8B71}W$`kLx]F`B"^+C28 R 8ܙîPE`$„h'*0 \ҧknk_a0R ZBt-k:}VUz?Ra,cؖ嚳.S牢d`hJY[-WcN+%Ұ2(M}vPa%JU6r]2J,YfBx+beE u?fvUy-3Rlq=dJw:õ"}ݣjmXTqwJ< %_a7>>j$-К𙛯bk⥀[vb[( qE2O"~Ixa- *5}՜|nQW᥼{lȶ3yMdBWZbiym&n̚H 5Cq[YC ^|{E9}sa~{|^'yN9R ׂʻkÆm}r+>c~KͲs3-V)^^V'uT%DP0k٬:y#bZWOm3׆$+V.-Toc/;%Y4U^QDn52m{d#b)V`hkϱ+Խ9i73  'ŮI\|g\9IfD(*r[E%E)ukæ,Ia~Gq2 *sLΉ'XչT KSÊ3֭QbO4SMyi 9KIOhلj͵EM]?노w#]U&iɩb£UㄜSUO!X'A#DʄmC!bv`k L0A/K }P&8E` {'?9;FFZalqza'`L%N}ٸMYlrTѷ&((% N龔Zu"k<ٌJvvZ!85xrGgyBX/dmm}7"%\|a$XU-movCe: %gl&g]IH4>!Ea2Ѩ'W\X۳)=#5V%_r`_=hО\fP5MNJD{m1BZR$ &߰jyj71uea4Q.|fWBҟ"ᚋ')mM"t: ;6TU KJê3g]N"I2Ys,CIv!¯{;ǒ ǓټY_/HL/>>$+k~s"ݵЯhڲbP`1V&y3}8o_?.f hY]v2wjk?+X֦ʀ᜽ 2|Oe1LhQF)Qecz`卮AT$|pdāK{'A_塘z~߽Ӻ\zMFtzax<p p`1:U ిN8EP% 0= bS6SIPݴԳPK8\J/6'pkcs12/requireExplicitPolicy7CACert.p12UT \ц?;7AUxUwT߄$6!2P@ h"U&Yaa@PeH%PPGF(FL-C "C?s}}?x@Ry% Dw ?+D1xhQ_A=CQ@ (Tpkxj{ޠ8طͅĽY3 i;]%W-V(fzWMwfW[Yw#S~JW5MK) R i H7{4˰B KTz~ dDS]Pػ{J_k\pjI&u.[YܪY~fs\hޞbԯ/sҊx8ˏ/Y^-*x=J2v>Nl+q6e}dBw9?H);;56L+)JgL hj.s T;ˮt.?A/\I_d)]I}I{,}ɰ]) nˆp~ spO¼icCujC2Vuɥ ӗT&y7&rx2-UԕOgFEiHSO-ZF/6`V77,5j}K 'hKwe'CaZ^`aA9O*=+NYʴΏwR# ۆEqO2j+Q3 *rwG2a'OlV`PןzXJnKRp+YGj4ݭ,rzͩE5wL\&оܵv2 t3mX54BMS:J_I@>C[PB% -u|Q7V$#Bc>5S*3:AXwOQ9)09,&3SmN߼a¶]B5PT.QXHv׊$՞)VT/[+;኉ǘlHnCB|P4,>SGlGҪ5t.$I\0ԟwNkNX+sn|/9vȜTkzѨ}nSe~(QMIԇBr0 ]{s=~F3EΌIۀ@q<^Dw3˖sf|U91s+#JW>],,|օxkǨg?GȖ޺PB_3U~`ad)̘ja0eNhݘп<6׻kWDo!s.M;vj@M1 r5 /S⅏tML/Z[aq? ʆ!Ͼع{MW`X{e12mYΤ3~ոb& qX/&~,1$鈝0:.M^mr'3;GX##D)z>le$Q('9h/, ˂vBZKXF Z{dWbY`Ɵ+h xdA@QV* bQ*ޭ9n,0ֆgB:>5J cN%ԇ^f-u_ybRy,~Cܗ) m\O4h3Lm_3` Q GMIEQ@>m}DN7TEΛn4[bJ{D"vAsuYfQ_Fjdw_)kyӞȏvw]HˆDw5!b N׭,"6u94j|y~2`g&b /nۯ\3olLIͭ0iEJ.Z S\}a9^]eDb: -o"PM xZt%C]4;BuBJj:\/$i5.!kfzs|JˤHʢۇ@y x(OpVvD]XV:Q*:Te7l_ub~?Cl3;<C.5e:cm.F]6}T?XԺ;i]`32P:z uީ&;Di]7 SPʏ٦^d&>Vr*xW* 4x!+w.ܫ~eӈ&KS=9MT&r?͌kS5{|$Wqs=^gc1zubﴤP:~cgUUW .|AqTwz6Լ]9%z20o;|jQe բ_^ M$J#៖<L/Te!,ԑ-~$_Ā2 qB! \w{ ]N2BT&tl--nhNg" W۞8=E.j,WNgǜ.nnu dl3ݫDa5˟%oWXҖ@ QqwxU Q4&ֳX W Wڋp3 O{hqڽk"q{NF RKi/3WR0E knx |xfnsZ)~[E|}~YЪ lfߵz,s:YvKUaf_#-&cN bc ua\޻ r佣|nu76ϒj+>]!;VQ؊-JgE~/s}4ԮH~I2Nm^)FtpLcZ;xZ>!D0\y'! 8|K~P.1poJs:lSٳ*QvYf8GaL_+q @PXdM=.:gFC$ؘHR-MjU#7kLjaSI}i\Iu.Ux= z PH[NZO𡸯v<.Qը IfBD`-n;RwWei~׻W)OU;X?w  ;)X]2FA'Di/GI7?A ̅DgPK8\J/U3pkcs12/requireExplicitPolicy7subsubCARE2RE4Cert.p12UT \ц?;7AUxUy8Ǭ+d˒0FSLo6($b$ŵE.2Y!Y¤Hi0 YZL&]y?@h:t ?SWQ!P Ch:(="B!4z?-i;@a0єO,U5v}zHꮅo":l3mm%>+cUXޜ Bp=F?'G/u3v\m9T7[WIe*!RZ9+ QaDsU"ƕG+Qb"È=&׬؉̞r8 n' "~w[,!]=Gyȳ/D4eXyODA2<$j^,j|'kg[mx 66(s;g=z(aJZYEnk!gh~1]t%hbB;g[i6WW˅yJ9.U*5;,9Vyгg95E6$/^u]yW-X$rUWv'O7:5:eyUFc ߬%ɕ}{Y `Ykg<}o*3rO+UtVV)cʫRH̓<,>M[卅\<݋l ND _s-Q>)V]+yjΜmKBBF 8ͿP A҇P;"kt`_AN\~T@ʩǰgʒU]sBA Wrc֘K͚LoGyU9))5zl6['D"["Rκ Wތ\g.G¢f18Hoi IzbOvRON}wVLxVTI%S9el g m1^Tq6V|A"a1:=c| Vddzr(Veݳ6[(SE!:}LC$V5VFg\#2DjH/Ct9QmfnyV'ܽAҭOR7Ŏ:7 f?sޤݚ{0;kDGE}~%[X/`b.0*-MbrtUVpgp!pعn}RtCҪ H~D.uȵA],{>- ! 4/XѿT@徟T.u޷̯qQ(,Nv[oQmXuG 4-[y9B\PyKahLb[}U&Qi}Y#蹠OdG2Gx Ѳ&wlǡu<:8*k @8  }@Up(DG TGۯȘvwURTzy}EPK9\J/4;6pkcs12/requireExplicitPolicy7subsubsubCARE2RE4Cert.p12UT ^ц?;7AUxUy<wd D&5W!Z[T3o3Fhʑ6iE=^9Q,sKy~~B7A@0 } ݅@ } Bvl N{-Cw`SHᔠv8I4P`S=v㜽bdt! ]=o_ b{_*[ 1>:/[ZȌ! bJmZz+}NԺ/՞?ٵ mxpmF;! P @MqJs O祝q_%M&U1~㉍ݐvZ8n/Nm ʧuj呧= eai.RggLOQ cM^%ڢԢGIq/Y{7)M吲*hL=[G I0schYjkԯB]nv<|KG?N("W[珷1k>{4P2;ԎPʨ ?iL(b6ج'*+&|k!edqT?bWZx0 X&(.rx7Ԧ~ncvuM%Cx,"}3m歼px7#ʾnO}7A:&gQB fW=_1-~F4x;#A7a{]߸{U=-xraSGc^mC]w$Mq}[/~# ò 2<Beaܮr,SY%B(]yu{=N-Vd-pG3eKD c]H9,U{ۯ*]Ta%1hH@EE D w8ӓp8U.$_ 5QPmnh@%Dq)f6jPK\J/K.̷pkcs12/RevokedsubCACert.p12UT І?;7AUxU{<Ӌǿ-9l1\7 ?JccHYr˵HrŪ#\ʨ:c6!9KT^GȍVGu|㐊 {/^f9ś*48)YޖǮ'7ͣbY#Jfs0w~Vʦ&jMcyKhLYRTˠ[Nd>b##*'DP?hEw>9zhAwKM^MqPq(u&E%}3-[}ĥgpaYfZ0Hq}^@Z!a*nz+(*}CԴX`h>gܩ ɰ ryR[X.F(v_3^j*CKX~w#ž-ZXk78:*yYհ09A;?B O`y[񔆩bv-Ե$yJ)AU[%RJ}nfJǝeRf4̝i5ߤknµMXis%\ -$ry;o&n_(*q9 U(@#^hkEȇD-L*qU^ZA|ۥ7<{0?#4Wmi'܏+LjGup-T/L&Q)(ӻ(avÑs{/q9-<;OE?<3K>Z&XB2,{t%}݌]Pzw- Hˎ>3G{0u=I5Jo wBѾ0ͳWF/4X-t BGFwTWn3p k8ﳢD#05:DUVVwb-ә3wFbp-  tO>mAàF`$QmTXWkai\\PK\J/_} /pkcs12/RFC3280MandatoryAttributeTypesCACert.p12UT ц?;7AUxUy8s#Yq4eD]`-nq6$YFC-JQtB]L]Vݔ{4e>,1yg$tSmSw@1`1 a.< |N?A@a_3HaxixAP$`N@3=/^)tUBry7";j}@p0G&,voMS>6%[T+&#iZǰC_rU-I(!m5l ۯm$[fٌR/=_(ZRRҡuݻ)K^PnxFBA*}D~1fgkW0Jpi8g}@㣬(Sϗ^yIs2@` V ToS ÝZn'5}Jj=^O/kBl=iIUdWwti{bHt"£Z7|v(!n7T4T!!^w'˽0nAÄ9E:p@#n>%CUw<&%J<ʿ ^ RLEL=n2uL:x^\Īcu=4;hޗ,\n&v1࿻^׫Q5#sGVˏ |484YYN:3gZVg{b9ү?Y+ P`im/Ϸ+G e ?ԈyFσUҚT-wu'D灄JZfħpT(1*d=^wqMINp?A)b`e De!ᒌĥs=Y)G~I2RiĎpecZ%>a PA~񨿰U16&Hft \&x{oa TFrMB,Y7' BoS5ؼ4c/p{)^hR-J5jo?ߐ:489綎WIԥ{iͣpq͋BJo?}eklv*WtU'6$Fg;g1K‰zv"g s SpT/MX6xgWh}m ఘm2jٕvں9sq>]PnZOy%Ex_Qĭa^}&̄P)j^7uվroAV$h+UCz?v`HI}2J'Yfd?~qJ,\OI%٠훕q-hVzCIXwR i{2}Ə|2g+Ag! l!g} RA& R|Hm- &B=%+AQaK\xPr|EK煰3] ۩ wu!l__@% H~2 ]B7Қl\ ytu! >^/IAPAC9m? _f]7n7PK\J/.pkcs12/RFC3280OptionalAttributeTypesCACert.p12UT ц?;7AUxUy8 f1*[c eQ 5e!i¸5b2uC7["!.Ɣ]e$}=`ɼ 0 Sl䑡C2oydpKH yX ^=6|\U嗄K2ji_v8_]ƕgǭȄ9-I%T|N?\&J".MK!{qՕ:ڶރmڵT#E8)RXaD&v.б-OQ1SyqyBU] \bT\CZeǜD; C-bI6i.^M*yE AcMъš/;+j'yũ)FZ}Ko)b:IrE+*l#8?Q $OENg?5Wj gVf3M=if蟋([`%ɴCbO y?+&eAS,s42_Yo#+']Mn4 ~YJե!Rh sZ1RGs_c͚T”J8A.z/_Yj0ުN&L8U3.iܤT!"?9~7{B\2TYS~ _tU wc4Rף&- h4lqdrʃC#/gݺtx6UYCIi-Ecfr:hw-vA R}@˲P7*9AA.5Ȫ5~[syKMռX$%F`~š!y OX X"Ua׌YuO)Kpg2ߗf2d3qv.`dbuc q}BFKmҺNl,,{F7\۲ohxYh?25ZxC*b~"V:NA%vV={NZCȲPfT"^6Zb"rȢ7-̀+3S•kmD~ :L;؉Z syrL&vuX޸`=l;̈XMJ[CA_EFG'Э&Et an'$T\FQ/# Jik\SSXxMAnDzx$cgwOxW=ZLv7EjiNnK|aQ'E+I Ыky2[LR'\,Յ+t.;;8ko;."AWO`ZU Gb*/ٶzg6JpoCBOm-:*fB@ë<~.q>i]Laވ\*Ye%hkݜI~G%<{ˀ| HDL+6e!a2 ``2@W&Dڷ\"! D?\z7(0BK_}> ]:Ax&lK9B(:1#:{]H鹃*S[4="uxZ1a^.={+0AkOI0ټjRdR!= zQ8ڸ<#ⵙDtP5˚Eo UU mkԺ ~l봰<">3XHn*[Ũzi e7r/5 ͝0,wgmܔ}c8F%8A"eM-9j0Z>S^ɑE.c01[/}d7%vS,uѥ0M1H(Jxj.^Í?H:PJ&IO,(J MTGQLf ]Bn[J^!!+yED "rqNYߙN znsm`wKKx i$d?Gv-V|s iRh9vHs] # ] YaQMqڭEz';CY[ J|Hk !(hj{^ t+#FT&Yϸʹ}j2n~BpL\p+W_}^7rk|w"}º3Zr\07BO~zM;+ !PBC2^vԘ4f=zQV5=eF@A!H%/^"@&XeKA/ꌓ6}~¿3ꁏDP~&s% IuA GXL>W=2)LлbiXθ2}\ߛ4!7МΆ4֌2&jhBJu9U_a+=Xql p㖌s3&鋜O+k"V^}hA1< ˑbOFa(I:ƪNAFmI3XѢOWGtWଽܬJ7a-)/JQٙ.ԋ>1 Wy㬷*~8JD} $!+ _)Lo)-WM5ʱ6tߦLH^I }1:inO';,@+ GCrk&w<jKa*^%ٚ_Yn밚J8?7FQ|`NmJ3*snIZ'r}ɻ]N`,تCɦg[-Q^QK_r @g?3CU E4յ VgFԊm7Z+g|n'ͻ_40iHaڈ)n]#P 7uJARfչ@_SxJzL(s9$HX5dC`̲-,e~n Y \/l͏gc^Vt%|".K7H)U;?xX`%lO7?mϷ,.TэQ*mɑQa͎J@WgZvc1%qH*&gl=aa@9,hȂrE/vF-_YP&{l&ѯveUy 2Yˤxs_ȎdO c9%ųBag;}tEnNxuo/ت#ƌă|KogY|w+ꭟOӉG9Y  [~<]i'j%3$Qܲ.zK찳0b;4Q5[_X7JɈ Y0R3*VMߦ2㎗dިT9 7yUn82̯疁L}- CH_-#2`=!f;K7FIVjN6fxIAZ49j/qq:%#-t~ ߧ9|Cӌxu9k'1"=BQVT fDQ1&Jc#02sh ٝ{Jz;1њܑtquǘwŶp7g[ 72”0NQA2ī{dU|+9‡nx YiXx2p [5N~Lu+JeSz=}k92)\miN^z#gzͬ r1 u)Cvhi~8n#͉)6iSiiG?<,//BE \oh^ $DDAs=equCiŔopUEɠzPK\J/jT9pkcs12/SeparateCertificateandCRLKeysCA2CRLSigningCert.p12UT ц?;7AUxUwTƳ! Bdh fHC!4lJ%2 a4 ! Y QB!C)XEM*CPzNw߽CGA@0-Ͳ LñYA`c P_ '9;:D ht0ƐvLx2u`%b9W,y+਴KOdWt8ACk /}råH=7#'J"K{ +nxϣ42K %9>(5,jj8;$6~1헯b-VA OA[[Csn綇|01yKwi끕ߎsla+cRFs..{Su;:ogh>˩tQ}QdwMl%gl?_k>!Dpם ! !/ٝ j\#GnQUCΐi.K0\eky_=c6j3R_m_ݏ[[lw$nn' d`πbxCWĭ#R#[qs^p]C=c^xAخ-Uᡔtb|Mc2V|}\3Oӱcz1*0-7j$Ї%졘 \) ǒtih8{#M!#1pTVe.]b #%?bRl'9o6(8k:_J, y)-pA.΀c?HDE i! [~ng (Wk$sק^XZ•pCO!C q{e\\UBdѷ֬TjխvU+et%S .ؘ 24ۚ$~NRyHGb884ұk?4(Kfm5ݕ)j5|?Mh>QsR|Pa%ԁbm0;(w1is$WRBI%  uTq"P!M10%\C֑B.(M_955%PK\J/֮s@pkcs12/SeparateCertificateandCRLKeysCertificateSigningCACert.p12UT ц?;7AUxUy8ԋ3vF%g#6 ǖ9Kq hhXBp$Btcҽ"<Ͻy^aBqP mI(6*DB};P!EÀ!P%AvJmh8 @n8.4|WF~MW"*%7-N<XÐϪm7K!,.r<=jJ}6hhn6Kla\amd;):S_SJftI*s7 JjR Svl]o Ѷ@ ]z`FKm(TL&k7.=]07NwSbk0߸qu&n?$7dw6Ru;omO@8\#|8Imgh?|bj0Ud7x#U1IL۲sÁwު`T;4:k7j4љZ7M\F/ȸ˪eH3_ȷr= DWĴO[F{pntޑw'p?}tԩJk#lx] [>^lHG+gK>JՏ0018%!S嬫{sb̵i]n$/D3B QxQssz+؂{X#'(&3dNH*T1OGO69E:/Ɨ™NQf$/Gltq ?c&BAɾeIGL;?NGA }Bط%/Vb0m~ mOXG .ALd#8+wV(4qU|dn)^-qB:[87QUM!i/㎍$߽UB{8<Ө4kXepLVa@ǧd5dw|ȿu*YKIQ!H~Ь׽?2jz94) iS e.4 $^c|se~Pnvvr,J2 2G^7#{]J8G'ٰ7%ccR mJԔdJ_zMIrA9XB#;%fq]:5M4/4|]aJk%ѬEd(-u _"b2r+p0`}DDDŽ9NXlk"t6'OzBcѭۿug~Stwm>I כo`oMJ,ZqǒpmOp)%N8!&ƀ׹~Z -T@s*v`4VRP&|xA4XL8#cY=\4VO(s{Dxx z|%<PJP`nU0sKne;L`tKG\rӜ,7xB.W‹ӍLv"&S57+aQ)՛I^|$ihv'N xт;uJAF;4S} viw')gK _Z ( *e+P0 AG4p|]]HUN(]c΄Sku|j}4m_.n9A27.g-K(+Bʚf{E|a u#;=ˬWgHPЃK?KYr(^=#(LvK-MggJGND˶s}vmW!}*" V-*??آƦ8*&ܕZ.MzU{_Îf7VqeilfħmLg|3yeUVvU[T -mFvoBLp93+MX:S[ӎj}ɔg|W1Y!}7k(od^ ?݉D줌z 'ɰNZzm蜗ΝWG ^)&ans 8H\NI'@n7kZ&. Od9tu3xyaMuxZx{v) PD^t2bXi\>Ai6T 8ĩ_o2N,n<5jQ]Pr*^GYPG߰ݍ~ݶ-fPɘ屦 d ѻI1PSA)LG:#hw}3 Ulk[k2'dPڸ1?5U$Q8R_$N\ $EX-F3l b"~1)]-P9fUS[xd(-M°{$5aX U U?*r?~,U(L*m.|Grz=gK.\cI / yLP}cPyKՐBD\AiWpM~z{/;m=AcE M"ۍXIN!4O;q3Ǟ7ls'6~;Բ-{މR* Ꜹ,[SE![!ݕ()L{ʈ|AOqae)h v8zr /Y7'1Ë*֍md"`yϛΕOrVߛd>#E݈oy{A"u`!| `5dB1V'}S-6FS8e[ZXxWUsg뿢j&$v{ N?r'V@ QWr^L?2C@<̍M%20X!@oZemTmuKcՙ|P]tGH m4O)Z/(NϑM/[1 !i|_*lUZ%U'瑙*?bY~᫛U:-[ۘRڑ."5N]Ou2;OZKt\';߼TI!Bh]ZG`/Z"_]R٪ ؅.(mF1ocجU{[löM>x$u9ݞ*ϞDb<{tJMVxkɖhG',`xŨ#:MQ/;#ڇq2?xWF]mS8+`* 9{y#Y[}` .ԛx=ǭrZߜTy<_L]0-Bp>]%{&|5J4GtN[^CSqxÐ!} ٛ$jG9,SIGT[mO}@ )tr 3#| IGiNB?z 7u_`*lZIA6'aTJ g+Dԗ ,ᅩC|;TZ'L6:#B+M>!6g͟z֖ePKX/v8߶,(8%GVw-ĭNA䝾0 xOne3̺IuNRIw| ߑ%]`LFC4wm]a8:7 Ra,0R'UP:'.':8q8n)y+KuVl_15]n-QW $n rк֙p 74TeT8BTwS^E|ՈVzGs[zde$)2dOԐ=h-ֹ-;wc 8m"-%&+$I|lqHu,|~HukE{H(L΃vphS etٝaPX_fI٪"roK0B\AYBיMD\1smIlAc-6&t.n5#|jp:gt^c:<<Ar =h+aڄ Y=&Qzv]O0~_ScV"j2KRՀQd2ǀ*{)WKo=YM%odІL;L㊼6uѣZN[6&70B6dѝ?YTX\ P8aOCL+%zqi'qTs80# IٖZed~, B <=p>}ojOiiG%;pK6yLͭ^Yg43iF@ 3@**O᰸8E9֓HImi{i]NOK^E PRرnPK\J/j)pkcs12/UnknownCRLEntryExtensionCACert.p12UT ц?;7AUxUi8#ֈ]kTR}_T.VZ TKbjA]dPcZ[FT{{Ώ9||΋@ MBeLq;_, @44 ʢq8( 5 r@(Z{*R)C$V,5"NOckM'HZi;7cv/&Bbm&L7A: z|$0vyk$ZF5kQL/z*g aD}+ipMjƆ#ZhRo.fYM_C[s5|+u8}Ƹ$Ř{BKkRC .jrʤ­HJ#,&+q#%vqƕ#cevք4SK|ЬŕV'Tjen-)U  E2Xkٮo#%kBl:Ru:/DVڀMzTe^D1jWgf?;&ksIBFLBj11~rpm=)~zWaLN;h1!](y>2Tq^A,/vS܌.[4^"߰ sK:: 40q?c$>r8sتObr%2^~n`縄uxkK4u)3-8H7:J _WP3OKz=”>Z>9{#jI-7l-D{JeD);lʿijzTyKχ%,;Jᢅt+P֏uۀCz!9Z=6G-23=ګ̲eG _eyA;;!O7}DF}{x" I/̌  zo@lād (h oh\0'e (mJY}tҜn='Ck /ZmTe[ֲy4\yپxq؛s*m  krtbA,o6BQ:s/DكxYg?`6(~|SfiY0KO1d#^ZtcR3BZɢpT&寳o&m 3ISkXOnɩެ)K%SD/UlBTZ4RQ^[?t2 }9RX^C,9o(|l6ڏKN6n4;Vp7BS,jL`yi19ډ{O㱷볶V*K sEF줰|R_SqBs OϩĒzoI0,Uѿ FyF/Kd[i`֤r||f"aF+4Z@P-)=E/D7m((2eh&Ri kT{N5:\><4\7u$դ ̜dU'781qfB#.&;'h7ɵ,JtYhN?y:ح>w}Z/"u^m5t>PK \J/3$pkcs12/UnknownCRLExtensionCACert.p12UT ц?;7AUxU{< g6沥L+\f& .N8;rk/J:y<|LP eB z v [2bb,&6 }9 u(+G/U3HA`hcr  caYVyc 'D-Zz4mjs'>X| >̱謠V* 7uyg寸mvY᠐ܦ&CT~C`۳|.` CMa^߸c069lP''~Uk?9N~AQJz_VLEr>>QFūwCצĶUC(kK@OgBSf0n4^n?Ey}Gg̎bm~gҌ.v7e|0v0ȟy^S !zO5Ss}78U BͿݍ _,QM&GoY٩G[yҥK|x>͝I[aOc?"5=S˰5 %q9.=f+/A 8{Wt(h&̷ZMTPa 4U(^s=H\ %)6 M(LE_8w yڜCzң.<\T7oT,N,`I'O;So4j˸7+{FLX$I&3V$ #'pOKk^L p(nAt;VG64 ,1o-Kc76 .7Mظw7aM'oSHK^_V~39f*7\F梿GB3DWMޫP]VcWچϲ+t#Ss7.%/Q&B;#mIw99Ng9$.7sYM:86vd_N'?0n^aPIl90A RLU>[9jv{?WkY0iS.m] %W~;T-\I~-T4/[kGҜ:`zIC?b #FFt[vqF5}mGV_ͯ\jIN)nl*ɼa,$}b:R߯pDl %i`QXI8FDJ( pH5RP!q=z11PK/\J/ v<F&pkcs12/UserNoticeQualifierTest15EE.p12UT Jц?;7AUxUw<dzDYFOH4Vj!f j6IFEUUZAլb;Tʵ:5>yܗ ieNj^3#?!ͰbN0[ z^S|?Y )1 a7 Uv]Y[ZrnE~˯[ mq> ͳXrjFÏ}/""I_uDʶIf JU2)F3%g.G~O,VKōV\U?]m.'.ñ y09j1"&IbcSsV HW$[_@-*铣gku@t{bνcMϾz|X**?uUp;7(ۨf{ڋ𤷑<\}X)r7 `=y(q r-yljrL{G~Zwȧ$@pgFSɤaR g4nAtď 7ŭ2:3j?.5Wr:rjܗxjj7fDAdX-!ept 6S_XL{.->e\d9/ju{,no.gUO>y9Y3fW>y&9qnpat2._!h;_'CT!;F<$ϑ8$ " 97'PgQ|PU!0HZ)Wچw.@ʦX{]PK/\J/=&pkcs12/UserNoticeQualifierTest16EE.p12UT Jц?;7AUxU{< wNj\Bl,cnIN)[Hp" ˰̝S-wrRX S.R69]ƺĈ Wp,O1 liuv(@Fr >^!S'S's9wЄCUc/c_K-9wzFD\Ū4Rb>jy{?fG\rQ̍Jn; O K>_o.~=NxSnhERnDTT[L5Ҕ>5{g9j,Imک!5Jy^esaYk3!8X_T 4-[qKrPB8_I' J6bm67Zܝ&I}l2B3ڑw&Ӈ\p框H*:զxTAҨibARfh_c!wW\Gv ?_9 |ˈnMfWl(ixW@!*1? ?< }.Z? nH>iw Ekoy$ܥ?x蛅}\"-2 Xw?qD"xTwN2fwX݅be7TL6M~v&X\WyZMrᨼΓowiv'9&lq;'U%A+g>[9IpXuH|2-[wN-~h!J:K[b>;?X =}Rb"0MDT|op3^[Z2%D=\cCb➪ثoNܣc'}<&H^ 8^9dzܵMy9}$Zyk:lj5kϹa͌{8{ 9tB2^R)p:} Dt3痪j}0PZ{ npfpq2P)8* "ؘ̔"k {i tFLrPK/\J/Ȱ36&pkcs12/UserNoticeQualifierTest17EE.p12UT Jц?;7AUxU{< w )D\rI.sm4"4m..R &=H8#͢D$#qbJvXBGs}?~y~@@0݀ n̕m@6*С-3-l;B#2P5|KM (=qObO]ʭ6;jW32cdI,*j /}.rq[[b*x[o}Sr.e{u\:?,K!Zc(1Rt ׊-҅i!688٪žÕӮ%Y t>2702>1-{.5u#GGvoDvO+ ْ͈ܥﺛ?WM)=kRDElԑ6G%ڧc;.cE:b#.IUo+k>#zaT{#Ya[$V+:wbzFu=.OYtr6m9[RF[nD1fCj xꐑKK]{O4_~~I26ş(~ϞUI9%gmg ,A4g^vO'\m cP+\ %.EZ*/5omj)z=$obʌjYYC6W݇Yxlj"sd Rgoh*i,GorbdE#ճė>\<ѻ rSJZYKfS^(a[ד:xזcKP*h:/SsZ7:(9ɡ[ *5~O ]tz1#])ؒ1A )|SN>AB **SMƉ ASú#Fv11 3QXn9m' %, :L?[ޏwz2WI5$L+-5bM;M(}`JEJ,F ;vlFdD=bɫD G~M:=>0"|mMD] FHn.Kߪ=4! 2s61) yPMńb>C Sߊ֕ck{/oby(GB>eXV}ey{l5O)k z$8̭dБ9Ϫ)"vqv4Nw#wӜ6e(` 0חm폝#HޗO9}Z5Z3Ta',U](lsDkS!.1@~^ "%Ҷ„O]gqΫ Wi-$XW?sHyG2-NB#AzN3yQOZhQIY*NV_+(Dc" Ve\5fWJWU"lhiT] ' B-mdZ JH !JQ<#q3-ɬxuPK0\J/c&pkcs12/UserNoticeQualifierTest18EE.p12UT Lц?;7AUxUgT Mz1DJV@zq)R !B*-"H"HQJ  9}㞙3ߜE()y 8CH]G[ J'A(GV 8*B3(~';nAm H"10ser#?RۑRV:1~v1 aP`Px0y!ëÄj\ {xv .Iκ3_V}wv4 !B"1[o"Ig'}v!ج )jKb;"CJFaANcnrI$Fdp@"6!Q6 1 u@(PϤB3'Qc`%O~^I.ۙe#u1֦J,sLʱK496iV21i%oO,=~(co~^ycܖ]ݣB|JTM蜍 9-)z\Q~+46҄vs:lfVZ_O>āerU 'Ue?˷4A"L*r0;7rV,q 6n:q8MG=.#6v\E3M + :<*%njOG+hXS8?G5vLq!e,.,5R BwBz kMh! e]jR/*vlA򽃢~§u9 _ik'жyg>WWTё*ϸHH`jԆμ̯+sEۓk$@tN]#Rg{N(]TǤy6˾~"E-8>/AtER)ege7 $1)yGu-S*OEj,84E?l&ܣce!5 rђH'Bo`aWNG֣fQY#׻ ,W.?93'aX,&|U߬b\wrdFt3 2DϊO |;En6rTGFƼH3e] }޳#ϛ+ʦhk E7h9NĈ-&"}ÞYXٸ2/Zo'0RDϙ7o" 'BjM܄R/+QeX(Tkdh%9,Ժڔ<Ǖ*Cd+CS81= =Jv3^+sG Hܙkm)qߘ>3'G_ lWD˃,WCe$BzM]%oB>5 Gc9g ^`^CjT8K,X͐ _svlU\<}ܲ:u} k-{6X-^2h :-=yiˡ@W9#`1(G٨|Ia-8c2xo}-forxJ_-*{XۼM\^v&_⦢P,#y^(eI7Iq "l[@ɬjqk+Df Fi/g]5 +O;z?C3/YƜ$~zKlu01J` 홟;{5RzV>SWyuVv*ܞ/ t`ݺW Ƈ'.j97aSF ׮†ha9>pj62HtO8%G]֮-f``z0"hԔNlZ^lQ d{hfV~0Yszeq ^O%*8p* Kl q^b~%;ڪovN2t^~.=4QGAj4XRTQV~N\*Z#I=%%3 d@ dO^AG ZP^F]Oֳ$mL-PFiM6OPK\J/TR/pkcs12/UTF8StringCaseInsensitiveMatchCACert.p12UT ц?;7AUxU{< w\܊vH+ YhaLq\=r4w^9[ǭEČZ.;z}y{ tc(P:TL3*uS xXNއPv6k-,[pP, $P "jR)$RG>}b/:W4i;Փ_-A$v2atwj\-"mx_C=Tx(F7[YI&@};xOi?4!6L j%^xhZxІPYzŏ.ʡ=.oFU5zMq!rY `j7^d|& 2$j$ua:-Eb,g̙aVnH#WnNb@ͲHd\For7(OԷagg8p+8V&wc*焻-]f> -zSȋbJ3)G||GDgcA6V^tVZt~̪5_Yήä^}լqp(*] 'gǽ&P-K"՘XKF~]Ze,C_aw+ uejI.E=zۚX+iYЦ;=.sw.*&k8ohE vl=ADm̯gk !\.!M[Bfjkys \Qg>G;*<#nJ{ >7O >|SÀ> uYQwh>˚sG9覧A,0RzƁjВ|K@_xk_K3[)ALjL=IVa|Dv M4[&$AOEXvew5ꙵ2nC"D L^F:Zqfߕ/;" I`J78-<[+?u"_+XO΋6cܲ3Od҇>$ztwM14[->F*ǚ-xD/+R[=shDʁy]? 4_s>'hʈi&%Q犲RAwe ϯSU+o_dͫ:/Q2hu$b?@8 ?ƨaĠ"Z00HYGzٶOs/<V;BDG5wORPK\J/ OG'pkcs12/UTF8StringEncodedNamesCACert.p12UT ц?;7AUxUy8 Ybw2-XX2,'Y&$KGvwɖ=$K>$NVLeD䜤dwq_s@C*UjuuB$9#AAg*cQ0ȋghsRYp8H7taJD l{xEuՎ\RHM zZd̤m1G_QS1o{'{`l-bfI0r褮|oJ^קv.,4ᚗ7=$w_o0C?YSVix# ϸ^D&{ :v7PdƃyAkY7I0BǸv(_φ_K N = htj&mO~SR,pG^0~*}N-wXwqtnB_UTWd 3zh&^v{6#@zeb\F'>+ty_ayYZ˃%zpYpR S0j#8|DtGIDNj|lmME%S 뱖2:2Qteo9%n{)B4n%BG6BoT/ϲ{v[ dudJaؚ]XZ+!5KvlnJXQմ&dz܄Kr:Q|oT)["}-RA-jw{Zk'gʆ(dyyNJë)+,bҡ+=3s{L h==Z^^bչY7'oئ]̢t7.& 66rGw#5b얇T:7ϣ]}~sOz[thե+Ѳ}N7_;/i{O /bH!t` _|8aR~EU|KsC?BB!s񁲌-T@w8 &;r鍕$$;n7x{.Z"5ߵF9v6kkӒbe6 xUъ԰rxdY" X fFX퇓,sbE"FʃK毫ntxC%bM<݂Ч :嗃m~ ~\xKtHtx}@HhYi¶lC3h~((PM#;OD{\1;_ a/})we1K?#J]X2EchMꢌp؋'d" ߂Sn{-2-iJ+ֆ9X5xfE4EgƓ_ǜS~gʻޙs/;j`2NawJˌyNsqYIeje0)1r~Wg0lMoأ%Ij'oSU+j ژ>,^:nCdZ,g״@'z=?G84`r9?ԃ<ʃX*/. ?%o9~bf)r~<,;PK\J/C@2pkcs12/ValidbasicConstraintsNotCriticalTest4EE.p12UT ц?;7AUxUy<211Qu̐ ь\}Ƹ{**Y qLD>mAȵ9GS~>}I {ed v뗽nvB=,*=ܘH&MҙR'n&%|w{v$b\O>/<^Qʍ={f%'7N2Ֆ׺ewwǴL֨jlLl.p}%^阶!T5vGX" {E{|NU̸6G&;pRk3ӓc#AzL3pvs$r@ӒE.#eོV;%cI" ~6G Kč)7:1'ΌD:Vۙ.‹rL_FV>9[CC 3YpzVpu`Mǚʪھ`4{3W ;s\j8T".N>kQ;5ldSrAibM֭r/yqmMu*YSw_~f$J2²k^il(-fbIӱI5ru5J&!Ý%e/푝Uf;29-\` ؽy'㕉FтP|XԁEn!|gd.V w eB {JcFpn~dpUG'$]B}&L_bP> Jm >P;!-Vj1][Oݦ> H#l}ȔrqG.۠Y 2z +>VVM҅38e{/>X-m)U3Kp" Kyg ZaqHKVEfߓ|onp tܦ7yͪRU"fJDnFbE-9,۶  I6*V<֧G8gk?Q4jQ$VW⤊;SS^4~iQr@FY--:P.~q:S8kQ@}y֐V;Vxd!C;Lv-R^q2m+_yޅ$\xM'|{w1+uaGkTm,QZp55펪ۇ`q ,zh9L!  GF_4V hCGB,1zcZA~/1tN},sܮE|.~SҢkK>%ς pd([}PU?_L1bAtH2r~8Rk7]FcxDJUdjYV)7(^b^eKX5O"0S3rwAtYQI6 p疛fߴa4(X]?5r(yŬD&F-6fu5#W,89dwAFiDLj4 o!eG/E e6ԓ]IIM +[f[<{wV{?-ks ߱c79bCn'N CgGz/aw dž1PtDd}3XGү7}d|Ac1'FhሚB"^?sj/xxm;X`5- ziANnX}ɆܼozP/4ʻGR'knYZHfK䓫?$qD乴5UFG=mM>lzY3;| r\lq8M؜K<o F˰2DSAp _Wx=I'GkAP+fKepv(vow/N#&# DdFO@0 : ~{qr8~TU  x+u+_33#X_#!Hu?PK\J/ B0pkcs12/ValidBasicSelfIssuedNewWithOldTest3EE.p12UT ц?;7AUxUy<ԉǿd 1/aQZh]Iu6Z3CeM6׈1L2HrZW|^|yPUp&BaCOA2<~aAO0ʵ Ap bpH\P8&} @n"8`wjZV癟_ma9Y㹏Vf ^{5Kvm\ mBHBljf7@79O9I|Q/3Ǐ+иbPǿ2qh* +Z{Mv(MqƄ=} ZDQGl(h™7-x{3p'NNC븱$ZYP `7x9 'HP/sl %McpBÏ2zaU:ф6OSuzRMrvBڠ6ہ?/^2L4^ԁ]wl'ulrؘC؟y>ĺU"\)+S;_\$M#&%zc#r;SşptQ^ڙ#885DAԒ&z#Kݪ7gqxIţ {ؔ;T(éq;I^q8% w<&C;1 0 RSZ3QmtɞD y}>8%l(*)?i\K%f٠ÂL?4`|H \2~;t31͓b{lŘ o 3R Q`lB=Ik YGtWt\.RۀE]F2}nՕt^ 2/|D ߌwVpaT/CÌ*bt ^ߩm!q\[ZP$I`l[>;H3^7 GR(9=v~X:ltB=.'t#(VvbcV0= `I!- aɄjOΪ!Ӗ{l6`ʬ"?m=a ZxplA6m+S 6 v@in?m?K2bôo4P e'C{^/m0)@ NɝCNeW&"7/9I>Zr.d^hH ֧4& Tm?>J; vbYR׵*B!E/ rQuNbJ=2:$v71Jf'$[. X>+ʛT',Kh1,\98Ӥ3|zjd3),}bSL4>\WG=A&ׯhDZCigAjwh}^{4f? ;Gp>/&I_-~mk0-aE3Q:[֩x1`E/WƍZq#%/E% ذ!dmkA3ﺘri~$3l_;#KIMƃ<3D@Eel-;}뫟UM=U6g̶1ӑ" ܜ呠z8A{у"f}9t,Q,pcmW뱕!!M!n^, g*:-ʄ+ϬG=%X}93HKR9 68T^mgu^`cПA{>OF|hdATnH^,.MǕof#BpBo9xI?zfe(_~1Yy5- *8jItT!;//|yz(4sl5_qMw#ߔN&7O3*Pfgmf Mt%q?ri̯SnqURCަH[]Cc\ٵaˇ.Xo ҽ48;oR ^ARD 8_3]27l~^ 3ɌO;t;Qˌ` ʢPdžNSLa3fC,eC1T_1Os8ʼY{nX*9w[f3r5JO=rBQ^ c(1¨ogI⸃,tн~oeI_|RjY[s+9 NscD3$%Jj7w1&|ܹ/$ky0?\ Qr![Ip{*~YOj74mᮽ]UnP IXz2$o&DK^+\//yP`d#aB#.:`{Kd~HFH蜆'igZOL>3PYH\G^^QA +?((tD$jaAŋH~[7(+JeA_U>\PK\J/iN0pkcs12/ValidBasicSelfIssuedOldWithNewTest1EE.p12UT ц?;7AUxUi8 IJUUAC%C2 chծ%ZjB[j4ZBkmIJQK"EچX*mR<Ͻwsw8:Tqt( ;dJrZoGG> ԡP"c/ BX C!.dQAObo<ďGD@3ӹDSY𧅬=瓋 -yK'IƫW|;zx;n A||f\se#9ݰvX9f-h`0aYggW# i~N&rF3t:UYˇ;'e_Ǿx YXi6 ]L JĠ^Qlss,O /Xn#?*Ŗ&GO_Tܸ~;OO8[ƫ{Q)Nlk+k6~aeX?)p R`~,` .ffq|o3nDQ3[NgᴹN"fQ`DfC.^{W֏疻ooK/5X0]ʫΉ7C]j[ + O4Hw%D`¶{Pzsrld˔\Ъ3_\1d#̆W)x >"$uT<)![7m4 )iAj\Vǘ2̀]ꓪR !t}/8_db:G>_U˗&JJ&\spڂI` l:~2R ǥub~X*7U/Z⻚6l/sL+i}BWfjV}S\NAD(k{U= QN{ +/"P@lC HP euEE[ͯĚduS~EAHɴ ȫҰU'\Ο;тha8\tnc]tRR臉{l7VMnvct%y{C =;ƆRW|4ʫe9V-Tf$W#03d'En!hb3:ua1?l'zAI 5&t/"n6vb%ZY|=G[M\iş㊹N/}Qϝ?cj|A$D.]xjyɅ4V?ݫpl9ZZ4Jfa5]- 䳿r#tj+(![5(sV6S[ؘ>̪ڧH+kǕ@f5>&T,vj 8[K􀺜-`ѱԌs!ֆV# W3E\B|jQܽ.e60(e?n:H w<Yg!~S%>|:6Sw:7rr[;A2{b3mE /jg;B WR!>-^Y7C6nNۼ \-Zcz+w/[ r0ӑt H# 9$%왡6;u-RC*.KnVEƸ6)?SGrv"L'BN+5+_Xa,J/&r/kb;0a6 ~GHtAaž-'IA!H5@T&wDϙu| FD<Z6Qt*wf>\fbAn4Dt.${Az.7-dzhQ.}@2eZwM1:÷&;aG gn]ng*P-JTS~d3I{awo&;(LGro)|*Х2{fOΣz]4 V5^s|M "Nn{A)֎1EߗU4Kr,&+; 9& M8VV[۞ 9uB0*ybCkԬvV[1KJz0 j1. E#$Ry|S>U(*1hq <&-G{c,] %MiUNp0krw(⊂MR<OSJJIԴcWN?oV5ٲ^kC/ w#kԚR xA @5|p~OgJav1ĭm({Uu<ˣ`'eǭE+9Shj tRb wDws<[{H˚3P4Ra:rgg <)}1RWWك@X t@וBA0W?569}'xaRWRPZPKx\J/sά!pkcs12/ValidcRLIssuerTest28EE.p12UT ц?;7AUxUy8 g3 !cd1d-B  t!,)d+Y%]ֵ}*L=,l=uqex@f7Jf-oVKZ4C>@9Y>EjXA%_vNdg+mXzF*%.E%]`^5C7hųG&l7\2Gz(jKW)y@U?_H@װ^nJ08SV#9#O* ȸ&{rȏ6[+gTo<6-=Y? ^=:xNъi1 kpI}F0 v3~V=R9snw*bIޚr7߃qlQʲd_VgR?x\+ tU p9ߍQE5",ڟ(d z/N3Pn⇌J$ QqISoR%~x 2AQ4R'2 B܇r@P&C"(bExƷ3xR$W|, A}%ONp/lTrdCr, kC;`V'anB]fk˙ mX1(| x#\yj$V}_a'ܦƂev-\(f<EMjLfڶ?\Y9henԦeHOxéqǹr}OJd)_#"$Be xȮ:Y[{|'ڐCvm+r$mjJ*a`Fn@.| AjUz@PGbcby9 :qt<X0 tN!vdD@st(A'QL9Tm!7-lz2K3gC|O pՉ-Yˍ6'%keljy+ Łh\)2J-5ؤ`V3 tp,kE=f.͸mW$D劝&-!i' B EFw"[N:oQ_^nOJ+fsz# --]@h]{($wv0$Ԃr_܇Mho7v$dq C2PJGL8'FaS9,M5ux|+Yϭr? h]"UUvzAT9Zɋ)F'JbReHftkreݷvܺTضkf\l^N)Jɜ¹#%JuM~LL|S 콗Sd0êMݵAp+R_liztaiXAs@S݇o~\x1'_T>C?S_UhYtD *νUiI 㩛܉DwlE7ܨenݶt,)Q$mu^+ߺ7*1C KV&DZKg h Ʀ+we2̖tȞݹłC+QXC+tQLb_ʂq?Cc;b?zV^9nyfsͅ;Re#jC?vcbPTtnew,WT/h>axD:?{.4 l */I;;2aUox2/olm=kŢ> gU[HHGzIq.WGB'/E-t ~8CrHz_Կ V^vz#Ahl Gj,o1tgOb/TƐPωˆ=taSS(jl uSx.9ѢaΩ \i{LĒJç]W'ꩣ~j !I#p0ס*vU RK, {$p \)c/DWCU]p\`1^%_`vqR-%h;>SkmS6K}*tNDaYR~c U}]Q9jԄ(|i63|07- )3R'kX H wӆ"o1k9[6bÕVk]/+&ak6!m]Dt) 7 N㽢pp[֧ Us K=đZ h2KAK5hj$p𱓭Z bn{Q:%8I:U(-EZ7611VJ#RE`(<˕OY+J$2V~ aĤw_|Q)WWl\.H7Qdy^׾qgNl9kyW xZ"bwZ-7z :΢o)CߗV1 )%5paTSzQrƔeN!1-yyY (" P0:'ANiqH8 "34e߶,v ,q1];PKz\J/D5˰!pkcs12/ValidcRLIssuerTest30EE.p12UT ц?;7AUxU{<Ӌǿ0T5+l[ɶF!+6#Rܭ5Rܭe(Ԉ[,\[L8;=7+ X:,Lwp{IP:gæbPVl:Tg!,ZaH*#W" 萹p%[WHI(`h,L;+!򺾥9$ D؟;q5[Ik l<o`MU`nFM%wh'&C|V!u4 jǤ@_^2cH@Dg&ZR5Lùn9:yMqZv bˆwÞɰk" 2OXͯݵ4>ܰ Eg|땏G~9Lkw]*UO^4kgN-NVTHa5'SK~n fS<M?r.ԧD% WȓВv_`Yh.v"Dǻ3D*D1Sj{_A$K;ze ZX&ʞKlyPߎeoN N;}r:+mQEɜCGkΝ g)=RF(m[s[qq*\6ﯙ 0%Yn>F{Ԁe`K=8Ha 9PЙ0wTD;]o'%u!%TKҒ>\)GO7UTo@n=)ЕEDP^{tKZl.6r󾴗.uh;V.'9蘞GJ:ε9_hmKFgK%ÂT@B3u2fцm|WF)|Tph1kۉYpՓcyqop ])܈.[KR s*4:SM9q'qY%zqc-O{UU])2'Pid_,e[ZYqcZh.Uy*A|;ruQڟ ,PÉА!fT͕HL$r;{%َG-LWWV`[#3H,%n7;4B4ԅc 6 9RZ`G),@ ,B#_:WJ#4+.6irbɜYKgKX^3;O}!gn˃͓RI-vlCV38&YC2X0ruOS]P&wok)7?vxsRAҨW^l6\-&rsW1P7Yf+ڗB˪Mڣ#d5v7[yuqƪS&>.O+t6ȢU[G#hijs ܷEG%z3횓HVbu)_ W)BQx`>VAGYP8554`4c>׆(FOc5pi=!`)b?Fi1N&Jn6FkЩ8 PK{\J/|w!pkcs12/ValidcRLIssuerTest33EE.p12UT ц?;7AUxU{<Ӌǿ5s]")s(QɑkIn%2# 6 1 Da.QaAz~;|^|zip0Zʦ4ͶmAUYiۖ$lX ^*)ͳ* 2*y*o9Nµ7ՂR jfI/D/}rM%XtmR m:D 1^k$,zR5ޔEv}- ?g%ᢃr3`t! jt`9*uc!mkɉV~LT7D8'#"Ch<!7sp) nCC!;ʹ:!0v&q"bß>F/:b#H.e$a9t:WMǩ;vڽSu^ŵr^ji(Uy[Ґu*-ii9iu)eAY͆N[{.^LΊʾ:·Bm[l~'Tzl=N'"D6Hq!jd?t$6aVGQ}~9=/[1+H ܷz18yvɟśxM8^s&~x"iD"V^ J< i#w]N{"tUq~Bl.I.ԶKsb{x޽<-uJ,ִhhe0l Yi8*Y6)f2Qu!;!qҝ^n:=#A#s!Qg4%K3O\X eh{7%4kcq[H9?TJk 6CY@H>GV {pM]W|?ɒ9^h3h&Q@.pF ܗ_Jb61 QndҲ{QhQގ ("ʆfQjriTn4`ٽ 7|bI H8Bg*[3lV jlsۅ3R5i`O7E+õ3]1j]$< /@vAim-$ _<40O3E ԸjȬz?7540VL^+CSn|T#2z-ʖMr ߄Z`Vu+q0SB\FfJ̸ot|#&e#?8xЇQly nu--4\A<-QUMȣ EoIŔxEسNnYXIe*;< K눐wWi-\XGeFM,ßy^1u+I1~<\ d@Z} Nvtڛinm8:Za]n S]Wu"؎PXYsf17ҭo^`w/8\Z*Lc)!$4Le?!M8H1VYnbr#;g6Cub¤Tg;:﹊ uäG'^fo ,!NYk]\Lؿ]n/dCQ T]&fȹ^1?XƧ7sy,Oa ojn70~.Xre@В I5/df|ӡ]A12Isn(nέ7@],PmIfDb7uDwS58ܒhM6J`O!H` e>w!bH h3`%77gTr\iq^Z(; zQ僞%y#af^)IMW;0:8ZRD^aCDCY=w4)08Ma0?8¯ k4OKSF-Os C@a:}&PAOx_ԧ'8܋ v'64ү6#i*vg˱z^uT%D?t2l]٤f1Vɧ"CLDğ5[K*#= } w<uvܔ5|:FtzHƔnmq.9#L>o#⫴OKz 4t6ȳ VOz0U93=i#MLPv\^nuB\40~=OI&[gt+cJ([yO|u iTTragAźuG.ye{+JG6+9&žMC>m)5ȗɩVfr/h1=KOoS2t?RQH(ǜG5SZIJBuTD!c?"zaH3`0g}q"'dUe hSݩ}x6vb)d{^u'xS.sHK7}zȥD7\oO;{,˫ 9s`;ʹ8İ`CBŗ7 ƁN cFpu![z7iWfb=k{eןǗ'cdbrʺ[Ѫ;=>Zqf)OoX4wBԝgv>HWZ:HZSy'W} P Db_>B0] S4( QG}oۓ(ljS隙;na0mGbxj,~^gilmc{^x>i<ihFxU1:I7;GNL34~WPG\nJ5X/kK<0F5Jfokπ F^LIvlgNJmthZRy" ,]<ɸ;xN$FE4c#2>c7P4/Mn[K̴ M*{/Pl@e\Ro"+kD#NvGle AQz_5Ȫ (A*ER nq_H*5A0c=2ro[^;*ua:Jγ`#`4lqrl,R׆N.FB捭%0K$CݮHjc1{b# TG@!T@[s8緋 W]F+m J]/n YKaPK=zwPK\J/Vlvpkcs12/ValiddeltaCRLTest7EE.p12UT ц?;7AUxUi8ڗ"jn0k/U*Z]Pmľ-i vQV[SK-QHʠV<Ͻw89;;ߋ"BA@0=c> XBj@PYE=.!O$8Iw9FC`1Y!wA  n#N+H5;=O:ų"πذku㝄DSGTn -jeӺsaf5.K}Mw|`[NJGg^Nn~ 8;h@ݬ=~y(=g+,vS zG$BKE*M[bAIX \ˣp@\Lct(>jኻH{!)a]Z2]#twlGN䯷WV24r|O{NaEd`|^6Xcg4 :zCwب[ #Ux8j{Kc[6,/:r0}Ts+>Ӷ{-$,='1)#K[~-q]vK08HʱoD9,2訰#76?׮XJf4]I+) !ENd@P E(evv/ @Ƙ{:7Lo:ɷ/ K?@WE!v=l!_/G QMmt"Cyo10c0{j2QF̠}DvŎ{yK1xfO0?;tW5 K= T˭5Eg Q#S͍!(4RGT-U-RT#Yp^!h;5P!N+M ]Ǘ 7O*me{?"ȠmfG@_ 6[op.㒪iy,6,Qj1-q:! LݎK=]$KZ22@@`/I|RcP($K @Dn] -/8ZL6\NaP?PK\J/Chvpkcs12/ValiddeltaCRLTest8EE.p12UT ц?;7AUxU{<Ƿv!V as'˚QNr0Y f=ɋ!2!eA,%St9<{0 A 1UݒB )0/+cB[D B4O;(O#Ci[ t@P!T5PX7aT:.":&噢s9{'^yR 5F4Yl=fWw+IIq5\hr_?Muh{DjU:2aK3͂J MqޤTE,hmY!x4U*"4e񠇝"@'/8YU};-e GUۻ<ٕ V؄"]%7Ia3YkGD kK6VD2M F-?Gm74z3Bidex~l̦#F ܽ6==EhmArB*wNMh+XAS!m:27H͡#ovv!iz;,NE R u? n~&o:~1.~ u_`% %s>6*tTHI>JbGA 7٨hn7ĦܣU$v56_Ĵ9ˊ|%!fL2h?W B}Yr?Dk@PTa BSiA_3@@W[ -=?X[wmM>鲔!QskP[t ܖ0U5nVۙՕvXI!Fd?yS`(s]rf>Aڳ êYlEnyb 1[.)>NJ:Cێ/btOe٨hFnar 9;N{{*_)KODFy,9Vۦfo,᭻$CGpӄ.kl4g|9H;Zҏ5Vyl9CpPc%7IAbi@ni꾰|(w+YV -c])Q%ܘK/0b^}թ# ޱY#ZD̉}4aRi+1 {Es B)p1 }œLj `$N"y9 )~Բ10tCͬqcPKk\J/)]f(pkcs12/ValiddistributionPointTest1EE.p12UT ц?;7AUxUy8 f Q22Ȟe ٢r5oKFM"Fdi,g$J0ݑ-ycC\YSQv>|spAq B ΋\tq "0݂Aȁ5pC)#0!Fì ĀP: QNN^nkVf7k2AGgkk*q,X'HvbxX@ n;BGHw2*{Y7!(É Zt1za 3 ܔpvĨ7d)9MRdnMG%z3:xJ>c Kܶ֍ 1PS?ݒ!e,`b|}%7޳˓|2AyDKQ38dx|ƙ;G#J)9=~G8nrS]ԫ3:v{om򊺻MX*ݻoy$)&vn6t]&FfkM Cuu"{t+__syCg/LLvnS0 ްzcހ܇Gb`k(b->"9j̉hDn ZJ)+ri7E(c.wf_m1+3[LmY0o-fGATjCc Vl$5./bU5m4Pk|j۽WebWZbzvo# XV!Hf [L۴q?$sRD_F_ .y|֘Gx AC,՝&(Ai&[qWA(l`0Yo*bW5s%z5O (iU.Vzt ̺r#FzЄ! 6L 5A85m?@9{J\{0H Lڲ*ĩUWqbNXԯ^xp'g;RلbjGs hktIaˬx`fٿ%෻YoM._뎚U:Q>EcZmakݪvgU^M^Bt>f"Jwb|U8)~ͭ(}ʉӖk <[Xb+rցjWͧw-a 02RsC|{B3oz,_haͭ­*h"&c`%)d3Q~?) 跾.!ԛZۨ X^߾Qrr#/i9i%9zi}L Hn^e]==Ҁ}A'qˌqj V[uľh1]<)(ڛ6WqnMoUvYǬX_rs%]UK ]b < uu_ :*N }IW9 UsDrvH9۪ {j#és^#F=&%aeŶ2n c)P![N}jy+R^BTd)Uɽ4ӾZajwռ"0^]ed43oqdN!$` A@0\;'~qX,έz `pISg0-Iߗ`<Տ+DփPKl\J/ (pkcs12/ValiddistributionPointTest4EE.p12UT ц?;7AUxUg8܉Ƨ13JՒn0WH0LXe=GHĈD 3KtV \AvBw;ɉvم6Ώ?zMh *<__z¦SKYbn5C`xrwト]q {>ɯYjGiUXr3[bã|*(0fcf" qJ=ߞ>e8ۃ'\T說E[jcɲA6ED iŔN4V]skyy[:v)n9c\`lqש?\ؖi g.lej)1Eyi V %f4{Y^2RW|Np8_ee~L`?T&b-{M^ƭ+lv,ߎ Et/#bbigN+-lQ!o)g%.pC2LekR 8.DAyJp)T}aU3˒!]@>} 0KnT y{Q8%&cFxLTBeh5 ޹FR)/_m/sw);x͛7u؅TF*@l3đ R gyH?(Ay?*JaHkK!j-L'Bb3l2+86Q#״|*lhOso 3vWta3dNЫX{=܀Ďȉ;y~QDR"r" P:xX5}5G/d5%Ut)A`zL˴eC6۫F9=Yj8vsq~w t$/<"|ZY3&n9[l}PمD C;-egjQ *\ }{ SzOw3FYQ9(X nbE [,g1j. ( %g2 آpLVcDY2b(B\1);R O G݄j]χo{xd (݈Hw\j=`*Zi1Ov' J0m2q*ԥ88{<V q(vf46jj_2X(r6@G$T :Mw}Qokj=۳2ڹTxk~4RsЉZѓ 2Oy;5l3+4r'gS{U. W\&뫑AXG޳ѓE-z&L@?FBBt C۝:84?b@@q_7Aϒ&5k8"`f3$0&tr>z3.ͺjE|hd#)b-?RGWE 6xQTF vl/WV!+^UY-w{*7 W Fr'(Y -R7HGя3&|ue|Az–z,Gkg7闷;4)D.`Xq69j:0I" 7tkN}?36gc4p}u6%dQɳ#D/AWٗޅm)G0RѼ?^\t'L!^BjY`2#\Ln›#3't,3R$a>N]bivb2HTѧњVQhHGϾg&CUe*l{= kf!fxb@DSc{7fط.^&톫62/_eN![vf{mn6]o ysǑ"~0bKdI.&lԟ`?eҲe_U66!a]LpzGKb/ 5gCӱ(6άVf|`@Jla"'bIHS%R;=K3DgG!-B2ᰲF>U{p{;p׳h]a0,1[h/TJ/b >.`Ҏ_# (dQ;rU(cQgm]dnƂ2wYJZ#DgVs8W+Iim?TҴ&m82Z?]ӭ\4- SuX?32 p++찖&*sV7.3yγH\KߧeT>W߅bqxaLv"B78 ^귅ɝtl_f3joOOW9_:+fgDFH:|L Y+(ۧdhN$9{sYZMɎPc;\WM23|P{ePo+@P9iB#e`UwRZ15C^p@L+miv\\F2ҜjR1L a}z2VBϑށD ꃑSaG.t6#9.:(*|XH0Id;ϟZ :=sqim|aDIFa[ՠaϱK m=P$7 bI"u>|;ikL붧tE,5OPjݰt7i5kvL:eb>0CDz`ŏZ`ߕ q3%@<` F_X/x M=! ٯX7` 0Iv!πFޖU56LHj`oauCC3CT5KKirKi{e;n*Xn{puh:/ceӋi[%>y }~s~lb)]GkcV^BMk#}֫h}.r:uB.3>=R=YXߕlѫNs/ Ev5#h@.Uߚ%#W$kmSmɝWy1MAJ}.r%h[Փp\fKiU=%q]]I1ճ1i<~XC]}垢rʟ}6 7R_M0 {bڸajbmƄ:xr|#HN,nV%b֠򺭝WB8rvYixW2k;T_-?6IA㖙-u_VV)X>ɜUj -]ApIU·IKN.Eqniaf!3JK`XF![G%\މxu>~W!FmR,J-9ᲂ%^W G+pQֻF‘^a 5xP   `L׳ V +D'T] |11m*zV`س`+οPKe\J/:mOV2pkcs12/ValidDNandRFC822nameConstraintsTest27EE.p12UT ц?;7AUxU{<ӋǿunIQȨ-r\'[bjrG.류%0N;1%9c:EuTtd&?~w/`^ >s qo 19{٪EJUT0Sxr=M=}`ϭ"UD+eڃbha?}$Eyfk+ T?2N-!MS]̂o)(ڄEѾjHyj'N[ۦF`hl0rcpKGdP=^Q[1vpNQzsQAL/&HWDA\a*8EAiu"iafӛC@Cq9M]m=Ǵ& &>?G8O%gT"$%s -b%WSAPHJaZX, {b׾7@d\I;a熖\+KdFYY˝]m1::=;LR}CVؘ"VPmmé[}xS=  oD8cจM=}K>f d\-==GZ;oBPt^"2LEN!o:;mɡ| NY{gKf5 KY:!rW/JPR%,[=8:q"j󇓎7i"Kxbw(^Z7Krsʦl'w IٿvcFXwo`Pт2!m[y[ p,0,\!Q>DٕWr(̨fW&DYFEU4=sS$e '\{'DQ#en7j=v>h}L|v_=u:(^;j<{ǥ0 .Ω9iIW9WWx~+4՟/j6i?#R*[bPɆ*9#B!p_QV ')&uc&w2u1!b⎓Yp2'-(2bJBX#PۊW\^m+&:]~ApZ~?~vq*țb/)ⶎkm^6=#J.Qdx}L" }k]XKA k$fDcqd% KiqjDrpH/,&Y[xM%QFzrӟ?qׅǤLen?[u`e: %io4fS:So%㥍%)]Qt/̳2A >3Ϭֈ8){Co h)P:Fn(0{ IxL_Gv=Jqk jnuXDbϙ__3kj#UgGcC~M|9-ڠ laA+9#~$_bģfq 1d4=3k)ej9mؾ-\7&%Kѱ}IHAF78 9,Q2ژٚ%ƶ8BU!5GrְRPFcRK Yk/ eL~Pu;SY< ;֪I=gKZ@7\&834֭*} ]A]eZ}߶;%S. wL]t)P-"sڂő XHc@?(yy_> Z& sY7t)6޷ FMqyWG %P G=D &=NZuRޅC um5 cf' j`dS=>Hɮ*瘫=+QJںl-׷Cofgx׺fC"s=g87"m :P:csQ֏v;$ Ig־p13 cz. |8~=\l+ʋ3zwԷk )wiׯd~=t&ACKLb[Ox`Y۪guHY"zO|b< z %~K VEY{fMk Mާ#"|D򊬩?rŠh'p6'PЖ1&bwqO bA,loR鵞X3!AHJE?k!W= eeo}ă ,"LWue% c1!4Ę]ɓ.)b@d-NPh }߲'~3A5Sh]o8`5'⇺%L9UnkA'i6ShɅrlVƕ/cWiW.@dg9Pw Q{zQ~bf`>Ua. >㴿QHc<@IHti6%Fܸ7rhp ?eaoPK]\J/)pkcs12/ValidDNnameConstraintsTest14EE.p12UT ц?;7AUxUy8 ؆˄0nJDfqJX"Kem}dFjQTLfϵȖl FQs<|s!g KHx@"J"B8X /5 @p %r h'ݞ 3I cqU> 3~ .}!]ߊcB(p^yуD[x"DTST2 ɇSjWGu4 Xۧ@en95)[ݑ3]}5\D,mK[,f]>UC~&Tեآ^ɒsx7"ҁ ngБɡY6*JJpz:raW;iO-]5nF/ ljfFu~!j5K}>_t8Qįv=$5)sQG3龵2E"slXjk.g0. 2 a޼H CrP4r͛B.[2k,w/"^`l"sZ*%}-=вHW[|J<&;N..pe_c9+C`2q"ŹjѼ+^[[-"``MT>qzxtrLNxfy}xJ߇$2DWT /@T^4rT i#?.u.k EXicĵ%zZ1_ ĶP( x@^A(a0u$, (Q'nCߣk-YwX`?PKa\J/6 B! W" gan R G2zBHdOkH 'Ux=c]~}/zbKQUw9B:{(L 13K?{P'Ux5_9cłMոB#%.oY+2JcB4j.cgYHZi]3;#֨Wo*k h&`cuB{݀.a#8-,,3o>n6uNjr›U| ( 2g7~Z= ޷s68c3uSܵ8Gu(:; >xR,~K9GFrm8@p]nvzjĶ8-p25DSw3ǐhQbKO؎N_\>xDY?i\`a[m#]Je}|- -u4V_l-'};դFEP_F&;"\heGMW[N@2yG=Ajt0x%2 0gߔf\E0~4Q$6Q޼=i +۸AW\~ړ굔Xhlaa$;Ɓ$1 !Ya{]}ȩ+e@p&0Mx5|bRl q$++#=UA-_ֆSE4aR`9Z:Z*땘@i1u;3LWVD*F"/%U>CYh1oaQ5vj_a*=O{ apvh?^h@hE]T6/ ^그4W't3-C/|~E'\1ӵ–CoWs58¸"N^o pL*VhJ븀%r :5m_:#Q¯)AU_J˟'/Z[C=o؆B` C$I@CD!E4DݷA, ߷`_TB 3H@$\KlOo*Pi0cԩ26=X"`n(5m&ͽ~P_$VhOrwP@ܝy.vRAlYZ̻ D ͉%v,m73{I+Z39%6G>(WBioؿ5sGe7d%q)PFOskZnf_boȈ4,j֝gtX34Cioް^zTyTt'JOغd.eX'-lԢDweM-^bp#Dt%aC"\,u,r.~] ,P PKV\J/<67(pkcs12/ValidDNnameConstraintsTest1EE.p12UT ц?;7AUxU{<ӋgFͭT~ DTr7'5EpX*ɤ̥PFjc4F7:ka {v-NDY`^ G}&%bq8߷`1P*brmUbhW[{}ԑ!;MY>~by$_Fm^x|?2.)H'mXf4N,ҝ 22\-35i;lmV ۣ[ɵ'ZiK|[Y|B;Z7kXY>4~ux/rs̻ VǶu9׵g0Ezԃ|>fd8M"rLsӶ޶P,Ǩp\{u6կ*aNG㨤C,]+r:+zݡm zN&dڑ+xY썳EV9Ųx@\9˔{=82`wpwVW+sy쩜oqyu΁WR;Ǣ#"N6 4"==iu??eWJ1J@Nj6Dtf6m9 J=}˲٭C]p7s94E~:Aۚ'JJF%3\p{w$G ިAM7m[ce=#}iRW3*"\L 0V$tPQN9Xnm/Zg +{~ ^7ˏJvxvVpX¬S45vӅ=?:M ?gd5M Tg] 9KnMt GErq*`H5M 6LW2,Ji8(yZl3pQ)iZ2pGY9iR/=7~t_wF}$cxJ)΂@ѠXP(xO>VF#`:(*(+<6bnV}(8a|>?PKW\J/NN+6(pkcs12/ValidDNnameConstraintsTest4EE.p12UT ц?;7AUxUw4܉!2F/XF բD'эmClD[5J"Kd(+Fݳ`³s{Ϲb 0:Y*(eFRlB.u4w VJW_XA E Zv?+ aJ605@L@Bs:5og*=O)_ËK eM$\㪪6=rmF7f=ۗ5'0Pmg[Ɗ]I5ѧګW~L4(,8s!g8Y0n%Fŷ??"hW^=Lsb}?C.^gIҎ ~{Y?9wp8P 4S.+><26QI?OpQx&u 9굨vK'{Ήa>cU1Bu+nJDZuu}`?Y+\::EQ9mUת3MjÛɂK) ]LyPZYթ-FuwfS7Sct"u<7(7EgyCV-x Yx]dgs.}N*n@^"D A hp%ƶ v>w W)pwMV\CVjy3XȖtT)lvqmp,F%^we tB Ռ&:L6B̰뿲Qݔ~@ EqQD)~\&OH~#N} w'Xy`pH8`D.>a3n3UwtzhdDl}͞D>\9>c[: (-Pc-M}ÐR&"ēTHUU1 A>$1dG|}n^\M=h`/֞MĔ˒1m\}ؒE-ee=Z'`XaRYumlM3Z!9/.c/@P%*(֤hB%7LA]t\=Z5}h5l`px%90~D,5~:i6&edvflGQDx#2aRkR >|>p7d+5gxb#'ŷ:'Zi|^3>RZ*hN@YXqr|#9,RSqt5DbˊB6ejU@2a#{:g&&N`큇ϥ史X,wNHX/[1 ΢VT kڞ`O(-<ܞU!)GJ*d;U[%#[n*b(=>i5jYE'X*t{͟:rMjV/JxnjН3Vxg"cўQWk'M)4oR "Cd绱m4T]k[ψ]BGfċSیMAx& *l0XKEz }#24B f@p< .]khfT D3rVNﺷ)MKh' „d锹oPKX\J/܅j(pkcs12/ValidDNnameConstraintsTest5EE.p12UT ц?;7AUxUy8 0&!]j-c$䆈qI>4-t'mZPi43![-L2 Y˞Kd ʫy9|9Qa)`G\&`"* زMqT-"*Q!`K8eq@P Q,$P!{ië[ɣH#|lS1;/T>aY>3 Y$Ja,.NŚcϭTb4)*FYV}(8uf+/+Y+r1W/Α*u끘0W'ډFd]S!˥wnVo{5aMC[ P3{i- &U*;nV'P/Wx\n9l휂gUjS>j|Q6wBwU *$ϖݰ b7Ԁ([|)<Τl[ce+f<|/=01 GܼF;$5ݰ kzh*W̻H(ճD86Xk8!p &(dJ6Tfݭ{0-FX`I+TXq3~m汪c]^fe*_z:`K_BH+S;EgJJ8&VUKILV^tUȚYn :}6/Y? A{g/\NxG\,?0cx\E읜 r'֢xoM.{j>?hݙ=D}puM6x}9g C5eҰKUYz2fvIށDMdjDNy=џUGKA> c}:Wyo7LJRFi dA"wƧ* cP] 6MK3-Az^D%'${Tg[Tǂ*|}M+8C򺪪ʀ=B-ơpbW>)@>Fc?Q-;R|*]3ʳ9PKY\J/\(pkcs12/ValidDNnameConstraintsTest6EE.p12UT ц?;7AUxUi8ۉY}j &RԾD2eIک-f(nK-!)KH0]j^Νsyy ; *HMʩ6(ә]B\ʩ3+  By?ۜ1@ bp=tiiji.Vs5D5XKKbPUiuYvtݧw>չي&-f'C<(£POFuLA$6=|j\6;!ұףX7xL eA[${ˌRm.8c""(Qxcʀ"VoR ,e4lx4.֩!LUꭨu*$eӨޑ  3>+:_ymj_0^:9۵,O|ᐑK\|\:0m[֭Z`K?ߴz=ivӐ༮xg=qu*sm(2|Tr"X#lX[qVn:=sWۡw΅yWQ dT3K̻B5{e. Slcۢ?5!ZHŘ]17*oXo 񗒖jj׈{.ߺzTG}@LfW}P=DrپE]U~ny=yȸW~jB@{~p`ѧu,?β#7%Z`j9ȓ{ЎRU o 庮\oqI󽈓;'$#.6K 瘕9 iͩ5`ѼRI55%G^IE}lѣvRfx:Tu#gс^6/O'HmmStF&}0vHtWEDU crWɁ1wBMrR=;'F.x{n5Չyڥ R!3[L0b˩g*/4B_]o]S\ɷHkfѿz|;y| Owo<er?ci¥!7KYsGOQ^XUiJ|h?k$LsqaP-#O2^r#xu΀41Á"/cELVd}['1_,D9}ogꮿsi} ~3Yo-+"G`B&3/ N& \ \oei4MXqg nTQ%Yzl,!83`6/>a&>pJ6i< `@W( =OMp<+*>;9B$%65N8٨=>KyصvZOk3t~q %ġj &š6O]bP-ɾs16W4`6MnX=Dn h TezڷX)ѪqÇֳ:. j I(*[KopcY]G5g(82`Pp n "BRs j6!lhuD`źWV/JDA\7׸7Sˇ: y[̲r;*| ,ZWe0ɺs UScjϬR# c2XȖ:8T DGAHvHC?脐AIm?^XW!~gaX[<<$7#rθC{JsфPAՎROBg ksHȳ`C]AxRV,Í1ͳ/2|<}*WB?M|QP 31b_"H-3:a uWMy-'Pc@\OBlzR-X FwiQD~I":'P.^I]Vv~8%쯴^dW'm:!|>TKO-51X, 6V m]͵)ȅ+D,&LXڳo<=.icBlEWAF3 E[=.,ƈD\S 1>Z̹7t%8R썺l{˴X^@)z_ Nf~#xYb"*:f=x)J^*iZ%.lq\MdBdBHX$mw#`N+W^ .&|ߛXzgq3; %? f_W8^a+~b#  wV'OBx^?Wj]Wbkz 6/TNDQE7ʥlCR1%O "%˂3iq sh}F"l|r^;+yj=Lm<THM  n;&h-T M![ߦ;nH6&ۀjM7PKh\J/&*pkcs12/ValidDNSnameConstraintsTest32EE.p12UT ц?;7AUxUi8- J3j-5I UELN-j:BCkhU2bjAhQ(" <ϽwswhFӡP>#@CmkeV8,1BA3 P |!/cb `OU2R!{lL~O:@M~/HU>Yt_mMȳꬡDp9fg]E&a3i.1ƭ D,XKVHRv&J^*$Ĺ"4!7=bLڻR&A]pч\-ͣηs"׺.oز$V8%잹}®USl5iH9b* \uv3յWrrɼF4bqI mØ}6dmvxX\X!U/{}f*g ~qv8uZض/elUF̋FHbvK ٘Ąw %6f Л;8E*a^No1*b*r[} K7f4JW_Vˋm y'WDg+w$߾OzeRYBIfc:hw}Vhhsc{*vHѥ.ap1$Dk?˺f6եƎKEC)F-vc&D16_t<->ؚM17!&Jo]dJk.+S-u>sXٲ܏K6 N !j΍b?v'fhULCG'JGP%*d M `BQBm\j*c aLvh (,Pܩ>7+[V)TaG]"'f?E6ҽ6T<ấv~g ]mij5~V"Nj`q r_fD= ٓQQI|!Au 09?ԍ=ɉC"=+2鋛 Ɗ]y)ގ 8 =Isk7Wqsw`jv*~?!/eC槺X\0~`:n}#CrE$I;=q1qoκvRg< = 'i.]:p4{i{s6?t13Mgv%Gj T[H|ɲ ~Gv:R>LhJh&"}Yod@d\=r-1IvlW.=Vk5h@'dT=bmPfjGx2N)0*u}~1EY&QV|rJ>jgfl#/8ؘK29Ktat`EWMOw&D;{ePV7owa?G,BdSYITtпaسQԬ0Y+"9$'__T0Pr`*-,i1Gh,D ( ;/軣é㐀 rRCP\ Xl:hMM2~PK\J/Z2pkcs12/ValidGeneralizedTimenotAfterDateTest8EE.p12UT І?;7AUxU{<ӋǿXM ÒKX6%\ˑ!c.ǽ) m&r=gC;˱բS8bphCD^< b ADBӆ!)pkgA+Dsܵ`X_C3` ^8Rfy7 "dv Z,pWLI0Wzyٽ;VH '=qF·㧓Ap2oS36z[ {cM׈`AeX yH:5ЛV2XH88鑖v,iу}S8.j5uՁ0=n;ƧXanopf%@A7]xFIN.n/.ƘJ7d.;:Is]=nÇK3;$BpT~ȯҬRs2nh 1qa%c&ш\1ڂV{9#lxLp[7v(l{*հUNl<&hdяRpW›$%Mç==O\pǦO,ل|w#Qit_6ɽ{XXa-ӠE(=UUÓ:[ۥ(JfybIW[.j^iL"{OO^:~[c }e!~`fzϚpBon6߫39Q.4ga8{iP>Vp7 6黎<# FJjt"s>?Ir1oK/Er,>yw$~U-Gwd$"ǯ>ʸ[{:EIԃ"f{/zz -g1=j}ӂaDnW:]?4?=@ B熢 !gWOK^'c|r?fʢ ALdvm]b@@hmh(N4\68M| IB , eK1|Ș*ٕ̺CidvDtY*U Gg&7`˷I; #b]8v J…,>({m얄6L\n BgxW93w|L<]ѝ݉)Pѵ+ղn'[I9!#w ?fH< a|XmsCUiXhPũJt&{4:ki 3@Я`p=&ulmչ3605g Z$?.x6s >p>$td#)ڙ!3kW\$MKKS*h\_zQM/Xc.7}gM22 I\/_yq>#R/f=ۍf=a NkX5Q-S[9I(kZL~ {Df'$4*@2`|cô J-8rӰ;7$ЗOG$3H0H~)ոȞsEJ>1Eo;Fh[MOnhse)S4Cv7?2^cbhMH(m<Ғ5Ag j}pY%MRh./Z@2gM>%)*  (@D@~}@T&#Ĵ b\K*Ū >ѱ (uPK[J/y3pkcs12/ValidGeneralizedTimenotBeforeDateTest4EE.p12UT І?;7AUxUy8g3FMñEjla)"ܱd cfR6t,aPq,نc+QٷB9NX+y{A'@@0-kXlIEl4Bfw4_+(&X X_pEKAČLpA 1mPce +*/rZ'‘/£㉾_(TZSvr6zmלM!M;Oz`ƂO Z'׸.mTzd|̈́|Bq1tEuiDx]H4nFTn8a ɖ*gq$/CKk{ؕp%%t=ְ|u{a{heg sqwfES JIC^wX8=3`3i%fɇ-O{#;GH:7f[0rs7Z=-P'n[=vW 6n6֤'/ll|6c*J#r W/K-q)M+RSM`` mCT ɏw: 72}@0(XIAl *m?iYٯI.D)AzV8J26$7;[O-O}dt])Nຟu&}k⊚n~cGLy$u's8=kL$ mƾyt?ک\mh:.hZTuƱꝈ\2[ +YQwm7ZZb6Eh/X|~JOƸ$h-LmCZUI]IdrYKw#MK,$zyw=Dl7gW^+f>.087x  (xbI`{>s^7MN:TyO_Ԩ;Ͱ*Brjv)0O߮nDݫz9v cC͎v gF=N%D]:t*V|[fK 3_z8F*f Yl31-MfLg8Nr.1iB %! ?$ڥkn6en;9LE9jyMA=2EBD"-yKwe i:- *x vX)c&BqxVKROvJ{ۗ.AQύjmuMs]] Iqp%O>Z_-~L AT=~cPhVqbfDkuSRR\_O(@ @ހ/ZhIAr"XV@@|w b ^A{PKu\J/j O*pkcs12/ValidIDPwithindirectCRLTest22EE.p12UT ц?;7AUxUi85EB--h҄jSXb'b թX˔h%گemj2i`5FPVX*ΝsǀA@0eCGL<f@ ! hޞcC^A`= B8T?Sd^!LLt@24Xժ(aoV\Pun&z1"y r/b;=?d0߰_"yrڈAxMXFR_@E_ZdTkKZxbf@v "&9=mi\|`>?$9n;꺰.B>i/p6}h|Ln )5l SΟ;/@T:~ᣦ҅$@r&b=c^U+ +j9XOnE=g:rboT2M x q{|-r*n6֥/|E*ou0Itrl^Bsu&v G>yX=Ֆk(“He F.ûE?+|Cv?5W6M[FwS` ׭c:xݯNU:tkHn>Ua͕r{źeqci?jqvWSiP%:>.ZX<݊U ! ;o9%{ >!g#XA P=mhM0 ]&OQD3M{C;E&U 5o,}0}G8]Wt *8~cHлffmEYw]R7g8o;#=bzz3;v3#4-s"Ѩ446%4=|,|O/,•-]Μtd2t D_1<9IF_n:iEOwߑUlB&Ϭfo$%r\O땳] viK|?$]M"Pt, V5qC<'3tR>xPKv\J/.6*pkcs12/ValidIDPwithindirectCRLTest24EE.p12UT ц?;7AUxUy8g3eeMv1bXN(d }1S IRDrGBƱdIXdjc܃Al8mIRIj;| 0L d߯@NgMG1?L- Q=:u˿|,*6Z ٌYX"O5s3#^tEaSdpYB3w=L8+=1R:8Q\^~/NGdvqYTczl.;{*N"eҗ4Tc 3DO6.N s/̋ǫ0D $.(^{K#í<ʤzXWG ?rVT$21$xPXqƏF 9892crYTd^ΔB.yʓ%F0Qu1Sm"W@5(kj9\ &ntE 񷅃?G[q.·i*ҡHY9 c d:z1B@OQ>I>A:57&F_/Q9'[:3Ft "}}(\Vcz, 즺U1B۶\n\7@Ǹ& MUrNt3Hq btZ/뫓/V'r2nkE>;.[}m]k BՠP4 ;]i?4yxgYo̿+ӓcT'o z%]y JLXr枞 1M3z^o:ǤD9/mXgHn NU2{;y-]9gD=] JҒxGya^ĤN_D Be_Q nhO>Js%"BȚdje,Lxѯ3Gj0BG W~ BUIP b7#V/!$P -cF 47ֽ坜>!w9k1ZV3Nu!(9G`D̴`ˊ[ܼC==~găoR+8˃ Go믶 Sf# =Z&xu*?$_vߣ_;VQ^[o[j>`/ܐR +m[WƭjhnvqM"T߼ۿ JnZ|*'R,9ܵj7:*k PX|ڒCe_kӞ֮EI戶(۫sO?R50 ɰ 6X%fY ]SH74'} cuI%QM1;*3+JsPL6Ep7Kn]i~l {: /.XF) enH8d2 99H4%«X3J9 ['c{Lc~'1'ߢٸ*U@R0":Z.zk4o桱l:~㩌^/㉽U RM6RnCȴ6!MkMx {bsĖf\ld䞯&߮˨EH,,ٯn$5|j7:Y (Rg~ <+p_ ~O 0N%:ZQ =HW96nSTG!rE׶(G38i򷓝w(tb# }Q.ꍆM.Eo[#:g;5Wn$:je@Jo/LkEc݈Xct9i0l9 ^˷o`~,_rB ݢ+v؋rd.&}G>k.Mae0yq?Q먽FPdH߻[]f HԽGW/SQEbvܾڽAO1Jt[)|ĉ7W }-bA/X=g ?^.5& yƆ K\"}? = ~ ̿BSTg`g++\F?D'' MOdp't!LZƸu)Y;r,g7+VM\,ش :+K_my~նXF_iYy!Wm܈1OY}g/lp,bUJ%i'K *``qKlBGcnғrdˣ\J/)y4 ۅ:[%7fn +e|ܿ2b]\`~Bn{ʿeAn* rla5Ti~Փҹԇ9z}8:2~_1~~ܘ:&%<OˈI]D?s^,u]E޲u 8oȪmld1wӒgqVN3MIŕHKs3VT6 &h35w)/&6bYf/)[="&^uLxB$b)Εz1zo.߳mma8).HV5)eCǫMqNS 19w+')M ?%fO5NocxkL_Ql#QggQՔs!vkk /T3age A#Ir~ x``*[SPmh(=a7|}I͐\A,J#$ZDD1@@A7߽Ht1sG~}CۗSD܉Ֆ nϿW2Ғ"B7i檋lsNݘY]jYa^3OwZ}|٭q;}Ky;u }Rd}#[_Sr\McFJY g\}޶5Ͳ3Ui|뒈^ Oa_\;&P_Jèi7Swd{`j#i @ms H:c TϬG)vHj]X.f;{ozuSˎ#zfF˄r?|^~`0x0&4 u0?:vYeokiБ6פZ-CsfJR֫ծt} jYfŒnQƦikl}s.~5͵Ѡ]uTɸM6;? c*+2ᇜT {_zGNSXώN UOe2&|hd٧Uo:|=q}BΫ/Ec$k LSC(G9#>wСsˍou6g<ԶɃ3O%duqw;>]B΄wm]!AR@9Lh o)2PgB3;,ZvrMSn;!Ѡ*c5c\EH XN4|˳20/n$2$r䓡ˏkm% N38H$WD1 h}Z!h0[ n uP V<eBs.-"!/)ObPG2W s=~Tz9ݞp<u^WKZ?1{UMD^?$Ж@JG@'8.p"(k\\ ]S>1cu7ϒ>3q߫Vb@wDxݩ Maɜ_>spb^7%Vq,B.jϾ](ITboy@]f'rd$%=ս9hZ9z7}{rGe˳9r'v'p3o[@$ ;|l.uhM~wnAN]fi}r40ɐgji٪w's4,/рaH\uՊ6Hq9NJaeQ۽+fS9\?sO փ6XG{o ]LGj'+ʃS }/t-]ʗ`FhYi1* 6tNCxl0V_}:\(<P]Ea} Q0dCkX.q󾼥Y/I3\9Od3?PKH\J/kN+pkcs12/ValidinhibitPolicyMappingTest2EE.p12UT xц?;7AUxU{<Ӌǿ k?M u#c#,v*(L.fb}mcLn(d39 [8*r?q:z<7DLC!0 !ͱB$! "v gaw,/()g/SFs p(8?]k'BiBlq)qS) "=GbyٯO2.^H{*6ҾƊ+!?Ǯ[#Ŧf$Y]klzkseѱtjmQ UUW/3FmOp"KmW %]! X7GZ`=p˫p!H<`J[ĩs}6hkF L#b῅{'vݪU7 BXQt<$6V!ʇOjryVv^VƘ[y qp?i >>=)Ҟ˨eۙnmEIe'k;e+mBXclpls1l.J̮>AjF|[>o mYm>JaCB?yjL~b1LtUz3|~+ivQd:KIė_6 C %Pq ^S( h|V8^ȝæV8{2)]Gmz"wh9l;|ݤ~Tvn,a3򴑟tpu{XUY5g5dLJʩ@ RհfPrȰZ2 H>H$|? M=Zue@2cROᒴȋ],ZHӧV=ZnގuvZ7IMܠ/=i,qdeQ!~ 4u֌grjLdҸ䳾iђSpRdi8M1-@M.1k}Ch݀f_Eu&nnw{ᘐ2CdCWɒp0TkPSp8UBA%8* Ȼ>ߞ0.$0OR&~PKI\J/P+pkcs12/ValidinhibitPolicyMappingTest4EE.p12UT zц?;7AUxUy8 9dD<ԙF!EAC6n `KQM+:AŮUGW6t4ڲΪ#GJkgwg}ApLX nraIo@eLX wpLH+X|` _gp Pٮȑؼ(6, d0!G?eC`Yt]HJjȒI@:CNoְx!YBq/& Z`zloCb!}c]Xz[xM=!Ib>4n?-γu+v7'{4,K_WVown湈3}'Z!7?K1iO=ϖAǻOiIk~1 dH5!RB T6=iQ&r Dwc3sC:ؚh{rd|[iDJ똬=}14Bv*zFћR鴦U"M,H'&`S/;oY?a&F_FU.Ip=EI xEU%3bv]}kΒ:4CckB #\c!KP΍#ӯ69hŖ\JzmTQoXI͍hcb%QK~J cLFt#:Zbf(*boBcFB;'REN׽ڥ-n >c =^Gw/8ho ;.1"[!@+D>ccǝ498;ހ3^ꠦ@fT[Zµs>"$Efr'9ʝ+bGG'(w#']<}ʙWg˖U&=" 9T4H>[V-߹tY(NS=VZP,vYQ{QB`_[ǎ6R:~ǯT:O4BԡLV</fr p\cy;}(\vnAL\7Z׷Yu.8Kws9+E/5C[V7∞Q5+I,xP|CXir#:},qç%Of0%*H1Q*Xv3h~f -Fy#>{|'bv\oXxvm E#uAK Ӏm>ؓ5b< pF Qp;8^'4 X'(35J_*k(m_I=NT#ů)$"5AHik&Q9;1za~gNRS"p߰kÞ/2h;FQuwaJYbQ{>>$lzx>֞(#'Hܨ-X4|}gBUQ7jZW—I1vFy)sQ^Yx=s̯x5e>I)'sNXUFf5wK7m3,:j\j6w7@I3[5#{t/93P0H[6 `/g〢 -|" `Ű 2T:B H3ovMx&Np |t|S}IR xLN*%QF˺+jB4:kU|xAn<^w$#7NK`;go/ 4lkq4HII{= p7yܻe5GI#C3Y'5\3Z9ymU<0] gLDS=F FF?X2ܗ( ێ}pTo-IJ2K3L'4vڃnWazvG 7~w7iz{ǾiA JJtQLh!#3+#).4eɱڝz`WDj|OW eypImP V_׹ f,D20Ӡ)$$a->#!wV^.ě5ɓ_U+ۙArhշWU q ̰ɹD9R6-/eYit.9uѽ[w~6]W=R bHڤeĘ*NG)M׬JȨ_~|CjHoIgh4VHݤ..ןZ+C: 1My+ev|ә`#@8 <յ| ?(B`c[XP"@(QWI񿨃@s[Ϊӧ5;9q  NEM#dJ-1gv e+yW4׹K8].MO[iC.0 Ӹw3lh7öhJ^xǞ:aG Zl5 q{N={ ~_4qG)}$>wN8@ 0 xp9Q(i7SY  NQJSւg%z?< Q!! NPK \J/Z?P^(pkcs12/ValidLongSerialNumberTest16EE.p12UT  ц?;7AUxUi8ۉH= TR*"PTZFkOhl-SU c%ډڇ&AvSN[EK3c;w>9=v~DtC&2PVUI À>0%v >D@a!2T?-S,1L\e6|GۈTn,8@+Hq|W~2q׽9 n!a!! %RY&8T`U &5yuK#ZD1'/qB|񀘹.j5.Rr Dmñl}J=+Y10&mi>g֥R/pq;ȈD#.ѩ~WRr* al)4xY-vխٽ<DU* [%3-CS3Znhcƒd^غ"U q7%Ap`O'+lٓofw̹9f5l)CL@Aitˠrv"z3WxvQ% SN>0ͅـM=dH<+imW~ҫCj ޭگɷ=9OV_֠[|]sޞF.m+޵x"#8HF}:dRQ.kO oi¼a,ݔ*M']'aLjb$y:ٔ|Z5/;x \GJL)&lSG, F7kו") ټ3;3_#k;b|Iۗ/`oFcE߯ amCI@%8H$!RHdB_Oa^W,_BCQ*:{wXrGڇFii:\fY ݩrP)!:sB{Mړ:L&K1[mqvxFS"L[LJ*HxR|إv{ί&ɁZ-7Fr!u<2,3SuEjDI1 "ц%~;P=Y};jwL=ޟM-Rpi]*KTJ`\FQȾ($I |/]fK揦϶µ {vd&ؔ;|RLunV߅;2•kr _T&|R 0_^^`穪\A{Ͷ֡xD*ߵܨY)h6)q製D)/ygΉWr5,2,cgy'j-4fKOiKRJ/Gi#U {eU1 Oϼ"饊h!GLf*BY /cڵPGwtߛU> Vl\YZO _7DIU~~jS,pmhYsc_°oP,G}є޲}`ݔul4ն Ο8gҙ[Q QX;&$c<'YRo5t @&ncouirhq%Drܚw?;e oOL[BIx=Y"}~ǹѪ|K ޅ %GoeWUu7x ;Ɵ.=`.%l~ oLIջ63R/kS)艠A:-ڜU>qݍ8iP|ͯaȠlRg#NolL%>ڌTp;Z4P-zA<*nͶ/*i&'d!!@r{#;吀;F/>LxGstc/~s$m֔vxd^GDXүcҘok٧wg>45W= sCT]-%_}LN .h\QbR-vz,8dTH&n i?@F'DqMwfUE7#r5ȵ'(SJhlg!0=ъj5O̦;e|xYmVeGǔ| P}_+OG:.41#zI]k*vucOBsV8C0PD{7pr"[Z$_$R qj$(X3 (U'4SЪҳn' .GF3:ɥvA9sr kaS3OHh.<=0)i꘷-:ih]>俐"yZK79 Ǖ:aǫ;uSg[ki <&`VEl>jSIo.sJ,bjzמA534NM?cwt|tU/K5AaHY$j*˶&-9I<|< GrW؁ Կ36<]{3*T.=^h{+$l{o0 U0aR-5y OVXzO\e?N . [jk}x찣-g[iJ9&ًſu)I/s]zʪCe >h[)[+4u3kס2<t7C*t/ 7w=Z +}A=MvMD'(X*FΕ]OK 5yN6},W-!CI ?pRI*V! RقȠpPtYX4V.-(`Dg, H[Gp"(LsL9LPK\J/u8U41pkcs12/ValidNameChainingCapitalizationTest5EE.p12UT І?;7AUxUy<ԉǿsl!̌41D~c]ѸƱ`fܬ5b)5\ʆ!D$B־^o<獥 XLP-\6*R4#;Kx # 0 + Pr6  Rӧ{I bHSC#,=P/nξb67MH~;Lڧհ$AkAm'(sT[y8/CU-zveνhOWY5G6{WrVթj ;ՉsjVocd Qn3=vmFR'C]DwrKd ^57J]noS1͸G\BuaQK\LhKn1%dg%/6,8 g9ONÝF.iFm̮>[ď?3, &cDIN#^yæd&[9ӪhϾom n-Y12F`16egvKHTC|]~hoic~5Egk,)ZT]3p̉$wds{Ét uKAЌ:jGe}R}Q,W q~W2e|В̒qRiB}o ڸ,#dE_/ !:ԜTn8佑15 ]ҾR47SEJe+T36аY}r$BHWE[G >1( "|d /VB p \sE/ m  JGcZ^N +zGSu>F zdvy o@o-"=%2,\LðYTH(q!dG4ەKOW{hI<@j..W[H*Y:1ʛ>h6E|w\- 7wM킳jkeW,FVΨ`6r,uw@}<ڭLˈK'킵'ӋJ6A4&4)<'<^+b b(c+ f@3ak_&w[$\ٿԒHr^\+peԛ4Iv^/כͻmzy{cj0FPG=76Us ?OKߚo5ҝ*G1kn;hm\\ Tͣj?ȸԫjUw|W1w~eb$ފ'7vPyb=y2iJ/)AWRR nYJ}4Q!mT| ! /дۼ+bP7OR𖮆SaA> joo;xVˡj1|T [SN+ʡnw0aIkҗ4Y-bML_$j;`1fA Pyz&' 8@]Z?GrrP2 HĢ0>uQ@˄4Jĉ[ Ihr. PK\J/-pkcs12/ValidNameChainingWhitespaceTest3EE.p12UT І?;7AUxUwTƳ! 0 e D@eZdQ#$@8e A"&D2e|*C0` {xNw߽ހ` Ƃ5IE%Bet  VB;Xv \F& aQڃq,0HOYJ"6 M'OH{ `7֝wd%Q ֢:$Σ+y_,juQȞ!ys_¥ʦe]s]1!l$E!̰t6;~+YoOMP '7\#h_2#<l^Ų+@Mվ3 pѨ;ÛRl-9dQe%_y[Tģqշ/8Ū4&QkVVܜ2rvqq傛▣JӸ$٣MrR;~i4cƇR4FT0YtAWsCaCv;<~>w| g CǂETc9~-km>4߀wqwm3ڮXK*9 _^ʗLijL}ٻ"wmF?dp"Iq*SR4L [ sW=j*u+ob6EKYS)άJhs;kwEUƥ#d32_vN6pRvEq^<fO^gWNtl6{$Q݂RmPxKCU Gc<;~KL6I&Ⲧb܉$k}w%_o /ʟQ{(pd t7NK3O5}qoaZv?i6EߩzUyltNa"֔+vmmI٥ޓ..#o) sUlxqTjSH1[!h.MUy4)]EF"I(8'6n͂L[4t!w&Ajw=N߉a\ `@zUkzeC&y(;ٕo7GA_ AOy<չ+˾l BjWRn鈊аL8{K:&g2ƊUѢ9n_+u %ws˫@褧QݵϜ j"g ;q¦8&;""gr17&u eUONa @xoB XW]'.{"#q䆞 whpHFT\( @=QaPMiޅ(IB^@OVBD6Au PK\J/z<-pkcs12/ValidNameChainingWhitespaceTest4EE.p12UT І?;7AUxUi4 ǟ,{jk-ZuPFaڷ(R[$(uІz-SڻRKjKFت33;~@*b TD)u. +ABTďp*"~Rat*ȲB[O#*!P)5DB vBZ焦 q쳵Ap-01}UKK7ͦUǼs-3.YwեsSAςIWMOhO+,{ ߍ|?=ZP]pPEz@GtE7gЄXL"!iC=ޥ܍G},IIY߷xGӖ&/L#|Q,Rg2>E3n.G_ڼyL mt. =0=9#+M$%9,N^Ɨ׻Nc i5d@>נ^`T~(!$;Yk;OVJ#u3~.ӏÞ/Y(JH۬<9.2Vi 5 -, S*W{*M >eh䫷 ڨwiwRk;dY]*jᘑ'Zzɳ⤊ Zx6AP׊?],5Z\pKp_.Ik˹k k%^pntD'nn]/ IeᇘW#;5&-}-GV|3ywA$@zy$=v6tE.Az OLt0NP!|)%Aȍk^S4(E". eg=]wB6 #j I`eeOV@$ \|0 HG.Q膝H4_`ɽyiH J{a1'PK\J/|pkcs12/ValidNameUIDsTest6EE.p12UT І?;7AUxU{< gV24^9.e 3B8**݈q_hqhBMb!Ki.iQ!9rtrmsPG8y?~y~Xn Ăۥo"ddY0 ܱI,бVbd2vH߃ C5# ̇@ T'yTr.Ex-VCxbH4V:>6YxvÊG0=AokHD-ofs/Esa0vLã73M䤧J<)1McJuQ#9ES;#qĂrtcw۲5dXD_Je0w}QRfLE2;oØ#CzNmx~'/~i+Nm5`Y%떧/ҙܵ2{%g؃~A;E.\`, ѝ t⎺Az֓;g7kȷe Ja2=9AVb"YSq,lpΘcˏ jV+V#m}Rd :\y6sOn\BW҄1 %G9巩c6K$ ٥( q[0KՍ7 J%#vhx:wTBE.[l$AEUd30?3Ip'e%rQ# #s]u%-F?|.lP/`|^ԱD7=:mZ8'QF֝yfʞ?vUo"l,WĕzKl2)U9t y]=FlT092>-E'Fx^M.(BCӭl}*FWJBp`HK-MxaߧM>U[ئA;e U0 cڑ4 5ڲܣхiu w؋sխC;4d%yx]c=%:{k\ 1M(yEg3Y}Y^[s&~IRHV|u ѓb9ޕq>96{dcktk-J*e3mtCN,'y)PFH{eghK_n.y&6N)|7ܿ7{tSp)`BZm;CAݿ+{h'V?ey6J{|:‰@r]64Qp;,;±՚QŜ5jPYcvd(KS<#3 ~-)q`_&J^ m]OObg,"d4*Dc=(8ׂwM7)4Z^?_{0iOJay0VrH8%*p<=I{_Z*3[-ȓfը&=wZ!'iad0`;;yЦ;#ULDvtI8 "K@j09n4#j!~C{X߷ PK \J/c\,pkcs12/ValidNegativeSerialNumberTest14EE.p12UT ц?;7AUxU<Ӊ?#6ϙ18;!I;26jHɯB!2I-HD&?"jF=HSq}~'ɀ1t]:#kSYFN@P]#YA`ҎE;B}߃  "sY A y2lh+Kacs,iU{H܂CrbLhհ=JhjόW8sDlml؍ůOjr, ؗdG rRJmyK(yY7AIm̓W/̠)xu4c=Iv#37rQu -4Z;5?ۻ.S Ӏ ։91#V?Pwa N[s܇ +Vn6?S&zܒ+Z]­ EJ&mġe^{#JA~`]bqnRme#rڮQ.ĉZA֓osZtbkM]I`zDr%E?9ixӼgRsЌ 52O[iI<ı'v?&:s.?]b3l Hq5~xD%JmB^-*"c%ҍ ą٪5C 1#KLJ+ %>#\|Z뢼 xrAp︥ _ J79~ S;n|TFL+<(wKܐx)i$7ލTl$}NhCͺϊ-4^r4S_]B,Vs>CжQtu+pQ@f8Y0\ea:@&N=ߋY2 nM@5Co8}*.LGh(Qւ;ʎ`PRAU:/QWӜ'dE̫DF?Lm>.\xrU,edSA)(/+;_ D /k?/$,51G_ F<RW]Oۄw7)Eb׆/kl/11# ly1L%.wsl 7+= _ϝG,GbǺ6#ȱf4u$HZ&vNaaR2Yf ^p'UBae+9x̑E#{^6 2o,\)߷XL 0(CF07#Ekgp j u ns~R|'v bbiBnfȂL6ZęA?.l 2FpTb-o?{2UF 6~eg zj玎 O)9W=pGD8lⓁ_/|ɠatw;fJfaC5UݴhiPq1zH-KYZbb>[oʃ$+!Snlk6oɗ|BIlGM<'lEޏZсz>y#i{f(V@XiBI3E{"UI#V7@ W *pjGN 1 PY]`,$y$rP泻FdP(RaPKo\J/^ե]f2pkcs12/ValidNoissuingDistributionPointTest10EE.p12UT ц?;7AUxUy8ԍ10֑& #K%5LdHo /F#Xʾڗke oIDlFss}9|9Q`GKl 8(g6Y˦@&ά`po 'cOqñCwI`0xBdn5&Zxzsߙ|$Wa3R΃" f םf `^\SWv6AZe=Thn1TTYVN "m 5F=L}[umМCDOt6a!ff 8C/:\[prrnu79b4WltZѻ^el-rӝXu{t F?BMet)4Qgw!]8C' RHv-%'sVU03D~rFJ~M="INޯ-IaDӬ}ŎWd͂\h eU5Z`_J vzO>JwdybLZ  P 5J#R}8/qԟr_Hz@7e!ǭ1'NT7';ToUP!<_] W2Uۏox[U FNhEb3f9|/JS%39< 6׾4'rjKZuQ=uvq1G06I{~M9-Dn[u8W%eWaBFI׏Dq=;z̿Prɫ5@gvWhمRǓ= \ݼAo8ggaY \ŝ<-lOߏA:tXKrxѢ,)a`M௦fئ>r-~jYOrfG-nǦEο")Ӄg@ @י<+xp!?w כz(_z{W/>-3]*\W  (6 ^<.y!?#9]T\[[Ӄ޺@0t:' %d^u8E(=* n[\q"VyEIE7Cծl0Y6 *3ԷiH=_W^25 yBG5݈ &B|@m=K5mP 35f'N8Wncy=@Y*a4I 2u8"\R]AFIq'y4 19iˢ}7B`)Vu,wA\|&B߈ݸ`hyo7NUvnGM\ͽ2I7,rwzB !X,JυzvRӚn$Р^.fO$JMe2:ׇcQ7}5r:P\V|N(%1游 a`E_[F/V' Ά}#sûa/-xG-ˣ( dmDKB^í+vik{c^xͩK:G*^W#;š=+| 6 _űP#VjJY]5Gߐ:yn E^ _k[ G@grr'4N1ICL;g@c>7?31 Ѝ۶ ۆw-=nL%ɘh%T'VF?Eu:>!ޑ])񕱾 둼q eIcJ iIey!*W90{%F& >({pB|-Et[t׼s&ٙAŀu+ȸ8egTߴ3 {xZDUJ*Tq@^poqZUWae?=c^Ԣ]cNdVWԫt?LĒ',>ȽUW `ȝ=8,е^o ^%NH&cDyCP|=2m}rtZXybPS.`H|] Hnq(G^i-s_Ål0?k1gzmpYϚD?ŪdtC_A`e5Et0.,gt]:NsA?Dxɕ`o2ynZ@}IM55sϳ2>,d괤u࿿늶"¿Fl—Qe3#w>\Y^x`$XM@Xnq=I7_EO]tE!2¶{õ1by'0QCFc֦2צwLEnQqk=bdH)J ^۲2yVyBiU43|in$lrR'28\$lkdz Ew fGmK7-kMZ=ߨ*XP-' qC!%,HoB0L9O a,Sm:\v'QD󬶀diS Fe(yƎYx3? )M{Iv{% 7ZĖxQ;]ljpvl+ꂫ6O:0.5a!(rdkF7vT NVsL qF0t]:S{ЦHDognAeNn^(QbeH!ZU:{J..1([j 3W# ?ݔJ i/hbs*'R ͉/Œ4})ʓ"hΦ+tYŅ{c۵m>vD*l`>^1, rZHw s#x>BL" !(bܙ[P}$_AA<3NU8 RF#1lLR(57s.B/cpBdu4Έ q`vh/IZNkgV]Eڨ'T丅x*cWw/tr&ql"+;,t}pPL6Y<&.v0Ԙ%'NFf7sx~eI*"@ ƞA^{p$0ޓ _~t)ot9~i^L!S~7PKs\J/=F'pkcs12/ValidonlySomeReasonsTest18EE.p12UT ц?;7AUxUi8ۉ#ؗZkjKmP4ӢeETM0GU05--մZ:U*TKPy{>+0p¸4v=>62 Xp `ejNKø3PD|$9^8 P!QDz;z7^q𿃞u%yVyUO6 U58lHJ^/f-?m4 &5֛Av"C#S]82_!Sw8=[~E::9^Ee9%R u iBenI?wbHmڱHI KʒjW)CfX5#@ŎȮFDzxWMO.װ_燠>?Q| `'mo4G٘g+,axC?8 oX1 rNb}q9|ϛX_]れobC:l'=hA4)I,4^ƍ#wfℓ4,5. hBt0XjfUph>|?.+ 'ByGihAы'vT1OֽricLἍ#r.L}r+ԋ6ei8{ikc]yH YR}@%oH R-E mKVwvd B%Z%sxUڞ7|p\Um&؃WUn_tu+rzaq{ʐjQ'L|3 q4'4uʦ޳NPԦ%(#wLlsAKobWĐFm!*g Kѳy҂bi^<{S-=9 ZcBł'8ƣvܴݖ0Z%q[Q+;Ի,32jhl{E7!4moo%MQDj Mlp/!P"|j _|e+A5/DžL$E5:IyHmOLТ$.1~A 27g 4xWTLgE,zeUQPܧ{F&X}3^0NH9ݚ%t8άުTmB.!ztho"[G35"!Ef 4xv+,sVJS.6urTn:F +nc־gKHɥ"]cPNZzPKt\J/8Ү'pkcs12/ValidonlySomeReasonsTest19EE.p12UT ц?;7AUxUy8g3؆FɌe 25H*TJ'ٳoӵFSDhs$fRs!K\y?G*, *v.T? ޵=T#( Zj `gB AI\HM/b9̧lȯNJz9@k;jzu$>$([ux/DzmW6/\_%*`t鈠?e2˹mJrbYdv\Jr!uߙt2Kvg bY>_wb|dk-)rτ? VDbڸ'G֗؛Q}ʂiĽ6 >ʈ{+O6. T: pݦ6(;;9ٳ# #CᗥL2KCI^LMrt Fjb!N*!o7 W` G,].-F2iz;['My%*=}`x\0eM:6T.x])%gMpjb9Sћ M ?v&Jjb%6@'йZ64"?MT R6}舙e,+'G_&oV!%kBl扄-,%@EFG n, 2T||~9P|fo?H<16j5LzR@GM5ʔ,Z5afܙE왪5 be!US$0܊{*r IMEe `Dsu6Ӫ]7RA|y췮dP։;a "z{vhDN(!#0\{ya2Uv$M:u;{´P9~L!:6JxEZ;B[2ؼP"VB3o] ,T*. u-H!n4ԙl<*Z8&a+o'Vhȸ6TtV$ ޯ/-WYjHG\)EKKvM}5秉1KRhX܄`ѿs ;7&azYESP޵cJ x{'<@bޏCV!;.MxwNiݙߤr4J`푏zL/3x!͸hOq֚`Nх;?hA]\FuV=~LLZMr~4ةVGe6l7Wo(34ll|ͽdMB2]qd4߫$6Iy #~Ρ09;$Tb7 R"LQP#ɳ#ԣ+ )3ABUcӿi@ 4;1[d΢\D5c1x^9t*d̫*roLJ ߎ+25hN x$5 X놡ҸV$3n;z8='6)-6Ki@~UwhٕF(a׬R j08NJ.,l|6-V^pn$ɇYT,1gK5N#.79啜9>mG͟+\_X}v d 2VRx8`˷~ 3^YLCH?9W:vb`{-wغy:eljyUZXPфN|dtIhOZsɇ˧r]NB6 z"|S"%%s\\RKl95LIFSkn̖:qTaiof<ȼ\u U(M:F߷%?fH eAwې?胰@i_ qt&e5.B~C+iB5?{Rnzjvٞc6"֢ĆaTS1z[WeHC uZLC8ȄVoL${qoe\"&兒&@+22 ]h|^U5h}6Q9<_0N ӲNU"yn{5|6(-T k \=Os?v;Tmo_Rc8k{y_b@MFs_r*Iroǚ6=c,eԂۗ6:=dmkć/h^~y]ciz&{ɾgo6t⢍LR_sn!=4UH\MK5>- "v8,n jXL;x`gK`:g8"7y5{rOZEu.U ڟSU6NUjr 4)<g2-]&o_َi\@1#\,RKyP,WbN=z]t%zhn I0;L/\V6VV"O6b(T@Xܳr c"VϯF(+BP3L 7k\qXCCHhNh&  W ~Obb0 @Pm&@PR)c p PK\J/y>y$8$x'!{fI: ̮HWp2 ufCGw`vp0 A #}&Pu;oro.`J4jh꽦e oS@K8q,Ja3xP4BEA-g v7:&K{oɢu*<(1wCʵ ]ID)N)@K덉Ftl#^U{*JI'vhV> t$|@#t>M=r7"%~%( nFzbӈ[k~_G̈dT1Ji]#+Γ-iG5:q;0<篶h!L,YuuPҮGaj2H܌lphbzFrt~!2 R 5W0E#H @TxC͏2yaFr6; @Ff֥ !IvnR;}Kp>aXG6&uv9A]Q _UT Uˍ[|T]qwzOg:#2r=>[0C__l6p6tE7jn)784n;E&%{zTmaI)hp&?-i6H  ,:]A3߱|E2t qbfϹL+j#M =&v-Ƅk5SU4ہVn|OgXqPG$xfDR8+cp$ctԃ?S ڍѳtG לoDQ7$m))Wc29&Ayw[)ìk?ݑ;QjfN^ƫk#?a$];my_و Gn zjfjf[(C{)tܓEyS@_@ɣa[X{FJLBm ?iAO@ W˙Ag3p LPm}@.ֺ^4t΅[cQ_b^PK\J/"(pkcs12/ValidpathLenConstraintTest7EE.p12UT ц?;7AUxUy8ƿ,jRkI- |!+FcwKF)V93A#ZPpXHq b(Gɵl>0٪X\z[|2׫e2qtgy$aܹY-h$kR+avHR'g!zgt} Y|E;ڔ$B՛۝,TC[ fϋ u: ̒+-v Ӕ̺zF4t7fB9'5X~o/oݸ7,+}J@5{< vB f-ؽ&-5e*lX.e/\Z BuwG}zLrɊޒh=T ;V&&48n}ަ@2i.ld!v@GrRX#t{Snvqol0 $ Ĩ<Ќt 6 ₹fʊi aD~6swIpmZ~1~o.Ӓ2zK MwYmMx$bՂy){Reԭ|SeǺOqD*@ڻƣ%kyݙYA nu+!/I&+|}Nfiތ0(_z–\鉿"cep!Ys#aɕz<*d<~3?MU̎[v'hb +< V>jncV4ĄMMe:|naHQtQݣm`GܤQ)=#|,*} |sM-p>#ZyWrRʡF R>C'6Vt[ˉ3?]nJyrz+P GgI:¾( DbjeCA74!P">;EDp). }?MPDhVAThߚƴ46G=mF$xS`iзZ^hiN_O"GY 0rSBg*'E8tGVa]wft+M,0-DT?hK9 Y .V1YUE=TPeK9}޳;\uF'8ƨ; 3|x?tLu#}SБv8mQL4ѮMi_tZߔ.2\n@;n7TZ^sVIX^ m^*+ {AOjfi~[n;·>q7io2[u^PxhGǰ scqkB o;]ݺwrB7 n G75_>w)V"7 H_E-PjV~'&m*kaV (?H`<=0Lc(XSdB!LO-  ZX> ࠸_ b!sc KJ `5 5!1/ cyl{zk)#FI ,Pn6;o?|هLQ(`0dS5p$ʣpW`BAr+6_w`pOs)ʧK@ngp+^;htoB~ϡv"PEu)Gtu>bru{ZU";/{J#vS"7]˭eOJUȡHO2UƁ@`ep`H*_āJ&U:M )1&Ȗtϲb!tZ&Y*(Bx:XzM9ECSƍ%K4':V^C Q%N=i&;4eƟҿ]JU=xa $9m(|s|5Pf^te(nQFO5t.|Hi6 Kne<ҝu)hWw|ВI ƭ-:W'֥r\˖")&ڋczdzŨ 1W7z:'~m`3=bhi3sI뾥R;\QlKE8iyuJ̓Qxʳ•w@N}0G)vDE%nJ  `߬r7L46`V҈۷DKk7T4Wq-d(9GV&qqVhruЛ'[æKm4ZWڛG{ ~\>sNz:[2s )L7bh ̿QL/vޚSaHÜTBl?g1Ꮝ8Ӳ N}AC/̑}5iQTq*儦8Tb HPCCHh* @ 911h *' / nH\vK!ߔ9zdúEPKE\J/Քt~%pkcs12/ValidPolicyMappingTest12EE.p12UT rц?;7AUxUy8 g3fK& fNdd YB˄,c,QH3Ȓ%bPLSd_ ٚ)Ze<>5P՚. )0]۵5N,Z\[f/EBgB"&Z@0@Xw6߻Wq@zvl}ncHrrRFhor5N=&=iGoevΪ+kZ9A\E*g"y{ #8Ce%J D)SzO[戵+ރE6QHRMTi{eI"&Sh3̅6ۮ4M#^g( Qg҂&a.9loZ~We+ZX+oX!ӭ{һ*&#U^YW2!ߞˍ76PDcҿh3 r9޿l@LmkgUԡ˾v官ϯ Ɩ}V[4j8APW]P)9 5vƨAd'aOĽe"n wZKZ,CGx>C8孃%b.3O8v=DH$xr]xXCa}X!dY+ /ِ}]Ɂ)p|DXTWZib&ih5B%{H g]c?4Z߭(fhjU//Йr8s Օ.zQ;K fkl@㉾ GR>h}7#U2S纷g##rNh!O=g8;7#bo;![^fɀ+il7f UKqcx 0aE%WWдH9>d>Jfp_з8Zi'gcoVB8No.Hf[tovU :[$aosV1 'P|NlWܔtuۜ;y_xN>1nWMAu{e۝MTĤ TW.rj-rp!Θax:?Җ -O ƬԚvxZq:Oaݙo+hQ&v@|b1fGEj#˒[/b v1ӋvD'>x3&S6j/,[~:(9QA35P%<|q/N[#j/;u-U6׿HG{4l1nw `1$)esr4%9*'R9Es$Fd, \vE}X9,*qU ]ʂL( %6<PKE\J/v%pkcs12/ValidPolicyMappingTest13EE.p12UT rц?;7AUxUi8 %A- tSľ-ZKKKMP*%2(J42ahQ4hi=R; j癙;ssŐ|!Cˠm)( ̓هv& }-!-{pX,/QJgB1tiԠ/_)E=K2.rEmY]O-QAPn81Prs@=vTfNIw /_;>'}MnXYw :5^m'uO /nqsS/on*^ͪU|;b[~ӦױZ 6 ½AW#^"wu60lRtu@*]=>cdThF'{SM{'iVHݦ$ZCP&v[qg6>hPH;De@a?A)^Lw8lļtl~"lT]t,}:YgB:`Tʙ >qU4/{Vߖ,fWF->,Bf~(/G~^7vm\#O阤ͅG.<~aL-JWuj9o^=N?CfGܬЯf=Qm KU[nXF:' {C#{3RRoۿ֙ ؇N#S=xF*| B2AaJ*!1dЋ?6sJ;r!H6UH}흺OoRmXrP(.WwI1|ߎSyN>t1?a,"ʿև`o܁ӽ$ QI‹}Ϝg`Cp} uMzÞ$OfS )/ZW\DqǓY2JQ.΍XEa#Mtd#BK= ZZb fk8.jʼnuRN-/O2^Q"nuw28KA K -x8:"ն(;k{?2iO.%C}a ݮs^i Dڛ+*3w#y^jREKo{dFp\a˒Cttӆ[J^ȓ2s%sahe؅w$BrU+L0,PF^ãT.U"!Z]5З])7"\y{MɁ ԉ?t-xRF%è se0}~໢5te L瞮*_A1d+ޮgg^ 6e.^C,3qFZWYf{.w '7](#>ٻ .ǞK]vvvv}dns5K|̾ xژ.i{=BEI51C6IȂW,J[fުeP;[ !Ydֈ xg֢MrV:(E([iOP\쟦S&,~m;Jzˮ<>QF Oɟ2 N ZB~)s(}!h63&77qwxzEqe-Lj:E2z &bCJF,g?^B CYA0mrc9l-{<ĕq/go85͸/7߄d OL KroI{}ˣ&Qgpt}L_ZW猤f*9'w^T^"'8O} U8BŘEf ŧ qizL|㇙*`WI|/5>>DaBFCͭ{$/GmF-4:5J{L(|ͼwx;ÊT]y5UWǭ r ouÛ0 d1#}Pwmw&顇 i>7*-y##J*1T/ mkdRK85.aVK13uj sB'%ݣ |f3S~Xa];^5HrKN_1xjdtgyEf۞F)xTMk8fEAQgoҟl G|0.b<r-^\&jS v(:hz0L˖d*7ro*kSy;Uj=.D<(2o[#Nsv{)+7t4)|g"o}µzɍBR1AGay TJRyH,u؜P~W{8sNQ "u-X[N]WZDVW5XV!Ҽa?Gp]J ,$=PW>= ss #V R@kir6:Mꭢ%#aB$ҟPK<\J/> Q$pkcs12/ValidPolicyMappingTest1EE.p12UT dц?;7AUxUy8ԋgciL}9v9"$bkGHb1c7!\ 7h*"qط8y{} P Zw`Hc;C:hűe 0A0!ݲWC |D`۹Z4_ڳQNjd}MÍBNmu%`TP'xꤖoG#EYa~5W"`J.<<^Xn?_jTt󖯐r_7 y;z <]+[ϘfK^cYp%4IJֈυݮح5gs@ GȊ*3.Ⓣ\||mWJ[J-q{BŁ+$i"8-)Wէ}6ӃHd\Tg Cf,Dn] ΄l_ ^ ɟ*G ɺdB|x?w>\-809qq1E$F7Cի5r%a_lB0}*jBxwCgcp0= ,_%x]C$?{'.syӇO'SvQ-"pS[թ{r'q7_hcFTF"mc ʼn  oA82~gIv;<Τ7o6nݰ,%>k[ψC7n=>NGL11#Um9'׻ׄžCtm]q a ԛ#r)G}>caTwrٛ¦ڟ#LWD{h+^|i@ #"$aFs.'f%wYJk2ÜֱՍ~ئ ^ƞ7R^vfpti~Qc(QWg𿯆k!ab'׻w$;1迎ĴddA Ht  ~=7h`0p- x@019Ҍc[%! PK@\J/A~9$pkcs12/ValidPolicyMappingTest3EE.p12UT hц?;7AUxUgT| 1 5 $dYx)RV^*EP M:"EB&H (KE@),&MY=޻wgfޙ }0@Pȸt PoiAfr t~p<ӿq*i只 ͱ4+-:vt'; Y6^qQw)#UtټܶlEPb+ffkz.KVuc~wz>-L֋Fu d8&c%A PJ:ަ9h:0Y%XhqC$1L ֹXENkZbrC]|zl9s!Rv]%j-^Ut7Eroq%yS51n-" 1 `M `|pѻt@ߵ3~҉QC[Ppb%K`% 6_ FsE%Ÿ /6!:j LE E 59sJȓ1Vfܗs^]{ZZ9XtBg0w| Vq3,(L55ϋR4jK\bߗQx-AlLži*SZ/V'I(<޴x'\BM3~]Myq.5z#(mwg;̎hE䅞Hs,rkK.25s6 ɵ>ϿmR{ ԱN$A`[0I8\VIX\˴_iO6߶t+m9:Rlk>A;3Qd8UQN$$B4xO&%QKQhTfg%k "IN13k\C/`gN U%ظ]#]|_:Т5(b”:)sWߛJ,OrE #IƱy4m&W'CD7 EIy2/%: { uLof_ -~>~c2mݲzm# fHDc]<}r*:~1]"HwWos`NhPZJY j~qL}=zSJchF>ͳzANN0",`@( xrػ5x~8 b}:'E>SdcmkJ10D7>8'PKA\J/4I$pkcs12/ValidPolicyMappingTest5EE.p12UT jц?;7AUxUi8ۉYDIIIRBB-ţA:SaZjnKvFKUmިmU-MBkUQ{Fc;w>9=v~D:l ^S4HTHtX桝JC`t BDL?FDBტb> htT"d"IBǶSf~Ә`?:8n+nxVs;\@JJYoAߐɯȐf&%@ܷvaK ;-,qB4 Hx̻hO{ ?'xhHov1v8 x3^*e2y%0xfGI"ڌMhJ]K~'>y}uy#KtQdz,h_zqԘ:$ ŗ-AlT~,)ۿ>ra=9H/eĎȒ&V|PG=XOםڪ\okQ+^G>m+ۈG2y֚.m\20r(JT{ t|tX]\xۤލIZ`_]hSAe9u!몛q4Ҕ *+/a Q^WV=ߖ@WoՂ6t^Nw8qgf^*rV eu:R6Bɷn$6_朘yo&b-=ΌYO:.kk_4&^L"<sBS9z{cρXqcycK#Ώ}-EqE,c:Ŷrᮂ,g[4`~Hq=ΈrsXܝ'Nذ>u ќlo]MG'+o. sk-DS%#n6r G˗OF]/kPo[ɥjܫa%zEC4 }Pv{p6$"0:EHJ/PvdN}XoHNg饋m7ښs ć{ F 6jV*ϹfL%m~Y.:0|iǞp,%)x6ʔk+lzP\wfXnJp Ҳ:kIWKC1Ҙ&2tn_G#T@׀P P{ Q&(vVlP62Xƺ8PKA\J/~2$pkcs12/ValidPolicyMappingTest6EE.p12UT jц?;7AUxUy8 s59nbv" 2Đ+Y8:\ Q,+Q0sR֕ʊ}=>~WP GA$&E RBt0{a^:qDzBbNk8H\_"jVĄ:Xx*Mxl 8׽1O䟸{:ث'dY{Hc~RяR&o{6X:78>ջ[R:{(Kˣ+2^F^ZR6uvK EKZ\hQ]v4nvF,`ѱv#S^7ȭظh0<==\}9 :w9:d`;{uD=)E!Bi4|7\1L[Q-KQd +Iڒ6finPF#N#\ek7])36&gΤl,W/"`>.ݐ5hv<"=% s0HsE_yѱfӻ7WG&B93ſnz 4zT:_uȷ9D[mƷMA %VQs̴k {ZDdt/ t6euTc.g($tk4k}*Թ sib3F Tcgۖ^5=v_]+Gm yC=i2mn]>3wNŽ3 2"cB̄S\Ln=;@ᒈyѤUZ k{y@ ==<(!G/qPEwO ޒ \ W:Kxżw#ԻpF|uQF Uqx,X\ 7Z,H$L@IZL7ğ( >&v)gΟ?ihl/:SR'䵫paZ~R;ݳٵd{g-FXTQЋ[nXр̴]mfҾG=bBkn Whe~Xg畧̸2NUu)z̆8kw6? z”WmM#YF?Z)jLwl ݤr3aԴ'8a9k&(f"7r>>sK,ښ剜W{9U%l%TIߜͱ‹^߮C鹚m,ć^`7VP,L3=,r,m͏CpbbNOt*B&4|ĀH& / EGw-|}#}BN._$7pvv@@zvx9+0P"^~yDS:QѢ:∝~"m|H{ lehf|bRJ+/DNۻ0kzFO뻮_90<=(Kedxm;-66iS竑R:p~RSTPgP;҂=QRR@~@8wz?CBZ(TNK$b 5qa(a0XH#Anqc)+!|c.娳ɿ p( (pL ͫZİϚ^Hq#NDOM.j=WL)韞YVo1#/צ5Qf>F1!~3p1t@E}:{n ~2%LZAƸ*ͮ˾bt;a4/ߩƦ\ ?ehEH\qYg U6(_&ʻhI-S,3"v}վwiO?6usYb)8|{~%$.cc%CxNbޝ#f#b#;rlH¼YXS ̓tkl6.{>ZSKd BV |b_N5ytѸWʙ{<%5FrD4wAU>8`E=Q7 W]pmL_/cݴ2jj}:}يJHGD^ٷ% ג h|82F <AIȺ 7ĭWqKgV$.i"tBv* tL~GҫerߌZTӷXDcOfb]6K_y(`AF/ˊ:/_Zϳզ96zHͶvu[rI"5߀ƭמy$I 8=.GʍœɗG{>UM8b[7|qբ r#_3^y*Su\'\1ʫgL`/Rܟ^gN*VMچge\{9LACէeT wy `X׶ۻ{c R)y[6Wa<P=lP2C;D8J+G6OVһĤ6][sjp7C;25D~uIpk4M3JN%3әksf?2/KUՈhk.~ZC(U!\YD>y 2S#,t%˕GYqhIvAyh,Δ4TyqFXxw4aSںt.E$.]\L 1Щ7X噑!W ֦%&K--`"2a@(  F #DCJA'M/F;s7 jjd\Ng[g)BKoiP33mI1 2\n\ʞxqEZY/wާ݌m3uFaNYEI%\8w *IM SzGufhjΌV6,FmG;m@zJ^Hz*PTonb $T!#ą7Nj=ʫfӑ7 ,P $#SLf7fiqo0"JN8`[,TVAwG/ uaJ<8nBdfQDkFOYst!R1:1;ȹx#-zmRys^DžSRmsJ*4KA/PX"vTKG6PI8>n7|S~tjS&(m'mf`z0 էJ.mkyV]m"& f>}\ۣJ;ÙvMtSŨuVv%I*;;)MHx@>7bzm̽WiLѩz(N45!'DwRupq?k`_8 CalEOʊ y?)C^*#D򛁻:/aFmq܁O{?bIsQ~9~XyYHb5|QrD 'PxֆnI^s<xJnf٤DFw܇RSտh#~΋kl!e4"H[z;*52f2+\r;oJn#>Au3iK #qﻲ[J8-jz1G9YápS 9?Ws ]j֨^ Gs{RF;>S(rP+j)2_1֬驄.}@7%8]'oY;0 F51牗1G$n/r+?\㿒 Pg޶V2;FtP2998UA`+-}B;j (70قYGMzYͷ8cUQ~=WҝmaeidWdRf]f@E|Qks2eXn\MRw\A*Ԑw7" t7.8=IBeטvw+gF|{>ntt 1'x0\6@^`=XuT̺ND񺌍ckw[xL`lFgq'nmNU^bc(Zr-"mŧƈqS^CduJci U̪#=Z5y.LHgyU|:\S06R'yNGNupyiLgMV9^qڢX! Uy7qg.,.ɦam46Ey^}X7\vv!>}`/(u^suw<6fiWz8˂%63qa)-~b䫐KA30+c#Y4g2ǪA+N5S,\g@;-Xj"=ee|#2vJ,+'y+ qT>̈/LZp'_aؾP1T2P ]eijŮ?邓zQ+5\WzED͹>dqQEO&^LhOH#rq&m 1̓iPw[#S-HuWQ\I"wIrEsdk(>槆6l+k-@eJq <9^yRhή%X0ʗ׸-˩ٟ%aLyPHcxm pw-Xb{lcO5QH);҄Bx~k z6LPS&bt9>eǹۤߏLg@TÎYKf4;*ɏOp0z]h؉Am%^눫B>Ut~(!|Yr.K&Q!ksq(Z~؝/e Z'Ie(mg8kk6 I,L]t\oۑֻ>,q?G˺D[oSd~U,9 DP~ߓ (ܵD8_8d&g{)3R N=cb/hdGZ@t m4ML >k+5kf[rgاQaɟ*# ;ώf%RNZ`rRX>_4 9B*(A 1%)$\ڠ2(8% d@h= ,aEdio6PK2\J/P=/,pkcs12/ValidrequireExplicitPolicyTest1EE.p12UT Pц?;7AUxUi8$4Jij)  EhK3ӫnE(wЪPAmTiJ-Qv-y{9sη;8 L8HA! x<ȀG8W ˀX o KqHPbf"LďA@8&G4vV--$5\%TT~~oUhJ ENPUhl+Eu W¹[zjSBEϏ/ݐ=U,$/Ii̢ϭXb"%_89,u: nLEߺ ko-5Ѽ$7"KdY"Z ɠ}®a*FH=:CM!`,IW100Z)v6_Br6Hs"EE+Sٛ+jbj(=ܥCٮo{ێaİpR%%43`dw_H#Zӈ}G2OO4FLd2K'I4-1y 'eq`.}?)RgOO-0?-#0ϋw 5M/VX/7C~t93%&X?ܵ) E\d0pRrKLOof&jvꅠo<T}K9|W[:R:7$ka6G%rT/!!3|P~H<&j^khxt’cm 冉 KW'sĔ%=)}O"fx#ۊC3%R_tG<7n˵ r bg-MҾ٥/t Lr0/{,DlʸS7FK< vSyNT2xաVgDlA:sktEޤMD/.iD㶑Z^>N>=蘹^b͙{!' ++kxFH>:ޙ|e\i";]Dݡa֌EZy^'"I=a4C"1?U֨4&e^[@1DkU) E.$߷~'K r8sX = [19Mi2ҢwAK[c'RɋLL^ӧž.:oq5ͽU= yNFklSM`\aB;>VP?$\C`ʼn{[or*{S>󹀈ϧ2c)*{Ύ&l\%VpxڏԙXg^M,\Ùuif4gZRcUw0;`3pB+_Q͓˹y+zBb2狶=`UnG!{a'偾Vdψ"5tǭ_җYӹ~%e8u2Y rva]+1-*=3ĊzA[[ .GaFLN"G -Cth(N5Y"Tl28*zSH:yp/%8Vjf;E9F䂚>|;7]R`SnMcgA3[yZM(9\G~=&z׹z/oJ;tT:mJxaO%mY3lK-uվ )U4NVÁ smLZH?'ᑡ5QM0׀<鿔wY8Q6yL!da͢)0WEQ s  h'ȴW5j|8f9R,0f4N]O! LT!!r=83WZf{w!yb3I5џnpN =S֓k Yvb!4~SgzB@ !Uڨ^\fO8G25VmڨXt]j߿h{{R%JRi}LsQONQ -ixU=ρcèyȺE즩1ɠOLY<>f.zbw P˂x1iMm<;tvFsZ%W3xɿEiY=MtE6ŹGթpp쳼ƨc-8, *X)ꈇx]3.>uPn5:ˣ! DB!#!G} *0 % 4XQZ$}*?ɟ[PK7\J/*",pkcs12/ValidrequireExplicitPolicyTest4EE.p12UT Zц?;7AUxUi8J[Z[ʄjTFkhG(NL5$JUck} `R˴)R2<Ͻwsw8&t1-P.Fa@3v) aQK స_ pšb9m3|g"!]7^h'0;*oJ,tNw"J2`XTVk 85)| ZrTa.r4HfYAz/m0эxdx?@qԄQߨ^;*DoEȧHZUlI}-ܙDf6nz-Z̫I,bIp<fqm>[qsC;ߗޔuQsgeU W!'.Ezqh 7L1C[PPb&qJT7OLPYRZ{X9 9=C~)DsJ-m_A/˟=eFl[H16U2 rQ),R6fHE( flVNk:Y|4BqtQј+i\ 534l>T3(x?C s&;GPMTT_ Iҡ*N,kB1L%yR'qG,v2Uu'EHͣC J:(ÙcMb)lt t |·um{/gV 8+!Xv̬: a"A(e>#i%ݱ5AL:MhU-!avJ ΍pR]^CDm8j,Ne #6UH&Ѿ.FߣnYEwOW |rE}ǖnߺ"DxI|T\4.>FBG hL .wP2:Vf#/68>dމ:Wjfgps s X+q҈cYLo[Vu`z!,ៜ=)WOh55Ε(k4*W3S9}G77nhf\A|;uuް/-i& l;Q5q@N5Mu:[&:Iёw>n.p!Q*ĊK_Zjh0E-UGKq w/Y,fs5*yܻ&AZ9[< :@ԹguEǫ+J,&Kd^I5Yh'E3V|pW&wnN\1(jk#L:KxsjVeLtr6p &fSܯRJt?y5e)l,ʼwtfT=z32!<86>?iǸѥxniY*bd1T! ˽8ehYh ;)z7(On(+'c4\SBCZYQ`za;xq-)À#^SHWFOuPʄ\B+J(2RZh,bJH-CY!G`dcޛ\\q`@HlH7mg&c^LY5O0''lПobQ[QXXBQp x6zֻ#Lpzv(q_i 뿣a Oef0FWA>PK\J/4>4pkcs12/ValidRFC3280OptionalAttributeTypesTest8EE.p12UT ц?;7AUxUy8g!ape='%dI!kd[f2BC X& ɱ$t{x{~2E!sA`܊&'\b2lBmb0 n{+&_[U ด_#g0|02)PХԅRTL|%TC wIs8H#Qp,F aYB:lu 2ٸv;v6Zap;=sґ\:}w4W,w< b^!@z]<kzE:"Lx.C;}XhhdD3ZtݼrmE%# z-PV;dYr(m͒CEJf[rU@Z(#ZepzhЫ2Y_z>IMV:6NMEQ!iGV[\7UYnxŒ q}( I\VG23"BF㲾,LvƞIL;Ԕ{la\peGB(x%c&nȸ+$m<,+Xì{$;'_vE|_x-ʑiew[qIKlu_vr~[(?Z ̔O3#$Xa]4v䍅fxq40rDcyTqF+#Կ-%g71ܽyY!gw;X`j0D|p1ni֝1M>A/`>l6[I_˹ -aWHfWOnˤemĺ8;lH MMhxCD{m+X1{[Ga6Rr+x-CKc\VZ8.kh擼x"F=b5I(=XAJu%m#Y7A M.oͦz b^aW($W^(42zmb7x$(pDy߹Ig(< )߆XZ!q- ;1nNy& ~Krja_H@j`~ le&Xԥ촯l9y]1rl}x`V[2Ӛ]$E+x Y~|fVƗ03~bGP B*NS e g`>BJJa)xpw(c10$@k!?Uz֟g:Tm:P7'PKb\J/%ɐ-pkcs12/ValidRFC822nameConstraintsTest21EE.p12UT ц?;7AUxUi8ۉJZӪɭҖLQjW!v[OQDEnMhmEl}KUZ<Ͻw|xs{dQM.A9R(8d( <{dVP:tf%؀!4 $yT"`iF\B%Cj PK'o f4"Bi@GSXR,uL4aj_۳Kí fo֎ $݅$;Pҭ=;mV:x-\ܼ_ݎ k2Xy@?2d )}RzU'?ЪMx@rx;_S'0lϾG؈knWi v\[1S-'6]DZ=tUȔx7O=Dʊc/ʜoyl0}.֒ާ{a^|YOJS-t¥gr,\ ˽,OKhR 3yn| VI˳{6TׅCƎvghlgo?,r[›:73QSl<,'޿SOTl ܱ(,SЄͩEoY=kZ epǘN#۳u}Ө҅ <)}<^^qY&W;ku$熰n<ճKv5Ȅ淇l}JrA>63-1NK3ګbI|fGӑWr&E$ܙxV ^!!xo(l;=ԙW9:fR SXUc{Xn[#fGo}>3)ggv5ggnN11Q\;ja 9 Ɇ2CͪEM頋cգoS S.}e2KKq`?2^fE)q=}_RT䀀4uu_Tc [(qIݻ'Uz`7cӕ)>Moq>5@D^ ?y%Nɠ Vo|b]ϟBȠȾn+tǕ զu0g&OD[ͼ*5.)fXu!50Ś1Y7\Ҷ;~n4S-7 8_kmn'Pj({g/;`QخA<~NWO)К*QS男)8|o\9"AȔG<0͔%D^?2Pڞf$ua?jz'zi2Zh@-oeFpG6ZReŀ*O[HCQcZd6Mbh0ka/ çZ2RĭGRX]>eut^Xͺ>D6OyY->w Åh^G~jL]Mm9>vi /;ZwQ4äF ˩ `9bRUsm'k9ڥ>s.j8OM_U|fDDδ/-D`!wȳNW4C!3?(t:#  w ހǙ\YVDK9<`(;6ҟ{b9fSR;uVQ5ۡ6_tL^TeОͱWپNhIm$8H6E=9>zq2z^֫%9Ь^XcW;Z\]Kڽk} S߲dVDɟ;ჸnC519cJg w&LI<D^arBʄpы +Rֻ7*U'^54MeK䪋2/!3)AZ+״ǭ?eY2Z"]ՙ9ZOw1|Nq7+q+~?Aћd%n^+J?K0"9ӡƹ64e>byPKdDlL_'i`ܽ ^۴>K9>ϖ{G[5e;lsp>Q)qHH,̶a"jq`қZ\nfBzh̚{~ bۀ˩Q^<^_UmAdM~l52p%e@1v Y_G,{LmBфKTA>u_f/5e̶GVx~S' ~#JY1oqy7%O{!rI 3D!YvW3Dd'&*W 5]}˛jCk }ӟ-(#N.B3Ȋ @+IFuxڒLML2?/j},cЗ P*YZ3{B6:6Q[1yiEΛ/$h[X%zq&=$| VYKϯ;M|c֏eH~nuYWqs||*V+6(.ZѦմ\)RWCh9` V*NXZGwrPzɢ7;uwP("'*  ;eqb͛(ʳHF2yPKd\J/ -pkcs12/ValidRFC822nameConstraintsTest25EE.p12UT ц?;7AUxUi8 f0kv 5f\dfc_*dX:+KFuZJdƮn!%L}~xs{A.AaXH9!WPybB EpBX[ +Cq \)r{*\ 51C.,.QwV(mXfFh/W-rVcǘ'o]Vu|lxtҟ.|BZ5MYN/t(䙧wvlmfL^2*Do/b},nf|Fb"&R\ tl"cO: aҩ'& *\Ϸ(r'g--~jc|km7e l$&,1M!슯h^Qs7٘X zԶ > TRgoRs6([G26+F̜)$l9%{HnF圯5 2Xhp9,lTb\VBHe@͎(E:^C`]P>e |wnݼT)_ّ6#$ϻK0iF_9;x7U.uvIg Gsu򎨝*% i&]!Cԗ>x_ߡ(hxwO_T" =`&nYc9Sk)EYr^/:[T}c!`/A=2qmM5`ܠBkPv' 㽸M}7qunGW1;dެS]VNS,Nx`ё!Y e|`1zI\`l⡸.5fֆU_с2O y E~\fn}(Ztq*!W&ivމ#e"=-6R\\ 0"IP< @\@H!`Pf%N0H[,;Y'A((3Pb+Vx?PK\J/2?pkcs12/ValidRolloverfromPrintableStringtoUTF8StringTest10EE.p12UT ц?;7AUxUy8ԋ[%$"el)#9ɒ,IKBk=2Еfp$d_bȠdy{} PxDL")ƃp<خCaIb<, B!$NN)#50Cv (@ y1F޹knσTsZE}Ѱ`uta{)u?*n@w[_oZfqK|sBsTz5t',ʵ*Ջ.VR *(hC+]yӐ];aۿؠѓ{Kf9 |ڍ:q%+Փiy&unljU!T{*$H`:L TW:/)<\T<%7{՞4{Yq3y&nhJ*q@.m s'$Yv͘lcW 7&R!P#s0%vŭ`l&/rAejƦmʋ]b%Fd4JԚỔPȿRR%H&7 ϱ<q:Aql08Γz#Kb| GPKT\J/Q1pkcs12/ValidSelfIssuedinhibitAnyPolicyTest7EE.p12UT ц?;7AUxUy4ۉǓ_A ZK[46kjj-R։+j*FEjM[msy{~,!X.唵%pgaWp6g0hx_5ñP B>QC΀B6&uU"*C0s5+H;3ŵ$<&6$cze]z4 fwNs2`>+ y>Z^ēhV0Lk|#0ؽ4sõ\,\i;Ym^,^7 Y+M,RPK01Ϊ:6[|kוCAgcK+oS?.W:{t]6ZŚ678fzӮ%P9Sհ7'r?rlFɽUH'g9є_ۣQ>Dumpyv!np*NٹXgrq_m.:'8  ~\Z,]j|BPѩXeSvo<ېa Ԋ^_cDΊ.6j {/:nFymvK4BT jFI._dTa@?I_^+"(oO ;YmYΓ0_K#HVp]V,?@6AT&mҕɤ9)i 10$JhMn2sӖ._Xe{2Bn:cT331N\3߶081\A`$EU(sFe ̴nB %i J]iˉ a$ '5HK*U6'&جzYO[.c.N{6Eq3/++k;}bo)Łx !uKy,B'eհ.!S *s6",4s#LݡNJ"W4H&uYZ<2=J̒H\2g.1uKod۬C 'W#ςW9-w;E OG1(64Tnnd`$bTJGH8D.DǗEۤg`OoG)Qb.9<7&LƎ ?W}LzjѴ{),`Dz]PLYj zYS}dWdYB-_uk2Fa@]rljwMH&hRhg:(녍0R"Lvc >R2Ā  Ń@!{z*{+ C59g Qkh4kUE2{PKU\J/1pkcs12/ValidSelfIssuedinhibitAnyPolicyTest9EE.p12UT ц?;7AUxUy<ԉǿs3# KX͹d\EmjgƬAFLƄc("$khshfСZ5rc|^|?D P'@$!&Dpw| g0a?XPSN_ 3!P4SHv@HMV,϶ -?/g=vϝ#ֵrXvO'm9_61[>n ؎5n(.Ip?4Xͭ Ԓ3W6W48fV2t,(dеg4'm.RtW`r*h=RMy|iwy&IS*Ӌt.x!mW%>m7"+zs6ƗF? zV qP 50+͸m0_)~|ƀaѰ8J)HTQi%w՘B%oYI]R]f?6_&Ǯ+E볈I]V/rWad/y$Z({zi\"k?7K89"g3=;p&NE?4*p\~N2bfՅʼ̩Wߦv^Nf׆*5o[ F 5=ڶ{EN^O-_ #3ed>̈Khn=Ic{KRogIq气;x~PSw؟+RϘ(ݳ* 'l*"MJD w|VT^wĪNMÈhrAI̵gFe1({u8(壭SY48GOvPFݿ_YEfyfnBvuz܋ .8J]:kv-[3f!{fHUӓoSݷЁm{gXLks9C0 hІD%8zJ]6O ȼѣ1٩|wdeK1c>X?Ug\;x=c%Ju |8Om6jcrHw9pck(829?/>AwmlϖKN3wOdS{}o_bt@zׁ YoNl$'nԻ BBTM̫[ 9<[BҹJ96ʇ}X^7>- ph.mI S{BaDoϙ@~33q^V6Ɵ/e[_zDSF[E4iy{F#ln6}Ij6 (h !IM A`0A]eG~@5@IcI\ a0a0 ) h "un@)$|n,WGC6 onhڳmBL (Xc ׆d"ŽS9Ģ|VAV/I:c <'(G]Q;+C`yt.E&=ΤMOVѽWtN/S\IEݡ{E'7VFªr햔ۥP~R]mZtR6P]IrvZ̭VqJU&2 6|fCP˿5t<9 `Y٨5oԽ2ҧGV%:qױ*LeG8$Q0P A@Ic[XB0Hc$ x !P8 BI@J*մ;1f|;IOYk;k}{O>mg^~DݨyWZ@)l ovͩ{vN` ޕɞ[nF=F~]liXtoiF6U\UQm>HMW oi?VhM}BG>`c*%Iġw&'>°.J7|Vw Z/4N1c1?k*VifDu!QnE=S. UuzG1zIj4IN*`:: *c-V1; nE,g=TsaS?aam)ޛ?c:ܧLW`aykO{{&YN޹XRWMY_Tn?}nS$85KUf/v*.8(P5϶U qG'sThN5~f7e|%jEyGtpb0ii Z9īӗ3Xwf\Rl3<)yo:&&m9'^ m@pv a~Q ]g}u[R+b{+=֝R 0tO E]@jQ2P)ob{Ik? 6ۄY][{Y5&\MnsC{bJa|[E]$z@# j0"*}RDnTar Z2U``t'j+_ mÂ{WD3w$/!0D{6ci~w.ҁ V4NNYV且o,n~<桛r<qp) ߫݊Y>09sLM!RjaP]S!}<5%LɎoy=QjY'Fj \Le^mTC-#%Cg<wQ|&QzTxV}:XYh38\A+x8ljT>0 /K5w5'KՋo힞1 %jHG4^nN8xOs16؇E皡ˣf#ON= -5.f^oW[0h=i>:3֢^i9LTtS v쮀iVĬZ0VY3:؋i4 _wz7;f-! {[ LCiCeݞ[H(hRt͠o^op1 'M=QV0ݻ@_ywu2ߵ祦7Ũ`Ё`1ʨg*I+-j?C nslY*yo2K,|-vx Lm  F}I39?!969y,3ݟ)}[#< gFD Y@e:KėL cVEqA5SD]&_JXe1s3W+h851jj@,\Pҁ?S(D\W :*3l-m`\$7>]PK!\J/Y3pkcs12/ValidSelfIssuedpathLenConstraintTest17EE.p12UT .ц?;7AUxUy4# %D2*5KT--)Io-(QZ˘XX%*j]3߹~~Y 0 v]1!&̀O1 P_+9<!"AT 9~ P@gPO!hSX*%5-m'64ql o{_Yja^LJFŃ=;rʇ[||ڣlK,%6?qa΄kH6rD3> w:m:\cC5;*[E%wQZBd8y"^2~궛TZr|Px*7M$!\vcA>ߧ8{EoYV܌h5m7fX%T l&;-O-hviDrKzJqy.s{Gޜ iyfhk1~%^mRM`@x̕|vp#o͘X,5xG^'5v}H p,#NU.R>SFꉪ a6PU &ѐ !-븁NhØ#|9w*v^}4Ú++{iXJNEQֶpƌʑ)(? jO; L)gXq8Gnd:c7}! " u(!ނf'A)<ߍBQX+T {w#p/_ ѻO$77A`HĖ8 /fP 0FO>0ڔKfp ΌL,noG1 :yߘ$Z^>2[vNɢS k )thʪ]t3ڴ(|qjxB\A8[IVYKR;E#_rD.%zkuvtK<;J?Ъ 7tyj9GN#7KDVu,gqv7EjDKffėo US]jWrf!f/ipsb iClWRr*Z1,=9s1>fo2]24ק9M*BnX2YىH Hwu(2?Sj^* \ipn~fwPqg<#2& J{bWw@eKDs tN,MM9;IjZ~ԟtT )oxͶUٻ؍n\Xu: NH1^22RxչӆZ!x]a67Sx뽾/*)IxD~BinyI=-iPy/*Mw8o`G1MfwHʗT3p}5QW 2`յ6|l uQ/ uX}3WK6ap6;Z5š8؂9s~ނҕqyR/g52.Qr:jڭN vtNr4OH_-DQ|Fd:X5\fIOK)Nd,8`Xzkv}jOI3VvOlp Pͷf9xf5XhcDv4p4Kt?D})M,ۄ UNiTuf(mշuKA{Gi8J+[}=UYh-Bwn,[WoHT #Z=E&A RMƬyƠf{QSB{^H}%P2uk-=yWIu{RQ@-!oLYjB6] kz?(OyΑyNM̀@QLB7,]zpɋjo6ϕuwb)HQnOC\#4 )3A^.L3[͙A|C=LqP=rkӟěcVyj|L^xMCjU$眇d G$oM[jCw(df6 q';aY0[J_/TBLh3K)zQjFٝ= ʰ9JX'XQp/GUD*BcKSf[Ox$T$SRa[&ޙQ9+קI ZCoӒ=V[Z; h>:s]dߑ֚ p3>:X/ooHxg|U"Hwe=w}(Y`(Ls!X _4ANB\Ýjv%d 5u I TD?'*:s͒Ia8kɋ{u`qDVa$0Fl{ Jt FPV8nb Kb};:i؍\äT9E7*e4FurlMJ&KkHCX:||di*X֫짫!o-qvR;冄OVVosW456B|W#(;mft7t#=~xTb9hFJӕݴD؂MThEZYfP`RA)Q(*e93[ZqPOj77~};$vBWYKrTIW1xW^ɾ(m{eZ:Sm_| %=9 !QF 1?XɘaoIlͧOJٟ`K}f>z׈_͑"䂟mubRK9|7/mRޔqҩuFd.$Ff#j$eB47;;gGh6o㸍{dc+]u_ `G{tR,6U((JH p8{J ]ౘb`.T"6f]g8qHأO%fPK\J/EXQ=pkcs12/ValidUnknownNotCriticalCertificateExtensionTest1EE.p12UT ц?;7AUxUy8ԋg3XSֱeߗ/H%di,Sc\reF3%ƒarmcKe}R(L?Tx}Dl x1C!/ GyГ2QxgWQR+CHec'~uP\^wէvy? #1OF>ۏR -6-66ΤN"Fjț#)?kMoGaX͇saxU6>L%{ID`Xf,,V@CUT5?^'ȇDžW)c_0r$`%#t#Tϋ:j9E7YnœNMñrrv1cQG-!?AR79gw} &d"I8!vp}]xhsQ?[qvI"wt.+~n{VOxk n?|L킫+-lt{5 1ܸws!!pqb,|{ I?zzg}m><k\ ~ vC@P#lq&_Hߵ5jy1Ղo+?4t0LլBI6YilQqyLMA [O#yP,^'>ρa -kvYx<y ۢŀ*7/00 C< `CNzPYL0@ zU6~w%讍my?+OPKi\J/4Â]&*pkcs12/ValidURInameConstraintsTest34EE.p12UT ц?;7AUxUwXƿ $,)[`R4<,*" WҲF |(K@"4LD* SA°Lh 2.}{ooxs{AP "@ciWh< DLA=a ~h=BÒ! `Fģ)GP! ۜÆPij9B_c ]@xJF$)_(EvtW"%|d \ۧ݁J|Xz&<}!i[U;i-wL[zVWoê\Uռ^M͛U{[`iנ> e)LEl'U[kXxJ6)t%E&'uϴETA1[^v[,C3ܔack`^nc Z 7 ob*MO&m䥲We[*(_~M% n\0 qL6|*szmr%y(#z1<7Th\m=hQt}S3.vi╮r)!ݍ%x R1+Dσ$uxjAF8vR&y_=H_W90PNJư f29S LȎ(݁bQq'8K&ӞA ԽvJ%J_ꨦEPEcZS[=aA}P(x"!ZP ڪNd,/j 4aVyyVкv';S9Oq}|t:N}VyEz<211f몞RD`׎Hۥ&7Wilsjo闖;_]`h}v޼c^'(;K$e?e&"GS͜\"znQc^0_T\ǶNo#9@MdONV{O`ԃz̧+I/2t;$В"!V^06.+TYK78uA¶:tO{g[ݚqHXy H2v{)[LW4jg?{ncfzuK8׉m 0iE*BΜZ6l-Uk轚mlV \BJ'KGcHF4ڟ_J^#[OPJf+4U4RE;Iމz.AU o>j HJSIIey(wkU( *'] ct kF) X.'ʿPKj\J/&*pkcs12/ValidURInameConstraintsTest36EE.p12UT ц?;7AUxUy8s[7 "&-㨪*BQ]TTɸRZG-W\ Lju%ZW<;;}}?$_# v]WQ ?J~S;$LsV8-/D@3H1t `?Y;&Gե ι\'֌~*bTޜmE<pY̠_zqXP!M%Lsu痪֋ן>ߎ/_$z95OY_6k\4"s5ZF?S8ڗ9ԥڪp^I;FrMHܝٰxҴ^w):v}$nDߢ|E˽˺1V-B_Kz<&RzkΎx@Ib{B2 j[q?DhcJ Ĺ=D 7n[^''-jVwi bǬvMU^s-D!Q`P D~TX"XkpJj;ː"(vtRĖDYuy2Ø| m-_(>$RZZI1C첞\)f{] F*T a:KtKA'܂^1ٱ.ThҾ&l+IЛ7ݝ,(9qFB-x}w?Cyꉛ߄;4)*$ݱofO?ŷ^b ^Hg.63>!X焹EZ e=.fJUFr>R,]V].MV| (iF(@NqyG[XM?+;>*O~]7*ZU/U]AZ+: (-e$z;8Z(| `/#XxX|nyMZ_(l5):dp_oRV8Q(Jt须vpsSs}>hK9ֲoDyz`T@c D5_,#Zj}0ש3:5.Cɫ+ypE3q19M.u*= kW@VLPy'4V yOfS%#1J5AbN,, GXp9ߖ-6/NYSa[i3rI}fH1._ߥסuk0оmJVɭQ5I^;+:Q^Z҆2E]"Le)F x ޺:aڱf2TW NY&iB.E+hIk1VlL?AQWcsxKdA|:,mn-b پ&5v1'4?߻G:YhYt5C-1h{Y~MRW#mn.]snHX>,G&! K7ngӈӢmM z;X4`-dPDh4=>[@pg#/?=2-_F_Y.mkFW{\f9RDPD~jXP]὜\f۩S Zu×-9xɋFy8qj Z$ڣσB23܉KZ|kRW6kJb?웜\*`7/p@wBqEaEGxCwfݖJcLbޚ/Ot@ڲ5tX6i1)KB$N󘝣"?cA0oN2M1v(YAh [8S] YH31,Zy"hPD37f<*R[&z+4K)] }i'? ^!} ^q`kEF];?G:EKc1׵?D8w!L̡-y($ _@PTc8@b^ /*!LP\4 :4f*(w¨SQn_DfY9 ĸ-G6Q]MY_rT\jv4:+=?-/u٥dGS\dlOFr)3ʖtYқ#ׄ:=>ES!@ tTNځ|ZAT(8(?_g%bZ7ẃ@1@2jtZXd~\aLhkx>޼ !Jڴ)Sp(zӢi#Xg1)UDuzw:Xj\i#C$?O:PkW5u ;xN-]1ڧA.Ki ]L~JQ?DnE{Bt:0yktRҢ_e3[{c~teu;כi-%e%յWQ6}Jw}[7{zq(#t_V1j38%B2+^p旲YxG|S+- 5D*P̄STi'U__#6`qgH/:'j^͌v^? 'r< bo!\شcM| #ɨSX'oza[=l A^gR՝E?bYRżjج1~~&1zn!ۻEvffcg a͔aN'XI];|/HV-lJm͸e-X;%A^%6]e1O { *2NEņbzjyaᆳ }Su@:7@`*H>t ?+NFOڞ='m`*0eZϚ*|_y:^DsZPgRR_&\<I=! N;5rԉ/vO 1p`! )xҤ{}Vdyk__S r8H:O }ΓAgwqQ=l"<4$:$X.AQ`RQ y#/'B`0`_xe7~hif8I+q1-abyRbЯS-P[UHgB/6 s*5z9.=YF#7f!6-o_xcc.Awyħ ⓘ8FNxLo5뗘Ncnmۃ!>}`Z,R(07 -K>kΫЈ_OGRV*#?sgĺWo y΃߻WqdMyLsfX~ݗ}q 7Gmފm@=,~5-X[ACW:qsn2$c-~GS-^BL3iqi4y\\UKĘ,-ͳfҌIKr2>]@kaF `8N=ʩ7]l6HHCC ( 8' G0$" efݴp0i`q0ɾuuPK\J/|϶[pkcs12/WrongCRLCACert.p12UT І?;7AUxUy8ԋKƃk"~I%d6q0Fz1ΔqSAC{&Ec Y{}CwA Fg:fn2*<J'* 9qhAaF . c$BrqG8`@B7nm^ *y)h˫ק5]׼?[Kg^ckwŭNj:ܿ|cdE2瘚+^)> :!(]=ۣ2=2*3e݋HwjQoK;ҵKd&p-dPd{~!2v]Br)[e)s9a{(AC[Pp#Q1Tpߨ|bTA`J|Jˊ OQ7NDf9@f@`,ӿpՙIB<_U.H^˷N6]q~eУD^=X){L4iN>D?nY{3F;ϋ)~*4n~'kTFܯW-\,PGG-XZ6seyM%O'3O >V4(X7=KÜ&jŌ=M2)pyvbféC#|b,\IYTfVkc+5h)tRn_#F0?鉶e((9:ё\&ZIQb8"t؇bt10pHҏE \l}l5`طTPK aJ/w@OUpkcs12/DSACACert.p12UT ن?;7AUxUy< 3rI\4r<i$bnr~XN%E{̅t\T"{ذ_ 9<YbVYd>tc ^ aI)bj}"&V(]z:x*׵CxTVu>.[}@i@0Oay785!X pp^iؼZyq Vnzl, >\ptیǣO4ϻ)_3<+'T?3en޲$ y9jbױrdᙼ<݊V.BʽkT ׈jb&U-cbN=rogg ~Z,ɲ+7"dfH;=xm/j8IJ*0<%5%,ZV%Ċs e h.U~X+2XHh~>qj2 0ۇoD|kU~8B0n#*ICwkݓs^M6*+'nrv#R/?6sW #d5t2ߍcʧə9^1zE~Hcb']jt Kas$"' ZS-乙C|=L1&v2[jTjaZh\p%%iATpYH>'"Rk)hY+g!_i9R43ѱzJYtf%dzpǂ"vAb!aVMВncY"Yap o7|;m.Ԫz'.2&9ܨ6jK|fm6P0d=NLjJVХ)[wctMinLYdn~=Yd 6.kXy-~5~&NK] Z_"AH/6A}?]*MAa:b؆=ϥ4 ґX;=o'wPi[Vv~+z{}ZɯOL)`'gv=N/VowDڪĔ])lW(Vc~5O'|wz.^.l{t/'x[\Wc d|:+sq_,UPkLF9|V,#rј)`E*er>9lm|Qk옧8BȺE|$JD0bٚswK0D%QCE|ȝ}Ko$z\e ;$ ",/S_b(aBOSQ?g8  PK aJ/'pkcs12/DSAParametersInheritedCACert.p12UT ن?;7AUx3hbylIJSͣ;/#;&,M,S #41m abdRK4ȰqA9i]qɯZy;)w v+S0Op!C@Ԃi&B7El8|߿m3yŻOI;^e`xˠ$Jfĸ ( ױqÒ-#P (XAyE@=ǠΥ.-*b/fE~|6)Mtz˞}a Gx>1xLSWo? qrWۯE Ʀ^*10>yuԅS^]l8'7Nw12G+b.q\ǿ:RJuȋAq*p`MG~vأZmp)crKu}%;B\󦝛zǕi|m*.|p׿B_>2CKsUs|CFșߖNHfիg#:w{bWVk/}2"鶲ƻh?4T5P;K-=wږAŭnECEN6Vm>f&)Vo\E⭎ʫ[N~##wXAPK aJ/A%pkcs12/InvalidDSASignatureTest6EE.p12UT ن?;7AUxUi4 4[2Z%F) EԒIcj%Җ֖F#AZZFCKlhG%=Lzμ{=燦A 4 s>(`B~-4W54A ҡ!4*PAJYll9& C_ Nr{%,a-a Ԭ҂eOŴ,yy䁖59A-@ܼn3O2[A 5Oc@8/ٟk`"Ё;nRsd  ټ{G#x+ZޠCw.D-*줳sݭgHSw2AfƲVƯ<4戥呀!; !7NQn٪xeO62$!6%ov3?,)G#2d^oHٖcPiצ<  kJ ExCA{Km.!MAz"WTVZUɸv'E"ZcHp~')pDZ}\q2gT}u2pNٝƁ0'MI艽;b-+]좏 31r6pf=6gӡbE>Z|>.ɮd4;vyO%;ǫ _Vq@Vrwʬrb)&j"sxy_=%"~TZ}sJnń+`Ap$ؖ9{&Pk]Mm홴|mwI~Ǖ#T w9oۡ.GVXX`~knsG}ϵJk?_TX2j.{{}*<si.:DPe2.K 9qQVJXZ!`/Uvq _iDeFmroU ]ZL2Jp̱M;Bxhz)k4V+Z04h@9HM!څOݎ T>SC'`.$-\1~+bwAo:.b^*y>]^,,wv+O‚DDWz.- &fr}@gWv#W=ᇶrG\䞴/Vw7۪Q+Jq+^(hPL]cys(K>^X\ K-\!A39D쉬LnMУbPiJHZwQ3'OzuruF#|6;+pP'9qLHǧ66ތfAh:*Pg+w%KÃL &qe4B1}iqVǂLcz\KQb[Ԉ;PK aJ/j.pkcs12/ValidDSAParameterInheritanceTest5EE.p12UT ن?;7AUxUy @")M<&!p f YD#( T@ cD!H4UBRhA@ Brv $LvbT>Gw3V=r c:=Y VK̭;=9B8f. VlԚp{+("䞠w: <]QD4FָUMn,{E|"D]YU{05˰)ptm5'C+mFJ)DHL({ۿ%Y~`k'ިuc;KƖ i N֪X#.ONS/$fPW 8 I-ꎄO?7FM~8Relȅ$LWH?`յٞCc丫 01*'"ʺvEJC-|\(0ݎtMZ;5czm+j]cXx/M"#dA;aȓSR}{kqitL j$ 9a7P,sL_X;ૠ0(ijk HPY}Px]?| *6">/lw [`rBy۰$#1TxN’8f?{So v VdCs= sغ*h[\g\}Iz^ͪ"OԕcWp`_VG,Dͳdi^̥+&:sId0*8LSL~8*7jOgrBoԪב쵦^ ( ݓE;O&cH#]u,_/%Dϣb&U o;WYӑ?& 1D&r GdH"Z PF"یg'o>j_79[#諔DEiiXIłŊhDGIkP-]ųq}Zi \&sQ㟧eɗLz=bP҈ Tf6):4֑ŬF%mTmX+ߚ:D @<?xpQ.|Q|S̃N8?Du@%P`P9G;YO"T,_L r r/_PK aJ/M&|$pkcs12/ValidDSASignaturesTest4EE.p12UT ن?;7AUxUy4ƿDbWb헫FUT&cL[5A(!u&!2eВ6ܑTuhPKZ[t AQ%b,7s;9_9?`B!* Pc`5!HH#\H!0Jh@gр @-@^I9y U*S[Νs~pqmm0waZ|ot!C:߿. 6m4ٮw;rzK2&g.䡖S׼z=>;ЖH,Kp}F>J~6*ꀫvٺ7 wX{󱍂j CdOC؋6{"P4wvGOw~MVV/aE3U?V1۔͌|a`y}`_hdck-:ڿXoZbo:y{|iď+byD'ib"KwhU$EVNϗؑWPgSyY1-Gu\<jYN +dI NPY W tˆ_^i"8TzڡƧ`pzoƙ77&M\%ᢳ6כ~i|Xü)eyfW9\8bgxݳ.sssW99~^h3vx7?D+l׀d7h$:%k.s<늤$.Jpq'ix7R/Z~^-ϖP C~rV Uf_hMCi)NOP\ZT 1HauoË=7:H:spg|9Hu_(ڇ*92<ηV82qF\Mnm{s`|&Evn^-5rtMÇY7-4b${x*l5ZaF'ݱS5zu T96)p|Kxk Su'{[}^w]ojOIPp. V0>^Q r&G{XT1.ZQ )F :MN(l;Z^ :0{o=y bjsQX=$V/qYqʵƶt^aa.(uգr]:cVX(R!D[ͨB{=ۚj?swELHq (#`Mb߬K7E2]8G/kX?(9wdYe7bd:R0IE jՔ$XU(>rRQA\*_ B&Y!;U_;@Td'XDJG{!P&axA~ 3sQ;! tT =7{4ٮ]ٺ+ל)ĺ#x4jqɞrZm9ʆyݜFxP|ܨPLqR2hS e(xi6BNXm xG 7T% |P"fXu @aQp{9ZVFE:}hP}qJ4cv-aBrlf1~ Ll(OZ_Q>U ?@Uנ! bq ax(Rh1|u8<{F(߰bl^5y Vve΁U$glk p6y)5 Fv^i#_wgyu;3,wy&T` ]@Blssx}삾\uI*^(m-a}l|8`L#*D_cRG, D>!p$ *_Fl.T~MʰӛboSbxөm3=M=4j!7z0<3xa7۞h6dDÚUX)7Gԓ-*Y*BF&AK_lגg/c_c%\2҇TG>vEL&U+om%딧Xj_LJgM[jֵŶvǣ6U޻oB5Jmȼ&_xݬ!vgZU /˹mؤFUEZ JOtH#%z )3dur]tzljLc;23 }8^46̿ƣ_N!9Mя}XVeYԆ[kΔ u֮r~'3Nq,^r"E|>Ĭ\&-/DoYsTݮ5R$Xx <]~-Pr9tU~Qnhlud f)PK\J/jff .smime/SignedAllCertificatesNoPoliciesTest2.emlUT  ҆?;7AUxVkHFvw7x R C 뷼w{tĈ$Ie9'Pķ6+9XiU[]ߺ>ՏD۬(x8f(fgZ=;E/26\cXWYǏ[قa7Hr9[,ޖIM'\]ux_g)^oM/eZf>nSTїo?*Ķͦ!ͯK|"Taz~]m6޷:?LJl6E9뀲pYמ Z_ KJYK:̃KڣcCf4Wy*m{"^? >W@ZV>hcVsLbeZ_[M7;͹rse [35 gcn "(i!yؤ*tIH녕 KIg1L}֨|ML{XGbNc?\ݬ}I^\,U/25x̐Ӄ?P':L%'"]WPjdhM'C}<#(Ga$1|%$q-31@jVb@>ά=0$](j*nhky{B,]/_/|#_Hhxrf=#ꤳS18h9,ՄxNI|Q.Z=mW6Xsw6sN*Zl֬<}B+B0hwX ]Fp:k {^ϕ#?Ӊռ.ItlI']%?|Κt"\}%u\~bb^"(Tlߔ舟,<ˢ,$sIh0pޞn:V/yc_cV'8_x^nW.Aݥ_GM|Ytj_صMw_ > 2KedYl_o mg,,;k f+,l ✇Q;R9VŢB]-<26Z0efwNopAK;xx.=N'~ڄ8/k.]-qSW@){Aư(y8Ҕ1.,܃A_ \W!Vh?jvZNGiB*t4VcZ5ƢWv+ʖPjal>qxޓ׃q;{kipHvqnnne'$ NV^̎z:Ymr;iQڶ=d6Xf27GWGu%H_x74+ /Jf?Tۆ/_5G ק3 t:Ҏh:~pbFXŭ,I~wGZֈh@y똢+_oBn*v6 OB`unOYbx{ 0 sې2R!F$.Y,rHq/E}c!DBqH*!jFWe za1B/u"7a FXNw)TݱZ~3Xy  ',aag}tp/f:+:t;Z JKnRtz!Mv )K`9 \a_wFʔZO5EI8c>ie9)*aǮ[b|5c]%Fˁ*szi[A.o\!U#sDT@I,dkW# W_MD3{aPK\J/}Ġ. 1smime/SignedAllCertificatesSamePoliciesTest13.emlUT ҆?;7AUxYHǟmY8==1Uj  &,~JOts[0,$2$#MR3'b:ˏYIE6l ST>.YOà,ߝ<, OWt¦}E$:hrE?Q[?N8|LHbv E$?hcI̦,Z7}WU8Eu ͷ<ßg[m~i/.^<>SɿW{Es o|>fׄL&i߻鵭9^yvMׁdywݾt(@ E#˲*߳:`d\X1ea~gK = - 5s22/ 6CqP(م#ڶG."gԊZ+`jc`bn* <#8TL+=Esc.FPYM,إGNLe]H>dՎSφ :D@<kSH1!(75_T.b{lG9b]o9^X\)}Z8P>p *r7XUV y6|3q1LsYnPȵq:?~,,sУE*w=sC$;Pp:6peu$X"aW+sƇ۹@jhVQ9[nL;\%{3ísU><]&G2;sݰX݋@8U݋㰸@WN٧bGVnJNV5b/6i]䩝FFPcN!Nǻ aI uJLT^<zn!|Uu<\t*:=vNdsV<!{Y wp28H.iŷ*KplO{6W|7,P`tǷDd:8H`l'Εrȸ;bX z('HS#SCjֻx?osnz--޻l)l6 <sF%nc9ؔrx}w`>S%9/7(j+F4~SO/G>o+=T}dY0@( Dpis:S H(m<tjXFkXF b,(o!2 ^0ۑf_ [ LBdw,4]p*caqwMXq7: e5֐ 4<6k%!kk*j_yd}z=5ogF`"jsCYD5>tՆWmP,Y'!r:z OV#ՂPg"ժ 0=Mz2m>mx OCA? ko?>@NA(| kol󽵩Yaյ>>BÅz8(@`:}ʲV{Ld [d0aKR~/ˢ =ڜQ$[;qr$5s F_{Cڳ#} 3u]{pm. r,ulLȻo0opȩڏ5I_d}Y'bfqX(9oWRW3ٌCtm oo5HA҆hs+sqUW3-GwH'[[!_-FIdv{ԕ}Xiخv:nZߘ?=J}(5>5a*ھ\+\Ãm}ZJ0N0g= >vfG?iHnumK6da7BŇF&\(X-zuu/j@,֥I-,qEJVwÿp:C}Sw_x O/݋`KԒHłjmZJF5WZjvzjMMP}<Á]}\6otsR=*OL1HfzdEe96lG+/a3TQR_sRѧ(h_p?nAٜ'TUt./cijLsSW͹}2h L :t}]XVWꠥPF(Ut̰%IY lĹ Lab:: 4ci]%N#iAʲ>fMiz\bnkl؃'|}nK &~QRnV'۷`{IB>/{.'zz; ^@Q$Q `Ʒޠ%4hE`%ŝ& Ae5Fb3R"zc9e0dD"HϮ!b86lt[>c(qٟ-L}|\xaؖ`&kz9+ WŒFb8Hu,lUbޱ}hE?wd4+br'Eo~;L6_,樀⠮^ڮ)'T]V֭= <92,Tj7 cvݙۗ*1˝}XRz-z(V.D%4"&Ae9+!=7*~FʷP9jh)p88 ."cwecLoѸun70>9z%QZF*ajRpq'HUȯx GmT|Pxe8ط3޳}Г41/W#|X]_Li ?]Q!>E!Ҫ}] $n XE' 4> wmlVDoQ|yX3Oy#Cv'dx=e?ei5ǀzLɡYgc Cs%!rmr8ɣٕJlݹz5Dfv䩓eU[<7]u"ᠽll%rd&v^kgt&z ֎ K/KyF==髲|7h20&8Z)2hϏ&z5*b5@5ho־*OCeh^ R0 ߪҀaPk_;hs^`{Cp) ?Eme汗TZMeA.|^~ۯj"2 3.,sa< fUKȨ''j߆)])yR7.6"V9Iv(X+#f鱭*[#dwMkҫZQO]$a:E<A+;',> <zuh?Uױૢ $ YVKlZQ..;>"}`LσPMZ cP$MUToZܞ*ÖW !84-z> q;gc ^1bu6:vkx?]>|n<~Da[bGmSK,)#3rO,{tS< NO3vq+WgG$w$}q*3ZXY[L(GM`h zjiޗ:A;@0QgDJ.8EI?gUunh]pt )>y}.6CwXy'u)s;Q@yZdIpmxIJP0?;i$yHwNpN $@F@ݱ^- cV' NU#:cdvawm+;wu ,{5`]Fh25*g5/j *n fg-Ā.O: Gz,-D"Nx2 n^pewN H0fg)G|{s@hxY#Fy` w{J+ߒ `̳pL!W\6) A @H=\ă;GcH]=SđRҙ$IH6˦R\l<]S㍧D>NNmGeo[C'i:b{]7[w,3m\ƕWWq&A-Xn` ~cl ',&6y,vR02T |ιH8?@6۟`l֯aʼU0FyN4H:jՆx0O|Z-d6RQxB2He0󟼍 zaZmU`!Ic]g]507T8'ꢫBhjCbr}F>%҅n5mu?QnW\I݈= :jm ;z? yLVv[{d\R0BL=e[Lf^&  # 8B7L݂`5u2Z=/!M's|$薫|AEUml6S|$jwO ,Dts! L2g`oete4Zhl^kUz$Ήݵ>hVZ9󋼜N֙S~΢C>{宖d4ue}N9palp]"SbGtW˷ ى$&_^ύ,hpqgJՑo_E8ٟa7ɻċpM;YRr<9_m-.[J"KHf(nE"w=\o4*ɯv'6AR_hmg17F 8kelNP-!93RV9\\k#ƛMi&kvNd8[AaPiM@'•QxRlmjid( a`7^CLwO!o5c[G}wAE>|B'9{MEs#OGȝmcNҺڐGa8.oAحt2q%$=堺C([mwHu۸&t3jݖZx) yzYw:o_2$՗Κ%M陮2J"15mUj]yZu`bENHE!uTH"XTr]ʵqnj}]pv>jӨ$Y\< vxph)Q:j޸nv\yԖHҚnN&魵ɤ%m)N%Oc('ZYe]ey=zu”W w,"a87W_셍XcukӃ=?S5AozAr@D E|Gj%8i  g(H YAY/]v97DvK0;q@]UW7UuFh'p"UU!T3Y(5}$Os֧ݘgS3A0H+eqbu\6[~rD`-e/!#vIU1Go`Kc}*:Izw.rH oރ{n( r˴ NlЧkkoV,dw#M~fd]Nk#AݢH萜Azʔe+'ł67%p;.nyeTs" [嬫"uOٻ̈́>EsQCnoxxgU0y4W' hPlG.5*95&Ou$Jn6[U93gl4͝Ȼ9+}H).bbF1֤~]Zn.&t;Z)g>LJ[x텊NE9š?.ڡZq0Ŀk;}O,eK?WwVP:-1-i%(Ht!b1 0\t\s~ PPt.ibTLZ|txޙ=A=ƅ?&OI9̀d0uXD㮬Pl3ϳegΒ&|@jXZ\\gzϧH 3'r̎sk{PK\J/l,'smime/SignedDifferentPoliciesTest12.emlUT ҆?;7AUxW[ӢH}^#^ov7rAn ٝ0 *3L/NܴiU~LxdU&:.n(nF5TǤcy 8>&|z: 5Wyq;pܶAQ?9M9 7_O ~L&&ZMOhcN,ɔ"x#G|5:݅85/Q~)"eҾ~tDm1_ƣAAd5[|g ʖ\PF1-Ij uզ;Aѹ _&4zl oA9#LB. 2LO02?JBd$aiawJ8uJbfm3sT:Ohͤ^YRwIxt(vn>R0JEQN^_߄Oߥ)v1yE<c߈?" !Pr}U0Lyy"Agh[gR|5 A8OlD/junX[ePy{NH/=\ca%>a+ }TJ<*Px{nOa{{\䎯x"JySݯm$Q*L.%=_1@S_P Mڹ=]aJwN%Ev-I9U` 3aɢ>x7R왌jio2}u()XeOiɓBN˲캤xEHbkٜ(z@mtҠH LzvEX:hm,ŢxU7y5}AT$`Vj^fѡϣPm$`8u{R6 @àP$9Y?#?oP#,+m9Lչ}a=}21BC߯)ɵ2qvlPNB&_^KQNC$RSrUQ~,/E#ev<#4F (ScWi[ %Pb@IȼJy]P&rP`;~]f~,[d(ՊXLQe=?h<, >mv޹UlV±+q;o](n5T٧|w ܗ^{2׾o `!2XFkW],؄=hbl]hs]*u]F| IL<8} ZlAnטyެ2p|k AL:>yntyB“aft灿\ރ'ؿO00'N!bk⋧$?+#yÙ˃Zt3.% *,ʾmƣKQXe={,Nlq/@tbgVPя5+ 5Q- ʻF.*d X,DŽY=껒-Хd'W{0kiʸ^-3bPuOW ]W69&uVQ5\s`WS+q5Y/as?b8:#o2u4qtrj3/mrg„ElM|w i%3WWuz]-F% zu1Eh-`Ѵg+h{AL}U3$zKFn[?(ǷP̂z}Ŋ~Y7$7ۂzۇMQbY|\Ro3M'\Uv gM.^G!9Kn>\k[#>.Cw^7?ĻeKNA(*J-x uf +dEm)Ug%}:0B"6)88`gbc;+XHm44:G.UHrIaC<^5+쮨c>=w5N'ݣ] 0޵xҹ¬¯;s)6 EE陶$8pzed*{A ^!p`8Ab݁1I|zJiBAbqW PG +d }T}Yn6h{x& أ#ťtR{=Z$9 `ȂThrVJ6cH2GH*$ ]l餵kݜU=KyZ5Ӟ4 Cp7f+ITUsH=]rMr8GL6}T [?(xI=7OwlyAև̃/%m34G#U/N})JF)OxF}H A]p4,۪cs=9U6R<6#k|nT:!=ާl$&!=R I a!"D"|w t*6JEHxI"=C//D7ú7+u̺~粔3~ kOu( %‰hּ|u-§~r6Z?Ϯů.|z%)wDa܉]t꧵9,{vRһsR/E ߹w9n|/d=GRj<]xTjx]9 , J=wAEא)"=yB|kt W|k.]v |8^<;`wftezfR9ExuEyz=?rt/MzɤmO YN;. ъ#3B,?Bl+<{،,yocR8ssuV;gA]MT#i y$*I[y jK.ۻ㲐6]'R:rp(3z;%#k.4.. |K/nL'9+`TkyIHgqjy+jRl3i'-k34ΌT!flbzE`ypz/e@/qWN: <9%bs׫#l\. t] jѤ* ha_YgcK:Rqz08!0!`O`=6K3eE^fɜQsUjYJ#DWMdPubl/mIIx(~A8g/[K8HEΨEEiVql@BHxv:A޽~?WK6xޟ.g5M>dB`FLVmdq-l]fW^yK*w[_[2pߤD۪@ /NDn1?kyqSu1n*~; RF0t[-Zm9lH0 5-WBݟxO@VDbEl@2+9jLՓ !0$L4ve%b- T'JqԥC7Ǔ{6^ўr.:1XtZCg ΟN~8|2O{/fvQ٢iK^Zp/ H(%K/BWA=#{ּPrn7c͉T'O%>Wښj+ Ƀhϛ!u$H7'Y߅FؕQsŝt^C}GLud ,6mH]"4G8A(\ WGM:pV(h5©l}LasNf)?+ͣSb+p] \Y=Gލ5~ewS`ZAZ}O ؃aziuñIsQzӹ{K.6[zMd:Q"Ǘҹo#3d$jԢEϥz)ٳYs^.8ң(mgCRtu=W/`77=3*lP\m`{o/PKtY"13 q&smime/SignedDifferentPoliciesTest4.emlUT +87A;7AUxXYȱ~D{Uw#޴/-H _vgnBI*+/V./|fo8̛c(DżEot$z;eqf7LOo _a`/k_3{c7-VyϨ ߬A~ӔOWPLvo=}o]Vq-{*dϯiv]Cc*} .R󮩻%{?.H[vET^D> =TR5EzM) 0tP\ANּ„TFTzp4"CMPtβRˈ^55:]i&6zC vr7nLܼ컛J]J RQG%}> Bi.nU #PD iʻ5PPdEϰPN3X q+SՁ31}=qw EP {`vtdcrapQ> U}F}JK(ecѱ)ýӧ,騌 o b=X#_1fHOC1zPN5ԓ-SGgХYIBm|ʡ& ^H+IDQZJ+2C&4->jέ.׭ԕoQ<4#Ɓv:茭NdboRq) HW$4*|'SC߭5BG{NZb/]: B[HYKNĬjK#NB |u7ZX !4ivN!4,30p9謂UE^,sۇe8שvVb1Ýr;P2(R*/iEN5/O!OIWE٦ +AqJ1浤}Dn -<`a퀺7M-# 5Qf˙BӯB#G_z(K1ݫbae4KYxGc)y=X' >"Wu 0:*mJ}$|AݟP E|P Y W<a|[`_CK>3H(7T@S0%T+-k>Lv|554١^J//>x,Nja W C/UmH'΋;Pkn{-$2 [\Wr3M/:ץ2"h۝Gz++v tu7H^81Bώ\IVatJa7T 6Qp'!/1m2ӝ1(p@x"0_^hb'yI@9gYݔPMŪÚp +qص۹a%ˇ4dVorClN9z4g:02xXWGFdKEJvVY5ެ4n ְtxyY~Mp4 6NO'_%i?|=G_^PđPY b 'P{_+|ϫ+|=?6Ia3ᜥ~'D),VS-"vfx^QWmmN'$V{V-Gv8bBjJi8Pic=ϙOX??l92kc{dD%7D膟!8E(Բ{I[UdCEm;uw;baf2=-&YWJzo:SU5=L4&)/ 5a||42]DBۆk9i *g!w/7 [;a&q f4vxl>_ΏReXlm~K! L'_d Wi!_p&v~Y5<,=n =idvIb!;$,b"Z$mzBLsҍQӶYi{&QDť*rOP CHxBO>^z)/^>~|д?(a}E?ƢG8j8E ]}zI"tmӒr/n €t:(]o{h}ܰruLݳI,]3-lX@ wC Yj5o5 w4v L <t2 rT$9Y~=sͣ>òY>a`bdWm/x_AxYCikvwj:"fg)?F; gxa~0K 64g%,.^_13B-‰4+\u,:w1Гx.gicdJ:~|$֗mlܚ2Gfn7]Ys$Z$*?Ş;lLcB=YX/wMϛ|F?!/H+8[яq_/YUss 3PP r3QļӉLq9E&dL`*Z6X|9F sl}`iJh`p#G$:;^5KpS%S5 U^ϖŹp3 +8 p%u1׫f*dLf&#] Kj`hFAdT,K8dX$h0h5\Yy7%.ѡ- '3%HүDžOEOˆ*0Wר-GYGJ{1h d/*vmnn`,kCneD§"̘ď0c:q #T=^fK-'D`$ ٜl:)_oǢxr9NzE:.u5Ad j=kA9r 8ڕXHuBC$mK-v&%#/֦u#Do)G a(Y#w.81Ȍ3Q ?p ڌxGX^ kVeؐi $&w!ZĤ$ {ɝMpM\P`2~o߳GW|a2{%j?t3y,mpQ"-2A3> ݉M@k<;Zj fs jSq' Q Ra$ʵ\J2o7QZf7#l!L fg+ VG? +l2q<&{0={CoE$ih69N'OYp\$UK.Ŀbr;x䍔D }1SӀ>!f0j{Urlvڝnsݜ]׫y(ͧEC21jkzơ s&jqӜc>6)(fޢvl>vrCQ,0 $HɁB&Ewh& W4 :TFrD֫->SO+sf- fWPPHz>sXSO|+\i0 @c!BX_)]FWuz@fF&yx1+ {#cl+L%ܘܫR?Y5>ы~I~Q Q$`_y^: uM,lgb[RRo.!M-{ +iu֫90+*_):=L!#sLFa֏&|}0wgOFq/!$$SجbU4t6mqNlnPOn2;[kLqԻ>#%SYj:W.7JK!\[F{-;~[[@ ^ik!Ɔx~:o>̇*,M* oR_*d{AH=3vsWǣ*~in-p] q6k-o1\\ wIZsk zI^nYX#CKكPx%~č=")lK/w=FqnLbhпg/>$y׃o~'ʫ˪'t!eucbdlll(wh l$0e8EuscE6rZަn&-W6!Z=m< :Y{i;;l;*N2j=Lm3|PK\J/ 삳E&smime/SignedDifferentPoliciesTest7.emlUT  ҆?;7AUxXiʲ\P}}u3Ad1<((ȯituS.W-4"v*~k5l>3/8,qׇY$}>M(bq 8?0_]/ZSfaw/&:ϔ$$2_#p"p Xm|Ơ>p_p/+ #^p3&^3{ Gm[>MA>-"6=}ўwYRѧgSZ{>TwY&Kwɺ5~aZ2KxbzUtTYΎ XW&Qh>a6T>AP$okKUZF ކm```#L0ϡ}|5g^e?}sWw­J.R5:8+ WeTv!xj꭬G|h!I L|z70ް`^pB۶29pa4|Gt+e;jvtuaGOVc2|@]1IT-Th1C1P``jk*;66}h>{gbŦ6B!񶯑Ͼ DaK!PGK䵽 Z;]= e9ΝW]&HD Xne-e7{D(YwfhƘ.ġUrx2gwJ`@jK"16.!2l>V Ho횠M {Ud)YE)2b} &=vtaqpUu~0X,`60cIPXNM]Ē?.]YpRF+^dD&a_%v\]F(]Ѕ% 3xXWvEO|> )ӿ?cђNi|,sZAn(w2^,k:7LjIEƍR)| +C' aLɓOT>^ ۛ^XZfXLPy q `DV9 Â< K~__p>/ZOXُP}﨡>yMߩ 5|Dxw}KGz=;};m%6!b¯:׎ShJm'[v|;0YӍKW GOcZD劚J+%f-*PmtGs|vZѥ *3,l4c~CIXVwQӒKl$KY $+ }[C>rA$w}{~лSsCh>6DߣQ?mǑe7}:Vi!BW4ʬm  ],S-u $2ByKva;iI{\ؖb ]Ӎ龿*7 ?zou@C/8ݝC|2`/qhvXrʱ"[<ܔݣ:͓ٓ_es^V^ TR C>{9xd~#}#xԑ)BĢ= y0HKt&:ME߮N6AH$UIF]\.;#$nU\s>ا;/9W4˔±"|4Wyz/pnt-:MXpr]bW{j ‘w//|VSqo~Ghm/,kaeZ ]S-vta՗/,CƳ=P|a= ,څ<]Ѽ ", hMHwgQ AJ@h[QV؋M6(CEM%}T"I\2r20,q82 3yuJTnx|PuUW 邯wn}%LIg1@RBסˇWEh[RgŪ `Eܗ (U zfRZwM>UgjeWz( ʐv 7^ygy=H艛ϫ._&?QCDM:'j\ n!ag:=kov8C>hF~cuh:s(tZt-)s£2co7ӡm7C\_O Ov6OLi@> H3 .4򣡷6gN@qle.w:~ScOi1ӱ^F L7ċ.^ܓDhybzO&(nAIy[ Pq̞ҁ:AT҆vŦIH]l)PEM[RK?=ӏ뎭[#@ xz&ȿT߲*Qi: Ks7L*ZfX뜼#V"= y) c-N20j@ےR1Xo1\Rv2c}.S%ߕ:U\_L#m<ajk7Q­Kgl>ޔzoPK\J/ &smime/SignedDifferentPoliciesTest8.emlUT  ҆?;7AUx[Ȓǟǵݩ&3Nr*(~RUUgX$̈_#T%d'P77t0o}]4doY{[.? I'9o\ImmUDE2zPa}~H rA{߄7 };D}&km¿m>RS]oPdM1}&:^4\'ڸhoa0$Sbڡ_c5--[ϗ*IGdi1g gMc22,3N#K6*lUoY,N(ty<<ϣFb"\N3:.IwHtoC˅_ۏe_=|[ @xurFձ \5{^މ=OKIĪrp?ra, tʲ]쵻j`2f~R3ڶzc2f@k.}G,Vuh9I<6 F;)eO(IDv0dje5XBfXFE[ƶ=E$А#4qO_Q;2^THY CI9c&_O8 Hi1w/0КVsYJG6ٰ;'j. 1{DZ.cWKw1iLG u|&v;_ezb|((1Eå^=DYI(BpgTBI \'bl54>$xAQ03$.e30I eK^vB1&dBj/8v9s`fFUhdߧI^es ?c [swZ>yؤՠ D]Yr5MW$(LlsG"իDESo6UkarV>MWze\QSgbqiu(vj{eLedW:&f/M%!E y'{GI1go6&FgWvҏvx"ZP / {?]V8Si +FV+:/~ lgEVP&}̷Χxr2ֱ鹳̖;:)~ϛ4NUYM@P"VP`Dan6 TH$|<_T]>ȃU 8] x5T3H TY5"3c*@~晠MN;I ,e]uu\H{* -q;@f?/F^Vj~'HA VqfUۊ7pF,a}ӻ?QXEG~ne¹ʢ!g%^ZZY TQ,92~6 1QN%+p@.}v.t9Ļ} TDzj7#`#i_'u+}ruEZzFT.Nw 6as١FyaGY@ps6\l FW 6e# [&ġ/>T >$nx10W1} ~!Kȇzp}7fh]F7ULtT흌8us n_fLXq`]w|| ڗ2 sVͱ&jƘ" .tl(?ʰ79:Jm>xgVepә4ٻ)$LsŠ FH|qf8tuk#s>Y]T1Kup^99pHMuD1Ma5$[oٴcT" vLUaiLٚ,C*U|U#*{uo߫NL&Ta0Lqm]В͝v4bn(+j|uM/>} ye>'9 CmU\ Ov듩7yzu< =z@V}ht oMnXǮ_PK\J/\n{s&smime/SignedDifferentPoliciesTest9.emlUT  ҆?;7AUxWsHǟz^l{! CWF=juoI`P,fU/%EP/NE|}~C %Qq)fאCtCQ-ko۵ח>is $E&\VET$?qX.,"__%0K` 傆}}a_0EE J`_ ?/6/K4 ~.//&c&o]z]/Lqd__ OOz0Q^E|\#N("1()33e+)2OD 9l*lɷ,uLc/agQV1]"|?hti&: Tvn˅_;wvF?wh BiUh=_I><bg^5a"B}~PRh)x ܙ|Mnd30!sreJꐠ 1z=:p=u}=狇WUt'ubY%m+D[`^YT¶p?M6[\|gOBnMͿia,ߜ φ<('#U,9cNv+ǀJ -0 hraX*W&fbZxnq; Didp%@_eU~TdUj-5d _X.Ҥ}\]dݖwzV̳ClAF잕 LirY¤{ G+OQ=[9Uk2N Φ3%ISͣnFDS<,eaN4ОY.x}OtϐM=`I.Bf,?gf31$2 h2r#QV A%3 }'м1SbO!HHh\gA=*X^4d &a;2XFVw0bP286➵rqkNɥ;YW:ƄK芽f:iH$ɓtoUh1| @9ʼr4m0L=۞*RvkKIEFƸuUz'W0+6;+sw-:)@)yK,vyq{e\J Vsܪe8ay)Ç^%B3(TѣIة:w>H4xPdAy0 ܌ 3Oݜ>|;\}Ͱnm$-Z.39ٰ0ԉ^:G=S(p' 9A4=|upG2t+b)1HTnd*|Fz@2ٙqbWuL =JL^tB[/h6ܝuVlhys7t0afs|Ӻ. V딇^\ |_B.!/ '>#W{e0GU(arcև z1&dwSb8I' \V>v Ʒ)>mvF8 }j>m֬_c*pV˅<9--=II |Ӄr b`zJyo,C;jgxiz!٣o2L-;uTGg,8F)Cͥ[7,MTv;2*8Aog AB7 =toHGRnbn.mVP`+#7B kRXVuWκBQئWGLڳ@Z>t-!5$v$=:O )b#V3d9 !N*L~T'5U&=O˅8JU韔}N Pm[_^ae6^\.BsXroux (FVrMe3zatZ ==+w3-5^sA [1IY /:]}36Y= .JNCD3!Aߩ+|ujlc+xn>h%]##'XU9(qʣhm uOU?{z+|w/d:EY0\ [H;oq$E' do$FIkyuM̂-u)aV=u]m.b3X%YKNfycta?!/+ό 6W}Hn{|9jⳀS]o 0niȤ ®P=NjļG4QZȰV[;_|gYo~V>[Ue:}P%Qw.mvr;q2.v]2~7Y V,>C(]!d|S sGܡ{ 4ne'6%dny F6^; "bוgۑN_O땤/ ) ([.VÖ=.]"f~B-C6ewqO;eP}NL맔}T7JPWί| w|I:;z$iT=3E! }&!`.s^Cԏ,Jro\}Ml0BC ##|'ԇ'y`9mφ^ג &.+G2nJ 5GEQRwE9k~X?a} |^Mﵓ)NX dž}za+,w3{F籝.Im6)^y{Z`jQA߳]PwTC8U类-۱ɜaj59qI|92[yDeD|7n kҵy1%tݴ>mfAXy ?[n׺??Ȯж_{Y- l?qbf}?'Y\Mds%0=R&#{].6v$'}$.wsz޴t\lKX3`Qf2lbዲlYa61>U"~5H_Sؐ0QljyxnS嗋_Tuu۹3GЗ]P~ 2͗+0\UVPF %wr imִJDEX'`Q߿tRyϨËثMp;TzwJ 2 ?1T6 *:faPp'jBU2'5C^9ϼլidzDi}hdu2B=i"\3$,tG]Qz:6+-  uI0JqGQE>`n%i>AZ-luHS TL(m'" xlkG"4Eg"wqpxon㾹{_ްoz7"~yM\MY4qJ۶ao8 ?|CEnr}:@>W`po@Bϙ@f##I F;[:N2/G-g,@mLjzH3*P<  ,@ Iu.<$#pVGk:;GhEze&4!kkLY )q=|Gb{{Ɓ$ϧ4DY@h AԱ _+ .k5ŹNpY7a{ ܳ9cY2 Lkl(!/ۊa^ꕜ K0םa;DWS{*Ue4]IzxH* 9Q(>A91EwRyH{u\CV⫄:$yt "@ggeg!DMǡ?zNQp!*ƒp,vT=%gq,$e8,vqxy0#Q}y^u,w:1u >+n: V<"2׊p|+A`&SBL jtyə*}ʔ%<,XgU\CKh 膽 'tDf8DmRk^\;)2ƚŗ4V\ztUr5n{~TA~Xe~,*˷Ufl¯5mY%_xdW ]8Q3B7 mPEo+!jۓ,:STpqFX c9Xt[ S:VG+wUūd Jʂ,k"FXی.Ƀ yaChJtAlc-IZM*ceF*T ;)Df?co7f<yU*=^:ߨ{mW{'3苽g[Fbu\QN6!I9+ha&܋ Dsc]w6|dA{tv;|`1[hY8EpF+2%Mp".!u@]w=ǼZkG f-VŬr9I󧞖kGgk}Pqi8o#iњ.r?̟֬1CP]67QyCZE?&@ .4 UcwUfK[zAΆxy(g~TV(,bX1"\5:l5*چE@3[$aΡ&ʠ}ഄ֙.Vw (rTgYo%iI-N}I<<8!lWjVu~YDʟm(5iu0*0[~Ÿh+x0/k:h"R 51>GwFݮ` #륦g75FK;IꞮ]=4̵Vf~1úImF~%|աTIXaa&wQM'\]o&,n߾̈́s$A7Ѫ83ÙNP4n~ٿ$ޟ&˿;~quId- _ٜtBE?+lVUNnQ~'yӬyb$*KO? ϯ_m;[4װ~$E6&ܬk$MU6I۶5~ߟH>JG;_O`h6z(@#f"D7F;{XWW(yzG/7W=[8 ) Vf"RֈQ*[ Z>mk=N'Nn>E|}ZBNe(Dgj^P~mĿbD2+L|Jp ;4(>Y LW3a9^aXѦlI&*D||lG=ی``94^.%ؗ#1 )B?X Ƴ4FE0zEH5wƹ r*{a84F|Dt.=2>.XS`ױgB}>W*0MwGP9c;Cy2TpOɥo2:j+7kb#6$ESafO'y<, f"łP$Z YFa`+e5F _{?*Az0dUtlG@S<Pю°lg>KlµRb؛=<=jLdxٵrntҊK(k۹>7A4*;qo`@Yg3Eu#}^B3͊H~;O{E8kSۧo|OpGͣOzYŗ?Nهwп0A\ '{+ѼqA5NʓhLgh=驲;9YAr\}-JxE.68tpEe| ]nѻfFm!2--a6 K*;tă.\oRqs9/C*Eo\Տiq9axMݔ p8|F7 7M A̐!p$_ Ͽ5i]t6kĻ88տ$HCMuaN/kUaA/kF!~\05>LpEx.*r/ ^ bgs{M)0(:,ӽԐuf9atx<ߩ8\m**n\OSt5Ը]kI, |$wNXtoq^"l2ޢzGYܣF:43܂zUZkpxXƣxehttoulƠQxr30Co:Ym ʸ7PK\J/VіF+smime/SignedInvalidBadCRLSignatureTest4.emlUT ц?;7AUxWiVVn N7fPPI@xoR/y/aZko5E8iu6ӉU4Λ<_sWX?˷YVIt.i͔ܿy2cdƙ)Utf/2Ӊv]/ 6sA-I+Ynfb{FCh\(m_ٜďtUb=l6MF4׸[)2iֽ޾ǒ&_NU%>{ڬkê;$, t|3󮩻ca9/~_OMQT#qֆ0pYh<8±eMmW;"ޑ X5L$I-$.,+HxM!u8o4|D/]{|rNymk.C~YQ\a֡w)+6颊JHT/,;Gݳ8T5P@Ù)7~ @/5pe lq ,t"8&o@vTg8Q3m$ w  v\9c±lTuPź輰,GM'{ag{:( 2tw|dO: h5K,VA>"xj:)YĝnI!`$;Ǝ煊ƅZCX6CIP9yFRa=*ܤxwY=!>/ K ׬nuqz1纍=&@! B9m`M³z&K }>2t_bQyiLHzPzW%&H].02oA` nOM 3:yq̷b2T*"*#2,.gwÊD/n7\SUU r@c,جK2+ja+RR\pP3'8B'XBgnID;';ijf9>on9esO' 1n8xn_yIw(KnQگh׮zU+<᥅~gVL\eٟi#-[i*+]U]jl5WӉwo+qdN*A;(tǴ9By W 9kPKqqJ1ﬖ\': u+6qVw[ō7n=!|'q9'ԽŹ/$%ᓺh,-P8fH( hN~h< X4{g m"ƹ~8 Ҥ҆)-ao GkO56ۋgz}貎7x o}5Tʶeש̞;r7*^= :_'u >hBn-sVB^2 O1\⨭y`/U`)8yPREGUm[G6ezU[繹yjH: k~9*'x)'?^)ZM9y|&=4ނ|?9ޢ8`10JP͂<4D2ze!k`R̓Uit<‡r&Ni./}l5Lx\Oۺ…1ݺW`/?ZFaW ؠ-rN'h8Ck Ÿ\ Znk1gjDJ%bNk<XѽT 1= .%*QѽėT鄿WYat_8ʧ_K0ӣ< 5# gv闤 3/NP4^}؏!hxhrEP[_7m>g$1SvF=#ɏ4M'LUx_.,h6K:k^>x68(zt_W_M^WU8&Z/^j.۹zmiŗ<㺯$:K30kYa*3ab1• j>DO//lTI(XːuI\*MRCj*lB*:ѳjԊ8+hik\XѴ.<{U*@ENj%3VyJ^?G&I@_X$y@2x?tb_TU$Xw&1@3;Vn8SY@&`Bp.Ld ʘN8K뫉JYC(g)\粖z3(1d i@Fr+d.cG=O\%^}muGC' 6tȪx 6Eu| I܌I\U 1|̨,lqW=R{.SRaWӉILc3]3ܪ&}ݔ"j+TgwS,]VfuSaM'AeJF{kTV>~^ʬځ[/da@[$VʒF\!L:t2F p eBu'=xGx6[x/{–Ivuqcj,_ [t\t*: +p^uq,P`9\ǾcU\@`vɂDV;RӷmwZ*̐,4f:qvh8V~ĘYo^?<,Q |~s:E6N?yGXgf5 F_a~3"HtZIc[Wr;IB!0M%fU*U:oy\cy3M3<ϧWNqI`Z&;UbP7&5idUNnZX9allYk [|20JQll#.[R7rtst +pzŹ<dust݅mu;j:;UX`'P@/}ٺțe U&(t=Ɂ]$avn&}ױwU$F`FTSޱ=Ys0iv~Kid{;+$؞oƳXE|5Zpk(b[^1dhˣA3h ČauVVk*F]]*yHo{„Fʳ.ݤYx|Ҫt;HwT2(j6Ior_{'XOXNZtZm B//υ>bN2~'QfpQIT-S|%: P)ݜcɍuȩA)Hi[XޕuvqEj#܌ߒ8,!ݨI _H|3,.P %ApNs Uqz<;2[?;k0<Лb@=z:/33Xn'\/ƱαcC QVEۥ\>K溾@!y޲p^KJ-ʹc;fC%qr[Dw󩴡sUI^ݱzhyeI~l{6=B}z?jޓ +Ii{ȴse?+qXD7[^?qYb^18B68IWdd֛4Bj—*$n5ة.OmC2,ܰ㭸(q@6W0ce罤Nd:[i[797\-d3K"gSu0z~1V-:l>'[Fe4@9n7d"."w\WǓ]oq4$A7 lK~h aiq yu}9]7u}h{XKw]">Ȅo5}Qj)̂U(ѱ$Rd׾A.rmw-JRw[C e-ݲYY;=6FF[ *h6p.U_L\Sdғ_myL't74Wx׵9ٙ]3yݩ4?t*3 L'?jز?W~RMUyRSwJԳ ςf@˝[pRɹ _2|۩|'oKw\cg^{-Ɣ>K>v:I߽LMD/50czBb̿esR!tv QY\W)t:#WԳQbaюdhv964Q|79d.WeӉc}pR"zSD=%̗Z[?"4^Y 7"ڭ'ǵ|?.q1I = ϛͮR-lE%ƼQJyW1V,F eQc-%]McBDYn:YzoPK\J/"ύ 8smime/SignedInvalidBasicSelfIssuedCRLSigningKeyTest8.emlUT ҆?;7AUxŘi⸖?3XL܉+yd6xUյtuI2##e8y$|p{sʏ3r:{^K\n {{9_BKR=^gM\F'SGpL)~~fo.̌iq4̼$LfxYx!v:AqIA?d(b%IB̿w:|(r&IfFQI5Nl&>XCu"[%,lK:k^>xοM}u://j_6A(*~M/M]5\ôΗ<~ )uvW@ [\\ Gz[?j1J#GM\Qkͣ:F.>#A5-Z=^m`9&m:IH:4xxx(PM&Z^7qq[-cWӉM\cq⋷ͩmfx)M.QXum맶}|Y}"W,+ ]A6h->(8PYixKjGrKFÁNWY$WʒA^!L:t2G{IpVeBw?3ax6[D?HQ%u-6V DZt$:]_ِM <$$9Bǿc]& ;ɂD |D▆ɶwn BfGTY*B " %u(yje9qe~7QWWX5n2չpkTG)j:!s&׮κ4u |Rڎ=nsLbOo:y ?$gNZ{Nn_| '?abKZ?NܟY;>Nc~叨;*wiNjkuzS[O01igҨ_2zG#WķY E:#@JyL%`x]x`Eaq]X% #%z3w4m,*yc΢΃ Vl1 fa5XưrãZH7:AđZƽz49WEv5UY)D2l}1K%h$-ѐHn׍x^/ ʑtI6.lgw59QPJglU>fʖY6Ivo ߰»Wb?ŴS?/]L'?Ҽon`qyԟ;S=4Fh*J,tRwZ{pI j9,J=}# -< F[Ս9UzK}= 1*wk]2e7kv1 >yYI4p0eW [u,S-Wq. o^gi,|ky g{H $VxL~S X! BjW]J#hd5>mCq4,㭸2AOf ;[P{J> }0´1opNp j:e` .nT>Ȇo?_^pDtp5Z/nU VXDn|;;%rYNؠo] EDh<[#gZr05˖cz"-M+`t/ٻv"I8ܣ5KFUD/nK xWi`:*# N/qp:iGn^I7-'wxJ6 ςaA˝GW!TlOXN~T~'oCH7Zc`_{cʜ&;$C]^a#P/eѫuk6,esJ,M6F6trEk|y Z\(L融dv4/wٟdI.W7ʦ+.W*ן}{`dHK?nH" ^<+:T\MեCeN巴zL'½*>ϚO]pL.~E37Y8<$7MG3%gv֞gj NP4~ϳ V$zH ~[ҫt<ٿHblII~^of6'l:a|25u:sQ_fȊY{diG"N z[-w&2L?7eM]5Y.߶~x.$q_/$9uwʓϏPZVx-Y+ 4~` Լs)b S .}PZK{ϨH(IJqd.VRRՉj.XRgS:=]%smT3rJaS;(}]MO1pAa]eÕrf󑧓#TrҽdӾ͆z\E@<<#ֲ ^ Sł2:Z-g$o+gNf.gi8F?ai aP(U{*?Q8BF*O'k}ҚDYsgtwtsvo{< ;\;\dAmuG#׈gϹGNp=%DXl#Y67HfxԆaH|1a=rEI0撀1ݛpxfZ>{%?ҊCJZW<_yxŕ:yJi==P*MjjtGxKF5:AK vk.>mCKX6U9ZiVܟ҂(o\QG}}E!.zjUkI!HhלN‹ '"`|Ma"<|E oWxёQ7amWԉ~-\.(({=,6+奺,$;x\id`ae~c_Fs!ιWL;\4LSt^ KCe2H_Z+9̊O#˭]V8 O'MiDY6Smi%ԺEho6Y&T)TX[RL 9krg  x`\q_l/_7PKY"1ER M5smime/SignedInvalidBasicSelfIssuedOldWithNewTest2.emlUT 87A;7AUxXײH}"ޙ[HLy!&$d2_?y]5uM9 ٱnYOVԴiU~^?Q}^4QiTv좶 Koi7?k>㚪h2?0џ= |yy.צB'mQPpqMdD^L֋O"ybM5%31;>/&I,Ԡ[P^5?.[gtUv8OXc{p: "-˧ҦqB~ |O+[|bˠ 26mτIۺj]T )ϋ[GxȢ(9+WL^P@W|ivh؁6cab4Wd60\zrD%kTq[>>*IRCЩLL:10f|jK-!Y\|(ӡwݖj N :*ϖ㏧ɹ[8/L~_^ɨiƳ2'֓aNd>խ8rmy8%ZSr9%yme F6G(v#cm5|d?@B\K2my /oh*6WꆩVBsʝYօJk" 6qwj{t^=K}K{Yy&A#bAn]'Y ]P_a{z{n& .y3bik!{zVz# YwCfb=WdW^Tw/U( lB^.:Wmc;ǗZ\KLm&XR# 1 ~}M(;9ujɗ"f|6t7p{O9B _q0 ; q#FRVz۪:đ_ {;kY?kW/("w`XA1N ؞`#MJZG;ȜqhuuF5|Gq&-j3~Mi(\aM;ͺ6j e_<j vyE4a)q<;xЏ 짛+ JpC!ܥASpccme`|0hP P`f ۳ޟLԣ_M/ŝĎNJclWr5ۺ:|#_=g u7+~0I斷?M(/R{ $ = QA@qh>[IV,@")ʆXuNwUnt8vl W<ӭC08޶4)Jp{B˲*#;.ٯmd>2#k=/IaUQ~hiw#>mDeטJw O%C͖t/zZ1SdH VXi5/ʰUz IzLlFxMFQZo\ u,y6w$I\IYz&]vυGoHㅵxPIKoVo+Sg)Ŋ3"d8m |auU#Mx{?l0 K&gIM|&9|4ᮌ>x[QڄM}U$]twЕW.$ׇ~$H H,n1fh xݳdxfa@qOk~XP} S!Fg62w+4|` fR[:YA4>5Pih7:[ߑ}Ǩw `稍m 8d5͝Z, å7bquowjqX9Mg.9ᖍ~iѵ9]FFwthn1&(oG=* [+Bqgaɛ!}|3YY7n>nz;ܹ0 ẲC7ke)hΪ1:q9PcZF-9I_,]#,yi`" ϳ`8#;( t5N<'sEPl 4}X5/7|lGy>XUQܴO/_~_PK\J/7 #smime/SignedInvalidcAFalseTest2.emlUT ҆?;7AUxW[ӢH}^#rQov6⪀DxC@.ro7;;+YIV9' ER/֦U1#ӉU}nQiTv袶 [^c:oU1k2n?q1, T>< g~F3 SӉG_$1AA|6?> cҿHb݌"zF4ngsf [_+E} ZK/>i\F_~m5S|%}ʠ 26Z/Ҷڴ{:?H levIǸK$9]yWyRTlmIJ)f D7+0JTVqϥK;yYU en笍]*IRCD4I HљZ"G:q:so.ΪR@EN Rܨnׄ)vPyy.WI Vx?t", cqw&z:upis0QQ 0VTt _u 5EG;(cBx.LKWTĭK'Qe:YMzh(QxGGI&|ǫ]njNʰ@bɎd:=X瞹N]@\]" 2r#ƔNk}8w3[7'"r¸gkHa4kgN:-H.Ξs،)HFx2Km ׄQ\C91{2G4Y[0pwB CSFh0X^~Ȃ7:R VCג,˶*zhlS\e@b݁ bKHNʍ]p15f@{}:  Xs{ !=nc'z:^T@~sp9|Nrjvw+Cy띗J܈6iRf슡IUӕ֏Fǹٮ|4\cge2'U=Hѩ%t*͕DY@k]?EmwAJV3"1vY|k6)iFׁ^R ̓7wR S4j>a6]a5nc |)r5XC^|=0M(0z&D"'zb]ٴAۆ LMgEj|x` .G$T0:_+v %ˆdql,a,7ɱ<8- 1tr-osp%j7%jg56̈ pr%3[/.2!*׼HpSJk,u a 6>gt9! 3fqjOtJ(Zg7*)3m恎~B$݆Kxޝ b=vx!a cTO7uPnK CqS[b5pvZV[| О3Ce/5\}RXJG&x>єMsۦ; R{Mxtb%qF.OTeT=KsA1O $xHE5+=V*$9%X]:4.*i^=D~ y%6M3쥇~M$Cќ ~Bv.Ց7'`ǖSLab8Bk\PMHgB''j]¢WY 7PK\J/z #smime/SignedInvalidcAFalseTest3.emlUT ҆?;7AUxWٲX}n#ogʤ譮>̃o  }fvufꨨh0<KET/NEۼЯra.K4ÿkޗ kU4qhx_=xT}~|Pȼ(|Ab;_\.}uW(Ңa!Bw7>V6R='Z_ʨ'Eo_׾Ț$Cr& YW.h4龰ME Oo[}1 !J*9󩈢T$#µLӴ@g')4 jl6F6[m1Kx3QA/4&C5„Oﴙ v۹yؾ NF+JWFJ< "j)E"\}̾p˅4h1˄G x2F62?(:PY*WhQ& <*S r:g:iVPօ5؟WǓ⏔2$G _?p0*j_Wg5*{E}|ύ^6{"gD vQw-c3,WEA 923fl2PԆMv$N{ծ xM2nWy*_!Hh.U1D'xf[-qw~bX;a*q=9#Jif;OdM bVS' W;;a'@rKc9xG>=KM ΊHibI *˓k9LϏ@:sd-VϞd(`8-gM鄎]λ@Bwmw|#NNx`07F`'yؕAiȝQtJC&zP% xK1ZoGپ"?wi4/^@.]a? R':=(-X.t\@vӘy5G)kvP;ȅW GSp U|CvmKe$wWо}hO k>)%f `CqۭEl@6PI~;iފ2M}kqM/qMm?ɡ1\Nњ>.&'%n!t{;d }~o4'!G]7 R%B:2&ɓKCGc r-u,Ye<:Y gʘK}˴:c2 FCli۵!n8]i0 6rʞB>KU8e [_\9/`@!y֬ؽ}-{m6_>Ơ *m@ṽo$f ;ٶBsnZezZ }7f}%USaP9_ d~ #ܕ_?/PK\J/{ E*smime/SignedInvalidCAnotAfterDateTest5.emlUT ц?;7AUxWYӢH}#;UI& ol& ~Rꪙ0\ysOe,|1úIcB#ԡTIXjæúM._1uL)~1%l "y|p4n~KS'KsYxu MM~;a(K^ɔ"xėEKEV$߭ ٬KO%9?7ITmݟƣnNb_ez[4"~$E1&\KAISMҾm[׏sirIۺ'孡]W%):ȨQy)a |C!Zjkn(y;O+/m"cPѕϬÉZ!(⨽=m#'7{üZ\qHkR3t8z] E_1" /7Dg>cI?"A<(.6i 0L&ѡ?t/P=W Іc̛&0RLJ}<LW#1宥ĤkF't62UR 0˕cn &w$pXWiezGR(cx]Mi a^c͔ՑsRT6#8got}뢰=VAO`Le%t=$\Rx;2b#9bвV{4Bq"ɹ&\<7왥YuMtݵe݅2Lsͼ`6M8jwfk^<_+M^ra˻;~5+zkG2v3ЮKu `v]k'6',HXԗm[KELߐQ`W'XZ/!3OC:\:P`tDZwԋc"@fxW8WNPxq,]b$1Xg?Vx۝~Qz{Rv}@G 9{ʂFh< *F]䬾LPD[PfGw \4Nك;2ɰ{𐬔i {bϠψ]PR 0mese͵Qdig8U̔lӜWs>hi7V S4w%oC nC|akP@D8`Sm ] ަ\,?笰2BĐzH Pki*M|ٳ雌>T:{k5t(`U_#2xl-1ЙSdzsBU2'I~Տ鄿Ǭ(}GŸYv3zE0ƗX83ӉO1Zkgr?KcΖL IrlNl:aN2 xyC[4yҟʴOw*>E~4K,{}ٻU{o*Bocj Mݦ;~aRbOKZ_}]$m'%PZX X24n`L BdX$3B@kQBK**ŢE]|d-r$ +eNeR56 7l?]g3N'^i?}w];JM- j)?u]gB!YTAi環,•xuz8"P=Bb^Wd~ C e `iq0ۖ!.D AmN'cH E;Jeem +1b JVR/&a/`MO'[Adp/kmhokmk|_L"z=;^e22#tyq [5YܯsQ&S"]5Q,a幯U@6{屧(;EfYguw(2mCjDV)<4o]xڪY֛9JWw*km$$6pfx:xfl`!w6Iśby\OKbr?=˂ÛE!~h":⹠|OoNɑSq_i>㶖 -W۞ϫ$].sܬ6Tby7M9y:Tϴg;ɛ~m $ײ$y`D`1&D=J#ɺo6APPjbc%8E1DZCnǽYj?XsI#k&%Ϫ0U HMؓA'Nd3:- & [[hpŠkw;W&'[[%z]$s{Y|eEzWz[G˻ݬJ @ik-95fMq܋` f|R ăRbĦ $gT+Q Av=1;# S,2Hx]ѻ~w,P_S֟)g ӷ9! $-bK:Gb s+ lpz2L@i6:%[*k}К4[uޯ_*Dc_n^[uVf%L^6^u\J4[я>_ J∇.@Z@hLheh@ucg4LÚR5^|ѻf{{һsW?k\J)B?hW'֘{Zci=gnieb{uuLhBzv 89'=J΅=^rq 糇IӠ$O5xF&<=} A J2Xxiۖ}(69p_Ih'Yzw[C{TR@ь°kpe5?zVڞ^^dE_d޿vgܳy'b=ˀieb'Y1O\Lj!I ^ÖV\K*ƖZ)Dd%[th$)&@ïZǢx 29duOl&M&I,BI^us .voİ>n3vŽanUXB{hd4vL*XN4M4.r bndH='z͑8kqU[WuԔ_bU#C쵖I|AJG$<gTr>y X 瞹ֱB3@ɹ&<( Za(= h᫺CY`Avո!w6p^#3HN/Iq]ˊJK )^}w؆ U11ȧjLa83OJPx2TK|z:o "_ N)CicLv61GryfBUo8H6 KeiO2̂Q ۔߃W؁ի`A_ݲȜ3"mbmʯ,ۼ;3oe:3&ahbg&hMROz.{wKva"5SS(cݰ 9wʤ) ;Uަi VZ/m\09_oQ̔bD泰pOq l3A}FՉy`-1Nb.{ö1AjHGrTHX6_pg }U/gAhJPPQY N68_B VHX0?ɼ]ol4i*ΨPƇ/V +4jׇHrzGZOb?ƂbYw F歎Ӄvi4zV6zČWng*`:ղ+8@> {2@j)o={"00g0K0;Cꌕ;P~W P~CMKW#b HR;kWl޲?PV[3*n6O(j'toVFǪ ` Wgg RXk@=nB~&S6hGf!N+=/E\w)C.XD:[ u2<\i5%cc 'LQUfթCo*D7kO M,9Roz3Gzk`޼Nӏ>Gv!ʭcnM8TzטlXS{3Ϛ;mo ܯ$mJ5|[J˻ǹ&/#pИ QH0QGL0O}wGT̫Þ? N8k6"kvWMn!i7Ҷ?:|^鍥)u;l jj=B,2%ՆU* Fh~($B\\I~&/?O8ҟQOHQNwW _uE6q $_X1? U_z(l).lbG8rҠ([seCc0PNpr1yϸ Gq o窶>KZocCZǗǏ~r<:PK\J/; o&smime/SignedInvalidcRLIssuerTest31.emlUT 8҆?;7AUxXYsȚ}E?S-ZNLvHBobGO"]Uv-}+T:OsK'3qY|~æt gԍ\8=]鄹:(uk>?bSE/t"uD'?c|C cO{yc ztBEvIWhSUٸiV^yS=Ԡ9O8O'U89oV7]'J?.OS_S:n4s4Sg®<'#K4$I4 'uȸRD /Òhϐ1Ҙ\֝2YseMȞ^!g>W|kXO)ΗZbmk9L'ܼmXb3RJ9Jkkp-#Yfʳx47ZG@@atQ%2fQ[44)-J en,)ll&>ЦW"en}6K>#ٔ5 sI\.]︳'KLKIWpyG/GRRwX;4ڑ`yT}NXʞ33#-:5O) eds#z0A')4NꠝA3 7m|o2*pб3]kJQK"<5`;[hDpɏfYŽgUL,V]]J{vy4 #{F^YsxkG+;ndB)< f{쯊hƇ3-( 򘽇ЦAC{To,To$𩎆NACxޜh{,бdN`qzُnсqoX0,D F8`̰y3~s婸7qzЖi^dm{Sn"$.qN 1EN⽽pf{Щ VΒbf7 w ,Dٱk*{`ۯ)Ĕѫ=c!^opt/&N^=ֆyv-t`W9;VJp=#y/ ۪ަP,$ ,/խ#6tnXK/9C^c kKY)שT >w v "$Ug$\~]w']@+6z I{^C|\,#jˉ~aȧx_wH8zno{В.Lxѷlq0{ΒhAE,OUI81Ѳ eqZ,vNz=,cv6a~\uj0*"7ER=n7&>> cOA*TP$p 9la Æ/6|>v2zuضrsr3i5QH)=Vw:.s2w:2,kKl2(eyd2PS!N d/˕$uk0nn^v1bw36cq7KbcRHoKK^N\1oq˂U<#.wImKAyB^Z(z]lK~p:Ξ:Nn;Ŗ08,R,L3Zå*F0Zu6eA$G+tnV WtP*gH)Y9ʕs2P)#"eaL\_Þ?f$!=RVFx,/b9ix 9aSk)Č^9!YQ+ )d-t S?LjE:> \V֪^˝#LaʻNN&'yπtT*j汱O^ݱ$li?G|s QXRB#y@B# D)ZRˎ=c~tcoM JS$?Ta-ޙ$`cO{2)ѷcw<ߩ\H(`PC!)M' |Iv=A}J; 69϶*ſ,;Lkt`s)Z,:xUp& ģ΀%c(sJs㡨pݜ pG1s8w˰q,e&6Yܩę"sѭY??fJMt'JD8LwSc:Z.~1z-E,OwY|{\RK{˽?wz=ݼS7,U1C#㦓X>6.=3Jߴz{XQp~!ʘNKU[[Yt8kpc\ekzcYvI}6go/{ z^jmz+LG T~飠 v}}ej}tf41̫JnK.ו޽vpl j#̹!|{&/e'B\F7Hn)U!{?}ͮnRtv]m_p?TVsumLfoL.;#gdUiWȆ2ښqNt5n88zʘC8OW05∤T"95O ͷ'QbzȳȞD0K#V>@x ~MKo Jh@ȂEt]huRu8@ח|iQ` k5 Zuى9V,֔- FsAbUߏH RQSc5])@/":X>6y4<R0v &a= FHAV#ohMn۵nڪn ϡn*#dxTWy_TxҒͦD"fԽ'ƞ)DԐAq|²x[2ޝ]ǼS\ \Zs=2@L ѤvWgw#7,pcB1ɒ:g'hBfR$j 09 D=vY*X0Q?C_# jЯ ڃ_j^f `EhF:1B\Oϣݜnj2$"t 2ٟ SZ\, ׽13ӨukY+qƪȉfiFE*cS 6w!Nɮ!6`9,%aPH>rXS^=pfM {0cwp[LیɲN$U"9:۱\^y5uF6Ъ=,uyE917 5;IEbi񌁣dtԣYe܀&On͒u뺥,@ 6z:RS-PwnG-yp=aa vi)G5 fȎE߁u'}2*n(o{4iJLmRɰBVޝe[~-Wc/|j"Գp5vXWQL[PJT=]0u6|>wu:b9c=p(%Y?rw@e2)̣eI윣Hg";saN]'.l< Fʁ~߆I(ƼuW j2Bqj˛A8qɘeKg˻\nr9{3Z+C;9']QŠW3./T"wHl;RYdl$M36Å0PI|pp _KM]AatP[ '.oa91떓<Ê?:[!f^Cj:̿>8;n6+N*E픈Vw,o uBxm{!$Yztj5NdUnA֓˘`Ln^ɚs(]En޳CV 9fjXK+ԸkDqÁ8\#$K a1>ud)*5%T D:Nт,x5v>=ɽAй<0ud-{}؈6hѦ};&P|ʅ, =-1Z;x/N@=>T(yLo.m".zE/= p *$l*arFǮ"qX;NPutxtTʀ9hfD9V\b ?ΓDG57:Z pbRW)v+0f7]c)5T_GOPTeH&s|Tч9<_19 0"CD4 1>[~8t1_E{~#g21 Av%\ŸA O_~gx?~~S|#y+k~t? я$b?S}LIzkcJYؼ>ɶc}\~{[ȩս^\o=+nP=!}Z I])1Vq VqdۙH>ƌYWبo mrY}MrʻzQ>5js+f r>sm%˓[-1a>+\n o~v4cUX5[Ծofky28(Gd(* Y")uvR&" yvhFNlOLp_obqlܜj^!:qQɱٞG ' [YW%e68\֋NSJEu$ڹs wPK\J/i+| &smime/SignedInvalidcRLIssuerTest34.emlUT :҆?;7AUxX۲H}#ߝ*A陉$rUx&UEI'&bq IrJQTG|B؇EkVnsT^To*,%_fkXU3FnG ʍO"zT E}FAdwGS_5ۈ~ӽ>Ez[5q;ᐵLCWO>Uקg0KX{a-]x E*NAPVn]~_z}_([Z_%P}$c(,P5#"FKA$Zjm Ye8`s/"{~D^^ 0li7{ܻ'niѰYE $Y6$(Ĩ=U76h\P+`f @ FŠ!LoA#" ,.kg(7Taـv`>l#Jۙ L;eo&Oj+*OeF`.4]gҼȨ^d8:BuA2B Gٯ;oa-r8ȡ2d3u5Y&:u @0}0Nю0ԅIɝ(I # ~ku;ic\FMȸ\;xR#0WYEV*kUgxCssQ#L.ƺ2N%VDN˺D?4O(# c-he̢ҫOr^PdZyU\ftʈF;IdQG]tIT7NyqS"eb&:L`ܼcjXǣ ;FsE`/*\AnA`TAjǵG$^̼s'Z8‘o"}&5> `X6u( s^ q=c7zzhL*9q,rJ:Es+J zVy^d6WV8 ĉ:xhiiL>]Rq,VԾ{|qk[0S󠐆5YxƤ2p" G^V*P5G2Pc_ʙvIWǖGֺpUKG6LPbJ1#%.SX]$@Q@GzѮFS=n]Y"Mgb8Bňe *Kq0e9F &ܑRsE<ܶ }X9vdVWeM\aniLH03y&ݹʹ(Dm~E:x>KMlp!Ng=j4Ia?u|׾ ZC+}t`nnA4o W6$_XmVx^FfX7p⦅0// q) B;D4]%[H&{A'6D eskҗzşE~"~K<3&'=}@aEfzi#v'lorΣ?6JWw.pfL*T*̄rkLg̨ʹLieͯt994lj9ŚKЫ6&7>ƧSiezʶf&0B%S!i0䒉5Bz> )Xs͟lxqv̮QX5Qo}qySoHGlO߾#zua$89o6Cwc+M]mA)3|IdMZe-Wf^popğh)ew Cbg2Wk6C'X Pz`N"v)T 1^8.'{n{h7dPK\J/| &smime/SignedInvalidcRLIssuerTest35.emlUT :҆?;7AUxXْ8}"ޙ* f͞ɒ7o _?2UݕU1IqGs%kKovw Y2,J?!]3ӗ^fAxB|IMkk(ngnG%' ŰC} |A4KF /{#a{ ;|{}.J'q9iS/f( O%k, >n#sS־PfQJ2e=B3NLǶ:Wm8y}YwZ:' \n'8cw?JS2 t'kr\^wpM=ez `|g@1d c Uajš|FkIXjqR)NITnE2*kZ^%܂/\[%USxϴ>MNNK$^KY! np1|[ߊpke&v;h M7?z.ؖ{H)Ʃ4E-P? .*{OeZW lnG8(7B#u|;4n^l8+Cvp ;SKM7n8@kΟ*Ց ~0ȼ*6Z} :e]P$ RSV[PJ#1Z39UK@Ys46c*o/gTӏ{{v>Z2 svaOIݫn.36hIK_z/'={pq11{}=Vf{Ss}[܁dpπI O~*#q0^&8Jhh(mƫB<[]X b*ص|tyﶻ2`N#s}:4ҸǔP|kҖ"?|t; K+gE?|Z7U>oK=H =wzyH'Q>r&;d'j10C !z[3i!p]是}:GMd:w;q_fe՚/f2دu,i0dL۱p V7@M K#ngaA@lvnSKi OZLOQ"5vec:Ж PFe]h£vkN'wk EOPǻ E^I橽P2ȟGuJ5 el{p70yncP1hzOD}2]Uv~u<_1lF6ZA&++JVݎ9]Ҧ/c|EKO- Y+OOUuMBkR3# du2Jr$ZXgV.8񭼚~#%.PؽϙJ[롱,_ PK\J/! 3smime/SignedInvaliddeltaCRLIndicatorNoBaseTest1.emlUT :҆?;7AUxWYX~#;U⭙>9(&(诟S=յDOHId_fdrmF~&~I5YRIGIg, 紾O'B[_f]RI IԿY<XCW3Kf6@N'( M>E"id5pLhHbْ IQۊ M'l]O֣AӔ7MuO|uO=gU>2 .X\UwJO|qVo^W˺=A_fL:,+)ڗHzX,=Z@r)bŜ)>%GVFVzH[u*fC( Mw#E";x݃MeMRh9M|L] FaOgQThiׅ8eV#t A搩r%\y鐻%~_0O[!?8fEf+!%H@O\#ȼr˃!w$UWWIҬ{^/CZA]KuBS%dTrLBO \K:q * RCפ"AV~ɯ(l/+Li\M n-J1AwT9Z6|y1Y{Fځ7 (Qi2ayT(fmv6,TAz٪Ȉ|SruVE;O7U"~^o??+ 0v!1,ֳ@XȨ?jkeT)sYKĢwNEt(pv1bkxg^j]TO߄nDY@V1jMX6~/Cb}[ oc#ٚiߟG܇zGyGޢ,mt™8`%jca`7&(0ķJ}d#a#VkL tr%- ` U'+nGv;:hfqv)aB"=^صRD!YSN꧓ɟ1WȋƏ 飻P;ۆ*DN}tmiVC g?걯UȾpFE}ck*]'dԘ֗2 W<uu4\okӃ7.lq._tˌu=2>\o[F ,hȓt TŐ\hzTkLu4~xacl_b- ;ȑ}r<[׮Y_eA2 OpuHRxőԘ.}ڄާfPׄ nyU9k<dɏ,fMӉ^ٵJhcw7$.PӓS]3,Ђ}9@|=81>P$<}ø̕ 'E%MC<+ ̱5E?M>WH:Vv_Xk JeiD8]~ίg1?t|wGՄ"~p"ބ2mjʠ![0FwuaN'^˲ an3v@~TGB9=i`l-:1~=Icģך'qѮAj%/䴦[!vqVPZ_EPK\J/, 3%smime/SignedInvaliddeltaCRLTest10.emlUT >҆?;7AUx[ǟZ~Q$+݀(w-wӧuOf&d&۵ˢ,j$!ݚ,>&,?&(8*Qѭ/q?1ne1i"nb$ ڏT<,'aVW&&œEWÂ#>&[ɜv(z2b2d+UUZ ӬJf%Iz71.Kޏ_ /'Mx7h. _ec{M^MU6q>@mKE_}$)Q,] -X]`h|Ϛ@غqBB "K%zZkYw6K 2d/*?i^BBn^ =px~0*_[jιT,.笊C h7(N+U6K5:s+Yv* ,ya~vQ9,(c/";X`Sz7j8^A z!.Ī AiG3s+t;5뭠ҧN*"OT_!SԍGjI @Zӱ;w{xA^{E-sӞs.v'L`~@"WmGB4 qZ_Xv|LAS.f㑻}L*ȴVC[+G.y|l^_+ [Rv2 "fGٯ +cmT'`[]y Ǒ[9 m[p"ɸ~6ּ*GSjGb//N=aA N|eAq+5] 3^tC=̈/9x tAra:)52oOC vu!pi<$pzhN H`]@@gXxE& ; Xc>,Oti=Uﺠ=/trnSZsU(u~UGg{)bv59laWMM;Gokc%WRX=6W[>@Gp+NPiccwUJP}}ݵD\D/3%ttik v ;"[W;"Y ^@ Q ӜƿHycaɤ 1cBaJJXr H+Fh%G읙-#.Jf=d0yϞI.?@sr0AEDߡEi5xt?+u_6nY?M-qN(tVn-xY'q@\JpR[)|3+,TTlE/@L2x";X㦸'M/go9B H VeENTe}`Z\ۃrs iM;ͨM{m4ִVwM2 SV\`õB7/B'5Oy57p4{#eGuD{,=J@8[L@!3U΢ѓ[vG\>k XcCeV[$ iK~GkgӞkᤜʬoɔov\7iU?QYq^ҸlMu'xUerĸYoRy4z$0P4>IoԜ9fo<$_FSojؾ(jFs}AM(6Uْb/Y iiz9[oǷIqG" {>.~߸2oī#0m.U~;yc I :w'WCh![ Y 4@dUCX!c pDąBn9(<(3+ "b] k;KTҗpiUiՠP`zxv;۞TS0wZ^o`Hwp8ˠϒ@\Iu#Q,(c1"I,j t@[ ֶCȀ`f@eGfv yt; ΅Frt+,!b&(*K "O- u5=f @Zӱ+u;81U ^١(]O$9P z;$q L)0|MΩ(9*{fˁSXx<䓁䐯eKIO^[rZ4a놫lۅ@|`*衱=R`%ȂjvMŵ;p -iɶv|t@qx$hb5c>~aA+$VDA2_k2+}J<տK#rZew ^TBTT^sg Giq&Ep*@$Yy@ :/(X/ƺn~ ,yN{n>n}V*y R ǀu5pҥ"y3MsCK㶋y;T9cSNQg6y?8ٕxkL.wVvqU念F[/{4<-OuKS&AbBCGuG/%}.?UxS] 4kg巨aOHunY?oWF:m .$@%Sw3< / ^OZU\B!e*^k M̵[erHqR8J6!Z&x<΁#=?Q+XwӨTYO}fxn:7+,N@02WnLEqGfF6dpܯPR)+ cj~㤓l%E*0D)Ցz& lv _ڔv+y8Z9G|yo822Rҩ~e 'd.|JC7:#c.,\䶉+{(q<,W:F z w=ָ Yu1@O3*`_351707BF>1KW!϶Ʊ22.[FKN_זn|B<䎡PMR̰G|@1IQ2CeOfBGǔy 4"fNsВQ8cʦ*Bip-^R[x_} d zKTCk.b!mo8@N͌nsӽ9bBn0rӵ/hsc #QO0<'=3; H x|4ߦ @aDދ%YH:ҜOXAG":*%bw U Nk%$Z .p/z?tH칱<# NW0ٲ_J=zǹJgGt5YmtIc6st2=;{WPiYYF ͯ؋{J**}<:~#p_2m{ę:>Û=i.ڻn't^dDy8jgNB1P`>S_gM6/g~ UǾAc"^~۹ϋr?H!7K[&0:U0~b1m)IW$Q=9 jՕ|x!y:z<:C!: [݃bf[UXGrJK}q)Z9y?vA3D{ +6/r]{.cLWPɹQH;ŭ\B8Y/|$aw|mLr ~ta9]m11oEUV6Μi}&%?좬_\F~7t~?s~XxVFg^];gA}n ̵bm,*NrͼȎt3O Aפ};a&!嗏PK\J/k $smime/SignedInvaliddeltaCRLTest4.emlUT <҆?;7AUxXrH}>Dsv#=}bJ[ tMH $(OLS$+WCfu>#~\8kޥm.;fqD~ HM$vӸ{=*dE}mc?`#mo>kA/)9GI>Nhjɜ~_ =Rk2uՑbxVB4kqI#g~i3Tɷ$ꢟǣĞjFU{L*BCԦ+!kͺWSI?OY 8:TOV$k|搷(Nqe@767 V#K*-)÷n9Ga? Ͽ9-MAYPU|awpCɻx(աϪLjw<}䷐5\<H{q qҬ +؄)KZ9x<=j1o"|o#ȡW] ھ.{va%Bp{Gdb,Zhrj&Η9ט7`(8(ArS BAi[«{fv<7_} jHp{8pnn9>@}QVx[<y'Ժ'TEKt >x-8~֖{TꂡZAa6+@7ɖ Y̚ktbyE"J' 6sR |@NYo7gNJΒGQ6[0<3׌SFb D"7Öq9?{8@˄%/;@*' Q ,egA{,>H3 (`=lLP@,:7}4hgYXhܴcm|xJ;'@Uz+b/e! .9b_i5s;2<Ac|'Ҟ%x8i]Dإۿ˂1ƣ'Ȯs32ЂE#ƣ>gWkT>6-n,Hˁ#϶._fދܸ\"-U6gl1 L]>f66 JË[ ,5鼪}k] E TemG4ju"JMntONeZ-_E}_`QR!!NW SN?IBj/Ix^[m sع Rsݼ}1sL<,=ozoGwqpd!wϊDgT?s#2yP(-L[@3@kpY]uR <.J{8I`G$eyO=2$G9aq\/SO]sd+p{FFw)Q&Vuï2]]*cDB:{$l ZE 9d\H7`å;؃ 2{>:ha͖'i/cjX3Za=5T,m{3Ж\ r|("/3Lx#ETYM|gÕ`MJӊ-bdR l 4Ádȑ?5餺'- Y$DRíXgړG- ̴%+lj98fkpu]>$J7rJ lj&  smd^4SD0+?RoO衋8tz vPo]$K9Ld9`8 = 7ٟ;=Z71"TUqĩ&{4_6e@7Wv/3=l5(2.{FﮇXhwe>zz/!JYp`ݖ]XE.O%QjK8 ~O5h{Oxj F!^ᏱVIX,Ŗj (d;]p(ZT߷S74`Hx݃qԶ8ҪmCV!uYL_*.x/U:_npPi=T_Dj@%3Ek2|zEpZ#)ҬRcu~Lwt|n6@hynp.s3b1y}Į?S48OGXc̛O $r/ {r/}ϳ~*!>n L[Bt,%ý[lOnIOɗzBV-tg:u{i,5С򼒷pӱ")uv\S3-̶qJyU,7}+WѷNVUGkH @҆?;7AUxXYӪJ}F|#8|vGW12 o<( ¯t{ާ5 âL+sZ+Ib:.1xqE&/x4-\ᷰ|N'?fuP'[^1¨ǙNPPn|؏KK&ߨoNXc?53 3X+j6'c60e~ w*OSZTWoq>Ƿ/ :⻍t?o&*-[^E1u^6wܦq(nq|w|"I:v?==(Sⵆefp/F" "FHKq!*_ 5JcYe gvUkR6E^!g>KVmNlH4*{h±hhmtf4֦vk)K;V)e&SKekp-zTV\s32rPF᧓2aPH] Xl8*SX@*`D/!6 eRN8SPܵg; fM^W@x:1d,G#]!Ak\uJ @J1;u{8}.&B)eOS)\ЋׁyZFET##!aޣ4v8g)\?t*HԐvBpfsb'2f>ֻ'y ng#} B/gR E^Qw>?vS\* 4*347r7`Es& d,r]`}ߕ{ʀH,;qDA%Î/1h A">B ^\>AhsI?dmHYIO,pWlEp Lec NA|6@@#|F!T] ^;E+g:L|ʠ.ej+ν`kDZ9r_ rmo`EqZ.} mA۠ʦ?񹑁S{u/|GQl\ B 8_ mPȮ>:d"ivM'#~]cې5s@ѿgtfҏYvM'#FvP]{#k]K }g UF@\6 $aJclDgVI7~inR#"$xq܄oGV% 1+ UfVV"5_ef$.)#Veڦ7t'Eǖ0 f}7M)&#K)?$i\'emQ!][y@H`_nX!Ԓt\ic/fP14-կ# tjdM BC{sSyڱ>ؒ#׹+[Eu,< .JOb_AWo!uZsC2/ldԲ;Δ{s ڙWg}8A>+x!u)X@ F t]2t qhe o΂cM` ;"*F/*6e ;g:k"uWjtw۽<J|nl(7,!N㹫^zSVi1 h^f~j8WҖxB)XCC~SטU^'#d_^Xv//5(.ˌq Ntnj`QEPDqGXƽ9 y/i/V#{@.ڬ @'ܭ?}dXMe.}ewyAͬċz9l6'BEc['Օp`7k3sH],-Ev\Ih8{" )BzqeHMCxrzz1{!WĂxv',  yٕ`YOEZ_='w!XəOm3G֡qg}`[{lRNاKM2nC\I"HV# 87(̠gةfΑo/n)2RXe:xp drxf)5E7$zjZ\amm'> 1;#,a'(s%H+mOj:oV~Yo]]@KꝗFSeBu.V Vd>1{!tG{)|[nEU;m H.rz =s(aa"wk*nm:2-lf3^axE!v~]3G|}{+ ;X:g. 拧Z);}˥KE#^rw#Q#Ȕc5A.XvJIՉtWWzMN}I5'v?~ܚ;G̅c7]M_>u^' vYE?PK\J/{G -smime/SignedInvaliddistributionPointTest2.emlUT .҆?;7AUxYZǟNRwfvP@vMEvs{v]b44ɓ"/ҟ̠nx[L/uUmд^P-3.E~P`unxۂ/z'7m] u.]|&M'z[YFq׿k>۷S_B ѷ X"ȲhaПG흪ʞ筪kv8~Y4?Zh&;|._-?хWq-\ PqSMܾ购E9g~oIh G'#Kx6$Y4$PGFM"&$쉒iϐ`BBiM.zL&MhcQRShaVBT֐R*pjTO57'l:^1XyPJ)Z:1|~ll O1B 77SE3o-EWy,H\Z'QihPPI) P&"4Mqd`d3T%T0YXRO;1ЃM 1WOK.$ޑ(u&~ϬUVB ҃`DDd_ީE@Zѹ^đKm3ZykX c݌a>Q#(E'b(À,  |)42Õ[8nu_2e5kw뭯Yf$JG:=6YC]KnǞj9|V\5P5~5jPh03,%s=-D@{<:P<= ƫ BQ\rٍeT~,.=dScֽq?V{Yt}r(*Bv1h17U\r ȼCk͐&c6a:\+Ǔ9b̵P)aUNNK iI_ISߓ6Ǥm8ѣ: r(ZXg>E B?I4=nQ?YLXJxe.Lh P=R UdFNCx3 m<+%|XTg+7 ->GvXLA@N,P 6(OdEPKni'jc;8#΄.X8l94UWfwCKLlgVDLNE Ĩo"l"*\jkh:QJK M# d/s@)Ũ敧iZbn$ ZQ(4"CdfAT_II$?4L#8|R OMDK'MY+#V'7<~ةui~@FEVMjoa%slwe%9VJq-(.趾ebl[T(V^֘YخT!yya%pJ~X?qP{eN?V ;ÊDGDۻ4K~!Q;;|SAxOԷ;YUe>tSez9Va =ӨcNqUĹ R햠6-h<Ȃzɓfcf$Uꄛ;.wp9!jq9xQO?hLn:]z0;i:78͋AO_ʺk|6u~0_G sJdSSuTI;NRrXf 2[r׏>Cw|tDatC%DA~_,matFR b_egƹIh'W\Ch4RQ4A {PK\J/7^} -smime/SignedInvaliddistributionPointTest3.emlUT .҆?;7AUxYFǟl:9ڻ.R#ně.t@Bw R߿Y+lڤ*_d>3EIek6]rI|~Ukuцe6轗~˛'"HڮI:VI- C|>öuEd^Bpy]Dt@eG 4T*Af}Zjg p6(-"wsű_Akv Z3F"gDvwlr΅uߛV`̵RI9¨Ձε=(X^zcfgCӠl( pg" j`owr a2x,˴e#*c>c- W#}n'Y3vpK>Kk hC AW Kʆ&qǪR> Yĺ2=cYw|>At'yRG>][Ba7/n0SjT9e8K݀P,P)|99,Xs: 'Tk-\\[9G,sĕpCz#x&#Cr*adVj y D/ Xǘeq $ܜ7/9T~.iA6Fo$;,T𨈆 \%6{I.#l8*Ww>BkiPrq,V֍_jmK 2 VʂAy, <]мa!v`1*(`U0UTϔJ~ըaݦ-dw̾ur)IUL)?q [f܅U($ sYl;dOXGjmF{v#-MJŵ^,͸wX%fYLnRHhBҤ朗g?9i '{v2t@JIYr ug~?=;L}[6Y׺| vJ zT#4ؙ=3?挂9c"K)z! cSԆ }e6{leJ5"z$+cv]" Qn+޹ǰ!ǽVܶʾmѝ{'4@HVx>˪рM(m fUu`p\Gy:&Hwx`zKLnݧԲO2a|eS>ŝxUxω⤎yg[2! ?9 dB+Lalt_cg,QTTCX eUHCskywľZ\@(Yķ9nIaql8P'x6*@Os)iUd98iZn4cZ1,r0ɂo~L\g$Fy4֤J}Nt^ׯztquRIy/Bov͊2f1x<gaO+(n |WN?;pqI@dr {P'FJetfZ-/w1+^iRl O8`8&FrLG>A gA9 *~Wo!Vz:\ޕGfy ˆvFZk^g 9g91 U9HJOR?OY6n*X&}b/<-D[6RHg2W)w$wz03c" c߉ectgCH<4l>TUX^}7T,ĠO6\}Ğos}d'Oܭ *v;.A 8J2jިjTvغ0Xuy3:[Do eYÝqjE mtJMDBN=PK\J/19-smime/SignedInvaliddistributionPointTest6.emlUT 0҆?;7AUxWےJ}#{z >3Sܱ- o\KOiϜ9;aPYjL W+WIotbo{$e먪^'qx*D׷YatDo4 귙^0{75P$y=3W Cѫ̽A,Hq-%A|6k:۷pO>#3 3|[o49{!g6E^_^Yf~Tkr~UJPW{M'˽+^{1&`v;' Ho<^[nh rˤH:WSjO\[lvC!'ͻt6ׁvap7xXqV*% څF{ RU*:٪-rK866R@`&73M43Ӧ\it''7|o]BW,cD󩬙NBNFw_.ux`2#nh/Y^ʳ5J-lmLq[>RCG9Cs\397ݦ>8ma\k~wmAq-i4N)"H#;[]'涛NPs77,W:mmYJB×jW얣`y.e ;" Z# V$Ϥ 2-;A1E㦚{&R([Hs;>lLL|B~禹l4>!IJ-pp#3qM1ݞMλ\d*ȧpNb\W7Bd{bg8w~T=}/i .5\ý:9?K!U;_lX:٬*^r˅ &\j5n<#c#)hMa{zTݼR$tw&pD5.c":72}֫O(F0@kNN|#!yxp+*$*i>Hs"AL4 kws:q5 xd5Y׫5Ct6&w ӫ&3 x;|?,]xsfwRݼ tmuǓ/ O}676] MxC!o`܋Rw6l>ȅ$Gtb\ёs-KVR7YÂ]f :p~PK\J/?`- N-smime/SignedInvaliddistributionPointTest8.emlUT 0҆?;7AUxWٲJ}n#}b@dɒA@KgĽ-aI+,(A͊U\ 9qGy: 9<|HIatI)xYN¸U"뉁\G0*Eo>95$^n'="'jPOhM(}Fϩɔğxy~3{e=##4Vo6?o5g< B~{WK~9yPq'WEL**_y .Wg~=ߺ}q.@ZxXE߱2ȼsb2|c[ϵf(P(Zݴ(~R!\\B*z]T8|zA)[޵xtZlZKoR^j f5#9PXxDϯ3kS-& ,V*T̔ˉ66,ȫmZw&ZNz7h8^ e;1.1אF[}(fWV.x<-'giGۙAn !0U)n/? /Q \5]fe7ow9d+.Ν٧ҥLmh+Ce0;p?c8$N3X& vIcqӒ3 L31!7e˃ⶄYó/:BfNLBECaΞ%U;l=l<:|Ihijqj*sx6C5kYt;B( R:z3#(zC]洟:=7{4sdA)k-#0 jSz0eW8\nҙ#lUqy+ȸu0-5ݺ} DȵmuV^YQBox m -xz8q<*&?/j7ABsU"=\!'[eB[lrBɂel~`o#ׁ˶0H-{yXu a^Bgy|&@j_E@x866B`KiM`}4i\9!zBW,αZt֌G!'!?OXuѯxd2#nhiքWl l-liLqS>RCGng&zyPNsq%(D^%.4Vx=ksړT #t=L;μldۃm.N/V6<&[C]>A# 8od?]q Lm4us8 \[.>3-vt{JA@@LPP(~চ2)-$ݳ3}6L\!34gg>zK'7f&nqxΌ` ~ (C>>u Y<Q{̧*+Y5K\WGi?TgՀkHo.X-&aΧH?\?5o(6Fn ^T&YD¢KduͶNYےY=ZpeLvGĆH n\itpG?k3}ٔiW9mscDIσ\"E>q~N?xE3::ijb= J @ В-4 S8s{ֶ>=D$UcR]PWK3yUQ9W*n] d}h@7HwNf5 :wx f^co#&Z:s\S-C47>[9:˦TM0`؛b+7*_ۈ{j٭h "_f)bEWx343͏/@'yO w,7sJSwyzf+X4,ѽdQtZ@y*N t2﹜Ar!l0|'@j:i)v9''?Ge˷H^j٩0VLPK\J/xH-smime/SignedInvaliddistributionPointTest9.emlUT 0҆?;7AUxiӢH_~߻݀Vq+;R@O=;=OHed~")'7YU~̨tbU{euۤifiWT=^&)م$j?fR,Y޳kUV3 q7(I("K|]KjE_5njgQLق$3XR455Nlq_g탺_5j6_H~5/-g2A2 k)~MܿpeTY>fa$k&lU<mD2K>p>I%n1 vf®'+ h31 w %\gpG"Nr/y{ s 鍕I=(6Hv,߬Ay"9ݤf+VnLE{m vh~zA*4av,?tukY(oX@ bykH8uCy2 }erEӡINŀ;&MajŇ c8IiI?$ʹ~Ot=kF"x!ss N*ğ=\tI3ꦓqN-nŒy|:|}u_RGm3sqX@=Ft\8:ԇnP^GOg&}!sKw4c_Jz]s0 њIDH^d]lƻdkSaڅ~a8\lp!d+cLloq<|[S@K0Z7AR{xS ŕ.6'sZ=5{>%iB//lTGԷ[#o!A^FSj&)0M0pɾm 9pK{fy:BL9m3[# *QmAsFoFJ$qdVvsQϑ&@s>?K*Y{^mVEfJ!y) 7Ԏɛ/˷$"ɶ*Ob!!{E.+_tч'wkAaA8RWx~._=+ :T.0ճۋ$ۆblr:IjZmVܟ"A7}^2$n-!fa9lsQ3&tvtGѷʉtpQGd4ujd4Tpy]ii5pka3GkhKvAvZ݃4-←qc|"uW o*_VƱDqgGcoO^o{ST`np y:W> l?x:V9p[&u&]VֽFZٵכl6D#?YܝE|kx~;ڦkGGsIy7Ix8."Qm kThs3ΟZ Mȉf=Fs鱔cyعhri.te@)ף~Ơ;W%=Qi KPi!<Wv`պX O:͇CuԎzUDA1DQnRޮ5A2Q#nLvϞ.f^G2K@BOK;#`!0;|{PK\J/!P 7smime/SignedInvalidDNandRFC822nameConstraintsTest28.emlUT *҆?;7AUxX[ӢH}>F|T gNt&w$Ax&UEjtW9a;k qҞ)ߺҝ_~Ix_ĿiT}=o 8>O N*E~:3~.ůc|Ua$xc {ju{^:97$-]y[{Rz ULǎðU3&ab]1Be>EąSTFTzgEu "b6} kwaK9ilBj{g6/ $x0yP,7XV PnY^LaԾH/V΋*(\"ԛ[Wi< :';U_vP>rS6 pax^_Ojw; Eem]gwq|s 箊k$wS! 5w (w0ӗƣc{bR;{mA&.e^;1U _e ghg&?&.$Ƞ PkuP5 %Sn5ΰZʿ4=io7zx 4|5Yx:up !+LMK3sS}xU}|8 .J-jt]{sWz Jx4,d.;H@_ 2eVrSEUhKW@o B t9/SB,ͭ9E=\0.,َ؞^@/A牧 ^`JF9g@gX=x0uHs" /g=k "Wx:V*o?Ə5t)Hsv$Mquus_3R!0yeQϮ:kmj[@RiJ򡵤ո]RֽN|.'7pm'EՄnxU:ι1Hzwk3p4jt^_c^+V3Fo 3 8}Upf9 G#sx d2R2 ӟdh̓QI8~Y'}  oLE{ҷ*icЧzW=.@\j4vr2}%sil9֑;m< t"IĨ/6I"~׵$3U[WyД8#*Ly<ۓ4j͕BZUݓHX/VWp{Bг@09'iT$O3Ly{Gx^?!~q{Ӈ  g޸ \/5p>^U!L dX 9OxΟ59aI#(<^%xxm.*@eoSY/ JpR^p9vsfxGsvR;'7qH>dsl.b)mwكtJI.{E8n=**~:J+<bPN&_Pa7i~jgǬ9򃬢=s~/{r {G& U֢P}mKhBc QOR(Z-.}=`E>,ean'YG.AGeo^ vn>.㑽I=(+ RnW[uT8Qm=tv?dva; d0.wFC B-:aDoMYp|[MTkeQj- }]^wqg3{÷[EwJֳX.o/ YpJP_0v?tnQ-VC߼<{Ȣ%ʴ4\"ݥ|>܉sq28d(D[[&|<eS sj(/E]f m7ʀVN2sءuhs8)xy^DHj+0,fRsO8w8|v5zIuCc !+`+y\+a$rXq2yO@85t%E _ *2y͊a[f}&MA,S*Aj-͖3;=ӏeÕAV5F!|JEai2$W=nOXC>p[{kIt_9 ⿫oy7gV}3h1fjk")5 M㎻ĸ(,.W%%P=-swpuES?*4lQt! 3eoql9"-{9?7 Ө dIS9ȕ |/k{C3a"/d(\9'5DnЅ_Iа8Fp#Sv.a3`77ǘ\͇H-.r`BRw+T=DB(sDש㓑PD_x~tF@DflMfZ_PK\J/:ۨO 7smime/SignedInvalidDNandRFC822nameConstraintsTest29.emlUT ,҆?;7AUxXiز?j̠AwS]cwݸO0&I\+J`mR_̨߰>\OaR';]xv9 }巸g*>7bq&ϓ{c"Yʋ_F/:PRʼnʶIٵgԶ~| _8x~#(X/5{Q0?e>C;ƽF~]fuER~i:dG)|?x[-w|~ʰ2i˄MںjYR_I~ %IMWWt BBk10l90@F"W62t +rYb>xFG|mKX*yuHPƸzFVـXc~w4yu?V̷ץ-r*w`#=6b!Aae!\<~f0 ҺLBW5ڗxZ1dM@Ʋ(cŢAeg#Z=· uj54FGqC򱫼Dj8a 0*ڨZobzh>>j37ȝ(ۺ2V . Fyj TR$NW!6 8mh?6v1%A@eA$2 C9aH_p goq5kVs6Use쨁v[uo0I:O1=!+, Ջ#!<=MJˆ] .GR,Ԩ*ώk5v6Roٴ4 C!}s}i;Ki: FI׻2J6'F^SQq^]Oׅ 5n5n,krt{vq^c'%|&7s-'Uy@ބjxE;NݦYx$WrОSr7 #7T51ǠkPF8J>u83 9r#{s as‰ Q-QƟ,`S_+xF5ED 3'GΟ\n=,bp̷%xs: D=xwKc,. {Ȃu]BXܹͨӓ򶥄^ι#؛^NƲX#'7Ɯ&q}![[ X rNG^pY .{*g]\g[7aSkQD98kkVnuuElYP A (t5,AlG󀥛oud }by/{2 N A#$aJhmv a[by!Kj@ňb%n3ۄAL%傈aqt#5&; ꁺ=:qn 8Q*fV]ɷlfitVr4Q $wsh֟ZttG|w FwS}iʵxq7bj,)r^S="E_y1 )`[Jkk4iwbIId?G=&90(rkhh2I}Ak})IV%sQLĢ@{Ñ[7}??ԊX\Vy/SbIVmc<ٌx Gۯ;gm5Aq yDou$]N QH^3|x$pMGfV6q$SUv38G'K7(T_P,RˍP9pDP!JP/m=q,Ӝrq0nBb!تMw!~ EKuU-9d`ݵZ_.oi|q/F{MWLX6'N%qX/gquy[ԗ~ymuZUIi\?ʱ%΂>ߊ(vHrygJl3aҚ:1&`xP0||KAaFzc Y{2[3C]yyFC!W͗$;0r3S,PNH/U&3JV9.Пg[ȓOi~|x.&ÀoPlKgv-ҿ͆}n<0RR:> U X>3QpblZAwNwWO=gA vA  :;d {+>Twde˃d'[ŝ¸,ql _0b{njʊςy&sQख़zRL\gVs wWc cY#'1ܫ~8KPaޢ4門O` ܕK5O #HR#9pUl_Y^ ` Дf%!VEzdQָzuְ`״[{0hY\RZA$-W/² >E3R={r 2v#:ʺst"zA$R'gԲp,hEv1ehy&g=2|*mѳ[k |wޕRZVU f}9s_pM cf-FNllakśFJwGk-j1xƞ(tH?N9U`qY,7|P层1  9Fo^g,(,%|Kʋ;NQ,A"_?.?X+VWƣϔՕ;e˷uxV*Qf\0 S`qYT7!cA5 {Ec˩r2\qrkCp!Ɖ~,PALr%X.d4 莞w}q}BMn%9J7tC+-zLqqwI|'ێMy&"Bߐevѵ{~ți?EN&Dx} ;.wVмU*u>D@Bȋ~F^".[]v#vQrՆ۶-i$G0|KN@]0 V uS/fSW=?ƅ'{tWĶ*b x( 's vO <2 F 7DZ_K)aI<65=E3 ͥb-vv*:PJ]DѪ0b+(|)(M5KGBszֲDzD3ZZ%@~z~=[D#ս3bÝȴ0}P]}{Ɂ%w!nʸGo &ӼH kY"gfWb(P *BL`VjPnr2ಭh 2k"?ryIorqwK+o\Y4սm;ifۄ"oޒcVU<qnZ~_%{\" >n>y¿.V/]ݢ'Tep)7m_[KSͥ}Em[?d蒅}~,lKG>}>Wt8d9Ӂcǘ0 ++֔8y;O*/ib9B|m|LTϫ1 ʱ#'7;ü:uEg i{k`[4yLVx"30ƍ#Gq8`/ATA&hA*@9ĽƊ AGԈ}5VYZʙx;`D`P/tiӺ'x遵̡̰uc-ZD+Īi{L<#w:+G£UZz_G3G=,|߃tGkV_9DH62Y3-pF<}<#63=,FP"wţxAE[\KQjmh(M>o]ǪTk.ϑqum(& A e[D+<-78ɲ0ǣT^IYca᎙km7ܣbsws/SF>Lsg$"h aRU*%tg#F"귛?v|v<=uU+uXpk:GB$ f&nµp`~n[0 4-U1ɗF*MIx2PU -;2 ~<19zF[`rӋaB)+#,? ~(2C ؂2U>Ș;y=˵rָ$q{]n-sj-na<whm%J9efY}AȽѷLNpݦ/\G"[ø0PBAao\B/WJo&2>nk&ncr1_X{ႃ3۸ۂs˔ZN!E(xʼ kM I2QNK!a런Rvj蕈YæGTTol9đnG(Fw 10>kSu& B: i '%kkX,{?vLΟAeCRwIceRAB%(8jj_oOVٴ99=|*<ޜz說ºΦ26wnb/(uI=c vnɩ{jj*}m`뵞i0;LHҁeϺ;(,K=v @Cd?cՂ?W3㑤/T×؝1@RW4Jbq-. DWwkpaE+VD5[xo_*\IAB{8JJ-a^" .t32yzjg| GsֵMEõRvTn#^OzQsvc.V݅s8;*΍;hF'/Oni/ S>c svVaze?M9X'O0_^Z#DG_j@,Qze,EpYܞbZGg>:D>yپЃܮU3=#%c]?|;;p"WB;XԻX> QIO iQE[ @nuzK(nݸnl^p~XSa7x9>,qʪph4`"LKrgfӇ+0A3[ԫ$~o ¥ofXgb?6 E_}Nd C~'DŽ0iH'%vVnfu{%{7l?>XqwD az++Fetڄ{K |+Dd.\Ɓ&kaԧCh|6]- d%? ϻ6;\pZĚ"Ti0](j,e^x$egwo.NO<~5´~u@j %Y%Z~O~=i.B%gJC{ݳ^^_D!:ZMTnp,VGkf9Yx܊5Mq[eYCM'*,%sUGކrK +p Ba{ݗuxަ,%0ra ߖL߈^"!~Mѡ-C4pܓ^o:oQ/5w{Y"ʳWez#-A@cz*JSLiL7*xԮ B }AḣYVj0 ԿW$Pw!,Vfp02ۯ`h:MT;{ed,Yӵ wO%5{kUS3bds6%sxwPK\J/P@ h.smime/SignedInvalidDNnameConstraintsTest13.emlUT &҆?;7AUxXYJ#ݩ+uNt&; Ⱦ!K " ~sީ0 $oAUVOnvy]}~##3֦qiO>N>8?~Cc>K$m0ź4?#*ު蚲umW}fj>SӮPI>X"7E?7&ěoAH&~gxliיppwOֽ>x]4D}|_~fwb6,m?U\'y>.ݮo wM{&e*ʾ#ր5K&*?6 rZXZRpOY*wr%NXf8Bs*:Ps\ie‘MLѽ!R3Dm|f«<8=Km*=ZQkli֑'x$bNW"dsH9w<˂n"_ e4 0DPEóʺ: \j{>]o rX^#O;h'լk~W7qdx _RBeF8oWqOg\U$*ΰA:ǚ6Hm5f=6yq?WϏ6*`y*&d!oQsWZDR8h>~r=TYT@u- `-jcan!2npUEЦ^|V'1 yA bߑ=52בSnl'0TQl3u!ۧ6VLgfC->=tCmnrvL ǁ/'" ӒdMnV엱I2Y-6x2KA`MuCd}RyR]ͅTovI\rޝ@>X2 rCKG;&a*v 2#0%N=: C>Cx7D@-C:Gn=8T=xXv)MyUٲρ;$ѴoL}KSTSMKU{xouc>X9TnV! ?:ce0jB/9+SzĨ:}]QO~o!k0C<]Fk9 8I=6^;H7*/#mz>Ve@+:'qҶlYF)gr.HD/iBrZv4Xqc ;9w"Ceg)5,ʂt@зfU[:x.[2lƜ7$Ʃu ~~:˷~1 Jc}˯Gcb 5Kr~+*Z1 so52O?ta^V=!w{Z)rO<,8(?_Ȃs. 1M/j$[gp-777}{3CD ߲pd)Xuu6k۵}JKؤf Ξ?ĩ"[#g};^OIYgi$KU'\f'HTk H5"OY6oĕق)O:5y:pW|H)>heES$ÔZ w1?%mcW46Xa0p2~й+l 7:nH𪋆I] tǾ .vUWk $ sQi̸{u@ώ4I@}fixfJ%]7JHALtsY>OI`ԅy.ns1[}inޔx% Qχ=oͽ|Џ^Lk^]2MwOppZ/@҉ $,R_dB>I> X-vr,00܎͚E{xYo?a1 ג36\|0EvJ&+x[q -KY1Άr_PK\J/S .smime/SignedInvalidDNnameConstraintsTest15.emlUT &҆?;7AUxXْƚ"xgHE'SJ-h_!!vORc{="*W- 1d'mwoOtbV$:']%m>SZݧߺK['QM.Aqx W]LNz54$bhbE`t“? ho bh3C^o3|M'dיHruO5{ԓ5tLOq?O':/7/k;%'TFU|.oa%KsWWݹdA]IӹH²|@)/gHZU$LO4L jsba%aY*wXEXj-oVi,˘(aޥ"ˢR-b>ԃj>\(YQ{[zjN[[l/*gxׂJ \=CbѢ(ë}E5֍#O' qYi*$3k_fh sb<69 ['kX\GH#6 kok[ļ*nS-GYRiBl@ 7 [ a@bcXbvLP&֫AQA"usUJFjz_sYGcg=YJwt3vvTt l?ր gNxTqB6U9u7ͽ`p24 =rtd]Ą6-m/[lY(ۗ\XU~T2o(~i*?PQMޏwf'Z//6=3#rA&"/I{E"]/)(X/]SObH&Lɼk{=8F>V NPVVЗ=rug tofbWtt2٣b2,-Yo>Uh#AW.Q0[ky=J ~Zk)s2}V̳#z i@Гē'?o{sJcR9KU~ոx/ywϷ]OW\7>*wsv:97P΃ocC!Ϡ6ufI?|Ysv̢-'JT,)5uj]80Lh0tF~ħ7ĿUUkW aHTn(Ak:Lpa?ϕ#F 1%pbLޓ y`lK;*o߀9y cr_beL G2>NMj}o$|udenqjNJ%7^gQ}=M.Ԍ{^8%{1BJ0qe^tlX0.݆vܦ.|Wt&>yuȀ*\O' ӾݢH.u%LH(bLns$'-i?s̡|RL'U}K%1WK)Q'c5c Kd7wzJvWCTNh;ovӯ]XS`#v+.[qL |釽+j-7yCda AYۘehnusm[04ƢڱK`m={|m$h7KЈ5oq.r嗏 PK\J/YwZ .smime/SignedInvalidDNnameConstraintsTest16.emlUT &҆?;7AUxXْȺ>FuY-"Vޱ3;&AD@@QVԽ{kU&i IXWoOtbomcZӮӶ?qշDh[VI~gy4Sߪumx¿$]f'{?""Wӂ HMAPo$NKmFtW?Y| 7oNqt>ӟߺO=Kw̪4}t?S>^V!m?U\'*{.L]Swɰ8?2rɲԁb1[1`,w Xw+,<c[**wr:KDg!&*_y\e‘M`zH$pbE9wWtvbs UKk-:P&}wxQV9"YƔ 㑧cYpYY&{5@828hx` ~Ib|53}<%p0H,΅gR^ͦ{̹y+MAD*ɶ_9Mi]%ah{l+}cXt3zΥ{o.CC9X/!Y D7fd:oL= "@/y!ͽPUmF(pM bti>q _k@X_d:? 0;]Q 312wa:A^6וt6V%XmA \h\QtZp[QR\?buS #ֺ{fձH7rj-MR7>8YWBj'+}u}>j$V&5 m$׼ >xjocxyūa+^WsYZG#~A0@1yh "{fE:}z{FXBp`jVQm׃"dq5ۏH_j3yȥt`:Y8si5aݬo ƅpVENz--EQl.@A+ɖ[ sp1#䴅 "1Kiv"$QEx-QI݃aX+`#OPfMOO'F:%/eb89O:g=ý)и/o#"HnQ2Vg$Ȝ2R?3X"#m$63םعөX#ߩ’Uɖ%?NMӉ~JhDItv2 Fs͈='E x3LEg"C$1V>Jb椸n 9t^k9P~Xazص,ĜeN ) l`!cU?gX't>[TaCq20bE|;VN82,9_a0nЄ&؃lf4,Ҿ *+=m/; J,O- !5 Kl߻-# aVo;UR7Y^E2,,’kG}ڒ&pQd,PK\J/Fے .smime/SignedInvalidDNnameConstraintsTest17.emlUT (҆?;7AUxXٲȺ>FS-Tޱ%QI@FyZݻVתa$ߐB r̨iӪgzNw]5]zI}%o[a|0|Q}~UJlKˮ}ѝn>QzqIb?F" "k>cŸ&7{; È7LC ޡm5u nYgATE[ԡ9i\F_yϿԻl/Q+*Lv6mMW&@㿾]uǒ]"{E7D d N cpcŤAgX]P RpT5U+Ϩ{(X֓$*)4 PԳQa ^iǠH_ 7uU^O0r4P ւXNlpԚz6ǽ}`- VŜQH;Џ)u 뢚-P!S~]f]~k[ 1RRń\xIcMqll@LX9ŖOV 9:+#Cns| B@M lqXZ˳r V峼=uIq&fkUCƕH_N}Z] &TN@(R ևkJ@U!X,pJ2tqvKTk#1169%uֵq|x =Y΅|ܜQWqcΜuN-Rbg,(H9^کh"4̎BiH X)iۄ6:h \U2 d1x1ڶObU.^w~WB#6#lx9Lу+4ƽrVN+Ͻ*E 5q,Oenuqea^er*9"كC>6xM.)7J?~y/)g+:"! S5eMC5r*qw!vpM z֔"'J輍HDV`UH_Fۤl%7|&yvw=/ǸʝRU6MC/x5;:2kZ}tEb3!DXB݋rWbiv``AiL%P{) C<˭=/Y:kALb|bh}W.vw=qXF&Kj h5tq\[wr c񸃢r宭N+ q|sُPd?FF: --wyp-cDYƐs$s,]k#OtScȇki+=2/CX5EP=XUÍlo@If`ӎ]9bfGl٪͔Cѭ36m:/7VuWy *Gbɧp=/nɖ?HOFCgC9|"{q;ԧdmm.g9(K2|HS||pP$Quoe7-digwԨ4;E%okLBwu΁M3RD ?Z~O'Iܠ謢2Iߍ@l+\i:F5+x o~7ZPd/t+bv0t,>,,wh֒SM!&]w.6Des`g4!s(b1h|P wFX!c!u&(۰p;]LH%[uN\tH=b>("Σ/ >8o?V9_6WOQ-# hNBP8G 8>qzZ^ rtr?׌ƣ甶|:,5syvrw-zSF'!K# GI`e>1q4(Aεwg3)Wk&, 0Ei,l[ >{;p pl p]nwFI땜d怚@4ܒOdqT^w_iOx,uj]ur[_dU%i>JGNSm!3h ۇ/( BJﭷ;\ƣL?6VT'-})xCʂV|TÖ/ǫA:ё-l,M B:WqI:ͱ cx '"8kZ GOE ā#^YA|F" {L=N*4<Ƴ簡Ox4,՝*3eRF+;{ͥ1^Jްw IcN2\d<2kUjh& +Y-L0w홚$fu8V{ NߚݫPڪvՖhaF.q&V%J`I `:v 8:LE+Db$[j^ıRdb_jƦ_zV$h{n1e.B(caaÛɸbgeZUV3]y0~(=.iw>gxoZ;y@:v'ZRÅ,47E79Ɔq]v3#6aJ{S)攖.E`oZIOE`,͋R8zojü.s$pV8ԇZr=C Yy޹S?ˆ49">TBZ.e!t|ЇyLB3PDV0]Sux!< 37zzx?7+snt'iQlK֫hL2&pw\j*l/wyO? ~\RU(rٔnkQ#Kizlov%?(f}v C!|_L* vĞx39Ὺ"nw&g5>91G{JnRxhu pv^`K^p vgTzԊzI+fm\G'S c&̢j٦n];3t}B$ ~N8c&ܲ?Hb݌"zF4$fsf ᬿ _.+%ťͷ*_g[:E~:_߷lM7(ӏYz)\^6@] :K21dYzw4|~*CcDzl@L"VY?̇R1AmAwT٤h/#vp 6u92KH1ƥv$Np"uu9͓Nz'`wm5\ѹӷhm 5&* `ݥ $.c +MQn{hsņg'e`6tI[z~.̐]"6_g25["QڧKDa h]1~fѺN)\vr8M/./{3O<ڽicʼnP62Xq=΃^0䅾t< ^d+V<|@|LK "{?g,!H-ˬ JDFӋ;̫eX*sy=kdL'h?$0c 3̊0 x~ y䡟l6yx 3X}VќvX40/z!߃u~1(`]mp^jz:ltw) -, Jsv2JxBJ婣`ԶwO=qN'+@ʳ Dxr@so[)폨&oT:`PDXaQ ! zG& Y *g'>}!<|Uy8@{G2}kȿ~,5p -P$8mmctS1(sVw3l tSN!Ld&gpne8~q~){>Ks`G([6;W7hdMQcvvF뵬7@ϧ*ϡhK[+2t$dޝ.Rw]dFĥU\UP:x\@/`uN>.%=)t]&' O]O]H]'H/wbcnm<=\M{5}rv9uYiG`4u:9oD'##[wy."Lp׬#}N}]t%쨅vܠ%Fn:aXښ֡7$Q-n=>G[kӒoVYi5uL8B 2#mPJLKU)hl'uf("&8\ Jop>rqow|w4uQY~bz2KԳۻ,G}9*m"H;lx23t˳N>,/UiIDO哐4²1vUT-IOׇuUPa|%zcvh=2L\\0:\鰈kqf {5 ,8ҫfUw!5g#~Bg?hyʽ d/jK{ܡX-J&H>$9ޥFט lyݭs|jO=Nt;v[x'Jh#M }JFxrm `%XNcwPF”ZP4$a~tAT '%lͅkW ̱>hE*BN$L?N-_'X72'AD K3E3*xY7N'O?]?G}"/H~:8Fc(\ " ={w΍GـU ud`5-Satf8ñ3ǁ|r͢~^9qՔS;Xסu HYp :Rr;D vncDΗg&ƦԧHzVޝ[ҵP/7V(*HUgj>4-s ku3nYѡ{Z @zWDaXrx u:9x(宭?TG=?G՟86 1x^5Y8$n:ٲ}UZ4DZ$0%#/T3%|; ujt16X.*IGQVw/kc=EA`.;BMe<tb1yE$2J} c-O={S@:2bBn)|sx-{@QÝ|c@cC,YPm*zy+Joey.&el*4^QlqOЙ/B/~n1~! Y8 X0*&e``1hАWij-Mj: ,y}% 6x7&u&C9xfq$3ijX<`s:>*&_tqf@w|[,A3{S!#/ɰPb&C>j>A&#npА"<\oOނ̓0>^nÊKzߗ{';3V>x}= jZ"">tRׁsy8Irnyq􏵻2&A:~k2Gt]oUU?ׇT՟rHe9Z15R%OkH1 p⟟˂{<@5>x* ÌS%{B4Ẋ)t:)]FT#&~>˯9Seøm_j=n}xj$mtwd^^;6kb7؛%vN| Y!Br]ckhe yPRfk5q1wIYTU 녾O41GJu=:-ټ-ǻ2ǿhz1U ¸+`2 ˕(ǣxN ϡ jߧB%/WMO FMŬ{'U,w̟=ؖV@+qњgE p sf p'I`u9Ux`nP睃 c/+xT;'|IIxAKy:WU1ɭ|*eVz[O0nXZ28ǒyHEΒk))]H-Z%G_csڢapa bQTaebr BB`I*:fw:(LU+$0O;5o_\d 3eLыMC"sMg!'+ZG[/$!(10RecofR_^b\"auTGjH@2giBדn(X-ꈹ@3-9cm3i%%{4zJ7[vR]sǣ)u[ҙ26yӮXX%ͰFkw̚ROxTT{<\݇ʹ#XtYJ=wn䭲-ТXG?``?0=( /w_vIpT8U` . rH[潿nMc\פ0 RM<AEOxztp¹9Gm# LεN)1qAϥCsJ2O4sR,PQ X mJ_v<k&+7iP . RSO$ڷ;]Ia!Vǣ%:"ZHe|{r fy,SqYL1`,MR mg4wwo7C:lIR-xF$TsDg MS,7>y'R;XYntl?خfn&~yu|7D}CJ%7gۻ7uFL3nȶx#n(6"us,BUCcz،GqvgUg,p XЧh`> 'Kh 8q-Xj. g&]$!iQE]_Y]dN9:U8[& mÝާlYI", ˍ.5~XǏ|[| ߞs#;0d>Hms^/U^?M/Y5O8xW?Vگk_:lN&W_p\~aVO$/.,[9um=T!2SR)zH-;2Ζ34E6} tMyZF}nϥޠv%,ȫβo|SβqFEGޮס]4uPم,eȨ7na<Kѧl4׻_W Pqw"-f6~'T!hujse;jF%lMw#y|s WU-p JUșAP) XhH|ɟ-9пE9z *s'6^MsbYG2eqh$%#hP 9Pݹ@yJM0-.YގGt8u [WŴVLK izY6v`#2Uc ]w,iz1bTz \Δ@+n~҉uKt[.f?-QJ u5{1X:6U%X;Wyt.'3#n~,W[S{Uє;(5w#x 4iՃ;qY_T<6ha>/v"+5>;SPup B\Hc#?W'sԝ?hO sgEko x94a~wNdPae-4cʜ=l6?뚚-*,O!0t@Q݈PG,OIdz!Zrf_[RaW%luVOP"bV]wꩻݓR{%D˼]ۻ*A ENáYf#k3'C4#1PGOrOQ󥃛ə guN.Q.,I?g =r?fS=6rO'S# }O8QDq}D ߙ y<IE8)4@պc sW:m l]K1`X)V mpJ$Jg \'$c `)XN" UO垠P1 4eYL *O Ia =SCedv55 0[.I<ӏ]+N)5[52'A kopM2Fsx$xQrҷ0:ΰ܄z릪rƉJb{|ƣ2ZhHy";7axf޼zHCf7n}gNTM$"WBt0k,RMYSv୥X]"9PK\J/U/smime/SignedInvalidDNSnameConstraintsTest31.emlUT ,҆?;7AUxWYH~#;UdG/ol& ,IU#A'}')HdGuۄLGf6 hFMDu#>6uM/TO}(˒pkƤ+hI>',E}f{<巉X'd~o z2o2-yWU)ݬS/_Q)ZO}\^ќPem{M\'MU6IJ׶^DdvR\u[h@j8]8[5'RFB`i$~qBom9OfC^ܦ%L<]̺3,urXjg>ƣSnwݹ9lO3KwDy|MVpdE`'HϞ*~+:ǍIIyOv]E*GMHLޘh;Y$<=LS-M#`Z}ؙ.+ EPWiOa`g,pܞNxeԷc]Y$:BH gB]= 1h"$҆\.Ϩ @xY&%k7QvчHo#gY_Cp^=;%5]p0S@VI'&|G8ubW ¾%8'Ϟ;_WԺ;1/#bTK%3$6xtT>N\4v9mbƣG{S43#$RaNFx;sG7x_b_.p[wtfӑ u^4a¯y4_z}IegXt<$4qvӽeJv0j.YM IWC'*p96$J~&koqhy怸~8>@6|pMl38xAz9:Cu,()RHtlHW3Ǯ jMQ]Z òcjMWaډ+ i9$[;l}~F4#<2| N9kcq7KvnIR鍌m/:֭8'1ErcZaxtUV{IDbqv<*)G5F/s)[S]»h+fOʗt`άUc r햁RW1rrf ghOٛE[,bkt\2U0qv?J>{Ϧt8hPx~> M%Gںm7x) gb͐sfinz9bA 9t)rJxG?zV!xf Hp{5b,a~"o(7z˹~KWdH~чw .81;UM\p˴pb밷~J$V) 1Ÿզn;;2kgJ9OV~Fە r/PK\J/5N /smime/SignedInvalidDNSnameConstraintsTest33.emlUT ,҆?;7AUxWkHFTV EyxYF@Q~ޙ+AI'H|}||QWqTQQƧ8ȟ/ R]&*¨'Qоeq8/hIEMMG9~3/Á@<:爡G4͍c'hLh8 [WU3(UA3S`TN35{pi?sYeLM 87h(u>ەa: y6+NUN?YJd.ejTXA'f#J! Kg6 p!mJs8o`垣I=Yعm y\/}Ns#rG)2 Fn8pWjh:xyne[!_qgwxXўs\V"9]@-2%vzY>TVgRK:x@CuT-W}N0D @al!6cQ<--MbϓngKGeKM,Yö|(]%#t_Jry{nn\ʝPVmml䢬EV:F r*F}Vz7^,%f\D tQDIsU2zi(){) $)DD"=X} M+;CdtA~fAyi/DO4CFfzC JX֩@cK %)<ɣf'H`h}hq^qHbV]gj%`k?N!ӧL^l ]k!ա :Θ7;zNvp>gJ`*Y[A@x9lfGb[d?81ݟ,Y%`+/qg5rsRSJoOE'^fASR8S`~jmL.z.3+h %O4{Od>ϥHB]_ MvsID{֐"vL<[:lf|(yQ޵y^i7qvy c&TpIeK¢8iM>~lډ@هs(q(gGrE\wEкߌG)B9loeVƿ[|~oߦ:AUr('$. !%ZF۽{X>ϩvҷ;Iy{WgЃR]3]u7KeKy} @{yjӴSD$ nL"kĉ3Ϣi,Քv%4 6lMSh>8z1i\RȢDhҠHfBϘcZ۝K/-Ɨ4U/5=Kl0qWݑ^Dj´w1烐Wj?ݛ)AӕNhCN&زRERˎL;NRԌ/N˰$ 7"4X1o-:.UMZ<;,De%n:rs#$mZ]0-[fG0H-fVUԍ×8o$(EXiW.xPU@~wˁ5'. {c=ɋەABS9q4KX-p=ξ 9j>?؈m(G+"K}*/jGlmXitmƣ%K-l[S,aNe^j9.ɢK@b 5l&ɮA5['o_-Ґ_l[\~h š$i_jf3 pz[;tTRCl tⴐ֬[ޢd5l̆{xRgڎ10o<['=ѫ[l%o.t8923͔tRx/;M"hTP#W[1عv<Uv^twRRQ8E:>9 _G;h.0ҞkaC=5n:~OeAA^!}vBARL'?|˛* ьE%үBàֺcjtFYey-&{ tr4ф/&Oќs#lX0z°+cܮɊXY, oP鮿#%_\]P-T %qx{f`OGߟQe@fU5{@ʿf X# .KEC25@A2A\胃켶Xj™-cR!}[r)|T^q[XRԬ<.?,x-#ौu3meUy#=t<=9&cv_7G_VE,PK\J/F.* _*smime/SignedInvalidEEnotAfterDateTest6.emlUT ц?;7AUxWYעH}?TX==3IVMل76YDA@~~Sg{fDAFĽW,cݛ,Ζ?QӉQ~ݣ Ҩhm {^#?~n:묉0(h4([pi A[O'8j/^\QO4eu&ӿϖ3r!lNl:ʢ%{b<+bUUlQ]fޢgKKl~iҸ/z?O'+Y{]~%ዠ ":&ZMU6iN׶^ϳKG}Xw]I@ Y8 p@;1'fa)a>0Ul8~Qơh}ܶE&v$ 5Ѳ h=xyЩi+jof=pճW!s)*Jpt%yt^7*<`ĥN،XKIdhxj*s1U ҘNxDkF[Po&$̞diG?Aa!SK{) TL_aC[O'k ֚DW,s= ,glrh0=G[l@*|eQPˢJ݆S]s?44frX1 w@wtk}s_."bu(ʎpbumzǙ?t}GHkMҕK]wꬸ[xqMh ?N% ʼnFQ/ 1 Ɛ}'{±m ,CmXOiA5Ś=@3^vFj/63BpayF ZBУ Tqr!F, 1pk&FÏpGVǴt:ѸYK%s|+иd>+39*K6=f#Ks[Jg Ϣba82pՍx#]RzZfYtHtKYVB9"pA۱8#0?yuOʖ1ϑSĀ9ugc&(t [>`ЫR2Aq[9g´0x X:%  =cPظ*2Av7oA}ԧр v)!dZŞ uT`ƴ<͋k2%.o ̊Y'>x!Eȕ{N8΃[ #&-Hތ@{G9+|',Ta|k*n{ku:$eң3O1jo*- 0K~Row-ЇOg.azUB7j5⤩߆}tpΟLlYK-]Cp~kF_YɨH=S[.qIQoN:E,aBeI"2{.oX0ߘ-IY眽`U&m{x[?VFZew=D=>|ymyGAŜ/#jK?ۺX  s, Ǣ9]f靖5&a)$9lMEJ hQb xk/obRFČH0 j UeGKPF~O*5 x3SOYKX[^{@|[-$W/ֆSZuUHG8g_s^Úr9DX9C@ǥuw2c<{M\Sܹpµ8 o-N _ԅ J?H)D>vt|̷JX8Qޥ/vdЫw* 2PugUmi^;o  #{=J>#2 26dG{uCb:h5as|ڊ/_PK\J/Y7:: `+smime/SignedInvalidEEnotBeforeDateTest2.emlUT ц?;7AUxWٲ}6-w<WiJM6Zw&F(Te'SHB37iU~ȯtW{觷4,aMwqN{U|̚ /\w c&O7OʪaTg:#5i8"4I\WjKcӿHbvE$?h̦*[/p햿VS[2|)"mּ._Z{e| m:K)ww& _ү?fۄ\شUMھm[O lmycׁ$i{)y2P|6Sgp=Ɲ#\+q!J5J5żs*s0wmbJ%o>mOlL4gQ+±VTZӉS06\kUR@ENJ%3ZN[m)FSyf& drPM'ۑa@Atq,Z@83uvm6),wD ip0Ai^Ʋ AO'JPyZrjt\gct0z\yԉ/#|GfRn:^V{u4 \7sb;:\k97q8s,8}Jp]l&=Fvc>4t767vo>'!Z)G@ӫ!@]QޡX\vȉ7<'%4ɳO@&I;կ.{c9]ϰR)Y@x_p:Oi&(1׈k Ntn`Tex[ ;}DY#H}X5X̰=JCEQXF?~l!|3*C: 088bQP :.:G G0 ޼s!=v99R &ORAEɎ JtI(sMp༥©۲*`:Y]A$XR7B4jgN4YTH4I[M 6V{]_O)<ы [wqc5`A5#XjA<}smzfO^:MU'7\/ʄɹ_7ȯW),߼=Ujt0|G,ף ݗ7V$Hx:XCNxCVm7^ãUƱ_*%#d̷8,v_ bW>1/&|CGӠM鍨t{٣e!^ #ZVy)hRR'Lq}~&9\\ 1Y!yMLRGJ^g X2qt}-`W߶&Z$ :W#!ϺBc0a]͓CGH*3G~'*o66s16 izqB~V:۲M p/C4>@Նv ?*׃'}C}X}6 }Eg^ օE^<5Qyc}]~=lBch #bJeVQ{礯 c!14ͩړ,"( v2sV0=AϏ!cg5FIXO?@w:qƻGNU?_)V@X_'#d_u, oTwgU;3Fh 2vRªÅ5>gHgɑVonK+=l}})u@n^$bGI5ٮa wYbvVOE;v=WO e9yB*π_9 ;+?OΦ)R?@d?;/@9at;)JV˃ ,&\PX|QSՄguzdjYWxnɢZ¦et*pTggzV><nu6=xĬ*5#|9gE*Huln?r PK\J/D©='smime/SignedInvalidEESignatureTest3.emlUT ц?;7AUxWYעH}?T"*_̙LH6EvDQ~~]3uzE$̌{oD$R3+1XDͿn\N(_e;2I'0Kc&mp3f%-Hf =hI]iE?f hx]4WjC_ w g$1E͌"zF4~9_+*lT jQ]z%/6/I%oE:~O *2, d 4MD2;]n.Mʶ<6ҁq%^3,,9 H0|qb4:NtXnaa4tVƢ9 E :9*[̓UDm;yC!.Ca]fN3)Loo:w;7$>N#VsEHON@^vi*Y%pdx ۍHUYG 0Jk:Ao xW?hG:>y0xR}5x o;  P5c~YMNdJ 9oG:R9hB6r|lGW gb:I+y섁n **_6+۸SMqO:dZ6~x5dRgBNzeue]ĝ꥓DŇ`|<'g:w§$3@p튁I]QIE^`:&_$J{MvR3r 2N( <[nP2bD6͔M:x[ yѕeξ/O}V-)5|!@ц D2B[XڡD›HE7ey>"G[ X?#).";5e?eqe}Gɡc S{vpLkak00 Օ .~̤MZV{\L)G)i-u/2ިl柧j|lɃ['5FϩI6vzJRFv i?R=EoR'.Ԑ7:ԍ&= }OlV}s^*X"!5J5;}S;b ib*VXG9FX`>Ap ha~;ij!@ 26}_qQF6 .L-8aa%RQBKzڈ6\H0s_NObCdPqΪ1Tq("{tMc76ʱLfAvҗW‘:DFѫ Oa&i6O'ݡ{;*1 s i6|SB)tDYЬk6e0>1h[`:FO;`QMMr,H^= ҂(('COqVdM\EnChp6=׫9/&>*m16T*T͓^X 6 O'7$6'ՊZ[ga+)Aoz bQl(eozl-aB4"L"u`^3dY]fE)=@s<#㏞B)8zZ>L,HmHa&/Tq|ҩ#F R̀_18cj}_[LZܰQv{^+4gGT8g ꞝQ\p| QepCfmĖu3JkӅ6"=7wCF !1+Ny`ElNW93?b,+Q"2 g]\0VTvObKW}?/-_WŶG~;h3a*ѻ1rDnzΛk_x۪/;V>^%ʇӦStF _oO;y#< :kj6a]23,awgax7Ebo3K|oW仝w5cPK\J/\ts' |/smime/SignedInvalidIDPwithindirectCRLTest23.emlUT 6҆?;7AUx[HnAtg&j k rS~)]ӧ{=ѣa&i/3A*9ɭsŒGV9%QdIK.Jn]fQ@x$s&U~ryuzEOTx;O* :M,97m|So 27.?#HHn2gn²`'S&PW57T?heuo\vIQ[t__UnAզXEuUsm]fmSYeuAt.Iɿz#UbiWϏHF$T@A\C,ؾA9x kӈY9JA|Ʊ,baCBYj¼|*!Du'4Η.c#tܽj+ .f~}#?x.Kbh^Ta\T-"N?sN#~Pc%p ?z#Jȟ8)#16NEz; &"c3ӎ*gK9(HG% VT2/y4Y$cbxK8#ӑߧC17\'j-ȂE:cREGWy|/! =`"`OQ a yhS->XxǖzJqaς{D̴XMVGClάk,mGy_ۤGM>|rV6WG0M9[X(S :\;f1%@3Â)5Q^01j`O烽 a j:;&5͂b<<4' RS!xe DgQy>W#E,@d#"_XPf< xYY0߃%ew~t:پ/T+f/sDL*d cىº,b/R]UO=UiKvpsya7)i-!Z[{h# dsWNz+JEX]0C1aÏ Fs#lӄDǢ~E oGc?Kً9{Q7ХǥiJ2ƴs]Vx m}~{@u@"*Ր@KNP3cK+Ccv23q

|k X!0+ .ԖFvq덾w+9vJXt>*F32o3h{Tf&Z;C1XPzB`$@E _] fKL3onZ,ⷮ%ls;Gr}褈WG L]G7]/ EYUaPn S}6`?, `L\PQ}/랽]x*`Dfg>%Q+qHukM|Z*G^|L7@'}Tk^MVEM+DmD&jJ>4ׂ,X+ WaxJ! (}RTE$Zi-!<h_Yp,dDoS9QDe{'J :Go.hܞ9ƾuy oz0YACC9PeHP T>i;o\šrUW[&0γ[?ϳp[^Ipg &t.4)`'CΒRP @|=L>,9 Lq3Y]JTjTۚ .lY?]=f˙ޥoImR~V#.(b-eO"q+,_[w}u?_OТهsonE=j* (D(2$)Sį%f1]:U)o_5o^(|8ns?4|$ {>m΋ ٪|*;>}uMXsZ)th yiOAi+)`5ªƣhM*%?6rቧ)~%8ݜO?%G;>hM#!=5sWv8&q=L.@q[FlVޕGC.b"wFaT}cg 5ڭc\{jGV]|Q62istS" :;v7,Ij~=PK\J/Q Z/smime/SignedInvalidIDPwithindirectCRLTest26.emlUT 6҆?;7AUxْ8ށ{4LHW,`cyuz,L9*I/TaM6b`y]Ҹhv8\CysKSNo8׷ZòHF*ڌHq=:)WG..pua~R̔e^ϔ3??D~I#u1tIJoSmƎ  BS_?}Kö-_MS-?UE8^槮4ouXѱe.aeXMR( t1 *Yk*:(+y_VUXnGA@(%>(0.(ǂ|`3G]Fu&Od+R<6mW0d(~;gt9+=pSfAU2j poge*^seUI2=ݨ?pj乒6STA_x/JBI'|?#`n4p 6-­q>ȷŵLhJCl`@k yE I }zk]luj)>2|*oI%u϶T%i9iop wZLmH>؞W^R9,8gQ)WFr@,5 ?\E-U>Se+$Q%zhvYL}ʬÄLU/NXƢuYrtC[pq_e}X'gPb& cW8 ov蒅=n=LfqmV.:Qlf ª0 R`ߥ 2ﶴͭ-nxhnNkqy\Ϟ/lY<O pB@Б.4 SR@,yk(6HsV Gf,}d4:sp #K.}5]_y? pm[#OXъ%ȓ׳ć{ T=9/SW]]!<"a"cqƈz9ȥF" .`{zț# i&B-YK'~k Nۙѡ繺ʄ4E3}'@SrWۑtv[\@]vON`7ڀ@Ce*;{g*Wn''Vfl]"^c9"`r~2}/ϱUisvg 8pcy7ۚirT(77Y}]g:((/zόYX ۣ@U웎!¢[ Qj7ǏP9W$P:87ǝNab[[=!F'0ǃl~88sc;w[^Pn30AFY.N__o{S42(y8OGξx@DTIU[L#S_d1I {$m0(%x¢N9Ae cRFjp3R?'mM(Ca 38/ ʲz!2,˄!غt: }*^?ʰB|ca" x:>:Jz>Y^02ޑy>#|1;JW)2$ ^afajvu#~qYsg ˓ҊuP\Y]Mw8l3+U'A E{OwW/xsTՇUp8kV&8sκ=[U</##'Kph.\RBZ"`8TM$,XR8p):qzYb+}Krj؞2c+&kQjS69GPJke2;`&4iPzU&R %0( r=]2eIͲ ]n3sJ&A#A,]'k\a6 3/e5.VlF؊śe3;?) fFDaߟ͸Jz<_4sYѐ)h'wFZlA~6)Ife]}SYg5?dĕr/xsD:aiނBJVP$[*9dw3Tx[S$9v/ʫ$(oj8'3Gw+ bKV0(s#ڛ^e|gifJN<3魭y ڈ[-"O{P,Y"Sg: NRN{9%\+)Ώxv3fLўc^lGˏt{0QR)u/)PZ%n,Lxŧnbx@޵ +rl2yA=WbȼQj_n8~nA{#2y3,tduzh|# N!cB,7/~`yQ#y5n x^-/wWչ=]zLNf#ܽW"DlS)֑F .|^cc;;Ej^wNۮKEV'k)Mj{G*$J8:RL*T5'['cOf& )ݹ*"z 7J{,BE,?:s绩a|:6ޕHc #2%1>\QYvM7=hawDi,( y+oCWZ-M#aPwqq(⭪ng56}I QٍʓdcY݂6=whmo/LOaG}m|u]<1]զE,"eW5^Fu6.<3ˉPC"c c՜nmеDLD?c?bt1$]cnb_t88AF')w5&e&E  Y} aJ c,)Gv۫P>9W.}^ \NIyMmFn7ǍW,b 27iƲbtt钔;ѬBh%F:=zϘtS}a% Rg|@{OIS9hw:b\ۑ#{mNѥK@ҘyGeY?K5c.}r$TҞϗZ{ZxN\yjr}\Uts^0JEp N*ʛ\gX';8) Qb2}i"?H9ݽ$xY-b|1sL ֍o"8EE8 EM9 ARYe>cʢC{fw*{nUU߮q>|P8*[v_ 7Gha+2spg U[ݮs[⿾\,yGE;\^W3%),ð70lHa!;M5++e(@=v 5 XMw`#pVXM{KKn{Ӻ;6um8Ār gRe2tJvNprlŌ|2+JE|J]Hg0}(2Y]jxr{ LƲAH#Ղ43ZY U;): Zr^yzYi-ʣd5|Ь+F:I) tQtxF? Hw Y$so^*.rj6^],qhwS0(cRp=$4ȧXùAp9I(4fT20di~(jc>wiMVq-lI,ޝt#rM=pk봎41 ԑ,E+6HIQÀѻ|eHqWieW*F&-"w;4% >N 'kۜφ̵ӲI:ʉfZ\gA-9>LR&cNذR?;Bg#t:~PXqghF<,8+\74P=C u}[J{{1_Ms͆[K﫮:WBܞ<4yGL=|I|_J;kI {ZnI+àXx,97E] _D:Hx ūT'/[ E"Fi}Kca Ek{Fs ͳeNmr[]Y]R9$_  bB*b́Wdb$r*ĝJ8 OPN_'ԑ };4CuawF>sYϫ?c+D3՘{&pMp3 sV%Xy8&FDw?O72Wm"=k~A| 5n* fG\kG7GF^P-qwr7PnZAp$ GZ1{0I3Iw'M6UnX/T 7~L>Ri]0pBM0HHĽ?b Olz±/ t\=b{[К~wiIz!yEb . Ȃ3s})Ax.꼫e7h'7 MqBa"nl)XEE0|dm;w,zԺ*EZ'2ZT;ߨWZ7sj_azZzn>r\Nbo?cƏN) }0`>CHBg} ?Kz4x!CIBoakŭ')PKm'OS׺X85[ -6GJoY/Ƭ =a0u6kGO8➓9opOԞEnf^$-UxM?v-h"jNuތ; /joloZJxxG] agni颡 @97Yd ك%Co07idUH؍8Zpsr1,ٺl 1 dj^]/m|/m~^Ϫf"ĶwBe9WJ2y\BK\;0QvX Xl&6^?~R@OCN(Ն _S>&j>>Suct=Z<ʷl}Y F\L@[]1 MN7Iu;Rqz)dH\rCfeVsw^nz0ݴ: W_2}#8~{M}#_uOUSe^5^e,Wx|OGuͧ#'ЙN泏y2q] Qϗ໓Ͼ̻n(򖄤1W}CnFb-y0h<#pA-ܨkZbЭDpYTH$s$ 2L)̖8ޢ6JnT"\xsn9d:vu ݴp4!?(nG !,)N"tӦW؎wxT]#0 d6]T.kYfU՛V o<˞ЙIrs/&`9{MSv5ܟG̈́?pDc/ o/ze֟ߺ(Ț,Q?Q7dq_z\.?QF[7" ߲*n\Y>rR~~?ׇHz¨.7 }ӂ GQ >-Az\8o 3Sѯoϒ* ?^Op/;*^W}u*ìJ>>mf}S~0AZ_⬈(tQ(W)S10܅b͌ D::6Q!ga>] X*<[u)n>b1]: {2&-OӠRŚM0@gVoNWDOe^]K{9Yw!+-W(*S\jUs0+ 𢺕]" [yYu=%w&v7׻xZs'Y*m+NT^qP(JQSۧb({,77ͭLךu$-y :&`O褘Uof LPئr'?Qfނ檨ĩEP]kY pwfe02w(q6^}Ew)+ F:G`+eLDg /GjW^-u`6i>*nAK_y&Gc{9O\bR+CǶ Z 7 %dJEL̎͜>V:MEte/{?#R!yɒxr.;tⱥzEO t@׸5yONY4N`З'L=_4 [b0md=A>Wr|[v֫qqk6]#zb zCcAbN ͽ2J@LtCN-vτÄN@KQcˮpCs ;b>?ŐĢ~*讬ӆbIhӐ6slm;ݷTm[#6Vt*V 5fQ@7bXVzwXN{h Пfx?F 2ҏๆ$w'ۀ @*% e݁s,jXhS^M􎺄@&I R3L@+c=Ȥ #|O`8f&ڠ nPHѦ??:LT!CWwUfNNj/^[U7|ndFrԣqԓ4ӄ #(`z^?`b1Jf^,Nⶔ$b0uoBNML]s:0ze oJOt0{g `(?yZuc\<=0B}N*Ò6Ƞz؈}dM"_ vhx2"t,-oj$ ѫwJ8δfdӦy~|h*İd%Guh=6OwT#9bHK'̈ړ|ʍh }vO43]h5p9z&/C58KlzbY:c%ʩeo?\mpCcGa@AΏEm^]Oao2ioqyaዿi0$~dNc , 3Qĺ}>+bK&_bj @,W?!'US̊M-\}OR؜}T5jv:d .cALAѳrW: "kt!~ӻS8 ;9 蚌*Ӧ}B"yn,7.eTyIbH;\‹RcwO?#\wMNO0YNA0~ny!li9*l gLBI})qq,ayž-D>v1N6P[n/< 6U,Ķ/Ue!jwItpBqg$53Ȧ,Ov8WL' f٫;PK\J/ƣ ,smime/SignedInvalidinhibitAnyPolicyTest6.emlUT  ҆?;7AUxXkH=rQM "wqP˯Ԛ鎙2JsN>eq[[ 6Y-H]vqzc_1 ֦U~2żG4EVTy}]f6L6/27ı A|ơU߄[o8a {[`m>cC1|2[6縥\K[Cs~kJ/I؅gW4|KC]YV1}᫸N*{6ݬ=+ڦnUư8_ߎE~^@ј=,g,0d +X&gj 򱭡bGա*s:KDg>&:Oy\ieMLНenbg4\D]cs}w=gU۹J/_J3j-uMf]bg1QV9"^Ƥ}GHxbYP}IX L~fsƷcޚxpgr:LsP[FfΘ%te;AkKǬOc'A{ű'>La>sP p`4>!` =(#CCWi^򔚌p0·x!TИ|υ1Y;tg6yT8IOËteêBӲzTvbj`3fy;ײc3"^2^suyAp>[6wl_)х&!X=*zYz9pxd=_d;xs>PYmp7rzN $n@q$Yl|ש~Nj4˅|A~^NτA[쮊Z{z㬌Ҥ}Uy r9 HL .>LUӮtѳv\2E_Ldͫh<31 vZ} u/w p(ZW&'Cx20+'p7EcQftY@r7͕Η[esk̰0.vkՍ㱛=xD{JLb 瀿@| _; i" 7`/=w >v?#QL2Z=9QoL1j\cICx;Vls "u \2; l3ͭOdoxk}G0bAtnjgLAwNbZ)Ieq! -3erTlAͿ8~#9@IGn3N~Ÿ9DyŲUCA4?k!-_)Ǭ:Uq%A2p!(zoUqw2,<ٷ)zS^-jjL>dq5m"=vgaZ7[pGf(Bգ9taHI2eewb7X˗@"fP؂,xw? k .>Pw½vRn}Pv|V2G?Uﳰiٟ~NKz{6g?< gj7T`&pNNT٭ VWf>Yc6=H}qɸSR]NClqKHѽ lܰKa}u 6WL}1g3L6<|R=rǃCwKo1i$i] 2ye=:Vw1&(pzh ZAl 175KTv.4{fyM-Iz2#NSJ/ nMpt {'ذXzYnG*}>0ws6 nLU}ԅ[ y*:/uyJQ$#jqTy;U9c=`#V/bVGT2 gxyeOCTx>dB g j*mVZMmXuEkOV́3HL5j`LD阳]uI<hsgǠRg&^=:K\;…U {^Yzmnm)w~wEeEv[j͚?0f)ű:8K$%앓T?'On/\1/3P]lU|FߵˊN5Y;^5FRJ͖qPk8v.7gdžD,` <$HQpW&.Ctɻ.5SiKsDeZEʬ-GTX2kd5>OPK\J/Cu !0smime/SignedInvalidinhibitPolicyMappingTest1.emlUT ҆?;7AUxXٲH}&K 鱎`ƾ @B;toUfvfNMa29N$}k_77b>3o$*"iI?Du(" ߲>O8t $>I=h",c[]W4ٛ%3}%$I>IoX7ZIi"$?S5 |ƴ̀|v~m nUQt.oӀ}Yğ`~ [=5h4~⚨?AlEߵ}12 [Z>H:d@aX1@ DYW6CP20VD\d8acaXf`cf?߅ey<YVAc3R;VpECxz=g~,UЍV;*Smuy'8ybeѪn³]IYG+#ga@Y&[:3Yp<J1B <69q3}e?c>NȰFnX[k+j)f jR(摊hd:I|漬V (fbrdD1z|=$E Է@5pUB-zAMew<n;glv{Ja4^jP̎:?HL#_N| 4+ ?5@+Ii~Yx;+|²xB'6T!L]6e/񻷾LBgtN$wmoa[W%ۑp tqǂ0`S,]G`=S<ɗcV;KH[Q7ztiP)qaX "@1pB9u n`& Tg6юxDž=xwUB:j?ץbtN\GzoGbC.#v9%Q%J]ެLPML|m_v Ũ}bs'ܷ~UO)oxMWkA, ]Ό+IۖpC1Izt>O*5ϞF;%o6ʗtW/ŊZw y Y }AXnЌ{\lOii{=JU͈!;'")OO@ٝt cx|'u]6 [_7ʁ`/.|?=K])0덶 c}o#VeyA_|bg @ ]xIΰ 5M}~(٫C9LelCyUW:vcx.doZI>rOrUe TT6/}76N| -t*uVtcu*w6eצF%.l,uuOcYO7*췛+1m$vFcOŕ$Mz֓KZ[^*:?t vF} y新m:a<t!bVz?u@'G/u;e{ lu'[p*=]s<ىz,\bWJ,S`qcbЊJع^{̒EdE6o_̨>ݢ EmD.$%U6*)O&'[R^?NU٫뤌 tj>|~|ħj_;1Ο߸[oKtoޖϫ5m>Cq25OA-,hOERDӯO6(z|_W_j~7l/[UB{mDNaڤ{:/h׷KG;dQؑ+^@j@WaOf/ Tv ؼ1L) cd60prT;Kר␷!|z J%eˣZ3>]{,؛|`Zwe) X9E3jйVyg9ގDO1K2_JyG9 0ıU@F+ jX`R KW,ySX 4t5V y)WRU}H_\)fߵhư!dce99t2p}f 0ʌ: W T\؏c(?q>Oc4~I~^}>G9'YS}bUp/'JZyꜵ\^Ox"z뢿bT`+aaҨ氁\HTKb^ w6c{rO27a|f #leY3 P<)/.YlGܚ8 BDeI5G6Z 3VI־}v("T+<\ cyyMOlKeq/ |GAP,}ym*!=nL֩&FHh %10p E2XzwDWf4㬹f )GeSJӚbp5}I9h+ Y{-SlcN7w{sbZm&ߨMUcI嵤2OT Q\6V-F?of=qקL NqoNh3Z\ πƙXyX9xi?%?NJ]9o5?fPZϐ/_p }0F6ԥ{3g;yv,z2_qWY,Y%ʨ?:z!* yxv8X I9[^Ĕ\HrZl86<~Iޒu9+~`+bp_88&u 3ҝ6hxvV9!C'%B谜#dQTkA5F)$f`bPY0 2` )d0tA:i .|`HulY@f $"3Dx4 Xevtm+uPy`nzXZ)"۰*.v ^j K;0-I2)%TuX<SO̠e=MCEs:V|nם\B7fE0یMuYMy0WO{0ec)!2'Hu Y]qșYՒIesl%΋EH/gKuSk @(rhF-1"nld#Z)czht2eL朿CwK|_iX>2·]}u2 NݱDǻwYhp/zƉf7`\En2%B95'"B> MTjZdK% 7)s2A ?rh}紋1 h0xG>i2_UIUՀ2Ԝ0靃l V%Z9P/KMBN NL_t2=g:f1tU NwJ}@/~j:]NR| t.-y먰+DnQn4f>&v'\:; 9AWa\ NNYSLb[CN]Ǫnn㓇!7؈&/]ȻAup-I];zQ'b݉ݛIs:z ˘ [:il{FylJB!싣J:?u(+?I3߳Z;~v^rI#iHj?.]1K֧ؔto58y껕w،K7 ʖG_ !ulXz0$ c4ȭ$C*N2bGeS"9&¨Յr%čݝW<#rofC˿gzpoz;csQ!78yq1ouGU+z;ۥ03y 0$3P;57=E "~/-]}{df<{X6ypi ȳOO83CAIȿtgX~~:|KS:ddA-fH9tG?>KQ&X"4"*|1h|xNo:׷Kp<%7N}4m,|Jŗ3J,\~3ظuyܠJ>Xl'E6j&??zeМϾOP~7>'2OGD1X}~}ԧ9U5c[DDuvْ9zGﴱTƱUu֏7ISѤwalȡZ+z rd-0ٻ~iMxZ?Sԑ|qF./.)AU?i*S'-LJ'd}ܩk4˶*z̳)na,4{ӟj$#Ys'e?RGha[w+l2٤2[DžD`-_.V-Q`rl\r0p/cpdZXytb|orK,w\7{뎷8&} mKkFvLjZ̵ߝ&z>xG"G'E--r[3ud7@w~h;; s_Z%5Gzw\ 8'{㬝|Qqcf"ۋk2_E>VxYY,t}*'=CmhZ$ ;YM.Kī_PK\J/5;@0smime/SignedInvalidinhibitPolicyMappingTest5.emlUT ҆?;7AUxYYȖ~"θтΝ.7mhATپj1E($[N"*'+> ˅Q~0kg!!d?KWQ}| 8>/%,Ȇc]dC&X.$$2_ QQAr?p]/( ~e傮h`8K\ݺS?^ۧg%U}r_¶4:/q:K} Mgk(aôxdE~KE\P{bzUt 9JhTbvL|NSɟS€թ*}b:xk\}biVj1hbAcT;#7LglM˅WZٴn.F^} nY ^tq}GI{fF,fbEU"܏\hpGQ$5PFF~7,G`4fVVRB[29pD(Pkzc#ҷvV(&.c:NCi\ɓ=C67|qfVt ! UaGa QuGfk˩#d3+TV:UN˅9^b9$͠xہbeq"`S: a ݠj*\P8Q9U^eAav2pŪG z"[lͬ[]X.{ySװm:I ~ԣ<#1xԝMa8 Z<LŽ \[*΋;ZU\}2KlG<+yȘ4͙Bx= F_+B= wj#( J!B2ՎgOFQ. q[D5v́墠6s֣΂Q8S΀e)`π++:taMfxS0_O!f$SR8>6{L,L 0I`v؊mv#y!pn}xu9y^KjX xm" GՕdݴ\ULǎ-EݜXJ{`q1w_?H~Cq}ErG?H<=Ǝ_8NfX JpqS4}:_q.ښ_)Ĺǃ|T^ݵDm9_َhvWs4V#=gвܟO83cc=*SQHHvS3{\}&0GsIKWuOb5N"_QW<pVXvB@Շ$MOפAW߰\ 3F>.i#" +TB:Dls \,e9B+~Ey? 8l"z\L%c, =zyGi3An@REwr9N bxq>U=際d.mm'(6۞Ĉ>BtZr r" ʖ'{a!4ux,b3:KQ ΜHH-p PXrGN9*"jV+u >gU7IIa׾-5GȗDP^([}y*P1} Q h޸۠`ej0Q_b椠Rr!kZ݊ "q# eA MeލFyRrzZf/XCy9nk!bۯ]O;]ohU-{},;Q3j r)Jo4Ѿ>gmdtVU٨I \639RFGxc:T`oޭ ״߯b&!dnq(k3$8H!)#mDf o\޸۠i)XN^G_Hjndm-:Ț)7%Jpjz;;xcS q?ͭ?u۩N7~T_UzM$. #::Q&amy+RV{\v| kfه 5;b!}xWl@ѱoi(s +3)Clbafl~C\WzȎ]0u7dSSᚈL`(n;V*!*ev_jM3PeB_53~?T/j 72~sG=e 2Ig )z8$]D]˅d;Y!T AWb2l#5р_qSs,s aeU7.ڟLs_̎_?B󅾄G$jΈvCE"ɑ4auaǷpl^%xxA;ty lC%QܶBPoAg yXJ]̲ mlLvh}g횲 |h%fJ-(R'"_]X~Sc[pWhde3}˳UH[ԫo ֟u1z]qN*"r = 19 =rWr5ṙo #57wXïcsEl7lde.xF@;7\ *Lpۍw;l3Np"LJ\Ű2urUh+?bs#2Bϋ(uRWrʇmޏ_q 'C0ux?ހݽT;Û{UKʖ1bŘu/DibU拉b$uv&-UVڗVV $4>Zm0 !6WS7u첓}%Ynk*I,tDj+s'ڊ56"۱K][2~} GIw,Vm"`P7GU(#-aڛ{s]?\HFB.#PΧhq].FΝ9rh{Vp6:Ly-<||>F?$%e}98: 8f4h3ÊA.ߠd۪ru m=C3NTv왷qvf|2*oзjFQSS9r*f _2ׯ*Y@n~&%DȖ#o9ڬ>{䓗k@o)\'Fte1ye_>v}bwM.1im NR>9tOTY /mDz 5خ15Et󶖋Q^o>W[^{v].PW~U,AB_kϓeRiqa447A>>^:2HVqr1=ߐ$B;K,;9 yd ZX˾ЂQ"֜ehE.!,5\1|8)CrZK*kbgEHdEFliWS3xj =*y;}{q۾ yXk03}kŬN^;Ag ܐt(v4y=Hv(kJ&rSܜB"SG,oPqQ9%2mDd=ʳt܈пUE&.Yft(gUNf"hPPPK\J/Fy0smime/SignedInvalidinhibitPolicyMappingTest6.emlUT ҆?;7AUxْȒGfzTzf;H /w VPfWtʰ 򟜤,VK͓[ߢ< }'ut?bK>=,%ߎMG5lۼN_,x/\I߇iI>$mr'~_P^0_P3~&^ oO֣[ʧQpu불zSWɟ/ק}I)oaǞ_7º?'' E{ mWW[e圗}~TY6@m9,,Ĥvǥ*+^X&3Aj<͑14"fIӥO},ˢZ+cm#ls;p)z0[H1KEP9 >-B9D8hBOMo2-vae}B2µ,g\PpE 4jk>_OuybYΪ9=UY=CZ0Fb93p,irc:Y FdT-V1i&cchO 7| M5Q6IOCd^+h})K_W&u2]ݩ X;` x Ac4 4&-Ya\OS`3Վ267x8n,bhD;jK~mOj^khVsh" ƍ}>J79W3^ok֔ϛ3tZݻU9ty86ydS1.D=6Zvz8.Sg $.0aj*4BȅaQhz }G5No8- ㏒:0>/|Mm~x*8GkqsT܉yf=E2W<7T0lŊ&J8QQrO_KudZ|.Wa-D2IGiI$g5.#~mB'ߙXWJ 4v5: qv<7]U(!St{^jQ(5+2˾0}ul*~-9mrW\#RDdͫh'ymx>w1兀%UGRW]ۇgo8}:X<MBױ a25GLӯs1,ހe\1ٱQpZc(]/wݭ$$6Ʉ;\ctvNfD5VEfFW`7G|zIIŲ0sZvfgĈ{YmB]xrڈu:`N#ټr 2!e1:i rQuiWAި;01G!H*$I0༁{fT]0aQʤm)p'[.`  _r@LROE17(BroUa#c11ZX9 yhdM#KAcOpZÐ.y0H;DoB!6Gt M3>SPAwY9LTow;KZabBpU4? o ctUG8̇j8}%*W5I"Ւ Xg'lj}|z@5[,9~HS9~8QmG9j~0?mρd׶E눠<>N̝z:uke߄gTW:xc\\c+Owl}}%By$eQQopGZ^U-RJC[3J"1@D gsב}M+gx \YA(iӣpdel8&|V`쩃 3ʯ!2F>UN_.*s{{kTb{˅͌)( `-wap:;i63up/@)Mvͻoq)m˕ݞBu!{fGnA$gy8WJ%?{0l`!=Ǜ6һ 9?a cT:~jc(SԟOTY=Q)w3FΪvxU}B~iiPG=lLԠI K_b*Z] 5UQfA G*񜃞k]}RAL.T;Vi6{]MEauk A_G]Eao5{H;1>WYq8/ i1=?vdiD•fw۰Q{zvo{C}۞eDgyU妈6l{跬BKdg&,/խV~ZH@SR߷Egb+ʸW"yPE*N-&beJP)n䅱WK ~ٟ@͜ꂊˁYp;>. :E{Ty]]e:876\ iʎ8bdV?\k+(s 'O+XOev>$: VbxرآU 2z#u:%Moėi y[<,reSIѵ"I\$cS,i,Pg5Vt}kN3لs?%,'=$ pF̱ q1H M٫H]F[Wbx8/N$5*gُ+9FKwkt<<~PkCɺ`- {A`cS*K6<-zwTxw>"5T2&ۋYνSjF(+yyx֚Vް4=_k ё&V*ԋ9&WjM=.)Iw }4ehWRkzXwx,>k$5F;PK\J/, 8smime/SignedInvalidkeyUsageCriticalcRLSignFalseTest4.emlUT ҆?;7AUxWYӪH}"; " _LLZ(""){n^fE0I̓yNHE+jڴ*?WrBǴNw]5]zIW !5U1m2q9, Z>< i^M&g> SShj0 E> i|]4ŐK_B?1Sn IzJQ4~r WeKbAGK~Glv&{FvgP., c檨=٪v2$vXHm0ceFeB ĸCP>u#G,%\rӲhcaB\LΗő?xD=O̬a k]1H %?! 3Ah:;[=l#󤽤 0TQSzx㬳@ rv AaCN_ʨ^j0ފ b݆dQ)GQPGp3 a,Š5gK81x2[X5"؋p.MYDj{cڻXHzZتi͡"Q\-&H{`׳M@V|ۖ"}uX3S-ns%57:^Q]k{_ [rM m @0c}/#7ۛ"|ݮuU>Ä>R[5\J՞:ݣ9{Fh&u﹑lK[O.7fHrfM3 洛Xw:?\wXй^;IŠy蘫O{}19"wwomNOoxW>u70 ԃ$,ZgY񸒊ǽk_ӻ]o7-|̹*۷QioooObfK dN]hǚ>_F.l A`$ H3޳oC/l #EZc3l -ɱH'_6OjM=\.ˮB~{ׄ {'vN? +b|OGRwJsf2WRd2ٍM|1IU{(4:]u"ޕ69)H=4 ̣~ ]N3'q2\h)ҿrT2'>]l<uPK\J/ %V/ <smime/SignedInvalidkeyUsageCriticalkeyCertSignFalseTest1.emlUT ҆?;7AUxW[ӢH}^#Tgwc r"-w2"adeUs2Q$dm՗όˢüww}}䡏|N|&ˢ(n|.qYH/hQģi`ۼG¢yZ-⅁Bw/Oe"EkLnk>D_B}Ac/HB_fg1uգe|2MSrDŚ"O^?z%G"VWd{ n7Z꒸WaUe]Y]SwyY0"o$/.EVs}I#T5Ued rŠ;X>4UAA֮@:-}0S0H6  8D>WWgiϣP;! 3@kU+p(A,wnW7ikyqϯL VZ~+|6-TE K{]!8>_|iYE"}Lo|)H,xqx[\QG|/'= qj)fNR{pвViyC]h4qлd7LNvbb6=3&͚#Y]k t5;6yl LoD#er*"Y!Y:!`;R@dK2wYG+ip!TN߃NL6ԊiGT7Q2'=Si,B>qIr-=0zl`^2 FRL(mh'CwmMfȨX A|(WF`V^n)q6EZ w ϾC,5X0ޯ* O_@Oc"5g! Onxa:50d\1hS$NǛrB:B$<(<}BGr"=ڕ7AmZw +?nq3I/5;l\=E *<:MyOJ&R<Jw Wkܙe2EdULv۟7<C%y&♢7r-_Uy;wWUzNiPygȅ'y,|h0_}xE~N/M{JH%0b' cN_o"֑SBU9M=Nm(n B@?'i),mGAp7o(o轀:[ps9.c#xt +&QY:Q<tϵ֌޵PK\J/w1> ;smime/SignedInvalidkeyUsageNotCriticalcRLSignFalseTest5.emlUT  ҆?;7AUxWW}6U HBY۵ʀM@׻gzkPW7sJD6mR|M'U]v~tI.5.۔EA}[͒`޺qnA5I$.BCL ۗǚ֯7W|OF7` l_}#Xk1Qeѡ4hcݪ^1dWU귻/y?-ϗEܟ泿n^V;[Q|a "6n~3*ۤ{W:׿hEd}EA8ֱ}h491ua5γ5-)kkpM E}<+H|B9@LS(>"L}6 e4sALgM C;a,| /2n)P=۴!#1^.!͗DtERdL~>3_U]Qn{J~{h0~EDi:]өlEdr,q8OVԎyjdC>_;|TWz:h<ƹyl$( \$5֜*x-3:N4cTԩz򍥆Eɝxjv)MA6ū3~,X3mJ zoy"˄Ka.)WNeJkӅP3K幭'0mcE]imFq>Wx"8DI-5ãM4\3AnI z@㴾 w/t!G4Ƣ50<\4f-i(%ZcWtwUBO_ub ^b2[FR9yv-%}_Y9L3 ^J;%ͣ23gCj_/O`FP.#Y_ؒ.[#%}qxZ(;H$&hMrbۤP &N\ 1Ă38wq@,c!a11T=V^ʷ-<'-\5rq g14 8;2%̯O|&D$ɺ۔{Vel\=Yi=$#r!9eBJuZasNf>lDXnl*uoG!u4-4U%uźbhi<4Rп泗 Ӭ2hC3O? A3j/MǙ3/!p O=߿y{0K|6I-b W=r'NHΌtVzW .!l뎁s  0bH0,Ebw1dw8iƿX;p1({Ex~i*wsK2jME:^vo;.k &;,qP^eRhaFqqpTx^;cvmm(07 RIG(mVqM"hL&8ұqwsn爏Ľ"ó#y&]_PaY\}"]*G[Cqy;+7 ~0m*ޤDRfr=-J*!P)=s//x7PK\J/5 ?smime/SignedInvalidkeyUsageNotCriticalkeyCertSignFalseTest2.emlUT ҆?;7AUxYǟM߁w܃t*݀$to]H%;3z]JlI7+kY|,/|f:5.qӆq^G|I|eh"1AB,~vx0?r."lZѳ5)5@7|,86]$NabG^8PvA`}K }]-:ʛ1TޯlxUf_E3zk r&"V9Zno9t-E7f smm뇗8_}KC鉗g(5Kv7hMlO@Y3D) oa)HlhHвP[K:(Љ@uI"%DhQ{*T=JdE-K0-Jc>c- &*a -_iGI3;sKE{t\ Pa)Pqy̞VoWƒtڍge/}4xmr 9R/V2yŖbe"K='B瀆d)vWȻv?z:dTY1&v; N1@)Se]6B}K-җ81Gr>m+W 3ÆcL&'nW뤚@Y8 s p]p6TNJ\<_gfÚqH#R5ˇÉX aTx.t /Sv¤IǕ\ytxF"!rye'/kB0}䤺HNd/nOpT@31ʂN Τe"sM%v̧/Pf+7 /z;x3n1ڢm2s."n.糕ڑc p; Z&}ۇ" mVԮ,@h>sfw-X?Dgi'~s D`&7g0hH 8) J0=A+D]ځ+X'Z5!a&*ًYVQZ _X=#B>r^5,1wLdwFӦfvDֻ8d띌%:Qŀ${PZZxn(RUva{{2${E*xd{Wd.Xy.VArԀ肝dL$>`uk>>S'N`撻Tz%{W93Yrj>C7 Z  + ^JĦO2՞שc?<:J!t 1 8X O>9M $s\n f;ɼmFQVV FUy? H-\" -w[k>#%8n5HI(v bo/Swz'ox`ݰe}.c 1#0M,}dq5'}s3ɮ3jv߱V"dV%!WxE?^Ĩ=2F8H\Vk84|N992 a_f ޟ[5ɷ0򟂶XL~DTj_\׸)Q{ʒKi[:l)S4M/ٚX:>N4vDF][d{G<~,k֮/7wUjqm ٨4b<^ n;T{*KB;A}G^^: C86CؑQLrЏ+  ʿѸcpxqז)}g~(3Y՛M4.GV>}[>9l}g&]7T{U,I@ڲjoTnߢ סlmsoqד{5M$QZnZ+TW8$aE1lVRN3d;3j1>IXaR50uO`k2$x齔zuC~-iRp3=%ÉiF y7 ({#V&.qؾOgI49-rσ61/'fo?'45Qv2ńNyL#,Z7YxצHu6<&%1?7 .-[ןu|7hM(2J > &^1 ᓦ*8Jm&$,KOc_N;wʝ= wLAbwFt0fr\(:T{+÷"اK~SKS0asPHtVҾ5E(;S!h-͓&f'Nr(Y/0gӟnG+F/AA5UrjUf][%]x$>b&ʁNW6h[vWGt*wb |?hUywTkm rYAbǨu0ʼnO>%rR^ i@&0Mn Huux l"@IQK,jp>5AfH/; |a/J,,˳=VB`6%=IXRNn]-Aě$z( H,ɚ'CU0E BRʮCn5=~TLaorJ? إ(%Ugʁ't]xVnaU_١?2k>#\9ǣKI"ׁnʰSu~"SnYN-K"3 | uhd8mU>ehGӹЫx`hy=6_^~sA@JVn>%w0xqR5Bv6kd (vWa /J)V#xu..W,A;Wn_az~iJz:vʞds{~l1xbѕWHܙ.\2܋lwlֹ#w4PJ{ Dv\oeiޮu N^d6KeE)7- V=myXahN}ڈgI!i[;8jǝk)+ec-Q X1>tov3`m>eoqv:{j8.hX؃{R* ?_+PK\J/I? 0smime/SignedInvalidMappingFromanyPolicyTest7.emlUT ҆?;7AUxWiHi%Y5%K>GP:RlϒeYg?Y 2ɬr'`ȽyYw mB-8 % 8)S9D:䴊\V:e5N'Nn GӺ^V3JΥ{h_H)&r&dJP#qK ΤWw=^ ?&a,%?)1אFYC f{Qb(R/4㟙b_a];[+W W"S8i C<z !U(!5!z-GsoMeGO ]/IE XPTq% Ai>XIpa% YԥŦ&ã̆ 8ڞ^gSxe}3CzE.ArtyIRgӽe*YESII"^IPqC:%' LpY="-s] [l,Bι T6%U~=aS !* S z @p&-gϯg2Olld!^T ήd~q?KlHY 0n4GN&?qE*֍S#H)ȍN.7d髛Vk&KDHCз>1RsuT_fR*ѢDsn69Au+!EGay26-"=c%cpD?~_PK\J/Kk.smime/SignedInvalidMappingToanyPolicyTest8.emlUT ҆?;7AUxWגH}^"{@!! |1=fgb U朓HFST7iYȯtbo: *6j 5.ӉP۬0_}pJxf3eL'(j/_MM+?{:緙P3 Iے 3Nزhq_̡3(ݢKwgoҸ/zM'(۞Vjh.Q/2y|˟piSMھJ鵭$97YdYGٕ<h[b[l,{&X=k Vň,}K = =IYeen;_*$Af!GVŴ.&sZԊp?cO:;٫3J;ptlb~~"gʦc(™:Ne65#G&a 80VOtŸt_54b{lGdNi߇s3vY(G'L .@W9FWakنDgG| ;H/;n`gG,(ͳsqq+УްWc?Oq glr(p  =#v/vnlW%{FhsӠ1Ww7YLM!g'Уͩ7ǁ}\nIk;/ %v a"5;rƃNϾJ+pD(X 'r"{鰱3Ų$E>熹ۣBX0'd)r3a:NѲYhe:} .h~)WϫCid]6rX?r{`Mp8E147;GuugVY_A:-y!~8Qu6}cjd" +=?QS~deNTϕ {䱈6ن" Js#䴴.?M(܅:3@EߩBF ?ۦ%Hk?L?-id!h9}7}hX芀tH 6{ Ho!% c6~S>wr'z=\@bLJOWv?^M^uZ/ݍ5h]^uNd䭉CV2rp6|Jx@x?F0it8I~] 'lMEw:plM( PqZ^t[>X2'AD{o!3Ϝ5A"~xJ~ٴ.wwm_dOCb_L#%FFh!-mhN5C0zȧ!=n:})7i`n\ߏͽ[~=8q-;eL'N_ʺY:BL5t,§f*# K,H=r_wa3?PK\J/g3smime/SignedInvalidMissingbasicConstraintsTest1.emlUT ҆?;7AUxWYH~#; rP9==Ub (ʯ򜎞陇 $+2A28IM ռ/$."Ck3kEԧxx_=,}_" "f~a|̽/AP$(&?3[_]I,xX Z;bIb>bm˗c8U{헪ˀu~심NN_N0+,{n_ºO _ &ټ[+#0q^a(.${ @ǹ2bYY+Y} GQF>8R9VD2c$ mt3q'lnиL-i"piOߥ,vn.]k$8QhBeowI/v:,eLyo8a>qDcIALfᏜhx`9E0S [s l_D0ֹ͑Z lh9Թnej sBfUͰn1T_{Mf\%-@A8z /,?!2Jl`/ד}Y6Yǣv r2fm B0Լq!~zGx !oQ( d瀆(+@(_{+yg($fE樞Cd:@93 b+(xUvW@ҳ5n6`gN9ޣZ% sMmL<oga}NhOVDBe1g[oGuGby?F|3 ?2#,^?PP1n4NK.PDgCt\3}nף${n}CvlR|svLþۻ~TPkYԍ ͍K4=Pk['c%$+j.nHr>;gy?j)&+Ǜ8unv} -"]/qC&%Q{JW\mk>maI]Sc{/=ix.9OXF<`J!Jbml%9vSE2RZIx{lP3`@4v1"Hhr,#^_}O+#kc\˒/jRdJcQv W glbFOYJaS\)Y L)FEv8OxvYq{yJCg ܌S|¬v7@xY^|`vNHY錄*S^VuD@ȑǹ90#fCl aeeG05ϾfBYő4nY޳l>ZK'nfDY K6t8]cԢ gG:Syo9).an[o59:D}jWꐦ&cJ?զ9 "*$XVt5KB|iN)70'?*k8@lυg]u/C.7D}Ld*X<٬r|O!sG{hz5ңMgsg>%Ch=qvho솹F?>фL;'lKH*]Z8J@n2m N맓I^,ߪݏO9PK\J/Ԏ|g*smime/SignedInvalidNameChainingEETest1.emlUT ц?;7AUxW۶H}|w<(ՙ\4A7|}ꪾbaD# \ڬ'gj<%&K.i(t13oR6IԽOY<т2iUY'8sx pI'4<4KQn#x}/ٿ'45ѣnP|Bs]ML#:'ig@$Ys2+?Stѿ*Ꮿ۟eKPI:&ѿO MoYmֽ1 JK~R5Jz4`D|Mּy7!y;#^ya-#1r4aeaet\Ʊu-4*LuF:x,u͇xt(q>:[eA FY{oh/ KHt͵8W8%c,{5@$3ye67qI#R|5D$ l0#2d; \NTCCZΕ^N# ; 6hmP{ڿ_rDF˛$ b ~ŧtwW;4>&9]-!BJ=>p_g I)Ifkg[8K6K<܍ ^S383RGbE*[gR¹^6(\u/7}<٫QQe6=Q !YYQnfGf׫>suOۤZڨG/~4jXP*NȦ'ҔT&,#l:WҫB_IU|QdfvueāЄs(J0$39?C 2,MTXJ|ژfdLhZK|n^xtAoCU5;9;šqnoBr:.`͗*$66v۷w"`_Bzs!ϦSﻅ3[@':JpTG>7Gf,6'vEBM5ZZp,Yu*^{:Z m "2#_-,-٠>[fg 4l-̨/u=].*X-}Q.ǣ2n[a6k;U[} \ˢW[=l<<R+}KiJ0zS=]9a@K0h ^ N]Y{^8qHUEEu2C}i=\Ly@fxt]uANh6~&&xtyouY(txjQp~{l=Ŷmz_NBfz*7֞1F8ė(Ȅ:-lMቭ[/~`+ Dq!s<~kK"$y޼MCw왴Ȉ:搵3E Hv983}){\8r nF :;f"zOjgWBVk! "Yega19:s%X ׶ڔְ.wjԆi~cAI*9+al .\>kIܑV'{|]5IlDMPF낭h_riwBT)K@z3Lŏ8tD 6wpoxDt |RƦC)g5[:)6iFO BH_@9+s~в_,%ǏPK\J/-Ap -smime/SignedInvalidNameChainingOrderTest2.emlUT ц?;7AUxWٖH}n| ի"Q edPP+o彷deDΰ>,aMg sqګj+vmK=Ae'Չ<~HNΧl9;g`[{ث*;$}jBSτQԗ13K M n=Sd@ )3P7-~(O$Q-=O&{~ANvm+#NX_+Dx8vͧž"3v]n9>}|$\sK o dbB)@@H" 0"01j2ɷ'Sj]LK̓OOh8_8Q0t399t᎙z@Y`񌲌i̺~JvWsmcm`b *}nqL&OwdNǒ@'Dv%^"* L"e6u4(, q0H] Y W=NJ$$m!{bknw'ʹ31teL,7êB˝{cUA2E~p#)O?6ܽع)tdnt đ - O0OBwlUFP{^SFdD%N$V *8|!DNqU8(ɷ~,Ce60)%ar 7S 8U4nCX,p2@|ҹɘ`V3]ᆥ1TLeyۭ*cb.WgR#(ˬ63K겷ۆ[t19QR_ 2F11~FcUySbKZ.Rl!%K]tpW.7-lSGnE>Qk6_{*4l0 h) /F1B[U\7]23wh< 4]4o8eyKUIe[1UΦ"f#Y ZLgWcrKP-WwZ\+s'KB*yIlHv4 '^W9C9JZ yG BszpxB; HԔ 90 fb:ʏYiE6n0%)ӉPǬ(bޏ8l?fr4q#qLǸYb:AqI.s4IL,̳Z䒩_ ;M'G$ (EL %_6cmH3gELRCL'"mԠw D+ 2ز.}!mi/~]>keYdN7Aa1"UV (>}~0Ӷ.8_$< i!M4#ͽ0f=;c!D?cF;`|oNUۉ9 ⚯y<|:ߍRd -s*z'}4YxiMZ,,Fz;_Sq!8\n%ޕ}"FT;v#VwRǸrt{\Nf*տnX 4I-jE8`rhouzHFx;/ ܝĞ=eeE8c};wwv ,#|;N¤J`_塐 ryVN!gq[ >gj>-8O>̯9px{< Nd1L ds{b']RD1]鄰RhK+t ͸0Qb|՝iVU` ͪU"'=jFˈ8)I^ p]J0db投/tqQ$LV.{C}Eǘ5bJXrΙ8;MTQ ˹uNn,;Kھ}ZpCdcͅߪ- ~KoO3?8s|L/U3n>ta1ujj@Zoy"H-+`ni!$Sv%2];Rb標ʳi\y=1ߩ 蓓%'Ukpv#3` ێ9O<Ȏ2QRX lيﴌZ2,8H;ag?V IJG7Z67kf;;Vx|XRq|I>KX~[wtOG3sgJRjӶdEmw/331YU?냨/%I}N.̺ *EAe&Vw3g~Uѣ7k KNPu^}/I&O' V2_g$1S~$jF_(~̦z'`}iO8ESy)fSu~.I;o_*IJͶ^U]*K|^mV0KΤ^X,яv_O$ I]1 ƲAӴi@c- h|k|^[B1F \g],4"d&XzIHD<ap5qc-nr{R/rʂ`Z (y M1`YT~i"OҼxDkpd">V} A y@,LmYgbAPؚcZ-gg+)vD9X1<̠Ɛ/ڧAH3 î(ӉK JHZ{[ȂL~)-mqn,9 {F!}b-3UYs{fа~?TLL'ӉÂ~]%{rwfSb{bG6 :ǨݣAMx.軅Tё0샪 K 4_Z@2|L'On.Ú>!ktr:9y*s efwdzWfrN'YzK$<2z"4IN~dפuyCJHE$Vt♠OuNw/TP_Clq Kl-1\dߎlȚp͘;g4M&l7^rdGR,ɖ&?a1l~K&^?.eVgեx*mjB N\Ibo0 2ja00.q{!xHeYZ)$Fͫ*,o% Cu<$v/]Œm;`(OFjvZ.h, pXG }T1@aHc23ݳB8cDB kי@*B #(I zXQhqqyO' 74w`''Vk`it6e]IN#zIno׆ k7 .>js<2=y>5gnN{6|:=_R$a鰎{?,2iA;z ̤YawѢVSbP8v /-Xlj ÔK_o:z}s@rIQ:5.TO]cإ| Zd;Ed/\d?OQjDە>ͨv7 yC6 PS1ꭧs&Z5l]~X1L*s IOQFYwco.H5kbӉ˭P=wU! _XPUlG8GGI2Xx:49Z+_Q?P]s+|k2>Uls8 -^5`P]䘤h92\F}lsR;}Y,>lflqR`ibu34P)Lā f'A@0) ȺN”PK@F`h:qԈt<`?J߬Urz6X+t9DW}T?ф*o0Şg˅$|B ipSr_iR ##xt u,r2&r8Pj|dPv[G}6 MN:Vg{Ҧ#*{S־9Cqzx ʛNEӪPJeX80*n BefGp`jGV>5Q#4ά\}iE8|hnfQd[U cl=iJM1y+c45 A-䉂ʙLzlvbst2QALC|=륜dpsa&vk;>`]3s$ 1n;dA0t]E'I[3COy /??Q"qSڅ鳭]^<*k p OFH)8~;;'7pu&KfR\ ಖJnBx"*[oN[1䂒-)UʉK|tzKDhn9{=9QL=8 'uƹ(j_.4,vG̔UHɴw!T/|m;_ .,=[A$[ A;'y}OG;d@*`/ڰf3 V#ѡ W5ɰ rz}B[;84[(I 8#@t 9{s (+ g ?wL3 X');+;oٳqhwӨ+X7fMXa'.~1͓`VMʆ,~t¦q}E$z R G uI4QAH&?lNl:y av_ o6_5/-we| i:G)~v& /|WAR3mW.inUvmEIFx쪋||>[aydY5cbĊ) c?$+֒bTq Zˀ(ܼzK58SLq1oG"ثq:soZf*N^l~3_scWا+Lܧ2ccYP}KyLf9AsL+b- b 1c^q#:=;`5,^V-Wr :r?/NMh"+9.;/] ڗC A3"C(Ov*|-X'>0?v.pCBDT"t'An=Ey\贂hrU8_pzAh]%eq/)Ӊ,}>e;k 1 WM.d3⫁U3 @Ǫ;~Y%d^xy1F>I`@6Fwbtj1rB'zd٠r&Rb w9}h: 9i8+ʱۅW +>*M7O2o ?F m9%' C/J;v}2tlZt Xbo,;;e6.2򰔆)#.v 1ͫ!a _ҏ|QBrәRclznv20PQ?L'm\ZW@ @<Z#1륗b¸*`2k^:fl/yk]o֎V;$AnCuwfP]Ii |Xka[lu(Gn]++N:GԂ/'2usD*FDѭԣcdҎc;MGȍe]$6]:6b<ĹQI4T$jat?V:g*ڸ~1 AMǐ%){۱W+nEIqn/-e^2c˹abq{DE9ϽJm&`qptRX9D0%vxx2z}gPWfM.: D,m=ywC z`M!հ".a28x PK\J/SXw5smime/SignedInvalidonlyContainsUserCertsCRLTest11.emlUT 2҆?;7AUxWٲ}6-.%޴hA׻===~0 (e%LI|1æMc,zjB?a҅mMF?s`Xa͟h~[MhÆ[+:@B ֍/QA~/Z.hc6W( C|8EWkVڻ{:qsvLUAi\ܟUn ^˯5nFa:HcmׄN{ݦ;n׹~RWQZ}] R9뛐<}(>Uõ0(v(0#%(2'k^b|Ci**3bup6DZw/kcKF>v.t^4d;arD4ɱy$f`ܵ) Vj*ڵv4rv,XQy Z0y(Pm8H022пaI ͈9 HiJ#e\0 +Sk vTc`6c 2"Ik>e ޑitgaX.תU+#%IiJy{d3Jd>Hɽ7`,͖FAi%㎽ ;V9]DҊN d2Ir!_B.GT0镢OĶ R|+l!hA {uzkz5O.2w8# 5IXȶQU?ܥٹ)Q͊LLj Dj<:[.{_Q+Ў+$WUT$#x`k`.`WpBBh/$0,ۈ{3n3QIW5z`͠0`H2r>EGxYH@7$0*V!V@xB^hkPRi.U}5q" w:z.=(HD:\|H|{vQ.(#jwNZ#:ɗ1_sq>P۩VqىS]hAnX[^λr᫆dmoq$0 ۄئ0e`޾÷?e|Ŷ1 ;Ko*لg;޻x)VU߲ow7IH%ۺC!TJr5m6msY`LV`ﷲ[-(G_ [qScљl+Cq9rhPrQ#홄;hU[Y!duӏ"iOpWg]ca^.T'CBƋZظp4p7YVSd1:n 5,kkU<^ya׷Ge-I5Qڃ$HQ38}"Aa(7;7[FEeZ"oQry_&$ 2mRFpmvUf=$;~B:6y1z{yT匘 'D:H0B$La-U㌶4 $pSn.tc[I4Bu䲛#=G-~GX_PO3{337Ds`m(zV<]L+Pxᲊ?{Y.uGlǐ1Ś9F]/tiC?#jiO_iD/cuq4N,֠CE!)M#2^tuzϪACCM¦(9ƗA;;}~g,jc]lNMV wj) FcC-fb؛^hA[b-L0'.aMyU{玮Z7hl3v4~P`tv301!wTlj{֏LיQyc& N^w .QQN>s,R=m׻0JqgFꊎSc2qQ3)bt::~O)Md+\ &s ǀ=#';qHF n۹uY*6V]>PK\J/sW ,smime/SignedInvalidonlySomeReasonsTest15.emlUT 2҆?;7AUxW[עȒ}?T *_O:$WM"qOsNUuUӺ\, ;b'1Ŋ6ʏ 5ǤNG]5]zNWHhcFe5?19, \޽< 'U?UVe;1c43m8"P z}4CQ׋x׏Ф=>&sZLhcA,ɔ"xUeGbb )U*w4y "t,ĝ7(8P^8 `3nxj"a91U xK'X[P Vf4Ai !_{) TLQ`CA#j|jgPZsۛeaKno=)g3s~Hx͗rßӹYXI@'Dyc쮿$@C,x*m+*Qn.+m"=pzTOcT\̳̎IZs{]Qf }=ogCj,gD.a-\ǣilݧbN[bպZ1WB = $ڢZ4OiʍYzf+?##·/mw͆/*I/s2/ ZG~b*{ CXOby?aE0Zz_ ֚Zf>}sBg{Yp x W4sR`UJ'wZ")k4Ѻp梏Gǝ)zh-]wShXY,wfT{nvQsfN&vbC+tC%GTV*nĭpyM0_mk2c+kP?HXxf'F ݓyRu\iVwvj)eݮ&Ȫ5/c觽VOb͊βryMvK25]Aq(Xrm*?<PK\J/A ,smime/SignedInvalidonlySomeReasonsTest16.emlUT 2҆?;7AUxW[ӢȖ}#;ՂxzzdroOg[0H6}YkJ$#7mVj<2IYe.n0n윅>%Hhce7?09ރKv<&U?UVe;1kj&C14zIQ7̿w<׏d=>&sb&4 z2g2UّϚu"kخY:i_?_:b[%e}up;n)L~)d^g1}v _s4?g8?tGg9wGҚo;VrDb,QbXA׳Jl'Y<[/@8f u\/-p[d+˳=E:3K{Sq'Vhꆏc2*n`xW ƒj‚aЊ+qf%zR}A2 dz2ty}9"^䀓i'xӠp֍7>o$N0̋K3R4?#~N,0\Օ=8G[cK &[z-^:z;?3ݵg{6kt=qyT=sLz#Y[oy^ƺ)A ܾuC0¡Hfܬne%Q$>p!ˁY.zTLh傿if{K{m .S"zVA+BAKpy-tga $<8kBd7(4c61P>Գ@`f!D*? ׊2, 3o#f}W߁@ Ql]aא&oq<⌟.Cy,|Ԯ+;a'lx}XX*L 1jIPg@k1 }#svb.Tǖv}<3>-OpG.L \D3P8.~<<  tv> a25o7A )}-)wj"gSw;^ PT_$257޴͌TGR^qZ'H'FEwk&tAK}-cG"*WOWMJ16٪JNۛ:c*r#E}cQd4}bq[%kX܊|rLtL~)w˜RϚn.௎ŤpZ; #TYB]?G\<]|]Wu*M\K]kR]OXNr\6uҾ^9>i2ϼU.M^,I)o1uD`I!?&Vo<@O!<8( 5Oз m.w k 1{;WBwKwwX-xoezO1-0}76p8N3/BK&$)K9*`g*.ݫ&rlxY)a,r _'\2'AD OPK\J/Æ ,smime/SignedInvalidonlySomeReasonsTest20.emlUT 4҆?;7AUxXٲH|ޙ[ha=53֙Jm@ 6ěmH }}')[uUwcJBId ,cMRj<ˏIxIE6hZ/$L<\Hc? nxD.NȞZiʢ6|Ɖ/2 Y]?&B焦&0Nh?dJxĕEKr?+TUJlV]f%OI%1$Q_|u~prjn)0WI}L\ AISMҾ购9Yu&YewvW^)@q@{NESFxXJ -N[)eE/#_4>\Qܴl&B|DWn(#B..ւڛm-蒛ϽamfsuEqHkRSqzl&bDnn^eF*c>}1Ki|2:= s9\)]VS0DA* r7YUU+VS߻|5w0yq1>{wt9o)ǺT6#$_θp>mt])]Ό܌=r=!Ru.o+IPdSv<jp(:Z輢wTڞClQ GIV0qZQvnin~,xdܥodzş qQgwմGJ|Y ~CEVj,щS1Z[[pt>%fݥP[aP>vTPS"qGa3\ˋrw-O# 2UTљmG2 mܔ!\.|mpׄaʕ 78^o (n&,zcD5znO:L,|*;1{J+N%RL7'zLhSy],a G Qk )tZ}6?χH}zjւp`6fXd!_kٌ.^ E &F*. E//~Fvq&E9ɗMxԻPgoyƻZEd=Zh-l+)JǣZji\\WdJt^qa*]Nu?עmki/SO0*#Xex">ْBuB j֡_ǽ< *2Zk'ËY6/`? jK|}R7ƤPo2̯8GA'r9'܀Kw}##Täu;X/lG+Q7c:{ R]-#?yEюYF(0ƣz!S/1T.7-WKGZKz;m-m~tq)DCmXnl"Q4\:[f3VY_7UE[q=i_Ǚe{s6.+gM͊ц2{)98ȩp/&r|,KQ)#"D:MiKNv "uO+'w2vDN` ;8r[w{ǼA}*j]V-{ 궎g2Dѧ7c UNgNj^xkS}m郸=j;\VB0Hr;,hn 6ܪ݉E>g҆Ewp_o\|<ٲ1|g[N"?n#n0 /z&##x7xqM)^o '`;r3 Qbn,궏V y*7s;F9ѐM[ݎj7MUwyrEAA rV?zWf 0^aPvc6]L$0sKB!>1fr\]/)PK\J/kȄ ,smime/SignedInvalidonlySomeReasonsTest21.emlUT 4҆?;7AUxXٲH|B۩E ]B+H ;)[uUw) %D%;:Y]}_?G(Ț,uQѹ,/I}s]~ڨ OBsVWQ]w.]uՎLz$j[/s_ 2'NnLwI?G,3݈c~IJ<)>Fż74k=ٸɃvQ|јn/yQy%]{~K3+٫8:*^M Ymֽu%]ugE'QURrUh@PM׎!& @u A|kbծ+?uʶER4"lpnvc077&0k{wwc88}m[36ݲ`^kޞ$ϗk[$/\"Yzi8*Dj@Tlc%^⚀\%” &7\h69':gC(=GKidgbb[{7+G KyW@# bPy_:GMm=DJΖ_~xΡq92'7mk+slavn}r[H+DeVNKbY45brWu!fݸl3coN'tڮ&ItaH;%BC?!t:f9񎓅9tߖb{2;5.|ZWOva1كn

nmNtXN+zb ՙn:_*by\JU;1|ޔDX@C@xovϋ_k&ݎ'cEKzgZ $+έ 'fџD!{#Gd+<F'mcfw"=`U_C!XS>79ZU*[K~0mbYsKz ?4L/v% <-n\-u:nյ>o{s[.U9-Py`qjL.@+S8Hu^YWFZnݔ鬫XC38%x·xT+zp7_PPE5+*~5Rڣ5sb u5GAKw.ZY@WPp/L?Eo!%k4el߳`igFQ:4:y:zWAv)W^@,ofI1hֵiεnI3i_.ՌF4QZ] u^L%~ԼNzFw[z!H:sx1^zݎsW 9T?)PK\J/‚ .smime/SignedInvalidpathLenConstraintTest10.emlUT ҆?;7AUxvʒ[k|-@s^'y3I@اvMv۶T*Ɍ/⏔ydǷ6/o|fV_nqY\v [GTU6.\—E/ߥR\Uv7?+}GOO}~/lc `o~( aB`?e -ޡ]25u:۲vȊvCs͒2>E~>GhlzzW|/s|Daee%x:ںjՐ~aZ_5q[y]8-;(kPj]Y%k#,S64 KQxN\5j* 6`?=g3g~J}C;R+U y+ߕp=JBZ,~ WJz";:8YD\I•xmO}wz5dhʤm{Lʜh[GkFψ责[={5 K{HBsi73ߏ:(Zۓj, 5Ҿ }09H>]@[d\ȺLjRdOL $,G$o{W=V!hF hfnV9[E'ODTOeѠ!w|)ʠgɂd \2{:y} 4n AdZ?xzFf's:Q%_S4oh[I| kVATՋq2ZtSΉT$)w;!Ed ;/zx I֡G074~!]?V1ŚTzM)pLVUk|="ڪv 6~6J|oӶ9o\2Y{ҟ\%F)埰7_@9 Dv2 b!ŕYV=k!s?=}N~,V]WP\/5m?oU!X^wP)ݽZ-nY*98טJTmrэD`kN۝cN]uW3a}qgrq `/&_I{͓~IިJ44l3F]}j>sU}ZRJq]do#l r>]F}hĜ,:atSL,866Dh"@Bo}04gil G EgmzճodX'WxZ^ś 0ȧe0AJ4[7Lꂲ(|ϢlRc/[r%vO{R~"dW$N}eQ YMNkb=JEݝ0YXbχ^'c ޏ, |QWd6L ޲>vrڱpyoW^J&%oíU jYT/zoM3fAR`A 㠴 "7y|Ӟ5a!]S=ǚ"G_o( ?{y_JAL$ȍ%%[꾩csVLaԙii-*vx-{_Qg|׉L \0mq*)ViKj'h{fb1kekfK86.%=Z-OO*?QfR&դ1 2S1&FQ=eRf?h5؉xI#ZpN־uM>v۱=yp>3}*4U>. C>[:}Q)֊q1oz-{I\ittxtA!RhX^aPIʲ>ev/@}_Q:vΓͥ=8].Bh!S1vf^kq#cN;(3tOע… TzTZgp6$l2b!"b&$vݑM𣁍ְ;9y8t#שׂcV^Y`VL׾$3spx+ J* xLX=܏\&ÀDjI ہ50h,wPUѩض2 9DiPgp}-{5cm 1VXstPu1 U~Z15\ap淣NNu55sB'v1csn<9( |V1y s$SOLhV3J'[zj89rxW&8@vӒkujUۺ"޾jvmsHSגSCKVT34::!tk"m'4tz {}NםtUWJ<Dd?'X/8=c 8|UDlѱuxʢMx󗋇tADu=N6VmV<ԕeHDq`h:˅hcQ`xP7pL( N+~HXQИ+vT+Ӽ>jc_3NZ|<ٴfk5$:qnO!ƒ2{iEq?'ٻ5z\A 6ߛ޿qxND!5XۛqCH5/wJꔬ#WPOa_ѦI0@r>G9wzm vTi𜢏X/0C}<#j{"OA!;,Wnp>Z1Z*)bm5m|9 Dt/IޢY͞Û;rQ̲4K'iT,H8f`cC VkY@ᰑ-k= !KF:*&qjVzs."˅ `TΡc>7U}%J#$QŽJ+&_L1Z+%!sخUTݮvU}DXǢCнvu.֒Ȏ 6kEiHb,Jq_b|ZSg,DNH<2>#@1[,ptf wRYcxH3$>Wjlp͇Ձm'BL5tb}zk1l3oo#o+эZ_>$<.n}nH̬ƽpYְ"m,Umi펚|F#ϝEb?E"x(,&('+9YQR!+_Ov ].]HڮOh%ǼoH &Z?NBp܍j0.]ri~BŕX[ɔ2^O7{a nl[إZnī͈jX.;9A(cRd+ԝ"?(vǮ,]Өbl-^,9S 57 U'L04V;#3OaL?Pgj QxSF6I NW

sFyٚ˵%oE+Y?(g^Dr0P$EA/Ǖӊ'ݙFKn2[׊ =# < "p -@tMozN`M}ndR )y%^{, dAƋ$'woj- ^ u_ o`z4[M{Xɞtc=d& k36s3C=$WO%zΎ*qVF~$tvgQM$ѱ`f2 ȫ̲֛_nڜ m[+IF 4 a+]}s+$vj`M"% @6z- T` pg&IpIf[>%7F$;52; `[D \+}M &Si;}Z-~WLZ5BSYuo~۱$(D|tEף r'Aǥt, YYKwַm&ygtm|8x{T.Ÿo?w;"b`;gf;w[cWn70nu^&F7C6Ŏt5J3O~1ROsüN v+_ĉ؁ND}ZIQ+3>>DD֋v`Kt|7ZmKfXm0=JO-\քQfhrPEf8)| G OG1};ڞzS,t?Jgj*nHe[yDn _^.s*N%cd z7av0 UM]t?"bS\rx xZb7G-#jhW1Vܶ|KJ[1=cSQٹ$c TM*HۃRڜJ5$˅sŦ- 'Q=!c_ 6C偛 }h"b˶o\HNnDz\AVY=?PK\J/I>#].smime/SignedInvalidpathLenConstraintTest12.emlUT ҆?;7AUxkwʶ??仧3vqQ-2Yٻ/k$&#%)jg$֕Me69[m?֗YG?1 K$~Ҹ"׏\&/mjZM ϴ<$s_#VX1|K3E^1xY>~Y`e>Ch՟EGm{~. mٞnR^tztve^ɧ$gUG4|vsb[TwYzquu)Eڦ+׃> KVo}~j0TvA.̘mИ̱`A:@br+V,gIcWG}6{O:à Kã(ǪC(Z?'ܪmopʰ3[TC=g7wq(^g6:{(+)W.nxN:DŽ^pgۊeAM<hhg2 r旻xU'\)4A@ǀƙxB󛹉{c"/hf!h8qM 0Nj JEkךcIu+Fl"ϝHcufy!P?!. v6HV9B:)O<1d8az:ũi1S`*tY<Nlk)e=XɎStf2.ZYAw/J2RM @g<;b2u20m^}6仛x;?ʷBSwM ۳nSk8!fVcu [!{N(W M4Wjtp(v H83Kh Syd瀡(Vp~^`JKɟ37p_#`N'>74qnѼkZn!ZFewr 7iQ覊ZQ Dp G FUC^));{tW.NG]d}>u~9\04 tOڰff;m>FB I0G&Nc?.MD`I\<($a~~{. :.1ɢJss]7x ]&xbJzߟVQw;=x ]4})pZ;rssa PFuϪ;.I gYN/H:V,V95 Vs۾"C3Ԙ*{*7}xLp~_Bdnmy5B(ў3 \Pڼ8D;CD"WPjQrW]Ba캍~iO붊=wz'R=CFޖXq_ߝ^vE["+ +%YQ^QƄK[QH;,֛tRh/P~2JJuZLL9Hݙp }GY*^  pjF֎縶\!ėL_vE|Ch1"}ˢ$=#絼3mQB3^>&U;p@Oɤgƒ.X?rpꅣl[ȷd3vp} 6eOkeYg|3Ǯ쒘DbƇڪV̉tm#V}%ߑțr(_>܍.f,'px*'*{Q&?#9Xsuxo,bJ]Mƭ#iU O*Q}+8pUN:]RzsҘ8fܼ)"n DiJS~"nwo,EDo,DQ#O UDwSwhUQSS@*8?M™ԠÛǤ$FG75|:_qk >3H3<+R"vj4zbGkiԇkK6b!D~ZxE.C-ףvE'"wKaCzy]%Q5m"Q({;~l>Ÿ31ҊD#΍X ŸK\PTn",`Έ\PK uRv~N=^¯ܩݻ;7 D?_ȩշTgK;*s7/~~S7)dm]CYPq\^"TaPGyj#mdz"MϚret+0$$KDoAtՓEoG,|ºC ܹG/;9Z S533{9. <Cy +]ڈSvLwK /W*b0 aZ9uL84+ IG橋Ȍ)ZrJ[]LM('y]=d<31݉GMhc\@g>yBz[ a9]Imnl@-1[CZj-1FLmIF:[>rGI W!E`~~W~yϲ4Vf@Ȭs R֡dDer d]V]nNIr}K=̪Xdde*}qgQF;11QS+1*O4]֜t֦J@4i^̸eM?ˢm\n҈kOs[ZIA#>#+Vv 'b1Slxs9P-QHӣe{*bع36`Eobh]wTΩH?῝G{bhn|[ުgB1(k߼O;{؇vЗùNggJꚸT=3 LV-g=E]N%H1AOgocG!)w aKFS7u@sRX)>tVVpZII+kC)=7;.r>)?WVg}ĥgV ;"J% b~\r@^`s]ˮFu6mK{nU4H+pbf#d$s *㪹:S-U3.|uZI 40iox%kҪunLj!:=KZgባKݭrYET}X&*.%-(V޳7ΰxOmfn)[ÏvmYp-{PK\J/. -smime/SignedInvalidpathLenConstraintTest5.emlUT ҆?;7AUxYHǟ3C;k[݈7]>Ё@~̮>f6ɴ WHF;j?Y}k mҨG]Dm^Lh[Ua, oru4|k>9D[W]ziտ E]?MM '~}HoAo$߻3Ǜb>l5M>ڲɃnLKmѥq_B~Jzf[_U5jUPi}.ڬ~3Ү^xkZD},ht}}{-`kp,`M jbK++bu*dw/ uK%IPEȑM@1ɣA<8|jM\5q묧Rσe.=g]S@eApZ^{g~\NCXq@_ڹ,E@Ʌ|i>@Xjdi? /@ E@Zץգ[!tyQ Tm,[i.Np^Q!!L2s(%+@(^#? a C} =8 kKW5sլTt$0ІrFۍ==Nո+ Ny)Sq-Ģh_uqՓM"ɐ-OsES*vM;y+{㫁Wy2ӃhW1ôW4S 7x1mQGצhZgS !b?eo{'؋!#&N^4\&|"kDCi= 6i @겞qJ%SơW\^fW%m6!&jcl1c 'Vt8 fhWDfFw>jRPQPj5ev8O5fL}U/*{Tmy: Y&:mT 6~EN UEMu;o=(1x<9eRm jEQ"-\:n=ˮ֐}aƏ9&7Z1NBY/rBrmW&!v>:*ŷ# ݾ|>W w*@)9+rwYfɢ՛hPjmG2F2:!"RIуG mSr'THg Yg;m>MX삋7FoOfA$ka ;de18'jz.J2*ĝ:.qk NsmֻfZp?.SP,Iq2L&(l{A֞2A70io#3B:wOa$FdC,ek@dF.+atfKHE814eq>`6͍I;e>w|oJhC2a}C]cU5:çM soSW8%MNkEg[N رۆ*.9u:g1Z\/z^t=;ObeNh VwX2TPGg3yM@[>(QTUe]u|JW-ۧ홉-PQ2/A_풪-F N²{v}rO|})V׷.,}￾͓vXK*u3Ѝ]F^ ðr- 2k}ñ߿y:0x[.-|׊uw/ER?u/=KDe| y-O'{[v–~$espm tu%ݾw@?ݓ< EQр#?|>]1Ši`im̖ ͧ4~>U My++fTQ[ۀ>^E~>Ag&:61jx;LcVXOٴ8f+ 8E1jйVWގN͎_1#K2s7~C;v"D;iU#nXR2 AdҖ'>)*c`- W#h3̑Rq2ҚB8 @tEa4T\q_G픒ڍngG2gօT.:ſ[gnW s[BvcZ[ w_^A?1T *gPQYGzy3"O,ёÂ1o;SHlIPy} .\qi4f~,- kb[=MBY. ;z]bӔL,J9Iyᎍn3Pw%hH$90prfKjRf<DCy<Y\e l^Ѱ"fSv2"˹qx_a5 3E9,GW9")lWeYj=E"Er!ep`u#TaMh0#ҖpW=VW"9(l$uˌTcOk#QT$EߓL>o;o75}jbo'{J$pWOs=9[+[&KNGr n單H <46663~LvM\A%ў˅cCHOy3P ^#~Ho-%{hSsP9tŁW{ŗ [7TE&6X~}ըc}ɸ^_ 3d3R!F Ր'7;=inwc~O73Y?V5c\dm(?0G(|' r`I;qطi.iC%<[{zOl[bx;cP@m]W񧱯BӠ|mCo4RهH<އ<2Ef^נ̉D7^]3t?"u}#X_ѷ\|_t}  3\[|\vʽLyx$i:э(7&r0E^OSv{] @⏶^k5oc|US\v;%tiW1Si0O\nϖh {8!*aQVܜDZOZSߪ+J`}Cz//YĺU݊D @)P{H >cQqj#7tyl)pƸt'9ޅaGdW&ޝ`/(02)@!8i)ϳyUFT.5g_Pe̽ZCÉ:1Q}b ro%">`u8 {9Fy0Bgdsc$'].,B6rmbΉMqm8t)K>.2"MHI|ugx<~gO;bJN=~!*|g2}];O:on`G%|vMEcx\..g0чմg4xj t/&Q'NL=˴>>fe6ݖ^C1UxV+1>EL~+q@ EoüW@$HQpP@n6rb'μ]Ld/V)?L`gUuRGQPp'S(nFh ٤0Ʀ*_CgQ:T| v7skAiwYIGdSpz}3I˲حMbkLB.K-P}d8O ^򪖩/c蜙4̑G)1:5޷{ j_m}:W4 X3f}p4RIxJ3RD‰[#Mn~j]ai; AQwűY.>翧t5:!ǀ1:R@#.^gpsRʘeCx]:  |\.]Ѷ. NY-́)D`zCBk#`IZ2HOykcS^Kк0̲Y2FPK\J/ȶ -smime/SignedInvalidpathLenConstraintTest9.emlUT ҆?;7AUxYHC3n$X3_v˝6$V$!ЯvmwUQ,) 2N]^W̬߰?](o']%>?Q-o{ˏo]R;S!<'QMnAoMgRRQu 7=4 [{[3-cojԿz+[`m>CkhGMSWhoͶbkPu:Ϋ[tf:D㿿"z,8z)@q4E1FS&aj]T3Se&dҋz/F߬Ә1CmszDER4DĮWW Nk $;$&si>K!YKW Uup}FDQ}8VJրs4t"P4dn/OðPF3 .-f2e; AmgT#Ge(:$ȌmkhnE=aJ,RdB3lj2 |<ż!{bJiͤ`56~ ,1ޅJ=]'Pp-___ iQf(:SIf;JA̵!:J Ve<=9tWکww'K L=ȋ:@w$HUWrDd)gd)V,cm7E\F@Y<6OEt a:5dI #fz +`vCW+y7tmd~*#ƀQ ܧ3 CU#Ggxΐ32LK^ORQ RJeWQ 5k+qPճdTp$Yh!<Ńc2E FZpD\H\•ߵFXSl0]* tUV[F'D[=iMcޥ0m>{Ӷymw{\69{Ј|9^a̻}<=P g~&>yH`Lv.ta@8R(e}>ͼh쓜;ó'tmvoGĺͰԴ]7}w=>(.ZaؒՑW^-yv8$Fh| H+Eэ#Vn{[#ym{Jxu51h@͉N2mERO|V{"'*}*dsr.R5|6^ dMzZvv |7hO!#}H&.)5 ' Y\AFV@O<~ƿ /ap2ƕ4R#:~8-LV'NˑvIǬQRdz%{PXKJ"QY",LpY1PҨXL.ˁCgOO,C7M$`@A(`e!+gNM@䵞 ۔z>u` &0JUz~ıX܋JJ#^e$숍 0ټZgBGe}=w5}2}W}U]QDŤ;UqS/qD-p$^Ʌ?,ېrr*lzLi VJ ujm@E劋^|yi) Ô͚4jm>[XaYZ~=ƀjL_ @͠#3zv*Q[/ǖlu:LؓEb>U7>=G5?/dEQ>2sV.('l7~T򽕾V/?) Ӡ?ɫfmR{p1C1ܤ/e27*H2<sKCf .D'u߫LKhvd+2I\^sOO<}{v 4!ORjX#]a -9iCv"$(x +:P3ǾT{[Bf,t21*nEr`be]Z~DgzUƃ i鸻{K7}jC|"UQEߍ4d_MCUͧdl~!q><}4}V}SJTS[^Ϭ^(w.Pcܷ*uV[,[voD-;|XNvût{‘N7JCet 0ɷt,-ՎBip /XJMS9bEc+Ǔ3h⟙[fD]1Z?ň/߻4`J=氵P Ola[G7}';G)ĞEOXId/* H^u5^tt94Q~ L#q>pw~0bx/Pm2y3ѯVh;%j[?a {>awm 0mz'Vkm|FWeBf>j4mSǒ$)9l%M%%Ռ6ԕmz .' !_ܽ泣Wz|bEŠT33CFJjoCf{\; 6K;U&iJX77 ħ|q!V@+ hSrBba7z5Ӎ|HR@Ujjѻ6UN؍Lrτ4 v?Ji8ydGʗ=xI}i՛IBUn1!& O~?")%8N?A/r9~5@ \&mO?*zdMYمGB\DxqC'_3K_GxG ta 0|8}:nj9"? M+ɡi'-Nh|mtUGfS26DXz] j/̥ ;I> ru'-d'\6cl_1-4=9 ]sdkKTKO9 wtS}(0¯0Bc?/?i- cUuya @pVXD 4*X>`BױqG%mzI0[5% DZ_y#^W5>!Nh;]oo&9צzfX>q 1(Wp[v|w#~c]6D&{ |YOk39[V[C^|~׃b{ZD B{#54ʣao 3IEw@Uo+KD16uC˝53˿-mu|Ƚngu;V6ZVxb:.'$gi }G椕1Cp%\a"fqe-dҽ|$R6ZV-ɥűgQ+?*MEauxH aoȱ$7ʳ0BgE5eWm)OjN0H&fPj`:" gOUԾ V{ĩiVO u&|vpɺmQZǃ=2R8p7LrEL$IZjv.ٽDF# N1-̐>MmĂCGbL=vHӞnХ<%x B姹$^IܾrBiwb֟%7m?PK\J/,[e= q)smime/SignedInvalidPolicyMappingTest2.emlUT ҆?;7AUxWٲ}66Z;TiC@IHhMv |{3=n;(T< fE]BL'F> k~~n,/I}NĮ.g}TQ#G>WdXY!i*WtMg hx]4tc3># 3 I M'\] 87)+עYx_,-oWbf]~>7 >>Z-8g}SQDo -Y~_]0}}[-jl;ـp ⤜ yXo .__i-ƳQ'd-Cn3yTR<;|B'k S q`fɹӺLfv˂Z  >]O1**.Dgʼ|DIkpf=ڷ"= SYK9paXt"X:%e=B(=[IqO'i0nׁ+v )'!4P NbR[!##Fƞ(a)% # dlaAwtq%%RUI6TRz"6:pI&WVR J IՐ#9^ѽ eF-.Yn^rL$Ǔv0ǽږ/U~!Y+ 2ST?k")UX| {O J h(D>Xgʽ(Y# k&WC>l _ž+GL' +dVK+Dlԩ/%0mǬެ²,p|K&uLT<O#l+K\æqtd 96| 30R/ A"C&6df$ L6xEh+yQBȂx}q58#2 Izvކt`5@aHG t w<WқsY䮃Sq?bwt4lq z~{(|b_{ULDw6pH˩GQ+%gL^1 7L`~uv?zk f $۬qӹŽ/--cqN]G|6$nEc](yggʞz$,QSYƞ%ޞCٲ+wi #s)=qMr qIU_WQTzٖc lhu٦ך 6.x(;6>4|&Mb?w3!6y#a{ .?&"q:FEt@? \99qٚ=!{fikjX;OJ3#+aWM9K6yV 4XPڬ2`m5[(N*~nõpWAP^."*5D#GN;^$s1U\qsWJ<*@xs2k؂qB50_zz~4՛}TnU%O?mY:_㵆|dU==x`5QFwU5)Vc1pMQ쭪/Mƅt 61V[e:q DdvtH85 M(1`eH`빻Ṽ*;Ќڴ1S]M'qWߕ%2Kو![P~ <~6^ o5?mlCvG~l?6{Yɣ dsU.OΣ`+'$@c+ڐFUӲb[`[MP 5L4$1ݵ(KoxOlh'~G>!F48<uUBK&=$g:2E[۠=ngŧNZj x\0 eExsnbe~ [X1WO++(7Tx? C WqDS/݂wbZ (?6Y˫~K?LoeyUɮ]Fҥ OE PhƃL0Wƒn7~څPN\vd?#qe\%UG޼g!q#q¥[ ~PK\J/@)smime/SignedInvalidPolicyMappingTest4.emlUT ҆?;7AUxiږ?narqfAA@̃ [uN׽iz׳ֻMY/_Q}#VnTF~&F鄫[_cľ|}FۡH#&eO'_voS>>(bk70hͯo\q R96tBy"?Jt>t V&nE[=|i9[GA{_KW;W\fD*vcEDVI\+G:k=E*7(:s^ #UJF[Njì@Nd3g.v`eeFdѐdqL}}Z&c$ep\*Jj{:rh4NTq 1>ub8O> eg^qҲʇ~\Àn'괮tT l\nj Gp Nv<%96=ϺBぷLC/2~:M)Ł;<[3* J;@Ue0`Ix@2 Io:|6~̲Җ$^j}>󓕐걲qiNevzx8.Y>6AXSZJC`繹܁#ⰍUkK[Ѱ|yX{1;HMky_OrvQ0/e"ed(*r.4ߒ[cT "Z#;: /QikFvJGv:R8 ) @\ vX Y;Z}ƏmMc`mϸPL:s9oqt)-/g`bEa 3ȁ]pYBe m[Pl^YՖ٬ܭgԙڄ|n:T!Y_S7ɪ!ŔVfU8R)0i-Q4΋mxCRf/Npf.qۈ ]%قIK|$-w͐ɭD@qt8N螵Ct\9;;o]bGyB$*}cdxZ$H$J| b0 NeA'B/`2x:#s)CdP?QQW~x/wiD0:02SGZ|5!Byf;f|{b8L'TN;oZ%Y_WJޔ`Knri^u mʷGr<7P<H^w{8l,zGV'd'wF,{a&NW8vuzrmHO'r c@:P~R +~O Wo B2L#WT+ӷ11ě[\~O莋96䖦;q%)͚'Ӱ4JNOUJnr:9Vo/}cg}+uyǐ(oЖgrꪃ{ KRߓݡeoo/>̾df#;(x v{1^Xw gbptL-\U׎[663;p޳=>O32?=|N}GMOd$knGt^+9/Qk-Hӹ{:Ta[;]sAәRv0RNigmWo%$/X$s'%+ -FTF w[ww6XgV'nq"짞XCMy^S}ٗ]/|dz~3˧}:yѡev=9af޷Vs snsU@sS i!h^}{Mt,QZE/>.K ͢ GgCt̥*%5;\♿}ݹ{@AB;Ւ >Nf._\ Bwլh/9^̶F{OƬn0,0 9B@cm޿ht*x^>Yd,G{=J(wkȇжI}Pnv݋<9D`N엸ĪwSQ\ҋbRf`&qA 8]a[bsmimuߞd-ˆm7KH0d9w/vj CZ-)n!ʹqPGyl_X:HM] )Jl~ʰx Y"tX:g.? j-}w,/J8:S=ؙ5A*_+Ug14wY2ZƚH fv۵#<(o-1c*CgN8ޗѤUõjި!T#uA.rg.vqBnZw-ai/{sxfmxpD!۝͊h'm'4vgq=*njͯ+>WG]E i3F{Wz{8㇄b/3'w%zg=Ҧ-P œ罣6Io#XU4 lڙcNe0e(n 8̛^Mա" !o\9X8TϹ/ElZMIbƇm2G >7oNo|VÏ 7JB5f%G lKExU)6Kl뗊kZ'>m)-(wh4@gGDI)oi밠dxXs73ttn[*T)G.x)dyns")cx}*q@Qw! nCKk|CR5[Ϳ)C)lo9-Д̓N.I0%FdzQ6Dȣ{viCއFwRn]+GQಒg^umHs5}O}//|dkoR\1ihHjvׁi;XpƁf}w;ZӽQakna6#)U9$ :9zo"SuWm،?plYeʦ{^9vψD*|dREcNY# h^+:HIb:HzM[BEK]}u;ts#%{*.\ YoQt9h:~uSnbS$qZ$|2,s}t%a2oܤ3_ ocvǽ0PK\J/э|+ r1smime/SignedInvalidpre2000CRLnextUpdateTest12.emlUT ц?;7AUxWٲX}n#sep<{3$! F["*$iLI>i߈Ĩ>gM'u[{ǷYA_>gR9xy&1ì ά=3$5(azQ!4I\7jK ?g|sF3f=#Ov92?0Ua?G_~u淛")Ÿf:?ITvi:GXxe{  )k*lUtlz]q?nI~ou($_#+W4b0 ce и1#a#RFׇpy9Zj%5(eUkF~y}j۩lD:1Z^+`zN'na=;.U&v`ʻ(tttlŌ|*/I1v)Ӊ#EXU@I"Vm454;( ir0VRF!1p"}qOl"9ah4z X]i T#˭C#O M'Kj^jh-b5Ce>9O/&VΖκlv(Ƚ([.RXiH*ų gi"8t9Ƞ <`4N}G;~umrrCC ' `I,{1IA%ieۭM^m5:jQ6BOYRVxζ 9,[pEK7}[.Ҵaqz'rN o\"XV@B@% mU8^4qAwom6l]:ir~}hkR<ۖrpMWBQEհH-UZ5{Bah\yץF|5K\e0OKw5%s}+|03RmDBapw"dHM a å ^\u3l#EC:H* D/,I@40*`/qIܖCDZ@UtXw+Co+oWx/*52Ct_S vEcS #˲!ZPˊLUXM78>ֽg=UX8 KoQ11Sa<6/Fu k >d`&;[3M:ٓ籦o]t(S(ɫjᅔϛR- ~U1K"\5S6kk)g;*r}>/կ%rqsPt!pI<.mw+ . >5`eTW ?1#o_jG7oa?^~ה #\Ó6GUkX;cD<8B8<`]F:won =&5uY|]oLs=C: -ڜ/tBY#FM=[,o` zs. (VnggAK_lluo!iY~(+YPPqXs1=2|g9ni~g#ՍuM sfct3QtQs|UO!r=Z ~So_{!94)E]դ\ґؗ_fè'Fʄ|z6yOBUwi:GS`l8>}o9G}{9ƿoTWUx@u|oN.=+ҼΝ#G8pzeDΞ.zA ^P8K`8E)>Ě AeGk6hK%v@ ϻ?txѪ#)\~<^^hzx{~:"Ntw>8l jzG8 #g#( BQo}vÒT=18̻ Dkt)aF9GVaJ:eMVcX7{樠g$ɑ%x 2Y <&[g처!a9fQ1FN*gBl9s6oѲ/gӪFSZWΞ_A=<beVacW">f]~bk49˄2ܙ|{40%{Ab\m[%L)Йkp}-0u8Jwq>hckޥrhJ氾 \] [" \<{B2&ɌvSMQ.scOj\.ޫFs~kDA#~9<1(N7(w%$p87(wD~T UC^~FYR%<̫crqDzo"ӼIc9'~<>Lc@J[6 |r&Ů1HFO cff`Y, Yi/Yu>wvj|*QBz3`H爻c.rN ?`ܸCR-;i^>JySUt*AFܤMU\TޛL?@>j\<%V>z|8y7L||L=BE>g8}źCޱ4ycDfq~@H* 6CX& E ksF1 l[6'S UK(ExxXAd6(܈7u5h:h%&*#3:\576mgHjQ\L|\.JAщRpwg2wF{ w涎3\[E0JQNr @p0?o jC]p0gBE2w!aB@ŒdK[IV"鬹u2U-?܏GrUn@p *Vr5;dtYq7I۳yπ`2zVp!OhdpuPP/=Pe2޹Itƒ H< ~Q3ϝ) L˯ ('xĎy9?}{'':][ Y߯q|r|7,e՘Վmp@ꦗcj0ZEhBQ 2RAYB { TWT.ʹҔᝎA';&V[q`F8-r>S7J2G^\7H&ZZ9[LaAƤ2D&U,T<м9C0cۚsB=wpכA+B1/U2MCB*RBYdt U-wtEޠB.\)oUCOܼ1 :pSI\}"4= Hi}d+b<+F1Kn:ԡ9)}^6;VsJx0,N%" jK߾p0 2?ij@pͳ߰*S-?U~ >~][p O3u8ޑ)Ng|3P~s˖hK6zmFk̰qbs?i,tgzJ# 3dz閸;Ǎ'iB?ݚlP'QRBmrTD5$螝=DcY3rCde>W;G۪cMcE邅VL«7IH}F,>uI2Ac_ԭ}W'?T(]Nd1<}v`,|vt`y24(QصIO(#]X# g[>Ch6r&DCugqmW4H8^*y'ؗl1KH7SXv/ LB'̑Q?/F*;B.*5#V y"z29b9xV.=a%uOοsvO Y|)0qM5íBذْ{_(bNVcz;Rb.]9O: }443ivĖ5Mw<7lV6`侬tqMќ0ijs.ԻDv\ˁ} SM6Z;o@OPK\J/Wu1smime/SignedInvalidRequireExplicitPolicyTest5.emlUT ҆?;7AUxYْȖ||gTόо ˛V$@-_?AfgwU}&& s܅*7uE||~C rKR_^8傿/]$;SXsK|ps+&M>$=}&:ñۿ]6OֻEMwJo&n>.]Mav5r*uU҆R5`L N6~tLeӭr>6!,\2avQ/Dz>E\~e/QaAa94ک ^J>kQeQ9TI[8}96X/~k7XgY>6a1V(ױ^/Hw͛͆F^x p - } bbfU׼*݀Ϙ%rh59$DܹqmeΜapwxz+״`k',墪k|NY}EzoK|P:3q*up 8Q #.Al@VHT 3&Zt6-pAEYGz}jDsJ A4^g4p C:JvB34y{ZP|V:H Ur2=8:G6M*G/޵]o3\Qmv%+syvl=c2x_VmXgد9΀?w,O nDp),8 xb-Ӗ~ڶ_[bث-,zhe=OUvJbDz(˹,ԁ]aE{Nz);L,NcksvmXm6!:VY]Ѻ 4`UMoSPմ?P^y؞h#I k'C<%Ԯc)׷g=6ĨaW-03YhBт( G eQ^<] [FI@ [Lzpmٍs*\{czW\8.CkͬǴu\wu\zMb9?1Żイwi_ P.#}""w^.!@ ! q) SR<3ĝ թ4ۺ$0tV r X_>l F|`VtpxFb9RkʥnnÑ*ut;a -X}˩kÜWs+G`xfq5f[ePk "DUG4ϠmVc|]V1vγȆ%$% Q@N:nEmL^KySAKJubrCEٝ-E@VyMCtj̬:~?W\|YwyyeysJ^5'8T?q۟~Ѓ0Pg}+QʛuhiʠX.~vyS^Λ#oIЉk{˺n.cD#mrǍuacDayn02_ FLm83u 4c2G#!GЯHk.k5 #gdu>;xLkĔ~X]U`k}),^+09s~_>uϻQe2`N/|;Eg%!4PDyg?Bۜt* Eo4lsO075vae~ex9CnCWˎ!HovftNvT3A3xi2srBuN PK\J/bgJ e%smime/SignedInvalidRevokedCATest2.emlUT ц?;7AUxXYH~n"v!53љڅ$. -hnr](Cd-K'3?gzIE&|4~xokoQg̽?="?Z/ _tnojؕ0x#~AgRxQ>±so07bgsOco'y#0lWux[`6eѠl?cݪʞ5-}ʓ<|Ԡ}$QqQ9{~[˿kxD~$Esv5JUHMq&Yϧ29±q@$)E"B8w*H6%aKN}CFjJcrY(`u@ze*/}D~!gW>oNT4l v6hcm쒛hCn)N X9yQJ)Z=/Gc.FYg_0Zn>st9Gg2yjh*W(ZAX"MS80MJ}>MͯD a%h=;9 s H\.s/K7e~{j-Ůg) XH镂[ H̹y$GYZ~PSGnW,)|k"㝀鶬ylວ᫃yZ"AO[Q{>tOe0 B3|w 4H+|m?'5qJ!#ą8,u<;)/iIޞ_p2'eh]JN}nz{DSg\Y+xy^'Lo"ܱf~qjg !wӠjiS`u7ķM$%xoEz } 3uI-{:H^i9 YiH`{0HJ {E!cLoL+).c߾h- *|e#7 h2XʃdϚ4)ȹڮm 2>w:'Xת/ b|}EʤD萬UyƊۺ[ˋ]qT +OcV܆8 >;L=Y5 u_~kXD;PQἚS63XG= +%^O!zF3nё8dLMifs+CR3ZIm Rk@=a 4@?L=K$&CU@{=(RUHZW+TaAŕprv6\6eE61֥p; VZrHcQvggH[&1tWE GJ,N㘏q'`J!"1yʻMJ$ZiQ>*Wz\jj^!_ .s ;7JpmS:yJN:ɺ?JLi#7ߏ/tGpancY_҈^ Hҵ&畈혋[쾻{v~L'iB f/3sv54ޢI{~+ų}ǃO/۳[ڿ]S'd}<&څl.z>MuQ_;LP2Y7 :cg.Z]s'XEU(چ;M0=jT݁ӯegCekexeǻZ|6:)oM+OBbhj#n`xܢxTup_4'lZq>d`lv]pƇC$R縴lY22H 2r! ؘTǰ+©S)F_$ʈmK;\Fr_[ ϾWo5$;;J4K+b^AVT9t# _;!^?CiSYoy_wnM L/G`Te_0XKk"K`ȵy\>7Ī$iy*fY; vvRZa;#KܴYf$cƨܢ^sUD~_Cp?a;Y#NS"ȩ e5x"Տ@a#䧛/>3Ӂ v[ &BN-mm$@g`)0nALe/krzHT"hlZz5+VGe !,x} FŶO~T\HKGi"e'!;0qH)>kr*̹?\9'U[w^mG렆πcSGs$h)h'E_"ǒjHoas?r>^n贻iI5;S[ kBf6p# QTpZ11'!5m!~Uf(/6ZvG.odW09^a[ڤp\&z _G^~>{yo`D lnRsn7c:WdKj>Mw7HMf;֔V!5^xrIw8m;I2O6̶¢D;FI ~,v5]{,.[H ̚y7PK\J/a4}s M%smime/SignedInvalidRevokedEETest3.emlUT ц?;7AUxW[H~^#سUW-"q (3sz7b $ʬX$mշ ۤMɒWt}}v̢Jx$ۤK8iy&ju ,ɵ.x">G8麀$_Tmcűs:s,FN92Qj{,P07KӨM4-"vܐѠp6g|wlx䟜v.lUfN%ZJ<e.6feB2ԟ8-,A'f Dqkids >Q $n0(d"L8&Dw HtLj ̹ry \=>i!Ǡ6U# OzrꠤslP}JnxYAs`H^~ )6e \f7퇷؂L| gWF1#1jR}{S;4uvJyͳčɍy[߳r3}mۮkXOuojvv4|wW j`mm]'wkg⣩%c%I`\`?'V0ҮXa]|jʔ2/]D wpYt,lփ ^_7~WgTQ/lS{ʴh`=aŜ>ŽaD[VqӑTv{h}N%?=:y||0 :Y].!n;W^+.њj6]x5F?ho;w7U缇/sŬ թ<0I^`=?Xpw\+61J%^J[8ն;PVvP"b F,S}eIqNL^ }Жn8x"[CVJ2k^ZŚM9o >w&z#>8UK:"V9s^w'}`tE/]Lʴ;u{6F0%[tەN w8>P/݇%d&.:Ɨql`H9eY\)Q ;a0 ɥH8m.n7Ox 9nCNLS`YZaaoɡHbRt$X\xfK-nLU]&e~s3ɷuX #q&q~"=ǂo.plqa?HK ޡcݺ_qWu淛/ER~^˗&Qy n</?՛wl[+*HcmMf&m]IuE~_oYCo#O_T2 Pс#a#RF;{X2 W^rT;S{G@0^F6~>Nl4l`՚s,;Ѷi>s s<&vk)]V _**Gɶp# 34nF;NZp '؀j ,l P(":2spիL~w7+1a  !\c<(0q{TX1% 4L-_зpRsz{lB̡4tFtՈm$ɏJW2z ӕOomW` ucZxird{zcD"dutYSk$zCGXgG{ q_\mUU!WϹ:\^Rquh*{k@##s+@4-up{GWLֳAa RNΆg _Yh 7uRx?f^"߹_^jSb̶ cE5g4sR߳w8Mُ2!!)cdgLdspn1%QQ bZ6}|B24mVR8"dRj?ˉkpzLzEMU[u~_PK\J/)C2smime/SignedInvalidRFC822nameConstraintsTest24.emlUT *҆?;7AUxWYX~#;U'xPExc/>ꙮ]A42(BCn&R'C|"j )b7/Ԍ3TQޭ \w4s bB»u־ ǴK1_C4^1Ĺ$ \XD Ps.Y )祽?H~r/VPkhY/b;g?ޯ`=`L'T\c)vA+xildw9?֭eknNayA*n#ec+ok^J=J2HsO+F1z,P]GAzʝ/vi&"Nr%Xe Ļ6]jS{ ԔEAWʎNdp_HP DӠccKW0A`i?\ыN!V#z_Â;/i]q\֦a Nlm쩡B$;L.RC28 yuNZ,/7 2x@ٴ|zT$I'_ P/ ךN]qq@' @QRI$;N?n’-Ս@Y?k!k˸=D#zȨ]!MD((#`Dߥ o1pL?@k:z?cfq1B4^.4G4"%(%Fanru$uAx:Iߓn}smI=rh)6{ZPK.Uޗ7rk"L}F>%> h\3<1V\i3kjphx;yk4TPAcd͞MW"3{/ W2-5d8GKʾ ^vӉu:w)Yx=w5 Wn5;dҍN킰C{sOJ qӱg=EjRtuBVGk ȯ=fe6Y} c%ìJZ0;X`]WUW'xЇd4Q_dJ=/I#k̃<̆e;dn. 67VRG8QJ Pk=^FS1?υՃr᮫nb.uSP-!cp<*'WN0o.} :y-;|MQɇM/a1 xfVO2m_h"m Pk@a?GڳW"ڍg6Tz3v3g@[;~CM eociu4Uzn(7v>l(5]Nm3W!d5m [,E\w퓸Z-*ǍӐ[UYC@A0Ch?v[=}~M'_O= r2 <>ü~109 }㧤O'>fFm8F-I/h MQگbguf:AqIIb?f"$z/5AD_=njf3 3X+r6'k6`=l߶+.-nʪYc_,S?^S9~갉:~oV5am{?L+|윕~_o$I#q}I=T2 >Ga{0ab^1B|aqV[b9xFD|]RiJdRtdVmـZ&t8x<ͥvocnU(L5$3 * JQ O'0 I" xe&14Vs6U0,w@ir0Ee&AcL'ajR3ʷg;"e-fX[c@TJ,ALC+ ˭( Ӊ:5gUpR#ў8NЋ~=bjyhC=30xYmse\@yTEQC;I7 1lU3Līu[7 g W9?cT Wq~HQ,Aifuw> #ٻuHx?R Uj.b}cD'sЇvAyŬ)$mZ!TXs-^B:2Va.\ ;nd9;2e~nߑ"~J̕\6! FuS1?䋎I/skva{d)=ߝd`nѭ:9al2͉6j|Vo/}ͅ&.r3V"vPxmSC)$cäRoAuH jٳXnlpnwc+^aZ;v~eb); SeealuOe;G"i:9_!s+W64z>[N|$Q 7mb86 5ozB`ʰZ*s zcYL׹/x@FPXsrg HxV~cQX~ap& C 'N O^^^b6b'orj*N؛ ѹN%zy5b9{%Yt$bt#z4xqysƷ.Ω3]j$}$1>\޲bXŽٶXa-SA/c)X/| ?>;Obi$Vh/EXFPGC;ӯk@q?|3T|gVO5OUN>ÊiN\.>s0LOc%`L]5-̍Hw"Ar.u֋U+qy#'Y?PK\J/+ 8smime/SignedInvalidSelfIssuedDNnameConstraintsTest20.emlUT (҆?;7AUxWٲ}66ZX@B+o%.㞞BAPr9dI͊mVW1YEU.j vY)IUatQнOY89FE&- ':2b^Vu^(x%j[/$}&E Ds9Iz6K(| e<3ϯOͪի8qUPYO|Ymֽu%^egEHҶBvW@ Ya\01l0B֢kWzWZg:u kb󩀪2M3'S;=~-[ud` Zƚ3fؖa H!qݾl"}A3͠/ڧ%$YFZw"9pW\LΞ-}j\'Nҋ_b"maC(nSVDsFp(9ęjCs[P lx܋ ˢqZHn+>5͑#oum&%l.`_p`17pi}Xatמdb݌iC]﮲Qav}XMjƬ%-/-Ҫ,n75Z UwQ3Mɘ{Fm@@< & 9 k`N]!Y .ųcT(N!t9i|[<(ϹE, ̙XҸ 8,ǂp|WG<Ɠ<= > ^co՚k3{fۏ(,Ck$Bv\ϛ'G%RA7] jplO÷ #lVQQ0~܃WV\dǣJ2<'*ilVy .)7¹7iAW3oN+/8(q|T˂ww_X]v Hya"`m ?Sg]]SY Q> _sԦ=GDtf _s<=2e|چ'Y_\$F+ݡ3<Ţ>NV+Ŋsf[\t}C>{ge'!\7z p&V}i<MTU=3}^aza@ zt:Ԃg[K(֯=N?d Мi뉵7qA'(Pĥ\w#>p~ݐz@뎟]DvNwy_%rFs%콼:WzrR7RWAI;ig-IN٢,_f{KrxJNэFʾ]U{ӿPK\J/1pv 7smime/SignedInvalidSelfIssuedinhibitAnyPolicyTest10.emlUT  ҆?;7AUxXْH}]%kzل"v7v&_?\Cŕ;w9 ҪF/F Nògv}%V.,}~ʇ'0xK$K@{p):7? I}H_{\0o\)~q > rAWedn\WzW|_]ү?ynn7Z¤]]uiS]?)׷(o}}$As:W7!y2P}BNvChalL,1zX%7eyrT{똏7ax]쬓/<`_{ E'FoM7EK{:65/z58CTtgJsrRzΎMS_WXOmmȟr!4 *0񱮀<Уg9QgXQD[4wX 債4kyr% a,UeI"_e$2BnG3IfLRCYkĎ=rːjIgvUVΗ [ߝ+zǙM$LXXn-lVSH8O ^e!PM6 *ڝakH+v&09LҳXh+5-.ce=qPj#ўalWy2-:>_ZD~kdO&!0 &zU)G=>Ws)dGQyT+D8u`P/ tpEw -wV7,fO =0Lʝ'I 921ʆ_zĖ 4,/A@Yc\w$= dAu_(>G`nǖjڝOX]QWh#㝎ݴ8VDJYm6RY.TU r C'Wb>1*Q>AMIY(XzGkM✸EzrpqGҾx%p(@g2&R0IFZu3ώ'˜YW{҉Y] v~J.$Խj+s1z227W@(`I1X\6U~k!,_s(  r(X(v2 xӌ6?bq~^;rOVMF#'0nj|)r?ds6RX>X`zr8: tNk}ujÆbU[_8ll irY,xsw㑫y"|nՙ)rV82GA ˝CػҢ&؞/ܨ#OW+I ^bFbʾ ـeH`u%~B成GUx[)l9אJ~C_Kx}ۊRwfVzE2#ښۀ|Sה%4yԉn{SbfجoԶJ*0UϘA[@*Ji4Ʃ/q-ߪ* Y5Fb1eaGa)P yFe3>l/z.w@0>Ž3Q& o(հ6)6yB.zz<!FNmΏV0)UT֏="S+!9Lo7 hd29? FsSybwJ E+&w7\$s# eI7K^u_𷖎;FߟSC$gv5*=m~h_G߁r r/Q*Q mʶD~xlS,^39mUnRs.fX8NJpzJnϛϒ#dW C&ZR/rIzfReqPW%U^zZXӅR:Cqg?-4G w@+1ʐ.|P&PzP?7䷝r[/y ؿӌ3zS1NJ*qC i*ysU($f6Wwۧ;ε-5Gʧ_ALhd(g@7[/B)gCEW, WlJ<4[]4.NȗZ[lÑ1n^ ;p(by(}K3uG!;˅?Gc q75ԹWkQ-WV0<7\}O 4?@ ꒁ-|+,?րD?{Ly@9#@$W:Se{]n3?StQ~v!zOd#kppdgmjtFB+״M/XgbvK0p4fu-7:tm,G _ }; !YO']5mqB 1C<(#;OV;&d<(ᴽǬeQ=l% kY+LExu48@qV4^[Ass+Hp5d ivIijF& ]^bY\0 >nFb{` ım%0G(.yynx<< -߫/*4;u>Mqj CSPTP]6(j8t|s[.' kwAvQ}ኛM.or"OX@z_OJ-(6LD Z#qB喋ݶ?KԺnc5BrAy IJ)99J|SgoߧW}u`/6jɛ?[xq~~;OMY4q Ӷe׷ No}~$Q[`MzWKi%YH@BfB ߟ*u k=W[SH^o=z?y'MhQr1XVaBL#ߠ7kLmͼ\2s:fgcmr%(2jse_ٶ0#t4gC%\\3M a(Dx~T0\$0"6Mi`SlRЗ jiXrW;K:͘ʰV޳|Y67FPA{I2cRB9u|~&H|[KZ1#;r*"+˅k-K 8D^+d8u(=||:(;I"HK_;^e)y04G*Tj wxmuU֎P$=rH*\œPc_K=Ҧs7+">iM! xsUd-C N *y\XCЗT4CԵVqe3Â7 PU1 xQH,+.yfX`j~.[#}&{V,F(@U̘#v˷ʊK nh\1 dybD%ThACkdM@c)_~g)F0hդPovFwv$VXŦ>Ux2= f9q&XmY=,z)n`qqu-G|,/7NeUH=OHfv *OKCkpn*\'zӖu :L .H^3QE38P6rgi̬#Q+sHL.:֭q]Qii\5ꞧ*d$|,m1BdP2:D΢NW6۶2r5NSr(TY(4LлzB Hbv76wc*SA4^k !ntKWä.P*&rSMsTʉYLSv[!cc} #w7CuL,x.֬*ʘt+ҋQB #$ᵧPT8p0nmˍ'iub(2BBQ6}Xܤ#gnVExX T_T,EOg4\/v`'(` Yp 0O5(y$RnُgṮh~B,Vuۭ,f H|)hloL&nHr*o*]v VZukr b#rA\3ݐG*J W2\ưufoX@2_jԸ7_\|r3¸ _rMiD <={?G Vx}tQݠ:3RYPV2%|݈螚^Tm*qҧ6M-tӾf5N. Q:uz>jt_5Y{ck MQ[1)"x- _JW> D R 3u1yh =;G-b+i_Qi7~k7 7?yнdtcfo8⴦-9|xwdWv tHc5TŅ+ܐLp=v)-Mx j궭Ulj:XXW"Uw# tYJd釟\\?Ֆ(phʛ"5\iUVOD U Z8\f^׏{LD/ 1O 䞻kXuV3nux5?[fp1A2vnnn 5èM3ESxJ$?!i,bSn%)n<+;֗~v} -O"<7YK)6o.Dsfw{d`CVmPe4&NvܽB3ʮfn@:+ҁ[>zuaw0CN?e{~Y0e|8 n}KA6o<}tF-}(Y0pąa߇P4v3eI~ V{(zLp ( ֌EX:s"ބ$xe5TFZ.7_4-+IaO] 74y-_j-O/m%)7vOwc&VuC#wpBG!>0oNOѭ>{ az!u$x{rE) 9OG)%}Kp^x6?cNj>NiqH9w:/(:\-•R.mxD3w#KX"krQQXQusǰܡ)hU|?@\i?]˝93íhǒW]yTg9G3hKÖ\Xs&:5"bto|P" 3A6nzf|?Ya(:Ogڃ(Cbwy?|e?p'>o޳K:Oz!vvXLuS/Z3C+L5*4iHH UjF6j7URsR/52O #˼xjR 3P%0msuqflIqh#֮7Ypt~ګV$^F5zPK\J/J;smime/SignedInvalidSelfIssuedinhibitPolicyMappingTest10.emlUT ҆?;7AUxْȶOE;Խ[ 'v2 c I ~Tnm}KPV*̕J*>o/Y|0k=ݐ]Ї~I Ƿ>N\p&U7ȢS\\>H}?[VY Ǻ»7MV%o&P~|?G G F>e"opxCя8q7?|L!\~׷ϒ*>D?_¶ǟivgu~_Wu-хṯ0aZ_.Y=J WמB !SK҉\I̘@c /ӵr**}b:{1|\4"b&&̬ްE2~BÚ8lՓ :(:^_7FmSZ0c ~IyOkӼTqG'nXZX>tm=gKbvg^=@'Px@˫͑4vL!%Y^H06!j5H\Z1ws\9P9NB@ӇeDӒ隒+} 'W|ɓ;=: NPItR9ݻ'ǂ1=&`J &`# K*;o06zb_en$C*蝧3r$"[?l1 wvXvY֐!V c%Q{Șp8]rGtSe{ TqV]-7|(⾀>a[/9 sjѴnffc` TzS[YC$N+hgU*c=y_D<} BP^ăY55Z7gքa`rfBװm  + 7^rPy)W.Z]DW|_7%^?5ܷ=AOW:/mMFysf"F X)G!ngoxק~?P%A@uDy-}aup+!+!'6TB)A[C)6ʆgjVaj3SJ.wD0L AGy{nvsV,Ӄ hyR!⃲-xW x͂:k[SK_p.q[^|/tH*>U7I'Cg4ϧqO!p4ߥ9tDzD°:͏Xlh pIvvyTsWVPf#VC AH9bvF>Ie#MAVf#2Dv'搨:s潽So4?j^@{m̖uO Į +a#}Giξ+ු,H;q}FrW@Iz$zD`DG\:D݊wNUmW]ypU:=Upk1rszP*HBD#AW' W'*TYz}bOE?koW?X^J]aF iB;'E[Ň͓>W ȫ;s>װVLf\ىkӍd\'\Ep%6{yqL*j1wZ2ŤyZGAaS`rL)/\{3D+D,aN-lL\{I59̽kaS[͐b~]KۉM|P^^EU!Y&ؿWy'^] ]Ӗ7TAi<z~g-i+s7yNi jYԆL4O,zZt0TARaRp1@fz E87i.&OM[\*C6a GvWtk̾ڞ/P*e`#S{zOo7J߹Oi,]Ao|y?O=]H *QIwUqQ`-l]ڲkjU(7O5ifOHގD jחb@\EZ= 6"OENܸ5*ڎb78DXU-[¤y\߈1awPlIXRl\6IԐ[. FC\P%>-}'O߸|.q+"Ҹ]jAQµ>6͎SFΞ0@ڞq"__1e?uD's?hO۬ [}wuF́līydqc:vSj}U60 \]d.dfrTZH_zPK\J/1;smime/SignedInvalidSelfIssuedinhibitPolicyMappingTest11.emlUT ҆?;7AUxYȲǟ/|~zsύS%$@ M|S3{4AtP]*+jETfдIY||CA ^R%A . ρ~r5e ?h3p}|%%b>-)MS%ި8Uћ˅D!_t `\0po\ C~ܠ ?o]4>Vp>\&wM]W?Iο>tpο$*tίN?RϞ8EJc U&\s8㿾I|"[:71~z*< 14 hTOz O-Ι[h)dM/#7>M.Ul,B|lLkW aRs\h~j-bDnn"fFoUiP>] h8[3ְ^XY)Pb6Me"դ@/y" 3GrRch\^l4j޳--q`HC~bOUWvNbocWcwhmOkxLcb^{c\p>M18֭1]Ab@nXp,qgņd} 74\P(43H9EvJG6 2]S5F\3\:qGY|0%̮rX8rM| u@u $֊Fǒ˥`sg[ "wT_=|i.Z?XM=KImiIIz^c-\}߳8*e/,}J`yvrkfrbo-"Z/hGYmmFgPl'mpądYjk,EXG<pwx|ߏ4aM{^X FK5S9)FFZ|4 J#zEcAw#J~ \T*gRR;#A_%VkoHg#e#'"f'k JS""ʓb]Ӧx\L&xq7fNblvuXjDS;:PSS\|!d/9.gg9BfBid\|!?>~7dw-n,G v71mZGFt *q a 9jO;-n1W*rj.Wu򭹮n}mȽV߸[ ,e5 nsO\LuwL#tVNAJ!҇k_;sQd ן>op3M~[rq"vA66hʀ xZY \hj0Ip{Tާ+?LQIKOYI:C-;!?idv^Eg̡򥖪*ƉډG"Q7p~VҗO?R`~7xhMHtOZ|sE0xv[$ؓbtwUI^G?Mv:M_00l y#Syhӱ"\k0}HCp }'^`s.>e*wޔ{rGUFQV穜%gF?(KL(jgxaͪۘ\[G7(ޣK)p4N(Gd cM UOvn#hY .m 8m"i+18.a})!Ѫ[xg+9箯+Sbs6xea"༆ޑJ>w͡5B݈>uv6|:6;{ `J+dqbr"ۧY`;^yT[A9ռB<5Mzs(kX:p^BHh'1>!s_JN@^+}T_`moMH@~fX3wO ;JOt]DgO@xdy VWW7kռuW9J7Gg](͸b7NY= Za.#7Z,b$}& ɥ+Z{$,n82(G`%TV{͗a\p8 [SGщ$SHΙ]SgNS?]ry_EGAzow?/0buh+LF68/0Ur$Fz^3mh)؃LV[JQ.:1Ph6rêtC¯ڇh ^ VgM&Ets=@İI%q dNoAyfcG]纞bGzE0QGOJe^UPo.yKc=) $KN=|3r5Tu\EfT0/S>`uo$!(}>k`~Ͻɟ0"m&4>'){F{V(pEi*ڲsU[ffHQ+P 7J$20$gurvr._ (|vMzF(׭T=U*hnp=_ˏB?zGUvgPl %Lv\lg-:xTUlWDau-z;[߸6){1+ 3u0wYfUݘ!'n~hIZAc+prq&%ƸxH4`cnWF?( ArM$"if&b$@/X٘SkI v5ec2Ǿʤy`3lqwf:6(:VzX.ėD$މJ3?X1XFȢ ӘiW$׽.&G@sr{ U o:).[UUX!WbxY)E'墚Dy)"y휌m8&d|أ&9SToU.\PȺZ'd& |+*d"xL=wBؤ5;VhM;ЯN|ɱo iVoyX>oNoiіLIh\(r 0*-L ,<u)Ȗ_gB)/a ; Y#Lz#D>kPMO>+i)p%j)D!@^8!?Dj 4#h+&j_Ajܯ 2;.wiX\!%7`\x_ńl[1v!:\x'bn򮵔*ړd^.Xpcq#pV: -M󶧁 |#cGUa6uY 3P(90@f)`ń~$Iڐqߴd s-Ċ\T = b gHLֲaBb1Fr3S-EXG'zd *!<-~6NYdbt[| ڵ&`{CM|z<FP\"Db{t=J/:H:4oL c'gߕ{Fr|X׮XOovɼg^y6zB&P*$@D SNf zqK8lls쭃 yٗNZ.Kr)UKqdt1eh]gdxE+sC T;VÚn-TR/]_qK{u74plPe!VQo5ٯ@5!N&+v>Y"^+xDrJ .QJ.1+yZ vEbD`p6h:':]%qaN%6ДN6]ILYII0+F?& H?uȴx_=}V-A\l{EaUSN?ԻE5 S]l PU뇹i_fu}H;-KIn;tT]h4n!6z\6FLxU(JZ'IkG^ @;=(6_&(_Picf#CЏp #@ɼ> k4!7ِʢ 2CqQy*x' +;X.̋| =3)( VT٫:dD>clkHTİAq¥k֤̣DCEX.ޏ:n>ΡnpNֶ7#+ `Y4AǶUʞEѿFsT+-2N83rӿͯX~姫ߡYn'>vĦaU*[] sz+3)Y^d4T>w w:7^ĹͬG2ٚ띌wVVkAp8t4^0h8ho03s#2sv>JIm>X>hV% c Mfk~_;\$/{{fTi`duz>J±XMYk]KCB=S-K-3..6G,F2Sbg hH٠~0%XnT^qRMjd=}8mRZ_<_mmûr!nCqNy$ެ%8^Fi"% rPn=;Г_{v=m|A/7-.`n97`rvy۷`{5S^8s (hޅGs vfg|4c bVk hrթѱx%" "N@q~AtAJ'K(<{]/ xY^RE%)1㈢нv%gT0ewLGwLo賄]`~I[.<NC' f)/>r<(dpM7D8rHH'4pPp /#O=Yzn{Ӻ8W̫kEV";kbXrl{&]PK\J/tq:smime/SignedInvalidSelfIssuedinhibitPolicyMappingTest9.emlUT ҆?;7AUxYWsH~; ޻D" D ¯ߦ4˖=cX*>NK5mVW_¬?4QݲEmDMY%cFU5L1zzxEQ۶—J3?봺ȂInJ^L\(QzIId>J`E` 傁O5`1^p%^03}^/+,t]u0OtSa-ݧ2+_:8mTQ):_T^ Ǟ+^Um5*C/FSmֽ:/HK88+>_(ZgJr}G=k8f4ͱ9 tvM P0BWJOՂ W¯bI&nM\k!F&@̻>VIUTXU5ݦW]Sbu"ݴJ$id ~^9>Z鑫ɓ' BB_q1C~“50 OTR}B~q}s8H` n80bϝ!cv#9d1ao۵H\m|9pF=gJ5!!Ʃnݙd}' bRk4rL>ԩ{ ϓ鴮\p o%P\ZcH0o8PXNB;_ջ䲓%1>oo} ׹Z.~O&yE +TD:DWvŋ  g {2\AoJâ<t@7k"UN tI([qyH* l~mwNi MV05T>5жKOKpS@>yzN +ǞKx2(]\YbyT: !ʬc-G1j֬TD>fe|+iO0:KQHLA TNW=ّ.gYRW 1:w~ s[Q/ F2Ebn߹J)̘{>MUMh޸dždOΰ~W½˅ȩϻqVyzSdm}"č"so_g29R2]gnC,$M V=bl9-w{1"pˣ)V_a5!\# ȓ6&?pH܍ѭ6ظ+&gY#/X }^&3Š ȚX'2}f{^!N ~^a{.h /Z*"Z *m=e٦%X%;"_9U S :JȨln+{ӔhD&+껮{׎G9Whk߻:UV*cʕ~=ɠ\kꝛIhVKz̀,Q-!RA^9M "uV%FiT;Q HZBn/Y1i[3rq i!rtKpY;z&h jķ>|\|_{v=0No8tW<r`Z>҈ t852  |®r[S;twyw:N%f:8`L:D>Qx IFR]N(I :2V{b=M:!'=D 2 ,,B䎧-'},e^=2\`/kOm}\<^˭G̾\<~vz߿x*#SҞ̉Yr,= d΋/BD~M$ 4*^#VmWA|Knۭ;:t.slzȚb#HY3O OuL j̘BB/:ǸYOv Qg_#v]. |W$Q9ǓeRqywAa$?r:IrW\2,sXFG7L>ar`YíhQ@x?kU{/ Nj鰉;?,Щ!(йb҃|"R.~!1iQ8^-DŽ"ZdJ!o;|ݥG^CdV%?#*ICo;3.8]_ w|8ƽt?}%_cl 7Lo o/PK\J/PcN 38smime/SignedInvalidSelfIssuedpathLenConstraintTest16.emlUT ҆?;7AUxY8syTcŦzz'6; ˯Au-]kwO<eX'╠wvԴIY3|DAR%Q..$>o6*¨Qн'wRޣLY]%Ef"#v>QzqNb߿±ko07Z3=$co{#0lWw|wẖBʟC\VYВn-}yס9I\D*{~[E޾xE{w\aR|Sؤ6^N 74%ɣ>_Pp}y@Zha2 Kf и1HVƐR:.E\zZgy68uz_+?mc^BCl l` vv6bl|GŲ.$,v=.3":t%d)I-b?jo>{Hfhxawu[뛹T١ Y?#=G/{ H~Dp scs\ů'@4{:~Zh~  ŋJm:ז>Y}YzV-i%[(mwC?XUc/;R"-$m y;nH苁cFRF XIIpV#Ӻ ~JΖݝmC! k\qvDu ЧR{}MӾKa~m>o?m݋OwOzi ]#v`qe/'gby5C:[ލ*]G\lem+0ʑC2yZ$Jax'| )}L$M#U>i+X o:qGsncpe,-kPĘ%,}AW'DE|%{6t&0 Su}>RwI'Wuk5pp>YG_gb Mwp|EGB CJ>T 75e|NrǠ: By5{EvR[YT=((/n1‚%z&w,ibeN81u,&nEIS9d^j0.~R7|}Q7Jo?R/I)?R7 ?n u=ՈF^acD 9[o:8uH8BVݢ] dɥ>\]{omq}pQ(ܕE?;9#.آ* ]}~) RqC!ԋ\H{GDx1T_DŚXEhٶ_SS9ǣC m Y5` 4_yb=*y\,a߇p!O ] w_^2o1#Xѭ0R?Z֒6@r\ƅmԯl; :YkPQL&YaUVW-@O":6S<cM:V&}?=4GCLV%-ű& 7km! U"/v\*syl*ZD߸{FWqᮂzWI%[7.n )=q5,RwQhXq2H yl JQި i&& ID* tJ2?5{?5 H? ~AT{~2PcMKTEڴ[>>|\V)\ҖؒtO,ve1O}܃>=8;,>e-Bh0bED >K$\8fɵ: _cE3ٿ!ody} _]G]%N,ؿ꩎:]_;7 ̇ʷUʮ *Q୴oNϊh Փi8:vؠtK:3|ڐi)M9Y:8HguvǨV6~mY*!Hq>{lRc vZ..ZQv׆ꎋCoD7Elx6' =R5ZM$ʷo|= ~߯Ypf/;CҶDqr_Jq֨;7~ĮHZ'X B8\c#(,_Cَe n I#ʱNMT4#0ܝUkEM8v9,ĵkn480Ƥ)LJPK\J/eWS V;smime/SignedInvalidSelfIssuedrequireExplicitPolicyTest7.emlUT ҆?;7AUxXٲH}d Y=c7}OpTwvnU3ð~q,'+l>a˅Q~kC?mҰއ]mF~aۺօU?ryܲ?Iiv u0@irSS~ڟk1r!]'7ı׋7#Ʒ؛oo8?S CoSW=r17h׼nznLG{K* >^\GhoͶ֫(l?q_i~y]HS¦]SwiW=?)oQZ_zɒtXR2 |Fkaؽ06[6!c` e?EMEVŭzK,Fר@ُ7onY;DR,ĮWW/j {#6koώy.ni'z8>MtcZa rz;tlb>QT%/|RI\| ˅<u=Ʊ3j_zPr'M&2cY$dbAPg|-kl%A>9JZr4WB&Ⱦ"v#!YPԕ5$ڤ,5Z^/fmV )x N*F"aNh/ dlqs/t <X=䩰1)*P\əNU͚h؎,0PCcv^E7LRCؼu=nVyA2r[/2F񅯎e#_L+{Pńw^9|+V8C*mzs96tZ Ӏ95c?blG4h {"o#{CC,ܵM/I_]ra^j!"(c(ڃD]fAl#qIl=sVXgjXogT:jrBD\Q{K^_ƾ?y}(?W̨ OvZ.~j$D2r.ҍd5=@IvD9lv#!]׎ah7aw>[Mv B2n-ks= aeqp-f\c7.`# Xn @*8C؊o3߭q9Jxl\<f ؚ 0+nE1ԧ1Ti-(f{5Cm@ʓKwv^L;5%mdwƝ&QXs wvI@Pqlc8ߡD;}5 @XcfbANEN-)⟻v>򉫔E&#j+'|R35G4OgHW ӺD1ZURt/:yb$!52>sT}l j 3]쥂QATkT_XZ72Z!p2'=D֗ u|Wy2A6?1XøQL|rrp)6Z2;^V-߳`DvlbW5 e@)Q&)o K3<|9|,L}q;-aڄ!]y;niډYVкO2UjkCe_oqr.C,.9}qSorGSݔà? M71s,}me8 wW@\f2ײDp2:`:/-!QfChVR*jjow#ԅ+bd3vv<7=܇ 2xg((p@ĢIC!BAap5r\y骞6QܪIJy.R24[ra t"Jn'NW| 69>8~Ks \PCw۵;'XDk>nB^;LxAL+×5G901OpZe %9ru!(JoܲȜ+R'gP~o,[%{y~3!L/^c'b~$ui-N˅I/Yn(M` oڛI+"ի35HrEv(ʷ@uqDv`CdlWr5q*[ ;sHp-~b " iBz"O_rqV]] t^ƪ2C!hWXα?t ȾzRj8] pm$^p5_rW6ZU&5 O^&r1M| ܺ*+u]mޭ9Ԛa&m?fA=̓>\ԱO'0`#>BeD OWr# lx+Ƴeܯӣ]J=Ǭg2nMmAc tɄeӭ ׵E:כGkxatj\) 3kLzηT ﵗWU^~J~,ۧ+gUKNZa٤y[/3YE[bKv.݉!L+v)QS53>‘26̎ߢ;ȃI~A7imrm%M`*tٍZim|<PK\J/;smime/SignedInvalidSelfIssuedrequireExplicitPolicyTest8.emlUT ҆?;7AUxYْH}xgBȞk.@ڗ7hڥo'*dXxv9C6mRv V}~kB?օmMD_~abֆe6?آ^7< 0>mۇ<'MHOuIwJ֍O<y}zE|~cvțwo(vg y m"N|w3=}*"[=m O۹Yt /y[Q|K 2mxJںj=n׹yw1/œ.<_ qOm{NۺyƙVʱia3!~Sb4Gizu]e,c׺'H{WARG:2f9t:z8#A4ßG*>Ƴ`$u^"92O~+n*,̘P1$i1lr Mai 32FC:qQm 8*Mk8YB )P@{=2# G${do|deCLw G1dn:9ZK׿Y + ƭ|/"YuB-pW]]qA4_{kiZ!;1ǐ,f~3aq!3 K^UDbsC]j\jm &(~0ɕw"Kv<-@ &u>&| #:{~AH.Q"h$R^H M_֫/߶\WTK[nùq/ f*oIE+uI!\kyY';ll (uFc?1qS=SO׫9xm\MZFnk܎}xٹ [zGiZX1/w/]OJЋ|B',>Szf*aSqQ JHfhȒɪ_;ه=#x=xף4^5KkU`! Q\|4s#& Dhi4Wn-b K1Nx}`ahYAyq69Np=* )N'b>cުY>t. Ѵ|X"ݵWykHO*R<(ggypt|gM+pKgb/︗zF:Fm`}k1DxfKͅiC$nzvٛ{aC+[L3S\&f3g:匞FDEfe%wChs+IAͤj:0 6{F ֫ 7 $81:ޥ;V #;Da40n>%omU1xYo+"VF-bh1~v+" $$o)=)b㿐4[.Xݷߦ"9W$S+x ZZ..>x,+aTe{}ќҤO.U%{ٗ_k' (Uwn6횺K}EmS$H\X{mUL3ðl0Z6Q!c`4֢…TzTZou &bc MuKnaK4!Ig6!>Z.[dO '~!/- j)wr 8dQKQzH#.C0$(hg.j_FN @X)m+& Am.Z3ҿ7Yѭ]Pqʞ# T뀒F V15BqF?^2)Z72G4eۚ9_ǺGtsdܿxKɞL tW?]G/$}+Z`cb6|BVC+I<#3W(7l@ / 﫭S(Ǽ|?GC>ԓn[f`Ke,yug~_>&#cD 흣˶[.Sbw#}8elxxZplhy*?{i/߉@5PZJc 0h&ܠԗY6ǝbS5k:7 )3lx䧔[S?Dj\uI*UaR^/zZwZ".^k1*|FDm&ZTxNnŰٓ`E^Jb] -~Ⱥ?c>Fi[Qʁh%Ft|8 il'wZ.=9s:b!ɝ5e'?}I[іQͨ8ͳv%|qF CM#W#w fe  _;$u{hBrArN Q5 ,Kx~K:yo8c @Sθ}'bъwdǞ\v#:sbM$J)ӣ21DǴ_'; aMC6[1c''rsԆpU,]"_#t~~~11?Ϣ@jZZ/0HED7 OO(6U-Yw44bEwCzq?s'=5|x$VTz d06*؞5M;/":ohok;XimGm%iZ{CEAUgtA| 3o+IxMܳ)q&7qpƿPK\J/ 9刯 5:smime/SignedInvalidSeparateCertificateandCRLKeysTest21.emlUT B҆?;7AUxXH"x52ݍɔ d~6U51 ARCϜDe۴>/_̨?/q6i\u {^G~I|󢍫('DYvb4Zqg¯}xlJDğD%IKrMPo>cw?/{I,԰[P\%yE-0=]WZ'clP4gZ&2-_C1ۦIG"Q%{ٖ_U{*J>/7?Cm6ޅ%uqI뼯,!qPZHhh2 4v ļ3L xX 2 *P:K(zϨVkM\z + ]2 h Pk³ׄdG^OWZdZ羽,ݲ V\^'&ѯIHUPZȓETe>z4>I4Ѿ\ A J2y@,ʴe&AmguFD1ҷ+Z$͞]P~0ʚ" T`)5TdtGaصlh2|fFdi흍geN/=/*-^Rȃcq"u΅Ȣչ"{湇2y蔵Gh']@T&q <xZ]#p:tb+&iER)T:^T]]^%61n4n)V4(\]QyuNlv{8GXg׵r|T/t(p?rS5{7|Ӳijۘ\+ 3 w:Fb2җSג4ft+M;I4³+ -eN11f'Wf X{L$& 4tPO7^% e0+>?a5㠬V =nkM٘[A/Oבg&ui1oLG`A*G}kq~ndNjyHc54ܕW>F}%?|O <=4N~^DU7&횧' L06_!|> w#G!DCjК ,l˜K9>|'w6e{^GvLeϾfO8s\ջ)2 Ҵ}_7h(yN1Aiڰ@0ʐ%nN'. GW$7Ts݌,#U26i,G$jtrj[\Ҳ{AOtTq/ $=9_VıGCfle]gL<]FţԒY4۵TLjFlnv4Y|e' 5IĨɔ\>FT ՟ԛ/׽cU]CAZiX_qf0ɞxk'ye*KW(g>fcM32| /2ktDCΌf[qAb?E`A<]֎ ΙlDϼɘ ~W%e[ՅgScbpO:*9R5ecN&lB[%R3K si,څo9msYoN7ZkX"n_qUנDȃ,]#va F3` G(bGLygqd3o_"s+{난RԺ9#jw43ֶMOؕdL溓c2 #e?midvAluj4ajr'$AU=m7P ^F;e=ގP{ fj|'ټ+巸3[gΚT5ʫލgYC>Î/gaq>aZV9!LX%f!oe1ZƈWIܶ̈́K9䪕{Qjm#Ĭ|tǰŒ dՎ"BiֻǓ] $rN= yB}㬭eX %v%ߝ{'uJ&BM87Xx2TBqq(㠱۠lk':44bY=Π=ҢU-RQ[_wiz۴:_8aoLIH:$[h49P=KL !go~C?PK\J/֨NS ?smime/SignedInvalidUnknownCriticalCertificateExtensionTest2.emlUT >҆?;7AUxU۲H}#ޝ},3=UBA.7 ~}D鈎i* Zkeְ$&O#dIYRIFɽYЏozG*>&)..$Qh#ȳkY%#ܳ:Fڤ|Xp4I>4=foj#d{o>jò3s1@/f<bֳA]%R5Gwy?>ZK2? G*޿|{P6!Qg%d I]Ĭ&kmgY=UmHF$TԖ|(@C w`AQb)uJAXyXoU$Vy,PKӨXd[{#DCn|wvk< 繳] μ"QBnV sYM"./¹j G3=9%hF1LEH22`oëY[B)z5II bp3V"pf¦K':;*W, zδ^M#?(-eK#m~c Mc#bQE'~Ox0-$[)Bn zfHh-qBHN7zM9Ĵ O:T \o5S=@AGZ?]I.tpU_xQ&u!BDnV!@a֫36<%bnxG-{Cg?MZe:zMD*%kɊ?3r.N$Q{K{DD4htQC۰ʦ*z7Vܟ7H !#z[hNO[6+z"-eF5VWeH@o՘ {)5IDaEp MVbxSZ8 `C8W;zVm)'Q%<vZٴyp ?_[?| X Uɗq&&䶓ܝvT=GhlXԁssݔvm8d;)JVyM|vʜ]6t<iȳh:'QށQ;t<=z-8`t+zb6i^@\=.3|A}O Pj<[՗ xF3UF;\o2r[pOqғ3=p671V4^:$<}ڋ.gVOim9 G{D[~Bd5+]s^8ztGwIEi,VXS$ofsCݲL_{ïZw|ʒ,eVkDy| e:WfZ\nUn^_"HspM%uYI4g욤q_"I"O_VXu hg ȬHa #?,DzZciw1(,:`һՑc?WӀ#Km\DNDi%-W^{K{5N':KګR M=+vNptlŌe{u2)5,O'Ȳк((83 ]}=:C{@ kYJ/܀#Ղ0d8iKk4sm5َnvs8K1sk XL-#uܣga }N:uZLZrLf< T9O)v37汵O: +~1#.~1̣ ]׺:Ȝ=S^ޒJXbE|H/,}$ г#} 1@j E'7dߣ@+%7N1YqUΤtY)I@._o@Q@sgRnv0r65e#Gy`.x7 }u >O'4{BF4;js 8d-:?בkk?'2x#<Ǽ֯eE:IXcܭ݆$ƜN:\X-餹^/^29u!q"T(a<X| '=s _`֩# =/"uP/}_wξx_Ӈ#hppNs肿ct?? ث2KrUë9܅ T%afۆ4x007Qճza(wU9Ҍb: !yi(her}K-řU̕;RȀ񊇘r66#1wVF?<H9щf{^PCooN 'miw;A?=fu)a?*t17Q=xR9دbNo2,.+w!l1sWy>ȸ Ն<ح /e9}@ 8A}yV]Pkź:s{PK\J/  0smime/SignedInvalidUnknownCRLExtensionTest10.emlUT ц?;7AUxiH?Tɢs&Ad& k4=y 7">7"OnEۼ-|fo>H?c:qڏũCs3oŐ6I"ĺFeo "Y8MմSBisa/hVCm/ı׋7{>Q\BaH,Yg\۠'ѡίeV]ԧϧ>Y&p ф5{=Q7NiIh6)mC]C^p8oSqNzAEQ[XF̵h9 0fNgJ;g[ Gyctt,u1S$]TY@yhǻGpۻ#6X^Bo Fqg }ށ>G8YLv+E1G¹Z9erv76ƷD {* s]xJ沠35Q~#3H: Mgw c;q>eZk#R< z=i>^^Bh ggIuB6{_Cӕ޳G_B|]j-5$6XgBE@H,o+Q=@CocM>}gU R8WQs 9o3[l0e'Lyv ܍m[GvNx ǙcaaGaT 2bdVB{!jA)mHI h(RJ&Βx:@JEm2p/M9E:(]i0F&u+IY= ? j20),[>{U_ @`, _e=60 2 8E_ 1eo>H*,K]NXBMK7MNz#&T[xS[Z;xasfZ9GODP}O+uQn> 3KQ<6qF/ژ?iS>6Tx%mEmw$H=^#2*f!S#SՑ.zy>5?7^xJפ32Q͐/PjL?ug1hծV~;2ͳ"_3"9Fm]UԄ[(#m]RKRUOKDS5gx[8e9;"7:Aw7ͪ mWjҧq+o_w b د*uQB){Y7anɥdC-L(P~b4liw)1mCEң,Ew 3QSrm;٘I?`Tyџʿj\JRj F,e45u ;ʖyun2'ޝ*;Kbfi5˗ЄKg~x8k}#^]ԎX}[ m$Q]2W)&i1VګLu@vwyb'5[.ϯrBln=gyGCa')?>3un;{].v7޴Z۴)[A$+fz;J~2!wǞ++<[,_]Niف9EJJĊ\r^,fÈɍ? W.UXu\NtrƋx+*-8b4ы*EM~ow{K=fHZ֟Zi\F˕V'Z=}Ϯ}-V3VS#w7Ł? ֶ{[_5e@s>0糛[iJrP!߿_PK\J/: /smime/SignedInvalidUnknownCRLExtensionTest9.emlUT ц?;7AUxWYH~#;U\TnOOLB& "~Rout0<yηdeXK}B#~C?mҰӇ]>R%_u<u>*?I9\,\]" &fWPM}7A>xîs 'z>G~~?S3wɔ"x$1 wxj~Reۤ{~|I]Wa%p{[fY~WV]ʯ'ۅ?S`5uY}IIM?}>,ol드\}hPXAph&`X2_zo*d^^ֺNFIbe]̓į"tW cZ=P75Лf}GҺL̹ܵJMZ v8~plŌyQy]#G!zx]d} y D; r &,XIpXxPtR_utm%!>nhp+uQzFX@SQ}HsTvI-3)x䊞*DUbw{'6T d{'WYu=T Α{,xNPث{!$+[yR3Ze!I=٠!0&a=Ɍ TXZIש  rgcY%ݯJO4՟jC?T~>p}F))Bjpt$ܧ7SC}8/.A)vŖ͞c#!֏͑U["YyWzs*9,:g,EPph1PCOvB?@0$ն||oFi϶2;ʳ4<Rz.h`rz7ަз~XX]恊gZ_SEt) {~.r@Z;ܕg2dd4np9zݎr13Amc]d<-j xekoH5s#\[ͭ pVz 0~)m4 0t;@ӈ#d`$ c t@Zhкd5'11:bZe^U]}Q8PrFT}5w9+hMCT+7]H>\ol<3U[XYl'1ViOTWQX,5ڸjVifhg\̨N.[kK<F&<惹 z=Hु-POG߳ pZo^m6s%.Ԁ @a#)dpƻ$v#6ł<@]:Ơ~& ZX O!S>>- V]%3nq~oK%Dž* Wl spwc=kc}ѪPahWI5 l{Amp|',Qdՙ Y&@;S(:n*띚-j12k( /7 HN8aK^idn(X$4 g ~rG,!;@-~0z1A4.]k^GϹ 9F%*6@ѝ>E0 7^ yˁ=8K7^oxvrsteߦ jmf\+ZGN5CYf{,ʦy2TVh}yX"ʚ\py_5[^; -GΚz׷E _C?~pȉ E2S@-c-DI^=<,#4_؎~nm2 nLӽO%LC5롙<Ӂ!=ibȎlc;CPKT /=N-5,,n?7PK\J/s nX /smime/SignedInvalidURInameConstraintsTest35.emlUT .҆?;7AUxWUdw&n@ thIHǎ=;S(| _^_cDGV1᥺EKMߛO|Gҽ?&u\DOB6a1Q]mc,_XRn>}Q?h_OO@2Lf47a1)MdoH_gE^E* ?Oۗ|//?G{UO2]_E,2cu'DUY_($'?OΗ,6Tuuf[zj5|I@{ ]<TxPYP荣dg8Yį@ZcMвH`]5{3{vN{9s{㑗;ϝ.N_-gF~\!wqfE;*3Yi-Gbc("M,,겈[~*]֏b N {48K_sV Y.٩BAcA'\Y[CO'|#v":]B$d6@W(N^Ʋd4sj~d:nC>Y);fL(&;E`s }r{d@X(;{~mq<"¨<'R .nУi uyrK|jDn?TxT Dh~,r8kx[kλ;u,SK90a<dvQ0mtf˪xP%5UlnC> R8M3m8*7yhS֍2`˘zDBPMDtWJ}WCa{>ί~~HyS }F%tRng}!2{톻BVJfqO~"THY澼):l cNAhs;̀$0% HS?"N6ΫlC;CMeRP BHv[K>uLdÁSZs>{wˏ'M-JUP |NYfdx"ԑXH?O}]%4-xعҶ ){/ b(No\vK&]%vijf4oX^Hi18g=yhiowf?5d׃sb-kV$xslwۜB=V-bĘϗ-w 5u[SNHii?_PK\J/Gg/smime/SignedInvalidURInameConstraintsTest37.emlUT .҆?;7AUxWiӢHF-;Sō-|,E9Oin#a&Id$Xj851)ߛnc?pyk꤈T[%Q>{p>#ېGE'lY58M=ȣr8@I]8y(fJ=/f:G,ߣ)5ҢfDS3Nߙl:S3ftD7NQ|ˏyqT?[}EA|25(4ET N*ܱؼR4Mr"8J[ ɲ鞲)}pTGlIdMƲl(@;È3b>,%GJ9,Ƒέo8Y̮P0GQcnZE8Ў3ʞ2#z&|x}.91G-ƲUD"#٧*z^:hu"p:1ĪAi c:isD@9:vvT802dV:D*"wT#KܧZfpe5o~{@#s^ׯN^3xLC#d&@i1vbݬgWL5Y f/Nlݦ֋-.j|gU5@%ꙷXnu4,HK H9b%8뱼H;jKn hɂc&;1O$ !l6dWb~fFp!O-+E/ujW,vt]iO;ۦ{t7uiEJ\1x8"+桼vѸL̰ O,Cm1ot3599-vfzݪ]B6ًv3F-3tH_-'ud"Yt ctx|D䗦t. /8=y$pE7܁G&?tsuFE܈>q}722B&گ78MKf< rPD=6>Wŕ޶db49$Qhf|hڥ&wiqu\=4iŜ&6^>~ -\q u6SgҦͩ_WyqoLEvc70T =w}gb+x&5D -" P:u*g3(uʆLċpgk鳵tE#VmwdM@қVi 15#CVB|chl=12nbٽTUezLM);*oemֶMi'ʏRd9KھP4;,c^ia'C9Ttw"ONdd P~d:'o.4!|+#bp*q&uPwn_ (g=kb_D6wrϔk!]E&=iTkwOEEHJJx[WIY۝2`&Q?k }PK\J/j $smime/SignedInvalidWrongCRLTest6.emlUT ц?;7AUxY6ǟ*̹xa1'H2x~6Gpf*MU2Ei_K nzmߨȮ?'4Κ,_e,ɇoGҵ.?'mZ%O\[q9Q{XdĻ6J6*|NE4􂢾1˿#HnP;O<֓)En񈯫,~6?lҬ9Izm4H.i(CO?ld:kÉ+wHxR#VS#rE Z~<^VV/mho\gC{] . zA3A&8dkI[n /tϗ9=_9g"XΗx${ffS* Z₳2gNRxTJAFt7ǦWxRӈ7DϭJ~d:N sĺǫ`uOy/0P:7].PnKu)u`R9jL|9}fɲL]»zY)%5B_ts#]lѱ'vNxHk'B/YoW!Uk(L,yR@@셯Pf8=xECww;1+~{sFu&`3OЧ+/;igH*.ËEWĿMx/u-xB9ؠ?5I1]ߥk);Ѳ,=VJ?rI44˶C-2ؚ<טՂdϛV;(PÀ;\Y^ d햛r(7my64.`J1/:ٳ@Ȭ{5t{ƃ"B4z!];<fp)OeFU귷f%sj=:_n|{hX-< dvwI'ή|=dx>Yܢmy)B1MPբȽv]FIEc5KP* $v,?i1!7X _Do/toޗ\?bI }Hfe*˯6Ǎ}[=WfgTPf5jd(XFS7ǹӞ,շ\^SQoPMyS$*09)VޔyDYN{2H9 \iɸC!fV$T&[qiU9&▝!b3lĐ1al]fps7[aVzZV~ށ;WažsHP. ƪWWd#"F#-XG)\=x.=HEgࠧ4Y'&ANT},@zN5]f6YppxI?J9X!%Hd: ~ )\m]k&8R̯"[pfwM64G" |E s9 {=hMe5sַqc"̘י,ZR_In|XЃ3tѐV,,p /s_軫1$ۊ%nbb <_b<#ijիh̽#h8XZa DjMW,&Θ띭$,W#;ܵdP]k z4I|$8"n" 98$@(B)(t@@"Wl`^T]lOysg` ҦUzt|mNU6p.8A#-|JDnai†|w߯;xyiKr飸Ԝ4=OWNkeswJC-)YU"+,/,V7FSl2_Rbη?QCՋ5ptťۇsO'O|翃V_33|Hs#bHS֠VLCmu\`LlLy̫1@ppd]#KPM8!oMuЦz慊<6>Y%<_|}V\yCl#q8,&N,?W9AoN4bzEdRAylo,`ۡ/8tڽഔhDJ1 N } ("/^ ;(CSR`Uv4)9_fl UeM tvWm;z鷔) &iq^CRiUx}4꽝)it) RRAAp&`f dئR{^{eRWk8 H45ÖݎHTzKr-Pnd]t(W^,m`*xۃޑw] ںJ^oR^ꄩ.ҕ),δ {ѡc,c#cOčƕ(?= PK\J/;(;{(smime/SignedOverlappingPoliciesTest6.emlUT  ҆?;7AUxkȖ?kS- (V:\! W#ȯ<]]՗\{?7*ō.ʯo/raW_(H4*QQۧ4}0j2.Y_{~]ev4H͆.ju~}olPA #7傁+~}PM7 A6o(u~őޖ *{x_G ϛZy[[sK2 ~\W_ZQ-*{vh>Iu~Ar㿾]"~*f2z\h E M';6iXbT%lh/Y\JwbIQP\}srM~DSISA-8 ̊]M=ϗG&205<8,3^HƑg# i'yL 6a)vdhp*g<#эSq Q,ܧnqBXn8įm/`%\]O\Q<дpS,iF0Fdr`-(M5+ܲGEzR6zޚCw(֮y~dլɢ 益ALF+TC,l*Dc6`ڽKR&%O YjPžދc&q>fUN"o,v*]-U0-`aB_C_x_`,)0QSлTL0 W5vN2hF% x'Ok"EJ#M1G|Qz.2x u*}[3"hX.L> {6Ql~衦S! PRE5m*8{:'tN9;;Ͻ3焞`$~O<4.Ī?x=gtމ-=[׮g_5G 3FVl}? !vy[G>ph]B!Xjf-FcCŃ,VZ?$M5%Hb̢0z BVP<<p=*#A31{бgG;Cdj3Qj*t6(Gם8.}?2LԻb`>I2r؎Q,`*|3+/d)0~.0 m{+V ?$$7p8JL;g,Ѓ_."-̉](˜Uestg85+{=8OVudq];tѭe\!Δ uUm;[h6l󴸸~[-N7;24S@,Roڳ\A}_q6 g>—r>g FdTmv>iQ3ʇccڟ{u[?F{mH*gyP sasK̗)!-~Nr,o4,[mDNP=م$z5($uow̳@*OgGjc⧦DA?>S0?uusB2ś2-s 0~kzU .I2!iFtP|E:o/p1[Ϯ{ܛ\5Z2 8-dmDѠԃGш8t'gP8%PgnYbd$i_s-2mTZhaZ㠎ޥ}wqއ{O 6nj +Ww+vwӊ*Aq#4s: pJ&O0dvEIp+۬ &3s墿++Dc$܂Ԭrؚ:-.Ew47SrQ|oV^/ӧ@UP-RBNX˞nfX+3˒P O|\p!Й@p2Xf Oͽw?fKIun)֐'tTSAjq~-#\?_u*x!(Xxc_(FFX]7oe%FĤJ341sY$Qs&gU/ꞟV=<)X.><@ 5}a>HԏwLogmybYͮ1qݮ³"[\!!ǝyڤ(dˌ5*jkWOB?y [<YE,XNc Kw>U; |G=#<߫u42!%0U3zWr1/]zs^PdQ6 lIJ'y2n>l2WsmPK\J/wd,Z )smime/SignedUserNoticeQualifierTest15.emlUT ҆?;7AUxVےJ}"ߝjhVOOL@@M,7䪠|uOĉ! Xl6J/vySOo8yuGv}^!;ˬM>:IabߢsK8fpKePu!N_t}/N}f|?'<7D8q">&S8ڇm[>áy"^JO奧6?i}eQŞoOaݝRM}]:wmgþ㬢)/ӯ~ msԳ{l3$KTUHR{hH]:2Jrt_»~iCgG,na@"l !b\$[^%2Q Ojg8YѤtDjCB[ZlQ^u ZԬ)uuq\<*Vg0r=5kY&~󗎷(C3IFI{T 8U/G M)MkC@E5\ns-z_)"_ivc{$=n ptW,sr27{u>kqݲ+7q DEm)oiݪAhrK3=~#j܏W t8T <8~jRʐ/:?Av@W6p?к2|~u&A3YvEt!HIISŻ.?y3@0돾%]SR]ڌ/v L`>L7tlt{m^cooS =8=}rʅg.6 Phi:gwqN'aJJv{kTA۠;ů r6cz)UiA89 (VƄ{2(kgV[UgC??H5l\Y;Tp6d]6XhDLb(Fc/C\\9-46R5os5ZMgTa^k9>=l0nPG94}e$`S6Ùps :\O'(l7oĒ$ϒ +,1f=$fQے|[9f [-[kQ_fHY3b7i\m_nm_MC[6Qx—~e6&\piSWMھ۶,J^n_9rUlmGeYH06\X1cakXI WrZS;G@4W;.:M@ G w r"w]JeS9KzctnCuvHap`~roFovX0QP) =]hIRv^Z1/\t`Ov拷1T|yٗs뿂< Ж/ѥBa3Hs'}[ 2^(k\nG=%Y6ʳ`w<V~B܅qQW5)s$]ѥ07#.fONWӟqGVg!f$U[wG #^`:Yhb>%* I,O^Ŷ%~-Ħ f#z31cG% .[bt+zIxB:ܹ,`JG^Y+I*X|dEb<1ɏ[?!d6x40bbyl,Fh3J3D`Pw[ڨt( {Iḇt1D:#^fΪ'Y3 wAc)+m\֘c27\'HgАڍ5@1JYhi# & v*5 X/sUuNn=ǝx/qѠ`{]PzX΃.;AA4ÏoH?? R )ܽK.}6Gj 6z#:ܯ WOs33_|R ֒mCMiǎǎ e# c?{=6QG$JF%OE@Ou`]0 ˦*zf4pz+WaS5yR^oyڢ1s@qvƐ`@>#u:SFĉD p:*ڝv:L.g8X*ZK)6 y+S uSs0xVJ'!/s_ǣ|RV _BT읅 }ka╧ַ9;e6ntfag((}E[_Cd40XoJRv穲5:)@v,zm64ڞ$Sb$j+ V1Ha1g =cC0$-IG",*k&t;CéG葞U=!0쑊DJ#|;~XT4 DxE VQȰ$wHUzRVɘt&?{=6t*:8y& 1JdRU=J~TqVL{\fHtmt(I5+;tu3).Lv(T.8#Tt¥Zʞ|jb&r;mxgG؟-gK·"'TD'۪wDT\Ug=0eL/oEi@k%}!^ IHw7ch/Cl\5C/+Q+}Ŗ)N'8-^jL׷{)bQ: w`M2} rl}2NBp@ wec|%qL`1;dER\&=KuF67Yr۹g}8Gަw\η̝@1_3ybm۹ ʤd8?n>kSSUx՟:<_KY8A kB6,'GӪ=geRnʒZʝKRNPaOuʭ)8zhŬT͖m 8}i<׃J.2j=Dެ/BЅrk*Ttj `$2?PK\J/bw )smime/SignedUserNoticeQualifierTest18.emlUT ҆?;7AUxWYH~#;.V exc-A6ESx19&IV.ߗ@ fu1>ӉUnI5YRutIEɭ, Ϩ~L'.?fmR*=̓mriuELV ?D1 L6@'\P]P+L3_=LeQu3$3XPKr6'g6pua?YMSจOeV&?ϧfJOq?M'۟M{jI:*1 6Y/Wᳶ۬{'1 :X,͊kʲZ־|~D#Ʋ8FЅ'g 'zp(J]VbYܶ% yUZTLwu0'7|HH"Na:K絷Go/iU2ʂZ \3;QEtQs%٧;GN<h`Ўđ0 :u^Cpe rR<i jk:בN;X*झq4^=ѱiG3ˆV ߝ# ;/S iZrzsۚ$cBY;CÑyU7-b./BG(yprYOnql5EI۞d89.0æyo )׭`jƕ+h$I+E >$U+Τs*x9R[ i r٣:ܜ#m)EDXdJƍyܪ2-m4}\Yh`ap s1(A8 9H,L(A 5CFUׄn̙*:[[_ "mpЊϷjKɽF^z;'H ge'YlS=ٗ5z`\/uA p0龍^`^!V)3>;paB:p#)Ǒ^Qwe[nVȢHygط + &kFB gX,? PPK75d);9 n0)EԗAkUbXSn-6{l.w/6{ޚW8'j i=&ݕ qgm'KʘWiKf/ll=-o'.CFqP@@nx"5ou&(WXṰ?s[կQ o_~[,dvX9"pI+9bz@qVV2wLoxF!G:7cEx&Ů6. \OMvcx^=0>G^]L'u),{K'O~RZFY8G<`. m#,+E0Qehd]<=/{1aNTQ1-VcɯXVG2Җ %y:<[.犵 ^u[k!~K2TI /<$X }W)Wwm,o>yV` 5j /j$vF9#?RnlNYb| Գ|S?}?PK\J/m% )smime/SignedUserNoticeQualifierTest19.emlUT ҆?;7AUxV[H~>twp#wVwwsI$X.} $#͊MZ35iFe{5m4N WDW0Y33j i%'jD`tMg45^KzMQߘO'>?g45;팡匦ߗ)M'lU$7YK]c8$E} [Y3D&e}:Gy)l?ػ_&o|TaZi?*\UE%H "><݊Z; }^ϝ# $v}z:BKVWq`3N3Ygx@0ƒ@{X/IGCcZAY"M}%@xkfx;ՠJOmnϳHآ-WG'34ilO_cH86 )8bidF G]…EmDevsJnDԬ²\ yNK~"^ +I rB1 RHЦFl'H :}" eEr%!DtB&S$.xBB˒mž;\xkF /0Xǎ9?Ծ=[bBK?EC 2t@H1t~oL'GC"r9syvqdkX"ƾKc=3a#xV^V?YD'"]B+q5J(o.K2!H2X1kWI(t ̊Vj ށ:=aS|5*۲b A^B)ue-[Hf xlXU?O01Ek$uNKpJ1چfX6U+^TyCG]>pm?muևf.ЉXGLji;䬔!ShOsqlՒsvN閱Q٠i+SpZxtpn:swEc>W{P{Y cmY[#W,9柛Lc7IO_pWH:E~2D^_w>eXEi|yy?TPUv/W"evN{7V]jx;:)GL!0o( 0jH܃P9ۢ?YU >:ģ/Ԋ-;%Kݤd(9t䨽sxzGnNNW繷Gorȕz ZPȨ48TpKtQW'We2Dw4 Im+gy^z{ r,m^8x3Ds Dtľ v{9vX:c$@\*`~{ 5LhHe,Q駓Kj}+=fF ƻ5Yw=> >8utrw<-\<(?v-E]H\2Cmqb]7"jO=lo% f#J7D V`j01JB]c[_ T#řthٚ onxN⍣/ď$(u4?e7Jr`6jXo3zs98&Lz }dxJicKé|CAb>Ecutib~U7e٭2k(%Mﳳm]q]q5Fңd@cNHHDH#ਫ਼rR~ ,B _gb#&=]㦣miSpלٍF.EC-nFD!qD"Xx&뻥oo'J1bN;?IUѺ5 f}JjRxذͯ;'Y͕.Z.5˖PYyI^ !4%OMOK jN!" nfO,UD&~/#{ l;5)j1#(5*,"r!ẗ@k'W4ro"*J0#\xx"^ 'pooU7;4k䢣}ڠЇ NbvN{nZs8(Gj[* 3c=]~zWoq8_)&{oˡrܬǽE;YqzΓa޶S q;ru掛Nv;ř%I'(,vϱ52_# ~?S=|А D6|/[t{w-o]h9dP|KUssc ~CFe{㺦:?b܂" /hA}.L>} #ON02 }Ycfðpb!\b-pXY7\,1>۶|t^ʫEa@s~nC~^/߬um"x2-0aVI^߮z@QTG͕'fPZH7h/hniZB/h*_ͧ^6B9zfFhr x >u, kuĠ2Z5L0a?]g7g^e?e˾8y]`V%hBzaz5}xY}uní:89 MTD|uz40j +Cpb Ҷ |\*Ul 4|:Z_K5~F|YNȎ.ckha=E4EqPaw$hoQQ\#Ƴd[C*}AVg׺8@!{-4%VP\ SʀwLb*ISDW|Ev(cb44XO@u>.9O *UN]](\{}{X + libYfprܨz4[tmq7nc#esa)8Y˨R40 #.JXhb ֍wyۍ~܉3&+QxeI JG|'KvG:Ǔzb2b4[{Rrl-9@yMptDH-FZ F p~eC02@` !`G}?&Є,XoYH5`'E b(2h23$Ŋ0*Z[gkL$1}S!)Sp/ZQlnMV8PŊ~@PlgxRi)> `:0ޢL=} O4~OG|7!}6?=+LyTUN.=DbiEy/37|I1褟Cv2&2yA\khzpN.&SΜ KsaٻR8=p}lqNwB2pj&aXF#؁Hf< {RCBtz HY= 16!Fc\' Wk6ތzD\zUYg8\w b|-!^{"|-AC6Z̘轌PMS ӯG#=A9ơE{ @@S@ c?r!L^AQd>07O%[{\iK]Z泐UX.a9G %5md \<~kjP zM4z-DziZ':1Mӭ+ /DӘ._bg0P-(!08!DH/M]Na߼>>Rx#fo'F5:R"?cB: w}^O|۱Y6^ښfO&9i`vUgW}s\w $N"{u.2&չJ̝*…: -QOi]iE«X&#x!UKRu{ BgR!P!GisJd+Ro<latn5E L7\_xyGvsN&Q%|v`cr`Y'[H=At=^OR fk̞q ATҁŦ䣾PJWrǫF̀"NJ38;[(7UfpTtgkL#uOi'JU җ5K/z@YV"@Ceh)< pR!YWPf|G6RAe:G0L5!7z$Nsnp_ډUcxI4jBsF$&w['Cm'ǩJք:&&'a{Kw'[)P*~?t^X|i@SeX۝<ڻwPJa- XwY,7sxy{0-+ٷw޽fbb3^8F˼d"3\֬l푖Yl #o):#\O=~ߞyRZ)sJӭ_Iul4`Lwu7n"+sa5CZi\%*4#MYW eKC[WL=+ ]8n5z.@Ҫnhke+t[VKYƵe}מ gּ]t N}B8Z+$) KAh'÷n_޿=PK\J/nL m3smime/SignedValidBasicSelfIssuedNewWithOldTest3.emlUT ҆?;7AUxX[ʖ~#;"g&N&w$Qr'ާR{9'bb2**M+.+E >qfUyFFL'vyaVgq..;ga-ӉTϳ6.`u?q}AE3Y8Ii{yYvE4q z:AqII?II ~g:'|M3nF=#4M'\Uv8O.^S.Kخ>]k}=fIG ~N xo.^9n> eXEY|6fgm]YVҠ0g笈z E٥WQIZds_ 0 I9JFB,Nѹr*$wq$)oJӰԋ'Zw;>!w1F͟(8z q:9^ݧw\)wkAFsYG#8IH^,BZOsQ=>>ILi4 !p0EAʁ݅5q|#1(I5vD ϻNXcAxՉVz9 u_yAAO'k~ˡ猷hЫ3 [^\LWz*xڧD̢ /"[%WD8I~g1pM{v<\p:HTPIlvZz`"9mGm~ 򍼞/>uS_]g,nCYM w^ǒIfϝ/nު dwI+oIo:a695dm>t4.7cw$ g_ Z`VtK۵y !HÃfY=pFQkB3*vZZ5`BI$n] ?@#\'L~BB=?b ȲJ͘B$ K1o]/W/ѝI<ҌD!h*a>kֿ.y-5lYOO*y{=U+%dVK(rsx-Mm5,A? $κIry1h8`F⓾ַAȬz + s<"EXZp ġ7NU%嶘 b Ԁ1y=ˠr5$rn"-7ƽm3y8|.QI|]Ǩ=#f[-}&KI<3c ׍%<ӗQŐCOߜz#"3qh1<>l*#(2d}tzt#c N3?-*BiyẑQuw_[ k և^vy՘7b 3VT681B/i:W}HǜeWDH3$6.11|WNcИXKc2T^at=}灿<sV^2iZE~dp)ajKq͂UHD߫xTQjHחSI0Uk tcI #i0lUXYM|,viu* ,CvyO]Q)%ϽMNm!b'o9ϧc(\}V&5?Q?~/p:y77?S!؁pNX`C|ag nO$VxMq>w;p{ @)q0M+k܇Ů]u`ƕzjv6߅'uP!ǫ\2S4 PjxrM`ssi1Oqu&sk9 Xv:[/Tȕ!5l83H$M'Rf"?- >,İ&Iؓ?^Ko?_uI_dg(}þ5oHJ#nA|M EF8xܟ)nn6۵tɥprň}+oai_1O??TOzc=}z`s6?a2o/+O3ɿ,+S¡`ޟJ2PWj9]f`ˍw[(@ڮEƁY.u =}|$^>ed0:|9e^v˅ahk7Fg5dc?VG\u0sOCj;;{0<~js)gn٢䞥;o>,}J19i1g4 Qڴ`w\Rd=(dfҶv~"# J;) żj%b/-w{ck)UZ4 鄼I+8&[kYMh_;PK\J/b6 m3smime/SignedValidBasicSelfIssuedNewWithOldTest4.emlUT ҆?;7AUxXYH~^?][ Q6oK   ~1Te(p}p Ϭ㢉U.n0n,[ZEWQd8q}\8AE Y0" #Z<,ܬ,EP j>S ~\NE4ڒEO8b >{Xk11uա?Xn+9tJv ͇2+ׇ[U}.}>*(n]&$n>pUXGY~\6^SnaVYVҠRIV}TI:\'k_Zd1 [q йSaSr_rŸ+8Wz[u 1,sަr +X݁M~c+]W4TlvCH,pV50दτ)v\:WI .~HҐbSLb4u0,*EeGx0jk>S}<#(WNa౎b V1K> ^BMEh,GNh4gkz͡on{oy1poފG,O([ j|Au%^+΂י'm\T#n T5qnHՀz8P%A&:(Znoe)в*Su D-Etoz%_+n:k{+6z;4 ՋI klez\F*GCzuC䁸%Ch E?xdևR *ܾjI0k fFi-;)bxuW!MuBk]wzߎiEJYpxZԷ$[՜π B6urM#YS>AlymA.p $^&86(>oa{l1ii_=<5z1%VTEOexF5`A$XcS:,m`d& ֳ@XQxy?iiEX7,rX8qʨo%?+E\zjFMT u5&hmvM97Q9%7)6@rϾdUCJ|tsmT12RKdz P5%he`a39!ُf6ثmUTgG*Mx4\Wϊ+ 58J}ŬP~`862HjWfi\W!aOz>u&z5Uc]KY|^H9 qz7f*'M _0CSNZJ BL bSCEC ޓ| r̈́݀j̓uv>4XKr"[حn\J]RGhk5 &ZGPX@\bӓ>%A"[l7V.ؽ;5mʎWٻeT˟|^)&󴑉{f|}$;P/<s4? |ꆦ=H_pݼ'|w,B).=5WUHX ǃ>UFkܷkq£p~8@%_zܪc"aqcGiqcX=zdF6?6sĕuP"K!*[r ԋFK+ՒXI?o.1kFj'&quVZǾTjqqOOC̢ĵ*>yςz,ǻٛ'z%.RZz3.\>W]>puzwUHgz淟Ne/o(b0sR'_13OIB$4YV$~'"35$SJTyy.f<1$(m=ls_s MbNOw6[9&n-[[L!:6i~7o {BcTUbs>{tRD~΁_vUפ8*UG7t\emF$ ~?sg*g_05ώ3Yӻeg4 o6t ?. Z}&b9wzqme$7Ll'rr3i#/.OǪ5mq8g%IAt;GE.oX1,`lnTeo)sc5iј%oq4;|cZbE)¢W( y^wM糿?@y;ZzNS#|BҢ\3aҏH55gMήƽ㘄tq^U]R5ǡY"8g O9 !q'|AW|toΦ4أ f}FKv?WU9~7kHVsz2OC;NGva+ځŒ\t~)ǭKS4* k(wU!V,7> дDNZ8#l>KCϹ+j\xz>`,Iݎݻ.KOQVxX< :2خ:ϖ'+cCf(!c#n:,vd "1Y+M2X}*33 %[L/$C4Mn+S|PK\J/H + G3smime/SignedValidBasicSelfIssuedOldWithNewTest1.emlUT ҆?;7AUxXٲȵ}Dsр,H iBz'nNo?pdfOk _ "3h0k]m]o~J|&uuUab>< /h. f\\]VDs֧ 5Ag(:?4I4OԎ_3ׅf  I~~$b>c^ x\5~)2yѽ_/]Tq%{*gjk (W.뚺}i^\"djON فcYY#k &v%s&a-!>U\2{G*ϪHtQhK\*MJ-"lBjk\Bj&1rzCxg8:=3|h;3Siݲ 8V¨ JOׄ{&IHUP:7Y$VS8i>{, jyH™,0 /@ :y"q(@P[ؿĢjar} VZ;O?=PGz77Ǟx#.6E#~x缋Bgq)ȻQ@-ZdI䲠E3 - ~HՀ@Z7>T~<ĥ-ZЪ|7-X1N5R2£>0n}T!ktk)p@ ~u+ݠVzi2 +&̦;L1<~>kʨYv`djs(+7޵Awp;`|7k{پQ$>D?Ch>[4lw:&IO܋>p@{Zw\w<9;$D!5IzKD[<ՠ `f.a|ю丽v.>T2812:.P U@Ky|E{>ӵH4fT:?2 *T+gj˛QO*(Iz;2%8nٽ dCYH1&1pHx?qքȚwє3u Ժ(  ?`{y+"w/_ }`(Ka()XH;U:ElBN@, Ā,@ 6Ml 0[&1vJQ 0~5_F}zxVYtWݮ,P.5ɜSCܕuH'& SNa1srT/rUc)r"K:W=:K}FZ|6)XT7l&PV*^k9>TvTFIl2HQ/" >y8\A#5G=0 Q<dsp xcAdKV4P`b ti=O]?,VwDW9ph-gZJ=#&#z*n9= ݪBQC49Zv }ōmh͵eIh ݥ53׺hA}g9-sδYc`3BG?4z ӀZ҈rNuJr ڕYMbHC9JHg@^(39 HG܉ꀉݷ<]LKua,`Iuas>ș؄5/gsn,7h4ٯSe4&\ƣz#^FM%SXC㣲P㱘ytpǸ]&nvjOtZݓa(u>{:Av31ŏ{nswÒY4k9zR $/?tZCܖ3Hhh@$YMvqY[P ۲ |0x$yoT%i}[1i2W. *]VՂ{=*qk<΋GNJCSitNjJYL!WZ#Y"?+Vѿ2[w#4vg@Y9hy%m )4*Ew֤؎)ˑeWYt:֛ ^?rhW} =+;llHΎ@y z5-ydSz-k.n^K~{j*:PK\J/ͭm c$smime/SignedValidcRLIssuerTest28.emlUT 8҆?;7AUxXْH}έ"Mh $ ! IZdeu-YՓXZ&P'74i]PS\(=Iu5iQr4 ?P}K]4I'ط}D7,%jܒˋivPU7Vk:PHfxx^Lb;@" !M}eʼJNbٝi5ȧǨҋXN^ QMvy vfxn޺7^70~YY|aǯosQS(j_*SEǀp=x@mR@\ojD3Ak \V䎐w]9Ht-Lc(CO?jhm[{6!9n_Q[ :&j;yUU/h6-o>wVsB=rB N>-a;lG[ }IiPu橼lIQ=@~#_Q,`8-ꬬ݀0]Q wt7yNr}sykOW)v!wH $w$ Ϻ ( ZpE"Lnj<*gCvgBszxЊ: UHXdqjvI 8w@IQPgq(i~}⦇_(m#+qK`@ Z#ZSq=[( ̗lxD@ [>0.I-ד&;]R~_=+PzCi*]8VgK3e٧]mPXPOw6z }()B~%dIOJ9s\],hz+٩]k0M0Sa 9sa,ѓk]uJ7Ev0L~ax >f,{0/=XfL>`Yeۼ$ڢry'Te 2#c3[l[ھ!WTXY[_c5M3\xQys dJihfAG-yfWw'3r#ƿFMmvag{P1H-B;]i 3.ī׫5(?c 3c-&L<>Ğ۫+})b=SO}̷_+bgޔk/{;ŋٷSl^U\JqsJ=mAhDs'i  bBM sFaI5=gr (I4С;YX0 %F.ΎӍOUf.JTP^tVN39Yi:dKb+(k6&gD_W7s<4-íz^KXֵǤrE=W}yO:׮5SC0;I݉z(;_k ~=h[<"f8s 6׆ij*9MFW:Cl10DTIjwM<$yvOxo1 ]NqcXj'S4I:跳ppOPL+qrp_ob"wDrY{k8##q/Q${~V$4`-!_8;mG~g|0ݷ_[Wz]cgq`S; ƚuoejO7OυS"[kCg ؤެm)Lw>Z9],؇yj@Pv7KF@,{$, hI@_+Mn==w z̊|`G"Nq_;w{ǯ*!b"̙:3Z<1X"8ͱϠҋ7+YgG[97+UD9:9T{*NLz3;0?((>2C9v  HnqcŅUSK͂e\IMo I-4SJ=qk_!+sݟհŭDd;RYfE z(o*T߿{"23}O2ξY.cb}Q"?Gܽ4vCrKkPW':Z:L{ǩP?]XDZGE;]22gux0,9cWxCkJҒ=W],~dfSEPK\J/gH' $smime/SignedValidcRLIssuerTest29.emlUT 8҆?;7AUxXYH#ީfuodG;AvOꪮTW8a<+R9ݚ>QӉU~iӭM4ߒ1֜tɖ=Na4z ͭ4tNM'O H"/oN'<>xK"}Iy f${Nj]?Y/yqfLoߧW&)t__.n~ħ' (oߜ-|\&m_%^-Nӏ>_HQU⪛SΏPFx9oW0 '2&Oa-#!522ZG.:ϪHr؈[w$^I\|+xҫVJߓ=o\aNnspq:Jgݥ׹Wz ,Hި50k=P[$*(\"dGw28"P]ȧ xh3xa@.qz).L4ښNA;C$8v't.# Q:j?xa,FNUϫ h:x& أ#ŝHy晴mypxmctqbiP*R 4sJ뎄a39Nux^?e_]ogg>32,C.ω!ۻ-NJ}3MNܙ Hr$m}28_5T

ICe>aȾ?2xvk[ yzNtB3Vis O/֕!z!Zs#_jRa8G˜^Ru`^3BWC=t3ɽw _~Cs~ v./X|f٪pQ̪[G&\q~1Η‘Prޮׇ<Đ GxpzF5p_Dhޱ!XR~,H182MW{zʁ4;MEC%gB+:]6NU6 ;<r'>:ŝFhhQtG6eiğ~NVg|[9_T1i?UTY K֫/&L5u >Ng옕ɷ~oE5~]틧[=k04ͤ) tN[@2B9 S=lmrXeX#oi;0Roy:EZ Dm1)؝&\%?;vޒ* ޹VҨ>? Gѿi,"}EH~iPC I H'ٰ3“B;rsTu u _O e;*=8:1rƘ0Ӽ Y@ta=P_(:t*Lq~}aRf=8XvDsϗFW.V_V̙-[J]eߙ40Nɹ{H6IG6Cu^)wşNP*Tz؈ :b"*-Ljp(g~˂;_Q?oQ_U=|]ff^a_y&ڿCe25rЁ}_Ӹr ےtmk#~y̴.f9P~.9bv^,,a X-.yʥpl❲DBjɃlq'PښK5Sz:%;(#<#-54/k_I)eBMo uL(WʄbT&9{%9)+l3w _+PvC}]™#]YhAF3%*[{LLaeݹ{ey:6䓭xȳ}NfVfb=Z)^PA0E l+nw.D'2`QDvV-I{A2DmMOہD} ;c"Ղˡm S-ԹZFsWncQq[!Msx9 }6Ӥu3?|2 ^O'_n#Lr 0x䨕{T47q:%М- RٝU5u7Jr[Vw.xcvÙux'`l2sP2Fji- ܜTyJ5ͅ{񠢬ڿPK\J/&G m$smime/SignedValidcRLIssuerTest33.emlUT :҆?;7AUx͘[ؖǟCTgnM |٘U]3g"&32*vZo]D$U2) ?.as%9&-n&,#KCbyFjkx~1qP4n~")1|S9AF.xako/9ϗ)//$AP/5}M_^ 2Uy~2'|=hrfHfI2 >}<-oEOn'XUۋ6!=zKS$~1Ïvo$Ij9:HW~, Kc 2y" )DL%" drT/MqJpӓO./[.nus`ω{ޏGºoLꐫ̵6SV kGLSOWX$LsRi^i<Ұ"PmaV&ZNg5gTЪ `jB&FeNHDŀaj=µfu8K6KX (c_A92ԩKxdOo)!iYaMl=t=bcY:w˄kNcb{-wo#A[!ԩ$02e&8KUK0zLo r26r :aLSM?T>}šk Q+yg sCksʱW7F˲|7TX{ޟ铼#v {VlE:kJ:Sx ߩm E{iK^/!H8-UHZqF |W77ޓ.#mk&'zX(a:Qr]`Ӌ퀉fC̤U!h%I~oQr`>N [f  E|D!RV2n h91,zwmz9k[E۔YQmuSo=DV@JqsZ3s'{juUf19Odi5YRN&rMdD U8CXB]a(|@xo C K c#M浘7'{UVs ֪pe"=i2VrXRS#Lv˼W8Bp |1r9jIgg nwU^YKiqC3k{J^G:Z[#\IR7%qy{,5Oj-}RpwYv?,݃GVx+ $^=gqj5 Uq``B3qpK ɾb2 x] T6^/NK,.rp؈Lb`J-ۅ4+VDn5kc)np?b~Y,o :8x(Yм,)!*9׎Ǜ/iey'k͂5ҵIy#YKg8W,g_Wj[Rn;dS~~s& Px\2H4^43pm&3p6 k?.n0\3>V:CQ, ?XWmo@F)Iq#{^ 6ߙ=fFk<*:2kWt]"aESEm? pVoGcө&#f.1zhgaE/)z6}փ ~g#BgzEBEB8t"8Yh3u.J'ʳ #}(E}mgjV;*uM:9WOߣ0|5q}N mToarL[Wߜ ҙoѳI0B`Z%ӿ 'hKa_xq7(dsRh>5̖;n^5Whw>5ٕ ޝ4e{sljNik',ܫ(#fDPK\J/lR3 |"smime/SignedValiddeltaCRLTest2.emlUT :҆?;7AUxXiJ) LY$B%{A\Ayۨy|}hMk߆^N?^VjhAyLe{MͥlY=m o(~o,Wi[br dLI d06kc?10_Rl`ʤ~e~uQGޚM?53K#^ٺUP2@'}윙aA $S;.ݶk>[%nݚrUwuemV})bjk\۹kAL@Y Ka8LǮg)LTnۑЂj&kLGܼ`lNi1-S0Zo& se&h^.R{ɚ 'Pv:Aw\ 7w㲈g^MؒZa9I~)]yc^Z`u,t* :t(t#%,0- ɱL9ݱGP+^}y@ZK%L= EjVRdùۻ3wbo*Xfd/)X]T\eb"<Ҙ^LnS$L7륎ѺTZL7ZW"- 6o+,ϕEq>*t"*\\OzA0`F`_E6m^OQ?|r~"fNT-5hAK֋m172Z[ƙ-S1 z?;0&[͑ybbo{^=b c-KV?D]ݿ)AI/(JwUZ]lotEjDޔkeau SOmt ѽOhHooV ^ϵ؞KLkתY2"Eg.rаG#^r\+{&RPأr3xh wĢ |HxSwo\GL*Ja|IfN"pdU%ŐLJf u-fy14VJt"jL6O[m3a6*J#b+MM8BQZ. wAi ܓ)ÍEELszڔ[D-ўBBY]@n b߄RI,b"Q^ ;5Y" =ZYfgS1^U3_r25DzF?XE2\62M1XqFp\!#r|`{]G֬"=xj Ao8_>s,1ً~ɟ3D'\@o*m1G3=Gg`ntps\ a}J8ksj6\e1\Mr/Q]MHgt{Y2֊ݶԙvc5hyMΕ4^U|nYY`]ǕdCza tmx$[B}=t`)C'JF!3{ԏ-<N<^jL^{l;\:}1˅3:;[ZLT>ssZJos?SMgmт2/ ltlij[&1hz:GcgsPiз++DzL]SB PK\J/7 |"smime/SignedValiddeltaCRLTest5.emlUT <҆?;7AUxXkHFv VQ

pPUn|CSybgo#L>ίGSbF4ohLpyMBd<޽^>z,ɂFU&6?WIO'v9.+ݼ )ɣVbTעJWܺv8#?$ >?Xp+@ق,*ײad(¬pfa9TH\K\-1mN5;w"{~'D_ޡT+s9̩=üznMnO0w `,Z(lG>-fOˬ$Щ(35$~8(˂\jH If A_eP-&cZn3aXpYFz4sJLf6\c#K%>s;zRxԈ`DA*tR3SV \#[fǹFk򎜣LjOyB[{@AEb),;r/n(gI}a#i$LQf;m7i>]N٘Jޞ<ڠYli,Gtg:ޯv=d}Ven5m;7QUUZ- ٭ F:,Sn k& ݂MP*Fՙɵt WYah:C5|3<"~wsR8bKj<6˻uOQq@O!b (PIr jĿr$P}7A<\< Dt̏v nܘ)Aܢ>L/A4 Q|]1+mހ9TKܯ^5{Qr}aOr(]q=a NX:Kk%d\:xZ+eLÛFK1Qʖ7tqpkۘK.s  b&A#_H0lh;=lB(=s~Hxe;Ot&qid2 ]r~<ìH@"5vcPDXIŜ!S:r y`Vd-/`ާ 8f}z\R)9_wTJ_` ϕ90pahW)9iSzHSX+(n4&Fl`RbH{m2(u:reIMDaD/N*[=CrGw"|=X$2\Gdj38q)| F]Mc>zMC֬^zo:`qA_1/0ƨf/#M ':zWi}Ox)vn?s㢾ɆP( ѵKXg&䪿*;7SÁќ%%z^ 2rvm*@[E|lWƤ #-Ƚ^ꘝK#'`qcZ^ͣd=G `xN~~_ȿPK\J/$#6 |"smime/SignedValiddeltaCRLTest7.emlUT <҆?;7AUxkH?݂xL&U7墀Mٞ٪$#9'XX';*Fgj80Q9_mܴa\! }示 |]o&.-58a6+.6ź-NG#S;S9Λ|H z28b(09]S&; #>qOlr OD)*\._^XJv)f2-jdsE,ffas*Gb"ʎ'la8(#dUZ{xsǙ*/M\JiWiGiOpҕٕGɵۃjI Yhc<߸H+%׊]KESN{824ǩ&!X$?I-W0xN q%E ԋ_ ܞH[2ci)͒- }Gx:@,}]Smb w-QO*1&+M$:uFqw̿FDǘ:c3N;qw{ph08.5vE`8''ˏٞ[Mpo}U7?ƒB|5Ju}-12s,p5=/Q;{c dT13~J|v%I|Li+}U4EبSǝxKvD$-7pQe;zL@atW#fN}UdT%ŒL*vmMpxZ h.EkoKZ/tGy߻ := ѨVג#W*OM<8'jCuF@sڑ.ÏYAtqveV C:Mϴ ʏavy%JI[l&Tj iGN'J{8x+ۃ,* 3>#<7/"̭Oc_hOp[F{ wtzw}WxϏثۄv>眭q^Ud(NnW&xޮMOWO5q[j*)Ӟ6-u.B~ߋL3yfA©RKGړ63X&jЈTB>gB.r=LHȘCMz|fidh 9*t_U5(T.X Wi.>)S^N~Oh$OO.)櫍|Wi7!b ϙqn\Z:`6N2㻍;ov'.l.8}/y `c_Hnʓ{=*|fYƒ3օ'egZ#!T|AiA_uyf%=r.:إ$,SuH/Sڞ|zufxvKξ3+0n^\nT_wסXqHePgYQnq;p+f6ԱT2/ yG d3pxz%Yp31& : X^_tg{-anԃ}2P`TrRZ{MQMSw@H=3wIR;gVMJ1sAGR.--¶ٹx#R/Lj§P;EhL6yauNYC|xt"t:~zK.]auGO}Eu=A7tkuG/%}[]UxS][4K$r84j3`EtB|2dH{9`x]x"0Ts0޴IB,T*~01RtqҦ%ؔ Y搌NrשUo ;-}LyY|=EcڑGY~p8D89ŅiFd,5v*>RdV s@+cvi!HڗP`G!ξ=O% <@ȥ)3k Kk ~@뽞nAx<2Cxpؼc MdT^Phyplы1^n[.ֱ! +PY mObTC@+&Y'Rgդf"-2!M2mt^] ~87u`etQ(Ucݣ.+E QcXv&={ ?؇9JVs*+o=-jJkRN%aC= bGE0JS#k OunDo< gҪ;Ogd[ ʠO_!Nd C~=ߝ 𪊽ÝTܲۚZ$HvwVe`CJo%Kі.8&Ee}2"Q=/W]I' (-8x9݅MjUEmT`qqoEpmI[=d*lKLa3tn`L Bd]Y0B@?D -:(<(3+ pٙ-h[k 6};")/)x)岥Cqr4'6T~op,`n& ]YQ 9s0յ"VD 3QWk =%vGMJ{/o By"WMfnTD:z up 4S0C\Ͼc]B`; HgU^:yv.2 qk ;EYrs!nIx^qqnZks6nqM}F*[d7N*հqhE׭4q"KTڠ`ߔsFķZ^q}*=nDD,tS@uG|@wOթ&x筘;;B;џoDHKQ{EG#iEs):dST>Wfe`2"6`g,ӪVY{l昍c͸M_<氇3[dS~?{5otDdBv9ƒN䆊T-hZN2<&]Bo@wX-Wt^zhDtNYȽj.>I~)HuW>Pm|9tB2 5uw ~0-}FE} AƅS=:! `Hk4"Ng=W{iĄ+E,PT-*}h~<<t3pAXWE?"QƜt0LL@|y9ݛAd{j qKQ/5Iy.5Xn˽HA+JQ.P2y3GĽH xG+l徲b[/eW|O H<*k͔ xl>r tѾm(\ʸ ׻8%ˋ/t ;IEZ{ ϗn:-:ðZNhh'"b϶Vs̨u8GO֢ ĮţqD6P-(eDwKw]ij5smL%HN5Mm6Z/ָȃOwʏc/  ?QTw7|7-}ud䬃c. N7_X5;֋"x_Jm+=wW5=#bO:$fIŸ.@%(tUs\s”l"Nh{Ww^hpZ6VN:tu7v1Ulޛ^]gnl䣕[eb֩{"| ]b]h*= 4WY^m-#oT=]~YT)Qv9DȝQT}oNE7_6WV}ط?$o\WjMM&|}BL('$Fosr2%k21E[e>SdQ}?_\S~q6-2k~ׯ/\no۪6ˢVXNo?J>Hv'`nwU [d)^e&J s=ZbBD0v~N\nt1j>wMg |iu`Raeҡ͑ ȣB\6 Ƃi,鏽MjX"?F6`º18v'@}vǣs0  3ZѱwPr{C:08xg_dJBY!ĻYduze CaR'o,@L-뎑_Yu՝^e\Kqԋ1pާU8}~XƖijv ['*`$6(p1Fb< ̄ L,y,/K[Dqeܦ|k^:5Ӕa!]tX.ukbj;v^)IXo~G (G^eHj9!_֜Qv 7O`qxzʰ'sA6)fejpf@`H,:ș! :ڔ)x]՝7k}V u<*Zb!Yv<: #yTv8bI[./ךQ/URx,%ɣMOs{5;uBiN*4:WwIܧU-k\zO=R(%c2v/bG]Ѫ4M18aZ=V#4dC)N~Nw"xyczb]ሿK%Me@&}\'{}nkh )N7IK!usyؼS@#@rɦY{*`H=([674+繅 b|ZHXȞFL#\VtijH5]sNK*١zyiW}PS4%^xB"nM\/n&# HrGx%ʠ;2\/Il"h?u$^99=XDf;? EUi.k51:ucc)-(LxJU!v1]Pn ~Id%a}x[~f&WnFM|zr`Kqxsj]C[G Iw^֤nY֛ʞm,^sWZ6^]$"8%ΐ)be"7U*:ݎy=❁i ze-r-a;C* VQ -1 c(^K`^K- TWAnjo֛ g2W=<+\-vWs9d w"Ȥ->؆PlZN,?e,v9_G;i:>ol7+l(5*!gL,ڛi߿ 탘- !-Ziډv=o>d?reǣXO.=үB:4s' {|%o|Gߒ0ǹC>_$ϯ]̾]+_#oB:HW)0B1p|wTCGuՀ\ru$N%6/ыp\UUӥ{ra|9S uͰNL<$YǹlI憒JW64((;:m<;+:߀v&K33vzwխ.ƓDUk|r]OS8|<u>#@>b[=$U?=<ǎTO\&2Ndq̡7tF!.w6ts[bu7oN!fIyiQbZg߮Xk{:9U,NGW̒[MuHy܆KC6d-`p0s;??PK\J/W>vW +smime/SignedValiddistributionPointTest5.emlUT 0҆?;7AUxWkHF흍o[zgvowlaP$YyJ7ï,'b1,&^ܴuZѱvז7yHyQ 7}?'$1v2'jB 'S&]-M{TޮoVn~:i?o-q_-2a*}Un[ۍruęDq ݾݕ%^4M{. 5 P|B|cK.Z;)s 5he£s45"2!+wie&$ebK`ƣKn<q63QJN}FkpL<+HE\J.sƣSBӠh0 HٰT@0цz> %RX+27)E8,P<B'J;!r%H DBJ؍GsUvL)MG+/o< }`mW\tN\;6/50q.g p?m4nZErɔBǣ\bw$6[ݷIhGM^sHMWWrhoN6H(;ȉH ;t>*ywxtcke-ChSqwN,zes ֣9;≄t,u :u,U9ͫ˞aށP_( ÏG%R<xI)`ϛLY?h7uzyz6S4֎ {[ B=75LyDBuUoY+83*[/Rf((͛[4ONp+tY86D%@aii L2Ma?e}˴{iN/nHD9Z86y*)~ºg~Ż'$ q#]"ϰ}ξHd Nd-N%|D-D>@iʫC1 [N ce;~m+R.0"ۢmlt|gi2"b;MGKYp J]2}0sdE~~\xq-2#ff+bq *zv40{(dpgƞp׊O Op!N0/->CńPDYzq B dd` hxB1 Vx!(K5:_AYV(zO2z"?ufW?c8斾Pⱒ*˜DA! }3!LĂ- dNen~݁j zi2p/ƛ#:ii/1:h5DDQ#@—X8t nQ3 v$ /YUM4V ؿOz~3B}}+cXsxD?)\ΦP~d)mxhN&HDuˠu,٭2 &:OTk# l9 h-1[ lJY9.cv`YO81CG\zd\l]eVMMx3u os)ƣoWVp bH.|{iˁW|qK@ j :s+U!:)S<_5mmTL}?ZU& "0 8g;fW5mYméRˊ;79d3>dB nB̍mfM'%qәjQIfK"Azfd. PƲ,p{u\Tꯩv [T~?c6@x2-HWY/z{ JJqS:*";/@Em.Fv"қѯS R0߮V`.r*JL!hwu;˚WtMiY2y ]7S3}AǿPK\J/( +smime/SignedValiddistributionPointTest7.emlUT 0҆?;7AUxW۲H}"ߝ}g&Z r߸ Szmn ðL\ke&HE_,އz@YiE&06i>퀒}XE_?01o)i4Һ!7ږi -r7P\>T}/zv1@k!C4=2y2M^ŗECB~*C79mX?b:EE~6QgrKŝw:obQZa|UYͫ~L&iFֱZ؆0B$giCy (W#^>a 15RAa4wđL#~T{Z LF0t/3荳{1g羱.3ߝz &9|W{τe]lyLҀO<XJHf*o%h  [G; Jk@Ύ7:HϾI; > g &jC 4A!` (yj} u/oح!W\]8W*p{+'~$wWwW rؒz(ax rRyYtx"PxyƮ;wf(_zfLyM%}'*Ŋ:6:nvz$ErbDzx,[S8Rj'M>I^g7>/ؠȺElJ귷A'k DdG ĝT{>'4P͘X/kBON)ʏ^YaFwA#0}" ǝ!NϺ((bM O N e ݁P_(`CT)_E2{+*EW[xda 8~ܝs^dXK\i x|q'$Й7cc*|<̈́Ho8|}w$6ʙ2YDi="J[-4RiԏZXiN/mlFg#`ۀK}:g{NkHc Z}JI<,vᜟ.WW ̛T`OFB9 <P_@H5D>#RVW8s˛-/+2kAGL@8qc<1JAJ: qӄ;af[2RF+P͔1pGx3/ !uTĽ$^x?Q,0.WCU/1VUs#WO&Ep:Ƴ]Τ`:4r6fQHp/OytB.uK5+$ERINNYX*hde&t>O=\Cƛ mS3< ,jrޕ1]\(_0şp&J5{m vΑo| GcrDU![cS¨U8T/$S)^W|4Ew[6C]+%kn=7sx1 Y.s-Hmik|#:mgI?@2@sGqdSSs?!9"#?<`z5eD\^W+cԈZ<#xՅD !~鯪,x!UڷMKyb(i7z/XdM=l?nʆ '_m& >GCŸZ<ʞeKQHԶ۷J\ W93|,څysŸ;1=`xtX9"u,$&1OWj*7fR,Ѩ^/hcLh%7|}PPK\J/.Tu w5smime/SignedValidDNandRFC822nameConstraintsTest27.emlUT *҆?;7AUxXْH}]%-(jjّolBB :;+#+&d,\nȢ~{T6= [?ڨi&$?U7qx3oĖe?1:=4 7˓Q޼2|9"+"*%esLƋ/"?c17"ݓ~ñ75h #pWCoڽE|1nsy˂fHE64I\Fkzzn^\ 0)7k_&Lܪ&i_I Z>?( p}.PZ fJ;`lޙXJTPRRk-!]CZyMkP*yවZq vc|b5v9-`Zey]"GI1F:+ϖq3 +y<H#gmJӠ} (2]UhFrP)e2x,ʴeƊAegX#1;+W$T/hcikϨG(ȱήU W6cU`1F*;|{W泿TMKZ^8WgX|`.0>}wx2\kJTGR{j?~Ne}B{"m4JpdQ@U^h{͑c4˦*Ji.JyynO>DHn+qAW+jN@}J^cAϤ@-fOFr5dats22B;~^eAfL 'kMOԕg{ɚ̉n=LC18ݛCpk50  zr X@]5;{Ju_|Xf$ڸm(}i o{Xr<``ic=,';2~X7EО{^ lX%(f,ma|@s1A(g''']P`,AlgsYOs:'YOr/^@d ʛ<^6&٠0&)Ckk3<vl"|T͔psi ˨8꟭NBA"E#wO>{H Ţ/ZX}5;v[~hNUAI)Swg5ݿ2j|$:6=Ov28%aQ}F ePMĔ݂cO\/ݢÎ9EcÕM]M*鋈uF1Z 'F?K(Tb$u;OaH-K1?V=x=A4mņaDR7--&szOݵQmvIY~M;zyڕa䧠8)7ޟc+ZvT+6 ;qVvYio~c/vuHK aBmk ƺgJ D5G3J(;X`TWcAkk.$ +r[=YT[:)6Y)z$Bj<% Դ%ַf${#?7 oZ?8tD a{aײ$5o$hH )ƾLc9Sg b2I)c?׉)z:~Y*i>#kD q귺M&8;l@h1p˧Q!PL)i>xlByݯNc[0ƜiLM&QfK;5 PC& v.EMseVG3| 5C .B8>@ 9@w!4O:糊.-<vLJO;?*'yn8~jT=pY$ smqlT/0Ҹhn M4ɗob]&.-8a>,F6*<ʢik?-fd@G¿E4XzFQߘ%x}uMva;b(;KOј"p@$7Q{g@$Iu [OM8zi83ﯟU_4I\ EXFiGL&m_eO99iYReM!w)=t5\Ipq\.t dG*'9oa)BhiAadAa,Q$ӈ[@ 9B"BfxDT03sf63/[˾;b3Kˌ?vwd8)AG1?haCu1 Y fRhHl jhu\}uM!lyG̞SөpJ#p2LbLE_jë_:69s'b֢ 9%Vq?,n%]Jqgl1Qn:̽`MmxwwހS˔X/pGe[. ZWYp%$6&Ҵv](gǖA)0_w?NmJ@–=k]_6bNhۃVNƺB/[8]}$CJo#5IXHkZ:2gvF,`^ 'vǹ6Bs jwD]]\kzKy!gky™fBz:=մO-ѵaw:8 1jcxGmC>'d INIxxD/d+$K %Jz<6&.!]FO.~e#C-ҭ?p]TO%Y, G4 Ȧ4}WT ]WB8Nf>kW+Eb8 wDžz#pySgxzx\Y9_',c1EO^65YL/J%G7axHx|bW)NW' ]8v>mVcӌOx;(efJ@ӥLÞW.g桎 Sx4s\sڜ9W{iQl-3/<܍k򶭏@.e3N8gGxk7\Z [^Z|ԴD߿PK\J/ ^ ,smime/SignedValidDNnameConstraintsTest11.emlUT $҆?;7AUxWkHF{v6x[o3wNauNjP&mUیNm&QVgIO>J>;gQt"m%ebNyo37,x&2&BUv}fel5B|ķٿH"_oZO Ͽ}mEQ?[$=7zcٜįt8oa]piD}:5&?Ϻןo=PNaٝTFUmv d|wca^9+q_oiۣoUHF$Tf \*(@ӊ J.T(E}*TC`W(V\&IS!QHт"9F-K25|N'}/֗[ E҅¬#DoOߣ)EyM`p= ({ L{}K2oʥPħPp]8*9y ዮap^X"UUqUL4I!EDcJ'ۀj`oµY x?m+uLJEqO)zsÀk<. t£K^2e=nq!SF,) zlP֮@!Nmgcg;N+nX^x-2zrЮؒ =B~Da)#TzGE\o0d-<&* =$6IUlGq h@|&_|~G>n?dD%F^hmPH4袴AOm^6-;+u~x18n j!<|]'}M'ng#f}1H \q0`H9L )YNΪtu8E?U9lh1g+hZ 'lu>D}j/W"/ًXf:t-U鄕YZ>ʥJlwjCI3(yڭ ھufw;褐<J> $KXxO̲ٓn(`IVuåz,)-TIq2yR fIËY gz$+Tμ !oj)Lkl~D1:;<>C |UeR3z'>kP l 1tYh涊iZG\q,&tL{ <2E͓Q&ӉgVqŜ,;?eJ{V n6s8(^znw2$v6 #Qx~3%$/mn4HO$̚=uM ĵR]F0Uo,nMo{Ჾ:ޥ󞬿|q AݡւF ۇK96*{9:oH5u+Gsg7(%'Z2.Lz ^']zj3msmk*Eh_> PK\J/tQxI ,,smime/SignedValidDNnameConstraintsTest14.emlUT &҆?;7AUxXiHz!V P==g"ٗo&, 3s2kf #g$!ݚ,ӉQ~}EAZQ6nm%) +__,?OCV.kĔEh WR~ʢ_ޭy`:AQIEbX$˂Z !%h_|!ɯK|e:0_ʟ#ϫKl\kK|95iRDo_{F׿T0-/'6?iSMھo[?8_/qG}$)z' Ԁ)22  P1&2&Oa)".0eSBm-1_R,R?$#Hf>m6rRJDZ IQ[=QT]ov~&A1^-!؉a{ci-K3.J=#΁5Z׭ U\Hhup&65Z^2h\뢻0֛=Kү eۋnoB_oM (ٖg,Kyb7^'^a +GF0 c1RGA$~BrA/ltlY`)ܰc} (jMs6ԧOqՉK}v7lufƀ9R^{d/J!g.`|0S[h"lCPѠp0p/ %P#ogɆDB i:5uƼƺpcx 䮩k8t. <\X'8G:q\x:"^u1I˯1,›ynXIdtE8oh.ZxÞڗOx֛}e)>sB8 a / `6?z%{Ԟ׌7lYºAgbDnZ\sQ%W2ԭ1(r V&37URɽUt"KƽC6FꃐPQ9Doߕ@UʋD2ߑ[Z.)4ܫ5xfZgS` ϧ~{{2OPK\J/v x,smime/SignedValidDNnameConstraintsTest18.emlUT (҆?;7AUxXגȶ}Ds{՜9qR $!7y2_}gzT*nOfviU_BVmu(]/q\.ض*V]Xa-B[n+ZZnRU}r!]'~[ Q-{ٷۦB+ A[-zO5u~TE{}ߺ4.S* 5aXR19 i#%\0 +S{,j+6m* ͌+㯨Gpc!f$]" du}h3҅kk"Ǐ ?l.'5`, )Kv<-"mGFalޔ/WR:ɾl,³Q2M $27=BrLf0}bCH+Q-rSL$qш HU mHA2]!ɽ7YH$?PNrA9|n6,(t:_gizvk5[FqKDLi\0V\p`VU$#x`+`PH>FU(0rW&Iain[5D.dO Jc*AI WMO`"88 9OB{J܏9Y75"~? a{KOR54uerц }hdqxTY#fL52E:~_TӮa yU}+`nCc[7+*JChĺ? TEp!aGܔOJq ](MgNl-@/ Cfbs2ƆܸO>ha^&r|mr~%;0?a |FbeTvV9QCG$Eű;w!9T ^jdgPp>`]m6yX\8D4׈H6QtzS;_7l7@Du1f95Nx袀D+]mX 5: p(!YvoGSBlC/ d_ ~<5~;Ӱ#L;ӵ!).LP7|#wd^S8r N61_^&bنx m*\V$J|WrEI? ؓ-``~Y.7Ĥc:Ió O"[Au&̠;/b |>s GB%b=ѹeȟɒ?CAgl4tE^l@Ԅ"͡ޣf]%3vÏ&|.,Y.vX!ʟڤHkLزjZt /+h皨li8EN#<~Y.~g*=cuKhVjD?_,H!r(pkR篪<48LV[q==Y.(\i;]xe}/l'wj)ދ#2*jŰힱ6^lv'|pǞa7q;teSlzJ5zެٳprmT!iuP`t :eGG1?'?̲\p2ezDsPWoq; < !MlO}pa"Qd2،b7z7col]-~(Ln\qK(|0[uM!Fx<'!r&ˆ@mms<CA.ޚ E" s*,ǯ_PK\J/u2Q [+smime/SignedValidDNnameConstraintsTest4.emlUT "҆?;7AUxWYӢH}#;U~==1,* ")h~R誊0 {= b&ʏ crìW7m,B|VHWDŽWKlڻmcs~\~EHO/21 ʬs MǜL)G$xKnk߯묾K/%{~m/G{%&/$AeXEY~L߶YSWM־ 뷭 $Ǹ";>uʓPzU % tq&`jT S~XI -;(<(֖rU<68:4˜aO!n5>#ẑuxvl( nS^\nTII_/סɯXiePWYUc=}39W[ sy <+*Bpt0Um*s5hE(m/v-#:^GB[ ETU>\ߜLHǤ^*pTp ߚB]' y\ٓc، :AXmgz3.EMO62`S(YEfuSҧ ʹʉLUwww?eKVJ/4rM[TEM;Srҡ9 C?-D4\i2)ln'>fKwiM!eô]SC{ep4U I~`%{OomN3aOr*[U[@y}𿝧I/›7L߈=.vNQUIX[RZ<1!,u-sBwZ - *4SovN"NآZqY,%`tkH82#il?{/=Vt=Nfrw29~腞`ӝ_Go-ȜI - ^#c`٣p G9 'wyx[՝Ьm? ͮ8M_ aKR@aAh%2n65pjznc) B-ʛl>eq2koZt&0tg\n/n\EspMyhUFm]!/K>P-}׻/ŧ d+u+ ;:Ȩ|BSBoȨ^^^Do=+lzs9 eDˣ R2NbEbSm|L'Nfl|ws-2?`eg)(Lja|%ň|<ͽ̼2WO'XQ Qf" m(_frzax4X iӄd>+ckWF6c*G?~n>L. W_aI+K!Ӊ_[Cig{4 }ɿ3Y\)mC <@-Թz#+%'b`l9TBU`"O(x P8'FGݡ=LiK8_pje$]u2+!u&(o$7ag֦ragv ǎKKkJ5c2=71!)|ԚC [t(i:)*hXBE^NjZ,TA >"@($\4 "JxFf/ͷ^;iOP8?X,otz$b֣B1",(0 b ?@Q z{[tD`=ulYJwn'^B"'"5WEf Hu:T/ف3Z:Yg33@ѳR !f#uG-&A,QX3V]ݙuUcܼsSzM^? *X^Xq}z֒;Aa"~OUJ:*HHW UVf7䋻q:xzL2,˯ON$]T[(0*^(@O)US0@˸A2g\އȪGSmcE 7}F < DN;L8UzE 42ݪ-w=F=JsG~"Z-ns~]jmlFxFA!b7:C隲NfO޲R2O斑eGZy™W*G1y tУZMwy]H%^#6}=fWzK=RMcOҮkR?7\\_3e"䄰j"R2ԥg*Jw*%,b(ԅR䏷: tϝ%YE @KB6S8d1ߚ׸,};MK+hI;,*ŹE ,/t"%H% .JnLJyTvLG|.&/ǣCJ*%Ma5]#eؕ|VyƐ6W搐[vG5xbV)U6HW 2|{j- GbC*U]篞,>0jS?!-޿oBE;)3?LH 0_ԵZd6G֗xX ^ [U}N=1[ݎ/x'^kL.=ŝt'q?t~Rn֊`W:(][/q$!?y:QeYXQ8_/ O욪жeٌ 1&&GMPP *he8,T$؏^L@"Ϟ~9@|d=P-|+6\fIThWr<dDy{WNݛs*ja[VA;n HAGmHTLHSxÁ[yY g|tlq F]}ئB6h,._v\i8 )})wBB[(ܟ9۟M#B_{ }Қ#c=\nDx BuDgl/qjktN_bsval#}awwGdqh硻󄱳l\z|J[ M46 p<"+0I>~dH 4#-H2~}PK\J/^*^ +smime/SignedValidDNnameConstraintsTest6.emlUT "҆?;7AUxWٲF}"ޙn^'\QHzӾ@Oqqv;FAI*3O)$!ݛfWb:1= kU/mԴAto8 }]Hڕg5`j| K\@yg9=EWZWjkEu 2dv/W?oJӠR%mlBug+S+= y5N'ni z8W1S Shgvt8:gLҺHYI2 %]HZ LzeױdPs. M, 9p`XtY&*e PYIq#Ҷ:,׻WRG@*[@6k?u1t}Lu'\wo=[֌'*QAZMo]_)cYi8YA]ݲ[+$= IB!0M%fU X `2LTY^8jL!ܬת nD"-ub( *F:5==PFj1no#!ŤHw,fݫCx¹63 @_Rlp }59JTw W7 ^J.A-@ppFeYo֣:hr$MZ;fSzӏSUƁz t*bcَƺ؁wLV]6BhyTY߹^Q8*Nj'b~>ᤎfA< . N?0sj4 Y p:޼/Z8Bp|z:FG?69S9IN>X 8G:)A|@χx>xy{x6k.kԞWeAek+g F#!i[ә?6&(f|RB\tīzļ|)~8y@vN;@_~ȱY[˧kZ{{8J#-Q>+>' + #$;;u}[Tmyw;Yu{X@\~h T;ӎh}qlOuj6?.ϼD;^H}w?僅 zGo=B'=a7a>ȸ k(>?!F$ A~`<|!,/}<`p&5xc+jyO"Nn΁ \^?*y|yi3xxd[>Yi+<7T5Z-~IӤ5*nV 0+MF,S&Z(X-6]Ë}Ǖs ZbEhaQ<3npN.Fqs=9\O&((X<=U_SOGb&ya(Kո>R͑)K~1x)cN bs:YRFi7Y"ldU'qid>I ?PK\J/zj -smime/SignedValidDNSnameConstraintsTest30.emlUT ,҆?;7AUxW۲X}#T "^NOMQPn@ _[OLuUuaI\Vpix,gM$Uݯ]vAt% |3* ߔ0jĸ(g%UYSmIѵ3H'*Q($I<Iņ &$f-;E/_{pԟGʞ!5hן$~ϯO&OL'xFusοE{O\aRo&lVetB]q],H+=)*g501@"DV"R"{X X*.гsuYP!_8 5 Y "`UyAC{[=N'^n?}s۫!g*Rpt?B"+ι}2 (5 pFz$ Lbm65k,WUXal[69pkH[؏PrQcV.kkG?XAa!9W3%b R?8SN &pl[#+bbEw;Ʉxq'{'eX}DώrkIșTHE`Hg84 N'e` Ҙ8aNHH>K{<^<U|ZHuh? :Y.ƔvN AϦVa @|`졗h¾jbBghcob?#ZI)+'Stz|\vIv]b,= fڎ<}%Zvxo;}YӉetWR>fF_HXE'CZ 1tӻVAh}nu1}R$nb&>]۞xv'ؿt3ko #T3x(|OỳZ;*tvW:3Tsƞ r>JЫZf{3bnpæX{eb,^l.kin;4G8pc+:ybfnnlhkENj@.]6QZ 45͑_Dߞo6{seRD`Enү>#\}y"jIqfZ+R`3LpyP8k\]r<,>=})K@> x*|qǝa,Z眢H_' {{ҝ,׬de1lT2FU:\. δrpU)"T(k\ffd<µM9ɯx~>H#O.,Y p=p7}~hj20޼0~HWrqX ΍[LES5q:^y[\N Sð(!^a8f0V,2;mVu_2d ,"h+bcWծ` J;Ƒ7PK\J/.dt -smime/SignedValidDNSnameConstraintsTest32.emlUT ,҆?;7AUxW۲H}#ߝ"鉩r޸Y((O鞞9}zwwa$if\+ "^ۼ>&Ȯ?&4Λ<uiˏy?>I1i*IಿEEw7,d"ISUNlr#CG(mTcS73g)'z@~Lkɜq7)c1L)G$zGf?6MJ6kNqvϓ#>9[v^S:V1~N LMym޽v]ggbyrǸ7R m=ց5]Øm@\x!񇵂I*\Ɖ.#Yj>eq0obz{!,x,a< SsܛOsc+#.)u{s/鲊IeY@;7RDr#Kc5@2N Ո4Ao IsG]=.=Eؤg"3R,{_pM8q atQ{%uD"ۜڏGjPCf;,A΋ϐBpP4>-P~flfs_e^RvCG(_1)B`:,d}<ss )U[m+yU|yY:ʎ8]P4N`d+-$Dq<\ߟ+$xz7>)gt<{ӡ4yo5A}(`GӼpp[bq1K5IL\ Kׯ%jo@u휧aU,H0\ק2 [5=j-cxVr;;>+45Y>TzMEaA/a`@>{zSBąD ubDx ϼD,g#N4G!APL(g[lg²Q==<)v`0%uAU #(Q%n! &.)zM??`8 `̇anO$RKqǓ|;. :U:V֠D{E&8JUzӀZWÏ}%@ :}0Eaֲ<.}7ң ݭeվY[KpjkK)MGۄ:B9Xybxt=O=vŐ]K{3YjJg_Ta ,IPwЀ/w7xk"!N o( 䓯 Q&Bc.OniM9fqyNwAz{sv`#4Xs7,dR/DQ@3kU/td޾g1p04-nc0OJ&İP7E٠qڙAݭ}u9VYWϹ={)p 6']lJ.ݫEl ݞ- 9=̩cO1˹[| ۧ̽j_//;f$} |ɕ=_Hn P4w{1u j l,YUP0o/Oʧ~D 8F5md{Q=/4?'/+^L#r٣FPh#zz8i4&ܥ*Gr¹݋gJi #Cvԣ%mU҄V,*_5'Q@*D}P(ih M_qðF`)AɆ_m$?'Z JFVM6 lŇS߫T<.;U*g-B{J=#P>=#]pTXZ!^U~1ٽoJdRxRxT^nثH7; X/:qe6FnGGÀ֤zk"pMw9vcK MCdBaWq]љa5!c%eY J\–_5P LZԦȀv3vwc@]9,ߟlY2 ,K;:9-5xUM$_Bs< <1ٓyz_Y3ؤDp0YC X2݃YTF@!6S;2;abJ؝PQOʫ .gVȾ+!-Tz?4bӇUx`r9]Q$6?4#>EmsZ˫Y\O<*V7p\p^/|>[PK\J/6): 7smime/SignedValidGeneralizedTimeCRLnextUpdateTest13.emlUT ц?;7AUxWYH~#3\oLt&xم7@6A@@A~}陪Ꙋv p8<|K$QfU>PӉYϚ(,*_¨8 }KRݧ.6*OQ')-8Ga>";ͤmNfvfY 33q NPԶ~)KS'K/( ftdv3M~̦*;7Q|gwxd킻e>?:6KNV{R._kM(ꔕ,h9o ufk~az_fqVD}>l*OI p,69;Є3 Ig&JFBhxAAu\Y%'ɞMHbe4,uȬxfAy΂ut]޲o.}gQ2J (y]C)bD!czd?r>I[^jjxa@.`8FՆ2q}-q)^tz5\apQUz9 U@FO'3j~uDZsګ$["ݖ^y︥|ǫ]F4h-2eTŢ3ql>R?G{K"Ӊhɿ;MXzn] 8R `WUė h 晴)D eo(/UMg/Iͱ=W{ɳCfʭ7Ωda x^ѧܪr=Ł^W$ɣ3fLzng(ɱt^^]A`xggw#"8@cB`O W5/6@xp@ '@,q^GO')sYn\4pɆㅹtBz$n}tHݑ5?T[ [^b·3r;elגw Qů{Űp=J\=cǺNbp=[ɊjTL9b~B{ (wHDFҏ~ƍ?#obp0J5+YQ;WpGB F/ϠS5}e3y\vA]Iw%pˏioHtѽQvpq< j"7Z \fP/p?`#`'0;? 6NHemM*<>킜#}KFxš+"XW2̅ZA![ү8jGO ƛ'rS"x2S{) x%&?NUj]VX/:%7^A6vn3VbsgQq{ƚ=#߉q?:F"X/S8]e\XuǴ_]p*/lUM%w:eYR*^űgQo6E?(rY) 2, 3ȭ)A>+t#gNw9oS{M{9}\J q;6wFPK\J/ P> z5smime/SignedValidGeneralizedTimenotAfterDateTest8.emlUT ц?;7AUxWזH}^xgLy$$dH Y ߄i3kRA")';7iUtbVo{uomܴa|oKϨzL'*fM\F'&4 q_ciʪ6X]l%nş$m&&Wҿs:yZ{I̴QAHƯlNl:a2u?cI.,l6 /66)*S/Jg۟M񕿻_6+*JK6 &^/m¦M]5i߶~%o>$!p}I#T2>sMal:3&!,R@g{X Z*{PyP-gV(e@ JT%ڶHD^" K{BZ$T|Geb:Jt}ۆd(X6UKa[qQHlY; 'pa{d#Y5"q~o!l9B^t(]б >:.:W#.pZK+C{߅I3I9Ac p%;.#s`+%廢*7qK1W!qeh:Y]Epnx: w[Ng$FRǢv߮Z 5zqfoF/B=] B`N7$4˜tMۦbT^s=o=ѫai^_3f XpzE4øM*k k؞\^|?ao/u bÂos{QbGGxg Ox'xz3[e`9dDb5BnfɁSmS>|i;R눤8c$aBfl_V% plvs(e7C})nyhw5Fmǚtv1,,=o ;SھW-t=+wkӆX h{8Pޏ[Lg)d7[(&93ؓ+=ێq8ck#KF;=WJY[Jox/X˜nN7=uh|^fwM%? ^dLj%?~ *xH@p53 o55 /j$x<Ѱb xũre^]X-sS֛x=% SuV7ɮor;vUWas, tX)3d(Sfgb:-&O.m8u)C3ӉpˏYVIzӸa'31~5鬪;[:wf6NԴmC~ٿ$^w\gt 3q7ٜtUd?l6M gh.qT ~Ow*M>%a4 K|s)V)}⫸N }̢Mo&\6uw]Y"]e%6|eWr5`l3˲?6 rnRYBGYDѹRv]&춏D-,+H8)9D1pFEԊwͧ$(q>ުs@eApFYG.߂WSEE",;GNDz$z$*L~]=] WELe]W3!\j{:]7AD,2N>G?8q aTjuD˽Ś?8~r?xSS 6&:#b3tŷw.8*DO XEQx_UmH$±|C1|Z`aϖNZ ;3o{ҁp4h}?zbIQvYM[U  tG\6{WhҭQק/w׋~ZW =Ed OQ4SO|Z̫> C d)Xu6Kky{J xr-z 'lQ2aRO` 81<|3& =we1 TxTl=wp(m|ȯ|\g8T2TxsoԲq`12]Q/iҾa%Z?cI#VhLdu'{TOuv߈&3+dsD.`TOq0vPGc">;ijY"k]EKh1\;#PҷAڪY"x3|bFȼVĕeqXi#o`=TɤްT9| k˳P9pAyB'>#ϕv^:5/  UĥІǦ<E0Jhy{p8yN^os_.'AH;[/)Nv< w$Jµ[.K0_KeSuM\4q|Xפ? |\+?ùWj(-PtrR fKu=eh'.ISK&,L~nˣʡ(;ԓ z~1V*ptMm\2TPl׺\i1Z8kmB6?%7ݕE憖ȹԨ:۫72QOi+n~>e[ .kıOZnFY*7ֵ/gg[&gfjga~jXkX+ߪO>P = վ XgY5v-X(xcknԉ8+5pqױYf=g/t]vI<.ǥ=x6<WɎԪU#{eηt5,Cm5+ ,?\!5ǢjwX:l!f:d\#m _<1elM-c ?Ɩe 7~›"QNj68n޽mM*1ZW0X؈;"o\6Qg82f|_yfԑM0{zIpY}zF1%\)V"49Jo\SkpXUFh,ެu?S4*,"ED>p=t@%4@\"kdU+yl{,D,LMc(~>"ghp{ˆ^KC +蘤TtrxY_[9X@gIyS .wttr:A-t8ҢÑTt8&JH`)TCk۱1}؀=2dza}ޓ3@0ٝS4< }/bJ6w&% F#%3Og;eyǏ1}tj3ENXjb@S ؚF(UlCA!eM]zڨ;!`͍,ut"KALM¼S91,]Oky[#>hX7 A6z!+4!X"orR}y ; Wߢ~ܧ36LӍ8 gR[-Gt%K+l >l)r?\Bxpx̥uQ3^iG\[hcWژ$yrȏ켱Va Z7X=ebdSb$~:)ylK"/rS=Z;U$-H[ӀDk0#EzI}lTD@in)Ͻkc{z N@*ߢO*}ldR :2>d (jj:I[yQ dv=6q=ѡ# ǃ=lsc8^@.>3x\T͓A\^#!ŜZܷxt%=*Lj mD=<] HŢb(r-fxVF:ԣ.#K4P~Z ղP9=\_2e(Yr$rSbQɪwcZO5e^ 0\u~yZu)랼NRULNWa\:3nXa+C=] *wPyP#dUYpgf k{DYM1X5vr)lRtr*ao;wfKZ H1VT&7*Ϗgң)vyN& xjr";Nha@i8 ((2CCO,W@&DaG+XuhPY ȿ3]5AюaCz# MZ$Trb:Jp:qUJBFy8(; $/(c{=Gh,pwX,OB>\qY8V,.GqvKTB~FF_Qb/cbPXZ8V=^dܸ=(9,'54uuQUv%M'ݛu }6n/nIWS:/0I)v77sؑK"q9C&O'P92I,.f,W7XA񩄁]i:|91{O*c. 3 hxay~'r:4,wqS3 9zu@̷hcP` F0?-A}? l~R~@Woz)x-;Z6* m2ƫKJx+f 42uㄥ-OD lE*:w]ЈjeץB/x(eQlzηg4o]H=7傥#"s6~N0emF̩&*jVG}l:@eJٓ8{RYNŸ@39IhT#yҨ-zG#Wr5&d~xy&t2¾T0-ˇ2yx5|XrtySvN㾱Q/K| Gl[goeìڮpGwBד\ЎSJ|.k.{V6mRފnaa?l!@6-#d}2 ZN!@8!M'u48Iv4CIn~d3"T:gÕTPR:=256jGLf"Rk[7;pjǵK!=) QRuJNJtd2GV CNMwCK%N6Al++S&R@:GӺ NZyK1*(;KNM'y *)s@?ʹGc^Abeڤr}HP?+PPQ'gP4RpwfyiqN]ء7\AΣ)j~ ipp j4&ۥWSI)**=m*!s‹[{mk[ʽos|KN'D{}k7ޡT'6Hꩾ;G?z.YT?wKTo=ז-6mh5!]߯T|dm5嬭ðqcU=l֝Vsk\TϘvD$n2ez~,*db{#a{Q(n ΩR 0/t\ %rHXh< ~PK\J/%ԭ T-smime/SignedValidIDPwithindirectCRLTest24.emlUT 6҆?;7AUxi⸖?3XL܉+ +o0+^0Aު鮮鎹IddiI/5G_dc_$CC-Ie ̶u3iA;IQC},ٜ_+/5TxWUkMxsDKѯKI" ^:Gxj&^%EPI|V'MU6I>Im_g$ YFF*,_ +:r#“ccĉ7wa)!!U|~ad~gCYܦmߚإנPf[)$^>$%w=.;v:ޤqYh `<#yT(_߮ GHq@g;,RY3mwx?tB8vRTd8zݍ:u^#xE㠧x.UҚNX!;Wv/.8FCB?WK{?Qya,RGNQ& أ!]\s>Zdt֝l8UR$ *D0N47= _@7|r+dF3qvsf(pOi9GaǮk|l N|yAyaB{,cQ֛<>]jm x;{atVvv &a~ɒͬo&8CL'PUy&6,H*{ Asz I*b?hw!_3*q$=[[­&V|8 |/@uޒ & "s kBD@`YYuwU%fup܆ j>"Bʔs/B*^ȌSSd{lqas6?/\^4w*KzOM?*7܁F+*]@.QDDh{MfY5;JѦIf;#Eta8 _i76|e/v9aW襾iKpГB9{[*Hkͣ $}sh^Za:T!" 65Tź* Ւ:Zq:ԭrR"Xwg0aVXQ ?&l=a.\_ T~nTABA5m9ٟP_^i`R/f,dA;,~O&YP9n{5c]،LpȀꨂk-{G&9uRtvJn,X%X.hz0O}/yDͥ$DW!9_5i"勘F P4 o21cO/BKbhz!P=toO7]`=W_u{Yr{j\~VV܆7]OtV`fUy\mI)r]4euBXV tg3XI%9}a=S{É;g)5_j\#yж|dDV^Ln^/M˳D;5ĠdAU?YbB:74ׁq22킕X2^ωN'zꉷ):YZ%ޣA-=# J*o3==YA/wBt1ޏE^y6Gâ)Z ?z#Pn'yƷ37ޭcK"h>׫91$F:EGl>utJ5=`=`/;rq*d4TKQѠp~hBSIvn=x%2f `ij:l2Z݃4][=Q aQ;C_ 0,_׽y'Y2|X ropDžxg_B?t >&)',tg`_0H߼}ۛrĝg.8p;i/6ܯnH҃$\<'fG0ShJm^x^=ƒs;,\܊nM?{ќƕ/<7ն~h.yusGu? OWW#W}(u^q~'9FýZsP! s\2FsAq-F1DxQ\cÜŹ3GUMFdעx̩q.:HvW_kdPcn.K򎏰/ZO'p' FTkPK\J/Vȟ T-smime/SignedValidIDPwithindirectCRLTest25.emlUT 6҆?;7AUxisH?3Z}djh_@|ӆhIObkVSTyU.m8w)C/Y{]-ڴJLqh)/o}}4E,PQ9?bX1W1}88` O2̼;it`~7ֲ&Ğ;"ΗY"t±C$Mti# VG ?Wη`c;Ue Z Z8{bҿ*QĔ~>^3q,"S8[o6A,^i*Y|_{JL!LmY?&RQ{4!} 1<򧄃0*:A>Ǻ輰\'eQ 58}5ITߛPf9nyحdb).?&l>d\Yx}m'!<U/|FTW£}T;lnyr#w03C I_ AΧpI`` ^\ զvX0, 6ƞS1d`![^;:5/6}2;4ebn ޯP>C?ap4D7N޸@Q!(뼼eRu!HX2shL0"{ ,l;i3o2$R[K'(Co2LA9|. aʥ|v]TZen\DX9SկY ~O|9a('alv%to/ e28ً2'exzd%?Lغs+\6^-NoE9v{ŘrFɮ4eVE\C|uVr|<"Ptq=txTCpVz+bQ^g5#ɦi:PLJ,_=O{|sSNj+XQ}7crZAsק{v![tn&iBy hv-j*mh'D(cxu@>W|?~ʹ8O~;\#cs^r]L3p>㯾hZm`d/ӧުN'bIt^Z-=ikĆ6r*h۠럛e1V1$1l7+Nb;e Srcim] HHe?zѯ__Ͼv,*:ȑke|P<~T:~( ?Vi w UKt*H s/Я?&&$ E$o1V/ bij4GQ_"6?&#焦&{0Nh?dJx$yM3֓#HMA%h0^s"Soo%ĝ n2-ƪ`j+_ fCPhľu9wMڦj 'mV'RD-(YzuO^T#3crl@ _9G(GΧ 9e$߶Uķ{|KUC+3%Ԧ| !h_H=f.#'Ws VFj_EȶbtRjsV}CazBWtEUZ[NDEsAj1P^lhZ{y9zYlSRO-XBրQhD<ԛ;BVn Yw}*/aZ%,%XZ!tEipCwL9ysoZRd*P#YQDhDG %+PhprVc!f<7ooB]b`r-|t-i0_k}UMIN&ɀY$ óN Y KI%J s#'ﯲ?I}29wmlosDZݝCejeQlTb<{r@WJp!=)G6ҡ}3OK+'osYyf+mfbxN읋Vff?g&ņHP:$ o.LX?. &kZTEn}7VM!CX N'd{S4T 2;zPWEmh0e2P:ikw׼`x~9xkK@G?,.Fd>$ 9fF:|KAB* B` Ux {&߾SvvI1wDcX4d ص>W6l*x'j,[[Z֛[s.囥qbe+6¤K{n)fiիs ɟan6-/T[0כ2a::~6ˉe,&ϻďӻԘmg$tkqDzGe̥5ƣw.};# |=y_(HKnD:.=tYy5-l+'%3=f${縢$uut;}u=:ks.9d"X-ky#!|J_!K{dsWp%{:LUYg~PK\J/;q y.smime/SignedValidinhibitPolicyMappingTest2.emlUT ҆?;7AUxXk?wsGDdx[ SڹɝLEu>{sʐ$.ko_j>](k']%>;eQ/~Am:.MK8|gy $?9AoYfa20h۬FoN`uJ>緿,k,&\-7-HX-+mFmGɺx?~K mQG*{=2T'8_Aמw \>u8oa%[k._ > vs(* )DzdO&?O7pקF"Xcm-W"%u1x@fu,0BN5'T 5 wР~u=wl}n;#&G\HM*q528E&nyqWIE tBA+T>\6ǽ;3]G*f*5 .ETu'0eiNy^ x[9M,1ᅜ%T.̜Azso8p|b(9A0lŊXȀP [=| t딫5FMQnR+g.= eLwz"Ɂ 5*[)9RT6/=M00j^W`tN$a` 1M-("r R&4I~ |2qWaa9 p#KȚgє% `d@ygұ "xUW=ʼZFU{GN@IYx@U*/aHxx GdA:Hm9CKwyTKc*+kv}.$vQH:Rѭ)0'`Cr=n\\K)Z KlI 4>4(f,3}$?pf: tH!tڈu:`>,Fټx [$SwM+rD} b FaCܑs l yDxT~%$}À'ޠ1j8qP1wX¹2Nw.`0߹rdž[Uqc+kL 9LQvwdzHvřV0N׍ZDZdMC̏E-pVwi8/WTdUmkD&l3t8,(I>QP1DGP\GxxR7WX>~`,Y@k5PVչ}4 zM`./9q:Q,ZA Yp4[oYޑ=4[,?HiBT_CK_ypjX>F9IMe\X.6O_CQ 9ois_.خ>I'OHyYñ)mė % M> B 6rAu?]/EA3#/+~,TSO֣]gIpoOU^%8y<$n9%a}$Y'D?rViI 2tdɼ2wgeޯ9־PѦ)q#* hIozgJS\*v A;U:ɜm(` vR2e*hDUz9q/?F0 UW@ɋ8Z˹ >EЍEl2j0?;?s矤⿯-L<~6 \:ͮBP'w>6S\-|s-V>C0ĺН#Q$Sؚ~:"53m3!N|b$[Cti=κH^4i\p VWjH;<D:|qh^U^B ;u|v@շ{x=>WVݓo_uh^r?q:!Vd?`rN :) }{˗=a}F$G_] ͪΒ0z=QJus̏噊Ph"I"4x4lf?W+FM<.wvaeR0x&nfkIII$S5Dkm\qp}"b[R$W 3~(*L;ޟ(BE9s슿;P?GX# +, jjt&]U.5MUsRl艱ACN$6ms5w+y\e]S( Q;x.2lV+ è݌y{X{;\6]p:5[u<&Ir,ԆS 7E ǵ$~P-B]ޱ̿gr,1O4aoP /9O_uV3*&T>ɇ^6(L1W={l6$#;)#}kN%.[s?BCjuvvƾN$Aco]_X:d"jew<#aTp(gbcO-_/rb]&1 8:}?P( 0.GC}i;i([.T!w]:m n 5޲YӔoy' 1kg+*p_OǺ7R + ql$C${j"sMgd`MUr'Fˀ*jkboYLz4O*XdYZ,\k~wv>$S Ɇz>|9oII#bHSˣILgy7`J^pjFTHco;|͹WM~9D;s{5 8 $4ܲ+^SCě(aCrR:6Zk¥mUiu^x)͢}H7nQNn-ufY֚@ $[ #V<0RB|`)8~g~uGCў,P6v$ % 9 ur1ĝ*ΧY;[bYե, 5g w@ppTV}E2 h%9R#tXmҥ{&@_w@qH bm3pax:_5~b{`o[=߻9RKI |E25R~sda1Ɨ:" T8q͌%eBZ8*71Z漲E}rƃ^ ϸGx*h!{Z ZLI3~Rz)keCŔ*|6fgpsUlv XE\;@?I[44ƣY%i铴{PӞT:}gj?{J/fLx n0A!k6%s5W:sr(U&MY!bԫEs8IcF~&(lM6$Q?|Fc:U1kbuaG &Ae|teP`M{P6I(꜔cMZ߅Oj]ǠmZ`/K}]\N9 “ sI)V&DfFy+tcP0mO]Qg#jyD-5R qb皃1tr*a縝OY1>_oT:Up[p="*/#Z(Ӊ3e#$gpf8;SoDh2 SJBPӉ8 R^~َBcO'*AzJ/_#]hAO'jkRjFs;$BA^wLWzGOGSS"FtԞr /ly>"B^k"0dy@ް9X@(]Db{ 3hO^۔Qn<$2j2GщvL)ZڶvAljm 2B'm:YKTr\vdXʻKх%gsPUR8ZSZn\\m:3hywxz?z:H"\XAƁ^ 7\#&BzΜ/Cr^[0<ŠC a#պQ%';/4|u\z_uNd %$ CBY yӃWuywpN22ؗ?9z-Yk&"Ƹx򩚄n,zQ8b[GD8 ݒMN=.sf}ჼ$^wsatn%/q}W*I1i(#M7 M/s r=v1S4@Hu,%4!{r#PLoܵ5%a+s8A Nn;75+G)?s/ٲXF,#hsy*`.}J)fdȼ8.1YSdg/?ks5\io&<& $v{l@hvyR [[5N~RizwMTq8;<9wuEVo1ͪm V]`5OȻӜ%4Ѫ{Ww̡7vDNfM<3EM/#ߊxwE΁\i|;ki20I=sisk^rpKۚ]ċjr8,^.';/;XU /Chf|zWSefO뙹eUϞ ~Z_uj.~]Q=R9`,&oi_NWW]6UЙ3R4ZP  /D Wi`mof_i!:4dMIctr;X>7qA%ڋWmȔ/#YuA~tX@|=m`Fgޥx M;>I~;__9=v2`!,CqBC`C~騏SHFeҫ~xYTf߇tm?c6ȭLZRi_fgw| Yzlɺ R,S%5d_%6u{ֈV=PK\J/S8 +smime/SignedValidLongSerialNumberTest17.emlUT ц?;7AUxYӢHN n|==1b ~R&Z4 cy3A2?9͛cF}&8iK.No]~5D5ǬM$żGEw3',dolf<,g꽊¿6 J6O21IS뢩I~^l{:p؏p9șwI3IM'lSwxџKZNvʫYza_Bt4|z*cKl(@!V,Xoa#!>U\6ʨ;G*jDt (\jp%^l;($NpbE;wWtTso;wCwUk9$9QhBeow)/v/:,ReL`aq>t"@Y&pf8;Co^=gP6Ou4a:4t;gy&bYzَȰ{9G1kgLXJm"ZS"+d:t⾬ַV;=|sbOpwt.vd!`t R/E`35tVWT8n tE' hN2f> ՑRzEk۳tn0,YET:\w,ۯu tG܄cTԨƽ񑡆Zks(#qrq-y7Žcptw7UA(& ,yBu^1¬`':[N'H)>/[<< tOWR/㒵+N$\Cy{}:LEbE羬D@`w]]tN:)-k9bҒ1GBҏV;*g%>8^ i5/͌FҼs2\uf:dK&#.}:AYSc!rS=qrSoiL'ݶ[r"k9 2GLeI&HK2CݗXpV{yC EּXeuB?v_ط@XhzyPAO%e^-ڸUYrS7# c=xB Sr>j_Bga/N4'U+~"6{f/\~ VܫWUx\.S"z, PK\*<93l(vi$U1)Hp,u ;fRGWFj?9Φ}5: SCz:Z0b'g[&2 zuVBߑt/׹>5#smPC-A~Q4yFq"LaMUS sl#(IyA([b6ɒ҇97#+H;̈́*By =# :*gӨXuފX C=-BywMT8{<9wT˂)rݞf.5OȻӬɷ:۽nCw%un).wN8{5#J0gCkۖZT4錧~u좤,vNKز 9ic}ԦD*ĊP11X*$u#sDtHK,lk`gK?<ַj6^_lpP^9IUN "myy$- IJZi_J9W)=g;h#ۍ2!uqãO4(oѥؤ:3Fݹ,0{A&6&oIlOtkbϏE̩j ˠ,yct9K уea y4Zꚤ 27pl:XC4_gN)colr[vAm=J9efV㇬lX<*n1^R1y ҡ>uQ72RxZ)b6뵢mu(_SPK\J/To8 u4smime/SignedValidNameChainingCapitalizationTest5.emlUT ц?;7AUxWYӢH}#;U`Dg ; ,~R z.眛ʢ~{UYe[]߻쒅>9wn_m\FOLGp,Z(-^ЩY,h:>xa"LOO"e/ıE LPo˂g\v !{Xb赘P̱F~]V:ݧ[vYO͒2>E~2D~ݾw?eXE(/o&LUu] dE%ht<1} BBk+MvEh0L" V̆zZg EU:}supmHӰT될'fby;:i>nxKsٔ RBn׀h+ nv.xJg+ Dp* 3erPưG<-2m_ ņ23֑-{;Jdel +,)! nJb/"' ndSÕI3j~\Nڞxlkb}&Tm;^wheb3 P'ce$.d@Cpъge֪r=Dx1F$ '@3V1\$@\h%s\M$`>{OBxBkg՜K;1lΒ׌^3mUVʞ-HF``oRJrl:eqzaVԫ>k }],۪2Ss +bo[&ќ B<6>=RGyHwfSRz bAnϽzc g5N< 0GTH8脱q)M GN̴T%%Ể"v=!#"h̫ TPLI(6Wpg)*;2*sȏBv:o "{OgeXz p4Ӡ:3`MЛ$ K[Fb@2oY@fځKmz;p &Jz݊{FLXM7 :Wu{1clL6Aa,RB 5o߬_9~ߟo\;Zb޸3 V<2k3 sLMg 튔(qs sehd4ԻҴlv|uֽmG"=awb.-5)S˖;,EO;סc!泥wm..A\qFW[:*{6r_.q>= e>G>Xr0 Xݸ%cODn*^޶']cQA*[v|v*%'#"b>ł^d)<5@<}ypz~x4%1YG,ږ ѫW="uC?<=0TtuR}-mTdo=6h'f M_L{^ImNE\OCz)ixl#yӯ1Z_gN@pTc ^^LQvKeC7zϳ meQȑooh_)+K[{ijz;}zkeL_/:?co3RWB\/}3c^ИkBJIwHD0Q'L45H˛uêYA]V_:6헢99򒧷;ܥ0ek]VSq&idc[ܕ[V].>*UgxA(BQ]ነBfWb:1-&.n0u9 }kR?V_>fm\E'*=~E3տ3.* O/ 1A5A|]Nxlc&޲Hbvْ I~P M'\]u/`}iʗC8ES-]fKu~o/M'/m7n~՞ 1 6WSᳶ۬{:?L/X윕v_R@ ˠq&p@ dX7>As0>e$TzTZgeuI*6} MLӰRˈ'pv>!䵆ksYӉweuu^Jj+?u]OpYV.,CJMu =r>IdGp 96g\%C (^ ,FjCM׽\ִt""y-/mXX{o7{E %R-%-{LeM' X?/jN DUOBl۷iB0;[Di7Wj(xQIpR=g trR-i1 ډrچsOdc ~N?2"5N'̶["VA T98r$Hx$dUmk+.6[:Kw: &E\lOHH ڮU:Z=Noh !*)@X=oI~_8OdLU E_-1LtW490uu}:_c#D~.qߪKt= x餺׽G8fuT!ǩ~=C,ynmjF󘾂C2 -2;N6jGn8".;SP!SlN.+pr 'zE-H9O'K=a\ G9,Iqh:*%RYz y5q^7v\}A/o,&n&IzfwkڝWvfh ;}e*n•V 6Ԥ0-;s]K1] MQT:|uPK\J/U y0smime/SignedValidNameChainingWhitespaceTest3.emlUT ц?;7AUxWٲH}n#s<(Lf7&JϩuR tZ{mTY_֤e6#?ӉUnqVi\qӆMiPM'­͚OL{a6s`vrM a5k&= 3wy@nN TG<|Eo*6~;dU? &ܧ5/i<̥"! gw yYP'iҮ N:eg(8JL0\A1:g Y[sNJoD$J)ØR$ZC,z-ő_meM6oXE043nϕxf[}|ķ>l},.ɽnle/ e˘v+}.Ȧ%PK\J/0&J }0smime/SignedValidNameChainingWhitespaceTest4.emlUT ц?;7AUxW۲H}#ߝ*Q&&;(;r'DuWU0L}YkŌmVWb:ѫ5 :?]vAt8 OGFBv%:r얞<: U6Cf\7Id H5 KBSßDd^3b,KG#O**EPj{)ΎȰ: `@2fovw_ADt@ = zn=1z8ϢNS}a4/\Yj_=A{ιKqs^zR 5?{ !0_p*D Fwݭ֣X[rhelrnH;%i[%ў;1w,9~4~4у'ݧ^"N^ 9;iIESOѷv%PNڜNMeA/;s۪D'[]CQ,6߱BI;tb['9#iB lcj1U I.=mIcگe-dҽ)C_7!x<. cWxݱ JdH`Q~nt]O"~ɏ0jk^TK(Xqa$-%݈3lFǨbᠳU=|Q0 `mh>¤*`t%icG.Gc$וY?&ٟtͩ}KwI*~n)M u490B VWBr4, [>K]JSk fȯ7sۡgvxjRn#L Χ1ŕn]$穴U馢O ܠ0h.o!r畕kJ l_8ON*1;t`G}Wt,Zw8c@Za~fYpjǵ{TvCsހov`-+f^O't"PZ#v×gV墋ن\7l=/n^>F'aAz]7u0R·dZ-޼xt~'Vo>~ PK\J/ 9e /smime/SignedValidNegativeSerialNumberTest14.emlUT ц?;7AUxWiXGSf^Po -ϔ$"?_AWrCE|{AC/HNb|UŘ5M<jk.AEG9?wYRE뽟U^b_C֫8jpUPY/|֫?Rجk._w%"󥈢t]1*F`3@F;-(30s>w *q zkW Q'`Bf;y8dZ,? q8#5OҸkӸlcӏ-I6Cn/MW PNYVLYIoMO1,*.@.iP?|cT!Ivu ԙXc750h,'+"`0B1qkFZS(g) ki0Ae=BBTk] z>a>QQ;u YŤn {pv|ܳ29HV1.\;ȫEPCh{ |;%Q@-b Yn,[_SVXoHtVQS냿{rN UqY*]f>{0&i5xX<>l)nq{(\NFg望A@4^Qǟ{7$tv<*N\n$5 1 <-Qc fg@& IAnwj}&AU I{i _r:@6&I/ t5aob l IPރC|W n3 ~_DdwP:n1aUr'LNgիMXy$x`ªL&mk(sw|E/fy<م#V#9ew s9񀔶| {&kzɄC<``|OwL>gˏ D:<۹M}>Ӣn3y}Hp9]S,(?Vb/`i{ht]%& #ViHG&,ѵL䳩SFX[o8zhZ5s5[W[)2 c[R,V,r钯Nݸ|nsI52`{"0x ]zq _:&@&3@RI'ʛ>h/'t\%{[>^)"'&/5Х!>k&MSj`wDWdtl} ^z9}\i&q?z D8m!e;ays$ӥV'XK нc@ `zJAͮtb{(c|jpDٯx&/b~JW2ڊWAvLJۡ\K Fou PX׃^s#ogmC-9m,*/]QQD6M瞰qU֤z(6>cȇ|*8@Dh*h=QюeP5AW>quXlub[i+[8083'N{i*E:7 .]#/P|gShϏ;^s[T#fMp2+^8' #^{)WK矿+PK\J/M9F 55smime/SignedValidNoissuingDistributionPointTest10.emlUT 2҆?;7AUxWגH}^"پr؞C <қ2ȁ$$[;'YA)#+9'$Ab֤߬U>#ӉQnQiTQѭMi?>px5QF蝟EA>< gr5KK˘I]]{p8Msų)rQ+ε;Iptlb~a]JN\P>tR4 *][ e&{F>*U%pa0h˒>e ʘNXKCX%Gg v4g{T̠Ɛ/ʧ~ GNyΠ.MO/o<-sd= ƯD,qO{ܳ!9d$ 6 |>UEz' ċV>wO/Ar2/ɳ&(0Cu ;,wL``Y˺Zkڻk;{K Ⱦo'NNLn^if\/, c;05X끿=-{vmk eՙ0(K !xc?\Bɜn)nyL{jh';{OH=qU):|4֨8{1;/ .++|ՓY߱q0#3`U^!=G!iUσjz'rZyGhI&F=ch睋kó!Jj#QđLcr7P]-9Ғ.dԼ;W~~ ;޺k`NN2?r`NᰜNBAT""46Ca[ {F>yS{z =$,wլoq,:pTfyzr]MY_ ʎvKovNi u &b}K : N5;oKKJnb1 iO1/2~͟/0Ȓ7$׬o\H1j^!PR=:D /zIBT 1Fy%E?tCby14־>k`W8l|Bt?6*n!cĥwtydZ'[)K<2ܜl !$e7Ex[c/ϭ~6ǒIăF% ]~atD8bKLngϼ,޶l8f%ʣv0 b*莰}eORtw5_zz-\]"4WI\ 6T6ޓt2 ѶH|y˼t 3y2(%.M'HӠ( Hc50ErPʰ2H1M=0RL*}:aM W#ui>}>/Kq#ҌlTax94nT.%B)?QvtTFqNT^jPBj;51ѻ_t4\/±0~F\]!ϰmG(oE*u1 gl:?@JhTd3Y5xٮʹzf4'R5k=]b{GGUi%ۣmrPwKѧX%eT u[zl#žRѝ.na}/ B> Apʙ/SגmUJi6SX A]T B}TR:%fCZ|K5gQ< p:15" L p("xU _a.CX[Q/*8Gp"/[fqAȥ|Aӓڂ8E]48)KLkQltt|!N't3iw.dRಾyK{;KWB}* -GpN“eF(B-4-D, x|ϢK1=fVz/jcdґV >Oԉ FF'=|rg2qKψn>\{bdϔ,U#duМg,*r{N$:']KNJk*>blG~C2d`E1gW .#QD#?sn3D_ |߀uGv53~A".daL~ޡhGE0:}F,V]tJ0.m.^Hﺚʂ9/P3۪Dwa'r2k5u GB<1KXsƉc!.'̽[Ph$a;Ö&ƒeIb.d 1x:- ë!ٳM%2DC 0u73:wx߾GO7տ1?MOŖ_>ry@=*͙ߞK_Ӑ*)d,ù}#z8P(M*>GEC^QA!LGTsXP[8ZO;xAG1Po3DZ}HBMh_Nj#9j}?XI[h"6=ʦ}qj8+:"pƣn[ַTZG,9|Pt`q`@xj[U5%D:s%ydw)-]4]Pxdߤ6jer\ޚaayͥg`XqVtxLŤNk䓘sxb>ǣyL_aMтpfKtsR@<%eTvW$#S%90Z8\ׇ4͈ꢲk6Lu'bv/`Znd}½qg~%}łdų/DyHx e'դYgXU~xij3 *#|C\v<*rU SC驘MwgF/Yr7iTb"T1E֡yi7͍kZ^kxBi9mʢ6J p, W$E(oXW Hy 3/)1`lqYt0TF"xa~4B2?'7u Y\m-)f =lmN ]du9[j&Ĕg/s{㑲,DM)xZl J[ h<LHT lN(=/1&@59m:7J.GF>QHA| ) Ð1}z#d$?YTCU"yۿF:|uZ ؝g(xwgUO{lJrmytQY0p?]h i)kozǣM2ls0enRіU;9 jǒ|F&s)o2Lq߸ÜnS[ýt ڰ>qп} _"th{' dBfDi> dVs=: $ȋz#`l|w>]{/S=PRLjIitވq?n)8ʹF[\sat\Ö iT}kUX"ن '!uN?PK\J/3X҉ *smime/SignedValidonlySomeReasonsTest19.emlUT 4҆?;7AUxX[J~#;DgOLBrS@ o]PD~I=ճg: \f]V*'y]M߈Ȫ&8̛<vqۅ˓< oi}k}~qןL1oSvo'(hRWìϱm] /"m_d6?bNל\ojG|nB|Bos&'SM#:/֣)5E.s}~|?ߞK_Ӑ*)d,ù}#z8P(M*>GEC^QA!LGTsXP[8ZO;xAG1Po3DZ}HBMh_Nj#9j}?XI[h"6=ʦ}qj8+:"pƣn[ַTZG,9|Pt`q`@xj[U5%D:s%ydw)-]4]Pxdߤ6jer\ޚaayͥg`XqVtxLŤNk䓘sxb>ǣyL_aMтpfKtsR@<%eTvW$#S%90Z8\ׇ4͈ꢲk6Lu'bv/`Znd}½qg~%}łdų/DyHx e'դYgXU~xij3 *#|C\v<*rU SC驘MwgF/Yr7iTb"T1E֡yi7͍kZ^kxBi9mʢ6J p, W$E(oXW Hy 3/)1`lqYt0TF"xa~4B2?'7u Y\m-)f =lmN ]du9[j&Ĕg/s{㑲,DM)xZl J[ h<LHT lN(=/1&@59m:7J.GF>QHA| ) Ð1}z#d$?YTCU"yۿF:|uZ ؝g(xwgUO{lJrmytQY0p?]h i)kozǣM2ls0enRіU;9 jǒ|F&s)o2Lq߸ÜnS[ýt ڰ>qп} _"th{' dBfDi> dVs=: $ȋz#`l|w>]{/S=PRLjIitވq?n)8ʹF[\sat\Ö iT}kUX"ن '!uN?PK\J/P|g,smime/SignedValidpathLenConstraintTest13.emlUT ҆?;7AUxYwȒǟG;]͢9C/o}O?)WWwk[q*ʌ_?ò 3q+^.=~nQ5姷>qc 8>Aq5㊪~{5mv?C_[lzEU?0M7Eoi No~WpA !M/彌ֿ~29I_C꿪cmOuAJ>AvL}S݌0QZEoYlD)Q5Mb"5fLщLq烚RJ/Jl|NR)&4JcMN0@gZkߣG϶^<[V6Y2˕ShOTZ3)P-M;wPI X/!c r#Ҵ$)Nr`v-R2Y'ңkI)K]K I E*5P%PT34.r(;؉ RBbGyS'=Н3ʪ+9~.8$} Z,{dm7N.nt"'$yt_ dbkuy.jWq=laE2Hƶnkg}k[Wzb2i 9 dz$Ф*Ggl!$`2@ZxzF}'s&Qρ*iv[IkvVIRMkSrT@8q*}!<@xׇXO@n<&UYc`41h,ï!An5͎Ruz)U.ɶ.Qf^6w4W?cv^isQOc՟ e~)?"f˿`EɃ^:"O] x() H ]L-> ե2[ 3<.r.*+[<;4zk"y7hg΢%wF3Ytڰم5HOn0w96޵^\7Ji}JNRl}1!d"N/I&͓A@*~*tA!S '/)d_24y;2=μL{9 $i_$ CH$Wa໵E(ٴogAFr O׫:Q{F Am0S>-9Cώr`ChDAkk' Ob^5 xmZ$נms."͎yv1?<Ʉ I CWf3pKǙE :S )~Z$ ۔z>%13k RDeA/ɅC3Aβq,0s#4*aݯ4\dN$$*V$ ߎ,zUʔe_ן7$Œ-6cdD}Zv6t(Zw~߸2(˹9Bp9N0mϴERvlG)?b]ebD;+<=yJpW O ` ?LRQ W%RBѳPof+zPZDILCbIYD+OVk );0~ _.@ˑ| P}$Fb4͒W(ǚX8DFP4kTwkFjJIJIo+pzK.lk~Eh#HD<]1ov8⑵wȢ YXD֚bF|+SɗOD<qHع Gkj2bFOl=y&K~bΫ:ύO{զW^6X}릴=PiGK 2nNeߛSI%%|OD=r;CH}gWlݢ`.τٙ$i^{%^ڠJ9:U^$;} Z0 L偎I}xW4IV^y=Xe~oDW- As|tӸZD}[_4sjJ- A,PLY+[| qfrɫ*aF fCϴ<2}un>ͰCN C F|-rF & ߝY:R8q:;ݦa9H#uRMG ]zР5<K=Ʃ#Clϕj\=.,ԋ#E=I7LܧJ[0bN\G񹳆#{":IPWLHf?ƥz1B`STU}#٭orF2wEv]cr 0Re%Ccǝz'>oV69/%oW+sB͒щ_ Usq;3˹WÐw} Gf;me$ce/J=n ѶB,TMQ îgo;c{ŚFUJ Boq0ܱtزk]?½.foC><u{^Ԅt8yKK&ǵxW7?[*׫VG7悖S (3D\J ?JT (`^4R ۓux0#`   j:fa\8*Hm3ѽ1woG2vNj36 =-/1g^N;)Z9n{C~Y׫ҖKE]1:,No50B2_C -69)x:BM hII6$>!6CxhcCFJso#{?w2^CQƊ4,#Z`yoI7[4:F5YrZP#ֽWUߎ-j/鴿 DѠKEgIߦ4U>F`'rA2n7xĔ"Zy o- sK59ؼD^/맕 Yj:+ѫKZ6#'2lJj$${  0ކT(ގҭ^7wN“uᎳpjꠉ 1N(jbiEmi k<&ˆcwܫl)h,ztںf.Bѵ;PK\J/ro,smime/SignedValidpathLenConstraintTest14.emlUT ҆?;7AUxrȒ|s{`{l7@xsGx!>tsf"VPXʬ/ςK+n`˅|}i0fq>>d%i6ח.>y__,̢ߧ&[?~ ,Ru~ᩯ/1Zc[?G´`/8_0_V(yY.=cZ>'W\*{>겤/.Ul{庯4^%nuDY|} .mBeݵՌ~aZ__.Y?%uR]Al<>2PCm\N֐@'-H$DO4D ZjoqM&"c2 OӰˈ®!~*(J-zٵ«dZ JnUd5#%Չkc[$:g2\˩\\(fLnWƓ@F Q `&MiY%"@c,Dŭ9bʷ!iH.epq2zD$Ak~Pb j|j H(X%"yJžNywuq9 |d0JкO+?"NH=Q9#( d")ni%V@!rh"q 2qi5czڦ@b"A%&7`]B9)+O>=8~:%c\.JԉKH*g=ڤKw-GX9Od}%M%_Yj05D=i6YI690Ųv!4# /##D22 0Wm3r7&kt1XkPypr(7QQC>!O<-'y|wɃ^l򧎉w. (xV KzS-+U_d\vA5JÈ4 L6tk0ڰ~+El{~y8ym6iN >}Hگ{~wԩÓ Om3KJN<#m2UC#/~T]O"7&Aj^{tO ۞s4p9>sG H:횤EBx*oB"oB ~ZhRMRtz x\ }*ve| eM-7#A&/?(smj;'BI;9͵=$8 rq\/Ro2Ex čl<{[p(N'0(raAYR:}fF'] IkF,sd2W9|+`ePʠA-a~<'cn!2bfDGdLk)' YuUb=笖 8J"yE?W>7CaDEI׶.SҪ- ʒ$)iI==$MbKk腣YN>ZHpI3DbUNi1Vf8as=+ `w.̢O[%4 (/ejg NPѫ=xEE^N{X}ˢNzĐUQJ@ŶlN ]Io-7xQ1碍Hwiq[_-tr3mnZTPgJ?:Re0*p^.dF#q9(Ⱥ{}ּClUh۝)9=,d $IώP\7rwȢ Y$$?xbU?QϬ(yϊoY*"̊3;N6sOay:g׶~˳ʏo͎vuEp;a|J^L]Owi̚\),MxwSmV,.*ml _Ͼx'P`")$u+[.B=CqS& A99#ZsD޶>-b f) 57 fGp:1z g ]•~P sN6Kfz"W*8i}G}dG|-[7bux־%Vb%eWD@Kܯ0mrJKnBFm-G&ۣKކx5dWr%Ԯ>3*oYt_=%Nթe|\ ¼WToF]]k+9 ?/TQJT.)rw.OlYܷ*i>aO9-Rwٳk!2=(3G# n BT`0׍vAm"=s4jX]ћ\V &Db[cyXʬ;&[-z$ײnSZp+V/g%$sJWC08/4:'EM`?)pH,}zӤUSW6sZu` 6)jM!D+ہdPIhM[sd%(Vgȫ"U~θ !n tz5=Ymg0/unGCdI uYP}u+S\Eތ%b|ϛ֧Jr^N~\0 pyDB^;qWJe=koP}C``LFLW4=IRCmI4&9 -)EcV:6`JSBř.u#[ޛ9H 6Q=|FԽAݏ[l2Aw%)1磻ӑՖsF^ԧT[D0cWNIVF[|tUg啿=ҹ4LcvH6eaETMnx͘7\.Co)!S!g']"<"̷TxCAV'K$ka |RG/ ;Z&n*dy987=z:c Uqyӳد*Il Oc=眕u6oꞩ'_KWXHH,B1?a$IdIg$ a܏J8OT2Ų6R8X|؎ wm+Xžr}sYEhZv 07YLW2Һ !&^[G$^Sy6URngX3ys1ĸ,kMb ٔj$҈9$oہ'Z@B}ricF瓌r\~$Vo2ʀ~I1hT6YbF6>ODA4^jy{Plrzsa$N]S׍Q[7 4}a$*ކ"Oa=#[ʊqEq<I&UXAr6 Afs;uQ8\a=nKu'EɎ6P+Ӓ>dG49 H}㱔pGuGNrK)QmɃn%;J<{]{5\8y5>~F^#btqP m>:ǫ-yQSN*LFiMg2e+7hz?uDzf+ඪƸ}?e7d=XsQZ R^Gu%)Vh;I$aPK\J/48 N+smime/SignedValidpathLenConstraintTest7.emlUT ҆?;7AUxYӲF*7|3nhAdQC@@YdQ_?o2ITF,}}êNcB@Gf1B?'a &$G~HcRyVb&&5.̹"KfbeuE7KaxJ97f2k2 7}~O_!7^˒,qR5D:0xxˈu:KX}C_I}L^I}/yGkϏ3"qrI{ nRrU\Adqs@Gg FVGa!a[*9?\ol)m]^ܦ=|#c?WӀ>6њAu~̒rKjgz#7e?fs\KR Kwpp4+4?gMԟX0!mIy0Lhy y&B0ƜmNF Aak#@L3oFY~n9S\nW1hMV/{ X[N[QyF}q1>:wt#p+?wMbLHۘēdnr0 [qR4x%"EmJ3K^PY,Xa1[ ڈsösWmno2Oj[:9V(n ]lbCuXmٹ5}(x#dž֚-6H͐;.ǣ]~ɝuî%io4ā3,QȁBB)3X;G $XefE+om B .0A Jf3X7BL|Idx$!h"qjQ ˂ }&w&HtΖ.* 5nsuT< XٷY૤Fl"S/d&7Jh+mh/i3_ii[ӡ0E3??sL"B_'E_G_"O5 y;bz?8-HMpwJ~t)<?/YR 9fYmY9Y8Q$L'`o^eݖB*Dvepj5R/N'NcَJ۫S|FK5Ýš bvű-'S05wLv[0%x(Թ_mȼs(g'DvTVR^]Jpa>*E>OH7C%Hj [ `Y Rd*T),Rx(İ}:l@yK7yUBK6o[s|uƣ_ǶW[_$=c:\w\W8-m[UG^aMۥV{2es٤ W<.A{,S3rƲB%yvCuFZ3)zFzn5밐kc`Tc}×(hC2Tj6F:}9ǣ:s דʉ7IVyLDc 2 P|cRo$d']vh0d?YluC9uZCU4&*tEu++PphtՔ1!a"=dhw lŧӰf|/.'M)0G8-=rS5TߥHqGF+r7T/Yr1o3gea AV}òxIדTϳ7=aJA30' GHPTbOhv_fitSwXL__&ޢ{y^$aܖm| z._|M 99nØ}vp m⦑LhyxusTo)yWj)BY+̍SPK\J/(b+smime/SignedValidpathLenConstraintTest8.emlUT ҆?;7AUxYH̹陉.(6" r 2Mr2S!͉6 & z4QiTv?vQQӥ4/qu' Ia|Gļ('dbU]e7x@Qzqɿhi s?$ V>ln47aw?WƏ I`6zXޫivlZgA|+"a>:,6(| $Qz>{~^_k=G͛TUh1Um]iu^9ͣ}^HpIK@EѱE`HhUHT.V^T$c/QdUq8P\"]6IRCw[3[QCӧÜ8{$q*vn.ʼüܦsF(~\Sb~d''־adаGq@3MH`ހL-  B;,=ou}\ycmڻͥ]o%25canEf4x̕$6򾜧5%;4>.VA/SҽȞB)v7=pQl^=kUjJ(ΐٰێ׾~\ k9T3!%a8D \wPM IlS,`SĽ?5hτ΂!:Yt٤vv2]ihoN= ݠM5[nl%oIsYχx==5@&,8Vz,iC=,ӏ8ٴ&m%~ؖ &7m)4Ѫ4i[L&BIiJI|6Umӻ}e)`W?H=ؠoo埰$O3yJi $'ȚAOE~v4U15NPRCuq.& o(ݵǦv^7lхm2xuYh=ط Ϝe]gPJ1v_VX>KیԉtFJ)G`egjV_)NS{rU&?.Nu84?* 8?cHR 8Ă-ok?u6}0Wn ,c&ɱaܨ~7)[:OvT W f4p ^μ$XHY> v7(]%\(#Ȼl9~ޫf{ۃVʭt.:8n ÁEwղYoLvnIv1]0'r NeGeHA*gU+a RnhD|jb=b6m9wo&"-0 h $$Z+|*N=ƛtH?.7r6\%NZϩ̱]{*Ek}d[6pS{Wqۛl#pfu.V48ΣX-b_' nO'c`6g+onlnW7AכB\ob!#g\RUP*.xڞšd8m͛bzh``#sg,m{Nֱ uv TΫ2jEJ?떕LV:9x!$?QWǒF@s_PK\J/k'smime/SignedValidPolicyMappingTest1.emlUT ҆?;7AUxWײH}^"nnLI%HB& d~K]B$+9$Jޚ*g'l:1-: 6lZ?%]) wYAx~og'X?$27t"MFgH{^$İOĆ? Dg- f #g8N6c3NloP#}tJtE3YI~5[t$Qoۺndןu񝽛[6Ɩ~ gۄ+ Lj#nۺ~\ %?}^(|?|>S!2 cQ Pٞ1@G Fç JXߔQR˽Rm-!FE̶x&r8K9 ^ĦU`+:C;Xq:9p0Cl3^JH1V2k{ѱqtD^z< E*"Z E&>ѳNك2&KcYRϧ#٢AeL'!jyr%-ȁBΉüQTؗ%VR2T=y;)5I?d)Hj1Ev9DG1YԀ\\O'aK)^K:g"G?= uoʼnV^!W#_߱ ٟ ۞6/еWtRBC`rVU]{6E9 ~3ֲV؛82YI(\{(t Hc_/k2dςFx2Eux .G:UzF>3^^@zYCM0,7_ݑ{GTBS쇆^A69.`|-uek&+5}Т:Nܥ/Ue:o]dꤴP.ayK{il np Wڻf@hfmn dzjNC prD2g\ͅu:N'4@/AW   ?ɮaDo^TG]A- boxZDu+@ͽCy})f4 K#$0͚h{ rC0ٶqruemjۆ]6ՇZKUmR:@+V=GeP/KLAD1cnZ̍[]XckOsE: Hnia8:LЋ0  KIL'mӆ$c"ˡ !/$h 0+`.dAW:1a)M#TyppHUQêc^}¤?&O=lXuݻhu qDz[k'2bhKv$ \mŲn,8&v=S=p_Ҳ! (b-ĒYMGT:2kV(n!j:鈎 N5%! 03HHpY=uHUIG~/ĻeXtKM32sQoģntzjW K|ٿhbQdY%UWk>!׿PK\J/`Y *(smime/SignedValidPolicyMappingTest11.emlUT ҆?;7AUxXْH}xgQm} !ZYY9]Ӂpp۹xq{ >=*KmҴQroS/ig½5I'XDY+,"}|'M{NC+dc>Жo=7FAS[m>cˢE ٣c7(,F ݒ_ߚ/-{E6u>"_*~hN _De| &Y/meMU6YaжAt_NY|˲QGE0#Dk׉e9a $:w.YG2<,֕hi,˘(TI}| #9Hr)3+.$W[ᚻ}o5gǛ;j5V6q, 6ߗAOotFd^7*DQH:4("p4(2m4MЛ*Yg]W aj|ƻ{;b~ <㌢Ϲ&ڣp0eHɽt 18~&aLr?yUкM{u&>a={W| x'Axl?m]H"_qOC18eQJƩ.ۼ櫱 Be4HU.,YN=^otx.O4YwٜPu;9ʱx]vm=CmZ9Sd>YHux9qpC晟XM_vmC$,HpS}-|Eiu&wVp`ػ9Od 81<|u ZBsSk QLdaXo :2B;|w &KEx)B$*ŗ'1͍b*Uv򖼐Cv -Dᭅ%Ş\ԚA0% % 04u9૾|砚n0k&nzm<oA֪H:JnpF=0MA/\h/4֕lUl@i!հRG 9VeQ'l=qfY'WE.[v|iYmks^SXOO;wY3}r,cLX.BPgakaG.h~w/>޿rqdՀO!9T>uMmO#1G0"3gm)@rey[z@o6z1 ZO("&-d#fy Ā. D]d=#Zâ<h|/jK gQy ו0ٴ&ckb"ĂZJM}-5ވ}-}egMM oƂY0ݣ"Y?0_5K }w/`:eb'NuпvSGECÜd%W1RY!z[z@IS#5UOpajEկ&F[+]oDsWoX+)[J,O\Vm2xguzF(vI M1k[4X~X1ltʨ45'k‡)C<8U8}ՅOUN *(7CH\؅b~ITnp_F|"NXjtX5O=(FLZ5dZxMl~>!PNE0ĉȕTJpW !G,X52iiq}$Y.X[kgw$k B&kv\_wzE[gPa]JC \rmp:u%&Kmn\'rr[.AfQMUg_)ZON؏KƄM{}\@p"lz<"eӗY>´J, ɘ"%ݶ:Y | 5,+oeBCJ|Ԥ:&(*#mvrpJRO+?`}[wc!ZF"!xc}//;HZ\irՋ(!b\c{|gݢf=ޣCVXtQ\׽OUSJ^"!)36HQo|::>{N96ȷ;G2&lqU<.X]!DI*v27Bfr#ȺKBd׎ibۺ)})&p5ebz ǡ3$Okp>jK +&AV g>VL|ܿ"ZrAKx}P8c&Oqu aG{"r.(G EMG46fhLh8Ҥ$1ڌ'zoHX/2*/%k$ ^2-dkg/_$HCh1} YZ C,|'뿌N-h"E"7 KɚqװЄ3 q҅2S%H~[)%krڗ̿a Qo!OgÖ;ӻZ̜r9ֱpޭvkZì=Ov1:k;"ܿ&8`nD߂zv"HDrXISHd  DZ-W Цψ,H@Zp X:aP=[=h;P;ucՅ]MR@EhSWW VԜ& 2;CHu=)v3 m#jdx4hP UG)CXG A"J q^eqe̮-]+RuK*?OS^SI).n/2z8XI\뙚NްęydE|R2ϝGuyiZOt_+Jm(*eA HB\)0Lgn)jp`pTNCֲڽ4λҼS1}lc"03'&Zn=Á||9[Rs8jp* @pb>{}]G~K#3&O 0kn$ @C:(tWM@ʙ̬ꊷ*㌥EjY_glbת!{v\TAAuqAˬRU=^,Ӂ;uL/*h)@3sʐY#PRr8NkmAj8PFo6=c߻=DYF: Q.@8_ciUShx(03 ?c !=/:|gssϾt*"|Kt7A97E|utDvBvv0ļ6v/SSq4)\YpX\#C tyWa܀V.iݻ 5^y瑱keN蕰 VSR4KlPӜ6`f"}9FXE76 7u H1+_0}gs]LQdauymn^ԅQ@36]]6 US]C6e\s ן f5bkztz$rҮf5Yƭ)c*Nx-Wk.U ix}j_^AVxq(\fmxi+k8>W^u-+,C-ցDM(P)(d\7=|\K9>K Ƥ pjֺ\{poqSy0~2q*m(QyHAm?[-MqRpڕ.Ӫ7"u=]#QaDLTQܠWv~ډݥO-R"U"FХv׉珏⦇$1*\:SanM>&vc?mjfdgS)[VޮVOsT̽xgT7fgj-S&Fr*r`11D~~n&m?̊}Y 4H(=y+O䁈 w@;:k%t<C\9@nY QjV"ZuԐɂqԈ֜WdeQ?dt1]26J To;H@/@av2IX^nj6g'up֘<0FЅy m͑#?"S.7&O?Er@ C#|>bIt/A*_FV؟VM\$59>-bu?':.J,T4:HF7gD9l,'G'Kv!\ ^?l|چsGHe3S.9剩[ѬWɢY|a<5~w/PK\J/zB (smime/SignedValidPolicyMappingTest13.emlUT ҆?;7AUxWYH~#;U"dW.f 'NOWݮ f-$#͹,&xdo:9.ڸiønϧs蓛GB]o&.![pmb99|L_UO ?xqE&s]Jos<Ȕo>}2&ZNhZLmIML#,Z/ƣ"2s7$YK~_&ϗ9"D~2s{>Zo9ˈmMZ1;7UٜmINLN,W1Sc7Vng#_{et,(*(A=@2= jY:L^YXX @8&Yv|nbשo]a%^x4@Ñdr­+:4tVsR)J;pg3-HS'zY3(SzJrÚfm3א=U$cٖ;הكazy-fj?&Zyq2MP RC}4HTPNፑbzr-T>YQz)̤͠q5-R c!g>0x6:P{nqlVu̶DnG?"_\|4#ĘHV1x1$8t8H/|5R$W(l#`'}HW2 M_yI;yHj/ q@ ameIvDf#ۋo=uP;Z8/mo֒sd[j&Kj,cᙬX9oguo(y \y.caIK}2PX&xD>` ]dorI=baBٓ,EU$bL|1I+3TO@Ա#b{xk5r)6l =K'vt$/tqCO'={ l^AS)fEVE !ϴ#)-RGޟEvgl3٨wVQvAc%譺gEVbj)Q,[])n}˕!_fyl)ifP`vsz5Нq)U}7.m(XRϳ v@N,^=nY7}H73,,y\2w%TMsг讯ےfd3|q4N l+SEyxT;2 %~wr\כa=a?JώG:|`HƤ'>=E Er{YMYRmiFWD9Z"4hxsG*VRhcj͐FYey{L4L,wA q/&s N'(M鼥mT4(zb C 5G{kҎ›٬6S+fsSGן)IPQm WZ Y^Y }gyyByݒ$:A{۰2]ԔUGi4`ڼIUDWص)5OʋrdkԬ[u#NO*P4@Tc9'Uhoǝ(Eut0o\Zb9wU*S/P~# PK\J/оD (smime/SignedValidPolicyMappingTest14.emlUT ҆?;7AUxWk8eI1q2O'ۺ̓EK^M~pʚ&7M=cg4 HȷI;aiz6aѓ)M&PW-7y!2k7$,R$9?gN׷qҨ~VEgzeqn[T5M:%{Q͹ R7y>èmx&Ny}A.XoP;>XPkf* `I`b&b$('bV89ڕqeZv]TqTXu"_SxL*LE撰1c^.btQxvvUD_9]ZC1d'lYgLf1d;GZcuVD"^dh$B##\ .=IoauR#8h: kYԷ{Gl+MxаEKxRgl1^}̐t^A R ~U8x}CMG^x X}ԣ {SGB7ɕ5(jwye<wĽ! qq=h:7Lx"gBCkmB2V{hGgS2QvMSٰ>z9naު)XOz;"[-WۻtAk7+4Ԃ p@T6S);f5yk'#٘H2&vӋ{Z>G* $"㆔S;r;!8}oy>dhY--|Z0:z5! 1XQӗDNGʵC kWR Y4i)u$I&"e䒼Sֶsdyɗ݆\'{\ܹYW04դr ~ly{!=y]Mٺ^<{4LB 03n{oRE`y*s6}VF4G<΁$"@+xTr@/ `k])NH 7HN{\uͼHY=|&oD7m6I_яя˯?sM)kP+Z]SvJr)8閡Cʿ{괗JǻϭNMz|-`f詇oء糀ʚ*ΎQst}xrȄDǕBsp JToVl@h>bYÆqI0('5d_p<xڋذZ.65c_#ZO }8IƖ3"~sq ,"˜BVxcHb\_5դ% 4 v@N>RjOb Љr^M2 ɽ N眜WL/dC®NGسpʖt$@sQ&ʪ!u["k+FF&`NV+"xy,5U[F@xDѾvEl ެ)ǣ9vϞ2gl-ج? '[ ,_}3n<\OŒ0 C]ZI+4\XƪU ]WXQS.<4p "db#UMuGU&j-kO"JGѤJH޺J;|?f|I;#H$,H FW Nj+*׏&p6ѻ+C%zq NMI=;.|mxuOyM.گ:al2iwŵi~ Z"[_d2t{|8DT盪XNPՠ(~l31f_L\4^RTdժ4.AD6u$ ($ţ@!MQyfy{syߢRta=8?`$iѭ q𖇝®ZW:|lfeAtunhߚ!zZjͲ@&r7%+=ZWf0x H^׌d]*o}ޑPKZ"1 ='smime/SignedValidPolicyMappingTest3.emlUT I:7A;7AUxْHfCsӂv$x Ȯ4,M[#~ /fuNfTuNm]g~Kt"\׷TE/noA~ o_fۡ.p|CUɛtj[?9}oG$%AFt HmvoAo$&.ަ:c[g0xVK/|}{fIuD~>O.w]O/|['f[mֽ:?LoqV>E|w=9*Bn僐?`b^bp?%ć:ePi%gI$Z(\M\*MJ-#Ժs ׉.\@- ^u]{N5*usMj=*[kA$~TYgE i5(糛N˂D"jzN~65 P4y"ֲ jAP oZQٷtYC!CN [Cy#"q%t+)Teqڰ7xB5 s'q=N>ː{-]{x,jt]P8-e:q)thzJ PaR4i5`sn[˃lA4m.Rj J4?W&4Нwd5B^fDw^DqXĢmz$R [笷t,̳k.ǽA1FRRGxiӧV2)_Nإ$D/7\y0_"ӑ!Lz&n<׋5oRP$k~{I{ݻu^K--3TolX=]u/gW>ʼZu0BDĒ{f|Wi;>~ ov{1VOtHk dQLDc=d6nVwo!cV0M=^/}llM)=J.x1YQEof>N^o s7P꺡K'YĐ)p%H1:/van,3ӱe;Z*x\ed{^`ã!~k.>]Kں:]j=uD Hs5PIm\mje6X_ݭqyң!xUL&.z&$-ia_6y=MC{9ſ3-XzF+ 0{gif#c'!#:k  {v/01r&ұlފt5{x"u'e 6ۭtZotwe^8tGEhҬ UtXŶ(ҐdY]]h'y W.禲-Z -O'I"7z~g:{m}GNNkomo?2Ì/^j^IIዠR*3^z4/ ¾v(6j;\)-o; ȖWtb;?8C[K@YUq;DFyp fgr_hTngĶ@*]b؀ hz(j'I6(E]`㬝3HܸȇǏlc_kts?{'ttwG>_uEe3ϡ2 nwjA IʺG0%9*[nܯW_^)RMi+*^+fH,yҥƟј#uLզPtA;b=ӑnj}x#0q)dJ9LsrNBOdʙ4ʡ !?x.Α1~w쩖aO|^3O E[O'xfr;ձ6tUyåaW)jЪ Yp8MYplwEWqga}ZDQP$sZedWN[7w^wZc cpQuH,PqJVc[`N>ZnLĤ0PÎE8kmϾ{[|>BiaSt Fv\w ]"xD#KcNneGgl3Q^u9z(f]0#* yiþ V#kMњ9}: ⛹$kTamOc]qak Vd&cN)4޺q:y}`}ʽNyyP٩L Ucw HB>(!#KUv_i+?{;څ}3>j > Sۿ+Ϊrvu:fFKq#%:ރ&ڌG6{Ȃw{9<|$|[+m^:؛Gt!f:ѫsNi Gq9[J][J,>T[`D$3VLnCA9{Y typCVOUzKz;#R \b⚑['`ATΞ:+o N'orq^}ps>i"U_"C#ՇsƇs9Ȱؿ?Ӹ8{ߤ#}K}׌z+,bƿ\?=fO«7 nyt.dD$WGH8o\C!Np$|,W3eE ";+V в_c-Q+p5ӹ|?LFf~ܦuw5,zCqᝰ[[\kIo}}ZhŐ&kT#pl/ ;b1DBXC m:ˡ.}ϩ8//-kNmByUUVWFH7sz?PK\J/6uŇ 'smime/SignedValidPolicyMappingTest5.emlUT ҆?;7AUxYHǟ۵#UPfeAOߡfeɡ[EDޱYOVԴ ό[ݿ킨.%oIu*>QFOT&{u})7=m$$'K.W8AE#~~?ߖ1'ߖ3-pyϘz?G : ͧRDϟO%)Su?J@mϿ7şkWUhM}^ںj/˅^yAZK}%Ig\) PBm0l@3@F"L̆MdF20(s GYb>FEvmiJ: &ˣZ>]{,ثi>s q0!gNZ)LUYNɱh3 +eJf30ʆ$eӺUl C d `ir0˒G (1qWI &k*ˍ*Pqpx_byܟIa;V5@vldš|j?<>2ؽ1@nV xͶFt F<(-sF뜸̂5`k[VSآ_e%q4aA76g!, YsH\ 88%a*CQ];h{lc1RdC'|q4ϖg4BcV{!RZ_WN<UbuP*6G(;K2&]$ib NXLV轐D̛`-CPTGi3 }usBē^Y/6zv}NNa^< 4oJCDO`w@ d z*O2F H$d_6wU7Ol`Yh}2[u(Nh0[+ƶȔ" L U?3)Ͷֈ8ʍ5Ph^T8y| \8W=%39{7X$;BۍiR 6.f4dL ]P`"l3BIVہQ_q-p2'CyE0+Ⱥn 3k Xu<b!j>hm?уF ھGp<@sE8yqh22`EQ~ٞ;ɹ^q͑r"jcNX}ᧅ>HΝ=C,˜,`j횮/*_#V2"a삄1|ImMIb:vg,J1Gn[ ^DŽF4 N/tX`'А뭨=:lhܱD;̌;7'٨2"EdAkVv_``M'r NgF2P\ {8O!A%PDⴢjNrDr(k !ϐ~~,_l>{un>o~I@Q6iw*IeVOđopzL5փeR1;\Ō ZPf} WoƚVidjWyX 3p &zBJUѾq^M \r_Qw-b}@b->ʿKGL8}Z;alUwdz^9dCyS<$^t􌎯\# 1NC~F:xT9 @D7FCy ISxwX+65~nT<t%HEw|:Dž)UgȟHwxí+h6ag\Z[ 4H 4cK[i8#擠ykƍRjA?&?yT_ײ? ?a|d-dGC~bܒu:Wʏ_{O}- nuoի7?Uq!)2] ,@,<_cdl7[뾯R[1(ldWs@% !\ۨ^ %zkҽ$v$O+^*glx~uSŮeѺ(;q̪ D=Up5j,g:;:CG_g ?%XOFCcUwx?݌"H'ޚʽY"LѱŦ5U@rњ|&2Gy.NNעly8wkmsZ'7pٝza{.V2bn̆+fNҽ[qHە}}pKiy5L=¶~K১[/2|NFdLa8q \['7d<1v+xnI"6AͶ^SW#N$/~[yV/N&+3׊F ./<wp}ɲԝ16Sux#MR92YTl2iUy'IԎ`FeX/kIFwbQw=׷FclMs)m|Kpy{'SqH4جZ™߄PK\J/[ 'smime/SignedValidPolicyMappingTest6.emlUT ҆?;7AUxXٲH}dIHDXGhc ěIhAwy+dXs܅HbU׷ot_*ߍϛ4~ݸ~Ax[X<*n_j?/['agv*ސ]qitC˖?$='_z (M'ˢW [ ݾn+ ; !2^ %|0mE[QJuf'ugX.^zar$dE\FMSTG8/*d݈YM.1jJ6G+Qv,VQx][Ӊ.KEÞ=D{ؓo[d=<3s Ht[B|i@azXZw$.N'[Z`.B+9_/;6Ew| MAFDb|@ a4JR>ض m?cLI0+%EW~^8\Ց|^}FD Ճ̩G稙7鷅7U| ǃP(>]kom[`1q' ߅Gt 3ɳ? P w0x{ 9mlf&Y< # A"[ܗ=@[VE/mgXusۃJi>z@p}O:򺇯bXQ3`N^ B\ V8Vs/?׵'!_y!Ćt_@IFUR p#h>}DCNz{i5 &Q}[Z-^4A?x0*4-.p]O#"%Aqel"/ ҡjRF R %oIr\hi9=}Z]X}Uss_!h^F+0 ˖aL7 tZGG$(#_]򘹡s Wg_UgE}G}6F[ ~gTplw>V熟Ȉ~C`[N6kj3O_> [gUoB}4F}>H$GfLNCtV&N%d{NkrS+ ܱ.m i}}--*󝰢p6'B앏ʝ!9N]r5ŕ+luݭ/;usM.z6!'":]u{-̔=PO1*z:s"KF~ Ag2K,!WyWt$5xC: .̮:HEbFϦټLt;vtB]n|Wp)2d "gzmٲFU4VUڌh^^mg˳7V('ɟ}t9Ð7.ίry~$Y+qîth"ͶzEvD`$N.06~sXT}Z'gle7<TMzs[U v>%QVgIM6Jnmvʢ@UQqr~<'Q>r"GȢH :+ȦYZ4!NT>óų|?> }$߲Xf0ey}ʌ  bU47QS jRQ3dQR Imp2PoxlNM**a̦&k_- 6 4:eE5 zS#ҁeH!u V;75Q9aҤiYKuW9wKrTxnpiTE:avg12jt 5'>{ezB\ .f~Oqpιz<"xV@2~[$C,m5+u$jjrĺ Aek68+%VkFT#@a Z(ˆ~.F+X/|C 2lP h6`4;t}i2Ӊ=Xؠpmͬ^OHо:Jzf}CCUڽ4'(7q]pY]Z]r=g Te *=u:KXRۖUg[X5[8rCvϹٙ t5Ns ը n]K=m)2óqhU-&b+Cs]vSuʵ&\ m9 ;i17ߤ1J\ j.ϯ˲)aE,,fvnHD,kf=U 8:zh$&3m^q5;:Xz2Ý4Ѣjzm{DGyn1-rKQuUC;C1=$c`2! )*SJÊ>~Θm$,#5PO+wa B!ۏ8@8$Cz "xʔk"O&߿g{QA|Q\)W|8!` (0vMeit~-Fga~x(k7ۣg]gv4A\ 92Yd%x&;%aSN%4Umd#.+j9M5F}SͶ?mݘ7SS^Q vKgXBV|dSOdt;[bt;zhrEm6jm?)fO_Y-͍ٱ1wy޿N> raܺmDF4YpbN39omdlCW̳> gP^뮰5qf y\2z\(vT9^-}bn6*N S}sԈyeso{^?IY?ۻikH":6XW_lgQDf<k!yQmR |h" U'|x {Wye]uF'7vT4e)ttN¢?Y].Tߘ')],j"Z͎+7Tc e1%Cނeۓ|W?`r-䍊;aņ#hBjz<<_d9Yd2|yYugpw3cai>8/{s $߆4(F SPK\J/ o1smime/SignedValidpre2000UTCnotBeforeDateTest3.emlUT ц?;7AUxWYH~#;₧g&MB7,AVA}ݺ{z:bC'M*[D $e>?Q]OnqTI\?qӆMI>>I24qŷIS $T(j([[<H&g#7M7ExbibE}b8GtK>.l'dIvB,[Ok/~T$?u0Rᬺ-OIz{kI?qmx"Ij-(s|{ONA/_R&i?m^rirNu_/(jV=ԁ%]Cxl vnFoaAbNѺ?%dw$K)m\.ag@W!õ;;N̂:z j[<ǣc>xb3J0J28 z| >}&88d┻WE/GH=x4MyT+")%h-WЎ/w]4)!]J{<]o`q偧_HOd:k5 r1NOѽ3z"3Fs.1뇷Vւ^eaw4j ?l͢.ͅ3Տǣ. : rzA՟H HyMY\ogUR6B]T>_qw Yro-0/WxG}~ wrDtЋ//0?c?/xO܂~?m"?> Ͽ,S֫ =?=Tw:lN>~߻PY6}6? ~V_/׬ߏ|Ig ǥPƵl@h$$ig"1;*H6',ѡ)K`3$b-,"Oc2miXeDmJ`E&JkAD2nYʚEӺȩ]d8V%DiLwy:6 b&!RAe !*b|감$Hc̸FJlhZhQ MH%ҲqHdc _K4Ě#|[NlIG!q)K(zga`ˋ+s߹h2.ZLI,̓> R W&;lja$%݂Gko D3FY!@.'$#DRqF1_K0j89iu9Ehr%_ޝ\26Ałv-rK=i>T7qR֫=tS"qd6b|Y YO5=9爨޶X7B T^[[v3KA juA@_h ~%x.EƞFEz^R{E/Ke./+RTXaIPC2H$2tY3Do1ɿؠGbB"02)mR pFxS{z}5pG'5j zyF4 uJ܂L\׀Dz&7i"j+|dd9zԮJn#V&'#=\ɬ S" D8Yhe/&]aLX rc.;txۤ0VH@H/s3WLMQU˦a5d̘x^*rݞU1CI]l" إib;jsD;oi Y"YgJx{㍇?G.h{\-HzdC_L* +rahSQ<398ch?Dk|VJ^?ҋ/fu+>d"n.=]x)At}w%XpKSfھ͇C{(Gx#=~8aW"&@񜆲>)@ 7ڠ ]kjIPIayFڙsˆ: -[TC<nM;kupDYdEնEFNPQJu|zLXv!ywrU곰#Nyz9./|i;{}F-/ (WnpJ3$B}S-fS˭o1)l0{eⳓlgfuȺOBD]_EMN??[ ) =/ ;W-iB897 ' =`C'J_۰=1: Ri2E#sfm 2};i|^dwrTX Ԗn+fn֫ *\vۓ@>-x}ٻpU Fl6!m3Qзy?hZVGg-iq!,ZƵ;xZ bѝ ؞[,-Nzz^WnRlfK8{E!z&UↃ rJBxC<А`{k:E }uM}ar?ܯWjk]ex%^=Z"Zݔ.}L1 ;aryp6[61}U,brXQlVAվ#6ɻ*"æ0 mnfs3%DNWE1׀?dۻ#tr,K^\81;<f%"|S\@{Jr"1#|ܷ!Nhy#FNZ@ߴOr?$a^t7$olR`^ջ Bt?ۏ]&njvؒoΡ S:5m'W!Qx08R!W`խO` ̺ci3|l,ۣ6og{a+."ほw/#'@o0Jtgm$RϤ 'D\\'֡koġydf#nԀ]MHCǝLtyؤ{tkXC6$\:\#}F?Ê~dss=?UcI%|b.%WL65 GM&uVxAA~$mzzr;>S+H97m(HɅ/J~y;Op֯Gxĭec֩ww aoP|P;C;W7U76>?9ӫ"vXazsm(+9ٵ蚵Ƚ\=[pt)ڠU$]#)tHܜ]8Ը,xY8P֬W,G'`x$tG~TYPHRlڃ<|YEU|#ǝ7o"v$bF"L DžK^|vCy}9cs![ %v 9r2{waz0R]cNvT9J0=,GY@#j$Bj3}47$7r8G{/7!L>qdmH #HnO>Dž, k(^P }^mIrnQPsE`c!}[£Y%P/0d-鸻AT:%ѓաJEႦYAo%eNU<\W;3!>z& S1Xb@{sVD(1g/L=g/bta(}BYOVvYU~~,F΢> j,GRݗ /]TQ)FA,|ѣfڈ< TNj].$$П_ 6mpc? ¶l5_P^6yY!ea25Ozu} :Sѿ^˧.K(z?JcϷZĔAfeh:ד %χ,4:r(@ 4EH(dbt"Sܕ"|e&0x~~Q%!gmC0[.q4 J%M^zF&Zi˅[Xɴ=</ `N#V)TWENOLΎb&~an9>S1I2ܙHk_aI ֕dpdT,K+pDHPcp}-PryJ w;n.j]ExA*ga}]fG M )ɧpk!4{0.PGʧ@Ukrȼ8A "IP`F>  .F~ +Z7R_tcF2gƓ5.*WHڽg,^I䭆,X5iuȒE3vJT/R"#'~Xc{x8sym+F K!8%m]`b[i =g^<4JPvg ]\nq(: zmQՉMCX=myiPB7{&/SBr.7J-w[)9\]Im.ss%K3l:ɥn]D4~8?OwUOb&и$J pxMR8yW 2KX\;o!Cz<:5K4s<ۇ0I?. 8. 2u/hҡauU?bX= ͬ#Q*֡$؂*!.yH|{Vz7@s Ƀm ?ۑWa-v'\}j{v\mt dIz|8WQo(Xr`]1_\.Na[!c C/rp E/*'n}\8tԓDƹux$r:4߫qAii-T/<4eg"u#]6KfFqhhFu} 5pWrjCvy{L8,DPO}Gu}/{kcpO,%m@l#P|`8&b*vE?&)qx^CxQc\Dq/M2ޞ`Sи|ݙg>e'V;F9 qC`Nb YE]V=Dۥj0ig Jǚӵefa)x iyG=:D:}N_XgscɦJߣCw$Y16Lۄ2v;:aؾ(L}"Tm>jyNl7pt-$V:]E>L7U`LT]3%J0sn; t߬6#5gLtɭt֫}Xe_(8Lnwu۵eVg! ݕs;]tT u>4x?VIQxZ2W-^ycW;<~۝R(1^.lyȰu{z!Vh dvBh}Gk"]A];zUL!xlmC7.ZݓK<=G ^쳏,YD+ʳe6S>W6A9*4dG52t*u,i]..ZWj tZkcXjLzW 4OʘdT \_)r'c?'[~jg3B;*V(P*k\j-Qa$b.=)j~O%ΰuHt H;.18<.=&8K&{ܮ / ʹrVzmB^/.zX.Z25=;Cy=PK\J/ R[/smime/SignedValidRequireExplicitPolicyTest4.emlUT ҆?;7AUxY[Ȗ~?S-3g;rxC@@ 3w١*'7yS~AC rM͓z!(9Bois_.kS}~:N?ĺ.I4|~q2_̤ׄ2Nj o,ja|/(|A~Hw`ğ_k/(G ~en~}>-mħ*ϏO}I)_aǞ_滆uN:jN?>m]}0QV2~KE$7# 1ݦivh`mJ+4S>fy14MLϵKXEV F9L21F˜-r|l_maFK =5}}# V֧-D-#\̹h`h4䘦¦*\\\ QmUTPuX*SiU'|*\ 4r&H }|YG-UKE3a0T>CCO*M/36>^"Q*`e`Rcmrcu\ϨrFqq 06? O[o'1X ^ILcI&4pVyɚlS*dk*zy=X-qkcpCg^ 'v j7G̹@ֶSɀM)>2^'Xg4mCZ ^J615N ݺŠgCՋP >{'X*\ 8W؟!Oke+tiƆRáMԥ䟓U0)m9CXMc@*=s0T˾< O0U I,PoY ulNo9.=f: i9i,%"As=bwwX4 A-¬K1֪՚ $DVLnfdpq興S |C-HThTZtY~D5яZ<;J3JOgʎi < Acx~r|Ğ,nDFj8zB86}?D@:oҵU79ZfT ;lY5V )>BFpMOrc%btU6Mx @.RSwUfŲ~/\\)QјJvJn$%omBU662*2{qy,HKT;vB@rư£̴IkB_q|xXbh&fiMdGI[w|bv]F/A!,!\T|7I34 d ]ۑz/.F\uO]8'vȯG?|ɣWc T@)Z@xO/gV N\H ɽpΉ!$lR9a朱qԵXT!{}Fcs.㵈N*EtrVS-=P+x 5 tF*VڄsL 9py^%:J5*ؾ1ņTy"ʻ[.TNi7O-o:]IH|21:7u&y.NkqriKmUloT>8Gl j5ź9fNE6STfW4](* :E,PekrAb7F%A41*f|E7F,]#OW4o|~'Nx7t;#xC,В~(Fn~GuhJޑPGMe9YEY0 ~s2ŜmBT՝GC3R$c&1)P&Ȕ.hu P+R{^Fdl[2FMWzso~*bCDЇ;*.'R_ tO ^>rKGCX|_b|2*hZ+ߏTlF ~IvFаyrrOgPjwEʽMg:Zj[|Dř uk.ůqEQɁ{I\=DKPOKVP9=o;vU 7Q|#⼇F0ei~vZQsUVQGtʿq9c|n6%M~͓imH]vC^'nUZrѢ`)I(*S]l'Gnzءz@aWC -g${d.Cr dv`ʱu&k޴ #P˅--X0Սswn92k14 [fݭ/nrYV@7k2:m@p˓| S|RMp.5ܷs{q,\=EA*Пa?i(^kA;B3M<+ eI5Z7gG9+̪7:yVeG˻Sw!sOTZui]&TH]Y-74 ]/KM:ȑZ꠻&{;iػ  `lPȠท9%,Mӹ7L~HYcRk޷*_.$ġ3.Uf0[o\T8!zFd2-;IFMjOv&fr] CA$9 c`SC޲M?h/)`C5~g%ǡsž7pL1%1+cflŻe3ؒ1ai˅]g/΍C<[̡t?4{9lpC/ j" 11Y.byh: @dT8S oH7fNisa{PVԕfw\ θ _#ꘜq{oo)%/(ar\&͹B)SI؏/WqZk*'ݏƋh_3Z]/bZ8gmC<@`.0[3JEa΄]dNȫ ]`Dwclc^F!2pPN \NnK)I7G~èæa1cΛ$1mH3jTTS~19g6 rsGOZ=g}Ǚ~K7g g4h0@~4v g GzJ~q굿~~uCEbYEGSpnDj89(ZT{d2teVa9o [Kvc\Y."#x?q%nXݎQcls;1׫|p[Rv%ê4\ bJϛ1=:yE|}:5#YC6i"$N[-Dc[tPE[sWam\rCFm=reyC'+!ĬzerPHǁpڸ.œh\%VL*Lj4+Ϩ;ثֹR%oPK\J/ 8smime/SignedValidRFC3280MandatoryAttributeTypesTest7.emlUT >҆?;7AUxWٲH}n#sqSɬ&  o3Ƞ(_ߩn՝VDEI;Z;A2̠i|PH'M%$(_0ST#I~ɖM{NM`CNSNW5 &q]0j/ZCyM EN^7$=wz&S&[N}\.3>(qɼvV$Eˤ}ux$* 2t l{./5NنAƗ^'e>q6X%jUU/.I~m[meSy˲E:`d4\X1ea+ ڻڙRz9uMȚűW*Qot{.GΩΝ-H wNa< 3̫5[giQ@[ENrjV9g=։O1"onafH̸|Y|Er]3Yp=~ /@*D@<k.bBPojؿ3y᜔g; LWBJr/Ş 2xtzZ'\4y?b<jmY[.؉*5g:^[S{vy!b`!N-;ǁG,D*p*m3x<W, Y܀J`.&)whj]QNw +ߴkoǣǞq[Nuz 9HY wLsi@bNhњJ6vyK4"ǃVg۩BUFZrnV;$@ brp:ܫ];Q mUrC]4 A򵛋hg͢6aYQzm`2p<!j^xK##1zS`t,u<$zU@x .]ANUT{[)KVfR6# b84^q@DzvW8F)t6}" l>xi 7uU^]01LA@De~Og[fo:;[Grk#F F 9ZMtqa.8g"cCW댪ʐ%Cr >R AyՌhj[g꩛9W\Yշ>1>:Ea *լJ |x ?>H5,~mv5ՌHʟmP% ^>*֒m'/z :q%xϛ~҆zV"u8;Y Y7>%8ewWvn:\,/52㑤V |4M9EC/t$/-CŻF[`on>|8 B֝ 5koXV2'AD;\w3c,6,E,'>pЊj%D Too$hE ; ǏN1|:Bϡxn5]NE(,G : [mupnA.~M͒y =XðEh[gM{G,}80YK|s!H<`U^B@8m}{\֚4։}%[tԦ=%>Blݳ1k#'NUwr:kUq!bzHJ6I4lgm&Toޝ,UJ E41Zn҅p@{aiԬ.WS0y!o,Åp v_ʺǃӕgv3ؾ<Gw{H,$ A[bg@-֠uԉFiǹ Tr#Oehw1m},fħi_@wQuuUdn[ErY4u3|ۥ:!⽒p~l9 `>}VjAV=g׸lJVvfFwb:ڍ2lޚ]Wé1u+HQvhS&3+5T},`}9DYP˝#=*3`yah[ okvEبf! u63Z{,"ϑv =[˴`=gP[نe,96V٠N)tFEzf3z40Rs/TA/^a",)Byb>w;&@ڴOI*.b:YX{yiY^*k,y P vJhS2Zӎ[\Vn)7ݲÆOgl(C/OM[1X(vYcJ܊n#acoDYx%VE1TZ%6Ӄ>f@|qw̰Üo} n.>8 _r(~ Uw#.$V33Cn`3f7a :C U7Nj  _ȩb.gfYmw)(vUW,[7NX{6;zĉǯw\;^>AY/ m3r’UrNK,xɅΓt\ۅ-g1 OUx7%Q\'@ծâm-VRAm;TPBb𛎚 =C&Z?!jpBG-C 絺=s rv?n nog5kb-^LJٺZȕ8Ӟ)y*b6نsq^i˭vϭmETK7^sc@!dZez9f͚T-,~79yR\%W-CW[ߛ~j齉ݛlNto)|a-t YP]M*zx5lG}6x΍+%T,vidU1,Jsv$<9=tӴei$tEW!>/Y c\(c.lt8j73%TkZ{*4_@$Te$αz*Ԛ;ݱQPF>bP+-z?LRc&QS?vDwѰ;HXE7y0ͣkѷHz Z5C:R6]^֕tT~i; ūamOfo[/ݬU$[!19B:J&pPKnȠfd9{|}#;K.8&^ˍ3XC6K>%9<97_PK\J/Д 0smime/SignedValidRFC822nameConstraintsTest21.emlUT (҆?;7AUxWٲF}"ޙn]'\(qބ$]-_?מvw_{"PPJRs2A2XAE6#ӉQ8ڠinkװxL'B]do3ߣH-s GP^_kfL Er7 "oڍtq̽E$| RO'v63vF=#7|cٜt8/Pb{,gT8Ey,΂_f66qm_<#ukv_+8f V7.nʢWaݶu(̮qF#y/9zx P=g`$5"VLX~o _r-jkIiE" %i3E^>Gi\HuԒPK±҆'i j{BsxI34dMԣȡ;GN#˂P6 pf2 LqꟳN7&#ZaXt[*e fD8ifwgR7}KZSp*r7SS;G6|̑w _q,sN;µL K h!fb[ p- ovC JP%BdJ ͩ<  X{\s?Z#bI5Cń){gq>HZ#,"k/u[lak[f]\FkٜS:Vϩk̡XϏ h1ۭ \m#&,NF~; 5^϶MIHʃ\ ም3aY;_3.ۆd)7E>%4Xe -BxYsjCh$WZ%+%tj  .± O$hD!֕at b"pѩ&C]Ti!"`pw*#34==,+BgzMlO,w-.j+0%wF/1hZ6gRk( o9Tz1zEvsZvl+}e<*Owܺaʲ>bήS.XN''WU\UOj$ֿ䪎:Y}yOJトBpGNd^X- +[p&3${v ZҊN'%zV:YO8֑_###УʄƵo?y:4{-ptzJ.t6?q;P qid^Nm\ MogUo]⺮2sG4nēa}|xf}V}ouĦu?M\cUܲ鍜+W.I4TNR/ Čb N`Na 0z.*>.;@;V.I >Bx慃rAIJ"w6.v||o8pz^<ρ#)cE);ٮ|RlN5OE{'y=ofߍ4*>8츮+=E\GTc*(Ql8){ׇ{;42NqmwPym%wַޖSَAl}\BV ggׂ1׃ϩTos⹃xo7I0OYLh\r2\\ea'c8r8[rj4xB1 >_gɷ*ݼLbi^ zm)K ,:Μk흱~l*Mk]f/s5 cLhu1jɎ~ѧaYC[]bl&GG jpdx2XcY>1B8< 湿0_8A0^6- xzt{;5?ȜY _!ս+!_zP̆/kfէs ,nсW^ޥ^hwңfdIz-z,!7t\bgdvo/xww@xV*)O x: <u\|.IL7${I򲿨-'wmܷ-6p$ g%S L [y~PK\J/ɪhI 0smime/SignedValidRFC822nameConstraintsTest23.emlUT *҆?;7AUxWٲH}n#[t3I@DQxcPTDSOuӷ**JPvk9[Uǀcp;D%;ͿCD[(`~JGܪc`{Xȼ!j>Np⁡HsAAqnnAV6N=| 9|ܘ^טpO|{(lf pxcCC=ްпY .+*rٷ"+?˷RgIyA/?]fwnAYorUqV&0S&(/U5jMDiׅ5mo|-}D: Tƒ$)%@V& %XRs &ˑqK83*UG Uu i9F%%ZD.(&Nc<=w{~<7s)p'6c8sTt6`3a<;sISs4S_,ߋ:I׊&fU4 ؄"}6  N*mXrܪ9`;TV';O"8X=,6|֎J%B±FicvGG[;{-&5ۛ*ӕcwraKJo߯/0{jH?ŖZLu^*e'4q%XSpd^US Lj{@Tu$5LBݏE&?nB,Irwk爁.\5{޷q6=m*@uKeW3:yX&":4 $r[%.t.6 b̓d7ѕz^h+Q= 3 %PvMK,QQw-n+rokBbZKcs֭N8OO l_^99+X݈G .PֺK? @ >㑩 G(0twd92W*~}a!| AAmd3x= jOgֺ=ShNJqfSӬH E($gg.~{0\z4= 3އGńxR=(suiC-q!J;HQz^0L$dP 6V/&kz^Tc0a0Yň[Kt+zbbg3YCnɯҭ\m/XBi|asQ4Zjh~JgMyw,3Kx2QN7f: o=Nfs Gvx\uZ^e٧YAh^1Ƥ37KJqbL&gx45YU-L7h?v ZD$֡@\.=Q*gK[xfsԁ㛇&U9l%e%!6YcS2V<ԅ|w(G@H,a% D<׀k3 2Vx Y,pL :s]1lȽ{_z)Gv _"Cۀ<8+t4!\T'qDs@i M&'r[rwqFG5Rw.uJUv?1`!;8otFWοus/[m^,qV2{h1)]c>*\eeU?R),Yl>YXب n1?әg<*\K 0|ep&3y?ZYŤY,S+m3w{m+4*S,zɄ1EA&hxX|NG*͛*ZдmaS=?ޟ矙- zf~mj*("w/cQ j٥57iȳQjkB?~¶æK./_>MU |o_ 7۰ן7/ }fy4Y!Sm׸IٵNPضn~rA/RQñ|T85mk|ş=c2H.PBiu1ߍeR`Ysqʎ3(Qs Z߫Ӊ4K1.xY-9{$EXXg H=kH ص f ˶*^)-;^!Ή f#Նиvˍ A9pȂó֢JApp:= = ]Y*?@>z{G{wpC^|8v^AFEAH ֧TvoNIƘsU9ܜn [*~·_d8qamDRIdV'j"4Jc-%W+B>p{kU.?cMIh8X+H~@QvD{ٝ<`#X%#X-`@: P qs5hC}f~++/M,^/\sr= ,x7z99HJv:F\:R{{mdJ7f^cf \pov<7xЋkWxMAjj2]LYo\RAYE]"qd߲Q:)ЃDAɱ, Igc9Rzg)x#N`=gt"+Ts~WDd%f奤xF|#PY=UE`ճafIg &zܱ+,FzlO RL9vOs3_JGhk$i7P2.;_עwƶؑÅO=NCeA;=:1g׶ײc,Gq,%LMo[t!QUNbtwk3Nešy|>}c.в'[HL=N>O`/#w ooxoVC3;Vz`@4y"81뿟^1D/~z a07Mp+VszLxʋ@\閯lQ17egG1ޣI;?q800#?0s [Ҫ^/tvYD/"KXh=2lPXD)t 1R/ ?b<|lX!PXnap&C{O:۝L^CԦR7)`ʽfsAPkUwͭ䛀F䋬 Q$2Oּyd7Ƶcb^A W[Ky*oYalkb,xS6W(8_ϕr9nx74W1T+BD2`> [ x3{+="Q\ӯJxNb2x,-$C[KMfW՚qY8¿DŽ GV1'ѹ:'E&(79 Oi{L꤈Q1%dxbYV>H~:EYb6[:iʉmI_,b&म4 ^@1Oh0Ë́`61g&S@^/D+TUrLUר^|y~}|k/9-[4ߊ 'O"{PM,2&L NTs]y'8h :DxΒv_o(j{3Ҡ%=.<χu-F}R}T!,,,Ygoi,;_,UN=t -eRzgN+!dX,:F0om1k g^A/5>3h\E&' imP}I^&؃`Opu? pc$RwbkP1ɧ"}Ȁ^A]fό_em<ɱɊ_yG:_~"yR@*,e7IX,LG.31 U]wyrxn,gb&:(=ٯub:Kƣ!ޯ2zkx9ec+/.S3b|9 h)G$FMM *HV -k 7 XHuaqz ڈ3x1սw/RDZU!Hp*=]S܂ b+"IbD,|U$S"~ϯ,.} 2&zJ ieÊY\OČGil*:]5&PiqΥ5u1rQ0q*3ax/QP-@쬭 14JKV[vƒ42|UJ&ң<{IJtee84:{$$&غv`D}ay>xגE7N.Ձ+G_װG? .nnD*%d@ڻ)nKYW*;GG,do}J6V@=B6?v֘޼ Zú{z~meġ=\H'ޑy|ѹ*`@Ջ?pYHzd2VOXVuI*6⽲xW=Jʍެlgq. 5+vqdmTSix\<{$oA}-p1|5wH{_&IKO[LQ&OyzGO+jOx g~QFЫށ窵OqDof*_K~n-x|kbQǣϽξyk:ᩂJ,ZnKU0:EFީF{ 33-.ylo}m.[2~ [9OZK[|DŽbv  F[ܔKL*pV&gmK|"I'Q>HN>ZȦtøqr}.ډuNDGAbЫUUP[R4ő8(]G{:=Y?ɮ]s+kA'mڹOWJL='gI.f~uKqvJ>Y+&}v֔g,ю XcvLڟr=mR+.8q'ҳQTK|IrBrpԐMƵӹVG& /qPK\J/E! ~6smime/SignedValidSelfIssuedDNnameConstraintsTest19.emlUT (҆?;7AUxXiF |1n+:v/e^&?/-#Ϫ$mtW?]); G4_*ʾnaǭ~[M sy| CXYDUXWI V>eu8 eP{(g ?b=CӅ;(*Yal[ `t>_tb(G=lG"QX[Y;WS._Y],*-{S.kw{Ռ*XӘ~h:bTI iz@X *`{ koBE튘'IٴN9&'ɝ{^*Gm:i1d.2@/|Q_Kv"UZ3$R4uզUSJ\MqO93عwQ.=ƈI,i H_5O 'ɠj:bp[JCz_"cA[_r|[2=i.SkPMXՈp tq1ࢱ Fu, 'puLp|@n9hu߻kVS$sGmd벇k*? 45}y|L€9Bn{7iqK׮S@$+'w|]y &3xTz";wk~ ~QKP{O&[M̾>H f ;D1b*pH 9+3]Q+Q2ҸicWsJ)E9f{?$7p*cȗi,KnMab/vqjį Vwr~7R|Z`~dn@5;i918RYxoK@yfpj $ۧ- k_@#`e(_"+N'Ͷ$P1 &cBc0WiNK!o8:l&9FƛQRw*y6 ]^m!e4:$vBv[Qeca!-7XCGL-pX/2X 0dPc]]%gQk|_ms$'aKscjiYzvw>?GV+|kdօJiSYq~p{1j $9͂>"ʹհHǮS4\Bcg21Ȱb TDo@!֜'$CBG'\yxFvv߳Zn5m7>\%{'8cZ:4cT=Q%ȞRQhF"͍wjJ򇒈̃E&"+L'ear]<i*l2X $t|u="CG<`=lޗ?d`o'M ocyc1s1?hߩ4ȱ0ا?1bY糅 O!KplQwo'^N=NͭhVl\$Eås;5fQfX)jùxNU98e!A=-!ֱBp:F|ZgO츘cҔEUհ^Nq~g@Lj{kʒ[VX>ul|02 ܏03l(h>9~of>)uF[5i@64 7 ϰԨ}}RoC9hjM?,_;xobEmIE}+ |Yw x3yF?ӟO S, ?~8W?qmzb|շ$dA&vheE^'M|%iKU{}~QW=r\3 t, CdW"Qi@kei#HŠvW'.^S›o^M]k2wLoS,ZoU Gw>s۫cuS܆qobE>G;R-3QeS$Ylz>[]SϢBx݅;G+AD]21U.HpzxA./3|i<@BaP^!}fC_t|oܻFU}HPdX<*y5SΩڲQ/W/aJRtٴԸuJnVfr[Y J#fxoL{;h\- 2tx-:Nh=HlGNU;N YcB\.V + 9H߽R$/g-pjRRg^TNJ ~P3oazRAs\gր)X~wޱ !aWЏd(WH7̸#Lf/^R.ǒyIńXw0~FKEټ^|]^S.iɂEl"a@L$u'&q\Ҫ|%DH6 QTv1(„ |Q弓gjwQ'4-Tb4@VwΠ# #QFmpZn'3I B5ULU|'E ? Gt$ W&A`wY JIp[mDR3{ܡ;9NUncl{p!%\-sku=(7v`;^Z[2mF{eLpƖ$;ُgW{ p 7ǧ~T1ߝUhYT[xFf[)=n>?q"?c<Śb) k)mT:wYTU 'U-X LE!aߜFJY0&K> g@:}n]ʊ!=ݯ[^:8>gmbUgQjubv#Ww.lqE[+_'Y`}Am]"1rZ\è)zla^t@!嫺PZ88HwŔ0&tO>/Eu4_8sTH~.VM!R–\h|:ph4'r:Bwo[' Hkq`& |ۼ 4}?z垧ʶlᘜc8#gX,˺a^A~>ۭ[}҅ ~@\WV,,W~U3N'ؗ:{x8&|ND] 8  /Cv>ÙI5w;&m~5C_s;l'R٭ yxLN?rRlnZ.z!% ‡YZVjU"4<.cim_LnȏfAҠn.p9W\EpXR8AXeu\(}AxEcr< Q7yF#}hHMX/0']Œa`5pSM7aS?>P0oZAC+LIw;L+Y.{i'{/L 6K_K. ޱ|:^vx3` 6*ERm`?-lO>_'^o9!2?e^UKQ-ʩS~G>pruyϵTS)Og_ѓ= ))c #۫ݙ2n'fǧxhbF%*|y|ms6X\ ץGДZ#Y)_mޟX$'egb+$NQ&OM-&wN!˛:<lpD!_U 虿Sm5`AwW9[]Q^RMZ }LJBp4;!,#C7TvHѩBu1˫birICmmz]>G-s{2 NڱkG8ǘiE@&XTcD;'h tDspOM _7a A+@@b`ʰy@ z~R%|JPUZ [mf#A{Mo "c˦Zfiz`-J@*$ZݓIULDu7p_;wL݊qG]@xϨ-Gz8)Qe#&5W+m1<{8B=ۓvf@;\è9+k սbpiӲ.f񥉂JO]5]zM[\> )/mTQ%Fߢb{YQv m/i~ځb:YL/&a\(QzqAb?ccr?M/r 5/>n?/S<szѠyG_:6(zr_Cߪm~WרAEڈM۪l5^yAC/4R$8k^./RTL ma{tl5l0ct)*\`0~g~u Cބnom쮓$(,d*XSݑV@/l}rb^..=,w׻1g(*wV5u0+Y],䲶z菲\L3À q,V%Pg|k79`Aw`G' c(܀KǪM\.8[kPrQ .kkˍzI<%ZP L:(&UQe-\O6Ff&lSAO.g85[.B.yvs3(4 Ʊ}r|[drq۩r" WcԂ!8zfT2ttZNם.MfBW,]`&P+:]b D, v2}:CfR4d jWԀl`@ē-_Uo*,p}TT1 KVש+#l%[ F @tCȂ3p 6Dr|O`+6\zܸ_Wk50Ys.cb{DQ9Tf l '1'(4~(MV@<б  N; Gea }ϣӐbC4=U+hNp.඘㥹Xb)mf=EP b^ /oǂ|\O0H5@d=wx*a s }=NnH3q7ڙn.OM&;n!m8,r]Rd5DV14&Hj/ښPT_n]ȃUNY'5\d\;JDŽ m嚌 %2nqڳu8-_w9']np0nOWs@N1ALUaAe9B15Ly7۳i'.L o^L {lp5-zldu{FysQgFwE #a:PĄqjc;ڶ4c9ѧj -Xx'#攷O8I46"j}?_0_O] #6Et]ITʦP;? ?;w?A݉ڏKTM6ĥÇ| }KrG35UQa،a=Qw}V۳>/aʼrC/7VvFU]C\4cd9XN?'7鶃OBO˧b;~-a=S,w_-SVK5] 8 ܼ4hB{׵PǚCIGS:pfzkلqſ<}5 ~焷\7=7\TtbJ&qG,^0%#-IPzHgE |;䲠ne'p=>|؅#D#xy,o=3>K.?!*g єdӱueD4'Mbt`̧p%*ʳSԖ?Mu j7ܛuXzEf{R+8kڡ#/2{s-nrq`WG}!^2 St N8-AN[)KFXO3T[Ӎ @^6TT;f8ŊҩҕSZyn[e{/g[  ~(C~aan,U %-Enp`v+{_nac$9pdG򘝺=K(E]ؗB'YDNiltF(r, ܐB͝JO1DMġv'~r<a}uۢ{EMɏ *<2T<7UpvFWd`~sL 6v~m7td@~yC9Q Oj|w5]Kc:ΛӍ@M.^X6ڭ?M?]?bK*{NTΩGd"+"ѻwٞ{VF}]٨F@D쐆tc(0g!lta_D7 ׾IZۗb{9 aϾ+MԿR>ԩk1fMmYDFmٹΛI\EV\̓,+PE[D#j6]x?BbF);rz]H4"zz!#g| N0<GĈSd-@cj*5ejEP5\ou0Wu 6cﮈ*8zsh· O3=5 *9/>_,)Ɨ[3bضXgSĤvϥ*+^X&4G>eX#o5i,:DS( mxR˲ʘCFKQ9Bl;n¯vF^U"hlyh>̞Y4:B2µ+n(/, Z0i w&?w7qow &k*(D9>5~Z.,T4ߨj<6Cۅ1TsX5Oc|2kl #f?)H R @,t0Czxy'fzzdLp2E=I.+ryFSl5a#Lw$cKǹninHs0!."wfJ(NyMR?z莒ucJ\ I%i! ~^.5D4X`sV(O<FR3I<rY.&]U/Jݱ7Y2I2_uxAGD .ƖbG F{ !YxIMPH:-IٰIH"WMWMhH)~4=z@/xȌgo0 &K\K̨y(f4b"هdMF4{5؄\?337emcow %\(lM+į& i/'119D/e`ʉΓ}6Sc0^sT)Ae7bXVA2Ѝg~w.-wXtL N%ƽ)cwl>9\N{7y51` OK B+xL+p>nrp<i&Q UG9K qFO -[OE, f"DdxC3y1m 򝝁<)-gұC3G;.ICd^+UyNљU~j# \%̽f@^1*C8 ~3#6cNnzY;I{#)a˷ pd^Ϳ2 9>#Sp:'= Ӛ]X_܊Ԓm&scԱMg$#tՇ;T(_/ NqSeh{lPXơdfc=-- r\Kۢz=B7ZW^_t.c2mz%]_RgC2'3WJ'싊BW:*[Nµ@RDƞr,&+˟W@'7C$εa Zo!\2jۋj'OO|/|~PY G> >Ǧ}=lI187 Ϟ?}uSyFdn6pGky].46O[q9$#QnA-+Τt rq.:a\dh9ѷMGLe Ƨnv&BXun}-^) U@=Ba[z;H~Y? nTS҃.svCcrDNOr+pR`fM"e|:> 0h^ *x0[zoTG"`.ZeHXʏ|Ġ e zވ%$ rj "[w1^OL9%Jcj;<(\LE肸QY~bpm%۞Ѩ|/;J$]f ];}:z񚐬灗 7Ek8_wyy?ڻBY#J픖ĉ~h >UVdV>z{&sua9Ѣz{z|XV/<*$ YG;UNہƦ D 2A Vֈ-4i|,a@'AL${?$aB&jwqaio~Gn 'B/b䃕7`ݻ7~#όEط]BKLF70[ꦬe͕5~߭YԶiJ5_*Fr TfuYݦ`*-觃,͔p*L[HM[R|}l̠7 ۹󸩵9ɱ9W֢2Q_>V57*ЗrBu/ |aB˓;`~ʼTy2= `bL=4u]?5Rw*g_bzEr1$0@wݕQ=}KXqVuġ1[\ᘔ\&kUr{s gN.q 1W5~ⴿ֖J z߮RHJa}ZSJӥn 9zzo4U#~(]G̍I*KkWBC^Ld< z;.ЩzǪî1V:RU ^$IvkcV/95]'Oo$!Ɏ6 'l>3ϋ& :]vAt5 /ڨ l1- paDܶ(\^QVe5^Zv 7֋O2yı׋7A|ơ'|^M-A 0\g}K }-3dC2:9\YR~^:mQ):oW?T+k|ˠ 26ڮ¥m]iNu^h5ͣo^PU ʾ3ЀZ#Mew t~`M 1p1dTKCSzgKy18uz_j.$A!Aw.6pz8LOlRأje)) "8TygޮLXq@_ؙ,y@jɅ(i>QD\q,(2F*pg6pXPo}= { ż-ANd|rl Zr/%'o$Z5mok"+5d_lO] 9%D /BS83ȷ쾲<|bnL9{ǘW807,v36vy8>e  5 J8WuQZ#);Mp`ĖefYhYQHgӗF6M[&awhQmanFZF4x}>SImҚVfLςVPzUvc*`-R]1p[D<ܽ)_WFT}`Xv@abJu*gNUyf(E2L2sA/+@_; {>~?b@3˂JXJ*-]5zUHZln%#[J[h}w쩇~q]vLt[ (v>#n>98-M,;ʕ:Ҹu9{ Tll=&myz8"Ɨh^t]i V/ںhi3i>Ӷ% mݻSeC'v<䏐#n?omo~gqhЇwq-~|ﲶ%1wFJ;vhJT- !}!UHґs{\_x] |74ʳ?8 -mQ +bcOs_ٿGCz7}͞88_r;/qi tL;ؗL4t.8kS蠩@G<՗"xrYxG? "Ų30=i4Zy:Wg vl/A=lvaI;jXJrabptӢPlW8CnYi2i|y"N̂!D9[KH)<؝Cwg+ 8=|x&sk{w|GNZZ7Xfn|و8i/pN ]ʲTŶzfQk|E:V+Eڡ'()lY2mpeOr26yTONAv-[2W$Z25'Z$iŎ]3Mk-p\crN<)jֶ,$%M @o~kUM\_O{w{ݛ2X̻V.1T-˛=1oG'~\Mlcܼ Cwms1rigɓQ?B(K@swѐ}y-y0PT5An-/=r `]m &ކ | ڒ{ynz& g!huvr/1bVoԳYGҽj+""E81cRw+=|@o;v Cァ/zIFzM[}(&xgz`9fš<_'zv 4#',Yρ e{B/HN8fOIv~iYƦKL8P6ZUhڬz^tU#V2'1HsϬ)24T9@>n=_|ݳ>'Rzځ(`?~=RÂ݄KuA A 2F{x!B,{9lii;0}lN ^l=6d-nO GBϡP6_&IFhӲ#rgqO~(-(oC`N|k8[uf-=j{٠2PNZ!ӫ/[PK\J/Db6smime/SignedValidSelfIssuedpathLenConstraintTest17.emlUT ҆?;7AUxgH_|~"S2țw2 o@ }+zwl\EE2ϬVD}6_ߐj?\Oqfptsoi{_.k[|OMr~gyS<||q*O^Su 피tɧn~y3X[.S߇||G G7"/Z<`G/+,ztp~usquWCק_ۇ|H!}&ߺ]km7Ǘ(O[)Lwm[Cg5W>_(C=V-3,fK:;Ծ2BM_ΧZAac[5F5Xm\}cY7j0hcAcRT3;&6Hn1v|,Cwh9BUhCOII;§iUMT;ȣUY7菲\#c M HcsoX3RB;2Tu(ZоH]5Ίa3m7Μj(doT(8.sr-(I_(9̆ _3'!t>AOğVXGe .ω ep?Ťݢf*yrD.Q܉"K:Y  /:w7sXwzo/:)M_AZrFSᖚVц1ߓ(447xܷ\L#WG> UuoB)#Oʚ6IjӭY?hbwB\u} ~|?[L T׊3"RPT:r-Wl>zɶI].uFQ>˩\1*rܭFkd H֣΂Qx}_.,4<]Ӽ 9CȦO.)T R:k$`t*8\8Kgr߷Ġ}2WփH5!27\if&)sQHE0{k}Nۓՙ[Y'AOQlz gtX GNZ6;`)fr|a\S?ǎK/ti3i[.F}h-޹yqVaSa_!?aW[.~y,Joz>W$BVsRs/E${@j`)6aZ {2EٛxK?bd?Ÿ?郞_~J̐w^?A4 7­1읬u{Bvp?ԄPꔵ%,n{uzeW%f;F8i_v[`mi&*?ypZqk٩e>;n,"劲06w]+hX?Dqu&$7Kk>j1s\:b'}Pm P7jĤ ̾DZ@RMŵ+Yy :*l^q%%rp-e=PlTȯՉy1 uh>2  v{ G nLartj=FvuODk{Z{;{/},ߪ^P> `MU)rj`z*RdNd*n.TLL=Z9Dz (yEލ((Zk8~;'>}l0&J ka`[&؀<ƴ9[7F"9dT.exÝ[}fmiY#6-hoA)zU/V! jJ/mP*98V%Lk\H#>qdҷZwf0NG1iKU F:<Fs FtbmN5Vx{4Ը۸HY,9dffE8TC}qCkh614~[-=';3k4ߨn&}'&8*HM]w:\~ ~kx^]5xv.0߾ӻПzzz=}9x1HOϏ:xsɒ]U56jߎA43Vi(*NNgE .l;~Xs1Q&LRFe9[f^ dl'M] TFL ]ѱ>nGb|ˬH%S Ԝs?Ti|ʶÖrKڲ!V;sl[u%:}]jlg [sYp5ٺ ywvėS+DD9O;qKݴ*R7c2Y,ZCZ8~=P,@ R}aO@Syßٓ+TУ4Ԭ~|a493fxdS@͉1r7#vnI!I I fJG+!uHa]:MaontgxT+t+M$[cipb?ܦ*ݲIuPnGLzJ5yׁU7/ (L^q쿮paVYs`@~[q]l|˖%x}L3\%35Q8"oWZO:ebnj6t5ZFAVaQ٧n<(s-.dy xTj08~[ߓ=^7vmT){O}\7HPK\J/'n 9smime/SignedValidSelfIssuedrequireExplicitPolicyTest6.emlUT ҆?;7AUxْHGfzל eMu; X&<2\C$C8[Y;D4^ġSWH5[̵&˅[0{8=k[*)8Ej%SVy. g[8 /̻y0z~hЊ@e qʄ5WðP3g 9 L$4ˀcلҗ jryYrV;KWaCJ3c>6{kv3TkgsF$mY:%Zd=$iql?rS cPk-kk`cykFlCb^Bt`@8T\.aʙ#r>զ7=oZ}T eqߕ {{ga|HϴeEB|ؾGBa>w\]=_ݵh=؃5f9w/Ь^[*z0St|+~zv` Mx%ڷDvBRNIǤS[?nmRz6WTRX>Z^oEh>~-M}BYN fj 0|?֘VO2=»lbRفd8pFm¤Vq' x bBQw )lDlg>;:M]Ҫ$Č2ɃR"83)" DZja1;(kR iU;`LL){j~Q #q+%I*SܩW75ljk^y = aaeꁳ:+\:ߙ~ܩ38Y`mPg~ g2*p{dUfypv4哶Lӣ9j]'%zOVLmU\'$W%Ұ x`+`pгwAlWj`"Ey(~*:̋⏘I2` ̀A0  UP90T~ 1 _`|D!V_HЪ~]rKX/E4)q,ݽcgU"}=}Ij|~.7Ј59s jW#8ibVt܂v큲 9WtC_Aa^\|QfD@A2*','2l%]Yט ߾͠,@q x?IP Ү-b"X̵Q@!% lFܱ_! /et!V1_HۨONffatd bOeA{.i7s8xe؀`c3hv)#qW+ѻ{PwmOjo%1T+ړA!MbD5B܊ESʘ.QnkT}Sy#:gY,ںg-ܟwdUTBE0K+.hce tu¶ƵBop;w!闋uv캦aLRluU3Ǭ>if!5y ߕh?;JpQFtle10S/ vDrǫ5PWwB'RсUg$CmQQf3=N_ h$IR&6a}fп淚JT=Er?=VBh﯒qrLbC2V]ՊYtv'mxDxfqygUƤg.ƖF{v19:u3QPF;@IyNwzW$roX,+lڴ.̨.0HoiXu¶ ¦K4Oqg\S_mX]O? Ûנ 3^u]qq@a|&m?"ד"8u5.|q Ԃ RX豘ngJ[/eZ?/ۗM*~z|?WnxWQ|aUu{mY{ MwYD?/?}=eQuH>P5;40& Tv lXZTPJ+J,\繛C&IP)ŕ!nNLLt|dkܽ=zzMܻS (,pFjϖ\+fEV.DPJGzAUq,d5D\Q] A *e0Yȴe#ƊAmgjwQÍRQa4ʚ4~>%B(20Z6TBa>Fߏ^2j;;eN'Țſ3-Ž9$x@lHR)}ףw5=?ե<PS2N%͞C`!9 Y"f[3`.meJl(l~ٱ`3i=h!(ܔ2ӎO-bi 3o7^uH]]K$ں o+e{< 2߳X@0SD28v;mLMN|&; ?6p/Thx ! mICWE e~uѧwMVEFrAstjVFݕ"=dpԲݢ\50פrHwƠ梼]h\ U]ib|wF%ٰ}r*IyL򑞀1@aV2]ڻHFк[i%(&+7㵟0AJްr+o@%bGAO$q(u5Ʈ-hn7pHwJ4XW+#z99Ta د}t 8`u/,ʀl |9Wv|BynNG vs/- cZk5|vGĝ Nϡv4Rx:5N]ܪg^:~`"sޜ46nQ(AIkP1ݸvSʬl &OwgDv-9T9k3CW鞖0 JMWu%@HvE[Q+1kuN+FoƆo9ΑMg~s".e!|5{F"}Vo `h"ޫj&f?2!s>\]vM גuR~O;4h{?l)׻ȝ;nX{Oq+Hr+a-mVc˜>[+g84LP=+I9?k;$|;KhQX ` Pm߉i09mҺM+ex'X.VͦDnM=.=Fru0v󋋨h A3UE3GtEp1 v&\1ᬨk1 xNFBlfKǡ?[k#+wy"WoMx sGf&=EqlJD%E fB61X 0װ~kNaJ\.7ݮWL EIgyAywlxt/rWY6GxAmQhb:. E)k<3ܒ.2sjѮ8%EF֔ EwA[z{çIJgﺾG书}t+%IKgDagx6JP0 dP-n(^*8C?D5& ђ ͒g(xtI芍l$cPl[m>!?bN/iI~㿍PK\J/J~9$smime/SignedValidSignaturesTest1.emlUT ц?;7AUxWY}UI0oT$[2xǼx _7tuOfXBܒt9 V1D&ʏctNw5m>5V&*~ʢ9~#3Kߢfdxn8QqE?F`'zN8edhyK>.hGV+[E>F~*YhUq8PZOY{|2Wۙl'| 1+p[۹{BK+rV+Mʍ?L{.GOS\T˃yNA$PT$WV0L}eGd٠%hE`%ƚAe 1z3Twfc9dGeDՉ]Epz-aYvb5+xeEPGQ*?> ]znW%4L(kw/٣ Ac%/* WVb8{|u,l]m6bޱC`E;ZwdT+brgEkO^;L6_,椀x[+SNL[{xr,WLdR٩v)w(XUbۇxgN3N>! \ܵ@k7\ȊЊlaL笈>")&B8 +CKsƉI$=l _(ݗP(#@T$Bi8X!0 TH 9sƵZ}z ǵq~+rh(aRuqrgHVo0V'uaW|Txe883޵ߓ$0/[#|ώލU}_DLi{Xwc2N2ÓCU߆)G])yR7.¯VC(kݏm鱫*Z#dqM˭hK OQ&i6MJ%OV&Omm8(51Ւ[:ʥd{3GO}JA1= }r6òʨj_sŰd)kdreq̓kvXt> cŴ Gm">L׵G _[2O[g^p[kyb>ml掠 vWwqNA{w\ѡJmmfܖ6ƉD!+l~[yMغޖ*wOTO6}[E PK\J/QDIQ @smime/SignedValidUnknownNotCriticalCertificateExtensionTest1.emlUT >҆?;7AUxUٲH}n#O+㩮d5QPpގ0ΕZk$~IfuE1Ĭ&kT]vQt9Ӊ&U4bKu_YLYU^}EuGM֑ԂġK1(1 J6ɧ"|Q9~]oӉ@}QRbhuK0_5g|鄯+}+%jvͣvYfeվnpğqM'^]W_jI)VQg M)B^6 .ҒYHHZ$_xzsh` -#K%$^ۢDz=M5c4"kĮAvBvA΂>st`w䁳༲VB39 [Tai>kI=tr3yܬcXD*Sx`{E j@.axF|Ī AmN'| k 5%ՎHz[#`E=Hv)OEdӉĞo܏9(z0}3zðeݘ{OvQ $"wsdSģRT $C"+3AaH{]xW]Gh#BvǼ},.yJ=#U8t "^ @o>%2 xRGͯCQ?ky6g noĂw`6x`ry:\9S : 87Ty]C" 6 tǴ_0.. +=VBz\*!lY}LNLg وxҳeMXqEau4e$3b?&!K  Hz&7'j]%o-<43'?}c˝jp/,K}ң a_{Wh8NhᵷU L |U(ޕ္}lr?gsd_^Ǎ4)li~܏ħ5-w 4rZRg|8MPK\J/> V] -smime/SignedValidURInameConstraintsTest34.emlUT ,҆?;7AUxWY~U5B8NeF;0Ho g8N몔QQ*Z=޾$#=,>f˟(?f(H$*5QѳInI?ᲝNg矨/$<+fVK}kޭ#v?f3lIA3)j5[.?Vf9S3Nx*UUvĶҠ~˓9XB GS! - sńE5v8 % eлYzN8^SN68zNNr}✀g iwEut8:~n̂"ɍDXJHd2 LqN&cZ;p V,Jc:-WJ[C(fg+1vDY*fPXcBJN' ǯ.Q-5Wj uǪD;X{Oiisʳʡzїu;c(bK*ei/ DxCY!겿Tp,L#*[ JpI}Y-/pOI!ʯy0r"d゗pW#x G5.k[cSg^:oWB 1c/3^ھz](ݣB誯m|Nx&ŷ.4{@Asj/|GrX2bN"#{-;A¥, ,!ȟԧ6UB4o:?oӶEZXgIApۑĽ;!5]QBqw@V8U _* B,tsPT'nKp #Q B |s!e:bf]s-t:I=C¡#uG~^a ':qv<t" z`XiI}$/r?C7L3P~7Z̖=JUV~}rdN㭇l׻˫Ԭk5صИ qn׃zIQ^P)^Rf82 }Vs q_z*}nw mDSm'Cv$`%~.4.a'~PANxH`c⯜A8?<Ȧ/FaPxV' 77ϗBnӫ޺P?|8j\|[c:m_eio[)v>zr[p 'ݬ5@Yvnc-\wo&6SbJ>;gQ@x$u1*NoaD ,ئ:2 nbHK.@7Ubiu4GQ?1+c"_'45G(vB,1'S&ޓYφMSB"͚K-Y<^zbP~OͲ6s~ }L K_Mk.߅ >Ғ<9gETu3`o}5G:0"&gXy><0o"9=Ml;"Q [5egkR4*U?Rh(娝c>=#t;۹y\%f4z{G8x.Mb)t.L>cH>xV 4و46q h[;sA;x$:&o q\$A3m,bOp ?r0,:dU; re}Z?usӌۛ,cbAO5ӑoǁR}aSQI2Ut$[e6~Y,TNNԺMiڜ.-ݡw~Nn\ "SSfr9kCqNnsl1Om~91˺X ThZQFV.%Ś(^ݩ`g±42x#taUh jo܉j㑣l7.)a k4r3W T_1&\4 oFKSxIͯ)2ԍ톽&BVJgxW4^ΠͶUR ;ܨtҰdʜC֒'A򁫁z:Ty^dY:0iR̝0.RPvJHwDM.YO3noy׮R?٢Vjl*(b-+'h'"3 SNRowSel ak<?PK\J/ 9smime/SignedValidUTF8StringCaseInsensitiveMatchTest11.emlUT @҆?;7AUxWٲH}n#{eS̠QdPӷQ-fV(|rmF~&~I5YRNYϨM'b[o.&5̓9A37ffqA̔ ?e}vKf0tfa7$9|R?$M2tymIQ?M-ٜtUsd=l4M ghQTfe۬{|? UI)oUPͺ_T)i? UT8YsZ-Ye >6;eEEmuOվ" W*8ί9 w2GrE;{.~XEX#o(emP0GiTiE̓MDmȃIyC!#Cq:K籷Gm xָ¨I/6 KHdZS#N'qgpw "A=g sxrHsXP[ӉؿtyRQG-َаaxG>Us,Z h6*tr|Z߯sփz7p˛$ cBYCH/Dp1|h?PS+&,#8&lp< WF|Ns&m} !OEw.ZڛC0ak[7xJsϨJ4VXz:׼0Μ2d6y[ke{e*[QvFHCT#5i"^Vk U'dmOHGdEz=Jj1zxS| A~v rEX{:Sū QܔL>'fi^Q2Ę-] es>!@xp`L ty{s C`۷V=e=uh- ;n˴.6JYt8A6W@C[KǮnt6 #0 F>] }3DM>|r CFy5"*`s c: b ukMÜřP 9#6cApY]P*G`I4W8έS]pԑA=^P\#gAI7Z}[_c?z&>co|Q/=ң= ۔P7 e^_G}N'zyq5ލJ2C\^ sCEg^$S : ӄ9- !td|퓎LHǯx)6`?z<|7>Ep&5<> GZP{c/ ͪl.*Zk NꮽVbqy !ih4xJ iKh Ӧ8%MAΘ̩"W׼lǭΠS+a,C 4},t 9ۭPJX /h- +<K> ³˒TC~0N%ErscϬlbR;R Ũ<8[< etm'Ro}!4mIϮgUE?n n;vZn.ZNp-L׫~aEY&bNPK\J/ٓ'+0smime/SignedValidUTF8StringEncodedNamesTest9.emlUT @҆?;7AUxWٲH}n#sqS] &,1 "|}u0 Z;Afu>#ӉYnq5Y\utqۅY/_1|qŷ_ }fE,UɌ:q;3ݻm'ľAP$(rM_4?~3n$jFZ~ͦ:94oo\vVfe۬}}u6K8zm:[/Ͷ&ͯs|{> 6ެfmSYL0-9+.$Iwe@ ,0F{2&ab1B"BK-**Ţ:{1>&]iXEĒMxZ59kbo+aowwκ:dr˂`Ze O(y]CpYTAi_$,BJMu  I"5@2Գڷp<@H)bl=0Qmjs:lmiPV.kk8F# T뀒z1 UQYnLTGN!DZ3G4e9#/&u[z'qgmyjFeh'}W&.$Ƞl84D Zp\B/lڃhe'uclM:RaMdäR]>tu+{_N[R][<#*fAӏ=wU@#t2,Idb> YA~)zEkIf fx-o +0Ds 4M/, R휩Ň[{GpxUh4?k:@z6-i@O&|\zE8 0G)4F ,ӽ emR/]ďƣ#sъuKhQ]} w_iS -Á' eZ)'ǕeV-D=<ʫ]//ZH2SEBZN'c ζRd'$߸jB``H~`Ú2 Dz euTB"+=aƍmW,Y1=2s:QYB9Նy,";Fc2vL'Ƀ6I̭s!%BWϾ:Ga^\@5Dah1 c:x߶a Qd l hh@nQtpysOqt]1D/~*&r ހ| ,bH9٘W]*ނ>j~:̧{QmDBɉt!t=66nQ'1Q 1w6 "5ci¨dbllC)N|L"ot,Wq8g9W`?x68:OQ>*O94̬3g$Dj B-/gf#>gDes_ *KqRJF%|}mF<>0L?}Zx[E1z\t79P>|u K/n~̗|&cpFtrW-b9gyitَ?cɃ5oY~gZ.AIQ=Q[V 2ۆ+6+:LxQRJbP3+Rx bSKS", 3XSU9~G߾9oysiL%`$e"`)}n сDn_.x &ߎ8f <Db:`GQ7׻8,6Ӌk?`9"\EJI9?NI aRy/E*70/O}> PK$aJ/[~ɷ (smime/SignedInvalidDSASignatureTest6.emlUT ن?;7AUx[ӢH޻=" 7;)9r#5ʬH&.o'#6O}QkEHXtI'?"Z2Va|$ {^` t]&_TcO&vͮifH&!!?vb]H^5Aы/$ 9/aۖ\-[mTyo_nN%aL,~}a5vV}uwM_:jN?KXB޵M5 >jeCTMC+ҁl&8y)Hd޺˖zST@yPP266찪r*|E)y rR?1(/UEojSקڼ`FlSTA7;HE0&)"޻$2X;"+SC!d홒G0 dL$&1l@"6Cqц$:mP6:5XAry[*eTڠ**I ~ft uv.bPe}$2*{=mU&5w\'8w1 \31 F$^,wErߢuAʎXN|0KU$Mt[u:<``|%)ݵϋU\)5}AClZˎm^ xiHW)>޷~Tnk˶ˈ!eyS!aӑk>=>Ns {pg܄GzKND&$tv7KyKq ǶKzu@[RZR_`&=]]2{6wVQed_g}bsۧ~4 [xxmǥaCgݎ' zY^D=(Y~ ۫9b#~[{ST̍-y(;Y6.2ot`TNĂyQ )O olcjRezz!"ā OK7ZJ3 .dk}Rtt亂~yU`ݳ[ao(SSnNzV%<ھv-{Ĉ');Cx 8˓X-m DzhwF8`/ ;܊N:|D-&WY}BcM>8WL{4T(B&/Ѯac%d|DpL (S>i mVȷ' 2eCx+a`_Jkj/;;]i1`W@U 0cayJ0]25lud}yq Sզ=4նK w`)T܌8)@UČ(CqW,e7+6+U1OXj&G;ɘlRh×z]YI) f&pf'_,6ŷaٜW3R=kWȋ]52Ɣgu*g-ݾ!l4%{.HkvF99Н"hրrV~36+`U?{Oz1pik/ec\6tF'fO|!@H.7^2y4v|pSr5(8Z;_~!PK$aJ/Vpy 1smime/SignedValidDSAParameterInheritanceTest5.emlUT ن?;7AUxW۶X}+|DP]zZ,@"7Enʪys< X1"澘A$e1[Fz1/hMuLOc?nxtğ! NNA3:i ftlMi("4Zn̒^M?ߖ_$?1[nfgIҳ%?(z\$E;E۩tEu͗<ɃgK;$Q_|u~'f~)?NUNфA+Oc:M@ISMҾ鴭d}&YS ,Xbdzl)NgYv@zv50+DV`.Tnȥ֤mI<=`9 رV2GV#d"z&ʦa/xLnSeA*vQKWd^4OXm^6d@p4F0M}"r ˮOH`$`] ϺAz9Įe<\psp.l:Hz4N3mX9$᪃199seYz^=1i|XjDyNwI+ :A֘,a}|?盭5nU3@xxWjz[38 m[c 1ܾ鋝z=?eEos7W +GPDLKD ujq| BUzy+ak\ܚb.uNdWE2o\¶3%A)LPB-ۥlRRC;Vt}"k*=X_!QkkKyPX'%mp{QJDjQHʺiqBuQYu wɷ+0 }00ͯDܛ>~x\M|,1g$,v(ϲ V̌!"d3 MV"UemY=?IRR \ /NE>j BokIԵ¯ض;׽FpzSJ_AH5|x1p]rK`/gsݾ{L a%0hHW!)";)w) -(;o!P DU"h~Nqpѩ 0w4gR</%&ɅP5t?x񎖤ۜ "/ʉNsm{H![#X6M)" #L#c}߶|{+ ]CD>`).b0.lOTTݟkJ W1]VH.jdm+pYGX% ,r_yc_jbB5¨se<bRK- 1\]>Y+:7 7`lN?'3ĞډџٷAr!Zf%ڞ4\%.j*0HAȁ6*VBI[ipeA $)VhNKuA [Ey۟GyB֡ނLtъ)7s99JnœՍ^-RUfx:O6֌U9u[.o,?UTxKM.ָuME ^; ?xl^F0,em{s6q#6#sTEդi.Ym_fY0 IE"eWW/ M/I]GB<Sy4@y?Ԥ?OE,c3DDi8vGʳ*&Ruq qIz*:}ڃiߞE\9wG=n Xdp9/E#դ#nKt|%bQ[v5͢7H.1׻5u^7PXFn{{IS5lAE$ȏ&~B|\~irZW8?Y43dS/SɅ{$g;M3KxZ!o]Yt"~۪EvZ_p$^4dmCɓ4c4}OHEm޸.G"|́gvZmڲx"+yI̯( 3|;V%?hHR 7#;ѻ_:=9iuQeQ%6Q0-~oPK$aJ/} 'smime/SignedValidDSASignaturesTest4.emlUT ن?;7AUxiתF)|ˢ>I7* YU@O?$drO&9(ץ—SloU"[}ItoI%m%ޢp&>c&e<_I}Na~W7T]LڕŌmC|Q? %Y!7'$؟˂+7"+ 6+ 7f 㪲[~qz:+YGԲ_[j__v_ V?ʰXlEa٦PFU|+ Ճu޺ ]FYX<ê(*|U%{E&#Zlq\qFn*DޓG'!N⎍tTdBMgOIN+,XVղJ"]M*#a"&q{fdv Ǔ{FH$ ߴph,DTP!Ak (k{8SZp#`ǞraPx\ QV,_<ʴޜKECe{+ٺx"˖? :bhQM lwC^ /'NKqV䵤sg\q a"Ҧ5²t dmiEwEM旮_x@Q"v@?2QguՈQ (kmS2S?2CAyu)P-sX @Lo"#n^Pq$8-`7[%/B *  k )->wNz&wn+m$c]k:צdV[8pt< 5MB"7Hu6ƌW0qoIjBmM}n7n AD̶2` ֙ 祵 ч蓆AܵsPV{;﨣ɫ8,nir`1h0Ԏ<@?M_06lz 0Eb\1"^6Bӱ,t4齱4W^mD+ '۝ᬋf[ɬϯf>G B!hiN۝W-p5F4dz5 y BFOP6ڗϝ<MXxo˾A%|T% ^\]mrm^ǪoZKH:,01eԶC, ȥd`3oM3!C$Q[5-FòS3GCxpFeݡMWcf{7_ <8`@J@Xv7_,`8| vjoH; H 6n7QwswȫmqZ}.mOyt24̐iR54F9<;ҔĜ} <Ə;9u7{y+Ql]BhG䖢80LMϥUӹ=y[=Rw3\VK3aaد"pmҜ50 lM͞KtQuh—Ǥo'|b7 vg*: IŗqGnSO%*:lB[+!pX?3R8/?geØXkA}H}@Ct oRrC]= V 1 (x4K{u~_V{G9>X߅2\mAHrYf ѪҾA!mעмĺ4s Lj%W~ol a(Crm OAwي/e{eMdyzV{MÏoPKV"1QU &[ pkits.ldifUT 47A;7AUx]rHr}Wt_iMid3W8lr֯`7$ P]u*O6bg}N"dVUm}9 lvk 0=<;[$n]f[G (37[vvur4<$Cw`wƒ"Wtvz9}>KFAKT$I՛>;ش|~O643`w*';4_lٓ/'}=ܧ `!+Cd_}x.~Lt5 SAg 2M}.6@7cTɏXp\g, de?-gOo߾0.g'! yY2]=?އ{6O"&!ZO>w[3ї -|b3q49hw_乽 tMlUO$I9JSAqs%q1K ^6ns1إ| BsקA)[ַQOG5g+|KoaRs<"yRwTܓ9xS?pޫ:EqBX\GIX a◂gmQ>SeRo5-t;ݴt|9xzyq0ycskq/,8Yr/M\|5?]]\tgԜXf\%s5IC|qQ`iY͚&zPd!m]Bڐg/EΚE.hn6ESA6$۾GSqQvq#M,4fN}HL(Z Gq# yݸp.w`0P&9Ôbyvw{fa1xQbzTp*3Ti_%9IĊ<^" K'ˆIFi^).8V >BMk =l12}PAwts0pEyM㪏a[3V,s{EUiQ C5,9c 0yPW/=Cgwq}iY@qǩŐ [4j(>#^&6ыl )4Փ!@T&^GZS#M Ta֫)+l=Nf^MC$>).1C;ZBsDH‰'rBgYe i')7}RT\)1HI;7ܘ`FJ#8ÿ̾%g3azI6mGăC6=q>76@AvA=t7-N_ >4F-W$+;wb`f̴ GRg]ſ)[2Y|H!rήV0{ί;$WclnN|hcMUg ⬁]R?fLvR̢l|~s[Q? 4#hffxu1ڈEsz(LUz{I?pw{e>qY-atqǛo|zQe\|su~eV}XֱKj.{ rT홳S%!*Sl~ˆU|[hqFSTTBm4UMs'_D7.$kkE= w5؃#P6S]xe*unx62l"d[n8ʫu &aj7uח~K-(ZB2, c-0땅|IG!A>AlZgR41/9z—;MS֞d)AxEf~eP FP"6pvb]_m>+GGxBUwja71F5>/ @hˆ"m>A VHCeު4@i6Q4*'0OҪJKő +X#ഓ/0<5i6)CP䜌/ hUBF|;pVnH̚`i+!)یF:iAv0@04* cyAupF@[x'8l?K8Bs St„[{0Hז rUlu\4W֊^8Nil#ɏm3MbDB^+ )IJX^[RB,zXQ0f/L L0Hil,V|)bT$.0+h3˟z13[ ،fF&nI9n +P(y_0m_vۿGك^/wZMe6muW-ֶǭf+}SZPރ[pQr_o'OhCSGIL%p}4ut2ut#Lt,e<5W9qs]7X*c$\ Uꢶ 'dqH e[E\1枻n5IfН~L9ZijTv:W`R7Vʰ̌J(ryN( ȜR} ls:RF>+ qT(qtLwyV Jƕt+ESWI6tM4P ^k "6}PǠ+,)t,W+_>ɕMK0媉b]ŞS?xK?^QGWt*Hg*B[B0}0s*Djg:"p ' Lc^f3^҉xTt2q vL ӳV\"ΈF0 vL5g@̂-ݒ2;.ZFX*5t*6JBá ηcuQ1xa~~ 8t8t4ԭCdl#!1 9C_5 ,*JL}՜A50K_5Z!4Rc1餆gJp4 >g3A]fI:Qps3uU0g5Y9ĥW#,0g1Y2 ssaΒo,9KaU9K0g;YrsÜ%0g61b䷪Y*a%s_%㲙r/aMOTL+g͝{x9vCyauOI?yi q|mS&fa{]\AeXy5e9||^N6NΧ[vn9cZ,DĨ^.i—4{ſ #cBv@)jℐA $d5<]}ߓdVCRTCRBy˱k T?ġ% ~1PXCf(ҭQ.KvOYLq/AX+,ZVB{,X.Jm@@[A5t[1Bg4B+ Ճ0Uڐ fP!]ߺ `OD܅dMCR{̐^`Vd Xq$j -[cڷVnAm5kkUL|$V#w2JuT2O;{gMM,IH16zt9fXvXeN)όKK`K3*a9h*Czs{9dAi?~|,%P"* Vj]7aV\Oh!qe܎+mP+ӊePAi3 Vl#iŔV|~F}xaSo1=':Sezϻ?Z3j[.CpMO.)=*2%kBxZ#~4nTe39@ģ4 &\]-<zg/ICH0ULrU_k W+*:&-jA4בn8Piw{{`;>4qգq*1L`M͹ 0!﷐6!oZ0u"[<5 2O.i']RH!1%xs$LE65"jq Εaqk +m&-h>[9&|'3ܭFXDy E݆i 4F: >+9~teڴۄA(B X}@<=_՚,̎thMՌK4B 21 dzaWM Bm'ɳyCʵSawab+[gLn¶p"X[ven L,pt&PR)`z=,嚫E6<\_.\!7TH?jB%&LB Pղd(@/cLưę5l6nyt.9Xh[c'JdM\缼"y8*&yripedԞomj0NSan角Adm3_mB2m&8lֲ!R[P0Yp*O|`+)fʅU1N[q͇#SZ+ uфfPs j_v,5M"v!k[N.͔tܙRޯl [SdK!f!$_ݞw#ǨWr9bRͱēb9A>0Ḻ˵R@Hkj-&G(f+b6jt>Sa 3iG[؞"i1L޳MONa S'ɧ#ic6f! A{_o; .CF 󜐵|ӯ-]8k-}UɥQbcmK\Tުcee>(ZMXȊ{6j >О0:LEN*R2(a's{dRxt".d72;o0eT3 a7xlX‡ 2.Sq԰/X02 8˗NP'[ψ=f*+p;L4Z&eZ9ȰdޤDf&'45 i5~xZW~6Mm @ZEB(=&6OPEiyncB/N{=w\G_Q-ZL+ih_'-[ۯn0I۲T119joFqL!hڪ/h}K5~Ǡ8 cW8C2>Nƫמaxҕs=\3 ͸ #nks"\:hܸ8gOvK^;kg7/dEKɕi*)h 002*YjI /.,oɫӼIv $ Wޙ2v1J`#ńcى9{HQ-^VbSVSEXhu.A jh\a:hc?Jycjo}Nv>SHɺEKPGeG=p;+& VT"G .;gjfvml#Vgcugm gǜCjBe<`+x|o p#$jhJXw*$=BY>T%}ObP7&ixO>~+p@z#r!D˙,M9r4Úmjң!e FBJHJ`KDP^Iwɓt\IwiN#ѵTC}C{I%%1P0Tb߭~fwhpr88p999V%v#$,sƺt&DxM4SR$iWaS uG(8酂aS@-GHxZW.΃dڛPKY"1I#> pkits.schemaUT y77A;7AUxmj0u8 GڝH\4M0$KŞ-=J-t@sZZX XaY!sRRx붇w/֓i,N8=hλם8^`/.Щ<&cq,a[gYϐHe?3d?W8[B Q`3tW' /ٜ,N&+ UHOPKKJ/]w ReadMe.txtUT ?;7AUxJ0-R+]ЃA b2 IN{ӜB?vӵ[<$Q^Ɯcf,xwwbAګPv^1Ɖ:@Թ D&C6U)>'u?(N*ylfs NhwJ> }Xa01/渚0'+XzllKĄ5P%!J3\q!9z4xE{ӉԒO\p{b<7m۠OPK aJ/ Acertpairs/UTن?UxPK[J/{07 =certpairs/anyPolicyCACertforwardcrossCertificatePair.cpUTІ?UxPK[J/+707 certpairs/anyPolicyCACertreversecrossCertificatePair.cpUTІ?UxPK[J/ݍ<> qcertpairs/BadCRLIssuerNameCACertforwardcrossCertificatePair.cpUTІ?UxPK[J/RP<> certpairs/BadCRLIssuerNameCACertreversecrossCertificatePair.cpUTІ?UxPK[J/ lTr9= certpairs/BadCRLSignatureCACertforwardcrossCertificatePair.cpUTІ?UxPK[J/J<9= t certpairs/BadCRLSignatureCACertreversecrossCertificatePair.cpUTІ?UxPK[J/~;= certpairs/BadnotAfterDateCACertforwardcrossCertificatePair.cpUTІ?UxPK[J/ ;= certpairs/BadnotAfterDateCACertreversecrossCertificatePair.cpUTІ?UxPK[J/p6> scertpairs/BadnotBeforeDateCACertforwardcrossCertificatePair.cpUTІ?UxPK[J/fX@6> certpairs/BadnotBeforeDateCACertreversecrossCertificatePair.cpUTІ?UxPK[J/6#07 certpairs/BadSignedCACertforwardcrossCertificatePair.cpUTІ?UxPK[J/Xsc07 [certpairs/BadSignedCACertreversecrossCertificatePair.cpUTІ?UxPK[J/۾JGM certpairs/basicConstraintsCriticalcAFalseCACertforwardcrossCertificatePair.cpUTІ?UxPK[J/P&,GM "certpairs/basicConstraintsCriticalcAFalseCACertreversecrossCertificatePair.cpUTІ?UxPK[J/BI %certpairs/basicConstraintsNotCriticalCACertforwardcrossCertificatePair.cpUTІ?UxPK[J/BI A(certpairs/basicConstraintsNotCriticalCACertreversecrossCertificatePair.cpUTІ?UxPK[J/.dJP *certpairs/basicConstraintsNotCriticalcAFalseCACertforwardcrossCertificatePair.cpUTІ?UxPK[J/bJP -certpairs/basicConstraintsNotCriticalcAFalseCACertreversecrossCertificatePair.cpUTІ?UxPK[J/HJ 0certpairs/BasicSelfIssuedCRLSigningKeyCACertforwardcrossCertificatePair.cpUTІ?UxPK[J/HJ ^3certpairs/BasicSelfIssuedCRLSigningKeyCACertreversecrossCertificatePair.cpUTІ?UxPK[J/)WBC #6certpairs/BasicSelfIssuedNewKeyCACertforwardcrossCertificatePair.cpUTІ?UxPK[J/ݰBC 8certpairs/BasicSelfIssuedNewKeyCACertreversecrossCertificatePair.cpUTІ?UxPK[J/Y@C ;certpairs/BasicSelfIssuedOldKeyCACertforwardcrossCertificatePair.cpUTІ?UxPK[J/'@C I>certpairs/BasicSelfIssuedOldKeyCACertreversecrossCertificatePair.cpUTІ?UxPK[J/L(~7 @certpairs/deltaCRLCA1CertforwardcrossCertificatePair.cpUTІ?UxPK[J/0\(~7 Ccertpairs/deltaCRLCA1CertreversecrossCertificatePair.cpUTІ?UxPK[J/Xc)~7 #Fcertpairs/deltaCRLCA2CertforwardcrossCertificatePair.cpUTІ?UxPK[J/j$R)~7 Hcertpairs/deltaCRLCA2CertreversecrossCertificatePair.cpUTІ?UxPK[J/h)~7 IKcertpairs/deltaCRLCA3CertforwardcrossCertificatePair.cpUTІ?UxPK[J/ )~7 Mcertpairs/deltaCRLCA3CertreversecrossCertificatePair.cpUTІ?UxPK[J/ ~?E oPcertpairs/deltaCRLIndicatorNoBaseCACertforwardcrossCertificatePair.cpUTІ?UxPK[J/k?E &Scertpairs/deltaCRLIndicatorNoBaseCACertreversecrossCertificatePair.cpUTІ?UxPK[J/{E@ Ucertpairs/DifferentPoliciesTest7EEforwardcrossCertificatePair.cpUTІ?UxPK[J/OPE@ Xcertpairs/DifferentPoliciesTest7EEreversecrossCertificatePair.cpUTІ?UxPK[J/G1D@ M[certpairs/DifferentPoliciesTest8EEforwardcrossCertificatePair.cpUTІ?UxPK[J/;D@ ^certpairs/DifferentPoliciesTest8EEreversecrossCertificatePair.cpUTІ?UxPK[J/F;@ `certpairs/distributionPoint1CACertforwardcrossCertificatePair.cpUTІ?UxPK[J/P9-;@ iccertpairs/distributionPoint1CACertreversecrossCertificatePair.cpUTІ?UxPK[J//'<@ fcertpairs/distributionPoint2CACertforwardcrossCertificatePair.cpUTІ?UxPK[J/h9<@ hcertpairs/distributionPoint2CACertreversecrossCertificatePair.cpUTІ?UxPK[J/p CJ ukcertpairs/GeneralizedTimeCRLnextUpdateCACertforwardcrossCertificatePair.cpUTІ?UxPK[J/NCJ 5ncertpairs/GeneralizedTimeCRLnextUpdateCACertreversecrossCertificatePair.cpUTІ?UxPK[J/C1*y2 pcertpairs/GoodCACertforwardcrossCertificatePair.cpUTІ?UxPK[J/ *y2 scertpairs/GoodCACertreversecrossCertificatePair.cpUTІ?UxPK[J/=b15 vcertpairs/GoodsubCACertforwardcrossCertificatePair.cpUTІ?UxPK[J/ˊ15 xcertpairs/GoodsubCACertreversecrossCertificatePair.cpUTІ?UxPK[J/W_L E{certpairs/GoodsubCAPanyPolicyMapping1to2CACertforwardcrossCertificatePair.cpUTІ?UxPK[J/h_L #~certpairs/GoodsubCAPanyPolicyMapping1to2CACertreversecrossCertificatePair.cpUTІ?UxPK[J/k-5: certpairs/indirectCRLCA1CertforwardcrossCertificatePair.cpUTІ?UxPK[J/{ (75: certpairs/indirectCRLCA1CertreversecrossCertificatePair.cpUTІ?UxPK[J/ʃ5: Ecertpairs/indirectCRLCA2CertforwardcrossCertificatePair.cpUTІ?UxPK[J/u>5: certpairs/indirectCRLCA2CertreversecrossCertificatePair.cpUTІ?UxPK[J/_6: certpairs/indirectCRLCA3CertforwardcrossCertificatePair.cpUTІ?UxPK[J/%x6: ,certpairs/indirectCRLCA3CertreversecrossCertificatePair.cpUTІ?UxPK[J/CC8: ϐcertpairs/indirectCRLCA4CertforwardcrossCertificatePair.cpUTІ?UxPK[J/S\Y8: tcertpairs/indirectCRLCA4CertreversecrossCertificatePair.cpUTІ?UxPK[J/"4: certpairs/indirectCRLCA5CertforwardcrossCertificatePair.cpUTІ?UxPK[J/294: certpairs/indirectCRLCA5CertreversecrossCertificatePair.cpUTІ?UxPK[J/N3: [certpairs/indirectCRLCA6CertforwardcrossCertificatePair.cpUTІ?UxPK[J/T3: certpairs/indirectCRLCA6CertreversecrossCertificatePair.cpUTІ?UxPK[J/ШM? certpairs/inhibitAnyPolicy0CACertforwardcrossCertificatePair.cpUTІ?UxPK[J/dM? Zcertpairs/inhibitAnyPolicy0CACertreversecrossCertificatePair.cpUTІ?UxPK[J/-rP? certpairs/inhibitAnyPolicy1CACertforwardcrossCertificatePair.cpUTІ?UxPK[J/`~P? ۨcertpairs/inhibitAnyPolicy1CACertreversecrossCertificatePair.cpUTІ?UxPK[J/h/C certpairs/inhibitAnyPolicy1subCA1CertforwardcrossCertificatePair.cpUTІ?UxPK[J/h/C Bcertpairs/inhibitAnyPolicy1subCA1CertreversecrossCertificatePair.cpUTІ?UxPK[J/2/C certpairs/inhibitAnyPolicy1subCA2CertforwardcrossCertificatePair.cpUTІ?UxPK[J/St/C certpairs/inhibitAnyPolicy1subCA2CertreversecrossCertificatePair.cpUTІ?UxPK[J/:eNBF 1certpairs/inhibitAnyPolicy1subCAIAP5CertforwardcrossCertificatePair.cpUTІ?UxPK[J/1FBF certpairs/inhibitAnyPolicy1subCAIAP5CertreversecrossCertificatePair.cpUTІ?UxPK[J/K6A-F certpairs/inhibitAnyPolicy1subsubCA2CertforwardcrossCertificatePair.cpUTІ?UxPK[J/i2-F Mcertpairs/inhibitAnyPolicy1subsubCA2CertreversecrossCertificatePair.cpUTІ?UxPK[J/6N? certpairs/inhibitAnyPolicy5CACertforwardcrossCertificatePair.cpUTІ?UxPK[J/P_dN? certpairs/inhibitAnyPolicy5CACertreversecrossCertificatePair.cpUTІ?UxPK[J/l=B scertpairs/inhibitAnyPolicy5subCACertforwardcrossCertificatePair.cpUTІ?UxPK[J/[=B %certpairs/inhibitAnyPolicy5subCACertreversecrossCertificatePair.cpUTІ?UxPK[J/m!4E certpairs/inhibitAnyPolicy5subsubCACertforwardcrossCertificatePair.cpUTІ?UxPK[J/64E certpairs/inhibitAnyPolicy5subsubCACertreversecrossCertificatePair.cpUTІ?UxPK[J/MC /certpairs/inhibitPolicyMapping0CACertforwardcrossCertificatePair.cpUTІ?UxPK[J/R9MC certpairs/inhibitPolicyMapping0CACertreversecrossCertificatePair.cpUTІ?UxPK[J/ ?FF certpairs/inhibitPolicyMapping0subCACertforwardcrossCertificatePair.cpUTІ?UxPK[J/fFF tcertpairs/inhibitPolicyMapping0subCACertreversecrossCertificatePair.cpUTІ?UxPK[J/ʞTF 3certpairs/inhibitPolicyMapping1P12CACertforwardcrossCertificatePair.cpUTІ?UxPK[J/:M#TF certpairs/inhibitPolicyMapping1P12CACertreversecrossCertificatePair.cpUTІ?UxPK[J/rWI certpairs/inhibitPolicyMapping1P12subCACertforwardcrossCertificatePair.cpUTІ?UxPK[J/FWI certpairs/inhibitPolicyMapping1P12subCACertreversecrossCertificatePair.cpUTІ?UxPK[J/YLM scertpairs/inhibitPolicyMapping1P12subCAIPM5CertforwardcrossCertificatePair.cpUTІ?UxPK[J/[LM ?certpairs/inhibitPolicyMapping1P12subCAIPM5CertreversecrossCertificatePair.cpUTІ?UxPK[J/SZPL certpairs/inhibitPolicyMapping1P12subsubCACertforwardcrossCertificatePair.cpUTІ?UxPK[J/`+PL certpairs/inhibitPolicyMapping1P12subsubCACertreversecrossCertificatePair.cpUTІ?UxPK[J/OVP certpairs/inhibitPolicyMapping1P12subsubCAIPM5CertforwardcrossCertificatePair.cpUTІ?UxPK[J/ RVP certpairs/inhibitPolicyMapping1P12subsubCAIPM5CertreversecrossCertificatePair.cpUTІ?UxPK[J/QE [certpairs/inhibitPolicyMapping1P1CACertforwardcrossCertificatePair.cpUTІ?UxPK[J/yȓQE $certpairs/inhibitPolicyMapping1P1CACertreversecrossCertificatePair.cpUTІ?UxPK[J/1JH certpairs/inhibitPolicyMapping1P1subCACertforwardcrossCertificatePair.cpUTІ?UxPK[J/|JH certpairs/inhibitPolicyMapping1P1subCACertreversecrossCertificatePair.cpUTІ?UxPK[J/JK wcertpairs/inhibitPolicyMapping1P1subsubCACertforwardcrossCertificatePair.cpUTІ?UxPK[J/]#DJK ?certpairs/inhibitPolicyMapping1P1subsubCACertreversecrossCertificatePair.cpUTІ?UxPK[J/?NC  certpairs/inhibitPolicyMapping5CACertforwardcrossCertificatePair.cpUTІ?UxPK[J/ hNC certpairs/inhibitPolicyMapping5CACertreversecrossCertificatePair.cpUTІ?UxPK[J/]>u=F certpairs/inhibitPolicyMapping5subCACertforwardcrossCertificatePair.cpUTІ?UxPK[J/M=F Ecertpairs/inhibitPolicyMapping5subCACertreversecrossCertificatePair.cpUTІ?UxPK[J/4v9I certpairs/inhibitPolicyMapping5subsubCACertforwardcrossCertificatePair.cpUTІ?UxPK[J/X9I certpairs/inhibitPolicyMapping5subsubCACertreversecrossCertificatePair.cpUTІ?UxPK[J/!'KL ecertpairs/inhibitPolicyMapping5subsubsubCACertforwardcrossCertificatePair.cpUTІ?UxPK[J/KL /certpairs/inhibitPolicyMapping5subsubsubCACertreversecrossCertificatePair.cpUTІ?UxPK[J/FAL certpairs/InvalidonlyContainsUserCertsTest11EEforwardcrossCertificatePair.cpUTІ?UxPK[J/:AL !certpairs/InvalidonlyContainsUserCertsTest11EEreversecrossCertificatePair.cpUTІ?UxPK[J/!FH y$certpairs/InvalidpathLenConstraintTest10EEforwardcrossCertificatePair.cpUTІ?UxPK[J/HeFH :'certpairs/InvalidpathLenConstraintTest10EEreversecrossCertificatePair.cpUTІ?UxPK[J/yGH )certpairs/InvalidpathLenConstraintTest12EEforwardcrossCertificatePair.cpUTІ?UxPK[J/e>GH ,certpairs/InvalidpathLenConstraintTest12EEreversecrossCertificatePair.cpUTІ?UxPK[J/3@G /certpairs/InvalidpathLenConstraintTest6EEforwardcrossCertificatePair.cpUTІ?UxPK[J/~B@G 92certpairs/InvalidpathLenConstraintTest6EEreversecrossCertificatePair.cpUTІ?UxPK[J/Q_TFJ 4certpairs/keyUsageCriticalcRLSignFalseCACertforwardcrossCertificatePair.cpUTІ?UxPK[J/2FJ 7certpairs/keyUsageCriticalcRLSignFalseCACertreversecrossCertificatePair.cpUTІ?UxPK[J/5 FN y:certpairs/keyUsageCriticalkeyCertSignFalseCACertforwardcrossCertificatePair.cpUTІ?UxPK[J/FN @=certpairs/keyUsageCriticalkeyCertSignFalseCACertreversecrossCertificatePair.cpUTІ?UxPK[J/>:9A @certpairs/keyUsageNotCriticalCACertforwardcrossCertificatePair.cpUTІ?UxPK[J/9A Bcertpairs/keyUsageNotCriticalCACertreversecrossCertificatePair.cpUTІ?UxPK[J/HIM aEcertpairs/keyUsageNotCriticalcRLSignFalseCACertforwardcrossCertificatePair.cpUTІ?UxPK[J/IM *Hcertpairs/keyUsageNotCriticalcRLSignFalseCACertreversecrossCertificatePair.cpUTІ?UxPK[J/ym3-{3 Jcertpairs/NoCRLCACertforwardcrossCertificatePair.cpUTІ?UxPK[J/oIQ Mcertpairs/keyUsageNotCriticalkeyCertSignFalseCACertforwardcrossCertificatePair.cpUTІ?UxPK[J/'u)6IQ SPcertpairs/keyUsageNotCriticalkeyCertSignFalseCACertreversecrossCertificatePair.cpUTІ?UxPK[J/> :> Scertpairs/LongSerialNumberCACertforwardcrossCertificatePair.cpUTІ?UxPK[J/y:> Ucertpairs/LongSerialNumberCACertreversecrossCertificatePair.cpUTІ?UxPK[J/G,O9 vXcertpairs/Mapping1to2CACertforwardcrossCertificatePair.cpUTІ?UxPK[J/>_O9 1[certpairs/Mapping1to2CACertreversecrossCertificatePair.cpUTІ?UxPK[J/ ;ZB ]certpairs/MappingFromanyPolicyCACertforwardcrossCertificatePair.cpUTІ?UxPK[J/nZB `certpairs/MappingFromanyPolicyCACertreversecrossCertificatePair.cpUTІ?UxPK[J/V@ ccertpairs/MappingToanyPolicyCACertforwardcrossCertificatePair.cpUTІ?UxPK[J/n [V@ Sfcertpairs/MappingToanyPolicyCACertreversecrossCertificatePair.cpUTІ?UxPK[J/t4|E icertpairs/MissingbasicConstraintsCACertforwardcrossCertificatePair.cpUTІ?UxPK[J/<ַ4|E kcertpairs/MissingbasicConstraintsCACertreversecrossCertificatePair.cpUTІ?UxPK[J/1tg@ tncertpairs/nameConstraintsDN1CACertforwardcrossCertificatePair.cpUTІ?UxPK[J/ͬˌg@ Nqcertpairs/nameConstraintsDN1CACertreversecrossCertificatePair.cpUTІ?UxPK[J/7%Tj+D (tcertpairs/nameConstraintsDN1subCA1CertforwardcrossCertificatePair.cpUTІ?UxPK[J/tj+D wcertpairs/nameConstraintsDN1subCA1CertreversecrossCertificatePair.cpUTІ?UxPK[J/oSdD ycertpairs/nameConstraintsDN1subCA2CertforwardcrossCertificatePair.cpUTІ?UxPK[J/dD |certpairs/nameConstraintsDN1subCA2CertreversecrossCertificatePair.cpUTІ?UxPK[J/ ciD certpairs/nameConstraintsDN1subCA3CertforwardcrossCertificatePair.cpUTІ?UxPK[J/iD certpairs/nameConstraintsDN1subCA3CertreversecrossCertificatePair.cpUTІ?UxPK[J/1q6@ `certpairs/nameConstraintsDN2CACertforwardcrossCertificatePair.cpUTІ?UxPK[J/UUq6@ Dcertpairs/nameConstraintsDN2CACertreversecrossCertificatePair.cpUTІ?UxPK[J/-Iah@ (certpairs/nameConstraintsDN3CACertforwardcrossCertificatePair.cpUTІ?UxPK[J/y:h@ certpairs/nameConstraintsDN3CACertreversecrossCertificatePair.cpUTІ?UxPK[J/b{dD ސcertpairs/nameConstraintsDN3subCA1CertforwardcrossCertificatePair.cpUTІ?UxPK[J/oWdD certpairs/nameConstraintsDN3subCA1CertreversecrossCertificatePair.cpUTІ?UxPK[J/S5ND certpairs/nameConstraintsDN3subCA2CertforwardcrossCertificatePair.cpUTІ?UxPK[J/>4ND Ycertpairs/nameConstraintsDN3subCA2CertreversecrossCertificatePair.cpUTІ?UxPK[J/ȿ8q4@ certpairs/nameConstraintsDN4CACertforwardcrossCertificatePair.cpUTІ?UxPK[J/k!q4@ certpairs/nameConstraintsDN4CACertreversecrossCertificatePair.cpUTІ?UxPK[J/귆R@ certpairs/nameConstraintsDN5CACertforwardcrossCertificatePair.cpUTІ?UxPK[J/gXR@ ߤcertpairs/nameConstraintsDN5CACertreversecrossCertificatePair.cpUTІ?UxPK[J/U|VA اcertpairs/nameConstraintsDNS1CACertforwardcrossCertificatePair.cpUTІ?UxPK[J/vB certpairs/NegativeSerialNumberCACertforwardcrossCertificatePair.cpUTІ?UxPK[J/w&>B ccertpairs/NegativeSerialNumberCACertreversecrossCertificatePair.cpUTІ?UxPK[J/K-{3 certpairs/NoCRLCACertreversecrossCertificatePair.cpUTІ?UxPK[J/y2EH certpairs/NoissuingDistributionPointCACertforwardcrossCertificatePair.cpUTІ?UxPK[J/zEH icertpairs/NoissuingDistributionPointCACertreversecrossCertificatePair.cpUTІ?UxPK[J/OUsg8 )certpairs/NoPoliciesCACertforwardcrossCertificatePair.cpUTІ?UxPK[J/hg8 certpairs/NoPoliciesCACertreversecrossCertificatePair.cpUTІ?UxPK[J/M78> 9certpairs/OldCRLnextUpdateCACertforwardcrossCertificatePair.cpUTІ?UxPK[J/ !XQ8> certpairs/OldCRLnextUpdateCACertreversecrossCertificatePair.cpUTІ?UxPK[J/×AH certpairs/onlyContainsAttributeCertsCACertforwardcrossCertificatePair.cpUTІ?UxPK[J/كAH Gcertpairs/onlyContainsAttributeCertsCACertreversecrossCertificatePair.cpUTІ?UxPK[J/#\9A certpairs/onlyContainsCACertsCACertforwardcrossCertificatePair.cpUTІ?UxPK[J/~w9A certpairs/onlyContainsCACertsCACertreversecrossCertificatePair.cpUTІ?UxPK[J/:C ]certpairs/onlyContainsUserCertsCACertforwardcrossCertificatePair.cpUTІ?UxPK[J/8l6> certpairs/onlySomeReasonsCA1CertforwardcrossCertificatePair.cpUTІ?UxPK[J/EH:C certpairs/onlyContainsUserCertsCACertreversecrossCertificatePair.cpUTІ?UxPK[J/B6> dcertpairs/onlySomeReasonsCA1CertreversecrossCertificatePair.cpUTІ?UxPK[J/7n9> certpairs/onlySomeReasonsCA2CertforwardcrossCertificatePair.cpUTІ?UxPK[J/$9> certpairs/onlySomeReasonsCA2CertreversecrossCertificatePair.cpUTІ?UxPK[J/F:> _certpairs/onlySomeReasonsCA3CertforwardcrossCertificatePair.cpUTІ?UxPK[J/:> certpairs/onlySomeReasonsCA3CertreversecrossCertificatePair.cpUTІ?UxPK[J/tX 9> certpairs/onlySomeReasonsCA4CertforwardcrossCertificatePair.cpUTІ?UxPK[J/KE9> _certpairs/onlySomeReasonsCA4CertreversecrossCertificatePair.cpUTІ?UxPK[J/6,IB certpairs/OverlappingPoliciesTest6EEforwardcrossCertificatePair.cpUTІ?UxPK[J/0IB certpairs/OverlappingPoliciesTest6EEreversecrossCertificatePair.cpUTІ?UxPK[J/) >W< certpairs/P12Mapping1to3CACertforwardcrossCertificatePair.cpUTІ?UxPK[J/#W< Kcertpairs/P12Mapping1to3CACertreversecrossCertificatePair.cpUTІ?UxPK[J/u^O? certpairs/P12Mapping1to3subCACertforwardcrossCertificatePair.cpUTІ?UxPK[J/#!=@ ?certpairs/pathLenConstraint0CACertforwardcrossCertificatePair.cpUTІ?UxPK[J/G=@ Bcertpairs/pathLenConstraint0CACertreversecrossCertificatePair.cpUTІ?UxPK[J/@ϥ7D KEcertpairs/pathLenConstraint0subCA2CertforwardcrossCertificatePair.cpUTІ?UxPK[J/@W7D Gcertpairs/pathLenConstraint0subCA2CertreversecrossCertificatePair.cpUTІ?UxPK[J/װ4C Jcertpairs/pathLenConstraint0subCACertforwardcrossCertificatePair.cpUTІ?UxPK[J/X4C QMcertpairs/pathLenConstraint0subCACertreversecrossCertificatePair.cpUTІ?UxPK[J/->@ Ocertpairs/pathLenConstraint1CACertforwardcrossCertificatePair.cpUTІ?UxPK[J/&>@ Rcertpairs/pathLenConstraint1CACertreversecrossCertificatePair.cpUTІ?UxPK[J/W0C ]Ucertpairs/pathLenConstraint1subCACertforwardcrossCertificatePair.cpUTІ?UxPK[J/~(0C Xcertpairs/pathLenConstraint1subCACertreversecrossCertificatePair.cpUTІ?UxPK[J/2(Q;@ Zcertpairs/pathLenConstraint6CACertforwardcrossCertificatePair.cpUTІ?UxPK[J/Kl;@ W]certpairs/pathLenConstraint6CACertreversecrossCertificatePair.cpUTІ?UxPK[J/9D `certpairs/pathLenConstraint6subCA0CertforwardcrossCertificatePair.cpUTІ?UxPK[J/Ԝ9D bcertpairs/pathLenConstraint6subCA0CertreversecrossCertificatePair.cpUTІ?UxPK[J/0"8D eecertpairs/pathLenConstraint6subCA1CertforwardcrossCertificatePair.cpUTІ?UxPK[J/k8D hcertpairs/pathLenConstraint6subCA1CertreversecrossCertificatePair.cpUTІ?UxPK[J/c-=D jcertpairs/pathLenConstraint6subCA4CertforwardcrossCertificatePair.cpUTІ?UxPK[J/dv;=D wmcertpairs/pathLenConstraint6subCA4CertreversecrossCertificatePair.cpUTІ?UxPK[J/u;H +pcertpairs/pathLenConstraint6subsubCA00CertforwardcrossCertificatePair.cpUTІ?UxPK[J/[;H rcertpairs/pathLenConstraint6subsubCA00CertreversecrossCertificatePair.cpUTІ?UxPK[J/cn7H ucertpairs/pathLenConstraint6subsubCA11CertforwardcrossCertificatePair.cpUTІ?UxPK[J/aKQ7H Ixcertpairs/pathLenConstraint6subsubCA11CertreversecrossCertificatePair.cpUTІ?UxPK[J/G (9H zcertpairs/pathLenConstraint6subsubCA41CertforwardcrossCertificatePair.cpUTІ?UxPK[J/Eq9H }certpairs/pathLenConstraint6subsubCA41CertreversecrossCertificatePair.cpUTІ?UxPK[J/,]9L ccertpairs/pathLenConstraint6subsubsubCA11XCertforwardcrossCertificatePair.cpUTІ?UxPK[J/ܕ89L certpairs/pathLenConstraint6subsubsubCA11XCertreversecrossCertificatePair.cpUTІ?UxPK[J/ŵ:L Ӆcertpairs/pathLenConstraint6subsubsubCA41XCertforwardcrossCertificatePair.cpUTІ?UxPK[J/gD3:L certpairs/pathLenConstraint6subsubsubCA41XCertreversecrossCertificatePair.cpUTІ?UxPK[J/BH; Ecertpairs/PoliciesP1234CACertforwardcrossCertificatePair.cpUTІ?UxPK[J/aBH; certpairs/PoliciesP1234CACertreversecrossCertificatePair.cpUTІ?UxPK[J/?G4B certpairs/PoliciesP1234subCAP123CertforwardcrossCertificatePair.cpUTІ?UxPK[J/4B Zcertpairs/PoliciesP1234subCAP123CertreversecrossCertificatePair.cpUTІ?UxPK[J/]{6H certpairs/PoliciesP1234subsubCAP123P12CertforwardcrossCertificatePair.cpUTІ?UxPK[J/^6H certpairs/PoliciesP1234subsubCAP123P12CertreversecrossCertificatePair.cpUTІ?UxPK[J/;` E: ecertpairs/PoliciesP123CACertforwardcrossCertificatePair.cpUTІ?UxPK[J/&kE: certpairs/PoliciesP123CACertreversecrossCertificatePair.cpUTІ?UxPK[J/~8@ ɠcertpairs/PoliciesP123subCAP12CertforwardcrossCertificatePair.cpUTІ?UxPK[J/"8@ tcertpairs/PoliciesP123subCAP12CertreversecrossCertificatePair.cpUTІ?UxPK[J/e3E certpairs/PoliciesP123subsubCAP12P1CertforwardcrossCertificatePair.cpUTІ?UxPK[J/>(3E ʨcertpairs/PoliciesP123subsubCAP12P1CertreversecrossCertificatePair.cpUTІ?UxPK[J/[ k3E ucertpairs/PoliciesP123subsubCAP12P2CertforwardcrossCertificatePair.cpUTІ?UxPK[J/\r3E certpairs/PoliciesP123subsubCAP12P2CertreversecrossCertificatePair.cpUTІ?UxPK[J/pSH:J ˰certpairs/PoliciesP123subsubsubCAP12P2P1CertforwardcrossCertificatePair.cpUTІ?UxPK[J/a1:J certpairs/PoliciesP123subsubsubCAP12P2P1CertreversecrossCertificatePair.cpUTІ?UxPK[J/C9 9certpairs/PoliciesP12CACertforwardcrossCertificatePair.cpUTІ?UxPK[J/ C9 certpairs/PoliciesP12CACertreversecrossCertificatePair.cpUTІ?UxPK[J/gG1> certpairs/PoliciesP12subCAP1CertforwardcrossCertificatePair.cpUTІ?UxPK[J/g 1> 9certpairs/PoliciesP12subCAP1CertreversecrossCertificatePair.cpUTІ?UxPK[J/2M55C certpairs/PoliciesP12subsubCAP1P2CertforwardcrossCertificatePair.cpUTІ?UxPK[J/1O5C certpairs/PoliciesP12subsubCAP1P2CertreversecrossCertificatePair.cpUTІ?UxPK[J/M>< 1certpairs/PoliciesP2subCA2CertforwardcrossCertificatePair.cpUTІ?UxPK[J/W*>< certpairs/PoliciesP2subCA2CertreversecrossCertificatePair.cpUTІ?UxPK[J/6\/~; certpairs/PoliciesP2subCACertforwardcrossCertificatePair.cpUTІ?UxPK[J/zJ/~; (certpairs/PoliciesP2subCACertreversecrossCertificatePair.cpUTІ?UxPK[J/X?8 certpairs/PoliciesP3CACertforwardcrossCertificatePair.cpUTІ?UxPK[J/6JS&?8 ocertpairs/PoliciesP3CACertreversecrossCertificatePair.cpUTІ?UxPK[J/}>B certpairs/pre2000CRLnextUpdateCACertforwardcrossCertificatePair.cpUTІ?UxPK[J/JJ>B certpairs/pre2000CRLnextUpdateCACertreversecrossCertificatePair.cpUTІ?UxPK[J/1 sGD certpairs/requireExplicitPolicy0CACertforwardcrossCertificatePair.cpUTІ?UxPK[J/MGD =certpairs/requireExplicitPolicy0CACertreversecrossCertificatePair.cpUTІ?UxPK[J/6G certpairs/requireExplicitPolicy0subCACertforwardcrossCertificatePair.cpUTІ?UxPK[J/6G certpairs/requireExplicitPolicy0subCACertreversecrossCertificatePair.cpUTІ?UxPK[J/dA7J [certpairs/requireExplicitPolicy0subsubCACertforwardcrossCertificatePair.cpUTІ?UxPK[J/s7J certpairs/requireExplicitPolicy0subsubCACertreversecrossCertificatePair.cpUTІ?UxPK[J/057M certpairs/requireExplicitPolicy0subsubsubCACertforwardcrossCertificatePair.cpUTІ?UxPK[J/`57M zcertpairs/requireExplicitPolicy0subsubsubCACertreversecrossCertificatePair.cpUTІ?UxPK[J/!IE 1certpairs/requireExplicitPolicy10CACertforwardcrossCertificatePair.cpUTІ?UxPK[J/IE certpairs/requireExplicitPolicy10CACertreversecrossCertificatePair.cpUTІ?UxPK[J/6I9H certpairs/requireExplicitPolicy10subCACertforwardcrossCertificatePair.cpUTІ?UxPK[J/9H gcertpairs/requireExplicitPolicy10subCACertreversecrossCertificatePair.cpUTІ?UxPK[J/H 8K certpairs/requireExplicitPolicy10subsubCACertforwardcrossCertificatePair.cpUTІ?UxPK[J/LY8K certpairs/requireExplicitPolicy10subsubCACertreversecrossCertificatePair.cpUTІ?UxPK[J/t69N certpairs/requireExplicitPolicy10subsubsubCACertforwardcrossCertificatePair.cpUTІ?UxPK[J/V9N Acertpairs/requireExplicitPolicy10subsubsubCACertreversecrossCertificatePair.cpUTІ?UxPK[J/c)GD certpairs/requireExplicitPolicy2CACertforwardcrossCertificatePair.cpUTІ?UxPK[J/vGD certpairs/requireExplicitPolicy2CACertreversecrossCertificatePair.cpUTІ?UxPK[J/2:G w certpairs/requireExplicitPolicy2subCACertforwardcrossCertificatePair.cpUTІ?UxPK[J/:G +certpairs/requireExplicitPolicy2subCACertreversecrossCertificatePair.cpUTІ?UxPK[J/g.GD certpairs/requireExplicitPolicy4CACertforwardcrossCertificatePair.cpUTІ?UxPK[J/GD certpairs/requireExplicitPolicy4CACertreversecrossCertificatePair.cpUTІ?UxPK[J/ØE8G [certpairs/requireExplicitPolicy4subCACertforwardcrossCertificatePair.cpUTІ?UxPK[J/"Y8G certpairs/requireExplicitPolicy4subCACertreversecrossCertificatePair.cpUTІ?UxPK[J/zS9J certpairs/requireExplicitPolicy4subsubCACertforwardcrossCertificatePair.cpUTІ?UxPK[J/B*9J ucertpairs/requireExplicitPolicy4subsubCACertreversecrossCertificatePair.cpUTІ?UxPK[J/K9M +"certpairs/requireExplicitPolicy4subsubsubCACertforwardcrossCertificatePair.cpUTІ?UxPK[J/NS9M $certpairs/requireExplicitPolicy4subsubsubCACertreversecrossCertificatePair.cpUTІ?UxPK[J/\$ED 'certpairs/requireExplicitPolicy5CACertforwardcrossCertificatePair.cpUTІ?UxPK[J/I D Acertpairs/DSAParametersInheritedCACertforwardcrossCertificatePair.cpUTqن?UxPK aJ/qKJ D certpairs/DSAParametersInheritedCACertreversecrossCertificatePair.cpUTqن?UxPK aJ/ A˶certs/UTن?UxPK[J/j* certs/AllCertificatesanyPolicyTest11EE.crtUTІ?UxPK[J/Zs* ~certs/AllCertificatesNoPoliciesTest2EE.crtUTІ?UxPK[J/N+- certs/AllCertificatesSamePoliciesTest10EE.crtUTІ?UxPK[J/?m5- ucerts/AllCertificatesSamePoliciesTest13EE.crtUTІ?UxPK[J/7d' certs/anyPolicyCACert.crtUTІ?UxPK[J/&"x }certs/AnyPolicyTest14EE.crtUTІ?UxPK[J/u4 certs/BadCRLIssuerNameCACert.crtUTІ?UxPK[J/])=1~ pcerts/BadCRLSignatureCACert.crtUTІ?UxPK[J/;3~ certs/BadnotAfterDateCACert.crtUTІ?UxPK[J/:-. xcerts/BadnotBeforeDateCACert.crtUTІ?UxPK[J/J(w certs/BadSignedCACert.crtUTІ?UxPK[J/k㊷?/ mcerts/basicConstraintsCriticalcAFalseCACert.crtUTІ?UxPK[J/ҹ:+ certs/basicConstraintsNotCriticalCACert.crtUTІ?UxPK[J/" certs/DifferentPoliciesTest8EE.crtUTІ?UxPK[J/4" certs/DifferentPoliciesTest9EE.crtUTІ?UxPK[J/5 L3" <certs/distributionPoint1CACert.crtUTІ?UxPK[J/O4" certs/distributionPoint2CACert.crtUTІ?UxPK[J/;, M certs/GeneralizedTimeCRLnextUpdateCACert.crtUTІ?UxPK[J/uQ"q certs/GoodCACert.crtUTІ?UxPK[J/H) Pcerts/GoodsubCACert.crtUTІ?UxPK[J/X. certs/GoodsubCAPanyPolicyMapping1to2CACert.crtUTІ?UxPK[J/8-y |certs/indirectCRLCA1Cert.crtUTІ?UxPK[J/c-y certs/indirectCRLCA2Cert.crtUTІ?UxPK[J/x׌.y tcerts/indirectCRLCA3Cert.crtUTІ?UxPK[J//xsE% certs/indirectCRLCA3cRLIssuerCert.crtUTІ?UxPK[J/tV0y !certs/indirectCRLCA4Cert.crtUTІ?UxPK[J/}Y]% $certs/indirectCRLCA4cRLIssuerCert.crtUTІ?UxPK[J/,y &certs/indirectCRLCA5Cert.crtUTІ?UxPK[J/kv[+y 9)certs/indirectCRLCA6Cert.crtUTІ?UxPK[J/*bF! +certs/inhibitAnyPolicy0CACert.crtUTІ?UxPK[J/עI! M.certs/inhibitAnyPolicy1CACert.crtUTІ?UxPK[J/?+ 0certs/inhibitAnyPolicy1SelfIssuedCACert.crtUTІ?UxPK[J/WP/ e3certs/inhibitAnyPolicy1SelfIssuedsubCA2Cert.crtUTІ?UxPK[J/Gη'% 5certs/inhibitAnyPolicy1subCA1Cert.crtUTІ?UxPK[J/r$&% a8certs/inhibitAnyPolicy1subCA2Cert.crtUTІ?UxPK[J/.;( :certs/inhibitAnyPolicy1subCAIAP5Cert.crtUTІ?UxPK[J/=%( u=certs/inhibitAnyPolicy1subsubCA2Cert.crtUTІ?UxPK[J/WG! ?certs/inhibitAnyPolicy5CACert.crtUTІ?UxPK[J/vJ5$ Bcerts/inhibitAnyPolicy5subCACert.crtUTІ?UxPK[J/-,' Ecerts/inhibitAnyPolicy5subsubCACert.crtUTІ?UxPK[J/V)! Gcerts/inhibitAnyPolicyTest3EE.crtUTІ?UxPK[J/AD% Jcerts/inhibitPolicyMapping0CACert.crtUTІ?UxPK[J/ճ(?( Lcerts/inhibitPolicyMapping0subCACert.crtUTІ?UxPK[J/tM( UOcerts/inhibitPolicyMapping1P12CACert.crtUTІ?UxPK[J/P+ Qcerts/inhibitPolicyMapping1P12subCACert.crtUTІ?UxPK[J/֩F/ Tcerts/inhibitPolicyMapping1P12subCAIPM5Cert.crtUTІ?UxPK[J/I. SWcerts/inhibitPolicyMapping1P12subsubCACert.crtUTІ?UxPK[J/;O2 Ycerts/inhibitPolicyMapping1P12subsubCAIPM5Cert.crtUTІ?UxPK[J/×nJ' \certs/inhibitPolicyMapping1P1CACert.crtUTІ?UxPK[J/4V$1 U_certs/inhibitPolicyMapping1P1SelfIssuedCACert.crtUTІ?UxPK[J/Po74 acerts/inhibitPolicyMapping1P1SelfIssuedsubCACert.crtUTІ?UxPK[J/ gC* {dcerts/inhibitPolicyMapping1P1subCACert.crtUTІ?UxPK[J/C- gcerts/inhibitPolicyMapping1P1subsubCACert.crtUTІ?UxPK[J/܈E% icerts/inhibitPolicyMapping5CACert.crtUTІ?UxPK[J/l7( [lcerts/inhibitPolicyMapping5subCACert.crtUTІ?UxPK[J/F0+ ncerts/inhibitPolicyMapping5subsubCACert.crtUTІ?UxPK[J/OMD. {qcerts/inhibitPolicyMapping5subsubsubCACert.crtUTІ?UxPK[J//-0Z-( tcerts/InvalidBadCRLIssuerNameTest5EE.crtUTІ?UxPK[J/}\{D,' vcerts/InvalidBadCRLSignatureTest4EE.crtUTІ?UxPK[J/,y>4 .ycerts/InvalidBasicSelfIssuedCRLSigningKeyTest7EE.crtUTІ?UxPK[J/B>4 {certs/InvalidBasicSelfIssuedCRLSigningKeyTest8EE.crtUTІ?UxPK[J/:@1 x~certs/InvalidBasicSelfIssuedNewWithOldTest5EE.crtUTІ?UxPK[J/>1 certs/InvalidBasicSelfIssuedOldWithNewTest2EE.crtUTІ?UxPK[J/5 certs/InvalidcAFalseTest2EE.crtUTІ?UxPK[J/Y`jdA Ecerts/InvalidcAFalseTest3EE.crtUTІ?UxPK[J//8C,& ؈certs/InvalidCAnotAfterDateTest5EE.crtUTІ?UxPK[J/Z /' ]certs/InvalidCAnotBeforeDateTest1EE.crtUTІ?UxPK[J/v݅'t# certs/InvalidCASignatureTest2EE.crtUTІ?UxPK[J/=PS" ccerts/InvalidcRLIssuerTest27EE.crtUTІ?UxPK[J/* nW" certs/InvalidcRLIssuerTest31EE.crtUTІ?UxPK[J/[_nW" Εcerts/InvalidcRLIssuerTest32EE.crtUTІ?UxPK[J/Qj^" certs/InvalidcRLIssuerTest34EE.crtUTІ?UxPK[J/pO" Dcerts/InvalidcRLIssuerTest35EE.crtUTІ?UxPK[J/4c2/ certs/InvaliddeltaCRLIndicatorNoBaseTest1EE.crtUTІ?UxPK[J/2E-! certs/InvaliddeltaCRLTest10EE.crtUTІ?UxPK[J/ɿA, 6certs/InvaliddeltaCRLTest3EE.crtUTІ?UxPK[J/H C, ʥcerts/InvaliddeltaCRLTest4EE.crtUTІ?UxPK[J/pOB, `certs/InvaliddeltaCRLTest6EE.crtUTІ?UxPK[J/u?, certs/InvaliddeltaCRLTest9EE.crtUTІ?UxPK[J/ h]) certs/InvaliddistributionPointTest2EE.crtUTІ?UxPK[J/3f߫_) @certs/InvaliddistributionPointTest3EE.crtUTІ?UxPK[J/VQ) certs/InvaliddistributionPointTest6EE.crtUTІ?UxPK[J/hTKH) certs/InvaliddistributionPointTest8EE.crtUTІ?UxPK[J/y0) Lcerts/InvaliddistributionPointTest9EE.crtUTІ?UxPK[J/~ش\u 3 غcerts/InvalidDNandRFC822nameConstraintsTest28EE.crtUTІ?UxPK[J/)r 3 certs/InvalidDNandRFC822nameConstraintsTest29EE.crtUTІ?UxPK[J/=_rZ* certs/InvalidDNnameConstraintsTest10EE.crtUTІ?UxPK[J/C2N* Bcerts/InvalidDNnameConstraintsTest12EE.crtUTІ?UxPK[J/֣N* certs/InvalidDNnameConstraintsTest13EE.crtUTІ?UxPK[J/u P* certs/InvalidDNnameConstraintsTest15EE.crtUTІ?UxPK[J/0M* Ecerts/InvalidDNnameConstraintsTest16EE.crtUTІ?UxPK[J/K+ certs/InvalidDNSnameConstraintsTest33EE.crtUTІ?UxPK[J/@ M+ certs/InvalidDNSnameConstraintsTest38EE.crtUTІ?UxPK[J/ڈ+3& mcerts/InvalidEEnotAfterDateTest6EE.crtUTІ?UxPK[J/7C*' certs/InvalidEEnotBeforeDateTest2EE.crtUTІ?UxPK[J/ŒJ$n# }certs/InvalidEESignatureTest3EE.crtUTІ?UxPK[J/7(0+ certs/InvalidIDPwithindirectCRLTest23EE.crtUTІ?UxPK[J/iTS+ certs/InvalidIDPwithindirectCRLTest26EE.crtUTІ?UxPK[J/'( 6certs/InvalidinhibitAnyPolicyTest1EE.crtUTІ?UxPK[J/cO&( certs/InvalidinhibitAnyPolicyTest4EE.crtUTІ?UxPK[J/Ē.( 9certs/InvalidinhibitAnyPolicyTest5EE.crtUTІ?UxPK[J/1}N.( certs/InvalidinhibitAnyPolicyTest6EE.crtUTІ?UxPK[J/tϝ;, Kcerts/InvalidinhibitPolicyMappingTest1EE.crtUTІ?UxPK[J/Ͼ:, certs/InvalidinhibitPolicyMappingTest3EE.crtUTІ?UxPK[J/!YR87, ~certs/InvalidinhibitPolicyMappingTest5EE.crtUTІ?UxPK[J/R @, certs/InvalidinhibitPolicyMappingTest6EE.crtUTІ?UxPK[J/94 certs/InvalidkeyUsageCriticalcRLSignFalseTest4EE.crtUTІ?UxPK[J/R;8 S certs/InvalidkeyUsageCriticalkeyCertSignFalseTest1EE.crtUTІ?UxPK[J/@=7 certs/InvalidkeyUsageNotCriticalcRLSignFalseTest5EE.crtUTІ?UxPK[J/iX?; certs/InvalidkeyUsageNotCriticalkeyCertSignFalseTest2EE.crtUTІ?UxPK[J/µC) Mcerts/InvalidLongSerialNumberTest18EE.crtUTІ?UxPK[J/O3, certs/InvalidMappingFromanyPolicyTest7EE.crtUTІ?UxPK[J/l!+* ~certs/InvalidMappingToanyPolicyTest8EE.crtUTІ?UxPK[J/Y5/ certs/InvalidMissingbasicConstraintsTest1EE.crtUTІ?UxPK[J/z5'~" certs/InvalidMissingCRLTest1EE.crtUTІ?UxPK[J/ T) !certs/InvalidNameChainingOrderTest2EE.crtUTІ?UxPK[J/#` 1$ #certs/InvalidNameChainingTest1EE.crtUTІ?UxPK[J/^d3- Q&certs/InvalidNegativeSerialNumberTest15EE.crtUTІ?UxPK[J/,) (certs/InvalidOldCRLnextUpdateTest11EE.crtUTІ?UxPK[J/ ̷<3 l+certs/InvalidonlyContainsAttributeCertsTest14EE.crtUTІ?UxPK[J/., .certs/InvalidonlyContainsCACertsTest12EE.crtUTІ?UxPK[J/O p:. 0certs/InvalidonlyContainsUserCertsTest11EE.crtUTІ?UxPK[J/c,( 63certs/InvalidonlySomeReasonsTest15EE.crtUTІ?UxPK[J/D+( 5certs/InvalidonlySomeReasonsTest16EE.crtUTІ?UxPK[J/'U,( C8certs/InvalidonlySomeReasonsTest17EE.crtUTІ?UxPK[J/ȃgh( :certs/InvalidonlySomeReasonsTest20EE.crtUTІ?UxPK[J/q2fh( =certs/InvalidonlySomeReasonsTest21EE.crtUTІ?UxPK[J/i ~?* M@certs/InvalidpathLenConstraintTest10EE.crtUTІ?UxPK[J/c]6* Bcerts/InvalidpathLenConstraintTest11EE.crtUTІ?UxPK[J/@* |Ecerts/InvalidpathLenConstraintTest12EE.crtUTІ?UxPK[J/4'1) Hcerts/InvalidpathLenConstraintTest5EE.crtUTІ?UxPK[J/;&9) Jcerts/InvalidpathLenConstraintTest6EE.crtUTІ?UxPK[J/Ԥ6) ;Mcerts/InvalidpathLenConstraintTest9EE.crtUTІ?UxPK[J/rb<& Ocerts/InvalidPolicyMappingTest10EE.crtUTІ?UxPK[J/0a0% bRcerts/InvalidPolicyMappingTest2EE.crtUTІ?UxPK[J/5% Tcerts/InvalidPolicyMappingTest4EE.crtUTІ?UxPK[J/R++0- wWcerts/Invalidpre2000CRLnextUpdateTest12EE.crtUTІ?UxPK[J/exH certs/Mapping1to2CACert.crtUTІ?UxPK[J/S$ 2certs/MappingFromanyPolicyCACert.crtUTІ?UxPK[J/PuPO" ܲcerts/MappingToanyPolicyCACert.crtUTІ?UxPK[J/s,t' certs/MissingbasicConstraintsCACert.crtUTІ?UxPK[J/6-`" certs/nameConstraintsDN1CACert.crtUTІ?UxPK[J/, certs/nameConstraintsDN1SelfIssuedCACert.crtUTІ?UxPK[J/ҕb#& 8certs/nameConstraintsDN1subCA1Cert.crtUTІ?UxPK[J/ТF\& certs/nameConstraintsDN1subCA2Cert.crtUTІ?UxPK[J/_rb& certs/nameConstraintsDN1subCA3Cert.crtUTІ?UxPK[J/Q|Wi." ccerts/nameConstraintsDN2CACert.crtUTІ?UxPK[J/9a" !certs/nameConstraintsDN3CACert.crtUTІ?UxPK[J/`^& certs/nameConstraintsDN3subCA1Cert.crtUTІ?UxPK[J/kKG& certs/nameConstraintsDN3subCA2Cert.crtUTІ?UxPK[J/*i," .certs/nameConstraintsDN4CACert.crtUTІ?UxPK[J/clU~J" certs/nameConstraintsDN5CACert.crtUTІ?UxPK[J/}O# certs/nameConstraintsDNS1CACert.crtUTІ?UxPK[J/r2U# dcerts/nameConstraintsDNS2CACert.crtUTІ?UxPK[J/P|K/T& certs/nameConstraintsRFC822CA1Cert.crtUTІ?UxPK[J/#S& certs/nameConstraintsRFC822CA2Cert.crtUTІ?UxPK[J/)R& hcerts/nameConstraintsRFC822CA3Cert.crtUTІ?UxPK[J/UoQ# certs/nameConstraintsURI1CACert.crtUTІ?UxPK[J/WYFT# certs/nameConstraintsURI2CACert.crtUTІ?UxPK[J/ˍ9\R dcerts/NameOrderingCACert.crtUTІ?UxPK[J/k%6$ certs/NegativeSerialNumberCACert.crtUTІ?UxPK[J/67/%s certs/NoCRLCACert.crtUTІ?UxPK[J/G =* certs/NoissuingDistributionPointCACert.crtUTІ?UxPK[J/(y_ certs/NoPoliciesCACert.crtUTІ?UxPK[J/}-0 certs/OldCRLnextUpdateCACert.crtUTІ?UxPK[J/܇9* ~certs/onlyContainsAttributeCertsCACert.crtUTІ?UxPK[J/ r$1# certs/onlyContainsCACertsCACert.crtUTІ?UxPK[J/W2% certs/onlyContainsUserCertsCACert.crtUTІ?UxPK[J/}&.} %certs/onlySomeReasonsCA1Cert.crtUTІ?UxPK[J/&L1} certs/onlySomeReasonsCA2Cert.crtUTІ?UxPK[J/]1} *certs/onlySomeReasonsCA3Cert.crtUTІ?UxPK[J/I!1} certs/onlySomeReasonsCA4Cert.crtUTІ?UxPK[J/"\*B$ 2 certs/OverlappingPoliciesTest6EE.crtUTІ?UxPK[J/k (P certs/P12Mapping1to3CACert.crtUTІ?UxPK[J/!XOH! lcerts/P12Mapping1to3subCACert.crtUTІ?UxPK[J/EA$ certs/P12Mapping1to3subsubCACert.crtUTІ?UxPK[J/s "& certs/P1anyPolicyMapping1to2CACert.crtUTІ?UxPK[J/VLʝV certs/P1Mapping1to234CACert.crtUTІ?UxPK[J/fJ" certs/P1Mapping1to234subCACert.crtUTІ?UxPK[J/L„W% Kcerts/PanyPolicyMapping1to2CACert.crtUTІ?UxPK[J/i5" certs/pathLenConstraint0CACert.crtUTІ?UxPK[J/5 ?, !certs/pathLenConstraint0SelfIssuedCACert.crtUTІ?UxPK[J/>GX/& $certs/pathLenConstraint0subCA2Cert.crtUTІ?UxPK[J/?f,% &certs/pathLenConstraint0subCACert.crtUTІ?UxPK[J/S6" )certs/pathLenConstraint1CACert.crtUTІ?UxPK[J/(LI, +certs/pathLenConstraint1SelfIssuedCACert.crtUTІ?UxPK[J/nxN/ .certs/pathLenConstraint1SelfIssuedsubCACert.crtUTІ?UxPK[J/R(% 0certs/pathLenConstraint1subCACert.crtUTІ?UxPK[J/M3" 3certs/pathLenConstraint6CACert.crtUTІ?UxPK[J/l1& 5certs/pathLenConstraint6subCA0Cert.crtUTІ?UxPK[J/p0& '8certs/pathLenConstraint6subCA1Cert.crtUTІ?UxPK[J/cmP4& :certs/pathLenConstraint6subCA4Cert.crtUTІ?UxPK[J/|E2* ==certs/pathLenConstraint6subsubCA00Cert.crtUTІ?UxPK[J/ DO.* ?certs/pathLenConstraint6subsubCA11Cert.crtUTІ?UxPK[J/(71* WBcerts/pathLenConstraint6subsubCA41Cert.crtUTІ?UxPK[J/ 2. Dcerts/pathLenConstraint6subsubsubCA11XCert.crtUTІ?UxPK[J/Vl3. xGcerts/pathLenConstraint6subsubsubCA41XCert.crtUTІ?UxPK[J/IA Jcerts/PoliciesP1234CACert.crtUTІ?UxPK[J/A-$ Lcerts/PoliciesP1234subCAP123Cert.crtUTІ?UxPK[J/V0* !Ocerts/PoliciesP1234subsubCAP123P12Cert.crtUTІ?UxPK[J/> Qcerts/PoliciesP123CACert.crtUTІ?UxPK[J/f7/" ;Tcerts/PoliciesP123subCAP12Cert.crtUTІ?UxPK[J/%C+' Vcerts/PoliciesP123subsubCAP12P1Cert.crtUTІ?UxPK[J/[+' DYcerts/PoliciesP123subsubCAP12P2Cert.crtUTІ?UxPK[J/* 2, [certs/PoliciesP123subsubsubCAP12P2P1Cert.crtUTІ?UxPK[J/`; Z^certs/PoliciesP12CACert.crtUTІ?UxPK[J/p) `certs/PoliciesP12subCAP1Cert.crtUTІ?UxPK[J/ĥ-% _ccerts/PoliciesP12subsubCAP1P2Cert.crtUTІ?UxPK[J/8I6 ecerts/PoliciesP2subCA2Cert.crtUTІ?UxPK[J/H'v khcerts/PoliciesP2subCACert.crtUTІ?UxPK[J/ G>7 jcerts/PoliciesP3CACert.crtUTІ?UxPK[J/M6$ fmcerts/pre2000CRLnextUpdateCACert.crtUTІ?UxPK[J/H>& ocerts/requireExplicitPolicy0CACert.crtUTІ?UxPK[J/.) rcerts/requireExplicitPolicy0subCACert.crtUTІ?UxPK[J/DN ., ucerts/requireExplicitPolicy0subsubCACert.crtUTІ?UxPK[J/ 4n"1/ wcerts/requireExplicitPolicy0subsubsubCACert.crtUTІ?UxPK[J/ @' 4zcerts/requireExplicitPolicy10CACert.crtUTІ?UxPK[J/LD1* |certs/requireExplicitPolicy10subCACert.crtUTІ?UxPK[J/h1- \certs/requireExplicitPolicy10subsubCACert.crtUTІ?UxPK[J/ !20 certs/requireExplicitPolicy10subsubsubCACert.crtUTІ?UxPK[J/l?& certs/requireExplicitPolicy2CACert.crtUTІ?UxPK[J/$!0 certs/requireExplicitPolicy2SelfIssuedCACert.crtUTІ?UxPK[J/,+#3 certs/requireExplicitPolicy2SelfIssuedsubCACert.crtUTІ?UxPK[J/1) 'certs/requireExplicitPolicy2subCACert.crtUTІ?UxPK[J/ā?& certs/requireExplicitPolicy4CACert.crtUTІ?UxPK[J/7H0) Lcerts/requireExplicitPolicy4subCACert.crtUTІ?UxPK[J/ 0, ؓcerts/requireExplicitPolicy4subsubCACert.crtUTІ?UxPK[J/!2/ gcerts/requireExplicitPolicy4subsubsubCACert.crtUTІ?UxPK[J/S|=& certs/requireExplicitPolicy5CACert.crtUTІ?UxPK[J/օ(/) certs/requireExplicitPolicy5subCACert.crtUTІ?UxPK[J//, certs/requireExplicitPolicy5subsubCACert.crtUTІ?UxPK[J/u1/ certs/requireExplicitPolicy5subsubsubCACert.crtUTІ?UxPK[J/k=& =certs/requireExplicitPolicy7CACert.crtUTІ?UxPK[J/FH2<, ӥcerts/requireExplicitPolicy7subCARE2Cert.crtUTІ?UxPK[J/WA2 ncerts/requireExplicitPolicy7subsubCARE2RE4Cert.crtUTІ?UxPK[J/:P55 certs/requireExplicitPolicy7subsubsubCARE2RE4Cert.crtUTІ?UxPK[J/"c"r certs/RevokedsubCACert.crtUTІ?UxPK[J/PZx ]. certs/RFC3280MandatoryAttributeTypesCACert.crtUTІ?UxPK[J/Ռsm- ޲certs/RFC3280OptionalAttributeTypesCACert.crtUTІ?UxPK[J/sD7 certs/RolloverfromPrintableStringtoUTF8StringCACert.crtUTІ?UxPK[J/Y,;Y9B Ycerts/SeparateCertificateandCRLKeysCA2CertificateSigningCACert.crtUTІ?UxPK[J/ ,~8 certs/SeparateCertificateandCRLKeysCA2CRLSigningCert.crtUTІ?UxPK[J/)98? certs/SeparateCertificateandCRLKeysCertificateSigningCACert.crtUTІ?UxPK[J/;N)~5 Hcerts/SeparateCertificateandCRLKeysCRLSigningCert.crtUTІ?UxPK[J/.<$ certs/TrustAnchorRootCertificate.crtUTІ?UxPK[J/](u certs/TwoCRLsCACert.crtUTІ?UxPK[J/Sm(u certs/UIDCACert.crtUTІ?UxPK[J/7z;( certs/UnknownCRLEntryExtensionCACert.crtUTІ?UxPK[J/l3# certs/UnknownCRLExtensionCACert.crtUTІ?UxPK[J/H% certs/UserNoticeQualifierTest15EE.crtUTІ?UxPK[J/.@j% certs/UserNoticeQualifierTest16EE.crtUTІ?UxPK[J/u% certs/UserNoticeQualifierTest17EE.crtUTІ?UxPK[J/]% certs/UserNoticeQualifierTest18EE.crtUTІ?UxPK[J/=o)% certs/UserNoticeQualifierTest19EE.crtUTІ?UxPK[J// scerts/ValidBasicSelfIssuedNewWithOldTest4EE.crtUTІ?UxPK[J/3J=/ certs/ValidBasicSelfIssuedOldWithNewTest1EE.crtUTІ?UxPK[J/<n% certs/ValidCertificatePathTest1EE.crtUTІ?UxPK[J/ ui %certs/ValidcRLIssuerTest28EE.crtUTІ?UxPK[J/NDm certs/ValidcRLIssuerTest29EE.crtUTІ?UxPK[J/Zui certs/ValidcRLIssuerTest30EE.crtUTІ?UxPK[J/7ēkU ucerts/ValidcRLIssuerTest33EE.crtUTІ?UxPK[J/OB* 3certs/ValiddeltaCRLTest2EE.crtUTІ?UxPK[J/\;A* certs/ValiddeltaCRLTest5EE.crtUTІ?UxPK[J/TB* Xcerts/ValiddeltaCRLTest7EE.crtUTІ?UxPK[J//0 vB* certs/ValiddeltaCRLTest8EE.crtUTІ?UxPK[J/+-]' ~certs/ValiddistributionPointTest1EE.crtUTІ?UxPK[J/R' 5 certs/ValiddistributionPointTest4EE.crtUTІ?UxPK[J/ʐʇR' certs/ValiddistributionPointTest5EE.crtUTІ?UxPK[J/"\' certs/ValiddistributionPointTest7EE.crtUTІ?UxPK[J/qu1 Ccerts/ValidDNandRFC822nameConstraintsTest27EE.crtUTІ?UxPK[J/4J( certs/ValidDNnameConstraintsTest11EE.crtUTІ?UxPK[J/V4V( certs/ValidDNnameConstraintsTest14EE.crtUTІ?UxPK[J/,\73( rcerts/ValidDNnameConstraintsTest18EE.crtUTІ?UxPK[J/>I( certs/ValidDNnameConstraintsTest19EE.crtUTІ?UxPK[J/F' certs/ValidDNnameConstraintsTest1EE.crtUTІ?UxPK[J/Whh' D#certs/ValidDNnameConstraintsTest4EE.crtUTІ?UxPK[J/@"_=' &certs/ValidDNnameConstraintsTest5EE.crtUTІ?UxPK[J/GE' (certs/ValidDNnameConstraintsTest6EE.crtUTІ?UxPK[J/dQ) ^+certs/ValidDNSnameConstraintsTest30EE.crtUTІ?UxPK[J/0lpT) .certs/ValidDNSnameConstraintsTest32EE.crtUTІ?UxPK[J/$:3 0certs/ValidGeneralizedTimeCRLnextUpdateTest13EE.crtUTІ?UxPK[J/^dA1 [3certs/ValidGeneralizedTimenotAfterDateTest8EE.crtUTІ?UxPK[J/B2 6certs/ValidGeneralizedTimenotBeforeDateTest4EE.crtUTІ?UxPK[J/Ze.) 8certs/ValidIDPwithindirectCRLTest22EE.crtUTІ?UxPK[J/#G) 1;certs/ValidIDPwithindirectCRLTest24EE.crtUTІ?UxPK[J/̞A) =certs/ValidIDPwithindirectCRLTest25EE.crtUTІ?UxPK[J/J$.& q@certs/ValidinhibitAnyPolicyTest2EE.crtUTІ?UxPK[J/]m8* Bcerts/ValidinhibitPolicyMappingTest2EE.crtUTІ?UxPK[J/&9* Ecerts/ValidinhibitPolicyMappingTest4EE.crtUTІ?UxPK[J/ԥ,) #Hcerts/ValidkeyUsageNotCriticalTest3EE.crtUTІ?UxPK[J//B' Jcerts/ValidLongSerialNumberTest16EE.crtUTІ?UxPK[J/9+@' GMcerts/ValidLongSerialNumberTest17EE.crtUTІ?UxPK[J/!@80 Ocerts/ValidNameChainingCapitalizationTest5EE.crtUTІ?UxPK[J/q@, |Rcerts/ValidNameChainingWhitespaceTest3EE.crtUTІ?UxPK[J/RC, Ucerts/ValidNameChainingWhitespaceTest4EE.crtUTІ?UxPK[J/␄"v Wcerts/ValidNameUIDsTest6EE.crtUTІ?UxPK[J/K4+ 0Zcerts/ValidNegativeSerialNumberTest14EE.crtUTІ?UxPK[J/t\&Z1 \certs/ValidNoissuingDistributionPointTest10EE.crtUTІ?UxPK[J/i6* _certs/ValidonlyContainsCACertsTest13EE.crtUTІ?UxPK[J/bRQ& bcerts/ValidonlySomeReasonsTest18EE.crtUTІ?UxPK[J/%gf& dcerts/ValidonlySomeReasonsTest19EE.crtUTІ?UxPK[J/06( }gcerts/ValidpathLenConstraintTest13EE.crtUTІ?UxPK[J/J@( jcerts/ValidpathLenConstraintTest14EE.crtUTІ?UxPK[J/R,' lcerts/ValidpathLenConstraintTest7EE.crtUTІ?UxPK[J/%>9' /ocerts/ValidpathLenConstraintTest8EE.crtUTІ?UxPK[J/ fv8$ qcerts/ValidPolicyMappingTest11EE.crtUTІ?UxPK[J/y,$ Qtcerts/ValidPolicyMappingTest12EE.crtUTІ?UxPK[J/?4$ wcerts/ValidPolicyMappingTest13EE.crtUTІ?UxPK[J/1$ 0zcerts/ValidPolicyMappingTest14EE.crtUTІ?UxPK[J/do.# |certs/ValidPolicyMappingTest1EE.crtUTІ?UxPK[J/h+$7# <certs/ValidPolicyMappingTest3EE.crtUTІ?UxPK[J/S7# Ɂcerts/ValidPolicyMappingTest5EE.crtUTІ?UxPK[J/xJ5# Vcerts/ValidPolicyMappingTest6EE.crtUTІ?UxPK[J/G,0# certs/ValidPolicyMappingTest9EE.crtUTІ?UxPK[J/(S>- gcerts/Validpre2000UTCnotBeforeDateTest3EE.crtUTІ?UxPK[J/l|>!{ certs/ValidTwoCRLsTest7EE.crtUTІ?UxPK[J/]$~ + vcerts/ValidrequireExplicitPolicyTest1EE.crtUTІ?UxPK[J/Z + certs/ValidrequireExplicitPolicyTest2EE.crtUTІ?UxPK[J/^u4+ pcerts/ValidrequireExplicitPolicyTest4EE.crtUTІ?UxPK[J/ֱdut4 certs/ValidRFC3280MandatoryAttributeTypesTest7EE.crtUTІ?UxPK[J/b3 ݘcerts/ValidRFC3280OptionalAttributeTypesTest8EE.crtUTІ?UxPK[J/*(^, ̛certs/ValidRFC822nameConstraintsTest21EE.crtUTІ?UxPK[J/2P, certs/ValidRFC822nameConstraintsTest23EE.crtUTІ?UxPK[J/ Z, 8certs/ValidRFC822nameConstraintsTest25EE.crtUTІ?UxPK[J/|B> certs/ValidRolloverfromPrintableStringtoUTF8StringTest10EE.crtUTІ?UxPK[J/i:0 certs/ValidSelfIssuedinhibitAnyPolicyTest7EE.crtUTІ?UxPK[J/:0 Acerts/ValidSelfIssuedinhibitAnyPolicyTest9EE.crtUTІ?UxPK[J/ؚ2F4 ޫcerts/ValidSelfIssuedinhibitPolicyMappingTest7EE.crtUTІ?UxPK[J/#%W:2 certs/ValidSelfIssuedpathLenConstraintTest15EE.crtUTІ?UxPK[J/];2 *certs/ValidSelfIssuedpathLenConstraintTest17EE.crtUTІ?UxPK[J/kq;$5 ʳcerts/ValidSelfIssuedrequireExplicitPolicyTest6EE.crtUTІ?UxPK[J/P24 Vcerts/ValidSeparateCertificateandCRLKeysTest19EE.crtUTІ?UxPK[J/]3N< certs/ValidUnknownNotCriticalCertificateExtensionTest1EE.crtUTІ?UxPK[J/D`f) certs/ValidURInameConstraintsTest34EE.crtUTІ?UxPK[J/Xg) ncerts/ValidURInameConstraintsTest36EE.crtUTІ?UxPK[J/6\?\5 1certs/ValidUTF8StringCaseInsensitiveMatchTest11EE.crtUTІ?UxPK[J/2]2, certs/ValidUTF8StringEncodedNamesTest9EE.crtUTІ?UxPK[J//l!v certs/WrongCRLCACert.crtUTІ?UxPKaJ/pTQ certs/DSACACert.crtUTن?UxPKaJ/l& certs/DSAParametersInheritedCACert.crtUTن?UxPKaJ/0;$ certs/InvalidDSASignatureTest6EE.crtUTن?UxPKaJ/6- certs/ValidDSAParameterInheritanceTest5EE.crtUTن?UxPKaJ/AG:# (certs/ValidDSASignaturesTest4EE.crtUTن?UxPK aJ/ Arcrls/UTن?UxPK[J/I(&'= crls/anyPolicyCACRL.crlUTІ?UxPK[J/~3J crls/BadCRLIssuerNameCACRL.crlUTІ?UxPK[J/o-E crls/BadCRLSignatureCACRL.crlUTІ?UxPK[J/-E crls/BadnotAfterDateCACRL.crlUTІ?UxPK[J/I.F crls/BadnotBeforeDateCACRL.crlUTІ?UxPK[J/f'> crls/BadSignedCACRL.crlUTІ?UxPK[J/P>V- crls/basicConstraintsCriticalcAFalseCACRL.crlUTІ?UxPK[J/8Q) 'crls/basicConstraintsNotCriticalCACRL.crlUTІ?UxPK[J//BZ0 crls/basicConstraintsNotCriticalcAFalseCACRL.crlUTІ?UxPK[J/d:Qy* `crls/BasicSelfIssuedCRLSigningKeyCACRL.crlUTІ?UxPK[J/op/ crls/BasicSelfIssuedCRLSigningKeyCRLCertCRL.crlUTІ?UxPK[J/=Jq# crls/BasicSelfIssuedNewKeyCACRL.crlUTІ?UxPK[J/]b~Hq# crls/BasicSelfIssuedOldKeyCACRL.crlUTІ?UxPK[J/?h/ crls/BasicSelfIssuedOldKeySelfIssuedCertCRL.crlUTІ?UxPK[J/Z^ crls/deltaCRLCA1CRL.crlUTІ?UxPK[J/e4a crls/deltaCRLCA1deltaCRL.crlUTІ?UxPK[J/|S @crls/deltaCRLCA2CRL.crlUTІ?UxPK[J/9{Op crls/deltaCRLCA2deltaCRL.crlUTІ?UxPK[J/bFC {crls/deltaCRLCA3CRL.crlUTІ?UxPK[J/| <L crls/deltaCRLCA3deltaCRL.crlUTІ?UxPK[J/FK=\% crls/deltaCRLIndicatorNoBaseCACRL.crlUTІ?UxPK[J/@q (crls/distributionPoint1CACRL.crlUTІ?UxPK[J/Ie crls/distributionPoint2CACRL.crlUTІ?UxPK[J/{BR* crls/GeneralizedTimeCRLnextUpdateCACRL.crlUTІ?UxPK[J/:~ Ccrls/GoodCACRL.crlUTІ?UxPK[J/i%; crls/GoodsubCACRL.crlUTІ?UxPK[J/%<S, /crls/GoodsubCAPanyPolicyMapping1to2CACRL.crlUTІ?UxPK[J/ OLu crls/indirectCRLCA1CRL.crlUTІ?UxPK[J/SgP ccrls/indirectCRLCA3CRL.crlUTІ?UxPK[J/6RNh# crls/indirectCRLCA3cRLIssuerCRL.crlUTІ?UxPK[J/Ri2j# crls/indirectCRLCA4cRLIssuerCRL.crlUTІ?UxPK[J/; ~ crls/indirectCRLCA5CRL.crlUTІ?UxPK[J/ﰳ.E crls/inhibitAnyPolicy0CACRL.crlUTІ?UxPK[J/>G-0E " crls/inhibitAnyPolicy1CACRL.crlUTІ?UxPK[J/"/I# crls/inhibitAnyPolicy1subCA1CRL.crlUTІ?UxPK[J/D.j2I# )crls/inhibitAnyPolicy1subCA2CRL.crlUTІ?UxPK[J/"5L& crls/inhibitAnyPolicy1subCAIAP5CRL.crlUTІ?UxPK[J/_J5L& ?crls/inhibitAnyPolicy1subsubCA2CRL.crlUTІ?UxPK[J/6.E crls/inhibitAnyPolicy5CACRL.crlUTІ?UxPK[J/L?%1H" Mcrls/inhibitAnyPolicy5subCACRL.crlUTІ?UxPK[J/dL4K% crls/inhibitAnyPolicy5subsubCACRL.crlUTІ?UxPK[J/M+X0I# _crls/inhibitPolicyMapping0CACRL.crlUTІ?UxPK[J/<D4L& crls/inhibitPolicyMapping0subCACRL.crlUTІ?UxPK[J/u5M& rcrls/inhibitPolicyMapping1P12CACRL.crlUTІ?UxPK[J/769P) crls/inhibitPolicyMapping1P12subCACRL.crlUTІ?UxPK[J/^h=T- crls/inhibitPolicyMapping1P12subCAIPM5CRL.crlUTІ?UxPK[J/=%7:S, 2!crls/inhibitPolicyMapping1P12subsubCACRL.crlUTІ?UxPK[J/&gp^?W0 "crls/inhibitPolicyMapping1P12subsubCAIPM5CRL.crlUTІ?UxPK[J/E$K5L% m$crls/inhibitPolicyMapping1P1CACRL.crlUTІ?UxPK[J/, @9O( %crls/inhibitPolicyMapping1P1subCACRL.crlUTІ?UxPK[J/:\r:R+ 'crls/inhibitPolicyMapping1P1subsubCACRL.crlUTІ?UxPK[J/8[b/I# &)crls/inhibitPolicyMapping5CACRL.crlUTІ?UxPK[J/w4L& *crls/inhibitPolicyMapping5subCACRL.crlUTІ?UxPK[J/C588O) 8,crls/inhibitPolicyMapping5subsubCACRL.crlUTІ?UxPK[J/ 7R, -crls/inhibitPolicyMapping5subsubsubCACRL.crlUTІ?UxPK[J/xPl9S* b/crls/keyUsageCriticalcRLSignFalseCACRL.crlUTІ?UxPK[J/AODu:W. 0crls/keyUsageCriticalkeyCertSignFalseCACRL.crlUTІ?UxPK[J/.I! 2crls/keyUsageNotCriticalCACRL.crlUTІ?UxPK[J/X $=W- 4crls/keyUsageNotCriticalcRLSignFalseCACRL.crlUTІ?UxPK[J/թ@[1 5crls/keyUsageNotCriticalkeyCertSignFalseCACRL.crlUTІ?UxPK[J/iaU} V7crls/LongSerialNumberCACRL.crlUTІ?UxPK[J/j'@ 8crls/Mapping1to2CACRL.crlUTІ?UxPK[J/TF74J" o:crls/MappingFromanyPolicyCACRL.crlUTІ?UxPK[J/ 0H ;crls/MappingToanyPolicyCACRL.crlUTІ?UxPK[J/t ي4L% {=crls/MissingbasicConstraintsCACRL.crlUTІ?UxPK[J/MA0G ?crls/nameConstraintsDN1CACRL.crlUTІ?UxPK[J/LfJg$ @crls/nameConstraintsDN1subCA1CRL.crlUTІ?UxPK[J/0Y$Ig$ +Bcrls/nameConstraintsDN1subCA2CRL.crlUTІ?UxPK[J/B#Ig$ Ccrls/nameConstraintsDN1subCA3CRL.crlUTІ?UxPK[J/O0G kEcrls/nameConstraintsDN2CACRL.crlUTІ?UxPK[J/mE1G Fcrls/nameConstraintsDN3CACRL.crlUTІ?UxPK[J/84K$ rHcrls/nameConstraintsDN3subCA1CRL.crlUTІ?UxPK[J/ck4K$ Icrls/nameConstraintsDN3subCA2CRL.crlUTІ?UxPK[J/o 1G Kcrls/nameConstraintsDN4CACRL.crlUTІ?UxPK[J/?;/G Mcrls/nameConstraintsDN5CACRL.crlUTІ?UxPK[J/Qw2H! Ncrls/nameConstraintsDNS1CACRL.crlUTІ?UxPK[J/c1H! Pcrls/nameConstraintsDNS2CACRL.crlUTІ?UxPK[J/PU b3K$ Qcrls/nameConstraintsRFC822CA1CRL.crlUTІ?UxPK[J/կ 3K$ #Scrls/nameConstraintsRFC822CA2CRL.crlUTІ?UxPK[J/qW4K$ Tcrls/nameConstraintsRFC822CA3CRL.crlUTІ?UxPK[J/ 2H! 8Vcrls/nameConstraintsURI1CACRL.crlUTІ?UxPK[J/I;1H! Wcrls/nameConstraintsURI2CACRL.crlUTІ?UxPK[J/;ȥ-M CYcrls/NameOrderCACRL.crlUTІ?UxPK[J/|En" Zcrls/NegativeSerialNumberCACRL.crlUTІ?UxPK[J/dO}p8O( t\crls/NoissuingDistributionPointCACRL.crlUTІ?UxPK[J/yx^(? ^crls/NoPoliciesCACRL.crlUTІ?UxPK[J/ܠ2F z_crls/OldCRLnextUpdateCACRL.crlUTІ?UxPK[J/rE_( `crls/onlyContainsAttributeCertsCACRL.crlUTІ?UxPK[J/Ee9>X! bcrls/onlyContainsCACertsCACRL.crlUTІ?UxPK[J/+y?Z# /dcrls/onlyContainsUserCertsCACRL.crlUTІ?UxPK[J/.Pz( ecrls/onlySomeReasonsCA1compromiseCRL.crlUTІ?UxPK[J/i([R{* ogcrls/onlySomeReasonsCA1otherreasonsCRL.crlUTІ?UxPK[J/s@V icrls/onlySomeReasonsCA2CRL1.crlUTІ?UxPK[J/^v=V jcrls/onlySomeReasonsCA2CRL2.crlUTІ?UxPK[J/X( ?lcrls/onlySomeReasonsCA3compromiseCRL.crlUTІ?UxPK[J/ZZ* mcrls/onlySomeReasonsCA3otherreasonsCRL.crlUTІ?UxPK[J/nfc[m( ocrls/onlySomeReasonsCA4compromiseCRL.crlUTІ?UxPK[J/sn* qqcrls/onlySomeReasonsCA4otherreasonsCRL.crlUTІ?UxPK[J/8 V-D  crls/RevokedsubCACRL.crlUTІ?UxPK[J/W!V, Ocrls/RFC3280MandatoryAttributeTypesCACRL.crlUTІ?UxPK[J/XVl+ crls/RFC3280OptionalAttributeTypesCACRL.crlUTІ?UxPK[J/jB_5 crls/RolloverfromPrintableStringtoUTF8StringCACRL.crlUTІ?UxPK[J/Qu4V, xcrls/SeparateCertificateandCRLKeysCA2CRL.crlUTІ?UxPK[J/RMGz) crls/SeparateCertificateandCRLKeysCRL.crlUTІ?UxPK[J/lI8a crls/TrustAnchorRootCRL.crlUTІ?UxPK[J/-V4Al 4crls/TwoCRLsCABadCRL.crlUTІ?UxPK[J/~T%< crls/TwoCRLsCAGoodCRL.crlUTІ?UxPK[J/l^& 1crls/UnknownCRLEntryExtensionCACRL.crlUTІ?UxPK[J/'V! crls/UnknownCRLExtensionCACRL.crlUTІ?UxPK[J/\ j=U, crls/UTF8StringCaseInsensitiveMatchCACRL.crlUTІ?UxPK[J/'>$ .crls/UTF8StringEncodedNamesCACRL.crlUTІ?UxPKU"1lI8a crls/WrongCRLCACRL.crlUT07AUxPKaJ/x{ -crls/DSACACRL.crlUTن?UxPKaJ/)x$ 3crls/DSAParametersInheritedCACRL.crlUTن?UxPK aJ/ Adpkcs12/UTن?UxPK-\J/*]Q+ pkcs12/AllCertificatesanyPolicyTest11EE.p12UTFц?UxPK%\J/,I+ pkcs12/AllCertificatesNoPoliciesTest2EE.p12UT6ц?UxPK,\J/<. pkcs12/AllCertificatesSamePoliciesTest10EE.p12UTDц?UxPK.\J/nF. &pkcs12/AllCertificatesSamePoliciesTest13EE.p12UTHц?UxPK-\J/-n { pkcs12/anyPolicyCACert.p12UTFц?UxPK.\J/Q#M pkcs12/AnyPolicyTest14EE.p12UTHц?UxPK\J/ԓ !  pkcs12/BadCRLIssuerNameCACert.p12UTІ?UxPK\J/RU  pkcs12/BadCRLSignatureCACert.p12UTІ?UxPK[J/n;  pkcs12/BadnotAfterDateCACert.p12UTІ?UxPK[J/i9! & pkcs12/BadnotBeforeDateCACert.p12UTІ?UxPK[J/ mV - pkcs12/BadSignedCACert.p12UTІ?UxPK\J/"0 4 pkcs12/basicConstraintsCriticalcAFalseCACert.p12UTц?UxPK\J/$, 7< pkcs12/basicConstraintsNotCriticalCACert.p12UTц?UxPK\J/[y^3 `C pkcs12/basicConstraintsNotCriticalcAFalseCACert.p12UTц?UxPK\J/1r5- J pkcs12/BasicSelfIssuedCRLSigningKeyCACert.p12UTц?UxPK\J/tcn. Q pkcs12/BasicSelfIssuedCRLSigningKeyCRLCert.p12UTц?UxPK\J/dL& Y pkcs12/BasicSelfIssuedNewKeyCACert.p12UT ц?UxPK\J/qڕ0 ` pkcs12/BasicSelfIssuedNewKeyOldWithNewCACert.p12UT ц?UxPK\J/& g pkcs12/BasicSelfIssuedOldKeyCACert.p12UTц?UxPK\J/wP`]f0 o pkcs12/BasicSelfIssuedOldKeyNewWithOldCACert.p12UTц?UxPK0\J/:& v pkcs12/CPSPointerQualifierTest20EE.p12UTLц?UxPK}\J/J4 8~ pkcs12/deltaCRLCA1Cert.p12UTц?UxPK\J/9N C pkcs12/deltaCRLCA2Cert.p12UTц?UxPK\J/)P M pkcs12/deltaCRLCA3Cert.p12UTц?UxPK|\J/( U pkcs12/deltaCRLIndicatorNoBaseCACert.p12UTц?UxPK.\J/)뺪$ } pkcs12/DifferentPoliciesTest12EE.p12UTHц?UxPK&\J/W # pkcs12/DifferentPoliciesTest3EE.p12UT8ц?UxPK&\J/C`# Ũ pkcs12/DifferentPoliciesTest4EE.p12UT8ц?UxPK'\J/I!=# ߯ pkcs12/DifferentPoliciesTest5EE.p12UT:ц?UxPK*\J/#  pkcs12/DifferentPoliciesTest7EE.p12UT@ц?UxPK+\J/=2 # @ pkcs12/DifferentPoliciesTest8EE.p12UTBц?UxPK,\J/ # z pkcs12/DifferentPoliciesTest9EE.p12UTDц?UxPKj\J/4~# pkcs12/distributionPoint1CACert.p12UTц?UxPKl\J/a5H# pkcs12/distributionPoint2CACert.p12UTц?UxPK \J/^lz- pkcs12/GeneralizedTimeCRLnextUpdateCACert.p12UTц?UxPK[J/zHL  pkcs12/GoodCACert.p12UTІ?UxPK&\J/  pkcs12/GoodsubCACert.p12UT8ц?UxPKD\J/TR?e/ " pkcs12/GoodsubCAPanyPolicyMapping1to2CACert.p12UTpц?UxPKu\J/b  pkcs12/indirectCRLCA1Cert.p12UTц?UxPKv\J/'4X pkcs12/indirectCRLCA2Cert.p12UTц?UxPKx\J/w(E  pkcs12/indirectCRLCA3Cert.p12UTц?UxPKx\J/ÓH$.& pkcs12/indirectCRLCA3cRLIssuerCert.p12UTц?UxPKy\J/ jK ! pkcs12/indirectCRLCA4Cert.p12UTц?UxPKy\J/fl & / pkcs12/indirectCRLCA4cRLIssuerCert.p12UTц?UxPKz\J/ ,# pkcs12/indirectCRLCA5Cert.p12UTц?UxPKz\J/ & :* pkcs12/indirectCRLCA6Cert.p12UTц?UxPKO\J/`" G1 pkcs12/inhibitAnyPolicy0CACert.p12UTц?UxPKP\J/" 8 pkcs12/inhibitAnyPolicy1CACert.p12UTц?UxPKS\J/` , ? pkcs12/inhibitAnyPolicy1SelfIssuedCACert.p12UTц?UxPKU\J/( 0 F pkcs12/inhibitAnyPolicy1SelfIssuedsubCA2Cert.p12UTц?UxPKP\J/50& N pkcs12/inhibitAnyPolicy1subCA1Cert.p12UTц?UxPKT\J/~Pd& 1U pkcs12/inhibitAnyPolicy1subCA2Cert.p12UTц?UxPKS\J/Ou) W\ pkcs12/inhibitAnyPolicy1subCAIAP5Cert.p12UTц?UxPKT\J/M,) c pkcs12/inhibitAnyPolicy1subsubCA2Cert.p12UTц?UxPKQ\J/T F" j pkcs12/inhibitAnyPolicy5CACert.p12UTц?UxPKR\J/糳% r pkcs12/inhibitAnyPolicy5subCACert.p12UTц?UxPKR\J/Ž"( ;y pkcs12/inhibitAnyPolicy5subsubCACert.p12UTц?UxPKQ\J/:0#" m pkcs12/inhibitAnyPolicyTest3EE.p12UTц?UxPKF\J/J5& pkcs12/inhibitPolicyMapping0CACert.p12UTtц?UxPKF\J/) Ǝ pkcs12/inhibitPolicyMapping0subCACert.p12UTtц?UxPKG\J/2) % pkcs12/inhibitPolicyMapping1P12CACert.p12UTvц?UxPKG\J/W[1>, l pkcs12/inhibitPolicyMapping1P12subCACert.p12UTvц?UxPKK\J/]720 pkcs12/inhibitPolicyMapping1P12subCAIPM5Cert.p12UT~ц?UxPKH\J/&/ b pkcs12/inhibitPolicyMapping1P12subsubCACert.p12UTxц?UxPKK\J/Y#!.3 ݳ pkcs12/inhibitPolicyMapping1P12subsubCAIPM5Cert.p12UT~ц?UxPKL\J/.( d pkcs12/inhibitPolicyMapping1P1CACert.p12UTц?UxPKL\J/S2 pkcs12/inhibitPolicyMapping1P1SelfIssuedCACert.p12UTц?UxPKN\J/ɱT 5 pkcs12/inhibitPolicyMapping1P1SelfIssuedsubCACert.p12UTц?UxPKL\J/1UH+ W pkcs12/inhibitPolicyMapping1P1subCACert.p12UTц?UxPKM\J/Æ. pkcs12/inhibitPolicyMapping1P1subsubCACert.p12UTц?UxPKI\J/>j& & pkcs12/inhibitPolicyMapping5CACert.p12UTzц?UxPKI\J/C8`) \ pkcs12/inhibitPolicyMapping5subCACert.p12UTzц?UxPKJ\J/?x, pkcs12/inhibitPolicyMapping5subsubCACert.p12UT|ц?UxPKJ\J/@P1s/ pkcs12/inhibitPolicyMapping5subsubsubCACert.p12UT|ц?UxPK\J/U:) R pkcs12/InvalidBadCRLIssuerNameTest5EE.p12UTІ?UxPK\J/i(  pkcs12/InvalidBadCRLSignatureTest4EE.p12UTІ?UxPK\J/q'5 pkcs12/InvalidBasicSelfIssuedCRLSigningKeyTest7EE.p12UTц?UxPK\J/E5  pkcs12/InvalidBasicSelfIssuedCRLSigningKeyTest8EE.p12UTц?UxPK\J/I0t2 p pkcs12/InvalidBasicSelfIssuedNewWithOldTest5EE.p12UTц?UxPK\J/\2 ! pkcs12/InvalidBasicSelfIssuedOldWithNewTest2EE.p12UTц?UxPK\J/n&, ) pkcs12/InvalidcAFalseTest2EE.p12UTц?UxPK\J/lF @0 pkcs12/InvalidcAFalseTest3EE.p12UTц?UxPK\J/ pkcs12/InvalidCAnotBeforeDateTest1EE.p12UTІ?UxPK[J/$ E pkcs12/InvalidCASignatureTest2EE.p12UTІ?UxPKw\J/&# L pkcs12/InvalidcRLIssuerTest27EE.p12UTц?UxPK{\J/lʈ# YT pkcs12/InvalidcRLIssuerTest31EE.p12UTц?UxPK{\J/q^# O\ pkcs12/InvalidcRLIssuerTest32EE.p12UTц?UxPK|\J/@^DN# ?d pkcs12/InvalidcRLIssuerTest34EE.p12UTц?UxPK|\J/T>:# k pkcs12/InvalidcRLIssuerTest35EE.p12UTц?UxPK}\J/|a?0 s pkcs12/InvaliddeltaCRLIndicatorNoBaseTest1EE.p12UTц?UxPK\J/]~s~" { pkcs12/InvaliddeltaCRLTest10EE.p12UTц?UxPK\J/&QKu~! Ԃ pkcs12/InvaliddeltaCRLTest3EE.p12UTц?UxPK\J/i㥍v~! pkcs12/InvaliddeltaCRLTest4EE.p12UTц?UxPK\J/>~v~! g pkcs12/InvaliddeltaCRLTest6EE.p12UTц?UxPK\J/,s~! 1 pkcs12/InvaliddeltaCRLTest9EE.p12UTц?UxPKk\J/Zf* pkcs12/InvaliddistributionPointTest2EE.p12UTц?UxPKk\J/^f* pkcs12/InvaliddistributionPointTest3EE.p12UTц?UxPKm\J/F? * j pkcs12/InvaliddistributionPointTest6EE.p12UTц?UxPKn\J/r1>* Ӹ pkcs12/InvaliddistributionPointTest8EE.p12UTц?UxPKn\J/jC* a pkcs12/InvaliddistributionPointTest9EE.p12UTц?UxPKf\J/Y.HV4 pkcs12/InvalidDNandRFC822nameConstraintsTest28EE.p12UTц?UxPKf\J/IP^4 @ pkcs12/InvalidDNandRFC822nameConstraintsTest29EE.p12UTц?UxPK[\J/e@+ pkcs12/InvalidDNnameConstraintsTest10EE.p12UTц?UxPK\\J/6.+ g pkcs12/InvalidDNnameConstraintsTest12EE.p12UTц?UxPK\\J/1+ pkcs12/InvalidDNnameConstraintsTest13EE.p12UTц?UxPK]\J/BcH+ L pkcs12/InvalidDNnameConstraintsTest15EE.p12UTц?UxPK`\J/~u+ pkcs12/InvalidDNnameConstraintsTest16EE.p12UTц?UxPK`\J/A+ pkcs12/InvalidDNnameConstraintsTest17EE.p12UTц?UxPKb\J/jƼ+ > pkcs12/InvalidDNnameConstraintsTest20EE.p12UTц?UxPKW\J/* X pkcs12/InvalidDNnameConstraintsTest2EE.p12UTц?UxPKW\J/ם*  pkcs12/InvalidDNnameConstraintsTest3EE.p12UTц?UxPKY\J/S:*  pkcs12/InvalidDNnameConstraintsTest7EE.p12UTц?UxPKZ\J/,* pkcs12/InvalidDNnameConstraintsTest8EE.p12UTц?UxPKZ\J/ג[* *( pkcs12/InvalidDNnameConstraintsTest9EE.p12UTц?UxPKg\J/F!b , v/ pkcs12/InvalidDNSnameConstraintsTest31EE.p12UTц?UxPKh\J/,, 6 pkcs12/InvalidDNSnameConstraintsTest33EE.p12UTц?UxPK\J/|, C> pkcs12/InvalidDNSnameConstraintsTest38EE.p12UTц?UxPK\J/?' E pkcs12/InvalidEEnotAfterDateTest6EE.p12UTІ?UxPK[J/2 ( L pkcs12/InvalidEEnotBeforeDateTest2EE.p12UTІ?UxPK[J/ܢc$ S pkcs12/InvalidEESignatureTest3EE.p12UTІ?UxPKv\J/Y4, Z pkcs12/InvalidIDPwithindirectCRLTest23EE.p12UTц?UxPKw\J/Yq+6, !b pkcs12/InvalidIDPwithindirectCRLTest26EE.p12UTц?UxPKO\J/N) i pkcs12/InvalidinhibitAnyPolicyTest1EE.p12UTц?UxPKQ\J/ ) p pkcs12/InvalidinhibitAnyPolicyTest4EE.p12UTц?UxPKR\J/`) x pkcs12/InvalidinhibitAnyPolicyTest5EE.p12UTц?UxPKS\J/H) ; pkcs12/InvalidinhibitAnyPolicyTest6EE.p12UTц?UxPKG\J/Ĵ- i pkcs12/InvalidinhibitPolicyMappingTest1EE.p12UTvц?UxPKH\J/c;j&- pkcs12/InvalidinhibitPolicyMappingTest3EE.p12UTxц?UxPKJ\J/- pkcs12/InvalidinhibitPolicyMappingTest5EE.p12UT|ц?UxPKK\J/԰ݶ- = pkcs12/InvalidinhibitPolicyMappingTest6EE.p12UT~ц?UxPK$\J/te)5 pkcs12/InvalidkeyUsageCriticalcRLSignFalseTest4EE.p12UT4ц?UxPK"\J/w59 pkcs12/InvalidkeyUsageCriticalkeyCertSignFalseTest1EE.p12UT0ц?UxPK$\J/gۯ8 L pkcs12/InvalidkeyUsageNotCriticalcRLSignFalseTest5EE.p12UT4ц?UxPK"\J/c< pkcs12/InvalidkeyUsageNotCriticalkeyCertSignFalseTest2EE.p12UT0ц?UxPK\J/e+*  pkcs12/InvalidLongSerialNumberTest18EE.p12UT ц?UxPKB\J/NZ- d pkcs12/InvalidMappingFromanyPolicyTest7EE.p12UTlц?UxPKC\J/{+ pkcs12/InvalidMappingToanyPolicyTest8EE.p12UTnц?UxPK\J/ cg0 pkcs12/InvalidMissingbasicConstraintsTest1EE.p12UTц?UxPK\J/fO#  pkcs12/InvalidMissingCRLTest1EE.p12UTІ?UxPK\J/Ӈ&* 9 pkcs12/InvalidNameChainingOrderTest2EE.p12UTІ?UxPK\J/y5% pkcs12/InvalidNameChainingTest1EE.p12UTІ?UxPK \J/Ӏ. pkcs12/InvalidNegativeSerialNumberTest15EE.p12UTц?UxPK \J/J*  pkcs12/InvalidOldCRLnextUpdateTest11EE.p12UTц?UxPKq\J/)R4 G pkcs12/InvalidonlyContainsAttributeCertsTest14EE.p12UTц?UxPKp\J/fׁ- pkcs12/InvalidonlyContainsCACertsTest12EE.p12UTц?UxPKo\J///  pkcs12/InvalidonlyContainsUserCertsTest11EE.p12UTц?UxPKr\J/7)  pkcs12/InvalidonlySomeReasonsTest15EE.p12UTц?UxPKr\J/J,) O pkcs12/InvalidonlySomeReasonsTest16EE.p12UTц?UxPKs\J/C) }& pkcs12/InvalidonlySomeReasonsTest17EE.p12UTц?UxPKt\J/kw) - pkcs12/InvalidonlySomeReasonsTest20EE.p12UTц?UxPKu\J/f) 5 pkcs12/InvalidonlySomeReasonsTest21EE.p12UTц?UxPK\J/+ = pkcs12/InvalidpathLenConstraintTest10EE.p12UT"ц?UxPK\J/ܼu+ E pkcs12/InvalidpathLenConstraintTest11EE.p12UT$ц?UxPK\J/`+ RL pkcs12/InvalidpathLenConstraintTest12EE.p12UT$ц?UxPK\J/Q* S pkcs12/InvalidpathLenConstraintTest5EE.p12UTц?UxPK\J/vx'* Z pkcs12/InvalidpathLenConstraintTest6EE.p12UTц?UxPK\J/;* b pkcs12/InvalidpathLenConstraintTest9EE.p12UT ц?UxPKD\J/q1t' \i pkcs12/InvalidPolicyMappingTest10EE.p12UTpц?UxPK<\J/⋟& p pkcs12/InvalidPolicyMappingTest2EE.p12UTdц?UxPK@\J/|1'& w pkcs12/InvalidPolicyMappingTest4EE.p12UThц?UxPK \J/. ~ pkcs12/Invalidpre2000CRLnextUpdateTest12EE.p12UTц?UxPK\J/GZ;1 . pkcs12/Invalidpre2000UTCEEnotAfterDateTest7EE.p12UTІ?UxPK6\J/Nv. j pkcs12/InvalidrequireExplicitPolicyTest3EE.p12UTXц?UxPK9\J/(. pkcs12/InvalidrequireExplicitPolicyTest5EE.p12UT^ц?UxPK\J/" Л pkcs12/InvalidRevokedCATest2EE.p12UTІ?UxPK\J/Lܼ" pkcs12/InvalidRevokedEETest3EE.p12UTІ?UxPKc\J/8P / pkcs12/InvalidRFC822nameConstraintsTest22EE.p12UTц?UxPKd\J/4/ c pkcs12/InvalidRFC822nameConstraintsTest24EE.p12UTц?UxPKe\J/ d / ظ pkcs12/InvalidRFC822nameConstraintsTest26EE.p12UTц?UxPKV\J/?4 F pkcs12/InvalidSelfIssuedinhibitAnyPolicyTest10EE.p12UTц?UxPKU\J/= t3 { pkcs12/InvalidSelfIssuedinhibitAnyPolicyTest8EE.p12UTц?UxPKN\J/d8 pkcs12/InvalidSelfIssuedinhibitPolicyMappingTest10EE.p12UTц?UxPKO\J/W+8  pkcs12/InvalidSelfIssuedinhibitPolicyMappingTest11EE.p12UTц?UxPKM\J/_77 m pkcs12/InvalidSelfIssuedinhibitPolicyMappingTest8EE.p12UTц?UxPKN\J/n(?7 pkcs12/InvalidSelfIssuedinhibitPolicyMappingTest9EE.p12UTц?UxPK\J/k5 + pkcs12/InvalidSelfIssuedpathLenConstraintTest16EE.p12UT*ц?UxPK;\J/8b8 y pkcs12/InvalidSelfIssuedrequireExplicitPolicyTest7EE.p12UTbц?UxPK;\J/>w8 pkcs12/InvalidSelfIssuedrequireExplicitPolicyTest8EE.p12UTbц?UxPK\J/ .(7 pkcs12/InvalidSeparateCertificateandCRLKeysTest20EE.p12UTц?UxPK\J/We7 Z pkcs12/InvalidSeparateCertificateandCRLKeysTest21EE.p12UTц?UxPK\J/-"< pkcs12/InvalidUnknownCriticalCertificateExtensionTest2EE.p12UTц?UxPK\J/W1 pkcs12/InvalidUnknownCRLEntryExtensionTest8EE.p12UTц?UxPK \J/* - kpkcs12/InvalidUnknownCRLExtensionTest10EE.p12UTц?UxPK\J/! &pkcs12/InvalidWrongCRLTest6EE.p12UTІ?UxPK \J/\n, -pkcs12/InvalidUnknownCRLExtensionTest9EE.p12UTц?UxPKi\J/, 4pkcs12/InvalidURInameConstraintsTest35EE.p12UTц?UxPKj\J/ ʺ, d<pkcs12/InvalidURInameConstraintsTest37EE.p12UTц?UxPK#\J/2- Cpkcs12/keyUsageCriticalcRLSignFalseCACert.p12UT2ц?UxPK!\J/~ \1 Kpkcs12/keyUsageCriticalkeyCertSignFalseCACert.p12UT.ц?UxPK#\J/d$U$ ARpkcs12/keyUsageNotCriticalCACert.p12UT2ц?UxPK$\J/0 \Ypkcs12/keyUsageNotCriticalcRLSignFalseCACert.p12UT4ц?UxPK"\J/H,4 `pkcs12/keyUsageNotCriticalkeyCertSignFalseCACert.p12UT0ц?UxPK \J/!! gpkcs12/LongSerialNumberCACert.p12UT ц?UxPK<\J/%[V npkcs12/Mapping1to2CACert.p12UTdц?UxPKB\J/0% *vpkcs12/MappingFromanyPolicyCACert.p12UTlц?UxPKB\J/E# x}pkcs12/MappingToanyPolicyCACert.p12UTlц?UxPK\J/1( Ƅpkcs12/MissingbasicConstraintsCACert.p12UTц?UxPKV\J/|\$.# ߋpkcs12/nameConstraintsDN1CACert.p12UTц?UxPKa\J/O- Ypkcs12/nameConstraintsDN1SelfIssuedCACert.p12UTц?UxPK[\J/ lv' pkcs12/nameConstraintsDN1subCA1Cert.p12UTц?UxPK\\J/KV' Jpkcs12/nameConstraintsDN1subCA2Cert.p12UTц?UxPKe\J/*]7M&' pkcs12/nameConstraintsDN1subCA3Cert.p12UTц?UxPKX\J/`w~# dpkcs12/nameConstraintsDN2CACert.p12UTц?UxPKX\J/T&.# 1pkcs12/nameConstraintsDN3CACert.p12UTц?UxPK]\J/W()6' pkcs12/nameConstraintsDN3subCA1Cert.p12UTц?UxPK`\J/ԹE' 0pkcs12/nameConstraintsDN3subCA2Cert.p12UTц?UxPKY\J/M%nw~# pkcs12/nameConstraintsDN4CACert.p12UTц?UxPKZ\J/,# jpkcs12/nameConstraintsDN5CACert.p12UTц?UxPKf\J/$ Mpkcs12/nameConstraintsDNS1CACert.p12UTц?UxPKg\J/ k$ pkcs12/nameConstraintsDNS2CACert.p12UTц?UxPKb\J/$' pkcs12/nameConstraintsRFC822CA1Cert.p12UTц?UxPKc\J/.' )pkcs12/nameConstraintsRFC822CA2Cert.p12UTц?UxPKd\J/ ' wpkcs12/nameConstraintsRFC822CA3Cert.p12UTц?UxPKh\J/=X$ pkcs12/nameConstraintsURI1CACert.p12UTц?UxPKi\J/$ pkcs12/nameConstraintsURI2CACert.p12UTц?UxPK\J/A  Wpkcs12/NameOrderingCACert.p12UTІ?UxPK \J/׋% pkcs12/NegativeSerialNumberCACert.p12UTц?UxPK\J/4ɽ pkcs12/NoCRLCACert.p12UTІ?UxPKn\J/˃+ 'pkcs12/NoissuingDistributionPointCACert.p12UTц?UxPK%\J/%Ħ /pkcs12/NoPoliciesCACert.p12UT6ц?UxPK \J/! 5pkcs12/OldCRLnextUpdateCACert.p12UTц?UxPKq\J/ + =pkcs12/onlyContainsAttributeCertsCACert.p12UTц?UxPKp\J/A?$ ;Dpkcs12/onlyContainsCACertsCACert.p12UTц?UxPKo\J/R& YKpkcs12/onlyContainsUserCertsCACert.p12UTц?UxPKq\J/! tRpkcs12/onlySomeReasonsCA1Cert.p12UTц?UxPKr\J/fd! Ypkcs12/onlySomeReasonsCA2Cert.p12UTц?UxPKs\J/vY! `pkcs12/onlySomeReasonsCA3Cert.p12UTц?UxPKt\J/"! gpkcs12/onlySomeReasonsCA4Cert.p12UTц?UxPK(\J/{7% npkcs12/OverlappingPoliciesTest6EE.p12UT<ц?UxPK=\J/DU  #vpkcs12/P12Mapping1to3CACert.p12UTfц?UxPK=\J/ㆭ&" }pkcs12/P12Mapping1to3subCACert.p12UTfц?UxPK=\J/k % pkcs12/P12Mapping1to3subsubCACert.p12UTfц?UxPKE\J/fKVcn' Spkcs12/P1anyPolicyMapping1to2CACert.p12UTrц?UxPK@\J/'\P+6 pkcs12/P1Mapping1to234CACert.p12UThц?UxPKA\J/B^#.# pkcs12/P1Mapping1to234subCACert.p12UTjц?UxPKC\J/Em& pkcs12/PanyPolicyMapping1to2CACert.p12UTnц?UxPK\J/o# \pkcs12/pathLenConstraint0CACert.p12UTц?UxPK\J/%- vpkcs12/pathLenConstraint0SelfIssuedCACert.p12UT(ц?UxPK\J/1i6' pkcs12/pathLenConstraint0subCA2Cert.p12UT*ц?UxPK\J/3Ck& pkcs12/pathLenConstraint0subCACert.p12UTц?UxPK \J/E# pkcs12/pathLenConstraint1CACert.p12UT,ц?UxPK \J/3- pkcs12/pathLenConstraint1SelfIssuedCACert.p12UT,ц?UxPK!\J/n/0 Ipkcs12/pathLenConstraint1SelfIssuedsubCACert.p12UT.ц?UxPK \J/m& pkcs12/pathLenConstraint1subCACert.p12UT,ц?UxPK\J/ϔ6# pkcs12/pathLenConstraint6CACert.p12UTц?UxPK\J/MXR' pkcs12/pathLenConstraint6subCA0Cert.p12UT ц?UxPK\J/ ' pkcs12/pathLenConstraint6subCA1Cert.p12UT"ц?UxPK\J/df' 'pkcs12/pathLenConstraint6subCA4Cert.p12UT&ц?UxPK\J/Z+ Vpkcs12/pathLenConstraint6subsubCA00Cert.p12UT ц?UxPK\J/ȼ2+ pkcs12/pathLenConstraint6subsubCA11Cert.p12UT"ц?UxPK\J/8+ pkcs12/pathLenConstraint6subsubCA41Cert.p12UT&ц?UxPK\J// pkcs12/pathLenConstraint6subsubsubCA11XCert.p12UT$ц?UxPK\J/p/ Epkcs12/pathLenConstraint6subsubsubCA41XCert.p12UT&ц?UxPK'\J/W %pkcs12/PoliciesP1234CACert.p12UT:ц?UxPK(\J/(m% ,pkcs12/PoliciesP1234subCAP123Cert.p12UT<ц?UxPK(\J/a\+ 4pkcs12/PoliciesP1234subsubCAP123P12Cert.p12UT<ц?UxPK)\J/L h;pkcs12/PoliciesP123CACert.p12UT>ц?UxPK)\J/# Bpkcs12/PoliciesP123subCAP12Cert.p12UT>ц?UxPK)\J/'( Ipkcs12/PoliciesP123subsubCAP12P1Cert.p12UT>ц?UxPK+\J/_2( Qpkcs12/PoliciesP123subsubCAP12P2Cert.p12UTBц?UxPK,\J/f- 4Xpkcs12/PoliciesP123subsubsubCAP12P2P1Cert.p12UTDц?UxPK*\J/R q_pkcs12/PoliciesP12CACert.p12UT@ц?UxPK*\J/)B! fpkcs12/PoliciesP12subCAP1Cert.p12UT@ц?UxPK+\J/kW& mpkcs12/PoliciesP12subsubCAP1P2Cert.p12UTBц?UxPK'\J/D+ tpkcs12/PoliciesP2subCA2Cert.p12UT:ц?UxPK%\J/#(>Z {pkcs12/PoliciesP2subCACert.p12UT6ц?UxPK-\J/Z pkcs12/PoliciesP3CACert.p12UTFц?UxPK \J/$% *pkcs12/pre2000CRLnextUpdateCACert.p12UTц?UxPK6\J//!' Npkcs12/requireExplicitPolicy0CACert.p12UTXц?UxPK6\J/4S* pkcs12/requireExplicitPolicy0subCACert.p12UTXц?UxPK7\J/- pkcs12/requireExplicitPolicy0subsubCACert.p12UTZц?UxPK7\J/N>0 pkcs12/requireExplicitPolicy0subsubsubCACert.p12UTZц?UxPK1\J/w( Fpkcs12/requireExplicitPolicy10CACert.p12UTNц?UxPK1\J/EM+ {pkcs12/requireExplicitPolicy10subCACert.p12UTNц?UxPK1\J/:. pkcs12/requireExplicitPolicy10subsubCACert.p12UTNц?UxPK2\J/H+^1 pkcs12/requireExplicitPolicy10subsubsubCACert.p12UTPц?UxPK9\J/TK#' @pkcs12/requireExplicitPolicy2CACert.p12UT^ц?UxPK:\J/F1 xpkcs12/requireExplicitPolicy2SelfIssuedCACert.p12UT`ц?UxPK;\J/ޚ4 pkcs12/requireExplicitPolicy2SelfIssuedsubCACert.p12UTbц?UxPK:\J/f* pkcs12/requireExplicitPolicy2subCACert.p12UT`ц?UxPK4\J/fl' -pkcs12/requireExplicitPolicy4CACert.p12UTTц?UxPK5\J/* cpkcs12/requireExplicitPolicy4subCACert.p12UTVц?UxPK5\J/e - pkcs12/requireExplicitPolicy4subsubCACert.p12UTVц?UxPK5\J/x 0 pkcs12/requireExplicitPolicy4subsubsubCACert.p12UTVц?UxPK3\J/NZz' pkcs12/requireExplicitPolicy5CACert.p12UTRц?UxPK3\J/=* U pkcs12/requireExplicitPolicy5subCACert.p12UTRц?UxPK3\J/#9- pkcs12/requireExplicitPolicy5subsubCACert.p12UTRц?UxPK4\J/J:0 pkcs12/requireExplicitPolicy5subsubsubCACert.p12UTTц?UxPK8\J/6' "pkcs12/requireExplicitPolicy7CACert.p12UT\ц?UxPK8\J/R-- J)pkcs12/requireExplicitPolicy7subCARE2Cert.p12UT\ц?UxPK8\J/U3 0pkcs12/requireExplicitPolicy7subsubCARE2RE4Cert.p12UT\ц?UxPK9\J/4;6 7pkcs12/requireExplicitPolicy7subsubsubCARE2RE4Cert.p12UT^ц?UxPK\J/K.̷ V?pkcs12/RevokedsubCACert.p12UTІ?UxPK\J/_} / [Fpkcs12/RFC3280MandatoryAttributeTypesCACert.p12UTц?UxPK\J/. Mpkcs12/RFC3280OptionalAttributeTypesCACert.p12UTц?UxPK\J/2n8 ?Upkcs12/RolloverfromPrintableStringtoUTF8StringCACert.p12UTц?UxPK\J/hC \pkcs12/SeparateCertificateandCRLKeysCA2CertificateSigningCACert.p12UTц?UxPK\J/jT9 cpkcs12/SeparateCertificateandCRLKeysCA2CRLSigningCert.p12UTц?UxPK\J/֮s@ kpkcs12/SeparateCertificateandCRLKeysCertificateSigningCACert.p12UTц?UxPK\J/c6 Lrpkcs12/SeparateCertificateandCRLKeysCRLSigningCert.p12UTц?UxPK[J/\-% yypkcs12/TrustAnchorRootCertificate.p12UTІ?UxPK\J/b̼ Ypkcs12/TwoCRLsCACert.p12UTІ?UxPK\J/H6 `pkcs12/UIDCACert.p12UTІ?UxPK\J/j) fpkcs12/UnknownCRLEntryExtensionCACert.p12UTц?UxPK \J/3$ pkcs12/UnknownCRLExtensionCACert.p12UTц?UxPK/\J/ v<F& pkcs12/UserNoticeQualifierTest15EE.p12UTJц?UxPK/\J/=& Apkcs12/UserNoticeQualifierTest16EE.p12UTJц?UxPK/\J/Ȱ36& Gpkcs12/UserNoticeQualifierTest17EE.p12UTJц?UxPK0\J/c& ӳpkcs12/UserNoticeQualifierTest18EE.p12UTLц?UxPK0\J/%.& :pkcs12/UserNoticeQualifierTest19EE.p12UTLц?UxPK\J/TR/ pkcs12/UTF8StringCaseInsensitiveMatchCACert.p12UTц?UxPK\J/ OG' pkcs12/UTF8StringEncodedNamesCACert.p12UTц?UxPK\J/C@2 pkcs12/ValidbasicConstraintsNotCriticalTest4EE.p12UTц?UxPK\J/3 Upkcs12/ValidBasicSelfIssuedCRLSigningKeyTest6EE.p12UTц?UxPK\J/ B0 pkcs12/ValidBasicSelfIssuedNewWithOldTest3EE.p12UTц?UxPK\J/l0 pkcs12/ValidBasicSelfIssuedNewWithOldTest4EE.p12UTц?UxPK\J/iN0 @pkcs12/ValidBasicSelfIssuedOldWithNewTest1EE.p12UTц?UxPK[J/ ƶ& pkcs12/ValidCertificatePathTest1EE.p12UTІ?UxPKx\J/sά! pkcs12/ValidcRLIssuerTest28EE.p12UTц?UxPKy\J/.M\f! pkcs12/ValidcRLIssuerTest29EE.p12UTц?UxPKz\J/D5˰! Gpkcs12/ValidcRLIssuerTest30EE.p12UTц?UxPK{\J/|w! Kpkcs12/ValidcRLIssuerTest33EE.p12UTц?UxPK}\J/q .ov >pkcs12/ValiddeltaCRLTest2EE.p12UTц?UxPK\J/Vov %pkcs12/ValiddeltaCRLTest5EE.p12UTц?UxPK\J/Vlv -pkcs12/ValiddeltaCRLTest7EE.p12UTц?UxPK\J/Chv ~5pkcs12/ValiddeltaCRLTest8EE.p12UTц?UxPKk\J/)]f( 8=pkcs12/ValiddistributionPointTest1EE.p12UTц?UxPKl\J/ ( Dpkcs12/ValiddistributionPointTest4EE.p12UTц?UxPKl\J/dQ ( VLpkcs12/ValiddistributionPointTest5EE.p12UTц?UxPKm\J/n|9Zf( Spkcs12/ValiddistributionPointTest7EE.p12UTц?UxPKe\J/:mOV2 s[pkcs12/ValidDNandRFC822nameConstraintsTest27EE.p12UTц?UxPK[\J/B ) 'cpkcs12/ValidDNnameConstraintsTest11EE.p12UTц?UxPK]\J/) jpkcs12/ValidDNnameConstraintsTest14EE.p12UTц?UxPKa\J/6 Q$ pkcs12/ValidPolicyMappingTest1EE.p12UTdц?UxPK@\J/A~9$ pkcs12/ValidPolicyMappingTest3EE.p12UThц?UxPKA\J/4I$ Ґpkcs12/ValidPolicyMappingTest5EE.p12UTjц?UxPKA\J/~2$ pkcs12/ValidPolicyMappingTest6EE.p12UTjц?UxPKC\J/ $ %pkcs12/ValidPolicyMappingTest9EE.p12UTnц?UxPK[J/ᮭl. Opkcs12/Validpre2000UTCnotBeforeDateTest3EE.p12UTІ?UxPK\J//r {pkcs12/ValidTwoCRLsTest7EE.p12UTц?UxPK2\J/P=/, pkcs12/ValidrequireExplicitPolicyTest1EE.p12UTPц?UxPK4\J/d, pkcs12/ValidrequireExplicitPolicyTest2EE.p12UTTц?UxPK7\J/*", pkcs12/ValidrequireExplicitPolicyTest4EE.p12UTZц?UxPK\J/X+65 %pkcs12/ValidRFC3280MandatoryAttributeTypesTest7EE.p12UTц?UxPK\J/4>4 pkcs12/ValidRFC3280OptionalAttributeTypesTest8EE.p12UTц?UxPKb\J/%ɐ- Spkcs12/ValidRFC822nameConstraintsTest21EE.p12UTц?UxPKc\J/ks - pkcs12/ValidRFC822nameConstraintsTest23EE.p12UTц?UxPKd\J/ - 0pkcs12/ValidRFC822nameConstraintsTest25EE.p12UTц?UxPK\J/2? pkcs12/ValidRolloverfromPrintableStringtoUTF8StringTest10EE.p12UTц?UxPKT\J/Q1 pkcs12/ValidSelfIssuedinhibitAnyPolicyTest7EE.p12UTц?UxPKU\J/1 Spkcs12/ValidSelfIssuedinhibitAnyPolicyTest9EE.p12UTц?UxPKM\J/5 pkcs12/ValidSelfIssuedinhibitPolicyMappingTest7EE.p12UTц?UxPK\J/c3 pkcs12/ValidSelfIssuedpathLenConstraintTest15EE.p12UT*ц?UxPK!\J/Y3 =pkcs12/ValidSelfIssuedpathLenConstraintTest17EE.p12UT.ц?UxPK:\J/K6 pkcs12/ValidSelfIssuedrequireExplicitPolicyTest6EE.p12UT`ц?UxPK\J/]5 "pkcs12/ValidSeparateCertificateandCRLKeysTest19EE.p12UTц?UxPK\J/EXQ= *pkcs12/ValidUnknownNotCriticalCertificateExtensionTest1EE.p12UTц?UxPKi\J/4Â]&* v1pkcs12/ValidURInameConstraintsTest34EE.p12UTц?UxPKj\J/&* 8pkcs12/ValidURInameConstraintsTest36EE.p12UTц?UxPK\J/6 h@pkcs12/ValidUTF8StringCaseInsensitiveMatchTest11EE.p12UTц?UxPK\J/P- Gpkcs12/ValidUTF8StringEncodedNamesTest9EE.p12UTц?UxPK\J/|϶[ Opkcs12/WrongCRLCACert.p12UTІ?UxPK aJ/w@OU Vpkcs12/DSACACert.p12UTن?UxPK aJ/' \pkcs12/DSAParametersInheritedCACert.p12UTن?UxPK aJ/A% apkcs12/InvalidDSASignatureTest6EE.p12UTن?UxPK aJ/j. hpkcs12/ValidDSAParameterInheritanceTest5EE.p12UTن?UxPK aJ/M&|$ npkcs12/ValidDSASignaturesTest4EE.p12UTن?UxPK j["1 Ausmime/UT;7AUxPK\J/jV$. usmime/SignedAllCertificatesAnyPolicyTest11.emlUT҆?UxPK\J/jff .  smime/SignedAllCertificatesNoPoliciesTest2.emlUT ҆?UxPK\J/| v1 8smime/SignedAllCertificatesSamePoliciesTest10.emlUT ҆?UxPK\J/}Ġ. 1 smime/SignedAllCertificatesSamePoliciesTest13.emlUT҆?UxPK\J/|HE. Lsmime/SignedAllCertificatesSamePolicyTest1.emlUT ҆?UxPK\J/f\ smime/SignedAnyPolicyTest14.emlUT҆?UxPK\J/xd ) smime/SignedCPSPointerQualifierTest20.emlUT҆?UxPK\J/l,' smime/SignedDifferentPoliciesTest12.emlUT҆?UxPK\J/d7&-F & smime/SignedDifferentPoliciesTest3.emlUT ҆?UxPKtY"13 q& [smime/SignedDifferentPoliciesTest4.emlUT+87AUxPK\J/)~ & Asmime/SignedDifferentPoliciesTest5.emlUT ҆?UxPK\J/ 삳E& 8smime/SignedDifferentPoliciesTest7.emlUT ҆?UxPK\J/ & smime/SignedDifferentPoliciesTest8.emlUT ҆?UxPK\J/\n{s& smime/SignedDifferentPoliciesTest9.emlUT ҆?UxPK\J/{  % smime/SignedinhibitAnyPolicyTest3.emlUT҆?UxPK\J/W` Z, smime/SignedInvalidBadCRLIssuerNameTest5.emlUTц?UxPK\J/VіF+ W'smime/SignedInvalidBadCRLSignatureTest4.emlUTц?UxPK\J/I 8 0smime/SignedInvalidBasicSelfIssuedCRLSigningKeyTest7.emlUT҆?UxPK\J/"ύ 8 <smime/SignedInvalidBasicSelfIssuedCRLSigningKeyTest8.emlUT҆?UxPK\J/3n s5 SIsmime/SignedInvalidBasicSelfIssuedNewWithOldTest5.emlUT҆?UxPKY"1ER M5 hUsmime/SignedInvalidBasicSelfIssuedOldWithNewTest2.emlUT87AUxPK\J/7 # `smime/SignedInvalidcAFalseTest2.emlUT҆?UxPK\J/z # 4jsmime/SignedInvalidcAFalseTest3.emlUT҆?UxPK\J/{ E* ssmime/SignedInvalidCAnotAfterDateTest5.emlUTц?UxPK\J/1KL+ }smime/SignedInvalidCAnotBeforeDateTest1.emlUTц?UxPK\J/Bv' smime/SignedInvalidCASignatureTest2.emlUTц?UxPK\J/VI4 5& smime/SignedInvalidcRLIssuerTest27.emlUT6҆?UxPK\J/; o& smime/SignedInvalidcRLIssuerTest31.emlUT8҆?UxPK\J/RE o& Jsmime/SignedInvalidcRLIssuerTest32.emlUT8҆?UxPK\J/i+| & |smime/SignedInvalidcRLIssuerTest34.emlUT:҆?UxPK\J/| & Qsmime/SignedInvalidcRLIssuerTest35.emlUT:҆?UxPK\J/! 3 &smime/SignedInvaliddeltaCRLIndicatorNoBaseTest1.emlUT:҆?UxPK\J/, 3% smime/SignedInvaliddeltaCRLTest10.emlUT>҆?UxPK\J/o $ smime/SignedInvaliddeltaCRLTest3.emlUT:҆?UxPK\J/k $ smime/SignedInvaliddeltaCRLTest4.emlUT<҆?UxPK\J/2}m $ smime/SignedInvaliddeltaCRLTest6.emlUT<҆?UxPK\J/#n' $ ]smime/SignedInvaliddeltaCRLTest9.emlUT>҆?UxPK\J/{G - smime/SignedInvaliddistributionPointTest2.emlUT.҆?UxPK\J/7^} - ?smime/SignedInvaliddistributionPointTest3.emlUT.҆?UxPK\J/19- smime/SignedInvaliddistributionPointTest6.emlUT0҆?UxPK\J/?`- N- #smime/SignedInvaliddistributionPointTest8.emlUT0҆?UxPK\J/xH- ,smime/SignedInvaliddistributionPointTest9.emlUT0҆?UxPK\J/!P 7 5smime/SignedInvalidDNandRFC822nameConstraintsTest28.emlUT*҆?UxPK\J/:ۨO 7 Bsmime/SignedInvalidDNandRFC822nameConstraintsTest29.emlUT,҆?UxPK\J/(/: . :Osmime/SignedInvalidDNnameConstraintsTest10.emlUT$҆?UxPK\J/@j[J . Xsmime/SignedInvalidDNnameConstraintsTest12.emlUT&҆?UxPK\J/P@ h. esmime/SignedInvalidDNnameConstraintsTest13.emlUT&҆?UxPK\J/S . !rsmime/SignedInvalidDNnameConstraintsTest15.emlUT&҆?UxPK\J/YwZ . ~smime/SignedInvalidDNnameConstraintsTest16.emlUT&҆?UxPK\J/Fے . smime/SignedInvalidDNnameConstraintsTest17.emlUT(҆?UxPK\J/Tf# - smime/SignedInvalidDNnameConstraintsTest2.emlUT"҆?UxPK\J/: - csmime/SignedInvalidDNnameConstraintsTest3.emlUT"҆?UxPK\J/=nY - Xsmime/SignedInvalidDNnameConstraintsTest7.emlUT$҆?UxPK\J/ O c- smime/SignedInvalidDNnameConstraintsTest8.emlUT$҆?UxPK\J/HO c- smime/SignedInvalidDNnameConstraintsTest9.emlUT$҆?UxPK\J/U/ osmime/SignedInvalidDNSnameConstraintsTest31.emlUT,҆?UxPK\J/5N / smime/SignedInvalidDNSnameConstraintsTest33.emlUT,҆?UxPK\J/S/ bsmime/SignedInvalidDNSnameConstraintsTest38.emlUT@҆?UxPK\J/F.* _* smime/SignedInvalidEEnotAfterDateTest6.emlUTц?UxPK\J/Y7:: `+ smime/SignedInvalidEEnotBeforeDateTest2.emlUTц?UxPK\J/D©=' smime/SignedInvalidEESignatureTest3.emlUTц?UxPK\J/\ts' |/  smime/SignedInvalidIDPwithindirectCRLTest23.emlUT6҆?UxPK\J/Q Z/  smime/SignedInvalidIDPwithindirectCRLTest26.emlUT6҆?UxPK\J/b' g, smime/SignedInvalidinhibitAnyPolicyTest1.emlUT҆?UxPK\J/\} , &smime/SignedInvalidinhibitAnyPolicyTest4.emlUT҆?UxPK\J/N~Q , 1*smime/SignedInvalidinhibitAnyPolicyTest5.emlUT҆?UxPK\J/ƣ , 8smime/SignedInvalidinhibitAnyPolicyTest6.emlUT ҆?UxPK\J/Cu !0 Dsmime/SignedInvalidinhibitPolicyMappingTest1.emlUT҆?UxPK\J/Nlz90 Psmime/SignedInvalidinhibitPolicyMappingTest3.emlUT҆?UxPK\J/5;@0 _smime/SignedInvalidinhibitPolicyMappingTest5.emlUT҆?UxPK\J/Fy0 psmime/SignedInvalidinhibitPolicyMappingTest6.emlUT҆?UxPK\J/, 8 smime/SignedInvalidkeyUsageCriticalcRLSignFalseTest4.emlUT҆?UxPK\J/ %V/ < Gsmime/SignedInvalidkeyUsageCriticalkeyCertSignFalseTest1.emlUT҆?UxPK\J/w1> ; smime/SignedInvalidkeyUsageNotCriticalcRLSignFalseTest5.emlUT ҆?UxPK\J/5 ? smime/SignedInvalidkeyUsageNotCriticalkeyCertSignFalseTest2.emlUT҆?UxPK\J/sG - 8smime/SignedInvalidLongSerialNumberTest18.emlUT҆?UxPK\J/I? 0 smime/SignedInvalidMappingFromanyPolicyTest7.emlUT҆?UxPK\J/Kk. @smime/SignedInvalidMappingToanyPolicyTest8.emlUT҆?UxPK\J/g3 msmime/SignedInvalidMissingbasicConstraintsTest1.emlUT҆?UxPK\J/Ԏ|g* smime/SignedInvalidNameChainingEETest1.emlUTц?UxPK\J/-Ap - smime/SignedInvalidNameChainingOrderTest2.emlUTц?UxPK\J/% 1 }smime/SignedInvalidNegativeSerialNumberTest15.emlUTц?UxPK\J/twR- smime/SignedInvalidOldCRLnextUpdateTest11.emlUTц?UxPK\J/z\,7 <smime/SignedInvalidonlyContainsAttributeCertsTest14.emlUT2҆?UxPK\J/ó) s3 smime/SignedInvalidonlyContainsCACertsCRLTest12.emlUT2҆?UxPK\J/SXw5 &smime/SignedInvalidonlyContainsUserCertsCRLTest11.emlUT2҆?UxPK\J/sW ,  smime/SignedInvalidonlySomeReasonsTest15.emlUT2҆?UxPK\J/A , smime/SignedInvalidonlySomeReasonsTest16.emlUT2҆?UxPK\J/w] +, !smime/SignedInvalidonlySomeReasonsTest17.emlUT4҆?UxPK\J/Æ , +smime/SignedInvalidonlySomeReasonsTest20.emlUT4҆?UxPK\J/kȄ , 6smime/SignedInvalidonlySomeReasonsTest21.emlUT4҆?UxPK\J/‚ . Asmime/SignedInvalidpathLenConstraintTest10.emlUT҆?UxPK\J/X!m. Osmime/SignedInvalidpathLenConstraintTest11.emlUT҆?UxPK\J/I>#]. `smime/SignedInvalidpathLenConstraintTest12.emlUT҆?UxPK\J/. - qsmime/SignedInvalidpathLenConstraintTest5.emlUT҆?UxPK\J/#D - |}smime/SignedInvalidpathLenConstraintTest6.emlUT҆?UxPK\J/ȶ - [smime/SignedInvalidpathLenConstraintTest9.emlUT҆?UxPK\J/ֈ= 0* qsmime/SignedInvalidPolicyMappingTest10.emlUT҆?UxPK\J/,[e= q) psmime/SignedInvalidPolicyMappingTest2.emlUT҆?UxPK\J/@)  smime/SignedInvalidPolicyMappingTest4.emlUT҆?UxPK\J/э|+ r1 smime/SignedInvalidpre2000CRLnextUpdateTest12.emlUTц?UxPK\J/7L,{4 vsmime/SignedInvalidpre2000UTCEEnotAfterDateTest7.emlUTц?UxPK\J/z1 smime/SignedInvalidRequireExplicitPolicyTest3.emlUT҆?UxPK\J/Wu1 0smime/SignedInvalidRequireExplicitPolicyTest5.emlUT҆?UxPK\J/bgJ e%  smime/SignedInvalidRevokedCATest2.emlUTц?UxPK\J/a4}s M% smime/SignedInvalidRevokedEETest3.emlUTц?UxPKY"1$ўo 2 smime/SignedInvalidRFC822nameConstraintsTest22.emlUT87AUxPK\J/)C2 smime/SignedInvalidRFC822nameConstraintsTest24.emlUT*҆?UxPK Z"1[ 2 Rsmime/SignedInvalidRFC822nameConstraintsTest26.emlUTA97AUxPK\J/+ 8 "smime/SignedInvalidSelfIssuedDNnameConstraintsTest20.emlUT(҆?UxPK\J/1pv 7 +smime/SignedInvalidSelfIssuedinhibitAnyPolicyTest10.emlUT ҆?UxPK\J/i8 K6 q9smime/SignedInvalidSelfIssuedinhibitAnyPolicyTest8.emlUT ҆?UxPK\J/J; Ismime/SignedInvalidSelfIssuedinhibitPolicyMappingTest10.emlUT҆?UxPK\J/1; +Ysmime/SignedInvalidSelfIssuedinhibitPolicyMappingTest11.emlUT҆?UxPK\J/orkq: hsmime/SignedInvalidSelfIssuedinhibitPolicyMappingTest8.emlUT҆?UxPK\J/tq: xsmime/SignedInvalidSelfIssuedinhibitPolicyMappingTest9.emlUT҆?UxPK\J/PcN 38 smime/SignedInvalidSelfIssuedpathLenConstraintTest16.emlUT҆?UxPK\J/eWS V; smime/SignedInvalidSelfIssuedrequireExplicitPolicyTest7.emlUT҆?UxPK\J/; Osmime/SignedInvalidSelfIssuedrequireExplicitPolicyTest8.emlUT҆?UxPK\J/v' g: smime/SignedInvalidSeparateCertificateandCRLKeysTest20.emlUTB҆?UxPK\J/ 9刯 5: smime/SignedInvalidSeparateCertificateandCRLKeysTest21.emlUTB҆?UxPK\J/֨NS ? smime/SignedInvalidUnknownCriticalCertificateExtensionTest2.emlUT>҆?UxPK\J/{6.L 4 smime/SignedInvalidUnknownCRLEntryExtensionTest8.emlUTц?UxPK\J/  0 @smime/SignedInvalidUnknownCRLExtensionTest10.emlUTц?UxPK\J/: / smime/SignedInvalidUnknownCRLExtensionTest9.emlUTц?UxPK\J/s nX / Ysmime/SignedInvalidURInameConstraintsTest35.emlUT.҆?UxPK\J/Gg/ smime/SignedInvalidURInameConstraintsTest37.emlUT.҆?UxPK\J/j $ Msmime/SignedInvalidWrongCRLTest6.emlUTц?UxPK\J/H   smime/SignedMissingCRLTest1.emlUTц?UxPK\J/;(;{( smime/SignedOverlappingPoliciesTest6.emlUT ҆?UxPK\J/wd,Z ) > smime/SignedUserNoticeQualifierTest15.emlUT҆?UxPK\J/+G޵ ) &smime/SignedUserNoticeQualifierTest16.emlUT҆?UxPK\J/Ϲ6u ) 0smime/SignedUserNoticeQualifierTest17.emlUT҆?UxPK\J/bw ) :smime/SignedUserNoticeQualifierTest18.emlUT҆?UxPK\J/m% ) Esmime/SignedUserNoticeQualifierTest19.emlUT҆?UxPK\J/5 Lsmime/SignedValidbasicConstraintsNotCriticalTest4.emlUT҆?UxPK\J/p/ 6 Usmime/SignedValidBasicSelfIssuedCRLSigningKeyTest6.emlUT҆?UxPK\J/nL m3 :bsmime/SignedValidBasicSelfIssuedNewWithOldTest3.emlUT҆?UxPK\J/b6 m3 ensmime/SignedValidBasicSelfIssuedNewWithOldTest4.emlUT҆?UxPK\J/H + G3 zsmime/SignedValidBasicSelfIssuedOldWithNewTest1.emlUT҆?UxPK\J/ͭm c$ smime/SignedValidcRLIssuerTest28.emlUT8҆?UxPK\J/gH' $ ksmime/SignedValidcRLIssuerTest29.emlUT8҆?UxPK\J/MJ# $ smime/SignedValidcRLIssuerTest30.emlUT8҆?UxPK\J/&G m$ csmime/SignedValidcRLIssuerTest33.emlUT:҆?UxPK\J/lR3 |" smime/SignedValiddeltaCRLTest2.emlUT:҆?UxPK\J/7 |" 3smime/SignedValiddeltaCRLTest5.emlUT<҆?UxPK\J/$#6 |" smime/SignedValiddeltaCRLTest7.emlUT<҆?UxPK\J/1 " Jsmime/SignedValiddeltaCRLTest8.emlUT<҆?UxPK\J/5: + smime/SignedValiddistributionPointTest1.emlUT.҆?UxPK\J/lF + @smime/SignedValiddistributionPointTest4.emlUT0҆?UxPK\J/W>vW + smime/SignedValiddistributionPointTest5.emlUT0҆?UxPK\J/( + smime/SignedValiddistributionPointTest7.emlUT0҆?UxPK\J/.Tu w5 smime/SignedValidDNandRFC822nameConstraintsTest27.emlUT*҆?UxPK\J/V15 + smime/SignedValidDNnameConstraintsTest1.emlUT"҆?UxPK\J/ ^ , smime/SignedValidDNnameConstraintsTest11.emlUT$҆?UxPK\J/tQxI ,, L'smime/SignedValidDNnameConstraintsTest14.emlUT&҆?UxPK\J/v x, 3smime/SignedValidDNnameConstraintsTest18.emlUT(҆?UxPK\J/u2Q [+ ?smime/SignedValidDNnameConstraintsTest4.emlUT"҆?UxPK\J/}Y ++ Ismime/SignedValidDNnameConstraintsTest5.emlUT"҆?UxPK\J/^*^ + Ssmime/SignedValidDNnameConstraintsTest6.emlUT"҆?UxPK\J/zj - D]smime/SignedValidDNSnameConstraintsTest30.emlUT,҆?UxPK\J/.dt - gsmime/SignedValidDNSnameConstraintsTest32.emlUT,҆?UxPK\J/6): 7 psmime/SignedValidGeneralizedTimeCRLnextUpdateTest13.emlUTц?UxPK\J/ P> z5 zsmime/SignedValidGeneralizedTimenotAfterDateTest8.emlUTц?UxPK\J/{6 ,smime/SignedValidGeneralizedTimenotBeforeDateTest4.emlUTц?UxPK\J/siۼ ! msmime/SignedValidTwoCRLsTest7.emlUTц?UxPK\J/k z- }smime/SignedValidIDPwithindirectCRLTest22.emlUT6҆?UxPK\J/%ԭ T- smime/SignedValidIDPwithindirectCRLTest24.emlUT6҆?UxPK\J/Vȟ T- smime/SignedValidIDPwithindirectCRLTest25.emlUT6҆?UxPK\J/Q u* smime/SignedValidinhibitAnyPolicyTest2.emlUT҆?UxPK\J/;q y. smime/SignedValidinhibitPolicyMappingTest2.emlUT҆?UxPK\J/;b{3. smime/SignedValidinhibitPolicyMappingTest4.emlUT҆?UxPK\J/wv^- smime/SignedValidkeyUsageNotCriticalTest3.emlUT҆?UxPK\J/R8 + smime/SignedValidLongSerialNumberTest16.emlUTц?UxPK\J/S8 + smime/SignedValidLongSerialNumberTest17.emlUTц?UxPK\J/To8 u4  smime/SignedValidNameChainingCapitalizationTest5.emlUTц?UxPK\J/zKb * smime/SignedValidNameChainingUIDsTest6.emlUTц?UxPK\J/U y0  smime/SignedValidNameChainingWhitespaceTest3.emlUTц?UxPK\J/0&J }0 smime/SignedValidNameChainingWhitespaceTest4.emlUTц?UxPK\J/ 9e / smime/SignedValidNegativeSerialNumberTest14.emlUTц?UxPK\J/M9F 55 ='smime/SignedValidNoissuingDistributionPointTest10.emlUT2҆?UxPK\J/ 1 0smime/SignedValidonlyContainsCACertsCRLTest13.emlUT2҆?UxPK\J/(u J * :smime/SignedValidonlySomeReasonsTest18.emlUT4҆?UxPK\J/3X҉ * Esmime/SignedValidonlySomeReasonsTest19.emlUT4҆?UxPK\J/P|g, Osmime/SignedValidpathLenConstraintTest13.emlUT҆?UxPK\J/ro, `smime/SignedValidpathLenConstraintTest14.emlUT҆?UxPK\J/48 N+ qsmime/SignedValidpathLenConstraintTest7.emlUT҆?UxPK\J/(b+ {smime/SignedValidpathLenConstraintTest8.emlUT҆?UxPK\J/k' /smime/SignedValidPolicyMappingTest1.emlUT҆?UxPK\J/`Y *( zsmime/SignedValidPolicyMappingTest11.emlUT҆?UxPK\J/DH ( Ιsmime/SignedValidPolicyMappingTest12.emlUT҆?UxPK\J/zB ( Hsmime/SignedValidPolicyMappingTest13.emlUT҆?UxPK\J/оD ( smime/SignedValidPolicyMappingTest14.emlUT҆?UxPKZ"1 =' smime/SignedValidPolicyMappingTest3.emlUTI:7AUxPK\J/6uŇ ' ]smime/SignedValidPolicyMappingTest5.emlUT҆?UxPK\J/[ ' smime/SignedValidPolicyMappingTest6.emlUT҆?UxPK\J/'4' smime/SignedValidPolicyMappingTest9.emlUT҆?UxPK\J/ o1 Ismime/SignedValidpre2000UTCnotBeforeDateTest3.emlUTц?UxPK\J/ܘx/ rsmime/SignedValidRequireExplicitPolicyTest1.emlUT҆?UxPK\J/%G/ Lsmime/SignedValidRequireExplicitPolicyTest2.emlUT҆?UxPK\J/ R[/ smime/SignedValidRequireExplicitPolicyTest4.emlUT҆?UxPK\J/ 8 %smime/SignedValidRFC3280MandatoryAttributeTypesTest7.emlUT>҆?UxPK\J/v 17 /smime/SignedValidRFC3280OptionalAttributeTypesTest8.emlUT@҆?UxPK\J/Д 0 9smime/SignedValidRFC822nameConstraintsTest21.emlUT(҆?UxPK\J/ɪhI 0 Csmime/SignedValidRFC822nameConstraintsTest23.emlUT*҆?UxPK\J/,$A 0 yMsmime/SignedValidRFC822nameConstraintsTest25.emlUT*҆?UxPK\J/5 B eWsmime/SignedValidRolloverfromPrintableStringtoUTF8StringTest10.emlUT@҆?UxPK\J/E! ~6 asmime/SignedValidSelfIssuedDNnameConstraintsTest19.emlUT(҆?UxPK\J/&z ;4 Mlsmime/SignedValidSelfIssuedinhibitAnyPolicyTest7.emlUT ҆?UxPK\J/4 Izsmime/SignedValidSelfIssuedinhibitAnyPolicyTest9.emlUT ҆?UxPKZ"1CH\v 8 smime/SignedValidSelfIssuedinhibitPolicyMappingTest7.emlUTy:7AUxPK\J/cz{ 6 smime/SignedValidSelfIssuedpathLenConstraintTest15.emlUT҆?UxPK\J/Db6 smime/SignedValidSelfIssuedpathLenConstraintTest17.emlUT҆?UxPK\J/'n 9 Osmime/SignedValidSelfIssuedrequireExplicitPolicyTest6.emlUT҆?UxPK\J/X+ e8 smime/SignedValidSeparateCertificateandCRLKeysTest19.emlUT@҆?UxPK\J/J~9$ smime/SignedValidSignaturesTest1.emlUTц?UxPK\J/QDIQ @ Ismime/SignedValidUnknownNotCriticalCertificateExtensionTest1.emlUT>҆?UxPK\J/> V] - smime/SignedValidURInameConstraintsTest34.emlUT,҆?UxPK\J/)[ - smime/SignedValidURInameConstraintsTest36.emlUT.҆?UxPK\J/ 9 smime/SignedValidUTF8StringCaseInsensitiveMatchTest11.emlUT@҆?UxPK\J/ٓ'+0 Hsmime/SignedValidUTF8StringEncodedNamesTest9.emlUT@҆?UxPK$aJ/[~ɷ ( smime/SignedInvalidDSASignatureTest6.emlUTن?UxPK$aJ/Vpy 1 smime/SignedValidDSAParameterInheritanceTest5.emlUTن?UxPK$aJ/} ' smime/SignedValidDSASignaturesTest4.emlUTن?UxPKV"1QU &[ [pkits.ldifUT47AUxPKY"1I#> Cpkits.schemaUTy77AUxPKKJ/]w DReadMe.txtUT?UxPKEheimdal-7.5.0/lib/hx509/data/kdc.key0000644000175000017500000000162412136107750015066 0ustar niknik-----BEGIN PRIVATE KEY----- MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBANJBevhLVbKvEflD m0OBCTualM8A9IV1ktcqpRHxqFBuxoR0JBfahMgDN7Ig87q1WTYhTatw4sMJk2gU EnnFu54bSvDGJFklwxyocGZbPkGO4yVxmpSgW0aRb91YFOyJ5YyWxThg5Kvyde5u YvzhvQNH/8S+D8pwc+N0WDovBC05AgMBAAECgYAw4vS6opmMcFRXhralHW2OJEUR VIGGPm4kBVBYOb4O5ZLW3UI/IZnZ/5WFn0/MS7owcdHjWN4Ax0s02eXp1mXm0sua gr6JuWTTv5y2Vjrq2AQ9RqNIaRp346gbtqt2/Nhoyl3BMcVPuq69WcbDVq+GPNE5 K5plwS32AQJsceitWQJBAP6M2xJ4cOh3keOOfYnVvoBRsS++ErViBOtHgjdriJXz Hy9uNPp4HGpKExPWBVRozBQ5HMYUY2Wv+Zsku+mlgzsCQQDTdAqkOzzhJ2+uD2et MyMDBm2oKiPUrpSBTFo1EiDH6ECrNAJd0FyYFwYvcI5b7BK06SFRmd80GSvBeOMI TKIbAkB2zFIpqqA3PiaOJyAbxe+kf3vMJk8g6+AT1knFh6A1K0QwpKSBCLFqQavp pAbUwBwOjCELqNRCzwAVEe3JO3+lAkEAhRhedl8/A62R8yqJJJCycf4C2b2kjgNR QE1x3kPJ1GqRAfIbpzc2gRjE8OlVAfEHGU5AhZ9nyeAqFX5k0N2DjwJAZpJApfQo VoCVZyPPASHV4B6k5b/DUcLo9XnNYkcm5EsdjJXR8TWCrkbBxPM3i1Nn/2Lpa0xp FiD4cMhNHreApQ== -----END PRIVATE KEY----- heimdal-7.5.0/lib/hx509/data/secp256r1TestCA.key.pem0000644000175000017500000000036113026237312017575 0ustar niknik-----BEGIN PRIVATE KEY----- MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQgL2N0gdHhAjBGcJ40 gHePPMwGKygIVDXTfjysn9zPiSOhRANCAATlK4Ur4qGCWilCvVoyOXhkQFrDgdgz bJU5HIE5BbHd7w+P3RsWhwTiDJLg/ZXRitrEAKxCAyn6zh7z/qBc94y2 -----END PRIVATE KEY----- heimdal-7.5.0/lib/hx509/data/test-signed-data-noattr0000644000175000017500000000711012136107750020174 0ustar niknik0D *H 5011 0 +0 D *H  5 1This is a static file don't change the content, it is used in the test #!/bin/sh # # Copyright (c) 2005 Kungliga Tekniska Hgskolan # (Royal Institute of Technology, Stockholm, Sweden). # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # 1. Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # # 3. Neither the name of the Institute nor the names of its contributors # may be used to endorse or promote products derived from this software # without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE # ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS # OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) # HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY # OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF # SUCH DAMAGE. # # srcdir="@srcdir@" echo "try printing" ./hxtool print \ --pass=PASS:foobar \ PKCS12:$srcdir/data/test.p12 || exit 1 echo "make sure entry is found (friendlyname)" ./hxtool query \ --pass=PASS:foobar \ --friendlyname=friendlyname-test \ PKCS12:$srcdir/data/test.p12 || exit 1 echo "make sure entry is not found (friendlyname)" ./hxtool query \ --pass=PASS:foobar \ --friendlyname=friendlyname-test-not \ PKCS12:$srcdir/data/test.p12 && exit 1 echo "check for ca cert (friendlyname)" ./hxtool query \ --pass=PASS:foobar \ --friendlyname=ca \ PKCS12:$srcdir/data/test.p12 || exit 1 echo "make sure entry is not found (friendlyname)" ./hxtool query \ --pass=PASS:foobar \ --friendlyname=friendlyname-test \ PKCS12:$srcdir/data/sub-cert.p12 && exit 1 echo "make sure entry is found (friendlyname|private key)" ./hxtool query \ --pass=PASS:foobar \ --friendlyname=friendlyname-test \ --private-key \ PKCS12:$srcdir/data/test.p12 || exit 1 echo "make sure entry is not found (friendlyname|private key)" ./hxtool query \ --pass=PASS:foobar \ --friendlyname=ca \ --private-key \ PKCS12:$srcdir/data/test.p12 && exit 1 exit 0 00c0  *H 0*10U hx509 Test Root CA1 0 USE0 090426202940Z 190424202940Z0!1 0 USE10U Test cert00  *H 0jy̫0*q s֤Uq3m)V@c~[jP"´F>{M>z|-`@B(<|_J*M Ty͠f9070 U00 U0Uwn !x|ùfL=J#0  *H E#0θɶ.JdWdJ0<0:0 +ڍ+f|-%-ynHܿL0'Yh#0!0 +0C@CcK>r["heimdal-7.5.0/lib/hx509/data/proxy10-child-child-test.key0000644000175000017500000000162412136107750020766 0ustar niknik-----BEGIN PRIVATE KEY----- MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBANyAj7lFll5JGorz J1BjJWqTYMYjx0tSRYTrxO2HFaDleOmMP21W3zLeRxBZchap42OYpLrNAcOuj93y hLqgdUzIVqTGri5APkO9pN4sWOYr/iIitWUlL5PyRQw2ioaA1hjsGmlxRTQ1q//C GV0aWG0QRYQS7gRn7hRsKPlAIdnDAgMBAAECgYAgEiLVU6W3OPK/WvZQ3trGUYE1 0GZgMisiVhhiY89lg3q+nUNsZ8I259V2L0xEt5j3F3B+KusixvTt1yQu8L+eki1i moA5YLtiqcDVHkSX44/f8+yN0QBqmtJDg3WU8mki+Nf4fKEAPvdmmgRhnfFE8hqM x6IRyL7B+7bmeUKeIQJBAPXw5KquGiwLjoZ+tHQhWN/3SZEBfB2uPFDAXsMgWnUS pShjnECQDaj9ogUYoWeJacFj8/Dyc01P+LyiAtmfLdcCQQDlhVAsQNxMXLpy5HKU ZcuZz4il/jQUViq/JRyXlqLccHsfs1P+7b3O+TN7LVNS59vKprkBCIcJoSZ4LaGi v331AkEAh+KrVSqQx1kzTFhhd/Cc3FITUY0SeIu2Q5+mPAV6NUkx+5jd0kZFZeON S2eKdlxUFEgXlj8/Oa4/7mlNTdRHTQJBANZ41IoFsdXJcJCb2FXDKZX40AAMoi2+ twMWcrlUEatbkDH3KK43Cf617t1TZWE7N68OTCIjDcx5wbDbMwcZWWECQAQhJrzq pdWb5EVvYRP88zJ1vJCISIGWjxQRsde9w0VX8Uu3kyT1EHEuW+JScoNI0avaV1DK yIG37HCRGTBiNqI= -----END PRIVATE KEY----- heimdal-7.5.0/lib/hx509/data/crl1.der0000644000175000017500000000041012136107750015140 0ustar niknik00o0  *H 0*10U hx509 Test Root CA1 0 USE 090426202941Z 190305202941Z00 090426202941Z0  *H eה!]MPLnQv \͸UsX z*⟴(TςT\Yۯ~ rH0®~&2:`I2}{{aCgY {̠{E-]Fheimdal-7.5.0/lib/hx509/data/sub-ca.key0000644000175000017500000000162412136107750015477 0ustar niknik-----BEGIN PRIVATE KEY----- MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBAL09Y3g+MYXZHbf4 BAJYUxLeGsaVm1Epe8didrmmY1Y9R8gvu2ubfdjxqTwLYWb90efXbXSgMJygfYBB BBqGYbQSeZ2dsDv7CkxpjwYzB4UOc80B+pb5ayAY2LEGAyGzcXrtQ/0p1SP6zM9D /INKy4vmmNuzSfG6Kpdyt0SD1udfAgMBAAECgYEAi8GahGLqD/+YgxUXYOP59iUx gRdb7UTFtSpypAjNtBLtwFoAACiFeIKAiWeeN4GcU6w1mbv0Krgb92wMq8oyvJIG mD+jyzdYSj1C00nQ3WF9b77nasAGP6IzhP82H+c6HjIJOo04MrM0s7lW3ETJbqyq CDpgqufEkXSKO4f1eAECQQD8RB3zRZw0+AMy+v8RBSvHGOyH8WPwheDKST9ycr/c fizcSjjUVaJOH107/SH/GKn+wrDx4vSJXnQqnFLTRYufAkEAwAp0CeXerZhpxAHf SnB/GFRE8xnR7U0sIuAkCupYtr0dQZj4bkeRWuM7dNujKM1EomU/S/ngHlns/KPJ kH0MQQJABtkGgxsJoXp2A8VCdUDRrmbjzNDlqJrJvlP8r+ujf6XBK/2ryz/D1yEM 09sMODOAMdUxHm/NuYjh2GJD8U46+wJAN4OOEcJqgaI6iNfFtZ4Zj23k1KWVItUZ OiezI5ik9oZqq6jNwAteQHjJmjlXzBayjYNZLdxY5k02jb3HKcaMQQJAdelGxbOu NRR3NdcwRUdRBlqTCVAx1qXlDmYvvUNRsEAr17t9ij7bwfxTrFmIEdCoqTlY5K+Z mg1qwSeTGe3x4Q== -----END PRIVATE KEY----- heimdal-7.5.0/lib/hx509/data/pkinit-proxy.crt0000644000175000017500000000146612136107750017006 0ustar niknik-----BEGIN CERTIFICATE----- MIICMTCCAZqgAwIBAgIJAOFd/6I9Oly5MA0GCSqGSIb3DQEBBQUAMB4xCzAJBgNV BAYTAlNFMQ8wDQYDVQQDDAZwa2luaXQwHhcNMDkwNDI2MjAyOTQwWhcNMTkwNDI0 MjAyOTQwWjA1MQswCQYDVQQGEwJTRTEPMA0GA1UEAwwGcGtpbml0MRUwEwYDVQQD DAxwa2luaXQtcHJveHkwgZ8wDQYJKoZIhvcNAQEBBQADgY0AMIGJAoGBANKxpMj4 is1Zy+3RQfaZyhIbPkK+1237l10YqJmh5vB4WF+VriouCw8bXK/Q84rnGlr48fYa 3qquiuT7TzUyBJ/vGMhuBosnO4zI3usM7wcp9zfmykesP/5ef1HRe8Lv2F1HZkLc 6N4jo5lIGtnlnXe4qJjbjTPsY4x0PVl5QV0DAgMBAAGjYDBeMAkGA1UdEwQCMAAw CwYDVR0PBAQDAgXgMB0GA1UdDgQWBBStm+lnDlopIzCh6tdbGhDyHDDdlzAlBggr BgEFBQcBDgEB/wQWMBQCAQAwDwYIKwYBBQUHFQAEA2ZvbzANBgkqhkiG9w0BAQUF AAOBgQB/udiUzrV5n+klF473NEMaajNvxC/u4/60vHXt6U42U4zHWWRuWTMDkPA/ 6LorSPIk+ZvWLAFHVR2EdeVFZzxbsb9IAsM+giZxv7bYfloBZHhbzc3r8IDSZa1H totfxDb/wZrFAbNiuuAdmKuRGxwGYE4ykw3ebLSuoRYPI2Szxw== -----END CERTIFICATE----- heimdal-7.5.0/lib/hx509/data/test-enveloped-rc2-640000644000175000017500000000611412136107750017406 0ustar niknik0 H *H  90 5100/0*10U hx509 Test Root CA1 0 USE0  *H >Ko^kz$!>x-I_2H4nm!&)vR[H24qjiR-iR_Edö¢ˑ3qIzV4 0<[BrTaLP-Ju0 b *H 0*H 0 x'@ 84.bxA@@om^[=1aQS5(U3[wɜQ|=qcc6a:"ZJ2Ы5zBc=w!}! ЖjjkH`cπH ݄iUG?(hۺA\wqSkF|$Nt1:ͅ>*5Hof'Hؙfu DqbᡂgERJOnR* Gy/Rvj?$hf`LQK}c=|}HiTz'H99B@R4Su' Z, ؋|SUd`[Bh@\ <,kX}顧ɳDN,BҒA0"k{!0-\0*X<{H9N9MdOd7z/#O7)Eɤ3mY5#ybgItԣZ\'H׿*1U'Q-" w)ӠAgz/).d\6RXXzSשR^a 67 {Z2\X ҩ4ՀFZ$5hgՓ!_?֙ڙ0p:# )!'Ěsw'ac,!1(ůƩvz$rQ_ݩՀ Y@]<ɹ3|TϝZHݡwDBuOQ )aByh '^ H h&+?{OU\u$3+]G0O&U ={d 8p=]y_fj!tww`X-lȇN%c LS1}#Z"t 8rdž¡E|h*swI7%0]RiZHJg1[=t( e(-aAyWГs\ k`*H!2G"geh*T6՛`f#L枋nas8=X7b 7:>HE6>SjKQֳPJ'bjŝwhf V[8ᶜZ~_g*'[&4 4 bUC@xt:.L,R;*@8XH76`jlTmg'OBU-c/!M$O X/_!MZw9EgOetiќGԦn$ 3C7=NXt,$o:e0}_G_ME?V o&y0ol7 қQ,wT}H0YX97kןK.ksWz}PwNM q%ud^P(nu79: a&bQ~)l|$hJs 6q7Mҿ,]֔$dX1mЬa;indw1DF:!ܬt,r\S[!M1BB&ɜo_=8(YSACpCl5ɪ?$[Ö#ɲplCG^ ʤ_Zy YNky}S#/l'|" =:(XI pVwݷt$FH2L>1Bj\T l ݼS%RO4JcxqwGjHMF. O"$Lߥ@Ⱥrӹot b*g~/K|bJt^闼V1uH,La+*SB#ccV@]>V~!G &"D Zڲ$0Q/heimdal-7.5.0/lib/hx509/data/secp256r1TestCA.pem0000644000175000017500000000160113026237312017004 0ustar niknik-----BEGIN PRIVATE KEY----- MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQgL2N0gdHhAjBGcJ40 gHePPMwGKygIVDXTfjysn9zPiSOhRANCAATlK4Ur4qGCWilCvVoyOXhkQFrDgdgz bJU5HIE5BbHd7w+P3RsWhwTiDJLg/ZXRitrEAKxCAyn6zh7z/qBc94y2 -----END PRIVATE KEY----- -----BEGIN CERTIFICATE----- MIIBuDCCAV6gAwIBAgIBATAKBggqhkjOPQQDAjA2MQswCQYDVQQGEwJTRTEQMA4G A1UEChMHSGVpbWRhbDEVMBMGA1UEAxMMQ0Egc2VjcDI1NnIxMB4XDTE0MDMxMDE5 NDAyM1oXDTM4MDExNzE5NDAyM1owNjELMAkGA1UEBhMCU0UxEDAOBgNVBAoTB0hl aW1kYWwxFTATBgNVBAMTDENBIHNlY3AyNTZyMTBZMBMGByqGSM49AgEGCCqGSM49 AwEHA0IABOUrhSvioYJaKUK9WjI5eGRAWsOB2DNslTkcgTkFsd3vD4/dGxaHBOIM kuD9ldGK2sQArEIDKfrOHvP+oFz3jLajXTBbMB0GA1UdDgQWBBTrUd8AqGhfZvHV spcznXeb328JgzAfBgNVHSMEGDAWgBTrUd8AqGhfZvHVspcznXeb328JgzAMBgNV HRMEBTADAQH/MAsGA1UdDwQEAwIBBjAKBggqhkjOPQQDAgNIADBFAiBd6J2N4B6L mtn0ZP/6vOyPkA7YMq2EwbVyTGlnBTwYsQIhALjsLWHQVSkt08rly48ns93DeSbM XejBzmT8QXEdib+1 -----END CERTIFICATE----- heimdal-7.5.0/lib/hx509/data/test-enveloped-des-ede30000644000175000017500000000610712136107750020064 0ustar niknik0 C *H  40 0100/0*10U hx509 Test Root CA1 0 USE0  *H Yr dmy}x4T!.ce ?p~O0/j Zg2pV1jB KvwG܎[/&,JO0 ] *H 0*H k'YN0 8&""NZ3E=e E%5 Jm0]w#iy7FyڐR#^ NjPI=w-9KwtvL+?7n#Xt~{N{:!c'*{}O3V8z2CQaS)b7"[?J 7[g` {aL6~Go$'xSR"㏶gM$O݀|ZFP:JZYV@ysغȐ vv!uDG?^MܠH8ǭV[0!l} RȔ|BV!_+0Ɏ[qؕY}bLa8+B2 ]B:l.$Ö5_q7M4O]`!%2L~uL6qOM*5c 'aN1hS\l*sR)xAմ!Z Ě +#" oͽSCQcx1`!g WR<˅!F# +g_[p/h㓞[L6xf%h1ꍆXxgAn3V< sxj r"uOL^-W:(.'J;,݈t;l.Stap8w'*a#1qFKX4,M;&*bBcK{OЮ_ 4¯1eu ܱO+2.sWw0Z8uc>dS?~_VgPJ?ip4.w{Sx@T\"x'w9BaU*)׈(a 0P}^l^ϣ[; ;b֐ 5j$aksKn4"$}zKI'NRj p*\i"-~sP%qp>Gb{Uj1Iph/fqBV<;8o1uynN_C\رcN a;*lAóbw70S\ĝѝc%<~dS`4 G?ɤ=n)e s(TdՓRU&\8^b ca?(h^t6/lSb}ѩaͤ`!Y#4fj0^ګ̂f[_/U J7}%Q22B5\_X}R0 K7לU$K'魏r\J'Jiq6,OHi"EB0v.:\q $H\7d74BDFo,%D䌝b/>9ߥN7P/}L`Jnླ@4x JGscٴ7nsVA/4(SL_(Hz`84tM-hЖ j!|O¡qʽU_0X7Iݳ9.Ou}%VřfN!nRTO?QVKoG˃v %КaXpl+l芨u)ܳ!}˽c0}_[̴ʦ`cUGp1!6bp{HRF}s}"3t'\W &['1 ud 9[còK<~y|o2]BA)|~ 6$+ 9H-4nx_[zPp;O50;(weU݂ڵZ |:J/x;sRDkD;a6:44܃+n5e|J~ Y8C`X1N”T|9Zz u6_vr'>$&g QZK'rڿz9U>.tB*Ǿs-VӋuVWN.-E+d;=y7/+ W*ic]{G p&hl ܝ"!^-P5Y cǔ oG&m6\:qb.B|'W*Ukf',oPתyv%X1 :ٱ-:gi<}kW!mf=X~c5m؛ lF'9heimdal-7.5.0/lib/hx509/data/test.combined.crt0000644000175000017500000000675112136107750017071 0ustar niknikCertificate: Data: Version: 3 (0x2) Serial Number: 2 (0x2) Signature Algorithm: sha1WithRSAEncryption Issuer: CN=hx509 Test Root CA, C=SE Validity Not Before: Apr 26 20:29:40 2009 GMT Not After : Apr 24 20:29:40 2019 GMT Subject: C=SE, CN=Test cert Subject Public Key Info: Public Key Algorithm: rsaEncryption Public-Key: (1024 bit) Modulus: 00:e8:6a:8a:12:02:ed:86:e3:1a:b6:79:18:cc:ab: c3:d4:cf:30:f4:dc:2a:90:71:c3:00:18:20:84:73: d6:a4:55:b6:71:e4:33:fd:b7:a3:e3:6d:d4:ff:29: d2:56:7f:40:63:e4:bf:12:8a:16:7e:ff:5b:e9:6a: ce:50:b4:e3:85:11:a1:22:cd:c2:b4:e5:46:b2:0f: 3e:04:85:7b:a5:4d:3e:7a:b8:c7:7c:d0:2d:fb:95: 60:d1:40:42:bc:28:ae:f1:3c:7c:0e:5f:ca:e4:8f: fc:4a:2a:1d:ef:10:05:4d:09:54:b7:12:16:79:bb: bf:cd:a0:92:66:9e:94:e1:ff Exponent: 65537 (0x10001) X509v3 extensions: X509v3 Basic Constraints: CA:FALSE X509v3 Key Usage: Digital Signature, Non Repudiation, Key Encipherment X509v3 Subject Key Identifier: CE:77:6E:DE:0B:F4:21:F8:78:C0:1A:7C:C3:B9:66:EC:4C:3D:4A:23 Signature Algorithm: sha1WithRSAEncryption 45:23:30:f4:ce:b8:c9:b6:a0:2e:4a:a0:64:bd:be:57:d5:64: ed:4a:8d:95:a3:9a:19:3c:56:7b:14:a6:2e:6c:37:37:ae:2a: b1:42:2e:0c:b8:7e:57:f5:5a:38:29:8d:78:53:b3:2d:c8:c2: 97:f3:ab:51:6a:c4:df:86:97:ca:68:55:39:e0:f8:99:5a:bd: a4:e1:34:50:34:8f:70:d2:74:2d:b8:90:ef:b8:d2:22:3a:ce: be:82:a8:4b:b3:32:cd:1b:8d:0b:69:7d:0c:d7:b6:33:dc:68: 41:76:a1:36:20:8e:ba:34:45:be:71:bd:ab:bf:74:77:87:e6: bf:7f -----BEGIN CERTIFICATE----- MIIB+jCCAWOgAwIBAgIBAjANBgkqhkiG9w0BAQUFADAqMRswGQYDVQQDDBJoeDUw OSBUZXN0IFJvb3QgQ0ExCzAJBgNVBAYTAlNFMB4XDTA5MDQyNjIwMjk0MFoXDTE5 MDQyNDIwMjk0MFowITELMAkGA1UEBhMCU0UxEjAQBgNVBAMMCVRlc3QgY2VydDCB nzANBgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEA6GqKEgLthuMatnkYzKvD1M8w9Nwq kHHDABgghHPWpFW2ceQz/bej423U/ynSVn9AY+S/EooWfv9b6WrOULTjhRGhIs3C tOVGsg8+BIV7pU0+erjHfNAt+5Vg0UBCvCiu8Tx8Dl/K5I/8Siod7xAFTQlUtxIW ebu/zaCSZp6U4f8CAwEAAaM5MDcwCQYDVR0TBAIwADALBgNVHQ8EBAMCBeAwHQYD VR0OBBYEFM53bt4L9CH4eMAafMO5ZuxMPUojMA0GCSqGSIb3DQEBBQUAA4GBAEUj MPTOuMm2oC5KoGS9vlfVZO1KjZWjmhk8VnsUpi5sNzeuKrFCLgy4flf1WjgpjXhT sy3Iwpfzq1FqxN+Gl8poVTng+JlavaThNFA0j3DSdC24kO+40iI6zr6CqEuzMs0b jQtpfQzXtjPcaEF2oTYgjro0Rb5xvau/dHeH5r9/ -----END CERTIFICATE----- -----BEGIN PRIVATE KEY----- MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBAOhqihIC7YbjGrZ5 GMyrw9TPMPTcKpBxwwAYIIRz1qRVtnHkM/23o+Nt1P8p0lZ/QGPkvxKKFn7/W+lq zlC044URoSLNwrTlRrIPPgSFe6VNPnq4x3zQLfuVYNFAQrworvE8fA5fyuSP/Eoq He8QBU0JVLcSFnm7v82gkmaelOH/AgMBAAECgYBSUxqhEqRsORmHNRHRva3aPaHL ugjhrUozSFiMUjPfdfTwFrNL1baZopfl4jx9Iwn92FLOEFezmGRII+r8r3Y/SY9k 9SS1X4IlPBIHggDKun9OJlpkAFKlOU6HDlEdB/rXR/unzGHQYgQ9DqX3OUEEHPFr OOxm0Yj5gvLXvCJDgQJBAPipSzTEAQAtNE/xAnTtZzZD6ABiLE62kMCBJ3dd4NBF 3+u6nssdExpdXBFrRtSqMxpbKZ5C+j2LFUI+1I6Zdd8CQQDvRoJNb5mUg3Xe+xkX JZ/ezXv2bq8pJgPPYnMC4F1Z9KqBRIl+6hDZanKkJP6+JKzHzyNALQv8++/4u/PT CtfhAkEAhpSp3X8Pw5azr2iTmdE7gUUzdbGspVVt9qJwR8yJdm+7B4xTkT7FLgnF YLAc/9C2I9efKMa7RT/XW6lBxYQNJQJAe2SMK+zicbE9pwkszkAL6vVi+RnpYLoG +vrVPuV/nrVK/LDgiz+gAs8fYcDmUh5NsBkFH8JbTVKLVWVv/yS3YQJAA7u25lSb JMuylkeVzpg52uaOTNK2NtOH8cXZOSMp8q4evQsrvoiVF4MGoZp0zVGpUUYIUaLA BN+BKthYPQEPPg== -----END PRIVATE KEY----- heimdal-7.5.0/lib/hx509/data/secp256r2TestServer.pem0000644000175000017500000000157113026237312017776 0ustar niknik-----BEGIN CERTIFICATE----- MIIBsDCCAVWgAwIBAgIBAjAKBggqhkjOPQQDAjA2MQswCQYDVQQGEwJTRTEQMA4G A1UEChMHSGVpbWRhbDEVMBMGA1UEAxMMQ0Egc2VjcDI1NnIxMB4XDTE0MDMxMDE5 NDAyM1oXDTM4MDExNzE5NDAyM1owMDELMAkGA1UEBhMCU0UxEDAOBgNVBAoTB0hl aW1kYWwxDzANBgNVBAMTBlNlcnZlcjBZMBMGByqGSM49AgEGCCqGSM49AwEHA0IA BItZgn1C8ZBvKkkNoEofWL0JLCTaHT2lJj7d9jRtSKiR2PlOtd5HhteDqP78K4eg lRMk5nqsmEooalfbNsFBy8SjWjBYMB0GA1UdDgQWBBTqMDTOezcRsax6lf6E/Xk+ QzPorjAfBgNVHSMEGDAWgBTrUd8AqGhfZvHVspcznXeb328JgzAJBgNVHRMEAjAA MAsGA1UdDwQEAwIEsDAKBggqhkjOPQQDAgNJADBGAiEAsvf//YdUWCD6OLZesENa 1mH8+b+kZDR6jx1JchRXAEQCIQDkTvTZrlmmxUaWEsf08/4xbxkYbrPAg4+VX2uI QcEwUA== -----END CERTIFICATE----- -----BEGIN PRIVATE KEY----- MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQgKo/47DaveCl90GxH LCE7IGBua2XsE+jI4RUWZrqjhBGhRANCAASLWYJ9QvGQbypJDaBKH1i9CSwk2h09 pSY+3fY0bUiokdj5TrXeR4bXg6j+/CuHoJUTJOZ6rJhKKGpX2zbBQcvE -----END PRIVATE KEY----- heimdal-7.5.0/lib/hx509/data/test-enveloped-rc2-1280000644000175000017500000000611412136107750017467 0ustar niknik0 H *H  90 5100/0*10U hx509 Test Root CA1 0 USE0  *H `6]- ݶ.SRtޕV:P*DURx=>A4[k|gdhYkU hDhVS+p6o>RJ`l)lft0 b *H 0*H 0 :յ9Ԁ 8A2zc" YlwM-Q[&/ *i>m#Z y*oBGe׌ɑ O;˷ye(0ȸ,G  bo +., /lj Z;UZҽ8v/~ _NBs6>Q>{8*܀(uU"0i#;WZ%^fŵk@GJ󠈧LL4d ךbLq(:1nu9ZzӞI>S;&.fMJ7\ǢeIwj[df.bmt!B8CY"V%D8mIaTtݧ;{&ʗgV2d:z2Uj;w7I +J3 ]q Ǖ꾐4 Udt nS&@6LWuh`!էJR3lgzf Bǃj Mi,˪qNnN]sl)sGRV VA`3x w/{B9 Yť::.Jn8e: ^I'!z'BP2Tn(dR ;؇VvYMVߖt_0:쾾7$&D)8ʴ/>;Qh9אM[oPհ rѯ?^;fNLgo }$H@0'ÌtL][)QwyWʝGӑT& mW.{)e2x~mڴ34WH?ߪ*|Y{ v<#J2_.{X~ [JNeіb# $iSC L&;*f2B(VionqF/!V!^|Ȍ.ﻢXK{b[E{N6h΄/`5C іPHR ]9gYW SƄPkoxyCLf0.0rKX XBA5o$ \$3r\ѐgUGT!uEکĤ08Yh;*4*4HlN l;ƙz7)`ÁL@QcN,Z2^{lAduĥغѝXUc4-Y 3=8 `KMO"R_]ZZ CZӒrG.Qxw8fc!3nM]&inRᆘBW"0Ӛh[F'8_[v]*EEBR]ZYEg57.&Y!y-eumayZPi:aOü.YS"c .Ejb [7YdNIFDxq;Z;'k)4p7&x6j \_aq*z*( ^>#4 $J:&\yBvh_fh$9@*[K΋p/ي?δj c~NƦOȢW[~ok#Vo)xaފ5ʀ-kw na;wv Ҟ/cKNoJ@1|oo!U~!֋eI}rΔ7`/J 1kVQԍ>gB}| js_ny3gÄ͍17E{?j6}#SB.J-}Ij/tֳ#$)B;j}`D"in4k?4K{k=lY%܀_d/f' <D,Uja@Q'u5*9mK ̟"I|;~\cM Vd)tP"ǃXXzjA̓(o=/:^lo,+ clTqzx]J ynҲ/0loT 14LWvl;LGN}`OG/Ұ>pHˀMzk ;+g)S<@TQ-%j%;|ΦOD`,+eQý YkO٬﬛+j7nvwv^LbŇ,,22>=nԅ-8;x0SXyT jgXFAm;91C?>TM@69W(Z7e*:;Ũs  wdyG`~QqG~ 30NsE]٫.q/y0[q&}_⌐ougAZCdN#dtX4{WԶIͨyvmFmimV(k,Zb碷Wq2"uxk$ɄG6B=%0Q||iP%\2b-ޕ;bJk[1T.y8:`17oXfU\SXa.heimdal-7.5.0/lib/hx509/data/secp256r2TestClient.cert.pem0000644000175000017500000000120413026237312020673 0ustar niknik-----BEGIN CERTIFICATE----- MIIBrzCCAVWgAwIBAgIBAjAKBggqhkjOPQQDAjA2MQswCQYDVQQGEwJTRTEQMA4G A1UEChMHSGVpbWRhbDEVMBMGA1UEAxMMQ0Egc2VjcDI1NnIxMB4XDTE0MDMxMDE5 NDAyM1oXDTM4MDExNzE5NDAyM1owMDELMAkGA1UEBhMCU0UxEDAOBgNVBAoTB0hl aW1kYWwxDzANBgNVBAMTBkNsaWVudDBZMBMGByqGSM49AgEGCCqGSM49AwEHA0IA BO7/MCIBHf8gQLQ5ltp1uyCOCAw8uylZZ7+v/rB3oKHuAIyL6q/QjZXZH3FR5VcI zANavN5SAfx9CFJpPk+pUISjWjBYMB0GA1UdDgQWBBSjXg4X3fs5xOQgTumjZQwF I13RejAfBgNVHSMEGDAWgBTrUd8AqGhfZvHVspcznXeb328JgzAJBgNVHRMEAjAA MAsGA1UdDwQEAwIEsDAKBggqhkjOPQQDAgNIADBFAiAa9d6aCxlioep3ViYqujWv A28/16yXOrmLY1a2wcj3awIhAMeVjMiUTP/U4yXfb3uJjJmq8hfyNZ/CAiTQKORx JjIt -----END CERTIFICATE----- heimdal-7.5.0/lib/hx509/data/pkinit.key0000644000175000017500000000162412136107750015623 0ustar niknik-----BEGIN PRIVATE KEY----- MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBALJHQtxG+JTjZiv5 JhRWQWjhegTNVUWu4KhIgDNY/IZP6GdiiffUutG7mmqDG04BtXyestK/hCGYWB22 Tfqv8uXo1NZ4owbaaRUJ2PoHCZfPGjssabJYogtITjcRLPV6j1DkQBQpKDCsC7UK HmC0mtSNvDjJL6nRNefJ1BhmHBUtAgMBAAECgYBKqzAkxJDvA0NS3ZqGYA4rWGzb wAicE//CXANd/kJeGu/TBWGV7IKGv5WQUPNJu8uAs5NgU5iK3ZzibO3CNpl74KZq JALQXVbLmOVNpiL8V4dfWxwPBFFzjcrUi0OEVrM0srXghDBRfuNtaf93IXoW32W3 4S8KgFfV/bDAWv5VfQJBAOS6bQBtcEGSUPILJzwPvvFNF5OvX/R98PrHjX01aSPW j0B1WMi7sceRDdyE/dV4gGwW7mEftLAogg8HSftaa5MCQQDHiO5/R3aktb3pl7ms PVZ1xwgF9sPVdiq0p1RhbT3YijktSRVuf7YCb6nqhmC6Il88D9LJg7XTzHkpNUx5 j3Q/AkEA4cTGbQKZKJA1SAUMUDO2pNYUrJkSHPHnWJJ6rZl304Eo21Y5McJbBALA 7Od06i5MjOTBnaq/HpaNcioes3UX8wJADQpC4+iMtWj3N1vmE36StvHB8XnWBI5L bjD9T7yu7Qbjg7UiBG2uPGyFw0Dy81cpuCgkk2zbJjNXu7yy+cLJSwJAQ6ZxX3ri E8Kvc07rFKfrLw1/37MqIbMhEvuneSrsS7GdTcaTGP4vqM9a6GQmVrg/gzGo8Wpe geynyqwNsSPReQ== -----END PRIVATE KEY----- heimdal-7.5.0/lib/hx509/data/test-signed-sha-2560000644000175000017500000000751712136107750017056 0ustar niknik0K *H <0810  `He0 D *H  5 1This is a static file don't change the content, it is used in the test #!/bin/sh # # Copyright (c) 2005 Kungliga Tekniska Hgskolan # (Royal Institute of Technology, Stockholm, Sweden). # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # 1. Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # # 3. Neither the name of the Institute nor the names of its contributors # may be used to endorse or promote products derived from this software # without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE # ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS # OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) # HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY # OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF # SUCH DAMAGE. # # srcdir="@srcdir@" echo "try printing" ./hxtool print \ --pass=PASS:foobar \ PKCS12:$srcdir/data/test.p12 || exit 1 echo "make sure entry is found (friendlyname)" ./hxtool query \ --pass=PASS:foobar \ --friendlyname=friendlyname-test \ PKCS12:$srcdir/data/test.p12 || exit 1 echo "make sure entry is not found (friendlyname)" ./hxtool query \ --pass=PASS:foobar \ --friendlyname=friendlyname-test-not \ PKCS12:$srcdir/data/test.p12 && exit 1 echo "check for ca cert (friendlyname)" ./hxtool query \ --pass=PASS:foobar \ --friendlyname=ca \ PKCS12:$srcdir/data/test.p12 || exit 1 echo "make sure entry is not found (friendlyname)" ./hxtool query \ --pass=PASS:foobar \ --friendlyname=friendlyname-test \ PKCS12:$srcdir/data/sub-cert.p12 && exit 1 echo "make sure entry is found (friendlyname|private key)" ./hxtool query \ --pass=PASS:foobar \ --friendlyname=friendlyname-test \ --private-key \ PKCS12:$srcdir/data/test.p12 || exit 1 echo "make sure entry is not found (friendlyname|private key)" ./hxtool query \ --pass=PASS:foobar \ --friendlyname=ca \ --private-key \ PKCS12:$srcdir/data/test.p12 && exit 1 exit 0 00c0  *H 0*10U hx509 Test Root CA1 0 USE0 090426202940Z 190424202940Z0!1 0 USE10U Test cert00  *H 0jy̫0*q s֤Uq3m)V@c~[jP"´F>{M>z|-`@B(<|_J*M Ty͠f9070 U00 U0Uwn !x|ùfL=J#0  *H E#0θɶ.JdWdJ:] l_c)a&5'N@1?9f'${" i0 Z *H 0+X4K9Y 8+_ᮩF.2*d[s #wCgYzrb"P_}Q@g7x_ d.(Ďg2BZl3Uʾd[-u2O3/S:aj)8#ɭ&z +wV \Z[XiKTnjCaGK_b 5f8˝ J6G7[MFNyC1\soeerz h_a#MLM ך(d5QWsɐb6vwm`ƒ#<}M+<tǏZ-,-/ސdsQ d"9",I1#D]gYzJo{D.y0qzM(l#rȏu%N`" Y!̡VqgVOilSE~-%4IpvաEs'DLq:SSh$*K 9 *R:k%;(i8ӼLgxob< 5~Uhi: ~i=9DL%lq)یG ^=RK-OUlS)qY!ߎYnN9-i7+PD|+Xu8_E> mGS\V>3k~ƟDOHBf:ıFR`\H!|iRs%wPZ%#1RU^WESngx2׸rI)KEw]BF)>hh1̆`VVUҁ ]pa9e/p=0ܣzJkp8HD y P_l~P&IJY 14Y7cZv?C^ ~}Mg[%ҋj' sQs:UGvX_. +_W[,iPq "ZV6CwN-/y0Ѓ2:>KFbWm 9m>وIk+-juݾhE,{$Sj5iW5Nwn «8 c_ _+b^]FX[{bsEv`$S$rޥqFu"!!OA[*,{>@E&9ll2O3\pnf-n^;  ʌ7ġQ6?Hba22Ճ*ä R=%t`BC3%X <`;܀-/{.B䖻gY*(w.1bJҐ<9;Pez#: [#qhj]o'yt zX92 *??TJ&0gzK2S44lf,!Fp{ZQI&h}|zlq+ B< ܐ,ҬI怋1 ƚn/By{E57p%~T>[i(P|5 T;s`YK τeX5&uhVG EmvZkf'Qi=U EZZ=ŎWﱱڸyYyV9:IwFZe}OɧN xW;YM%8겱>Ǹ@/5n IߕZƟV042_P x_ k,Juݍ!?ʒQ;KH8p^ '{$3 Ф/fS/ߛ3uW=&]8q'T~J2cJҪ3\ESElhF o`g`zQŹ\TeCB[L/s4p2{hAJJ{A xVBDYNcx?v򫮧&NL{ Kyt`ie8OPcU(i&C`Nr0uPB$N QM̄מfH)6QO% M/ w:fGYXM׃.iLn59 -䲷$K+L|9֪ ":NP'6Adpvv5Wb:d6,L+ܔcdE rdK-N޻z@.0wz/Uvq-ϕԋnE+&ږlE$'' ^|[&no>d\/`^Ef$N8*-ӅEMYߏ.M7X9wD G']5KĀtU9uTnN&񩽘 K֛몐ծy BB3) =l0aW"' hN⍣xgYH96S/1>bK@ZNn1CnQh2f_heimdal-7.5.0/lib/hx509/data/nist-result20000644000175000017500000000070712136107750016112 0ustar niknik# $Id$ # id FAIL 4.2.8 EITHER depeneds on if time_t is 64 bit or not 4.3.5 FAIL 4.4.13 EITHER depeneds on if time_t is 64 bit or not 4.5.1 FAIL 4.5.4 FAIL 4.5.6 FAIL 4.6.15 FAIL 4.6.17 FAIL 4.11.2 FAIL 4.12.2 FAIL 4.13.19 FAIL 4.13.21 FAIL 4.13.23 FAIL 4.13.26 FAIL 4.13.27 FAIL 4.13.30 FAIL 4.13.33 FAIL 4.13.34 FAIL 4.13.37 FAIL 4.14.1 FAIL 4.14.4 FAIL 4.14.5 FAIL 4.14.7 FAIL 4.14.13 FAIL 4.14.18 FAIL 4.14.19 FAIL 4.15.4 FAIL 4.15.5 FAIL 4.16.2 FAIL heimdal-7.5.0/lib/hx509/data/test-ds-only.key0000644000175000017500000000162412136107750016667 0ustar niknik-----BEGIN PRIVATE KEY----- MIICeAIBADANBgkqhkiG9w0BAQEFAASCAmIwggJeAgEAAoGBAOtsyQ2XkauIXESn QO0lsdkNzSIeB4AVSQWwffK8bBJ6SnSoJkyYDynQsmghw7tqzUoncVuLURLtR8wh lO4FEVVhLIgiM8JOEsrtYwAQTE98Ypegn5UqmdeOp4rXU7Kyfai3X91MeTDnSA4N nW2FBFZj1CdTCam8s8FnHmW7ThClAgMBAAECgYEApDDTq8oYy0Qn7a2kR4Cxn8rT VUcSPg8aRYCI5qDo0p49jUy0oVivwp8NvjhGNVDQajZGBe2NFqEsIL8PCk24frfF LNUAi0FllQjq4iUKTKJyahqQvUenhVaAUdYJdDfS6wZM4xYc3TxHpKdbp+DVii+F HA9dcpGCwumbRv7ZmoECQQD+iQOM/iJAXOJa0QEwqsuAlQbC82S3yoedpX7AAup3 lme8BreDMPyv5cCVs8UW9z+z9N+4wEB9cmA98vhCxq9FAkEA7MeeLY04wyFH4VBO 1/GqiTVdOF5mOd3dCfv6xWgO2xUe0h1twIuAmbsST9Bvj7AQM2nAv1EoU88OrhVX BY/B4QJAZnqflVqUS7mZ4NqZUhDR0jkt+buo516Bb3U8LO5/nBpQNaG2rPlCI0er XBp+1ZpCaZ/Dm0y8KkWsfgSe87OuyQJBANefXRN8VGGWECBGAtax86vplc+8X3l4 6k6qUg6tGUI3NI8BT64VG/JjImTemomOOuKm/mj7Hi9cErFDK7Eb3eECQQCxNUEt Lxdipay7Iz1yAr953GoQAXdgJ4l6dmOyle1wE21Mvsc4okGr6cNAp2K3d/LnOAId a09Ph64VsUwGaIEh -----END PRIVATE KEY----- heimdal-7.5.0/lib/hx509/data/proxy10-test.crt0000644000175000017500000000146612136107750016630 0ustar niknik-----BEGIN CERTIFICATE----- MIICMjCCAZugAwIBAgIJAMJEvwnR1+3WMA0GCSqGSIb3DQEBBQUAMCExCzAJBgNV BAYTAlNFMRIwEAYDVQQDDAlUZXN0IGNlcnQwHhcNMDkwNDI2MjAyOTQxWhcNMTkw NDI0MjAyOTQxWjAzMQswCQYDVQQGEwJTRTESMBAGA1UEAwwJVGVzdCBjZXJ0MRAw DgYDVQQDDAdwcm94eTEwMIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDAwvFE RvMpm6Oje46mf4ta4or7w/cUcJ5wrn9f1plR6/ETOiCGKf4i9/9Yj8vr0MFLSNcb LpipSq/JDoiQJQuCvfwGe/g/Im0byhcWmqcvmUQJ+tp/qBsrZQqKMAZxBE1rzvBs pWqQCFHDOebLzcl1zmTDcrDgwsO0j0EOFRiIkwIDAQABo2AwXjAJBgNVHRMEAjAA MAsGA1UdDwQEAwIF4DAdBgNVHQ4EFgQU5aYR98LOKtpDlBTC9W4axWXpg9EwJQYI KwYBBQUHAQ4BAf8EFjAUAgEKMA8GCCsGAQUFBxUABANmb28wDQYJKoZIhvcNAQEF BQADgYEALsp0p4UR2YqO3HYNEkPFluconjaKOcj4X1y1K0dnQneBfrKJJ812h/Dh bs/Kc/SbKWRD8wkNF13WURZiH3emkYgvdB3QIFaWb52gK4n8T2L5PkcEJIv3hFkl 5TyqSgsy4SlaQ0KnBx+E+l9fDXUBYhpxLEVpaav5u3RLNJhG0jY= -----END CERTIFICATE----- heimdal-7.5.0/lib/hx509/data/test-ke-only.key0000644000175000017500000000162412136107750016660 0ustar niknik-----BEGIN PRIVATE KEY----- MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBAMCF3Qt/12ruwKvj Bv1ARBAj45RioLgJr80B60eSWwfIeoS4chLLQqSxvncIX+ls1QU/62Gblmg5ZXkE wQjDirO9QnkxtjsjHtAEsdyAW90fU6dgeL101CdwHwrlH0KX/42vyAOZ5Cjy2rDq NKDUOTdZN/RxHrtVrdeRsqHAXkB/AgMBAAECgYEArZfGYXkLb0MKfbJ+edn5xSfn K8PmsSsi1lJ1qJph9Fmjh4qcaS/XzpLqb4Ago2Rbi5lAD0nwS9f9FCriN5nBtJCO frm3b4Ct0yQrtwID3kVqGDg6MmMu+11x8IlQAz/zDZ34ik/3+Z+G9N4WRUD2HFRr +18SzS5yhZmmjgKYkGkCQQDt/LKcz020nfVednN/6fzx6ZbSFX/x8MehJaI/BEbS uqAl6u9pr24I8FaDGySdBsJua4xZJVS6YUE4LXqRFeIFAkEAzxg9PQp7AqK3Cf90 6pS7IKnHfRraBY6uvioHVIqjU1LYOoLGHKzlrtOhGDpN3E12S/0u6LJZGRAZ/7Aa f98LswJAFbvLD/j6jrESNGM63waeW/VKGbtu6MhlYrkOHRUl5p62e1/+JzenI9fW /rge2txAK1dVBNsc5rx0+U1l8RP/hQJANZFXhcqINw5Puk5Rt7vxC2nfKAUiD/3w RVApxTx3Mr5jH/9jr1cpsicbrGCocyu2RcGfuKEpWspHb1PmBt1y8QJBAJYfAmjL B4p8C9TCnb2NosRj/2wLcvdMJV22E8KFWzXAqRL9FKUKASULKxHy+rne4FHytEQD w7MMQNWHjQVnFcM= -----END PRIVATE KEY----- heimdal-7.5.0/lib/hx509/data/crl1.crl0000644000175000017500000000062612136107750015157 0ustar niknik-----BEGIN X509 CRL----- MIIBBDBvMA0GCSqGSIb3DQEBBQUAMCoxGzAZBgNVBAMMEmh4NTA5IFRlc3QgUm9v dCBDQTELMAkGA1UEBhMCU0UXDTA5MDQyNjIwMjk0MVoXDTE5MDMwNTIwMjk0MVow FDASAgEDFw0wOTA0MjYyMDI5NDFaMA0GCSqGSIb3DQEBBQUAA4GBAGXXCNeUIctd TfKIUIpMbtHnUXYLA8hcB+6Iyc24VR3m+HNYx9XT6Qp6hY4Wg8Qq4p+0KFTxz4JU XLTZWduvgB9+AL+ECXIUmx4FHkgwwq5+AyYygDqzYOVJszJ9hNp7HHthobObrRm4 Q6hn748UG1nd4gp7zKB7ReLvLYff411G -----END X509 CRL----- heimdal-7.5.0/lib/hx509/data/nist-data20000644000175000017500000004331012136107750015502 0ustar niknik# 4.1.1 Valid Signatures Test1 - Validate Successfully 0 ValidCertificatePathTest1EE.crt # 4.1.2 Invalid CA Signature Test2 - Reject - Invalid signature on intermediate certificate 1 InvalidCASignatureTest2EE.crt # 4.1.3 Invalid EE Signature Test3 - Reject - Invalid signature on end entity certificate 1 InvalidEESignatureTest3EE.crt # 4.1.4 Valid DSA Signatures Test4 - Reject - Application can not process DSA signatures 1 ValidDSASignaturesTest4EE.crt # 4.2.1 Invalid CA notBefore Date Test1 - Reject - notBefore date in intermediate certificate is after the current date 1 InvalidCAnotBeforeDateTest1EE.crt # 4.2.2 Invalid EE notBefore Date Test2 - Reject - notBefore date in end entity certificate is after the current date 1 InvalidEEnotBeforeDateTest2EE.crt # 4.2.3 Valid pre2000 UTC notBefore Date Test3 - Validate Successfully 0 Validpre2000UTCnotBeforeDateTest3EE.crt # 4.2.4 Valid GeneralizedTime notBefore Date Test4 - Validate Successfully 0 ValidGeneralizedTimenotBeforeDateTest4EE.crt # 4.2.5 Invalid CA notAfter Date Test5 - Reject - notAfter date in intermediate certificate is before the current date 1 InvalidCAnotAfterDateTest5EE.crt # 4.2.6 Invalid EE notAfter Date Test6 - Reject - notAfter date in end entity certificate is before the current date 1 InvalidEEnotAfterDateTest6EE.crt # 4.2.7 Invalid pre2000 UTC EE notAfter Date Test7 - Reject - notAfter date in end entity certificate is before the current date 1 Invalidpre2000UTCEEnotAfterDateTest7EE.crt # 4.2.8 Valid GeneralizedTime notAfter Date Test8 - Validate Successfully 0 ValidGeneralizedTimenotAfterDateTest8EE.crt # 4.3.1 Invalid Name Chaining EE Test1 - Reject - names do not chain 1 InvalidNameChainingTest1EE.crt # 4.3.2 Invalid Name Chaining Order Test2 - Reject - names do not chain 1 InvalidNameChainingOrderTest2EE.crt # 4.3.3 Valid Name Chaining Whitespace Test3 - Validate Successfully 0 ValidNameChainingWhitespaceTest3EE.crt # 4.3.4 Valid Name Chaining Whitespace Test4 - Validate Successfully 0 ValidNameChainingWhitespaceTest4EE.crt # 4.3.5 Valid Name Chaining Capitalization Test5 - Validate Successfully 0 ValidNameChainingCapitalizationTest5EE.crt # 4.3.6 Valid Name Chaining UIDs Test6 - Validate Successfully 0 ValidNameUIDsTest6EE.crt # 4.3.9 Valid UTF8String Encoded Names Test9 - Validate Successfully 0 ValidUTF8StringEncodedNamesTest9EE.crt # 4.4.1 Missing CRL Test1 - Reject or Warn - status of end entity certificate can not be determined 3 InvalidMissingCRLTest1EE.crt # 4.4.2 Invalid Revoked CA Test2 - Reject - an intermediate certificate has been revoked. 2 InvalidRevokedCATest2EE.crt # 4.4.3 Invalid Revoked EE Test3 - Reject - the end entity certificate has been revoked 2 InvalidRevokedEETest3EE.crt # 4.4.4. Invalid Bad CRL Signature Test4 - Reject or Warn - status of end entity certificate can not be determined 3 InvalidBadCRLSignatureTest4EE.crt # 4.4.5 Invalid Bad CRL Issuer Name Test5 - Reject or Warn - status of end entity certificate can not be determined 3 InvalidBadCRLIssuerNameTest5EE.crt # 4.4.6 Invalid Wrong CRL Test6 - Reject or Warn - status of end entity certificate can not be determined 3 InvalidWrongCRLTest6EE.crt # 4.4.7 Valid Two CRLs Test7 - Validate Successfully 0 ValidTwoCRLsTest7EE.crt # 4.4.8 Invalid Unknown CRL Entry Extension Test8 - Reject - the end entity certificate has been revoked 2 InvalidUnknownCRLEntryExtensionTest8EE.crt # 4.4.9 Invalid Unknown CRL Extension Test9 - Reject - the end entity certificate has been revoked 2 InvalidUnknownCRLExtensionTest9EE.crt # 4.4.10 Invalid Unknown CRL Extension Test10 - Reject or Warn - status of end entity certificate can not be determined 3 InvalidUnknownCRLExtensionTest10EE.crt # 4.4.11 Invalid Old CRL nextUpdate Test11 - Reject or Warn - status of end entity certificate can not be determined 3 InvalidOldCRLnextUpdateTest11EE.crt # 4.4.12 Invalid pre2000 CRL nextUpdate Tesst12 - Reject or Warn - status of end entity certificate can not be determined 3 Invalidpre2000CRLnextUpdateTest12EE.crt # 4.4.13 Valid GeneralizedTime CRL nextUpdate Test13 - Validate Successfully 0 ValidGeneralizedTimeCRLnextUpdateTest13EE.crt # 4.4.14 Valid Negative Serial Number Test14 - Validate Successfully 0 ValidNegativeSerialNumberTest14EE.crt # 4.4.15 Invalid Negative Serial Number Test15 - Reject - the end entity certificate has been revoked 2 InvalidNegativeSerialNumberTest15EE.crt # 4.4.16 Valid Long Serial Number Test16 - Validate Successfully 0 ValidLongSerialNumberTest16EE.crt # 4.4.17 Valid Long Serial Number Test17 - Validate Successfully 0 ValidLongSerialNumberTest17EE.crt # 4.4.18 Invalid Long Serial Number Test18 - Reject - the end entity certificate has been revoked 2 InvalidLongSerialNumberTest18EE.crt # 4.4.19 Valid Separate Certificate and CRL Keys Test19 - Validate Successfully 0 ValidSeparateCertificateandCRLKeysTest19EE.crt # 4.4.20 Invalid Separate Certificate and CRL Keys Test20 - Reject - the end entity certificate has been revoked 2 InvalidSeparateCertificateandCRLKeysTest20EE.crt # 4.4.21 Invalid Separate Certificate and CRL Keys Test21 - Reject or Warn - status of end entity certificate can not be determined 3 InvalidSeparateCertificateandCRLKeysTest21EE.crt # 4.5.1 Valid Basic Self-Issued Old With New Test1 - Validate Successfully 0 ValidBasicSelfIssuedOldWithNewTest1EE.crt # 4.5.2 Invalid Basic Self-Issued Old With New Test2 - Reject - the end entity certificate has been revoked 2 InvalidBasicSelfIssuedOldWithNewTest2EE.crt # 4.5.3 Valid Basic Self-Issued New With Old Test3 - Validate Successfully 0 ValidBasicSelfIssuedNewWithOldTest3EE.crt # 4.5.4 Valid Basic Self-Issued New With Old Test4 - Validate Successfully 0 ValidBasicSelfIssuedNewWithOldTest4EE.crt # 4.5.5 Invalid Basic Self-Issued New With Old Test5 - Reject - the end entity certificate has been revoked 2 InvalidBasicSelfIssuedNewWithOldTest5EE.crt # 4.5.6 Valid Basic Self-Issued CRL Signing Key Test6 - Validate Successfully 0 ValidBasicSelfIssuedCRLSigningKeyTest6EE.crt # 4.5.7 Invalid Basic Self-Issued CRL Signing Key Test7 - Reject - the end entity certificate has been revoked 2 InvalidBasicSelfIssuedCRLSigningKeyTest7EE.crt # 4.5.8 Invalid Basic Self-Issued CRL Signing Key Test8 - Reject - invalid certification path 1 InvalidBasicSelfIssuedCRLSigningKeyTest8EE.crt # 4.6.1 Invalid Missing basicConstraints Test1 - Reject - invalid certification path 1 InvalidMissingbasicConstraintsTest1EE.crt # 4.6.2 Invalid cA False Test2 - Reject - invalid certification path 1 InvalidcAFalseTest2EE.crt # 4.6.3 Invalid cA False Test3 - Reject - invalid certification path 1 InvalidcAFalseTest3EE.crt # 4.6.4 Valid basicConstraints Not Critical Test4 - Validate Successfully 0 ValidbasicConstraintsNotCriticalTest4EE.crt # 4.6.5 Invalid pathLenConstraint Test5 - Reject - invalid certification path 1 InvalidpathLenConstraintTest5EE.crt # 4.6.6 Invalid pathLenConstraint Test6 - Reject - invalid certification path 1 InvalidpathLenConstraintTest6EE.crt # 4.6.7 Valid pathLenConstraint Test7 - Validate Successfully 0 ValidpathLenConstraintTest7EE.crt # 4.6.8 Valid pathLenConstraint Test8 - Validate Successfully 0 ValidpathLenConstraintTest8EE.crt # 4.6.9 Invalid pathLenConstraint Test9 - Reject - invalid certification path 1 InvalidpathLenConstraintTest9EE.crt # 4.6.10 Invalid pathLenConstraint Test10 - Reject - invalid certification path 1 InvalidpathLenConstraintTest10EE.crt # 4.6.11 Invalid pathLenConstraint Test11 - Reject - invalid certification path 1 InvalidpathLenConstraintTest11EE.crt # 4.6.12 Invalid pathLenConstraint Test12 - Reject - invalid certification path 1 InvalidpathLenConstraintTest12EE.crt # 4.6.13 Valid pathLenConstraint Test13 - Validate Successfully 0 ValidpathLenConstraintTest13EE.crt # 4.6.14 Valid pathLenConstraint Test14 - Validate Successfully 0 ValidpathLenConstraintTest14EE.crt # 4.6.15 Valid Self-Issued pathLenConstraint Test15 - Validate Successfully 0 ValidSelfIssuedpathLenConstraintTest15EE.crt # 4.6.16 Invalid Self-Issued pathLenConstraint Test16 - Reject - invalid certification path 1 InvalidSelfIssuedpathLenConstraintTest16EE.crt # 4.6.17 Valid Self-Issued pathLenConstraint Test17 - Validate Successfully 0 ValidSelfIssuedpathLenConstraintTest17EE.crt # 4.7.1 Invalid keyUsage Critical keyCertSign False Test1 - Reject - invalid certification path 1 InvalidkeyUsageCriticalkeyCertSignFalseTest1EE.crt # 4.7.2 Invalid keyUsage Not Critical keyCertSign False Test2 - Reject - invalid certification path 1 InvalidkeyUsageNotCriticalkeyCertSignFalseTest2EE.crt # 4.7.3 Valid keyUsage Not Critical Test3 - Validate Successfully 0 ValidkeyUsageNotCriticalTest3EE.crt # 4.7.4 Invalid keyUsage Critical cRLSign False Test4 - Reject - invalid certification path 1 InvalidkeyUsageCriticalcRLSignFalseTest4EE.crt # 4.7.5 Invalid keyUsage Not Critical cRLSign False Test5 - Reject - invalid certification path 1 InvalidkeyUsageNotCriticalcRLSignFalseTest5EE.crt 0 UserNoticeQualifierTest19EE.crt # 4.10.1 Valid Policy Mapping Test1, subtest 1 - Reject - unrecognized critical extension [Test using the default settings (i.e., initial-policy-set = any-policy) 1 InvalidSelfIssuedrequireExplicitPolicyTest8EE.crt # 4.11.2 Valid inhibitPolicyMapping Test2 - Reject - unrecognized critical extension 1 ValidinhibitPolicyMappingTest2EE.crt # 4.12.2 Valid inhibitAnyPolicy Test2 - Reject - unrecognized critical extension 1 ValidinhibitAnyPolicyTest2EE.crt # 4.13.1 Valid DN nameConstraints Test1 - Validate Successfully 0 ValidDNnameConstraintsTest1EE.crt # 4.13.2 Invalid DN nameConstraints Test2 - Reject - name constraints violation 1 InvalidDNnameConstraintsTest2EE.crt # 4.13.3 Invalid DN nameConstraints Test3 - Reject - name constraints violation 1 InvalidDNnameConstraintsTest3EE.crt # 4.13.4 Valid DN nameConstraints Test4 - Validate Successfully 0 ValidDNnameConstraintsTest4EE.crt # 4.13.5 Valid DN nameConstraints Test5 - Validate Successfully 0 ValidDNnameConstraintsTest5EE.crt # 4.13.6 Valid DN nameConstraints Test6 - Validate Successfully 0 ValidDNnameConstraintsTest6EE.crt # 4.13.7 Invalid DN nameConstraints Test7 - Reject - name constraints violation 1 InvalidDNnameConstraintsTest7EE.crt # 4.13.8 Invalid DN nameConstraints Test8 - Reject - name constraints violation 1 InvalidDNnameConstraintsTest8EE.crt # 4.13.9 Invalid DN nameConstraints Test9 - Reject - name constraints violation 1 InvalidDNnameConstraintsTest9EE.crt # 4.13.10 Invalid DN nameConstraints Test10 - Reject - name constraints violation 1 InvalidDNnameConstraintsTest10EE.crt # 4.13.11 Valid DN nameConstraints Test11 - Validate Successfully 0 ValidDNnameConstraintsTest11EE.crt # 4.13.12 Invalid DN nameConstraints Test12 - Reject - name constraints violation 1 InvalidDNnameConstraintsTest12EE.crt # 4.13.13 Invalid DN nameConstraints Test13 - Reject - name constraints violation 1 InvalidDNnameConstraintsTest13EE.crt # 4.13.14 Valid DN nameConstraints Test14 - Validate Successfully 0 ValidDNnameConstraintsTest14EE.crt # 4.13.15 Invalid DN nameConstraints Test15 - Reject - name constraints violation 1 InvalidDNnameConstraintsTest15EE.crt # 4.13.16 Invalid DN nameConstraints Test16 - Reject - name constraints violation 1 InvalidDNnameConstraintsTest16EE.crt # 4.13.17 Invalid DN nameConstraints Test17 - Reject - name constraints violation 1 InvalidDNnameConstraintsTest17EE.crt # 4.13.18 Valid DN nameConstraints Test18 - Validate Successfully 0 ValidDNnameConstraintsTest18EE.crt # 4.13.19 Valid Self-Issued DN nameConstraints Test19 - Validate Successfully 0 ValidDNnameConstraintsTest19EE.crt # 4.13.20 Invalid Self-Issued DN nameConstraints Test20 - Reject - name constraints violation 1 InvalidDNnameConstraintsTest20EE.crt # 4.13.21 Valid RFC822 nameConstraints Test21 - Validate Successfully 0 ValidRFC822nameConstraintsTest21EE.crt # 4.13.22 Invalid RFC822 nameConstraints Test22 - Reject - name constraints violation 1 InvalidRFC822nameConstraintsTest22EE.crt # 4.13.23 Valid RFC822 nameConstraints Test23 - Validate Successfully 0 ValidRFC822nameConstraintsTest23EE.crt # 4.13.24 Invalid RFC822 nameConstraints Test24 - Reject - name constraints violation 1 InvalidRFC822nameConstraintsTest24EE.crt # 4.13.25 Valid RFC822 nameConstraints Test25 - Validate Successfully 0 ValidRFC822nameConstraintsTest25EE.crt # 4.13.26 Invalid RFC822 nameConstraints Test26 - Reject - name constraints violation 1 InvalidRFC822nameConstraintsTest26EE.crt # 4.13.27 Valid DN and RFC822 nameConstraints Test27 - Validate Successfully 0 ValidDNandRFC822nameConstraintsTest27EE.crt # 4.13.28 Invalid DN and RFC822 nameConstraints Test28 - Reject - name constraints violation 1 InvalidDNandRFC822nameConstraintsTest28EE.crt # 4.13.29 Invalid DN and RFC822 nameConstraints Test29 - Reject - name constraints violation 1 InvalidDNandRFC822nameConstraintsTest29EE.crt # 4.13.30 Valid DNS nameConstraints Test30 - Validate Successfully 0 ValidDNSnameConstraintsTest30EE.crt # 4.13.31 Invalid DNS nameConstraints Test31 - Reject - name constraints violation 1 InvalidDNSnameConstraintsTest31EE.crt # 4.13.32 Valid DNS nameConstraints Test32 - Validate Successfully 0 ValidDNSnameConstraintsTest32EE.crt # 4.13.33 Invalid DNS nameConstraints Test33 - Reject - name constraints violation 1 InvalidDNSnameConstraintsTest33EE.crt # 4.13.34 Valid URI nameConstraints Test34 - Validate Successfully 0 ValidURInameConstraintsTest34EE.crt # 4.13.35 Invalid URI nameConstraints Test35 - Reject - name constraints violation 1 InvalidURInameConstraintsTest35EE.crt # 4.13.36 Valid URI nameConstraints Test36 - Validate Successfully 0 ValidURInameConstraintsTest36EE.crt # 4.13.37 Invalid URI nameConstraints Test37 - Reject - name constraints violation 1 InvalidURInameConstraintsTest37EE.crt # 4.13.38 Invalid DNS nameConstraints Test38 - Reject - name constraints violation 1 InvalidDNSnameConstraintsTest38EE.crt # 4.14.1 Valid distributionPoint Test1 - Validate Successfully 0 ValiddistributionPointTest1EE.crt # 4.14.2 Invalid distributionPoint Test2 - Reject - end entity certificate has been revoked 2 InvaliddistributionPointTest2EE.crt # 4.14.3 Invalid distributionPoint Test3 - Reject or Warn - status of end entity certificate can not be determined 3 InvaliddistributionPointTest3EE.crt # 4.14.4 Valid distributionPoint Test4 - Validate Successfully 0 ValiddistributionPointTest4EE.crt # 4.14.5 Valid distributionPoint Test5 - Validate Successfully 0 ValiddistributionPointTest5EE.crt # 4.14.6 Invalid distributionPoint Test6 - Reject - end entity certificate has been revoked 2 InvaliddistributionPointTest6EE.crt # 4.14.7 Valid distributionPoint Test7 - Validate Successfully 0 ValiddistributionPointTest7EE.crt # 4.14.8 Invalid distributionPoint Test8 - Reject or Warn - status of end entity certificate can not be determined 3 InvaliddistributionPointTest8EE.crt # 4.14.9 Invalid distributionPoint Test9 - Reject or Warn - status of end entity certificate can not be determined 3 InvaliddistributionPointTest9EE.crt # 4.14.10 Valid No issuingDistributionPoint Test10 - Validate Successfully 0 ValidNoissuingDistributionPointTest10EE.crt # 4.14.11 Invalid onlyContainsUserCerts CRL Test11 - Reject or Warn - status of end entity certificate can not be determined 3 InvalidonlyContainsUserCertsTest11EE.crt # 4.14.12 Invalid onlyContainsCACerts CRL Test12 - Reject or Warn - status of end entity certificate can not be determined 3 InvalidonlyContainsCACertsTest12EE.crt # 4.14.13 Valid onlyContainsCACerts CRL Test13 - Validate Successfully 0 ValidonlyContainsCACertsTest13EE.crt # 4.14.14 Invalid onlyContainsAttributeCerts Test14 - Reject or Warn - status of end entity certificate can not be determined 3 InvalidonlyContainsAttributeCertsTest14EE.crt # 4.14.15 Invalid onlySomeReasons Test15 - Reject - end entity certificate has been revoked 2 InvalidonlySomeReasonsTest15EE.crt # 4.14.16 Invalid onlySomeReasons Test16 - Reject - end entity certificate is on hold 2 InvalidonlySomeReasonsTest16EE.crt # 4.14.17 Invalid onlySomeReasons Test17 - Reject or Warn - status of end entity certificate can not be determined 3 InvalidonlySomeReasonsTest17EE.crt # 4.14.18 Valid onlySomeReasons Test18 - Validate Successfully 0 ValidonlySomeReasonsTest18EE.crt # 4.14.19 Valid onlySomeReasons Test19 - Validate Successfully 0 ValidonlySomeReasonsTest19EE.crt # 4.14.20 Invalid onlySomeReasons Test20 - Reject - end entity certificate has been revoked 2 InvalidonlySomeReasonsTest20EE.crt # 4.14.21 Invalid onlySomeReasons Test21 - Reject - end entity certificate has been revoked 2 InvalidonlySomeReasonsTest21EE.crt # 4.14.24 Valid IDP with indirectCRL Test24 - Reject or Warn - status of end entity certificate can not be determined 3 ValidIDPwithindirectCRLTest24EE.crt # 4.15.1 Invalid deltaCRLIndicator No Base Test1 - Reject or Warn - status of end entity certificate can not be determined 3 InvaliddeltaCRLIndicatorNoBaseTest1EE.crt # 4.15.2 Valid delta-CRL Test2 - Validate Successfully 0 ValiddeltaCRLTest2EE.crt # 4.15.3 Invalid delta-CRL Test3 - Reject - end entity certificate has been revoked 2 InvaliddeltaCRLTest3EE.crt # 4.15.4 Invalid delta-CRL Test4 - Reject - end entity certificate has been revoked 2 InvaliddeltaCRLTest4EE.crt # 4.15.5 Valid delta-CRL Test5 - Validate Successfully 0 ValiddeltaCRLTest5EE.crt # 4.15.6 Invalid delta-CRL Test6 - Reject - end entity certificate has been revoked 2 InvaliddeltaCRLTest6EE.crt # 4.15.7 Valid delta-CRL Test7 - Validate Successfully 0 ValiddeltaCRLTest7EE.crt # 4.15.8 Valid delta-CRL Test8 - Validate Successfully 0 ValiddeltaCRLTest8EE.crt # 4.15.9 Invalid delta-CRL Test9 - Reject - end entity certificate has been revoked 2 InvaliddeltaCRLTest9EE.crt # 4.15.10 Invalid delta-CRL Test10 - Reject or Warn - status of end entity certificate can not be determined 3 InvaliddeltaCRLTest10EE.crt # 4.16.1 Valid Unknown Not Critical Certificate Extension Test1 - Validate Successfully 0 ValidUnknownNotCriticalCertificateExtensionTest1EE.crt # 4.16.2 Invalid Unknown Critical Certificate Extension Test2 - Reject - unrecognized critical extension 1 InvalidUnknownCriticalCertificateExtensionTest2EE.crt heimdal-7.5.0/lib/hx509/data/ocsp-resp2.der0000644000175000017500000000164712136107750016311 0ustar niknik0 0 +000ġ(0&1 0 USE10U OCSP responder20090426202941Z0b0`0:0 +ڍ+f|-%-ynHܿL0'Yh20090426202941Z20090426202941Z#0!0 +0C@CcK>r["0  *H [Oygk _̛V?98fܛYX w3EMħ2UqoFJUo!TzNcAĪ)UiczjP.'68FF /O Mv ^o'0#000  *H 0*10U hx509 Test Root CA1 0 USE0 090426202940Z 190424202940Z0&1 0 USE10U OCSP responder00  *H 08^sW+ W<S( 7-v6\k]"|枂ٗ<{tSn&?*gއGvĿ\, 6-eAG4TE8v?I@qY0W0 U00 U0U%0 +0+ 0U/?5r\QRO_ V/ 0  *H $XMN MK7(y(EJ udc*D4t-HbXiZ=~X9qvlW%zpP  ֊heimdal-7.5.0/lib/hx509/data/gen-req.sh0000644000175000017500000001647212136107750015514 0ustar niknik#!/bin/sh # $Id$ # # This script need openssl 0.9.8a or newer, so it can parse the # otherName section for pkinit certificates. # openssl=openssl gen_cert() { keytype=${6:-rsa:1024} ${openssl} req \ -new \ -subj "$1" \ -config openssl.cnf \ -newkey $keytype \ -sha1 \ -nodes \ -keyout out.key \ -out cert.req > /dev/null 2>/dev/null if [ "$3" = "ca" ] ; then ${openssl} x509 \ -req \ -days 3650 \ -in cert.req \ -extfile openssl.cnf \ -extensions $4 \ -signkey out.key \ -out cert.crt ln -s ca.crt `${openssl} x509 -hash -noout -in cert.crt`.0 name=$3 elif [ "$3" = "proxy" ] ; then ${openssl} x509 \ -req \ -in cert.req \ -days 3650 \ -out cert.crt \ -CA $2.crt \ -CAkey $2.key \ -CAcreateserial \ -extfile openssl.cnf \ -extensions $4 name=$5 else ${openssl} ca \ -name $4 \ -days 3650 \ -cert $2.crt \ -keyfile $2.key \ -in cert.req \ -out cert.crt \ -outdir . \ -batch \ -config openssl.cnf name=$3 fi mv cert.crt $name.crt mv out.key $name.key } echo "01" > serial > index.txt rm -f *.0 gen_cert "/CN=hx509 Test Root CA/C=SE" "root" "ca" "v3_ca" gen_cert "/CN=OCSP responder/C=SE" "ca" "ocsp-responder" "ocsp" gen_cert "/CN=Test cert/C=SE" "ca" "test" "usr" gen_cert "/CN=Revoke cert/C=SE" "ca" "revoke" "usr" gen_cert "/CN=Test cert KeyEncipherment/C=SE" "ca" "test-ke-only" "usr_ke" gen_cert "/CN=Test cert DigitalSignature/C=SE" "ca" "test-ds-only" "usr_ds" gen_cert "/CN=pkinit/C=SE" "ca" "pkinit" "pkinit_client" $openssl ecparam -name secp256r1 -out eccurve.pem gen_cert "/CN=pkinit-ec/C=SE" "ca" "pkinit-ec" "pkinit_client" "XXX" ec:eccurve.pem gen_cert "/C=SE/CN=pkinit/CN=pkinit-proxy" "pkinit" "proxy" "proxy_cert" pkinit-proxy gen_cert "/CN=kdc/C=SE" "ca" "kdc" "pkinit_kdc" gen_cert "/CN=www.test.h5l.se/C=SE" "ca" "https" "https" gen_cert "/CN=Sub CA/C=SE" "ca" "sub-ca" "subca" gen_cert "/CN=Test sub cert/C=SE" "sub-ca" "sub-cert" "usr" gen_cert "/C=SE/CN=Test cert/CN=proxy" "test" "proxy" "proxy_cert" proxy-test gen_cert "/C=SE/CN=Test cert/CN=proxy/CN=child" "proxy-test" "proxy" "proxy_cert" proxy-level-test gen_cert "/C=SE/CN=Test cert/CN=no-proxy" "test" "proxy" "usr_cert" no-proxy-test gen_cert "/C=SE/CN=Test cert/CN=proxy10" "test" "proxy" "proxy10_cert" proxy10-test gen_cert "/C=SE/CN=Test cert/CN=proxy10/CN=child" "proxy10-test" "proxy" "proxy10_cert" proxy10-child-test gen_cert "/C=SE/CN=Test cert/CN=proxy10/CN=child/CN=child" "proxy10-child-test" "proxy" "proxy10_cert" proxy10-child-child-test # combine cat sub-ca.crt ca.crt > sub-ca-combined.crt cat test.crt test.key > test.combined.crt cat pkinit-proxy.crt pkinit.crt > pkinit-proxy-chain.crt # password protected key ${openssl} rsa -in test.key -aes256 -passout pass:foobar -out test-pw.key ${openssl} rsa -in pkinit.key -aes256 -passout pass:foo -out pkinit-pw.key ${openssl} ca \ -name usr \ -cert ca.crt \ -keyfile ca.key \ -revoke revoke.crt \ -config openssl.cnf ${openssl} pkcs12 \ -export \ -in test.crt \ -inkey test.key \ -passout pass:foobar \ -out test.p12 \ -name "friendlyname-test" \ -certfile ca.crt \ -caname ca ${openssl} pkcs12 \ -export \ -in sub-cert.crt \ -inkey sub-cert.key \ -passout pass:foobar \ -out sub-cert.p12 \ -name "friendlyname-sub-cert" \ -certfile sub-ca-combined.crt \ -caname sub-ca \ -caname ca ${openssl} pkcs12 \ -keypbe NONE \ -certpbe NONE \ -export \ -in test.crt \ -inkey test.key \ -passout pass:foobar \ -out test-nopw.p12 \ -name "friendlyname-cert" \ -certfile ca.crt \ -caname ca ${openssl} smime \ -sign \ -nodetach \ -binary \ -in static-file \ -signer test.crt \ -inkey test.key \ -outform DER \ -out test-signed-data ${openssl} smime \ -sign \ -nodetach \ -binary \ -in static-file \ -signer test.crt \ -inkey test.key \ -noattr \ -outform DER \ -out test-signed-data-noattr ${openssl} smime \ -sign \ -nodetach \ -binary \ -in static-file \ -signer test.crt \ -inkey test.key \ -noattr \ -nocerts \ -outform DER \ -out test-signed-data-noattr-nocerts ${openssl} smime \ -sign \ -md sha1 \ -nodetach \ -binary \ -in static-file \ -signer test.crt \ -inkey test.key \ -outform DER \ -out test-signed-sha-1 ${openssl} smime \ -sign \ -md sha256 \ -nodetach \ -binary \ -in static-file \ -signer test.crt \ -inkey test.key \ -outform DER \ -out test-signed-sha-256 ${openssl} smime \ -sign \ -md sha512 \ -nodetach \ -binary \ -in static-file \ -signer test.crt \ -inkey test.key \ -outform DER \ -out test-signed-sha-512 ${openssl} smime \ -encrypt \ -nodetach \ -binary \ -in static-file \ -outform DER \ -out test-enveloped-rc2-40 \ -rc2-40 \ test.crt ${openssl} smime \ -encrypt \ -nodetach \ -binary \ -in static-file \ -outform DER \ -out test-enveloped-rc2-64 \ -rc2-64 \ test.crt ${openssl} smime \ -encrypt \ -nodetach \ -binary \ -in static-file \ -outform DER \ -out test-enveloped-rc2-128 \ -rc2-128 \ test.crt ${openssl} smime \ -encrypt \ -nodetach \ -binary \ -in static-file \ -outform DER \ -out test-enveloped-des \ -des \ test.crt ${openssl} smime \ -encrypt \ -nodetach \ -binary \ -in static-file \ -outform DER \ -out test-enveloped-des-ede3 \ -des3 \ test.crt ${openssl} smime \ -encrypt \ -nodetach \ -binary \ -in static-file \ -outform DER \ -out test-enveloped-aes-128 \ -aes128 \ test.crt ${openssl} smime \ -encrypt \ -nodetach \ -binary \ -in static-file \ -outform DER \ -out test-enveloped-aes-256 \ -aes256 \ test.crt echo ocsp requests ${openssl} ocsp \ -issuer ca.crt \ -cert test.crt \ -reqout ocsp-req1.der ${openssl} ocsp \ -index index.txt \ -rsigner ocsp-responder.crt \ -rkey ocsp-responder.key \ -CA ca.crt \ -reqin ocsp-req1.der \ -noverify \ -respout ocsp-resp1-ocsp.der ${openssl} ocsp \ -index index.txt \ -rsigner ca.crt \ -rkey ca.key \ -CA ca.crt \ -reqin ocsp-req1.der \ -noverify \ -respout ocsp-resp1-ca.der ${openssl} ocsp \ -index index.txt \ -rsigner ocsp-responder.crt \ -rkey ocsp-responder.key \ -CA ca.crt \ -resp_no_certs \ -reqin ocsp-req1.der \ -noverify \ -respout ocsp-resp1-ocsp-no-cert.der ${openssl} ocsp \ -index index.txt \ -rsigner ocsp-responder.crt \ -rkey ocsp-responder.key \ -CA ca.crt \ -reqin ocsp-req1.der \ -resp_key_id \ -noverify \ -respout ocsp-resp1-keyhash.der ${openssl} ocsp \ -issuer ca.crt \ -cert revoke.crt \ -reqout ocsp-req2.der ${openssl} ocsp \ -index index.txt \ -rsigner ocsp-responder.crt \ -rkey ocsp-responder.key \ -CA ca.crt \ -reqin ocsp-req2.der \ -noverify \ -respout ocsp-resp2.der ${openssl} ca \ -gencrl \ -name usr \ -crldays 3600 \ -keyfile ca.key \ -cert ca.crt \ -crl_reason superseded \ -out crl1.crl \ -config openssl.cnf ${openssl} crl -in crl1.crl -outform der -out crl1.der heimdal-7.5.0/lib/hx509/data/nist-data0000644000175000017500000001545512136107750015431 0ustar niknik# $Id$ # id verify cert hxtool-verify-arguments... # p(ass) f(ail) # Those id's that end with i are invariants of the orignal test # # 4.1 Signature Verification # 4.1.1 p ValidCertificatePathTest1EE.crt GoodCACert.crt GoodCACRL.crl 4.1.2 f InvalidCASignatureTest2EE.crt BadSignedCACert.crt BadSignedCACRL.crl 4.1.3 f InvalidEESignatureTest3EE.crt GoodCACert.crt GoodCACRL.crl #4.1.4 p ValidDSASignaturesTest4EE.crt DSACACert.crt DSACACRL.crl #4.1.5 p ValidDSAParameterInheritanceTest5EE.crl DSAParametersInheritedCACert.crt DSAParametersInheritedCACRL.crl DSACACert.crt DSACACRL.crl #4.1.6 f InvalidDSASignaturesTest6EE.crt DSACACert.crt DSACACRL.crl # # 4.2 Validity Periods # 4.2.1 f InvalidCAnotBeforeDateTest1EE.crt BadnotBeforeDateCACert.crt BadnotBeforeDateCACRL.crl 4.2.2 f InvalidEEnotBeforeDateTest2EE.crt GoodCACert.crt GoodCACRL.crl 4.2.3 p Validpre2000UTCnotBeforeDateTest3EE.crt GoodCACert.crt GoodCACRL.crl 4.2.4 p ValidGeneralizedTimenotBeforeDateTest4EE.crt GoodCACert.crt GoodCACRL.crl 4.2.5 f InvalidCAnotAfterDateTest5EE.crt BadnotAfterDateCACert.crt BadnotAfterDateCACRL.crl 4.2.6 f InvalidEEnotAfterDateTest6EE.crt GoodCACert.crt GoodCACRL.crl 4.2.7 f Invalidpre2000UTCEEnotAfterDateTest7EE.crt GoodCACert.crt GoodCACRL.crl #4.2.8 p ValidGeneralizedTimenotAfterDateTest8EE.crt GoodCACert.crt GoodCACRL.crl # # 4.4 CRtests # 4.4.1 f InvalidMissingCRLTest1EE.crt NoCRLCACert.crt 4.4.1i p InvalidMissingCRLTest1EE.crt --missing-revoke NoCRLCACert.crt 4.4.2 f InvalidRevokedEETest3EE.crt GoodCACert.crt InvalidRevokedCATest2EE.crt GoodCACRL.crl RevokedsubCACRL.crl 4.4.2i p InvalidRevokedEETest3EE.crt --missing-revoke GoodCACert.crt InvalidRevokedCATest2EE.crt 4.4.3 f InvalidRevokedEETest3EE.crt GoodCACert.crt GoodCACRL.crl 4.4.3i p InvalidRevokedEETest3EE.crt --missing-revoke GoodCACert.crt 4.4.4 f InvalidBadCRLSignatureTest4EE.crt BadCRLSignatureCACert.crt BadCRLSignatureCACRL.crl 4.4.4i p InvalidBadCRLSignatureTest4EE.crt --missing-revoke BadCRLSignatureCACert.crt 4.4.5 f InvalidBadCRLIssuerNameTest5EE.crt BadCRLIssuerNameCACert.crt BadCRLIssuerNameCACRL.crl 4.4.5i p InvalidBadCRLIssuerNameTest5EE.crt --missing-revoke BadCRLIssuerNameCACert.crt 4.4.6 f InvalidWrongCRLTest6EE.crt WrongCRLCACert.crt WrongCRLCACRL.crl 4.4.7 p ValidTwoCRLsTest7EE.crt TwoCRLsCACert.crt TwoCRLsCAGoodCRL.crl TwoCRLsCABadCRL.crl 4.4.8 f InvalidUnknownCRLEntryExtensionTest8EE.crt UnknownCRLEntryExtensionCACert.crt UnknownCRLEntryExtensionCACRL.crl 4.4.9 f InvalidUnknownCRLExtensionTest9EE.crt UnknownCRLExtensionCACert.crt UnknownCRLExtensionCACRL.crl 4.4.10 f InvalidUnknownCRLExtensionTest10EE.crt UnknownCRLExtensionCACert.crt UnknownCRLExtensionCACRL.crl 4.4.11 f InvalidOldCRLnextUpdateTest11EE.crt OldCRLnextUpdateCACert.crt OldCRLnextUpdateCACRL.crl 4.4.12 f Invalidpre2000CRLnextUpdateTest12EE.crt pre2000CRLnextUpdateCACert.crt pre2000CRLnextUpdateCACRL.crl #4.4.13-xxx s ValidGeneralizedTimeCRLnextUpdateTest13EE.crt GeneralizedTimeCRLnextUpdateCACert.crt GeneralizedTimeCRLnextUpdateCACRL.crl 4.4.14 p ValidNegativeSerialNumberTest14EE.crt NegativeSerialNumberCACert.crt NegativeSerialNumberCACRL.crl 4.4.15 f InvalidNegativeSerialNumberTest15EE.crt NegativeSerialNumberCACert.crt NegativeSerialNumberCACRL.crl 4.4.16 p ValidLongSerialNumberTest16EE.crt LongSerialNumberCACert.crt LongSerialNumberCACRL.crl 4.4.17 p ValidLongSerialNumberTest17EE.crt LongSerialNumberCACert.crt LongSerialNumberCACRL.crl 4.4.18 f InvalidLongSerialNumberTest18EE.crt LongSerialNumberCACert.crt LongSerialNumberCACRL.crl # # # 4.8 Ceificate Policies incomplete4.8.2 p AllCertificatesNoPoliciesTest2EE.crt NoPoliciesCACert.crt NoPoliciesCACRL.crl incomplete4.8.10 p AllCertificatesSamePoliciesTest10EE.crt PoliciesP12CACert.crt PoliciesP12CACRL.crl incomplete4.8.13 p AllCertificatesSamePoliciesTest13EE.crt PoliciesP123CACert.crt PoliciesP123CACRL.crl incomplete4.8.11 p AllCertificatesanyPolicyTest11EE.crt anyPolicyCACert.crt anyPolicyCACRL.crl unknown p AnyPolicyTest14EE.crt anyPolicyCACert.crt anyPolicyCACRL.crl unknown f BadSignedCACert.crt unknown f BadnotAfterDateCACert.crt unknown f BadnotBeforeDateCACert.crt # # 4.13 Name Constraints # 4.13.1 p ValidDNnameConstraintsTest1EE.crt nameConstraintsDN1CACert.crt nameConstraintsDN1CACRL.crl 4.13.2 f InvalidDNnameConstraintsTest2EE.crt nameConstraintsDN1CACert.crt nameConstraintsDN1CACRL.crl 4.13.3 f InvalidDNnameConstraintsTest3EE.crt nameConstraintsDN1CACert.crt nameConstraintsDN1CACRL.crl 4.13.4 p ValidDNnameConstraintsTest4EE.crt nameConstraintsDN1CACert.crt nameConstraintsDN1CACRL.crl 4.13.5 p ValidDNnameConstraintsTest5EE.crt nameConstraintsDN2CACert.crt nameConstraintsDN2CACRL.crl 4.13.6 p ValidDNnameConstraintsTest6EE.crt nameConstraintsDN3CACert.crt nameConstraintsDN3CACRL.crl 4.13.7 f InvalidDNnameConstraintsTest7EE.crt nameConstraintsDN3CACert.crt nameConstraintsDN3CACRL.crl 4.13.8 f InvalidDNnameConstraintsTest8EE.crt nameConstraintsDN4CACert.crt nameConstraintsDN4CACRL.crl 4.13.9 f InvalidDNnameConstraintsTest9EE.crt nameConstraintsDN4CACert.crt nameConstraintsDN4CACRL.crl 4.13.10 f InvalidDNnameConstraintsTest10EE.crt nameConstraintsDN5CACert.crt nameConstraintsDN5CACRL.crl 4.13.11 p ValidDNnameConstraintsTest11EE.crt nameConstraintsDN5CACert.crt nameConstraintsDN5CACRL.crl 4.13.12 f InvalidDNnameConstraintsTest12EE.crt nameConstraintsDN1subCA1Cert.crt nameConstraintsDN1subCA1CRL.crl nameConstraintsDN1CACert.crt nameConstraintsDN1CACRL.crl 4.13.13 f InvalidDNnameConstraintsTest13EE.crt nameConstraintsDN1subCA1Cert.crt nameConstraintsDN1subCA1CRL.crl nameConstraintsDN1CACert.crt nameConstraintsDN1CACRL.crl 4.13.14 p ValidDNnameConstraintsTest14EE.crt nameConstraintsDN1subCA2Cert.crt nameConstraintsDN1subCA2CRL.crl nameConstraintsDN1CACert.crt nameConstraintsDN1CACRL.crl 4.13.15 f InvalidDNnameConstraintsTest15EE.crt nameConstraintsDN3subCA1Cert.crt nameConstraintsDN3subCA1CRL.crl nameConstraintsDN3CACert.crt nameConstraintsDN3CACRL.crl 4.13.16 f InvalidDNnameConstraintsTest16EE.crt nameConstraintsDN3subCA1Cert.crt nameConstraintsDN3subCA1CRL.crl nameConstraintsDN3CACert.crt nameConstraintsDN3CACRL.crl 4.13.17 f InvalidDNnameConstraintsTest17EE.crt nameConstraintsDN3subCA2Cert.crt nameConstraintsDN3subCA2CRL.crl nameConstraintsDN3CACert.crt nameConstraintsDN3CACRL.crl 4.13.18 p ValidDNnameConstraintsTest18EE.crt nameConstraintsDN3subCA2Cert.crt nameConstraintsDN3subCA2CRL.crl nameConstraintsDN3CACert.crt nameConstraintsDN3CACRL.crl # # no crl for self issued cert # #4.13.19 p ValidDNnameConstraintsTest19EE.crt nameConstraintsDN1SelfIssuedCACert.crt nameConstraintsDN1CACert.crt nameConstraintsDN1CACRL.crl # ?? 4.13.20 f InvalidDNnameConstraintsTest20EE.crt nameConstraintsDN1CACert.crt nameConstraintsDN1CACRL.crl #4.13.21 p ValidRFC822nameConstraintsTest21EE.crt nameConstraintsRFC822CA1Cert.crt nameConstraintsRFC822CA1CRL.crl #page 74 end heimdal-7.5.0/lib/hx509/data/proxy10-child-test.crt0000644000175000017500000000154312136107750017705 0ustar niknik-----BEGIN CERTIFICATE----- MIICVDCCAb2gAwIBAgIJAONwGxXRj9jiMA0GCSqGSIb3DQEBBQUAMDMxCzAJBgNV BAYTAlNFMRIwEAYDVQQDDAlUZXN0IGNlcnQxEDAOBgNVBAMMB3Byb3h5MTAwHhcN MDkwNDI2MjAyOTQxWhcNMTkwNDI0MjAyOTQxWjBDMQswCQYDVQQGEwJTRTESMBAG A1UEAwwJVGVzdCBjZXJ0MRAwDgYDVQQDDAdwcm94eTEwMQ4wDAYDVQQDDAVjaGls ZDCBnzANBgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEAr982Voxa1DhcIIa22u5oO497 L2FF0r91yZh2IjY02XSGbLiyFV6OwKULRli587BMryq8G0BBKAmXVvZszOLOe9xV eipWkyFxiF2s6ERYJ7muHHXxIQyGgRMxhsDuiqiGc51TZ+2H7A2CIHbzUOdom9qf UwXqyd8iD9N/a/Zy3JcCAwEAAaNgMF4wCQYDVR0TBAIwADALBgNVHQ8EBAMCBeAw HQYDVR0OBBYEFBBhzv8RTjHAfZxnKZ7bRv1K9MxSMCUGCCsGAQUFBwEOAQH/BBYw FAIBCjAPBggrBgEFBQcVAAQDZm9vMA0GCSqGSIb3DQEBBQUAA4GBALT+aUqBtZDM W7/F5I9QgZL9+zebGqzjxSTYpIT6iYRop/oA4ZFc6k0UjR5A8A+/u9mISwB9P6R+ GtQ8CBgcqLgsLsTEUiz/N2XtC+I++ZSkR33b6ZbNefq9vSib+OzQjdqw9vshK9zX bajUTjXEGuJrGMeqvv8iwl4SIpCT5f3C -----END CERTIFICATE----- heimdal-7.5.0/lib/hx509/data/test-enveloped-rc2-400000644000175000017500000000611512136107750017401 0ustar niknik0 I *H  :0 6100/0*10U hx509 Test Root CA1 0 USE0  *H ϙ0 VTH#{ɔq5ms0Gx%t.8t*cgpP MZ0 c *H 0*H 0 8=:㾡L //?|/̒GWpϥpH-ūE{[Ȑ`W鑅8Ikg\kI*r;T)T+=r#i0͕̱UM؛.OVJKVz4׬+r~ShŐ(uͭ|޻*ZJ|)r}(Jl1~Kb ^KSl7-ظb"\DU঒vUGE%￷j; ܯ ⠖Ye$-/ ,8H⒉fдx$."J. 3x(3_ `-Xx% bw'XcG+Gϵ\ئ sXȅPEtehӶ8/[@6e4an*  \5zbl}., RRerm?vD?Ǩ K;FN Ad2'^SZ3_I.gp+xhhxOy%p&X fkZ(-uuCa' -*Iԧ4S2\GCӚt,}3N 8XW|*2ybƣ8hFjq7ݵ'QcrD۷uzBH`ٸ|~#N(fT[9C> g<[2ܲjL7˟}Il:9}Fv7Q,b1 ^&`(g2г .Y *~f4\XyGH s'^Uh-)Р+a:@n?«-^ ׊1j{=.!\I}PN!):1^#scҬW Lq~t5DG0# Gқ:mS+, lY "g@b/t+4ڏ0T 0Fy=4,ӯKyG˟Pz{yYsS!|ŽA(ReR^DMMfVGܞd۶-}ݼH) ذ"máBYצ3^6j OVa}\d bIRFF@c6F~ɲ[aS|i ݭUk?~hCmZҙJ䖛^Z+'-bOżя~~ʦ'5YxɒR%xk31PwUՕ>~X;1 m.)df9 K]}$gSZksI_tQm>!{2E2ƻҨ{^Q~OմZ!D^i0ׇ!*.2z+G^C u&]% FYjfN؜;0:nk9V9_5)lB#ްBL8!#M~o~hB/"HnKol##3d' HG %\ ՏЛ#@@?c_t3%s'!~|Ydģ#I9ĩqLkk +A!.UQ;͉ArTЭ#z3]m""Z(lX+XK*ЩmXbJquJW`Pah<0`P bW@ CUw1OE^q[ K>SP(i)POtqVﯨű]Us5e9,HMNpj<3*1b-E[u7U#7[5^9@`h]gƛ&k1 }+A*9khS|E 9,ԜtP1`Tk4.ɢD`ЭBO7u} ~jcq-PԥEZeZn]v, X?֎.lmOwŷ4a{'y().܂8Rv*:YI9EbB]O]D9(]# S&,bq a>j#&BS 4CmELyc ~enWYMj}EfCG'#UBut!ځ: 4)r\]p$3@rvL)j3KMTWZ`'{sf >.(eWz|#υTho4:Jheimdal-7.5.0/lib/hx509/data/mkcert.sh0000755000175000017500000000424313026237312015434 0ustar niknik#! /bin/bash set -e # For now, avoid going past the 2038 32-bit clock rollover DAYS=$(( ( 0x7fffffff - $(date +%s) ) / 86400 - 1 )) key() { local key=$1; shift if [ ! -f "${key}.pem" ]; then openssl genpkey \ -paramfile <(openssl ecparam -name prime256v1) \ -out "${key}.pem" fi } req() { local key=$1; shift local dn=$1; shift openssl req -new -sha256 -key "${key}.pem" \ -config <(printf "[req]\n%s\n%s\n[dn]\nCN_default=foo\n" \ "prompt = yes" "distinguished_name = dn") \ -subj "${dn}" } cert() { local cert=$1; shift local exts=$1; shift openssl x509 -req -sha256 -out "${cert}.pem" \ -extfile <(printf "%s\n" "$exts") "$@" } genroot() { local dn=$1; shift local key=$1; shift local cert=$1; shift exts=$(printf "%s\n%s\n%s\n%s\n" \ "subjectKeyIdentifier = hash" \ "authorityKeyIdentifier = keyid" \ "basicConstraints = CA:true" \ "keyUsage = keyCertSign, cRLSign" ) key "$key"; req "$key" "$dn" | cert "$cert" "$exts" -signkey "${key}.pem" \ -set_serial 1 -days "${DAYS}" } genee() { local dn=$1; shift local key=$1; shift local cert=$1; shift local cakey=$1; shift local cacert=$1; shift exts=$(printf "%s\n%s\n%s\n%s\n" \ "subjectKeyIdentifier = hash" \ "authorityKeyIdentifier = keyid, issuer" \ "basicConstraints = CA:false" \ "keyUsage = digitalSignature, keyEncipherment, dataEncipherment" \ ) key "$key"; req "$key" "$dn" | cert "$cert" "$exts" -CA "${cacert}.pem" -CAkey "${cakey}.pem" \ -set_serial 2 -days "${DAYS}" "$@" } genroot "/C=SE/O=Heimdal/CN=CA secp256r1" \ secp256r1TestCA.key secp256r1TestCA.cert genee "/C=SE/O=Heimdal/CN=Server" \ secp256r2TestServer.key secp256r2TestServer.cert \ secp256r1TestCA.key secp256r1TestCA.cert genee "/C=SE/O=Heimdal/CN=Client" \ secp256r2TestClient.key secp256r2TestClient.cert \ secp256r1TestCA.key secp256r1TestCA.cert cat secp256r1TestCA.key.pem secp256r1TestCA.cert.pem > \ secp256r1TestCA.pem cat secp256r2TestClient.cert.pem secp256r2TestClient.key.pem > \ secp256r2TestClient.pem cat secp256r2TestServer.cert.pem secp256r2TestServer.key.pem > \ secp256r2TestServer.pem heimdal-7.5.0/lib/hx509/data/test.key0000644000175000017500000000162412136107750015304 0ustar niknik-----BEGIN PRIVATE KEY----- MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBAOhqihIC7YbjGrZ5 GMyrw9TPMPTcKpBxwwAYIIRz1qRVtnHkM/23o+Nt1P8p0lZ/QGPkvxKKFn7/W+lq zlC044URoSLNwrTlRrIPPgSFe6VNPnq4x3zQLfuVYNFAQrworvE8fA5fyuSP/Eoq He8QBU0JVLcSFnm7v82gkmaelOH/AgMBAAECgYBSUxqhEqRsORmHNRHRva3aPaHL ugjhrUozSFiMUjPfdfTwFrNL1baZopfl4jx9Iwn92FLOEFezmGRII+r8r3Y/SY9k 9SS1X4IlPBIHggDKun9OJlpkAFKlOU6HDlEdB/rXR/unzGHQYgQ9DqX3OUEEHPFr OOxm0Yj5gvLXvCJDgQJBAPipSzTEAQAtNE/xAnTtZzZD6ABiLE62kMCBJ3dd4NBF 3+u6nssdExpdXBFrRtSqMxpbKZ5C+j2LFUI+1I6Zdd8CQQDvRoJNb5mUg3Xe+xkX JZ/ezXv2bq8pJgPPYnMC4F1Z9KqBRIl+6hDZanKkJP6+JKzHzyNALQv8++/4u/PT CtfhAkEAhpSp3X8Pw5azr2iTmdE7gUUzdbGspVVt9qJwR8yJdm+7B4xTkT7FLgnF YLAc/9C2I9efKMa7RT/XW6lBxYQNJQJAe2SMK+zicbE9pwkszkAL6vVi+RnpYLoG +vrVPuV/nrVK/LDgiz+gAs8fYcDmUh5NsBkFH8JbTVKLVWVv/yS3YQJAA7u25lSb JMuylkeVzpg52uaOTNK2NtOH8cXZOSMp8q4evQsrvoiVF4MGoZp0zVGpUUYIUaLA BN+BKthYPQEPPg== -----END PRIVATE KEY----- heimdal-7.5.0/lib/hx509/data/static-file0000644000175000017500000000546112136107750015745 0ustar niknikThis is a static file don't change the content, it is used in the test #!/bin/sh # # Copyright (c) 2005 Kungliga Tekniska Hgskolan # (Royal Institute of Technology, Stockholm, Sweden). # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # 1. Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # # 3. Neither the name of the Institute nor the names of its contributors # may be used to endorse or promote products derived from this software # without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE # ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS # OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) # HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY # OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF # SUCH DAMAGE. # # srcdir="@srcdir@" echo "try printing" ./hxtool print \ --pass=PASS:foobar \ PKCS12:$srcdir/data/test.p12 || exit 1 echo "make sure entry is found (friendlyname)" ./hxtool query \ --pass=PASS:foobar \ --friendlyname=friendlyname-test \ PKCS12:$srcdir/data/test.p12 || exit 1 echo "make sure entry is not found (friendlyname)" ./hxtool query \ --pass=PASS:foobar \ --friendlyname=friendlyname-test-not \ PKCS12:$srcdir/data/test.p12 && exit 1 echo "check for ca cert (friendlyname)" ./hxtool query \ --pass=PASS:foobar \ --friendlyname=ca \ PKCS12:$srcdir/data/test.p12 || exit 1 echo "make sure entry is not found (friendlyname)" ./hxtool query \ --pass=PASS:foobar \ --friendlyname=friendlyname-test \ PKCS12:$srcdir/data/sub-cert.p12 && exit 1 echo "make sure entry is found (friendlyname|private key)" ./hxtool query \ --pass=PASS:foobar \ --friendlyname=friendlyname-test \ --private-key \ PKCS12:$srcdir/data/test.p12 || exit 1 echo "make sure entry is not found (friendlyname|private key)" ./hxtool query \ --pass=PASS:foobar \ --friendlyname=ca \ --private-key \ PKCS12:$srcdir/data/test.p12 && exit 1 exit 0 heimdal-7.5.0/lib/hx509/data/revoke.key0000644000175000017500000000162412136107750015620 0ustar niknik-----BEGIN PRIVATE KEY----- MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBAKZfETA1Ol/twgas 9BQnwduuefC2ngqD54JqaZKmhZxd5IoOazKZTSK56qaMhJ5i8KPx0rDvQc6TztlJ Q74Np+rNN7u6Te517YZ0iuIIdytgkTCylldOQtFebw31staY7T+roGQzi1KttXpK /XDc2IvhRwyNj5NcnDU/yyHXXGyzAgMBAAECgYBeDVZRM3YZrvZGAdZF4qfkAgGr hAFaHnFtN60RG5Ri7m15YmdVhnal0AaIOt3qEDLL67RZFBjWqJaCHbnvIhcva5Gw OLEQPsvvTBvRq5O7hTwij2f0hTGu7gOHiiW3YCPxvma1qHNOXKRDh5Gi2eG0gKgo fUC2pqvPomNaqZERqQJBANFQXr+KQ9Hcv1cp2+FNOXg8x0sC20+Svwaxs+T4gSr2 AaiWIJgcdYpxkNPke+IGPZ8Bip6jgRpRK1gRLhx7qw0CQQDLercoA7FiwpRMzo1j Yvh4188uhodvuSg6Yj/meQ2zQvsjAipZ0XJgEuZZnoifxkl2A6K+tFLwSq1hy18K C4a/AkEAnwfCRSMG7i8bDV2XWvGyhWEgRiSwfh/PlYV0WbZZZUut7OnLb+bHg11P nT5OxWbacLHaITe3AkjDdtDuyONJDQJAN4RW3rMLPe/q+H3Os9Q4CPiQzZfk8gWp xSwzVRWoOEXJMYcQuQrdUvs1IDSSAE3gkzNwvumCS4+EeM89MgdtDwJAN7ucdA1c m6MiJgTVxTeva7cgw6PCF4Ph9AGRAB+m/qkg8I8W7G0tXxHVUAXfKdfeirigsrnT LKLsQFEQrhuA5A== -----END PRIVATE KEY----- heimdal-7.5.0/lib/hx509/data/ocsp-resp1.der0000644000175000017500000000162612136107750016305 0ustar niknik0 0 +0x0t0(0&1 0 USE10U OCSP responder20060401000225Z0Q0O0:0 +ڍ+f|-%-y^LSlqdm6920060401000225Z#0!0 +0i"e K;S0  *H @˙kƇ n` $:O#ٮ@<y~ |, {&GE(F%@J冤R#YLgQ݂T›2 SǏnhQhY'0#000  *H 0*10U hx509 Test Root CA1 0 USE0 060401000222Z 160329000222Z0&1 0 USE10U OCSP responder00  *H 0Kq`T ?qn\6_Ry0FWT6xmSv9N -Y2.OgTw)?x(gDZTi׿^&ˍD^ݑa{lFO;[~9XqY0W0 U00 U0U%0 +0+ 0UHsΨj­Ƈ499G0  *H AK5'7MA8(cG8i:჏DpE'/[TY#{"_`fuɹew_k ܞN_]/uZzZT(1/8B*j vw@Ex"heimdal-7.5.0/lib/hx509/data/j.pem0000644000175000017500000000306612136107750014551 0ustar niknik-----BEGIN CERTIFICATE----- MIIEajCCA1KgAwIBAgIBATANBgkqhkiG9w0BAQUFADBaMQswCQYDVQQGEwJKUDEN MAsGA1UECgwESlBLSTEpMCcGA1UECwwgUHJlZmVjdHVyYWwgQXNzb2NpYXRpb24g Rm9yIEpQS0kxETAPBgNVBAsMCEJyaWRnZUNBMB4XDTAzMTIyNzA1MDgxNVoXDTEz MTIyNjE0NTk1OVowWjELMAkGA1UEBhMCSlAxDTALBgNVBAoMBEpQS0kxKTAnBgNV BAsMIFByZWZlY3R1cmFsIEFzc29jaWF0aW9uIEZvciBKUEtJMREwDwYDVQQLDAhC cmlkZ2VDQTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBANTnUmg7K3m8 52vd77kwkq156euwoWm5no8E8kmaTSc7x2RABPpqNTlMKdZ6ttsyYrqREeDkcvPL yF7yf/I8+innasNtsytcTAy8xY8Avsbd4JkCGW9dyPjk9pzzc3yLQ64Rx2fujRn2 agcEVdPCr/XpJygX8FD5bbhkZ0CVoiASBmlHOcC3YpFlfbT1QcpOSOb7o+VdKVEi MMfbBuU2IlYIaSr/R1nO7RPNtkqkFWJ1/nKjKHyzZje7j70qSxb+BTGcNgTHa1YA UrogKB+UpBftmb4ds+XlkEJ1dvwokiSbCDaWFKD+YD4B2s0bvjCbw8xuZFYGhNyR /2D5XfN1s2MCAwEAAaOCATkwggE1MA4GA1UdDwEB/wQEAwIBBjAPBgNVHRMBAf8E BTADAQH/MG0GA1UdHwRmMGQwYqBgoF6kXDBaMQswCQYDVQQGEwJKUDENMAsGA1UE CgwESlBLSTEpMCcGA1UECwwgUHJlZmVjdHVyYWwgQXNzb2NpYXRpb24gRm9yIEpQ S0kxETAPBgNVBAsMCEJyaWRnZUNBMIGDBgNVHREEfDB6pHgwdjELMAkGA1UEBhMC SlAxJzAlBgNVBAoMHuWFrOeahOWAi+S6uuiqjeiovOOCteODvOODk+OCuTEeMBwG A1UECwwV6YO96YGT5bqc55yM5Y2U6K2w5LyaMR4wHAYDVQQLDBXjg5bjg6rjg4Pj grjoqo3oqLzlsYAwHQYDVR0OBBYEFNQXMiCqQNkR2OaZmQgLtf8mR8p8MA0GCSqG SIb3DQEBBQUAA4IBAQATjJo4reTNPC5CsvAKu1RYT8PyXFVYHbKsEpGt4GR8pDCg HEGAiAhHSNrGh9CagZMXADvlG0gmMOnXowriQQixrtpkmx0TB8tNAlZptZWkZC+R 8TnjOkHrk2nFAEC3ezbdK0R7MR4tJLDQCnhEWbg50rf0wZ/aF8uAaVeEtHXa6W0M Xq3dSe0XAcrLbX4zZHQTaWvdpLAIjl6DZ3SCieRMyoWUL+LXaLFdTP5WBCd+No58 IounD9X4xxze2aeRVaiV/WnQ0OSPNS7n7YXy6xQdnaOU4KRW/Lne1EDf5IfWC/ih bVAmhZMbcrkWWcsR6aCPG+2mV3zTD6AUzuKPal8Y -----END CERTIFICATE----- heimdal-7.5.0/lib/hx509/data/openssl.cnf0000644000175000017500000001025313026237312015761 0ustar niknikoid_section = new_oids [new_oids] pkkdcekuoid = 1.3.6.1.5.2.3.5 [ca] default_ca = user [usr] database = index.txt serial = serial x509_extensions = usr_cert default_md=sha1 policy = policy_match email_in_dn = no certs = . [ocsp] database = index.txt serial = serial x509_extensions = ocsp_cert default_md=sha1 policy = policy_match email_in_dn = no certs = . [usr_ke] database = index.txt serial = serial x509_extensions = usr_cert_ke default_md=sha1 policy = policy_match email_in_dn = no certs = . [usr_ds] database = index.txt serial = serial x509_extensions = usr_cert_ds default_md=sha1 policy = policy_match email_in_dn = no certs = . [pkinit_client] database = index.txt serial = serial x509_extensions = pkinit_client_cert default_md=sha1 policy = policy_match email_in_dn = no certs = . [pkinit_kdc] database = index.txt serial = serial x509_extensions = pkinit_kdc_cert default_md=sha1 policy = policy_match email_in_dn = no certs = . [https] database = index.txt serial = serial x509_extensions = https_cert default_md=sha1 policy = policy_match email_in_dn = no certs = . [subca] database = index.txt serial = serial x509_extensions = v3_ca default_md=sha1 policy = policy_match email_in_dn = no certs = . [req] distinguished_name = req_distinguished_name x509_extensions = v3_ca # The extensions to add to the self signed cert string_mask = utf8only [v3_ca] subjectKeyIdentifier=hash authorityKeyIdentifier=keyid:always,issuer:always basicConstraints = CA:true keyUsage = cRLSign, keyCertSign, keyEncipherment, nonRepudiation, digitalSignature [usr_cert] basicConstraints=CA:FALSE keyUsage = nonRepudiation, digitalSignature, keyEncipherment subjectKeyIdentifier = hash [usr_cert_ke] basicConstraints=CA:FALSE keyUsage = nonRepudiation, keyEncipherment subjectKeyIdentifier = hash [proxy_cert] basicConstraints=CA:FALSE keyUsage = nonRepudiation, digitalSignature, keyEncipherment subjectKeyIdentifier = hash proxyCertInfo=critical,language:id-ppl-anyLanguage,pathlen:0,policy:text:foo [pkinitc_principals] princ1 = GeneralString:bar [pkinitc_principal_seq] name_type = EXP:0,INTEGER:1 name_string = EXP:1,SEQUENCE:pkinitc_principals [pkinitc_princ_name] realm = EXP:0,GeneralString:TEST.H5L.SE principal_name = EXP:1,SEQUENCE:pkinitc_principal_seq [pkinit_client_cert] basicConstraints=CA:FALSE keyUsage = nonRepudiation, digitalSignature, keyEncipherment subjectKeyIdentifier = hash subjectAltName=otherName:1.3.6.1.5.2.2;SEQUENCE:pkinitc_princ_name [https_cert] basicConstraints=CA:FALSE keyUsage = nonRepudiation, digitalSignature, keyEncipherment #extendedKeyUsage = https-server XXX subjectKeyIdentifier = hash [pkinit_kdc_cert] basicConstraints=CA:FALSE keyUsage = nonRepudiation, digitalSignature, keyEncipherment extendedKeyUsage = pkkdcekuoid subjectKeyIdentifier = hash subjectAltName=otherName:1.3.6.1.5.2.2;SEQUENCE:pkinitkdc_princ_name [pkinitkdc_princ_name] realm = EXP:0,GeneralString:TEST.H5L.SE principal_name = EXP:1,SEQUENCE:pkinitkdc_principal_seq [pkinitkdc_principal_seq] name_type = EXP:0,INTEGER:1 name_string = EXP:1,SEQUENCE:pkinitkdc_principals [pkinitkdc_principals] princ1 = GeneralString:krbtgt princ2 = GeneralString:TEST.H5L.SE [proxy10_cert] basicConstraints=CA:FALSE keyUsage = nonRepudiation, digitalSignature, keyEncipherment subjectKeyIdentifier = hash proxyCertInfo=critical,language:id-ppl-anyLanguage,pathlen:10,policy:text:foo [usr_cert_ds] basicConstraints=CA:FALSE keyUsage = nonRepudiation, digitalSignature subjectKeyIdentifier = hash [ocsp_cert] basicConstraints=CA:FALSE keyUsage = nonRepudiation, digitalSignature, keyEncipherment # ocsp-nocheck and kp-OCSPSigning extendedKeyUsage = 1.3.6.1.5.5.7.48.1.5, 1.3.6.1.5.5.7.3.9 subjectKeyIdentifier = hash [req_distinguished_name] countryName = Country Name (2 letter code) countryName_default = SE countryName_min = 2 countryName_max = 2 organizationalName = Organizational Unit Name (eg, section) commonName = Common Name (eg, YOUR name) commonName_max = 64 #[req_attributes] #challengePassword = A challenge password #challengePassword_min = 4 #challengePassword_max = 20 [policy_match] countryName = match commonName = supplied heimdal-7.5.0/lib/hx509/data/key.der0000644000175000017500000000114112136107750015071 0ustar niknik0]ªB[u^Tӕ-|˜zk:6{漎:~~M\F*<4=<]KIŋY4ˤx+{Oʭ`n  @9.LM}.#$-K n~=HM#R!v >VTehtI{A,)t9МѱX]8ksmS_ۤM+k|сA>8p%VM/w1?_P.]ԛpW2[P?%Mheimdal-7.5.0/lib/hx509/data/proxy-level-test.key0000644000175000017500000000162412136107750017570 0ustar niknik-----BEGIN PRIVATE KEY----- MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBAO3ICAWZ2JzsnuWt y+dWYA29pFW3sWiphcqhzFCOFv9uDMGOsVWqJTGd+x60cIxmU9lqSW+JxIAplC+7 fQsGf0g501v6M+0gWYblX8BlRb84DEpDEe1u0mCS2CqgZscatvRqM8N8zjgpom/U pTQYknn5upjhc4RY7KkOz5nWJ51vAgMBAAECgYBRzwSTiL7yHqb8trL0wM8Daz/j DfRH4itZ8BjvjjNzZlWVMpbotkVdsND5W3Ntmrc2kk75xRiKT8PgOE1pQa8AbL7F uR1U5itWKbyKCOPA/mzYoh9Pw9IouB4noNFzwDWnilsviV4yshKzKQtjryHPe1ft RuF7YdGjsweUJriNoQJBAPeP6+fiT2WO/pXiextMhACU2fkgskgi+CFD+z6r8JtP Kysk5+2PM6iSMm1XkBYxmPbCYMJtzShXnm3X41LgUgMCQQD14sSt9s9rIcT4w01P oUm5d3MGgLf1khBzUT9VdKqb0ZqmtTBANKmU8GP2jmSguItNRiSbSiyvL3pitoHl o0ElAkA5XEaLzvsYi/5fGj/t/lejjtnGiJXmcvvNMWQ4jDxOsBRPhdibSY/toho/ DYfcLJfFrRogUrKzg0G5L8mDPWijAkA1vOjFKGKuhEPbJjvYQmStbwipjCooNlL4 EPKph4Td5xJIiuLPtXK2hU8jjH07jvmK2uCXO7/GTbcOqdp7yJEtAkEAhFuJnqk8 7N+TMUouU6DRCioGI6kg3kGPXD2p0dZn2XoTVvluklv9s4cpH5ht7BxKw6flDPqC ity2FjTxEJ88BQ== -----END PRIVATE KEY----- heimdal-7.5.0/lib/hx509/data/secp256r2TestServer.key.pem0000644000175000017500000000036113026237312020561 0ustar niknik-----BEGIN PRIVATE KEY----- MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQgKo/47DaveCl90GxH LCE7IGBua2XsE+jI4RUWZrqjhBGhRANCAASLWYJ9QvGQbypJDaBKH1i9CSwk2h09 pSY+3fY0bUiokdj5TrXeR4bXg6j+/CuHoJUTJOZ6rJhKKGpX2zbBQcvE -----END PRIVATE KEY----- heimdal-7.5.0/lib/hx509/data/no-proxy-test.key0000644000175000017500000000162012136107750017071 0ustar niknik-----BEGIN PRIVATE KEY----- MIICdQIBADANBgkqhkiG9w0BAQEFAASCAl8wggJbAgEAAoGBAKI/Z1n5TK1eKUyq II2UrEdGsr9EpzSQ2pRCkrxIHuzXliZv6jpet2Rafxbu+gl+bMNLpt8tPLM13Oz0 N233mjgEiNw0Y3qvwXaPddfPSLnSo0UBpqcL2i2gfoHoidM8S/DGzs2AimUdh7cJ p8gLblcQc4PyZG0Yr2TWOnhbo3s9AgMBAAECgYBWdSjy1hkZDWM+mi3MpFwFg1P+ /muHZGVFuhANSvVHyj4V729GeXCKhnrQ0rnk0zzL+QVMSgPdj6dRkXX0IIxJ0iyI k7ZVoaCuC8dmc/rF9pJ58saqKYCqQFtjdFO68E3aQbnk89ai69AzgdjegRSVmOQ8 yJ9ArHcggxbEqGq94QJBANOk9UWdI72KbIRElrTtWAvIrNaF4iixR+AdYuFL2+cJ WaGApfFtcNppllmbWxh0IayIDzRpWzSpTILNLQdqF9UCQQDEQDzfZ04+x2RhX28o O1Vzqkado6OvyhwVlzp19ZGstMWq6IVNZEJDBYCilk7dkIkjBHojaVEu/k9vMUZS KzHJAkBk6xmRUjbCoIjSISqDp1D+fXf86uZGZRJSyXBm4Zc/+XNl0URPdNIFM6ff nna3mFiePlqRsVMuLzQugstf57TpAkAYCvqqMADRBiKRH10B48sDQaAnHe4m0i8A oidiXjR7oSX6W0RBh//qMBljUeDVmiiC5sCD6BovFK7so2/HD02pAkA9zFWyVTdq Y3t01+ZG6TfcxwKGCgpwS3x9OQbMVb34JPQ65U0JzW7ubmYFMD5Fl1RPjDbLc+wm uSnStI7RGOt+ -----END PRIVATE KEY----- heimdal-7.5.0/lib/hx509/data/test-signed-sha-10000644000175000017500000000747312136107750016703 0ustar niknik07 *H (0$1 0 +0 D *H  5 1This is a static file don't change the content, it is used in the test #!/bin/sh # # Copyright (c) 2005 Kungliga Tekniska Hgskolan # (Royal Institute of Technology, Stockholm, Sweden). # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # 1. Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # # 3. Neither the name of the Institute nor the names of its contributors # may be used to endorse or promote products derived from this software # without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE # ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS # OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) # HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY # OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF # SUCH DAMAGE. # # srcdir="@srcdir@" echo "try printing" ./hxtool print \ --pass=PASS:foobar \ PKCS12:$srcdir/data/test.p12 || exit 1 echo "make sure entry is found (friendlyname)" ./hxtool query \ --pass=PASS:foobar \ --friendlyname=friendlyname-test \ PKCS12:$srcdir/data/test.p12 || exit 1 echo "make sure entry is not found (friendlyname)" ./hxtool query \ --pass=PASS:foobar \ --friendlyname=friendlyname-test-not \ PKCS12:$srcdir/data/test.p12 && exit 1 echo "check for ca cert (friendlyname)" ./hxtool query \ --pass=PASS:foobar \ --friendlyname=ca \ PKCS12:$srcdir/data/test.p12 || exit 1 echo "make sure entry is not found (friendlyname)" ./hxtool query \ --pass=PASS:foobar \ --friendlyname=friendlyname-test \ PKCS12:$srcdir/data/sub-cert.p12 && exit 1 echo "make sure entry is found (friendlyname|private key)" ./hxtool query \ --pass=PASS:foobar \ --friendlyname=friendlyname-test \ --private-key \ PKCS12:$srcdir/data/test.p12 || exit 1 echo "make sure entry is not found (friendlyname|private key)" ./hxtool query \ --pass=PASS:foobar \ --friendlyname=ca \ --private-key \ PKCS12:$srcdir/data/test.p12 && exit 1 exit 0 00c0  *H 0*10U hx509 Test Root CA1 0 USE0 090426202940Z 190424202940Z0!1 0 USE10U Test cert00  *H 0jy̫0*q s֤Uq3m)V@c~[jP"´F>{M>z|-`@B(<|_J*M Ty͠f9070 U00 U0Uwn !x|ùfL=J#0  *H E#0θɶ.JdWdJʠ+1C9$MT?6 tL(C'"xqBjW{RѧyYi\ _\P$p Signature Algorithm: sha1WithRSAEncryption b5:ab:c2:d5:f8:30:fc:bb:b3:53:c2:42:a0:f1:4d:a0:5c:92: 1a:c7:dc:01:df:42:6a:d2:c8:79:18:ae:a7:09:8e:ea:1c:97: 80:93:b1:e3:23:4d:ca:15:f5:f8:c2:d0:38:5d:0d:76:7b:41: 47:f1:a4:77:26:86:2c:69:2a:5c:86:32:00:09:da:04:3c:d6: 30:9d:a3:0a:e2:b1:a6:36:2f:ff:3c:80:d6:e7:2a:8b:49:dd: d8:24:98:7a:15:0a:29:f0:4b:30:ae:73:b5:af:70:7a:3a:b0: 40:27:a7:4e:74:8c:46:1e:2f:bb:cc:57:63:30:bf:b1:38:81: 10:bd -----BEGIN CERTIFICATE----- MIICMTCCAZqgAwIBAgIBBjANBgkqhkiG9w0BAQUFADAqMRswGQYDVQQDDBJoeDUw OSBUZXN0IFJvb3QgQ0ExCzAJBgNVBAYTAlNFMB4XDTA5MDQyNjIwMjk0MFoXDTE5 MDQyNDIwMjk0MFowHjELMAkGA1UEBhMCU0UxDzANBgNVBAMMBnBraW5pdDCBnzAN BgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEAskdC3Eb4lONmK/kmFFZBaOF6BM1VRa7g qEiAM1j8hk/oZ2KJ99S60buaaoMbTgG1fJ6y0r+EIZhYHbZN+q/y5ejU1nijBtpp FQnY+gcJl88aOyxpsliiC0hONxEs9XqPUORAFCkoMKwLtQoeYLSa1I28OMkvqdE1 58nUGGYcFS0CAwEAAaNzMHEwCQYDVR0TBAIwADALBgNVHQ8EBAMCBeAwHQYDVR0O BBYEFOg/GovCipz5tE+V2VUpDKULDhPGMDgGA1UdEQQxMC+gLQYGKwYBBQICoCMw IaANGwtURVNULkg1TC5TRaEQMA6gAwIBAaEHMAUbA2JhcjANBgkqhkiG9w0BAQUF AAOBgQC1q8LV+DD8u7NTwkKg8U2gXJIax9wB30Jq0sh5GK6nCY7qHJeAk7HjI03K FfX4wtA4XQ12e0FH8aR3JoYsaSpchjIACdoEPNYwnaMK4rGmNi//PIDW5yqLSd3Y JJh6FQop8EswrnO1r3B6OrBAJ6dOdIxGHi+7zFdjML+xOIEQvQ== -----END CERTIFICATE----- heimdal-7.5.0/lib/hx509/data/sub-cert.p120000644000175000017500000000570012136107750015662 0ustar niknik0 0  *H  s o0 k0/ *H  00 *H 0 *H  0!{H‚ _ qM( S@cDG['wэߨʹҀÂ.@%[WJStxJ"u{6o|]ܮXyTF Q̩Vi\&]u훫g}Q-+b$0TFk$m82.8G/aF*sVd]pO'zh^)6O 8B׺>Zhptuw8-~v QTi0NVComUHyne/#$,i(G_4uV|݁ ufK9''^#n$7t0Uk-#܋CAG!j6s0@&yO_mMt?W~OM$?b,ES5TBB,fIp*Nh q2wJHtb:W5%O$6 n3RIClSfJ`I U/|NLbߺϹɛh>0z ̰~\VwUL uqu^ cl9Lsln/Dh;#M#=tDK.@}h&h lۇ$YZ8 r*w$bI$цhG3ӅFqؓniFe@0HOvQNk gٜ]VP+ [9eʦ>[1HM6! *u ]MŤH-<5юAȎbMUP4 L/ H>hʃv6` Q,'qT2Ԅ MTPTC?qE`p琀(RfU5xAi;- (<:cilN*j!G҃"wsr$PL/wwp`G4|1 u%L@? mOB0h᮵jK~M\<VNv5u bț uUf{M 쀪Kqe*P`w3LU`. J/U:båszYcvNcb ,TSsaA4gmrɅ g L`pag:;u| y]~BztLDf+)D;`Sygvg :.^ܻVl'H[ŢW= 2}"E@bNԆ0A:̔JR6.ɸX1JrFp^L(`T"<ۣ-Z=xx"brti&coZoǃ}Pa. 3\mL#|iWLkxb$oT/#k3LfD?Yo7Vb*s :TӣzbI 88.v uX^k^g*t};F pUpR$~>5X\s\Pc&]cݝT*xIgF~Ca…KOcSm=]8R:fH;#O su7v+`(wr4nZ.jXjSI;D`1$|EEJ6a mU,-* z:JPD5dotnȆD:`bl^:;_U5@̺04 *H %!00 *H  00 *H  0_Si*\}&]+`F Xc4qIM魉ZpɎwL:LyrѰHd m{aМJPqoèKLQ0CP1䭆"oJFIEiu8CΉ?o\y ~WTQԵ[1>P-at+WY+ŁT+IL[`1zq>5u|Ԃ#ʅ0ښ4;YbӤ h޲qU-L{I^/q!N7FO> uߍ?$$œ EY7ȴ*1/'el耙ib>GU>U1[Zj⢿YWC@4#Wdc OcIY n0'ῶ!c]&fْ}w̡kt:cBEY;b%ьTFC'pd 9viS^u{@4(UP|Fi=\,N0x7]K_>zۚ9Ji/Zdbob:].-MՎxOҭ/P7ʥA^ĐcƎ, IfJ3i,5:YoXz!P=%[{]1`0# *H  1Mj teI`209 *H  1,*friendlyname-sub-cert010!0 +({Z{倾sr}3i1ply heimdal-7.5.0/lib/hx509/data/test-enveloped-aes-2560000644000175000017500000000613012136107750017551 0ustar niknik0 T *H  E0 A100/0*10U hx509 Test Root CA1 0 USE0  *H <[bw#/fDhnrqvFϡo)TCxut."2/W&;-˚uVugƧk>حAbj5R.k_0 n *H 0 `He*u̝b~ݍt3Ҁ @\x!!? (Wk'2kAaGG^t7܂KN^A/U3Zнb6V5YՅ;tb'|S+uBro+ُheWد (*0NԢu'X8d{>DSZMPWjO Fʜ&V9P6yh7Gk,(ih'tc= l]n}`25]B9>T_Y)TkL`juX طrB.۷Cytdy6̯N?=;A<| PJĸ 4k/(\Ը$ 5CgIMnP=koR#AYݡ>v5J!y&.cQ h+*ѶWU&~Q7®p[c~]7W{Z7?8gk3p:2]Eј Jynv?=SXi2pm̖ Hfw(BOݝ]J&;Zn9~x%KƳXTo!TGYOrLP iQ&J@C͚&z9K&+η1{ط57W^M_kz?:'ⴝgM^>v!=覲Kc^-%L:=ApuDݐE="`m_CUJM^Щq8(Y|`| hkqJOoj\ Mb9k:. AvxU6Jga`j퍐=UQC mB {Hقo`HNR]_}a jTby42>ոC;韑ϔrͦ)DP|v"+ s,1@ɻWR DKS~|[J8Y9m0}ǁlq0}D O2'(%8@Tk:e#6SWK;)]-1 sm&ZX'%!04xcO!\iN#7KFx|XzI(9%o&= QNޑt[=ڦWݤe0˦e] 6yT0+9ZAd1}Q`ύP+S^$^/ݺFj\4K9(3]*CfҫNc+?8WVn2j 0}4=X؋&pZ`Y̗‘@wH4 n$y)u#21ꕏ8 27ݱaYd '*5$Z˦O,0uQhj7Ug)v8Ѐ:0 umh@FQkTL2ʪ1; }*CaQG !J#78cm9茁Re$CyIR Ji^9!V.lQ z@RfSdR_3` ^]{ G"#J δH3ry%n>u@T$HMdXuU)7SUg`3K;{r;? F1Z 8C&uTpUP29sc t&q@S"]d>ͽ3Kh"e;Xhz@:[VyoR wrKD7Ua0!Xj\ 4+pZCW17]?XN)lLri)aaQeJDJy7p@q\^,M ؃iy@=g18qQa.3o-Orł ףZ󖓱=v(_-heimdal-7.5.0/lib/hx509/data/https.key0000644000175000017500000000162412136107750015467 0ustar niknik-----BEGIN PRIVATE KEY----- MIICeAIBADANBgkqhkiG9w0BAQEFAASCAmIwggJeAgEAAoGBAMb0lCUr1frpPQCp RiTxv/5h373M2nS3+TbBzlHSAW95urNK1aRDWset5OBQ4qa/VHOtpYYKvVbET7X1 f37+EHgX4jVMu8xLdDXQq2OxAnKUp5rcEO8ogqls3BmNuD5bIVIfiFGmWvhnzctI b/WLcXxNUtq7+SaKJ5x+itGZVDV/AgMBAAECgYBfO282I7d3NPGYQW5r/LPUBfFd HpNqzy0hQr+JdqZtP61YaPe+eucXMWue29jBzE+WV4YllTpwL+Ofy3VNyjsDCIva acqVrimYl5EAT1yiqvC1DNC0SvAfEsBlpMJr7w8F4M7wbSxvGIWjRVeZtLd7H4pw 8ooDNZNlcXPyrBozQQJBAPGxPPiO66EpiN66ffRiqnof1lGUFaZPqBKYF/M3mybt X7vMKQsrQpdNQTbtR2u42yBUJGw4trhIn1qDInkgXfECQQDSu61Z/m5xRVlBk3mj QMqSVX+FoD3WtSry003lcxGfNsuguJtYHXHHhPbPNMUaDEtErkbUMQHNFX5mEjGp 0RpvAkEAwbDhhOy8pw5rMtvP3w9HQdHL5tq/MuY5cpVS9EaG335yL0VhSyMjHa/6 6HLlvs2JRnJIMjaNMEh69IWNFfc7cQJBAIOzIy3BI0jLLHMdNcHfdjpqEJ50fPE4 nDTR9jbV6Ud1uWEivoMdM8SbxpvMwPn8gPXVbRKj5hpDupEUAdG9iyUCQQCNSVcl NREl42G5ZQ2Q+zYtYIJbe9SAxu7WcfzctFleRbmKPLqrcnCLWenWWHtrzZLRgFhw rLiglEkVDRXivfhq -----END PRIVATE KEY----- heimdal-7.5.0/lib/hx509/data/test-signed-sha-5120000644000175000017500000000756012136107750017047 0ustar niknik0l *H ]0Y10  `He0 D *H  5 1This is a static file don't change the content, it is used in the test #!/bin/sh # # Copyright (c) 2005 Kungliga Tekniska Hgskolan # (Royal Institute of Technology, Stockholm, Sweden). # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # 1. Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # # 3. Neither the name of the Institute nor the names of its contributors # may be used to endorse or promote products derived from this software # without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE # ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS # OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) # HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY # OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF # SUCH DAMAGE. # # srcdir="@srcdir@" echo "try printing" ./hxtool print \ --pass=PASS:foobar \ PKCS12:$srcdir/data/test.p12 || exit 1 echo "make sure entry is found (friendlyname)" ./hxtool query \ --pass=PASS:foobar \ --friendlyname=friendlyname-test \ PKCS12:$srcdir/data/test.p12 || exit 1 echo "make sure entry is not found (friendlyname)" ./hxtool query \ --pass=PASS:foobar \ --friendlyname=friendlyname-test-not \ PKCS12:$srcdir/data/test.p12 && exit 1 echo "check for ca cert (friendlyname)" ./hxtool query \ --pass=PASS:foobar \ --friendlyname=ca \ PKCS12:$srcdir/data/test.p12 || exit 1 echo "make sure entry is not found (friendlyname)" ./hxtool query \ --pass=PASS:foobar \ --friendlyname=friendlyname-test \ PKCS12:$srcdir/data/sub-cert.p12 && exit 1 echo "make sure entry is found (friendlyname|private key)" ./hxtool query \ --pass=PASS:foobar \ --friendlyname=friendlyname-test \ --private-key \ PKCS12:$srcdir/data/test.p12 || exit 1 echo "make sure entry is not found (friendlyname|private key)" ./hxtool query \ --pass=PASS:foobar \ --friendlyname=ca \ --private-key \ PKCS12:$srcdir/data/test.p12 && exit 1 exit 0 00c0  *H 0*10U hx509 Test Root CA1 0 USE0 090426202940Z 190424202940Z0!1 0 USE10U Test cert00  *H 0jy̫0*q s֤Uq3m)V@c~[jP"´F>{M>z|-`@B(<|_J*M Ty͠f9070 U00 U0Uwn !x|ùfL=J#0  *H E#0θɶ.JdWdJv)&6|heimdal-7.5.0/lib/hx509/data/sub-ca.crt0000644000175000017500000000572412136107750015504 0ustar niknikCertificate: Data: Version: 3 (0x2) Serial Number: 10 (0xa) Signature Algorithm: sha1WithRSAEncryption Issuer: CN=hx509 Test Root CA, C=SE Validity Not Before: Apr 26 20:29:41 2009 GMT Not After : Apr 24 20:29:41 2019 GMT Subject: C=SE, CN=Sub CA Subject Public Key Info: Public Key Algorithm: rsaEncryption Public-Key: (1024 bit) Modulus: 00:bd:3d:63:78:3e:31:85:d9:1d:b7:f8:04:02:58: 53:12:de:1a:c6:95:9b:51:29:7b:c7:62:76:b9:a6: 63:56:3d:47:c8:2f:bb:6b:9b:7d:d8:f1:a9:3c:0b: 61:66:fd:d1:e7:d7:6d:74:a0:30:9c:a0:7d:80:41: 04:1a:86:61:b4:12:79:9d:9d:b0:3b:fb:0a:4c:69: 8f:06:33:07:85:0e:73:cd:01:fa:96:f9:6b:20:18: d8:b1:06:03:21:b3:71:7a:ed:43:fd:29:d5:23:fa: cc:cf:43:fc:83:4a:cb:8b:e6:98:db:b3:49:f1:ba: 2a:97:72:b7:44:83:d6:e7:5f Exponent: 65537 (0x10001) X509v3 extensions: X509v3 Subject Key Identifier: 9B:B5:FE:90:D3:72:49:B1:98:9A:67:76:A3:C9:22:15:F1:5A:AE:11 X509v3 Authority Key Identifier: keyid:6E:48:13:DC:BF:8B:95:4C:13:F3:1F:97:30:DD:27:96:59:9B:0E:68 DirName:/CN=hx509 Test Root CA/C=SE serial:99:32:DE:61:0E:40:19:8A X509v3 Basic Constraints: CA:TRUE X509v3 Key Usage: Digital Signature, Non Repudiation, Key Encipherment, Certificate Sign, CRL Sign Signature Algorithm: sha1WithRSAEncryption 25:cb:bf:77:d2:16:0f:a5:ac:4e:42:17:e1:81:03:36:1e:dc: 33:1a:49:ba:1f:40:5b:5b:80:9c:20:b7:13:3b:f4:4f:79:c1: b4:6e:14:d5:fd:84:59:58:d5:db:a6:6d:5b:6f:e6:d0:58:d6: 8e:41:2c:ef:e9:c8:b7:ca:6f:cb:11:6e:13:45:f7:73:6e:91: 71:22:14:18:b9:b4:ad:3b:c4:e9:6f:99:6d:59:59:52:6f:c8: 65:67:f1:e4:d9:6f:0b:a3:3c:9f:ac:01:b7:1a:9b:97:74:92: 7b:ea:05:a0:5d:09:77:fb:79:17:c2:35:2f:f9:09:fc:10:b3: e0:3e -----BEGIN CERTIFICATE----- MIICWDCCAcGgAwIBAgIBCjANBgkqhkiG9w0BAQUFADAqMRswGQYDVQQDDBJoeDUw OSBUZXN0IFJvb3QgQ0ExCzAJBgNVBAYTAlNFMB4XDTA5MDQyNjIwMjk0MVoXDTE5 MDQyNDIwMjk0MVowHjELMAkGA1UEBhMCU0UxDzANBgNVBAMMBlN1YiBDQTCBnzAN BgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEAvT1jeD4xhdkdt/gEAlhTEt4axpWbUSl7 x2J2uaZjVj1HyC+7a5t92PGpPAthZv3R59dtdKAwnKB9gEEEGoZhtBJ5nZ2wO/sK TGmPBjMHhQ5zzQH6lvlrIBjYsQYDIbNxeu1D/SnVI/rMz0P8g0rLi+aY27NJ8boq l3K3RIPW518CAwEAAaOBmTCBljAdBgNVHQ4EFgQUm7X+kNNySbGYmmd2o8kiFfFa rhEwWgYDVR0jBFMwUYAUbkgT3L+LlUwT8x+XMN0nllmbDmihLqQsMCoxGzAZBgNV BAMMEmh4NTA5IFRlc3QgUm9vdCBDQTELMAkGA1UEBhMCU0WCCQCZMt5hDkAZijAM BgNVHRMEBTADAQH/MAsGA1UdDwQEAwIB5jANBgkqhkiG9w0BAQUFAAOBgQAly793 0hYPpaxOQhfhgQM2HtwzGkm6H0BbW4CcILcTO/RPecG0bhTV/YRZWNXbpm1bb+bQ WNaOQSzv6ci3ym/LEW4TRfdzbpFxIhQYubStO8Tpb5ltWVlSb8hlZ/Hk2W8Lozyf rAG3GpuXdJJ76gWgXQl3+3kXwjUv+Qn8ELPgPg== -----END CERTIFICATE----- heimdal-7.5.0/lib/hx509/data/pkinit-proxy.key0000644000175000017500000000162412136107750017002 0ustar niknik-----BEGIN PRIVATE KEY----- MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBANKxpMj4is1Zy+3R QfaZyhIbPkK+1237l10YqJmh5vB4WF+VriouCw8bXK/Q84rnGlr48fYa3qquiuT7 TzUyBJ/vGMhuBosnO4zI3usM7wcp9zfmykesP/5ef1HRe8Lv2F1HZkLc6N4jo5lI GtnlnXe4qJjbjTPsY4x0PVl5QV0DAgMBAAECgYEAo99RWJKferqV92GjmYbh+RVB Zq6CZmOhxeHw+JVJRs2Dhsynit0G8vgILiMp2WaIRCuOHiml+EELfK/OWoSNvOGy q0ss+mu0Jm3d9bQUYE7O6fBbFtY9zYIYOVWP4YCIyA0su48W3Fk+wQeNewKj396Q 7tx4aBn5f8DARkZrVRECQQDxX81pSf8VTnNQNhvp76YhANGtBhiJ8OtADCNUoJT+ sKAPa8HiBTHL2alkBbi/b4whOzePCJSjHTinkEBE+iuJAkEA33XtpR3ACDCtrvAo WNdE7zt4yV4tByzmQCK3u3ZxSJOPKinR55tUjZynqghZmpS+XSE5rRwmsx75ZwkP oNdlKwJBALcPmZJI9JUMMpia8QCzKKPPIza+cM3tUf35NrJwN5ASFNKdPyZUGjgo lDevvzYxO23Yo4JvV4t+FgG/fX7S3UECQFh1/tXWqSaU3qzaNZ612Xw7Nt3AgmLM y3moRMPZZ48rmwk99PKS8y38TgNpus8PAy0q8gItmsReBq1bUOyDWHECQDQOIlRO k1OWBLD4PLYaxB1c5F59tfCV+cRlm/sYTnDjdDWWu8D2Qhjhz367iLLMJvV2Klyu 7FwUNyfKI6Tk3oY= -----END PRIVATE KEY----- heimdal-7.5.0/lib/hx509/data/test-enveloped-aes-1280000644000175000017500000000613012136107750017547 0ustar niknik0 T *H  E0 A100/0*10U hx509 Test Root CA1 0 USE0  *H [ِTApc{K s'm"iD,;*WlqYzpp Xe_!)@R:AK#'pElTsJ9YOT@t+8WF7SׯPrzi0 n *H 0 `He( 1 ^ 4Ң @,`’ݏlX{r"#h=I0i\wqJ_-a7۩!A@a $Y x¼ ^ov.XI4 _u_bRR]o|Q+bYen>F1qi%β4,jt897/ЈJx|ޟ>$b?̿*hܪml`-c|)]`kU =vuL`n"E:3t)\wOTOFI%YpA9mxO8+`tNphcn҃^~ν+2%DgE5=[ĨK`[6;1/s 6,nڝڜ(,wS_S71n`p]YߕeFM~Sr%A&ۦg-}~7@f}[1AnhqoF+>R1cqfkcad7Lk|A0d*W/S2GY.6qDs2# i>]?SĻX*s3D U,nU8$GG-ׇ`Ū'CFm+Ѭh]cLpN,ًdݯq iܭxDѓ2P|꼲L{[ZPk1Ew$eӖfFǬ94&m -7qtɤde0 2J ct u6BpvVb9\{\L -[Bo&i N(N2F'O]WTRK+,\k"H{$IRŏ4oX[GmO zF sMD<G;0َ85)>̛MW9dK+!:+k{ qE~Voi"냾Τ3߾/LAƱG1ډ+=9i9}T*H&\(|hCqJYL>슙~kT ddZe%h;8JZn]Tю`CP + zk0'̗Ȅv0M1VđTrU*Gɨ' qG l@:/Ftw ;}uAXOm$ "ϗMO)\Hc3nKn)dxB 鷬8vwCkBVX*5ODl"(UWI0ۓ\5iݦ/_EĮްQ/DL!*/F>$r]58u_$ ż[B3}P-D1 R6f_qi;՟i1ix x/.lVo,$P7F܍o+9j(XvqP~C2#uh,\y=$j/Zה[v z-**%{]U VF_2[~c4g'Fï5aMu nR H[縷u=z"T9KcNH;s8a0ȊȪׄޑ?'| mb鑴O9M>oAfheimdal-7.5.0/lib/hx509/data/ca.crt0000644000175000017500000000160312136107750014705 0ustar niknik-----BEGIN CERTIFICATE----- MIICbDCCAdWgAwIBAgIJAJky3mEOQBmKMA0GCSqGSIb3DQEBBQUAMCoxGzAZBgNV BAMMEmh4NTA5IFRlc3QgUm9vdCBDQTELMAkGA1UEBhMCU0UwHhcNMDkwNDI2MjAy OTQwWhcNMTkwNDI0MjAyOTQwWjAqMRswGQYDVQQDDBJoeDUwOSBUZXN0IFJvb3Qg Q0ExCzAJBgNVBAYTAlNFMIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC50xtn HPdeJoE7gv8DpEO1smMLiVhD/j3gOH2TdLutIaQp2TR58xyMWtaw1xnqzK/gqEAC HZHxrDaw+wi9zJrht27uCmm/bSvuIIJhBvIYzIkRZH6y/0fRO1Jz61rAA6ZLx0B+ vOEOZUQ/QIsCglQE2cwsZwG2FoLYM1MX196NXQIDAQABo4GZMIGWMB0GA1UdDgQW BBRuSBPcv4uVTBPzH5cw3SeWWZsOaDBaBgNVHSMEUzBRgBRuSBPcv4uVTBPzH5cw 3SeWWZsOaKEupCwwKjEbMBkGA1UEAwwSaHg1MDkgVGVzdCBSb290IENBMQswCQYD VQQGEwJTRYIJAJky3mEOQBmKMAwGA1UdEwQFMAMBAf8wCwYDVR0PBAQDAgHmMA0G CSqGSIb3DQEBBQUAA4GBAFKb5A7uwl238bpH4/6vPVEQ/egNFFgFNqfr2AXlJ29R uOyQ2QPhvJyTOCFcr05se2xlqZLNlO+orpASFHgtoxWqQvHZRGQsPMC9OkjYgEWL 0XmC4A/fCDxgIW8xR5iuL8uxobnBo3FeSsJn32YKUbWtYAXbAtQa0rlOAQgrw1ev -----END CERTIFICATE----- heimdal-7.5.0/lib/hx509/data/test-nopw.p120000644000175000017500000000425512136107750016102 0ustar niknik00o *H `\0X0P *H A=090 *H  0 *H  00c0  *H 0*10U hx509 Test Root CA1 0 USE0 090426202940Z 190424202940Z0!1 0 USE10U Test cert00  *H 0jy̫0*q s֤Uq3m)V@c~[jP"´F>{M>z|-`@B(<|_J*M Ty͠f9070 U00 U0Uwn !x|ùfL=J#0  *H E#0θɶ.JdWdJ{M>z|-`@B(<|_J*M Ty͠fRSl95ѽ=˺J3HXR3uKն<}# RWdH#v?Id$_%<ʺN&ZdR9NQGab=9Ak8fш׼"CAK4-4Otg6Cb,N'w]E뺞]\kFԪ3[)B=B>ԎuAFMou%{n)&bs]YD~jr$$#@- AÖh;E3uUmpG̉voS>. `ж#ן(ƻE?[Ań %@{d+q= ,@ b`>J?aRM[MRUeo$a@T$˲GΘ9LҶ6Ӈ9#) +tQQFQ߁*X=>1X0# *H  1A{맳GY\cYj01 *H  1$"friendlyname-cert010!0 +x=ʹ_G߬{?84Qheimdal-7.5.0/lib/hx509/data/proxy10-child-child-test.crt0000644000175000017500000000162012136107750020762 0ustar niknik-----BEGIN CERTIFICATE----- MIICdDCCAd2gAwIBAgIJANtSso4F/YPoMA0GCSqGSIb3DQEBBQUAMEMxCzAJBgNV BAYTAlNFMRIwEAYDVQQDDAlUZXN0IGNlcnQxEDAOBgNVBAMMB3Byb3h5MTAxDjAM BgNVBAMMBWNoaWxkMB4XDTA5MDQyNjIwMjk0MVoXDTE5MDQyNDIwMjk0MVowUzEL MAkGA1UEBhMCU0UxEjAQBgNVBAMMCVRlc3QgY2VydDEQMA4GA1UEAwwHcHJveHkx MDEOMAwGA1UEAwwFY2hpbGQxDjAMBgNVBAMMBWNoaWxkMIGfMA0GCSqGSIb3DQEB AQUAA4GNADCBiQKBgQDcgI+5RZZeSRqK8ydQYyVqk2DGI8dLUkWE68TthxWg5Xjp jD9tVt8y3kcQWXIWqeNjmKS6zQHDro/d8oS6oHVMyFakxq4uQD5DvaTeLFjmK/4i IrVlJS+T8kUMNoqGgNYY7BppcUU0Nav/whldGlhtEEWEEu4EZ+4UbCj5QCHZwwID AQABo2AwXjAJBgNVHRMEAjAAMAsGA1UdDwQEAwIF4DAdBgNVHQ4EFgQUrbpGGsqI EM708LMvCSGULkOS0CowJQYIKwYBBQUHAQ4BAf8EFjAUAgEKMA8GCCsGAQUFBxUA BANmb28wDQYJKoZIhvcNAQEFBQADgYEAFk/qvmcnH5QqMLxEtUY9O+2A1ag6iJEs 18sIp87PRLP06OmtWPkijS+7c7Dbs5ttwAWW8tZ9+f+yyXE2ctwrc2ap3TicrTB8 yI2Fgf+ytxgpZharMjeUi9E10K/xKxU3hsrD7ug3iHp15HKyuP8uFmBP6gcsVsgj tsIaPKR43xU= -----END CERTIFICATE----- heimdal-7.5.0/lib/hx509/data/test.p120000644000175000017500000000442012136107750015113 0ustar niknik0 0 *H 00 *H x0t0m *H 0 *H  0뉙@(3q$E=c/Z0:voV#=z̹-`4,0{pԥ .ZpI6MإLj=M!}@ihNbQbUQ:4P#Z |~D1-uGkq$2n:7vwH1I&5%lPgZ/5Dra<|M[|TDbԽXBn-wb/T DM.l8]zpbcXWK=Q^pցa`)n◢ 0wdP6^U c4*Wzl;=UVɻBA7tIN^^ÃwE)X6\;vy5mZJp?pZKN6Z7Rb]Z,6Ϗ"pq5vL!DX̷ə_?`$?VĶL !vP<իuu3v]HT&+OP`2n~;$b4uN Zʗ4wƃl^ܑ[,I^&&4xѸX8^˻?quCr(4d|z&MˁRFҶ 2o-j_o 0)"zTXۇ gLF? {&)dzBA\ o]xe]oCdVY>&Gt [;wѹ}/ F#&NVYN^%eS~ 3&^šxw뀐CH3 b\dX-PHeqD4w!ȌC Z>TC_c5x{:rKk_;_d*1k-(`VuI ~d>1?{fKT{#L:s 1R(\޽-l 7qF3{!$IkdlSDoTvJޭfШ2qYJ<"":#x?I潴jm5,9aycjCPډZthyQƋ &oQtH+]:zMqA͵J((!x_Q.vk.o3)~kA[Ӂ!8f|r秞Xel]&r0s;/ҖkV2r.5W>O7栗lݝM*kfgҾv)ŸnǺ/ΌBs$m0, *H 00 *H  00 *H  0 NDWpGr0IW=Jl6::XK_L j>DK!S9':J̓<(Sí)lå_{A z-FLgu92 Àw_͔dq55.Q(l{n2>(J&Q?2=&p?S(r&pK)LGQZg]86@8'/(]m1ɎQgc7RJIZBRxMj h(IQy|eY4qrF^#$WvZ T:8ax3T ASlN8vdS>S|}RXhkOA'p(GX{M>z|-`@B(<|_J*M Ty͠f9070 U00 U0Uwn !x|ùfL=J#0  *H E#0θɶ.JdWdJR[EX(V |1'o␵P5>|߰=e]&Fy9ely9]eL02I|Vo 66lhy/4NNUJZ!K/w4z%_ bHɧheimdal-7.5.0/lib/hx509/data/kdc.crt0000644000175000017500000000554312136107750015072 0ustar niknikCertificate: Data: Version: 3 (0x2) Serial Number: 8 (0x8) Signature Algorithm: sha1WithRSAEncryption Issuer: CN=hx509 Test Root CA, C=SE Validity Not Before: Apr 26 20:29:40 2009 GMT Not After : Apr 24 20:29:40 2019 GMT Subject: C=SE, CN=kdc Subject Public Key Info: Public Key Algorithm: rsaEncryption Public-Key: (1024 bit) Modulus: 00:d2:41:7a:f8:4b:55:b2:af:11:f9:43:9b:43:81: 09:3b:9a:94:cf:00:f4:85:75:92:d7:2a:a5:11:f1: a8:50:6e:c6:84:74:24:17:da:84:c8:03:37:b2:20: f3:ba:b5:59:36:21:4d:ab:70:e2:c3:09:93:68:14: 12:79:c5:bb:9e:1b:4a:f0:c6:24:59:25:c3:1c:a8: 70:66:5b:3e:41:8e:e3:25:71:9a:94:a0:5b:46:91: 6f:dd:58:14:ec:89:e5:8c:96:c5:38:60:e4:ab:f2: 75:ee:6e:62:fc:e1:bd:03:47:ff:c4:be:0f:ca:70: 73:e3:74:58:3a:2f:04:2d:39 Exponent: 65537 (0x10001) X509v3 extensions: X509v3 Basic Constraints: CA:FALSE X509v3 Key Usage: Digital Signature, Non Repudiation, Key Encipherment X509v3 Extended Key Usage: pkkdcekuoid X509v3 Subject Key Identifier: 3A:D3:73:FF:AB:DB:7D:8D:C6:3A:A2:26:3E:AE:78:95:80:C9:E6:31 X509v3 Subject Alternative Name: othername: Signature Algorithm: sha1WithRSAEncryption 83:f4:14:a7:6e:59:ff:80:64:e7:fa:cf:13:80:86:e1:ed:02: 38:ad:96:72:25:e5:06:7a:9a:bc:24:74:a9:75:55:b2:49:80: 69:45:95:4a:4c:76:a9:e3:4e:49:d3:c2:69:5a:95:03:eb:ba: 72:23:9c:fd:3d:8b:c6:07:82:3b:f4:f3:ef:6c:2e:9e:0b:ac: 9e:6c:bb:37:4a:a1:9e:73:d1:dc:97:61:ba:fc:d3:49:a6:c2: 4c:55:2e:06:37:76:b5:ef:57:e7:57:58:8a:71:63:f3:eb:e7: 55:68:0d:f6:46:4c:fb:f9:43:bb:0c:92:4f:4e:22:7b:63:e8: 4f:9c -----BEGIN CERTIFICATE----- MIICVDCCAb2gAwIBAgIBCDANBgkqhkiG9w0BAQUFADAqMRswGQYDVQQDDBJoeDUw OSBUZXN0IFJvb3QgQ0ExCzAJBgNVBAYTAlNFMB4XDTA5MDQyNjIwMjk0MFoXDTE5 MDQyNDIwMjk0MFowGzELMAkGA1UEBhMCU0UxDDAKBgNVBAMMA2tkYzCBnzANBgkq hkiG9w0BAQEFAAOBjQAwgYkCgYEA0kF6+EtVsq8R+UObQ4EJO5qUzwD0hXWS1yql EfGoUG7GhHQkF9qEyAM3siDzurVZNiFNq3DiwwmTaBQSecW7nhtK8MYkWSXDHKhw Zls+QY7jJXGalKBbRpFv3VgU7InljJbFOGDkq/J17m5i/OG9A0f/xL4PynBz43RY Oi8ELTkCAwEAAaOBmDCBlTAJBgNVHRMEAjAAMAsGA1UdDwQEAwIF4DASBgNVHSUE CzAJBgcrBgEFAgMFMB0GA1UdDgQWBBQ603P/q9t9jcY6oiY+rniVgMnmMTBIBgNV HREEQTA/oD0GBisGAQUCAqAzMDGgDRsLVEVTVC5INUwuU0WhIDAeoAMCAQGhFzAV GwZrcmJ0Z3QbC1RFU1QuSDVMLlNFMA0GCSqGSIb3DQEBBQUAA4GBAIP0FKduWf+A ZOf6zxOAhuHtAjitlnIl5QZ6mrwkdKl1VbJJgGlFlUpMdqnjTknTwmlalQPrunIj nP09i8YHgjv08+9sLp4LrJ5suzdKoZ5z0dyXYbr800mmwkxVLgY3drXvV+dXWIpx Y/Pr51VoDfZGTPv5Q7sMkk9OIntj6E+c -----END CERTIFICATE----- heimdal-7.5.0/lib/hx509/data/secp256r2TestClient.key.pem0000644000175000017500000000036113026237312020531 0ustar niknik-----BEGIN PRIVATE KEY----- MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQg6oD5CbNzN7oAWqcq dKJKw2WU5EwnUV05+7S9gXgeW/qhRANCAATu/zAiAR3/IEC0OZbadbsgjggMPLsp WWe/r/6wd6Ch7gCMi+qv0I2V2R9xUeVXCMwDWrzeUgH8fQhSaT5PqVCE -----END PRIVATE KEY----- heimdal-7.5.0/lib/hx509/data/secp256r2TestServer.cert.pem0000644000175000017500000000121013026237312020720 0ustar niknik-----BEGIN CERTIFICATE----- MIIBsDCCAVWgAwIBAgIBAjAKBggqhkjOPQQDAjA2MQswCQYDVQQGEwJTRTEQMA4G A1UEChMHSGVpbWRhbDEVMBMGA1UEAxMMQ0Egc2VjcDI1NnIxMB4XDTE0MDMxMDE5 NDAyM1oXDTM4MDExNzE5NDAyM1owMDELMAkGA1UEBhMCU0UxEDAOBgNVBAoTB0hl aW1kYWwxDzANBgNVBAMTBlNlcnZlcjBZMBMGByqGSM49AgEGCCqGSM49AwEHA0IA BItZgn1C8ZBvKkkNoEofWL0JLCTaHT2lJj7d9jRtSKiR2PlOtd5HhteDqP78K4eg lRMk5nqsmEooalfbNsFBy8SjWjBYMB0GA1UdDgQWBBTqMDTOezcRsax6lf6E/Xk+ QzPorjAfBgNVHSMEGDAWgBTrUd8AqGhfZvHVspcznXeb328JgzAJBgNVHRMEAjAA MAsGA1UdDwQEAwIEsDAKBggqhkjOPQQDAgNJADBGAiEAsvf//YdUWCD6OLZesENa 1mH8+b+kZDR6jx1JchRXAEQCIQDkTvTZrlmmxUaWEsf08/4xbxkYbrPAg4+VX2uI QcEwUA== -----END CERTIFICATE----- heimdal-7.5.0/lib/hx509/data/test.crt0000644000175000017500000000512512136107750015304 0ustar niknikCertificate: Data: Version: 3 (0x2) Serial Number: 2 (0x2) Signature Algorithm: sha1WithRSAEncryption Issuer: CN=hx509 Test Root CA, C=SE Validity Not Before: Apr 26 20:29:40 2009 GMT Not After : Apr 24 20:29:40 2019 GMT Subject: C=SE, CN=Test cert Subject Public Key Info: Public Key Algorithm: rsaEncryption Public-Key: (1024 bit) Modulus: 00:e8:6a:8a:12:02:ed:86:e3:1a:b6:79:18:cc:ab: c3:d4:cf:30:f4:dc:2a:90:71:c3:00:18:20:84:73: d6:a4:55:b6:71:e4:33:fd:b7:a3:e3:6d:d4:ff:29: d2:56:7f:40:63:e4:bf:12:8a:16:7e:ff:5b:e9:6a: ce:50:b4:e3:85:11:a1:22:cd:c2:b4:e5:46:b2:0f: 3e:04:85:7b:a5:4d:3e:7a:b8:c7:7c:d0:2d:fb:95: 60:d1:40:42:bc:28:ae:f1:3c:7c:0e:5f:ca:e4:8f: fc:4a:2a:1d:ef:10:05:4d:09:54:b7:12:16:79:bb: bf:cd:a0:92:66:9e:94:e1:ff Exponent: 65537 (0x10001) X509v3 extensions: X509v3 Basic Constraints: CA:FALSE X509v3 Key Usage: Digital Signature, Non Repudiation, Key Encipherment X509v3 Subject Key Identifier: CE:77:6E:DE:0B:F4:21:F8:78:C0:1A:7C:C3:B9:66:EC:4C:3D:4A:23 Signature Algorithm: sha1WithRSAEncryption 45:23:30:f4:ce:b8:c9:b6:a0:2e:4a:a0:64:bd:be:57:d5:64: ed:4a:8d:95:a3:9a:19:3c:56:7b:14:a6:2e:6c:37:37:ae:2a: b1:42:2e:0c:b8:7e:57:f5:5a:38:29:8d:78:53:b3:2d:c8:c2: 97:f3:ab:51:6a:c4:df:86:97:ca:68:55:39:e0:f8:99:5a:bd: a4:e1:34:50:34:8f:70:d2:74:2d:b8:90:ef:b8:d2:22:3a:ce: be:82:a8:4b:b3:32:cd:1b:8d:0b:69:7d:0c:d7:b6:33:dc:68: 41:76:a1:36:20:8e:ba:34:45:be:71:bd:ab:bf:74:77:87:e6: bf:7f -----BEGIN CERTIFICATE----- MIIB+jCCAWOgAwIBAgIBAjANBgkqhkiG9w0BAQUFADAqMRswGQYDVQQDDBJoeDUw OSBUZXN0IFJvb3QgQ0ExCzAJBgNVBAYTAlNFMB4XDTA5MDQyNjIwMjk0MFoXDTE5 MDQyNDIwMjk0MFowITELMAkGA1UEBhMCU0UxEjAQBgNVBAMMCVRlc3QgY2VydDCB nzANBgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEA6GqKEgLthuMatnkYzKvD1M8w9Nwq kHHDABgghHPWpFW2ceQz/bej423U/ynSVn9AY+S/EooWfv9b6WrOULTjhRGhIs3C tOVGsg8+BIV7pU0+erjHfNAt+5Vg0UBCvCiu8Tx8Dl/K5I/8Siod7xAFTQlUtxIW ebu/zaCSZp6U4f8CAwEAAaM5MDcwCQYDVR0TBAIwADALBgNVHQ8EBAMCBeAwHQYD VR0OBBYEFM53bt4L9CH4eMAafMO5ZuxMPUojMA0GCSqGSIb3DQEBBQUAA4GBAEUj MPTOuMm2oC5KoGS9vlfVZO1KjZWjmhk8VnsUpi5sNzeuKrFCLgy4flf1WjgpjXhT sy3Iwpfzq1FqxN+Gl8poVTng+JlavaThNFA0j3DSdC24kO+40iI6zr6CqEuzMs0b jQtpfQzXtjPcaEF2oTYgjro0Rb5xvau/dHeH5r9/ -----END CERTIFICATE----- heimdal-7.5.0/lib/hx509/data/revoke.crt0000644000175000017500000000513312136107750015617 0ustar niknikCertificate: Data: Version: 3 (0x2) Serial Number: 3 (0x3) Signature Algorithm: sha1WithRSAEncryption Issuer: CN=hx509 Test Root CA, C=SE Validity Not Before: Apr 26 20:29:40 2009 GMT Not After : Apr 24 20:29:40 2019 GMT Subject: C=SE, CN=Revoke cert Subject Public Key Info: Public Key Algorithm: rsaEncryption Public-Key: (1024 bit) Modulus: 00:a6:5f:11:30:35:3a:5f:ed:c2:06:ac:f4:14:27: c1:db:ae:79:f0:b6:9e:0a:83:e7:82:6a:69:92:a6: 85:9c:5d:e4:8a:0e:6b:32:99:4d:22:b9:ea:a6:8c: 84:9e:62:f0:a3:f1:d2:b0:ef:41:ce:93:ce:d9:49: 43:be:0d:a7:ea:cd:37:bb:ba:4d:ee:75:ed:86:74: 8a:e2:08:77:2b:60:91:30:b2:96:57:4e:42:d1:5e: 6f:0d:f5:b2:d6:98:ed:3f:ab:a0:64:33:8b:52:ad: b5:7a:4a:fd:70:dc:d8:8b:e1:47:0c:8d:8f:93:5c: 9c:35:3f:cb:21:d7:5c:6c:b3 Exponent: 65537 (0x10001) X509v3 extensions: X509v3 Basic Constraints: CA:FALSE X509v3 Key Usage: Digital Signature, Non Repudiation, Key Encipherment X509v3 Subject Key Identifier: AC:ED:61:9B:1A:7D:7D:27:D4:E3:B9:3D:79:9C:F1:96:10:B3:46:45 Signature Algorithm: sha1WithRSAEncryption 71:4d:fc:63:69:bb:b5:cf:0c:50:dc:de:55:ef:9b:90:07:42: 98:3e:80:36:e4:94:aa:d5:f3:0b:56:38:12:1d:3d:e6:dc:a3: 8b:bf:8a:f6:82:d6:25:8b:9c:88:ce:38:2a:ee:e1:2f:2e:8f: c7:74:c6:42:5f:68:99:a5:48:e7:08:5a:bd:3c:fa:db:14:5a: 39:cc:dc:50:c5:ba:05:97:c9:66:9e:39:d8:ce:17:a6:ec:6b: bd:c9:c9:a8:d1:6d:dc:68:c0:79:20:6e:df:04:0a:14:37:06: 7b:e8:54:62:60:0c:9f:d5:73:55:b7:d0:4f:cb:e0:14:75:65: b7:d1 -----BEGIN CERTIFICATE----- MIIB/DCCAWWgAwIBAgIBAzANBgkqhkiG9w0BAQUFADAqMRswGQYDVQQDDBJoeDUw OSBUZXN0IFJvb3QgQ0ExCzAJBgNVBAYTAlNFMB4XDTA5MDQyNjIwMjk0MFoXDTE5 MDQyNDIwMjk0MFowIzELMAkGA1UEBhMCU0UxFDASBgNVBAMMC1Jldm9rZSBjZXJ0 MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCmXxEwNTpf7cIGrPQUJ8Hbrnnw tp4Kg+eCammSpoWcXeSKDmsymU0iueqmjISeYvCj8dKw70HOk87ZSUO+DafqzTe7 uk3ude2GdIriCHcrYJEwspZXTkLRXm8N9bLWmO0/q6BkM4tSrbV6Sv1w3NiL4UcM jY+TXJw1P8sh11xsswIDAQABozkwNzAJBgNVHRMEAjAAMAsGA1UdDwQEAwIF4DAd BgNVHQ4EFgQUrO1hmxp9fSfU47k9eZzxlhCzRkUwDQYJKoZIhvcNAQEFBQADgYEA cU38Y2m7tc8MUNzeVe+bkAdCmD6ANuSUqtXzC1Y4Eh095tyji7+K9oLWJYuciM44 Ku7hLy6Px3TGQl9omaVI5whavTz62xRaOczcUMW6BZfJZp452M4XpuxrvcnJqNFt 3GjAeSBu3wQKFDcGe+hUYmAMn9VzVbfQT8vgFHVlt9E= -----END CERTIFICATE----- heimdal-7.5.0/lib/hx509/data/yutaka-pad-broken-cert.pem0000644000175000017500000000201212136107750020557 0ustar niknik-----BEGIN CERTIFICATE----- MIICzTCCAjagAwIBAgIJAOSnzE4Qx2H/MA0GCSqGSIb3DQEBBQUAMDkxCzAJBgNV BAYTAkpQMRQwEgYDVQQKEwtDQSBURVNUIDEtNDEUMBIGA1UEAxMLQ0EgVEVTVCAx LTQwHhcNMDYwOTA3MTY0MDM3WhcNMDcwOTA3MTY0MDM3WjBPMQswCQYDVQQGEwJK UDEOMAwGA1UECBMFVG9reW8xFjAUBgNVBAoTDVRFU1QgMiBDTElFTlQxGDAWBgNV BAMTD3d3dzIuZXhhbXBsZS5qcDCBnzANBgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEA vSpZ6ig9DpeKB60h7ii1RitNuvkn4INOfEXjCjPSFwmIbGJqnyWvKTiMKzguEYkG 6CZAbsx44t3kvsVDeUd5WZBRgMoeQd1tNJBU4BXxOA8bVzdwstzaPeeufQtZDvKf M4ej+fo/j9lYH9udCug1huaNybcCtijzGonkddX4JEUCAwEAAaOBxjCBwzAJBgNV HRMEAjAAMCwGCWCGSAGG+EIBDQQfFh1PcGVuU1NMIEdlbmVyYXRlZCBDZXJ0aWZp Y2F0ZTAdBgNVHQ4EFgQUK0DZtd8K1P2ij9gVKUNcHlx7uCIwaQYDVR0jBGIwYIAU 340JbeYcg6V9zi8aozy48aIhtfihPaQ7MDkxCzAJBgNVBAYTAkpQMRQwEgYDVQQK EwtDQSBURVNUIDEtNDEUMBIGA1UEAxMLQ0EgVEVTVCAxLTSCCQDkp8xOEMdh/jAN BgkqhkiG9w0BAQUFAAOBgQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA AAAAAAAAAUKJ+eFJYSvXwGF2wxzDXj+x5YCItrHFmrEy4AXXAW+H0NgJVNvqRY/O Kw== -----END CERTIFICATE----- heimdal-7.5.0/lib/hx509/data/proxy10-child-test.key0000644000175000017500000000162412136107750017705 0ustar niknik-----BEGIN PRIVATE KEY----- MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBAK/fNlaMWtQ4XCCG ttruaDuPey9hRdK/dcmYdiI2NNl0hmy4shVejsClC0ZYufOwTK8qvBtAQSgJl1b2 bMziznvcVXoqVpMhcYhdrOhEWCe5rhx18SEMhoETMYbA7oqohnOdU2fth+wNgiB2 81DnaJvan1MF6snfIg/Tf2v2ctyXAgMBAAECgYBbnR/2J7js0csT2nkIRKahWBWo UbiIltmpwTTQj4IqQKwBmJiTzyT3r0HXTELZcV4Q5WcFnwwR6iUe1NFKTV+XgrcK OMBY43+6InTvsXAKxLH6MZ7tfKWA13forzs90CmvYxTHtEFYS2MnzZ7FFqBk59lA gMrcDVKYiOLenjKm6QJBANuEuoq/ZiNC9bJ3JjVyH/yHYqAwi6g8B8kQufecAqIu eQBpx2vsry8V6LpTfIsle8dWFKauiE4s5VyBMn7l2kMCQQDNGZHFI9j8SaGVGmbF 5nDtBnWoyAWCQ3VzTj+uaO/ybkTFFvVkVLU1+3j2cWRVYdnoXK9uL2eH9E35radx d6EdAkEAyEI2l1ryh5qPYEb4MWuyqIKtw6tlzI0vIQtETBIkCOZSdsEJL3jVfCQF ku2Uwa/pUrlBz6mLKZ4lg5VNhpyT1wJAEfXaQQQ5nSYpgzATreLXIrp9FTGm4dhc caN5iiFgWb90QDoZdRbB459I4XPekGeIOIPdTO3TyCEJrwKY9iO+tQJAGdLTwcsz o1Ic+rVL8IfXPRCwtvi3e/xVgGxDHhV498/ofY3xgVmOkSRdDjAz2FgZeaotnKj6 d9og/gBzfNdK2g== -----END PRIVATE KEY----- heimdal-7.5.0/lib/hx509/data/bleichenbacher-sf-pad-correct.pem0000644000175000017500000000164412136107750022045 0ustar niknik-----BEGIN CERTIFICATE----- MIICgzCCAWugAwIBAgIBFzANBgkqhkiG9w0BAQUFADBoMQswCQYDVQQGEwJVUzEl MCMGA1UEChMcU3RhcmZpZWxkIFRlY2hub2xvZ2llcywgSW5jLjEyMDAGA1UECxMp U3RhcmZpZWxkIENsYXNzIDIgQ2VydGlmaWNhdGlvbiBBdXRob3JpdHkwHhcNMDYw ODE5MTY1MTMwWhcNMDYxMDE4MTY1MTMwWjARMQ8wDQYDVQQDEwZIYWNrZXIwgZ8w DQYJKoZIhvcNAQEBBQADgY0AMIGJAoGBAKSu6ChWttBsOpaBrYf4PzyCGNe6DuE7 rmq4CMskdz8uiAJ3wVd8jGsjdeY4YzoXSVp+9mEF6XqNgyDf8Ub3kNgPYxvJ28lg QVpd5RdGWXHo14LWBTD1mtFkCiAhVlATsVNI/tjv2tv7Jp8EsylbDHe7hslA0rns Rr2cS9bvpM03AgMBAAGjEzARMA8GA1UdEwEB/wQFMAMBAf8wDQYJKoZIhvcNAQEF BQADggEBAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADLL/Up63HkFWD15INcW Xd1nZGI+gO/whm58ICyJ1Js7ON6N4NyBTwe8513CvdOlOdG/Ctmy2gxEE47HhEed ST8AUooI0ey599t84P20gGRuOYIjr7c= -----END CERTIFICATE----- heimdal-7.5.0/lib/hx509/data/test-ds-only.crt0000644000175000017500000000515412136107750016671 0ustar niknikCertificate: Data: Version: 3 (0x2) Serial Number: 5 (0x5) Signature Algorithm: sha1WithRSAEncryption Issuer: CN=hx509 Test Root CA, C=SE Validity Not Before: Apr 26 20:29:40 2009 GMT Not After : Apr 24 20:29:40 2019 GMT Subject: C=SE, CN=Test cert DigitalSignature Subject Public Key Info: Public Key Algorithm: rsaEncryption Public-Key: (1024 bit) Modulus: 00:eb:6c:c9:0d:97:91:ab:88:5c:44:a7:40:ed:25: b1:d9:0d:cd:22:1e:07:80:15:49:05:b0:7d:f2:bc: 6c:12:7a:4a:74:a8:26:4c:98:0f:29:d0:b2:68:21: c3:bb:6a:cd:4a:27:71:5b:8b:51:12:ed:47:cc:21: 94:ee:05:11:55:61:2c:88:22:33:c2:4e:12:ca:ed: 63:00:10:4c:4f:7c:62:97:a0:9f:95:2a:99:d7:8e: a7:8a:d7:53:b2:b2:7d:a8:b7:5f:dd:4c:79:30:e7: 48:0e:0d:9d:6d:85:04:56:63:d4:27:53:09:a9:bc: b3:c1:67:1e:65:bb:4e:10:a5 Exponent: 65537 (0x10001) X509v3 extensions: X509v3 Basic Constraints: CA:FALSE X509v3 Key Usage: Digital Signature, Non Repudiation X509v3 Subject Key Identifier: 30:2F:86:11:EA:5A:CD:C6:B4:61:FC:11:59:74:34:7C:16:93:25:52 Signature Algorithm: sha1WithRSAEncryption 15:f4:85:10:1a:98:d7:ec:74:4c:2b:55:1f:db:c9:2f:e0:ad: 2d:76:83:17:e1:13:d7:17:8d:27:a7:e3:21:1f:63:f2:30:94: ae:9f:1f:b9:4f:6a:6b:ce:50:7d:1a:a7:4e:be:f1:98:33:16: a0:53:a3:06:61:4f:6e:11:8b:55:3f:cd:91:4f:0a:0b:2d:f1: 5a:68:13:e2:f9:25:88:00:74:79:e8:f4:a9:c4:5c:9e:df:c0: 17:e2:e5:75:54:3d:64:65:52:b4:a5:9c:51:ff:c3:ec:8f:88: 06:18:f6:a5:42:b9:d9:75:7b:d1:4c:d1:fa:ab:89:b3:24:5a: 14:aa -----BEGIN CERTIFICATE----- MIICCzCCAXSgAwIBAgIBBTANBgkqhkiG9w0BAQUFADAqMRswGQYDVQQDDBJoeDUw OSBUZXN0IFJvb3QgQ0ExCzAJBgNVBAYTAlNFMB4XDTA5MDQyNjIwMjk0MFoXDTE5 MDQyNDIwMjk0MFowMjELMAkGA1UEBhMCU0UxIzAhBgNVBAMMGlRlc3QgY2VydCBE aWdpdGFsU2lnbmF0dXJlMIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDrbMkN l5GriFxEp0DtJbHZDc0iHgeAFUkFsH3yvGwSekp0qCZMmA8p0LJoIcO7as1KJ3Fb i1ES7UfMIZTuBRFVYSyIIjPCThLK7WMAEExPfGKXoJ+VKpnXjqeK11Oysn2ot1/d THkw50gODZ1thQRWY9QnUwmpvLPBZx5lu04QpQIDAQABozkwNzAJBgNVHRMEAjAA MAsGA1UdDwQEAwIGwDAdBgNVHQ4EFgQUMC+GEepazca0YfwRWXQ0fBaTJVIwDQYJ KoZIhvcNAQEFBQADgYEAFfSFEBqY1+x0TCtVH9vJL+CtLXaDF+ET1xeNJ6fjIR9j 8jCUrp8fuU9qa85QfRqnTr7xmDMWoFOjBmFPbhGLVT/NkU8KCy3xWmgT4vkliAB0 eej0qcRcnt/AF+LldVQ9ZGVStKWcUf/D7I+IBhj2pUK52XV70UzR+quJsyRaFKo= -----END CERTIFICATE----- heimdal-7.5.0/lib/hx509/data/proxy10-test.key0000644000175000017500000000162012136107750016620 0ustar niknik-----BEGIN PRIVATE KEY----- MIICdQIBADANBgkqhkiG9w0BAQEFAASCAl8wggJbAgEAAoGBAMDC8URG8ymbo6N7 jqZ/i1riivvD9xRwnnCuf1/WmVHr8RM6IIYp/iL3/1iPy+vQwUtI1xsumKlKr8kO iJAlC4K9/AZ7+D8ibRvKFxaapy+ZRAn62n+oGytlCoowBnEETWvO8GylapAIUcM5 5svNyXXOZMNysODCw7SPQQ4VGIiTAgMBAAECgYBTMM7nZKd1AZKx75U1Dj6aTsMk vQJZc/EtOGIIfplU3bsBTUjUHjNr7BPrqMOdVk7Vqu4K8SU5it4qq3cMnrBETxTA k3oLwIM5U/MLF8PCxFFfjARA3iqp5ldCBRbFwBi3iBa3+dxRQgx0TYdhg32LPE4a 7sAz+GGSHspa8mPR4QJBAP9qA1LSsSi/hargSNaNnCEy/4YW7MIkbJwX3A0INGT5 cEUhSG+w0UhnkAf0Hi8/Gh19EsvDEOY/Nu6ucSmmnK8CQQDBNCNO2Qae7GJSOPLQ T6RpcFThH/7D09gCnF25V5An3jawT2BNue8iHxKztOwneSw16D1xSDm3nIs8m8sJ gXNdAkBs9pY6ZEZOIv7seki4t6svAqm+U9Nns9Bd+1PWf3SSy1OZOmzDsYRnRj9N FVk3QM1sXSqCoVJ5V+ighO0kHr9jAkARbnvVDF29jwRb+MlnpBfob3spCLL6xi1S JvuJ0m2uOy1iAPdma+U4hecxEZzQ/uzPPFH225Zhi51AbaoHBIf9AkBHxYNY9TPW nWpEcH7Mq+5KdAgXhXb0uWQbWoK7m/wm7OY8KQMc2Uo1chatb0qxlmUxZvQXva+w QxahbNp1Uyun -----END PRIVATE KEY----- heimdal-7.5.0/lib/hx509/data/test-ke-only.crt0000644000175000017500000000515212136107750016660 0ustar niknikCertificate: Data: Version: 3 (0x2) Serial Number: 4 (0x4) Signature Algorithm: sha1WithRSAEncryption Issuer: CN=hx509 Test Root CA, C=SE Validity Not Before: Apr 26 20:29:40 2009 GMT Not After : Apr 24 20:29:40 2019 GMT Subject: C=SE, CN=Test cert KeyEncipherment Subject Public Key Info: Public Key Algorithm: rsaEncryption Public-Key: (1024 bit) Modulus: 00:c0:85:dd:0b:7f:d7:6a:ee:c0:ab:e3:06:fd:40: 44:10:23:e3:94:62:a0:b8:09:af:cd:01:eb:47:92: 5b:07:c8:7a:84:b8:72:12:cb:42:a4:b1:be:77:08: 5f:e9:6c:d5:05:3f:eb:61:9b:96:68:39:65:79:04: c1:08:c3:8a:b3:bd:42:79:31:b6:3b:23:1e:d0:04: b1:dc:80:5b:dd:1f:53:a7:60:78:bd:74:d4:27:70: 1f:0a:e5:1f:42:97:ff:8d:af:c8:03:99:e4:28:f2: da:b0:ea:34:a0:d4:39:37:59:37:f4:71:1e:bb:55: ad:d7:91:b2:a1:c0:5e:40:7f Exponent: 65537 (0x10001) X509v3 extensions: X509v3 Basic Constraints: CA:FALSE X509v3 Key Usage: Non Repudiation, Key Encipherment X509v3 Subject Key Identifier: 95:66:6F:BD:03:40:04:B1:BA:9B:FC:A6:F1:CF:B6:93:41:B9:AB:61 Signature Algorithm: sha1WithRSAEncryption 3e:d9:cb:96:da:5f:4d:49:10:45:2f:42:cf:32:9a:d7:fe:72: 4f:24:d7:60:e1:0e:df:da:03:73:44:4f:27:7e:f9:cf:aa:16: c5:18:8a:ec:0d:56:0a:1f:1e:41:87:0a:67:62:d5:73:20:26: e1:2e:10:6d:cd:ef:c2:28:2b:99:9a:13:5c:73:ad:a2:7d:5c: 34:31:42:b2:44:52:ad:4f:96:06:30:b8:31:59:b6:e1:68:5d: a0:ee:0f:83:45:1e:51:9d:8d:bc:8f:43:9f:42:c5:82:90:e4: 00:9b:91:13:40:e4:15:60:e6:cd:3a:29:a9:4c:a1:c8:33:0d: d6:24 -----BEGIN CERTIFICATE----- MIICCjCCAXOgAwIBAgIBBDANBgkqhkiG9w0BAQUFADAqMRswGQYDVQQDDBJoeDUw OSBUZXN0IFJvb3QgQ0ExCzAJBgNVBAYTAlNFMB4XDTA5MDQyNjIwMjk0MFoXDTE5 MDQyNDIwMjk0MFowMTELMAkGA1UEBhMCU0UxIjAgBgNVBAMMGVRlc3QgY2VydCBL ZXlFbmNpcGhlcm1lbnQwgZ8wDQYJKoZIhvcNAQEBBQADgY0AMIGJAoGBAMCF3Qt/ 12ruwKvjBv1ARBAj45RioLgJr80B60eSWwfIeoS4chLLQqSxvncIX+ls1QU/62Gb lmg5ZXkEwQjDirO9QnkxtjsjHtAEsdyAW90fU6dgeL101CdwHwrlH0KX/42vyAOZ 5Cjy2rDqNKDUOTdZN/RxHrtVrdeRsqHAXkB/AgMBAAGjOTA3MAkGA1UdEwQCMAAw CwYDVR0PBAQDAgVgMB0GA1UdDgQWBBSVZm+9A0AEsbqb/Kbxz7aTQbmrYTANBgkq hkiG9w0BAQUFAAOBgQA+2cuW2l9NSRBFL0LPMprX/nJPJNdg4Q7f2gNzRE8nfvnP qhbFGIrsDVYKHx5BhwpnYtVzICbhLhBtze/CKCuZmhNcc62ifVw0MUKyRFKtT5YG MLgxWbbhaF2g7g+DRR5RnY28j0OfQsWCkOQAm5ETQOQVYObNOimpTKHIMw3WJA== -----END CERTIFICATE----- heimdal-7.5.0/lib/hx509/data/win-u16-in-printablestring.der0000644000175000017500000000140412136107750021322 0ustar niknik00vBG G>t?܋0 +0-1+0)U"w2k8r2.matws.net0 100428114154Z 110428114154Z0-1+0)U"w2k8r2.matws.net0"0  *H 0 2&iWJU+[}48섆>G.qÿwӰVkB+&\BQZUk0,6M_YW9[49"qYz@{2_l2X|B6Wxc`Wp69qZ*%IH_,Xm,,smOp?_7bI7!zy ^B"1'JN}'{q'GW]!ܡ?t>G GBvܡ?t>G GBv0 +fu~}1됀%Y-5"t6O'\c{*Yvw@x|1botm;W٩}_ĕޗCp'c_ -?] '@_]T(.H`qFiۈ{-%2vI v%Ce|3ua9k0cF(yvH8r?%S1ћ\!*Le8zEVGnn{K@<veT!\'heimdal-7.5.0/lib/hx509/data/yutaka-pad-broken-ca.pem0000644000175000017500000000165412136107750020220 0ustar niknik-----BEGIN CERTIFICATE----- MIICijCCAfOgAwIBAgIJAOSnzE4Qx2H+MA0GCSqGSIb3DQEBBQUAMDkxCzAJBgNV BAYTAkpQMRQwEgYDVQQKEwtDQSBURVNUIDEtNDEUMBIGA1UEAxMLQ0EgVEVTVCAx LTQwHhcNMDYwOTA3MTYzMzE4WhcNMDYxMDA3MTYzMzE4WjA5MQswCQYDVQQGEwJK UDEUMBIGA1UEChMLQ0EgVEVTVCAxLTQxFDASBgNVBAMTC0NBIFRFU1QgMS00MIGd MA0GCSqGSIb3DQEBAQUAA4GLADCBhwKBgQDZfFjkPDZeorxWqk7/DKM2d/9Nao28 dM6T5sb5L41hD5C1kXV6MJev5ALASSxtI6OVOmZO4gfubnsvcj0NTZO4SeF1yL1r VDPdx7juQI1cbDiG/EwIMW29UIdj9h052JTmEbpT0RuP/4JWmAWrdO5UE40xua7S z2/6+DB2ZklFoQIBA6OBmzCBmDAdBgNVHQ4EFgQU340JbeYcg6V9zi8aozy48aIh tfgwaQYDVR0jBGIwYIAU340JbeYcg6V9zi8aozy48aIhtfihPaQ7MDkxCzAJBgNV BAYTAkpQMRQwEgYDVQQKEwtDQSBURVNUIDEtNDEUMBIGA1UEAxMLQ0EgVEVTVCAx LTSCCQDkp8xOEMdh/jAMBgNVHRMEBTADAQH/MA0GCSqGSIb3DQEBBQUAA4GBABsH aJ/c/3cGHssi8IvVRci/aavqj607y7l22nKDtG1p4KAjnfNhBMOhRhFv00nJnokK y0uc4DIegAW1bxQjqcMNNEmGbzAeixH/cRCot8C1LobEQmxNWCY2DJLWoI3wwqr8 uUSnI1CDZ5402etkCiNXsDy/eYDrF+2KonkIWRrr -----END CERTIFICATE----- heimdal-7.5.0/lib/hx509/data/ocsp-resp1-ocsp.der0000644000175000017500000000162612136107750017247 0ustar niknik0 0 +0x0t0(0&1 0 USE10U OCSP responder20090426202941Z0Q0O0:0 +ڍ+f|-%-ynHܿL0'Yh20090426202941Z#0!0 +0ƒ0T<~0  *H _]. VB=Yv1es ?hPee20o&>ʠ+1C9$MT?6 tL(C'"xqBjW{RѧyYi\ _\P$p Signature Algorithm: sha1WithRSAEncryption 08:6e:66:b5:58:e0:e3:fb:15:04:11:89:f0:73:a0:d1:17:c4: b8:7e:dd:ce:34:fb:7b:ab:ae:bb:af:6f:4d:47:1f:02:f8:e7: 7c:c9:33:37:7e:7c:2c:2a:4a:26:38:e1:e5:a9:dd:7c:e1:f8: 5a:2c:c7:6f:26:aa:f2:b0:7f:d4:85:0a:33:b7:ec:df:93:fe: e4:04:a0:3e:e2:65:ac:1a:f4:b0:50:d6:cf:9e:bb:ce:90:ca: 34:7a:13:f5:6f:30:bd:ec:af:c5:b9:dd:fa:bc:37:b8:34:6e: bb:12:5e:aa:d2:bf:91:64:d8:fe:c0:fb:9a:b0:10:ba:95:02: be:9b -----BEGIN CERTIFICATE----- MIIB7TCCAVagAwIBAgIBBzANBgkqhkiG9w0BAQUFADAqMRswGQYDVQQDDBJoeDUw OSBUZXN0IFJvb3QgQ0ExCzAJBgNVBAYTAlNFMB4XDTA5MDQyNjIwMjk0MFoXDTE5 MDQyNDIwMjk0MFowITELMAkGA1UEBhMCU0UxEjAQBgNVBAMMCXBraW5pdC1lYzBZ MBMGByqGSM49AgEGCCqGSM49AwEHA0IABN/XMuvWcXgZXU9ZaoUSIC+XYarobnGs t95CgiqLizOG0/xOpUmayhlrG6s9/U3FevSgELKgjAU611XlyfWJZwejczBxMAkG A1UdEwQCMAAwCwYDVR0PBAQDAgXgMB0GA1UdDgQWBBS7jBZxyCH7IQ+BEaG7QxLI 78jaZDA4BgNVHREEMTAvoC0GBisGAQUCAqAjMCGgDRsLVEVTVC5INUwuU0WhEDAO oAMCAQGhBzAFGwNiYXIwDQYJKoZIhvcNAQEFBQADgYEACG5mtVjg4/sVBBGJ8HOg 0RfEuH7dzjT7e6uuu69vTUcfAvjnfMkzN358LCpKJjjh5andfOH4WizHbyaq8rB/ 1IUKM7fs35P+5ASgPuJlrBr0sFDWz567zpDKNHoT9W8wveyvxbnd+rw3uDRuuxJe qtK/kWTY/sD7mrAQupUCvps= -----END CERTIFICATE----- heimdal-7.5.0/lib/hx509/data/proxy-test.crt0000644000175000017500000000146212136107750016463 0ustar niknik-----BEGIN CERTIFICATE----- MIICMDCCAZmgAwIBAgIJAMJEvwnR1+3UMA0GCSqGSIb3DQEBBQUAMCExCzAJBgNV BAYTAlNFMRIwEAYDVQQDDAlUZXN0IGNlcnQwHhcNMDkwNDI2MjAyOTQxWhcNMTkw NDI0MjAyOTQxWjAxMQswCQYDVQQGEwJTRTESMBAGA1UEAwwJVGVzdCBjZXJ0MQ4w DAYDVQQDDAVwcm94eTCBnzANBgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEAxxP4tpnb qS5NjzDgrujdZovK/FHnlgO2Kjha1LQpTLDPwQh4zoymu9Hi/HzYTzdBCwA+auMY vog4EE5hIgpbXFlnSP8gFmQvE2evPBf7Y1O2oK0xEih4/7D2oFikQ+QWHfy92EUm mDe7fjkx5ipF+qwOSLU+YuG07+ltXW7XH8UCAwEAAaNgMF4wCQYDVR0TBAIwADAL BgNVHQ8EBAMCBeAwHQYDVR0OBBYEFM1/xN3+Jz4m3NYEctNo8Y9CnopqMCUGCCsG AQUFBwEOAQH/BBYwFAIBADAPBggrBgEFBQcVAAQDZm9vMA0GCSqGSIb3DQEBBQUA A4GBAB06t/tkcci9IFnSnmogi3LEare/aVkAxbfWHoFBRCZOyat/K7moDsPng6a1 v1DZY0LqgVDL4DCyTKXxAbN9352cca5spmnNKWegCSA9UJXGCTNtIJCPA/x4PO8C nhAAaxERYu123XhRZ8HhRM6t7uGiyLkAX3JFcWvPhAbWjNbo -----END CERTIFICATE----- heimdal-7.5.0/lib/hx509/data/test-signed-data-noattr-nocerts0000644000175000017500000000610612136107750021653 0ustar niknik0 B *H  30 /1 0 +0 D *H  5 1This is a static file don't change the content, it is used in the test #!/bin/sh # # Copyright (c) 2005 Kungliga Tekniska Hgskolan # (Royal Institute of Technology, Stockholm, Sweden). # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # 1. Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # # 3. Neither the name of the Institute nor the names of its contributors # may be used to endorse or promote products derived from this software # without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE # ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS # OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) # HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY # OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF # SUCH DAMAGE. # # srcdir="@srcdir@" echo "try printing" ./hxtool print \ --pass=PASS:foobar \ PKCS12:$srcdir/data/test.p12 || exit 1 echo "make sure entry is found (friendlyname)" ./hxtool query \ --pass=PASS:foobar \ --friendlyname=friendlyname-test \ PKCS12:$srcdir/data/test.p12 || exit 1 echo "make sure entry is not found (friendlyname)" ./hxtool query \ --pass=PASS:foobar \ --friendlyname=friendlyname-test-not \ PKCS12:$srcdir/data/test.p12 && exit 1 echo "check for ca cert (friendlyname)" ./hxtool query \ --pass=PASS:foobar \ --friendlyname=ca \ PKCS12:$srcdir/data/test.p12 || exit 1 echo "make sure entry is not found (friendlyname)" ./hxtool query \ --pass=PASS:foobar \ --friendlyname=friendlyname-test \ PKCS12:$srcdir/data/sub-cert.p12 && exit 1 echo "make sure entry is found (friendlyname|private key)" ./hxtool query \ --pass=PASS:foobar \ --friendlyname=friendlyname-test \ --private-key \ PKCS12:$srcdir/data/test.p12 || exit 1 echo "make sure entry is not found (friendlyname|private key)" ./hxtool query \ --pass=PASS:foobar \ --friendlyname=ca \ --private-key \ PKCS12:$srcdir/data/test.p12 && exit 1 exit 0 100/0*10U hx509 Test Root CA1 0 USE0 +0  *H |0p?9MdSUXB23qSv Signature Algorithm: sha1WithRSAEncryption b5:ab:c2:d5:f8:30:fc:bb:b3:53:c2:42:a0:f1:4d:a0:5c:92: 1a:c7:dc:01:df:42:6a:d2:c8:79:18:ae:a7:09:8e:ea:1c:97: 80:93:b1:e3:23:4d:ca:15:f5:f8:c2:d0:38:5d:0d:76:7b:41: 47:f1:a4:77:26:86:2c:69:2a:5c:86:32:00:09:da:04:3c:d6: 30:9d:a3:0a:e2:b1:a6:36:2f:ff:3c:80:d6:e7:2a:8b:49:dd: d8:24:98:7a:15:0a:29:f0:4b:30:ae:73:b5:af:70:7a:3a:b0: 40:27:a7:4e:74:8c:46:1e:2f:bb:cc:57:63:30:bf:b1:38:81: 10:bd -----BEGIN CERTIFICATE----- MIICMTCCAZqgAwIBAgIBBjANBgkqhkiG9w0BAQUFADAqMRswGQYDVQQDDBJoeDUw OSBUZXN0IFJvb3QgQ0ExCzAJBgNVBAYTAlNFMB4XDTA5MDQyNjIwMjk0MFoXDTE5 MDQyNDIwMjk0MFowHjELMAkGA1UEBhMCU0UxDzANBgNVBAMMBnBraW5pdDCBnzAN BgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEAskdC3Eb4lONmK/kmFFZBaOF6BM1VRa7g qEiAM1j8hk/oZ2KJ99S60buaaoMbTgG1fJ6y0r+EIZhYHbZN+q/y5ejU1nijBtpp FQnY+gcJl88aOyxpsliiC0hONxEs9XqPUORAFCkoMKwLtQoeYLSa1I28OMkvqdE1 58nUGGYcFS0CAwEAAaNzMHEwCQYDVR0TBAIwADALBgNVHQ8EBAMCBeAwHQYDVR0O BBYEFOg/GovCipz5tE+V2VUpDKULDhPGMDgGA1UdEQQxMC+gLQYGKwYBBQICoCMw IaANGwtURVNULkg1TC5TRaEQMA6gAwIBAaEHMAUbA2JhcjANBgkqhkiG9w0BAQUF AAOBgQC1q8LV+DD8u7NTwkKg8U2gXJIax9wB30Jq0sh5GK6nCY7qHJeAk7HjI03K FfX4wtA4XQ12e0FH8aR3JoYsaSpchjIACdoEPNYwnaMK4rGmNi//PIDW5yqLSd3Y JJh6FQop8EswrnO1r3B6OrBAJ6dOdIxGHi+7zFdjML+xOIEQvQ== -----END CERTIFICATE----- heimdal-7.5.0/lib/hx509/data/ocsp-responder.crt0000644000175000017500000000534312136107750017272 0ustar niknikCertificate: Data: Version: 3 (0x2) Serial Number: 1 (0x1) Signature Algorithm: sha1WithRSAEncryption Issuer: CN=hx509 Test Root CA, C=SE Validity Not Before: Apr 26 20:29:40 2009 GMT Not After : Apr 24 20:29:40 2019 GMT Subject: C=SE, CN=OCSP responder Subject Public Key Info: Public Key Algorithm: rsaEncryption Public-Key: (1024 bit) Modulus: 00:f1:38:9c:a0:5e:b9:0e:73:19:b6:f5:57:2b:9c: 0c:ef:a6:c7:57:0f:8d:3c:05:03:8f:53:28:f0:b6: f8:d1:0d:c9:dc:13:37:2d:f1:76:36:b7:5c:6b:5d: a5:22:02:7c:86:84:9e:b5:e3:8b:e6:9e:82:d9:97: 96:02:9f:3c:7b:74:e6:1b:b6:c9:fa:b3:b7:8b:53: 6e:26:fb:b2:3f:ae:2a:7f:f9:67:df:1a:e1:de:87: 97:47:76:80:a3:c4:bf:5c:2c:0d:ab:36:97:13:2d: b8:c2:65:41:47:e8:34:54:f8:45:fc:38:76:b8:99: 3f:ee:83:f6:49:40:96:16:71 Exponent: 65537 (0x10001) X509v3 extensions: X509v3 Basic Constraints: CA:FALSE X509v3 Key Usage: Digital Signature, Non Repudiation, Key Encipherment X509v3 Extended Key Usage: OCSP No Check, OCSP Signing X509v3 Subject Key Identifier: FD:2F:3F:35:BC:72:5C:51:52:4F:5F:D6:20:CB:D1:CB:56:2F:BC:0A Signature Algorithm: sha1WithRSAEncryption 24:95:11:a0:f2:10:58:4d:4e:20:e5:d3:4d:17:b5:4b:37:aa: fe:c8:28:79:e4:ca:15:b1:9e:28:93:fc:45:99:d5:4a:8a:a0: 0a:e4:9e:75:64:f9:a4:63:96:dd:2a:9e:c7:0f:03:83:86:44: c5:1c:a4:34:b6:b7:74:e3:ff:e3:97:0f:11:b5:00:bd:10:fd: 91:db:ec:2d:14:9b:16:c7:e5:48:b0:08:62:d1:58:be:92:69: a6:5a:3d:7e:58:39:f0:bb:bc:71:08:b9:76:6c:9b:e6:57:1c: 25:1b:d6:7a:98:70:9f:95:50:09:17:d9:1a:d9:20:db:d6:8a: be:9e -----BEGIN CERTIFICATE----- MIICHzCCAYigAwIBAgIBATANBgkqhkiG9w0BAQUFADAqMRswGQYDVQQDDBJoeDUw OSBUZXN0IFJvb3QgQ0ExCzAJBgNVBAYTAlNFMB4XDTA5MDQyNjIwMjk0MFoXDTE5 MDQyNDIwMjk0MFowJjELMAkGA1UEBhMCU0UxFzAVBgNVBAMMDk9DU1AgcmVzcG9u ZGVyMIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDxOJygXrkOcxm29VcrnAzv psdXD408BQOPUyjwtvjRDcncEzct8XY2t1xrXaUiAnyGhJ6144vmnoLZl5YCnzx7 dOYbtsn6s7eLU24m+7I/rip/+WffGuHeh5dHdoCjxL9cLA2rNpcTLbjCZUFH6DRU +EX8OHa4mT/ug/ZJQJYWcQIDAQABo1kwVzAJBgNVHRMEAjAAMAsGA1UdDwQEAwIF 4DAeBgNVHSUEFzAVBgkrBgEFBQcwAQUGCCsGAQUFBwMJMB0GA1UdDgQWBBT9Lz81 vHJcUVJPX9Ygy9HLVi+8CjANBgkqhkiG9w0BAQUFAAOBgQAklRGg8hBYTU4g5dNN F7VLN6r+yCh55MoVsZ4ok/xFmdVKiqAK5J51ZPmkY5bdKp7HDwODhkTFHKQ0trd0 4//jlw8RtQC9EP2R2+wtFJsWx+VIsAhi0Vi+kmmmWj1+WDnwu7xxCLl2bJvmVxwl G9Z6mHCflVAJF9ka2SDb1oq+ng== -----END CERTIFICATE----- heimdal-7.5.0/lib/hx509/data/secp256r2TestClient.pem0000644000175000017500000000156513026237312017751 0ustar niknik-----BEGIN CERTIFICATE----- MIIBrzCCAVWgAwIBAgIBAjAKBggqhkjOPQQDAjA2MQswCQYDVQQGEwJTRTEQMA4G A1UEChMHSGVpbWRhbDEVMBMGA1UEAxMMQ0Egc2VjcDI1NnIxMB4XDTE0MDMxMDE5 NDAyM1oXDTM4MDExNzE5NDAyM1owMDELMAkGA1UEBhMCU0UxEDAOBgNVBAoTB0hl aW1kYWwxDzANBgNVBAMTBkNsaWVudDBZMBMGByqGSM49AgEGCCqGSM49AwEHA0IA BO7/MCIBHf8gQLQ5ltp1uyCOCAw8uylZZ7+v/rB3oKHuAIyL6q/QjZXZH3FR5VcI zANavN5SAfx9CFJpPk+pUISjWjBYMB0GA1UdDgQWBBSjXg4X3fs5xOQgTumjZQwF I13RejAfBgNVHSMEGDAWgBTrUd8AqGhfZvHVspcznXeb328JgzAJBgNVHRMEAjAA MAsGA1UdDwQEAwIEsDAKBggqhkjOPQQDAgNIADBFAiAa9d6aCxlioep3ViYqujWv A28/16yXOrmLY1a2wcj3awIhAMeVjMiUTP/U4yXfb3uJjJmq8hfyNZ/CAiTQKORx JjIt -----END CERTIFICATE----- -----BEGIN PRIVATE KEY----- MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQg6oD5CbNzN7oAWqcq dKJKw2WU5EwnUV05+7S9gXgeW/qhRANCAATu/zAiAR3/IEC0OZbadbsgjggMPLsp WWe/r/6wd6Ch7gCMi+qv0I2V2R9xUeVXCMwDWrzeUgH8fQhSaT5PqVCE -----END PRIVATE KEY----- heimdal-7.5.0/lib/hx509/data/sub-cert.crt0000644000175000017500000000510612136107750016050 0ustar niknikCertificate: Data: Version: 3 (0x2) Serial Number: 11 (0xb) Signature Algorithm: sha1WithRSAEncryption Issuer: C=SE, CN=Sub CA Validity Not Before: Apr 26 20:29:41 2009 GMT Not After : Apr 24 20:29:41 2019 GMT Subject: C=SE, CN=Test sub cert Subject Public Key Info: Public Key Algorithm: rsaEncryption Public-Key: (1024 bit) Modulus: 00:c2:e7:0c:98:23:cd:54:66:28:8c:e4:75:fc:4e: cd:1c:1d:eb:1f:0c:c4:56:78:07:7d:73:3d:9e:0d: 02:29:a3:c9:f6:46:fa:24:ce:1f:49:f8:1f:0d:ea: d7:aa:91:ed:0a:8d:69:05:a9:36:94:70:52:e8:05: 42:04:19:6d:55:44:85:c2:d4:3a:2c:a7:ad:aa:42: 54:cb:78:a1:fa:bb:b9:40:41:80:28:c4:27:42:a6: 6b:f2:33:84:a2:c0:3e:f6:fe:b1:70:54:8a:0c:44: 8f:81:1b:27:d8:7c:59:3f:f0:de:ea:dc:08:3f:88: f8:f2:bf:58:3f:a4:fa:f5:9b Exponent: 65537 (0x10001) X509v3 extensions: X509v3 Basic Constraints: CA:FALSE X509v3 Key Usage: Digital Signature, Non Repudiation, Key Encipherment X509v3 Subject Key Identifier: C1:80:37:61:B7:F7:BD:09:84:1C:5C:CF:65:6D:FE:15:0B:78:85:C0 Signature Algorithm: sha1WithRSAEncryption 97:06:c7:34:4f:17:20:6f:fd:f1:0e:eb:33:f1:eb:fe:49:ee: 5d:6c:59:f2:4d:97:c0:ad:5a:2c:85:c2:b5:21:04:b0:ee:d1: 2c:2b:54:0e:9c:82:c9:45:81:9c:2a:3a:e2:fa:78:94:52:56: 19:99:11:44:78:f4:7d:b0:fc:d2:d3:49:d8:2f:9d:ff:23:5c: 83:96:a0:14:a8:49:a1:bd:4a:ef:d2:67:96:5e:b7:36:36:86: cc:ea:17:c3:3e:b7:18:ae:0a:03:43:4a:af:ab:ef:b9:c8:ec: d6:27:39:c7:33:b7:34:54:d6:b5:1b:8c:85:a1:c1:13:b5:cd: 0f:b7 -----BEGIN CERTIFICATE----- MIIB8jCCAVugAwIBAgIBCzANBgkqhkiG9w0BAQUFADAeMQswCQYDVQQGEwJTRTEP MA0GA1UEAwwGU3ViIENBMB4XDTA5MDQyNjIwMjk0MVoXDTE5MDQyNDIwMjk0MVow JTELMAkGA1UEBhMCU0UxFjAUBgNVBAMMDVRlc3Qgc3ViIGNlcnQwgZ8wDQYJKoZI hvcNAQEBBQADgY0AMIGJAoGBAMLnDJgjzVRmKIzkdfxOzRwd6x8MxFZ4B31zPZ4N AimjyfZG+iTOH0n4Hw3q16qR7QqNaQWpNpRwUugFQgQZbVVEhcLUOiynrapCVMt4 ofq7uUBBgCjEJ0Kma/IzhKLAPvb+sXBUigxEj4EbJ9h8WT/w3urcCD+I+PK/WD+k +vWbAgMBAAGjOTA3MAkGA1UdEwQCMAAwCwYDVR0PBAQDAgXgMB0GA1UdDgQWBBTB gDdht/e9CYQcXM9lbf4VC3iFwDANBgkqhkiG9w0BAQUFAAOBgQCXBsc0Txcgb/3x Dusz8ev+Se5dbFnyTZfArVoshcK1IQSw7tEsK1QOnILJRYGcKjri+niUUlYZmRFE ePR9sPzS00nYL53/I1yDlqAUqEmhvUrv0meWXrc2NobM6hfDPrcYrgoDQ0qvq++5 yOzWJznHM7c0VNa1G4yFocETtc0Ptw== -----END CERTIFICATE----- heimdal-7.5.0/lib/hx509/sel-lex.l0000644000175000017500000000662613131326447014441 0ustar niknik%{ /* * Copyright (c) 2004 - 2017 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ /* $Id$ */ #ifdef __GNUC__ #pragma GCC diagnostic ignored "-Wunused-function" #endif #ifdef HAVE_CONFIG_H #include #endif #undef ECHO #include #include #include #include #include "sel.h" #include "sel-gram.h" unsigned lineno = 1; static char * handle_string(void); static int lex_input(char *, int); struct hx_expr_input _hx509_expr_input; #ifndef YY_NULL #define YY_NULL 0 #endif #define YY_NO_UNPUT 1 #undef YY_INPUT #define YY_INPUT(buf,res,maxsize) (res = lex_input(buf, maxsize)) #undef ECHO %} %% TRUE { return kw_TRUE; } FALSE { return kw_FALSE; } AND { return kw_AND; } OR { return kw_OR; } IN { return kw_IN; } TAILMATCH { return kw_TAILMATCH; } [A-Za-z][-A-Za-z0-9_]* { yylval.string = strdup ((const char *)yytext); return IDENTIFIER; } "\"" { yylval.string = handle_string(); return STRING; } \n { ++lineno; } [,.!={}()%] { return *yytext; } [ \t] ; %% static char * handle_string(void) { char x[1024]; int i = 0; int c; int quote = 0; while((c = input()) != EOF){ if(quote) { x[i++] = '\\'; x[i++] = c; quote = 0; continue; } if(c == '\n'){ _hx509_sel_yyerror("unterminated string"); lineno++; break; } if(c == '\\'){ quote++; continue; } if(c == '\"') break; x[i++] = c; } x[i] = '\0'; return strdup(x); } #if !defined(yywrap) #define yywrap _hx509_sel_yywrap #endif int yywrap () { return 1; } static int lex_input(char *buf, int max_size) { int n; n = _hx509_expr_input.length - _hx509_expr_input.offset; if (max_size < n) n = max_size; if (n <= 0) return YY_NULL; memcpy(buf, _hx509_expr_input.buf + _hx509_expr_input.offset, n); _hx509_expr_input.offset += n; return n; } heimdal-7.5.0/lib/hx509/hxtool-commands.in0000644000175000017500000003714513026237312016352 0ustar niknik/* * Copyright (c) 2005 - 2007 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ /* $Id$ */ command = { name = "cms-create-sd" name = "cms-sign" option = { long = "certificate" short = "c" type = "strings" argument = "certificate-store" help = "certificate stores to pull certificates from" } option = { long = "signer" short = "s" type = "string" argument = "signer-friendly-name" help = "certificate to sign with" } option = { long = "anchors" type = "strings" argument = "certificate-store" help = "trust anchors" } option = { long = "pool" type = "strings" argument = "certificate-pool" help = "certificate store to pull certificates from" } option = { long = "pass" type = "strings" argument = "password" help = "password, prompter, or environment" } option = { long = "peer-alg" type = "strings" argument = "oid" help = "oid that the peer support" } option = { long = "content-type" type = "string" argument = "oid" help = "content type oid" } option = { long = "content-info" type = "flag" help = "wrapped out-data in a ContentInfo" } option = { long = "pem" type = "flag" help = "wrap out-data in PEM armor" } option = { long = "detached-signature" type = "flag" help = "create a detached signature" } option = { long = "signer" type = "-flag" help = "do not sign" } option = { long = "id-by-name" type = "flag" help = "use subject name for CMS Identifier" } option = { long = "embedded-certs" type = "-flag" help = "don't embed certificates" } option = { long = "embed-leaf-only" type = "flag" help = "only embed leaf certificate" } min_args="1" max_args="2" argument="in-file out-file" help = "Wrap a file within a SignedData object" } command = { name = "cms-verify-sd" option = { long = "anchors" short = "D" type = "strings" argument = "certificate-store" help = "trust anchors" } option = { long = "certificate" short = "c" type = "strings" argument = "certificate-store" help = "certificate store to pull certificates from" } option = { long = "pass" type = "strings" argument = "password" help = "password, prompter, or environment" } option = { long = "missing-revoke" type = "flag" help = "missing CRL/OCSP is ok" } option = { long = "content-info" type = "flag" help = "unwrap in-data that's in a ContentInfo" } option = { long = "pem" type = "flag" help = "unwrap in-data from PEM armor" } option = { long = "signer-allowed" type = "-flag" help = "allow no signer" } option = { long = "allow-wrong-oid" type = "flag" help = "allow wrong oid flag" } option = { long = "signed-content" type = "string" help = "file containing content" } min_args="1" max_args="2" argument="in-file [out-file]" help = "Verify a file within a SignedData object" } command = { name = "cms-unenvelope" option = { long = "certificate" short = "c" type = "strings" argument = "certificate-store" help = "certificate used to decrypt the data" } option = { long = "pass" type = "strings" argument = "password" help = "password, prompter, or environment" } option = { long = "content-info" type = "flag" help = "wrapped out-data in a ContentInfo" } option = { long = "allow-weak-crypto" type = "flag" help = "allow weak crypto" } min_args="2" argument="in-file out-file" help = "Unenvelope a file containing a EnvelopedData object" } command = { name = "cms-envelope" function = "cms_create_enveloped" option = { long = "certificate" short = "c" type = "strings" argument = "certificate-store" help = "certificates used to receive the data" } option = { long = "pass" type = "strings" argument = "password" help = "password, prompter, or environment" } option = { long = "encryption-type" type = "string" argument = "enctype" help = "enctype" } option = { long = "content-type" type = "string" argument = "oid" help = "content type oid" } option = { long = "content-info" type = "flag" help = "wrapped out-data in a ContentInfo" } option = { long = "allow-weak-crypto" type = "flag" help = "allow weak crypto" } min_args="2" argument="in-file out-file" help = "Envelope a file containing a EnvelopedData object" } command = { name = "verify" function = "pcert_verify" option = { long = "pass" type = "strings" argument = "password" help = "password, prompter, or environment" } option = { long = "allow-proxy-certificate" type = "flag" help = "allow proxy certificates" } option = { long = "missing-revoke" type = "flag" help = "missing CRL/OCSP is ok" } option = { long = "time" type = "string" help = "time when to validate the chain" } option = { long = "verbose" short = "v" type = "flag" help = "verbose logging" } option = { long = "max-depth" type = "integer" help = "maximum search length of certificate trust anchor" } option = { long = "hostname" type = "string" help = "match hostname to certificate" } argument = "cert:foo chain:cert1 chain:cert2 anchor:anchor1 anchor:anchor2" help = "Verify certificate chain" } command = { name = "print" function = "pcert_print" option = { long = "pass" type = "strings" argument = "password" help = "password, prompter, or environment" } option = { long = "content" type = "flag" help = "print the content of the certificates" } option = { long = "never-fail" type = "flag" help = "never fail with an error code" } option = { long = "info" type = "flag" help = "print the information about the certificate store" } min_args="1" argument="certificate ..." help = "Print certificates" } command = { name = "validate" function = "pcert_validate" option = { long = "pass" type = "strings" argument = "password" help = "password, prompter, or environment" } min_args="1" argument="certificate ..." help = "Validate content of certificates" } command = { name = "certificate-copy" name = "cc" option = { long = "in-pass" type = "strings" argument = "password" help = "password, prompter, or environment" } option = { long = "out-pass" type = "string" argument = "password" help = "password, prompter, or environment" } min_args="2" argument="in-certificates-1 ... out-certificate" help = "Copy in certificates stores into out certificate store" } command = { name = "ocsp-fetch" option = { long = "pass" type = "strings" argument = "password" help = "password, prompter, or environment" } option = { long = "sign" type = "string" argument = "certificate" help = "certificate use to sign the request" } option = { long = "url-path" type = "string" argument = "url" help = "part after host in url to put in the request" } option = { long = "nonce" type = "-flag" default = "1" help = "don't include nonce in request" } option = { long = "pool" type = "strings" argument = "certificate-store" help = "pool to find parent certificate in" } min_args="2" argument="outfile certs ..." help = "Fetch OCSP responses for the following certs" } command = { option = { long = "ocsp-file" type = "string" help = "OCSP file" } name = "ocsp-verify" min_args="1" argument="certificates ..." help = "Check that certificates are in OCSP file and valid" } command = { name = "ocsp-print" option = { long = "verbose" type = "flag" help = "verbose" } min_args="1" argument="ocsp-response-file ..." help = "Print the OCSP responses" } command = { name = "revoke-print" option = { long = "verbose" type = "flag" help = "verbose" } min_args="1" argument="ocsp/crl files" help = "Print the OCSP/CRL files" } command = { name = "request-create" option = { long = "subject" type = "string" help = "Subject DN" } option = { long = "email" type = "strings" help = "Email address in SubjectAltName" } option = { long = "dnsname" type = "strings" help = "Hostname or domainname in SubjectAltName" } option = { long = "type" type = "string" help = "Type of request CRMF or PKCS10, defaults to PKCS10" } option = { long = "key" type = "string" help = "Key-pair" } option = { long = "generate-key" type = "string" help = "keytype" } option = { long = "key-bits" type = "integer" help = "number of bits in the generated key"; } option = { long = "verbose" type = "flag" help = "verbose status" } min_args="1" max_args="1" argument="output-file" help = "Create a CRMF or PKCS10 request" } command = { name = "request-print" option = { long = "verbose" type = "flag" help = "verbose printing" } min_args="1" argument="requests ..." help = "Print requests" } command = { name = "query" option = { long = "exact" type = "flag" help = "exact match" } option = { long = "private-key" type = "flag" help = "search for private key" } option = { long = "friendlyname" type = "string" argument = "name" help = "match on friendly name" } option = { long = "eku" type = "string" argument = "oid-string" help = "match on EKU" } option = { long = "expr" type = "string" argument = "expression" help = "match on expression" } option = { long = "keyEncipherment" type = "flag" help = "match keyEncipherment certificates" } option = { long = "digitalSignature" type = "flag" help = "match digitalSignature certificates" } option = { long = "print" type = "flag" help = "print matches" } option = { long = "pass" type = "strings" argument = "password" help = "password, prompter, or environment" } min_args="1" argument="certificates ..." help = "Query the certificates for a match" } command = { name = "info" } command = { name = "random-data" min_args="1" argument="bytes" help = "Generates random bytes and prints them to standard output" } command = { option = { long = "type" type = "string" help = "type of CMS algorithm" } name = "crypto-available" min_args="0" help = "Print available CMS crypto types" } command = { option = { long = "type" type = "string" help = "type of CMS algorithm" } option = { long = "certificate" type = "string" help = "source certificate limiting the choices" } option = { long = "peer-cmstype" type = "strings" help = "peer limiting cmstypes" } name = "crypto-select" min_args="0" help = "Print selected CMS type" } command = { option = { long = "decode" short = "d" type = "flag" help = "decode instead of encode" } name = "hex" function = "hxtool_hex" min_args="0" help = "Encode input to hex" } command = { option = { long = "issue-ca" type = "flag" help = "Issue a CA certificate" } option = { long = "issue-proxy" type = "flag" help = "Issue a proxy certificate" } option = { long = "domain-controller" type = "flag" help = "Issue a MS domaincontroller certificate" } option = { long = "subject" type = "string" help = "Subject of issued certificate" } option = { long = "ca-certificate" type = "string" help = "Issuing CA certificate" } option = { long = "self-signed" type = "flag" help = "Issuing a self-signed certificate" } option = { long = "ca-private-key" type = "string" help = "Private key for self-signed certificate" } option = { long = "certificate" type = "string" help = "Issued certificate" } option = { long = "type" type = "strings" help = "Types of certificate to issue (can be used more then once)" } option = { long = "lifetime" type = "string" help = "Lifetime of certificate" } option = { long = "signature-algorithm" type = "string" help = "Signature algorithm to use" } option = { long = "serial-number" type = "string" help = "serial-number of certificate" } option = { long = "path-length" default = "-1" type = "integer" help = "Maximum path length (CA and proxy certificates), -1 no limit" } option = { long = "hostname" type = "strings" help = "DNS names this certificate is allowed to serve" } option = { long = "email" type = "strings" help = "email addresses assigned to this certificate" } option = { long = "pk-init-principal" type = "strings" help = "PK-INIT principal (for SAN)" } option = { long = "ms-upn" type = "string" help = "Microsoft UPN (for SAN)" } option = { long = "jid" type = "string" help = "XMPP jabber id (for SAN)" } option = { long = "req" type = "string" help = "certificate request" } option = { long = "certificate-private-key" type = "string" help = "private-key" } option = { long = "generate-key" type = "string" help = "keytype" } option = { long = "key-bits" type = "integer" help = "number of bits in the generated key" } option = { long = "crl-uri" type = "string" help = "URI to CRL" } option = { long = "template-certificate" type = "string" help = "certificate" } option = { long = "template-fields" type = "string" help = "flag" } name = "certificate-sign" name = "cert-sign" name = "issue-certificate" name = "ca" function = "hxtool_ca" min_args="0" help = "Issue a certificate" } command = { name = "test-crypto" option = { long = "pass" type = "strings" argument = "password" help = "password, prompter, or environment" } option = { long = "verbose" type = "flag" help = "verbose printing" } min_args="1" argument="certificates..." help = "Test crypto system related to the certificates" } command = { option = { long = "type" type = "integer" help = "type of statistics" } name = "statistic-print" min_args="0" help = "Print statistics" } command = { option = { long = "signer" type = "string" help = "signer certificate" } option = { long = "pass" type = "strings" argument = "password" help = "password, prompter, or environment" } option = { long = "crl-file" type = "string" help = "CRL output file" } option = { long = "lifetime" type = "string" help = "time the crl will be valid" } name = "crl-sign" min_args="0" argument="certificates..." help = "Create a CRL" } command = { name = "help" name = "?" argument = "[command]" min_args = "0" max_args = "1" help = "Help! I need somebody" } heimdal-7.5.0/lib/hx509/test_req.in0000644000175000017500000000441112136107750015055 0ustar niknik#!/bin/sh # # Copyright (c) 2005 - 2007 Kungliga Tekniska Högskolan # (Royal Institute of Technology, Stockholm, Sweden). # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # 1. Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # # 3. Neither the name of the Institute nor the names of its contributors # may be used to endorse or promote products derived from this software # without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE # ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS # OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) # HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY # OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF # SUCH DAMAGE. # # $Id$ # srcdir="@srcdir@" objdir="@objdir@" stat="--statistic-file=${objdir}/statfile" hxtool="${TESTS_ENVIRONMENT} ./hxtool ${stat}" if ${hxtool} info | grep 'rsa: hcrypto null RSA' > /dev/null ; then exit 77 fi if ${hxtool} info | grep 'rand: not available' > /dev/null ; then exit 77 fi ${hxtool} request-create \ --subject="CN=Love,DC=it,DC=su,DC=se" \ --key=FILE:$srcdir/data/key.der \ request.out || exit 1 ${hxtool} request-print \ PKCS10:request.out > /dev/null || exit 1 ${hxtool} request-create \ --subject="CN=Love,DC=it,DC=su,DC=se" \ --dnsname=nutcracker.it.su.se \ --key=FILE:$srcdir/data/key.der \ request.out || exit 1 heimdal-7.5.0/lib/hx509/lock.c0000644000175000017500000001312413026237312013771 0ustar niknik/* * Copyright (c) 2005 - 2006 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "hx_locl.h" /** * @page page_lock Locking and unlocking certificates and encrypted data. * * See the library functions here: @ref hx509_lock */ struct hx509_lock_data { struct _hx509_password password; hx509_certs certs; hx509_prompter_fct prompt; void *prompt_data; }; static struct hx509_lock_data empty_lock_data = { { 0, NULL }, NULL, NULL, NULL }; hx509_lock _hx509_empty_lock = &empty_lock_data; /* * */ int hx509_lock_init(hx509_context context, hx509_lock *lock) { hx509_lock l; int ret; *lock = NULL; l = calloc(1, sizeof(*l)); if (l == NULL) return ENOMEM; ret = hx509_certs_init(context, "MEMORY:locks-internal", 0, NULL, &l->certs); if (ret) { free(l); return ret; } *lock = l; return 0; } int hx509_lock_add_password(hx509_lock lock, const char *password) { void *d; char *s; s = strdup(password); if (s == NULL) return ENOMEM; d = realloc(lock->password.val, (lock->password.len + 1) * sizeof(lock->password.val[0])); if (d == NULL) { free(s); return ENOMEM; } lock->password.val = d; lock->password.val[lock->password.len] = s; lock->password.len++; return 0; } const struct _hx509_password * _hx509_lock_get_passwords(hx509_lock lock) { return &lock->password; } hx509_certs _hx509_lock_unlock_certs(hx509_lock lock) { return lock->certs; } void hx509_lock_reset_passwords(hx509_lock lock) { size_t i; for (i = 0; i < lock->password.len; i++) free(lock->password.val[i]); free(lock->password.val); lock->password.val = NULL; lock->password.len = 0; } int hx509_lock_add_cert(hx509_context context, hx509_lock lock, hx509_cert cert) { return hx509_certs_add(context, lock->certs, cert); } int hx509_lock_add_certs(hx509_context context, hx509_lock lock, hx509_certs certs) { return hx509_certs_merge(context, lock->certs, certs); } void hx509_lock_reset_certs(hx509_context context, hx509_lock lock) { hx509_certs certs = lock->certs; int ret; ret = hx509_certs_init(context, "MEMORY:locks-internal", 0, NULL, &lock->certs); if (ret == 0) hx509_certs_free(&certs); else lock->certs = certs; } int _hx509_lock_find_cert(hx509_lock lock, const hx509_query *q, hx509_cert *c) { *c = NULL; return 0; } int hx509_lock_set_prompter(hx509_lock lock, hx509_prompter_fct prompt, void *data) { lock->prompt = prompt; lock->prompt_data = data; return 0; } void hx509_lock_reset_promper(hx509_lock lock) { lock->prompt = NULL; lock->prompt_data = NULL; } static int default_prompter(void *data, const hx509_prompt *prompter) { if (hx509_prompt_hidden(prompter->type)) { if(UI_UTIL_read_pw_string(prompter->reply.data, prompter->reply.length, prompter->prompt, 0)) return 1; } else { char *s = prompter->reply.data; fputs (prompter->prompt, stdout); fflush (stdout); if(fgets(prompter->reply.data, prompter->reply.length, stdin) == NULL) return 1; s[strcspn(s, "\n")] = '\0'; } return 0; } int hx509_lock_prompt(hx509_lock lock, hx509_prompt *prompt) { if (lock->prompt == NULL) return HX509_CRYPTO_NO_PROMPTER; return (*lock->prompt)(lock->prompt_data, prompt); } void hx509_lock_free(hx509_lock lock) { if (lock) { hx509_certs_free(&lock->certs); hx509_lock_reset_passwords(lock); memset(lock, 0, sizeof(*lock)); free(lock); } } int hx509_prompt_hidden(hx509_prompt_type type) { /* default to hidden if unknown */ switch (type) { case HX509_PROMPT_TYPE_QUESTION: case HX509_PROMPT_TYPE_INFO: return 0; default: return 1; } } int hx509_lock_command_string(hx509_lock lock, const char *string) { if (strncasecmp(string, "PASS:", 5) == 0) { hx509_lock_add_password(lock, string + 5); } else if (strcasecmp(string, "PROMPT") == 0) { hx509_lock_set_prompter(lock, default_prompter, NULL); } else return HX509_UNKNOWN_LOCK_COMMAND; return 0; } heimdal-7.5.0/lib/hx509/sel.h0000644000175000017500000000500413212137553013632 0ustar niknik/* * Copyright (c) 2008 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ enum hx_expr_op { op_TRUE, op_FALSE, op_NOT, op_AND, op_OR, op_COMP, comp_EQ, comp_NE, comp_IN, comp_TAILEQ, expr_NUMBER, expr_STRING, expr_FUNCTION, expr_VAR, expr_WORDS }; struct hx_expr { enum hx_expr_op op; void *arg1; void *arg2; }; struct hx_expr_input { const char *buf; size_t length; size_t offset; struct hx_expr *expr; char *error; }; extern struct hx_expr_input _hx509_expr_input; #if !defined(yylex) #define yylex _hx509_sel_yylex #define yywrap _hx509_sel_yywrap #endif #if !defined(yyparse) #define yyparse _hx509_sel_yyparse #define yyerror _hx509_sel_yyerror #define yylval _hx509_sel_yylval #define yychar _hx509_sel_yychar #define yydebug _hx509_sel_yydebug #define yynerrs _hx509_sel_yynerrs #endif int _hx509_sel_yyparse(void); int _hx509_sel_yylex(void); void _hx509_sel_yyerror(const char *); heimdal-7.5.0/lib/hx509/sel-lex.c0000644000175000017500000013771213212445575014435 0ustar niknik #line 3 "sel-lex.c" #define YY_INT_ALIGNED short int /* A lexical scanner generated by flex */ #define FLEX_SCANNER #define YY_FLEX_MAJOR_VERSION 2 #define YY_FLEX_MINOR_VERSION 5 #define YY_FLEX_SUBMINOR_VERSION 35 #if YY_FLEX_SUBMINOR_VERSION > 0 #define FLEX_BETA #endif /* First, we deal with platform-specific or compiler-specific issues. */ /* begin standard C headers. */ #include #include #include #include /* end standard C headers. */ /* flex integer type definitions */ #ifndef FLEXINT_H #define FLEXINT_H /* C99 systems have . Non-C99 systems may or may not. */ #if defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L /* C99 says to define __STDC_LIMIT_MACROS before including stdint.h, * if you want the limit (max/min) macros for int types. */ #ifndef __STDC_LIMIT_MACROS #define __STDC_LIMIT_MACROS 1 #endif #include typedef int8_t flex_int8_t; typedef uint8_t flex_uint8_t; typedef int16_t flex_int16_t; typedef uint16_t flex_uint16_t; typedef int32_t flex_int32_t; typedef uint32_t flex_uint32_t; typedef uint64_t flex_uint64_t; #else typedef signed char flex_int8_t; typedef short int flex_int16_t; typedef int flex_int32_t; typedef unsigned char flex_uint8_t; typedef unsigned short int flex_uint16_t; typedef unsigned int flex_uint32_t; #endif /* ! C99 */ /* Limits of integral types. */ #ifndef INT8_MIN #define INT8_MIN (-128) #endif #ifndef INT16_MIN #define INT16_MIN (-32767-1) #endif #ifndef INT32_MIN #define INT32_MIN (-2147483647-1) #endif #ifndef INT8_MAX #define INT8_MAX (127) #endif #ifndef INT16_MAX #define INT16_MAX (32767) #endif #ifndef INT32_MAX #define INT32_MAX (2147483647) #endif #ifndef UINT8_MAX #define UINT8_MAX (255U) #endif #ifndef UINT16_MAX #define UINT16_MAX (65535U) #endif #ifndef UINT32_MAX #define UINT32_MAX (4294967295U) #endif #endif /* ! FLEXINT_H */ #ifdef __cplusplus /* The "const" storage-class-modifier is valid. */ #define YY_USE_CONST #else /* ! __cplusplus */ /* C99 requires __STDC__ to be defined as 1. */ #if defined (__STDC__) #define YY_USE_CONST #endif /* defined (__STDC__) */ #endif /* ! __cplusplus */ #ifdef YY_USE_CONST #define yyconst const #else #define yyconst #endif /* Returned upon end-of-file. */ #define YY_NULL 0 /* Promotes a possibly negative, possibly signed char to an unsigned * integer for use as an array index. If the signed char is negative, * we want to instead treat it as an 8-bit unsigned char, hence the * double cast. */ #define YY_SC_TO_UI(c) ((unsigned int) (unsigned char) c) /* Enter a start condition. This macro really ought to take a parameter, * but we do it the disgusting crufty way forced on us by the ()-less * definition of BEGIN. */ #define BEGIN (yy_start) = 1 + 2 * /* Translate the current start state into a value that can be later handed * to BEGIN to return to the state. The YYSTATE alias is for lex * compatibility. */ #define YY_START (((yy_start) - 1) / 2) #define YYSTATE YY_START /* Action number for EOF rule of a given start state. */ #define YY_STATE_EOF(state) (YY_END_OF_BUFFER + state + 1) /* Special action meaning "start processing a new file". */ #define YY_NEW_FILE yyrestart(yyin ) #define YY_END_OF_BUFFER_CHAR 0 /* Size of default input buffer. */ #ifndef YY_BUF_SIZE #define YY_BUF_SIZE 16384 #endif /* The state buf must be large enough to hold one state per character in the main buffer. */ #define YY_STATE_BUF_SIZE ((YY_BUF_SIZE + 2) * sizeof(yy_state_type)) #ifndef YY_TYPEDEF_YY_BUFFER_STATE #define YY_TYPEDEF_YY_BUFFER_STATE typedef struct yy_buffer_state *YY_BUFFER_STATE; #endif #ifndef YY_TYPEDEF_YY_SIZE_T #define YY_TYPEDEF_YY_SIZE_T typedef size_t yy_size_t; #endif extern yy_size_t yyleng; extern FILE *yyin, *yyout; #define EOB_ACT_CONTINUE_SCAN 0 #define EOB_ACT_END_OF_FILE 1 #define EOB_ACT_LAST_MATCH 2 #define YY_LESS_LINENO(n) /* Return all but the first "n" matched characters back to the input stream. */ #define yyless(n) \ do \ { \ /* Undo effects of setting up yytext. */ \ int yyless_macro_arg = (n); \ YY_LESS_LINENO(yyless_macro_arg);\ *yy_cp = (yy_hold_char); \ YY_RESTORE_YY_MORE_OFFSET \ (yy_c_buf_p) = yy_cp = yy_bp + yyless_macro_arg - YY_MORE_ADJ; \ YY_DO_BEFORE_ACTION; /* set up yytext again */ \ } \ while ( 0 ) #define unput(c) yyunput( c, (yytext_ptr) ) #ifndef YY_STRUCT_YY_BUFFER_STATE #define YY_STRUCT_YY_BUFFER_STATE struct yy_buffer_state { FILE *yy_input_file; char *yy_ch_buf; /* input buffer */ char *yy_buf_pos; /* current position in input buffer */ /* Size of input buffer in bytes, not including room for EOB * characters. */ yy_size_t yy_buf_size; /* Number of characters read into yy_ch_buf, not including EOB * characters. */ yy_size_t yy_n_chars; /* Whether we "own" the buffer - i.e., we know we created it, * and can realloc() it to grow it, and should free() it to * delete it. */ int yy_is_our_buffer; /* Whether this is an "interactive" input source; if so, and * if we're using stdio for input, then we want to use getc() * instead of fread(), to make sure we stop fetching input after * each newline. */ int yy_is_interactive; /* Whether we're considered to be at the beginning of a line. * If so, '^' rules will be active on the next match, otherwise * not. */ int yy_at_bol; int yy_bs_lineno; /**< The line count. */ int yy_bs_column; /**< The column count. */ /* Whether to try to fill the input buffer when we reach the * end of it. */ int yy_fill_buffer; int yy_buffer_status; #define YY_BUFFER_NEW 0 #define YY_BUFFER_NORMAL 1 /* When an EOF's been seen but there's still some text to process * then we mark the buffer as YY_EOF_PENDING, to indicate that we * shouldn't try reading from the input source any more. We might * still have a bunch of tokens to match, though, because of * possible backing-up. * * When we actually see the EOF, we change the status to "new" * (via yyrestart()), so that the user can continue scanning by * just pointing yyin at a new input file. */ #define YY_BUFFER_EOF_PENDING 2 }; #endif /* !YY_STRUCT_YY_BUFFER_STATE */ /* Stack of input buffers. */ static size_t yy_buffer_stack_top = 0; /**< index of top of stack. */ static size_t yy_buffer_stack_max = 0; /**< capacity of stack. */ static YY_BUFFER_STATE * yy_buffer_stack = 0; /**< Stack as an array. */ /* We provide macros for accessing buffer states in case in the * future we want to put the buffer states in a more general * "scanner state". * * Returns the top of the stack, or NULL. */ #define YY_CURRENT_BUFFER ( (yy_buffer_stack) \ ? (yy_buffer_stack)[(yy_buffer_stack_top)] \ : NULL) /* Same as previous macro, but useful when we know that the buffer stack is not * NULL or when we need an lvalue. For internal use only. */ #define YY_CURRENT_BUFFER_LVALUE (yy_buffer_stack)[(yy_buffer_stack_top)] /* yy_hold_char holds the character lost when yytext is formed. */ static char yy_hold_char; static yy_size_t yy_n_chars; /* number of characters read into yy_ch_buf */ yy_size_t yyleng; /* Points to current character in buffer. */ static char *yy_c_buf_p = (char *) 0; static int yy_init = 0; /* whether we need to initialize */ static int yy_start = 0; /* start state number */ /* Flag which is used to allow yywrap()'s to do buffer switches * instead of setting up a fresh yyin. A bit of a hack ... */ static int yy_did_buffer_switch_on_eof; void yyrestart (FILE *input_file ); void yy_switch_to_buffer (YY_BUFFER_STATE new_buffer ); YY_BUFFER_STATE yy_create_buffer (FILE *file,int size ); void yy_delete_buffer (YY_BUFFER_STATE b ); void yy_flush_buffer (YY_BUFFER_STATE b ); void yypush_buffer_state (YY_BUFFER_STATE new_buffer ); void yypop_buffer_state (void ); static void yyensure_buffer_stack (void ); static void yy_load_buffer_state (void ); static void yy_init_buffer (YY_BUFFER_STATE b,FILE *file ); #define YY_FLUSH_BUFFER yy_flush_buffer(YY_CURRENT_BUFFER ) YY_BUFFER_STATE yy_scan_buffer (char *base,yy_size_t size ); YY_BUFFER_STATE yy_scan_string (yyconst char *yy_str ); YY_BUFFER_STATE yy_scan_bytes (yyconst char *bytes,yy_size_t len ); void *yyalloc (yy_size_t ); void *yyrealloc (void *,yy_size_t ); void yyfree (void * ); #define yy_new_buffer yy_create_buffer #define yy_set_interactive(is_interactive) \ { \ if ( ! YY_CURRENT_BUFFER ){ \ yyensure_buffer_stack (); \ YY_CURRENT_BUFFER_LVALUE = \ yy_create_buffer(yyin,YY_BUF_SIZE ); \ } \ YY_CURRENT_BUFFER_LVALUE->yy_is_interactive = is_interactive; \ } #define yy_set_bol(at_bol) \ { \ if ( ! YY_CURRENT_BUFFER ){\ yyensure_buffer_stack (); \ YY_CURRENT_BUFFER_LVALUE = \ yy_create_buffer(yyin,YY_BUF_SIZE ); \ } \ YY_CURRENT_BUFFER_LVALUE->yy_at_bol = at_bol; \ } #define YY_AT_BOL() (YY_CURRENT_BUFFER_LVALUE->yy_at_bol) /* Begin user sect3 */ typedef unsigned char YY_CHAR; FILE *yyin = (FILE *) 0, *yyout = (FILE *) 0; typedef int yy_state_type; extern int yylineno; int yylineno = 1; extern char *yytext; #define yytext_ptr yytext static yy_state_type yy_get_previous_state (void ); static yy_state_type yy_try_NUL_trans (yy_state_type current_state ); static int yy_get_next_buffer (void ); static void yy_fatal_error (yyconst char msg[] ); /* Done after the current pattern has been matched and before the * corresponding action - sets up yytext. */ #define YY_DO_BEFORE_ACTION \ (yytext_ptr) = yy_bp; \ yyleng = (yy_size_t) (yy_cp - yy_bp); \ (yy_hold_char) = *yy_cp; \ *yy_cp = '\0'; \ (yy_c_buf_p) = yy_cp; #define YY_NUM_RULES 12 #define YY_END_OF_BUFFER 13 /* This struct is not used in this scanner, but its presence is necessary. */ struct yy_trans_info { flex_int32_t yy_verify; flex_int32_t yy_nxt; }; static yyconst flex_int16_t yy_accept[36] = { 0, 0, 0, 13, 12, 11, 9, 10, 8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 5, 4, 7, 7, 3, 7, 7, 7, 7, 7, 1, 2, 7, 7, 7, 7, 6, 0 } ; static yyconst flex_int32_t yy_ec[256] = { 0, 1, 1, 1, 1, 1, 1, 1, 1, 2, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 4, 5, 1, 1, 4, 1, 1, 4, 4, 1, 1, 4, 6, 4, 1, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 1, 1, 1, 4, 1, 1, 1, 7, 8, 9, 10, 11, 12, 8, 13, 14, 8, 8, 15, 16, 17, 18, 8, 8, 19, 20, 21, 22, 8, 8, 8, 8, 8, 1, 1, 1, 1, 6, 1, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 4, 1, 4, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 } ; static yyconst flex_int32_t yy_meta[23] = { 0, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2 } ; static yyconst flex_int16_t yy_base[37] = { 0, 0, 0, 43, 44, 44, 44, 44, 44, 25, 0, 34, 23, 20, 16, 0, 28, 22, 0, 0, 22, 12, 0, 13, 17, 20, 19, 13, 0, 0, 21, 6, 17, 12, 0, 44, 22 } ; static yyconst flex_int16_t yy_def[37] = { 0, 35, 1, 35, 35, 35, 35, 35, 35, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 0, 35 } ; static yyconst flex_int16_t yy_nxt[67] = { 0, 4, 5, 6, 7, 8, 4, 9, 10, 10, 10, 10, 11, 10, 12, 10, 10, 10, 13, 10, 10, 14, 10, 20, 15, 34, 33, 32, 31, 30, 29, 28, 27, 26, 25, 21, 24, 23, 22, 19, 18, 17, 16, 35, 3, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35 } ; static yyconst flex_int16_t yy_chk[67] = { 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 14, 36, 33, 32, 31, 30, 27, 26, 25, 24, 23, 21, 14, 20, 17, 16, 13, 12, 11, 9, 3, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35 } ; static yy_state_type yy_last_accepting_state; static char *yy_last_accepting_cpos; extern int yy_flex_debug; int yy_flex_debug = 0; /* The intent behind this definition is that it'll catch * any uses of REJECT which flex missed. */ #define REJECT reject_used_but_not_detected #define yymore() yymore_used_but_not_detected #define YY_MORE_ADJ 0 #define YY_RESTORE_YY_MORE_OFFSET char *yytext; #line 1 "sel-lex.l" #line 2 "sel-lex.l" /* * Copyright (c) 2004 - 2017 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ /* $Id$ */ #ifdef __GNUC__ #pragma GCC diagnostic ignored "-Wunused-function" #endif #ifdef HAVE_CONFIG_H #include #endif #undef ECHO #include #include #include #include #include "sel.h" #include "sel-gram.h" unsigned lineno = 1; static char * handle_string(void); static int lex_input(char *, int); struct hx_expr_input _hx509_expr_input; #ifndef YY_NULL #define YY_NULL 0 #endif #define YY_NO_UNPUT 1 #undef YY_INPUT #define YY_INPUT(buf,res,maxsize) (res = lex_input(buf, maxsize)) #undef ECHO #line 544 "sel-lex.c" #define INITIAL 0 #ifndef YY_NO_UNISTD_H /* Special case for "unistd.h", since it is non-ANSI. We include it way * down here because we want the user's section 1 to have been scanned first. * The user has a chance to override it with an option. */ #include #endif #ifndef YY_EXTRA_TYPE #define YY_EXTRA_TYPE void * #endif static int yy_init_globals (void ); /* Accessor methods to globals. These are made visible to non-reentrant scanners for convenience. */ int yylex_destroy (void ); int yyget_debug (void ); void yyset_debug (int debug_flag ); YY_EXTRA_TYPE yyget_extra (void ); void yyset_extra (YY_EXTRA_TYPE user_defined ); FILE *yyget_in (void ); void yyset_in (FILE * in_str ); FILE *yyget_out (void ); void yyset_out (FILE * out_str ); yy_size_t yyget_leng (void ); char *yyget_text (void ); int yyget_lineno (void ); void yyset_lineno (int line_number ); /* Macros after this point can all be overridden by user definitions in * section 1. */ #ifndef YY_SKIP_YYWRAP #ifdef __cplusplus extern "C" int yywrap (void ); #else extern int yywrap (void ); #endif #endif static void yyunput (int c,char *buf_ptr ); #ifndef yytext_ptr static void yy_flex_strncpy (char *,yyconst char *,int ); #endif #ifdef YY_NEED_STRLEN static int yy_flex_strlen (yyconst char * ); #endif #ifndef YY_NO_INPUT #ifdef __cplusplus static int yyinput (void ); #else static int input (void ); #endif #endif /* Amount of stuff to slurp up with each read. */ #ifndef YY_READ_BUF_SIZE #define YY_READ_BUF_SIZE 8192 #endif /* Copy whatever the last rule matched to the standard output. */ #ifndef ECHO /* This used to be an fputs(), but since the string might contain NUL's, * we now use fwrite(). */ #define ECHO fwrite( yytext, yyleng, 1, yyout ) #endif /* Gets input and stuffs it into "buf". number of characters read, or YY_NULL, * is returned in "result". */ #ifndef YY_INPUT #define YY_INPUT(buf,result,max_size) \ if ( YY_CURRENT_BUFFER_LVALUE->yy_is_interactive ) \ { \ int c = '*'; \ yy_size_t n; \ for ( n = 0; n < max_size && \ (c = getc( yyin )) != EOF && c != '\n'; ++n ) \ buf[n] = (char) c; \ if ( c == '\n' ) \ buf[n++] = (char) c; \ if ( c == EOF && ferror( yyin ) ) \ YY_FATAL_ERROR( "input in flex scanner failed" ); \ result = n; \ } \ else \ { \ errno=0; \ while ( (result = fread(buf, 1, max_size, yyin))==0 && ferror(yyin)) \ { \ if( errno != EINTR) \ { \ YY_FATAL_ERROR( "input in flex scanner failed" ); \ break; \ } \ errno=0; \ clearerr(yyin); \ } \ }\ \ #endif /* No semi-colon after return; correct usage is to write "yyterminate();" - * we don't want an extra ';' after the "return" because that will cause * some compilers to complain about unreachable statements. */ #ifndef yyterminate #define yyterminate() return YY_NULL #endif /* Number of entries by which start-condition stack grows. */ #ifndef YY_START_STACK_INCR #define YY_START_STACK_INCR 25 #endif /* Report a fatal error. */ #ifndef YY_FATAL_ERROR #define YY_FATAL_ERROR(msg) yy_fatal_error( msg ) #endif /* end tables serialization structures and prototypes */ /* Default declaration of generated scanner - a define so the user can * easily add parameters. */ #ifndef YY_DECL #define YY_DECL_IS_OURS 1 extern int yylex (void); #define YY_DECL int yylex (void) #endif /* !YY_DECL */ /* Code executed at the beginning of each rule, after yytext and yyleng * have been set up. */ #ifndef YY_USER_ACTION #define YY_USER_ACTION #endif /* Code executed at the end of each rule. */ #ifndef YY_BREAK #define YY_BREAK break; #endif #define YY_RULE_SETUP \ YY_USER_ACTION /** The main scanner function which does all the work. */ YY_DECL { register yy_state_type yy_current_state; register char *yy_cp, *yy_bp; register int yy_act; #line 73 "sel-lex.l" #line 729 "sel-lex.c" if ( !(yy_init) ) { (yy_init) = 1; #ifdef YY_USER_INIT YY_USER_INIT; #endif if ( ! (yy_start) ) (yy_start) = 1; /* first start state */ if ( ! yyin ) yyin = stdin; if ( ! yyout ) yyout = stdout; if ( ! YY_CURRENT_BUFFER ) { yyensure_buffer_stack (); YY_CURRENT_BUFFER_LVALUE = yy_create_buffer(yyin,YY_BUF_SIZE ); } yy_load_buffer_state( ); } while ( 1 ) /* loops until end-of-file is reached */ { yy_cp = (yy_c_buf_p); /* Support of yytext. */ *yy_cp = (yy_hold_char); /* yy_bp points to the position in yy_ch_buf of the start of * the current run. */ yy_bp = yy_cp; yy_current_state = (yy_start); yy_match: do { register YY_CHAR yy_c = yy_ec[YY_SC_TO_UI(*yy_cp)]; if ( yy_accept[yy_current_state] ) { (yy_last_accepting_state) = yy_current_state; (yy_last_accepting_cpos) = yy_cp; } while ( yy_chk[yy_base[yy_current_state] + yy_c] != yy_current_state ) { yy_current_state = (int) yy_def[yy_current_state]; if ( yy_current_state >= 36 ) yy_c = yy_meta[(unsigned int) yy_c]; } yy_current_state = yy_nxt[yy_base[yy_current_state] + (unsigned int) yy_c]; ++yy_cp; } while ( yy_base[yy_current_state] != 44 ); yy_find_action: yy_act = yy_accept[yy_current_state]; if ( yy_act == 0 ) { /* have to back up */ yy_cp = (yy_last_accepting_cpos); yy_current_state = (yy_last_accepting_state); yy_act = yy_accept[yy_current_state]; } YY_DO_BEFORE_ACTION; do_action: /* This label is used only to access EOF actions. */ switch ( yy_act ) { /* beginning of action switch */ case 0: /* must back up */ /* undo the effects of YY_DO_BEFORE_ACTION */ *yy_cp = (yy_hold_char); yy_cp = (yy_last_accepting_cpos); yy_current_state = (yy_last_accepting_state); goto yy_find_action; case 1: YY_RULE_SETUP #line 75 "sel-lex.l" { return kw_TRUE; } YY_BREAK case 2: YY_RULE_SETUP #line 76 "sel-lex.l" { return kw_FALSE; } YY_BREAK case 3: YY_RULE_SETUP #line 77 "sel-lex.l" { return kw_AND; } YY_BREAK case 4: YY_RULE_SETUP #line 78 "sel-lex.l" { return kw_OR; } YY_BREAK case 5: YY_RULE_SETUP #line 79 "sel-lex.l" { return kw_IN; } YY_BREAK case 6: YY_RULE_SETUP #line 80 "sel-lex.l" { return kw_TAILMATCH; } YY_BREAK case 7: YY_RULE_SETUP #line 82 "sel-lex.l" { yylval.string = strdup ((const char *)yytext); return IDENTIFIER; } YY_BREAK case 8: YY_RULE_SETUP #line 86 "sel-lex.l" { yylval.string = handle_string(); return STRING; } YY_BREAK case 9: /* rule 9 can match eol */ YY_RULE_SETUP #line 87 "sel-lex.l" { ++lineno; } YY_BREAK case 10: YY_RULE_SETUP #line 88 "sel-lex.l" { return *yytext; } YY_BREAK case 11: YY_RULE_SETUP #line 89 "sel-lex.l" ; YY_BREAK case 12: YY_RULE_SETUP #line 90 "sel-lex.l" ECHO; YY_BREAK #line 876 "sel-lex.c" case YY_STATE_EOF(INITIAL): yyterminate(); case YY_END_OF_BUFFER: { /* Amount of text matched not including the EOB char. */ int yy_amount_of_matched_text = (int) (yy_cp - (yytext_ptr)) - 1; /* Undo the effects of YY_DO_BEFORE_ACTION. */ *yy_cp = (yy_hold_char); YY_RESTORE_YY_MORE_OFFSET if ( YY_CURRENT_BUFFER_LVALUE->yy_buffer_status == YY_BUFFER_NEW ) { /* We're scanning a new file or input source. It's * possible that this happened because the user * just pointed yyin at a new source and called * yylex(). If so, then we have to assure * consistency between YY_CURRENT_BUFFER and our * globals. Here is the right place to do so, because * this is the first action (other than possibly a * back-up) that will match for the new input source. */ (yy_n_chars) = YY_CURRENT_BUFFER_LVALUE->yy_n_chars; YY_CURRENT_BUFFER_LVALUE->yy_input_file = yyin; YY_CURRENT_BUFFER_LVALUE->yy_buffer_status = YY_BUFFER_NORMAL; } /* Note that here we test for yy_c_buf_p "<=" to the position * of the first EOB in the buffer, since yy_c_buf_p will * already have been incremented past the NUL character * (since all states make transitions on EOB to the * end-of-buffer state). Contrast this with the test * in input(). */ if ( (yy_c_buf_p) <= &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[(yy_n_chars)] ) { /* This was really a NUL. */ yy_state_type yy_next_state; (yy_c_buf_p) = (yytext_ptr) + yy_amount_of_matched_text; yy_current_state = yy_get_previous_state( ); /* Okay, we're now positioned to make the NUL * transition. We couldn't have * yy_get_previous_state() go ahead and do it * for us because it doesn't know how to deal * with the possibility of jamming (and we don't * want to build jamming into it because then it * will run more slowly). */ yy_next_state = yy_try_NUL_trans( yy_current_state ); yy_bp = (yytext_ptr) + YY_MORE_ADJ; if ( yy_next_state ) { /* Consume the NUL. */ yy_cp = ++(yy_c_buf_p); yy_current_state = yy_next_state; goto yy_match; } else { yy_cp = (yy_c_buf_p); goto yy_find_action; } } else switch ( yy_get_next_buffer( ) ) { case EOB_ACT_END_OF_FILE: { (yy_did_buffer_switch_on_eof) = 0; if ( yywrap( ) ) { /* Note: because we've taken care in * yy_get_next_buffer() to have set up * yytext, we can now set up * yy_c_buf_p so that if some total * hoser (like flex itself) wants to * call the scanner after we return the * YY_NULL, it'll still work - another * YY_NULL will get returned. */ (yy_c_buf_p) = (yytext_ptr) + YY_MORE_ADJ; yy_act = YY_STATE_EOF(YY_START); goto do_action; } else { if ( ! (yy_did_buffer_switch_on_eof) ) YY_NEW_FILE; } break; } case EOB_ACT_CONTINUE_SCAN: (yy_c_buf_p) = (yytext_ptr) + yy_amount_of_matched_text; yy_current_state = yy_get_previous_state( ); yy_cp = (yy_c_buf_p); yy_bp = (yytext_ptr) + YY_MORE_ADJ; goto yy_match; case EOB_ACT_LAST_MATCH: (yy_c_buf_p) = &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[(yy_n_chars)]; yy_current_state = yy_get_previous_state( ); yy_cp = (yy_c_buf_p); yy_bp = (yytext_ptr) + YY_MORE_ADJ; goto yy_find_action; } break; } default: YY_FATAL_ERROR( "fatal flex scanner internal error--no action found" ); } /* end of action switch */ } /* end of scanning one token */ } /* end of yylex */ /* yy_get_next_buffer - try to read in a new buffer * * Returns a code representing an action: * EOB_ACT_LAST_MATCH - * EOB_ACT_CONTINUE_SCAN - continue scanning from current position * EOB_ACT_END_OF_FILE - end of file */ static int yy_get_next_buffer (void) { register char *dest = YY_CURRENT_BUFFER_LVALUE->yy_ch_buf; register char *source = (yytext_ptr); register int number_to_move, i; int ret_val; if ( (yy_c_buf_p) > &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[(yy_n_chars) + 1] ) YY_FATAL_ERROR( "fatal flex scanner internal error--end of buffer missed" ); if ( YY_CURRENT_BUFFER_LVALUE->yy_fill_buffer == 0 ) { /* Don't try to fill the buffer, so this is an EOF. */ if ( (yy_c_buf_p) - (yytext_ptr) - YY_MORE_ADJ == 1 ) { /* We matched a single character, the EOB, so * treat this as a final EOF. */ return EOB_ACT_END_OF_FILE; } else { /* We matched some text prior to the EOB, first * process it. */ return EOB_ACT_LAST_MATCH; } } /* Try to read more data. */ /* First move last chars to start of buffer. */ number_to_move = (int) ((yy_c_buf_p) - (yytext_ptr)) - 1; for ( i = 0; i < number_to_move; ++i ) *(dest++) = *(source++); if ( YY_CURRENT_BUFFER_LVALUE->yy_buffer_status == YY_BUFFER_EOF_PENDING ) /* don't do the read, it's not guaranteed to return an EOF, * just force an EOF */ YY_CURRENT_BUFFER_LVALUE->yy_n_chars = (yy_n_chars) = 0; else { yy_size_t num_to_read = YY_CURRENT_BUFFER_LVALUE->yy_buf_size - number_to_move - 1; while ( num_to_read <= 0 ) { /* Not enough room in the buffer - grow it. */ /* just a shorter name for the current buffer */ YY_BUFFER_STATE b = YY_CURRENT_BUFFER; int yy_c_buf_p_offset = (int) ((yy_c_buf_p) - b->yy_ch_buf); if ( b->yy_is_our_buffer ) { yy_size_t new_size = b->yy_buf_size * 2; if ( new_size <= 0 ) b->yy_buf_size += b->yy_buf_size / 8; else b->yy_buf_size *= 2; b->yy_ch_buf = (char *) /* Include room in for 2 EOB chars. */ yyrealloc((void *) b->yy_ch_buf,b->yy_buf_size + 2 ); } else /* Can't grow it, we don't own it. */ b->yy_ch_buf = 0; if ( ! b->yy_ch_buf ) YY_FATAL_ERROR( "fatal error - scanner input buffer overflow" ); (yy_c_buf_p) = &b->yy_ch_buf[yy_c_buf_p_offset]; num_to_read = YY_CURRENT_BUFFER_LVALUE->yy_buf_size - number_to_move - 1; } if ( num_to_read > YY_READ_BUF_SIZE ) num_to_read = YY_READ_BUF_SIZE; /* Read in more data. */ YY_INPUT( (&YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[number_to_move]), (yy_n_chars), num_to_read ); YY_CURRENT_BUFFER_LVALUE->yy_n_chars = (yy_n_chars); } if ( (yy_n_chars) == 0 ) { if ( number_to_move == YY_MORE_ADJ ) { ret_val = EOB_ACT_END_OF_FILE; yyrestart(yyin ); } else { ret_val = EOB_ACT_LAST_MATCH; YY_CURRENT_BUFFER_LVALUE->yy_buffer_status = YY_BUFFER_EOF_PENDING; } } else ret_val = EOB_ACT_CONTINUE_SCAN; if ((yy_size_t) ((yy_n_chars) + number_to_move) > YY_CURRENT_BUFFER_LVALUE->yy_buf_size) { /* Extend the array by 50%, plus the number we really need. */ yy_size_t new_size = (yy_n_chars) + number_to_move + ((yy_n_chars) >> 1); YY_CURRENT_BUFFER_LVALUE->yy_ch_buf = (char *) yyrealloc((void *) YY_CURRENT_BUFFER_LVALUE->yy_ch_buf,new_size ); if ( ! YY_CURRENT_BUFFER_LVALUE->yy_ch_buf ) YY_FATAL_ERROR( "out of dynamic memory in yy_get_next_buffer()" ); } (yy_n_chars) += number_to_move; YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[(yy_n_chars)] = YY_END_OF_BUFFER_CHAR; YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[(yy_n_chars) + 1] = YY_END_OF_BUFFER_CHAR; (yytext_ptr) = &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[0]; return ret_val; } /* yy_get_previous_state - get the state just before the EOB char was reached */ static yy_state_type yy_get_previous_state (void) { register yy_state_type yy_current_state; register char *yy_cp; yy_current_state = (yy_start); for ( yy_cp = (yytext_ptr) + YY_MORE_ADJ; yy_cp < (yy_c_buf_p); ++yy_cp ) { register YY_CHAR yy_c = (*yy_cp ? yy_ec[YY_SC_TO_UI(*yy_cp)] : 1); if ( yy_accept[yy_current_state] ) { (yy_last_accepting_state) = yy_current_state; (yy_last_accepting_cpos) = yy_cp; } while ( yy_chk[yy_base[yy_current_state] + yy_c] != yy_current_state ) { yy_current_state = (int) yy_def[yy_current_state]; if ( yy_current_state >= 36 ) yy_c = yy_meta[(unsigned int) yy_c]; } yy_current_state = yy_nxt[yy_base[yy_current_state] + (unsigned int) yy_c]; } return yy_current_state; } /* yy_try_NUL_trans - try to make a transition on the NUL character * * synopsis * next_state = yy_try_NUL_trans( current_state ); */ static yy_state_type yy_try_NUL_trans (yy_state_type yy_current_state ) { register int yy_is_jam; register char *yy_cp = (yy_c_buf_p); register YY_CHAR yy_c = 1; if ( yy_accept[yy_current_state] ) { (yy_last_accepting_state) = yy_current_state; (yy_last_accepting_cpos) = yy_cp; } while ( yy_chk[yy_base[yy_current_state] + yy_c] != yy_current_state ) { yy_current_state = (int) yy_def[yy_current_state]; if ( yy_current_state >= 36 ) yy_c = yy_meta[(unsigned int) yy_c]; } yy_current_state = yy_nxt[yy_base[yy_current_state] + (unsigned int) yy_c]; yy_is_jam = (yy_current_state == 35); return yy_is_jam ? 0 : yy_current_state; } static void yyunput (int c, register char * yy_bp ) { register char *yy_cp; yy_cp = (yy_c_buf_p); /* undo effects of setting up yytext */ *yy_cp = (yy_hold_char); if ( yy_cp < YY_CURRENT_BUFFER_LVALUE->yy_ch_buf + 2 ) { /* need to shift things up to make room */ /* +2 for EOB chars. */ register yy_size_t number_to_move = (yy_n_chars) + 2; register char *dest = &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[ YY_CURRENT_BUFFER_LVALUE->yy_buf_size + 2]; register char *source = &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[number_to_move]; while ( source > YY_CURRENT_BUFFER_LVALUE->yy_ch_buf ) *--dest = *--source; yy_cp += (int) (dest - source); yy_bp += (int) (dest - source); YY_CURRENT_BUFFER_LVALUE->yy_n_chars = (yy_n_chars) = YY_CURRENT_BUFFER_LVALUE->yy_buf_size; if ( yy_cp < YY_CURRENT_BUFFER_LVALUE->yy_ch_buf + 2 ) YY_FATAL_ERROR( "flex scanner push-back overflow" ); } *--yy_cp = (char) c; (yytext_ptr) = yy_bp; (yy_hold_char) = *yy_cp; (yy_c_buf_p) = yy_cp; } #ifndef YY_NO_INPUT #ifdef __cplusplus static int yyinput (void) #else static int input (void) #endif { int c; *(yy_c_buf_p) = (yy_hold_char); if ( *(yy_c_buf_p) == YY_END_OF_BUFFER_CHAR ) { /* yy_c_buf_p now points to the character we want to return. * If this occurs *before* the EOB characters, then it's a * valid NUL; if not, then we've hit the end of the buffer. */ if ( (yy_c_buf_p) < &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[(yy_n_chars)] ) /* This was really a NUL. */ *(yy_c_buf_p) = '\0'; else { /* need more input */ yy_size_t offset = (yy_c_buf_p) - (yytext_ptr); ++(yy_c_buf_p); switch ( yy_get_next_buffer( ) ) { case EOB_ACT_LAST_MATCH: /* This happens because yy_g_n_b() * sees that we've accumulated a * token and flags that we need to * try matching the token before * proceeding. But for input(), * there's no matching to consider. * So convert the EOB_ACT_LAST_MATCH * to EOB_ACT_END_OF_FILE. */ /* Reset buffer status. */ yyrestart(yyin ); /*FALLTHROUGH*/ case EOB_ACT_END_OF_FILE: { if ( yywrap( ) ) return 0; if ( ! (yy_did_buffer_switch_on_eof) ) YY_NEW_FILE; #ifdef __cplusplus return yyinput(); #else return input(); #endif } case EOB_ACT_CONTINUE_SCAN: (yy_c_buf_p) = (yytext_ptr) + offset; break; } } } c = *(unsigned char *) (yy_c_buf_p); /* cast for 8-bit char's */ *(yy_c_buf_p) = '\0'; /* preserve yytext */ (yy_hold_char) = *++(yy_c_buf_p); return c; } #endif /* ifndef YY_NO_INPUT */ /** Immediately switch to a different input stream. * @param input_file A readable stream. * * @note This function does not reset the start condition to @c INITIAL . */ void yyrestart (FILE * input_file ) { if ( ! YY_CURRENT_BUFFER ){ yyensure_buffer_stack (); YY_CURRENT_BUFFER_LVALUE = yy_create_buffer(yyin,YY_BUF_SIZE ); } yy_init_buffer(YY_CURRENT_BUFFER,input_file ); yy_load_buffer_state( ); } /** Switch to a different input buffer. * @param new_buffer The new input buffer. * */ void yy_switch_to_buffer (YY_BUFFER_STATE new_buffer ) { /* TODO. We should be able to replace this entire function body * with * yypop_buffer_state(); * yypush_buffer_state(new_buffer); */ yyensure_buffer_stack (); if ( YY_CURRENT_BUFFER == new_buffer ) return; if ( YY_CURRENT_BUFFER ) { /* Flush out information for old buffer. */ *(yy_c_buf_p) = (yy_hold_char); YY_CURRENT_BUFFER_LVALUE->yy_buf_pos = (yy_c_buf_p); YY_CURRENT_BUFFER_LVALUE->yy_n_chars = (yy_n_chars); } YY_CURRENT_BUFFER_LVALUE = new_buffer; yy_load_buffer_state( ); /* We don't actually know whether we did this switch during * EOF (yywrap()) processing, but the only time this flag * is looked at is after yywrap() is called, so it's safe * to go ahead and always set it. */ (yy_did_buffer_switch_on_eof) = 1; } static void yy_load_buffer_state (void) { (yy_n_chars) = YY_CURRENT_BUFFER_LVALUE->yy_n_chars; (yytext_ptr) = (yy_c_buf_p) = YY_CURRENT_BUFFER_LVALUE->yy_buf_pos; yyin = YY_CURRENT_BUFFER_LVALUE->yy_input_file; (yy_hold_char) = *(yy_c_buf_p); } /** Allocate and initialize an input buffer state. * @param file A readable stream. * @param size The character buffer size in bytes. When in doubt, use @c YY_BUF_SIZE. * * @return the allocated buffer state. */ YY_BUFFER_STATE yy_create_buffer (FILE * file, int size ) { YY_BUFFER_STATE b; b = (YY_BUFFER_STATE) yyalloc(sizeof( struct yy_buffer_state ) ); if ( ! b ) YY_FATAL_ERROR( "out of dynamic memory in yy_create_buffer()" ); b->yy_buf_size = size; /* yy_ch_buf has to be 2 characters longer than the size given because * we need to put in 2 end-of-buffer characters. */ b->yy_ch_buf = (char *) yyalloc(b->yy_buf_size + 2 ); if ( ! b->yy_ch_buf ) YY_FATAL_ERROR( "out of dynamic memory in yy_create_buffer()" ); b->yy_is_our_buffer = 1; yy_init_buffer(b,file ); return b; } /** Destroy the buffer. * @param b a buffer created with yy_create_buffer() * */ void yy_delete_buffer (YY_BUFFER_STATE b ) { if ( ! b ) return; if ( b == YY_CURRENT_BUFFER ) /* Not sure if we should pop here. */ YY_CURRENT_BUFFER_LVALUE = (YY_BUFFER_STATE) 0; if ( b->yy_is_our_buffer ) yyfree((void *) b->yy_ch_buf ); yyfree((void *) b ); } #ifndef __cplusplus extern int isatty (int ); #endif /* __cplusplus */ /* Initializes or reinitializes a buffer. * This function is sometimes called more than once on the same buffer, * such as during a yyrestart() or at EOF. */ static void yy_init_buffer (YY_BUFFER_STATE b, FILE * file ) { int oerrno = errno; yy_flush_buffer(b ); b->yy_input_file = file; b->yy_fill_buffer = 1; /* If b is the current buffer, then yy_init_buffer was _probably_ * called from yyrestart() or through yy_get_next_buffer. * In that case, we don't want to reset the lineno or column. */ if (b != YY_CURRENT_BUFFER){ b->yy_bs_lineno = 1; b->yy_bs_column = 0; } b->yy_is_interactive = file ? (isatty( fileno(file) ) > 0) : 0; errno = oerrno; } /** Discard all buffered characters. On the next scan, YY_INPUT will be called. * @param b the buffer state to be flushed, usually @c YY_CURRENT_BUFFER. * */ void yy_flush_buffer (YY_BUFFER_STATE b ) { if ( ! b ) return; b->yy_n_chars = 0; /* We always need two end-of-buffer characters. The first causes * a transition to the end-of-buffer state. The second causes * a jam in that state. */ b->yy_ch_buf[0] = YY_END_OF_BUFFER_CHAR; b->yy_ch_buf[1] = YY_END_OF_BUFFER_CHAR; b->yy_buf_pos = &b->yy_ch_buf[0]; b->yy_at_bol = 1; b->yy_buffer_status = YY_BUFFER_NEW; if ( b == YY_CURRENT_BUFFER ) yy_load_buffer_state( ); } /** Pushes the new state onto the stack. The new state becomes * the current state. This function will allocate the stack * if necessary. * @param new_buffer The new state. * */ void yypush_buffer_state (YY_BUFFER_STATE new_buffer ) { if (new_buffer == NULL) return; yyensure_buffer_stack(); /* This block is copied from yy_switch_to_buffer. */ if ( YY_CURRENT_BUFFER ) { /* Flush out information for old buffer. */ *(yy_c_buf_p) = (yy_hold_char); YY_CURRENT_BUFFER_LVALUE->yy_buf_pos = (yy_c_buf_p); YY_CURRENT_BUFFER_LVALUE->yy_n_chars = (yy_n_chars); } /* Only push if top exists. Otherwise, replace top. */ if (YY_CURRENT_BUFFER) (yy_buffer_stack_top)++; YY_CURRENT_BUFFER_LVALUE = new_buffer; /* copied from yy_switch_to_buffer. */ yy_load_buffer_state( ); (yy_did_buffer_switch_on_eof) = 1; } /** Removes and deletes the top of the stack, if present. * The next element becomes the new top. * */ void yypop_buffer_state (void) { if (!YY_CURRENT_BUFFER) return; yy_delete_buffer(YY_CURRENT_BUFFER ); YY_CURRENT_BUFFER_LVALUE = NULL; if ((yy_buffer_stack_top) > 0) --(yy_buffer_stack_top); if (YY_CURRENT_BUFFER) { yy_load_buffer_state( ); (yy_did_buffer_switch_on_eof) = 1; } } /* Allocates the stack if it does not exist. * Guarantees space for at least one push. */ static void yyensure_buffer_stack (void) { yy_size_t num_to_alloc; if (!(yy_buffer_stack)) { /* First allocation is just for 2 elements, since we don't know if this * scanner will even need a stack. We use 2 instead of 1 to avoid an * immediate realloc on the next call. */ num_to_alloc = 1; (yy_buffer_stack) = (struct yy_buffer_state**)yyalloc (num_to_alloc * sizeof(struct yy_buffer_state*) ); if ( ! (yy_buffer_stack) ) YY_FATAL_ERROR( "out of dynamic memory in yyensure_buffer_stack()" ); memset((yy_buffer_stack), 0, num_to_alloc * sizeof(struct yy_buffer_state*)); (yy_buffer_stack_max) = num_to_alloc; (yy_buffer_stack_top) = 0; return; } if ((yy_buffer_stack_top) >= ((yy_buffer_stack_max)) - 1){ /* Increase the buffer to prepare for a possible push. */ int grow_size = 8 /* arbitrary grow size */; num_to_alloc = (yy_buffer_stack_max) + grow_size; (yy_buffer_stack) = (struct yy_buffer_state**)yyrealloc ((yy_buffer_stack), num_to_alloc * sizeof(struct yy_buffer_state*) ); if ( ! (yy_buffer_stack) ) YY_FATAL_ERROR( "out of dynamic memory in yyensure_buffer_stack()" ); /* zero only the new slots.*/ memset((yy_buffer_stack) + (yy_buffer_stack_max), 0, grow_size * sizeof(struct yy_buffer_state*)); (yy_buffer_stack_max) = num_to_alloc; } } /** Setup the input buffer state to scan directly from a user-specified character buffer. * @param base the character buffer * @param size the size in bytes of the character buffer * * @return the newly allocated buffer state object. */ YY_BUFFER_STATE yy_scan_buffer (char * base, yy_size_t size ) { YY_BUFFER_STATE b; if ( size < 2 || base[size-2] != YY_END_OF_BUFFER_CHAR || base[size-1] != YY_END_OF_BUFFER_CHAR ) /* They forgot to leave room for the EOB's. */ return 0; b = (YY_BUFFER_STATE) yyalloc(sizeof( struct yy_buffer_state ) ); if ( ! b ) YY_FATAL_ERROR( "out of dynamic memory in yy_scan_buffer()" ); b->yy_buf_size = size - 2; /* "- 2" to take care of EOB's */ b->yy_buf_pos = b->yy_ch_buf = base; b->yy_is_our_buffer = 0; b->yy_input_file = 0; b->yy_n_chars = b->yy_buf_size; b->yy_is_interactive = 0; b->yy_at_bol = 1; b->yy_fill_buffer = 0; b->yy_buffer_status = YY_BUFFER_NEW; yy_switch_to_buffer(b ); return b; } /** Setup the input buffer state to scan a string. The next call to yylex() will * scan from a @e copy of @a str. * @param yystr a NUL-terminated string to scan * * @return the newly allocated buffer state object. * @note If you want to scan bytes that may contain NUL values, then use * yy_scan_bytes() instead. */ YY_BUFFER_STATE yy_scan_string (yyconst char * yystr ) { return yy_scan_bytes(yystr,strlen(yystr) ); } /** Setup the input buffer state to scan the given bytes. The next call to yylex() will * scan from a @e copy of @a bytes. * @param bytes the byte buffer to scan * @param len the number of bytes in the buffer pointed to by @a bytes. * * @return the newly allocated buffer state object. */ YY_BUFFER_STATE yy_scan_bytes (yyconst char * yybytes, yy_size_t _yybytes_len ) { YY_BUFFER_STATE b; char *buf; yy_size_t n, i; /* Get memory for full buffer, including space for trailing EOB's. */ n = _yybytes_len + 2; buf = (char *) yyalloc(n ); if ( ! buf ) YY_FATAL_ERROR( "out of dynamic memory in yy_scan_bytes()" ); for ( i = 0; i < _yybytes_len; ++i ) buf[i] = yybytes[i]; buf[_yybytes_len] = buf[_yybytes_len+1] = YY_END_OF_BUFFER_CHAR; b = yy_scan_buffer(buf,n ); if ( ! b ) YY_FATAL_ERROR( "bad buffer in yy_scan_bytes()" ); /* It's okay to grow etc. this buffer, and we should throw it * away when we're done. */ b->yy_is_our_buffer = 1; return b; } #ifndef YY_EXIT_FAILURE #define YY_EXIT_FAILURE 2 #endif static void yy_fatal_error (yyconst char* msg ) { (void) fprintf( stderr, "%s\n", msg ); exit( YY_EXIT_FAILURE ); } /* Redefine yyless() so it works in section 3 code. */ #undef yyless #define yyless(n) \ do \ { \ /* Undo effects of setting up yytext. */ \ int yyless_macro_arg = (n); \ YY_LESS_LINENO(yyless_macro_arg);\ yytext[yyleng] = (yy_hold_char); \ (yy_c_buf_p) = yytext + yyless_macro_arg; \ (yy_hold_char) = *(yy_c_buf_p); \ *(yy_c_buf_p) = '\0'; \ yyleng = yyless_macro_arg; \ } \ while ( 0 ) /* Accessor methods (get/set functions) to struct members. */ /** Get the current line number. * */ int yyget_lineno (void) { return yylineno; } /** Get the input stream. * */ FILE *yyget_in (void) { return yyin; } /** Get the output stream. * */ FILE *yyget_out (void) { return yyout; } /** Get the length of the current token. * */ yy_size_t yyget_leng (void) { return yyleng; } /** Get the current token. * */ char *yyget_text (void) { return yytext; } /** Set the current line number. * @param line_number * */ void yyset_lineno (int line_number ) { yylineno = line_number; } /** Set the input stream. This does not discard the current * input buffer. * @param in_str A readable stream. * * @see yy_switch_to_buffer */ void yyset_in (FILE * in_str ) { yyin = in_str ; } void yyset_out (FILE * out_str ) { yyout = out_str ; } int yyget_debug (void) { return yy_flex_debug; } void yyset_debug (int bdebug ) { yy_flex_debug = bdebug ; } static int yy_init_globals (void) { /* Initialization is the same as for the non-reentrant scanner. * This function is called from yylex_destroy(), so don't allocate here. */ (yy_buffer_stack) = 0; (yy_buffer_stack_top) = 0; (yy_buffer_stack_max) = 0; (yy_c_buf_p) = (char *) 0; (yy_init) = 0; (yy_start) = 0; /* Defined in main.c */ #ifdef YY_STDINIT yyin = stdin; yyout = stdout; #else yyin = (FILE *) 0; yyout = (FILE *) 0; #endif /* For future reference: Set errno on error, since we are called by * yylex_init() */ return 0; } /* yylex_destroy is for both reentrant and non-reentrant scanners. */ int yylex_destroy (void) { /* Pop the buffer stack, destroying each element. */ while(YY_CURRENT_BUFFER){ yy_delete_buffer(YY_CURRENT_BUFFER ); YY_CURRENT_BUFFER_LVALUE = NULL; yypop_buffer_state(); } /* Destroy the stack itself. */ yyfree((yy_buffer_stack) ); (yy_buffer_stack) = NULL; /* Reset the globals. This is important in a non-reentrant scanner so the next time * yylex() is called, initialization will occur. */ yy_init_globals( ); return 0; } /* * Internal utility routines. */ #ifndef yytext_ptr static void yy_flex_strncpy (char* s1, yyconst char * s2, int n ) { register int i; for ( i = 0; i < n; ++i ) s1[i] = s2[i]; } #endif #ifdef YY_NEED_STRLEN static int yy_flex_strlen (yyconst char * s ) { register int n; for ( n = 0; s[n]; ++n ) ; return n; } #endif void *yyalloc (yy_size_t size ) { return (void *) malloc( size ); } void *yyrealloc (void * ptr, yy_size_t size ) { /* The cast to (char *) in the following accommodates both * implementations that use char* generic pointers, and those * that use void* generic pointers. It works with the latter * because both ANSI C and C++ allow castless assignment from * any pointer type to void*, and deal with argument conversions * as though doing an assignment. */ return (void *) realloc( (char *) ptr, size ); } void yyfree (void * ptr ) { free( (char *) ptr ); /* see yyrealloc() for (char *) cast */ } #define YYTABLES_NAME "yytables" #line 90 "sel-lex.l" static char * handle_string(void) { char x[1024]; int i = 0; int c; int quote = 0; while((c = input()) != EOF){ if(quote) { x[i++] = '\\'; x[i++] = c; quote = 0; continue; } if(c == '\n'){ _hx509_sel_yyerror("unterminated string"); lineno++; break; } if(c == '\\'){ quote++; continue; } if(c == '\"') break; x[i++] = c; } x[i] = '\0'; return strdup(x); } #if !defined(yywrap) #define yywrap _hx509_sel_yywrap #endif int yywrap () { return 1; } static int lex_input(char *buf, int max_size) { int n; n = _hx509_expr_input.length - _hx509_expr_input.offset; if (max_size < n) n = max_size; if (n <= 0) return YY_NULL; memcpy(buf, _hx509_expr_input.buf + _hx509_expr_input.offset, n); _hx509_expr_input.offset += n; return n; } heimdal-7.5.0/lib/hx509/file.c0000644000175000017500000001374113026237312013765 0ustar niknik/* * Copyright (c) 2005 - 2006 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "hx_locl.h" int _hx509_map_file_os(const char *fn, heim_octet_string *os) { size_t length; void *data; int ret; ret = rk_undumpdata(fn, &data, &length); os->data = data; os->length = length; return ret; } void _hx509_unmap_file_os(heim_octet_string *os) { rk_xfree(os->data); } int _hx509_write_file(const char *fn, const void *data, size_t length) { rk_dumpdata(fn, data, length); return 0; } /* * */ static void print_pem_stamp(FILE *f, const char *type, const char *str) { fprintf(f, "-----%s %s-----\n", type, str); } int hx509_pem_write(hx509_context context, const char *type, hx509_pem_header *headers, FILE *f, const void *data, size_t size) { const char *p = data; size_t length; char *line; #define ENCODE_LINE_LENGTH 54 print_pem_stamp(f, "BEGIN", type); while (headers) { fprintf(f, "%s: %s\n%s", headers->header, headers->value, headers->next ? "" : "\n"); headers = headers->next; } while (size > 0) { ssize_t l; length = size; if (length > ENCODE_LINE_LENGTH) length = ENCODE_LINE_LENGTH; l = rk_base64_encode(p, length, &line); if (l < 0) { hx509_set_error_string(context, 0, ENOMEM, "malloc - out of memory"); return ENOMEM; } size -= length; fprintf(f, "%s\n", line); p += length; free(line); } print_pem_stamp(f, "END", type); return 0; } /* * */ int hx509_pem_add_header(hx509_pem_header **headers, const char *header, const char *value) { hx509_pem_header *h; h = calloc(1, sizeof(*h)); if (h == NULL) return ENOMEM; h->header = strdup(header); if (h->header == NULL) { free(h); return ENOMEM; } h->value = strdup(value); if (h->value == NULL) { free(h->header); free(h); return ENOMEM; } h->next = *headers; *headers = h; return 0; } void hx509_pem_free_header(hx509_pem_header *headers) { hx509_pem_header *h; while (headers) { h = headers; headers = headers->next; free(h->header); free(h->value); free(h); } } /* * */ const char * hx509_pem_find_header(const hx509_pem_header *h, const char *header) { while(h) { if (strcmp(header, h->header) == 0) return h->value; h = h->next; } return NULL; } /* * */ int hx509_pem_read(hx509_context context, FILE *f, hx509_pem_read_func func, void *ctx) { hx509_pem_header *headers = NULL; char *type = NULL; void *data = NULL; size_t len = 0; char buf[1024]; int ret = HX509_PARSING_KEY_FAILED; enum { BEFORE, SEARCHHEADER, INHEADER, INDATA, DONE } where; where = BEFORE; while (fgets(buf, sizeof(buf), f) != NULL) { char *p; int i; i = strcspn(buf, "\n"); if (buf[i] == '\n') { buf[i] = '\0'; if (i > 0) i--; } if (buf[i] == '\r') { buf[i] = '\0'; if (i > 0) i--; } switch (where) { case BEFORE: if (strncmp("-----BEGIN ", buf, 11) == 0) { type = strdup(buf + 11); if (type == NULL) break; p = strchr(type, '-'); if (p) *p = '\0'; where = SEARCHHEADER; } break; case SEARCHHEADER: p = strchr(buf, ':'); if (p == NULL) { where = INDATA; goto indata; } /* FALLTHOUGH */ case INHEADER: if (buf[0] == '\0') { where = INDATA; break; } p = strchr(buf, ':'); if (p) { *p++ = '\0'; while (isspace((int)*p)) p++; ret = hx509_pem_add_header(&headers, buf, p); if (ret) abort(); } break; case INDATA: indata: if (strncmp("-----END ", buf, 9) == 0) { where = DONE; break; } p = emalloc(i); i = rk_base64_decode(buf, p); if (i < 0) { free(p); goto out; } data = erealloc(data, len + i); memcpy(((char *)data) + len, p, i); free(p); len += i; break; case DONE: abort(); } if (where == DONE) { ret = (*func)(context, type, headers, data, len, ctx); out: free(data); data = NULL; len = 0; free(type); type = NULL; where = BEFORE; hx509_pem_free_header(headers); headers = NULL; if (ret) break; } } if (where != BEFORE) { hx509_set_error_string(context, 0, HX509_PARSING_KEY_FAILED, "File ends before end of PEM end tag"); ret = HX509_PARSING_KEY_FAILED; } if (data) free(data); if (type) free(type); if (headers) hx509_pem_free_header(headers); return ret; } heimdal-7.5.0/lib/hx509/ocsp.asn10000644000175000017500000001005012136107750014423 0ustar niknik-- From rfc2560 -- $Id$ OCSP DEFINITIONS EXPLICIT TAGS::= BEGIN IMPORTS Certificate, AlgorithmIdentifier, CRLReason, Name, GeneralName, CertificateSerialNumber, Extensions FROM rfc2459; OCSPVersion ::= INTEGER { ocsp-v1(0) } OCSPCertStatus ::= CHOICE { good [0] IMPLICIT NULL, revoked [1] IMPLICIT -- OCSPRevokedInfo -- SEQUENCE { revocationTime GeneralizedTime, revocationReason[0] EXPLICIT CRLReason OPTIONAL }, unknown [2] IMPLICIT NULL } OCSPCertID ::= SEQUENCE { hashAlgorithm AlgorithmIdentifier, issuerNameHash OCTET STRING, -- Hash of Issuer's DN issuerKeyHash OCTET STRING, -- Hash of Issuers public key serialNumber CertificateSerialNumber } OCSPSingleResponse ::= SEQUENCE { certID OCSPCertID, certStatus OCSPCertStatus, thisUpdate GeneralizedTime, nextUpdate [0] EXPLICIT GeneralizedTime OPTIONAL, singleExtensions [1] EXPLICIT Extensions OPTIONAL } OCSPInnerRequest ::= SEQUENCE { reqCert OCSPCertID, singleRequestExtensions [0] EXPLICIT Extensions OPTIONAL } OCSPTBSRequest ::= SEQUENCE { version [0] EXPLICIT OCSPVersion -- DEFAULT v1 -- OPTIONAL, requestorName [1] EXPLICIT GeneralName OPTIONAL, requestList SEQUENCE OF OCSPInnerRequest, requestExtensions [2] EXPLICIT Extensions OPTIONAL } OCSPSignature ::= SEQUENCE { signatureAlgorithm AlgorithmIdentifier, signature BIT STRING, certs [0] EXPLICIT SEQUENCE OF Certificate OPTIONAL } OCSPRequest ::= SEQUENCE { tbsRequest OCSPTBSRequest, optionalSignature [0] EXPLICIT OCSPSignature OPTIONAL } OCSPResponseBytes ::= SEQUENCE { responseType OBJECT IDENTIFIER, response OCTET STRING } OCSPResponseStatus ::= ENUMERATED { successful (0), --Response has valid confirmations malformedRequest (1), --Illegal confirmation request internalError (2), --Internal error in issuer tryLater (3), --Try again later --(4) is not used sigRequired (5), --Must sign the request unauthorized (6) --Request unauthorized } OCSPResponse ::= SEQUENCE { responseStatus OCSPResponseStatus, responseBytes [0] EXPLICIT OCSPResponseBytes OPTIONAL } OCSPKeyHash ::= OCTET STRING --SHA-1 hash of responder's public key --(excluding the tag and length fields) OCSPResponderID ::= CHOICE { byName [1] Name, byKey [2] OCSPKeyHash } OCSPResponseData ::= SEQUENCE { version [0] EXPLICIT OCSPVersion -- DEFAULT v1 -- OPTIONAL, responderID OCSPResponderID, producedAt GeneralizedTime, responses SEQUENCE OF OCSPSingleResponse, responseExtensions [1] EXPLICIT Extensions OPTIONAL } OCSPBasicOCSPResponse ::= SEQUENCE { tbsResponseData OCSPResponseData, signatureAlgorithm AlgorithmIdentifier, signature BIT STRING, certs [0] EXPLICIT SEQUENCE OF Certificate OPTIONAL } -- ArchiveCutoff ::= GeneralizedTime -- AcceptableResponses ::= SEQUENCE OF OBJECT IDENTIFIER -- Object Identifiers id-pkix-ocsp OBJECT IDENTIFIER ::= { iso(1) identified-organization(3) dod(6) internet(1) security(5) mechanisms(5) pkix(7) pkix-ad(48) 1 } id-pkix-ocsp-basic OBJECT IDENTIFIER ::= { id-pkix-ocsp 1 } id-pkix-ocsp-nonce OBJECT IDENTIFIER ::= { id-pkix-ocsp 2 } -- id-pkix-ocsp-crl OBJECT IDENTIFIER ::= { id-pkix-ocsp 3 } -- id-pkix-ocsp-response OBJECT IDENTIFIER ::= { id-pkix-ocsp 4 } -- id-pkix-ocsp-nocheck OBJECT IDENTIFIER ::= { id-pkix-ocsp 5 } -- id-pkix-ocsp-archive-cutoff OBJECT IDENTIFIER ::= { id-pkix-ocsp 6 } -- id-pkix-ocsp-service-locator OBJECT IDENTIFIER ::= { id-pkix-ocsp 7 } END heimdal-7.5.0/lib/hx509/version-script.map0000644000175000017500000001447113026237312016371 0ustar niknik# $Id$ HEIMDAL_X509_1.2 { global: _hx509_cert_assign_key; _hx509_cert_private_key; _hx509_certs_keys_free; _hx509_certs_keys_get; _hx509_expr_eval; _hx509_expr_free; _hx509_expr_parse; _hx509_generate_private_key; _hx509_generate_private_key_bits; _hx509_generate_private_key_free; _hx509_generate_private_key_init; _hx509_generate_private_key_is_ca; _hx509_map_file_os; _hx509_name_from_Name; _hx509_private_key_ref; _hx509_request_add_dns_name; _hx509_request_add_email; _hx509_request_parse; _hx509_request_print; _hx509_request_set_email; _hx509_request_to_pkcs10; _hx509_unmap_file_os; _hx509_write_file; hx509_bitstring_print; hx509_ca_sign; hx509_ca_sign_self; hx509_ca_tbs_add_crl_dp_uri; hx509_ca_tbs_add_eku; hx509_ca_tbs_add_san_hostname; hx509_ca_tbs_add_san_jid; hx509_ca_tbs_add_san_ms_upn; hx509_ca_tbs_add_san_otherName; hx509_ca_tbs_add_san_pkinit; hx509_ca_tbs_add_san_rfc822name; hx509_ca_tbs_free; hx509_ca_tbs_init; hx509_ca_tbs_set_ca; hx509_ca_tbs_set_domaincontroller; hx509_ca_tbs_set_notAfter; hx509_ca_tbs_set_notAfter_lifetime; hx509_ca_tbs_set_notBefore; hx509_ca_tbs_set_proxy; hx509_ca_tbs_set_serialnumber; hx509_ca_tbs_set_spki; hx509_ca_tbs_set_subject; hx509_ca_tbs_set_template; hx509_ca_tbs_set_unique; hx509_ca_tbs_subject_expand; hx509_ca_tbs_template_units; hx509_cert; hx509_cert_attribute; hx509_cert_binary; hx509_cert_check_eku; hx509_cert_cmp; hx509_cert_find_subjectAltName_otherName; hx509_cert_free; hx509_cert_get_SPKI; hx509_cert_get_SPKI_AlgorithmIdentifier; hx509_cert_get_attribute; hx509_cert_get_base_subject; hx509_cert_get_friendly_name; hx509_cert_get_issuer; hx509_cert_get_notAfter; hx509_cert_get_notBefore; hx509_cert_get_serialnumber; hx509_cert_get_subject; hx509_cert_get_issuer_unique_id; hx509_cert_get_subject_unique_id; hx509_cert_init; hx509_cert_init_data; hx509_cert_keyusage_print; hx509_cert_public_encrypt; hx509_cert_ref; hx509_cert_set_friendly_name; hx509_certs_add; hx509_certs_append; hx509_certs_end_seq; hx509_certs_ref; hx509_certs_filter; hx509_certs_find; hx509_certs_free; hx509_certs_info; hx509_certs_init; hx509_certs_iter; hx509_certs_iter_f; hx509_certs_merge; hx509_certs_next_cert; hx509_certs_start_seq; hx509_certs_store; hx509_ci_print_names; hx509_clear_error_string; hx509_cms_create_signed; hx509_cms_create_signed_1; hx509_cms_decrypt_encrypted; hx509_cms_envelope_1; hx509_cms_unenvelope; hx509_cms_unwrap_ContentInfo; hx509_cms_verify_signed; hx509_cms_wrap_ContentInfo; hx509_context_free; hx509_context_init; hx509_context_set_missing_revoke; hx509_crl_add_revoked_certs; hx509_crl_alloc; hx509_crl_free; hx509_crl_lifetime; hx509_crl_sign; hx509_crypto_aes128_cbc; hx509_crypto_aes256_cbc; hx509_crypto_allow_weak; hx509_crypto_available; hx509_crypto_decrypt; hx509_crypto_des_rsdi_ede3_cbc; hx509_crypto_destroy; hx509_crypto_encrypt; hx509_crypto_enctype_by_name; hx509_crypto_free_algs; hx509_crypto_get_params; hx509_crypto_init; hx509_crypto_provider; hx509_crypto_select; hx509_crypto_set_key_data; hx509_crypto_set_key_name; hx509_crypto_set_padding; hx509_crypto_set_params; hx509_crypto_set_random_key; hx509_env_add; hx509_env_add_binding; hx509_env_find; hx509_env_find_binding; hx509_env_free; hx509_env_init; hx509_env_lfind; hx509_err; hx509_free_error_string; hx509_free_octet_string_list; hx509_find_private_alg; hx509_general_name_unparse; hx509_get_error_string; hx509_get_one_cert; hx509_lock_add_cert; hx509_lock_add_certs; hx509_lock_add_password; hx509_lock_command_string; hx509_lock_free; hx509_lock_init; hx509_lock_prompt; hx509_lock_reset_certs; hx509_lock_reset_passwords; hx509_lock_reset_promper; hx509_lock_set_prompter; hx509_name_binary; hx509_name_cmp; hx509_name_copy; hx509_name_expand; hx509_name_free; hx509_name_is_null_p; hx509_name_normalize; hx509_name_to_Name; hx509_name_to_string; hx509_ocsp_request; hx509_ocsp_verify; hx509_oid_print; hx509_oid_sprint; hx509_parse_name; hx509_parse_private_key; hx509_peer_info_add_cms_alg; hx509_peer_info_alloc; hx509_peer_info_free; hx509_peer_info_set_cert; hx509_peer_info_set_cms_algs; hx509_pem_add_header; hx509_pem_find_header; hx509_pem_free_header; hx509_pem_read; hx509_pem_write; hx509_print_stdout; hx509_print_cert; hx509_private_key_assign_rsa; hx509_private_key_free; hx509_private_key_private_decrypt; hx509_private_key_init; hx509_private_key2SPKI; hx509_prompt_hidden; hx509_query_alloc; hx509_query_free; hx509_query_match_cmp_func; hx509_query_match_eku; hx509_query_match_expr; hx509_query_match_friendly_name; hx509_query_match_issuer_serial; hx509_query_match_option; hx509_query_statistic_file; hx509_query_unparse_stats; hx509_request_get_name; hx509_request_get_SubjectPublicKeyInfo; hx509_request_free; hx509_request_init; hx509_request_set_name; hx509_request_set_SubjectPublicKeyInfo; hx509_revoke_add_crl; hx509_revoke_add_ocsp; hx509_revoke_free; hx509_revoke_init; hx509_revoke_ocsp_print; hx509_revoke_verify; hx509_revoke_print; hx509_set_error_string; hx509_set_error_stringv; hx509_signature_md5; hx509_signature_rsa; hx509_signature_rsa_with_md5; hx509_signature_rsa_with_sha1; hx509_signature_rsa_with_sha256; hx509_signature_rsa_with_sha384; hx509_signature_rsa_with_sha512; hx509_signature_sha1; hx509_signature_sha256; hx509_signature_sha384; hx509_signature_sha512; hx509_unparse_der_name; hx509_validate_cert; hx509_validate_ctx_add_flags; hx509_validate_ctx_free; hx509_validate_ctx_init; hx509_validate_ctx_set_print; hx509_verify_attach_anchors; hx509_verify_attach_revoke; hx509_verify_ctx_f_allow_default_trustanchors; hx509_verify_destroy_ctx; hx509_verify_hostname; hx509_verify_init_ctx; hx509_verify_path; hx509_verify_set_max_depth; hx509_verify_set_proxy_certificate; hx509_verify_set_strict_rfc3280_verification; hx509_verify_set_time; hx509_verify_signature; hx509_xfree; initialize_hx_error_table_r; # pkcs11 symbols C_GetFunctionList; local: *; }; HEIMDAL_X509_1.3 { global: hx509_ca_tbs_set_signature_algorithm; }; heimdal-7.5.0/lib/hx509/name.c0000644000175000017500000006114313026237312013765 0ustar niknik/* * Copyright (c) 2004 - 2009 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "hx_locl.h" #include #include "char_map.h" /** * @page page_name PKIX/X.509 Names * * There are several names in PKIX/X.509, GeneralName and Name. * * A Name consists of an ordered list of Relative Distinguished Names * (RDN). Each RDN consists of an unordered list of typed strings. The * types are defined by OID and have long and short description. For * example id-at-commonName (2.5.4.3) have the long name CommonName * and short name CN. The string itself can be of several encoding, * UTF8, UTF16, Teltex string, etc. The type limit what encoding * should be used. * * GeneralName is a broader nametype that can contains al kind of * stuff like Name, IP addresses, partial Name, etc. * * Name is mapped into a hx509_name object. * * Parse and string name into a hx509_name object with hx509_parse_name(), * make it back into string representation with hx509_name_to_string(). * * Name string are defined rfc2253, rfc1779 and X.501. * * See the library functions here: @ref hx509_name */ static const struct { const char *n; const heim_oid *o; wind_profile_flags flags; } no[] = { { "C", &asn1_oid_id_at_countryName, 0 }, { "CN", &asn1_oid_id_at_commonName, 0 }, { "DC", &asn1_oid_id_domainComponent, 0 }, { "L", &asn1_oid_id_at_localityName, 0 }, { "O", &asn1_oid_id_at_organizationName, 0 }, { "OU", &asn1_oid_id_at_organizationalUnitName, 0 }, { "S", &asn1_oid_id_at_stateOrProvinceName, 0 }, { "STREET", &asn1_oid_id_at_streetAddress, 0 }, { "UID", &asn1_oid_id_Userid, 0 }, { "emailAddress", &asn1_oid_id_pkcs9_emailAddress, 0 }, { "serialNumber", &asn1_oid_id_at_serialNumber, 0 } }; static char * quote_string(const char *f, size_t len, int flags, size_t *rlen) { size_t i, j, tolen; const unsigned char *from = (const unsigned char *)f; unsigned char *to; tolen = len * 3 + 1; to = malloc(tolen); if (to == NULL) return NULL; for (i = 0, j = 0; i < len; i++) { unsigned char map = char_map[from[i]] & flags; if (i == 0 && (map & Q_RFC2253_QUOTE_FIRST)) { to[j++] = '\\'; to[j++] = from[i]; } else if ((i + 1) == len && (map & Q_RFC2253_QUOTE_LAST)) { to[j++] = '\\'; to[j++] = from[i]; } else if (map & Q_RFC2253_QUOTE) { to[j++] = '\\'; to[j++] = from[i]; } else if (map & Q_RFC2253_HEX) { int l = snprintf((char *)&to[j], tolen - j - 1, "#%02x", (unsigned char)from[i]); j += l; } else { to[j++] = from[i]; } } to[j] = '\0'; assert(j < tolen); *rlen = j; return (char *)to; } static int append_string(char **str, size_t *total_len, const char *ss, size_t len, int quote) { char *s, *qs; if (quote) qs = quote_string(ss, len, Q_RFC2253, &len); else qs = rk_UNCONST(ss); s = realloc(*str, len + *total_len + 1); if (s == NULL) _hx509_abort("allocation failure"); /* XXX */ memcpy(s + *total_len, qs, len); if (qs != ss) free(qs); s[*total_len + len] = '\0'; *str = s; *total_len += len; return 0; } static char * oidtostring(const heim_oid *type) { char *s; size_t i; for (i = 0; i < sizeof(no)/sizeof(no[0]); i++) { if (der_heim_oid_cmp(no[i].o, type) == 0) return strdup(no[i].n); } if (der_print_heim_oid(type, '.', &s) != 0) return NULL; return s; } static int stringtooid(const char *name, size_t len, heim_oid *oid) { int ret; size_t i; char *s; memset(oid, 0, sizeof(*oid)); for (i = 0; i < sizeof(no)/sizeof(no[0]); i++) { if (strncasecmp(no[i].n, name, len) == 0) return der_copy_oid(no[i].o, oid); } s = malloc(len + 1); if (s == NULL) return ENOMEM; memcpy(s, name, len); s[len] = '\0'; ret = der_parse_heim_oid(s, ".", oid); free(s); return ret; } /** * Convert the hx509 name object into a printable string. * The resulting string should be freed with free(). * * @param name name to print * @param str the string to return * * @return An hx509 error code, see hx509_get_error_string(). * * @ingroup hx509_name */ int hx509_name_to_string(const hx509_name name, char **str) { return _hx509_Name_to_string(&name->der_name, str); } int _hx509_Name_to_string(const Name *n, char **str) { size_t total_len = 0; size_t i, j, m; int ret; *str = strdup(""); if (*str == NULL) return ENOMEM; for (m = n->u.rdnSequence.len; m > 0; m--) { size_t len; i = m - 1; for (j = 0; j < n->u.rdnSequence.val[i].len; j++) { DirectoryString *ds = &n->u.rdnSequence.val[i].val[j].value; char *oidname; char *ss; oidname = oidtostring(&n->u.rdnSequence.val[i].val[j].type); switch(ds->element) { case choice_DirectoryString_ia5String: ss = ds->u.ia5String.data; len = ds->u.ia5String.length; break; case choice_DirectoryString_printableString: ss = ds->u.printableString.data; len = ds->u.printableString.length; break; case choice_DirectoryString_utf8String: ss = ds->u.utf8String; len = strlen(ss); break; case choice_DirectoryString_bmpString: { const uint16_t *bmp = ds->u.bmpString.data; size_t bmplen = ds->u.bmpString.length; size_t k; ret = wind_ucs2utf8_length(bmp, bmplen, &k); if (ret) { free(oidname); free(*str); *str = NULL; return ret; } ss = malloc(k + 1); if (ss == NULL) _hx509_abort("allocation failure"); /* XXX */ ret = wind_ucs2utf8(bmp, bmplen, ss, NULL); if (ret) { free(oidname); free(ss); free(*str); *str = NULL; return ret; } ss[k] = '\0'; len = k; break; } case choice_DirectoryString_teletexString: ss = ds->u.teletexString; len = strlen(ss); break; case choice_DirectoryString_universalString: { const uint32_t *uni = ds->u.universalString.data; size_t unilen = ds->u.universalString.length; size_t k; ret = wind_ucs4utf8_length(uni, unilen, &k); if (ret) { free(oidname); free(*str); *str = NULL; return ret; } ss = malloc(k + 1); if (ss == NULL) _hx509_abort("allocation failure"); /* XXX */ ret = wind_ucs4utf8(uni, unilen, ss, NULL); if (ret) { free(ss); free(oidname); free(*str); *str = NULL; return ret; } ss[k] = '\0'; len = k; break; } default: _hx509_abort("unknown directory type: %d", ds->element); exit(1); } append_string(str, &total_len, oidname, strlen(oidname), 0); free(oidname); append_string(str, &total_len, "=", 1, 0); append_string(str, &total_len, ss, len, 1); if (ds->element == choice_DirectoryString_bmpString || ds->element == choice_DirectoryString_universalString) { free(ss); } if (j + 1 < n->u.rdnSequence.val[i].len) append_string(str, &total_len, "+", 1, 0); } if (i > 0) append_string(str, &total_len, ",", 1, 0); } return 0; } #define COPYCHARARRAY(_ds,_el,_l,_n) \ (_l) = strlen(_ds->u._el); \ (_n) = malloc((_l) * sizeof((_n)[0])); \ if ((_n) == NULL) \ return ENOMEM; \ for (i = 0; i < (_l); i++) \ (_n)[i] = _ds->u._el[i] #define COPYVALARRAY(_ds,_el,_l,_n) \ (_l) = _ds->u._el.length; \ (_n) = malloc((_l) * sizeof((_n)[0])); \ if ((_n) == NULL) \ return ENOMEM; \ for (i = 0; i < (_l); i++) \ (_n)[i] = _ds->u._el.data[i] #define COPYVOIDARRAY(_ds,_el,_l,_n) \ (_l) = _ds->u._el.length; \ (_n) = malloc((_l) * sizeof((_n)[0])); \ if ((_n) == NULL) \ return ENOMEM; \ for (i = 0; i < (_l); i++) \ (_n)[i] = ((unsigned char *)_ds->u._el.data)[i] static int dsstringprep(const DirectoryString *ds, uint32_t **rname, size_t *rlen) { wind_profile_flags flags; size_t i, len; int ret; uint32_t *name; *rname = NULL; *rlen = 0; switch(ds->element) { case choice_DirectoryString_ia5String: flags = WIND_PROFILE_LDAP; COPYVOIDARRAY(ds, ia5String, len, name); break; case choice_DirectoryString_printableString: flags = WIND_PROFILE_LDAP; flags |= WIND_PROFILE_LDAP_CASE_EXACT_ATTRIBUTE; COPYVOIDARRAY(ds, printableString, len, name); break; case choice_DirectoryString_teletexString: flags = WIND_PROFILE_LDAP_CASE; COPYCHARARRAY(ds, teletexString, len, name); break; case choice_DirectoryString_bmpString: flags = WIND_PROFILE_LDAP; COPYVALARRAY(ds, bmpString, len, name); break; case choice_DirectoryString_universalString: flags = WIND_PROFILE_LDAP; COPYVALARRAY(ds, universalString, len, name); break; case choice_DirectoryString_utf8String: flags = WIND_PROFILE_LDAP; ret = wind_utf8ucs4_length(ds->u.utf8String, &len); if (ret) return ret; name = malloc(len * sizeof(name[0])); if (name == NULL) return ENOMEM; ret = wind_utf8ucs4(ds->u.utf8String, name, &len); if (ret) { free(name); return ret; } break; default: _hx509_abort("unknown directory type: %d", ds->element); } *rlen = len; /* try a couple of times to get the length right, XXX gross */ for (i = 0; i < 4; i++) { *rlen = *rlen * 2; *rname = malloc(*rlen * sizeof((*rname)[0])); ret = wind_stringprep(name, len, *rname, rlen, flags); if (ret == WIND_ERR_OVERRUN) { free(*rname); *rname = NULL; continue; } else break; } free(name); if (ret) { if (*rname) free(*rname); *rname = NULL; *rlen = 0; return ret; } return 0; } int _hx509_name_ds_cmp(const DirectoryString *ds1, const DirectoryString *ds2, int *diff) { uint32_t *ds1lp, *ds2lp; size_t ds1len, ds2len, i; int ret; ret = dsstringprep(ds1, &ds1lp, &ds1len); if (ret) return ret; ret = dsstringprep(ds2, &ds2lp, &ds2len); if (ret) { free(ds1lp); return ret; } if (ds1len != ds2len) *diff = ds1len - ds2len; else { for (i = 0; i < ds1len; i++) { *diff = ds1lp[i] - ds2lp[i]; if (*diff) break; } } free(ds1lp); free(ds2lp); return 0; } int _hx509_name_cmp(const Name *n1, const Name *n2, int *c) { int ret; size_t i, j; *c = n1->u.rdnSequence.len - n2->u.rdnSequence.len; if (*c) return 0; for (i = 0 ; i < n1->u.rdnSequence.len; i++) { *c = n1->u.rdnSequence.val[i].len - n2->u.rdnSequence.val[i].len; if (*c) return 0; for (j = 0; j < n1->u.rdnSequence.val[i].len; j++) { *c = der_heim_oid_cmp(&n1->u.rdnSequence.val[i].val[j].type, &n1->u.rdnSequence.val[i].val[j].type); if (*c) return 0; ret = _hx509_name_ds_cmp(&n1->u.rdnSequence.val[i].val[j].value, &n2->u.rdnSequence.val[i].val[j].value, c); if (ret) return ret; if (*c) return 0; } } *c = 0; return 0; } /** * Compare to hx509 name object, useful for sorting. * * @param n1 a hx509 name object. * @param n2 a hx509 name object. * * @return 0 the objects are the same, returns > 0 is n2 is "larger" * then n2, < 0 if n1 is "smaller" then n2. * * @ingroup hx509_name */ int hx509_name_cmp(hx509_name n1, hx509_name n2) { int ret, diff; ret = _hx509_name_cmp(&n1->der_name, &n2->der_name, &diff); if (ret) return ret; return diff; } int _hx509_name_from_Name(const Name *n, hx509_name *name) { int ret; *name = calloc(1, sizeof(**name)); if (*name == NULL) return ENOMEM; ret = copy_Name(n, &(*name)->der_name); if (ret) { free(*name); *name = NULL; } return ret; } int _hx509_name_modify(hx509_context context, Name *name, int append, const heim_oid *oid, const char *str) { RelativeDistinguishedName *rdn; int ret; void *ptr; ptr = realloc(name->u.rdnSequence.val, sizeof(name->u.rdnSequence.val[0]) * (name->u.rdnSequence.len + 1)); if (ptr == NULL) { hx509_set_error_string(context, 0, ENOMEM, "Out of memory"); return ENOMEM; } name->u.rdnSequence.val = ptr; if (append) { rdn = &name->u.rdnSequence.val[name->u.rdnSequence.len]; } else { memmove(&name->u.rdnSequence.val[1], &name->u.rdnSequence.val[0], name->u.rdnSequence.len * sizeof(name->u.rdnSequence.val[0])); rdn = &name->u.rdnSequence.val[0]; } rdn->val = malloc(sizeof(rdn->val[0])); if (rdn->val == NULL) return ENOMEM; rdn->len = 1; ret = der_copy_oid(oid, &rdn->val[0].type); if (ret) return ret; rdn->val[0].value.element = choice_DirectoryString_utf8String; rdn->val[0].value.u.utf8String = strdup(str); if (rdn->val[0].value.u.utf8String == NULL) return ENOMEM; name->u.rdnSequence.len += 1; return 0; } /** * Parse a string into a hx509 name object. * * @param context A hx509 context. * @param str a string to parse. * @param name the resulting object, NULL in case of error. * * @return An hx509 error code, see hx509_get_error_string(). * * @ingroup hx509_name */ int hx509_parse_name(hx509_context context, const char *str, hx509_name *name) { const char *p, *q; size_t len; hx509_name n; int ret; *name = NULL; n = calloc(1, sizeof(*n)); if (n == NULL) { hx509_set_error_string(context, 0, ENOMEM, "out of memory"); return ENOMEM; } n->der_name.element = choice_Name_rdnSequence; p = str; while (p != NULL && *p != '\0') { heim_oid oid; int last; q = strchr(p, ','); if (q) { len = (q - p); last = 1; } else { len = strlen(p); last = 0; } q = strchr(p, '='); if (q == NULL) { ret = HX509_PARSING_NAME_FAILED; hx509_set_error_string(context, 0, ret, "missing = in %s", p); goto out; } if (q == p) { ret = HX509_PARSING_NAME_FAILED; hx509_set_error_string(context, 0, ret, "missing name before = in %s", p); goto out; } if ((size_t)(q - p) > len) { ret = HX509_PARSING_NAME_FAILED; hx509_set_error_string(context, 0, ret, " = after , in %s", p); goto out; } ret = stringtooid(p, q - p, &oid); if (ret) { ret = HX509_PARSING_NAME_FAILED; hx509_set_error_string(context, 0, ret, "unknown type: %.*s", (int)(q - p), p); goto out; } { size_t pstr_len = len - (q - p) - 1; const char *pstr = p + (q - p) + 1; char *r; r = malloc(pstr_len + 1); if (r == NULL) { der_free_oid(&oid); ret = ENOMEM; hx509_set_error_string(context, 0, ret, "out of memory"); goto out; } memcpy(r, pstr, pstr_len); r[pstr_len] = '\0'; ret = _hx509_name_modify(context, &n->der_name, 0, &oid, r); free(r); der_free_oid(&oid); if(ret) goto out; } p += len + last; } *name = n; return 0; out: hx509_name_free(&n); return HX509_NAME_MALFORMED; } /** * Copy a hx509 name object. * * @param context A hx509 cotext. * @param from the name to copy from * @param to the name to copy to * * @return An hx509 error code, see hx509_get_error_string(). * * @ingroup hx509_name */ int hx509_name_copy(hx509_context context, const hx509_name from, hx509_name *to) { int ret; *to = calloc(1, sizeof(**to)); if (*to == NULL) return ENOMEM; ret = copy_Name(&from->der_name, &(*to)->der_name); if (ret) { free(*to); *to = NULL; return ENOMEM; } return 0; } /** * Convert a hx509_name into a Name. * * @param from the name to copy from * @param to the name to copy to * * @return An hx509 error code, see hx509_get_error_string(). * * @ingroup hx509_name */ int hx509_name_to_Name(const hx509_name from, Name *to) { return copy_Name(&from->der_name, to); } int hx509_name_normalize(hx509_context context, hx509_name name) { return 0; } /** * Expands variables in the name using env. Variables are on the form * ${name}. Useful when dealing with certificate templates. * * @param context A hx509 cotext. * @param name the name to expand. * @param env environment variable to expand. * * @return An hx509 error code, see hx509_get_error_string(). * * @ingroup hx509_name */ int hx509_name_expand(hx509_context context, hx509_name name, hx509_env env) { Name *n = &name->der_name; size_t i, j; if (env == NULL) return 0; if (n->element != choice_Name_rdnSequence) { hx509_set_error_string(context, 0, EINVAL, "RDN not of supported type"); return EINVAL; } for (i = 0 ; i < n->u.rdnSequence.len; i++) { for (j = 0; j < n->u.rdnSequence.val[i].len; j++) { /** Only UTF8String rdnSequence names are allowed */ /* THIS SHOULD REALLY BE: COMP = n->u.rdnSequence.val[i].val[j]; normalize COMP to utf8 check if there are variables expand variables convert back to orignal format, store in COMP free normalized utf8 string */ DirectoryString *ds = &n->u.rdnSequence.val[i].val[j].value; char *p, *p2; struct rk_strpool *strpool = NULL; if (ds->element != choice_DirectoryString_utf8String) { hx509_set_error_string(context, 0, EINVAL, "unsupported type"); return EINVAL; } p = strstr(ds->u.utf8String, "${"); if (p) { strpool = rk_strpoolprintf(strpool, "%.*s", (int)(p - ds->u.utf8String), ds->u.utf8String); if (strpool == NULL) { hx509_set_error_string(context, 0, ENOMEM, "out of memory"); return ENOMEM; } } while (p != NULL) { /* expand variables */ const char *value; p2 = strchr(p, '}'); if (p2 == NULL) { hx509_set_error_string(context, 0, EINVAL, "missing }"); rk_strpoolfree(strpool); return EINVAL; } p += 2; value = hx509_env_lfind(context, env, p, p2 - p); if (value == NULL) { hx509_set_error_string(context, 0, EINVAL, "variable %.*s missing", (int)(p2 - p), p); rk_strpoolfree(strpool); return EINVAL; } strpool = rk_strpoolprintf(strpool, "%s", value); if (strpool == NULL) { hx509_set_error_string(context, 0, ENOMEM, "out of memory"); return ENOMEM; } p2++; p = strstr(p2, "${"); if (p) strpool = rk_strpoolprintf(strpool, "%.*s", (int)(p - p2), p2); else strpool = rk_strpoolprintf(strpool, "%s", p2); if (strpool == NULL) { hx509_set_error_string(context, 0, ENOMEM, "out of memory"); return ENOMEM; } } if (strpool) { free(ds->u.utf8String); ds->u.utf8String = rk_strpoolcollect(strpool); if (ds->u.utf8String == NULL) { hx509_set_error_string(context, 0, ENOMEM, "out of memory"); return ENOMEM; } } } } return 0; } /** * Free a hx509 name object, upond return *name will be NULL. * * @param name a hx509 name object to be freed. * * @ingroup hx509_name */ void hx509_name_free(hx509_name *name) { free_Name(&(*name)->der_name); memset(*name, 0, sizeof(**name)); free(*name); *name = NULL; } /** * Convert a DER encoded name info a string. * * @param data data to a DER/BER encoded name * @param length length of data * @param str the resulting string, is NULL on failure. * * @return An hx509 error code, see hx509_get_error_string(). * * @ingroup hx509_name */ int hx509_unparse_der_name(const void *data, size_t length, char **str) { Name name; int ret; *str = NULL; ret = decode_Name(data, length, &name, NULL); if (ret) return ret; ret = _hx509_Name_to_string(&name, str); free_Name(&name); return ret; } /** * Convert a hx509_name object to DER encoded name. * * @param name name to concert * @param os data to a DER encoded name, free the resulting octet * string with hx509_xfree(os->data). * * @return An hx509 error code, see hx509_get_error_string(). * * @ingroup hx509_name */ int hx509_name_binary(const hx509_name name, heim_octet_string *os) { size_t size; int ret; ASN1_MALLOC_ENCODE(Name, os->data, os->length, &name->der_name, &size, ret); if (ret) return ret; if (os->length != size) _hx509_abort("internal ASN.1 encoder error"); return 0; } int _hx509_unparse_Name(const Name *aname, char **str) { hx509_name name; int ret; ret = _hx509_name_from_Name(aname, &name); if (ret) return ret; ret = hx509_name_to_string(name, str); hx509_name_free(&name); return ret; } /** * Unparse the hx509 name in name into a string. * * @param name the name to check if its empty/null. * * @return non zero if the name is empty/null. * * @ingroup hx509_name */ int hx509_name_is_null_p(const hx509_name name) { return name->der_name.u.rdnSequence.len == 0; } /** * Unparse the hx509 name in name into a string. * * @param name the name to print * @param str an allocated string returns the name in string form * * @return An hx509 error code, see hx509_get_error_string(). * * @ingroup hx509_name */ int hx509_general_name_unparse(GeneralName *name, char **str) { struct rk_strpool *strpool = NULL; *str = NULL; switch (name->element) { case choice_GeneralName_otherName: { char *oid; hx509_oid_sprint(&name->u.otherName.type_id, &oid); if (oid == NULL) return ENOMEM; strpool = rk_strpoolprintf(strpool, "otherName: %s", oid); free(oid); break; } case choice_GeneralName_rfc822Name: strpool = rk_strpoolprintf(strpool, "rfc822Name: %.*s\n", (int)name->u.rfc822Name.length, (char *)name->u.rfc822Name.data); break; case choice_GeneralName_dNSName: strpool = rk_strpoolprintf(strpool, "dNSName: %.*s\n", (int)name->u.dNSName.length, (char *)name->u.dNSName.data); break; case choice_GeneralName_directoryName: { Name dir; char *s; int ret; memset(&dir, 0, sizeof(dir)); dir.element = (enum Name_enum)name->u.directoryName.element; dir.u.rdnSequence = name->u.directoryName.u.rdnSequence; ret = _hx509_unparse_Name(&dir, &s); if (ret) return ret; strpool = rk_strpoolprintf(strpool, "directoryName: %s", s); free(s); break; } case choice_GeneralName_uniformResourceIdentifier: strpool = rk_strpoolprintf(strpool, "URI: %.*s", (int)name->u.uniformResourceIdentifier.length, (char *)name->u.uniformResourceIdentifier.data); break; case choice_GeneralName_iPAddress: { unsigned char *a = name->u.iPAddress.data; strpool = rk_strpoolprintf(strpool, "IPAddress: "); if (strpool == NULL) break; if (name->u.iPAddress.length == 4) strpool = rk_strpoolprintf(strpool, "%d.%d.%d.%d", a[0], a[1], a[2], a[3]); else if (name->u.iPAddress.length == 16) strpool = rk_strpoolprintf(strpool, "%02X:%02X:%02X:%02X:" "%02X:%02X:%02X:%02X:" "%02X:%02X:%02X:%02X:" "%02X:%02X:%02X:%02X", a[0], a[1], a[2], a[3], a[4], a[5], a[6], a[7], a[8], a[9], a[10], a[11], a[12], a[13], a[14], a[15]); else strpool = rk_strpoolprintf(strpool, "unknown IP address of length %lu", (unsigned long)name->u.iPAddress.length); break; } case choice_GeneralName_registeredID: { char *oid; hx509_oid_sprint(&name->u.registeredID, &oid); if (oid == NULL) return ENOMEM; strpool = rk_strpoolprintf(strpool, "registeredID: %s", oid); free(oid); break; } default: return EINVAL; } if (strpool == NULL) return ENOMEM; *str = rk_strpoolcollect(strpool); return 0; } heimdal-7.5.0/lib/hx509/hxtool.c0000644000175000017500000015404313212137553014367 0ustar niknik/* * Copyright (c) 2004 - 2016 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "hx_locl.h" #include #include #include #include static hx509_context context; static char *stat_file_string; static int version_flag; static int help_flag; struct getargs args[] = { { "statistic-file", 0, arg_string, &stat_file_string, NULL, NULL }, { "version", 0, arg_flag, &version_flag, NULL, NULL }, { "help", 0, arg_flag, &help_flag, NULL, NULL } }; int num_args = sizeof(args) / sizeof(args[0]); static void usage(int code) { arg_printusage(args, num_args, NULL, "command"); printf("Use \"%s help\" to get more help\n", getprogname()); exit(code); } /* * */ static void lock_strings(hx509_lock lock, getarg_strings *pass) { int i; for (i = 0; i < pass->num_strings; i++) { int ret = hx509_lock_command_string(lock, pass->strings[i]); if (ret) errx(1, "hx509_lock_command_string: %s: %d", pass->strings[i], ret); } } /* * */ static void certs_strings(hx509_context contextp, const char *type, hx509_certs certs, hx509_lock lock, const getarg_strings *s) { int i, ret; for (i = 0; i < s->num_strings; i++) { ret = hx509_certs_append(contextp, certs, lock, s->strings[i]); if (ret) hx509_err(contextp, 1, ret, "hx509_certs_append: %s %s", type, s->strings[i]); } } /* * */ static void parse_oid(const char *str, const heim_oid *def, heim_oid *oid) { int ret; if (str) ret = der_parse_heim_oid (str, " .", oid); else ret = der_copy_oid(def, oid); if (ret) errx(1, "parse_oid failed for: %s", str ? str : "default oid"); } /* * */ static void peer_strings(hx509_context contextp, hx509_peer_info *peer, const getarg_strings *s) { AlgorithmIdentifier *val; int ret, i; ret = hx509_peer_info_alloc(contextp, peer); if (ret) hx509_err(contextp, 1, ret, "hx509_peer_info_alloc"); val = calloc(s->num_strings, sizeof(*val)); if (val == NULL) err(1, "malloc"); for (i = 0; i < s->num_strings; i++) parse_oid(s->strings[i], NULL, &val[i].algorithm); ret = hx509_peer_info_set_cms_algs(contextp, *peer, val, s->num_strings); if (ret) hx509_err(contextp, 1, ret, "hx509_peer_info_set_cms_algs"); for (i = 0; i < s->num_strings; i++) free_AlgorithmIdentifier(&val[i]); free(val); } /* * */ struct pem_data { heim_octet_string *os; int detached_data; }; static int pem_reader(hx509_context contextp, const char *type, const hx509_pem_header *headers, const void *data , size_t length, void *ctx) { struct pem_data *p = (struct pem_data *)ctx; const char *h; p->os->data = malloc(length); if (p->os->data == NULL) return ENOMEM; memcpy(p->os->data, data, length); p->os->length = length; h = hx509_pem_find_header(headers, "Content-disposition"); if (h && strcasecmp(h, "detached") == 0) p->detached_data = 1; return 0; } /* * */ int cms_verify_sd(struct cms_verify_sd_options *opt, int argc, char **argv) { hx509_verify_ctx ctx = NULL; heim_oid type; heim_octet_string c, co, signeddata, *sd = NULL; hx509_certs store = NULL; hx509_certs signers = NULL; hx509_certs anchors = NULL; hx509_lock lock; int ret, flags = 0; size_t sz; void *p = NULL; if (opt->missing_revoke_flag) hx509_context_set_missing_revoke(context, 1); hx509_lock_init(context, &lock); lock_strings(lock, &opt->pass_strings); ret = hx509_verify_init_ctx(context, &ctx); if (ret) hx509_err(context, 1, ret, "hx509_verify_init_ctx"); ret = hx509_certs_init(context, "MEMORY:cms-anchors", 0, NULL, &anchors); if (ret) hx509_err(context, 1, ret, "hx509_certs_init: MEMORY"); ret = hx509_certs_init(context, "MEMORY:cert-store", 0, NULL, &store); if (ret) hx509_err(context, 1, ret, "hx509_certs_init: MEMORY"); certs_strings(context, "anchors", anchors, lock, &opt->anchors_strings); certs_strings(context, "store", store, lock, &opt->certificate_strings); if (opt->pem_flag) { struct pem_data pd; FILE *f; pd.os = &co; pd.detached_data = 0; f = fopen(argv[0], "r"); if (f == NULL) err(1, "Failed to open file %s", argv[0]); ret = hx509_pem_read(context, f, pem_reader, &pd); fclose(f); if (ret) errx(1, "PEM reader failed: %d", ret); if (pd.detached_data && opt->signed_content_string == NULL) { char *r = strrchr(argv[0], '.'); if (r && strcasecmp(r, ".pem") == 0) { char *s = strdup(argv[0]); if (s == NULL) errx(1, "malloc: out of memory"); s[r - argv[0]] = '\0'; ret = _hx509_map_file_os(s, &signeddata); if (ret) errx(1, "map_file: %s: %d", s, ret); free(s); sd = &signeddata; } } } else { ret = rk_undumpdata(argv[0], &p, &sz); if (ret) err(1, "map_file: %s: %d", argv[0], ret); co.data = p; co.length = sz; } if (opt->signed_content_string) { ret = _hx509_map_file_os(opt->signed_content_string, &signeddata); if (ret) errx(1, "map_file: %s: %d", opt->signed_content_string, ret); sd = &signeddata; } if (opt->content_info_flag) { heim_octet_string uwco; heim_oid oid; ret = hx509_cms_unwrap_ContentInfo(&co, &oid, &uwco, NULL); if (ret) errx(1, "hx509_cms_unwrap_ContentInfo: %d", ret); if (der_heim_oid_cmp(&oid, &asn1_oid_id_pkcs7_signedData) != 0) errx(1, "Content is not SignedData"); der_free_oid(&oid); if (p == NULL) der_free_octet_string(&co); else { rk_xfree(p); p = NULL; } co = uwco; } hx509_verify_attach_anchors(ctx, anchors); if (!opt->signer_allowed_flag) flags |= HX509_CMS_VS_ALLOW_ZERO_SIGNER; if (opt->allow_wrong_oid_flag) flags |= HX509_CMS_VS_ALLOW_DATA_OID_MISMATCH; ret = hx509_cms_verify_signed(context, ctx, flags, co.data, co.length, sd, store, &type, &c, &signers); if (p != co.data) der_free_octet_string(&co); else rk_xfree(p); if (ret) hx509_err(context, 1, ret, "hx509_cms_verify_signed"); { char *str; der_print_heim_oid(&type, '.', &str); printf("type: %s\n", str); free(str); der_free_oid(&type); } if (signers == NULL) { printf("unsigned\n"); } else { printf("signers:\n"); hx509_certs_iter_f(context, signers, hx509_ci_print_names, stdout); } hx509_verify_destroy_ctx(ctx); hx509_certs_free(&store); hx509_certs_free(&signers); hx509_certs_free(&anchors); hx509_lock_free(lock); if (argc > 1) { ret = _hx509_write_file(argv[1], c.data, c.length); if (ret) errx(1, "hx509_write_file: %d", ret); } der_free_octet_string(&c); if (sd) _hx509_unmap_file_os(sd); return 0; } static int print_signer(hx509_context contextp, void *ctx, hx509_cert cert) { hx509_pem_header **header = ctx; char *signer_name = NULL; hx509_name name; int ret; ret = hx509_cert_get_subject(cert, &name); if (ret) errx(1, "hx509_cert_get_subject"); ret = hx509_name_to_string(name, &signer_name); hx509_name_free(&name); if (ret) errx(1, "hx509_name_to_string"); hx509_pem_add_header(header, "Signer", signer_name); free(signer_name); return 0; } int cms_create_sd(struct cms_create_sd_options *opt, int argc, char **argv) { heim_oid contentType; hx509_peer_info peer = NULL; heim_octet_string o; hx509_query *q; hx509_lock lock; hx509_certs store, pool, anchors, signer = NULL; size_t sz; void *p; int ret, flags = 0; char *infile, *outfile = NULL; memset(&contentType, 0, sizeof(contentType)); infile = argv[0]; if (argc < 2) { ret = asprintf(&outfile, "%s.%s", infile, opt->pem_flag ? "pem" : "cms-signeddata"); if (ret == -1 || outfile == NULL) errx(1, "out of memory"); } else outfile = argv[1]; hx509_lock_init(context, &lock); lock_strings(lock, &opt->pass_strings); ret = hx509_certs_init(context, "MEMORY:cert-store", 0, NULL, &store); if (ret) hx509_err(context, 1, ret, "hx509_certs_init: MEMORY"); ret = hx509_certs_init(context, "MEMORY:cert-pool", 0, NULL, &pool); if (ret) hx509_err(context, 1, ret, "hx509_certs_init: MEMORY"); certs_strings(context, "store", store, lock, &opt->certificate_strings); certs_strings(context, "pool", pool, lock, &opt->pool_strings); if (opt->anchors_strings.num_strings) { ret = hx509_certs_init(context, "MEMORY:cert-anchors", 0, NULL, &anchors); if (ret) hx509_err(context, 1, ret, "hx509_certs_init: MEMORY"); certs_strings(context, "anchors", anchors, lock, &opt->anchors_strings); } else anchors = NULL; if (opt->detached_signature_flag) flags |= HX509_CMS_SIGNATURE_DETACHED; if (opt->id_by_name_flag) flags |= HX509_CMS_SIGNATURE_ID_NAME; if (!opt->signer_flag) { flags |= HX509_CMS_SIGNATURE_NO_SIGNER; } if (opt->signer_flag) { ret = hx509_query_alloc(context, &q); if (ret) errx(1, "hx509_query_alloc: %d", ret); hx509_query_match_option(q, HX509_QUERY_OPTION_PRIVATE_KEY); hx509_query_match_option(q, HX509_QUERY_OPTION_KU_DIGITALSIGNATURE); if (opt->signer_string) hx509_query_match_friendly_name(q, opt->signer_string); ret = hx509_certs_filter(context, store, q, &signer); hx509_query_free(context, q); if (ret) hx509_err(context, 1, ret, "hx509_certs_find"); } if (!opt->embedded_certs_flag) flags |= HX509_CMS_SIGNATURE_NO_CERTS; if (opt->embed_leaf_only_flag) flags |= HX509_CMS_SIGNATURE_LEAF_ONLY; ret = rk_undumpdata(infile, &p, &sz); if (ret) err(1, "map_file: %s: %d", infile, ret); if (opt->peer_alg_strings.num_strings) peer_strings(context, &peer, &opt->peer_alg_strings); parse_oid(opt->content_type_string, &asn1_oid_id_pkcs7_data, &contentType); ret = hx509_cms_create_signed(context, flags, &contentType, p, sz, NULL, signer, peer, anchors, pool, &o); if (ret) hx509_err(context, 1, ret, "hx509_cms_create_signed: %d", ret); hx509_certs_free(&anchors); hx509_certs_free(&pool); hx509_certs_free(&store); rk_xfree(p); hx509_lock_free(lock); hx509_peer_info_free(peer); der_free_oid(&contentType); if (opt->content_info_flag) { heim_octet_string wo; ret = hx509_cms_wrap_ContentInfo(&asn1_oid_id_pkcs7_signedData, &o, &wo); if (ret) errx(1, "hx509_cms_wrap_ContentInfo: %d", ret); der_free_octet_string(&o); o = wo; } if (opt->pem_flag) { hx509_pem_header *header = NULL; FILE *f; hx509_pem_add_header(&header, "Content-disposition", opt->detached_signature_flag ? "detached" : "inline"); if (signer) { ret = hx509_certs_iter_f(context, signer, print_signer, header); if (ret) hx509_err(context, 1, ret, "print signer"); } f = fopen(outfile, "w"); if (f == NULL) err(1, "open %s", outfile); ret = hx509_pem_write(context, "CMS SIGNEDDATA", header, f, o.data, o.length); fclose(f); hx509_pem_free_header(header); if (ret) errx(1, "hx509_pem_write: %d", ret); } else { ret = _hx509_write_file(outfile, o.data, o.length); if (ret) errx(1, "hx509_write_file: %d", ret); } hx509_certs_free(&signer); free(o.data); return 0; } int cms_unenvelope(struct cms_unenvelope_options *opt, int argc, char **argv) { heim_oid contentType = { 0, NULL }; heim_octet_string o, co; hx509_certs certs; size_t sz; void *p; int ret; hx509_lock lock; int flags = 0; hx509_lock_init(context, &lock); lock_strings(lock, &opt->pass_strings); ret = rk_undumpdata(argv[0], &p, &sz); if (ret) err(1, "map_file: %s: %d", argv[0], ret); co.data = p; co.length = sz; if (opt->content_info_flag) { heim_octet_string uwco; heim_oid oid; ret = hx509_cms_unwrap_ContentInfo(&co, &oid, &uwco, NULL); if (ret) errx(1, "hx509_cms_unwrap_ContentInfo: %d", ret); if (der_heim_oid_cmp(&oid, &asn1_oid_id_pkcs7_envelopedData) != 0) errx(1, "Content is not SignedData"); der_free_oid(&oid); co = uwco; } ret = hx509_certs_init(context, "MEMORY:cert-store", 0, NULL, &certs); if (ret) errx(1, "hx509_certs_init: MEMORY: %d", ret); certs_strings(context, "store", certs, lock, &opt->certificate_strings); if (opt->allow_weak_crypto_flag) flags |= HX509_CMS_UE_ALLOW_WEAK; ret = hx509_cms_unenvelope(context, certs, flags, co.data, co.length, NULL, 0, &contentType, &o); if (co.data != p) der_free_octet_string(&co); if (ret) hx509_err(context, 1, ret, "hx509_cms_unenvelope"); rk_xfree(p); hx509_lock_free(lock); hx509_certs_free(&certs); der_free_oid(&contentType); ret = _hx509_write_file(argv[1], o.data, o.length); if (ret) errx(1, "hx509_write_file: %d", ret); der_free_octet_string(&o); return 0; } int cms_create_enveloped(struct cms_envelope_options *opt, int argc, char **argv) { heim_oid contentType; heim_octet_string o; const heim_oid *enctype = NULL; hx509_query *q; hx509_certs certs; hx509_cert cert; int ret; size_t sz; void *p; hx509_lock lock; int flags = 0; memset(&contentType, 0, sizeof(contentType)); hx509_lock_init(context, &lock); lock_strings(lock, &opt->pass_strings); ret = rk_undumpdata(argv[0], &p, &sz); if (ret) err(1, "map_file: %s: %d", argv[0], ret); ret = hx509_certs_init(context, "MEMORY:cert-store", 0, NULL, &certs); if (ret) hx509_err(context, 1, ret, "hx509_certs_init: MEMORY"); certs_strings(context, "store", certs, lock, &opt->certificate_strings); if (opt->allow_weak_crypto_flag) flags |= HX509_CMS_EV_ALLOW_WEAK; if (opt->encryption_type_string) { enctype = hx509_crypto_enctype_by_name(opt->encryption_type_string); if (enctype == NULL) errx(1, "encryption type: %s no found", opt->encryption_type_string); } ret = hx509_query_alloc(context, &q); if (ret) errx(1, "hx509_query_alloc: %d", ret); hx509_query_match_option(q, HX509_QUERY_OPTION_KU_ENCIPHERMENT); ret = hx509_certs_find(context, certs, q, &cert); hx509_query_free(context, q); if (ret) errx(1, "hx509_certs_find: %d", ret); parse_oid(opt->content_type_string, &asn1_oid_id_pkcs7_data, &contentType); ret = hx509_cms_envelope_1(context, flags, cert, p, sz, enctype, &contentType, &o); if (ret) errx(1, "hx509_cms_envelope_1: %d", ret); hx509_cert_free(cert); hx509_certs_free(&certs); rk_xfree(p); der_free_oid(&contentType); if (opt->content_info_flag) { heim_octet_string wo; ret = hx509_cms_wrap_ContentInfo(&asn1_oid_id_pkcs7_envelopedData, &o, &wo); if (ret) errx(1, "hx509_cms_wrap_ContentInfo: %d", ret); der_free_octet_string(&o); o = wo; } hx509_lock_free(lock); ret = _hx509_write_file(argv[1], o.data, o.length); if (ret) errx(1, "hx509_write_file: %d", ret); der_free_octet_string(&o); return 0; } static void print_certificate(hx509_context hxcontext, hx509_cert cert, int verbose) { const char *fn; int ret; fn = hx509_cert_get_friendly_name(cert); if (fn) printf(" friendly name: %s\n", fn); printf(" private key: %s\n", _hx509_cert_private_key(cert) ? "yes" : "no"); ret = hx509_print_cert(hxcontext, cert, NULL); if (ret) errx(1, "failed to print cert"); if (verbose) { hx509_validate_ctx vctx; hx509_validate_ctx_init(hxcontext, &vctx); hx509_validate_ctx_set_print(vctx, hx509_print_stdout, stdout); hx509_validate_ctx_add_flags(vctx, HX509_VALIDATE_F_VALIDATE); hx509_validate_ctx_add_flags(vctx, HX509_VALIDATE_F_VERBOSE); hx509_validate_cert(hxcontext, vctx, cert); hx509_validate_ctx_free(vctx); } } struct print_s { int counter; int verbose; }; static int print_f(hx509_context hxcontext, void *ctx, hx509_cert cert) { struct print_s *s = ctx; printf("cert: %d\n", s->counter++); print_certificate(context, cert, s->verbose); return 0; } int pcert_print(struct print_options *opt, int argc, char **argv) { hx509_certs certs; hx509_lock lock; struct print_s s; s.counter = 0; s.verbose = opt->content_flag; hx509_lock_init(context, &lock); lock_strings(lock, &opt->pass_strings); while(argc--) { int ret; ret = hx509_certs_init(context, argv[0], 0, lock, &certs); if (ret) { if (opt->never_fail_flag) { printf("ignoreing failure: %d\n", ret); continue; } hx509_err(context, 1, ret, "hx509_certs_init"); } if (opt->info_flag) hx509_certs_info(context, certs, NULL, NULL); hx509_certs_iter_f(context, certs, print_f, &s); hx509_certs_free(&certs); argv++; } hx509_lock_free(lock); return 0; } static int validate_f(hx509_context hxcontext, void *ctx, hx509_cert c) { hx509_validate_cert(hxcontext, ctx, c); return 0; } int pcert_validate(struct validate_options *opt, int argc, char **argv) { hx509_validate_ctx ctx; hx509_certs certs; hx509_lock lock; hx509_lock_init(context, &lock); lock_strings(lock, &opt->pass_strings); hx509_validate_ctx_init(context, &ctx); hx509_validate_ctx_set_print(ctx, hx509_print_stdout, stdout); hx509_validate_ctx_add_flags(ctx, HX509_VALIDATE_F_VALIDATE); while(argc--) { int ret; ret = hx509_certs_init(context, argv[0], 0, lock, &certs); if (ret) errx(1, "hx509_certs_init: %d", ret); hx509_certs_iter_f(context, certs, validate_f, ctx); hx509_certs_free(&certs); argv++; } hx509_validate_ctx_free(ctx); hx509_lock_free(lock); return 0; } int certificate_copy(struct certificate_copy_options *opt, int argc, char **argv) { hx509_certs certs; hx509_lock inlock, outlock = NULL; int ret; hx509_lock_init(context, &inlock); lock_strings(inlock, &opt->in_pass_strings); if (opt->out_pass_string) { hx509_lock_init(context, &outlock); ret = hx509_lock_command_string(outlock, opt->out_pass_string); if (ret) errx(1, "hx509_lock_command_string: %s: %d", opt->out_pass_string, ret); } ret = hx509_certs_init(context, argv[argc - 1], HX509_CERTS_CREATE, inlock, &certs); if (ret) hx509_err(context, 1, ret, "hx509_certs_init"); while(argc-- > 1) { int retx; retx = hx509_certs_append(context, certs, inlock, argv[0]); if (retx) hx509_err(context, 1, retx, "hx509_certs_append"); argv++; } ret = hx509_certs_store(context, certs, 0, outlock); if (ret) hx509_err(context, 1, ret, "hx509_certs_store"); hx509_certs_free(&certs); hx509_lock_free(inlock); hx509_lock_free(outlock); return 0; } struct verify { hx509_verify_ctx ctx; hx509_certs chain; const char *hostname; int errors; int count; }; static int verify_f(hx509_context hxcontext, void *ctx, hx509_cert c) { struct verify *v = ctx; int ret; ret = hx509_verify_path(hxcontext, v->ctx, c, v->chain); if (ret) { char *s = hx509_get_error_string(hxcontext, ret); printf("verify_path: %s: %d\n", s, ret); hx509_free_error_string(s); v->errors++; } else { v->count++; printf("path ok\n"); } if (v->hostname) { ret = hx509_verify_hostname(hxcontext, c, 0, HX509_HN_HOSTNAME, v->hostname, NULL, 0); if (ret) { printf("verify_hostname: %d\n", ret); v->errors++; } } return 0; } int pcert_verify(struct verify_options *opt, int argc, char **argv) { hx509_certs anchors, chain, certs; hx509_revoke_ctx revoke_ctx; hx509_verify_ctx ctx; struct verify v; int ret; memset(&v, 0, sizeof(v)); if (opt->missing_revoke_flag) hx509_context_set_missing_revoke(context, 1); ret = hx509_verify_init_ctx(context, &ctx); if (ret) hx509_err(context, 1, ret, "hx509_verify_init_ctx"); ret = hx509_certs_init(context, "MEMORY:anchors", 0, NULL, &anchors); if (ret) hx509_err(context, 1, ret, "hx509_certs_init: MEMORY"); ret = hx509_certs_init(context, "MEMORY:chain", 0, NULL, &chain); if (ret) hx509_err(context, 1, ret, "hx509_certs_init: MEMORY"); ret = hx509_certs_init(context, "MEMORY:certs", 0, NULL, &certs); if (ret) hx509_err(context, 1, ret, "hx509_certs_init: MEMORY"); if (opt->allow_proxy_certificate_flag) hx509_verify_set_proxy_certificate(ctx, 1); if (opt->time_string) { const char *p; struct tm tm; time_t t; memset(&tm, 0, sizeof(tm)); p = strptime (opt->time_string, "%Y-%m-%d", &tm); if (p == NULL) errx(1, "Failed to parse time %s, need to be on format %%Y-%%m-%%d", opt->time_string); t = tm2time (tm, 0); hx509_verify_set_time(ctx, t); } if (opt->hostname_string) v.hostname = opt->hostname_string; if (opt->max_depth_integer) hx509_verify_set_max_depth(ctx, opt->max_depth_integer); ret = hx509_revoke_init(context, &revoke_ctx); if (ret) errx(1, "hx509_revoke_init: %d", ret); while(argc--) { char *s = *argv++; if (strncmp(s, "chain:", 6) == 0) { s += 6; ret = hx509_certs_append(context, chain, NULL, s); if (ret) hx509_err(context, 1, ret, "hx509_certs_append: chain: %s: %d", s, ret); } else if (strncmp(s, "anchor:", 7) == 0) { s += 7; ret = hx509_certs_append(context, anchors, NULL, s); if (ret) hx509_err(context, 1, ret, "hx509_certs_append: anchor: %s: %d", s, ret); } else if (strncmp(s, "cert:", 5) == 0) { s += 5; ret = hx509_certs_append(context, certs, NULL, s); if (ret) hx509_err(context, 1, ret, "hx509_certs_append: certs: %s: %d", s, ret); } else if (strncmp(s, "crl:", 4) == 0) { s += 4; ret = hx509_revoke_add_crl(context, revoke_ctx, s); if (ret) errx(1, "hx509_revoke_add_crl: %s: %d", s, ret); } else if (strncmp(s, "ocsp:", 4) == 0) { s += 5; ret = hx509_revoke_add_ocsp(context, revoke_ctx, s); if (ret) errx(1, "hx509_revoke_add_ocsp: %s: %d", s, ret); } else { errx(1, "unknown option to verify: `%s'\n", s); } } hx509_verify_attach_anchors(ctx, anchors); hx509_verify_attach_revoke(ctx, revoke_ctx); v.ctx = ctx; v.chain = chain; hx509_certs_iter_f(context, certs, verify_f, &v); hx509_verify_destroy_ctx(ctx); hx509_certs_free(&certs); hx509_certs_free(&chain); hx509_certs_free(&anchors); hx509_revoke_free(&revoke_ctx); if (v.count == 0) { printf("no certs verify at all\n"); return 1; } if (v.errors) { printf("failed verifing %d checks\n", v.errors); return 1; } return 0; } int query(struct query_options *opt, int argc, char **argv) { hx509_lock lock; hx509_query *q; hx509_certs certs; hx509_cert c; int ret; ret = hx509_query_alloc(context, &q); if (ret) errx(1, "hx509_query_alloc: %d", ret); hx509_lock_init(context, &lock); lock_strings(lock, &opt->pass_strings); ret = hx509_certs_init(context, "MEMORY:cert-store", 0, NULL, &certs); if (ret) hx509_err(context, 1, ret, "hx509_certs_init: MEMORY"); while (argc > 0) { ret = hx509_certs_append(context, certs, lock, argv[0]); if (ret) errx(1, "hx509_certs_append: %s: %d", argv[0], ret); argc--; argv++; } if (opt->friendlyname_string) hx509_query_match_friendly_name(q, opt->friendlyname_string); if (opt->eku_string) { heim_oid oid; parse_oid(opt->eku_string, NULL, &oid); ret = hx509_query_match_eku(q, &oid); if (ret) errx(1, "hx509_query_match_eku: %d", ret); der_free_oid(&oid); } if (opt->private_key_flag) hx509_query_match_option(q, HX509_QUERY_OPTION_PRIVATE_KEY); if (opt->keyEncipherment_flag) hx509_query_match_option(q, HX509_QUERY_OPTION_KU_ENCIPHERMENT); if (opt->digitalSignature_flag) hx509_query_match_option(q, HX509_QUERY_OPTION_KU_DIGITALSIGNATURE); if (opt->expr_string) hx509_query_match_expr(context, q, opt->expr_string); ret = hx509_certs_find(context, certs, q, &c); hx509_query_free(context, q); if (ret) printf("no match found (%d)\n", ret); else { printf("match found\n"); if (opt->print_flag) print_certificate(context, c, 0); } hx509_cert_free(c); hx509_certs_free(&certs); hx509_lock_free(lock); return ret; } int ocsp_fetch(struct ocsp_fetch_options *opt, int argc, char **argv) { hx509_certs reqcerts, pool; heim_octet_string req, nonce_data, *nonce = &nonce_data; hx509_lock lock; int i, ret; char *file; const char *url = "/"; memset(&nonce, 0, sizeof(nonce)); hx509_lock_init(context, &lock); lock_strings(lock, &opt->pass_strings); /* no nonce */ if (!opt->nonce_flag) nonce = NULL; if (opt->url_path_string) url = opt->url_path_string; ret = hx509_certs_init(context, "MEMORY:ocsp-pool", 0, NULL, &pool); if (ret) hx509_err(context, 1, ret, "hx509_certs_init: MEMORY"); certs_strings(context, "ocsp-pool", pool, lock, &opt->pool_strings); file = argv[0]; ret = hx509_certs_init(context, "MEMORY:ocsp-req", 0, NULL, &reqcerts); if (ret) hx509_err(context, 1, ret, "hx509_certs_init: MEMORY"); for (i = 1; i < argc; i++) { ret = hx509_certs_append(context, reqcerts, lock, argv[i]); if (ret) errx(1, "hx509_certs_append: req: %s: %d", argv[i], ret); } ret = hx509_ocsp_request(context, reqcerts, pool, NULL, NULL, &req, nonce); if (ret) errx(1, "hx509_ocsp_request: req: %d", ret); { FILE *f; f = fopen(file, "w"); if (f == NULL) abort(); fprintf(f, "POST %s HTTP/1.0\r\n" "Content-Type: application/ocsp-request\r\n" "Content-Length: %ld\r\n" "\r\n", url, (unsigned long)req.length); fwrite(req.data, req.length, 1, f); fclose(f); } if (nonce) der_free_octet_string(nonce); hx509_certs_free(&reqcerts); hx509_certs_free(&pool); return 0; } int ocsp_print(struct ocsp_print_options *opt, int argc, char **argv) { hx509_revoke_ocsp_print(context, argv[0], stdout); return 0; } int revoke_print(struct revoke_print_options *opt, int argc, char **argv) { hx509_revoke_ctx revoke_ctx; int ret; ret = hx509_revoke_init(context, &revoke_ctx); if (ret) errx(1, "hx509_revoke_init: %d", ret); while(argc--) { char *s = *argv++; if (strncmp(s, "crl:", 4) == 0) { s += 4; ret = hx509_revoke_add_crl(context, revoke_ctx, s); if (ret) errx(1, "hx509_revoke_add_crl: %s: %d", s, ret); } else if (strncmp(s, "ocsp:", 4) == 0) { s += 5; ret = hx509_revoke_add_ocsp(context, revoke_ctx, s); if (ret) errx(1, "hx509_revoke_add_ocsp: %s: %d", s, ret); } else { errx(1, "unknown option to verify: `%s'\n", s); } } ret = hx509_revoke_print(context, revoke_ctx, stdout); if (ret) warnx("hx509_revoke_print: %d", ret); return ret; } /* * */ static int verify_o(hx509_context hxcontext, void *ctx, hx509_cert c) { heim_octet_string *os = ctx; time_t expiration; int ret; ret = hx509_ocsp_verify(context, 0, c, 0, os->data, os->length, &expiration); if (ret) { char *s = hx509_get_error_string(hxcontext, ret); printf("ocsp_verify: %s: %d\n", s, ret); hx509_free_error_string(s); } else printf("expire: %d\n", (int)expiration); return ret; } int ocsp_verify(struct ocsp_verify_options *opt, int argc, char **argv) { hx509_lock lock; hx509_certs certs; int ret, i; heim_octet_string os; hx509_lock_init(context, &lock); if (opt->ocsp_file_string == NULL) errx(1, "no ocsp file given"); ret = _hx509_map_file_os(opt->ocsp_file_string, &os); if (ret) err(1, "map_file: %s: %d", argv[0], ret); ret = hx509_certs_init(context, "MEMORY:test-certs", 0, NULL, &certs); if (ret) hx509_err(context, 1, ret, "hx509_certs_init: MEMORY"); for (i = 0; i < argc; i++) { ret = hx509_certs_append(context, certs, lock, argv[i]); if (ret) hx509_err(context, 1, ret, "hx509_certs_append: %s", argv[i]); } ret = hx509_certs_iter_f(context, certs, verify_o, &os); hx509_certs_free(&certs); _hx509_unmap_file_os(&os); hx509_lock_free(lock); return ret; } static int read_private_key(const char *fn, hx509_private_key *key) { hx509_private_key *keys; hx509_certs certs; int ret; *key = NULL; ret = hx509_certs_init(context, fn, 0, NULL, &certs); if (ret) hx509_err(context, 1, ret, "hx509_certs_init: %s", fn); ret = _hx509_certs_keys_get(context, certs, &keys); hx509_certs_free(&certs); if (ret) hx509_err(context, 1, ret, "hx509_certs_keys_get"); if (keys[0] == NULL) errx(1, "no keys in key store: %s", fn); *key = _hx509_private_key_ref(keys[0]); _hx509_certs_keys_free(context, keys); return 0; } static void get_key(const char *fn, const char *type, int optbits, hx509_private_key *signer) { int ret; if (type) { BIGNUM *e; RSA *rsa; unsigned char *p0, *p; size_t len; int bits = 1024; if (fn == NULL) errx(1, "no key argument, don't know here to store key"); if (strcasecmp(type, "rsa") != 0) errx(1, "can only handle rsa keys for now"); e = BN_new(); BN_set_word(e, 0x10001); if (optbits) bits = optbits; rsa = RSA_new(); if(rsa == NULL) errx(1, "RSA_new failed"); ret = RSA_generate_key_ex(rsa, bits, e, NULL); if(ret != 1) errx(1, "RSA_new failed"); BN_free(e); len = i2d_RSAPrivateKey(rsa, NULL); p0 = p = malloc(len); if (p == NULL) errx(1, "out of memory"); i2d_RSAPrivateKey(rsa, &p); rk_dumpdata(fn, p0, len); memset(p0, 0, len); free(p0); RSA_free(rsa); } else if (fn == NULL) err(1, "no private key"); ret = read_private_key(fn, signer); if (ret) err(1, "read_private_key"); } int request_create(struct request_create_options *opt, int argc, char **argv) { heim_octet_string request; hx509_request req; int ret, i; hx509_private_key signer; SubjectPublicKeyInfo key; const char *outfile = argv[0]; memset(&key, 0, sizeof(key)); get_key(opt->key_string, opt->generate_key_string, opt->key_bits_integer, &signer); hx509_request_init(context, &req); if (opt->subject_string) { hx509_name name = NULL; ret = hx509_parse_name(context, opt->subject_string, &name); if (ret) errx(1, "hx509_parse_name: %d\n", ret); hx509_request_set_name(context, req, name); if (opt->verbose_flag) { char *s; hx509_name_to_string(name, &s); printf("%s\n", s); } hx509_name_free(&name); } for (i = 0; i < opt->email_strings.num_strings; i++) { ret = _hx509_request_add_email(context, req, opt->email_strings.strings[i]); if (ret) hx509_err(context, 1, ret, "hx509_request_add_email"); } for (i = 0; i < opt->dnsname_strings.num_strings; i++) { ret = _hx509_request_add_dns_name(context, req, opt->dnsname_strings.strings[i]); if (ret) hx509_err(context, 1, ret, "hx509_request_add_dns_name"); } ret = hx509_private_key2SPKI(context, signer, &key); if (ret) errx(1, "hx509_private_key2SPKI: %d\n", ret); ret = hx509_request_set_SubjectPublicKeyInfo(context, req, &key); free_SubjectPublicKeyInfo(&key); if (ret) hx509_err(context, 1, ret, "hx509_request_set_SubjectPublicKeyInfo"); ret = _hx509_request_to_pkcs10(context, req, signer, &request); if (ret) hx509_err(context, 1, ret, "_hx509_request_to_pkcs10"); hx509_private_key_free(&signer); hx509_request_free(&req); if (ret == 0) rk_dumpdata(outfile, request.data, request.length); der_free_octet_string(&request); return 0; } int request_print(struct request_print_options *opt, int argc, char **argv) { int ret, i; printf("request print\n"); for (i = 0; i < argc; i++) { hx509_request req; ret = _hx509_request_parse(context, argv[i], &req); if (ret) hx509_err(context, 1, ret, "parse_request: %s", argv[i]); ret = _hx509_request_print(context, req, stdout); hx509_request_free(&req); if (ret) hx509_err(context, 1, ret, "Failed to print file %s", argv[i]); } return 0; } int info(void *opt, int argc, char **argv) { ENGINE_add_conf_module(); { const RSA_METHOD *m = RSA_get_default_method(); if (m != NULL) printf("rsa: %s\n", m->name); } { const DH_METHOD *m = DH_get_default_method(); if (m != NULL) printf("dh: %s\n", m->name); } #ifdef HAVE_HCRYPTO_W_OPENSSL { printf("ecdsa: ECDSA_METHOD-not-export\n"); } #else { printf("ecdsa: hcrypto null\n"); } #endif { int ret = RAND_status(); printf("rand: %s\n", ret == 1 ? "ok" : "not available"); } return 0; } int random_data(void *opt, int argc, char **argv) { void *ptr; int len, ret; len = parse_bytes(argv[0], "byte"); if (len <= 0) { fprintf(stderr, "bad argument to random-data\n"); return 1; } ptr = malloc(len); if (ptr == NULL) { fprintf(stderr, "out of memory\n"); return 1; } ret = RAND_bytes(ptr, len); if (ret != 1) { free(ptr); fprintf(stderr, "did not get cryptographic strong random\n"); return 1; } fwrite(ptr, len, 1, stdout); fflush(stdout); free(ptr); return 0; } int crypto_available(struct crypto_available_options *opt, int argc, char **argv) { AlgorithmIdentifier *val; unsigned int len, i; int ret, type = HX509_SELECT_ALL; if (opt->type_string) { if (strcmp(opt->type_string, "all") == 0) type = HX509_SELECT_ALL; else if (strcmp(opt->type_string, "digest") == 0) type = HX509_SELECT_DIGEST; else if (strcmp(opt->type_string, "public-sig") == 0) type = HX509_SELECT_PUBLIC_SIG; else if (strcmp(opt->type_string, "secret") == 0) type = HX509_SELECT_SECRET_ENC; else errx(1, "unknown type: %s", opt->type_string); } ret = hx509_crypto_available(context, type, NULL, &val, &len); if (ret) errx(1, "hx509_crypto_available"); for (i = 0; i < len; i++) { char *s; der_print_heim_oid (&val[i].algorithm, '.', &s); printf("%s\n", s); free(s); } hx509_crypto_free_algs(val, len); return 0; } int crypto_select(struct crypto_select_options *opt, int argc, char **argv) { hx509_peer_info peer = NULL; AlgorithmIdentifier selected; int ret, type = HX509_SELECT_DIGEST; char *s; if (opt->type_string) { if (strcmp(opt->type_string, "digest") == 0) type = HX509_SELECT_DIGEST; else if (strcmp(opt->type_string, "public-sig") == 0) type = HX509_SELECT_PUBLIC_SIG; else if (strcmp(opt->type_string, "secret") == 0) type = HX509_SELECT_SECRET_ENC; else errx(1, "unknown type: %s", opt->type_string); } if (opt->peer_cmstype_strings.num_strings) peer_strings(context, &peer, &opt->peer_cmstype_strings); ret = hx509_crypto_select(context, type, NULL, peer, &selected); if (ret) errx(1, "hx509_crypto_available"); der_print_heim_oid (&selected.algorithm, '.', &s); printf("%s\n", s); free(s); free_AlgorithmIdentifier(&selected); hx509_peer_info_free(peer); return 0; } int hxtool_hex(struct hex_options *opt, int argc, char **argv) { if (opt->decode_flag) { char buf[1024], buf2[1024], *p; ssize_t len; while(fgets(buf, sizeof(buf), stdin) != NULL) { buf[strcspn(buf, "\r\n")] = '\0'; p = buf; while(isspace(*(unsigned char *)p)) p++; len = hex_decode(p, buf2, strlen(p)); if (len < 0) errx(1, "hex_decode failed"); if (fwrite(buf2, 1, len, stdout) != (size_t)len) errx(1, "fwrite failed"); } } else { char buf[28], *p; ssize_t len; while((len = fread(buf, 1, sizeof(buf), stdin)) != 0) { len = hex_encode(buf, len, &p); if (len < 0) continue; fprintf(stdout, "%s\n", p); free(p); } } return 0; } struct cert_type_opt { int pkinit; }; static int https_server(hx509_context contextp, hx509_ca_tbs tbs, struct cert_type_opt *opt) { return hx509_ca_tbs_add_eku(contextp, tbs, &asn1_oid_id_pkix_kp_serverAuth); } static int https_client(hx509_context contextp, hx509_ca_tbs tbs, struct cert_type_opt *opt) { return hx509_ca_tbs_add_eku(contextp, tbs, &asn1_oid_id_pkix_kp_clientAuth); } static int peap_server(hx509_context contextp, hx509_ca_tbs tbs, struct cert_type_opt *opt) { return hx509_ca_tbs_add_eku(contextp, tbs, &asn1_oid_id_pkix_kp_serverAuth); } static int pkinit_kdc(hx509_context contextp, hx509_ca_tbs tbs, struct cert_type_opt *opt) { opt->pkinit++; return hx509_ca_tbs_add_eku(contextp, tbs, &asn1_oid_id_pkkdcekuoid); } static int pkinit_client(hx509_context contextp, hx509_ca_tbs tbs, struct cert_type_opt *opt) { int ret; opt->pkinit++; ret = hx509_ca_tbs_add_eku(contextp, tbs, &asn1_oid_id_pkekuoid); if (ret) return ret; ret = hx509_ca_tbs_add_eku(context, tbs, &asn1_oid_id_ms_client_authentication); if (ret) return ret; return hx509_ca_tbs_add_eku(context, tbs, &asn1_oid_id_pkinit_ms_eku); } static int email_client(hx509_context contextp, hx509_ca_tbs tbs, struct cert_type_opt *opt) { return hx509_ca_tbs_add_eku(contextp, tbs, &asn1_oid_id_pkix_kp_emailProtection); } struct { const char *type; const char *desc; int (*eval)(hx509_context, hx509_ca_tbs, struct cert_type_opt *); } certtypes[] = { { "https-server", "Used for HTTPS server and many other TLS server certificate types", https_server }, { "https-client", "Used for HTTPS client certificates", https_client }, { "email-client", "Certificate will be use for email", email_client }, { "pkinit-client", "Certificate used for Kerberos PK-INIT client certificates", pkinit_client }, { "pkinit-kdc", "Certificates used for Kerberos PK-INIT KDC certificates", pkinit_kdc }, { "peap-server", "Certificate used for Radius PEAP (Protected EAP)", peap_server } }; static void print_eval_types(FILE *out) { rtbl_t table; unsigned i; table = rtbl_create(); rtbl_add_column_by_id (table, 0, "Name", 0); rtbl_add_column_by_id (table, 1, "Description", 0); for (i = 0; i < sizeof(certtypes)/sizeof(certtypes[0]); i++) { rtbl_add_column_entry_by_id(table, 0, certtypes[i].type); rtbl_add_column_entry_by_id(table, 1, certtypes[i].desc); } rtbl_format (table, out); rtbl_destroy (table); } static int eval_types(hx509_context contextp, hx509_ca_tbs tbs, const struct certificate_sign_options *opt) { struct cert_type_opt ctopt; int i; size_t j; int ret; memset(&ctopt, 0, sizeof(ctopt)); for (i = 0; i < opt->type_strings.num_strings; i++) { const char *type = opt->type_strings.strings[i]; for (j = 0; j < sizeof(certtypes)/sizeof(certtypes[0]); j++) { if (strcasecmp(type, certtypes[j].type) == 0) { ret = (*certtypes[j].eval)(contextp, tbs, &ctopt); if (ret) hx509_err(contextp, 1, ret, "Failed to evaluate cert type %s", type); break; } } if (j >= sizeof(certtypes)/sizeof(certtypes[0])) { fprintf(stderr, "Unknown certificate type %s\n\n", type); fprintf(stderr, "Available types:\n"); print_eval_types(stderr); exit(1); } } for (i = 0; i < opt->pk_init_principal_strings.num_strings; i++) { const char *pk_init_princ = opt->pk_init_principal_strings.strings[i]; if (!ctopt.pkinit) errx(1, "pk-init principal given but no pk-init oid"); ret = hx509_ca_tbs_add_san_pkinit(contextp, tbs, pk_init_princ); if (ret) hx509_err(contextp, 1, ret, "hx509_ca_tbs_add_san_pkinit"); } if (opt->ms_upn_string) { if (!ctopt.pkinit) errx(1, "MS upn given but no pk-init oid"); ret = hx509_ca_tbs_add_san_ms_upn(contextp, tbs, opt->ms_upn_string); if (ret) hx509_err(contextp, 1, ret, "hx509_ca_tbs_add_san_ms_upn"); } for (i = 0; i < opt->hostname_strings.num_strings; i++) { const char *hostname = opt->hostname_strings.strings[i]; ret = hx509_ca_tbs_add_san_hostname(contextp, tbs, hostname); if (ret) hx509_err(contextp, 1, ret, "hx509_ca_tbs_add_san_hostname"); } for (i = 0; i < opt->email_strings.num_strings; i++) { const char *email = opt->email_strings.strings[i]; ret = hx509_ca_tbs_add_san_rfc822name(contextp, tbs, email); if (ret) hx509_err(contextp, 1, ret, "hx509_ca_tbs_add_san_hostname"); ret = hx509_ca_tbs_add_eku(contextp, tbs, &asn1_oid_id_pkix_kp_emailProtection); if (ret) hx509_err(contextp, 1, ret, "hx509_ca_tbs_add_eku"); } if (opt->jid_string) { ret = hx509_ca_tbs_add_san_jid(contextp, tbs, opt->jid_string); if (ret) hx509_err(contextp, 1, ret, "hx509_ca_tbs_add_san_jid"); } return 0; } int hxtool_ca(struct certificate_sign_options *opt, int argc, char **argv) { int ret; hx509_ca_tbs tbs; hx509_cert signer = NULL, cert = NULL; hx509_private_key private_key = NULL; hx509_private_key cert_key = NULL; hx509_name subject = NULL; SubjectPublicKeyInfo spki; int delta = 0; memset(&spki, 0, sizeof(spki)); if (opt->ca_certificate_string == NULL && !opt->self_signed_flag) errx(1, "--ca-certificate argument missing (not using --self-signed)"); if (opt->ca_private_key_string == NULL && opt->generate_key_string == NULL && opt->self_signed_flag) errx(1, "--ca-private-key argument missing (using --self-signed)"); if (opt->certificate_string == NULL) errx(1, "--certificate argument missing"); if (opt->template_certificate_string) { if (opt->template_fields_string == NULL) errx(1, "--template-certificate not no --template-fields"); } if (opt->lifetime_string) { delta = parse_time(opt->lifetime_string, "day"); if (delta < 0) errx(1, "Invalid lifetime: %s", opt->lifetime_string); } if (opt->ca_certificate_string) { hx509_certs cacerts = NULL; hx509_query *q; ret = hx509_certs_init(context, opt->ca_certificate_string, 0, NULL, &cacerts); if (ret) hx509_err(context, 1, ret, "hx509_certs_init: %s", opt->ca_certificate_string); ret = hx509_query_alloc(context, &q); if (ret) errx(1, "hx509_query_alloc: %d", ret); hx509_query_match_option(q, HX509_QUERY_OPTION_PRIVATE_KEY); if (!opt->issue_proxy_flag) hx509_query_match_option(q, HX509_QUERY_OPTION_KU_KEYCERTSIGN); ret = hx509_certs_find(context, cacerts, q, &signer); hx509_query_free(context, q); hx509_certs_free(&cacerts); if (ret) hx509_err(context, 1, ret, "no CA certificate found"); } else if (opt->self_signed_flag) { if (opt->generate_key_string == NULL && opt->ca_private_key_string == NULL) errx(1, "no signing private key"); if (opt->req_string) errx(1, "can't be self-signing and have a request at the same time"); } else errx(1, "missing ca key"); if (opt->ca_private_key_string) { ret = read_private_key(opt->ca_private_key_string, &private_key); if (ret) err(1, "read_private_key"); ret = hx509_private_key2SPKI(context, private_key, &spki); if (ret) errx(1, "hx509_private_key2SPKI: %d\n", ret); if (opt->self_signed_flag) cert_key = private_key; } if (opt->req_string) { hx509_request req; ret = _hx509_request_parse(context, opt->req_string, &req); if (ret) hx509_err(context, 1, ret, "parse_request: %s", opt->req_string); ret = hx509_request_get_name(context, req, &subject); if (ret) hx509_err(context, 1, ret, "get name"); ret = hx509_request_get_SubjectPublicKeyInfo(context, req, &spki); if (ret) hx509_err(context, 1, ret, "get spki"); hx509_request_free(&req); } if (opt->generate_key_string) { struct hx509_generate_private_context *keyctx; ret = _hx509_generate_private_key_init(context, &asn1_oid_id_pkcs1_rsaEncryption, &keyctx); if (ret) hx509_err(context, 1, ret, "generate private key"); if (opt->issue_ca_flag) _hx509_generate_private_key_is_ca(context, keyctx); if (opt->key_bits_integer) _hx509_generate_private_key_bits(context, keyctx, opt->key_bits_integer); ret = _hx509_generate_private_key(context, keyctx, &cert_key); _hx509_generate_private_key_free(&keyctx); if (ret) hx509_err(context, 1, ret, "generate private key"); ret = hx509_private_key2SPKI(context, cert_key, &spki); if (ret) errx(1, "hx509_private_key2SPKI: %d\n", ret); if (opt->self_signed_flag) private_key = cert_key; } if (opt->certificate_private_key_string) { ret = read_private_key(opt->certificate_private_key_string, &cert_key); if (ret) err(1, "read_private_key for certificate"); } if (opt->subject_string) { if (subject) hx509_name_free(&subject); ret = hx509_parse_name(context, opt->subject_string, &subject); if (ret) hx509_err(context, 1, ret, "hx509_parse_name"); } /* * */ ret = hx509_ca_tbs_init(context, &tbs); if (ret) hx509_err(context, 1, ret, "hx509_ca_tbs_init"); if (opt->signature_algorithm_string) { const AlgorithmIdentifier *sigalg; if (strcasecmp(opt->signature_algorithm_string, "rsa-with-sha1") == 0) sigalg = hx509_signature_rsa_with_sha1(); else if (strcasecmp(opt->signature_algorithm_string, "rsa-with-sha256") == 0) sigalg = hx509_signature_rsa_with_sha256(); else errx(1, "unsupported sigature algorithm"); hx509_ca_tbs_set_signature_algorithm(context, tbs, sigalg); } if (opt->template_certificate_string) { hx509_cert template; hx509_certs tcerts; int flags; ret = hx509_certs_init(context, opt->template_certificate_string, 0, NULL, &tcerts); if (ret) hx509_err(context, 1, ret, "hx509_certs_init: %s", opt->template_certificate_string); ret = hx509_get_one_cert(context, tcerts, &template); hx509_certs_free(&tcerts); if (ret) hx509_err(context, 1, ret, "no template certificate found"); flags = parse_units(opt->template_fields_string, hx509_ca_tbs_template_units(), ""); ret = hx509_ca_tbs_set_template(context, tbs, flags, template); if (ret) hx509_err(context, 1, ret, "hx509_ca_tbs_set_template"); hx509_cert_free(template); } if (opt->serial_number_string) { heim_integer serialNumber; ret = der_parse_hex_heim_integer(opt->serial_number_string, &serialNumber); if (ret) err(1, "der_parse_hex_heim_integer"); ret = hx509_ca_tbs_set_serialnumber(context, tbs, &serialNumber); if (ret) hx509_err(context, 1, ret, "hx509_ca_tbs_init"); der_free_heim_integer(&serialNumber); } if (spki.subjectPublicKey.length) { ret = hx509_ca_tbs_set_spki(context, tbs, &spki); if (ret) hx509_err(context, 1, ret, "hx509_ca_tbs_set_spki"); } if (subject) { ret = hx509_ca_tbs_set_subject(context, tbs, subject); if (ret) hx509_err(context, 1, ret, "hx509_ca_tbs_set_subject"); } if (opt->crl_uri_string) { ret = hx509_ca_tbs_add_crl_dp_uri(context, tbs, opt->crl_uri_string, NULL); if (ret) hx509_err(context, 1, ret, "hx509_ca_tbs_add_crl_dp_uri"); } eval_types(context, tbs, opt); if (opt->issue_ca_flag) { ret = hx509_ca_tbs_set_ca(context, tbs, opt->path_length_integer); if (ret) hx509_err(context, 1, ret, "hx509_ca_tbs_set_ca"); } if (opt->issue_proxy_flag) { ret = hx509_ca_tbs_set_proxy(context, tbs, opt->path_length_integer); if (ret) hx509_err(context, 1, ret, "hx509_ca_tbs_set_proxy"); } if (opt->domain_controller_flag) { hx509_ca_tbs_set_domaincontroller(context, tbs); if (ret) hx509_err(context, 1, ret, "hx509_ca_tbs_set_domaincontroller"); } if (delta) { ret = hx509_ca_tbs_set_notAfter_lifetime(context, tbs, delta); if (ret) hx509_err(context, 1, ret, "hx509_ca_tbs_set_notAfter_lifetime"); } if (opt->self_signed_flag) { ret = hx509_ca_sign_self(context, tbs, private_key, &cert); if (ret) hx509_err(context, 1, ret, "hx509_ca_sign_self"); } else { ret = hx509_ca_sign(context, tbs, signer, &cert); if (ret) hx509_err(context, 1, ret, "hx509_ca_sign"); } if (cert_key) { ret = _hx509_cert_assign_key(cert, cert_key); if (ret) hx509_err(context, 1, ret, "_hx509_cert_assign_key"); } { hx509_certs certs; ret = hx509_certs_init(context, opt->certificate_string, HX509_CERTS_CREATE, NULL, &certs); if (ret) hx509_err(context, 1, ret, "hx509_certs_init"); ret = hx509_certs_add(context, certs, cert); if (ret) hx509_err(context, 1, ret, "hx509_certs_add"); ret = hx509_certs_store(context, certs, 0, NULL); if (ret) hx509_err(context, 1, ret, "hx509_certs_store"); hx509_certs_free(&certs); } if (subject) hx509_name_free(&subject); if (signer) hx509_cert_free(signer); hx509_cert_free(cert); free_SubjectPublicKeyInfo(&spki); if (private_key != cert_key) hx509_private_key_free(&private_key); hx509_private_key_free(&cert_key); hx509_ca_tbs_free(&tbs); return 0; } static int test_one_cert(hx509_context hxcontext, void *ctx, hx509_cert cert) { heim_octet_string sd, c; hx509_verify_ctx vctx = ctx; hx509_certs signer = NULL; heim_oid type; int ret; if (_hx509_cert_private_key(cert) == NULL) return 0; ret = hx509_cms_create_signed_1(context, 0, NULL, NULL, 0, NULL, cert, NULL, NULL, NULL, &sd); if (ret) errx(1, "hx509_cms_create_signed_1"); ret = hx509_cms_verify_signed(context, vctx, 0, sd.data, sd.length, NULL, NULL, &type, &c, &signer); free(sd.data); if (ret) hx509_err(context, 1, ret, "hx509_cms_verify_signed"); printf("create-signature verify-sigature done\n"); free(c.data); return 0; } int test_crypto(struct test_crypto_options *opt, int argc, char ** argv) { hx509_verify_ctx vctx; hx509_certs certs; hx509_lock lock; int i, ret; hx509_lock_init(context, &lock); lock_strings(lock, &opt->pass_strings); ret = hx509_certs_init(context, "MEMORY:test-crypto", 0, NULL, &certs); if (ret) hx509_err(context, 1, ret, "hx509_certs_init: MEMORY"); for (i = 0; i < argc; i++) { ret = hx509_certs_append(context, certs, lock, argv[i]); if (ret) hx509_err(context, 1, ret, "hx509_certs_append"); } ret = hx509_verify_init_ctx(context, &vctx); if (ret) hx509_err(context, 1, ret, "hx509_verify_init_ctx"); hx509_verify_attach_anchors(vctx, certs); ret = hx509_certs_iter_f(context, certs, test_one_cert, vctx); if (ret) hx509_err(context, 1, ret, "hx509_cert_iter"); hx509_certs_free(&certs); return 0; } int statistic_print(struct statistic_print_options*opt, int argc, char **argv) { int type = 0; if (stat_file_string == NULL) errx(1, "no stat file"); if (opt->type_integer) type = opt->type_integer; hx509_query_unparse_stats(context, type, stdout); return 0; } /* * */ int crl_sign(struct crl_sign_options *opt, int argc, char **argv) { hx509_crl crl; heim_octet_string os; hx509_cert signer = NULL; hx509_lock lock; int ret; hx509_lock_init(context, &lock); lock_strings(lock, &opt->pass_strings); ret = hx509_crl_alloc(context, &crl); if (ret) errx(1, "crl alloc"); if (opt->signer_string == NULL) errx(1, "signer missing"); { hx509_certs certs = NULL; hx509_query *q; ret = hx509_certs_init(context, opt->signer_string, 0, NULL, &certs); if (ret) hx509_err(context, 1, ret, "hx509_certs_init: %s", opt->signer_string); ret = hx509_query_alloc(context, &q); if (ret) hx509_err(context, 1, ret, "hx509_query_alloc: %d", ret); hx509_query_match_option(q, HX509_QUERY_OPTION_PRIVATE_KEY); ret = hx509_certs_find(context, certs, q, &signer); hx509_query_free(context, q); hx509_certs_free(&certs); if (ret) hx509_err(context, 1, ret, "no signer certificate found"); } if (opt->lifetime_string) { int delta; delta = parse_time(opt->lifetime_string, "day"); if (delta < 0) errx(1, "Invalid lifetime: %s", opt->lifetime_string); hx509_crl_lifetime(context, crl, delta); } { hx509_certs revoked = NULL; int i; ret = hx509_certs_init(context, "MEMORY:revoked-certs", 0, NULL, &revoked); if (ret) hx509_err(context, 1, ret, "hx509_certs_init: MEMORY cert"); for (i = 0; i < argc; i++) { ret = hx509_certs_append(context, revoked, lock, argv[i]); if (ret) hx509_err(context, 1, ret, "hx509_certs_append: %s", argv[i]); } hx509_crl_add_revoked_certs(context, crl, revoked); hx509_certs_free(&revoked); } hx509_crl_sign(context, signer, crl, &os); if (opt->crl_file_string) rk_dumpdata(opt->crl_file_string, os.data, os.length); free(os.data); hx509_crl_free(context, &crl); hx509_cert_free(signer); hx509_lock_free(lock); return 0; } /* * */ int help(void *opt, int argc, char **argv) { sl_slc_help(commands, argc, argv); return 0; } int main(int argc, char **argv) { int ret, optidx = 0; setprogname (argv[0]); if(getarg(args, num_args, argc, argv, &optidx)) usage(1); if(help_flag) usage(0); if(version_flag) { print_version(NULL); exit(0); } argv += optidx; argc -= optidx; if (argc == 0) usage(1); ret = hx509_context_init(&context); if (ret) errx(1, "hx509_context_init failed with %d", ret); if (stat_file_string) hx509_query_statistic_file(context, stat_file_string); ret = sl_command(commands, argc, argv); if(ret == -1) warnx ("unrecognized command: %s", argv[0]); hx509_context_free(&context); return ret; } heimdal-7.5.0/lib/hx509/pkcs10.opt0000644000175000017500000000005312136107750014522 0ustar niknik--preserve-binary=CertificationRequestInfo heimdal-7.5.0/lib/hx509/req.c0000644000175000017500000001723613026237312013640 0ustar niknik/* * Copyright (c) 2006 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "hx_locl.h" #include struct hx509_request_data { hx509_name name; SubjectPublicKeyInfo key; ExtKeyUsage eku; GeneralNames san; }; /* * */ int hx509_request_init(hx509_context context, hx509_request *req) { *req = calloc(1, sizeof(**req)); if (*req == NULL) return ENOMEM; return 0; } void hx509_request_free(hx509_request *req) { if ((*req)->name) hx509_name_free(&(*req)->name); free_SubjectPublicKeyInfo(&(*req)->key); free_ExtKeyUsage(&(*req)->eku); free_GeneralNames(&(*req)->san); memset(*req, 0, sizeof(**req)); free(*req); *req = NULL; } int hx509_request_set_name(hx509_context context, hx509_request req, hx509_name name) { if (req->name) hx509_name_free(&req->name); if (name) { int ret = hx509_name_copy(context, name, &req->name); if (ret) return ret; } return 0; } int hx509_request_get_name(hx509_context context, hx509_request req, hx509_name *name) { if (req->name == NULL) { hx509_set_error_string(context, 0, EINVAL, "Request have no name"); return EINVAL; } return hx509_name_copy(context, req->name, name); } int hx509_request_set_SubjectPublicKeyInfo(hx509_context context, hx509_request req, const SubjectPublicKeyInfo *key) { free_SubjectPublicKeyInfo(&req->key); return copy_SubjectPublicKeyInfo(key, &req->key); } int hx509_request_get_SubjectPublicKeyInfo(hx509_context context, hx509_request req, SubjectPublicKeyInfo *key) { return copy_SubjectPublicKeyInfo(&req->key, key); } int _hx509_request_add_eku(hx509_context context, hx509_request req, const heim_oid *oid) { void *val; int ret; val = realloc(req->eku.val, sizeof(req->eku.val[0]) * (req->eku.len + 1)); if (val == NULL) return ENOMEM; req->eku.val = val; ret = der_copy_oid(oid, &req->eku.val[req->eku.len]); if (ret) return ret; req->eku.len += 1; return 0; } int _hx509_request_add_dns_name(hx509_context context, hx509_request req, const char *hostname) { GeneralName name; memset(&name, 0, sizeof(name)); name.element = choice_GeneralName_dNSName; name.u.dNSName.data = rk_UNCONST(hostname); name.u.dNSName.length = strlen(hostname); return add_GeneralNames(&req->san, &name); } int _hx509_request_add_email(hx509_context context, hx509_request req, const char *email) { GeneralName name; memset(&name, 0, sizeof(name)); name.element = choice_GeneralName_rfc822Name; name.u.dNSName.data = rk_UNCONST(email); name.u.dNSName.length = strlen(email); return add_GeneralNames(&req->san, &name); } int _hx509_request_to_pkcs10(hx509_context context, const hx509_request req, const hx509_private_key signer, heim_octet_string *request) { CertificationRequest r; heim_octet_string data, os; int ret; size_t size; if (req->name == NULL) { hx509_set_error_string(context, 0, EINVAL, "PKCS10 needs to have a subject"); return EINVAL; } memset(&r, 0, sizeof(r)); memset(request, 0, sizeof(*request)); r.certificationRequestInfo.version = pkcs10_v1; ret = copy_Name(&req->name->der_name, &r.certificationRequestInfo.subject); if (ret) goto out; ret = copy_SubjectPublicKeyInfo(&req->key, &r.certificationRequestInfo.subjectPKInfo); if (ret) goto out; r.certificationRequestInfo.attributes = calloc(1, sizeof(*r.certificationRequestInfo.attributes)); if (r.certificationRequestInfo.attributes == NULL) { ret = ENOMEM; goto out; } ASN1_MALLOC_ENCODE(CertificationRequestInfo, data.data, data.length, &r.certificationRequestInfo, &size, ret); if (ret) goto out; if (data.length != size) abort(); ret = _hx509_create_signature(context, signer, _hx509_crypto_default_sig_alg, &data, &r.signatureAlgorithm, &os); free(data.data); if (ret) goto out; r.signature.data = os.data; r.signature.length = os.length * 8; ASN1_MALLOC_ENCODE(CertificationRequest, data.data, data.length, &r, &size, ret); if (ret) goto out; if (data.length != size) abort(); *request = data; out: free_CertificationRequest(&r); return ret; } int _hx509_request_parse(hx509_context context, const char *path, hx509_request *req) { CertificationRequest r; CertificationRequestInfo *rinfo; hx509_name subject; size_t len, size; void *p; int ret; if (strncmp(path, "PKCS10:", 7) != 0) { hx509_set_error_string(context, 0, HX509_UNSUPPORTED_OPERATION, "unsupport type in %s", path); return HX509_UNSUPPORTED_OPERATION; } path += 7; /* XXX PEM request */ ret = rk_undumpdata(path, &p, &len); if (ret) { hx509_set_error_string(context, 0, ret, "Failed to map file %s", path); return ret; } ret = decode_CertificationRequest(p, len, &r, &size); rk_xfree(p); if (ret) { hx509_set_error_string(context, 0, ret, "Failed to decode %s", path); return ret; } ret = hx509_request_init(context, req); if (ret) { free_CertificationRequest(&r); return ret; } rinfo = &r.certificationRequestInfo; ret = hx509_request_set_SubjectPublicKeyInfo(context, *req, &rinfo->subjectPKInfo); if (ret) { free_CertificationRequest(&r); hx509_request_free(req); return ret; } ret = _hx509_name_from_Name(&rinfo->subject, &subject); if (ret) { free_CertificationRequest(&r); hx509_request_free(req); return ret; } ret = hx509_request_set_name(context, *req, subject); hx509_name_free(&subject); free_CertificationRequest(&r); if (ret) { hx509_request_free(req); return ret; } return 0; } int _hx509_request_print(hx509_context context, hx509_request req, FILE *f) { int ret; if (req->name) { char *subject; ret = hx509_name_to_string(req->name, &subject); if (ret) { hx509_set_error_string(context, 0, ret, "Failed to print name"); return ret; } fprintf(f, "name: %s\n", subject); free(subject); } return 0; } heimdal-7.5.0/lib/hx509/test_windows.in0000644000175000017500000000603512136107750015764 0ustar niknik#!/bin/sh # # Copyright (c) 2007 Kungliga Tekniska Högskolan # (Royal Institute of Technology, Stockholm, Sweden). # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # 1. Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # # 3. Neither the name of the Institute nor the names of its contributors # may be used to endorse or promote products derived from this software # without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE # ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS # OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) # HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY # OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF # SUCH DAMAGE. # # $Id$ # srcdir="@srcdir@" objdir="@objdir@" stat="--statistic-file=${objdir}/statfile" hxtool="${TESTS_ENVIRONMENT} ./hxtool ${stat}" if ${hxtool} info | grep 'rsa: hcrypto null RSA' > /dev/null ; then exit 77 fi if ${hxtool} info | grep 'rand: not available' > /dev/null ; then exit 77 fi echo "Create trust anchor" ${hxtool} issue-certificate \ --self-signed \ --issue-ca \ --generate-key=rsa \ --subject="CN=Windows-CA,DC=heimdal,DC=pki" \ --lifetime=10years \ --certificate="FILE:wca.pem" || exit 1 echo "Create domain controller cert" ${hxtool} issue-certificate \ --type="pkinit-kdc" \ --pk-init-principal="krbtgt/HEIMDAL.PKI@HEIMDAL.PKI" \ --hostname=kdc.heimdal.pki \ --generate-key=rsa \ --subject="CN=kdc.heimdal.pki,dc=heimdal,dc=pki" \ --certificate="FILE:wdc.pem" \ --domain-controller \ --crl-uri="http://www.test.h5l.se/test-hemdal-pki-crl1.crl" \ --ca-certificate=FILE:wca.pem || exit 1 echo "Create user cert" ${hxtool} issue-certificate \ --type="pkinit-client" \ --pk-init-principal="user@HEIMDAL.PKI" \ --generate-key=rsa \ --subject="CN=User,DC=heimdal,DC=pki" \ --ms-upn="user@heimdal.pki" \ --crl-uri="http://www.test.h5l.se/test-hemdal-pki-crl1.crl" \ --certificate="FILE:wuser.pem" \ --ca-certificate=FILE:wca.pem || exit 1 echo "Create crl" ${hxtool} crl-sign \ --crl-file=wcrl.crl \ --signer=FILE:wca.pem || exit 1 exit 0 heimdal-7.5.0/lib/hx509/test_expr.c0000644000175000017500000000413613026237312015061 0ustar niknik #include "hx_locl.h" #include struct foo { int val; char *str; } foo[] = { { 0, "FALSE" }, { 1, "TRUE" }, { 0, "!TRUE" }, { 0, "! TRUE" }, { 0, "!\tTRUE" }, { 0, "( FALSE AND FALSE )" }, { 0, "( TRUE AND FALSE )" }, { 1, "( TRUE AND TRUE )" }, { 1, "( TRUE OR TRUE )" }, { 1, "( TRUE OR FALSE )" }, { 0, "( FALSE OR FALSE )" }, { 1, "! ( FALSE OR FALSE )" }, { 1, "\"foo\" TAILMATCH \"foo\"" }, { 1, "\"foobar\" TAILMATCH \"bar\"" }, { 0, "\"foobar\" TAILMATCH \"foo\"" }, { 1, "\"foo\" == \"foo\"" }, { 0, "\"foo\" == \"bar\"" }, { 0, "\"foo\" != \"foo\"" }, { 1, "\"foo\" != \"bar\"" }, { 1, "%{variable} == \"foo\"" }, { 0, "%{variable} == \"bar\"" }, { 1, "%{context.variable} == \"foo\"" }, { 0, "%{context.variable} == \"bar\"" }, { 1, "\"foo\" IN ( \"bar\", \"foo\")" }, { 0, "\"foo\" IN ( \"bar\", \"baz\")" }, { 0, "\"bar\" IN %{context}" }, { 1, "\"foo\" IN %{context}" }, { 1, "\"variable\" IN %{context}" }, { 1, "\"foo\" IN %{context} AND %{context.variable} == \"foo\"" } }; int main(int argc, char **argv) { struct hx_expr *expr; hx509_context context; hx509_env env = NULL, env2 = NULL; int val, i, ret; #if 0 extern int yydebug; yydebug = 1; #endif ret = hx509_context_init(&context); if (ret) errx(1, "hx509_context_init failed with %d", ret); hx509_env_add(context, &env, "variable", "foo"); hx509_env_add(context, &env2, "variable", "foo"); hx509_env_add_binding(context, &env, "context", env2); for (i = 0; i < sizeof(foo)/sizeof(foo[0]); i++) { expr = _hx509_expr_parse(foo[i].str); if (expr == NULL) errx(1, "_hx509_expr_parse failed for %d: %s", i, foo[i].str); val = _hx509_expr_eval(context, env, expr); if (foo[i].val) { if (val == 0) errx(1, "_hx509_expr_eval not true when it should: %d: %s", i, foo[i].str); } else { if (val) errx(1, "_hx509_expr_eval true when it should not: %d: %s", i, foo[i].str); } _hx509_expr_free(expr); } hx509_env_free(&env); return 0; } heimdal-7.5.0/lib/hx509/ks_dir.c0000644000175000017500000001171613026237312014321 0ustar niknik/* * Copyright (c) 2006 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "hx_locl.h" #include /* * The DIR keyset module is strange compared to the other modules * since it does lazy evaluation and really doesn't keep any local * state except for the directory iteration and cert iteration of * files. DIR ignores most errors so that the consumer doesn't get * failes for stray files in directories. */ struct dircursor { DIR *dir; hx509_certs certs; void *iter; }; /* * */ static int dir_init(hx509_context context, hx509_certs certs, void **data, int flags, const char *residue, hx509_lock lock) { *data = NULL; { struct stat sb; int ret; ret = stat(residue, &sb); if (ret == -1) { hx509_set_error_string(context, 0, ENOENT, "No such file %s", residue); return ENOENT; } if (!S_ISDIR(sb.st_mode)) { hx509_set_error_string(context, 0, ENOTDIR, "%s is not a directory", residue); return ENOTDIR; } } *data = strdup(residue); if (*data == NULL) { hx509_clear_error_string(context); return ENOMEM; } return 0; } static int dir_free(hx509_certs certs, void *data) { free(data); return 0; } static int dir_iter_start(hx509_context context, hx509_certs certs, void *data, void **cursor) { struct dircursor *d; *cursor = NULL; d = calloc(1, sizeof(*d)); if (d == NULL) { hx509_clear_error_string(context); return ENOMEM; } d->dir = opendir(data); if (d->dir == NULL) { hx509_clear_error_string(context); free(d); return errno; } rk_cloexec_dir(d->dir); d->certs = NULL; d->iter = NULL; *cursor = d; return 0; } static int dir_iter(hx509_context context, hx509_certs certs, void *data, void *iter, hx509_cert *cert) { struct dircursor *d = iter; int ret = 0; *cert = NULL; do { struct dirent *dir; char *fn; if (d->certs) { ret = hx509_certs_next_cert(context, d->certs, d->iter, cert); if (ret) { hx509_certs_end_seq(context, d->certs, d->iter); d->iter = NULL; hx509_certs_free(&d->certs); return ret; } if (*cert) { ret = 0; break; } hx509_certs_end_seq(context, d->certs, d->iter); d->iter = NULL; hx509_certs_free(&d->certs); } dir = readdir(d->dir); if (dir == NULL) { ret = 0; break; } if (strcmp(dir->d_name, ".") == 0 || strcmp(dir->d_name, "..") == 0) continue; if (asprintf(&fn, "FILE:%s/%s", (char *)data, dir->d_name) == -1) return ENOMEM; ret = hx509_certs_init(context, fn, 0, NULL, &d->certs); if (ret == 0) { ret = hx509_certs_start_seq(context, d->certs, &d->iter); if (ret) hx509_certs_free(&d->certs); } /* ignore errors */ if (ret) { d->certs = NULL; ret = 0; } free(fn); } while(ret == 0); return ret; } static int dir_iter_end(hx509_context context, hx509_certs certs, void *data, void *cursor) { struct dircursor *d = cursor; if (d->certs) { hx509_certs_end_seq(context, d->certs, d->iter); d->iter = NULL; hx509_certs_free(&d->certs); } closedir(d->dir); free(d); return 0; } static struct hx509_keyset_ops keyset_dir = { "DIR", 0, dir_init, NULL, dir_free, NULL, NULL, dir_iter_start, dir_iter, dir_iter_end, NULL, NULL, NULL }; void _hx509_ks_dir_register(hx509_context context) { _hx509_ks_register(context, &keyset_dir); } heimdal-7.5.0/lib/hx509/keyset.c0000644000175000017500000004476413026237312014363 0ustar niknik/* * Copyright (c) 2004 - 2007 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Portions Copyright (c) 2009 Apple Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "hx_locl.h" /** * @page page_keyset Certificate store operations * * Type of certificates store: * - MEMORY * In memory based format. Doesnt support storing. * - FILE * FILE supports raw DER certicates and PEM certicates. When PEM is * used the file can contain may certificates and match private * keys. Support storing the certificates. DER format only supports * on certificate and no private key. * - PEM-FILE * Same as FILE, defaulting to PEM encoded certificates. * - PEM-FILE * Same as FILE, defaulting to DER encoded certificates. * - PKCS11 * - PKCS12 * - DIR * - KEYCHAIN * Apple Mac OS X KeyChain backed keychain object. * * See the library functions here: @ref hx509_keyset */ struct hx509_certs_data { unsigned int ref; struct hx509_keyset_ops *ops; void *ops_data; }; static struct hx509_keyset_ops * _hx509_ks_type(hx509_context context, const char *type) { int i; for (i = 0; i < context->ks_num_ops; i++) if (strcasecmp(type, context->ks_ops[i]->name) == 0) return context->ks_ops[i]; return NULL; } void _hx509_ks_register(hx509_context context, struct hx509_keyset_ops *ops) { struct hx509_keyset_ops **val; if (_hx509_ks_type(context, ops->name)) return; val = realloc(context->ks_ops, (context->ks_num_ops + 1) * sizeof(context->ks_ops[0])); if (val == NULL) return; val[context->ks_num_ops] = ops; context->ks_ops = val; context->ks_num_ops++; } /** * Open or creates a new hx509 certificate store. * * @param context A hx509 context * @param name name of the store, format is TYPE:type-specific-string, * if NULL is used the MEMORY store is used. * @param flags list of flags: * - HX509_CERTS_CREATE create a new keystore of the specific TYPE. * - HX509_CERTS_UNPROTECT_ALL fails if any private key failed to be extracted. * @param lock a lock that unlocks the certificates store, use NULL to * select no password/certifictes/prompt lock (see @ref page_lock). * @param certs return pointer, free with hx509_certs_free(). * * @return Returns an hx509 error code. * * @ingroup hx509_keyset */ int hx509_certs_init(hx509_context context, const char *name, int flags, hx509_lock lock, hx509_certs *certs) { struct hx509_keyset_ops *ops; const char *residue; hx509_certs c; char *type; int ret; *certs = NULL; residue = strchr(name, ':'); if (residue) { type = malloc(residue - name + 1); if (type) strlcpy(type, name, residue - name + 1); residue++; if (residue[0] == '\0') residue = NULL; } else { type = strdup("MEMORY"); residue = name; } if (type == NULL) { hx509_clear_error_string(context); return ENOMEM; } ops = _hx509_ks_type(context, type); if (ops == NULL) { hx509_set_error_string(context, 0, ENOENT, "Keyset type %s is not supported", type); free(type); return ENOENT; } free(type); c = calloc(1, sizeof(*c)); if (c == NULL) { hx509_clear_error_string(context); return ENOMEM; } c->ops = ops; c->ref = 1; ret = (*ops->init)(context, c, &c->ops_data, flags, residue, lock); if (ret) { free(c); return ret; } *certs = c; return 0; } /** * Write the certificate store to stable storage. * * @param context A hx509 context. * @param certs a certificate store to store. * @param flags currently unused, use 0. * @param lock a lock that unlocks the certificates store, use NULL to * select no password/certifictes/prompt lock (see @ref page_lock). * * @return Returns an hx509 error code. HX509_UNSUPPORTED_OPERATION if * the certificate store doesn't support the store operation. * * @ingroup hx509_keyset */ int hx509_certs_store(hx509_context context, hx509_certs certs, int flags, hx509_lock lock) { if (certs->ops->store == NULL) { hx509_set_error_string(context, 0, HX509_UNSUPPORTED_OPERATION, "keystore if type %s doesn't support " "store operation", certs->ops->name); return HX509_UNSUPPORTED_OPERATION; } return (*certs->ops->store)(context, certs, certs->ops_data, flags, lock); } hx509_certs hx509_certs_ref(hx509_certs certs) { if (certs == NULL) return NULL; if (certs->ref == 0) _hx509_abort("certs refcount == 0 on ref"); if (certs->ref == UINT_MAX) _hx509_abort("certs refcount == UINT_MAX on ref"); certs->ref++; return certs; } /** * Free a certificate store. * * @param certs certificate store to free. * * @ingroup hx509_keyset */ void hx509_certs_free(hx509_certs *certs) { if (*certs) { if ((*certs)->ref == 0) _hx509_abort("cert refcount == 0 on free"); if (--(*certs)->ref > 0) return; (*(*certs)->ops->free)(*certs, (*certs)->ops_data); free(*certs); *certs = NULL; } } /** * Start the integration * * @param context a hx509 context. * @param certs certificate store to iterate over * @param cursor cursor that will keep track of progress, free with * hx509_certs_end_seq(). * * @return Returns an hx509 error code. HX509_UNSUPPORTED_OPERATION is * returned if the certificate store doesn't support the iteration * operation. * * @ingroup hx509_keyset */ int hx509_certs_start_seq(hx509_context context, hx509_certs certs, hx509_cursor *cursor) { int ret; if (certs->ops->iter_start == NULL) { hx509_set_error_string(context, 0, HX509_UNSUPPORTED_OPERATION, "Keyset type %s doesn't support iteration", certs->ops->name); return HX509_UNSUPPORTED_OPERATION; } ret = (*certs->ops->iter_start)(context, certs, certs->ops_data, cursor); if (ret) return ret; return 0; } /** * Get next ceritificate from the certificate keystore pointed out by * cursor. * * @param context a hx509 context. * @param certs certificate store to iterate over. * @param cursor cursor that keeps track of progress. * @param cert return certificate next in store, NULL if the store * contains no more certificates. Free with hx509_cert_free(). * * @return Returns an hx509 error code. * * @ingroup hx509_keyset */ int hx509_certs_next_cert(hx509_context context, hx509_certs certs, hx509_cursor cursor, hx509_cert *cert) { *cert = NULL; return (*certs->ops->iter)(context, certs, certs->ops_data, cursor, cert); } /** * End the iteration over certificates. * * @param context a hx509 context. * @param certs certificate store to iterate over. * @param cursor cursor that will keep track of progress, freed. * * @return Returns an hx509 error code. * * @ingroup hx509_keyset */ int hx509_certs_end_seq(hx509_context context, hx509_certs certs, hx509_cursor cursor) { (*certs->ops->iter_end)(context, certs, certs->ops_data, cursor); return 0; } /** * Iterate over all certificates in a keystore and call a function * for each of them. * * @param context a hx509 context. * @param certs certificate store to iterate over. * @param func function to call for each certificate. The function * should return non-zero to abort the iteration, that value is passed * back to the caller of hx509_certs_iter_f(). * @param ctx context variable that will passed to the function. * * @return Returns an hx509 error code. * * @ingroup hx509_keyset */ int hx509_certs_iter_f(hx509_context context, hx509_certs certs, int (*func)(hx509_context, void *, hx509_cert), void *ctx) { hx509_cursor cursor; hx509_cert c; int ret; ret = hx509_certs_start_seq(context, certs, &cursor); if (ret) return ret; while (1) { ret = hx509_certs_next_cert(context, certs, cursor, &c); if (ret) break; if (c == NULL) { ret = 0; break; } ret = (*func)(context, ctx, c); hx509_cert_free(c); if (ret) break; } hx509_certs_end_seq(context, certs, cursor); return ret; } #ifdef __BLOCKS__ static int certs_iter(hx509_context context, void *ctx, hx509_cert cert) { int (^func)(hx509_cert) = ctx; return func(cert); } /** * Iterate over all certificates in a keystore and call a block * for each of them. * * @param context a hx509 context. * @param certs certificate store to iterate over. * @param func block to call for each certificate. The function * should return non-zero to abort the iteration, that value is passed * back to the caller of hx509_certs_iter(). * * @return Returns an hx509 error code. * * @ingroup hx509_keyset */ int hx509_certs_iter(hx509_context context, hx509_certs certs, int (^func)(hx509_cert)) { return hx509_certs_iter_f(context, certs, certs_iter, func); } #endif /** * Function to use to hx509_certs_iter_f() as a function argument, the * ctx variable to hx509_certs_iter_f() should be a FILE file descriptor. * * @param context a hx509 context. * @param ctx used by hx509_certs_iter_f(). * @param c a certificate * * @return Returns an hx509 error code. * * @ingroup hx509_keyset */ int hx509_ci_print_names(hx509_context context, void *ctx, hx509_cert c) { Certificate *cert; hx509_name n; char *s, *i; cert = _hx509_get_cert(c); _hx509_name_from_Name(&cert->tbsCertificate.subject, &n); hx509_name_to_string(n, &s); hx509_name_free(&n); _hx509_name_from_Name(&cert->tbsCertificate.issuer, &n); hx509_name_to_string(n, &i); hx509_name_free(&n); fprintf(ctx, "subject: %s\nissuer: %s\n", s, i); free(s); free(i); return 0; } /** * Add a certificate to the certificiate store. * * The receiving keyset certs will either increase reference counter * of the cert or make a deep copy, either way, the caller needs to * free the cert itself. * * @param context a hx509 context. * @param certs certificate store to add the certificate to. * @param cert certificate to add. * * @return Returns an hx509 error code. * * @ingroup hx509_keyset */ int hx509_certs_add(hx509_context context, hx509_certs certs, hx509_cert cert) { if (certs->ops->add == NULL) { hx509_set_error_string(context, 0, ENOENT, "Keyset type %s doesn't support add operation", certs->ops->name); return ENOENT; } return (*certs->ops->add)(context, certs, certs->ops_data, cert); } /** * Find a certificate matching the query. * * @param context a hx509 context. * @param certs certificate store to search. * @param q query allocated with @ref hx509_query functions. * @param r return certificate (or NULL on error), should be freed * with hx509_cert_free(). * * @return Returns an hx509 error code. * * @ingroup hx509_keyset */ int hx509_certs_find(hx509_context context, hx509_certs certs, const hx509_query *q, hx509_cert *r) { hx509_cursor cursor; hx509_cert c; int ret; *r = NULL; _hx509_query_statistic(context, 0, q); if (certs->ops->query) return (*certs->ops->query)(context, certs, certs->ops_data, q, r); ret = hx509_certs_start_seq(context, certs, &cursor); if (ret) return ret; c = NULL; while (1) { ret = hx509_certs_next_cert(context, certs, cursor, &c); if (ret) break; if (c == NULL) break; if (_hx509_query_match_cert(context, q, c)) { *r = c; break; } hx509_cert_free(c); } hx509_certs_end_seq(context, certs, cursor); if (ret) return ret; /** * Return HX509_CERT_NOT_FOUND if no certificate in certs matched * the query. */ if (c == NULL) { hx509_clear_error_string(context); return HX509_CERT_NOT_FOUND; } return 0; } /** * Filter certificate matching the query. * * @param context a hx509 context. * @param certs certificate store to search. * @param q query allocated with @ref hx509_query functions. * @param result the filtered certificate store, caller must free with * hx509_certs_free(). * * @return Returns an hx509 error code. * * @ingroup hx509_keyset */ int hx509_certs_filter(hx509_context context, hx509_certs certs, const hx509_query *q, hx509_certs *result) { hx509_cursor cursor; hx509_cert c; int ret, found = 0; _hx509_query_statistic(context, 0, q); ret = hx509_certs_init(context, "MEMORY:filter-certs", 0, NULL, result); if (ret) return ret; ret = hx509_certs_start_seq(context, certs, &cursor); if (ret) { hx509_certs_free(result); return ret; } c = NULL; while (1) { ret = hx509_certs_next_cert(context, certs, cursor, &c); if (ret) break; if (c == NULL) break; if (_hx509_query_match_cert(context, q, c)) { hx509_certs_add(context, *result, c); found = 1; } hx509_cert_free(c); } hx509_certs_end_seq(context, certs, cursor); if (ret) { hx509_certs_free(result); return ret; } /** * Return HX509_CERT_NOT_FOUND if no certificate in certs matched * the query. */ if (!found) { hx509_certs_free(result); hx509_clear_error_string(context); return HX509_CERT_NOT_FOUND; } return 0; } static int certs_merge_func(hx509_context context, void *ctx, hx509_cert c) { return hx509_certs_add(context, (hx509_certs)ctx, c); } /** * Merge a certificate store into another. The from store is keep * intact. * * @param context a hx509 context. * @param to the store to merge into. * @param from the store to copy the object from. * * @return Returns an hx509 error code. * * @ingroup hx509_keyset */ int hx509_certs_merge(hx509_context context, hx509_certs to, hx509_certs from) { if (from == NULL) return 0; return hx509_certs_iter_f(context, from, certs_merge_func, to); } /** * Same a hx509_certs_merge() but use a lock and name to describe the * from source. * * @param context a hx509 context. * @param to the store to merge into. * @param lock a lock that unlocks the certificates store, use NULL to * select no password/certifictes/prompt lock (see @ref page_lock). * @param name name of the source store * * @return Returns an hx509 error code. * * @ingroup hx509_keyset */ int hx509_certs_append(hx509_context context, hx509_certs to, hx509_lock lock, const char *name) { hx509_certs s; int ret; ret = hx509_certs_init(context, name, 0, lock, &s); if (ret) return ret; ret = hx509_certs_merge(context, to, s); hx509_certs_free(&s); return ret; } /** * Get one random certificate from the certificate store. * * @param context a hx509 context. * @param certs a certificate store to get the certificate from. * @param c return certificate, should be freed with hx509_cert_free(). * * @return Returns an hx509 error code. * * @ingroup hx509_keyset */ int hx509_get_one_cert(hx509_context context, hx509_certs certs, hx509_cert *c) { hx509_cursor cursor; int ret; *c = NULL; ret = hx509_certs_start_seq(context, certs, &cursor); if (ret) return ret; ret = hx509_certs_next_cert(context, certs, cursor, c); if (ret) return ret; hx509_certs_end_seq(context, certs, cursor); return 0; } static int certs_info_stdio(void *ctx, const char *str) { FILE *f = ctx; fprintf(f, "%s\n", str); return 0; } /** * Print some info about the certificate store. * * @param context a hx509 context. * @param certs certificate store to print information about. * @param func function that will get each line of the information, if * NULL is used the data is printed on a FILE descriptor that should * be passed in ctx, if ctx also is NULL, stdout is used. * @param ctx parameter to func. * * @return Returns an hx509 error code. * * @ingroup hx509_keyset */ int hx509_certs_info(hx509_context context, hx509_certs certs, int (*func)(void *, const char *), void *ctx) { if (func == NULL) { func = certs_info_stdio; if (ctx == NULL) ctx = stdout; } if (certs->ops->printinfo == NULL) { (*func)(ctx, "No info function for certs"); return 0; } return (*certs->ops->printinfo)(context, certs, certs->ops_data, func, ctx); } void _hx509_pi_printf(int (*func)(void *, const char *), void *ctx, const char *fmt, ...) { va_list ap; char *str; int ret; va_start(ap, fmt); ret = vasprintf(&str, fmt, ap); va_end(ap); if (ret == -1 || str == NULL) return; (*func)(ctx, str); free(str); } int _hx509_certs_keys_get(hx509_context context, hx509_certs certs, hx509_private_key **keys) { if (certs->ops->getkeys == NULL) { *keys = NULL; return 0; } return (*certs->ops->getkeys)(context, certs, certs->ops_data, keys); } int _hx509_certs_keys_add(hx509_context context, hx509_certs certs, hx509_private_key key) { if (certs->ops->addkey == NULL) { hx509_set_error_string(context, 0, EINVAL, "keystore if type %s doesn't support " "key add operation", certs->ops->name); return EINVAL; } return (*certs->ops->addkey)(context, certs, certs->ops_data, key); } void _hx509_certs_keys_free(hx509_context context, hx509_private_key *keys) { int i; for (i = 0; keys[i]; i++) hx509_private_key_free(&keys[i]); free(keys); } heimdal-7.5.0/lib/hx509/test_ca.in0000644000175000017500000003445213026237312014656 0ustar niknik#!/bin/sh # # Copyright (c) 2006 - 2007 Kungliga Tekniska Högskolan # (Royal Institute of Technology, Stockholm, Sweden). # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # 1. Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # # 3. Neither the name of the Institute nor the names of its contributors # may be used to endorse or promote products derived from this software # without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE # ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS # OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) # HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY # OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF # SUCH DAMAGE. # # $Id$ # srcdir="@srcdir@" objdir="@objdir@" stat="--statistic-file=${objdir}/statfile" hxtool="${TESTS_ENVIRONMENT} ./hxtool ${stat}" if ${hxtool} info | grep 'rsa: hcrypto null RSA' > /dev/null ; then exit 77 fi if ${hxtool} info | grep 'rand: not available' > /dev/null ; then exit 77 fi echo "create certificate request" ${hxtool} request-create \ --subject="CN=Love,DC=it,DC=su,DC=se" \ --key=FILE:$srcdir/data/key.der \ pkcs10-request.der || exit 1 echo "issue certificate" ${hxtool} issue-certificate \ --ca-certificate=FILE:$srcdir/data/ca.crt,$srcdir/data/ca.key \ --subject="cn=foo" \ --req="PKCS10:pkcs10-request.der" \ --certificate="FILE:cert-ee.pem" || exit 1 echo "verify certificate" ${hxtool} verify --missing-revoke \ cert:FILE:cert-ee.pem \ anchor:FILE:$srcdir/data/ca.crt > /dev/null || exit 1 echo "issue crl (no cert)" ${hxtool} crl-sign \ --crl-file=crl.crl \ --signer=FILE:$srcdir/data/ca.crt,$srcdir/data/ca.key || exit 1 echo "verify certificate (with CRL)" ${hxtool} verify \ cert:FILE:cert-ee.pem \ crl:FILE:crl.crl \ anchor:FILE:$srcdir/data/ca.crt > /dev/null || exit 1 echo "issue crl (with cert)" ${hxtool} crl-sign \ --crl-file=crl.crl \ --signer=FILE:$srcdir/data/ca.crt,$srcdir/data/ca.key \ FILE:cert-ee.pem || exit 1 echo "verify certificate (included in CRL)" ${hxtool} verify \ cert:FILE:cert-ee.pem \ crl:FILE:crl.crl \ anchor:FILE:$srcdir/data/ca.crt > /dev/null && exit 1 echo "issue crl (with cert)" ${hxtool} crl-sign \ --crl-file=crl.crl \ --lifetime='1 month' \ --signer=FILE:$srcdir/data/ca.crt,$srcdir/data/ca.key \ FILE:cert-ee.pem || exit 1 echo "verify certificate (included in CRL, and lifetime 1 month)" ${hxtool} verify \ cert:FILE:cert-ee.pem \ crl:FILE:crl.crl \ anchor:FILE:$srcdir/data/ca.crt > /dev/null && exit 1 echo "issue certificate (10years 1 month)" ${hxtool} issue-certificate \ --ca-certificate=FILE:$srcdir/data/ca.crt,$srcdir/data/ca.key \ --subject="cn=foo" \ --lifetime="10years 1 month" \ --req="PKCS10:pkcs10-request.der" \ --certificate="FILE:cert-ee.pem" || exit 1 echo "issue certificate (with https ekus)" ${hxtool} issue-certificate \ --ca-certificate=FILE:$srcdir/data/ca.crt,$srcdir/data/ca.key \ --subject="cn=foo" \ --type="https-server" \ --type="https-client" \ --req="PKCS10:pkcs10-request.der" \ --certificate="FILE:cert-ee.pem" || exit 1 echo "issue certificate (pkinit KDC)" ${hxtool} issue-certificate \ --ca-certificate=FILE:$srcdir/data/ca.crt,$srcdir/data/ca.key \ --subject="cn=foo" \ --type="pkinit-kdc" \ --pk-init-principal="krbtgt/TEST.H5L.SE@TEST.H5L.SE" \ --req="PKCS10:pkcs10-request.der" \ --certificate="FILE:cert-ee.pem" || exit 1 echo "issue certificate (pkinit client)" ${hxtool} issue-certificate \ --ca-certificate=FILE:$srcdir/data/ca.crt,$srcdir/data/ca.key \ --subject="cn=foo" \ --type="pkinit-client" \ --pk-init-principal="lha@TEST.H5L.SE" \ --req="PKCS10:pkcs10-request.der" \ --certificate="FILE:cert-ee.pem" || exit 1 echo "issue certificate (hostnames)" ${hxtool} issue-certificate \ --ca-certificate=FILE:$srcdir/data/ca.crt,$srcdir/data/ca.key \ --subject="cn=foo" \ --type="https-server" \ --hostname="www.test.h5l.se" \ --hostname="ftp.test.h5l.se" \ --req="PKCS10:pkcs10-request.der" \ --certificate="FILE:cert-ee.pem" || exit 1 echo "verify certificate hostname (ok)" ${hxtool} verify --missing-revoke \ --hostname=www.test.h5l.se \ cert:FILE:cert-ee.pem \ anchor:FILE:$srcdir/data/ca.crt > /dev/null || exit 1 echo "verify certificate hostname (fail)" ${hxtool} verify --missing-revoke \ --hostname=www2.test.h5l.se \ cert:FILE:cert-ee.pem \ anchor:FILE:$srcdir/data/ca.crt > /dev/null && exit 1 echo "verify certificate hostname (fail)" ${hxtool} verify --missing-revoke \ --hostname=2www.test.h5l.se \ cert:FILE:cert-ee.pem \ anchor:FILE:$srcdir/data/ca.crt > /dev/null && exit 1 echo "issue certificate (hostname in CN)" ${hxtool} issue-certificate \ --ca-certificate=FILE:$srcdir/data/ca.crt,$srcdir/data/ca.key \ --subject="cn=www.test.h5l.se" \ --type="https-server" \ --req="PKCS10:pkcs10-request.der" \ --certificate="FILE:cert-ee.pem" || exit 1 echo "verify certificate hostname (ok)" ${hxtool} verify --missing-revoke \ --hostname=www.test.h5l.se \ cert:FILE:cert-ee.pem \ anchor:FILE:$srcdir/data/ca.crt > /dev/null || exit 1 echo "verify certificate hostname (fail)" ${hxtool} verify --missing-revoke \ --hostname=www2.test.h5l.se \ cert:FILE:cert-ee.pem \ anchor:FILE:$srcdir/data/ca.crt > /dev/null && exit 1 echo "issue certificate (email)" ${hxtool} issue-certificate \ --ca-certificate=FILE:$srcdir/data/ca.crt,$srcdir/data/ca.key \ --subject="cn=foo" \ --email="lha@test.h5l.se" \ --email="test@test.h5l.se" \ --req="PKCS10:pkcs10-request.der" \ --certificate="FILE:cert-ee.pem" || exit 1 echo "issue certificate (email, null subject DN)" ${hxtool} issue-certificate \ --ca-certificate=FILE:$srcdir/data/ca.crt,$srcdir/data/ca.key \ --subject="" \ --email="lha@test.h5l.se" \ --req="PKCS10:pkcs10-request.der" \ --certificate="FILE:cert-null.pem" || exit 1 echo "issue certificate (jabber)" ${hxtool} issue-certificate \ --ca-certificate=FILE:$srcdir/data/ca.crt,$srcdir/data/ca.key \ --subject="cn=foo" \ --jid="lha@test.h5l.se" \ --req="PKCS10:pkcs10-request.der" \ --certificate="FILE:cert-ee.pem" || exit 1 echo "issue self-signed cert" ${hxtool} issue-certificate \ --self-signed \ --ca-private-key=FILE:$srcdir/data/key.der \ --subject="cn=test" \ --certificate="FILE:cert-ee.pem" || exit 1 echo "issue ca cert" ${hxtool} issue-certificate \ --ca-certificate=FILE:$srcdir/data/ca.crt,$srcdir/data/ca.key \ --issue-ca \ --subject="cn=ca-cert" \ --req="PKCS10:pkcs10-request.der" \ --certificate="FILE:cert-ca.der" || exit 1 echo "issue self-signed ca cert" ${hxtool} issue-certificate \ --self-signed \ --issue-ca \ --ca-private-key=FILE:$srcdir/data/key.der \ --subject="cn=ca-root" \ --certificate="FILE:cert-ca.der" || exit 1 echo "issue proxy certificate" ${hxtool} issue-certificate \ --ca-certificate=FILE:$srcdir/data/test.crt,$srcdir/data/test.key \ --issue-proxy \ --req="PKCS10:pkcs10-request.der" \ --certificate="FILE:cert-proxy.der" || exit 1 echo "verify proxy cert" ${hxtool} verify --missing-revoke \ --allow-proxy-certificate \ cert:FILE:cert-proxy.der \ chain:FILE:$srcdir/data/test.crt \ anchor:FILE:$srcdir/data/ca.crt > /dev/null || exit 1 echo "issue ca cert (generate rsa key)" ${hxtool} issue-certificate \ --self-signed \ --issue-ca \ --serial-number="deadbeaf" \ --generate-key=rsa \ --path-length=-1 \ --subject="cn=ca2-cert" \ --certificate="FILE:cert-ca.pem" || exit 1 echo "issue sub-ca cert (generate rsa key)" ${hxtool} issue-certificate \ --ca-certificate=FILE:cert-ca.pem \ --issue-ca \ --serial-number="deadbeaf22" \ --generate-key=rsa \ --subject="cn=sub-ca2-cert" \ --certificate="FILE:cert-sub-ca.pem" || exit 1 echo "issue ee cert (generate rsa key)" ${hxtool} issue-certificate \ --ca-certificate=FILE:cert-ca.pem \ --generate-key=rsa \ --subject="cn=cert-ee2" \ --certificate="FILE:cert-ee.pem" || exit 1 echo "issue sub-ca ee cert (generate rsa key)" ${hxtool} issue-certificate \ --ca-certificate=FILE:cert-sub-ca.pem \ --generate-key=rsa \ --subject="cn=cert-sub-ee2" \ --certificate="FILE:cert-sub-ee.pem" || exit 1 echo "verify certificate (ee)" ${hxtool} verify --missing-revoke \ cert:FILE:cert-ee.pem \ anchor:FILE:cert-ca.pem > /dev/null || exit 1 echo "verify certificate (sub-ee)" ${hxtool} verify --missing-revoke \ cert:FILE:cert-sub-ee.pem \ chain:FILE:cert-sub-ca.pem \ anchor:FILE:cert-ca.pem || exit 1 echo "sign CMS signature (generate key)" ${hxtool} cms-create-sd \ --certificate=FILE:cert-ee.pem \ "$srcdir/test_name.c" \ sd.data > /dev/null || exit 1 echo "verify CMS signature (generate key)" ${hxtool} cms-verify-sd \ --missing-revoke \ --anchors=FILE:cert-ca.pem \ sd.data sd.data.out > /dev/null || exit 1 cmp "$srcdir/test_name.c" sd.data.out || exit 1 echo "extend ca cert" ${hxtool} issue-certificate \ --self-signed \ --issue-ca \ --lifetime="2years" \ --serial-number="deadbeaf" \ --ca-private-key=FILE:cert-ca.pem \ --subject="cn=ca2-cert" \ --certificate="FILE:cert-ca.pem" || exit 1 echo "verify certificate generated by previous ca" ${hxtool} verify --missing-revoke \ cert:FILE:cert-ee.pem \ anchor:FILE:cert-ca.pem > /dev/null || exit 1 echo "extend ca cert (template)" ${hxtool} issue-certificate \ --self-signed \ --issue-ca \ --lifetime="3years" \ --template-certificate="FILE:cert-ca.pem" \ --template-fields="serialNumber,notBefore,subject" \ --path-length=-1 \ --ca-private-key=FILE:cert-ca.pem \ --certificate="FILE:cert-ca.pem" || exit 1 echo "verify certificate generated by previous ca" ${hxtool} verify --missing-revoke \ cert:FILE:cert-ee.pem \ anchor:FILE:cert-ca.pem > /dev/null || exit 1 echo "extend sub-ca cert (template)" ${hxtool} issue-certificate \ --ca-certificate=FILE:cert-ca.pem \ --issue-ca \ --lifetime="2years" \ --template-certificate="FILE:cert-sub-ca.pem" \ --template-fields="serialNumber,notBefore,subject,SPKI" \ --certificate="FILE:cert-sub-ca2.pem" || exit 1 echo "verify certificate (sub-ee) with extended chain" ${hxtool} verify --missing-revoke \ cert:FILE:cert-sub-ee.pem \ chain:FILE:cert-sub-ca.pem \ anchor:FILE:cert-ca.pem > /dev/null || exit 1 echo "+++++++++++ test basic constraints" echo "extend ca cert (too low path-length constraint)" ${hxtool} issue-certificate \ --self-signed \ --issue-ca \ --lifetime="3years" \ --template-certificate="FILE:cert-ca.pem" \ --template-fields="serialNumber,notBefore,subject" \ --path-length=0 \ --ca-private-key=FILE:cert-ca.pem \ --certificate="FILE:cert-ca.pem" || exit 1 echo "verify failure of certificate (sub-ee) with path-length constraint" ${hxtool} verify --missing-revoke \ cert:FILE:cert-sub-ee.pem \ chain:FILE:cert-sub-ca.pem \ anchor:FILE:cert-ca.pem > /dev/null && exit 1 echo "extend ca cert (exact path-length constraint)" ${hxtool} issue-certificate \ --self-signed \ --issue-ca \ --lifetime="3years" \ --template-certificate="FILE:cert-ca.pem" \ --template-fields="serialNumber,notBefore,subject" \ --path-length=1 \ --ca-private-key=FILE:cert-ca.pem \ --certificate="FILE:cert-ca.pem" || exit 1 echo "verify certificate (sub-ee) with exact path-length constraint" ${hxtool} verify --missing-revoke \ cert:FILE:cert-sub-ee.pem \ chain:FILE:cert-sub-ca.pem \ anchor:FILE:cert-ca.pem > /dev/null || exit 1 echo "Check missing basicConstrants.isCa" ${hxtool} issue-certificate \ --ca-certificate=FILE:cert-ca.pem \ --lifetime="2years" \ --template-certificate="FILE:cert-sub-ca.pem" \ --template-fields="serialNumber,notBefore,subject,SPKI" \ --certificate="FILE:cert-sub-ca2.pem" || exit 1 echo "verify failure certificate (sub-ee) with missing isCA" ${hxtool} verify --missing-revoke \ cert:FILE:cert-sub-ee.pem \ chain:FILE:cert-sub-ca2.pem \ anchor:FILE:cert-ca.pem > /dev/null && exit 1 echo "issue ee cert (crl uri)" ${hxtool} issue-certificate \ --ca-certificate=FILE:cert-ca.pem \ --req="PKCS10:pkcs10-request.der" \ --crl-uri="http://www.test.h5l.se/crl1.crl" \ --subject="cn=cert-ee-crl-uri" \ --certificate="FILE:cert-ee.pem" || exit 1 echo "issue null subject cert" ${hxtool} issue-certificate \ --ca-certificate=FILE:cert-ca.pem \ --req="PKCS10:pkcs10-request.der" \ --subject="" \ --email="lha@test.h5l.se" \ --certificate="FILE:cert-ee.pem" || exit 1 echo "verify certificate null subject" ${hxtool} verify --missing-revoke \ cert:FILE:cert-ee.pem \ anchor:FILE:cert-ca.pem > /dev/null || exit 1 echo "+++++++++++ test sigalg" echo "issue cert with sha256" ${hxtool} issue-certificate \ --ca-certificate=FILE:cert-ca.pem \ --signature-algorithm=rsa-with-sha256 \ --subject="cn=foo" \ --req="PKCS10:pkcs10-request.der" \ --certificate="FILE:cert-ee.pem" || exit 1 echo "verify certificate" ${hxtool} verify --missing-revoke \ cert:FILE:cert-ee.pem \ anchor:FILE:cert-ca.pem > /dev/null || exit 1 echo "issue cert with sha1" ${hxtool} issue-certificate \ --ca-certificate=FILE:cert-ca.pem \ --signature-algorithm=rsa-with-sha1 \ --subject="cn=foo" \ --req="PKCS10:pkcs10-request.der" \ --certificate="FILE:cert-ee.pem" || exit 1 echo "verify certificate" ${hxtool} verify --missing-revoke \ cert:FILE:cert-ee.pem \ anchor:FILE:cert-ca.pem > /dev/null || exit 1 exit 0 heimdal-7.5.0/lib/hx509/test_chain.in0000644000175000017500000002117013026237312015346 0ustar niknik#!/bin/sh # # Copyright (c) 2004 - 2006 Kungliga Tekniska Högskolan # (Royal Institute of Technology, Stockholm, Sweden). # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # 1. Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # # 3. Neither the name of the Institute nor the names of its contributors # may be used to endorse or promote products derived from this software # without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE # ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS # OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) # HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY # OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF # SUCH DAMAGE. # # $Id$ # srcdir="@srcdir@" objdir="@objdir@" stat="--statistic-file=${objdir}/statfile" hxtool="${TESTS_ENVIRONMENT} ./hxtool ${stat}" if ${hxtool} info | grep 'rsa: hcrypto null RSA' > /dev/null ; then exit 77 fi if ${hxtool} info | grep 'rand: not available' > /dev/null ; then exit 77 fi echo "cert -> root" ${hxtool} verify --missing-revoke \ cert:FILE:$srcdir/data/test.crt \ chain:FILE:$srcdir/data/test.crt \ chain:FILE:$srcdir/data/ca.crt \ anchor:FILE:$srcdir/data/ca.crt > /dev/null || exit 1 echo "cert -> root" ${hxtool} verify --missing-revoke \ cert:FILE:$srcdir/data/test.crt \ chain:FILE:$srcdir/data/ca.crt \ anchor:FILE:$srcdir/data/ca.crt > /dev/null || exit 1 echo "cert -> root" ${hxtool} verify --missing-revoke \ cert:FILE:$srcdir/data/test.crt \ anchor:FILE:$srcdir/data/ca.crt > /dev/null || exit 1 echo "sub-cert -> root" ${hxtool} verify --missing-revoke \ cert:FILE:$srcdir/data/sub-cert.crt \ chain:FILE:$srcdir/data/ca.crt \ anchor:FILE:$srcdir/data/ca.crt > /dev/null && exit 1 echo "sub-cert -> sub-ca -> root" ${hxtool} verify --missing-revoke \ cert:FILE:$srcdir/data/sub-cert.crt \ chain:FILE:$srcdir/data/sub-ca.crt \ chain:FILE:$srcdir/data/ca.crt \ anchor:FILE:$srcdir/data/ca.crt > /dev/null || exit 1 echo "sub-cert -> sub-ca" ${hxtool} verify --missing-revoke \ cert:FILE:$srcdir/data/sub-cert.crt \ anchor:FILE:$srcdir/data/sub-ca.crt > /dev/null || exit 1 echo "sub-cert -> sub-ca -> root" ${hxtool} verify --missing-revoke \ cert:FILE:$srcdir/data/sub-cert.crt \ chain:FILE:$srcdir/data/sub-ca.crt \ chain:FILE:$srcdir/data/ca.crt \ anchor:FILE:$srcdir/data/ca.crt > /dev/null || exit 1 echo "sub-cert -> sub-ca -> root" ${hxtool} verify --missing-revoke \ cert:FILE:$srcdir/data/sub-cert.crt \ chain:FILE:$srcdir/data/ca.crt \ chain:FILE:$srcdir/data/sub-ca.crt \ anchor:FILE:$srcdir/data/ca.crt > /dev/null || exit 1 echo "sub-cert -> sub-ca -> root" ${hxtool} verify --missing-revoke \ cert:FILE:$srcdir/data/sub-cert.crt \ chain:FILE:$srcdir/data/sub-ca.crt \ anchor:FILE:$srcdir/data/ca.crt > /dev/null || exit 1 echo "max depth 2 (ok)" ${hxtool} verify --missing-revoke \ --max-depth=2 \ cert:FILE:$srcdir/data/sub-cert.crt \ chain:FILE:$srcdir/data/sub-ca.crt \ anchor:FILE:$srcdir/data/ca.crt > /dev/null && exit 1 echo "max depth 1 (fail)" ${hxtool} verify --missing-revoke \ --max-depth=1 \ cert:FILE:$srcdir/data/sub-cert.crt \ chain:FILE:$srcdir/data/sub-ca.crt \ anchor:FILE:$srcdir/data/ca.crt > /dev/null && exit 1 echo "ocsp non-ca responder" ${hxtool} verify \ cert:FILE:$srcdir/data/test.crt \ anchor:FILE:$srcdir/data/ca.crt \ ocsp:FILE:$srcdir/data/ocsp-resp1-ocsp.der > /dev/null || exit 1 echo "ocsp ca responder" ${hxtool} verify \ cert:FILE:$srcdir/data/test.crt \ anchor:FILE:$srcdir/data/ca.crt \ ocsp:FILE:$srcdir/data/ocsp-resp1-ca.der > /dev/null || exit 1 echo "ocsp no-ca responder, missing cert" ${hxtool} verify \ cert:FILE:$srcdir/data/test.crt \ anchor:FILE:$srcdir/data/ca.crt \ ocsp:FILE:$srcdir/data/ocsp-resp1-ocsp-no-cert.der > /dev/null && exit 1 echo "ocsp no-ca responder, missing cert, in pool" ${hxtool} verify \ cert:FILE:$srcdir/data/test.crt \ anchor:FILE:$srcdir/data/ca.crt \ ocsp:FILE:$srcdir/data/ocsp-resp1-ocsp-no-cert.der \ chain:FILE:$srcdir/data/ocsp-responder.crt > /dev/null || exit 1 echo "ocsp no-ca responder, keyHash" ${hxtool} verify \ cert:FILE:$srcdir/data/test.crt \ anchor:FILE:$srcdir/data/ca.crt \ ocsp:FILE:$srcdir/data/ocsp-resp1-keyhash.der > /dev/null || exit 1 echo "ocsp revoked cert" ${hxtool} verify \ cert:FILE:$srcdir/data/revoke.crt \ anchor:FILE:$srcdir/data/ca.crt \ ocsp:FILE:$srcdir/data/ocsp-resp2.der > /dev/null && exit 1 for a in resp1-ocsp-no-cert resp1-ca resp1-keyhash resp2 ; do echo "ocsp print reply $a" ${hxtool} ocsp-print \ $srcdir/data/ocsp-${a}.der > /dev/null || exit 1 done echo "ocsp verify exists" ${hxtool} ocsp-verify \ --ocsp-file=$srcdir/data/ocsp-resp1-ca.der \ FILE:$srcdir/data/test.crt > /dev/null || exit 1 echo "ocsp verify not exists" ${hxtool} ocsp-verify \ --ocsp-file=$srcdir/data/ocsp-resp1.der \ FILE:$srcdir/data/ca.crt > /dev/null && exit 1 echo "ocsp verify revoked" ${hxtool} ocsp-verify \ --ocsp-file=$srcdir/data/ocsp-resp2.der \ FILE:$srcdir/data/revoke.crt > /dev/null && exit 1 echo "crl non-revoked cert" ${hxtool} verify \ cert:FILE:$srcdir/data/test.crt \ anchor:FILE:$srcdir/data/ca.crt \ crl:FILE:$srcdir/data/crl1.der > /dev/null || exit 1 echo "crl revoked cert" ${hxtool} verify \ cert:FILE:$srcdir/data/revoke.crt \ anchor:FILE:$srcdir/data/ca.crt \ crl:FILE:$srcdir/data/crl1.der > /dev/null && exit 1 if ${hxtool} info | grep 'ecdsa: hcrypto null' > /dev/null ; then echo "not testing ECDSA since hcrypto doesnt support ECDSA" else echo "eccert -> root" ${hxtool} verify --missing-revoke \ cert:FILE:$srcdir/data/secp256r2TestServer.cert.pem \ anchor:FILE:$srcdir/data/secp256r1TestCA.cert.pem > /dev/null || exit 1 echo "eccert -> root" ${hxtool} verify --missing-revoke \ cert:FILE:$srcdir/data/secp256r2TestClient.cert.pem \ anchor:FILE:$srcdir/data/secp256r1TestCA.cert.pem > /dev/null || exit 1 fi echo "proxy cert" ${hxtool} verify --missing-revoke \ --allow-proxy-certificate \ cert:FILE:$srcdir/data/proxy-test.crt \ chain:FILE:$srcdir/data/test.crt \ anchor:FILE:$srcdir/data/ca.crt > /dev/null || exit 1 echo "proxy cert (negative)" ${hxtool} verify --missing-revoke \ cert:FILE:$srcdir/data/proxy-test.crt \ chain:FILE:$srcdir/data/test.crt \ anchor:FILE:$srcdir/data/ca.crt > /dev/null && exit 1 echo "proxy cert (level fail)" ${hxtool} verify --missing-revoke \ --allow-proxy-certificate \ cert:FILE:$srcdir/data/proxy-level-test.crt \ chain:FILE:$srcdir/data/proxy-test.crt \ chain:FILE:$srcdir/data/test.crt \ anchor:FILE:$srcdir/data/ca.crt > /dev/null && exit 1 echo "not a proxy cert" ${hxtool} verify --missing-revoke \ --allow-proxy-certificate \ cert:FILE:$srcdir/data/no-proxy-test.crt \ chain:FILE:$srcdir/data/test.crt \ anchor:FILE:$srcdir/data/ca.crt > /dev/null && exit 1 echo "proxy cert (max level 10)" ${hxtool} verify --missing-revoke \ --allow-proxy-certificate \ cert:FILE:$srcdir/data/proxy10-test.crt \ chain:FILE:$srcdir/data/test.crt \ anchor:FILE:$srcdir/data/ca.crt > /dev/null || exit 1 echo "proxy cert (second level)" ${hxtool} verify --missing-revoke \ --allow-proxy-certificate \ cert:FILE:$srcdir/data/proxy10-child-test.crt \ chain:FILE:$srcdir/data/proxy10-test.crt \ chain:FILE:$srcdir/data/test.crt \ anchor:FILE:$srcdir/data/ca.crt > /dev/null || exit 1 echo "proxy cert (third level)" ${hxtool} verify --missing-revoke \ --allow-proxy-certificate \ cert:FILE:$srcdir/data/proxy10-child-child-test.crt \ chain:FILE:$srcdir/data/proxy10-child-test.crt \ chain:FILE:$srcdir/data/proxy10-test.crt \ chain:FILE:$srcdir/data/test.crt \ anchor:FILE:$srcdir/data/ca.crt > /dev/null || exit 1 exit 0 heimdal-7.5.0/lib/hx509/error.c0000644000175000017500000001223413026237312014173 0ustar niknik/* * Copyright (c) 2006 - 2007 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "hx_locl.h" /** * @page page_error Hx509 error reporting functions * * See the library functions here: @ref hx509_error */ struct hx509_error_data { hx509_error next; int code; char *msg; }; /** * Resets the error strings the hx509 context. * * @param context A hx509 context. * * @ingroup hx509_error */ void hx509_clear_error_string(hx509_context context) { if (context) { heim_release(context->error); context->error = NULL; } } /** * Add an error message to the hx509 context. * * @param context A hx509 context. * @param flags * - HX509_ERROR_APPEND appends the error string to the old messages (code is updated). * @param code error code related to error message * @param fmt error message format * @param ap arguments to error message format * * @ingroup hx509_error */ void hx509_set_error_stringv(hx509_context context, int flags, int code, const char *fmt, va_list ap) { heim_error_t msg; if (context == NULL) return; msg = heim_error_createv(code, fmt, ap); if (msg) { if (flags & HX509_ERROR_APPEND) heim_error_append(msg, context->error); heim_release(context->error); } context->error = msg; } /** * See hx509_set_error_stringv(). * * @param context A hx509 context. * @param flags * - HX509_ERROR_APPEND appends the error string to the old messages (code is updated). * @param code error code related to error message * @param fmt error message format * @param ... arguments to error message format * * @ingroup hx509_error */ void hx509_set_error_string(hx509_context context, int flags, int code, const char *fmt, ...) { va_list ap; va_start(ap, fmt); hx509_set_error_stringv(context, flags, code, fmt, ap); va_end(ap); } /** * Get an error string from context associated with error_code. * * @param context A hx509 context. * @param error_code Get error message for this error code. * * @return error string, free with hx509_free_error_string(). * * @ingroup hx509_error */ char * hx509_get_error_string(hx509_context context, int error_code) { heim_error_t msg = context->error; heim_string_t s; char *str = NULL; if (msg == NULL || heim_error_get_code(msg) != error_code) { const char *cstr; cstr = com_right(context->et_list, error_code); if (cstr) return strdup(cstr); cstr = strerror(error_code); if (cstr) return strdup(cstr); if (asprintf(&str, "", error_code) == -1) return NULL; return str; } s = heim_error_copy_string(msg); if (s) { const char *cstr = heim_string_get_utf8(s); if (cstr) str = strdup(cstr); heim_release(s); } return str; } /** * Free error string returned by hx509_get_error_string(). * * @param str error string to free. * * @ingroup hx509_error */ void hx509_free_error_string(char *str) { free(str); } /** * Print error message and fatally exit from error code * * @param context A hx509 context. * @param exit_code exit() code from process. * @param error_code Error code for the reason to exit. * @param fmt format string with the exit message. * @param ... argument to format string. * * @ingroup hx509_error */ void hx509_err(hx509_context context, int exit_code, int error_code, const char *fmt, ...) { va_list ap; const char *msg; char *str; int ret; va_start(ap, fmt); ret = vasprintf(&str, fmt, ap); va_end(ap); msg = hx509_get_error_string(context, error_code); if (msg == NULL) msg = "no error"; errx(exit_code, "%s: %s", ret != -1 ? str : "ENOMEM", msg); } heimdal-7.5.0/lib/hx509/hxtool-version.rc0000644000175000017500000000324112136107750016225 0ustar niknik/*********************************************************************** * Copyright (c) 2010, Secure Endpoints Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * - Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. * **********************************************************************/ #define RC_FILE_TYPE VFT_APP #define RC_FILE_DESC_0409 "Heimdal X.509 Certificate Tool" #define RC_FILE_ORIG_0409 "hxtool.exe" #include "../../windows/version.rc" heimdal-7.5.0/lib/hx509/crypto-ec.c0000644000175000017500000003313013026237312014745 0ustar niknik/* * Copyright (c) 2016 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include #ifdef HAVE_HCRYPTO_W_OPENSSL #include #include #include #include #include #define HEIM_NO_CRYPTO_HDRS #endif /* HAVE_HCRYPTO_W_OPENSSL */ #include "hx_locl.h" extern const AlgorithmIdentifier _hx509_signature_sha512_data; extern const AlgorithmIdentifier _hx509_signature_sha384_data; extern const AlgorithmIdentifier _hx509_signature_sha256_data; extern const AlgorithmIdentifier _hx509_signature_sha1_data; void _hx509_private_eckey_free(void *eckey) { #ifdef HAVE_HCRYPTO_W_OPENSSL EC_KEY_free(eckey); #endif } #ifdef HAVE_HCRYPTO_W_OPENSSL static int heim_oid2ecnid(heim_oid *oid) { /* * Now map to openssl OID fun */ if (der_heim_oid_cmp(oid, ASN1_OID_ID_EC_GROUP_SECP256R1) == 0) return NID_X9_62_prime256v1; #ifdef NID_secp521r1 else if (der_heim_oid_cmp(oid, ASN1_OID_ID_EC_GROUP_SECP521R1) == 0) return NID_secp521r1; #endif #ifdef NID_secp384r1 else if (der_heim_oid_cmp(oid, ASN1_OID_ID_EC_GROUP_SECP384R1) == 0) return NID_secp384r1; #endif #ifdef NID_secp160r1 else if (der_heim_oid_cmp(oid, ASN1_OID_ID_EC_GROUP_SECP160R1) == 0) return NID_secp160r1; #endif #ifdef NID_secp160r2 else if (der_heim_oid_cmp(oid, ASN1_OID_ID_EC_GROUP_SECP160R2) == 0) return NID_secp160r2; #endif return NID_undef; } static int parse_ECParameters(hx509_context context, heim_octet_string *parameters, int *nid) { ECParameters ecparam; size_t size; int ret; if (parameters == NULL) { ret = HX509_PARSING_KEY_FAILED; hx509_set_error_string(context, 0, ret, "EC parameters missing"); return ret; } ret = decode_ECParameters(parameters->data, parameters->length, &ecparam, &size); if (ret) { hx509_set_error_string(context, 0, ret, "Failed to decode EC parameters"); return ret; } if (ecparam.element != choice_ECParameters_namedCurve) { free_ECParameters(&ecparam); hx509_set_error_string(context, 0, ret, "EC parameters is not a named curve"); return HX509_CRYPTO_SIG_INVALID_FORMAT; } *nid = heim_oid2ecnid(&ecparam.u.namedCurve); free_ECParameters(&ecparam); if (*nid == NID_undef) { hx509_set_error_string(context, 0, ret, "Failed to find matcing NID for EC curve"); return HX509_CRYPTO_SIG_INVALID_FORMAT; } return 0; } /* * */ static int ecdsa_verify_signature(hx509_context context, const struct signature_alg *sig_alg, const Certificate *signer, const AlgorithmIdentifier *alg, const heim_octet_string *data, const heim_octet_string *sig) { const AlgorithmIdentifier *digest_alg; const SubjectPublicKeyInfo *spi; heim_octet_string digest; int ret; EC_KEY *key = NULL; int groupnid; EC_GROUP *group; const unsigned char *p; long len; digest_alg = sig_alg->digest_alg; ret = _hx509_create_signature(context, NULL, digest_alg, data, NULL, &digest); if (ret) return ret; /* set up EC KEY */ spi = &signer->tbsCertificate.subjectPublicKeyInfo; if (der_heim_oid_cmp(&spi->algorithm.algorithm, ASN1_OID_ID_ECPUBLICKEY) != 0) return HX509_CRYPTO_SIG_INVALID_FORMAT; /* * Find the group id */ ret = parse_ECParameters(context, spi->algorithm.parameters, &groupnid); if (ret) { der_free_octet_string(&digest); return ret; } /* * Create group, key, parse key */ key = EC_KEY_new(); group = EC_GROUP_new_by_curve_name(groupnid); EC_KEY_set_group(key, group); EC_GROUP_free(group); p = spi->subjectPublicKey.data; len = spi->subjectPublicKey.length / 8; if (o2i_ECPublicKey(&key, &p, len) == NULL) { EC_KEY_free(key); return HX509_CRYPTO_SIG_INVALID_FORMAT; } ret = ECDSA_verify(-1, digest.data, digest.length, sig->data, sig->length, key); der_free_octet_string(&digest); EC_KEY_free(key); if (ret != 1) { ret = HX509_CRYPTO_SIG_INVALID_FORMAT; return ret; } return 0; } static int ecdsa_create_signature(hx509_context context, const struct signature_alg *sig_alg, const hx509_private_key signer, const AlgorithmIdentifier *alg, const heim_octet_string *data, AlgorithmIdentifier *signatureAlgorithm, heim_octet_string *sig) { const AlgorithmIdentifier *digest_alg; heim_octet_string indata; const heim_oid *sig_oid; unsigned int siglen; int ret; if (signer->ops && der_heim_oid_cmp(signer->ops->key_oid, ASN1_OID_ID_ECPUBLICKEY) != 0) _hx509_abort("internal error passing private key to wrong ops"); sig_oid = sig_alg->sig_oid; digest_alg = sig_alg->digest_alg; if (signatureAlgorithm) { ret = _hx509_set_digest_alg(signatureAlgorithm, sig_oid, "\x05\x00", 2); if (ret) { hx509_clear_error_string(context); return ret; } } ret = _hx509_create_signature(context, NULL, digest_alg, data, NULL, &indata); if (ret) goto error; sig->length = ECDSA_size(signer->private_key.ecdsa); sig->data = malloc(sig->length); if (sig->data == NULL) { der_free_octet_string(&indata); ret = ENOMEM; hx509_set_error_string(context, 0, ret, "out of memory"); goto error; } siglen = sig->length; ret = ECDSA_sign(-1, indata.data, indata.length, sig->data, &siglen, signer->private_key.ecdsa); der_free_octet_string(&indata); if (ret != 1) { ret = HX509_CMS_FAILED_CREATE_SIGATURE; hx509_set_error_string(context, 0, ret, "ECDSA sign failed: %d", ret); goto error; } if (siglen > sig->length) _hx509_abort("ECDSA signature prelen longer the output len"); sig->length = siglen; return 0; error: if (signatureAlgorithm) free_AlgorithmIdentifier(signatureAlgorithm); return ret; } static int ecdsa_available(const hx509_private_key signer, const AlgorithmIdentifier *sig_alg) { const struct signature_alg *sig; const EC_GROUP *group; BN_CTX *bnctx = NULL; BIGNUM *order = NULL; int ret = 0; if (der_heim_oid_cmp(signer->ops->key_oid, &asn1_oid_id_ecPublicKey) != 0) _hx509_abort("internal error passing private key to wrong ops"); sig = _hx509_find_sig_alg(&sig_alg->algorithm); if (sig == NULL || sig->digest_size == 0) return 0; group = EC_KEY_get0_group(signer->private_key.ecdsa); if (group == NULL) return 0; bnctx = BN_CTX_new(); order = BN_new(); if (order == NULL) goto err; if (EC_GROUP_get_order(group, order, bnctx) != 1) goto err; #if 0 /* If anything, require a digest at least as wide as the EC key size */ if (BN_num_bytes(order) > sig->digest_size) #endif ret = 1; err: if (bnctx) BN_CTX_free(bnctx); if (order) BN_clear_free(order); return ret; } static int ecdsa_private_key2SPKI(hx509_context context, hx509_private_key private_key, SubjectPublicKeyInfo *spki) { memset(spki, 0, sizeof(*spki)); return ENOMEM; } static int ecdsa_private_key_export(hx509_context context, const hx509_private_key key, hx509_key_format_t format, heim_octet_string *data) { return HX509_CRYPTO_KEY_FORMAT_UNSUPPORTED; } static int ecdsa_private_key_import(hx509_context context, const AlgorithmIdentifier *keyai, const void *data, size_t len, hx509_key_format_t format, hx509_private_key private_key) { const unsigned char *p = data; EC_KEY **pkey = NULL; EC_KEY *key; if (keyai->parameters) { EC_GROUP *group; int groupnid; int ret; ret = parse_ECParameters(context, keyai->parameters, &groupnid); if (ret) return ret; key = EC_KEY_new(); if (key == NULL) return ENOMEM; group = EC_GROUP_new_by_curve_name(groupnid); if (group == NULL) { EC_KEY_free(key); return ENOMEM; } EC_GROUP_set_asn1_flag(group, OPENSSL_EC_NAMED_CURVE); if (EC_KEY_set_group(key, group) == 0) { EC_KEY_free(key); EC_GROUP_free(group); return ENOMEM; } EC_GROUP_free(group); pkey = &key; } switch (format) { case HX509_KEY_FORMAT_DER: private_key->private_key.ecdsa = d2i_ECPrivateKey(pkey, &p, len); if (private_key->private_key.ecdsa == NULL) { hx509_set_error_string(context, 0, HX509_PARSING_KEY_FAILED, "Failed to parse EC private key"); return HX509_PARSING_KEY_FAILED; } private_key->signature_alg = ASN1_OID_ID_ECDSA_WITH_SHA256; break; default: return HX509_CRYPTO_KEY_FORMAT_UNSUPPORTED; } return 0; } static int ecdsa_generate_private_key(hx509_context context, struct hx509_generate_private_context *ctx, hx509_private_key private_key) { return ENOMEM; } static BIGNUM * ecdsa_get_internal(hx509_context context, hx509_private_key key, const char *type) { return NULL; } static const unsigned ecPublicKey[] ={ 1, 2, 840, 10045, 2, 1 }; const AlgorithmIdentifier _hx509_signature_ecPublicKey = { { 6, rk_UNCONST(ecPublicKey) }, NULL }; static const unsigned ecdsa_with_sha256_oid[] ={ 1, 2, 840, 10045, 4, 3, 2 }; const AlgorithmIdentifier _hx509_signature_ecdsa_with_sha256_data = { { 7, rk_UNCONST(ecdsa_with_sha256_oid) }, NULL }; static const unsigned ecdsa_with_sha384_oid[] ={ 1, 2, 840, 10045, 4, 3, 3 }; const AlgorithmIdentifier _hx509_signature_ecdsa_with_sha384_data = { { 7, rk_UNCONST(ecdsa_with_sha384_oid) }, NULL }; static const unsigned ecdsa_with_sha512_oid[] ={ 1, 2, 840, 10045, 4, 3, 4 }; const AlgorithmIdentifier _hx509_signature_ecdsa_with_sha512_data = { { 7, rk_UNCONST(ecdsa_with_sha512_oid) }, NULL }; static const unsigned ecdsa_with_sha1_oid[] ={ 1, 2, 840, 10045, 4, 1 }; const AlgorithmIdentifier _hx509_signature_ecdsa_with_sha1_data = { { 6, rk_UNCONST(ecdsa_with_sha1_oid) }, NULL }; hx509_private_key_ops ecdsa_private_key_ops = { "EC PRIVATE KEY", ASN1_OID_ID_ECPUBLICKEY, ecdsa_available, ecdsa_private_key2SPKI, ecdsa_private_key_export, ecdsa_private_key_import, ecdsa_generate_private_key, ecdsa_get_internal }; const struct signature_alg ecdsa_with_sha512_alg = { "ecdsa-with-sha512", ASN1_OID_ID_ECDSA_WITH_SHA512, &_hx509_signature_ecdsa_with_sha512_data, ASN1_OID_ID_ECPUBLICKEY, &_hx509_signature_sha512_data, PROVIDE_CONF|REQUIRE_SIGNER|RA_RSA_USES_DIGEST_INFO| SIG_PUBLIC_SIG|SELF_SIGNED_OK, 0, NULL, ecdsa_verify_signature, ecdsa_create_signature, 64 }; const struct signature_alg ecdsa_with_sha384_alg = { "ecdsa-with-sha384", ASN1_OID_ID_ECDSA_WITH_SHA384, &_hx509_signature_ecdsa_with_sha384_data, ASN1_OID_ID_ECPUBLICKEY, &_hx509_signature_sha384_data, PROVIDE_CONF|REQUIRE_SIGNER|RA_RSA_USES_DIGEST_INFO| SIG_PUBLIC_SIG|SELF_SIGNED_OK, 0, NULL, ecdsa_verify_signature, ecdsa_create_signature, 48 }; const struct signature_alg ecdsa_with_sha256_alg = { "ecdsa-with-sha256", ASN1_OID_ID_ECDSA_WITH_SHA256, &_hx509_signature_ecdsa_with_sha256_data, ASN1_OID_ID_ECPUBLICKEY, &_hx509_signature_sha256_data, PROVIDE_CONF|REQUIRE_SIGNER|RA_RSA_USES_DIGEST_INFO| SIG_PUBLIC_SIG|SELF_SIGNED_OK, 0, NULL, ecdsa_verify_signature, ecdsa_create_signature, 32 }; const struct signature_alg ecdsa_with_sha1_alg = { "ecdsa-with-sha1", ASN1_OID_ID_ECDSA_WITH_SHA1, &_hx509_signature_ecdsa_with_sha1_data, ASN1_OID_ID_ECPUBLICKEY, &_hx509_signature_sha1_data, PROVIDE_CONF|REQUIRE_SIGNER|RA_RSA_USES_DIGEST_INFO| SIG_PUBLIC_SIG|SELF_SIGNED_OK, 0, NULL, ecdsa_verify_signature, ecdsa_create_signature, 20 }; #endif /* HAVE_HCRYPTO_W_OPENSSL */ const AlgorithmIdentifier * hx509_signature_ecPublicKey(void) { #ifdef HAVE_HCRYPTO_W_OPENSSL return &_hx509_signature_ecPublicKey; #else return NULL; #endif /* HAVE_HCRYPTO_W_OPENSSL */ } const AlgorithmIdentifier * hx509_signature_ecdsa_with_sha256(void) { #ifdef HAVE_HCRYPTO_W_OPENSSL return &_hx509_signature_ecdsa_with_sha256_data; #else return NULL; #endif /* HAVE_HCRYPTO_W_OPENSSL */ } heimdal-7.5.0/lib/hx509/test_nist2.in0000644000175000017500000000754212136107750015335 0ustar niknik#!/bin/sh # # Copyright (c) 2004 - 2008 Kungliga Tekniska Högskolan # (Royal Institute of Technology, Stockholm, Sweden). # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # 1. Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # # 3. Neither the name of the Institute nor the names of its contributors # may be used to endorse or promote products derived from this software # without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE # ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS # OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) # HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY # OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF # SUCH DAMAGE. # # $Id: test_nist.in 21787 2007-08-02 08:50:24Z lha $ # srcdir="@srcdir@" objdir="@objdir@" nistdir=${objdir}/PKITS_data nistzip=${srcdir}/data/PKITS_data.zip egrep="@egrep@" limit="${1:-nolimit}" stat="--statistic-file=${objdir}/statfile" hxtool="${TESTS_ENVIRONMENT} ./hxtool ${stat}" # nistzip is not distributed part of the distribution test -f "$nistzip" || exit 77 if ${hxtool} info | grep 'rsa: hcrypto null RSA' > /dev/null ; then exit 77 fi if ${hxtool} info | grep 'rand: not available' > /dev/null ; then exit 77 fi #--------- Try to find unzip oldifs=$IFS IFS=: set -- $PATH IFS=$oldifs found= for p in "$@" ; do test -x "$p/unzip" && { found=1 ; break; } done test "X$found" = "X" && exit 77 #--------- echo "nist tests, version 2" if [ ! -d "$nistdir" ] ; then ( mkdir "$nistdir" && unzip -d "${nistdir}" "${nistzip}" ) >/dev/null || \ { rm -rf "$nistdir" ; exit 1; } fi ec= name= description= while read result cert other ; do if expr "$result" : "#" > /dev/null; then name=${cert} description="${other}" continue fi test nolimit != "${limit}" && ! expr "$name" : "$limit" > /dev/null && continue test "$result" = "end" && break args= args="$args cert:FILE:$nistdir/certs/$cert" args="$args chain:DIR:$nistdir/certs" args="$args anchor:FILE:$nistdir/certs/TrustAnchorRootCertificate.crt" for a in $nistdir/crls/*.crl; do args="$args crl:FILE:$a" done cmd="${hxtool} verify --time=2008-05-20 $args" eval ${cmd} > /dev/null res=$? case "${result},${res}" in 0,0) r="PASSs";; 0,*) r="FAILs";; [123],0) r="FAILf";; [123],*) r="PASSf";; *) echo="unknown result ${result},${res}" ; exit 1 ;; esac if ${egrep} "^${name} FAIL" $srcdir/data/nist-result2 > /dev/null; then if expr "$r" : "PASS" >/dev/null; then echo "${name} passed when expected not to" echo "# ${description}" > nist2-passed-${name}.tmp ec=1 fi elif ${egrep} "^${name} EITHER" $srcdir/data/nist-result2 > /dev/null; then : elif expr "$r" : "FAIL.*" >/dev/null ; then echo "$r ${name} ${description}" echo "# ${description}" > nist2-failed-${name}.tmp echo "$cmd" >> nist2-failed-${name}.tmp ec=1 fi done < $srcdir/data/nist-data2 echo "done!" exit $ec heimdal-7.5.0/lib/hx509/test_nist_cert.in0000644000175000017500000000446512136107750016271 0ustar niknik#!/bin/sh # # Copyright (c) 2006 Kungliga Tekniska Högskolan # (Royal Institute of Technology, Stockholm, Sweden). # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # 1. Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # # 3. Neither the name of the Institute nor the names of its contributors # may be used to endorse or promote products derived from this software # without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE # ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS # OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) # HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY # OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF # SUCH DAMAGE. # # $Id$ # srcdir="@srcdir@" objdir="@objdir@" nistdir=${objdir}/PKITS_data nistzip=${srcdir}/data/PKITS_data.zip # nistzip is not distributed part of the distribution test -f "$nistzip" || exit 77 stat="--statistic-file=${objdir}/statfile" hxtool="${TESTS_ENVIRONMENT} ./hxtool ${stat}" if ${hxtool} info | grep 'rsa: hcrypto null RSA' > /dev/null ; then exit 77 fi if ${hxtool} info | grep 'rand: not available' > /dev/null ; then exit 77 fi if [ ! -d "$nistdir" ] ; then ( mkdir "$nistdir" && cd "$nistdir" && unzip "$nistzip" ) >/dev/null || \ { rm -rf "$nistdir" ; exit 1; } fi if ${hxtool} validate DIR:$nistdir/certs > /dev/null; then : else echo "validate failed" exit 1 fi exit 0 heimdal-7.5.0/lib/hx509/env.c0000644000175000017500000001302213026237312013626 0ustar niknik/* * Copyright (c) 2007 - 2008 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "hx_locl.h" /** * @page page_env Hx509 environment functions * * See the library functions here: @ref hx509_env */ /** * Add a new key/value pair to the hx509_env. * * @param context A hx509 context. * @param env environment to add the environment variable too. * @param key key to add * @param value value to add * * @return An hx509 error code, see hx509_get_error_string(). * * @ingroup hx509_env */ int hx509_env_add(hx509_context context, hx509_env *env, const char *key, const char *value) { hx509_env n; n = malloc(sizeof(*n)); if (n == NULL) { hx509_set_error_string(context, 0, ENOMEM, "out of memory"); return ENOMEM; } n->type = env_string; n->next = NULL; n->name = strdup(key); if (n->name == NULL) { free(n); return ENOMEM; } n->u.string = strdup(value); if (n->u.string == NULL) { free(n->name); free(n); return ENOMEM; } /* add to tail */ if (*env) { hx509_env e = *env; while (e->next) e = e->next; e->next = n; } else *env = n; return 0; } /** * Add a new key/binding pair to the hx509_env. * * @param context A hx509 context. * @param env environment to add the environment variable too. * @param key key to add * @param list binding list to add * * @return An hx509 error code, see hx509_get_error_string(). * * @ingroup hx509_env */ int hx509_env_add_binding(hx509_context context, hx509_env *env, const char *key, hx509_env list) { hx509_env n; n = malloc(sizeof(*n)); if (n == NULL) { hx509_set_error_string(context, 0, ENOMEM, "out of memory"); return ENOMEM; } n->type = env_list; n->next = NULL; n->name = strdup(key); if (n->name == NULL) { free(n); return ENOMEM; } n->u.list = list; /* add to tail */ if (*env) { hx509_env e = *env; while (e->next) e = e->next; e->next = n; } else *env = n; return 0; } /** * Search the hx509_env for a length based key. * * @param context A hx509 context. * @param env environment to add the environment variable too. * @param key key to search for. * @param len length of key. * * @return the value if the key is found, NULL otherwise. * * @ingroup hx509_env */ const char * hx509_env_lfind(hx509_context context, hx509_env env, const char *key, size_t len) { while(env) { if (strncmp(key, env->name ,len) == 0 && env->name[len] == '\0' && env->type == env_string) return env->u.string; env = env->next; } return NULL; } /** * Search the hx509_env for a key. * * @param context A hx509 context. * @param env environment to add the environment variable too. * @param key key to search for. * * @return the value if the key is found, NULL otherwise. * * @ingroup hx509_env */ const char * hx509_env_find(hx509_context context, hx509_env env, const char *key) { while(env) { if (strcmp(key, env->name) == 0 && env->type == env_string) return env->u.string; env = env->next; } return NULL; } /** * Search the hx509_env for a binding. * * @param context A hx509 context. * @param env environment to add the environment variable too. * @param key key to search for. * * @return the binding if the key is found, NULL if not found. * * @ingroup hx509_env */ hx509_env hx509_env_find_binding(hx509_context context, hx509_env env, const char *key) { while(env) { if (strcmp(key, env->name) == 0 && env->type == env_list) return env->u.list; env = env->next; } return NULL; } static void env_free(hx509_env b) { while(b) { hx509_env next = b->next; if (b->type == env_string) free(b->u.string); else if (b->type == env_list) env_free(b->u.list); free(b->name); free(b); b = next; } } /** * Free an hx509_env environment context. * * @param env the environment to free. * * @ingroup hx509_env */ void hx509_env_free(hx509_env *env) { if (*env) env_free(*env); *env = NULL; } heimdal-7.5.0/lib/hx509/ks_mem.c0000644000175000017500000001235413026237312014320 0ustar niknik/* * Copyright (c) 2005 - 2006 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "hx_locl.h" /* * Should use two hash/tree certificates intead of a array. Criteria * should be subject and subjectKeyIdentifier since those two are * commonly seached on in CMS and path building. */ struct mem_data { char *name; struct { unsigned long len; hx509_cert *val; } certs; hx509_private_key *keys; }; static int mem_init(hx509_context context, hx509_certs certs, void **data, int flags, const char *residue, hx509_lock lock) { struct mem_data *mem; mem = calloc(1, sizeof(*mem)); if (mem == NULL) return ENOMEM; if (residue == NULL || residue[0] == '\0') residue = "anonymous"; mem->name = strdup(residue); if (mem->name == NULL) { free(mem); return ENOMEM; } *data = mem; return 0; } static int mem_free(hx509_certs certs, void *data) { struct mem_data *mem = data; unsigned long i; for (i = 0; i < mem->certs.len; i++) hx509_cert_free(mem->certs.val[i]); free(mem->certs.val); for (i = 0; mem->keys && mem->keys[i]; i++) hx509_private_key_free(&mem->keys[i]); free(mem->keys); free(mem->name); free(mem); return 0; } static int mem_add(hx509_context context, hx509_certs certs, void *data, hx509_cert c) { struct mem_data *mem = data; hx509_cert *val; val = realloc(mem->certs.val, (mem->certs.len + 1) * sizeof(mem->certs.val[0])); if (val == NULL) return ENOMEM; mem->certs.val = val; mem->certs.val[mem->certs.len] = hx509_cert_ref(c); mem->certs.len++; return 0; } static int mem_iter_start(hx509_context context, hx509_certs certs, void *data, void **cursor) { unsigned long *iter = malloc(sizeof(*iter)); if (iter == NULL) return ENOMEM; *iter = 0; *cursor = iter; return 0; } static int mem_iter(hx509_context contexst, hx509_certs certs, void *data, void *cursor, hx509_cert *cert) { unsigned long *iter = cursor; struct mem_data *mem = data; if (*iter >= mem->certs.len) { *cert = NULL; return 0; } *cert = hx509_cert_ref(mem->certs.val[*iter]); (*iter)++; return 0; } static int mem_iter_end(hx509_context context, hx509_certs certs, void *data, void *cursor) { free(cursor); return 0; } static int mem_getkeys(hx509_context context, hx509_certs certs, void *data, hx509_private_key **keys) { struct mem_data *mem = data; int i; for (i = 0; mem->keys && mem->keys[i]; i++) ; *keys = calloc(i + 1, sizeof(**keys)); for (i = 0; mem->keys && mem->keys[i]; i++) { (*keys)[i] = _hx509_private_key_ref(mem->keys[i]); if ((*keys)[i] == NULL) { while (--i >= 0) hx509_private_key_free(&(*keys)[i]); hx509_set_error_string(context, 0, ENOMEM, "out of memory"); return ENOMEM; } } (*keys)[i] = NULL; return 0; } static int mem_addkey(hx509_context context, hx509_certs certs, void *data, hx509_private_key key) { struct mem_data *mem = data; void *ptr; int i; for (i = 0; mem->keys && mem->keys[i]; i++) ; ptr = realloc(mem->keys, (i + 2) * sizeof(*mem->keys)); if (ptr == NULL) { hx509_set_error_string(context, 0, ENOMEM, "out of memory"); return ENOMEM; } mem->keys = ptr; mem->keys[i] = _hx509_private_key_ref(key); mem->keys[i + 1] = NULL; return 0; } static struct hx509_keyset_ops keyset_mem = { "MEMORY", 0, mem_init, NULL, mem_free, mem_add, NULL, mem_iter_start, mem_iter, mem_iter_end, NULL, mem_getkeys, mem_addkey }; void _hx509_ks_mem_register(hx509_context context) { _hx509_ks_register(context, &keyset_mem); } heimdal-7.5.0/lib/hx509/peer.c0000644000175000017500000001314012136107750013775 0ustar niknik/* * Copyright (c) 2006 - 2007 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Portions Copyright (c) 2009 Apple Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "hx_locl.h" /** * @page page_peer Hx509 crypto selecting functions * * Peer info structures are used togeter with hx509_crypto_select() to * select the best avaible crypto algorithm to use. * * See the library functions here: @ref hx509_peer */ /** * Allocate a new peer info structure an init it to default values. * * @param context A hx509 context. * @param peer return an allocated peer, free with hx509_peer_info_free(). * * @return An hx509 error code, see hx509_get_error_string(). * * @ingroup hx509_peer */ int hx509_peer_info_alloc(hx509_context context, hx509_peer_info *peer) { *peer = calloc(1, sizeof(**peer)); if (*peer == NULL) { hx509_set_error_string(context, 0, ENOMEM, "out of memory"); return ENOMEM; } return 0; } static void free_cms_alg(hx509_peer_info peer) { if (peer->val) { size_t i; for (i = 0; i < peer->len; i++) free_AlgorithmIdentifier(&peer->val[i]); free(peer->val); peer->val = NULL; peer->len = 0; } } /** * Free a peer info structure. * * @param peer peer info to be freed. * * @ingroup hx509_peer */ void hx509_peer_info_free(hx509_peer_info peer) { if (peer == NULL) return; if (peer->cert) hx509_cert_free(peer->cert); free_cms_alg(peer); memset(peer, 0, sizeof(*peer)); free(peer); } /** * Set the certificate that remote peer is using. * * @param peer peer info to update * @param cert cerificate of the remote peer. * * @return An hx509 error code, see hx509_get_error_string(). * * @ingroup hx509_peer */ int hx509_peer_info_set_cert(hx509_peer_info peer, hx509_cert cert) { if (peer->cert) hx509_cert_free(peer->cert); peer->cert = hx509_cert_ref(cert); return 0; } /** * Add an additional algorithm that the peer supports. * * @param context A hx509 context. * @param peer the peer to set the new algorithms for * @param val an AlgorithmsIdentier to add * * @return An hx509 error code, see hx509_get_error_string(). * * @ingroup hx509_peer */ int hx509_peer_info_add_cms_alg(hx509_context context, hx509_peer_info peer, const AlgorithmIdentifier *val) { void *ptr; int ret; ptr = realloc(peer->val, sizeof(peer->val[0]) * (peer->len + 1)); if (ptr == NULL) { hx509_set_error_string(context, 0, ENOMEM, "out of memory"); return ENOMEM; } peer->val = ptr; ret = copy_AlgorithmIdentifier(val, &peer->val[peer->len]); if (ret == 0) peer->len += 1; else hx509_set_error_string(context, 0, ret, "out of memory"); return ret; } /** * Set the algorithms that the peer supports. * * @param context A hx509 context. * @param peer the peer to set the new algorithms for * @param val array of supported AlgorithmsIdentiers * @param len length of array val. * * @return An hx509 error code, see hx509_get_error_string(). * * @ingroup hx509_peer */ int hx509_peer_info_set_cms_algs(hx509_context context, hx509_peer_info peer, const AlgorithmIdentifier *val, size_t len) { size_t i; free_cms_alg(peer); peer->val = calloc(len, sizeof(*peer->val)); if (peer->val == NULL) { peer->len = 0; hx509_set_error_string(context, 0, ENOMEM, "out of memory"); return ENOMEM; } peer->len = len; for (i = 0; i < len; i++) { int ret; ret = copy_AlgorithmIdentifier(&val[i], &peer->val[i]); if (ret) { hx509_clear_error_string(context); free_cms_alg(peer); return ret; } } return 0; } #if 0 /* * S/MIME */ int hx509_peer_info_parse_smime(hx509_peer_info peer, const heim_octet_string *data) { return 0; } int hx509_peer_info_unparse_smime(hx509_peer_info peer, heim_octet_string *data) { return 0; } /* * For storing hx509_peer_info to be able to cache them. */ int hx509_peer_info_parse(hx509_peer_info peer, const heim_octet_string *data) { return 0; } int hx509_peer_info_unparse(hx509_peer_info peer, heim_octet_string *data) { return 0; } #endif heimdal-7.5.0/lib/hx509/cms.c0000644000175000017500000012306213212137553013631 0ustar niknik/* * Copyright (c) 2003 - 2007 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "hx_locl.h" /** * @page page_cms CMS/PKCS7 message functions. * * CMS is defined in RFC 3369 and is an continuation of the RSA Labs * standard PKCS7. The basic messages in CMS is * * - SignedData * Data signed with private key (RSA, DSA, ECDSA) or secret * (symmetric) key * - EnvelopedData * Data encrypted with private key (RSA) * - EncryptedData * Data encrypted with secret (symmetric) key. * - ContentInfo * Wrapper structure including type and data. * * * See the library functions here: @ref hx509_cms */ #define ALLOC(X, N) (X) = calloc((N), sizeof(*(X))) #define ALLOC_SEQ(X, N) do { (X)->len = (N); ALLOC((X)->val, (N)); } while(0) /** * Wrap data and oid in a ContentInfo and encode it. * * @param oid type of the content. * @param buf data to be wrapped. If a NULL pointer is passed in, the * optional content field in the ContentInfo is not going be filled * in. * @param res the encoded buffer, the result should be freed with * der_free_octet_string(). * * @return Returns an hx509 error code. * * @ingroup hx509_cms */ int hx509_cms_wrap_ContentInfo(const heim_oid *oid, const heim_octet_string *buf, heim_octet_string *res) { ContentInfo ci; size_t size; int ret; memset(res, 0, sizeof(*res)); memset(&ci, 0, sizeof(ci)); ret = der_copy_oid(oid, &ci.contentType); if (ret) return ret; if (buf) { ALLOC(ci.content, 1); if (ci.content == NULL) { free_ContentInfo(&ci); return ENOMEM; } ci.content->data = malloc(buf->length); if (ci.content->data == NULL) { free_ContentInfo(&ci); return ENOMEM; } memcpy(ci.content->data, buf->data, buf->length); ci.content->length = buf->length; } ASN1_MALLOC_ENCODE(ContentInfo, res->data, res->length, &ci, &size, ret); free_ContentInfo(&ci); if (ret) return ret; if (res->length != size) _hx509_abort("internal ASN.1 encoder error"); return 0; } /** * Decode an ContentInfo and unwrap data and oid it. * * @param in the encoded buffer. * @param oid type of the content. * @param out data to be wrapped. * @param have_data since the data is optional, this flags show dthe * diffrence between no data and the zero length data. * * @return Returns an hx509 error code. * * @ingroup hx509_cms */ int hx509_cms_unwrap_ContentInfo(const heim_octet_string *in, heim_oid *oid, heim_octet_string *out, int *have_data) { ContentInfo ci; size_t size; int ret; memset(oid, 0, sizeof(*oid)); memset(out, 0, sizeof(*out)); ret = decode_ContentInfo(in->data, in->length, &ci, &size); if (ret) return ret; ret = der_copy_oid(&ci.contentType, oid); if (ret) { free_ContentInfo(&ci); return ret; } if (ci.content) { ret = der_copy_octet_string(ci.content, out); if (ret) { der_free_oid(oid); free_ContentInfo(&ci); return ret; } } else memset(out, 0, sizeof(*out)); if (have_data) *have_data = (ci.content != NULL) ? 1 : 0; free_ContentInfo(&ci); return 0; } #define CMS_ID_SKI 0 #define CMS_ID_NAME 1 static int fill_CMSIdentifier(const hx509_cert cert, int type, CMSIdentifier *id) { int ret; switch (type) { case CMS_ID_SKI: id->element = choice_CMSIdentifier_subjectKeyIdentifier; ret = _hx509_find_extension_subject_key_id(_hx509_get_cert(cert), &id->u.subjectKeyIdentifier); if (ret == 0) break; /* FALL THOUGH */ case CMS_ID_NAME: { hx509_name name; id->element = choice_CMSIdentifier_issuerAndSerialNumber; ret = hx509_cert_get_issuer(cert, &name); if (ret) return ret; ret = hx509_name_to_Name(name, &id->u.issuerAndSerialNumber.issuer); hx509_name_free(&name); if (ret) return ret; ret = hx509_cert_get_serialnumber(cert, &id->u.issuerAndSerialNumber.serialNumber); break; } default: _hx509_abort("CMS fill identifier with unknown type"); } return ret; } static int unparse_CMSIdentifier(hx509_context context, CMSIdentifier *id, char **str) { int ret = -1; *str = NULL; switch (id->element) { case choice_CMSIdentifier_issuerAndSerialNumber: { IssuerAndSerialNumber *iasn; char *serial, *name; iasn = &id->u.issuerAndSerialNumber; ret = _hx509_Name_to_string(&iasn->issuer, &name); if(ret) return ret; ret = der_print_hex_heim_integer(&iasn->serialNumber, &serial); if (ret) { free(name); return ret; } ret = asprintf(str, "certificate issued by %s with serial number %s", name, serial); free(name); free(serial); break; } case choice_CMSIdentifier_subjectKeyIdentifier: { KeyIdentifier *ki = &id->u.subjectKeyIdentifier; char *keyid; ssize_t len; len = hex_encode(ki->data, ki->length, &keyid); if (len < 0) return ENOMEM; ret = asprintf(str, "certificate with id %s", keyid); free(keyid); break; } default: ret = asprintf(str, "certificate have unknown CMSidentifier type"); break; } /* * In the following if, we check ret and *str which should be returned/set * by asprintf(3) in every branch of the switch statement. */ if (ret == -1 || *str == NULL) return ENOMEM; return 0; } static int find_CMSIdentifier(hx509_context context, CMSIdentifier *client, hx509_certs certs, time_t time_now, hx509_cert *signer_cert, int match) { hx509_query q; hx509_cert cert; Certificate c; int ret; memset(&c, 0, sizeof(c)); _hx509_query_clear(&q); *signer_cert = NULL; switch (client->element) { case choice_CMSIdentifier_issuerAndSerialNumber: q.serial = &client->u.issuerAndSerialNumber.serialNumber; q.issuer_name = &client->u.issuerAndSerialNumber.issuer; q.match = HX509_QUERY_MATCH_SERIALNUMBER|HX509_QUERY_MATCH_ISSUER_NAME; break; case choice_CMSIdentifier_subjectKeyIdentifier: q.subject_id = &client->u.subjectKeyIdentifier; q.match = HX509_QUERY_MATCH_SUBJECT_KEY_ID; break; default: hx509_set_error_string(context, 0, HX509_CMS_NO_RECIPIENT_CERTIFICATE, "unknown CMS identifier element"); return HX509_CMS_NO_RECIPIENT_CERTIFICATE; } q.match |= match; q.match |= HX509_QUERY_MATCH_TIME; if (time_now) q.timenow = time_now; else q.timenow = time(NULL); ret = hx509_certs_find(context, certs, &q, &cert); if (ret == HX509_CERT_NOT_FOUND) { char *str; ret = unparse_CMSIdentifier(context, client, &str); if (ret == 0) { hx509_set_error_string(context, 0, HX509_CMS_NO_RECIPIENT_CERTIFICATE, "Failed to find %s", str); } else hx509_clear_error_string(context); return HX509_CMS_NO_RECIPIENT_CERTIFICATE; } else if (ret) { hx509_set_error_string(context, HX509_ERROR_APPEND, HX509_CMS_NO_RECIPIENT_CERTIFICATE, "Failed to find CMS id in cert store"); return HX509_CMS_NO_RECIPIENT_CERTIFICATE; } *signer_cert = cert; return 0; } /** * Decode and unencrypt EnvelopedData. * * Extract data and parameteres from from the EnvelopedData. Also * supports using detached EnvelopedData. * * @param context A hx509 context. * @param certs Certificate that can decrypt the EnvelopedData * encryption key. * @param flags HX509_CMS_UE flags to control the behavior. * @param data pointer the structure the contains the DER/BER encoded * EnvelopedData stucture. * @param length length of the data that data point to. * @param encryptedContent in case of detached signature, this * contains the actual encrypted data, othersize its should be NULL. * @param time_now set the current time, if zero the library uses now as the date. * @param contentType output type oid, should be freed with der_free_oid(). * @param content the data, free with der_free_octet_string(). * * @return an hx509 error code. * * @ingroup hx509_cms */ int hx509_cms_unenvelope(hx509_context context, hx509_certs certs, int flags, const void *data, size_t length, const heim_octet_string *encryptedContent, time_t time_now, heim_oid *contentType, heim_octet_string *content) { heim_octet_string key; EnvelopedData ed; hx509_cert cert; AlgorithmIdentifier *ai; const heim_octet_string *enccontent; heim_octet_string *params, params_data; heim_octet_string ivec; size_t size; int ret, matched = 0, findflags = 0; size_t i; memset(&key, 0, sizeof(key)); memset(&ed, 0, sizeof(ed)); memset(&ivec, 0, sizeof(ivec)); memset(content, 0, sizeof(*content)); memset(contentType, 0, sizeof(*contentType)); if ((flags & HX509_CMS_UE_DONT_REQUIRE_KU_ENCIPHERMENT) == 0) findflags |= HX509_QUERY_KU_ENCIPHERMENT; ret = decode_EnvelopedData(data, length, &ed, &size); if (ret) { hx509_set_error_string(context, 0, ret, "Failed to decode EnvelopedData"); return ret; } if (ed.recipientInfos.len == 0) { ret = HX509_CMS_NO_RECIPIENT_CERTIFICATE; hx509_set_error_string(context, 0, ret, "No recipient info in enveloped data"); goto out; } enccontent = ed.encryptedContentInfo.encryptedContent; if (enccontent == NULL) { if (encryptedContent == NULL) { ret = HX509_CMS_NO_DATA_AVAILABLE; hx509_set_error_string(context, 0, ret, "Content missing from encrypted data"); goto out; } enccontent = encryptedContent; } else if (encryptedContent != NULL) { ret = HX509_CMS_NO_DATA_AVAILABLE; hx509_set_error_string(context, 0, ret, "Both internal and external encrypted data"); goto out; } cert = NULL; for (i = 0; i < ed.recipientInfos.len; i++) { KeyTransRecipientInfo *ri; char *str; int ret2; ri = &ed.recipientInfos.val[i]; ret = find_CMSIdentifier(context, &ri->rid, certs, time_now, &cert, HX509_QUERY_PRIVATE_KEY|findflags); if (ret) continue; matched = 1; /* found a matching certificate, let decrypt */ ret = _hx509_cert_private_decrypt(context, &ri->encryptedKey, &ri->keyEncryptionAlgorithm.algorithm, cert, &key); hx509_cert_free(cert); if (ret == 0) break; /* succuessfully decrypted cert */ cert = NULL; ret2 = unparse_CMSIdentifier(context, &ri->rid, &str); if (ret2 == 0) { hx509_set_error_string(context, HX509_ERROR_APPEND, ret, "Failed to decrypt with %s", str); free(str); } } if (!matched) { ret = HX509_CMS_NO_RECIPIENT_CERTIFICATE; hx509_set_error_string(context, 0, ret, "No private key matched any certificate"); goto out; } if (cert == NULL) { ret = HX509_CMS_NO_RECIPIENT_CERTIFICATE; hx509_set_error_string(context, HX509_ERROR_APPEND, ret, "No private key decrypted the transfer key"); goto out; } ret = der_copy_oid(&ed.encryptedContentInfo.contentType, contentType); if (ret) { hx509_set_error_string(context, 0, ret, "Failed to copy EnvelopedData content oid"); goto out; } ai = &ed.encryptedContentInfo.contentEncryptionAlgorithm; if (ai->parameters) { params_data.data = ai->parameters->data; params_data.length = ai->parameters->length; params = ¶ms_data; } else params = NULL; { hx509_crypto crypto; ret = hx509_crypto_init(context, NULL, &ai->algorithm, &crypto); if (ret) goto out; if (flags & HX509_CMS_UE_ALLOW_WEAK) hx509_crypto_allow_weak(crypto); if (params) { ret = hx509_crypto_set_params(context, crypto, params, &ivec); if (ret) { hx509_crypto_destroy(crypto); goto out; } } ret = hx509_crypto_set_key_data(crypto, key.data, key.length); if (ret) { hx509_crypto_destroy(crypto); hx509_set_error_string(context, 0, ret, "Failed to set key for decryption " "of EnvelopedData"); goto out; } ret = hx509_crypto_decrypt(crypto, enccontent->data, enccontent->length, ivec.length ? &ivec : NULL, content); hx509_crypto_destroy(crypto); if (ret) { hx509_set_error_string(context, 0, ret, "Failed to decrypt EnvelopedData"); goto out; } } out: free_EnvelopedData(&ed); der_free_octet_string(&key); if (ivec.length) der_free_octet_string(&ivec); if (ret) { der_free_oid(contentType); der_free_octet_string(content); } return ret; } /** * Encrypt end encode EnvelopedData. * * Encrypt and encode EnvelopedData. The data is encrypted with a * random key and the the random key is encrypted with the * certificates private key. This limits what private key type can be * used to RSA. * * @param context A hx509 context. * @param flags flags to control the behavior. * - HX509_CMS_EV_NO_KU_CHECK - Dont check KU on certificate * - HX509_CMS_EV_ALLOW_WEAK - Allow weak crytpo * - HX509_CMS_EV_ID_NAME - prefer issuer name and serial number * @param cert Certificate to encrypt the EnvelopedData encryption key * with. * @param data pointer the data to encrypt. * @param length length of the data that data point to. * @param encryption_type Encryption cipher to use for the bulk data, * use NULL to get default. * @param contentType type of the data that is encrypted * @param content the output of the function, * free with der_free_octet_string(). * * @return an hx509 error code. * * @ingroup hx509_cms */ int hx509_cms_envelope_1(hx509_context context, int flags, hx509_cert cert, const void *data, size_t length, const heim_oid *encryption_type, const heim_oid *contentType, heim_octet_string *content) { KeyTransRecipientInfo *ri; heim_octet_string ivec; heim_octet_string key; hx509_crypto crypto = NULL; int ret, cmsidflag; EnvelopedData ed; size_t size; memset(&ivec, 0, sizeof(ivec)); memset(&key, 0, sizeof(key)); memset(&ed, 0, sizeof(ed)); memset(content, 0, sizeof(*content)); if (encryption_type == NULL) encryption_type = &asn1_oid_id_aes_256_cbc; if ((flags & HX509_CMS_EV_NO_KU_CHECK) == 0) { ret = _hx509_check_key_usage(context, cert, 1 << 2, TRUE); if (ret) goto out; } ret = hx509_crypto_init(context, NULL, encryption_type, &crypto); if (ret) goto out; if (flags & HX509_CMS_EV_ALLOW_WEAK) hx509_crypto_allow_weak(crypto); ret = hx509_crypto_set_random_key(crypto, &key); if (ret) { hx509_set_error_string(context, 0, ret, "Create random key for EnvelopedData content"); goto out; } ret = hx509_crypto_random_iv(crypto, &ivec); if (ret) { hx509_set_error_string(context, 0, ret, "Failed to create a random iv"); goto out; } ret = hx509_crypto_encrypt(crypto, data, length, &ivec, &ed.encryptedContentInfo.encryptedContent); if (ret) { hx509_set_error_string(context, 0, ret, "Failed to encrypt EnvelopedData content"); goto out; } { AlgorithmIdentifier *enc_alg; enc_alg = &ed.encryptedContentInfo.contentEncryptionAlgorithm; ret = der_copy_oid(encryption_type, &enc_alg->algorithm); if (ret) { hx509_set_error_string(context, 0, ret, "Failed to set crypto oid " "for EnvelopedData"); goto out; } ALLOC(enc_alg->parameters, 1); if (enc_alg->parameters == NULL) { ret = ENOMEM; hx509_set_error_string(context, 0, ret, "Failed to allocate crypto paramaters " "for EnvelopedData"); goto out; } ret = hx509_crypto_get_params(context, crypto, &ivec, enc_alg->parameters); if (ret) { goto out; } } ALLOC_SEQ(&ed.recipientInfos, 1); if (ed.recipientInfos.val == NULL) { ret = ENOMEM; hx509_set_error_string(context, 0, ret, "Failed to allocate recipients info " "for EnvelopedData"); goto out; } ri = &ed.recipientInfos.val[0]; if (flags & HX509_CMS_EV_ID_NAME) { ri->version = 0; cmsidflag = CMS_ID_NAME; } else { ri->version = 2; cmsidflag = CMS_ID_SKI; } ret = fill_CMSIdentifier(cert, cmsidflag, &ri->rid); if (ret) { hx509_set_error_string(context, 0, ret, "Failed to set CMS identifier info " "for EnvelopedData"); goto out; } ret = hx509_cert_public_encrypt(context, &key, cert, &ri->keyEncryptionAlgorithm.algorithm, &ri->encryptedKey); if (ret) { hx509_set_error_string(context, HX509_ERROR_APPEND, ret, "Failed to encrypt transport key for " "EnvelopedData"); goto out; } /* * */ ed.version = 0; ed.originatorInfo = NULL; ret = der_copy_oid(contentType, &ed.encryptedContentInfo.contentType); if (ret) { hx509_set_error_string(context, 0, ret, "Failed to copy content oid for " "EnvelopedData"); goto out; } ed.unprotectedAttrs = NULL; ASN1_MALLOC_ENCODE(EnvelopedData, content->data, content->length, &ed, &size, ret); if (ret) { hx509_set_error_string(context, 0, ret, "Failed to encode EnvelopedData"); goto out; } if (size != content->length) _hx509_abort("internal ASN.1 encoder error"); out: if (crypto) hx509_crypto_destroy(crypto); if (ret) der_free_octet_string(content); der_free_octet_string(&key); der_free_octet_string(&ivec); free_EnvelopedData(&ed); return ret; } static int any_to_certs(hx509_context context, const SignedData *sd, hx509_certs certs) { int ret; size_t i; if (sd->certificates == NULL) return 0; for (i = 0; i < sd->certificates->len; i++) { heim_error_t error; hx509_cert c; c = hx509_cert_init_data(context, sd->certificates->val[i].data, sd->certificates->val[i].length, &error); if (c == NULL) { ret = heim_error_get_code(error); heim_release(error); return ret; } ret = hx509_certs_add(context, certs, c); hx509_cert_free(c); if (ret) return ret; } return 0; } static const Attribute * find_attribute(const CMSAttributes *attr, const heim_oid *oid) { size_t i; for (i = 0; i < attr->len; i++) if (der_heim_oid_cmp(&attr->val[i].type, oid) == 0) return &attr->val[i]; return NULL; } /** * Decode SignedData and verify that the signature is correct. * * @param context A hx509 context. * @param ctx a hx509 verify context. * @param flags to control the behaivor of the function. * - HX509_CMS_VS_NO_KU_CHECK - Don't check KeyUsage * - HX509_CMS_VS_ALLOW_DATA_OID_MISMATCH - allow oid mismatch * - HX509_CMS_VS_ALLOW_ZERO_SIGNER - no signer, see below. * @param data pointer to CMS SignedData encoded data. * @param length length of the data that data point to. * @param signedContent external data used for signature. * @param pool certificate pool to build certificates paths. * @param contentType free with der_free_oid(). * @param content the output of the function, free with * der_free_octet_string(). * @param signer_certs list of the cerficates used to sign this * request, free with hx509_certs_free(). * * @return an hx509 error code. * * @ingroup hx509_cms */ int hx509_cms_verify_signed(hx509_context context, hx509_verify_ctx ctx, unsigned int flags, const void *data, size_t length, const heim_octet_string *signedContent, hx509_certs pool, heim_oid *contentType, heim_octet_string *content, hx509_certs *signer_certs) { SignerInfo *signer_info; hx509_cert cert = NULL; hx509_certs certs = NULL; SignedData sd; size_t size; int ret, found_valid_sig; size_t i; *signer_certs = NULL; content->data = NULL; content->length = 0; contentType->length = 0; contentType->components = NULL; memset(&sd, 0, sizeof(sd)); ret = decode_SignedData(data, length, &sd, &size); if (ret) { hx509_set_error_string(context, 0, ret, "Failed to decode SignedData"); goto out; } if (sd.encapContentInfo.eContent == NULL && signedContent == NULL) { ret = HX509_CMS_NO_DATA_AVAILABLE; hx509_set_error_string(context, 0, ret, "No content data in SignedData"); goto out; } if (sd.encapContentInfo.eContent && signedContent) { ret = HX509_CMS_NO_DATA_AVAILABLE; hx509_set_error_string(context, 0, ret, "Both external and internal SignedData"); goto out; } if (sd.encapContentInfo.eContent) ret = der_copy_octet_string(sd.encapContentInfo.eContent, content); else ret = der_copy_octet_string(signedContent, content); if (ret) { hx509_set_error_string(context, 0, ret, "malloc: out of memory"); goto out; } ret = hx509_certs_init(context, "MEMORY:cms-cert-buffer", 0, NULL, &certs); if (ret) goto out; ret = hx509_certs_init(context, "MEMORY:cms-signer-certs", 0, NULL, signer_certs); if (ret) goto out; /* XXX Check CMS version */ ret = any_to_certs(context, &sd, certs); if (ret) goto out; if (pool) { ret = hx509_certs_merge(context, certs, pool); if (ret) goto out; } for (found_valid_sig = 0, i = 0; i < sd.signerInfos.len; i++) { heim_octet_string signed_data = { 0, 0 }; const heim_oid *match_oid; heim_oid decode_oid; signer_info = &sd.signerInfos.val[i]; match_oid = NULL; if (signer_info->signature.length == 0) { ret = HX509_CMS_MISSING_SIGNER_DATA; hx509_set_error_string(context, 0, ret, "SignerInfo %d in SignedData " "missing sigature", i); continue; } ret = find_CMSIdentifier(context, &signer_info->sid, certs, _hx509_verify_get_time(ctx), &cert, HX509_QUERY_KU_DIGITALSIGNATURE); if (ret) { /** * If HX509_CMS_VS_NO_KU_CHECK is set, allow more liberal * search for matching certificates by not considering * KeyUsage bits on the certificates. */ if ((flags & HX509_CMS_VS_NO_KU_CHECK) == 0) continue; ret = find_CMSIdentifier(context, &signer_info->sid, certs, _hx509_verify_get_time(ctx), &cert, 0); if (ret) continue; } if (signer_info->signedAttrs) { const Attribute *attr; CMSAttributes sa; heim_octet_string os; sa.val = signer_info->signedAttrs->val; sa.len = signer_info->signedAttrs->len; /* verify that sigature exists */ attr = find_attribute(&sa, &asn1_oid_id_pkcs9_messageDigest); if (attr == NULL) { ret = HX509_CRYPTO_SIGNATURE_MISSING; hx509_set_error_string(context, 0, ret, "SignerInfo have signed attributes " "but messageDigest (signature) " "is missing"); goto next_sigature; } if (attr->value.len != 1) { ret = HX509_CRYPTO_SIGNATURE_MISSING; hx509_set_error_string(context, 0, ret, "SignerInfo have more then one " "messageDigest (signature)"); goto next_sigature; } ret = decode_MessageDigest(attr->value.val[0].data, attr->value.val[0].length, &os, &size); if (ret) { hx509_set_error_string(context, 0, ret, "Failed to decode " "messageDigest (signature)"); goto next_sigature; } ret = _hx509_verify_signature(context, NULL, &signer_info->digestAlgorithm, content, &os); der_free_octet_string(&os); if (ret) { hx509_set_error_string(context, HX509_ERROR_APPEND, ret, "Failed to verify messageDigest"); goto next_sigature; } /* * Fetch content oid inside signedAttrs or set it to * id-pkcs7-data. */ attr = find_attribute(&sa, &asn1_oid_id_pkcs9_contentType); if (attr == NULL) { match_oid = &asn1_oid_id_pkcs7_data; } else { if (attr->value.len != 1) { ret = HX509_CMS_DATA_OID_MISMATCH; hx509_set_error_string(context, 0, ret, "More then one oid in signedAttrs"); goto next_sigature; } ret = decode_ContentType(attr->value.val[0].data, attr->value.val[0].length, &decode_oid, &size); if (ret) { hx509_set_error_string(context, 0, ret, "Failed to decode " "oid in signedAttrs"); goto next_sigature; } match_oid = &decode_oid; } ASN1_MALLOC_ENCODE(CMSAttributes, signed_data.data, signed_data.length, &sa, &size, ret); if (ret) { if (match_oid == &decode_oid) der_free_oid(&decode_oid); hx509_clear_error_string(context); goto next_sigature; } if (size != signed_data.length) _hx509_abort("internal ASN.1 encoder error"); } else { signed_data.data = content->data; signed_data.length = content->length; match_oid = &asn1_oid_id_pkcs7_data; } /** * If HX509_CMS_VS_ALLOW_DATA_OID_MISMATCH, allow * encapContentInfo mismatch with the oid in signedAttributes * (or if no signedAttributes where use, pkcs7-data oid). * This is only needed to work with broken CMS implementations * that doesn't follow CMS signedAttributes rules. */ if (der_heim_oid_cmp(match_oid, &sd.encapContentInfo.eContentType) && (flags & HX509_CMS_VS_ALLOW_DATA_OID_MISMATCH) == 0) { ret = HX509_CMS_DATA_OID_MISMATCH; hx509_set_error_string(context, 0, ret, "Oid in message mismatch from the expected"); } if (match_oid == &decode_oid) der_free_oid(&decode_oid); if (ret == 0) { ret = hx509_verify_signature(context, cert, &signer_info->signatureAlgorithm, &signed_data, &signer_info->signature); if (ret) hx509_set_error_string(context, HX509_ERROR_APPEND, ret, "Failed to verify signature in " "CMS SignedData"); } if (signed_data.data != NULL && content->data != signed_data.data) { free(signed_data.data); signed_data.data = NULL; } if (ret) goto next_sigature; /** * If HX509_CMS_VS_NO_VALIDATE flags is set, do not verify the * signing certificates and leave that up to the caller. */ if ((flags & HX509_CMS_VS_NO_VALIDATE) == 0) { ret = hx509_verify_path(context, ctx, cert, certs); if (ret) goto next_sigature; } ret = hx509_certs_add(context, *signer_certs, cert); if (ret) goto next_sigature; found_valid_sig++; next_sigature: if (cert) hx509_cert_free(cert); cert = NULL; } /** * If HX509_CMS_VS_ALLOW_ZERO_SIGNER is set, allow empty * SignerInfo (no signatures). If SignedData have no signatures, * the function will return 0 with signer_certs set to NULL. Zero * signers is allowed by the standard, but since its only useful * in corner cases, it make into a flag that the caller have to * turn on. */ if (sd.signerInfos.len == 0 && (flags & HX509_CMS_VS_ALLOW_ZERO_SIGNER)) { if (*signer_certs) hx509_certs_free(signer_certs); } else if (found_valid_sig == 0) { if (ret == 0) { ret = HX509_CMS_SIGNER_NOT_FOUND; hx509_set_error_string(context, 0, ret, "No signers where found"); } goto out; } ret = der_copy_oid(&sd.encapContentInfo.eContentType, contentType); if (ret) { hx509_clear_error_string(context); goto out; } out: free_SignedData(&sd); if (certs) hx509_certs_free(&certs); if (ret) { if (content->data) der_free_octet_string(content); if (*signer_certs) hx509_certs_free(signer_certs); der_free_oid(contentType); der_free_octet_string(content); } return ret; } static int add_one_attribute(Attribute **attr, unsigned int *len, const heim_oid *oid, heim_octet_string *data) { void *d; int ret; d = realloc(*attr, sizeof((*attr)[0]) * (*len + 1)); if (d == NULL) return ENOMEM; (*attr) = d; ret = der_copy_oid(oid, &(*attr)[*len].type); if (ret) return ret; ALLOC_SEQ(&(*attr)[*len].value, 1); if ((*attr)[*len].value.val == NULL) { der_free_oid(&(*attr)[*len].type); return ENOMEM; } (*attr)[*len].value.val[0].data = data->data; (*attr)[*len].value.val[0].length = data->length; *len += 1; return 0; } /** * Decode SignedData and verify that the signature is correct. * * @param context A hx509 context. * @param flags * @param eContentType the type of the data. * @param data data to sign * @param length length of the data that data point to. * @param digest_alg digest algorithm to use, use NULL to get the * default or the peer determined algorithm. * @param cert certificate to use for sign the data. * @param peer info about the peer the message to send the message to, * like what digest algorithm to use. * @param anchors trust anchors that the client will use, used to * polulate the certificates included in the message * @param pool certificates to use in try to build the path to the * trust anchors. * @param signed_data the output of the function, free with * der_free_octet_string(). * * @return Returns an hx509 error code. * * @ingroup hx509_cms */ int hx509_cms_create_signed_1(hx509_context context, int flags, const heim_oid *eContentType, const void *data, size_t length, const AlgorithmIdentifier *digest_alg, hx509_cert cert, hx509_peer_info peer, hx509_certs anchors, hx509_certs pool, heim_octet_string *signed_data) { hx509_certs certs; int ret = 0; signed_data->data = NULL; signed_data->length = 0; ret = hx509_certs_init(context, "MEMORY:certs", 0, NULL, &certs); if (ret) return ret; ret = hx509_certs_add(context, certs, cert); if (ret) goto out; ret = hx509_cms_create_signed(context, flags, eContentType, data, length, digest_alg, certs, peer, anchors, pool, signed_data); out: hx509_certs_free(&certs); return ret; } struct sigctx { SignedData sd; const AlgorithmIdentifier *digest_alg; const heim_oid *eContentType; heim_octet_string content; hx509_peer_info peer; int cmsidflag; int leafonly; hx509_certs certs; hx509_certs anchors; hx509_certs pool; }; static int sig_process(hx509_context context, void *ctx, hx509_cert cert) { struct sigctx *sigctx = ctx; heim_octet_string buf, sigdata = { 0, NULL }; SignerInfo *signer_info = NULL; AlgorithmIdentifier digest; size_t size; void *ptr; int ret; SignedData *sd = &sigctx->sd; hx509_path path; memset(&digest, 0, sizeof(digest)); memset(&path, 0, sizeof(path)); if (_hx509_cert_private_key(cert) == NULL) { hx509_set_error_string(context, 0, HX509_PRIVATE_KEY_MISSING, "Private key missing for signing"); return HX509_PRIVATE_KEY_MISSING; } if (sigctx->digest_alg) { ret = copy_AlgorithmIdentifier(sigctx->digest_alg, &digest); if (ret) hx509_clear_error_string(context); } else { ret = hx509_crypto_select(context, HX509_SELECT_DIGEST, _hx509_cert_private_key(cert), sigctx->peer, &digest); } if (ret) goto out; /* * Allocate on more signerInfo and do the signature processing */ ptr = realloc(sd->signerInfos.val, (sd->signerInfos.len + 1) * sizeof(sd->signerInfos.val[0])); if (ptr == NULL) { ret = ENOMEM; goto out; } sd->signerInfos.val = ptr; signer_info = &sd->signerInfos.val[sd->signerInfos.len]; memset(signer_info, 0, sizeof(*signer_info)); signer_info->version = 1; ret = fill_CMSIdentifier(cert, sigctx->cmsidflag, &signer_info->sid); if (ret) { hx509_clear_error_string(context); goto out; } signer_info->signedAttrs = NULL; signer_info->unsignedAttrs = NULL; ret = copy_AlgorithmIdentifier(&digest, &signer_info->digestAlgorithm); if (ret) { hx509_clear_error_string(context); goto out; } /* * If it isn't pkcs7-data send signedAttributes */ if (der_heim_oid_cmp(sigctx->eContentType, &asn1_oid_id_pkcs7_data) != 0) { CMSAttributes sa; heim_octet_string sig; ALLOC(signer_info->signedAttrs, 1); if (signer_info->signedAttrs == NULL) { ret = ENOMEM; goto out; } ret = _hx509_create_signature(context, NULL, &digest, &sigctx->content, NULL, &sig); if (ret) goto out; ASN1_MALLOC_ENCODE(MessageDigest, buf.data, buf.length, &sig, &size, ret); der_free_octet_string(&sig); if (ret) { hx509_clear_error_string(context); goto out; } if (size != buf.length) _hx509_abort("internal ASN.1 encoder error"); ret = add_one_attribute(&signer_info->signedAttrs->val, &signer_info->signedAttrs->len, &asn1_oid_id_pkcs9_messageDigest, &buf); if (ret) { free(buf.data); hx509_clear_error_string(context); goto out; } ASN1_MALLOC_ENCODE(ContentType, buf.data, buf.length, sigctx->eContentType, &size, ret); if (ret) goto out; if (size != buf.length) _hx509_abort("internal ASN.1 encoder error"); ret = add_one_attribute(&signer_info->signedAttrs->val, &signer_info->signedAttrs->len, &asn1_oid_id_pkcs9_contentType, &buf); if (ret) { free(buf.data); hx509_clear_error_string(context); goto out; } sa.val = signer_info->signedAttrs->val; sa.len = signer_info->signedAttrs->len; ASN1_MALLOC_ENCODE(CMSAttributes, sigdata.data, sigdata.length, &sa, &size, ret); if (ret) { hx509_clear_error_string(context); goto out; } if (size != sigdata.length) _hx509_abort("internal ASN.1 encoder error"); } else { sigdata.data = sigctx->content.data; sigdata.length = sigctx->content.length; } { AlgorithmIdentifier sigalg; ret = hx509_crypto_select(context, HX509_SELECT_PUBLIC_SIG, _hx509_cert_private_key(cert), sigctx->peer, &sigalg); if (ret) goto out; ret = _hx509_create_signature(context, _hx509_cert_private_key(cert), &sigalg, &sigdata, &signer_info->signatureAlgorithm, &signer_info->signature); free_AlgorithmIdentifier(&sigalg); if (ret) goto out; } sigctx->sd.signerInfos.len++; signer_info = NULL; /* * Provide best effort path */ if (sigctx->certs) { unsigned int i; if (sigctx->pool && sigctx->leafonly == 0) { _hx509_calculate_path(context, HX509_CALCULATE_PATH_NO_ANCHOR, time(NULL), sigctx->anchors, 0, cert, sigctx->pool, &path); } else _hx509_path_append(context, &path, cert); for (i = 0; i < path.len; i++) { /* XXX remove dups */ ret = hx509_certs_add(context, sigctx->certs, path.val[i]); if (ret) { hx509_clear_error_string(context); goto out; } } } out: if (signer_info) free_SignerInfo(signer_info); if (sigdata.data != sigctx->content.data) der_free_octet_string(&sigdata); _hx509_path_free(&path); free_AlgorithmIdentifier(&digest); return ret; } static int cert_process(hx509_context context, void *ctx, hx509_cert cert) { struct sigctx *sigctx = ctx; const unsigned int i = sigctx->sd.certificates->len; void *ptr; int ret; ptr = realloc(sigctx->sd.certificates->val, (i + 1) * sizeof(sigctx->sd.certificates->val[0])); if (ptr == NULL) return ENOMEM; sigctx->sd.certificates->val = ptr; ret = hx509_cert_binary(context, cert, &sigctx->sd.certificates->val[i]); if (ret == 0) sigctx->sd.certificates->len++; return ret; } static int cmp_AlgorithmIdentifier(const AlgorithmIdentifier *p, const AlgorithmIdentifier *q) { return der_heim_oid_cmp(&p->algorithm, &q->algorithm); } int hx509_cms_create_signed(hx509_context context, int flags, const heim_oid *eContentType, const void *data, size_t length, const AlgorithmIdentifier *digest_alg, hx509_certs certs, hx509_peer_info peer, hx509_certs anchors, hx509_certs pool, heim_octet_string *signed_data) { unsigned int i, j; hx509_name name; int ret; size_t size; struct sigctx sigctx; memset(&sigctx, 0, sizeof(sigctx)); memset(&name, 0, sizeof(name)); if (eContentType == NULL) eContentType = &asn1_oid_id_pkcs7_data; sigctx.digest_alg = digest_alg; sigctx.content.data = rk_UNCONST(data); sigctx.content.length = length; sigctx.eContentType = eContentType; sigctx.peer = peer; /** * Use HX509_CMS_SIGNATURE_ID_NAME to preferred use of issuer name * and serial number if possible. Otherwise subject key identifier * will preferred. */ if (flags & HX509_CMS_SIGNATURE_ID_NAME) sigctx.cmsidflag = CMS_ID_NAME; else sigctx.cmsidflag = CMS_ID_SKI; /** * Use HX509_CMS_SIGNATURE_LEAF_ONLY to only request leaf * certificates to be added to the SignedData. */ sigctx.leafonly = (flags & HX509_CMS_SIGNATURE_LEAF_ONLY) ? 1 : 0; /** * Use HX509_CMS_NO_CERTS to make the SignedData contain no * certificates, overrides HX509_CMS_SIGNATURE_LEAF_ONLY. */ if ((flags & HX509_CMS_SIGNATURE_NO_CERTS) == 0) { ret = hx509_certs_init(context, "MEMORY:certs", 0, NULL, &sigctx.certs); if (ret) return ret; } sigctx.anchors = anchors; sigctx.pool = pool; sigctx.sd.version = CMSVersion_v3; der_copy_oid(eContentType, &sigctx.sd.encapContentInfo.eContentType); /** * Use HX509_CMS_SIGNATURE_DETACHED to create detached signatures. */ if ((flags & HX509_CMS_SIGNATURE_DETACHED) == 0) { ALLOC(sigctx.sd.encapContentInfo.eContent, 1); if (sigctx.sd.encapContentInfo.eContent == NULL) { hx509_clear_error_string(context); ret = ENOMEM; goto out; } sigctx.sd.encapContentInfo.eContent->data = malloc(length); if (sigctx.sd.encapContentInfo.eContent->data == NULL) { hx509_clear_error_string(context); ret = ENOMEM; goto out; } memcpy(sigctx.sd.encapContentInfo.eContent->data, data, length); sigctx.sd.encapContentInfo.eContent->length = length; } /** * Use HX509_CMS_SIGNATURE_NO_SIGNER to create no sigInfo (no * signatures). */ if ((flags & HX509_CMS_SIGNATURE_NO_SIGNER) == 0) { ret = hx509_certs_iter_f(context, certs, sig_process, &sigctx); if (ret) goto out; } if (sigctx.sd.signerInfos.len) { /* * For each signerInfo, collect all different digest types. */ for (i = 0; i < sigctx.sd.signerInfos.len; i++) { AlgorithmIdentifier *di = &sigctx.sd.signerInfos.val[i].digestAlgorithm; for (j = 0; j < sigctx.sd.digestAlgorithms.len; j++) if (cmp_AlgorithmIdentifier(di, &sigctx.sd.digestAlgorithms.val[j]) == 0) break; if (j == sigctx.sd.digestAlgorithms.len) { ret = add_DigestAlgorithmIdentifiers(&sigctx.sd.digestAlgorithms, di); if (ret) { hx509_clear_error_string(context); goto out; } } } } /* * Add certs we think are needed, build as part of sig_process */ if (sigctx.certs) { ALLOC(sigctx.sd.certificates, 1); if (sigctx.sd.certificates == NULL) { hx509_clear_error_string(context); ret = ENOMEM; goto out; } ret = hx509_certs_iter_f(context, sigctx.certs, cert_process, &sigctx); if (ret) goto out; } ASN1_MALLOC_ENCODE(SignedData, signed_data->data, signed_data->length, &sigctx.sd, &size, ret); if (ret) { hx509_clear_error_string(context); goto out; } if (signed_data->length != size) _hx509_abort("internal ASN.1 encoder error"); out: hx509_certs_free(&sigctx.certs); free_SignedData(&sigctx.sd); return ret; } int hx509_cms_decrypt_encrypted(hx509_context context, hx509_lock lock, const void *data, size_t length, heim_oid *contentType, heim_octet_string *content) { heim_octet_string cont; CMSEncryptedData ed; AlgorithmIdentifier *ai; int ret; memset(content, 0, sizeof(*content)); memset(&cont, 0, sizeof(cont)); ret = decode_CMSEncryptedData(data, length, &ed, NULL); if (ret) { hx509_set_error_string(context, 0, ret, "Failed to decode CMSEncryptedData"); return ret; } if (ed.encryptedContentInfo.encryptedContent == NULL) { ret = HX509_CMS_NO_DATA_AVAILABLE; hx509_set_error_string(context, 0, ret, "No content in EncryptedData"); goto out; } ret = der_copy_oid(&ed.encryptedContentInfo.contentType, contentType); if (ret) { hx509_clear_error_string(context); goto out; } ai = &ed.encryptedContentInfo.contentEncryptionAlgorithm; if (ai->parameters == NULL) { ret = HX509_ALG_NOT_SUPP; hx509_clear_error_string(context); goto out; } ret = _hx509_pbe_decrypt(context, lock, ai, ed.encryptedContentInfo.encryptedContent, &cont); if (ret) goto out; *content = cont; out: if (ret) { if (cont.data) free(cont.data); } free_CMSEncryptedData(&ed); return ret; } heimdal-7.5.0/lib/hx509/ChangeLog0000644000175000017500000021616012136107747014465 0ustar niknik2008-07-14 Love Hörnquist Åstrand * hxtool.c: Break out print_eval_types(). 2008-06-21 Love Hörnquist Åstrand * ks_p12.c: pass in time_now to unevelope * cms.c: Pass in time_now to unevelope, us verify context time in verify_signed. 2008-05-23 Love Hörnquist Åstrand * hx_locl.h: Include for TYPE_MAX defines. 2008-04-29 Love Hörnquist Åstrand * sel-lex.l: Use _hx509_sel_yyerror() instead of error_message(). 2008-04-20 Love Hörnquist Åstrand * sel-lex.l: Include 2008-04-17 Love Hörnquist Åstrand * Makefile.am: Update make-proto usage. 2008-04-15 Love Hörnquist Åstrand * ca.c: BasicConstraints.pathLenConstraint unsigned int. * sel-lex.l: Prefix sel_error with _hx509_ since its global on platforms w/o symbol versioning. * sel.h: rename yyerror to sel_yyerror in the whole library, not just the lexer * sel-lex.l: rename yyerror to sel_yyerror in the whole library, not just the lexer 2008-04-14 Love Hörnquist Åstrand * sel-lex.l: Rename yyerror to sel_yyerror and make it static. 2008-04-08 Love Hörnquist Åstrand * hx509.h: Make self-standing by including missing files. 2008-04-07 Love Hörnquist Åstrand * ks_p11.c: Use unsigned where appropriate. * softp11.c: call va_start before using vsnprintf. * crypto.c: make refcount slightly more sane. * keyset.c: make refcount slightly more sane. * cert.c: make refcount slightly more sane. 2008-03-19 Love Hörnquist Åstrand * test_nist2.in: Try to find unzip. 2008-03-16 Love Hörnquist Åstrand * version-script.map: add missing symbols * spnego: Make delegated credentials delegated directly, Oleg Sharoiko pointed out that it always didnt work with the old code. Also add som missing cred and context pass-thou functions in the SPNEGO layer. 2008-03-14 Love Hörnquist Åstrand * rename to be more consistent, export for teting * Add language to support querying certificates to find a match. Support constructs like "1.3.6.1.5.2.3.5" IN %{certificate.eku} AND %{certificate.subject} TAILMATCH "C=SE". 2008-02-26 Love Hörnquist Åstrand * version-script.map: add hx509_pem_read * hxtool-commands.in: Add --pem to cms-verify-sd. * test_cms.in: Test verifying PEM signature files. * hxtool.c: Support verifying PEM signature files. 2008-02-25 Love Hörnquist Åstrand * Makefile.am: libhx509_la_OBJECTS depends on hx_locl.h 2008-02-11 Love Hörnquist Åstrand * Use ldap-prep (with libwind) to compare names 2008-01-27 Love Hörnquist Åstrand * cert.c (hx509_query_match_eku): update to support the NULL eku (reset), clearify the old behaivor with regards repetitive calls. * Add matching on EKU, validate EKUs, add hxtool matching glue, add check. Adapted from pach from Tim Miller of Mitre 2008-01-21 Love Hörnquist Åstrand * test_soft_pkcs11.c: use func for more C_ functions. 2008-01-18 Love Hörnquist Åstrand * version-script.map: Export hx509_free_error_string(). 2008-01-17 Love Hörnquist Åstrand * version-script.map: only export C_GetFunctionList * test_soft_pkcs11.c: use C_GetFunctionList * softp11.c: fix comment, remove label. * softp11.c: Add option app-fatal to control if softtoken should abort() on erroneous input from applications. 2008-01-16 Love Hörnquist Åstrand * test_pkcs11.in: Test password less certificates too * keyset.c: document HX509_CERTS_UNPROTECT_ALL * ks_file.c: Support HX509_CERTS_UNPROTECT_ALL. * hx509.h: Add HX509_CERTS_UNPROTECT_ALL. * test_soft_pkcs11.c: Only log in if needed. 2008-01-15 Love Hörnquist Åstrand * softp11.c: Support PINs to login to the store. * Makefile.am: add java pkcs11 test * test_java_pkcs11.in: first version of disable java test * softp11.c: Drop unused stuff. * cert.c: Spelling, Add hx509_cert_get_SPKI_AlgorithmIdentifier, remove unused stuff, add hx509_context to some functions. * softp11.c: Add more glue to figure out what keytype this certificate is using. 2008-01-14 Love Hörnquist Åstrand * test_pkcs11.in: test debug * Add a PKCS11 provider supporting signing and verifing sigatures. 2008-01-13 Love Hörnquist Åstrand * version-script.map: Replace hx509_name_to_der_name with hx509_name_binary. * print.c: make print_func static 2007-12-26 Love Hörnquist Åstrand * print.c: doxygen * env.c: doxygen * doxygen.c: add more groups * ca.c: doxygen. 2007-12-17 Love Hörnquist Åstrand * ca.c: doxygen 2007-12-16 Love Hörnquist Åstrand * error.c: doxygen 2007-12-15 Love Hörnquist Åstrand * More documentation * lock.c: Add page referance * keyset.c: some more documentation. * cms.c: Doxygen documentation. 2007-12-11 Love Hörnquist Åstrand * *.[ch]: More documentation 2007-12-09 Love Hörnquist Åstrand * handle refcount on NULL. * test_nist_pkcs12.in: drop echo -n, doesn't work with posix sh 2007-12-08 Love Hörnquist Åstrand * test_nist2.in: Print that this is version 2 of the tests * test_nist.in: Drop printing of $id. * hx509.h: Add HX509_VHN_F_ALLOW_NO_MATCH. * name.c: spelling. * cert.c: make work the doxygen. * name.c: fix doxygen compiling. * Makefile.am: add doxygen.c * doxygen.c: Add doxygen main page. * cert.c: Add doxygen. * revoke.c (_hx509_revoke_ref): new function. 2007-11-16 Love Hörnquist Åstrand * ks_keychain.c: Check if SecKeyGetCSPHandle needs prototype. 2007-08-16 Love Hörnquist Åstrand * data/nist-data: Make work on case senstive filesystems too. 2007-08-09 Love Hörnquist Åstrand * cert.c: match rfc822 contrains better, provide better error strings. 2007-08-08 Love Hörnquist Åstrand * cert.c: "self-signed doesn't count" doesn't apply to trust anchor certificate. make trust anchor check consistant. * revoke.c: make compile. * revoke.c (verify_crl): set error strings. * revoke.c (verify_crl): handle with the signer is the CRLsigner (shortcut). * cert.c: Fix NC, comment on how to use _hx509_check_key_usage. 2007-08-03 Love Hörnquist Åstrand * test_nist2.in, Makefile, test/nist*: Add nist pkits tests. * revoke.c: Update to use CERT_REVOKED error, shortcut out of OCSP checking when OCSP reply is a revocation reply. * hx509_err.et: Make CERT_REVOKED error OCSP/CRL agnostic. * name.c (_hx509_Name_to_string): make printableString handle space (0x20) diffrences as required by rfc3280. * revoke.c: Search for the right issuer when looking for the issuer of the CRL signer. 2007-08-02 Love Hörnquist Åstrand * revoke.c: Handle CRL signing certificate better, try to not revalidate invalid CRLs over and over. 2007-08-01 Love Hörnquist Åstrand * cms.c: remove stale comment. * test_nist.in: Unpack PKITS_data.zip and run tests. * test_nist_cert.in: Adapt to new nist pkits framework. * test_nist_pkcs12.in: Adapt to new nist pkits framework. * Makefile.am: clean PKITS_data 2007-07-16 Love Hörnquist Åstrand * Makefile.am: Add version-script.map to EXTRA_DIST 2007-07-12 Love Hörnquist Åstrand * Makefile.am: Add depenency on asn1_compile for asn1 built files. 2007-07-10 Love Hörnquist Åstrand * peer.c: update (c), indent. * Makefile.am: New library version. 2007-06-28 Love Hörnquist Åstrand * ks_p11.c: Add sha2 types. * ref/pkcs11.h: Sync with scute. * ref/pkcs11.h: Add sha2 CKM's. * print.c: Print authorityInfoAccess. * cert.c: Rename proxyCertInfo oid. * ca.c: Rename proxyCertInfo oid. * print.c: Rename proxyCertInfo oid. 2007-06-26 Love Hörnquist Åstrand * test_ca.in: Adapt to new request handling. * req.c: Allow export some of the request parameters. * hxtool-commands.in: Adapt to new request handling. * hxtool.c: Adapt to new request handling. * test_req.in: Adapt to new request handling. * version-script.map: Add initialize_hx_error_table_r. * req.c: Move _hx509_request_print here. * hxtool.c: use _hx509_request_print * version-script.map: Export more crap^W semiprivate functions. * hxtool.c: don't _hx509_abort * version-script.map: add missing ; 2007-06-25 Love Hörnquist Åstrand * cms.c: Use hx509_crypto_random_iv. * crypto.c: Split out the iv creation from hx509_crypto_encrypt since _hx509_pbe_encrypt needs to use the iv from the s2k function. * test_cert.in: Test PEM and DER FILE writing functionallity. * ks_file.c: Add writing DER certificates. * hxtool.c: Update to new hx509_pem_write(). * test_cms.in: test creation of PEM signeddata. * hx509.h: PEM struct/function declarations. * ks_file.c: Use PEM encoding/decoding functions. * file.c: PEM encode/decoding functions. * ks_file.c: Use hx509_pem_write. * version-script.map: Export some semi-private functions. * hxtool.c: Enable writing out signed data as a pem attachment. * hxtool-commands.in (cms-create-signed): add --pem * file.c (hx509_pem_write): Add. * test_ca.in: Issue and test null subject cert. * cert.c: Match is first component is in a CN=. * test_ca.in: Test hostname if first CN. * Makefile.am: Add version script. * version-script.map: Limited exported symbols. * test_ca.in: test --hostname. * test_chain.in: test max-depth * hx509.h: fixate HX509_HN_HOSTNAME at 0. * hxtool-commands.in: add --hostname add --max-depth * cert.c: Verify hostname and max-depth. * hxtool.c: Verify hostname and test max-depth. 2007-06-24 Love Hörnquist Åstrand * test_cms.in: Test --id-by-name. * hxtool-commands.in: add cms-create-sd --id-by-name * hxtool.c: Use HX509_CMS_SIGATURE_ID_NAME. * cms.c: Implement and use HX509_CMS_SIGATURE_ID_NAME. * hx509.h: Add HX509_CMS_SIGATURE_ID_NAME, use subject name for CMS.Identifier. hx509_hostname_type: add hostname type for matching. * cert.c (match_general_name): more strict rfc822Name matching. (hx509_verify_hostname): add hostname type for matching. 2007-06-19 Love Hörnquist Åstrand * hxtool.c: Make compile again. * hxtool.c: Added peap-server for to make windows peap clients happy. * hxtool.c: Unify parse_oid code. * hxtool.c: Implement --content-type. * hxtool-commands.in: Add content-type. * test_cert.in: more cert and keyset tests. 2007-06-18 Love Hörnquist Åstrand * revoke.c: Avoid stomping on NULL. * revoke.c: Avoid reusing i. * cert.c: Provide __attribute__ for _hx509_abort. * ks_file.c: Fail if not finding iv. * keyset.c: Avoid useing freed memory. * crypto.c: Free memory in failure case. * crypto.c: Free memory in failure case. 2007-06-12 Love Hörnquist Åstrand * *.c: Add hx509_cert_init_data and use everywhere * hx_locl.h: Now that KEYCHAIN:system-anchors is fast again, use that. * ks_keychain.c: Implement trust anchor support with SecTrustCopyAnchorCertificates. * keyset.c: Set ref to 1 for the new object. * cert.c: Fix logic for allow_default_trust_anchors * keyset.c: Add refcounting to keystores. * cert.c: Change logic for default trust anchors, make it be either default trust anchor, the user supplied, or non at all. 2007-06-08 Love Hörnquist Åstrand * Makefile.am: Add data/j.pem. * Makefile.am: Add test_windows.in. 2007-06-06 Love Hörnquist Åstrand * ks_keychain.c: rename functions, leaks less memory and more paranoia. * test_cms.in: Test cms peer-alg. * crypto.c (rsa_create_signature): make oid_id_pkcs1_rsaEncryption mean rsa-with-sha1 but oid oid_id_pkcs1_rsaEncryption in algorithm field. XXX should probably use another algorithmIdentifier for this. * peer.c: Make free function return void. * cms.c (hx509_cms_create_signed_1): Use hx509_peer_info to select the signature algorithm too. * hxtool-commands.in: Add cms-create-sd --peer-alg. * req.c: Use _hx509_crypto_default_sig_alg. * test_windows.in: Create crl, because everyone needs one. * Makefile.am: add wcrl.crl 2007-06-05 Love Hörnquist Åstrand * hx_locl.h: Disable KEYCHAIN for now, its slow. * cms.c: When we are not using pkcs7-data, avoid seing signedAttributes since some clients get upset by that (pkcs7 based or just plain broken). * ks_keychain.c: Provide rsa signatures. * ks_keychain.c: Limit the searches to the selected keychain. * ks_keychain.c: include -framework Security specific header files after #ifdef * ks_keychain.c: Find and attach private key (does not provide operations yet though). * ks_p11.c: Prefix rsa method with p11_ * ks_keychain.c: Allow opening a specific chain, making "system" special and be the system X509Anchors file. By not specifing any keychain ("KEYCHAIN:"), all keychains are probed. 2007-06-04 Love Hörnquist Åstrand * hxtool.c (verify): Friendlier error message. * cert.c: Read in and use default trust anchors if they exists. * hx_locl.h: Add concept of default_trust_anchors. * ks_keychain.c: Remove err(), remove extra empty comment, fix _iter function. * error.c (hx509_get_error_string): if the error code is not the one we expect, punt and use the default com_err/strerror string instead. * keyset.c (hx509_certs_merge): its ok to merge in the NULL set of certs. * test_windows.in: Fix status string. * ks_p12.c (store_func): free whole CertBag, not just the data part. * print.c: Check that the self-signed cert is really self-signed. * print.c: Use selfsigned for CRL DP whine, tell if its a self-signed. * print.c: Whine if its a non CA/proxy and doesn't have CRL DP. * ca.c: Add cRLSign to CA certs. * cert.c: Register NULL and KEYCHAIN. * ks_null.c: register the NULL keystore. * Makefile.am: Add ks_keychain.c and related libs. * test_crypto.in: Print certificate with utf8. * print.c: Leak less memory. * hxtool.c: Leak less memory. * print.c: Leak less memory, use functions that does same but more. * name.c (quote_string): don't sign extend the (signed) char to avoid printing too much, add an assert to check that we didn't overrun the buffer. * name.c: Use right element out of the CHOICE for printableString and utf8String * ks_keychain.c: Certificate only KeyChain backend. * name.c: Reset name before parsing it. 2007-06-03 Love Hörnquist Åstrand * revoke.c (hx509_crl_*): fix sizeof() mistakes to fix memory corruption. * hxtool.c: Add lifetime to crls. * hxtool-commands.in: Add lifetime to crls. * revoke.c: Add lifetime to crls. * test_ca.in: More crl checks. * revoke.c: Add revoking certs. * hxtool-commands.in: argument is certificates.. for crl-sign * hxtool.c (certificate_copy): free lock * revoke.c: Fix hx509_set_error_string calls, add hx509_crl_add_revoked_certs(), implement hx509_crl_{alloc,free}. * hxtool.c (crl_sign): free lock * cert.c (hx509_context_free): free querystat 2007-06-02 Love Hörnquist Åstrand * test_chain.in: test ocsp-verify * revoke.c (hx509_ocsp_verify): explain what its useful for and provide sane error message. * hx509_err.et: New error code, CERT_NOT_IN_OCSP * hxtool.c: New command ocsp-verify, check if ocsp contains all certs and are valid (exist and non expired). * hxtool-commands.in: New command ocsp-verify. 2007-06-01 Love Hörnquist Åstrand * test_ca.in: Create crl and verify that is works. * hxtool.c: Sign CRL command. * hx509.h: Add hx509_crl. * hxtool-commands.in: Add crl-sign commands. * revoke.c: Support to generate an empty CRL. * tst-crypto-select2: Switched default types. * tst-crypto-select1: Switched default types. * ca.c: Use default AlgorithmIdentifier. * cms.c: Use default AlgorithmIdentifier. * crypto.c: Provide default AlgorithmIdentifier and use them. * hx_locl.h: Provide default AlgorithmIdentifier. * keyset.c (hx509_certs_find): collects stats for queries. * cert.c: Sort and print more info. * hx_locl.h: Add querystat to hx509_context. * test_*.in: sprinle stat saveing * Makefile.am: Add stat and objdir. * collector.c (_hx509_collector_alloc): return error code instead of pointer. * hxtool.c: Add statistic hook. * ks_file.c: Update _hx509_collector_alloc prototype. * ks_p12.c: Update _hx509_collector_alloc prototype. * ks_p11.c: Update _hx509_collector_alloc prototype. * hxtool-commands.in: Add statistics hook. * cert.c: Statistics printing. * ks_p12.c: plug memory leak * ca.c (hx509_ca_tbs_add_crl_dp_uri): plug memory leak 2007-05-31 Love Hörnquist Åstrand * print.c: print utf8 type SAN's * Makefile.am: Fix windows client cert name. * test_windows.in: Add crl-uri for the ee certs. * print.c: Printf formating. * ca.c: Add glue for adding CRL dps. * test_ca.in: Readd the crl adding code, it works (somewhat) now. * print.c: Fix printing of CRL DPnames (I hate IMPLICIT encoded structures). * hxtool-commands.in: make ca and alias of certificate-sign 2007-05-30 Love Hörnquist Åstrand * crypto.c (hx509_crypto_select): copy AI to the right place. * hxtool-commands.in: Add ca --ms-upn. * hxtool.c: add --ms-upn and add more EKU's for pk-init client. * ca.c: Add hx509_ca_tbs_add_san_ms_upn and refactor code. * test_crypto.in: Resurect killed e. * test_crypto.in: check for aes256-cbc * tst-crypto-select7: check for aes256-cbc * test_windows.in: test windows stuff * hxtool.c: add ca --domain-controller option, add secret key option to avaible. * ca.c: Add hx509_ca_tbs_set_domaincontroller. * hxtool-commands.in: add ca --domain-controller * hxtool.c: hook for testing secrety key algs * crypto.c: Add selection code for secret key crypto. * hx509.h: Add HX509_SELECT_SECRET_ENC. 2007-05-13 Love Hörnquist Åstrand * ks_p11.c: add more mechtypes 2007-05-10 Love Hörnquist Åstrand * print.c: Indent. * hxtool-commands.in: add test-crypto command * hxtool.c: test crypto command * cms.c (hx509_cms_create_signed_1): if no eContentType is given, use pkcs7-data. * print.c: add Netscape cert comment * crypto.c: Try both the empty password and the NULL password (nothing vs the octet string \x00\x00). * print.c: Add some US Fed PKI oids. * ks_p11.c: Add some more hashes. 2007-04-24 Love Hörnquist Åstrand * hxtool.c (crypto_select): stop memory leak 2007-04-19 Love Hörnquist Åstrand * peer.c (hx509_peer_info_free): free memory used too * hxtool.c (crypto_select): only free peer if it was used. 2007-04-18 Love Hörnquist Åstrand * hxtool.c: free template * ks_mem.c (mem_free): free key array too * hxtool.c: free private key and tbs * hxtool.c (hxtool_ca): free signer * hxtool.c (crypto_available): free peer too. * ca.c (get_AuthorityKeyIdentifier): leak less memory * hxtool.c (hxtool_ca): free SPKI * hxtool.c (hxtool_ca): free cert * ks_mem.c (mem_getkeys): allocate one more the we have elements so its possible to store the NULL pointer at the end. 2007-04-16 Love Hörnquist Åstrand * Makefile.am: CLEANFILES += cert-null.pem cert-sub-ca2.pem 2007-02-05 Love Hörnquist Åstrand * ca.c: Disable CRLDistributionPoints for now, its IMPLICIT code in the asn1 parser. * print.c: Add some more \n's. 2007-02-03 Love Hörnquist Åstrand * file.c: Allow mapping using heim_octet_string. * hxtool.c: Add options to generate detached signatures. * cms.c: Add flags to generate detached signatures. * hx509.h: Flag to generate detached signatures. * test_cms.in: Support detached sigatures. * name.c (hx509_general_name_unparse): unparse the other GeneralName nametypes. * print.c: Use less printf. Use hx509_general_name_unparse. * cert.c: Fix printing and plug leak-on-error. 2007-01-31 Love Hörnquist Åstrand * test_ca.in: Add test for ca --crl-uri. * hxtool.c: Add ca --crl-uri. * hxtool-commands.in: add ca --crl-uri * ca.c: Code to set CRLDistributionPoints in certificates. * print.c: Check CRLDistributionPointNames. * name.c (hx509_general_name_unparse): function for unparsing GeneralName, only supports GeneralName.URI * cert.c (is_proxy_cert): free info if we wont return it. 2007-01-30 Love Hörnquist Åstrand * hxtool.c: Try to help how to use this command. 2007-01-21 Love Hörnquist Åstrand * switch to sha256 as default digest for signing 2007-01-20 Love Hörnquist Åstrand * test_ca.in: Really test sub-ca code, add basic constraints tests 2007-01-17 Love Hörnquist Åstrand * Makefile.am: Fix makefile problem. 2007-01-16 Love Hörnquist Åstrand * hxtool.c: Set num of bits before we generate the key. 2007-01-15 Love Hörnquist Åstrand * cms.c (hx509_cms_create_signed_1): use hx509_cert_binary * ks_p12.c (store_func): use hx509_cert_binary * ks_file.c (store_func): use hx509_cert_binary * cert.c (hx509_cert_binary): return binary encoded certificate (DER format) 2007-01-14 Love Hörnquist Åstrand * ca.c (hx509_ca_tbs_subject_expand): new function. * name.c (hx509_name_expand): if env is NULL, return directly * test_ca.in: test template handling * hx509.h: Add template flags. * Makefile.am: clean out new files * hxtool.c: Add certificate template processing, fix hx509_err usage. * hxtool-commands.in: Add certificate template processing. * ca.c: Add certificate template processing. Fix return messages from hx509_ca_tbs_add_eku. * cert.c: Export more stuff from certificate. 2007-01-13 Love Hörnquist Åstrand * ca.c: update (c) * ca.c: (hx509_ca_tbs_add_eku): filter out dups. * hxtool.c: Add type email and add email eku when using option --email. * Makefile.am: add env.c * name.c: Remove abort, add error handling. * test_name.c: test name expansion * name.c: add hx509_name_expand * env.c: key-value pair help functions 2007-01-12 Love Hörnquist Åstrand * ca.c: Don't issue certs with subject DN that is NULL and have no SANs * print.c: Fix previous test. * print.c: Check there is a SAN if subject DN is NULL. * test_ca.in: test email, null subject dn * hxtool.c: Allow setting parameters to private key generation. * hx_locl.h: Allow setting parameters to private key generation. * crypto.c: Allow setting parameters to private key generation. * hxtool.c (eval_types): add jid if user gave one * hxtool-commands.in (certificate-sign): add --jid * ca.c (hx509_ca_tbs_add_san_jid): Allow adding id-pkix-on-xmppAddr OtherName. * print.c: Print id-pkix-on-xmppAddr OtherName. 2007-01-11 Love Hörnquist Åstrand * no random, no RSA/DH tests * hxtool.c (info): print status of random generator * Makefile.am: remove files created by tests * error.c: constify * name.c: constify * revoke.c: constify * hx_locl.h: constify * keyset.c: constify * ks_p11.c: constify * hx_locl.h: make printinfo char * argument const. * cms.c: move _hx509_set_digest_alg from cms.c to crypto.c since its only used there. * crypto.c: remove no longer used stuff, move set_digest_alg here from cms.c since its only used here. * Makefile.am: add data/test-nopw.p12 to EXTRA_DIST 2007-01-10 Love Hörnquist Åstrand * print.c: BasicConstraints vs criticality bit is complicated and not really possible to evaluate on its own, silly RFC3280. * ca.c: Make basicConstraints critical if this is a CA. * print.c: fix the version vs extension test * print.c: More validation checks. * name.c (hx509_name_cmp): add 2007-01-09 Love Hörnquist Åstrand * ks_p11.c (collect_private_key): Missing CKA_MODULUS is ok too (XXX why should these be fetched given they are not used). * test_ca.in: rename all files to PEM files, since that is what they are. * hxtool.c: copy out the key with the self signed CA cert * Factor out private key operation out of the signing, operations, support import, export, and generation of private keys. Add support for writing PEM and PKCS12 files with private keys in them. * data/gen-req.sh: Generate a no password pkcs12 file. 2007-01-08 Love Hörnquist Åstrand * cms.c: Check for internal ASN1 encoder error. 2007-01-05 Love Hörnquist Åstrand * Makefile.am: Drop most of the pkcs11 files. * test_ca.in: test reissueing ca certificate (xxx time validAfter). * hxtool.c: Allow setting serialNumber (needed for reissuing certificates) Change --key argument to --out-key. * hxtool-commands.in (issue-certificate): Allow setting serialNumber (needed for reissuing certificates), Change --key argument to --out-key. * ref: Replace with Marcus Brinkmann of g10 Code GmbH pkcs11 headerfile that is compatible with GPL (file taken from scute) 2007-01-04 Love Hörnquist Åstrand * test_ca.in: Test to generate key and use them. * hxtool.c: handle other keys the pkcs10 requested keys * hxtool-commands.in: add generate key commands * req.c (_hx509_request_to_pkcs10): PKCS10 needs to have a subject * hxtool-commands.in: Spelling. * ca.c (hx509_ca_tbs_set_proxy): allow negative pathLenConstraint to signal no limit * ks_file.c: Try all formats on the binary file before giving up, this way we can handle binary rsa keys too. * data/key2.der: new test key 2007-01-04 David Love * Makefile.am (hxtool_LDADD): Add libasn1.la * hxtool.c (pcert_verify): Fix format string. 2006-12-31 Love Hörnquist Åstrand * hxtool.c: Allow setting path length * cert.c: Fix test for proxy certs chain length, it was too restrictive. * data: regen * data/openssl.cnf: (proxy_cert) make length 0 * test_ca.in: Issue a long living cert. * hxtool.c: add --lifetime to ca command. * hxtool-commands.in: add --lifetime to ca command. * ca.c: allow setting notBefore and notAfter. * test_ca.in: Test generation of proxy certificates. * ca.c: Allow generation of proxy certificates, always include BasicConstraints, fix error codes. * hxtool.c: Allow generation of proxy certificates. * test_name.c: make hx509_parse_name take a hx509_context. * name.c: Split building RDN to a separate function. 2006-12-30 Love Hörnquist Åstrand * Makefile.am: clean test_ca files. * test_ca.in: test issuing self-signed and CA certificates. * hxtool.c: Add bits to allow issuing self-signed and CA certificates. * hxtool-commands.in: Add bits to allow issuing self-signed and CA certificates. * ca.c: Add bits to allow issuing CA certificates. * revoke.c: use new OCSPSigning. * ca.c: Add Subject Key Identifier. * ca.c: Add Authority Key Identifier. * cert.c: Locally export _hx509_find_extension_subject_key_id. Handle AuthorityKeyIdentifier where only authorityCertSerialNumber and authorityCertSerialNumber is set. * hxtool-commands.in: Add dnsname and rfc822 SANs. * test_ca.in: Test dnsname and rfc822 SANs. * ca.c: Add dnsname and rfc822 SANs. * hxtool.c: Add dnsname and rfc822 SANs. * test_ca.in: test adding eku, ku and san to the certificate (https and pk-init) * hxtool.c: Add eku, ku and san to the certificate. * ca.c: Add eku, ku and san to the certificate. * hxtool-commands.in: Add --type and --pk-init-principal * ocsp.asn1: remove id-kp-OCSPSigning, its in rfc2459.asn1 now 2006-12-29 Love Hörnquist Åstrand * ca.c: Add KeyUsage extension. * Makefile.am: add ca.c, add sign-certificate tests. * crypto.c: Add _hx509_create_signature_bitstring. * hxtool-commands.in: Add the sign-certificate tool. * hxtool.c: Add the sign-certificate tool. * cert.c: Add HX509_QUERY_OPTION_KU_KEYCERTSIGN. * hx509.h: Add hx509_ca_tbs and HX509_QUERY_OPTION_KU_KEYCERTSIGN. * test_ca.in: Basic test of generating a pkcs10 request, signing it and verifying the chain. * ca.c: Naive certificate signer. 2006-12-28 Love Hörnquist Åstrand * hxtool.c: add hxtool_hex 2006-12-22 Love Hörnquist Åstrand * Makefile.am: use top_builddir for libasn1.la 2006-12-11 Love Hörnquist Åstrand * hxtool.c (print_certificate): print serial number. * name.c (no): add S=stateOrProvinceName 2006-12-09 Love Hörnquist Åstrand * crypto.c (_hx509_private_key_assign_rsa): set a default sig alg * ks_file.c (try_decrypt): pass down AlgorithmIdentifier that key uses to do sigatures so there is no need to hardcode RSA into this function. 2006-12-08 Love Hörnquist Åstrand * ks_file.c: Pass filename to the parse functions and use it in the error messages * test_chain.in: test proxy cert (third level) * hx509_err.et: fix errorstring for PROXY_CERT_NAME_WRONG * data: regen * Makefile.am: EXTRA_DIST: add data/proxy10-child-child-test.{key,crt} * data/gen-req.sh: Fix names and restrictions on the proxy certificates * cert.c: Clairfy and make proxy cert handling work for multiple levels, before it was too restrictive. More helpful error message. 2006-12-07 Love Hörnquist Åstrand * cert.c (check_key_usage): tell what keyusages are missing * print.c: Split OtherName printing code to a oid lookup and print function. * print.c (Time2string): print hour as hour not min * Makefile.am: CLEANFILES += test 2006-12-06 Love Hörnquist Åstrand * Makefile.am (EXTRA_DIST): add data/pkinit-proxy* files * Makefile.am (EXTRA_DIST): add tst-crypto* files * cert.c (hx509_query_match_issuer_serial): make a copy of the data * cert.c (hx509_query_match_issuer_serial): allow matching on issuer and serial num * cert.c (_hx509_calculate_path): add flag to allow leaving out trust anchor * cms.c (hx509_cms_create_signed_1): when building the path, omit the trust anchors. * crypto.c (rsa_create_signature): Abort when signature is longer, not shorter. * cms.c: Provide time to _hx509_calculate_path so we don't send no longer valid certs to our peer. * cert.c (find_parent): when checking for certs and its not a trust anchor, require time be in range. (_hx509_query_match_cert): Add time validity-testing to query mask * hx_locl.h: add time validity-testing to query mask * test_cms.in: Tests for CMS SignedData with incomplete chain from the signer. 2006-11-28 Love Hörnquist Åstrand * cms.c (hx509_cms_verify_signed): specify what signature we failed to verify * Makefile.am: Depend on LIB_com_err for AIX. * keyset.c: Remove anther strndup that causes AIX to fall over. * cert.c: Don't check the trust anchors expiration time since they are transported out of band, from RFC3820. * cms.c: sprinkle more error strings * crypto.c: sprinkle more error strings * hxtool.c: use unsigned int as counter to fit better with the asn1 compiler * crypto.c: use unsigned int as counter to fit better with the asn1 compiler 2006-11-27 Love Hörnquist Åstrand * cms.c: Remove trailing white space. * crypto.c: rewrite comment to make more sense * crypto.c (hx509_crypto_select): check sig_algs[j]->key_oid * hxtool-commands.in (crypto-available): add --type * crypto.c (hx509_crypto_available): let alg pass if its keyless * hxtool-commands.in: Expand crypto-select * cms.c: Rename hx509_select to hx509_crypto_select. * hxtool-commands.in: Add crypto-select and crypto-available. * hxtool.c: Add crypto-select and crypto-available. * crypto.c (hx509_crypto_available): use right index. (hx509_crypto_free_algs): new function * crypto.c (hx509_crypto_select): improve (hx509_crypto_available): new function 2006-11-26 Love Hörnquist Åstrand * cert.c: Sprinkle more error string and hx509_contexts. * cms.c: Sprinkle more error strings. * crypto.c: Sprinkle error string and hx509_contexts. * crypto.c: Add some more comments about how this works. * crypto.c (hx509_select): new function. * Makefile.am: add peer.c * hxtool.c: Update hx509_cms_create_signed_1. * hx_locl.h: add struct hx509_peer_info * peer.c: Allow selection of digest/sig-alg * cms.c: Allow selection of a better digest using hx509_peer_info. * revoke.c: Handle that _hx509_verify_signature takes a context. * cert.c: Handle that _hx509_verify_signature takes a context. 2006-11-25 Love Hörnquist Åstrand * cms.c: Sprinkle error strings. * crypto.c: Sprinkle context and error strings. 2006-11-24 Love Hörnquist Åstrand * name.c: Handle printing and parsing raw oids in name. 2006-11-23 Love Hörnquist Åstrand * cert.c (_hx509_calculate_path): allow to calculate optimistic path when we don't know the trust anchors, just follow the chain upward until we no longer find a parent or we hit the max limit. * cms.c (hx509_cms_create_signed_1): provide a best effort path to the trust anchors to be stored in the SignedData packet, if find parents until trust anchor or max length. * data: regen * data/gen-req.sh: Build pk-init proxy cert. 2006-11-16 Love Hörnquist Åstrand * error.c (hx509_get_error_string): Put ", " between strings in error message. 2006-11-13 Love Hörnquist Åstrand * data/openssl.cnf: Change realm to TEST.H5L.SE 2006-11-07 Love Hörnquist Åstrand * revoke.c: Sprinkle error strings. 2006-11-04 Love Hörnquist Åstrand * hx_locl.h: add context variable to cmp function. * cert.c (hx509_query_match_cmp_func): allow setting the match function. 2006-10-24 Love Hörnquist Åstrand * ks_p11.c: Return less EINVAL. * hx509_err.et: add more pkcs11 errors * hx509_err.et: more error-codes * revoke.c: Return less EINVAL. * ks_dir.c: sprinkel more hx509_set_error_string * ks_file.c: Return less EINVAL. * hxtool.c: Pass in context to _hx509_parse_private_key. * ks_file.c: Sprinkle more hx509_context so we can return propper errors. * hx509_err.et: add HX509_PARSING_KEY_FAILED * crypto.c: Sprinkle more hx509_context so we can return propper errors. * collector.c: No more EINVAL. * hx509_err.et: add HX509_LOCAL_ATTRIBUTE_MISSING * cert.c (hx509_cert_get_base_subject): one less EINVAL (_hx509_cert_private_decrypt): one less EINVAL 2006-10-22 Love Hörnquist Åstrand * collector.c: indent * hxtool.c: Try to not leak memory. * req.c: clean memory before free * crypto.c (_hx509_private_key2SPKI): indent * req.c: Try to not leak memory. 2006-10-21 Love Hörnquist Åstrand * test_crypto.in: Read 50 kilobyte random data * revoke.c: Try to not leak memory. * hxtool.c: Try to not leak memory. * crypto.c (hx509_crypto_destroy): free oid. * error.c: Clean error string on failure just to make sure. * cms.c: Try to not leak memory (again). * hxtool.c: use a sensable content type * cms.c: Try harder to free certificate. 2006-10-20 Love Hörnquist Åstrand * Makefile.am: Add make check data. 2006-10-19 Love Hörnquist Åstrand * ks_p11.c (p11_list_keys): make element of search_data[0] constants and set them later * Makefile.am: Add more files. 2006-10-17 Love Hörnquist Åstrand * ks_file.c: set ret, remember to free ivdata 2006-10-16 Love Hörnquist Åstrand * hx_locl.h: Include . * test_crypto.in: Test random-data. * hxtool.c: RAND_bytes() return 1 for cryptographic strong data, check for that. * Makefile.am: clean random-data * hxtool.c: Add random-data command, use sl_slc_help. * hxtool-commands.in: Add random-data. * ks_p12.c: Remember to release certs. * ks_p11.c: Remember to release certs. 2006-10-14 Love Hörnquist Åstrand * prefix der primitives with der_ * lock.c: Match the prompt type PROMPT exact. * hx_locl.h: Drop heim_any.h 2006-10-11 Love Hörnquist Åstrand * ks_p11.c (p11_release_module): j needs to be used as inter loop index. From Douglas Engert. * ks_file.c (parse_rsa_private_key): try all passwords and prompter. 2006-10-10 Love Hörnquist Åstrand * test_*.in: Parameterise the invocation of hxtool, so we can make it run under TESTS_ENVIRONMENT. From Andrew Bartlett 2006-10-08 Love Hörnquist Åstrand * test_crypto.in: Put all test stuck at 2006-09-25 since all their chains where valied then. * hxtool.c: Implement --time= option. * hxtool-commands.in: Add option time. * Makefile.am: test_name is a PROGRAM_TESTS * ks_p11.c: Return HX509_PKCS11_NO_SLOT when there are no slots and HX509_PKCS11_NO_TOKEN when there are no token. For use in PAM modules that want to detect when to use smartcard login and when not to. Patched based on code from Douglas Engert. * hx509_err.et: Add new pkcs11 related errors in a new section: keystore related error. Patched based on code from Douglas Engert. 2006-10-07 Love Hörnquist Åstrand * Makefile.am: Make depenency for slc built files just like everywhere else. * cert.c: Add all openssl algs and init asn1 et 2006-10-06 Love Hörnquist Åstrand * ks_file.c (parse_rsa_private_key): free type earlier. * ks_file.c (parse_rsa_private_key): free type after use * name.c (_hx509_Name_to_string): remove dup const 2006-10-02 Love Hörnquist Åstrand * Makefile.am: Add more libs to libhx509 2006-10-01 Love Hörnquist Åstrand * ks_p11.c: Fix double free's, NULL ptr de-reference, and conform better to pkcs11. From Douglas Engert. * ref: remove ^M, it breaks solaris 10s cc. From Harald Barth 2006-09-19 Love Hörnquist Åstrand * test_crypto.in: Bleichenbacher bad cert from Ralf-Philipp Weinmann and Andrew Pyshkin, pad right. * data: starfield test root cert and Ralf-Philipp and Andreis correctly padded bad cert 2006-09-15 Love Hörnquist Åstrand * test_crypto.in: Add test for yutaka certs. * cert.c: Add a strict rfc3280 verification flag. rfc3280 requires certificates to have KeyUsage.keyCertSign if they are to be used for signing of certificates, but the step in the verifiation is optional. * hxtool.c: Improve printing and error reporting. 2006-09-13 Love Hörnquist Åstrand * test_crypto.in,Makefile.am,data/bleichenbacher-{bad,good}.pem: test bleichenbacher from eay 2006-09-12 Love Hörnquist Åstrand * hxtool.c: Make common function for all getarg_strings and hx509_certs_append commonly used. * cms.c: HX509_CMS_UE_DONT_REQUIRE_KU_ENCIPHERMENT is a negative flag, treat it was such. 2006-09-11 Love Hörnquist Åstrand * req.c: Use the new add_GeneralNames function. * hx509.h: Add HX509_CMS_UE_DONT_REQUIRE_KU_ENCIPHERMENT. * ks_p12.c: Adapt to new signature of hx509_cms_unenvelope. * hxtool.c: Adapt to new signature of hx509_cms_unenvelope. * cms.c: Allow passing in encryptedContent and flag. Add new flag HX509_CMS_UE_DONT_REQUIRE_KU_ENCIPHERMENT. 2006-09-08 Love Hörnquist Åstrand * ks_p11.c: cast void * to char * when using it for %s formating in printf. * name.c: New function _hx509_Name_to_string. 2006-09-07 Love Hörnquist Åstrand * ks_file.c: Sprinkle error messages. * cms.c: Sprinkle even more error messages. * cms.c: Sprinkle some error messages. * cms.c (find_CMSIdentifier): only free string when we allocated one. * ks_p11.c: Don't build most of the pkcs11 module if there are no dlopen(). 2006-09-06 Love Hörnquist Åstrand * cms.c (hx509_cms_unenvelope): try to save the error string from find_CMSIdentifier so we have one more bit of information what went wrong. * hxtool.c: More pretty printing, make verify_signed return the error string from the library. * cms.c: Try returning what certificates failed to parse or be found. * ks_p11.c (p11_list_keys): fetch CKA_LABEL and use it to set the friendlyname for the certificate. 2006-09-05 Love Hörnquist Åstrand * crypto.c: check that there are no extra bytes in the checksum and that the parameters are NULL or the NULL-type. All to avoid having excess data that can be used to fake the signature. * hxtool.c: print keyusage * print.c: add hx509_cert_keyusage_print, simplify oid printing * cert.c: add _hx509_cert_get_keyusage * ks_p11.c: keep one session around for the whole life of the keyset * test_query.in: tests more selection * hxtool.c: improve pretty printing in print and query * hxtool{.c,-commands.in}: add selection on KU and printing to query * test_cms.in: Add cms test for digitalSignature and keyEncipherment certs. * name.c (no): Add serialNumber * ks_p11.c (p11_get_session): return better error messages 2006-09-04 Love Hörnquist Åstrand * ref: update to pkcs11 reference files 2.20 * ks_p11.c: add more mechflags * name.c (no): add OU and sort * revoke.c: pass context to _hx509_create_signature * ks_p11.c (p11_printinfo): print proper plural s * ks_p11.c: save the mechs supported when initing the token, print them in printinfo. * hx_locl.h: Include . * cms.c: pass context to _hx509_create_signature * req.c: pass context to _hx509_create_signature * keyset.c (hx509_certs_info): print information about the keyset. * hxtool.c (pcert_print) print keystore info when --info flag is given. * hxtool-commands.in: Add hxtool print --info. * test_query.in: Test hxtool print --info. * hx_locl.h (hx509_keyset_ops): add printinfo * crypto.c: Start to hang the private key operations of the private key, pass hx509_context to create_checksum. 2006-05-29 Love Hörnquist Åstrand * ks_p11.c: Iterate over all slots, not just the first/selected one. 2006-05-27 Love Hörnquist Åstrand * cert.c: Add release function for certifiates so backend knowns when its no longer used. * ks_p11.c: Add reference counting on certifiates, push out CK_SESSION_HANDLE from slot. * cms.c: sprinkle more hx509_clear_error_string 2006-05-22 Love Hörnquist Åstrand * ks_p11.c: Sprinkle some hx509_set_error_strings 2006-05-13 Love Hörnquist Åstrand * hxtool.c: Avoid shadowing. * revoke.c: Avoid shadowing. * ks_file.c: Avoid shadowing. * cert.c: Avoid shadowing. 2006-05-12 Love Hörnquist Åstrand * lock.c (hx509_prompt_hidden): reshuffle to avoid gcc warning * hx509.h: Reshuffle the prompter types, remove the hidden field. * lock.c (hx509_prompt_hidden): return if the prompt should be hidden or not * revoke.c (hx509_revoke_free): allow free of NULL. 2006-05-11 Love Hörnquist Åstrand * ks_file.c (file_init): Avoid shadowing ret (and thus avoiding crashing). * ks_dir.c: Implement DIR: caches useing FILE: caches. * ks_p11.c: Catch more errors. 2006-05-08 Love Hörnquist Åstrand * crypto.c (hx509_crypto_encrypt): free correctly in error path. From Andrew Bartlett. * crypto.c: If RAND_bytes fails, then we will attempt to double-free crypt->key.data. From Andrew Bartlett. 2006-05-05 Love Hörnquist Åstrand * name.c: Rename u_intXX_t to uintXX_t 2006-05-03 Love Hörnquist Åstrand * TODO: More to do about the about the PKCS11 code. * ks_p11.c: Use the prompter from the lock function. * lock.c: Deal with that hx509_prompt.reply is no longer a pointer. * hx509.h: Make hx509_prompt.reply not a pointer. 2006-05-02 Love Hörnquist Åstrand * keyset.c: Sprinkle setting error strings. * crypto.c: Sprinkle setting error strings. * collector.c: Sprinkle setting error strings. * cms.c: Sprinkle setting error strings. 2006-05-01 Love Hörnquist Åstrand * test_name.c: renamed one error code * name.c: renamed one error code * ks_p11.c: _hx509_set_cert_attribute changed signature * hxtool.c (pcert_print): use hx509_err so I can test it * error.c (hx509_set_error_stringv): clear errors on malloc failure * hx509_err.et: Add some more errors * cert.c: Sprinkle setting error strings. * cms.c: _hx509_path_append changed signature. * revoke.c: changed signature of _hx509_check_key_usage * keyset.c: changed signature of _hx509_query_match_cert * hx509.h: Add support for error strings. * cms.c: changed signature of _hx509_check_key_usage * Makefile.am: ibhx509_la_files += error.c * ks_file.c: Sprinkel setting error strings. * cert.c: Sprinkel setting error strings. * hx_locl.h: Add support for error strings. * error.c: Add string error handling functions. * keyset.c (hx509_certs_init): pass the right error code back 2006-04-30 Love Hörnquist Åstrand * revoke.c: Revert previous patch. (hx509_ocsp_verify): new function that returns the expiration of certificate in ocsp data-blob * cert.c: Reverse previous patch, lets do it another way. * cert.c (hx509_revoke_verify): update usage * revoke.c: Make compile. * revoke.c: Add the expiration time the crl/ocsp info expire * name.c: Add hx509_name_is_null_p * cert.c: remove _hx509_cert_private_sigature 2006-04-29 Love Hörnquist Åstrand * name.c: Expose more of Name. * hxtool.c (main): add missing argument to printf * data/openssl.cnf: Add EKU for the KDC certificate * cert.c (hx509_cert_get_base_subject): reject un-canon proxy certs, not the reverse (add_to_list): constify and fix argument order to copy_octet_string (hx509_cert_find_subjectAltName_otherName): make work 2006-04-28 Love Hörnquist Åstrand * data/{pkinit,kdc}.{crt,key}: pkinit certificates * data/gen-req.sh: Generate pkinit certificates. * data/openssl.cnf: Add pkinit glue. * cert.c (hx509_verify_hostname): implement stub function 2006-04-27 Love Hörnquist Åstrand * TODO: CRL delta support 2006-04-26 Love Hörnquist Åstrand * data/.cvsignore: ignore leftover from OpenSSL cert generation * hx509_err.et: Add name malformated error * name.c (hx509_parse_name): don't abort on error, rather return error * test_name.c: Test failure parsing name. * cert.c: When verifying certificates, store subject basename for later consumption. * test_name.c: test to parse and print name and check that they are the same. * name.c (hx509_parse_name): fix length argument to printf string * name.c (hx509_parse_name): fix length argument to stringtooid, 1 too short. * cert.c: remove debug printf's * name.c (hx509_parse_name): make compile pre c99 * data/gen-req.sh: OpenSSL have a serious issue of user confusion -subj in -ca takes the arguments in LDAP order. -subj for x509 takes it in x509 order. * cert.c (hx509_verify_path): handle the case where the where two proxy certs in a chain. * test_chain.in: enable two proxy certificates in a chain test * test_chain.in: tests proxy certificates * data: re-gen * data/gen-req.sh: build proxy certificates * data/openssl.cnf: add def for proxy10_cert * hx509_err.et: Add another proxy certificate error. * cert.c (hx509_verify_path): Need to mangle name to remove the CN of the subject, copying issuer only works for one level but is better then doing no checking at all. * hxtool.c: Add verify --allow-proxy-certificate. * hxtool-commands.in: add verify --allow-proxy-certificate * hx509_err.et: Add proxy certificate errors. * cert.c: Fix comment about subject name of proxy certificate. * test_chain.in: tests for proxy certs * data/gen-req.sh: gen proxy and non-proxy tests certificates * data/openssl.cnf: Add definition for proxy certs * data/*proxy-test.*: Add proxy certificates * cert.c (hx509_verify_path): verify proxy certificate have no san or ian * cert.c (hx509_verify_set_proxy_certificate): Add (*): rename policy cert to proxy cert * cert.c: Initial support for proxy certificates. 2006-04-24 Love Hörnquist Åstrand * hxtool.c: some error checking * name.c: Switch over to asn1 generaed oids. * TODO: merge with old todo file 2006-04-23 Love Hörnquist Åstrand * test_query.in: make quiet * test_req.in: SKIP test if there is no RSA support. * hxtool.c: print dh method too * test_chain.in: SKIP test if there is no RSA support. * test_cms.in: SKIP test if there is no RSA support. * test_nist.in: SKIP test if there is no RSA support. 2006-04-22 Love Hörnquist Åstrand * hxtool-commands.in: Allow passing in pool and anchor to signedData * hxtool.c: Allow passing in pool and anchor to signedData * test_cms.in: Test that certs in signed data is picked up. * hx_locl.h: Expose the path building function to internal functions. * cert.c: Expose the path building function to internal functions. * hxtool-commands.in: cms-envelope: Add support for choosing the encryption type * hxtool.c (cms_create_enveloped): Add support for choosing the encryption type * test_cms.in: Test generating des-ede3 aes-128 aes-256 enveloped data * crypto.c: Add names to cipher types. * cert.c (hx509_query_match_friendly_name): fix return value * data/gen-req.sh: generate tests for enveloped data using des-ede3 and aes256 * test_cms.in: add tests for enveloped data using des-ede3 and aes256 * cert.c (hx509_query_match_friendly_name): New function. 2006-04-21 Love Hörnquist Åstrand * ks_p11.c: Add support for parsing slot-number. * crypto.c (oid_private_rc2_40): simply * crypto.c: Use oids from asn1 generator. * ks_file.c (file_init): reset length when done with a part * test_cms.in: check with test.combined.crt. * data/gen-req.sh: Create test.combined.crt. * test_cms.in: Test signed data using keyfile that is encrypted. * ks_file.c: Remove (commented out) debug printf * ks_file.c (parse_rsa_private_key): use EVP_get_cipherbyname * ks_file.c (parse_rsa_private_key): make working for one password. * ks_file.c (parse_rsa_private_key): Implement enought for testing. * hx_locl.h: Add * ks_file.c: Add glue code for PEM encrypted password files. * test_cms.in: Add commeted out password protected PEM file, remove password for those tests that doesn't need it. * test_cms.in: adapt test now that we can use any certificate and trust anchor * collector.c: handle PEM RSA PRIVATE KEY files * cert.c: Remove unused function. * ks_dir.c: move code here from ks_file.c now that its no longer used. * ks_file.c: Add support for parsing unencrypted RSA PRIVATE KEY * crypto.c: Handle rsa private keys better. 2006-04-20 Love Hörnquist Åstrand * hxtool.c: Use hx509_cms_{,un}wrap_ContentInfo * cms.c: Make hx509_cms_{,un}wrap_ContentInfo usable in asn1 un-aware code. * cert.c (hx509_verify_path): if trust anchor is not self signed, don't check sig From Douglas Engert. * test_chain.in: test "sub-cert -> sub-ca" * crypto.c: Use the right length for the sha256 checksums. 2006-04-15 Love Hörnquist Åstrand * crypto.c: Fix breakage from sha256 code. * crypto.c: Add SHA256 support, and symbols for the other new SHA-2 types. 2006-04-14 Love Hörnquist Åstrand * test_cms.in: test rc2-40 rc2-64 rc2-128 enveloped data * data/test-enveloped-rc2-{40,64,128}: add tests cases for rc2 * cms.c: Update prototypes changes for hx509_crypto_[gs]et_params. * crypto.c: Break out the parameter handling code for encrypting data to handle RC2. Needed for Windows 2k pk-init support. 2006-04-04 Love Hörnquist Åstrand * Makefile.am: Split libhx509_la_SOURCES into build file and distributed files so we can avoid building prototypes for build-files. 2006-04-03 Love Hörnquist Åstrand * TODO: split certificate request into pkcs10 and CRMF * hxtool-commands.in: Add nonce flag to ocsp-fetch * hxtool.c: control sending nonce * hxtool.c (request_create): store the request in a file, no in bitbucket. * cert.c: expose print_cert_subject internally * hxtool.c: Add ocsp_print. * hxtool-commands.in: New command "ocsp-print". * hx_locl.h: Include . * revoke.c (verify_ocsp): require issuer to match too. (free_ocsp): new function (hx509_revoke_ocsp_print): new function, print ocsp reply * Makefile.am: build CRMF files * data/key.der: needed for cert request test * test_req.in: adapt to rename of pkcs10-create to request-create * hxtool.c: adapt to rename of pkcs10-create to request-create * hxtool-commands.in: Rename pkcs10-create to request-create * crypto.c: (_hx509_parse_private_key): Avoid crashing on bad input. * hxtool.c (pkcs10_create): use opt->subject_string * hxtool-commands.in: Add pkcs10-create --subject * Makefile.am: Add test_req to tests. * test_req.in: Test for pkcs10 commands. * name.c (hx509_parse_name): new function. * hxtool.c (pkcs10_create): implement * hxtool-commands.in (pkcs10-create): Add arguments * crypto.c: Add _hx509_private_key2SPKI and support functions (only support RSA for now). 2006-04-02 Love Hörnquist Åstrand * hxtool-commands.in: Add pkcs10-create command. * hx509.h: Add hx509_request. * TODO: more stuff * Makefile.am: Add req.c * req.c: Create certificate requests, prototype converts the request in a pkcs10 packet. * hxtool.c: Add pkcs10_create * name.c (hx509_name_copy): new function. 2006-04-01 Love Hörnquist Åstrand * TODO: fill out what do * hxtool-commands.in: add pkcs10-print * hx_locl.h: Include . * pkcs10.asn1: PKCS#10 * hxtool.c (pkcs10_print): new function. * test_chain.in: test ocsp keyhash * data: generate ocsp keyhash version too * revoke.c (load_ocsp): test that we got back a BasicReponse * ocsp.asn1: Add asn1_id_pkix_ocsp*. * Makefile.am: Add asn1_id_pkix_ocsp*. * cert.c: Add HX509_QUERY_MATCH_KEY_HASH_SHA1 * hx_locl.h: Add HX509_QUERY_MATCH_KEY_HASH_SHA1 * revoke.c: Support OCSPResponderID.byKey, indent. * revoke.c (hx509_ocsp_request): Add nonce to ocsp request. * hxtool.c: Add nonce to ocsp request. * test_chain.in: Added crl tests * data/nist-data: rename missing-crl to missing-revoke * data: make ca use openssl ca command so we can add ocsp tests, and regen certs * test_chain.in: Add revoked ocsp cert test * cert.c: rename missing-crl to missing-revoke * revoke.c: refactor code, fix a un-init-ed variable * test_chain.in: rename missing-crl to missing-revoke add ocsp tests * test_cms.in: rename missing-crl to missing-revoke * hxtool.c: rename missing-crl to missing-revoke * hxtool-commands.in: rename missing-crl to missing-revoke * revoke.c: Plug one memory leak. * revoke.c: Renamed generic CRL related errors. * hx509_err.et: Comments and renamed generic CRL related errors * revoke.c: Add ocsp checker. * ocsp.asn1: Add id-kp-OCSPSigning * hxtool-commands.in: add url-path argument to ocsp-fetch * hxtool.c: implement ocsp-fetch * cert.c: Use HX509_DEFAULT_OCSP_TIME_DIFF. * hx_locl.h: Add ocsp_time_diff to hx509_context * crypto.c (_hx509_verify_signature_bitstring): new function, commonly use when checking certificates * cms.c (hx509_cms_envelope_1): check for internal ASN.1 encoder error * cert.c: Add ocsp glue, use new _hx509_verify_signature_bitstring, add eku checking function. 2006-03-31 Love Hörnquist Åstrand * Makefile.am: add id_kp_OCSPSigning.x * revoke.c: Pick out certs in ocsp response * TODO: list of stuff to verify * revoke.c: Add code to load OCSPBasicOCSPResponse files, reload crl when its changed on disk. * cert.c: Update for ocsp merge. handle building path w/o subject (using subject key id) * ks_p12.c: _hx509_map_file changed prototype. * file.c: _hx509_map_file changed prototype, returns struct stat if requested. * ks_file.c: _hx509_map_file changed prototype. * hxtool.c: Add stub for ocsp-fetch, _hx509_map_file changed prototype, add ocsp parsing to verify command. * hx_locl.h: rename HX509_CTX_CRL_MISSING_OK to HX509_CTX_VERIFY_MISSING_OK now that we have OCSP glue 2006-03-30 Love Hörnquist Åstrand * hx_locl.h: Add to make it compile on Solaris, from Alex V. Labuta. 2006-03-28 Love Hörnquist Åstrand * crypto.c (_hx509_pbe_decrypt): try all passwords, not just the first one. 2006-03-27 Love Hörnquist Åstrand * print.c (check_altName): Print the othername oid. * crypto.c: Manual page claims RSA_public_decrypt will return -1 on error, lets check for that * crypto.c (_hx509_pbe_decrypt): also try the empty password * collector.c (match_localkeyid): no need to add back the cert to the cert pool, its already there. * crypto.c: Add REQUIRE_SIGNER * cert.c (hx509_cert_free): ok to free NULL * hx509_err.et: Add new error code SIGNATURE_WITHOUT_SIGNER. * name.c (_hx509_name_ds_cmp): make DirectoryString case insenstive (hx509_name_to_string): less spacing * cms.c: Check for signature error, check consitency of error 2006-03-26 Love Hörnquist Åstrand * collector.c (_hx509_collector_alloc): handle errors * cert.c (hx509_query_alloc): allocate slight more more then a sizeof(pointer) * crypto.c (_hx509_private_key_assign_key_file): ask for password if nothing matches. * cert.c: Expose more of the hx509_query interface. * collector.c: hx509_certs_find is now exposed. * cms.c: hx509_certs_find is now exposed. * revoke.c: hx509_certs_find is now exposed. * keyset.c (hx509_certs_free): allow free-ing NULL (hx509_certs_find): expose (hx509_get_one_cert): new function * hxtool.c: hx509_certs_find is now exposed. * hx_locl.h: Remove hx509_query, its exposed now. * hx509.h: Add hx509_query. 2006-02-22 Love Hörnquist Åstrand * cert.c: Add exceptions for null (empty) subjectNames * data/nist-data: Add some more name constraints tests. * data/nist-data: Add some of the test from 4.13 Name Constraints. * cert.c: Name constraits needs to be evaluated in block as they appear in the certificates, they can not be joined to one list. One example of this is: - cert is cn=foo,dc=bar,dc=baz - subca is dc=foo,dc=baz with name restriction dc=kaka,dc=baz - ca is dc=baz with name restriction dc=baz If the name restrictions are merged to a list, the certificate will pass this test. 2006-02-14 Love Hörnquist Åstrand * cert.c: Handle more name constraints cases. * crypto.c (dsa_verify_signature): if test if malloc failed 2006-01-31 Love Hörnquist Åstrand * cms.c: Drop partial pkcs12 string2key implementation. 2006-01-20 Love Hörnquist Åstrand * data/nist-data: Add commited out DSA tests (they fail). * data/nist-data: Add 4.2 Validity Periods. * test_nist.in: Make less verbose to use. * Makefile.am: Add test_nist_cert. * data/nist-data: Add some more CRL-tests. * test_nist.in: Print $id instead of . when running the tests. * test_nist.in: Drop verifying certifiates, its done in another test now. * data/nist-data: fixup kill-rectangle leftovers * data/nist-data: Drop verifying certifiates, its done in another test now. Add more crl tests. comment out all unused tests. * test_nist_cert.in: test parse all nist certs 2006-01-19 Love Hörnquist Åstrand * hx509_err.et: Add HX509_CRL_UNKNOWN_EXTENSION. * revoke.c: Check for unknown extentions in CRLs and CRLEntries. * test_nist.in: Parse new format to handle CRL info. * test_chain.in: Add --missing-crl. * name.c (hx509_unparse_der_name): Rename from hx509_parse_name. (_hx509_unparse_Name): Add. * hxtool-commands.in: Add --missing-crl to verify commands. * hx509_err.et: Add CRL errors. * cert.c (hx509_context_set_missing_crl): new function Add CRL handling. * hx_locl.h: Add HX509_CTX_CRL_MISSING_OK. * revoke.c: Parse and verify CRLs (simplistic). * hxtool.c: Parse CRL info. * data/nist-data: Change format so we can deal with CRLs, also note the test-id from PKITS. * data: regenerate test * data/gen-req.sh: use static-file to generate tests * data/static-file: new file to use for commited tests * test_cms.in: Use static file, add --missing-crl. 2006-01-18 Love Hörnquist Åstrand * print.c: Its cRLReason, not cRLReasons. * hxtool.c: Attach revoke context to verify context. * data/nist-data: change syntax to make match better with crl checks * cert.c: Verify no certificates has been revoked with the new revoke interface. * Makefile.am: libhx509_la_SOURCES += revoke.c * revoke.c: Add framework for handling CRLs. * hx509.h: Add hx509_revoke_ctx. 2006-01-13 Love Hörnquist Åstrand * delete crypto_headers.h, use global file instead. * crypto.c (PBE_string2key): libdes now supports PKCS12_key_gen 2006-01-12 Love Hörnquist Åstrand * crypto_headers.h: Need BN_is_negative too. 2006-01-11 Love Hörnquist Åstrand * ks_p11.c (p11_rsa_public_decrypt): since is wrong, don't provide it. PKCS11 can't do public_decrypt, it support verify though. All this doesn't matter, since the code never go though this path. * crypto_headers.h: Provide glue to compile with less warnings with OpenSSL 2006-01-08 Love Hörnquist Åstrand * Makefile.am: Depend on LIB_des * lock.c: Use "crypto_headers.h". * crypto_headers.h: Include the two diffrent implementation of crypto headers. * cert.c: Use "crypto-headers.h". Load ENGINE configuration. * crypto.c: Make compile with both OpenSSL and heimdal libdes. * ks_p11.c: Add code for public key decryption (not supported yet) and use "crypto-headers.h". 2006-01-04 Love Hörnquist Åstrand * add a hx509_context where we can store configuration * p11.c,Makefile.am: pkcs11 is now supported by library, remove old files. * ks_p11.c: more paranoid on refcount, set refcounter ealier, reset pointers after free * collector.c (struct private_key): remove temporary key data storage, convert directly to a key (match_localkeyid): match certificate and key using localkeyid (match_keys): match certificate and key using _hx509_match_keys (_hx509_collector_collect): rewrite to use match_keys and match_localkeyid * crypto.c (_hx509_match_keys): function that determins if a private key matches a certificate, used when there is no localkeyid. (*) reset free pointer * ks_file.c: Rewrite to use collector and mapping support function. * ks_p11.c (rsa_pkcs1_method): constify * ks_p11.c: drop extra wrapping of p11_init * crypto.c (_hx509_private_key_assign_key_file): use function to extact rsa key * cert.c: Revert previous, refcounter is unsigned, so it can never be negative. * cert.c (hx509_cert_ref): more refcount paranoia * ks_p11.c: Implement rsa_private_decrypt and add stubs for public ditto. * ks_p11.c: Less printf, less memory leaks. * ks_p11.c: Implement signing using pkcs11. * ks_p11.c: Partly assign private key, enough to complete collection, but not any crypto functionallity. * collector.c: Use hx509_private_key to assign private keys. * crypto.c: Remove most of the EVP_PKEY code, and use RSA directly, this temporary removes DSA support. * hxtool.c (print_f): print if there is a friendly name and if there is a private key 2006-01-03 Love Hörnquist Åstrand * name.c: Avoid warning from missing __attribute__((noreturn)) * lock.c (_hx509_lock_unlock_certs): return unlock certificates * crypto.c (_hx509_private_key_assign_ptr): new function, exposes EVP_PKEY (_hx509_private_key_assign_key_file): remember to free private key if there is one. * cert.c (_hx509_abort): add newline to output and flush stdout * Makefile.am: libhx509_la_SOURCES += collector.c * hx_locl.h: forward type declaration of struct hx509_collector. * collector.c: Support functions to collect certificates and private keys and then match them. * ks_p12.c: Use the new hx509_collector support functions. * ks_p11.c: Add enough glue to support certificate iteration. * test_nist_pkcs12.in: Less verbose. * cert.c (hx509_cert_free): if there is a private key assosited with this cert, free it * print.c: Use _hx509_abort. * ks_p12.c: Use _hx509_abort. * hxtool.c: Use _hx509_abort. * crypto.c: Use _hx509_abort. * cms.c: Use _hx509_abort. * cert.c: Use _hx509_abort. * name.c: use _hx509_abort 2006-01-02 Love Hörnquist Åstrand * name.c (hx509_name_to_string): don't cut bmpString in half. * name.c (hx509_name_to_string): don't overwrite with 1 byte with bmpString. * ks_file.c (parse_certificate): avoid stomping before array * name.c (oidtostring): avoid leaking memory * keyset.c: Add _hx509_ks_dir_register. * Makefile.am (libhx509_la_SOURCES): += ks_dir.c * hxtool-commands.in: Remove pkcs11. * hxtool.c: Remove pcert_pkcs11. * ks_file.c: Factor out certificate parsing code. * ks_dir.c: Add new keystore that treats all files in a directory a keystore, useful for regression tests. 2005-12-12 Love Hörnquist Åstrand * test_nist_pkcs12.in: Test parse PKCS12 files from NIST. * data/nist-data: Can handle DSA certificate. * hxtool.c: Print error code on failure. 2005-10-29 Love Hörnquist Åstrand * crypto.c: Support DSA signature operations. 2005-10-04 Love Hörnquist Åstrand * print.c: Validate that issuerAltName and subjectAltName isn't empty. 2005-09-14 Love Hörnquist Åstrand * p11.c: Cast to unsigned char to avoid warning. * keyset.c: Register pkcs11 module. * Makefile.am: Add ks_p11.c, install hxtool. * ks_p11.c: Starting point of a pkcs11 module. 2005-09-04 Love Hörnquist Åstrand * lock.c: Implement prompter. * hxtool-commands.in: add --content to print * hxtool.c: Split verify and print. * cms.c: _hx509_pbe_decrypt now takes a hx509_lock. * crypto.c: Make _hx509_pbe_decrypt take a hx509_lock, workaround for empty password. * name.c: Add DC, handle all Directory strings, fix signless problems. 2005-09-03 Love Hörnquist Åstrand * test_query.in: Pass in --pass to all commands. * hxtool.c: Use option --pass. * hxtool-commands.in: Add --pass to all commands. * hx509_err.et: add UNKNOWN_LOCK_COMMAND and CRYPTO_NO_PROMPTER * test_cms.in: pass in password to cms-create-sd * crypto.c: Abstract out PBE_string2key so I can add PBE2 s2k later. Avoid signess warnings with OpenSSL. * cms.c: Use void * instead of char * for to avoid signedness issues * cert.c (hx509_cert_get_attribute): remove const, its not * ks_p12.c: Cast size_t to unsigned long when print. * name.c: Fix signedness warning. * test_query.in: Use echo, the function check isn't defined here. 2005-08-11 Love Hörnquist Åstrand * hxtool-commands.in: Add more options that was missing. 2005-07-28 Love Hörnquist Åstrand * test_cms.in: Use --certificate= for enveloped/unenvelope. * hxtool.c: Use --certificate= for enveloped/unenvelope. Clean up. * test_cms.in: add EnvelopeData tests * hxtool.c: use id-envelopedData for ContentInfo * hxtool-commands.in: add contentinfo wrapping for create/unwrap enveloped data * hxtool.c: add contentinfo wrapping for create/unwrap enveloped data * data/gen-req.sh: add enveloped data (aes128) * crypto.c: add "new" RC2 oid 2005-07-27 Love Hörnquist Åstrand * hx_locl.h, cert.c: Add HX509_QUERY_MATCH_FUNCTION that allows caller to match by function, note that this doesn't not work directly for backends that implements ->query, they must do their own processing. (I'm running out of flags, only 12 left now) * test_cms.in: verify ContentInfo wrapping code in hxtool * hxtool-commands.in (cms_create_sd): support wrapping in content info spelling * hxtool.c (cms_create_sd): support wrapping in content info * test_cms.in: test more cms signeddata messages * data/gen-req.sh: generate SignedData * hxtool.c (cms_create_sd): support certificate store, add support to unwrap a ContentInfo the SignedData inside. * crypto.c: sprinkel rk_UNCONST * crypto.c: add DER NULL to the digest oid's * hxtool-commands.in: add --content-info to cms-verify-sd * cms.c (hx509_cms_create_signed_1): pass in a full AlgorithmIdentifier instead of heim_oid for digest_alg * crypto.c: make digest_alg a digest_oid, it's not needed right now * hx509_err.et: add CERT_NOT_FOUND * keyset.c (_hx509_certs_find): add error code for cert not found * cms.c (hx509_cms_verify_signed): add external store of certificates, use the right digest algorithm identifier. * cert.c: fix const warning * ks_p12.c: slightly less verbose * cert.c: add hx509_cert_find_subjectAltName_otherName, add HX509_QUERY_MATCH_FRIENDLY_NAME * hx509.h: add hx509_octet_string_list, remove bad comment * hx_locl.h: add HX509_QUERY_MATCH_FRIENDLY_NAME * keyset.c (hx509_certs_append): needs a hx509_lock, add one * Makefile.am: add test cases tempfiles to CLEANFILES * Makefile.am: add test_query to TESTS, fix dependency on hxtool sources on hxtool-commands.h * hxtool-commands.in: explain what signer is for create-sd * hxtool.c: add query, add more options to verify-sd and create-sd * test_cms.in: add more cms tests * hxtool-commands.in: add query, add more options to verify-sd * test_query.in: test query interface * data: fix filenames for ds/ke files, add pkcs12 files, regen * hxtool.c,Makefile.am,hxtool-commands.in: switch to slc 2005-07-26 Love Hörnquist Åstrand * cert.c (hx509_verify_destroy_ctx): add * hxtool.c: free hx509_verify_ctx * name.c (_hx509_name_ds_cmp): make sure all strings are not equal 2005-07-25 Love Hörnquist Åstrand * hxtool.c: return error * keyset.c: return errors from iterations * test_chain.in: clean up checks * ks_file.c (parse_certificate): return errno's not 1 in case of error * ks_file.c (file_iter): make sure endpointer is NULL * ks_mem.c (mem_iter): follow conversion and return NULL when we get to the end, not ENOENT. * Makefile.am: test_chain depends on hxtool * data: test certs that lasts 10 years * data/gen-req.sh: script to generate test certs * Makefile.am: Add regression tests. * data: test certificate and keys * test_chain.in: test chain * hxtool.c (cms_create_sd): add KU digitalSigature as a requirement to the query * hx_locl.h: add KeyUsage query bits * hx509_err.et: add KeyUsage error * cms.c: add checks for KeyUsage * cert.c: more checks on KeyUsage, allow to query on them too 2005-07-24 Love Hörnquist Åstrand * cms.c: Add missing break. * hx_locl.h,cms.c,cert.c: allow matching on SubjectKeyId * hxtool.c: Use _hx509_map_file, _hx509_unmap_file and _hx509_write_file. * file.c (_hx509_write_file): in case of write error, return errno * file.c (_hx509_write_file): add a function that write a data blob to disk too * Fix id-tags * Import mostly complete X.509 and CMS library. Handles, PEM, DER, PKCS12 encoded certicates. Verificate RSA chains and handled CMS's SignedData, and EnvelopedData. heimdal-7.5.0/lib/hx509/test_java_pkcs11.in0000644000175000017500000000435312136107750016376 0ustar niknik#!/bin/sh # # Copyright (c) 2008 Kungliga Tekniska Högskolan # (Royal Institute of Technology, Stockholm, Sweden). # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # 1. Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # # 3. Neither the name of the Institute nor the names of its contributors # may be used to endorse or promote products derived from this software # without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE # ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS # OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) # HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY # OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF # SUCH DAMAGE. # exit 0 srcdir="@srcdir@" objdir="@objdir@" dir=$objdir file= for a in libhx509.so .libs/libhx509.so libhx509.dylib .libs/libhx509.dylib ; do if [ -f $dir/$a ] ; then file=$dir/$a break fi done if [ "X$file" = X ] ; then exit 0 fi cat > pkcs11.cfg < test-rc-file.rc < #include #include #include #include #ifdef HAVE_STRINGS_H #include #endif #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include /* * We use OpenSSL for EC, but to do this we need to disable cross-references * between OpenSSL and hcrypto bn.h and such. Source files that use OpenSSL EC * must define HEIM_NO_CRYPTO_HDRS before including this file. */ #define HC_DEPRECATED_CRYPTO #ifndef HEIM_NO_CRYPTO_HDRS #include "crypto-headers.h" #endif struct hx509_keyset_ops; struct hx509_collector; struct hx509_generate_private_context; typedef struct hx509_path hx509_path; #include #include typedef void (*_hx509_cert_release_func)(struct hx509_cert_data *, void *); #include "sel.h" #include #include struct hx509_peer_info { hx509_cert cert; AlgorithmIdentifier *val; size_t len; }; #define HX509_CERTS_FIND_SERIALNUMBER 1 #define HX509_CERTS_FIND_ISSUER 2 #define HX509_CERTS_FIND_SUBJECT 4 #define HX509_CERTS_FIND_ISSUER_KEY_ID 8 #define HX509_CERTS_FIND_SUBJECT_KEY_ID 16 struct hx509_name_data { Name der_name; }; struct hx509_path { size_t len; hx509_cert *val; }; struct hx509_query_data { int match; #define HX509_QUERY_FIND_ISSUER_CERT 0x000001 #define HX509_QUERY_MATCH_SERIALNUMBER 0x000002 #define HX509_QUERY_MATCH_ISSUER_NAME 0x000004 #define HX509_QUERY_MATCH_SUBJECT_NAME 0x000008 #define HX509_QUERY_MATCH_SUBJECT_KEY_ID 0x000010 #define HX509_QUERY_MATCH_ISSUER_ID 0x000020 #define HX509_QUERY_PRIVATE_KEY 0x000040 #define HX509_QUERY_KU_ENCIPHERMENT 0x000080 #define HX509_QUERY_KU_DIGITALSIGNATURE 0x000100 #define HX509_QUERY_KU_KEYCERTSIGN 0x000200 #define HX509_QUERY_KU_CRLSIGN 0x000400 #define HX509_QUERY_KU_NONREPUDIATION 0x000800 #define HX509_QUERY_KU_KEYAGREEMENT 0x001000 #define HX509_QUERY_KU_DATAENCIPHERMENT 0x002000 #define HX509_QUERY_ANCHOR 0x004000 #define HX509_QUERY_MATCH_CERTIFICATE 0x008000 #define HX509_QUERY_MATCH_LOCAL_KEY_ID 0x010000 #define HX509_QUERY_NO_MATCH_PATH 0x020000 #define HX509_QUERY_MATCH_FRIENDLY_NAME 0x040000 #define HX509_QUERY_MATCH_FUNCTION 0x080000 #define HX509_QUERY_MATCH_KEY_HASH_SHA1 0x100000 #define HX509_QUERY_MATCH_TIME 0x200000 #define HX509_QUERY_MATCH_EKU 0x400000 #define HX509_QUERY_MATCH_EXPR 0x800000 #define HX509_QUERY_MASK 0xffffff Certificate *subject; Certificate *certificate; heim_integer *serial; heim_octet_string *subject_id; heim_octet_string *local_key_id; Name *issuer_name; Name *subject_name; hx509_path *path; char *friendlyname; int (*cmp_func)(hx509_context, hx509_cert, void *); void *cmp_func_ctx; heim_octet_string *keyhash_sha1; time_t timenow; heim_oid *eku; struct hx_expr *expr; }; struct hx509_keyset_ops { const char *name; int flags; int (*init)(hx509_context, hx509_certs, void **, int, const char *, hx509_lock); int (*store)(hx509_context, hx509_certs, void *, int, hx509_lock); int (*free)(hx509_certs, void *); int (*add)(hx509_context, hx509_certs, void *, hx509_cert); int (*query)(hx509_context, hx509_certs, void *, const hx509_query *, hx509_cert *); int (*iter_start)(hx509_context, hx509_certs, void *, void **); int (*iter)(hx509_context, hx509_certs, void *, void *, hx509_cert *); int (*iter_end)(hx509_context, hx509_certs, void *, void *); int (*printinfo)(hx509_context, hx509_certs, void *, int (*)(void *, const char *), void *); int (*getkeys)(hx509_context, hx509_certs, void *, hx509_private_key **); int (*addkey)(hx509_context, hx509_certs, void *, hx509_private_key); }; struct _hx509_password { size_t len; char **val; }; extern hx509_lock _hx509_empty_lock; struct hx509_context_data { struct hx509_keyset_ops **ks_ops; int ks_num_ops; int flags; #define HX509_CTX_VERIFY_MISSING_OK 1 int ocsp_time_diff; #define HX509_DEFAULT_OCSP_TIME_DIFF (5*60) heim_error_t error; struct et_list *et_list; char *querystat; hx509_certs default_trust_anchors; }; /* _hx509_calculate_path flag field */ #define HX509_CALCULATE_PATH_NO_ANCHOR 1 /* environment */ struct hx509_env_data { enum { env_string, env_list } type; char *name; struct hx509_env_data *next; union { char *string; struct hx509_env_data *list; } u; }; extern const AlgorithmIdentifier * _hx509_crypto_default_sig_alg; extern const AlgorithmIdentifier * _hx509_crypto_default_digest_alg; extern const AlgorithmIdentifier * _hx509_crypto_default_secret_alg; /* * Private bits from crypto.c, so crypto-ec.c can also see them. * * This is part of the use-OpenSSL-for-EC hack. */ struct hx509_crypto; struct signature_alg; struct hx509_generate_private_context { const heim_oid *key_oid; int isCA; unsigned long num_bits; }; struct hx509_private_key_ops { const char *pemtype; const heim_oid *key_oid; int (*available)(const hx509_private_key, const AlgorithmIdentifier *); int (*get_spki)(hx509_context, const hx509_private_key, SubjectPublicKeyInfo *); int (*export)(hx509_context context, const hx509_private_key, hx509_key_format_t, heim_octet_string *); int (*import)(hx509_context, const AlgorithmIdentifier *, const void *, size_t, hx509_key_format_t, hx509_private_key); int (*generate_private_key)(hx509_context, struct hx509_generate_private_context *, hx509_private_key); BIGNUM *(*get_internal)(hx509_context, hx509_private_key, const char *); }; struct hx509_private_key { unsigned int ref; const struct signature_alg *md; const heim_oid *signature_alg; union { RSA *rsa; void *keydata; void *ecdsa; /* EC_KEY */ } private_key; hx509_private_key_ops *ops; }; /* * */ struct signature_alg { const char *name; const heim_oid *sig_oid; const AlgorithmIdentifier *sig_alg; const heim_oid *key_oid; const AlgorithmIdentifier *digest_alg; int flags; #define PROVIDE_CONF 0x1 #define REQUIRE_SIGNER 0x2 #define SELF_SIGNED_OK 0x4 #define WEAK_SIG_ALG 0x8 #define SIG_DIGEST 0x100 #define SIG_PUBLIC_SIG 0x200 #define SIG_SECRET 0x400 #define RA_RSA_USES_DIGEST_INFO 0x1000000 time_t best_before; /* refuse signature made after best before date */ const EVP_MD *(*evp_md)(void); int (*verify_signature)(hx509_context context, const struct signature_alg *, const Certificate *, const AlgorithmIdentifier *, const heim_octet_string *, const heim_octet_string *); int (*create_signature)(hx509_context, const struct signature_alg *, const hx509_private_key, const AlgorithmIdentifier *, const heim_octet_string *, AlgorithmIdentifier *, heim_octet_string *); int digest_size; }; /* * Configurable options */ #ifdef __APPLE__ #define HX509_DEFAULT_ANCHORS "KEYCHAIN:system-anchors" #endif heimdal-7.5.0/lib/hx509/collector.c0000644000175000017500000001741513026237312015036 0ustar niknik/* * Copyright (c) 2004 - 2007 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "hx_locl.h" struct private_key { AlgorithmIdentifier alg; hx509_private_key private_key; heim_octet_string localKeyId; }; struct hx509_collector { hx509_lock lock; hx509_certs unenvelop_certs; hx509_certs certs; struct { struct private_key **data; size_t len; } val; }; int _hx509_collector_alloc(hx509_context context, hx509_lock lock, struct hx509_collector **collector) { struct hx509_collector *c; int ret; *collector = NULL; c = calloc(1, sizeof(*c)); if (c == NULL) { hx509_set_error_string(context, 0, ENOMEM, "out of memory"); return ENOMEM; } c->lock = lock; ret = hx509_certs_init(context, "MEMORY:collector-unenvelop-cert", 0,NULL, &c->unenvelop_certs); if (ret) { free(c); return ret; } c->val.data = NULL; c->val.len = 0; ret = hx509_certs_init(context, "MEMORY:collector-tmp-store", 0, NULL, &c->certs); if (ret) { hx509_certs_free(&c->unenvelop_certs); free(c); return ret; } *collector = c; return 0; } hx509_lock _hx509_collector_get_lock(struct hx509_collector *c) { return c->lock; } int _hx509_collector_certs_add(hx509_context context, struct hx509_collector *c, hx509_cert cert) { return hx509_certs_add(context, c->certs, cert); } static void free_private_key(struct private_key *key) { free_AlgorithmIdentifier(&key->alg); if (key->private_key) hx509_private_key_free(&key->private_key); der_free_octet_string(&key->localKeyId); free(key); } int _hx509_collector_private_key_add(hx509_context context, struct hx509_collector *c, const AlgorithmIdentifier *alg, hx509_private_key private_key, const heim_octet_string *key_data, const heim_octet_string *localKeyId) { struct private_key *key; void *d; int ret; key = calloc(1, sizeof(*key)); if (key == NULL) return ENOMEM; d = realloc(c->val.data, (c->val.len + 1) * sizeof(c->val.data[0])); if (d == NULL) { free(key); hx509_set_error_string(context, 0, ENOMEM, "Out of memory"); return ENOMEM; } c->val.data = d; ret = copy_AlgorithmIdentifier(alg, &key->alg); if (ret) { hx509_set_error_string(context, 0, ret, "Failed to copy " "AlgorithmIdentifier"); goto out; } if (private_key) { key->private_key = private_key; } else { ret = hx509_parse_private_key(context, alg, key_data->data, key_data->length, HX509_KEY_FORMAT_DER, &key->private_key); if (ret) goto out; } if (localKeyId) { ret = der_copy_octet_string(localKeyId, &key->localKeyId); if (ret) { hx509_set_error_string(context, 0, ret, "Failed to copy localKeyId"); goto out; } } else memset(&key->localKeyId, 0, sizeof(key->localKeyId)); c->val.data[c->val.len] = key; c->val.len++; out: if (ret) free_private_key(key); return ret; } static int match_localkeyid(hx509_context context, struct private_key *value, hx509_certs certs) { hx509_cert cert; hx509_query q; int ret; if (value->localKeyId.length == 0) { hx509_set_error_string(context, 0, HX509_LOCAL_ATTRIBUTE_MISSING, "No local key attribute on private key"); return HX509_LOCAL_ATTRIBUTE_MISSING; } _hx509_query_clear(&q); q.match |= HX509_QUERY_MATCH_LOCAL_KEY_ID; q.local_key_id = &value->localKeyId; ret = hx509_certs_find(context, certs, &q, &cert); if (ret == 0) { if (value->private_key) _hx509_cert_assign_key(cert, value->private_key); hx509_cert_free(cert); } return ret; } static int match_keys(hx509_context context, struct private_key *value, hx509_certs certs) { hx509_cursor cursor; hx509_cert c; int ret, found = HX509_CERT_NOT_FOUND; if (value->private_key == NULL) { hx509_set_error_string(context, 0, HX509_PRIVATE_KEY_MISSING, "No private key to compare with"); return HX509_PRIVATE_KEY_MISSING; } ret = hx509_certs_start_seq(context, certs, &cursor); if (ret) return ret; c = NULL; while (1) { ret = hx509_certs_next_cert(context, certs, cursor, &c); if (ret) break; if (c == NULL) break; if (_hx509_cert_private_key(c)) { hx509_cert_free(c); continue; } ret = _hx509_match_keys(c, value->private_key); if (ret) { _hx509_cert_assign_key(c, value->private_key); hx509_cert_free(c); found = 0; break; } hx509_cert_free(c); } hx509_certs_end_seq(context, certs, cursor); if (found) hx509_clear_error_string(context); return found; } int _hx509_collector_collect_certs(hx509_context context, struct hx509_collector *c, hx509_certs *ret_certs) { hx509_certs certs; int ret; size_t i; *ret_certs = NULL; ret = hx509_certs_init(context, "MEMORY:collector-store", 0, NULL, &certs); if (ret) return ret; ret = hx509_certs_merge(context, certs, c->certs); if (ret) { hx509_certs_free(&certs); return ret; } for (i = 0; i < c->val.len; i++) { ret = match_localkeyid(context, c->val.data[i], certs); if (ret == 0) continue; ret = match_keys(context, c->val.data[i], certs); if (ret == 0) continue; } *ret_certs = certs; return 0; } int _hx509_collector_collect_private_keys(hx509_context context, struct hx509_collector *c, hx509_private_key **keys) { size_t i, nkeys; *keys = NULL; for (i = 0, nkeys = 0; i < c->val.len; i++) if (c->val.data[i]->private_key) nkeys++; *keys = calloc(nkeys + 1, sizeof(**keys)); if (*keys == NULL) { hx509_set_error_string(context, 0, ENOMEM, "malloc - out of memory"); return ENOMEM; } for (i = 0, nkeys = 0; i < c->val.len; i++) { if (c->val.data[i]->private_key) { (*keys)[nkeys++] = c->val.data[i]->private_key; c->val.data[i]->private_key = NULL; } } (*keys)[nkeys] = NULL; return 0; } void _hx509_collector_free(struct hx509_collector *c) { size_t i; if (c->unenvelop_certs) hx509_certs_free(&c->unenvelop_certs); if (c->certs) hx509_certs_free(&c->certs); for (i = 0; i < c->val.len; i++) free_private_key(c->val.data[i]); if (c->val.data) free(c->val.data); free(c); } heimdal-7.5.0/lib/hx509/tst-crypto-select60000644000175000017500000000002512136107750016312 0ustar niknik1.2.840.113549.1.1.5 heimdal-7.5.0/lib/hx509/tst-crypto-select10000644000175000017500000000002712136107750016307 0ustar niknik2.16.840.1.101.3.4.2.1 heimdal-7.5.0/lib/hx509/tst-crypto-select70000644000175000017500000000003012136107750016307 0ustar niknik2.16.840.1.101.3.4.1.42 heimdal-7.5.0/lib/hx509/tst-crypto-available10000644000175000017500000000040712136107750016752 0ustar niknik1.2.840.113549.1.1.11 1.2.840.113549.1.1.5 1.2.840.113549.1.1.5 1.2.840.113549.1.1.4 1.2.840.113549.1.1.2 1.2.752.43.16.1 2.16.840.1.101.3.4.2.1 1.3.14.3.2.26 1.2.840.113549.2.5 1.2.840.113549.2.2 1.2.840.113549.3.7 2.16.840.1.101.3.4.1.2 2.16.840.1.101.3.4.1.42 heimdal-7.5.0/lib/hx509/TODO0000644000175000017500000000244012136107747013375 0ustar niknikHandle private_key_ops better, esp wrt ->key_oid Better support for keyex negotiation, DH and ECDH. x501 name parsing comparing (ldap canonlisation rules) DSA support DSA2 support Rewrite the pkcs11 code to support the following: * Reset the pin on card change. * Ref count the lock structure to make sure we have a prompter when we need it. * Add support for CK_TOKEN_INFO.CKF_PROTECTED_AUTHENTICATION_PATH x509 policy mappings support CRL delta support Qualified statement https://bugzilla.mozilla.org/show_bug.cgi?id=277797#c2 Signed Receipts http://www.faqs.org/rfcs/rfc2634.html chapter 2 tests nist tests name constrains policy mappings http://csrc.nist.gov/pki/testing/x509paths.html building path using Subject/Issuer vs SubjKeyID vs AuthKeyID negative tests all checksums conditions/branches pkcs7 handle pkcs7 support in CMS ? certificate request generate pkcs10 request from existing cert generate CRMF request pk-init KDC/client web server/client jabber server/client email x509 issues: OtherName is left unspecified, but it's used by other specs. creating this hole where a application/CA can't specify policy for SubjectAltName what covers whole space. For example, a CA is trusted to provide authentication but not authorization. heimdal-7.5.0/lib/hx509/test_soft_pkcs11.c0000644000175000017500000001443013026237312016236 0ustar niknik/* * Copyright (c) 2006 - 2008 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "hx_locl.h" #include "ref/pkcs11.h" #include static CK_FUNCTION_LIST_PTR func; static CK_RV find_object(CK_SESSION_HANDLE session, char *id, CK_OBJECT_CLASS key_class, CK_OBJECT_HANDLE_PTR object) { CK_ULONG object_count; CK_RV ret; CK_ATTRIBUTE search_data[] = { {CKA_ID, id, 0 }, {CKA_CLASS, &key_class, sizeof(key_class)} }; CK_ULONG num_search_data = sizeof(search_data)/sizeof(search_data[0]); search_data[0].ulValueLen = strlen(id); ret = (*func->C_FindObjectsInit)(session, search_data, num_search_data); if (ret != CKR_OK) return ret; ret = (*func->C_FindObjects)(session, object, 1, &object_count); if (ret != CKR_OK) return ret; if (object_count == 0) { printf("found no object\n"); return 1; } ret = (*func->C_FindObjectsFinal)(session); if (ret != CKR_OK) return ret; return CKR_OK; } static char *sighash = "hej"; static char signature[1024]; int main(int argc, char **argv) { CK_SLOT_ID_PTR slot_ids; CK_SLOT_ID slot; CK_ULONG num_slots; CK_RV ret; CK_SLOT_INFO slot_info; CK_TOKEN_INFO token_info; CK_SESSION_HANDLE session; CK_OBJECT_HANDLE public, private; ret = C_GetFunctionList(&func); if (ret != CKR_OK) errx(1, "C_GetFunctionList failed: %d", (int)ret); (*func->C_Initialize)(NULL_PTR); ret = (*func->C_GetSlotList)(FALSE, NULL, &num_slots); if (ret != CKR_OK) errx(1, "C_GetSlotList1 failed: %d", (int)ret); if (num_slots == 0) errx(1, "no slots"); if ((slot_ids = calloc(1, num_slots * sizeof(*slot_ids))) == NULL) err(1, "alloc slots failed"); ret = (*func->C_GetSlotList)(FALSE, slot_ids, &num_slots); if (ret != CKR_OK) errx(1, "C_GetSlotList2 failed: %d", (int)ret); slot = slot_ids[0]; free(slot_ids); ret = (*func->C_GetSlotInfo)(slot, &slot_info); if (ret) errx(1, "C_GetSlotInfo failed: %d", (int)ret); if ((slot_info.flags & CKF_TOKEN_PRESENT) == 0) errx(1, "no token present"); ret = (*func->C_OpenSession)(slot, CKF_SERIAL_SESSION, NULL, NULL, &session); if (ret != CKR_OK) errx(1, "C_OpenSession failed: %d", (int)ret); ret = (*func->C_GetTokenInfo)(slot, &token_info); if (ret) errx(1, "C_GetTokenInfo1 failed: %d", (int)ret); if (token_info.flags & CKF_LOGIN_REQUIRED) { ret = (*func->C_Login)(session, CKU_USER, (unsigned char*)"foobar", 6); if (ret != CKR_OK) errx(1, "C_Login failed: %d", (int)ret); } ret = (*func->C_GetTokenInfo)(slot, &token_info); if (ret) errx(1, "C_GetTokenInfo2 failed: %d", (int)ret); if (token_info.flags & CKF_LOGIN_REQUIRED) errx(1, "login required, even after C_Login"); ret = find_object(session, "cert", CKO_PUBLIC_KEY, &public); if (ret != CKR_OK) errx(1, "find cert failed: %d", (int)ret); ret = find_object(session, "cert", CKO_PRIVATE_KEY, &private); if (ret != CKR_OK) errx(1, "find private key failed: %d", (int)ret); { CK_ULONG ck_sigsize; CK_MECHANISM mechanism; memset(&mechanism, 0, sizeof(mechanism)); mechanism.mechanism = CKM_RSA_PKCS; ret = (*func->C_SignInit)(session, &mechanism, private); if (ret != CKR_OK) return 1; ck_sigsize = sizeof(signature); ret = (*func->C_Sign)(session, (CK_BYTE *)sighash, strlen(sighash), (CK_BYTE *)signature, &ck_sigsize); if (ret != CKR_OK) { printf("C_Sign failed with: %d\n", (int)ret); return 1; } ret = (*func->C_VerifyInit)(session, &mechanism, public); if (ret != CKR_OK) return 1; ret = (*func->C_Verify)(session, (CK_BYTE *)signature, ck_sigsize, (CK_BYTE *)sighash, strlen(sighash)); if (ret != CKR_OK) { printf("message: %d\n", (int)ret); return 1; } } #if 0 { CK_ULONG ck_sigsize, outsize; CK_MECHANISM mechanism; char outdata[1024]; memset(&mechanism, 0, sizeof(mechanism)); mechanism.mechanism = CKM_RSA_PKCS; ret = (*func->C_EncryptInit)(session, &mechanism, public); if (ret != CKR_OK) return 1; ck_sigsize = sizeof(signature); ret = (*func->C_Encrypt)(session, (CK_BYTE *)sighash, strlen(sighash), (CK_BYTE *)signature, &ck_sigsize); if (ret != CKR_OK) { printf("message: %d\n", (int)ret); return 1; } ret = (*func->C_DecryptInit)(session, &mechanism, private); if (ret != CKR_OK) return 1; outsize = sizeof(outdata); ret = (*func->C_Decrypt)(session, (CK_BYTE *)signature, ck_sigsize, (CK_BYTE *)outdata, &outsize); if (ret != CKR_OK) { printf("message: %d\n", (int)ret); return 1; } if (ct_memcmp(sighash, outdata, strlen(sighash)) != 0) return 1; } #endif ret = (*func->C_CloseSession)(session); if (ret != CKR_OK) return 1; (*func->C_Finalize)(NULL_PTR); return 0; } heimdal-7.5.0/lib/hx509/sel-gram.h0000644000175000017500000000477413212445575014601 0ustar niknik/* A Bison parser, made by GNU Bison 2.3. */ /* Skeleton interface for Bison's Yacc-like parsers in C Copyright (C) 1984, 1989, 1990, 2000, 2001, 2002, 2003, 2004, 2005, 2006 Free Software Foundation, Inc. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ /* As a special exception, you may create a larger work that contains part or all of the Bison parser skeleton and distribute that work under terms of your choice, so long as that work isn't itself a parser generator using the skeleton or a modified version thereof as a parser skeleton. Alternatively, if you modify or redistribute the parser skeleton itself, you may (at your option) remove this special exception, which will cause the skeleton and the resulting Bison output files to be licensed under the GNU General Public License without this special exception. This special exception was added by the Free Software Foundation in version 2.2 of Bison. */ /* Tokens. */ #ifndef YYTOKENTYPE # define YYTOKENTYPE /* Put the tokens into the symbol table, so that GDB and other debuggers know about them. */ enum yytokentype { kw_TRUE = 258, kw_FALSE = 259, kw_AND = 260, kw_OR = 261, kw_IN = 262, kw_TAILMATCH = 263, NUMBER = 264, STRING = 265, IDENTIFIER = 266 }; #endif /* Tokens. */ #define kw_TRUE 258 #define kw_FALSE 259 #define kw_AND 260 #define kw_OR 261 #define kw_IN 262 #define kw_TAILMATCH 263 #define NUMBER 264 #define STRING 265 #define IDENTIFIER 266 #if ! defined YYSTYPE && ! defined YYSTYPE_IS_DECLARED typedef union YYSTYPE #line 57 "sel-gram.y" { char *string; struct hx_expr *expr; } /* Line 1529 of yacc.c. */ #line 76 "sel-gram.h" YYSTYPE; # define yystype YYSTYPE /* obsolescent; will be withdrawn */ # define YYSTYPE_IS_DECLARED 1 # define YYSTYPE_IS_TRIVIAL 1 #endif extern YYSTYPE yylval; heimdal-7.5.0/lib/hx509/hx509_err.et0000644000175000017500000001176213026237312014762 0ustar niknik# # Error messages for the hx509 library # # This might look like a com_err file, but is not # id "$Id$" error_table hx prefix HX509 # path validation and construction related errors error_code BAD_TIMEFORMAT, "ASN.1 failed call to system time library" error_code EXTENSION_NOT_FOUND, "Extension not found" error_code NO_PATH, "Certification path not found" error_code PARENT_NOT_CA, "Parent certificate is not a CA" error_code CA_PATH_TOO_DEEP, "CA path too deep" error_code SIG_ALG_NO_SUPPORTED, "Signature algorithm not supported" error_code SIG_ALG_DONT_MATCH_KEY_ALG, "Signature algorithm doesn't match certificate key" error_code CERT_USED_BEFORE_TIME, "Certificate used before it became valid" error_code CERT_USED_AFTER_TIME, "Certificate used after it became invalid" error_code PRIVATE_KEY_MISSING, "Private key required for the operation is missing" error_code ALG_NOT_SUPP, "Algorithm not supported" error_code ISSUER_NOT_FOUND, "Issuer couldn't be found" error_code VERIFY_CONSTRAINTS, "Error verifying constraints" error_code RANGE, "Number too large" error_code NAME_CONSTRAINT_ERROR, "Error while verifying name constraints" error_code PATH_TOO_LONG, "Path is too long, failed to find valid anchor" error_code KU_CERT_MISSING, "Required keyusage for this certificate is missing" error_code CERT_NOT_FOUND, "Certificate not found" error_code UNKNOWN_LOCK_COMMAND, "Unknown lock command" error_code PARENT_IS_CA, "Parent certificate is a CA" error_code EXTRA_DATA_AFTER_STRUCTURE, "Extra data was found after the structure" error_code PROXY_CERT_INVALID, "Proxy certificate is invalid" error_code PROXY_CERT_NAME_WRONG, "Proxy certificate name is wrong" error_code NAME_MALFORMED, "Name is malformed" error_code CERTIFICATE_MALFORMED, "Certificate is malformed" error_code CERTIFICATE_MISSING_EKU, "Certificate is missing a required EKU" error_code PROXY_CERTIFICATE_NOT_CANONICALIZED, "Proxy certificate not canonicalized" # cms related errors index 32 prefix HX509_CMS error_code FAILED_CREATE_SIGATURE, "Failed to create signature" error_code MISSING_SIGNER_DATA, "Missing signer data" error_code SIGNER_NOT_FOUND, "Couldn't find signers certificate" error_code NO_DATA_AVAILABLE, "No data to perform the operation on" error_code INVALID_DATA, "Data in the message is invalid" error_code PADDING_ERROR, "Padding in the message invalid" error_code NO_RECIPIENT_CERTIFICATE, "Couldn't find recipient certificate" error_code DATA_OID_MISMATCH, "Mismatch bewteen signed type and unsigned type" # crypto related errors index 64 prefix HX509_CRYPTO error_code INTERNAL_ERROR, "Internal error in the crypto engine" error_code EXTERNAL_ERROR, "External error in the crypto engine" error_code SIGNATURE_MISSING, "Signature missing for data" error_code BAD_SIGNATURE, "Signature is not valid" error_code SIG_NO_CONF, "Sigature doesn't provide confidentiality" error_code SIG_INVALID_FORMAT, "Invalid format on signature" error_code OID_MISMATCH, "Mismatch between oids" error_code NO_PROMPTER, "No prompter function defined" error_code SIGNATURE_WITHOUT_SIGNER, "Signature requires signer, but none available" error_code RSA_PUBLIC_ENCRYPT, "RSA public encyption failed" error_code RSA_PRIVATE_ENCRYPT, "RSA private encyption failed" error_code RSA_PUBLIC_DECRYPT, "RSA public decryption failed" error_code RSA_PRIVATE_DECRYPT, "RSA private decryption failed" error_code ALGORITHM_BEST_BEFORE, "Algorithm has passed its best before date" error_code KEY_FORMAT_UNSUPPORTED, "Key format is unsupported" # revoke related errors index 96 prefix HX509 error_code CRL_USED_BEFORE_TIME, "CRL used before it became valid" error_code CRL_USED_AFTER_TIME, "CRL used after it became invalid" error_code CRL_INVALID_FORMAT, "CRL have invalid format" error_code CERT_REVOKED, "Certificate is revoked" error_code REVOKE_STATUS_MISSING, "No revoke status found for certificates" error_code CRL_UNKNOWN_EXTENSION, "Unknown extension" error_code REVOKE_WRONG_DATA, "Got wrong CRL/OCSP data from server" error_code REVOKE_NOT_SAME_PARENT, "Doesn't have same parent as other certificates" error_code CERT_NOT_IN_OCSP, "Certificates not in OCSP reply" # misc error index 108 error_code LOCAL_ATTRIBUTE_MISSING, "No local key attribute" error_code PARSING_KEY_FAILED, "Failed to parse key" error_code UNSUPPORTED_OPERATION, "Unsupported operation" error_code UNIMPLEMENTED_OPERATION, "Unimplemented operation" error_code PARSING_NAME_FAILED, "Failed to parse name" # keystore related error index 128 prefix HX509_PKCS11 error_code NO_SLOT, "No smartcard reader/device found" error_code NO_TOKEN, "No smartcard in reader" error_code NO_MECH, "No supported mech(s)" error_code TOKEN_CONFUSED, "Token or slot failed in inconsistent way" error_code OPEN_SESSION, "Failed to open session to slot" error_code LOGIN, "Failed to login to slot" error_code LOAD, "Failed to load PKCS module" # pkinit related errors error_code PIN_INCORRECT, "Incorrect User PIN" error_code PIN_LOCKED, "User PIN locked" error_code PIN_NOT_INITIALIZED, "User PIN not initialized" error_code PIN_EXPIRED, "User PIN expired" end heimdal-7.5.0/lib/hx509/ca.c0000644000175000017500000012005213026237312013423 0ustar niknik/* * Copyright (c) 2006 - 2010 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "hx_locl.h" #include /** * @page page_ca Hx509 CA functions * * See the library functions here: @ref hx509_ca */ struct hx509_ca_tbs { hx509_name subject; SubjectPublicKeyInfo spki; ExtKeyUsage eku; GeneralNames san; unsigned key_usage; heim_integer serial; struct { unsigned int proxy:1; unsigned int ca:1; unsigned int key:1; unsigned int serial:1; unsigned int domaincontroller:1; unsigned int xUniqueID:1; } flags; time_t notBefore; time_t notAfter; int pathLenConstraint; /* both for CA and Proxy */ CRLDistributionPoints crldp; heim_bit_string subjectUniqueID; heim_bit_string issuerUniqueID; AlgorithmIdentifier *sigalg; }; /** * Allocate an to-be-signed certificate object that will be converted * into an certificate. * * @param context A hx509 context. * @param tbs returned to-be-signed certicate object, free with * hx509_ca_tbs_free(). * * @return An hx509 error code, see hx509_get_error_string(). * * @ingroup hx509_ca */ int hx509_ca_tbs_init(hx509_context context, hx509_ca_tbs *tbs) { *tbs = calloc(1, sizeof(**tbs)); if (*tbs == NULL) return ENOMEM; return 0; } /** * Free an To Be Signed object. * * @param tbs object to free. * * @ingroup hx509_ca */ void hx509_ca_tbs_free(hx509_ca_tbs *tbs) { if (tbs == NULL || *tbs == NULL) return; free_SubjectPublicKeyInfo(&(*tbs)->spki); free_GeneralNames(&(*tbs)->san); free_ExtKeyUsage(&(*tbs)->eku); der_free_heim_integer(&(*tbs)->serial); free_CRLDistributionPoints(&(*tbs)->crldp); der_free_bit_string(&(*tbs)->subjectUniqueID); der_free_bit_string(&(*tbs)->issuerUniqueID); hx509_name_free(&(*tbs)->subject); if ((*tbs)->sigalg) { free_AlgorithmIdentifier((*tbs)->sigalg); free((*tbs)->sigalg); } memset(*tbs, 0, sizeof(**tbs)); free(*tbs); *tbs = NULL; } /** * Set the absolute time when the certificate is valid from. If not * set the current time will be used. * * @param context A hx509 context. * @param tbs object to be signed. * @param t time the certificated will start to be valid * * @return An hx509 error code, see hx509_get_error_string(). * * @ingroup hx509_ca */ int hx509_ca_tbs_set_notBefore(hx509_context context, hx509_ca_tbs tbs, time_t t) { tbs->notBefore = t; return 0; } /** * Set the absolute time when the certificate is valid to. * * @param context A hx509 context. * @param tbs object to be signed. * @param t time when the certificate will expire * * @return An hx509 error code, see hx509_get_error_string(). * * @ingroup hx509_ca */ int hx509_ca_tbs_set_notAfter(hx509_context context, hx509_ca_tbs tbs, time_t t) { tbs->notAfter = t; return 0; } /** * Set the relative time when the certificiate is going to expire. * * @param context A hx509 context. * @param tbs object to be signed. * @param delta seconds to the certificate is going to expire. * * @return An hx509 error code, see hx509_get_error_string(). * * @ingroup hx509_ca */ int hx509_ca_tbs_set_notAfter_lifetime(hx509_context context, hx509_ca_tbs tbs, time_t delta) { return hx509_ca_tbs_set_notAfter(context, tbs, time(NULL) + delta); } static const struct units templatebits[] = { { "ExtendedKeyUsage", HX509_CA_TEMPLATE_EKU }, { "KeyUsage", HX509_CA_TEMPLATE_KU }, { "SPKI", HX509_CA_TEMPLATE_SPKI }, { "notAfter", HX509_CA_TEMPLATE_NOTAFTER }, { "notBefore", HX509_CA_TEMPLATE_NOTBEFORE }, { "serial", HX509_CA_TEMPLATE_SERIAL }, { "subject", HX509_CA_TEMPLATE_SUBJECT }, { NULL, 0 } }; /** * Make of template units, use to build flags argument to * hx509_ca_tbs_set_template() with parse_units(). * * @return an units structure. * * @ingroup hx509_ca */ const struct units * hx509_ca_tbs_template_units(void) { return templatebits; } /** * Initialize the to-be-signed certificate object from a template certifiate. * * @param context A hx509 context. * @param tbs object to be signed. * @param flags bit field selecting what to copy from the template * certifiate. * @param cert template certificate. * * @return An hx509 error code, see hx509_get_error_string(). * * @ingroup hx509_ca */ int hx509_ca_tbs_set_template(hx509_context context, hx509_ca_tbs tbs, int flags, hx509_cert cert) { int ret; if (flags & HX509_CA_TEMPLATE_SUBJECT) { if (tbs->subject) hx509_name_free(&tbs->subject); ret = hx509_cert_get_subject(cert, &tbs->subject); if (ret) { hx509_set_error_string(context, 0, ret, "Failed to get subject from template"); return ret; } } if (flags & HX509_CA_TEMPLATE_SERIAL) { der_free_heim_integer(&tbs->serial); ret = hx509_cert_get_serialnumber(cert, &tbs->serial); tbs->flags.serial = !ret; if (ret) { hx509_set_error_string(context, 0, ret, "Failed to copy serial number"); return ret; } } if (flags & HX509_CA_TEMPLATE_NOTBEFORE) tbs->notBefore = hx509_cert_get_notBefore(cert); if (flags & HX509_CA_TEMPLATE_NOTAFTER) tbs->notAfter = hx509_cert_get_notAfter(cert); if (flags & HX509_CA_TEMPLATE_SPKI) { free_SubjectPublicKeyInfo(&tbs->spki); ret = hx509_cert_get_SPKI(context, cert, &tbs->spki); tbs->flags.key = !ret; if (ret) return ret; } if (flags & HX509_CA_TEMPLATE_KU) { KeyUsage ku; ret = _hx509_cert_get_keyusage(context, cert, &ku); if (ret) return ret; tbs->key_usage = KeyUsage2int(ku); } if (flags & HX509_CA_TEMPLATE_EKU) { ExtKeyUsage eku; size_t i; ret = _hx509_cert_get_eku(context, cert, &eku); if (ret) return ret; for (i = 0; i < eku.len; i++) { ret = hx509_ca_tbs_add_eku(context, tbs, &eku.val[i]); if (ret) { free_ExtKeyUsage(&eku); return ret; } } free_ExtKeyUsage(&eku); } return 0; } /** * Make the to-be-signed certificate object a CA certificate. If the * pathLenConstraint is negative path length constraint is used. * * @param context A hx509 context. * @param tbs object to be signed. * @param pathLenConstraint path length constraint, negative, no * constraint. * * @return An hx509 error code, see hx509_get_error_string(). * * @ingroup hx509_ca */ int hx509_ca_tbs_set_ca(hx509_context context, hx509_ca_tbs tbs, int pathLenConstraint) { tbs->flags.ca = 1; tbs->pathLenConstraint = pathLenConstraint; return 0; } /** * Make the to-be-signed certificate object a proxy certificate. If the * pathLenConstraint is negative path length constraint is used. * * @param context A hx509 context. * @param tbs object to be signed. * @param pathLenConstraint path length constraint, negative, no * constraint. * * @return An hx509 error code, see hx509_get_error_string(). * * @ingroup hx509_ca */ int hx509_ca_tbs_set_proxy(hx509_context context, hx509_ca_tbs tbs, int pathLenConstraint) { tbs->flags.proxy = 1; tbs->pathLenConstraint = pathLenConstraint; return 0; } /** * Make the to-be-signed certificate object a windows domain controller certificate. * * @param context A hx509 context. * @param tbs object to be signed. * * @return An hx509 error code, see hx509_get_error_string(). * * @ingroup hx509_ca */ int hx509_ca_tbs_set_domaincontroller(hx509_context context, hx509_ca_tbs tbs) { tbs->flags.domaincontroller = 1; return 0; } /** * Set the subject public key info (SPKI) in the to-be-signed certificate * object. SPKI is the public key and key related parameters in the * certificate. * * @param context A hx509 context. * @param tbs object to be signed. * @param spki subject public key info to use for the to-be-signed certificate object. * * @return An hx509 error code, see hx509_get_error_string(). * * @ingroup hx509_ca */ int hx509_ca_tbs_set_spki(hx509_context context, hx509_ca_tbs tbs, const SubjectPublicKeyInfo *spki) { int ret; free_SubjectPublicKeyInfo(&tbs->spki); ret = copy_SubjectPublicKeyInfo(spki, &tbs->spki); tbs->flags.key = !ret; return ret; } /** * Set the serial number to use for to-be-signed certificate object. * * @param context A hx509 context. * @param tbs object to be signed. * @param serialNumber serial number to use for the to-be-signed * certificate object. * * @return An hx509 error code, see hx509_get_error_string(). * * @ingroup hx509_ca */ int hx509_ca_tbs_set_serialnumber(hx509_context context, hx509_ca_tbs tbs, const heim_integer *serialNumber) { int ret; der_free_heim_integer(&tbs->serial); ret = der_copy_heim_integer(serialNumber, &tbs->serial); tbs->flags.serial = !ret; return ret; } /** * An an extended key usage to the to-be-signed certificate object. * Duplicates will detected and not added. * * @param context A hx509 context. * @param tbs object to be signed. * @param oid extended key usage to add. * * @return An hx509 error code, see hx509_get_error_string(). * * @ingroup hx509_ca */ int hx509_ca_tbs_add_eku(hx509_context context, hx509_ca_tbs tbs, const heim_oid *oid) { void *ptr; int ret; unsigned i; /* search for duplicates */ for (i = 0; i < tbs->eku.len; i++) { if (der_heim_oid_cmp(oid, &tbs->eku.val[i]) == 0) return 0; } ptr = realloc(tbs->eku.val, sizeof(tbs->eku.val[0]) * (tbs->eku.len + 1)); if (ptr == NULL) { hx509_set_error_string(context, 0, ENOMEM, "out of memory"); return ENOMEM; } tbs->eku.val = ptr; ret = der_copy_oid(oid, &tbs->eku.val[tbs->eku.len]); if (ret) { hx509_set_error_string(context, 0, ret, "out of memory"); return ret; } tbs->eku.len += 1; return 0; } /** * Add CRL distribution point URI to the to-be-signed certificate * object. * * @param context A hx509 context. * @param tbs object to be signed. * @param uri uri to the CRL. * @param issuername name of the issuer. * * @return An hx509 error code, see hx509_get_error_string(). * * @ingroup hx509_ca */ int hx509_ca_tbs_add_crl_dp_uri(hx509_context context, hx509_ca_tbs tbs, const char *uri, hx509_name issuername) { DistributionPoint dp; int ret; memset(&dp, 0, sizeof(dp)); dp.distributionPoint = ecalloc(1, sizeof(*dp.distributionPoint)); { DistributionPointName name; GeneralName gn; size_t size; name.element = choice_DistributionPointName_fullName; name.u.fullName.len = 1; name.u.fullName.val = &gn; gn.element = choice_GeneralName_uniformResourceIdentifier; gn.u.uniformResourceIdentifier.data = rk_UNCONST(uri); gn.u.uniformResourceIdentifier.length = strlen(uri); ASN1_MALLOC_ENCODE(DistributionPointName, dp.distributionPoint->data, dp.distributionPoint->length, &name, &size, ret); if (ret) { hx509_set_error_string(context, 0, ret, "Failed to encoded DistributionPointName"); goto out; } if (dp.distributionPoint->length != size) _hx509_abort("internal ASN.1 encoder error"); } if (issuername) { #if 1 /** * issuername not supported */ hx509_set_error_string(context, 0, EINVAL, "CRLDistributionPoints.name.issuername not yet supported"); return EINVAL; #else GeneralNames *crlissuer; GeneralName gn; Name n; crlissuer = calloc(1, sizeof(*crlissuer)); if (crlissuer == NULL) { return ENOMEM; } memset(&gn, 0, sizeof(gn)); gn.element = choice_GeneralName_directoryName; ret = hx509_name_to_Name(issuername, &n); if (ret) { hx509_set_error_string(context, 0, ret, "out of memory"); goto out; } gn.u.directoryName.element = n.element; gn.u.directoryName.u.rdnSequence = n.u.rdnSequence; ret = add_GeneralNames(&crlissuer, &gn); free_Name(&n); if (ret) { hx509_set_error_string(context, 0, ret, "out of memory"); goto out; } dp.cRLIssuer = &crlissuer; #endif } ret = add_CRLDistributionPoints(&tbs->crldp, &dp); if (ret) { hx509_set_error_string(context, 0, ret, "out of memory"); goto out; } out: free_DistributionPoint(&dp); return ret; } /** * Add Subject Alternative Name otherName to the to-be-signed * certificate object. * * @param context A hx509 context. * @param tbs object to be signed. * @param oid the oid of the OtherName. * @param os data in the other name. * * @return An hx509 error code, see hx509_get_error_string(). * * @ingroup hx509_ca */ int hx509_ca_tbs_add_san_otherName(hx509_context context, hx509_ca_tbs tbs, const heim_oid *oid, const heim_octet_string *os) { GeneralName gn; memset(&gn, 0, sizeof(gn)); gn.element = choice_GeneralName_otherName; gn.u.otherName.type_id = *oid; gn.u.otherName.value = *os; return add_GeneralNames(&tbs->san, &gn); } /** * Add Kerberos Subject Alternative Name to the to-be-signed * certificate object. The principal string is a UTF8 string. * * @param context A hx509 context. * @param tbs object to be signed. * @param principal Kerberos principal to add to the certificate. * * @return An hx509 error code, see hx509_get_error_string(). * * @ingroup hx509_ca */ int hx509_ca_tbs_add_san_pkinit(hx509_context context, hx509_ca_tbs tbs, const char *principal) { heim_octet_string os; KRB5PrincipalName p; size_t size; int ret; char *s = NULL; memset(&p, 0, sizeof(p)); /* parse principal */ { const char *str; char *q; int n; /* count number of component */ n = 1; for(str = principal; *str != '\0' && *str != '@'; str++){ if(*str=='\\'){ if(str[1] == '\0' || str[1] == '@') { ret = HX509_PARSING_NAME_FAILED; hx509_set_error_string(context, 0, ret, "trailing \\ in principal name"); goto out; } str++; } else if(*str == '/') n++; } p.principalName.name_string.val = calloc(n, sizeof(*p.principalName.name_string.val)); if (p.principalName.name_string.val == NULL) { ret = ENOMEM; hx509_set_error_string(context, 0, ret, "malloc: out of memory"); goto out; } p.principalName.name_string.len = n; p.principalName.name_type = KRB5_NT_PRINCIPAL; q = s = strdup(principal); if (q == NULL) { ret = ENOMEM; hx509_set_error_string(context, 0, ret, "malloc: out of memory"); goto out; } p.realm = strrchr(q, '@'); if (p.realm == NULL) { ret = HX509_PARSING_NAME_FAILED; hx509_set_error_string(context, 0, ret, "Missing @ in principal"); goto out; }; *p.realm++ = '\0'; n = 0; while (q) { p.principalName.name_string.val[n++] = q; q = strchr(q, '/'); if (q) *q++ = '\0'; } } ASN1_MALLOC_ENCODE(KRB5PrincipalName, os.data, os.length, &p, &size, ret); if (ret) { hx509_set_error_string(context, 0, ret, "Out of memory"); goto out; } if (size != os.length) _hx509_abort("internal ASN.1 encoder error"); ret = hx509_ca_tbs_add_san_otherName(context, tbs, &asn1_oid_id_pkinit_san, &os); free(os.data); out: if (p.principalName.name_string.val) free (p.principalName.name_string.val); if (s) free(s); return ret; } /* * */ static int add_utf8_san(hx509_context context, hx509_ca_tbs tbs, const heim_oid *oid, const char *string) { const PKIXXmppAddr ustring = (const PKIXXmppAddr)(intptr_t)string; heim_octet_string os; size_t size; int ret; os.length = 0; os.data = NULL; ASN1_MALLOC_ENCODE(PKIXXmppAddr, os.data, os.length, &ustring, &size, ret); if (ret) { hx509_set_error_string(context, 0, ret, "Out of memory"); goto out; } if (size != os.length) _hx509_abort("internal ASN.1 encoder error"); ret = hx509_ca_tbs_add_san_otherName(context, tbs, oid, &os); free(os.data); out: return ret; } /** * Add Microsoft UPN Subject Alternative Name to the to-be-signed * certificate object. The principal string is a UTF8 string. * * @param context A hx509 context. * @param tbs object to be signed. * @param principal Microsoft UPN string. * * @return An hx509 error code, see hx509_get_error_string(). * * @ingroup hx509_ca */ int hx509_ca_tbs_add_san_ms_upn(hx509_context context, hx509_ca_tbs tbs, const char *principal) { return add_utf8_san(context, tbs, &asn1_oid_id_pkinit_ms_san, principal); } /** * Add a Jabber/XMPP jid Subject Alternative Name to the to-be-signed * certificate object. The jid is an UTF8 string. * * @param context A hx509 context. * @param tbs object to be signed. * @param jid string of an a jabber id in UTF8. * * @return An hx509 error code, see hx509_get_error_string(). * * @ingroup hx509_ca */ int hx509_ca_tbs_add_san_jid(hx509_context context, hx509_ca_tbs tbs, const char *jid) { return add_utf8_san(context, tbs, &asn1_oid_id_pkix_on_xmppAddr, jid); } /** * Add a Subject Alternative Name hostname to to-be-signed certificate * object. A domain match starts with ., an exact match does not. * * Example of a an domain match: .domain.se matches the hostname * host.domain.se. * * @param context A hx509 context. * @param tbs object to be signed. * @param dnsname a hostame. * * @return An hx509 error code, see hx509_get_error_string(). * * @ingroup hx509_ca */ int hx509_ca_tbs_add_san_hostname(hx509_context context, hx509_ca_tbs tbs, const char *dnsname) { GeneralName gn; memset(&gn, 0, sizeof(gn)); gn.element = choice_GeneralName_dNSName; gn.u.dNSName.data = rk_UNCONST(dnsname); gn.u.dNSName.length = strlen(dnsname); return add_GeneralNames(&tbs->san, &gn); } /** * Add a Subject Alternative Name rfc822 (email address) to * to-be-signed certificate object. * * @param context A hx509 context. * @param tbs object to be signed. * @param rfc822Name a string to a email address. * * @return An hx509 error code, see hx509_get_error_string(). * * @ingroup hx509_ca */ int hx509_ca_tbs_add_san_rfc822name(hx509_context context, hx509_ca_tbs tbs, const char *rfc822Name) { GeneralName gn; memset(&gn, 0, sizeof(gn)); gn.element = choice_GeneralName_rfc822Name; gn.u.rfc822Name.data = rk_UNCONST(rfc822Name); gn.u.rfc822Name.length = strlen(rfc822Name); return add_GeneralNames(&tbs->san, &gn); } /** * Set the subject name of a to-be-signed certificate object. * * @param context A hx509 context. * @param tbs object to be signed. * @param subject the name to set a subject. * * @return An hx509 error code, see hx509_get_error_string(). * * @ingroup hx509_ca */ int hx509_ca_tbs_set_subject(hx509_context context, hx509_ca_tbs tbs, hx509_name subject) { if (tbs->subject) hx509_name_free(&tbs->subject); return hx509_name_copy(context, subject, &tbs->subject); } /** * Set the issuerUniqueID and subjectUniqueID * * These are only supposed to be used considered with version 2 * certificates, replaced by the two extensions SubjectKeyIdentifier * and IssuerKeyIdentifier. This function is to allow application * using legacy protocol to issue them. * * @param context A hx509 context. * @param tbs object to be signed. * @param issuerUniqueID to be set * @param subjectUniqueID to be set * * @return An hx509 error code, see hx509_get_error_string(). * * @ingroup hx509_ca */ int hx509_ca_tbs_set_unique(hx509_context context, hx509_ca_tbs tbs, const heim_bit_string *subjectUniqueID, const heim_bit_string *issuerUniqueID) { int ret; der_free_bit_string(&tbs->subjectUniqueID); der_free_bit_string(&tbs->issuerUniqueID); if (subjectUniqueID) { ret = der_copy_bit_string(subjectUniqueID, &tbs->subjectUniqueID); if (ret) return ret; } if (issuerUniqueID) { ret = der_copy_bit_string(issuerUniqueID, &tbs->issuerUniqueID); if (ret) return ret; } return 0; } /** * Expand the the subject name in the to-be-signed certificate object * using hx509_name_expand(). * * @param context A hx509 context. * @param tbs object to be signed. * @param env environment variable to expand variables in the subject * name, see hx509_env_init(). * * @return An hx509 error code, see hx509_get_error_string(). * * @ingroup hx509_ca */ int hx509_ca_tbs_subject_expand(hx509_context context, hx509_ca_tbs tbs, hx509_env env) { return hx509_name_expand(context, tbs->subject, env); } /** * Set signature algorithm on the to be signed certificate * * @param context A hx509 context. * @param tbs object to be signed. * @param sigalg signature algorithm to use * * @return An hx509 error code, see hx509_get_error_string(). * * @ingroup hx509_ca */ int hx509_ca_tbs_set_signature_algorithm(hx509_context context, hx509_ca_tbs tbs, const AlgorithmIdentifier *sigalg) { int ret; tbs->sigalg = calloc(1, sizeof(*tbs->sigalg)); if (tbs->sigalg == NULL) { hx509_set_error_string(context, 0, ENOMEM, "Out of memory"); return ENOMEM; } ret = copy_AlgorithmIdentifier(sigalg, tbs->sigalg); if (ret) { free(tbs->sigalg); tbs->sigalg = NULL; return ret; } return 0; } /* * */ static int add_extension(hx509_context context, TBSCertificate *tbsc, int critical_flag, const heim_oid *oid, const heim_octet_string *data) { Extension ext; int ret; memset(&ext, 0, sizeof(ext)); if (critical_flag) { ext.critical = malloc(sizeof(*ext.critical)); if (ext.critical == NULL) { ret = ENOMEM; hx509_set_error_string(context, 0, ret, "Out of memory"); goto out; } *ext.critical = TRUE; } ret = der_copy_oid(oid, &ext.extnID); if (ret) { hx509_set_error_string(context, 0, ret, "Out of memory"); goto out; } ret = der_copy_octet_string(data, &ext.extnValue); if (ret) { hx509_set_error_string(context, 0, ret, "Out of memory"); goto out; } ret = add_Extensions(tbsc->extensions, &ext); if (ret) { hx509_set_error_string(context, 0, ret, "Out of memory"); goto out; } out: free_Extension(&ext); return ret; } static int build_proxy_prefix(hx509_context context, const Name *issuer, Name *subject) { char *tstr; time_t t; int ret; ret = copy_Name(issuer, subject); if (ret) { hx509_set_error_string(context, 0, ret, "Failed to copy subject name"); return ret; } t = time(NULL); ret = asprintf(&tstr, "ts-%lu", (unsigned long)t); if (ret == -1 || tstr == NULL) { hx509_set_error_string(context, 0, ENOMEM, "Failed to copy subject name"); return ENOMEM; } /* prefix with CN=,...*/ ret = _hx509_name_modify(context, subject, 1, &asn1_oid_id_at_commonName, tstr); free(tstr); if (ret) free_Name(subject); return ret; } static int ca_sign(hx509_context context, hx509_ca_tbs tbs, hx509_private_key signer, const AuthorityKeyIdentifier *ai, const Name *issuername, hx509_cert *certificate) { heim_error_t error = NULL; heim_octet_string data; Certificate c; TBSCertificate *tbsc; size_t size; int ret; const AlgorithmIdentifier *sigalg; time_t notBefore; time_t notAfter; unsigned key_usage; sigalg = tbs->sigalg; if (sigalg == NULL) sigalg = _hx509_crypto_default_sig_alg; memset(&c, 0, sizeof(c)); /* * Default values are: Valid since 24h ago, valid one year into * the future, KeyUsage digitalSignature and keyEncipherment set, * and keyCertSign for CA certificates. */ notBefore = tbs->notBefore; if (notBefore == 0) notBefore = time(NULL) - 3600 * 24; notAfter = tbs->notAfter; if (notAfter == 0) notAfter = time(NULL) + 3600 * 24 * 365; key_usage = tbs->key_usage; if (key_usage == 0) { KeyUsage ku; memset(&ku, 0, sizeof(ku)); ku.digitalSignature = 1; ku.keyEncipherment = 1; key_usage = KeyUsage2int(ku); } if (tbs->flags.ca) { KeyUsage ku; memset(&ku, 0, sizeof(ku)); ku.keyCertSign = 1; ku.cRLSign = 1; key_usage |= KeyUsage2int(ku); } /* * */ tbsc = &c.tbsCertificate; if (tbs->flags.key == 0) { ret = EINVAL; hx509_set_error_string(context, 0, ret, "No public key set"); return ret; } /* * Don't put restrictions on proxy certificate's subject name, it * will be generated below. */ if (!tbs->flags.proxy) { if (tbs->subject == NULL) { hx509_set_error_string(context, 0, EINVAL, "No subject name set"); return EINVAL; } if (hx509_name_is_null_p(tbs->subject) && tbs->san.len == 0) { hx509_set_error_string(context, 0, EINVAL, "NULL subject and no SubjectAltNames"); return EINVAL; } } if (tbs->flags.ca && tbs->flags.proxy) { hx509_set_error_string(context, 0, EINVAL, "Can't be proxy and CA " "at the same time"); return EINVAL; } if (tbs->flags.proxy) { if (tbs->san.len > 0) { hx509_set_error_string(context, 0, EINVAL, "Proxy certificate is not allowed " "to have SubjectAltNames"); return EINVAL; } } /* version [0] Version OPTIONAL, -- EXPLICIT nnn DEFAULT 1, */ tbsc->version = calloc(1, sizeof(*tbsc->version)); if (tbsc->version == NULL) { ret = ENOMEM; hx509_set_error_string(context, 0, ret, "Out of memory"); goto out; } *tbsc->version = rfc3280_version_3; /* serialNumber CertificateSerialNumber, */ if (tbs->flags.serial) { ret = der_copy_heim_integer(&tbs->serial, &tbsc->serialNumber); if (ret) { hx509_set_error_string(context, 0, ret, "Out of memory"); goto out; } } else { /* * If no explicit serial number is specified, 20 random bytes should be * sufficiently collision resistant. Since the serial number must be a * positive integer, ensure minimal ASN.1 DER form by forcing the high * bit off and the next bit on (thus avoiding an all zero first octet). */ tbsc->serialNumber.length = 20; tbsc->serialNumber.data = malloc(tbsc->serialNumber.length); if (tbsc->serialNumber.data == NULL){ ret = ENOMEM; hx509_set_error_string(context, 0, ret, "Out of memory"); goto out; } RAND_bytes(tbsc->serialNumber.data, tbsc->serialNumber.length); ((unsigned char *)tbsc->serialNumber.data)[0] &= 0x7f; ((unsigned char *)tbsc->serialNumber.data)[0] |= 0x40; } /* signature AlgorithmIdentifier, */ ret = copy_AlgorithmIdentifier(sigalg, &tbsc->signature); if (ret) { hx509_set_error_string(context, 0, ret, "Failed to copy sigature alg"); goto out; } /* issuer Name, */ if (issuername) ret = copy_Name(issuername, &tbsc->issuer); else ret = hx509_name_to_Name(tbs->subject, &tbsc->issuer); if (ret) { hx509_set_error_string(context, 0, ret, "Failed to copy issuer name"); goto out; } /* validity Validity, */ tbsc->validity.notBefore.element = choice_Time_generalTime; tbsc->validity.notBefore.u.generalTime = notBefore; tbsc->validity.notAfter.element = choice_Time_generalTime; tbsc->validity.notAfter.u.generalTime = notAfter; /* subject Name, */ if (tbs->flags.proxy) { ret = build_proxy_prefix(context, &tbsc->issuer, &tbsc->subject); if (ret) goto out; } else { ret = hx509_name_to_Name(tbs->subject, &tbsc->subject); if (ret) { hx509_set_error_string(context, 0, ret, "Failed to copy subject name"); goto out; } } /* subjectPublicKeyInfo SubjectPublicKeyInfo, */ ret = copy_SubjectPublicKeyInfo(&tbs->spki, &tbsc->subjectPublicKeyInfo); if (ret) { hx509_set_error_string(context, 0, ret, "Failed to copy spki"); goto out; } /* issuerUniqueID [1] IMPLICIT BIT STRING OPTIONAL */ if (tbs->issuerUniqueID.length) { tbsc->issuerUniqueID = calloc(1, sizeof(*tbsc->issuerUniqueID)); if (tbsc->issuerUniqueID == NULL) { ret = ENOMEM; hx509_set_error_string(context, 0, ret, "Out of memory"); goto out; } ret = der_copy_bit_string(&tbs->issuerUniqueID, tbsc->issuerUniqueID); if (ret) { hx509_set_error_string(context, 0, ret, "Out of memory"); goto out; } } /* subjectUniqueID [2] IMPLICIT BIT STRING OPTIONAL */ if (tbs->subjectUniqueID.length) { tbsc->subjectUniqueID = calloc(1, sizeof(*tbsc->subjectUniqueID)); if (tbsc->subjectUniqueID == NULL) { ret = ENOMEM; hx509_set_error_string(context, 0, ret, "Out of memory"); goto out; } ret = der_copy_bit_string(&tbs->subjectUniqueID, tbsc->subjectUniqueID); if (ret) { hx509_set_error_string(context, 0, ret, "Out of memory"); goto out; } } /* extensions [3] EXPLICIT Extensions OPTIONAL */ tbsc->extensions = calloc(1, sizeof(*tbsc->extensions)); if (tbsc->extensions == NULL) { ret = ENOMEM; hx509_set_error_string(context, 0, ret, "Out of memory"); goto out; } /* Add the text BMP string Domaincontroller to the cert */ if (tbs->flags.domaincontroller) { data.data = rk_UNCONST("\x1e\x20\x00\x44\x00\x6f\x00\x6d" "\x00\x61\x00\x69\x00\x6e\x00\x43" "\x00\x6f\x00\x6e\x00\x74\x00\x72" "\x00\x6f\x00\x6c\x00\x6c\x00\x65" "\x00\x72"); data.length = 34; ret = add_extension(context, tbsc, 0, &asn1_oid_id_ms_cert_enroll_domaincontroller, &data); if (ret) goto out; } /* add KeyUsage */ { KeyUsage ku; ku = int2KeyUsage(key_usage); ASN1_MALLOC_ENCODE(KeyUsage, data.data, data.length, &ku, &size, ret); if (ret) { hx509_set_error_string(context, 0, ret, "Out of memory"); goto out; } if (size != data.length) _hx509_abort("internal ASN.1 encoder error"); ret = add_extension(context, tbsc, 1, &asn1_oid_id_x509_ce_keyUsage, &data); free(data.data); if (ret) goto out; } /* add ExtendedKeyUsage */ if (tbs->eku.len > 0) { ASN1_MALLOC_ENCODE(ExtKeyUsage, data.data, data.length, &tbs->eku, &size, ret); if (ret) { hx509_set_error_string(context, 0, ret, "Out of memory"); goto out; } if (size != data.length) _hx509_abort("internal ASN.1 encoder error"); ret = add_extension(context, tbsc, 0, &asn1_oid_id_x509_ce_extKeyUsage, &data); free(data.data); if (ret) goto out; } /* add Subject Alternative Name */ if (tbs->san.len > 0) { ASN1_MALLOC_ENCODE(GeneralNames, data.data, data.length, &tbs->san, &size, ret); if (ret) { hx509_set_error_string(context, 0, ret, "Out of memory"); goto out; } if (size != data.length) _hx509_abort("internal ASN.1 encoder error"); ret = add_extension(context, tbsc, 0, &asn1_oid_id_x509_ce_subjectAltName, &data); free(data.data); if (ret) goto out; } /* Add Authority Key Identifier */ if (ai) { ASN1_MALLOC_ENCODE(AuthorityKeyIdentifier, data.data, data.length, ai, &size, ret); if (ret) { hx509_set_error_string(context, 0, ret, "Out of memory"); goto out; } if (size != data.length) _hx509_abort("internal ASN.1 encoder error"); ret = add_extension(context, tbsc, 0, &asn1_oid_id_x509_ce_authorityKeyIdentifier, &data); free(data.data); if (ret) goto out; } /* Add Subject Key Identifier */ { SubjectKeyIdentifier si; unsigned char hash[SHA_DIGEST_LENGTH]; { EVP_MD_CTX *ctx; ctx = EVP_MD_CTX_create(); EVP_DigestInit_ex(ctx, EVP_sha1(), NULL); EVP_DigestUpdate(ctx, tbs->spki.subjectPublicKey.data, tbs->spki.subjectPublicKey.length / 8); EVP_DigestFinal_ex(ctx, hash, NULL); EVP_MD_CTX_destroy(ctx); } si.data = hash; si.length = sizeof(hash); ASN1_MALLOC_ENCODE(SubjectKeyIdentifier, data.data, data.length, &si, &size, ret); if (ret) { hx509_set_error_string(context, 0, ret, "Out of memory"); goto out; } if (size != data.length) _hx509_abort("internal ASN.1 encoder error"); ret = add_extension(context, tbsc, 0, &asn1_oid_id_x509_ce_subjectKeyIdentifier, &data); free(data.data); if (ret) goto out; } /* Add BasicConstraints */ { BasicConstraints bc; int aCA = 1; unsigned int path; memset(&bc, 0, sizeof(bc)); if (tbs->flags.ca) { bc.cA = &aCA; if (tbs->pathLenConstraint >= 0) { path = tbs->pathLenConstraint; bc.pathLenConstraint = &path; } } ASN1_MALLOC_ENCODE(BasicConstraints, data.data, data.length, &bc, &size, ret); if (ret) { hx509_set_error_string(context, 0, ret, "Out of memory"); goto out; } if (size != data.length) _hx509_abort("internal ASN.1 encoder error"); /* Critical if this is a CA */ ret = add_extension(context, tbsc, tbs->flags.ca, &asn1_oid_id_x509_ce_basicConstraints, &data); free(data.data); if (ret) goto out; } /* add Proxy */ if (tbs->flags.proxy) { ProxyCertInfo info; memset(&info, 0, sizeof(info)); if (tbs->pathLenConstraint >= 0) { info.pCPathLenConstraint = malloc(sizeof(*info.pCPathLenConstraint)); if (info.pCPathLenConstraint == NULL) { ret = ENOMEM; hx509_set_error_string(context, 0, ret, "Out of memory"); goto out; } *info.pCPathLenConstraint = tbs->pathLenConstraint; } ret = der_copy_oid(&asn1_oid_id_pkix_ppl_inheritAll, &info.proxyPolicy.policyLanguage); if (ret) { free_ProxyCertInfo(&info); hx509_set_error_string(context, 0, ret, "Out of memory"); goto out; } ASN1_MALLOC_ENCODE(ProxyCertInfo, data.data, data.length, &info, &size, ret); free_ProxyCertInfo(&info); if (ret) { hx509_set_error_string(context, 0, ret, "Out of memory"); goto out; } if (size != data.length) _hx509_abort("internal ASN.1 encoder error"); ret = add_extension(context, tbsc, 0, &asn1_oid_id_pkix_pe_proxyCertInfo, &data); free(data.data); if (ret) goto out; } if (tbs->crldp.len) { ASN1_MALLOC_ENCODE(CRLDistributionPoints, data.data, data.length, &tbs->crldp, &size, ret); if (ret) { hx509_set_error_string(context, 0, ret, "Out of memory"); goto out; } if (size != data.length) _hx509_abort("internal ASN.1 encoder error"); ret = add_extension(context, tbsc, FALSE, &asn1_oid_id_x509_ce_cRLDistributionPoints, &data); free(data.data); if (ret) goto out; } ASN1_MALLOC_ENCODE(TBSCertificate, data.data, data.length,tbsc, &size, ret); if (ret) { hx509_set_error_string(context, 0, ret, "malloc out of memory"); goto out; } if (data.length != size) _hx509_abort("internal ASN.1 encoder error"); ret = _hx509_create_signature_bitstring(context, signer, sigalg, &data, &c.signatureAlgorithm, &c.signatureValue); free(data.data); if (ret) goto out; *certificate = hx509_cert_init(context, &c, &error); if (*certificate == NULL) { ret = heim_error_get_code(error); heim_release(error); goto out; } free_Certificate(&c); return 0; out: free_Certificate(&c); return ret; } static int get_AuthorityKeyIdentifier(hx509_context context, const Certificate *certificate, AuthorityKeyIdentifier *ai) { SubjectKeyIdentifier si; int ret; ret = _hx509_find_extension_subject_key_id(certificate, &si); if (ret == 0) { ai->keyIdentifier = calloc(1, sizeof(*ai->keyIdentifier)); if (ai->keyIdentifier == NULL) { free_SubjectKeyIdentifier(&si); ret = ENOMEM; hx509_set_error_string(context, 0, ret, "Out of memory"); goto out; } ret = der_copy_octet_string(&si, ai->keyIdentifier); free_SubjectKeyIdentifier(&si); if (ret) { hx509_set_error_string(context, 0, ret, "Out of memory"); goto out; } } else { GeneralNames gns; GeneralName gn; Name name; memset(&gn, 0, sizeof(gn)); memset(&gns, 0, sizeof(gns)); memset(&name, 0, sizeof(name)); ai->authorityCertIssuer = calloc(1, sizeof(*ai->authorityCertIssuer)); if (ai->authorityCertIssuer == NULL) { ret = ENOMEM; hx509_set_error_string(context, 0, ret, "Out of memory"); goto out; } ai->authorityCertSerialNumber = calloc(1, sizeof(*ai->authorityCertSerialNumber)); if (ai->authorityCertSerialNumber == NULL) { ret = ENOMEM; hx509_set_error_string(context, 0, ret, "Out of memory"); goto out; } /* * XXX unbreak when asn1 compiler handle IMPLICIT * * This is so horrible. */ ret = copy_Name(&certificate->tbsCertificate.subject, &name); if (ret) { hx509_set_error_string(context, 0, ret, "Out of memory"); goto out; } memset(&gn, 0, sizeof(gn)); gn.element = choice_GeneralName_directoryName; gn.u.directoryName.element = choice_GeneralName_directoryName_rdnSequence; gn.u.directoryName.u.rdnSequence = name.u.rdnSequence; ret = add_GeneralNames(&gns, &gn); if (ret) { hx509_set_error_string(context, 0, ret, "Out of memory"); goto out; } ai->authorityCertIssuer->val = gns.val; ai->authorityCertIssuer->len = gns.len; ret = der_copy_heim_integer(&certificate->tbsCertificate.serialNumber, ai->authorityCertSerialNumber); if (ai->authorityCertSerialNumber == NULL) { ret = ENOMEM; hx509_set_error_string(context, 0, ret, "Out of memory"); goto out; } } out: if (ret) free_AuthorityKeyIdentifier(ai); return ret; } /** * Sign a to-be-signed certificate object with a issuer certificate. * * The caller needs to at least have called the following functions on the * to-be-signed certificate object: * - hx509_ca_tbs_init() * - hx509_ca_tbs_set_subject() * - hx509_ca_tbs_set_spki() * * When done the to-be-signed certificate object should be freed with * hx509_ca_tbs_free(). * * When creating self-signed certificate use hx509_ca_sign_self() instead. * * @param context A hx509 context. * @param tbs object to be signed. * @param signer the CA certificate object to sign with (need private key). * @param certificate return cerificate, free with hx509_cert_free(). * * @return An hx509 error code, see hx509_get_error_string(). * * @ingroup hx509_ca */ int hx509_ca_sign(hx509_context context, hx509_ca_tbs tbs, hx509_cert signer, hx509_cert *certificate) { const Certificate *signer_cert; AuthorityKeyIdentifier ai; int ret; memset(&ai, 0, sizeof(ai)); signer_cert = _hx509_get_cert(signer); ret = get_AuthorityKeyIdentifier(context, signer_cert, &ai); if (ret) goto out; ret = ca_sign(context, tbs, _hx509_cert_private_key(signer), &ai, &signer_cert->tbsCertificate.subject, certificate); out: free_AuthorityKeyIdentifier(&ai); return ret; } /** * Work just like hx509_ca_sign() but signs it-self. * * @param context A hx509 context. * @param tbs object to be signed. * @param signer private key to sign with. * @param certificate return cerificate, free with hx509_cert_free(). * * @return An hx509 error code, see hx509_get_error_string(). * * @ingroup hx509_ca */ int hx509_ca_sign_self(hx509_context context, hx509_ca_tbs tbs, hx509_private_key signer, hx509_cert *certificate) { return ca_sign(context, tbs, signer, NULL, NULL, certificate); } heimdal-7.5.0/lib/hx509/softp11.c0000644000175000017500000012723613212137553014353 0ustar niknik/* * Copyright (c) 2004 - 2008 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #define CRYPTOKI_EXPORTS 1 #include "hx_locl.h" #include "ref/pkcs11.h" #define OBJECT_ID_MASK 0xfff #define HANDLE_OBJECT_ID(h) ((h) & OBJECT_ID_MASK) #define OBJECT_ID(obj) HANDLE_OBJECT_ID((obj)->object_handle) #ifndef HAVE_RANDOM #define random() rand() #define srandom(s) srand(s) #endif #ifdef _WIN32 #include #endif struct st_attr { CK_ATTRIBUTE attribute; int secret; }; struct st_object { CK_OBJECT_HANDLE object_handle; struct st_attr *attrs; int num_attributes; hx509_cert cert; }; static struct soft_token { CK_VOID_PTR application; CK_NOTIFY notify; char *config_file; hx509_certs certs; struct { struct st_object **objs; int num_objs; } object; struct { int hardware_slot; int app_error_fatal; int login_done; } flags; int open_sessions; struct session_state { CK_SESSION_HANDLE session_handle; struct { CK_ATTRIBUTE *attributes; CK_ULONG num_attributes; int next_object; } find; int sign_object; CK_MECHANISM_PTR sign_mechanism; int verify_object; CK_MECHANISM_PTR verify_mechanism; } state[10]; #define MAX_NUM_SESSION (sizeof(soft_token.state)/sizeof(soft_token.state[0])) FILE *logfile; } soft_token; static hx509_context context; static void application_error(const char *fmt, ...) { va_list ap; va_start(ap, fmt); vprintf(fmt, ap); va_end(ap); if (soft_token.flags.app_error_fatal) abort(); } static void st_logf(const char *fmt, ...) { va_list ap; if (soft_token.logfile == NULL) return; va_start(ap, fmt); vfprintf(soft_token.logfile, fmt, ap); va_end(ap); fflush(soft_token.logfile); } static CK_RV init_context(void) { if (context == NULL) { int ret = hx509_context_init(&context); if (ret) return CKR_GENERAL_ERROR; } return CKR_OK; } #define INIT_CONTEXT() { CK_RV icret = init_context(); if (icret) return icret; } static void snprintf_fill(char *str, size_t size, char fillchar, const char *fmt, ...) { int len; va_list ap; va_start(ap, fmt); len = vsnprintf(str, size, fmt, ap); va_end(ap); if (len < 0 || (size_t)len > size) return; while ((size_t)len < size) str[len++] = fillchar; } #ifndef TEST_APP #define printf error_use_st_logf #endif #define VERIFY_SESSION_HANDLE(s, state) \ { \ CK_RV xret; \ xret = verify_session_handle(s, state); \ if (xret != CKR_OK) { \ /* return CKR_OK */; \ } \ } static CK_RV verify_session_handle(CK_SESSION_HANDLE hSession, struct session_state **state) { size_t i; for (i = 0; i < MAX_NUM_SESSION; i++){ if (soft_token.state[i].session_handle == hSession) break; } if (i == MAX_NUM_SESSION) { application_error("use of invalid handle: 0x%08lx\n", (unsigned long)hSession); return CKR_SESSION_HANDLE_INVALID; } if (state) *state = &soft_token.state[i]; return CKR_OK; } static CK_RV object_handle_to_object(CK_OBJECT_HANDLE handle, struct st_object **object) { int i = HANDLE_OBJECT_ID(handle); *object = NULL; if (i >= soft_token.object.num_objs) return CKR_ARGUMENTS_BAD; if (soft_token.object.objs[i] == NULL) return CKR_ARGUMENTS_BAD; if (soft_token.object.objs[i]->object_handle != handle) return CKR_ARGUMENTS_BAD; *object = soft_token.object.objs[i]; return CKR_OK; } static int attributes_match(const struct st_object *obj, const CK_ATTRIBUTE *attributes, CK_ULONG num_attributes) { CK_ULONG i; int j; st_logf("attributes_match: %ld\n", (unsigned long)OBJECT_ID(obj)); for (i = 0; i < num_attributes; i++) { int match = 0; for (j = 0; j < obj->num_attributes; j++) { if (attributes[i].type == obj->attrs[j].attribute.type && attributes[i].ulValueLen == obj->attrs[j].attribute.ulValueLen && memcmp(attributes[i].pValue, obj->attrs[j].attribute.pValue, attributes[i].ulValueLen) == 0) { match = 1; break; } } if (match == 0) { st_logf("type %d attribute have no match\n", attributes[i].type); return 0; } } st_logf("attribute matches\n"); return 1; } static void print_attributes(const CK_ATTRIBUTE *attributes, CK_ULONG num_attributes) { CK_ULONG i; st_logf("find objects: attrs: %lu\n", (unsigned long)num_attributes); for (i = 0; i < num_attributes; i++) { st_logf(" type: "); switch (attributes[i].type) { case CKA_TOKEN: { CK_BBOOL *ck_true; if (attributes[i].ulValueLen != sizeof(CK_BBOOL)) { application_error("token attribute wrong length\n"); break; } ck_true = attributes[i].pValue; st_logf("token: %s", *ck_true ? "TRUE" : "FALSE"); break; } case CKA_CLASS: { CK_OBJECT_CLASS *class; if (attributes[i].ulValueLen != sizeof(CK_ULONG)) { application_error("class attribute wrong length\n"); break; } class = attributes[i].pValue; st_logf("class "); switch (*class) { case CKO_CERTIFICATE: st_logf("certificate"); break; case CKO_PUBLIC_KEY: st_logf("public key"); break; case CKO_PRIVATE_KEY: st_logf("private key"); break; case CKO_SECRET_KEY: st_logf("secret key"); break; case CKO_DOMAIN_PARAMETERS: st_logf("domain parameters"); break; default: st_logf("[class %lx]", (long unsigned)*class); break; } break; } case CKA_PRIVATE: st_logf("private"); break; case CKA_LABEL: st_logf("label"); break; case CKA_APPLICATION: st_logf("application"); break; case CKA_VALUE: st_logf("value"); break; case CKA_ID: st_logf("id"); break; default: st_logf("[unknown 0x%08lx]", (unsigned long)attributes[i].type); break; } st_logf("\n"); } } static struct st_object * add_st_object(void) { struct st_object *o, **objs; int i; o = calloc(1, sizeof(*o)); if (o == NULL) return NULL; for (i = 0; i < soft_token.object.num_objs; i++) { if (soft_token.object.objs == NULL) { soft_token.object.objs[i] = o; break; } } if (i == soft_token.object.num_objs) { objs = realloc(soft_token.object.objs, (soft_token.object.num_objs + 1) * sizeof(soft_token.object.objs[0])); if (objs == NULL) { free(o); return NULL; } soft_token.object.objs = objs; soft_token.object.objs[soft_token.object.num_objs++] = o; } soft_token.object.objs[i]->object_handle = (random() & (~OBJECT_ID_MASK)) | i; return o; } static CK_RV add_object_attribute(struct st_object *o, int secret, CK_ATTRIBUTE_TYPE type, CK_VOID_PTR pValue, CK_ULONG ulValueLen) { struct st_attr *a; int i; i = o->num_attributes; a = realloc(o->attrs, (i + 1) * sizeof(o->attrs[0])); if (a == NULL) return CKR_DEVICE_MEMORY; o->attrs = a; o->attrs[i].secret = secret; o->attrs[i].attribute.type = type; o->attrs[i].attribute.pValue = malloc(ulValueLen); if (o->attrs[i].attribute.pValue == NULL && ulValueLen != 0) return CKR_DEVICE_MEMORY; memcpy(o->attrs[i].attribute.pValue, pValue, ulValueLen); o->attrs[i].attribute.ulValueLen = ulValueLen; o->num_attributes++; return CKR_OK; } static CK_RV add_pubkey_info(hx509_context hxctx, struct st_object *o, CK_KEY_TYPE key_type, hx509_cert cert) { BIGNUM *num; CK_BYTE *modulus = NULL; size_t modulus_len = 0; CK_ULONG modulus_bits = 0; CK_BYTE *exponent = NULL; size_t exponent_len = 0; if (key_type != CKK_RSA) return CKR_OK; if (_hx509_cert_private_key(cert) == NULL) return CKR_OK; num = _hx509_private_key_get_internal(context, _hx509_cert_private_key(cert), "rsa-modulus"); if (num == NULL) return CKR_GENERAL_ERROR; modulus_bits = BN_num_bits(num); modulus_len = BN_num_bytes(num); modulus = malloc(modulus_len); BN_bn2bin(num, modulus); BN_free(num); add_object_attribute(o, 0, CKA_MODULUS, modulus, modulus_len); add_object_attribute(o, 0, CKA_MODULUS_BITS, &modulus_bits, sizeof(modulus_bits)); free(modulus); num = _hx509_private_key_get_internal(context, _hx509_cert_private_key(cert), "rsa-exponent"); if (num == NULL) return CKR_GENERAL_ERROR; exponent_len = BN_num_bytes(num); exponent = malloc(exponent_len); BN_bn2bin(num, exponent); BN_free(num); add_object_attribute(o, 0, CKA_PUBLIC_EXPONENT, exponent, exponent_len); free(exponent); return CKR_OK; } struct foo { char *label; char *id; }; static int add_cert(hx509_context hxctx, void *ctx, hx509_cert cert) { static char empty[] = ""; struct foo *foo = (struct foo *)ctx; struct st_object *o = NULL; CK_OBJECT_CLASS type; CK_BBOOL bool_true = CK_TRUE; CK_BBOOL bool_false = CK_FALSE; CK_CERTIFICATE_TYPE cert_type = CKC_X_509; CK_KEY_TYPE key_type; CK_MECHANISM_TYPE mech_type; CK_RV ret = CKR_GENERAL_ERROR; int hret; heim_octet_string cert_data, subject_data, issuer_data, serial_data; st_logf("adding certificate\n"); serial_data.data = NULL; serial_data.length = 0; cert_data = subject_data = issuer_data = serial_data; hret = hx509_cert_binary(hxctx, cert, &cert_data); if (hret) goto out; { hx509_name name; hret = hx509_cert_get_issuer(cert, &name); if (hret) goto out; hret = hx509_name_binary(name, &issuer_data); hx509_name_free(&name); if (hret) goto out; hret = hx509_cert_get_subject(cert, &name); if (hret) goto out; hret = hx509_name_binary(name, &subject_data); hx509_name_free(&name); if (hret) goto out; } { AlgorithmIdentifier alg; hret = hx509_cert_get_SPKI_AlgorithmIdentifier(context, cert, &alg); if (hret) { ret = CKR_DEVICE_MEMORY; goto out; } key_type = CKK_RSA; /* XXX */ free_AlgorithmIdentifier(&alg); } type = CKO_CERTIFICATE; o = add_st_object(); if (o == NULL) { ret = CKR_DEVICE_MEMORY; goto out; } o->cert = hx509_cert_ref(cert); add_object_attribute(o, 0, CKA_CLASS, &type, sizeof(type)); add_object_attribute(o, 0, CKA_TOKEN, &bool_true, sizeof(bool_true)); add_object_attribute(o, 0, CKA_PRIVATE, &bool_false, sizeof(bool_false)); add_object_attribute(o, 0, CKA_MODIFIABLE, &bool_false, sizeof(bool_false)); add_object_attribute(o, 0, CKA_LABEL, foo->label, strlen(foo->label)); add_object_attribute(o, 0, CKA_CERTIFICATE_TYPE, &cert_type, sizeof(cert_type)); add_object_attribute(o, 0, CKA_ID, foo->id, strlen(foo->id)); add_object_attribute(o, 0, CKA_SUBJECT, subject_data.data, subject_data.length); add_object_attribute(o, 0, CKA_ISSUER, issuer_data.data, issuer_data.length); add_object_attribute(o, 0, CKA_SERIAL_NUMBER, serial_data.data, serial_data.length); add_object_attribute(o, 0, CKA_VALUE, cert_data.data, cert_data.length); add_object_attribute(o, 0, CKA_TRUSTED, &bool_false, sizeof(bool_false)); st_logf("add cert ok: %lx\n", (unsigned long)OBJECT_ID(o)); type = CKO_PUBLIC_KEY; o = add_st_object(); if (o == NULL) { ret = CKR_DEVICE_MEMORY; goto out; } o->cert = hx509_cert_ref(cert); add_object_attribute(o, 0, CKA_CLASS, &type, sizeof(type)); add_object_attribute(o, 0, CKA_TOKEN, &bool_true, sizeof(bool_true)); add_object_attribute(o, 0, CKA_PRIVATE, &bool_false, sizeof(bool_false)); add_object_attribute(o, 0, CKA_MODIFIABLE, &bool_false, sizeof(bool_false)); add_object_attribute(o, 0, CKA_LABEL, foo->label, strlen(foo->label)); add_object_attribute(o, 0, CKA_KEY_TYPE, &key_type, sizeof(key_type)); add_object_attribute(o, 0, CKA_ID, foo->id, strlen(foo->id)); add_object_attribute(o, 0, CKA_START_DATE, empty, 1); /* XXX */ add_object_attribute(o, 0, CKA_END_DATE, empty, 1); /* XXX */ add_object_attribute(o, 0, CKA_DERIVE, &bool_false, sizeof(bool_false)); add_object_attribute(o, 0, CKA_LOCAL, &bool_false, sizeof(bool_false)); mech_type = CKM_RSA_X_509; add_object_attribute(o, 0, CKA_KEY_GEN_MECHANISM, &mech_type, sizeof(mech_type)); add_object_attribute(o, 0, CKA_SUBJECT, subject_data.data, subject_data.length); add_object_attribute(o, 0, CKA_ENCRYPT, &bool_true, sizeof(bool_true)); add_object_attribute(o, 0, CKA_VERIFY, &bool_true, sizeof(bool_true)); add_object_attribute(o, 0, CKA_VERIFY_RECOVER, &bool_false, sizeof(bool_false)); add_object_attribute(o, 0, CKA_WRAP, &bool_true, sizeof(bool_true)); add_object_attribute(o, 0, CKA_TRUSTED, &bool_true, sizeof(bool_true)); add_pubkey_info(hxctx, o, key_type, cert); st_logf("add key ok: %lx\n", (unsigned long)OBJECT_ID(o)); if (hx509_cert_have_private_key(cert)) { CK_FLAGS flags; type = CKO_PRIVATE_KEY; /* Note to static analyzers: `o' is still referred to via globals */ o = add_st_object(); if (o == NULL) { ret = CKR_DEVICE_MEMORY; goto out; } o->cert = hx509_cert_ref(cert); add_object_attribute(o, 0, CKA_CLASS, &type, sizeof(type)); add_object_attribute(o, 0, CKA_TOKEN, &bool_true, sizeof(bool_true)); add_object_attribute(o, 0, CKA_PRIVATE, &bool_true, sizeof(bool_false)); add_object_attribute(o, 0, CKA_MODIFIABLE, &bool_false, sizeof(bool_false)); add_object_attribute(o, 0, CKA_LABEL, foo->label, strlen(foo->label)); add_object_attribute(o, 0, CKA_KEY_TYPE, &key_type, sizeof(key_type)); add_object_attribute(o, 0, CKA_ID, foo->id, strlen(foo->id)); add_object_attribute(o, 0, CKA_START_DATE, empty, 1); /* XXX */ add_object_attribute(o, 0, CKA_END_DATE, empty, 1); /* XXX */ add_object_attribute(o, 0, CKA_DERIVE, &bool_false, sizeof(bool_false)); add_object_attribute(o, 0, CKA_LOCAL, &bool_false, sizeof(bool_false)); mech_type = CKM_RSA_X_509; add_object_attribute(o, 0, CKA_KEY_GEN_MECHANISM, &mech_type, sizeof(mech_type)); add_object_attribute(o, 0, CKA_SUBJECT, subject_data.data, subject_data.length); add_object_attribute(o, 0, CKA_SENSITIVE, &bool_true, sizeof(bool_true)); add_object_attribute(o, 0, CKA_SECONDARY_AUTH, &bool_false, sizeof(bool_true)); flags = 0; add_object_attribute(o, 0, CKA_AUTH_PIN_FLAGS, &flags, sizeof(flags)); add_object_attribute(o, 0, CKA_DECRYPT, &bool_true, sizeof(bool_true)); add_object_attribute(o, 0, CKA_SIGN, &bool_true, sizeof(bool_true)); add_object_attribute(o, 0, CKA_SIGN_RECOVER, &bool_false, sizeof(bool_false)); add_object_attribute(o, 0, CKA_UNWRAP, &bool_true, sizeof(bool_true)); add_object_attribute(o, 0, CKA_EXTRACTABLE, &bool_true, sizeof(bool_true)); add_object_attribute(o, 0, CKA_NEVER_EXTRACTABLE, &bool_false, sizeof(bool_false)); add_pubkey_info(hxctx, o, key_type, cert); } ret = CKR_OK; out: if (ret != CKR_OK) { st_logf("something went wrong when adding cert!\n"); /* XXX wack o */; } hx509_xfree(cert_data.data); hx509_xfree(serial_data.data); hx509_xfree(issuer_data.data); hx509_xfree(subject_data.data); /* Note to static analyzers: `o' is still referred to via globals */ return 0; } static CK_RV add_certificate(const char *cert_file, const char *pin, char *id, char *label) { hx509_certs certs; hx509_lock lock = NULL; int ret, flags = 0; struct foo foo; foo.id = id; foo.label = label; if (pin == NULL) flags |= HX509_CERTS_UNPROTECT_ALL; if (pin) { char *str; ret = asprintf(&str, "PASS:%s", pin); if (ret == -1 || !str) { st_logf("failed to allocate memory\n"); return CKR_GENERAL_ERROR; } hx509_lock_init(context, &lock); hx509_lock_command_string(lock, str); memset(str, 0, strlen(str)); free(str); } ret = hx509_certs_init(context, cert_file, flags, lock, &certs); if (ret) { st_logf("failed to open file %s\n", cert_file); return CKR_GENERAL_ERROR; } ret = hx509_certs_iter_f(context, certs, add_cert, &foo); hx509_certs_free(&certs); if (ret) { st_logf("failed adding certs from file %s\n", cert_file); return CKR_GENERAL_ERROR; } return CKR_OK; } static void find_object_final(struct session_state *state) { if (state->find.attributes) { CK_ULONG i; for (i = 0; i < state->find.num_attributes; i++) { if (state->find.attributes[i].pValue) free(state->find.attributes[i].pValue); } free(state->find.attributes); state->find.attributes = NULL; state->find.num_attributes = 0; state->find.next_object = -1; } } static void reset_crypto_state(struct session_state *state) { state->sign_object = -1; if (state->sign_mechanism) free(state->sign_mechanism); state->sign_mechanism = NULL_PTR; state->verify_object = -1; if (state->verify_mechanism) free(state->verify_mechanism); state->verify_mechanism = NULL_PTR; } static void close_session(struct session_state *state) { if (state->find.attributes) { application_error("application didn't do C_FindObjectsFinal\n"); find_object_final(state); } state->session_handle = CK_INVALID_HANDLE; soft_token.application = NULL_PTR; soft_token.notify = NULL_PTR; reset_crypto_state(state); } static const char * has_session(void) { return soft_token.open_sessions > 0 ? "yes" : "no"; } static CK_RV read_conf_file(const char *fn, CK_USER_TYPE userType, const char *pin) { char buf[1024], *type, *s, *p; FILE *f; CK_RV ret = CKR_OK; CK_RV failed = CKR_OK; if (fn == NULL) { st_logf("Can't open configuration file. No file specified\n"); return CKR_GENERAL_ERROR; } f = fopen(fn, "r"); if (f == NULL) { st_logf("can't open configuration file %s\n", fn); return CKR_GENERAL_ERROR; } rk_cloexec_file(f); while(fgets(buf, sizeof(buf), f) != NULL) { buf[strcspn(buf, "\n")] = '\0'; st_logf("line: %s\n", buf); p = buf; while (isspace((unsigned char)*p)) p++; if (*p == '#') continue; while (isspace((unsigned char)*p)) p++; s = NULL; type = strtok_r(p, "\t", &s); if (type == NULL) continue; if (strcasecmp("certificate", type) == 0) { char *cert, *id, *label; id = strtok_r(NULL, "\t", &s); if (id == NULL) { st_logf("no id\n"); continue; } st_logf("id: %s\n", id); label = strtok_r(NULL, "\t", &s); if (label == NULL) { st_logf("no label\n"); continue; } cert = strtok_r(NULL, "\t", &s); if (cert == NULL) { st_logf("no certfiicate store\n"); continue; } st_logf("adding: %s: %s in file %s\n", id, label, cert); ret = add_certificate(cert, pin, id, label); if (ret) failed = ret; } else if (strcasecmp("debug", type) == 0) { char *name; name = strtok_r(NULL, "\t", &s); if (name == NULL) { st_logf("no filename\n"); continue; } if (soft_token.logfile) fclose(soft_token.logfile); if (strcasecmp(name, "stdout") == 0) soft_token.logfile = stdout; else { soft_token.logfile = fopen(name, "a"); if (soft_token.logfile) rk_cloexec_file(soft_token.logfile); } if (soft_token.logfile == NULL) st_logf("failed to open file: %s\n", name); } else if (strcasecmp("app-fatal", type) == 0) { char *name; name = strtok_r(NULL, "\t", &s); if (name == NULL) { st_logf("argument to app-fatal\n"); continue; } if (strcmp(name, "true") == 0 || strcmp(name, "on") == 0) soft_token.flags.app_error_fatal = 1; else if (strcmp(name, "false") == 0 || strcmp(name, "off") == 0) soft_token.flags.app_error_fatal = 0; else st_logf("unknown app-fatal: %s\n", name); } else { st_logf("unknown type: %s\n", type); } } fclose(f); return failed; } static CK_RV func_not_supported(void) { st_logf("function not supported\n"); return CKR_FUNCTION_NOT_SUPPORTED; } static char * get_config_file_for_user(void) { char *fn = NULL; #ifndef _WIN32 char *home = NULL; int ret; if (!issuid()) { fn = getenv("SOFTPKCS11RC"); if (fn) fn = strdup(fn); home = getenv("HOME"); } if (fn == NULL && home == NULL) { struct passwd *pw = getpwuid(getuid()); if(pw != NULL) home = pw->pw_dir; } if (fn == NULL) { if (home) { ret = asprintf(&fn, "%s/.soft-token.rc", home); if (ret == -1) fn = NULL; } else fn = strdup("/etc/soft-token.rc"); } #else /* Windows */ char appdatafolder[MAX_PATH]; fn = getenv("SOFTPKCS11RC"); /* Retrieve the roaming AppData folder for the current user. The current user is the user account represented by the current thread token. */ if (fn == NULL && SUCCEEDED(SHGetFolderPath(NULL, CSIDL_APPDATA, NULL, SHGFP_TYPE_CURRENT, appdatafolder))) { asprintf(&fn, "%s\\.soft-token.rc", appdatafolder); } #endif /* _WIN32 */ return fn; } CK_RV CK_SPEC C_Initialize(CK_VOID_PTR a) { CK_C_INITIALIZE_ARGS_PTR args = a; CK_RV ret; size_t i; st_logf("Initialize\n"); INIT_CONTEXT(); OpenSSL_add_all_algorithms(); srandom(getpid() ^ (int) time(NULL)); for (i = 0; i < MAX_NUM_SESSION; i++) { soft_token.state[i].session_handle = CK_INVALID_HANDLE; soft_token.state[i].find.attributes = NULL; soft_token.state[i].find.num_attributes = 0; soft_token.state[i].find.next_object = -1; reset_crypto_state(&soft_token.state[i]); } soft_token.flags.hardware_slot = 1; soft_token.flags.app_error_fatal = 0; soft_token.flags.login_done = 0; soft_token.object.objs = NULL; soft_token.object.num_objs = 0; soft_token.logfile = NULL; #if 0 soft_token.logfile = stdout; #endif #if 0 soft_token.logfile = fopen("/tmp/log-pkcs11.txt", "a"); #endif if (a != NULL_PTR) { st_logf("\tCreateMutex:\t%p\n", args->CreateMutex); st_logf("\tDestroyMutext\t%p\n", args->DestroyMutex); st_logf("\tLockMutext\t%p\n", args->LockMutex); st_logf("\tUnlockMutext\t%p\n", args->UnlockMutex); st_logf("\tFlags\t%04x\n", (unsigned int)args->flags); } soft_token.config_file = get_config_file_for_user(); /* * This operations doesn't return CKR_OK if any of the * certificates failes to be unparsed (ie password protected). */ ret = read_conf_file(soft_token.config_file, CKU_USER, NULL); if (ret == CKR_OK) soft_token.flags.login_done = 1; return CKR_OK; } CK_RV C_Finalize(CK_VOID_PTR args) { size_t i; INIT_CONTEXT(); st_logf("Finalize\n"); for (i = 0; i < MAX_NUM_SESSION; i++) { if (soft_token.state[i].session_handle != CK_INVALID_HANDLE) { application_error("application finalized without " "closing session\n"); close_session(&soft_token.state[i]); } } return CKR_OK; } CK_RV C_GetInfo(CK_INFO_PTR args) { INIT_CONTEXT(); st_logf("GetInfo\n"); memset(args, 17, sizeof(*args)); args->cryptokiVersion.major = 2; args->cryptokiVersion.minor = 10; snprintf_fill((char *)args->manufacturerID, sizeof(args->manufacturerID), ' ', "Heimdal hx509 SoftToken"); snprintf_fill((char *)args->libraryDescription, sizeof(args->libraryDescription), ' ', "Heimdal hx509 SoftToken"); args->libraryVersion.major = 2; args->libraryVersion.minor = 0; return CKR_OK; } extern CK_FUNCTION_LIST funcs; CK_RV C_GetFunctionList(CK_FUNCTION_LIST_PTR_PTR ppFunctionList) { INIT_CONTEXT(); *ppFunctionList = &funcs; return CKR_OK; } CK_RV C_GetSlotList(CK_BBOOL tokenPresent, CK_SLOT_ID_PTR pSlotList, CK_ULONG_PTR pulCount) { INIT_CONTEXT(); st_logf("GetSlotList: %s\n", tokenPresent ? "tokenPresent" : "token not Present"); if (pSlotList) pSlotList[0] = 1; *pulCount = 1; return CKR_OK; } CK_RV C_GetSlotInfo(CK_SLOT_ID slotID, CK_SLOT_INFO_PTR pInfo) { INIT_CONTEXT(); st_logf("GetSlotInfo: slot: %d : %s\n", (int)slotID, has_session()); memset(pInfo, 18, sizeof(*pInfo)); if (slotID != 1) return CKR_ARGUMENTS_BAD; snprintf_fill((char *)pInfo->slotDescription, sizeof(pInfo->slotDescription), ' ', "Heimdal hx509 SoftToken (slot)"); snprintf_fill((char *)pInfo->manufacturerID, sizeof(pInfo->manufacturerID), ' ', "Heimdal hx509 SoftToken (slot)"); pInfo->flags = CKF_TOKEN_PRESENT; if (soft_token.flags.hardware_slot) pInfo->flags |= CKF_HW_SLOT; pInfo->hardwareVersion.major = 1; pInfo->hardwareVersion.minor = 0; pInfo->firmwareVersion.major = 1; pInfo->firmwareVersion.minor = 0; return CKR_OK; } CK_RV C_GetTokenInfo(CK_SLOT_ID slotID, CK_TOKEN_INFO_PTR pInfo) { INIT_CONTEXT(); st_logf("GetTokenInfo: %s\n", has_session()); memset(pInfo, 19, sizeof(*pInfo)); snprintf_fill((char *)pInfo->label, sizeof(pInfo->label), ' ', "Heimdal hx509 SoftToken (token)"); snprintf_fill((char *)pInfo->manufacturerID, sizeof(pInfo->manufacturerID), ' ', "Heimdal hx509 SoftToken (token)"); snprintf_fill((char *)pInfo->model, sizeof(pInfo->model), ' ', "Heimdal hx509 SoftToken (token)"); snprintf_fill((char *)pInfo->serialNumber, sizeof(pInfo->serialNumber), ' ', "4711"); pInfo->flags = CKF_TOKEN_INITIALIZED | CKF_USER_PIN_INITIALIZED; if (soft_token.flags.login_done == 0) pInfo->flags |= CKF_LOGIN_REQUIRED; /* CFK_RNG | CKF_RESTORE_KEY_NOT_NEEDED | */ pInfo->ulMaxSessionCount = MAX_NUM_SESSION; pInfo->ulSessionCount = soft_token.open_sessions; pInfo->ulMaxRwSessionCount = MAX_NUM_SESSION; pInfo->ulRwSessionCount = soft_token.open_sessions; pInfo->ulMaxPinLen = 1024; pInfo->ulMinPinLen = 0; pInfo->ulTotalPublicMemory = 4711; pInfo->ulFreePublicMemory = 4712; pInfo->ulTotalPrivateMemory = 4713; pInfo->ulFreePrivateMemory = 4714; pInfo->hardwareVersion.major = 2; pInfo->hardwareVersion.minor = 0; pInfo->firmwareVersion.major = 2; pInfo->firmwareVersion.minor = 0; return CKR_OK; } CK_RV C_GetMechanismList(CK_SLOT_ID slotID, CK_MECHANISM_TYPE_PTR pMechanismList, CK_ULONG_PTR pulCount) { INIT_CONTEXT(); st_logf("GetMechanismList\n"); *pulCount = 1; if (pMechanismList == NULL_PTR) return CKR_OK; pMechanismList[0] = CKM_RSA_PKCS; return CKR_OK; } CK_RV C_GetMechanismInfo(CK_SLOT_ID slotID, CK_MECHANISM_TYPE type, CK_MECHANISM_INFO_PTR pInfo) { INIT_CONTEXT(); st_logf("GetMechanismInfo: slot %d type: %d\n", (int)slotID, (int)type); memset(pInfo, 0, sizeof(*pInfo)); return CKR_OK; } CK_RV C_InitToken(CK_SLOT_ID slotID, CK_UTF8CHAR_PTR pPin, CK_ULONG ulPinLen, CK_UTF8CHAR_PTR pLabel) { INIT_CONTEXT(); st_logf("InitToken: slot %d\n", (int)slotID); return CKR_FUNCTION_NOT_SUPPORTED; } CK_RV C_OpenSession(CK_SLOT_ID slotID, CK_FLAGS flags, CK_VOID_PTR pApplication, CK_NOTIFY Notify, CK_SESSION_HANDLE_PTR phSession) { size_t i; INIT_CONTEXT(); st_logf("OpenSession: slot: %d\n", (int)slotID); if (soft_token.open_sessions == MAX_NUM_SESSION) return CKR_SESSION_COUNT; soft_token.application = pApplication; soft_token.notify = Notify; for (i = 0; i < MAX_NUM_SESSION; i++) if (soft_token.state[i].session_handle == CK_INVALID_HANDLE) break; if (i == MAX_NUM_SESSION) abort(); soft_token.open_sessions++; soft_token.state[i].session_handle = (CK_SESSION_HANDLE)(random() & 0xfffff); *phSession = soft_token.state[i].session_handle; return CKR_OK; } CK_RV C_CloseSession(CK_SESSION_HANDLE hSession) { struct session_state *state; INIT_CONTEXT(); st_logf("CloseSession\n"); if (verify_session_handle(hSession, &state) != CKR_OK) application_error("closed session not open"); else close_session(state); return CKR_OK; } CK_RV C_CloseAllSessions(CK_SLOT_ID slotID) { size_t i; INIT_CONTEXT(); st_logf("CloseAllSessions\n"); for (i = 0; i < MAX_NUM_SESSION; i++) if (soft_token.state[i].session_handle != CK_INVALID_HANDLE) close_session(&soft_token.state[i]); return CKR_OK; } CK_RV C_GetSessionInfo(CK_SESSION_HANDLE hSession, CK_SESSION_INFO_PTR pInfo) { st_logf("GetSessionInfo\n"); INIT_CONTEXT(); VERIFY_SESSION_HANDLE(hSession, NULL); memset(pInfo, 20, sizeof(*pInfo)); pInfo->slotID = 1; if (soft_token.flags.login_done) pInfo->state = CKS_RO_USER_FUNCTIONS; else pInfo->state = CKS_RO_PUBLIC_SESSION; pInfo->flags = CKF_SERIAL_SESSION; pInfo->ulDeviceError = 0; return CKR_OK; } CK_RV C_Login(CK_SESSION_HANDLE hSession, CK_USER_TYPE userType, CK_UTF8CHAR_PTR pPin, CK_ULONG ulPinLen) { char *pin = NULL; CK_RV ret; INIT_CONTEXT(); st_logf("Login\n"); VERIFY_SESSION_HANDLE(hSession, NULL); if (pPin != NULL_PTR) { int aret; aret = asprintf(&pin, "%.*s", (int)ulPinLen, pPin); if (aret != -1 && pin) st_logf("type: %d password: %s\n", (int)userType, pin); else st_logf("memory error: asprintf failed\n"); } /* * Login */ ret = read_conf_file(soft_token.config_file, userType, pin); if (ret == CKR_OK) soft_token.flags.login_done = 1; free(pin); return soft_token.flags.login_done ? CKR_OK : CKR_PIN_INCORRECT; } CK_RV C_Logout(CK_SESSION_HANDLE hSession) { st_logf("Logout\n"); INIT_CONTEXT(); VERIFY_SESSION_HANDLE(hSession, NULL); return CKR_FUNCTION_NOT_SUPPORTED; } CK_RV C_GetObjectSize(CK_SESSION_HANDLE hSession, CK_OBJECT_HANDLE hObject, CK_ULONG_PTR pulSize) { st_logf("GetObjectSize\n"); INIT_CONTEXT(); VERIFY_SESSION_HANDLE(hSession, NULL); return CKR_FUNCTION_NOT_SUPPORTED; } CK_RV C_GetAttributeValue(CK_SESSION_HANDLE hSession, CK_OBJECT_HANDLE hObject, CK_ATTRIBUTE_PTR pTemplate, CK_ULONG ulCount) { struct session_state *state; struct st_object *obj; CK_ULONG i; CK_RV ret; int j; INIT_CONTEXT(); st_logf("GetAttributeValue: %lx\n", (unsigned long)HANDLE_OBJECT_ID(hObject)); VERIFY_SESSION_HANDLE(hSession, &state); if ((ret = object_handle_to_object(hObject, &obj)) != CKR_OK) { st_logf("object not found: %lx\n", (unsigned long)HANDLE_OBJECT_ID(hObject)); return ret; } for (i = 0; i < ulCount; i++) { st_logf(" getting 0x%08lx\n", (unsigned long)pTemplate[i].type); for (j = 0; j < obj->num_attributes; j++) { if (obj->attrs[j].secret) { pTemplate[i].ulValueLen = (CK_ULONG)-1; break; } if (pTemplate[i].type == obj->attrs[j].attribute.type) { if (pTemplate[i].pValue != NULL_PTR && obj->attrs[j].secret == 0) { if (pTemplate[i].ulValueLen >= obj->attrs[j].attribute.ulValueLen) memcpy(pTemplate[i].pValue, obj->attrs[j].attribute.pValue, obj->attrs[j].attribute.ulValueLen); } pTemplate[i].ulValueLen = obj->attrs[j].attribute.ulValueLen; break; } } if (j == obj->num_attributes) { st_logf("key type: 0x%08lx not found\n", (unsigned long)pTemplate[i].type); pTemplate[i].ulValueLen = (CK_ULONG)-1; } } return CKR_OK; } CK_RV C_FindObjectsInit(CK_SESSION_HANDLE hSession, CK_ATTRIBUTE_PTR pTemplate, CK_ULONG ulCount) { struct session_state *state; st_logf("FindObjectsInit\n"); INIT_CONTEXT(); VERIFY_SESSION_HANDLE(hSession, &state); if (state->find.next_object != -1) { application_error("application didn't do C_FindObjectsFinal\n"); find_object_final(state); } if (ulCount) { CK_ULONG i; print_attributes(pTemplate, ulCount); state->find.attributes = calloc(1, ulCount * sizeof(state->find.attributes[0])); if (state->find.attributes == NULL) return CKR_DEVICE_MEMORY; for (i = 0; i < ulCount; i++) { state->find.attributes[i].pValue = malloc(pTemplate[i].ulValueLen); if (state->find.attributes[i].pValue == NULL) { find_object_final(state); return CKR_DEVICE_MEMORY; } memcpy(state->find.attributes[i].pValue, pTemplate[i].pValue, pTemplate[i].ulValueLen); state->find.attributes[i].type = pTemplate[i].type; state->find.attributes[i].ulValueLen = pTemplate[i].ulValueLen; } state->find.num_attributes = ulCount; state->find.next_object = 0; } else { st_logf("find all objects\n"); state->find.attributes = NULL; state->find.num_attributes = 0; state->find.next_object = 0; } return CKR_OK; } CK_RV C_FindObjects(CK_SESSION_HANDLE hSession, CK_OBJECT_HANDLE_PTR phObject, CK_ULONG ulMaxObjectCount, CK_ULONG_PTR pulObjectCount) { struct session_state *state; int i; INIT_CONTEXT(); st_logf("FindObjects\n"); VERIFY_SESSION_HANDLE(hSession, &state); if (state->find.next_object == -1) { application_error("application didn't do C_FindObjectsInit\n"); return CKR_ARGUMENTS_BAD; } if (ulMaxObjectCount == 0) { application_error("application asked for 0 objects\n"); return CKR_ARGUMENTS_BAD; } *pulObjectCount = 0; for (i = state->find.next_object; i < soft_token.object.num_objs; i++) { st_logf("FindObjects: %d\n", i); state->find.next_object = i + 1; if (attributes_match(soft_token.object.objs[i], state->find.attributes, state->find.num_attributes)) { *phObject++ = soft_token.object.objs[i]->object_handle; ulMaxObjectCount--; (*pulObjectCount)++; if (ulMaxObjectCount == 0) break; } } return CKR_OK; } CK_RV C_FindObjectsFinal(CK_SESSION_HANDLE hSession) { struct session_state *state; INIT_CONTEXT(); st_logf("FindObjectsFinal\n"); VERIFY_SESSION_HANDLE(hSession, &state); find_object_final(state); return CKR_OK; } static CK_RV commonInit(CK_ATTRIBUTE *attr_match, int attr_match_len, const CK_MECHANISM_TYPE *mechs, int mechs_len, const CK_MECHANISM_PTR pMechanism, CK_OBJECT_HANDLE hKey, struct st_object **o) { CK_RV ret; int i; *o = NULL; if ((ret = object_handle_to_object(hKey, o)) != CKR_OK) return ret; ret = attributes_match(*o, attr_match, attr_match_len); if (!ret) { application_error("called commonInit on key that doesn't " "support required attr"); return CKR_ARGUMENTS_BAD; } for (i = 0; i < mechs_len; i++) if (mechs[i] == pMechanism->mechanism) break; if (i == mechs_len) { application_error("called mech (%08lx) not supported\n", pMechanism->mechanism); return CKR_ARGUMENTS_BAD; } return CKR_OK; } static CK_RV dup_mechanism(CK_MECHANISM_PTR *dp, const CK_MECHANISM_PTR pMechanism) { CK_MECHANISM_PTR p; p = malloc(sizeof(*p)); if (p == NULL) return CKR_DEVICE_MEMORY; if (*dp) free(*dp); *dp = p; memcpy(p, pMechanism, sizeof(*p)); return CKR_OK; } CK_RV C_DigestInit(CK_SESSION_HANDLE hSession, CK_MECHANISM_PTR pMechanism) { st_logf("DigestInit\n"); INIT_CONTEXT(); VERIFY_SESSION_HANDLE(hSession, NULL); return CKR_FUNCTION_NOT_SUPPORTED; } CK_RV C_SignInit(CK_SESSION_HANDLE hSession, CK_MECHANISM_PTR pMechanism, CK_OBJECT_HANDLE hKey) { struct session_state *state; CK_MECHANISM_TYPE mechs[] = { CKM_RSA_PKCS }; CK_BBOOL bool_true = CK_TRUE; CK_ATTRIBUTE attr[] = { { CKA_SIGN, &bool_true, sizeof(bool_true) } }; struct st_object *o; CK_RV ret; INIT_CONTEXT(); st_logf("SignInit\n"); VERIFY_SESSION_HANDLE(hSession, &state); ret = commonInit(attr, sizeof(attr)/sizeof(attr[0]), mechs, sizeof(mechs)/sizeof(mechs[0]), pMechanism, hKey, &o); if (ret) return ret; ret = dup_mechanism(&state->sign_mechanism, pMechanism); if (ret == CKR_OK) state->sign_object = OBJECT_ID(o); return CKR_OK; } CK_RV C_Sign(CK_SESSION_HANDLE hSession, CK_BYTE_PTR pData, CK_ULONG ulDataLen, CK_BYTE_PTR pSignature, CK_ULONG_PTR pulSignatureLen) { struct session_state *state; struct st_object *o; CK_RV ret; int hret; const AlgorithmIdentifier *alg; heim_octet_string sig, data; INIT_CONTEXT(); st_logf("Sign\n"); VERIFY_SESSION_HANDLE(hSession, &state); sig.data = NULL; sig.length = 0; if (state->sign_object == -1) return CKR_ARGUMENTS_BAD; if (pulSignatureLen == NULL) { st_logf("signature len NULL\n"); ret = CKR_ARGUMENTS_BAD; goto out; } if (pData == NULL_PTR) { st_logf("data NULL\n"); ret = CKR_ARGUMENTS_BAD; goto out; } o = soft_token.object.objs[state->sign_object]; if (hx509_cert_have_private_key(o->cert) == 0) { st_logf("private key NULL\n"); return CKR_ARGUMENTS_BAD; } switch(state->sign_mechanism->mechanism) { case CKM_RSA_PKCS: alg = hx509_signature_rsa_pkcs1_x509(); break; default: ret = CKR_FUNCTION_NOT_SUPPORTED; goto out; } data.data = pData; data.length = ulDataLen; hret = _hx509_create_signature(context, _hx509_cert_private_key(o->cert), alg, &data, NULL, &sig); if (hret) { ret = CKR_DEVICE_ERROR; goto out; } *pulSignatureLen = sig.length; if (pSignature != NULL_PTR) memcpy(pSignature, sig.data, sig.length); ret = CKR_OK; out: if (sig.data) { memset(sig.data, 0, sig.length); der_free_octet_string(&sig); } return ret; } CK_RV C_SignUpdate(CK_SESSION_HANDLE hSession, CK_BYTE_PTR pPart, CK_ULONG ulPartLen) { INIT_CONTEXT(); st_logf("SignUpdate\n"); VERIFY_SESSION_HANDLE(hSession, NULL); return CKR_FUNCTION_NOT_SUPPORTED; } CK_RV C_SignFinal(CK_SESSION_HANDLE hSession, CK_BYTE_PTR pSignature, CK_ULONG_PTR pulSignatureLen) { INIT_CONTEXT(); st_logf("SignUpdate\n"); VERIFY_SESSION_HANDLE(hSession, NULL); return CKR_FUNCTION_NOT_SUPPORTED; } CK_RV C_VerifyInit(CK_SESSION_HANDLE hSession, CK_MECHANISM_PTR pMechanism, CK_OBJECT_HANDLE hKey) { struct session_state *state; CK_MECHANISM_TYPE mechs[] = { CKM_RSA_PKCS }; CK_BBOOL bool_true = CK_TRUE; CK_ATTRIBUTE attr[] = { { CKA_VERIFY, &bool_true, sizeof(bool_true) } }; struct st_object *o; CK_RV ret; INIT_CONTEXT(); st_logf("VerifyInit\n"); VERIFY_SESSION_HANDLE(hSession, &state); ret = commonInit(attr, sizeof(attr)/sizeof(attr[0]), mechs, sizeof(mechs)/sizeof(mechs[0]), pMechanism, hKey, &o); if (ret) return ret; ret = dup_mechanism(&state->verify_mechanism, pMechanism); if (ret == CKR_OK) state->verify_object = OBJECT_ID(o); return ret; } CK_RV C_Verify(CK_SESSION_HANDLE hSession, CK_BYTE_PTR pData, CK_ULONG ulDataLen, CK_BYTE_PTR pSignature, CK_ULONG ulSignatureLen) { struct session_state *state; struct st_object *o; const AlgorithmIdentifier *alg; CK_RV ret; int hret; heim_octet_string data, sig; INIT_CONTEXT(); st_logf("Verify\n"); VERIFY_SESSION_HANDLE(hSession, &state); if (state->verify_object == -1) return CKR_ARGUMENTS_BAD; o = soft_token.object.objs[state->verify_object]; switch(state->verify_mechanism->mechanism) { case CKM_RSA_PKCS: alg = hx509_signature_rsa_pkcs1_x509(); break; default: ret = CKR_FUNCTION_NOT_SUPPORTED; goto out; } sig.data = pData; sig.length = ulDataLen; data.data = pSignature; data.length = ulSignatureLen; hret = _hx509_verify_signature(context, o->cert, alg, &data, &sig); if (hret) { ret = CKR_GENERAL_ERROR; goto out; } ret = CKR_OK; out: return ret; } CK_RV C_VerifyUpdate(CK_SESSION_HANDLE hSession, CK_BYTE_PTR pPart, CK_ULONG ulPartLen) { INIT_CONTEXT(); st_logf("VerifyUpdate\n"); VERIFY_SESSION_HANDLE(hSession, NULL); return CKR_FUNCTION_NOT_SUPPORTED; } CK_RV C_VerifyFinal(CK_SESSION_HANDLE hSession, CK_BYTE_PTR pSignature, CK_ULONG ulSignatureLen) { INIT_CONTEXT(); st_logf("VerifyFinal\n"); VERIFY_SESSION_HANDLE(hSession, NULL); return CKR_FUNCTION_NOT_SUPPORTED; } CK_RV C_GenerateRandom(CK_SESSION_HANDLE hSession, CK_BYTE_PTR RandomData, CK_ULONG ulRandomLen) { INIT_CONTEXT(); st_logf("GenerateRandom\n"); VERIFY_SESSION_HANDLE(hSession, NULL); return CKR_FUNCTION_NOT_SUPPORTED; } CK_FUNCTION_LIST funcs = { { 2, 11 }, C_Initialize, C_Finalize, C_GetInfo, C_GetFunctionList, C_GetSlotList, C_GetSlotInfo, C_GetTokenInfo, C_GetMechanismList, C_GetMechanismInfo, C_InitToken, (void *)func_not_supported, /* C_InitPIN */ (void *)func_not_supported, /* C_SetPIN */ C_OpenSession, C_CloseSession, C_CloseAllSessions, C_GetSessionInfo, (void *)func_not_supported, /* C_GetOperationState */ (void *)func_not_supported, /* C_SetOperationState */ C_Login, C_Logout, (void *)func_not_supported, /* C_CreateObject */ (void *)func_not_supported, /* C_CopyObject */ (void *)func_not_supported, /* C_DestroyObject */ (void *)func_not_supported, /* C_GetObjectSize */ C_GetAttributeValue, (void *)func_not_supported, /* C_SetAttributeValue */ C_FindObjectsInit, C_FindObjects, C_FindObjectsFinal, (void *)func_not_supported, /* C_EncryptInit, */ (void *)func_not_supported, /* C_Encrypt, */ (void *)func_not_supported, /* C_EncryptUpdate, */ (void *)func_not_supported, /* C_EncryptFinal, */ (void *)func_not_supported, /* C_DecryptInit, */ (void *)func_not_supported, /* C_Decrypt, */ (void *)func_not_supported, /* C_DecryptUpdate, */ (void *)func_not_supported, /* C_DecryptFinal, */ C_DigestInit, (void *)func_not_supported, /* C_Digest */ (void *)func_not_supported, /* C_DigestUpdate */ (void *)func_not_supported, /* C_DigestKey */ (void *)func_not_supported, /* C_DigestFinal */ C_SignInit, C_Sign, C_SignUpdate, C_SignFinal, (void *)func_not_supported, /* C_SignRecoverInit */ (void *)func_not_supported, /* C_SignRecover */ C_VerifyInit, C_Verify, C_VerifyUpdate, C_VerifyFinal, (void *)func_not_supported, /* C_VerifyRecoverInit */ (void *)func_not_supported, /* C_VerifyRecover */ (void *)func_not_supported, /* C_DigestEncryptUpdate */ (void *)func_not_supported, /* C_DecryptDigestUpdate */ (void *)func_not_supported, /* C_SignEncryptUpdate */ (void *)func_not_supported, /* C_DecryptVerifyUpdate */ (void *)func_not_supported, /* C_GenerateKey */ (void *)func_not_supported, /* C_GenerateKeyPair */ (void *)func_not_supported, /* C_WrapKey */ (void *)func_not_supported, /* C_UnwrapKey */ (void *)func_not_supported, /* C_DeriveKey */ (void *)func_not_supported, /* C_SeedRandom */ C_GenerateRandom, (void *)func_not_supported, /* C_GetFunctionStatus */ (void *)func_not_supported, /* C_CancelFunction */ (void *)func_not_supported /* C_WaitForSlotEvent */ }; heimdal-7.5.0/lib/hx509/tst-crypto-select0000644000175000017500000000002612136107750016225 0ustar niknik1.2.840.113549.1.1.11 heimdal-7.5.0/lib/hx509/test_cms.in0000644000175000017500000004032313026237312015047 0ustar niknik#!/bin/sh # # Copyright (c) 2005 Kungliga Tekniska Högskolan # (Royal Institute of Technology, Stockholm, Sweden). # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # 1. Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # # 3. Neither the name of the Institute nor the names of its contributors # may be used to endorse or promote products derived from this software # without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE # ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS # OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) # HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY # OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF # SUCH DAMAGE. # # $Id$ # srcdir="@srcdir@" objdir="@objdir@" stat="--statistic-file=${objdir}/statfile" hxtool="${TESTS_ENVIRONMENT} ./hxtool ${stat}" if ${hxtool} info | grep 'rsa: hcrypto null RSA' > /dev/null ; then exit 77 fi if ${hxtool} info | grep 'rand: not available' > /dev/null ; then exit 77 fi if ${hxtool} info | grep 'ecdsa: hcrypto null' > /dev/null ; then echo "not testing ECDSA since hcrypto doesnt support ECDSA" else echo "create signed data (ec)" ${hxtool} cms-create-sd \ --certificate=FILE:$srcdir/data/secp256r2TestClient.pem \ "$srcdir/test_chain.in" \ sd.data > /dev/null || exit 1 echo "verify signed data (ec)" ${hxtool} cms-verify-sd \ --missing-revoke \ --anchors=FILE:$srcdir/data/secp256r1TestCA.cert.pem \ sd.data sd.data.out > /dev/null || exit 1 cmp "$srcdir/test_chain.in" sd.data.out || exit 1 fi echo "create signed data" ${hxtool} cms-create-sd \ --certificate=FILE:$srcdir/data/test.crt,$srcdir/data/test.key \ "$srcdir/test_chain.in" \ sd.data > /dev/null || exit 1 echo "verify signed data" ${hxtool} cms-verify-sd \ --missing-revoke \ --anchors=FILE:$srcdir/data/ca.crt \ sd.data sd.data.out > /dev/null || exit 1 cmp "$srcdir/test_chain.in" sd.data.out || exit 1 echo "create signed data (no signer)" ${hxtool} cms-create-sd \ --no-signer \ --certificate=FILE:$srcdir/data/test.crt,$srcdir/data/test.key \ "$srcdir/test_chain.in" \ sd.data > /dev/null || exit 1 echo "verify signed data (no signer)" ${hxtool} cms-verify-sd \ --missing-revoke \ --no-signer-allowed \ --anchors=FILE:$srcdir/data/ca.crt \ sd.data sd.data.out > signer.tmp || exit 1 cmp "$srcdir/test_chain.in" sd.data.out || exit 1 grep "unsigned" signer.tmp > /dev/null || exit 1 echo "verify signed data (no signer) (test failure)" ${hxtool} cms-verify-sd \ --missing-revoke \ --anchors=FILE:$srcdir/data/ca.crt \ sd.data sd.data.out 2> signer.tmp && exit 1 grep "No signers where found" signer.tmp > /dev/null || exit 1 echo "create signed data (id-by-name)" ${hxtool} cms-create-sd \ --certificate=FILE:$srcdir/data/test.crt,$srcdir/data/test.key \ --id-by-name \ "$srcdir/test_chain.in" \ sd.data > /dev/null || exit 1 echo "verify signed data" ${hxtool} cms-verify-sd \ --missing-revoke \ --anchors=FILE:$srcdir/data/ca.crt \ sd.data sd.data.out > /dev/null || exit 1 cmp "$srcdir/test_chain.in" sd.data.out || exit 1 echo "verify signed data (EE cert as anchor)" ${hxtool} cms-verify-sd \ --missing-revoke \ --anchors=FILE:$srcdir/data/test.crt \ sd.data sd.data.out > /dev/null || exit 1 cmp "$srcdir/test_chain.in" sd.data.out || exit 1 echo "create signed data (password)" ${hxtool} cms-create-sd \ --pass=PASS:foobar \ --certificate=FILE:$srcdir/data/test.crt,$srcdir/data/test-pw.key \ "$srcdir/test_chain.in" \ sd.data > /dev/null || exit 1 echo "verify signed data" ${hxtool} cms-verify-sd \ --missing-revoke \ --anchors=FILE:$srcdir/data/ca.crt \ sd.data sd.data.out > /dev/null || exit 1 cmp "$srcdir/test_chain.in" sd.data.out || exit 1 echo "create signed data (combined)" ${hxtool} cms-create-sd \ --certificate=FILE:$srcdir/data/test.combined.crt \ "$srcdir/test_chain.in" \ sd.data > /dev/null || exit 1 echo "verify signed data" ${hxtool} cms-verify-sd \ --missing-revoke \ --anchors=FILE:$srcdir/data/ca.crt \ sd.data sd.data.out > /dev/null || exit 1 cmp "$srcdir/test_chain.in" sd.data.out || exit 1 echo "create signed data (content info)" ${hxtool} cms-create-sd \ --certificate=FILE:$srcdir/data/test.crt,$srcdir/data/test.key \ --content-info \ "$srcdir/test_chain.in" \ sd.data > /dev/null || exit 1 echo "verify signed data (content info)" ${hxtool} cms-verify-sd \ --missing-revoke \ --anchors=FILE:$srcdir/data/ca.crt \ --content-info \ sd.data sd.data.out > /dev/null || exit 1 cmp "$srcdir/test_chain.in" sd.data.out || exit 1 echo "create signed data (content type)" ${hxtool} cms-create-sd \ --certificate=FILE:$srcdir/data/test.crt,$srcdir/data/test.key \ --content-type=1.1.1.1 \ "$srcdir/test_chain.in" \ sd.data > /dev/null || exit 1 echo "verify signed data (content type)" ${hxtool} cms-verify-sd \ --missing-revoke \ --anchors=FILE:$srcdir/data/ca.crt \ sd.data sd.data.out > /dev/null || exit 1 cmp "$srcdir/test_chain.in" sd.data.out || exit 1 echo "create signed data (pem)" ${hxtool} cms-create-sd \ --certificate=FILE:$srcdir/data/test.crt,$srcdir/data/test.key \ --pem \ "$srcdir/test_chain.in" \ sd.data > /dev/null || exit 1 echo "verify signed data (pem)" ${hxtool} cms-verify-sd \ --missing-revoke \ --anchors=FILE:$srcdir/data/ca.crt \ --pem \ sd.data sd.data.out > /dev/null cmp "$srcdir/test_chain.in" sd.data.out || exit 1 echo "create signed data (pem, detached)" ${hxtool} cms-create-sd \ --certificate=FILE:$srcdir/data/test.crt,$srcdir/data/test.key \ --detached-signature \ --pem \ "$srcdir/test_chain.in" \ sd.data > /dev/null || exit 1 echo "verify signed data (pem, detached)" ${hxtool} cms-verify-sd \ --missing-revoke \ --anchors=FILE:$srcdir/data/ca.crt \ --pem \ --signed-content="$srcdir/test_chain.in" \ sd.data sd.data.out > /dev/null cmp "$srcdir/test_chain.in" sd.data.out || exit 1 echo "create signed data (p12)" ${hxtool} cms-create-sd \ --pass=PASS:foobar \ --certificate=PKCS12:$srcdir/data/test.p12 \ --signer=friendlyname-test \ "$srcdir/test_chain.in" \ sd.data > /dev/null || exit 1 echo "verify signed data" ${hxtool} cms-verify-sd \ --missing-revoke \ --anchors=FILE:$srcdir/data/ca.crt \ --content-info \ "$srcdir/data/test-signed-data" sd.data.out > /dev/null || exit 1 cmp "$srcdir/data/static-file" sd.data.out || exit 1 echo "verify signed data (no attr)" ${hxtool} cms-verify-sd \ --missing-revoke \ --anchors=FILE:$srcdir/data/ca.crt \ --content-info \ "$srcdir/data/test-signed-data-noattr" sd.data.out > /dev/null || exit 1 cmp "$srcdir/data/static-file" sd.data.out || exit 1 echo "verify failure signed data (no attr, no certs)" ${hxtool} cms-verify-sd \ --missing-revoke \ --anchors=FILE:$srcdir/data/ca.crt \ --content-info \ "$srcdir/data/test-signed-data-noattr-nocerts" \ sd.data.out > /dev/null 2>/dev/null && exit 1 echo "verify signed data (no attr, no certs)" ${hxtool} cms-verify-sd \ --missing-revoke \ --anchors=FILE:$srcdir/data/ca.crt \ --certificate=FILE:$srcdir/data/test.crt \ --content-info \ "$srcdir/data/test-signed-data-noattr-nocerts" \ sd.data.out > /dev/null || exit 1 cmp "$srcdir/data/static-file" sd.data.out || exit 1 echo "verify signed data - sha1" ${hxtool} cms-verify-sd \ --missing-revoke \ --anchors=FILE:$srcdir/data/ca.crt \ --content-info \ "$srcdir/data/test-signed-sha-1" sd.data.out > /dev/null || exit 1 cmp "$srcdir/data/static-file" sd.data.out || exit 1 echo "verify signed data - sha256" ${hxtool} cms-verify-sd \ --missing-revoke \ --anchors=FILE:$srcdir/data/ca.crt \ --content-info \ "$srcdir/data/test-signed-sha-256" sd.data.out > /dev/null || exit 1 cmp "$srcdir/data/static-file" sd.data.out || exit 1 #echo "verify signed data - sha512" #${hxtool} cms-verify-sd \ # --missing-revoke \ # --anchors=FILE:$srcdir/data/ca.crt \ # --content-info \ # "$srcdir/data/test-signed-sha-512" sd.data.out > /dev/null || exit 1 #cmp "$srcdir/data/static-file" sd.data.out || exit 1 echo "create signed data (subcert, no certs)" ${hxtool} cms-create-sd \ --certificate=FILE:$srcdir/data/sub-cert.crt,$srcdir/data/sub-cert.key \ "$srcdir/test_chain.in" \ sd.data > /dev/null || exit 1 echo "verify failure signed data" ${hxtool} cms-verify-sd \ --missing-revoke \ --anchors=FILE:$srcdir/data/ca.crt \ sd.data sd.data.out > /dev/null 2> /dev/null && exit 1 echo "verify success signed data" ${hxtool} cms-verify-sd \ --missing-revoke \ --certificate=FILE:$srcdir/data/sub-ca.crt \ --anchors=FILE:$srcdir/data/ca.crt \ sd.data sd.data.out > /dev/null || exit 1 cmp "$srcdir/test_chain.in" sd.data.out || exit 1 echo "create signed data (subcert, certs)" ${hxtool} cms-create-sd \ --certificate=FILE:$srcdir/data/sub-cert.crt,$srcdir/data/sub-cert.key \ --pool=FILE:$srcdir/data/sub-ca.crt \ --anchors=FILE:$srcdir/data/ca.crt \ "$srcdir/test_chain.in" \ sd.data > /dev/null || exit 1 echo "verify success signed data" ${hxtool} cms-verify-sd \ --missing-revoke \ --anchors=FILE:$srcdir/data/ca.crt \ sd.data sd.data.out > /dev/null || exit 1 cmp "$srcdir/test_chain.in" sd.data.out || exit 1 echo "create signed data (subcert, certs, no-root)" ${hxtool} cms-create-sd \ --certificate=FILE:$srcdir/data/sub-cert.crt,$srcdir/data/sub-cert.key \ --pool=FILE:$srcdir/data/sub-ca.crt \ "$srcdir/test_chain.in" \ sd.data > /dev/null || exit 1 echo "verify success signed data" ${hxtool} cms-verify-sd \ --missing-revoke \ --anchors=FILE:$srcdir/data/ca.crt \ sd.data sd.data.out > /dev/null || exit 1 cmp "$srcdir/test_chain.in" sd.data.out || exit 1 echo "create signed data (subcert, no-subca, no-root)" ${hxtool} cms-create-sd \ --certificate=FILE:$srcdir/data/sub-cert.crt,$srcdir/data/sub-cert.key \ "$srcdir/test_chain.in" \ sd.data > /dev/null || exit 1 echo "verify failure signed data" ${hxtool} cms-verify-sd \ --missing-revoke \ --anchors=FILE:$srcdir/data/ca.crt \ sd.data sd.data.out > /dev/null 2>/dev/null && exit 1 echo "create signed data (sd cert)" ${hxtool} cms-create-sd \ --certificate=FILE:$srcdir/data/test-ds-only.crt,$srcdir/data/test-ds-only.key \ "$srcdir/test_chain.in" \ sd.data > /dev/null || exit 1 echo "create signed data (ke cert)" ${hxtool} cms-create-sd \ --certificate=FILE:$srcdir/data/test-ke-only.crt,$srcdir/data/test-ke-only.key \ "$srcdir/test_chain.in" \ sd.data > /dev/null 2>/dev/null && exit 1 echo "create signed data (sd + ke certs)" ${hxtool} cms-create-sd \ --certificate=FILE:$srcdir/data/test-ke-only.crt,$srcdir/data/test-ke-only.key \ --certificate=FILE:$srcdir/data/test-ds-only.crt,$srcdir/data/test-ds-only.key \ "$srcdir/test_chain.in" \ sd.data > /dev/null || exit 1 echo "create signed data (ke + sd certs)" ${hxtool} cms-create-sd \ --certificate=FILE:$srcdir/data/test-ds-only.crt,$srcdir/data/test-ds-only.key \ --certificate=FILE:$srcdir/data/test-ke-only.crt,$srcdir/data/test-ke-only.key \ "$srcdir/test_chain.in" \ sd.data > /dev/null || exit 1 echo "create signed data (detached)" ${hxtool} cms-create-sd \ --certificate=FILE:$srcdir/data/test.crt,$srcdir/data/test.key \ --detached-signature \ "$srcdir/test_chain.in" \ sd.data > /dev/null || exit 1 echo "verify signed data (detached)" ${hxtool} cms-verify-sd \ --missing-revoke \ --signed-content="$srcdir/test_chain.in" \ --anchors=FILE:$srcdir/data/ca.crt \ sd.data sd.data.out > /dev/null || exit 1 cmp "$srcdir/test_chain.in" sd.data.out || exit 1 echo "verify failure signed data (detached)" ${hxtool} cms-verify-sd \ --missing-revoke \ --anchors=FILE:$srcdir/data/ca.crt \ sd.data sd.data.out > /dev/null 2>/dev/null && exit 1 echo "create signed data (rsa)" ${hxtool} cms-create-sd \ --peer-alg=1.2.840.113549.1.1.1 \ --certificate=FILE:$srcdir/data/test.crt,$srcdir/data/test.key \ "$srcdir/test_chain.in" \ sd.data > /dev/null || exit 1 echo "verify signed data (rsa)" ${hxtool} cms-verify-sd \ --missing-revoke \ --anchors=FILE:$srcdir/data/ca.crt \ sd.data sd.data.out > /dev/null 2>/dev/null || exit 1 cmp "$srcdir/test_chain.in" sd.data.out || exit 1 echo "create signed data (pem, detached)" cp "$srcdir/test_chain.in" sd ${hxtool} cms-sign \ --certificate=FILE:$srcdir/data/test.crt,$srcdir/data/test.key \ --detached-signature \ --pem \ sd > /dev/null || exit 1 echo "verify signed data (pem, detached)" ${hxtool} cms-verify-sd \ --missing-revoke \ --anchors=FILE:$srcdir/data/ca.crt \ --pem \ sd.pem > /dev/null echo "create signed data (no certs, detached sig)" cp "$srcdir/test_chain.in" sd ${hxtool} cms-sign \ --certificate=FILE:$srcdir/data/test.crt,$srcdir/data/test.key \ --detached-signature \ --no-embedded-certs \ "$srcdir/data/static-file" \ sd > /dev/null || exit 1 echo "create signed data (leif only, detached sig)" cp "$srcdir/test_chain.in" sd ${hxtool} cms-sign \ --certificate=FILE:$srcdir/data/test.crt,$srcdir/data/test.key \ --detached-signature \ --embed-leaf-only \ "$srcdir/data/static-file" \ sd > /dev/null || exit 1 echo "create signed data (no certs, detached sig, 2 signers)" cp "$srcdir/test_chain.in" sd ${hxtool} cms-sign \ --certificate=FILE:$srcdir/data/test.crt,$srcdir/data/test.key \ --certificate=FILE:$srcdir/data/sub-cert.crt,$srcdir/data/sub-cert.key \ --detached-signature \ --no-embedded-certs \ "$srcdir/data/static-file" \ sd > /dev/null || exit 1 echo "create signed data (no certs, detached sig, 3 signers)" cp "$srcdir/test_chain.in" sd ${hxtool} cms-sign \ --certificate=FILE:$srcdir/data/test.crt,$srcdir/data/test.key \ --certificate=FILE:$srcdir/data/sub-cert.crt,$srcdir/data/sub-cert.key \ --certificate=FILE:$srcdir/data/test-ds-only.crt,$srcdir/data/test-ds-only.key \ --detached-signature \ --no-embedded-certs \ "$srcdir/data/static-file" \ sd > /dev/null || exit 1 echo "envelope data (content-type)" ${hxtool} cms-envelope \ --certificate=FILE:$srcdir/data/test.crt \ --content-type=1.1.1.1 \ "$srcdir/data/static-file" \ ev.data > /dev/null || exit 1 echo "unenvelope data (content-type)" ${hxtool} cms-unenvelope \ --certificate=FILE:$srcdir/data/test.crt,$srcdir/data/test.key \ ev.data ev.data.out \ FILE:$srcdir/data/test.crt,$srcdir/data/test.key > /dev/null || exit 1 cmp "$srcdir/data/static-file" ev.data.out || exit 1 echo "envelope data (content-info)" ${hxtool} cms-envelope \ --certificate=FILE:$srcdir/data/test.crt \ --content-info \ "$srcdir/data/static-file" \ ev.data > /dev/null || exit 1 echo "unenvelope data (content-info)" ${hxtool} cms-unenvelope \ --certificate=FILE:$srcdir/data/test.crt,$srcdir/data/test.key \ --content-info \ ev.data ev.data.out \ FILE:$srcdir/data/test.crt,$srcdir/data/test.key > /dev/null || exit 1 cmp "$srcdir/data/static-file" ev.data.out || exit 1 for a in des-ede3 aes-128 aes-256; do rm -f ev.data ev.data.out echo "envelope data ($a)" ${hxtool} cms-envelope \ --encryption-type="$a-cbc" \ --certificate=FILE:$srcdir/data/test.crt \ "$srcdir/data/static-file" \ ev.data || exit 1 echo "unenvelope data ($a)" ${hxtool} cms-unenvelope \ --certificate=FILE:$srcdir/data/test.crt,$srcdir/data/test.key \ ev.data ev.data.out > /dev/null || exit 1 cmp "$srcdir/data/static-file" ev.data.out || exit 1 done for a in rc2-40 rc2-64 rc2-128 des-ede3 aes-128 aes-256; do echo "static unenvelope data ($a)" rm -f ev.data.out ${hxtool} cms-unenvelope \ --certificate=FILE:$srcdir/data/test.crt,$srcdir/data/test.key \ --content-info \ --allow-weak \ "$srcdir/data/test-enveloped-$a" ev.data.out > /dev/null || exit 1 cmp "$srcdir/data/static-file" ev.data.out || exit 1 done exit 0 heimdal-7.5.0/lib/hx509/Makefile.am0000644000175000017500000002711113026237312014732 0ustar niknikinclude $(top_srcdir)/Makefile.am.common AM_CPPFLAGS += $(INCLUDE_openssl_crypto) lib_LTLIBRARIES = libhx509.la libhx509_la_LDFLAGS = -version-info 5:0:0 BUILT_SOURCES = \ sel-gram.h \ $(gen_files_ocsp:.x=.c) \ $(gen_files_pkcs10:.x=.c) \ hx509_err.c \ hx509_err.h gen_files_ocsp = \ asn1_OCSPBasicOCSPResponse.x \ asn1_OCSPCertID.x \ asn1_OCSPCertStatus.x \ asn1_OCSPInnerRequest.x \ asn1_OCSPKeyHash.x \ asn1_OCSPRequest.x \ asn1_OCSPResponderID.x \ asn1_OCSPResponse.x \ asn1_OCSPResponseBytes.x \ asn1_OCSPResponseData.x \ asn1_OCSPResponseStatus.x \ asn1_OCSPSignature.x \ asn1_OCSPSingleResponse.x \ asn1_OCSPTBSRequest.x \ asn1_OCSPVersion.x \ asn1_id_pkix_ocsp.x \ asn1_id_pkix_ocsp_basic.x \ asn1_id_pkix_ocsp_nonce.x gen_files_pkcs10 = \ asn1_CertificationRequestInfo.x \ asn1_CertificationRequest.x gen_files_crmf = \ asn1_CRMFRDNSequence.x \ asn1_CertReqMessages.x \ asn1_CertReqMsg.x \ asn1_CertRequest.x \ asn1_CertTemplate.x \ asn1_Controls.x \ asn1_PBMParameter.x \ asn1_PKMACValue.x \ asn1_POPOPrivKey.x \ asn1_POPOSigningKey.x \ asn1_POPOSigningKeyInput.x \ asn1_ProofOfPossession.x \ asn1_SubsequentMessage.x AM_YFLAGS = -d dist_libhx509_la_SOURCES = \ ca.c \ cert.c \ char_map.h \ cms.c \ collector.c \ crypto.c \ crypto-ec.c \ doxygen.c \ error.c \ env.c \ file.c \ hx509.h \ hx_locl.h \ sel.c \ sel.h \ sel-gram.y \ sel-lex.l \ keyset.c \ ks_dir.c \ ks_file.c \ ks_mem.c \ ks_null.c \ ks_p11.c \ ks_p12.c \ ks_keychain.c \ lock.c \ name.c \ peer.c \ print.c \ softp11.c \ ref/pkcs11.h \ req.c \ revoke.c sel-lex.c: sel-gram.h libhx509_la_DEPENDENCIES = version-script.map libhx509_la_LIBADD = \ $(LIB_com_err) \ $(LIB_hcrypto) \ $(LIB_openssl_crypto) \ $(top_builddir)/lib/asn1/libasn1.la \ $(top_builddir)/lib/wind/libwind.la \ $(top_builddir)/lib/base/libheimbase.la \ $(LIBADD_roken) \ $(LIB_dlopen) if FRAMEWORK_SECURITY libhx509_la_LDFLAGS += -framework Security -framework CoreFoundation endif if versionscript libhx509_la_LDFLAGS += $(LDFLAGS_VERSION_SCRIPT)$(srcdir)/version-script.map endif $(libhx509_la_OBJECTS): $(srcdir)/version-script.map $(nodist_include_HEADERS) $(priv_headers) nodist_libhx509_la_SOURCES = $(BUILT_SOURCES) $(gen_files_ocsp) ocsp_asn1.hx ocsp_asn1-priv.hx: ocsp_asn1_files $(gen_files_pkcs10) pkcs10_asn1.hx pkcs10_asn1-priv.hx: pkcs10_asn1_files $(gen_files_crmf) crmf_asn1.hx crmf_asn1-priv.hx: crmf_asn1_files dist_include_HEADERS = hx509.h $(srcdir)/hx509-protos.h noinst_HEADERS = $(srcdir)/hx509-private.h nodist_include_HEADERS = hx509_err.h nodist_include_HEADERS += ocsp_asn1.h nodist_include_HEADERS += pkcs10_asn1.h nodist_include_HEADERS += crmf_asn1.h priv_headers = ocsp_asn1-priv.h priv_headers += pkcs10_asn1-priv.h priv_headers += crmf_asn1-priv.h ocsp_asn1_files: $(ASN1_COMPILE_DEP) $(srcdir)/ocsp.asn1 $(srcdir)/ocsp.opt $(heim_verbose)$(ASN1_COMPILE) --option-file=$(srcdir)/ocsp.opt $(srcdir)/ocsp.asn1 ocsp_asn1 || (rm -f ocsp_asn1_files ; exit 1) pkcs10_asn1_files: $(ASN1_COMPILE_DEP) $(srcdir)/pkcs10.asn1 $(srcdir)/pkcs10.opt $(heim_verbose)$(ASN1_COMPILE) --option-file=$(srcdir)/pkcs10.opt $(srcdir)/pkcs10.asn1 pkcs10_asn1 || (rm -f pkcs10_asn1_files ; exit 1) crmf_asn1_files: $(ASN1_COMPILE_DEP) $(srcdir)/crmf.asn1 $(heim_verbose)$(ASN1_COMPILE) $(srcdir)/crmf.asn1 crmf_asn1 || (rm -f crmf_asn1_files ; exit 1) ALL_OBJECTS = $(libhx509_la_OBJECTS) ALL_OBJECTS += $(hxtool_OBJECTS) HX509_PROTOS = $(srcdir)/hx509-protos.h $(srcdir)/hx509-private.h $(ALL_OBJECTS): $(HX509_PROTOS) $(libhx509_la_OBJECTS): $(srcdir)/hx_locl.h $(libhx509_la_OBJECTS): ocsp_asn1.h pkcs10_asn1.h $(srcdir)/hx509-protos.h: $(dist_libhx509_la_SOURCES) $(heim_verbose)cd $(srcdir) && perl ../../cf/make-proto.pl -R '^(_|^C)' -E HX509_LIB -q -P comment -o hx509-protos.h $(dist_libhx509_la_SOURCES) || rm -f hx509-protos.h $(srcdir)/hx509-private.h: $(dist_libhx509_la_SOURCES) $(heim_verbose)cd $(srcdir) && perl ../../cf/make-proto.pl -q -P comment -p hx509-private.h $(dist_libhx509_la_SOURCES) || rm -f hx509-private.h bin_PROGRAMS = hxtool hxtool-commands.c hxtool-commands.h: hxtool-commands.in $(SLC) $(heim_verbose)$(SLC) $(srcdir)/hxtool-commands.in dist_hxtool_SOURCES = hxtool.c nodist_hxtool_SOURCES = hxtool-commands.c hxtool-commands.h $(hxtool_OBJECTS): hxtool-commands.h hx509_err.h hxtool_LDADD = \ libhx509.la \ $(top_builddir)/lib/asn1/libasn1.la \ $(LIB_hcrypto) \ $(LIB_roken) \ $(top_builddir)/lib/sl/libsl.la CLEANFILES = $(BUILT_SOURCES) sel-gram.c sel-lex.c \ $(gen_files_ocsp) ocsp_asn1_files ocsp_asn1{,-priv}.h* \ ocsp_asn1-template.[chx]* \ $(gen_files_pkcs10) pkcs10_asn1_files pkcs10_asn1{,-priv}.h* \ pkcs10_asn1-template.[chx]* \ $(gen_files_crmf) crmf_asn1_files crmf_asn1{,-priv}.h* \ crmf_asn1-template.[chx]* \ $(TESTS) \ hxtool-commands.c hxtool-commands.h *.tmp \ request.out \ out.pem out2.pem \ sd sd.pem \ sd.data sd.data.out \ ev.data ev.data.out \ cert-null.pem cert-sub-ca2.pem \ cert-ee.pem cert-ca.pem \ cert-sub-ee.pem cert-sub-ca.pem \ cert-proxy.der cert-ca.der cert-ee.der pkcs10-request.der \ wca.pem wuser.pem wdc.pem wcrl.crl \ random-data statfile crl.crl \ test p11dbg.log pkcs11.cfg \ test-rc-file.rc clean-local: @echo "cleaning PKITS" ; rm -rf PKITS_data # # regression tests # check_SCRIPTS = $(SCRIPT_TESTS) check_PROGRAMS = $(PROGRAM_TESTS) test_soft_pkcs11 LDADD = libhx509.la test_soft_pkcs11_LDADD = libhx509.la $(top_builddir)/lib/asn1/libasn1.la test_name_LDADD = libhx509.la $(LIB_roken) $(top_builddir)/lib/asn1/libasn1.la test_expr_LDADD = libhx509.la $(LIB_roken) $(top_builddir)/lib/asn1/libasn1.la TESTS = $(SCRIPT_TESTS) $(PROGRAM_TESTS) PROGRAM_TESTS = \ test_name \ test_expr SCRIPT_TESTS = \ test_ca \ test_cert \ test_chain \ test_cms \ test_crypto \ test_nist \ test_nist2 \ test_pkcs11 \ test_java_pkcs11 \ test_nist_cert \ test_nist_pkcs12 \ test_req \ test_windows \ test_query do_subst = $(heim_verbose)sed -e 's,[@]srcdir[@],$(srcdir),g' \ -e 's,[@]objdir[@],$(top_builddir)/lib/hx509,g' \ -e 's,[@]egrep[@],$(EGREP),g' test_ca: test_ca.in Makefile $(do_subst) < $(srcdir)/test_ca.in > test_ca.tmp $(heim_verbose)chmod +x test_ca.tmp mv test_ca.tmp test_ca test_cert: test_cert.in Makefile $(do_subst) < $(srcdir)/test_cert.in > test_cert.tmp $(heim_verbose)chmod +x test_cert.tmp mv test_cert.tmp test_cert test_chain: test_chain.in Makefile $(do_subst) < $(srcdir)/test_chain.in > test_chain.tmp $(heim_verbose)chmod +x test_chain.tmp mv test_chain.tmp test_chain test_cms: test_cms.in Makefile $(do_subst) < $(srcdir)/test_cms.in > test_cms.tmp $(heim_verbose)chmod +x test_cms.tmp mv test_cms.tmp test_cms test_crypto: test_crypto.in Makefile $(do_subst) < $(srcdir)/test_crypto.in > test_crypto.tmp $(heim_verbose)chmod +x test_crypto.tmp mv test_crypto.tmp test_crypto test_nist: test_nist.in Makefile $(do_subst) < $(srcdir)/test_nist.in > test_nist.tmp $(heim_verbose)chmod +x test_nist.tmp mv test_nist.tmp test_nist test_nist2: test_nist2.in Makefile $(do_subst) < $(srcdir)/test_nist2.in > test_nist2.tmp $(heim_verbose)chmod +x test_nist2.tmp mv test_nist2.tmp test_nist2 test_pkcs11: test_pkcs11.in Makefile $(do_subst) < $(srcdir)/test_pkcs11.in > test_pkcs11.tmp $(heim_verbose)chmod +x test_pkcs11.tmp mv test_pkcs11.tmp test_pkcs11 test_java_pkcs11: test_java_pkcs11.in Makefile $(do_subst) < $(srcdir)/test_java_pkcs11.in > test_java_pkcs11.tmp $(heim_verbose)chmod +x test_java_pkcs11.tmp mv test_java_pkcs11.tmp test_java_pkcs11 test_nist_cert: test_nist_cert.in Makefile $(do_subst) < $(srcdir)/test_nist_cert.in > test_nist_cert.tmp $(heim_verbose)chmod +x test_nist_cert.tmp mv test_nist_cert.tmp test_nist_cert test_nist_pkcs12: test_nist_pkcs12.in Makefile $(do_subst) < $(srcdir)/test_nist_pkcs12.in > test_nist_pkcs12.tmp $(heim_verbose)chmod +x test_nist_pkcs12.tmp mv test_nist_pkcs12.tmp test_nist_pkcs12 test_req: test_req.in Makefile $(do_subst) < $(srcdir)/test_req.in > test_req.tmp $(heim_verbose)chmod +x test_req.tmp mv test_req.tmp test_req test_windows: test_windows.in Makefile $(do_subst) < $(srcdir)/test_windows.in > test_windows.tmp $(heim_verbose)chmod +x test_windows.tmp mv test_windows.tmp test_windows test_query: test_query.in Makefile $(do_subst) < $(srcdir)/test_query.in > test_query.tmp $(heim_verbose)chmod +x test_query.tmp mv test_query.tmp test_query EXTRA_DIST = \ NTMakefile \ hxtool-version.rc \ libhx509-exports.def \ version-script.map \ crmf.asn1 \ hx509_err.et \ hxtool-commands.in \ quote.py \ ocsp.asn1 \ ocsp.opt \ pkcs10.asn1 \ pkcs10.opt \ test_ca.in \ test_chain.in \ test_cert.in \ test_cms.in \ test_crypto.in \ test_nist.in \ test_nist2.in \ test_nist_cert.in \ test_nist_pkcs12.in \ test_pkcs11.in \ test_java_pkcs11.in \ test_query.in \ test_req.in \ test_windows.in \ tst-crypto-available1 \ tst-crypto-available2 \ tst-crypto-available3 \ tst-crypto-select \ tst-crypto-select1 \ tst-crypto-select2 \ tst-crypto-select3 \ tst-crypto-select4 \ tst-crypto-select5 \ tst-crypto-select6 \ tst-crypto-select7 \ data/PKITS_data.zip \ data/eccurve.pem \ data/https.crt \ data/https.key \ data/mkcert.sh \ data/nist-result2 \ data/n0ll.pem \ data/secp256r1TestCA.cert.pem \ data/secp256r1TestCA.key.pem \ data/secp256r1TestCA.pem \ data/secp256r2TestClient.cert.pem \ data/secp256r2TestClient.key.pem \ data/secp256r2TestClient.pem \ data/secp256r2TestServer.cert.pem \ data/secp256r2TestServer.key.pem \ data/secp256r2TestServer.pem \ data/bleichenbacher-bad.pem \ data/bleichenbacher-good.pem \ data/bleichenbacher-sf-pad-correct.pem \ data/ca.crt \ data/ca.key \ data/crl1.crl \ data/crl1.der \ data/gen-req.sh \ data/j.pem \ data/kdc.crt \ data/kdc.key \ data/key.der \ data/key2.der \ data/nist-data \ data/nist-data2 \ data/no-proxy-test.crt \ data/no-proxy-test.key \ data/ocsp-req1.der \ data/ocsp-req2.der \ data/ocsp-resp1-2.der \ data/ocsp-resp1-3.der \ data/ocsp-resp1-ca.der \ data/ocsp-resp1-keyhash.der \ data/ocsp-resp1-ocsp-no-cert.der \ data/ocsp-resp1-ocsp.der \ data/ocsp-resp1.der \ data/ocsp-resp2.der \ data/ocsp-responder.crt \ data/ocsp-responder.key \ data/openssl.cnf \ data/pkinit-proxy-chain.crt \ data/pkinit-proxy.crt \ data/pkinit-proxy.key \ data/pkinit-pw.key \ data/pkinit.crt \ data/pkinit.key \ data/pkinit-ec.crt \ data/pkinit-ec.key \ data/proxy-level-test.crt \ data/proxy-level-test.key \ data/proxy-test.crt \ data/proxy-test.key \ data/proxy10-child-test.crt \ data/proxy10-child-test.key \ data/proxy10-child-child-test.crt \ data/proxy10-child-child-test.key \ data/proxy10-test.crt \ data/proxy10-test.key \ data/revoke.crt \ data/revoke.key \ data/sf-class2-root.pem \ data/static-file \ data/sub-ca.crt \ data/sub-ca.key \ data/sub-cert.crt \ data/sub-cert.key \ data/sub-cert.p12 \ data/test-ds-only.crt \ data/test-ds-only.key \ data/test-enveloped-aes-128 \ data/test-enveloped-aes-256 \ data/test-enveloped-des \ data/test-enveloped-des-ede3 \ data/test-enveloped-rc2-128 \ data/test-enveloped-rc2-40 \ data/test-enveloped-rc2-64 \ data/test-ke-only.crt \ data/test-ke-only.key \ data/test-nopw.p12 \ data/test-pw.key \ data/test-signed-data \ data/test-signed-data-noattr \ data/test-signed-data-noattr-nocerts \ data/test-signed-sha-1 \ data/test-signed-sha-256 \ data/test-signed-sha-512 \ data/test.combined.crt \ data/test.crt \ data/test.key \ data/test.p12 \ data/win-u16-in-printablestring.der \ data/yutaka-pad-broken-ca.pem \ data/yutaka-pad-broken-cert.pem \ data/yutaka-pad-ok-ca.pem \ data/yutaka-pad-ok-cert.pem \ data/yutaka-pad.key heimdal-7.5.0/lib/hx509/hx509-private.h0000644000175000017500000002322513212445575015407 0ustar niknik/* This is a generated file */ #ifndef __hx509_private_h__ #define __hx509_private_h__ #include #if !defined(__GNUC__) && !defined(__attribute__) #define __attribute__(x) #endif int _hx509_AlgorithmIdentifier_cmp ( const AlgorithmIdentifier */*p*/, const AlgorithmIdentifier */*q*/); int _hx509_Certificate_cmp ( const Certificate */*p*/, const Certificate */*q*/); int _hx509_Name_to_string ( const Name */*n*/, char **/*str*/); time_t _hx509_Time2time_t (const Time */*t*/); void _hx509_abort ( const char */*fmt*/, ...) __attribute__ ((__noreturn__, __format__ (__printf__, 1, 2))); int _hx509_calculate_path ( hx509_context /*context*/, int /*flags*/, time_t /*time_now*/, hx509_certs /*anchors*/, unsigned int /*max_depth*/, hx509_cert /*cert*/, hx509_certs /*pool*/, hx509_path */*path*/); int _hx509_cert_assign_key ( hx509_cert /*cert*/, hx509_private_key /*private_key*/); int _hx509_cert_get_eku ( hx509_context /*context*/, hx509_cert /*cert*/, ExtKeyUsage */*e*/); int _hx509_cert_get_keyusage ( hx509_context /*context*/, hx509_cert /*c*/, KeyUsage */*ku*/); int _hx509_cert_get_version (const Certificate */*t*/); int _hx509_cert_is_parent_cmp ( const Certificate */*subject*/, const Certificate */*issuer*/, int /*allow_self_signed*/); int _hx509_cert_private_decrypt ( hx509_context /*context*/, const heim_octet_string */*ciphertext*/, const heim_oid */*encryption_oid*/, hx509_cert /*p*/, heim_octet_string */*cleartext*/); hx509_private_key _hx509_cert_private_key (hx509_cert /*p*/); int _hx509_cert_private_key_exportable (hx509_cert /*p*/); void _hx509_cert_set_release ( hx509_cert /*cert*/, _hx509_cert_release_func /*release*/, void */*ctx*/); int _hx509_cert_to_env ( hx509_context /*context*/, hx509_cert /*cert*/, hx509_env */*env*/); int _hx509_certs_keys_add ( hx509_context /*context*/, hx509_certs /*certs*/, hx509_private_key /*key*/); void _hx509_certs_keys_free ( hx509_context /*context*/, hx509_private_key */*keys*/); int _hx509_certs_keys_get ( hx509_context /*context*/, hx509_certs /*certs*/, hx509_private_key **/*keys*/); int _hx509_check_key_usage ( hx509_context /*context*/, hx509_cert /*cert*/, unsigned /*flags*/, int /*req_present*/); int _hx509_collector_alloc ( hx509_context /*context*/, hx509_lock /*lock*/, struct hx509_collector **/*collector*/); int _hx509_collector_certs_add ( hx509_context /*context*/, struct hx509_collector */*c*/, hx509_cert /*cert*/); int _hx509_collector_collect_certs ( hx509_context /*context*/, struct hx509_collector */*c*/, hx509_certs */*ret_certs*/); int _hx509_collector_collect_private_keys ( hx509_context /*context*/, struct hx509_collector */*c*/, hx509_private_key **/*keys*/); void _hx509_collector_free (struct hx509_collector */*c*/); hx509_lock _hx509_collector_get_lock (struct hx509_collector */*c*/); int _hx509_collector_private_key_add ( hx509_context /*context*/, struct hx509_collector */*c*/, const AlgorithmIdentifier */*alg*/, hx509_private_key /*private_key*/, const heim_octet_string */*key_data*/, const heim_octet_string */*localKeyId*/); int _hx509_create_signature ( hx509_context /*context*/, const hx509_private_key /*signer*/, const AlgorithmIdentifier */*alg*/, const heim_octet_string */*data*/, AlgorithmIdentifier */*signatureAlgorithm*/, heim_octet_string */*sig*/); int _hx509_create_signature_bitstring ( hx509_context /*context*/, const hx509_private_key /*signer*/, const AlgorithmIdentifier */*alg*/, const heim_octet_string */*data*/, AlgorithmIdentifier */*signatureAlgorithm*/, heim_bit_string */*sig*/); int _hx509_expr_eval ( hx509_context /*context*/, hx509_env /*env*/, struct hx_expr */*expr*/); void _hx509_expr_free (struct hx_expr */*expr*/); struct hx_expr * _hx509_expr_parse (const char */*buf*/); int _hx509_find_extension_subject_key_id ( const Certificate */*issuer*/, SubjectKeyIdentifier */*si*/); const struct signature_alg * _hx509_find_sig_alg (const heim_oid */*oid*/); int _hx509_generate_private_key ( hx509_context /*context*/, struct hx509_generate_private_context */*ctx*/, hx509_private_key */*private_key*/); int _hx509_generate_private_key_bits ( hx509_context /*context*/, struct hx509_generate_private_context */*ctx*/, unsigned long /*bits*/); void _hx509_generate_private_key_free (struct hx509_generate_private_context **/*ctx*/); int _hx509_generate_private_key_init ( hx509_context /*context*/, const heim_oid */*oid*/, struct hx509_generate_private_context **/*ctx*/); int _hx509_generate_private_key_is_ca ( hx509_context /*context*/, struct hx509_generate_private_context */*ctx*/); Certificate * _hx509_get_cert (hx509_cert /*cert*/); void _hx509_ks_dir_register (hx509_context /*context*/); void _hx509_ks_file_register (hx509_context /*context*/); void _hx509_ks_keychain_register (hx509_context /*context*/); void _hx509_ks_mem_register (hx509_context /*context*/); void _hx509_ks_null_register (hx509_context /*context*/); void _hx509_ks_pkcs11_register (hx509_context /*context*/); void _hx509_ks_pkcs12_register (hx509_context /*context*/); void _hx509_ks_register ( hx509_context /*context*/, struct hx509_keyset_ops */*ops*/); int _hx509_lock_find_cert ( hx509_lock /*lock*/, const hx509_query */*q*/, hx509_cert */*c*/); const struct _hx509_password * _hx509_lock_get_passwords (hx509_lock /*lock*/); hx509_certs _hx509_lock_unlock_certs (hx509_lock /*lock*/); struct hx_expr * _hx509_make_expr ( enum hx_expr_op /*op*/, void */*arg1*/, void */*arg2*/); int _hx509_map_file_os ( const char */*fn*/, heim_octet_string */*os*/); int _hx509_match_keys ( hx509_cert /*c*/, hx509_private_key /*key*/); int _hx509_name_cmp ( const Name */*n1*/, const Name */*n2*/, int */*c*/); int _hx509_name_ds_cmp ( const DirectoryString */*ds1*/, const DirectoryString */*ds2*/, int */*diff*/); int _hx509_name_from_Name ( const Name */*n*/, hx509_name */*name*/); int _hx509_name_modify ( hx509_context /*context*/, Name */*name*/, int /*append*/, const heim_oid */*oid*/, const char */*str*/); int _hx509_path_append ( hx509_context /*context*/, hx509_path */*path*/, hx509_cert /*cert*/); void _hx509_path_free (hx509_path */*path*/); int _hx509_pbe_decrypt ( hx509_context /*context*/, hx509_lock /*lock*/, const AlgorithmIdentifier */*ai*/, const heim_octet_string */*econtent*/, heim_octet_string */*content*/); int _hx509_pbe_encrypt ( hx509_context /*context*/, hx509_lock /*lock*/, const AlgorithmIdentifier */*ai*/, const heim_octet_string */*content*/, heim_octet_string */*econtent*/); void _hx509_pi_printf ( int (*/*func*/)(void *, const char *), void */*ctx*/, const char */*fmt*/, ...); void _hx509_private_eckey_free (void */*eckey*/); int _hx509_private_key_export ( hx509_context /*context*/, const hx509_private_key /*key*/, hx509_key_format_t /*format*/, heim_octet_string */*data*/); int _hx509_private_key_exportable (hx509_private_key /*key*/); BIGNUM * _hx509_private_key_get_internal ( hx509_context /*context*/, hx509_private_key /*key*/, const char */*type*/); int _hx509_private_key_oid ( hx509_context /*context*/, const hx509_private_key /*key*/, heim_oid */*data*/); hx509_private_key _hx509_private_key_ref (hx509_private_key /*key*/); const char * _hx509_private_pem_name (hx509_private_key /*key*/); int _hx509_public_encrypt ( hx509_context /*context*/, const heim_octet_string */*cleartext*/, const Certificate */*cert*/, heim_oid */*encryption_oid*/, heim_octet_string */*ciphertext*/); void _hx509_query_clear (hx509_query */*q*/); int _hx509_query_match_cert ( hx509_context /*context*/, const hx509_query */*q*/, hx509_cert /*cert*/); void _hx509_query_statistic ( hx509_context /*context*/, int /*type*/, const hx509_query */*q*/); int _hx509_request_add_dns_name ( hx509_context /*context*/, hx509_request /*req*/, const char */*hostname*/); int _hx509_request_add_eku ( hx509_context /*context*/, hx509_request /*req*/, const heim_oid */*oid*/); int _hx509_request_add_email ( hx509_context /*context*/, hx509_request /*req*/, const char */*email*/); int _hx509_request_parse ( hx509_context /*context*/, const char */*path*/, hx509_request */*req*/); int _hx509_request_print ( hx509_context /*context*/, hx509_request /*req*/, FILE */*f*/); int _hx509_request_to_pkcs10 ( hx509_context /*context*/, const hx509_request /*req*/, const hx509_private_key /*signer*/, heim_octet_string */*request*/); hx509_revoke_ctx _hx509_revoke_ref (hx509_revoke_ctx /*ctx*/); void _hx509_sel_yyerror (const char */*s*/); int _hx509_self_signed_valid ( hx509_context /*context*/, const AlgorithmIdentifier */*alg*/); int _hx509_set_cert_attribute ( hx509_context /*context*/, hx509_cert /*cert*/, const heim_oid */*oid*/, const heim_octet_string */*attr*/); int _hx509_set_digest_alg ( DigestAlgorithmIdentifier */*id*/, const heim_oid */*oid*/, const void */*param*/, size_t /*length*/); int _hx509_signature_is_weak ( hx509_context /*context*/, const AlgorithmIdentifier */*alg*/); void _hx509_unmap_file_os (heim_octet_string */*os*/); int _hx509_unparse_Name ( const Name */*aname*/, char **/*str*/); time_t _hx509_verify_get_time (hx509_verify_ctx /*ctx*/); int _hx509_verify_signature ( hx509_context /*context*/, const hx509_cert /*cert*/, const AlgorithmIdentifier */*alg*/, const heim_octet_string */*data*/, const heim_octet_string */*sig*/); int _hx509_verify_signature_bitstring ( hx509_context /*context*/, const hx509_cert /*signer*/, const AlgorithmIdentifier */*alg*/, const heim_octet_string */*data*/, const heim_bit_string */*sig*/); int _hx509_write_file ( const char */*fn*/, const void */*data*/, size_t /*length*/); #endif /* __hx509_private_h__ */ heimdal-7.5.0/lib/hx509/test_nist.in0000644000175000017500000000731712136107750015253 0ustar niknik#!/bin/sh # # Copyright (c) 2004 - 2005 Kungliga Tekniska Högskolan # (Royal Institute of Technology, Stockholm, Sweden). # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # 1. Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # # 3. Neither the name of the Institute nor the names of its contributors # may be used to endorse or promote products derived from this software # without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE # ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS # OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) # HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY # OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF # SUCH DAMAGE. # # $Id$ # srcdir="@srcdir@" objdir="@objdir@" nistdir=${objdir}/PKITS_data nistzip=${srcdir}/data/PKITS_data.zip stat="--statistic-file=${objdir}/statfile" hxtool="${TESTS_ENVIRONMENT} ./hxtool ${stat}" # nistzip is not distributed part of the distribution test -f "$nistzip" || exit 77 if ${hxtool} info | grep 'rsa: hcrypto null RSA' > /dev/null ; then exit 77 fi if ${hxtool} info | grep 'rand: not available' > /dev/null ; then exit 77 fi echo "nist tests" if [ ! -d "$nistdir" ] ; then ( mkdir "$nistdir" && unzip -d "${nistdir}" "${nistzip}" ) >/dev/null || \ { rm -rf "$nistdir" ; exit 1; } fi while read id verify cert arg1 arg2 arg3 arg4 arg5 ; do expr "$id" : "#" > /dev/null && continue test "$id" = "end" && break args="" case "$arg1" in *.crt) args="$args chain:FILE:$nistdir/certs/$arg1" ;; *.crl) args="$args crl:FILE:$nistdir/crls/$arg1" ;; *) args="$args $arg1" ;; esac case "$arg2" in *.crt) args="$args chain:FILE:$nistdir/certs/$arg2" ;; *.crl) args="$args crl:FILE:$nistdir/crls/$arg2" ;; *) args="$args $arg2" ;; esac case "$arg3" in *.crt) args="$args chain:FILE:$nistdir/certs/$arg3" ;; *.crl) args="$args crl:FILE:$nistdir/crls/$arg3" ;; *) args="$args $arg3" ;; esac case "$arg4" in *.crt) args="$args chain:FILE:$nistdir/certs/$arg4" ;; *.crl) args="$args crl:FILE:$nistdir/crls/$arg4" ;; *) args="$args $arg4" ;; esac case "$arg5" in *.crt) args="$args chain:FILE:$nistdir/certs/$arg5" ;; *.crl) args="$args crl:FILE:$nistdir/crls/$arg5" ;; *) args="$args $arg5" ;; esac args="$args anchor:FILE:$nistdir/certs/TrustAnchorRootCertificate.crt" args="$args crl:FILE:$nistdir/crls/TrustAnchorRootCRL.crl" args="$args cert:FILE:$nistdir/certs/$cert" if ${hxtool} verify --time=2008-05-20 $args > /dev/null; then if test "$verify" = "f"; then echo "verify passed on fail: $id $cert" exit 1 fi else if test "$verify" = "p"; then echo "verify failed on pass: $id $cert" exit 1 fi fi done < $srcdir/data/nist-data echo "done!" exit 0 heimdal-7.5.0/lib/hx509/sel.c0000644000175000017500000001334213026237312013626 0ustar niknik/* * Copyright (c) 2008 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "hx_locl.h" struct hx_expr * _hx509_make_expr(enum hx_expr_op op, void *arg1, void *arg2) { struct hx_expr *expr; expr = malloc(sizeof(*expr)); if (expr == NULL) return NULL; expr->op = op; expr->arg1 = arg1; expr->arg2 = arg2; return expr; } static const char * eval_word(hx509_context context, hx509_env env, struct hx_expr *word) { switch (word->op) { case expr_STRING: return word->arg1; case expr_VAR: if (word->arg2 == NULL) return hx509_env_find(context, env, word->arg1); env = hx509_env_find_binding(context, env, word->arg1); if (env == NULL) return NULL; return eval_word(context, env, word->arg2); default: return NULL; } } static hx509_env find_variable(hx509_context context, hx509_env env, struct hx_expr *word) { assert(word->op == expr_VAR); if (word->arg2 == NULL) return hx509_env_find_binding(context, env, word->arg1); env = hx509_env_find_binding(context, env, word->arg1); if (env == NULL) return NULL; return find_variable(context, env, word->arg2); } static int eval_comp(hx509_context context, hx509_env env, struct hx_expr *expr) { switch (expr->op) { case comp_NE: case comp_EQ: case comp_TAILEQ: { const char *s1, *s2; int ret; s1 = eval_word(context, env, expr->arg1); s2 = eval_word(context, env, expr->arg2); if (s1 == NULL || s2 == NULL) return FALSE; if (expr->op == comp_TAILEQ) { size_t len1 = strlen(s1); size_t len2 = strlen(s2); if (len1 < len2) return 0; ret = strcmp(s1 + (len1 - len2), s2) == 0; } else { ret = strcmp(s1, s2) == 0; if (expr->op == comp_NE) ret = !ret; } return ret; } case comp_IN: { struct hx_expr *subexpr; const char *w, *s1; w = eval_word(context, env, expr->arg1); subexpr = expr->arg2; if (subexpr->op == expr_WORDS) { while (subexpr) { s1 = eval_word(context, env, subexpr->arg1); if (strcmp(w, s1) == 0) return TRUE; subexpr = subexpr->arg2; } } else if (subexpr->op == expr_VAR) { hx509_env subenv; subenv = find_variable(context, env, subexpr); if (subenv == NULL) return FALSE; while (subenv) { if (subenv->type != env_string) continue; if (strcmp(w, subenv->name) == 0) return TRUE; if (strcmp(w, subenv->u.string) == 0) return TRUE; subenv = subenv->next; } } else _hx509_abort("hx509 eval IN unknown op: %d", (int)subexpr->op); return FALSE; } default: _hx509_abort("hx509 eval expr with unknown op: %d", (int)expr->op); } return FALSE; } int _hx509_expr_eval(hx509_context context, hx509_env env, struct hx_expr *expr) { switch (expr->op) { case op_TRUE: return 1; case op_FALSE: return 0; case op_NOT: return ! _hx509_expr_eval(context, env, expr->arg1); case op_AND: return _hx509_expr_eval(context, env, expr->arg1) && _hx509_expr_eval(context, env, expr->arg2); case op_OR: return _hx509_expr_eval(context, env, expr->arg1) || _hx509_expr_eval(context, env, expr->arg2); case op_COMP: return eval_comp(context, env, expr->arg1); default: _hx509_abort("hx509 eval expr with unknown op: %d", (int)expr->op); UNREACHABLE(return 0); } } void _hx509_expr_free(struct hx_expr *expr) { switch (expr->op) { case expr_STRING: case expr_NUMBER: free(expr->arg1); break; case expr_WORDS: case expr_FUNCTION: case expr_VAR: free(expr->arg1); if (expr->arg2) _hx509_expr_free(expr->arg2); break; default: if (expr->arg1) _hx509_expr_free(expr->arg1); if (expr->arg2) _hx509_expr_free(expr->arg2); break; } free(expr); } struct hx_expr * _hx509_expr_parse(const char *buf) { _hx509_expr_input.buf = buf; _hx509_expr_input.length = strlen(buf); _hx509_expr_input.offset = 0; _hx509_expr_input.expr = NULL; if (_hx509_expr_input.error) { free(_hx509_expr_input.error); _hx509_expr_input.error = NULL; } yyparse(); return _hx509_expr_input.expr; } void _hx509_sel_yyerror (const char *s) { if (_hx509_expr_input.error) free(_hx509_expr_input.error); _hx509_expr_input.error = strdup(s); } heimdal-7.5.0/lib/hx509/doxygen.c0000644000175000017500000000656013026237312014524 0ustar niknik/* * Copyright (c) 2007 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ /** @mainpage Heimdal PKIX/X.509 library * * @section intro Introduction * * Heimdal libhx509 library is a implementation of the PKIX/X.509 and * related protocols. * * PKIX/X.509 is ... * * * Sections in this manual are: * - @ref page_name * - @ref page_cert * - @ref page_keyset * - @ref page_error * - @ref page_lock * - @ref page_cms * - @ref page_ca * - @ref page_revoke * - @ref page_print * - @ref page_env * * The project web page: * http://www.h5l.org/ * */ /** @defgroup hx509 hx509 library */ /** @defgroup hx509_error hx509 error functions * See the @ref page_error for description and examples. */ /** @defgroup hx509_cert hx509 certificate functions * See the @ref page_cert for description and examples. */ /** @defgroup hx509_keyset hx509 certificate store functions * See the @ref page_keyset for description and examples. */ /** @defgroup hx509_cms hx509 CMS/pkcs7 functions * See the @ref page_cms for description and examples. */ /** @defgroup hx509_crypto hx509 crypto functions */ /** @defgroup hx509_misc hx509 misc functions */ /** @defgroup hx509_name hx509 name functions * See the @ref page_name for description and examples. */ /** @defgroup hx509_revoke hx509 revokation checking functions * See the @ref page_revoke for description and examples. */ /** @defgroup hx509_verify hx509 verification functions */ /** @defgroup hx509_lock hx509 lock functions * See the @ref page_lock for description and examples. */ /** @defgroup hx509_query hx509 query functions */ /** @defgroup hx509_ca hx509 CA functions * See the @ref page_ca for description and examples. */ /** @defgroup hx509_peer hx509 certificate selecting functions */ /** @defgroup hx509_print hx509 printing functions */ /** @defgroup hx509_env hx509 environment functions */ heimdal-7.5.0/lib/hx509/ks_p12.c0000644000175000017500000004114513026237312014144 0ustar niknik/* * Copyright (c) 2004 - 2007 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "hx_locl.h" struct ks_pkcs12 { hx509_certs certs; char *fn; }; typedef int (*collector_func)(hx509_context, struct hx509_collector *, const void *, size_t, const PKCS12_Attributes *); struct type { const heim_oid *oid; collector_func func; }; static void parse_pkcs12_type(hx509_context, struct hx509_collector *, const heim_oid *, const void *, size_t, const PKCS12_Attributes *); static const PKCS12_Attribute * find_attribute(const PKCS12_Attributes *attrs, const heim_oid *oid) { size_t i; if (attrs == NULL) return NULL; for (i = 0; i < attrs->len; i++) if (der_heim_oid_cmp(oid, &attrs->val[i].attrId) == 0) return &attrs->val[i]; return NULL; } static int keyBag_parser(hx509_context context, struct hx509_collector *c, const void *data, size_t length, const PKCS12_Attributes *attrs) { const PKCS12_Attribute *attr; PKCS8PrivateKeyInfo ki; const heim_octet_string *os = NULL; int ret; attr = find_attribute(attrs, &asn1_oid_id_pkcs_9_at_localKeyId); if (attr) os = &attr->attrValues; ret = decode_PKCS8PrivateKeyInfo(data, length, &ki, NULL); if (ret) return ret; _hx509_collector_private_key_add(context, c, &ki.privateKeyAlgorithm, NULL, &ki.privateKey, os); free_PKCS8PrivateKeyInfo(&ki); return 0; } static int ShroudedKeyBag_parser(hx509_context context, struct hx509_collector *c, const void *data, size_t length, const PKCS12_Attributes *attrs) { PKCS8EncryptedPrivateKeyInfo pk; heim_octet_string content; int ret; memset(&pk, 0, sizeof(pk)); ret = decode_PKCS8EncryptedPrivateKeyInfo(data, length, &pk, NULL); if (ret) return ret; ret = _hx509_pbe_decrypt(context, _hx509_collector_get_lock(c), &pk.encryptionAlgorithm, &pk.encryptedData, &content); free_PKCS8EncryptedPrivateKeyInfo(&pk); if (ret) return ret; ret = keyBag_parser(context, c, content.data, content.length, attrs); der_free_octet_string(&content); return ret; } static int certBag_parser(hx509_context context, struct hx509_collector *c, const void *data, size_t length, const PKCS12_Attributes *attrs) { heim_error_t error = NULL; heim_octet_string os; hx509_cert cert; PKCS12_CertBag cb; int ret; ret = decode_PKCS12_CertBag(data, length, &cb, NULL); if (ret) return ret; if (der_heim_oid_cmp(&asn1_oid_id_pkcs_9_at_certTypes_x509, &cb.certType)) { free_PKCS12_CertBag(&cb); return 0; } ret = decode_PKCS12_OctetString(cb.certValue.data, cb.certValue.length, &os, NULL); free_PKCS12_CertBag(&cb); if (ret) return ret; cert = hx509_cert_init_data(context, os.data, os.length, &error); der_free_octet_string(&os); if (cert == NULL) { ret = heim_error_get_code(error); heim_release(error); return ret; } ret = _hx509_collector_certs_add(context, c, cert); if (ret) { hx509_cert_free(cert); return ret; } { const PKCS12_Attribute *attr; const heim_oid *oids[] = { &asn1_oid_id_pkcs_9_at_localKeyId, &asn1_oid_id_pkcs_9_at_friendlyName }; size_t i; for (i = 0; i < sizeof(oids)/sizeof(oids[0]); i++) { const heim_oid *oid = oids[i]; attr = find_attribute(attrs, oid); if (attr) _hx509_set_cert_attribute(context, cert, oid, &attr->attrValues); } } hx509_cert_free(cert); return 0; } static int parse_safe_content(hx509_context context, struct hx509_collector *c, const unsigned char *p, size_t len) { PKCS12_SafeContents sc; int ret; size_t i; memset(&sc, 0, sizeof(sc)); ret = decode_PKCS12_SafeContents(p, len, &sc, NULL); if (ret) return ret; for (i = 0; i < sc.len ; i++) parse_pkcs12_type(context, c, &sc.val[i].bagId, sc.val[i].bagValue.data, sc.val[i].bagValue.length, sc.val[i].bagAttributes); free_PKCS12_SafeContents(&sc); return 0; } static int safeContent_parser(hx509_context context, struct hx509_collector *c, const void *data, size_t length, const PKCS12_Attributes *attrs) { heim_octet_string os; int ret; ret = decode_PKCS12_OctetString(data, length, &os, NULL); if (ret) return ret; ret = parse_safe_content(context, c, os.data, os.length); der_free_octet_string(&os); return ret; } static int encryptedData_parser(hx509_context context, struct hx509_collector *c, const void *data, size_t length, const PKCS12_Attributes *attrs) { heim_octet_string content; heim_oid contentType; int ret; memset(&contentType, 0, sizeof(contentType)); ret = hx509_cms_decrypt_encrypted(context, _hx509_collector_get_lock(c), data, length, &contentType, &content); if (ret) return ret; if (der_heim_oid_cmp(&contentType, &asn1_oid_id_pkcs7_data) == 0) ret = parse_safe_content(context, c, content.data, content.length); der_free_octet_string(&content); der_free_oid(&contentType); return ret; } static int envelopedData_parser(hx509_context context, struct hx509_collector *c, const void *data, size_t length, const PKCS12_Attributes *attrs) { heim_octet_string content; heim_oid contentType; hx509_lock lock; int ret; memset(&contentType, 0, sizeof(contentType)); lock = _hx509_collector_get_lock(c); ret = hx509_cms_unenvelope(context, _hx509_lock_unlock_certs(lock), 0, data, length, NULL, 0, &contentType, &content); if (ret) { hx509_set_error_string(context, HX509_ERROR_APPEND, ret, "PKCS12 failed to unenvelope"); return ret; } if (der_heim_oid_cmp(&contentType, &asn1_oid_id_pkcs7_data) == 0) ret = parse_safe_content(context, c, content.data, content.length); der_free_octet_string(&content); der_free_oid(&contentType); return ret; } struct type bagtypes[] = { { &asn1_oid_id_pkcs12_keyBag, keyBag_parser }, { &asn1_oid_id_pkcs12_pkcs8ShroudedKeyBag, ShroudedKeyBag_parser }, { &asn1_oid_id_pkcs12_certBag, certBag_parser }, { &asn1_oid_id_pkcs7_data, safeContent_parser }, { &asn1_oid_id_pkcs7_encryptedData, encryptedData_parser }, { &asn1_oid_id_pkcs7_envelopedData, envelopedData_parser } }; static void parse_pkcs12_type(hx509_context context, struct hx509_collector *c, const heim_oid *oid, const void *data, size_t length, const PKCS12_Attributes *attrs) { size_t i; for (i = 0; i < sizeof(bagtypes)/sizeof(bagtypes[0]); i++) if (der_heim_oid_cmp(bagtypes[i].oid, oid) == 0) (*bagtypes[i].func)(context, c, data, length, attrs); } static int p12_init(hx509_context context, hx509_certs certs, void **data, int flags, const char *residue, hx509_lock lock) { struct ks_pkcs12 *p12; size_t len; void *buf; PKCS12_PFX pfx; PKCS12_AuthenticatedSafe as; int ret; size_t i; struct hx509_collector *c; *data = NULL; if (lock == NULL) lock = _hx509_empty_lock; ret = _hx509_collector_alloc(context, lock, &c); if (ret) return ret; p12 = calloc(1, sizeof(*p12)); if (p12 == NULL) { ret = ENOMEM; hx509_set_error_string(context, 0, ret, "out of memory"); goto out; } p12->fn = strdup(residue); if (p12->fn == NULL) { ret = ENOMEM; hx509_set_error_string(context, 0, ret, "out of memory"); goto out; } if (flags & HX509_CERTS_CREATE) { ret = hx509_certs_init(context, "MEMORY:ks-file-create", 0, lock, &p12->certs); if (ret == 0) *data = p12; goto out; } ret = rk_undumpdata(residue, &buf, &len); if (ret) { hx509_clear_error_string(context); goto out; } ret = decode_PKCS12_PFX(buf, len, &pfx, NULL); rk_xfree(buf); if (ret) { hx509_set_error_string(context, 0, ret, "Failed to decode the PFX in %s", residue); goto out; } if (der_heim_oid_cmp(&pfx.authSafe.contentType, &asn1_oid_id_pkcs7_data) != 0) { free_PKCS12_PFX(&pfx); ret = EINVAL; hx509_set_error_string(context, 0, ret, "PKCS PFX isn't a pkcs7-data container"); goto out; } if (pfx.authSafe.content == NULL) { free_PKCS12_PFX(&pfx); ret = EINVAL; hx509_set_error_string(context, 0, ret, "PKCS PFX missing data"); goto out; } { heim_octet_string asdata; ret = decode_PKCS12_OctetString(pfx.authSafe.content->data, pfx.authSafe.content->length, &asdata, NULL); free_PKCS12_PFX(&pfx); if (ret) { hx509_clear_error_string(context); goto out; } ret = decode_PKCS12_AuthenticatedSafe(asdata.data, asdata.length, &as, NULL); der_free_octet_string(&asdata); if (ret) { hx509_clear_error_string(context); goto out; } } for (i = 0; i < as.len; i++) parse_pkcs12_type(context, c, &as.val[i].contentType, as.val[i].content->data, as.val[i].content->length, NULL); free_PKCS12_AuthenticatedSafe(&as); ret = _hx509_collector_collect_certs(context, c, &p12->certs); if (ret == 0) *data = p12; out: _hx509_collector_free(c); if (ret && p12) { if (p12->fn) free(p12->fn); if (p12->certs) hx509_certs_free(&p12->certs); free(p12); } return ret; } static int addBag(hx509_context context, PKCS12_AuthenticatedSafe *as, const heim_oid *oid, void *data, size_t length) { void *ptr; int ret; ptr = realloc(as->val, sizeof(as->val[0]) * (as->len + 1)); if (ptr == NULL) { hx509_set_error_string(context, 0, ENOMEM, "out of memory"); return ENOMEM; } as->val = ptr; ret = der_copy_oid(oid, &as->val[as->len].contentType); if (ret) { hx509_set_error_string(context, 0, ret, "out of memory"); return ret; } as->val[as->len].content = calloc(1, sizeof(*as->val[0].content)); if (as->val[as->len].content == NULL) { der_free_oid(&as->val[as->len].contentType); hx509_set_error_string(context, 0, ENOMEM, "malloc out of memory"); return ENOMEM; } as->val[as->len].content->data = data; as->val[as->len].content->length = length; as->len++; return 0; } static int store_func(hx509_context context, void *ctx, hx509_cert c) { PKCS12_AuthenticatedSafe *as = ctx; PKCS12_OctetString os; PKCS12_CertBag cb; size_t size; int ret; memset(&os, 0, sizeof(os)); memset(&cb, 0, sizeof(cb)); os.data = NULL; os.length = 0; ret = hx509_cert_binary(context, c, &os); if (ret) return ret; ASN1_MALLOC_ENCODE(PKCS12_OctetString, cb.certValue.data,cb.certValue.length, &os, &size, ret); free(os.data); if (ret) goto out; ret = der_copy_oid(&asn1_oid_id_pkcs_9_at_certTypes_x509, &cb.certType); if (ret) { free_PKCS12_CertBag(&cb); goto out; } ASN1_MALLOC_ENCODE(PKCS12_CertBag, os.data, os.length, &cb, &size, ret); free_PKCS12_CertBag(&cb); if (ret) goto out; ret = addBag(context, as, &asn1_oid_id_pkcs12_certBag, os.data, os.length); if (_hx509_cert_private_key_exportable(c)) { hx509_private_key key = _hx509_cert_private_key(c); PKCS8PrivateKeyInfo pki; memset(&pki, 0, sizeof(pki)); ret = der_parse_hex_heim_integer("00", &pki.version); if (ret) return ret; ret = _hx509_private_key_oid(context, key, &pki.privateKeyAlgorithm.algorithm); if (ret) { free_PKCS8PrivateKeyInfo(&pki); return ret; } ret = _hx509_private_key_export(context, _hx509_cert_private_key(c), HX509_KEY_FORMAT_DER, &pki.privateKey); if (ret) { free_PKCS8PrivateKeyInfo(&pki); return ret; } /* set attribute, asn1_oid_id_pkcs_9_at_localKeyId */ ASN1_MALLOC_ENCODE(PKCS8PrivateKeyInfo, os.data, os.length, &pki, &size, ret); free_PKCS8PrivateKeyInfo(&pki); if (ret) return ret; ret = addBag(context, as, &asn1_oid_id_pkcs12_keyBag, os.data, os.length); if (ret) return ret; } out: return ret; } static int p12_store(hx509_context context, hx509_certs certs, void *data, int flags, hx509_lock lock) { struct ks_pkcs12 *p12 = data; PKCS12_PFX pfx; PKCS12_AuthenticatedSafe as; PKCS12_OctetString asdata; size_t size; int ret; memset(&as, 0, sizeof(as)); memset(&pfx, 0, sizeof(pfx)); ret = hx509_certs_iter_f(context, p12->certs, store_func, &as); if (ret) goto out; ASN1_MALLOC_ENCODE(PKCS12_AuthenticatedSafe, asdata.data, asdata.length, &as, &size, ret); free_PKCS12_AuthenticatedSafe(&as); if (ret) return ret; ret = der_parse_hex_heim_integer("03", &pfx.version); if (ret) { free(asdata.data); goto out; } pfx.authSafe.content = calloc(1, sizeof(*pfx.authSafe.content)); ASN1_MALLOC_ENCODE(PKCS12_OctetString, pfx.authSafe.content->data, pfx.authSafe.content->length, &asdata, &size, ret); free(asdata.data); if (ret) goto out; ret = der_copy_oid(&asn1_oid_id_pkcs7_data, &pfx.authSafe.contentType); if (ret) goto out; ASN1_MALLOC_ENCODE(PKCS12_PFX, asdata.data, asdata.length, &pfx, &size, ret); if (ret) goto out; #if 0 const struct _hx509_password *pw; pw = _hx509_lock_get_passwords(lock); if (pw != NULL) { pfx.macData = calloc(1, sizeof(*pfx.macData)); if (pfx.macData == NULL) { ret = ENOMEM; hx509_set_error_string(context, 0, ret, "malloc out of memory"); return ret; } if (pfx.macData == NULL) { free(asdata.data); goto out; } } ret = calculate_hash(&aspath, pw, pfx.macData); #endif rk_dumpdata(p12->fn, asdata.data, asdata.length); free(asdata.data); out: free_PKCS12_AuthenticatedSafe(&as); free_PKCS12_PFX(&pfx); return ret; } static int p12_free(hx509_certs certs, void *data) { struct ks_pkcs12 *p12 = data; hx509_certs_free(&p12->certs); free(p12->fn); free(p12); return 0; } static int p12_add(hx509_context context, hx509_certs certs, void *data, hx509_cert c) { struct ks_pkcs12 *p12 = data; return hx509_certs_add(context, p12->certs, c); } static int p12_iter_start(hx509_context context, hx509_certs certs, void *data, void **cursor) { struct ks_pkcs12 *p12 = data; return hx509_certs_start_seq(context, p12->certs, cursor); } static int p12_iter(hx509_context context, hx509_certs certs, void *data, void *cursor, hx509_cert *cert) { struct ks_pkcs12 *p12 = data; return hx509_certs_next_cert(context, p12->certs, cursor, cert); } static int p12_iter_end(hx509_context context, hx509_certs certs, void *data, void *cursor) { struct ks_pkcs12 *p12 = data; return hx509_certs_end_seq(context, p12->certs, cursor); } static struct hx509_keyset_ops keyset_pkcs12 = { "PKCS12", 0, p12_init, p12_store, p12_free, p12_add, NULL, p12_iter_start, p12_iter, p12_iter_end, NULL, NULL, NULL }; void _hx509_ks_pkcs12_register(hx509_context context) { _hx509_ks_register(context, &keyset_pkcs12); } heimdal-7.5.0/lib/hx509/quote.py0000644000175000017500000000630112136107750014406 0ustar niknik#!/usr/bin/python # -*- coding: utf-8 -*- # # Copyright (c) 2010 Kungliga Tekniska Högskolan # (Royal Institute of Technology, Stockholm, Sweden). # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # 1. Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # # 3. Neither the name of the Institute nor the names of its contributors # may be used to endorse or promote products derived from this software # without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE # ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS # OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) # HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY # OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF # SUCH DAMAGE. # CONTROL_CHAR = 1 PRINTABLE = 2 RFC2253_QUOTE_FIRST = 4 RFC2253_QUOTE_LAST = 8 RFC2253_QUOTE = 16 RFC2253_HEX = 32 chars = [] for i in range(0, 256): chars.append(0); for i in range(0, 256): if (i < 32 or i > 126): chars[i] |= CONTROL_CHAR | RFC2253_HEX; for i in range(ord("A"), ord("Z") + 1): chars[i] |= PRINTABLE for i in range(ord("a"), ord("z") + 1): chars[i] |= PRINTABLE for i in range(ord("0"), ord("9") + 1): chars[i] |= PRINTABLE chars[ord(' ')] |= PRINTABLE chars[ord('+')] |= PRINTABLE chars[ord(',')] |= PRINTABLE chars[ord('-')] |= PRINTABLE chars[ord('.')] |= PRINTABLE chars[ord('/')] |= PRINTABLE chars[ord(':')] |= PRINTABLE chars[ord('=')] |= PRINTABLE chars[ord('?')] |= PRINTABLE chars[ord(' ')] |= RFC2253_QUOTE_FIRST | RFC2253_QUOTE_FIRST chars[ord(',')] |= RFC2253_QUOTE chars[ord('=')] |= RFC2253_QUOTE chars[ord('+')] |= RFC2253_QUOTE chars[ord('<')] |= RFC2253_QUOTE chars[ord('>')] |= RFC2253_QUOTE chars[ord('#')] |= RFC2253_QUOTE chars[ord(';')] |= RFC2253_QUOTE print "#define Q_CONTROL_CHAR 1" print "#define Q_PRINTABLE 2" print "#define Q_RFC2253_QUOTE_FIRST 4" print "#define Q_RFC2253_QUOTE_LAST 8" print "#define Q_RFC2253_QUOTE 16" print "#define Q_RFC2253_HEX 32" print "" print "#define Q_RFC2253 (Q_RFC2253_QUOTE_FIRST|Q_RFC2253_QUOTE_LAST|Q_RFC2253_QUOTE|Q_RFC2253_HEX)" print "\n" * 2 print "unsigned char char_map[] = {\n\t", for x in range(0, 256): if (x % 8) == 0 and x != 0: print "\n\t", print "0x%(char)02x" % { 'char' : chars[x] }, if x < 255: print ", ", else: print "" print "};" heimdal-7.5.0/lib/hx509/test_pkcs11.in0000644000175000017500000000414412136107750015373 0ustar niknik#!/bin/sh # # Copyright (c) 2008 Kungliga Tekniska Högskolan # (Royal Institute of Technology, Stockholm, Sweden). # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # 1. Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # # 3. Neither the name of the Institute nor the names of its contributors # may be used to endorse or promote products derived from this software # without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE # ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS # OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) # HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY # OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF # SUCH DAMAGE. # srcdir="@srcdir@" objdir="@objdir@" SOFTPKCS11RC="test-rc-file.rc" \ export SOFTPKCS11RC echo "password less" cat > test-rc-file.rc < test-rc-file.rc < /dev/null ; then exit 77 fi if ${hxtool} info | grep 'rand: not available' > /dev/null ; then exit 77 fi echo "Bleichenbacher good cert (from eay)" ${hxtool} verify --missing-revoke \ --time=2006-09-25 \ cert:FILE:$srcdir/data/bleichenbacher-good.pem \ anchor:FILE:$srcdir/data/bleichenbacher-good.pem > /dev/null || exit 1 echo "Bleichenbacher bad cert (from eay)" ${hxtool} verify --missing-revoke \ --time=2006-09-25 \ cert:FILE:$srcdir/data/bleichenbacher-bad.pem \ anchor:FILE:$srcdir/data/bleichenbacher-bad.pem > /dev/null && exit 1 echo "Bleichenbacher good cert (from yutaka)" ${hxtool} verify --missing-revoke \ --time=2006-09-25 \ cert:FILE:$srcdir/data/yutaka-pad-ok-cert.pem \ anchor:FILE:$srcdir/data/yutaka-pad-ok-ca.pem > /dev/null || exit 1 echo "Bleichenbacher bad cert (from yutaka)" ${hxtool} verify --missing-revoke \ --time=2006-09-25 \ cert:FILE:$srcdir/data/yutaka-pad-broken-cert.pem \ anchor:FILE:$srcdir/data/yutaka-pad-broken-ca.pem > /dev/null && exit 1 # Ralf-Philipp Weinmann # Andrew Pyshkin echo "Bleichenbacher bad cert (sf pad correct)" ${hxtool} verify --missing-revoke \ --time=2006-09-25 \ cert:FILE:$srcdir/data/bleichenbacher-sf-pad-correct.pem \ anchor:FILE:$srcdir/data/sf-class2-root.pem > /dev/null && exit 1 echo Read 50 kilobyte random data ${hxtool} random-data 50kilobyte > random-data || exit 1 echo "crypto select1" ${hxtool} crypto-select > test || { echo "select1"; exit 1; } cmp test ${srcdir}/tst-crypto-select1 > /dev/null || \ { echo "select1 failure"; exit 1; } echo "crypto select1" ${hxtool} crypto-select --type=digest > test || { echo "select1"; exit 1; } cmp test ${srcdir}/tst-crypto-select1 > /dev/null || \ { echo "select1 failure"; exit 1; } echo "crypto select2" ${hxtool} crypto-select --type=public-sig > test || { echo "select2"; exit 1; } cmp test ${srcdir}/tst-crypto-select2 > /dev/null || \ { echo "select2 failure"; exit 1; } echo "crypto select3" ${hxtool} crypto-select \ --type=public-sig \ --peer-cmstype=1.2.840.113549.1.1.4 \ > test || { echo "select3"; exit 1; } cmp test ${srcdir}/tst-crypto-select3 > /dev/null || \ { echo "select3 failure"; exit 1; } echo "crypto select4" ${hxtool} crypto-select \ --type=public-sig \ --peer-cmstype=1.2.840.113549.1.1.5 \ --peer-cmstype=1.2.840.113549.1.1.4 \ > test || { echo "select4"; exit 1; } cmp test ${srcdir}/tst-crypto-select4 > /dev/null || \ { echo "select4 failure"; exit 1; } echo "crypto select5" ${hxtool} crypto-select \ --type=public-sig \ --peer-cmstype=1.2.840.113549.1.1.11 \ --peer-cmstype=1.2.840.113549.1.1.5 \ > test || { echo "select5"; exit 1; } cmp test ${srcdir}/tst-crypto-select5 > /dev/null || \ { echo "select5 failure"; exit 1; } echo "crypto select6" ${hxtool} crypto-select \ --type=public-sig \ --peer-cmstype=1.2.840.113549.2.5 \ --peer-cmstype=1.2.840.113549.1.1.5 \ > test || { echo "select6"; exit 1; } cmp test ${srcdir}/tst-crypto-select6 > /dev/null || \ { echo "select6 failure"; exit 1; } echo "crypto select7" ${hxtool} crypto-select \ --type=secret \ --peer-cmstype=2.16.840.1.101.3.4.1.42 \ --peer-cmstype=1.2.840.113549.3.7 \ --peer-cmstype=1.2.840.113549.1.1.5 \ > test || { echo "select7"; exit 1; } cmp test ${srcdir}/tst-crypto-select7 > /dev/null || \ { echo "select7 failure"; exit 1; } #echo "crypto available1" #${hxtool} crypto-available \ # --type=all \ # > test || { echo "available1"; exit 1; } #cmp test ${srcdir}/tst-crypto-available1 > /dev/null || \ # { echo "available1 failure"; exit 1; } echo "crypto available2" ${hxtool} crypto-available \ --type=digest \ > test || { echo "available2"; exit 1; } cmp test ${srcdir}/tst-crypto-available2 > /dev/null || \ { echo "available2 failure"; exit 1; } #echo "crypto available3" #${hxtool} crypto-available \ # --type=public-sig \ # > test || { echo "available3"; exit 1; } #cmp test ${srcdir}/tst-crypto-available3 > /dev/null || \ # { echo "available3 failure"; exit 1; } echo "copy keystore FILE existing -> FILE" ${hxtool} certificate-copy \ FILE:${srcdir}/data/test.crt,${srcdir}/data/test.key \ FILE:out.pem || exit 1 echo "copy keystore FILE -> FILE" ${hxtool} certificate-copy \ FILE:out.pem \ FILE:out2.pem || exit 1 echo "copy keystore FILE -> PKCS12" ${hxtool} certificate-copy \ FILE:out.pem \ PKCS12:out2.pem || exit 1 echo "print certificate with utf8" ${hxtool} print \ FILE:$srcdir/data/j.pem >/dev/null 2>/dev/null || exit 1 echo "Make sure that we can parse EC private keys" ${hxtool} print --content \ FILE:$srcdir/data/pkinit-ec.crt,$srcdir/data/pkinit-ec.key \ > /dev/null || exit 1 exit 0 heimdal-7.5.0/lib/hx509/ks_file.c0000644000175000017500000004002013212137553014453 0ustar niknik/* * Copyright (c) 2005 - 2007 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "hx_locl.h" typedef enum { USE_PEM, USE_DER } outformat; struct ks_file { hx509_certs certs; char *fn; outformat format; }; /* * */ static int parse_certificate(hx509_context context, const char *fn, struct hx509_collector *c, const hx509_pem_header *headers, const void *data, size_t len, const AlgorithmIdentifier *ai) { heim_error_t error = NULL; hx509_cert cert; int ret; cert = hx509_cert_init_data(context, data, len, &error); if (cert == NULL) { ret = heim_error_get_code(error); heim_release(error); return ret; } ret = _hx509_collector_certs_add(context, c, cert); hx509_cert_free(cert); return ret; } static int try_decrypt(hx509_context context, struct hx509_collector *collector, const AlgorithmIdentifier *alg, const EVP_CIPHER *c, const void *ivdata, const void *password, size_t passwordlen, const void *cipher, size_t len) { heim_octet_string clear; size_t keylen; void *key; int ret; keylen = EVP_CIPHER_key_length(c); key = malloc(keylen); if (key == NULL) { hx509_clear_error_string(context); return ENOMEM; } ret = EVP_BytesToKey(c, EVP_md5(), ivdata, password, passwordlen, 1, key, NULL); if (ret <= 0) { ret = HX509_CRYPTO_INTERNAL_ERROR; hx509_set_error_string(context, 0, ret, "Failed to do string2key for private key"); goto out; } clear.data = malloc(len); if (clear.data == NULL) { hx509_set_error_string(context, 0, ENOMEM, "Out of memory to decrypt for private key"); ret = ENOMEM; goto out; } clear.length = len; { EVP_CIPHER_CTX ctx; EVP_CIPHER_CTX_init(&ctx); EVP_CipherInit_ex(&ctx, c, NULL, key, ivdata, 0); EVP_Cipher(&ctx, clear.data, cipher, len); EVP_CIPHER_CTX_cleanup(&ctx); } ret = _hx509_collector_private_key_add(context, collector, alg, NULL, &clear, NULL); memset(clear.data, 0, clear.length); free(clear.data); out: memset(key, 0, keylen); free(key); return ret; } static int parse_pkcs8_private_key(hx509_context context, const char *fn, struct hx509_collector *c, const hx509_pem_header *headers, const void *data, size_t length, const AlgorithmIdentifier *ai) { PKCS8PrivateKeyInfo ki; heim_octet_string keydata; int ret; ret = decode_PKCS8PrivateKeyInfo(data, length, &ki, NULL); if (ret) return ret; keydata.data = rk_UNCONST(data); keydata.length = length; ret = _hx509_collector_private_key_add(context, c, &ki.privateKeyAlgorithm, NULL, &ki.privateKey, &keydata); free_PKCS8PrivateKeyInfo(&ki); return ret; } static int parse_pem_private_key(hx509_context context, const char *fn, struct hx509_collector *c, const hx509_pem_header *headers, const void *data, size_t len, const AlgorithmIdentifier *ai) { int ret = 0; const char *enc; enc = hx509_pem_find_header(headers, "Proc-Type"); if (enc) { const char *dek; char *type, *iv; ssize_t ssize, size; void *ivdata; const EVP_CIPHER *cipher; const struct _hx509_password *pw; hx509_lock lock; int decrypted = 0; size_t i; lock = _hx509_collector_get_lock(c); if (lock == NULL) { hx509_set_error_string(context, 0, HX509_ALG_NOT_SUPP, "Failed to get password for " "password protected file %s", fn); return HX509_ALG_NOT_SUPP; } if (strcmp(enc, "4,ENCRYPTED") != 0) { hx509_set_error_string(context, 0, HX509_PARSING_KEY_FAILED, "Private key encrypted in unknown method %s " "in file", enc, fn); hx509_clear_error_string(context); return HX509_PARSING_KEY_FAILED; } dek = hx509_pem_find_header(headers, "DEK-Info"); if (dek == NULL) { hx509_set_error_string(context, 0, HX509_PARSING_KEY_FAILED, "Encrypted private key missing DEK-Info"); return HX509_PARSING_KEY_FAILED; } type = strdup(dek); if (type == NULL) { hx509_clear_error_string(context); return ENOMEM; } iv = strchr(type, ','); if (iv == NULL) { free(type); hx509_set_error_string(context, 0, HX509_PARSING_KEY_FAILED, "IV missing"); return HX509_PARSING_KEY_FAILED; } *iv++ = '\0'; size = strlen(iv); ivdata = malloc(size); if (ivdata == NULL) { hx509_clear_error_string(context); free(type); return ENOMEM; } cipher = EVP_get_cipherbyname(type); if (cipher == NULL) { free(ivdata); hx509_set_error_string(context, 0, HX509_ALG_NOT_SUPP, "Private key encrypted with " "unsupported cipher: %s", type); free(type); return HX509_ALG_NOT_SUPP; } #define PKCS5_SALT_LEN 8 ssize = hex_decode(iv, ivdata, size); free(type); type = NULL; iv = NULL; if (ssize < 0 || ssize < PKCS5_SALT_LEN || ssize < EVP_CIPHER_iv_length(cipher)) { free(ivdata); hx509_set_error_string(context, 0, HX509_PARSING_KEY_FAILED, "Salt have wrong length in " "private key file"); return HX509_PARSING_KEY_FAILED; } pw = _hx509_lock_get_passwords(lock); if (pw != NULL) { const void *password; size_t passwordlen; for (i = 0; i < pw->len; i++) { password = pw->val[i]; passwordlen = strlen(password); ret = try_decrypt(context, c, ai, cipher, ivdata, password, passwordlen, data, len); if (ret == 0) { decrypted = 1; break; } } } if (!decrypted) { hx509_prompt prompt; char password[128]; memset(&prompt, 0, sizeof(prompt)); prompt.prompt = "Password for keyfile: "; prompt.type = HX509_PROMPT_TYPE_PASSWORD; prompt.reply.data = password; prompt.reply.length = sizeof(password); ret = hx509_lock_prompt(lock, &prompt); if (ret == 0) ret = try_decrypt(context, c, ai, cipher, ivdata, password, strlen(password), data, len); /* XXX add password to lock password collection ? */ memset(password, 0, sizeof(password)); } free(ivdata); } else { heim_octet_string keydata; keydata.data = rk_UNCONST(data); keydata.length = len; ret = _hx509_collector_private_key_add(context, c, ai, NULL, &keydata, NULL); } return ret; } struct pem_formats { const char *name; int (*func)(hx509_context, const char *, struct hx509_collector *, const hx509_pem_header *, const void *, size_t, const AlgorithmIdentifier *); const AlgorithmIdentifier *(*ai)(void); } formats[] = { { "CERTIFICATE", parse_certificate, NULL }, { "PRIVATE KEY", parse_pkcs8_private_key, NULL }, { "RSA PRIVATE KEY", parse_pem_private_key, hx509_signature_rsa }, #ifdef HAVE_HCRYPTO_W_OPENSSL { "EC PRIVATE KEY", parse_pem_private_key, hx509_signature_ecPublicKey } #endif }; struct pem_ctx { int flags; struct hx509_collector *c; }; static int pem_func(hx509_context context, const char *type, const hx509_pem_header *header, const void *data, size_t len, void *ctx) { struct pem_ctx *pem_ctx = (struct pem_ctx*)ctx; int ret = 0; size_t j; for (j = 0; j < sizeof(formats)/sizeof(formats[0]); j++) { const char *q = formats[j].name; if (strcasecmp(type, q) == 0) { const AlgorithmIdentifier *ai = NULL; if (formats[j].ai != NULL) ai = (*formats[j].ai)(); ret = (*formats[j].func)(context, NULL, pem_ctx->c, header, data, len, ai); if (ret && (pem_ctx->flags & HX509_CERTS_UNPROTECT_ALL)) { hx509_set_error_string(context, HX509_ERROR_APPEND, ret, "Failed parseing PEM format %s", type); return ret; } break; } } if (j == sizeof(formats)/sizeof(formats[0])) { ret = HX509_UNSUPPORTED_OPERATION; hx509_set_error_string(context, 0, ret, "Found no matching PEM format for %s", type); return ret; } return 0; } /* * */ static int file_init_common(hx509_context context, hx509_certs certs, void **data, int flags, const char *residue, hx509_lock lock, outformat format) { char *p, *pnext; struct ks_file *ksf = NULL; hx509_private_key *keys = NULL; int ret; struct pem_ctx pem_ctx; pem_ctx.flags = flags; pem_ctx.c = NULL; *data = NULL; if (lock == NULL) lock = _hx509_empty_lock; ksf = calloc(1, sizeof(*ksf)); if (ksf == NULL) { hx509_clear_error_string(context); return ENOMEM; } ksf->format = format; ksf->fn = strdup(residue); if (ksf->fn == NULL) { hx509_clear_error_string(context); ret = ENOMEM; goto out; } /* * XXX this is broken, the function should parse the file before * overwriting it */ if (flags & HX509_CERTS_CREATE) { ret = hx509_certs_init(context, "MEMORY:ks-file-create", 0, lock, &ksf->certs); if (ret) goto out; *data = ksf; return 0; } ret = _hx509_collector_alloc(context, lock, &pem_ctx.c); if (ret) goto out; for (p = ksf->fn; p != NULL; p = pnext) { FILE *f; pnext = strchr(p, ','); if (pnext) *pnext++ = '\0'; if ((f = fopen(p, "r")) == NULL) { ret = ENOENT; hx509_set_error_string(context, 0, ret, "Failed to open PEM file \"%s\": %s", p, strerror(errno)); goto out; } rk_cloexec_file(f); ret = hx509_pem_read(context, f, pem_func, &pem_ctx); fclose(f); if (ret != 0 && ret != HX509_PARSING_KEY_FAILED) goto out; else if (ret == HX509_PARSING_KEY_FAILED) { size_t length; void *ptr; size_t i; ret = rk_undumpdata(p, &ptr, &length); if (ret) { hx509_clear_error_string(context); goto out; } for (i = 0; i < sizeof(formats)/sizeof(formats[0]); i++) { const AlgorithmIdentifier *ai = NULL; if (formats[i].ai != NULL) ai = (*formats[i].ai)(); ret = (*formats[i].func)(context, p, pem_ctx.c, NULL, ptr, length, ai); if (ret == 0) break; } rk_xfree(ptr); if (ret) { hx509_clear_error_string(context); goto out; } } } ret = _hx509_collector_collect_certs(context, pem_ctx.c, &ksf->certs); if (ret) goto out; ret = _hx509_collector_collect_private_keys(context, pem_ctx.c, &keys); if (ret == 0) { int i; for (i = 0; keys[i]; i++) _hx509_certs_keys_add(context, ksf->certs, keys[i]); _hx509_certs_keys_free(context, keys); } out: if (ret == 0) *data = ksf; else { if (ksf->fn) free(ksf->fn); free(ksf); } if (pem_ctx.c) _hx509_collector_free(pem_ctx.c); return ret; } static int file_init_pem(hx509_context context, hx509_certs certs, void **data, int flags, const char *residue, hx509_lock lock) { return file_init_common(context, certs, data, flags, residue, lock, USE_PEM); } static int file_init_der(hx509_context context, hx509_certs certs, void **data, int flags, const char *residue, hx509_lock lock) { return file_init_common(context, certs, data, flags, residue, lock, USE_DER); } static int file_free(hx509_certs certs, void *data) { struct ks_file *ksf = data; hx509_certs_free(&ksf->certs); free(ksf->fn); free(ksf); return 0; } struct store_ctx { FILE *f; outformat format; }; static int store_func(hx509_context context, void *ctx, hx509_cert c) { struct store_ctx *sc = ctx; heim_octet_string data; int ret; ret = hx509_cert_binary(context, c, &data); if (ret) return ret; switch (sc->format) { case USE_DER: fwrite(data.data, data.length, 1, sc->f); free(data.data); break; case USE_PEM: hx509_pem_write(context, "CERTIFICATE", NULL, sc->f, data.data, data.length); free(data.data); if (_hx509_cert_private_key_exportable(c)) { hx509_private_key key = _hx509_cert_private_key(c); ret = _hx509_private_key_export(context, key, HX509_KEY_FORMAT_DER, &data); if (ret) break; hx509_pem_write(context, _hx509_private_pem_name(key), NULL, sc->f, data.data, data.length); free(data.data); } break; } return 0; } static int file_store(hx509_context context, hx509_certs certs, void *data, int flags, hx509_lock lock) { struct ks_file *ksf = data; struct store_ctx sc; int ret; sc.f = fopen(ksf->fn, "w"); if (sc.f == NULL) { hx509_set_error_string(context, 0, ENOENT, "Failed to open file %s for writing"); return ENOENT; } rk_cloexec_file(sc.f); sc.format = ksf->format; ret = hx509_certs_iter_f(context, ksf->certs, store_func, &sc); fclose(sc.f); return ret; } static int file_add(hx509_context context, hx509_certs certs, void *data, hx509_cert c) { struct ks_file *ksf = data; return hx509_certs_add(context, ksf->certs, c); } static int file_iter_start(hx509_context context, hx509_certs certs, void *data, void **cursor) { struct ks_file *ksf = data; return hx509_certs_start_seq(context, ksf->certs, cursor); } static int file_iter(hx509_context context, hx509_certs certs, void *data, void *iter, hx509_cert *cert) { struct ks_file *ksf = data; return hx509_certs_next_cert(context, ksf->certs, iter, cert); } static int file_iter_end(hx509_context context, hx509_certs certs, void *data, void *cursor) { struct ks_file *ksf = data; return hx509_certs_end_seq(context, ksf->certs, cursor); } static int file_getkeys(hx509_context context, hx509_certs certs, void *data, hx509_private_key **keys) { struct ks_file *ksf = data; return _hx509_certs_keys_get(context, ksf->certs, keys); } static int file_addkey(hx509_context context, hx509_certs certs, void *data, hx509_private_key key) { struct ks_file *ksf = data; return _hx509_certs_keys_add(context, ksf->certs, key); } static struct hx509_keyset_ops keyset_file = { "FILE", 0, file_init_pem, file_store, file_free, file_add, NULL, file_iter_start, file_iter, file_iter_end, NULL, file_getkeys, file_addkey }; static struct hx509_keyset_ops keyset_pemfile = { "PEM-FILE", 0, file_init_pem, file_store, file_free, file_add, NULL, file_iter_start, file_iter, file_iter_end, NULL, file_getkeys, file_addkey }; static struct hx509_keyset_ops keyset_derfile = { "DER-FILE", 0, file_init_der, file_store, file_free, file_add, NULL, file_iter_start, file_iter, file_iter_end, NULL, file_getkeys, file_addkey }; void _hx509_ks_file_register(hx509_context context) { _hx509_ks_register(context, &keyset_file); _hx509_ks_register(context, &keyset_pemfile); _hx509_ks_register(context, &keyset_derfile); } heimdal-7.5.0/lib/hx509/test_nist_pkcs12.in0000644000175000017500000000464712136107750016441 0ustar niknik#!/bin/sh # # Copyright (c) 2004 - 2005 Kungliga Tekniska Högskolan # (Royal Institute of Technology, Stockholm, Sweden). # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # 1. Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # # 3. Neither the name of the Institute nor the names of its contributors # may be used to endorse or promote products derived from this software # without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE # ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS # OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) # HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY # OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF # SUCH DAMAGE. # # $Id$ # srcdir="@srcdir@" objdir="@objdir@" pass="--pass=PASS:password" nistdir=${objdir}/PKITS_data nistzip=${srcdir}/data/PKITS_data.zip # nistzip is not distributed part of the distribution test -f "$nistzip" || exit 77 stat="--statistic-file=${objdir}/statfile" hxtool="${TESTS_ENVIRONMENT} ./hxtool ${stat}" if ${hxtool} info | grep 'rsa: hcrypto null RSA' > /dev/null ; then exit 77 fi if ${hxtool} info | grep 'rand: not available' > /dev/null ; then exit 77 fi if [ ! -d "$nistdir" ] ; then ( mkdir "$nistdir" && cd "$nistdir" && unzip "$nistzip" ) >/dev/null || \ { rm -rf "$nistdir" ; exit 1; } fi echo "nist pkcs12 tests" for a in $nistdir/pkcs12/*.p12 ; do if ${hxtool} validate $pass PKCS12:$a > /dev/null; then : else echo "$a failed" exit 1 fi done echo "done!" exit 0heimdal-7.5.0/lib/hx509/Makefile.in0000644000175000017500000022072213212444522014746 0ustar niknik# Makefile.in generated by automake 1.15.1 from Makefile.am. # @configure_input@ # Copyright (C) 1994-2017 Free Software Foundation, Inc. # This Makefile.in is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, # with or without modifications, as long as this notice is preserved. # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY, to the extent permitted by law; without # even the implied warranty of MERCHANTABILITY or FITNESS FOR A # PARTICULAR PURPOSE. @SET_MAKE@ # $Id$ # $Id$ VPATH = @srcdir@ am__is_gnu_make = { \ if test -z '$(MAKELEVEL)'; then \ false; \ elif test -n '$(MAKE_HOST)'; then \ true; \ elif test -n '$(MAKE_VERSION)' && test -n '$(CURDIR)'; then \ true; \ else \ false; \ fi; \ } am__make_running_with_option = \ case $${target_option-} in \ ?) ;; \ *) echo "am__make_running_with_option: internal error: invalid" \ "target option '$${target_option-}' specified" >&2; \ exit 1;; \ esac; \ has_opt=no; \ sane_makeflags=$$MAKEFLAGS; \ if $(am__is_gnu_make); then \ sane_makeflags=$$MFLAGS; \ else \ case $$MAKEFLAGS in \ *\\[\ \ ]*) \ bs=\\; \ sane_makeflags=`printf '%s\n' "$$MAKEFLAGS" \ | sed "s/$$bs$$bs[$$bs $$bs ]*//g"`;; \ esac; \ fi; \ skip_next=no; \ strip_trailopt () \ { \ flg=`printf '%s\n' "$$flg" | sed "s/$$1.*$$//"`; \ }; \ for flg in $$sane_makeflags; do \ test $$skip_next = yes && { skip_next=no; continue; }; \ case $$flg in \ *=*|--*) continue;; \ -*I) strip_trailopt 'I'; skip_next=yes;; \ -*I?*) strip_trailopt 'I';; \ -*O) strip_trailopt 'O'; skip_next=yes;; \ -*O?*) strip_trailopt 'O';; \ -*l) strip_trailopt 'l'; skip_next=yes;; \ -*l?*) strip_trailopt 'l';; \ -[dEDm]) skip_next=yes;; \ -[JT]) skip_next=yes;; \ esac; \ case $$flg in \ *$$target_option*) has_opt=yes; break;; \ esac; \ done; \ test $$has_opt = yes am__make_dryrun = (target_option=n; $(am__make_running_with_option)) am__make_keepgoing = (target_option=k; $(am__make_running_with_option)) pkgdatadir = $(datadir)/@PACKAGE@ pkgincludedir = $(includedir)/@PACKAGE@ pkglibdir = $(libdir)/@PACKAGE@ pkglibexecdir = $(libexecdir)/@PACKAGE@ am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd install_sh_DATA = $(install_sh) -c -m 644 install_sh_PROGRAM = $(install_sh) -c install_sh_SCRIPT = $(install_sh) -c INSTALL_HEADER = $(INSTALL_DATA) transform = $(program_transform_name) NORMAL_INSTALL = : PRE_INSTALL = : POST_INSTALL = : NORMAL_UNINSTALL = : PRE_UNINSTALL = : POST_UNINSTALL = : build_triplet = @build@ host_triplet = @host@ @FRAMEWORK_SECURITY_TRUE@am__append_1 = -framework Security -framework CoreFoundation @versionscript_TRUE@am__append_2 = $(LDFLAGS_VERSION_SCRIPT)$(srcdir)/version-script.map bin_PROGRAMS = hxtool$(EXEEXT) check_PROGRAMS = $(am__EXEEXT_1) test_soft_pkcs11$(EXEEXT) TESTS = $(SCRIPT_TESTS) $(am__EXEEXT_1) subdir = lib/hx509 ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 am__aclocal_m4_deps = $(top_srcdir)/cf/aix.m4 \ $(top_srcdir)/cf/auth-modules.m4 \ $(top_srcdir)/cf/broken-getaddrinfo.m4 \ $(top_srcdir)/cf/broken-glob.m4 \ $(top_srcdir)/cf/broken-realloc.m4 \ $(top_srcdir)/cf/broken-snprintf.m4 $(top_srcdir)/cf/broken.m4 \ $(top_srcdir)/cf/broken2.m4 $(top_srcdir)/cf/c-attribute.m4 \ $(top_srcdir)/cf/capabilities.m4 \ $(top_srcdir)/cf/check-compile-et.m4 \ $(top_srcdir)/cf/check-getpwnam_r-posix.m4 \ $(top_srcdir)/cf/check-man.m4 \ $(top_srcdir)/cf/check-netinet-ip-and-tcp.m4 \ $(top_srcdir)/cf/check-type-extra.m4 \ $(top_srcdir)/cf/check-var.m4 $(top_srcdir)/cf/crypto.m4 \ $(top_srcdir)/cf/db.m4 $(top_srcdir)/cf/destdirs.m4 \ $(top_srcdir)/cf/dispatch.m4 $(top_srcdir)/cf/dlopen.m4 \ $(top_srcdir)/cf/find-func-no-libs.m4 \ $(top_srcdir)/cf/find-func-no-libs2.m4 \ $(top_srcdir)/cf/find-func.m4 \ $(top_srcdir)/cf/find-if-not-broken.m4 \ $(top_srcdir)/cf/framework-security.m4 \ $(top_srcdir)/cf/have-struct-field.m4 \ $(top_srcdir)/cf/have-type.m4 $(top_srcdir)/cf/irix.m4 \ $(top_srcdir)/cf/krb-bigendian.m4 \ $(top_srcdir)/cf/krb-func-getlogin.m4 \ $(top_srcdir)/cf/krb-ipv6.m4 $(top_srcdir)/cf/krb-prog-ln-s.m4 \ $(top_srcdir)/cf/krb-prog-perl.m4 \ $(top_srcdir)/cf/krb-readline.m4 \ $(top_srcdir)/cf/krb-struct-spwd.m4 \ $(top_srcdir)/cf/krb-struct-winsize.m4 \ $(top_srcdir)/cf/largefile.m4 $(top_srcdir)/cf/libtool.m4 \ $(top_srcdir)/cf/ltoptions.m4 $(top_srcdir)/cf/ltsugar.m4 \ $(top_srcdir)/cf/ltversion.m4 $(top_srcdir)/cf/lt~obsolete.m4 \ $(top_srcdir)/cf/mips-abi.m4 $(top_srcdir)/cf/misc.m4 \ $(top_srcdir)/cf/need-proto.m4 $(top_srcdir)/cf/osfc2.m4 \ $(top_srcdir)/cf/otp.m4 $(top_srcdir)/cf/pkg.m4 \ $(top_srcdir)/cf/proto-compat.m4 $(top_srcdir)/cf/pthreads.m4 \ $(top_srcdir)/cf/resolv.m4 $(top_srcdir)/cf/retsigtype.m4 \ $(top_srcdir)/cf/roken-frag.m4 \ $(top_srcdir)/cf/socket-wrapper.m4 $(top_srcdir)/cf/sunos.m4 \ $(top_srcdir)/cf/telnet.m4 $(top_srcdir)/cf/test-package.m4 \ $(top_srcdir)/cf/version-script.m4 $(top_srcdir)/cf/wflags.m4 \ $(top_srcdir)/cf/win32.m4 $(top_srcdir)/cf/with-all.m4 \ $(top_srcdir)/acinclude.m4 $(top_srcdir)/configure.ac am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \ $(ACLOCAL_M4) DIST_COMMON = $(srcdir)/Makefile.am $(dist_include_HEADERS) \ $(noinst_HEADERS) $(am__DIST_COMMON) mkinstalldirs = $(install_sh) -d CONFIG_HEADER = $(top_builddir)/include/config.h CONFIG_CLEAN_FILES = CONFIG_CLEAN_VPATH_FILES = am__vpath_adj_setup = srcdirstrip=`echo "$(srcdir)" | sed 's|.|.|g'`; am__vpath_adj = case $$p in \ $(srcdir)/*) f=`echo "$$p" | sed "s|^$$srcdirstrip/||"`;; \ *) f=$$p;; \ esac; am__strip_dir = f=`echo $$p | sed -e 's|^.*/||'`; am__install_max = 40 am__nobase_strip_setup = \ srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*|]/\\\\&/g'` am__nobase_strip = \ for p in $$list; do echo "$$p"; done | sed -e "s|$$srcdirstrip/||" am__nobase_list = $(am__nobase_strip_setup); \ for p in $$list; do echo "$$p $$p"; done | \ sed "s| $$srcdirstrip/| |;"' / .*\//!s/ .*/ ./; s,\( .*\)/[^/]*$$,\1,' | \ $(AWK) 'BEGIN { files["."] = "" } { files[$$2] = files[$$2] " " $$1; \ if (++n[$$2] == $(am__install_max)) \ { print $$2, files[$$2]; n[$$2] = 0; files[$$2] = "" } } \ END { for (dir in files) print dir, files[dir] }' am__base_list = \ sed '$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;s/\n/ /g' | \ sed '$$!N;$$!N;$$!N;$$!N;s/\n/ /g' am__uninstall_files_from_dir = { \ test -z "$$files" \ || { test ! -d "$$dir" && test ! -f "$$dir" && test ! -r "$$dir"; } \ || { echo " ( cd '$$dir' && rm -f" $$files ")"; \ $(am__cd) "$$dir" && rm -f $$files; }; \ } am__installdirs = "$(DESTDIR)$(libdir)" "$(DESTDIR)$(bindir)" \ "$(DESTDIR)$(includedir)" "$(DESTDIR)$(includedir)" LTLIBRARIES = $(lib_LTLIBRARIES) am__DEPENDENCIES_1 = dist_libhx509_la_OBJECTS = ca.lo cert.lo cms.lo collector.lo crypto.lo \ crypto-ec.lo doxygen.lo error.lo env.lo file.lo sel.lo \ sel-gram.lo sel-lex.lo keyset.lo ks_dir.lo ks_file.lo \ ks_mem.lo ks_null.lo ks_p11.lo ks_p12.lo ks_keychain.lo \ lock.lo name.lo peer.lo print.lo softp11.lo req.lo revoke.lo am__objects_1 = asn1_OCSPBasicOCSPResponse.lo asn1_OCSPCertID.lo \ asn1_OCSPCertStatus.lo asn1_OCSPInnerRequest.lo \ asn1_OCSPKeyHash.lo asn1_OCSPRequest.lo \ asn1_OCSPResponderID.lo asn1_OCSPResponse.lo \ asn1_OCSPResponseBytes.lo asn1_OCSPResponseData.lo \ asn1_OCSPResponseStatus.lo asn1_OCSPSignature.lo \ asn1_OCSPSingleResponse.lo asn1_OCSPTBSRequest.lo \ asn1_OCSPVersion.lo asn1_id_pkix_ocsp.lo \ asn1_id_pkix_ocsp_basic.lo asn1_id_pkix_ocsp_nonce.lo am__objects_2 = asn1_CertificationRequestInfo.lo \ asn1_CertificationRequest.lo am__objects_3 = $(am__objects_1) $(am__objects_2) hx509_err.lo nodist_libhx509_la_OBJECTS = $(am__objects_3) libhx509_la_OBJECTS = $(dist_libhx509_la_OBJECTS) \ $(nodist_libhx509_la_OBJECTS) AM_V_lt = $(am__v_lt_@AM_V@) am__v_lt_ = $(am__v_lt_@AM_DEFAULT_V@) am__v_lt_0 = --silent am__v_lt_1 = libhx509_la_LINK = $(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) \ $(LIBTOOLFLAGS) --mode=link $(CCLD) $(AM_CFLAGS) $(CFLAGS) \ $(libhx509_la_LDFLAGS) $(LDFLAGS) -o $@ am__EXEEXT_1 = test_name$(EXEEXT) test_expr$(EXEEXT) PROGRAMS = $(bin_PROGRAMS) dist_hxtool_OBJECTS = hxtool.$(OBJEXT) nodist_hxtool_OBJECTS = hxtool-commands.$(OBJEXT) hxtool_OBJECTS = $(dist_hxtool_OBJECTS) $(nodist_hxtool_OBJECTS) hxtool_DEPENDENCIES = libhx509.la $(top_builddir)/lib/asn1/libasn1.la \ $(am__DEPENDENCIES_1) $(am__DEPENDENCIES_1) \ $(top_builddir)/lib/sl/libsl.la test_expr_SOURCES = test_expr.c test_expr_OBJECTS = test_expr.$(OBJEXT) test_expr_DEPENDENCIES = libhx509.la $(am__DEPENDENCIES_1) \ $(top_builddir)/lib/asn1/libasn1.la test_name_SOURCES = test_name.c test_name_OBJECTS = test_name.$(OBJEXT) test_name_DEPENDENCIES = libhx509.la $(am__DEPENDENCIES_1) \ $(top_builddir)/lib/asn1/libasn1.la test_soft_pkcs11_SOURCES = test_soft_pkcs11.c test_soft_pkcs11_OBJECTS = test_soft_pkcs11.$(OBJEXT) test_soft_pkcs11_DEPENDENCIES = libhx509.la \ $(top_builddir)/lib/asn1/libasn1.la AM_V_P = $(am__v_P_@AM_V@) am__v_P_ = $(am__v_P_@AM_DEFAULT_V@) am__v_P_0 = false am__v_P_1 = : AM_V_GEN = $(am__v_GEN_@AM_V@) am__v_GEN_ = $(am__v_GEN_@AM_DEFAULT_V@) am__v_GEN_0 = @echo " GEN " $@; am__v_GEN_1 = AM_V_at = $(am__v_at_@AM_V@) am__v_at_ = $(am__v_at_@AM_DEFAULT_V@) am__v_at_0 = @ am__v_at_1 = depcomp = $(SHELL) $(top_srcdir)/depcomp am__depfiles_maybe = depfiles am__mv = mv -f COMPILE = $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) \ $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) LTCOMPILE = $(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) \ $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) \ $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) \ $(AM_CFLAGS) $(CFLAGS) AM_V_CC = $(am__v_CC_@AM_V@) am__v_CC_ = $(am__v_CC_@AM_DEFAULT_V@) am__v_CC_0 = @echo " CC " $@; am__v_CC_1 = CCLD = $(CC) LINK = $(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) \ $(LIBTOOLFLAGS) --mode=link $(CCLD) $(AM_CFLAGS) $(CFLAGS) \ $(AM_LDFLAGS) $(LDFLAGS) -o $@ AM_V_CCLD = $(am__v_CCLD_@AM_V@) am__v_CCLD_ = $(am__v_CCLD_@AM_DEFAULT_V@) am__v_CCLD_0 = @echo " CCLD " $@; am__v_CCLD_1 = @MAINTAINER_MODE_FALSE@am__skiplex = test -f $@ || LEXCOMPILE = $(LEX) $(AM_LFLAGS) $(LFLAGS) LTLEXCOMPILE = $(LIBTOOL) $(AM_V_lt) $(AM_LIBTOOLFLAGS) \ $(LIBTOOLFLAGS) --mode=compile $(LEX) $(AM_LFLAGS) $(LFLAGS) AM_V_LEX = $(am__v_LEX_@AM_V@) am__v_LEX_ = $(am__v_LEX_@AM_DEFAULT_V@) am__v_LEX_0 = @echo " LEX " $@; am__v_LEX_1 = YLWRAP = $(top_srcdir)/ylwrap @MAINTAINER_MODE_FALSE@am__skipyacc = test -f $@ || am__yacc_c2h = sed -e s/cc$$/hh/ -e s/cpp$$/hpp/ -e s/cxx$$/hxx/ \ -e s/c++$$/h++/ -e s/c$$/h/ YACCCOMPILE = $(YACC) $(AM_YFLAGS) $(YFLAGS) LTYACCCOMPILE = $(LIBTOOL) $(AM_V_lt) $(AM_LIBTOOLFLAGS) \ $(LIBTOOLFLAGS) --mode=compile $(YACC) $(AM_YFLAGS) $(YFLAGS) AM_V_YACC = $(am__v_YACC_@AM_V@) am__v_YACC_ = $(am__v_YACC_@AM_DEFAULT_V@) am__v_YACC_0 = @echo " YACC " $@; am__v_YACC_1 = SOURCES = $(dist_libhx509_la_SOURCES) $(nodist_libhx509_la_SOURCES) \ $(dist_hxtool_SOURCES) $(nodist_hxtool_SOURCES) test_expr.c \ test_name.c test_soft_pkcs11.c DIST_SOURCES = $(dist_libhx509_la_SOURCES) $(dist_hxtool_SOURCES) \ test_expr.c test_name.c test_soft_pkcs11.c am__can_run_installinfo = \ case $$AM_UPDATE_INFO_DIR in \ n|no|NO) false;; \ *) (install-info --version) >/dev/null 2>&1;; \ esac HEADERS = $(dist_include_HEADERS) $(nodist_include_HEADERS) \ $(noinst_HEADERS) am__tagged_files = $(HEADERS) $(SOURCES) $(TAGS_FILES) $(LISP) # Read a list of newline-separated strings from the standard input, # and print each of them once, without duplicates. Input order is # *not* preserved. am__uniquify_input = $(AWK) '\ BEGIN { nonempty = 0; } \ { items[$$0] = 1; nonempty = 1; } \ END { if (nonempty) { for (i in items) print i; }; } \ ' # Make sure the list of sources is unique. This is necessary because, # e.g., the same source file might be shared among _SOURCES variables # for different programs/libraries. am__define_uniq_tagged_files = \ list='$(am__tagged_files)'; \ unique=`for i in $$list; do \ if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ done | $(am__uniquify_input)` ETAGS = etags CTAGS = ctags am__tty_colors_dummy = \ mgn= red= grn= lgn= blu= brg= std=; \ am__color_tests=no am__tty_colors = { \ $(am__tty_colors_dummy); \ if test "X$(AM_COLOR_TESTS)" = Xno; then \ am__color_tests=no; \ elif test "X$(AM_COLOR_TESTS)" = Xalways; then \ am__color_tests=yes; \ elif test "X$$TERM" != Xdumb && { test -t 1; } 2>/dev/null; then \ am__color_tests=yes; \ fi; \ if test $$am__color_tests = yes; then \ red=''; \ grn=''; \ lgn=''; \ blu=''; \ mgn=''; \ brg=''; \ std=''; \ fi; \ } am__recheck_rx = ^[ ]*:recheck:[ ]* am__global_test_result_rx = ^[ ]*:global-test-result:[ ]* am__copy_in_global_log_rx = ^[ ]*:copy-in-global-log:[ ]* # A command that, given a newline-separated list of test names on the # standard input, print the name of the tests that are to be re-run # upon "make recheck". am__list_recheck_tests = $(AWK) '{ \ recheck = 1; \ while ((rc = (getline line < ($$0 ".trs"))) != 0) \ { \ if (rc < 0) \ { \ if ((getline line2 < ($$0 ".log")) < 0) \ recheck = 0; \ break; \ } \ else if (line ~ /$(am__recheck_rx)[nN][Oo]/) \ { \ recheck = 0; \ break; \ } \ else if (line ~ /$(am__recheck_rx)[yY][eE][sS]/) \ { \ break; \ } \ }; \ if (recheck) \ print $$0; \ close ($$0 ".trs"); \ close ($$0 ".log"); \ }' # A command that, given a newline-separated list of test names on the # standard input, create the global log from their .trs and .log files. am__create_global_log = $(AWK) ' \ function fatal(msg) \ { \ print "fatal: making $@: " msg | "cat >&2"; \ exit 1; \ } \ function rst_section(header) \ { \ print header; \ len = length(header); \ for (i = 1; i <= len; i = i + 1) \ printf "="; \ printf "\n\n"; \ } \ { \ copy_in_global_log = 1; \ global_test_result = "RUN"; \ while ((rc = (getline line < ($$0 ".trs"))) != 0) \ { \ if (rc < 0) \ fatal("failed to read from " $$0 ".trs"); \ if (line ~ /$(am__global_test_result_rx)/) \ { \ sub("$(am__global_test_result_rx)", "", line); \ sub("[ ]*$$", "", line); \ global_test_result = line; \ } \ else if (line ~ /$(am__copy_in_global_log_rx)[nN][oO]/) \ copy_in_global_log = 0; \ }; \ if (copy_in_global_log) \ { \ rst_section(global_test_result ": " $$0); \ while ((rc = (getline line < ($$0 ".log"))) != 0) \ { \ if (rc < 0) \ fatal("failed to read from " $$0 ".log"); \ print line; \ }; \ printf "\n"; \ }; \ close ($$0 ".trs"); \ close ($$0 ".log"); \ }' # Restructured Text title. am__rst_title = { sed 's/.*/ & /;h;s/./=/g;p;x;s/ *$$//;p;g' && echo; } # Solaris 10 'make', and several other traditional 'make' implementations, # pass "-e" to $(SHELL), and POSIX 2008 even requires this. Work around it # by disabling -e (using the XSI extension "set +e") if it's set. am__sh_e_setup = case $$- in *e*) set +e;; esac # Default flags passed to test drivers. am__common_driver_flags = \ --color-tests "$$am__color_tests" \ --enable-hard-errors "$$am__enable_hard_errors" \ --expect-failure "$$am__expect_failure" # To be inserted before the command running the test. Creates the # directory for the log if needed. Stores in $dir the directory # containing $f, in $tst the test, in $log the log. Executes the # developer- defined test setup AM_TESTS_ENVIRONMENT (if any), and # passes TESTS_ENVIRONMENT. Set up options for the wrapper that # will run the test scripts (or their associated LOG_COMPILER, if # thy have one). am__check_pre = \ $(am__sh_e_setup); \ $(am__vpath_adj_setup) $(am__vpath_adj) \ $(am__tty_colors); \ srcdir=$(srcdir); export srcdir; \ case "$@" in \ */*) am__odir=`echo "./$@" | sed 's|/[^/]*$$||'`;; \ *) am__odir=.;; \ esac; \ test "x$$am__odir" = x"." || test -d "$$am__odir" \ || $(MKDIR_P) "$$am__odir" || exit $$?; \ if test -f "./$$f"; then dir=./; \ elif test -f "$$f"; then dir=; \ else dir="$(srcdir)/"; fi; \ tst=$$dir$$f; log='$@'; \ if test -n '$(DISABLE_HARD_ERRORS)'; then \ am__enable_hard_errors=no; \ else \ am__enable_hard_errors=yes; \ fi; \ case " $(XFAIL_TESTS) " in \ *[\ \ ]$$f[\ \ ]* | *[\ \ ]$$dir$$f[\ \ ]*) \ am__expect_failure=yes;; \ *) \ am__expect_failure=no;; \ esac; \ $(AM_TESTS_ENVIRONMENT) $(TESTS_ENVIRONMENT) # A shell command to get the names of the tests scripts with any registered # extension removed (i.e., equivalently, the names of the test logs, with # the '.log' extension removed). The result is saved in the shell variable # '$bases'. This honors runtime overriding of TESTS and TEST_LOGS. Sadly, # we cannot use something simpler, involving e.g., "$(TEST_LOGS:.log=)", # since that might cause problem with VPATH rewrites for suffix-less tests. # See also 'test-harness-vpath-rewrite.sh' and 'test-trs-basic.sh'. am__set_TESTS_bases = \ bases='$(TEST_LOGS)'; \ bases=`for i in $$bases; do echo $$i; done | sed 's/\.log$$//'`; \ bases=`echo $$bases` RECHECK_LOGS = $(TEST_LOGS) AM_RECURSIVE_TARGETS = check recheck TEST_SUITE_LOG = test-suite.log TEST_EXTENSIONS = @EXEEXT@ .test LOG_DRIVER = $(SHELL) $(top_srcdir)/test-driver LOG_COMPILE = $(LOG_COMPILER) $(AM_LOG_FLAGS) $(LOG_FLAGS) am__set_b = \ case '$@' in \ */*) \ case '$*' in \ */*) b='$*';; \ *) b=`echo '$@' | sed 's/\.log$$//'`; \ esac;; \ *) \ b='$*';; \ esac am__test_logs1 = $(TESTS:=.log) am__test_logs2 = $(am__test_logs1:@EXEEXT@.log=.log) TEST_LOGS = $(am__test_logs2:.test.log=.log) TEST_LOG_DRIVER = $(SHELL) $(top_srcdir)/test-driver TEST_LOG_COMPILE = $(TEST_LOG_COMPILER) $(AM_TEST_LOG_FLAGS) \ $(TEST_LOG_FLAGS) am__DIST_COMMON = $(srcdir)/Makefile.in \ $(top_srcdir)/Makefile.am.common \ $(top_srcdir)/cf/Makefile.am.common $(top_srcdir)/depcomp \ $(top_srcdir)/test-driver $(top_srcdir)/ylwrap ChangeLog TODO \ sel-gram.c sel-gram.h sel-lex.c DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST) ACLOCAL = @ACLOCAL@ AIX_EXTRA_KAFS = @AIX_EXTRA_KAFS@ AMTAR = @AMTAR@ AM_DEFAULT_VERBOSITY = @AM_DEFAULT_VERBOSITY@ AR = @AR@ AS = @AS@ ASN1_COMPILE = @ASN1_COMPILE@ ASN1_COMPILE_DEP = @ASN1_COMPILE_DEP@ AUTOCONF = @AUTOCONF@ AUTOHEADER = @AUTOHEADER@ AUTOMAKE = @AUTOMAKE@ AWK = @AWK@ CANONICAL_HOST = @CANONICAL_HOST@ CAPNG_CFLAGS = @CAPNG_CFLAGS@ CAPNG_LIBS = @CAPNG_LIBS@ CATMAN = @CATMAN@ CATMANEXT = @CATMANEXT@ CC = @CC@ CCDEPMODE = @CCDEPMODE@ CFLAGS = @CFLAGS@ COMPILE_ET = @COMPILE_ET@ CPP = @CPP@ CPPFLAGS = @CPPFLAGS@ CYGPATH_W = @CYGPATH_W@ DB1LIB = @DB1LIB@ DB3LIB = @DB3LIB@ DBHEADER = @DBHEADER@ DEFS = @DEFS@ DEPDIR = @DEPDIR@ DIR_com_err = @DIR_com_err@ DIR_hdbdir = @DIR_hdbdir@ DIR_roken = @DIR_roken@ DLLTOOL = @DLLTOOL@ DSYMUTIL = @DSYMUTIL@ DUMPBIN = @DUMPBIN@ ECHO_C = @ECHO_C@ ECHO_N = @ECHO_N@ ECHO_T = @ECHO_T@ EGREP = @EGREP@ ENABLE_AFS_STRING_TO_KEY = @ENABLE_AFS_STRING_TO_KEY@ EXEEXT = @EXEEXT@ FGREP = @FGREP@ GCD_MIG = @GCD_MIG@ GREP = @GREP@ GROFF = @GROFF@ INCLUDES_roken = @INCLUDES_roken@ INCLUDE_libedit = @INCLUDE_libedit@ INCLUDE_libintl = @INCLUDE_libintl@ INCLUDE_openldap = @INCLUDE_openldap@ INCLUDE_openssl_crypto = @INCLUDE_openssl_crypto@ INCLUDE_readline = @INCLUDE_readline@ INCLUDE_sqlite3 = @INCLUDE_sqlite3@ INSTALL = @INSTALL@ INSTALL_DATA = @INSTALL_DATA@ INSTALL_PROGRAM = @INSTALL_PROGRAM@ INSTALL_SCRIPT = @INSTALL_SCRIPT@ INSTALL_STRIP_PROGRAM = @INSTALL_STRIP_PROGRAM@ LD = @LD@ LDFLAGS = @LDFLAGS@ LDFLAGS_VERSION_SCRIPT = @LDFLAGS_VERSION_SCRIPT@ LEX = @LEX@ LEXLIB = @LEXLIB@ LEX_OUTPUT_ROOT = @LEX_OUTPUT_ROOT@ LIBADD_roken = @LIBADD_roken@ LIBOBJS = @LIBOBJS@ LIBS = @LIBS@ LIBTOOL = @LIBTOOL@ LIB_AUTH_SUBDIRS = @LIB_AUTH_SUBDIRS@ LIB_bswap16 = @LIB_bswap16@ LIB_bswap32 = @LIB_bswap32@ LIB_bswap64 = @LIB_bswap64@ LIB_com_err = @LIB_com_err@ LIB_com_err_a = @LIB_com_err_a@ LIB_com_err_so = @LIB_com_err_so@ LIB_crypt = @LIB_crypt@ LIB_db_create = @LIB_db_create@ LIB_dbm_firstkey = @LIB_dbm_firstkey@ LIB_dbopen = @LIB_dbopen@ LIB_dispatch_async_f = @LIB_dispatch_async_f@ LIB_dladdr = @LIB_dladdr@ LIB_dlopen = @LIB_dlopen@ LIB_dn_expand = @LIB_dn_expand@ LIB_dns_search = @LIB_dns_search@ LIB_door_create = @LIB_door_create@ LIB_freeaddrinfo = @LIB_freeaddrinfo@ LIB_gai_strerror = @LIB_gai_strerror@ LIB_getaddrinfo = @LIB_getaddrinfo@ LIB_gethostbyname = @LIB_gethostbyname@ LIB_gethostbyname2 = @LIB_gethostbyname2@ LIB_getnameinfo = @LIB_getnameinfo@ LIB_getpwnam_r = @LIB_getpwnam_r@ LIB_getsockopt = @LIB_getsockopt@ LIB_hcrypto = @LIB_hcrypto@ LIB_hcrypto_a = @LIB_hcrypto_a@ LIB_hcrypto_appl = @LIB_hcrypto_appl@ LIB_hcrypto_so = @LIB_hcrypto_so@ LIB_hstrerror = @LIB_hstrerror@ LIB_kdb = @LIB_kdb@ LIB_libedit = @LIB_libedit@ LIB_libintl = @LIB_libintl@ LIB_loadquery = @LIB_loadquery@ LIB_logout = @LIB_logout@ LIB_logwtmp = @LIB_logwtmp@ LIB_openldap = @LIB_openldap@ LIB_openpty = @LIB_openpty@ LIB_openssl_crypto = @LIB_openssl_crypto@ LIB_otp = @LIB_otp@ LIB_pidfile = @LIB_pidfile@ LIB_readline = @LIB_readline@ LIB_res_ndestroy = @LIB_res_ndestroy@ LIB_res_nsearch = @LIB_res_nsearch@ LIB_res_search = @LIB_res_search@ LIB_roken = @LIB_roken@ LIB_security = @LIB_security@ LIB_setsockopt = @LIB_setsockopt@ LIB_socket = @LIB_socket@ LIB_sqlite3 = @LIB_sqlite3@ LIB_syslog = @LIB_syslog@ LIB_tgetent = @LIB_tgetent@ LIPO = @LIPO@ LMDBLIB = @LMDBLIB@ LN_S = @LN_S@ LTLIBOBJS = @LTLIBOBJS@ LT_SYS_LIBRARY_PATH = @LT_SYS_LIBRARY_PATH@ MAINT = @MAINT@ MAKEINFO = @MAKEINFO@ MANIFEST_TOOL = @MANIFEST_TOOL@ MKDIR_P = @MKDIR_P@ NDBMLIB = @NDBMLIB@ NM = @NM@ NMEDIT = @NMEDIT@ NO_AFS = @NO_AFS@ NROFF = @NROFF@ OBJDUMP = @OBJDUMP@ OBJEXT = @OBJEXT@ OTOOL = @OTOOL@ OTOOL64 = @OTOOL64@ PACKAGE = @PACKAGE@ PACKAGE_BUGREPORT = @PACKAGE_BUGREPORT@ PACKAGE_NAME = @PACKAGE_NAME@ PACKAGE_STRING = @PACKAGE_STRING@ PACKAGE_TARNAME = @PACKAGE_TARNAME@ PACKAGE_URL = @PACKAGE_URL@ PACKAGE_VERSION = @PACKAGE_VERSION@ PATH_SEPARATOR = @PATH_SEPARATOR@ PERL = @PERL@ PKG_CONFIG = @PKG_CONFIG@ PTHREAD_CFLAGS = @PTHREAD_CFLAGS@ PTHREAD_LDADD = @PTHREAD_LDADD@ PTHREAD_LIBADD = @PTHREAD_LIBADD@ RANLIB = @RANLIB@ SED = @SED@ SET_MAKE = @SET_MAKE@ SHELL = @SHELL@ SLC = @SLC@ SLC_DEP = @SLC_DEP@ STRIP = @STRIP@ VERSION = @VERSION@ VERSIONING = @VERSIONING@ WFLAGS = @WFLAGS@ WFLAGS_LITE = @WFLAGS_LITE@ YACC = @YACC@ YFLAGS = @YFLAGS@ abs_builddir = @abs_builddir@ abs_srcdir = @abs_srcdir@ abs_top_builddir = @abs_top_builddir@ abs_top_srcdir = @abs_top_srcdir@ ac_ct_AR = @ac_ct_AR@ ac_ct_CC = @ac_ct_CC@ ac_ct_DUMPBIN = @ac_ct_DUMPBIN@ am__include = @am__include@ am__leading_dot = @am__leading_dot@ am__quote = @am__quote@ am__tar = @am__tar@ am__untar = @am__untar@ bindir = @bindir@ build = @build@ build_alias = @build_alias@ build_cpu = @build_cpu@ build_os = @build_os@ build_vendor = @build_vendor@ builddir = @builddir@ datadir = @datadir@ datarootdir = @datarootdir@ db_type = @db_type@ db_type_preference = @db_type_preference@ docdir = @docdir@ dpagaix_cflags = @dpagaix_cflags@ dpagaix_ldadd = @dpagaix_ldadd@ dpagaix_ldflags = @dpagaix_ldflags@ dvidir = @dvidir@ exec_prefix = @exec_prefix@ host = @host@ host_alias = @host_alias@ host_cpu = @host_cpu@ host_os = @host_os@ host_vendor = @host_vendor@ htmldir = @htmldir@ includedir = @includedir@ infodir = @infodir@ install_sh = @install_sh@ libdir = @libdir@ libexecdir = @libexecdir@ localedir = @localedir@ localstatedir = @localstatedir@ mandir = @mandir@ mkdir_p = @mkdir_p@ oldincludedir = @oldincludedir@ pdfdir = @pdfdir@ prefix = @prefix@ program_transform_name = @program_transform_name@ psdir = @psdir@ sbindir = @sbindir@ sharedstatedir = @sharedstatedir@ srcdir = @srcdir@ subdirs = @subdirs@ sysconfdir = @sysconfdir@ target_alias = @target_alias@ top_build_prefix = @top_build_prefix@ top_builddir = @top_builddir@ top_srcdir = @top_srcdir@ SUFFIXES = .et .h .pc.in .pc .x .z .hx .1 .3 .5 .7 .8 .cat1 .cat3 \ .cat5 .cat7 .cat8 DEFAULT_INCLUDES = -I. -I$(srcdir) -I$(top_builddir)/include -I$(top_srcdir)/include AM_CPPFLAGS = $(INCLUDES_roken) $(INCLUDE_openssl_crypto) @do_roken_rename_TRUE@ROKEN_RENAME = -DROKEN_RENAME AM_CFLAGS = $(WFLAGS) CP = cp buildinclude = $(top_builddir)/include LIB_XauReadAuth = @LIB_XauReadAuth@ LIB_el_init = @LIB_el_init@ LIB_getattr = @LIB_getattr@ LIB_getpwent_r = @LIB_getpwent_r@ LIB_odm_initialize = @LIB_odm_initialize@ LIB_setpcred = @LIB_setpcred@ INCLUDE_krb4 = @INCLUDE_krb4@ LIB_krb4 = @LIB_krb4@ libexec_heimdaldir = $(libexecdir)/heimdal NROFF_MAN = groff -mandoc -Tascii @NO_AFS_FALSE@LIB_kafs = $(top_builddir)/lib/kafs/libkafs.la $(AIX_EXTRA_KAFS) @NO_AFS_TRUE@LIB_kafs = @KRB5_TRUE@LIB_krb5 = $(top_builddir)/lib/krb5/libkrb5.la \ @KRB5_TRUE@ $(top_builddir)/lib/asn1/libasn1.la @KRB5_TRUE@LIB_gssapi = $(top_builddir)/lib/gssapi/libgssapi.la LIB_heimbase = $(top_builddir)/lib/base/libheimbase.la @DCE_TRUE@LIB_kdfs = $(top_builddir)/lib/kdfs/libkdfs.la #silent-rules heim_verbose = $(heim_verbose_$(V)) heim_verbose_ = $(heim_verbose_$(AM_DEFAULT_VERBOSITY)) heim_verbose_0 = @echo " GEN "$@; lib_LTLIBRARIES = libhx509.la libhx509_la_LDFLAGS = -version-info 5:0:0 $(am__append_1) \ $(am__append_2) BUILT_SOURCES = \ sel-gram.h \ $(gen_files_ocsp:.x=.c) \ $(gen_files_pkcs10:.x=.c) \ hx509_err.c \ hx509_err.h gen_files_ocsp = \ asn1_OCSPBasicOCSPResponse.x \ asn1_OCSPCertID.x \ asn1_OCSPCertStatus.x \ asn1_OCSPInnerRequest.x \ asn1_OCSPKeyHash.x \ asn1_OCSPRequest.x \ asn1_OCSPResponderID.x \ asn1_OCSPResponse.x \ asn1_OCSPResponseBytes.x \ asn1_OCSPResponseData.x \ asn1_OCSPResponseStatus.x \ asn1_OCSPSignature.x \ asn1_OCSPSingleResponse.x \ asn1_OCSPTBSRequest.x \ asn1_OCSPVersion.x \ asn1_id_pkix_ocsp.x \ asn1_id_pkix_ocsp_basic.x \ asn1_id_pkix_ocsp_nonce.x gen_files_pkcs10 = \ asn1_CertificationRequestInfo.x \ asn1_CertificationRequest.x gen_files_crmf = \ asn1_CRMFRDNSequence.x \ asn1_CertReqMessages.x \ asn1_CertReqMsg.x \ asn1_CertRequest.x \ asn1_CertTemplate.x \ asn1_Controls.x \ asn1_PBMParameter.x \ asn1_PKMACValue.x \ asn1_POPOPrivKey.x \ asn1_POPOSigningKey.x \ asn1_POPOSigningKeyInput.x \ asn1_ProofOfPossession.x \ asn1_SubsequentMessage.x AM_YFLAGS = -d dist_libhx509_la_SOURCES = \ ca.c \ cert.c \ char_map.h \ cms.c \ collector.c \ crypto.c \ crypto-ec.c \ doxygen.c \ error.c \ env.c \ file.c \ hx509.h \ hx_locl.h \ sel.c \ sel.h \ sel-gram.y \ sel-lex.l \ keyset.c \ ks_dir.c \ ks_file.c \ ks_mem.c \ ks_null.c \ ks_p11.c \ ks_p12.c \ ks_keychain.c \ lock.c \ name.c \ peer.c \ print.c \ softp11.c \ ref/pkcs11.h \ req.c \ revoke.c libhx509_la_DEPENDENCIES = version-script.map libhx509_la_LIBADD = \ $(LIB_com_err) \ $(LIB_hcrypto) \ $(LIB_openssl_crypto) \ $(top_builddir)/lib/asn1/libasn1.la \ $(top_builddir)/lib/wind/libwind.la \ $(top_builddir)/lib/base/libheimbase.la \ $(LIBADD_roken) \ $(LIB_dlopen) nodist_libhx509_la_SOURCES = $(BUILT_SOURCES) dist_include_HEADERS = hx509.h $(srcdir)/hx509-protos.h noinst_HEADERS = $(srcdir)/hx509-private.h nodist_include_HEADERS = hx509_err.h ocsp_asn1.h pkcs10_asn1.h \ crmf_asn1.h priv_headers = ocsp_asn1-priv.h pkcs10_asn1-priv.h crmf_asn1-priv.h ALL_OBJECTS = $(libhx509_la_OBJECTS) $(hxtool_OBJECTS) HX509_PROTOS = $(srcdir)/hx509-protos.h $(srcdir)/hx509-private.h dist_hxtool_SOURCES = hxtool.c nodist_hxtool_SOURCES = hxtool-commands.c hxtool-commands.h hxtool_LDADD = \ libhx509.la \ $(top_builddir)/lib/asn1/libasn1.la \ $(LIB_hcrypto) \ $(LIB_roken) \ $(top_builddir)/lib/sl/libsl.la CLEANFILES = $(BUILT_SOURCES) sel-gram.c sel-lex.c \ $(gen_files_ocsp) ocsp_asn1_files ocsp_asn1{,-priv}.h* \ ocsp_asn1-template.[chx]* \ $(gen_files_pkcs10) pkcs10_asn1_files pkcs10_asn1{,-priv}.h* \ pkcs10_asn1-template.[chx]* \ $(gen_files_crmf) crmf_asn1_files crmf_asn1{,-priv}.h* \ crmf_asn1-template.[chx]* \ $(TESTS) \ hxtool-commands.c hxtool-commands.h *.tmp \ request.out \ out.pem out2.pem \ sd sd.pem \ sd.data sd.data.out \ ev.data ev.data.out \ cert-null.pem cert-sub-ca2.pem \ cert-ee.pem cert-ca.pem \ cert-sub-ee.pem cert-sub-ca.pem \ cert-proxy.der cert-ca.der cert-ee.der pkcs10-request.der \ wca.pem wuser.pem wdc.pem wcrl.crl \ random-data statfile crl.crl \ test p11dbg.log pkcs11.cfg \ test-rc-file.rc # # regression tests # check_SCRIPTS = $(SCRIPT_TESTS) LDADD = libhx509.la test_soft_pkcs11_LDADD = libhx509.la $(top_builddir)/lib/asn1/libasn1.la test_name_LDADD = libhx509.la $(LIB_roken) $(top_builddir)/lib/asn1/libasn1.la test_expr_LDADD = libhx509.la $(LIB_roken) $(top_builddir)/lib/asn1/libasn1.la PROGRAM_TESTS = \ test_name \ test_expr SCRIPT_TESTS = \ test_ca \ test_cert \ test_chain \ test_cms \ test_crypto \ test_nist \ test_nist2 \ test_pkcs11 \ test_java_pkcs11 \ test_nist_cert \ test_nist_pkcs12 \ test_req \ test_windows \ test_query do_subst = $(heim_verbose)sed -e 's,[@]srcdir[@],$(srcdir),g' \ -e 's,[@]objdir[@],$(top_builddir)/lib/hx509,g' \ -e 's,[@]egrep[@],$(EGREP),g' EXTRA_DIST = \ NTMakefile \ hxtool-version.rc \ libhx509-exports.def \ version-script.map \ crmf.asn1 \ hx509_err.et \ hxtool-commands.in \ quote.py \ ocsp.asn1 \ ocsp.opt \ pkcs10.asn1 \ pkcs10.opt \ test_ca.in \ test_chain.in \ test_cert.in \ test_cms.in \ test_crypto.in \ test_nist.in \ test_nist2.in \ test_nist_cert.in \ test_nist_pkcs12.in \ test_pkcs11.in \ test_java_pkcs11.in \ test_query.in \ test_req.in \ test_windows.in \ tst-crypto-available1 \ tst-crypto-available2 \ tst-crypto-available3 \ tst-crypto-select \ tst-crypto-select1 \ tst-crypto-select2 \ tst-crypto-select3 \ tst-crypto-select4 \ tst-crypto-select5 \ tst-crypto-select6 \ tst-crypto-select7 \ data/PKITS_data.zip \ data/eccurve.pem \ data/https.crt \ data/https.key \ data/mkcert.sh \ data/nist-result2 \ data/n0ll.pem \ data/secp256r1TestCA.cert.pem \ data/secp256r1TestCA.key.pem \ data/secp256r1TestCA.pem \ data/secp256r2TestClient.cert.pem \ data/secp256r2TestClient.key.pem \ data/secp256r2TestClient.pem \ data/secp256r2TestServer.cert.pem \ data/secp256r2TestServer.key.pem \ data/secp256r2TestServer.pem \ data/bleichenbacher-bad.pem \ data/bleichenbacher-good.pem \ data/bleichenbacher-sf-pad-correct.pem \ data/ca.crt \ data/ca.key \ data/crl1.crl \ data/crl1.der \ data/gen-req.sh \ data/j.pem \ data/kdc.crt \ data/kdc.key \ data/key.der \ data/key2.der \ data/nist-data \ data/nist-data2 \ data/no-proxy-test.crt \ data/no-proxy-test.key \ data/ocsp-req1.der \ data/ocsp-req2.der \ data/ocsp-resp1-2.der \ data/ocsp-resp1-3.der \ data/ocsp-resp1-ca.der \ data/ocsp-resp1-keyhash.der \ data/ocsp-resp1-ocsp-no-cert.der \ data/ocsp-resp1-ocsp.der \ data/ocsp-resp1.der \ data/ocsp-resp2.der \ data/ocsp-responder.crt \ data/ocsp-responder.key \ data/openssl.cnf \ data/pkinit-proxy-chain.crt \ data/pkinit-proxy.crt \ data/pkinit-proxy.key \ data/pkinit-pw.key \ data/pkinit.crt \ data/pkinit.key \ data/pkinit-ec.crt \ data/pkinit-ec.key \ data/proxy-level-test.crt \ data/proxy-level-test.key \ data/proxy-test.crt \ data/proxy-test.key \ data/proxy10-child-test.crt \ data/proxy10-child-test.key \ data/proxy10-child-child-test.crt \ data/proxy10-child-child-test.key \ data/proxy10-test.crt \ data/proxy10-test.key \ data/revoke.crt \ data/revoke.key \ data/sf-class2-root.pem \ data/static-file \ data/sub-ca.crt \ data/sub-ca.key \ data/sub-cert.crt \ data/sub-cert.key \ data/sub-cert.p12 \ data/test-ds-only.crt \ data/test-ds-only.key \ data/test-enveloped-aes-128 \ data/test-enveloped-aes-256 \ data/test-enveloped-des \ data/test-enveloped-des-ede3 \ data/test-enveloped-rc2-128 \ data/test-enveloped-rc2-40 \ data/test-enveloped-rc2-64 \ data/test-ke-only.crt \ data/test-ke-only.key \ data/test-nopw.p12 \ data/test-pw.key \ data/test-signed-data \ data/test-signed-data-noattr \ data/test-signed-data-noattr-nocerts \ data/test-signed-sha-1 \ data/test-signed-sha-256 \ data/test-signed-sha-512 \ data/test.combined.crt \ data/test.crt \ data/test.key \ data/test.p12 \ data/win-u16-in-printablestring.der \ data/yutaka-pad-broken-ca.pem \ data/yutaka-pad-broken-cert.pem \ data/yutaka-pad-ok-ca.pem \ data/yutaka-pad-ok-cert.pem \ data/yutaka-pad.key all: $(BUILT_SOURCES) $(MAKE) $(AM_MAKEFLAGS) all-am .SUFFIXES: .SUFFIXES: .et .h .pc.in .pc .x .z .hx .1 .3 .5 .7 .8 .cat1 .cat3 .cat5 .cat7 .cat8 .c .l .lo .log .o .obj .test .test$(EXEEXT) .trs .y $(srcdir)/Makefile.in: @MAINTAINER_MODE_TRUE@ $(srcdir)/Makefile.am $(top_srcdir)/Makefile.am.common $(top_srcdir)/cf/Makefile.am.common $(am__configure_deps) @for dep in $?; do \ case '$(am__configure_deps)' in \ *$$dep*) \ ( cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh ) \ && { if test -f $@; then exit 0; else break; fi; }; \ exit 1;; \ esac; \ done; \ echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign lib/hx509/Makefile'; \ $(am__cd) $(top_srcdir) && \ $(AUTOMAKE) --foreign lib/hx509/Makefile Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status @case '$?' in \ *config.status*) \ cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh;; \ *) \ echo ' cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe)'; \ cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe);; \ esac; $(top_srcdir)/Makefile.am.common $(top_srcdir)/cf/Makefile.am.common $(am__empty): $(top_builddir)/config.status: $(top_srcdir)/configure $(CONFIG_STATUS_DEPENDENCIES) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(top_srcdir)/configure: @MAINTAINER_MODE_TRUE@ $(am__configure_deps) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(ACLOCAL_M4): @MAINTAINER_MODE_TRUE@ $(am__aclocal_m4_deps) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(am__aclocal_m4_deps): install-libLTLIBRARIES: $(lib_LTLIBRARIES) @$(NORMAL_INSTALL) @list='$(lib_LTLIBRARIES)'; test -n "$(libdir)" || list=; \ list2=; for p in $$list; do \ if test -f $$p; then \ list2="$$list2 $$p"; \ else :; fi; \ done; \ test -z "$$list2" || { \ echo " $(MKDIR_P) '$(DESTDIR)$(libdir)'"; \ $(MKDIR_P) "$(DESTDIR)$(libdir)" || exit 1; \ echo " $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=install $(INSTALL) $(INSTALL_STRIP_FLAG) $$list2 '$(DESTDIR)$(libdir)'"; \ $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=install $(INSTALL) $(INSTALL_STRIP_FLAG) $$list2 "$(DESTDIR)$(libdir)"; \ } uninstall-libLTLIBRARIES: @$(NORMAL_UNINSTALL) @list='$(lib_LTLIBRARIES)'; test -n "$(libdir)" || list=; \ for p in $$list; do \ $(am__strip_dir) \ echo " $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=uninstall rm -f '$(DESTDIR)$(libdir)/$$f'"; \ $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=uninstall rm -f "$(DESTDIR)$(libdir)/$$f"; \ done clean-libLTLIBRARIES: -test -z "$(lib_LTLIBRARIES)" || rm -f $(lib_LTLIBRARIES) @list='$(lib_LTLIBRARIES)'; \ locs=`for p in $$list; do echo $$p; done | \ sed 's|^[^/]*$$|.|; s|/[^/]*$$||; s|$$|/so_locations|' | \ sort -u`; \ test -z "$$locs" || { \ echo rm -f $${locs}; \ rm -f $${locs}; \ } sel-gram.h: sel-gram.c @if test ! -f $@; then rm -f sel-gram.c; else :; fi @if test ! -f $@; then $(MAKE) $(AM_MAKEFLAGS) sel-gram.c; else :; fi libhx509.la: $(libhx509_la_OBJECTS) $(libhx509_la_DEPENDENCIES) $(EXTRA_libhx509_la_DEPENDENCIES) $(AM_V_CCLD)$(libhx509_la_LINK) -rpath $(libdir) $(libhx509_la_OBJECTS) $(libhx509_la_LIBADD) $(LIBS) install-binPROGRAMS: $(bin_PROGRAMS) @$(NORMAL_INSTALL) @list='$(bin_PROGRAMS)'; test -n "$(bindir)" || list=; \ if test -n "$$list"; then \ echo " $(MKDIR_P) '$(DESTDIR)$(bindir)'"; \ $(MKDIR_P) "$(DESTDIR)$(bindir)" || exit 1; \ fi; \ for p in $$list; do echo "$$p $$p"; done | \ sed 's/$(EXEEXT)$$//' | \ while read p p1; do if test -f $$p \ || test -f $$p1 \ ; then echo "$$p"; echo "$$p"; else :; fi; \ done | \ sed -e 'p;s,.*/,,;n;h' \ -e 's|.*|.|' \ -e 'p;x;s,.*/,,;s/$(EXEEXT)$$//;$(transform);s/$$/$(EXEEXT)/' | \ sed 'N;N;N;s,\n, ,g' | \ $(AWK) 'BEGIN { files["."] = ""; dirs["."] = 1 } \ { d=$$3; if (dirs[d] != 1) { print "d", d; dirs[d] = 1 } \ if ($$2 == $$4) files[d] = files[d] " " $$1; \ else { print "f", $$3 "/" $$4, $$1; } } \ END { for (d in files) print "f", d, files[d] }' | \ while read type dir files; do \ if test "$$dir" = .; then dir=; else dir=/$$dir; fi; \ test -z "$$files" || { \ echo " $(INSTALL_PROGRAM_ENV) $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=install $(INSTALL_PROGRAM) $$files '$(DESTDIR)$(bindir)$$dir'"; \ $(INSTALL_PROGRAM_ENV) $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=install $(INSTALL_PROGRAM) $$files "$(DESTDIR)$(bindir)$$dir" || exit $$?; \ } \ ; done uninstall-binPROGRAMS: @$(NORMAL_UNINSTALL) @list='$(bin_PROGRAMS)'; test -n "$(bindir)" || list=; \ files=`for p in $$list; do echo "$$p"; done | \ sed -e 'h;s,^.*/,,;s/$(EXEEXT)$$//;$(transform)' \ -e 's/$$/$(EXEEXT)/' \ `; \ test -n "$$list" || exit 0; \ echo " ( cd '$(DESTDIR)$(bindir)' && rm -f" $$files ")"; \ cd "$(DESTDIR)$(bindir)" && rm -f $$files clean-binPROGRAMS: @list='$(bin_PROGRAMS)'; test -n "$$list" || exit 0; \ echo " rm -f" $$list; \ rm -f $$list || exit $$?; \ test -n "$(EXEEXT)" || exit 0; \ list=`for p in $$list; do echo "$$p"; done | sed 's/$(EXEEXT)$$//'`; \ echo " rm -f" $$list; \ rm -f $$list clean-checkPROGRAMS: @list='$(check_PROGRAMS)'; test -n "$$list" || exit 0; \ echo " rm -f" $$list; \ rm -f $$list || exit $$?; \ test -n "$(EXEEXT)" || exit 0; \ list=`for p in $$list; do echo "$$p"; done | sed 's/$(EXEEXT)$$//'`; \ echo " rm -f" $$list; \ rm -f $$list hxtool$(EXEEXT): $(hxtool_OBJECTS) $(hxtool_DEPENDENCIES) $(EXTRA_hxtool_DEPENDENCIES) @rm -f hxtool$(EXEEXT) $(AM_V_CCLD)$(LINK) $(hxtool_OBJECTS) $(hxtool_LDADD) $(LIBS) test_expr$(EXEEXT): $(test_expr_OBJECTS) $(test_expr_DEPENDENCIES) $(EXTRA_test_expr_DEPENDENCIES) @rm -f test_expr$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_expr_OBJECTS) $(test_expr_LDADD) $(LIBS) test_name$(EXEEXT): $(test_name_OBJECTS) $(test_name_DEPENDENCIES) $(EXTRA_test_name_DEPENDENCIES) @rm -f test_name$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_name_OBJECTS) $(test_name_LDADD) $(LIBS) test_soft_pkcs11$(EXEEXT): $(test_soft_pkcs11_OBJECTS) $(test_soft_pkcs11_DEPENDENCIES) $(EXTRA_test_soft_pkcs11_DEPENDENCIES) @rm -f test_soft_pkcs11$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_soft_pkcs11_OBJECTS) $(test_soft_pkcs11_LDADD) $(LIBS) mostlyclean-compile: -rm -f *.$(OBJEXT) distclean-compile: -rm -f *.tab.c @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/asn1_CertificationRequest.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/asn1_CertificationRequestInfo.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/asn1_OCSPBasicOCSPResponse.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/asn1_OCSPCertID.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/asn1_OCSPCertStatus.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/asn1_OCSPInnerRequest.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/asn1_OCSPKeyHash.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/asn1_OCSPRequest.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/asn1_OCSPResponderID.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/asn1_OCSPResponse.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/asn1_OCSPResponseBytes.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/asn1_OCSPResponseData.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/asn1_OCSPResponseStatus.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/asn1_OCSPSignature.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/asn1_OCSPSingleResponse.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/asn1_OCSPTBSRequest.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/asn1_OCSPVersion.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/asn1_id_pkix_ocsp.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/asn1_id_pkix_ocsp_basic.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/asn1_id_pkix_ocsp_nonce.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/ca.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/cert.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/cms.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/collector.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/crypto-ec.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/crypto.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/doxygen.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/env.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/error.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/file.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/hx509_err.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/hxtool-commands.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/hxtool.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/keyset.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/ks_dir.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/ks_file.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/ks_keychain.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/ks_mem.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/ks_null.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/ks_p11.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/ks_p12.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/lock.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/name.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/peer.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/print.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/req.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/revoke.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/sel-gram.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/sel-lex.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/sel.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/softp11.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_expr.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_name.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_soft_pkcs11.Po@am__quote@ .c.o: @am__fastdepCC_TRUE@ $(AM_V_CC)$(COMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o $@ $< @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='$<' object='$@' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(COMPILE) -c -o $@ $< .c.obj: @am__fastdepCC_TRUE@ $(AM_V_CC)$(COMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o $@ `$(CYGPATH_W) '$<'` @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='$<' object='$@' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(COMPILE) -c -o $@ `$(CYGPATH_W) '$<'` .c.lo: @am__fastdepCC_TRUE@ $(AM_V_CC)$(LTCOMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o $@ $< @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='$<' object='$@' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LTCOMPILE) -c -o $@ $< .l.c: $(AM_V_LEX)$(am__skiplex) $(SHELL) $(YLWRAP) $< $(LEX_OUTPUT_ROOT).c $@ -- $(LEXCOMPILE) .y.c: $(AM_V_YACC)$(am__skipyacc) $(SHELL) $(YLWRAP) $< y.tab.c $@ y.tab.h `echo $@ | $(am__yacc_c2h)` y.output $*.output -- $(YACCCOMPILE) mostlyclean-libtool: -rm -f *.lo clean-libtool: -rm -rf .libs _libs install-dist_includeHEADERS: $(dist_include_HEADERS) @$(NORMAL_INSTALL) @list='$(dist_include_HEADERS)'; test -n "$(includedir)" || list=; \ if test -n "$$list"; then \ echo " $(MKDIR_P) '$(DESTDIR)$(includedir)'"; \ $(MKDIR_P) "$(DESTDIR)$(includedir)" || exit 1; \ fi; \ for p in $$list; do \ if test -f "$$p"; then d=; else d="$(srcdir)/"; fi; \ echo "$$d$$p"; \ done | $(am__base_list) | \ while read files; do \ echo " $(INSTALL_HEADER) $$files '$(DESTDIR)$(includedir)'"; \ $(INSTALL_HEADER) $$files "$(DESTDIR)$(includedir)" || exit $$?; \ done uninstall-dist_includeHEADERS: @$(NORMAL_UNINSTALL) @list='$(dist_include_HEADERS)'; test -n "$(includedir)" || list=; \ files=`for p in $$list; do echo $$p; done | sed -e 's|^.*/||'`; \ dir='$(DESTDIR)$(includedir)'; $(am__uninstall_files_from_dir) install-nodist_includeHEADERS: $(nodist_include_HEADERS) @$(NORMAL_INSTALL) @list='$(nodist_include_HEADERS)'; test -n "$(includedir)" || list=; \ if test -n "$$list"; then \ echo " $(MKDIR_P) '$(DESTDIR)$(includedir)'"; \ $(MKDIR_P) "$(DESTDIR)$(includedir)" || exit 1; \ fi; \ for p in $$list; do \ if test -f "$$p"; then d=; else d="$(srcdir)/"; fi; \ echo "$$d$$p"; \ done | $(am__base_list) | \ while read files; do \ echo " $(INSTALL_HEADER) $$files '$(DESTDIR)$(includedir)'"; \ $(INSTALL_HEADER) $$files "$(DESTDIR)$(includedir)" || exit $$?; \ done uninstall-nodist_includeHEADERS: @$(NORMAL_UNINSTALL) @list='$(nodist_include_HEADERS)'; test -n "$(includedir)" || list=; \ files=`for p in $$list; do echo $$p; done | sed -e 's|^.*/||'`; \ dir='$(DESTDIR)$(includedir)'; $(am__uninstall_files_from_dir) ID: $(am__tagged_files) $(am__define_uniq_tagged_files); mkid -fID $$unique tags: tags-am TAGS: tags tags-am: $(TAGS_DEPENDENCIES) $(am__tagged_files) set x; \ here=`pwd`; \ $(am__define_uniq_tagged_files); \ shift; \ if test -z "$(ETAGS_ARGS)$$*$$unique"; then :; else \ test -n "$$unique" || unique=$$empty_fix; \ if test $$# -gt 0; then \ $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ "$$@" $$unique; \ else \ $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ $$unique; \ fi; \ fi ctags: ctags-am CTAGS: ctags ctags-am: $(TAGS_DEPENDENCIES) $(am__tagged_files) $(am__define_uniq_tagged_files); \ test -z "$(CTAGS_ARGS)$$unique" \ || $(CTAGS) $(CTAGSFLAGS) $(AM_CTAGSFLAGS) $(CTAGS_ARGS) \ $$unique GTAGS: here=`$(am__cd) $(top_builddir) && pwd` \ && $(am__cd) $(top_srcdir) \ && gtags -i $(GTAGS_ARGS) "$$here" cscopelist: cscopelist-am cscopelist-am: $(am__tagged_files) list='$(am__tagged_files)'; \ case "$(srcdir)" in \ [\\/]* | ?:[\\/]*) sdir="$(srcdir)" ;; \ *) sdir=$(subdir)/$(srcdir) ;; \ esac; \ for i in $$list; do \ if test -f "$$i"; then \ echo "$(subdir)/$$i"; \ else \ echo "$$sdir/$$i"; \ fi; \ done >> $(top_builddir)/cscope.files distclean-tags: -rm -f TAGS ID GTAGS GRTAGS GSYMS GPATH tags # Recover from deleted '.trs' file; this should ensure that # "rm -f foo.log; make foo.trs" re-run 'foo.test', and re-create # both 'foo.log' and 'foo.trs'. Break the recipe in two subshells # to avoid problems with "make -n". .log.trs: rm -f $< $@ $(MAKE) $(AM_MAKEFLAGS) $< # Leading 'am--fnord' is there to ensure the list of targets does not # expand to empty, as could happen e.g. with make check TESTS=''. am--fnord $(TEST_LOGS) $(TEST_LOGS:.log=.trs): $(am__force_recheck) am--force-recheck: @: $(TEST_SUITE_LOG): $(TEST_LOGS) @$(am__set_TESTS_bases); \ am__f_ok () { test -f "$$1" && test -r "$$1"; }; \ redo_bases=`for i in $$bases; do \ am__f_ok $$i.trs && am__f_ok $$i.log || echo $$i; \ done`; \ if test -n "$$redo_bases"; then \ redo_logs=`for i in $$redo_bases; do echo $$i.log; done`; \ redo_results=`for i in $$redo_bases; do echo $$i.trs; done`; \ if $(am__make_dryrun); then :; else \ rm -f $$redo_logs && rm -f $$redo_results || exit 1; \ fi; \ fi; \ if test -n "$$am__remaking_logs"; then \ echo "fatal: making $(TEST_SUITE_LOG): possible infinite" \ "recursion detected" >&2; \ elif test -n "$$redo_logs"; then \ am__remaking_logs=yes $(MAKE) $(AM_MAKEFLAGS) $$redo_logs; \ fi; \ if $(am__make_dryrun); then :; else \ st=0; \ errmsg="fatal: making $(TEST_SUITE_LOG): failed to create"; \ for i in $$redo_bases; do \ test -f $$i.trs && test -r $$i.trs \ || { echo "$$errmsg $$i.trs" >&2; st=1; }; \ test -f $$i.log && test -r $$i.log \ || { echo "$$errmsg $$i.log" >&2; st=1; }; \ done; \ test $$st -eq 0 || exit 1; \ fi @$(am__sh_e_setup); $(am__tty_colors); $(am__set_TESTS_bases); \ ws='[ ]'; \ results=`for b in $$bases; do echo $$b.trs; done`; \ test -n "$$results" || results=/dev/null; \ all=` grep "^$$ws*:test-result:" $$results | wc -l`; \ pass=` grep "^$$ws*:test-result:$$ws*PASS" $$results | wc -l`; \ fail=` grep "^$$ws*:test-result:$$ws*FAIL" $$results | wc -l`; \ skip=` grep "^$$ws*:test-result:$$ws*SKIP" $$results | wc -l`; \ xfail=`grep "^$$ws*:test-result:$$ws*XFAIL" $$results | wc -l`; \ xpass=`grep "^$$ws*:test-result:$$ws*XPASS" $$results | wc -l`; \ error=`grep "^$$ws*:test-result:$$ws*ERROR" $$results | wc -l`; \ if test `expr $$fail + $$xpass + $$error` -eq 0; then \ success=true; \ else \ success=false; \ fi; \ br='==================='; br=$$br$$br$$br$$br; \ result_count () \ { \ if test x"$$1" = x"--maybe-color"; then \ maybe_colorize=yes; \ elif test x"$$1" = x"--no-color"; then \ maybe_colorize=no; \ else \ echo "$@: invalid 'result_count' usage" >&2; exit 4; \ fi; \ shift; \ desc=$$1 count=$$2; \ if test $$maybe_colorize = yes && test $$count -gt 0; then \ color_start=$$3 color_end=$$std; \ else \ color_start= color_end=; \ fi; \ echo "$${color_start}# $$desc $$count$${color_end}"; \ }; \ create_testsuite_report () \ { \ result_count $$1 "TOTAL:" $$all "$$brg"; \ result_count $$1 "PASS: " $$pass "$$grn"; \ result_count $$1 "SKIP: " $$skip "$$blu"; \ result_count $$1 "XFAIL:" $$xfail "$$lgn"; \ result_count $$1 "FAIL: " $$fail "$$red"; \ result_count $$1 "XPASS:" $$xpass "$$red"; \ result_count $$1 "ERROR:" $$error "$$mgn"; \ }; \ { \ echo "$(PACKAGE_STRING): $(subdir)/$(TEST_SUITE_LOG)" | \ $(am__rst_title); \ create_testsuite_report --no-color; \ echo; \ echo ".. contents:: :depth: 2"; \ echo; \ for b in $$bases; do echo $$b; done \ | $(am__create_global_log); \ } >$(TEST_SUITE_LOG).tmp || exit 1; \ mv $(TEST_SUITE_LOG).tmp $(TEST_SUITE_LOG); \ if $$success; then \ col="$$grn"; \ else \ col="$$red"; \ test x"$$VERBOSE" = x || cat $(TEST_SUITE_LOG); \ fi; \ echo "$${col}$$br$${std}"; \ echo "$${col}Testsuite summary for $(PACKAGE_STRING)$${std}"; \ echo "$${col}$$br$${std}"; \ create_testsuite_report --maybe-color; \ echo "$$col$$br$$std"; \ if $$success; then :; else \ echo "$${col}See $(subdir)/$(TEST_SUITE_LOG)$${std}"; \ if test -n "$(PACKAGE_BUGREPORT)"; then \ echo "$${col}Please report to $(PACKAGE_BUGREPORT)$${std}"; \ fi; \ echo "$$col$$br$$std"; \ fi; \ $$success || exit 1 check-TESTS: @list='$(RECHECK_LOGS)'; test -z "$$list" || rm -f $$list @list='$(RECHECK_LOGS:.log=.trs)'; test -z "$$list" || rm -f $$list @test -z "$(TEST_SUITE_LOG)" || rm -f $(TEST_SUITE_LOG) @set +e; $(am__set_TESTS_bases); \ log_list=`for i in $$bases; do echo $$i.log; done`; \ trs_list=`for i in $$bases; do echo $$i.trs; done`; \ log_list=`echo $$log_list`; trs_list=`echo $$trs_list`; \ $(MAKE) $(AM_MAKEFLAGS) $(TEST_SUITE_LOG) TEST_LOGS="$$log_list"; \ exit $$?; recheck: all $(check_PROGRAMS) $(check_SCRIPTS) @test -z "$(TEST_SUITE_LOG)" || rm -f $(TEST_SUITE_LOG) @set +e; $(am__set_TESTS_bases); \ bases=`for i in $$bases; do echo $$i; done \ | $(am__list_recheck_tests)` || exit 1; \ log_list=`for i in $$bases; do echo $$i.log; done`; \ log_list=`echo $$log_list`; \ $(MAKE) $(AM_MAKEFLAGS) $(TEST_SUITE_LOG) \ am__force_recheck=am--force-recheck \ TEST_LOGS="$$log_list"; \ exit $$? test_ca.log: test_ca @p='test_ca'; \ b='test_ca'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_cert.log: test_cert @p='test_cert'; \ b='test_cert'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_chain.log: test_chain @p='test_chain'; \ b='test_chain'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_cms.log: test_cms @p='test_cms'; \ b='test_cms'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_crypto.log: test_crypto @p='test_crypto'; \ b='test_crypto'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_nist.log: test_nist @p='test_nist'; \ b='test_nist'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_nist2.log: test_nist2 @p='test_nist2'; \ b='test_nist2'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_pkcs11.log: test_pkcs11 @p='test_pkcs11'; \ b='test_pkcs11'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_java_pkcs11.log: test_java_pkcs11 @p='test_java_pkcs11'; \ b='test_java_pkcs11'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_nist_cert.log: test_nist_cert @p='test_nist_cert'; \ b='test_nist_cert'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_nist_pkcs12.log: test_nist_pkcs12 @p='test_nist_pkcs12'; \ b='test_nist_pkcs12'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_req.log: test_req @p='test_req'; \ b='test_req'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_windows.log: test_windows @p='test_windows'; \ b='test_windows'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_query.log: test_query @p='test_query'; \ b='test_query'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_name.log: test_name$(EXEEXT) @p='test_name$(EXEEXT)'; \ b='test_name'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_expr.log: test_expr$(EXEEXT) @p='test_expr$(EXEEXT)'; \ b='test_expr'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) .test.log: @p='$<'; \ $(am__set_b); \ $(am__check_pre) $(TEST_LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_TEST_LOG_DRIVER_FLAGS) $(TEST_LOG_DRIVER_FLAGS) -- $(TEST_LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) @am__EXEEXT_TRUE@.test$(EXEEXT).log: @am__EXEEXT_TRUE@ @p='$<'; \ @am__EXEEXT_TRUE@ $(am__set_b); \ @am__EXEEXT_TRUE@ $(am__check_pre) $(TEST_LOG_DRIVER) --test-name "$$f" \ @am__EXEEXT_TRUE@ --log-file $$b.log --trs-file $$b.trs \ @am__EXEEXT_TRUE@ $(am__common_driver_flags) $(AM_TEST_LOG_DRIVER_FLAGS) $(TEST_LOG_DRIVER_FLAGS) -- $(TEST_LOG_COMPILE) \ @am__EXEEXT_TRUE@ "$$tst" $(AM_TESTS_FD_REDIRECT) distdir: $(DISTFILES) @srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ topsrcdirstrip=`echo "$(top_srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ list='$(DISTFILES)'; \ dist_files=`for file in $$list; do echo $$file; done | \ sed -e "s|^$$srcdirstrip/||;t" \ -e "s|^$$topsrcdirstrip/|$(top_builddir)/|;t"`; \ case $$dist_files in \ */*) $(MKDIR_P) `echo "$$dist_files" | \ sed '/\//!d;s|^|$(distdir)/|;s,/[^/]*$$,,' | \ sort -u` ;; \ esac; \ for file in $$dist_files; do \ if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \ if test -d $$d/$$file; then \ dir=`echo "/$$file" | sed -e 's,/[^/]*$$,,'`; \ if test -d "$(distdir)/$$file"; then \ find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ fi; \ if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \ cp -fpR $(srcdir)/$$file "$(distdir)$$dir" || exit 1; \ find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ fi; \ cp -fpR $$d/$$file "$(distdir)$$dir" || exit 1; \ else \ test -f "$(distdir)/$$file" \ || cp -p $$d/$$file "$(distdir)/$$file" \ || exit 1; \ fi; \ done $(MAKE) $(AM_MAKEFLAGS) \ top_distdir="$(top_distdir)" distdir="$(distdir)" \ dist-hook check-am: all-am $(MAKE) $(AM_MAKEFLAGS) $(check_PROGRAMS) $(check_SCRIPTS) $(MAKE) $(AM_MAKEFLAGS) check-TESTS check-local check: $(BUILT_SOURCES) $(MAKE) $(AM_MAKEFLAGS) check-am all-am: Makefile $(LTLIBRARIES) $(PROGRAMS) $(HEADERS) all-local install-binPROGRAMS: install-libLTLIBRARIES installdirs: for dir in "$(DESTDIR)$(libdir)" "$(DESTDIR)$(bindir)" "$(DESTDIR)$(includedir)" "$(DESTDIR)$(includedir)"; do \ test -z "$$dir" || $(MKDIR_P) "$$dir"; \ done install: $(BUILT_SOURCES) $(MAKE) $(AM_MAKEFLAGS) install-am install-exec: install-exec-am install-data: install-data-am uninstall: uninstall-am install-am: all-am @$(MAKE) $(AM_MAKEFLAGS) install-exec-am install-data-am installcheck: installcheck-am install-strip: if test -z '$(STRIP)'; then \ $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ install; \ else \ $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'" install; \ fi mostlyclean-generic: -test -z "$(TEST_LOGS)" || rm -f $(TEST_LOGS) -test -z "$(TEST_LOGS:.log=.trs)" || rm -f $(TEST_LOGS:.log=.trs) -test -z "$(TEST_SUITE_LOG)" || rm -f $(TEST_SUITE_LOG) clean-generic: -test -z "$(CLEANFILES)" || rm -f $(CLEANFILES) distclean-generic: -test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES) -test . = "$(srcdir)" || test -z "$(CONFIG_CLEAN_VPATH_FILES)" || rm -f $(CONFIG_CLEAN_VPATH_FILES) maintainer-clean-generic: @echo "This command is intended for maintainers to use" @echo "it deletes files that may require special tools to rebuild." -rm -f sel-gram.c -rm -f sel-gram.h -rm -f sel-lex.c -test -z "$(BUILT_SOURCES)" || rm -f $(BUILT_SOURCES) clean: clean-am clean-am: clean-binPROGRAMS clean-checkPROGRAMS clean-generic \ clean-libLTLIBRARIES clean-libtool clean-local mostlyclean-am distclean: distclean-am -rm -rf ./$(DEPDIR) -rm -f Makefile distclean-am: clean-am distclean-compile distclean-generic \ distclean-tags dvi: dvi-am dvi-am: html: html-am html-am: info: info-am info-am: install-data-am: install-dist_includeHEADERS \ install-nodist_includeHEADERS @$(NORMAL_INSTALL) $(MAKE) $(AM_MAKEFLAGS) install-data-hook install-dvi: install-dvi-am install-dvi-am: install-exec-am: install-binPROGRAMS install-exec-local \ install-libLTLIBRARIES install-html: install-html-am install-html-am: install-info: install-info-am install-info-am: install-man: install-pdf: install-pdf-am install-pdf-am: install-ps: install-ps-am install-ps-am: installcheck-am: maintainer-clean: maintainer-clean-am -rm -rf ./$(DEPDIR) -rm -f Makefile maintainer-clean-am: distclean-am maintainer-clean-generic mostlyclean: mostlyclean-am mostlyclean-am: mostlyclean-compile mostlyclean-generic \ mostlyclean-libtool pdf: pdf-am pdf-am: ps: ps-am ps-am: uninstall-am: uninstall-binPROGRAMS uninstall-dist_includeHEADERS \ uninstall-libLTLIBRARIES uninstall-nodist_includeHEADERS @$(NORMAL_INSTALL) $(MAKE) $(AM_MAKEFLAGS) uninstall-hook .MAKE: all check check-am install install-am install-data-am \ install-strip uninstall-am .PHONY: CTAGS GTAGS TAGS all all-am all-local check check-TESTS \ check-am check-local clean clean-binPROGRAMS \ clean-checkPROGRAMS clean-generic clean-libLTLIBRARIES \ clean-libtool clean-local cscopelist-am ctags ctags-am \ dist-hook distclean distclean-compile distclean-generic \ distclean-libtool distclean-tags distdir dvi dvi-am html \ html-am info info-am install install-am install-binPROGRAMS \ install-data install-data-am install-data-hook \ install-dist_includeHEADERS install-dvi install-dvi-am \ install-exec install-exec-am install-exec-local install-html \ install-html-am install-info install-info-am \ install-libLTLIBRARIES install-man \ install-nodist_includeHEADERS install-pdf install-pdf-am \ install-ps install-ps-am install-strip installcheck \ installcheck-am installdirs maintainer-clean \ maintainer-clean-generic mostlyclean mostlyclean-compile \ mostlyclean-generic mostlyclean-libtool pdf pdf-am ps ps-am \ recheck tags tags-am uninstall uninstall-am \ uninstall-binPROGRAMS uninstall-dist_includeHEADERS \ uninstall-hook uninstall-libLTLIBRARIES \ uninstall-nodist_includeHEADERS .PRECIOUS: Makefile install-suid-programs: @foo='$(bin_SUIDS)'; \ for file in $$foo; do \ x=$(DESTDIR)$(bindir)/$$file; \ if chown 0:0 $$x && chmod u+s $$x; then :; else \ echo "*"; \ echo "* Failed to install $$x setuid root"; \ echo "*"; \ fi; \ done install-exec-local: install-suid-programs codesign-all: @if [ X"$$CODE_SIGN_IDENTITY" != X ] ; then \ foo='$(bin_PROGRAMS) $(sbin_PROGRAMS) $(libexec_PROGRAMS)' ; \ for file in $$foo ; do \ echo "CODESIGN $$file" ; \ codesign -f -s "$$CODE_SIGN_IDENTITY" $$file || exit 1 ; \ done ; \ fi all-local: codesign-all install-build-headers:: $(include_HEADERS) $(dist_include_HEADERS) $(nodist_include_HEADERS) $(build_HEADERZ) $(nobase_include_HEADERS) $(noinst_HEADERS) @foo='$(include_HEADERS) $(dist_include_HEADERS) $(nodist_include_HEADERS) $(build_HEADERZ) $(noinst_HEADERS)'; \ for f in $$foo; do \ f=`basename $$f`; \ if test -f "$(srcdir)/$$f"; then file="$(srcdir)/$$f"; \ else file="$$f"; fi; \ if cmp -s $$file $(buildinclude)/$$f 2> /dev/null ; then \ : ; else \ echo " $(CP) $$file $(buildinclude)/$$f"; \ $(CP) $$file $(buildinclude)/$$f || true; \ fi ; \ done ; \ foo='$(nobase_include_HEADERS)'; \ for f in $$foo; do \ if test -f "$(srcdir)/$$f"; then file="$(srcdir)/$$f"; \ else file="$$f"; fi; \ $(mkdir_p) $(buildinclude)/`dirname $$f` ; \ if cmp -s $$file $(buildinclude)/$$f 2> /dev/null ; then \ : ; else \ echo " $(CP) $$file $(buildinclude)/$$f"; \ $(CP) $$file $(buildinclude)/$$f; \ fi ; \ done all-local: install-build-headers check-local:: @if test '$(CHECK_LOCAL)' = "no-check-local"; then \ foo=''; elif test '$(CHECK_LOCAL)'; then \ foo='$(CHECK_LOCAL)'; else \ foo='$(PROGRAMS)'; fi; \ if test "$$foo"; then \ failed=0; all=0; \ for i in $$foo; do \ all=`expr $$all + 1`; \ if (./$$i --version && ./$$i --help) > /dev/null 2>&1; then \ echo "PASS: $$i"; \ else \ echo "FAIL: $$i"; \ failed=`expr $$failed + 1`; \ fi; \ done; \ if test "$$failed" -eq 0; then \ banner="All $$all tests passed"; \ else \ banner="$$failed of $$all tests failed"; \ fi; \ dashes=`echo "$$banner" | sed s/./=/g`; \ echo "$$dashes"; \ echo "$$banner"; \ echo "$$dashes"; \ test "$$failed" -eq 0 || exit 1; \ fi .x.c: @cmp -s $< $@ 2> /dev/null || cp $< $@ .hx.h: @cmp -s $< $@ 2> /dev/null || cp $< $@ #NROFF_MAN = nroff -man .1.cat1: $(NROFF_MAN) $< > $@ .3.cat3: $(NROFF_MAN) $< > $@ .5.cat5: $(NROFF_MAN) $< > $@ .7.cat7: $(NROFF_MAN) $< > $@ .8.cat8: $(NROFF_MAN) $< > $@ dist-cat1-mans: @foo='$(man1_MANS)'; \ bar='$(man_MANS)'; \ for i in $$bar; do \ case $$i in \ *.1) foo="$$foo $$i";; \ esac; done ;\ for i in $$foo; do \ x=`echo $$i | sed 's/\.[^.]*$$/.cat1/'`; \ echo "$(NROFF_MAN) $(srcdir)/$$i > $(distdir)/$$x"; \ $(NROFF_MAN) $(srcdir)/$$i > $(distdir)/$$x; \ done dist-cat3-mans: @foo='$(man3_MANS)'; \ bar='$(man_MANS)'; \ for i in $$bar; do \ case $$i in \ *.3) foo="$$foo $$i";; \ esac; done ;\ for i in $$foo; do \ x=`echo $$i | sed 's/\.[^.]*$$/.cat3/'`; \ echo "$(NROFF_MAN) $(srcdir)/$$i > $(distdir)/$$x"; \ $(NROFF_MAN) $(srcdir)/$$i > $(distdir)/$$x; \ done dist-cat5-mans: @foo='$(man5_MANS)'; \ bar='$(man_MANS)'; \ for i in $$bar; do \ case $$i in \ *.5) foo="$$foo $$i";; \ esac; done ;\ for i in $$foo; do \ x=`echo $$i | sed 's/\.[^.]*$$/.cat5/'`; \ echo "$(NROFF_MAN) $(srcdir)/$$i > $(distdir)/$$x"; \ $(NROFF_MAN) $(srcdir)/$$i > $(distdir)/$$x; \ done dist-cat7-mans: @foo='$(man7_MANS)'; \ bar='$(man_MANS)'; \ for i in $$bar; do \ case $$i in \ *.7) foo="$$foo $$i";; \ esac; done ;\ for i in $$foo; do \ x=`echo $$i | sed 's/\.[^.]*$$/.cat7/'`; \ echo "$(NROFF_MAN) $(srcdir)/$$i > $(distdir)/$$x"; \ $(NROFF_MAN) $(srcdir)/$$i > $(distdir)/$$x; \ done dist-cat8-mans: @foo='$(man8_MANS)'; \ bar='$(man_MANS)'; \ for i in $$bar; do \ case $$i in \ *.8) foo="$$foo $$i";; \ esac; done ;\ for i in $$foo; do \ x=`echo $$i | sed 's/\.[^.]*$$/.cat8/'`; \ echo "$(NROFF_MAN) $(srcdir)/$$i > $(distdir)/$$x"; \ $(NROFF_MAN) $(srcdir)/$$i > $(distdir)/$$x; \ done dist-hook: dist-cat1-mans dist-cat3-mans dist-cat5-mans dist-cat7-mans dist-cat8-mans install-cat-mans: $(SHELL) $(top_srcdir)/cf/install-catman.sh install "$(INSTALL_DATA)" "$(mkinstalldirs)" "$(srcdir)" "$(DESTDIR)$(mandir)" '$(CATMANEXT)' $(man_MANS) $(man1_MANS) $(man3_MANS) $(man5_MANS) $(man7_MANS) $(man8_MANS) uninstall-cat-mans: $(SHELL) $(top_srcdir)/cf/install-catman.sh uninstall "$(INSTALL_DATA)" "$(mkinstalldirs)" "$(srcdir)" "$(DESTDIR)$(mandir)" '$(CATMANEXT)' $(man_MANS) $(man1_MANS) $(man3_MANS) $(man5_MANS) $(man7_MANS) $(man8_MANS) install-data-hook: install-cat-mans uninstall-hook: uninstall-cat-mans .et.h: $(COMPILE_ET) $< .et.c: $(COMPILE_ET) $< # # Useful target for debugging # check-valgrind: tobjdir=`cd $(top_builddir) && pwd` ; \ tsrcdir=`cd $(top_srcdir) && pwd` ; \ env TESTS_ENVIRONMENT="$${tsrcdir}/cf/maybe-valgrind.sh -s $${tsrcdir} -o $${tobjdir}" make check # # Target to please samba build farm, builds distfiles in-tree. # Will break when automake changes... # distdir-in-tree: $(DISTFILES) $(INFO_DEPS) list='$(DIST_SUBDIRS)'; for subdir in $$list; do \ if test "$$subdir" != .; then \ (cd $$subdir && $(MAKE) $(AM_MAKEFLAGS) distdir-in-tree) ; \ fi ; \ done sel-lex.c: sel-gram.h $(libhx509_la_OBJECTS): $(srcdir)/version-script.map $(nodist_include_HEADERS) $(priv_headers) $(gen_files_ocsp) ocsp_asn1.hx ocsp_asn1-priv.hx: ocsp_asn1_files $(gen_files_pkcs10) pkcs10_asn1.hx pkcs10_asn1-priv.hx: pkcs10_asn1_files $(gen_files_crmf) crmf_asn1.hx crmf_asn1-priv.hx: crmf_asn1_files ocsp_asn1_files: $(ASN1_COMPILE_DEP) $(srcdir)/ocsp.asn1 $(srcdir)/ocsp.opt $(heim_verbose)$(ASN1_COMPILE) --option-file=$(srcdir)/ocsp.opt $(srcdir)/ocsp.asn1 ocsp_asn1 || (rm -f ocsp_asn1_files ; exit 1) pkcs10_asn1_files: $(ASN1_COMPILE_DEP) $(srcdir)/pkcs10.asn1 $(srcdir)/pkcs10.opt $(heim_verbose)$(ASN1_COMPILE) --option-file=$(srcdir)/pkcs10.opt $(srcdir)/pkcs10.asn1 pkcs10_asn1 || (rm -f pkcs10_asn1_files ; exit 1) crmf_asn1_files: $(ASN1_COMPILE_DEP) $(srcdir)/crmf.asn1 $(heim_verbose)$(ASN1_COMPILE) $(srcdir)/crmf.asn1 crmf_asn1 || (rm -f crmf_asn1_files ; exit 1) $(ALL_OBJECTS): $(HX509_PROTOS) $(libhx509_la_OBJECTS): $(srcdir)/hx_locl.h $(libhx509_la_OBJECTS): ocsp_asn1.h pkcs10_asn1.h $(srcdir)/hx509-protos.h: $(dist_libhx509_la_SOURCES) $(heim_verbose)cd $(srcdir) && perl ../../cf/make-proto.pl -R '^(_|^C)' -E HX509_LIB -q -P comment -o hx509-protos.h $(dist_libhx509_la_SOURCES) || rm -f hx509-protos.h $(srcdir)/hx509-private.h: $(dist_libhx509_la_SOURCES) $(heim_verbose)cd $(srcdir) && perl ../../cf/make-proto.pl -q -P comment -p hx509-private.h $(dist_libhx509_la_SOURCES) || rm -f hx509-private.h hxtool-commands.c hxtool-commands.h: hxtool-commands.in $(SLC) $(heim_verbose)$(SLC) $(srcdir)/hxtool-commands.in $(hxtool_OBJECTS): hxtool-commands.h hx509_err.h clean-local: @echo "cleaning PKITS" ; rm -rf PKITS_data test_ca: test_ca.in Makefile $(do_subst) < $(srcdir)/test_ca.in > test_ca.tmp $(heim_verbose)chmod +x test_ca.tmp mv test_ca.tmp test_ca test_cert: test_cert.in Makefile $(do_subst) < $(srcdir)/test_cert.in > test_cert.tmp $(heim_verbose)chmod +x test_cert.tmp mv test_cert.tmp test_cert test_chain: test_chain.in Makefile $(do_subst) < $(srcdir)/test_chain.in > test_chain.tmp $(heim_verbose)chmod +x test_chain.tmp mv test_chain.tmp test_chain test_cms: test_cms.in Makefile $(do_subst) < $(srcdir)/test_cms.in > test_cms.tmp $(heim_verbose)chmod +x test_cms.tmp mv test_cms.tmp test_cms test_crypto: test_crypto.in Makefile $(do_subst) < $(srcdir)/test_crypto.in > test_crypto.tmp $(heim_verbose)chmod +x test_crypto.tmp mv test_crypto.tmp test_crypto test_nist: test_nist.in Makefile $(do_subst) < $(srcdir)/test_nist.in > test_nist.tmp $(heim_verbose)chmod +x test_nist.tmp mv test_nist.tmp test_nist test_nist2: test_nist2.in Makefile $(do_subst) < $(srcdir)/test_nist2.in > test_nist2.tmp $(heim_verbose)chmod +x test_nist2.tmp mv test_nist2.tmp test_nist2 test_pkcs11: test_pkcs11.in Makefile $(do_subst) < $(srcdir)/test_pkcs11.in > test_pkcs11.tmp $(heim_verbose)chmod +x test_pkcs11.tmp mv test_pkcs11.tmp test_pkcs11 test_java_pkcs11: test_java_pkcs11.in Makefile $(do_subst) < $(srcdir)/test_java_pkcs11.in > test_java_pkcs11.tmp $(heim_verbose)chmod +x test_java_pkcs11.tmp mv test_java_pkcs11.tmp test_java_pkcs11 test_nist_cert: test_nist_cert.in Makefile $(do_subst) < $(srcdir)/test_nist_cert.in > test_nist_cert.tmp $(heim_verbose)chmod +x test_nist_cert.tmp mv test_nist_cert.tmp test_nist_cert test_nist_pkcs12: test_nist_pkcs12.in Makefile $(do_subst) < $(srcdir)/test_nist_pkcs12.in > test_nist_pkcs12.tmp $(heim_verbose)chmod +x test_nist_pkcs12.tmp mv test_nist_pkcs12.tmp test_nist_pkcs12 test_req: test_req.in Makefile $(do_subst) < $(srcdir)/test_req.in > test_req.tmp $(heim_verbose)chmod +x test_req.tmp mv test_req.tmp test_req test_windows: test_windows.in Makefile $(do_subst) < $(srcdir)/test_windows.in > test_windows.tmp $(heim_verbose)chmod +x test_windows.tmp mv test_windows.tmp test_windows test_query: test_query.in Makefile $(do_subst) < $(srcdir)/test_query.in > test_query.tmp $(heim_verbose)chmod +x test_query.tmp mv test_query.tmp test_query # Tell versions [3.59,3.63) of GNU make to not export all variables. # Otherwise a system limit (for SysV at least) may be exceeded. .NOEXPORT: heimdal-7.5.0/lib/hx509/crmf.asn10000644000175000017500000000533512136107747014426 0ustar niknik-- $Id$ PKCS10 DEFINITIONS ::= BEGIN IMPORTS Time, GeneralName, SubjectPublicKeyInfo, RelativeDistinguishedName, AttributeTypeAndValue, Extension, AlgorithmIdentifier FROM rfc2459 heim_any FROM heim; CRMFRDNSequence ::= SEQUENCE OF RelativeDistinguishedName Controls ::= SEQUENCE -- SIZE(1..MAX) -- OF AttributeTypeAndValue -- XXX IMPLICIT brokenness POPOSigningKey ::= SEQUENCE { poposkInput [0] IMPLICIT POPOSigningKeyInput OPTIONAL, algorithmIdentifier AlgorithmIdentifier, signature BIT STRING } PKMACValue ::= SEQUENCE { algId AlgorithmIdentifier, value BIT STRING } -- XXX IMPLICIT brokenness POPOSigningKeyInput ::= SEQUENCE { authInfo CHOICE { sender [0] IMPLICIT GeneralName, publicKeyMAC PKMACValue }, publicKey SubjectPublicKeyInfo } -- from CertTemplate PBMParameter ::= SEQUENCE { salt OCTET STRING, owf AlgorithmIdentifier, iterationCount INTEGER, mac AlgorithmIdentifier } SubsequentMessage ::= INTEGER { encrCert (0), challengeResp (1) } -- XXX IMPLICIT brokenness POPOPrivKey ::= CHOICE { thisMessage [0] BIT STRING, -- Deprecated subsequentMessage [1] IMPLICIT SubsequentMessage, dhMAC [2] BIT STRING, -- Deprecated agreeMAC [3] IMPLICIT PKMACValue, encryptedKey [4] heim_any } -- XXX IMPLICIT brokenness ProofOfPossession ::= CHOICE { raVerified [0] NULL, signature [1] POPOSigningKey, keyEncipherment [2] POPOPrivKey, keyAgreement [3] POPOPrivKey } CertTemplate ::= SEQUENCE { version [0] INTEGER OPTIONAL, serialNumber [1] INTEGER OPTIONAL, signingAlg [2] SEQUENCE { algorithm OBJECT IDENTIFIER, parameters heim_any OPTIONAL } -- AlgorithmIdentifier -- OPTIONAL, issuer [3] IMPLICIT CHOICE { rdnSequence CRMFRDNSequence } -- Name -- OPTIONAL, validity [4] SEQUENCE { notBefore [0] Time OPTIONAL, notAfter [1] Time OPTIONAL } -- OptionalValidity -- OPTIONAL, subject [5] IMPLICIT CHOICE { rdnSequence CRMFRDNSequence } -- Name -- OPTIONAL, publicKey [6] IMPLICIT SEQUENCE { algorithm AlgorithmIdentifier, subjectPublicKey BIT STRING OPTIONAL } -- SubjectPublicKeyInfo -- OPTIONAL, issuerUID [7] IMPLICIT BIT STRING OPTIONAL, subjectUID [8] IMPLICIT BIT STRING OPTIONAL, extensions [9] IMPLICIT SEQUENCE OF Extension OPTIONAL } CertRequest ::= SEQUENCE { certReqId INTEGER, certTemplate CertTemplate, controls Controls OPTIONAL } CertReqMsg ::= SEQUENCE { certReq CertRequest, popo ProofOfPossession OPTIONAL, regInfo SEQUENCE OF AttributeTypeAndValue OPTIONAL } CertReqMessages ::= SEQUENCE OF CertReqMsg END heimdal-7.5.0/lib/hx509/revoke.c0000644000175000017500000011630313026237312014337 0ustar niknik/* * Copyright (c) 2006 - 2007 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ /** * @page page_revoke Revocation methods * * There are two revocation method for PKIX/X.509: CRL and OCSP. * Revocation is needed if the private key is lost and * stolen. Depending on how picky you are, you might want to make * revocation for destroyed private keys too (smartcard broken), but * that should not be a problem. * * CRL is a list of certifiates that have expired. * * OCSP is an online checking method where the requestor sends a list * of certificates to the OCSP server to return a signed reply if they * are valid or not. Some services sends a OCSP reply as part of the * hand-shake to make the revoktion decision simpler/faster for the * client. */ #include "hx_locl.h" struct revoke_crl { char *path; time_t last_modfied; CRLCertificateList crl; int verified; int failed_verify; }; struct revoke_ocsp { char *path; time_t last_modfied; OCSPBasicOCSPResponse ocsp; hx509_certs certs; hx509_cert signer; }; struct hx509_revoke_ctx_data { unsigned int ref; struct { struct revoke_crl *val; size_t len; } crls; struct { struct revoke_ocsp *val; size_t len; } ocsps; }; /** * Allocate a revokation context. Free with hx509_revoke_free(). * * @param context A hx509 context. * @param ctx returns a newly allocated revokation context. * * @return An hx509 error code, see hx509_get_error_string(). * * @ingroup hx509_revoke */ int hx509_revoke_init(hx509_context context, hx509_revoke_ctx *ctx) { *ctx = calloc(1, sizeof(**ctx)); if (*ctx == NULL) return ENOMEM; (*ctx)->ref = 1; (*ctx)->crls.len = 0; (*ctx)->crls.val = NULL; (*ctx)->ocsps.len = 0; (*ctx)->ocsps.val = NULL; return 0; } hx509_revoke_ctx _hx509_revoke_ref(hx509_revoke_ctx ctx) { if (ctx == NULL) return NULL; if (ctx->ref == 0) _hx509_abort("revoke ctx refcount == 0 on ref"); ctx->ref++; if (ctx->ref == UINT_MAX) _hx509_abort("revoke ctx refcount == UINT_MAX on ref"); return ctx; } static void free_ocsp(struct revoke_ocsp *ocsp) { free(ocsp->path); free_OCSPBasicOCSPResponse(&ocsp->ocsp); hx509_certs_free(&ocsp->certs); hx509_cert_free(ocsp->signer); } /** * Free a hx509 revokation context. * * @param ctx context to be freed * * @ingroup hx509_revoke */ void hx509_revoke_free(hx509_revoke_ctx *ctx) { size_t i ; if (ctx == NULL || *ctx == NULL) return; if ((*ctx)->ref == 0) _hx509_abort("revoke ctx refcount == 0 on free"); if (--(*ctx)->ref > 0) return; for (i = 0; i < (*ctx)->crls.len; i++) { free((*ctx)->crls.val[i].path); free_CRLCertificateList(&(*ctx)->crls.val[i].crl); } for (i = 0; i < (*ctx)->ocsps.len; i++) free_ocsp(&(*ctx)->ocsps.val[i]); free((*ctx)->ocsps.val); free((*ctx)->crls.val); memset(*ctx, 0, sizeof(**ctx)); free(*ctx); *ctx = NULL; } static int verify_ocsp(hx509_context context, struct revoke_ocsp *ocsp, time_t time_now, hx509_certs certs, hx509_cert parent) { hx509_cert signer = NULL; hx509_query q; int ret; _hx509_query_clear(&q); /* * Need to match on issuer too in case there are two CA that have * issued the same name to a certificate. One example of this is * the www.openvalidation.org test's ocsp validator. */ q.match = HX509_QUERY_MATCH_ISSUER_NAME; q.issuer_name = &_hx509_get_cert(parent)->tbsCertificate.issuer; switch(ocsp->ocsp.tbsResponseData.responderID.element) { case choice_OCSPResponderID_byName: q.match |= HX509_QUERY_MATCH_SUBJECT_NAME; q.subject_name = &ocsp->ocsp.tbsResponseData.responderID.u.byName; break; case choice_OCSPResponderID_byKey: q.match |= HX509_QUERY_MATCH_KEY_HASH_SHA1; q.keyhash_sha1 = &ocsp->ocsp.tbsResponseData.responderID.u.byKey; break; } ret = hx509_certs_find(context, certs, &q, &signer); if (ret && ocsp->certs) ret = hx509_certs_find(context, ocsp->certs, &q, &signer); if (ret) goto out; /* * If signer certificate isn't the CA certificate, lets check the * it is the CA that signed the signer certificate and the OCSP EKU * is set. */ if (hx509_cert_cmp(signer, parent) != 0) { Certificate *p = _hx509_get_cert(parent); Certificate *s = _hx509_get_cert(signer); ret = _hx509_cert_is_parent_cmp(s, p, 0); if (ret != 0) { ret = HX509_PARENT_NOT_CA; hx509_set_error_string(context, 0, ret, "Revoke OCSP signer is " "doesn't have CA as signer certificate"); goto out; } ret = _hx509_verify_signature_bitstring(context, parent, &s->signatureAlgorithm, &s->tbsCertificate._save, &s->signatureValue); if (ret) { hx509_set_error_string(context, HX509_ERROR_APPEND, ret, "OCSP signer signature invalid"); goto out; } ret = hx509_cert_check_eku(context, signer, &asn1_oid_id_pkix_kp_OCSPSigning, 0); if (ret) goto out; } ret = _hx509_verify_signature_bitstring(context, signer, &ocsp->ocsp.signatureAlgorithm, &ocsp->ocsp.tbsResponseData._save, &ocsp->ocsp.signature); if (ret) { hx509_set_error_string(context, HX509_ERROR_APPEND, ret, "OCSP signature invalid"); goto out; } ocsp->signer = signer; signer = NULL; out: if (signer) hx509_cert_free(signer); return ret; } /* * */ static int parse_ocsp_basic(const void *data, size_t length, OCSPBasicOCSPResponse *basic) { OCSPResponse resp; size_t size; int ret; memset(basic, 0, sizeof(*basic)); ret = decode_OCSPResponse(data, length, &resp, &size); if (ret) return ret; if (length != size) { free_OCSPResponse(&resp); return ASN1_EXTRA_DATA; } switch (resp.responseStatus) { case successful: break; default: free_OCSPResponse(&resp); return HX509_REVOKE_WRONG_DATA; } if (resp.responseBytes == NULL) { free_OCSPResponse(&resp); return EINVAL; } ret = der_heim_oid_cmp(&resp.responseBytes->responseType, &asn1_oid_id_pkix_ocsp_basic); if (ret != 0) { free_OCSPResponse(&resp); return HX509_REVOKE_WRONG_DATA; } ret = decode_OCSPBasicOCSPResponse(resp.responseBytes->response.data, resp.responseBytes->response.length, basic, &size); if (ret) { free_OCSPResponse(&resp); return ret; } if (size != resp.responseBytes->response.length) { free_OCSPResponse(&resp); free_OCSPBasicOCSPResponse(basic); return ASN1_EXTRA_DATA; } free_OCSPResponse(&resp); return 0; } /* * */ static int load_ocsp(hx509_context context, struct revoke_ocsp *ocsp) { OCSPBasicOCSPResponse basic; hx509_certs certs = NULL; size_t length; struct stat sb; void *data; int ret; ret = rk_undumpdata(ocsp->path, &data, &length); if (ret) return ret; ret = stat(ocsp->path, &sb); if (ret) { rk_xfree(data); return errno; } ret = parse_ocsp_basic(data, length, &basic); rk_xfree(data); if (ret) { hx509_set_error_string(context, 0, ret, "Failed to parse OCSP response"); return ret; } if (basic.certs) { size_t i; ret = hx509_certs_init(context, "MEMORY:ocsp-certs", 0, NULL, &certs); if (ret) { free_OCSPBasicOCSPResponse(&basic); return ret; } for (i = 0; i < basic.certs->len; i++) { hx509_cert c; c = hx509_cert_init(context, &basic.certs->val[i], NULL); if (c == NULL) continue; ret = hx509_certs_add(context, certs, c); hx509_cert_free(c); if (ret) continue; } } ocsp->last_modfied = sb.st_mtime; free_OCSPBasicOCSPResponse(&ocsp->ocsp); hx509_certs_free(&ocsp->certs); hx509_cert_free(ocsp->signer); ocsp->ocsp = basic; ocsp->certs = certs; ocsp->signer = NULL; return 0; } /** * Add a OCSP file to the revokation context. * * @param context hx509 context * @param ctx hx509 revokation context * @param path path to file that is going to be added to the context. * * @return An hx509 error code, see hx509_get_error_string(). * * @ingroup hx509_revoke */ int hx509_revoke_add_ocsp(hx509_context context, hx509_revoke_ctx ctx, const char *path) { void *data; int ret; size_t i; if (strncmp(path, "FILE:", 5) != 0) { hx509_set_error_string(context, 0, HX509_UNSUPPORTED_OPERATION, "unsupport type in %s", path); return HX509_UNSUPPORTED_OPERATION; } path += 5; for (i = 0; i < ctx->ocsps.len; i++) { if (strcmp(ctx->ocsps.val[0].path, path) == 0) return 0; } data = realloc(ctx->ocsps.val, (ctx->ocsps.len + 1) * sizeof(ctx->ocsps.val[0])); if (data == NULL) { hx509_clear_error_string(context); return ENOMEM; } ctx->ocsps.val = data; memset(&ctx->ocsps.val[ctx->ocsps.len], 0, sizeof(ctx->ocsps.val[0])); ctx->ocsps.val[ctx->ocsps.len].path = strdup(path); if (ctx->ocsps.val[ctx->ocsps.len].path == NULL) { hx509_clear_error_string(context); return ENOMEM; } ret = load_ocsp(context, &ctx->ocsps.val[ctx->ocsps.len]); if (ret) { free(ctx->ocsps.val[ctx->ocsps.len].path); return ret; } ctx->ocsps.len++; return ret; } /* * */ static int verify_crl(hx509_context context, hx509_revoke_ctx ctx, CRLCertificateList *crl, time_t time_now, hx509_certs certs, hx509_cert parent) { hx509_cert signer; hx509_query q; time_t t; int ret; t = _hx509_Time2time_t(&crl->tbsCertList.thisUpdate); if (t > time_now) { hx509_set_error_string(context, 0, HX509_CRL_USED_BEFORE_TIME, "CRL used before time"); return HX509_CRL_USED_BEFORE_TIME; } if (crl->tbsCertList.nextUpdate == NULL) { hx509_set_error_string(context, 0, HX509_CRL_INVALID_FORMAT, "CRL missing nextUpdate"); return HX509_CRL_INVALID_FORMAT; } t = _hx509_Time2time_t(crl->tbsCertList.nextUpdate); if (t < time_now) { hx509_set_error_string(context, 0, HX509_CRL_USED_AFTER_TIME, "CRL used after time"); return HX509_CRL_USED_AFTER_TIME; } _hx509_query_clear(&q); /* * If it's the signer have CRLSIGN bit set, use that as the signer * cert for the certificate, otherwise, search for a certificate. */ if (_hx509_check_key_usage(context, parent, 1 << 6, FALSE) == 0) { signer = hx509_cert_ref(parent); } else { q.match = HX509_QUERY_MATCH_SUBJECT_NAME; q.match |= HX509_QUERY_KU_CRLSIGN; q.subject_name = &crl->tbsCertList.issuer; ret = hx509_certs_find(context, certs, &q, &signer); if (ret) { hx509_set_error_string(context, HX509_ERROR_APPEND, ret, "Failed to find certificate for CRL"); return ret; } } ret = _hx509_verify_signature_bitstring(context, signer, &crl->signatureAlgorithm, &crl->tbsCertList._save, &crl->signatureValue); if (ret) { hx509_set_error_string(context, HX509_ERROR_APPEND, ret, "CRL signature invalid"); goto out; } /* * If signer is not CA cert, need to check revoke status of this * CRL signing cert too, this include all parent CRL signer cert * up to the root *sigh*, assume root at least hve CERTSIGN flag * set. */ while (_hx509_check_key_usage(context, signer, 1 << 5, TRUE)) { hx509_cert crl_parent; _hx509_query_clear(&q); q.match = HX509_QUERY_MATCH_SUBJECT_NAME; q.match |= HX509_QUERY_KU_CRLSIGN; q.subject_name = &_hx509_get_cert(signer)->tbsCertificate.issuer; ret = hx509_certs_find(context, certs, &q, &crl_parent); if (ret) { hx509_set_error_string(context, HX509_ERROR_APPEND, ret, "Failed to find parent of CRL signer"); goto out; } ret = hx509_revoke_verify(context, ctx, certs, time_now, signer, crl_parent); hx509_cert_free(signer); signer = crl_parent; if (ret) { hx509_set_error_string(context, HX509_ERROR_APPEND, ret, "Failed to verify revoke " "status of CRL signer"); goto out; } } out: hx509_cert_free(signer); return ret; } static int crl_parser(hx509_context context, const char *type, const hx509_pem_header *header, const void *data, size_t len, void *ctx) { CRLCertificateList *crl = (CRLCertificateList *)ctx; size_t size; int ret; if (strcasecmp("X509 CRL", type) != 0) return HX509_CRYPTO_SIG_INVALID_FORMAT; ret = decode_CRLCertificateList(data, len, crl, &size); if (ret) return ret; /* check signature is aligned */ if (crl->signatureValue.length & 7) { free_CRLCertificateList(crl); return HX509_CRYPTO_SIG_INVALID_FORMAT; } return 0; } static int load_crl(hx509_context context, const char *path, time_t *t, CRLCertificateList *crl) { struct stat sb; size_t length; void *data; FILE *f; int ret; memset(crl, 0, sizeof(*crl)); ret = stat(path, &sb); if (ret) return errno; *t = sb.st_mtime; if ((f = fopen(path, "r")) == NULL) return errno; rk_cloexec_file(f); ret = hx509_pem_read(context, f, crl_parser, crl); fclose(f); if (ret == HX509_PARSING_KEY_FAILED) { ret = rk_undumpdata(path, &data, &length); if (ret) return ret; ret = crl_parser(context, "X509 CRL", NULL, data, length, crl); rk_xfree(data); } return ret; } /** * Add a CRL file to the revokation context. * * @param context hx509 context * @param ctx hx509 revokation context * @param path path to file that is going to be added to the context. * * @return An hx509 error code, see hx509_get_error_string(). * * @ingroup hx509_revoke */ int hx509_revoke_add_crl(hx509_context context, hx509_revoke_ctx ctx, const char *path) { void *data; size_t i; int ret; if (strncmp(path, "FILE:", 5) != 0) { hx509_set_error_string(context, 0, HX509_UNSUPPORTED_OPERATION, "unsupport type in %s", path); return HX509_UNSUPPORTED_OPERATION; } path += 5; for (i = 0; i < ctx->crls.len; i++) { if (strcmp(ctx->crls.val[i].path, path) == 0) return 0; } data = realloc(ctx->crls.val, (ctx->crls.len + 1) * sizeof(ctx->crls.val[0])); if (data == NULL) { hx509_clear_error_string(context); return ENOMEM; } ctx->crls.val = data; memset(&ctx->crls.val[ctx->crls.len], 0, sizeof(ctx->crls.val[0])); ctx->crls.val[ctx->crls.len].path = strdup(path); if (ctx->crls.val[ctx->crls.len].path == NULL) { hx509_clear_error_string(context); return ENOMEM; } ret = load_crl(context, path, &ctx->crls.val[ctx->crls.len].last_modfied, &ctx->crls.val[ctx->crls.len].crl); if (ret) { free(ctx->crls.val[ctx->crls.len].path); return ret; } ctx->crls.len++; return ret; } /** * Check that a certificate is not expired according to a revokation * context. Also need the parent certificte to the check OCSP * parent identifier. * * @param context hx509 context * @param ctx hx509 revokation context * @param certs * @param now * @param cert * @param parent_cert * * @return An hx509 error code, see hx509_get_error_string(). * * @ingroup hx509_revoke */ int hx509_revoke_verify(hx509_context context, hx509_revoke_ctx ctx, hx509_certs certs, time_t now, hx509_cert cert, hx509_cert parent_cert) { const Certificate *c = _hx509_get_cert(cert); const Certificate *p = _hx509_get_cert(parent_cert); unsigned long i, j, k; int ret; hx509_clear_error_string(context); for (i = 0; i < ctx->ocsps.len; i++) { struct revoke_ocsp *ocsp = &ctx->ocsps.val[i]; struct stat sb; /* check this ocsp apply to this cert */ /* check if there is a newer version of the file */ ret = stat(ocsp->path, &sb); if (ret == 0 && ocsp->last_modfied != sb.st_mtime) { ret = load_ocsp(context, ocsp); if (ret) continue; } /* verify signature in ocsp if not already done */ if (ocsp->signer == NULL) { ret = verify_ocsp(context, ocsp, now, certs, parent_cert); if (ret) continue; } for (j = 0; j < ocsp->ocsp.tbsResponseData.responses.len; j++) { heim_octet_string os; ret = der_heim_integer_cmp(&ocsp->ocsp.tbsResponseData.responses.val[j].certID.serialNumber, &c->tbsCertificate.serialNumber); if (ret != 0) continue; /* verify issuer hashes hash */ ret = _hx509_verify_signature(context, NULL, &ocsp->ocsp.tbsResponseData.responses.val[i].certID.hashAlgorithm, &c->tbsCertificate.issuer._save, &ocsp->ocsp.tbsResponseData.responses.val[i].certID.issuerNameHash); if (ret != 0) continue; os.data = p->tbsCertificate.subjectPublicKeyInfo.subjectPublicKey.data; os.length = p->tbsCertificate.subjectPublicKeyInfo.subjectPublicKey.length / 8; ret = _hx509_verify_signature(context, NULL, &ocsp->ocsp.tbsResponseData.responses.val[j].certID.hashAlgorithm, &os, &ocsp->ocsp.tbsResponseData.responses.val[j].certID.issuerKeyHash); if (ret != 0) continue; switch (ocsp->ocsp.tbsResponseData.responses.val[j].certStatus.element) { case choice_OCSPCertStatus_good: break; case choice_OCSPCertStatus_revoked: hx509_set_error_string(context, 0, HX509_CERT_REVOKED, "Certificate revoked by issuer in OCSP"); return HX509_CERT_REVOKED; case choice_OCSPCertStatus_unknown: continue; } /* don't allow the update to be in the future */ if (ocsp->ocsp.tbsResponseData.responses.val[j].thisUpdate > now + context->ocsp_time_diff) continue; /* don't allow the next update to be in the past */ if (ocsp->ocsp.tbsResponseData.responses.val[j].nextUpdate) { if (*ocsp->ocsp.tbsResponseData.responses.val[j].nextUpdate < now) continue; } /* else should force a refetch, but can we ? */ return 0; } } for (i = 0; i < ctx->crls.len; i++) { struct revoke_crl *crl = &ctx->crls.val[i]; struct stat sb; int diff; /* check if cert.issuer == crls.val[i].crl.issuer */ ret = _hx509_name_cmp(&c->tbsCertificate.issuer, &crl->crl.tbsCertList.issuer, &diff); if (ret || diff) continue; ret = stat(crl->path, &sb); if (ret == 0 && crl->last_modfied != sb.st_mtime) { CRLCertificateList cl; ret = load_crl(context, crl->path, &crl->last_modfied, &cl); if (ret == 0) { free_CRLCertificateList(&crl->crl); crl->crl = cl; crl->verified = 0; crl->failed_verify = 0; } } if (crl->failed_verify) continue; /* verify signature in crl if not already done */ if (crl->verified == 0) { ret = verify_crl(context, ctx, &crl->crl, now, certs, parent_cert); if (ret) { crl->failed_verify = 1; continue; } crl->verified = 1; } if (crl->crl.tbsCertList.crlExtensions) { for (j = 0; j < crl->crl.tbsCertList.crlExtensions->len; j++) { if (crl->crl.tbsCertList.crlExtensions->val[j].critical) { hx509_set_error_string(context, 0, HX509_CRL_UNKNOWN_EXTENSION, "Unknown CRL extension"); return HX509_CRL_UNKNOWN_EXTENSION; } } } if (crl->crl.tbsCertList.revokedCertificates == NULL) return 0; /* check if cert is in crl */ for (j = 0; j < crl->crl.tbsCertList.revokedCertificates->len; j++) { time_t t; ret = der_heim_integer_cmp(&crl->crl.tbsCertList.revokedCertificates->val[j].userCertificate, &c->tbsCertificate.serialNumber); if (ret != 0) continue; t = _hx509_Time2time_t(&crl->crl.tbsCertList.revokedCertificates->val[j].revocationDate); if (t > now) continue; if (crl->crl.tbsCertList.revokedCertificates->val[j].crlEntryExtensions) for (k = 0; k < crl->crl.tbsCertList.revokedCertificates->val[j].crlEntryExtensions->len; k++) if (crl->crl.tbsCertList.revokedCertificates->val[j].crlEntryExtensions->val[k].critical) return HX509_CRL_UNKNOWN_EXTENSION; hx509_set_error_string(context, 0, HX509_CERT_REVOKED, "Certificate revoked by issuer in CRL"); return HX509_CERT_REVOKED; } return 0; } if (context->flags & HX509_CTX_VERIFY_MISSING_OK) return 0; hx509_set_error_string(context, HX509_ERROR_APPEND, HX509_REVOKE_STATUS_MISSING, "No revoke status found for " "certificates"); return HX509_REVOKE_STATUS_MISSING; } struct ocsp_add_ctx { OCSPTBSRequest *req; hx509_certs certs; const AlgorithmIdentifier *digest; hx509_cert parent; }; static int add_to_req(hx509_context context, void *ptr, hx509_cert cert) { struct ocsp_add_ctx *ctx = ptr; OCSPInnerRequest *one; hx509_cert parent = NULL; Certificate *p, *c = _hx509_get_cert(cert); heim_octet_string os; int ret; hx509_query q; void *d; d = realloc(ctx->req->requestList.val, sizeof(ctx->req->requestList.val[0]) * (ctx->req->requestList.len + 1)); if (d == NULL) return ENOMEM; ctx->req->requestList.val = d; one = &ctx->req->requestList.val[ctx->req->requestList.len]; memset(one, 0, sizeof(*one)); _hx509_query_clear(&q); q.match |= HX509_QUERY_FIND_ISSUER_CERT; q.subject = c; ret = hx509_certs_find(context, ctx->certs, &q, &parent); if (ret) goto out; if (ctx->parent) { if (hx509_cert_cmp(ctx->parent, parent) != 0) { ret = HX509_REVOKE_NOT_SAME_PARENT; hx509_set_error_string(context, 0, ret, "Not same parent certifate as " "last certificate in request"); goto out; } } else ctx->parent = hx509_cert_ref(parent); p = _hx509_get_cert(parent); ret = copy_AlgorithmIdentifier(ctx->digest, &one->reqCert.hashAlgorithm); if (ret) goto out; ret = _hx509_create_signature(context, NULL, &one->reqCert.hashAlgorithm, &c->tbsCertificate.issuer._save, NULL, &one->reqCert.issuerNameHash); if (ret) goto out; os.data = p->tbsCertificate.subjectPublicKeyInfo.subjectPublicKey.data; os.length = p->tbsCertificate.subjectPublicKeyInfo.subjectPublicKey.length / 8; ret = _hx509_create_signature(context, NULL, &one->reqCert.hashAlgorithm, &os, NULL, &one->reqCert.issuerKeyHash); if (ret) goto out; ret = copy_CertificateSerialNumber(&c->tbsCertificate.serialNumber, &one->reqCert.serialNumber); if (ret) goto out; ctx->req->requestList.len++; out: hx509_cert_free(parent); if (ret) { free_OCSPInnerRequest(one); memset(one, 0, sizeof(*one)); } return ret; } /** * Create an OCSP request for a set of certificates. * * @param context a hx509 context * @param reqcerts list of certificates to request ocsp data for * @param pool certificate pool to use when signing * @param signer certificate to use to sign the request * @param digest the signing algorithm in the request, if NULL use the * default signature algorithm, * @param request the encoded request, free with free_heim_octet_string(). * @param nonce nonce in the request, free with free_heim_octet_string(). * * @return An hx509 error code, see hx509_get_error_string(). * * @ingroup hx509_revoke */ int hx509_ocsp_request(hx509_context context, hx509_certs reqcerts, hx509_certs pool, hx509_cert signer, const AlgorithmIdentifier *digest, heim_octet_string *request, heim_octet_string *nonce) { OCSPRequest req; size_t size; int ret; struct ocsp_add_ctx ctx; Extensions *es; memset(&req, 0, sizeof(req)); if (digest == NULL) digest = _hx509_crypto_default_digest_alg; ctx.req = &req.tbsRequest; ctx.certs = pool; ctx.digest = digest; ctx.parent = NULL; ret = hx509_certs_iter_f(context, reqcerts, add_to_req, &ctx); hx509_cert_free(ctx.parent); if (ret) goto out; if (nonce) { req.tbsRequest.requestExtensions = calloc(1, sizeof(*req.tbsRequest.requestExtensions)); if (req.tbsRequest.requestExtensions == NULL) { ret = ENOMEM; goto out; } es = req.tbsRequest.requestExtensions; es->val = calloc(es->len, sizeof(es->val[0])); if (es->val == NULL) { ret = ENOMEM; goto out; } es->len = 1; ret = der_copy_oid(&asn1_oid_id_pkix_ocsp_nonce, &es->val[0].extnID); if (ret) { free_OCSPRequest(&req); return ret; } es->val[0].extnValue.data = malloc(10); if (es->val[0].extnValue.data == NULL) { ret = ENOMEM; goto out; } es->val[0].extnValue.length = 10; ret = RAND_bytes(es->val[0].extnValue.data, es->val[0].extnValue.length); if (ret != 1) { ret = HX509_CRYPTO_INTERNAL_ERROR; goto out; } ret = der_copy_octet_string(nonce, &es->val[0].extnValue); if (ret) { ret = ENOMEM; goto out; } } ASN1_MALLOC_ENCODE(OCSPRequest, request->data, request->length, &req, &size, ret); free_OCSPRequest(&req); if (ret) goto out; if (size != request->length) _hx509_abort("internal ASN.1 encoder error"); return 0; out: free_OCSPRequest(&req); return ret; } static char * printable_time(time_t t) { static char s[128]; char *p; if ((p = ctime(&t)) == NULL) strlcpy(s, "?", sizeof(s)); else { strlcpy(s, p + 4, sizeof(s)); s[20] = 0; } return s; } /* * */ static int print_ocsp(hx509_context context, struct revoke_ocsp *ocsp, FILE *out) { int ret = 0; size_t i; fprintf(out, "signer: "); switch(ocsp->ocsp.tbsResponseData.responderID.element) { case choice_OCSPResponderID_byName: { hx509_name n; char *s; _hx509_name_from_Name(&ocsp->ocsp.tbsResponseData.responderID.u.byName, &n); hx509_name_to_string(n, &s); hx509_name_free(&n); fprintf(out, " byName: %s\n", s); free(s); break; } case choice_OCSPResponderID_byKey: { char *s; hex_encode(ocsp->ocsp.tbsResponseData.responderID.u.byKey.data, ocsp->ocsp.tbsResponseData.responderID.u.byKey.length, &s); fprintf(out, " byKey: %s\n", s); free(s); break; } default: _hx509_abort("choice_OCSPResponderID unknown"); break; } fprintf(out, "producedAt: %s\n", printable_time(ocsp->ocsp.tbsResponseData.producedAt)); fprintf(out, "replies: %d\n", ocsp->ocsp.tbsResponseData.responses.len); for (i = 0; i < ocsp->ocsp.tbsResponseData.responses.len; i++) { const char *status; switch (ocsp->ocsp.tbsResponseData.responses.val[i].certStatus.element) { case choice_OCSPCertStatus_good: status = "good"; break; case choice_OCSPCertStatus_revoked: status = "revoked"; break; case choice_OCSPCertStatus_unknown: status = "unknown"; break; default: status = "element unknown"; } fprintf(out, "\t%llu. status: %s\n", (unsigned long long)i, status); fprintf(out, "\tthisUpdate: %s\n", printable_time(ocsp->ocsp.tbsResponseData.responses.val[i].thisUpdate)); if (ocsp->ocsp.tbsResponseData.responses.val[i].nextUpdate) fprintf(out, "\tproducedAt: %s\n", printable_time(ocsp->ocsp.tbsResponseData.responses.val[i].thisUpdate)); } fprintf(out, "appended certs:\n"); if (ocsp->certs) ret = hx509_certs_iter_f(context, ocsp->certs, hx509_ci_print_names, out); return ret; } static int print_crl(hx509_context context, struct revoke_crl *crl, FILE *out) { { hx509_name n; char *s; _hx509_name_from_Name(&crl->crl.tbsCertList.issuer, &n); hx509_name_to_string(n, &s); hx509_name_free(&n); fprintf(out, " issuer: %s\n", s); free(s); } fprintf(out, " thisUpdate: %s\n", printable_time(_hx509_Time2time_t(&crl->crl.tbsCertList.thisUpdate))); return 0; } /* * */ int hx509_revoke_print(hx509_context context, hx509_revoke_ctx ctx, FILE *out) { int saved_ret = 0, ret; size_t n; for (n = 0; n < ctx->ocsps.len; n++) { struct revoke_ocsp *ocsp = &ctx->ocsps.val[n]; fprintf(out, "OCSP %s\n", ocsp->path); ret = print_ocsp(context, ocsp, out); if (ret) { fprintf(out, "failure printing OCSP: %d\n", ret); saved_ret = ret; } } for (n = 0; n < ctx->crls.len; n++) { struct revoke_crl *crl = &ctx->crls.val[n]; fprintf(out, "CRL %s\n", crl->path); ret = print_crl(context, crl, out); if (ret) { fprintf(out, "failure printing CRL: %d\n", ret); saved_ret = ret; } } return saved_ret; } /** * Print the OCSP reply stored in a file. * * @param context a hx509 context * @param path path to a file with a OCSP reply * @param out the out FILE descriptor to print the reply on * * @return An hx509 error code, see hx509_get_error_string(). * * @ingroup hx509_revoke */ int hx509_revoke_ocsp_print(hx509_context context, const char *path, FILE *out) { struct revoke_ocsp ocsp; int ret; if (out == NULL) out = stdout; memset(&ocsp, 0, sizeof(ocsp)); ocsp.path = strdup(path); if (ocsp.path == NULL) return ENOMEM; ret = load_ocsp(context, &ocsp); if (ret) { free_ocsp(&ocsp); return ret; } ret = print_ocsp(context, &ocsp, out); free_ocsp(&ocsp); return ret; } /** * Verify that the certificate is part of the OCSP reply and it's not * expired. Doesn't verify signature the OCSP reply or it's done by a * authorized sender, that is assumed to be already done. * * @param context a hx509 context * @param now the time right now, if 0, use the current time. * @param cert the certificate to verify * @param flags flags control the behavior * @param data pointer to the encode ocsp reply * @param length the length of the encode ocsp reply * @param expiration return the time the OCSP will expire and need to * be rechecked. * * @return An hx509 error code, see hx509_get_error_string(). * * @ingroup hx509_verify */ int hx509_ocsp_verify(hx509_context context, time_t now, hx509_cert cert, int flags, const void *data, size_t length, time_t *expiration) { const Certificate *c = _hx509_get_cert(cert); OCSPBasicOCSPResponse basic; int ret; size_t i; if (now == 0) now = time(NULL); *expiration = 0; ret = parse_ocsp_basic(data, length, &basic); if (ret) { hx509_set_error_string(context, 0, ret, "Failed to parse OCSP response"); return ret; } for (i = 0; i < basic.tbsResponseData.responses.len; i++) { ret = der_heim_integer_cmp(&basic.tbsResponseData.responses.val[i].certID.serialNumber, &c->tbsCertificate.serialNumber); if (ret != 0) continue; /* verify issuer hashes hash */ ret = _hx509_verify_signature(context, NULL, &basic.tbsResponseData.responses.val[i].certID.hashAlgorithm, &c->tbsCertificate.issuer._save, &basic.tbsResponseData.responses.val[i].certID.issuerNameHash); if (ret != 0) continue; switch (basic.tbsResponseData.responses.val[i].certStatus.element) { case choice_OCSPCertStatus_good: break; case choice_OCSPCertStatus_revoked: case choice_OCSPCertStatus_unknown: continue; } /* don't allow the update to be in the future */ if (basic.tbsResponseData.responses.val[i].thisUpdate > now + context->ocsp_time_diff) continue; /* don't allow the next update to be in the past */ if (basic.tbsResponseData.responses.val[i].nextUpdate) { if (*basic.tbsResponseData.responses.val[i].nextUpdate < now) continue; *expiration = *basic.tbsResponseData.responses.val[i].nextUpdate; } else *expiration = now; free_OCSPBasicOCSPResponse(&basic); return 0; } free_OCSPBasicOCSPResponse(&basic); { hx509_name name; char *subject; ret = hx509_cert_get_subject(cert, &name); if (ret) { hx509_clear_error_string(context); goto out; } ret = hx509_name_to_string(name, &subject); hx509_name_free(&name); if (ret) { hx509_clear_error_string(context); goto out; } hx509_set_error_string(context, 0, HX509_CERT_NOT_IN_OCSP, "Certificate %s not in OCSP response " "or not good", subject); free(subject); } out: return HX509_CERT_NOT_IN_OCSP; } struct hx509_crl { hx509_certs revoked; time_t expire; }; /** * Create a CRL context. Use hx509_crl_free() to free the CRL context. * * @param context a hx509 context. * @param crl return pointer to a newly allocated CRL context. * * @return An hx509 error code, see hx509_get_error_string(). * * @ingroup hx509_verify */ int hx509_crl_alloc(hx509_context context, hx509_crl *crl) { int ret; *crl = calloc(1, sizeof(**crl)); if (*crl == NULL) { hx509_set_error_string(context, 0, ENOMEM, "out of memory"); return ENOMEM; } ret = hx509_certs_init(context, "MEMORY:crl", 0, NULL, &(*crl)->revoked); if (ret) { free(*crl); *crl = NULL; return ret; } (*crl)->expire = 0; return ret; } /** * Add revoked certificate to an CRL context. * * @param context a hx509 context. * @param crl the CRL to add the revoked certificate to. * @param certs keyset of certificate to revoke. * * @return An hx509 error code, see hx509_get_error_string(). * * @ingroup hx509_verify */ int hx509_crl_add_revoked_certs(hx509_context context, hx509_crl crl, hx509_certs certs) { return hx509_certs_merge(context, crl->revoked, certs); } /** * Set the lifetime of a CRL context. * * @param context a hx509 context. * @param crl a CRL context * @param delta delta time the certificate is valid, library adds the * current time to this. * * @return An hx509 error code, see hx509_get_error_string(). * * @ingroup hx509_verify */ int hx509_crl_lifetime(hx509_context context, hx509_crl crl, int delta) { crl->expire = time(NULL) + delta; return 0; } /** * Free a CRL context. * * @param context a hx509 context. * @param crl a CRL context to free. * * @ingroup hx509_verify */ void hx509_crl_free(hx509_context context, hx509_crl *crl) { if (*crl == NULL) return; hx509_certs_free(&(*crl)->revoked); memset(*crl, 0, sizeof(**crl)); free(*crl); *crl = NULL; } static int add_revoked(hx509_context context, void *ctx, hx509_cert cert) { TBSCRLCertList *c = ctx; unsigned int num; void *ptr; int ret; num = c->revokedCertificates->len; ptr = realloc(c->revokedCertificates->val, (num + 1) * sizeof(c->revokedCertificates->val[0])); if (ptr == NULL) { hx509_clear_error_string(context); return ENOMEM; } c->revokedCertificates->val = ptr; ret = hx509_cert_get_serialnumber(cert, &c->revokedCertificates->val[num].userCertificate); if (ret) { hx509_clear_error_string(context); return ret; } c->revokedCertificates->val[num].revocationDate.element = choice_Time_generalTime; c->revokedCertificates->val[num].revocationDate.u.generalTime = time(NULL) - 3600 * 24; c->revokedCertificates->val[num].crlEntryExtensions = NULL; c->revokedCertificates->len++; return 0; } /** * Sign a CRL and return an encode certificate. * * @param context a hx509 context. * @param signer certificate to sign the CRL with * @param crl the CRL to sign * @param os return the signed and encoded CRL, free with * free_heim_octet_string() * * @return An hx509 error code, see hx509_get_error_string(). * * @ingroup hx509_verify */ int hx509_crl_sign(hx509_context context, hx509_cert signer, hx509_crl crl, heim_octet_string *os) { const AlgorithmIdentifier *sigalg = _hx509_crypto_default_sig_alg; CRLCertificateList c; size_t size; int ret; hx509_private_key signerkey; memset(&c, 0, sizeof(c)); signerkey = _hx509_cert_private_key(signer); if (signerkey == NULL) { ret = HX509_PRIVATE_KEY_MISSING; hx509_set_error_string(context, 0, ret, "Private key missing for CRL signing"); return ret; } c.tbsCertList.version = malloc(sizeof(*c.tbsCertList.version)); if (c.tbsCertList.version == NULL) { hx509_set_error_string(context, 0, ENOMEM, "out of memory"); return ENOMEM; } *c.tbsCertList.version = 1; ret = copy_AlgorithmIdentifier(sigalg, &c.tbsCertList.signature); if (ret) { hx509_clear_error_string(context); goto out; } ret = copy_Name(&_hx509_get_cert(signer)->tbsCertificate.issuer, &c.tbsCertList.issuer); if (ret) { hx509_clear_error_string(context); goto out; } c.tbsCertList.thisUpdate.element = choice_Time_generalTime; c.tbsCertList.thisUpdate.u.generalTime = time(NULL) - 24 * 3600; c.tbsCertList.nextUpdate = malloc(sizeof(*c.tbsCertList.nextUpdate)); if (c.tbsCertList.nextUpdate == NULL) { hx509_set_error_string(context, 0, ENOMEM, "out of memory"); ret = ENOMEM; goto out; } { time_t next = crl->expire; if (next == 0) next = time(NULL) + 24 * 3600 * 365; c.tbsCertList.nextUpdate->element = choice_Time_generalTime; c.tbsCertList.nextUpdate->u.generalTime = next; } c.tbsCertList.revokedCertificates = calloc(1, sizeof(*c.tbsCertList.revokedCertificates)); if (c.tbsCertList.revokedCertificates == NULL) { hx509_set_error_string(context, 0, ENOMEM, "out of memory"); ret = ENOMEM; goto out; } c.tbsCertList.crlExtensions = NULL; ret = hx509_certs_iter_f(context, crl->revoked, add_revoked, &c.tbsCertList); if (ret) goto out; /* if not revoked certs, remove OPTIONAL entry */ if (c.tbsCertList.revokedCertificates->len == 0) { free(c.tbsCertList.revokedCertificates); c.tbsCertList.revokedCertificates = NULL; } ASN1_MALLOC_ENCODE(TBSCRLCertList, os->data, os->length, &c.tbsCertList, &size, ret); if (ret) { hx509_set_error_string(context, 0, ret, "failed to encode tbsCRL"); goto out; } if (size != os->length) _hx509_abort("internal ASN.1 encoder error"); ret = _hx509_create_signature_bitstring(context, signerkey, sigalg, os, &c.signatureAlgorithm, &c.signatureValue); free(os->data); if (ret) { hx509_set_error_string(context, 0, ret, "Failed to sign CRL"); goto out; } ASN1_MALLOC_ENCODE(CRLCertificateList, os->data, os->length, &c, &size, ret); if (ret) { hx509_set_error_string(context, 0, ret, "failed to encode CRL"); goto out; } if (size != os->length) _hx509_abort("internal ASN.1 encoder error"); free_CRLCertificateList(&c); return 0; out: free_CRLCertificateList(&c); return ret; } heimdal-7.5.0/lib/hx509/cert.c0000644000175000017500000024705613062303006014005 0ustar niknik/* * Copyright (c) 2004 - 2007 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "hx_locl.h" #include "crypto-headers.h" #include /** * @page page_cert The basic certificate * * The basic hx509 cerificate object in hx509 is hx509_cert. The * hx509_cert object is representing one X509/PKIX certificate and * associated attributes; like private key, friendly name, etc. * * A hx509_cert object is usully found via the keyset interfaces (@ref * page_keyset), but its also possible to create a certificate * directly from a parsed object with hx509_cert_init() and * hx509_cert_init_data(). * * See the library functions here: @ref hx509_cert */ struct hx509_verify_ctx_data { hx509_certs trust_anchors; int flags; #define HX509_VERIFY_CTX_F_TIME_SET 1 #define HX509_VERIFY_CTX_F_ALLOW_PROXY_CERTIFICATE 2 #define HX509_VERIFY_CTX_F_REQUIRE_RFC3280 4 #define HX509_VERIFY_CTX_F_CHECK_TRUST_ANCHORS 8 #define HX509_VERIFY_CTX_F_NO_DEFAULT_ANCHORS 16 #define HX509_VERIFY_CTX_F_NO_BEST_BEFORE_CHECK 32 time_t time_now; unsigned int max_depth; #define HX509_VERIFY_MAX_DEPTH 30 hx509_revoke_ctx revoke_ctx; }; #define REQUIRE_RFC3280(ctx) ((ctx)->flags & HX509_VERIFY_CTX_F_REQUIRE_RFC3280) #define CHECK_TA(ctx) ((ctx)->flags & HX509_VERIFY_CTX_F_CHECK_TRUST_ANCHORS) #define ALLOW_DEF_TA(ctx) (((ctx)->flags & HX509_VERIFY_CTX_F_NO_DEFAULT_ANCHORS) == 0) struct _hx509_cert_attrs { size_t len; hx509_cert_attribute *val; }; struct hx509_cert_data { unsigned int ref; char *friendlyname; Certificate *data; hx509_private_key private_key; struct _hx509_cert_attrs attrs; hx509_name basename; _hx509_cert_release_func release; void *ctx; }; typedef struct hx509_name_constraints { NameConstraints *val; size_t len; } hx509_name_constraints; #define GeneralSubtrees_SET(g,var) \ (g)->len = (var)->len, (g)->val = (var)->val; static void init_context_once(void *ignored) { ENGINE_add_conf_module(); OpenSSL_add_all_algorithms(); } /** * Creates a hx509 context that most functions in the library * uses. The context is only allowed to be used by one thread at each * moment. Free the context with hx509_context_free(). * * @param context Returns a pointer to new hx509 context. * * @return Returns an hx509 error code. * * @ingroup hx509 */ int hx509_context_init(hx509_context *context) { static heim_base_once_t init_context = HEIM_BASE_ONCE_INIT; *context = calloc(1, sizeof(**context)); if (*context == NULL) return ENOMEM; heim_base_once_f(&init_context, NULL, init_context_once); _hx509_ks_null_register(*context); _hx509_ks_mem_register(*context); _hx509_ks_file_register(*context); _hx509_ks_pkcs12_register(*context); _hx509_ks_pkcs11_register(*context); _hx509_ks_dir_register(*context); _hx509_ks_keychain_register(*context); (*context)->ocsp_time_diff = HX509_DEFAULT_OCSP_TIME_DIFF; initialize_hx_error_table_r(&(*context)->et_list); initialize_asn1_error_table_r(&(*context)->et_list); #ifdef HX509_DEFAULT_ANCHORS (void)hx509_certs_init(*context, HX509_DEFAULT_ANCHORS, 0, NULL, &(*context)->default_trust_anchors); #endif return 0; } /** * Selects if the hx509_revoke_verify() function is going to require * the existans of a revokation method (OCSP, CRL) or not. Note that * hx509_verify_path(), hx509_cms_verify_signed(), and other function * call hx509_revoke_verify(). * * @param context hx509 context to change the flag for. * @param flag zero, revokation method required, non zero missing * revokation method ok * * @ingroup hx509_verify */ void hx509_context_set_missing_revoke(hx509_context context, int flag) { if (flag) context->flags |= HX509_CTX_VERIFY_MISSING_OK; else context->flags &= ~HX509_CTX_VERIFY_MISSING_OK; } /** * Free the context allocated by hx509_context_init(). * * @param context context to be freed. * * @ingroup hx509 */ void hx509_context_free(hx509_context *context) { hx509_clear_error_string(*context); if ((*context)->ks_ops) { free((*context)->ks_ops); (*context)->ks_ops = NULL; } (*context)->ks_num_ops = 0; free_error_table ((*context)->et_list); if ((*context)->querystat) free((*context)->querystat); memset(*context, 0, sizeof(**context)); free(*context); *context = NULL; } /* * */ Certificate * _hx509_get_cert(hx509_cert cert) { return cert->data; } /* * */ int _hx509_cert_get_version(const Certificate *t) { return t->tbsCertificate.version ? *t->tbsCertificate.version + 1 : 1; } /** * Allocate and init an hx509 certificate object from the decoded * certificate `c´. * * @param context A hx509 context. * @param c * @param error * * @return Returns an hx509 certificate * * @ingroup hx509_cert */ hx509_cert hx509_cert_init(hx509_context context, const Certificate *c, heim_error_t *error) { hx509_cert cert; int ret; cert = malloc(sizeof(*cert)); if (cert == NULL) { if (error) *error = heim_error_create_enomem(); return NULL; } cert->ref = 1; cert->friendlyname = NULL; cert->attrs.len = 0; cert->attrs.val = NULL; cert->private_key = NULL; cert->basename = NULL; cert->release = NULL; cert->ctx = NULL; cert->data = calloc(1, sizeof(*(cert->data))); if (cert->data == NULL) { free(cert); if (error) *error = heim_error_create_enomem(); return NULL; } ret = copy_Certificate(c, cert->data); if (ret) { free(cert->data); free(cert); cert = NULL; } return cert; } /** * Just like hx509_cert_init(), but instead of a decode certificate * takes an pointer and length to a memory region that contains a * DER/BER encoded certificate. * * If the memory region doesn't contain just the certificate and * nothing more the function will fail with * HX509_EXTRA_DATA_AFTER_STRUCTURE. * * @param context A hx509 context. * @param ptr pointer to memory region containing encoded certificate. * @param len length of memory region. * @param error possibly returns an error * * @return An hx509 certificate * * @ingroup hx509_cert */ hx509_cert hx509_cert_init_data(hx509_context context, const void *ptr, size_t len, heim_error_t *error) { hx509_cert cert; Certificate t; size_t size; int ret; ret = decode_Certificate(ptr, len, &t, &size); if (ret) { if (error) *error = heim_error_create(ret, "Failed to decode certificate"); return NULL; } if (size != len) { free_Certificate(&t); if (error) *error = heim_error_create(HX509_EXTRA_DATA_AFTER_STRUCTURE, "Extra data after certificate"); return NULL; } cert = hx509_cert_init(context, &t, error); free_Certificate(&t); return cert; } void _hx509_cert_set_release(hx509_cert cert, _hx509_cert_release_func release, void *ctx) { cert->release = release; cert->ctx = ctx; } /* Doesn't make a copy of `private_key'. */ int _hx509_cert_assign_key(hx509_cert cert, hx509_private_key private_key) { if (cert->private_key) hx509_private_key_free(&cert->private_key); cert->private_key = _hx509_private_key_ref(private_key); return 0; } /** * Free reference to the hx509 certificate object, if the refcounter * reaches 0, the object if freed. Its allowed to pass in NULL. * * @param cert the cert to free. * * @ingroup hx509_cert */ void hx509_cert_free(hx509_cert cert) { size_t i; if (cert == NULL) return; if (cert->ref <= 0) _hx509_abort("cert refcount <= 0 on free"); if (--cert->ref > 0) return; if (cert->release) (cert->release)(cert, cert->ctx); if (cert->private_key) hx509_private_key_free(&cert->private_key); free_Certificate(cert->data); free(cert->data); for (i = 0; i < cert->attrs.len; i++) { der_free_octet_string(&cert->attrs.val[i]->data); der_free_oid(&cert->attrs.val[i]->oid); free(cert->attrs.val[i]); } free(cert->attrs.val); free(cert->friendlyname); if (cert->basename) hx509_name_free(&cert->basename); memset(cert, 0, sizeof(*cert)); free(cert); } /** * Add a reference to a hx509 certificate object. * * @param cert a pointer to an hx509 certificate object. * * @return the same object as is passed in. * * @ingroup hx509_cert */ hx509_cert hx509_cert_ref(hx509_cert cert) { if (cert == NULL) return NULL; if (cert->ref <= 0) _hx509_abort("cert refcount <= 0"); cert->ref++; if (cert->ref == 0) _hx509_abort("cert refcount == 0"); return cert; } /** * Allocate an verification context that is used fo control the * verification process. * * @param context A hx509 context. * @param ctx returns a pointer to a hx509_verify_ctx object. * * @return An hx509 error code, see hx509_get_error_string(). * * @ingroup hx509_verify */ int hx509_verify_init_ctx(hx509_context context, hx509_verify_ctx *ctx) { hx509_verify_ctx c; c = calloc(1, sizeof(*c)); if (c == NULL) return ENOMEM; c->max_depth = HX509_VERIFY_MAX_DEPTH; *ctx = c; return 0; } /** * Free an hx509 verification context. * * @param ctx the context to be freed. * * @ingroup hx509_verify */ void hx509_verify_destroy_ctx(hx509_verify_ctx ctx) { if (ctx) { hx509_certs_free(&ctx->trust_anchors); hx509_revoke_free(&ctx->revoke_ctx); memset(ctx, 0, sizeof(*ctx)); } free(ctx); } /** * Set the trust anchors in the verification context, makes an * reference to the keyset, so the consumer can free the keyset * independent of the destruction of the verification context (ctx). * If there already is a keyset attached, it's released. * * @param ctx a verification context * @param set a keyset containing the trust anchors. * * @ingroup hx509_verify */ void hx509_verify_attach_anchors(hx509_verify_ctx ctx, hx509_certs set) { if (ctx->trust_anchors) hx509_certs_free(&ctx->trust_anchors); ctx->trust_anchors = hx509_certs_ref(set); } /** * Attach an revocation context to the verfication context, , makes an * reference to the revoke context, so the consumer can free the * revoke context independent of the destruction of the verification * context. If there is no revoke context, the verification process is * NOT going to check any verification status. * * @param ctx a verification context. * @param revoke_ctx a revoke context. * * @ingroup hx509_verify */ void hx509_verify_attach_revoke(hx509_verify_ctx ctx, hx509_revoke_ctx revoke_ctx) { if (ctx->revoke_ctx) hx509_revoke_free(&ctx->revoke_ctx); ctx->revoke_ctx = _hx509_revoke_ref(revoke_ctx); } /** * Set the clock time the the verification process is going to * use. Used to check certificate in the past and future time. If not * set the current time will be used. * * @param ctx a verification context. * @param t the time the verifiation is using. * * * @ingroup hx509_verify */ void hx509_verify_set_time(hx509_verify_ctx ctx, time_t t) { ctx->flags |= HX509_VERIFY_CTX_F_TIME_SET; ctx->time_now = t; } time_t _hx509_verify_get_time(hx509_verify_ctx ctx) { return ctx->time_now; } /** * Set the maximum depth of the certificate chain that the path * builder is going to try. * * @param ctx a verification context * @param max_depth maxium depth of the certificate chain, include * trust anchor. * * @ingroup hx509_verify */ void hx509_verify_set_max_depth(hx509_verify_ctx ctx, unsigned int max_depth) { ctx->max_depth = max_depth; } /** * Allow or deny the use of proxy certificates * * @param ctx a verification context * @param boolean if non zero, allow proxy certificates. * * @ingroup hx509_verify */ void hx509_verify_set_proxy_certificate(hx509_verify_ctx ctx, int boolean) { if (boolean) ctx->flags |= HX509_VERIFY_CTX_F_ALLOW_PROXY_CERTIFICATE; else ctx->flags &= ~HX509_VERIFY_CTX_F_ALLOW_PROXY_CERTIFICATE; } /** * Select strict RFC3280 verification of certificiates. This means * checking key usage on CA certificates, this will make version 1 * certificiates unuseable. * * @param ctx a verification context * @param boolean if non zero, use strict verification. * * @ingroup hx509_verify */ void hx509_verify_set_strict_rfc3280_verification(hx509_verify_ctx ctx, int boolean) { if (boolean) ctx->flags |= HX509_VERIFY_CTX_F_REQUIRE_RFC3280; else ctx->flags &= ~HX509_VERIFY_CTX_F_REQUIRE_RFC3280; } /** * Allow using the operating system builtin trust anchors if no other * trust anchors are configured. * * @param ctx a verification context * @param boolean if non zero, useing the operating systems builtin * trust anchors. * * * @return An hx509 error code, see hx509_get_error_string(). * * @ingroup hx509_cert */ void hx509_verify_ctx_f_allow_default_trustanchors(hx509_verify_ctx ctx, int boolean) { if (boolean) ctx->flags &= ~HX509_VERIFY_CTX_F_NO_DEFAULT_ANCHORS; else ctx->flags |= HX509_VERIFY_CTX_F_NO_DEFAULT_ANCHORS; } void hx509_verify_ctx_f_allow_best_before_signature_algs(hx509_context ctx, int boolean) { if (boolean) ctx->flags &= ~HX509_VERIFY_CTX_F_NO_BEST_BEFORE_CHECK; else ctx->flags |= HX509_VERIFY_CTX_F_NO_BEST_BEFORE_CHECK; } static const Extension * find_extension(const Certificate *cert, const heim_oid *oid, size_t *idx) { const TBSCertificate *c = &cert->tbsCertificate; if (c->version == NULL || *c->version < 2 || c->extensions == NULL) return NULL; for (;*idx < c->extensions->len; (*idx)++) { if (der_heim_oid_cmp(&c->extensions->val[*idx].extnID, oid) == 0) return &c->extensions->val[(*idx)++]; } return NULL; } static int find_extension_auth_key_id(const Certificate *subject, AuthorityKeyIdentifier *ai) { const Extension *e; size_t size; size_t i = 0; memset(ai, 0, sizeof(*ai)); e = find_extension(subject, &asn1_oid_id_x509_ce_authorityKeyIdentifier, &i); if (e == NULL) return HX509_EXTENSION_NOT_FOUND; return decode_AuthorityKeyIdentifier(e->extnValue.data, e->extnValue.length, ai, &size); } int _hx509_find_extension_subject_key_id(const Certificate *issuer, SubjectKeyIdentifier *si) { const Extension *e; size_t size; size_t i = 0; memset(si, 0, sizeof(*si)); e = find_extension(issuer, &asn1_oid_id_x509_ce_subjectKeyIdentifier, &i); if (e == NULL) return HX509_EXTENSION_NOT_FOUND; return decode_SubjectKeyIdentifier(e->extnValue.data, e->extnValue.length, si, &size); } static int find_extension_name_constraints(const Certificate *subject, NameConstraints *nc) { const Extension *e; size_t size; size_t i = 0; memset(nc, 0, sizeof(*nc)); e = find_extension(subject, &asn1_oid_id_x509_ce_nameConstraints, &i); if (e == NULL) return HX509_EXTENSION_NOT_FOUND; return decode_NameConstraints(e->extnValue.data, e->extnValue.length, nc, &size); } static int find_extension_subject_alt_name(const Certificate *cert, size_t *i, GeneralNames *sa) { const Extension *e; size_t size; memset(sa, 0, sizeof(*sa)); e = find_extension(cert, &asn1_oid_id_x509_ce_subjectAltName, i); if (e == NULL) return HX509_EXTENSION_NOT_FOUND; return decode_GeneralNames(e->extnValue.data, e->extnValue.length, sa, &size); } static int find_extension_eku(const Certificate *cert, ExtKeyUsage *eku) { const Extension *e; size_t size; size_t i = 0; memset(eku, 0, sizeof(*eku)); e = find_extension(cert, &asn1_oid_id_x509_ce_extKeyUsage, &i); if (e == NULL) return HX509_EXTENSION_NOT_FOUND; return decode_ExtKeyUsage(e->extnValue.data, e->extnValue.length, eku, &size); } static int add_to_list(hx509_octet_string_list *list, const heim_octet_string *entry) { void *p; int ret; p = realloc(list->val, (list->len + 1) * sizeof(list->val[0])); if (p == NULL) return ENOMEM; list->val = p; ret = der_copy_octet_string(entry, &list->val[list->len]); if (ret) return ret; list->len++; return 0; } /** * Free a list of octet strings returned by another hx509 library * function. * * @param list list to be freed. * * @ingroup hx509_misc */ void hx509_free_octet_string_list(hx509_octet_string_list *list) { size_t i; for (i = 0; i < list->len; i++) der_free_octet_string(&list->val[i]); free(list->val); list->val = NULL; list->len = 0; } /** * Return a list of subjectAltNames specified by oid in the * certificate. On error the * * The returned list of octet string should be freed with * hx509_free_octet_string_list(). * * @param context A hx509 context. * @param cert a hx509 certificate object. * @param oid an oid to for SubjectAltName. * @param list list of matching SubjectAltName. * * @return An hx509 error code, see hx509_get_error_string(). * * @ingroup hx509_cert */ int hx509_cert_find_subjectAltName_otherName(hx509_context context, hx509_cert cert, const heim_oid *oid, hx509_octet_string_list *list) { GeneralNames sa; int ret; size_t i, j; list->val = NULL; list->len = 0; i = 0; while (1) { ret = find_extension_subject_alt_name(_hx509_get_cert(cert), &i, &sa); i++; if (ret == HX509_EXTENSION_NOT_FOUND) { return 0; } else if (ret != 0) { hx509_set_error_string(context, 0, ret, "Error searching for SAN"); hx509_free_octet_string_list(list); return ret; } for (j = 0; j < sa.len; j++) { if (sa.val[j].element == choice_GeneralName_otherName && der_heim_oid_cmp(&sa.val[j].u.otherName.type_id, oid) == 0) { ret = add_to_list(list, &sa.val[j].u.otherName.value); if (ret) { hx509_set_error_string(context, 0, ret, "Error adding an exra SAN to " "return list"); hx509_free_octet_string_list(list); free_GeneralNames(&sa); return ret; } } } free_GeneralNames(&sa); } } static int check_key_usage(hx509_context context, const Certificate *cert, unsigned flags, int req_present) { const Extension *e; KeyUsage ku; size_t size; int ret; size_t i = 0; unsigned ku_flags; if (_hx509_cert_get_version(cert) < 3) return 0; e = find_extension(cert, &asn1_oid_id_x509_ce_keyUsage, &i); if (e == NULL) { if (req_present) { hx509_set_error_string(context, 0, HX509_KU_CERT_MISSING, "Required extension key " "usage missing from certifiate"); return HX509_KU_CERT_MISSING; } return 0; } ret = decode_KeyUsage(e->extnValue.data, e->extnValue.length, &ku, &size); if (ret) return ret; ku_flags = KeyUsage2int(ku); if ((ku_flags & flags) != flags) { unsigned missing = (~ku_flags) & flags; char buf[256], *name; unparse_flags(missing, asn1_KeyUsage_units(), buf, sizeof(buf)); _hx509_unparse_Name(&cert->tbsCertificate.subject, &name); hx509_set_error_string(context, 0, HX509_KU_CERT_MISSING, "Key usage %s required but missing " "from certifiate %s", buf, name ? name : ""); free(name); return HX509_KU_CERT_MISSING; } return 0; } /* * Return 0 on matching key usage 'flags' for 'cert', otherwise return * an error code. If 'req_present' the existance is required of the * KeyUsage extension. */ int _hx509_check_key_usage(hx509_context context, hx509_cert cert, unsigned flags, int req_present) { return check_key_usage(context, _hx509_get_cert(cert), flags, req_present); } enum certtype { PROXY_CERT, EE_CERT, CA_CERT }; static int check_basic_constraints(hx509_context context, const Certificate *cert, enum certtype type, size_t depth) { BasicConstraints bc; const Extension *e; size_t size; int ret; size_t i = 0; if (_hx509_cert_get_version(cert) < 3) return 0; e = find_extension(cert, &asn1_oid_id_x509_ce_basicConstraints, &i); if (e == NULL) { switch(type) { case PROXY_CERT: case EE_CERT: return 0; case CA_CERT: { char *name; ret = _hx509_unparse_Name(&cert->tbsCertificate.subject, &name); assert(ret == 0); hx509_set_error_string(context, 0, HX509_EXTENSION_NOT_FOUND, "basicConstraints missing from " "CA certifiacte %s", name); free(name); return HX509_EXTENSION_NOT_FOUND; } } } ret = decode_BasicConstraints(e->extnValue.data, e->extnValue.length, &bc, &size); if (ret) return ret; switch(type) { case PROXY_CERT: if (bc.cA != NULL && *bc.cA) ret = HX509_PARENT_IS_CA; break; case EE_CERT: ret = 0; break; case CA_CERT: if (bc.cA == NULL || !*bc.cA) ret = HX509_PARENT_NOT_CA; else if (bc.pathLenConstraint) if (depth - 1 > *bc.pathLenConstraint) ret = HX509_CA_PATH_TOO_DEEP; break; } free_BasicConstraints(&bc); return ret; } int _hx509_cert_is_parent_cmp(const Certificate *subject, const Certificate *issuer, int allow_self_signed) { int diff; AuthorityKeyIdentifier ai; SubjectKeyIdentifier si; int ret_ai, ret_si, ret; ret = _hx509_name_cmp(&issuer->tbsCertificate.subject, &subject->tbsCertificate.issuer, &diff); if (ret) return ret; if (diff) return diff; memset(&ai, 0, sizeof(ai)); memset(&si, 0, sizeof(si)); /* * Try to find AuthorityKeyIdentifier, if it's not present in the * subject certificate nor the parent. */ ret_ai = find_extension_auth_key_id(subject, &ai); if (ret_ai && ret_ai != HX509_EXTENSION_NOT_FOUND) return 1; ret_si = _hx509_find_extension_subject_key_id(issuer, &si); if (ret_si && ret_si != HX509_EXTENSION_NOT_FOUND) return -1; if (ret_si && ret_ai) goto out; if (ret_ai) goto out; if (ret_si) { if (allow_self_signed) { diff = 0; goto out; } else if (ai.keyIdentifier) { diff = -1; goto out; } } if (ai.keyIdentifier == NULL) { Name name; if (ai.authorityCertIssuer == NULL) return -1; if (ai.authorityCertSerialNumber == NULL) return -1; diff = der_heim_integer_cmp(ai.authorityCertSerialNumber, &issuer->tbsCertificate.serialNumber); if (diff) return diff; if (ai.authorityCertIssuer->len != 1) return -1; if (ai.authorityCertIssuer->val[0].element != choice_GeneralName_directoryName) return -1; name.element = (enum Name_enum) ai.authorityCertIssuer->val[0].u.directoryName.element; name.u.rdnSequence = ai.authorityCertIssuer->val[0].u.directoryName.u.rdnSequence; ret = _hx509_name_cmp(&issuer->tbsCertificate.subject, &name, &diff); if (ret) return ret; if (diff) return diff; diff = 0; } else diff = der_heim_octet_string_cmp(ai.keyIdentifier, &si); if (diff) goto out; out: free_AuthorityKeyIdentifier(&ai); free_SubjectKeyIdentifier(&si); return diff; } static int certificate_is_anchor(hx509_context context, hx509_certs trust_anchors, const hx509_cert cert) { hx509_query q; hx509_cert c; int ret; if (trust_anchors == NULL) return 0; _hx509_query_clear(&q); q.match = HX509_QUERY_MATCH_CERTIFICATE; q.certificate = _hx509_get_cert(cert); ret = hx509_certs_find(context, trust_anchors, &q, &c); if (ret == 0) hx509_cert_free(c); return ret == 0; } static int certificate_is_self_signed(hx509_context context, const Certificate *cert, int *self_signed) { int ret, diff; ret = _hx509_name_cmp(&cert->tbsCertificate.subject, &cert->tbsCertificate.issuer, &diff); *self_signed = (diff == 0); if (ret) { hx509_set_error_string(context, 0, ret, "Failed to check if self signed"); } else ret = _hx509_self_signed_valid(context, &cert->signatureAlgorithm); return ret; } /* * The subjectName is "null" when it's empty set of relative DBs. */ static int subject_null_p(const Certificate *c) { return c->tbsCertificate.subject.u.rdnSequence.len == 0; } static int find_parent(hx509_context context, time_t time_now, hx509_certs trust_anchors, hx509_path *path, hx509_certs pool, hx509_cert current, hx509_cert *parent) { AuthorityKeyIdentifier ai; hx509_query q; int ret; *parent = NULL; memset(&ai, 0, sizeof(ai)); _hx509_query_clear(&q); if (!subject_null_p(current->data)) { q.match |= HX509_QUERY_FIND_ISSUER_CERT; q.subject = _hx509_get_cert(current); } else { ret = find_extension_auth_key_id(current->data, &ai); if (ret) { hx509_set_error_string(context, 0, HX509_CERTIFICATE_MALFORMED, "Subjectless certificate missing AuthKeyID"); return HX509_CERTIFICATE_MALFORMED; } if (ai.keyIdentifier == NULL) { free_AuthorityKeyIdentifier(&ai); hx509_set_error_string(context, 0, HX509_CERTIFICATE_MALFORMED, "Subjectless certificate missing keyIdentifier " "inside AuthKeyID"); return HX509_CERTIFICATE_MALFORMED; } q.subject_id = ai.keyIdentifier; q.match = HX509_QUERY_MATCH_SUBJECT_KEY_ID; } q.path = path; q.match |= HX509_QUERY_NO_MATCH_PATH; if (pool) { q.timenow = time_now; q.match |= HX509_QUERY_MATCH_TIME; ret = hx509_certs_find(context, pool, &q, parent); if (ret == 0) { free_AuthorityKeyIdentifier(&ai); return 0; } q.match &= ~HX509_QUERY_MATCH_TIME; } if (trust_anchors) { ret = hx509_certs_find(context, trust_anchors, &q, parent); if (ret == 0) { free_AuthorityKeyIdentifier(&ai); return ret; } } free_AuthorityKeyIdentifier(&ai); { hx509_name name; char *str; ret = hx509_cert_get_subject(current, &name); if (ret) { hx509_clear_error_string(context); return HX509_ISSUER_NOT_FOUND; } ret = hx509_name_to_string(name, &str); hx509_name_free(&name); if (ret) { hx509_clear_error_string(context); return HX509_ISSUER_NOT_FOUND; } hx509_set_error_string(context, 0, HX509_ISSUER_NOT_FOUND, "Failed to find issuer for " "certificate with subject: '%s'", str); free(str); } return HX509_ISSUER_NOT_FOUND; } /* * */ static int is_proxy_cert(hx509_context context, const Certificate *cert, ProxyCertInfo *rinfo) { ProxyCertInfo info; const Extension *e; size_t size; int ret; size_t i = 0; if (rinfo) memset(rinfo, 0, sizeof(*rinfo)); e = find_extension(cert, &asn1_oid_id_pkix_pe_proxyCertInfo, &i); if (e == NULL) { hx509_clear_error_string(context); return HX509_EXTENSION_NOT_FOUND; } ret = decode_ProxyCertInfo(e->extnValue.data, e->extnValue.length, &info, &size); if (ret) { hx509_clear_error_string(context); return ret; } if (size != e->extnValue.length) { free_ProxyCertInfo(&info); hx509_clear_error_string(context); return HX509_EXTRA_DATA_AFTER_STRUCTURE; } if (rinfo == NULL) free_ProxyCertInfo(&info); else *rinfo = info; return 0; } /* * Path operations are like MEMORY based keyset, but with exposed * internal so we can do easy searches. */ int _hx509_path_append(hx509_context context, hx509_path *path, hx509_cert cert) { hx509_cert *val; val = realloc(path->val, (path->len + 1) * sizeof(path->val[0])); if (val == NULL) { hx509_set_error_string(context, 0, ENOMEM, "out of memory"); return ENOMEM; } path->val = val; path->val[path->len] = hx509_cert_ref(cert); path->len++; return 0; } void _hx509_path_free(hx509_path *path) { unsigned i; for (i = 0; i < path->len; i++) hx509_cert_free(path->val[i]); free(path->val); path->val = NULL; path->len = 0; } /* * Find path by looking up issuer for the top certificate and continue * until an anchor certificate is found or max limit is found. A * certificate never included twice in the path. * * If the trust anchors are not given, calculate optimistic path, just * follow the chain upward until we no longer find a parent or we hit * the max path limit. In this case, a failure will always be returned * depending on what error condition is hit first. * * The path includes a path from the top certificate to the anchor * certificate. * * The caller needs to free `path´ both on successful built path and * failure. */ int _hx509_calculate_path(hx509_context context, int flags, time_t time_now, hx509_certs anchors, unsigned int max_depth, hx509_cert cert, hx509_certs pool, hx509_path *path) { hx509_cert parent, current; int ret; if (max_depth == 0) max_depth = HX509_VERIFY_MAX_DEPTH; ret = _hx509_path_append(context, path, cert); if (ret) return ret; current = hx509_cert_ref(cert); while (!certificate_is_anchor(context, anchors, current)) { ret = find_parent(context, time_now, anchors, path, pool, current, &parent); hx509_cert_free(current); if (ret) return ret; ret = _hx509_path_append(context, path, parent); if (ret) return ret; current = parent; if (path->len > max_depth) { hx509_cert_free(current); hx509_set_error_string(context, 0, HX509_PATH_TOO_LONG, "Path too long while bulding " "certificate chain"); return HX509_PATH_TOO_LONG; } } if ((flags & HX509_CALCULATE_PATH_NO_ANCHOR) && path->len > 0 && certificate_is_anchor(context, anchors, path->val[path->len - 1])) { hx509_cert_free(path->val[path->len - 1]); path->len--; } hx509_cert_free(current); return 0; } int _hx509_AlgorithmIdentifier_cmp(const AlgorithmIdentifier *p, const AlgorithmIdentifier *q) { int diff; diff = der_heim_oid_cmp(&p->algorithm, &q->algorithm); if (diff) return diff; if (p->parameters) { if (q->parameters) return heim_any_cmp(p->parameters, q->parameters); else return 1; } else { if (q->parameters) return -1; else return 0; } } int _hx509_Certificate_cmp(const Certificate *p, const Certificate *q) { int diff; diff = der_heim_bit_string_cmp(&p->signatureValue, &q->signatureValue); if (diff) return diff; diff = _hx509_AlgorithmIdentifier_cmp(&p->signatureAlgorithm, &q->signatureAlgorithm); if (diff) return diff; diff = der_heim_octet_string_cmp(&p->tbsCertificate._save, &q->tbsCertificate._save); return diff; } /** * Compare to hx509 certificate object, useful for sorting. * * @param p a hx509 certificate object. * @param q a hx509 certificate object. * * @return 0 the objects are the same, returns > 0 is p is "larger" * then q, < 0 if p is "smaller" then q. * * @ingroup hx509_cert */ int hx509_cert_cmp(hx509_cert p, hx509_cert q) { return _hx509_Certificate_cmp(p->data, q->data); } /** * Return the name of the issuer of the hx509 certificate. * * @param p a hx509 certificate object. * @param name a pointer to a hx509 name, should be freed by * hx509_name_free(). * * @return An hx509 error code, see hx509_get_error_string(). * * @ingroup hx509_cert */ int hx509_cert_get_issuer(hx509_cert p, hx509_name *name) { return _hx509_name_from_Name(&p->data->tbsCertificate.issuer, name); } /** * Return the name of the subject of the hx509 certificate. * * @param p a hx509 certificate object. * @param name a pointer to a hx509 name, should be freed by * hx509_name_free(). See also hx509_cert_get_base_subject(). * * @return An hx509 error code, see hx509_get_error_string(). * * @ingroup hx509_cert */ int hx509_cert_get_subject(hx509_cert p, hx509_name *name) { return _hx509_name_from_Name(&p->data->tbsCertificate.subject, name); } /** * Return the name of the base subject of the hx509 certificate. If * the certiicate is a verified proxy certificate, the this function * return the base certificate (root of the proxy chain). If the proxy * certificate is not verified with the base certificate * HX509_PROXY_CERTIFICATE_NOT_CANONICALIZED is returned. * * @param context a hx509 context. * @param c a hx509 certificate object. * @param name a pointer to a hx509 name, should be freed by * hx509_name_free(). See also hx509_cert_get_subject(). * * @return An hx509 error code, see hx509_get_error_string(). * * @ingroup hx509_cert */ int hx509_cert_get_base_subject(hx509_context context, hx509_cert c, hx509_name *name) { if (c->basename) return hx509_name_copy(context, c->basename, name); if (is_proxy_cert(context, c->data, NULL) == 0) { int ret = HX509_PROXY_CERTIFICATE_NOT_CANONICALIZED; hx509_set_error_string(context, 0, ret, "Proxy certificate have not been " "canonicalize yet, no base name"); return ret; } return _hx509_name_from_Name(&c->data->tbsCertificate.subject, name); } /** * Get serial number of the certificate. * * @param p a hx509 certificate object. * @param i serial number, should be freed ith der_free_heim_integer(). * * @return An hx509 error code, see hx509_get_error_string(). * * @ingroup hx509_cert */ int hx509_cert_get_serialnumber(hx509_cert p, heim_integer *i) { return der_copy_heim_integer(&p->data->tbsCertificate.serialNumber, i); } /** * Get notBefore time of the certificate. * * @param p a hx509 certificate object. * * @return return not before time * * @ingroup hx509_cert */ time_t hx509_cert_get_notBefore(hx509_cert p) { return _hx509_Time2time_t(&p->data->tbsCertificate.validity.notBefore); } /** * Get notAfter time of the certificate. * * @param p a hx509 certificate object. * * @return return not after time. * * @ingroup hx509_cert */ time_t hx509_cert_get_notAfter(hx509_cert p) { return _hx509_Time2time_t(&p->data->tbsCertificate.validity.notAfter); } /** * Get the SubjectPublicKeyInfo structure from the hx509 certificate. * * @param context a hx509 context. * @param p a hx509 certificate object. * @param spki SubjectPublicKeyInfo, should be freed with * free_SubjectPublicKeyInfo(). * * @return An hx509 error code, see hx509_get_error_string(). * * @ingroup hx509_cert */ int hx509_cert_get_SPKI(hx509_context context, hx509_cert p, SubjectPublicKeyInfo *spki) { int ret; ret = copy_SubjectPublicKeyInfo(&p->data->tbsCertificate.subjectPublicKeyInfo, spki); if (ret) hx509_set_error_string(context, 0, ret, "Failed to copy SPKI"); return ret; } /** * Get the AlgorithmIdentifier from the hx509 certificate. * * @param context a hx509 context. * @param p a hx509 certificate object. * @param alg AlgorithmIdentifier, should be freed with * free_AlgorithmIdentifier(). The algorithmidentifier is * typicly rsaEncryption, or id-ecPublicKey, or some other * public key mechanism. * * @return An hx509 error code, see hx509_get_error_string(). * * @ingroup hx509_cert */ int hx509_cert_get_SPKI_AlgorithmIdentifier(hx509_context context, hx509_cert p, AlgorithmIdentifier *alg) { int ret; ret = copy_AlgorithmIdentifier(&p->data->tbsCertificate.subjectPublicKeyInfo.algorithm, alg); if (ret) hx509_set_error_string(context, 0, ret, "Failed to copy SPKI AlgorithmIdentifier"); return ret; } static int get_x_unique_id(hx509_context context, const char *name, const heim_bit_string *cert, heim_bit_string *subject) { int ret; if (cert == NULL) { ret = HX509_EXTENSION_NOT_FOUND; hx509_set_error_string(context, 0, ret, "%s unique id doesn't exists", name); return ret; } ret = der_copy_bit_string(cert, subject); if (ret) { hx509_set_error_string(context, 0, ret, "malloc out of memory", name); return ret; } return 0; } /** * Get a copy of the Issuer Unique ID * * @param context a hx509_context * @param p a hx509 certificate * @param issuer the issuer id returned, free with der_free_bit_string() * * @return An hx509 error code, see hx509_get_error_string(). The * error code HX509_EXTENSION_NOT_FOUND is returned if the certificate * doesn't have a issuerUniqueID * * @ingroup hx509_cert */ int hx509_cert_get_issuer_unique_id(hx509_context context, hx509_cert p, heim_bit_string *issuer) { return get_x_unique_id(context, "issuer", p->data->tbsCertificate.issuerUniqueID, issuer); } /** * Get a copy of the Subect Unique ID * * @param context a hx509_context * @param p a hx509 certificate * @param subject the subject id returned, free with der_free_bit_string() * * @return An hx509 error code, see hx509_get_error_string(). The * error code HX509_EXTENSION_NOT_FOUND is returned if the certificate * doesn't have a subjectUniqueID * * @ingroup hx509_cert */ int hx509_cert_get_subject_unique_id(hx509_context context, hx509_cert p, heim_bit_string *subject) { return get_x_unique_id(context, "subject", p->data->tbsCertificate.subjectUniqueID, subject); } hx509_private_key _hx509_cert_private_key(hx509_cert p) { return p->private_key; } int hx509_cert_have_private_key(hx509_cert p) { return p->private_key ? 1 : 0; } int _hx509_cert_private_key_exportable(hx509_cert p) { if (p->private_key == NULL) return 0; return _hx509_private_key_exportable(p->private_key); } int _hx509_cert_private_decrypt(hx509_context context, const heim_octet_string *ciphertext, const heim_oid *encryption_oid, hx509_cert p, heim_octet_string *cleartext) { cleartext->data = NULL; cleartext->length = 0; if (p->private_key == NULL) { hx509_set_error_string(context, 0, HX509_PRIVATE_KEY_MISSING, "Private key missing"); return HX509_PRIVATE_KEY_MISSING; } return hx509_private_key_private_decrypt(context, ciphertext, encryption_oid, p->private_key, cleartext); } int hx509_cert_public_encrypt(hx509_context context, const heim_octet_string *cleartext, const hx509_cert p, heim_oid *encryption_oid, heim_octet_string *ciphertext) { return _hx509_public_encrypt(context, cleartext, p->data, encryption_oid, ciphertext); } /* * */ time_t _hx509_Time2time_t(const Time *t) { switch(t->element) { case choice_Time_utcTime: return t->u.utcTime; case choice_Time_generalTime: return t->u.generalTime; } return 0; } /* * */ static int init_name_constraints(hx509_name_constraints *nc) { memset(nc, 0, sizeof(*nc)); return 0; } static int add_name_constraints(hx509_context context, const Certificate *c, int not_ca, hx509_name_constraints *nc) { NameConstraints tnc; int ret; ret = find_extension_name_constraints(c, &tnc); if (ret == HX509_EXTENSION_NOT_FOUND) return 0; else if (ret) { hx509_set_error_string(context, 0, ret, "Failed getting NameConstraints"); return ret; } else if (not_ca) { ret = HX509_VERIFY_CONSTRAINTS; hx509_set_error_string(context, 0, ret, "Not a CA and " "have NameConstraints"); } else { NameConstraints *val; val = realloc(nc->val, sizeof(nc->val[0]) * (nc->len + 1)); if (val == NULL) { hx509_clear_error_string(context); ret = ENOMEM; goto out; } nc->val = val; ret = copy_NameConstraints(&tnc, &nc->val[nc->len]); if (ret) { hx509_clear_error_string(context); goto out; } nc->len += 1; } out: free_NameConstraints(&tnc); return ret; } static int match_RDN(const RelativeDistinguishedName *c, const RelativeDistinguishedName *n) { size_t i; if (c->len != n->len) return HX509_NAME_CONSTRAINT_ERROR; for (i = 0; i < n->len; i++) { int diff, ret; if (der_heim_oid_cmp(&c->val[i].type, &n->val[i].type) != 0) return HX509_NAME_CONSTRAINT_ERROR; ret = _hx509_name_ds_cmp(&c->val[i].value, &n->val[i].value, &diff); if (ret) return ret; if (diff != 0) return HX509_NAME_CONSTRAINT_ERROR; } return 0; } static int match_X501Name(const Name *c, const Name *n) { size_t i; int ret; if (c->element != choice_Name_rdnSequence || n->element != choice_Name_rdnSequence) return 0; if (c->u.rdnSequence.len > n->u.rdnSequence.len) return HX509_NAME_CONSTRAINT_ERROR; for (i = 0; i < c->u.rdnSequence.len; i++) { ret = match_RDN(&c->u.rdnSequence.val[i], &n->u.rdnSequence.val[i]); if (ret) return ret; } return 0; } static int match_general_name(const GeneralName *c, const GeneralName *n, int *match) { /* * Name constraints only apply to the same name type, see RFC3280, * 4.2.1.11. */ assert(c->element == n->element); switch(c->element) { case choice_GeneralName_otherName: if (der_heim_oid_cmp(&c->u.otherName.type_id, &n->u.otherName.type_id) != 0) return HX509_NAME_CONSTRAINT_ERROR; if (heim_any_cmp(&c->u.otherName.value, &n->u.otherName.value) != 0) return HX509_NAME_CONSTRAINT_ERROR; *match = 1; return 0; case choice_GeneralName_rfc822Name: { const char *s; size_t len1, len2; s = memchr(c->u.rfc822Name.data, '@', c->u.rfc822Name.length); if (s) { if (der_printable_string_cmp(&c->u.rfc822Name, &n->u.rfc822Name) != 0) return HX509_NAME_CONSTRAINT_ERROR; } else { s = memchr(n->u.rfc822Name.data, '@', n->u.rfc822Name.length); if (s == NULL) return HX509_NAME_CONSTRAINT_ERROR; len1 = c->u.rfc822Name.length; len2 = n->u.rfc822Name.length - (s - ((char *)n->u.rfc822Name.data)); if (len1 > len2) return HX509_NAME_CONSTRAINT_ERROR; if (memcmp(s + 1 + len2 - len1, c->u.rfc822Name.data, len1) != 0) return HX509_NAME_CONSTRAINT_ERROR; if (len1 < len2 && s[len2 - len1 + 1] != '.') return HX509_NAME_CONSTRAINT_ERROR; } *match = 1; return 0; } case choice_GeneralName_dNSName: { size_t lenc, lenn; char *ptr; lenc = c->u.dNSName.length; lenn = n->u.dNSName.length; if (lenc > lenn) return HX509_NAME_CONSTRAINT_ERROR; ptr = n->u.dNSName.data; if (memcmp(&ptr[lenn - lenc], c->u.dNSName.data, lenc) != 0) return HX509_NAME_CONSTRAINT_ERROR; if (lenn != lenc && ptr[lenn - lenc - 1] != '.') return HX509_NAME_CONSTRAINT_ERROR; *match = 1; return 0; } case choice_GeneralName_directoryName: { Name c_name, n_name; int ret; c_name._save.data = NULL; c_name._save.length = 0; c_name.element = (enum Name_enum)c->u.directoryName.element; c_name.u.rdnSequence = c->u.directoryName.u.rdnSequence; n_name._save.data = NULL; n_name._save.length = 0; n_name.element = (enum Name_enum)n->u.directoryName.element; n_name.u.rdnSequence = n->u.directoryName.u.rdnSequence; ret = match_X501Name(&c_name, &n_name); if (ret == 0) *match = 1; return ret; } case choice_GeneralName_uniformResourceIdentifier: case choice_GeneralName_iPAddress: case choice_GeneralName_registeredID: default: return HX509_NAME_CONSTRAINT_ERROR; } } static int match_alt_name(const GeneralName *n, const Certificate *c, int *same, int *match) { GeneralNames sa; int ret = 0; size_t i, j; i = 0; do { ret = find_extension_subject_alt_name(c, &i, &sa); if (ret == HX509_EXTENSION_NOT_FOUND) { ret = 0; break; } else if (ret != 0) break; for (j = 0; j < sa.len; j++) { if (n->element == sa.val[j].element) { *same = 1; match_general_name(n, &sa.val[j], match); } } free_GeneralNames(&sa); } while (1); return ret; } static int match_tree(const GeneralSubtrees *t, const Certificate *c, int *match) { int name, alt_name, same; unsigned int i; int ret = 0; name = alt_name = same = *match = 0; for (i = 0; i < t->len; i++) { if (t->val[i].minimum && t->val[i].maximum) return HX509_RANGE; /* * If the constraint apply to directoryNames, test is with * subjectName of the certificate if the certificate have a * non-null (empty) subjectName. */ if (t->val[i].base.element == choice_GeneralName_directoryName && !subject_null_p(c)) { GeneralName certname; memset(&certname, 0, sizeof(certname)); certname.element = choice_GeneralName_directoryName; certname.u.directoryName.element = (enum GeneralName_directoryName_enum) c->tbsCertificate.subject.element; certname.u.directoryName.u.rdnSequence = c->tbsCertificate.subject.u.rdnSequence; match_general_name(&t->val[i].base, &certname, &name); } /* Handle subjectAltNames, this is icky since they * restrictions only apply if the subjectAltName is of the * same type. So if there have been a match of type, require * altname to be set. */ match_alt_name(&t->val[i].base, c, &same, &alt_name); } if (name && (!same || alt_name)) *match = 1; return ret; } static int check_name_constraints(hx509_context context, const hx509_name_constraints *nc, const Certificate *c) { int match, ret; size_t i; for (i = 0 ; i < nc->len; i++) { GeneralSubtrees gs; if (nc->val[i].permittedSubtrees) { GeneralSubtrees_SET(&gs, nc->val[i].permittedSubtrees); ret = match_tree(&gs, c, &match); if (ret) { hx509_clear_error_string(context); return ret; } /* allow null subjectNames, they wont matches anything */ if (match == 0 && !subject_null_p(c)) { hx509_set_error_string(context, 0, HX509_VERIFY_CONSTRAINTS, "Error verify constraints, " "certificate didn't match any " "permitted subtree"); return HX509_VERIFY_CONSTRAINTS; } } if (nc->val[i].excludedSubtrees) { GeneralSubtrees_SET(&gs, nc->val[i].excludedSubtrees); ret = match_tree(&gs, c, &match); if (ret) { hx509_clear_error_string(context); return ret; } if (match) { hx509_set_error_string(context, 0, HX509_VERIFY_CONSTRAINTS, "Error verify constraints, " "certificate included in excluded " "subtree"); return HX509_VERIFY_CONSTRAINTS; } } } return 0; } static void free_name_constraints(hx509_name_constraints *nc) { size_t i; for (i = 0 ; i < nc->len; i++) free_NameConstraints(&nc->val[i]); free(nc->val); } /** * Build and verify the path for the certificate to the trust anchor * specified in the verify context. The path is constructed from the * certificate, the pool and the trust anchors. * * @param context A hx509 context. * @param ctx A hx509 verification context. * @param cert the certificate to build the path from. * @param pool A keyset of certificates to build the chain from. * * @return An hx509 error code, see hx509_get_error_string(). * * @ingroup hx509_verify */ int hx509_verify_path(hx509_context context, hx509_verify_ctx ctx, hx509_cert cert, hx509_certs pool) { hx509_name_constraints nc; hx509_path path; int ret, proxy_cert_depth, selfsigned_depth, diff; size_t i, k; enum certtype type; Name proxy_issuer; hx509_certs anchors = NULL; memset(&proxy_issuer, 0, sizeof(proxy_issuer)); if ((ctx->flags & HX509_VERIFY_CTX_F_ALLOW_PROXY_CERTIFICATE) == 0 && is_proxy_cert(context, cert->data, NULL) == 0) { ret = HX509_PROXY_CERT_INVALID; hx509_set_error_string(context, 0, ret, "Proxy certificate is not allowed as an EE " "certificae if proxy certificate is disabled"); return ret; } ret = init_name_constraints(&nc); if (ret) return ret; path.val = NULL; path.len = 0; if ((ctx->flags & HX509_VERIFY_CTX_F_TIME_SET) == 0) ctx->time_now = time(NULL); /* * */ if (ctx->trust_anchors) anchors = hx509_certs_ref(ctx->trust_anchors); else if (context->default_trust_anchors && ALLOW_DEF_TA(ctx)) anchors = hx509_certs_ref(context->default_trust_anchors); else { ret = hx509_certs_init(context, "MEMORY:no-TA", 0, NULL, &anchors); if (ret) goto out; } /* * Calculate the path from the certificate user presented to the * to an anchor. */ ret = _hx509_calculate_path(context, 0, ctx->time_now, anchors, ctx->max_depth, cert, pool, &path); if (ret) goto out; /* * Check CA and proxy certificate chain from the top of the * certificate chain. Also check certificate is valid with respect * to the current time. * */ proxy_cert_depth = 0; selfsigned_depth = 0; if (ctx->flags & HX509_VERIFY_CTX_F_ALLOW_PROXY_CERTIFICATE) type = PROXY_CERT; else type = EE_CERT; for (i = 0; i < path.len; i++) { Certificate *c; time_t t; c = _hx509_get_cert(path.val[i]); /* * Lets do some basic check on issuer like * keyUsage.keyCertSign and basicConstraints.cA bit depending * on what type of certificate this is. */ switch (type) { case CA_CERT: /* XXX make constants for keyusage */ ret = check_key_usage(context, c, 1 << 5, REQUIRE_RFC3280(ctx) ? TRUE : FALSE); if (ret) { hx509_set_error_string(context, HX509_ERROR_APPEND, ret, "Key usage missing from CA certificate"); goto out; } /* self signed cert doesn't add to path length */ if (i + 1 != path.len) { int selfsigned; ret = certificate_is_self_signed(context, c, &selfsigned); if (ret) goto out; if (selfsigned) selfsigned_depth++; } break; case PROXY_CERT: { ProxyCertInfo info; if (is_proxy_cert(context, c, &info) == 0) { size_t j; if (info.pCPathLenConstraint != NULL && *info.pCPathLenConstraint < i) { free_ProxyCertInfo(&info); ret = HX509_PATH_TOO_LONG; hx509_set_error_string(context, 0, ret, "Proxy certificate chain " "longer then allowed"); goto out; } /* XXX MUST check info.proxyPolicy */ free_ProxyCertInfo(&info); j = 0; if (find_extension(c, &asn1_oid_id_x509_ce_subjectAltName, &j)) { ret = HX509_PROXY_CERT_INVALID; hx509_set_error_string(context, 0, ret, "Proxy certificate have explicity " "forbidden subjectAltName"); goto out; } j = 0; if (find_extension(c, &asn1_oid_id_x509_ce_issuerAltName, &j)) { ret = HX509_PROXY_CERT_INVALID; hx509_set_error_string(context, 0, ret, "Proxy certificate have explicity " "forbidden issuerAltName"); goto out; } /* * The subject name of the proxy certificate should be * CN=XXX,, prune of CN and check if its * the same over the whole chain of proxy certs and * then check with the EE cert when we get to it. */ if (proxy_cert_depth) { ret = _hx509_name_cmp(&proxy_issuer, &c->tbsCertificate.subject, &diff); if (ret) { hx509_set_error_string(context, 0, ret, "Out of memory"); goto out; } if (diff) { ret = HX509_PROXY_CERT_NAME_WRONG; hx509_set_error_string(context, 0, ret, "Base proxy name not right"); goto out; } } free_Name(&proxy_issuer); ret = copy_Name(&c->tbsCertificate.subject, &proxy_issuer); if (ret) { hx509_clear_error_string(context); goto out; } j = proxy_issuer.u.rdnSequence.len; if (proxy_issuer.u.rdnSequence.len < 2 || proxy_issuer.u.rdnSequence.val[j - 1].len > 1 || der_heim_oid_cmp(&proxy_issuer.u.rdnSequence.val[j - 1].val[0].type, &asn1_oid_id_at_commonName)) { ret = HX509_PROXY_CERT_NAME_WRONG; hx509_set_error_string(context, 0, ret, "Proxy name too short or " "does not have Common name " "at the top"); goto out; } free_RelativeDistinguishedName(&proxy_issuer.u.rdnSequence.val[j - 1]); proxy_issuer.u.rdnSequence.len -= 1; ret = _hx509_name_cmp(&proxy_issuer, &c->tbsCertificate.issuer, &diff); if (ret) { hx509_set_error_string(context, 0, ret, "Out of memory"); goto out; } if (diff != 0) { ret = HX509_PROXY_CERT_NAME_WRONG; hx509_set_error_string(context, 0, ret, "Proxy issuer name not as expected"); goto out; } break; } else { /* * Now we are done with the proxy certificates, this * cert was an EE cert and we we will fall though to * EE checking below. */ type = EE_CERT; /* FALLTHOUGH */ } } case EE_CERT: /* * If there where any proxy certificates in the chain * (proxy_cert_depth > 0), check that the proxy issuer * matched proxy certificates "base" subject. */ if (proxy_cert_depth) { ret = _hx509_name_cmp(&proxy_issuer, &c->tbsCertificate.subject, &diff); if (ret) { hx509_set_error_string(context, 0, ret, "out of memory"); goto out; } if (diff) { ret = HX509_PROXY_CERT_NAME_WRONG; hx509_clear_error_string(context); goto out; } if (cert->basename) hx509_name_free(&cert->basename); ret = _hx509_name_from_Name(&proxy_issuer, &cert->basename); if (ret) { hx509_clear_error_string(context); goto out; } } break; } ret = check_basic_constraints(context, c, type, i - proxy_cert_depth - selfsigned_depth); if (ret) goto out; /* * Don't check the trust anchors expiration time since they * are transported out of band, from RFC3820. */ if (i + 1 != path.len || CHECK_TA(ctx)) { t = _hx509_Time2time_t(&c->tbsCertificate.validity.notBefore); if (t > ctx->time_now) { ret = HX509_CERT_USED_BEFORE_TIME; hx509_clear_error_string(context); goto out; } t = _hx509_Time2time_t(&c->tbsCertificate.validity.notAfter); if (t < ctx->time_now) { ret = HX509_CERT_USED_AFTER_TIME; hx509_clear_error_string(context); goto out; } } if (type == EE_CERT) type = CA_CERT; else if (type == PROXY_CERT) proxy_cert_depth++; } /* * Verify constraints, do this backward so path constraints are * checked in the right order. */ for (ret = 0, k = path.len; k > 0; k--) { Certificate *c; int selfsigned; i = k - 1; c = _hx509_get_cert(path.val[i]); ret = certificate_is_self_signed(context, c, &selfsigned); if (ret) goto out; /* verify name constraints, not for selfsigned and anchor */ if (!selfsigned || i + 1 != path.len) { ret = check_name_constraints(context, &nc, c); if (ret) { goto out; } } ret = add_name_constraints(context, c, i == 0, &nc); if (ret) goto out; /* XXX verify all other silly constraints */ } /* * Verify that no certificates has been revoked. */ if (ctx->revoke_ctx) { hx509_certs certs; ret = hx509_certs_init(context, "MEMORY:revoke-certs", 0, NULL, &certs); if (ret) goto out; for (i = 0; i < path.len; i++) { ret = hx509_certs_add(context, certs, path.val[i]); if (ret) { hx509_certs_free(&certs); goto out; } } ret = hx509_certs_merge(context, certs, pool); if (ret) { hx509_certs_free(&certs); goto out; } for (i = 0; i < path.len - 1; i++) { size_t parent = (i < path.len - 1) ? i + 1 : i; ret = hx509_revoke_verify(context, ctx->revoke_ctx, certs, ctx->time_now, path.val[i], path.val[parent]); if (ret) { hx509_certs_free(&certs); goto out; } } hx509_certs_free(&certs); } /* * Verify signatures, do this backward so public key working * parameter is passed up from the anchor up though the chain. */ for (k = path.len; k > 0; k--) { hx509_cert signer; Certificate *c; i = k - 1; c = _hx509_get_cert(path.val[i]); /* is last in chain (trust anchor) */ if (i + 1 == path.len) { int selfsigned; signer = path.val[i]; ret = certificate_is_self_signed(context, signer->data, &selfsigned); if (ret) goto out; /* if trust anchor is not self signed, don't check sig */ if (!selfsigned) continue; } else { /* take next certificate in chain */ signer = path.val[i + 1]; } /* verify signatureValue */ ret = _hx509_verify_signature_bitstring(context, signer, &c->signatureAlgorithm, &c->tbsCertificate._save, &c->signatureValue); if (ret) { hx509_set_error_string(context, HX509_ERROR_APPEND, ret, "Failed to verify signature of certificate"); goto out; } /* * Verify that the sigature algorithm is not weak. Ignore * trust anchors since they are provisioned by the user. */ if (i + 1 != path.len && (ctx->flags & HX509_VERIFY_CTX_F_NO_BEST_BEFORE_CHECK) == 0) { ret = _hx509_signature_is_weak(context, &c->signatureAlgorithm); if (ret) goto out; } } out: hx509_certs_free(&anchors); free_Name(&proxy_issuer); free_name_constraints(&nc); _hx509_path_free(&path); return ret; } /** * Verify a signature made using the private key of an certificate. * * @param context A hx509 context. * @param signer the certificate that made the signature. * @param alg algorthm that was used to sign the data. * @param data the data that was signed. * @param sig the sigature to verify. * * @return An hx509 error code, see hx509_get_error_string(). * * @ingroup hx509_crypto */ int hx509_verify_signature(hx509_context context, const hx509_cert signer, const AlgorithmIdentifier *alg, const heim_octet_string *data, const heim_octet_string *sig) { return _hx509_verify_signature(context, signer, alg, data, sig); } int _hx509_verify_signature_bitstring(hx509_context context, const hx509_cert signer, const AlgorithmIdentifier *alg, const heim_octet_string *data, const heim_bit_string *sig) { heim_octet_string os; if (sig->length & 7) { hx509_set_error_string(context, 0, HX509_CRYPTO_SIG_INVALID_FORMAT, "signature not multiple of 8 bits"); return HX509_CRYPTO_SIG_INVALID_FORMAT; } os.data = sig->data; os.length = sig->length / 8; return _hx509_verify_signature(context, signer, alg, data, &os); } /** * Verify that the certificate is allowed to be used for the hostname * and address. * * @param context A hx509 context. * @param cert the certificate to match with * @param flags Flags to modify the behavior: * - HX509_VHN_F_ALLOW_NO_MATCH no match is ok * @param type type of hostname: * - HX509_HN_HOSTNAME for plain hostname. * - HX509_HN_DNSSRV for DNS SRV names. * @param hostname the hostname to check * @param sa address of the host * @param sa_size length of address * * @return An hx509 error code, see hx509_get_error_string(). * * @ingroup hx509_cert */ int hx509_verify_hostname(hx509_context context, const hx509_cert cert, int flags, hx509_hostname_type type, const char *hostname, const struct sockaddr *sa, /* XXX krb5_socklen_t */ int sa_size) { GeneralNames san; const Name *name; int ret; size_t i, j, k; if (sa && sa_size <= 0) return EINVAL; memset(&san, 0, sizeof(san)); i = 0; do { ret = find_extension_subject_alt_name(cert->data, &i, &san); if (ret == HX509_EXTENSION_NOT_FOUND) break; else if (ret != 0) return HX509_PARSING_NAME_FAILED; for (j = 0; j < san.len; j++) { switch (san.val[j].element) { case choice_GeneralName_dNSName: { heim_printable_string hn; hn.data = rk_UNCONST(hostname); hn.length = strlen(hostname); if (der_printable_string_cmp(&san.val[j].u.dNSName, &hn) == 0) { free_GeneralNames(&san); return 0; } break; } default: break; } } free_GeneralNames(&san); } while (1); name = &cert->data->tbsCertificate.subject; /* Find first CN= in the name, and try to match the hostname on that */ for (ret = 0, k = name->u.rdnSequence.len; ret == 0 && k > 0; k--) { i = k - 1; for (j = 0; ret == 0 && j < name->u.rdnSequence.val[i].len; j++) { AttributeTypeAndValue *n = &name->u.rdnSequence.val[i].val[j]; if (der_heim_oid_cmp(&n->type, &asn1_oid_id_at_commonName) == 0) { DirectoryString *ds = &n->value; switch (ds->element) { case choice_DirectoryString_printableString: { heim_printable_string hn; hn.data = rk_UNCONST(hostname); hn.length = strlen(hostname); if (der_printable_string_cmp(&ds->u.printableString, &hn) == 0) return 0; break; } case choice_DirectoryString_ia5String: { heim_ia5_string hn; hn.data = rk_UNCONST(hostname); hn.length = strlen(hostname); if (der_ia5_string_cmp(&ds->u.ia5String, &hn) == 0) return 0; break; } case choice_DirectoryString_utf8String: if (strcasecmp(ds->u.utf8String, hostname) == 0) return 0; default: break; } ret = HX509_NAME_CONSTRAINT_ERROR; } } } if ((flags & HX509_VHN_F_ALLOW_NO_MATCH) == 0) ret = HX509_NAME_CONSTRAINT_ERROR; return ret; } int _hx509_set_cert_attribute(hx509_context context, hx509_cert cert, const heim_oid *oid, const heim_octet_string *attr) { hx509_cert_attribute a; void *d; if (hx509_cert_get_attribute(cert, oid) != NULL) return 0; d = realloc(cert->attrs.val, sizeof(cert->attrs.val[0]) * (cert->attrs.len + 1)); if (d == NULL) { hx509_clear_error_string(context); return ENOMEM; } cert->attrs.val = d; a = malloc(sizeof(*a)); if (a == NULL) return ENOMEM; der_copy_octet_string(attr, &a->data); der_copy_oid(oid, &a->oid); cert->attrs.val[cert->attrs.len] = a; cert->attrs.len++; return 0; } /** * Get an external attribute for the certificate, examples are * friendly name and id. * * @param cert hx509 certificate object to search * @param oid an oid to search for. * * @return an hx509_cert_attribute, only valid as long as the * certificate is referenced. * * @ingroup hx509_cert */ hx509_cert_attribute hx509_cert_get_attribute(hx509_cert cert, const heim_oid *oid) { size_t i; for (i = 0; i < cert->attrs.len; i++) if (der_heim_oid_cmp(oid, &cert->attrs.val[i]->oid) == 0) return cert->attrs.val[i]; return NULL; } /** * Set the friendly name on the certificate. * * @param cert The certificate to set the friendly name on * @param name Friendly name. * * @return An hx509 error code, see hx509_get_error_string(). * * @ingroup hx509_cert */ int hx509_cert_set_friendly_name(hx509_cert cert, const char *name) { if (cert->friendlyname) free(cert->friendlyname); cert->friendlyname = strdup(name); if (cert->friendlyname == NULL) return ENOMEM; return 0; } /** * Get friendly name of the certificate. * * @param cert cert to get the friendly name from. * * @return an friendly name or NULL if there is. The friendly name is * only valid as long as the certificate is referenced. * * @ingroup hx509_cert */ const char * hx509_cert_get_friendly_name(hx509_cert cert) { hx509_cert_attribute a; PKCS9_friendlyName n; size_t sz; int ret; size_t i; if (cert->friendlyname) return cert->friendlyname; a = hx509_cert_get_attribute(cert, &asn1_oid_id_pkcs_9_at_friendlyName); if (a == NULL) { hx509_name name; ret = hx509_cert_get_subject(cert, &name); if (ret) return NULL; ret = hx509_name_to_string(name, &cert->friendlyname); hx509_name_free(&name); if (ret) return NULL; return cert->friendlyname; } ret = decode_PKCS9_friendlyName(a->data.data, a->data.length, &n, &sz); if (ret) return NULL; if (n.len != 1) { free_PKCS9_friendlyName(&n); return NULL; } cert->friendlyname = malloc(n.val[0].length + 1); if (cert->friendlyname == NULL) { free_PKCS9_friendlyName(&n); return NULL; } for (i = 0; i < n.val[0].length; i++) { if (n.val[0].data[i] <= 0xff) cert->friendlyname[i] = n.val[0].data[i] & 0xff; else cert->friendlyname[i] = 'X'; } cert->friendlyname[i] = '\0'; free_PKCS9_friendlyName(&n); return cert->friendlyname; } void _hx509_query_clear(hx509_query *q) { memset(q, 0, sizeof(*q)); } /** * Allocate an query controller. Free using hx509_query_free(). * * @param context A hx509 context. * @param q return pointer to a hx509_query. * * @return An hx509 error code, see hx509_get_error_string(). * * @ingroup hx509_cert */ int hx509_query_alloc(hx509_context context, hx509_query **q) { *q = calloc(1, sizeof(**q)); if (*q == NULL) return ENOMEM; return 0; } /** * Set match options for the hx509 query controller. * * @param q query controller. * @param option options to control the query controller. * * @return An hx509 error code, see hx509_get_error_string(). * * @ingroup hx509_cert */ void hx509_query_match_option(hx509_query *q, hx509_query_option option) { switch(option) { case HX509_QUERY_OPTION_PRIVATE_KEY: q->match |= HX509_QUERY_PRIVATE_KEY; break; case HX509_QUERY_OPTION_KU_ENCIPHERMENT: q->match |= HX509_QUERY_KU_ENCIPHERMENT; break; case HX509_QUERY_OPTION_KU_DIGITALSIGNATURE: q->match |= HX509_QUERY_KU_DIGITALSIGNATURE; break; case HX509_QUERY_OPTION_KU_KEYCERTSIGN: q->match |= HX509_QUERY_KU_KEYCERTSIGN; break; case HX509_QUERY_OPTION_END: default: break; } } /** * Set the issuer and serial number of match in the query * controller. The function make copies of the isser and serial number. * * @param q a hx509 query controller * @param issuer issuer to search for * @param serialNumber the serialNumber of the issuer. * * @return An hx509 error code, see hx509_get_error_string(). * * @ingroup hx509_cert */ int hx509_query_match_issuer_serial(hx509_query *q, const Name *issuer, const heim_integer *serialNumber) { int ret; if (q->serial) { der_free_heim_integer(q->serial); free(q->serial); } q->serial = malloc(sizeof(*q->serial)); if (q->serial == NULL) return ENOMEM; ret = der_copy_heim_integer(serialNumber, q->serial); if (ret) { free(q->serial); q->serial = NULL; return ret; } if (q->issuer_name) { free_Name(q->issuer_name); free(q->issuer_name); } q->issuer_name = malloc(sizeof(*q->issuer_name)); if (q->issuer_name == NULL) return ENOMEM; ret = copy_Name(issuer, q->issuer_name); if (ret) { free(q->issuer_name); q->issuer_name = NULL; return ret; } q->match |= HX509_QUERY_MATCH_SERIALNUMBER|HX509_QUERY_MATCH_ISSUER_NAME; return 0; } /** * Set the query controller to match on a friendly name * * @param q a hx509 query controller. * @param name a friendly name to match on * * @return An hx509 error code, see hx509_get_error_string(). * * @ingroup hx509_cert */ int hx509_query_match_friendly_name(hx509_query *q, const char *name) { if (q->friendlyname) free(q->friendlyname); q->friendlyname = strdup(name); if (q->friendlyname == NULL) return ENOMEM; q->match |= HX509_QUERY_MATCH_FRIENDLY_NAME; return 0; } /** * Set the query controller to require an one specific EKU (extended * key usage). Any previous EKU matching is overwitten. If NULL is * passed in as the eku, the EKU requirement is reset. * * @param q a hx509 query controller. * @param eku an EKU to match on. * * @return An hx509 error code, see hx509_get_error_string(). * * @ingroup hx509_cert */ int hx509_query_match_eku(hx509_query *q, const heim_oid *eku) { int ret; if (eku == NULL) { if (q->eku) { der_free_oid(q->eku); free(q->eku); q->eku = NULL; } q->match &= ~HX509_QUERY_MATCH_EKU; } else { if (q->eku) { der_free_oid(q->eku); } else { q->eku = calloc(1, sizeof(*q->eku)); if (q->eku == NULL) return ENOMEM; } ret = der_copy_oid(eku, q->eku); if (ret) { free(q->eku); q->eku = NULL; return ret; } q->match |= HX509_QUERY_MATCH_EKU; } return 0; } int hx509_query_match_expr(hx509_context context, hx509_query *q, const char *expr) { if (q->expr) { _hx509_expr_free(q->expr); q->expr = NULL; } if (expr == NULL) { q->match &= ~HX509_QUERY_MATCH_EXPR; } else { q->expr = _hx509_expr_parse(expr); if (q->expr) q->match |= HX509_QUERY_MATCH_EXPR; } return 0; } /** * Set the query controller to match using a specific match function. * * @param q a hx509 query controller. * @param func function to use for matching, if the argument is NULL, * the match function is removed. * @param ctx context passed to the function. * * @return An hx509 error code, see hx509_get_error_string(). * * @ingroup hx509_cert */ int hx509_query_match_cmp_func(hx509_query *q, int (*func)(hx509_context, hx509_cert, void *), void *ctx) { if (func) q->match |= HX509_QUERY_MATCH_FUNCTION; else q->match &= ~HX509_QUERY_MATCH_FUNCTION; q->cmp_func = func; q->cmp_func_ctx = ctx; return 0; } /** * Free the query controller. * * @param context A hx509 context. * @param q a pointer to the query controller. * * @ingroup hx509_cert */ void hx509_query_free(hx509_context context, hx509_query *q) { if (q == NULL) return; if (q->serial) { der_free_heim_integer(q->serial); free(q->serial); } if (q->issuer_name) { free_Name(q->issuer_name); free(q->issuer_name); } if (q->eku) { der_free_oid(q->eku); free(q->eku); } if (q->friendlyname) free(q->friendlyname); if (q->expr) _hx509_expr_free(q->expr); memset(q, 0, sizeof(*q)); free(q); } int _hx509_query_match_cert(hx509_context context, const hx509_query *q, hx509_cert cert) { Certificate *c = _hx509_get_cert(cert); int ret, diff; _hx509_query_statistic(context, 1, q); if ((q->match & HX509_QUERY_FIND_ISSUER_CERT) && _hx509_cert_is_parent_cmp(q->subject, c, 0) != 0) return 0; if ((q->match & HX509_QUERY_MATCH_CERTIFICATE) && _hx509_Certificate_cmp(q->certificate, c) != 0) return 0; if ((q->match & HX509_QUERY_MATCH_SERIALNUMBER) && der_heim_integer_cmp(&c->tbsCertificate.serialNumber, q->serial) != 0) return 0; if (q->match & HX509_QUERY_MATCH_ISSUER_NAME) { ret = _hx509_name_cmp(&c->tbsCertificate.issuer, q->issuer_name, &diff); if (ret || diff) return 0; } if (q->match & HX509_QUERY_MATCH_SUBJECT_NAME) { ret = _hx509_name_cmp(&c->tbsCertificate.subject, q->subject_name, &diff); if (ret || diff) return 0; } if (q->match & HX509_QUERY_MATCH_SUBJECT_KEY_ID) { SubjectKeyIdentifier si; ret = _hx509_find_extension_subject_key_id(c, &si); if (ret == 0) { if (der_heim_octet_string_cmp(&si, q->subject_id) != 0) ret = 1; free_SubjectKeyIdentifier(&si); } if (ret) return 0; } if ((q->match & HX509_QUERY_MATCH_ISSUER_ID)) return 0; if ((q->match & HX509_QUERY_PRIVATE_KEY) && _hx509_cert_private_key(cert) == NULL) return 0; { unsigned ku = 0; if (q->match & HX509_QUERY_KU_DIGITALSIGNATURE) ku |= (1 << 0); if (q->match & HX509_QUERY_KU_NONREPUDIATION) ku |= (1 << 1); if (q->match & HX509_QUERY_KU_ENCIPHERMENT) ku |= (1 << 2); if (q->match & HX509_QUERY_KU_DATAENCIPHERMENT) ku |= (1 << 3); if (q->match & HX509_QUERY_KU_KEYAGREEMENT) ku |= (1 << 4); if (q->match & HX509_QUERY_KU_KEYCERTSIGN) ku |= (1 << 5); if (q->match & HX509_QUERY_KU_CRLSIGN) ku |= (1 << 6); if (ku && check_key_usage(context, c, ku, TRUE)) return 0; } if ((q->match & HX509_QUERY_ANCHOR)) return 0; if (q->match & HX509_QUERY_MATCH_LOCAL_KEY_ID) { hx509_cert_attribute a; a = hx509_cert_get_attribute(cert, &asn1_oid_id_pkcs_9_at_localKeyId); if (a == NULL) return 0; if (der_heim_octet_string_cmp(&a->data, q->local_key_id) != 0) return 0; } if (q->match & HX509_QUERY_NO_MATCH_PATH) { size_t i; for (i = 0; i < q->path->len; i++) if (hx509_cert_cmp(q->path->val[i], cert) == 0) return 0; } if (q->match & HX509_QUERY_MATCH_FRIENDLY_NAME) { const char *name = hx509_cert_get_friendly_name(cert); if (name == NULL) return 0; if (strcasecmp(q->friendlyname, name) != 0) return 0; } if (q->match & HX509_QUERY_MATCH_FUNCTION) { ret = (*q->cmp_func)(context, cert, q->cmp_func_ctx); if (ret != 0) return 0; } if (q->match & HX509_QUERY_MATCH_KEY_HASH_SHA1) { heim_octet_string os; os.data = c->tbsCertificate.subjectPublicKeyInfo.subjectPublicKey.data; os.length = c->tbsCertificate.subjectPublicKeyInfo.subjectPublicKey.length / 8; ret = _hx509_verify_signature(context, NULL, hx509_signature_sha1(), &os, q->keyhash_sha1); if (ret != 0) return 0; } if (q->match & HX509_QUERY_MATCH_TIME) { time_t t; t = _hx509_Time2time_t(&c->tbsCertificate.validity.notBefore); if (t > q->timenow) return 0; t = _hx509_Time2time_t(&c->tbsCertificate.validity.notAfter); if (t < q->timenow) return 0; } /* If an EKU is required, check the cert for it. */ if ((q->match & HX509_QUERY_MATCH_EKU) && hx509_cert_check_eku(context, cert, q->eku, 0)) return 0; if ((q->match & HX509_QUERY_MATCH_EXPR)) { hx509_env env = NULL; ret = _hx509_cert_to_env(context, cert, &env); if (ret) return 0; ret = _hx509_expr_eval(context, env, q->expr); hx509_env_free(&env); if (ret == 0) return 0; } if (q->match & ~HX509_QUERY_MASK) return 0; return 1; } /** * Set a statistic file for the query statistics. * * @param context A hx509 context. * @param fn statistics file name * * @ingroup hx509_cert */ void hx509_query_statistic_file(hx509_context context, const char *fn) { if (context->querystat) free(context->querystat); context->querystat = strdup(fn); } void _hx509_query_statistic(hx509_context context, int type, const hx509_query *q) { FILE *f; if (context->querystat == NULL) return; f = fopen(context->querystat, "a"); if (f == NULL) return; rk_cloexec_file(f); fprintf(f, "%d %d\n", type, q->match); fclose(f); } static const char *statname[] = { "find issuer cert", "match serialnumber", "match issuer name", "match subject name", "match subject key id", "match issuer id", "private key", "ku encipherment", "ku digitalsignature", "ku keycertsign", "ku crlsign", "ku nonrepudiation", "ku keyagreement", "ku dataencipherment", "anchor", "match certificate", "match local key id", "no match path", "match friendly name", "match function", "match key hash sha1", "match time" }; struct stat_el { unsigned long stats; unsigned int index; }; static int stat_sort(const void *a, const void *b) { const struct stat_el *ae = a; const struct stat_el *be = b; return be->stats - ae->stats; } /** * Unparse the statistics file and print the result on a FILE descriptor. * * @param context A hx509 context. * @param printtype tyep to print * @param out the FILE to write the data on. * * @ingroup hx509_cert */ void hx509_query_unparse_stats(hx509_context context, int printtype, FILE *out) { rtbl_t t; FILE *f; int type, mask, num; size_t i; unsigned long multiqueries = 0, totalqueries = 0; struct stat_el stats[32]; if (context->querystat == NULL) return; f = fopen(context->querystat, "r"); if (f == NULL) { fprintf(out, "No statistic file %s: %s.\n", context->querystat, strerror(errno)); return; } rk_cloexec_file(f); for (i = 0; i < sizeof(stats)/sizeof(stats[0]); i++) { stats[i].index = i; stats[i].stats = 0; } while (fscanf(f, "%d %d\n", &type, &mask) == 2) { if (type != printtype) continue; num = i = 0; while (mask && i < sizeof(stats)/sizeof(stats[0])) { if (mask & 1) { stats[i].stats++; num++; } mask = mask >>1 ; i++; } if (num > 1) multiqueries++; totalqueries++; } fclose(f); qsort(stats, sizeof(stats)/sizeof(stats[0]), sizeof(stats[0]), stat_sort); t = rtbl_create(); if (t == NULL) errx(1, "out of memory"); rtbl_set_separator (t, " "); rtbl_add_column_by_id (t, 0, "Name", 0); rtbl_add_column_by_id (t, 1, "Counter", 0); for (i = 0; i < sizeof(stats)/sizeof(stats[0]); i++) { char str[10]; if (stats[i].index < sizeof(statname)/sizeof(statname[0])) rtbl_add_column_entry_by_id (t, 0, statname[stats[i].index]); else { snprintf(str, sizeof(str), "%d", stats[i].index); rtbl_add_column_entry_by_id (t, 0, str); } snprintf(str, sizeof(str), "%lu", stats[i].stats); rtbl_add_column_entry_by_id (t, 1, str); } rtbl_format(t, out); rtbl_destroy(t); fprintf(out, "\nQueries: multi %lu total %lu\n", multiqueries, totalqueries); } /** * Check the extended key usage on the hx509 certificate. * * @param context A hx509 context. * @param cert A hx509 context. * @param eku the EKU to check for * @param allow_any_eku if the any EKU is set, allow that to be a * substitute. * * @return An hx509 error code, see hx509_get_error_string(). * * @ingroup hx509_cert */ int hx509_cert_check_eku(hx509_context context, hx509_cert cert, const heim_oid *eku, int allow_any_eku) { ExtKeyUsage e; int ret; size_t i; ret = find_extension_eku(_hx509_get_cert(cert), &e); if (ret) { hx509_clear_error_string(context); return ret; } for (i = 0; i < e.len; i++) { if (der_heim_oid_cmp(eku, &e.val[i]) == 0) { free_ExtKeyUsage(&e); return 0; } if (allow_any_eku) { #if 0 if (der_heim_oid_cmp(id_any_eku, &e.val[i]) == 0) { free_ExtKeyUsage(&e); return 0; } #endif } } free_ExtKeyUsage(&e); hx509_clear_error_string(context); return HX509_CERTIFICATE_MISSING_EKU; } int _hx509_cert_get_keyusage(hx509_context context, hx509_cert c, KeyUsage *ku) { Certificate *cert; const Extension *e; size_t size; int ret; size_t i = 0; memset(ku, 0, sizeof(*ku)); cert = _hx509_get_cert(c); if (_hx509_cert_get_version(cert) < 3) return 0; e = find_extension(cert, &asn1_oid_id_x509_ce_keyUsage, &i); if (e == NULL) return HX509_KU_CERT_MISSING; ret = decode_KeyUsage(e->extnValue.data, e->extnValue.length, ku, &size); if (ret) return ret; return 0; } int _hx509_cert_get_eku(hx509_context context, hx509_cert cert, ExtKeyUsage *e) { int ret; memset(e, 0, sizeof(*e)); ret = find_extension_eku(_hx509_get_cert(cert), e); if (ret && ret != HX509_EXTENSION_NOT_FOUND) { hx509_clear_error_string(context); return ret; } return 0; } /** * Encodes the hx509 certificate as a DER encode binary. * * @param context A hx509 context. * @param c the certificate to encode. * @param os the encode certificate, set to NULL, 0 on case of * error. Free the os->data with hx509_xfree(). * * @return An hx509 error code, see hx509_get_error_string(). * * @ingroup hx509_cert */ int hx509_cert_binary(hx509_context context, hx509_cert c, heim_octet_string *os) { size_t size; int ret; os->data = NULL; os->length = 0; ASN1_MALLOC_ENCODE(Certificate, os->data, os->length, _hx509_get_cert(c), &size, ret); if (ret) { os->data = NULL; os->length = 0; return ret; } if (os->length != size) _hx509_abort("internal ASN.1 encoder error"); return ret; } /* * Last to avoid lost __attribute__s due to #undef. */ #undef __attribute__ #define __attribute__(X) void _hx509_abort(const char *fmt, ...) __attribute__ ((__noreturn__, __format__ (__printf__, 1, 2))) { va_list ap; va_start(ap, fmt); vprintf(fmt, ap); va_end(ap); printf("\n"); fflush(stdout); abort(); } /** * Free a data element allocated in the library. * * @param ptr data to be freed. * * @ingroup hx509_misc */ void hx509_xfree(void *ptr) { free(ptr); } /** * */ int _hx509_cert_to_env(hx509_context context, hx509_cert cert, hx509_env *env) { ExtKeyUsage eku; hx509_name name; char *buf; int ret; hx509_env envcert = NULL; *env = NULL; /* version */ ret = asprintf(&buf, "%d", _hx509_cert_get_version(_hx509_get_cert(cert))); if (ret == -1) goto out; ret = hx509_env_add(context, &envcert, "version", buf); free(buf); if (ret) goto out; /* subject */ ret = hx509_cert_get_subject(cert, &name); if (ret) goto out; ret = hx509_name_to_string(name, &buf); if (ret) { hx509_name_free(&name); goto out; } ret = hx509_env_add(context, &envcert, "subject", buf); hx509_name_free(&name); if (ret) goto out; /* issuer */ ret = hx509_cert_get_issuer(cert, &name); if (ret) goto out; ret = hx509_name_to_string(name, &buf); hx509_name_free(&name); if (ret) goto out; ret = hx509_env_add(context, &envcert, "issuer", buf); hx509_xfree(buf); if (ret) goto out; /* eku */ ret = _hx509_cert_get_eku(context, cert, &eku); if (ret == HX509_EXTENSION_NOT_FOUND) ; else if (ret != 0) goto out; else { size_t i; hx509_env enveku = NULL; for (i = 0; i < eku.len; i++) { ret = der_print_heim_oid(&eku.val[i], '.', &buf); if (ret) { free_ExtKeyUsage(&eku); hx509_env_free(&enveku); goto out; } ret = hx509_env_add(context, &enveku, buf, "oid-name-here"); free(buf); if (ret) { free_ExtKeyUsage(&eku); hx509_env_free(&enveku); goto out; } } free_ExtKeyUsage(&eku); ret = hx509_env_add_binding(context, &envcert, "eku", enveku); if (ret) { hx509_env_free(&enveku); goto out; } } { Certificate *c = _hx509_get_cert(cert); heim_octet_string os, sig; hx509_env envhash = NULL; os.data = c->tbsCertificate.subjectPublicKeyInfo.subjectPublicKey.data; os.length = c->tbsCertificate.subjectPublicKeyInfo.subjectPublicKey.length / 8; ret = _hx509_create_signature(context, NULL, hx509_signature_sha1(), &os, NULL, &sig); if (ret != 0) goto out; ret = hex_encode(sig.data, sig.length, &buf); der_free_octet_string(&sig); if (ret < 0) { ret = ENOMEM; hx509_set_error_string(context, 0, ret, "Out of memory"); goto out; } ret = hx509_env_add(context, &envhash, "sha1", buf); free(buf); if (ret) goto out; ret = hx509_env_add_binding(context, &envcert, "hash", envhash); if (ret) { hx509_env_free(&envhash); goto out; } } ret = hx509_env_add_binding(context, env, "certificate", envcert); if (ret) goto out; return 0; out: hx509_env_free(&envcert); return ret; } /** * Print a simple representation of a certificate * * @param context A hx509 context, can be NULL * @param cert certificate to print * @param out the stdio output stream, if NULL, stdout is used * * @return An hx509 error code * * @ingroup hx509_cert */ int hx509_print_cert(hx509_context context, hx509_cert cert, FILE *out) { hx509_name name; char *str; int ret; if (out == NULL) out = stderr; ret = hx509_cert_get_issuer(cert, &name); if (ret) return ret; hx509_name_to_string(name, &str); hx509_name_free(&name); fprintf(out, " issuer: \"%s\"\n", str); free(str); ret = hx509_cert_get_subject(cert, &name); if (ret) return ret; hx509_name_to_string(name, &str); hx509_name_free(&name); fprintf(out, " subject: \"%s\"\n", str); free(str); { heim_integer serialNumber; ret = hx509_cert_get_serialnumber(cert, &serialNumber); if (ret) return ret; ret = der_print_hex_heim_integer(&serialNumber, &str); if (ret) return ret; der_free_heim_integer(&serialNumber); fprintf(out, " serial: %s\n", str); free(str); } printf(" keyusage: "); ret = hx509_cert_keyusage_print(context, cert, &str); if (ret == 0) { fprintf(out, "%s\n", str); free(str); } else fprintf(out, "no"); return 0; } heimdal-7.5.0/lib/hx509/print.c0000644000175000017500000006435213212137553014211 0ustar niknik/* * Copyright (c) 2004 - 2007 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "hx_locl.h" /** * @page page_print Hx509 printing functions * * See the library functions here: @ref hx509_print */ struct hx509_validate_ctx_data { int flags; hx509_vprint_func vprint_func; void *ctx; }; struct cert_status { unsigned int selfsigned:1; unsigned int isca:1; unsigned int isproxy:1; unsigned int haveSAN:1; unsigned int haveIAN:1; unsigned int haveSKI:1; unsigned int haveAKI:1; unsigned int haveCRLDP:1; }; /* * */ static int Time2string(const Time *T, char **str) { time_t t; char *s; struct tm *tm; *str = NULL; t = _hx509_Time2time_t(T); tm = gmtime (&t); s = malloc(30); if (s == NULL) return ENOMEM; strftime(s, 30, "%Y-%m-%d %H:%M:%S", tm); *str = s; return 0; } /** * Helper function to print on stdout for: * - hx509_oid_print(), * - hx509_bitstring_print(), * - hx509_validate_ctx_set_print(). * * @param ctx the context to the print function. If the ctx is NULL, * stdout is used. * @param fmt the printing format. * @param va the argumet list. * * @ingroup hx509_print */ void hx509_print_stdout(void *ctx, const char *fmt, va_list va) { FILE *f = ctx; if (f == NULL) f = stdout; vfprintf(f, fmt, va); } static void print_func(hx509_vprint_func func, void *ctx, const char *fmt, ...) { va_list va; va_start(va, fmt); (*func)(ctx, fmt, va); va_end(va); } /** * Print a oid to a string. * * @param oid oid to print * @param str allocated string, free with hx509_xfree(). * * @return An hx509 error code, see hx509_get_error_string(). * * @ingroup hx509_print */ int hx509_oid_sprint(const heim_oid *oid, char **str) { return der_print_heim_oid(oid, '.', str); } /** * Print a oid using a hx509_vprint_func function. To print to stdout * use hx509_print_stdout(). * * @param oid oid to print * @param func hx509_vprint_func to print with. * @param ctx context variable to hx509_vprint_func function. * * @ingroup hx509_print */ void hx509_oid_print(const heim_oid *oid, hx509_vprint_func func, void *ctx) { char *str; hx509_oid_sprint(oid, &str); print_func(func, ctx, "%s", str); free(str); } /** * Print a bitstring using a hx509_vprint_func function. To print to * stdout use hx509_print_stdout(). * * @param b bit string to print. * @param func hx509_vprint_func to print with. * @param ctx context variable to hx509_vprint_func function. * * @ingroup hx509_print */ void hx509_bitstring_print(const heim_bit_string *b, hx509_vprint_func func, void *ctx) { size_t i; print_func(func, ctx, "\tlength: %d\n\t", b->length); for (i = 0; i < (b->length + 7) / 8; i++) print_func(func, ctx, "%02x%s%s", ((unsigned char *)b->data)[i], i < (b->length - 7) / 8 && (i == 0 || (i % 16) != 15) ? ":" : "", i != 0 && (i % 16) == 15 ? (i <= ((b->length + 7) / 8 - 2) ? "\n\t" : "\n"):""); } /** * Print certificate usage for a certificate to a string. * * @param context A hx509 context. * @param c a certificate print the keyusage for. * @param s the return string with the keysage printed in to, free * with hx509_xfree(). * * @return An hx509 error code, see hx509_get_error_string(). * * @ingroup hx509_print */ int hx509_cert_keyusage_print(hx509_context context, hx509_cert c, char **s) { KeyUsage ku; char buf[256]; int ret; *s = NULL; ret = _hx509_cert_get_keyusage(context, c, &ku); if (ret) return ret; unparse_flags(KeyUsage2int(ku), asn1_KeyUsage_units(), buf, sizeof(buf)); *s = strdup(buf); if (*s == NULL) { hx509_set_error_string(context, 0, ENOMEM, "out of memory"); return ENOMEM; } return 0; } /* * */ static void validate_vprint(void *c, const char *fmt, va_list va) { hx509_validate_ctx ctx = c; if (ctx->vprint_func == NULL) return; (ctx->vprint_func)(ctx->ctx, fmt, va); } static void validate_print(hx509_validate_ctx ctx, int flags, const char *fmt, ...) { va_list va; if ((ctx->flags & flags) == 0) return; va_start(va, fmt); validate_vprint(ctx, fmt, va); va_end(va); } /* * Dont Care, SHOULD critical, SHOULD NOT critical, MUST critical, * MUST NOT critical */ enum critical_flag { D_C = 0, S_C, S_N_C, M_C, M_N_C }; static int check_Null(hx509_validate_ctx ctx, struct cert_status *status, enum critical_flag cf, const Extension *e) { switch(cf) { case D_C: break; case S_C: if (!e->critical) validate_print(ctx, HX509_VALIDATE_F_VALIDATE, "\tCritical not set on SHOULD\n"); break; case S_N_C: if (e->critical) validate_print(ctx, HX509_VALIDATE_F_VALIDATE, "\tCritical set on SHOULD NOT\n"); break; case M_C: if (!e->critical) validate_print(ctx, HX509_VALIDATE_F_VALIDATE, "\tCritical not set on MUST\n"); break; case M_N_C: if (e->critical) validate_print(ctx, HX509_VALIDATE_F_VALIDATE, "\tCritical set on MUST NOT\n"); break; default: _hx509_abort("internal check_Null state error"); } return 0; } static int check_subjectKeyIdentifier(hx509_validate_ctx ctx, struct cert_status *status, enum critical_flag cf, const Extension *e) { SubjectKeyIdentifier si; size_t size; int ret; status->haveSKI = 1; check_Null(ctx, status, cf, e); ret = decode_SubjectKeyIdentifier(e->extnValue.data, e->extnValue.length, &si, &size); if (ret) { validate_print(ctx, HX509_VALIDATE_F_VALIDATE, "Decoding SubjectKeyIdentifier failed: %d", ret); return 1; } if (size != e->extnValue.length) { validate_print(ctx, HX509_VALIDATE_F_VALIDATE, "Decoding SKI ahve extra bits on the end"); return 1; } if (si.length == 0) validate_print(ctx, HX509_VALIDATE_F_VALIDATE, "SKI is too short (0 bytes)"); if (si.length > 20) validate_print(ctx, HX509_VALIDATE_F_VALIDATE, "SKI is too long"); { char *id; hex_encode(si.data, si.length, &id); if (id) { validate_print(ctx, HX509_VALIDATE_F_VERBOSE, "\tsubject key id: %s\n", id); free(id); } } free_SubjectKeyIdentifier(&si); return 0; } static int check_authorityKeyIdentifier(hx509_validate_ctx ctx, struct cert_status *status, enum critical_flag cf, const Extension *e) { AuthorityKeyIdentifier ai; size_t size; int ret; status->haveAKI = 1; check_Null(ctx, status, cf, e); ret = decode_AuthorityKeyIdentifier(e->extnValue.data, e->extnValue.length, &ai, &size); if (ret) { validate_print(ctx, HX509_VALIDATE_F_VALIDATE, "Decoding AuthorityKeyIdentifier failed: %d", ret); return 1; } if (size != e->extnValue.length) { validate_print(ctx, HX509_VALIDATE_F_VALIDATE, "Decoding SKI ahve extra bits on the end"); return 1; } if (ai.keyIdentifier) { char *id; hex_encode(ai.keyIdentifier->data, ai.keyIdentifier->length, &id); if (id) { validate_print(ctx, HX509_VALIDATE_F_VERBOSE, "\tauthority key id: %s\n", id); free(id); } } return 0; } static int check_extKeyUsage(hx509_validate_ctx ctx, struct cert_status *status, enum critical_flag cf, const Extension *e) { ExtKeyUsage eku; size_t size, i; int ret; check_Null(ctx, status, cf, e); ret = decode_ExtKeyUsage(e->extnValue.data, e->extnValue.length, &eku, &size); if (ret) { validate_print(ctx, HX509_VALIDATE_F_VALIDATE, "Decoding ExtKeyUsage failed: %d", ret); return 1; } if (size != e->extnValue.length) { validate_print(ctx, HX509_VALIDATE_F_VALIDATE, "Padding data in EKU"); free_ExtKeyUsage(&eku); return 1; } if (eku.len == 0) { validate_print(ctx, HX509_VALIDATE_F_VALIDATE, "ExtKeyUsage length is 0"); return 1; } for (i = 0; i < eku.len; i++) { char *str; ret = der_print_heim_oid (&eku.val[i], '.', &str); if (ret) { validate_print(ctx, HX509_VALIDATE_F_VALIDATE, "\tEKU: failed to print oid %d", i); free_ExtKeyUsage(&eku); return 1; } validate_print(ctx, HX509_VALIDATE_F_VERBOSE, "\teku-%d: %s\n", i, str);; free(str); } free_ExtKeyUsage(&eku); return 0; } static int check_pkinit_san(hx509_validate_ctx ctx, heim_any *a) { KRB5PrincipalName kn; unsigned i; size_t size; int ret; ret = decode_KRB5PrincipalName(a->data, a->length, &kn, &size); if (ret) { validate_print(ctx, HX509_VALIDATE_F_VALIDATE, "Decoding kerberos name in SAN failed: %d", ret); return 1; } if (size != a->length) { validate_print(ctx, HX509_VALIDATE_F_VALIDATE, "Decoding kerberos name have extra bits on the end"); return 1; } /* print kerberos principal, add code to quote / within components */ for (i = 0; i < kn.principalName.name_string.len; i++) { validate_print(ctx, HX509_VALIDATE_F_VERBOSE, "%s", kn.principalName.name_string.val[i]); if (i + 1 < kn.principalName.name_string.len) validate_print(ctx, HX509_VALIDATE_F_VERBOSE, "/"); } validate_print(ctx, HX509_VALIDATE_F_VERBOSE, "@"); validate_print(ctx, HX509_VALIDATE_F_VERBOSE, "%s", kn.realm); free_KRB5PrincipalName(&kn); return 0; } static int check_utf8_string_san(hx509_validate_ctx ctx, heim_any *a) { PKIXXmppAddr jid; size_t size; int ret; ret = decode_PKIXXmppAddr(a->data, a->length, &jid, &size); if (ret) { validate_print(ctx, HX509_VALIDATE_F_VALIDATE, "Decoding JID in SAN failed: %d", ret); return 1; } validate_print(ctx, HX509_VALIDATE_F_VERBOSE, "%s", jid); free_PKIXXmppAddr(&jid); return 0; } static int check_altnull(hx509_validate_ctx ctx, heim_any *a) { return 0; } static int check_CRLDistributionPoints(hx509_validate_ctx ctx, struct cert_status *status, enum critical_flag cf, const Extension *e) { CRLDistributionPoints dp; size_t size; int ret; size_t i; check_Null(ctx, status, cf, e); ret = decode_CRLDistributionPoints(e->extnValue.data, e->extnValue.length, &dp, &size); if (ret) { validate_print(ctx, HX509_VALIDATE_F_VALIDATE, "Decoding CRL Distribution Points failed: %d\n", ret); return 1; } validate_print(ctx, HX509_VALIDATE_F_VERBOSE, "CRL Distribution Points:\n"); for (i = 0 ; i < dp.len; i++) { if (dp.val[i].distributionPoint) { DistributionPointName dpname; heim_any *data = dp.val[i].distributionPoint; size_t j; ret = decode_DistributionPointName(data->data, data->length, &dpname, NULL); if (ret) { validate_print(ctx, HX509_VALIDATE_F_VALIDATE, "Failed to parse CRL Distribution Point Name: %d\n", ret); continue; } switch (dpname.element) { case choice_DistributionPointName_fullName: validate_print(ctx, HX509_VALIDATE_F_VERBOSE, "Fullname:\n"); for (j = 0 ; j < dpname.u.fullName.len; j++) { char *s; GeneralName *name = &dpname.u.fullName.val[j]; ret = hx509_general_name_unparse(name, &s); if (ret == 0 && s != NULL) { validate_print(ctx, HX509_VALIDATE_F_VERBOSE, " %s\n", s); free(s); } } break; case choice_DistributionPointName_nameRelativeToCRLIssuer: validate_print(ctx, HX509_VALIDATE_F_VERBOSE, "Unknown nameRelativeToCRLIssuer"); break; default: validate_print(ctx, HX509_VALIDATE_F_VALIDATE, "Unknown DistributionPointName"); break; } free_DistributionPointName(&dpname); } } free_CRLDistributionPoints(&dp); status->haveCRLDP = 1; return 0; } struct { const char *name; const heim_oid *oid; int (*func)(hx509_validate_ctx, heim_any *); } altname_types[] = { { "pk-init", &asn1_oid_id_pkinit_san, check_pkinit_san }, { "jabber", &asn1_oid_id_pkix_on_xmppAddr, check_utf8_string_san }, { "dns-srv", &asn1_oid_id_pkix_on_dnsSRV, check_altnull }, { "card-id", &asn1_oid_id_uspkicommon_card_id, check_altnull }, { "Microsoft NT-PRINCIPAL-NAME", &asn1_oid_id_pkinit_ms_san, check_utf8_string_san } }; static int check_altName(hx509_validate_ctx ctx, struct cert_status *status, const char *name, enum critical_flag cf, const Extension *e) { GeneralNames gn; size_t size; int ret; size_t i; check_Null(ctx, status, cf, e); if (e->extnValue.length == 0) { validate_print(ctx, HX509_VALIDATE_F_VALIDATE, "%sAltName empty, not allowed", name); return 1; } ret = decode_GeneralNames(e->extnValue.data, e->extnValue.length, &gn, &size); if (ret) { validate_print(ctx, HX509_VALIDATE_F_VALIDATE, "\tret = %d while decoding %s GeneralNames\n", ret, name); return 1; } if (gn.len == 0) { validate_print(ctx, HX509_VALIDATE_F_VALIDATE, "%sAltName generalName empty, not allowed\n", name); return 1; } for (i = 0; i < gn.len; i++) { switch (gn.val[i].element) { case choice_GeneralName_otherName: { unsigned j; validate_print(ctx, HX509_VALIDATE_F_VERBOSE, "%sAltName otherName ", name); for (j = 0; j < sizeof(altname_types)/sizeof(altname_types[0]); j++) { if (der_heim_oid_cmp(altname_types[j].oid, &gn.val[i].u.otherName.type_id) != 0) continue; validate_print(ctx, HX509_VALIDATE_F_VERBOSE, "%s: ", altname_types[j].name); (*altname_types[j].func)(ctx, &gn.val[i].u.otherName.value); break; } if (j == sizeof(altname_types)/sizeof(altname_types[0])) { hx509_oid_print(&gn.val[i].u.otherName.type_id, validate_vprint, ctx); validate_print(ctx, HX509_VALIDATE_F_VERBOSE, " unknown"); } validate_print(ctx, HX509_VALIDATE_F_VERBOSE, "\n"); break; } default: { char *s; ret = hx509_general_name_unparse(&gn.val[i], &s); if (ret) { validate_print(ctx, HX509_VALIDATE_F_VALIDATE, "ret = %d unparsing GeneralName\n", ret); return 1; } validate_print(ctx, HX509_VALIDATE_F_VERBOSE, "%s\n", s); free(s); break; } } } free_GeneralNames(&gn); return 0; } static int check_subjectAltName(hx509_validate_ctx ctx, struct cert_status *status, enum critical_flag cf, const Extension *e) { status->haveSAN = 1; return check_altName(ctx, status, "subject", cf, e); } static int check_issuerAltName(hx509_validate_ctx ctx, struct cert_status *status, enum critical_flag cf, const Extension *e) { status->haveIAN = 1; return check_altName(ctx, status, "issuer", cf, e); } static int check_basicConstraints(hx509_validate_ctx ctx, struct cert_status *status, enum critical_flag cf, const Extension *e) { BasicConstraints b; size_t size; int ret; check_Null(ctx, status, cf, e); ret = decode_BasicConstraints(e->extnValue.data, e->extnValue.length, &b, &size); if (ret) { printf("\tret = %d while decoding BasicConstraints\n", ret); return 0; } if (size != e->extnValue.length) printf("\tlength of der data isn't same as extension\n"); validate_print(ctx, HX509_VALIDATE_F_VERBOSE, "\tis %sa CA\n", b.cA && *b.cA ? "" : "NOT "); if (b.pathLenConstraint) validate_print(ctx, HX509_VALIDATE_F_VERBOSE, "\tpathLenConstraint: %d\n", *b.pathLenConstraint); if (b.cA) { if (*b.cA) { if (!e->critical) validate_print(ctx, HX509_VALIDATE_F_VALIDATE, "Is a CA and not BasicConstraints CRITICAL\n"); status->isca = 1; } else validate_print(ctx, HX509_VALIDATE_F_VALIDATE, "cA is FALSE, not allowed to be\n"); } free_BasicConstraints(&b); return 0; } static int check_proxyCertInfo(hx509_validate_ctx ctx, struct cert_status *status, enum critical_flag cf, const Extension *e) { check_Null(ctx, status, cf, e); status->isproxy = 1; return 0; } static int check_authorityInfoAccess(hx509_validate_ctx ctx, struct cert_status *status, enum critical_flag cf, const Extension *e) { AuthorityInfoAccessSyntax aia; size_t size; int ret; size_t i; check_Null(ctx, status, cf, e); ret = decode_AuthorityInfoAccessSyntax(e->extnValue.data, e->extnValue.length, &aia, &size); if (ret) { printf("\tret = %d while decoding AuthorityInfoAccessSyntax\n", ret); return 0; } for (i = 0; i < aia.len; i++) { char *str; validate_print(ctx, HX509_VALIDATE_F_VERBOSE, "\ttype: "); hx509_oid_print(&aia.val[i].accessMethod, validate_vprint, ctx); hx509_general_name_unparse(&aia.val[i].accessLocation, &str); validate_print(ctx, HX509_VALIDATE_F_VERBOSE, "\n\tdirname: %s\n", str); free(str); } free_AuthorityInfoAccessSyntax(&aia); return 0; } /* * */ struct { const char *name; const heim_oid *oid; int (*func)(hx509_validate_ctx ctx, struct cert_status *status, enum critical_flag cf, const Extension *); enum critical_flag cf; } check_extension[] = { #define ext(name, checkname) #name, &asn1_oid_id_x509_ce_##name, check_##checkname { ext(subjectDirectoryAttributes, Null), M_N_C }, { ext(subjectKeyIdentifier, subjectKeyIdentifier), M_N_C }, { ext(keyUsage, Null), S_C }, { ext(subjectAltName, subjectAltName), M_N_C }, { ext(issuerAltName, issuerAltName), S_N_C }, { ext(basicConstraints, basicConstraints), D_C }, { ext(cRLNumber, Null), M_N_C }, { ext(cRLReason, Null), M_N_C }, { ext(holdInstructionCode, Null), M_N_C }, { ext(invalidityDate, Null), M_N_C }, { ext(deltaCRLIndicator, Null), M_C }, { ext(issuingDistributionPoint, Null), M_C }, { ext(certificateIssuer, Null), M_C }, { ext(nameConstraints, Null), M_C }, { ext(cRLDistributionPoints, CRLDistributionPoints), S_N_C }, { ext(certificatePolicies, Null), 0 }, { ext(policyMappings, Null), M_N_C }, { ext(authorityKeyIdentifier, authorityKeyIdentifier), M_N_C }, { ext(policyConstraints, Null), D_C }, { ext(extKeyUsage, extKeyUsage), D_C }, { ext(freshestCRL, Null), M_N_C }, { ext(inhibitAnyPolicy, Null), M_C }, #undef ext #define ext(name, checkname) #name, &asn1_oid_id_pkix_pe_##name, check_##checkname { ext(proxyCertInfo, proxyCertInfo), M_C }, { ext(authorityInfoAccess, authorityInfoAccess), M_C }, #undef ext { "US Fed PKI - PIV Interim", &asn1_oid_id_uspkicommon_piv_interim, check_Null, D_C }, { "Netscape cert comment", &asn1_oid_id_netscape_cert_comment, check_Null, D_C }, { NULL, NULL, NULL, 0 } }; /** * Allocate a hx509 validation/printing context. * * @param context A hx509 context. * @param ctx a new allocated hx509 validation context, free with * hx509_validate_ctx_free(). * @return An hx509 error code, see hx509_get_error_string(). * * @ingroup hx509_print */ int hx509_validate_ctx_init(hx509_context context, hx509_validate_ctx *ctx) { *ctx = malloc(sizeof(**ctx)); if (*ctx == NULL) return ENOMEM; memset(*ctx, 0, sizeof(**ctx)); return 0; } /** * Set the printing functions for the validation context. * * @param ctx a hx509 valication context. * @param func the printing function to usea. * @param c the context variable to the printing function. * * @return An hx509 error code, see hx509_get_error_string(). * * @ingroup hx509_print */ void hx509_validate_ctx_set_print(hx509_validate_ctx ctx, hx509_vprint_func func, void *c) { ctx->vprint_func = func; ctx->ctx = c; } /** * Add flags to control the behaivor of the hx509_validate_cert() * function. * * @param ctx A hx509 validation context. * @param flags flags to add to the validation context. * * @return An hx509 error code, see hx509_get_error_string(). * * @ingroup hx509_print */ void hx509_validate_ctx_add_flags(hx509_validate_ctx ctx, int flags) { ctx->flags |= flags; } /** * Free an hx509 validate context. * * @param ctx the hx509 validate context to free. * * @ingroup hx509_print */ void hx509_validate_ctx_free(hx509_validate_ctx ctx) { free(ctx); } /** * Validate/Print the status of the certificate. * * @param context A hx509 context. * @param ctx A hx509 validation context. * @param cert the cerificate to validate/print. * @return An hx509 error code, see hx509_get_error_string(). * * @ingroup hx509_print */ int hx509_validate_cert(hx509_context context, hx509_validate_ctx ctx, hx509_cert cert) { Certificate *c = _hx509_get_cert(cert); TBSCertificate *t = &c->tbsCertificate; hx509_name issuer, subject; char *str; struct cert_status status; int ret; memset(&status, 0, sizeof(status)); if (_hx509_cert_get_version(c) != 3) validate_print(ctx, HX509_VALIDATE_F_VERBOSE, "Not version 3 certificate\n"); if ((t->version == NULL || *t->version < 2) && t->extensions) validate_print(ctx, HX509_VALIDATE_F_VALIDATE, "Not version 3 certificate with extensions\n"); if (_hx509_cert_get_version(c) >= 3 && t->extensions == NULL) validate_print(ctx, HX509_VALIDATE_F_VALIDATE, "Version 3 certificate without extensions\n"); ret = hx509_cert_get_subject(cert, &subject); if (ret) abort(); hx509_name_to_string(subject, &str); validate_print(ctx, HX509_VALIDATE_F_VERBOSE, "subject name: %s\n", str); free(str); ret = hx509_cert_get_issuer(cert, &issuer); if (ret) abort(); hx509_name_to_string(issuer, &str); validate_print(ctx, HX509_VALIDATE_F_VERBOSE, "issuer name: %s\n", str); free(str); if (hx509_name_cmp(subject, issuer) == 0) { status.selfsigned = 1; validate_print(ctx, HX509_VALIDATE_F_VERBOSE, "\tis a self-signed certificate\n"); } validate_print(ctx, HX509_VALIDATE_F_VERBOSE, "Validity:\n"); Time2string(&t->validity.notBefore, &str); validate_print(ctx, HX509_VALIDATE_F_VERBOSE, "\tnotBefore %s\n", str); free(str); Time2string(&t->validity.notAfter, &str); validate_print(ctx, HX509_VALIDATE_F_VERBOSE, "\tnotAfter %s\n", str); free(str); if (t->extensions) { size_t i, j; if (t->extensions->len == 0) { validate_print(ctx, HX509_VALIDATE_F_VALIDATE|HX509_VALIDATE_F_VERBOSE, "The empty extensions list is not " "allowed by PKIX\n"); } for (i = 0; i < t->extensions->len; i++) { for (j = 0; check_extension[j].name; j++) if (der_heim_oid_cmp(check_extension[j].oid, &t->extensions->val[i].extnID) == 0) break; if (check_extension[j].name == NULL) { int flags = HX509_VALIDATE_F_VERBOSE; if (t->extensions->val[i].critical) flags |= HX509_VALIDATE_F_VALIDATE; validate_print(ctx, flags, "don't know what "); if (t->extensions->val[i].critical) validate_print(ctx, flags, "and is CRITICAL "); if (ctx->flags & flags) hx509_oid_print(&t->extensions->val[i].extnID, validate_vprint, ctx); validate_print(ctx, flags, " is\n"); continue; } validate_print(ctx, HX509_VALIDATE_F_VALIDATE|HX509_VALIDATE_F_VERBOSE, "checking extension: %s\n", check_extension[j].name); (*check_extension[j].func)(ctx, &status, check_extension[j].cf, &t->extensions->val[i]); } } else validate_print(ctx, HX509_VALIDATE_F_VERBOSE, "no extensions\n"); if (status.isca) { if (!status.haveSKI) validate_print(ctx, HX509_VALIDATE_F_VALIDATE, "CA certificate have no SubjectKeyIdentifier\n"); } else { if (!status.haveAKI) validate_print(ctx, HX509_VALIDATE_F_VALIDATE, "Is not CA and doesn't have " "AuthorityKeyIdentifier\n"); } if (!status.haveSKI) validate_print(ctx, HX509_VALIDATE_F_VALIDATE, "Doesn't have SubjectKeyIdentifier\n"); if (status.isproxy && status.isca) validate_print(ctx, HX509_VALIDATE_F_VALIDATE, "Proxy and CA at the same time!\n"); if (status.isproxy) { if (status.haveSAN) validate_print(ctx, HX509_VALIDATE_F_VALIDATE, "Proxy and have SAN\n"); if (status.haveIAN) validate_print(ctx, HX509_VALIDATE_F_VALIDATE, "Proxy and have IAN\n"); } if (hx509_name_is_null_p(subject) && !status.haveSAN) validate_print(ctx, HX509_VALIDATE_F_VALIDATE, "NULL subject DN and doesn't have a SAN\n"); if (!status.selfsigned && !status.haveCRLDP) validate_print(ctx, HX509_VALIDATE_F_VALIDATE, "Not a CA nor PROXY and doesn't have" "CRL Dist Point\n"); if (status.selfsigned) { ret = _hx509_verify_signature_bitstring(context, cert, &c->signatureAlgorithm, &c->tbsCertificate._save, &c->signatureValue); if (ret == 0) validate_print(ctx, HX509_VALIDATE_F_VERBOSE, "Self-signed certificate was self-signed\n"); else validate_print(ctx, HX509_VALIDATE_F_VALIDATE, "Self-signed certificate NOT really self-signed!\n"); } hx509_name_free(&subject); hx509_name_free(&issuer); return 0; } heimdal-7.5.0/lib/hx509/char_map.h0000644000175000017500000000444613026237312014627 0ustar niknik#define Q_CONTROL_CHAR 1 #define Q_PRINTABLE 2 #define Q_RFC2253_QUOTE_FIRST 4 #define Q_RFC2253_QUOTE_LAST 8 #define Q_RFC2253_QUOTE 16 #define Q_RFC2253_HEX 32 #define Q_RFC2253 (Q_RFC2253_QUOTE_FIRST|Q_RFC2253_QUOTE_LAST|Q_RFC2253_QUOTE|Q_RFC2253_HEX) unsigned char char_map[] = { 0x21 , 0x21 , 0x21 , 0x21 , 0x21 , 0x21 , 0x21 , 0x21 , 0x21 , 0x21 , 0x21 , 0x21 , 0x21 , 0x21 , 0x21 , 0x21 , 0x21 , 0x21 , 0x21 , 0x21 , 0x21 , 0x21 , 0x21 , 0x21 , 0x21 , 0x21 , 0x21 , 0x21 , 0x21 , 0x21 , 0x21 , 0x21 , 0x06 , 0x00 , 0x00 , 0x10 , 0x00 , 0x00 , 0x00 , 0x00 , 0x00 , 0x00 , 0x00 , 0x12 , 0x12 , 0x02 , 0x02 , 0x02 , 0x02 , 0x02 , 0x02 , 0x02 , 0x02 , 0x02 , 0x02 , 0x02 , 0x02 , 0x02 , 0x02 , 0x10 , 0x10 , 0x12 , 0x10 , 0x02 , 0x00 , 0x02 , 0x02 , 0x02 , 0x02 , 0x02 , 0x02 , 0x02 , 0x02 , 0x02 , 0x02 , 0x02 , 0x02 , 0x02 , 0x02 , 0x02 , 0x02 , 0x02 , 0x02 , 0x02 , 0x02 , 0x02 , 0x02 , 0x02 , 0x02 , 0x02 , 0x02 , 0x00 , 0x00 , 0x00 , 0x00 , 0x00 , 0x00 , 0x02 , 0x02 , 0x02 , 0x02 , 0x02 , 0x02 , 0x02 , 0x02 , 0x02 , 0x02 , 0x02 , 0x02 , 0x02 , 0x02 , 0x02 , 0x02 , 0x02 , 0x02 , 0x02 , 0x02 , 0x02 , 0x02 , 0x02 , 0x02 , 0x02 , 0x02 , 0x00 , 0x00 , 0x00 , 0x00 , 0x21 , 0x21 , 0x21 , 0x21 , 0x21 , 0x21 , 0x21 , 0x21 , 0x21 , 0x21 , 0x21 , 0x21 , 0x21 , 0x21 , 0x21 , 0x21 , 0x21 , 0x21 , 0x21 , 0x21 , 0x21 , 0x21 , 0x21 , 0x21 , 0x21 , 0x21 , 0x21 , 0x21 , 0x21 , 0x21 , 0x21 , 0x21 , 0x21 , 0x21 , 0x21 , 0x21 , 0x21 , 0x21 , 0x21 , 0x21 , 0x21 , 0x21 , 0x21 , 0x21 , 0x21 , 0x21 , 0x21 , 0x21 , 0x21 , 0x21 , 0x21 , 0x21 , 0x21 , 0x21 , 0x21 , 0x21 , 0x21 , 0x21 , 0x21 , 0x21 , 0x21 , 0x21 , 0x21 , 0x21 , 0x21 , 0x21 , 0x21 , 0x21 , 0x21 , 0x21 , 0x21 , 0x21 , 0x21 , 0x21 , 0x21 , 0x21 , 0x21 , 0x21 , 0x21 , 0x21 , 0x21 , 0x21 , 0x21 , 0x21 , 0x21 , 0x21 , 0x21 , 0x21 , 0x21 , 0x21 , 0x21 , 0x21 , 0x21 , 0x21 , 0x21 , 0x21 , 0x21 , 0x21 , 0x21 , 0x21 , 0x21 , 0x21 , 0x21 , 0x21 , 0x21 , 0x21 , 0x21 , 0x21 , 0x21 , 0x21 , 0x21 , 0x21 , 0x21 , 0x21 , 0x21 , 0x21 , 0x21 , 0x21 , 0x21 , 0x21 , 0x21 , 0x21 , 0x21 , 0x21 , 0x21 , 0x21 , 0x21 , 0x21 , 0x21 }; heimdal-7.5.0/lib/hx509/NTMakefile0000644000175000017500000001373313131326447014612 0ustar niknik######################################################################## # # Copyright (c) 2009-2017, Secure Endpoints Inc. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # - Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # # - Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in # the documentation and/or other materials provided with the # distribution. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS # FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE # COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, # BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN # ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. # RELDIR=lib\hx509 intcflags=-I$(OBJ) localcflags=-DASN1_LIB !include ../../windows/NTMakefile.w32 gen_files_ocsp = $(OBJ)\asn1_ocsp_asn1.x gen_files_pkcs10 = $(OBJ)\asn1_pkcs10_asn1.x gen_files_crmf = $(OBJ)\asn1_crmf_asn1.x libhx509_la_OBJS = \ $(OBJ)\ca.obj \ $(OBJ)\cert.obj \ $(OBJ)\cms.obj \ $(OBJ)\collector.obj \ $(OBJ)\crypto.obj \ $(OBJ)\crypto-ec.obj \ $(OBJ)\error.obj \ $(OBJ)\env.obj \ $(OBJ)\file.obj \ $(OBJ)\hx509_err.obj \ $(OBJ)\sel.obj \ $(OBJ)\sel-gram.obj \ $(OBJ)\sel-lex.obj \ $(OBJ)\keyset.obj \ $(OBJ)\ks_dir.obj \ $(OBJ)\ks_file.obj \ $(OBJ)\ks_mem.obj \ $(OBJ)\ks_null.obj \ $(OBJ)\ks_p11.obj \ $(OBJ)\ks_p12.obj \ $(OBJ)\ks_keychain.obj \ $(OBJ)\lock.obj \ $(OBJ)\name.obj \ $(OBJ)\peer.obj \ $(OBJ)\print.obj \ $(OBJ)\softp11.obj \ $(OBJ)\req.obj \ $(OBJ)\revoke.obj \ $(gen_files_ocsp:.x=.obj) \ $(gen_files_pkcs10:.x=.obj) $(LIBHX509): $(libhx509_la_OBJS) $(LIBCON) dist_libhx509_la_SOURCES = \ $(SRCDIR)\ca.c \ $(SRCDIR)\cert.c \ $(SRCDIR)\cms.c \ $(SRCDIR)\collector.c \ $(SRCDIR)\crypto.c \ $(SRCDIR)\crypto-ec.c \ $(SRCDIR)\doxygen.c \ $(SRCDIR)\error.c \ $(SRCDIR)\env.c \ $(SRCDIR)\file.c \ $(SRCDIR)\hx509.h \ $(SRCDIR)\hx_locl.h \ $(SRCDIR)\sel.c \ $(SRCDIR)\sel.h \ $(SRCDIR)\sel-gram.y \ $(SRCDIR)\sel-lex.l \ $(SRCDIR)\keyset.c \ $(SRCDIR)\ks_dir.c \ $(SRCDIR)\ks_file.c \ $(SRCDIR)\ks_mem.c \ $(SRCDIR)\ks_null.c \ $(SRCDIR)\ks_p11.c \ $(SRCDIR)\ks_p12.c \ $(SRCDIR)\ks_keychain.c \ $(SRCDIR)\lock.c \ $(SRCDIR)\name.c \ $(SRCDIR)\peer.c \ $(SRCDIR)\print.c \ $(SRCDIR)\softp11.c \ $(SRCDIR)\ref\pkcs11.h \ $(SRCDIR)\req.c \ $(SRCDIR)\revoke.c asn1_compile=$(BINDIR)\asn1_compile.exe $(gen_files_ocsp:.x=.c): $$(@R).x $(gen_files_pkcs10:.x=.c): $$(@R).x $(gen_files_crmf:.x=.c): $$(@R).x $(gen_files_ocsp) $(OBJ)\ocsp_asn1.hx: $(asn1_compile) ocsp.asn1 cd $(OBJ) $(asn1_compile) --one-code-file \ --preserve-binary=OCSPTBSRequest \ --preserve-binary=OCSPResponseData \ $(SRCDIR)\ocsp.asn1 ocsp_asn1 \ || ( $(RM) -f $(gen_files_ocsp) $(OBJ)\ocsp_asn1.h ; exit /b 1 ) cd $(SRCDIR) $(gen_files_pkcs10) $(OBJ)\pkcs10_asn1.hx: $(asn1_compile) pkcs10.asn1 cd $(OBJ) $(asn1_compile) --one-code-file \ --preserve-binary=CertificationRequestInfo \ $(SRCDIR)\pkcs10.asn1 pkcs10_asn1 \ || ( $(RM) -f $(gen_files_pkcs10) $(OBJ)\pkcs10_asn1.h ; exit /b 1 ) cd $(SRCDIR) $(gen_files_crmf) $(OBJ)\crmf_asn1.hx: $(asn1_compile) crmf.asn1 cd $(OBJ) $(asn1_compile) --one-code-file $(SRCDIR)\crmf.asn1 crmf_asn1 \ || ( $(RM) -f $(gen_files_crmf) $(OBJ)\crmf_asn1.h ; exit /b 1 ) cd $(SRCDIR) INCFILES= \ $(INCDIR)\hx509.h \ $(INCDIR)\hx509-protos.h \ $(INCDIR)\hx509-private.h \ $(INCDIR)\hx509_err.h \ $(INCDIR)\ocsp_asn1.h \ $(INCDIR)\pkcs10_asn1.h \ $(INCDIR)\crmf_asn1.h \ $(OBJ)\ocsp_asn1-priv.h \ $(OBJ)\pkcs10_asn1-priv.h \ $(OBJ)\crmf_asn1-priv.h hxtool.c: $(OBJ)\hxtool-commands.h SLC=$(BINDIR)\slc.exe $(OBJ)\hxtool-commands.c $(OBJ)\hxtool-commands.h: hxtool-commands.in $(SLC) cd $(OBJ) $(CP) $(SRCDIR)\hxtool-commands.in $(OBJ)\hxtool-commands.in $(SLC) hxtool-commands.in cd $(SRCDIR) $(BINDIR)\hxtool.exe: $(OBJ)\tool\hxtool.obj $(OBJ)\tool\hxtool-commands.obj $(LIBHEIMDAL) $(OBJ)\hxtool-version.res $(EXECONLINK) $(LIBHEIMDAL) $(LIBROKEN) $(LIBSL) $(LIBVERS) $(LIBCOMERR) $(LIB_openssl_crypto) $(EXEPREP) $(OBJ)\hx509-protos.h: cd $(OBJ) $(PERL) $(SRCDIR)\..\..\cf\make-proto.pl -R "^(_|^C)" -E HX509_LIB -q -P remove -o hx509-protos.h $(dist_libhx509_la_SOURCES) || $(RM) -f hx509-protos.h cd $(SRCDIR) $(OBJ)\hx509-private.h: cd $(OBJ) $(PERL) $(SRCDIR)\..\..\cf\make-proto.pl -q -P remove -p hx509-private.h $(dist_libhx509_la_SOURCES) || $(RM) -f hx509-private.h cd $(SRCDIR) $(OBJ)\hx509_err.c $(OBJ)\hx509_err.h: hx509_err.et cd $(OBJ) $(BINDIR)\compile_et.exe $(SRCDIR)\hx509_err.et cd $(SRCDIR) $(OBJ)\sel-gram.obj: $(OBJ)\sel-gram.c $(C2OBJ) -I$(SRCDIR) $(OBJ)\sel-lex.obj: $(OBJ)\sel-lex.c $(C2OBJ) -I$(SRCDIR) -I$(OBJ) -DYY_NO_UNISTD_H $(OBJ)\sel-gram.c: sel-gram.y $(YACC) -o $@ --defines=$(OBJ)\sel-gram.h sel-gram.y $(OBJ)\sel-lex.c: sel-lex.l $(LEX) -P_hx509_sel_yy -o$@ sel-lex.l all:: $(INCFILES) $(LIBHX509) prep:: mktooldir mktooldir: ! if !exist($(OBJ)\tool) $(MKDIR) $(OBJ)\tool ! endif all-tools:: $(BINDIR)\hxtool.exe clean:: -$(RM) $(BINDIR)\hxtool.* -$(RM) $(OBJ)\tool\*.* {}.c{$(OBJ)\tool}.obj:: $(C2OBJ_C) /Fd$(OBJ)\tool\ /Fo$(OBJ)\tool\ $(MPOPT) /UASN1_LIB $< {$(OBJ)}.c{$(OBJ)\tool}.obj:: $(C2OBJ_C) /Fd$(OBJ)\tool\ /Fo$(OBJ)\tool\ $(MPOPT) /UASN1_LIB $< heimdal-7.5.0/lib/hx509/ks_null.c0000644000175000017500000000520513026237312014511 0ustar niknik/* * Copyright (c) 2005 - 2006 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "hx_locl.h" static int null_init(hx509_context context, hx509_certs certs, void **data, int flags, const char *residue, hx509_lock lock) { *data = NULL; return 0; } static int null_free(hx509_certs certs, void *data) { assert(data == NULL); return 0; } static int null_iter_start(hx509_context context, hx509_certs certs, void *data, void **cursor) { *cursor = NULL; return 0; } static int null_iter(hx509_context context, hx509_certs certs, void *data, void *iter, hx509_cert *cert) { *cert = NULL; return ENOENT; } static int null_iter_end(hx509_context context, hx509_certs certs, void *data, void *cursor) { assert(cursor == NULL); return 0; } struct hx509_keyset_ops keyset_null = { "NULL", 0, null_init, NULL, null_free, NULL, NULL, null_iter_start, null_iter, null_iter_end, NULL, NULL, NULL }; void _hx509_ks_null_register(hx509_context context) { _hx509_ks_register(context, &keyset_null); } heimdal-7.5.0/lib/hx509/ref/0000755000175000017500000000000013214604041013444 5ustar niknikheimdal-7.5.0/lib/hx509/ref/pkcs11.h0000644000175000017500000015121213026237312014725 0ustar niknik/* pkcs11.h Copyright 2006, 2007 g10 Code GmbH Copyright 2006 Andreas Jellinghaus This file is free software; as a special exception the author gives unlimited permission to copy and/or distribute it, with or without modifications, as long as this notice is preserved. This file is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY, to the extent permitted by law; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. */ /* Please submit changes back to the Scute project at http://www.scute.org/ (or send them to marcus@g10code.com), so that they can be picked up by other projects from there as well. */ /* This file is a modified implementation of the PKCS #11 standard by RSA Security Inc. It is mostly a drop-in replacement, with the following change: This header file does not require any macro definitions by the user (like CK_DEFINE_FUNCTION etc). In fact, it defines those macros for you (if useful, some are missing, let me know if you need more). There is an additional API available that does comply better to the GNU coding standard. It can be switched on by defining CRYPTOKI_GNU before including this header file. For this, the following changes are made to the specification: All structure types are changed to a "struct ck_foo" where CK_FOO is the type name in PKCS #11. All non-structure types are changed to ck_foo_t where CK_FOO is the lowercase version of the type name in PKCS #11. The basic types (CK_ULONG et al.) are removed without substitute. All members of structures are modified in the following way: Type indication prefixes are removed, and underscore characters are inserted before words. Then the result is lowercased. Note that function names are still in the original case, as they need for ABI compatibility. CK_FALSE, CK_TRUE and NULL_PTR are removed without substitute. Use . If CRYPTOKI_COMPAT is defined before including this header file, then none of the API changes above take place, and the API is the one defined by the PKCS #11 standard. */ #ifndef PKCS11_H #define PKCS11_H 1 #if defined(__cplusplus) extern "C" { #endif /* The version of cryptoki we implement. The revision is changed with each modification of this file. If you do not use the "official" version of this file, please consider deleting the revision macro (you may use a macro with a different name to keep track of your versions). */ #define CRYPTOKI_VERSION_MAJOR 2 #define CRYPTOKI_VERSION_MINOR 30 #define CRYPTOKI_VERSION_REVISION 0 #define CRYPTOKI_VERSION_AMENDMENT 0 /* Compatibility interface is default, unless CRYPTOKI_GNU is given. */ #ifndef CRYPTOKI_GNU #ifndef CRYPTOKI_COMPAT #define CRYPTOKI_COMPAT 1 #endif #endif /* System dependencies. */ #if defined(_WIN32) || defined(CRYPTOKI_FORCE_WIN32) /* There is a matching pop below. */ #pragma pack(push, cryptoki, 1) #ifdef CRYPTOKI_EXPORTS #define CK_SPEC __declspec(dllexport) #else #define CK_SPEC __declspec(dllimport) #endif #else #if defined(CRYPTOKI_VISIBILITY) && defined(CRYPTOKI_EXPORTS) #define CK_SPEC __attribute__((visibility("default"))) #else #define CK_SPEC #endif #endif #ifdef CRYPTOKI_COMPAT /* If we are in compatibility mode, switch all exposed names to the PKCS #11 variant. There are corresponding #undefs below. */ #define ck_flags_t CK_FLAGS #define ck_version _CK_VERSION #define ck_info _CK_INFO #define cryptoki_version cryptokiVersion #define manufacturer_id manufacturerID #define library_description libraryDescription #define library_version libraryVersion #define ck_notification_t CK_NOTIFICATION #define ck_slot_id_t CK_SLOT_ID #define ck_slot_info _CK_SLOT_INFO #define slot_description slotDescription #define hardware_version hardwareVersion #define firmware_version firmwareVersion #define ck_token_info _CK_TOKEN_INFO #define serial_number serialNumber #define max_session_count ulMaxSessionCount #define session_count ulSessionCount #define max_rw_session_count ulMaxRwSessionCount #define rw_session_count ulRwSessionCount #define max_pin_len ulMaxPinLen #define min_pin_len ulMinPinLen #define total_public_memory ulTotalPublicMemory #define free_public_memory ulFreePublicMemory #define total_private_memory ulTotalPrivateMemory #define free_private_memory ulFreePrivateMemory #define utc_time utcTime #define ck_session_handle_t CK_SESSION_HANDLE #define ck_user_type_t CK_USER_TYPE #define ck_state_t CK_STATE #define ck_session_info _CK_SESSION_INFO #define slot_id slotID #define device_error ulDeviceError #define ck_object_handle_t CK_OBJECT_HANDLE #define ck_object_class_t CK_OBJECT_CLASS #define ck_hw_feature_type_t CK_HW_FEATURE_TYPE #define ck_key_type_t CK_KEY_TYPE #define ck_certificate_type_t CK_CERTIFICATE_TYPE #define ck_attribute_type_t CK_ATTRIBUTE_TYPE #define ck_attribute _CK_ATTRIBUTE #define value pValue #define value_len ulValueLen #define ck_date _CK_DATE #define ck_mechanism_type_t CK_MECHANISM_TYPE #define ck_mechanism _CK_MECHANISM #define parameter pParameter #define parameter_len ulParameterLen #define ck_mechanism_info _CK_MECHANISM_INFO #define min_key_size ulMinKeySize #define max_key_size ulMaxKeySize #define hash_alg hashAlg #define source_data pSourceData #define source_data_len ulSourceDataLen #define slen sLen #define ck_ec_kdf_type_t CK_EC_KDF_TYPE #define shared_data_len ulSharedDataLen #define shared_data pSharedData #define public_data_len ulPublicDataLen #define public_data pPublicData #define private_data_len ulPrivateDataLen #define private_data hPrivateData #define public_data_len2 ulPublicDataLen2 #define public_data2 pPublicData2 #define public_key publicKey #define ck_x9_42_dh_kdf_type_t CK_X9_42_DH_KDF_TYPE #define other_info_len ulOtherInfoLen #define other_info pOtherInfo #define data pData #define len ulLen #define ck_rv_t CK_RV #define ck_notify_t CK_NOTIFY #define ck_function_list _CK_FUNCTION_LIST #define ck_createmutex_t CK_CREATEMUTEX #define ck_destroymutex_t CK_DESTROYMUTEX #define ck_lockmutex_t CK_LOCKMUTEX #define ck_unlockmutex_t CK_UNLOCKMUTEX #define ck_c_initialize_args _CK_C_INITIALIZE_ARGS #define create_mutex CreateMutex #define destroy_mutex DestroyMutex #define lock_mutex LockMutex #define unlock_mutex UnlockMutex #define reserved pReserved #endif /* CRYPTOKI_COMPAT */ typedef unsigned long ck_flags_t; struct ck_version { unsigned char major; unsigned char minor; }; struct ck_info { struct ck_version cryptoki_version; unsigned char manufacturer_id[32]; ck_flags_t flags; unsigned char library_description[32]; struct ck_version library_version; }; typedef unsigned long ck_notification_t; #define CKN_SURRENDER (0) #define CKN_OTP_CHANGED (1) typedef unsigned long ck_slot_id_t; struct ck_slot_info { unsigned char slot_description[64]; unsigned char manufacturer_id[32]; ck_flags_t flags; struct ck_version hardware_version; struct ck_version firmware_version; }; #define CKF_TOKEN_PRESENT (1 << 0) #define CKF_REMOVABLE_DEVICE (1 << 1) #define CKF_HW_SLOT (1 << 2) #define CKF_ARRAY_ATTRIBUTE (1 << 30) struct ck_token_info { unsigned char label[32]; unsigned char manufacturer_id[32]; unsigned char model[16]; unsigned char serial_number[16]; ck_flags_t flags; unsigned long max_session_count; unsigned long session_count; unsigned long max_rw_session_count; unsigned long rw_session_count; unsigned long max_pin_len; unsigned long min_pin_len; unsigned long total_public_memory; unsigned long free_public_memory; unsigned long total_private_memory; unsigned long free_private_memory; struct ck_version hardware_version; struct ck_version firmware_version; unsigned char utc_time[16]; }; #define CKF_RNG (1 << 0) #define CKF_WRITE_PROTECTED (1 << 1) #define CKF_LOGIN_REQUIRED (1 << 2) #define CKF_USER_PIN_INITIALIZED (1 << 3) #define CKF_RESTORE_KEY_NOT_NEEDED (1 << 5) #define CKF_CLOCK_ON_TOKEN (1 << 6) #define CKF_PROTECTED_AUTHENTICATION_PATH (1 << 8) #define CKF_DUAL_CRYPTO_OPERATIONS (1 << 9) #define CKF_TOKEN_INITIALIZED (1 << 10) #define CKF_SECONDARY_AUTHENTICATION (1 << 11) #define CKF_USER_PIN_COUNT_LOW (1 << 16) #define CKF_USER_PIN_FINAL_TRY (1 << 17) #define CKF_USER_PIN_LOCKED (1 << 18) #define CKF_USER_PIN_TO_BE_CHANGED (1 << 19) #define CKF_SO_PIN_COUNT_LOW (1 << 20) #define CKF_SO_PIN_FINAL_TRY (1 << 21) #define CKF_SO_PIN_LOCKED (1 << 22) #define CKF_SO_PIN_TO_BE_CHANGED (1 << 23) #define CKF_ERROR_STATE (1 << 24) #define CK_UNAVAILABLE_INFORMATION ((unsigned long) -1) #define CK_EFFECTIVELY_INFINITE (0) typedef unsigned long ck_session_handle_t; #define CK_INVALID_HANDLE (0) typedef unsigned long ck_user_type_t; #define CKU_SO (0) #define CKU_USER (1) #define CKU_CONTEXT_SPECIFIC (2) typedef unsigned long ck_state_t; #define CKS_RO_PUBLIC_SESSION (0) #define CKS_RO_USER_FUNCTIONS (1) #define CKS_RW_PUBLIC_SESSION (2) #define CKS_RW_USER_FUNCTIONS (3) #define CKS_RW_SO_FUNCTIONS (4) struct ck_session_info { ck_slot_id_t slot_id; ck_state_t state; ck_flags_t flags; unsigned long device_error; }; #define CKF_RW_SESSION (1 << 1) #define CKF_SERIAL_SESSION (1 << 2) typedef unsigned long ck_object_handle_t; typedef unsigned long ck_object_class_t; #define CKO_DATA (0) #define CKO_CERTIFICATE (1) #define CKO_PUBLIC_KEY (2) #define CKO_PRIVATE_KEY (3) #define CKO_SECRET_KEY (4) #define CKO_HW_FEATURE (5) #define CKO_DOMAIN_PARAMETERS (6) #define CKO_MECHANISM (7) #define CKO_OTP_KEY (8) #define CKO_VENDOR_DEFINED ((unsigned long) (1ul << 31)) typedef unsigned long ck_hw_feature_type_t; #define CKH_MONOTONIC_COUNTER (1) #define CKH_CLOCK (2) #define CKH_USER_INTERFACE (3) #define CKH_VENDOR_DEFINED ((unsigned long) (1ul << 31)) typedef unsigned long ck_key_type_t; #define CKK_RSA (0) #define CKK_DSA (1) #define CKK_DH (2) #define CKK_ECDSA (3) #define CKK_EC (3) #define CKK_X9_42_DH (4) #define CKK_KEA (5) #define CKK_GENERIC_SECRET (0x10) #define CKK_RC2 (0x11) #define CKK_RC4 (0x12) #define CKK_DES (0x13) #define CKK_DES2 (0x14) #define CKK_DES3 (0x15) #define CKK_CAST (0x16) #define CKK_CAST3 (0x17) #define CKK_CAST5 (0x18) #define CKK_CAST128 (0x18) #define CKK_RC5 (0x19) #define CKK_IDEA (0x1a) #define CKK_SKIPJACK (0x1b) #define CKK_BATON (0x1c) #define CKK_JUNIPER (0x1d) #define CKK_CDMF (0x1e) #define CKK_AES (0x1f) #define CKK_BLOWFISH (0x20) #define CKK_TWOFISH (0x21) #define CKK_SECURID (0x22) #define CKK_HOTP (0x23) #define CKK_ACTI (0x24) #define CKK_CAMELLIA (0x25) #define CKK_ARIA (0x26) #define CKK_MD5_HMAC (0x27) #define CKK_SHA_1_HMAC (0x28) #define CKK_RIPEMD128_HMAC (0x29) #define CKK_RIPEMD160_HMAC (0x2A) #define CKK_SHA256_HMAC (0x2B) #define CKK_SHA384_HMAC (0x2C) #define CKK_SHA512_HMAC (0x2D) #define CKK_SHA224_HMAC (0x2E) #define CKK_SEED (0x2F) #define CKK_GOSTR3410 (0x30) #define CKK_GOSTR3411 (0x31) #define CKK_GOST28147 (0x32) #define CKK_VENDOR_DEFINED ((unsigned long) (1ul << 31)) typedef unsigned long ck_certificate_type_t; #define CKC_X_509 (0) #define CKC_X_509_ATTR_CERT (1) #define CKC_WTLS (2) #define CKC_VENDOR_DEFINED ((unsigned long) (1ul << 31)) #define CKC_OPENPGP (CKC_VENDOR_DEFINED|0x00504750) #define CK_OTP_FORMAT_DECIMAL (0) #define CK_OTP_FORMAT_HEXADECIMAL (1) #define CK_OTP_FORMAT_ALPHANUMERIC (2) #define CK_OTP_FORMAT_BINARY (3) #define CK_OTP_PARAM_IGNORED (0) #define CK_OTP_PARAM_OPTIONAL (1) #define CK_OTP_PARAM_MANDATORY (2) typedef unsigned long ck_attribute_type_t; #define CKA_CLASS (0) #define CKA_TOKEN (1) #define CKA_PRIVATE (2) #define CKA_LABEL (3) #define CKA_APPLICATION (0x10) #define CKA_VALUE (0x11) #define CKA_OBJECT_ID (0x12) #define CKA_CERTIFICATE_TYPE (0x80) #define CKA_ISSUER (0x81) #define CKA_SERIAL_NUMBER (0x82) #define CKA_AC_ISSUER (0x83) #define CKA_OWNER (0x84) #define CKA_ATTR_TYPES (0x85) #define CKA_TRUSTED (0x86) #define CKA_CERTIFICATE_CATEGORY (0x87) #define CKA_JAVA_MIDP_SECURITY_DOMAIN (0x88) #define CKA_URL (0x89) #define CKA_HASH_OF_SUBJECT_PUBLIC_KEY (0x8a) #define CKA_HASH_OF_ISSUER_PUBLIC_KEY (0x8b) #define CKA_NAME_HASH_ALGORITHM (0x8c) #define CKA_CHECK_VALUE (0x90) #define CKA_KEY_TYPE (0x100) #define CKA_SUBJECT (0x101) #define CKA_ID (0x102) #define CKA_SENSITIVE (0x103) #define CKA_ENCRYPT (0x104) #define CKA_DECRYPT (0x105) #define CKA_WRAP (0x106) #define CKA_UNWRAP (0x107) #define CKA_SIGN (0x108) #define CKA_SIGN_RECOVER (0x109) #define CKA_VERIFY (0x10a) #define CKA_VERIFY_RECOVER (0x10b) #define CKA_DERIVE (0x10c) #define CKA_START_DATE (0x110) #define CKA_END_DATE (0x111) #define CKA_MODULUS (0x120) #define CKA_MODULUS_BITS (0x121) #define CKA_PUBLIC_EXPONENT (0x122) #define CKA_PRIVATE_EXPONENT (0x123) #define CKA_PRIME_1 (0x124) #define CKA_PRIME_2 (0x125) #define CKA_EXPONENT_1 (0x126) #define CKA_EXPONENT_2 (0x127) #define CKA_COEFFICIENT (0x128) #define CKA_PRIME (0x130) #define CKA_SUBPRIME (0x131) #define CKA_BASE (0x132) #define CKA_PRIME_BITS (0x133) #define CKA_SUB_PRIME_BITS (0x134) #define CKA_SUBPRIME_BITS (0x134) #define CKA_VALUE_BITS (0x160) #define CKA_VALUE_LEN (0x161) #define CKA_EXTRACTABLE (0x162) #define CKA_LOCAL (0x163) #define CKA_NEVER_EXTRACTABLE (0x164) #define CKA_ALWAYS_SENSITIVE (0x165) #define CKA_KEY_GEN_MECHANISM (0x166) #define CKA_MODIFIABLE (0x170) #define CKA_COPYABLE (0x171) #define CKA_ECDSA_PARAMS (0x180) #define CKA_EC_PARAMS (0x180) #define CKA_EC_POINT (0x181) #define CKA_SECONDARY_AUTH (0x200) #define CKA_AUTH_PIN_FLAGS (0x201) #define CKA_ALWAYS_AUTHENTICATE (0x202) #define CKA_WRAP_WITH_TRUSTED (0x210) #define CKA_OTP_FORMAT (0x220) #define CKA_OTP_LENGTH (0x221) #define CKA_OTP_TIME_INTERVAL (0x222) #define CKA_OTP_USER_FRIENDLY_MODE (0x223) #define CKA_OTP_CHALLENGE_REQUIREMENT (0x224) #define CKA_OTP_TIME_REQUIREMENT (0x225) #define CKA_OTP_COUNTER_REQUIREMENT (0x226) #define CKA_OTP_PIN_REQUIREMENT (0x227) #define CKA_OTP_COUNTER (0x22E) #define CKA_OTP_TIME (0x22F) #define CKA_OTP_USER_IDENTIFIER (0x22A) #define CKA_OTP_SERVICE_IDENTIFIER (0x22B) #define CKA_OTP_SERVICE_LOGO (0x22C) #define CKA_OTP_SERVICE_LOGO_TYPE (0x22D) #define CKA_GOSTR3410_PARAMS (0x250) #define CKA_GOSTR3411_PARAMS (0x251) #define CKA_GOST28147_PARAMS (0x252) #define CKA_HW_FEATURE_TYPE (0x300) #define CKA_RESET_ON_INIT (0x301) #define CKA_HAS_RESET (0x302) #define CKA_PIXEL_X (0x400) #define CKA_PIXEL_Y (0x401) #define CKA_RESOLUTION (0x402) #define CKA_CHAR_ROWS (0x403) #define CKA_CHAR_COLUMNS (0x404) #define CKA_COLOR (0x405) #define CKA_BITS_PER_PIXEL (0x406) #define CKA_CHAR_SETS (0x480) #define CKA_ENCODING_METHODS (0x481) #define CKA_MIME_TYPES (0x482) #define CKA_MECHANISM_TYPE (0x500) #define CKA_REQUIRED_CMS_ATTRIBUTES (0x501) #define CKA_DEFAULT_CMS_ATTRIBUTES (0x502) #define CKA_SUPPORTED_CMS_ATTRIBUTES (0x503) #define CKA_WRAP_TEMPLATE (CKF_ARRAY_ATTRIBUTE | 0x211) #define CKA_UNWRAP_TEMPLATE (CKF_ARRAY_ATTRIBUTE | 0x212) #define CKA_DERIVE_TEMPLATE (CKF_ARRAY_ATTRIBUTE | 0x213) #define CKA_ALLOWED_MECHANISMS (CKF_ARRAY_ATTRIBUTE | 0x600) #define CKA_VENDOR_DEFINED ((unsigned long) (1ul << 31)) struct ck_attribute { ck_attribute_type_t type; void *value; unsigned long value_len; }; struct ck_date { unsigned char year[4]; unsigned char month[2]; unsigned char day[2]; }; typedef unsigned long ck_mechanism_type_t; #define CKM_RSA_PKCS_KEY_PAIR_GEN (0) #define CKM_RSA_PKCS (1) #define CKM_RSA_9796 (2) #define CKM_RSA_X_509 (3) #define CKM_MD2_RSA_PKCS (4) #define CKM_MD5_RSA_PKCS (5) #define CKM_SHA1_RSA_PKCS (6) #define CKM_RIPEMD128_RSA_PKCS (7) #define CKM_RIPEMD160_RSA_PKCS (8) #define CKM_RSA_PKCS_OAEP (9) #define CKM_RSA_X9_31_KEY_PAIR_GEN (0xa) #define CKM_RSA_X9_31 (0xb) #define CKM_SHA1_RSA_X9_31 (0xc) #define CKM_RSA_PKCS_PSS (0xd) #define CKM_SHA1_RSA_PKCS_PSS (0xe) #define CKM_DSA_KEY_PAIR_GEN (0x10) #define CKM_DSA (0x11) #define CKM_DSA_SHA1 (0x12) #define CKM_DSA_SHA224 (0x13) #define CKM_DSA_SHA256 (0x14) #define CKM_DSA_SHA384 (0x15) #define CKM_DSA_SHA512 (0x16) #define CKM_DH_PKCS_KEY_PAIR_GEN (0x20) #define CKM_DH_PKCS_DERIVE (0x21) #define CKM_X9_42_DH_KEY_PAIR_GEN (0x30) #define CKM_X9_42_DH_DERIVE (0x31) #define CKM_X9_42_DH_HYBRID_DERIVE (0x32) #define CKM_X9_42_MQV_DERIVE (0x33) #define CKM_SHA256_RSA_PKCS (0x40) #define CKM_SHA384_RSA_PKCS (0x41) #define CKM_SHA512_RSA_PKCS (0x42) #define CKM_SHA256_RSA_PKCS_PSS (0x43) #define CKM_SHA384_RSA_PKCS_PSS (0x44) #define CKM_SHA512_RSA_PKCS_PSS (0x45) #define CKM_SHA224_RSA_PKCS (0x46) #define CKM_SHA224_RSA_PKCS_PSS (0x47) #define CKM_RC2_KEY_GEN (0x100) #define CKM_RC2_ECB (0x101) #define CKM_RC2_CBC (0x102) #define CKM_RC2_MAC (0x103) #define CKM_RC2_MAC_GENERAL (0x104) #define CKM_RC2_CBC_PAD (0x105) #define CKM_RC4_KEY_GEN (0x110) #define CKM_RC4 (0x111) #define CKM_DES_KEY_GEN (0x120) #define CKM_DES_ECB (0x121) #define CKM_DES_CBC (0x122) #define CKM_DES_MAC (0x123) #define CKM_DES_MAC_GENERAL (0x124) #define CKM_DES_CBC_PAD (0x125) #define CKM_DES2_KEY_GEN (0x130) #define CKM_DES3_KEY_GEN (0x131) #define CKM_DES3_ECB (0x132) #define CKM_DES3_CBC (0x133) #define CKM_DES3_MAC (0x134) #define CKM_DES3_MAC_GENERAL (0x135) #define CKM_DES3_CBC_PAD (0x136) #define CKM_DES3_CMAC_GENERAL (0x137) #define CKM_DES3_CMAC (0x138) #define CKM_CDMF_KEY_GEN (0x140) #define CKM_CDMF_ECB (0x141) #define CKM_CDMF_CBC (0x142) #define CKM_CDMF_MAC (0x143) #define CKM_CDMF_MAC_GENERAL (0x144) #define CKM_CDMF_CBC_PAD (0x145) #define CKM_DES_OFB64 (0x150) #define CKM_DES_OFB8 (0x151) #define CKM_DES_CFB64 (0x152) #define CKM_DES_CFB8 (0x153) #define CKM_MD2 (0x200) #define CKM_MD2_HMAC (0x201) #define CKM_MD2_HMAC_GENERAL (0x202) #define CKM_MD5 (0x210) #define CKM_MD5_HMAC (0x211) #define CKM_MD5_HMAC_GENERAL (0x212) #define CKM_SHA_1 (0x220) #define CKM_SHA_1_HMAC (0x221) #define CKM_SHA_1_HMAC_GENERAL (0x222) #define CKM_RIPEMD128 (0x230) #define CKM_RIPEMD128_HMAC (0x231) #define CKM_RIPEMD128_HMAC_GENERAL (0x232) #define CKM_RIPEMD160 (0x240) #define CKM_RIPEMD160_HMAC (0x241) #define CKM_RIPEMD160_HMAC_GENERAL (0x242) #define CKM_SHA256 (0x250) #define CKM_SHA256_HMAC (0x251) #define CKM_SHA256_HMAC_GENERAL (0x252) #define CKM_SHA224 (0x255) #define CKM_SHA224_HMAC (0x256) #define CKM_SHA224_HMAC_GENERAL (0x257) #define CKM_SHA384 (0x260) #define CKM_SHA384_HMAC (0x261) #define CKM_SHA384_HMAC_GENERAL (0x262) #define CKM_SHA512 (0x270) #define CKM_SHA512_HMAC (0x271) #define CKM_SHA512_HMAC_GENERAL (0x272) #define CKM_SECURID_KEY_GEN (0x280) #define CKM_SECURID (0x282) #define CKM_HOTP_KEY_GEN (0x290) #define CKM_HOTP (0x291) #define CKM_ACTI (0x2A0) #define CKM_ACTI_KEY_GEN (0x2A1) #define CKM_CAST_KEY_GEN (0x300) #define CKM_CAST_ECB (0x301) #define CKM_CAST_CBC (0x302) #define CKM_CAST_MAC (0x303) #define CKM_CAST_MAC_GENERAL (0x304) #define CKM_CAST_CBC_PAD (0x305) #define CKM_CAST3_KEY_GEN (0x310) #define CKM_CAST3_ECB (0x311) #define CKM_CAST3_CBC (0x312) #define CKM_CAST3_MAC (0x313) #define CKM_CAST3_MAC_GENERAL (0x314) #define CKM_CAST3_CBC_PAD (0x315) #define CKM_CAST5_KEY_GEN (0x320) #define CKM_CAST128_KEY_GEN (0x320) #define CKM_CAST5_ECB (0x321) #define CKM_CAST128_ECB (0x321) #define CKM_CAST5_CBC (0x322) #define CKM_CAST128_CBC (0x322) #define CKM_CAST5_MAC (0x323) #define CKM_CAST128_MAC (0x323) #define CKM_CAST5_MAC_GENERAL (0x324) #define CKM_CAST128_MAC_GENERAL (0x324) #define CKM_CAST5_CBC_PAD (0x325) #define CKM_CAST128_CBC_PAD (0x325) #define CKM_RC5_KEY_GEN (0x330) #define CKM_RC5_ECB (0x331) #define CKM_RC5_CBC (0x332) #define CKM_RC5_MAC (0x333) #define CKM_RC5_MAC_GENERAL (0x334) #define CKM_RC5_CBC_PAD (0x335) #define CKM_IDEA_KEY_GEN (0x340) #define CKM_IDEA_ECB (0x341) #define CKM_IDEA_CBC (0x342) #define CKM_IDEA_MAC (0x343) #define CKM_IDEA_MAC_GENERAL (0x344) #define CKM_IDEA_CBC_PAD (0x345) #define CKM_GENERIC_SECRET_KEY_GEN (0x350) #define CKM_CONCATENATE_BASE_AND_KEY (0x360) #define CKM_CONCATENATE_BASE_AND_DATA (0x362) #define CKM_CONCATENATE_DATA_AND_BASE (0x363) #define CKM_XOR_BASE_AND_DATA (0x364) #define CKM_EXTRACT_KEY_FROM_KEY (0x365) #define CKM_SSL3_PRE_MASTER_KEY_GEN (0x370) #define CKM_SSL3_MASTER_KEY_DERIVE (0x371) #define CKM_SSL3_KEY_AND_MAC_DERIVE (0x372) #define CKM_SSL3_MASTER_KEY_DERIVE_DH (0x373) #define CKM_TLS_PRE_MASTER_KEY_GEN (0x374) #define CKM_TLS_MASTER_KEY_DERIVE (0x375) #define CKM_TLS_KEY_AND_MAC_DERIVE (0x376) #define CKM_TLS_MASTER_KEY_DERIVE_DH (0x377) #define CKM_TLS_PRF (0x378) #define CKM_SSL3_MD5_MAC (0x380) #define CKM_SSL3_SHA1_MAC (0x381) #define CKM_MD5_KEY_DERIVATION (0x390) #define CKM_MD2_KEY_DERIVATION (0x391) #define CKM_SHA1_KEY_DERIVATION (0x392) #define CKM_SHA256_KEY_DERIVATION (0x393) #define CKM_SHA384_KEY_DERIVATION (0x394) #define CKM_SHA512_KEY_DERIVATION (0x395) #define CKM_SHA224_KEY_DERIVATION (0x396) #define CKM_PBE_MD2_DES_CBC (0x3a0) #define CKM_PBE_MD5_DES_CBC (0x3a1) #define CKM_PBE_MD5_CAST_CBC (0x3a2) #define CKM_PBE_MD5_CAST3_CBC (0x3a3) #define CKM_PBE_MD5_CAST5_CBC (0x3a4) #define CKM_PBE_MD5_CAST128_CBC (0x3a4) #define CKM_PBE_SHA1_CAST5_CBC (0x3a5) #define CKM_PBE_SHA1_CAST128_CBC (0x3a5) #define CKM_PBE_SHA1_RC4_128 (0x3a6) #define CKM_PBE_SHA1_RC4_40 (0x3a7) #define CKM_PBE_SHA1_DES3_EDE_CBC (0x3a8) #define CKM_PBE_SHA1_DES2_EDE_CBC (0x3a9) #define CKM_PBE_SHA1_RC2_128_CBC (0x3aa) #define CKM_PBE_SHA1_RC2_40_CBC (0x3ab) #define CKM_PKCS5_PBKD2 (0x3b0) #define CKM_PBA_SHA1_WITH_SHA1_HMAC (0x3c0) #define CKM_WTLS_PRE_MASTER_KEY_GEN (0x3d0) #define CKM_WTLS_MASTER_KEY_DERIVE (0x3d1) #define CKM_WTLS_MASTER_KEY_DERIVE_DH_ECC (0x3d2) #define CKM_WTLS_PRF (0x3d3) #define CKM_WTLS_SERVER_KEY_AND_MAC_DERIVE (0x3d4) #define CKM_WTLS_CLIENT_KEY_AND_MAC_DERIVE (0x3d5) #define CKM_KEY_WRAP_LYNKS (0x400) #define CKM_KEY_WRAP_SET_OAEP (0x401) #define CKM_CMS_SIG (0x500) #define CKM_KIP_DERIVE (0x510) #define CKM_KIP_WRAP (0x511) #define CKM_KIP_MAC (0x512) #define CKM_CAMELLIA_KEY_GEN (0x550) #define CKM_CAMELLIA_ECB (0x551) #define CKM_CAMELLIA_CBC (0x552) #define CKM_CAMELLIA_MAC (0x553) #define CKM_CAMELLIA_MAC_GENERAL (0x554) #define CKM_CAMELLIA_CBC_PAD (0x555) #define CKM_CAMELLIA_ECB_ENCRYPT_DATA (0x556) #define CKM_CAMELLIA_CBC_ENCRYPT_DATA (0x557) #define CKM_CAMELLIA_CTR (0x558) #define CKM_ARIA_KEY_GEN (0x560) #define CKM_ARIA_ECB (0x561) #define CKM_ARIA_CBC (0x562) #define CKM_ARIA_MAC (0x563) #define CKM_ARIA_MAC_GENERAL (0x564) #define CKM_ARIA_CBC_PAD (0x565) #define CKM_ARIA_ECB_ENCRYPT_DATA (0x566) #define CKM_ARIA_CBC_ENCRYPT_DATA (0x567) #define CKM_SEED_KEY_GEN (0x650) #define CKM_SEED_ECB (0x651) #define CKM_SEED_CBC (0x652) #define CKM_SEED_MAC (0x653) #define CKM_SEED_MAC_GENERAL (0x654) #define CKM_SEED_CBC_PAD (0x655) #define CKM_SEED_ECB_ENCRYPT_DATA (0x656) #define CKM_SEED_CBC_ENCRYPT_DATA (0x657) #define CKM_SKIPJACK_KEY_GEN (0x1000) #define CKM_SKIPJACK_ECB64 (0x1001) #define CKM_SKIPJACK_CBC64 (0x1002) #define CKM_SKIPJACK_OFB64 (0x1003) #define CKM_SKIPJACK_CFB64 (0x1004) #define CKM_SKIPJACK_CFB32 (0x1005) #define CKM_SKIPJACK_CFB16 (0x1006) #define CKM_SKIPJACK_CFB8 (0x1007) #define CKM_SKIPJACK_WRAP (0x1008) #define CKM_SKIPJACK_PRIVATE_WRAP (0x1009) #define CKM_SKIPJACK_RELAYX (0x100a) #define CKM_KEA_KEY_PAIR_GEN (0x1010) #define CKM_KEA_KEY_DERIVE (0x1011) #define CKM_FORTEZZA_TIMESTAMP (0x1020) #define CKM_BATON_KEY_GEN (0x1030) #define CKM_BATON_ECB128 (0x1031) #define CKM_BATON_ECB96 (0x1032) #define CKM_BATON_CBC128 (0x1033) #define CKM_BATON_COUNTER (0x1034) #define CKM_BATON_SHUFFLE (0x1035) #define CKM_BATON_WRAP (0x1036) #define CKM_ECDSA_KEY_PAIR_GEN (0x1040) #define CKM_EC_KEY_PAIR_GEN (0x1040) #define CKM_ECDSA (0x1041) #define CKM_ECDSA_SHA1 (0x1042) #define CKM_ECDSA_SHA224 (0x1043) #define CKM_ECDSA_SHA256 (0x1044) #define CKM_ECDSA_SHA384 (0x1045) #define CKM_ECDSA_SHA512 (0x1046) #define CKM_ECDH1_DERIVE (0x1050) #define CKM_ECDH1_COFACTOR_DERIVE (0x1051) #define CKM_ECMQV_DERIVE (0x1052) #define CKM_JUNIPER_KEY_GEN (0x1060) #define CKM_JUNIPER_ECB128 (0x1061) #define CKM_JUNIPER_CBC128 (0x1062) #define CKM_JUNIPER_COUNTER (0x1063) #define CKM_JUNIPER_SHUFFLE (0x1064) #define CKM_JUNIPER_WRAP (0x1065) #define CKM_FASTHASH (0x1070) #define CKM_AES_KEY_GEN (0x1080) #define CKM_AES_ECB (0x1081) #define CKM_AES_CBC (0x1082) #define CKM_AES_MAC (0x1083) #define CKM_AES_MAC_GENERAL (0x1084) #define CKM_AES_CBC_PAD (0x1085) #define CKM_AES_CTR (0x1086) #define CKM_AES_GCM (0x1087) #define CKM_AES_CCM (0x1088) #define CKM_AES_CTS (0x1089) #define CKM_AES_CMAC (0x108a) #define CKM_AES_CMAC_GENERAL (0x108b) #define CKM_BLOWFISH_KEY_GEN (0x1090) #define CKM_BLOWFISH_CBC (0x1091) #define CKM_TWOFISH_KEY_GEN (0x1092) #define CKM_TWOFISH_CBC (0x1093) #define CKM_BLOWFISH_CBC_PAD (0x1094) #define CKM_TWOFISH_CBC_PAD (0x1095) #define CKM_DES_ECB_ENCRYPT_DATA (0x1100) #define CKM_DES_CBC_ENCRYPT_DATA (0x1101) #define CKM_DES3_ECB_ENCRYPT_DATA (0x1102) #define CKM_DES3_CBC_ENCRYPT_DATA (0x1103) #define CKM_AES_ECB_ENCRYPT_DATA (0x1104) #define CKM_AES_CBC_ENCRYPT_DATA (0x1105) #define CKM_GOSTR3410_KEY_PAIR_GEN (0x1200) #define CKM_GOSTR3410 (0x1201) #define CKM_GOSTR3410_WITH_GOSTR3411 (0x1202) #define CKM_GOSTR3410_KEY_WRAP (0x1203) #define CKM_GOSTR3410_DERIVE (0x1204) #define CKM_GOSTR3411 (0x1210) #define CKM_GOSTR3411_HMAC (0x1211) #define CKM_GOST28147_KEY_GEN (0x1220) #define CKM_GOST28147_ECB (0x1221) #define CKM_GOST28147 (0x1222) #define CKM_GOST28147_MAC (0x1223) #define CKM_GOST28147_KEY_WRAP (0x1224) #define CKM_DSA_PARAMETER_GEN (0x2000) #define CKM_DH_PKCS_PARAMETER_GEN (0x2001) #define CKM_X9_42_DH_PARAMETER_GEN (0x2002) #define CKM_AES_OFB (0x2104) #define CKM_AES_CFB64 (0x2105) #define CKM_AES_CFB8 (0x2106) #define CKM_AES_CFB128 (0x2107) #define CKM_AES_KEY_WRAP (0x2109) #define CKM_AES_KEY_WRAP_PAD (0x210a) #define CKM_RSA_PKCS_TPM_1_1 (0x4001) #define CKM_RSA_PKCS_OAEPTPM_1_1 (0x4002) #define CKM_VENDOR_DEFINED ((unsigned long) (1ul << 31)) struct ck_mechanism { ck_mechanism_type_t mechanism; void *parameter; unsigned long parameter_len; }; struct ck_mechanism_info { unsigned long min_key_size; unsigned long max_key_size; ck_flags_t flags; }; #define CKF_HW (1 << 0) #define CKF_ENCRYPT (1 << 8) #define CKF_DECRYPT (1 << 9) #define CKF_DIGEST (1 << 10) #define CKF_SIGN (1 << 11) #define CKF_SIGN_RECOVER (1 << 12) #define CKF_VERIFY (1 << 13) #define CKF_VERIFY_RECOVER (1 << 14) #define CKF_GENERATE (1 << 15) #define CKF_GENERATE_KEY_PAIR (1 << 16) #define CKF_WRAP (1 << 17) #define CKF_UNWRAP (1 << 18) #define CKF_DERIVE (1 << 19) #define CKF_EC_F_P (1 << 20) #define CKF_EC_F_2M (1 << 21) #define CKF_EC_ECPARAMETERS (1 << 22) #define CKF_EC_NAMEDCURVE (1 << 23) #define CKF_EC_UNCOMPRESS (1 << 24) #define CKF_EC_COMPRESS (1 << 25) #define CKF_EXTENSION ((unsigned long) (1ul << 31)) /* The following MGFs are defined */ #define CKG_MGF1_SHA1 (0x00000001) #define CKG_MGF1_SHA256 (0x00000002) #define CKG_MGF1_SHA384 (0x00000003) #define CKG_MGF1_SHA512 (0x00000004) #define CKG_MGF1_SHA224 (0x00000005) #define CKZ_DATA_SPECIFIED (0x00000001) struct ck_rsa_pkcs_oaep_params { ck_mechanism_type_t hash_alg; unsigned long mgf; unsigned long source; void *source_data; unsigned long source_data_len; }; struct ck_rsa_pkcs_pss_params { ck_mechanism_type_t hash_alg; unsigned long mgf; unsigned long slen; }; typedef unsigned long ck_ec_kdf_type_t; /* The following EC Key Derivation Functions are defined */ #define CKD_NULL (0x00000001) #define CKD_SHA1_KDF (0x00000002) struct ck_ecdh1_derive_params { ck_ec_kdf_type_t kdf; unsigned long shared_data_len; unsigned char *shared_data; unsigned long public_data_len; unsigned char *public_data; }; struct ck_ecdh2_derive_params { ck_ec_kdf_type_t kdf; unsigned long shared_data_len; unsigned char *shared_data; unsigned long public_data_len; unsigned char *public_data; unsigned long private_data_len; ck_object_handle_t private_data; unsigned long public_data_len2; unsigned char *public_data2; }; struct ck_ecmqv_derive_params { ck_ec_kdf_type_t kdf; unsigned long shared_data_len; unsigned char *shared_data; unsigned long public_data_len; unsigned char *public_data; unsigned long private_data_len; ck_object_handle_t private_data; unsigned long public_data_len2; unsigned char *public_data2; ck_object_handle_t public_key; }; typedef unsigned long ck_x9_42_dh_kdf_type_t; /* The following X9.42 DH key derivation functions are defined */ #define CKD_SHA1_KDF_ASN1 (0x00000003) #define CKD_SHA1_KDF_CONCATENATE (0x00000004) #define CKD_SHA224_KDF (0x00000005) #define CKD_SHA256_KDF (0x00000006) #define CKD_SHA384_KDF (0x00000007) #define CKD_SHA512_KDF (0x00000008) #define CKD_CPDIVERSIFY_KDF (0x00000009) struct ck_x9_42_dh1_derive_params { ck_x9_42_dh_kdf_type_t kdf; unsigned long other_info_len; unsigned char *other_info; unsigned long public_data_len; unsigned char *public_data; }; struct ck_x9_42_dh2_derive_params { ck_x9_42_dh_kdf_type_t kdf; unsigned long other_info_len; unsigned char *other_info; unsigned long public_data_len; unsigned char *public_data; unsigned long private_data_len; ck_object_handle_t private_data; unsigned long public_data_len2; unsigned char *public_data2; }; struct ck_x9_42_mqv_derive_params { ck_x9_42_dh_kdf_type_t kdf; unsigned long other_info_len; unsigned char *other_info; unsigned long public_data_len; unsigned char *public_data; unsigned long private_data_len; ck_object_handle_t private_data; unsigned long public_data_len2; unsigned char *public_data2; ck_object_handle_t public_key; }; struct ck_des_cbc_encrypt_data_params { unsigned char iv[8]; unsigned char *data; unsigned long length; }; struct ck_aes_cbc_encrypt_data_params { unsigned char iv[16]; unsigned char *data; unsigned long length; }; struct ck_key_derivation_string_data { unsigned char *data; unsigned long len; }; /* Flags for C_WaitForSlotEvent. */ #define CKF_DONT_BLOCK (1) typedef unsigned long ck_rv_t; typedef ck_rv_t (*ck_notify_t) (ck_session_handle_t session, ck_notification_t event, void *application); /* Forward reference. */ struct ck_function_list; #define _CK_DECLARE_FUNCTION(name, args) \ typedef ck_rv_t (*CK_ ## name) args; \ ck_rv_t CK_SPEC name args _CK_DECLARE_FUNCTION (C_Initialize, (void *init_args)); _CK_DECLARE_FUNCTION (C_Finalize, (void *reserved)); _CK_DECLARE_FUNCTION (C_GetInfo, (struct ck_info *info)); _CK_DECLARE_FUNCTION (C_GetFunctionList, (struct ck_function_list **function_list)); _CK_DECLARE_FUNCTION (C_GetSlotList, (unsigned char token_present, ck_slot_id_t *slot_list, unsigned long *count)); _CK_DECLARE_FUNCTION (C_GetSlotInfo, (ck_slot_id_t slot_id, struct ck_slot_info *info)); _CK_DECLARE_FUNCTION (C_GetTokenInfo, (ck_slot_id_t slot_id, struct ck_token_info *info)); _CK_DECLARE_FUNCTION (C_WaitForSlotEvent, (ck_flags_t flags, ck_slot_id_t *slot, void *reserved)); _CK_DECLARE_FUNCTION (C_GetMechanismList, (ck_slot_id_t slot_id, ck_mechanism_type_t *mechanism_list, unsigned long *count)); _CK_DECLARE_FUNCTION (C_GetMechanismInfo, (ck_slot_id_t slot_id, ck_mechanism_type_t type, struct ck_mechanism_info *info)); _CK_DECLARE_FUNCTION (C_InitToken, (ck_slot_id_t slot_id, unsigned char *pin, unsigned long pin_len, unsigned char *label)); _CK_DECLARE_FUNCTION (C_InitPIN, (ck_session_handle_t session, unsigned char *pin, unsigned long pin_len)); _CK_DECLARE_FUNCTION (C_SetPIN, (ck_session_handle_t session, unsigned char *old_pin, unsigned long old_len, unsigned char *new_pin, unsigned long new_len)); _CK_DECLARE_FUNCTION (C_OpenSession, (ck_slot_id_t slot_id, ck_flags_t flags, void *application, ck_notify_t notify, ck_session_handle_t *session)); _CK_DECLARE_FUNCTION (C_CloseSession, (ck_session_handle_t session)); _CK_DECLARE_FUNCTION (C_CloseAllSessions, (ck_slot_id_t slot_id)); _CK_DECLARE_FUNCTION (C_GetSessionInfo, (ck_session_handle_t session, struct ck_session_info *info)); _CK_DECLARE_FUNCTION (C_GetOperationState, (ck_session_handle_t session, unsigned char *operation_state, unsigned long *operation_state_len)); _CK_DECLARE_FUNCTION (C_SetOperationState, (ck_session_handle_t session, unsigned char *operation_state, unsigned long operation_state_len, ck_object_handle_t encryption_key, ck_object_handle_t authentiation_key)); _CK_DECLARE_FUNCTION (C_Login, (ck_session_handle_t session, ck_user_type_t user_type, unsigned char *pin, unsigned long pin_len)); _CK_DECLARE_FUNCTION (C_Logout, (ck_session_handle_t session)); _CK_DECLARE_FUNCTION (C_CreateObject, (ck_session_handle_t session, struct ck_attribute *templ, unsigned long count, ck_object_handle_t *object)); _CK_DECLARE_FUNCTION (C_CopyObject, (ck_session_handle_t session, ck_object_handle_t object, struct ck_attribute *templ, unsigned long count, ck_object_handle_t *new_object)); _CK_DECLARE_FUNCTION (C_DestroyObject, (ck_session_handle_t session, ck_object_handle_t object)); _CK_DECLARE_FUNCTION (C_GetObjectSize, (ck_session_handle_t session, ck_object_handle_t object, unsigned long *size)); _CK_DECLARE_FUNCTION (C_GetAttributeValue, (ck_session_handle_t session, ck_object_handle_t object, struct ck_attribute *templ, unsigned long count)); _CK_DECLARE_FUNCTION (C_SetAttributeValue, (ck_session_handle_t session, ck_object_handle_t object, struct ck_attribute *templ, unsigned long count)); _CK_DECLARE_FUNCTION (C_FindObjectsInit, (ck_session_handle_t session, struct ck_attribute *templ, unsigned long count)); _CK_DECLARE_FUNCTION (C_FindObjects, (ck_session_handle_t session, ck_object_handle_t *object, unsigned long max_object_count, unsigned long *object_count)); _CK_DECLARE_FUNCTION (C_FindObjectsFinal, (ck_session_handle_t session)); _CK_DECLARE_FUNCTION (C_EncryptInit, (ck_session_handle_t session, struct ck_mechanism *mechanism, ck_object_handle_t key)); _CK_DECLARE_FUNCTION (C_Encrypt, (ck_session_handle_t session, unsigned char *data, unsigned long data_len, unsigned char *encrypted_data, unsigned long *encrypted_data_len)); _CK_DECLARE_FUNCTION (C_EncryptUpdate, (ck_session_handle_t session, unsigned char *part, unsigned long part_len, unsigned char *encrypted_part, unsigned long *encrypted_part_len)); _CK_DECLARE_FUNCTION (C_EncryptFinal, (ck_session_handle_t session, unsigned char *last_encrypted_part, unsigned long *last_encrypted_part_len)); _CK_DECLARE_FUNCTION (C_DecryptInit, (ck_session_handle_t session, struct ck_mechanism *mechanism, ck_object_handle_t key)); _CK_DECLARE_FUNCTION (C_Decrypt, (ck_session_handle_t session, unsigned char *encrypted_data, unsigned long encrypted_data_len, unsigned char *data, unsigned long *data_len)); _CK_DECLARE_FUNCTION (C_DecryptUpdate, (ck_session_handle_t session, unsigned char *encrypted_part, unsigned long encrypted_part_len, unsigned char *part, unsigned long *part_len)); _CK_DECLARE_FUNCTION (C_DecryptFinal, (ck_session_handle_t session, unsigned char *last_part, unsigned long *last_part_len)); _CK_DECLARE_FUNCTION (C_DigestInit, (ck_session_handle_t session, struct ck_mechanism *mechanism)); _CK_DECLARE_FUNCTION (C_Digest, (ck_session_handle_t session, unsigned char *data, unsigned long data_len, unsigned char *digest, unsigned long *digest_len)); _CK_DECLARE_FUNCTION (C_DigestUpdate, (ck_session_handle_t session, unsigned char *part, unsigned long part_len)); _CK_DECLARE_FUNCTION (C_DigestKey, (ck_session_handle_t session, ck_object_handle_t key)); _CK_DECLARE_FUNCTION (C_DigestFinal, (ck_session_handle_t session, unsigned char *digest, unsigned long *digest_len)); _CK_DECLARE_FUNCTION (C_SignInit, (ck_session_handle_t session, struct ck_mechanism *mechanism, ck_object_handle_t key)); _CK_DECLARE_FUNCTION (C_Sign, (ck_session_handle_t session, unsigned char *data, unsigned long data_len, unsigned char *signature, unsigned long *signature_len)); _CK_DECLARE_FUNCTION (C_SignUpdate, (ck_session_handle_t session, unsigned char *part, unsigned long part_len)); _CK_DECLARE_FUNCTION (C_SignFinal, (ck_session_handle_t session, unsigned char *signature, unsigned long *signature_len)); _CK_DECLARE_FUNCTION (C_SignRecoverInit, (ck_session_handle_t session, struct ck_mechanism *mechanism, ck_object_handle_t key)); _CK_DECLARE_FUNCTION (C_SignRecover, (ck_session_handle_t session, unsigned char *data, unsigned long data_len, unsigned char *signature, unsigned long *signature_len)); _CK_DECLARE_FUNCTION (C_VerifyInit, (ck_session_handle_t session, struct ck_mechanism *mechanism, ck_object_handle_t key)); _CK_DECLARE_FUNCTION (C_Verify, (ck_session_handle_t session, unsigned char *data, unsigned long data_len, unsigned char *signature, unsigned long signature_len)); _CK_DECLARE_FUNCTION (C_VerifyUpdate, (ck_session_handle_t session, unsigned char *part, unsigned long part_len)); _CK_DECLARE_FUNCTION (C_VerifyFinal, (ck_session_handle_t session, unsigned char *signature, unsigned long signature_len)); _CK_DECLARE_FUNCTION (C_VerifyRecoverInit, (ck_session_handle_t session, struct ck_mechanism *mechanism, ck_object_handle_t key)); _CK_DECLARE_FUNCTION (C_VerifyRecover, (ck_session_handle_t session, unsigned char *signature, unsigned long signature_len, unsigned char *data, unsigned long *data_len)); _CK_DECLARE_FUNCTION (C_DigestEncryptUpdate, (ck_session_handle_t session, unsigned char *part, unsigned long part_len, unsigned char *encrypted_part, unsigned long *encrypted_part_len)); _CK_DECLARE_FUNCTION (C_DecryptDigestUpdate, (ck_session_handle_t session, unsigned char *encrypted_part, unsigned long encrypted_part_len, unsigned char *part, unsigned long *part_len)); _CK_DECLARE_FUNCTION (C_SignEncryptUpdate, (ck_session_handle_t session, unsigned char *part, unsigned long part_len, unsigned char *encrypted_part, unsigned long *encrypted_part_len)); _CK_DECLARE_FUNCTION (C_DecryptVerifyUpdate, (ck_session_handle_t session, unsigned char *encrypted_part, unsigned long encrypted_part_len, unsigned char *part, unsigned long *part_len)); _CK_DECLARE_FUNCTION (C_GenerateKey, (ck_session_handle_t session, struct ck_mechanism *mechanism, struct ck_attribute *templ, unsigned long count, ck_object_handle_t *key)); _CK_DECLARE_FUNCTION (C_GenerateKeyPair, (ck_session_handle_t session, struct ck_mechanism *mechanism, struct ck_attribute *public_key_template, unsigned long public_key_attribute_count, struct ck_attribute *private_key_template, unsigned long private_key_attribute_count, ck_object_handle_t *public_key, ck_object_handle_t *private_key)); _CK_DECLARE_FUNCTION (C_WrapKey, (ck_session_handle_t session, struct ck_mechanism *mechanism, ck_object_handle_t wrapping_key, ck_object_handle_t key, unsigned char *wrapped_key, unsigned long *wrapped_key_len)); _CK_DECLARE_FUNCTION (C_UnwrapKey, (ck_session_handle_t session, struct ck_mechanism *mechanism, ck_object_handle_t unwrapping_key, unsigned char *wrapped_key, unsigned long wrapped_key_len, struct ck_attribute *templ, unsigned long attribute_count, ck_object_handle_t *key)); _CK_DECLARE_FUNCTION (C_DeriveKey, (ck_session_handle_t session, struct ck_mechanism *mechanism, ck_object_handle_t base_key, struct ck_attribute *templ, unsigned long attribute_count, ck_object_handle_t *key)); _CK_DECLARE_FUNCTION (C_SeedRandom, (ck_session_handle_t session, unsigned char *seed, unsigned long seed_len)); _CK_DECLARE_FUNCTION (C_GenerateRandom, (ck_session_handle_t session, unsigned char *random_data, unsigned long random_len)); _CK_DECLARE_FUNCTION (C_GetFunctionStatus, (ck_session_handle_t session)); _CK_DECLARE_FUNCTION (C_CancelFunction, (ck_session_handle_t session)); struct ck_function_list { struct ck_version version; CK_C_Initialize C_Initialize; CK_C_Finalize C_Finalize; CK_C_GetInfo C_GetInfo; CK_C_GetFunctionList C_GetFunctionList; CK_C_GetSlotList C_GetSlotList; CK_C_GetSlotInfo C_GetSlotInfo; CK_C_GetTokenInfo C_GetTokenInfo; CK_C_GetMechanismList C_GetMechanismList; CK_C_GetMechanismInfo C_GetMechanismInfo; CK_C_InitToken C_InitToken; CK_C_InitPIN C_InitPIN; CK_C_SetPIN C_SetPIN; CK_C_OpenSession C_OpenSession; CK_C_CloseSession C_CloseSession; CK_C_CloseAllSessions C_CloseAllSessions; CK_C_GetSessionInfo C_GetSessionInfo; CK_C_GetOperationState C_GetOperationState; CK_C_SetOperationState C_SetOperationState; CK_C_Login C_Login; CK_C_Logout C_Logout; CK_C_CreateObject C_CreateObject; CK_C_CopyObject C_CopyObject; CK_C_DestroyObject C_DestroyObject; CK_C_GetObjectSize C_GetObjectSize; CK_C_GetAttributeValue C_GetAttributeValue; CK_C_SetAttributeValue C_SetAttributeValue; CK_C_FindObjectsInit C_FindObjectsInit; CK_C_FindObjects C_FindObjects; CK_C_FindObjectsFinal C_FindObjectsFinal; CK_C_EncryptInit C_EncryptInit; CK_C_Encrypt C_Encrypt; CK_C_EncryptUpdate C_EncryptUpdate; CK_C_EncryptFinal C_EncryptFinal; CK_C_DecryptInit C_DecryptInit; CK_C_Decrypt C_Decrypt; CK_C_DecryptUpdate C_DecryptUpdate; CK_C_DecryptFinal C_DecryptFinal; CK_C_DigestInit C_DigestInit; CK_C_Digest C_Digest; CK_C_DigestUpdate C_DigestUpdate; CK_C_DigestKey C_DigestKey; CK_C_DigestFinal C_DigestFinal; CK_C_SignInit C_SignInit; CK_C_Sign C_Sign; CK_C_SignUpdate C_SignUpdate; CK_C_SignFinal C_SignFinal; CK_C_SignRecoverInit C_SignRecoverInit; CK_C_SignRecover C_SignRecover; CK_C_VerifyInit C_VerifyInit; CK_C_Verify C_Verify; CK_C_VerifyUpdate C_VerifyUpdate; CK_C_VerifyFinal C_VerifyFinal; CK_C_VerifyRecoverInit C_VerifyRecoverInit; CK_C_VerifyRecover C_VerifyRecover; CK_C_DigestEncryptUpdate C_DigestEncryptUpdate; CK_C_DecryptDigestUpdate C_DecryptDigestUpdate; CK_C_SignEncryptUpdate C_SignEncryptUpdate; CK_C_DecryptVerifyUpdate C_DecryptVerifyUpdate; CK_C_GenerateKey C_GenerateKey; CK_C_GenerateKeyPair C_GenerateKeyPair; CK_C_WrapKey C_WrapKey; CK_C_UnwrapKey C_UnwrapKey; CK_C_DeriveKey C_DeriveKey; CK_C_SeedRandom C_SeedRandom; CK_C_GenerateRandom C_GenerateRandom; CK_C_GetFunctionStatus C_GetFunctionStatus; CK_C_CancelFunction C_CancelFunction; CK_C_WaitForSlotEvent C_WaitForSlotEvent; }; typedef ck_rv_t (*ck_createmutex_t) (void **mutex); typedef ck_rv_t (*ck_destroymutex_t) (void *mutex); typedef ck_rv_t (*ck_lockmutex_t) (void *mutex); typedef ck_rv_t (*ck_unlockmutex_t) (void *mutex); struct ck_c_initialize_args { ck_createmutex_t create_mutex; ck_destroymutex_t destroy_mutex; ck_lockmutex_t lock_mutex; ck_unlockmutex_t unlock_mutex; ck_flags_t flags; void *reserved; }; #define CKF_LIBRARY_CANT_CREATE_OS_THREADS (1 << 0) #define CKF_OS_LOCKING_OK (1 << 1) #define CKR_OK (0) #define CKR_CANCEL (1) #define CKR_HOST_MEMORY (2) #define CKR_SLOT_ID_INVALID (3) #define CKR_GENERAL_ERROR (5) #define CKR_FUNCTION_FAILED (6) #define CKR_ARGUMENTS_BAD (7) #define CKR_NO_EVENT (8) #define CKR_NEED_TO_CREATE_THREADS (9) #define CKR_CANT_LOCK (0xa) #define CKR_ATTRIBUTE_READ_ONLY (0x10) #define CKR_ATTRIBUTE_SENSITIVE (0x11) #define CKR_ATTRIBUTE_TYPE_INVALID (0x12) #define CKR_ATTRIBUTE_VALUE_INVALID (0x13) #define CKR_COPY_PROHIBITED (0x1A) #define CKR_DATA_INVALID (0x20) #define CKR_DATA_LEN_RANGE (0x21) #define CKR_DEVICE_ERROR (0x30) #define CKR_DEVICE_MEMORY (0x31) #define CKR_DEVICE_REMOVED (0x32) #define CKR_ENCRYPTED_DATA_INVALID (0x40) #define CKR_ENCRYPTED_DATA_LEN_RANGE (0x41) #define CKR_FUNCTION_CANCELED (0x50) #define CKR_FUNCTION_NOT_PARALLEL (0x51) #define CKR_FUNCTION_NOT_SUPPORTED (0x54) #define CKR_KEY_HANDLE_INVALID (0x60) #define CKR_KEY_SIZE_RANGE (0x62) #define CKR_KEY_TYPE_INCONSISTENT (0x63) #define CKR_KEY_NOT_NEEDED (0x64) #define CKR_KEY_CHANGED (0x65) #define CKR_KEY_NEEDED (0x66) #define CKR_KEY_INDIGESTIBLE (0x67) #define CKR_KEY_FUNCTION_NOT_PERMITTED (0x68) #define CKR_KEY_NOT_WRAPPABLE (0x69) #define CKR_KEY_UNEXTRACTABLE (0x6a) #define CKR_MECHANISM_INVALID (0x70) #define CKR_MECHANISM_PARAM_INVALID (0x71) #define CKR_OBJECT_HANDLE_INVALID (0x82) #define CKR_OPERATION_ACTIVE (0x90) #define CKR_OPERATION_NOT_INITIALIZED (0x91) #define CKR_PIN_INCORRECT (0xa0) #define CKR_PIN_INVALID (0xa1) #define CKR_PIN_LEN_RANGE (0xa2) #define CKR_PIN_EXPIRED (0xa3) #define CKR_PIN_LOCKED (0xa4) #define CKR_SESSION_CLOSED (0xb0) #define CKR_SESSION_COUNT (0xb1) #define CKR_SESSION_HANDLE_INVALID (0xb3) #define CKR_SESSION_PARALLEL_NOT_SUPPORTED (0xb4) #define CKR_SESSION_READ_ONLY (0xb5) #define CKR_SESSION_EXISTS (0xb6) #define CKR_SESSION_READ_ONLY_EXISTS (0xb7) #define CKR_SESSION_READ_WRITE_SO_EXISTS (0xb8) #define CKR_SIGNATURE_INVALID (0xc0) #define CKR_SIGNATURE_LEN_RANGE (0xc1) #define CKR_TEMPLATE_INCOMPLETE (0xd0) #define CKR_TEMPLATE_INCONSISTENT (0xd1) #define CKR_TOKEN_NOT_PRESENT (0xe0) #define CKR_TOKEN_NOT_RECOGNIZED (0xe1) #define CKR_TOKEN_WRITE_PROTECTED (0xe2) #define CKR_UNWRAPPING_KEY_HANDLE_INVALID (0xf0) #define CKR_UNWRAPPING_KEY_SIZE_RANGE (0xf1) #define CKR_UNWRAPPING_KEY_TYPE_INCONSISTENT (0xf2) #define CKR_USER_ALREADY_LOGGED_IN (0x100) #define CKR_USER_NOT_LOGGED_IN (0x101) #define CKR_USER_PIN_NOT_INITIALIZED (0x102) #define CKR_USER_TYPE_INVALID (0x103) #define CKR_USER_ANOTHER_ALREADY_LOGGED_IN (0x104) #define CKR_USER_TOO_MANY_TYPES (0x105) #define CKR_WRAPPED_KEY_INVALID (0x110) #define CKR_WRAPPED_KEY_LEN_RANGE (0x112) #define CKR_WRAPPING_KEY_HANDLE_INVALID (0x113) #define CKR_WRAPPING_KEY_SIZE_RANGE (0x114) #define CKR_WRAPPING_KEY_TYPE_INCONSISTENT (0x115) #define CKR_RANDOM_SEED_NOT_SUPPORTED (0x120) #define CKR_RANDOM_NO_RNG (0x121) #define CKR_DOMAIN_PARAMS_INVALID (0x130) #define CKR_BUFFER_TOO_SMALL (0x150) #define CKR_SAVED_STATE_INVALID (0x160) #define CKR_INFORMATION_SENSITIVE (0x170) #define CKR_STATE_UNSAVEABLE (0x180) #define CKR_CRYPTOKI_NOT_INITIALIZED (0x190) #define CKR_CRYPTOKI_ALREADY_INITIALIZED (0x191) #define CKR_MUTEX_BAD (0x1a0) #define CKR_MUTEX_NOT_LOCKED (0x1a1) #define CKR_NEW_PIN_MODE (0x1b0) #define CKR_NEXT_OTP (0x1b1) #define CKR_EXCEEDED_MAX_ITERATIONS (0x1b5) #define CKR_FIPS_SELF_TEST_FAILED (0x1b6) #define CKR_LIBRARY_LOAD_FAILED (0x1b7) #define CKR_PIN_TOO_WEAK (0x1b8) #define CKR_PUBLIC_KEY_INVALID (0x1b9) #define CKR_FUNCTION_REJECTED (0x200) #define CKR_VENDOR_DEFINED ((unsigned long) (1ul << 31)) /* Compatibility layer. */ #ifdef CRYPTOKI_COMPAT #undef CK_DEFINE_FUNCTION #define CK_DEFINE_FUNCTION(retval, name) retval CK_SPEC name /* For NULL. */ #include typedef unsigned char CK_BYTE; typedef unsigned char CK_CHAR; typedef unsigned char CK_UTF8CHAR; typedef unsigned char CK_BBOOL; typedef unsigned long int CK_ULONG; typedef long int CK_LONG; typedef CK_BYTE *CK_BYTE_PTR; typedef CK_CHAR *CK_CHAR_PTR; typedef CK_UTF8CHAR *CK_UTF8CHAR_PTR; typedef CK_ULONG *CK_ULONG_PTR; typedef void *CK_VOID_PTR; typedef void **CK_VOID_PTR_PTR; #define CK_FALSE 0 #define CK_TRUE 1 #ifndef CK_DISABLE_TRUE_FALSE #ifndef FALSE #define FALSE 0 #endif #ifndef TRUE #define TRUE 1 #endif #endif typedef struct ck_version CK_VERSION; typedef struct ck_version *CK_VERSION_PTR; typedef struct ck_info CK_INFO; typedef struct ck_info *CK_INFO_PTR; typedef ck_slot_id_t *CK_SLOT_ID_PTR; typedef struct ck_slot_info CK_SLOT_INFO; typedef struct ck_slot_info *CK_SLOT_INFO_PTR; typedef struct ck_token_info CK_TOKEN_INFO; typedef struct ck_token_info *CK_TOKEN_INFO_PTR; typedef ck_session_handle_t *CK_SESSION_HANDLE_PTR; typedef struct ck_session_info CK_SESSION_INFO; typedef struct ck_session_info *CK_SESSION_INFO_PTR; typedef ck_object_handle_t *CK_OBJECT_HANDLE_PTR; typedef ck_object_class_t *CK_OBJECT_CLASS_PTR; typedef struct ck_attribute CK_ATTRIBUTE; typedef struct ck_attribute *CK_ATTRIBUTE_PTR; typedef struct ck_date CK_DATE; typedef struct ck_date *CK_DATE_PTR; typedef ck_mechanism_type_t *CK_MECHANISM_TYPE_PTR; typedef struct ck_mechanism CK_MECHANISM; typedef struct ck_mechanism *CK_MECHANISM_PTR; typedef struct ck_mechanism_info CK_MECHANISM_INFO; typedef struct ck_mechanism_info *CK_MECHANISM_INFO_PTR; typedef struct ck_rsa_pkcs_oaep_params CK_RSA_PKCS_OAEP_PARAMS; typedef struct ck_rsa_pkcs_oaep_params *CK_RSA_PKCS_OAEP_PARAMS_PTR; typedef struct ck_rsa_pkcs_pss_params CK_RSA_PKCS_PSS_PARAMS; typedef struct ck_rsa_pkcs_pss_params *CK_RSA_PKCS_PSS_PARAMS_PTR; typedef struct ck_ecdh1_derive_params CK_ECDH1_DERIVE_PARAMS; typedef struct ck_ecdh1_derive_params *CK_ECDH1_DERIVE_PARAMS_PTR; typedef struct ck_des_cbc_encrypt_data_params CK_DES_CBC_ENCRYPT_DATA_PARAMS; typedef struct ck_des_cbc_encrypt_data_params *CK_DES_CBC_ENCRYPT_DATA_PARAMS_PTR; typedef struct ck_aes_cbc_encrypt_data_params CK_AES_CBC_ENCRYPT_DATA_PARAMS; typedef struct ck_aes_cbc_encrypt_data_params *CK_AES_CBC_ENCRYPT_DATA_PARAMS_PTR; typedef struct ck_key_derivation_string_data CK_KEY_DERIVATION_STRING_DATA; typedef struct ck_key_derivation_string_data *CK_KEY_DERIVATION_STRING_DATA_PTR; typedef struct ck_function_list CK_FUNCTION_LIST; typedef struct ck_function_list *CK_FUNCTION_LIST_PTR; typedef struct ck_function_list **CK_FUNCTION_LIST_PTR_PTR; typedef struct ck_c_initialize_args CK_C_INITIALIZE_ARGS; typedef struct ck_c_initialize_args *CK_C_INITIALIZE_ARGS_PTR; #define NULL_PTR NULL /* Delete the helper macros defined at the top of the file. */ #undef ck_flags_t #undef ck_version #undef ck_info #undef cryptoki_version #undef manufacturer_id #undef library_description #undef library_version #undef ck_notification_t #undef ck_slot_id_t #undef ck_slot_info #undef slot_description #undef hardware_version #undef firmware_version #undef ck_token_info #undef serial_number #undef max_session_count #undef session_count #undef max_rw_session_count #undef rw_session_count #undef max_pin_len #undef min_pin_len #undef total_public_memory #undef free_public_memory #undef total_private_memory #undef free_private_memory #undef utc_time #undef ck_session_handle_t #undef ck_user_type_t #undef ck_state_t #undef ck_session_info #undef slot_id #undef device_error #undef ck_object_handle_t #undef ck_object_class_t #undef ck_hw_feature_type_t #undef ck_key_type_t #undef ck_certificate_type_t #undef ck_attribute_type_t #undef ck_attribute #undef value #undef value_len #undef ck_date #undef ck_mechanism_type_t #undef ck_mechanism #undef parameter #undef parameter_len #undef ck_mechanism_info #undef min_key_size #undef max_key_size #undef ck_rsa_pkcs_oaep_params #undef hash_alg #undef source_data #undef source_data_len #undef slen #undef ck_ec_kdf_type_t #undef shared_data_len #undef shared_data #undef public_data_len #undef public_data #undef private_data_len #undef private_data #undef public_data_len2 #undef public_data2 #undef public_key #undef ck_x9_42_dh_kdf_type_t #undef other_info_len #undef other_info #undef data #undef len #undef ck_rv_t #undef ck_notify_t #undef ck_function_list #undef ck_createmutex_t #undef ck_destroymutex_t #undef ck_lockmutex_t #undef ck_unlockmutex_t #undef ck_c_initialize_args #undef create_mutex #undef destroy_mutex #undef lock_mutex #undef unlock_mutex #undef reserved #endif /* CRYPTOKI_COMPAT */ /* System dependencies. */ #if defined(_WIN32) || defined(CRYPTOKI_FORCE_WIN32) #pragma pack(pop, cryptoki) #endif #if defined(__cplusplus) } #endif #endif /* PKCS11_H */ heimdal-7.5.0/lib/hx509/libhx509-exports.def0000644000175000017500000001304613026237312016426 0ustar niknik EXPORTS _hx509_cert_assign_key _hx509_cert_private_key _hx509_certs_keys_free _hx509_certs_keys_get _hx509_expr_eval _hx509_expr_free _hx509_expr_parse _hx509_generate_private_key _hx509_generate_private_key_bits _hx509_generate_private_key_free _hx509_generate_private_key_init _hx509_generate_private_key_is_ca _hx509_map_file_os _hx509_name_from_Name hx509_private_key2SPKI hx509_private_key_free _hx509_private_key_ref _hx509_request_add_dns_name _hx509_request_add_email hx509_request_free hx509_request_get_SubjectPublicKeyInfo hx509_request_get_name hx509_request_init _hx509_request_parse _hx509_request_print hx509_request_set_SubjectPublicKeyInfo ; _hx509_request_set_email hx509_request_set_name _hx509_request_to_pkcs10 _hx509_request_to_pkcs10 _hx509_unmap_file_os _hx509_write_file hx509_bitstring_print hx509_ca_sign hx509_ca_sign_self hx509_ca_tbs_add_crl_dp_uri hx509_ca_tbs_add_eku hx509_ca_tbs_add_san_hostname hx509_ca_tbs_add_san_jid hx509_ca_tbs_add_san_ms_upn hx509_ca_tbs_add_san_otherName hx509_ca_tbs_add_san_pkinit hx509_ca_tbs_add_san_rfc822name hx509_ca_tbs_free hx509_ca_tbs_init hx509_ca_tbs_set_ca hx509_ca_tbs_set_domaincontroller hx509_ca_tbs_set_notAfter hx509_ca_tbs_set_notAfter_lifetime hx509_ca_tbs_set_notBefore hx509_ca_tbs_set_proxy hx509_ca_tbs_set_serialnumber hx509_ca_tbs_set_signature_algorithm hx509_ca_tbs_set_spki hx509_ca_tbs_set_subject hx509_ca_tbs_set_template hx509_ca_tbs_subject_expand hx509_ca_tbs_template_units ; hx509_cert ; hx509_cert_attribute hx509_cert_binary hx509_cert_check_eku hx509_cert_cmp hx509_cert_find_subjectAltName_otherName hx509_cert_free hx509_cert_get_SPKI hx509_cert_get_SPKI_AlgorithmIdentifier hx509_cert_get_attribute hx509_cert_get_base_subject hx509_cert_get_friendly_name hx509_cert_get_issuer hx509_cert_get_notAfter hx509_cert_get_notBefore hx509_cert_get_serialnumber hx509_cert_get_subject hx509_cert_init hx509_cert_init_data hx509_cert_keyusage_print hx509_cert_ref hx509_cert_set_friendly_name hx509_certs_add hx509_certs_append hx509_certs_end_seq hx509_certs_ref hx509_certs_filter hx509_certs_find hx509_certs_free hx509_certs_info hx509_certs_init ; hx509_certs_iter hx509_certs_iter_f hx509_certs_merge hx509_certs_next_cert hx509_certs_start_seq hx509_certs_store hx509_ci_print_names hx509_clear_error_string hx509_cms_create_signed hx509_cms_create_signed_1 hx509_cms_decrypt_encrypted hx509_cms_envelope_1 hx509_cms_unenvelope hx509_cms_unwrap_ContentInfo hx509_cms_verify_signed hx509_cms_wrap_ContentInfo hx509_context_free hx509_context_init hx509_context_set_missing_revoke hx509_crl_add_revoked_certs hx509_crl_alloc hx509_crl_free hx509_crl_lifetime hx509_crl_sign hx509_crypto_aes128_cbc hx509_crypto_aes256_cbc hx509_crypto_allow_weak hx509_crypto_available hx509_crypto_decrypt hx509_crypto_des_rsdi_ede3_cbc hx509_crypto_destroy hx509_crypto_encrypt hx509_crypto_enctype_by_name hx509_crypto_free_algs hx509_crypto_get_params hx509_crypto_init hx509_crypto_provider hx509_crypto_select hx509_crypto_set_key_data hx509_crypto_set_key_name hx509_crypto_set_padding hx509_crypto_set_params hx509_crypto_set_random_key hx509_env_add hx509_env_add_binding hx509_env_find hx509_env_find_binding hx509_env_free ; hx509_env_init hx509_env_lfind hx509_err hx509_free_error_string hx509_free_octet_string_list hx509_general_name_unparse hx509_get_error_string hx509_get_one_cert hx509_lock_add_cert hx509_lock_add_certs hx509_lock_add_password hx509_lock_command_string hx509_lock_free hx509_lock_init hx509_lock_prompt hx509_lock_reset_certs hx509_lock_reset_passwords hx509_lock_reset_promper hx509_lock_set_prompter hx509_name_binary hx509_name_cmp hx509_name_copy hx509_name_expand hx509_name_free hx509_name_is_null_p hx509_name_normalize hx509_name_to_Name hx509_name_to_string hx509_ocsp_request hx509_ocsp_verify hx509_oid_print hx509_oid_sprint hx509_parse_name hx509_peer_info_add_cms_alg hx509_peer_info_alloc hx509_peer_info_free hx509_peer_info_set_cert hx509_peer_info_set_cms_algs hx509_pem_add_header hx509_pem_find_header hx509_pem_free_header hx509_pem_read hx509_pem_write hx509_print_stdout hx509_print_cert hx509_prompt_hidden hx509_query_alloc hx509_query_free hx509_query_match_cmp_func hx509_query_match_eku hx509_query_match_expr hx509_query_match_friendly_name hx509_query_match_issuer_serial hx509_query_match_option hx509_query_statistic_file hx509_query_unparse_stats hx509_revoke_add_crl hx509_revoke_add_ocsp hx509_revoke_free hx509_revoke_init hx509_revoke_ocsp_print hx509_revoke_print hx509_revoke_verify hx509_set_error_string hx509_set_error_stringv hx509_signature_md5 hx509_signature_rsa hx509_signature_rsa_with_md5 hx509_signature_rsa_with_sha1 hx509_signature_rsa_with_sha256 hx509_signature_rsa_with_sha384 hx509_signature_rsa_with_sha512 hx509_signature_sha1 hx509_signature_sha256 hx509_signature_sha384 hx509_signature_sha512 hx509_unparse_der_name hx509_validate_cert hx509_validate_ctx_add_flags hx509_validate_ctx_free hx509_validate_ctx_init hx509_validate_ctx_set_print hx509_verify_attach_anchors hx509_verify_attach_revoke hx509_verify_ctx_f_allow_default_trustanchors hx509_verify_destroy_ctx hx509_verify_hostname hx509_verify_init_ctx hx509_verify_path hx509_verify_set_max_depth hx509_verify_set_proxy_certificate hx509_verify_set_strict_rfc3280_verification hx509_verify_set_time hx509_verify_signature hx509_xfree initialize_hx_error_table_r ; pkcs11 symbols C_GetFunctionList heimdal-7.5.0/lib/hx509/pkcs10.asn10000644000175000017500000000101112136107750014555 0ustar niknik-- $Id$ PKCS10 DEFINITIONS ::= BEGIN IMPORTS Name, SubjectPublicKeyInfo, Attribute, AlgorithmIdentifier FROM rfc2459; CertificationRequestInfo ::= SEQUENCE { version INTEGER { pkcs10-v1(0) }, subject Name, subjectPKInfo SubjectPublicKeyInfo, attributes [0] IMPLICIT SET OF Attribute OPTIONAL } CertificationRequest ::= SEQUENCE { certificationRequestInfo CertificationRequestInfo, signatureAlgorithm AlgorithmIdentifier, signature BIT STRING } END heimdal-7.5.0/lib/hx509/hx509.h0000644000175000017500000001363613026237312013733 0ustar niknik/* * Copyright (c) 2004 - 2007 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ /* $Id$ */ #ifndef HEIMDAL_HX509_H #define HEIMDAL_HX509_H 1 #include #include #include #include typedef struct hx509_cert_attribute_data *hx509_cert_attribute; typedef struct hx509_cert_data *hx509_cert; typedef struct hx509_certs_data *hx509_certs; typedef struct hx509_context_data *hx509_context; typedef struct hx509_crypto_data *hx509_crypto; typedef struct hx509_lock_data *hx509_lock; typedef struct hx509_name_data *hx509_name; typedef struct hx509_private_key *hx509_private_key; typedef struct hx509_private_key_ops hx509_private_key_ops; typedef struct hx509_validate_ctx_data *hx509_validate_ctx; typedef struct hx509_verify_ctx_data *hx509_verify_ctx; typedef struct hx509_revoke_ctx_data *hx509_revoke_ctx; typedef struct hx509_query_data hx509_query; typedef void * hx509_cursor; typedef struct hx509_request_data *hx509_request; typedef struct hx509_error_data *hx509_error; typedef struct hx509_peer_info *hx509_peer_info; typedef struct hx509_ca_tbs *hx509_ca_tbs; typedef struct hx509_env_data *hx509_env; typedef struct hx509_crl *hx509_crl; typedef void (*hx509_vprint_func)(void *, const char *, va_list); enum { HX509_VHN_F_ALLOW_NO_MATCH = 1 }; enum { HX509_VALIDATE_F_VALIDATE = 1, HX509_VALIDATE_F_VERBOSE = 2 }; enum { HX509_CRYPTO_PADDING_PKCS7 = 0, HX509_CRYPTO_PADDING_NONE = 1 }; enum { HX509_KEY_FORMAT_GUESS = 0, HX509_KEY_FORMAT_DER = 1, HX509_KEY_FORMAT_WIN_BACKUPKEY = 2 }; typedef uint32_t hx509_key_format_t; struct hx509_cert_attribute_data { heim_oid oid; heim_octet_string data; }; typedef enum { HX509_PROMPT_TYPE_PASSWORD = 0x1, /* password, hidden */ HX509_PROMPT_TYPE_QUESTION = 0x2, /* question, not hidden */ HX509_PROMPT_TYPE_INFO = 0x4 /* infomation, reply doesn't matter */ } hx509_prompt_type; typedef struct hx509_prompt { const char *prompt; hx509_prompt_type type; heim_octet_string reply; } hx509_prompt; typedef int (*hx509_prompter_fct)(void *, const hx509_prompt *); typedef struct hx509_octet_string_list { size_t len; heim_octet_string *val; } hx509_octet_string_list; typedef struct hx509_pem_header { struct hx509_pem_header *next; char *header; char *value; } hx509_pem_header; typedef int (*hx509_pem_read_func)(hx509_context, const char *, const hx509_pem_header *, const void *, size_t, void *ctx); /* * Options passed to hx509_query_match_option. */ typedef enum { HX509_QUERY_OPTION_PRIVATE_KEY = 1, HX509_QUERY_OPTION_KU_ENCIPHERMENT = 2, HX509_QUERY_OPTION_KU_DIGITALSIGNATURE = 3, HX509_QUERY_OPTION_KU_KEYCERTSIGN = 4, HX509_QUERY_OPTION_END = 0xffff } hx509_query_option; /* flags to hx509_certs_init */ #define HX509_CERTS_CREATE 0x01 #define HX509_CERTS_UNPROTECT_ALL 0x02 /* flags to hx509_set_error_string */ #define HX509_ERROR_APPEND 0x01 /* flags to hx509_cms_unenvelope */ #define HX509_CMS_UE_DONT_REQUIRE_KU_ENCIPHERMENT 0x01 #define HX509_CMS_UE_ALLOW_WEAK 0x02 /* flags to hx509_cms_envelope_1 */ #define HX509_CMS_EV_NO_KU_CHECK 0x01 #define HX509_CMS_EV_ALLOW_WEAK 0x02 #define HX509_CMS_EV_ID_NAME 0x04 /* flags to hx509_cms_verify_signed */ #define HX509_CMS_VS_ALLOW_DATA_OID_MISMATCH 0x01 #define HX509_CMS_VS_NO_KU_CHECK 0x02 #define HX509_CMS_VS_ALLOW_ZERO_SIGNER 0x04 #define HX509_CMS_VS_NO_VALIDATE 0x08 /* selectors passed to hx509_crypto_select and hx509_crypto_available */ #define HX509_SELECT_ALL 0 #define HX509_SELECT_DIGEST 1 #define HX509_SELECT_PUBLIC_SIG 2 #define HX509_SELECT_PUBLIC_ENC 3 #define HX509_SELECT_SECRET_ENC 4 /* flags to hx509_ca_tbs_set_template */ #define HX509_CA_TEMPLATE_SUBJECT 1 #define HX509_CA_TEMPLATE_SERIAL 2 #define HX509_CA_TEMPLATE_NOTBEFORE 4 #define HX509_CA_TEMPLATE_NOTAFTER 8 #define HX509_CA_TEMPLATE_SPKI 16 #define HX509_CA_TEMPLATE_KU 32 #define HX509_CA_TEMPLATE_EKU 64 /* flags hx509_cms_create_signed* */ #define HX509_CMS_SIGNATURE_DETACHED 0x01 #define HX509_CMS_SIGNATURE_ID_NAME 0x02 #define HX509_CMS_SIGNATURE_NO_SIGNER 0x04 #define HX509_CMS_SIGNATURE_LEAF_ONLY 0x08 #define HX509_CMS_SIGNATURE_NO_CERTS 0x10 /* hx509_verify_hostname nametype */ typedef enum { HX509_HN_HOSTNAME = 0, HX509_HN_DNSSRV } hx509_hostname_type; #include #include #endif /* HEIMDAL_HX509_H */ heimdal-7.5.0/lib/hx509/hx509-protos.h0000644000175000017500000021454713212445575015274 0ustar niknik/* This is a generated file */ #ifndef __hx509_protos_h__ #define __hx509_protos_h__ #ifndef DOXY #include #ifdef __cplusplus extern "C" { #endif #ifndef HX509_LIB #ifndef HX509_LIB_FUNCTION #if defined(_WIN32) #define HX509_LIB_FUNCTION __declspec(dllimport) #define HX509_LIB_CALL __stdcall #define HX509_LIB_VARIABLE __declspec(dllimport) #else #define HX509_LIB_FUNCTION #define HX509_LIB_CALL #define HX509_LIB_VARIABLE #endif #endif #endif /** * Print a bitstring using a hx509_vprint_func function. To print to * stdout use hx509_print_stdout(). * * @param b bit string to print. * @param func hx509_vprint_func to print with. * @param ctx context variable to hx509_vprint_func function. * * @ingroup hx509_print */ void hx509_bitstring_print ( const heim_bit_string */*b*/, hx509_vprint_func /*func*/, void */*ctx*/); /** * Sign a to-be-signed certificate object with a issuer certificate. * * The caller needs to at least have called the following functions on the * to-be-signed certificate object: * - hx509_ca_tbs_init() * - hx509_ca_tbs_set_subject() * - hx509_ca_tbs_set_spki() * * When done the to-be-signed certificate object should be freed with * hx509_ca_tbs_free(). * * When creating self-signed certificate use hx509_ca_sign_self() instead. * * @param context A hx509 context. * @param tbs object to be signed. * @param signer the CA certificate object to sign with (need private key). * @param certificate return cerificate, free with hx509_cert_free(). * * @return An hx509 error code, see hx509_get_error_string(). * * @ingroup hx509_ca */ int hx509_ca_sign ( hx509_context /*context*/, hx509_ca_tbs /*tbs*/, hx509_cert /*signer*/, hx509_cert */*certificate*/); /** * Work just like hx509_ca_sign() but signs it-self. * * @param context A hx509 context. * @param tbs object to be signed. * @param signer private key to sign with. * @param certificate return cerificate, free with hx509_cert_free(). * * @return An hx509 error code, see hx509_get_error_string(). * * @ingroup hx509_ca */ int hx509_ca_sign_self ( hx509_context /*context*/, hx509_ca_tbs /*tbs*/, hx509_private_key /*signer*/, hx509_cert */*certificate*/); /** * Add CRL distribution point URI to the to-be-signed certificate * object. * * @param context A hx509 context. * @param tbs object to be signed. * @param uri uri to the CRL. * @param issuername name of the issuer. * * @return An hx509 error code, see hx509_get_error_string(). * * @ingroup hx509_ca */ int hx509_ca_tbs_add_crl_dp_uri ( hx509_context /*context*/, hx509_ca_tbs /*tbs*/, const char */*uri*/, hx509_name /*issuername*/); /** * An an extended key usage to the to-be-signed certificate object. * Duplicates will detected and not added. * * @param context A hx509 context. * @param tbs object to be signed. * @param oid extended key usage to add. * * @return An hx509 error code, see hx509_get_error_string(). * * @ingroup hx509_ca */ int hx509_ca_tbs_add_eku ( hx509_context /*context*/, hx509_ca_tbs /*tbs*/, const heim_oid */*oid*/); /** * Add a Subject Alternative Name hostname to to-be-signed certificate * object. A domain match starts with ., an exact match does not. * * Example of a an domain match: .domain.se matches the hostname * host.domain.se. * * @param context A hx509 context. * @param tbs object to be signed. * @param dnsname a hostame. * * @return An hx509 error code, see hx509_get_error_string(). * * @ingroup hx509_ca */ int hx509_ca_tbs_add_san_hostname ( hx509_context /*context*/, hx509_ca_tbs /*tbs*/, const char */*dnsname*/); /** * Add a Jabber/XMPP jid Subject Alternative Name to the to-be-signed * certificate object. The jid is an UTF8 string. * * @param context A hx509 context. * @param tbs object to be signed. * @param jid string of an a jabber id in UTF8. * * @return An hx509 error code, see hx509_get_error_string(). * * @ingroup hx509_ca */ int hx509_ca_tbs_add_san_jid ( hx509_context /*context*/, hx509_ca_tbs /*tbs*/, const char */*jid*/); /** * Add Microsoft UPN Subject Alternative Name to the to-be-signed * certificate object. The principal string is a UTF8 string. * * @param context A hx509 context. * @param tbs object to be signed. * @param principal Microsoft UPN string. * * @return An hx509 error code, see hx509_get_error_string(). * * @ingroup hx509_ca */ int hx509_ca_tbs_add_san_ms_upn ( hx509_context /*context*/, hx509_ca_tbs /*tbs*/, const char */*principal*/); /** * Add Subject Alternative Name otherName to the to-be-signed * certificate object. * * @param context A hx509 context. * @param tbs object to be signed. * @param oid the oid of the OtherName. * @param os data in the other name. * * @return An hx509 error code, see hx509_get_error_string(). * * @ingroup hx509_ca */ int hx509_ca_tbs_add_san_otherName ( hx509_context /*context*/, hx509_ca_tbs /*tbs*/, const heim_oid */*oid*/, const heim_octet_string */*os*/); /** * Add Kerberos Subject Alternative Name to the to-be-signed * certificate object. The principal string is a UTF8 string. * * @param context A hx509 context. * @param tbs object to be signed. * @param principal Kerberos principal to add to the certificate. * * @return An hx509 error code, see hx509_get_error_string(). * * @ingroup hx509_ca */ int hx509_ca_tbs_add_san_pkinit ( hx509_context /*context*/, hx509_ca_tbs /*tbs*/, const char */*principal*/); /** * Add a Subject Alternative Name rfc822 (email address) to * to-be-signed certificate object. * * @param context A hx509 context. * @param tbs object to be signed. * @param rfc822Name a string to a email address. * * @return An hx509 error code, see hx509_get_error_string(). * * @ingroup hx509_ca */ int hx509_ca_tbs_add_san_rfc822name ( hx509_context /*context*/, hx509_ca_tbs /*tbs*/, const char */*rfc822Name*/); /** * Free an To Be Signed object. * * @param tbs object to free. * * @ingroup hx509_ca */ void hx509_ca_tbs_free (hx509_ca_tbs */*tbs*/); /** * Allocate an to-be-signed certificate object that will be converted * into an certificate. * * @param context A hx509 context. * @param tbs returned to-be-signed certicate object, free with * hx509_ca_tbs_free(). * * @return An hx509 error code, see hx509_get_error_string(). * * @ingroup hx509_ca */ int hx509_ca_tbs_init ( hx509_context /*context*/, hx509_ca_tbs */*tbs*/); /** * Make the to-be-signed certificate object a CA certificate. If the * pathLenConstraint is negative path length constraint is used. * * @param context A hx509 context. * @param tbs object to be signed. * @param pathLenConstraint path length constraint, negative, no * constraint. * * @return An hx509 error code, see hx509_get_error_string(). * * @ingroup hx509_ca */ int hx509_ca_tbs_set_ca ( hx509_context /*context*/, hx509_ca_tbs /*tbs*/, int /*pathLenConstraint*/); /** * Make the to-be-signed certificate object a windows domain controller certificate. * * @param context A hx509 context. * @param tbs object to be signed. * * @return An hx509 error code, see hx509_get_error_string(). * * @ingroup hx509_ca */ int hx509_ca_tbs_set_domaincontroller ( hx509_context /*context*/, hx509_ca_tbs /*tbs*/); /** * Set the absolute time when the certificate is valid to. * * @param context A hx509 context. * @param tbs object to be signed. * @param t time when the certificate will expire * * @return An hx509 error code, see hx509_get_error_string(). * * @ingroup hx509_ca */ int hx509_ca_tbs_set_notAfter ( hx509_context /*context*/, hx509_ca_tbs /*tbs*/, time_t /*t*/); /** * Set the relative time when the certificiate is going to expire. * * @param context A hx509 context. * @param tbs object to be signed. * @param delta seconds to the certificate is going to expire. * * @return An hx509 error code, see hx509_get_error_string(). * * @ingroup hx509_ca */ int hx509_ca_tbs_set_notAfter_lifetime ( hx509_context /*context*/, hx509_ca_tbs /*tbs*/, time_t /*delta*/); /** * Set the absolute time when the certificate is valid from. If not * set the current time will be used. * * @param context A hx509 context. * @param tbs object to be signed. * @param t time the certificated will start to be valid * * @return An hx509 error code, see hx509_get_error_string(). * * @ingroup hx509_ca */ int hx509_ca_tbs_set_notBefore ( hx509_context /*context*/, hx509_ca_tbs /*tbs*/, time_t /*t*/); /** * Make the to-be-signed certificate object a proxy certificate. If the * pathLenConstraint is negative path length constraint is used. * * @param context A hx509 context. * @param tbs object to be signed. * @param pathLenConstraint path length constraint, negative, no * constraint. * * @return An hx509 error code, see hx509_get_error_string(). * * @ingroup hx509_ca */ int hx509_ca_tbs_set_proxy ( hx509_context /*context*/, hx509_ca_tbs /*tbs*/, int /*pathLenConstraint*/); /** * Set the serial number to use for to-be-signed certificate object. * * @param context A hx509 context. * @param tbs object to be signed. * @param serialNumber serial number to use for the to-be-signed * certificate object. * * @return An hx509 error code, see hx509_get_error_string(). * * @ingroup hx509_ca */ int hx509_ca_tbs_set_serialnumber ( hx509_context /*context*/, hx509_ca_tbs /*tbs*/, const heim_integer */*serialNumber*/); /** * Set signature algorithm on the to be signed certificate * * @param context A hx509 context. * @param tbs object to be signed. * @param sigalg signature algorithm to use * * @return An hx509 error code, see hx509_get_error_string(). * * @ingroup hx509_ca */ int hx509_ca_tbs_set_signature_algorithm ( hx509_context /*context*/, hx509_ca_tbs /*tbs*/, const AlgorithmIdentifier */*sigalg*/); /** * Set the subject public key info (SPKI) in the to-be-signed certificate * object. SPKI is the public key and key related parameters in the * certificate. * * @param context A hx509 context. * @param tbs object to be signed. * @param spki subject public key info to use for the to-be-signed certificate object. * * @return An hx509 error code, see hx509_get_error_string(). * * @ingroup hx509_ca */ int hx509_ca_tbs_set_spki ( hx509_context /*context*/, hx509_ca_tbs /*tbs*/, const SubjectPublicKeyInfo */*spki*/); /** * Set the subject name of a to-be-signed certificate object. * * @param context A hx509 context. * @param tbs object to be signed. * @param subject the name to set a subject. * * @return An hx509 error code, see hx509_get_error_string(). * * @ingroup hx509_ca */ int hx509_ca_tbs_set_subject ( hx509_context /*context*/, hx509_ca_tbs /*tbs*/, hx509_name /*subject*/); /** * Initialize the to-be-signed certificate object from a template certifiate. * * @param context A hx509 context. * @param tbs object to be signed. * @param flags bit field selecting what to copy from the template * certifiate. * @param cert template certificate. * * @return An hx509 error code, see hx509_get_error_string(). * * @ingroup hx509_ca */ int hx509_ca_tbs_set_template ( hx509_context /*context*/, hx509_ca_tbs /*tbs*/, int /*flags*/, hx509_cert /*cert*/); /** * Set the issuerUniqueID and subjectUniqueID * * These are only supposed to be used considered with version 2 * certificates, replaced by the two extensions SubjectKeyIdentifier * and IssuerKeyIdentifier. This function is to allow application * using legacy protocol to issue them. * * @param context A hx509 context. * @param tbs object to be signed. * @param issuerUniqueID to be set * @param subjectUniqueID to be set * * @return An hx509 error code, see hx509_get_error_string(). * * @ingroup hx509_ca */ int hx509_ca_tbs_set_unique ( hx509_context /*context*/, hx509_ca_tbs /*tbs*/, const heim_bit_string */*subjectUniqueID*/, const heim_bit_string */*issuerUniqueID*/); /** * Expand the the subject name in the to-be-signed certificate object * using hx509_name_expand(). * * @param context A hx509 context. * @param tbs object to be signed. * @param env environment variable to expand variables in the subject * name, see hx509_env_init(). * * @return An hx509 error code, see hx509_get_error_string(). * * @ingroup hx509_ca */ int hx509_ca_tbs_subject_expand ( hx509_context /*context*/, hx509_ca_tbs /*tbs*/, hx509_env /*env*/); /** * Make of template units, use to build flags argument to * hx509_ca_tbs_set_template() with parse_units(). * * @return an units structure. * * @ingroup hx509_ca */ const struct units * hx509_ca_tbs_template_units (void); /** * Encodes the hx509 certificate as a DER encode binary. * * @param context A hx509 context. * @param c the certificate to encode. * @param os the encode certificate, set to NULL, 0 on case of * error. Free the os->data with hx509_xfree(). * * @return An hx509 error code, see hx509_get_error_string(). * * @ingroup hx509_cert */ int hx509_cert_binary ( hx509_context /*context*/, hx509_cert /*c*/, heim_octet_string */*os*/); /** * Check the extended key usage on the hx509 certificate. * * @param context A hx509 context. * @param cert A hx509 context. * @param eku the EKU to check for * @param allow_any_eku if the any EKU is set, allow that to be a * substitute. * * @return An hx509 error code, see hx509_get_error_string(). * * @ingroup hx509_cert */ int hx509_cert_check_eku ( hx509_context /*context*/, hx509_cert /*cert*/, const heim_oid */*eku*/, int /*allow_any_eku*/); /** * Compare to hx509 certificate object, useful for sorting. * * @param p a hx509 certificate object. * @param q a hx509 certificate object. * * @return 0 the objects are the same, returns > 0 is p is "larger" * then q, < 0 if p is "smaller" then q. * * @ingroup hx509_cert */ int hx509_cert_cmp ( hx509_cert /*p*/, hx509_cert /*q*/); /** * Return a list of subjectAltNames specified by oid in the * certificate. On error the * * The returned list of octet string should be freed with * hx509_free_octet_string_list(). * * @param context A hx509 context. * @param cert a hx509 certificate object. * @param oid an oid to for SubjectAltName. * @param list list of matching SubjectAltName. * * @return An hx509 error code, see hx509_get_error_string(). * * @ingroup hx509_cert */ int hx509_cert_find_subjectAltName_otherName ( hx509_context /*context*/, hx509_cert /*cert*/, const heim_oid */*oid*/, hx509_octet_string_list */*list*/); /** * Free reference to the hx509 certificate object, if the refcounter * reaches 0, the object if freed. Its allowed to pass in NULL. * * @param cert the cert to free. * * @ingroup hx509_cert */ void hx509_cert_free (hx509_cert /*cert*/); /** * Get the SubjectPublicKeyInfo structure from the hx509 certificate. * * @param context a hx509 context. * @param p a hx509 certificate object. * @param spki SubjectPublicKeyInfo, should be freed with * free_SubjectPublicKeyInfo(). * * @return An hx509 error code, see hx509_get_error_string(). * * @ingroup hx509_cert */ int hx509_cert_get_SPKI ( hx509_context /*context*/, hx509_cert /*p*/, SubjectPublicKeyInfo */*spki*/); /** * Get the AlgorithmIdentifier from the hx509 certificate. * * @param context a hx509 context. * @param p a hx509 certificate object. * @param alg AlgorithmIdentifier, should be freed with * free_AlgorithmIdentifier(). The algorithmidentifier is * typicly rsaEncryption, or id-ecPublicKey, or some other * public key mechanism. * * @return An hx509 error code, see hx509_get_error_string(). * * @ingroup hx509_cert */ int hx509_cert_get_SPKI_AlgorithmIdentifier ( hx509_context /*context*/, hx509_cert /*p*/, AlgorithmIdentifier */*alg*/); /** * Get an external attribute for the certificate, examples are * friendly name and id. * * @param cert hx509 certificate object to search * @param oid an oid to search for. * * @return an hx509_cert_attribute, only valid as long as the * certificate is referenced. * * @ingroup hx509_cert */ hx509_cert_attribute hx509_cert_get_attribute ( hx509_cert /*cert*/, const heim_oid */*oid*/); /** * Return the name of the base subject of the hx509 certificate. If * the certiicate is a verified proxy certificate, the this function * return the base certificate (root of the proxy chain). If the proxy * certificate is not verified with the base certificate * HX509_PROXY_CERTIFICATE_NOT_CANONICALIZED is returned. * * @param context a hx509 context. * @param c a hx509 certificate object. * @param name a pointer to a hx509 name, should be freed by * hx509_name_free(). See also hx509_cert_get_subject(). * * @return An hx509 error code, see hx509_get_error_string(). * * @ingroup hx509_cert */ int hx509_cert_get_base_subject ( hx509_context /*context*/, hx509_cert /*c*/, hx509_name */*name*/); /** * Get friendly name of the certificate. * * @param cert cert to get the friendly name from. * * @return an friendly name or NULL if there is. The friendly name is * only valid as long as the certificate is referenced. * * @ingroup hx509_cert */ const char * hx509_cert_get_friendly_name (hx509_cert /*cert*/); /** * Return the name of the issuer of the hx509 certificate. * * @param p a hx509 certificate object. * @param name a pointer to a hx509 name, should be freed by * hx509_name_free(). * * @return An hx509 error code, see hx509_get_error_string(). * * @ingroup hx509_cert */ int hx509_cert_get_issuer ( hx509_cert /*p*/, hx509_name */*name*/); /** * Get a copy of the Issuer Unique ID * * @param context a hx509_context * @param p a hx509 certificate * @param issuer the issuer id returned, free with der_free_bit_string() * * @return An hx509 error code, see hx509_get_error_string(). The * error code HX509_EXTENSION_NOT_FOUND is returned if the certificate * doesn't have a issuerUniqueID * * @ingroup hx509_cert */ int hx509_cert_get_issuer_unique_id ( hx509_context /*context*/, hx509_cert /*p*/, heim_bit_string */*issuer*/); /** * Get notAfter time of the certificate. * * @param p a hx509 certificate object. * * @return return not after time. * * @ingroup hx509_cert */ time_t hx509_cert_get_notAfter (hx509_cert /*p*/); /** * Get notBefore time of the certificate. * * @param p a hx509 certificate object. * * @return return not before time * * @ingroup hx509_cert */ time_t hx509_cert_get_notBefore (hx509_cert /*p*/); /** * Get serial number of the certificate. * * @param p a hx509 certificate object. * @param i serial number, should be freed ith der_free_heim_integer(). * * @return An hx509 error code, see hx509_get_error_string(). * * @ingroup hx509_cert */ int hx509_cert_get_serialnumber ( hx509_cert /*p*/, heim_integer */*i*/); /** * Return the name of the subject of the hx509 certificate. * * @param p a hx509 certificate object. * @param name a pointer to a hx509 name, should be freed by * hx509_name_free(). See also hx509_cert_get_base_subject(). * * @return An hx509 error code, see hx509_get_error_string(). * * @ingroup hx509_cert */ int hx509_cert_get_subject ( hx509_cert /*p*/, hx509_name */*name*/); /** * Get a copy of the Subect Unique ID * * @param context a hx509_context * @param p a hx509 certificate * @param subject the subject id returned, free with der_free_bit_string() * * @return An hx509 error code, see hx509_get_error_string(). The * error code HX509_EXTENSION_NOT_FOUND is returned if the certificate * doesn't have a subjectUniqueID * * @ingroup hx509_cert */ int hx509_cert_get_subject_unique_id ( hx509_context /*context*/, hx509_cert /*p*/, heim_bit_string */*subject*/); int hx509_cert_have_private_key (hx509_cert /*p*/); /** * Allocate and init an hx509 certificate object from the decoded * certificate `c´. * * @param context A hx509 context. * @param c * @param error * * @return Returns an hx509 certificate * * @ingroup hx509_cert */ hx509_cert hx509_cert_init ( hx509_context /*context*/, const Certificate */*c*/, heim_error_t */*error*/); /** * Just like hx509_cert_init(), but instead of a decode certificate * takes an pointer and length to a memory region that contains a * DER/BER encoded certificate. * * If the memory region doesn't contain just the certificate and * nothing more the function will fail with * HX509_EXTRA_DATA_AFTER_STRUCTURE. * * @param context A hx509 context. * @param ptr pointer to memory region containing encoded certificate. * @param len length of memory region. * @param error possibly returns an error * * @return An hx509 certificate * * @ingroup hx509_cert */ hx509_cert hx509_cert_init_data ( hx509_context /*context*/, const void */*ptr*/, size_t /*len*/, heim_error_t */*error*/); /** * Print certificate usage for a certificate to a string. * * @param context A hx509 context. * @param c a certificate print the keyusage for. * @param s the return string with the keysage printed in to, free * with hx509_xfree(). * * @return An hx509 error code, see hx509_get_error_string(). * * @ingroup hx509_print */ int hx509_cert_keyusage_print ( hx509_context /*context*/, hx509_cert /*c*/, char **/*s*/); int hx509_cert_public_encrypt ( hx509_context /*context*/, const heim_octet_string */*cleartext*/, const hx509_cert /*p*/, heim_oid */*encryption_oid*/, heim_octet_string */*ciphertext*/); /** * Add a reference to a hx509 certificate object. * * @param cert a pointer to an hx509 certificate object. * * @return the same object as is passed in. * * @ingroup hx509_cert */ hx509_cert hx509_cert_ref (hx509_cert /*cert*/); /** * Set the friendly name on the certificate. * * @param cert The certificate to set the friendly name on * @param name Friendly name. * * @return An hx509 error code, see hx509_get_error_string(). * * @ingroup hx509_cert */ int hx509_cert_set_friendly_name ( hx509_cert /*cert*/, const char */*name*/); /** * Add a certificate to the certificiate store. * * The receiving keyset certs will either increase reference counter * of the cert or make a deep copy, either way, the caller needs to * free the cert itself. * * @param context a hx509 context. * @param certs certificate store to add the certificate to. * @param cert certificate to add. * * @return Returns an hx509 error code. * * @ingroup hx509_keyset */ int hx509_certs_add ( hx509_context /*context*/, hx509_certs /*certs*/, hx509_cert /*cert*/); /** * Same a hx509_certs_merge() but use a lock and name to describe the * from source. * * @param context a hx509 context. * @param to the store to merge into. * @param lock a lock that unlocks the certificates store, use NULL to * select no password/certifictes/prompt lock (see @ref page_lock). * @param name name of the source store * * @return Returns an hx509 error code. * * @ingroup hx509_keyset */ int hx509_certs_append ( hx509_context /*context*/, hx509_certs /*to*/, hx509_lock /*lock*/, const char */*name*/); /** * End the iteration over certificates. * * @param context a hx509 context. * @param certs certificate store to iterate over. * @param cursor cursor that will keep track of progress, freed. * * @return Returns an hx509 error code. * * @ingroup hx509_keyset */ int hx509_certs_end_seq ( hx509_context /*context*/, hx509_certs /*certs*/, hx509_cursor /*cursor*/); /** * Filter certificate matching the query. * * @param context a hx509 context. * @param certs certificate store to search. * @param q query allocated with @ref hx509_query functions. * @param result the filtered certificate store, caller must free with * hx509_certs_free(). * * @return Returns an hx509 error code. * * @ingroup hx509_keyset */ int hx509_certs_filter ( hx509_context /*context*/, hx509_certs /*certs*/, const hx509_query */*q*/, hx509_certs */*result*/); /** * Find a certificate matching the query. * * @param context a hx509 context. * @param certs certificate store to search. * @param q query allocated with @ref hx509_query functions. * @param r return certificate (or NULL on error), should be freed * with hx509_cert_free(). * * @return Returns an hx509 error code. * * @ingroup hx509_keyset */ int hx509_certs_find ( hx509_context /*context*/, hx509_certs /*certs*/, const hx509_query */*q*/, hx509_cert */*r*/); /** * Free a certificate store. * * @param certs certificate store to free. * * @ingroup hx509_keyset */ void hx509_certs_free (hx509_certs */*certs*/); /** * Print some info about the certificate store. * * @param context a hx509 context. * @param certs certificate store to print information about. * @param func function that will get each line of the information, if * NULL is used the data is printed on a FILE descriptor that should * be passed in ctx, if ctx also is NULL, stdout is used. * @param ctx parameter to func. * * @return Returns an hx509 error code. * * @ingroup hx509_keyset */ int hx509_certs_info ( hx509_context /*context*/, hx509_certs /*certs*/, int (*/*func*/)(void *, const char *), void */*ctx*/); /** * Open or creates a new hx509 certificate store. * * @param context A hx509 context * @param name name of the store, format is TYPE:type-specific-string, * if NULL is used the MEMORY store is used. * @param flags list of flags: * - HX509_CERTS_CREATE create a new keystore of the specific TYPE. * - HX509_CERTS_UNPROTECT_ALL fails if any private key failed to be extracted. * @param lock a lock that unlocks the certificates store, use NULL to * select no password/certifictes/prompt lock (see @ref page_lock). * @param certs return pointer, free with hx509_certs_free(). * * @return Returns an hx509 error code. * * @ingroup hx509_keyset */ int hx509_certs_init ( hx509_context /*context*/, const char */*name*/, int /*flags*/, hx509_lock /*lock*/, hx509_certs */*certs*/); /** * Iterate over all certificates in a keystore and call a block * for each of them. * * @param context a hx509 context. * @param certs certificate store to iterate over. * @param func block to call for each certificate. The function * should return non-zero to abort the iteration, that value is passed * back to the caller of hx509_certs_iter(). * * @return Returns an hx509 error code. * * @ingroup hx509_keyset */ #ifdef __BLOCKS__ int hx509_certs_iter ( hx509_context /*context*/, hx509_certs /*certs*/, int (^func)(hx509_cert)); #endif /* __BLOCKS__ */ /** * Iterate over all certificates in a keystore and call a function * for each of them. * * @param context a hx509 context. * @param certs certificate store to iterate over. * @param func function to call for each certificate. The function * should return non-zero to abort the iteration, that value is passed * back to the caller of hx509_certs_iter_f(). * @param ctx context variable that will passed to the function. * * @return Returns an hx509 error code. * * @ingroup hx509_keyset */ int hx509_certs_iter_f ( hx509_context /*context*/, hx509_certs /*certs*/, int (*/*func*/)(hx509_context, void *, hx509_cert), void */*ctx*/); /** * Merge a certificate store into another. The from store is keep * intact. * * @param context a hx509 context. * @param to the store to merge into. * @param from the store to copy the object from. * * @return Returns an hx509 error code. * * @ingroup hx509_keyset */ int hx509_certs_merge ( hx509_context /*context*/, hx509_certs /*to*/, hx509_certs /*from*/); /** * Get next ceritificate from the certificate keystore pointed out by * cursor. * * @param context a hx509 context. * @param certs certificate store to iterate over. * @param cursor cursor that keeps track of progress. * @param cert return certificate next in store, NULL if the store * contains no more certificates. Free with hx509_cert_free(). * * @return Returns an hx509 error code. * * @ingroup hx509_keyset */ int hx509_certs_next_cert ( hx509_context /*context*/, hx509_certs /*certs*/, hx509_cursor /*cursor*/, hx509_cert */*cert*/); hx509_certs hx509_certs_ref (hx509_certs /*certs*/); /** * Start the integration * * @param context a hx509 context. * @param certs certificate store to iterate over * @param cursor cursor that will keep track of progress, free with * hx509_certs_end_seq(). * * @return Returns an hx509 error code. HX509_UNSUPPORTED_OPERATION is * returned if the certificate store doesn't support the iteration * operation. * * @ingroup hx509_keyset */ int hx509_certs_start_seq ( hx509_context /*context*/, hx509_certs /*certs*/, hx509_cursor */*cursor*/); /** * Write the certificate store to stable storage. * * @param context A hx509 context. * @param certs a certificate store to store. * @param flags currently unused, use 0. * @param lock a lock that unlocks the certificates store, use NULL to * select no password/certifictes/prompt lock (see @ref page_lock). * * @return Returns an hx509 error code. HX509_UNSUPPORTED_OPERATION if * the certificate store doesn't support the store operation. * * @ingroup hx509_keyset */ int hx509_certs_store ( hx509_context /*context*/, hx509_certs /*certs*/, int /*flags*/, hx509_lock /*lock*/); /** * Function to use to hx509_certs_iter_f() as a function argument, the * ctx variable to hx509_certs_iter_f() should be a FILE file descriptor. * * @param context a hx509 context. * @param ctx used by hx509_certs_iter_f(). * @param c a certificate * * @return Returns an hx509 error code. * * @ingroup hx509_keyset */ int hx509_ci_print_names ( hx509_context /*context*/, void */*ctx*/, hx509_cert /*c*/); /** * Resets the error strings the hx509 context. * * @param context A hx509 context. * * @ingroup hx509_error */ void hx509_clear_error_string (hx509_context /*context*/); int hx509_cms_create_signed ( hx509_context /*context*/, int /*flags*/, const heim_oid */*eContentType*/, const void */*data*/, size_t /*length*/, const AlgorithmIdentifier */*digest_alg*/, hx509_certs /*certs*/, hx509_peer_info /*peer*/, hx509_certs /*anchors*/, hx509_certs /*pool*/, heim_octet_string */*signed_data*/); /** * Decode SignedData and verify that the signature is correct. * * @param context A hx509 context. * @param flags * @param eContentType the type of the data. * @param data data to sign * @param length length of the data that data point to. * @param digest_alg digest algorithm to use, use NULL to get the * default or the peer determined algorithm. * @param cert certificate to use for sign the data. * @param peer info about the peer the message to send the message to, * like what digest algorithm to use. * @param anchors trust anchors that the client will use, used to * polulate the certificates included in the message * @param pool certificates to use in try to build the path to the * trust anchors. * @param signed_data the output of the function, free with * der_free_octet_string(). * * @return Returns an hx509 error code. * * @ingroup hx509_cms */ int hx509_cms_create_signed_1 ( hx509_context /*context*/, int /*flags*/, const heim_oid */*eContentType*/, const void */*data*/, size_t /*length*/, const AlgorithmIdentifier */*digest_alg*/, hx509_cert /*cert*/, hx509_peer_info /*peer*/, hx509_certs /*anchors*/, hx509_certs /*pool*/, heim_octet_string */*signed_data*/); /** * Use HX509_CMS_SIGNATURE_NO_SIGNER to create no sigInfo (no * signatures). */ int hx509_cms_decrypt_encrypted ( hx509_context /*context*/, hx509_lock /*lock*/, const void */*data*/, size_t /*length*/, heim_oid */*contentType*/, heim_octet_string */*content*/); /** * Encrypt end encode EnvelopedData. * * Encrypt and encode EnvelopedData. The data is encrypted with a * random key and the the random key is encrypted with the * certificates private key. This limits what private key type can be * used to RSA. * * @param context A hx509 context. * @param flags flags to control the behavior. * - HX509_CMS_EV_NO_KU_CHECK - Dont check KU on certificate * - HX509_CMS_EV_ALLOW_WEAK - Allow weak crytpo * - HX509_CMS_EV_ID_NAME - prefer issuer name and serial number * @param cert Certificate to encrypt the EnvelopedData encryption key * with. * @param data pointer the data to encrypt. * @param length length of the data that data point to. * @param encryption_type Encryption cipher to use for the bulk data, * use NULL to get default. * @param contentType type of the data that is encrypted * @param content the output of the function, * free with der_free_octet_string(). * * @return an hx509 error code. * * @ingroup hx509_cms */ int hx509_cms_envelope_1 ( hx509_context /*context*/, int /*flags*/, hx509_cert /*cert*/, const void */*data*/, size_t /*length*/, const heim_oid */*encryption_type*/, const heim_oid */*contentType*/, heim_octet_string */*content*/); /** * Decode and unencrypt EnvelopedData. * * Extract data and parameteres from from the EnvelopedData. Also * supports using detached EnvelopedData. * * @param context A hx509 context. * @param certs Certificate that can decrypt the EnvelopedData * encryption key. * @param flags HX509_CMS_UE flags to control the behavior. * @param data pointer the structure the contains the DER/BER encoded * EnvelopedData stucture. * @param length length of the data that data point to. * @param encryptedContent in case of detached signature, this * contains the actual encrypted data, othersize its should be NULL. * @param time_now set the current time, if zero the library uses now as the date. * @param contentType output type oid, should be freed with der_free_oid(). * @param content the data, free with der_free_octet_string(). * * @return an hx509 error code. * * @ingroup hx509_cms */ int hx509_cms_unenvelope ( hx509_context /*context*/, hx509_certs /*certs*/, int /*flags*/, const void */*data*/, size_t /*length*/, const heim_octet_string */*encryptedContent*/, time_t /*time_now*/, heim_oid */*contentType*/, heim_octet_string */*content*/); /** * Decode an ContentInfo and unwrap data and oid it. * * @param in the encoded buffer. * @param oid type of the content. * @param out data to be wrapped. * @param have_data since the data is optional, this flags show dthe * diffrence between no data and the zero length data. * * @return Returns an hx509 error code. * * @ingroup hx509_cms */ int hx509_cms_unwrap_ContentInfo ( const heim_octet_string */*in*/, heim_oid */*oid*/, heim_octet_string */*out*/, int */*have_data*/); /** * Decode SignedData and verify that the signature is correct. * * @param context A hx509 context. * @param ctx a hx509 verify context. * @param flags to control the behaivor of the function. * - HX509_CMS_VS_NO_KU_CHECK - Don't check KeyUsage * - HX509_CMS_VS_ALLOW_DATA_OID_MISMATCH - allow oid mismatch * - HX509_CMS_VS_ALLOW_ZERO_SIGNER - no signer, see below. * @param data pointer to CMS SignedData encoded data. * @param length length of the data that data point to. * @param signedContent external data used for signature. * @param pool certificate pool to build certificates paths. * @param contentType free with der_free_oid(). * @param content the output of the function, free with * der_free_octet_string(). * @param signer_certs list of the cerficates used to sign this * request, free with hx509_certs_free(). * * @return an hx509 error code. * * @ingroup hx509_cms */ int hx509_cms_verify_signed ( hx509_context /*context*/, hx509_verify_ctx /*ctx*/, unsigned int /*flags*/, const void */*data*/, size_t /*length*/, const heim_octet_string */*signedContent*/, hx509_certs /*pool*/, heim_oid */*contentType*/, heim_octet_string */*content*/, hx509_certs */*signer_certs*/); /** * Wrap data and oid in a ContentInfo and encode it. * * @param oid type of the content. * @param buf data to be wrapped. If a NULL pointer is passed in, the * optional content field in the ContentInfo is not going be filled * in. * @param res the encoded buffer, the result should be freed with * der_free_octet_string(). * * @return Returns an hx509 error code. * * @ingroup hx509_cms */ int hx509_cms_wrap_ContentInfo ( const heim_oid */*oid*/, const heim_octet_string */*buf*/, heim_octet_string */*res*/); /** * Free the context allocated by hx509_context_init(). * * @param context context to be freed. * * @ingroup hx509 */ void hx509_context_free (hx509_context */*context*/); /** * Creates a hx509 context that most functions in the library * uses. The context is only allowed to be used by one thread at each * moment. Free the context with hx509_context_free(). * * @param context Returns a pointer to new hx509 context. * * @return Returns an hx509 error code. * * @ingroup hx509 */ int hx509_context_init (hx509_context */*context*/); /** * Selects if the hx509_revoke_verify() function is going to require * the existans of a revokation method (OCSP, CRL) or not. Note that * hx509_verify_path(), hx509_cms_verify_signed(), and other function * call hx509_revoke_verify(). * * @param context hx509 context to change the flag for. * @param flag zero, revokation method required, non zero missing * revokation method ok * * @ingroup hx509_verify */ void hx509_context_set_missing_revoke ( hx509_context /*context*/, int /*flag*/); /** * Add revoked certificate to an CRL context. * * @param context a hx509 context. * @param crl the CRL to add the revoked certificate to. * @param certs keyset of certificate to revoke. * * @return An hx509 error code, see hx509_get_error_string(). * * @ingroup hx509_verify */ int hx509_crl_add_revoked_certs ( hx509_context /*context*/, hx509_crl /*crl*/, hx509_certs /*certs*/); /** * Create a CRL context. Use hx509_crl_free() to free the CRL context. * * @param context a hx509 context. * @param crl return pointer to a newly allocated CRL context. * * @return An hx509 error code, see hx509_get_error_string(). * * @ingroup hx509_verify */ int hx509_crl_alloc ( hx509_context /*context*/, hx509_crl */*crl*/); /** * Free a CRL context. * * @param context a hx509 context. * @param crl a CRL context to free. * * @ingroup hx509_verify */ void hx509_crl_free ( hx509_context /*context*/, hx509_crl */*crl*/); /** * Set the lifetime of a CRL context. * * @param context a hx509 context. * @param crl a CRL context * @param delta delta time the certificate is valid, library adds the * current time to this. * * @return An hx509 error code, see hx509_get_error_string(). * * @ingroup hx509_verify */ int hx509_crl_lifetime ( hx509_context /*context*/, hx509_crl /*crl*/, int /*delta*/); /** * Sign a CRL and return an encode certificate. * * @param context a hx509 context. * @param signer certificate to sign the CRL with * @param crl the CRL to sign * @param os return the signed and encoded CRL, free with * free_heim_octet_string() * * @return An hx509 error code, see hx509_get_error_string(). * * @ingroup hx509_verify */ int hx509_crl_sign ( hx509_context /*context*/, hx509_cert /*signer*/, hx509_crl /*crl*/, heim_octet_string */*os*/); const AlgorithmIdentifier * hx509_crypto_aes128_cbc (void); const AlgorithmIdentifier * hx509_crypto_aes256_cbc (void); void hx509_crypto_allow_weak (hx509_crypto /*crypto*/); int hx509_crypto_available ( hx509_context /*context*/, int /*type*/, hx509_cert /*source*/, AlgorithmIdentifier **/*val*/, unsigned int */*plen*/); int hx509_crypto_decrypt ( hx509_crypto /*crypto*/, const void */*data*/, const size_t /*length*/, heim_octet_string */*ivec*/, heim_octet_string */*clear*/); const AlgorithmIdentifier * hx509_crypto_des_rsdi_ede3_cbc (void); void hx509_crypto_destroy (hx509_crypto /*crypto*/); int hx509_crypto_encrypt ( hx509_crypto /*crypto*/, const void */*data*/, const size_t /*length*/, const heim_octet_string */*ivec*/, heim_octet_string **/*ciphertext*/); const heim_oid * hx509_crypto_enctype_by_name (const char */*name*/); void hx509_crypto_free_algs ( AlgorithmIdentifier */*val*/, unsigned int /*len*/); int hx509_crypto_get_params ( hx509_context /*context*/, hx509_crypto /*crypto*/, const heim_octet_string */*ivec*/, heim_octet_string */*param*/); int hx509_crypto_init ( hx509_context /*context*/, const char */*provider*/, const heim_oid */*enctype*/, hx509_crypto */*crypto*/); const char * hx509_crypto_provider (hx509_crypto /*crypto*/); int hx509_crypto_random_iv ( hx509_crypto /*crypto*/, heim_octet_string */*ivec*/); int hx509_crypto_select ( const hx509_context /*context*/, int /*type*/, const hx509_private_key /*source*/, hx509_peer_info /*peer*/, AlgorithmIdentifier */*selected*/); int hx509_crypto_set_key_data ( hx509_crypto /*crypto*/, const void */*data*/, size_t /*length*/); int hx509_crypto_set_key_name ( hx509_crypto /*crypto*/, const char */*name*/); void hx509_crypto_set_padding ( hx509_crypto /*crypto*/, int /*padding_type*/); int hx509_crypto_set_params ( hx509_context /*context*/, hx509_crypto /*crypto*/, const heim_octet_string */*param*/, heim_octet_string */*ivec*/); int hx509_crypto_set_random_key ( hx509_crypto /*crypto*/, heim_octet_string */*key*/); /** * Add a new key/value pair to the hx509_env. * * @param context A hx509 context. * @param env environment to add the environment variable too. * @param key key to add * @param value value to add * * @return An hx509 error code, see hx509_get_error_string(). * * @ingroup hx509_env */ int hx509_env_add ( hx509_context /*context*/, hx509_env */*env*/, const char */*key*/, const char */*value*/); /** * Add a new key/binding pair to the hx509_env. * * @param context A hx509 context. * @param env environment to add the environment variable too. * @param key key to add * @param list binding list to add * * @return An hx509 error code, see hx509_get_error_string(). * * @ingroup hx509_env */ int hx509_env_add_binding ( hx509_context /*context*/, hx509_env */*env*/, const char */*key*/, hx509_env /*list*/); /** * Search the hx509_env for a key. * * @param context A hx509 context. * @param env environment to add the environment variable too. * @param key key to search for. * * @return the value if the key is found, NULL otherwise. * * @ingroup hx509_env */ const char * hx509_env_find ( hx509_context /*context*/, hx509_env /*env*/, const char */*key*/); /** * Search the hx509_env for a binding. * * @param context A hx509 context. * @param env environment to add the environment variable too. * @param key key to search for. * * @return the binding if the key is found, NULL if not found. * * @ingroup hx509_env */ hx509_env hx509_env_find_binding ( hx509_context /*context*/, hx509_env /*env*/, const char */*key*/); /** * Free an hx509_env environment context. * * @param env the environment to free. * * @ingroup hx509_env */ void hx509_env_free (hx509_env */*env*/); /** * Search the hx509_env for a length based key. * * @param context A hx509 context. * @param env environment to add the environment variable too. * @param key key to search for. * @param len length of key. * * @return the value if the key is found, NULL otherwise. * * @ingroup hx509_env */ const char * hx509_env_lfind ( hx509_context /*context*/, hx509_env /*env*/, const char */*key*/, size_t /*len*/); /** * Print error message and fatally exit from error code * * @param context A hx509 context. * @param exit_code exit() code from process. * @param error_code Error code for the reason to exit. * @param fmt format string with the exit message. * @param ... argument to format string. * * @ingroup hx509_error */ void hx509_err ( hx509_context /*context*/, int /*exit_code*/, int /*error_code*/, const char */*fmt*/, ...); hx509_private_key_ops * hx509_find_private_alg (const heim_oid */*oid*/); /** * Free error string returned by hx509_get_error_string(). * * @param str error string to free. * * @ingroup hx509_error */ void hx509_free_error_string (char */*str*/); /** * Free a list of octet strings returned by another hx509 library * function. * * @param list list to be freed. * * @ingroup hx509_misc */ void hx509_free_octet_string_list (hx509_octet_string_list */*list*/); /** * Unparse the hx509 name in name into a string. * * @param name the name to print * @param str an allocated string returns the name in string form * * @return An hx509 error code, see hx509_get_error_string(). * * @ingroup hx509_name */ int hx509_general_name_unparse ( GeneralName */*name*/, char **/*str*/); /** * Get an error string from context associated with error_code. * * @param context A hx509 context. * @param error_code Get error message for this error code. * * @return error string, free with hx509_free_error_string(). * * @ingroup hx509_error */ char * hx509_get_error_string ( hx509_context /*context*/, int /*error_code*/); /** * Get one random certificate from the certificate store. * * @param context a hx509 context. * @param certs a certificate store to get the certificate from. * @param c return certificate, should be freed with hx509_cert_free(). * * @return Returns an hx509 error code. * * @ingroup hx509_keyset */ int hx509_get_one_cert ( hx509_context /*context*/, hx509_certs /*certs*/, hx509_cert */*c*/); int hx509_lock_add_cert ( hx509_context /*context*/, hx509_lock /*lock*/, hx509_cert /*cert*/); int hx509_lock_add_certs ( hx509_context /*context*/, hx509_lock /*lock*/, hx509_certs /*certs*/); int hx509_lock_add_password ( hx509_lock /*lock*/, const char */*password*/); int hx509_lock_command_string ( hx509_lock /*lock*/, const char */*string*/); void hx509_lock_free (hx509_lock /*lock*/); /** * @page page_lock Locking and unlocking certificates and encrypted data. * * See the library functions here: @ref hx509_lock */ int hx509_lock_init ( hx509_context /*context*/, hx509_lock */*lock*/); int hx509_lock_prompt ( hx509_lock /*lock*/, hx509_prompt */*prompt*/); void hx509_lock_reset_certs ( hx509_context /*context*/, hx509_lock /*lock*/); void hx509_lock_reset_passwords (hx509_lock /*lock*/); void hx509_lock_reset_promper (hx509_lock /*lock*/); int hx509_lock_set_prompter ( hx509_lock /*lock*/, hx509_prompter_fct /*prompt*/, void */*data*/); /** * Convert a hx509_name object to DER encoded name. * * @param name name to concert * @param os data to a DER encoded name, free the resulting octet * string with hx509_xfree(os->data). * * @return An hx509 error code, see hx509_get_error_string(). * * @ingroup hx509_name */ int hx509_name_binary ( const hx509_name /*name*/, heim_octet_string */*os*/); /** * Compare to hx509 name object, useful for sorting. * * @param n1 a hx509 name object. * @param n2 a hx509 name object. * * @return 0 the objects are the same, returns > 0 is n2 is "larger" * then n2, < 0 if n1 is "smaller" then n2. * * @ingroup hx509_name */ int hx509_name_cmp ( hx509_name /*n1*/, hx509_name /*n2*/); /** * Copy a hx509 name object. * * @param context A hx509 cotext. * @param from the name to copy from * @param to the name to copy to * * @return An hx509 error code, see hx509_get_error_string(). * * @ingroup hx509_name */ int hx509_name_copy ( hx509_context /*context*/, const hx509_name /*from*/, hx509_name */*to*/); /** * Expands variables in the name using env. Variables are on the form * ${name}. Useful when dealing with certificate templates. * * @param context A hx509 cotext. * @param name the name to expand. * @param env environment variable to expand. * * @return An hx509 error code, see hx509_get_error_string(). * * @ingroup hx509_name */ int hx509_name_expand ( hx509_context /*context*/, hx509_name /*name*/, hx509_env /*env*/); /** * Free a hx509 name object, upond return *name will be NULL. * * @param name a hx509 name object to be freed. * * @ingroup hx509_name */ void hx509_name_free (hx509_name */*name*/); /** * Unparse the hx509 name in name into a string. * * @param name the name to check if its empty/null. * * @return non zero if the name is empty/null. * * @ingroup hx509_name */ int hx509_name_is_null_p (const hx509_name /*name*/); int hx509_name_normalize ( hx509_context /*context*/, hx509_name /*name*/); /** * Convert a hx509_name into a Name. * * @param from the name to copy from * @param to the name to copy to * * @return An hx509 error code, see hx509_get_error_string(). * * @ingroup hx509_name */ int hx509_name_to_Name ( const hx509_name /*from*/, Name */*to*/); /** * Convert the hx509 name object into a printable string. * The resulting string should be freed with free(). * * @param name name to print * @param str the string to return * * @return An hx509 error code, see hx509_get_error_string(). * * @ingroup hx509_name */ int hx509_name_to_string ( const hx509_name /*name*/, char **/*str*/); /** * Create an OCSP request for a set of certificates. * * @param context a hx509 context * @param reqcerts list of certificates to request ocsp data for * @param pool certificate pool to use when signing * @param signer certificate to use to sign the request * @param digest the signing algorithm in the request, if NULL use the * default signature algorithm, * @param request the encoded request, free with free_heim_octet_string(). * @param nonce nonce in the request, free with free_heim_octet_string(). * * @return An hx509 error code, see hx509_get_error_string(). * * @ingroup hx509_revoke */ int hx509_ocsp_request ( hx509_context /*context*/, hx509_certs /*reqcerts*/, hx509_certs /*pool*/, hx509_cert /*signer*/, const AlgorithmIdentifier */*digest*/, heim_octet_string */*request*/, heim_octet_string */*nonce*/); /** * Verify that the certificate is part of the OCSP reply and it's not * expired. Doesn't verify signature the OCSP reply or it's done by a * authorized sender, that is assumed to be already done. * * @param context a hx509 context * @param now the time right now, if 0, use the current time. * @param cert the certificate to verify * @param flags flags control the behavior * @param data pointer to the encode ocsp reply * @param length the length of the encode ocsp reply * @param expiration return the time the OCSP will expire and need to * be rechecked. * * @return An hx509 error code, see hx509_get_error_string(). * * @ingroup hx509_verify */ int hx509_ocsp_verify ( hx509_context /*context*/, time_t /*now*/, hx509_cert /*cert*/, int /*flags*/, const void */*data*/, size_t /*length*/, time_t */*expiration*/); /** * Print a oid using a hx509_vprint_func function. To print to stdout * use hx509_print_stdout(). * * @param oid oid to print * @param func hx509_vprint_func to print with. * @param ctx context variable to hx509_vprint_func function. * * @ingroup hx509_print */ void hx509_oid_print ( const heim_oid */*oid*/, hx509_vprint_func /*func*/, void */*ctx*/); /** * Print a oid to a string. * * @param oid oid to print * @param str allocated string, free with hx509_xfree(). * * @return An hx509 error code, see hx509_get_error_string(). * * @ingroup hx509_print */ int hx509_oid_sprint ( const heim_oid */*oid*/, char **/*str*/); /** * Parse a string into a hx509 name object. * * @param context A hx509 context. * @param str a string to parse. * @param name the resulting object, NULL in case of error. * * @return An hx509 error code, see hx509_get_error_string(). * * @ingroup hx509_name */ int hx509_parse_name ( hx509_context /*context*/, const char */*str*/, hx509_name */*name*/); int hx509_parse_private_key ( hx509_context /*context*/, const AlgorithmIdentifier */*keyai*/, const void */*data*/, size_t /*len*/, hx509_key_format_t /*format*/, hx509_private_key */*private_key*/); /** * Add an additional algorithm that the peer supports. * * @param context A hx509 context. * @param peer the peer to set the new algorithms for * @param val an AlgorithmsIdentier to add * * @return An hx509 error code, see hx509_get_error_string(). * * @ingroup hx509_peer */ int hx509_peer_info_add_cms_alg ( hx509_context /*context*/, hx509_peer_info /*peer*/, const AlgorithmIdentifier */*val*/); /** * Allocate a new peer info structure an init it to default values. * * @param context A hx509 context. * @param peer return an allocated peer, free with hx509_peer_info_free(). * * @return An hx509 error code, see hx509_get_error_string(). * * @ingroup hx509_peer */ int hx509_peer_info_alloc ( hx509_context /*context*/, hx509_peer_info */*peer*/); /** * Free a peer info structure. * * @param peer peer info to be freed. * * @ingroup hx509_peer */ void hx509_peer_info_free (hx509_peer_info /*peer*/); /** * Set the certificate that remote peer is using. * * @param peer peer info to update * @param cert cerificate of the remote peer. * * @return An hx509 error code, see hx509_get_error_string(). * * @ingroup hx509_peer */ int hx509_peer_info_set_cert ( hx509_peer_info /*peer*/, hx509_cert /*cert*/); /** * Set the algorithms that the peer supports. * * @param context A hx509 context. * @param peer the peer to set the new algorithms for * @param val array of supported AlgorithmsIdentiers * @param len length of array val. * * @return An hx509 error code, see hx509_get_error_string(). * * @ingroup hx509_peer */ int hx509_peer_info_set_cms_algs ( hx509_context /*context*/, hx509_peer_info /*peer*/, const AlgorithmIdentifier */*val*/, size_t /*len*/); int hx509_pem_add_header ( hx509_pem_header **/*headers*/, const char */*header*/, const char */*value*/); const char * hx509_pem_find_header ( const hx509_pem_header */*h*/, const char */*header*/); void hx509_pem_free_header (hx509_pem_header */*headers*/); int hx509_pem_read ( hx509_context /*context*/, FILE */*f*/, hx509_pem_read_func /*func*/, void */*ctx*/); int hx509_pem_write ( hx509_context /*context*/, const char */*type*/, hx509_pem_header */*headers*/, FILE */*f*/, const void */*data*/, size_t /*size*/); /** * Print a simple representation of a certificate * * @param context A hx509 context, can be NULL * @param cert certificate to print * @param out the stdio output stream, if NULL, stdout is used * * @return An hx509 error code * * @ingroup hx509_cert */ int hx509_print_cert ( hx509_context /*context*/, hx509_cert /*cert*/, FILE */*out*/); /** * Helper function to print on stdout for: * - hx509_oid_print(), * - hx509_bitstring_print(), * - hx509_validate_ctx_set_print(). * * @param ctx the context to the print function. If the ctx is NULL, * stdout is used. * @param fmt the printing format. * @param va the argumet list. * * @ingroup hx509_print */ void hx509_print_stdout ( void */*ctx*/, const char */*fmt*/, va_list /*va*/); int hx509_private_key2SPKI ( hx509_context /*context*/, hx509_private_key /*private_key*/, SubjectPublicKeyInfo */*spki*/); void hx509_private_key_assign_rsa ( hx509_private_key /*key*/, void */*ptr*/); int hx509_private_key_free (hx509_private_key */*key*/); int hx509_private_key_init ( hx509_private_key */*key*/, hx509_private_key_ops */*ops*/, void */*keydata*/); int hx509_private_key_private_decrypt ( hx509_context /*context*/, const heim_octet_string */*ciphertext*/, const heim_oid */*encryption_oid*/, hx509_private_key /*p*/, heim_octet_string */*cleartext*/); int hx509_prompt_hidden (hx509_prompt_type /*type*/); /** * Allocate an query controller. Free using hx509_query_free(). * * @param context A hx509 context. * @param q return pointer to a hx509_query. * * @return An hx509 error code, see hx509_get_error_string(). * * @ingroup hx509_cert */ int hx509_query_alloc ( hx509_context /*context*/, hx509_query **/*q*/); /** * Free the query controller. * * @param context A hx509 context. * @param q a pointer to the query controller. * * @ingroup hx509_cert */ void hx509_query_free ( hx509_context /*context*/, hx509_query */*q*/); /** * Set the query controller to match using a specific match function. * * @param q a hx509 query controller. * @param func function to use for matching, if the argument is NULL, * the match function is removed. * @param ctx context passed to the function. * * @return An hx509 error code, see hx509_get_error_string(). * * @ingroup hx509_cert */ int hx509_query_match_cmp_func ( hx509_query */*q*/, int (*/*func*/)(hx509_context, hx509_cert, void *), void */*ctx*/); /** * Set the query controller to require an one specific EKU (extended * key usage). Any previous EKU matching is overwitten. If NULL is * passed in as the eku, the EKU requirement is reset. * * @param q a hx509 query controller. * @param eku an EKU to match on. * * @return An hx509 error code, see hx509_get_error_string(). * * @ingroup hx509_cert */ int hx509_query_match_eku ( hx509_query */*q*/, const heim_oid */*eku*/); int hx509_query_match_expr ( hx509_context /*context*/, hx509_query */*q*/, const char */*expr*/); /** * Set the query controller to match on a friendly name * * @param q a hx509 query controller. * @param name a friendly name to match on * * @return An hx509 error code, see hx509_get_error_string(). * * @ingroup hx509_cert */ int hx509_query_match_friendly_name ( hx509_query */*q*/, const char */*name*/); /** * Set the issuer and serial number of match in the query * controller. The function make copies of the isser and serial number. * * @param q a hx509 query controller * @param issuer issuer to search for * @param serialNumber the serialNumber of the issuer. * * @return An hx509 error code, see hx509_get_error_string(). * * @ingroup hx509_cert */ int hx509_query_match_issuer_serial ( hx509_query */*q*/, const Name */*issuer*/, const heim_integer */*serialNumber*/); /** * Set match options for the hx509 query controller. * * @param q query controller. * @param option options to control the query controller. * * @return An hx509 error code, see hx509_get_error_string(). * * @ingroup hx509_cert */ void hx509_query_match_option ( hx509_query */*q*/, hx509_query_option /*option*/); /** * Set a statistic file for the query statistics. * * @param context A hx509 context. * @param fn statistics file name * * @ingroup hx509_cert */ void hx509_query_statistic_file ( hx509_context /*context*/, const char */*fn*/); /** * Unparse the statistics file and print the result on a FILE descriptor. * * @param context A hx509 context. * @param printtype tyep to print * @param out the FILE to write the data on. * * @ingroup hx509_cert */ void hx509_query_unparse_stats ( hx509_context /*context*/, int /*printtype*/, FILE */*out*/); void hx509_request_free (hx509_request */*req*/); int hx509_request_get_SubjectPublicKeyInfo ( hx509_context /*context*/, hx509_request /*req*/, SubjectPublicKeyInfo */*key*/); int hx509_request_get_name ( hx509_context /*context*/, hx509_request /*req*/, hx509_name */*name*/); int hx509_request_init ( hx509_context /*context*/, hx509_request */*req*/); int hx509_request_set_SubjectPublicKeyInfo ( hx509_context /*context*/, hx509_request /*req*/, const SubjectPublicKeyInfo */*key*/); int hx509_request_set_name ( hx509_context /*context*/, hx509_request /*req*/, hx509_name /*name*/); /** * Add a CRL file to the revokation context. * * @param context hx509 context * @param ctx hx509 revokation context * @param path path to file that is going to be added to the context. * * @return An hx509 error code, see hx509_get_error_string(). * * @ingroup hx509_revoke */ int hx509_revoke_add_crl ( hx509_context /*context*/, hx509_revoke_ctx /*ctx*/, const char */*path*/); /** * Add a OCSP file to the revokation context. * * @param context hx509 context * @param ctx hx509 revokation context * @param path path to file that is going to be added to the context. * * @return An hx509 error code, see hx509_get_error_string(). * * @ingroup hx509_revoke */ int hx509_revoke_add_ocsp ( hx509_context /*context*/, hx509_revoke_ctx /*ctx*/, const char */*path*/); /** * Free a hx509 revokation context. * * @param ctx context to be freed * * @ingroup hx509_revoke */ void hx509_revoke_free (hx509_revoke_ctx */*ctx*/); /** * Allocate a revokation context. Free with hx509_revoke_free(). * * @param context A hx509 context. * @param ctx returns a newly allocated revokation context. * * @return An hx509 error code, see hx509_get_error_string(). * * @ingroup hx509_revoke */ int hx509_revoke_init ( hx509_context /*context*/, hx509_revoke_ctx */*ctx*/); /** * Print the OCSP reply stored in a file. * * @param context a hx509 context * @param path path to a file with a OCSP reply * @param out the out FILE descriptor to print the reply on * * @return An hx509 error code, see hx509_get_error_string(). * * @ingroup hx509_revoke */ int hx509_revoke_ocsp_print ( hx509_context /*context*/, const char */*path*/, FILE */*out*/); int hx509_revoke_print ( hx509_context /*context*/, hx509_revoke_ctx /*ctx*/, FILE */*out*/); /** * Check that a certificate is not expired according to a revokation * context. Also need the parent certificte to the check OCSP * parent identifier. * * @param context hx509 context * @param ctx hx509 revokation context * @param certs * @param now * @param cert * @param parent_cert * * @return An hx509 error code, see hx509_get_error_string(). * * @ingroup hx509_revoke */ int hx509_revoke_verify ( hx509_context /*context*/, hx509_revoke_ctx /*ctx*/, hx509_certs /*certs*/, time_t /*now*/, hx509_cert /*cert*/, hx509_cert /*parent_cert*/); /** * See hx509_set_error_stringv(). * * @param context A hx509 context. * @param flags * - HX509_ERROR_APPEND appends the error string to the old messages (code is updated). * @param code error code related to error message * @param fmt error message format * @param ... arguments to error message format * * @ingroup hx509_error */ void hx509_set_error_string ( hx509_context /*context*/, int /*flags*/, int /*code*/, const char */*fmt*/, ...); /** * Add an error message to the hx509 context. * * @param context A hx509 context. * @param flags * - HX509_ERROR_APPEND appends the error string to the old messages (code is updated). * @param code error code related to error message * @param fmt error message format * @param ap arguments to error message format * * @ingroup hx509_error */ void hx509_set_error_stringv ( hx509_context /*context*/, int /*flags*/, int /*code*/, const char */*fmt*/, va_list /*ap*/); const AlgorithmIdentifier * hx509_signature_ecPublicKey (void); const AlgorithmIdentifier * hx509_signature_ecdsa_with_sha256 (void); const AlgorithmIdentifier * hx509_signature_md5 (void); const AlgorithmIdentifier * hx509_signature_rsa (void); const AlgorithmIdentifier * hx509_signature_rsa_pkcs1_x509 (void); const AlgorithmIdentifier * hx509_signature_rsa_with_md5 (void); const AlgorithmIdentifier * hx509_signature_rsa_with_sha1 (void); const AlgorithmIdentifier * hx509_signature_rsa_with_sha256 (void); const AlgorithmIdentifier * hx509_signature_rsa_with_sha384 (void); const AlgorithmIdentifier * hx509_signature_rsa_with_sha512 (void); const AlgorithmIdentifier * hx509_signature_sha1 (void); const AlgorithmIdentifier * hx509_signature_sha256 (void); const AlgorithmIdentifier * hx509_signature_sha384 (void); const AlgorithmIdentifier * hx509_signature_sha512 (void); /** * Convert a DER encoded name info a string. * * @param data data to a DER/BER encoded name * @param length length of data * @param str the resulting string, is NULL on failure. * * @return An hx509 error code, see hx509_get_error_string(). * * @ingroup hx509_name */ int hx509_unparse_der_name ( const void */*data*/, size_t /*length*/, char **/*str*/); /** * Validate/Print the status of the certificate. * * @param context A hx509 context. * @param ctx A hx509 validation context. * @param cert the cerificate to validate/print. * @return An hx509 error code, see hx509_get_error_string(). * * @ingroup hx509_print */ int hx509_validate_cert ( hx509_context /*context*/, hx509_validate_ctx /*ctx*/, hx509_cert /*cert*/); /** * Add flags to control the behaivor of the hx509_validate_cert() * function. * * @param ctx A hx509 validation context. * @param flags flags to add to the validation context. * * @return An hx509 error code, see hx509_get_error_string(). * * @ingroup hx509_print */ void hx509_validate_ctx_add_flags ( hx509_validate_ctx /*ctx*/, int /*flags*/); /** * Free an hx509 validate context. * * @param ctx the hx509 validate context to free. * * @ingroup hx509_print */ void hx509_validate_ctx_free (hx509_validate_ctx /*ctx*/); /** * Allocate a hx509 validation/printing context. * * @param context A hx509 context. * @param ctx a new allocated hx509 validation context, free with * hx509_validate_ctx_free(). * @return An hx509 error code, see hx509_get_error_string(). * * @ingroup hx509_print */ int hx509_validate_ctx_init ( hx509_context /*context*/, hx509_validate_ctx */*ctx*/); /** * Set the printing functions for the validation context. * * @param ctx a hx509 valication context. * @param func the printing function to usea. * @param c the context variable to the printing function. * * @return An hx509 error code, see hx509_get_error_string(). * * @ingroup hx509_print */ void hx509_validate_ctx_set_print ( hx509_validate_ctx /*ctx*/, hx509_vprint_func /*func*/, void */*c*/); /** * Set the trust anchors in the verification context, makes an * reference to the keyset, so the consumer can free the keyset * independent of the destruction of the verification context (ctx). * If there already is a keyset attached, it's released. * * @param ctx a verification context * @param set a keyset containing the trust anchors. * * @ingroup hx509_verify */ void hx509_verify_attach_anchors ( hx509_verify_ctx /*ctx*/, hx509_certs /*set*/); /** * Attach an revocation context to the verfication context, , makes an * reference to the revoke context, so the consumer can free the * revoke context independent of the destruction of the verification * context. If there is no revoke context, the verification process is * NOT going to check any verification status. * * @param ctx a verification context. * @param revoke_ctx a revoke context. * * @ingroup hx509_verify */ void hx509_verify_attach_revoke ( hx509_verify_ctx /*ctx*/, hx509_revoke_ctx /*revoke_ctx*/); void hx509_verify_ctx_f_allow_best_before_signature_algs ( hx509_context /*ctx*/, int /*boolean*/); /** * Allow using the operating system builtin trust anchors if no other * trust anchors are configured. * * @param ctx a verification context * @param boolean if non zero, useing the operating systems builtin * trust anchors. * * * @return An hx509 error code, see hx509_get_error_string(). * * @ingroup hx509_cert */ void hx509_verify_ctx_f_allow_default_trustanchors ( hx509_verify_ctx /*ctx*/, int /*boolean*/); /** * Free an hx509 verification context. * * @param ctx the context to be freed. * * @ingroup hx509_verify */ void hx509_verify_destroy_ctx (hx509_verify_ctx /*ctx*/); /** * Verify that the certificate is allowed to be used for the hostname * and address. * * @param context A hx509 context. * @param cert the certificate to match with * @param flags Flags to modify the behavior: * - HX509_VHN_F_ALLOW_NO_MATCH no match is ok * @param type type of hostname: * - HX509_HN_HOSTNAME for plain hostname. * - HX509_HN_DNSSRV for DNS SRV names. * @param hostname the hostname to check * @param sa address of the host * @param sa_size length of address * * @return An hx509 error code, see hx509_get_error_string(). * * @ingroup hx509_cert */ int hx509_verify_hostname ( hx509_context /*context*/, const hx509_cert /*cert*/, int /*flags*/, hx509_hostname_type /*type*/, const char */*hostname*/, const struct sockaddr */*sa*/, int /*sa_size*/); /** * Allocate an verification context that is used fo control the * verification process. * * @param context A hx509 context. * @param ctx returns a pointer to a hx509_verify_ctx object. * * @return An hx509 error code, see hx509_get_error_string(). * * @ingroup hx509_verify */ int hx509_verify_init_ctx ( hx509_context /*context*/, hx509_verify_ctx */*ctx*/); /** * Build and verify the path for the certificate to the trust anchor * specified in the verify context. The path is constructed from the * certificate, the pool and the trust anchors. * * @param context A hx509 context. * @param ctx A hx509 verification context. * @param cert the certificate to build the path from. * @param pool A keyset of certificates to build the chain from. * * @return An hx509 error code, see hx509_get_error_string(). * * @ingroup hx509_verify */ int hx509_verify_path ( hx509_context /*context*/, hx509_verify_ctx /*ctx*/, hx509_cert /*cert*/, hx509_certs /*pool*/); /** * Set the maximum depth of the certificate chain that the path * builder is going to try. * * @param ctx a verification context * @param max_depth maxium depth of the certificate chain, include * trust anchor. * * @ingroup hx509_verify */ void hx509_verify_set_max_depth ( hx509_verify_ctx /*ctx*/, unsigned int /*max_depth*/); /** * Allow or deny the use of proxy certificates * * @param ctx a verification context * @param boolean if non zero, allow proxy certificates. * * @ingroup hx509_verify */ void hx509_verify_set_proxy_certificate ( hx509_verify_ctx /*ctx*/, int /*boolean*/); /** * Select strict RFC3280 verification of certificiates. This means * checking key usage on CA certificates, this will make version 1 * certificiates unuseable. * * @param ctx a verification context * @param boolean if non zero, use strict verification. * * @ingroup hx509_verify */ void hx509_verify_set_strict_rfc3280_verification ( hx509_verify_ctx /*ctx*/, int /*boolean*/); /** * Set the clock time the the verification process is going to * use. Used to check certificate in the past and future time. If not * set the current time will be used. * * @param ctx a verification context. * @param t the time the verifiation is using. * * * @ingroup hx509_verify */ void hx509_verify_set_time ( hx509_verify_ctx /*ctx*/, time_t /*t*/); /** * Verify a signature made using the private key of an certificate. * * @param context A hx509 context. * @param signer the certificate that made the signature. * @param alg algorthm that was used to sign the data. * @param data the data that was signed. * @param sig the sigature to verify. * * @return An hx509 error code, see hx509_get_error_string(). * * @ingroup hx509_crypto */ int hx509_verify_signature ( hx509_context /*context*/, const hx509_cert /*signer*/, const AlgorithmIdentifier */*alg*/, const heim_octet_string */*data*/, const heim_octet_string */*sig*/); /** * Free a data element allocated in the library. * * @param ptr data to be freed. * * @ingroup hx509_misc */ void hx509_xfree (void */*ptr*/); int yywrap (void); #ifdef __cplusplus } #endif #endif /* DOXY */ #endif /* __hx509_protos_h__ */ heimdal-7.5.0/lib/hx509/ks_p11.c0000644000175000017500000007052613026237312014150 0ustar niknik/* * Copyright (c) 2004 - 2008 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "hx_locl.h" #ifdef HAVE_DLFCN_H #include #endif #ifdef HAVE_DLOPEN #include "ref/pkcs11.h" struct p11_slot { int flags; #define P11_SESSION 1 #define P11_SESSION_IN_USE 2 #define P11_LOGIN_REQ 4 #define P11_LOGIN_DONE 8 #define P11_TOKEN_PRESENT 16 CK_SESSION_HANDLE session; CK_SLOT_ID id; CK_BBOOL token; char *name; hx509_certs certs; char *pin; struct { CK_MECHANISM_TYPE_PTR list; CK_ULONG num; CK_MECHANISM_INFO_PTR *infos; } mechs; }; struct p11_module { void *dl_handle; CK_FUNCTION_LIST_PTR funcs; CK_ULONG num_slots; unsigned int ref; unsigned int selected_slot; struct p11_slot *slot; }; #define P11FUNC(module,f,args) (*(module)->funcs->C_##f)args static int p11_get_session(hx509_context, struct p11_module *, struct p11_slot *, hx509_lock, CK_SESSION_HANDLE *); static int p11_put_session(struct p11_module *, struct p11_slot *, CK_SESSION_HANDLE); static void p11_release_module(struct p11_module *); static int p11_list_keys(hx509_context, struct p11_module *, struct p11_slot *, CK_SESSION_HANDLE, hx509_lock, hx509_certs *); /* * */ struct p11_rsa { struct p11_module *p; struct p11_slot *slot; CK_OBJECT_HANDLE private_key; CK_OBJECT_HANDLE public_key; }; static int p11_rsa_public_encrypt(int flen, const unsigned char *from, unsigned char *to, RSA *rsa, int padding) { return -1; } static int p11_rsa_public_decrypt(int flen, const unsigned char *from, unsigned char *to, RSA *rsa, int padding) { return -1; } static int p11_rsa_private_encrypt(int flen, const unsigned char *from, unsigned char *to, RSA *rsa, int padding) { struct p11_rsa *p11rsa = RSA_get_app_data(rsa); CK_OBJECT_HANDLE key = p11rsa->private_key; CK_SESSION_HANDLE session; CK_MECHANISM mechanism; CK_ULONG ck_sigsize; int ret; if (padding != RSA_PKCS1_PADDING) return -1; memset(&mechanism, 0, sizeof(mechanism)); mechanism.mechanism = CKM_RSA_PKCS; ck_sigsize = RSA_size(rsa); ret = p11_get_session(NULL, p11rsa->p, p11rsa->slot, NULL, &session); if (ret) return -1; ret = P11FUNC(p11rsa->p, SignInit, (session, &mechanism, key)); if (ret != CKR_OK) { p11_put_session(p11rsa->p, p11rsa->slot, session); return -1; } ret = P11FUNC(p11rsa->p, Sign, (session, (CK_BYTE *)(intptr_t)from, flen, to, &ck_sigsize)); p11_put_session(p11rsa->p, p11rsa->slot, session); if (ret != CKR_OK) return -1; return ck_sigsize; } static int p11_rsa_private_decrypt(int flen, const unsigned char *from, unsigned char *to, RSA * rsa, int padding) { struct p11_rsa *p11rsa = RSA_get_app_data(rsa); CK_OBJECT_HANDLE key = p11rsa->private_key; CK_SESSION_HANDLE session; CK_MECHANISM mechanism; CK_ULONG ck_sigsize; int ret; if (padding != RSA_PKCS1_PADDING) return -1; memset(&mechanism, 0, sizeof(mechanism)); mechanism.mechanism = CKM_RSA_PKCS; ck_sigsize = RSA_size(rsa); ret = p11_get_session(NULL, p11rsa->p, p11rsa->slot, NULL, &session); if (ret) return -1; ret = P11FUNC(p11rsa->p, DecryptInit, (session, &mechanism, key)); if (ret != CKR_OK) { p11_put_session(p11rsa->p, p11rsa->slot, session); return -1; } ret = P11FUNC(p11rsa->p, Decrypt, (session, (CK_BYTE *)(intptr_t)from, flen, to, &ck_sigsize)); p11_put_session(p11rsa->p, p11rsa->slot, session); if (ret != CKR_OK) return -1; return ck_sigsize; } static int p11_rsa_init(RSA *rsa) { return 1; } static int p11_rsa_finish(RSA *rsa) { struct p11_rsa *p11rsa = RSA_get_app_data(rsa); p11_release_module(p11rsa->p); free(p11rsa); return 1; } static const RSA_METHOD p11_rsa_pkcs1_method = { "hx509 PKCS11 PKCS#1 RSA", p11_rsa_public_encrypt, p11_rsa_public_decrypt, p11_rsa_private_encrypt, p11_rsa_private_decrypt, NULL, NULL, p11_rsa_init, p11_rsa_finish, 0, NULL, NULL, NULL, NULL }; /* * */ static int p11_mech_info(hx509_context context, struct p11_module *p, struct p11_slot *slot, int num) { CK_ULONG i; int ret; ret = P11FUNC(p, GetMechanismList, (slot->id, NULL_PTR, &i)); if (ret) { hx509_set_error_string(context, 0, HX509_PKCS11_NO_MECH, "Failed to get mech list count for slot %d", num); return HX509_PKCS11_NO_MECH; } if (i == 0) { hx509_set_error_string(context, 0, HX509_PKCS11_NO_MECH, "no mech supported for slot %d", num); return HX509_PKCS11_NO_MECH; } slot->mechs.list = calloc(i, sizeof(slot->mechs.list[0])); if (slot->mechs.list == NULL) { hx509_set_error_string(context, 0, ENOMEM, "out of memory"); return ENOMEM; } slot->mechs.num = i; ret = P11FUNC(p, GetMechanismList, (slot->id, slot->mechs.list, &i)); if (ret) { hx509_set_error_string(context, 0, HX509_PKCS11_NO_MECH, "Failed to get mech list for slot %d", num); return HX509_PKCS11_NO_MECH; } assert(i == slot->mechs.num); slot->mechs.infos = calloc(i, sizeof(*slot->mechs.infos)); if (slot->mechs.list == NULL) { hx509_set_error_string(context, 0, ENOMEM, "out of memory"); return ENOMEM; } for (i = 0; i < slot->mechs.num; i++) { slot->mechs.infos[i] = calloc(1, sizeof(*(slot->mechs.infos[0]))); if (slot->mechs.infos[i] == NULL) { hx509_set_error_string(context, 0, ENOMEM, "out of memory"); return ENOMEM; } ret = P11FUNC(p, GetMechanismInfo, (slot->id, slot->mechs.list[i], slot->mechs.infos[i])); if (ret) { hx509_set_error_string(context, 0, HX509_PKCS11_NO_MECH, "Failed to get mech info for slot %d", num); return HX509_PKCS11_NO_MECH; } } return 0; } static int p11_init_slot(hx509_context context, struct p11_module *p, hx509_lock lock, CK_SLOT_ID id, int num, struct p11_slot *slot) { CK_SESSION_HANDLE session; CK_SLOT_INFO slot_info; CK_TOKEN_INFO token_info; size_t i; int ret; slot->certs = NULL; slot->id = id; ret = P11FUNC(p, GetSlotInfo, (slot->id, &slot_info)); if (ret) { hx509_set_error_string(context, 0, HX509_PKCS11_TOKEN_CONFUSED, "Failed to init PKCS11 slot %d", num); return HX509_PKCS11_TOKEN_CONFUSED; } for (i = sizeof(slot_info.slotDescription) - 1; i > 0; i--) { char c = slot_info.slotDescription[i]; if (c == ' ' || c == '\t' || c == '\n' || c == '\r' || c == '\0') continue; i++; break; } ret = asprintf(&slot->name, "%.*s", (int)i, slot_info.slotDescription); if (ret == -1) return ENOMEM; if ((slot_info.flags & CKF_TOKEN_PRESENT) == 0) return 0; ret = P11FUNC(p, GetTokenInfo, (slot->id, &token_info)); if (ret) { hx509_set_error_string(context, 0, HX509_PKCS11_NO_TOKEN, "Failed to init PKCS11 slot %d " "with error 0x%08x", num, ret); return HX509_PKCS11_NO_TOKEN; } slot->flags |= P11_TOKEN_PRESENT; if (token_info.flags & CKF_LOGIN_REQUIRED) slot->flags |= P11_LOGIN_REQ; ret = p11_get_session(context, p, slot, lock, &session); if (ret) return ret; ret = p11_mech_info(context, p, slot, num); if (ret) goto out; ret = p11_list_keys(context, p, slot, session, lock, &slot->certs); out: p11_put_session(p, slot, session); return ret; } static int p11_get_session(hx509_context context, struct p11_module *p, struct p11_slot *slot, hx509_lock lock, CK_SESSION_HANDLE *psession) { CK_RV ret; if (slot->flags & P11_SESSION_IN_USE) _hx509_abort("slot already in session"); if (slot->flags & P11_SESSION) { slot->flags |= P11_SESSION_IN_USE; *psession = slot->session; return 0; } ret = P11FUNC(p, OpenSession, (slot->id, CKF_SERIAL_SESSION, NULL, NULL, &slot->session)); if (ret != CKR_OK) { if (context) hx509_set_error_string(context, 0, HX509_PKCS11_OPEN_SESSION, "Failed to OpenSession for slot id %d " "with error: 0x%08x", (int)slot->id, ret); return HX509_PKCS11_OPEN_SESSION; } slot->flags |= P11_SESSION; /* * If we have have to login, and haven't tried before and have a * prompter or known to work pin code. * * This code is very conversative and only uses the prompter in * the hx509_lock, the reason is that it's bad to try many * passwords on a pkcs11 token, it might lock up and have to be * unlocked by a administrator. * * XXX try harder to not use pin several times on the same card. */ if ( (slot->flags & P11_LOGIN_REQ) && (slot->flags & P11_LOGIN_DONE) == 0 && (lock || slot->pin)) { hx509_prompt prompt; char pin[20]; char *str; if (slot->pin == NULL) { memset(&prompt, 0, sizeof(prompt)); ret = asprintf(&str, "PIN code for %s: ", slot->name); if (ret == -1 || str == NULL) { if (context) hx509_set_error_string(context, 0, ENOMEM, "out of memory"); return ENOMEM; } prompt.prompt = str; prompt.type = HX509_PROMPT_TYPE_PASSWORD; prompt.reply.data = pin; prompt.reply.length = sizeof(pin); ret = hx509_lock_prompt(lock, &prompt); if (ret) { free(str); if (context) hx509_set_error_string(context, 0, ret, "Failed to get pin code for slot " "id %d with error: %d", (int)slot->id, ret); return ret; } free(str); } else { strlcpy(pin, slot->pin, sizeof(pin)); } ret = P11FUNC(p, Login, (slot->session, CKU_USER, (unsigned char*)pin, strlen(pin))); if (ret != CKR_OK) { if (context) hx509_set_error_string(context, 0, HX509_PKCS11_LOGIN, "Failed to login on slot id %d " "with error: 0x%08x", (int)slot->id, ret); switch(ret) { case CKR_PIN_LOCKED: return HX509_PKCS11_PIN_LOCKED; case CKR_PIN_EXPIRED: return HX509_PKCS11_PIN_EXPIRED; case CKR_PIN_INCORRECT: return HX509_PKCS11_PIN_INCORRECT; case CKR_USER_PIN_NOT_INITIALIZED: return HX509_PKCS11_PIN_NOT_INITIALIZED; default: return HX509_PKCS11_LOGIN; } } else slot->flags |= P11_LOGIN_DONE; if (slot->pin == NULL) { slot->pin = strdup(pin); if (slot->pin == NULL) { if (context) hx509_set_error_string(context, 0, ENOMEM, "out of memory"); return ENOMEM; } } } else slot->flags |= P11_LOGIN_DONE; slot->flags |= P11_SESSION_IN_USE; *psession = slot->session; return 0; } static int p11_put_session(struct p11_module *p, struct p11_slot *slot, CK_SESSION_HANDLE session) { if ((slot->flags & P11_SESSION_IN_USE) == 0) _hx509_abort("slot not in session"); slot->flags &= ~P11_SESSION_IN_USE; return 0; } static int iterate_entries(hx509_context context, struct p11_module *p, struct p11_slot *slot, CK_SESSION_HANDLE session, CK_ATTRIBUTE *search_data, int num_search_data, CK_ATTRIBUTE *query, int num_query, int (*func)(hx509_context, struct p11_module *, struct p11_slot *, CK_SESSION_HANDLE session, CK_OBJECT_HANDLE object, void *, CK_ATTRIBUTE *, int), void *ptr) { CK_OBJECT_HANDLE object; CK_ULONG object_count; int ret, ret2, i; ret = P11FUNC(p, FindObjectsInit, (session, search_data, num_search_data)); if (ret != CKR_OK) { return -1; } while (1) { ret = P11FUNC(p, FindObjects, (session, &object, 1, &object_count)); if (ret != CKR_OK) { return -1; } if (object_count == 0) break; for (i = 0; i < num_query; i++) query[i].pValue = NULL; ret = P11FUNC(p, GetAttributeValue, (session, object, query, num_query)); if (ret != CKR_OK) { return -1; } for (i = 0; i < num_query; i++) { query[i].pValue = malloc(query[i].ulValueLen); if (query[i].pValue == NULL) { ret = ENOMEM; goto out; } } ret = P11FUNC(p, GetAttributeValue, (session, object, query, num_query)); if (ret != CKR_OK) { ret = -1; goto out; } ret = (*func)(context, p, slot, session, object, ptr, query, num_query); if (ret) goto out; for (i = 0; i < num_query; i++) { if (query[i].pValue) free(query[i].pValue); query[i].pValue = NULL; } } out: for (i = 0; i < num_query; i++) { if (query[i].pValue) free(query[i].pValue); query[i].pValue = NULL; } ret2 = P11FUNC(p, FindObjectsFinal, (session)); if (ret2 != CKR_OK) { return ret2; } return ret; } static BIGNUM * getattr_bn(struct p11_module *p, struct p11_slot *slot, CK_SESSION_HANDLE session, CK_OBJECT_HANDLE object, unsigned int type) { CK_ATTRIBUTE query; BIGNUM *bn; int ret; query.type = type; query.pValue = NULL; query.ulValueLen = 0; ret = P11FUNC(p, GetAttributeValue, (session, object, &query, 1)); if (ret != CKR_OK) return NULL; query.pValue = malloc(query.ulValueLen); ret = P11FUNC(p, GetAttributeValue, (session, object, &query, 1)); if (ret != CKR_OK) { free(query.pValue); return NULL; } bn = BN_bin2bn(query.pValue, query.ulValueLen, NULL); free(query.pValue); return bn; } static int collect_private_key(hx509_context context, struct p11_module *p, struct p11_slot *slot, CK_SESSION_HANDLE session, CK_OBJECT_HANDLE object, void *ptr, CK_ATTRIBUTE *query, int num_query) { struct hx509_collector *collector = ptr; hx509_private_key key; heim_octet_string localKeyId; int ret; RSA *rsa; struct p11_rsa *p11rsa; localKeyId.data = query[0].pValue; localKeyId.length = query[0].ulValueLen; ret = hx509_private_key_init(&key, NULL, NULL); if (ret) return ret; rsa = RSA_new(); if (rsa == NULL) _hx509_abort("out of memory"); /* * The exponent and modulus should always be present according to * the pkcs11 specification, but some smartcards leaves it out, * let ignore any failure to fetch it. */ rsa->n = getattr_bn(p, slot, session, object, CKA_MODULUS); rsa->e = getattr_bn(p, slot, session, object, CKA_PUBLIC_EXPONENT); p11rsa = calloc(1, sizeof(*p11rsa)); if (p11rsa == NULL) _hx509_abort("out of memory"); p11rsa->p = p; p11rsa->slot = slot; p11rsa->private_key = object; if (p->ref == 0) _hx509_abort("pkcs11 ref == 0 on alloc"); p->ref++; if (p->ref == UINT_MAX) _hx509_abort("pkcs11 ref == UINT_MAX on alloc"); RSA_set_method(rsa, &p11_rsa_pkcs1_method); ret = RSA_set_app_data(rsa, p11rsa); if (ret != 1) _hx509_abort("RSA_set_app_data"); hx509_private_key_assign_rsa(key, rsa); ret = _hx509_collector_private_key_add(context, collector, hx509_signature_rsa(), key, NULL, &localKeyId); if (ret) { hx509_private_key_free(&key); return ret; } return 0; } static void p11_cert_release(hx509_cert cert, void *ctx) { struct p11_module *p = ctx; p11_release_module(p); } static int collect_cert(hx509_context context, struct p11_module *p, struct p11_slot *slot, CK_SESSION_HANDLE session, CK_OBJECT_HANDLE object, void *ptr, CK_ATTRIBUTE *query, int num_query) { struct hx509_collector *collector = ptr; heim_error_t error = NULL; hx509_cert cert; int ret; if ((CK_LONG)query[0].ulValueLen == -1 || (CK_LONG)query[1].ulValueLen == -1) { return 0; } cert = hx509_cert_init_data(context, query[1].pValue, query[1].ulValueLen, &error); if (cert == NULL) { ret = heim_error_get_code(error); heim_release(error); return ret; } if (p->ref == 0) _hx509_abort("pkcs11 ref == 0 on alloc"); p->ref++; if (p->ref == UINT_MAX) _hx509_abort("pkcs11 ref to high"); _hx509_cert_set_release(cert, p11_cert_release, p); { heim_octet_string data; data.data = query[0].pValue; data.length = query[0].ulValueLen; _hx509_set_cert_attribute(context, cert, &asn1_oid_id_pkcs_9_at_localKeyId, &data); } if ((CK_LONG)query[2].ulValueLen != -1) { char *str; ret = asprintf(&str, "%.*s", (int)query[2].ulValueLen, (char *)query[2].pValue); if (ret != -1 && str) { hx509_cert_set_friendly_name(cert, str); free(str); } } ret = _hx509_collector_certs_add(context, collector, cert); hx509_cert_free(cert); return ret; } static int p11_list_keys(hx509_context context, struct p11_module *p, struct p11_slot *slot, CK_SESSION_HANDLE session, hx509_lock lock, hx509_certs *certs) { struct hx509_collector *collector; CK_OBJECT_CLASS key_class; CK_ATTRIBUTE search_data[] = { {CKA_CLASS, NULL, 0}, }; CK_ATTRIBUTE query_data[3] = { {CKA_ID, NULL, 0}, {CKA_VALUE, NULL, 0}, {CKA_LABEL, NULL, 0} }; int ret; search_data[0].pValue = &key_class; search_data[0].ulValueLen = sizeof(key_class); if (lock == NULL) lock = _hx509_empty_lock; ret = _hx509_collector_alloc(context, lock, &collector); if (ret) return ret; key_class = CKO_PRIVATE_KEY; ret = iterate_entries(context, p, slot, session, search_data, 1, query_data, 1, collect_private_key, collector); if (ret) goto out; key_class = CKO_CERTIFICATE; ret = iterate_entries(context, p, slot, session, search_data, 1, query_data, 3, collect_cert, collector); if (ret) goto out; ret = _hx509_collector_collect_certs(context, collector, &slot->certs); out: _hx509_collector_free(collector); return ret; } static int p11_init(hx509_context context, hx509_certs certs, void **data, int flags, const char *residue, hx509_lock lock) { CK_C_GetFunctionList getFuncs; struct p11_module *p; char *list, *str; int ret; *data = NULL; list = strdup(residue); if (list == NULL) return ENOMEM; p = calloc(1, sizeof(*p)); if (p == NULL) { free(list); return ENOMEM; } p->ref = 1; p->selected_slot = 0; str = strchr(list, ','); if (str) *str++ = '\0'; while (str) { char *strnext; strnext = strchr(str, ','); if (strnext) *strnext++ = '\0'; if (strncasecmp(str, "slot=", 5) == 0) p->selected_slot = atoi(str + 5); str = strnext; } p->dl_handle = dlopen(list, RTLD_NOW); if (p->dl_handle == NULL) { ret = HX509_PKCS11_LOAD; hx509_set_error_string(context, 0, ret, "Failed to open %s: %s", list, dlerror()); goto out; } getFuncs = (CK_C_GetFunctionList) dlsym(p->dl_handle, "C_GetFunctionList"); if (getFuncs == NULL) { ret = HX509_PKCS11_LOAD; hx509_set_error_string(context, 0, ret, "C_GetFunctionList missing in %s: %s", list, dlerror()); goto out; } ret = (*getFuncs)(&p->funcs); if (ret) { ret = HX509_PKCS11_LOAD; hx509_set_error_string(context, 0, ret, "C_GetFunctionList failed in %s", list); goto out; } ret = P11FUNC(p, Initialize, (NULL_PTR)); if (ret != CKR_OK) { ret = HX509_PKCS11_TOKEN_CONFUSED; hx509_set_error_string(context, 0, ret, "Failed initialize the PKCS11 module"); goto out; } ret = P11FUNC(p, GetSlotList, (FALSE, NULL, &p->num_slots)); if (ret) { ret = HX509_PKCS11_TOKEN_CONFUSED; hx509_set_error_string(context, 0, ret, "Failed to get number of PKCS11 slots"); goto out; } if (p->num_slots == 0) { ret = HX509_PKCS11_NO_SLOT; hx509_set_error_string(context, 0, ret, "Selected PKCS11 module have no slots"); goto out; } { CK_SLOT_ID_PTR slot_ids; int num_tokens = 0; size_t i; slot_ids = malloc(p->num_slots * sizeof(*slot_ids)); if (slot_ids == NULL) { hx509_clear_error_string(context); ret = ENOMEM; goto out; } ret = P11FUNC(p, GetSlotList, (FALSE, slot_ids, &p->num_slots)); if (ret) { free(slot_ids); hx509_set_error_string(context, 0, HX509_PKCS11_TOKEN_CONFUSED, "Failed getting slot-list from " "PKCS11 module"); ret = HX509_PKCS11_TOKEN_CONFUSED; goto out; } p->slot = calloc(p->num_slots, sizeof(p->slot[0])); if (p->slot == NULL) { free(slot_ids); hx509_set_error_string(context, 0, ENOMEM, "Failed to get memory for slot-list"); ret = ENOMEM; goto out; } for (i = 0; i < p->num_slots; i++) { if ((p->selected_slot != 0) && (slot_ids[i] != (p->selected_slot - 1))) continue; ret = p11_init_slot(context, p, lock, slot_ids[i], i, &p->slot[i]); if (!ret) { if (p->slot[i].flags & P11_TOKEN_PRESENT) num_tokens++; } } free(slot_ids); if (ret) goto out; if (num_tokens == 0) { ret = HX509_PKCS11_NO_TOKEN; goto out; } } free(list); *data = p; return 0; out: if (list) free(list); p11_release_module(p); return ret; } static void p11_release_module(struct p11_module *p) { size_t i; if (p->ref == 0) _hx509_abort("pkcs11 ref to low"); if (--p->ref > 0) return; for (i = 0; i < p->num_slots; i++) { if (p->slot[i].flags & P11_SESSION_IN_USE) _hx509_abort("pkcs11 module release while session in use"); if (p->slot[i].flags & P11_SESSION) { P11FUNC(p, CloseSession, (p->slot[i].session)); } if (p->slot[i].name) free(p->slot[i].name); if (p->slot[i].pin) { memset(p->slot[i].pin, 0, strlen(p->slot[i].pin)); free(p->slot[i].pin); } if (p->slot[i].mechs.num) { free(p->slot[i].mechs.list); if (p->slot[i].mechs.infos) { size_t j; for (j = 0 ; j < p->slot[i].mechs.num ; j++) free(p->slot[i].mechs.infos[j]); free(p->slot[i].mechs.infos); } } } free(p->slot); if (p->funcs) P11FUNC(p, Finalize, (NULL)); if (p->dl_handle) dlclose(p->dl_handle); memset(p, 0, sizeof(*p)); free(p); } static int p11_free(hx509_certs certs, void *data) { struct p11_module *p = data; size_t i; for (i = 0; i < p->num_slots; i++) { if (p->slot[i].certs) hx509_certs_free(&p->slot[i].certs); } p11_release_module(p); return 0; } struct p11_cursor { hx509_certs certs; void *cursor; }; static int p11_iter_start(hx509_context context, hx509_certs certs, void *data, void **cursor) { struct p11_module *p = data; struct p11_cursor *c; int ret; size_t i; c = malloc(sizeof(*c)); if (c == NULL) { hx509_clear_error_string(context); return ENOMEM; } ret = hx509_certs_init(context, "MEMORY:pkcs11-iter", 0, NULL, &c->certs); if (ret) { free(c); return ret; } for (i = 0 ; i < p->num_slots; i++) { if (p->slot[i].certs == NULL) continue; ret = hx509_certs_merge(context, c->certs, p->slot[i].certs); if (ret) { hx509_certs_free(&c->certs); free(c); return ret; } } ret = hx509_certs_start_seq(context, c->certs, &c->cursor); if (ret) { hx509_certs_free(&c->certs); free(c); return 0; } *cursor = c; return 0; } static int p11_iter(hx509_context context, hx509_certs certs, void *data, void *cursor, hx509_cert *cert) { struct p11_cursor *c = cursor; return hx509_certs_next_cert(context, c->certs, c->cursor, cert); } static int p11_iter_end(hx509_context context, hx509_certs certs, void *data, void *cursor) { struct p11_cursor *c = cursor; int ret; ret = hx509_certs_end_seq(context, c->certs, c->cursor); hx509_certs_free(&c->certs); free(c); return ret; } #define MECHFLAG(x) { "unknown-flag-" #x, x } static struct units mechflags[] = { MECHFLAG(0x80000000), MECHFLAG(0x40000000), MECHFLAG(0x20000000), MECHFLAG(0x10000000), MECHFLAG(0x08000000), MECHFLAG(0x04000000), {"ec-compress", 0x2000000 }, {"ec-uncompress", 0x1000000 }, {"ec-namedcurve", 0x0800000 }, {"ec-ecparameters", 0x0400000 }, {"ec-f-2m", 0x0200000 }, {"ec-f-p", 0x0100000 }, {"derive", 0x0080000 }, {"unwrap", 0x0040000 }, {"wrap", 0x0020000 }, {"genereate-key-pair", 0x0010000 }, {"generate", 0x0008000 }, {"verify-recover", 0x0004000 }, {"verify", 0x0002000 }, {"sign-recover", 0x0001000 }, {"sign", 0x0000800 }, {"digest", 0x0000400 }, {"decrypt", 0x0000200 }, {"encrypt", 0x0000100 }, MECHFLAG(0x00080), MECHFLAG(0x00040), MECHFLAG(0x00020), MECHFLAG(0x00010), MECHFLAG(0x00008), MECHFLAG(0x00004), MECHFLAG(0x00002), {"hw", 0x0000001 }, { NULL, 0x0000000 } }; #undef MECHFLAG static int p11_printinfo(hx509_context context, hx509_certs certs, void *data, int (*func)(void *, const char *), void *ctx) { struct p11_module *p = data; size_t i, j; _hx509_pi_printf(func, ctx, "pkcs11 driver with %d slot%s", p->num_slots, p->num_slots > 1 ? "s" : ""); for (i = 0; i < p->num_slots; i++) { struct p11_slot *s = &p->slot[i]; _hx509_pi_printf(func, ctx, "slot %d: id: %d name: %s flags: %08x", i, (int)s->id, s->name, s->flags); _hx509_pi_printf(func, ctx, "number of supported mechanisms: %lu", (unsigned long)s->mechs.num); for (j = 0; j < s->mechs.num; j++) { const char *mechname = "unknown"; char flags[256], unknownname[40]; #define MECHNAME(s,n) case s: mechname = n; break switch(s->mechs.list[j]) { MECHNAME(CKM_RSA_PKCS_KEY_PAIR_GEN, "rsa-pkcs-key-pair-gen"); MECHNAME(CKM_RSA_PKCS, "rsa-pkcs"); MECHNAME(CKM_RSA_X_509, "rsa-x-509"); MECHNAME(CKM_MD5_RSA_PKCS, "md5-rsa-pkcs"); MECHNAME(CKM_SHA1_RSA_PKCS, "sha1-rsa-pkcs"); MECHNAME(CKM_SHA256_RSA_PKCS, "sha256-rsa-pkcs"); MECHNAME(CKM_SHA384_RSA_PKCS, "sha384-rsa-pkcs"); MECHNAME(CKM_SHA512_RSA_PKCS, "sha512-rsa-pkcs"); MECHNAME(CKM_RIPEMD160_RSA_PKCS, "ripemd160-rsa-pkcs"); MECHNAME(CKM_RSA_PKCS_OAEP, "rsa-pkcs-oaep"); MECHNAME(CKM_SHA512_HMAC, "sha512-hmac"); MECHNAME(CKM_SHA512, "sha512"); MECHNAME(CKM_SHA384_HMAC, "sha384-hmac"); MECHNAME(CKM_SHA384, "sha384"); MECHNAME(CKM_SHA256_HMAC, "sha256-hmac"); MECHNAME(CKM_SHA256, "sha256"); MECHNAME(CKM_SHA_1, "sha1"); MECHNAME(CKM_MD5, "md5"); MECHNAME(CKM_RIPEMD160, "ripemd-160"); MECHNAME(CKM_DES_ECB, "des-ecb"); MECHNAME(CKM_DES_CBC, "des-cbc"); MECHNAME(CKM_AES_ECB, "aes-ecb"); MECHNAME(CKM_AES_CBC, "aes-cbc"); MECHNAME(CKM_DH_PKCS_PARAMETER_GEN, "dh-pkcs-parameter-gen"); default: snprintf(unknownname, sizeof(unknownname), "unknown-mech-%lu", (unsigned long)s->mechs.list[j]); mechname = unknownname; break; } #undef MECHNAME unparse_flags(s->mechs.infos[j]->flags, mechflags, flags, sizeof(flags)); _hx509_pi_printf(func, ctx, " %s: %s", mechname, flags); } } return 0; } static struct hx509_keyset_ops keyset_pkcs11 = { "PKCS11", 0, p11_init, NULL, p11_free, NULL, NULL, p11_iter_start, p11_iter, p11_iter_end, p11_printinfo, NULL, NULL }; #endif /* HAVE_DLOPEN */ void _hx509_ks_pkcs11_register(hx509_context context) { #ifdef HAVE_DLOPEN _hx509_ks_register(context, &keyset_pkcs11); #endif } heimdal-7.5.0/lib/hx509/ks_keychain.c0000644000175000017500000003215013026237312015331 0ustar niknik/* * Copyright (c) 2007 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "hx_locl.h" #ifdef HAVE_FRAMEWORK_SECURITY #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wdeprecated-declarations" #include /* Missing function decls in pre Leopard */ #ifdef NEED_SECKEYGETCSPHANDLE_PROTO OSStatus SecKeyGetCSPHandle(SecKeyRef, CSSM_CSP_HANDLE *); OSStatus SecKeyGetCredentials(SecKeyRef, CSSM_ACL_AUTHORIZATION_TAG, int, const CSSM_ACCESS_CREDENTIALS **); #define kSecCredentialTypeDefault 0 #define CSSM_SIZE uint32_t #endif static int getAttribute(SecKeychainItemRef itemRef, SecItemAttr item, SecKeychainAttributeList **attrs) { SecKeychainAttributeInfo attrInfo; UInt32 attrFormat = 0; OSStatus ret; *attrs = NULL; attrInfo.count = 1; attrInfo.tag = &item; attrInfo.format = &attrFormat; ret = SecKeychainItemCopyAttributesAndData(itemRef, &attrInfo, NULL, attrs, NULL, NULL); if (ret) return EINVAL; return 0; } /* * */ struct kc_rsa { SecKeychainItemRef item; size_t keysize; }; static int kc_rsa_public_encrypt(int flen, const unsigned char *from, unsigned char *to, RSA *rsa, int padding) { return -1; } static int kc_rsa_public_decrypt(int flen, const unsigned char *from, unsigned char *to, RSA *rsa, int padding) { return -1; } static int kc_rsa_private_encrypt(int flen, const unsigned char *from, unsigned char *to, RSA *rsa, int padding) { struct kc_rsa *kc = RSA_get_app_data(rsa); CSSM_RETURN cret; OSStatus ret; const CSSM_ACCESS_CREDENTIALS *creds; SecKeyRef privKeyRef = (SecKeyRef)kc->item; CSSM_CSP_HANDLE cspHandle; const CSSM_KEY *cssmKey; CSSM_CC_HANDLE sigHandle = 0; CSSM_DATA sig, in; int fret = 0; if (padding != RSA_PKCS1_PADDING) return -1; cret = SecKeyGetCSSMKey(privKeyRef, &cssmKey); if(cret) abort(); cret = SecKeyGetCSPHandle(privKeyRef, &cspHandle); if(cret) abort(); ret = SecKeyGetCredentials(privKeyRef, CSSM_ACL_AUTHORIZATION_SIGN, kSecCredentialTypeDefault, &creds); if(ret) abort(); ret = CSSM_CSP_CreateSignatureContext(cspHandle, CSSM_ALGID_RSA, creds, cssmKey, &sigHandle); if(ret) abort(); in.Data = (uint8 *)from; in.Length = flen; sig.Data = (uint8 *)to; sig.Length = kc->keysize; cret = CSSM_SignData(sigHandle, &in, 1, CSSM_ALGID_NONE, &sig); if(cret) { /* cssmErrorString(cret); */ fret = -1; } else fret = sig.Length; if(sigHandle) CSSM_DeleteContext(sigHandle); return fret; } static int kc_rsa_private_decrypt(int flen, const unsigned char *from, unsigned char *to, RSA * rsa, int padding) { struct kc_rsa *kc = RSA_get_app_data(rsa); CSSM_RETURN cret; OSStatus ret; const CSSM_ACCESS_CREDENTIALS *creds; SecKeyRef privKeyRef = (SecKeyRef)kc->item; CSSM_CSP_HANDLE cspHandle; const CSSM_KEY *cssmKey; CSSM_CC_HANDLE handle = 0; CSSM_DATA out, in, rem; int fret = 0; CSSM_SIZE outlen = 0; char remdata[1024]; if (padding != RSA_PKCS1_PADDING) return -1; cret = SecKeyGetCSSMKey(privKeyRef, &cssmKey); if(cret) abort(); cret = SecKeyGetCSPHandle(privKeyRef, &cspHandle); if(cret) abort(); ret = SecKeyGetCredentials(privKeyRef, CSSM_ACL_AUTHORIZATION_DECRYPT, kSecCredentialTypeDefault, &creds); if(ret) abort(); ret = CSSM_CSP_CreateAsymmetricContext (cspHandle, CSSM_ALGID_RSA, creds, cssmKey, CSSM_PADDING_PKCS1, &handle); if(ret) abort(); in.Data = (uint8 *)from; in.Length = flen; out.Data = (uint8 *)to; out.Length = kc->keysize; rem.Data = (uint8 *)remdata; rem.Length = sizeof(remdata); cret = CSSM_DecryptData(handle, &in, 1, &out, 1, &outlen, &rem); if(cret) { /* cssmErrorString(cret); */ fret = -1; } else fret = out.Length; if(handle) CSSM_DeleteContext(handle); return fret; } static int kc_rsa_init(RSA *rsa) { return 1; } static int kc_rsa_finish(RSA *rsa) { struct kc_rsa *kc_rsa = RSA_get_app_data(rsa); CFRelease(kc_rsa->item); memset(kc_rsa, 0, sizeof(*kc_rsa)); free(kc_rsa); return 1; } static const RSA_METHOD kc_rsa_pkcs1_method = { "hx509 Keychain PKCS#1 RSA", kc_rsa_public_encrypt, kc_rsa_public_decrypt, kc_rsa_private_encrypt, kc_rsa_private_decrypt, NULL, NULL, kc_rsa_init, kc_rsa_finish, 0, NULL, NULL, NULL, NULL }; static int set_private_key(hx509_context context, SecKeychainItemRef itemRef, hx509_cert cert) { struct kc_rsa *kc; hx509_private_key key; RSA *rsa; int ret; ret = hx509_private_key_init(&key, NULL, NULL); if (ret) return ret; kc = calloc(1, sizeof(*kc)); if (kc == NULL) _hx509_abort("out of memory"); kc->item = itemRef; rsa = RSA_new(); if (rsa == NULL) _hx509_abort("out of memory"); /* Argh, fake modulus since OpenSSL API is on crack */ { SecKeychainAttributeList *attrs = NULL; uint32_t size; void *data; rsa->n = BN_new(); if (rsa->n == NULL) abort(); ret = getAttribute(itemRef, kSecKeyKeySizeInBits, &attrs); if (ret) abort(); size = *(uint32_t *)attrs->attr[0].data; SecKeychainItemFreeAttributesAndData(attrs, NULL); kc->keysize = (size + 7) / 8; data = malloc(kc->keysize); memset(data, 0xe0, kc->keysize); BN_bin2bn(data, kc->keysize, rsa->n); free(data); } rsa->e = NULL; RSA_set_method(rsa, &kc_rsa_pkcs1_method); ret = RSA_set_app_data(rsa, kc); if (ret != 1) _hx509_abort("RSA_set_app_data"); hx509_private_key_assign_rsa(key, rsa); _hx509_cert_assign_key(cert, key); return 0; } /* * */ struct ks_keychain { int anchors; SecKeychainRef keychain; }; static int keychain_init(hx509_context context, hx509_certs certs, void **data, int flags, const char *residue, hx509_lock lock) { struct ks_keychain *ctx; ctx = calloc(1, sizeof(*ctx)); if (ctx == NULL) { hx509_clear_error_string(context); return ENOMEM; } if (residue) { if (strcasecmp(residue, "system-anchors") == 0) { ctx->anchors = 1; } else if (strncasecmp(residue, "FILE:", 5) == 0) { OSStatus ret; ret = SecKeychainOpen(residue + 5, &ctx->keychain); if (ret != noErr) { hx509_set_error_string(context, 0, ENOENT, "Failed to open %s", residue); free(ctx); return ENOENT; } } else { hx509_set_error_string(context, 0, ENOENT, "Unknown subtype %s", residue); free(ctx); return ENOENT; } } *data = ctx; return 0; } /* * */ static int keychain_free(hx509_certs certs, void *data) { struct ks_keychain *ctx = data; if (ctx->keychain) CFRelease(ctx->keychain); memset(ctx, 0, sizeof(*ctx)); free(ctx); return 0; } /* * */ struct iter { hx509_certs certs; void *cursor; SecKeychainSearchRef searchRef; }; static int keychain_iter_start(hx509_context context, hx509_certs certs, void *data, void **cursor) { struct ks_keychain *ctx = data; struct iter *iter; iter = calloc(1, sizeof(*iter)); if (iter == NULL) { hx509_set_error_string(context, 0, ENOMEM, "out of memory"); return ENOMEM; } if (ctx->anchors) { CFArrayRef anchors; int ret; int i; ret = hx509_certs_init(context, "MEMORY:ks-file-create", 0, NULL, &iter->certs); if (ret) { free(iter); return ret; } ret = SecTrustCopyAnchorCertificates(&anchors); if (ret != 0) { hx509_certs_free(&iter->certs); free(iter); hx509_set_error_string(context, 0, ENOMEM, "Can't get trust anchors from Keychain"); return ENOMEM; } for (i = 0; i < CFArrayGetCount(anchors); i++) { SecCertificateRef cr; hx509_cert cert; CSSM_DATA cssm; cr = (SecCertificateRef)CFArrayGetValueAtIndex(anchors, i); SecCertificateGetData(cr, &cssm); cert = hx509_cert_init_data(context, cssm.Data, cssm.Length, NULL); if (cert == NULL) continue; ret = hx509_certs_add(context, iter->certs, cert); hx509_cert_free(cert); } CFRelease(anchors); } if (iter->certs) { int ret; ret = hx509_certs_start_seq(context, iter->certs, &iter->cursor); if (ret) { hx509_certs_free(&iter->certs); free(iter); return ret; } } else { OSStatus ret; ret = SecKeychainSearchCreateFromAttributes(ctx->keychain, kSecCertificateItemClass, NULL, &iter->searchRef); if (ret) { free(iter); hx509_set_error_string(context, 0, ret, "Failed to start search for attributes"); return ENOMEM; } } *cursor = iter; return 0; } /* * */ static int keychain_iter(hx509_context context, hx509_certs certs, void *data, void *cursor, hx509_cert *cert) { SecKeychainAttributeList *attrs = NULL; SecKeychainAttributeInfo attrInfo; UInt32 attrFormat[1] = { 0 }; SecKeychainItemRef itemRef; SecItemAttr item[1]; heim_error_t error = NULL; struct iter *iter = cursor; OSStatus ret; UInt32 len; void *ptr = NULL; if (iter->certs) return hx509_certs_next_cert(context, iter->certs, iter->cursor, cert); *cert = NULL; ret = SecKeychainSearchCopyNext(iter->searchRef, &itemRef); if (ret == errSecItemNotFound) return 0; else if (ret != 0) return EINVAL; /* * Pick out certificate and matching "keyid" */ item[0] = kSecPublicKeyHashItemAttr; attrInfo.count = 1; attrInfo.tag = item; attrInfo.format = attrFormat; ret = SecKeychainItemCopyAttributesAndData(itemRef, &attrInfo, NULL, &attrs, &len, &ptr); if (ret) return EINVAL; *cert = hx509_cert_init_data(context, ptr, len, &error); if (*cert == NULL) { ret = heim_error_get_code(error); heim_release(error); goto out; } /* * Find related private key if there is one by looking at * kSecPublicKeyHashItemAttr == kSecKeyLabel */ { SecKeychainSearchRef search; SecKeychainAttribute attrKeyid; SecKeychainAttributeList attrList; attrKeyid.tag = kSecKeyLabel; attrKeyid.length = attrs->attr[0].length; attrKeyid.data = attrs->attr[0].data; attrList.count = 1; attrList.attr = &attrKeyid; ret = SecKeychainSearchCreateFromAttributes(NULL, CSSM_DL_DB_RECORD_PRIVATE_KEY, &attrList, &search); if (ret) { ret = 0; goto out; } ret = SecKeychainSearchCopyNext(search, &itemRef); CFRelease(search); if (ret == errSecItemNotFound) { ret = 0; goto out; } else if (ret) { ret = EINVAL; goto out; } set_private_key(context, itemRef, *cert); } out: SecKeychainItemFreeAttributesAndData(attrs, ptr); return ret; } /* * */ static int keychain_iter_end(hx509_context context, hx509_certs certs, void *data, void *cursor) { struct iter *iter = cursor; if (iter->certs) { hx509_certs_end_seq(context, iter->certs, iter->cursor); hx509_certs_free(&iter->certs); } else { CFRelease(iter->searchRef); } memset(iter, 0, sizeof(*iter)); free(iter); return 0; } /* * */ struct hx509_keyset_ops keyset_keychain = { "KEYCHAIN", 0, keychain_init, NULL, keychain_free, NULL, NULL, keychain_iter_start, keychain_iter, keychain_iter_end, NULL, NULL, NULL }; #pragma clang diagnostic pop #endif /* HAVE_FRAMEWORK_SECURITY */ /* * */ void _hx509_ks_keychain_register(hx509_context context) { #ifdef HAVE_FRAMEWORK_SECURITY _hx509_ks_register(context, &keyset_keychain); #endif } heimdal-7.5.0/lib/hdb/0000755000175000017500000000000013214604041012550 5ustar niknikheimdal-7.5.0/lib/hdb/hdb.schema0000644000175000017500000001022513026237312014473 0ustar niknik# Definitions for a Kerberos V KDC schema # # $Id$ # # This version is compatible with OpenLDAP 1.8 # # OID Base is iso(1) org(3) dod(6) internet(1) private(4) enterprise(1) padl(5322) kdcSchema(10) # # Syntaxes are under 1.3.6.1.4.1.5322.10.0 # Attributes types are under 1.3.6.1.4.1.5322.10.1 # Object classes are under 1.3.6.1.4.1.5322.10.2 # Syntax definitions #krb5KDCFlagsSyntax SYNTAX ::= { # WITH SYNTAX INTEGER #-- initial(0), -- require as-req #-- forwardable(1), -- may issue forwardable #-- proxiable(2), -- may issue proxiable #-- renewable(3), -- may issue renewable #-- postdate(4), -- may issue postdatable #-- server(5), -- may be server #-- client(6), -- may be client #-- invalid(7), -- entry is invalid #-- require-preauth(8), -- must use preauth #-- change-pw(9), -- change password service #-- require-hwauth(10), -- must use hwauth #-- ok-as-delegate(11), -- as in TicketFlags #-- user-to-user(12), -- may use user-to-user auth #-- immutable(13) -- may not be deleted # ID { 1.3.6.1.4.1.5322.10.0.1 } #} #krb5PrincipalNameSyntax SYNTAX ::= { # WITH SYNTAX OCTET STRING #-- String representations of distinguished names as per RFC1510 # ID { 1.3.6.1.4.1.5322.10.0.2 } #} # Attribute type definitions attributetype ( 1.3.6.1.4.1.5322.10.1.1 NAME 'krb5PrincipalName' DESC 'The unparsed Kerberos principal name' EQUALITY caseExactIA5Match SINGLE-VALUE SYNTAX 1.3.6.1.4.1.1466.115.121.1.26 ) attributetype ( 1.3.6.1.4.1.5322.10.1.2 NAME 'krb5KeyVersionNumber' EQUALITY integerMatch SINGLE-VALUE SYNTAX 1.3.6.1.4.1.1466.115.121.1.27 ) attributetype ( 1.3.6.1.4.1.5322.10.1.3 NAME 'krb5MaxLife' EQUALITY integerMatch SINGLE-VALUE SYNTAX 1.3.6.1.4.1.1466.115.121.1.27 ) attributetype ( 1.3.6.1.4.1.5322.10.1.4 NAME 'krb5MaxRenew' EQUALITY integerMatch SINGLE-VALUE SYNTAX 1.3.6.1.4.1.1466.115.121.1.27 ) attributetype ( 1.3.6.1.4.1.5322.10.1.5 NAME 'krb5KDCFlags' EQUALITY integerMatch SINGLE-VALUE SYNTAX 1.3.6.1.4.1.1466.115.121.1.27 ) attributetype ( 1.3.6.1.4.1.5322.10.1.6 NAME 'krb5EncryptionType' EQUALITY integerMatch SYNTAX 1.3.6.1.4.1.1466.115.121.1.27 ) attributetype ( 1.3.6.1.4.1.5322.10.1.7 NAME 'krb5ValidStart' EQUALITY generalizedTimeMatch ORDERING generalizedTimeOrderingMatch SYNTAX 1.3.6.1.4.1.1466.115.121.1.24 SINGLE-VALUE ) attributetype ( 1.3.6.1.4.1.5322.10.1.8 NAME 'krb5ValidEnd' EQUALITY generalizedTimeMatch ORDERING generalizedTimeOrderingMatch SYNTAX 1.3.6.1.4.1.1466.115.121.1.24 SINGLE-VALUE ) attributetype ( 1.3.6.1.4.1.5322.10.1.9 NAME 'krb5PasswordEnd' EQUALITY generalizedTimeMatch ORDERING generalizedTimeOrderingMatch SYNTAX 1.3.6.1.4.1.1466.115.121.1.24 SINGLE-VALUE ) # this is temporary; keys will eventually # be child entries or compound attributes. attributetype ( 1.3.6.1.4.1.5322.10.1.10 NAME 'krb5Key' DESC 'Encoded ASN1 Key as an octet string' SYNTAX 1.3.6.1.4.1.1466.115.121.1.5 ) attributetype ( 1.3.6.1.4.1.5322.10.1.11 NAME 'krb5PrincipalRealm' DESC 'Distinguished name of krb5Realm entry' SUP distinguishedName ) attributetype ( 1.3.6.1.4.1.5322.10.1.12 NAME 'krb5RealmName' EQUALITY octetStringMatch SYNTAX 1.3.6.1.4.1.1466.115.121.1.40{128} ) attributetype ( 1.3.6.1.4.1.5322.10.1.13 NAME 'krb5ExtendedAttributes' DESC 'Encoded ASN1 HDB Extension Attributes as an octet string' SYNTAX 1.3.6.1.4.1.1466.115.121.1.5 ) # Object class definitions objectclass ( 1.3.6.1.4.1.5322.10.2.1 NAME 'krb5Principal' SUP top AUXILIARY MUST ( krb5PrincipalName ) MAY ( cn $ krb5PrincipalRealm ) ) objectclass ( 1.3.6.1.4.1.5322.10.2.2 NAME 'krb5KDCEntry' SUP krb5Principal AUXILIARY MUST ( krb5KeyVersionNumber ) MAY ( krb5ValidStart $ krb5ValidEnd $ krb5PasswordEnd $ krb5MaxLife $ krb5MaxRenew $ krb5KDCFlags $ krb5EncryptionType $ krb5Key $ krb5ExtendedAttributes ) ) objectclass ( 1.3.6.1.4.1.5322.10.2.3 NAME 'krb5Realm' SUP top AUXILIARY MUST ( krb5RealmName ) ) heimdal-7.5.0/lib/hdb/db.c0000644000175000017500000002314113212137553013311 0ustar niknik/* * Copyright (c) 1997 - 2001 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "hdb_locl.h" #if defined(HAVE_DB1) #if defined(HAVE_DB_185_H) #include #elif defined(HAVE_DB_H) #include #endif typedef struct { HDB hdb; /* generic members */ int lock_fd; /* DB-specific */ } DB1_HDB; static krb5_error_code DB_close(krb5_context context, HDB *db) { DB1_HDB *db1 = (DB1_HDB *)db; DB *d = (DB*)db->hdb_db; heim_assert(d != 0, "Closing already closed HDB"); (*d->close)(d); db->hdb_db = 0; if (db1->lock_fd >= 0) { close(db1->lock_fd); db1->lock_fd = -1; } return 0; } static krb5_error_code DB_destroy(krb5_context context, HDB *db) { krb5_error_code ret; ret = hdb_clear_master_key (context, db); free(db->hdb_name); free(db); return ret; } static krb5_error_code DB_lock(krb5_context context, HDB *db, int operation) { return 0; } static krb5_error_code DB_unlock(krb5_context context, HDB *db) { return 0; } static krb5_error_code DB_seq(krb5_context context, HDB *db, unsigned flags, hdb_entry_ex *entry, int flag) { DB *d = (DB*)db->hdb_db; DBT key, value; krb5_data key_data, data; int code; code = (*d->seq)(d, &key, &value, flag); if(code == -1) { code = errno; krb5_set_error_message(context, code, "Database %s seq error: %s", db->hdb_name, strerror(code)); return code; } if(code == 1) { krb5_clear_error_message(context); return HDB_ERR_NOENTRY; } key_data.data = key.data; key_data.length = key.size; data.data = value.data; data.length = value.size; memset(entry, 0, sizeof(*entry)); if (hdb_value2entry(context, &data, &entry->entry)) return DB_seq(context, db, flags, entry, R_NEXT); if (db->hdb_master_key_set && (flags & HDB_F_DECRYPT)) { code = hdb_unseal_keys (context, db, &entry->entry); if (code) hdb_free_entry (context, entry); } if (code == 0 && entry->entry.principal == NULL) { entry->entry.principal = malloc(sizeof(*entry->entry.principal)); if (entry->entry.principal == NULL) { code = ENOMEM; krb5_set_error_message(context, code, "malloc: out of memory"); hdb_free_entry (context, entry); } else { hdb_key2principal(context, &key_data, entry->entry.principal); } } return code; } static krb5_error_code DB_firstkey(krb5_context context, HDB *db, unsigned flags, hdb_entry_ex *entry) { return DB_seq(context, db, flags, entry, R_FIRST); } static krb5_error_code DB_nextkey(krb5_context context, HDB *db, unsigned flags, hdb_entry_ex *entry) { return DB_seq(context, db, flags, entry, R_NEXT); } static krb5_error_code DB_rename(krb5_context context, HDB *db, const char *new_name) { int ret; char *old, *new; if (strncmp(new_name, "db:", sizeof("db:") - 1) == 0) new_name += sizeof("db:") - 1; else if (strncmp(new_name, "db1:", sizeof("db1:") - 1) == 0) new_name += sizeof("db1:") - 1; asprintf(&old, "%s.db", db->hdb_name); asprintf(&new, "%s.db", new_name); ret = rename(old, new); free(old); free(new); if(ret) return errno; free(db->hdb_name); db->hdb_name = strdup(new_name); return 0; } static krb5_error_code DB__get(krb5_context context, HDB *db, krb5_data key, krb5_data *reply) { DB *d = (DB*)db->hdb_db; DBT k, v; int code; k.data = key.data; k.size = key.length; code = (*d->get)(d, &k, &v, 0); if(code < 0) { code = errno; krb5_set_error_message(context, code, "Database %s get error: %s", db->hdb_name, strerror(code)); return code; } if(code == 1) { krb5_clear_error_message(context); return HDB_ERR_NOENTRY; } krb5_data_copy(reply, v.data, v.size); return 0; } static krb5_error_code DB__put(krb5_context context, HDB *db, int replace, krb5_data key, krb5_data value) { DB *d = (DB*)db->hdb_db; DBT k, v; int code; k.data = key.data; k.size = key.length; v.data = value.data; v.size = value.length; krb5_clear_error_message(context); code = (*d->put)(d, &k, &v, replace ? 0 : R_NOOVERWRITE); if(code < 0) { code = errno; krb5_set_error_message(context, code, "Database %s put error: %s", db->hdb_name, strerror(code)); return code; } if(code == 1) { return HDB_ERR_EXISTS; } code = (*d->sync)(d, 0); if (code == -1) { code = errno; krb5_set_error_message(context, code, "Database %s put sync error: %s", db->hdb_name, strerror(code)); return code; } return 0; } static krb5_error_code DB__del(krb5_context context, HDB *db, krb5_data key) { DB *d = (DB*)db->hdb_db; DBT k; krb5_error_code code; k.data = key.data; k.size = key.length; krb5_clear_error_message(context); code = (*d->del)(d, &k, 0); if (code == 1) return HDB_ERR_NOENTRY; if (code < 0) { code = errno; krb5_set_error_message(context, code, "Database %s del error: %s", db->hdb_name, strerror(code)); return code; } code = (*d->sync)(d, 0); if (code == -1) { code = errno; krb5_set_error_message(context, code, "Database %s del sync error: %s", db->hdb_name, strerror(code)); return code; } return 0; } static DB * _open_db(char *fn, int flags, int mode, int *fd) { #ifndef O_EXLOCK int op; int ret; *fd = open(fn, flags, mode); if (*fd == -1) return NULL; if ((flags & O_ACCMODE) == O_RDONLY) op = LOCK_SH; else op = LOCK_EX; ret = flock(*fd, op); if (ret == -1) { int saved_errno; saved_errno = errno; close(*fd); errno = saved_errno; return NULL; } #else if ((flags & O_ACCMODE) == O_RDONLY) flags |= O_SHLOCK; else flags |= O_EXLOCK; #endif return dbopen(fn, flags, mode, DB_BTREE, NULL); } static krb5_error_code DB_open(krb5_context context, HDB *db, int flags, mode_t mode) { DB1_HDB *db1 = (DB1_HDB *)db; char *fn; krb5_error_code ret; asprintf(&fn, "%s.db", db->hdb_name); if (fn == NULL) { krb5_set_error_message(context, ENOMEM, "malloc: out of memory"); return ENOMEM; } db->hdb_db = _open_db(fn, flags, mode, &db1->lock_fd); free(fn); /* try to open without .db extension */ if(db->hdb_db == NULL && errno == ENOENT) db->hdb_db = _open_db(db->hdb_name, flags, mode, &db1->lock_fd); if(db->hdb_db == NULL) { krb5_set_error_message(context, errno, "dbopen (%s): %s", db->hdb_name, strerror(errno)); return errno; } if((flags & O_ACCMODE) == O_RDONLY) ret = hdb_check_db_format(context, db); else ret = hdb_init_db(context, db); if(ret == HDB_ERR_NOENTRY) { krb5_clear_error_message(context); return 0; } if (ret) { DB_close(context, db); krb5_set_error_message(context, ret, "hdb_open: failed %s database %s", (flags & O_ACCMODE) == O_RDONLY ? "checking format of" : "initialize", db->hdb_name); } return ret; } krb5_error_code hdb_db1_create(krb5_context context, HDB **db, const char *filename) { DB1_HDB **db1 = (DB1_HDB **)db; *db = calloc(1, sizeof(**db1)); /* Allocate space for the larger db1 */ if (*db == NULL) { krb5_set_error_message(context, ENOMEM, "malloc: out of memory"); return ENOMEM; } (*db)->hdb_db = NULL; (*db)->hdb_name = strdup(filename); if ((*db)->hdb_name == NULL) { free(*db); *db = NULL; krb5_set_error_message(context, ENOMEM, "malloc: out of memory"); return ENOMEM; } (*db)->hdb_master_key_set = 0; (*db)->hdb_openp = 0; (*db)->hdb_capability_flags = HDB_CAP_F_HANDLE_ENTERPRISE_PRINCIPAL; (*db)->hdb_open = DB_open; (*db)->hdb_close = DB_close; (*db)->hdb_fetch_kvno = _hdb_fetch_kvno; (*db)->hdb_store = _hdb_store; (*db)->hdb_remove = _hdb_remove; (*db)->hdb_firstkey = DB_firstkey; (*db)->hdb_nextkey= DB_nextkey; (*db)->hdb_lock = DB_lock; (*db)->hdb_unlock = DB_unlock; (*db)->hdb_rename = DB_rename; (*db)->hdb__get = DB__get; (*db)->hdb__put = DB__put; (*db)->hdb__del = DB__del; (*db)->hdb_destroy = DB_destroy; (*db1)->lock_fd = -1; return 0; } #endif /* defined(HAVE_DB1) */ heimdal-7.5.0/lib/hdb/version-script.map0000644000175000017500000000521013062055136016242 0ustar niknik# $Id$ HEIMDAL_HDB_1.0 { global: encode_hdb_keyset; hdb_add_master_key; hdb_add_current_keys_to_history; hdb_change_kvno; hdb_check_db_format; hdb_clear_extension; hdb_clear_master_key; hdb_create; hdb_db_dir; hdb_dbinfo_get_acl_file; hdb_dbinfo_get_binding; hdb_dbinfo_get_dbname; hdb_dbinfo_get_label; hdb_dbinfo_get_log_file; hdb_dbinfo_get_mkey_file; hdb_dbinfo_get_next; hdb_dbinfo_get_realm; hdb_default_db; hdb_enctype2key; hdb_entry2string; hdb_entry2value; hdb_entry_alias2value; hdb_entry_check_mandatory; hdb_entry_clear_password; hdb_entry_get_ConstrainedDelegACL; hdb_entry_get_aliases; hdb_entry_get_password; hdb_entry_get_pkinit_acl; hdb_entry_get_pkinit_cert; hdb_entry_get_pkinit_hash; hdb_entry_get_pw_change_time; hdb_entry_set_password; hdb_entry_set_pw_change_time; hdb_find_extension; hdb_foreach; hdb_free_dbinfo; hdb_free_entry; hdb_free_key; hdb_free_keys; hdb_free_master_key; hdb_generate_key_set; hdb_generate_key_set_password; hdb_generate_key_set_password_with_ks_tuple; hdb_get_dbinfo; hdb_init_db; hdb_key2principal; hdb_kvno2keys; hdb_list_builtin; hdb_lock; hdb_next_enctype2key; hdb_principal2key; hdb_print_entry; hdb_process_master_key; hdb_prune_keys; hdb_read_master_key; hdb_replace_extension; hdb_seal_key; hdb_seal_key_mkey; hdb_seal_keys; hdb_seal_keys_mkey; hdb_set_last_modified_by; hdb_set_master_key; hdb_set_master_keyfile; hdb_unlock; hdb_unseal_key; hdb_unseal_key_mkey; hdb_unseal_keys; hdb_unseal_keys_mkey; hdb_value2entry; hdb_value2entry_alias; hdb_write_master_key; length_hdb_keyset; hdb_interface_version; initialize_hdb_error_table_r; # MIT KDB related entries _hdb_mdb_value2entry; _hdb_mit_dump2mitdb_entry; hdb_kt_ops; hdb_get_kt_ops; # some random bits needed for libkadm add_HDB_Ext_KeySet; add_Keys; asn1_HDBFlags_units; copy_Event; copy_HDB_extensions; copy_Key; copy_Keys; copy_Salt; decode_HDB_Ext_Aliases; decode_HDB_extension; decode_HDB_Ext_PKINIT_acl; decode_Key; decode_Keys; encode_HDB_Ext_Aliases; encode_HDB_extension; encode_HDB_Ext_PKINIT_acl; encode_Key; encode_Keys; free_Event; free_hdb_entry; free_HDB_Ext_Aliases; free_HDB_extension; free_HDB_extensions; free_HDB_Ext_PKINIT_acl; free_hdb_keyset; free_Key; free_Keys; free_Salt; HDBFlags2int; int2HDBFlags; length_HDB_Ext_Aliases; length_HDB_extension; length_HDB_Ext_PKINIT_acl; length_Key; length_Keys; remove_Keys; add_Keys; add_HDB_Ext_KeySet; local: *; }; heimdal-7.5.0/lib/hdb/hdb_err.et0000644000175000017500000000240213026237312014511 0ustar niknik# # Error messages for the hdb library # # This might look like a com_err file, but is not # id "$Id$" error_table hdb prefix HDB_ERR index 1 #error_code INUSE, "Entry already exists in database" error_code UK_SERROR, "Database store error" error_code UK_RERROR, "Database read error" error_code NOENTRY, "No such entry in the database" error_code DB_INUSE, "Database is locked or in use--try again later" error_code DB_CHANGED, "Database was modified during read" error_code RECURSIVELOCK, "Attempt to lock database twice" error_code NOTLOCKED, "Attempt to unlock database when not locked" error_code BADLOCKMODE, "Invalid kdb lock mode" error_code CANT_LOCK_DB, "Insufficient access to lock database" error_code EXISTS, "Entry already exists in database" error_code BADVERSION, "Wrong database version" error_code NO_MKEY, "No correct master key" error_code MANDATORY_OPTION, "Entry contains unknown mandatory extension" error_code NO_WRITE_SUPPORT, "HDB backend doesn't contain write support" error_code NOT_FOUND_HERE, "The secret for this entry is not replicated to this database" error_code MISUSE, "Incorrect use of the API" error_code KVNO_NOT_FOUND, "Entry key version number not found" error_code WRONG_REALM, "The principal exists in another realm." end heimdal-7.5.0/lib/hdb/hdb-mdb.c0000644000175000017500000002370713212137553014231 0ustar niknik/* * Copyright (c) 1997 - 2006 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * Copyright (c) 2011 - Howard Chu, Symas Corp. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "hdb_locl.h" #if HAVE_LMDB /* LMDB */ #include #define KILO 1024 typedef struct mdb_info { MDB_env *e; MDB_txn *t; MDB_dbi d; MDB_cursor *c; } mdb_info; static krb5_error_code DB_close(krb5_context context, HDB *db) { mdb_info *mi = (mdb_info *)db->hdb_db; mdb_cursor_close(mi->c); mdb_txn_abort(mi->t); mdb_env_close(mi->e); mi->c = 0; mi->t = 0; mi->e = 0; return 0; } static krb5_error_code DB_destroy(krb5_context context, HDB *db) { krb5_error_code ret; ret = hdb_clear_master_key (context, db); free(db->hdb_name); free(db->hdb_db); free(db); return ret; } static krb5_error_code DB_lock(krb5_context context, HDB *db, int operation) { db->lock_count++; return 0; } static krb5_error_code DB_unlock(krb5_context context, HDB *db) { if (db->lock_count > 1) { db->lock_count--; return 0; } heim_assert(db->lock_count == 1, "HDB lock/unlock sequence does not match"); db->lock_count--; return 0; } static krb5_error_code DB_seq(krb5_context context, HDB *db, unsigned flags, hdb_entry_ex *entry, int flag) { mdb_info *mi = db->hdb_db; MDB_val key, value; krb5_data key_data, data; int code; key.mv_size = 0; value.mv_size = 0; code = mdb_cursor_get(mi->c, &key, &value, flag); if (code == MDB_NOTFOUND) return HDB_ERR_NOENTRY; if (code) return code; key_data.data = key.mv_data; key_data.length = key.mv_size; data.data = value.mv_data; data.length = value.mv_size; memset(entry, 0, sizeof(*entry)); if (hdb_value2entry(context, &data, &entry->entry)) return DB_seq(context, db, flags, entry, MDB_NEXT); if (db->hdb_master_key_set && (flags & HDB_F_DECRYPT)) { code = hdb_unseal_keys (context, db, &entry->entry); if (code) hdb_free_entry (context, entry); } if (entry->entry.principal == NULL) { entry->entry.principal = malloc(sizeof(*entry->entry.principal)); if (entry->entry.principal == NULL) { hdb_free_entry (context, entry); krb5_set_error_message(context, ENOMEM, "malloc: out of memory"); return ENOMEM; } else { hdb_key2principal(context, &key_data, entry->entry.principal); } } return 0; } static krb5_error_code DB_firstkey(krb5_context context, HDB *db, unsigned flags, hdb_entry_ex *entry) { mdb_info *mi = db->hdb_db; int code; /* Always start with a fresh cursor to pick up latest DB state */ if (mi->t) mdb_txn_abort(mi->t); code = mdb_txn_begin(mi->e, NULL, MDB_RDONLY, &mi->t); if (code) return code; code = mdb_cursor_open(mi->t, mi->d, &mi->c); if (code) return code; return DB_seq(context, db, flags, entry, MDB_FIRST); } static krb5_error_code DB_nextkey(krb5_context context, HDB *db, unsigned flags, hdb_entry_ex *entry) { return DB_seq(context, db, flags, entry, MDB_NEXT); } static krb5_error_code DB_rename(krb5_context context, HDB *db, const char *new_name) { int ret; char *old, *new; if (strncmp(new_name, "mdb:", sizeof("mdb:") - 1) == 0) new_name += sizeof("mdb:") - 1; else if (strncmp(new_name, "lmdb:", sizeof("lmdb:") - 1) == 0) new_name += sizeof("lmdb:") - 1; if (asprintf(&old, "%s.mdb", db->hdb_name) == -1) return ENOMEM; if (asprintf(&new, "%s.mdb", new_name) == -1) { free(old); return ENOMEM; } ret = rename(old, new); free(old); free(new); if(ret) return errno; free(db->hdb_name); db->hdb_name = strdup(new_name); return 0; } static krb5_error_code DB__get(krb5_context context, HDB *db, krb5_data key, krb5_data *reply) { mdb_info *mi = (mdb_info*)db->hdb_db; MDB_txn *txn; MDB_val k, v; int code; k.mv_data = key.data; k.mv_size = key.length; code = mdb_txn_begin(mi->e, NULL, MDB_RDONLY, &txn); if (code) return code; code = mdb_get(txn, mi->d, &k, &v); if (code == 0) krb5_data_copy(reply, v.mv_data, v.mv_size); mdb_txn_abort(txn); if(code == MDB_NOTFOUND) return HDB_ERR_NOENTRY; return code; } static krb5_error_code DB__put(krb5_context context, HDB *db, int replace, krb5_data key, krb5_data value) { mdb_info *mi = (mdb_info*)db->hdb_db; MDB_txn *txn; MDB_val k, v; int code; k.mv_data = key.data; k.mv_size = key.length; v.mv_data = value.data; v.mv_size = value.length; code = mdb_txn_begin(mi->e, NULL, 0, &txn); if (code) return code; code = mdb_put(txn, mi->d, &k, &v, replace ? 0 : MDB_NOOVERWRITE); if (code) mdb_txn_abort(txn); else code = mdb_txn_commit(txn); if(code == MDB_KEYEXIST) return HDB_ERR_EXISTS; return code; } static krb5_error_code DB__del(krb5_context context, HDB *db, krb5_data key) { mdb_info *mi = (mdb_info*)db->hdb_db; MDB_txn *txn; MDB_val k; krb5_error_code code; k.mv_data = key.data; k.mv_size = key.length; code = mdb_txn_begin(mi->e, NULL, 0, &txn); if (code) return code; code = mdb_del(txn, mi->d, &k, NULL); if (code) mdb_txn_abort(txn); else code = mdb_txn_commit(txn); if(code == MDB_NOTFOUND) return HDB_ERR_NOENTRY; return code; } static krb5_error_code DB_open(krb5_context context, HDB *db, int flags, mode_t mode) { mdb_info *mi = (mdb_info *)db->hdb_db; MDB_txn *txn; char *fn; krb5_error_code ret; int myflags = MDB_NOSUBDIR, tmp; if((flags & O_ACCMODE) == O_RDONLY) myflags |= MDB_RDONLY; if (asprintf(&fn, "%s.mdb", db->hdb_name) == -1) return krb5_enomem(context); if (mdb_env_create(&mi->e)) { free(fn); return krb5_enomem(context); } tmp = krb5_config_get_int_default(context, NULL, 0, "kdc", "hdb-mdb-maxreaders", NULL); if (tmp) { ret = mdb_env_set_maxreaders(mi->e, tmp); if (ret) { free(fn); krb5_set_error_message(context, ret, "setting maxreaders on %s: %s", db->hdb_name, mdb_strerror(ret)); return ret; } } tmp = krb5_config_get_int_default(context, NULL, 0, "kdc", "hdb-mdb-mapsize", NULL); if (tmp) { size_t maps = tmp; maps *= KILO; ret = mdb_env_set_mapsize(mi->e, maps); if (ret) { free(fn); krb5_set_error_message(context, ret, "setting mapsize on %s: %s", db->hdb_name, mdb_strerror(ret)); return ret; } } ret = mdb_env_open(mi->e, fn, myflags, mode); free(fn); if (ret) { fail: mdb_env_close(mi->e); mi->e = 0; krb5_set_error_message(context, ret, "opening %s: %s", db->hdb_name, mdb_strerror(ret)); return ret; } ret = mdb_txn_begin(mi->e, NULL, MDB_RDONLY, &txn); if (ret) goto fail; ret = mdb_open(txn, NULL, 0, &mi->d); mdb_txn_abort(txn); if (ret) goto fail; if((flags & O_ACCMODE) == O_RDONLY) ret = hdb_check_db_format(context, db); else ret = hdb_init_db(context, db); if(ret == HDB_ERR_NOENTRY) return 0; if (ret) { DB_close(context, db); krb5_set_error_message(context, ret, "hdb_open: failed %s database %s", (flags & O_ACCMODE) == O_RDONLY ? "checking format of" : "initialize", db->hdb_name); } return ret; } krb5_error_code hdb_mdb_create(krb5_context context, HDB **db, const char *filename) { *db = calloc(1, sizeof(**db)); if (*db == NULL) { krb5_set_error_message(context, ENOMEM, "malloc: out of memory"); return ENOMEM; } (*db)->hdb_db = calloc(1, sizeof(mdb_info)); if ((*db)->hdb_db == NULL) { free(*db); *db = NULL; krb5_set_error_message(context, ENOMEM, "malloc: out of memory"); return ENOMEM; } (*db)->hdb_name = strdup(filename); if ((*db)->hdb_name == NULL) { free((*db)->hdb_db); free(*db); *db = NULL; krb5_set_error_message(context, ENOMEM, "malloc: out of memory"); return ENOMEM; } (*db)->hdb_master_key_set = 0; (*db)->hdb_openp = 0; (*db)->hdb_capability_flags = HDB_CAP_F_HANDLE_ENTERPRISE_PRINCIPAL; (*db)->hdb_open = DB_open; (*db)->hdb_close = DB_close; (*db)->hdb_fetch_kvno = _hdb_fetch_kvno; (*db)->hdb_store = _hdb_store; (*db)->hdb_remove = _hdb_remove; (*db)->hdb_firstkey = DB_firstkey; (*db)->hdb_nextkey= DB_nextkey; (*db)->hdb_lock = DB_lock; (*db)->hdb_unlock = DB_unlock; (*db)->hdb_rename = DB_rename; (*db)->hdb__get = DB__get; (*db)->hdb__put = DB__put; (*db)->hdb__del = DB__del; (*db)->hdb_destroy = DB_destroy; return 0; } #endif /* HAVE_LMDB */ heimdal-7.5.0/lib/hdb/libhdb-exports.def0000644000175000017500000000461213062057075016173 0ustar niknikEXPORTS encode_hdb_keyset hdb_add_master_key hdb_add_current_keys_to_history hdb_change_kvno hdb_check_db_format hdb_clear_extension hdb_clear_master_key hdb_create hdb_db_dir hdb_dbinfo_get_acl_file hdb_dbinfo_get_binding hdb_dbinfo_get_dbname hdb_dbinfo_get_label hdb_dbinfo_get_log_file hdb_dbinfo_get_mkey_file hdb_dbinfo_get_next hdb_dbinfo_get_realm hdb_default_db hdb_enctype2key hdb_entry2string hdb_entry2value hdb_entry_alias2value hdb_entry_check_mandatory hdb_entry_clear_password hdb_entry_get_ConstrainedDelegACL hdb_entry_get_aliases hdb_entry_get_password hdb_entry_get_pkinit_acl hdb_entry_get_pkinit_cert hdb_entry_get_pkinit_hash hdb_entry_get_pw_change_time hdb_entry_set_password hdb_entry_set_pw_change_time hdb_find_extension hdb_foreach hdb_free_dbinfo hdb_free_entry hdb_free_key hdb_free_keys hdb_free_master_key hdb_generate_key_set hdb_generate_key_set_password hdb_generate_key_set_password_with_ks_tuple hdb_get_dbinfo hdb_init_db hdb_interface_version DATA hdb_key2principal hdb_kvno2keys hdb_list_builtin hdb_lock hdb_next_enctype2key hdb_principal2key hdb_print_entry hdb_process_master_key hdb_prune_keys hdb_read_master_key hdb_replace_extension hdb_seal_key hdb_seal_key_mkey hdb_seal_keys hdb_seal_keys_mkey hdb_set_last_modified_by hdb_set_master_key hdb_set_master_keyfile hdb_unlock hdb_unseal_key hdb_unseal_key_mkey hdb_unseal_keys hdb_unseal_keys_mkey hdb_value2entry hdb_value2entry_alias hdb_write_master_key length_hdb_keyset initialize_hdb_error_table_r hdb_kt_ops hdb_get_kt_ops ; MIT KDB related entries _hdb_mdb_value2entry _hdb_mit_dump2mitdb_entry ; some random bits needed for libkadm HDBFlags2int asn1_HDBFlags_units copy_Event copy_HDB_extensions copy_Key copy_Keys copy_Salt decode_HDB_Ext_Aliases decode_HDB_Ext_PKINIT_acl decode_HDB_extension decode_Key decode_Keys encode_HDB_Ext_Aliases encode_HDB_Ext_PKINIT_acl encode_HDB_extension encode_Key encode_Keys free_Event free_HDB_Ext_Aliases free_HDB_Ext_PKINIT_acl free_HDB_extension free_HDB_extensions free_Key free_Keys free_Salt free_hdb_entry free_hdb_keyset int2HDBFlags length_HDB_Ext_Aliases length_HDB_Ext_PKINIT_acl length_HDB_extension length_Key length_Keys add_Keys add_HDB_Ext_KeySet remove_Keys heimdal-7.5.0/lib/hdb/keytab.c0000644000175000017500000002450013026237312014200 0ustar niknik/* * Copyright (c) 1999 - 2002 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "hdb_locl.h" /* keytab backend for HDB databases */ struct hdb_data { char *dbname; char *mkey; }; struct hdb_cursor { HDB *db; hdb_entry_ex hdb_entry; int first, next; int key_idx; }; /* * the format for HDB keytabs is: * HDB:[HDBFORMAT:database-specific-data[:mkey=mkey-file]] */ static krb5_error_code KRB5_CALLCONV hdb_resolve(krb5_context context, const char *name, krb5_keytab id) { struct hdb_data *d; const char *db, *mkey; d = malloc(sizeof(*d)); if(d == NULL) { krb5_set_error_message(context, ENOMEM, "malloc: out of memory"); return ENOMEM; } db = name; mkey = strstr(name, ":mkey="); if(mkey == NULL || mkey[6] == '\0') { if(*name == '\0') d->dbname = NULL; else { d->dbname = strdup(name); if(d->dbname == NULL) { free(d); krb5_set_error_message(context, ENOMEM, "malloc: out of memory"); return ENOMEM; } } d->mkey = NULL; } else { d->dbname = malloc(mkey - db + 1); if(d->dbname == NULL) { free(d); krb5_set_error_message(context, ENOMEM, "malloc: out of memory"); return ENOMEM; } memmove(d->dbname, db, mkey - db); d->dbname[mkey - db] = '\0'; d->mkey = strdup(mkey + 6); if(d->mkey == NULL) { free(d->dbname); free(d); krb5_set_error_message(context, ENOMEM, "malloc: out of memory"); return ENOMEM; } } id->data = d; return 0; } static krb5_error_code KRB5_CALLCONV hdb_close(krb5_context context, krb5_keytab id) { struct hdb_data *d = id->data; free(d->dbname); free(d->mkey); free(d); return 0; } static krb5_error_code KRB5_CALLCONV hdb_get_name(krb5_context context, krb5_keytab id, char *name, size_t namesize) { struct hdb_data *d = id->data; snprintf(name, namesize, "%s%s%s", d->dbname ? d->dbname : "", (d->dbname || d->mkey) ? ":" : "", d->mkey ? d->mkey : ""); return 0; } /* * try to figure out the database (`dbname') and master-key (`mkey') * that should be used for `principal'. */ static krb5_error_code find_db (krb5_context context, char **dbname, char **mkey, krb5_const_principal principal) { krb5_const_realm realm = krb5_principal_get_realm(context, principal); krb5_error_code ret; struct hdb_dbinfo *head, *dbinfo = NULL; *dbname = *mkey = NULL; ret = hdb_get_dbinfo(context, &head); if (ret) return ret; while ((dbinfo = hdb_dbinfo_get_next(head, dbinfo)) != NULL) { const char *p = hdb_dbinfo_get_realm(context, dbinfo); if (p && strcmp (realm, p) == 0) { p = hdb_dbinfo_get_dbname(context, dbinfo); if (p) *dbname = strdup(p); p = hdb_dbinfo_get_mkey_file(context, dbinfo); if (p) *mkey = strdup(p); break; } } hdb_free_dbinfo(context, &head); if (*dbname == NULL) *dbname = strdup(HDB_DEFAULT_DB); return 0; } /* * find the keytab entry in `id' for `principal, kvno, enctype' and return * it in `entry'. return 0 or an error code */ static krb5_error_code KRB5_CALLCONV hdb_get_entry(krb5_context context, krb5_keytab id, krb5_const_principal principal, krb5_kvno kvno, krb5_enctype enctype, krb5_keytab_entry *entry) { hdb_entry_ex ent; krb5_error_code ret; struct hdb_data *d = id->data; const char *dbname = d->dbname; const char *mkey = d->mkey; char *fdbname = NULL, *fmkey = NULL; HDB *db; size_t i; memset(&ent, 0, sizeof(ent)); if (dbname == NULL) { ret = find_db(context, &fdbname, &fmkey, principal); if (ret) return ret; dbname = fdbname; mkey = fmkey; } ret = hdb_create (context, &db, dbname); if (ret) goto out2; ret = hdb_set_master_keyfile (context, db, mkey); if (ret) { (*db->hdb_destroy)(context, db); goto out2; } ret = (*db->hdb_open)(context, db, O_RDONLY, 0); if (ret) { (*db->hdb_destroy)(context, db); goto out2; } ret = (*db->hdb_fetch_kvno)(context, db, principal, HDB_F_DECRYPT|HDB_F_KVNO_SPECIFIED| HDB_F_GET_CLIENT|HDB_F_GET_SERVER|HDB_F_GET_KRBTGT, kvno, &ent); if(ret == HDB_ERR_NOENTRY) { ret = KRB5_KT_NOTFOUND; goto out; }else if(ret) goto out; if(kvno && (krb5_kvno)ent.entry.kvno != kvno) { hdb_free_entry(context, &ent); ret = KRB5_KT_NOTFOUND; goto out; } if(enctype == 0) if(ent.entry.keys.len > 0) enctype = ent.entry.keys.val[0].key.keytype; ret = KRB5_KT_NOTFOUND; for(i = 0; i < ent.entry.keys.len; i++) { if(ent.entry.keys.val[i].key.keytype == enctype) { krb5_copy_principal(context, principal, &entry->principal); entry->vno = ent.entry.kvno; krb5_copy_keyblock_contents(context, &ent.entry.keys.val[i].key, &entry->keyblock); ret = 0; break; } } hdb_free_entry(context, &ent); out: (*db->hdb_close)(context, db); (*db->hdb_destroy)(context, db); out2: free(fdbname); free(fmkey); return ret; } /* * find the keytab entry in `id' for `principal, kvno, enctype' and return * it in `entry'. return 0 or an error code */ static krb5_error_code KRB5_CALLCONV hdb_start_seq_get(krb5_context context, krb5_keytab id, krb5_kt_cursor *cursor) { krb5_error_code ret; struct hdb_cursor *c; struct hdb_data *d = id->data; const char *dbname = d->dbname; const char *mkey = d->mkey; HDB *db; if (dbname == NULL) { /* * We don't support enumerating without being told what * backend to enumerate on */ ret = KRB5_KT_NOTFOUND; return ret; } ret = hdb_create (context, &db, dbname); if (ret) return ret; ret = hdb_set_master_keyfile (context, db, mkey); if (ret) { (*db->hdb_destroy)(context, db); return ret; } ret = (*db->hdb_open)(context, db, O_RDONLY, 0); if (ret) { (*db->hdb_destroy)(context, db); return ret; } cursor->data = c = malloc (sizeof(*c)); if(c == NULL){ (*db->hdb_close)(context, db); (*db->hdb_destroy)(context, db); krb5_set_error_message(context, ENOMEM, "malloc: out of memory"); return ENOMEM; } c->db = db; c->first = TRUE; c->next = TRUE; c->key_idx = 0; cursor->data = c; return ret; } static int KRB5_CALLCONV hdb_next_entry(krb5_context context, krb5_keytab id, krb5_keytab_entry *entry, krb5_kt_cursor *cursor) { struct hdb_cursor *c = cursor->data; krb5_error_code ret; memset(entry, 0, sizeof(*entry)); if (c->first) { c->first = FALSE; ret = (c->db->hdb_firstkey)(context, c->db, HDB_F_DECRYPT| HDB_F_GET_CLIENT|HDB_F_GET_SERVER|HDB_F_GET_KRBTGT, &c->hdb_entry); if (ret == HDB_ERR_NOENTRY) return KRB5_KT_END; else if (ret) return ret; if (c->hdb_entry.entry.keys.len == 0) hdb_free_entry(context, &c->hdb_entry); else c->next = FALSE; } while (c->next) { ret = (c->db->hdb_nextkey)(context, c->db, HDB_F_DECRYPT| HDB_F_GET_CLIENT|HDB_F_GET_SERVER|HDB_F_GET_KRBTGT, &c->hdb_entry); if (ret == HDB_ERR_NOENTRY) return KRB5_KT_END; else if (ret) return ret; /* If no keys on this entry, try again */ if (c->hdb_entry.entry.keys.len == 0) hdb_free_entry(context, &c->hdb_entry); else c->next = FALSE; } /* * Return next enc type (keytabs are one slot per key, while * hdb is one record per principal. */ ret = krb5_copy_principal(context, c->hdb_entry.entry.principal, &entry->principal); if (ret) return ret; entry->vno = c->hdb_entry.entry.kvno; ret = krb5_copy_keyblock_contents(context, &c->hdb_entry.entry.keys.val[c->key_idx].key, &entry->keyblock); if (ret) { krb5_free_principal(context, entry->principal); memset(entry, 0, sizeof(*entry)); return ret; } c->key_idx++; /* * Once we get to the end of the list, signal that we want the * next entry */ if ((size_t)c->key_idx == c->hdb_entry.entry.keys.len) { hdb_free_entry(context, &c->hdb_entry); c->next = TRUE; c->key_idx = 0; } return 0; } static int KRB5_CALLCONV hdb_end_seq_get(krb5_context context, krb5_keytab id, krb5_kt_cursor *cursor) { struct hdb_cursor *c = cursor->data; if (!c->next) hdb_free_entry(context, &c->hdb_entry); (c->db->hdb_close)(context, c->db); (c->db->hdb_destroy)(context, c->db); free(c); return 0; } krb5_kt_ops hdb_kt_ops = { "HDB", hdb_resolve, hdb_get_name, hdb_close, NULL, /* destroy */ hdb_get_entry, hdb_start_seq_get, hdb_next_entry, hdb_end_seq_get, NULL, /* add */ NULL, /* remove */ NULL, 0 }; krb5_kt_ops hdb_get_kt_ops = { "HDBGET", hdb_resolve, hdb_get_name, hdb_close, NULL, hdb_get_entry, NULL, NULL, NULL, NULL, NULL, NULL, 0 }; heimdal-7.5.0/lib/hdb/libhdb-version.rc0000644000175000017500000000322512136107747016024 0ustar niknik/*********************************************************************** * Copyright (c) 2010, Secure Endpoints Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * - Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. * **********************************************************************/ #define RC_FILE_TYPE VFT_DLL #define RC_FILE_DESC_0409 "Heimdal DB Library" #define RC_FILE_ORIG_0409 "libhdb.dll" #include "../../windows/version.rc" heimdal-7.5.0/lib/hdb/keys.c0000644000175000017500000005073613062055136013710 0ustar niknik/* * Copyright (c) 1997 - 2011 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "hdb_locl.h" struct hx509_certs_data; struct krb5_pk_identity; struct krb5_pk_cert; struct ContentInfo; struct AlgorithmIdentifier; struct _krb5_krb_auth_data; typedef struct krb5_pk_init_ctx_data *krb5_pk_init_ctx; struct krb5_dh_moduli; struct _krb5_key_data; struct _krb5_encryption_type; struct _krb5_key_type; #include #include #include /* * free all the memory used by (len, keys) */ void hdb_free_keys(krb5_context context, int len, Key *keys) { size_t i; for (i = 0; i < len; i++) { free(keys[i].mkvno); keys[i].mkvno = NULL; if (keys[i].salt != NULL) { free_Salt(keys[i].salt); free(keys[i].salt); keys[i].salt = NULL; } krb5_free_keyblock_contents(context, &keys[i].key); } free (keys); } /* * for each entry in `default_keys' try to parse it as a sequence * of etype:salttype:salt, syntax of this if something like: * [(des|des3|etype):](pw-salt|afs3)[:string], if etype is omitted it * means all etypes, and if string is omitted is means the default * string (for that principal). Additional special values: * v5 == pw-salt, and * v4 == des:pw-salt: * afs or afs3 == des:afs3-salt */ static const krb5_enctype des_etypes[] = { KRB5_ENCTYPE_DES_CBC_MD5, KRB5_ENCTYPE_DES_CBC_MD4, KRB5_ENCTYPE_DES_CBC_CRC }; static const krb5_enctype all_etypes[] = { KRB5_ENCTYPE_AES256_CTS_HMAC_SHA1_96, KRB5_ENCTYPE_DES3_CBC_SHA1, KRB5_ENCTYPE_ARCFOUR_HMAC_MD5 }; static krb5_error_code parse_key_set(krb5_context context, const char *key, krb5_enctype **ret_enctypes, size_t *ret_num_enctypes, krb5_salt *salt, krb5_principal principal) { const char *p; char buf[3][256]; int num_buf = 0; int i, num_enctypes = 0; krb5_enctype e; const krb5_enctype *enctypes = NULL; krb5_error_code ret; p = key; *ret_enctypes = NULL; *ret_num_enctypes = 0; /* split p in a list of :-separated strings */ for(num_buf = 0; num_buf < 3; num_buf++) if(strsep_copy(&p, ":", buf[num_buf], sizeof(buf[num_buf])) == -1) break; salt->saltvalue.data = NULL; salt->saltvalue.length = 0; for(i = 0; i < num_buf; i++) { if(enctypes == NULL && num_buf > 1) { /* this might be a etype specifier */ /* XXX there should be a string_to_etypes handling special cases like `des' and `all' */ if(strcmp(buf[i], "des") == 0) { enctypes = des_etypes; num_enctypes = sizeof(des_etypes)/sizeof(des_etypes[0]); } else if(strcmp(buf[i], "des3") == 0) { e = KRB5_ENCTYPE_DES3_CBC_SHA1; enctypes = &e; num_enctypes = 1; } else { ret = krb5_string_to_enctype(context, buf[i], &e); if (ret == 0) { enctypes = &e; num_enctypes = 1; } else return ret; } continue; } if(salt->salttype == 0) { /* interpret string as a salt specifier, if no etype is set, this sets default values */ /* XXX should perhaps use string_to_salttype, but that interface sucks */ if(strcmp(buf[i], "pw-salt") == 0) { if(enctypes == NULL) { enctypes = all_etypes; num_enctypes = sizeof(all_etypes)/sizeof(all_etypes[0]); } salt->salttype = KRB5_PW_SALT; } else if(strcmp(buf[i], "afs3-salt") == 0) { if(enctypes == NULL) { enctypes = des_etypes; num_enctypes = sizeof(des_etypes)/sizeof(des_etypes[0]); } salt->salttype = KRB5_AFS3_SALT; } continue; } if (salt->saltvalue.data != NULL) free(salt->saltvalue.data); /* if there is a final string, use it as the string to salt with, this is mostly useful with null salt for v4 compat, and a cell name for afs compat */ salt->saltvalue.data = strdup(buf[i]); if (salt->saltvalue.data == NULL) return krb5_enomem(context); salt->saltvalue.length = strlen(buf[i]); } if(enctypes == NULL || salt->salttype == 0) { krb5_free_salt(context, *salt); krb5_set_error_message(context, EINVAL, "bad value for default_keys `%s'", key); return EINVAL; } /* if no salt was specified make up default salt */ if(salt->saltvalue.data == NULL) { if(salt->salttype == KRB5_PW_SALT) { ret = krb5_get_pw_salt(context, principal, salt); if (ret) return ret; } else if(salt->salttype == KRB5_AFS3_SALT) { krb5_const_realm realm = krb5_principal_get_realm(context, principal); salt->saltvalue.data = strdup(realm); if(salt->saltvalue.data == NULL) { krb5_set_error_message(context, ENOMEM, "out of memory while " "parsing salt specifiers"); return ENOMEM; } strlwr(salt->saltvalue.data); salt->saltvalue.length = strlen(realm); } } *ret_enctypes = malloc(sizeof(enctypes[0]) * num_enctypes); if (*ret_enctypes == NULL) { krb5_free_salt(context, *salt); krb5_set_error_message(context, ENOMEM, "malloc: out of memory"); return ENOMEM; } memcpy(*ret_enctypes, enctypes, sizeof(enctypes[0]) * num_enctypes); *ret_num_enctypes = num_enctypes; return 0; } /** * This function prunes an HDB entry's keys that are too old to have been used * to mint still valid tickets (based on the entry's maximum ticket lifetime). * * @param context Context * @param entry HDB entry */ krb5_error_code hdb_prune_keys(krb5_context context, hdb_entry *entry) { HDB_extension *ext; HDB_Ext_KeySet *keys; size_t nelem; ext = hdb_find_extension(entry, choice_HDB_extension_data_hist_keys); if (ext == NULL) return 0; keys = &ext->data.u.hist_keys; nelem = keys->len; /* Optionally drop key history for keys older than now - max_life */ if (entry->max_life != NULL && nelem > 0 && krb5_config_get_bool_default(context, NULL, FALSE, "kadmin", "prune-key-history", NULL)) { hdb_keyset *elem; time_t ceiling = time(NULL) - *entry->max_life; time_t keep_time = 0; size_t i; /* * Compute most recent key timestamp that predates the current time * by at least the entry's maximum ticket lifetime. */ for (i = 0; i < nelem; ++i) { elem = &keys->val[i]; if (elem->set_time && *elem->set_time < ceiling && (keep_time == 0 || *elem->set_time > keep_time)) keep_time = *elem->set_time; } /* Drop obsolete entries */ if (keep_time) { for (i = 0; i < nelem; /* see below */) { elem = &keys->val[i]; if (elem->set_time && *elem->set_time < keep_time) { remove_HDB_Ext_KeySet(keys, i); /* * Removing the i'th element shifts the tail down, continue * at same index with reduced upper bound. */ --nelem; continue; } ++i; } } } return 0; } /** * This function adds an HDB entry's current keyset to the entry's key * history. The current keyset is left alone; the caller is responsible * for freeing it. * * @param context Context * @param entry HDB entry */ krb5_error_code hdb_add_current_keys_to_history(krb5_context context, hdb_entry *entry) { krb5_boolean replace = FALSE; krb5_error_code ret; HDB_extension *ext; HDB_Ext_KeySet *keys; hdb_keyset newkeyset; time_t newtime; if (entry->keys.len == 0) return 0; /* nothing to do */ ext = hdb_find_extension(entry, choice_HDB_extension_data_hist_keys); if (ext == NULL) { replace = TRUE; ext = calloc(1, sizeof (*ext)); if (ext == NULL) return krb5_enomem(context); ext->data.element = choice_HDB_extension_data_hist_keys; } keys = &ext->data.u.hist_keys; ext->mandatory = FALSE; /* * Copy in newest old keyset */ ret = hdb_entry_get_pw_change_time(entry, &newtime); if (ret) goto out; memset(&newkeyset, 0, sizeof(newkeyset)); newkeyset.keys = entry->keys; newkeyset.kvno = entry->kvno; newkeyset.set_time = &newtime; ret = add_HDB_Ext_KeySet(keys, &newkeyset); if (ret) goto out; if (replace) { /* hdb_replace_extension() deep-copies ext; what a waste */ ret = hdb_replace_extension(context, entry, ext); if (ret) goto out; } ret = hdb_prune_keys(context, entry); if (ret) goto out; out: if (replace && ext) { free_HDB_extension(ext); free(ext); } return ret; } /** * This function adds a key to an HDB entry's key history. * * @param context Context * @param entry HDB entry * @param kvno Key version number of the key to add to the history * @param key The Key to add */ krb5_error_code hdb_add_history_key(krb5_context context, hdb_entry *entry, krb5_kvno kvno, Key *key) { size_t i; hdb_keyset keyset; HDB_Ext_KeySet *hist_keys; HDB_extension ext; HDB_extension *extp; krb5_error_code ret; memset(&keyset, 0, sizeof (keyset)); memset(&ext, 0, sizeof (ext)); extp = hdb_find_extension(entry, choice_HDB_extension_data_hist_keys); if (extp == NULL) { ext.data.element = choice_HDB_extension_data_hist_keys; extp = &ext; } extp->mandatory = FALSE; hist_keys = &extp->data.u.hist_keys; for (i = 0; i < hist_keys->len; i++) { if (hist_keys->val[i].kvno == kvno) { ret = add_Keys(&hist_keys->val[i].keys, key); goto out; } } keyset.kvno = kvno; ret = add_Keys(&keyset.keys, key); if (ret) goto out; ret = add_HDB_Ext_KeySet(hist_keys, &keyset); if (ret) goto out; if (extp == &ext) { ret = hdb_replace_extension(context, entry, &ext); if (ret) goto out; } out: free_hdb_keyset(&keyset); free_HDB_extension(&ext); return ret; } /** * This function changes an hdb_entry's kvno, swapping the current key * set with a historical keyset. If no historical keys are found then * an error is returned (the caller can still set entry->kvno directly). * * @param context krb5_context * @param new_kvno New kvno for the entry * @param entry hdb_entry to modify */ krb5_error_code hdb_change_kvno(krb5_context context, krb5_kvno new_kvno, hdb_entry *entry) { HDB_extension ext; HDB_extension *extp; hdb_keyset keyset; HDB_Ext_KeySet *hist_keys; size_t i; int found = 0; krb5_error_code ret; if (entry->kvno == new_kvno) return 0; extp = hdb_find_extension(entry, choice_HDB_extension_data_hist_keys); if (extp == NULL) { memset(&ext, 0, sizeof (ext)); ext.data.element = choice_HDB_extension_data_hist_keys; extp = &ext; } memset(&keyset, 0, sizeof (keyset)); hist_keys = &extp->data.u.hist_keys; for (i = 0; i < hist_keys->len; i++) { if (hist_keys->val[i].kvno == new_kvno) { found = 1; ret = copy_hdb_keyset(&hist_keys->val[i], &keyset); if (ret) goto out; ret = remove_HDB_Ext_KeySet(hist_keys, i); if (ret) goto out; break; } } if (!found) return HDB_ERR_KVNO_NOT_FOUND; ret = hdb_add_current_keys_to_history(context, entry); if (ret) goto out; /* Note: we do nothing with keyset.set_time */ entry->kvno = new_kvno; entry->keys = keyset.keys; /* shortcut */ memset(&keyset.keys, 0, sizeof (keyset.keys)); out: free_hdb_keyset(&keyset); return ret; } static krb5_error_code add_enctype_to_key_set(Key **key_set, size_t *nkeyset, krb5_enctype enctype, krb5_salt *salt) { krb5_error_code ret; Key key, *tmp; memset(&key, 0, sizeof(key)); tmp = realloc(*key_set, (*nkeyset + 1) * sizeof((*key_set)[0])); if (tmp == NULL) return ENOMEM; *key_set = tmp; key.key.keytype = enctype; key.key.keyvalue.length = 0; key.key.keyvalue.data = NULL; if (salt) { key.salt = calloc(1, sizeof(*key.salt)); if (key.salt == NULL) { free_Key(&key); return ENOMEM; } key.salt->type = salt->salttype; krb5_data_zero (&key.salt->salt); ret = krb5_data_copy(&key.salt->salt, salt->saltvalue.data, salt->saltvalue.length); if (ret) { free_Key(&key); return ret; } } else key.salt = NULL; (*key_set)[*nkeyset] = key; *nkeyset += 1; return 0; } static krb5_error_code ks_tuple2str(krb5_context context, int n_ks_tuple, krb5_key_salt_tuple *ks_tuple, char ***ks_tuple_strs) { size_t i; char **ksnames; krb5_error_code rc = KRB5_PROG_ETYPE_NOSUPP; *ks_tuple_strs = NULL; if (n_ks_tuple < 1) return 0; if ((ksnames = calloc(n_ks_tuple + 1, sizeof (*ksnames))) == NULL) return (errno); for (i = 0; i < n_ks_tuple; i++) { char *ename, *sname; if (krb5_enctype_to_string(context, ks_tuple[i].ks_enctype, &ename)) goto out; if (krb5_salttype_to_string(context, ks_tuple[i].ks_enctype, ks_tuple[i].ks_salttype, &sname)) { free(ename); goto out; } if (asprintf(&ksnames[i], "%s:%s", ename, sname) == -1) { rc = errno; free(ename); free(sname); goto out; } free(ename); free(sname); } ksnames[i] = NULL; *ks_tuple_strs = ksnames; return 0; out: for (i = 0; i < n_ks_tuple; i++) free(ksnames[i]); free(ksnames); return (rc); } /* * */ static char ** glob_rules_keys(krb5_context context, krb5_const_principal principal) { const krb5_config_binding *list; krb5_principal pattern; krb5_error_code ret; list = krb5_config_get_list(context, NULL, "kadmin", "default_key_rules", NULL); if (list == NULL) return NULL; while (list) { if (list->type == krb5_config_string) { ret = krb5_parse_name(context, list->name, &pattern); if (ret == 0) { ret = krb5_principal_match(context, principal, pattern); krb5_free_principal(context, pattern); if (ret) { return krb5_config_get_strings(context, list, list->name, NULL); } } } list = list->next; } return NULL; } /* * NIST guidance in Section 5.1 of [SP800-132] requires that a portion * of the salt of at least 128 bits shall be randomly generated. */ static krb5_error_code add_random_to_salt(krb5_context context, krb5_salt *in, krb5_salt *out) { krb5_error_code ret; char *p; unsigned char random[16]; char *s; int slen; krb5_generate_random_block(random, sizeof(random)); slen = rk_base64_encode(random, sizeof(random), &s); if (slen < 0) return ENOMEM; ret = krb5_data_alloc(&out->saltvalue, slen + in->saltvalue.length); if (ret) { free(s); return ret; } p = out->saltvalue.data; memcpy(p, s, slen); memcpy(&p[slen], in->saltvalue.data, in->saltvalue.length); out->salttype = in->salttype; free(s); return 0; } /* * Generate the `key_set' from the [kadmin]default_keys statement. If * `no_salt' is set, salt is not important (and will not be set) since * it's random keys that is going to be created. */ krb5_error_code hdb_generate_key_set(krb5_context context, krb5_principal principal, krb5_key_salt_tuple *ks_tuple, int n_ks_tuple, Key **ret_key_set, size_t *nkeyset, int no_salt) { char **ktypes = NULL; char **kp; krb5_error_code ret; Key *k, *key_set; size_t i, j; char **ks_tuple_strs; char **config_ktypes = NULL; static const char *default_keytypes[] = { "aes256-cts-hmac-sha1-96:pw-salt", "des3-cbc-sha1:pw-salt", "arcfour-hmac-md5:pw-salt", NULL }; if ((ret = ks_tuple2str(context, n_ks_tuple, ks_tuple, &ks_tuple_strs))) return ret; ktypes = ks_tuple_strs; if (ktypes == NULL) { ktypes = glob_rules_keys(context, principal); } if (ktypes == NULL) { config_ktypes = krb5_config_get_strings(context, NULL, "kadmin", "default_keys", NULL); ktypes = config_ktypes; } if (ktypes == NULL) ktypes = (char **)(intptr_t)default_keytypes; *ret_key_set = key_set = NULL; *nkeyset = 0; for(kp = ktypes; kp && *kp; kp++) { const char *p; krb5_salt salt; krb5_enctype *enctypes; size_t num_enctypes; p = *kp; /* check alias */ if(strcmp(p, "v5") == 0) p = "pw-salt"; else if(strcmp(p, "v4") == 0) p = "des:pw-salt:"; else if(strcmp(p, "afs") == 0 || strcmp(p, "afs3") == 0) p = "des:afs3-salt"; else if (strcmp(p, "arcfour-hmac-md5") == 0) p = "arcfour-hmac-md5:pw-salt"; memset(&salt, 0, sizeof(salt)); ret = parse_key_set(context, p, &enctypes, &num_enctypes, &salt, principal); if (ret) { krb5_warn(context, ret, "bad value for default_keys `%s'", *kp); ret = 0; krb5_free_salt(context, salt); continue; } for (i = 0; i < num_enctypes; i++) { krb5_salt *saltp = no_salt ? NULL : &salt; krb5_salt rsalt; /* find duplicates */ for (j = 0; j < *nkeyset; j++) { k = &key_set[j]; if (k->key.keytype == enctypes[i]) { if (no_salt) break; if (k->salt == NULL && salt.salttype == KRB5_PW_SALT) break; if (k->salt->type == salt.salttype && k->salt->salt.length == salt.saltvalue.length && memcmp(k->salt->salt.data, salt.saltvalue.data, salt.saltvalue.length) == 0) break; } } /* not a duplicate, lets add it */ if (j < *nkeyset) continue; memset(&rsalt, 0, sizeof(rsalt)); /* prepend salt with randomness if required */ if (!no_salt && _krb5_enctype_requires_random_salt(context, enctypes[i])) { saltp = &rsalt; ret = add_random_to_salt(context, &salt, &rsalt); } if (ret == 0) ret = add_enctype_to_key_set(&key_set, nkeyset, enctypes[i], saltp); krb5_free_salt(context, rsalt); if (ret) { free(enctypes); krb5_free_salt(context, salt); goto out; } } free(enctypes); krb5_free_salt(context, salt); } *ret_key_set = key_set; out: if (config_ktypes != NULL) krb5_config_free_strings(config_ktypes); for(kp = ks_tuple_strs; kp && *kp; kp++) free(*kp); free(ks_tuple_strs); if (ret) { krb5_warn(context, ret, "failed to parse the [kadmin]default_keys values"); for (i = 0; i < *nkeyset; i++) free_Key(&key_set[i]); free(key_set); } else if (*nkeyset == 0) { krb5_warnx(context, "failed to parse any of the [kadmin]default_keys values"); ret = EINVAL; /* XXX */ } return ret; } krb5_error_code hdb_generate_key_set_password_with_ks_tuple(krb5_context context, krb5_principal principal, const char *password, krb5_key_salt_tuple *ks_tuple, int n_ks_tuple, Key **keys, size_t *num_keys) { krb5_error_code ret; size_t i; ret = hdb_generate_key_set(context, principal, ks_tuple, n_ks_tuple, keys, num_keys, 0); if (ret) return ret; for (i = 0; i < (*num_keys); i++) { krb5_salt salt; Key *key = &(*keys)[i]; salt.salttype = key->salt->type; salt.saltvalue.length = key->salt->salt.length; salt.saltvalue.data = key->salt->salt.data; ret = krb5_string_to_key_salt (context, key->key.keytype, password, salt, &key->key); if(ret) break; } if(ret) { hdb_free_keys (context, *num_keys, *keys); return ret; } return ret; } krb5_error_code hdb_generate_key_set_password(krb5_context context, krb5_principal principal, const char *password, Key **keys, size_t *num_keys) { return hdb_generate_key_set_password_with_ks_tuple(context, principal, password, NULL, 0, keys, num_keys); } heimdal-7.5.0/lib/hdb/hdb-protos.h0000644000175000017500000002612713212445602015016 0ustar niknik/* This is a generated file */ #ifndef __hdb_protos_h__ #define __hdb_protos_h__ #ifndef DOXY #include #ifdef __cplusplus extern "C" { #endif krb5_error_code entry2mit_string_int ( krb5_context /*context*/, krb5_storage */*sp*/, hdb_entry */*ent*/); /** * This function adds an HDB entry's current keyset to the entry's key * history. The current keyset is left alone; the caller is responsible * for freeing it. * * @param context Context * @param entry HDB entry */ krb5_error_code hdb_add_current_keys_to_history ( krb5_context /*context*/, hdb_entry */*entry*/); /** * This function adds a key to an HDB entry's key history. * * @param context Context * @param entry HDB entry * @param kvno Key version number of the key to add to the history * @param key The Key to add */ krb5_error_code hdb_add_history_key ( krb5_context /*context*/, hdb_entry */*entry*/, krb5_kvno /*kvno*/, Key */*key*/); krb5_error_code hdb_add_master_key ( krb5_context /*context*/, krb5_keyblock */*key*/, hdb_master_key */*inout*/); /** * This function changes an hdb_entry's kvno, swapping the current key * set with a historical keyset. If no historical keys are found then * an error is returned (the caller can still set entry->kvno directly). * * @param context krb5_context * @param new_kvno New kvno for the entry * @param entry hdb_entry to modify */ krb5_error_code hdb_change_kvno ( krb5_context /*context*/, krb5_kvno /*new_kvno*/, hdb_entry */*entry*/); krb5_error_code hdb_check_db_format ( krb5_context /*context*/, HDB */*db*/); krb5_error_code hdb_clear_extension ( krb5_context /*context*/, hdb_entry */*entry*/, int /*type*/); krb5_error_code hdb_clear_master_key ( krb5_context /*context*/, HDB */*db*/); /** * Create a handle for a Kerberos database * * Create a handle for a Kerberos database backend specified by a * filename. Doesn't create a file if its doesn't exists, you have to * use O_CREAT to tell the backend to create the file. */ krb5_error_code hdb_create ( krb5_context /*context*/, HDB **/*db*/, const char */*filename*/); krb5_error_code hdb_db1_create ( krb5_context /*context*/, HDB **/*db*/, const char */*filename*/); krb5_error_code hdb_db3_create ( krb5_context /*context*/, HDB **/*db*/, const char */*filename*/); /** * Return the directory where the hdb database resides. * * @param context Kerberos 5 context. * * @return string pointing to directory. */ const char * hdb_db_dir (krb5_context /*context*/); const char * hdb_dbinfo_get_acl_file ( krb5_context /*context*/, struct hdb_dbinfo */*dbp*/); const krb5_config_binding * hdb_dbinfo_get_binding ( krb5_context /*context*/, struct hdb_dbinfo */*dbp*/); const char * hdb_dbinfo_get_dbname ( krb5_context /*context*/, struct hdb_dbinfo */*dbp*/); const char * hdb_dbinfo_get_label ( krb5_context /*context*/, struct hdb_dbinfo */*dbp*/); const char * hdb_dbinfo_get_log_file ( krb5_context /*context*/, struct hdb_dbinfo */*dbp*/); const char * hdb_dbinfo_get_mkey_file ( krb5_context /*context*/, struct hdb_dbinfo */*dbp*/); struct hdb_dbinfo * hdb_dbinfo_get_next ( struct hdb_dbinfo */*dbp*/, struct hdb_dbinfo */*dbprevp*/); const char * hdb_dbinfo_get_realm ( krb5_context /*context*/, struct hdb_dbinfo */*dbp*/); /** * Return the default hdb database resides. * * @param context Kerberos 5 context. * * @return string pointing to directory. */ const char * hdb_default_db (krb5_context /*context*/); krb5_error_code hdb_enctype2key ( krb5_context /*context*/, hdb_entry */*e*/, const Keys */*keyset*/, krb5_enctype /*enctype*/, Key **/*key*/); krb5_error_code hdb_entry2string ( krb5_context /*context*/, hdb_entry */*ent*/, char **/*str*/); int hdb_entry2value ( krb5_context /*context*/, const hdb_entry */*ent*/, krb5_data */*value*/); int hdb_entry_alias2value ( krb5_context /*context*/, const hdb_entry_alias */*alias*/, krb5_data */*value*/); krb5_error_code hdb_entry_check_mandatory ( krb5_context /*context*/, const hdb_entry */*ent*/); krb5_error_code hdb_entry_clear_kvno_diff_clnt ( krb5_context /*context*/, hdb_entry */*entry*/); krb5_error_code hdb_entry_clear_kvno_diff_svc ( krb5_context /*context*/, hdb_entry */*entry*/); int hdb_entry_clear_password ( krb5_context /*context*/, hdb_entry */*entry*/); krb5_error_code hdb_entry_get_ConstrainedDelegACL ( const hdb_entry */*entry*/, const HDB_Ext_Constrained_delegation_acl **/*a*/); krb5_error_code hdb_entry_get_aliases ( const hdb_entry */*entry*/, const HDB_Ext_Aliases **/*a*/); unsigned int hdb_entry_get_kvno_diff_clnt (const hdb_entry */*entry*/); unsigned int hdb_entry_get_kvno_diff_svc (const hdb_entry */*entry*/); int hdb_entry_get_password ( krb5_context /*context*/, HDB */*db*/, const hdb_entry */*entry*/, char **/*p*/); krb5_error_code hdb_entry_get_pkinit_acl ( const hdb_entry */*entry*/, const HDB_Ext_PKINIT_acl **/*a*/); krb5_error_code hdb_entry_get_pkinit_cert ( const hdb_entry */*entry*/, const HDB_Ext_PKINIT_cert **/*a*/); krb5_error_code hdb_entry_get_pkinit_hash ( const hdb_entry */*entry*/, const HDB_Ext_PKINIT_hash **/*a*/); krb5_error_code hdb_entry_get_pw_change_time ( const hdb_entry */*entry*/, time_t */*t*/); krb5_error_code hdb_entry_set_kvno_diff_clnt ( krb5_context /*context*/, hdb_entry */*entry*/, unsigned int /*diff*/); krb5_error_code hdb_entry_set_kvno_diff_svc ( krb5_context /*context*/, hdb_entry */*entry*/, unsigned int /*diff*/); int hdb_entry_set_password ( krb5_context /*context*/, HDB */*db*/, hdb_entry */*entry*/, const char */*p*/); krb5_error_code hdb_entry_set_pw_change_time ( krb5_context /*context*/, hdb_entry */*entry*/, time_t /*t*/); HDB_extension * hdb_find_extension ( const hdb_entry */*entry*/, int /*type*/); krb5_error_code hdb_foreach ( krb5_context /*context*/, HDB */*db*/, unsigned /*flags*/, hdb_foreach_func_t /*func*/, void */*data*/); void hdb_free_dbinfo ( krb5_context /*context*/, struct hdb_dbinfo **/*dbp*/); void hdb_free_entry ( krb5_context /*context*/, hdb_entry_ex */*ent*/); void hdb_free_key (Key */*key*/); void hdb_free_keys ( krb5_context /*context*/, int /*len*/, Key */*keys*/); void hdb_free_master_key ( krb5_context /*context*/, hdb_master_key /*mkey*/); krb5_error_code hdb_generate_key_set ( krb5_context /*context*/, krb5_principal /*principal*/, krb5_key_salt_tuple */*ks_tuple*/, int /*n_ks_tuple*/, Key **/*ret_key_set*/, size_t */*nkeyset*/, int /*no_salt*/); krb5_error_code hdb_generate_key_set_password ( krb5_context /*context*/, krb5_principal /*principal*/, const char */*password*/, Key **/*keys*/, size_t */*num_keys*/); krb5_error_code hdb_generate_key_set_password_with_ks_tuple ( krb5_context /*context*/, krb5_principal /*principal*/, const char */*password*/, krb5_key_salt_tuple */*ks_tuple*/, int /*n_ks_tuple*/, Key **/*keys*/, size_t */*num_keys*/); int hdb_get_dbinfo ( krb5_context /*context*/, struct hdb_dbinfo **/*dbp*/); krb5_error_code hdb_init_db ( krb5_context /*context*/, HDB */*db*/); int hdb_key2principal ( krb5_context /*context*/, krb5_data */*key*/, krb5_principal /*p*/); krb5_error_code hdb_keytab_create ( krb5_context /*context*/, HDB ** /*db*/, const char */*arg*/); const Keys * hdb_kvno2keys ( krb5_context /*context*/, const hdb_entry */*e*/, krb5_kvno /*kvno*/); krb5_error_code hdb_ldap_create ( krb5_context /*context*/, HDB ** /*db*/, const char */*arg*/); krb5_error_code hdb_ldapi_create ( krb5_context /*context*/, HDB ** /*db*/, const char */*arg*/); krb5_error_code hdb_list_builtin ( krb5_context /*context*/, char **/*list*/); krb5_error_code hdb_lock ( int /*fd*/, int /*operation*/); krb5_error_code hdb_mdb_create ( krb5_context /*context*/, HDB **/*db*/, const char */*filename*/); krb5_error_code hdb_mitdb_create ( krb5_context /*context*/, HDB **/*db*/, const char */*filename*/); krb5_error_code hdb_ndbm_create ( krb5_context /*context*/, HDB **/*db*/, const char */*filename*/); krb5_error_code hdb_next_enctype2key ( krb5_context /*context*/, const hdb_entry */*e*/, const Keys */*keyset*/, krb5_enctype /*enctype*/, Key **/*key*/); int hdb_principal2key ( krb5_context /*context*/, krb5_const_principal /*p*/, krb5_data */*key*/); krb5_error_code hdb_print_entry ( krb5_context /*context*/, HDB */*db*/, hdb_entry_ex */*entry*/, void */*data*/); krb5_error_code hdb_process_master_key ( krb5_context /*context*/, int /*kvno*/, krb5_keyblock */*key*/, krb5_enctype /*etype*/, hdb_master_key */*mkey*/); /** * This function prunes an HDB entry's keys that are too old to have been used * to mint still valid tickets (based on the entry's maximum ticket lifetime). * * @param context Context * @param entry HDB entry */ krb5_error_code hdb_prune_keys ( krb5_context /*context*/, hdb_entry */*entry*/); krb5_error_code hdb_read_master_key ( krb5_context /*context*/, const char */*filename*/, hdb_master_key */*mkey*/); krb5_error_code hdb_replace_extension ( krb5_context /*context*/, hdb_entry */*entry*/, const HDB_extension */*ext*/); krb5_error_code hdb_seal_key ( krb5_context /*context*/, HDB */*db*/, Key */*k*/); krb5_error_code hdb_seal_key_mkey ( krb5_context /*context*/, Key */*k*/, hdb_master_key /*mkey*/); krb5_error_code hdb_seal_keys ( krb5_context /*context*/, HDB */*db*/, hdb_entry */*ent*/); krb5_error_code hdb_seal_keys_mkey ( krb5_context /*context*/, hdb_entry */*ent*/, hdb_master_key /*mkey*/); krb5_error_code hdb_set_last_modified_by ( krb5_context /*context*/, hdb_entry */*entry*/, krb5_principal /*modby*/, time_t /*modtime*/); krb5_error_code hdb_set_master_key ( krb5_context /*context*/, HDB */*db*/, krb5_keyblock */*key*/); krb5_error_code hdb_set_master_keyfile ( krb5_context /*context*/, HDB */*db*/, const char */*keyfile*/); /** * Create SQLITE object, and creates the on disk database if its doesn't exists. * * @param context A Kerberos 5 context. * @param db a returned database handle. * @param filename filename * * @return 0 on success, an error code if not */ krb5_error_code hdb_sqlite_create ( krb5_context /*context*/, HDB **/*db*/, const char */*filename*/); krb5_error_code hdb_unlock (int /*fd*/); krb5_error_code hdb_unseal_key ( krb5_context /*context*/, HDB */*db*/, Key */*k*/); krb5_error_code hdb_unseal_key_mkey ( krb5_context /*context*/, Key */*k*/, hdb_master_key /*mkey*/); krb5_error_code hdb_unseal_keys ( krb5_context /*context*/, HDB */*db*/, hdb_entry */*ent*/); krb5_error_code hdb_unseal_keys_kvno ( krb5_context /*context*/, HDB */*db*/, krb5_kvno /*kvno*/, unsigned /*flags*/, hdb_entry */*ent*/); krb5_error_code hdb_unseal_keys_mkey ( krb5_context /*context*/, hdb_entry */*ent*/, hdb_master_key /*mkey*/); int hdb_value2entry ( krb5_context /*context*/, krb5_data */*value*/, hdb_entry */*ent*/); int hdb_value2entry_alias ( krb5_context /*context*/, krb5_data */*value*/, hdb_entry_alias */*ent*/); krb5_error_code hdb_write_master_key ( krb5_context /*context*/, const char */*filename*/, hdb_master_key /*mkey*/); #ifdef __cplusplus } #endif #endif /* DOXY */ #endif /* __hdb_protos_h__ */ heimdal-7.5.0/lib/hdb/hdb-keytab.c0000644000175000017500000001344213026237312014736 0ustar niknik/* * Copyright (c) 2009 Kungliga Tekniska Hgskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Portions Copyright (c) 2009 Apple Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "hdb_locl.h" #include typedef struct { char *path; krb5_keytab keytab; } *hdb_keytab; /* * */ static krb5_error_code hkt_close(krb5_context context, HDB *db) { hdb_keytab k = (hdb_keytab)db->hdb_db; krb5_error_code ret; assert(k->keytab); ret = krb5_kt_close(context, k->keytab); k->keytab = NULL; return ret; } static krb5_error_code hkt_destroy(krb5_context context, HDB *db) { hdb_keytab k = (hdb_keytab)db->hdb_db; krb5_error_code ret; ret = hdb_clear_master_key (context, db); free(k->path); free(k); free(db->hdb_name); free(db); return ret; } static krb5_error_code hkt_lock(krb5_context context, HDB *db, int operation) { return 0; } static krb5_error_code hkt_unlock(krb5_context context, HDB *db) { return 0; } static krb5_error_code hkt_firstkey(krb5_context context, HDB *db, unsigned flags, hdb_entry_ex *entry) { return HDB_ERR_DB_INUSE; } static krb5_error_code hkt_nextkey(krb5_context context, HDB * db, unsigned flags, hdb_entry_ex * entry) { return HDB_ERR_DB_INUSE; } static krb5_error_code hkt_open(krb5_context context, HDB * db, int flags, mode_t mode) { hdb_keytab k = (hdb_keytab)db->hdb_db; krb5_error_code ret; assert(k->keytab == NULL); ret = krb5_kt_resolve(context, k->path, &k->keytab); if (ret) return ret; return 0; } static krb5_error_code hkt_fetch_kvno(krb5_context context, HDB * db, krb5_const_principal principal, unsigned flags, krb5_kvno kvno, hdb_entry_ex * entry) { hdb_keytab k = (hdb_keytab)db->hdb_db; krb5_error_code ret; krb5_keytab_entry ktentry; if (!(flags & HDB_F_KVNO_SPECIFIED)) { /* Preserve previous behaviour if no kvno specified */ kvno = 0; } memset(&ktentry, 0, sizeof(ktentry)); entry->entry.flags.server = 1; entry->entry.flags.forwardable = 1; entry->entry.flags.renewable = 1; /* Not recorded in the OD backend, make something up */ ret = krb5_parse_name(context, "hdb/keytab@WELL-KNOWN:KEYTAB-BACKEND", &entry->entry.created_by.principal); if (ret) goto out; /* * XXX really needs to try all enctypes and just not pick the * first one, even if that happens to be des3-cbc-sha1 (ie best * enctype) in the Apple case. A while loop over all known * enctypes should work. */ ret = krb5_kt_get_entry(context, k->keytab, principal, kvno, 0, &ktentry); if (ret) { ret = HDB_ERR_NOENTRY; goto out; } ret = krb5_copy_principal(context, principal, &entry->entry.principal); if (ret) goto out; ret = _hdb_keytab2hdb_entry(context, &ktentry, entry); out: if (ret) { free_hdb_entry(&entry->entry); memset(&entry->entry, 0, sizeof(entry->entry)); } krb5_kt_free_entry(context, &ktentry); return ret; } static krb5_error_code hkt_store(krb5_context context, HDB * db, unsigned flags, hdb_entry_ex * entry) { return HDB_ERR_DB_INUSE; } krb5_error_code hdb_keytab_create(krb5_context context, HDB ** db, const char *arg) { hdb_keytab k; *db = calloc(1, sizeof(**db)); if (*db == NULL) { krb5_set_error_message(context, ENOMEM, "malloc: out of memory"); return ENOMEM; } memset(*db, 0, sizeof(**db)); k = calloc(1, sizeof(*k)); if (k == NULL) { free(*db); *db = NULL; krb5_set_error_message(context, ENOMEM, "malloc: out of memory"); return ENOMEM; } k->path = strdup(arg); if (k->path == NULL) { free(k); free(*db); *db = NULL; krb5_set_error_message(context, ENOMEM, "malloc: out of memory"); return ENOMEM; } (*db)->hdb_db = k; (*db)->hdb_master_key_set = 0; (*db)->hdb_openp = 0; (*db)->hdb_open = hkt_open; (*db)->hdb_close = hkt_close; (*db)->hdb_fetch_kvno = hkt_fetch_kvno; (*db)->hdb_store = hkt_store; (*db)->hdb_remove = NULL; (*db)->hdb_firstkey = hkt_firstkey; (*db)->hdb_nextkey = hkt_nextkey; (*db)->hdb_lock = hkt_lock; (*db)->hdb_unlock = hkt_unlock; (*db)->hdb_rename = NULL; (*db)->hdb__get = NULL; (*db)->hdb__put = NULL; (*db)->hdb__del = NULL; (*db)->hdb_destroy = hkt_destroy; return 0; } heimdal-7.5.0/lib/hdb/hdb.c0000644000175000017500000003213513026237312013461 0ustar niknik/* * Copyright (c) 1997 - 2008 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Portions Copyright (c) 2009 Apple Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "krb5_locl.h" #include "hdb_locl.h" #ifdef HAVE_DLFCN_H #include #endif /*! @mainpage Heimdal database backend library * * @section intro Introduction * * Heimdal libhdb library provides the backend support for Heimdal kdc * and kadmind. Its here where plugins for diffrent database engines * can be pluged in and extend support for here Heimdal get the * principal and policy data from. * * Example of Heimdal backend are: * - Berkeley DB 1.85 * - Berkeley DB 3.0 * - Berkeley DB 4.0 * - New Berkeley DB * - LDAP * * * The project web page: http://www.h5l.org/ * */ const int hdb_interface_version = HDB_INTERFACE_VERSION; static struct hdb_method methods[] = { /* "db:" should be db3 if we have db3, or db1 if we have db1 */ #if HAVE_DB3 { HDB_INTERFACE_VERSION, NULL, NULL, "db:", hdb_db3_create}, #elif HAVE_DB1 { HDB_INTERFACE_VERSION, NULL, NULL, "db:", hdb_db1_create}, #endif #if HAVE_DB1 { HDB_INTERFACE_VERSION, NULL, NULL, "db1:", hdb_db1_create}, #endif #if HAVE_DB3 { HDB_INTERFACE_VERSION, NULL, NULL, "db3:", hdb_db3_create}, #endif #if HAVE_DB1 { HDB_INTERFACE_VERSION, NULL, NULL, "mit-db:", hdb_mitdb_create}, #endif #if HAVE_LMDB { HDB_INTERFACE_VERSION, NULL, NULL, "mdb:", hdb_mdb_create}, { HDB_INTERFACE_VERSION, NULL, NULL, "lmdb:", hdb_mdb_create}, #endif #if HAVE_NDBM { HDB_INTERFACE_VERSION, NULL, NULL, "ndbm:", hdb_ndbm_create}, #endif { HDB_INTERFACE_VERSION, NULL, NULL, "keytab:", hdb_keytab_create}, #if defined(OPENLDAP) && !defined(OPENLDAP_MODULE) { HDB_INTERFACE_VERSION, NULL, NULL, "ldap:", hdb_ldap_create}, { HDB_INTERFACE_VERSION, NULL, NULL, "ldapi:", hdb_ldapi_create}, #elif defined(OPENLDAP) { HDB_INTERFACE_VERSION, NULL, NULL, "ldap:", NULL}, { HDB_INTERFACE_VERSION, NULL, NULL, "ldapi:", NULL}, #endif #ifdef HAVE_SQLITE3 { HDB_INTERFACE_VERSION, NULL, NULL, "sqlite:", hdb_sqlite_create}, #endif { 0, NULL, NULL, NULL, NULL} }; /* * It'd be nice if we could try opening an HDB with each supported * backend until one works or all fail. It may not be possible for all * flavors, but where it's possible we should. */ #if defined(HAVE_LMDB) static struct hdb_method default_dbmethod = { HDB_INTERFACE_VERSION, NULL, NULL, "", hdb_mdb_create }; #elif defined(HAVE_DB3) static struct hdb_method default_dbmethod = { HDB_INTERFACE_VERSION, NULL, NULL, "", hdb_db3_create }; #elif defined(HAVE_DB1) static struct hdb_method default_dbmethod = { HDB_INTERFACE_VERSION, NULL, NULL, "", hdb_db1_create }; #elif defined(HAVE_NDBM) static struct hdb_method default_dbmethod = { HDB_INTERFACE_VERSION, NULL, NULL, "", hdb_ndbm_create }; #endif const Keys * hdb_kvno2keys(krb5_context context, const hdb_entry *e, krb5_kvno kvno) { HDB_Ext_KeySet *hist_keys; HDB_extension *extp; size_t i; if (kvno == 0) return &e->keys; extp = hdb_find_extension(e, choice_HDB_extension_data_hist_keys); if (extp == NULL) return 0; hist_keys = &extp->data.u.hist_keys; for (i = 0; i < hist_keys->len; i++) { if (hist_keys->val[i].kvno == kvno) return &hist_keys->val[i].keys; } return NULL; } krb5_error_code hdb_next_enctype2key(krb5_context context, const hdb_entry *e, const Keys *keyset, krb5_enctype enctype, Key **key) { const Keys *keys = keyset ? keyset : &e->keys; Key *k; for (k = *key ? (*key) + 1 : keys->val; k < keys->val + keys->len; k++) { if(k->key.keytype == enctype){ *key = k; return 0; } } krb5_set_error_message(context, KRB5_PROG_ETYPE_NOSUPP, "No next enctype %d for hdb-entry", (int)enctype); return KRB5_PROG_ETYPE_NOSUPP; /* XXX */ } krb5_error_code hdb_enctype2key(krb5_context context, hdb_entry *e, const Keys *keyset, krb5_enctype enctype, Key **key) { *key = NULL; return hdb_next_enctype2key(context, e, keyset, enctype, key); } void hdb_free_key(Key *key) { memset(key->key.keyvalue.data, 0, key->key.keyvalue.length); free_Key(key); free(key); } krb5_error_code hdb_lock(int fd, int operation) { int i, code = 0; for(i = 0; i < 3; i++){ code = flock(fd, (operation == HDB_RLOCK ? LOCK_SH : LOCK_EX) | LOCK_NB); if(code == 0 || errno != EWOULDBLOCK) break; sleep(1); } if(code == 0) return 0; if(errno == EWOULDBLOCK) return HDB_ERR_DB_INUSE; return HDB_ERR_CANT_LOCK_DB; } krb5_error_code hdb_unlock(int fd) { int code; code = flock(fd, LOCK_UN); if(code) return 4711 /* XXX */; return 0; } void hdb_free_entry(krb5_context context, hdb_entry_ex *ent) { Key *k; size_t i; if (ent->free_entry) (*ent->free_entry)(context, ent); for(i = 0; i < ent->entry.keys.len; i++) { k = &ent->entry.keys.val[i]; memset (k->key.keyvalue.data, 0, k->key.keyvalue.length); } free_hdb_entry(&ent->entry); } krb5_error_code hdb_foreach(krb5_context context, HDB *db, unsigned flags, hdb_foreach_func_t func, void *data) { krb5_error_code ret; hdb_entry_ex entry; ret = db->hdb_firstkey(context, db, flags, &entry); if (ret == 0) krb5_clear_error_message(context); while(ret == 0){ ret = (*func)(context, db, &entry, data); hdb_free_entry(context, &entry); if(ret == 0) ret = db->hdb_nextkey(context, db, flags, &entry); } if(ret == HDB_ERR_NOENTRY) ret = 0; return ret; } krb5_error_code hdb_check_db_format(krb5_context context, HDB *db) { krb5_data tag; krb5_data version; krb5_error_code ret, ret2; unsigned ver; int foo; ret = db->hdb_lock(context, db, HDB_RLOCK); if (ret) return ret; tag.data = (void *)(intptr_t)HDB_DB_FORMAT_ENTRY; tag.length = strlen(tag.data); ret = (*db->hdb__get)(context, db, tag, &version); ret2 = db->hdb_unlock(context, db); if(ret) return ret; if (ret2) return ret2; foo = sscanf(version.data, "%u", &ver); krb5_data_free (&version); if (foo != 1) return HDB_ERR_BADVERSION; if(ver != HDB_DB_FORMAT) return HDB_ERR_BADVERSION; return 0; } krb5_error_code hdb_init_db(krb5_context context, HDB *db) { krb5_error_code ret, ret2; krb5_data tag; krb5_data version; char ver[32]; ret = hdb_check_db_format(context, db); if(ret != HDB_ERR_NOENTRY) return ret; ret = db->hdb_lock(context, db, HDB_WLOCK); if (ret) return ret; tag.data = (void *)(intptr_t)HDB_DB_FORMAT_ENTRY; tag.length = strlen(tag.data); snprintf(ver, sizeof(ver), "%u", HDB_DB_FORMAT); version.data = ver; version.length = strlen(version.data) + 1; /* zero terminated */ ret = (*db->hdb__put)(context, db, 0, tag, version); ret2 = db->hdb_unlock(context, db); if (ret) { if (ret2) krb5_clear_error_message(context); return ret; } return ret2; } /* * find the relevant method for `filename', returning a pointer to the * rest in `rest'. * return NULL if there's no such method. */ static const struct hdb_method * find_method (const char *filename, const char **rest) { const struct hdb_method *h; for (h = methods; h->prefix != NULL; ++h) { if (strncmp (filename, h->prefix, strlen(h->prefix)) == 0) { *rest = filename + strlen(h->prefix); return h; } } #if defined(HAVE_DB1) || defined(HAVE_DB3) || defined(HAVE_LMDB) || defined(HAVE_NDBM) if (strncmp(filename, "/", sizeof("/") - 1) == 0 || strncmp(filename, "./", sizeof("./") - 1) == 0 || strncmp(filename, "../", sizeof("../") - 1) == 0 #ifdef WIN32 || strncmp(filename, "\\\\", sizeof("\\\\") - 1) || (isalpha(filename[0]) && filename[1] == ':') #endif ) { *rest = filename; return &default_dbmethod; } #endif return NULL; } struct cb_s { const char *residual; const char *filename; const struct hdb_method *h; }; static krb5_error_code KRB5_LIB_CALL callback(krb5_context context, const void *plug, void *plugctx, void *userctx) { const struct hdb_method *h = (const struct hdb_method *)plug; struct cb_s *cb_ctx = (struct cb_s *)userctx; if (strncmp(cb_ctx->filename, h->prefix, strlen(h->prefix)) == 0) { cb_ctx->residual = cb_ctx->filename + strlen(h->prefix) + 1; cb_ctx->h = h; return 0; } return KRB5_PLUGIN_NO_HANDLE; } static char * make_sym(const char *prefix) { char *s, *sym; errno = 0; if (prefix == NULL || prefix[0] == '\0') return NULL; if ((s = strdup(prefix)) == NULL) return NULL; if (strchr(s, ':') != NULL) *strchr(s, ':') = '\0'; if (asprintf(&sym, "hdb_%s_interface", s) == -1) sym = NULL; free(s); return sym; } krb5_error_code hdb_list_builtin(krb5_context context, char **list) { const struct hdb_method *h; size_t len = 0; char *buf = NULL; for (h = methods; h->prefix != NULL; ++h) { if (h->prefix[0] == '\0') continue; len += strlen(h->prefix) + 2; } len += 1; buf = malloc(len); if (buf == NULL) { return krb5_enomem(context); } buf[0] = '\0'; for (h = methods; h->prefix != NULL; ++h) { if (h->create == NULL) { struct cb_s cb_ctx; char *f; char *sym; /* Try loading the plugin */ if (asprintf(&f, "%sfoo", h->prefix) == -1) f = NULL; if ((sym = make_sym(h->prefix)) == NULL) { free(buf); free(f); return krb5_enomem(context); } cb_ctx.filename = f; cb_ctx.residual = NULL; cb_ctx.h = NULL; (void)_krb5_plugin_run_f(context, "krb5", sym, HDB_INTERFACE_VERSION, 0, &cb_ctx, callback); free(f); free(sym); if (cb_ctx.h == NULL || cb_ctx.h->create == NULL) continue; } if (h != methods) strlcat(buf, ", ", len); strlcat(buf, h->prefix, len); } *list = buf; return 0; } krb5_error_code _hdb_keytab2hdb_entry(krb5_context context, const krb5_keytab_entry *ktentry, hdb_entry_ex *entry) { entry->entry.kvno = ktentry->vno; entry->entry.created_by.time = ktentry->timestamp; entry->entry.keys.val = calloc(1, sizeof(entry->entry.keys.val[0])); if (entry->entry.keys.val == NULL) return ENOMEM; entry->entry.keys.len = 1; entry->entry.keys.val[0].mkvno = NULL; entry->entry.keys.val[0].salt = NULL; return krb5_copy_keyblock_contents(context, &ktentry->keyblock, &entry->entry.keys.val[0].key); } /** * Create a handle for a Kerberos database * * Create a handle for a Kerberos database backend specified by a * filename. Doesn't create a file if its doesn't exists, you have to * use O_CREAT to tell the backend to create the file. */ krb5_error_code hdb_create(krb5_context context, HDB **db, const char *filename) { struct cb_s cb_ctx; if (filename == NULL) filename = HDB_DEFAULT_DB; cb_ctx.h = find_method (filename, &cb_ctx.residual); cb_ctx.filename = filename; if (cb_ctx.h == NULL || cb_ctx.h->create == NULL) { char *sym; if ((sym = make_sym(filename)) == NULL) return krb5_enomem(context); (void)_krb5_plugin_run_f(context, "krb5", sym, HDB_INTERFACE_VERSION, 0, &cb_ctx, callback); free(sym); } if (cb_ctx.h == NULL) krb5_errx(context, 1, "No database support for %s", cb_ctx.filename); return (*cb_ctx.h->create)(context, db, cb_ctx.residual); } heimdal-7.5.0/lib/hdb/hdb-ldap.c0000644000175000017500000014541113212137553014404 0ustar niknik/* * Copyright (c) 1999-2001, 2003, PADL Software Pty Ltd. * Copyright (c) 2004, Andrew Bartlett. * Copyright (c) 2003 - 2008, Kungliga Tekniska Högskolan. * Copyright (c) 2015, Timothy Pearson. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of PADL Software nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY PADL SOFTWARE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL PADL SOFTWARE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "hdb_locl.h" #ifdef OPENLDAP #include #include #include #include static krb5_error_code LDAP__connect(krb5_context context, HDB *); static krb5_error_code LDAP_close(krb5_context context, HDB *); static krb5_error_code LDAP_message2entry(krb5_context context, HDB * db, LDAPMessage * msg, int flags, hdb_entry_ex * ent); static const char *default_structural_object = "account"; static char *structural_object; static const char *default_ldap_url = "ldapi:///"; static krb5_boolean samba_forwardable; struct hdbldapdb { LDAP *h_lp; int h_msgid; char *h_base; char *h_url; char *h_bind_dn; char *h_bind_password; krb5_boolean h_start_tls; char *h_createbase; }; #define HDB2LDAP(db) (((struct hdbldapdb *)(db)->hdb_db)->h_lp) #define HDB2MSGID(db) (((struct hdbldapdb *)(db)->hdb_db)->h_msgid) #define HDBSETMSGID(db,msgid) \ do { ((struct hdbldapdb *)(db)->hdb_db)->h_msgid = msgid; } while(0) #define HDB2BASE(dn) (((struct hdbldapdb *)(db)->hdb_db)->h_base) #define HDB2URL(dn) (((struct hdbldapdb *)(db)->hdb_db)->h_url) #define HDB2BINDDN(db) (((struct hdbldapdb *)(db)->hdb_db)->h_bind_dn) #define HDB2BINDPW(db) (((struct hdbldapdb *)(db)->hdb_db)->h_bind_password) #define HDB2CREATE(db) (((struct hdbldapdb *)(db)->hdb_db)->h_createbase) /* * */ static char * krb5kdcentry_attrs[] = { "cn", "createTimestamp", "creatorsName", "krb5EncryptionType", "krb5KDCFlags", "krb5Key", "krb5KeyVersionNumber", "krb5MaxLife", "krb5MaxRenew", "krb5PasswordEnd", "krb5PrincipalName", "krb5PrincipalRealm", "krb5ExtendedAttributes", "krb5ValidEnd", "krb5ValidStart", "modifiersName", "modifyTimestamp", "objectClass", "sambaAcctFlags", "sambaKickoffTime", "sambaNTPassword", "sambaPwdLastSet", "sambaPwdMustChange", "uid", NULL }; static char *krb5principal_attrs[] = { "cn", "createTimestamp", "creatorsName", "krb5PrincipalName", "krb5PrincipalRealm", "modifiersName", "modifyTimestamp", "objectClass", "uid", NULL }; static int LDAP_no_size_limit(krb5_context context, LDAP *lp) { int ret, limit = LDAP_NO_LIMIT; ret = ldap_set_option(lp, LDAP_OPT_SIZELIMIT, (const void *)&limit); if (ret != LDAP_SUCCESS) { krb5_set_error_message(context, HDB_ERR_BADVERSION, "ldap_set_option: %s", ldap_err2string(ret)); return HDB_ERR_BADVERSION; } return 0; } static int check_ldap(krb5_context context, HDB *db, int ret) { switch (ret) { case LDAP_SUCCESS: return 0; case LDAP_SERVER_DOWN: LDAP_close(context, db); return 1; default: return 1; } } static krb5_error_code LDAP__setmod(LDAPMod *** modlist, int modop, const char *attribute, int *pIndex) { int cMods; if (*modlist == NULL) { *modlist = (LDAPMod **)ber_memcalloc(1, sizeof(LDAPMod *)); if (*modlist == NULL) return ENOMEM; } for (cMods = 0; (*modlist)[cMods] != NULL; cMods++) { if ((*modlist)[cMods]->mod_op == modop && strcasecmp((*modlist)[cMods]->mod_type, attribute) == 0) { break; } } *pIndex = cMods; if ((*modlist)[cMods] == NULL) { LDAPMod *mod; *modlist = (LDAPMod **)ber_memrealloc(*modlist, (cMods + 2) * sizeof(LDAPMod *)); if (*modlist == NULL) return ENOMEM; (*modlist)[cMods] = (LDAPMod *)ber_memalloc(sizeof(LDAPMod)); if ((*modlist)[cMods] == NULL) return ENOMEM; mod = (*modlist)[cMods]; mod->mod_op = modop; mod->mod_type = ber_strdup(attribute); if (mod->mod_type == NULL) { ber_memfree(mod); (*modlist)[cMods] = NULL; return ENOMEM; } if (modop & LDAP_MOD_BVALUES) { mod->mod_bvalues = NULL; } else { mod->mod_values = NULL; } (*modlist)[cMods + 1] = NULL; } return 0; } static krb5_error_code LDAP_addmod_len(LDAPMod *** modlist, int modop, const char *attribute, unsigned char *value, size_t len) { krb5_error_code ret; int cMods, i = 0; ret = LDAP__setmod(modlist, modop | LDAP_MOD_BVALUES, attribute, &cMods); if (ret) return ret; if (value != NULL) { struct berval **bv; bv = (*modlist)[cMods]->mod_bvalues; if (bv != NULL) { for (i = 0; bv[i] != NULL; i++) ; bv = ber_memrealloc(bv, (i + 2) * sizeof(*bv)); } else bv = ber_memalloc(2 * sizeof(*bv)); if (bv == NULL) return ENOMEM; (*modlist)[cMods]->mod_bvalues = bv; bv[i] = ber_memalloc(sizeof(**bv));; if (bv[i] == NULL) return ENOMEM; bv[i]->bv_val = (void *)value; bv[i]->bv_len = len; bv[i + 1] = NULL; } return 0; } static krb5_error_code LDAP_addmod(LDAPMod *** modlist, int modop, const char *attribute, const char *value) { int cMods, i = 0; krb5_error_code ret; ret = LDAP__setmod(modlist, modop, attribute, &cMods); if (ret) return ret; if (value != NULL) { char **bv; bv = (*modlist)[cMods]->mod_values; if (bv != NULL) { for (i = 0; bv[i] != NULL; i++) ; bv = ber_memrealloc(bv, (i + 2) * sizeof(*bv)); } else bv = ber_memalloc(2 * sizeof(*bv)); if (bv == NULL) return ENOMEM; (*modlist)[cMods]->mod_values = bv; bv[i] = ber_strdup(value); if (bv[i] == NULL) return ENOMEM; bv[i + 1] = NULL; } return 0; } static krb5_error_code LDAP_addmod_generalized_time(LDAPMod *** mods, int modop, const char *attribute, KerberosTime * time) { char buf[22]; struct tm *tm; /* XXX not threadsafe */ tm = gmtime(time); strftime(buf, sizeof(buf), "%Y%m%d%H%M%SZ", tm); return LDAP_addmod(mods, modop, attribute, buf); } static krb5_error_code LDAP_addmod_integer(krb5_context context, LDAPMod *** mods, int modop, const char *attribute, unsigned long l) { krb5_error_code ret; char *buf; ret = asprintf(&buf, "%ld", l); if (ret < 0) { krb5_set_error_message(context, ENOMEM, "asprintf: out of memory:"); return ENOMEM; } ret = LDAP_addmod(mods, modop, attribute, buf); free (buf); return ret; } static krb5_error_code LDAP_get_string_value(HDB * db, LDAPMessage * entry, const char *attribute, char **ptr) { struct berval **vals; vals = ldap_get_values_len(HDB2LDAP(db), entry, attribute); if (vals == NULL || vals[0] == NULL) { *ptr = NULL; return HDB_ERR_NOENTRY; } *ptr = malloc(vals[0]->bv_len + 1); if (*ptr == NULL) { ldap_value_free_len(vals); return ENOMEM; } memcpy(*ptr, vals[0]->bv_val, vals[0]->bv_len); (*ptr)[vals[0]->bv_len] = 0; ldap_value_free_len(vals); return 0; } static krb5_error_code LDAP_get_integer_value(HDB * db, LDAPMessage * entry, const char *attribute, int *ptr) { krb5_error_code ret; char *val; ret = LDAP_get_string_value(db, entry, attribute, &val); if (ret) return ret; *ptr = atoi(val); free(val); return 0; } static krb5_error_code LDAP_get_generalized_time_value(HDB * db, LDAPMessage * entry, const char *attribute, KerberosTime * kt) { char *tmp, *gentime; struct tm tm; int ret; *kt = 0; ret = LDAP_get_string_value(db, entry, attribute, &gentime); if (ret) return ret; tmp = strptime(gentime, "%Y%m%d%H%M%SZ", &tm); if (tmp == NULL) { free(gentime); return HDB_ERR_NOENTRY; } free(gentime); *kt = timegm(&tm); return 0; } static int bervalstrcmp(struct berval *v, const char *str) { size_t len = strlen(str); return (v->bv_len == len) && strncasecmp(str, (char *)v->bv_val, len) == 0; } static krb5_error_code LDAP_entry2mods(krb5_context context, HDB * db, hdb_entry_ex * ent, LDAPMessage * msg, LDAPMod *** pmods) { krb5_error_code ret; krb5_boolean is_new_entry; char *tmp = NULL; LDAPMod **mods = NULL; hdb_entry_ex orig; unsigned long oflags, nflags; int i; krb5_boolean is_samba_account = FALSE; krb5_boolean is_account = FALSE; krb5_boolean is_heimdal_entry = FALSE; krb5_boolean is_heimdal_principal = FALSE; struct berval **vals; *pmods = NULL; if (msg != NULL) { ret = LDAP_message2entry(context, db, msg, 0, &orig); if (ret) goto out; is_new_entry = FALSE; vals = ldap_get_values_len(HDB2LDAP(db), msg, "objectClass"); if (vals) { int num_objectclasses = ldap_count_values_len(vals); for (i=0; i < num_objectclasses; i++) { if (bervalstrcmp(vals[i], "sambaSamAccount")) is_samba_account = TRUE; else if (bervalstrcmp(vals[i], structural_object)) is_account = TRUE; else if (bervalstrcmp(vals[i], "krb5Principal")) is_heimdal_principal = TRUE; else if (bervalstrcmp(vals[i], "krb5KDCEntry")) is_heimdal_entry = TRUE; } ldap_value_free_len(vals); } /* * If this is just a "account" entry and no other objectclass * is hanging on this entry, it's really a new entry. */ if (is_samba_account == FALSE && is_heimdal_principal == FALSE && is_heimdal_entry == FALSE) { if (is_account == TRUE) { is_new_entry = TRUE; } else { ret = HDB_ERR_NOENTRY; goto out; } } } else is_new_entry = TRUE; if (is_new_entry) { /* to make it perfectly obvious we're depending on * orig being intiialized to zero */ memset(&orig, 0, sizeof(orig)); ret = LDAP_addmod(&mods, LDAP_MOD_ADD, "objectClass", "top"); if (ret) goto out; /* account is the structural object class */ if (is_account == FALSE) { ret = LDAP_addmod(&mods, LDAP_MOD_ADD, "objectClass", structural_object); is_account = TRUE; if (ret) goto out; } ret = LDAP_addmod(&mods, LDAP_MOD_ADD, "objectClass", "krb5Principal"); is_heimdal_principal = TRUE; if (ret) goto out; ret = LDAP_addmod(&mods, LDAP_MOD_ADD, "objectClass", "krb5KDCEntry"); is_heimdal_entry = TRUE; if (ret) goto out; } if (is_new_entry || krb5_principal_compare(context, ent->entry.principal, orig.entry.principal) == FALSE) { if (is_heimdal_principal || is_heimdal_entry) { ret = krb5_unparse_name(context, ent->entry.principal, &tmp); if (ret) goto out; ret = LDAP_addmod(&mods, LDAP_MOD_REPLACE, "krb5PrincipalName", tmp); if (ret) { free(tmp); goto out; } free(tmp); } if (is_account || is_samba_account) { ret = krb5_unparse_name_short(context, ent->entry.principal, &tmp); if (ret) goto out; ret = LDAP_addmod(&mods, LDAP_MOD_REPLACE, "uid", tmp); if (ret) { free(tmp); goto out; } free(tmp); } } if (is_heimdal_entry && (ent->entry.kvno != orig.entry.kvno || is_new_entry)) { ret = LDAP_addmod_integer(context, &mods, LDAP_MOD_REPLACE, "krb5KeyVersionNumber", ent->entry.kvno); if (ret) goto out; } if (is_heimdal_entry && ent->entry.extensions) { if (!is_new_entry) { vals = ldap_get_values_len(HDB2LDAP(db), msg, "krb5ExtendedAttributes"); if (vals) { ldap_value_free_len(vals); ret = LDAP_addmod(&mods, LDAP_MOD_DELETE, "krb5ExtendedAttributes", NULL); if (ret) goto out; } } for (i = 0; i < ent->entry.extensions->len; i++) { unsigned char *buf; size_t size, sz = 0; ASN1_MALLOC_ENCODE(HDB_extension, buf, size, &ent->entry.extensions->val[i], &sz, ret); if (ret) goto out; if (size != sz) krb5_abortx(context, "internal error in ASN.1 encoder"); ret = LDAP_addmod_len(&mods, LDAP_MOD_ADD, "krb5ExtendedAttributes", buf, sz); if (ret) goto out; } } if (is_heimdal_entry && ent->entry.valid_start) { if (orig.entry.valid_end == NULL || (*(ent->entry.valid_start) != *(orig.entry.valid_start))) { ret = LDAP_addmod_generalized_time(&mods, LDAP_MOD_REPLACE, "krb5ValidStart", ent->entry.valid_start); if (ret) goto out; } } if (ent->entry.valid_end) { if (orig.entry.valid_end == NULL || (*(ent->entry.valid_end) != *(orig.entry.valid_end))) { if (is_heimdal_entry) { ret = LDAP_addmod_generalized_time(&mods, LDAP_MOD_REPLACE, "krb5ValidEnd", ent->entry.valid_end); if (ret) goto out; } if (is_samba_account) { ret = LDAP_addmod_integer(context, &mods, LDAP_MOD_REPLACE, "sambaKickoffTime", *(ent->entry.valid_end)); if (ret) goto out; } } } if (ent->entry.pw_end) { if (orig.entry.pw_end == NULL || (*(ent->entry.pw_end) != *(orig.entry.pw_end))) { if (is_heimdal_entry) { ret = LDAP_addmod_generalized_time(&mods, LDAP_MOD_REPLACE, "krb5PasswordEnd", ent->entry.pw_end); if (ret) goto out; } if (is_samba_account) { ret = LDAP_addmod_integer(context, &mods, LDAP_MOD_REPLACE, "sambaPwdMustChange", *(ent->entry.pw_end)); if (ret) goto out; } } } #if 0 /* we we have last_pw_change */ if (is_samba_account && ent->entry.last_pw_change) { if (orig.entry.last_pw_change == NULL || (*(ent->entry.last_pw_change) != *(orig.entry.last_pw_change))) { ret = LDAP_addmod_integer(context, &mods, LDAP_MOD_REPLACE, "sambaPwdLastSet", *(ent->entry.last_pw_change)); if (ret) goto out; } } #endif if (is_heimdal_entry && ent->entry.max_life) { if (orig.entry.max_life == NULL || (*(ent->entry.max_life) != *(orig.entry.max_life))) { ret = LDAP_addmod_integer(context, &mods, LDAP_MOD_REPLACE, "krb5MaxLife", *(ent->entry.max_life)); if (ret) goto out; } } if (is_heimdal_entry && ent->entry.max_renew) { if (orig.entry.max_renew == NULL || (*(ent->entry.max_renew) != *(orig.entry.max_renew))) { ret = LDAP_addmod_integer(context, &mods, LDAP_MOD_REPLACE, "krb5MaxRenew", *(ent->entry.max_renew)); if (ret) goto out; } } oflags = HDBFlags2int(orig.entry.flags); nflags = HDBFlags2int(ent->entry.flags); if (is_heimdal_entry && oflags != nflags) { ret = LDAP_addmod_integer(context, &mods, LDAP_MOD_REPLACE, "krb5KDCFlags", nflags); if (ret) goto out; } /* Remove keys if they exists, and then replace keys. */ if (!is_new_entry && orig.entry.keys.len > 0) { vals = ldap_get_values_len(HDB2LDAP(db), msg, "krb5Key"); if (vals) { ldap_value_free_len(vals); ret = LDAP_addmod(&mods, LDAP_MOD_DELETE, "krb5Key", NULL); if (ret) goto out; } } for (i = 0; i < ent->entry.keys.len; i++) { if (is_samba_account && ent->entry.keys.val[i].key.keytype == ETYPE_ARCFOUR_HMAC_MD5) { char *ntHexPassword; char *nt; time_t now = time(NULL); /* the key might have been 'sealed', but samba passwords are clear in the directory */ ret = hdb_unseal_key(context, db, &ent->entry.keys.val[i]); if (ret) goto out; nt = ent->entry.keys.val[i].key.keyvalue.data; /* store in ntPassword, not krb5key */ ret = hex_encode(nt, 16, &ntHexPassword); if (ret < 0) { ret = ENOMEM; krb5_set_error_message(context, ret, "hdb-ldap: failed to " "hex encode key"); goto out; } ret = LDAP_addmod(&mods, LDAP_MOD_REPLACE, "sambaNTPassword", ntHexPassword); free(ntHexPassword); if (ret) goto out; ret = LDAP_addmod_integer(context, &mods, LDAP_MOD_REPLACE, "sambaPwdLastSet", now); if (ret) goto out; /* have to kill the LM passwod if it exists */ vals = ldap_get_values_len(HDB2LDAP(db), msg, "sambaLMPassword"); if (vals) { ldap_value_free_len(vals); ret = LDAP_addmod(&mods, LDAP_MOD_DELETE, "sambaLMPassword", NULL); if (ret) goto out; } } else if (is_heimdal_entry) { unsigned char *buf; size_t len, buf_size; ASN1_MALLOC_ENCODE(Key, buf, buf_size, &ent->entry.keys.val[i], &len, ret); if (ret) goto out; if(buf_size != len) krb5_abortx(context, "internal error in ASN.1 encoder"); /* addmod_len _owns_ the key, doesn't need to copy it */ ret = LDAP_addmod_len(&mods, LDAP_MOD_ADD, "krb5Key", buf, len); if (ret) goto out; } } if (ent->entry.etypes) { int add_krb5EncryptionType = 0; /* * Only add/modify krb5EncryptionType if it's a new heimdal * entry or krb5EncryptionType already exists on the entry. */ if (!is_new_entry) { vals = ldap_get_values_len(HDB2LDAP(db), msg, "krb5EncryptionType"); if (vals) { ldap_value_free_len(vals); ret = LDAP_addmod(&mods, LDAP_MOD_DELETE, "krb5EncryptionType", NULL); if (ret) goto out; add_krb5EncryptionType = 1; } } else if (is_heimdal_entry) add_krb5EncryptionType = 1; if (add_krb5EncryptionType) { for (i = 0; i < ent->entry.etypes->len; i++) { if (is_samba_account && ent->entry.keys.val[i].key.keytype == ETYPE_ARCFOUR_HMAC_MD5) { ; } else if (is_heimdal_entry) { ret = LDAP_addmod_integer(context, &mods, LDAP_MOD_ADD, "krb5EncryptionType", ent->entry.etypes->val[i]); if (ret) goto out; } } } } /* for clarity */ ret = 0; out: if (ret == 0) *pmods = mods; else if (mods != NULL) { ldap_mods_free(mods, 1); *pmods = NULL; } if (msg) hdb_free_entry(context, &orig); return ret; } static krb5_error_code LDAP_dn2principal(krb5_context context, HDB * db, const char *dn, krb5_principal * principal) { krb5_error_code ret; int rc; const char *filter = "(objectClass=krb5Principal)"; LDAPMessage *res = NULL, *e; char *p; ret = LDAP_no_size_limit(context, HDB2LDAP(db)); if (ret) goto out; rc = ldap_search_ext_s(HDB2LDAP(db), dn, LDAP_SCOPE_SUBTREE, filter, krb5principal_attrs, 0, NULL, NULL, NULL, 0, &res); if (check_ldap(context, db, rc)) { ret = HDB_ERR_NOENTRY; krb5_set_error_message(context, ret, "ldap_search_ext_s: " "filter: %s error: %s", filter, ldap_err2string(rc)); goto out; } e = ldap_first_entry(HDB2LDAP(db), res); if (e == NULL) { ret = HDB_ERR_NOENTRY; goto out; } ret = LDAP_get_string_value(db, e, "krb5PrincipalName", &p); if (ret) { ret = HDB_ERR_NOENTRY; goto out; } ret = krb5_parse_name(context, p, principal); free(p); out: if (res) ldap_msgfree(res); return ret; } static int need_quote(unsigned char c) { return (c & 0x80) || (c < 32) || (c == '(') || (c == ')') || (c == '*') || (c == '\\') || (c == 0x7f); } static const char hexchar[] = "0123456789ABCDEF"; static krb5_error_code escape_value(krb5_context context, const char *unquoted, char **quoted) { size_t i, len; for (i = 0, len = 0; unquoted[i] != '\0'; i++, len++) { if (need_quote((unsigned char)unquoted[i])) len += 2; } *quoted = malloc(len + 1); if (*quoted == NULL) { krb5_set_error_message(context, ENOMEM, "malloc: out of memory"); return ENOMEM; } for (i = 0; unquoted[0] ; unquoted++) { if (need_quote((unsigned char)unquoted[0])) { (*quoted)[i++] = '\\'; (*quoted)[i++] = hexchar[(unquoted[0] >> 4) & 0xf]; (*quoted)[i++] = hexchar[(unquoted[0] ) & 0xf]; } else (*quoted)[i++] = (char)unquoted[0]; } (*quoted)[i] = '\0'; return 0; } static krb5_error_code LDAP__lookup_princ(krb5_context context, HDB *db, const char *princname, const char *userid, LDAPMessage **msg) { krb5_error_code ret; int rc; char *quote, *filter = NULL; ret = LDAP__connect(context, db); if (ret) return ret; /* * Quote searches that contain filter language, this quote * searches for *@REALM, which takes very long time. */ ret = escape_value(context, princname, "e); if (ret) goto out; rc = asprintf(&filter, "(&(objectClass=krb5Principal)(krb5PrincipalName=%s))", quote); free(quote); if (rc < 0) { ret = ENOMEM; krb5_set_error_message(context, ret, "malloc: out of memory"); goto out; } ret = LDAP_no_size_limit(context, HDB2LDAP(db)); if (ret) goto out; rc = ldap_search_ext_s(HDB2LDAP(db), HDB2BASE(db), LDAP_SCOPE_SUBTREE, filter, krb5kdcentry_attrs, 0, NULL, NULL, NULL, 0, msg); if (check_ldap(context, db, rc)) { ret = HDB_ERR_NOENTRY; krb5_set_error_message(context, ret, "ldap_search_ext_s: " "filter: %s - error: %s", filter, ldap_err2string(rc)); goto out; } if (userid && ldap_count_entries(HDB2LDAP(db), *msg) == 0) { free(filter); filter = NULL; ldap_msgfree(*msg); *msg = NULL; ret = escape_value(context, userid, "e); if (ret) goto out; rc = asprintf(&filter, "(&(|(objectClass=sambaSamAccount)(objectClass=%s))(uid=%s))", structural_object, quote); free(quote); if (rc < 0) { ret = ENOMEM; krb5_set_error_message(context, ret, "asprintf: out of memory"); goto out; } ret = LDAP_no_size_limit(context, HDB2LDAP(db)); if (ret) goto out; rc = ldap_search_ext_s(HDB2LDAP(db), HDB2BASE(db), LDAP_SCOPE_SUBTREE, filter, krb5kdcentry_attrs, 0, NULL, NULL, NULL, 0, msg); if (check_ldap(context, db, rc)) { ret = HDB_ERR_NOENTRY; krb5_set_error_message(context, ret, "ldap_search_ext_s: filter: %s error: %s", filter, ldap_err2string(rc)); goto out; } } ret = 0; out: if (filter) free(filter); return ret; } static krb5_error_code LDAP_principal2message(krb5_context context, HDB * db, krb5_const_principal princ, LDAPMessage ** msg) { char *name, *name_short = NULL; krb5_error_code ret; krb5_realm *r, *r0; *msg = NULL; ret = krb5_unparse_name(context, princ, &name); if (ret) return ret; ret = krb5_get_default_realms(context, &r0); if(ret) { free(name); return ret; } for (r = r0; *r != NULL; r++) { if(strcmp(krb5_principal_get_realm(context, princ), *r) == 0) { ret = krb5_unparse_name_short(context, princ, &name_short); if (ret) { krb5_free_host_realm(context, r0); free(name); return ret; } break; } } krb5_free_host_realm(context, r0); ret = LDAP__lookup_princ(context, db, name, name_short, msg); free(name); free(name_short); return ret; } /* * Construct an hdb_entry from a directory entry. */ static krb5_error_code LDAP_message2entry(krb5_context context, HDB * db, LDAPMessage * msg, int flags, hdb_entry_ex * ent) { char *unparsed_name = NULL, *dn = NULL, *ntPasswordIN = NULL; char *samba_acct_flags = NULL; struct berval **keys; struct berval **extensions; struct berval **vals; int tmp, tmp_time, i, ret, have_arcfour = 0; memset(ent, 0, sizeof(*ent)); ent->entry.flags = int2HDBFlags(0); ret = LDAP_get_string_value(db, msg, "krb5PrincipalName", &unparsed_name); if (ret == 0) { ret = krb5_parse_name(context, unparsed_name, &ent->entry.principal); if (ret) goto out; } else { ret = LDAP_get_string_value(db, msg, "uid", &unparsed_name); if (ret == 0) { ret = krb5_parse_name(context, unparsed_name, &ent->entry.principal); if (ret) goto out; } else { krb5_set_error_message(context, HDB_ERR_NOENTRY, "hdb-ldap: ldap entry missing" "principal name"); return HDB_ERR_NOENTRY; } } { int integer; ret = LDAP_get_integer_value(db, msg, "krb5KeyVersionNumber", &integer); if (ret) ent->entry.kvno = 0; else ent->entry.kvno = integer; } keys = ldap_get_values_len(HDB2LDAP(db), msg, "krb5Key"); if (keys != NULL) { size_t l; ent->entry.keys.len = ldap_count_values_len(keys); ent->entry.keys.val = (Key *) calloc(ent->entry.keys.len, sizeof(Key)); if (ent->entry.keys.val == NULL) { ret = ENOMEM; krb5_set_error_message(context, ret, "calloc: out of memory"); goto out; } for (i = 0; i < ent->entry.keys.len; i++) { decode_Key((unsigned char *) keys[i]->bv_val, (size_t) keys[i]->bv_len, &ent->entry.keys.val[i], &l); } ber_bvecfree(keys); } else { #if 1 /* * This violates the ASN1 but it allows a principal to * be related to a general directory entry without creating * the keys. Hopefully it's OK. */ ent->entry.keys.len = 0; ent->entry.keys.val = NULL; #else ret = HDB_ERR_NOENTRY; goto out; #endif } extensions = ldap_get_values_len(HDB2LDAP(db), msg, "krb5ExtendedAttributes"); if (extensions != NULL) { size_t l; ent->entry.extensions = calloc(1, sizeof(*(ent->entry.extensions))); if (ent->entry.extensions == NULL) { ret = krb5_enomem(context); goto out; } ent->entry.extensions->len = ldap_count_values_len(extensions); ent->entry.extensions->val = (HDB_extension *) calloc(ent->entry.extensions->len, sizeof(HDB_extension)); if (ent->entry.extensions->val == NULL) { ent->entry.extensions->len = 0; ret = krb5_enomem(context); goto out; } for (i = 0; i < ent->entry.extensions->len; i++) { ret = decode_HDB_extension((unsigned char *) extensions[i]->bv_val, (size_t) extensions[i]->bv_len, &ent->entry.extensions->val[i], &l); if (ret) krb5_set_error_message(context, ret, "decode_HDB_extension failed"); } ber_bvecfree(extensions); } else { ent->entry.extensions = NULL; } vals = ldap_get_values_len(HDB2LDAP(db), msg, "krb5EncryptionType"); if (vals != NULL) { ent->entry.etypes = malloc(sizeof(*(ent->entry.etypes))); if (ent->entry.etypes == NULL) { ret = ENOMEM; krb5_set_error_message(context, ret,"malloc: out of memory"); goto out; } ent->entry.etypes->len = ldap_count_values_len(vals); ent->entry.etypes->val = calloc(ent->entry.etypes->len, sizeof(ent->entry.etypes->val[0])); if (ent->entry.etypes->val == NULL) { ret = ENOMEM; krb5_set_error_message(context, ret, "malloc: out of memory"); ent->entry.etypes->len = 0; goto out; } for (i = 0; i < ent->entry.etypes->len; i++) { char *buf; buf = malloc(vals[i]->bv_len + 1); if (buf == NULL) { ret = ENOMEM; krb5_set_error_message(context, ret, "malloc: out of memory"); goto out; } memcpy(buf, vals[i]->bv_val, vals[i]->bv_len); buf[vals[i]->bv_len] = '\0'; ent->entry.etypes->val[i] = atoi(buf); free(buf); } ldap_value_free_len(vals); } for (i = 0; i < ent->entry.keys.len; i++) { if (ent->entry.keys.val[i].key.keytype == ETYPE_ARCFOUR_HMAC_MD5) { have_arcfour = 1; break; } } /* manually construct the NT (type 23) key */ ret = LDAP_get_string_value(db, msg, "sambaNTPassword", &ntPasswordIN); if (ret == 0 && have_arcfour == 0) { unsigned *etypes; Key *ks; ks = realloc(ent->entry.keys.val, (ent->entry.keys.len + 1) * sizeof(ent->entry.keys.val[0])); if (ks == NULL) { ret = ENOMEM; krb5_set_error_message(context, ret, "malloc: out of memory"); goto out; } ent->entry.keys.val = ks; memset(&ent->entry.keys.val[ent->entry.keys.len], 0, sizeof(Key)); ent->entry.keys.val[ent->entry.keys.len].key.keytype = ETYPE_ARCFOUR_HMAC_MD5; ret = krb5_data_alloc (&ent->entry.keys.val[ent->entry.keys.len].key.keyvalue, 16); if (ret) { krb5_set_error_message(context, ret, "malloc: out of memory"); ret = ENOMEM; goto out; } ret = hex_decode(ntPasswordIN, ent->entry.keys.val[ent->entry.keys.len].key.keyvalue.data, 16); ent->entry.keys.len++; if (ent->entry.etypes == NULL) { ent->entry.etypes = malloc(sizeof(*(ent->entry.etypes))); if (ent->entry.etypes == NULL) { ret = ENOMEM; krb5_set_error_message(context, ret, "malloc: out of memory"); goto out; } ent->entry.etypes->val = NULL; ent->entry.etypes->len = 0; } for (i = 0; i < ent->entry.etypes->len; i++) if (ent->entry.etypes->val[i] == ETYPE_ARCFOUR_HMAC_MD5) break; /* If there is no ARCFOUR enctype, add one */ if (i == ent->entry.etypes->len) { etypes = realloc(ent->entry.etypes->val, (ent->entry.etypes->len + 1) * sizeof(ent->entry.etypes->val[0])); if (etypes == NULL) { ret = ENOMEM; krb5_set_error_message(context, ret, "malloc: out of memory"); goto out; } ent->entry.etypes->val = etypes; ent->entry.etypes->val[ent->entry.etypes->len] = ETYPE_ARCFOUR_HMAC_MD5; ent->entry.etypes->len++; } } ret = LDAP_get_generalized_time_value(db, msg, "createTimestamp", &ent->entry.created_by.time); if (ret) ent->entry.created_by.time = time(NULL); ent->entry.created_by.principal = NULL; if (flags & HDB_F_ADMIN_DATA) { ret = LDAP_get_string_value(db, msg, "creatorsName", &dn); if (ret == 0) { LDAP_dn2principal(context, db, dn, &ent->entry.created_by.principal); free(dn); } ent->entry.modified_by = calloc(1, sizeof(*ent->entry.modified_by)); if (ent->entry.modified_by == NULL) { ret = ENOMEM; krb5_set_error_message(context, ret, "malloc: out of memory"); goto out; } ret = LDAP_get_generalized_time_value(db, msg, "modifyTimestamp", &ent->entry.modified_by->time); if (ret == 0) { ret = LDAP_get_string_value(db, msg, "modifiersName", &dn); if (ret == 0) { LDAP_dn2principal(context, db, dn, &ent->entry.modified_by->principal); free(dn); } else { free(ent->entry.modified_by); ent->entry.modified_by = NULL; } } } ent->entry.valid_start = malloc(sizeof(*ent->entry.valid_start)); if (ent->entry.valid_start == NULL) { ret = ENOMEM; krb5_set_error_message(context, ret, "malloc: out of memory"); goto out; } ret = LDAP_get_generalized_time_value(db, msg, "krb5ValidStart", ent->entry.valid_start); if (ret) { /* OPTIONAL */ free(ent->entry.valid_start); ent->entry.valid_start = NULL; } ent->entry.valid_end = malloc(sizeof(*ent->entry.valid_end)); if (ent->entry.valid_end == NULL) { ret = ENOMEM; krb5_set_error_message(context, ret, "malloc: out of memory"); goto out; } ret = LDAP_get_generalized_time_value(db, msg, "krb5ValidEnd", ent->entry.valid_end); if (ret) { /* OPTIONAL */ free(ent->entry.valid_end); ent->entry.valid_end = NULL; } ret = LDAP_get_integer_value(db, msg, "sambaKickoffTime", &tmp_time); if (ret == 0) { if (ent->entry.valid_end == NULL) { ent->entry.valid_end = malloc(sizeof(*ent->entry.valid_end)); if (ent->entry.valid_end == NULL) { ret = ENOMEM; krb5_set_error_message(context, ret, "malloc: out of memory"); goto out; } } *ent->entry.valid_end = tmp_time; } ent->entry.pw_end = malloc(sizeof(*ent->entry.pw_end)); if (ent->entry.pw_end == NULL) { ret = ENOMEM; krb5_set_error_message(context, ret, "malloc: out of memory"); goto out; } ret = LDAP_get_generalized_time_value(db, msg, "krb5PasswordEnd", ent->entry.pw_end); if (ret) { /* OPTIONAL */ free(ent->entry.pw_end); ent->entry.pw_end = NULL; } ret = LDAP_get_integer_value(db, msg, "sambaPwdLastSet", &tmp_time); if (ret == 0) { time_t delta; delta = krb5_config_get_time_default(context, NULL, 0, "kadmin", "password_lifetime", NULL); if (delta) { if (ent->entry.pw_end == NULL) { ent->entry.pw_end = malloc(sizeof(*ent->entry.pw_end)); if (ent->entry.pw_end == NULL) { ret = ENOMEM; krb5_set_error_message(context, ret, "malloc: out of memory"); goto out; } } *ent->entry.pw_end = tmp_time + delta; } } ret = LDAP_get_integer_value(db, msg, "sambaPwdMustChange", &tmp_time); if (ret == 0) { if (ent->entry.pw_end == NULL) { ent->entry.pw_end = malloc(sizeof(*ent->entry.pw_end)); if (ent->entry.pw_end == NULL) { ret = ENOMEM; krb5_set_error_message(context, ret, "malloc: out of memory"); goto out; } } *ent->entry.pw_end = tmp_time; } /* OPTIONAL */ ret = LDAP_get_integer_value(db, msg, "sambaPwdLastSet", &tmp_time); if (ret == 0) hdb_entry_set_pw_change_time(context, &ent->entry, tmp_time); { int max_life; ent->entry.max_life = malloc(sizeof(*ent->entry.max_life)); if (ent->entry.max_life == NULL) { ret = ENOMEM; krb5_set_error_message(context, ret, "malloc: out of memory"); goto out; } ret = LDAP_get_integer_value(db, msg, "krb5MaxLife", &max_life); if (ret) { free(ent->entry.max_life); ent->entry.max_life = NULL; } else *ent->entry.max_life = max_life; } { int max_renew; ent->entry.max_renew = malloc(sizeof(*ent->entry.max_renew)); if (ent->entry.max_renew == NULL) { ret = ENOMEM; krb5_set_error_message(context, ret, "malloc: out of memory"); goto out; } ret = LDAP_get_integer_value(db, msg, "krb5MaxRenew", &max_renew); if (ret) { free(ent->entry.max_renew); ent->entry.max_renew = NULL; } else *ent->entry.max_renew = max_renew; } ret = LDAP_get_integer_value(db, msg, "krb5KDCFlags", &tmp); if (ret) tmp = 0; ent->entry.flags = int2HDBFlags(tmp); /* Try and find Samba flags to put into the mix */ ret = LDAP_get_string_value(db, msg, "sambaAcctFlags", &samba_acct_flags); if (ret == 0) { /* parse the [UXW...] string: 'N' No password 'D' Disabled 'H' Homedir required 'T' Temp account. 'U' User account (normal) 'M' MNS logon user account - what is this ? 'W' Workstation account 'S' Server account 'L' Locked account 'X' No Xpiry on password 'I' Interdomain trust account */ int flags_len = strlen(samba_acct_flags); if (flags_len < 2) goto out2; if (samba_acct_flags[0] != '[' || samba_acct_flags[flags_len - 1] != ']') goto out2; /* Allow forwarding */ if (samba_forwardable) ent->entry.flags.forwardable = TRUE; for (i=0; i < flags_len; i++) { switch (samba_acct_flags[i]) { case ' ': case '[': case ']': break; case 'N': /* how to handle no password in kerberos? */ break; case 'D': ent->entry.flags.invalid = TRUE; break; case 'H': break; case 'T': /* temp duplicate */ ent->entry.flags.invalid = TRUE; break; case 'U': ent->entry.flags.client = TRUE; break; case 'M': break; case 'W': case 'S': ent->entry.flags.server = TRUE; ent->entry.flags.client = TRUE; break; case 'L': ent->entry.flags.invalid = TRUE; break; case 'X': if (ent->entry.pw_end) { free(ent->entry.pw_end); ent->entry.pw_end = NULL; } break; case 'I': ent->entry.flags.server = TRUE; ent->entry.flags.client = TRUE; break; } } out2: free(samba_acct_flags); } ret = 0; out: free(unparsed_name); free(ntPasswordIN); if (ret) hdb_free_entry(context, ent); return ret; } static krb5_error_code LDAP_close(krb5_context context, HDB * db) { if (HDB2LDAP(db)) { ldap_unbind_ext(HDB2LDAP(db), NULL, NULL); ((struct hdbldapdb *)db->hdb_db)->h_lp = NULL; } return 0; } static krb5_error_code LDAP_lock(krb5_context context, HDB * db, int operation) { return 0; } static krb5_error_code LDAP_unlock(krb5_context context, HDB * db) { return 0; } static krb5_error_code LDAP_seq(krb5_context context, HDB * db, unsigned flags, hdb_entry_ex * entry) { int msgid, rc, parserc; krb5_error_code ret; LDAPMessage *e; msgid = HDB2MSGID(db); if (msgid < 0) return HDB_ERR_NOENTRY; do { rc = ldap_result(HDB2LDAP(db), msgid, LDAP_MSG_ONE, NULL, &e); switch (rc) { case LDAP_RES_SEARCH_REFERENCE: ldap_msgfree(e); ret = 0; break; case LDAP_RES_SEARCH_ENTRY: /* We have an entry. Parse it. */ ret = LDAP_message2entry(context, db, e, flags, entry); ldap_msgfree(e); break; case LDAP_RES_SEARCH_RESULT: /* We're probably at the end of the results. If not, abandon. */ parserc = ldap_parse_result(HDB2LDAP(db), e, NULL, NULL, NULL, NULL, NULL, 1); ret = HDB_ERR_NOENTRY; if (parserc != LDAP_SUCCESS && parserc != LDAP_MORE_RESULTS_TO_RETURN) { krb5_set_error_message(context, ret, "ldap_parse_result: %s", ldap_err2string(parserc)); ldap_abandon_ext(HDB2LDAP(db), msgid, NULL, NULL); } HDBSETMSGID(db, -1); break; case LDAP_SERVER_DOWN: ldap_msgfree(e); LDAP_close(context, db); HDBSETMSGID(db, -1); ret = ENETDOWN; break; default: /* Some unspecified error (timeout?). Abandon. */ ldap_msgfree(e); ldap_abandon_ext(HDB2LDAP(db), msgid, NULL, NULL); ret = HDB_ERR_NOENTRY; HDBSETMSGID(db, -1); break; } } while (rc == LDAP_RES_SEARCH_REFERENCE); if (ret == 0) { if (db->hdb_master_key_set && (flags & HDB_F_DECRYPT)) { ret = hdb_unseal_keys(context, db, &entry->entry); if (ret) hdb_free_entry(context, entry); } } return ret; } static krb5_error_code LDAP_firstkey(krb5_context context, HDB *db, unsigned flags, hdb_entry_ex *entry) { krb5_error_code ret; int msgid; ret = LDAP__connect(context, db); if (ret) return ret; ret = LDAP_no_size_limit(context, HDB2LDAP(db)); if (ret) return ret; ret = ldap_search_ext(HDB2LDAP(db), HDB2BASE(db), LDAP_SCOPE_SUBTREE, "(|(objectClass=krb5Principal)(objectClass=sambaSamAccount))", krb5kdcentry_attrs, 0, NULL, NULL, NULL, 0, &msgid); if (ret != LDAP_SUCCESS || msgid < 0) return HDB_ERR_NOENTRY; HDBSETMSGID(db, msgid); return LDAP_seq(context, db, flags, entry); } static krb5_error_code LDAP_nextkey(krb5_context context, HDB * db, unsigned flags, hdb_entry_ex * entry) { return LDAP_seq(context, db, flags, entry); } static krb5_error_code LDAP__connect(krb5_context context, HDB * db) { int rc, version = LDAP_VERSION3; /* * Empty credentials to do a SASL bind with LDAP. Note that empty * different from NULL credentials. If you provide NULL * credentials instead of empty credentials you will get a SASL * bind in progress message. */ struct berval bv = { 0, "" }; const char *sasl_method = "EXTERNAL"; const char *bind_dn = NULL; if (HDB2BINDDN(db) != NULL && HDB2BINDPW(db) != NULL) { /* A bind DN was specified; use SASL SIMPLE */ bind_dn = HDB2BINDDN(db); sasl_method = LDAP_SASL_SIMPLE; bv.bv_val = HDB2BINDPW(db); bv.bv_len = strlen(bv.bv_val); } if (HDB2LDAP(db)) { /* connection has been opened. ping server. */ struct sockaddr_un addr; socklen_t len = sizeof(addr); int sd; if (ldap_get_option(HDB2LDAP(db), LDAP_OPT_DESC, &sd) == 0 && getpeername(sd, (struct sockaddr *) &addr, &len) < 0) { /* the other end has died. reopen. */ LDAP_close(context, db); } } if (HDB2LDAP(db) != NULL) /* server is UP */ return 0; rc = ldap_initialize(&((struct hdbldapdb *)db->hdb_db)->h_lp, HDB2URL(db)); if (rc != LDAP_SUCCESS) { krb5_set_error_message(context, HDB_ERR_NOENTRY, "ldap_initialize: %s", ldap_err2string(rc)); return HDB_ERR_NOENTRY; } rc = ldap_set_option(HDB2LDAP(db), LDAP_OPT_PROTOCOL_VERSION, (const void *)&version); if (rc != LDAP_SUCCESS) { krb5_set_error_message(context, HDB_ERR_BADVERSION, "ldap_set_option: %s", ldap_err2string(rc)); LDAP_close(context, db); return HDB_ERR_BADVERSION; } if (((struct hdbldapdb *)db->hdb_db)->h_start_tls) { rc = ldap_start_tls_s(HDB2LDAP(db), NULL, NULL); if (rc != LDAP_SUCCESS) { krb5_set_error_message(context, HDB_ERR_BADVERSION, "ldap_start_tls_s: %s", ldap_err2string(rc)); LDAP_close(context, db); return HDB_ERR_BADVERSION; } } rc = ldap_sasl_bind_s(HDB2LDAP(db), bind_dn, sasl_method, &bv, NULL, NULL, NULL); if (rc != LDAP_SUCCESS) { krb5_set_error_message(context, HDB_ERR_BADVERSION, "ldap_sasl_bind_s: %s", ldap_err2string(rc)); LDAP_close(context, db); return HDB_ERR_BADVERSION; } return 0; } static krb5_error_code LDAP_open(krb5_context context, HDB * db, int flags, mode_t mode) { /* Not the right place for this. */ #ifdef HAVE_SIGACTION struct sigaction sa; sa.sa_flags = 0; sa.sa_handler = SIG_IGN; sigemptyset(&sa.sa_mask); sigaction(SIGPIPE, &sa, NULL); #else signal(SIGPIPE, SIG_IGN); #endif /* HAVE_SIGACTION */ return LDAP__connect(context, db); } static krb5_error_code LDAP_fetch_kvno(krb5_context context, HDB * db, krb5_const_principal principal, unsigned flags, krb5_kvno kvno, hdb_entry_ex * entry) { LDAPMessage *msg, *e; krb5_error_code ret; ret = LDAP_principal2message(context, db, principal, &msg); if (ret) return ret; e = ldap_first_entry(HDB2LDAP(db), msg); if (e == NULL) { ret = HDB_ERR_NOENTRY; goto out; } ret = LDAP_message2entry(context, db, e, flags, entry); if (ret == 0) { if (db->hdb_master_key_set && (flags & HDB_F_DECRYPT)) { ret = hdb_unseal_keys(context, db, &entry->entry); if (ret) hdb_free_entry(context, entry); } } out: ldap_msgfree(msg); return ret; } #if 0 static krb5_error_code LDAP_fetch(krb5_context context, HDB * db, krb5_const_principal principal, unsigned flags, hdb_entry_ex * entry) { return LDAP_fetch_kvno(context, db, principal, flags & (~HDB_F_KVNO_SPECIFIED), 0, entry); } #endif static krb5_error_code LDAP_store(krb5_context context, HDB * db, unsigned flags, hdb_entry_ex * entry) { LDAPMod **mods = NULL; krb5_error_code ret; const char *errfn; int rc; LDAPMessage *msg = NULL, *e = NULL; char *dn = NULL, *name = NULL; if ((flags & HDB_F_PRECHECK)) return 0; /* we can't guarantee whether we'll be able to perform it */ ret = LDAP_principal2message(context, db, entry->entry.principal, &msg); if (ret == 0) e = ldap_first_entry(HDB2LDAP(db), msg); ret = krb5_unparse_name(context, entry->entry.principal, &name); if (ret) { free(name); return ret; } ret = hdb_seal_keys(context, db, &entry->entry); if (ret) goto out; /* turn new entry into LDAPMod array */ ret = LDAP_entry2mods(context, db, entry, e, &mods); if (ret) goto out; if (e == NULL) { ret = asprintf(&dn, "krb5PrincipalName=%s,%s", name, HDB2CREATE(db)); if (ret < 0) { ret = ENOMEM; krb5_set_error_message(context, ret, "asprintf: out of memory"); goto out; } } else if (flags & HDB_F_REPLACE) { /* Entry exists, and we're allowed to replace it. */ dn = ldap_get_dn(HDB2LDAP(db), e); } else { /* Entry exists, but we're not allowed to replace it. Bail. */ ret = HDB_ERR_EXISTS; goto out; } /* write entry into directory */ if (e == NULL) { /* didn't exist before */ rc = ldap_add_ext_s(HDB2LDAP(db), dn, mods, NULL, NULL ); errfn = "ldap_add_ext_s"; } else { /* already existed, send deltas only */ rc = ldap_modify_ext_s(HDB2LDAP(db), dn, mods, NULL, NULL ); errfn = "ldap_modify_ext_s"; } if (check_ldap(context, db, rc)) { char *ld_error = NULL; ldap_get_option(HDB2LDAP(db), LDAP_OPT_ERROR_STRING, &ld_error); ret = HDB_ERR_CANT_LOCK_DB; krb5_set_error_message(context, ret, "%s: %s (DN=%s) %s: %s", errfn, name, dn, ldap_err2string(rc), ld_error); } else ret = 0; out: /* free stuff */ if (dn) free(dn); if (msg) ldap_msgfree(msg); if (mods) ldap_mods_free(mods, 1); if (name) free(name); return ret; } static krb5_error_code LDAP_remove(krb5_context context, HDB *db, unsigned flags, krb5_const_principal principal) { krb5_error_code ret; LDAPMessage *msg, *e; char *dn = NULL; int rc, limit = LDAP_NO_LIMIT; if ((flags & HDB_F_PRECHECK)) return 0; /* we can't guarantee whether we'll be able to perform it */ ret = LDAP_principal2message(context, db, principal, &msg); if (ret) goto out; e = ldap_first_entry(HDB2LDAP(db), msg); if (e == NULL) { ret = HDB_ERR_NOENTRY; goto out; } dn = ldap_get_dn(HDB2LDAP(db), e); if (dn == NULL) { ret = HDB_ERR_NOENTRY; goto out; } rc = ldap_set_option(HDB2LDAP(db), LDAP_OPT_SIZELIMIT, (const void *)&limit); if (rc != LDAP_SUCCESS) { ret = HDB_ERR_BADVERSION; krb5_set_error_message(context, ret, "ldap_set_option: %s", ldap_err2string(rc)); goto out; } rc = ldap_delete_ext_s(HDB2LDAP(db), dn, NULL, NULL ); if (check_ldap(context, db, rc)) { ret = HDB_ERR_CANT_LOCK_DB; krb5_set_error_message(context, ret, "ldap_delete_ext_s: %s", ldap_err2string(rc)); } else ret = 0; out: if (dn != NULL) free(dn); if (msg != NULL) ldap_msgfree(msg); return ret; } static krb5_error_code LDAP_destroy(krb5_context context, HDB * db) { krb5_error_code ret; LDAP_close(context, db); ret = hdb_clear_master_key(context, db); if (HDB2BASE(db)) free(HDB2BASE(db)); if (HDB2CREATE(db)) free(HDB2CREATE(db)); if (HDB2URL(db)) free(HDB2URL(db)); if (db->hdb_name) free(db->hdb_name); free(db->hdb_db); free(db); return ret; } static krb5_error_code hdb_ldap_common(krb5_context context, HDB ** db, const char *search_base, const char *url) { struct hdbldapdb *h; const char *create_base = NULL; const char *ldap_secret_file = NULL; if (url == NULL || url[0] == '\0') { const char *p; p = krb5_config_get_string(context, NULL, "kdc", "hdb-ldap-url", NULL); if (p == NULL) p = default_ldap_url; url = p; } if (search_base == NULL || search_base[0] == '\0') { krb5_set_error_message(context, ENOMEM, "ldap search base not configured"); return ENOMEM; /* XXX */ } if (structural_object == NULL) { const char *p; p = krb5_config_get_string(context, NULL, "kdc", "hdb-ldap-structural-object", NULL); if (p == NULL) p = default_structural_object; structural_object = strdup(p); if (structural_object == NULL) { krb5_set_error_message(context, ENOMEM, "malloc: out of memory"); return ENOMEM; } } samba_forwardable = krb5_config_get_bool_default(context, NULL, TRUE, "kdc", "hdb-samba-forwardable", NULL); *db = calloc(1, sizeof(**db)); if (*db == NULL) { krb5_set_error_message(context, ENOMEM, "malloc: out of memory"); return ENOMEM; } memset(*db, 0, sizeof(**db)); h = calloc(1, sizeof(*h)); if (h == NULL) { free(*db); *db = NULL; krb5_set_error_message(context, ENOMEM, "malloc: out of memory"); return ENOMEM; } (*db)->hdb_db = h; /* XXX */ if (asprintf(&(*db)->hdb_name, "ldap:%s", search_base) == -1) { LDAP_destroy(context, *db); *db = NULL; krb5_set_error_message(context, ENOMEM, "strdup: out of memory"); return ENOMEM; } h->h_url = strdup(url); h->h_base = strdup(search_base); if (h->h_url == NULL || h->h_base == NULL) { LDAP_destroy(context, *db); *db = NULL; krb5_set_error_message(context, ENOMEM, "strdup: out of memory"); return ENOMEM; } ldap_secret_file = krb5_config_get_string(context, NULL, "kdc", "hdb-ldap-secret-file", NULL); if (ldap_secret_file != NULL) { krb5_config_binding *tmp; krb5_error_code ret; const char *p; ret = krb5_config_parse_file(context, ldap_secret_file, &tmp); if (ret) return ret; p = krb5_config_get_string(context, tmp, "kdc", "hdb-ldap-bind-dn", NULL); if (p != NULL) h->h_bind_dn = strdup(p); p = krb5_config_get_string(context, tmp, "kdc", "hdb-ldap-bind-password", NULL); if (p != NULL) h->h_bind_password = strdup(p); krb5_config_file_free(context, tmp); } h->h_start_tls = krb5_config_get_bool_default(context, NULL, FALSE, "kdc", "hdb-ldap-start-tls", NULL); create_base = krb5_config_get_string(context, NULL, "kdc", "hdb-ldap-create-base", NULL); if (create_base == NULL) create_base = h->h_base; h->h_createbase = strdup(create_base); if (h->h_createbase == NULL) { LDAP_destroy(context, *db); *db = NULL; krb5_set_error_message(context, ENOMEM, "strdup: out of memory"); return ENOMEM; } (*db)->hdb_master_key_set = 0; (*db)->hdb_openp = 0; (*db)->hdb_capability_flags = HDB_CAP_F_SHARED_DIRECTORY; (*db)->hdb_open = LDAP_open; (*db)->hdb_close = LDAP_close; (*db)->hdb_fetch_kvno = LDAP_fetch_kvno; (*db)->hdb_store = LDAP_store; (*db)->hdb_remove = LDAP_remove; (*db)->hdb_firstkey = LDAP_firstkey; (*db)->hdb_nextkey = LDAP_nextkey; (*db)->hdb_lock = LDAP_lock; (*db)->hdb_unlock = LDAP_unlock; (*db)->hdb_rename = NULL; (*db)->hdb__get = NULL; (*db)->hdb__put = NULL; (*db)->hdb__del = NULL; (*db)->hdb_destroy = LDAP_destroy; return 0; } #ifdef OPENLDAP_MODULE static #endif krb5_error_code hdb_ldap_create(krb5_context context, HDB ** db, const char *arg) { return hdb_ldap_common(context, db, arg, NULL); } #ifdef OPENLDAP_MODULE static #endif krb5_error_code hdb_ldapi_create(krb5_context context, HDB ** db, const char *arg) { krb5_error_code ret; char *search_base, *p; if (asprintf(&p, "ldapi:%s", arg) == -1 || p == NULL) { *db = NULL; krb5_set_error_message(context, ENOMEM, "out of memory"); return ENOMEM; } search_base = strchr(p + strlen("ldapi://"), ':'); if (search_base == NULL) { *db = NULL; krb5_set_error_message(context, HDB_ERR_BADVERSION, "search base missing"); return HDB_ERR_BADVERSION; } *search_base = '\0'; search_base++; ret = hdb_ldap_common(context, db, search_base, p); free(p); return ret; } #ifdef OPENLDAP_MODULE static krb5_error_code init(krb5_context context, void **ctx) { *ctx = NULL; return 0; } static void fini(void *ctx) { } struct hdb_method hdb_ldap_interface = { HDB_INTERFACE_VERSION, init, fini, "ldap", hdb_ldap_create }; struct hdb_method hdb_ldapi_interface = { HDB_INTERFACE_VERSION, init, fini, "ldapi", hdb_ldapi_create }; #endif #endif /* OPENLDAP */ heimdal-7.5.0/lib/hdb/hdb-private.h0000644000175000017500000000277013212445602015140 0ustar niknik/* This is a generated file */ #ifndef __hdb_private_h__ #define __hdb_private_h__ #include krb5_error_code _hdb_fetch_kvno ( krb5_context /*context*/, HDB */*db*/, krb5_const_principal /*principal*/, unsigned /*flags*/, krb5_kvno /*kvno*/, hdb_entry_ex */*entry*/); hdb_master_key _hdb_find_master_key ( unsigned int */*mkvno*/, hdb_master_key /*mkey*/); krb5_error_code _hdb_keytab2hdb_entry ( krb5_context /*context*/, const krb5_keytab_entry */*ktentry*/, hdb_entry_ex */*entry*/); krb5_error_code _hdb_mdb_value2entry ( krb5_context /*context*/, krb5_data */*data*/, krb5_kvno /*target_kvno*/, hdb_entry */*entry*/); int _hdb_mit_dump2mitdb_entry ( krb5_context /*context*/, char */*line*/, krb5_storage */*sp*/); int _hdb_mkey_decrypt ( krb5_context /*context*/, hdb_master_key /*key*/, krb5_key_usage /*usage*/, void */*ptr*/, size_t /*size*/, krb5_data */*res*/); int _hdb_mkey_encrypt ( krb5_context /*context*/, hdb_master_key /*key*/, krb5_key_usage /*usage*/, const void */*ptr*/, size_t /*size*/, krb5_data */*res*/); int _hdb_mkey_version (hdb_master_key /*mkey*/); krb5_error_code _hdb_remove ( krb5_context /*context*/, HDB */*db*/, unsigned /*flags*/, krb5_const_principal /*principal*/); krb5_error_code _hdb_set_master_key_usage ( krb5_context /*context*/, HDB */*db*/, unsigned int /*key_usage*/); krb5_error_code _hdb_store ( krb5_context /*context*/, HDB */*db*/, unsigned /*flags*/, hdb_entry_ex */*entry*/); #endif /* __hdb_private_h__ */ heimdal-7.5.0/lib/hdb/hdb.asn10000644000175000017500000001047413026237312014103 0ustar niknik-- $Id$ HDB DEFINITIONS ::= BEGIN IMPORTS EncryptionKey, KerberosTime, Principal FROM krb5; HDB_DB_FORMAT INTEGER ::= 2 -- format of database, -- update when making changes -- these must have the same value as the pa-* counterparts hdb-pw-salt INTEGER ::= 3 hdb-afs3-salt INTEGER ::= 10 Salt ::= SEQUENCE { type[0] INTEGER (0..4294967295), salt[1] OCTET STRING, opaque[2] OCTET STRING OPTIONAL } Key ::= SEQUENCE { mkvno[0] INTEGER (0..4294967295) OPTIONAL, -- master key version number key[1] EncryptionKey, salt[2] Salt OPTIONAL } Event ::= SEQUENCE { time[0] KerberosTime, principal[1] Principal OPTIONAL } HDBFlags ::= BIT STRING { initial(0), -- require as-req forwardable(1), -- may issue forwardable proxiable(2), -- may issue proxiable renewable(3), -- may issue renewable postdate(4), -- may issue postdatable server(5), -- may be server client(6), -- may be client invalid(7), -- entry is invalid require-preauth(8), -- must use preauth change-pw(9), -- change password service require-hwauth(10), -- must use hwauth ok-as-delegate(11), -- as in TicketFlags user-to-user(12), -- may use user-to-user auth immutable(13), -- may not be deleted trusted-for-delegation(14), -- Trusted to print forwardabled tickets allow-kerberos4(15), -- Allow Kerberos 4 requests allow-digest(16), -- Allow digest requests locked-out(17), -- Account is locked out, -- authentication will be denied require-pwchange(18), -- require a passwd change do-not-store(31) -- Not to be modified and stored in HDB } GENERATION ::= SEQUENCE { time[0] KerberosTime, -- timestamp usec[1] INTEGER (0..4294967295), -- microseconds gen[2] INTEGER (0..4294967295) -- generation number } HDB-Ext-PKINIT-acl ::= SEQUENCE OF SEQUENCE { subject[0] UTF8String, issuer[1] UTF8String OPTIONAL, anchor[2] UTF8String OPTIONAL } HDB-Ext-PKINIT-hash ::= SEQUENCE OF SEQUENCE { digest-type[0] OBJECT IDENTIFIER, digest[1] OCTET STRING } HDB-Ext-PKINIT-cert ::= SEQUENCE OF SEQUENCE { cert[0] OCTET STRING } HDB-Ext-Constrained-delegation-acl ::= SEQUENCE OF Principal -- hdb-ext-referrals ::= PA-SERVER-REFERRAL-DATA HDB-Ext-Lan-Manager-OWF ::= OCTET STRING HDB-Ext-Password ::= SEQUENCE { mkvno[0] INTEGER (0..4294967295) OPTIONAL, -- master key version number password OCTET STRING } HDB-Ext-Aliases ::= SEQUENCE { case-insensitive[0] BOOLEAN, -- case insensitive name allowed aliases[1] SEQUENCE OF Principal -- all names, inc primary } Keys ::= SEQUENCE OF Key hdb_keyset ::= SEQUENCE { kvno[0] INTEGER (0..4294967295), keys[1] Keys, set-time[2] KerberosTime OPTIONAL, -- time this keyset was created/set ... } HDB-Ext-KeySet ::= SEQUENCE OF hdb_keyset HDB-extension ::= SEQUENCE { mandatory[0] BOOLEAN, -- kdc MUST understand this extension, -- if not the whole entry must -- be rejected data[1] CHOICE { pkinit-acl[0] HDB-Ext-PKINIT-acl, pkinit-cert-hash[1] HDB-Ext-PKINIT-hash, allowed-to-delegate-to[2] HDB-Ext-Constrained-delegation-acl, -- referral-info[3] HDB-Ext-Referrals, lm-owf[4] HDB-Ext-Lan-Manager-OWF, password[5] HDB-Ext-Password, aliases[6] HDB-Ext-Aliases, last-pw-change[7] KerberosTime, pkinit-cert[8] HDB-Ext-PKINIT-cert, hist-keys[9] HDB-Ext-KeySet, hist-kvno-diff-clnt[10] INTEGER (0..4294967295), hist-kvno-diff-svc[11] INTEGER (0..4294967295), policy[12] UTF8String, principal-id[13] INTEGER(-9223372036854775808..9223372036854775807), ... }, ... } HDB-extensions ::= SEQUENCE OF HDB-extension hdb_entry ::= SEQUENCE { principal[0] Principal OPTIONAL, -- this is optional only -- for compatibility with libkrb5 kvno[1] INTEGER (0..4294967295), keys[2] Keys, created-by[3] Event, modified-by[4] Event OPTIONAL, valid-start[5] KerberosTime OPTIONAL, valid-end[6] KerberosTime OPTIONAL, pw-end[7] KerberosTime OPTIONAL, max-life[8] INTEGER (0..4294967295) OPTIONAL, max-renew[9] INTEGER (0..4294967295) OPTIONAL, flags[10] HDBFlags, etypes[11] SEQUENCE OF INTEGER (0..4294967295) OPTIONAL, generation[12] GENERATION OPTIONAL, extensions[13] HDB-extensions OPTIONAL } hdb_entry_alias ::= [APPLICATION 0] SEQUENCE { principal[0] Principal OPTIONAL } END heimdal-7.5.0/lib/hdb/dbinfo.c0000644000175000017500000001527113026237312014167 0ustar niknik/* * Copyright (c) 2005 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "hdb_locl.h" struct hdb_dbinfo { char *label; char *realm; char *dbname; char *mkey_file; char *acl_file; char *log_file; const krb5_config_binding *binding; struct hdb_dbinfo *next; }; static int get_dbinfo(krb5_context context, const krb5_config_binding *db_binding, const char *label, struct hdb_dbinfo **db) { struct hdb_dbinfo *di; const char *p; *db = NULL; p = krb5_config_get_string(context, db_binding, "dbname", NULL); if(p == NULL) return 0; di = calloc(1, sizeof(*di)); if (di == NULL) { krb5_set_error_message(context, ENOMEM, "malloc: out of memory"); return ENOMEM; } di->label = strdup(label); di->dbname = strdup(p); p = krb5_config_get_string(context, db_binding, "realm", NULL); if(p) di->realm = strdup(p); p = krb5_config_get_string(context, db_binding, "mkey_file", NULL); if(p) di->mkey_file = strdup(p); p = krb5_config_get_string(context, db_binding, "acl_file", NULL); if(p) di->acl_file = strdup(p); p = krb5_config_get_string(context, db_binding, "log_file", NULL); if(p) di->log_file = strdup(p); di->binding = db_binding; *db = di; return 0; } int hdb_get_dbinfo(krb5_context context, struct hdb_dbinfo **dbp) { const krb5_config_binding *db_binding; struct hdb_dbinfo *di, **dt, *databases; const char *default_dbname = HDB_DEFAULT_DB; const char *default_mkey = HDB_DB_DIR "/m-key"; const char *default_acl = HDB_DB_DIR "/kadmind.acl"; const char *p; int ret; *dbp = NULL; dt = NULL; databases = NULL; db_binding = krb5_config_get_list(context, NULL, "kdc", "database", NULL); if (db_binding) { ret = get_dbinfo(context, db_binding, "default", &databases); if (ret == 0 && databases != NULL) dt = &databases->next; for ( ; db_binding != NULL; db_binding = db_binding->next) { if (db_binding->type != krb5_config_list) continue; ret = get_dbinfo(context, db_binding->u.list, db_binding->name, &di); if (ret) krb5_err(context, 1, ret, "failed getting realm"); if (di == NULL) continue; if (dt) *dt = di; else { hdb_free_dbinfo(context, &databases); databases = di; } dt = &di->next; } } if (databases == NULL) { /* if there are none specified, create one and use defaults */ databases = calloc(1, sizeof(*databases)); databases->label = strdup("default"); } for (di = databases; di; di = di->next) { if (di->dbname == NULL) { di->dbname = strdup(default_dbname); if (di->mkey_file == NULL) di->mkey_file = strdup(default_mkey); } if (di->mkey_file == NULL) { p = strrchr(di->dbname, '.'); if(p == NULL || strchr(p, '/') != NULL) /* final pathname component does not contain a . */ ret = asprintf(&di->mkey_file, "%s.mkey", di->dbname); else /* the filename is something.else, replace .else with .mkey */ ret = asprintf(&di->mkey_file, "%.*s.mkey", (int)(p - di->dbname), di->dbname); if (ret == -1) { hdb_free_dbinfo(context, &databases); return ENOMEM; } } if(di->acl_file == NULL) di->acl_file = strdup(default_acl); } *dbp = databases; return 0; } struct hdb_dbinfo * hdb_dbinfo_get_next(struct hdb_dbinfo *dbp, struct hdb_dbinfo *dbprevp) { if (dbprevp == NULL) return dbp; else return dbprevp->next; } const char * hdb_dbinfo_get_label(krb5_context context, struct hdb_dbinfo *dbp) { return dbp->label; } const char * hdb_dbinfo_get_realm(krb5_context context, struct hdb_dbinfo *dbp) { return dbp->realm; } const char * hdb_dbinfo_get_dbname(krb5_context context, struct hdb_dbinfo *dbp) { return dbp->dbname; } const char * hdb_dbinfo_get_mkey_file(krb5_context context, struct hdb_dbinfo *dbp) { return dbp->mkey_file; } const char * hdb_dbinfo_get_acl_file(krb5_context context, struct hdb_dbinfo *dbp) { return dbp->acl_file; } const char * hdb_dbinfo_get_log_file(krb5_context context, struct hdb_dbinfo *dbp) { return dbp->log_file; } const krb5_config_binding * hdb_dbinfo_get_binding(krb5_context context, struct hdb_dbinfo *dbp) { return dbp->binding; } void hdb_free_dbinfo(krb5_context context, struct hdb_dbinfo **dbp) { struct hdb_dbinfo *di, *ndi; for(di = *dbp; di != NULL; di = ndi) { ndi = di->next; free (di->label); free (di->realm); free (di->dbname); free (di->mkey_file); free (di->acl_file); free (di->log_file); free(di); } *dbp = NULL; } /** * Return the directory where the hdb database resides. * * @param context Kerberos 5 context. * * @return string pointing to directory. */ const char * hdb_db_dir(krb5_context context) { const char *p; p = krb5_config_get_string(context, NULL, "hdb", "db-dir", NULL); if (p) return p; return HDB_DB_DIR; } /** * Return the default hdb database resides. * * @param context Kerberos 5 context. * * @return string pointing to directory. */ const char * hdb_default_db(krb5_context context) { return HDB_DEFAULT_DB; } heimdal-7.5.0/lib/hdb/hdb_locl.h0000644000175000017500000000442013026237312014473 0ustar niknik/* * Copyright (c) 1997-2001 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ /* $Id$ */ #ifndef __HDB_LOCL_H__ #define __HDB_LOCL_H__ #include #include #include #include #include #include #include #ifdef HAVE_SYS_TYPES_H #include #endif #ifdef HAVE_UNISTD_H #include #endif #ifdef HAVE_FCNTL_H #include #endif #ifdef HAVE_SYS_FILE_H #include #endif #ifdef HAVE_LIMITS_H #include #endif #include #include "crypto-headers.h" #include #include #include #define HDB_DEFAULT_DB HDB_DB_DIR "/heimdal" #define HDB_DB_FORMAT_ENTRY "hdb/db-format" #endif /* __HDB_LOCL_H__ */ heimdal-7.5.0/lib/hdb/test_mkey.c0000644000175000017500000000221413026237312014723 0ustar niknik #include "hdb_locl.h" #include #include static char *mkey_file; static int help_flag; static int version_flag; struct getargs args[] = { { "mkey-file", 0, arg_string, &mkey_file, NULL, NULL }, { "help", 'h', arg_flag, &help_flag, NULL, NULL }, { "version", 0, arg_flag, &version_flag, NULL, NULL } }; static int num_args = sizeof(args) / sizeof(args[0]); int main(int argc, char **argv) { krb5_context context; int ret, o = 0; setprogname(argv[0]); if(getarg(args, num_args, argc, argv, &o)) krb5_std_usage(1, args, num_args); if(help_flag) krb5_std_usage(0, args, num_args); if(version_flag){ print_version(NULL); exit(0); } ret = krb5_init_context(&context); if (ret) errx(1, "krb5_init_context failed: %d", ret); if (mkey_file) { hdb_master_key mkey; ret = hdb_read_master_key(context, mkey_file, &mkey); if (ret) krb5_err(context, 1, ret, "failed to read master key %s", mkey_file); hdb_free_master_key(context, mkey); } else krb5_errx(context, 1, "no command option given"); krb5_free_context(context); return 0; } heimdal-7.5.0/lib/hdb/ndbm.c0000644000175000017500000002343613026237312013650 0ustar niknik/* * Copyright (c) 1997 - 2001 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "hdb_locl.h" #if HAVE_NDBM #if defined(HAVE_GDBM_NDBM_H) #include #define WRITE_SUPPORT 1 #elif defined(HAVE_NDBM_H) #include #elif defined(HAVE_DBM_H) #define WRITE_SUPPORT 1 #include #endif struct ndbm_db { DBM *db; int lock_fd; }; static krb5_error_code NDBM_destroy(krb5_context context, HDB *db) { hdb_clear_master_key (context, db); free(db->hdb_name); free(db); return 0; } static krb5_error_code NDBM_lock(krb5_context context, HDB *db, int operation) { struct ndbm_db *d = db->hdb_db; return hdb_lock(d->lock_fd, operation); } static krb5_error_code NDBM_unlock(krb5_context context, HDB *db) { struct ndbm_db *d = db->hdb_db; return hdb_unlock(d->lock_fd); } static krb5_error_code NDBM_seq(krb5_context context, HDB *db, unsigned flags, hdb_entry_ex *entry, int first) { struct ndbm_db *d = (struct ndbm_db *)db->hdb_db; datum key, value; krb5_data key_data, data; krb5_error_code ret = 0; if(first) key = dbm_firstkey(d->db); else key = dbm_nextkey(d->db); if(key.dptr == NULL) return HDB_ERR_NOENTRY; key_data.data = key.dptr; key_data.length = key.dsize; ret = db->hdb_lock(context, db, HDB_RLOCK); if(ret) return ret; value = dbm_fetch(d->db, key); db->hdb_unlock(context, db); data.data = value.dptr; data.length = value.dsize; memset(entry, 0, sizeof(*entry)); if(hdb_value2entry(context, &data, &entry->entry)) return NDBM_seq(context, db, flags, entry, 0); if (db->hdb_master_key_set && (flags & HDB_F_DECRYPT)) { ret = hdb_unseal_keys (context, db, &entry->entry); if (ret) hdb_free_entry (context, entry); } if (ret == 0 && entry->entry.principal == NULL) { entry->entry.principal = malloc (sizeof(*entry->entry.principal)); if (entry->entry.principal == NULL) { hdb_free_entry (context, entry); ret = ENOMEM; krb5_set_error_message(context, ret, "malloc: out of memory"); } else { hdb_key2principal (context, &key_data, entry->entry.principal); } } return ret; } static krb5_error_code NDBM_firstkey(krb5_context context, HDB *db,unsigned flags,hdb_entry_ex *entry) { return NDBM_seq(context, db, flags, entry, 1); } static krb5_error_code NDBM_nextkey(krb5_context context, HDB *db, unsigned flags,hdb_entry_ex *entry) { return NDBM_seq(context, db, flags, entry, 0); } static krb5_error_code open_lock_file(krb5_context context, const char *db_name, int *fd) { char *lock_file; /* lock old and new databases */ asprintf(&lock_file, "%s.lock", db_name); if(lock_file == NULL) { krb5_set_error_message(context, ENOMEM, "malloc: out of memory"); return ENOMEM; } *fd = open(lock_file, O_RDWR | O_CREAT, 0600); free(lock_file); if(*fd < 0) { int ret = errno; krb5_set_error_message(context, ret, "open(%s): %s", lock_file, strerror(ret)); return ret; } return 0; } static krb5_error_code NDBM_rename(krb5_context context, HDB *db, const char *new_name) { int ret; char *old_dir, *old_pag, *new_dir, *new_pag; int old_lock_fd, new_lock_fd; /* lock old and new databases */ ret = open_lock_file(context, db->hdb_name, &old_lock_fd); if (ret) return ret; ret = hdb_lock(old_lock_fd, HDB_WLOCK); if(ret) { close(old_lock_fd); return ret; } ret = open_lock_file(context, new_name, &new_lock_fd); if (ret) { hdb_unlock(old_lock_fd); close(old_lock_fd); return ret; } ret = hdb_lock(new_lock_fd, HDB_WLOCK); if(ret) { hdb_unlock(old_lock_fd); close(old_lock_fd); close(new_lock_fd); return ret; } asprintf(&old_dir, "%s.dir", db->hdb_name); asprintf(&old_pag, "%s.pag", db->hdb_name); asprintf(&new_dir, "%s.dir", new_name); asprintf(&new_pag, "%s.pag", new_name); ret = rename(old_dir, new_dir) || rename(old_pag, new_pag); if (ret) { ret = errno; if (ret == 0) ret = EPERM; krb5_set_error_message(context, ret, "rename: %s", strerror(ret)); } free(old_dir); free(old_pag); free(new_dir); free(new_pag); hdb_unlock(new_lock_fd); hdb_unlock(old_lock_fd); close(new_lock_fd); close(old_lock_fd); if(ret) return ret; free(db->hdb_name); db->hdb_name = strdup(new_name); return 0; } static krb5_error_code NDBM__get(krb5_context context, HDB *db, krb5_data key, krb5_data *reply) { struct ndbm_db *d = (struct ndbm_db *)db->hdb_db; datum k, v; int code; k.dptr = key.data; k.dsize = key.length; code = db->hdb_lock(context, db, HDB_RLOCK); if(code) return code; v = dbm_fetch(d->db, k); db->hdb_unlock(context, db); if(v.dptr == NULL) return HDB_ERR_NOENTRY; krb5_data_copy(reply, v.dptr, v.dsize); return 0; } static krb5_error_code NDBM__put(krb5_context context, HDB *db, int replace, krb5_data key, krb5_data value) { #ifdef WRITE_SUPPORT struct ndbm_db *d = (struct ndbm_db *)db->hdb_db; datum k, v; int code; k.dptr = key.data; k.dsize = key.length; v.dptr = value.data; v.dsize = value.length; code = db->hdb_lock(context, db, HDB_WLOCK); if(code) return code; code = dbm_store(d->db, k, v, replace ? DBM_REPLACE : DBM_INSERT); db->hdb_unlock(context, db); if(code == 1) return HDB_ERR_EXISTS; if (code < 0) return code; return 0; #else return HDB_ERR_NO_WRITE_SUPPORT; #endif } static krb5_error_code NDBM__del(krb5_context context, HDB *db, krb5_data key) { struct ndbm_db *d = (struct ndbm_db *)db->hdb_db; datum k; int code; krb5_error_code ret; k.dptr = key.data; k.dsize = key.length; ret = db->hdb_lock(context, db, HDB_WLOCK); if(ret) return ret; code = dbm_delete(d->db, k); db->hdb_unlock(context, db); if(code < 0) return errno; return 0; } static krb5_error_code NDBM_close(krb5_context context, HDB *db) { struct ndbm_db *d = db->hdb_db; dbm_close(d->db); close(d->lock_fd); free(d); return 0; } static krb5_error_code NDBM_open(krb5_context context, HDB *db, int flags, mode_t mode) { krb5_error_code ret; struct ndbm_db *d = malloc(sizeof(*d)); if(d == NULL) { krb5_set_error_message(context, ENOMEM, "malloc: out of memory"); return ENOMEM; } d->db = dbm_open((char*)db->hdb_name, flags, mode); if(d->db == NULL){ ret = errno; free(d); krb5_set_error_message(context, ret, "dbm_open(%s): %s", db->hdb_name, strerror(ret)); return ret; } ret = open_lock_file(context, db->hdb_name, &d->lock_fd); if (ret) { ret = errno; dbm_close(d->db); free(d); krb5_set_error_message(context, ret, "open(lock file): %s", strerror(ret)); return ret; } db->hdb_db = d; if((flags & O_ACCMODE) == O_RDONLY) ret = hdb_check_db_format(context, db); else ret = hdb_init_db(context, db); if(ret == HDB_ERR_NOENTRY) return 0; if (ret) { NDBM_close(context, db); krb5_set_error_message(context, ret, "hdb_open: failed %s database %s", (flags & O_ACCMODE) == O_RDONLY ? "checking format of" : "initialize", db->hdb_name); } return ret; } krb5_error_code hdb_ndbm_create(krb5_context context, HDB **db, const char *filename) { *db = calloc(1, sizeof(**db)); if (*db == NULL) { krb5_set_error_message(context, ENOMEM, "malloc: out of memory"); return ENOMEM; } (*db)->hdb_db = NULL; (*db)->hdb_name = strdup(filename); if ((*db)->hdb_name == NULL) { free(*db); *db = NULL; krb5_set_error_message(context, ENOMEM, "malloc: out of memory"); return ENOMEM; } (*db)->hdb_master_key_set = 0; (*db)->hdb_openp = 0; (*db)->hdb_capability_flags = HDB_CAP_F_HANDLE_ENTERPRISE_PRINCIPAL; (*db)->hdb_open = NDBM_open; (*db)->hdb_close = NDBM_close; (*db)->hdb_fetch_kvno = _hdb_fetch_kvno; (*db)->hdb_store = _hdb_store; (*db)->hdb_remove = _hdb_remove; (*db)->hdb_firstkey = NDBM_firstkey; (*db)->hdb_nextkey= NDBM_nextkey; (*db)->hdb_lock = NDBM_lock; (*db)->hdb_unlock = NDBM_unlock; (*db)->hdb_rename = NDBM_rename; (*db)->hdb__get = NDBM__get; (*db)->hdb__put = NDBM__put; (*db)->hdb__del = NDBM__del; (*db)->hdb_destroy = NDBM_destroy; return 0; } #endif /* HAVE_NDBM */ heimdal-7.5.0/lib/hdb/hdb-mitdb.c0000644000175000017500000011673313212137553014570 0ustar niknik/* * Copyright (c) 1997 - 2001 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Portions Copyright (c) 2009 Apple Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #define KRB5_KDB_DISALLOW_POSTDATED 0x00000001 #define KRB5_KDB_DISALLOW_FORWARDABLE 0x00000002 #define KRB5_KDB_DISALLOW_TGT_BASED 0x00000004 #define KRB5_KDB_DISALLOW_RENEWABLE 0x00000008 #define KRB5_KDB_DISALLOW_PROXIABLE 0x00000010 #define KRB5_KDB_DISALLOW_DUP_SKEY 0x00000020 #define KRB5_KDB_DISALLOW_ALL_TIX 0x00000040 #define KRB5_KDB_REQUIRES_PRE_AUTH 0x00000080 #define KRB5_KDB_REQUIRES_HW_AUTH 0x00000100 #define KRB5_KDB_REQUIRES_PWCHANGE 0x00000200 #define KRB5_KDB_DISALLOW_SVR 0x00001000 #define KRB5_KDB_PWCHANGE_SERVICE 0x00002000 #define KRB5_KDB_SUPPORT_DESMD5 0x00004000 #define KRB5_KDB_NEW_PRINC 0x00008000 /* key: krb5_unparse_name + NUL 16: baselength 32: attributes 32: max time 32: max renewable time 32: client expire 32: passwd expire 32: last successful passwd 32: last failed attempt 32: num of failed attempts 16: num tl data 16: num data data 16: principal length length: principal for num tl data times 16: tl data type 16: tl data length length: length for num key data times 16: version (num keyblocks) 16: kvno for version times: 16: type 16: length length: keydata key_data_contents[0] int16: length read-of-data: key-encrypted, key-usage 0, master-key salt: version2 = salt in key_data->key_data_contents[1] else default salt. */ #include "hdb_locl.h" static void attr_to_flags(unsigned attr, HDBFlags *flags) { flags->postdate = !(attr & KRB5_KDB_DISALLOW_POSTDATED); flags->forwardable = !(attr & KRB5_KDB_DISALLOW_FORWARDABLE); flags->initial = !!(attr & KRB5_KDB_DISALLOW_TGT_BASED); flags->renewable = !(attr & KRB5_KDB_DISALLOW_RENEWABLE); flags->proxiable = !(attr & KRB5_KDB_DISALLOW_PROXIABLE); /* DUP_SKEY */ flags->invalid = !!(attr & KRB5_KDB_DISALLOW_ALL_TIX); flags->require_preauth = !!(attr & KRB5_KDB_REQUIRES_PRE_AUTH); flags->require_hwauth = !!(attr & KRB5_KDB_REQUIRES_HW_AUTH); flags->server = !(attr & KRB5_KDB_DISALLOW_SVR); flags->change_pw = !!(attr & KRB5_KDB_PWCHANGE_SERVICE); flags->client = 1; /* XXX */ } #define KDB_V1_BASE_LENGTH 38 #define CHECK(x) do { if ((x)) goto out; } while(0) #ifdef HAVE_DB1 static krb5_error_code mdb_principal2key(krb5_context context, krb5_const_principal principal, krb5_data *key) { krb5_error_code ret; char *str; ret = krb5_unparse_name(context, principal, &str); if (ret) return ret; key->data = str; key->length = strlen(str) + 1; return 0; } #endif /* HAVE_DB1 */ #define KRB5_KDB_SALTTYPE_NORMAL 0 #define KRB5_KDB_SALTTYPE_V4 1 #define KRB5_KDB_SALTTYPE_NOREALM 2 #define KRB5_KDB_SALTTYPE_ONLYREALM 3 #define KRB5_KDB_SALTTYPE_SPECIAL 4 #define KRB5_KDB_SALTTYPE_AFS3 5 #define KRB5_KDB_SALTTYPE_CERTHASH 6 static krb5_error_code fix_salt(krb5_context context, hdb_entry *ent, Key *k) { krb5_error_code ret; Salt *salt = k->salt; /* fix salt type */ switch((int)salt->type) { case KRB5_KDB_SALTTYPE_NORMAL: salt->type = KRB5_PADATA_PW_SALT; break; case KRB5_KDB_SALTTYPE_V4: krb5_data_free(&salt->salt); salt->type = KRB5_PADATA_PW_SALT; break; case KRB5_KDB_SALTTYPE_NOREALM: { size_t len; size_t i; char *p; len = 0; for (i = 0; i < ent->principal->name.name_string.len; ++i) len += strlen(ent->principal->name.name_string.val[i]); ret = krb5_data_alloc (&salt->salt, len); if (ret) return ret; p = salt->salt.data; for (i = 0; i < ent->principal->name.name_string.len; ++i) { memcpy (p, ent->principal->name.name_string.val[i], strlen(ent->principal->name.name_string.val[i])); p += strlen(ent->principal->name.name_string.val[i]); } salt->type = KRB5_PADATA_PW_SALT; break; } case KRB5_KDB_SALTTYPE_ONLYREALM: krb5_data_free(&salt->salt); ret = krb5_data_copy(&salt->salt, ent->principal->realm, strlen(ent->principal->realm)); if(ret) return ret; salt->type = KRB5_PADATA_PW_SALT; break; case KRB5_KDB_SALTTYPE_SPECIAL: salt->type = KRB5_PADATA_PW_SALT; break; case KRB5_KDB_SALTTYPE_AFS3: krb5_data_free(&salt->salt); ret = krb5_data_copy(&salt->salt, ent->principal->realm, strlen(ent->principal->realm)); if(ret) return ret; salt->type = KRB5_PADATA_AFS3_SALT; break; case KRB5_KDB_SALTTYPE_CERTHASH: krb5_data_free(&salt->salt); free(k->salt); k->salt = NULL; break; default: abort(); } return 0; } /** * This function takes a key from a krb5_storage from an MIT KDB encoded * entry and places it in the given Key object. * * @param context Context * @param entry HDB entry * @param sp krb5_storage with current offset set to the beginning of a * key * @param version See comments in caller body for the backstory on this * @param k Key * to load the key into */ static krb5_error_code mdb_keyvalue2key(krb5_context context, hdb_entry *entry, krb5_storage *sp, uint16_t version, Key *k) { size_t i; uint16_t u16, type; krb5_error_code ret; k->mkvno = malloc(sizeof(*k->mkvno)); if (k->mkvno == NULL) { ret = ENOMEM; goto out; } *k->mkvno = 1; for (i = 0; i < version; i++) { CHECK(ret = krb5_ret_uint16(sp, &type)); CHECK(ret = krb5_ret_uint16(sp, &u16)); if (i == 0) { /* This "version" means we have a key */ k->key.keytype = type; /* * MIT stores keys encrypted keys as {16-bit length * of plaintext key, {encrypted key}}. The reason * for this is that the Kerberos cryptosystem is not * length-preserving. Heimdal's approach is to * truncate the plaintext to the expected length of * the key given its enctype, so we ignore this * 16-bit length-of-plaintext-key field. */ if (u16 > 2) { krb5_storage_seek(sp, 2, SEEK_CUR); /* skip real length */ k->key.keyvalue.length = u16 - 2; /* adjust cipher len */ k->key.keyvalue.data = malloc(k->key.keyvalue.length); krb5_storage_read(sp, k->key.keyvalue.data, k->key.keyvalue.length); } else { /* We'll ignore this key; see our caller */ k->key.keyvalue.length = 0; k->key.keyvalue.data = NULL; krb5_storage_seek(sp, u16, SEEK_CUR); /* skip real length */ } } else if (i == 1) { /* This "version" means we have a salt */ k->salt = calloc(1, sizeof(*k->salt)); if (k->salt == NULL) { ret = ENOMEM; goto out; } k->salt->type = type; if (u16 != 0) { k->salt->salt.data = malloc(u16); if (k->salt->salt.data == NULL) { ret = ENOMEM; goto out; } k->salt->salt.length = u16; krb5_storage_read(sp, k->salt->salt.data, k->salt->salt.length); } fix_salt(context, entry, k); } else { /* * Whatever this "version" might be, we skip it * * XXX A krb5.conf parameter requesting that we log * about strangeness like this, or return an error * from here, might be nice. */ krb5_storage_seek(sp, u16, SEEK_CUR); } } return 0; out: free_Key(k); return ret; } static krb5_error_code add_1des_dup(krb5_context context, Keys *keys, Key *key, krb5_keytype keytype) { key->key.keytype = keytype; return add_Keys(keys, key); } /* * This monstrosity is here so we can avoid having to do enctype * similarity checking in the KDC. This helper function dups 1DES keys * in a keyset for all the similar 1DES enctypes for which keys are * missing. And, of course, we do this only if there's any 1DES keys in * the keyset to begin with. */ static krb5_error_code dup_similar_keys_in_keyset(krb5_context context, Keys *keys) { krb5_error_code ret; size_t i, k; Key key; int keyset_has_1des_crc = 0; int keyset_has_1des_md4 = 0; int keyset_has_1des_md5 = 0; memset(&key, 0, sizeof (key)); k = keys->len; for (i = 0; i < keys->len; i++) { if (keys->val[i].key.keytype == ETYPE_DES_CBC_CRC) { keyset_has_1des_crc = 1; if (k == keys->len) k = i; } else if (keys->val[i].key.keytype == ETYPE_DES_CBC_MD4) { keyset_has_1des_crc = 1; if (k == keys->len) k = i; } else if (keys->val[i].key.keytype == ETYPE_DES_CBC_MD5) { keyset_has_1des_crc = 1; if (k == keys->len) k = i; } } if (k == keys->len) return 0; ret = copy_Key(&keys->val[k], &key); if (ret) return ret; if (!keyset_has_1des_crc) { ret = add_1des_dup(context, keys, &key, ETYPE_DES_CBC_CRC); if (ret) goto out; } if (!keyset_has_1des_md4) { ret = add_1des_dup(context, keys, &key, ETYPE_DES_CBC_MD4); if (ret) goto out; } if (!keyset_has_1des_md5) { ret = add_1des_dup(context, keys, &key, ETYPE_DES_CBC_MD5); if (ret) goto out; } out: free_Key(&key); return ret; } static krb5_error_code dup_similar_keys(krb5_context context, hdb_entry *entry) { krb5_error_code ret; HDB_Ext_KeySet *hist_keys; HDB_extension *extp; size_t i; ret = dup_similar_keys_in_keyset(context, &entry->keys); if (ret) return ret; extp = hdb_find_extension(entry, choice_HDB_extension_data_hist_keys); if (extp == NULL) return 0; hist_keys = &extp->data.u.hist_keys; for (i = 0; i < hist_keys->len; i++) { ret = dup_similar_keys_in_keyset(context, &hist_keys->val[i].keys); if (ret) return ret; } return 0; } /** * This function parses an MIT krb5 encoded KDB entry and fills in the * given HDB entry with it. * * @param context krb5_context * @param data Encoded MIT KDB entry * @param target_kvno Desired kvno, or 0 for the entry's current kvno * @param entry Desired kvno, or 0 for the entry's current kvno */ krb5_error_code _hdb_mdb_value2entry(krb5_context context, krb5_data *data, krb5_kvno target_kvno, hdb_entry *entry) { krb5_error_code ret; krb5_storage *sp; Key k; krb5_kvno key_kvno; uint32_t u32; uint16_t u16, num_keys, num_tl; ssize_t sz; size_t i; char *p; memset(&k, 0, sizeof (k)); memset(entry, 0, sizeof(*entry)); sp = krb5_storage_from_data(data); if (sp == NULL) { krb5_set_error_message(context, ENOMEM, "out of memory"); return ENOMEM; } krb5_storage_set_byteorder(sp, KRB5_STORAGE_BYTEORDER_LE); /* * 16: baselength * * The story here is that these 16 bits have to be a constant: * KDB_V1_BASE_LENGTH. Once upon a time a different value here * would have been used to indicate the presence of "extra data" * between the "base" contents and the {principal name, TL data, * keys} that follow it. Nothing supports such "extra data" * nowadays, so neither do we here. * * XXX But... surely we ought to log about this extra data, or skip * it, or something, in case anyone has MIT KDBs with ancient * entries in them... Logging would allow the admin to know which * entries to dump with MIT krb5's kdb5_util. But logging would be * noisy. For now we do nothing. */ CHECK(ret = krb5_ret_uint16(sp, &u16)); if (u16 != KDB_V1_BASE_LENGTH) { ret = EINVAL; goto out; } /* 32: attributes */ CHECK(ret = krb5_ret_uint32(sp, &u32)); attr_to_flags(u32, &entry->flags); /* 32: max time */ CHECK(ret = krb5_ret_uint32(sp, &u32)); if (u32) { entry->max_life = malloc(sizeof(*entry->max_life)); *entry->max_life = u32; } /* 32: max renewable time */ CHECK(ret = krb5_ret_uint32(sp, &u32)); if (u32) { entry->max_renew = malloc(sizeof(*entry->max_renew)); *entry->max_renew = u32; } /* 32: client expire */ CHECK(ret = krb5_ret_uint32(sp, &u32)); if (u32) { entry->valid_end = malloc(sizeof(*entry->valid_end)); *entry->valid_end = u32; } /* 32: passwd expire */ CHECK(ret = krb5_ret_uint32(sp, &u32)); if (u32) { entry->pw_end = malloc(sizeof(*entry->pw_end)); *entry->pw_end = u32; } /* 32: last successful passwd */ CHECK(ret = krb5_ret_uint32(sp, &u32)); /* 32: last failed attempt */ CHECK(ret = krb5_ret_uint32(sp, &u32)); /* 32: num of failed attempts */ CHECK(ret = krb5_ret_uint32(sp, &u32)); /* 16: num tl data */ CHECK(ret = krb5_ret_uint16(sp, &u16)); num_tl = u16; /* 16: num key data */ CHECK(ret = krb5_ret_uint16(sp, &u16)); num_keys = u16; /* 16: principal length */ CHECK(ret = krb5_ret_uint16(sp, &u16)); /* length: principal */ { /* * Note that the principal name includes the NUL in the entry, * but we don't want to take chances, so we add an extra NUL. */ p = malloc(u16 + 1); if (p == NULL) { ret = ENOMEM; goto out; } sz = krb5_storage_read(sp, p, u16); if (sz != u16) { ret = EINVAL; /* XXX */ goto out; } p[u16] = '\0'; CHECK(ret = krb5_parse_name(context, p, &entry->principal)); free(p); } /* for num tl data times 16: tl data type 16: tl data length length: length */ #define mit_KRB5_TL_LAST_PWD_CHANGE 1 #define mit_KRB5_TL_MOD_PRINC 2 for (i = 0; i < num_tl; i++) { int tl_type; krb5_principal modby; /* 16: TL data type */ CHECK(ret = krb5_ret_uint16(sp, &u16)); tl_type = u16; /* 16: TL data length */ CHECK(ret = krb5_ret_uint16(sp, &u16)); /* * For rollback to MIT purposes we really must understand some * TL data! * * XXX Move all this to separate functions, one per-TL type. */ switch (tl_type) { case mit_KRB5_TL_LAST_PWD_CHANGE: CHECK(ret = krb5_ret_uint32(sp, &u32)); CHECK(ret = hdb_entry_set_pw_change_time(context, entry, u32)); break; case mit_KRB5_TL_MOD_PRINC: if (u16 < 5) { ret = EINVAL; /* XXX */ goto out; } CHECK(ret = krb5_ret_uint32(sp, &u32)); /* mod time */ p = malloc(u16 - 4 + 1); if (!p) { ret = ENOMEM; goto out; } p[u16 - 4] = '\0'; sz = krb5_storage_read(sp, p, u16 - 4); if (sz != u16 - 4) { ret = EINVAL; /* XXX */ goto out; } CHECK(ret = krb5_parse_name(context, p, &modby)); ret = hdb_set_last_modified_by(context, entry, modby, u32); krb5_free_principal(context, modby); free(p); break; default: krb5_storage_seek(sp, u16, SEEK_CUR); break; } } /* * for num key data times * 16: "version" * 16: kvno * for version times: * 16: type * 16: length * length: keydata * * "version" here is really 1 or 2, the first meaning there's only * keys for this kvno, the second meaning there's keys and salt[s?]. * That's right... hold that gag reflex, you can do it. */ for (i = 0; i < num_keys; i++) { uint16_t version; CHECK(ret = krb5_ret_uint16(sp, &u16)); version = u16; CHECK(ret = krb5_ret_uint16(sp, &u16)); key_kvno = u16; ret = mdb_keyvalue2key(context, entry, sp, version, &k); if (ret) goto out; if (k.key.keytype == 0 || k.key.keyvalue.length == 0) { /* * Older MIT KDBs may have enctype 0 / length 0 keys. We * ignore these. */ free_Key(&k); continue; } if ((target_kvno == 0 && entry->kvno < key_kvno) || (target_kvno == key_kvno && entry->kvno != target_kvno)) { /* * MIT's KDB doesn't keep track of kvno. The highest kvno * is the current kvno, and we just found a new highest * kvno or the desired kvno. * * Note that there's no guarantee of any key ordering, but * generally MIT KDB entries have keys in strictly * descending kvno order. * * XXX We do assume that keys are clustered by kvno. If * not, then bad. It might be possible to construct * non-clustered keys via the kadm5 API. It wouldn't be * hard to cope with this, since if it happens the worst * that will happen is that some of the current keys can be * found in the history extension, and we could just pull * them back out in that case. */ ret = hdb_add_current_keys_to_history(context, entry); if (ret) goto out; free_Keys(&entry->keys); ret = add_Keys(&entry->keys, &k); free_Key(&k); if (ret) goto out; entry->kvno = key_kvno; continue; } if (entry->kvno == key_kvno) { /* * Note that if key_kvno == 0 and target_kvno == 0 then we * end up adding those keys here. Yeah, kvno 0 is very * special for us, but just in case, we keep such keys. */ ret = add_Keys(&entry->keys, &k); free_Key(&k); if (ret) goto out; entry->kvno = key_kvno; } else { ret = hdb_add_history_key(context, entry, key_kvno, &k); if (ret) goto out; free_Key(&k); } } if (target_kvno != 0 && entry->kvno != target_kvno) { ret = HDB_ERR_KVNO_NOT_FOUND; goto out; } krb5_storage_free(sp); return dup_similar_keys(context, entry); out: krb5_storage_free(sp); if (ret == HEIM_ERR_EOF) /* Better error code than "end of file" */ ret = HEIM_ERR_BAD_HDBENT_ENCODING; free_hdb_entry(entry); free_Key(&k); return ret; } #if 0 static krb5_error_code mdb_entry2value(krb5_context context, hdb_entry *entry, krb5_data *data) { return EINVAL; } #endif #if HAVE_DB1 #if defined(HAVE_DB_185_H) #include #elif defined(HAVE_DB_H) #include #endif static krb5_error_code mdb_close(krb5_context context, HDB *db) { DB *d = (DB*)db->hdb_db; (*d->close)(d); return 0; } static krb5_error_code mdb_destroy(krb5_context context, HDB *db) { krb5_error_code ret; ret = hdb_clear_master_key (context, db); free(db->hdb_name); free(db); return ret; } static krb5_error_code mdb_lock(krb5_context context, HDB *db, int operation) { DB *d = (DB*)db->hdb_db; int fd = (*d->fd)(d); krb5_error_code ret; if (db->lock_count > 1) { db->lock_count++; if (db->lock_type == HDB_WLOCK || db->lock_count == operation) return 0; } if(fd < 0) { krb5_set_error_message(context, HDB_ERR_CANT_LOCK_DB, "Can't lock database: %s", db->hdb_name); return HDB_ERR_CANT_LOCK_DB; } ret = hdb_lock(fd, operation); if (ret) return ret; db->lock_count++; return 0; } static krb5_error_code mdb_unlock(krb5_context context, HDB *db) { DB *d = (DB*)db->hdb_db; int fd = (*d->fd)(d); if (db->lock_count > 1) { db->lock_count--; return 0; } heim_assert(db->lock_count == 1, "HDB lock/unlock sequence does not match"); db->lock_count--; if(fd < 0) { krb5_set_error_message(context, HDB_ERR_CANT_LOCK_DB, "Can't unlock database: %s", db->hdb_name); return HDB_ERR_CANT_LOCK_DB; } return hdb_unlock(fd); } static krb5_error_code mdb_seq(krb5_context context, HDB *db, unsigned flags, hdb_entry_ex *entry, int flag) { DB *d = (DB*)db->hdb_db; DBT key, value; krb5_data key_data, data; int code; code = db->hdb_lock(context, db, HDB_RLOCK); if(code == -1) { krb5_set_error_message(context, HDB_ERR_DB_INUSE, "Database %s in use", db->hdb_name); return HDB_ERR_DB_INUSE; } code = (*d->seq)(d, &key, &value, flag); db->hdb_unlock(context, db); /* XXX check value */ if(code == -1) { code = errno; krb5_set_error_message(context, code, "Database %s seq error: %s", db->hdb_name, strerror(code)); return code; } if(code == 1) { krb5_clear_error_message(context); return HDB_ERR_NOENTRY; } key_data.data = key.data; key_data.length = key.size; data.data = value.data; data.length = value.size; memset(entry, 0, sizeof(*entry)); if (_hdb_mdb_value2entry(context, &data, 0, &entry->entry)) return mdb_seq(context, db, flags, entry, R_NEXT); if (db->hdb_master_key_set && (flags & HDB_F_DECRYPT)) { code = hdb_unseal_keys (context, db, &entry->entry); if (code) hdb_free_entry (context, entry); } return code; } static krb5_error_code mdb_firstkey(krb5_context context, HDB *db, unsigned flags, hdb_entry_ex *entry) { return mdb_seq(context, db, flags, entry, R_FIRST); } static krb5_error_code mdb_nextkey(krb5_context context, HDB *db, unsigned flags, hdb_entry_ex *entry) { return mdb_seq(context, db, flags, entry, R_NEXT); } static krb5_error_code mdb_rename(krb5_context context, HDB *db, const char *new_name) { int ret; char *old = NULL; char *new = NULL; if (asprintf(&old, "%s.db", db->hdb_name) < 0) goto out; if (asprintf(&new, "%s.db", new_name) < 0) goto out; ret = rename(old, new); if(ret) goto out; free(db->hdb_name); db->hdb_name = strdup(new_name); errno = 0; out: free(old); free(new); return errno; } static krb5_error_code mdb__get(krb5_context context, HDB *db, krb5_data key, krb5_data *reply) { DB *d = (DB*)db->hdb_db; DBT k, v; int code; k.data = key.data; k.size = key.length; code = db->hdb_lock(context, db, HDB_RLOCK); if(code) return code; code = (*d->get)(d, &k, &v, 0); db->hdb_unlock(context, db); if(code < 0) { code = errno; krb5_set_error_message(context, code, "Database %s get error: %s", db->hdb_name, strerror(code)); return code; } if(code == 1) { krb5_clear_error_message(context); return HDB_ERR_NOENTRY; } krb5_data_copy(reply, v.data, v.size); return 0; } static krb5_error_code mdb__put(krb5_context context, HDB *db, int replace, krb5_data key, krb5_data value) { DB *d = (DB*)db->hdb_db; DBT k, v; int code; k.data = key.data; k.size = key.length; v.data = value.data; v.size = value.length; code = db->hdb_lock(context, db, HDB_WLOCK); if(code) return code; code = (*d->put)(d, &k, &v, replace ? 0 : R_NOOVERWRITE); db->hdb_unlock(context, db); if(code < 0) { code = errno; krb5_set_error_message(context, code, "Database %s put error: %s", db->hdb_name, strerror(code)); return code; } if(code == 1) { krb5_clear_error_message(context); return HDB_ERR_EXISTS; } return 0; } static krb5_error_code mdb__del(krb5_context context, HDB *db, krb5_data key) { DB *d = (DB*)db->hdb_db; DBT k; krb5_error_code code; k.data = key.data; k.size = key.length; code = db->hdb_lock(context, db, HDB_WLOCK); if(code) return code; code = (*d->del)(d, &k, 0); db->hdb_unlock(context, db); if(code == 1) { code = errno; krb5_set_error_message(context, code, "Database %s put error: %s", db->hdb_name, strerror(code)); return code; } if(code < 0) return errno; return 0; } static krb5_error_code mdb_fetch_kvno(krb5_context context, HDB *db, krb5_const_principal principal, unsigned flags, krb5_kvno kvno, hdb_entry_ex *entry) { krb5_data key, value; krb5_error_code ret; ret = mdb_principal2key(context, principal, &key); if (ret) return ret; ret = db->hdb__get(context, db, key, &value); krb5_data_free(&key); if(ret) return ret; ret = _hdb_mdb_value2entry(context, &value, kvno, &entry->entry); krb5_data_free(&value); if (ret) return ret; if (db->hdb_master_key_set && (flags & HDB_F_DECRYPT)) { ret = hdb_unseal_keys (context, db, &entry->entry); if (ret) { hdb_free_entry(context, entry); return ret; } } return 0; } static krb5_error_code mdb_store(krb5_context context, HDB *db, unsigned flags, hdb_entry_ex *entry) { krb5_error_code ret; krb5_storage *sp = NULL; krb5_storage *spent = NULL; krb5_data line = { 0, 0 }; krb5_data kdb_ent = { 0, 0 }; krb5_data key = { 0, 0 }; krb5_data value = { 0, 0 }; ssize_t sz; if ((flags & HDB_F_PRECHECK) && (flags & HDB_F_REPLACE)) return 0; if ((flags & HDB_F_PRECHECK)) { ret = mdb_principal2key(context, entry->entry.principal, &key); if (ret) return ret; ret = db->hdb__get(context, db, key, &value); krb5_data_free(&key); if (ret == 0) krb5_data_free(&value); if (ret == HDB_ERR_NOENTRY) return 0; return ret ? ret : HDB_ERR_EXISTS; } sp = krb5_storage_emem(); if (!sp) return ENOMEM; ret = _hdb_set_master_key_usage(context, db, 0); /* MIT KDB uses KU 0 */ ret = hdb_seal_keys(context, db, &entry->entry); if (ret) return ret; ret = entry2mit_string_int(context, sp, &entry->entry); if (ret) goto out; sz = krb5_storage_write(sp, "\n", 2); /* NUL-terminate */ ret = ENOMEM; if (sz == -1) goto out; ret = krb5_storage_to_data(sp, &line); if (ret) goto out; ret = ENOMEM; spent = krb5_storage_emem(); if (!spent) goto out; ret = _hdb_mit_dump2mitdb_entry(context, line.data, spent); if (ret) goto out; ret = krb5_storage_to_data(spent, &kdb_ent); if (ret) goto out; ret = mdb_principal2key(context, entry->entry.principal, &key); if (ret) goto out; ret = mdb__put(context, db, 1, key, kdb_ent); out: if (sp) krb5_storage_free(sp); if (spent) krb5_storage_free(spent); krb5_data_free(&line); krb5_data_free(&kdb_ent); krb5_data_free(&key); return ret; } static krb5_error_code mdb_remove(krb5_context context, HDB *db, unsigned flags, krb5_const_principal principal) { krb5_error_code code; krb5_data key; krb5_data value = { 0, 0 }; if ((flags & HDB_F_PRECHECK)) { code = db->hdb__get(context, db, key, &value); krb5_data_free(&key); if (code == 0) { krb5_data_free(&value); return 0; } return code; } mdb_principal2key(context, principal, &key); code = db->hdb__del(context, db, key); krb5_data_free(&key); return code; } static krb5_error_code mdb_open(krb5_context context, HDB *db, int flags, mode_t mode) { char *fn; char *actual_fn; krb5_error_code ret; struct stat st; if (asprintf(&fn, "%s.db", db->hdb_name) < 0) { krb5_set_error_message(context, ENOMEM, "malloc: out of memory"); return ENOMEM; } if (stat(fn, &st) == 0) actual_fn = fn; else actual_fn = db->hdb_name; db->hdb_db = dbopen(actual_fn, flags, mode, DB_BTREE, NULL); if (db->hdb_db == NULL) { switch (errno) { #ifdef EFTYPE case EFTYPE: #endif case EINVAL: db->hdb_db = dbopen(actual_fn, flags, mode, DB_HASH, NULL); } } free(fn); if (db->hdb_db == NULL) { ret = errno; krb5_set_error_message(context, ret, "dbopen (%s): %s", db->hdb_name, strerror(ret)); return ret; } #if 0 /* * Don't do this -- MIT won't be able to handle the * HDB_DB_FORMAT_ENTRY key. */ if ((flags & O_ACCMODE) != O_RDONLY) ret = hdb_init_db(context, db); #endif ret = hdb_check_db_format(context, db); if (ret == HDB_ERR_NOENTRY) { krb5_clear_error_message(context); return 0; } if (ret) { mdb_close(context, db); krb5_set_error_message(context, ret, "hdb_open: failed %s database %s", (flags & O_ACCMODE) == O_RDONLY ? "checking format of" : "initialize", db->hdb_name); } return ret; } krb5_error_code hdb_mitdb_create(krb5_context context, HDB **db, const char *filename) { *db = calloc(1, sizeof(**db)); if (*db == NULL) { krb5_set_error_message(context, ENOMEM, "malloc: out of memory"); return ENOMEM; } (*db)->hdb_db = NULL; (*db)->hdb_name = strdup(filename); if ((*db)->hdb_name == NULL) { free(*db); *db = NULL; krb5_set_error_message(context, ENOMEM, "malloc: out of memory"); return ENOMEM; } (*db)->hdb_master_key_set = 0; (*db)->hdb_openp = 0; (*db)->hdb_capability_flags = 0; (*db)->hdb_open = mdb_open; (*db)->hdb_close = mdb_close; (*db)->hdb_fetch_kvno = mdb_fetch_kvno; (*db)->hdb_store = mdb_store; (*db)->hdb_remove = mdb_remove; (*db)->hdb_firstkey = mdb_firstkey; (*db)->hdb_nextkey= mdb_nextkey; (*db)->hdb_lock = mdb_lock; (*db)->hdb_unlock = mdb_unlock; (*db)->hdb_rename = mdb_rename; (*db)->hdb__get = mdb__get; (*db)->hdb__put = mdb__put; (*db)->hdb__del = mdb__del; (*db)->hdb_destroy = mdb_destroy; return 0; } #endif /* HAVE_DB1 */ /* can have any number of princ stanzas. format is as follows (only \n indicates newlines) princ\t%d\t (%d is KRB5_KDB_V1_BASE_LENGTH, always 38) %d\t (strlen of principal e.g. shadow/foo@ANDREW.CMU.EDU) %d\t (number of tl_data) %d\t (number of key data, e.g. how many keys for this user) %d\t (extra data length) %s\t (principal name) %d\t (attributes) %d\t (max lifetime, seconds) %d\t (max renewable life, seconds) %d\t (expiration, seconds since epoch or 2145830400 for never) %d\t (password expiration, seconds, 0 for never) %d\t (last successful auth, seconds since epoch) %d\t (last failed auth, per above) %d\t (failed auth count) foreach tl_data 0 to number of tl_data - 1 as above %d\t%d\t (data type, data length) foreach tl_data 0 to length-1 %02x (tl data contents[element n]) except if tl_data length is 0 %d (always -1) \t foreach key 0 to number of keys - 1 as above %d\t%d\t (key data version, kvno) foreach version 0 to key data version - 1 (a key or a salt) %d\t%d\t(data type for this key, data length for this key) foreach key data length 0 to length-1 %02x (key data contents[element n]) except if key_data length is 0 %d (always -1) \t foreach extra data length 0 to length - 1 %02x (extra data part) unless no extra data %d (always -1) ;\n */ #if 0 /* Why ever did we loop? */ static char * nexttoken(char **p) { char *q; do { q = strsep(p, " \t"); } while(q && *q == '\0'); return q; } #endif static char * nexttoken(char **p, size_t len, const char *what) { char *q; if (*p == NULL) return NULL; q = *p; *p += len; /* Must be followed by a delimiter (right?) */ if (strsep(p, " \t") != q + len) { warnx("No tokens left in dump entry while looking for %s", what); return NULL; } if (*q == '\0') warnx("Empty last token in dump entry while looking for %s", what); return q; } static size_t getdata(char **p, unsigned char *buf, size_t len, const char *what) { size_t i; int v; char *q = nexttoken(p, 0, what); if (q == NULL) { warnx("Failed to find hex-encoded binary data (%s) in dump", what); return 0; } i = 0; while (*q && i < len) { if (sscanf(q, "%02x", &v) != 1) break; buf[i++] = v; q += 2; } return i; } static int getint(char **p, const char *what) { int val; char *q = nexttoken(p, 0, what); if (!q) { warnx("Failed to find a signed integer (%s) in dump", what); return -1; } if (sscanf(q, "%d", &val) != 1) return -1; return val; } static unsigned int getuint(char **p, const char *what) { int val; char *q = nexttoken(p, 0, what); if (!q) { warnx("Failed to find an unsigned integer (%s) in dump", what); return 0; } if (sscanf(q, "%u", &val) != 1) return 0; return val; } #define KRB5_KDB_SALTTYPE_NORMAL 0 #define KRB5_KDB_SALTTYPE_V4 1 #define KRB5_KDB_SALTTYPE_NOREALM 2 #define KRB5_KDB_SALTTYPE_ONLYREALM 3 #define KRB5_KDB_SALTTYPE_SPECIAL 4 #define KRB5_KDB_SALTTYPE_AFS3 5 #define CHECK_UINT(num) \ if ((num) < 0 || (num) > INT_MAX) return EINVAL #define CHECK_UINT16(num) \ if ((num) < 0 || (num) > 1<<15) return EINVAL #define CHECK_NUM(num, maxv) \ if ((num) > (maxv)) return EINVAL /* * This utility function converts an MIT dump entry to an MIT on-disk * encoded entry, which can then be decoded with _hdb_mdb_value2entry(). * This allows us to have a single decoding function (_hdb_mdb_value2entry), * which makes the code cleaner (less code duplication), if a bit less * efficient. It also will allow us to have a function to dump an HDB * entry in MIT format so we can dump HDB into MIT format for rollback * purposes. And that will allow us to write to MIT KDBs, again * somewhat inefficiently, also for migration/rollback purposes. */ int _hdb_mit_dump2mitdb_entry(krb5_context context, char *line, krb5_storage *sp) { krb5_error_code ret = EINVAL; char *p = line, *q; char *princ; ssize_t sz; size_t i; size_t princ_len; unsigned int num_tl_data; size_t num_key_data; unsigned int attributes; int tmp; krb5_storage_set_byteorder(sp, KRB5_STORAGE_BYTEORDER_LE); q = nexttoken(&p, 0, "record type (princ or policy)"); if (strcmp(q, "kdb5_util") == 0 || strcmp(q, "policy") == 0 || strcmp(q, "princ") != 0) { warnx("Supposed MIT dump entry does not start with 'kdb5_util', " "'policy', nor 'princ'"); return -1; } if (getint(&p, "constant '38'") != 38) { warnx("Dump entry does not start with '38'"); return EINVAL; } #define KDB_V1_BASE_LENGTH 38 ret = krb5_store_int16(sp, KDB_V1_BASE_LENGTH); if (ret) return ret; princ_len = getuint(&p, "principal name length"); if (princ_len > (1<<15) - 1) { warnx("Principal name in dump entry too long (%llu)", (unsigned long long)princ_len); return EINVAL; } num_tl_data = getuint(&p, "number of TL data"); num_key_data = getuint(&p, "number of key data"); getint(&p, "5th field, length of 'extra data'"); princ = nexttoken(&p, (int)princ_len, "principal name"); if (princ == NULL) { warnx("Failed to read principal name (expected length %llu)", (unsigned long long)princ_len); return -1; } attributes = getuint(&p, "attributes"); ret = krb5_store_uint32(sp, attributes); if (ret) return ret; tmp = getint(&p, "max life"); CHECK_UINT(tmp); ret = krb5_store_uint32(sp, tmp); if (ret) return ret; tmp = getint(&p, "max renewable life"); CHECK_UINT(tmp); ret = krb5_store_uint32(sp, tmp); if (ret) return ret; tmp = getint(&p, "expiration"); CHECK_UINT(tmp); ret = krb5_store_uint32(sp, tmp); if (ret) return ret; tmp = getint(&p, "pw expiration"); CHECK_UINT(tmp); ret = krb5_store_uint32(sp, tmp); if (ret) return ret; tmp = getint(&p, "last auth"); CHECK_UINT(tmp); ret = krb5_store_uint32(sp, tmp); if (ret) return ret; tmp = getint(&p, "last failed auth"); CHECK_UINT(tmp); ret = krb5_store_uint32(sp, tmp); if (ret) return ret; tmp = getint(&p,"fail auth count"); CHECK_UINT(tmp); ret = krb5_store_uint32(sp, tmp); if (ret) return ret; /* add TL data count */ CHECK_NUM(num_tl_data, 1023); ret = krb5_store_uint16(sp, num_tl_data); if (ret) return ret; /* add key count */ CHECK_NUM(num_key_data, 1023); ret = krb5_store_uint16(sp, num_key_data); if (ret) return ret; /* add principal unparsed name length and unparsed name */ princ_len = strlen(princ); princ_len++; /* must count and write the NUL in the on-disk encoding */ ret = krb5_store_uint16(sp, princ_len); if (ret) return ret; sz = krb5_storage_write(sp, princ, princ_len); if (sz == -1) return ENOMEM; /* scan and write TL data */ for (i = 0; i < num_tl_data; i++) { char *reading_what; int tl_type, tl_length; unsigned char *buf; tl_type = getint(&p, "TL data type"); tl_length = getint(&p, "data length"); if (asprintf(&reading_what, "TL data type %d (length %d)", tl_type, tl_length) < 0) return ENOMEM; /* * XXX Leaking reading_what, but only on ENOMEM cases anyways, * so we don't care. */ CHECK_UINT16(tl_type); ret = krb5_store_uint16(sp, tl_type); if (ret) return ret; CHECK_UINT16(tl_length); ret = krb5_store_uint16(sp, tl_length); if (ret) return ret; if (tl_length) { buf = malloc(tl_length); if (!buf) return ENOMEM; if (getdata(&p, buf, tl_length, reading_what) != tl_length) return EINVAL; sz = krb5_storage_write(sp, buf, tl_length); free(buf); if (sz == -1) return ENOMEM; } else { if (strcmp(nexttoken(&p, 0, "'-1' field"), "-1") != 0) return EINVAL; } free(reading_what); } for (i = 0; i < num_key_data; i++) { unsigned char *buf; int key_versions; int kvno; int keytype; int keylen; size_t k; key_versions = getint(&p, "key data 'version'"); CHECK_UINT16(key_versions); ret = krb5_store_int16(sp, key_versions); if (ret) return ret; kvno = getint(&p, "kvno"); CHECK_UINT16(kvno); ret = krb5_store_int16(sp, kvno); if (ret) return ret; for (k = 0; k < key_versions; k++) { keytype = getint(&p, "enctype"); CHECK_UINT16(keytype); ret = krb5_store_int16(sp, keytype); if (ret) return ret; keylen = getint(&p, "encrypted key length"); CHECK_UINT16(keylen); ret = krb5_store_int16(sp, keylen); if (ret) return ret; if (keylen) { buf = malloc(keylen); if (!buf) return ENOMEM; if (getdata(&p, buf, keylen, "key (or salt) data") != keylen) return EINVAL; sz = krb5_storage_write(sp, buf, keylen); free(buf); if (sz == -1) return ENOMEM; } else { if (strcmp(nexttoken(&p, 0, "'-1' zero-length key/salt field"), "-1") != 0) { warnx("Expected '-1' field because key/salt length is 0"); return -1; } } } } /* * The rest is "extra data", but there's never any and we wouldn't * know what to do with it. */ /* nexttoken(&p, 0, "extra data"); */ return 0; } heimdal-7.5.0/lib/hdb/Makefile.am0000644000175000017500000000677113073757062014636 0ustar niknik# $Id$ include $(top_srcdir)/Makefile.am.common AM_CPPFLAGS += -I../asn1 -I$(srcdir)/../asn1 AM_CPPFLAGS += $(INCLUDE_openldap) -DHDB_DB_DIR=\"$(DIR_hdbdir)\" AM_CPPFLAGS += -I$(srcdir)/../krb5 AM_CPPFLAGS += $(INCLUDE_sqlite3) AM_CPPFLAGS += $(INCLUDE_libintl) if HAVE_DBHEADER AM_CPPFLAGS += -I$(DBHEADER) endif BUILT_SOURCES = \ $(gen_files_hdb:.x=.c) \ hdb_err.c \ hdb_err.h gen_files_hdb = \ asn1_Salt.x \ asn1_Key.x \ asn1_Event.x \ asn1_HDBFlags.x \ asn1_GENERATION.x \ asn1_HDB_Ext_PKINIT_acl.x \ asn1_HDB_Ext_PKINIT_cert.x \ asn1_HDB_Ext_PKINIT_hash.x \ asn1_HDB_Ext_Constrained_delegation_acl.x \ asn1_HDB_Ext_Lan_Manager_OWF.x \ asn1_HDB_Ext_Password.x \ asn1_HDB_Ext_Aliases.x \ asn1_HDB_Ext_KeySet.x \ asn1_HDB_extension.x \ asn1_HDB_extensions.x \ asn1_hdb_entry.x \ asn1_hdb_entry_alias.x \ asn1_hdb_keyset.x \ asn1_Keys.x CLEANFILES = $(BUILT_SOURCES) $(gen_files_hdb) \ hdb_asn1{,-priv}.h* hdb_asn1_files hdb_asn1-template.[cx] LDADD = libhdb.la \ ../krb5/libkrb5.la \ ../asn1/libasn1.la \ $(LIB_hcrypto) \ $(LIB_roken) \ $(LIB_openldap) \ $(LIB_libintl) \ $(LIB_ldopen) if OPENLDAP_MODULE ldap_so = hdb_ldap.la hdb_ldap_la_SOURCES = hdb-ldap.c hdb_ldap_la_LDFLAGS = -module -avoid-version hdb_ldap_la_LIBADD = $(LIB_openldap) libhdb.la else ldap = hdb-ldap.c ldap_lib = $(LIB_openldap) endif lib_LTLIBRARIES = libhdb.la $(ldap_so) libhdb_la_LDFLAGS = -version-info 11:0:2 if versionscript libhdb_la_LDFLAGS += $(LDFLAGS_VERSION_SCRIPT)$(srcdir)/version-script.map endif noinst_PROGRAMS = test_dbinfo test_hdbkeys test_mkey test_hdbplugin dist_libhdb_la_SOURCES = \ common.c \ db.c \ db3.c \ ext.c \ $(ldap) \ hdb.c \ hdb-sqlite.c \ hdb-keytab.c \ hdb-mdb.c \ hdb-mitdb.c \ hdb_locl.h \ keys.c \ keytab.c \ dbinfo.c \ mkey.c \ ndbm.c \ print.c nodist_libhdb_la_SOURCES = $(BUILT_SOURCES) libhdb_la_DEPENDENCIES = version-script.map include_HEADERS = hdb.h $(srcdir)/hdb-protos.h nodist_include_HEADERS = hdb_err.h hdb_asn1.h noinst_HEADERS = $(srcdir)/hdb-private.h libhdb_la_LIBADD = \ $(LIB_com_err) \ ../krb5/libkrb5.la \ ../asn1/libasn1.la \ $(LIB_sqlite3) \ $(LIBADD_roken) \ $(ldap_lib) \ $(LIB_dlopen) \ $(DB3LIB) $(DB1LIB) $(LMDBLIB) $(NDBMLIB) HDB_PROTOS = $(srcdir)/hdb-protos.h $(srcdir)/hdb-private.h ALL_OBJECTS = $(libhdb_la_OBJECTS) ALL_OBJECTS += $(test_dbinfo_OBJECTS) ALL_OBJECTS += $(test_hdbkeys_OBJECTS) ALL_OBJECTS += $(test_mkey_OBJECTS) ALL_OBJECTS += $(test_hdbplugin_OBJECTS) $(ALL_OBJECTS): $(HDB_PROTOS) hdb_asn1.h hdb_asn1-priv.h hdb_err.h $(srcdir)/hdb-protos.h: $(dist_libhdb_la_SOURCES) cd $(srcdir); perl ../../cf/make-proto.pl -q -P comment -o hdb-protos.h $(dist_libhdb_la_SOURCES) || rm -f hdb-protos.h $(srcdir)/hdb-private.h: $(dist_libhdb_la_SOURCES) cd $(srcdir); perl ../../cf/make-proto.pl -q -P comment -p hdb-private.h $(dist_libhdb_la_SOURCES) || rm -f hdb-private.h $(gen_files_hdb) hdb_asn1.hx hdb_asn1-priv.hx: hdb_asn1_files hdb_asn1_files: $(ASN1_COMPILE_DEP) $(srcdir)/hdb.asn1 $(ASN1_COMPILE) --sequence=HDB-Ext-KeySet --sequence=Keys $(srcdir)/hdb.asn1 hdb_asn1 test_dbinfo_LIBS = libhdb.la test_hdbkeys_LIBS = ../krb5/libkrb5.la libhdb.la test_mkey_LIBS = $(test_hdbkeys_LIBS) test_hdbplugin_LIBS = $(test_hdbkeys_LIBS) # to help stupid solaris make hdb_err.h: hdb_err.et EXTRA_DIST = \ NTMakefile \ libhdb-version.rc \ libhdb-exports.def \ hdb.asn1 \ hdb_err.et \ hdb.schema \ version-script.map \ data-mkey.mit.des3.le \ data-mkey.mit.des3.be heimdal-7.5.0/lib/hdb/db3.c0000644000175000017500000003245113212137553013400 0ustar niknik/* * Copyright (c) 1997 - 2006 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "hdb_locl.h" #include #if HAVE_DB3 #ifdef HAVE_DBHEADER #include #elif HAVE_DB6_DB_H #include #elif HAVE_DB5_DB_H #include #elif HAVE_DB4_DB_H #include #elif HAVE_DB3_DB_H #include #else #include #endif typedef struct { HDB hdb; /* generic members */ int lock_fd; /* DB3-specific */ } DB3_HDB; static krb5_error_code DB_close(krb5_context context, HDB *db) { DB3_HDB *db3 = (DB3_HDB *)db; DB *d = (DB*)db->hdb_db; DBC *dbcp = (DBC*)db->hdb_dbc; heim_assert(d != 0, "Closing already closed HDB"); if (dbcp != NULL) dbcp->c_close(dbcp); if (d != NULL) d->close(d, 0); if (db3->lock_fd >= 0) close(db3->lock_fd); db3->lock_fd = -1; db->hdb_dbc = 0; db->hdb_db = 0; return 0; } static krb5_error_code DB_destroy(krb5_context context, HDB *db) { krb5_error_code ret; ret = hdb_clear_master_key (context, db); free(db->hdb_name); free(db); return ret; } static krb5_error_code DB_lock(krb5_context context, HDB *db, int operation) { return 0; } static krb5_error_code DB_unlock(krb5_context context, HDB *db) { return 0; } static krb5_error_code DB_seq(krb5_context context, HDB *db, unsigned flags, hdb_entry_ex *entry, int flag) { DBT key, value; DBC *dbcp = db->hdb_dbc; krb5_data key_data, data; int code; memset(&key, 0, sizeof(DBT)); memset(&value, 0, sizeof(DBT)); code = (*dbcp->c_get)(dbcp, &key, &value, flag); if (code == DB_NOTFOUND) return HDB_ERR_NOENTRY; if (code) return code; key_data.data = key.data; key_data.length = key.size; data.data = value.data; data.length = value.size; memset(entry, 0, sizeof(*entry)); if (hdb_value2entry(context, &data, &entry->entry)) return DB_seq(context, db, flags, entry, DB_NEXT); if (db->hdb_master_key_set && (flags & HDB_F_DECRYPT)) { code = hdb_unseal_keys (context, db, &entry->entry); if (code) hdb_free_entry (context, entry); } if (entry->entry.principal == NULL) { entry->entry.principal = malloc(sizeof(*entry->entry.principal)); if (entry->entry.principal == NULL) { hdb_free_entry (context, entry); krb5_set_error_message(context, ENOMEM, "malloc: out of memory"); return ENOMEM; } else { hdb_key2principal(context, &key_data, entry->entry.principal); } } return 0; } static krb5_error_code DB_firstkey(krb5_context context, HDB *db, unsigned flags, hdb_entry_ex *entry) { return DB_seq(context, db, flags, entry, DB_FIRST); } static krb5_error_code DB_nextkey(krb5_context context, HDB *db, unsigned flags, hdb_entry_ex *entry) { return DB_seq(context, db, flags, entry, DB_NEXT); } static krb5_error_code DB_rename(krb5_context context, HDB *db, const char *new_name) { int ret; char *old, *new; if (strncmp(new_name, "db:", sizeof("db:") - 1) == 0) new_name += sizeof("db:") - 1; else if (strncmp(new_name, "db3:", sizeof("db3:") - 1) == 0) new_name += sizeof("db3:") - 1; ret = asprintf(&old, "%s.db", db->hdb_name); if (ret == -1) return ENOMEM; ret = asprintf(&new, "%s.db", new_name); if (ret == -1) { free(old); return ENOMEM; } ret = rename(old, new); free(old); if(ret) { free(new); return errno; } free(db->hdb_name); new[strlen(new) - 3] = '\0'; db->hdb_name = new; return 0; } static krb5_error_code DB__get(krb5_context context, HDB *db, krb5_data key, krb5_data *reply) { DB *d = (DB*)db->hdb_db; DBT k, v; int code; memset(&k, 0, sizeof(DBT)); memset(&v, 0, sizeof(DBT)); k.data = key.data; k.size = key.length; k.flags = 0; code = (*d->get)(d, NULL, &k, &v, 0); if(code == DB_NOTFOUND) return HDB_ERR_NOENTRY; if(code) return code; krb5_data_copy(reply, v.data, v.size); return 0; } static krb5_error_code DB__put(krb5_context context, HDB *db, int replace, krb5_data key, krb5_data value) { DB *d = (DB*)db->hdb_db; DBT k, v; int code; memset(&k, 0, sizeof(DBT)); memset(&v, 0, sizeof(DBT)); k.data = key.data; k.size = key.length; k.flags = 0; v.data = value.data; v.size = value.length; v.flags = 0; code = (*d->put)(d, NULL, &k, &v, replace ? 0 : DB_NOOVERWRITE); if(code == DB_KEYEXIST) return HDB_ERR_EXISTS; if (code) { /* * Berkeley DB 3 and up have a terrible error reporting * interface... * * DB->err() doesn't output a string. * DB->set_errcall()'s callback function doesn't have a void * * argument that can be used to place the error somewhere. * * The only thing we could do is fopen()/fdopen() a file, set it * with DB->set_errfile(), then call DB->err(), then read the * message from the file, unset it with DB->set_errfile(), close * it and delete it. That's a lot of work... so we don't do it. */ if (code == EACCES || code == ENOSPC || code == EINVAL) { krb5_set_error_message(context, code, "Database %s put error: %s", db->hdb_name, strerror(code)); } else { code = HDB_ERR_UK_SERROR; krb5_set_error_message(context, code, "Database %s put error: unknown (%d)", db->hdb_name, code); } return code; } code = (*d->sync)(d, 0); if (code) { if (code == EACCES || code == ENOSPC || code == EINVAL) { krb5_set_error_message(context, code, "Database %s put sync error: %s", db->hdb_name, strerror(code)); } else { code = HDB_ERR_UK_SERROR; krb5_set_error_message(context, code, "Database %s put sync error: unknown (%d)", db->hdb_name, code); } return code; } return 0; } static krb5_error_code DB__del(krb5_context context, HDB *db, krb5_data key) { DB *d = (DB*)db->hdb_db; DBT k; krb5_error_code code; memset(&k, 0, sizeof(DBT)); k.data = key.data; k.size = key.length; k.flags = 0; code = (*d->del)(d, NULL, &k, 0); if(code == DB_NOTFOUND) return HDB_ERR_NOENTRY; if (code) { if (code == EACCES || code == ENOSPC || code == EINVAL) { krb5_set_error_message(context, code, "Database %s del error: %s", db->hdb_name, strerror(code)); } else { code = HDB_ERR_UK_SERROR; krb5_set_error_message(context, code, "Database %s del error: unknown (%d)", db->hdb_name, code); } return code; } code = (*d->sync)(d, 0); if (code) { if (code == EACCES || code == ENOSPC || code == EINVAL) { krb5_set_error_message(context, code, "Database %s del sync error: %s", db->hdb_name, strerror(code)); } else { code = HDB_ERR_UK_SERROR; krb5_set_error_message(context, code, "Database %s del sync error: unknown (%d)", db->hdb_name, code); } return code; } return 0; } #define RD_CACHE_SZ 0x8000 /* Minimal read cache size */ #define WR_CACHE_SZ 0x8000 /* Minimal write cache size */ static int _open_db(DB *d, char *fn, int myflags, int flags, mode_t mode, int *fd) { int ret; int cache_size = (myflags & DB_RDONLY) ? RD_CACHE_SZ : WR_CACHE_SZ; *fd = open(fn, flags, mode); if (*fd == -1) return errno; /* * Without DB_FCNTL_LOCKING, the DB library complains when initializing * a database in an empty file. Since the database is our lock file, * we create it before Berkeley DB does, so a new DB always starts empty. */ myflags |= DB_FCNTL_LOCKING; ret = flock(*fd, (myflags&DB_RDONLY) ? LOCK_SH : LOCK_EX); if (ret == -1) { ret = errno; close(*fd); *fd = -1; return ret; } d->set_cachesize(d, 0, cache_size, 0); #if (DB_VERSION_MAJOR > 4) || ((DB_VERSION_MAJOR == 4) && (DB_VERSION_MINOR >= 1)) ret = (*d->open)(d, NULL, fn, NULL, DB_BTREE, myflags, mode); #else ret = (*d->open)(d, fn, NULL, DB_BTREE, myflags, mode); #endif if (ret != 0) { close(*fd); *fd = -1; } return ret; } static krb5_error_code DB_open(krb5_context context, HDB *db, int flags, mode_t mode) { DB3_HDB *db3 = (DB3_HDB *)db; DBC *dbc = NULL; char *fn; krb5_error_code ret; DB *d; int myflags = 0; int aret; heim_assert(db->hdb_db == 0, "Opening already open HDB"); if (flags & O_CREAT) myflags |= DB_CREATE; if (flags & O_EXCL) myflags |= DB_EXCL; if((flags & O_ACCMODE) == O_RDONLY) myflags |= DB_RDONLY; if (flags & O_TRUNC) myflags |= DB_TRUNCATE; aret = asprintf(&fn, "%s.db", db->hdb_name); if (aret == -1) { krb5_set_error_message(context, ENOMEM, "malloc: out of memory"); return ENOMEM; } if (db_create(&d, NULL, 0) != 0) { free(fn); krb5_set_error_message(context, ENOMEM, "malloc: out of memory"); return ENOMEM; } db->hdb_db = d; /* From here on out always DB_close() before returning on error */ ret = _open_db(d, fn, myflags, flags, mode, &db3->lock_fd); free(fn); if (ret == ENOENT) { /* try to open without .db extension */ ret = _open_db(d, db->hdb_name, myflags, flags, mode, &db3->lock_fd); } if (ret) { DB_close(context, db); krb5_set_error_message(context, ret, "opening %s: %s", db->hdb_name, strerror(ret)); return ret; } #ifndef DB_CURSOR_BULK # define DB_CURSOR_BULK 0 /* Missing with DB < 4.8 */ #endif ret = (*d->cursor)(d, NULL, &dbc, DB_CURSOR_BULK); if (ret) { DB_close(context, db); krb5_set_error_message(context, ret, "d->cursor: %s", strerror(ret)); return ret; } db->hdb_dbc = dbc; if((flags & O_ACCMODE) == O_RDONLY) ret = hdb_check_db_format(context, db); else ret = hdb_init_db(context, db); if(ret == HDB_ERR_NOENTRY) return 0; if (ret) { DB_close(context, db); krb5_set_error_message(context, ret, "hdb_open: failed %s database %s", (flags & O_ACCMODE) == O_RDONLY ? "checking format of" : "initialize", db->hdb_name); } return ret; } krb5_error_code hdb_db3_create(krb5_context context, HDB **db, const char *filename) { DB3_HDB **db3 = (DB3_HDB **)db; *db3 = calloc(1, sizeof(**db3)); /* Allocate space for the larger db3 */ if (*db == NULL) { krb5_set_error_message(context, ENOMEM, "malloc: out of memory"); return ENOMEM; } (*db)->hdb_db = NULL; (*db)->hdb_name = strdup(filename); if ((*db)->hdb_name == NULL) { free(*db); *db = NULL; krb5_set_error_message(context, ENOMEM, "malloc: out of memory"); return ENOMEM; } (*db)->hdb_master_key_set = 0; (*db)->hdb_openp = 0; (*db)->hdb_capability_flags = HDB_CAP_F_HANDLE_ENTERPRISE_PRINCIPAL; (*db)->hdb_open = DB_open; (*db)->hdb_close = DB_close; (*db)->hdb_fetch_kvno = _hdb_fetch_kvno; (*db)->hdb_store = _hdb_store; (*db)->hdb_remove = _hdb_remove; (*db)->hdb_firstkey = DB_firstkey; (*db)->hdb_nextkey= DB_nextkey; (*db)->hdb_lock = DB_lock; (*db)->hdb_unlock = DB_unlock; (*db)->hdb_rename = DB_rename; (*db)->hdb__get = DB__get; (*db)->hdb__put = DB__put; (*db)->hdb__del = DB__del; (*db)->hdb_destroy = DB_destroy; (*db3)->lock_fd = -1; return 0; } #endif /* HAVE_DB3 */ heimdal-7.5.0/lib/hdb/test_hdbplugin.c0000644000175000017500000000545213026237312015741 0ustar niknik/* * Copyright (c) 2013 Jeffrey Clark * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "hdb_locl.h" struct hdb_called { int create; int init; int fini; }; struct hdb_called testresult; static krb5_error_code hdb_test_create(krb5_context context, struct HDB **db, const char *arg) { testresult.create = 1; return 0; } static krb5_error_code hdb_test_init(krb5_context context, void **ctx) { *ctx = NULL; testresult.init = 1; return 0; } static void hdb_test_fini(void *ctx) { testresult.fini = 1; } struct hdb_method hdb_test = { #ifdef WIN32 /* Not c99 */ HDB_INTERFACE_VERSION, hdb_test_init, hdb_test_fini, "test", hdb_test_create #else .version = HDB_INTERFACE_VERSION, .init = hdb_test_init, .fini = hdb_test_fini, .prefix = "test", .create = hdb_test_create #endif }; int main(int argc, char **argv) { krb5_error_code ret; krb5_context context; HDB *db; setprogname(argv[0]); ret = krb5_init_context(&context); if (ret) errx(1, "krb5_init_contex"); ret = krb5_plugin_register(context, PLUGIN_TYPE_DATA, "hdb_test_interface", &hdb_test); if(ret) { krb5_err(context, 1, ret, "krb5_plugin_register"); } ret = hdb_create(context, &db, "test:test&1234"); if(ret) { krb5_err(context, 1, ret, "hdb_create"); } krb5_free_context(context); return 0; } heimdal-7.5.0/lib/hdb/ext.c0000644000175000017500000003267613026237312013536 0ustar niknik/* * Copyright (c) 2004 - 2005 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "hdb_locl.h" #include krb5_error_code hdb_entry_check_mandatory(krb5_context context, const hdb_entry *ent) { size_t i; if (ent->extensions == NULL) return 0; /* * check for unknown extensions and if they where tagged mandatory */ for (i = 0; i < ent->extensions->len; i++) { if (ent->extensions->val[i].data.element != choice_HDB_extension_data_asn1_ellipsis) continue; if (ent->extensions->val[i].mandatory) { krb5_set_error_message(context, HDB_ERR_MANDATORY_OPTION, "Principal have unknown " "mandatory extension"); return HDB_ERR_MANDATORY_OPTION; } } return 0; } HDB_extension * hdb_find_extension(const hdb_entry *entry, int type) { size_t i; if (entry->extensions == NULL) return NULL; for (i = 0; i < entry->extensions->len; i++) if (entry->extensions->val[i].data.element == (unsigned)type) return &entry->extensions->val[i]; return NULL; } /* * Replace the extension `ext' in `entry'. Make a copy of the * extension, so the caller must still free `ext' on both success and * failure. Returns 0 or error code. */ krb5_error_code hdb_replace_extension(krb5_context context, hdb_entry *entry, const HDB_extension *ext) { HDB_extension *ext2; HDB_extension *es; int ret; ext2 = NULL; if (entry->extensions == NULL) { entry->extensions = calloc(1, sizeof(*entry->extensions)); if (entry->extensions == NULL) { krb5_set_error_message(context, ENOMEM, "malloc: out of memory"); return ENOMEM; } } else if (ext->data.element != choice_HDB_extension_data_asn1_ellipsis) { ext2 = hdb_find_extension(entry, ext->data.element); } else { /* * This is an unknown extension, and we are asked to replace a * possible entry in `entry' that is of the same type. This * might seem impossible, but ASN.1 CHOICE comes to our * rescue. The first tag in each branch in the CHOICE is * unique, so just find the element in the list that have the * same tag was we are putting into the list. */ Der_class replace_class, list_class; Der_type replace_type, list_type; unsigned int replace_tag, list_tag; size_t size; size_t i; ret = der_get_tag(ext->data.u.asn1_ellipsis.data, ext->data.u.asn1_ellipsis.length, &replace_class, &replace_type, &replace_tag, &size); if (ret) { krb5_set_error_message(context, ret, "hdb: failed to decode " "replacement hdb extension"); return ret; } for (i = 0; i < entry->extensions->len; i++) { HDB_extension *ext3 = &entry->extensions->val[i]; if (ext3->data.element != choice_HDB_extension_data_asn1_ellipsis) continue; ret = der_get_tag(ext3->data.u.asn1_ellipsis.data, ext3->data.u.asn1_ellipsis.length, &list_class, &list_type, &list_tag, &size); if (ret) { krb5_set_error_message(context, ret, "hdb: failed to decode " "present hdb extension"); return ret; } if (MAKE_TAG(replace_class,replace_type,replace_type) == MAKE_TAG(list_class,list_type,list_type)) { ext2 = ext3; break; } } } if (ext2) { free_HDB_extension(ext2); ret = copy_HDB_extension(ext, ext2); if (ret) krb5_set_error_message(context, ret, "hdb: failed to copy replacement " "hdb extension"); return ret; } es = realloc(entry->extensions->val, (entry->extensions->len+1)*sizeof(entry->extensions->val[0])); if (es == NULL) { krb5_set_error_message(context, ENOMEM, "malloc: out of memory"); return ENOMEM; } entry->extensions->val = es; ret = copy_HDB_extension(ext, &entry->extensions->val[entry->extensions->len]); if (ret == 0) entry->extensions->len++; else krb5_set_error_message(context, ret, "hdb: failed to copy new extension"); return ret; } krb5_error_code hdb_clear_extension(krb5_context context, hdb_entry *entry, int type) { size_t i; if (entry->extensions == NULL) return 0; for (i = 0; i < entry->extensions->len; i++) { if (entry->extensions->val[i].data.element == (unsigned)type) { free_HDB_extension(&entry->extensions->val[i]); memmove(&entry->extensions->val[i], &entry->extensions->val[i + 1], sizeof(entry->extensions->val[i]) * (entry->extensions->len - i - 1)); entry->extensions->len--; } } if (entry->extensions->len == 0) { free(entry->extensions->val); free(entry->extensions); entry->extensions = NULL; } return 0; } krb5_error_code hdb_entry_get_pkinit_acl(const hdb_entry *entry, const HDB_Ext_PKINIT_acl **a) { const HDB_extension *ext; ext = hdb_find_extension(entry, choice_HDB_extension_data_pkinit_acl); if (ext) *a = &ext->data.u.pkinit_acl; else *a = NULL; return 0; } krb5_error_code hdb_entry_get_pkinit_hash(const hdb_entry *entry, const HDB_Ext_PKINIT_hash **a) { const HDB_extension *ext; ext = hdb_find_extension(entry, choice_HDB_extension_data_pkinit_cert_hash); if (ext) *a = &ext->data.u.pkinit_cert_hash; else *a = NULL; return 0; } krb5_error_code hdb_entry_get_pkinit_cert(const hdb_entry *entry, const HDB_Ext_PKINIT_cert **a) { const HDB_extension *ext; ext = hdb_find_extension(entry, choice_HDB_extension_data_pkinit_cert); if (ext) *a = &ext->data.u.pkinit_cert; else *a = NULL; return 0; } krb5_error_code hdb_entry_get_pw_change_time(const hdb_entry *entry, time_t *t) { const HDB_extension *ext; ext = hdb_find_extension(entry, choice_HDB_extension_data_last_pw_change); if (ext) *t = ext->data.u.last_pw_change; else *t = 0; return 0; } krb5_error_code hdb_entry_set_pw_change_time(krb5_context context, hdb_entry *entry, time_t t) { HDB_extension ext; ext.mandatory = FALSE; ext.data.element = choice_HDB_extension_data_last_pw_change; if (t == 0) t = time(NULL); ext.data.u.last_pw_change = t; return hdb_replace_extension(context, entry, &ext); } int hdb_entry_get_password(krb5_context context, HDB *db, const hdb_entry *entry, char **p) { HDB_extension *ext; char *str; int ret; ext = hdb_find_extension(entry, choice_HDB_extension_data_password); if (ext) { heim_utf8_string xstr; heim_octet_string pw; if (db->hdb_master_key_set && ext->data.u.password.mkvno) { hdb_master_key key; key = _hdb_find_master_key(ext->data.u.password.mkvno, db->hdb_master_key); if (key == NULL) { krb5_set_error_message(context, HDB_ERR_NO_MKEY, "master key %d missing", *ext->data.u.password.mkvno); return HDB_ERR_NO_MKEY; } ret = _hdb_mkey_decrypt(context, key, HDB_KU_MKEY, ext->data.u.password.password.data, ext->data.u.password.password.length, &pw); } else { ret = der_copy_octet_string(&ext->data.u.password.password, &pw); } if (ret) { krb5_clear_error_message(context); return ret; } xstr = pw.data; if (xstr[pw.length - 1] != '\0') { krb5_set_error_message(context, EINVAL, "malformed password"); return EINVAL; } *p = strdup(xstr); der_free_octet_string(&pw); if (*p == NULL) { krb5_set_error_message(context, ENOMEM, "malloc: out of memory"); return ENOMEM; } return 0; } ret = krb5_unparse_name(context, entry->principal, &str); if (ret == 0) { krb5_set_error_message(context, ENOENT, "no password attribute for %s", str); free(str); } else krb5_clear_error_message(context); return ENOENT; } int hdb_entry_set_password(krb5_context context, HDB *db, hdb_entry *entry, const char *p) { HDB_extension ext; hdb_master_key key; int ret; ext.mandatory = FALSE; ext.data.element = choice_HDB_extension_data_password; if (db->hdb_master_key_set) { key = _hdb_find_master_key(NULL, db->hdb_master_key); if (key == NULL) { krb5_set_error_message(context, HDB_ERR_NO_MKEY, "hdb_entry_set_password: " "failed to find masterkey"); return HDB_ERR_NO_MKEY; } ret = _hdb_mkey_encrypt(context, key, HDB_KU_MKEY, p, strlen(p) + 1, &ext.data.u.password.password); if (ret) return ret; ext.data.u.password.mkvno = malloc(sizeof(*ext.data.u.password.mkvno)); if (ext.data.u.password.mkvno == NULL) { free_HDB_extension(&ext); krb5_set_error_message(context, ENOMEM, "malloc: out of memory"); return ENOMEM; } *ext.data.u.password.mkvno = _hdb_mkey_version(key); } else { ext.data.u.password.mkvno = NULL; ret = krb5_data_copy(&ext.data.u.password.password, p, strlen(p) + 1); if (ret) { krb5_set_error_message(context, ret, "malloc: out of memory"); free_HDB_extension(&ext); return ret; } } ret = hdb_replace_extension(context, entry, &ext); free_HDB_extension(&ext); return ret; } int hdb_entry_clear_password(krb5_context context, hdb_entry *entry) { return hdb_clear_extension(context, entry, choice_HDB_extension_data_password); } krb5_error_code hdb_entry_get_ConstrainedDelegACL(const hdb_entry *entry, const HDB_Ext_Constrained_delegation_acl **a) { const HDB_extension *ext; ext = hdb_find_extension(entry, choice_HDB_extension_data_allowed_to_delegate_to); if (ext) *a = &ext->data.u.allowed_to_delegate_to; else *a = NULL; return 0; } krb5_error_code hdb_entry_get_aliases(const hdb_entry *entry, const HDB_Ext_Aliases **a) { const HDB_extension *ext; ext = hdb_find_extension(entry, choice_HDB_extension_data_aliases); if (ext) *a = &ext->data.u.aliases; else *a = NULL; return 0; } unsigned int hdb_entry_get_kvno_diff_clnt(const hdb_entry *entry) { const HDB_extension *ext; ext = hdb_find_extension(entry, choice_HDB_extension_data_hist_kvno_diff_clnt); if (ext) return ext->data.u.hist_kvno_diff_clnt; return 1; } krb5_error_code hdb_entry_set_kvno_diff_clnt(krb5_context context, hdb_entry *entry, unsigned int diff) { HDB_extension ext; if (diff > 16384) return EINVAL; ext.mandatory = FALSE; ext.data.element = choice_HDB_extension_data_hist_kvno_diff_clnt; ext.data.u.hist_kvno_diff_clnt = diff; return hdb_replace_extension(context, entry, &ext); } krb5_error_code hdb_entry_clear_kvno_diff_clnt(krb5_context context, hdb_entry *entry) { return hdb_clear_extension(context, entry, choice_HDB_extension_data_hist_kvno_diff_clnt); } unsigned int hdb_entry_get_kvno_diff_svc(const hdb_entry *entry) { const HDB_extension *ext; ext = hdb_find_extension(entry, choice_HDB_extension_data_hist_kvno_diff_svc); if (ext) return ext->data.u.hist_kvno_diff_svc; return 1024; /* max_life effectively provides a better default */ } krb5_error_code hdb_entry_set_kvno_diff_svc(krb5_context context, hdb_entry *entry, unsigned int diff) { HDB_extension ext; if (diff > 16384) return EINVAL; ext.mandatory = FALSE; ext.data.element = choice_HDB_extension_data_hist_kvno_diff_svc; ext.data.u.hist_kvno_diff_svc = diff; return hdb_replace_extension(context, entry, &ext); } krb5_error_code hdb_entry_clear_kvno_diff_svc(krb5_context context, hdb_entry *entry) { return hdb_clear_extension(context, entry, choice_HDB_extension_data_hist_kvno_diff_svc); } krb5_error_code hdb_set_last_modified_by(krb5_context context, hdb_entry *entry, krb5_principal modby, time_t modtime) { krb5_error_code ret; Event *old_ev; Event *ev; old_ev = entry->modified_by; ev = calloc(1, sizeof (*ev)); if (!ev) return ENOMEM; if (modby) ret = krb5_copy_principal(context, modby, &ev->principal); else ret = krb5_parse_name(context, "root/admin", &ev->principal); if (ret) { free(ev); return ret; } ev->time = modtime; if (!ev->time) time(&ev->time); entry->modified_by = ev; if (old_ev) free_Event(old_ev); return 0; } heimdal-7.5.0/lib/hdb/data-mkey.mit.des3.be0000644000175000017500000000005612136107747016377 0ustar niknik heimdal-7.5.0/lib/hdb/Makefile.in0000644000175000017500000013101513212444521014621 0ustar niknik# Makefile.in generated by automake 1.15.1 from Makefile.am. # @configure_input@ # Copyright (C) 1994-2017 Free Software Foundation, Inc. # This Makefile.in is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, # with or without modifications, as long as this notice is preserved. # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY, to the extent permitted by law; without # even the implied warranty of MERCHANTABILITY or FITNESS FOR A # PARTICULAR PURPOSE. @SET_MAKE@ # $Id$ # $Id$ # $Id$ VPATH = @srcdir@ am__is_gnu_make = { \ if test -z '$(MAKELEVEL)'; then \ false; \ elif test -n '$(MAKE_HOST)'; then \ true; \ elif test -n '$(MAKE_VERSION)' && test -n '$(CURDIR)'; then \ true; \ else \ false; \ fi; \ } am__make_running_with_option = \ case $${target_option-} in \ ?) ;; \ *) echo "am__make_running_with_option: internal error: invalid" \ "target option '$${target_option-}' specified" >&2; \ exit 1;; \ esac; \ has_opt=no; \ sane_makeflags=$$MAKEFLAGS; \ if $(am__is_gnu_make); then \ sane_makeflags=$$MFLAGS; \ else \ case $$MAKEFLAGS in \ *\\[\ \ ]*) \ bs=\\; \ sane_makeflags=`printf '%s\n' "$$MAKEFLAGS" \ | sed "s/$$bs$$bs[$$bs $$bs ]*//g"`;; \ esac; \ fi; \ skip_next=no; \ strip_trailopt () \ { \ flg=`printf '%s\n' "$$flg" | sed "s/$$1.*$$//"`; \ }; \ for flg in $$sane_makeflags; do \ test $$skip_next = yes && { skip_next=no; continue; }; \ case $$flg in \ *=*|--*) continue;; \ -*I) strip_trailopt 'I'; skip_next=yes;; \ -*I?*) strip_trailopt 'I';; \ -*O) strip_trailopt 'O'; skip_next=yes;; \ -*O?*) strip_trailopt 'O';; \ -*l) strip_trailopt 'l'; skip_next=yes;; \ -*l?*) strip_trailopt 'l';; \ -[dEDm]) skip_next=yes;; \ -[JT]) skip_next=yes;; \ esac; \ case $$flg in \ *$$target_option*) has_opt=yes; break;; \ esac; \ done; \ test $$has_opt = yes am__make_dryrun = (target_option=n; $(am__make_running_with_option)) am__make_keepgoing = (target_option=k; $(am__make_running_with_option)) pkgdatadir = $(datadir)/@PACKAGE@ pkgincludedir = $(includedir)/@PACKAGE@ pkglibdir = $(libdir)/@PACKAGE@ pkglibexecdir = $(libexecdir)/@PACKAGE@ am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd install_sh_DATA = $(install_sh) -c -m 644 install_sh_PROGRAM = $(install_sh) -c install_sh_SCRIPT = $(install_sh) -c INSTALL_HEADER = $(INSTALL_DATA) transform = $(program_transform_name) NORMAL_INSTALL = : PRE_INSTALL = : POST_INSTALL = : NORMAL_UNINSTALL = : PRE_UNINSTALL = : POST_UNINSTALL = : build_triplet = @build@ host_triplet = @host@ @HAVE_DBHEADER_TRUE@am__append_1 = -I$(DBHEADER) @versionscript_TRUE@am__append_2 = $(LDFLAGS_VERSION_SCRIPT)$(srcdir)/version-script.map noinst_PROGRAMS = test_dbinfo$(EXEEXT) test_hdbkeys$(EXEEXT) \ test_mkey$(EXEEXT) test_hdbplugin$(EXEEXT) subdir = lib/hdb ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 am__aclocal_m4_deps = $(top_srcdir)/cf/aix.m4 \ $(top_srcdir)/cf/auth-modules.m4 \ $(top_srcdir)/cf/broken-getaddrinfo.m4 \ $(top_srcdir)/cf/broken-glob.m4 \ $(top_srcdir)/cf/broken-realloc.m4 \ $(top_srcdir)/cf/broken-snprintf.m4 $(top_srcdir)/cf/broken.m4 \ $(top_srcdir)/cf/broken2.m4 $(top_srcdir)/cf/c-attribute.m4 \ $(top_srcdir)/cf/capabilities.m4 \ $(top_srcdir)/cf/check-compile-et.m4 \ $(top_srcdir)/cf/check-getpwnam_r-posix.m4 \ $(top_srcdir)/cf/check-man.m4 \ $(top_srcdir)/cf/check-netinet-ip-and-tcp.m4 \ $(top_srcdir)/cf/check-type-extra.m4 \ $(top_srcdir)/cf/check-var.m4 $(top_srcdir)/cf/crypto.m4 \ $(top_srcdir)/cf/db.m4 $(top_srcdir)/cf/destdirs.m4 \ $(top_srcdir)/cf/dispatch.m4 $(top_srcdir)/cf/dlopen.m4 \ $(top_srcdir)/cf/find-func-no-libs.m4 \ $(top_srcdir)/cf/find-func-no-libs2.m4 \ $(top_srcdir)/cf/find-func.m4 \ $(top_srcdir)/cf/find-if-not-broken.m4 \ $(top_srcdir)/cf/framework-security.m4 \ $(top_srcdir)/cf/have-struct-field.m4 \ $(top_srcdir)/cf/have-type.m4 $(top_srcdir)/cf/irix.m4 \ $(top_srcdir)/cf/krb-bigendian.m4 \ $(top_srcdir)/cf/krb-func-getlogin.m4 \ $(top_srcdir)/cf/krb-ipv6.m4 $(top_srcdir)/cf/krb-prog-ln-s.m4 \ $(top_srcdir)/cf/krb-prog-perl.m4 \ $(top_srcdir)/cf/krb-readline.m4 \ $(top_srcdir)/cf/krb-struct-spwd.m4 \ $(top_srcdir)/cf/krb-struct-winsize.m4 \ $(top_srcdir)/cf/largefile.m4 $(top_srcdir)/cf/libtool.m4 \ $(top_srcdir)/cf/ltoptions.m4 $(top_srcdir)/cf/ltsugar.m4 \ $(top_srcdir)/cf/ltversion.m4 $(top_srcdir)/cf/lt~obsolete.m4 \ $(top_srcdir)/cf/mips-abi.m4 $(top_srcdir)/cf/misc.m4 \ $(top_srcdir)/cf/need-proto.m4 $(top_srcdir)/cf/osfc2.m4 \ $(top_srcdir)/cf/otp.m4 $(top_srcdir)/cf/pkg.m4 \ $(top_srcdir)/cf/proto-compat.m4 $(top_srcdir)/cf/pthreads.m4 \ $(top_srcdir)/cf/resolv.m4 $(top_srcdir)/cf/retsigtype.m4 \ $(top_srcdir)/cf/roken-frag.m4 \ $(top_srcdir)/cf/socket-wrapper.m4 $(top_srcdir)/cf/sunos.m4 \ $(top_srcdir)/cf/telnet.m4 $(top_srcdir)/cf/test-package.m4 \ $(top_srcdir)/cf/version-script.m4 $(top_srcdir)/cf/wflags.m4 \ $(top_srcdir)/cf/win32.m4 $(top_srcdir)/cf/with-all.m4 \ $(top_srcdir)/acinclude.m4 $(top_srcdir)/configure.ac am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \ $(ACLOCAL_M4) DIST_COMMON = $(srcdir)/Makefile.am $(include_HEADERS) \ $(noinst_HEADERS) $(am__DIST_COMMON) mkinstalldirs = $(install_sh) -d CONFIG_HEADER = $(top_builddir)/include/config.h CONFIG_CLEAN_FILES = CONFIG_CLEAN_VPATH_FILES = am__vpath_adj_setup = srcdirstrip=`echo "$(srcdir)" | sed 's|.|.|g'`; am__vpath_adj = case $$p in \ $(srcdir)/*) f=`echo "$$p" | sed "s|^$$srcdirstrip/||"`;; \ *) f=$$p;; \ esac; am__strip_dir = f=`echo $$p | sed -e 's|^.*/||'`; am__install_max = 40 am__nobase_strip_setup = \ srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*|]/\\\\&/g'` am__nobase_strip = \ for p in $$list; do echo "$$p"; done | sed -e "s|$$srcdirstrip/||" am__nobase_list = $(am__nobase_strip_setup); \ for p in $$list; do echo "$$p $$p"; done | \ sed "s| $$srcdirstrip/| |;"' / .*\//!s/ .*/ ./; s,\( .*\)/[^/]*$$,\1,' | \ $(AWK) 'BEGIN { files["."] = "" } { files[$$2] = files[$$2] " " $$1; \ if (++n[$$2] == $(am__install_max)) \ { print $$2, files[$$2]; n[$$2] = 0; files[$$2] = "" } } \ END { for (dir in files) print dir, files[dir] }' am__base_list = \ sed '$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;s/\n/ /g' | \ sed '$$!N;$$!N;$$!N;$$!N;s/\n/ /g' am__uninstall_files_from_dir = { \ test -z "$$files" \ || { test ! -d "$$dir" && test ! -f "$$dir" && test ! -r "$$dir"; } \ || { echo " ( cd '$$dir' && rm -f" $$files ")"; \ $(am__cd) "$$dir" && rm -f $$files; }; \ } am__installdirs = "$(DESTDIR)$(libdir)" "$(DESTDIR)$(includedir)" \ "$(DESTDIR)$(includedir)" LTLIBRARIES = $(lib_LTLIBRARIES) am__DEPENDENCIES_1 = @OPENLDAP_MODULE_TRUE@hdb_ldap_la_DEPENDENCIES = \ @OPENLDAP_MODULE_TRUE@ $(am__DEPENDENCIES_1) libhdb.la am__hdb_ldap_la_SOURCES_DIST = hdb-ldap.c @OPENLDAP_MODULE_TRUE@am_hdb_ldap_la_OBJECTS = hdb-ldap.lo hdb_ldap_la_OBJECTS = $(am_hdb_ldap_la_OBJECTS) AM_V_lt = $(am__v_lt_@AM_V@) am__v_lt_ = $(am__v_lt_@AM_DEFAULT_V@) am__v_lt_0 = --silent am__v_lt_1 = hdb_ldap_la_LINK = $(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) \ $(LIBTOOLFLAGS) --mode=link $(CCLD) $(AM_CFLAGS) $(CFLAGS) \ $(hdb_ldap_la_LDFLAGS) $(LDFLAGS) -o $@ @OPENLDAP_MODULE_TRUE@am_hdb_ldap_la_rpath = -rpath $(libdir) @OPENLDAP_MODULE_FALSE@am__DEPENDENCIES_2 = $(am__DEPENDENCIES_1) am__dist_libhdb_la_SOURCES_DIST = common.c db.c db3.c ext.c hdb-ldap.c \ hdb.c hdb-sqlite.c hdb-keytab.c hdb-mdb.c hdb-mitdb.c \ hdb_locl.h keys.c keytab.c dbinfo.c mkey.c ndbm.c print.c @OPENLDAP_MODULE_FALSE@am__objects_1 = hdb-ldap.lo dist_libhdb_la_OBJECTS = common.lo db.lo db3.lo ext.lo \ $(am__objects_1) hdb.lo hdb-sqlite.lo hdb-keytab.lo hdb-mdb.lo \ hdb-mitdb.lo keys.lo keytab.lo dbinfo.lo mkey.lo ndbm.lo \ print.lo am__objects_2 = asn1_Salt.lo asn1_Key.lo asn1_Event.lo \ asn1_HDBFlags.lo asn1_GENERATION.lo asn1_HDB_Ext_PKINIT_acl.lo \ asn1_HDB_Ext_PKINIT_cert.lo asn1_HDB_Ext_PKINIT_hash.lo \ asn1_HDB_Ext_Constrained_delegation_acl.lo \ asn1_HDB_Ext_Lan_Manager_OWF.lo asn1_HDB_Ext_Password.lo \ asn1_HDB_Ext_Aliases.lo asn1_HDB_Ext_KeySet.lo \ asn1_HDB_extension.lo asn1_HDB_extensions.lo asn1_hdb_entry.lo \ asn1_hdb_entry_alias.lo asn1_hdb_keyset.lo asn1_Keys.lo am__objects_3 = $(am__objects_2) hdb_err.lo nodist_libhdb_la_OBJECTS = $(am__objects_3) libhdb_la_OBJECTS = $(dist_libhdb_la_OBJECTS) \ $(nodist_libhdb_la_OBJECTS) libhdb_la_LINK = $(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) \ $(LIBTOOLFLAGS) --mode=link $(CCLD) $(AM_CFLAGS) $(CFLAGS) \ $(libhdb_la_LDFLAGS) $(LDFLAGS) -o $@ PROGRAMS = $(noinst_PROGRAMS) test_dbinfo_SOURCES = test_dbinfo.c test_dbinfo_OBJECTS = test_dbinfo.$(OBJEXT) test_dbinfo_LDADD = $(LDADD) test_dbinfo_DEPENDENCIES = libhdb.la ../krb5/libkrb5.la \ ../asn1/libasn1.la $(am__DEPENDENCIES_1) $(am__DEPENDENCIES_1) \ $(am__DEPENDENCIES_1) $(am__DEPENDENCIES_1) test_hdbkeys_SOURCES = test_hdbkeys.c test_hdbkeys_OBJECTS = test_hdbkeys.$(OBJEXT) test_hdbkeys_LDADD = $(LDADD) test_hdbkeys_DEPENDENCIES = libhdb.la ../krb5/libkrb5.la \ ../asn1/libasn1.la $(am__DEPENDENCIES_1) $(am__DEPENDENCIES_1) \ $(am__DEPENDENCIES_1) $(am__DEPENDENCIES_1) test_hdbplugin_SOURCES = test_hdbplugin.c test_hdbplugin_OBJECTS = test_hdbplugin.$(OBJEXT) test_hdbplugin_LDADD = $(LDADD) test_hdbplugin_DEPENDENCIES = libhdb.la ../krb5/libkrb5.la \ ../asn1/libasn1.la $(am__DEPENDENCIES_1) $(am__DEPENDENCIES_1) \ $(am__DEPENDENCIES_1) $(am__DEPENDENCIES_1) test_mkey_SOURCES = test_mkey.c test_mkey_OBJECTS = test_mkey.$(OBJEXT) test_mkey_LDADD = $(LDADD) test_mkey_DEPENDENCIES = libhdb.la ../krb5/libkrb5.la \ ../asn1/libasn1.la $(am__DEPENDENCIES_1) $(am__DEPENDENCIES_1) \ $(am__DEPENDENCIES_1) $(am__DEPENDENCIES_1) AM_V_P = $(am__v_P_@AM_V@) am__v_P_ = $(am__v_P_@AM_DEFAULT_V@) am__v_P_0 = false am__v_P_1 = : AM_V_GEN = $(am__v_GEN_@AM_V@) am__v_GEN_ = $(am__v_GEN_@AM_DEFAULT_V@) am__v_GEN_0 = @echo " GEN " $@; am__v_GEN_1 = AM_V_at = $(am__v_at_@AM_V@) am__v_at_ = $(am__v_at_@AM_DEFAULT_V@) am__v_at_0 = @ am__v_at_1 = depcomp = $(SHELL) $(top_srcdir)/depcomp am__depfiles_maybe = depfiles am__mv = mv -f COMPILE = $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) \ $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) LTCOMPILE = $(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) \ $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) \ $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) \ $(AM_CFLAGS) $(CFLAGS) AM_V_CC = $(am__v_CC_@AM_V@) am__v_CC_ = $(am__v_CC_@AM_DEFAULT_V@) am__v_CC_0 = @echo " CC " $@; am__v_CC_1 = CCLD = $(CC) LINK = $(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) \ $(LIBTOOLFLAGS) --mode=link $(CCLD) $(AM_CFLAGS) $(CFLAGS) \ $(AM_LDFLAGS) $(LDFLAGS) -o $@ AM_V_CCLD = $(am__v_CCLD_@AM_V@) am__v_CCLD_ = $(am__v_CCLD_@AM_DEFAULT_V@) am__v_CCLD_0 = @echo " CCLD " $@; am__v_CCLD_1 = SOURCES = $(hdb_ldap_la_SOURCES) $(dist_libhdb_la_SOURCES) \ $(nodist_libhdb_la_SOURCES) test_dbinfo.c test_hdbkeys.c \ test_hdbplugin.c test_mkey.c DIST_SOURCES = $(am__hdb_ldap_la_SOURCES_DIST) \ $(am__dist_libhdb_la_SOURCES_DIST) test_dbinfo.c \ test_hdbkeys.c test_hdbplugin.c test_mkey.c am__can_run_installinfo = \ case $$AM_UPDATE_INFO_DIR in \ n|no|NO) false;; \ *) (install-info --version) >/dev/null 2>&1;; \ esac HEADERS = $(include_HEADERS) $(nodist_include_HEADERS) \ $(noinst_HEADERS) am__tagged_files = $(HEADERS) $(SOURCES) $(TAGS_FILES) $(LISP) # Read a list of newline-separated strings from the standard input, # and print each of them once, without duplicates. Input order is # *not* preserved. am__uniquify_input = $(AWK) '\ BEGIN { nonempty = 0; } \ { items[$$0] = 1; nonempty = 1; } \ END { if (nonempty) { for (i in items) print i; }; } \ ' # Make sure the list of sources is unique. This is necessary because, # e.g., the same source file might be shared among _SOURCES variables # for different programs/libraries. am__define_uniq_tagged_files = \ list='$(am__tagged_files)'; \ unique=`for i in $$list; do \ if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ done | $(am__uniquify_input)` ETAGS = etags CTAGS = ctags am__DIST_COMMON = $(srcdir)/Makefile.in \ $(top_srcdir)/Makefile.am.common \ $(top_srcdir)/cf/Makefile.am.common $(top_srcdir)/depcomp DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST) ACLOCAL = @ACLOCAL@ AIX_EXTRA_KAFS = @AIX_EXTRA_KAFS@ AMTAR = @AMTAR@ AM_DEFAULT_VERBOSITY = @AM_DEFAULT_VERBOSITY@ AR = @AR@ AS = @AS@ ASN1_COMPILE = @ASN1_COMPILE@ ASN1_COMPILE_DEP = @ASN1_COMPILE_DEP@ AUTOCONF = @AUTOCONF@ AUTOHEADER = @AUTOHEADER@ AUTOMAKE = @AUTOMAKE@ AWK = @AWK@ CANONICAL_HOST = @CANONICAL_HOST@ CAPNG_CFLAGS = @CAPNG_CFLAGS@ CAPNG_LIBS = @CAPNG_LIBS@ CATMAN = @CATMAN@ CATMANEXT = @CATMANEXT@ CC = @CC@ CCDEPMODE = @CCDEPMODE@ CFLAGS = @CFLAGS@ COMPILE_ET = @COMPILE_ET@ CPP = @CPP@ CPPFLAGS = @CPPFLAGS@ CYGPATH_W = @CYGPATH_W@ DB1LIB = @DB1LIB@ DB3LIB = @DB3LIB@ DBHEADER = @DBHEADER@ DEFS = @DEFS@ DEPDIR = @DEPDIR@ DIR_com_err = @DIR_com_err@ DIR_hdbdir = @DIR_hdbdir@ DIR_roken = @DIR_roken@ DLLTOOL = @DLLTOOL@ DSYMUTIL = @DSYMUTIL@ DUMPBIN = @DUMPBIN@ ECHO_C = @ECHO_C@ ECHO_N = @ECHO_N@ ECHO_T = @ECHO_T@ EGREP = @EGREP@ ENABLE_AFS_STRING_TO_KEY = @ENABLE_AFS_STRING_TO_KEY@ EXEEXT = @EXEEXT@ FGREP = @FGREP@ GCD_MIG = @GCD_MIG@ GREP = @GREP@ GROFF = @GROFF@ INCLUDES_roken = @INCLUDES_roken@ INCLUDE_libedit = @INCLUDE_libedit@ INCLUDE_libintl = @INCLUDE_libintl@ INCLUDE_openldap = @INCLUDE_openldap@ INCLUDE_openssl_crypto = @INCLUDE_openssl_crypto@ INCLUDE_readline = @INCLUDE_readline@ INCLUDE_sqlite3 = @INCLUDE_sqlite3@ INSTALL = @INSTALL@ INSTALL_DATA = @INSTALL_DATA@ INSTALL_PROGRAM = @INSTALL_PROGRAM@ INSTALL_SCRIPT = @INSTALL_SCRIPT@ INSTALL_STRIP_PROGRAM = @INSTALL_STRIP_PROGRAM@ LD = @LD@ LDFLAGS = @LDFLAGS@ LDFLAGS_VERSION_SCRIPT = @LDFLAGS_VERSION_SCRIPT@ LEX = @LEX@ LEXLIB = @LEXLIB@ LEX_OUTPUT_ROOT = @LEX_OUTPUT_ROOT@ LIBADD_roken = @LIBADD_roken@ LIBOBJS = @LIBOBJS@ LIBS = @LIBS@ LIBTOOL = @LIBTOOL@ LIB_AUTH_SUBDIRS = @LIB_AUTH_SUBDIRS@ LIB_bswap16 = @LIB_bswap16@ LIB_bswap32 = @LIB_bswap32@ LIB_bswap64 = @LIB_bswap64@ LIB_com_err = @LIB_com_err@ LIB_com_err_a = @LIB_com_err_a@ LIB_com_err_so = @LIB_com_err_so@ LIB_crypt = @LIB_crypt@ LIB_db_create = @LIB_db_create@ LIB_dbm_firstkey = @LIB_dbm_firstkey@ LIB_dbopen = @LIB_dbopen@ LIB_dispatch_async_f = @LIB_dispatch_async_f@ LIB_dladdr = @LIB_dladdr@ LIB_dlopen = @LIB_dlopen@ LIB_dn_expand = @LIB_dn_expand@ LIB_dns_search = @LIB_dns_search@ LIB_door_create = @LIB_door_create@ LIB_freeaddrinfo = @LIB_freeaddrinfo@ LIB_gai_strerror = @LIB_gai_strerror@ LIB_getaddrinfo = @LIB_getaddrinfo@ LIB_gethostbyname = @LIB_gethostbyname@ LIB_gethostbyname2 = @LIB_gethostbyname2@ LIB_getnameinfo = @LIB_getnameinfo@ LIB_getpwnam_r = @LIB_getpwnam_r@ LIB_getsockopt = @LIB_getsockopt@ LIB_hcrypto = @LIB_hcrypto@ LIB_hcrypto_a = @LIB_hcrypto_a@ LIB_hcrypto_appl = @LIB_hcrypto_appl@ LIB_hcrypto_so = @LIB_hcrypto_so@ LIB_hstrerror = @LIB_hstrerror@ LIB_kdb = @LIB_kdb@ LIB_libedit = @LIB_libedit@ LIB_libintl = @LIB_libintl@ LIB_loadquery = @LIB_loadquery@ LIB_logout = @LIB_logout@ LIB_logwtmp = @LIB_logwtmp@ LIB_openldap = @LIB_openldap@ LIB_openpty = @LIB_openpty@ LIB_openssl_crypto = @LIB_openssl_crypto@ LIB_otp = @LIB_otp@ LIB_pidfile = @LIB_pidfile@ LIB_readline = @LIB_readline@ LIB_res_ndestroy = @LIB_res_ndestroy@ LIB_res_nsearch = @LIB_res_nsearch@ LIB_res_search = @LIB_res_search@ LIB_roken = @LIB_roken@ LIB_security = @LIB_security@ LIB_setsockopt = @LIB_setsockopt@ LIB_socket = @LIB_socket@ LIB_sqlite3 = @LIB_sqlite3@ LIB_syslog = @LIB_syslog@ LIB_tgetent = @LIB_tgetent@ LIPO = @LIPO@ LMDBLIB = @LMDBLIB@ LN_S = @LN_S@ LTLIBOBJS = @LTLIBOBJS@ LT_SYS_LIBRARY_PATH = @LT_SYS_LIBRARY_PATH@ MAINT = @MAINT@ MAKEINFO = @MAKEINFO@ MANIFEST_TOOL = @MANIFEST_TOOL@ MKDIR_P = @MKDIR_P@ NDBMLIB = @NDBMLIB@ NM = @NM@ NMEDIT = @NMEDIT@ NO_AFS = @NO_AFS@ NROFF = @NROFF@ OBJDUMP = @OBJDUMP@ OBJEXT = @OBJEXT@ OTOOL = @OTOOL@ OTOOL64 = @OTOOL64@ PACKAGE = @PACKAGE@ PACKAGE_BUGREPORT = @PACKAGE_BUGREPORT@ PACKAGE_NAME = @PACKAGE_NAME@ PACKAGE_STRING = @PACKAGE_STRING@ PACKAGE_TARNAME = @PACKAGE_TARNAME@ PACKAGE_URL = @PACKAGE_URL@ PACKAGE_VERSION = @PACKAGE_VERSION@ PATH_SEPARATOR = @PATH_SEPARATOR@ PERL = @PERL@ PKG_CONFIG = @PKG_CONFIG@ PTHREAD_CFLAGS = @PTHREAD_CFLAGS@ PTHREAD_LDADD = @PTHREAD_LDADD@ PTHREAD_LIBADD = @PTHREAD_LIBADD@ RANLIB = @RANLIB@ SED = @SED@ SET_MAKE = @SET_MAKE@ SHELL = @SHELL@ SLC = @SLC@ SLC_DEP = @SLC_DEP@ STRIP = @STRIP@ VERSION = @VERSION@ VERSIONING = @VERSIONING@ WFLAGS = @WFLAGS@ WFLAGS_LITE = @WFLAGS_LITE@ YACC = @YACC@ YFLAGS = @YFLAGS@ abs_builddir = @abs_builddir@ abs_srcdir = @abs_srcdir@ abs_top_builddir = @abs_top_builddir@ abs_top_srcdir = @abs_top_srcdir@ ac_ct_AR = @ac_ct_AR@ ac_ct_CC = @ac_ct_CC@ ac_ct_DUMPBIN = @ac_ct_DUMPBIN@ am__include = @am__include@ am__leading_dot = @am__leading_dot@ am__quote = @am__quote@ am__tar = @am__tar@ am__untar = @am__untar@ bindir = @bindir@ build = @build@ build_alias = @build_alias@ build_cpu = @build_cpu@ build_os = @build_os@ build_vendor = @build_vendor@ builddir = @builddir@ datadir = @datadir@ datarootdir = @datarootdir@ db_type = @db_type@ db_type_preference = @db_type_preference@ docdir = @docdir@ dpagaix_cflags = @dpagaix_cflags@ dpagaix_ldadd = @dpagaix_ldadd@ dpagaix_ldflags = @dpagaix_ldflags@ dvidir = @dvidir@ exec_prefix = @exec_prefix@ host = @host@ host_alias = @host_alias@ host_cpu = @host_cpu@ host_os = @host_os@ host_vendor = @host_vendor@ htmldir = @htmldir@ includedir = @includedir@ infodir = @infodir@ install_sh = @install_sh@ libdir = @libdir@ libexecdir = @libexecdir@ localedir = @localedir@ localstatedir = @localstatedir@ mandir = @mandir@ mkdir_p = @mkdir_p@ oldincludedir = @oldincludedir@ pdfdir = @pdfdir@ prefix = @prefix@ program_transform_name = @program_transform_name@ psdir = @psdir@ sbindir = @sbindir@ sharedstatedir = @sharedstatedir@ srcdir = @srcdir@ subdirs = @subdirs@ sysconfdir = @sysconfdir@ target_alias = @target_alias@ top_build_prefix = @top_build_prefix@ top_builddir = @top_builddir@ top_srcdir = @top_srcdir@ SUFFIXES = .et .h .pc.in .pc .x .z .hx .1 .3 .5 .7 .8 .cat1 .cat3 \ .cat5 .cat7 .cat8 DEFAULT_INCLUDES = -I. -I$(srcdir) -I$(top_builddir)/include -I$(top_srcdir)/include AM_CPPFLAGS = $(INCLUDES_roken) -I../asn1 -I$(srcdir)/../asn1 \ $(INCLUDE_openldap) -DHDB_DB_DIR=\"$(DIR_hdbdir)\" \ -I$(srcdir)/../krb5 $(INCLUDE_sqlite3) $(INCLUDE_libintl) \ $(am__append_1) @do_roken_rename_TRUE@ROKEN_RENAME = -DROKEN_RENAME AM_CFLAGS = $(WFLAGS) CP = cp buildinclude = $(top_builddir)/include LIB_XauReadAuth = @LIB_XauReadAuth@ LIB_el_init = @LIB_el_init@ LIB_getattr = @LIB_getattr@ LIB_getpwent_r = @LIB_getpwent_r@ LIB_odm_initialize = @LIB_odm_initialize@ LIB_setpcred = @LIB_setpcred@ INCLUDE_krb4 = @INCLUDE_krb4@ LIB_krb4 = @LIB_krb4@ libexec_heimdaldir = $(libexecdir)/heimdal NROFF_MAN = groff -mandoc -Tascii @NO_AFS_FALSE@LIB_kafs = $(top_builddir)/lib/kafs/libkafs.la $(AIX_EXTRA_KAFS) @NO_AFS_TRUE@LIB_kafs = @KRB5_TRUE@LIB_krb5 = $(top_builddir)/lib/krb5/libkrb5.la \ @KRB5_TRUE@ $(top_builddir)/lib/asn1/libasn1.la @KRB5_TRUE@LIB_gssapi = $(top_builddir)/lib/gssapi/libgssapi.la LIB_heimbase = $(top_builddir)/lib/base/libheimbase.la @DCE_TRUE@LIB_kdfs = $(top_builddir)/lib/kdfs/libkdfs.la #silent-rules heim_verbose = $(heim_verbose_$(V)) heim_verbose_ = $(heim_verbose_$(AM_DEFAULT_VERBOSITY)) heim_verbose_0 = @echo " GEN "$@; BUILT_SOURCES = \ $(gen_files_hdb:.x=.c) \ hdb_err.c \ hdb_err.h gen_files_hdb = \ asn1_Salt.x \ asn1_Key.x \ asn1_Event.x \ asn1_HDBFlags.x \ asn1_GENERATION.x \ asn1_HDB_Ext_PKINIT_acl.x \ asn1_HDB_Ext_PKINIT_cert.x \ asn1_HDB_Ext_PKINIT_hash.x \ asn1_HDB_Ext_Constrained_delegation_acl.x \ asn1_HDB_Ext_Lan_Manager_OWF.x \ asn1_HDB_Ext_Password.x \ asn1_HDB_Ext_Aliases.x \ asn1_HDB_Ext_KeySet.x \ asn1_HDB_extension.x \ asn1_HDB_extensions.x \ asn1_hdb_entry.x \ asn1_hdb_entry_alias.x \ asn1_hdb_keyset.x \ asn1_Keys.x CLEANFILES = $(BUILT_SOURCES) $(gen_files_hdb) \ hdb_asn1{,-priv}.h* hdb_asn1_files hdb_asn1-template.[cx] LDADD = libhdb.la \ ../krb5/libkrb5.la \ ../asn1/libasn1.la \ $(LIB_hcrypto) \ $(LIB_roken) \ $(LIB_openldap) \ $(LIB_libintl) \ $(LIB_ldopen) @OPENLDAP_MODULE_TRUE@ldap_so = hdb_ldap.la @OPENLDAP_MODULE_TRUE@hdb_ldap_la_SOURCES = hdb-ldap.c @OPENLDAP_MODULE_TRUE@hdb_ldap_la_LDFLAGS = -module -avoid-version @OPENLDAP_MODULE_TRUE@hdb_ldap_la_LIBADD = $(LIB_openldap) libhdb.la @OPENLDAP_MODULE_FALSE@ldap = hdb-ldap.c @OPENLDAP_MODULE_FALSE@ldap_lib = $(LIB_openldap) lib_LTLIBRARIES = libhdb.la $(ldap_so) libhdb_la_LDFLAGS = -version-info 11:0:2 $(am__append_2) dist_libhdb_la_SOURCES = \ common.c \ db.c \ db3.c \ ext.c \ $(ldap) \ hdb.c \ hdb-sqlite.c \ hdb-keytab.c \ hdb-mdb.c \ hdb-mitdb.c \ hdb_locl.h \ keys.c \ keytab.c \ dbinfo.c \ mkey.c \ ndbm.c \ print.c nodist_libhdb_la_SOURCES = $(BUILT_SOURCES) libhdb_la_DEPENDENCIES = version-script.map include_HEADERS = hdb.h $(srcdir)/hdb-protos.h nodist_include_HEADERS = hdb_err.h hdb_asn1.h noinst_HEADERS = $(srcdir)/hdb-private.h libhdb_la_LIBADD = \ $(LIB_com_err) \ ../krb5/libkrb5.la \ ../asn1/libasn1.la \ $(LIB_sqlite3) \ $(LIBADD_roken) \ $(ldap_lib) \ $(LIB_dlopen) \ $(DB3LIB) $(DB1LIB) $(LMDBLIB) $(NDBMLIB) HDB_PROTOS = $(srcdir)/hdb-protos.h $(srcdir)/hdb-private.h ALL_OBJECTS = $(libhdb_la_OBJECTS) $(test_dbinfo_OBJECTS) \ $(test_hdbkeys_OBJECTS) $(test_mkey_OBJECTS) \ $(test_hdbplugin_OBJECTS) test_dbinfo_LIBS = libhdb.la test_hdbkeys_LIBS = ../krb5/libkrb5.la libhdb.la test_mkey_LIBS = $(test_hdbkeys_LIBS) test_hdbplugin_LIBS = $(test_hdbkeys_LIBS) EXTRA_DIST = \ NTMakefile \ libhdb-version.rc \ libhdb-exports.def \ hdb.asn1 \ hdb_err.et \ hdb.schema \ version-script.map \ data-mkey.mit.des3.le \ data-mkey.mit.des3.be all: $(BUILT_SOURCES) $(MAKE) $(AM_MAKEFLAGS) all-am .SUFFIXES: .SUFFIXES: .et .h .pc.in .pc .x .z .hx .1 .3 .5 .7 .8 .cat1 .cat3 .cat5 .cat7 .cat8 .c .lo .o .obj $(srcdir)/Makefile.in: @MAINTAINER_MODE_TRUE@ $(srcdir)/Makefile.am $(top_srcdir)/Makefile.am.common $(top_srcdir)/cf/Makefile.am.common $(am__configure_deps) @for dep in $?; do \ case '$(am__configure_deps)' in \ *$$dep*) \ ( cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh ) \ && { if test -f $@; then exit 0; else break; fi; }; \ exit 1;; \ esac; \ done; \ echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign lib/hdb/Makefile'; \ $(am__cd) $(top_srcdir) && \ $(AUTOMAKE) --foreign lib/hdb/Makefile Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status @case '$?' in \ *config.status*) \ cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh;; \ *) \ echo ' cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe)'; \ cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe);; \ esac; $(top_srcdir)/Makefile.am.common $(top_srcdir)/cf/Makefile.am.common $(am__empty): $(top_builddir)/config.status: $(top_srcdir)/configure $(CONFIG_STATUS_DEPENDENCIES) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(top_srcdir)/configure: @MAINTAINER_MODE_TRUE@ $(am__configure_deps) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(ACLOCAL_M4): @MAINTAINER_MODE_TRUE@ $(am__aclocal_m4_deps) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(am__aclocal_m4_deps): install-libLTLIBRARIES: $(lib_LTLIBRARIES) @$(NORMAL_INSTALL) @list='$(lib_LTLIBRARIES)'; test -n "$(libdir)" || list=; \ list2=; for p in $$list; do \ if test -f $$p; then \ list2="$$list2 $$p"; \ else :; fi; \ done; \ test -z "$$list2" || { \ echo " $(MKDIR_P) '$(DESTDIR)$(libdir)'"; \ $(MKDIR_P) "$(DESTDIR)$(libdir)" || exit 1; \ echo " $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=install $(INSTALL) $(INSTALL_STRIP_FLAG) $$list2 '$(DESTDIR)$(libdir)'"; \ $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=install $(INSTALL) $(INSTALL_STRIP_FLAG) $$list2 "$(DESTDIR)$(libdir)"; \ } uninstall-libLTLIBRARIES: @$(NORMAL_UNINSTALL) @list='$(lib_LTLIBRARIES)'; test -n "$(libdir)" || list=; \ for p in $$list; do \ $(am__strip_dir) \ echo " $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=uninstall rm -f '$(DESTDIR)$(libdir)/$$f'"; \ $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=uninstall rm -f "$(DESTDIR)$(libdir)/$$f"; \ done clean-libLTLIBRARIES: -test -z "$(lib_LTLIBRARIES)" || rm -f $(lib_LTLIBRARIES) @list='$(lib_LTLIBRARIES)'; \ locs=`for p in $$list; do echo $$p; done | \ sed 's|^[^/]*$$|.|; s|/[^/]*$$||; s|$$|/so_locations|' | \ sort -u`; \ test -z "$$locs" || { \ echo rm -f $${locs}; \ rm -f $${locs}; \ } hdb_ldap.la: $(hdb_ldap_la_OBJECTS) $(hdb_ldap_la_DEPENDENCIES) $(EXTRA_hdb_ldap_la_DEPENDENCIES) $(AM_V_CCLD)$(hdb_ldap_la_LINK) $(am_hdb_ldap_la_rpath) $(hdb_ldap_la_OBJECTS) $(hdb_ldap_la_LIBADD) $(LIBS) libhdb.la: $(libhdb_la_OBJECTS) $(libhdb_la_DEPENDENCIES) $(EXTRA_libhdb_la_DEPENDENCIES) $(AM_V_CCLD)$(libhdb_la_LINK) -rpath $(libdir) $(libhdb_la_OBJECTS) $(libhdb_la_LIBADD) $(LIBS) clean-noinstPROGRAMS: @list='$(noinst_PROGRAMS)'; test -n "$$list" || exit 0; \ echo " rm -f" $$list; \ rm -f $$list || exit $$?; \ test -n "$(EXEEXT)" || exit 0; \ list=`for p in $$list; do echo "$$p"; done | sed 's/$(EXEEXT)$$//'`; \ echo " rm -f" $$list; \ rm -f $$list test_dbinfo$(EXEEXT): $(test_dbinfo_OBJECTS) $(test_dbinfo_DEPENDENCIES) $(EXTRA_test_dbinfo_DEPENDENCIES) @rm -f test_dbinfo$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_dbinfo_OBJECTS) $(test_dbinfo_LDADD) $(LIBS) test_hdbkeys$(EXEEXT): $(test_hdbkeys_OBJECTS) $(test_hdbkeys_DEPENDENCIES) $(EXTRA_test_hdbkeys_DEPENDENCIES) @rm -f test_hdbkeys$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_hdbkeys_OBJECTS) $(test_hdbkeys_LDADD) $(LIBS) test_hdbplugin$(EXEEXT): $(test_hdbplugin_OBJECTS) $(test_hdbplugin_DEPENDENCIES) $(EXTRA_test_hdbplugin_DEPENDENCIES) @rm -f test_hdbplugin$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_hdbplugin_OBJECTS) $(test_hdbplugin_LDADD) $(LIBS) test_mkey$(EXEEXT): $(test_mkey_OBJECTS) $(test_mkey_DEPENDENCIES) $(EXTRA_test_mkey_DEPENDENCIES) @rm -f test_mkey$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_mkey_OBJECTS) $(test_mkey_LDADD) $(LIBS) mostlyclean-compile: -rm -f *.$(OBJEXT) distclean-compile: -rm -f *.tab.c @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/asn1_Event.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/asn1_GENERATION.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/asn1_HDBFlags.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/asn1_HDB_Ext_Aliases.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/asn1_HDB_Ext_Constrained_delegation_acl.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/asn1_HDB_Ext_KeySet.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/asn1_HDB_Ext_Lan_Manager_OWF.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/asn1_HDB_Ext_PKINIT_acl.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/asn1_HDB_Ext_PKINIT_cert.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/asn1_HDB_Ext_PKINIT_hash.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/asn1_HDB_Ext_Password.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/asn1_HDB_extension.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/asn1_HDB_extensions.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/asn1_Key.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/asn1_Keys.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/asn1_Salt.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/asn1_hdb_entry.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/asn1_hdb_entry_alias.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/asn1_hdb_keyset.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/common.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/db.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/db3.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/dbinfo.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/ext.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/hdb-keytab.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/hdb-ldap.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/hdb-mdb.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/hdb-mitdb.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/hdb-sqlite.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/hdb.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/hdb_err.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/keys.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/keytab.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/mkey.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/ndbm.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/print.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_dbinfo.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_hdbkeys.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_hdbplugin.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_mkey.Po@am__quote@ .c.o: @am__fastdepCC_TRUE@ $(AM_V_CC)$(COMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o $@ $< @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='$<' object='$@' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(COMPILE) -c -o $@ $< .c.obj: @am__fastdepCC_TRUE@ $(AM_V_CC)$(COMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o $@ `$(CYGPATH_W) '$<'` @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='$<' object='$@' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(COMPILE) -c -o $@ `$(CYGPATH_W) '$<'` .c.lo: @am__fastdepCC_TRUE@ $(AM_V_CC)$(LTCOMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o $@ $< @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='$<' object='$@' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LTCOMPILE) -c -o $@ $< mostlyclean-libtool: -rm -f *.lo clean-libtool: -rm -rf .libs _libs install-includeHEADERS: $(include_HEADERS) @$(NORMAL_INSTALL) @list='$(include_HEADERS)'; test -n "$(includedir)" || list=; \ if test -n "$$list"; then \ echo " $(MKDIR_P) '$(DESTDIR)$(includedir)'"; \ $(MKDIR_P) "$(DESTDIR)$(includedir)" || exit 1; \ fi; \ for p in $$list; do \ if test -f "$$p"; then d=; else d="$(srcdir)/"; fi; \ echo "$$d$$p"; \ done | $(am__base_list) | \ while read files; do \ echo " $(INSTALL_HEADER) $$files '$(DESTDIR)$(includedir)'"; \ $(INSTALL_HEADER) $$files "$(DESTDIR)$(includedir)" || exit $$?; \ done uninstall-includeHEADERS: @$(NORMAL_UNINSTALL) @list='$(include_HEADERS)'; test -n "$(includedir)" || list=; \ files=`for p in $$list; do echo $$p; done | sed -e 's|^.*/||'`; \ dir='$(DESTDIR)$(includedir)'; $(am__uninstall_files_from_dir) install-nodist_includeHEADERS: $(nodist_include_HEADERS) @$(NORMAL_INSTALL) @list='$(nodist_include_HEADERS)'; test -n "$(includedir)" || list=; \ if test -n "$$list"; then \ echo " $(MKDIR_P) '$(DESTDIR)$(includedir)'"; \ $(MKDIR_P) "$(DESTDIR)$(includedir)" || exit 1; \ fi; \ for p in $$list; do \ if test -f "$$p"; then d=; else d="$(srcdir)/"; fi; \ echo "$$d$$p"; \ done | $(am__base_list) | \ while read files; do \ echo " $(INSTALL_HEADER) $$files '$(DESTDIR)$(includedir)'"; \ $(INSTALL_HEADER) $$files "$(DESTDIR)$(includedir)" || exit $$?; \ done uninstall-nodist_includeHEADERS: @$(NORMAL_UNINSTALL) @list='$(nodist_include_HEADERS)'; test -n "$(includedir)" || list=; \ files=`for p in $$list; do echo $$p; done | sed -e 's|^.*/||'`; \ dir='$(DESTDIR)$(includedir)'; $(am__uninstall_files_from_dir) ID: $(am__tagged_files) $(am__define_uniq_tagged_files); mkid -fID $$unique tags: tags-am TAGS: tags tags-am: $(TAGS_DEPENDENCIES) $(am__tagged_files) set x; \ here=`pwd`; \ $(am__define_uniq_tagged_files); \ shift; \ if test -z "$(ETAGS_ARGS)$$*$$unique"; then :; else \ test -n "$$unique" || unique=$$empty_fix; \ if test $$# -gt 0; then \ $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ "$$@" $$unique; \ else \ $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ $$unique; \ fi; \ fi ctags: ctags-am CTAGS: ctags ctags-am: $(TAGS_DEPENDENCIES) $(am__tagged_files) $(am__define_uniq_tagged_files); \ test -z "$(CTAGS_ARGS)$$unique" \ || $(CTAGS) $(CTAGSFLAGS) $(AM_CTAGSFLAGS) $(CTAGS_ARGS) \ $$unique GTAGS: here=`$(am__cd) $(top_builddir) && pwd` \ && $(am__cd) $(top_srcdir) \ && gtags -i $(GTAGS_ARGS) "$$here" cscopelist: cscopelist-am cscopelist-am: $(am__tagged_files) list='$(am__tagged_files)'; \ case "$(srcdir)" in \ [\\/]* | ?:[\\/]*) sdir="$(srcdir)" ;; \ *) sdir=$(subdir)/$(srcdir) ;; \ esac; \ for i in $$list; do \ if test -f "$$i"; then \ echo "$(subdir)/$$i"; \ else \ echo "$$sdir/$$i"; \ fi; \ done >> $(top_builddir)/cscope.files distclean-tags: -rm -f TAGS ID GTAGS GRTAGS GSYMS GPATH tags distdir: $(DISTFILES) @srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ topsrcdirstrip=`echo "$(top_srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ list='$(DISTFILES)'; \ dist_files=`for file in $$list; do echo $$file; done | \ sed -e "s|^$$srcdirstrip/||;t" \ -e "s|^$$topsrcdirstrip/|$(top_builddir)/|;t"`; \ case $$dist_files in \ */*) $(MKDIR_P) `echo "$$dist_files" | \ sed '/\//!d;s|^|$(distdir)/|;s,/[^/]*$$,,' | \ sort -u` ;; \ esac; \ for file in $$dist_files; do \ if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \ if test -d $$d/$$file; then \ dir=`echo "/$$file" | sed -e 's,/[^/]*$$,,'`; \ if test -d "$(distdir)/$$file"; then \ find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ fi; \ if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \ cp -fpR $(srcdir)/$$file "$(distdir)$$dir" || exit 1; \ find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ fi; \ cp -fpR $$d/$$file "$(distdir)$$dir" || exit 1; \ else \ test -f "$(distdir)/$$file" \ || cp -p $$d/$$file "$(distdir)/$$file" \ || exit 1; \ fi; \ done $(MAKE) $(AM_MAKEFLAGS) \ top_distdir="$(top_distdir)" distdir="$(distdir)" \ dist-hook check-am: all-am $(MAKE) $(AM_MAKEFLAGS) check-local check: $(BUILT_SOURCES) $(MAKE) $(AM_MAKEFLAGS) check-am all-am: Makefile $(LTLIBRARIES) $(PROGRAMS) $(HEADERS) all-local installdirs: for dir in "$(DESTDIR)$(libdir)" "$(DESTDIR)$(includedir)" "$(DESTDIR)$(includedir)"; do \ test -z "$$dir" || $(MKDIR_P) "$$dir"; \ done install: $(BUILT_SOURCES) $(MAKE) $(AM_MAKEFLAGS) install-am install-exec: install-exec-am install-data: install-data-am uninstall: uninstall-am install-am: all-am @$(MAKE) $(AM_MAKEFLAGS) install-exec-am install-data-am installcheck: installcheck-am install-strip: if test -z '$(STRIP)'; then \ $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ install; \ else \ $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'" install; \ fi mostlyclean-generic: clean-generic: -test -z "$(CLEANFILES)" || rm -f $(CLEANFILES) distclean-generic: -test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES) -test . = "$(srcdir)" || test -z "$(CONFIG_CLEAN_VPATH_FILES)" || rm -f $(CONFIG_CLEAN_VPATH_FILES) maintainer-clean-generic: @echo "This command is intended for maintainers to use" @echo "it deletes files that may require special tools to rebuild." -test -z "$(BUILT_SOURCES)" || rm -f $(BUILT_SOURCES) clean: clean-am clean-am: clean-generic clean-libLTLIBRARIES clean-libtool \ clean-noinstPROGRAMS mostlyclean-am distclean: distclean-am -rm -rf ./$(DEPDIR) -rm -f Makefile distclean-am: clean-am distclean-compile distclean-generic \ distclean-tags dvi: dvi-am dvi-am: html: html-am html-am: info: info-am info-am: install-data-am: install-includeHEADERS install-nodist_includeHEADERS @$(NORMAL_INSTALL) $(MAKE) $(AM_MAKEFLAGS) install-data-hook install-dvi: install-dvi-am install-dvi-am: install-exec-am: install-exec-local install-libLTLIBRARIES install-html: install-html-am install-html-am: install-info: install-info-am install-info-am: install-man: install-pdf: install-pdf-am install-pdf-am: install-ps: install-ps-am install-ps-am: installcheck-am: maintainer-clean: maintainer-clean-am -rm -rf ./$(DEPDIR) -rm -f Makefile maintainer-clean-am: distclean-am maintainer-clean-generic mostlyclean: mostlyclean-am mostlyclean-am: mostlyclean-compile mostlyclean-generic \ mostlyclean-libtool pdf: pdf-am pdf-am: ps: ps-am ps-am: uninstall-am: uninstall-includeHEADERS uninstall-libLTLIBRARIES \ uninstall-nodist_includeHEADERS @$(NORMAL_INSTALL) $(MAKE) $(AM_MAKEFLAGS) uninstall-hook .MAKE: all check check-am install install-am install-data-am \ install-strip uninstall-am .PHONY: CTAGS GTAGS TAGS all all-am all-local check check-am \ check-local clean clean-generic clean-libLTLIBRARIES \ clean-libtool clean-noinstPROGRAMS cscopelist-am ctags \ ctags-am dist-hook distclean distclean-compile \ distclean-generic distclean-libtool distclean-tags distdir dvi \ dvi-am html html-am info info-am install install-am \ install-data install-data-am install-data-hook install-dvi \ install-dvi-am install-exec install-exec-am install-exec-local \ install-html install-html-am install-includeHEADERS \ install-info install-info-am install-libLTLIBRARIES \ install-man install-nodist_includeHEADERS install-pdf \ install-pdf-am install-ps install-ps-am install-strip \ installcheck installcheck-am installdirs maintainer-clean \ maintainer-clean-generic mostlyclean mostlyclean-compile \ mostlyclean-generic mostlyclean-libtool pdf pdf-am ps ps-am \ tags tags-am uninstall uninstall-am uninstall-hook \ uninstall-includeHEADERS uninstall-libLTLIBRARIES \ uninstall-nodist_includeHEADERS .PRECIOUS: Makefile install-suid-programs: @foo='$(bin_SUIDS)'; \ for file in $$foo; do \ x=$(DESTDIR)$(bindir)/$$file; \ if chown 0:0 $$x && chmod u+s $$x; then :; else \ echo "*"; \ echo "* Failed to install $$x setuid root"; \ echo "*"; \ fi; \ done install-exec-local: install-suid-programs codesign-all: @if [ X"$$CODE_SIGN_IDENTITY" != X ] ; then \ foo='$(bin_PROGRAMS) $(sbin_PROGRAMS) $(libexec_PROGRAMS)' ; \ for file in $$foo ; do \ echo "CODESIGN $$file" ; \ codesign -f -s "$$CODE_SIGN_IDENTITY" $$file || exit 1 ; \ done ; \ fi all-local: codesign-all install-build-headers:: $(include_HEADERS) $(dist_include_HEADERS) $(nodist_include_HEADERS) $(build_HEADERZ) $(nobase_include_HEADERS) $(noinst_HEADERS) @foo='$(include_HEADERS) $(dist_include_HEADERS) $(nodist_include_HEADERS) $(build_HEADERZ) $(noinst_HEADERS)'; \ for f in $$foo; do \ f=`basename $$f`; \ if test -f "$(srcdir)/$$f"; then file="$(srcdir)/$$f"; \ else file="$$f"; fi; \ if cmp -s $$file $(buildinclude)/$$f 2> /dev/null ; then \ : ; else \ echo " $(CP) $$file $(buildinclude)/$$f"; \ $(CP) $$file $(buildinclude)/$$f || true; \ fi ; \ done ; \ foo='$(nobase_include_HEADERS)'; \ for f in $$foo; do \ if test -f "$(srcdir)/$$f"; then file="$(srcdir)/$$f"; \ else file="$$f"; fi; \ $(mkdir_p) $(buildinclude)/`dirname $$f` ; \ if cmp -s $$file $(buildinclude)/$$f 2> /dev/null ; then \ : ; else \ echo " $(CP) $$file $(buildinclude)/$$f"; \ $(CP) $$file $(buildinclude)/$$f; \ fi ; \ done all-local: install-build-headers check-local:: @if test '$(CHECK_LOCAL)' = "no-check-local"; then \ foo=''; elif test '$(CHECK_LOCAL)'; then \ foo='$(CHECK_LOCAL)'; else \ foo='$(PROGRAMS)'; fi; \ if test "$$foo"; then \ failed=0; all=0; \ for i in $$foo; do \ all=`expr $$all + 1`; \ if (./$$i --version && ./$$i --help) > /dev/null 2>&1; then \ echo "PASS: $$i"; \ else \ echo "FAIL: $$i"; \ failed=`expr $$failed + 1`; \ fi; \ done; \ if test "$$failed" -eq 0; then \ banner="All $$all tests passed"; \ else \ banner="$$failed of $$all tests failed"; \ fi; \ dashes=`echo "$$banner" | sed s/./=/g`; \ echo "$$dashes"; \ echo "$$banner"; \ echo "$$dashes"; \ test "$$failed" -eq 0 || exit 1; \ fi .x.c: @cmp -s $< $@ 2> /dev/null || cp $< $@ .hx.h: @cmp -s $< $@ 2> /dev/null || cp $< $@ #NROFF_MAN = nroff -man .1.cat1: $(NROFF_MAN) $< > $@ .3.cat3: $(NROFF_MAN) $< > $@ .5.cat5: $(NROFF_MAN) $< > $@ .7.cat7: $(NROFF_MAN) $< > $@ .8.cat8: $(NROFF_MAN) $< > $@ dist-cat1-mans: @foo='$(man1_MANS)'; \ bar='$(man_MANS)'; \ for i in $$bar; do \ case $$i in \ *.1) foo="$$foo $$i";; \ esac; done ;\ for i in $$foo; do \ x=`echo $$i | sed 's/\.[^.]*$$/.cat1/'`; \ echo "$(NROFF_MAN) $(srcdir)/$$i > $(distdir)/$$x"; \ $(NROFF_MAN) $(srcdir)/$$i > $(distdir)/$$x; \ done dist-cat3-mans: @foo='$(man3_MANS)'; \ bar='$(man_MANS)'; \ for i in $$bar; do \ case $$i in \ *.3) foo="$$foo $$i";; \ esac; done ;\ for i in $$foo; do \ x=`echo $$i | sed 's/\.[^.]*$$/.cat3/'`; \ echo "$(NROFF_MAN) $(srcdir)/$$i > $(distdir)/$$x"; \ $(NROFF_MAN) $(srcdir)/$$i > $(distdir)/$$x; \ done dist-cat5-mans: @foo='$(man5_MANS)'; \ bar='$(man_MANS)'; \ for i in $$bar; do \ case $$i in \ *.5) foo="$$foo $$i";; \ esac; done ;\ for i in $$foo; do \ x=`echo $$i | sed 's/\.[^.]*$$/.cat5/'`; \ echo "$(NROFF_MAN) $(srcdir)/$$i > $(distdir)/$$x"; \ $(NROFF_MAN) $(srcdir)/$$i > $(distdir)/$$x; \ done dist-cat7-mans: @foo='$(man7_MANS)'; \ bar='$(man_MANS)'; \ for i in $$bar; do \ case $$i in \ *.7) foo="$$foo $$i";; \ esac; done ;\ for i in $$foo; do \ x=`echo $$i | sed 's/\.[^.]*$$/.cat7/'`; \ echo "$(NROFF_MAN) $(srcdir)/$$i > $(distdir)/$$x"; \ $(NROFF_MAN) $(srcdir)/$$i > $(distdir)/$$x; \ done dist-cat8-mans: @foo='$(man8_MANS)'; \ bar='$(man_MANS)'; \ for i in $$bar; do \ case $$i in \ *.8) foo="$$foo $$i";; \ esac; done ;\ for i in $$foo; do \ x=`echo $$i | sed 's/\.[^.]*$$/.cat8/'`; \ echo "$(NROFF_MAN) $(srcdir)/$$i > $(distdir)/$$x"; \ $(NROFF_MAN) $(srcdir)/$$i > $(distdir)/$$x; \ done dist-hook: dist-cat1-mans dist-cat3-mans dist-cat5-mans dist-cat7-mans dist-cat8-mans install-cat-mans: $(SHELL) $(top_srcdir)/cf/install-catman.sh install "$(INSTALL_DATA)" "$(mkinstalldirs)" "$(srcdir)" "$(DESTDIR)$(mandir)" '$(CATMANEXT)' $(man_MANS) $(man1_MANS) $(man3_MANS) $(man5_MANS) $(man7_MANS) $(man8_MANS) uninstall-cat-mans: $(SHELL) $(top_srcdir)/cf/install-catman.sh uninstall "$(INSTALL_DATA)" "$(mkinstalldirs)" "$(srcdir)" "$(DESTDIR)$(mandir)" '$(CATMANEXT)' $(man_MANS) $(man1_MANS) $(man3_MANS) $(man5_MANS) $(man7_MANS) $(man8_MANS) install-data-hook: install-cat-mans uninstall-hook: uninstall-cat-mans .et.h: $(COMPILE_ET) $< .et.c: $(COMPILE_ET) $< # # Useful target for debugging # check-valgrind: tobjdir=`cd $(top_builddir) && pwd` ; \ tsrcdir=`cd $(top_srcdir) && pwd` ; \ env TESTS_ENVIRONMENT="$${tsrcdir}/cf/maybe-valgrind.sh -s $${tsrcdir} -o $${tobjdir}" make check # # Target to please samba build farm, builds distfiles in-tree. # Will break when automake changes... # distdir-in-tree: $(DISTFILES) $(INFO_DEPS) list='$(DIST_SUBDIRS)'; for subdir in $$list; do \ if test "$$subdir" != .; then \ (cd $$subdir && $(MAKE) $(AM_MAKEFLAGS) distdir-in-tree) ; \ fi ; \ done $(ALL_OBJECTS): $(HDB_PROTOS) hdb_asn1.h hdb_asn1-priv.h hdb_err.h $(srcdir)/hdb-protos.h: $(dist_libhdb_la_SOURCES) cd $(srcdir); perl ../../cf/make-proto.pl -q -P comment -o hdb-protos.h $(dist_libhdb_la_SOURCES) || rm -f hdb-protos.h $(srcdir)/hdb-private.h: $(dist_libhdb_la_SOURCES) cd $(srcdir); perl ../../cf/make-proto.pl -q -P comment -p hdb-private.h $(dist_libhdb_la_SOURCES) || rm -f hdb-private.h $(gen_files_hdb) hdb_asn1.hx hdb_asn1-priv.hx: hdb_asn1_files hdb_asn1_files: $(ASN1_COMPILE_DEP) $(srcdir)/hdb.asn1 $(ASN1_COMPILE) --sequence=HDB-Ext-KeySet --sequence=Keys $(srcdir)/hdb.asn1 hdb_asn1 # to help stupid solaris make hdb_err.h: hdb_err.et # Tell versions [3.59,3.63) of GNU make to not export all variables. # Otherwise a system limit (for SysV at least) may be exceeded. .NOEXPORT: heimdal-7.5.0/lib/hdb/mkey.c0000644000175000017500000004716313212137553013703 0ustar niknik/* * Copyright (c) 2000 - 2004 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "hdb_locl.h" #ifndef O_BINARY #define O_BINARY 0 #endif struct hdb_master_key_data { krb5_keytab_entry keytab; krb5_crypto crypto; struct hdb_master_key_data *next; unsigned int key_usage; }; void hdb_free_master_key(krb5_context context, hdb_master_key mkey) { struct hdb_master_key_data *ptr; while(mkey) { krb5_kt_free_entry(context, &mkey->keytab); if (mkey->crypto) krb5_crypto_destroy(context, mkey->crypto); ptr = mkey; mkey = mkey->next; free(ptr); } } krb5_error_code hdb_process_master_key(krb5_context context, int kvno, krb5_keyblock *key, krb5_enctype etype, hdb_master_key *mkey) { krb5_error_code ret; *mkey = calloc(1, sizeof(**mkey)); if(*mkey == NULL) { krb5_set_error_message(context, ENOMEM, "malloc: out of memory"); return ENOMEM; } (*mkey)->key_usage = HDB_KU_MKEY; (*mkey)->keytab.vno = kvno; ret = krb5_parse_name(context, "K/M", &(*mkey)->keytab.principal); if(ret) goto fail; ret = krb5_copy_keyblock_contents(context, key, &(*mkey)->keytab.keyblock); if(ret) goto fail; if(etype != 0) (*mkey)->keytab.keyblock.keytype = etype; (*mkey)->keytab.timestamp = time(NULL); ret = krb5_crypto_init(context, key, etype, &(*mkey)->crypto); if(ret) goto fail; return 0; fail: hdb_free_master_key(context, *mkey); *mkey = NULL; return ret; } krb5_error_code hdb_add_master_key(krb5_context context, krb5_keyblock *key, hdb_master_key *inout) { int vno = 0; hdb_master_key p; krb5_error_code ret; for(p = *inout; p; p = p->next) vno = max(vno, p->keytab.vno); vno++; ret = hdb_process_master_key(context, vno, key, 0, &p); if(ret) return ret; p->next = *inout; *inout = p; return 0; } static krb5_error_code read_master_keytab(krb5_context context, const char *filename, hdb_master_key *mkey) { krb5_error_code ret; krb5_keytab id; krb5_kt_cursor cursor; krb5_keytab_entry entry; hdb_master_key p; *mkey = NULL; ret = krb5_kt_resolve(context, filename, &id); if(ret) return ret; ret = krb5_kt_start_seq_get(context, id, &cursor); if(ret) goto out; while(krb5_kt_next_entry(context, id, &entry, &cursor) == 0) { p = calloc(1, sizeof(*p)); if (p == NULL) { ret = ENOMEM; break; } p->keytab = entry; p->next = *mkey; *mkey = p; ret = krb5_crypto_init(context, &p->keytab.keyblock, 0, &p->crypto); if (ret) break; } krb5_kt_end_seq_get(context, id, &cursor); out: krb5_kt_close(context, id); if (ret) { hdb_free_master_key(context, *mkey); *mkey = NULL; } return ret; } /* read a MIT master keyfile */ static krb5_error_code read_master_mit(krb5_context context, const char *filename, int byteorder, hdb_master_key *mkey) { int fd; krb5_error_code ret; krb5_storage *sp; int16_t enctype; krb5_keyblock key; fd = open(filename, O_RDONLY | O_BINARY); if(fd < 0) { int save_errno = errno; krb5_set_error_message(context, save_errno, "failed to open %s: %s", filename, strerror(save_errno)); return save_errno; } sp = krb5_storage_from_fd(fd); if(sp == NULL) { close(fd); return errno; } krb5_storage_set_flags(sp, byteorder); /* could possibly use ret_keyblock here, but do it with more checks for now */ { ret = krb5_ret_int16(sp, &enctype); if (ret) goto out; ret = krb5_enctype_valid(context, enctype); if (ret) goto out; key.keytype = enctype; ret = krb5_ret_data(sp, &key.keyvalue); if(ret) goto out; } ret = hdb_process_master_key(context, 1, &key, 0, mkey); krb5_free_keyblock_contents(context, &key); out: krb5_storage_free(sp); close(fd); return ret; } /* read an old master key file */ static krb5_error_code read_master_encryptionkey(krb5_context context, const char *filename, hdb_master_key *mkey) { int fd; krb5_keyblock key; krb5_error_code ret; unsigned char buf[256]; ssize_t len; size_t ret_len; fd = open(filename, O_RDONLY | O_BINARY); if(fd < 0) { int save_errno = errno; krb5_set_error_message(context, save_errno, "failed to open %s: %s", filename, strerror(save_errno)); return save_errno; } len = read(fd, buf, sizeof(buf)); close(fd); if(len < 0) { int save_errno = errno; krb5_set_error_message(context, save_errno, "error reading %s: %s", filename, strerror(save_errno)); return save_errno; } ret = decode_EncryptionKey(buf, len, &key, &ret_len); memset(buf, 0, sizeof(buf)); if(ret) return ret; /* Originally, the keytype was just that, and later it got changed to des-cbc-md5, but we always used des in cfb64 mode. This should cover all cases, but will break if someone has hacked this code to really use des-cbc-md5 -- but then that's not my problem. */ if(key.keytype == ETYPE_DES_CBC_CRC || key.keytype == ETYPE_DES_CBC_MD5) key.keytype = ETYPE_DES_CFB64_NONE; ret = hdb_process_master_key(context, 0, &key, 0, mkey); krb5_free_keyblock_contents(context, &key); return ret; } /* read a krb4 /.k style file */ static krb5_error_code read_master_krb4(krb5_context context, const char *filename, hdb_master_key *mkey) { int fd; krb5_keyblock key; krb5_error_code ret; unsigned char buf[256]; ssize_t len; fd = open(filename, O_RDONLY | O_BINARY); if(fd < 0) { int save_errno = errno; krb5_set_error_message(context, save_errno, "failed to open %s: %s", filename, strerror(save_errno)); return save_errno; } len = read(fd, buf, sizeof(buf)); close(fd); if(len < 0) { int save_errno = errno; krb5_set_error_message(context, save_errno, "error reading %s: %s", filename, strerror(save_errno)); return save_errno; } if(len != 8) { krb5_set_error_message(context, HEIM_ERR_EOF, "bad contents of %s", filename); return HEIM_ERR_EOF; /* XXX file might be too large */ } memset(&key, 0, sizeof(key)); key.keytype = ETYPE_DES_PCBC_NONE; ret = krb5_data_copy(&key.keyvalue, buf, len); memset(buf, 0, sizeof(buf)); if(ret) return ret; ret = hdb_process_master_key(context, 0, &key, 0, mkey); krb5_free_keyblock_contents(context, &key); return ret; } krb5_error_code hdb_read_master_key(krb5_context context, const char *filename, hdb_master_key *mkey) { FILE *f; unsigned char buf[16]; krb5_error_code ret; off_t len; *mkey = NULL; if(filename == NULL) filename = HDB_DB_DIR "/m-key"; f = fopen(filename, "r"); if(f == NULL) { int save_errno = errno; krb5_set_error_message(context, save_errno, "failed to open %s: %s", filename, strerror(save_errno)); return save_errno; } if(fread(buf, 1, 2, f) != 2) { fclose(f); krb5_set_error_message(context, HEIM_ERR_EOF, "end of file reading %s", filename); return HEIM_ERR_EOF; } fseek(f, 0, SEEK_END); len = ftell(f); if(fclose(f) != 0) return errno; if(len < 0) return errno; if(len == 8) { ret = read_master_krb4(context, filename, mkey); } else if(buf[0] == 0x30 && len <= 127 && buf[1] == len - 2) { ret = read_master_encryptionkey(context, filename, mkey); } else if(buf[0] == 5 && buf[1] >= 1 && buf[1] <= 2) { ret = read_master_keytab(context, filename, mkey); } else { /* * Check both LittleEndian and BigEndian since they key file * might be moved from a machine with diffrent byte order, or * its running on MacOS X that always uses BE master keys. */ ret = read_master_mit(context, filename, KRB5_STORAGE_BYTEORDER_LE, mkey); if (ret) ret = read_master_mit(context, filename, KRB5_STORAGE_BYTEORDER_BE, mkey); } return ret; } krb5_error_code hdb_write_master_key(krb5_context context, const char *filename, hdb_master_key mkey) { krb5_error_code ret; hdb_master_key p; krb5_keytab kt; if(filename == NULL) filename = HDB_DB_DIR "/m-key"; ret = krb5_kt_resolve(context, filename, &kt); if(ret) return ret; for(p = mkey; p; p = p->next) { ret = krb5_kt_add_entry(context, kt, &p->keytab); } krb5_kt_close(context, kt); return ret; } krb5_error_code _hdb_set_master_key_usage(krb5_context context, HDB *db, unsigned int key_usage) { if (db->hdb_master_key_set == 0) return HDB_ERR_NO_MKEY; db->hdb_master_key->key_usage = key_usage; return 0; } hdb_master_key _hdb_find_master_key(unsigned int *mkvno, hdb_master_key mkey) { hdb_master_key ret = NULL; while(mkey) { if(ret == NULL && mkey->keytab.vno == 0) ret = mkey; if(mkvno == NULL) { if(ret == NULL || mkey->keytab.vno > ret->keytab.vno) ret = mkey; } else if((uint32_t)mkey->keytab.vno == *mkvno) return mkey; mkey = mkey->next; } return ret; } int _hdb_mkey_version(hdb_master_key mkey) { return mkey->keytab.vno; } int _hdb_mkey_decrypt(krb5_context context, hdb_master_key key, krb5_key_usage usage, void *ptr, size_t size, krb5_data *res) { return krb5_decrypt(context, key->crypto, usage, ptr, size, res); } int _hdb_mkey_encrypt(krb5_context context, hdb_master_key key, krb5_key_usage usage, const void *ptr, size_t size, krb5_data *res) { return krb5_encrypt(context, key->crypto, usage, ptr, size, res); } krb5_error_code hdb_unseal_key_mkey(krb5_context context, Key *k, hdb_master_key mkey) { krb5_error_code ret; krb5_data res; size_t keysize; hdb_master_key key; if(k->mkvno == NULL) return 0; key = _hdb_find_master_key(k->mkvno, mkey); if (key == NULL) return HDB_ERR_NO_MKEY; ret = _hdb_mkey_decrypt(context, key, HDB_KU_MKEY, k->key.keyvalue.data, k->key.keyvalue.length, &res); if(ret == KRB5KRB_AP_ERR_BAD_INTEGRITY) { /* try to decrypt with MIT key usage */ ret = _hdb_mkey_decrypt(context, key, 0, k->key.keyvalue.data, k->key.keyvalue.length, &res); } if (ret) return ret; /* fixup keylength if the key got padded when encrypting it */ ret = krb5_enctype_keysize(context, k->key.keytype, &keysize); if (ret) { krb5_data_free(&res); return ret; } if (keysize > res.length) { krb5_data_free(&res); return KRB5_BAD_KEYSIZE; } memset(k->key.keyvalue.data, 0, k->key.keyvalue.length); free(k->key.keyvalue.data); k->key.keyvalue = res; k->key.keyvalue.length = keysize; free(k->mkvno); k->mkvno = NULL; return 0; } krb5_error_code hdb_unseal_keys_mkey(krb5_context context, hdb_entry *ent, hdb_master_key mkey) { size_t i; for(i = 0; i < ent->keys.len; i++){ krb5_error_code ret; ret = hdb_unseal_key_mkey(context, &ent->keys.val[i], mkey); if (ret) return ret; } return 0; } krb5_error_code hdb_unseal_keys(krb5_context context, HDB *db, hdb_entry *ent) { if (db->hdb_master_key_set == 0) return 0; return hdb_unseal_keys_mkey(context, ent, db->hdb_master_key); } /* * Unseal the keys for the given kvno (or all of them) of entry. * * If kvno == 0 -> unseal all. * if kvno != 0 -> unseal the requested kvno and make sure it's the one listed * as the current keyset for the entry (swapping it with a * historical keyset if need be). */ krb5_error_code hdb_unseal_keys_kvno(krb5_context context, HDB *db, krb5_kvno kvno, unsigned flags, hdb_entry *ent) { krb5_error_code ret = HDB_ERR_NOENTRY; HDB_extension *ext; HDB_Ext_KeySet *hist_keys; Key *tmp_val; time_t tmp_set_time; unsigned int tmp_len; unsigned int kvno_diff = 0; krb5_kvno tmp_kvno; size_t i, k; int exclude_dead = 0; KerberosTime now = 0; if (kvno == 0) ret = 0; if ((flags & HDB_F_LIVE_CLNT_KVNOS) || (flags & HDB_F_LIVE_SVC_KVNOS)) { exclude_dead = 1; now = time(NULL); if (HDB_F_LIVE_CLNT_KVNOS) kvno_diff = hdb_entry_get_kvno_diff_clnt(ent); else kvno_diff = hdb_entry_get_kvno_diff_svc(ent); } ext = hdb_find_extension(ent, choice_HDB_extension_data_hist_keys); if (ext == NULL || (&ext->data.u.hist_keys)->len == 0) return hdb_unseal_keys_mkey(context, ent, db->hdb_master_key); /* For swapping; see below */ tmp_len = ent->keys.len; tmp_val = ent->keys.val; tmp_kvno = ent->kvno; (void) hdb_entry_get_pw_change_time(ent, &tmp_set_time); hist_keys = &ext->data.u.hist_keys; for (i = 0; i < hist_keys->len; i++) { if (kvno != 0 && hist_keys->val[i].kvno != kvno) continue; if (exclude_dead && ((ent->max_life != NULL && hist_keys->val[i].set_time != NULL && (*hist_keys->val[i].set_time) < (now - (*ent->max_life))) || (hist_keys->val[i].kvno < kvno && (kvno - hist_keys->val[i].kvno) > kvno_diff))) /* * The KDC may want to to check for this keyset's set_time * is within the TGS principal's max_life, say. But we stop * here. */ continue; /* Either the keys we want, or all the keys */ for (k = 0; k < hist_keys->val[i].keys.len; k++) { ret = hdb_unseal_key_mkey(context, &hist_keys->val[i].keys.val[k], db->hdb_master_key); /* * If kvno == 0 we might not want to bail here! E.g., if we * no longer have the right master key, so just ignore this. * * We could filter out keys that we can't decrypt here * because of HDB_ERR_NO_MKEY. However, it seems safest to * filter them out only where necessary, say, in kadm5. */ if (ret && kvno != 0) return ret; if (ret && ret != HDB_ERR_NO_MKEY) return (ret); } if (kvno == 0) continue; /* * What follows is a bit of a hack. * * This is the keyset we're being asked for, but it's not the * current keyset. So we add the current keyset to the history, * leave the one we were asked for in the history, and pretend * the one we were asked for is also the current keyset. * * This is a bit of a defensive hack in case an entry fetched * this way ever gets modified then stored: if the keyset is not * changed we can detect this and put things back, else we won't * drop any keysets from history by accident. * * Note too that we only ever get called with a non-zero kvno * either in the KDC or in cases where we aren't changing the * HDB entry anyways, which is why this is just a defensive * hack. We also don't fetch specific kvnos in the dump case, * so there's no danger that we'll dump this entry and load it * again, repeatedly causing the history to grow boundelessly. */ /* Swap key sets */ ent->kvno = hist_keys->val[i].kvno; ent->keys.val = hist_keys->val[i].keys.val; ent->keys.len = hist_keys->val[i].keys.len; if (hist_keys->val[i].set_time != NULL) /* Sloppy, but the callers we expect won't care */ (void) hdb_entry_set_pw_change_time(context, ent, *hist_keys->val[i].set_time); hist_keys->val[i].kvno = tmp_kvno; hist_keys->val[i].keys.val = tmp_val; hist_keys->val[i].keys.len = tmp_len; if (hist_keys->val[i].set_time != NULL) /* Sloppy, but the callers we expect won't care */ *hist_keys->val[i].set_time = tmp_set_time; return 0; } return (ret); } krb5_error_code hdb_unseal_key(krb5_context context, HDB *db, Key *k) { if (db->hdb_master_key_set == 0) return 0; return hdb_unseal_key_mkey(context, k, db->hdb_master_key); } krb5_error_code hdb_seal_key_mkey(krb5_context context, Key *k, hdb_master_key mkey) { krb5_error_code ret; krb5_data res; hdb_master_key key; if(k->mkvno != NULL) return 0; key = _hdb_find_master_key(k->mkvno, mkey); if (key == NULL) return HDB_ERR_NO_MKEY; ret = _hdb_mkey_encrypt(context, key, HDB_KU_MKEY, k->key.keyvalue.data, k->key.keyvalue.length, &res); if (ret) return ret; memset(k->key.keyvalue.data, 0, k->key.keyvalue.length); free(k->key.keyvalue.data); k->key.keyvalue = res; if (k->mkvno == NULL) { k->mkvno = malloc(sizeof(*k->mkvno)); if (k->mkvno == NULL) return ENOMEM; } *k->mkvno = key->keytab.vno; return 0; } krb5_error_code hdb_seal_keys_mkey(krb5_context context, hdb_entry *ent, hdb_master_key mkey) { HDB_extension *ext; HDB_Ext_KeySet *hist_keys; size_t i, k; krb5_error_code ret; for(i = 0; i < ent->keys.len; i++){ ret = hdb_seal_key_mkey(context, &ent->keys.val[i], mkey); if (ret) return ret; } ext = hdb_find_extension(ent, choice_HDB_extension_data_hist_keys); if (ext == NULL) return 0; hist_keys = &ext->data.u.hist_keys; for (i = 0; i < hist_keys->len; i++) { for (k = 0; k < hist_keys->val[i].keys.len; k++) { ret = hdb_seal_key_mkey(context, &hist_keys->val[i].keys.val[k], mkey); if (ret) return ret; } } return 0; } krb5_error_code hdb_seal_keys(krb5_context context, HDB *db, hdb_entry *ent) { if (db->hdb_master_key_set == 0) return 0; return hdb_seal_keys_mkey(context, ent, db->hdb_master_key); } krb5_error_code hdb_seal_key(krb5_context context, HDB *db, Key *k) { if (db->hdb_master_key_set == 0) return 0; return hdb_seal_key_mkey(context, k, db->hdb_master_key); } krb5_error_code hdb_set_master_key(krb5_context context, HDB *db, krb5_keyblock *key) { krb5_error_code ret; hdb_master_key mkey; ret = hdb_process_master_key(context, 0, key, 0, &mkey); if (ret) return ret; db->hdb_master_key = mkey; #if 0 /* XXX - why? */ des_set_random_generator_seed(key.keyvalue.data); #endif db->hdb_master_key_set = 1; db->hdb_master_key->key_usage = HDB_KU_MKEY; return 0; } krb5_error_code hdb_set_master_keyfile (krb5_context context, HDB *db, const char *keyfile) { hdb_master_key key; krb5_error_code ret; ret = hdb_read_master_key(context, keyfile, &key); if (ret) { if (ret != ENOENT) return ret; krb5_clear_error_message(context); return 0; } db->hdb_master_key = key; db->hdb_master_key_set = 1; return ret; } krb5_error_code hdb_clear_master_key (krb5_context context, HDB *db) { if (db->hdb_master_key_set) { hdb_free_master_key(context, db->hdb_master_key); db->hdb_master_key_set = 0; } return 0; } heimdal-7.5.0/lib/hdb/data-mkey.mit.des3.le0000644000175000017500000000003612136107747016407 0ustar niknik heimdal-7.5.0/lib/hdb/print.c0000644000175000017500000004352313026237312014063 0ustar niknik/* * Copyright (c) 1999-2005 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of KTH nor the names of its contributors may be * used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY KTH AND ITS CONTRIBUTORS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL KTH OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "hdb_locl.h" #include #include /* This is the present contents of a dump line. This might change at any time. Fields are separated by white space. principal keyblock kvno keys... mkvno enctype keyvalue salt (- means use normal salt) creation date and principal modification date and principal principal valid from date (not used) principal valid end date (not used) principal key expires (not used) max ticket life max renewable life flags generation number */ /* * These utility functions return the number of bytes written or -1, and * they set an error in the context. */ static ssize_t append_string(krb5_context context, krb5_storage *sp, const char *fmt, ...) { ssize_t sz; char *s; int rc; va_list ap; va_start(ap, fmt); rc = vasprintf(&s, fmt, ap); va_end(ap); if(rc < 0) { krb5_set_error_message(context, ENOMEM, "malloc: out of memory"); return -1; } sz = krb5_storage_write(sp, s, strlen(s)); free(s); return sz; } static krb5_error_code append_hex(krb5_context context, krb5_storage *sp, int always_encode, int lower, krb5_data *data) { ssize_t sz; int printable = 1; size_t i; char *p; p = data->data; if (!always_encode) { for (i = 0; i < data->length; i++) { if (!isalnum((unsigned char)p[i]) && p[i] != '.'){ printable = 0; break; } } } if (printable && !always_encode) return append_string(context, sp, "\"%.*s\"", data->length, data->data); sz = hex_encode(data->data, data->length, &p); if (sz == -1) return sz; if (lower) strlwr(p); sz = append_string(context, sp, "%s", p); free(p); return sz; } static char * time2str(time_t t) { static char buf[128]; strftime(buf, sizeof(buf), "%Y%m%d%H%M%S", gmtime(&t)); return buf; } static ssize_t append_event(krb5_context context, krb5_storage *sp, Event *ev) { krb5_error_code ret; ssize_t sz; char *pr = NULL; if(ev == NULL) return append_string(context, sp, "- "); if (ev->principal != NULL) { ret = krb5_unparse_name(context, ev->principal, &pr); if (ret) return -1; /* krb5_unparse_name() sets error info */ } sz = append_string(context, sp, "%s:%s ", time2str(ev->time), pr ? pr : "UNKNOWN"); free(pr); return sz; } #define KRB5_KDB_SALTTYPE_NORMAL 0 #define KRB5_KDB_SALTTYPE_V4 1 #define KRB5_KDB_SALTTYPE_NOREALM 2 #define KRB5_KDB_SALTTYPE_ONLYREALM 3 #define KRB5_KDB_SALTTYPE_SPECIAL 4 #define KRB5_KDB_SALTTYPE_AFS3 5 static ssize_t append_mit_key(krb5_context context, krb5_storage *sp, krb5_const_principal princ, unsigned int kvno, Key *key) { krb5_error_code ret; krb5_salt k5salt; ssize_t sz; size_t key_versions = key->salt ? 2 : 1; size_t decrypted_key_length; char buf[2]; krb5_data keylenbytes; unsigned int salttype; sz = append_string(context, sp, "\t%u\t%u\t%d\t%d\t", key_versions, kvno, key->key.keytype, key->key.keyvalue.length + 2); if (sz == -1) return sz; ret = krb5_enctype_keysize(context, key->key.keytype, &decrypted_key_length); if (ret) return -1; /* XXX we lose the error code */ buf[0] = decrypted_key_length & 0xff; buf[1] = (decrypted_key_length & 0xff00) >> 8; keylenbytes.data = buf; keylenbytes.length = sizeof (buf); sz = append_hex(context, sp, 1, 1, &keylenbytes); if (sz == -1) return sz; sz = append_hex(context, sp, 1, 1, &key->key.keyvalue); if (!key->salt) return sz; /* Map salt to MIT KDB style */ switch (key->salt->type) { case KRB5_PADATA_PW_SALT: /* * Compute normal salt and then see whether it matches the stored one */ ret = krb5_get_pw_salt(context, princ, &k5salt); if (ret) return -1; if (k5salt.saltvalue.length == key->salt->salt.length && memcmp(k5salt.saltvalue.data, key->salt->salt.data, k5salt.saltvalue.length) == 0) salttype = KRB5_KDB_SALTTYPE_NORMAL; /* matches */ else if (key->salt->salt.length == strlen(princ->realm) && memcmp(key->salt->salt.data, princ->realm, key->salt->salt.length) == 0) salttype = KRB5_KDB_SALTTYPE_ONLYREALM; /* matches realm */ else if (key->salt->salt.length == k5salt.saltvalue.length - strlen(princ->realm) && memcmp((char *)k5salt.saltvalue.data + strlen(princ->realm), key->salt->salt.data, key->salt->salt.length) == 0) salttype = KRB5_KDB_SALTTYPE_NOREALM; /* matches w/o realm */ else salttype = KRB5_KDB_SALTTYPE_NORMAL; /* hope for best */ break; case KRB5_PADATA_AFS3_SALT: salttype = KRB5_KDB_SALTTYPE_AFS3; break; default: return -1; } sz = append_string(context, sp, "\t%u\t%u\t", salttype, key->salt->salt.length); if (sz == -1) return sz; return append_hex(context, sp, 1, 1, &key->salt->salt); } static krb5_error_code entry2string_int (krb5_context context, krb5_storage *sp, hdb_entry *ent) { char *p; size_t i; krb5_error_code ret; /* --- principal */ ret = krb5_unparse_name(context, ent->principal, &p); if(ret) return ret; append_string(context, sp, "%s ", p); free(p); /* --- kvno */ append_string(context, sp, "%d", ent->kvno); /* --- keys */ for(i = 0; i < ent->keys.len; i++){ /* --- mkvno, keytype */ if(ent->keys.val[i].mkvno) append_string(context, sp, ":%d:%d:", *ent->keys.val[i].mkvno, ent->keys.val[i].key.keytype); else append_string(context, sp, "::%d:", ent->keys.val[i].key.keytype); /* --- keydata */ append_hex(context, sp, 0, 0, &ent->keys.val[i].key.keyvalue); append_string(context, sp, ":"); /* --- salt */ if(ent->keys.val[i].salt){ append_string(context, sp, "%u/", ent->keys.val[i].salt->type); append_hex(context, sp, 0, 0, &ent->keys.val[i].salt->salt); }else append_string(context, sp, "-"); } append_string(context, sp, " "); /* --- created by */ append_event(context, sp, &ent->created_by); /* --- modified by */ append_event(context, sp, ent->modified_by); /* --- valid start */ if(ent->valid_start) append_string(context, sp, "%s ", time2str(*ent->valid_start)); else append_string(context, sp, "- "); /* --- valid end */ if(ent->valid_end) append_string(context, sp, "%s ", time2str(*ent->valid_end)); else append_string(context, sp, "- "); /* --- password ends */ if(ent->pw_end) append_string(context, sp, "%s ", time2str(*ent->pw_end)); else append_string(context, sp, "- "); /* --- max life */ if(ent->max_life) append_string(context, sp, "%d ", *ent->max_life); else append_string(context, sp, "- "); /* --- max renewable life */ if(ent->max_renew) append_string(context, sp, "%d ", *ent->max_renew); else append_string(context, sp, "- "); /* --- flags */ append_string(context, sp, "%d ", HDBFlags2int(ent->flags)); /* --- generation number */ if(ent->generation) { append_string(context, sp, "%s:%d:%d ", time2str(ent->generation->time), ent->generation->usec, ent->generation->gen); } else append_string(context, sp, "- "); /* --- extensions */ if(ent->extensions && ent->extensions->len > 0) { for(i = 0; i < ent->extensions->len; i++) { void *d; size_t size, sz = 0; ASN1_MALLOC_ENCODE(HDB_extension, d, size, &ent->extensions->val[i], &sz, ret); if (ret) { krb5_clear_error_message(context); return ret; } if(size != sz) krb5_abortx(context, "internal asn.1 encoder error"); if (hex_encode(d, size, &p) < 0) { free(d); krb5_set_error_message(context, ENOMEM, "malloc: out of memory"); return ENOMEM; } free(d); append_string(context, sp, "%s%s", p, ent->extensions->len - 1 != i ? ":" : ""); free(p); } } else append_string(context, sp, "-"); return 0; } #define KRB5_KDB_DISALLOW_POSTDATED 0x00000001 #define KRB5_KDB_DISALLOW_FORWARDABLE 0x00000002 #define KRB5_KDB_DISALLOW_TGT_BASED 0x00000004 #define KRB5_KDB_DISALLOW_RENEWABLE 0x00000008 #define KRB5_KDB_DISALLOW_PROXIABLE 0x00000010 #define KRB5_KDB_DISALLOW_DUP_SKEY 0x00000020 #define KRB5_KDB_DISALLOW_ALL_TIX 0x00000040 #define KRB5_KDB_REQUIRES_PRE_AUTH 0x00000080 #define KRB5_KDB_REQUIRES_HW_AUTH 0x00000100 #define KRB5_KDB_REQUIRES_PWCHANGE 0x00000200 #define KRB5_KDB_DISALLOW_SVR 0x00001000 #define KRB5_KDB_PWCHANGE_SERVICE 0x00002000 #define KRB5_KDB_SUPPORT_DESMD5 0x00004000 #define KRB5_KDB_NEW_PRINC 0x00008000 static int flags_to_attr(HDBFlags flags) { int a = 0; if (!flags.postdate) a |= KRB5_KDB_DISALLOW_POSTDATED; if (!flags.forwardable) a |= KRB5_KDB_DISALLOW_FORWARDABLE; if (flags.initial) a |= KRB5_KDB_DISALLOW_TGT_BASED; if (!flags.renewable) a |= KRB5_KDB_DISALLOW_RENEWABLE; if (!flags.proxiable) a |= KRB5_KDB_DISALLOW_PROXIABLE; if (flags.invalid) a |= KRB5_KDB_DISALLOW_ALL_TIX; if (flags.require_preauth) a |= KRB5_KDB_REQUIRES_PRE_AUTH; if (flags.require_hwauth) a |= KRB5_KDB_REQUIRES_HW_AUTH; if (!flags.server) a |= KRB5_KDB_DISALLOW_SVR; if (flags.change_pw) a |= KRB5_KDB_PWCHANGE_SERVICE; return a; } krb5_error_code entry2mit_string_int(krb5_context context, krb5_storage *sp, hdb_entry *ent) { krb5_error_code ret; ssize_t sz; size_t i, k; size_t num_tl_data = 0; size_t num_key_data = 0; char *p; HDB_Ext_KeySet *hist_keys = NULL; HDB_extension *extp; time_t last_pw_chg = 0; time_t exp = 0; time_t pwexp = 0; unsigned int max_life = 0; unsigned int max_renew = 0; if (ent->modified_by) num_tl_data++; ret = hdb_entry_get_pw_change_time(ent, &last_pw_chg); if (ret) return ret; if (last_pw_chg) num_tl_data++; extp = hdb_find_extension(ent, choice_HDB_extension_data_hist_keys); if (extp) hist_keys = &extp->data.u.hist_keys; for (i = 0; i < ent->keys.len;i++) { if (ent->keys.val[i].key.keytype == ETYPE_DES_CBC_MD4 || ent->keys.val[i].key.keytype == ETYPE_DES_CBC_MD5) continue; num_key_data++; } if (hist_keys) { for (i = 0; i < hist_keys->len; i++) { /* * MIT uses the highest kvno as the current kvno instead of * tracking kvno separately, so we can't dump keysets with kvno * higher than the entry's kvno. */ if (hist_keys->val[i].kvno >= ent->kvno) continue; for (k = 0; k < hist_keys->val[i].keys.len; k++) { if (ent->keys.val[k].key.keytype == ETYPE_DES_CBC_MD4 || ent->keys.val[k].key.keytype == ETYPE_DES_CBC_MD5) continue; num_key_data++; } } } ret = krb5_unparse_name(context, ent->principal, &p); if (ret) return ret; sz = append_string(context, sp, "princ\t38\t%u\t%u\t%u\t0\t%s\t%d", strlen(p), num_tl_data, num_key_data, p, flags_to_attr(ent->flags)); free(p); if (sz == -1) return ENOMEM; if (ent->max_life) max_life = *ent->max_life; if (ent->max_renew) max_renew = *ent->max_renew; if (ent->valid_end) exp = *ent->valid_end; if (ent->pw_end) pwexp = *ent->pw_end; sz = append_string(context, sp, "\t%u\t%u\t%u\t%u\t0\t0\t0", max_life, max_renew, exp, pwexp); if (sz == -1) return ENOMEM; /* Dump TL data we know: last pw chg and modified_by */ #define mit_KRB5_TL_LAST_PWD_CHANGE 1 #define mit_KRB5_TL_MOD_PRINC 2 if (last_pw_chg) { krb5_data d; time_t val; unsigned char *ptr; ptr = (unsigned char *)&last_pw_chg; val = ptr[0] | (ptr[1] << 8) | (ptr[2] << 16) | (ptr[3] << 24); d.data = &val; d.length = sizeof (last_pw_chg); sz = append_string(context, sp, "\t%u\t%u\t", mit_KRB5_TL_LAST_PWD_CHANGE, d.length); if (sz == -1) return ENOMEM; sz = append_hex(context, sp, 1, 1, &d); if (sz == -1) return ENOMEM; } if (ent->modified_by) { krb5_data d; unsigned int val; size_t plen; unsigned char *ptr; char *modby_p; ptr = (unsigned char *)&ent->modified_by->time; val = ptr[0] | (ptr[1] << 8) | (ptr[2] << 16) | (ptr[3] << 24); d.data = &val; d.length = sizeof (ent->modified_by->time); ret = krb5_unparse_name(context, ent->modified_by->principal, &modby_p); if (ret) return ret; plen = strlen(modby_p); sz = append_string(context, sp, "\t%u\t%u\t", mit_KRB5_TL_MOD_PRINC, d.length + plen + 1 /* NULL counted */); if (sz == -1) return ENOMEM; sz = append_hex(context, sp, 1, 1, &d); if (sz == -1) { free(modby_p); return ENOMEM; } d.data = modby_p; d.length = plen + 1; sz = append_hex(context, sp, 1, 1, &d); free(modby_p); if (sz == -1) return ENOMEM; } /* * Dump keys (remembering to not include any with kvno higher than * the entry's because MIT doesn't track entry kvno separately from * the entry's keys -- max kvno is it) */ for (i = 0; i < ent->keys.len; i++) { if (ent->keys.val[i].key.keytype == ETYPE_DES_CBC_MD4 || ent->keys.val[i].key.keytype == ETYPE_DES_CBC_MD5) continue; sz = append_mit_key(context, sp, ent->principal, ent->kvno, &ent->keys.val[i]); if (sz == -1) return ENOMEM; } for (i = 0; hist_keys && i < ent->kvno; i++) { size_t m; /* dump historical keys */ for (k = 0; k < hist_keys->len; k++) { if (hist_keys->val[k].kvno != ent->kvno - i) continue; for (m = 0; m < hist_keys->val[k].keys.len; m++) { if (ent->keys.val[k].key.keytype == ETYPE_DES_CBC_MD4 || ent->keys.val[k].key.keytype == ETYPE_DES_CBC_MD5) continue; sz = append_mit_key(context, sp, ent->principal, hist_keys->val[k].kvno, &hist_keys->val[k].keys.val[m]); if (sz == -1) return ENOMEM; } } } sz = append_string(context, sp, "\t-1;"); /* "extra data" */ if (sz == -1) return ENOMEM; return 0; } krb5_error_code hdb_entry2string(krb5_context context, hdb_entry *ent, char **str) { krb5_error_code ret; krb5_data data; krb5_storage *sp; sp = krb5_storage_emem(); if (sp == NULL) { krb5_set_error_message(context, ENOMEM, "malloc: out of memory"); return ENOMEM; } ret = entry2string_int(context, sp, ent); if (ret) { krb5_storage_free(sp); return ret; } krb5_storage_write(sp, "\0", 1); krb5_storage_to_data(sp, &data); krb5_storage_free(sp); *str = data.data; return 0; } /* print a hdb_entry to (FILE*)data; suitable for hdb_foreach */ krb5_error_code hdb_print_entry(krb5_context context, HDB *db, hdb_entry_ex *entry, void *data) { struct hdb_print_entry_arg *parg = data; krb5_error_code ret; krb5_storage *sp; fflush(parg->out); sp = krb5_storage_from_fd(fileno(parg->out)); if (sp == NULL) { krb5_set_error_message(context, ENOMEM, "malloc: out of memory"); return ENOMEM; } switch (parg->fmt) { case HDB_DUMP_HEIMDAL: ret = entry2string_int(context, sp, &entry->entry); break; case HDB_DUMP_MIT: ret = entry2mit_string_int(context, sp, &entry->entry); break; default: heim_abort("Only two dump formats supported: Heimdal and MIT"); } if (ret) { krb5_storage_free(sp); return ret; } krb5_storage_write(sp, "\n", 1); krb5_storage_free(sp); return 0; } heimdal-7.5.0/lib/hdb/NTMakefile0000644000175000017500000001124413026237312014460 0ustar niknik######################################################################## # # Copyright (c) 2009, Secure Endpoints Inc. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # - Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # # - Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in # the documentation and/or other materials provided with the # distribution. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS # FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE # COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, # BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN # ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. # RELDIR=lib\hdb !include ../../windows/NTMakefile.w32 gen_files_hdb = $(OBJ)\asn1_hdb_asn1.x $(gen_files_hdb) $(OBJ)\hdb_asn1.hx $(OBJ)\hdb_asn1-priv.hx: $(BINDIR)\asn1_compile.exe hdb.asn1 cd $(OBJ) $(BINDIR)\asn1_compile.exe --sequence=HDB-Ext-KeySet --sequence=Keys --one-code-file $(SRCDIR)\hdb.asn1 hdb_asn1 cd $(SRCDIR) $(gen_files_hdb:.x=.c): $$(@R).x !ifdef OPENLDAP_MODULE ldap_dll = $(BINDIR)\hdb_ldap.dll ldap_lib = $(LIBDIR)\hdb_ldap.lib ldap_objs = $(OBJ)\hdb-ldap.obj $(ldap_dll): $(ldap_objs) $(DLLGUILINK) -implib:$(ldap_lib) $(DLLPREP) clean:: -$(RM) $(ldap_dll) -$(RM) $(ldap_lib) !else ldap = $(OBJ)\hdb-ldap.obj ldap_c = hdb-ldap.c !endif dist_libhdb_la_SOURCES = \ common.c \ db.c \ db3.c \ ext.c \ $(ldap_c) \ hdb.c \ hdb-sqlite.c \ hdb-keytab.c \ hdb-mitdb.c \ hdb-mdb.c \ hdb_locl.h \ keys.c \ keytab.c \ dbinfo.c \ mkey.c \ ndbm.c \ print.c libhdb_OBJs = \ $(OBJ)\common.obj \ $(OBJ)\db.obj \ $(OBJ)\db3.obj \ $(OBJ)\ext.obj \ $(ldap) \ $(OBJ)\hdb.obj \ $(OBJ)\hdb-sqlite.obj \ $(OBJ)\hdb-keytab.obj \ $(OBJ)\hdb-mitdb.obj \ $(OBJ)\keys.obj \ $(OBJ)\keytab.obj \ $(OBJ)\dbinfo.obj \ $(OBJ)\mkey.obj \ $(OBJ)\ndbm.obj \ $(OBJ)\print.obj \ $(gen_files_hdb:.x=.obj) \ $(OBJ)\hdb_err.obj $(OBJ)\hdb_err.c $(OBJ)\hdb_err.h: hdb_err.et cd $(OBJ) $(BINDIR)\compile_et.exe $(SRCDIR)\hdb_err.et cd $(SRCDIR) $(OBJ)\hdb-protos.h: $(dist_libhdb_la_SOURCES) $(PERL) ../../cf/make-proto.pl -q -P remove -o $@ $(dist_libhdb_la_SOURCES) \ || $(RM) $@ $(OBJ)\hdb-private.h: $(dist_libhdb_la_SOURCES) $(PERL) ../../cf/make-proto.pl -q -P remote -p $@ $(dist_libhdb_la_SOURCES) \ || $(RM) $@ INCFILES= \ $(INCDIR)\hdb.h \ $(INCDIR)\hdb-protos.h \ $(OBJ)\hdb-private.h \ $(INCDIR)\hdb_err.h \ $(INCDIR)\hdb_asn1.h \ $(INCDIR)\hdb_asn1-priv.h !ifndef STATICLIBS RES=$(OBJ)\libhdb-version.res $(LIBHDB): $(BINDIR)\libhdb.dll $(BINDIR)\libhdb.dll: $(libhdb_OBJs) $(ldap_lib) $(LIBHEIMBASE) $(LIBHEIMDAL) $(LIBSQLITE) $(LIBCOMERR) $(LIBROKEN) $(RES) $(DLLGUILINK) -def:libhdb-exports.def -implib:$(LIBHDB) $(DLLPREP_NODIST) clean:: -$(RM) $(BINDIR)\libhdb.* !else $(LIBHDB): $(libhdb_OBJs) $(ldap_lib) $(LIBCON) !endif all:: $(INCFILES) $(LIBHDB) clean:: -$(RM) $(INCFILES) -$(RM) $(LIBHDB) test:: test-binaries test-run test-binaries: $(OBJ)\test_dbinfo.exe $(OBJ)\test_hdbkeys.exe $(OBJ)\test_hdbplugin.exe $(OBJ)\test_dbinfo.exe: $(OBJ)\test_dbinfo.obj $(LIBHDB) $(LIBHEIMDAL) $(LIBROKEN) $(LIBVERS) $(EXECONLINK) $(EXEPREP_NODIST) $(OBJ)\test_hdbkeys.exe: $(OBJ)\test_hdbkeys.obj $(LIBHDB) $(LIBHEIMDAL) $(LIBROKEN) $(LIBVERS) $(EXECONLINK) $(EXEPREP_NODIST) $(OBJ)\test_hdbplugin.exe: $(OBJ)\test_hdbplugin.obj $(LIBHDB) $(LIBHEIMDAL) $(LIBROKEN) $(LIBVERS) $(EXECONLINK) $(EXEPREP_NODIST) test-run: cd $(OBJ) -test_dbinfo.exe -test_hdbkeys.exe -test_hdbplugin.exe cd $(SRCDIR) !ifdef OPENLDAP_INC openldap_inc_flag=-I$(OPENLDAP_INC) !else openldap_inc_flag= !endif hdb_cflags=$(openldap_inc_flag) -I$(OBJ) {}.c{$(OBJ)}.obj:: $(C2OBJ_P) $(hdb_cflags) -DASN1_LIB {$(OBJ)}.c{$(OBJ)}.obj:: $(C2OBJ_P) $(hdb_cflags) test-exports: $(PERL) ..\..\cf\w32-check-exported-symbols.pl --vs version-script.map --def libhdb-exports.def test:: test-exports heimdal-7.5.0/lib/hdb/test_hdbkeys.c0000644000175000017500000000737713062055136015430 0ustar niknik/* * Copyright (c) 2005 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "hdb_locl.h" #include #include static int help_flag; static int version_flag; static int kvno_integer = 1; struct getargs args[] = { { "kvno", 'd', arg_integer, &kvno_integer, NULL, NULL }, { "help", 'h', arg_flag, &help_flag, NULL, NULL }, { "version", 0, arg_flag, &version_flag, NULL, NULL } }; static int num_args = sizeof(args) / sizeof(args[0]); int main(int argc, char **argv) { krb5_principal principal; krb5_context context; char *principal_str, *password_str, *str; int ret, o = 0; hdb_keyset keyset; size_t length, len; void *data; setprogname(argv[0]); if(getarg(args, num_args, argc, argv, &o)) krb5_std_usage(1, args, num_args); if(help_flag) krb5_std_usage(0, args, num_args); if(version_flag){ print_version(NULL); exit(0); } ret = krb5_init_context(&context); if (ret) errx (1, "krb5_init_context failed: %d", ret); if (argc != 3) errx(1, "username and password missing"); principal_str = argv[1]; password_str = argv[2]; ret = krb5_parse_name (context, principal_str, &principal); if (ret) krb5_err (context, 1, ret, "krb5_parse_name %s", principal_str); memset(&keyset, 0, sizeof(keyset)); keyset.kvno = kvno_integer; keyset.set_time = malloc(sizeof (*keyset.set_time)); if (keyset.set_time == NULL) errx(1, "couldn't allocate set_time field of keyset"); *keyset.set_time = time(NULL); ret = hdb_generate_key_set_password(context, principal, password_str, &keyset.keys.val, &len); if (ret) krb5_err(context, 1, ret, "hdb_generate_key_set_password"); keyset.keys.len = len; if (keyset.keys.len == 0) krb5_errx (context, 1, "hdb_generate_key_set_password length 0"); krb5_free_principal (context, principal); ASN1_MALLOC_ENCODE(hdb_keyset, data, length, &keyset, &len, ret); if (ret) krb5_errx(context, 1, "encode keyset"); if (len != length) krb5_abortx(context, "foo"); krb5_free_context(context); ret = rk_base64_encode(data, length, &str); if (ret < 0) errx(1, "base64_encode"); printf("keyset: %s\n", str); free(data); return 0; } heimdal-7.5.0/lib/hdb/hdb-sqlite.c0000644000175000017500000007374013212137553014772 0ustar niknik/* * Copyright (c) 2009 Kungliga Tekniska Hgskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "hdb_locl.h" #include "sqlite3.h" #define MAX_RETRIES 10 typedef struct hdb_sqlite_db { double version; sqlite3 *db; char *db_file; sqlite3_stmt *get_version; sqlite3_stmt *fetch; sqlite3_stmt *get_ids; sqlite3_stmt *add_entry; sqlite3_stmt *add_principal; sqlite3_stmt *add_alias; sqlite3_stmt *delete_aliases; sqlite3_stmt *update_entry; sqlite3_stmt *remove; sqlite3_stmt *get_all_entries; } hdb_sqlite_db; /* This should be used to mark updates which make the code incompatible * with databases created with previous versions. Don't update it if * compatibility is not broken. */ #define HDBSQLITE_VERSION 0.1 #define _HDBSQLITE_STRINGIFY(x) #x #define HDBSQLITE_STRINGIFY(x) _HDBSQLITE_STRINGIFY(x) #define HDBSQLITE_CREATE_TABLES \ " BEGIN TRANSACTION;" \ " CREATE TABLE Version (number REAL);" \ " INSERT INTO Version (number)" \ " VALUES (" HDBSQLITE_STRINGIFY(HDBSQLITE_VERSION) ");" \ " CREATE TABLE Principal" \ " (id INTEGER PRIMARY KEY," \ " principal TEXT UNIQUE NOT NULL," \ " canonical INTEGER," \ " entry INTEGER);" \ " CREATE TABLE Entry" \ " (id INTEGER PRIMARY KEY," \ " data BLOB);" \ " COMMIT" #define HDBSQLITE_CREATE_TRIGGERS \ " CREATE TRIGGER remove_principals AFTER DELETE ON Entry" \ " BEGIN" \ " DELETE FROM Principal" \ " WHERE entry = OLD.id;" \ " END" #define HDBSQLITE_GET_VERSION \ " SELECT number FROM Version" #define HDBSQLITE_FETCH \ " SELECT Entry.data FROM Principal, Entry" \ " WHERE Principal.principal = ? AND" \ " Entry.id = Principal.entry" #define HDBSQLITE_GET_IDS \ " SELECT id, entry FROM Principal" \ " WHERE principal = ?" #define HDBSQLITE_ADD_ENTRY \ " INSERT INTO Entry (data) VALUES (?)" #define HDBSQLITE_ADD_PRINCIPAL \ " INSERT INTO Principal (principal, entry, canonical)" \ " VALUES (?, last_insert_rowid(), 1)" #define HDBSQLITE_ADD_ALIAS \ " INSERT INTO Principal (principal, entry, canonical)" \ " VALUES(?, ?, 0)" #define HDBSQLITE_DELETE_ALIASES \ " DELETE FROM Principal" \ " WHERE entry = ? AND canonical = 0" #define HDBSQLITE_UPDATE_ENTRY \ " UPDATE Entry SET data = ?" \ " WHERE id = ?" #define HDBSQLITE_REMOVE \ " DELETE FROM ENTRY WHERE id = " \ " (SELECT entry FROM Principal" \ " WHERE principal = ?)" #define HDBSQLITE_GET_ALL_ENTRIES \ " SELECT data FROM Entry" /** * Wrapper around sqlite3_prepare_v2. * * @param context The current krb5 context * @param statement Where to store the pointer to the statement * after preparing it * @param str SQL code for the statement * * @return 0 if OK, an error code if not */ static krb5_error_code hdb_sqlite_prepare_stmt(krb5_context context, sqlite3 *db, sqlite3_stmt **statement, const char *str) { int ret, tries = 0; ret = sqlite3_prepare_v2(db, str, -1, statement, NULL); while((tries++ < MAX_RETRIES) && ((ret == SQLITE_BUSY) || (ret == SQLITE_IOERR_BLOCKED) || (ret == SQLITE_LOCKED))) { krb5_warnx(context, "hdb-sqlite: prepare busy"); sleep(1); ret = sqlite3_prepare_v2(db, str, -1, statement, NULL); } if (ret != SQLITE_OK) { krb5_set_error_message(context, HDB_ERR_UK_RERROR, "Failed to prepare stmt %s: %s", str, sqlite3_errmsg(db)); return HDB_ERR_UK_RERROR; } return 0; } static krb5_error_code prep_stmts(krb5_context context, hdb_sqlite_db *hsdb) { int ret; ret = hdb_sqlite_prepare_stmt(context, hsdb->db, &hsdb->get_version, HDBSQLITE_GET_VERSION); if (ret) return ret; ret = hdb_sqlite_prepare_stmt(context, hsdb->db, &hsdb->fetch, HDBSQLITE_FETCH); if (ret) return ret; ret = hdb_sqlite_prepare_stmt(context, hsdb->db, &hsdb->get_ids, HDBSQLITE_GET_IDS); if (ret) return ret; ret = hdb_sqlite_prepare_stmt(context, hsdb->db, &hsdb->add_entry, HDBSQLITE_ADD_ENTRY); if (ret) return ret; ret = hdb_sqlite_prepare_stmt(context, hsdb->db, &hsdb->add_principal, HDBSQLITE_ADD_PRINCIPAL); if (ret) return ret; ret = hdb_sqlite_prepare_stmt(context, hsdb->db, &hsdb->add_alias, HDBSQLITE_ADD_ALIAS); if (ret) return ret; ret = hdb_sqlite_prepare_stmt(context, hsdb->db, &hsdb->delete_aliases, HDBSQLITE_DELETE_ALIASES); if (ret) return ret; ret = hdb_sqlite_prepare_stmt(context, hsdb->db, &hsdb->update_entry, HDBSQLITE_UPDATE_ENTRY); if (ret) return ret; ret = hdb_sqlite_prepare_stmt(context, hsdb->db, &hsdb->remove, HDBSQLITE_REMOVE); if (ret) return ret; ret = hdb_sqlite_prepare_stmt(context, hsdb->db, &hsdb->get_all_entries, HDBSQLITE_GET_ALL_ENTRIES); return ret; } static void finalize_stmts(krb5_context context, hdb_sqlite_db *hsdb) { if (hsdb->get_version != NULL) sqlite3_finalize(hsdb->get_version); hsdb->get_version = NULL; if (hsdb->fetch != NULL) sqlite3_finalize(hsdb->fetch); hsdb->fetch = NULL; if (hsdb->get_ids != NULL) sqlite3_finalize(hsdb->get_ids); hsdb->get_ids = NULL; if (hsdb->add_entry != NULL) sqlite3_finalize(hsdb->add_entry); hsdb->add_entry = NULL; if (hsdb->add_principal != NULL) sqlite3_finalize(hsdb->add_principal); hsdb->add_principal = NULL; if (hsdb->add_alias != NULL) sqlite3_finalize(hsdb->add_alias); hsdb->add_alias = NULL; if (hsdb->delete_aliases != NULL) sqlite3_finalize(hsdb->delete_aliases); hsdb->delete_aliases = NULL; if (hsdb->update_entry != NULL) sqlite3_finalize(hsdb->update_entry); hsdb->update_entry = NULL; if (hsdb->remove != NULL) sqlite3_finalize(hsdb->remove); hsdb->remove = NULL; if (hsdb->get_all_entries != NULL) sqlite3_finalize(hsdb->get_all_entries); hsdb->get_all_entries = NULL; } /** * A wrapper around sqlite3_exec. * * @param context The current krb5 context * @param database An open sqlite3 database handle * @param statement SQL code to execute * @param error_code What to return if the statement fails * * @return 0 if OK, else error_code */ static krb5_error_code hdb_sqlite_exec_stmt(krb5_context context, hdb_sqlite_db *hsdb, const char *statement, krb5_error_code error_code) { int ret; int reinit_stmts = 0; sqlite3 *database = hsdb->db; ret = sqlite3_exec(database, statement, NULL, NULL, NULL); while(((ret == SQLITE_BUSY) || (ret == SQLITE_IOERR_BLOCKED) || (ret == SQLITE_LOCKED))) { if (reinit_stmts == 0 && ret == SQLITE_BUSY) { finalize_stmts(context, hsdb); reinit_stmts = 1; } krb5_warnx(context, "hdb-sqlite: exec busy: %d", (int)getpid()); sleep(1); ret = sqlite3_exec(database, statement, NULL, NULL, NULL); } if (ret != SQLITE_OK && error_code) { krb5_set_error_message(context, error_code, "Execute %s: %s", statement, sqlite3_errmsg(database)); return error_code; } if (reinit_stmts) return prep_stmts(context, hsdb); return 0; } /** * */ static krb5_error_code bind_principal(krb5_context context, krb5_const_principal principal, sqlite3_stmt *stmt, int key) { krb5_error_code ret; char *str = NULL; ret = krb5_unparse_name(context, principal, &str); if (ret) return ret; sqlite3_bind_text(stmt, key, str, -1, SQLITE_TRANSIENT); free(str); return 0; } /** * Opens an sqlite3 database handle to a file, may create the * database file depending on flags. * * @param context The current krb5 context * @param db Heimdal database handle * @param flags Controls whether or not the file may be created, * may be 0 or SQLITE_OPEN_CREATE */ static krb5_error_code hdb_sqlite_open_database(krb5_context context, HDB *db, int flags) { int ret; hdb_sqlite_db *hsdb = (hdb_sqlite_db*) db->hdb_db; ret = sqlite3_open_v2(hsdb->db_file, &hsdb->db, SQLITE_OPEN_READWRITE | flags, NULL); if (ret) { if (hsdb->db) { ret = ENOENT; krb5_set_error_message(context, ret, "Error opening sqlite database %s: %s", hsdb->db_file, sqlite3_errmsg(hsdb->db)); sqlite3_close(hsdb->db); hsdb->db = NULL; } else ret = krb5_enomem(context); return ret; } return 0; } static int hdb_sqlite_step(krb5_context context, sqlite3 *db, sqlite3_stmt *stmt) { int ret; ret = sqlite3_step(stmt); while(((ret == SQLITE_BUSY) || (ret == SQLITE_IOERR_BLOCKED) || (ret == SQLITE_LOCKED))) { krb5_warnx(context, "hdb-sqlite: step busy: %d", (int)getpid()); sleep(1); ret = sqlite3_step(stmt); } return ret; } /** * Closes the database and frees memory allocated for statements. * * @param context The current krb5 context * @param db Heimdal database handle */ static krb5_error_code hdb_sqlite_close_database(krb5_context context, HDB *db) { hdb_sqlite_db *hsdb = (hdb_sqlite_db *) db->hdb_db; finalize_stmts(context, hsdb); /* XXX Use sqlite3_close_v2() when we upgrade SQLite3 */ if (sqlite3_close(hsdb->db) != SQLITE_OK) { krb5_set_error_message(context, HDB_ERR_UK_SERROR, "SQLite BEGIN TRANSACTION failed: %s", sqlite3_errmsg(hsdb->db)); return HDB_ERR_UK_SERROR; } return 0; } /** * Opens an sqlite database file and prepares it for use. * If the file does not exist it will be created. * * @param context The current krb5_context * @param db The heimdal database handle * @param filename Where to store the database file * * @return 0 if everything worked, an error code if not */ static krb5_error_code hdb_sqlite_make_database(krb5_context context, HDB *db, const char *filename) { int ret; int created_file = 0; hdb_sqlite_db *hsdb = (hdb_sqlite_db *) db->hdb_db; hsdb->db_file = strdup(filename); if(hsdb->db_file == NULL) return ENOMEM; ret = hdb_sqlite_open_database(context, db, 0); if (ret) { ret = hdb_sqlite_open_database(context, db, SQLITE_OPEN_CREATE); if (ret) goto out; created_file = 1; ret = hdb_sqlite_exec_stmt(context, hsdb, HDBSQLITE_CREATE_TABLES, HDB_ERR_UK_SERROR); if (ret) goto out; ret = hdb_sqlite_exec_stmt(context, hsdb, HDBSQLITE_CREATE_TRIGGERS, HDB_ERR_UK_SERROR); if (ret) goto out; } ret = prep_stmts(context, hsdb); if (ret) goto out; ret = hdb_sqlite_step(context, hsdb->db, hsdb->get_version); if(ret == SQLITE_ROW) { hsdb->version = sqlite3_column_double(hsdb->get_version, 0); } sqlite3_reset(hsdb->get_version); ret = 0; if(hsdb->version != HDBSQLITE_VERSION) { ret = HDB_ERR_UK_SERROR; krb5_set_error_message(context, ret, "HDBSQLITE_VERSION mismatch"); } if(ret) goto out; return 0; out: if (hsdb->db) sqlite3_close(hsdb->db); if (created_file) unlink(hsdb->db_file); free(hsdb->db_file); hsdb->db_file = NULL; return ret; } /** * Retrieves an entry by searching for the given * principal in the Principal database table, both * for canonical principals and aliases. * * @param context The current krb5_context * @param db Heimdal database handle * @param principal The principal whose entry to search for * @param flags Currently only for HDB_F_DECRYPT * @param kvno kvno to fetch is HDB_F_KVNO_SPECIFIED use used * * @return 0 if everything worked, an error code if not */ static krb5_error_code hdb_sqlite_fetch_kvno(krb5_context context, HDB *db, krb5_const_principal principal, unsigned flags, krb5_kvno kvno, hdb_entry_ex *entry) { int sqlite_error; krb5_error_code ret; hdb_sqlite_db *hsdb = (hdb_sqlite_db*)(db->hdb_db); sqlite3_stmt *fetch = hsdb->fetch; krb5_data value; krb5_principal enterprise_principal = NULL; if (principal->name.name_type == KRB5_NT_ENTERPRISE_PRINCIPAL) { if (principal->name.name_string.len != 1) { ret = KRB5_PARSE_MALFORMED; krb5_set_error_message(context, ret, "malformed principal: " "enterprise name with %d name components", principal->name.name_string.len); return ret; } ret = krb5_parse_name(context, principal->name.name_string.val[0], &enterprise_principal); if (ret) return ret; principal = enterprise_principal; } ret = bind_principal(context, principal, fetch, 1); krb5_free_principal(context, enterprise_principal); if (ret) return ret; sqlite_error = hdb_sqlite_step(context, hsdb->db, fetch); if (sqlite_error != SQLITE_ROW) { if(sqlite_error == SQLITE_DONE) { ret = HDB_ERR_NOENTRY; goto out; } else { ret = HDB_ERR_UK_RERROR; krb5_set_error_message(context, ret, "sqlite fetch failed: %d", sqlite_error); goto out; } } value.length = sqlite3_column_bytes(fetch, 0); value.data = (void *) sqlite3_column_blob(fetch, 0); ret = hdb_value2entry(context, &value, &entry->entry); if(ret) goto out; if (db->hdb_master_key_set && (flags & HDB_F_DECRYPT)) { ret = hdb_unseal_keys(context, db, &entry->entry); if(ret) { hdb_free_entry(context, entry); goto out; } } ret = 0; out: sqlite3_clear_bindings(fetch); sqlite3_reset(fetch); return ret; } /** * Convenience function to step a prepared statement with no * value once. * * @param context The current krb5_context * @param statement A prepared sqlite3 statement * * @return 0 if everything worked, an error code if not */ static krb5_error_code hdb_sqlite_step_once(krb5_context context, HDB *db, sqlite3_stmt *statement) { int ret; hdb_sqlite_db *hsdb = (hdb_sqlite_db *) db->hdb_db; ret = hdb_sqlite_step(context, hsdb->db, statement); sqlite3_clear_bindings(statement); sqlite3_reset(statement); return ret; } /** * Stores an hdb_entry in the database. If flags contains HDB_F_REPLACE * a previous entry may be replaced. * * @param context The current krb5_context * @param db Heimdal database handle * @param flags May currently only contain HDB_F_REPLACE * @param entry The data to store * * @return 0 if everything worked, an error code if not */ static krb5_error_code hdb_sqlite_store(krb5_context context, HDB *db, unsigned flags, hdb_entry_ex *entry) { int ret; int i; sqlite_int64 entry_id; const HDB_Ext_Aliases *aliases; hdb_sqlite_db *hsdb = (hdb_sqlite_db *)(db->hdb_db); krb5_data value; sqlite3_stmt *get_ids = hsdb->get_ids; krb5_data_zero(&value); ret = hdb_sqlite_exec_stmt(context, hsdb, "BEGIN IMMEDIATE TRANSACTION", HDB_ERR_UK_SERROR); if(ret != SQLITE_OK) { ret = HDB_ERR_UK_SERROR; krb5_set_error_message(context, ret, "SQLite BEGIN TRANSACTION failed: %s", sqlite3_errmsg(hsdb->db)); goto rollback; } ret = hdb_seal_keys(context, db, &entry->entry); if(ret) { goto rollback; } ret = hdb_entry2value(context, &entry->entry, &value); if(ret) { goto rollback; } ret = bind_principal(context, entry->entry.principal, get_ids, 1); if (ret) goto rollback; ret = hdb_sqlite_step(context, hsdb->db, get_ids); if(ret == SQLITE_DONE) { /* No such principal */ sqlite3_bind_blob(hsdb->add_entry, 1, value.data, value.length, SQLITE_STATIC); ret = hdb_sqlite_step(context, hsdb->db, hsdb->add_entry); sqlite3_clear_bindings(hsdb->add_entry); sqlite3_reset(hsdb->add_entry); if (ret != SQLITE_DONE && ret != SQLITE_CONSTRAINT) { ret = HDB_ERR_UK_SERROR; goto rollback; } if (ret == SQLITE_CONSTRAINT) { ret = HDB_ERR_EXISTS; goto rollback; } ret = bind_principal(context, entry->entry.principal, hsdb->add_principal, 1); if (ret) goto rollback; ret = hdb_sqlite_step(context, hsdb->db, hsdb->add_principal); sqlite3_clear_bindings(hsdb->add_principal); sqlite3_reset(hsdb->add_principal); if (ret != SQLITE_DONE && ret != SQLITE_CONSTRAINT) { ret = HDB_ERR_UK_SERROR; goto rollback; } if (ret == SQLITE_CONSTRAINT) { ret = HDB_ERR_EXISTS; goto rollback; } /* Now let's learn what Entry ID we got for the new principal */ sqlite3_reset(get_ids); ret = hdb_sqlite_step(context, hsdb->db, get_ids); if (ret != SQLITE_ROW) { ret = HDB_ERR_UK_SERROR; goto rollback; } entry_id = sqlite3_column_int64(get_ids, 1); } else if(ret == SQLITE_ROW) { /* Found a principal */ if(! (flags & HDB_F_REPLACE)) /* Not allowed to replace it */ goto rollback; entry_id = sqlite3_column_int64(get_ids, 1); sqlite3_bind_int64(hsdb->delete_aliases, 1, entry_id); ret = hdb_sqlite_step_once(context, db, hsdb->delete_aliases); if (ret != SQLITE_DONE) { ret = HDB_ERR_UK_SERROR; goto rollback; } sqlite3_bind_blob(hsdb->update_entry, 1, value.data, value.length, SQLITE_STATIC); sqlite3_bind_int64(hsdb->update_entry, 2, entry_id); ret = hdb_sqlite_step_once(context, db, hsdb->update_entry); if (ret != SQLITE_DONE) { ret = HDB_ERR_UK_SERROR; goto rollback; } } else { /* Error! */ ret = HDB_ERR_UK_SERROR; goto rollback; } ret = hdb_entry_get_aliases(&entry->entry, &aliases); if(ret || aliases == NULL) goto commit; for(i = 0; i < aliases->aliases.len; i++) { ret = bind_principal(context, &aliases->aliases.val[i], hsdb->add_alias, 1); if (ret) goto rollback; sqlite3_bind_int64(hsdb->add_alias, 2, entry_id); ret = hdb_sqlite_step_once(context, db, hsdb->add_alias); if (ret == SQLITE_CONSTRAINT) { ret = HDB_ERR_EXISTS; goto rollback; } if (ret != SQLITE_DONE) { ret = HDB_ERR_UK_SERROR; goto rollback; } } commit: krb5_data_free(&value); sqlite3_clear_bindings(get_ids); sqlite3_reset(get_ids); if ((flags & HDB_F_PRECHECK)) { (void) hdb_sqlite_exec_stmt(context, hsdb, "ROLLBACK", 0); return 0; } ret = hdb_sqlite_exec_stmt(context, hsdb, "COMMIT", HDB_ERR_UK_SERROR); if(ret != SQLITE_OK) krb5_warnx(context, "hdb-sqlite: COMMIT problem: %ld: %s", (long)HDB_ERR_UK_SERROR, sqlite3_errmsg(hsdb->db)); return ret == SQLITE_OK ? 0 : HDB_ERR_UK_SERROR; rollback: krb5_data_free(&value); sqlite3_clear_bindings(get_ids); sqlite3_reset(get_ids); krb5_warnx(context, "hdb-sqlite: store rollback problem: %d: %s", ret, sqlite3_errmsg(hsdb->db)); (void) hdb_sqlite_exec_stmt(context, hsdb, "ROLLBACK", 0); return ret; } /** * This may be called often by other code, since the BDB backends * can not have several open connections. SQLite can handle * many processes with open handles to the database file * and closing/opening the handle is an expensive operation. * Hence, this function does nothing. * * @param context The current krb5 context * @param db Heimdal database handle * * @return Always returns 0 */ static krb5_error_code hdb_sqlite_close(krb5_context context, HDB *db) { return 0; } /** * The opposite of hdb_sqlite_close. Since SQLite accepts * many open handles to the database file the handle does not * need to be closed, or reopened. * * @param context The current krb5 context * @param db Heimdal database handle * @param flags * @param mode_t * * @return Always returns 0 */ static krb5_error_code hdb_sqlite_open(krb5_context context, HDB *db, int flags, mode_t mode) { return 0; } /** * Closes the databse and frees all resources. * * @param context The current krb5 context * @param db Heimdal database handle * * @return 0 on success, an error code if not */ static krb5_error_code hdb_sqlite_destroy(krb5_context context, HDB *db) { int ret, ret2; hdb_sqlite_db *hsdb; ret = hdb_clear_master_key(context, db); ret2 = hdb_sqlite_close_database(context, db); hsdb = (hdb_sqlite_db*)(db->hdb_db); free(hsdb->db_file); free(db->hdb_db); free(db); return ret ? ret : ret2; } /* * Not sure if this is needed. */ static krb5_error_code hdb_sqlite_lock(krb5_context context, HDB *db, int operation) { krb5_set_error_message(context, HDB_ERR_CANT_LOCK_DB, "lock not implemented"); return HDB_ERR_CANT_LOCK_DB; } /* * Not sure if this is needed. */ static krb5_error_code hdb_sqlite_unlock(krb5_context context, HDB *db) { krb5_set_error_message(context, HDB_ERR_CANT_LOCK_DB, "unlock not implemented"); return HDB_ERR_CANT_LOCK_DB; } /* * Should get the next entry, to allow iteration over all entries. */ static krb5_error_code hdb_sqlite_nextkey(krb5_context context, HDB *db, unsigned flags, hdb_entry_ex *entry) { krb5_error_code ret = 0; int sqlite_error; krb5_data value; hdb_sqlite_db *hsdb = (hdb_sqlite_db *) db->hdb_db; sqlite_error = hdb_sqlite_step(context, hsdb->db, hsdb->get_all_entries); if(sqlite_error == SQLITE_ROW) { /* Found an entry */ value.length = sqlite3_column_bytes(hsdb->get_all_entries, 0); value.data = (void *) sqlite3_column_blob(hsdb->get_all_entries, 0); memset(entry, 0, sizeof(*entry)); ret = hdb_value2entry(context, &value, &entry->entry); } else if(sqlite_error == SQLITE_DONE) { /* No more entries */ ret = HDB_ERR_NOENTRY; sqlite3_reset(hsdb->get_all_entries); } else { ret = HDB_ERR_UK_RERROR; krb5_set_error_message(context, HDB_ERR_UK_RERROR, "SELECT failed after returning one or " "more rows: %s", sqlite3_errmsg(hsdb->db)); } return ret; } /* * Should get the first entry in the database. * What is flags used for? */ static krb5_error_code hdb_sqlite_firstkey(krb5_context context, HDB *db, unsigned flags, hdb_entry_ex *entry) { hdb_sqlite_db *hsdb = (hdb_sqlite_db *) db->hdb_db; krb5_error_code ret; sqlite3_reset(hsdb->get_all_entries); ret = hdb_sqlite_nextkey(context, db, flags, entry); if(ret) return ret; return 0; } /* * Renames the database file. */ static krb5_error_code hdb_sqlite_rename(krb5_context context, HDB *db, const char *new_name) { krb5_error_code ret, ret2; hdb_sqlite_db *hsdb = (hdb_sqlite_db *) db->hdb_db; krb5_warnx(context, "hdb_sqlite_rename"); if (strncasecmp(new_name, "sqlite:", 7) == 0) new_name += 7; ret = hdb_sqlite_close_database(context, db); if (rename(hsdb->db_file, new_name) == -1) return errno; free(hsdb->db_file); ret2 = hdb_sqlite_make_database(context, db, new_name); return ret ? ret : ret2; } /* * Removes a principal, including aliases and associated entry. */ static krb5_error_code hdb_sqlite_remove(krb5_context context, HDB *db, unsigned flags, krb5_const_principal principal) { krb5_error_code ret; hdb_sqlite_db *hsdb = (hdb_sqlite_db*)(db->hdb_db); sqlite3_stmt *get_ids = hsdb->get_ids; sqlite3_stmt *rm = hsdb->remove; bind_principal(context, principal, rm, 1); ret = hdb_sqlite_exec_stmt(context, hsdb, "BEGIN IMMEDIATE TRANSACTION", HDB_ERR_UK_SERROR); if (ret != SQLITE_OK) { ret = HDB_ERR_UK_SERROR; (void) hdb_sqlite_exec_stmt(context, hsdb, "ROLLBACK", 0); krb5_set_error_message(context, ret, "SQLite BEGIN TRANSACTION failed: %s", sqlite3_errmsg(hsdb->db)); return ret; } if ((flags & HDB_F_PRECHECK)) { ret = bind_principal(context, principal, get_ids, 1); if (ret) return ret; ret = hdb_sqlite_step(context, hsdb->db, get_ids); sqlite3_clear_bindings(get_ids); sqlite3_reset(get_ids); if (ret == SQLITE_DONE) { (void) hdb_sqlite_exec_stmt(context, hsdb, "ROLLBACK", 0); return HDB_ERR_NOENTRY; } } ret = hdb_sqlite_step(context, hsdb->db, rm); sqlite3_clear_bindings(rm); sqlite3_reset(rm); if (ret != SQLITE_DONE) { (void) hdb_sqlite_exec_stmt(context, hsdb, "ROLLBACK", 0); ret = HDB_ERR_UK_SERROR; krb5_set_error_message(context, ret, "sqlite remove failed: %d", ret); return ret; } if ((flags & HDB_F_PRECHECK)) { (void) hdb_sqlite_exec_stmt(context, hsdb, "ROLLBACK", 0); return 0; } ret = hdb_sqlite_exec_stmt(context, hsdb, "COMMIT", HDB_ERR_UK_SERROR); if (ret != SQLITE_OK) krb5_warnx(context, "hdb-sqlite: COMMIT problem: %ld: %s", (long)HDB_ERR_UK_SERROR, sqlite3_errmsg(hsdb->db)); return 0; } /** * Create SQLITE object, and creates the on disk database if its doesn't exists. * * @param context A Kerberos 5 context. * @param db a returned database handle. * @param filename filename * * @return 0 on success, an error code if not */ krb5_error_code hdb_sqlite_create(krb5_context context, HDB **db, const char *filename) { krb5_error_code ret; hdb_sqlite_db *hsdb; *db = calloc(1, sizeof (**db)); if (*db == NULL) return krb5_enomem(context); (*db)->hdb_name = strdup(filename); if ((*db)->hdb_name == NULL) { free(*db); *db = NULL; return krb5_enomem(context); } hsdb = (hdb_sqlite_db*) calloc(1, sizeof (*hsdb)); if (hsdb == NULL) { free((*db)->hdb_name); free(*db); *db = NULL; return krb5_enomem(context); } (*db)->hdb_db = hsdb; /* XXX make_database should make sure everything else is freed on error */ ret = hdb_sqlite_make_database(context, *db, filename); if (ret) { free((*db)->hdb_db); free(*db); return ret; } (*db)->hdb_master_key_set = 0; (*db)->hdb_openp = 0; (*db)->hdb_capability_flags = 0; (*db)->hdb_open = hdb_sqlite_open; (*db)->hdb_close = hdb_sqlite_close; (*db)->hdb_lock = hdb_sqlite_lock; (*db)->hdb_unlock = hdb_sqlite_unlock; (*db)->hdb_firstkey = hdb_sqlite_firstkey; (*db)->hdb_nextkey = hdb_sqlite_nextkey; (*db)->hdb_fetch_kvno = hdb_sqlite_fetch_kvno; (*db)->hdb_store = hdb_sqlite_store; (*db)->hdb_remove = hdb_sqlite_remove; (*db)->hdb_destroy = hdb_sqlite_destroy; (*db)->hdb_rename = hdb_sqlite_rename; (*db)->hdb__get = NULL; (*db)->hdb__put = NULL; (*db)->hdb__del = NULL; return 0; } heimdal-7.5.0/lib/hdb/common.c0000644000175000017500000002663713026237312014226 0ustar niknik/* * Copyright (c) 1997-2002 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "hdb_locl.h" int hdb_principal2key(krb5_context context, krb5_const_principal p, krb5_data *key) { Principal new; size_t len = 0; int ret; ret = copy_Principal(p, &new); if(ret) return ret; new.name.name_type = 0; ASN1_MALLOC_ENCODE(Principal, key->data, key->length, &new, &len, ret); if (ret == 0 && key->length != len) krb5_abortx(context, "internal asn.1 encoder error"); free_Principal(&new); return ret; } int hdb_key2principal(krb5_context context, krb5_data *key, krb5_principal p) { return decode_Principal(key->data, key->length, p, NULL); } int hdb_entry2value(krb5_context context, const hdb_entry *ent, krb5_data *value) { size_t len = 0; int ret; ASN1_MALLOC_ENCODE(hdb_entry, value->data, value->length, ent, &len, ret); if (ret == 0 && value->length != len) krb5_abortx(context, "internal asn.1 encoder error"); return ret; } int hdb_value2entry(krb5_context context, krb5_data *value, hdb_entry *ent) { return decode_hdb_entry(value->data, value->length, ent, NULL); } int hdb_entry_alias2value(krb5_context context, const hdb_entry_alias *alias, krb5_data *value) { size_t len = 0; int ret; ASN1_MALLOC_ENCODE(hdb_entry_alias, value->data, value->length, alias, &len, ret); if (ret == 0 && value->length != len) krb5_abortx(context, "internal asn.1 encoder error"); return ret; } int hdb_value2entry_alias(krb5_context context, krb5_data *value, hdb_entry_alias *ent) { return decode_hdb_entry_alias(value->data, value->length, ent, NULL); } krb5_error_code _hdb_fetch_kvno(krb5_context context, HDB *db, krb5_const_principal principal, unsigned flags, krb5_kvno kvno, hdb_entry_ex *entry) { krb5_principal enterprise_principal = NULL; krb5_data key, value; krb5_error_code ret; if (principal->name.name_type == KRB5_NT_ENTERPRISE_PRINCIPAL) { if (principal->name.name_string.len != 1) { ret = KRB5_PARSE_MALFORMED; krb5_set_error_message(context, ret, "malformed principal: " "enterprise name with %d name components", principal->name.name_string.len); return ret; } ret = krb5_parse_name(context, principal->name.name_string.val[0], &enterprise_principal); if (ret) return ret; principal = enterprise_principal; } hdb_principal2key(context, principal, &key); if (enterprise_principal) krb5_free_principal(context, enterprise_principal); ret = db->hdb__get(context, db, key, &value); krb5_data_free(&key); if(ret) return ret; ret = hdb_value2entry(context, &value, &entry->entry); if (ret == ASN1_BAD_ID && (flags & HDB_F_CANON) == 0) { krb5_data_free(&value); return HDB_ERR_NOENTRY; } else if (ret == ASN1_BAD_ID) { hdb_entry_alias alias; ret = hdb_value2entry_alias(context, &value, &alias); if (ret) { krb5_data_free(&value); return ret; } hdb_principal2key(context, alias.principal, &key); krb5_data_free(&value); free_hdb_entry_alias(&alias); ret = db->hdb__get(context, db, key, &value); krb5_data_free(&key); if (ret) return ret; ret = hdb_value2entry(context, &value, &entry->entry); if (ret) { krb5_data_free(&value); return ret; } } krb5_data_free(&value); if ((flags & HDB_F_DECRYPT) && (flags & HDB_F_ALL_KVNOS)) { /* Decrypt the current keys */ ret = hdb_unseal_keys(context, db, &entry->entry); if (ret) { hdb_free_entry(context, entry); return ret; } /* Decrypt the key history too */ ret = hdb_unseal_keys_kvno(context, db, 0, flags, &entry->entry); if (ret) { hdb_free_entry(context, entry); return ret; } } else if ((flags & HDB_F_DECRYPT)) { if ((flags & HDB_F_KVNO_SPECIFIED) == 0 || kvno == entry->entry.kvno) { /* Decrypt the current keys */ ret = hdb_unseal_keys(context, db, &entry->entry); if (ret) { hdb_free_entry(context, entry); return ret; } } else { if ((flags & HDB_F_ALL_KVNOS)) kvno = 0; /* * Find and decrypt the keys from the history that we want, * and swap them with the current keys */ ret = hdb_unseal_keys_kvno(context, db, kvno, flags, &entry->entry); if (ret) { hdb_free_entry(context, entry); return ret; } } } return 0; } static krb5_error_code hdb_remove_aliases(krb5_context context, HDB *db, krb5_data *key) { const HDB_Ext_Aliases *aliases; krb5_error_code code; hdb_entry oldentry; krb5_data value; size_t i; code = db->hdb__get(context, db, *key, &value); if (code == HDB_ERR_NOENTRY) return 0; else if (code) return code; code = hdb_value2entry(context, &value, &oldentry); krb5_data_free(&value); if (code) return code; code = hdb_entry_get_aliases(&oldentry, &aliases); if (code || aliases == NULL) { free_hdb_entry(&oldentry); return code; } for (i = 0; i < aliases->aliases.len; i++) { krb5_data akey; code = hdb_principal2key(context, &aliases->aliases.val[i], &akey); if (code == 0) { code = db->hdb__del(context, db, akey); krb5_data_free(&akey); } if (code) { free_hdb_entry(&oldentry); return code; } } free_hdb_entry(&oldentry); return 0; } static krb5_error_code hdb_add_aliases(krb5_context context, HDB *db, unsigned flags, hdb_entry_ex *entry) { const HDB_Ext_Aliases *aliases; krb5_error_code code; krb5_data key, value; size_t i; code = hdb_entry_get_aliases(&entry->entry, &aliases); if (code || aliases == NULL) return code; for (i = 0; i < aliases->aliases.len; i++) { hdb_entry_alias entryalias; entryalias.principal = entry->entry.principal; code = hdb_entry_alias2value(context, &entryalias, &value); if (code) return code; code = hdb_principal2key(context, &aliases->aliases.val[i], &key); if (code == 0) { code = db->hdb__put(context, db, flags, key, value); krb5_data_free(&key); } krb5_data_free(&value); if (code) return code; } return 0; } static krb5_error_code hdb_check_aliases(krb5_context context, HDB *db, hdb_entry_ex *entry) { const HDB_Ext_Aliases *aliases; int code; size_t i; /* check if new aliases already is used */ code = hdb_entry_get_aliases(&entry->entry, &aliases); if (code) return code; for (i = 0; aliases && i < aliases->aliases.len; i++) { hdb_entry_alias alias; krb5_data akey, value; code = hdb_principal2key(context, &aliases->aliases.val[i], &akey); if (code == 0) { code = db->hdb__get(context, db, akey, &value); krb5_data_free(&akey); } if (code == HDB_ERR_NOENTRY) continue; else if (code) return code; code = hdb_value2entry_alias(context, &value, &alias); krb5_data_free(&value); if (code == ASN1_BAD_ID) return HDB_ERR_EXISTS; else if (code) return code; code = krb5_principal_compare(context, alias.principal, entry->entry.principal); free_hdb_entry_alias(&alias); if (code == 0) return HDB_ERR_EXISTS; } return 0; } krb5_error_code _hdb_store(krb5_context context, HDB *db, unsigned flags, hdb_entry_ex *entry) { krb5_data key, value; int code; if (entry->entry.flags.do_not_store) return HDB_ERR_MISUSE; /* check if new aliases already is used */ code = hdb_check_aliases(context, db, entry); if (code) return code; if ((flags & HDB_F_PRECHECK) && (flags & HDB_F_REPLACE)) return 0; if ((flags & HDB_F_PRECHECK)) { code = hdb_principal2key(context, entry->entry.principal, &key); if (code) return code; code = db->hdb__get(context, db, key, &value); krb5_data_free(&key); if (code == 0) krb5_data_free(&value); if (code == HDB_ERR_NOENTRY) return 0; return code ? code : HDB_ERR_EXISTS; } if(entry->entry.generation == NULL) { struct timeval t; entry->entry.generation = malloc(sizeof(*entry->entry.generation)); if(entry->entry.generation == NULL) { krb5_set_error_message(context, ENOMEM, "malloc: out of memory"); return ENOMEM; } gettimeofday(&t, NULL); entry->entry.generation->time = t.tv_sec; entry->entry.generation->usec = t.tv_usec; entry->entry.generation->gen = 0; } else entry->entry.generation->gen++; code = hdb_seal_keys(context, db, &entry->entry); if (code) return code; hdb_principal2key(context, entry->entry.principal, &key); /* remove aliases */ code = hdb_remove_aliases(context, db, &key); if (code) { krb5_data_free(&key); return code; } hdb_entry2value(context, &entry->entry, &value); code = db->hdb__put(context, db, flags & HDB_F_REPLACE, key, value); krb5_data_free(&value); krb5_data_free(&key); if (code) return code; code = hdb_add_aliases(context, db, flags, entry); return code; } krb5_error_code _hdb_remove(krb5_context context, HDB *db, unsigned flags, krb5_const_principal principal) { krb5_data key, value; int code; hdb_principal2key(context, principal, &key); if ((flags & HDB_F_PRECHECK)) { /* * We don't check that we can delete the aliases because we * assume that the DB is consistent. If we did check for alias * consistency we'd also have to provide a way to fsck the DB, * otherwise admins would have no way to recover -- papering * over this here is less work, but we really ought to provide * an HDB fsck. */ code = db->hdb__get(context, db, key, &value); krb5_data_free(&key); if (code == 0) { krb5_data_free(&value); return 0; } return code; } code = hdb_remove_aliases(context, db, &key); if (code) { krb5_data_free(&key); return code; } code = db->hdb__del(context, db, key); krb5_data_free(&key); return code; } heimdal-7.5.0/lib/hdb/hdb.h0000644000175000017500000002525713212137553013500 0ustar niknik/* * Copyright (c) 1997 - 2007 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ /* $Id$ */ #ifndef __HDB_H__ #define __HDB_H__ #include #include #include #include #include struct hdb_dbinfo; enum hdb_lockop{ HDB_RLOCK, HDB_WLOCK }; /* flags for various functions */ #define HDB_F_DECRYPT 1 /* decrypt keys */ #define HDB_F_REPLACE 2 /* replace entry */ #define HDB_F_GET_CLIENT 4 /* fetch client */ #define HDB_F_GET_SERVER 8 /* fetch server */ #define HDB_F_GET_KRBTGT 16 /* fetch krbtgt */ #define HDB_F_GET_ANY 28 /* fetch any of client,server,krbtgt */ #define HDB_F_CANON 32 /* want canonicalition */ #define HDB_F_ADMIN_DATA 64 /* want data that kdc don't use */ #define HDB_F_KVNO_SPECIFIED 128 /* we want a particular KVNO */ #define HDB_F_CURRENT_KVNO 256 /* we want the current KVNO */ #define HDB_F_LIVE_CLNT_KVNOS 512 /* we want all live keys for pre-auth */ #define HDB_F_LIVE_SVC_KVNOS 1024 /* we want all live keys for tix */ #define HDB_F_ALL_KVNOS 2048 /* we want all the keys, live or not */ #define HDB_F_FOR_AS_REQ 4096 /* fetch is for a AS REQ */ #define HDB_F_FOR_TGS_REQ 8192 /* fetch is for a TGS REQ */ #define HDB_F_PRECHECK 16384 /* check that the operation would succeed */ /* hdb_capability_flags */ #define HDB_CAP_F_HANDLE_ENTERPRISE_PRINCIPAL 1 #define HDB_CAP_F_HANDLE_PASSWORDS 2 #define HDB_CAP_F_PASSWORD_UPDATE_KEYS 4 #define HDB_CAP_F_SHARED_DIRECTORY 8 /* auth status values */ #define HDB_AUTH_SUCCESS 0 #define HDB_AUTH_WRONG_PASSWORD 1 #define HDB_AUTH_INVALID_SIGNATURE 2 /* key usage for master key */ #define HDB_KU_MKEY 0x484442 typedef struct hdb_master_key_data *hdb_master_key; /** * hdb_entry_ex is a wrapper structure around the hdb_entry structure * that allows backends to keep a pointer to the backing store, ie in * ->hdb_fetch_kvno(), so that we the kadmin/kpasswd backend gets around to * ->hdb_store(), the backend doesn't need to lookup the entry again. */ typedef struct hdb_entry_ex { void *ctx; hdb_entry entry; void (*free_entry)(krb5_context, struct hdb_entry_ex *); } hdb_entry_ex; /** * HDB backend function pointer structure * * The HDB structure is what the KDC and kadmind framework uses to * query the backend database when talking about principals. */ typedef struct HDB { void *hdb_db; void *hdb_dbc; /** don't use, only for DB3 */ char *hdb_name; int hdb_master_key_set; hdb_master_key hdb_master_key; int hdb_openp; int hdb_capability_flags; int lock_count; int lock_type; /** * Open (or create) the a Kerberos database. * * Open (or create) the a Kerberos database that was resolved with * hdb_create(). The third and fourth flag to the function are the * same as open(), thus passing O_CREAT will create the data base * if it doesn't exists. * * Then done the caller should call hdb_close(), and to release * all resources hdb_destroy(). */ krb5_error_code (*hdb_open)(krb5_context, struct HDB*, int, mode_t); /** * Close the database for transaction * * Closes the database for further transactions, wont release any * permanant resources. the database can be ->hdb_open-ed again. */ krb5_error_code (*hdb_close)(krb5_context, struct HDB*); /** * Free an entry after use. */ void (*hdb_free)(krb5_context, struct HDB*, hdb_entry_ex*); /** * Fetch an entry from the backend * * Fetch an entry from the backend, flags are what type of entry * should be fetch: client, server, krbtgt. * knvo (if specified and flags HDB_F_KVNO_SPECIFIED set) is the kvno to get */ krb5_error_code (*hdb_fetch_kvno)(krb5_context, struct HDB*, krb5_const_principal, unsigned, krb5_kvno, hdb_entry_ex*); /** * Store an entry to database */ krb5_error_code (*hdb_store)(krb5_context, struct HDB*, unsigned, hdb_entry_ex*); /** * Remove an entry from the database. */ krb5_error_code (*hdb_remove)(krb5_context, struct HDB*, unsigned, krb5_const_principal); /** * As part of iteration, fetch one entry */ krb5_error_code (*hdb_firstkey)(krb5_context, struct HDB*, unsigned, hdb_entry_ex*); /** * As part of iteration, fetch next entry */ krb5_error_code (*hdb_nextkey)(krb5_context, struct HDB*, unsigned, hdb_entry_ex*); /** * Lock database * * A lock can only be held by one consumers. Transaction can still * happen on the database while the lock is held, so the entry is * only useful for syncroning creation of the database and renaming of the database. */ krb5_error_code (*hdb_lock)(krb5_context, struct HDB*, int); /** * Unlock database */ krb5_error_code (*hdb_unlock)(krb5_context, struct HDB*); /** * Rename the data base. * * Assume that the database is not hdb_open'ed and not locked. */ krb5_error_code (*hdb_rename)(krb5_context, struct HDB*, const char*); /** * Get an hdb_entry from a classical DB backend * * This function takes a principal key (krb5_data) and returns all * data related to principal in the return krb5_data. The returned * encoded entry is of type hdb_entry or hdb_entry_alias. */ krb5_error_code (*hdb__get)(krb5_context, struct HDB*, krb5_data, krb5_data*); /** * Store an hdb_entry from a classical DB backend * * This function takes a principal key (krb5_data) and encoded * hdb_entry or hdb_entry_alias as the data to store. * * For a file-based DB, this must synchronize to disk when done. * This is sub-optimal for kadm5_s_rename_principal(), and for * kadm5_s_modify_principal() when using principal aliases; to * improve this so that only one fsync() need be done * per-transaction will require HDB API extensions. */ krb5_error_code (*hdb__put)(krb5_context, struct HDB*, int, krb5_data, krb5_data); /** * Delete and hdb_entry from a classical DB backend * * This function takes a principal key (krb5_data) naming the record * to delete. * * Same discussion as in @ref HDB::hdb__put */ krb5_error_code (*hdb__del)(krb5_context, struct HDB*, krb5_data); /** * Destroy the handle to the database. * * Destroy the handle to the database, deallocate all memory and * related resources. Does not remove any permanent data. Its the * logical reverse of hdb_create() function that is the entry * point for the module. */ krb5_error_code (*hdb_destroy)(krb5_context, struct HDB*); /** * Get the list of realms this backend handles. * This call is optional to support. The returned realms are used * for announcing the realms over bonjour. Free returned array * with krb5_free_host_realm(). */ krb5_error_code (*hdb_get_realms)(krb5_context, struct HDB *, krb5_realm **); /** * Change password. * * Will update keys for the entry when given password. The new * keys must be written into the entry and will then later be * ->hdb_store() into the database. The backend will still perform * all other operations, increasing the kvno, and update * modification timestamp. * * The backend needs to call _kadm5_set_keys() and perform password * quality checks. */ krb5_error_code (*hdb_password)(krb5_context, struct HDB*, hdb_entry_ex*, const char *, int); /** * Auth feedback * * This is a feedback call that allows backends that provides * lockout functionality to register failure and/or successes. * * In case the entry is locked out, the backend should set the * hdb_entry.flags.locked-out flag. */ krb5_error_code (*hdb_auth_status)(krb5_context, struct HDB *, hdb_entry_ex *, int); /** * Check if delegation is allowed. */ krb5_error_code (*hdb_check_constrained_delegation)(krb5_context, struct HDB *, hdb_entry_ex *, krb5_const_principal); /** * Check if this name is an alias for the supplied client for PKINIT userPrinicpalName logins */ krb5_error_code (*hdb_check_pkinit_ms_upn_match)(krb5_context, struct HDB *, hdb_entry_ex *, krb5_const_principal); /** * Check if s4u2self is allowed from this client to this server */ krb5_error_code (*hdb_check_s4u2self)(krb5_context, struct HDB *, hdb_entry_ex *, krb5_const_principal); }HDB; #define HDB_INTERFACE_VERSION 9 struct hdb_method { int version; krb5_error_code (*init)(krb5_context, void **); void (*fini)(void *); const char *prefix; krb5_error_code (*create)(krb5_context, HDB **, const char *filename); }; /* dump entry format, for hdb_print_entry() */ typedef enum hdb_dump_format { HDB_DUMP_HEIMDAL = 0, HDB_DUMP_MIT = 1, } hdb_dump_format_t; struct hdb_print_entry_arg { FILE *out; hdb_dump_format_t fmt; }; typedef krb5_error_code (*hdb_foreach_func_t)(krb5_context, HDB*, hdb_entry_ex*, void*); extern krb5_kt_ops hdb_kt_ops; extern krb5_kt_ops hdb_get_kt_ops; extern const int hdb_interface_version; #include #endif /* __HDB_H__ */ heimdal-7.5.0/lib/hdb/test_dbinfo.c0000644000175000017500000000604413026237312015224 0ustar niknik/* * Copyright (c) 2005 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "hdb_locl.h" #include static int help_flag; static int version_flag; struct getargs args[] = { { "help", 'h', arg_flag, &help_flag, NULL, NULL }, { "version", 0, arg_flag, &version_flag, NULL, NULL } }; static int num_args = sizeof(args) / sizeof(args[0]); int main(int argc, char **argv) { struct hdb_dbinfo *info, *d; krb5_context context; int ret, o = 0; setprogname(argv[0]); if(getarg(args, num_args, argc, argv, &o)) krb5_std_usage(1, args, num_args); if(help_flag) krb5_std_usage(0, args, num_args); if(version_flag){ print_version(NULL); exit(0); } ret = krb5_init_context(&context); if (ret) errx (1, "krb5_init_context failed: %d", ret); ret = hdb_get_dbinfo(context, &info); if (ret) krb5_err(context, 1, ret, "hdb_get_dbinfo"); d = NULL; while ((d = hdb_dbinfo_get_next(info, d)) != NULL) { const char *s; s = hdb_dbinfo_get_label(context, d); printf("label: %s\n", s ? s : "no label"); s = hdb_dbinfo_get_realm(context, d); printf("\trealm: %s\n", s ? s : "no realm"); s = hdb_dbinfo_get_dbname(context, d); printf("\tdbname: %s\n", s ? s : "no dbname"); s = hdb_dbinfo_get_mkey_file(context, d); printf("\tmkey_file: %s\n", s ? s : "no mkey file"); s = hdb_dbinfo_get_acl_file(context, d); printf("\tacl_file: %s\n", s ? s : "no acl file"); } hdb_free_dbinfo(context, &info); krb5_free_context(context); return 0; } heimdal-7.5.0/lib/ipc/0000755000175000017500000000000013214604041012566 5ustar niknikheimdal-7.5.0/lib/ipc/heim_ipc_reply.defs0000644000175000017500000000414412136107750016433 0ustar niknik/* * Copyright (c) 2009 Kungliga Tekniska Hgskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Portions Copyright (c) 2009 Apple Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include #include type heim_ipc_message_inband_t = array [ * : 2048 ] of char; type heim_ipc_message_outband_t = array [] of char; import "heim_ipc_types.h"; subsystem heim_ipc 101; userprefix mheim_ripc_; simpleroutine call_reply( reply_port : mach_port_move_send_once_t; returnvalue : int; replyin : heim_ipc_message_inband_t; replyout : heim_ipc_message_outband_t, dealloc); heimdal-7.5.0/lib/ipc/heim_ipc_async.defs0000644000175000017500000000426512136107750016421 0ustar niknik/* * Copyright (c) 2009 Kungliga Tekniska Hgskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Portions Copyright (c) 2009 Apple Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include #include type heim_ipc_message_inband_t = array [ * : 2048 ] of char; type heim_ipc_message_outband_t = array [] of char; import "heim_ipc_types.h"; subsystem mheim_aipc 201; userprefix mheim_aipc_; serverprefix mheim_ado_; simpleroutine acall_reply( server_port : mach_port_move_send_once_t; ServerAuditToken client_creds : audit_token_t; in returnvalue : int; in requestin : heim_ipc_message_inband_t; in requestout : heim_ipc_message_outband_t); heimdal-7.5.0/lib/ipc/ts-http.c0000644000175000017500000000710213026237312014341 0ustar niknik/* * Copyright (c) 2009 Kungliga Tekniska Hgskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Portions Copyright (c) 2009 Apple Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include #include #include #include #include #include static int help_flag; static int version_flag; static struct getargs args[] = { { "help", 'h', arg_flag, &help_flag, NULL, NULL }, { "version", 'v', arg_flag, &version_flag, NULL, NULL } }; static int num_args = sizeof(args) / sizeof(args[0]); static void usage(int ret) { arg_printusage (args, num_args, NULL, ""); exit (ret); } static void test_service(void *ctx, const heim_idata *req, const heim_icred cred, heim_ipc_complete complete, heim_sipc_call cctx) { heim_idata rep; printf("got request\n"); rep.length = 3; rep.data = strdup("hej"); (*complete)(cctx, 0, &rep); } static void setup_sockets(void) { struct addrinfo hints, *res, *res0; int ret, s; heim_sipc u; memset(&hints, 0, sizeof(hints)); hints.ai_family = PF_UNSPEC; hints.ai_socktype = SOCK_STREAM; hints.ai_flags = AI_PASSIVE; ret = getaddrinfo(NULL, "8080", &hints, &res0); if (ret) errx(1, "%s", gai_strerror(ret)); for (res = res0; res ; res = res->ai_next) { s = socket(res->ai_family, res->ai_socktype, res->ai_protocol); if (s < 0) { warn("socket"); continue; } socket_set_reuseaddr(s, 1); socket_set_ipv6only(s, 1); if (bind(s, res->ai_addr, res->ai_addrlen) < 0) { warn("bind"); close(s); continue; } listen(s, 5); ret = heim_sipc_stream_listener(s, HEIM_SIPC_TYPE_HTTP, test_service, NULL, &u); if (ret) errx(1, "heim_sipc_stream_listener: %d", ret); } freeaddrinfo(res0); } int main(int argc, char **argv) { int optidx = 0; setprogname(argv[0]); if (getarg(args, num_args, argc, argv, &optidx)) usage(1); if (help_flag) usage(0); if (version_flag) { print_version(NULL); exit(0); } setup_sockets(); heim_ipc_main(); return 0; } heimdal-7.5.0/lib/ipc/heim-ipc.h0000644000175000017500000000670513026237312014446 0ustar niknik/* * Copyright (c) 2009 Kungliga Tekniska Hgskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Portions Copyright (c) 2009 Apple Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include typedef struct heim_ipc *heim_ipc; typedef struct heim_sipc *heim_sipc; typedef struct heim_icred *heim_icred; typedef struct heim_isemaphore *heim_isemaphore; typedef struct heim_base_data heim_idata; typedef struct heim_sipc_call *heim_sipc_call; /* common */ void heim_ipc_free_cred(heim_icred); uid_t heim_ipc_cred_get_uid(heim_icred); gid_t heim_ipc_cred_get_gid(heim_icred); pid_t heim_ipc_cred_get_pid(heim_icred); pid_t heim_ipc_cred_get_session(heim_icred); void heim_ipc_main(void); heim_isemaphore heim_ipc_semaphore_create(long); long heim_ipc_semaphore_wait(heim_isemaphore, time_t); long heim_ipc_semaphore_signal(heim_isemaphore); void heim_ipc_semaphore_release(heim_isemaphore); #define HEIM_IPC_WAIT_FOREVER ((time_t)-1) void heim_ipc_free_data(heim_idata *); /* client */ int heim_ipc_init_context(const char *, heim_ipc *); void heim_ipc_free_context(heim_ipc); int heim_ipc_call(heim_ipc, const heim_idata *, heim_idata *, heim_icred *); int heim_ipc_async(heim_ipc, const heim_idata *, void *, void (*func)(void *, int, heim_idata *, heim_icred)); /* server */ #define HEIM_SIPC_TYPE_IPC 1 #define HEIM_SIPC_TYPE_UINT32 2 #define HEIM_SIPC_TYPE_HTTP 4 typedef void (*heim_ipc_complete)(heim_sipc_call, int, heim_idata *); typedef void (*heim_ipc_callback)(void *, const heim_idata *, const heim_icred, heim_ipc_complete, heim_sipc_call); int heim_sipc_launchd_mach_init(const char *, heim_ipc_callback, void *, heim_sipc *); int heim_sipc_stream_listener(int, int, heim_ipc_callback, void *, heim_sipc *); int heim_sipc_service_unix(const char *, heim_ipc_callback, void *, heim_sipc *); void heim_sipc_timeout(time_t); void heim_sipc_set_timeout_handler(void (*)(void)); void heim_sipc_free_context(heim_sipc); heimdal-7.5.0/lib/ipc/client.c0000644000175000017500000003245513026237312014225 0ustar niknik/* * Copyright (c) 2009 Kungliga Tekniska Hgskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Portions Copyright (c) 2009 Apple Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "hi_locl.h" #if defined(__APPLE__) && defined(HAVE_GCD) #include "heim_ipc.h" #include "heim_ipc_asyncServer.h" #include #include static dispatch_once_t jobqinited = 0; static dispatch_queue_t jobq = NULL; static dispatch_queue_t syncq; struct mach_ctx { mach_port_t server; char *name; }; static int mach_release(void *ctx); static int mach_init(const char *service, void **ctx) { struct mach_ctx *ipc; mach_port_t sport; int ret; dispatch_once(&jobqinited, ^{ jobq = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0); syncq = dispatch_queue_create("heim-ipc-syncq", NULL); }); ret = bootstrap_look_up(bootstrap_port, service, &sport); if (ret) return ret; ipc = malloc(sizeof(*ipc)); if (ipc == NULL) { mach_port_destroy(mach_task_self(), sport); return ENOMEM; } ipc->server = sport; ipc->name = strdup(service); if (ipc->name == NULL) { mach_release(ipc); return ENOMEM; } *ctx = ipc; return 0; } static int mach_ipc(void *ctx, const heim_idata *request, heim_idata *response, heim_icred *cred) { struct mach_ctx *ipc = ctx; heim_ipc_message_inband_t requestin; mach_msg_type_number_t requestin_length = 0; heim_ipc_message_outband_t requestout = NULL; mach_msg_type_number_t requestout_length = 0; heim_ipc_message_inband_t replyin; mach_msg_type_number_t replyin_length; heim_ipc_message_outband_t replyout; mach_msg_type_number_t replyout_length; int ret, errorcode, retries = 0; memcpy(requestin, request->data, request->length); requestin_length = request->length; while (retries < 2) { __block mach_port_t sport; dispatch_sync(syncq, ^{ sport = ipc->server; }); ret = mheim_ipc_call(sport, requestin, requestin_length, requestout, requestout_length, &errorcode, replyin, &replyin_length, &replyout, &replyout_length); if (ret == MACH_SEND_INVALID_DEST) { mach_port_t nport; /* race other threads to get a new port */ ret = bootstrap_look_up(bootstrap_port, ipc->name, &nport); if (ret) return ret; dispatch_sync(syncq, ^{ /* check if we lost the race to lookup the port */ if (sport != ipc->server) { mach_port_deallocate(mach_task_self(), nport); } else { mach_port_deallocate(mach_task_self(), ipc->server); ipc->server = nport; } }); retries++; } else if (ret) { return ret; } else break; } if (retries >= 2) return EINVAL; if (errorcode) { if (replyout_length) vm_deallocate (mach_task_self (), (vm_address_t) replyout, replyout_length); return errorcode; } if (replyout_length) { response->data = malloc(replyout_length); if (response->data == NULL) { vm_deallocate (mach_task_self (), (vm_address_t) replyout, replyout_length); return ENOMEM; } memcpy(response->data, replyout, replyout_length); response->length = replyout_length; vm_deallocate (mach_task_self (), (vm_address_t) replyout, replyout_length); } else { response->data = malloc(replyin_length); if (response->data == NULL) return ENOMEM; memcpy(response->data, replyin, replyin_length); response->length = replyin_length; } return 0; } struct async_client { mach_port_t mp; dispatch_source_t source; dispatch_queue_t queue; void (*func)(void *, int, heim_idata *, heim_icred); void *userctx; }; kern_return_t mheim_ado_acall_reply(mach_port_t server_port, audit_token_t client_creds, int returnvalue, heim_ipc_message_inband_t replyin, mach_msg_type_number_t replyinCnt, heim_ipc_message_outband_t replyout, mach_msg_type_number_t replyoutCnt) { struct async_client *c = dispatch_get_context(dispatch_get_current_queue()); heim_idata response; if (returnvalue) { response.data = NULL; response.length = 0; } else if (replyoutCnt) { response.data = replyout; response.length = replyoutCnt; } else { response.data = replyin; response.length = replyinCnt; } (*c->func)(c->userctx, returnvalue, &response, NULL); if (replyoutCnt) vm_deallocate (mach_task_self (), (vm_address_t) replyout, replyoutCnt); dispatch_source_cancel(c->source); return 0; } static int mach_async(void *ctx, const heim_idata *request, void *userctx, void (*func)(void *, int, heim_idata *, heim_icred)) { struct mach_ctx *ipc = ctx; heim_ipc_message_inband_t requestin; mach_msg_type_number_t requestin_length = 0; heim_ipc_message_outband_t requestout = NULL; mach_msg_type_number_t requestout_length = 0; int ret, retries = 0; kern_return_t kr; struct async_client *c; /* first create the service that will catch the reply from the server */ /* XXX these object should be cached and reused */ c = malloc(sizeof(*c)); if (c == NULL) return ENOMEM; kr = mach_port_allocate(mach_task_self(), MACH_PORT_RIGHT_RECEIVE, &c->mp); if (kr != KERN_SUCCESS) return EINVAL; c->queue = dispatch_queue_create("heim-ipc-async-client", NULL); c->source = dispatch_source_create(DISPATCH_SOURCE_TYPE_MACH_RECV, c->mp, 0, c->queue); dispatch_set_context(c->queue, c); dispatch_source_set_event_handler(c->source, ^{ dispatch_mig_server(c->source, sizeof(union __RequestUnion__mheim_ado_mheim_aipc_subsystem), mheim_aipc_server); }); dispatch_source_set_cancel_handler(c->source, ^{ mach_port_mod_refs(mach_task_self(), c->mp, MACH_PORT_RIGHT_RECEIVE, -1); dispatch_release(c->queue); dispatch_release(c->source); free(c); }); c->func = func; c->userctx = userctx; dispatch_resume(c->source); /* ok, send the message */ memcpy(requestin, request->data, request->length); requestin_length = request->length; while (retries < 2) { __block mach_port_t sport; dispatch_sync(syncq, ^{ sport = ipc->server; }); ret = mheim_ipc_call_request(sport, c->mp, requestin, requestin_length, requestout, requestout_length); if (ret == MACH_SEND_INVALID_DEST) { ret = bootstrap_look_up(bootstrap_port, ipc->name, &sport); if (ret) { dispatch_source_cancel(c->source); return ret; } mach_port_deallocate(mach_task_self(), ipc->server); ipc->server = sport; retries++; } else if (ret) { dispatch_source_cancel(c->source); return ret; } else break; } if (retries >= 2) { dispatch_source_cancel(c->source); return EINVAL; } return 0; } static int mach_release(void *ctx) { struct mach_ctx *ipc = ctx; if (ipc->server != MACH_PORT_NULL) mach_port_deallocate(mach_task_self(), ipc->server); free(ipc->name); free(ipc); return 0; } #endif struct path_ctx { char *path; int fd; }; static int common_release(void *); static int connect_unix(struct path_ctx *s) { struct sockaddr_un addr; addr.sun_family = AF_UNIX; strlcpy(addr.sun_path, s->path, sizeof(addr.sun_path)); s->fd = socket(AF_UNIX, SOCK_STREAM, 0); if (s->fd < 0) return errno; rk_cloexec(s->fd); if (connect(s->fd, (struct sockaddr *)&addr, sizeof(addr)) != 0) { close(s->fd); return errno; } return 0; } static int common_path_init(const char *service, const char *file, void **ctx) { struct path_ctx *s; s = malloc(sizeof(*s)); if (s == NULL) return ENOMEM; s->fd = -1; if (asprintf(&s->path, "/var/run/.heim_%s-%s", service, file) == -1) { free(s); return ENOMEM; } *ctx = s; return 0; } static int unix_socket_init(const char *service, void **ctx) { int ret; ret = common_path_init(service, "socket", ctx); if (ret) return ret; ret = connect_unix(*ctx); if (ret) common_release(*ctx); return ret; } static int unix_socket_ipc(void *ctx, const heim_idata *req, heim_idata *rep, heim_icred *cred) { struct path_ctx *s = ctx; uint32_t len = htonl(req->length); uint32_t rv; int retval; if (cred) *cred = NULL; rep->data = NULL; rep->length = 0; if (net_write(s->fd, &len, sizeof(len)) != sizeof(len)) return -1; if (net_write(s->fd, req->data, req->length) != (ssize_t)req->length) return -1; if (net_read(s->fd, &len, sizeof(len)) != sizeof(len)) return -1; if (net_read(s->fd, &rv, sizeof(rv)) != sizeof(rv)) return -1; retval = ntohl(rv); rep->length = ntohl(len); if (rep->length > 0) { rep->data = malloc(rep->length); if (rep->data == NULL) return -1; if (net_read(s->fd, rep->data, rep->length) != (ssize_t)rep->length) return -1; } else rep->data = NULL; return retval; } int common_release(void *ctx) { struct path_ctx *s = ctx; if (s->fd >= 0) close(s->fd); free(s->path); free(s); return 0; } #ifdef HAVE_DOOR static int door_init(const char *service, void **ctx) { ret = common_path_init(context, service, "door", ctx); if (ret) return ret; ret = connect_door(*ctx); if (ret) common_release(*ctx); return ret; } static int door_ipc(void *ctx, const heim_idata *request, heim_idata *response, heim_icred *cred) { door_arg_t arg; int ret; arg.data_ptr = request->data; arg.data_size = request->length; arg.desc_ptr = NULL; arg.desc_num = 0; arg.rbuf = NULL; arg.rsize = 0; ret = door_call(fd, &arg); close(fd); if (ret != 0) return errno; response->data = malloc(arg.rsize); if (response->data == NULL) { munmap(arg.rbuf, arg.rsize); return ENOMEM; } memcpy(response->data, arg.rbuf, arg.rsize); response->length = arg.rsize; munmap(arg.rbuf, arg.rsize); return ret; } #endif struct hipc_ops { const char *prefix; int (*init)(const char *, void **); int (*release)(void *); int (*ipc)(void *,const heim_idata *, heim_idata *, heim_icred *); int (*async)(void *, const heim_idata *, void *, void (*)(void *, int, heim_idata *, heim_icred)); }; struct hipc_ops ipcs[] = { #if defined(__APPLE__) && defined(HAVE_GCD) { "MACH", mach_init, mach_release, mach_ipc, mach_async }, #endif #ifdef HAVE_DOOR { "DOOR", door_init, common_release, door_ipc, NULL } #endif { "UNIX", unix_socket_init, common_release, unix_socket_ipc, NULL } }; struct heim_ipc { struct hipc_ops *ops; void *ctx; }; int heim_ipc_init_context(const char *name, heim_ipc *ctx) { unsigned int i; int ret, any = 0; for(i = 0; i < sizeof(ipcs)/sizeof(ipcs[0]); i++) { size_t prefix_len = strlen(ipcs[i].prefix); heim_ipc c; if(strncmp(ipcs[i].prefix, name, prefix_len) == 0 && name[prefix_len] == ':') { } else if (strncmp("ANY:", name, 4) == 0) { prefix_len = 3; any = 1; } else continue; c = calloc(1, sizeof(*c)); if (c == NULL) return ENOMEM; c->ops = &ipcs[i]; ret = (c->ops->init)(name + prefix_len + 1, &c->ctx); if (ret) { free(c); if (any) continue; return ret; } *ctx = c; return 0; } return ENOENT; } void heim_ipc_free_context(heim_ipc ctx) { (ctx->ops->release)(ctx->ctx); free(ctx); } int heim_ipc_call(heim_ipc ctx, const heim_idata *snd, heim_idata *rcv, heim_icred *cred) { if (cred) *cred = NULL; return (ctx->ops->ipc)(ctx->ctx, snd, rcv, cred); } int heim_ipc_async(heim_ipc ctx, const heim_idata *snd, void *userctx, void (*func)(void *, int, heim_idata *, heim_icred)) { if (ctx->ops->async == NULL) { heim_idata rcv; heim_icred cred = NULL; int ret; ret = (ctx->ops->ipc)(ctx->ctx, snd, &rcv, &cred); (*func)(userctx, ret, &rcv, cred); heim_ipc_free_cred(cred); free(rcv.data); return ret; } else { return (ctx->ops->async)(ctx->ctx, snd, userctx, func); } } heimdal-7.5.0/lib/ipc/hi_locl.h0000644000175000017500000000512413026237312014356 0ustar niknik/* * Copyright (c) 2009 Kungliga Tekniska Hgskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Portions Copyright (c) 2009 Apple Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "config.h" #include #include #ifdef HAVE_SYS_UN_H #include #endif #include #include #include #include #include #include #ifdef HAVE_GETPEERUCRED #include #endif #include #include #include #include #include #if defined(__APPLE__) && defined(HAVE_GCD) #include #include #include #include #ifndef __APPLE_PRIVATE__ /* awe, using private interface */ typedef boolean_t (*dispatch_mig_callback_t)(mach_msg_header_t *message, mach_msg_header_t *reply); mach_msg_return_t dispatch_mig_server(dispatch_source_t ds, size_t maxmsgsz, dispatch_mig_callback_t callback); #endif #endif #include int _heim_ipc_create_cred(uid_t, gid_t, pid_t, pid_t, heim_icred *); heimdal-7.5.0/lib/ipc/tc.c0000644000175000017500000000667713026237312013364 0ustar niknik/* * Copyright (c) 2009 Kungliga Tekniska Hgskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Portions Copyright (c) 2009 Apple Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include #include #include #include #include #include #include #include static int help_flag; static int version_flag; static struct getargs args[] = { { "help", 'h', arg_flag, &help_flag, NULL, NULL }, { "version", 'v', arg_flag, &version_flag, NULL, NULL } }; static int num_args = sizeof(args) / sizeof(args[0]); static void usage(int ret) { arg_printusage (args, num_args, NULL, ""); exit (ret); } static void reply(void *ctx, int errorcode, heim_idata *rep, heim_icred cred) { printf("got reply\n"); heim_ipc_semaphore_signal((heim_isemaphore)ctx); /* tell caller we are done */ } static void test_ipc(const char *service) { heim_isemaphore s; heim_idata req, rep; heim_ipc ipc; int ret; ret = heim_ipc_init_context(service, &ipc); if (ret) errx(1, "heim_ipc_init_context: %d", ret); req.length = 0; req.data = NULL; ret = heim_ipc_call(ipc, &req, &rep, NULL); if (ret) errx(1, "heim_ipc_call: %d", ret); s = heim_ipc_semaphore_create(0); if (s == NULL) errx(1, "heim_ipc_semaphore_create"); ret = heim_ipc_async(ipc, &req, s, reply); if (ret) errx(1, "heim_ipc_async: %d", ret); heim_ipc_semaphore_wait(s, HEIM_IPC_WAIT_FOREVER); /* wait for reply to complete the work */ heim_ipc_free_context(ipc); } int main(int argc, char **argv) { int optidx = 0; setprogname(argv[0]); if (getarg(args, num_args, argc, argv, &optidx)) usage(1); if (help_flag) usage(0); if (version_flag) { print_version(NULL); exit(0); } #ifdef __APPLE__ test_ipc("MACH:org.h5l.test-ipc"); #endif test_ipc("ANY:org.h5l.test-ipc"); test_ipc("UNIX:org.h5l.test-ipc"); return 0; } heimdal-7.5.0/lib/ipc/server.c0000644000175000017500000006372713026237312014263 0ustar niknik/* * Copyright (c) 2009 Kungliga Tekniska Hgskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Portions Copyright (c) 2009 Apple Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "hi_locl.h" #include #include #define MAX_PACKET_SIZE (128 * 1024) struct heim_sipc { int (*release)(heim_sipc ctx); heim_ipc_callback callback; void *userctx; void *mech; }; #if defined(__APPLE__) && defined(HAVE_GCD) #include "heim_ipcServer.h" #include "heim_ipc_reply.h" #include "heim_ipc_async.h" static dispatch_source_t timer; static dispatch_queue_t timerq; static uint64_t timeoutvalue; static dispatch_queue_t eventq; static dispatch_queue_t workq; static void default_timer_ev(void) { exit(0); } static void (*timer_ev)(void) = default_timer_ev; static void set_timer(void) { dispatch_source_set_timer(timer, dispatch_time(DISPATCH_TIME_NOW, timeoutvalue * NSEC_PER_SEC), timeoutvalue * NSEC_PER_SEC, 1000000); } static void init_globals(void) { static dispatch_once_t once; dispatch_once(&once, ^{ timerq = dispatch_queue_create("hiem-sipc-timer-q", NULL); timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, timerq); dispatch_source_set_event_handler(timer, ^{ timer_ev(); } ); workq = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0); eventq = dispatch_queue_create("heim-ipc.event-queue", NULL); }); } static void suspend_timer(void) { dispatch_suspend(timer); } static void restart_timer(void) { dispatch_sync(timerq, ^{ set_timer(); }); dispatch_resume(timer); } struct mach_service { mach_port_t sport; dispatch_source_t source; dispatch_queue_t queue; }; struct mach_call_ctx { mach_port_t reply_port; heim_icred cred; heim_idata req; }; static void mach_complete_sync(heim_sipc_call ctx, int returnvalue, heim_idata *reply) { struct mach_call_ctx *s = (struct mach_call_ctx *)ctx; heim_ipc_message_inband_t replyin; mach_msg_type_number_t replyinCnt; heim_ipc_message_outband_t replyout; mach_msg_type_number_t replyoutCnt; kern_return_t kr; if (returnvalue) { /* on error, no reply */ replyinCnt = 0; replyout = 0; replyoutCnt = 0; kr = KERN_SUCCESS; } else if (reply->length < 2048) { replyinCnt = reply->length; memcpy(replyin, reply->data, replyinCnt); replyout = 0; replyoutCnt = 0; kr = KERN_SUCCESS; } else { replyinCnt = 0; kr = vm_read(mach_task_self(), (vm_address_t)reply->data, reply->length, (vm_address_t *)&replyout, &replyoutCnt); } mheim_ripc_call_reply(s->reply_port, returnvalue, replyin, replyinCnt, replyout, replyoutCnt); heim_ipc_free_cred(s->cred); free(s->req.data); free(s); restart_timer(); } static void mach_complete_async(heim_sipc_call ctx, int returnvalue, heim_idata *reply) { struct mach_call_ctx *s = (struct mach_call_ctx *)ctx; heim_ipc_message_inband_t replyin; mach_msg_type_number_t replyinCnt; heim_ipc_message_outband_t replyout; mach_msg_type_number_t replyoutCnt; kern_return_t kr; if (returnvalue) { /* on error, no reply */ replyinCnt = 0; replyout = 0; replyoutCnt = 0; kr = KERN_SUCCESS; } else if (reply->length < 2048) { replyinCnt = reply->length; memcpy(replyin, reply->data, replyinCnt); replyout = 0; replyoutCnt = 0; kr = KERN_SUCCESS; } else { replyinCnt = 0; kr = vm_read(mach_task_self(), (vm_address_t)reply->data, reply->length, (vm_address_t *)&replyout, &replyoutCnt); } kr = mheim_aipc_acall_reply(s->reply_port, returnvalue, replyin, replyinCnt, replyout, replyoutCnt); heim_ipc_free_cred(s->cred); free(s->req.data); free(s); restart_timer(); } kern_return_t mheim_do_call(mach_port_t server_port, audit_token_t client_creds, mach_port_t reply_port, heim_ipc_message_inband_t requestin, mach_msg_type_number_t requestinCnt, heim_ipc_message_outband_t requestout, mach_msg_type_number_t requestoutCnt, int *returnvalue, heim_ipc_message_inband_t replyin, mach_msg_type_number_t *replyinCnt, heim_ipc_message_outband_t *replyout, mach_msg_type_number_t *replyoutCnt) { heim_sipc ctx = dispatch_get_context(dispatch_get_current_queue()); struct mach_call_ctx *s; kern_return_t kr; uid_t uid; gid_t gid; pid_t pid; au_asid_t session; *replyout = NULL; *replyoutCnt = 0; *replyinCnt = 0; s = malloc(sizeof(*s)); if (s == NULL) return KERN_MEMORY_FAILURE; /* XXX */ s->reply_port = reply_port; audit_token_to_au32(client_creds, NULL, &uid, &gid, NULL, NULL, &pid, &session, NULL); kr = _heim_ipc_create_cred(uid, gid, pid, session, &s->cred); if (kr) { free(s); return kr; } suspend_timer(); if (requestinCnt) { s->req.data = malloc(requestinCnt); memcpy(s->req.data, requestin, requestinCnt); s->req.length = requestinCnt; } else { s->req.data = malloc(requestoutCnt); memcpy(s->req.data, requestout, requestoutCnt); s->req.length = requestoutCnt; } dispatch_async(workq, ^{ (ctx->callback)(ctx->userctx, &s->req, s->cred, mach_complete_sync, (heim_sipc_call)s); }); return MIG_NO_REPLY; } kern_return_t mheim_do_call_request(mach_port_t server_port, audit_token_t client_creds, mach_port_t reply_port, heim_ipc_message_inband_t requestin, mach_msg_type_number_t requestinCnt, heim_ipc_message_outband_t requestout, mach_msg_type_number_t requestoutCnt) { heim_sipc ctx = dispatch_get_context(dispatch_get_current_queue()); struct mach_call_ctx *s; kern_return_t kr; uid_t uid; gid_t gid; pid_t pid; au_asid_t session; s = malloc(sizeof(*s)); if (s == NULL) return KERN_MEMORY_FAILURE; /* XXX */ s->reply_port = reply_port; audit_token_to_au32(client_creds, NULL, &uid, &gid, NULL, NULL, &pid, &session, NULL); kr = _heim_ipc_create_cred(uid, gid, pid, session, &s->cred); if (kr) { free(s); return kr; } suspend_timer(); if (requestinCnt) { s->req.data = malloc(requestinCnt); memcpy(s->req.data, requestin, requestinCnt); s->req.length = requestinCnt; } else { s->req.data = malloc(requestoutCnt); memcpy(s->req.data, requestout, requestoutCnt); s->req.length = requestoutCnt; } dispatch_async(workq, ^{ (ctx->callback)(ctx->userctx, &s->req, s->cred, mach_complete_async, (heim_sipc_call)s); }); return KERN_SUCCESS; } static int mach_init(const char *service, mach_port_t sport, heim_sipc ctx) { struct mach_service *s; char *name; init_globals(); s = calloc(1, sizeof(*s)); if (s == NULL) return ENOMEM; asprintf(&name, "heim-ipc-mach-%s", service); s->queue = dispatch_queue_create(name, NULL); free(name); s->sport = sport; s->source = dispatch_source_create(DISPATCH_SOURCE_TYPE_MACH_RECV, s->sport, 0, s->queue); if (s->source == NULL) { dispatch_release(s->queue); free(s); return ENOMEM; } ctx->mech = s; dispatch_set_context(s->queue, ctx); dispatch_set_context(s->source, s); dispatch_source_set_event_handler(s->source, ^{ dispatch_mig_server(s->source, sizeof(union __RequestUnion__mheim_do_mheim_ipc_subsystem), mheim_ipc_server); }); dispatch_source_set_cancel_handler(s->source, ^{ heim_sipc sctx = dispatch_get_context(dispatch_get_current_queue()); struct mach_service *st = sctx->mech; mach_port_mod_refs(mach_task_self(), st->sport, MACH_PORT_RIGHT_RECEIVE, -1); dispatch_release(st->queue); dispatch_release(st->source); free(st); free(sctx); }); dispatch_resume(s->source); return 0; } static int mach_release(heim_sipc ctx) { struct mach_service *s = ctx->mech; dispatch_source_cancel(s->source); dispatch_release(s->source); return 0; } static mach_port_t mach_checkin_or_register(const char *service) { mach_port_t mp; kern_return_t kr; kr = bootstrap_check_in(bootstrap_port, service, &mp); if (kr == KERN_SUCCESS) return mp; #if __MAC_OS_X_VERSION_MIN_REQUIRED <= 1050 /* Pre SnowLeopard version */ kr = mach_port_allocate(mach_task_self(), MACH_PORT_RIGHT_RECEIVE, &mp); if (kr != KERN_SUCCESS) return MACH_PORT_NULL; kr = mach_port_insert_right(mach_task_self(), mp, mp, MACH_MSG_TYPE_MAKE_SEND); if (kr != KERN_SUCCESS) { mach_port_destroy(mach_task_self(), mp); return MACH_PORT_NULL; } kr = bootstrap_register(bootstrap_port, rk_UNCONST(service), mp); if (kr != KERN_SUCCESS) { mach_port_destroy(mach_task_self(), mp); return MACH_PORT_NULL; } return mp; #else return MACH_PORT_NULL; #endif } #endif /* __APPLE__ && HAVE_GCD */ int heim_sipc_launchd_mach_init(const char *service, heim_ipc_callback callback, void *user, heim_sipc *ctx) { #if defined(__APPLE__) && defined(HAVE_GCD) mach_port_t sport = MACH_PORT_NULL; heim_sipc c = NULL; int ret; *ctx = NULL; sport = mach_checkin_or_register(service); if (sport == MACH_PORT_NULL) { ret = ENOENT; goto error; } c = calloc(1, sizeof(*c)); if (c == NULL) { ret = ENOMEM; goto error; } c->release = mach_release; c->userctx = user; c->callback = callback; ret = mach_init(service, sport, c); if (ret) goto error; *ctx = c; return 0; error: if (c) free(c); if (sport != MACH_PORT_NULL) mach_port_mod_refs(mach_task_self(), sport, MACH_PORT_RIGHT_RECEIVE, -1); return ret; #else /* !(__APPLE__ && HAVE_GCD) */ *ctx = NULL; return EINVAL; #endif /* __APPLE__ && HAVE_GCD */ } struct client { int fd; heim_ipc_callback callback; void *userctx; int flags; #define LISTEN_SOCKET 1 #define WAITING_READ 2 #define WAITING_WRITE 4 #define WAITING_CLOSE 8 #define HTTP_REPLY 16 #define INHERIT_MASK 0xffff0000 #define INCLUDE_ERROR_CODE (1 << 16) #define ALLOW_HTTP (1<<17) #define UNIX_SOCKET (1<<18) unsigned calls; size_t ptr, len; uint8_t *inmsg; size_t olen; uint8_t *outmsg; #ifdef HAVE_GCD dispatch_source_t in; dispatch_source_t out; #endif struct { uid_t uid; gid_t gid; pid_t pid; } unixrights; }; #ifndef HAVE_GCD static unsigned num_clients = 0; static struct client **clients = NULL; #endif static void handle_read(struct client *); static void handle_write(struct client *); static int maybe_close(struct client *); /* * Update peer credentials from socket. * * SCM_CREDS can only be updated the first time there is read data to * read from the filedescriptor, so if we read do it before this * point, the cred data might not be is not there yet. */ static int update_client_creds(struct client *c) { #ifdef HAVE_GETPEERUCRED /* Solaris 10 */ { ucred_t *peercred; if (getpeerucred(c->fd, &peercred) != 0) { c->unixrights.uid = ucred_geteuid(peercred); c->unixrights.gid = ucred_getegid(peercred); c->unixrights.pid = 0; ucred_free(peercred); return 1; } } #endif #ifdef HAVE_GETPEEREID /* FreeBSD, OpenBSD */ { uid_t uid; gid_t gid; if (getpeereid(c->fd, &uid, &gid) == 0) { c->unixrights.uid = uid; c->unixrights.gid = gid; c->unixrights.pid = 0; return 1; } } #endif #if defined(SO_PEERCRED) && defined(__linux__) /* Linux */ { struct ucred pc; socklen_t pclen = sizeof(pc); if (getsockopt(c->fd, SOL_SOCKET, SO_PEERCRED, (void *)&pc, &pclen) == 0) { c->unixrights.uid = pc.uid; c->unixrights.gid = pc.gid; c->unixrights.pid = pc.pid; return 1; } } #endif #if defined(LOCAL_PEERCRED) && defined(XUCRED_VERSION) { struct xucred peercred; socklen_t peercredlen = sizeof(peercred); if (getsockopt(c->fd, LOCAL_PEERCRED, 1, (void *)&peercred, &peercredlen) == 0 && peercred.cr_version == XUCRED_VERSION) { c->unixrights.uid = peercred.cr_uid; c->unixrights.gid = peercred.cr_gid; c->unixrights.pid = 0; return 1; } } #endif #if defined(SOCKCREDSIZE) && defined(SCM_CREDS) /* NetBSD */ if (c->unixrights.uid == (uid_t)-1) { struct msghdr msg; socklen_t crmsgsize; void *crmsg; struct cmsghdr *cmp; struct sockcred *sc; memset(&msg, 0, sizeof(msg)); crmsgsize = CMSG_SPACE(SOCKCREDSIZE(NGROUPS)); if (crmsgsize == 0) return 1 ; crmsg = malloc(crmsgsize); if (crmsg == NULL) goto failed_scm_creds; memset(crmsg, 0, crmsgsize); msg.msg_control = crmsg; msg.msg_controllen = crmsgsize; if (recvmsg(c->fd, &msg, 0) < 0) { free(crmsg); goto failed_scm_creds; } if (msg.msg_controllen == 0 || (msg.msg_flags & MSG_CTRUNC) != 0) { free(crmsg); goto failed_scm_creds; } cmp = CMSG_FIRSTHDR(&msg); if (cmp->cmsg_level != SOL_SOCKET || cmp->cmsg_type != SCM_CREDS) { free(crmsg); goto failed_scm_creds; } sc = (struct sockcred *)(void *)CMSG_DATA(cmp); c->unixrights.uid = sc->sc_euid; c->unixrights.gid = sc->sc_egid; c->unixrights.pid = 0; free(crmsg); return 1; } else { /* we already got the cred, just return it */ return 1; } failed_scm_creds: #endif return 0; } static struct client * add_new_socket(int fd, int flags, heim_ipc_callback callback, void *userctx) { struct client *c; int fileflags; c = calloc(1, sizeof(*c)); if (c == NULL) return NULL; if (flags & LISTEN_SOCKET) { c->fd = fd; } else { c->fd = accept(fd, NULL, NULL); if(c->fd < 0) { free(c); return NULL; } } c->flags = flags; c->callback = callback; c->userctx = userctx; fileflags = fcntl(c->fd, F_GETFL, 0); fcntl(c->fd, F_SETFL, fileflags | O_NONBLOCK); #ifdef HAVE_GCD init_globals(); c->in = dispatch_source_create(DISPATCH_SOURCE_TYPE_READ, c->fd, 0, eventq); c->out = dispatch_source_create(DISPATCH_SOURCE_TYPE_WRITE, c->fd, 0, eventq); dispatch_source_set_event_handler(c->in, ^{ int rw = (c->flags & WAITING_WRITE); handle_read(c); if (rw == 0 && (c->flags & WAITING_WRITE)) dispatch_resume(c->out); if ((c->flags & WAITING_READ) == 0) dispatch_suspend(c->in); maybe_close(c); }); dispatch_source_set_event_handler(c->out, ^{ handle_write(c); if ((c->flags & WAITING_WRITE) == 0) { dispatch_suspend(c->out); } maybe_close(c); }); dispatch_resume(c->in); #else clients = erealloc(clients, sizeof(clients[0]) * (num_clients + 1)); clients[num_clients] = c; num_clients++; #endif return c; } static int maybe_close(struct client *c) { if (c->calls != 0) return 0; if (c->flags & (WAITING_READ|WAITING_WRITE)) return 0; #ifdef HAVE_GCD dispatch_source_cancel(c->in); if ((c->flags & WAITING_READ) == 0) dispatch_resume(c->in); dispatch_release(c->in); dispatch_source_cancel(c->out); if ((c->flags & WAITING_WRITE) == 0) dispatch_resume(c->out); dispatch_release(c->out); #endif close(c->fd); /* ref count fd close */ free(c); return 1; } struct socket_call { heim_idata in; struct client *c; heim_icred cred; }; static void output_data(struct client *c, const void *data, size_t len) { if (c->olen + len < c->olen) abort(); c->outmsg = erealloc(c->outmsg, c->olen + len); memcpy(&c->outmsg[c->olen], data, len); c->olen += len; c->flags |= WAITING_WRITE; } static void socket_complete(heim_sipc_call ctx, int returnvalue, heim_idata *reply) { struct socket_call *sc = (struct socket_call *)ctx; struct client *c = sc->c; /* double complete ? */ if (c == NULL) abort(); if ((c->flags & WAITING_CLOSE) == 0) { uint32_t u32; /* length */ u32 = htonl(reply->length); output_data(c, &u32, sizeof(u32)); /* return value */ if (c->flags & INCLUDE_ERROR_CODE) { u32 = htonl(returnvalue); output_data(c, &u32, sizeof(u32)); } /* data */ output_data(c, reply->data, reply->length); /* if HTTP, close connection */ if (c->flags & HTTP_REPLY) { c->flags |= WAITING_CLOSE; c->flags &= ~WAITING_READ; } } c->calls--; if (sc->cred) heim_ipc_free_cred(sc->cred); free(sc->in.data); sc->c = NULL; /* so we can catch double complete */ free(sc); maybe_close(c); } /* remove HTTP %-quoting from buf */ static int de_http(char *buf) { unsigned char *p, *q; for(p = q = (unsigned char *)buf; *p; p++, q++) { if(*p == '%' && isxdigit(p[1]) && isxdigit(p[2])) { unsigned int x; if(sscanf((char *)p + 1, "%2x", &x) != 1) return -1; *q = x; p += 2; } else *q = *p; } *q = '\0'; return 0; } static struct socket_call * handle_http_tcp(struct client *c) { struct socket_call *cs; char *s, *p, *t; void *data; char *proto; int len; s = (char *)c->inmsg; p = strstr(s, "\r\n"); if (p == NULL) return NULL; *p = 0; p = NULL; t = strtok_r(s, " \t", &p); if (t == NULL) return NULL; t = strtok_r(NULL, " \t", &p); if (t == NULL) return NULL; data = malloc(strlen(t)); if (data == NULL) return NULL; if(*t == '/') t++; if(de_http(t) != 0) { free(data); return NULL; } proto = strtok_r(NULL, " \t", &p); if (proto == NULL) { free(data); return NULL; } len = rk_base64_decode(t, data); if(len <= 0){ const char *msg = " 404 Not found\r\n" "Server: Heimdal/" VERSION "\r\n" "Cache-Control: no-cache\r\n" "Pragma: no-cache\r\n" "Content-type: text/html\r\n" "Content-transfer-encoding: 8bit\r\n\r\n" "404 Not found\r\n" "

404 Not found

\r\n" "That page doesn't exist, maybe you are looking for " "Heimdal?\r\n"; free(data); output_data(c, proto, strlen(proto)); output_data(c, msg, strlen(msg)); return NULL; } cs = emalloc(sizeof(*cs)); cs->c = c; cs->in.data = data; cs->in.length = len; c->ptr = 0; { const char *msg = " 200 OK\r\n" "Server: Heimdal/" VERSION "\r\n" "Cache-Control: no-cache\r\n" "Pragma: no-cache\r\n" "Content-type: application/octet-stream\r\n" "Content-transfer-encoding: binary\r\n\r\n"; output_data(c, proto, strlen(proto)); output_data(c, msg, strlen(msg)); } return cs; } static void handle_read(struct client *c) { ssize_t len; uint32_t dlen; if (c->flags & LISTEN_SOCKET) { add_new_socket(c->fd, WAITING_READ | (c->flags & INHERIT_MASK), c->callback, c->userctx); return; } if (c->ptr - c->len < 1024) { c->inmsg = erealloc(c->inmsg, c->len + 1024); c->len += 1024; } len = read(c->fd, c->inmsg + c->ptr, c->len - c->ptr); if (len <= 0) { c->flags |= WAITING_CLOSE; c->flags &= ~WAITING_READ; return; } c->ptr += len; if (c->ptr > c->len) abort(); while (c->ptr >= sizeof(dlen)) { struct socket_call *cs; if((c->flags & ALLOW_HTTP) && c->ptr >= 4 && strncmp((char *)c->inmsg, "GET ", 4) == 0 && strncmp((char *)c->inmsg + c->ptr - 4, "\r\n\r\n", 4) == 0) { /* remove the trailing \r\n\r\n so the string is NUL terminated */ c->inmsg[c->ptr - 4] = '\0'; c->flags |= HTTP_REPLY; cs = handle_http_tcp(c); if (cs == NULL) { c->flags |= WAITING_CLOSE; c->flags &= ~WAITING_READ; break; } } else { memcpy(&dlen, c->inmsg, sizeof(dlen)); dlen = ntohl(dlen); if (dlen > MAX_PACKET_SIZE) { c->flags |= WAITING_CLOSE; c->flags &= ~WAITING_READ; return; } if (dlen > c->ptr - sizeof(dlen)) { break; } cs = emalloc(sizeof(*cs)); cs->c = c; cs->in.data = emalloc(dlen); memcpy(cs->in.data, c->inmsg + sizeof(dlen), dlen); cs->in.length = dlen; c->ptr -= sizeof(dlen) + dlen; memmove(c->inmsg, c->inmsg + sizeof(dlen) + dlen, c->ptr); } c->calls++; if ((c->flags & UNIX_SOCKET) != 0) { if (update_client_creds(c)) _heim_ipc_create_cred(c->unixrights.uid, c->unixrights.gid, c->unixrights.pid, -1, &cs->cred); } c->callback(c->userctx, &cs->in, cs->cred, socket_complete, (heim_sipc_call)cs); } } static void handle_write(struct client *c) { ssize_t len; len = write(c->fd, c->outmsg, c->olen); if (len <= 0) { c->flags |= WAITING_CLOSE; c->flags &= ~(WAITING_WRITE); } else if (c->olen != (size_t)len) { memmove(&c->outmsg[0], &c->outmsg[len], c->olen - len); c->olen -= len; } else { c->olen = 0; free(c->outmsg); c->outmsg = NULL; c->flags &= ~(WAITING_WRITE); } } #ifndef HAVE_GCD static void process_loop(void) { struct pollfd *fds; unsigned n; unsigned num_fds; while (num_clients > 0) { fds = malloc(num_clients * sizeof(fds[0])); if(fds == NULL) abort(); num_fds = num_clients; for (n = 0 ; n < num_fds; n++) { fds[n].fd = clients[n]->fd; fds[n].events = 0; if (clients[n]->flags & WAITING_READ) fds[n].events |= POLLIN; if (clients[n]->flags & WAITING_WRITE) fds[n].events |= POLLOUT; fds[n].revents = 0; } while (poll(fds, num_fds, -1) == -1) { if (errno == EINTR || errno == EAGAIN) continue; err(1, "poll(2) failed"); } for (n = 0 ; n < num_fds; n++) { if (clients[n] == NULL) continue; if (fds[n].revents & POLLERR) { clients[n]->flags |= WAITING_CLOSE; continue; } if (fds[n].revents & POLLIN) handle_read(clients[n]); if (fds[n].revents & POLLOUT) handle_write(clients[n]); } n = 0; while (n < num_clients) { struct client *c = clients[n]; if (maybe_close(c)) { if (n < num_clients - 1) clients[n] = clients[num_clients - 1]; num_clients--; } else n++; } free(fds); } } #endif static int socket_release(heim_sipc ctx) { struct client *c = ctx->mech; c->flags |= WAITING_CLOSE; return 0; } int heim_sipc_stream_listener(int fd, int type, heim_ipc_callback callback, void *user, heim_sipc *ctx) { heim_sipc ct = calloc(1, sizeof(*ct)); struct client *c; if ((type & HEIM_SIPC_TYPE_IPC) && (type & (HEIM_SIPC_TYPE_UINT32|HEIM_SIPC_TYPE_HTTP))) return EINVAL; switch (type) { case HEIM_SIPC_TYPE_IPC: c = add_new_socket(fd, LISTEN_SOCKET|WAITING_READ|INCLUDE_ERROR_CODE, callback, user); break; case HEIM_SIPC_TYPE_UINT32: c = add_new_socket(fd, LISTEN_SOCKET|WAITING_READ, callback, user); break; case HEIM_SIPC_TYPE_HTTP: case HEIM_SIPC_TYPE_UINT32|HEIM_SIPC_TYPE_HTTP: c = add_new_socket(fd, LISTEN_SOCKET|WAITING_READ|ALLOW_HTTP, callback, user); break; default: free(ct); return EINVAL; } ct->mech = c; ct->release = socket_release; c->unixrights.uid = (uid_t) -1; c->unixrights.gid = (gid_t) -1; c->unixrights.pid = (pid_t) 0; *ctx = ct; return 0; } int heim_sipc_service_unix(const char *service, heim_ipc_callback callback, void *user, heim_sipc *ctx) { struct sockaddr_un un; int fd, ret; un.sun_family = AF_UNIX; snprintf(un.sun_path, sizeof(un.sun_path), "/var/run/.heim_%s-socket", service); fd = socket(AF_UNIX, SOCK_STREAM, 0); if (fd < 0) return errno; socket_set_reuseaddr(fd, 1); #ifdef LOCAL_CREDS { int one = 1; setsockopt(fd, 0, LOCAL_CREDS, (void *)&one, sizeof(one)); } #endif unlink(un.sun_path); if (bind(fd, (struct sockaddr *)&un, sizeof(un)) < 0) { close(fd); return errno; } if (listen(fd, SOMAXCONN) < 0) { close(fd); return errno; } chmod(un.sun_path, 0666); ret = heim_sipc_stream_listener(fd, HEIM_SIPC_TYPE_IPC, callback, user, ctx); if (ret == 0) { struct client *c = (*ctx)->mech; c->flags |= UNIX_SOCKET; } return ret; } /** * Set the idle timeout value * The timeout event handler is triggered recurrently every idle * period `t'. The default action is rather draconian and just calls * exit(0), so you might want to change this to something more * graceful using heim_sipc_set_timeout_handler(). */ void heim_sipc_timeout(time_t t) { #ifdef HAVE_GCD static dispatch_once_t timeoutonce; init_globals(); dispatch_sync(timerq, ^{ timeoutvalue = t; set_timer(); }); dispatch_once(&timeoutonce, ^{ dispatch_resume(timer); }); #else abort(); #endif } /** * Set the timeout event handler * * Replaces the default idle timeout action. */ void heim_sipc_set_timeout_handler(void (*func)(void)) { #ifdef HAVE_GCD init_globals(); dispatch_sync(timerq, ^{ timer_ev = func; }); #else abort(); #endif } void heim_sipc_free_context(heim_sipc ctx) { (ctx->release)(ctx); } void heim_ipc_main(void) { #ifdef HAVE_GCD dispatch_main(); #else process_loop(); #endif } heimdal-7.5.0/lib/ipc/Makefile.am0000644000175000017500000000417513026237312014635 0ustar niknikinclude $(top_srcdir)/Makefile.am.common noinst_LTLIBRARIES = libheim-ipcc.la libheim-ipcs.la dist_libheim_ipcc_la_SOURCES = hi_locl.h heim_ipc_types.h client.c common.c dist_libheim_ipcs_la_SOURCES = hi_locl.h heim_ipc_types.h server.c common.c include_HEADERS = heim-ipc.h ## ## Enable when this is not a noinst_ library ## #libheim_ipcc_la_LDFLAGS = -version-info 0:0:0 #libheim_ipcs_la_LDFLAGS = -version-info 0:0:0 # #if versionscript #libheim_ipcc_la_LDFLAGS += $(LDFLAGS_VERSION_SCRIPT)$(srcdir)/version-scriptc.map #libheim_ipcs_la_LDFLAGS += $(LDFLAGS_VERSION_SCRIPT)$(srcdir)/version-scripts.map #endif libheim_ipcc_la_LIBADD = \ $(LIB_heimbase) \ $(LIB_roken) \ $(PTHREAD_LIBADD) libheim_ipcs_la_LIBADD = $(libheim_ipcc_la_LIBADD) TESTS = $(check_PROGRAMS) noinst_PROGRAMS = tc ts ts-http ts_LDADD = libheim-ipcs.la $(LIB_roken) ts_http_LDADD = $(ts_LDADD) tc_LDADD = libheim-ipcc.la $(LIB_roken) EXTRA_DIST = heim_ipc.defs heim_ipc_async.defs heim_ipc_reply.defs if have_gcd heim_ipc.h heim_ipcUser.c heim_ipcServer.c heim_ipcServer.h: heim_ipc.defs mig -header heim_ipc.h -user heim_ipcUser.c -sheader heim_ipcServer.h -server heim_ipcServer.c -I$(srcdir) $(srcdir)/heim_ipc.defs heim_ipc_async.h heim_ipc_asyncUser.c heim_ipc_asyncServer.c heim_ipc_asyncServer.h: heim_ipc_async.defs mig -header heim_ipc_async.h -user heim_ipc_asyncUser.c -sheader heim_ipc_asyncServer.h -server heim_ipc_asyncServer.c -I$(srcdir) $(srcdir)/heim_ipc_async.defs heim_ipc_reply.h heim_ipc_replyUser.c: heim_ipc_reply.defs mig -header heim_ipc_reply.h -user heim_ipc_replyUser.c -sheader /dev/null -server /dev/null -I$(srcdir) $(srcdir)/heim_ipc_reply.defs built_ipcc = heim_ipc.h heim_ipcUser.c built_ipcc += heim_ipc_asyncServer.c heim_ipc_asyncServer.h nodist_libheim_ipcc_la_SOURCES = $(built_ipcc) built_ipcs = heim_ipcServer.c heim_ipcServer.h built_ipcs += heim_ipc_asyncUser.c heim_ipc_async.h built_ipcs += heim_ipc_reply.h heim_ipc_replyUser.c nodist_libheim_ipcs_la_SOURCES = $(built_ipcs) libheim_ipcs_la_LIBADD += -lbsm CLEANFILES = $(built_ipcc) $(built_ipcs) $(srcdir)/client.c: $(built_ipcc) $(srcdir)/server.c: $(built_ipcs) endif heimdal-7.5.0/lib/ipc/heim_ipc.defs0000644000175000017500000000504612136107750015222 0ustar niknik/* * Copyright (c) 2009 Kungliga Tekniska Hgskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Portions Copyright (c) 2009 Apple Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include #include type heim_ipc_message_inband_t = array [ * : 2048 ] of char; type heim_ipc_message_outband_t = array [] of char; import "heim_ipc_types.h"; subsystem mheim_ipc 1; userprefix mheim_ipc_; serverprefix mheim_do_; routine call( server_port : mach_port_t; ServerAuditToken client_creds : audit_token_t; sreplyport reply_port : mach_port_make_send_once_t; in requestin : heim_ipc_message_inband_t; in requestout : heim_ipc_message_outband_t; out returnvalue : int; out replyin : heim_ipc_message_inband_t; out replyout : heim_ipc_message_outband_t, dealloc); simpleroutine call_request( server_port : mach_port_t; ServerAuditToken client_creds : audit_token_t; in reply_to : mach_port_make_send_once_t; in requestin : heim_ipc_message_inband_t; in requestout : heim_ipc_message_outband_t); heimdal-7.5.0/lib/ipc/Makefile.in0000644000175000017500000014101013212444522014634 0ustar niknik# Makefile.in generated by automake 1.15.1 from Makefile.am. # @configure_input@ # Copyright (C) 1994-2017 Free Software Foundation, Inc. # This Makefile.in is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, # with or without modifications, as long as this notice is preserved. # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY, to the extent permitted by law; without # even the implied warranty of MERCHANTABILITY or FITNESS FOR A # PARTICULAR PURPOSE. @SET_MAKE@ # $Id$ # $Id$ VPATH = @srcdir@ am__is_gnu_make = { \ if test -z '$(MAKELEVEL)'; then \ false; \ elif test -n '$(MAKE_HOST)'; then \ true; \ elif test -n '$(MAKE_VERSION)' && test -n '$(CURDIR)'; then \ true; \ else \ false; \ fi; \ } am__make_running_with_option = \ case $${target_option-} in \ ?) ;; \ *) echo "am__make_running_with_option: internal error: invalid" \ "target option '$${target_option-}' specified" >&2; \ exit 1;; \ esac; \ has_opt=no; \ sane_makeflags=$$MAKEFLAGS; \ if $(am__is_gnu_make); then \ sane_makeflags=$$MFLAGS; \ else \ case $$MAKEFLAGS in \ *\\[\ \ ]*) \ bs=\\; \ sane_makeflags=`printf '%s\n' "$$MAKEFLAGS" \ | sed "s/$$bs$$bs[$$bs $$bs ]*//g"`;; \ esac; \ fi; \ skip_next=no; \ strip_trailopt () \ { \ flg=`printf '%s\n' "$$flg" | sed "s/$$1.*$$//"`; \ }; \ for flg in $$sane_makeflags; do \ test $$skip_next = yes && { skip_next=no; continue; }; \ case $$flg in \ *=*|--*) continue;; \ -*I) strip_trailopt 'I'; skip_next=yes;; \ -*I?*) strip_trailopt 'I';; \ -*O) strip_trailopt 'O'; skip_next=yes;; \ -*O?*) strip_trailopt 'O';; \ -*l) strip_trailopt 'l'; skip_next=yes;; \ -*l?*) strip_trailopt 'l';; \ -[dEDm]) skip_next=yes;; \ -[JT]) skip_next=yes;; \ esac; \ case $$flg in \ *$$target_option*) has_opt=yes; break;; \ esac; \ done; \ test $$has_opt = yes am__make_dryrun = (target_option=n; $(am__make_running_with_option)) am__make_keepgoing = (target_option=k; $(am__make_running_with_option)) pkgdatadir = $(datadir)/@PACKAGE@ pkgincludedir = $(includedir)/@PACKAGE@ pkglibdir = $(libdir)/@PACKAGE@ pkglibexecdir = $(libexecdir)/@PACKAGE@ am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd install_sh_DATA = $(install_sh) -c -m 644 install_sh_PROGRAM = $(install_sh) -c install_sh_SCRIPT = $(install_sh) -c INSTALL_HEADER = $(INSTALL_DATA) transform = $(program_transform_name) NORMAL_INSTALL = : PRE_INSTALL = : POST_INSTALL = : NORMAL_UNINSTALL = : PRE_UNINSTALL = : POST_UNINSTALL = : build_triplet = @build@ host_triplet = @host@ TESTS = noinst_PROGRAMS = tc$(EXEEXT) ts$(EXEEXT) ts-http$(EXEEXT) @have_gcd_TRUE@am__append_1 = -lbsm subdir = lib/ipc ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 am__aclocal_m4_deps = $(top_srcdir)/cf/aix.m4 \ $(top_srcdir)/cf/auth-modules.m4 \ $(top_srcdir)/cf/broken-getaddrinfo.m4 \ $(top_srcdir)/cf/broken-glob.m4 \ $(top_srcdir)/cf/broken-realloc.m4 \ $(top_srcdir)/cf/broken-snprintf.m4 $(top_srcdir)/cf/broken.m4 \ $(top_srcdir)/cf/broken2.m4 $(top_srcdir)/cf/c-attribute.m4 \ $(top_srcdir)/cf/capabilities.m4 \ $(top_srcdir)/cf/check-compile-et.m4 \ $(top_srcdir)/cf/check-getpwnam_r-posix.m4 \ $(top_srcdir)/cf/check-man.m4 \ $(top_srcdir)/cf/check-netinet-ip-and-tcp.m4 \ $(top_srcdir)/cf/check-type-extra.m4 \ $(top_srcdir)/cf/check-var.m4 $(top_srcdir)/cf/crypto.m4 \ $(top_srcdir)/cf/db.m4 $(top_srcdir)/cf/destdirs.m4 \ $(top_srcdir)/cf/dispatch.m4 $(top_srcdir)/cf/dlopen.m4 \ $(top_srcdir)/cf/find-func-no-libs.m4 \ $(top_srcdir)/cf/find-func-no-libs2.m4 \ $(top_srcdir)/cf/find-func.m4 \ $(top_srcdir)/cf/find-if-not-broken.m4 \ $(top_srcdir)/cf/framework-security.m4 \ $(top_srcdir)/cf/have-struct-field.m4 \ $(top_srcdir)/cf/have-type.m4 $(top_srcdir)/cf/irix.m4 \ $(top_srcdir)/cf/krb-bigendian.m4 \ $(top_srcdir)/cf/krb-func-getlogin.m4 \ $(top_srcdir)/cf/krb-ipv6.m4 $(top_srcdir)/cf/krb-prog-ln-s.m4 \ $(top_srcdir)/cf/krb-prog-perl.m4 \ $(top_srcdir)/cf/krb-readline.m4 \ $(top_srcdir)/cf/krb-struct-spwd.m4 \ $(top_srcdir)/cf/krb-struct-winsize.m4 \ $(top_srcdir)/cf/largefile.m4 $(top_srcdir)/cf/libtool.m4 \ $(top_srcdir)/cf/ltoptions.m4 $(top_srcdir)/cf/ltsugar.m4 \ $(top_srcdir)/cf/ltversion.m4 $(top_srcdir)/cf/lt~obsolete.m4 \ $(top_srcdir)/cf/mips-abi.m4 $(top_srcdir)/cf/misc.m4 \ $(top_srcdir)/cf/need-proto.m4 $(top_srcdir)/cf/osfc2.m4 \ $(top_srcdir)/cf/otp.m4 $(top_srcdir)/cf/pkg.m4 \ $(top_srcdir)/cf/proto-compat.m4 $(top_srcdir)/cf/pthreads.m4 \ $(top_srcdir)/cf/resolv.m4 $(top_srcdir)/cf/retsigtype.m4 \ $(top_srcdir)/cf/roken-frag.m4 \ $(top_srcdir)/cf/socket-wrapper.m4 $(top_srcdir)/cf/sunos.m4 \ $(top_srcdir)/cf/telnet.m4 $(top_srcdir)/cf/test-package.m4 \ $(top_srcdir)/cf/version-script.m4 $(top_srcdir)/cf/wflags.m4 \ $(top_srcdir)/cf/win32.m4 $(top_srcdir)/cf/with-all.m4 \ $(top_srcdir)/acinclude.m4 $(top_srcdir)/configure.ac am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \ $(ACLOCAL_M4) DIST_COMMON = $(srcdir)/Makefile.am $(include_HEADERS) \ $(am__DIST_COMMON) mkinstalldirs = $(install_sh) -d CONFIG_HEADER = $(top_builddir)/include/config.h CONFIG_CLEAN_FILES = CONFIG_CLEAN_VPATH_FILES = LTLIBRARIES = $(noinst_LTLIBRARIES) am__DEPENDENCIES_1 = libheim_ipcc_la_DEPENDENCIES = $(LIB_heimbase) $(am__DEPENDENCIES_1) \ $(am__DEPENDENCIES_1) dist_libheim_ipcc_la_OBJECTS = client.lo common.lo @have_gcd_TRUE@am__objects_1 = heim_ipcUser.lo heim_ipc_asyncServer.lo @have_gcd_TRUE@nodist_libheim_ipcc_la_OBJECTS = $(am__objects_1) libheim_ipcc_la_OBJECTS = $(dist_libheim_ipcc_la_OBJECTS) \ $(nodist_libheim_ipcc_la_OBJECTS) AM_V_lt = $(am__v_lt_@AM_V@) am__v_lt_ = $(am__v_lt_@AM_DEFAULT_V@) am__v_lt_0 = --silent am__v_lt_1 = am__DEPENDENCIES_2 = $(LIB_heimbase) $(am__DEPENDENCIES_1) \ $(am__DEPENDENCIES_1) libheim_ipcs_la_DEPENDENCIES = $(am__DEPENDENCIES_2) \ $(am__DEPENDENCIES_1) dist_libheim_ipcs_la_OBJECTS = server.lo common.lo @have_gcd_TRUE@am__objects_2 = heim_ipcServer.lo heim_ipc_asyncUser.lo \ @have_gcd_TRUE@ heim_ipc_replyUser.lo @have_gcd_TRUE@nodist_libheim_ipcs_la_OBJECTS = $(am__objects_2) libheim_ipcs_la_OBJECTS = $(dist_libheim_ipcs_la_OBJECTS) \ $(nodist_libheim_ipcs_la_OBJECTS) PROGRAMS = $(noinst_PROGRAMS) tc_SOURCES = tc.c tc_OBJECTS = tc.$(OBJEXT) tc_DEPENDENCIES = libheim-ipcc.la $(am__DEPENDENCIES_1) ts_SOURCES = ts.c ts_OBJECTS = ts.$(OBJEXT) ts_DEPENDENCIES = libheim-ipcs.la $(am__DEPENDENCIES_1) ts_http_SOURCES = ts-http.c ts_http_OBJECTS = ts-http.$(OBJEXT) am__DEPENDENCIES_3 = libheim-ipcs.la $(am__DEPENDENCIES_1) ts_http_DEPENDENCIES = $(am__DEPENDENCIES_3) AM_V_P = $(am__v_P_@AM_V@) am__v_P_ = $(am__v_P_@AM_DEFAULT_V@) am__v_P_0 = false am__v_P_1 = : AM_V_GEN = $(am__v_GEN_@AM_V@) am__v_GEN_ = $(am__v_GEN_@AM_DEFAULT_V@) am__v_GEN_0 = @echo " GEN " $@; am__v_GEN_1 = AM_V_at = $(am__v_at_@AM_V@) am__v_at_ = $(am__v_at_@AM_DEFAULT_V@) am__v_at_0 = @ am__v_at_1 = depcomp = $(SHELL) $(top_srcdir)/depcomp am__depfiles_maybe = depfiles am__mv = mv -f COMPILE = $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) \ $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) LTCOMPILE = $(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) \ $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) \ $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) \ $(AM_CFLAGS) $(CFLAGS) AM_V_CC = $(am__v_CC_@AM_V@) am__v_CC_ = $(am__v_CC_@AM_DEFAULT_V@) am__v_CC_0 = @echo " CC " $@; am__v_CC_1 = CCLD = $(CC) LINK = $(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) \ $(LIBTOOLFLAGS) --mode=link $(CCLD) $(AM_CFLAGS) $(CFLAGS) \ $(AM_LDFLAGS) $(LDFLAGS) -o $@ AM_V_CCLD = $(am__v_CCLD_@AM_V@) am__v_CCLD_ = $(am__v_CCLD_@AM_DEFAULT_V@) am__v_CCLD_0 = @echo " CCLD " $@; am__v_CCLD_1 = SOURCES = $(dist_libheim_ipcc_la_SOURCES) \ $(nodist_libheim_ipcc_la_SOURCES) \ $(dist_libheim_ipcs_la_SOURCES) \ $(nodist_libheim_ipcs_la_SOURCES) tc.c ts.c ts-http.c DIST_SOURCES = $(dist_libheim_ipcc_la_SOURCES) \ $(dist_libheim_ipcs_la_SOURCES) tc.c ts.c ts-http.c am__can_run_installinfo = \ case $$AM_UPDATE_INFO_DIR in \ n|no|NO) false;; \ *) (install-info --version) >/dev/null 2>&1;; \ esac am__vpath_adj_setup = srcdirstrip=`echo "$(srcdir)" | sed 's|.|.|g'`; am__vpath_adj = case $$p in \ $(srcdir)/*) f=`echo "$$p" | sed "s|^$$srcdirstrip/||"`;; \ *) f=$$p;; \ esac; am__strip_dir = f=`echo $$p | sed -e 's|^.*/||'`; am__install_max = 40 am__nobase_strip_setup = \ srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*|]/\\\\&/g'` am__nobase_strip = \ for p in $$list; do echo "$$p"; done | sed -e "s|$$srcdirstrip/||" am__nobase_list = $(am__nobase_strip_setup); \ for p in $$list; do echo "$$p $$p"; done | \ sed "s| $$srcdirstrip/| |;"' / .*\//!s/ .*/ ./; s,\( .*\)/[^/]*$$,\1,' | \ $(AWK) 'BEGIN { files["."] = "" } { files[$$2] = files[$$2] " " $$1; \ if (++n[$$2] == $(am__install_max)) \ { print $$2, files[$$2]; n[$$2] = 0; files[$$2] = "" } } \ END { for (dir in files) print dir, files[dir] }' am__base_list = \ sed '$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;s/\n/ /g' | \ sed '$$!N;$$!N;$$!N;$$!N;s/\n/ /g' am__uninstall_files_from_dir = { \ test -z "$$files" \ || { test ! -d "$$dir" && test ! -f "$$dir" && test ! -r "$$dir"; } \ || { echo " ( cd '$$dir' && rm -f" $$files ")"; \ $(am__cd) "$$dir" && rm -f $$files; }; \ } am__installdirs = "$(DESTDIR)$(includedir)" HEADERS = $(include_HEADERS) am__tagged_files = $(HEADERS) $(SOURCES) $(TAGS_FILES) $(LISP) # Read a list of newline-separated strings from the standard input, # and print each of them once, without duplicates. Input order is # *not* preserved. am__uniquify_input = $(AWK) '\ BEGIN { nonempty = 0; } \ { items[$$0] = 1; nonempty = 1; } \ END { if (nonempty) { for (i in items) print i; }; } \ ' # Make sure the list of sources is unique. This is necessary because, # e.g., the same source file might be shared among _SOURCES variables # for different programs/libraries. am__define_uniq_tagged_files = \ list='$(am__tagged_files)'; \ unique=`for i in $$list; do \ if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ done | $(am__uniquify_input)` ETAGS = etags CTAGS = ctags am__tty_colors_dummy = \ mgn= red= grn= lgn= blu= brg= std=; \ am__color_tests=no am__tty_colors = { \ $(am__tty_colors_dummy); \ if test "X$(AM_COLOR_TESTS)" = Xno; then \ am__color_tests=no; \ elif test "X$(AM_COLOR_TESTS)" = Xalways; then \ am__color_tests=yes; \ elif test "X$$TERM" != Xdumb && { test -t 1; } 2>/dev/null; then \ am__color_tests=yes; \ fi; \ if test $$am__color_tests = yes; then \ red=''; \ grn=''; \ lgn=''; \ blu=''; \ mgn=''; \ brg=''; \ std=''; \ fi; \ } am__recheck_rx = ^[ ]*:recheck:[ ]* am__global_test_result_rx = ^[ ]*:global-test-result:[ ]* am__copy_in_global_log_rx = ^[ ]*:copy-in-global-log:[ ]* # A command that, given a newline-separated list of test names on the # standard input, print the name of the tests that are to be re-run # upon "make recheck". am__list_recheck_tests = $(AWK) '{ \ recheck = 1; \ while ((rc = (getline line < ($$0 ".trs"))) != 0) \ { \ if (rc < 0) \ { \ if ((getline line2 < ($$0 ".log")) < 0) \ recheck = 0; \ break; \ } \ else if (line ~ /$(am__recheck_rx)[nN][Oo]/) \ { \ recheck = 0; \ break; \ } \ else if (line ~ /$(am__recheck_rx)[yY][eE][sS]/) \ { \ break; \ } \ }; \ if (recheck) \ print $$0; \ close ($$0 ".trs"); \ close ($$0 ".log"); \ }' # A command that, given a newline-separated list of test names on the # standard input, create the global log from their .trs and .log files. am__create_global_log = $(AWK) ' \ function fatal(msg) \ { \ print "fatal: making $@: " msg | "cat >&2"; \ exit 1; \ } \ function rst_section(header) \ { \ print header; \ len = length(header); \ for (i = 1; i <= len; i = i + 1) \ printf "="; \ printf "\n\n"; \ } \ { \ copy_in_global_log = 1; \ global_test_result = "RUN"; \ while ((rc = (getline line < ($$0 ".trs"))) != 0) \ { \ if (rc < 0) \ fatal("failed to read from " $$0 ".trs"); \ if (line ~ /$(am__global_test_result_rx)/) \ { \ sub("$(am__global_test_result_rx)", "", line); \ sub("[ ]*$$", "", line); \ global_test_result = line; \ } \ else if (line ~ /$(am__copy_in_global_log_rx)[nN][oO]/) \ copy_in_global_log = 0; \ }; \ if (copy_in_global_log) \ { \ rst_section(global_test_result ": " $$0); \ while ((rc = (getline line < ($$0 ".log"))) != 0) \ { \ if (rc < 0) \ fatal("failed to read from " $$0 ".log"); \ print line; \ }; \ printf "\n"; \ }; \ close ($$0 ".trs"); \ close ($$0 ".log"); \ }' # Restructured Text title. am__rst_title = { sed 's/.*/ & /;h;s/./=/g;p;x;s/ *$$//;p;g' && echo; } # Solaris 10 'make', and several other traditional 'make' implementations, # pass "-e" to $(SHELL), and POSIX 2008 even requires this. Work around it # by disabling -e (using the XSI extension "set +e") if it's set. am__sh_e_setup = case $$- in *e*) set +e;; esac # Default flags passed to test drivers. am__common_driver_flags = \ --color-tests "$$am__color_tests" \ --enable-hard-errors "$$am__enable_hard_errors" \ --expect-failure "$$am__expect_failure" # To be inserted before the command running the test. Creates the # directory for the log if needed. Stores in $dir the directory # containing $f, in $tst the test, in $log the log. Executes the # developer- defined test setup AM_TESTS_ENVIRONMENT (if any), and # passes TESTS_ENVIRONMENT. Set up options for the wrapper that # will run the test scripts (or their associated LOG_COMPILER, if # thy have one). am__check_pre = \ $(am__sh_e_setup); \ $(am__vpath_adj_setup) $(am__vpath_adj) \ $(am__tty_colors); \ srcdir=$(srcdir); export srcdir; \ case "$@" in \ */*) am__odir=`echo "./$@" | sed 's|/[^/]*$$||'`;; \ *) am__odir=.;; \ esac; \ test "x$$am__odir" = x"." || test -d "$$am__odir" \ || $(MKDIR_P) "$$am__odir" || exit $$?; \ if test -f "./$$f"; then dir=./; \ elif test -f "$$f"; then dir=; \ else dir="$(srcdir)/"; fi; \ tst=$$dir$$f; log='$@'; \ if test -n '$(DISABLE_HARD_ERRORS)'; then \ am__enable_hard_errors=no; \ else \ am__enable_hard_errors=yes; \ fi; \ case " $(XFAIL_TESTS) " in \ *[\ \ ]$$f[\ \ ]* | *[\ \ ]$$dir$$f[\ \ ]*) \ am__expect_failure=yes;; \ *) \ am__expect_failure=no;; \ esac; \ $(AM_TESTS_ENVIRONMENT) $(TESTS_ENVIRONMENT) # A shell command to get the names of the tests scripts with any registered # extension removed (i.e., equivalently, the names of the test logs, with # the '.log' extension removed). The result is saved in the shell variable # '$bases'. This honors runtime overriding of TESTS and TEST_LOGS. Sadly, # we cannot use something simpler, involving e.g., "$(TEST_LOGS:.log=)", # since that might cause problem with VPATH rewrites for suffix-less tests. # See also 'test-harness-vpath-rewrite.sh' and 'test-trs-basic.sh'. am__set_TESTS_bases = \ bases='$(TEST_LOGS)'; \ bases=`for i in $$bases; do echo $$i; done | sed 's/\.log$$//'`; \ bases=`echo $$bases` RECHECK_LOGS = $(TEST_LOGS) AM_RECURSIVE_TARGETS = check recheck TEST_SUITE_LOG = test-suite.log TEST_EXTENSIONS = @EXEEXT@ .test am__test_logs1 = $(TESTS:=.log) am__test_logs2 = $(am__test_logs1:@EXEEXT@.log=.log) TEST_LOGS = $(am__test_logs2:.test.log=.log) TEST_LOG_DRIVER = $(SHELL) $(top_srcdir)/test-driver TEST_LOG_COMPILE = $(TEST_LOG_COMPILER) $(AM_TEST_LOG_FLAGS) \ $(TEST_LOG_FLAGS) am__set_b = \ case '$@' in \ */*) \ case '$*' in \ */*) b='$*';; \ *) b=`echo '$@' | sed 's/\.log$$//'`; \ esac;; \ *) \ b='$*';; \ esac am__DIST_COMMON = $(srcdir)/Makefile.in \ $(top_srcdir)/Makefile.am.common \ $(top_srcdir)/cf/Makefile.am.common $(top_srcdir)/depcomp \ $(top_srcdir)/test-driver DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST) ACLOCAL = @ACLOCAL@ AIX_EXTRA_KAFS = @AIX_EXTRA_KAFS@ AMTAR = @AMTAR@ AM_DEFAULT_VERBOSITY = @AM_DEFAULT_VERBOSITY@ AR = @AR@ AS = @AS@ ASN1_COMPILE = @ASN1_COMPILE@ ASN1_COMPILE_DEP = @ASN1_COMPILE_DEP@ AUTOCONF = @AUTOCONF@ AUTOHEADER = @AUTOHEADER@ AUTOMAKE = @AUTOMAKE@ AWK = @AWK@ CANONICAL_HOST = @CANONICAL_HOST@ CAPNG_CFLAGS = @CAPNG_CFLAGS@ CAPNG_LIBS = @CAPNG_LIBS@ CATMAN = @CATMAN@ CATMANEXT = @CATMANEXT@ CC = @CC@ CCDEPMODE = @CCDEPMODE@ CFLAGS = @CFLAGS@ COMPILE_ET = @COMPILE_ET@ CPP = @CPP@ CPPFLAGS = @CPPFLAGS@ CYGPATH_W = @CYGPATH_W@ DB1LIB = @DB1LIB@ DB3LIB = @DB3LIB@ DBHEADER = @DBHEADER@ DEFS = @DEFS@ DEPDIR = @DEPDIR@ DIR_com_err = @DIR_com_err@ DIR_hdbdir = @DIR_hdbdir@ DIR_roken = @DIR_roken@ DLLTOOL = @DLLTOOL@ DSYMUTIL = @DSYMUTIL@ DUMPBIN = @DUMPBIN@ ECHO_C = @ECHO_C@ ECHO_N = @ECHO_N@ ECHO_T = @ECHO_T@ EGREP = @EGREP@ ENABLE_AFS_STRING_TO_KEY = @ENABLE_AFS_STRING_TO_KEY@ EXEEXT = @EXEEXT@ FGREP = @FGREP@ GCD_MIG = @GCD_MIG@ GREP = @GREP@ GROFF = @GROFF@ INCLUDES_roken = @INCLUDES_roken@ INCLUDE_libedit = @INCLUDE_libedit@ INCLUDE_libintl = @INCLUDE_libintl@ INCLUDE_openldap = @INCLUDE_openldap@ INCLUDE_openssl_crypto = @INCLUDE_openssl_crypto@ INCLUDE_readline = @INCLUDE_readline@ INCLUDE_sqlite3 = @INCLUDE_sqlite3@ INSTALL = @INSTALL@ INSTALL_DATA = @INSTALL_DATA@ INSTALL_PROGRAM = @INSTALL_PROGRAM@ INSTALL_SCRIPT = @INSTALL_SCRIPT@ INSTALL_STRIP_PROGRAM = @INSTALL_STRIP_PROGRAM@ LD = @LD@ LDFLAGS = @LDFLAGS@ LDFLAGS_VERSION_SCRIPT = @LDFLAGS_VERSION_SCRIPT@ LEX = @LEX@ LEXLIB = @LEXLIB@ LEX_OUTPUT_ROOT = @LEX_OUTPUT_ROOT@ LIBADD_roken = @LIBADD_roken@ LIBOBJS = @LIBOBJS@ LIBS = @LIBS@ LIBTOOL = @LIBTOOL@ LIB_AUTH_SUBDIRS = @LIB_AUTH_SUBDIRS@ LIB_bswap16 = @LIB_bswap16@ LIB_bswap32 = @LIB_bswap32@ LIB_bswap64 = @LIB_bswap64@ LIB_com_err = @LIB_com_err@ LIB_com_err_a = @LIB_com_err_a@ LIB_com_err_so = @LIB_com_err_so@ LIB_crypt = @LIB_crypt@ LIB_db_create = @LIB_db_create@ LIB_dbm_firstkey = @LIB_dbm_firstkey@ LIB_dbopen = @LIB_dbopen@ LIB_dispatch_async_f = @LIB_dispatch_async_f@ LIB_dladdr = @LIB_dladdr@ LIB_dlopen = @LIB_dlopen@ LIB_dn_expand = @LIB_dn_expand@ LIB_dns_search = @LIB_dns_search@ LIB_door_create = @LIB_door_create@ LIB_freeaddrinfo = @LIB_freeaddrinfo@ LIB_gai_strerror = @LIB_gai_strerror@ LIB_getaddrinfo = @LIB_getaddrinfo@ LIB_gethostbyname = @LIB_gethostbyname@ LIB_gethostbyname2 = @LIB_gethostbyname2@ LIB_getnameinfo = @LIB_getnameinfo@ LIB_getpwnam_r = @LIB_getpwnam_r@ LIB_getsockopt = @LIB_getsockopt@ LIB_hcrypto = @LIB_hcrypto@ LIB_hcrypto_a = @LIB_hcrypto_a@ LIB_hcrypto_appl = @LIB_hcrypto_appl@ LIB_hcrypto_so = @LIB_hcrypto_so@ LIB_hstrerror = @LIB_hstrerror@ LIB_kdb = @LIB_kdb@ LIB_libedit = @LIB_libedit@ LIB_libintl = @LIB_libintl@ LIB_loadquery = @LIB_loadquery@ LIB_logout = @LIB_logout@ LIB_logwtmp = @LIB_logwtmp@ LIB_openldap = @LIB_openldap@ LIB_openpty = @LIB_openpty@ LIB_openssl_crypto = @LIB_openssl_crypto@ LIB_otp = @LIB_otp@ LIB_pidfile = @LIB_pidfile@ LIB_readline = @LIB_readline@ LIB_res_ndestroy = @LIB_res_ndestroy@ LIB_res_nsearch = @LIB_res_nsearch@ LIB_res_search = @LIB_res_search@ LIB_roken = @LIB_roken@ LIB_security = @LIB_security@ LIB_setsockopt = @LIB_setsockopt@ LIB_socket = @LIB_socket@ LIB_sqlite3 = @LIB_sqlite3@ LIB_syslog = @LIB_syslog@ LIB_tgetent = @LIB_tgetent@ LIPO = @LIPO@ LMDBLIB = @LMDBLIB@ LN_S = @LN_S@ LTLIBOBJS = @LTLIBOBJS@ LT_SYS_LIBRARY_PATH = @LT_SYS_LIBRARY_PATH@ MAINT = @MAINT@ MAKEINFO = @MAKEINFO@ MANIFEST_TOOL = @MANIFEST_TOOL@ MKDIR_P = @MKDIR_P@ NDBMLIB = @NDBMLIB@ NM = @NM@ NMEDIT = @NMEDIT@ NO_AFS = @NO_AFS@ NROFF = @NROFF@ OBJDUMP = @OBJDUMP@ OBJEXT = @OBJEXT@ OTOOL = @OTOOL@ OTOOL64 = @OTOOL64@ PACKAGE = @PACKAGE@ PACKAGE_BUGREPORT = @PACKAGE_BUGREPORT@ PACKAGE_NAME = @PACKAGE_NAME@ PACKAGE_STRING = @PACKAGE_STRING@ PACKAGE_TARNAME = @PACKAGE_TARNAME@ PACKAGE_URL = @PACKAGE_URL@ PACKAGE_VERSION = @PACKAGE_VERSION@ PATH_SEPARATOR = @PATH_SEPARATOR@ PERL = @PERL@ PKG_CONFIG = @PKG_CONFIG@ PTHREAD_CFLAGS = @PTHREAD_CFLAGS@ PTHREAD_LDADD = @PTHREAD_LDADD@ PTHREAD_LIBADD = @PTHREAD_LIBADD@ RANLIB = @RANLIB@ SED = @SED@ SET_MAKE = @SET_MAKE@ SHELL = @SHELL@ SLC = @SLC@ SLC_DEP = @SLC_DEP@ STRIP = @STRIP@ VERSION = @VERSION@ VERSIONING = @VERSIONING@ WFLAGS = @WFLAGS@ WFLAGS_LITE = @WFLAGS_LITE@ YACC = @YACC@ YFLAGS = @YFLAGS@ abs_builddir = @abs_builddir@ abs_srcdir = @abs_srcdir@ abs_top_builddir = @abs_top_builddir@ abs_top_srcdir = @abs_top_srcdir@ ac_ct_AR = @ac_ct_AR@ ac_ct_CC = @ac_ct_CC@ ac_ct_DUMPBIN = @ac_ct_DUMPBIN@ am__include = @am__include@ am__leading_dot = @am__leading_dot@ am__quote = @am__quote@ am__tar = @am__tar@ am__untar = @am__untar@ bindir = @bindir@ build = @build@ build_alias = @build_alias@ build_cpu = @build_cpu@ build_os = @build_os@ build_vendor = @build_vendor@ builddir = @builddir@ datadir = @datadir@ datarootdir = @datarootdir@ db_type = @db_type@ db_type_preference = @db_type_preference@ docdir = @docdir@ dpagaix_cflags = @dpagaix_cflags@ dpagaix_ldadd = @dpagaix_ldadd@ dpagaix_ldflags = @dpagaix_ldflags@ dvidir = @dvidir@ exec_prefix = @exec_prefix@ host = @host@ host_alias = @host_alias@ host_cpu = @host_cpu@ host_os = @host_os@ host_vendor = @host_vendor@ htmldir = @htmldir@ includedir = @includedir@ infodir = @infodir@ install_sh = @install_sh@ libdir = @libdir@ libexecdir = @libexecdir@ localedir = @localedir@ localstatedir = @localstatedir@ mandir = @mandir@ mkdir_p = @mkdir_p@ oldincludedir = @oldincludedir@ pdfdir = @pdfdir@ prefix = @prefix@ program_transform_name = @program_transform_name@ psdir = @psdir@ sbindir = @sbindir@ sharedstatedir = @sharedstatedir@ srcdir = @srcdir@ subdirs = @subdirs@ sysconfdir = @sysconfdir@ target_alias = @target_alias@ top_build_prefix = @top_build_prefix@ top_builddir = @top_builddir@ top_srcdir = @top_srcdir@ SUFFIXES = .et .h .pc.in .pc .x .z .hx .1 .3 .5 .7 .8 .cat1 .cat3 \ .cat5 .cat7 .cat8 DEFAULT_INCLUDES = -I. -I$(srcdir) -I$(top_builddir)/include -I$(top_srcdir)/include AM_CPPFLAGS = $(INCLUDES_roken) @do_roken_rename_TRUE@ROKEN_RENAME = -DROKEN_RENAME AM_CFLAGS = $(WFLAGS) CP = cp buildinclude = $(top_builddir)/include LIB_XauReadAuth = @LIB_XauReadAuth@ LIB_el_init = @LIB_el_init@ LIB_getattr = @LIB_getattr@ LIB_getpwent_r = @LIB_getpwent_r@ LIB_odm_initialize = @LIB_odm_initialize@ LIB_setpcred = @LIB_setpcred@ INCLUDE_krb4 = @INCLUDE_krb4@ LIB_krb4 = @LIB_krb4@ libexec_heimdaldir = $(libexecdir)/heimdal NROFF_MAN = groff -mandoc -Tascii @NO_AFS_FALSE@LIB_kafs = $(top_builddir)/lib/kafs/libkafs.la $(AIX_EXTRA_KAFS) @NO_AFS_TRUE@LIB_kafs = @KRB5_TRUE@LIB_krb5 = $(top_builddir)/lib/krb5/libkrb5.la \ @KRB5_TRUE@ $(top_builddir)/lib/asn1/libasn1.la @KRB5_TRUE@LIB_gssapi = $(top_builddir)/lib/gssapi/libgssapi.la LIB_heimbase = $(top_builddir)/lib/base/libheimbase.la @DCE_TRUE@LIB_kdfs = $(top_builddir)/lib/kdfs/libkdfs.la #silent-rules heim_verbose = $(heim_verbose_$(V)) heim_verbose_ = $(heim_verbose_$(AM_DEFAULT_VERBOSITY)) heim_verbose_0 = @echo " GEN "$@; noinst_LTLIBRARIES = libheim-ipcc.la libheim-ipcs.la dist_libheim_ipcc_la_SOURCES = hi_locl.h heim_ipc_types.h client.c common.c dist_libheim_ipcs_la_SOURCES = hi_locl.h heim_ipc_types.h server.c common.c include_HEADERS = heim-ipc.h #libheim_ipcc_la_LDFLAGS = -version-info 0:0:0 #libheim_ipcs_la_LDFLAGS = -version-info 0:0:0 # #if versionscript #libheim_ipcc_la_LDFLAGS += $(LDFLAGS_VERSION_SCRIPT)$(srcdir)/version-scriptc.map #libheim_ipcs_la_LDFLAGS += $(LDFLAGS_VERSION_SCRIPT)$(srcdir)/version-scripts.map #endif libheim_ipcc_la_LIBADD = \ $(LIB_heimbase) \ $(LIB_roken) \ $(PTHREAD_LIBADD) libheim_ipcs_la_LIBADD = $(libheim_ipcc_la_LIBADD) $(am__append_1) ts_LDADD = libheim-ipcs.la $(LIB_roken) ts_http_LDADD = $(ts_LDADD) tc_LDADD = libheim-ipcc.la $(LIB_roken) EXTRA_DIST = heim_ipc.defs heim_ipc_async.defs heim_ipc_reply.defs @have_gcd_TRUE@built_ipcc = heim_ipc.h heim_ipcUser.c \ @have_gcd_TRUE@ heim_ipc_asyncServer.c heim_ipc_asyncServer.h @have_gcd_TRUE@nodist_libheim_ipcc_la_SOURCES = $(built_ipcc) @have_gcd_TRUE@built_ipcs = heim_ipcServer.c heim_ipcServer.h \ @have_gcd_TRUE@ heim_ipc_asyncUser.c heim_ipc_async.h \ @have_gcd_TRUE@ heim_ipc_reply.h heim_ipc_replyUser.c @have_gcd_TRUE@nodist_libheim_ipcs_la_SOURCES = $(built_ipcs) @have_gcd_TRUE@CLEANFILES = $(built_ipcc) $(built_ipcs) all: all-am .SUFFIXES: .SUFFIXES: .et .h .pc.in .pc .x .z .hx .1 .3 .5 .7 .8 .cat1 .cat3 .cat5 .cat7 .cat8 .c .lo .log .o .obj .test .test$(EXEEXT) .trs $(srcdir)/Makefile.in: @MAINTAINER_MODE_TRUE@ $(srcdir)/Makefile.am $(top_srcdir)/Makefile.am.common $(top_srcdir)/cf/Makefile.am.common $(am__configure_deps) @for dep in $?; do \ case '$(am__configure_deps)' in \ *$$dep*) \ ( cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh ) \ && { if test -f $@; then exit 0; else break; fi; }; \ exit 1;; \ esac; \ done; \ echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign lib/ipc/Makefile'; \ $(am__cd) $(top_srcdir) && \ $(AUTOMAKE) --foreign lib/ipc/Makefile Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status @case '$?' in \ *config.status*) \ cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh;; \ *) \ echo ' cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe)'; \ cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe);; \ esac; $(top_srcdir)/Makefile.am.common $(top_srcdir)/cf/Makefile.am.common $(am__empty): $(top_builddir)/config.status: $(top_srcdir)/configure $(CONFIG_STATUS_DEPENDENCIES) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(top_srcdir)/configure: @MAINTAINER_MODE_TRUE@ $(am__configure_deps) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(ACLOCAL_M4): @MAINTAINER_MODE_TRUE@ $(am__aclocal_m4_deps) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(am__aclocal_m4_deps): clean-noinstLTLIBRARIES: -test -z "$(noinst_LTLIBRARIES)" || rm -f $(noinst_LTLIBRARIES) @list='$(noinst_LTLIBRARIES)'; \ locs=`for p in $$list; do echo $$p; done | \ sed 's|^[^/]*$$|.|; s|/[^/]*$$||; s|$$|/so_locations|' | \ sort -u`; \ test -z "$$locs" || { \ echo rm -f $${locs}; \ rm -f $${locs}; \ } libheim-ipcc.la: $(libheim_ipcc_la_OBJECTS) $(libheim_ipcc_la_DEPENDENCIES) $(EXTRA_libheim_ipcc_la_DEPENDENCIES) $(AM_V_CCLD)$(LINK) $(libheim_ipcc_la_OBJECTS) $(libheim_ipcc_la_LIBADD) $(LIBS) libheim-ipcs.la: $(libheim_ipcs_la_OBJECTS) $(libheim_ipcs_la_DEPENDENCIES) $(EXTRA_libheim_ipcs_la_DEPENDENCIES) $(AM_V_CCLD)$(LINK) $(libheim_ipcs_la_OBJECTS) $(libheim_ipcs_la_LIBADD) $(LIBS) clean-noinstPROGRAMS: @list='$(noinst_PROGRAMS)'; test -n "$$list" || exit 0; \ echo " rm -f" $$list; \ rm -f $$list || exit $$?; \ test -n "$(EXEEXT)" || exit 0; \ list=`for p in $$list; do echo "$$p"; done | sed 's/$(EXEEXT)$$//'`; \ echo " rm -f" $$list; \ rm -f $$list tc$(EXEEXT): $(tc_OBJECTS) $(tc_DEPENDENCIES) $(EXTRA_tc_DEPENDENCIES) @rm -f tc$(EXEEXT) $(AM_V_CCLD)$(LINK) $(tc_OBJECTS) $(tc_LDADD) $(LIBS) ts$(EXEEXT): $(ts_OBJECTS) $(ts_DEPENDENCIES) $(EXTRA_ts_DEPENDENCIES) @rm -f ts$(EXEEXT) $(AM_V_CCLD)$(LINK) $(ts_OBJECTS) $(ts_LDADD) $(LIBS) ts-http$(EXEEXT): $(ts_http_OBJECTS) $(ts_http_DEPENDENCIES) $(EXTRA_ts_http_DEPENDENCIES) @rm -f ts-http$(EXEEXT) $(AM_V_CCLD)$(LINK) $(ts_http_OBJECTS) $(ts_http_LDADD) $(LIBS) mostlyclean-compile: -rm -f *.$(OBJEXT) distclean-compile: -rm -f *.tab.c @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/client.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/common.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/heim_ipcServer.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/heim_ipcUser.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/heim_ipc_asyncServer.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/heim_ipc_asyncUser.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/heim_ipc_replyUser.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/server.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/tc.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/ts-http.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/ts.Po@am__quote@ .c.o: @am__fastdepCC_TRUE@ $(AM_V_CC)$(COMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o $@ $< @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='$<' object='$@' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(COMPILE) -c -o $@ $< .c.obj: @am__fastdepCC_TRUE@ $(AM_V_CC)$(COMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o $@ `$(CYGPATH_W) '$<'` @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='$<' object='$@' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(COMPILE) -c -o $@ `$(CYGPATH_W) '$<'` .c.lo: @am__fastdepCC_TRUE@ $(AM_V_CC)$(LTCOMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o $@ $< @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='$<' object='$@' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LTCOMPILE) -c -o $@ $< mostlyclean-libtool: -rm -f *.lo clean-libtool: -rm -rf .libs _libs install-includeHEADERS: $(include_HEADERS) @$(NORMAL_INSTALL) @list='$(include_HEADERS)'; test -n "$(includedir)" || list=; \ if test -n "$$list"; then \ echo " $(MKDIR_P) '$(DESTDIR)$(includedir)'"; \ $(MKDIR_P) "$(DESTDIR)$(includedir)" || exit 1; \ fi; \ for p in $$list; do \ if test -f "$$p"; then d=; else d="$(srcdir)/"; fi; \ echo "$$d$$p"; \ done | $(am__base_list) | \ while read files; do \ echo " $(INSTALL_HEADER) $$files '$(DESTDIR)$(includedir)'"; \ $(INSTALL_HEADER) $$files "$(DESTDIR)$(includedir)" || exit $$?; \ done uninstall-includeHEADERS: @$(NORMAL_UNINSTALL) @list='$(include_HEADERS)'; test -n "$(includedir)" || list=; \ files=`for p in $$list; do echo $$p; done | sed -e 's|^.*/||'`; \ dir='$(DESTDIR)$(includedir)'; $(am__uninstall_files_from_dir) ID: $(am__tagged_files) $(am__define_uniq_tagged_files); mkid -fID $$unique tags: tags-am TAGS: tags tags-am: $(TAGS_DEPENDENCIES) $(am__tagged_files) set x; \ here=`pwd`; \ $(am__define_uniq_tagged_files); \ shift; \ if test -z "$(ETAGS_ARGS)$$*$$unique"; then :; else \ test -n "$$unique" || unique=$$empty_fix; \ if test $$# -gt 0; then \ $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ "$$@" $$unique; \ else \ $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ $$unique; \ fi; \ fi ctags: ctags-am CTAGS: ctags ctags-am: $(TAGS_DEPENDENCIES) $(am__tagged_files) $(am__define_uniq_tagged_files); \ test -z "$(CTAGS_ARGS)$$unique" \ || $(CTAGS) $(CTAGSFLAGS) $(AM_CTAGSFLAGS) $(CTAGS_ARGS) \ $$unique GTAGS: here=`$(am__cd) $(top_builddir) && pwd` \ && $(am__cd) $(top_srcdir) \ && gtags -i $(GTAGS_ARGS) "$$here" cscopelist: cscopelist-am cscopelist-am: $(am__tagged_files) list='$(am__tagged_files)'; \ case "$(srcdir)" in \ [\\/]* | ?:[\\/]*) sdir="$(srcdir)" ;; \ *) sdir=$(subdir)/$(srcdir) ;; \ esac; \ for i in $$list; do \ if test -f "$$i"; then \ echo "$(subdir)/$$i"; \ else \ echo "$$sdir/$$i"; \ fi; \ done >> $(top_builddir)/cscope.files distclean-tags: -rm -f TAGS ID GTAGS GRTAGS GSYMS GPATH tags # Recover from deleted '.trs' file; this should ensure that # "rm -f foo.log; make foo.trs" re-run 'foo.test', and re-create # both 'foo.log' and 'foo.trs'. Break the recipe in two subshells # to avoid problems with "make -n". .log.trs: rm -f $< $@ $(MAKE) $(AM_MAKEFLAGS) $< # Leading 'am--fnord' is there to ensure the list of targets does not # expand to empty, as could happen e.g. with make check TESTS=''. am--fnord $(TEST_LOGS) $(TEST_LOGS:.log=.trs): $(am__force_recheck) am--force-recheck: @: $(TEST_SUITE_LOG): $(TEST_LOGS) @$(am__set_TESTS_bases); \ am__f_ok () { test -f "$$1" && test -r "$$1"; }; \ redo_bases=`for i in $$bases; do \ am__f_ok $$i.trs && am__f_ok $$i.log || echo $$i; \ done`; \ if test -n "$$redo_bases"; then \ redo_logs=`for i in $$redo_bases; do echo $$i.log; done`; \ redo_results=`for i in $$redo_bases; do echo $$i.trs; done`; \ if $(am__make_dryrun); then :; else \ rm -f $$redo_logs && rm -f $$redo_results || exit 1; \ fi; \ fi; \ if test -n "$$am__remaking_logs"; then \ echo "fatal: making $(TEST_SUITE_LOG): possible infinite" \ "recursion detected" >&2; \ elif test -n "$$redo_logs"; then \ am__remaking_logs=yes $(MAKE) $(AM_MAKEFLAGS) $$redo_logs; \ fi; \ if $(am__make_dryrun); then :; else \ st=0; \ errmsg="fatal: making $(TEST_SUITE_LOG): failed to create"; \ for i in $$redo_bases; do \ test -f $$i.trs && test -r $$i.trs \ || { echo "$$errmsg $$i.trs" >&2; st=1; }; \ test -f $$i.log && test -r $$i.log \ || { echo "$$errmsg $$i.log" >&2; st=1; }; \ done; \ test $$st -eq 0 || exit 1; \ fi @$(am__sh_e_setup); $(am__tty_colors); $(am__set_TESTS_bases); \ ws='[ ]'; \ results=`for b in $$bases; do echo $$b.trs; done`; \ test -n "$$results" || results=/dev/null; \ all=` grep "^$$ws*:test-result:" $$results | wc -l`; \ pass=` grep "^$$ws*:test-result:$$ws*PASS" $$results | wc -l`; \ fail=` grep "^$$ws*:test-result:$$ws*FAIL" $$results | wc -l`; \ skip=` grep "^$$ws*:test-result:$$ws*SKIP" $$results | wc -l`; \ xfail=`grep "^$$ws*:test-result:$$ws*XFAIL" $$results | wc -l`; \ xpass=`grep "^$$ws*:test-result:$$ws*XPASS" $$results | wc -l`; \ error=`grep "^$$ws*:test-result:$$ws*ERROR" $$results | wc -l`; \ if test `expr $$fail + $$xpass + $$error` -eq 0; then \ success=true; \ else \ success=false; \ fi; \ br='==================='; br=$$br$$br$$br$$br; \ result_count () \ { \ if test x"$$1" = x"--maybe-color"; then \ maybe_colorize=yes; \ elif test x"$$1" = x"--no-color"; then \ maybe_colorize=no; \ else \ echo "$@: invalid 'result_count' usage" >&2; exit 4; \ fi; \ shift; \ desc=$$1 count=$$2; \ if test $$maybe_colorize = yes && test $$count -gt 0; then \ color_start=$$3 color_end=$$std; \ else \ color_start= color_end=; \ fi; \ echo "$${color_start}# $$desc $$count$${color_end}"; \ }; \ create_testsuite_report () \ { \ result_count $$1 "TOTAL:" $$all "$$brg"; \ result_count $$1 "PASS: " $$pass "$$grn"; \ result_count $$1 "SKIP: " $$skip "$$blu"; \ result_count $$1 "XFAIL:" $$xfail "$$lgn"; \ result_count $$1 "FAIL: " $$fail "$$red"; \ result_count $$1 "XPASS:" $$xpass "$$red"; \ result_count $$1 "ERROR:" $$error "$$mgn"; \ }; \ { \ echo "$(PACKAGE_STRING): $(subdir)/$(TEST_SUITE_LOG)" | \ $(am__rst_title); \ create_testsuite_report --no-color; \ echo; \ echo ".. contents:: :depth: 2"; \ echo; \ for b in $$bases; do echo $$b; done \ | $(am__create_global_log); \ } >$(TEST_SUITE_LOG).tmp || exit 1; \ mv $(TEST_SUITE_LOG).tmp $(TEST_SUITE_LOG); \ if $$success; then \ col="$$grn"; \ else \ col="$$red"; \ test x"$$VERBOSE" = x || cat $(TEST_SUITE_LOG); \ fi; \ echo "$${col}$$br$${std}"; \ echo "$${col}Testsuite summary for $(PACKAGE_STRING)$${std}"; \ echo "$${col}$$br$${std}"; \ create_testsuite_report --maybe-color; \ echo "$$col$$br$$std"; \ if $$success; then :; else \ echo "$${col}See $(subdir)/$(TEST_SUITE_LOG)$${std}"; \ if test -n "$(PACKAGE_BUGREPORT)"; then \ echo "$${col}Please report to $(PACKAGE_BUGREPORT)$${std}"; \ fi; \ echo "$$col$$br$$std"; \ fi; \ $$success || exit 1 check-TESTS: @list='$(RECHECK_LOGS)'; test -z "$$list" || rm -f $$list @list='$(RECHECK_LOGS:.log=.trs)'; test -z "$$list" || rm -f $$list @test -z "$(TEST_SUITE_LOG)" || rm -f $(TEST_SUITE_LOG) @set +e; $(am__set_TESTS_bases); \ log_list=`for i in $$bases; do echo $$i.log; done`; \ trs_list=`for i in $$bases; do echo $$i.trs; done`; \ log_list=`echo $$log_list`; trs_list=`echo $$trs_list`; \ $(MAKE) $(AM_MAKEFLAGS) $(TEST_SUITE_LOG) TEST_LOGS="$$log_list"; \ exit $$?; recheck: all @test -z "$(TEST_SUITE_LOG)" || rm -f $(TEST_SUITE_LOG) @set +e; $(am__set_TESTS_bases); \ bases=`for i in $$bases; do echo $$i; done \ | $(am__list_recheck_tests)` || exit 1; \ log_list=`for i in $$bases; do echo $$i.log; done`; \ log_list=`echo $$log_list`; \ $(MAKE) $(AM_MAKEFLAGS) $(TEST_SUITE_LOG) \ am__force_recheck=am--force-recheck \ TEST_LOGS="$$log_list"; \ exit $$? .test.log: @p='$<'; \ $(am__set_b); \ $(am__check_pre) $(TEST_LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_TEST_LOG_DRIVER_FLAGS) $(TEST_LOG_DRIVER_FLAGS) -- $(TEST_LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) @am__EXEEXT_TRUE@.test$(EXEEXT).log: @am__EXEEXT_TRUE@ @p='$<'; \ @am__EXEEXT_TRUE@ $(am__set_b); \ @am__EXEEXT_TRUE@ $(am__check_pre) $(TEST_LOG_DRIVER) --test-name "$$f" \ @am__EXEEXT_TRUE@ --log-file $$b.log --trs-file $$b.trs \ @am__EXEEXT_TRUE@ $(am__common_driver_flags) $(AM_TEST_LOG_DRIVER_FLAGS) $(TEST_LOG_DRIVER_FLAGS) -- $(TEST_LOG_COMPILE) \ @am__EXEEXT_TRUE@ "$$tst" $(AM_TESTS_FD_REDIRECT) distdir: $(DISTFILES) @srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ topsrcdirstrip=`echo "$(top_srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ list='$(DISTFILES)'; \ dist_files=`for file in $$list; do echo $$file; done | \ sed -e "s|^$$srcdirstrip/||;t" \ -e "s|^$$topsrcdirstrip/|$(top_builddir)/|;t"`; \ case $$dist_files in \ */*) $(MKDIR_P) `echo "$$dist_files" | \ sed '/\//!d;s|^|$(distdir)/|;s,/[^/]*$$,,' | \ sort -u` ;; \ esac; \ for file in $$dist_files; do \ if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \ if test -d $$d/$$file; then \ dir=`echo "/$$file" | sed -e 's,/[^/]*$$,,'`; \ if test -d "$(distdir)/$$file"; then \ find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ fi; \ if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \ cp -fpR $(srcdir)/$$file "$(distdir)$$dir" || exit 1; \ find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ fi; \ cp -fpR $$d/$$file "$(distdir)$$dir" || exit 1; \ else \ test -f "$(distdir)/$$file" \ || cp -p $$d/$$file "$(distdir)/$$file" \ || exit 1; \ fi; \ done $(MAKE) $(AM_MAKEFLAGS) \ top_distdir="$(top_distdir)" distdir="$(distdir)" \ dist-hook check-am: all-am $(MAKE) $(AM_MAKEFLAGS) check-TESTS check-local check: check-am all-am: Makefile $(LTLIBRARIES) $(PROGRAMS) $(HEADERS) all-local installdirs: for dir in "$(DESTDIR)$(includedir)"; do \ test -z "$$dir" || $(MKDIR_P) "$$dir"; \ done install: install-am install-exec: install-exec-am install-data: install-data-am uninstall: uninstall-am install-am: all-am @$(MAKE) $(AM_MAKEFLAGS) install-exec-am install-data-am installcheck: installcheck-am install-strip: if test -z '$(STRIP)'; then \ $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ install; \ else \ $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'" install; \ fi mostlyclean-generic: -test -z "$(TEST_LOGS)" || rm -f $(TEST_LOGS) -test -z "$(TEST_LOGS:.log=.trs)" || rm -f $(TEST_LOGS:.log=.trs) -test -z "$(TEST_SUITE_LOG)" || rm -f $(TEST_SUITE_LOG) clean-generic: -test -z "$(CLEANFILES)" || rm -f $(CLEANFILES) distclean-generic: -test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES) -test . = "$(srcdir)" || test -z "$(CONFIG_CLEAN_VPATH_FILES)" || rm -f $(CONFIG_CLEAN_VPATH_FILES) maintainer-clean-generic: @echo "This command is intended for maintainers to use" @echo "it deletes files that may require special tools to rebuild." clean: clean-am clean-am: clean-generic clean-libtool clean-noinstLTLIBRARIES \ clean-noinstPROGRAMS mostlyclean-am distclean: distclean-am -rm -rf ./$(DEPDIR) -rm -f Makefile distclean-am: clean-am distclean-compile distclean-generic \ distclean-tags dvi: dvi-am dvi-am: html: html-am html-am: info: info-am info-am: install-data-am: install-includeHEADERS @$(NORMAL_INSTALL) $(MAKE) $(AM_MAKEFLAGS) install-data-hook install-dvi: install-dvi-am install-dvi-am: install-exec-am: install-exec-local install-html: install-html-am install-html-am: install-info: install-info-am install-info-am: install-man: install-pdf: install-pdf-am install-pdf-am: install-ps: install-ps-am install-ps-am: installcheck-am: maintainer-clean: maintainer-clean-am -rm -rf ./$(DEPDIR) -rm -f Makefile maintainer-clean-am: distclean-am maintainer-clean-generic mostlyclean: mostlyclean-am mostlyclean-am: mostlyclean-compile mostlyclean-generic \ mostlyclean-libtool pdf: pdf-am pdf-am: ps: ps-am ps-am: uninstall-am: uninstall-includeHEADERS @$(NORMAL_INSTALL) $(MAKE) $(AM_MAKEFLAGS) uninstall-hook .MAKE: check-am install-am install-data-am install-strip uninstall-am .PHONY: CTAGS GTAGS TAGS all all-am all-local check check-TESTS \ check-am check-local clean clean-generic clean-libtool \ clean-noinstLTLIBRARIES clean-noinstPROGRAMS cscopelist-am \ ctags ctags-am dist-hook distclean distclean-compile \ distclean-generic distclean-libtool distclean-tags distdir dvi \ dvi-am html html-am info info-am install install-am \ install-data install-data-am install-data-hook install-dvi \ install-dvi-am install-exec install-exec-am install-exec-local \ install-html install-html-am install-includeHEADERS \ install-info install-info-am install-man install-pdf \ install-pdf-am install-ps install-ps-am install-strip \ installcheck installcheck-am installdirs maintainer-clean \ maintainer-clean-generic mostlyclean mostlyclean-compile \ mostlyclean-generic mostlyclean-libtool pdf pdf-am ps ps-am \ recheck tags tags-am uninstall uninstall-am uninstall-hook \ uninstall-includeHEADERS .PRECIOUS: Makefile install-suid-programs: @foo='$(bin_SUIDS)'; \ for file in $$foo; do \ x=$(DESTDIR)$(bindir)/$$file; \ if chown 0:0 $$x && chmod u+s $$x; then :; else \ echo "*"; \ echo "* Failed to install $$x setuid root"; \ echo "*"; \ fi; \ done install-exec-local: install-suid-programs codesign-all: @if [ X"$$CODE_SIGN_IDENTITY" != X ] ; then \ foo='$(bin_PROGRAMS) $(sbin_PROGRAMS) $(libexec_PROGRAMS)' ; \ for file in $$foo ; do \ echo "CODESIGN $$file" ; \ codesign -f -s "$$CODE_SIGN_IDENTITY" $$file || exit 1 ; \ done ; \ fi all-local: codesign-all install-build-headers:: $(include_HEADERS) $(dist_include_HEADERS) $(nodist_include_HEADERS) $(build_HEADERZ) $(nobase_include_HEADERS) $(noinst_HEADERS) @foo='$(include_HEADERS) $(dist_include_HEADERS) $(nodist_include_HEADERS) $(build_HEADERZ) $(noinst_HEADERS)'; \ for f in $$foo; do \ f=`basename $$f`; \ if test -f "$(srcdir)/$$f"; then file="$(srcdir)/$$f"; \ else file="$$f"; fi; \ if cmp -s $$file $(buildinclude)/$$f 2> /dev/null ; then \ : ; else \ echo " $(CP) $$file $(buildinclude)/$$f"; \ $(CP) $$file $(buildinclude)/$$f || true; \ fi ; \ done ; \ foo='$(nobase_include_HEADERS)'; \ for f in $$foo; do \ if test -f "$(srcdir)/$$f"; then file="$(srcdir)/$$f"; \ else file="$$f"; fi; \ $(mkdir_p) $(buildinclude)/`dirname $$f` ; \ if cmp -s $$file $(buildinclude)/$$f 2> /dev/null ; then \ : ; else \ echo " $(CP) $$file $(buildinclude)/$$f"; \ $(CP) $$file $(buildinclude)/$$f; \ fi ; \ done all-local: install-build-headers check-local:: @if test '$(CHECK_LOCAL)' = "no-check-local"; then \ foo=''; elif test '$(CHECK_LOCAL)'; then \ foo='$(CHECK_LOCAL)'; else \ foo='$(PROGRAMS)'; fi; \ if test "$$foo"; then \ failed=0; all=0; \ for i in $$foo; do \ all=`expr $$all + 1`; \ if (./$$i --version && ./$$i --help) > /dev/null 2>&1; then \ echo "PASS: $$i"; \ else \ echo "FAIL: $$i"; \ failed=`expr $$failed + 1`; \ fi; \ done; \ if test "$$failed" -eq 0; then \ banner="All $$all tests passed"; \ else \ banner="$$failed of $$all tests failed"; \ fi; \ dashes=`echo "$$banner" | sed s/./=/g`; \ echo "$$dashes"; \ echo "$$banner"; \ echo "$$dashes"; \ test "$$failed" -eq 0 || exit 1; \ fi .x.c: @cmp -s $< $@ 2> /dev/null || cp $< $@ .hx.h: @cmp -s $< $@ 2> /dev/null || cp $< $@ #NROFF_MAN = nroff -man .1.cat1: $(NROFF_MAN) $< > $@ .3.cat3: $(NROFF_MAN) $< > $@ .5.cat5: $(NROFF_MAN) $< > $@ .7.cat7: $(NROFF_MAN) $< > $@ .8.cat8: $(NROFF_MAN) $< > $@ dist-cat1-mans: @foo='$(man1_MANS)'; \ bar='$(man_MANS)'; \ for i in $$bar; do \ case $$i in \ *.1) foo="$$foo $$i";; \ esac; done ;\ for i in $$foo; do \ x=`echo $$i | sed 's/\.[^.]*$$/.cat1/'`; \ echo "$(NROFF_MAN) $(srcdir)/$$i > $(distdir)/$$x"; \ $(NROFF_MAN) $(srcdir)/$$i > $(distdir)/$$x; \ done dist-cat3-mans: @foo='$(man3_MANS)'; \ bar='$(man_MANS)'; \ for i in $$bar; do \ case $$i in \ *.3) foo="$$foo $$i";; \ esac; done ;\ for i in $$foo; do \ x=`echo $$i | sed 's/\.[^.]*$$/.cat3/'`; \ echo "$(NROFF_MAN) $(srcdir)/$$i > $(distdir)/$$x"; \ $(NROFF_MAN) $(srcdir)/$$i > $(distdir)/$$x; \ done dist-cat5-mans: @foo='$(man5_MANS)'; \ bar='$(man_MANS)'; \ for i in $$bar; do \ case $$i in \ *.5) foo="$$foo $$i";; \ esac; done ;\ for i in $$foo; do \ x=`echo $$i | sed 's/\.[^.]*$$/.cat5/'`; \ echo "$(NROFF_MAN) $(srcdir)/$$i > $(distdir)/$$x"; \ $(NROFF_MAN) $(srcdir)/$$i > $(distdir)/$$x; \ done dist-cat7-mans: @foo='$(man7_MANS)'; \ bar='$(man_MANS)'; \ for i in $$bar; do \ case $$i in \ *.7) foo="$$foo $$i";; \ esac; done ;\ for i in $$foo; do \ x=`echo $$i | sed 's/\.[^.]*$$/.cat7/'`; \ echo "$(NROFF_MAN) $(srcdir)/$$i > $(distdir)/$$x"; \ $(NROFF_MAN) $(srcdir)/$$i > $(distdir)/$$x; \ done dist-cat8-mans: @foo='$(man8_MANS)'; \ bar='$(man_MANS)'; \ for i in $$bar; do \ case $$i in \ *.8) foo="$$foo $$i";; \ esac; done ;\ for i in $$foo; do \ x=`echo $$i | sed 's/\.[^.]*$$/.cat8/'`; \ echo "$(NROFF_MAN) $(srcdir)/$$i > $(distdir)/$$x"; \ $(NROFF_MAN) $(srcdir)/$$i > $(distdir)/$$x; \ done dist-hook: dist-cat1-mans dist-cat3-mans dist-cat5-mans dist-cat7-mans dist-cat8-mans install-cat-mans: $(SHELL) $(top_srcdir)/cf/install-catman.sh install "$(INSTALL_DATA)" "$(mkinstalldirs)" "$(srcdir)" "$(DESTDIR)$(mandir)" '$(CATMANEXT)' $(man_MANS) $(man1_MANS) $(man3_MANS) $(man5_MANS) $(man7_MANS) $(man8_MANS) uninstall-cat-mans: $(SHELL) $(top_srcdir)/cf/install-catman.sh uninstall "$(INSTALL_DATA)" "$(mkinstalldirs)" "$(srcdir)" "$(DESTDIR)$(mandir)" '$(CATMANEXT)' $(man_MANS) $(man1_MANS) $(man3_MANS) $(man5_MANS) $(man7_MANS) $(man8_MANS) install-data-hook: install-cat-mans uninstall-hook: uninstall-cat-mans .et.h: $(COMPILE_ET) $< .et.c: $(COMPILE_ET) $< # # Useful target for debugging # check-valgrind: tobjdir=`cd $(top_builddir) && pwd` ; \ tsrcdir=`cd $(top_srcdir) && pwd` ; \ env TESTS_ENVIRONMENT="$${tsrcdir}/cf/maybe-valgrind.sh -s $${tsrcdir} -o $${tobjdir}" make check # # Target to please samba build farm, builds distfiles in-tree. # Will break when automake changes... # distdir-in-tree: $(DISTFILES) $(INFO_DEPS) list='$(DIST_SUBDIRS)'; for subdir in $$list; do \ if test "$$subdir" != .; then \ (cd $$subdir && $(MAKE) $(AM_MAKEFLAGS) distdir-in-tree) ; \ fi ; \ done @have_gcd_TRUE@heim_ipc.h heim_ipcUser.c heim_ipcServer.c heim_ipcServer.h: heim_ipc.defs @have_gcd_TRUE@ mig -header heim_ipc.h -user heim_ipcUser.c -sheader heim_ipcServer.h -server heim_ipcServer.c -I$(srcdir) $(srcdir)/heim_ipc.defs @have_gcd_TRUE@heim_ipc_async.h heim_ipc_asyncUser.c heim_ipc_asyncServer.c heim_ipc_asyncServer.h: heim_ipc_async.defs @have_gcd_TRUE@ mig -header heim_ipc_async.h -user heim_ipc_asyncUser.c -sheader heim_ipc_asyncServer.h -server heim_ipc_asyncServer.c -I$(srcdir) $(srcdir)/heim_ipc_async.defs @have_gcd_TRUE@heim_ipc_reply.h heim_ipc_replyUser.c: heim_ipc_reply.defs @have_gcd_TRUE@ mig -header heim_ipc_reply.h -user heim_ipc_replyUser.c -sheader /dev/null -server /dev/null -I$(srcdir) $(srcdir)/heim_ipc_reply.defs @have_gcd_TRUE@$(srcdir)/client.c: $(built_ipcc) @have_gcd_TRUE@$(srcdir)/server.c: $(built_ipcs) # Tell versions [3.59,3.63) of GNU make to not export all variables. # Otherwise a system limit (for SysV at least) may be exceeded. .NOEXPORT: heimdal-7.5.0/lib/ipc/ts.c0000644000175000017500000000563513026237312013375 0ustar niknik/* * Copyright (c) 2009 Kungliga Tekniska Hgskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Portions Copyright (c) 2009 Apple Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include #include #include #include #include #include static int help_flag; static int version_flag; static struct getargs args[] = { { "help", 'h', arg_flag, &help_flag, NULL, NULL }, { "version", 'v', arg_flag, &version_flag, NULL, NULL } }; static int num_args = sizeof(args) / sizeof(args[0]); static void usage(int ret) { arg_printusage (args, num_args, NULL, ""); exit (ret); } static void test_service(void *ctx, const heim_idata *req, const heim_icred cred, heim_ipc_complete complete, heim_sipc_call cctx) { heim_idata rep; printf("got request\n"); rep.length = 0; rep.data = NULL; (*complete)(cctx, 0, &rep); } int main(int argc, char **argv) { heim_sipc u; int optidx = 0; setprogname(argv[0]); if (getarg(args, num_args, argc, argv, &optidx)) usage(1); if (help_flag) usage(0); if (version_flag) { print_version(NULL); exit(0); } #if __APPLE__ { heim_sipc mach; heim_sipc_launchd_mach_init("org.h5l.test-ipc", test_service, NULL, &mach); } #endif heim_sipc_service_unix("org.h5l.test-ipc", test_service, NULL, &u); heim_ipc_main(); return 0; } heimdal-7.5.0/lib/ipc/heim_ipc_types.h0000644000175000017500000000357012136107750015754 0ustar niknik/* * Copyright (c) 2009 Kungliga Tekniska Hgskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Portions Copyright (c) 2009 Apple Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #ifndef _HEIM_IPC_TYPES_H_ #define _HEIM_IPC_TYPES_H_ #define HEIM_KCM_BOOTSTRAP_NAME "org.h5l.Kerberos.kcm" typedef char heim_ipc_message_inband_t[2048]; typedef char *heim_ipc_message_outband_t; #endif heimdal-7.5.0/lib/ipc/common.c0000644000175000017500000001167513062057075014246 0ustar niknik/* * Copyright (c) 2009 Kungliga Tekniska Hgskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Portions Copyright (c) 2009 Apple Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "hi_locl.h" #ifdef HAVE_GCD #include #else #include "heim_threads.h" #endif struct heim_icred { uid_t uid; gid_t gid; pid_t pid; pid_t session; }; void heim_ipc_free_cred(heim_icred cred) { free(cred); } uid_t heim_ipc_cred_get_uid(heim_icred cred) { return cred->uid; } gid_t heim_ipc_cred_get_gid(heim_icred cred) { return cred->gid; } pid_t heim_ipc_cred_get_pid(heim_icred cred) { return cred->pid; } pid_t heim_ipc_cred_get_session(heim_icred cred) { return cred->session; } int _heim_ipc_create_cred(uid_t uid, gid_t gid, pid_t pid, pid_t session, heim_icred *cred) { *cred = calloc(1, sizeof(**cred)); if (*cred == NULL) return ENOMEM; (*cred)->uid = uid; (*cred)->gid = gid; (*cred)->pid = pid; (*cred)->session = session; return 0; } #ifndef HAVE_GCD struct heim_isemaphore { HEIMDAL_MUTEX mutex; #ifdef ENABLE_PTHREAD_SUPPORT pthread_cond_t cond; #endif long counter; }; #endif heim_isemaphore heim_ipc_semaphore_create(long value) { #ifdef HAVE_GCD return (heim_isemaphore)dispatch_semaphore_create(value); #elif !defined(ENABLE_PTHREAD_SUPPORT) heim_assert(0, "no semaphore support w/o pthreads"); return NULL; #else heim_isemaphore s = malloc(sizeof(*s)); if (s == NULL) return NULL; HEIMDAL_MUTEX_init(&s->mutex); pthread_cond_init(&s->cond, NULL); s->counter = value; return s; #endif } long heim_ipc_semaphore_wait(heim_isemaphore s, time_t t) { #ifdef HAVE_GCD uint64_t timeout; if (t == HEIM_IPC_WAIT_FOREVER) timeout = DISPATCH_TIME_FOREVER; else timeout = (uint64_t)t * NSEC_PER_SEC; return dispatch_semaphore_wait((dispatch_semaphore_t)s, timeout); #elif !defined(ENABLE_PTHREAD_SUPPORT) heim_assert(0, "no semaphore support w/o pthreads"); return 0; #else HEIMDAL_MUTEX_lock(&s->mutex); /* if counter hits below zero, we get to wait */ if (--s->counter < 0) { int ret; if (t == HEIM_IPC_WAIT_FOREVER) ret = pthread_cond_wait(&s->cond, &s->mutex); else { struct timespec ts; ts.tv_sec = t; ts.tv_nsec = 0; ret = pthread_cond_timedwait(&s->cond, &s->mutex, &ts); } if (ret) { HEIMDAL_MUTEX_unlock(&s->mutex); return errno; } } HEIMDAL_MUTEX_unlock(&s->mutex); return 0; #endif } long heim_ipc_semaphore_signal(heim_isemaphore s) { #ifdef HAVE_GCD return dispatch_semaphore_signal((dispatch_semaphore_t)s); #elif !defined(ENABLE_PTHREAD_SUPPORT) heim_assert(0, "no semaphore support w/o pthreads"); return EINVAL; #else int wakeup; HEIMDAL_MUTEX_lock(&s->mutex); wakeup = (++s->counter == 0) ; HEIMDAL_MUTEX_unlock(&s->mutex); if (wakeup) pthread_cond_signal(&s->cond); return 0; #endif } void heim_ipc_semaphore_release(heim_isemaphore s) { #ifdef HAVE_GCD dispatch_release((dispatch_semaphore_t)s); #elif !defined(ENABLE_PTHREAD_SUPPORT) heim_assert(0, "no semaphore support w/o pthreads"); #else HEIMDAL_MUTEX_lock(&s->mutex); if (s->counter != 0) abort(); HEIMDAL_MUTEX_unlock(&s->mutex); HEIMDAL_MUTEX_destroy(&s->mutex); pthread_cond_destroy(&s->cond); free(s); #endif } void heim_ipc_free_data(heim_idata *data) { if (data->data) free(data->data); data->data = NULL; data->length = 0; } heimdal-7.5.0/lib/krb5/0000755000175000017500000000000013214604041012656 5ustar niknikheimdal-7.5.0/lib/krb5/dcache.c0000644000175000017500000003737013026237312014247 0ustar niknik/* * Copyright (c) 1997 - 2008 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Portions Copyright (c) 2009 Apple Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "krb5_locl.h" typedef struct krb5_dcache{ krb5_ccache fcache; char *dir; char *name; } krb5_dcache; #define DCACHE(X) ((krb5_dcache*)(X)->data.data) #define D2FCACHE(X) ((X)->fcache) static krb5_error_code KRB5_CALLCONV dcc_close(krb5_context, krb5_ccache); static krb5_error_code KRB5_CALLCONV dcc_get_default_name(krb5_context, char **); static char * primary_create(krb5_dcache *dc) { char *primary = NULL; asprintf(&primary, "%s/primary", dc->dir); if (primary == NULL) return NULL; return primary; } static int is_filename_cacheish(const char *name) { return strncmp(name, "tkt", 3) == 0; } static krb5_error_code set_default_cache(krb5_context context, krb5_dcache *dc, const char *residual) { char *path = NULL, *primary = NULL; krb5_error_code ret; struct iovec iov[2]; size_t len; int fd = -1; if (!is_filename_cacheish(residual)) { krb5_set_error_message(context, KRB5_CC_FORMAT, "name %s is not a cache (doesn't start with tkt)", residual); return KRB5_CC_FORMAT; } asprintf(&path, "%s/primary-XXXXXX", dc->dir); if (path == NULL) return krb5_enomem(context); fd = mkstemp(path); if (fd < 0) { ret = errno; goto out; } rk_cloexec(fd); #ifndef _WIN32 if (fchmod(fd, S_IRUSR | S_IWUSR) < 0) { ret = errno; goto out; } #endif len = strlen(residual); iov[0].iov_base = rk_UNCONST(residual); iov[0].iov_len = len; iov[1].iov_base = "\n"; iov[1].iov_len = 1; if (writev(fd, iov, sizeof(iov)/sizeof(iov[0])) != len + 1) { ret = errno; goto out; } primary = primary_create(dc); if (primary == NULL) { ret = krb5_enomem(context); goto out; } if (rename(path, primary) < 0) { ret = errno; goto out; } close(fd); fd = -1; ret = 0; out: if (fd >= 0) { (void)unlink(path); close(fd); } if (path) free(path); if (primary) free(primary); return ret; } static krb5_error_code get_default_cache(krb5_context context, krb5_dcache *dc, char **residual) { krb5_error_code ret; char buf[MAXPATHLEN]; char *primary; FILE *f; *residual = NULL; primary = primary_create(dc); if (primary == NULL) return krb5_enomem(context); f = fopen(primary, "r"); if (f == NULL) { if (errno == ENOENT) { free(primary); *residual = strdup("tkt"); if (*residual == NULL) return krb5_enomem(context); return 0; } ret = errno; krb5_set_error_message(context, ret, "failed to open %s", primary); free(primary); return ret; } if (fgets(buf, sizeof(buf), f) == NULL) { ret = ferror(f); fclose(f); krb5_set_error_message(context, ret, "read file %s", primary); free(primary); return ret; } fclose(f); buf[strcspn(buf, "\r\n")] = '\0'; if (!is_filename_cacheish(buf)) { krb5_set_error_message(context, KRB5_CC_FORMAT, "name in %s is not a cache (doesn't start with tkt)", primary); free(primary); return KRB5_CC_FORMAT; } free(primary); *residual = strdup(buf); if (*residual == NULL) return krb5_enomem(context); return 0; } static const char* KRB5_CALLCONV dcc_get_name(krb5_context context, krb5_ccache id) { krb5_dcache *dc = DCACHE(id); return dc->name; } static krb5_error_code verify_directory(krb5_context context, const char *path) { struct stat sb; if (stat(path, &sb) != 0) { if (errno == ENOENT) { /* XXX should use mkdirx_np() */ if (rk_mkdir(path, S_IRWXU) == 0) return 0; krb5_set_error_message(context, ENOENT, N_("DIR directory %s doesn't exists", ""), path); return ENOENT; } else { int ret = errno; krb5_set_error_message(context, ret, N_("DIR directory %s is bad: %s", ""), path, strerror(ret)); return errno; } } if (!S_ISDIR(sb.st_mode)) { krb5_set_error_message(context, KRB5_CC_BADNAME, N_("DIR directory %s is not a directory", ""), path); return KRB5_CC_BADNAME; } return 0; } static void dcc_release(krb5_context context, krb5_dcache *dc) { if (dc->fcache) krb5_cc_close(context, dc->fcache); if (dc->dir) free(dc->dir); if (dc->name) free(dc->name); memset(dc, 0, sizeof(*dc)); free(dc); } static krb5_error_code KRB5_CALLCONV dcc_resolve(krb5_context context, krb5_ccache *id, const char *res) { char *filename = NULL; krb5_error_code ret; krb5_dcache *dc; const char *p; p = res; do { p = strstr(p, ".."); if (p && (p == res || ISPATHSEP(p[-1])) && (ISPATHSEP(p[2]) || p[2] == '\0')) { krb5_set_error_message(context, KRB5_CC_FORMAT, N_("Path contains a .. component", "")); return KRB5_CC_FORMAT; } if (p) p += 3; } while (p); dc = calloc(1, sizeof(*dc)); if (dc == NULL) { krb5_set_error_message(context, KRB5_CC_NOMEM, N_("malloc: out of memory", "")); return KRB5_CC_NOMEM; } /* check for explicit component */ if (res[0] == ':') { char *q; dc->dir = strdup(&res[1]); #ifdef _WIN32 q = strrchr(dc->dir, '\\'); if (q == NULL) #endif q = strrchr(dc->dir, '/'); if (q) { *q++ = '\0'; } else { krb5_set_error_message(context, KRB5_CC_FORMAT, N_("Cache not an absolute path: %s", ""), dc->dir); dcc_release(context, dc); return KRB5_CC_FORMAT; } if (!is_filename_cacheish(q)) { krb5_set_error_message(context, KRB5_CC_FORMAT, N_("Name %s is not a cache (doesn't start with tkt)", ""), q); dcc_release(context, dc); return KRB5_CC_FORMAT; } ret = verify_directory(context, dc->dir); if (ret) { dcc_release(context, dc); return ret; } dc->name = strdup(res); if (dc->name == NULL) { dcc_release(context, dc); return krb5_enomem(context); } } else { char *residual; size_t len; dc->dir = strdup(res); if (dc->dir == NULL) { dcc_release(context, dc); return krb5_enomem(context); } len = strlen(dc->dir); if (ISPATHSEP(dc->dir[len - 1])) dc->dir[len - 1] = '\0'; ret = verify_directory(context, dc->dir); if (ret) { dcc_release(context, dc); return ret; } ret = get_default_cache(context, dc, &residual); if (ret) { dcc_release(context, dc); return ret; } asprintf(&dc->name, ":%s/%s", dc->dir, residual); free(residual); if (dc->name == NULL) { dcc_release(context, dc); return krb5_enomem(context); } } asprintf(&filename, "FILE%s", dc->name); if (filename == NULL) { dcc_release(context, dc); return krb5_enomem(context); } ret = krb5_cc_resolve(context, filename, &dc->fcache); free(filename); if (ret) { dcc_release(context, dc); return ret; } (*id)->data.data = dc; (*id)->data.length = sizeof(*dc); return 0; } static char * copy_default_dcc_cache(krb5_context context) { const char *defname; krb5_error_code ret; char *name = NULL; size_t len; len = strlen(krb5_dcc_ops.prefix); defname = krb5_cc_default_name(context); if (defname == NULL || strncmp(defname, krb5_dcc_ops.prefix, len) != 0 || defname[len] != ':') { ret = dcc_get_default_name(context, &name); if (ret) return NULL; return name; } else { return strdup(&defname[len + 1]); } } static krb5_error_code KRB5_CALLCONV dcc_gen_new(krb5_context context, krb5_ccache *id) { krb5_error_code ret; char *name = NULL; krb5_dcache *dc; int fd; size_t len; name = copy_default_dcc_cache(context); if (name == NULL) { krb5_set_error_message(context, KRB5_CC_FORMAT, N_("Can't generate DIR caches unless its the default type", "")); return KRB5_CC_FORMAT; } len = strlen(krb5_dcc_ops.prefix); if (strncmp(name, krb5_dcc_ops.prefix, len) == 0 && name[len] == ':') ++len; else len = 0; ret = dcc_resolve(context, id, name + len); free(name); name = NULL; if (ret) return ret; dc = DCACHE((*id)); asprintf(&name, ":%s/tktXXXXXX", dc->dir); if (name == NULL) { dcc_close(context, *id); return krb5_enomem(context); } fd = mkstemp(&name[1]); if (fd < 0) { dcc_close(context, *id); return krb5_enomem(context); } close(fd); free(dc->name); dc->name = name; return 0; } static krb5_error_code KRB5_CALLCONV dcc_initialize(krb5_context context, krb5_ccache id, krb5_principal primary_principal) { krb5_dcache *dc = DCACHE(id); return krb5_cc_initialize(context, D2FCACHE(dc), primary_principal); } static krb5_error_code KRB5_CALLCONV dcc_close(krb5_context context, krb5_ccache id) { dcc_release(context, DCACHE(id)); return 0; } static krb5_error_code KRB5_CALLCONV dcc_destroy(krb5_context context, krb5_ccache id) { krb5_dcache *dc = DCACHE(id); krb5_ccache fcache = D2FCACHE(dc); dc->fcache = NULL; return krb5_cc_destroy(context, fcache); } static krb5_error_code KRB5_CALLCONV dcc_store_cred(krb5_context context, krb5_ccache id, krb5_creds *creds) { krb5_dcache *dc = DCACHE(id); return krb5_cc_store_cred(context, D2FCACHE(dc), creds); } static krb5_error_code KRB5_CALLCONV dcc_get_principal(krb5_context context, krb5_ccache id, krb5_principal *principal) { krb5_dcache *dc = DCACHE(id); return krb5_cc_get_principal(context, D2FCACHE(dc), principal); } static krb5_error_code KRB5_CALLCONV dcc_get_first (krb5_context context, krb5_ccache id, krb5_cc_cursor *cursor) { krb5_dcache *dc = DCACHE(id); return krb5_cc_start_seq_get(context, D2FCACHE(dc), cursor); } static krb5_error_code KRB5_CALLCONV dcc_get_next (krb5_context context, krb5_ccache id, krb5_cc_cursor *cursor, krb5_creds *creds) { krb5_dcache *dc = DCACHE(id); return krb5_cc_next_cred(context, D2FCACHE(dc), cursor, creds); } static krb5_error_code KRB5_CALLCONV dcc_end_get (krb5_context context, krb5_ccache id, krb5_cc_cursor *cursor) { krb5_dcache *dc = DCACHE(id); return krb5_cc_end_seq_get(context, D2FCACHE(dc), cursor); } static krb5_error_code KRB5_CALLCONV dcc_remove_cred(krb5_context context, krb5_ccache id, krb5_flags which, krb5_creds *cred) { krb5_dcache *dc = DCACHE(id); return krb5_cc_remove_cred(context, D2FCACHE(dc), which, cred); } static krb5_error_code KRB5_CALLCONV dcc_set_flags(krb5_context context, krb5_ccache id, krb5_flags flags) { krb5_dcache *dc = DCACHE(id); return krb5_cc_set_flags(context, D2FCACHE(dc), flags); } static int KRB5_CALLCONV dcc_get_version(krb5_context context, krb5_ccache id) { krb5_dcache *dc = DCACHE(id); return krb5_cc_get_version(context, D2FCACHE(dc)); } struct dcache_iter { int first; krb5_dcache *dc; }; static krb5_error_code KRB5_CALLCONV dcc_get_cache_first(krb5_context context, krb5_cc_cursor *cursor) { struct dcache_iter *iter; krb5_error_code ret; char *name; *cursor = NULL; iter = calloc(1, sizeof(*iter)); if (iter == NULL) return krb5_enomem(context); iter->first = 1; name = copy_default_dcc_cache(context); if (name == NULL) { free(iter); krb5_set_error_message(context, KRB5_CC_FORMAT, N_("Can't generate DIR caches unless its the default type", "")); return KRB5_CC_FORMAT; } ret = dcc_resolve(context, NULL, name); free(name); if (ret) { free(iter); return ret; } /* XXX We need to opendir() here */ *cursor = iter; return 0; } static krb5_error_code KRB5_CALLCONV dcc_get_cache_next(krb5_context context, krb5_cc_cursor cursor, krb5_ccache *id) { struct dcache_iter *iter = cursor; if (iter == NULL) return krb5_einval(context, 2); if (!iter->first) { krb5_clear_error_message(context); return KRB5_CC_END; } /* XXX We need to readdir() here */ iter->first = 0; return KRB5_CC_END; } static krb5_error_code KRB5_CALLCONV dcc_end_cache_get(krb5_context context, krb5_cc_cursor cursor) { struct dcache_iter *iter = cursor; if (iter == NULL) return krb5_einval(context, 2); /* XXX We need to closedir() here */ if (iter->dc) dcc_release(context, iter->dc); free(iter); return 0; } static krb5_error_code KRB5_CALLCONV dcc_move(krb5_context context, krb5_ccache from, krb5_ccache to) { krb5_dcache *dcfrom = DCACHE(from); krb5_dcache *dcto = DCACHE(to); return krb5_cc_move(context, D2FCACHE(dcfrom), D2FCACHE(dcto)); } static krb5_error_code KRB5_CALLCONV dcc_get_default_name(krb5_context context, char **str) { return _krb5_expand_default_cc_name(context, KRB5_DEFAULT_CCNAME_DIR, str); } static krb5_error_code KRB5_CALLCONV dcc_set_default(krb5_context context, krb5_ccache id) { krb5_dcache *dc = DCACHE(id); const char *name; name = krb5_cc_get_name(context, D2FCACHE(dc)); if (name == NULL) return ENOENT; return set_default_cache(context, dc, name); } static krb5_error_code KRB5_CALLCONV dcc_lastchange(krb5_context context, krb5_ccache id, krb5_timestamp *mtime) { krb5_dcache *dc = DCACHE(id); return krb5_cc_last_change_time(context, D2FCACHE(dc), mtime); } static krb5_error_code KRB5_CALLCONV dcc_set_kdc_offset(krb5_context context, krb5_ccache id, krb5_deltat kdc_offset) { krb5_dcache *dc = DCACHE(id); return krb5_cc_set_kdc_offset(context, D2FCACHE(dc), kdc_offset); } static krb5_error_code KRB5_CALLCONV dcc_get_kdc_offset(krb5_context context, krb5_ccache id, krb5_deltat *kdc_offset) { krb5_dcache *dc = DCACHE(id); return krb5_cc_get_kdc_offset(context, D2FCACHE(dc), kdc_offset); } /** * Variable containing the DIR based credential cache implemention. * * @ingroup krb5_ccache */ KRB5_LIB_VARIABLE const krb5_cc_ops krb5_dcc_ops = { KRB5_CC_OPS_VERSION, "DIR", dcc_get_name, dcc_resolve, dcc_gen_new, dcc_initialize, dcc_destroy, dcc_close, dcc_store_cred, NULL, /* dcc_retrieve */ dcc_get_principal, dcc_get_first, dcc_get_next, dcc_end_get, dcc_remove_cred, dcc_set_flags, dcc_get_version, dcc_get_cache_first, dcc_get_cache_next, dcc_end_cache_get, dcc_move, dcc_get_default_name, dcc_set_default, dcc_lastchange, dcc_set_kdc_offset, dcc_get_kdc_offset }; heimdal-7.5.0/lib/krb5/krb5_krbhst_init.cat30000644000175000017500000001546313212450757016721 0ustar niknik KRB5_KRBHST_INIT(3) BSD Library Functions Manual KRB5_KRBHST_INIT(3) NNAAMMEE kkrrbb55__kkrrbbhhsstt__iinniitt, kkrrbb55__kkrrbbhhsstt__iinniitt__ffllaaggss, kkrrbb55__kkrrbbhhsstt__nneexxtt, kkrrbb55__kkrrbbhhsstt__nneexxtt__aass__ssttrriinngg, kkrrbb55__kkrrbbhhsstt__rreesseett, kkrrbb55__kkrrbbhhsstt__ffrreeee, kkrrbb55__kkrrbbhhsstt__ffoorrmmaatt__ssttrriinngg, kkrrbb55__kkrrbbhhsstt__ggeett__aaddddrriinnffoo -- lookup Kerberos KDC hosts LLIIBBRRAARRYY Kerberos 5 Library (libkrb5, -lkrb5) SSYYNNOOPPSSIISS ##iinncclluuddee <> _k_r_b_5___e_r_r_o_r___c_o_d_e kkrrbb55__kkrrbbhhsstt__iinniitt(_k_r_b_5___c_o_n_t_e_x_t _c_o_n_t_e_x_t, _c_o_n_s_t _c_h_a_r _*_r_e_a_l_m, _u_n_s_i_g_n_e_d _i_n_t _t_y_p_e, _k_r_b_5___k_r_b_h_s_t___h_a_n_d_l_e _*_h_a_n_d_l_e); _k_r_b_5___e_r_r_o_r___c_o_d_e kkrrbb55__kkrrbbhhsstt__iinniitt__ffllaaggss(_k_r_b_5___c_o_n_t_e_x_t _c_o_n_t_e_x_t, _c_o_n_s_t _c_h_a_r _*_r_e_a_l_m, _u_n_s_i_g_n_e_d _i_n_t _t_y_p_e, _i_n_t _f_l_a_g_s, _k_r_b_5___k_r_b_h_s_t___h_a_n_d_l_e _*_h_a_n_d_l_e); _k_r_b_5___e_r_r_o_r___c_o_d_e kkrrbb55__kkrrbbhhsstt__nneexxtt(_k_r_b_5___c_o_n_t_e_x_t _c_o_n_t_e_x_t, _k_r_b_5___k_r_b_h_s_t___h_a_n_d_l_e _h_a_n_d_l_e, _k_r_b_5___k_r_b_h_s_t___i_n_f_o _*_*_h_o_s_t); _k_r_b_5___e_r_r_o_r___c_o_d_e kkrrbb55__kkrrbbhhsstt__nneexxtt__aass__ssttrriinngg(_k_r_b_5___c_o_n_t_e_x_t _c_o_n_t_e_x_t, _k_r_b_5___k_r_b_h_s_t___h_a_n_d_l_e _h_a_n_d_l_e, _c_h_a_r _*_h_o_s_t_n_a_m_e, _s_i_z_e___t _h_o_s_t_l_e_n); _v_o_i_d kkrrbb55__kkrrbbhhsstt__rreesseett(_k_r_b_5___c_o_n_t_e_x_t _c_o_n_t_e_x_t, _k_r_b_5___k_r_b_h_s_t___h_a_n_d_l_e _h_a_n_d_l_e); _v_o_i_d kkrrbb55__kkrrbbhhsstt__ffrreeee(_k_r_b_5___c_o_n_t_e_x_t _c_o_n_t_e_x_t, _k_r_b_5___k_r_b_h_s_t___h_a_n_d_l_e _h_a_n_d_l_e); _k_r_b_5___e_r_r_o_r___c_o_d_e kkrrbb55__kkrrbbhhsstt__ffoorrmmaatt__ssttrriinngg(_k_r_b_5___c_o_n_t_e_x_t _c_o_n_t_e_x_t, _c_o_n_s_t _k_r_b_5___k_r_b_h_s_t___i_n_f_o _*_h_o_s_t, _c_h_a_r _*_h_o_s_t_n_a_m_e, _s_i_z_e___t _h_o_s_t_l_e_n); _k_r_b_5___e_r_r_o_r___c_o_d_e kkrrbb55__kkrrbbhhsstt__ggeett__aaddddrriinnffoo(_k_r_b_5___c_o_n_t_e_x_t _c_o_n_t_e_x_t, _k_r_b_5___k_r_b_h_s_t___i_n_f_o _*_h_o_s_t, _s_t_r_u_c_t _a_d_d_r_i_n_f_o _*_*_a_i); DDEESSCCRRIIPPTTIIOONN These functions are used to sequence through all Kerberos hosts of a par- ticular realm and service. The service type can be the KDCs, the adminis- trative servers, the password changing servers, or the servers for Ker- beros 4 ticket conversion. First a handle to a particular service is obtained by calling kkrrbb55__kkrrbbhhsstt__iinniitt() (or kkrrbb55__kkrrbbhhsstt__iinniitt__ffllaaggss()) with the _r_e_a_l_m of inter- est and the type of service to lookup. The _t_y_p_e can be one of: KRB5_KRBHST_KDC KRB5_KRBHST_ADMIN KRB5_KRBHST_CHANGEPW KRB5_KRBHST_KRB524 The _h_a_n_d_l_e is returned to the caller, and should be passed to the other functions. The _f_l_a_g argument to kkrrbb55__kkrrbbhhsstt__iinniitt__ffllaaggss is the same flags as kkrrbb55__sseenndd__ttoo__kkddcc__ffllaaggss() uses. Possible values are: KRB5_KRBHST_FLAGS_MASTER only talk to master (readwrite) KDC KRB5_KRBHST_FLAGS_LARGE_MSG this is a large message, so use trans- port that can handle that. For each call to kkrrbb55__kkrrbbhhsstt__nneexxtt() information on a new host is returned. The former function returns in _h_o_s_t a pointer to a structure containing information about the host, such as protocol, hostname, and port: typedef struct krb5_krbhst_info { enum { KRB5_KRBHST_UDP, KRB5_KRBHST_TCP, KRB5_KRBHST_HTTP } proto; unsigned short port; struct addrinfo *ai; struct krb5_krbhst_info *next; char hostname[1]; } krb5_krbhst_info; The related function, kkrrbb55__kkrrbbhhsstt__nneexxtt__aass__ssttrriinngg(), return the same information as a URL-like string. When there are no more hosts, these functions return KRB5_KDC_UNREACH. To re-iterate over all hosts, call kkrrbb55__kkrrbbhhsstt__rreesseett() and the next call to kkrrbb55__kkrrbbhhsstt__nneexxtt() will return the first host. When done with the handle, kkrrbb55__kkrrbbhhsstt__ffrreeee() should be called. To use a _k_r_b_5___k_r_b_h_s_t___i_n_f_o, there are two functions: kkrrbb55__kkrrbbhhsstt__ffoorrmmaatt__ssttrriinngg() that will return a printable representation of that struct and kkrrbb55__kkrrbbhhsstt__ggeett__aaddddrriinnffoo() that will return a _s_t_r_u_c_t _a_d_d_r_i_n_f_o that can then be used for communicating with the server men- tioned. EEXXAAMMPPLLEESS The following code will print the KDCs of the realm ``MY.REALM'': krb5_krbhst_handle handle; char host[MAXHOSTNAMELEN]; krb5_krbhst_init(context, "MY.REALM", KRB5_KRBHST_KDC, &handle); while(krb5_krbhst_next_as_string(context, handle, host, sizeof(host)) == 0) printf("%s\n", host); krb5_krbhst_free(context, handle); SSEEEE AALLSSOO getaddrinfo(3), krb5_get_krbhst(3), krb5_send_to_kdc_flags(3) HHIISSTTOORRYY These functions first appeared in Heimdal 0.3g. HEIMDAL May 10, 2005 HEIMDAL heimdal-7.5.0/lib/krb5/krb5_aname_to_localname.30000644000175000017500000000557012136107750017501 0ustar niknik.\" Copyright (c) 2003 - 2007 Kungliga Tekniska Högskolan .\" (Royal Institute of Technology, Stockholm, Sweden). .\" All rights reserved. .\" .\" Redistribution and use in source and binary forms, with or without .\" modification, are permitted provided that the following conditions .\" are met: .\" .\" 1. Redistributions of source code must retain the above copyright .\" notice, this list of conditions and the following disclaimer. .\" .\" 2. Redistributions in binary form must reproduce the above copyright .\" notice, this list of conditions and the following disclaimer in the .\" documentation and/or other materials provided with the distribution. .\" .\" 3. Neither the name of the Institute nor the names of its contributors .\" may be used to endorse or promote products derived from this software .\" without specific prior written permission. .\" .\" THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND .\" ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE .\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE .\" ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE .\" FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL .\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS .\" OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) .\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT .\" LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF .\" SUCH DAMAGE. .\" .\" $Id$ .\" .Dd February 18, 2006 .Dt KRB5_ANAME_TO_LOCALNAME 3 .Os HEIMDAL .Sh NAME .Nm krb5_aname_to_localname .Nd converts a principal to a system local name .Sh LIBRARY Kerberos 5 Library (libkrb5, -lkrb5) .Sh SYNOPSIS .In krb5.h .Ft krb5_boolean .Fo krb5_aname_to_localname .Fa "krb5_context context" .Fa "krb5_const_principal name" .Fa "size_t lnsize" .Fa "char *lname" .Fc .Sh DESCRIPTION This function takes a principal .Fa name , verifies that it is in the local realm (using .Fn krb5_get_default_realms ) and then returns the local name of the principal. .Pp If .Fa name isn't in one of the local realms an error is returned. .Pp If the size .Fa ( lnsize ) of the local name .Fa ( lname ) is too small, an error is returned. .Pp .Fn krb5_aname_to_localname should only be use by an application that implements protocols that don't transport the login name and thus needs to convert a principal to a local name. .Pp Protocols should be designed so that they authenticate using Kerberos, send over the login name and then verify the principal that is authenticated is allowed to login and the login name. A way to check if a user is allowed to login is using the function .Fn krb5_kuserok . .Sh SEE ALSO .Xr krb5_get_default_realms 3 , .Xr krb5_kuserok 3 heimdal-7.5.0/lib/krb5/store_mem.c0000644000175000017500000001277213026237312015031 0ustar niknik/* * Copyright (c) 1997 - 2000, 2002 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "krb5_locl.h" #include "store-int.h" typedef struct mem_storage{ unsigned char *base; size_t size; unsigned char *ptr; }mem_storage; static ssize_t mem_fetch(krb5_storage *sp, void *data, size_t size) { mem_storage *s = (mem_storage*)sp->data; if(size > (size_t)(s->base + s->size - s->ptr)) size = s->base + s->size - s->ptr; memmove(data, s->ptr, size); sp->seek(sp, size, SEEK_CUR); return size; } static ssize_t mem_store(krb5_storage *sp, const void *data, size_t size) { mem_storage *s = (mem_storage*)sp->data; if(size > (size_t)(s->base + s->size - s->ptr)) size = s->base + s->size - s->ptr; memmove(s->ptr, data, size); sp->seek(sp, size, SEEK_CUR); return size; } static ssize_t mem_no_store(krb5_storage *sp, const void *data, size_t size) { return -1; } static off_t mem_seek(krb5_storage *sp, off_t offset, int whence) { mem_storage *s = (mem_storage*)sp->data; switch(whence){ case SEEK_SET: if((size_t)offset > s->size) offset = s->size; if(offset < 0) offset = 0; s->ptr = s->base + offset; break; case SEEK_CUR: return sp->seek(sp, s->ptr - s->base + offset, SEEK_SET); case SEEK_END: return sp->seek(sp, s->size + offset, SEEK_SET); default: errno = EINVAL; return -1; } return s->ptr - s->base; } static int mem_trunc(krb5_storage *sp, off_t offset) { mem_storage *s = (mem_storage*)sp->data; if((size_t)offset > s->size) return ERANGE; s->size = offset; if ((s->ptr - s->base) > offset) s->ptr = s->base + offset; return 0; } static int mem_no_trunc(krb5_storage *sp, off_t offset) { return EINVAL; } /** * Create a fixed size memory storage block * * @return A krb5_storage on success, or NULL on out of memory error. * * @ingroup krb5_storage * * @sa krb5_storage_mem() * @sa krb5_storage_from_readonly_mem() * @sa krb5_storage_from_data() * @sa krb5_storage_from_fd() * @sa krb5_storage_from_socket() */ KRB5_LIB_FUNCTION krb5_storage * KRB5_LIB_CALL krb5_storage_from_mem(void *buf, size_t len) { krb5_storage *sp = malloc(sizeof(krb5_storage)); mem_storage *s; if(sp == NULL) return NULL; s = malloc(sizeof(*s)); if(s == NULL) { free(sp); return NULL; } sp->data = s; sp->flags = 0; sp->eof_code = HEIM_ERR_EOF; s->base = buf; s->size = len; s->ptr = buf; sp->fetch = mem_fetch; sp->store = mem_store; sp->seek = mem_seek; sp->trunc = mem_trunc; sp->fsync = NULL; sp->free = NULL; sp->max_alloc = UINT_MAX/8; return sp; } /** * Create a fixed size memory storage block * * @return A krb5_storage on success, or NULL on out of memory error. * * @ingroup krb5_storage * * @sa krb5_storage_mem() * @sa krb5_storage_from_mem() * @sa krb5_storage_from_readonly_mem() * @sa krb5_storage_from_fd() */ KRB5_LIB_FUNCTION krb5_storage * KRB5_LIB_CALL krb5_storage_from_data(krb5_data *data) { return krb5_storage_from_mem(data->data, data->length); } /** * Create a fixed size memory storage block that is read only * * @return A krb5_storage on success, or NULL on out of memory error. * * @ingroup krb5_storage * * @sa krb5_storage_mem() * @sa krb5_storage_from_mem() * @sa krb5_storage_from_data() * @sa krb5_storage_from_fd() */ KRB5_LIB_FUNCTION krb5_storage * KRB5_LIB_CALL krb5_storage_from_readonly_mem(const void *buf, size_t len) { krb5_storage *sp = malloc(sizeof(krb5_storage)); mem_storage *s; if(sp == NULL) return NULL; s = malloc(sizeof(*s)); if(s == NULL) { free(sp); return NULL; } sp->data = s; sp->flags = 0; sp->eof_code = HEIM_ERR_EOF; s->base = rk_UNCONST(buf); s->size = len; s->ptr = rk_UNCONST(buf); sp->fetch = mem_fetch; sp->store = mem_no_store; sp->seek = mem_seek; sp->trunc = mem_no_trunc; sp->fsync = NULL; sp->free = NULL; sp->max_alloc = UINT_MAX/8; return sp; } heimdal-7.5.0/lib/krb5/test_kuserok.c0000644000175000017500000000575613026237312015565 0ustar niknik/* * Copyright (c) 2005 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of KTH nor the names of its contributors may be * used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY KTH AND ITS CONTRIBUTORS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL KTH OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "krb5_locl.h" #include #include static int version_flag = 0; static int help_flag = 0; static struct getargs args[] = { {"version", 0, arg_flag, &version_flag, "print version", NULL }, {"help", 0, arg_flag, &help_flag, NULL, NULL } }; static void usage (int ret) { arg_printusage (args, sizeof(args)/sizeof(*args), NULL, "principal luser"); exit (ret); } int main(int argc, char **argv) { krb5_context context; krb5_error_code ret; krb5_principal principal; char *p; int o = 0; setprogname(argv[0]); if(getarg(args, sizeof(args) / sizeof(args[0]), argc, argv, &o)) usage(1); if (help_flag) usage (0); if(version_flag){ print_version(NULL); exit(0); } argc -= o; argv += o; ret = krb5_init_context(&context); if (ret) errx (1, "krb5_init_context failed: %d", ret); if (argc != 2) usage(1); ret = krb5_parse_name(context, argv[0], &principal); if (ret) krb5_err(context, 1, ret, "krb5_parse_name"); ret = krb5_unparse_name(context, principal, &p); if (ret) krb5_err(context, 1, ret, "krb5_unparse_name"); ret = krb5_kuserok(context, principal, argv[1]); krb5_free_principal(context, principal); krb5_free_context(context); printf("%s is %sallowed to login as %s\n", p, ret ? "" : "NOT ", argv[1]); free(p); if (ret) return 0; return 1; } heimdal-7.5.0/lib/krb5/rd_safe.c0000644000175000017500000001444113026237312014435 0ustar niknik/* * Copyright (c) 1997 - 2003 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "krb5_locl.h" static krb5_error_code verify_checksum(krb5_context context, krb5_auth_context auth_context, KRB_SAFE *safe) { krb5_error_code ret; u_char *buf; size_t buf_size; size_t len = 0; Checksum c; krb5_crypto crypto; krb5_keyblock *key; c = safe->cksum; safe->cksum.cksumtype = 0; safe->cksum.checksum.data = NULL; safe->cksum.checksum.length = 0; ASN1_MALLOC_ENCODE(KRB_SAFE, buf, buf_size, safe, &len, ret); if(ret) return ret; if(buf_size != len) krb5_abortx(context, "internal error in ASN.1 encoder"); if (auth_context->remote_subkey) key = auth_context->remote_subkey; else if (auth_context->local_subkey) key = auth_context->local_subkey; else key = auth_context->keyblock; ret = krb5_crypto_init(context, key, 0, &crypto); if (ret) goto out; ret = krb5_verify_checksum (context, crypto, KRB5_KU_KRB_SAFE_CKSUM, buf + buf_size - len, len, &c); krb5_crypto_destroy(context, crypto); out: safe->cksum = c; free (buf); return ret; } KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_rd_safe(krb5_context context, krb5_auth_context auth_context, const krb5_data *inbuf, krb5_data *outbuf, krb5_replay_data *outdata) { krb5_error_code ret; KRB_SAFE safe; size_t len; krb5_data_zero(outbuf); if ((auth_context->flags & (KRB5_AUTH_CONTEXT_RET_TIME | KRB5_AUTH_CONTEXT_RET_SEQUENCE))) { if (outdata == NULL) { krb5_set_error_message(context, KRB5_RC_REQUIRED, N_("rd_safe: need outdata " "to return data", "")); return KRB5_RC_REQUIRED; /* XXX better error, MIT returns this */ } /* if these fields are not present in the safe-part, silently return zero */ memset(outdata, 0, sizeof(*outdata)); } ret = decode_KRB_SAFE (inbuf->data, inbuf->length, &safe, &len); if (ret) return ret; if (safe.pvno != 5) { ret = KRB5KRB_AP_ERR_BADVERSION; krb5_clear_error_message (context); goto failure; } if (safe.msg_type != krb_safe) { ret = KRB5KRB_AP_ERR_MSG_TYPE; krb5_clear_error_message (context); goto failure; } if (!krb5_checksum_is_keyed(context, safe.cksum.cksumtype) || !krb5_checksum_is_collision_proof(context, safe.cksum.cksumtype)) { ret = KRB5KRB_AP_ERR_INAPP_CKSUM; krb5_clear_error_message (context); goto failure; } /* check sender address */ if (safe.safe_body.s_address && auth_context->remote_address && !krb5_address_compare (context, auth_context->remote_address, safe.safe_body.s_address)) { ret = KRB5KRB_AP_ERR_BADADDR; krb5_clear_error_message (context); goto failure; } /* check receiver address */ if (safe.safe_body.r_address && auth_context->local_address && !krb5_address_compare (context, auth_context->local_address, safe.safe_body.r_address)) { ret = KRB5KRB_AP_ERR_BADADDR; krb5_clear_error_message (context); goto failure; } /* check timestamp */ if (auth_context->flags & KRB5_AUTH_CONTEXT_DO_TIME) { krb5_timestamp sec; krb5_timeofday (context, &sec); if (safe.safe_body.timestamp == NULL || safe.safe_body.usec == NULL || labs(*safe.safe_body.timestamp - sec) > context->max_skew) { ret = KRB5KRB_AP_ERR_SKEW; krb5_clear_error_message (context); goto failure; } } /* XXX - check replay cache */ /* check sequence number. since MIT krb5 cannot generate a sequence number of zero but instead generates no sequence number, we accept that */ if (auth_context->flags & KRB5_AUTH_CONTEXT_DO_SEQUENCE) { if ((safe.safe_body.seq_number == NULL && auth_context->remote_seqnumber != 0) || (safe.safe_body.seq_number != NULL && *safe.safe_body.seq_number != auth_context->remote_seqnumber)) { ret = KRB5KRB_AP_ERR_BADORDER; krb5_clear_error_message (context); goto failure; } auth_context->remote_seqnumber++; } ret = verify_checksum (context, auth_context, &safe); if (ret) goto failure; outbuf->length = safe.safe_body.user_data.length; outbuf->data = malloc(outbuf->length); if (outbuf->data == NULL && outbuf->length != 0) { ret = krb5_enomem(context); krb5_data_zero(outbuf); goto failure; } memcpy (outbuf->data, safe.safe_body.user_data.data, outbuf->length); if ((auth_context->flags & (KRB5_AUTH_CONTEXT_RET_TIME | KRB5_AUTH_CONTEXT_RET_SEQUENCE))) { if(safe.safe_body.timestamp) outdata->timestamp = *safe.safe_body.timestamp; if(safe.safe_body.usec) outdata->usec = *safe.safe_body.usec; if(safe.safe_body.seq_number) outdata->seq = *safe.safe_body.seq_number; } failure: free_KRB_SAFE (&safe); return ret; } heimdal-7.5.0/lib/krb5/krb5_get_credentials.cat30000644000175000017500000001314113212450756017523 0ustar niknik KRB5_GET_CREDENTIALS(3) BSD Library Functions Manual KRB5_GET_CREDENTIALS(3) NNAAMMEE kkrrbb55__ggeett__ccrreeddeennttiiaallss, kkrrbb55__ggeett__ccrreeddeennttiiaallss__wwiitthh__ffllaaggss, kkrrbb55__ggeett__kkddcc__ccrreedd, kkrrbb55__ggeett__rreenneewweedd__ccrreeddss -- get credentials from the KDC using krbtgt LLIIBBRRAARRYY Kerberos 5 Library (libkrb5, -lkrb5) SSYYNNOOPPSSIISS ##iinncclluuddee <> _k_r_b_5___e_r_r_o_r___c_o_d_e kkrrbb55__ggeett__ccrreeddeennttiiaallss(_k_r_b_5___c_o_n_t_e_x_t _c_o_n_t_e_x_t, _k_r_b_5___f_l_a_g_s _o_p_t_i_o_n_s, _k_r_b_5___c_c_a_c_h_e _c_c_a_c_h_e, _k_r_b_5___c_r_e_d_s _*_i_n___c_r_e_d_s, _k_r_b_5___c_r_e_d_s _*_*_o_u_t___c_r_e_d_s); _k_r_b_5___e_r_r_o_r___c_o_d_e kkrrbb55__ggeett__ccrreeddeennttiiaallss__wwiitthh__ffllaaggss(_k_r_b_5___c_o_n_t_e_x_t _c_o_n_t_e_x_t, _k_r_b_5___f_l_a_g_s _o_p_t_i_o_n_s, _k_r_b_5___k_d_c___f_l_a_g_s _f_l_a_g_s, _k_r_b_5___c_c_a_c_h_e _c_c_a_c_h_e, _k_r_b_5___c_r_e_d_s _*_i_n___c_r_e_d_s, _k_r_b_5___c_r_e_d_s _*_*_o_u_t___c_r_e_d_s); _k_r_b_5___e_r_r_o_r___c_o_d_e kkrrbb55__ggeett__kkddcc__ccrreedd(_k_r_b_5___c_o_n_t_e_x_t _c_o_n_t_e_x_t, _k_r_b_5___c_c_a_c_h_e _i_d, _k_r_b_5___k_d_c___f_l_a_g_s _f_l_a_g_s, _k_r_b_5___a_d_d_r_e_s_s_e_s _*_a_d_d_r_e_s_s_e_s, _T_i_c_k_e_t _*_s_e_c_o_n_d___t_i_c_k_e_t, _k_r_b_5___c_r_e_d_s _*_i_n___c_r_e_d_s, _k_r_b_5___c_r_e_d_s _*_*_o_u_t___c_r_e_d_s); _k_r_b_5___e_r_r_o_r___c_o_d_e kkrrbb55__ggeett__rreenneewweedd__ccrreeddss(_k_r_b_5___c_o_n_t_e_x_t _c_o_n_t_e_x_t, _k_r_b_5___c_r_e_d_s _*_c_r_e_d_s, _k_r_b_5___c_o_n_s_t___p_r_i_n_c_i_p_a_l _c_l_i_e_n_t, _k_r_b_5___c_c_a_c_h_e _c_c_a_c_h_e, _c_o_n_s_t _c_h_a_r _*_i_n___t_k_t___s_e_r_v_i_c_e); DDEESSCCRRIIPPTTIIOONN kkrrbb55__ggeett__ccrreeddeennttiiaallss__wwiitthh__ffllaaggss() get credentials specified by _i_n___c_r_e_d_s_-_>_s_e_r_v_e_r and _i_n___c_r_e_d_s_-_>_c_l_i_e_n_t (the rest of the _i_n___c_r_e_d_s structure is ignored) by first looking in the _c_c_a_c_h_e and if doesn't exists or is expired, fetch the credential from the KDC using the krbtgt in _c_c_a_c_h_e. The credential is returned in _o_u_t___c_r_e_d_s and should be freed using the function kkrrbb55__ffrreeee__ccrreeddss(). Valid flags to pass into _o_p_t_i_o_n_s argument are: KRB5_GC_CACHED Only check the _c_c_a_c_h_e, don't got out on network to fetch credential. KRB5_GC_USER_USER Request a user to user ticket. This option doesn't store the resulting user to user credential in the _c_c_a_c_h_e. KRB5_GC_EXPIRED_OK returns the credential even if it is expired, default behavior is trying to refetch the credential from the KDC. _F_l_a_g_s are KDCOptions, note the caller must fill in the bit-field and not use the integer associated structure. kkrrbb55__ggeett__ccrreeddeennttiiaallss() works the same way as kkrrbb55__ggeett__ccrreeddeennttiiaallss__wwiitthh__ffllaaggss() except that the _f_l_a_g_s field is missing. kkrrbb55__ggeett__kkddcc__ccrreedd() does the same as the functions above, but the caller must fill in all the information andits closer to the wire protocol. kkrrbb55__ggeett__rreenneewweedd__ccrreeddss() renews a credential given by _i_n___t_k_t___s_e_r_v_i_c_e (if NULL the default krbtgt) using the credential cache _c_c_a_c_h_e. The result is stored in _c_r_e_d_s and should be freed using _k_r_b_5___f_r_e_e___c_r_e_d_s. EEXXAAMMPPLLEESS Here is a example function that get a credential from a credential cache _i_d or the KDC and returns it to the caller. #include int getcred(krb5_context context, krb5_ccache id, krb5_creds **creds) { krb5_error_code ret; krb5_creds in; ret = krb5_parse_name(context, "client@EXAMPLE.COM", &in.client); if (ret) krb5_err(context, 1, ret, "krb5_parse_name"); ret = krb5_parse_name(context, "host/server.example.com@EXAMPLE.COM", &in.server); if (ret) krb5_err(context, 1, ret, "krb5_parse_name"); ret = krb5_get_credentials(context, 0, id, &in, creds); if (ret) krb5_err(context, 1, ret, "krb5_get_credentials"); return 0; } SSEEEE AALLSSOO krb5(3), krb5_get_forwarded_creds(3), krb5.conf(5) HEIMDAL July 26, 2004 HEIMDAL heimdal-7.5.0/lib/krb5/pcache.c0000644000175000017500000000500213026237312014246 0ustar niknik/*********************************************************************** * Copyright (c) 2010, Secure Endpoints Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * - Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. * **********************************************************************/ #include "krb5_locl.h" #include "ccache_plugin.h" #ifdef HAVE_DLFCN_H #include #endif #include /* * cc_plugin_register_to_context is executed once per krb5_init_context(). * Its job is to register the plugin's krb5_cc_ops structure with the * krb5_context. */ static krb5_error_code KRB5_LIB_CALL cc_plugin_register_to_context(krb5_context context, const void *plug, void *plugctx, void *userctx) { krb5_cc_ops *ccops = (krb5_cc_ops *)plugctx; krb5_error_code ret; if (ccops == NULL || ccops->version < KRB5_CC_OPS_VERSION) return KRB5_PLUGIN_NO_HANDLE; ret = krb5_cc_register(context, ccops, TRUE); if (ret != 0) *((krb5_error_code *)userctx) = ret; return KRB5_PLUGIN_NO_HANDLE; } KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL _krb5_load_ccache_plugins(krb5_context context) { krb5_error_code userctx = 0; (void)_krb5_plugin_run_f(context, "krb5", KRB5_PLUGIN_CCACHE, 0, 0, &userctx, cc_plugin_register_to_context); return userctx; } heimdal-7.5.0/lib/krb5/krb5_getportbyname.30000644000175000017500000000450512136107750016560 0ustar niknik.\" Copyright (c) 2004 Kungliga Tekniska Högskolan .\" (Royal Institute of Technology, Stockholm, Sweden). .\" All rights reserved. .\" .\" Redistribution and use in source and binary forms, with or without .\" modification, are permitted provided that the following conditions .\" are met: .\" .\" 1. Redistributions of source code must retain the above copyright .\" notice, this list of conditions and the following disclaimer. .\" .\" 2. Redistributions in binary form must reproduce the above copyright .\" notice, this list of conditions and the following disclaimer in the .\" documentation and/or other materials provided with the distribution. .\" .\" 3. Neither the name of the Institute nor the names of its contributors .\" may be used to endorse or promote products derived from this software .\" without specific prior written permission. .\" .\" THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND .\" ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE .\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE .\" ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE .\" FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL .\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS .\" OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) .\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT .\" LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF .\" SUCH DAMAGE. .\" .\" $Id$ .\" .Dd August 15, 2004 .Dt NAME 3 .Os HEIMDAL .Sh NAME .Nm krb5_getportbyname .Nd get port number by name .Sh LIBRARY Kerberos 5 Library (libkrb5, -lkrb5) .Sh SYNOPSIS .In krb5.h .Ft int .Fo krb5_getportbyname .Fa "krb5_context context" .Fa "const char *service" .Fa "const char *proto" .Fa "int default_port" .Fc .Sh DESCRIPTION .Fn krb5_getportbyname gets the port number for .Fa service / .Fa proto pair from the global service table for and returns it in network order. If it isn't found in the global table, the .Fa default_port (given in host order) is returned. .Sh EXAMPLE .Bd -literal int port = krb5_getportbyname(context, "kerberos", "tcp", 88); .Ed .\" .Sh BUGS .Sh SEE ALSO .Xr krb5 3 heimdal-7.5.0/lib/krb5/db_plugin.c0000644000175000017500000000131213026237312014766 0ustar niknik/* */ #include "krb5_locl.h" #include "db_plugin.h" /* Default plugin (DB using binary search of sorted text file) follows */ static heim_base_once_t db_plugins_once = HEIM_BASE_ONCE_INIT; static krb5_error_code KRB5_LIB_CALL db_plugins_plcallback(krb5_context context, const void *plug, void *plugctx, void *userctx) { return 0; } static void db_plugins_init(void *arg) { krb5_context context = arg; (void)_krb5_plugin_run_f(context, "krb5", KRB5_PLUGIN_DB, KRB5_PLUGIN_DB_VERSION_0, 0, NULL, db_plugins_plcallback); } KRB5_LIB_FUNCTION void KRB5_LIB_CALL _krb5_load_db_plugins(krb5_context context) { heim_base_once_f(&db_plugins_once, context, db_plugins_init); } heimdal-7.5.0/lib/krb5/get_in_tkt.c0000644000175000017500000003403613212137553015166 0ustar niknik/* * Copyright (c) 1997 - 2008 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #define KRB5_DEPRECATED_FUNCTION(x) #include "krb5_locl.h" #ifndef HEIMDAL_SMALLER static krb5_error_code make_pa_enc_timestamp(krb5_context context, PA_DATA *pa, krb5_enctype etype, krb5_keyblock *key) { PA_ENC_TS_ENC p; unsigned char *buf; size_t buf_size; size_t len = 0; EncryptedData encdata; krb5_error_code ret; int32_t usec; int usec2; krb5_crypto crypto; krb5_us_timeofday (context, &p.patimestamp, &usec); usec2 = usec; p.pausec = &usec2; ASN1_MALLOC_ENCODE(PA_ENC_TS_ENC, buf, buf_size, &p, &len, ret); if (ret) return ret; if(buf_size != len) krb5_abortx(context, "internal error in ASN.1 encoder"); ret = krb5_crypto_init(context, key, 0, &crypto); if (ret) { free(buf); return ret; } ret = krb5_encrypt_EncryptedData(context, crypto, KRB5_KU_PA_ENC_TIMESTAMP, buf, len, 0, &encdata); free(buf); krb5_crypto_destroy(context, crypto); if (ret) return ret; ASN1_MALLOC_ENCODE(EncryptedData, buf, buf_size, &encdata, &len, ret); free_EncryptedData(&encdata); if (ret) return ret; if(buf_size != len) krb5_abortx(context, "internal error in ASN.1 encoder"); pa->padata_type = KRB5_PADATA_ENC_TIMESTAMP; pa->padata_value.length = len; pa->padata_value.data = buf; return 0; } static krb5_error_code add_padata(krb5_context context, METHOD_DATA *md, krb5_principal client, krb5_key_proc key_proc, krb5_const_pointer keyseed, krb5_enctype *enctypes, unsigned netypes, krb5_salt *salt) { krb5_error_code ret; PA_DATA *pa2; krb5_salt salt2; krb5_enctype *ep; size_t i; if(salt == NULL) { /* default to standard salt */ ret = krb5_get_pw_salt (context, client, &salt2); if (ret) return ret; salt = &salt2; } if (!enctypes) { enctypes = context->etypes; netypes = 0; for (ep = enctypes; *ep != (krb5_enctype)ETYPE_NULL; ep++) netypes++; } pa2 = realloc (md->val, (md->len + netypes) * sizeof(*md->val)); if (pa2 == NULL) return krb5_enomem(context); md->val = pa2; for (i = 0; i < netypes; ++i) { krb5_keyblock *key; ret = (*key_proc)(context, enctypes[i], *salt, keyseed, &key); if (ret) continue; ret = make_pa_enc_timestamp (context, &md->val[md->len], enctypes[i], key); krb5_free_keyblock (context, key); if (ret) return ret; ++md->len; } if(salt == &salt2) krb5_free_salt(context, salt2); return 0; } static krb5_error_code init_as_req (krb5_context context, KDCOptions opts, krb5_creds *creds, const krb5_addresses *addrs, const krb5_enctype *etypes, const krb5_preauthtype *ptypes, const krb5_preauthdata *preauth, krb5_key_proc key_proc, krb5_const_pointer keyseed, unsigned nonce, AS_REQ *a) { krb5_error_code ret; krb5_salt salt; memset(a, 0, sizeof(*a)); a->pvno = 5; a->msg_type = krb_as_req; a->req_body.kdc_options = opts; a->req_body.cname = malloc(sizeof(*a->req_body.cname)); if (a->req_body.cname == NULL) { ret = krb5_enomem(context); goto fail; } a->req_body.sname = malloc(sizeof(*a->req_body.sname)); if (a->req_body.sname == NULL) { ret = krb5_enomem(context); goto fail; } ret = _krb5_principal2principalname (a->req_body.cname, creds->client); if (ret) goto fail; ret = _krb5_principal2principalname (a->req_body.sname, creds->server); if (ret) goto fail; ret = copy_Realm(&creds->client->realm, &a->req_body.realm); if (ret) goto fail; if(creds->times.starttime) { a->req_body.from = malloc(sizeof(*a->req_body.from)); if (a->req_body.from == NULL) { ret = krb5_enomem(context); goto fail; } *a->req_body.from = creds->times.starttime; } if(creds->times.endtime){ ALLOC(a->req_body.till, 1); *a->req_body.till = creds->times.endtime; } if(creds->times.renew_till){ a->req_body.rtime = malloc(sizeof(*a->req_body.rtime)); if (a->req_body.rtime == NULL) { ret = krb5_enomem(context); goto fail; } *a->req_body.rtime = creds->times.renew_till; } a->req_body.nonce = nonce; ret = _krb5_init_etype(context, KRB5_PDU_AS_REQUEST, &a->req_body.etype.len, &a->req_body.etype.val, etypes); if (ret) goto fail; /* * This means no addresses */ if (addrs && addrs->len == 0) { a->req_body.addresses = NULL; } else { a->req_body.addresses = malloc(sizeof(*a->req_body.addresses)); if (a->req_body.addresses == NULL) { ret = krb5_enomem(context); goto fail; } if (addrs) ret = krb5_copy_addresses(context, addrs, a->req_body.addresses); else { ret = krb5_get_all_client_addrs (context, a->req_body.addresses); if(ret == 0 && a->req_body.addresses->len == 0) { free(a->req_body.addresses); a->req_body.addresses = NULL; } } if (ret) return ret; } a->req_body.enc_authorization_data = NULL; a->req_body.additional_tickets = NULL; if(preauth != NULL) { size_t i; ALLOC(a->padata, 1); if(a->padata == NULL) { ret = krb5_enomem(context); goto fail; } a->padata->val = NULL; a->padata->len = 0; for(i = 0; i < preauth->len; i++) { if(preauth->val[i].type == KRB5_PADATA_ENC_TIMESTAMP){ size_t j; for(j = 0; j < preauth->val[i].info.len; j++) { krb5_salt *sp = &salt; if(preauth->val[i].info.val[j].salttype) salt.salttype = *preauth->val[i].info.val[j].salttype; else salt.salttype = KRB5_PW_SALT; if(preauth->val[i].info.val[j].salt) salt.saltvalue = *preauth->val[i].info.val[j].salt; else if(salt.salttype == KRB5_PW_SALT) sp = NULL; else krb5_data_zero(&salt.saltvalue); ret = add_padata(context, a->padata, creds->client, key_proc, keyseed, &preauth->val[i].info.val[j].etype, 1, sp); if (ret == 0) break; } } } } else /* not sure this is the way to use `ptypes' */ if (ptypes == NULL || *ptypes == KRB5_PADATA_NONE) a->padata = NULL; else if (*ptypes == KRB5_PADATA_ENC_TIMESTAMP) { ALLOC(a->padata, 1); if (a->padata == NULL) { ret = krb5_enomem(context); goto fail; } a->padata->len = 0; a->padata->val = NULL; /* make a v5 salted pa-data */ add_padata(context, a->padata, creds->client, key_proc, keyseed, a->req_body.etype.val, a->req_body.etype.len, NULL); /* make a v4 salted pa-data */ salt.salttype = KRB5_PW_SALT; krb5_data_zero(&salt.saltvalue); add_padata(context, a->padata, creds->client, key_proc, keyseed, a->req_body.etype.val, a->req_body.etype.len, &salt); } else { ret = KRB5_PREAUTH_BAD_TYPE; krb5_set_error_message (context, ret, N_("pre-auth type %d not supported", ""), *ptypes); goto fail; } return 0; fail: free_AS_REQ(a); return ret; } static int set_ptypes(krb5_context context, KRB_ERROR *error, const krb5_preauthtype **ptypes, krb5_preauthdata **preauth) { static krb5_preauthdata preauth2; static krb5_preauthtype ptypes2[] = { KRB5_PADATA_ENC_TIMESTAMP, KRB5_PADATA_NONE }; if(error->e_data) { METHOD_DATA md; size_t i; decode_METHOD_DATA(error->e_data->data, error->e_data->length, &md, NULL); for(i = 0; i < md.len; i++){ switch(md.val[i].padata_type){ case KRB5_PADATA_ENC_TIMESTAMP: *ptypes = ptypes2; break; case KRB5_PADATA_ETYPE_INFO: *preauth = &preauth2; ALLOC_SEQ(*preauth, 1); (*preauth)->val[0].type = KRB5_PADATA_ENC_TIMESTAMP; decode_ETYPE_INFO(md.val[i].padata_value.data, md.val[i].padata_value.length, &(*preauth)->val[0].info, NULL); break; default: break; } } free_METHOD_DATA(&md); } else { *ptypes = ptypes2; } return(1); } KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_get_in_cred(krb5_context context, krb5_flags options, const krb5_addresses *addrs, const krb5_enctype *etypes, const krb5_preauthtype *ptypes, const krb5_preauthdata *preauth, krb5_key_proc key_proc, krb5_const_pointer keyseed, krb5_decrypt_proc decrypt_proc, krb5_const_pointer decryptarg, krb5_creds *creds, krb5_kdc_rep *ret_as_reply) KRB5_DEPRECATED_FUNCTION("Use X instead") { krb5_error_code ret; AS_REQ a; krb5_kdc_rep rep; krb5_data req, resp; size_t len = 0; krb5_salt salt; krb5_keyblock *key; size_t size; KDCOptions opts; PA_DATA *pa; krb5_enctype etype; krb5_preauthdata *my_preauth = NULL; unsigned nonce; int done; opts = int2KDCOptions(options); krb5_generate_random_block (&nonce, sizeof(nonce)); nonce &= 0xffffffff; do { done = 1; ret = init_as_req (context, opts, creds, addrs, etypes, ptypes, preauth, key_proc, keyseed, nonce, &a); if (my_preauth) { free_ETYPE_INFO(&my_preauth->val[0].info); free (my_preauth->val); my_preauth = NULL; } if (ret) return ret; ASN1_MALLOC_ENCODE(AS_REQ, req.data, req.length, &a, &len, ret); free_AS_REQ(&a); if (ret) return ret; if(len != req.length) krb5_abortx(context, "internal error in ASN.1 encoder"); ret = krb5_sendto_kdc (context, &req, &creds->client->realm, &resp); krb5_data_free(&req); if (ret) return ret; memset (&rep, 0, sizeof(rep)); ret = decode_AS_REP(resp.data, resp.length, &rep.kdc_rep, &size); if(ret) { /* let's try to parse it as a KRB-ERROR */ KRB_ERROR error; int ret2; ret2 = krb5_rd_error(context, &resp, &error); if(ret2 && resp.data && ((char*)resp.data)[0] == 4) ret = KRB5KRB_AP_ERR_V4_REPLY; krb5_data_free(&resp); if (ret2 == 0) { ret = krb5_error_from_rd_error(context, &error, creds); /* if no preauth was set and KDC requires it, give it one more try */ if (!ptypes && !preauth && ret == KRB5KDC_ERR_PREAUTH_REQUIRED #if 0 || ret == KRB5KDC_ERR_BADOPTION #endif && set_ptypes(context, &error, &ptypes, &my_preauth)) { done = 0; preauth = my_preauth; krb5_free_error_contents(context, &error); krb5_clear_error_message(context); continue; } if(ret_as_reply) ret_as_reply->error = error; else free_KRB_ERROR (&error); return ret; } return ret; } krb5_data_free(&resp); } while(!done); pa = NULL; etype = rep.kdc_rep.enc_part.etype; if(rep.kdc_rep.padata){ int i = 0; pa = krb5_find_padata(rep.kdc_rep.padata->val, rep.kdc_rep.padata->len, KRB5_PADATA_PW_SALT, &i); if(pa == NULL) { i = 0; pa = krb5_find_padata(rep.kdc_rep.padata->val, rep.kdc_rep.padata->len, KRB5_PADATA_AFS3_SALT, &i); } } if(pa) { salt.salttype = (krb5_salttype)pa->padata_type; salt.saltvalue = pa->padata_value; ret = (*key_proc)(context, etype, salt, keyseed, &key); } else { /* make a v5 salted pa-data */ ret = krb5_get_pw_salt (context, creds->client, &salt); if (ret) goto out; ret = (*key_proc)(context, etype, salt, keyseed, &key); krb5_free_salt(context, salt); } if (ret) goto out; { unsigned flags = EXTRACT_TICKET_TIMESYNC; if (opts.request_anonymous) flags |= EXTRACT_TICKET_ALLOW_SERVER_MISMATCH; ret = _krb5_extract_ticket(context, &rep, creds, key, keyseed, KRB5_KU_AS_REP_ENC_PART, NULL, nonce, flags, NULL, decrypt_proc, decryptarg); } memset (key->keyvalue.data, 0, key->keyvalue.length); krb5_free_keyblock_contents (context, key); free (key); out: if (ret == 0 && ret_as_reply) *ret_as_reply = rep; else krb5_free_kdc_rep (context, &rep); return ret; } KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_get_in_tkt(krb5_context context, krb5_flags options, const krb5_addresses *addrs, const krb5_enctype *etypes, const krb5_preauthtype *ptypes, krb5_key_proc key_proc, krb5_const_pointer keyseed, krb5_decrypt_proc decrypt_proc, krb5_const_pointer decryptarg, krb5_creds *creds, krb5_ccache ccache, krb5_kdc_rep *ret_as_reply) KRB5_DEPRECATED_FUNCTION("Use X instead") { krb5_error_code ret; ret = krb5_get_in_cred (context, options, addrs, etypes, ptypes, NULL, key_proc, keyseed, decrypt_proc, decryptarg, creds, ret_as_reply); if(ret) return ret; if (ccache) ret = krb5_cc_store_cred (context, ccache, creds); return ret; } #endif /* HEIMDAL_SMALLER */ heimdal-7.5.0/lib/krb5/build_auth.c0000644000175000017500000001254313212137553015156 0ustar niknik/* * Copyright (c) 1997 - 2003 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "krb5_locl.h" static krb5_error_code make_etypelist(krb5_context context, krb5_authdata **auth_data) { EtypeList etypes; krb5_error_code ret; krb5_authdata ad; u_char *buf; size_t len = 0; size_t buf_size; ret = _krb5_init_etype(context, KRB5_PDU_NONE, &etypes.len, &etypes.val, NULL); if (ret) return ret; ASN1_MALLOC_ENCODE(EtypeList, buf, buf_size, &etypes, &len, ret); if (ret) { free_EtypeList(&etypes); return ret; } if(buf_size != len) krb5_abortx(context, "internal error in ASN.1 encoder"); free_EtypeList(&etypes); ALLOC_SEQ(&ad, 1); if (ad.val == NULL) { free(buf); return krb5_enomem(context); } ad.val[0].ad_type = KRB5_AUTHDATA_GSS_API_ETYPE_NEGOTIATION; ad.val[0].ad_data.length = len; ad.val[0].ad_data.data = buf; ASN1_MALLOC_ENCODE(AD_IF_RELEVANT, buf, buf_size, &ad, &len, ret); if (ret) { free_AuthorizationData(&ad); return ret; } if(buf_size != len) krb5_abortx(context, "internal error in ASN.1 encoder"); free_AuthorizationData(&ad); ALLOC(*auth_data, 1); if (*auth_data == NULL) { free(buf); return krb5_enomem(context); } ALLOC_SEQ(*auth_data, 1); if ((*auth_data)->val == NULL) { free(*auth_data); free(buf); return krb5_enomem(context); } (*auth_data)->val[0].ad_type = KRB5_AUTHDATA_IF_RELEVANT; (*auth_data)->val[0].ad_data.length = len; (*auth_data)->val[0].ad_data.data = buf; return 0; } KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL _krb5_build_authenticator (krb5_context context, krb5_auth_context auth_context, krb5_enctype enctype, krb5_creds *cred, Checksum *cksum, krb5_data *result, krb5_key_usage usage) { Authenticator auth; u_char *buf = NULL; size_t buf_size; size_t len = 0; krb5_error_code ret; krb5_crypto crypto; memset(&auth, 0, sizeof(auth)); auth.authenticator_vno = 5; copy_Realm(&cred->client->realm, &auth.crealm); copy_PrincipalName(&cred->client->name, &auth.cname); krb5_us_timeofday (context, &auth.ctime, &auth.cusec); ret = krb5_auth_con_getlocalsubkey(context, auth_context, &auth.subkey); if(ret) goto fail; if (auth_context->flags & KRB5_AUTH_CONTEXT_DO_SEQUENCE) { if(auth_context->local_seqnumber == 0) krb5_generate_seq_number (context, &cred->session, &auth_context->local_seqnumber); ALLOC(auth.seq_number, 1); if(auth.seq_number == NULL) { ret = krb5_enomem(context); goto fail; } *auth.seq_number = auth_context->local_seqnumber; } else auth.seq_number = NULL; auth.authorization_data = NULL; if (cksum) { ALLOC(auth.cksum, 1); if (auth.cksum == NULL) { ret = krb5_enomem(context); goto fail; } ret = copy_Checksum(cksum, auth.cksum); if (ret) goto fail; if (auth.cksum->cksumtype == CKSUMTYPE_GSSAPI) { /* * This is not GSS-API specific, we only enable it for * GSS for now */ ret = make_etypelist(context, &auth.authorization_data); if (ret) goto fail; } } /* XXX - Copy more to auth_context? */ auth_context->authenticator->ctime = auth.ctime; auth_context->authenticator->cusec = auth.cusec; ASN1_MALLOC_ENCODE(Authenticator, buf, buf_size, &auth, &len, ret); if (ret) goto fail; if(buf_size != len) krb5_abortx(context, "internal error in ASN.1 encoder"); ret = krb5_crypto_init(context, &cred->session, enctype, &crypto); if (ret) goto fail; ret = krb5_encrypt (context, crypto, usage /* KRB5_KU_AP_REQ_AUTH */, buf, len, result); krb5_crypto_destroy(context, crypto); if (ret) goto fail; fail: free_Authenticator (&auth); free (buf); return ret; } heimdal-7.5.0/lib/krb5/krb5_get_creds.cat30000644000175000017500000001466113212450756016336 0ustar niknik KRB5_GET_CREDS(3) BSD Library Functions Manual KRB5_GET_CREDS(3) NNAAMMEE kkrrbb55__ggeett__ccrreeddss, kkrrbb55__ggeett__ccrreeddss__oopptt__aadddd__ooppttiioonnss, kkrrbb55__ggeett__ccrreeddss__oopptt__aalllloocc, kkrrbb55__ggeett__ccrreeddss__oopptt__ffrreeee, kkrrbb55__ggeett__ccrreeddss__oopptt__sseett__eennccttyyppee, kkrrbb55__ggeett__ccrreeddss__oopptt__sseett__iimmppeerrssoonnaattee, kkrrbb55__ggeett__ccrreeddss__oopptt__sseett__ooppttiioonnss, kkrrbb55__ggeett__ccrreeddss__oopptt__sseett__ttiicckkeett -- get credentials from the KDC LLIIBBRRAARRYY Kerberos 5 Library (libkrb5, -lkrb5) SSYYNNOOPPSSIISS ##iinncclluuddee <> _k_r_b_5___e_r_r_o_r___c_o_d_e kkrrbb55__ggeett__ccrreeddss(_k_r_b_5___c_o_n_t_e_x_t _c_o_n_t_e_x_t, _k_r_b_5___g_e_t___c_r_e_d_s___o_p_t _o_p_t, _k_r_b_5___c_c_a_c_h_e _c_c_a_c_h_e, _k_r_b_5___c_o_n_s_t___p_r_i_n_c_i_p_a_l _i_n_p_r_i_n_c, _k_r_b_5___c_r_e_d_s _*_*_o_u_t___c_r_e_d_s); _v_o_i_d kkrrbb55__ggeett__ccrreeddss__oopptt__aadddd__ooppttiioonnss(_k_r_b_5___c_o_n_t_e_x_t _c_o_n_t_e_x_t, _k_r_b_5___g_e_t___c_r_e_d_s___o_p_t _o_p_t, _k_r_b_5___f_l_a_g_s _o_p_t_i_o_n_s); _k_r_b_5___e_r_r_o_r___c_o_d_e kkrrbb55__ggeett__ccrreeddss__oopptt__aalllloocc(_k_r_b_5___c_o_n_t_e_x_t _c_o_n_t_e_x_t, _k_r_b_5___g_e_t___c_r_e_d_s___o_p_t _*_o_p_t); _v_o_i_d kkrrbb55__ggeett__ccrreeddss__oopptt__ffrreeee(_k_r_b_5___c_o_n_t_e_x_t _c_o_n_t_e_x_t, _k_r_b_5___g_e_t___c_r_e_d_s___o_p_t _o_p_t); _v_o_i_d kkrrbb55__ggeett__ccrreeddss__oopptt__sseett__eennccttyyppee(_k_r_b_5___c_o_n_t_e_x_t _c_o_n_t_e_x_t, _k_r_b_5___g_e_t___c_r_e_d_s___o_p_t _o_p_t, _k_r_b_5___e_n_c_t_y_p_e _e_n_c_t_y_p_e); _k_r_b_5___e_r_r_o_r___c_o_d_e kkrrbb55__ggeett__ccrreeddss__oopptt__sseett__iimmppeerrssoonnaattee(_k_r_b_5___c_o_n_t_e_x_t _c_o_n_t_e_x_t, _k_r_b_5___g_e_t___c_r_e_d_s___o_p_t _o_p_t, _k_r_b_5___c_o_n_s_t___p_r_i_n_c_i_p_a_l _s_e_l_f); _v_o_i_d kkrrbb55__ggeett__ccrreeddss__oopptt__sseett__ooppttiioonnss(_k_r_b_5___c_o_n_t_e_x_t _c_o_n_t_e_x_t, _k_r_b_5___g_e_t___c_r_e_d_s___o_p_t _o_p_t, _k_r_b_5___f_l_a_g_s _o_p_t_i_o_n_s); _k_r_b_5___e_r_r_o_r___c_o_d_e kkrrbb55__ggeett__ccrreeddss__oopptt__sseett__ttiicckkeett(_k_r_b_5___c_o_n_t_e_x_t _c_o_n_t_e_x_t, _k_r_b_5___g_e_t___c_r_e_d_s___o_p_t _o_p_t, _c_o_n_s_t _T_i_c_k_e_t _*_t_i_c_k_e_t); DDEESSCCRRIIPPTTIIOONN kkrrbb55__ggeett__ccrreeddss() fetches credentials specified by _o_p_t by first looking in the _c_c_a_c_h_e, and then it doesn't exists, fetch the credential from the KDC using the krbtgts in _c_c_a_c_h_e. The credential is returned in _o_u_t___c_r_e_d_s and should be freed using the function kkrrbb55__ffrreeee__ccrreeddss(). The structure krb5_get_creds_opt controls the behavior of kkrrbb55__ggeett__ccrreeddss(). The structure is opaque to consumers that can set the content of the structure with accessors functions. All accessor functions make copies of the data that is passed into accessor functions, so exter- nal consumers free the memory before calling kkrrbb55__ggeett__ccrreeddss(). The structure krb5_get_creds_opt is allocated with kkrrbb55__ggeett__ccrreeddss__oopptt__aalllloocc() and freed with kkrrbb55__ggeett__ccrreeddss__oopptt__ffrreeee(). The free function also frees the content of the structure set by the accessor functions. kkrrbb55__ggeett__ccrreeddss__oopptt__aadddd__ooppttiioonnss() and kkrrbb55__ggeett__ccrreeddss__oopptt__sseett__ooppttiioonnss() adds and sets options to the krb5_get_creds_opt structure . The possible options to set are KRB5_GC_CACHED Only check the _c_c_a_c_h_e, don't got out on network to fetch credential. KRB5_GC_USER_USER request a user to user ticket. This options doesn't store the resulting user to user credential in the _c_c_a_c_h_e. KRB5_GC_EXPIRED_OK returns the credential even if it is expired, default behavior is trying to refetch the credential from the KDC. KRB5_GC_NO_STORE Do not store the resulting credentials in the _c_c_a_c_h_e. kkrrbb55__ggeett__ccrreeddss__oopptt__sseett__eennccttyyppee() sets the preferred encryption type of the application. Don't set this unless you have to since if there is no match in the KDC, the function call will fail. kkrrbb55__ggeett__ccrreeddss__oopptt__sseett__iimmppeerrssoonnaattee() sets the principal to impersonate., Returns a ticket that have the impersonation principal as a client and the requestor as the service. Note that the requested principal have to be the same as the client principal in the krbtgt. kkrrbb55__ggeett__ccrreeddss__oopptt__sseett__ttiicckkeett() sets the extra ticket used in user-to- user or contrained delegation use case. SSEEEE AALLSSOO krb5(3), krb5_get_credentials(3), krb5.conf(5) HEIMDAL June 15, 2006 HEIMDAL heimdal-7.5.0/lib/krb5/krb5_mk_req.30000644000175000017500000001226513026237312015155 0ustar niknik.\" Copyright (c) 2005 Kungliga Tekniska Högskolan .\" (Royal Institute of Technology, Stockholm, Sweden). .\" All rights reserved. .\" .\" Redistribution and use in source and binary forms, with or without .\" modification, are permitted provided that the following conditions .\" are met: .\" .\" 1. Redistributions of source code must retain the above copyright .\" notice, this list of conditions and the following disclaimer. .\" .\" 2. Redistributions in binary form must reproduce the above copyright .\" notice, this list of conditions and the following disclaimer in the .\" documentation and/or other materials provided with the distribution. .\" .\" 3. Neither the name of the Institute nor the names of its contributors .\" may be used to endorse or promote products derived from this software .\" without specific prior written permission. .\" .\" THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND .\" ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE .\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE .\" ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE .\" FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL .\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS .\" OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) .\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT .\" LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF .\" SUCH DAMAGE. .\" .\" $Id$ .\" .Dd August 27, 2005 .Dt KRB5_MK_REQ 3 .Os HEIMDAL .Sh NAME .Nm krb5_mk_req , .Nm krb5_mk_req_exact , .Nm krb5_mk_req_extended , .Nm krb5_rd_req , .Nm krb5_rd_req_with_keyblock , .Nm krb5_mk_rep , .Nm krb5_mk_rep_exact , .Nm krb5_mk_rep_extended , .Nm krb5_rd_rep , .Nm krb5_build_ap_req , .Nm krb5_verify_ap_req .Nd create and read application authentication request .Sh LIBRARY Kerberos 5 Library (libkrb5, -lkrb5) .Sh SYNOPSIS .In krb5.h .Ft krb5_error_code .Fo krb5_mk_req .Fa "krb5_context context" .Fa "krb5_auth_context *auth_context" .Fa "const krb5_flags ap_req_options" .Fa "const char *service" .Fa "const char *hostname" .Fa "krb5_data *in_data" .Fa "krb5_ccache ccache" .Fa "krb5_data *outbuf" .Fc .Ft krb5_error_code .Fo krb5_mk_req_extended .Fa "krb5_context context" .Fa "krb5_auth_context *auth_context" .Fa "const krb5_flags ap_req_options" .Fa "krb5_data *in_data" .Fa "krb5_creds *in_creds" .Fa "krb5_data *outbuf" .Fc .Ft krb5_error_code .Fo krb5_rd_req .Fa "krb5_context context" .Fa "krb5_auth_context *auth_context" .Fa "const krb5_data *inbuf" .Fa "krb5_const_principal server" .Fa "krb5_keytab keytab" .Fa "krb5_flags *ap_req_options" .Fa "krb5_ticket **ticket" .Fc .Ft krb5_error_code .Fo krb5_build_ap_req .Fa "krb5_context context" .Fa "krb5_enctype enctype" .Fa "krb5_creds *cred" .Fa "krb5_flags ap_options" .Fa "krb5_data authenticator" .Fa "krb5_data *retdata" .Fc .Ft krb5_error_code .Fo krb5_verify_ap_req .Fa "krb5_context context" .Fa "krb5_auth_context *auth_context" .Fa "krb5_ap_req *ap_req" .Fa "krb5_const_principal server" .Fa "krb5_keyblock *keyblock" .Fa "krb5_flags flags" .Fa "krb5_flags *ap_req_options" .Fa "krb5_ticket **ticket" .Fc .Sh DESCRIPTION The functions documented in this manual page document the functions that facilitates the exchange between a Kerberos client and server. They are the core functions used in the authentication exchange between the client and the server. .Pp The .Nm krb5_mk_req and .Nm krb5_mk_req_extended creates the Kerberos message .Dv KRB_AP_REQ that is sent from the client to the server as the first packet in a client/server exchange. The result that should be sent to server is stored in .Fa outbuf . .Pp .Fa auth_context should be allocated with .Fn krb5_auth_con_init or .Dv NULL passed in, in that case, it will be allocated and freed internally. .Pp The input data .Fa in_data will have a checksum calculated over it and checksum will be transported in the message to the server. .Pp .Fa ap_req_options can be set to one or more of the following flags: .Pp .Bl -tag -width indent .It Dv AP_OPTS_USE_SESSION_KEY Use the session key when creating the request, used for user to user authentication. .It Dv AP_OPTS_MUTUAL_REQUIRED Mark the request as mutual authenticate required so that the receiver returns a mutual authentication packet. .El .Pp The .Nm krb5_rd_req read the AP_REQ in .Fa inbuf and verify and extract the content. If .Fa server is specified, that server will be fetched from the .Fa keytab and used unconditionally. If .Fa server is .Dv NULL , the .Fa keytab will be search for a matching principal. .Pp The .Fa keytab argument specifies what keytab to search for receiving principals. The arguments .Fa ap_req_options and .Fa ticket returns the content. .Pp When the AS-REQ is a user to user request, neither of .Fa keytab or .Fa principal are used, instead .Fn krb5_rd_req expects the session key to be set in .Fa auth_context . .Pp The .Nm krb5_verify_ap_req and .Nm krb5_build_ap_req both constructs and verify the AP_REQ message, should not be used by external code. .Sh SEE ALSO .Xr krb5 3 , .Xr krb5.conf 5 heimdal-7.5.0/lib/krb5/get_host_realm.c0000644000175000017500000002145113026237312016025 0ustar niknik/* * Copyright (c) 1997 - 2005 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "krb5_locl.h" #include /* To automagically find the correct realm of a host (without * [domain_realm] in krb5.conf) add a text record for your domain with * the name of your realm, like this: * * _kerberos IN TXT "FOO.SE" * * The search is recursive, so you can add entries for specific * hosts. To find the realm of host a.b.c, it first tries * _kerberos.a.b.c, then _kerberos.b.c and so on. * * This method is described in draft-ietf-cat-krb-dns-locate-03.txt. * */ static int copy_txt_to_realms(krb5_context context, const char *domain, struct rk_resource_record *head, krb5_realm **realms) { struct rk_resource_record *rr; unsigned int n, i; for(n = 0, rr = head; rr; rr = rr->next) if (rr->type == rk_ns_t_txt) ++n; if (n == 0) return -1; *realms = malloc ((n + 1) * sizeof(krb5_realm)); if (*realms == NULL) return krb5_enomem(context);; for (i = 0; i < n + 1; ++i) (*realms)[i] = NULL; for (i = 0, rr = head; rr; rr = rr->next) { if (rr->type == rk_ns_t_txt) { char *tmp = NULL; int invalid_tld = 1; /* Check for a gTLD controlled interruption */ if (strcmp("Your DNS configuration needs immediate " "attention see https://icann.org/namecollision", rr->u.txt) != 0) { invalid_tld = 0; tmp = strdup(rr->u.txt); } if (tmp == NULL) { for (i = 0; i < n; ++i) free ((*realms)[i]); free (*realms); if (invalid_tld) { krb5_warnx(context, "Realm lookup failed: " "Domain '%s' needs immediate attention " "see https://icann.org/namecollision", domain); return KRB5_KDC_UNREACH; } return krb5_enomem(context);; } (*realms)[i] = tmp; ++i; } } return 0; } static int dns_find_realm(krb5_context context, const char *domain, krb5_realm **realms) { static const char *default_labels[] = { "_kerberos", NULL }; char dom[MAXHOSTNAMELEN]; struct rk_dns_reply *r; const char **labels; char **config_labels; int i, ret = 0; config_labels = krb5_config_get_strings(context, NULL, "libdefaults", "dns_lookup_realm_labels", NULL); if(config_labels != NULL) labels = (const char **)config_labels; else labels = default_labels; if(*domain == '.') domain++; for (i = 0; labels[i] != NULL; i++) { ret = snprintf(dom, sizeof(dom), "%s.%s.", labels[i], domain); if(ret < 0 || (size_t)ret >= sizeof(dom)) { ret = krb5_enomem(context); goto out; } r = rk_dns_lookup(dom, "TXT"); if(r != NULL) { ret = copy_txt_to_realms(context, domain, r->head, realms); rk_dns_free_data(r); if(ret == 0) goto out; } } krb5_set_error_message(context, KRB5_KDC_UNREACH, "Realm lookup failed: " "No DNS TXT record for %s", domain); ret = KRB5_KDC_UNREACH; out: if (config_labels) krb5_config_free_strings(config_labels); return ret; } /* * Try to figure out what realms host in `domain' belong to from the * configuration file. */ static int config_find_realm(krb5_context context, const char *domain, krb5_realm **realms) { char **tmp = krb5_config_get_strings (context, NULL, "domain_realm", domain, NULL); if (tmp == NULL) return -1; *realms = tmp; return 0; } /* * This function assumes that `host' is a FQDN (and doesn't handle the * special case of host == NULL either). * Try to find mapping in the config file or DNS and it that fails, * fall back to guessing */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL _krb5_get_host_realm_int(krb5_context context, const char *host, krb5_boolean use_dns, krb5_realm **realms) { const char *p, *q; const char *port; krb5_boolean dns_locate_enable; krb5_error_code ret = 0; /* Strip off any trailing ":port" suffix. */ port = strchr(host, ':'); if (port != NULL) { host = strndup(host, port - host); if (host == NULL) return krb5_enomem(context); } dns_locate_enable = krb5_config_get_bool_default(context, NULL, TRUE, "libdefaults", "dns_lookup_realm", NULL); for (p = host; p != NULL; p = strchr (p + 1, '.')) { if (config_find_realm(context, p, realms) == 0) { if (strcasecmp(*realms[0], "dns_locate") != 0) break; krb5_free_host_realm(context, *realms); *realms = NULL; if (!use_dns) continue; for (q = host; q != NULL; q = strchr(q + 1, '.')) if (dns_find_realm(context, q, realms) == 0) break; if (q) break; } else if (use_dns && dns_locate_enable) { if (dns_find_realm(context, p, realms) == 0) break; } } /* * If 'p' is NULL, we did not find an explicit realm mapping in either the * configuration file or DNS. Try the hostname suffix as a last resort. * * XXX: If we implement a KDC-specific variant of this function just for * referrals, we could check whether we have a cross-realm TGT for the * realm in question, and if not try the parent (loop again). */ if (p == NULL) { p = strchr(host, '.'); if (p != NULL) { p++; *realms = malloc(2 * sizeof(krb5_realm)); if (*realms != NULL && ((*realms)[0] = strdup(p)) != NULL) { strupr((*realms)[0]); (*realms)[1] = NULL; } else { free(*realms); ret = krb5_enomem(context); } } else { krb5_set_error_message(context, KRB5_ERR_HOST_REALM_UNKNOWN, N_("unable to find realm of host %s", ""), host); ret = KRB5_ERR_HOST_REALM_UNKNOWN; } } /* If 'port' is not NULL, we have a copy of 'host' to free. */ if (port) free((void *)host); return ret; } /* * Return the realm(s) of `host' as a NULL-terminated list in * `realms'. Free `realms' with krb5_free_host_realm(). */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_get_host_realm(krb5_context context, const char *targethost, krb5_realm **realms) { const char *host = targethost; char hostname[MAXHOSTNAMELEN]; krb5_error_code ret; int use_dns; if (host == NULL) { if (gethostname (hostname, sizeof(hostname))) { *realms = NULL; return errno; } host = hostname; } /* * If our local hostname is without components, don't even try to dns. */ use_dns = (strchr(host, '.') != NULL); ret = _krb5_get_host_realm_int (context, host, use_dns, realms); if (ret && targethost != NULL) { /* * If there was no realm mapping for the host (and we wasn't * looking for ourself), guess at the local realm, maybe our * KDC knows better then we do and we get a referral back. */ ret = krb5_get_default_realms(context, realms); if (ret) { krb5_set_error_message(context, KRB5_ERR_HOST_REALM_UNKNOWN, N_("Unable to find realm of host %s", ""), host); return KRB5_ERR_HOST_REALM_UNKNOWN; } } return ret; } heimdal-7.5.0/lib/krb5/config_reg.c0000644000175000017500000004611013026237312015132 0ustar niknik/*********************************************************************** * Copyright (c) 2010, Secure Endpoints Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * - Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. * **********************************************************************/ #include "krb5_locl.h" #ifndef _WIN32 #error config_reg.c is only for Windows #endif #include #ifndef MAX_DWORD #define MAX_DWORD 0xFFFFFFFF #endif #define REGPATH_KERBEROS "SOFTWARE\\Kerberos" #define REGPATH_HEIMDAL "SOFTWARE\\Heimdal" /** * Store a string as a registry value of the specified type * * The following registry types are handled: * * - REG_DWORD: The string is converted to a number. * * - REG_SZ: The string is stored as is. * * - REG_EXPAND_SZ: The string is stored as is. * * - REG_MULTI_SZ: * * . If a separator is specified, the input string is broken * up into multiple strings and stored as a multi-sz. * * . If no separator is provided, the input string is stored * as a multi-sz. * * - REG_NONE: * * . If the string is all numeric, it will be stored as a * REG_DWORD. * * . Otherwise, the string is stored as a REG_SZ. * * Other types are rejected. * * If cb_data is MAX_DWORD, the string pointed to by data must be nul-terminated * otherwise a buffer overrun will occur. * * @param [in]valuename Name of the registry value to be modified or created * @param [in]type Type of the value. REG_NONE if unknown * @param [in]data The input string to be stored in the registry. * @param [in]cb_data Size of the input string in bytes. MAX_DWORD if unknown. * @param [in]separator Separator character for parsing strings. * * @retval 0 if success or non-zero on error. * If non-zero is returned, an error message has been set using * krb5_set_error_message(). * */ KRB5_LIB_FUNCTION int KRB5_LIB_CALL _krb5_store_string_to_reg_value(krb5_context context, HKEY key, const char * valuename, DWORD type, const char *data, DWORD cb_data, const char * separator) { LONG rcode; DWORD dwData; BYTE static_buffer[16384]; BYTE *pbuffer = &static_buffer[0]; if (data == NULL) { if (context) krb5_set_error_message(context, 0, "'data' must not be NULL"); return -1; } if (cb_data == MAX_DWORD) { cb_data = (DWORD)strlen(data) + 1; } else if ((type == REG_MULTI_SZ && cb_data >= sizeof(static_buffer) - 1) || cb_data >= sizeof(static_buffer)) { if (context) krb5_set_error_message(context, 0, "cb_data too big"); return -1; } else if (data[cb_data-1] != '\0') { memcpy(static_buffer, data, cb_data); static_buffer[cb_data++] = '\0'; if (type == REG_MULTI_SZ) static_buffer[cb_data++] = '\0'; data = static_buffer; } if (type == REG_NONE) { /* * If input is all numeric, convert to DWORD and save as REG_DWORD. * Otherwise, store as REG_SZ. */ if ( StrToIntExA( data, STIF_SUPPORT_HEX, &dwData) ) { type = REG_DWORD; } else { type = REG_SZ; } } switch (type) { case REG_SZ: case REG_EXPAND_SZ: rcode = RegSetValueEx(key, valuename, 0, type, data, cb_data); if (rcode) { if (context) krb5_set_error_message(context, 0, "Unexpected error when setting registry value %s gle 0x%x", valuename, GetLastError()); return -1; } break; case REG_MULTI_SZ: if (separator && *separator) { char *cp; if (data != static_buffer) static_buffer[cb_data++] = '\0'; for ( cp = static_buffer; cp < static_buffer+cb_data; cp++) { if (*cp == *separator) *cp = '\0'; } rcode = RegSetValueEx(key, valuename, 0, type, data, cb_data); if (rcode) { if (context) krb5_set_error_message(context, 0, "Unexpected error when setting registry value %s gle 0x%x", valuename, GetLastError()); return -1; } } break; case REG_DWORD: if ( !StrToIntExA( data, STIF_SUPPORT_HEX, &dwData) ) { if (context) krb5_set_error_message(context, 0, "Unexpected error when parsing %s as number gle 0x%x", data, GetLastError()); } rcode = RegSetValueEx(key, valuename, 0, type, (BYTE *)&dwData, sizeof(DWORD)); if (rcode) { if (context) krb5_set_error_message(context, 0, "Unexpected error when setting registry value %s gle 0x%x", valuename, GetLastError()); return -1; } break; default: return -1; } return 0; } /** * Parse a registry value as a string * * @see _krb5_parse_reg_value_as_multi_string() */ KRB5_LIB_FUNCTION char * KRB5_LIB_CALL _krb5_parse_reg_value_as_string(krb5_context context, HKEY key, const char * valuename, DWORD type, DWORD cb_data) { return _krb5_parse_reg_value_as_multi_string(context, key, valuename, type, cb_data, " "); } /** * Parse a registry value as a multi string * * The following registry value types are handled: * * - REG_DWORD: The decimal string representation is used as the * value. * * - REG_SZ: The string is used as-is. * * - REG_EXPAND_SZ: Environment variables in the string are expanded * and the result is used as the value. * * - REG_MULTI_SZ: The list of strings is concatenated using the * separator. No quoting is performed. * * Any other value type is rejected. * * @param [in]valuename Name of the registry value to be queried * @param [in]type Type of the value. REG_NONE if unknown * @param [in]cbdata Size of value. 0 if unknown. * @param [in]separator Separator character for concatenating strings. * * @a type and @a cbdata are only considered valid if both are * specified. * * @retval The registry value string, or NULL if there was an error. * If NULL is returned, an error message has been set using * krb5_set_error_message(). */ KRB5_LIB_FUNCTION char * KRB5_LIB_CALL _krb5_parse_reg_value_as_multi_string(krb5_context context, HKEY key, const char * valuename, DWORD type, DWORD cb_data, char *separator) { LONG rcode = ERROR_MORE_DATA; BYTE static_buffer[16384]; BYTE *pbuffer = &static_buffer[0]; DWORD cb_alloc = sizeof(static_buffer); char *ret_string = NULL; /* If we know a type and cb_data from a previous call to * RegEnumValue(), we use it. Otherwise we use the * static_buffer[] and query directly. We do this to minimize the * number of queries. */ if (type == REG_NONE || cb_data == 0) { pbuffer = &static_buffer[0]; cb_alloc = cb_data = sizeof(static_buffer); rcode = RegQueryValueExA(key, valuename, NULL, &type, pbuffer, &cb_data); if (rcode == ERROR_SUCCESS && ((type != REG_SZ && type != REG_EXPAND_SZ) || cb_data + 1 <= sizeof(static_buffer)) && (type != REG_MULTI_SZ || cb_data + 2 <= sizeof(static_buffer))) goto have_data; if (rcode != ERROR_MORE_DATA && rcode != ERROR_SUCCESS) return NULL; } /* Either we don't have the data or we aren't sure of the size * (due to potentially missing terminating NULs). */ switch (type) { case REG_DWORD: if (cb_data != sizeof(DWORD)) { if (context) krb5_set_error_message(context, 0, "Unexpected size while reading registry value %s", valuename); return NULL; } break; case REG_SZ: case REG_EXPAND_SZ: if (rcode == ERROR_SUCCESS && cb_data > 0 && pbuffer[cb_data - 1] == '\0') goto have_data; cb_data += sizeof(char); /* Accout for potential missing NUL * terminator. */ break; case REG_MULTI_SZ: if (rcode == ERROR_SUCCESS && cb_data > 0 && pbuffer[cb_data - 1] == '\0' && (cb_data == 1 || pbuffer[cb_data - 2] == '\0')) goto have_data; cb_data += sizeof(char) * 2; /* Potential missing double NUL * terminator. */ break; default: if (context) krb5_set_error_message(context, 0, "Unexpected type while reading registry value %s", valuename); return NULL; } if (cb_data <= sizeof(static_buffer)) pbuffer = &static_buffer[0]; else { pbuffer = malloc(cb_data); if (pbuffer == NULL) return NULL; } cb_alloc = cb_data; rcode = RegQueryValueExA(key, valuename, NULL, NULL, pbuffer, &cb_data); if (rcode != ERROR_SUCCESS) { /* This can potentially be from a race condition. I.e. some * other process or thread went and modified the registry * value between the time we queried its size and queried for * its value. Ideally we would retry the query in a loop. */ if (context) krb5_set_error_message(context, 0, "Unexpected error while reading registry value %s", valuename); goto done; } if (cb_data > cb_alloc || cb_data == 0) { if (context) krb5_set_error_message(context, 0, "Unexpected size while reading registry value %s", valuename); goto done; } have_data: switch (type) { case REG_DWORD: asprintf(&ret_string, "%d", *((DWORD *) pbuffer)); break; case REG_SZ: { char * str = (char *) pbuffer; if (str[cb_data - 1] != '\0') { if (cb_data < cb_alloc) str[cb_data] = '\0'; else break; } if (pbuffer != static_buffer) { ret_string = (char *) pbuffer; pbuffer = NULL; } else { ret_string = strdup((char *) pbuffer); } } break; case REG_EXPAND_SZ: { char *str = (char *) pbuffer; char expsz[32768]; /* Size of output buffer for * ExpandEnvironmentStrings() is * limited to 32K. */ if (str[cb_data - 1] != '\0') { if (cb_data < cb_alloc) str[cb_data] = '\0'; else break; } if (ExpandEnvironmentStrings(str, expsz, sizeof(expsz)/sizeof(char)) != 0) { ret_string = strdup(expsz); } else { if (context) krb5_set_error_message(context, 0, "Overflow while expanding environment strings " "for registry value %s", valuename); } } break; case REG_MULTI_SZ: { char * str = (char *) pbuffer; char * iter; str[cb_alloc - 1] = '\0'; str[cb_alloc - 2] = '\0'; for (iter = str; *iter;) { size_t len = strlen(iter); iter += len; if (iter[1] != '\0') *iter++ = *separator; else break; } if (pbuffer != static_buffer) { ret_string = str; pbuffer = NULL; } else { ret_string = strdup(str); } } break; default: if (context) krb5_set_error_message(context, 0, "Unexpected type while reading registry value %s", valuename); } done: if (pbuffer != static_buffer && pbuffer != NULL) free(pbuffer); return ret_string; } /** * Parse a registry value as a configuration value * * @see parse_reg_value_as_string() */ static krb5_error_code parse_reg_value(krb5_context context, HKEY key, const char * valuename, DWORD type, DWORD cbdata, krb5_config_section ** parent) { char *reg_string = NULL; krb5_config_section *value; krb5_error_code code = 0; reg_string = _krb5_parse_reg_value_as_string(context, key, valuename, type, cbdata); if (reg_string == NULL) return KRB5_CONFIG_BADFORMAT; value = _krb5_config_get_entry(parent, valuename, krb5_config_string); if (value == NULL) { code = ENOMEM; goto done; } if (value->u.string != NULL) free(value->u.string); value->u.string = reg_string; reg_string = NULL; done: if (reg_string != NULL) free(reg_string); return code; } static krb5_error_code parse_reg_values(krb5_context context, HKEY key, krb5_config_section ** parent) { DWORD index; LONG rcode; for (index = 0; ; index ++) { char name[16385]; DWORD cch = sizeof(name)/sizeof(name[0]); DWORD type; DWORD cbdata = 0; krb5_error_code code; rcode = RegEnumValue(key, index, name, &cch, NULL, &type, NULL, &cbdata); if (rcode != ERROR_SUCCESS) break; if (cbdata == 0) continue; code = parse_reg_value(context, key, name, type, cbdata, parent); if (code != 0) return code; } return 0; } static krb5_error_code parse_reg_subkeys(krb5_context context, HKEY key, krb5_config_section ** parent) { DWORD index; LONG rcode; for (index = 0; ; index ++) { HKEY subkey = NULL; char name[256]; DWORD cch = sizeof(name)/sizeof(name[0]); krb5_config_section *section = NULL; krb5_error_code code; rcode = RegEnumKeyEx(key, index, name, &cch, NULL, NULL, NULL, NULL); if (rcode != ERROR_SUCCESS) break; rcode = RegOpenKeyEx(key, name, 0, KEY_READ, &subkey); if (rcode != ERROR_SUCCESS) continue; section = _krb5_config_get_entry(parent, name, krb5_config_list); if (section == NULL) { RegCloseKey(subkey); return ENOMEM; } code = parse_reg_values(context, subkey, §ion->u.list); if (code) { RegCloseKey(subkey); return code; } code = parse_reg_subkeys(context, subkey, §ion->u.list); if (code) { RegCloseKey(subkey); return code; } RegCloseKey(subkey); } return 0; } static krb5_error_code parse_reg_root(krb5_context context, HKEY key, krb5_config_section ** parent) { krb5_config_section *libdefaults = NULL; krb5_error_code code = 0; libdefaults = _krb5_config_get_entry(parent, "libdefaults", krb5_config_list); if (libdefaults == NULL) return krb5_enomem(context); code = parse_reg_values(context, key, &libdefaults->u.list); if (code) return code; return parse_reg_subkeys(context, key, parent); } static krb5_error_code load_config_from_regpath(krb5_context context, HKEY hk_root, const char* key_path, krb5_config_section ** res) { HKEY key = NULL; LONG rcode; krb5_error_code code = 0; rcode = RegOpenKeyEx(hk_root, key_path, 0, KEY_READ, &key); if (rcode == ERROR_SUCCESS) { code = parse_reg_root(context, key, res); RegCloseKey(key); key = NULL; } return code; } /** * Load configuration from registry * * The registry keys 'HKCU\Software\Heimdal' and * 'HKLM\Software\Heimdal' are treated as krb5.conf files. Each * registry key corresponds to a configuration section (or bound list) * and each value in a registry key is treated as a bound value. The * set of values that are directly under the Heimdal key are treated * as if they were defined in the [libdefaults] section. * * @see parse_reg_value() for details about how each type of value is handled. */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL _krb5_load_config_from_registry(krb5_context context, krb5_config_section ** res) { krb5_error_code code; code = load_config_from_regpath(context, HKEY_LOCAL_MACHINE, REGPATH_KERBEROS, res); if (code) return code; code = load_config_from_regpath(context, HKEY_LOCAL_MACHINE, REGPATH_HEIMDAL, res); if (code) return code; code = load_config_from_regpath(context, HKEY_CURRENT_USER, REGPATH_KERBEROS, res); if (code) return code; code = load_config_from_regpath(context, HKEY_CURRENT_USER, REGPATH_HEIMDAL, res); if (code) return code; return 0; } heimdal-7.5.0/lib/krb5/get_port.c0000644000175000017500000000405412136107750014657 0ustar niknik/* * Copyright (c) 1997-2001 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "krb5_locl.h" KRB5_LIB_FUNCTION int KRB5_LIB_CALL krb5_getportbyname (krb5_context context, const char *service, const char *proto, int default_port) { struct servent *sp; if ((sp = roken_getservbyname (service, proto)) == NULL) { #if 0 krb5_warnx(context, "%s/%s unknown service, using default port %d", service, proto, default_port); #endif return htons(default_port); } else return sp->s_port; } heimdal-7.5.0/lib/krb5/crypto-stubs.c0000644000175000017500000000614213026237312015507 0ustar niknik/* * Copyright (c) 1997 - 2008 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include /* These are stub functions for the standalone RFC3961 crypto library */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_init_context(krb5_context *context) { krb5_context p; *context = NULL; /* should have a run_once */ bindtextdomain(HEIMDAL_TEXTDOMAIN, HEIMDAL_LOCALEDIR); p = calloc(1, sizeof(*p)); if(!p) return ENOMEM; HEIMDAL_MUTEX_init(&p->mutex); *context = p; return 0; } KRB5_LIB_FUNCTION void KRB5_LIB_CALL krb5_free_context(krb5_context context) { krb5_clear_error_message(context); HEIMDAL_MUTEX_destroy(&context->mutex); if (context->flags & KRB5_CTX_F_SOCKETS_INITIALIZED) { rk_SOCK_EXIT(); } memset(context, 0, sizeof(*context)); free(context); } KRB5_LIB_FUNCTION krb5_boolean KRB5_LIB_CALL _krb5_homedir_access(krb5_context context) { return 0; } KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_log(krb5_context context, krb5_log_facility *fac, int level, const char *fmt, ...) { return 0; } void KRB5_LIB_FUNCTION _krb5_debug(krb5_context context, int level, const char *fmt, ...) { } /* This function is currently just used to get the location of the EGD * socket. If we're not using an EGD, then we can just return NULL */ KRB5_LIB_FUNCTION const char* KRB5_LIB_CALL krb5_config_get_string (krb5_context context, const krb5_config_section *c, ...) { return NULL; } heimdal-7.5.0/lib/krb5/test_alname.c0000644000175000017500000001431213026237312015323 0ustar niknik/* * Copyright (c) 2003 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of KTH nor the names of its contributors may be * used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY KTH AND ITS CONTRIBUTORS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL KTH OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "krb5_locl.h" #include #include char localname[1024]; static size_t lname_size = sizeof (localname); static int lname_size_arg = 0; static int simple_flag = 0; static int verbose_flag = 0; static int version_flag = 0; static int help_flag = 0; static struct getargs args[] = { {"lname-size", 0, arg_integer, &lname_size_arg, "set localname size (0 means use default, must be 0..1023)", "integer" }, {"simple", 0, arg_flag, &simple_flag, /* Used for scripting */ "map the given principal and print the resulting localname", NULL }, {"verbose", 0, arg_flag, &verbose_flag, "print the actual principal name as well as the localname", NULL }, {"version", 0, arg_flag, &version_flag, "print version", NULL }, {"help", 0, arg_flag, &help_flag, NULL, NULL } }; static void test_alname(krb5_context context, krb5_const_realm realm, const char *user, const char *inst, const char *localuser, int ok) { krb5_principal p; krb5_error_code ret; char *princ; ret = krb5_make_principal(context, &p, realm, user, inst, NULL); if (ret) krb5_err(context, 1, ret, "krb5_build_principal"); ret = krb5_unparse_name(context, p, &princ); if (ret) krb5_err(context, 1, ret, "krb5_unparse_name"); ret = krb5_aname_to_localname(context, p, lname_size, localname); krb5_free_principal(context, p); if (ret) { if (!ok) { free(princ); return; } krb5_err(context, 1, ret, "krb5_aname_to_localname: %s -> %s", princ, localuser); free(princ); } if (strcmp(localname, localuser) != 0) { if (ok) errx(1, "compared failed %s != %s (should have succeded)", localname, localuser); } else { if (!ok) errx(1, "compared failed %s == %s (should have failed)", localname, localuser); } } static void usage (int ret) { arg_printusage (args, sizeof(args)/sizeof(*args), NULL, ""); exit (ret); } int main(int argc, char **argv) { krb5_context context; krb5_error_code ret; krb5_realm realm; int optidx = 0; char *user; setprogname(argv[0]); if(getarg(args, sizeof(args) / sizeof(args[0]), argc, argv, &optidx)) usage(1); if (help_flag) usage (0); if(version_flag){ print_version(NULL); exit(0); } argc -= optidx; argv += optidx; ret = krb5_init_context(&context); if (ret) errx (1, "krb5_init_context failed: %d", ret); if (simple_flag) { krb5_principal princ; char *unparsed; int status = 0; /* Map then print the result and exit */ if (argc != 1) errx(1, "One argument is required and it must be a principal name"); ret = krb5_parse_name(context, argv[0], &princ); if (ret) krb5_err(context, 1, ret, "krb5_build_principal"); ret = krb5_unparse_name(context, princ, &unparsed); if (ret) krb5_err(context, 1, ret, "krb5_unparse_name"); if (lname_size_arg > 0 && lname_size_arg < 1024) lname_size = lname_size_arg; else if (lname_size_arg != 0) errx(1, "local name size must be between 0 and 1023 (inclusive)"); ret = krb5_aname_to_localname(context, princ, lname_size, localname); if (ret == KRB5_NO_LOCALNAME) { if (verbose_flag) fprintf(stderr, "No mapping obtained for %s\n", unparsed); exit(1); } switch (ret) { case KRB5_PLUGIN_NO_HANDLE: fprintf(stderr, "Error: KRB5_PLUGIN_NO_HANDLE leaked!\n"); status = 2; break; case KRB5_CONFIG_NOTENUFSPACE: fprintf(stderr, "Error: lname-size (%lu) too small\n", (long unsigned)lname_size); status = 3; break; case 0: if (verbose_flag) printf("%s ", unparsed); printf("%s\n", localname); break; default: krb5_err(context, 4, ret, "krb5_aname_to_localname"); break; } free(unparsed); krb5_free_principal(context, princ); krb5_free_context(context); exit(status); } if (argc != 1) errx(1, "first argument should be a local user that is in root .k5login"); user = argv[0]; ret = krb5_get_default_realm(context, &realm); if (ret) krb5_err(context, 1, ret, "krb5_get_default_realm"); test_alname(context, realm, user, NULL, user, 1); test_alname(context, realm, user, "root", "root", 1); test_alname(context, "FOO.BAR.BAZ.KAKA", user, NULL, user, 0); test_alname(context, "FOO.BAR.BAZ.KAKA", user, "root", "root", 0); test_alname(context, realm, user, NULL, "not-same-as-user", 0); test_alname(context, realm, user, "root", "not-same-as-user", 0); test_alname(context, "FOO.BAR.BAZ.KAKA", user, NULL, "not-same-as-user", 0); test_alname(context, "FOO.BAR.BAZ.KAKA", user, "root", "not-same-as-user", 0); krb5_free_context(context); return 0; } heimdal-7.5.0/lib/krb5/dll.c0000644000175000017500000000445013026237312013604 0ustar niknik/*********************************************************************** * Copyright (c) 2009, Secure Endpoints Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * - Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. * **********************************************************************/ #include extern void heim_w32_service_thread_detach(void *); HINSTANCE _krb5_hInstance = NULL; #if NTDDI_VERSION >= NTDDI_VISTA extern BOOL WINAPI _hc_w32crypto_DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpvReserved); #endif BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpvReserved) { #if NTDDI_VERSION >= NTDDI_VISTA BOOL ret; ret = _hc_w32crypto_DllMain(hinstDLL, fdwReason, lpvReserved); if (!ret) return ret; #endif switch (fdwReason) { case DLL_PROCESS_ATTACH: _krb5_hInstance = hinstDLL; return TRUE; case DLL_PROCESS_DETACH: return FALSE; case DLL_THREAD_ATTACH: return FALSE; case DLL_THREAD_DETACH: heim_w32_service_thread_detach(NULL); return FALSE; } return FALSE; } heimdal-7.5.0/lib/krb5/krb5_find_padata.cat30000644000175000017500000000277013212450756016627 0ustar niknik KRB5_FIND_PADATA(3) BSD Library Functions Manual KRB5_FIND_PADATA(3) NNAAMMEE kkrrbb55__ffiinndd__ppaaddaattaa, kkrrbb55__ppaaddaattaa__aadddd -- Kerberos 5 pre-authentication data handling functions LLIIBBRRAARRYY Kerberos 5 Library (libkrb5, -lkrb5) SSYYNNOOPPSSIISS ##iinncclluuddee <> _P_A___D_A_T_A _* kkrrbb55__ffiinndd__ppaaddaattaa(_P_A___D_A_T_A _*_v_a_l, _u_n_s_i_g_n_e_d _l_e_n, _i_n_t _t_y_p_e, _i_n_t _*_i_n_d_e_x); _i_n_t kkrrbb55__ppaaddaattaa__aadddd(_k_r_b_5___c_o_n_t_e_x_t _c_o_n_t_e_x_t, _M_E_T_H_O_D___D_A_T_A _*_m_d, _i_n_t _t_y_p_e, _v_o_i_d _*_b_u_f, _s_i_z_e___t _l_e_n); DDEESSCCRRIIPPTTIIOONN kkrrbb55__ffiinndd__ppaaddaattaa() tries to find the pre-authentication data entry of type _t_y_p_e in the array _v_a_l of length _l_e_n. The search is started at entry pointed out by _*_i_n_d_e_x (zero based indexing). If the type isn't found, NULL is returned. kkrrbb55__ppaaddaattaa__aadddd() adds a pre-authentication data entry of type _t_y_p_e pointed out by _b_u_f and _l_e_n to _m_d. SSEEEE AALLSSOO krb5(3), kerberos(8) HEIMDAL March 21, 2004 HEIMDAL heimdal-7.5.0/lib/krb5/test_princ.c0000644000175000017500000002470112136107750015207 0ustar niknik/* * Copyright (c) 2003 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of KTH nor the names of its contributors may be * used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY KTH AND ITS CONTRIBUTORS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL KTH OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "krb5_locl.h" #include /* * Check that a closed cc still keeps it data and that it's no longer * there when it's destroyed. */ static void test_princ(krb5_context context) { const char *princ = "lha@SU.SE"; const char *princ_short = "lha"; const char *noquote; krb5_error_code ret; char *princ_unparsed; char *princ_reformed = NULL; const char *realm; krb5_principal p, p2; ret = krb5_parse_name(context, princ, &p); if (ret) krb5_err(context, 1, ret, "krb5_parse_name"); ret = krb5_unparse_name(context, p, &princ_unparsed); if (ret) krb5_err(context, 1, ret, "krb5_parse_name"); if (strcmp(princ, princ_unparsed)) { krb5_errx(context, 1, "%s != %s", princ, princ_unparsed); } free(princ_unparsed); ret = krb5_unparse_name_flags(context, p, KRB5_PRINCIPAL_UNPARSE_NO_REALM, &princ_unparsed); if (ret) krb5_err(context, 1, ret, "krb5_parse_name"); if (strcmp(princ_short, princ_unparsed)) krb5_errx(context, 1, "%s != %s", princ_short, princ_unparsed); free(princ_unparsed); realm = krb5_principal_get_realm(context, p); if (asprintf(&princ_reformed, "%s@%s", princ_short, realm) < 0 || princ_reformed == NULL) errx(1, "malloc"); ret = krb5_parse_name(context, princ_reformed, &p2); free(princ_reformed); if (ret) krb5_err(context, 1, ret, "krb5_parse_name"); if (!krb5_principal_compare(context, p, p2)) { krb5_errx(context, 1, "p != p2"); } krb5_free_principal(context, p2); ret = krb5_set_default_realm(context, "SU.SE"); if (ret) krb5_err(context, 1, ret, "krb5_parse_name"); ret = krb5_unparse_name_flags(context, p, KRB5_PRINCIPAL_UNPARSE_SHORT, &princ_unparsed); if (ret) krb5_err(context, 1, ret, "krb5_parse_name"); if (strcmp(princ_short, princ_unparsed)) krb5_errx(context, 1, "'%s' != '%s'", princ_short, princ_unparsed); free(princ_unparsed); ret = krb5_parse_name(context, princ_short, &p2); if (ret) krb5_err(context, 1, ret, "krb5_parse_name"); if (!krb5_principal_compare(context, p, p2)) krb5_errx(context, 1, "p != p2"); krb5_free_principal(context, p2); ret = krb5_unparse_name(context, p, &princ_unparsed); if (ret) krb5_err(context, 1, ret, "krb5_parse_name"); if (strcmp(princ, princ_unparsed)) krb5_errx(context, 1, "'%s' != '%s'", princ, princ_unparsed); free(princ_unparsed); ret = krb5_set_default_realm(context, "SAMBA.ORG"); if (ret) krb5_err(context, 1, ret, "krb5_parse_name"); ret = krb5_parse_name(context, princ_short, &p2); if (ret) krb5_err(context, 1, ret, "krb5_parse_name"); if (krb5_principal_compare(context, p, p2)) krb5_errx(context, 1, "p == p2"); if (!krb5_principal_compare_any_realm(context, p, p2)) krb5_errx(context, 1, "(ignoring realms) p != p2"); ret = krb5_unparse_name(context, p2, &princ_unparsed); if (ret) krb5_err(context, 1, ret, "krb5_parse_name"); if (strcmp(princ, princ_unparsed) == 0) krb5_errx(context, 1, "%s == %s", princ, princ_unparsed); free(princ_unparsed); krb5_free_principal(context, p2); ret = krb5_parse_name(context, princ, &p2); if (ret) krb5_err(context, 1, ret, "krb5_parse_name"); if (!krb5_principal_compare(context, p, p2)) krb5_errx(context, 1, "p != p2"); ret = krb5_unparse_name(context, p2, &princ_unparsed); if (ret) krb5_err(context, 1, ret, "krb5_parse_name"); if (strcmp(princ, princ_unparsed)) krb5_errx(context, 1, "'%s' != '%s'", princ, princ_unparsed); free(princ_unparsed); krb5_free_principal(context, p2); ret = krb5_unparse_name_flags(context, p, KRB5_PRINCIPAL_UNPARSE_SHORT, &princ_unparsed); if (ret) krb5_err(context, 1, ret, "krb5_unparse_name_short"); if (strcmp(princ, princ_unparsed) != 0) krb5_errx(context, 1, "'%s' != '%s'", princ, princ_unparsed); free(princ_unparsed); ret = krb5_unparse_name(context, p, &princ_unparsed); if (ret) krb5_err(context, 1, ret, "krb5_unparse_name_short"); if (strcmp(princ, princ_unparsed)) krb5_errx(context, 1, "'%s' != '%s'", princ, princ_unparsed); free(princ_unparsed); ret = krb5_parse_name_flags(context, princ, KRB5_PRINCIPAL_PARSE_NO_REALM, &p2); if (!ret) krb5_err(context, 1, ret, "Should have failed to parse %s a " "short name", princ); ret = krb5_parse_name_flags(context, princ_short, KRB5_PRINCIPAL_PARSE_NO_REALM, &p2); if (ret) krb5_err(context, 1, ret, "krb5_parse_name"); ret = krb5_unparse_name_flags(context, p2, KRB5_PRINCIPAL_UNPARSE_NO_REALM, &princ_unparsed); krb5_free_principal(context, p2); if (ret) krb5_err(context, 1, ret, "krb5_unparse_name_norealm"); if (strcmp(princ_short, princ_unparsed)) krb5_errx(context, 1, "'%s' != '%s'", princ_short, princ_unparsed); free(princ_unparsed); ret = krb5_parse_name_flags(context, princ_short, KRB5_PRINCIPAL_PARSE_REQUIRE_REALM, &p2); if (!ret) krb5_err(context, 1, ret, "Should have failed to parse %s " "because it lacked a realm", princ_short); ret = krb5_parse_name_flags(context, princ, KRB5_PRINCIPAL_PARSE_REQUIRE_REALM, &p2); if (ret) krb5_err(context, 1, ret, "krb5_parse_name"); if (!krb5_principal_compare(context, p, p2)) krb5_errx(context, 1, "p != p2"); ret = krb5_unparse_name_flags(context, p2, KRB5_PRINCIPAL_UNPARSE_NO_REALM, &princ_unparsed); krb5_free_principal(context, p2); if (ret) krb5_err(context, 1, ret, "krb5_unparse_name_norealm"); if (strcmp(princ_short, princ_unparsed)) krb5_errx(context, 1, "'%s' != '%s'", princ_short, princ_unparsed); free(princ_unparsed); krb5_free_principal(context, p); /* test quoting */ princ = "test\\ principal@SU.SE"; noquote = "test principal@SU.SE"; ret = krb5_parse_name_flags(context, princ, 0, &p); if (ret) krb5_err(context, 1, ret, "krb5_parse_name"); ret = krb5_unparse_name_flags(context, p, 0, &princ_unparsed); if (ret) krb5_err(context, 1, ret, "krb5_unparse_name_flags"); if (strcmp(princ, princ_unparsed)) krb5_errx(context, 1, "q '%s' != '%s'", princ, princ_unparsed); free(princ_unparsed); ret = krb5_unparse_name_flags(context, p, KRB5_PRINCIPAL_UNPARSE_DISPLAY, &princ_unparsed); if (ret) krb5_err(context, 1, ret, "krb5_unparse_name_flags"); if (strcmp(noquote, princ_unparsed)) krb5_errx(context, 1, "nq '%s' != '%s'", noquote, princ_unparsed); free(princ_unparsed); krb5_free_principal(context, p); } static void test_enterprise(krb5_context context) { krb5_error_code ret; char *unparsed; krb5_principal p; ret = krb5_set_default_realm(context, "SAMBA.ORG"); if (ret) krb5_err(context, 1, ret, "krb5_parse_name"); ret = krb5_parse_name_flags(context, "lha@su.se@WIN.SU.SE", KRB5_PRINCIPAL_PARSE_ENTERPRISE, &p); if (ret) krb5_err(context, 1, ret, "krb5_parse_name_flags"); ret = krb5_unparse_name(context, p, &unparsed); if (ret) krb5_err(context, 1, ret, "krb5_unparse_name"); krb5_free_principal(context, p); if (strcmp(unparsed, "lha\\@su.se@WIN.SU.SE") != 0) krb5_errx(context, 1, "enterprise name failed 1"); free(unparsed); /* * */ ret = krb5_parse_name_flags(context, "lha\\@su.se@WIN.SU.SE", KRB5_PRINCIPAL_PARSE_ENTERPRISE, &p); if (ret) krb5_err(context, 1, ret, "krb5_parse_name_flags"); ret = krb5_unparse_name(context, p, &unparsed); if (ret) krb5_err(context, 1, ret, "krb5_unparse_name"); krb5_free_principal(context, p); if (strcmp(unparsed, "lha\\@su.se\\@WIN.SU.SE@SAMBA.ORG") != 0) krb5_errx(context, 1, "enterprise name failed 2: %s", unparsed); free(unparsed); /* * */ ret = krb5_parse_name_flags(context, "lha\\@su.se@WIN.SU.SE", 0, &p); if (ret) krb5_err(context, 1, ret, "krb5_parse_name_flags"); ret = krb5_unparse_name(context, p, &unparsed); if (ret) krb5_err(context, 1, ret, "krb5_unparse_name"); krb5_free_principal(context, p); if (strcmp(unparsed, "lha\\@su.se@WIN.SU.SE") != 0) krb5_errx(context, 1, "enterprise name failed 3"); free(unparsed); /* * */ ret = krb5_parse_name_flags(context, "lha@su.se", KRB5_PRINCIPAL_PARSE_ENTERPRISE, &p); if (ret) krb5_err(context, 1, ret, "krb5_parse_name_flags"); ret = krb5_unparse_name(context, p, &unparsed); if (ret) krb5_err(context, 1, ret, "krb5_unparse_name"); krb5_free_principal(context, p); if (strcmp(unparsed, "lha\\@su.se@SAMBA.ORG") != 0) krb5_errx(context, 1, "enterprise name failed 2: %s", unparsed); free(unparsed); } int main(int argc, char **argv) { krb5_context context; krb5_error_code ret; setprogname(argv[0]); ret = krb5_init_context(&context); if (ret) errx (1, "krb5_init_context failed: %d", ret); test_princ(context); test_enterprise(context); krb5_free_context(context); return 0; } heimdal-7.5.0/lib/krb5/write_message.c0000644000175000017500000000557612136107750015704 0ustar niknik/* * Copyright (c) 1997 - 2001 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "krb5_locl.h" KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_write_message (krb5_context context, krb5_pointer p_fd, krb5_data *data) { uint32_t len; uint8_t buf[4]; int ret; len = data->length; _krb5_put_int(buf, len, 4); if (krb5_net_write (context, p_fd, buf, 4) != 4 || krb5_net_write (context, p_fd, data->data, len) != len) { ret = errno; krb5_set_error_message (context, ret, "write: %s", strerror(ret)); return ret; } return 0; } KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_write_priv_message(krb5_context context, krb5_auth_context ac, krb5_pointer p_fd, krb5_data *data) { krb5_error_code ret; krb5_data packet; ret = krb5_mk_priv (context, ac, data, &packet, NULL); if(ret) return ret; ret = krb5_write_message(context, p_fd, &packet); krb5_data_free(&packet); return ret; } KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_write_safe_message(krb5_context context, krb5_auth_context ac, krb5_pointer p_fd, krb5_data *data) { krb5_error_code ret; krb5_data packet; ret = krb5_mk_safe (context, ac, data, &packet, NULL); if(ret) return ret; ret = krb5_write_message(context, p_fd, &packet); krb5_data_free(&packet); return ret; } heimdal-7.5.0/lib/krb5/krb5_generate_random_block.30000644000175000017500000000415212136107750020202 0ustar niknik.\" Copyright (c) 2004 Kungliga Tekniska Högskolan .\" (Royal Institute of Technology, Stockholm, Sweden). .\" All rights reserved. .\" .\" Redistribution and use in source and binary forms, with or without .\" modification, are permitted provided that the following conditions .\" are met: .\" .\" 1. Redistributions of source code must retain the above copyright .\" notice, this list of conditions and the following disclaimer. .\" .\" 2. Redistributions in binary form must reproduce the above copyright .\" notice, this list of conditions and the following disclaimer in the .\" documentation and/or other materials provided with the distribution. .\" .\" 3. Neither the name of the Institute nor the names of its contributors .\" may be used to endorse or promote products derived from this software .\" without specific prior written permission. .\" .\" THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND .\" ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE .\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE .\" ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE .\" FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL .\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS .\" OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) .\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT .\" LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF .\" SUCH DAMAGE. .\" .\" $Id$ .\" .Dd March 21, 2004 .Dt KRB5_GENERATE_RANDOM_BLOCK 3 .Os HEIMDAL .Sh NAME .Nm krb5_generate_random_block .Nd Kerberos 5 random functions .Sh LIBRARY Kerberos 5 Library (libkrb5, -lkrb5) .Sh SYNOPSIS .In krb5.h .Ft void .Fo krb5_generate_random_block .Fa "void *buf" .Fa "size_t len" .Fc .Sh DESCRIPTION .Fn krb5_generate_random_block generates a cryptographically strong pseudo-random block into the buffer .Fa buf of length .Fa len . .Sh SEE ALSO .Xr krb5 3 , .Xr krb5.conf 5 heimdal-7.5.0/lib/krb5/string-to-key-test.c0000644000175000017500000001342113026237312016520 0ustar niknik/* * Copyright (c) 1999 - 2001 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of KTH nor the names of its contributors may be * used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY KTH AND ITS CONTRIBUTORS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL KTH OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "krb5_locl.h" #include enum { MAXSIZE = 24 }; static struct testcase { const char *principal_name; const char *password; krb5_enctype enctype; unsigned char res[MAXSIZE]; } tests[] = { #ifdef HEIM_WEAK_CRYPTO {"@", "", ETYPE_DES_CBC_MD5, {0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0xf1}}, {"nisse@FOO.SE", "hej", ETYPE_DES_CBC_MD5, {0xfe, 0x67, 0xbf, 0x9e, 0x57, 0x6b, 0xfe, 0x52}}, {"assar/liten@FOO.SE", "hemligt", ETYPE_DES_CBC_MD5, {0x5b, 0x9b, 0xcb, 0xf2, 0x97, 0x43, 0xc8, 0x40}}, {"raeburn@ATHENA.MIT.EDU", "password", ETYPE_DES_CBC_MD5, {0xcb, 0xc2, 0x2f, 0xae, 0x23, 0x52, 0x98, 0xe3}}, {"danny@WHITEHOUSE.GOV", "potatoe", ETYPE_DES_CBC_MD5, {0xdf, 0x3d, 0x32, 0xa7, 0x4f, 0xd9, 0x2a, 0x01}}, {"buckaroo@EXAMPLE.COM", "penny", ETYPE_DES_CBC_MD5, {0x94, 0x43, 0xa2, 0xe5, 0x32, 0xfd, 0xc4, 0xf1}}, {"Juri\xc5\xa1i\xc4\x87@ATHENA.MIT.EDU", "\xc3\x9f", ETYPE_DES_CBC_MD5, {0x62, 0xc8, 0x1a, 0x52, 0x32, 0xb5, 0xe6, 0x9d}}, {"AAAAAAAA", "11119999", ETYPE_DES_CBC_MD5, {0x98, 0x40, 0x54, 0xd0, 0xf1, 0xa7, 0x3e, 0x31}}, {"FFFFAAAA", "NNNN6666", ETYPE_DES_CBC_MD5, {0xc4, 0xbf, 0x6b, 0x25, 0xad, 0xf7, 0xa4, 0xf8}}, #endif #if 0 {"@", "", ETYPE_DES3_CBC_SHA1, {0xce, 0xa2, 0x2f, 0x9b, 0x52, 0x2c, 0xb0, 0x15, 0x6e, 0x6b, 0x64, 0x73, 0x62, 0x64, 0x73, 0x4f, 0x6e, 0x73, 0xce, 0xa2, 0x2f, 0x9b, 0x52, 0x57}}, #endif {"nisse@FOO.SE", "hej", ETYPE_DES3_CBC_SHA1, {0x0e, 0xbc, 0x23, 0x9d, 0x68, 0x46, 0xf2, 0xd5, 0x51, 0x98, 0x5b, 0x57, 0xc1, 0x57, 0x01, 0x79, 0x04, 0xc4, 0xe9, 0xfe, 0xc1, 0x0e, 0x13, 0xd0}}, {"assar/liten@FOO.SE", "hemligt", ETYPE_DES3_CBC_SHA1, {0x7f, 0x40, 0x67, 0xb9, 0xbc, 0xc4, 0x40, 0xfb, 0x43, 0x73, 0xd9, 0xd3, 0xcd, 0x7c, 0xc7, 0x67, 0xe6, 0x79, 0x94, 0xd0, 0xa8, 0x34, 0xdf, 0x62}}, {"does/not@MATTER", "foo", ETYPE_ARCFOUR_HMAC_MD5, {0xac, 0x8e, 0x65, 0x7f, 0x83, 0xdf, 0x82, 0xbe, 0xea, 0x5d, 0x43, 0xbd, 0xaf, 0x78, 0x00, 0xcc}}, {"raeburn@ATHENA.MIT.EDU", "password", ETYPE_DES3_CBC_SHA1, {0x85, 0x0b, 0xb5, 0x13, 0x58, 0x54, 0x8c, 0xd0, 0x5e, 0x86, 0x76, 0x8c, 0x31, 0x3e, 0x3b, 0xfe, 0xf7, 0x51, 0x19, 0x37, 0xdc, 0xf7, 0x2c, 0x3e}}, {"danny@WHITEHOUSE.GOV", "potatoe", ETYPE_DES3_CBC_SHA1, {0xdf, 0xcd, 0x23, 0x3d, 0xd0, 0xa4, 0x32, 0x04, 0xea, 0x6d, 0xc4, 0x37, 0xfb, 0x15, 0xe0, 0x61, 0xb0, 0x29, 0x79, 0xc1, 0xf7, 0x4f, 0x37, 0x7a}}, {"buckaroo@EXAMPLE.COM", "penny", ETYPE_DES3_CBC_SHA1, {0x6d, 0x2f, 0xcd, 0xf2, 0xd6, 0xfb, 0xbc, 0x3d, 0xdc, 0xad, 0xb5, 0xda, 0x57, 0x10, 0xa2, 0x34, 0x89, 0xb0, 0xd3, 0xb6, 0x9d, 0x5d, 0x9d, 0x4a}}, {"Juri\xc5\xa1i\xc4\x87@ATHENA.MIT.EDU", "\xc3\x9f", ETYPE_DES3_CBC_SHA1, {0x16, 0xd5, 0xa4, 0x0e, 0x1c, 0xe3, 0xba, 0xcb, 0x61, 0xb9, 0xdc, 0xe0, 0x04, 0x70, 0x32, 0x4c, 0x83, 0x19, 0x73, 0xa7, 0xb9, 0x52, 0xfe, 0xb0}}, {NULL, NULL, 0, {0}} }; int main(int argc, char **argv) { struct testcase *t; krb5_context context; krb5_error_code ret; int val = 0; ret = krb5_init_context (&context); if (ret) errx (1, "krb5_init_context failed: %d", ret); /* to enable realm-less principal name above */ krb5_set_default_realm(context, ""); for (t = tests; t->principal_name; ++t) { krb5_keyblock key; krb5_principal principal; int i; ret = krb5_parse_name (context, t->principal_name, &principal); if (ret) krb5_err (context, 1, ret, "krb5_parse_name %s", t->principal_name); ret = krb5_string_to_key (context, t->enctype, t->password, principal, &key); if (ret) krb5_err (context, 1, ret, "krb5_string_to_key"); krb5_free_principal (context, principal); if (memcmp (key.keyvalue.data, t->res, key.keyvalue.length) != 0) { const unsigned char *p = key.keyvalue.data; printf ("string_to_key(%s, %s) failed\n", t->principal_name, t->password); printf ("should be: "); for (i = 0; i < key.keyvalue.length; ++i) printf ("%02x", t->res[i]); printf ("\nresult was: "); for (i = 0; i < key.keyvalue.length; ++i) printf ("%02x", p[i]); printf ("\n"); val = 1; } krb5_free_keyblock_contents(context, &key); } krb5_free_context(context); return val; } heimdal-7.5.0/lib/krb5/test_forward.c0000644000175000017500000000721712136107750015543 0ustar niknik/* * Copyright (c) 2008 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of KTH nor the names of its contributors may be * used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY KTH AND ITS CONTRIBUTORS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL KTH OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "krb5_locl.h" #include #include static int version_flag = 0; static int help_flag = 0; static struct getargs args[] = { {"version", 0, arg_flag, &version_flag, "print version", NULL }, {"help", 0, arg_flag, &help_flag, NULL, NULL } }; static void usage (int ret) { arg_printusage (args, sizeof(args)/sizeof(*args), NULL, "hostname"); exit (ret); } int main(int argc, char **argv) { const char *hostname; krb5_context context; krb5_auth_context ac; krb5_error_code ret; krb5_creds cred; krb5_ccache id; krb5_data data; int optidx = 0; setprogname (argv[0]); if(getarg(args, sizeof(args) / sizeof(args[0]), argc, argv, &optidx)) usage(1); if (help_flag) usage (0); if(version_flag){ print_version(NULL); exit(0); } argc -= optidx; argv += optidx; if (argc < 1) usage(1); hostname = argv[0]; memset(&cred, 0, sizeof(cred)); ret = krb5_init_context(&context); if (ret) errx (1, "krb5_init_context failed: %d", ret); ret = krb5_cc_default(context, &id); if (ret) krb5_err(context, 1, ret, "krb5_cc_default failed"); ret = krb5_auth_con_init(context, &ac); if (ret) krb5_err(context, 1, ret, "krb5_auth_con_init failed"); krb5_auth_con_addflags(context, ac, KRB5_AUTH_CONTEXT_CLEAR_FORWARDED_CRED, NULL); ret = krb5_cc_get_principal(context, id, &cred.client); if (ret) krb5_err(context, 1, ret, "krb5_cc_get_principal"); ret = krb5_make_principal(context, &cred.server, krb5_principal_get_realm(context, cred.client), KRB5_TGS_NAME, krb5_principal_get_realm(context, cred.client), NULL); if (ret) krb5_err(context, 1, ret, "krb5_make_principal(server)"); ret = krb5_get_forwarded_creds (context, ac, id, KDC_OPT_FORWARDABLE, hostname, &cred, &data); if (ret) krb5_err (context, 1, ret, "krb5_get_forwarded_creds"); krb5_data_free(&data); krb5_free_context(context); return 0; } heimdal-7.5.0/lib/krb5/salt-arcfour.c0000644000175000017500000000612513026237312015434 0ustar niknik/* * Copyright (c) 1997 - 2008 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "krb5_locl.h" static krb5_error_code ARCFOUR_string_to_key(krb5_context context, krb5_enctype enctype, krb5_data password, krb5_salt salt, krb5_data opaque, krb5_keyblock *key) { krb5_error_code ret; uint16_t *s = NULL; size_t len = 0, i; EVP_MD_CTX *m; m = EVP_MD_CTX_create(); if (m == NULL) { ret = krb5_enomem(context); goto out; } EVP_DigestInit_ex(m, EVP_md4(), NULL); ret = wind_utf8ucs2_length(password.data, &len); if (ret) { krb5_set_error_message (context, ret, N_("Password is not valid UTF-8", "")); goto out; } s = malloc (len * sizeof(s[0])); if (len != 0 && s == NULL) { ret = krb5_enomem(context); goto out; } ret = wind_utf8ucs2(password.data, s, &len); if (ret) { krb5_set_error_message (context, ret, N_("Password is not valid UTF-8", "")); goto out; } /* LE encoding */ for (i = 0; i < len; i++) { unsigned char p; p = (s[i] & 0xff); EVP_DigestUpdate (m, &p, 1); p = (s[i] >> 8) & 0xff; EVP_DigestUpdate (m, &p, 1); } key->keytype = enctype; ret = krb5_data_alloc (&key->keyvalue, 16); if (ret) { krb5_enomem(context); goto out; } EVP_DigestFinal_ex (m, key->keyvalue.data, NULL); out: EVP_MD_CTX_destroy(m); if (s) memset (s, 0, len); free (s); return ret; } struct salt_type _krb5_arcfour_salt[] = { { KRB5_PW_SALT, "pw-salt", ARCFOUR_string_to_key }, { 0, NULL, NULL } }; heimdal-7.5.0/lib/krb5/krb5_get_init_creds.30000644000175000017500000002625413026237312016664 0ustar niknik.\" Copyright (c) 2003 - 2007 Kungliga Tekniska Högskolan .\" (Royal Institute of Technology, Stockholm, Sweden). .\" All rights reserved. .\" .\" Redistribution and use in source and binary forms, with or without .\" modification, are permitted provided that the following conditions .\" are met: .\" .\" 1. Redistributions of source code must retain the above copyright .\" notice, this list of conditions and the following disclaimer. .\" .\" 2. Redistributions in binary form must reproduce the above copyright .\" notice, this list of conditions and the following disclaimer in the .\" documentation and/or other materials provided with the distribution. .\" .\" 3. Neither the name of the Institute nor the names of its contributors .\" may be used to endorse or promote products derived from this software .\" without specific prior written permission. .\" .\" THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND .\" ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE .\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE .\" ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE .\" FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL .\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS .\" OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) .\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT .\" LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF .\" SUCH DAMAGE. .\" .\" $Id$ .\" .Dd Sep 16, 2006 .Dt KRB5_GET_INIT_CREDS 3 .Os HEIMDAL .Sh NAME .Nm krb5_get_init_creds , .Nm krb5_get_init_creds_keytab , .Nm krb5_get_init_creds_opt , .Nm krb5_get_init_creds_opt_alloc , .Nm krb5_get_init_creds_opt_free , .Nm krb5_get_init_creds_opt_init , .Nm krb5_get_init_creds_opt_set_address_list , .Nm krb5_get_init_creds_opt_set_addressless , .Nm krb5_get_init_creds_opt_set_anonymous , .Nm krb5_get_init_creds_opt_set_default_flags , .Nm krb5_get_init_creds_opt_set_etype_list , .Nm krb5_get_init_creds_opt_set_forwardable , .Nm krb5_get_init_creds_opt_set_pa_password , .Nm krb5_get_init_creds_opt_set_paq_request , .Nm krb5_get_init_creds_opt_set_preauth_list , .Nm krb5_get_init_creds_opt_set_proxiable , .Nm krb5_get_init_creds_opt_set_renew_life , .Nm krb5_get_init_creds_opt_set_salt , .Nm krb5_get_init_creds_opt_set_tkt_life , .Nm krb5_get_init_creds_opt_set_canonicalize , .Nm krb5_get_init_creds_opt_set_win2k , .Nm krb5_get_init_creds_password , .Nm krb5_prompt , .Nm krb5_prompter_posix .Nd Kerberos 5 initial authentication functions .Sh LIBRARY Kerberos 5 Library (libkrb5, -lkrb5) .Sh SYNOPSIS .In krb5.h .Pp .Ft krb5_get_init_creds_opt; .Pp .Ft krb5_error_code .Fo krb5_get_init_creds_opt_alloc .Fa "krb5_context context" .Fa "krb5_get_init_creds_opt **opt" .Fc .Ft void .Fo krb5_get_init_creds_opt_free .Fa "krb5_context context" .Fa "krb5_get_init_creds_opt *opt" .Fc .Ft void .Fo krb5_get_init_creds_opt_init .Fa "krb5_get_init_creds_opt *opt" .Fc .Ft void .Fo krb5_get_init_creds_opt_set_address_list .Fa "krb5_get_init_creds_opt *opt" .Fa "krb5_addresses *addresses" .Fc .Ft void .Fo krb5_get_init_creds_opt_set_addressless .Fa "krb5_get_init_creds_opt *opt" .Fa "krb5_boolean addressless" .Fc .Ft void .Fo krb5_get_init_creds_opt_set_anonymous .Fa "krb5_get_init_creds_opt *opt" .Fa "int anonymous" .Fc .Ft void .Fo krb5_get_init_creds_opt_set_change_password_prompt .Fa "krb5_get_init_creds_opt *opt" .Fa "int change_password_prompt" .Fc .Ft void .Fo krb5_get_init_creds_opt_set_default_flags .Fa "krb5_context context" .Fa "const char *appname" .Fa "krb5_const_realm realm" .Fa "krb5_get_init_creds_opt *opt" .Fc .Ft void .Fo krb5_get_init_creds_opt_set_etype_list .Fa "krb5_get_init_creds_opt *opt" .Fa "krb5_enctype *etype_list" .Fa "int etype_list_length" .Fc .Ft void .Fo krb5_get_init_creds_opt_set_forwardable .Fa "krb5_get_init_creds_opt *opt" .Fa "int forwardable" .Fc .Ft krb5_error_code .Fo krb5_get_init_creds_opt_set_pa_password .Fa "krb5_context context" .Fa "krb5_get_init_creds_opt *opt" .Fa "const char *password" .Fa "krb5_s2k_proc key_proc" .Fc .Ft krb5_error_code .Fo krb5_get_init_creds_opt_set_paq_request .Fa "krb5_context context" .Fa "krb5_get_init_creds_opt *opt" .Fa "krb5_boolean req_pac" .Fc .Ft krb5_error_code .Fo krb5_get_init_creds_opt_set_pkinit .Fa "krb5_context context" .Fa "krb5_get_init_creds_opt *opt" .Fa "const char *cert_file" .Fa "const char *key_file" .Fa "const char *x509_anchors" .Fa "int flags" .Fa "char *password" .Fc .Ft void .Fo krb5_get_init_creds_opt_set_preauth_list .Fa "krb5_get_init_creds_opt *opt" .Fa "krb5_preauthtype *preauth_list" .Fa "int preauth_list_length" .Fc .Ft void .Fo krb5_get_init_creds_opt_set_proxiable .Fa "krb5_get_init_creds_opt *opt" .Fa "int proxiable" .Fc .Ft void .Fo krb5_get_init_creds_opt_set_renew_life .Fa "krb5_get_init_creds_opt *opt" .Fa "krb5_deltat renew_life" .Fc .Ft void .Fo krb5_get_init_creds_opt_set_salt .Fa "krb5_get_init_creds_opt *opt" .Fa "krb5_data *salt" .Fc .Ft void .Fo krb5_get_init_creds_opt_set_tkt_life .Fa "krb5_get_init_creds_opt *opt" .Fa "krb5_deltat tkt_life" .Fc .Ft krb5_error_code .Fo krb5_get_init_creds_opt_set_canonicalize .Fa "krb5_context context" .Fa "krb5_get_init_creds_opt *opt" .Fa "krb5_boolean req" .Fc .Ft krb5_error_code .Fo krb5_get_init_creds_opt_set_win2k .Fa "krb5_context context" .Fa "krb5_get_init_creds_opt *opt" .Fa "krb5_boolean req" .Fc .Ft krb5_error_code .Fo krb5_get_init_creds .Fa "krb5_context context" .Fa "krb5_creds *creds" .Fa "krb5_principal client" .Fa "krb5_prompter_fct prompter" .Fa "void *prompter_data" .Fa "krb5_deltat start_time" .Fa "const char *in_tkt_service" .Fa "krb5_get_init_creds_opt *options" .Fc .Ft krb5_error_code .Fo krb5_get_init_creds_password .Fa "krb5_context context" .Fa "krb5_creds *creds" .Fa "krb5_principal client" .Fa "const char *password" .Fa "krb5_prompter_fct prompter" .Fa "void *prompter_data" .Fa "krb5_deltat start_time" .Fa "const char *in_tkt_service" .Fa "krb5_get_init_creds_opt *in_options" .Fc .Ft krb5_error_code .Fo krb5_get_init_creds_keytab .Fa "krb5_context context" .Fa "krb5_creds *creds" .Fa "krb5_principal client" .Fa "krb5_keytab keytab" .Fa "krb5_deltat start_time" .Fa "const char *in_tkt_service" .Fa "krb5_get_init_creds_opt *options" .Fc .Ft int .Fo krb5_prompter_posix .Fa "krb5_context context" .Fa "void *data" .Fa "const char *name" .Fa "const char *banner" .Fa "int num_prompts" .Fa "krb5_prompt prompts[]" .Fc .Sh DESCRIPTION Getting initial credential ticket for a principal. That may include changing an expired password, and doing preauthentication. This interface that replaces the deprecated .Fa krb5_in_tkt and .Fa krb5_in_cred functions. .Pp If you only want to verify a username and password, consider using .Xr krb5_verify_user 3 instead, since it also verifies that initial credentials with using a keytab to make sure the response was from the KDC. .Pp First a .Li krb5_get_init_creds_opt structure is initialized with .Fn krb5_get_init_creds_opt_alloc or .Fn krb5_get_init_creds_opt_init . .Fn krb5_get_init_creds_opt_alloc allocates a extendible structures that needs to be freed with .Fn krb5_get_init_creds_opt_free . The structure may be modified by any of the .Fn krb5_get_init_creds_opt_set functions to change request parameters and authentication information. .Pp If the caller want to use the default options, .Dv NULL can be passed instead. .Pp The the actual request to the KDC is done by any of the .Fn krb5_get_init_creds , .Fn krb5_get_init_creds_password , or .Fn krb5_get_init_creds_keytab functions. .Fn krb5_get_init_creds is the least specialized function and can, with the right in data, behave like the latter two. The latter two are there for compatibility with older releases and they are slightly easier to use. .Pp .Li krb5_prompt is a structure containing the following elements: .Bd -literal typedef struct { const char *prompt; int hidden; krb5_data *reply; krb5_prompt_type type } krb5_prompt; .Ed .Pp .Fa prompt is the prompt that should shown to the user If .Fa hidden is set, the prompter function shouldn't echo the output to the display device. .Fa reply must be preallocated; it will not be allocated by the prompter function. Possible values for the .Fa type element are: .Pp .Bl -tag -width Ds -compact -offset indent .It KRB5_PROMPT_TYPE_PASSWORD .It KRB5_PROMPT_TYPE_NEW_PASSWORD .It KRB5_PROMPT_TYPE_NEW_PASSWORD_AGAIN .It KRB5_PROMPT_TYPE_PREAUTH .It KRB5_PROMPT_TYPE_INFO .El .Pp .Fn krb5_prompter_posix is the default prompter function in a POSIX environment. It matches the .Fa krb5_prompter_fct and can be used in the .Fa krb5_get_init_creds functions. .Fn krb5_prompter_posix doesn't require .Fa prompter_data. .Pp If the .Fa start_time is zero, then the requested ticket will be valid beginning immediately. Otherwise, the .Fa start_time indicates how far in the future the ticket should be postdated. .Pp If the .Fa in_tkt_service name is .Dv non-NULL , that principal name will be used as the server name for the initial ticket request. The realm of the name specified will be ignored and will be set to the realm of the client name. If no in_tkt_service name is specified, krbtgt/CLIENT-REALM@CLIENT-REALM will be used. .Pp For the rest of arguments, a configuration or library default will be used if no value is specified in the options structure. .Pp .Fn krb5_get_init_creds_opt_set_address_list sets the list of .Fa addresses that is should be stored in the ticket. .Pp .Fn krb5_get_init_creds_opt_set_addressless controls if the ticket is requested with addresses or not, .Fn krb5_get_init_creds_opt_set_address_list overrides this option. .Pp .Fn krb5_get_init_creds_opt_set_anonymous make the request anonymous if the .Fa anonymous parameter is non-zero. .Pp .Fn krb5_get_init_creds_opt_set_default_flags sets the default flags using the configuration file. .Pp .Fn krb5_get_init_creds_opt_set_etype_list set a list of enctypes that the client is willing to support in the request. .Pp .Fn krb5_get_init_creds_opt_set_forwardable request a forwardable ticket. .Pp .Fn krb5_get_init_creds_opt_set_pa_password set the .Fa password and .Fa key_proc that is going to be used to get a new ticket. .Fa password or .Fa key_proc can be .Dv NULL if the caller wants to use the default values. If the .Fa password is unset and needed, the user will be prompted for it. .Pp .Fn krb5_get_init_creds_opt_set_paq_request sets the password that is going to be used to get a new ticket. .Pp .Fn krb5_get_init_creds_opt_set_preauth_list sets the list of client-supported preauth types. .Pp .Fn krb5_get_init_creds_opt_set_proxiable makes the request proxiable. .Pp .Fn krb5_get_init_creds_opt_set_renew_life sets the requested renewable lifetime. .Pp .Fn krb5_get_init_creds_opt_set_salt sets the salt that is going to be used in the request. .Pp .Fn krb5_get_init_creds_opt_set_tkt_life sets requested ticket lifetime. .Pp .Fn krb5_get_init_creds_opt_set_canonicalize requests that the KDC canonicalize the client principal if possible. .Pp .Fn krb5_get_init_creds_opt_set_win2k turns on compatibility with Windows 2000. .Sh SEE ALSO .Xr krb5 3 , .Xr krb5_creds 3 , .Xr krb5_verify_user 3 , .Xr krb5.conf 5 , .Xr kerberos 8 heimdal-7.5.0/lib/krb5/krb5-plugin.cat70000644000175000017500000001714413212450757015617 0ustar niknik KRB5-PLUGIN(7) BSD Miscellaneous Information Manual KRB5-PLUGIN(7) NNAAMMEE kkrrbb55--pplluuggiinn -- plugin interface for Heimdal SSYYNNOOPPSSIISS ##iinncclluuddee <> ##iinncclluuddee <> ##iinncclluuddee <> ##iinncclluuddee <> ##iinncclluuddee <> ##iinncclluuddee <> ##iinncclluuddee <> DDEESSCCRRIIPPTTIIOONN Heimdal has a plugin interface. Plugins may be statically linked into Heimdal and registered via the krb5_plugin_register(3) function, or they may be dynamically loaded from shared objects present in the Heimdal plugins directories. Plugins consist of a C struct whose struct name is given in the associ- ated header file, such as, for example, _k_r_b_5_p_l_u_g_i_n___k_u_s_e_r_o_k___f_t_a_b_l_e and a pointer to which is either registered via krb5_plugin_register(3) or found in a shared object via a symbol lookup for the symbol name defined in the associated header file (e.g., "kuserok" for the plugin for krb5_kuserok(3) ). The plugin structs for all plugin types always begin with the same three common fields: 1. _m_i_n_o_r___v_e_r_s_i_o_n , an int. Plugin minor versions are defined in each plugin type's associated header file. 2. _i_n_i_t , a pointer to a function with two arguments, a krb5_context and a void **, returning a krb5_error_code. This function will be called to initialize a plugin-specific context in the form of a void * that will be output through the init function's second argument. 3. _f_i_n_i , a pointer to a function of one argument, a void *, consisting of the plugin's context to be destroyed, and returning void. Each plugin type must add zero or more fields to this struct following the above three. Plugins are typically invoked in no particular order until one succeeds or fails, or all return a special return value such as KRB5_PLUGIN_NO_HANDLE to indicate that the plugin was not applicable. Most plugin types obtain deterministic plugin behavior in spite of the non-deterministic invocation order by, for example, invoking all plugins for each "rule" and passing the rule to each plugin with the expectation that just one plugin will match any given rule. There is a database plugin system intended for many of the uses of data- bases in Heimdal. The plugin is expected to call heim_db_register(3) from its _i_n_i_t entry point to register a DB type. The DB plugin's _f_i_n_i function must do nothing, and the plugin must not provide any other entry points. The krb5_kuserok plugin adds a single field to its struct: a pointer to a function that implements kuserok functionality with the following form: static krb5_error_code kuserok(void *plug_ctx, krb5_context context, const char *rule, unsigned int flags, const char *k5login_dir, const char *luser, krb5_const_principal principal, krb5_boolean *result) The _l_u_s_e_r , _p_r_i_n_c_i_p_a_l and _r_e_s_u_l_t arguments are self-explanatory (see krb5_kuserok(3) ). The _p_l_u_g___c_t_x argument is the context output by the plugin's init function. The _r_u_l_e argument is a kuserok rule from the krb5.conf file; each plugin is invoked once for each rule until all plug- ins fail or one succeeds. The _k_5_l_o_g_i_n___d_i_r argument provides an alterna- tive k5login file location, if not NULL. The _f_l_a_g_s argument indicates whether the plugin may call krb5_aname_to_localname(3) (KUSEROK_ANAME_TO_LNAME_OK), and whether k5login databases are expected to be authoritative (KUSEROK_K5LOGIN_IS_AUTHORITATIVE). The plugin for krb5_aname_to_localname(3) is named "an2ln" and has a sin- gle extra field for the plugin struct: typedef krb5_error_code (*set_result_f)(void *, const char *); static krb5_error_code an2ln(void *plug_ctx, krb5_context context, const char *rule, krb5_const_principal aname, set_result_f set_res_f, void *set_res_ctx) The arguments for the _a_n_2_l_n plugin are similar to those of the kuserok plugin, but the result, being a string, is set by calling the _s_e_t___r_e_s___f function argument with the _s_e_t___r_e_s___c_t_x and result string as arguments. The _s_e_t___r_e_s___f function will make a copy of the string. FFIILLEESS libdir/plugin/krb5/* Shared objects containing plugins for Heimdal. EEXXAAMMPPLLEESS An example an2ln plugin that maps principals to a constant "nouser" fol- lows: #include static krb5_error_code nouser_plug_init(krb5_context context, void **ctx) { *ctx = NULL; return 0; } static void nouser_plug_fini(void *ctx) { } static krb5_error_code nouser_plug_an2ln(void *plug_ctx, krb5_context context, const char *rule, krb5_const_principal aname, set_result_f set_res_f, void *set_res_ctx) { krb5_error_code ret; if (strcmp(rule, "NOUSER") != 0) return KRB5_PLUGIN_NO_HANDLE; ret = set_res_f(set_res_ctx, "nouser"); return ret; } krb5plugin_an2ln_ftable an2ln = { KRB5_PLUGIN_AN2LN_VERSION_0, nouser_plug_init, nouser_plug_fini, nouser_plug_an2ln, }; An example kuserok plugin that rejects all requests follows. (Note that there exists a built-in plugin with this functionality; see krb5_kuserok(3) ). #include static krb5_error_code reject_plug_init(krb5_context context, void **ctx) { *ctx = NULL; return 0; } static void reject_plug_fini(void *ctx) { } static krb5_error_code reject_plug_kuserok(void *plug_ctx, krb5_context context, const char *rule, unsigned int flags, const char *k5login_dir, const char *luser, krb5_const_principal principal, krb5_boolean *result) { if (strcmp(rule, "REJECT") != 0) return KRB5_PLUGIN_NO_HANDLE; *result = FALSE; return 0; } krb5plugin_kuserok_ftable kuserok = { KRB5_PLUGIN_KUSEROK_VERSION_0, reject_plug_init, reject_plug_fini, reject_plug_kuserok, }; SSEEEE AALLSSOO krb5_plugin_register(3) krb5_kuserok(3) krb5_aname_to_localname(3) HEIMDAL December 21, 2011 HEIMDAL heimdal-7.5.0/lib/krb5/krb5_string_to_key.30000644000175000017500000001061413026237312016553 0ustar niknik.\" Copyright (c) 2004 - 2006 Kungliga Tekniska Högskolan .\" (Royal Institute of Technology, Stockholm, Sweden). .\" All rights reserved. .\" .\" Redistribution and use in source and binary forms, with or without .\" modification, are permitted provided that the following conditions .\" are met: .\" .\" 1. Redistributions of source code must retain the above copyright .\" notice, this list of conditions and the following disclaimer. .\" .\" 2. Redistributions in binary form must reproduce the above copyright .\" notice, this list of conditions and the following disclaimer in the .\" documentation and/or other materials provided with the distribution. .\" .\" 3. Neither the name of the Institute nor the names of its contributors .\" may be used to endorse or promote products derived from this software .\" without specific prior written permission. .\" .\" THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND .\" ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE .\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE .\" ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE .\" FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL .\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS .\" OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) .\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT .\" LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF .\" SUCH DAMAGE. .\" .\" $Id$ .\" .Dd July 10, 2006 .Dt KRB5_STRING_TO_KEY 3 .Os HEIMDAL .Sh NAME .Nm krb5_string_to_key , .Nm krb5_string_to_key_data , .Nm krb5_string_to_key_data_salt , .Nm krb5_string_to_key_data_salt_opaque , .Nm krb5_string_to_key_salt , .Nm krb5_string_to_key_salt_opaque , .Nm krb5_get_pw_salt , .Nm krb5_free_salt .Nd turns a string to a Kerberos key .Sh LIBRARY Kerberos 5 Library (libkrb5, -lkrb5) .Sh SYNOPSIS .In krb5.h .Ft krb5_error_code .Fo krb5_string_to_key .Fa "krb5_context context" .Fa "krb5_enctype enctype" .Fa "const char *password" .Fa "krb5_principal principal" .Fa "krb5_keyblock *key" .Fc .Ft krb5_error_code .Fo krb5_string_to_key_data .Fa "krb5_context context" .Fa "krb5_enctype enctype" .Fa "krb5_data password" .Fa "krb5_principal principal" .Fa "krb5_keyblock *key" .Fc .Ft krb5_error_code .Fo krb5_string_to_key_data_salt .Fa "krb5_context context" .Fa "krb5_enctype enctype" .Fa "krb5_data password" .Fa "krb5_salt salt" .Fa "krb5_keyblock *key" .Fc .Ft krb5_error_code .Fo krb5_string_to_key_data_salt_opaque .Fa "krb5_context context" .Fa "krb5_enctype enctype" .Fa "krb5_data password" .Fa "krb5_salt salt" .Fa "krb5_data opaque" .Fa "krb5_keyblock *key" .Fc .Ft krb5_error_code .Fo krb5_string_to_key_salt .Fa "krb5_context context" .Fa "krb5_enctype enctype" .Fa "const char *password" .Fa "krb5_salt salt" .Fa "krb5_keyblock *key" .Fc .Ft krb5_error_code .Fo krb5_string_to_key_salt_opaque .Fa "krb5_context context" .Fa "krb5_enctype enctype" .Fa "const char *password" .Fa "krb5_salt salt" .Fa "krb5_data opaque" .Fa "krb5_keyblock *key" .Fc .Ft krb5_error_code .Fo krb5_get_pw_salt .Fa "krb5_context context" .Fa "krb5_const_principal principal" .Fa "krb5_salt *salt" .Fc .Ft krb5_error_code .Fo krb5_free_salt .Fa "krb5_context context" .Fa "krb5_salt salt" .Fc .Sh DESCRIPTION The string to key functions convert a string to a kerberos key. .Pp .Fn krb5_string_to_key_data_salt_opaque is the function that does all the work, the rest of the functions are just wrappers around .Fn krb5_string_to_key_data_salt_opaque that calls it with default values. .Pp .Fn krb5_string_to_key_data_salt_opaque transforms the .Fa password with the given salt-string .Fa salt and the opaque, encryption type specific parameter .Fa opaque to a encryption key .Fa key according to the string to key function associated with .Fa enctype . .Pp The .Fa key should be freed with .Fn krb5_free_keyblock_contents . .Pp If one of the functions that doesn't take a .Li krb5_salt as it argument .Fn krb5_get_pw_salt is used to get the salt value. .Pp .Fn krb5_get_pw_salt get the default password salt for a principal, use .Fn krb5_free_salt to free the salt when done. .Pp .Fn krb5_free_salt frees the content of .Fa salt . .Sh SEE ALSO .Xr krb5 3 , .Xr krb5_data 3 , .Xr krb5_keyblock 3 , .Xr kerberos 8 heimdal-7.5.0/lib/krb5/get_for_creds.c0000644000175000017500000003217413212137553015645 0ustar niknik/* * Copyright (c) 1997 - 2004 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "krb5_locl.h" static krb5_error_code add_addrs(krb5_context context, krb5_addresses *addr, struct addrinfo *ai) { krb5_error_code ret; unsigned n, i; void *tmp; struct addrinfo *a; n = 0; for (a = ai; a != NULL; a = a->ai_next) ++n; tmp = realloc(addr->val, (addr->len + n) * sizeof(*addr->val)); if (tmp == NULL && (addr->len + n) != 0) { ret = krb5_enomem(context); goto fail; } addr->val = tmp; for (i = addr->len; i < (addr->len + n); ++i) { addr->val[i].addr_type = 0; krb5_data_zero(&addr->val[i].address); } i = addr->len; for (a = ai; a != NULL; a = a->ai_next) { krb5_address ad; ret = krb5_sockaddr2address (context, a->ai_addr, &ad); if (ret == 0) { if (krb5_address_search(context, &ad, addr)) krb5_free_address(context, &ad); else addr->val[i++] = ad; } else if (ret == KRB5_PROG_ATYPE_NOSUPP) krb5_clear_error_message (context); else goto fail; addr->len = i; } return 0; fail: krb5_free_addresses (context, addr); return ret; } /** * Forward credentials for client to host hostname , making them * forwardable if forwardable, and returning the blob of data to sent * in out_data. If hostname == NULL, pick it from server. * * @param context A kerberos 5 context. * @param auth_context the auth context with the key to encrypt the out_data. * @param hostname the host to forward the tickets too. * @param client the client to delegate from. * @param server the server to delegate the credential too. * @param ccache credential cache to use. * @param forwardable make the forwarded ticket forwabledable. * @param out_data the resulting credential. * * @return Return an error code or 0. * * @ingroup krb5_credential */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_fwd_tgt_creds (krb5_context context, krb5_auth_context auth_context, const char *hostname, krb5_principal client, krb5_principal server, krb5_ccache ccache, int forwardable, krb5_data *out_data) { krb5_flags flags = 0; krb5_creds creds; krb5_error_code ret; krb5_const_realm client_realm; flags |= KDC_OPT_FORWARDED; if (forwardable) flags |= KDC_OPT_FORWARDABLE; if (hostname == NULL && krb5_principal_get_type(context, server) == KRB5_NT_SRV_HST) { const char *inst = krb5_principal_get_comp_string(context, server, 0); const char *host = krb5_principal_get_comp_string(context, server, 1); if (inst != NULL && strcmp(inst, "host") == 0 && host != NULL && krb5_principal_get_comp_string(context, server, 2) == NULL) hostname = host; } client_realm = krb5_principal_get_realm(context, client); memset (&creds, 0, sizeof(creds)); creds.client = client; ret = krb5_make_principal(context, &creds.server, client_realm, KRB5_TGS_NAME, client_realm, NULL); if (ret) return ret; ret = krb5_get_forwarded_creds (context, auth_context, ccache, flags, hostname, &creds, out_data); return ret; } /** * Gets tickets forwarded to hostname. If the tickets that are * forwarded are address-less, the forwarded tickets will also be * address-less. * * If the ticket have any address, hostname will be used for figure * out the address to forward the ticket too. This since this might * use DNS, its insecure and also doesn't represent configured all * addresses of the host. For example, the host might have two * adresses, one IPv4 and one IPv6 address where the later is not * published in DNS. This IPv6 address might be used communications * and thus the resulting ticket useless. * * @param context A kerberos 5 context. * @param auth_context the auth context with the key to encrypt the out_data. * @param ccache credential cache to use * @param flags the flags to control the resulting ticket flags * @param hostname the host to forward the tickets too. * @param in_creds the in client and server ticket names. The client * and server components forwarded to the remote host. * @param out_data the resulting credential. * * @return Return an error code or 0. * * @ingroup krb5_credential */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_get_forwarded_creds (krb5_context context, krb5_auth_context auth_context, krb5_ccache ccache, krb5_flags flags, const char *hostname, krb5_creds *in_creds, krb5_data *out_data) { krb5_error_code ret; krb5_creds *out_creds; krb5_addresses addrs, *paddrs; KRB_CRED cred; KrbCredInfo *krb_cred_info; EncKrbCredPart enc_krb_cred_part; size_t len; unsigned char *buf; size_t buf_size; krb5_kdc_flags kdc_flags; krb5_crypto crypto; struct addrinfo *ai; krb5_creds *ticket; paddrs = NULL; addrs.len = 0; addrs.val = NULL; ret = krb5_get_credentials(context, 0, ccache, in_creds, &ticket); if(ret == 0) { if (ticket->addresses.len) paddrs = &addrs; krb5_free_creds (context, ticket); } else { krb5_boolean noaddr; krb5_appdefault_boolean(context, NULL, krb5_principal_get_realm(context, in_creds->client), "no-addresses", KRB5_ADDRESSLESS_DEFAULT, &noaddr); if (!noaddr) paddrs = &addrs; } /* * If tickets have addresses, get the address of the remote host. */ if (paddrs != NULL) { ret = getaddrinfo (hostname, NULL, NULL, &ai); if (ret) { krb5_error_code ret2 = krb5_eai_to_heim_errno(ret, errno); krb5_set_error_message(context, ret2, N_("resolving host %s failed: %s", "hostname, error"), hostname, gai_strerror(ret)); return ret2; } ret = add_addrs (context, &addrs, ai); freeaddrinfo (ai); if (ret) return ret; } kdc_flags.b = int2KDCOptions(flags); ret = krb5_get_kdc_cred (context, ccache, kdc_flags, paddrs, NULL, in_creds, &out_creds); krb5_free_addresses (context, &addrs); if (ret) return ret; memset (&cred, 0, sizeof(cred)); cred.pvno = 5; cred.msg_type = krb_cred; ALLOC_SEQ(&cred.tickets, 1); if (cred.tickets.val == NULL) { ret = krb5_enomem(context); goto out2; } ret = decode_Ticket(out_creds->ticket.data, out_creds->ticket.length, cred.tickets.val, &len); if (ret) goto out3; memset (&enc_krb_cred_part, 0, sizeof(enc_krb_cred_part)); ALLOC_SEQ(&enc_krb_cred_part.ticket_info, 1); if (enc_krb_cred_part.ticket_info.val == NULL) { ret = krb5_enomem(context); goto out4; } if (auth_context->flags & KRB5_AUTH_CONTEXT_DO_TIME) { krb5_timestamp sec; int32_t usec; krb5_us_timeofday (context, &sec, &usec); ALLOC(enc_krb_cred_part.timestamp, 1); if (enc_krb_cred_part.timestamp == NULL) { ret = krb5_enomem(context); goto out4; } *enc_krb_cred_part.timestamp = sec; ALLOC(enc_krb_cred_part.usec, 1); if (enc_krb_cred_part.usec == NULL) { ret = krb5_enomem(context); goto out4; } *enc_krb_cred_part.usec = usec; } else { enc_krb_cred_part.timestamp = NULL; enc_krb_cred_part.usec = NULL; } if (auth_context->local_address && auth_context->local_port && paddrs) { ret = krb5_make_addrport (context, &enc_krb_cred_part.s_address, auth_context->local_address, auth_context->local_port); if (ret) goto out4; } if (auth_context->remote_address) { if (auth_context->remote_port) { krb5_boolean noaddr; krb5_const_realm srealm; srealm = krb5_principal_get_realm(context, out_creds->server); /* Is this correct, and should we use the paddrs == NULL trick here as well? Having an address-less ticket may indicate that we don't know our own global address, but it does not necessary mean that we don't know the server's. */ krb5_appdefault_boolean(context, NULL, srealm, "no-addresses", FALSE, &noaddr); if (!noaddr) { ret = krb5_make_addrport (context, &enc_krb_cred_part.r_address, auth_context->remote_address, auth_context->remote_port); if (ret) goto out4; } } else { ALLOC(enc_krb_cred_part.r_address, 1); if (enc_krb_cred_part.r_address == NULL) { ret = krb5_enomem(context); goto out4; } ret = krb5_copy_address (context, auth_context->remote_address, enc_krb_cred_part.r_address); if (ret) goto out4; } } /* fill ticket_info.val[0] */ enc_krb_cred_part.ticket_info.len = 1; krb_cred_info = enc_krb_cred_part.ticket_info.val; copy_EncryptionKey (&out_creds->session, &krb_cred_info->key); ALLOC(krb_cred_info->prealm, 1); copy_Realm (&out_creds->client->realm, krb_cred_info->prealm); ALLOC(krb_cred_info->pname, 1); copy_PrincipalName(&out_creds->client->name, krb_cred_info->pname); ALLOC(krb_cred_info->flags, 1); *krb_cred_info->flags = out_creds->flags.b; ALLOC(krb_cred_info->authtime, 1); *krb_cred_info->authtime = out_creds->times.authtime; ALLOC(krb_cred_info->starttime, 1); *krb_cred_info->starttime = out_creds->times.starttime; ALLOC(krb_cred_info->endtime, 1); *krb_cred_info->endtime = out_creds->times.endtime; ALLOC(krb_cred_info->renew_till, 1); *krb_cred_info->renew_till = out_creds->times.renew_till; ALLOC(krb_cred_info->srealm, 1); copy_Realm (&out_creds->server->realm, krb_cred_info->srealm); ALLOC(krb_cred_info->sname, 1); copy_PrincipalName (&out_creds->server->name, krb_cred_info->sname); ALLOC(krb_cred_info->caddr, 1); copy_HostAddresses (&out_creds->addresses, krb_cred_info->caddr); krb5_free_creds (context, out_creds); /* encode EncKrbCredPart */ ASN1_MALLOC_ENCODE(EncKrbCredPart, buf, buf_size, &enc_krb_cred_part, &len, ret); free_EncKrbCredPart (&enc_krb_cred_part); if (ret) { free_KRB_CRED(&cred); return ret; } if(buf_size != len) krb5_abortx(context, "internal error in ASN.1 encoder"); /** * Some older of the MIT gssapi library used clear-text tickets * (warped inside AP-REQ encryption), use the krb5_auth_context * flag KRB5_AUTH_CONTEXT_CLEAR_FORWARDED_CRED to support those * tickets. The session key is used otherwise to encrypt the * forwarded ticket. */ if (auth_context->flags & KRB5_AUTH_CONTEXT_CLEAR_FORWARDED_CRED) { cred.enc_part.etype = KRB5_ENCTYPE_NULL; cred.enc_part.kvno = NULL; cred.enc_part.cipher.data = buf; cred.enc_part.cipher.length = buf_size; } else { /* * Here older versions then 0.7.2 of Heimdal used the local or * remote subkey. That is wrong, the session key should be * used. Heimdal 0.7.2 and newer have code to try both in the * receiving end. */ ret = krb5_crypto_init(context, auth_context->keyblock, 0, &crypto); if (ret) { free(buf); free_KRB_CRED(&cred); return ret; } ret = krb5_encrypt_EncryptedData (context, crypto, KRB5_KU_KRB_CRED, buf, len, 0, &cred.enc_part); free(buf); krb5_crypto_destroy(context, crypto); if (ret) { free_KRB_CRED(&cred); return ret; } } ASN1_MALLOC_ENCODE(KRB_CRED, buf, buf_size, &cred, &len, ret); free_KRB_CRED (&cred); if (ret) return ret; if(buf_size != len) krb5_abortx(context, "internal error in ASN.1 encoder"); out_data->length = len; out_data->data = buf; return 0; out4: free_EncKrbCredPart(&enc_krb_cred_part); out3: free_KRB_CRED(&cred); out2: krb5_free_creds (context, out_creds); return ret; } heimdal-7.5.0/lib/krb5/krb5_init_context.30000644000175000017500000001760013026237312016404 0ustar niknik.\" Copyright (c) 2001 - 2004 Kungliga Tekniska Högskolan .\" (Royal Institute of Technology, Stockholm, Sweden). .\" All rights reserved. .\" .\" Redistribution and use in source and binary forms, with or without .\" modification, are permitted provided that the following conditions .\" are met: .\" .\" 1. Redistributions of source code must retain the above copyright .\" notice, this list of conditions and the following disclaimer. .\" .\" 2. Redistributions in binary form must reproduce the above copyright .\" notice, this list of conditions and the following disclaimer in the .\" documentation and/or other materials provided with the distribution. .\" .\" 3. Neither the name of the Institute nor the names of its contributors .\" may be used to endorse or promote products derived from this software .\" without specific prior written permission. .\" .\" THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND .\" ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE .\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE .\" ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE .\" FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL .\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS .\" OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) .\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT .\" LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF .\" SUCH DAMAGE. .\" .\" $Id$ .\" .Dd December 8, 2004 .Dt KRB5_CONTEXT 3 .Os HEIMDAL .Sh NAME .Nm krb5_add_et_list , .Nm krb5_add_extra_addresses , .Nm krb5_add_ignore_addresses , .Nm krb5_context , .Nm krb5_free_config_files , .Nm krb5_free_context , .Nm krb5_get_default_config_files , .Nm krb5_get_dns_canonize_hostname , .Nm krb5_get_extra_addresses , .Nm krb5_get_fcache_version , .Nm krb5_get_ignore_addresses , .Nm krb5_get_kdc_sec_offset , .Nm krb5_get_max_time_skew , .Nm krb5_get_use_admin_kdc .Nm krb5_init_context , .Nm krb5_init_ets , .Nm krb5_prepend_config_files , .Nm krb5_prepend_config_files_default , .Nm krb5_set_config_files , .Nm krb5_set_dns_canonize_hostname , .Nm krb5_set_extra_addresses , .Nm krb5_set_fcache_version , .Nm krb5_set_ignore_addresses , .Nm krb5_set_max_time_skew , .Nm krb5_set_use_admin_kdc , .Nd create, modify and delete krb5_context structures .Sh LIBRARY Kerberos 5 Library (libkrb5, -lkrb5) .Sh SYNOPSIS .In krb5.h .Pp .Li "struct krb5_context;" .Pp .Ft krb5_error_code .Fo krb5_init_context .Fa "krb5_context *context" .Fc .Ft void .Fo krb5_free_context .Fa "krb5_context context" .Fc .Ft void .Fo krb5_init_ets .Fa "krb5_context context" .Fc .Ft krb5_error_code .Fo krb5_add_et_list .Fa "krb5_context context" .Fa "void (*func)(struct et_list **)" .Fc .Ft krb5_error_code .Fo krb5_add_extra_addresses .Fa "krb5_context context" .Fa "krb5_addresses *addresses" .Fc .Ft krb5_error_code .Fo krb5_set_extra_addresses .Fa "krb5_context context" .Fa "const krb5_addresses *addresses" .Fc .Ft krb5_error_code .Fo krb5_get_extra_addresses .Fa "krb5_context context" .Fa "krb5_addresses *addresses" .Fc .Ft krb5_error_code .Fo krb5_add_ignore_addresses .Fa "krb5_context context" .Fa "krb5_addresses *addresses" .Fc .Ft krb5_error_code .Fo krb5_set_ignore_addresses .Fa "krb5_context context" .Fa "const krb5_addresses *addresses" .Fc .Ft krb5_error_code .Fo krb5_get_ignore_addresses .Fa "krb5_context context" .Fa "krb5_addresses *addresses" .Fc .Ft krb5_error_code .Fo krb5_set_fcache_version .Fa "krb5_context context" .Fa "int version" .Fc .Ft krb5_error_code .Fo krb5_get_fcache_version .Fa "krb5_context context" .Fa "int *version" .Fc .Ft void .Fo krb5_set_dns_canonize_hostname .Fa "krb5_context context" .Fa "krb5_boolean flag" .Fc .Ft krb5_boolean .Fo krb5_get_dns_canonize_hostname .Fa "krb5_context context" .Fc .Ft krb5_error_code .Fo krb5_get_kdc_sec_offset .Fa "krb5_context context" .Fa "int32_t *sec" .Fa "int32_t *usec" .Fc .Ft krb5_error_code .Fo krb5_set_config_files .Fa "krb5_context context" .Fa "char **filenames" .Fc .Ft krb5_error_code .Fo krb5_prepend_config_files .Fa "const char *filelist" .Fa "char **pq" .Fa "char ***ret_pp" .Fc .Ft krb5_error_code .Fo krb5_prepend_config_files_default .Fa "const char *filelist" .Fa "char ***pfilenames" .Fc .Ft krb5_error_code .Fo krb5_get_default_config_files .Fa "char ***pfilenames" .Fc .Ft void .Fo krb5_free_config_files .Fa "char **filenames" .Fc .Ft void .Fo krb5_set_use_admin_kdc .Fa "krb5_context context" .Fa "krb5_boolean flag" .Fc .Ft krb5_boolean .Fo krb5_get_use_admin_kdc .Fa "krb5_context context" .Fc .Ft time_t .Fo krb5_get_max_time_skew .Fa "krb5_context context" .Fc .Ft krb5_error_code .Fo krb5_set_max_time_skew .Fa "krb5_context context" .Fa "time_t time" .Fc .Sh DESCRIPTION The .Fn krb5_init_context function initializes the .Fa context structure and reads the configuration file .Pa /etc/krb5.conf . .Pp The structure should be freed by calling .Fn krb5_free_context when it is no longer being used. .Pp .Fn krb5_init_context returns 0 to indicate success. Otherwise an errno code is returned. Failure means either that something bad happened during initialization (typically .Bq ENOMEM ) or that Kerberos should not be used .Bq ENXIO . .Pp .Fn krb5_init_ets adds all .Xr com_err 3 libs to .Fa context . This is done by .Fn krb5_init_context . .Pp .Fn krb5_add_et_list adds a .Xr com_err 3 error-code handler .Fa func to the specified .Fa context . The error handler must generated by the the re-rentrant version of the .Xr compile_et 1 program. .Fn krb5_add_extra_addresses add a list of addresses that should be added when requesting tickets. .Pp .Fn krb5_add_ignore_addresses add a list of addresses that should be ignored when requesting tickets. .Pp .Fn krb5_get_extra_addresses get the list of addresses that should be added when requesting tickets. .Pp .Fn krb5_get_ignore_addresses get the list of addresses that should be ignored when requesting tickets. .Pp .Fn krb5_set_ignore_addresses set the list of addresses that should be ignored when requesting tickets. .Pp .Fn krb5_set_extra_addresses set the list of addresses that should be added when requesting tickets. .Pp .Fn krb5_set_fcache_version sets the version of file credentials caches that should be used. .Pp .Fn krb5_get_fcache_version gets the version of file credentials caches that should be used. .Pp .Fn krb5_set_dns_canonize_hostname sets if the context is configured to canonicalize hostnames using DNS. .Pp .Fn krb5_get_dns_canonize_hostname returns if the context is configured to canonicalize hostnames using DNS. .Pp .Fn krb5_get_kdc_sec_offset returns the offset between the localtime and the KDC's time. .Fa sec and .Fa usec are both optional argument and .Dv NULL can be passed in. .Pp .Fn krb5_set_config_files set the list of configuration files to use and re-initialize the configuration from the files. .Pp .Fn krb5_prepend_config_files parse the .Fa filelist and prepend the result to the already existing list .Fa pq The result is returned in .Fa ret_pp and should be freed with .Fn krb5_free_config_files . .Pp .Fn krb5_prepend_config_files_default parse the .Fa filelist and append that to the default list of configuration files. .Pp .Fn krb5_get_default_config_files get a list of default configuration files. .Pp .Fn krb5_free_config_files free a list of configuration files returned by .Fn krb5_get_default_config_files , .Fn krb5_prepend_config_files_default , or .Fn krb5_prepend_config_files . .Pp .Fn krb5_set_use_admin_kdc sets if all KDC requests should go admin KDC. .Pp .Fn krb5_get_use_admin_kdc gets if all KDC requests should go admin KDC. .Pp .Fn krb5_get_max_time_skew and .Fn krb5_set_max_time_skew get and sets the maximum allowed time skew between client and server. .Sh SEE ALSO .Xr errno 2 , .Xr krb5 3 , .Xr krb5_config 3 , .Xr krb5_context 3 , .Xr kerberos 8 heimdal-7.5.0/lib/krb5/crypto.c0000644000175000017500000022644213212137553014363 0ustar niknik/* * Copyright (c) 1997 - 2008 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "krb5_locl.h" struct _krb5_key_usage { unsigned usage; struct _krb5_key_data key; }; #ifndef HEIMDAL_SMALLER #define DES3_OLD_ENCTYPE 1 #endif static krb5_error_code _get_derived_key(krb5_context, krb5_crypto, unsigned, struct _krb5_key_data**); static struct _krb5_key_data *_new_derived_key(krb5_crypto crypto, unsigned usage); static void free_key_schedule(krb5_context, struct _krb5_key_data *, struct _krb5_encryption_type *); /* * Converts etype to a user readable string and sets as a side effect * the krb5_error_message containing this string. Returns * KRB5_PROG_ETYPE_NOSUPP in not the conversion of the etype failed in * which case the error code of the etype convesion is returned. */ static krb5_error_code unsupported_enctype(krb5_context context, krb5_enctype etype) { krb5_error_code ret; char *name; ret = krb5_enctype_to_string(context, etype, &name); if (ret) return ret; krb5_set_error_message(context, KRB5_PROG_ETYPE_NOSUPP, N_("Encryption type %s not supported", ""), name); free(name); return KRB5_PROG_ETYPE_NOSUPP; } /* * */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_enctype_keysize(krb5_context context, krb5_enctype type, size_t *keysize) { struct _krb5_encryption_type *et = _krb5_find_enctype(type); if(et == NULL) { return unsupported_enctype (context, type); } *keysize = et->keytype->size; return 0; } KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_enctype_keybits(krb5_context context, krb5_enctype type, size_t *keybits) { struct _krb5_encryption_type *et = _krb5_find_enctype(type); if(et == NULL) { return unsupported_enctype (context, type); } *keybits = et->keytype->bits; return 0; } KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_generate_random_keyblock(krb5_context context, krb5_enctype type, krb5_keyblock *key) { krb5_error_code ret; struct _krb5_encryption_type *et = _krb5_find_enctype(type); if(et == NULL) { return unsupported_enctype (context, type); } ret = krb5_data_alloc(&key->keyvalue, et->keytype->size); if(ret) return ret; key->keytype = type; if(et->keytype->random_key) (*et->keytype->random_key)(context, key); else krb5_generate_random_block(key->keyvalue.data, key->keyvalue.length); return 0; } static krb5_error_code _key_schedule(krb5_context context, struct _krb5_key_data *key) { krb5_error_code ret; struct _krb5_encryption_type *et = _krb5_find_enctype(key->key->keytype); struct _krb5_key_type *kt; if (et == NULL) { return unsupported_enctype (context, key->key->keytype); } kt = et->keytype; if(kt->schedule == NULL) return 0; if (key->schedule != NULL) return 0; ALLOC(key->schedule, 1); if (key->schedule == NULL) return krb5_enomem(context); ret = krb5_data_alloc(key->schedule, kt->schedule_size); if(ret) { free(key->schedule); key->schedule = NULL; return ret; } (*kt->schedule)(context, kt, key); return 0; } /************************************************************ * * ************************************************************/ static krb5_error_code SHA1_checksum(krb5_context context, struct _krb5_key_data *key, const void *data, size_t len, unsigned usage, Checksum *C) { if (EVP_Digest(data, len, C->checksum.data, NULL, EVP_sha1(), NULL) != 1) krb5_abortx(context, "sha1 checksum failed"); return 0; } /* HMAC according to RFC2104 */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL _krb5_internal_hmac(krb5_context context, struct _krb5_checksum_type *cm, const void *data, size_t len, unsigned usage, struct _krb5_key_data *keyblock, Checksum *result) { unsigned char *ipad, *opad; unsigned char *key; size_t key_len; size_t i; ipad = malloc(cm->blocksize + len); if (ipad == NULL) return ENOMEM; opad = malloc(cm->blocksize + cm->checksumsize); if (opad == NULL) { free(ipad); return ENOMEM; } memset(ipad, 0x36, cm->blocksize); memset(opad, 0x5c, cm->blocksize); if(keyblock->key->keyvalue.length > cm->blocksize){ (*cm->checksum)(context, keyblock, keyblock->key->keyvalue.data, keyblock->key->keyvalue.length, usage, result); key = result->checksum.data; key_len = result->checksum.length; } else { key = keyblock->key->keyvalue.data; key_len = keyblock->key->keyvalue.length; } for(i = 0; i < key_len; i++){ ipad[i] ^= key[i]; opad[i] ^= key[i]; } memcpy(ipad + cm->blocksize, data, len); (*cm->checksum)(context, keyblock, ipad, cm->blocksize + len, usage, result); memcpy(opad + cm->blocksize, result->checksum.data, result->checksum.length); (*cm->checksum)(context, keyblock, opad, cm->blocksize + cm->checksumsize, usage, result); memset(ipad, 0, cm->blocksize + len); free(ipad); memset(opad, 0, cm->blocksize + cm->checksumsize); free(opad); return 0; } KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_hmac(krb5_context context, krb5_cksumtype cktype, const void *data, size_t len, unsigned usage, krb5_keyblock *key, Checksum *result) { struct _krb5_checksum_type *c = _krb5_find_checksum(cktype); struct _krb5_key_data kd; krb5_error_code ret; if (c == NULL) { krb5_set_error_message (context, KRB5_PROG_SUMTYPE_NOSUPP, N_("checksum type %d not supported", ""), cktype); return KRB5_PROG_SUMTYPE_NOSUPP; } kd.key = key; kd.schedule = NULL; ret = _krb5_internal_hmac(context, c, data, len, usage, &kd, result); if (kd.schedule) krb5_free_data(context, kd.schedule); return ret; } krb5_error_code _krb5_SP_HMAC_SHA1_checksum(krb5_context context, struct _krb5_key_data *key, const void *data, size_t len, unsigned usage, Checksum *result) { struct _krb5_checksum_type *c = _krb5_find_checksum(CKSUMTYPE_SHA1); Checksum res; char sha1_data[20]; krb5_error_code ret; res.checksum.data = sha1_data; res.checksum.length = sizeof(sha1_data); ret = _krb5_internal_hmac(context, c, data, len, usage, key, &res); if (ret) krb5_abortx(context, "hmac failed"); memcpy(result->checksum.data, res.checksum.data, result->checksum.length); return 0; } struct _krb5_checksum_type _krb5_checksum_sha1 = { CKSUMTYPE_SHA1, "sha1", 64, 20, F_CPROOF, SHA1_checksum, NULL }; KRB5_LIB_FUNCTION struct _krb5_checksum_type * KRB5_LIB_CALL _krb5_find_checksum(krb5_cksumtype type) { int i; for(i = 0; i < _krb5_num_checksums; i++) if(_krb5_checksum_types[i]->type == type) return _krb5_checksum_types[i]; return NULL; } static krb5_error_code get_checksum_key(krb5_context context, krb5_crypto crypto, unsigned usage, /* not krb5_key_usage */ struct _krb5_checksum_type *ct, struct _krb5_key_data **key) { krb5_error_code ret = 0; if(ct->flags & F_DERIVED) ret = _get_derived_key(context, crypto, usage, key); else if(ct->flags & F_VARIANT) { size_t i; *key = _new_derived_key(crypto, 0xff/* KRB5_KU_RFC1510_VARIANT */); if (*key == NULL) return krb5_enomem(context); ret = krb5_copy_keyblock(context, crypto->key.key, &(*key)->key); if(ret) return ret; for(i = 0; i < (*key)->key->keyvalue.length; i++) ((unsigned char*)(*key)->key->keyvalue.data)[i] ^= 0xF0; } else { *key = &crypto->key; } if(ret == 0) ret = _key_schedule(context, *key); return ret; } static krb5_error_code create_checksum (krb5_context context, struct _krb5_checksum_type *ct, krb5_crypto crypto, unsigned usage, void *data, size_t len, Checksum *result) { krb5_error_code ret; struct _krb5_key_data *dkey; int keyed_checksum; if (ct->flags & F_DISABLED) { krb5_clear_error_message (context); return KRB5_PROG_SUMTYPE_NOSUPP; } keyed_checksum = (ct->flags & F_KEYED) != 0; if(keyed_checksum && crypto == NULL) { krb5_set_error_message (context, KRB5_PROG_SUMTYPE_NOSUPP, N_("Checksum type %s is keyed but no " "crypto context (key) was passed in", ""), ct->name); return KRB5_PROG_SUMTYPE_NOSUPP; /* XXX */ } if(keyed_checksum) { ret = get_checksum_key(context, crypto, usage, ct, &dkey); if (ret) return ret; } else dkey = NULL; result->cksumtype = ct->type; ret = krb5_data_alloc(&result->checksum, ct->checksumsize); if (ret) return (ret); return (*ct->checksum)(context, dkey, data, len, usage, result); } static int arcfour_checksum_p(struct _krb5_checksum_type *ct, krb5_crypto crypto) { return (ct->type == CKSUMTYPE_HMAC_MD5) && (crypto->key.key->keytype == KEYTYPE_ARCFOUR); } KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_create_checksum(krb5_context context, krb5_crypto crypto, krb5_key_usage usage, int type, void *data, size_t len, Checksum *result) { struct _krb5_checksum_type *ct = NULL; unsigned keyusage; /* type 0 -> pick from crypto */ if (type) { ct = _krb5_find_checksum(type); } else if (crypto) { ct = crypto->et->keyed_checksum; if (ct == NULL) ct = crypto->et->checksum; } if(ct == NULL) { krb5_set_error_message (context, KRB5_PROG_SUMTYPE_NOSUPP, N_("checksum type %d not supported", ""), type); return KRB5_PROG_SUMTYPE_NOSUPP; } if (arcfour_checksum_p(ct, crypto)) { keyusage = usage; _krb5_usage2arcfour(context, &keyusage); } else keyusage = CHECKSUM_USAGE(usage); return create_checksum(context, ct, crypto, keyusage, data, len, result); } static krb5_error_code verify_checksum(krb5_context context, krb5_crypto crypto, unsigned usage, /* not krb5_key_usage */ void *data, size_t len, Checksum *cksum) { krb5_error_code ret; struct _krb5_key_data *dkey; int keyed_checksum; Checksum c; struct _krb5_checksum_type *ct; ct = _krb5_find_checksum(cksum->cksumtype); if (ct == NULL || (ct->flags & F_DISABLED)) { krb5_set_error_message (context, KRB5_PROG_SUMTYPE_NOSUPP, N_("checksum type %d not supported", ""), cksum->cksumtype); return KRB5_PROG_SUMTYPE_NOSUPP; } if(ct->checksumsize != cksum->checksum.length) { krb5_clear_error_message (context); krb5_set_error_message(context, KRB5KRB_AP_ERR_BAD_INTEGRITY, N_("Decrypt integrity check failed for checksum type %s, " "length was %u, expected %u", ""), ct->name, (unsigned)cksum->checksum.length, (unsigned)ct->checksumsize); return KRB5KRB_AP_ERR_BAD_INTEGRITY; /* XXX */ } keyed_checksum = (ct->flags & F_KEYED) != 0; if(keyed_checksum) { struct _krb5_checksum_type *kct; if (crypto == NULL) { krb5_set_error_message(context, KRB5_PROG_SUMTYPE_NOSUPP, N_("Checksum type %s is keyed but no " "crypto context (key) was passed in", ""), ct->name); return KRB5_PROG_SUMTYPE_NOSUPP; /* XXX */ } kct = crypto->et->keyed_checksum; if (kct == NULL || kct->type != ct->type) { krb5_set_error_message(context, KRB5_PROG_SUMTYPE_NOSUPP, N_("Checksum type %s is keyed, but " "the key type %s passed didnt have that checksum " "type as the keyed type", ""), ct->name, crypto->et->name); return KRB5_PROG_SUMTYPE_NOSUPP; /* XXX */ } ret = get_checksum_key(context, crypto, usage, ct, &dkey); if (ret) return ret; } else dkey = NULL; /* * If checksum have a verify function, lets use that instead of * calling ->checksum and then compare result. */ if(ct->verify) { ret = (*ct->verify)(context, dkey, data, len, usage, cksum); if (ret) krb5_set_error_message(context, ret, N_("Decrypt integrity check failed for checksum " "type %s, key type %s", ""), ct->name, (crypto != NULL)? crypto->et->name : "(none)"); return ret; } ret = krb5_data_alloc (&c.checksum, ct->checksumsize); if (ret) return ret; ret = (*ct->checksum)(context, dkey, data, len, usage, &c); if (ret) { krb5_data_free(&c.checksum); return ret; } if(krb5_data_ct_cmp(&c.checksum, &cksum->checksum) != 0) { ret = KRB5KRB_AP_ERR_BAD_INTEGRITY; krb5_set_error_message(context, ret, N_("Decrypt integrity check failed for checksum " "type %s, key type %s", ""), ct->name, crypto ? crypto->et->name : "(unkeyed)"); } else { ret = 0; } krb5_data_free (&c.checksum); return ret; } KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_verify_checksum(krb5_context context, krb5_crypto crypto, krb5_key_usage usage, void *data, size_t len, Checksum *cksum) { struct _krb5_checksum_type *ct; unsigned keyusage; ct = _krb5_find_checksum(cksum->cksumtype); if(ct == NULL) { krb5_set_error_message (context, KRB5_PROG_SUMTYPE_NOSUPP, N_("checksum type %d not supported", ""), cksum->cksumtype); return KRB5_PROG_SUMTYPE_NOSUPP; } if (arcfour_checksum_p(ct, crypto)) { keyusage = usage; _krb5_usage2arcfour(context, &keyusage); } else keyusage = CHECKSUM_USAGE(usage); return verify_checksum(context, crypto, keyusage, data, len, cksum); } KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_crypto_get_checksum_type(krb5_context context, krb5_crypto crypto, krb5_cksumtype *type) { struct _krb5_checksum_type *ct = NULL; if (crypto != NULL) { ct = crypto->et->keyed_checksum; if (ct == NULL) ct = crypto->et->checksum; } if (ct == NULL) { krb5_set_error_message (context, KRB5_PROG_SUMTYPE_NOSUPP, N_("checksum type not found", "")); return KRB5_PROG_SUMTYPE_NOSUPP; } *type = ct->type; return 0; } KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_checksumsize(krb5_context context, krb5_cksumtype type, size_t *size) { struct _krb5_checksum_type *ct = _krb5_find_checksum(type); if(ct == NULL) { krb5_set_error_message (context, KRB5_PROG_SUMTYPE_NOSUPP, N_("checksum type %d not supported", ""), type); return KRB5_PROG_SUMTYPE_NOSUPP; } *size = ct->checksumsize; return 0; } KRB5_LIB_FUNCTION krb5_boolean KRB5_LIB_CALL krb5_checksum_is_keyed(krb5_context context, krb5_cksumtype type) { struct _krb5_checksum_type *ct = _krb5_find_checksum(type); if(ct == NULL) { if (context) krb5_set_error_message (context, KRB5_PROG_SUMTYPE_NOSUPP, N_("checksum type %d not supported", ""), type); return KRB5_PROG_SUMTYPE_NOSUPP; } return ct->flags & F_KEYED; } KRB5_LIB_FUNCTION krb5_boolean KRB5_LIB_CALL krb5_checksum_is_collision_proof(krb5_context context, krb5_cksumtype type) { struct _krb5_checksum_type *ct = _krb5_find_checksum(type); if(ct == NULL) { if (context) krb5_set_error_message (context, KRB5_PROG_SUMTYPE_NOSUPP, N_("checksum type %d not supported", ""), type); return KRB5_PROG_SUMTYPE_NOSUPP; } return ct->flags & F_CPROOF; } KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_checksum_disable(krb5_context context, krb5_cksumtype type) { struct _krb5_checksum_type *ct = _krb5_find_checksum(type); if(ct == NULL) { if (context) krb5_set_error_message (context, KRB5_PROG_SUMTYPE_NOSUPP, N_("checksum type %d not supported", ""), type); return KRB5_PROG_SUMTYPE_NOSUPP; } ct->flags |= F_DISABLED; return 0; } /************************************************************ * * ************************************************************/ KRB5_LIB_FUNCTION struct _krb5_encryption_type * KRB5_LIB_CALL _krb5_find_enctype(krb5_enctype type) { int i; for(i = 0; i < _krb5_num_etypes; i++) if(_krb5_etypes[i]->type == type) return _krb5_etypes[i]; return NULL; } KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_enctype_to_string(krb5_context context, krb5_enctype etype, char **string) { struct _krb5_encryption_type *e; e = _krb5_find_enctype(etype); if(e == NULL) { krb5_set_error_message (context, KRB5_PROG_ETYPE_NOSUPP, N_("encryption type %d not supported", ""), etype); *string = NULL; return KRB5_PROG_ETYPE_NOSUPP; } *string = strdup(e->name); if (*string == NULL) return krb5_enomem(context); return 0; } KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_string_to_enctype(krb5_context context, const char *string, krb5_enctype *etype) { int i; for(i = 0; i < _krb5_num_etypes; i++) { if(strcasecmp(_krb5_etypes[i]->name, string) == 0){ *etype = _krb5_etypes[i]->type; return 0; } if(_krb5_etypes[i]->alias != NULL && strcasecmp(_krb5_etypes[i]->alias, string) == 0){ *etype = _krb5_etypes[i]->type; return 0; } } krb5_set_error_message (context, KRB5_PROG_ETYPE_NOSUPP, N_("encryption type %s not supported", ""), string); return KRB5_PROG_ETYPE_NOSUPP; } KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_enctype_to_keytype(krb5_context context, krb5_enctype etype, krb5_keytype *keytype) { struct _krb5_encryption_type *e = _krb5_find_enctype(etype); if(e == NULL) { return unsupported_enctype (context, etype); } *keytype = e->keytype->type; /* XXX */ return 0; } /** * Check if a enctype is valid, return 0 if it is. * * @param context Kerberos context * @param etype enctype to check if its valid or not * * @return Return an error code for an failure or 0 on success (enctype valid). * @ingroup krb5_crypto */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_enctype_valid(krb5_context context, krb5_enctype etype) { struct _krb5_encryption_type *e = _krb5_find_enctype(etype); if(e && (e->flags & F_DISABLED) == 0) return 0; if (context == NULL) return KRB5_PROG_ETYPE_NOSUPP; if(e == NULL) { return unsupported_enctype (context, etype); } /* Must be (e->flags & F_DISABLED) */ krb5_set_error_message (context, KRB5_PROG_ETYPE_NOSUPP, N_("encryption type %s is disabled", ""), e->name); return KRB5_PROG_ETYPE_NOSUPP; } /** * Return the coresponding encryption type for a checksum type. * * @param context Kerberos context * @param ctype The checksum type to get the result enctype for * @param etype The returned encryption, when the matching etype is * not found, etype is set to ETYPE_NULL. * * @return Return an error code for an failure or 0 on success. * @ingroup krb5_crypto */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_cksumtype_to_enctype(krb5_context context, krb5_cksumtype ctype, krb5_enctype *etype) { int i; *etype = ETYPE_NULL; for(i = 0; i < _krb5_num_etypes; i++) { if(_krb5_etypes[i]->keyed_checksum && _krb5_etypes[i]->keyed_checksum->type == ctype) { *etype = _krb5_etypes[i]->type; return 0; } } krb5_set_error_message (context, KRB5_PROG_SUMTYPE_NOSUPP, N_("checksum type %d not supported", ""), (int)ctype); return KRB5_PROG_SUMTYPE_NOSUPP; } KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_cksumtype_valid(krb5_context context, krb5_cksumtype ctype) { struct _krb5_checksum_type *c = _krb5_find_checksum(ctype); if (c == NULL) { krb5_set_error_message (context, KRB5_PROG_SUMTYPE_NOSUPP, N_("checksum type %d not supported", ""), ctype); return KRB5_PROG_SUMTYPE_NOSUPP; } if (c->flags & F_DISABLED) { krb5_set_error_message (context, KRB5_PROG_SUMTYPE_NOSUPP, N_("checksum type %s is disabled", ""), c->name); return KRB5_PROG_SUMTYPE_NOSUPP; } return 0; } static krb5_boolean derived_crypto(krb5_context context, krb5_crypto crypto) { return (crypto->et->flags & F_DERIVED) != 0; } #define CHECKSUMSIZE(C) ((C)->checksumsize) #define CHECKSUMTYPE(C) ((C)->type) static krb5_error_code encrypt_internal_derived(krb5_context context, krb5_crypto crypto, unsigned usage, const void *data, size_t len, krb5_data *result, void *ivec) { size_t sz, block_sz, checksum_sz, total_sz; Checksum cksum; unsigned char *p, *q; krb5_error_code ret; struct _krb5_key_data *dkey; const struct _krb5_encryption_type *et = crypto->et; checksum_sz = CHECKSUMSIZE(et->keyed_checksum); sz = et->confoundersize + len; block_sz = (sz + et->padsize - 1) &~ (et->padsize - 1); /* pad */ total_sz = block_sz + checksum_sz; p = calloc(1, total_sz); if (p == NULL) return krb5_enomem(context); q = p; krb5_generate_random_block(q, et->confoundersize); /* XXX */ q += et->confoundersize; memcpy(q, data, len); ret = create_checksum(context, et->keyed_checksum, crypto, INTEGRITY_USAGE(usage), p, block_sz, &cksum); if(ret == 0 && cksum.checksum.length != checksum_sz) { free_Checksum (&cksum); krb5_clear_error_message (context); ret = KRB5_CRYPTO_INTERNAL; } if(ret) goto fail; memcpy(p + block_sz, cksum.checksum.data, cksum.checksum.length); free_Checksum (&cksum); ret = _get_derived_key(context, crypto, ENCRYPTION_USAGE(usage), &dkey); if(ret) goto fail; ret = _key_schedule(context, dkey); if(ret) goto fail; ret = (*et->encrypt)(context, dkey, p, block_sz, 1, usage, ivec); if (ret) goto fail; result->data = p; result->length = total_sz; return 0; fail: memset(p, 0, total_sz); free(p); return ret; } static krb5_error_code encrypt_internal_enc_then_cksum(krb5_context context, krb5_crypto crypto, unsigned usage, const void *data, size_t len, krb5_data *result, void *ivec) { size_t sz, block_sz, checksum_sz, total_sz; Checksum cksum; unsigned char *p, *q, *ivc = NULL; krb5_error_code ret; struct _krb5_key_data *dkey; const struct _krb5_encryption_type *et = crypto->et; checksum_sz = CHECKSUMSIZE(et->keyed_checksum); sz = et->confoundersize + len; block_sz = (sz + et->padsize - 1) &~ (et->padsize - 1); /* pad */ total_sz = block_sz + checksum_sz; p = calloc(1, total_sz); if (p == NULL) return krb5_enomem(context); q = p; krb5_generate_random_block(q, et->confoundersize); /* XXX */ q += et->confoundersize; memcpy(q, data, len); ret = _get_derived_key(context, crypto, ENCRYPTION_USAGE(usage), &dkey); if(ret) goto fail; ret = _key_schedule(context, dkey); if(ret) goto fail; /* XXX EVP style update API would avoid needing to allocate here */ ivc = malloc(et->blocksize + block_sz); if (ivc == NULL) { ret = krb5_enomem(context); goto fail; } if (ivec) memcpy(ivc, ivec, et->blocksize); else memset(ivc, 0, et->blocksize); ret = (*et->encrypt)(context, dkey, p, block_sz, 1, usage, ivec); if (ret) goto fail; memcpy(&ivc[et->blocksize], p, block_sz); ret = create_checksum(context, et->keyed_checksum, crypto, INTEGRITY_USAGE(usage), ivc, et->blocksize + block_sz, &cksum); if(ret == 0 && cksum.checksum.length != checksum_sz) { free_Checksum (&cksum); krb5_clear_error_message (context); ret = KRB5_CRYPTO_INTERNAL; } if(ret) goto fail; memcpy(p + block_sz, cksum.checksum.data, cksum.checksum.length); free_Checksum (&cksum); result->data = p; result->length = total_sz; free(ivc); return 0; fail: memset_s(p, total_sz, 0, total_sz); free(p); free(ivc); return ret; } static krb5_error_code encrypt_internal(krb5_context context, krb5_crypto crypto, const void *data, size_t len, krb5_data *result, void *ivec) { size_t sz, block_sz, checksum_sz; Checksum cksum; unsigned char *p, *q; krb5_error_code ret; const struct _krb5_encryption_type *et = crypto->et; checksum_sz = CHECKSUMSIZE(et->checksum); sz = et->confoundersize + checksum_sz + len; block_sz = (sz + et->padsize - 1) &~ (et->padsize - 1); /* pad */ p = calloc(1, block_sz); if (p == NULL) return krb5_enomem(context); q = p; krb5_generate_random_block(q, et->confoundersize); /* XXX */ q += et->confoundersize; memset(q, 0, checksum_sz); q += checksum_sz; memcpy(q, data, len); ret = create_checksum(context, et->checksum, crypto, 0, p, block_sz, &cksum); if(ret == 0 && cksum.checksum.length != checksum_sz) { krb5_clear_error_message (context); free_Checksum(&cksum); ret = KRB5_CRYPTO_INTERNAL; } if(ret) goto fail; memcpy(p + et->confoundersize, cksum.checksum.data, cksum.checksum.length); free_Checksum(&cksum); ret = _key_schedule(context, &crypto->key); if(ret) goto fail; ret = (*et->encrypt)(context, &crypto->key, p, block_sz, 1, 0, ivec); if (ret) { memset(p, 0, block_sz); free(p); return ret; } result->data = p; result->length = block_sz; return 0; fail: memset(p, 0, block_sz); free(p); return ret; } static krb5_error_code encrypt_internal_special(krb5_context context, krb5_crypto crypto, int usage, const void *data, size_t len, krb5_data *result, void *ivec) { struct _krb5_encryption_type *et = crypto->et; size_t cksum_sz = CHECKSUMSIZE(et->checksum); size_t sz = len + cksum_sz + et->confoundersize; char *tmp, *p; krb5_error_code ret; tmp = malloc (sz); if (tmp == NULL) return krb5_enomem(context); p = tmp; memset (p, 0, cksum_sz); p += cksum_sz; krb5_generate_random_block(p, et->confoundersize); p += et->confoundersize; memcpy (p, data, len); ret = (*et->encrypt)(context, &crypto->key, tmp, sz, TRUE, usage, ivec); if (ret) { memset(tmp, 0, sz); free(tmp); return ret; } result->data = tmp; result->length = sz; return 0; } static krb5_error_code decrypt_internal_derived(krb5_context context, krb5_crypto crypto, unsigned usage, void *data, size_t len, krb5_data *result, void *ivec) { size_t checksum_sz; Checksum cksum; unsigned char *p; krb5_error_code ret; struct _krb5_key_data *dkey; struct _krb5_encryption_type *et = crypto->et; unsigned long l; checksum_sz = CHECKSUMSIZE(et->keyed_checksum); if (len < checksum_sz + et->confoundersize) { krb5_set_error_message(context, KRB5_BAD_MSIZE, N_("Encrypted data shorter then " "checksum + confunder", "")); return KRB5_BAD_MSIZE; } if (((len - checksum_sz) % et->padsize) != 0) { krb5_clear_error_message(context); return KRB5_BAD_MSIZE; } p = malloc(len); if (len != 0 && p == NULL) return krb5_enomem(context); memcpy(p, data, len); len -= checksum_sz; ret = _get_derived_key(context, crypto, ENCRYPTION_USAGE(usage), &dkey); if(ret) { free(p); return ret; } ret = _key_schedule(context, dkey); if(ret) { free(p); return ret; } ret = (*et->encrypt)(context, dkey, p, len, 0, usage, ivec); if (ret) { free(p); return ret; } cksum.checksum.data = p + len; cksum.checksum.length = checksum_sz; cksum.cksumtype = CHECKSUMTYPE(et->keyed_checksum); ret = verify_checksum(context, crypto, INTEGRITY_USAGE(usage), p, len, &cksum); if(ret) { free(p); return ret; } l = len - et->confoundersize; memmove(p, p + et->confoundersize, l); result->data = realloc(p, l); if(result->data == NULL && l != 0) { free(p); return krb5_enomem(context); } result->length = l; return 0; } static krb5_error_code decrypt_internal_enc_then_cksum(krb5_context context, krb5_crypto crypto, unsigned usage, void *data, size_t len, krb5_data *result, void *ivec) { size_t checksum_sz; Checksum cksum; unsigned char *p; krb5_error_code ret; struct _krb5_key_data *dkey; struct _krb5_encryption_type *et = crypto->et; unsigned long l; checksum_sz = CHECKSUMSIZE(et->keyed_checksum); if (len < checksum_sz + et->confoundersize) { krb5_set_error_message(context, KRB5_BAD_MSIZE, N_("Encrypted data shorter then " "checksum + confunder", "")); return KRB5_BAD_MSIZE; } if (((len - checksum_sz) % et->padsize) != 0) { krb5_clear_error_message(context); return KRB5_BAD_MSIZE; } len -= checksum_sz; p = malloc(et->blocksize + len); if (p == NULL) return krb5_enomem(context); if (ivec) memcpy(p, ivec, et->blocksize); else memset(p, 0, et->blocksize); memcpy(&p[et->blocksize], data, len); cksum.checksum.data = (unsigned char *)data + len; cksum.checksum.length = checksum_sz; cksum.cksumtype = CHECKSUMTYPE(et->keyed_checksum); ret = verify_checksum(context, crypto, INTEGRITY_USAGE(usage), p, et->blocksize + len, &cksum); if(ret) { free(p); return ret; } ret = _get_derived_key(context, crypto, ENCRYPTION_USAGE(usage), &dkey); if(ret) { free(p); return ret; } ret = _key_schedule(context, dkey); if(ret) { free(p); return ret; } ret = (*et->encrypt)(context, dkey, &p[et->blocksize], len, 0, usage, ivec); if (ret) { free(p); return ret; } l = len - et->confoundersize; memmove(p, p + et->blocksize + et->confoundersize, l); result->data = realloc(p, l); if(result->data == NULL && l != 0) { free(p); return krb5_enomem(context); } result->length = l; return 0; } static krb5_error_code decrypt_internal(krb5_context context, krb5_crypto crypto, void *data, size_t len, krb5_data *result, void *ivec) { krb5_error_code ret; unsigned char *p; Checksum cksum; size_t checksum_sz, l; struct _krb5_encryption_type *et = crypto->et; if ((len % et->padsize) != 0) { krb5_clear_error_message(context); return KRB5_BAD_MSIZE; } checksum_sz = CHECKSUMSIZE(et->checksum); if (len < checksum_sz + et->confoundersize) { krb5_set_error_message(context, KRB5_BAD_MSIZE, N_("Encrypted data shorter then " "checksum + confunder", "")); return KRB5_BAD_MSIZE; } p = malloc(len); if (len != 0 && p == NULL) return krb5_enomem(context); memcpy(p, data, len); ret = _key_schedule(context, &crypto->key); if(ret) { free(p); return ret; } ret = (*et->encrypt)(context, &crypto->key, p, len, 0, 0, ivec); if (ret) { free(p); return ret; } ret = krb5_data_copy(&cksum.checksum, p + et->confoundersize, checksum_sz); if(ret) { free(p); return ret; } memset(p + et->confoundersize, 0, checksum_sz); cksum.cksumtype = CHECKSUMTYPE(et->checksum); ret = verify_checksum(context, NULL, 0, p, len, &cksum); free_Checksum(&cksum); if(ret) { free(p); return ret; } l = len - et->confoundersize - checksum_sz; memmove(p, p + et->confoundersize + checksum_sz, l); result->data = realloc(p, l); if(result->data == NULL && l != 0) { free(p); return krb5_enomem(context); } result->length = l; return 0; } static krb5_error_code decrypt_internal_special(krb5_context context, krb5_crypto crypto, int usage, void *data, size_t len, krb5_data *result, void *ivec) { struct _krb5_encryption_type *et = crypto->et; size_t cksum_sz = CHECKSUMSIZE(et->checksum); size_t sz = len - cksum_sz - et->confoundersize; unsigned char *p; krb5_error_code ret; if ((len % et->padsize) != 0) { krb5_clear_error_message(context); return KRB5_BAD_MSIZE; } if (len < cksum_sz + et->confoundersize) { krb5_set_error_message(context, KRB5_BAD_MSIZE, N_("Encrypted data shorter then " "checksum + confunder", "")); return KRB5_BAD_MSIZE; } p = malloc (len); if (p == NULL) return krb5_enomem(context); memcpy(p, data, len); ret = (*et->encrypt)(context, &crypto->key, p, len, FALSE, usage, ivec); if (ret) { free(p); return ret; } memmove (p, p + cksum_sz + et->confoundersize, sz); result->data = realloc(p, sz); if(result->data == NULL && sz != 0) { free(p); return krb5_enomem(context); } result->length = sz; return 0; } static krb5_crypto_iov * iov_find(krb5_crypto_iov *data, size_t num_data, unsigned type) { size_t i; for (i = 0; i < num_data; i++) if (data[i].flags == type) return &data[i]; return NULL; } static size_t iov_enc_data_len(krb5_crypto_iov *data, int num_data) { size_t i, len; for (len = 0, i = 0; i < num_data; i++) { if (data[i].flags != KRB5_CRYPTO_TYPE_DATA) continue; len += data[i].data.length; } return len; } static size_t iov_sign_data_len(krb5_crypto_iov *data, int num_data) { size_t i, len; for (len = 0, i = 0; i < num_data; i++) { if (data[i].flags != KRB5_CRYPTO_TYPE_DATA && data[i].flags != KRB5_CRYPTO_TYPE_SIGN_ONLY) continue; len += data[i].data.length; } return len; } static krb5_error_code iov_coalesce(krb5_context context, krb5_data *prefix, krb5_crypto_iov *data, int num_data, krb5_boolean inc_sign_data, krb5_data *out) { unsigned char *p, *q; krb5_crypto_iov *hiv, *piv; size_t len; unsigned int i; hiv = iov_find(data, num_data, KRB5_CRYPTO_TYPE_HEADER); piv = iov_find(data, num_data, KRB5_CRYPTO_TYPE_PADDING); len = 0; if (prefix) len += prefix->length; len += hiv->data.length; if (inc_sign_data) len += iov_sign_data_len(data, num_data); else len += iov_enc_data_len(data, num_data); if (piv) len += piv->data.length; p = q = malloc(len); if (p == NULL) return krb5_enomem(context); if (prefix) { memcpy(q, prefix->data, prefix->length); q += prefix->length; } memcpy(q, hiv->data.data, hiv->data.length); q += hiv->data.length; for (i = 0; i < num_data; i++) { if (data[i].flags == KRB5_CRYPTO_TYPE_DATA || (inc_sign_data && data[i].flags == KRB5_CRYPTO_TYPE_SIGN_ONLY)) { memcpy(q, data[i].data.data, data[i].data.length); q += data[i].data.length; } } if (piv) memset(q, 0, piv->data.length); out->length = len; out->data = p; return 0; } static krb5_error_code iov_uncoalesce(krb5_context context, krb5_data *enc_data, krb5_crypto_iov *data, int num_data) { unsigned char *q = enc_data->data; krb5_crypto_iov *hiv, *piv; unsigned int i; hiv = iov_find(data, num_data, KRB5_CRYPTO_TYPE_HEADER); piv = iov_find(data, num_data, KRB5_CRYPTO_TYPE_PADDING); memcpy(hiv->data.data, q, hiv->data.length); q += hiv->data.length; for (i = 0; i < num_data; i++) { if (data[i].flags != KRB5_CRYPTO_TYPE_DATA) continue; memcpy(data[i].data.data, q, data[i].data.length); q += data[i].data.length; } if (piv) memcpy(piv->data.data, q, piv->data.length); return 0; } static krb5_error_code iov_pad_validate(const struct _krb5_encryption_type *et, krb5_crypto_iov *data, int num_data, krb5_crypto_iov **ppiv) { krb5_crypto_iov *piv; size_t sz, headersz, block_sz, pad_sz, len; len = iov_enc_data_len(data, num_data); headersz = et->confoundersize; sz = headersz + len; block_sz = (sz + et->padsize - 1) &~ (et->padsize - 1); /* pad */ pad_sz = block_sz - sz; piv = iov_find(data, num_data, KRB5_CRYPTO_TYPE_PADDING); /* its ok to have no TYPE_PADDING if there is no padding */ if (piv == NULL && pad_sz != 0) return KRB5_BAD_MSIZE; if (piv) { if (piv->data.length < pad_sz) return KRB5_BAD_MSIZE; piv->data.length = pad_sz; if (pad_sz) memset(piv->data.data, pad_sz, pad_sz); else piv = NULL; } *ppiv = piv; return 0; } /** * Inline encrypt a kerberos message * * @param context Kerberos context * @param crypto Kerberos crypto context * @param usage Key usage for this buffer * @param data array of buffers to process * @param num_data length of array * @param ivec initial cbc/cts vector * * @return Return an error code or 0. * @ingroup krb5_crypto * * Kerberos encrypted data look like this: * * 1. KRB5_CRYPTO_TYPE_HEADER * 2. array [1,...] KRB5_CRYPTO_TYPE_DATA and array [0,...] * KRB5_CRYPTO_TYPE_SIGN_ONLY in any order, however the receiver * have to aware of the order. KRB5_CRYPTO_TYPE_SIGN_ONLY is * commonly used headers and trailers. * 3. KRB5_CRYPTO_TYPE_PADDING, at least on padsize long if padsize > 1 * 4. KRB5_CRYPTO_TYPE_TRAILER */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_encrypt_iov_ivec(krb5_context context, krb5_crypto crypto, unsigned usage, krb5_crypto_iov *data, int num_data, void *ivec) { size_t headersz, trailersz; Checksum cksum; krb5_data enc_data, sign_data; krb5_error_code ret; struct _krb5_key_data *dkey; const struct _krb5_encryption_type *et = crypto->et; krb5_crypto_iov *tiv, *piv, *hiv; if (num_data < 0) { krb5_clear_error_message(context); return KRB5_CRYPTO_INTERNAL; } if(!derived_crypto(context, crypto)) { krb5_clear_error_message(context); return KRB5_CRYPTO_INTERNAL; } krb5_data_zero(&enc_data); krb5_data_zero(&sign_data); headersz = et->confoundersize; trailersz = CHECKSUMSIZE(et->keyed_checksum); /* header */ hiv = iov_find(data, num_data, KRB5_CRYPTO_TYPE_HEADER); if (hiv == NULL || hiv->data.length != headersz) return KRB5_BAD_MSIZE; krb5_generate_random_block(hiv->data.data, hiv->data.length); /* padding */ ret = iov_pad_validate(et, data, num_data, &piv); if(ret) goto cleanup; /* trailer */ tiv = iov_find(data, num_data, KRB5_CRYPTO_TYPE_TRAILER); if (tiv == NULL || tiv->data.length != trailersz) { ret = KRB5_BAD_MSIZE; goto cleanup; } if (et->flags & F_ENC_THEN_CKSUM) { unsigned char old_ivec[EVP_MAX_IV_LENGTH]; krb5_data ivec_data; ret = iov_coalesce(context, NULL, data, num_data, FALSE, &enc_data); if(ret) goto cleanup; ret = _get_derived_key(context, crypto, ENCRYPTION_USAGE(usage), &dkey); if(ret) goto cleanup; ret = _key_schedule(context, dkey); if(ret) goto cleanup; heim_assert(et->blocksize <= sizeof(old_ivec), "blocksize too big for ivec buffer"); if (ivec) memcpy(old_ivec, ivec, et->blocksize); else memset(old_ivec, 0, et->blocksize); ret = (*et->encrypt)(context, dkey, enc_data.data, enc_data.length, 1, usage, ivec); if(ret) goto cleanup; ret = iov_uncoalesce(context, &enc_data, data, num_data); if(ret) goto cleanup; ivec_data.length = et->blocksize; ivec_data.data = old_ivec; ret = iov_coalesce(context, &ivec_data, data, num_data, TRUE, &sign_data); if(ret) goto cleanup; } else { ret = iov_coalesce(context, NULL, data, num_data, TRUE, &sign_data); if(ret) goto cleanup; } ret = create_checksum(context, et->keyed_checksum, crypto, INTEGRITY_USAGE(usage), sign_data.data, sign_data.length, &cksum); if(ret == 0 && cksum.checksum.length != trailersz) { free_Checksum (&cksum); krb5_clear_error_message (context); ret = KRB5_CRYPTO_INTERNAL; } if(ret) goto cleanup; /* save cksum at end */ memcpy(tiv->data.data, cksum.checksum.data, cksum.checksum.length); free_Checksum (&cksum); if (!(et->flags & F_ENC_THEN_CKSUM)) { ret = iov_coalesce(context, NULL, data, num_data, FALSE, &enc_data); if(ret) goto cleanup; ret = _get_derived_key(context, crypto, ENCRYPTION_USAGE(usage), &dkey); if(ret) goto cleanup; ret = _key_schedule(context, dkey); if(ret) goto cleanup; ret = (*et->encrypt)(context, dkey, enc_data.data, enc_data.length, 1, usage, ivec); if(ret) goto cleanup; ret = iov_uncoalesce(context, &enc_data, data, num_data); if(ret) goto cleanup; } cleanup: if (enc_data.data) { memset_s(enc_data.data, enc_data.length, 0, enc_data.length); krb5_data_free(&enc_data); } if (sign_data.data) { memset_s(sign_data.data, sign_data.length, 0, sign_data.length); krb5_data_free(&sign_data); } return ret; } /** * Inline decrypt a Kerberos message. * * @param context Kerberos context * @param crypto Kerberos crypto context * @param usage Key usage for this buffer * @param data array of buffers to process * @param num_data length of array * @param ivec initial cbc/cts vector * * @return Return an error code or 0. * @ingroup krb5_crypto * * 1. KRB5_CRYPTO_TYPE_HEADER * 2. one KRB5_CRYPTO_TYPE_DATA and array [0,...] of KRB5_CRYPTO_TYPE_SIGN_ONLY in * any order, however the receiver have to aware of the * order. KRB5_CRYPTO_TYPE_SIGN_ONLY is commonly used unencrypoted * protocol headers and trailers. The output data will be of same * size as the input data or shorter. */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_decrypt_iov_ivec(krb5_context context, krb5_crypto crypto, unsigned usage, krb5_crypto_iov *data, unsigned int num_data, void *ivec) { Checksum cksum; krb5_data enc_data, sign_data; krb5_error_code ret; struct _krb5_key_data *dkey; struct _krb5_encryption_type *et = crypto->et; krb5_crypto_iov *tiv, *hiv; if(!derived_crypto(context, crypto)) { krb5_clear_error_message(context); return KRB5_CRYPTO_INTERNAL; } /* header */ hiv = iov_find(data, num_data, KRB5_CRYPTO_TYPE_HEADER); if (hiv == NULL || hiv->data.length != et->confoundersize) return KRB5_BAD_MSIZE; /* trailer */ tiv = iov_find(data, num_data, KRB5_CRYPTO_TYPE_TRAILER); if (tiv->data.length != CHECKSUMSIZE(et->keyed_checksum)) return KRB5_BAD_MSIZE; /* padding */ if ((iov_enc_data_len(data, num_data) % et->padsize) != 0) { krb5_clear_error_message(context); return KRB5_BAD_MSIZE; } krb5_data_zero(&enc_data); krb5_data_zero(&sign_data); if (!(et->flags & F_ENC_THEN_CKSUM)) { ret = iov_coalesce(context, NULL, data, num_data, FALSE, &enc_data); if(ret) goto cleanup; ret = _get_derived_key(context, crypto, ENCRYPTION_USAGE(usage), &dkey); if(ret) goto cleanup; ret = _key_schedule(context, dkey); if(ret) goto cleanup; ret = (*et->encrypt)(context, dkey, enc_data.data, enc_data.length, 0, usage, ivec); if(ret) goto cleanup; ret = iov_uncoalesce(context, &enc_data, data, num_data); if(ret) goto cleanup; ret = iov_coalesce(context, NULL, data, num_data, TRUE, &sign_data); if(ret) goto cleanup; } else { krb5_data ivec_data; static unsigned char zero_ivec[EVP_MAX_IV_LENGTH]; heim_assert(et->blocksize <= sizeof(zero_ivec), "blocksize too big for ivec buffer"); ivec_data.length = et->blocksize; ivec_data.data = ivec ? ivec : zero_ivec; ret = iov_coalesce(context, &ivec_data, data, num_data, TRUE, &sign_data); if(ret) goto cleanup; } cksum.checksum.data = tiv->data.data; cksum.checksum.length = tiv->data.length; cksum.cksumtype = CHECKSUMTYPE(et->keyed_checksum); ret = verify_checksum(context, crypto, INTEGRITY_USAGE(usage), sign_data.data, sign_data.length, &cksum); if(ret) goto cleanup; if (et->flags & F_ENC_THEN_CKSUM) { ret = iov_coalesce(context, NULL, data, num_data, FALSE, &enc_data); if(ret) goto cleanup; ret = _get_derived_key(context, crypto, ENCRYPTION_USAGE(usage), &dkey); if(ret) goto cleanup; ret = _key_schedule(context, dkey); if(ret) goto cleanup; ret = (*et->encrypt)(context, dkey, enc_data.data, enc_data.length, 0, usage, ivec); if(ret) goto cleanup; ret = iov_uncoalesce(context, &enc_data, data, num_data); if(ret) goto cleanup; } cleanup: if (enc_data.data) { memset_s(enc_data.data, enc_data.length, 0, enc_data.length); krb5_data_free(&enc_data); } if (sign_data.data) { memset_s(sign_data.data, sign_data.length, 0, sign_data.length); krb5_data_free(&sign_data); } return ret; } /** * Create a Kerberos message checksum. * * @param context Kerberos context * @param crypto Kerberos crypto context * @param usage Key usage for this buffer * @param data array of buffers to process * @param num_data length of array * @param type output data * * @return Return an error code or 0. * @ingroup krb5_crypto */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_create_checksum_iov(krb5_context context, krb5_crypto crypto, unsigned usage, krb5_crypto_iov *data, unsigned int num_data, krb5_cksumtype *type) { Checksum cksum; krb5_crypto_iov *civ; krb5_error_code ret; size_t i; size_t len; char *p, *q; if(!derived_crypto(context, crypto)) { krb5_clear_error_message(context); return KRB5_CRYPTO_INTERNAL; } civ = iov_find(data, num_data, KRB5_CRYPTO_TYPE_CHECKSUM); if (civ == NULL) return KRB5_BAD_MSIZE; len = 0; for (i = 0; i < num_data; i++) { if (data[i].flags != KRB5_CRYPTO_TYPE_DATA && data[i].flags != KRB5_CRYPTO_TYPE_SIGN_ONLY) continue; len += data[i].data.length; } p = q = malloc(len); for (i = 0; i < num_data; i++) { if (data[i].flags != KRB5_CRYPTO_TYPE_DATA && data[i].flags != KRB5_CRYPTO_TYPE_SIGN_ONLY) continue; memcpy(q, data[i].data.data, data[i].data.length); q += data[i].data.length; } ret = krb5_create_checksum(context, crypto, usage, 0, p, len, &cksum); free(p); if (ret) return ret; if (type) *type = cksum.cksumtype; if (cksum.checksum.length > civ->data.length) { krb5_set_error_message(context, KRB5_BAD_MSIZE, N_("Checksum larger then input buffer", "")); free_Checksum(&cksum); return KRB5_BAD_MSIZE; } civ->data.length = cksum.checksum.length; memcpy(civ->data.data, cksum.checksum.data, civ->data.length); free_Checksum(&cksum); return 0; } /** * Verify a Kerberos message checksum. * * @param context Kerberos context * @param crypto Kerberos crypto context * @param usage Key usage for this buffer * @param data array of buffers to process * @param num_data length of array * @param type return checksum type if not NULL * * @return Return an error code or 0. * @ingroup krb5_crypto */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_verify_checksum_iov(krb5_context context, krb5_crypto crypto, unsigned usage, krb5_crypto_iov *data, unsigned int num_data, krb5_cksumtype *type) { struct _krb5_encryption_type *et = crypto->et; Checksum cksum; krb5_crypto_iov *civ; krb5_error_code ret; size_t i; size_t len; char *p, *q; if(!derived_crypto(context, crypto)) { krb5_clear_error_message(context); return KRB5_CRYPTO_INTERNAL; } civ = iov_find(data, num_data, KRB5_CRYPTO_TYPE_CHECKSUM); if (civ == NULL) return KRB5_BAD_MSIZE; len = 0; for (i = 0; i < num_data; i++) { if (data[i].flags != KRB5_CRYPTO_TYPE_DATA && data[i].flags != KRB5_CRYPTO_TYPE_SIGN_ONLY) continue; len += data[i].data.length; } p = q = malloc(len); for (i = 0; i < num_data; i++) { if (data[i].flags != KRB5_CRYPTO_TYPE_DATA && data[i].flags != KRB5_CRYPTO_TYPE_SIGN_ONLY) continue; memcpy(q, data[i].data.data, data[i].data.length); q += data[i].data.length; } cksum.cksumtype = CHECKSUMTYPE(et->keyed_checksum); cksum.checksum.length = civ->data.length; cksum.checksum.data = civ->data.data; ret = krb5_verify_checksum(context, crypto, usage, p, len, &cksum); free(p); if (ret == 0 && type) *type = cksum.cksumtype; return ret; } KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_crypto_length(krb5_context context, krb5_crypto crypto, int type, size_t *len) { if (!derived_crypto(context, crypto)) { krb5_set_error_message(context, EINVAL, "not a derived crypto"); return EINVAL; } switch(type) { case KRB5_CRYPTO_TYPE_EMPTY: *len = 0; return 0; case KRB5_CRYPTO_TYPE_HEADER: *len = crypto->et->blocksize; return 0; case KRB5_CRYPTO_TYPE_DATA: case KRB5_CRYPTO_TYPE_SIGN_ONLY: /* len must already been filled in */ return 0; case KRB5_CRYPTO_TYPE_PADDING: if (crypto->et->padsize > 1) *len = crypto->et->padsize; else *len = 0; return 0; case KRB5_CRYPTO_TYPE_TRAILER: *len = CHECKSUMSIZE(crypto->et->keyed_checksum); return 0; case KRB5_CRYPTO_TYPE_CHECKSUM: if (crypto->et->keyed_checksum) *len = CHECKSUMSIZE(crypto->et->keyed_checksum); else *len = CHECKSUMSIZE(crypto->et->checksum); return 0; } krb5_set_error_message(context, EINVAL, "%d not a supported type", type); return EINVAL; } KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_crypto_length_iov(krb5_context context, krb5_crypto crypto, krb5_crypto_iov *data, unsigned int num_data) { krb5_error_code ret; size_t i; for (i = 0; i < num_data; i++) { ret = krb5_crypto_length(context, crypto, data[i].flags, &data[i].data.length); if (ret) return ret; } return 0; } KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_encrypt_ivec(krb5_context context, krb5_crypto crypto, unsigned usage, const void *data, size_t len, krb5_data *result, void *ivec) { krb5_error_code ret; switch (crypto->et->flags & F_CRYPTO_MASK) { case F_RFC3961_ENC: ret = encrypt_internal_derived(context, crypto, usage, data, len, result, ivec); break; case F_SPECIAL: ret = encrypt_internal_special (context, crypto, usage, data, len, result, ivec); break; case F_ENC_THEN_CKSUM: ret = encrypt_internal_enc_then_cksum(context, crypto, usage, data, len, result, ivec); break; default: ret = encrypt_internal(context, crypto, data, len, result, ivec); break; } return ret; } KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_encrypt(krb5_context context, krb5_crypto crypto, unsigned usage, const void *data, size_t len, krb5_data *result) { return krb5_encrypt_ivec(context, crypto, usage, data, len, result, NULL); } KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_encrypt_EncryptedData(krb5_context context, krb5_crypto crypto, unsigned usage, void *data, size_t len, int kvno, EncryptedData *result) { result->etype = CRYPTO_ETYPE(crypto); if(kvno){ ALLOC(result->kvno, 1); *result->kvno = kvno; }else result->kvno = NULL; return krb5_encrypt(context, crypto, usage, data, len, &result->cipher); } KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_decrypt_ivec(krb5_context context, krb5_crypto crypto, unsigned usage, void *data, size_t len, krb5_data *result, void *ivec) { krb5_error_code ret; switch (crypto->et->flags & F_CRYPTO_MASK) { case F_RFC3961_ENC: ret = decrypt_internal_derived(context, crypto, usage, data, len, result, ivec); break; case F_SPECIAL: ret = decrypt_internal_special(context, crypto, usage, data, len, result, ivec); break; case F_ENC_THEN_CKSUM: ret = decrypt_internal_enc_then_cksum(context, crypto, usage, data, len, result, ivec); break; default: ret = decrypt_internal(context, crypto, data, len, result, ivec); break; } return ret; } KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_decrypt(krb5_context context, krb5_crypto crypto, unsigned usage, void *data, size_t len, krb5_data *result) { return krb5_decrypt_ivec (context, crypto, usage, data, len, result, NULL); } KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_decrypt_EncryptedData(krb5_context context, krb5_crypto crypto, unsigned usage, const EncryptedData *e, krb5_data *result) { return krb5_decrypt(context, crypto, usage, e->cipher.data, e->cipher.length, result); } /************************************************************ * * ************************************************************/ static krb5_error_code derive_key_rfc3961(krb5_context context, struct _krb5_encryption_type *et, struct _krb5_key_data *key, const void *constant, size_t len) { unsigned char *k = NULL; unsigned int nblocks = 0, i; krb5_error_code ret = 0; struct _krb5_key_type *kt = et->keytype; if(et->blocksize * 8 < kt->bits || len != et->blocksize) { nblocks = (kt->bits + et->blocksize * 8 - 1) / (et->blocksize * 8); k = malloc(nblocks * et->blocksize); if(k == NULL) { ret = krb5_enomem(context); goto out; } ret = _krb5_n_fold(constant, len, k, et->blocksize); if (ret) { krb5_enomem(context); goto out; } for(i = 0; i < nblocks; i++) { if(i > 0) memcpy(k + i * et->blocksize, k + (i - 1) * et->blocksize, et->blocksize); (*et->encrypt)(context, key, k + i * et->blocksize, et->blocksize, 1, 0, NULL); } } else { /* this case is probably broken, but won't be run anyway */ void *c = malloc(len); size_t res_len = (kt->bits + 7) / 8; if(len != 0 && c == NULL) { ret = krb5_enomem(context); goto out; } memcpy(c, constant, len); (*et->encrypt)(context, key, c, len, 1, 0, NULL); k = malloc(res_len); if(res_len != 0 && k == NULL) { free(c); ret = krb5_enomem(context); goto out; } ret = _krb5_n_fold(c, len, k, res_len); free(c); if (ret) { krb5_enomem(context); goto out; } } if (kt->type == KRB5_ENCTYPE_OLD_DES3_CBC_SHA1) _krb5_DES3_random_to_key(context, key->key, k, nblocks * et->blocksize); else memcpy(key->key->keyvalue.data, k, key->key->keyvalue.length); out: if (k) { memset_s(k, nblocks * et->blocksize, 0, nblocks * et->blocksize); free(k); } return ret; } static krb5_error_code derive_key_sp800_hmac(krb5_context context, struct _krb5_encryption_type *et, struct _krb5_key_data *key, const void *constant, size_t len) { krb5_error_code ret; struct _krb5_key_type *kt = et->keytype; krb5_data label; const EVP_MD *md = NULL; const unsigned char *c = constant; size_t key_len; krb5_data K1; ret = _krb5_aes_sha2_md_for_enctype(context, kt->type, &md); if (ret) return ret; /* * PRF usage: not handled here (output cannot be longer) * Integrity usage: truncated hash (half length) * Encryption usage: base key length */ if (len == 5 && (c[4] == 0x99 || c[4] == 0x55)) key_len = EVP_MD_size(md) / 2; else key_len = kt->size; ret = krb5_data_alloc(&K1, key_len); if (ret) return ret; label.data = (void *)constant; label.length = len; ret = _krb5_SP800_108_HMAC_KDF(context, &key->key->keyvalue, &label, NULL, md, &K1); if (ret == 0) { if (key->key->keyvalue.length > key_len) key->key->keyvalue.length = key_len; memcpy(key->key->keyvalue.data, K1.data, key_len); } memset_s(K1.data, K1.length, 0, K1.length); krb5_data_free(&K1); return ret; } KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL _krb5_derive_key(krb5_context context, struct _krb5_encryption_type *et, struct _krb5_key_data *key, const void *constant, size_t len) { krb5_error_code ret; ret = _key_schedule(context, key); if(ret) return ret; switch (et->flags & F_KDF_MASK) { case F_RFC3961_KDF: ret = derive_key_rfc3961(context, et, key, constant, len); break; case F_SP800_108_HMAC_KDF: ret = derive_key_sp800_hmac(context, et, key, constant, len); break; default: ret = KRB5_CRYPTO_INTERNAL; krb5_set_error_message(context, ret, N_("derive_key() called with unknown keytype (%u)", ""), et->keytype->type); break; } if (key->schedule) { free_key_schedule(context, key, et); key->schedule = NULL; } return ret; } static struct _krb5_key_data * _new_derived_key(krb5_crypto crypto, unsigned usage) { struct _krb5_key_usage *d = crypto->key_usage; d = realloc(d, (crypto->num_key_usage + 1) * sizeof(*d)); if(d == NULL) return NULL; crypto->key_usage = d; d += crypto->num_key_usage++; memset(d, 0, sizeof(*d)); d->usage = usage; return &d->key; } KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_derive_key(krb5_context context, const krb5_keyblock *key, krb5_enctype etype, const void *constant, size_t constant_len, krb5_keyblock **derived_key) { krb5_error_code ret; struct _krb5_encryption_type *et; struct _krb5_key_data d; *derived_key = NULL; et = _krb5_find_enctype (etype); if (et == NULL) { return unsupported_enctype (context, etype); } ret = krb5_copy_keyblock(context, key, &d.key); if (ret) return ret; d.schedule = NULL; ret = _krb5_derive_key(context, et, &d, constant, constant_len); if (ret == 0) ret = krb5_copy_keyblock(context, d.key, derived_key); _krb5_free_key_data(context, &d, et); return ret; } static krb5_error_code _get_derived_key(krb5_context context, krb5_crypto crypto, unsigned usage, struct _krb5_key_data **key) { int i; struct _krb5_key_data *d; unsigned char constant[5]; *key = NULL; for(i = 0; i < crypto->num_key_usage; i++) if(crypto->key_usage[i].usage == usage) { *key = &crypto->key_usage[i].key; return 0; } d = _new_derived_key(crypto, usage); if (d == NULL) return krb5_enomem(context); *key = d; krb5_copy_keyblock(context, crypto->key.key, &d->key); _krb5_put_int(constant, usage, sizeof(constant)); return _krb5_derive_key(context, crypto->et, d, constant, sizeof(constant)); } /** * Create a crypto context used for all encryption and signature * operation. The encryption type to use is taken from the key, but * can be overridden with the enctype parameter. This can be useful * for encryptions types which is compatiable (DES for example). * * To free the crypto context, use krb5_crypto_destroy(). * * @param context Kerberos context * @param key the key block information with all key data * @param etype the encryption type * @param crypto the resulting crypto context * * @return Return an error code or 0. * * @ingroup krb5_crypto */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_crypto_init(krb5_context context, const krb5_keyblock *key, krb5_enctype etype, krb5_crypto *crypto) { krb5_error_code ret; ALLOC(*crypto, 1); if (*crypto == NULL) return krb5_enomem(context); if(etype == (krb5_enctype)ETYPE_NULL) etype = key->keytype; (*crypto)->et = _krb5_find_enctype(etype); if((*crypto)->et == NULL || ((*crypto)->et->flags & F_DISABLED)) { free(*crypto); *crypto = NULL; return unsupported_enctype(context, etype); } if((*crypto)->et->keytype->size != key->keyvalue.length) { free(*crypto); *crypto = NULL; krb5_set_error_message (context, KRB5_BAD_KEYSIZE, "encryption key has bad length"); return KRB5_BAD_KEYSIZE; } ret = krb5_copy_keyblock(context, key, &(*crypto)->key.key); if(ret) { free(*crypto); *crypto = NULL; return ret; } (*crypto)->key.schedule = NULL; (*crypto)->num_key_usage = 0; (*crypto)->key_usage = NULL; return 0; } static void free_key_schedule(krb5_context context, struct _krb5_key_data *key, struct _krb5_encryption_type *et) { if (et->keytype->cleanup) (*et->keytype->cleanup)(context, key); memset(key->schedule->data, 0, key->schedule->length); krb5_free_data(context, key->schedule); } KRB5_LIB_FUNCTION void KRB5_LIB_CALL _krb5_free_key_data(krb5_context context, struct _krb5_key_data *key, struct _krb5_encryption_type *et) { krb5_free_keyblock(context, key->key); if(key->schedule) { free_key_schedule(context, key, et); key->schedule = NULL; } } static void free_key_usage(krb5_context context, struct _krb5_key_usage *ku, struct _krb5_encryption_type *et) { _krb5_free_key_data(context, &ku->key, et); } /** * Free a crypto context created by krb5_crypto_init(). * * @param context Kerberos context * @param crypto crypto context to free * * @return Return an error code or 0. * * @ingroup krb5_crypto */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_crypto_destroy(krb5_context context, krb5_crypto crypto) { int i; for(i = 0; i < crypto->num_key_usage; i++) free_key_usage(context, &crypto->key_usage[i], crypto->et); free(crypto->key_usage); _krb5_free_key_data(context, &crypto->key, crypto->et); free (crypto); return 0; } /** * Return the blocksize used algorithm referenced by the crypto context * * @param context Kerberos context * @param crypto crypto context to query * @param blocksize the resulting blocksize * * @return Return an error code or 0. * * @ingroup krb5_crypto */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_crypto_getblocksize(krb5_context context, krb5_crypto crypto, size_t *blocksize) { *blocksize = crypto->et->blocksize; return 0; } /** * Return the encryption type used by the crypto context * * @param context Kerberos context * @param crypto crypto context to query * @param enctype the resulting encryption type * * @return Return an error code or 0. * * @ingroup krb5_crypto */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_crypto_getenctype(krb5_context context, krb5_crypto crypto, krb5_enctype *enctype) { *enctype = crypto->et->type; return 0; } /** * Return the padding size used by the crypto context * * @param context Kerberos context * @param crypto crypto context to query * @param padsize the return padding size * * @return Return an error code or 0. * * @ingroup krb5_crypto */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_crypto_getpadsize(krb5_context context, krb5_crypto crypto, size_t *padsize) { *padsize = crypto->et->padsize; return 0; } /** * Return the confounder size used by the crypto context * * @param context Kerberos context * @param crypto crypto context to query * @param confoundersize the returned confounder size * * @return Return an error code or 0. * * @ingroup krb5_crypto */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_crypto_getconfoundersize(krb5_context context, krb5_crypto crypto, size_t *confoundersize) { *confoundersize = crypto->et->confoundersize; return 0; } /** * Disable encryption type * * @param context Kerberos 5 context * @param enctype encryption type to disable * * @return Return an error code or 0. * * @ingroup krb5_crypto */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_enctype_disable(krb5_context context, krb5_enctype enctype) { struct _krb5_encryption_type *et = _krb5_find_enctype(enctype); if(et == NULL) { if (context) krb5_set_error_message (context, KRB5_PROG_ETYPE_NOSUPP, N_("encryption type %d not supported", ""), enctype); return KRB5_PROG_ETYPE_NOSUPP; } et->flags |= F_DISABLED; return 0; } /** * Enable encryption type * * @param context Kerberos 5 context * @param enctype encryption type to enable * * @return Return an error code or 0. * * @ingroup krb5_crypto */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_enctype_enable(krb5_context context, krb5_enctype enctype) { struct _krb5_encryption_type *et = _krb5_find_enctype(enctype); if(et == NULL) { if (context) krb5_set_error_message (context, KRB5_PROG_ETYPE_NOSUPP, N_("encryption type %d not supported", ""), enctype); return KRB5_PROG_ETYPE_NOSUPP; } et->flags &= ~F_DISABLED; return 0; } /** * Enable or disable all weak encryption types * * @param context Kerberos 5 context * @param enable true to enable, false to disable * * @return Return an error code or 0. * * @ingroup krb5_crypto */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_allow_weak_crypto(krb5_context context, krb5_boolean enable) { int i; for(i = 0; i < _krb5_num_etypes; i++) if(_krb5_etypes[i]->flags & F_WEAK) { if(enable) _krb5_etypes[i]->flags &= ~F_DISABLED; else _krb5_etypes[i]->flags |= F_DISABLED; } return 0; } /** * Returns is the encryption is strong or weak * * @param context Kerberos 5 context * @param enctype encryption type to probe * * @return Returns true if encryption type is weak or is not supported. * * @ingroup krb5_crypto */ KRB5_LIB_FUNCTION krb5_boolean KRB5_LIB_CALL krb5_is_enctype_weak(krb5_context context, krb5_enctype enctype) { struct _krb5_encryption_type *et = _krb5_find_enctype(enctype); if(et == NULL || (et->flags & F_WEAK)) return TRUE; return FALSE; } /** * Returns whether the encryption type should use randomly generated salts * * @param context Kerberos 5 context * @param enctype encryption type to probe * * @return Returns true if generated salts should have random component * * @ingroup krb5_crypto */ KRB5_LIB_FUNCTION krb5_boolean KRB5_LIB_CALL _krb5_enctype_requires_random_salt(krb5_context context, krb5_enctype enctype) { struct _krb5_encryption_type *et; et = _krb5_find_enctype (enctype); return et && (et->flags & F_SP800_108_HMAC_KDF); } static size_t wrapped_length (krb5_context context, krb5_crypto crypto, size_t data_len) { struct _krb5_encryption_type *et = crypto->et; size_t padsize = et->padsize; size_t checksumsize = CHECKSUMSIZE(et->checksum); size_t res; res = et->confoundersize + checksumsize + data_len; res = (res + padsize - 1) / padsize * padsize; return res; } static size_t wrapped_length_dervied (krb5_context context, krb5_crypto crypto, size_t data_len) { struct _krb5_encryption_type *et = crypto->et; size_t padsize = et->padsize; size_t res; res = et->confoundersize + data_len; res = (res + padsize - 1) / padsize * padsize; if (et->keyed_checksum) res += et->keyed_checksum->checksumsize; else res += et->checksum->checksumsize; return res; } /* * Return the size of an encrypted packet of length `data_len' */ KRB5_LIB_FUNCTION size_t KRB5_LIB_CALL krb5_get_wrapped_length (krb5_context context, krb5_crypto crypto, size_t data_len) { if (derived_crypto (context, crypto)) return wrapped_length_dervied (context, crypto, data_len); else return wrapped_length (context, crypto, data_len); } /* * Return the size of an encrypted packet of length `data_len' */ static size_t crypto_overhead (krb5_context context, krb5_crypto crypto) { struct _krb5_encryption_type *et = crypto->et; size_t res; res = CHECKSUMSIZE(et->checksum); res += et->confoundersize; if (et->padsize > 1) res += et->padsize; return res; } static size_t crypto_overhead_dervied (krb5_context context, krb5_crypto crypto) { struct _krb5_encryption_type *et = crypto->et; size_t res; if (et->keyed_checksum) res = CHECKSUMSIZE(et->keyed_checksum); else res = CHECKSUMSIZE(et->checksum); res += et->confoundersize; if (et->padsize > 1) res += et->padsize; return res; } KRB5_LIB_FUNCTION size_t KRB5_LIB_CALL krb5_crypto_overhead (krb5_context context, krb5_crypto crypto) { if (derived_crypto (context, crypto)) return crypto_overhead_dervied (context, crypto); else return crypto_overhead (context, crypto); } /** * Converts the random bytestring to a protocol key according to * Kerberos crypto frame work. It may be assumed that all the bits of * the input string are equally random, even though the entropy * present in the random source may be limited. * * @param context Kerberos 5 context * @param type the enctype resulting key will be of * @param data input random data to convert to a key * @param size size of input random data, at least krb5_enctype_keysize() long * @param key key, output key, free with krb5_free_keyblock_contents() * * @return Return an error code or 0. * * @ingroup krb5_crypto */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_random_to_key(krb5_context context, krb5_enctype type, const void *data, size_t size, krb5_keyblock *key) { krb5_error_code ret; struct _krb5_encryption_type *et = _krb5_find_enctype(type); if(et == NULL) { krb5_set_error_message(context, KRB5_PROG_ETYPE_NOSUPP, N_("encryption type %d not supported", ""), type); return KRB5_PROG_ETYPE_NOSUPP; } if ((et->keytype->bits + 7) / 8 > size) { krb5_set_error_message(context, KRB5_PROG_ETYPE_NOSUPP, N_("encryption key %s needs %d bytes " "of random to make an encryption key " "out of it", ""), et->name, (int)et->keytype->size); return KRB5_PROG_ETYPE_NOSUPP; } ret = krb5_data_alloc(&key->keyvalue, et->keytype->size); if(ret) return ret; key->keytype = type; if (et->keytype->random_to_key) (*et->keytype->random_to_key)(context, key, data, size); else memcpy(key->keyvalue.data, data, et->keytype->size); return 0; } KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_crypto_prf_length(krb5_context context, krb5_enctype type, size_t *length) { struct _krb5_encryption_type *et = _krb5_find_enctype(type); if(et == NULL || et->prf_length == 0) { krb5_set_error_message(context, KRB5_PROG_ETYPE_NOSUPP, N_("encryption type %d not supported", ""), type); return KRB5_PROG_ETYPE_NOSUPP; } *length = et->prf_length; return 0; } KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_crypto_prf(krb5_context context, const krb5_crypto crypto, const krb5_data *input, krb5_data *output) { struct _krb5_encryption_type *et = crypto->et; krb5_data_zero(output); if(et->prf == NULL) { krb5_set_error_message(context, KRB5_PROG_ETYPE_NOSUPP, "kerberos prf for %s not supported", et->name); return KRB5_PROG_ETYPE_NOSUPP; } return (*et->prf)(context, crypto, input, output); } static krb5_error_code krb5_crypto_prfplus(krb5_context context, const krb5_crypto crypto, const krb5_data *input, size_t length, krb5_data *output) { krb5_error_code ret; krb5_data input2; unsigned char i = 1; unsigned char *p; krb5_data_zero(&input2); krb5_data_zero(output); krb5_clear_error_message(context); ret = krb5_data_alloc(output, length); if (ret) goto out; ret = krb5_data_alloc(&input2, input->length + 1); if (ret) goto out; krb5_clear_error_message(context); memcpy(((unsigned char *)input2.data) + 1, input->data, input->length); p = output->data; while (length) { krb5_data block; ((unsigned char *)input2.data)[0] = i++; ret = krb5_crypto_prf(context, crypto, &input2, &block); if (ret) goto out; if (block.length < length) { memcpy(p, block.data, block.length); length -= block.length; } else { memcpy(p, block.data, length); length = 0; } p += block.length; krb5_data_free(&block); } out: krb5_data_free(&input2); if (ret) krb5_data_free(output); return ret; } /** * The FX-CF2 key derivation function, used in FAST and preauth framework. * * @param context Kerberos 5 context * @param crypto1 first key to combine * @param crypto2 second key to combine * @param pepper1 factor to combine with first key to garante uniqueness * @param pepper2 factor to combine with second key to garante uniqueness * @param enctype the encryption type of the resulting key * @param res allocated key, free with krb5_free_keyblock_contents() * * @return Return an error code or 0. * * @ingroup krb5_crypto */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_crypto_fx_cf2(krb5_context context, const krb5_crypto crypto1, const krb5_crypto crypto2, krb5_data *pepper1, krb5_data *pepper2, krb5_enctype enctype, krb5_keyblock *res) { krb5_error_code ret; krb5_data os1, os2; size_t i, keysize; memset(res, 0, sizeof(*res)); krb5_data_zero(&os1); krb5_data_zero(&os2); ret = krb5_enctype_keybits(context, enctype, &keysize); if (ret) return ret; keysize = (keysize + 7) / 8; ret = krb5_crypto_prfplus(context, crypto1, pepper1, keysize, &os1); if (ret) goto out; ret = krb5_crypto_prfplus(context, crypto2, pepper2, keysize, &os2); if (ret) goto out; res->keytype = enctype; { unsigned char *p1 = os1.data, *p2 = os2.data; for (i = 0; i < keysize; i++) p1[i] ^= p2[i]; } ret = krb5_random_to_key(context, enctype, os1.data, keysize, res); out: krb5_data_free(&os1); krb5_data_free(&os2); return ret; } #ifndef HEIMDAL_SMALLER /** * Deprecated: keytypes doesn't exists, they are really enctypes. * * @ingroup krb5_deprecated */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_keytype_to_enctypes (krb5_context context, krb5_keytype keytype, unsigned *len, krb5_enctype **val) KRB5_DEPRECATED_FUNCTION("Use X instead") { int i; unsigned n = 0; krb5_enctype *ret; for (i = _krb5_num_etypes - 1; i >= 0; --i) { if (_krb5_etypes[i]->keytype->type == keytype && !(_krb5_etypes[i]->flags & F_PSEUDO) && krb5_enctype_valid(context, _krb5_etypes[i]->type) == 0) ++n; } if (n == 0) { krb5_set_error_message(context, KRB5_PROG_KEYTYPE_NOSUPP, "Keytype have no mapping"); return KRB5_PROG_KEYTYPE_NOSUPP; } ret = malloc(n * sizeof(*ret)); if (ret == NULL && n != 0) return krb5_enomem(context); n = 0; for (i = _krb5_num_etypes - 1; i >= 0; --i) { if (_krb5_etypes[i]->keytype->type == keytype && !(_krb5_etypes[i]->flags & F_PSEUDO) && krb5_enctype_valid(context, _krb5_etypes[i]->type) == 0) ret[n++] = _krb5_etypes[i]->type; } *len = n; *val = ret; return 0; } /** * Deprecated: keytypes doesn't exists, they are really enctypes. * * @ingroup krb5_deprecated */ /* if two enctypes have compatible keys */ KRB5_LIB_FUNCTION krb5_boolean KRB5_LIB_CALL krb5_enctypes_compatible_keys(krb5_context context, krb5_enctype etype1, krb5_enctype etype2) KRB5_DEPRECATED_FUNCTION("Use X instead") { struct _krb5_encryption_type *e1 = _krb5_find_enctype(etype1); struct _krb5_encryption_type *e2 = _krb5_find_enctype(etype2); return e1 != NULL && e2 != NULL && e1->keytype == e2->keytype; } #endif /* HEIMDAL_SMALLER */ heimdal-7.5.0/lib/krb5/krb5_set_default_realm.cat30000644000175000017500000001111313212450757020044 0ustar niknik KRB5_SET_DEFAULT_REAL... BSD Library Functions Manual KRB5_SET_DEFAULT_REAL... NNAAMMEE kkrrbb55__ccooppyy__hhoosstt__rreeaallmm, kkrrbb55__ffrreeee__hhoosstt__rreeaallmm, kkrrbb55__ggeett__ddeeffaauulltt__rreeaallmm, kkrrbb55__ggeett__ddeeffaauulltt__rreeaallmmss, kkrrbb55__ggeett__hhoosstt__rreeaallmm, kkrrbb55__sseett__ddeeffaauulltt__rreeaallmm -- default and host realm read and manipulation routines LLIIBBRRAARRYY Kerberos 5 Library (libkrb5, -lkrb5) SSYYNNOOPPSSIISS ##iinncclluuddee <> _k_r_b_5___e_r_r_o_r___c_o_d_e kkrrbb55__ccooppyy__hhoosstt__rreeaallmm(_k_r_b_5___c_o_n_t_e_x_t _c_o_n_t_e_x_t, _c_o_n_s_t _k_r_b_5___r_e_a_l_m _*_f_r_o_m, _k_r_b_5___r_e_a_l_m _*_*_t_o); _k_r_b_5___e_r_r_o_r___c_o_d_e kkrrbb55__ffrreeee__hhoosstt__rreeaallmm(_k_r_b_5___c_o_n_t_e_x_t _c_o_n_t_e_x_t, _k_r_b_5___r_e_a_l_m _*_r_e_a_l_m_l_i_s_t); _k_r_b_5___e_r_r_o_r___c_o_d_e kkrrbb55__ggeett__ddeeffaauulltt__rreeaallmm(_k_r_b_5___c_o_n_t_e_x_t _c_o_n_t_e_x_t, _k_r_b_5___r_e_a_l_m _*_r_e_a_l_m); _k_r_b_5___e_r_r_o_r___c_o_d_e kkrrbb55__ggeett__ddeeffaauulltt__rreeaallmmss(_k_r_b_5___c_o_n_t_e_x_t _c_o_n_t_e_x_t, _k_r_b_5___r_e_a_l_m _*_*_r_e_a_l_m); _k_r_b_5___e_r_r_o_r___c_o_d_e kkrrbb55__ggeett__hhoosstt__rreeaallmm(_k_r_b_5___c_o_n_t_e_x_t _c_o_n_t_e_x_t, _c_o_n_s_t _c_h_a_r _*_h_o_s_t, _k_r_b_5___r_e_a_l_m _*_*_r_e_a_l_m_s); _k_r_b_5___e_r_r_o_r___c_o_d_e kkrrbb55__sseett__ddeeffaauulltt__rreeaallmm(_k_r_b_5___c_o_n_t_e_x_t _c_o_n_t_e_x_t, _c_o_n_s_t _c_h_a_r _*_r_e_a_l_m); DDEESSCCRRIIPPTTIIOONN kkrrbb55__ccooppyy__hhoosstt__rreeaallmm() copies the list of realms from _f_r_o_m to _t_o. _t_o should be freed by the caller using _k_r_b_5___f_r_e_e___h_o_s_t___r_e_a_l_m. kkrrbb55__ffrreeee__hhoosstt__rreeaallmm() frees all memory allocated by _r_e_a_l_m_l_i_s_t. kkrrbb55__ggeett__ddeeffaauulltt__rreeaallmm() returns the first default realm for this host. The realm returned should be freed with kkrrbb55__xxffrreeee(). kkrrbb55__ggeett__ddeeffaauulltt__rreeaallmmss() returns a NULL terminated list of default realms for this context. Realms returned by kkrrbb55__ggeett__ddeeffaauulltt__rreeaallmmss() should be freed with kkrrbb55__ffrreeee__hhoosstt__rreeaallmm(). kkrrbb55__ggeett__hhoosstt__rreeaallmm() returns a NULL terminated list of realms for _h_o_s_t by looking up the information in the [domain_realm] in _k_r_b_5_._c_o_n_f or in DNS. If the mapping in [domain_realm] results in the string dns_locate, DNS is used to lookup the realm. When using DNS to a resolve the domain for the host a.b.c, kkrrbb55__ggeett__hhoosstt__rreeaallmm() looks for a TXT resource record named _kerberos.a.b.c, and if not found, it strips off the first component and tries a again (_kerberos.b.c) until it reaches the root. If there is no configuration or DNS information found, kkrrbb55__ggeett__hhoosstt__rreeaallmm() assumes it can use the domain part of the _h_o_s_t to form a realm. Caller must free _r_e_a_l_m_l_i_s_t with kkrrbb55__ffrreeee__hhoosstt__rreeaallmm(). kkrrbb55__sseett__ddeeffaauulltt__rreeaallmm() sets the default realm for the _c_o_n_t_e_x_t. If NULL is used as a _r_e_a_l_m, the [libdefaults]default_realm stanza in _k_r_b_5_._c_o_n_f is used. If there is no such stanza in the configuration file, the kkrrbb55__ggeett__hhoosstt__rreeaallmm() function is used to form a default realm. SSEEEE AALLSSOO free(3), krb5.conf(5) HEIMDAL April 24, 2005 HEIMDAL heimdal-7.5.0/lib/krb5/krb5.h0000644000175000017500000010014613026237312013700 0ustar niknik/* * Copyright (c) 1997 - 2007 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Portions Copyright (c) 2009 Apple Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ /* $Id$ */ #ifndef __KRB5_H__ #define __KRB5_H__ #include #include #include #include #include #include #include /* name confusion with MIT */ #ifndef KRB5KDC_ERR_KEY_EXP #define KRB5KDC_ERR_KEY_EXP KRB5KDC_ERR_KEY_EXPIRED #endif #ifdef _WIN32 #define KRB5_CALLCONV __stdcall #else #define KRB5_CALLCONV #endif /* simple constants */ #ifndef TRUE #define TRUE 1 #define FALSE 0 #endif typedef int krb5_boolean; typedef int32_t krb5_error_code; typedef int32_t krb5_kvno; typedef uint32_t krb5_flags; typedef void *krb5_pointer; typedef const void *krb5_const_pointer; struct krb5_crypto_data; typedef struct krb5_crypto_data *krb5_crypto; struct krb5_get_creds_opt_data; typedef struct krb5_get_creds_opt_data *krb5_get_creds_opt; struct krb5_digest_data; typedef struct krb5_digest_data *krb5_digest; struct krb5_ntlm_data; typedef struct krb5_ntlm_data *krb5_ntlm; struct krb5_pac_data; typedef struct krb5_pac_data *krb5_pac; typedef struct krb5_rd_req_in_ctx_data *krb5_rd_req_in_ctx; typedef struct krb5_rd_req_out_ctx_data *krb5_rd_req_out_ctx; typedef CKSUMTYPE krb5_cksumtype; typedef Checksum krb5_checksum; typedef ENCTYPE krb5_enctype; typedef struct krb5_get_init_creds_ctx *krb5_init_creds_context; typedef heim_octet_string krb5_data; /* PKINIT related forward declarations */ struct ContentInfo; struct krb5_pk_identity; struct krb5_pk_cert; /* krb5_enc_data is a mit compat structure */ typedef struct krb5_enc_data { krb5_enctype enctype; krb5_kvno kvno; krb5_data ciphertext; } krb5_enc_data; /* alternative names */ enum { ENCTYPE_NULL = KRB5_ENCTYPE_NULL, ENCTYPE_DES_CBC_CRC = KRB5_ENCTYPE_DES_CBC_CRC, ENCTYPE_DES_CBC_MD4 = KRB5_ENCTYPE_DES_CBC_MD4, ENCTYPE_DES_CBC_MD5 = KRB5_ENCTYPE_DES_CBC_MD5, ENCTYPE_DES3_CBC_MD5 = KRB5_ENCTYPE_DES3_CBC_MD5, ENCTYPE_OLD_DES3_CBC_SHA1 = KRB5_ENCTYPE_OLD_DES3_CBC_SHA1, ENCTYPE_SIGN_DSA_GENERATE = KRB5_ENCTYPE_SIGN_DSA_GENERATE, ENCTYPE_ENCRYPT_RSA_PRIV = KRB5_ENCTYPE_ENCRYPT_RSA_PRIV, ENCTYPE_ENCRYPT_RSA_PUB = KRB5_ENCTYPE_ENCRYPT_RSA_PUB, ENCTYPE_DES3_CBC_SHA1 = KRB5_ENCTYPE_DES3_CBC_SHA1, ENCTYPE_AES128_CTS_HMAC_SHA1_96 = KRB5_ENCTYPE_AES128_CTS_HMAC_SHA1_96, ENCTYPE_AES256_CTS_HMAC_SHA1_96 = KRB5_ENCTYPE_AES256_CTS_HMAC_SHA1_96, ENCTYPE_ARCFOUR_HMAC = KRB5_ENCTYPE_ARCFOUR_HMAC_MD5, ENCTYPE_ARCFOUR_HMAC_MD5 = KRB5_ENCTYPE_ARCFOUR_HMAC_MD5, ENCTYPE_ARCFOUR_HMAC_MD5_56 = KRB5_ENCTYPE_ARCFOUR_HMAC_MD5_56, ENCTYPE_ENCTYPE_PK_CROSS = KRB5_ENCTYPE_ENCTYPE_PK_CROSS, ENCTYPE_DES_CBC_NONE = KRB5_ENCTYPE_DES_CBC_NONE, ENCTYPE_DES3_CBC_NONE = KRB5_ENCTYPE_DES3_CBC_NONE, ENCTYPE_DES_CFB64_NONE = KRB5_ENCTYPE_DES_CFB64_NONE, ENCTYPE_DES_PCBC_NONE = KRB5_ENCTYPE_DES_PCBC_NONE, ETYPE_NULL = KRB5_ENCTYPE_NULL, ETYPE_DES_CBC_CRC = KRB5_ENCTYPE_DES_CBC_CRC, ETYPE_DES_CBC_MD4 = KRB5_ENCTYPE_DES_CBC_MD4, ETYPE_DES_CBC_MD5 = KRB5_ENCTYPE_DES_CBC_MD5, ETYPE_DES3_CBC_MD5 = KRB5_ENCTYPE_DES3_CBC_MD5, ETYPE_OLD_DES3_CBC_SHA1 = KRB5_ENCTYPE_OLD_DES3_CBC_SHA1, ETYPE_SIGN_DSA_GENERATE = KRB5_ENCTYPE_SIGN_DSA_GENERATE, ETYPE_ENCRYPT_RSA_PRIV = KRB5_ENCTYPE_ENCRYPT_RSA_PRIV, ETYPE_ENCRYPT_RSA_PUB = KRB5_ENCTYPE_ENCRYPT_RSA_PUB, ETYPE_DES3_CBC_SHA1 = KRB5_ENCTYPE_DES3_CBC_SHA1, ETYPE_AES128_CTS_HMAC_SHA1_96 = KRB5_ENCTYPE_AES128_CTS_HMAC_SHA1_96, ETYPE_AES256_CTS_HMAC_SHA1_96 = KRB5_ENCTYPE_AES256_CTS_HMAC_SHA1_96, ETYPE_AES128_CTS_HMAC_SHA256_128 = KRB5_ENCTYPE_AES128_CTS_HMAC_SHA256_128, ETYPE_AES256_CTS_HMAC_SHA384_192 = KRB5_ENCTYPE_AES256_CTS_HMAC_SHA384_192, ETYPE_ARCFOUR_HMAC_MD5 = KRB5_ENCTYPE_ARCFOUR_HMAC_MD5, ETYPE_ARCFOUR_HMAC_MD5_56 = KRB5_ENCTYPE_ARCFOUR_HMAC_MD5_56, ETYPE_ENCTYPE_PK_CROSS = KRB5_ENCTYPE_ENCTYPE_PK_CROSS, ETYPE_ARCFOUR_MD4 = KRB5_ENCTYPE_ARCFOUR_MD4, ETYPE_ARCFOUR_HMAC_OLD = KRB5_ENCTYPE_ARCFOUR_HMAC_OLD, ETYPE_ARCFOUR_HMAC_OLD_EXP = KRB5_ENCTYPE_ARCFOUR_HMAC_OLD_EXP, ETYPE_DES_CBC_NONE = KRB5_ENCTYPE_DES_CBC_NONE, ETYPE_DES3_CBC_NONE = KRB5_ENCTYPE_DES3_CBC_NONE, ETYPE_DES_CFB64_NONE = KRB5_ENCTYPE_DES_CFB64_NONE, ETYPE_DES_PCBC_NONE = KRB5_ENCTYPE_DES_PCBC_NONE, ETYPE_DIGEST_MD5_NONE = KRB5_ENCTYPE_DIGEST_MD5_NONE, ETYPE_CRAM_MD5_NONE = KRB5_ENCTYPE_CRAM_MD5_NONE }; /* PDU types */ typedef enum krb5_pdu { KRB5_PDU_ERROR = 0, KRB5_PDU_TICKET = 1, KRB5_PDU_AS_REQUEST = 2, KRB5_PDU_AS_REPLY = 3, KRB5_PDU_TGS_REQUEST = 4, KRB5_PDU_TGS_REPLY = 5, KRB5_PDU_AP_REQUEST = 6, KRB5_PDU_AP_REPLY = 7, KRB5_PDU_KRB_SAFE = 8, KRB5_PDU_KRB_PRIV = 9, KRB5_PDU_KRB_CRED = 10, KRB5_PDU_NONE = 11 /* See krb5_get_permitted_enctypes() */ } krb5_pdu; typedef PADATA_TYPE krb5_preauthtype; typedef enum krb5_key_usage { KRB5_KU_PA_ENC_TIMESTAMP = 1, /* AS-REQ PA-ENC-TIMESTAMP padata timestamp, encrypted with the client key (section 5.4.1) */ KRB5_KU_TICKET = 2, /* AS-REP Ticket and TGS-REP Ticket (includes tgs session key or application session key), encrypted with the service key (section 5.4.2) */ KRB5_KU_AS_REP_ENC_PART = 3, /* AS-REP encrypted part (includes tgs session key or application session key), encrypted with the client key (section 5.4.2) */ KRB5_KU_TGS_REQ_AUTH_DAT_SESSION = 4, /* TGS-REQ KDC-REQ-BODY AuthorizationData, encrypted with the tgs session key (section 5.4.1) */ KRB5_KU_TGS_REQ_AUTH_DAT_SUBKEY = 5, /* TGS-REQ KDC-REQ-BODY AuthorizationData, encrypted with the tgs authenticator subkey (section 5.4.1) */ KRB5_KU_TGS_REQ_AUTH_CKSUM = 6, /* TGS-REQ PA-TGS-REQ padata AP-REQ Authenticator cksum, keyed with the tgs session key (sections 5.3.2, 5.4.1) */ KRB5_KU_TGS_REQ_AUTH = 7, /* TGS-REQ PA-TGS-REQ padata AP-REQ Authenticator (includes tgs authenticator subkey), encrypted with the tgs session key (section 5.3.2) */ KRB5_KU_TGS_REP_ENC_PART_SESSION = 8, /* TGS-REP encrypted part (includes application session key), encrypted with the tgs session key (section 5.4.2) */ KRB5_KU_TGS_REP_ENC_PART_SUB_KEY = 9, /* TGS-REP encrypted part (includes application session key), encrypted with the tgs authenticator subkey (section 5.4.2) */ KRB5_KU_AP_REQ_AUTH_CKSUM = 10, /* AP-REQ Authenticator cksum, keyed with the application session key (section 5.3.2) */ KRB5_KU_AP_REQ_AUTH = 11, /* AP-REQ Authenticator (includes application authenticator subkey), encrypted with the application session key (section 5.3.2) */ KRB5_KU_AP_REQ_ENC_PART = 12, /* AP-REP encrypted part (includes application session subkey), encrypted with the application session key (section 5.5.2) */ KRB5_KU_KRB_PRIV = 13, /* KRB-PRIV encrypted part, encrypted with a key chosen by the application (section 5.7.1) */ KRB5_KU_KRB_CRED = 14, /* KRB-CRED encrypted part, encrypted with a key chosen by the application (section 5.8.1) */ KRB5_KU_KRB_SAFE_CKSUM = 15, /* KRB-SAFE cksum, keyed with a key chosen by the application (section 5.6.1) */ KRB5_KU_OTHER_ENCRYPTED = 16, /* Data which is defined in some specification outside of Kerberos to be encrypted using an RFC1510 encryption type. */ KRB5_KU_OTHER_CKSUM = 17, /* Data which is defined in some specification outside of Kerberos to be checksummed using an RFC1510 checksum type. */ KRB5_KU_KRB_ERROR = 18, /* Krb-error checksum */ KRB5_KU_AD_KDC_ISSUED = 19, /* AD-KDCIssued checksum */ KRB5_KU_MANDATORY_TICKET_EXTENSION = 20, /* Checksum for Mandatory Ticket Extensions */ KRB5_KU_AUTH_DATA_TICKET_EXTENSION = 21, /* Checksum in Authorization Data in Ticket Extensions */ KRB5_KU_USAGE_SEAL = 22, /* seal in GSSAPI krb5 mechanism */ KRB5_KU_USAGE_SIGN = 23, /* sign in GSSAPI krb5 mechanism */ KRB5_KU_USAGE_SEQ = 24, /* SEQ in GSSAPI krb5 mechanism */ KRB5_KU_USAGE_ACCEPTOR_SEAL = 22, /* acceptor sign in GSSAPI CFX krb5 mechanism */ KRB5_KU_USAGE_ACCEPTOR_SIGN = 23, /* acceptor seal in GSSAPI CFX krb5 mechanism */ KRB5_KU_USAGE_INITIATOR_SEAL = 24, /* initiator sign in GSSAPI CFX krb5 mechanism */ KRB5_KU_USAGE_INITIATOR_SIGN = 25, /* initiator seal in GSSAPI CFX krb5 mechanism */ KRB5_KU_PA_SERVER_REFERRAL_DATA = 22, /* encrypted server referral data */ KRB5_KU_SAM_CHECKSUM = 25, /* Checksum for the SAM-CHECKSUM field */ KRB5_KU_SAM_ENC_TRACK_ID = 26, /* Encryption of the SAM-TRACK-ID field */ KRB5_KU_PA_SERVER_REFERRAL = 26, /* Keyusage for the server referral in a TGS req */ KRB5_KU_SAM_ENC_NONCE_SAD = 27, /* Encryption of the SAM-NONCE-OR-SAD field */ KRB5_KU_PA_PKINIT_KX = 44, /* Encryption type of the kdc session contribution in pk-init */ KRB5_KU_AS_REQ = 56, /* Checksum of over the AS-REQ send by the KDC in PA-REQ-ENC-PA-REP */ KRB5_KU_FAST_REQ_CHKSUM = 50, /* FAST armor checksum */ KRB5_KU_FAST_ENC = 51, /* FAST armor encryption */ KRB5_KU_FAST_REP = 52, /* FAST armor reply */ KRB5_KU_FAST_FINISHED = 53, /* FAST finished checksum */ KRB5_KU_ENC_CHALLENGE_CLIENT = 54, /* fast challenge from client */ KRB5_KU_ENC_CHALLENGE_KDC = 55, /* fast challenge from kdc */ KRB5_KU_DIGEST_ENCRYPT = -18, /* Encryption key usage used in the digest encryption field */ KRB5_KU_DIGEST_OPAQUE = -19, /* Checksum key usage used in the digest opaque field */ KRB5_KU_KRB5SIGNEDPATH = -21, /* Checksum key usage on KRB5SignedPath */ KRB5_KU_CANONICALIZED_NAMES = -23, /* Checksum key usage on PA-CANONICALIZED */ KRB5_KU_H5L_COOKIE = -25 /* encrypted foo */ } krb5_key_usage; typedef krb5_key_usage krb5_keyusage; typedef enum krb5_salttype { KRB5_PW_SALT = KRB5_PADATA_PW_SALT, KRB5_AFS3_SALT = KRB5_PADATA_AFS3_SALT }krb5_salttype; typedef struct krb5_salt { krb5_salttype salttype; krb5_data saltvalue; } krb5_salt; typedef ETYPE_INFO krb5_preauthinfo; typedef struct { krb5_preauthtype type; krb5_preauthinfo info; /* list of preauthinfo for this type */ } krb5_preauthdata_entry; typedef struct krb5_preauthdata { unsigned len; krb5_preauthdata_entry *val; }krb5_preauthdata; typedef enum krb5_address_type { KRB5_ADDRESS_INET = 2, KRB5_ADDRESS_NETBIOS = 20, KRB5_ADDRESS_INET6 = 24, KRB5_ADDRESS_ADDRPORT = 256, KRB5_ADDRESS_IPPORT = 257 } krb5_address_type; enum { AP_OPTS_USE_SESSION_KEY = 1, AP_OPTS_MUTUAL_REQUIRED = 2, AP_OPTS_USE_SUBKEY = 4 /* library internal */ }; typedef HostAddress krb5_address; typedef HostAddresses krb5_addresses; typedef krb5_enctype krb5_keytype; enum krb5_keytype_old { KEYTYPE_NULL = ETYPE_NULL, KEYTYPE_DES = ETYPE_DES_CBC_CRC, KEYTYPE_DES3 = ETYPE_OLD_DES3_CBC_SHA1, KEYTYPE_AES128 = ETYPE_AES128_CTS_HMAC_SHA1_96, KEYTYPE_AES256 = ETYPE_AES256_CTS_HMAC_SHA1_96, KEYTYPE_ARCFOUR = ETYPE_ARCFOUR_HMAC_MD5, KEYTYPE_ARCFOUR_56 = ETYPE_ARCFOUR_HMAC_MD5_56 }; typedef EncryptionKey krb5_keyblock; typedef AP_REQ krb5_ap_req; struct krb5_cc_ops; #ifdef _WIN32 #define KRB5_USE_PATH_TOKENS 1 #endif #ifdef KRB5_USE_PATH_TOKENS #define KRB5_DEFAULT_CCFILE_ROOT "%{TEMP}/krb5cc_" #else #define KRB5_DEFAULT_CCFILE_ROOT "/tmp/krb5cc_" #endif #define KRB5_DEFAULT_CCROOT "FILE:" KRB5_DEFAULT_CCFILE_ROOT #define KRB5_ACCEPT_NULL_ADDRESSES(C) \ krb5_config_get_bool_default((C), NULL, TRUE, \ "libdefaults", "accept_null_addresses", \ NULL) typedef void *krb5_cc_cursor; typedef struct krb5_cccol_cursor_data *krb5_cccol_cursor; typedef struct krb5_ccache_data { const struct krb5_cc_ops *ops; krb5_data data; int initialized; /* if non-zero: krb5_cc_initialize() called, now empty */ }krb5_ccache_data; typedef struct krb5_ccache_data *krb5_ccache; typedef struct krb5_context_data *krb5_context; typedef Realm krb5_realm; typedef const char *krb5_const_realm; /* stupid language */ #define krb5_realm_length(r) strlen(r) #define krb5_realm_data(r) (r) typedef Principal krb5_principal_data; typedef struct Principal *krb5_principal; typedef const struct Principal *krb5_const_principal; typedef struct Principals *krb5_principals; typedef time_t krb5_deltat; typedef time_t krb5_timestamp; typedef struct krb5_times { krb5_timestamp authtime; krb5_timestamp starttime; krb5_timestamp endtime; krb5_timestamp renew_till; } krb5_times; typedef union { TicketFlags b; krb5_flags i; } krb5_ticket_flags; /* options for krb5_get_in_tkt() */ #define KDC_OPT_FORWARDABLE (1 << 1) #define KDC_OPT_FORWARDED (1 << 2) #define KDC_OPT_PROXIABLE (1 << 3) #define KDC_OPT_PROXY (1 << 4) #define KDC_OPT_ALLOW_POSTDATE (1 << 5) #define KDC_OPT_POSTDATED (1 << 6) #define KDC_OPT_RENEWABLE (1 << 8) #define KDC_OPT_REQUEST_ANONYMOUS (1 << 14) #define KDC_OPT_DISABLE_TRANSITED_CHECK (1 << 26) #define KDC_OPT_RENEWABLE_OK (1 << 27) #define KDC_OPT_ENC_TKT_IN_SKEY (1 << 28) #define KDC_OPT_RENEW (1 << 30) #define KDC_OPT_VALIDATE (1 << 31) typedef union { KDCOptions b; krb5_flags i; } krb5_kdc_flags; /* flags for krb5_verify_ap_req */ #define KRB5_VERIFY_AP_REQ_IGNORE_INVALID (1 << 0) #define KRB5_GC_CACHED (1U << 0) #define KRB5_GC_USER_USER (1U << 1) #define KRB5_GC_EXPIRED_OK (1U << 2) #define KRB5_GC_NO_STORE (1U << 3) #define KRB5_GC_FORWARDABLE (1U << 4) #define KRB5_GC_NO_TRANSIT_CHECK (1U << 5) #define KRB5_GC_CONSTRAINED_DELEGATION (1U << 6) #define KRB5_GC_CANONICALIZE (1U << 7) /* constants for compare_creds (and cc_retrieve_cred) */ #define KRB5_TC_DONT_MATCH_REALM (1U << 31) #define KRB5_TC_MATCH_KEYTYPE (1U << 30) #define KRB5_TC_MATCH_KTYPE KRB5_TC_MATCH_KEYTYPE /* MIT name */ #define KRB5_TC_MATCH_SRV_NAMEONLY (1 << 29) #define KRB5_TC_MATCH_FLAGS_EXACT (1 << 28) #define KRB5_TC_MATCH_FLAGS (1 << 27) #define KRB5_TC_MATCH_TIMES_EXACT (1 << 26) #define KRB5_TC_MATCH_TIMES (1 << 25) #define KRB5_TC_MATCH_AUTHDATA (1 << 24) #define KRB5_TC_MATCH_2ND_TKT (1 << 23) #define KRB5_TC_MATCH_IS_SKEY (1 << 22) /* constants for get_flags and set_flags */ #define KRB5_TC_OPENCLOSE 0x00000001 #define KRB5_TC_NOTICKET 0x00000002 typedef AuthorizationData krb5_authdata; typedef KRB_ERROR krb5_error; typedef struct krb5_creds { krb5_principal client; krb5_principal server; krb5_keyblock session; krb5_times times; krb5_data ticket; krb5_data second_ticket; krb5_authdata authdata; krb5_addresses addresses; krb5_ticket_flags flags; } krb5_creds; typedef struct krb5_cc_cache_cursor_data *krb5_cc_cache_cursor; #define KRB5_CC_OPS_VERSION 3 typedef struct krb5_cc_ops { int version; const char *prefix; const char* (KRB5_CALLCONV * get_name)(krb5_context, krb5_ccache); krb5_error_code (KRB5_CALLCONV * resolve)(krb5_context, krb5_ccache *, const char *); krb5_error_code (KRB5_CALLCONV * gen_new)(krb5_context, krb5_ccache *); krb5_error_code (KRB5_CALLCONV * init)(krb5_context, krb5_ccache, krb5_principal); krb5_error_code (KRB5_CALLCONV * destroy)(krb5_context, krb5_ccache); krb5_error_code (KRB5_CALLCONV * close)(krb5_context, krb5_ccache); krb5_error_code (KRB5_CALLCONV * store)(krb5_context, krb5_ccache, krb5_creds*); krb5_error_code (KRB5_CALLCONV * retrieve)(krb5_context, krb5_ccache, krb5_flags, const krb5_creds*, krb5_creds *); krb5_error_code (KRB5_CALLCONV * get_princ)(krb5_context, krb5_ccache, krb5_principal*); krb5_error_code (KRB5_CALLCONV * get_first)(krb5_context, krb5_ccache, krb5_cc_cursor *); krb5_error_code (KRB5_CALLCONV * get_next)(krb5_context, krb5_ccache, krb5_cc_cursor*, krb5_creds*); krb5_error_code (KRB5_CALLCONV * end_get)(krb5_context, krb5_ccache, krb5_cc_cursor*); krb5_error_code (KRB5_CALLCONV * remove_cred)(krb5_context, krb5_ccache, krb5_flags, krb5_creds*); krb5_error_code (KRB5_CALLCONV * set_flags)(krb5_context, krb5_ccache, krb5_flags); int (KRB5_CALLCONV * get_version)(krb5_context, krb5_ccache); krb5_error_code (KRB5_CALLCONV * get_cache_first)(krb5_context, krb5_cc_cursor *); krb5_error_code (KRB5_CALLCONV * get_cache_next)(krb5_context, krb5_cc_cursor, krb5_ccache *); krb5_error_code (KRB5_CALLCONV * end_cache_get)(krb5_context, krb5_cc_cursor); krb5_error_code (KRB5_CALLCONV * move)(krb5_context, krb5_ccache, krb5_ccache); krb5_error_code (KRB5_CALLCONV * get_default_name)(krb5_context, char **); krb5_error_code (KRB5_CALLCONV * set_default)(krb5_context, krb5_ccache); krb5_error_code (KRB5_CALLCONV * lastchange)(krb5_context, krb5_ccache, krb5_timestamp *); krb5_error_code (KRB5_CALLCONV * set_kdc_offset)(krb5_context, krb5_ccache, krb5_deltat); krb5_error_code (KRB5_CALLCONV * get_kdc_offset)(krb5_context, krb5_ccache, krb5_deltat *); } krb5_cc_ops; struct krb5_log_facility; struct krb5_config_binding { enum { krb5_config_string, krb5_config_list } type; char *name; struct krb5_config_binding *next; union { char *string; struct krb5_config_binding *list; void *generic; } u; }; typedef struct krb5_config_binding krb5_config_binding; typedef krb5_config_binding krb5_config_section; typedef struct krb5_ticket { EncTicketPart ticket; krb5_principal client; krb5_principal server; } krb5_ticket; typedef Authenticator krb5_authenticator_data; typedef krb5_authenticator_data *krb5_authenticator; struct krb5_rcache_data; typedef struct krb5_rcache_data *krb5_rcache; typedef Authenticator krb5_donot_replay; #define KRB5_STORAGE_HOST_BYTEORDER 0x01 /* old */ #define KRB5_STORAGE_PRINCIPAL_WRONG_NUM_COMPONENTS 0x02 #define KRB5_STORAGE_PRINCIPAL_NO_NAME_TYPE 0x04 #define KRB5_STORAGE_KEYBLOCK_KEYTYPE_TWICE 0x08 #define KRB5_STORAGE_BYTEORDER_MASK 0x60 #define KRB5_STORAGE_BYTEORDER_BE 0x00 /* default */ #define KRB5_STORAGE_BYTEORDER_LE 0x20 #define KRB5_STORAGE_BYTEORDER_HOST 0x40 #define KRB5_STORAGE_CREDS_FLAGS_WRONG_BITORDER 0x80 struct krb5_storage_data; typedef struct krb5_storage_data krb5_storage; typedef struct krb5_keytab_entry { krb5_principal principal; krb5_kvno vno; krb5_keyblock keyblock; uint32_t timestamp; uint32_t flags; krb5_principals aliases; } krb5_keytab_entry; typedef struct krb5_kt_cursor { int fd; krb5_storage *sp; void *data; } krb5_kt_cursor; struct krb5_keytab_data; typedef struct krb5_keytab_data *krb5_keytab; #define KRB5_KT_PREFIX_MAX_LEN 30 struct krb5_keytab_data { const char *prefix; krb5_error_code (KRB5_CALLCONV * resolve)(krb5_context, const char*, krb5_keytab); krb5_error_code (KRB5_CALLCONV * get_name)(krb5_context, krb5_keytab, char*, size_t); krb5_error_code (KRB5_CALLCONV * close)(krb5_context, krb5_keytab); krb5_error_code (KRB5_CALLCONV * destroy)(krb5_context, krb5_keytab); krb5_error_code (KRB5_CALLCONV * get)(krb5_context, krb5_keytab, krb5_const_principal, krb5_kvno, krb5_enctype, krb5_keytab_entry*); krb5_error_code (KRB5_CALLCONV * start_seq_get)(krb5_context, krb5_keytab, krb5_kt_cursor*); krb5_error_code (KRB5_CALLCONV * next_entry)(krb5_context, krb5_keytab, krb5_keytab_entry*, krb5_kt_cursor*); krb5_error_code (KRB5_CALLCONV * end_seq_get)(krb5_context, krb5_keytab, krb5_kt_cursor*); krb5_error_code (KRB5_CALLCONV * add)(krb5_context, krb5_keytab, krb5_keytab_entry*); krb5_error_code (KRB5_CALLCONV * remove)(krb5_context, krb5_keytab, krb5_keytab_entry*); void *data; int32_t version; }; typedef struct krb5_keytab_data krb5_kt_ops; struct krb5_keytab_key_proc_args { krb5_keytab keytab; krb5_principal principal; }; typedef struct krb5_keytab_key_proc_args krb5_keytab_key_proc_args; typedef struct krb5_replay_data { krb5_timestamp timestamp; int32_t usec; uint32_t seq; } krb5_replay_data; /* flags for krb5_auth_con_setflags */ enum { KRB5_AUTH_CONTEXT_DO_TIME = 1, KRB5_AUTH_CONTEXT_RET_TIME = 2, KRB5_AUTH_CONTEXT_DO_SEQUENCE = 4, KRB5_AUTH_CONTEXT_RET_SEQUENCE = 8, KRB5_AUTH_CONTEXT_PERMIT_ALL = 16, KRB5_AUTH_CONTEXT_USE_SUBKEY = 32, KRB5_AUTH_CONTEXT_CLEAR_FORWARDED_CRED = 64 }; /* flags for krb5_auth_con_genaddrs */ enum { KRB5_AUTH_CONTEXT_GENERATE_LOCAL_ADDR = 1, KRB5_AUTH_CONTEXT_GENERATE_LOCAL_FULL_ADDR = 3, KRB5_AUTH_CONTEXT_GENERATE_REMOTE_ADDR = 4, KRB5_AUTH_CONTEXT_GENERATE_REMOTE_FULL_ADDR = 12 }; typedef struct krb5_auth_context_data { unsigned int flags; krb5_address *local_address; krb5_address *remote_address; int16_t local_port; int16_t remote_port; krb5_keyblock *keyblock; krb5_keyblock *local_subkey; krb5_keyblock *remote_subkey; uint32_t local_seqnumber; uint32_t remote_seqnumber; krb5_authenticator authenticator; krb5_pointer i_vector; krb5_rcache rcache; krb5_keytype keytype; /* ¿requested key type ? */ krb5_cksumtype cksumtype; /* ¡requested checksum type! */ AuthorizationData *auth_data; }krb5_auth_context_data, *krb5_auth_context; typedef struct { KDC_REP kdc_rep; EncKDCRepPart enc_part; KRB_ERROR error; } krb5_kdc_rep; extern const char *heimdal_version, *heimdal_long_version; typedef void (KRB5_CALLCONV * krb5_log_log_func_t)(const char*, const char*, void*); typedef void (KRB5_CALLCONV * krb5_log_close_func_t)(void*); typedef struct krb5_log_facility { char *program; int len; struct facility *val; } krb5_log_facility; typedef EncAPRepPart krb5_ap_rep_enc_part; #define KRB5_RECVAUTH_IGNORE_VERSION 1 #define KRB5_SENDAUTH_VERSION "KRB5_SENDAUTH_V1.0" #define KRB5_TGS_NAME_SIZE (6) #define KRB5_TGS_NAME ("krbtgt") #define KRB5_WELLKNOWN_NAME ("WELLKNOWN") #define KRB5_ANON_NAME ("ANONYMOUS") #define KRB5_ANON_REALM ("WELLKNOWN:ANONYMOUS") #define KRB5_WELLKNOWN_ORG_H5L_REALM ("WELLKNOWN:ORG.H5L") #define KRB5_DIGEST_NAME ("digest") #define KRB5_PKU2U_REALM_NAME ("WELLKNOWN:PKU2U") #define KRB5_LKDC_REALM_NAME ("WELLKNOWN:COM.APPLE.LKDC") #define KRB5_GSS_HOSTBASED_SERVICE_NAME ("WELLKNOWN:ORG.H5L.HOSTBASED-SERVICE") #define KRB5_GSS_REFERALS_REALM_NAME ("WELLKNOWN:ORG.H5L.REFERALS-REALM") typedef enum { KRB5_PROMPT_TYPE_PASSWORD = 0x1, KRB5_PROMPT_TYPE_NEW_PASSWORD = 0x2, KRB5_PROMPT_TYPE_NEW_PASSWORD_AGAIN = 0x3, KRB5_PROMPT_TYPE_PREAUTH = 0x4, KRB5_PROMPT_TYPE_INFO = 0x5 } krb5_prompt_type; typedef struct _krb5_prompt { const char *prompt; int hidden; krb5_data *reply; krb5_prompt_type type; } krb5_prompt; typedef int (KRB5_CALLCONV * krb5_prompter_fct)(krb5_context /*context*/, void * /*data*/, const char * /*name*/, const char * /*banner*/, int /*num_prompts*/, krb5_prompt /*prompts*/[]); typedef krb5_error_code (KRB5_CALLCONV * krb5_key_proc)(krb5_context /*context*/, krb5_enctype /*type*/, krb5_salt /*salt*/, krb5_const_pointer /*keyseed*/, krb5_keyblock ** /*key*/); typedef krb5_error_code (KRB5_CALLCONV * krb5_decrypt_proc)(krb5_context /*context*/, krb5_keyblock * /*key*/, krb5_key_usage /*usage*/, krb5_const_pointer /*decrypt_arg*/, krb5_kdc_rep * /*dec_rep*/); typedef krb5_error_code (KRB5_CALLCONV * krb5_s2k_proc)(krb5_context /*context*/, krb5_enctype /*type*/, krb5_const_pointer /*keyseed*/, krb5_salt /*salt*/, krb5_data * /*s2kparms*/, krb5_keyblock ** /*key*/); struct _krb5_get_init_creds_opt_private; struct _krb5_get_init_creds_opt { krb5_flags flags; krb5_deltat tkt_life; krb5_deltat renew_life; int forwardable; int proxiable; int anonymous; int change_password_prompt; krb5_enctype *etype_list; int etype_list_length; krb5_addresses *address_list; /* XXX the next three should not be used, as they may be removed later */ krb5_preauthtype *preauth_list; int preauth_list_length; krb5_data *salt; struct _krb5_get_init_creds_opt_private *opt_private; }; typedef struct _krb5_get_init_creds_opt krb5_get_init_creds_opt; #define KRB5_GET_INIT_CREDS_OPT_TKT_LIFE 0x0001 #define KRB5_GET_INIT_CREDS_OPT_RENEW_LIFE 0x0002 #define KRB5_GET_INIT_CREDS_OPT_FORWARDABLE 0x0004 #define KRB5_GET_INIT_CREDS_OPT_PROXIABLE 0x0008 #define KRB5_GET_INIT_CREDS_OPT_ETYPE_LIST 0x0010 #define KRB5_GET_INIT_CREDS_OPT_ADDRESS_LIST 0x0020 #define KRB5_GET_INIT_CREDS_OPT_PREAUTH_LIST 0x0040 #define KRB5_GET_INIT_CREDS_OPT_SALT 0x0080 /* no supported */ #define KRB5_GET_INIT_CREDS_OPT_ANONYMOUS 0x0100 #define KRB5_GET_INIT_CREDS_OPT_DISABLE_TRANSITED_CHECK 0x0200 #define KRB5_GET_INIT_CREDS_OPT_CHANGE_PASSWORD_PROMPT 0x0400 /* krb5_init_creds_step flags argument */ #define KRB5_INIT_CREDS_STEP_FLAG_CONTINUE 0x0001 typedef struct _krb5_verify_init_creds_opt { krb5_flags flags; int ap_req_nofail; } krb5_verify_init_creds_opt; #define KRB5_VERIFY_INIT_CREDS_OPT_AP_REQ_NOFAIL 0x0001 typedef struct krb5_verify_opt { unsigned int flags; krb5_ccache ccache; krb5_keytab keytab; krb5_boolean secure; const char *service; } krb5_verify_opt; #define KRB5_VERIFY_LREALMS 1 #define KRB5_VERIFY_NO_ADDRESSES 2 #define KRB5_KPASSWD_VERS_CHANGEPW 1 #define KRB5_KPASSWD_VERS_SETPW 0xff80 #define KRB5_KPASSWD_SUCCESS 0 #define KRB5_KPASSWD_MALFORMED 1 #define KRB5_KPASSWD_HARDERROR 2 #define KRB5_KPASSWD_AUTHERROR 3 #define KRB5_KPASSWD_SOFTERROR 4 #define KRB5_KPASSWD_ACCESSDENIED 5 #define KRB5_KPASSWD_BAD_VERSION 6 #define KRB5_KPASSWD_INITIAL_FLAG_NEEDED 7 #define KPASSWD_PORT 464 /* types for the new krbhst interface */ struct krb5_krbhst_data; typedef struct krb5_krbhst_data *krb5_krbhst_handle; #define KRB5_KRBHST_KDC 1 #define KRB5_KRBHST_ADMIN 2 #define KRB5_KRBHST_CHANGEPW 3 #define KRB5_KRBHST_KRB524 4 #define KRB5_KRBHST_KCA 5 typedef struct krb5_krbhst_info { enum { KRB5_KRBHST_UDP, KRB5_KRBHST_TCP, KRB5_KRBHST_HTTP } proto; unsigned short port; unsigned short def_port; struct addrinfo *ai; struct krb5_krbhst_info *next; char hostname[1]; /* has to come last */ } krb5_krbhst_info; /* flags for krb5_krbhst_init_flags (and krb5_send_to_kdc_flags) */ enum { KRB5_KRBHST_FLAGS_MASTER = 1, KRB5_KRBHST_FLAGS_LARGE_MSG = 2 }; typedef krb5_error_code (*krb5_sendto_prexmit)(krb5_context, int, void *, int, krb5_data *); typedef krb5_error_code (KRB5_CALLCONV * krb5_send_to_kdc_func)(krb5_context, void *, krb5_krbhst_info *, time_t, const krb5_data *, krb5_data *); /** flags for krb5_parse_name_flags */ enum { KRB5_PRINCIPAL_PARSE_NO_REALM = 1, /**< Require that there are no realm */ KRB5_PRINCIPAL_PARSE_REQUIRE_REALM = 2, /**< Require a realm present */ KRB5_PRINCIPAL_PARSE_ENTERPRISE = 4, /**< Parse as a NT-ENTERPRISE name */ KRB5_PRINCIPAL_PARSE_IGNORE_REALM = 8, /**< Ignore realm if present */ KRB5_PRINCIPAL_PARSE_NO_DEF_REALM = 16 /**< Don't default the realm */ }; /** flags for krb5_unparse_name_flags */ enum { KRB5_PRINCIPAL_UNPARSE_SHORT = 1, /**< No realm if it is the default realm */ KRB5_PRINCIPAL_UNPARSE_NO_REALM = 2, /**< No realm */ KRB5_PRINCIPAL_UNPARSE_DISPLAY = 4 /**< No quoting */ }; typedef struct krb5_sendto_ctx_data *krb5_sendto_ctx; #define KRB5_SENDTO_DONE 0 #define KRB5_SENDTO_RESET 1 #define KRB5_SENDTO_CONTINUE 2 #define KRB5_SENDTO_TIMEOUT 3 #define KRB5_SENDTO_INITIAL 4 #define KRB5_SENDTO_FILTER 5 #define KRB5_SENDTO_FAILED 6 #define KRB5_SENDTO_KRBHST 7 typedef krb5_error_code (KRB5_CALLCONV * krb5_sendto_ctx_func)(krb5_context, krb5_sendto_ctx, void *, const krb5_data *, int *); struct krb5_plugin; enum krb5_plugin_type { PLUGIN_TYPE_DATA = 1, PLUGIN_TYPE_FUNC }; #define KRB5_PLUGIN_INVOKE_ALL 1 struct credentials; /* this is to keep the compiler happy */ struct getargs; struct sockaddr; /** * Semi private, not stable yet */ typedef struct krb5_crypto_iov { unsigned int flags; /* ignored */ #define KRB5_CRYPTO_TYPE_EMPTY 0 /* OUT krb5_crypto_length(KRB5_CRYPTO_TYPE_HEADER) */ #define KRB5_CRYPTO_TYPE_HEADER 1 /* IN and OUT */ #define KRB5_CRYPTO_TYPE_DATA 2 /* IN */ #define KRB5_CRYPTO_TYPE_SIGN_ONLY 3 /* (only for encryption) OUT krb5_crypto_length(KRB5_CRYPTO_TYPE_TRAILER) */ #define KRB5_CRYPTO_TYPE_PADDING 4 /* OUT krb5_crypto_length(KRB5_CRYPTO_TYPE_TRAILER) */ #define KRB5_CRYPTO_TYPE_TRAILER 5 /* OUT krb5_crypto_length(KRB5_CRYPTO_TYPE_CHECKSUM) */ #define KRB5_CRYPTO_TYPE_CHECKSUM 6 krb5_data data; } krb5_crypto_iov; /* Glue for MIT */ typedef struct { int32_t lr_type; krb5_timestamp value; } krb5_last_req_entry; typedef krb5_error_code (KRB5_CALLCONV * krb5_gic_process_last_req)(krb5_context, krb5_last_req_entry **, void *); typedef struct { krb5_enctype ks_enctype; krb5int32 ks_salttype; }krb5_key_salt_tuple; /* * Name canonicalization rule options */ typedef enum krb5_name_canon_rule_options { KRB5_NCRO_GC_ONLY = 1 << 0, KRB5_NCRO_USE_REFERRALS = 1 << 1, KRB5_NCRO_NO_REFERRALS = 1 << 2, KRB5_NCRO_USE_FAST = 1 << 3, KRB5_NCRO_USE_DNSSEC = 1 << 4, KRB5_NCRO_LOOKUP_REALM = 1 << 5 } krb5_name_canon_rule_options; typedef struct krb5_name_canon_rule_data *krb5_name_canon_rule; typedef const struct krb5_name_canon_rule_data *krb5_const_name_canon_rule; typedef struct krb5_name_canon_iterator_data *krb5_name_canon_iterator; /* * */ struct hx509_certs_data; #include /* variables */ extern KRB5_LIB_VARIABLE const char *krb5_config_file; extern KRB5_LIB_VARIABLE const char *krb5_defkeyname; extern KRB5_LIB_VARIABLE const krb5_cc_ops krb5_acc_ops; extern KRB5_LIB_VARIABLE const krb5_cc_ops krb5_dcc_ops; extern KRB5_LIB_VARIABLE const krb5_cc_ops krb5_fcc_ops; extern KRB5_LIB_VARIABLE const krb5_cc_ops krb5_mcc_ops; extern KRB5_LIB_VARIABLE const krb5_cc_ops krb5_kcm_ops; extern KRB5_LIB_VARIABLE const krb5_cc_ops krb5_akcm_ops; extern KRB5_LIB_VARIABLE const krb5_cc_ops krb5_scc_ops; extern KRB5_LIB_VARIABLE const krb5_kt_ops krb5_fkt_ops; extern KRB5_LIB_VARIABLE const krb5_kt_ops krb5_wrfkt_ops; extern KRB5_LIB_VARIABLE const krb5_kt_ops krb5_javakt_ops; extern KRB5_LIB_VARIABLE const krb5_kt_ops krb5_mkt_ops; extern KRB5_LIB_VARIABLE const krb5_kt_ops krb5_akf_ops; extern KRB5_LIB_VARIABLE const krb5_kt_ops krb5_any_ops; extern KRB5_LIB_VARIABLE const char *krb5_cc_type_api; extern KRB5_LIB_VARIABLE const char *krb5_cc_type_file; extern KRB5_LIB_VARIABLE const char *krb5_cc_type_memory; extern KRB5_LIB_VARIABLE const char *krb5_cc_type_kcm; extern KRB5_LIB_VARIABLE const char *krb5_cc_type_scc; extern KRB5_LIB_VARIABLE const char *krb5_cc_type_dcc; #endif /* __KRB5_H__ */ heimdal-7.5.0/lib/krb5/heim_err.et0000644000175000017500000000352213026237312015010 0ustar niknik# # Error messages for the krb5 library # # This might look like a com_err file, but is not # id "$Id$" error_table heim prefix HEIM_ERR error_code LOG_PARSE, "Error parsing log destination" error_code V4_PRINC_NO_CONV, "Failed to convert v4 principal" error_code SALTTYPE_NOSUPP, "Salt type is not supported by enctype" error_code NOHOST, "Host not found" error_code OPNOTSUPP, "Operation not supported" error_code EOF, "End of file" error_code BAD_MKEY, "Failed to get the master key" error_code SERVICE_NOMATCH, "Unacceptable service used" error_code NOT_SEEKABLE, "File descriptor not seekable" error_code TOO_BIG, "Offset too large" error_code BAD_HDBENT_ENCODING, "Invalid HDB entry encoding" error_code RANDOM_OFFLINE, "No random source available" index 64 prefix HEIM_PKINIT error_code NO_CERTIFICATE, "Certificate missing" error_code NO_PRIVATE_KEY, "Private key missing" error_code NO_VALID_CA, "No valid certificate authority" error_code CERTIFICATE_INVALID, "Certificate invalid" error_code PRIVATE_KEY_INVALID, "Private key invalid" index 128 prefix HEIM_EAI #error_code NOERROR, "no error" error_code UNKNOWN, "unknown error from getaddrinfo" error_code ADDRFAMILY, "address family for nodename not supported" error_code AGAIN, "temporary failure in name resolution" error_code BADFLAGS, "invalid value for ai_flags" error_code FAIL, "non-recoverable failure in name resolution" error_code FAMILY, "ai_family not supported" error_code MEMORY, "memory allocation failure" error_code NODATA, "no address associated with nodename" error_code NONAME, "nodename nor servname provided, or not known" error_code SERVICE, "servname not supported for ai_socktype" error_code SOCKTYPE, "ai_socktype not supported" error_code SYSTEM, "system error returned in errno" index 192 prefix HEIM_NET error_code CONN_REFUSED, "connection refused" end heimdal-7.5.0/lib/krb5/krb5_get_credentials.30000644000175000017500000001203412136107750017030 0ustar niknik.\" Copyright (c) 2004 - 2005 Kungliga Tekniska Högskolan .\" (Royal Institute of Technology, Stockholm, Sweden). .\" All rights reserved. .\" .\" Redistribution and use in source and binary forms, with or without .\" modification, are permitted provided that the following conditions .\" are met: .\" .\" 1. Redistributions of source code must retain the above copyright .\" notice, this list of conditions and the following disclaimer. .\" .\" 2. Redistributions in binary form must reproduce the above copyright .\" notice, this list of conditions and the following disclaimer in the .\" documentation and/or other materials provided with the distribution. .\" .\" 3. Neither the name of the Institute nor the names of its contributors .\" may be used to endorse or promote products derived from this software .\" without specific prior written permission. .\" .\" THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND .\" ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE .\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE .\" ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE .\" FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL .\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS .\" OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) .\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT .\" LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF .\" SUCH DAMAGE. .\" .\" $Id$ .\" .Dd July 26, 2004 .Dt KRB5_GET_CREDENTIALS 3 .Os HEIMDAL .Sh NAME .Nm krb5_get_credentials , .Nm krb5_get_credentials_with_flags , .Nm krb5_get_kdc_cred , .Nm krb5_get_renewed_creds .Nd get credentials from the KDC using krbtgt .Sh LIBRARY Kerberos 5 Library (libkrb5, -lkrb5) .Sh SYNOPSIS .In krb5.h .Ft krb5_error_code .Fo krb5_get_credentials .Fa "krb5_context context" .Fa "krb5_flags options" .Fa "krb5_ccache ccache" .Fa "krb5_creds *in_creds" .Fa "krb5_creds **out_creds" .Fc .Ft krb5_error_code .Fo krb5_get_credentials_with_flags .Fa "krb5_context context" .Fa "krb5_flags options" .Fa "krb5_kdc_flags flags" .Fa "krb5_ccache ccache" .Fa "krb5_creds *in_creds" .Fa "krb5_creds **out_creds" .Fc .Ft krb5_error_code .Fo krb5_get_kdc_cred .Fa "krb5_context context" .Fa "krb5_ccache id" .Fa "krb5_kdc_flags flags" .Fa "krb5_addresses *addresses" .Fa "Ticket *second_ticket" .Fa "krb5_creds *in_creds" .Fa "krb5_creds **out_creds" .Fc .Ft krb5_error_code .Fo krb5_get_renewed_creds .Fa "krb5_context context" .Fa "krb5_creds *creds" .Fa "krb5_const_principal client" .Fa "krb5_ccache ccache" .Fa "const char *in_tkt_service" .Fc .Sh DESCRIPTION .Fn krb5_get_credentials_with_flags get credentials specified by .Fa in_creds->server and .Fa in_creds->client (the rest of the .Fa in_creds structure is ignored) by first looking in the .Fa ccache and if doesn't exists or is expired, fetch the credential from the KDC using the krbtgt in .Fa ccache . The credential is returned in .Fa out_creds and should be freed using the function .Fn krb5_free_creds . .Pp Valid flags to pass into .Fa options argument are: .Pp .Bl -tag -width "KRB5_GC_EXPIRED_OK" -compact .It KRB5_GC_CACHED Only check the .Fa ccache , don't got out on network to fetch credential. .It KRB5_GC_USER_USER Request a user to user ticket. This option doesn't store the resulting user to user credential in the .Fa ccache . .It KRB5_GC_EXPIRED_OK returns the credential even if it is expired, default behavior is trying to refetch the credential from the KDC. .El .Pp .Fa Flags are KDCOptions, note the caller must fill in the bit-field and not use the integer associated structure. .Pp .Fn krb5_get_credentials works the same way as .Fn krb5_get_credentials_with_flags except that the .Fa flags field is missing. .Pp .Fn krb5_get_kdc_cred does the same as the functions above, but the caller must fill in all the information andits closer to the wire protocol. .Pp .Fn krb5_get_renewed_creds renews a credential given by .Fa in_tkt_service (if .Dv NULL the default .Li krbtgt ) using the credential cache .Fa ccache . The result is stored in .Fa creds and should be freed using .Fa krb5_free_creds . .Sh EXAMPLES Here is a example function that get a credential from a credential cache .Fa id or the KDC and returns it to the caller. .Bd -literal #include int getcred(krb5_context context, krb5_ccache id, krb5_creds **creds) { krb5_error_code ret; krb5_creds in; ret = krb5_parse_name(context, "client@EXAMPLE.COM", &in.client); if (ret) krb5_err(context, 1, ret, "krb5_parse_name"); ret = krb5_parse_name(context, "host/server.example.com@EXAMPLE.COM", &in.server); if (ret) krb5_err(context, 1, ret, "krb5_parse_name"); ret = krb5_get_credentials(context, 0, id, &in, creds); if (ret) krb5_err(context, 1, ret, "krb5_get_credentials"); return 0; } .Ed .Sh SEE ALSO .Xr krb5 3 , .Xr krb5_get_forwarded_creds 3 , .Xr krb5.conf 5 heimdal-7.5.0/lib/krb5/net_write.c0000644000175000017500000000606713026237312015037 0ustar niknik/* * Copyright (c) 1997, 1998 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "krb5_locl.h" KRB5_LIB_FUNCTION krb5_ssize_t KRB5_LIB_CALL krb5_net_write (krb5_context context, void *p_fd, const void *buf, size_t len) { krb5_socket_t fd = *((krb5_socket_t *)p_fd); return net_write(fd, buf, len); } KRB5_LIB_FUNCTION krb5_ssize_t KRB5_LIB_CALL krb5_net_write_block(krb5_context context, void *p_fd, const void *buf, size_t len, time_t timeout) { krb5_socket_t fd = *((krb5_socket_t *)p_fd); int ret; struct timeval tv, *tvp; const char *cbuf = (const char *)buf; size_t rem = len; ssize_t count; fd_set wfds; do { FD_ZERO(&wfds); FD_SET(fd, &wfds); if (timeout != 0) { tv.tv_sec = timeout; tv.tv_usec = 0; tvp = &tv; } else tvp = NULL; ret = select(fd + 1, NULL, &wfds, NULL, tvp); if (rk_IS_SOCKET_ERROR(ret)) { if (rk_SOCK_ERRNO == EINTR) continue; return -1; } #ifdef HAVE_WINSOCK if (ret == 0) { WSASetLastError( WSAETIMEDOUT ); return 0; } count = send (fd, cbuf, rem, 0); if (rk_IS_SOCKET_ERROR(count)) { return -1; } #else if (ret == 0) { return 0; } if (!FD_ISSET(fd, &wfds)) { errno = ETIMEDOUT; return -1; } count = write (fd, cbuf, rem); if (count < 0) { if (errno == EINTR) continue; else return count; } #endif cbuf += count; rem -= count; } while (rem > 0); return len; } heimdal-7.5.0/lib/krb5/test_time.c0000644000175000017500000000511313026237312015023 0ustar niknik/* * Copyright (c) 2003 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of KTH nor the names of its contributors may be * used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY KTH AND ITS CONTRIBUTORS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL KTH OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "krb5_locl.h" #include static void check_set_time(krb5_context context) { krb5_error_code ret; krb5_timestamp sec; int32_t usec; struct timeval tv; int diff = 10; int diff2; gettimeofday(&tv, NULL); ret = krb5_set_real_time(context, tv.tv_sec + diff, tv.tv_usec); if (ret) krb5_err(context, 1, ret, "krb5_us_timeofday"); ret = krb5_us_timeofday(context, &sec, &usec); if (ret) krb5_err(context, 1, ret, "krb5_us_timeofday"); diff2 = labs(sec - tv.tv_sec); if (diff2 < 9 || diff > 11) krb5_errx(context, 1, "set time error: diff: %ld", labs(sec - tv.tv_sec)); } int main(int argc, char **argv) { krb5_context context; krb5_error_code ret; ret = krb5_init_context(&context); if (ret) errx(1, "krb5_init_context %d", ret); check_set_time(context); check_set_time(context); check_set_time(context); check_set_time(context); check_set_time(context); krb5_free_context(context); return 0; } heimdal-7.5.0/lib/krb5/get_default_principal.c0000644000175000017500000001103713026237312017354 0ustar niknik/* * Copyright (c) 1997 - 2001 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "krb5_locl.h" /* * Try to find out what's a reasonable default principal. */ static const char* get_env_user(void) { const char *user = getenv("USER"); if(user == NULL) user = getenv("LOGNAME"); if(user == NULL) user = getenv("USERNAME"); return user; } #ifndef _WIN32 /* * Will only use operating-system dependant operation to get the * default principal, for use of functions that in ccache layer to * avoid recursive calls. */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL _krb5_get_default_principal_local (krb5_context context, krb5_principal *princ) { krb5_error_code ret; const char *user; uid_t uid; *princ = NULL; uid = getuid(); if(uid == 0) { user = getlogin(); if(user == NULL) user = get_env_user(); if(user != NULL && strcmp(user, "root") != 0) ret = krb5_make_principal(context, princ, NULL, user, "root", NULL); else ret = krb5_make_principal(context, princ, NULL, "root", NULL); } else { struct passwd *pw = getpwuid(uid); if(pw != NULL) user = pw->pw_name; else { user = get_env_user(); if(user == NULL) user = getlogin(); } if(user == NULL) { krb5_set_error_message(context, ENOTTY, N_("unable to figure out current " "principal", "")); return ENOTTY; /* XXX */ } ret = krb5_make_principal(context, princ, NULL, user, NULL); } return ret; } #else /* _WIN32 */ #define SECURITY_WIN32 #include KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL _krb5_get_default_principal_local(krb5_context context, krb5_principal *princ) { /* See if we can get the principal first. We only expect this to work if logged into a domain. */ { char username[1024]; ULONG sz = sizeof(username); if (GetUserNameEx(NameUserPrincipal, username, &sz)) { return krb5_parse_name_flags(context, username, KRB5_PRINCIPAL_PARSE_ENTERPRISE, princ); } } /* Just get the Windows username. This should pretty much always work. */ { char username[1024]; DWORD dsz = sizeof(username); if (GetUserName(username, &dsz)) { return krb5_make_principal(context, princ, NULL, username, NULL); } } /* Failing that, we look at the environment */ { const char * username = get_env_user(); if (username == NULL) { krb5_set_error_string(context, "unable to figure out current principal"); return ENOTTY; /* Really? */ } return krb5_make_principal(context, princ, NULL, username, NULL); } } #endif KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_get_default_principal (krb5_context context, krb5_principal *princ) { krb5_error_code ret; krb5_ccache id; *princ = NULL; ret = krb5_cc_default (context, &id); if (ret == 0) { ret = krb5_cc_get_principal (context, id, princ); krb5_cc_close (context, id); if (ret == 0) return 0; } return _krb5_get_default_principal_local(context, princ); } heimdal-7.5.0/lib/krb5/krb5-private.h0000644000175000017500000004341413212445576015366 0ustar niknik/* This is a generated file */ #ifndef __krb5_private_h__ #define __krb5_private_h__ #include #if !defined(__GNUC__) && !defined(__attribute__) #define __attribute__(x) #endif #ifndef KRB5_DEPRECATED_FUNCTION #ifndef __has_extension #define __has_extension(x) 0 #define KRB5_DEPRECATED_FUNCTIONhas_extension 1 #endif #if __has_extension(attribute_deprecated_with_message) #define KRB5_DEPRECATED_FUNCTION(x) __attribute__((__deprecated__(x))) #elif defined(__GNUC__) && ((__GNUC__ > 3) || ((__GNUC__ == 3) && (__GNUC_MINOR__ >= 1 ))) #define KRB5_DEPRECATED_FUNCTION(X) __attribute__((__deprecated__)) #else #define KRB5_DEPRECATED_FUNCTION(X) #endif #ifdef KRB5_DEPRECATED_FUNCTIONhas_extension #undef __has_extension #undef KRB5_DEPRECATED_FUNCTIONhas_extension #endif #endif /* KRB5_DEPRECATED_FUNCTION */ KRB5_LIB_FUNCTION void KRB5_LIB_CALL _heim_krb5_ipc_client_clear_target (void); KRB5_LIB_FUNCTION void KRB5_LIB_CALL _heim_krb5_ipc_client_set_target_uid (uid_t /*uid*/); void _krb5_DES3_random_to_key ( krb5_context /*context*/, krb5_keyblock */*key*/, const void */*data*/, size_t /*size*/); krb5_error_code _krb5_HMAC_MD5_checksum ( krb5_context /*context*/, struct _krb5_key_data */*key*/, const void */*data*/, size_t /*len*/, unsigned /*usage*/, Checksum */*result*/); krb5_error_code _krb5_SP800_108_HMAC_KDF ( krb5_context /*context*/, const krb5_data */*kdf_K1*/, const krb5_data */*kdf_label*/, const krb5_data */*kdf_context*/, const EVP_MD */*md*/, krb5_data */*kdf_K0*/); krb5_error_code _krb5_SP_HMAC_SHA1_checksum ( krb5_context /*context*/, struct _krb5_key_data */*key*/, const void */*data*/, size_t /*len*/, unsigned /*usage*/, Checksum */*result*/); krb5_error_code _krb5_aes_sha2_md_for_enctype ( krb5_context /*context*/, krb5_enctype /*enctype*/, const EVP_MD **/*md*/); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL _krb5_build_authenticator ( krb5_context /*context*/, krb5_auth_context /*auth_context*/, krb5_enctype /*enctype*/, krb5_creds */*cred*/, Checksum */*cksum*/, krb5_data */*result*/, krb5_key_usage /*usage*/); krb5_error_code _krb5_build_authpack_subjectPK_EC ( krb5_context /*context*/, krb5_pk_init_ctx /*ctx*/, AuthPack */*a*/); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL _krb5_cc_allocate ( krb5_context /*context*/, const krb5_cc_ops */*ops*/, krb5_ccache */*id*/); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL _krb5_config_copy ( krb5_context /*context*/, krb5_config_section */*c*/, krb5_config_section **/*head*/); KRB5_LIB_FUNCTION const void * KRB5_LIB_CALL _krb5_config_get ( krb5_context /*context*/, const krb5_config_section */*c*/, int /*type*/, ...); KRB5_LIB_FUNCTION krb5_config_section * KRB5_LIB_CALL _krb5_config_get_entry ( krb5_config_section **/*parent*/, const char */*name*/, int /*type*/); KRB5_LIB_FUNCTION const void * KRB5_LIB_CALL _krb5_config_get_next ( krb5_context /*context*/, const krb5_config_section */*c*/, const krb5_config_binding **/*pointer*/, int /*type*/, ...); KRB5_LIB_FUNCTION const void * KRB5_LIB_CALL _krb5_config_vget ( krb5_context /*context*/, const krb5_config_section */*c*/, int /*type*/, va_list /*args*/); KRB5_LIB_FUNCTION const void * KRB5_LIB_CALL _krb5_config_vget_next ( krb5_context /*context*/, const krb5_config_section */*c*/, const krb5_config_binding **/*pointer*/, int /*type*/, va_list /*args*/); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL _krb5_copy_send_to_kdc_func ( krb5_context /*context*/, krb5_context /*to*/); KRB5_LIB_FUNCTION void KRB5_LIB_CALL _krb5_crc_init_table (void); KRB5_LIB_FUNCTION uint32_t KRB5_LIB_CALL _krb5_crc_update ( const char */*p*/, size_t /*len*/, uint32_t /*res*/); void KRB5_LIB_FUNCTION _krb5_debug ( krb5_context /*context*/, int /*level*/, const char */*fmt*/, ...) __attribute__ ((__format__ (__printf__, 3, 4))); KRB5_LIB_FUNCTION void KRB5_LIB_CALL _krb5_debug_backtrace (krb5_context /*context*/); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL _krb5_derive_key ( krb5_context /*context*/, struct _krb5_encryption_type */*et*/, struct _krb5_key_data */*key*/, const void */*constant*/, size_t /*len*/); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL _krb5_des_checksum ( krb5_context /*context*/, const EVP_MD */*evp_md*/, struct _krb5_key_data */*key*/, const void */*data*/, size_t /*len*/, Checksum */*cksum*/); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL _krb5_des_verify ( krb5_context /*context*/, const EVP_MD */*evp_md*/, struct _krb5_key_data */*key*/, const void */*data*/, size_t /*len*/, Checksum */*C*/); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL _krb5_dh_group_ok ( krb5_context /*context*/, unsigned long /*bits*/, heim_integer */*p*/, heim_integer */*g*/, heim_integer */*q*/, struct krb5_dh_moduli **/*moduli*/, char **/*name*/); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL _krb5_einval ( krb5_context /*context*/, const char */*func*/, unsigned long /*argn*/); KRB5_LIB_FUNCTION krb5_boolean KRB5_LIB_CALL _krb5_enctype_requires_random_salt ( krb5_context /*context*/, krb5_enctype /*enctype*/); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL _krb5_erase_file ( krb5_context /*context*/, const char */*filename*/); void _krb5_evp_cleanup ( krb5_context /*context*/, struct _krb5_key_data */*kd*/); krb5_error_code _krb5_evp_encrypt ( krb5_context /*context*/, struct _krb5_key_data */*key*/, void */*data*/, size_t /*len*/, krb5_boolean /*encryptp*/, int /*usage*/, void */*ivec*/); krb5_error_code _krb5_evp_encrypt_cts ( krb5_context /*context*/, struct _krb5_key_data */*key*/, void */*data*/, size_t /*len*/, krb5_boolean /*encryptp*/, int /*usage*/, void */*ivec*/); void _krb5_evp_schedule ( krb5_context /*context*/, struct _krb5_key_type */*kt*/, struct _krb5_key_data */*kd*/); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL _krb5_expand_default_cc_name ( krb5_context /*context*/, const char */*str*/, char **/*res*/); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL _krb5_expand_path_tokens ( krb5_context /*context*/, const char */*path_in*/, int /*filepath*/, char **/*ppath_out*/); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL _krb5_expand_path_tokensv ( krb5_context /*context*/, const char */*path_in*/, int /*filepath*/, char **/*ppath_out*/, ...); KRB5_LIB_FUNCTION int KRB5_LIB_CALL _krb5_extract_ticket ( krb5_context /*context*/, krb5_kdc_rep */*rep*/, krb5_creds */*creds*/, krb5_keyblock */*key*/, krb5_const_pointer /*keyseed*/, krb5_key_usage /*key_usage*/, krb5_addresses */*addrs*/, unsigned /*nonce*/, unsigned /*flags*/, krb5_data */*request*/, krb5_decrypt_proc /*decrypt_proc*/, krb5_const_pointer /*decryptarg*/); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL _krb5_fast_armor_key ( krb5_context /*context*/, krb5_keyblock */*subkey*/, krb5_keyblock */*sessionkey*/, krb5_keyblock */*armorkey*/, krb5_crypto */*armor_crypto*/); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL _krb5_fast_cf2 ( krb5_context /*context*/, krb5_keyblock */*key1*/, const char */*pepper1*/, krb5_keyblock */*key2*/, const char */*pepper2*/, krb5_keyblock */*armorkey*/, krb5_crypto */*armor_crypto*/); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL _krb5_find_capath ( krb5_context /*context*/, const char */*client_realm*/, const char */*local_realm*/, const char */*server_realm*/, krb5_boolean /*use_hierarchical*/, char ***/*rpath*/, size_t */*npath*/); KRB5_LIB_FUNCTION struct _krb5_checksum_type * KRB5_LIB_CALL _krb5_find_checksum (krb5_cksumtype /*type*/); KRB5_LIB_FUNCTION struct _krb5_encryption_type * KRB5_LIB_CALL _krb5_find_enctype (krb5_enctype /*type*/); KRB5_LIB_FUNCTION void KRB5_LIB_CALL _krb5_free_capath ( krb5_context /*context*/, char **/*capath*/); KRB5_LIB_FUNCTION void KRB5_LIB_CALL _krb5_free_key_data ( krb5_context /*context*/, struct _krb5_key_data */*key*/, struct _krb5_encryption_type */*et*/); KRB5_LIB_FUNCTION void KRB5_LIB_CALL _krb5_free_krbhst_info (krb5_krbhst_info */*hi*/); KRB5_LIB_FUNCTION void KRB5_LIB_CALL _krb5_free_moduli (struct krb5_dh_moduli **/*moduli*/); KRB5_LIB_FUNCTION void _krb5_free_name_canon_rules ( krb5_context /*context*/, krb5_name_canon_rule /*rules*/); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL _krb5_get_ad ( krb5_context /*context*/, const AuthorizationData */*ad*/, krb5_keyblock */*sessionkey*/, int /*type*/, krb5_data */*data*/); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL _krb5_get_cred_kdc_any ( krb5_context /*context*/, krb5_kdc_flags /*flags*/, krb5_ccache /*ccache*/, krb5_creds */*in_creds*/, krb5_principal /*impersonate_principal*/, Ticket */*second_ticket*/, krb5_creds **/*out_creds*/, krb5_creds ***/*ret_tgts*/); KRB5_LIB_FUNCTION char * KRB5_LIB_CALL _krb5_get_default_cc_name_from_registry (krb5_context /*context*/); KRB5_LIB_FUNCTION char * KRB5_LIB_CALL _krb5_get_default_config_config_files_from_registry (void); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL _krb5_get_default_principal_local ( krb5_context /*context*/, krb5_principal */*princ*/); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL _krb5_get_host_realm_int ( krb5_context /*context*/, const char */*host*/, krb5_boolean /*use_dns*/, krb5_realm **/*realms*/); KRB5_LIB_FUNCTION void KRB5_LIB_CALL _krb5_get_init_creds_opt_free_pkinit (krb5_get_init_creds_opt */*opt*/); KRB5_LIB_FUNCTION krb5_ssize_t KRB5_LIB_CALL _krb5_get_int ( void */*buffer*/, unsigned long */*value*/, size_t /*size*/); KRB5_LIB_FUNCTION krb5_ssize_t KRB5_LIB_CALL _krb5_get_int64 ( void */*buffer*/, uint64_t */*value*/, size_t /*size*/); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL _krb5_get_krbtgt ( krb5_context /*context*/, krb5_ccache /*id*/, krb5_realm /*realm*/, krb5_creds **/*cred*/); KRB5_LIB_FUNCTION krb5_error_code _krb5_get_name_canon_rules ( krb5_context /*context*/, krb5_name_canon_rule */*rules*/); KRB5_LIB_FUNCTION krb5_boolean KRB5_LIB_CALL _krb5_have_debug ( krb5_context /*context*/, int /*level*/); KRB5_LIB_FUNCTION krb5_boolean KRB5_LIB_CALL _krb5_homedir_access (krb5_context /*context*/); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL _krb5_init_etype ( krb5_context /*context*/, krb5_pdu /*pdu_type*/, unsigned */*len*/, krb5_enctype **/*val*/, const krb5_enctype */*etypes*/); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL _krb5_internal_hmac ( krb5_context /*context*/, struct _krb5_checksum_type */*cm*/, const void */*data*/, size_t /*len*/, unsigned /*usage*/, struct _krb5_key_data */*keyblock*/, Checksum */*result*/); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL _krb5_kcm_get_initial_ticket ( krb5_context /*context*/, krb5_ccache /*id*/, krb5_principal /*server*/, krb5_keyblock */*key*/); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL _krb5_kcm_get_ticket ( krb5_context /*context*/, krb5_ccache /*id*/, krb5_kdc_flags /*flags*/, krb5_enctype /*enctype*/, krb5_principal /*server*/); KRB5_LIB_FUNCTION krb5_boolean KRB5_LIB_CALL _krb5_kcm_is_running (krb5_context /*context*/); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL _krb5_kcm_noop ( krb5_context /*context*/, krb5_ccache /*id*/); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL _krb5_kdc_retry ( krb5_context /*context*/, krb5_sendto_ctx /*ctx*/, void */*data*/, const krb5_data */*reply*/, int */*action*/); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL _krb5_krbhost_info_move ( krb5_context /*context*/, krb5_krbhst_info */*from*/, krb5_krbhst_info **/*to*/); KRB5_LIB_FUNCTION const char * KRB5_LIB_CALL _krb5_krbhst_get_realm (krb5_krbhst_handle /*handle*/); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL _krb5_kt_principal_not_found ( krb5_context /*context*/, krb5_error_code /*ret*/, krb5_keytab /*id*/, krb5_const_principal /*principal*/, krb5_enctype /*enctype*/, int /*kvno*/); KRB5_LIB_FUNCTION krb5_boolean KRB5_LIB_CALL _krb5_kuserok ( krb5_context /*context*/, krb5_principal /*principal*/, const char */*luser*/, krb5_boolean /*an2ln_ok*/); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL _krb5_load_ccache_plugins (krb5_context /*context*/); KRB5_LIB_FUNCTION void KRB5_LIB_CALL _krb5_load_db_plugins (krb5_context /*context*/); KRB5_LIB_FUNCTION void KRB5_LIB_CALL _krb5_load_plugins ( krb5_context /*context*/, const char */*name*/, const char **/*paths*/); krb5_error_code _krb5_make_fast_ap_fxarmor ( krb5_context /*context*/, krb5_ccache /*armor_ccache*/, krb5_data */*armor_value*/, krb5_keyblock */*armor_key*/, krb5_crypto */*armor_crypto*/); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL _krb5_mk_req_internal ( krb5_context /*context*/, krb5_auth_context */*auth_context*/, const krb5_flags /*ap_req_options*/, krb5_data */*in_data*/, krb5_creds */*in_creds*/, krb5_data */*outbuf*/, krb5_key_usage /*checksum_usage*/, krb5_key_usage /*encrypt_usage*/); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL _krb5_n_fold ( const void */*str*/, size_t /*len*/, void */*key*/, size_t /*size*/); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL _krb5_pac_sign ( krb5_context /*context*/, krb5_pac /*p*/, time_t /*authtime*/, krb5_principal /*principal*/, const krb5_keyblock */*server_key*/, const krb5_keyblock */*priv_key*/, krb5_data */*data*/); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL _krb5_parse_moduli ( krb5_context /*context*/, const char */*file*/, struct krb5_dh_moduli ***/*moduli*/); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL _krb5_parse_moduli_line ( krb5_context /*context*/, const char */*file*/, int /*lineno*/, char */*p*/, struct krb5_dh_moduli **/*m*/); KRB5_LIB_FUNCTION void KRB5_LIB_CALL _krb5_pk_cert_free (struct krb5_pk_cert */*cert*/); void _krb5_pk_eckey_free (void */*eckey*/); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL _krb5_pk_kdf ( krb5_context /*context*/, const struct AlgorithmIdentifier */*ai*/, const void */*dhdata*/, size_t /*dhsize*/, krb5_const_principal /*client*/, krb5_const_principal /*server*/, krb5_enctype /*enctype*/, const krb5_data */*as_req*/, const krb5_data */*pk_as_rep*/, const Ticket */*ticket*/, krb5_keyblock */*key*/); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL _krb5_pk_load_id ( krb5_context /*context*/, struct krb5_pk_identity **/*ret_id*/, const char */*user_id*/, const char */*anchor_id*/, char * const */*chain_list*/, char * const */*revoke_list*/, krb5_prompter_fct /*prompter*/, void */*prompter_data*/, char */*password*/); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL _krb5_pk_mk_ContentInfo ( krb5_context /*context*/, const krb5_data */*buf*/, const heim_oid */*oid*/, struct ContentInfo */*content_info*/); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL _krb5_pk_mk_padata ( krb5_context /*context*/, void */*c*/, int /*ic_flags*/, int /*win2k*/, const KDC_REQ_BODY */*req_body*/, unsigned /*nonce*/, METHOD_DATA */*md*/); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL _krb5_pk_octetstring2key ( krb5_context /*context*/, krb5_enctype /*type*/, const void */*dhdata*/, size_t /*dhsize*/, const heim_octet_string */*c_n*/, const heim_octet_string */*k_n*/, krb5_keyblock */*key*/); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL _krb5_pk_rd_pa_reply ( krb5_context /*context*/, const char */*realm*/, void */*c*/, krb5_enctype /*etype*/, const krb5_krbhst_info */*hi*/, unsigned /*nonce*/, const krb5_data */*req_buffer*/, PA_DATA */*pa*/, krb5_keyblock **/*key*/); krb5_error_code _krb5_pk_rd_pa_reply_ecdh_compute_key ( krb5_context /*context*/, krb5_pk_init_ctx /*ctx*/, const unsigned char */*in*/, size_t /*in_sz*/, unsigned char **/*out*/, int */*out_sz*/); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL _krb5_plugin_find ( krb5_context /*context*/, enum krb5_plugin_type /*type*/, const char */*name*/, struct krb5_plugin **/*list*/); KRB5_LIB_FUNCTION void KRB5_LIB_CALL _krb5_plugin_free (struct krb5_plugin */*list*/); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL _krb5_plugin_run_f ( krb5_context /*context*/, const char */*module*/, const char */*name*/, int /*min_version*/, int /*flags*/, void */*userctx*/, krb5_error_code (KRB5_LIB_CALL *func)(krb5_context, const void *, void *, void *)); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL _krb5_principal2principalname ( PrincipalName */*p*/, const krb5_principal /*from*/); KRB5_LIB_FUNCTION krb5_boolean KRB5_LIB_CALL _krb5_principal_compare_PrincipalName ( krb5_context /*context*/, krb5_const_principal /*princ1*/, PrincipalName */*princ2*/); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL _krb5_principalname2krb5_principal ( krb5_context /*context*/, krb5_principal */*principal*/, const PrincipalName /*from*/, const Realm /*realm*/); KRB5_LIB_FUNCTION krb5_ssize_t KRB5_LIB_CALL _krb5_put_int ( void */*buffer*/, uint64_t /*value*/, size_t /*size*/); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL _krb5_s4u2self_to_checksumdata ( krb5_context /*context*/, const PA_S4U2Self */*self*/, krb5_data */*data*/); KRB5_LIB_FUNCTION void KRB5_LIB_CALL _krb5_sendto_ctx_set_krb5hst ( krb5_context /*context*/, krb5_sendto_ctx /*ctx*/, krb5_krbhst_handle /*handle*/); KRB5_LIB_FUNCTION void KRB5_LIB_CALL _krb5_sendto_ctx_set_prexmit ( krb5_sendto_ctx /*ctx*/, krb5_sendto_prexmit /*prexmit*/, void */*data*/); KRB5_LIB_FUNCTION int KRB5_LIB_CALL _krb5_set_default_cc_name_to_registry ( krb5_context /*context*/, krb5_ccache /*id*/); KRB5_LIB_FUNCTION void KRB5_LIB_CALL _krb5_unload_plugins ( krb5_context /*context*/, const char */*name*/); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL _krb5_usage2arcfour ( krb5_context /*context*/, unsigned */*usage*/); KRB5_LIB_FUNCTION int KRB5_LIB_CALL _krb5_xlock ( krb5_context /*context*/, int /*fd*/, krb5_boolean /*exclusive*/, const char */*filename*/); KRB5_LIB_FUNCTION void KRB5_LIB_CALL _krb5_xor8 ( unsigned char */*a*/, const unsigned char */*b*/); KRB5_LIB_FUNCTION int KRB5_LIB_CALL _krb5_xunlock ( krb5_context /*context*/, int /*fd*/); #undef KRB5_DEPRECATED_FUNCTION #define KRB5_DEPRECATED_FUNCTION(X) #endif /* __krb5_private_h__ */ heimdal-7.5.0/lib/krb5/verify_init.c0000644000175000017500000001501013026237312015352 0ustar niknik/* * Copyright (c) 1997 - 2008 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "krb5_locl.h" KRB5_LIB_FUNCTION void KRB5_LIB_CALL krb5_verify_init_creds_opt_init(krb5_verify_init_creds_opt *options) { memset (options, 0, sizeof(*options)); } KRB5_LIB_FUNCTION void KRB5_LIB_CALL krb5_verify_init_creds_opt_set_ap_req_nofail(krb5_verify_init_creds_opt *options, int ap_req_nofail) { options->flags |= KRB5_VERIFY_INIT_CREDS_OPT_AP_REQ_NOFAIL; options->ap_req_nofail = ap_req_nofail; } /* * */ static krb5_boolean fail_verify_is_ok (krb5_context context, krb5_verify_init_creds_opt *options) { if (options && (options->flags & KRB5_VERIFY_INIT_CREDS_OPT_AP_REQ_NOFAIL) && options->ap_req_nofail != 0) return FALSE; if (krb5_config_get_bool(context, NULL, "libdefaults", "verify_ap_req_nofail", NULL)) return FALSE; return TRUE; } KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_verify_init_creds(krb5_context context, krb5_creds *creds, krb5_principal ap_req_server, krb5_keytab ap_req_keytab, krb5_ccache *ccache, krb5_verify_init_creds_opt *options) { krb5_error_code ret; krb5_data req; krb5_ccache local_ccache = NULL; krb5_creds *new_creds = NULL; krb5_auth_context auth_context = NULL; krb5_principal server = NULL; krb5_keytab keytab = NULL; krb5_data_zero (&req); if (ap_req_server == NULL) { char local_hostname[MAXHOSTNAMELEN]; if (gethostname (local_hostname, sizeof(local_hostname)) < 0) { ret = errno; krb5_set_error_message (context, ret, "gethostname: %s", strerror(ret)); return ret; } ret = krb5_sname_to_principal (context, local_hostname, "host", KRB5_NT_SRV_HST, &server); if (ret) goto cleanup; } else server = ap_req_server; if (ap_req_keytab == NULL) { ret = krb5_kt_default (context, &keytab); if (ret) goto cleanup; } else keytab = ap_req_keytab; if (ccache && *ccache) local_ccache = *ccache; else { ret = krb5_cc_new_unique(context, krb5_cc_type_memory, NULL, &local_ccache); if (ret) goto cleanup; ret = krb5_cc_initialize (context, local_ccache, creds->client); if (ret) goto cleanup; ret = krb5_cc_store_cred (context, local_ccache, creds); if (ret) goto cleanup; } if (!krb5_principal_compare (context, server, creds->server)) { krb5_creds match_cred; memset (&match_cred, 0, sizeof(match_cred)); match_cred.client = creds->client; match_cred.server = server; ret = krb5_get_credentials (context, 0, local_ccache, &match_cred, &new_creds); if (ret) { if (fail_verify_is_ok (context, options)) ret = 0; goto cleanup; } creds = new_creds; } ret = krb5_mk_req_extended (context, &auth_context, 0, NULL, creds, &req); krb5_auth_con_free (context, auth_context); auth_context = NULL; if (ret) goto cleanup; ret = krb5_rd_req (context, &auth_context, &req, server, keytab, 0, NULL); if (ret == KRB5_KT_NOTFOUND && fail_verify_is_ok (context, options)) ret = 0; cleanup: if (auth_context) krb5_auth_con_free (context, auth_context); krb5_data_free (&req); if (new_creds != NULL) krb5_free_creds (context, new_creds); if (ap_req_server == NULL && server) krb5_free_principal (context, server); if (ap_req_keytab == NULL && keytab) krb5_kt_close (context, keytab); if (local_ccache != NULL && (ccache == NULL || (ret != 0 && *ccache == NULL))) krb5_cc_destroy (context, local_ccache); if (ret == 0 && ccache != NULL && *ccache == NULL) *ccache = local_ccache; return ret; } /** * Validate the newly fetch credential, see also krb5_verify_init_creds(). * * @param context a Kerberos 5 context * @param creds the credentials to verify * @param client the client name to match up * @param ccache the credential cache to use * @param service a service name to use, used with * krb5_sname_to_principal() to build a hostname to use to * verify. * * @ingroup krb5_ccache */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_get_validated_creds(krb5_context context, krb5_creds *creds, krb5_principal client, krb5_ccache ccache, char *service) { krb5_verify_init_creds_opt vopt; krb5_principal server; krb5_error_code ret; if (krb5_principal_compare(context, creds->client, client) != TRUE) { krb5_set_error_message(context, KRB5_PRINC_NOMATCH, N_("Validation credentials and client " "doesn't match", "")); return KRB5_PRINC_NOMATCH; } ret = krb5_sname_to_principal (context, NULL, service, KRB5_NT_SRV_HST, &server); if(ret) return ret; krb5_verify_init_creds_opt_init(&vopt); ret = krb5_verify_init_creds(context, creds, server, NULL, NULL, &vopt); krb5_free_principal(context, server); return ret; } heimdal-7.5.0/lib/krb5/misc.c0000644000175000017500000000745013026237312013767 0ustar niknik/* * Copyright (c) 1997 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "krb5_locl.h" #ifdef HAVE_EXECINFO_H #include #endif KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL _krb5_s4u2self_to_checksumdata(krb5_context context, const PA_S4U2Self *self, krb5_data *data) { krb5_error_code ret; krb5_ssize_t ssize; krb5_storage *sp; size_t size; size_t i; sp = krb5_storage_emem(); if (sp == NULL) return krb5_enomem(context); krb5_storage_set_flags(sp, KRB5_STORAGE_BYTEORDER_LE); ret = krb5_store_int32(sp, self->name.name_type); if (ret) { krb5_clear_error_message(context); return ret; } for (i = 0; i < self->name.name_string.len; i++) { size = strlen(self->name.name_string.val[i]); ssize = krb5_storage_write(sp, self->name.name_string.val[i], size); if (ssize != (krb5_ssize_t)size) return krb5_enomem(context); } size = strlen(self->realm); ssize = krb5_storage_write(sp, self->realm, size); if (ssize != (krb5_ssize_t)size) return krb5_enomem(context); size = strlen(self->auth); ssize = krb5_storage_write(sp, self->auth, size); if (ssize != (krb5_ssize_t)size) return krb5_enomem(context); ret = krb5_storage_to_data(sp, data); krb5_storage_free(sp); return ret; } KRB5_LIB_FUNCTION void KRB5_LIB_CALL _krb5_debug_backtrace(krb5_context context) { #if defined(HAVE_BACKTRACE) && defined(HAVE_BACKTRACE_SYMBOLS) && !defined(HEIMDAL_SMALLER) void *stack[128]; char **strs = NULL; int i, frames = backtrace(stack, sizeof(stack) / sizeof(stack[0])); if (frames > 0) strs = backtrace_symbols(stack, frames); if (strs) { for (i = 0; i < frames; i++) _krb5_debug(context, 10, "frame %d: %s", i, strs[i]); free(strs); } #endif } KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL _krb5_einval(krb5_context context, const char *func, unsigned long argn) { #ifndef HEIMDAL_SMALLER krb5_set_error_message(context, EINVAL, N_("programmer error: invalid argument to %s argument %lu", "function:line"), func, argn); if (_krb5_have_debug(context, 10)) { _krb5_debug(context, 10, "invalid argument to function %s argument %lu", func, argn); _krb5_debug_backtrace(context); } #endif return EINVAL; } heimdal-7.5.0/lib/krb5/krb5_acl_match_file.cat30000644000175000017500000000525413212450756017307 0ustar niknik KRB5_ACL_MATCH_FILE(3) BSD Library Functions Manual KRB5_ACL_MATCH_FILE(3) NNAAMMEE kkrrbb55__aaccll__mmaattcchh__ffiillee, kkrrbb55__aaccll__mmaattcchh__ssttrriinngg -- ACL matching functions LLIIBBRRAARRYY Kerberos 5 Library (libkrb5, -lkrb5) SSYYNNOOPPSSIISS _k_r_b_5___e_r_r_o_r___c_o_d_e kkrrbb55__aaccll__mmaattcchh__ffiillee(_k_r_b_5___c_o_n_t_e_x_t _c_o_n_t_e_x_t, _c_o_n_s_t _c_h_a_r _*_f_i_l_e, _c_o_n_s_t _c_h_a_r _*_f_o_r_m_a_t, _._._.); _k_r_b_5___e_r_r_o_r___c_o_d_e kkrrbb55__aaccll__mmaattcchh__ssttrriinngg(_k_r_b_5___c_o_n_t_e_x_t _c_o_n_t_e_x_t, _c_o_n_s_t _c_h_a_r _*_s_t_r_i_n_g, _c_o_n_s_t _c_h_a_r _*_f_o_r_m_a_t, _._._.); DDEESSCCRRIIPPTTIIOONN kkrrbb55__aaccll__mmaattcchh__ffiillee matches ACL format against each line in a file. Lines starting with # are treated like comments and ignored. kkrrbb55__aaccll__mmaattcchh__ssttrriinngg matches ACL format against a string. The ACL format has three format specifiers: s, f, and r. Each specifier will retrieve one argument from the variable arguments for either match- ing or storing data. The input string is split up using " " and "\t" as a delimiter; multiple " " and "\t" in a row are considered to be the same. s Matches a string using strcmp(3) (case sensitive). f Matches the string with fnmatch(3). The _f_l_a_g_s argument (the last argument) passed to the fnmatch function is 0. r Returns a copy of the string in the char ** passed in; the copy must be freed with free(3). There is no need to free(3) the string on error: the function will clean up and set the pointer to NULL. All unknown format specifiers cause an error. EEXXAAMMPPLLEESS char *s; ret = krb5_acl_match_string(context, "foo", "s", "foo"); if (ret) krb5_errx(context, 1, "acl didn't match"); ret = krb5_acl_match_string(context, "foo foo baz/kaka", "ss", "foo", &s, "foo/*"); if (ret) { /* no need to free(s) on error */ assert(s == NULL); krb5_errx(context, 1, "acl didn't match"); } free(s); SSEEEE AALLSSOO krb5(3) HEIMDAL May 12, 2006 HEIMDAL heimdal-7.5.0/lib/krb5/krb5_create_checksum.30000644000175000017500000001402213026237312017015 0ustar niknik.\" Copyright (c) 1999-2005 Kungliga Tekniska Högskolan .\" (Royal Institute of Technology, Stockholm, Sweden). .\" All rights reserved. .\" .\" Redistribution and use in source and binary forms, with or without .\" modification, are permitted provided that the following conditions .\" are met: .\" .\" 1. Redistributions of source code must retain the above copyright .\" notice, this list of conditions and the following disclaimer. .\" .\" 2. Redistributions in binary form must reproduce the above copyright .\" notice, this list of conditions and the following disclaimer in the .\" documentation and/or other materials provided with the distribution. .\" .\" 3. Neither the name of the Institute nor the names of its contributors .\" may be used to endorse or promote products derived from this software .\" without specific prior written permission. .\" .\" THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND .\" ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE .\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE .\" ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE .\" FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL .\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS .\" OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) .\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT .\" LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF .\" SUCH DAMAGE. .\" .\" $Id$ .\" .Dd August 12, 2005 .Dt NAME 3 .Os HEIMDAL .Sh NAME .Nm krb5_checksum , .Nm krb5_checksum_disable , .Nm krb5_checksum_is_collision_proof , .Nm krb5_checksum_is_keyed , .Nm krb5_checksumsize , .Nm krb5_cksumtype_valid , .Nm krb5_copy_checksum , .Nm krb5_create_checksum , .Nm krb5_crypto_get_checksum_type .Nm krb5_free_checksum , .Nm krb5_free_checksum_contents , .Nm krb5_hmac , .Nm krb5_verify_checksum .Nd creates, handles and verifies checksums .Sh LIBRARY Kerberos 5 Library (libkrb5, -lkrb5) .Sh SYNOPSIS .In krb5.h .Pp .Li "typedef Checksum krb5_checksum;" .Ft void .Fo krb5_checksum_disable .Fa "krb5_context context" .Fa "krb5_cksumtype type" .Fc .Ft krb5_boolean .Fo krb5_checksum_is_collision_proof .Fa "krb5_context context" .Fa "krb5_cksumtype type" .Fc .Ft krb5_boolean .Fo krb5_checksum_is_keyed .Fa "krb5_context context" .Fa "krb5_cksumtype type" .Fc .Ft krb5_error_code .Fo krb5_cksumtype_valid .Fa "krb5_context context" .Fa "krb5_cksumtype ctype" .Fc .Ft krb5_error_code .Fo krb5_checksumsize .Fa "krb5_context context" .Fa "krb5_cksumtype type" .Fa "size_t *size" .Fc .Ft krb5_error_code .Fo krb5_create_checksum .Fa "krb5_context context" .Fa "krb5_crypto crypto" .Fa "krb5_key_usage usage" .Fa "int type" .Fa "void *data" .Fa "size_t len" .Fa "Checksum *result" .Fc .Ft krb5_error_code .Fo krb5_verify_checksum .Fa "krb5_context context" .Fa "krb5_crypto crypto" .Fa "krb5_key_usage usage" .Fa "void *data" .Fa "size_t len" .Fa "Checksum *cksum" .Fc .Ft krb5_error_code .Fo krb5_crypto_get_checksum_type .Fa "krb5_context context" .Fa "krb5_crypto crypto" .Fa "krb5_cksumtype *type" .Fc .Ft void .Fo krb5_free_checksum .Fa "krb5_context context" .Fa "krb5_checksum *cksum" .Fc .Ft void .Fo krb5_free_checksum_contents .Fa "krb5_context context" .Fa "krb5_checksum *cksum" .Fc .Ft krb5_error_code .Fo krb5_hmac .Fa "krb5_context context" .Fa "krb5_cksumtype cktype" .Fa "const void *data" .Fa "size_t len" .Fa "unsigned usage" .Fa "krb5_keyblock *key" .Fa "Checksum *result" .Fc .Ft krb5_error_code .Fo krb5_copy_checksum .Fa "krb5_context context" .Fa "const krb5_checksum *old" .Fa "krb5_checksum **new" .Fc .Sh DESCRIPTION The .Li krb5_checksum structure holds a Kerberos checksum. There is no component inside .Li krb5_checksum that is directly referable. .Pp The functions are used to create and verify checksums. .Fn krb5_create_checksum creates a checksum of the specified data, and puts it in .Fa result . If .Fa crypto is .Dv NULL , .Fa usage_or_type specifies the checksum type to use; it must not be keyed. Otherwise .Fa crypto is an encryption context created by .Fn krb5_crypto_init , and .Fa usage_or_type specifies a key-usage. .Pp .Fn krb5_verify_checksum verifies the .Fa checksum against the provided data. .Pp .Fn krb5_checksum_is_collision_proof returns true is the specified checksum is collision proof (that it's very unlikely that two strings has the same hash value, and that it's hard to find two strings that has the same hash). Examples of collision proof checksums are MD5, and SHA1, while CRC32 is not. .Pp .Fn krb5_checksum_is_keyed returns true if the specified checksum type is keyed (that the hash value is a function of both the data, and a separate key). Examples of keyed hash algorithms are HMAC-SHA1-DES3, and RSA-MD5-DES. The .Dq plain hash functions MD5, and SHA1 are not keyed. .Pp .Fn krb5_crypto_get_checksum_type returns the checksum type that will be used when creating a checksum for the given .Fa crypto context. This function is useful in combination with .Fn krb5_checksumsize when you want to know the size a checksum will use when you create it. .Pp .Fn krb5_cksumtype_valid returns 0 or an error if the checksumtype is implemented and not currently disabled in this kerberos library. .Pp .Fn krb5_checksumsize returns the size of the outdata of checksum function. .Pp .Fn krb5_copy_checksum returns a copy of the checksum .Fn krb5_free_checksum should use used to free the .Fa new checksum. .Pp .Fn krb5_free_checksum free the checksum and the content of the checksum. .Pp .Fn krb5_free_checksum_contents frees the content of checksum in .Fa cksum . .Pp .Fn krb5_hmac calculates the HMAC over .Fa data (with length .Fa len ) using the keyusage .Fa usage and keyblock .Fa key . Note that keyusage is not always used in checksums. .Pp .Nm krb5_checksum_disable globally disables the checksum type. .\" .Sh EXAMPLE .\" .Sh BUGS .Sh SEE ALSO .Xr krb5_crypto_init 3 , .Xr krb5_c_encrypt 3 , .Xr krb5_encrypt 3 heimdal-7.5.0/lib/krb5/digest.c0000644000175000017500000007246213026237312014320 0ustar niknik/* * Copyright (c) 2006 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "krb5_locl.h" #include "digest_asn1.h" #ifndef HEIMDAL_SMALLER struct krb5_digest_data { char *cbtype; char *cbbinding; DigestInit init; DigestInitReply initReply; DigestRequest request; DigestResponse response; }; KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_digest_alloc(krb5_context context, krb5_digest *digest) { krb5_digest d; d = calloc(1, sizeof(*d)); if (d == NULL) { *digest = NULL; return krb5_enomem(context); } *digest = d; return 0; } KRB5_LIB_FUNCTION void KRB5_LIB_CALL krb5_digest_free(krb5_digest digest) { if (digest == NULL) return; free_DigestInit(&digest->init); free_DigestInitReply(&digest->initReply); free_DigestRequest(&digest->request); free_DigestResponse(&digest->response); memset(digest, 0, sizeof(*digest)); free(digest); return; } KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_digest_set_server_cb(krb5_context context, krb5_digest digest, const char *type, const char *binding) { if (digest->init.channel) { krb5_set_error_message(context, EINVAL, N_("server channel binding already set", "")); return EINVAL; } digest->init.channel = calloc(1, sizeof(*digest->init.channel)); if (digest->init.channel == NULL) goto error; digest->init.channel->cb_type = strdup(type); if (digest->init.channel->cb_type == NULL) goto error; digest->init.channel->cb_binding = strdup(binding); if (digest->init.channel->cb_binding == NULL) goto error; return 0; error: if (digest->init.channel) { free(digest->init.channel->cb_type); free(digest->init.channel->cb_binding); free(digest->init.channel); digest->init.channel = NULL; } return krb5_enomem(context); } KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_digest_set_type(krb5_context context, krb5_digest digest, const char *type) { if (digest->init.type) { krb5_set_error_message(context, EINVAL, "client type already set"); return EINVAL; } digest->init.type = strdup(type); if (digest->init.type == NULL) return krb5_enomem(context); return 0; } KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_digest_set_hostname(krb5_context context, krb5_digest digest, const char *hostname) { if (digest->init.hostname) { krb5_set_error_message(context, EINVAL, "server hostname already set"); return EINVAL; } digest->init.hostname = malloc(sizeof(*digest->init.hostname)); if (digest->init.hostname == NULL) return krb5_enomem(context); *digest->init.hostname = strdup(hostname); if (*digest->init.hostname == NULL) { free(digest->init.hostname); digest->init.hostname = NULL; return krb5_enomem(context); } return 0; } KRB5_LIB_FUNCTION const char * KRB5_LIB_CALL krb5_digest_get_server_nonce(krb5_context context, krb5_digest digest) { return digest->initReply.nonce; } KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_digest_set_server_nonce(krb5_context context, krb5_digest digest, const char *nonce) { if (digest->request.serverNonce) { krb5_set_error_message(context, EINVAL, N_("nonce already set", "")); return EINVAL; } digest->request.serverNonce = strdup(nonce); if (digest->request.serverNonce == NULL) return krb5_enomem(context); return 0; } KRB5_LIB_FUNCTION const char * KRB5_LIB_CALL krb5_digest_get_opaque(krb5_context context, krb5_digest digest) { return digest->initReply.opaque; } KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_digest_set_opaque(krb5_context context, krb5_digest digest, const char *opaque) { if (digest->request.opaque) { krb5_set_error_message(context, EINVAL, "opaque already set"); return EINVAL; } digest->request.opaque = strdup(opaque); if (digest->request.opaque == NULL) return krb5_enomem(context); return 0; } KRB5_LIB_FUNCTION const char * KRB5_LIB_CALL krb5_digest_get_identifier(krb5_context context, krb5_digest digest) { if (digest->initReply.identifier == NULL) return NULL; return *digest->initReply.identifier; } KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_digest_set_identifier(krb5_context context, krb5_digest digest, const char *id) { if (digest->request.identifier) { krb5_set_error_message(context, EINVAL, N_("identifier already set", "")); return EINVAL; } digest->request.identifier = calloc(1, sizeof(*digest->request.identifier)); if (digest->request.identifier == NULL) return krb5_enomem(context); *digest->request.identifier = strdup(id); if (*digest->request.identifier == NULL) { free(digest->request.identifier); digest->request.identifier = NULL; return krb5_enomem(context); } return 0; } static krb5_error_code digest_request(krb5_context context, krb5_realm realm, krb5_ccache ccache, krb5_key_usage usage, const DigestReqInner *ireq, DigestRepInner *irep) { DigestREQ req; DigestREP rep; krb5_error_code ret; krb5_data data, data2; size_t size = 0; krb5_crypto crypto = NULL; krb5_auth_context ac = NULL; krb5_principal principal = NULL; krb5_ccache id = NULL; krb5_realm r = NULL; krb5_data_zero(&data); krb5_data_zero(&data2); memset(&req, 0, sizeof(req)); memset(&rep, 0, sizeof(rep)); if (ccache == NULL) { ret = krb5_cc_default(context, &id); if (ret) goto out; } else id = ccache; if (realm == NULL) { ret = krb5_get_default_realm(context, &r); if (ret) goto out; } else r = realm; /* * */ ret = krb5_make_principal(context, &principal, r, KRB5_DIGEST_NAME, r, NULL); if (ret) goto out; ASN1_MALLOC_ENCODE(DigestReqInner, data.data, data.length, ireq, &size, ret); if (ret) { krb5_set_error_message(context, ret, N_("Failed to encode digest inner request", "")); goto out; } if (size != data.length) krb5_abortx(context, "ASN.1 internal encoder error"); ret = krb5_mk_req_exact(context, &ac, AP_OPTS_USE_SUBKEY|AP_OPTS_MUTUAL_REQUIRED, principal, NULL, id, &req.apReq); if (ret) goto out; { krb5_keyblock *key; ret = krb5_auth_con_getlocalsubkey(context, ac, &key); if (ret) goto out; if (key == NULL) { ret = EINVAL; krb5_set_error_message(context, ret, N_("Digest failed to get local subkey", "")); goto out; } ret = krb5_crypto_init(context, key, 0, &crypto); krb5_free_keyblock (context, key); if (ret) goto out; } ret = krb5_encrypt_EncryptedData(context, crypto, usage, data.data, data.length, 0, &req.innerReq); if (ret) goto out; krb5_data_free(&data); ASN1_MALLOC_ENCODE(DigestREQ, data.data, data.length, &req, &size, ret); if (ret) { krb5_set_error_message(context, ret, N_("Failed to encode DigestREQest", "")); goto out; } if (size != data.length) krb5_abortx(context, "ASN.1 internal encoder error"); ret = krb5_sendto_kdc(context, &data, &r, &data2); if (ret) goto out; ret = decode_DigestREP(data2.data, data2.length, &rep, NULL); if (ret) { krb5_set_error_message(context, ret, N_("Failed to parse digest response", "")); goto out; } { krb5_ap_rep_enc_part *repl; ret = krb5_rd_rep(context, ac, &rep.apRep, &repl); if (ret) goto out; krb5_free_ap_rep_enc_part(context, repl); } { krb5_keyblock *key; ret = krb5_auth_con_getremotesubkey(context, ac, &key); if (ret) goto out; if (key == NULL) { ret = EINVAL; krb5_set_error_message(context, ret, N_("Digest reply have no remote subkey", "")); goto out; } krb5_crypto_destroy(context, crypto); ret = krb5_crypto_init(context, key, 0, &crypto); krb5_free_keyblock (context, key); if (ret) goto out; } krb5_data_free(&data); ret = krb5_decrypt_EncryptedData(context, crypto, usage, &rep.innerRep, &data); if (ret) goto out; ret = decode_DigestRepInner(data.data, data.length, irep, NULL); if (ret) { krb5_set_error_message(context, ret, N_("Failed to decode digest inner reply", "")); goto out; } out: if (ccache == NULL && id) krb5_cc_close(context, id); if (realm == NULL && r) free(r); if (crypto) krb5_crypto_destroy(context, crypto); if (ac) krb5_auth_con_free(context, ac); if (principal) krb5_free_principal(context, principal); krb5_data_free(&data); krb5_data_free(&data2); free_DigestREQ(&req); free_DigestREP(&rep); return ret; } KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_digest_init_request(krb5_context context, krb5_digest digest, krb5_realm realm, krb5_ccache ccache) { DigestReqInner ireq; DigestRepInner irep; krb5_error_code ret; memset(&ireq, 0, sizeof(ireq)); memset(&irep, 0, sizeof(irep)); if (digest->init.type == NULL) { krb5_set_error_message(context, EINVAL, N_("Type missing from init req", "")); return EINVAL; } ireq.element = choice_DigestReqInner_init; ireq.u.init = digest->init; ret = digest_request(context, realm, ccache, KRB5_KU_DIGEST_ENCRYPT, &ireq, &irep); if (ret) goto out; if (irep.element == choice_DigestRepInner_error) { ret = irep.u.error.code; krb5_set_error_message(context, ret, N_("Digest init error: %s", ""), irep.u.error.reason); goto out; } if (irep.element != choice_DigestRepInner_initReply) { ret = EINVAL; krb5_set_error_message(context, ret, N_("digest reply not an initReply", "")); goto out; } ret = copy_DigestInitReply(&irep.u.initReply, &digest->initReply); if (ret) { krb5_set_error_message(context, ret, N_("Failed to copy initReply", "")); goto out; } out: free_DigestRepInner(&irep); return ret; } KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_digest_set_client_nonce(krb5_context context, krb5_digest digest, const char *nonce) { if (digest->request.clientNonce) { krb5_set_error_message(context, EINVAL, N_("clientNonce already set", "")); return EINVAL; } digest->request.clientNonce = calloc(1, sizeof(*digest->request.clientNonce)); if (digest->request.clientNonce == NULL) return krb5_enomem(context); *digest->request.clientNonce = strdup(nonce); if (*digest->request.clientNonce == NULL) { free(digest->request.clientNonce); digest->request.clientNonce = NULL; return krb5_enomem(context); } return 0; } KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_digest_set_digest(krb5_context context, krb5_digest digest, const char *dgst) { if (digest->request.digest) { krb5_set_error_message(context, EINVAL, N_("digest already set", "")); return EINVAL; } digest->request.digest = strdup(dgst); if (digest->request.digest == NULL) return krb5_enomem(context); return 0; } KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_digest_set_username(krb5_context context, krb5_digest digest, const char *username) { if (digest->request.username) { krb5_set_error_message(context, EINVAL, "username already set"); return EINVAL; } digest->request.username = strdup(username); if (digest->request.username == NULL) return krb5_enomem(context); return 0; } KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_digest_set_authid(krb5_context context, krb5_digest digest, const char *authid) { if (digest->request.authid) { krb5_set_error_message(context, EINVAL, "authid already set"); return EINVAL; } digest->request.authid = malloc(sizeof(*digest->request.authid)); if (digest->request.authid == NULL) return krb5_enomem(context); *digest->request.authid = strdup(authid); if (*digest->request.authid == NULL) { free(digest->request.authid); digest->request.authid = NULL; return krb5_enomem(context); } return 0; } KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_digest_set_authentication_user(krb5_context context, krb5_digest digest, krb5_principal authentication_user) { krb5_error_code ret; if (digest->request.authentication_user) { krb5_set_error_message(context, EINVAL, N_("authentication_user already set", "")); return EINVAL; } ret = krb5_copy_principal(context, authentication_user, &digest->request.authentication_user); if (ret) return ret; return 0; } KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_digest_set_realm(krb5_context context, krb5_digest digest, const char *realm) { if (digest->request.realm) { krb5_set_error_message(context, EINVAL, "realm already set"); return EINVAL; } digest->request.realm = malloc(sizeof(*digest->request.realm)); if (digest->request.realm == NULL) return krb5_enomem(context); *digest->request.realm = strdup(realm); if (*digest->request.realm == NULL) { free(digest->request.realm); digest->request.realm = NULL; return krb5_enomem(context); } return 0; } KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_digest_set_method(krb5_context context, krb5_digest digest, const char *method) { if (digest->request.method) { krb5_set_error_message(context, EINVAL, N_("method already set", "")); return EINVAL; } digest->request.method = malloc(sizeof(*digest->request.method)); if (digest->request.method == NULL) return krb5_enomem(context); *digest->request.method = strdup(method); if (*digest->request.method == NULL) { free(digest->request.method); digest->request.method = NULL; return krb5_enomem(context); } return 0; } KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_digest_set_uri(krb5_context context, krb5_digest digest, const char *uri) { if (digest->request.uri) { krb5_set_error_message(context, EINVAL, N_("uri already set", "")); return EINVAL; } digest->request.uri = malloc(sizeof(*digest->request.uri)); if (digest->request.uri == NULL) return krb5_enomem(context); *digest->request.uri = strdup(uri); if (*digest->request.uri == NULL) { free(digest->request.uri); digest->request.uri = NULL; return krb5_enomem(context); } return 0; } KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_digest_set_nonceCount(krb5_context context, krb5_digest digest, const char *nonce_count) { if (digest->request.nonceCount) { krb5_set_error_message(context, EINVAL, N_("nonceCount already set", "")); return EINVAL; } digest->request.nonceCount = malloc(sizeof(*digest->request.nonceCount)); if (digest->request.nonceCount == NULL) return krb5_enomem(context); *digest->request.nonceCount = strdup(nonce_count); if (*digest->request.nonceCount == NULL) { free(digest->request.nonceCount); digest->request.nonceCount = NULL; return krb5_enomem(context); } return 0; } KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_digest_set_qop(krb5_context context, krb5_digest digest, const char *qop) { if (digest->request.qop) { krb5_set_error_message(context, EINVAL, "qop already set"); return EINVAL; } digest->request.qop = malloc(sizeof(*digest->request.qop)); if (digest->request.qop == NULL) return krb5_enomem(context); *digest->request.qop = strdup(qop); if (*digest->request.qop == NULL) { free(digest->request.qop); digest->request.qop = NULL; return krb5_enomem(context); } return 0; } KRB5_LIB_FUNCTION int KRB5_LIB_CALL krb5_digest_set_responseData(krb5_context context, krb5_digest digest, const char *response) { digest->request.responseData = strdup(response); if (digest->request.responseData == NULL) return krb5_enomem(context); return 0; } KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_digest_request(krb5_context context, krb5_digest digest, krb5_realm realm, krb5_ccache ccache) { DigestReqInner ireq; DigestRepInner irep; krb5_error_code ret; memset(&ireq, 0, sizeof(ireq)); memset(&irep, 0, sizeof(irep)); ireq.element = choice_DigestReqInner_digestRequest; ireq.u.digestRequest = digest->request; if (digest->request.type == NULL) { if (digest->init.type == NULL) { krb5_set_error_message(context, EINVAL, N_("Type missing from req", "")); return EINVAL; } ireq.u.digestRequest.type = digest->init.type; } if (ireq.u.digestRequest.digest == NULL) { static char md5[] = "md5"; ireq.u.digestRequest.digest = md5; } ret = digest_request(context, realm, ccache, KRB5_KU_DIGEST_ENCRYPT, &ireq, &irep); if (ret) return ret; if (irep.element == choice_DigestRepInner_error) { ret = irep.u.error.code; krb5_set_error_message(context, ret, N_("Digest response error: %s", ""), irep.u.error.reason); goto out; } if (irep.element != choice_DigestRepInner_response) { krb5_set_error_message(context, EINVAL, N_("digest reply not an DigestResponse", "")); ret = EINVAL; goto out; } ret = copy_DigestResponse(&irep.u.response, &digest->response); if (ret) { krb5_set_error_message(context, ret, N_("Failed to copy initReply,", "")); goto out; } out: free_DigestRepInner(&irep); return ret; } KRB5_LIB_FUNCTION krb5_boolean KRB5_LIB_CALL krb5_digest_rep_get_status(krb5_context context, krb5_digest digest) { return digest->response.success ? TRUE : FALSE; } KRB5_LIB_FUNCTION const char * KRB5_LIB_CALL krb5_digest_get_rsp(krb5_context context, krb5_digest digest) { if (digest->response.rsp == NULL) return NULL; return *digest->response.rsp; } KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_digest_get_tickets(krb5_context context, krb5_digest digest, Ticket **tickets) { *tickets = NULL; return 0; } KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_digest_get_client_binding(krb5_context context, krb5_digest digest, char **type, char **binding) { if (digest->response.channel) { *type = strdup(digest->response.channel->cb_type); *binding = strdup(digest->response.channel->cb_binding); if (*type == NULL || *binding == NULL) { free(*type); free(*binding); return krb5_enomem(context); } } else { *type = NULL; *binding = NULL; } return 0; } KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_digest_get_session_key(krb5_context context, krb5_digest digest, krb5_data *data) { krb5_error_code ret; krb5_data_zero(data); if (digest->response.session_key == NULL) return 0; ret = der_copy_octet_string(digest->response.session_key, data); if (ret) krb5_clear_error_message(context); return ret; } struct krb5_ntlm_data { NTLMInit init; NTLMInitReply initReply; NTLMRequest request; NTLMResponse response; }; KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_ntlm_alloc(krb5_context context, krb5_ntlm *ntlm) { *ntlm = calloc(1, sizeof(**ntlm)); if (*ntlm == NULL) return krb5_enomem(context); return 0; } KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_ntlm_free(krb5_context context, krb5_ntlm ntlm) { free_NTLMInit(&ntlm->init); free_NTLMInitReply(&ntlm->initReply); free_NTLMRequest(&ntlm->request); free_NTLMResponse(&ntlm->response); memset(ntlm, 0, sizeof(*ntlm)); free(ntlm); return 0; } KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_ntlm_init_request(krb5_context context, krb5_ntlm ntlm, krb5_realm realm, krb5_ccache ccache, uint32_t flags, const char *hostname, const char *domainname) { DigestReqInner ireq; DigestRepInner irep; krb5_error_code ret; memset(&ireq, 0, sizeof(ireq)); memset(&irep, 0, sizeof(irep)); ntlm->init.flags = flags; if (hostname) { ALLOC(ntlm->init.hostname, 1); *ntlm->init.hostname = strdup(hostname); } if (domainname) { ALLOC(ntlm->init.domain, 1); *ntlm->init.domain = strdup(domainname); } ireq.element = choice_DigestReqInner_ntlmInit; ireq.u.ntlmInit = ntlm->init; ret = digest_request(context, realm, ccache, KRB5_KU_DIGEST_ENCRYPT, &ireq, &irep); if (ret) goto out; if (irep.element == choice_DigestRepInner_error) { ret = irep.u.error.code; krb5_set_error_message(context, ret, N_("Digest init error: %s", ""), irep.u.error.reason); goto out; } if (irep.element != choice_DigestRepInner_ntlmInitReply) { ret = EINVAL; krb5_set_error_message(context, ret, N_("ntlm reply not an initReply", "")); goto out; } ret = copy_NTLMInitReply(&irep.u.ntlmInitReply, &ntlm->initReply); if (ret) { krb5_set_error_message(context, ret, N_("Failed to copy initReply", "")); goto out; } out: free_DigestRepInner(&irep); return ret; } KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_ntlm_init_get_flags(krb5_context context, krb5_ntlm ntlm, uint32_t *flags) { *flags = ntlm->initReply.flags; return 0; } KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_ntlm_init_get_challenge(krb5_context context, krb5_ntlm ntlm, krb5_data *challenge) { krb5_error_code ret; ret = der_copy_octet_string(&ntlm->initReply.challenge, challenge); if (ret) krb5_clear_error_message(context); return ret; } KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_ntlm_init_get_opaque(krb5_context context, krb5_ntlm ntlm, krb5_data *opaque) { krb5_error_code ret; ret = der_copy_octet_string(&ntlm->initReply.opaque, opaque); if (ret) krb5_clear_error_message(context); return ret; } KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_ntlm_init_get_targetname(krb5_context context, krb5_ntlm ntlm, char **name) { *name = strdup(ntlm->initReply.targetname); if (*name == NULL) return krb5_enomem(context); return 0; } KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_ntlm_init_get_targetinfo(krb5_context context, krb5_ntlm ntlm, krb5_data *data) { krb5_error_code ret; if (ntlm->initReply.targetinfo == NULL) { krb5_data_zero(data); return 0; } ret = krb5_data_copy(data, ntlm->initReply.targetinfo->data, ntlm->initReply.targetinfo->length); if (ret) { krb5_clear_error_message(context); return ret; } return 0; } KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_ntlm_request(krb5_context context, krb5_ntlm ntlm, krb5_realm realm, krb5_ccache ccache) { DigestReqInner ireq; DigestRepInner irep; krb5_error_code ret; memset(&ireq, 0, sizeof(ireq)); memset(&irep, 0, sizeof(irep)); ireq.element = choice_DigestReqInner_ntlmRequest; ireq.u.ntlmRequest = ntlm->request; ret = digest_request(context, realm, ccache, KRB5_KU_DIGEST_ENCRYPT, &ireq, &irep); if (ret) return ret; if (irep.element == choice_DigestRepInner_error) { ret = irep.u.error.code; krb5_set_error_message(context, ret, N_("NTLM response error: %s", ""), irep.u.error.reason); goto out; } if (irep.element != choice_DigestRepInner_ntlmResponse) { ret = EINVAL; krb5_set_error_message(context, ret, N_("NTLM reply not an NTLMResponse", "")); goto out; } ret = copy_NTLMResponse(&irep.u.ntlmResponse, &ntlm->response); if (ret) { krb5_set_error_message(context, ret, N_("Failed to copy NTLMResponse", "")); goto out; } out: free_DigestRepInner(&irep); return ret; } KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_ntlm_req_set_flags(krb5_context context, krb5_ntlm ntlm, uint32_t flags) { ntlm->request.flags = flags; return 0; } KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_ntlm_req_set_username(krb5_context context, krb5_ntlm ntlm, const char *username) { ntlm->request.username = strdup(username); if (ntlm->request.username == NULL) return krb5_enomem(context); return 0; } KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_ntlm_req_set_targetname(krb5_context context, krb5_ntlm ntlm, const char *targetname) { ntlm->request.targetname = strdup(targetname); if (ntlm->request.targetname == NULL) return krb5_enomem(context); return 0; } KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_ntlm_req_set_lm(krb5_context context, krb5_ntlm ntlm, void *hash, size_t len) { ntlm->request.lm.data = malloc(len); if (ntlm->request.lm.data == NULL && len != 0) return krb5_enomem(context); ntlm->request.lm.length = len; memcpy(ntlm->request.lm.data, hash, len); return 0; } KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_ntlm_req_set_ntlm(krb5_context context, krb5_ntlm ntlm, void *hash, size_t len) { ntlm->request.ntlm.data = malloc(len); if (ntlm->request.ntlm.data == NULL && len != 0) return krb5_enomem(context); ntlm->request.ntlm.length = len; memcpy(ntlm->request.ntlm.data, hash, len); return 0; } KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_ntlm_req_set_opaque(krb5_context context, krb5_ntlm ntlm, krb5_data *opaque) { ntlm->request.opaque.data = malloc(opaque->length); if (ntlm->request.opaque.data == NULL && opaque->length != 0) return krb5_enomem(context); ntlm->request.opaque.length = opaque->length; memcpy(ntlm->request.opaque.data, opaque->data, opaque->length); return 0; } KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_ntlm_req_set_session(krb5_context context, krb5_ntlm ntlm, void *sessionkey, size_t length) { ntlm->request.sessionkey = calloc(1, sizeof(*ntlm->request.sessionkey)); if (ntlm->request.sessionkey == NULL) return krb5_enomem(context); ntlm->request.sessionkey->data = malloc(length); if (ntlm->request.sessionkey->data == NULL && length != 0) return krb5_enomem(context); memcpy(ntlm->request.sessionkey->data, sessionkey, length); ntlm->request.sessionkey->length = length; return 0; } KRB5_LIB_FUNCTION krb5_boolean KRB5_LIB_CALL krb5_ntlm_rep_get_status(krb5_context context, krb5_ntlm ntlm) { return ntlm->response.success ? TRUE : FALSE; } KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_ntlm_rep_get_sessionkey(krb5_context context, krb5_ntlm ntlm, krb5_data *data) { if (ntlm->response.sessionkey == NULL) { krb5_set_error_message(context, EINVAL, N_("no ntlm session key", "")); return EINVAL; } krb5_clear_error_message(context); return krb5_data_copy(data, ntlm->response.sessionkey->data, ntlm->response.sessionkey->length); } /** * Get the supported/allowed mechanism for this principal. * * @param context A Keberos context. * @param realm The realm of the KDC. * @param ccache The credential cache to use when talking to the KDC. * @param flags The supported mechanism. * * @return Return an error code or 0. * * @ingroup krb5_digest */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_digest_probe(krb5_context context, krb5_realm realm, krb5_ccache ccache, unsigned *flags) { DigestReqInner ireq; DigestRepInner irep; krb5_error_code ret; memset(&ireq, 0, sizeof(ireq)); memset(&irep, 0, sizeof(irep)); ireq.element = choice_DigestReqInner_supportedMechs; ret = digest_request(context, realm, ccache, KRB5_KU_DIGEST_ENCRYPT, &ireq, &irep); if (ret) goto out; if (irep.element == choice_DigestRepInner_error) { ret = irep.u.error.code; krb5_set_error_message(context, ret, "Digest probe error: %s", irep.u.error.reason); goto out; } if (irep.element != choice_DigestRepInner_supportedMechs) { ret = EINVAL; krb5_set_error_message(context, ret, "Digest reply not an probe"); goto out; } *flags = DigestTypes2int(irep.u.supportedMechs); out: free_DigestRepInner(&irep); return ret; } #endif /* HEIMDAL_SMALLER */ heimdal-7.5.0/lib/krb5/krbhst-test.c0000644000175000017500000000602112136107750015302 0ustar niknik/* * Copyright (c) 2001 - 2002 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "krb5_locl.h" #include #include static int version_flag = 0; static int help_flag = 0; static struct getargs args[] = { {"version", 0, arg_flag, &version_flag, "print version", NULL }, {"help", 0, arg_flag, &help_flag, NULL, NULL } }; static void usage (int ret) { arg_printusage (args, sizeof(args)/sizeof(*args), NULL, "[realms ...]"); exit (ret); } int main(int argc, char **argv) { int i, j; krb5_context context; int types[] = {KRB5_KRBHST_KDC, KRB5_KRBHST_ADMIN, KRB5_KRBHST_CHANGEPW, KRB5_KRBHST_KRB524}; const char *type_str[] = {"kdc", "admin", "changepw", "krb524"}; int optidx = 0; setprogname (argv[0]); if(getarg(args, sizeof(args) / sizeof(args[0]), argc, argv, &optidx)) usage(1); if (help_flag) usage (0); if(version_flag){ print_version(NULL); exit(0); } argc -= optidx; argv += optidx; krb5_init_context (&context); for(i = 0; i < argc; i++) { krb5_krbhst_handle handle; char host[MAXHOSTNAMELEN]; for (j = 0; j < sizeof(types)/sizeof(*types); ++j) { printf ("%s for %s:\n", type_str[j], argv[i]); krb5_krbhst_init(context, argv[i], types[j], &handle); while(krb5_krbhst_next_as_string(context, handle, host, sizeof(host)) == 0) printf("\thost: %s\n", host); krb5_krbhst_reset(context, handle); printf ("\n"); } } return 0; } heimdal-7.5.0/lib/krb5/krb5_is_thread_safe.cat30000644000175000017500000000172613212450757017336 0ustar niknik KRB5_IS_THREAD_SAFE(3) BSD Library Functions Manual KRB5_IS_THREAD_SAFE(3) NNAAMMEE kkrrbb55__iiss__tthhrreeaadd__ssaaffee -- is the Kerberos library compiled with multithread support LLIIBBRRAARRYY Kerberos 5 Library (libkrb5, -lkrb5) SSYYNNOOPPSSIISS ##iinncclluuddee <> _k_r_b_5___b_o_o_l_e_a_n kkrrbb55__iiss__tthhrreeaadd__ssaaffee(_v_o_i_d); DDEESSCCRRIIPPTTIIOONN kkrrbb55__iiss__tthhrreeaadd__ssaaffee returns TRUE if the library was compiled with with multithread support. If the library isn't compiled, the consumer have to use a global lock to make sure Kerboros functions are not called at the same time by different threads. SSEEEE AALLSSOO krb5_create_checksum(3), krb5_encrypt(3) HEIMDAL May 5, 2006 HEIMDAL heimdal-7.5.0/lib/krb5/krb5_encrypt.30000644000175000017500000001577513026237312015374 0ustar niknik.\" Copyright (c) 1999 - 2004 Kungliga Tekniska Högskolan .\" (Royal Institute of Technology, Stockholm, Sweden). .\" All rights reserved. .\" .\" Redistribution and use in source and binary forms, with or without .\" modification, are permitted provided that the following conditions .\" are met: .\" .\" 1. Redistributions of source code must retain the above copyright .\" notice, this list of conditions and the following disclaimer. .\" .\" 2. Redistributions in binary form must reproduce the above copyright .\" notice, this list of conditions and the following disclaimer in the .\" documentation and/or other materials provided with the distribution. .\" .\" 3. Neither the name of the Institute nor the names of its contributors .\" may be used to endorse or promote products derived from this software .\" without specific prior written permission. .\" .\" THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND .\" ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE .\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE .\" ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE .\" FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL .\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS .\" OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) .\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT .\" LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF .\" SUCH DAMAGE. .\" .\" $Id$ .\" .Dd March 20, 2004 .Dt KRB5_ENCRYPT 3 .Os HEIMDAL .Sh NAME .Nm krb5_crypto_getblocksize , .Nm krb5_crypto_getconfoundersize .Nm krb5_crypto_getenctype , .Nm krb5_crypto_getpadsize , .Nm krb5_crypto_overhead , .Nm krb5_decrypt , .Nm krb5_decrypt_EncryptedData , .Nm krb5_decrypt_ivec , .Nm krb5_decrypt_ticket , .Nm krb5_encrypt , .Nm krb5_encrypt_EncryptedData , .Nm krb5_encrypt_ivec , .Nm krb5_enctype_disable , .Nm krb5_enctype_keysize , .Nm krb5_enctype_to_string , .Nm krb5_enctype_valid , .Nm krb5_get_wrapped_length , .Nm krb5_string_to_enctype .Nd "encrypt and decrypt data, set and get encryption type parameters" .Sh LIBRARY Kerberos 5 Library (libkrb5, -lkrb5) .Sh SYNOPSIS .In krb5.h .Ft krb5_error_code .Fo krb5_encrypt .Fa "krb5_context context" .Fa "krb5_crypto crypto" .Fa "unsigned usage" .Fa "void *data" .Fa "size_t len" .Fa "krb5_data *result" .Fc .Ft krb5_error_code .Fo krb5_encrypt_EncryptedData .Fa "krb5_context context" .Fa "krb5_crypto crypto" .Fa "unsigned usage" .Fa "void *data" .Fa "size_t len" .Fa "int kvno" .Fa "EncryptedData *result" .Fc .Ft krb5_error_code .Fo krb5_encrypt_ivec .Fa "krb5_context context" .Fa "krb5_crypto crypto" .Fa "unsigned usage" .Fa "void *data" .Fa "size_t len" .Fa "krb5_data *result" .Fa "void *ivec" .Fc .Ft krb5_error_code .Fo krb5_decrypt .Fa "krb5_context context" .Fa "krb5_crypto crypto" .Fa "unsigned usage" .Fa "void *data" .Fa "size_t len" .Fa "krb5_data *result" .Fc .Ft krb5_error_code .Fo krb5_decrypt_EncryptedData .Fa "krb5_context context" .Fa "krb5_crypto crypto" .Fa "unsigned usage" .Fa "EncryptedData *e" .Fa "krb5_data *result" .Fc .Ft krb5_error_code .Fo krb5_decrypt_ivec .Fa "krb5_context context" .Fa "krb5_crypto crypto" .Fa "unsigned usage" .Fa "void *data" .Fa "size_t len" .Fa "krb5_data *result" .Fa "void *ivec" .Fc .Ft krb5_error_code .Fo krb5_decrypt_ticket .Fa "krb5_context context" .Fa "Ticket *ticket" .Fa "krb5_keyblock *key" .Fa "EncTicketPart *out" .Fa "krb5_flags flags" .Fc .Ft krb5_error_code .Fo krb5_crypto_getblocksize .Fa "krb5_context context" .Fa "size_t *blocksize" .Fc .Ft krb5_error_code .Fo krb5_crypto_getenctype .Fa "krb5_context context" .Fa "krb5_crypto crypto" .Fa "krb5_enctype *enctype" .Fc .Ft krb5_error_code .Fo krb5_crypto_getpadsize .Fa "krb5_context context" .Fa size_t *padsize" .Fc .Ft krb5_error_code .Fo krb5_crypto_getconfoundersize .Fa "krb5_context context" .Fa "krb5_crypto crypto" .Fa size_t *confoundersize" .Fc .Ft krb5_error_code .Fo krb5_enctype_keysize .Fa "krb5_context context" .Fa "krb5_enctype type" .Fa "size_t *keysize" .Fc .Ft krb5_error_code .Fo krb5_crypto_overhead .Fa "krb5_context context" .Fa size_t *padsize" .Fc .Ft krb5_error_code .Fo krb5_string_to_enctype .Fa "krb5_context context" .Fa "const char *string" .Fa "krb5_enctype *etype" .Fc .Ft krb5_error_code .Fo krb5_enctype_to_string .Fa "krb5_context context" .Fa "krb5_enctype etype" .Fa "char **string" .Fc .Ft krb5_error_code .Fo krb5_enctype_valid .Fa "krb5_context context" .Fa "krb5_enctype etype" .Fc .Ft void .Fo krb5_enctype_disable .Fa "krb5_context context" .Fa "krb5_enctype etype" .Fc .Ft size_t .Fo krb5_get_wrapped_length .Fa "krb5_context context" .Fa "krb5_crypto crypto" .Fa "size_t data_len" .Fc .Sh DESCRIPTION These functions are used to encrypt and decrypt data. .Pp .Fn krb5_encrypt_ivec puts the encrypted version of .Fa data (of size .Fa len ) in .Fa result . If the encryption type supports using derived keys, .Fa usage should be the appropriate key-usage. .Fa ivec is a pointer to a initial IV, it is modified to the end IV at the end of the round. Ivec should be the size of If .Dv NULL is passed in, the default IV is used. .Fn krb5_encrypt does the same as .Fn krb5_encrypt_ivec but with .Fa ivec being .Dv NULL . .Fn krb5_encrypt_EncryptedData does the same as .Fn krb5_encrypt , but it puts the encrypted data in a .Fa EncryptedData structure instead. If .Fa kvno is not zero, it will be put in the (optional) .Fa kvno field in the .Fa EncryptedData . .Pp .Fn krb5_decrypt_ivec , .Fn krb5_decrypt , and .Fn krb5_decrypt_EncryptedData works similarly. .Pp .Fn krb5_decrypt_ticket decrypts the encrypted part of .Fa ticket with .Fa key . .Fn krb5_decrypt_ticket also verifies the timestamp in the ticket, invalid flag and if the KDC haven't verified the transited path, the transit path. .Pp .Fn krb5_enctype_keysize , .Fn krb5_crypto_getconfoundersize , .Fn krb5_crypto_getblocksize , .Fn krb5_crypto_getenctype , .Fn krb5_crypto_getpadsize , .Fn krb5_crypto_overhead all returns various (sometimes) useful information from a crypto context. .Fn krb5_crypto_overhead is the combination of krb5_crypto_getconfoundersize, krb5_crypto_getblocksize and krb5_crypto_getpadsize and return the maximum overhead size. .Pp .Fn krb5_enctype_to_string converts a encryption type number to a string that can be printable and stored. The strings returned should be freed with .Xr free 3 . .Pp .Fn krb5_string_to_enctype converts a encryption type strings to a encryption type number that can use used for other Kerberos crypto functions. .Pp .Fn krb5_enctype_valid returns 0 if the encrypt is supported and not disabled, otherwise and error code is returned. .Pp .Fn krb5_enctype_disable (globally, for all contextes) disables the .Fa enctype . .Pp .Fn krb5_get_wrapped_length returns the size of an encrypted packet by .Fa crypto of length .Fa data_len . .\" .Sh EXAMPLE .\" .Sh BUGS .Sh SEE ALSO .Xr krb5_create_checksum 3 , .Xr krb5_crypto_init 3 heimdal-7.5.0/lib/krb5/data.c0000644000175000017500000001311513026237312013740 0ustar niknik/* * Copyright (c) 1997 - 2007 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "krb5_locl.h" /** * Reset the (potentially uninitalized) krb5_data structure. * * @param p krb5_data to reset. * * @ingroup krb5 */ KRB5_LIB_FUNCTION void KRB5_LIB_CALL krb5_data_zero(krb5_data *p) { p->length = 0; p->data = NULL; } /** * Free the content of krb5_data structure, its ok to free a zeroed * structure (with memset() or krb5_data_zero()). When done, the * structure will be zeroed. The same function is called * krb5_free_data_contents() in MIT Kerberos. * * @param p krb5_data to free. * * @ingroup krb5 */ KRB5_LIB_FUNCTION void KRB5_LIB_CALL krb5_data_free(krb5_data *p) { free(p->data); krb5_data_zero(p); } /** * Free krb5_data (and its content). * * @param context Kerberos 5 context. * @param p krb5_data to free. * * @ingroup krb5 */ KRB5_LIB_FUNCTION void KRB5_LIB_CALL krb5_free_data(krb5_context context, krb5_data *p) { krb5_data_free(p); free(p); } /** * Allocate data of and krb5_data. * * @param p krb5_data to allocate. * @param len size to allocate. * * @return Returns 0 to indicate success. Otherwise an kerberos et * error code is returned. * * @ingroup krb5 */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_data_alloc(krb5_data *p, int len) { p->data = malloc(len); if(len && p->data == NULL) return ENOMEM; p->length = len; return 0; } /** * Grow (or shrink) the content of krb5_data to a new size. * * @param p krb5_data to free. * @param len new size. * * @return Returns 0 to indicate success. Otherwise an kerberos et * error code is returned. * * @ingroup krb5 */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_data_realloc(krb5_data *p, int len) { void *tmp; tmp = realloc(p->data, len); if(len && !tmp) return ENOMEM; p->data = tmp; p->length = len; return 0; } /** * Copy the data of len into the krb5_data. * * @param p krb5_data to copy into. * @param data data to copy.. * @param len new size. * * @return Returns 0 to indicate success. Otherwise an kerberos et * error code is returned. * * @ingroup krb5 */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_data_copy(krb5_data *p, const void *data, size_t len) { if (len) { if(krb5_data_alloc(p, len)) return ENOMEM; memmove(p->data, data, len); } else p->data = NULL; p->length = len; return 0; } /** * Copy the data into a newly allocated krb5_data. * * @param context Kerberos 5 context. * @param indata the krb5_data data to copy * @param outdata new krb5_date to copy too. Free with krb5_free_data(). * * @return Returns 0 to indicate success. Otherwise an kerberos et * error code is returned. * * @ingroup krb5 */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_copy_data(krb5_context context, const krb5_data *indata, krb5_data **outdata) { krb5_error_code ret; ALLOC(*outdata, 1); if(*outdata == NULL) return krb5_enomem(context); ret = der_copy_octet_string(indata, *outdata); if(ret) { krb5_clear_error_message (context); free(*outdata); *outdata = NULL; } return ret; } /** * Compare to data. * * @param data1 krb5_data to compare * @param data2 krb5_data to compare * * @return return the same way as memcmp(), useful when sorting. * * @ingroup krb5 */ KRB5_LIB_FUNCTION int KRB5_LIB_CALL krb5_data_cmp(const krb5_data *data1, const krb5_data *data2) { if (data1->length != data2->length) return data1->length - data2->length; return memcmp(data1->data, data2->data, data1->length); } /** * Compare to data not exposing timing information from the checksum data * * @param data1 krb5_data to compare * @param data2 krb5_data to compare * * @return returns zero for same data, otherwise non zero. * * @ingroup krb5 */ KRB5_LIB_FUNCTION int KRB5_LIB_CALL krb5_data_ct_cmp(const krb5_data *data1, const krb5_data *data2) { if (data1->length != data2->length) return data1->length - data2->length; return ct_memcmp(data1->data, data2->data, data1->length); } heimdal-7.5.0/lib/krb5/crypto-aes-sha2.c0000644000175000017500000001214113026237312015746 0ustar niknik/* * Copyright (c) 1997 - 2008 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "krb5_locl.h" /* * AES HMAC-SHA2 */ krb5_error_code _krb5_aes_sha2_md_for_enctype(krb5_context context, krb5_enctype enctype, const EVP_MD **md) { switch (enctype) { case ETYPE_AES128_CTS_HMAC_SHA256_128: *md = EVP_sha256(); break; case ETYPE_AES256_CTS_HMAC_SHA384_192: *md = EVP_sha384(); break; default: return KRB5_PROG_ETYPE_NOSUPP; break; } return 0; } static krb5_error_code SP_HMAC_SHA2_checksum(krb5_context context, struct _krb5_key_data *key, const void *data, size_t len, unsigned usage, Checksum *result) { krb5_error_code ret; const EVP_MD *md; unsigned char hmac[EVP_MAX_MD_SIZE]; unsigned int hmaclen = sizeof(hmac); ret = _krb5_aes_sha2_md_for_enctype(context, key->key->keytype, &md); if (ret) return ret; HMAC(md, key->key->keyvalue.data, key->key->keyvalue.length, data, len, hmac, &hmaclen); heim_assert(result->checksum.length <= hmaclen, "SHA2 internal error"); memcpy(result->checksum.data, hmac, result->checksum.length); return 0; } static struct _krb5_key_type keytype_aes128_sha2 = { KRB5_ENCTYPE_AES128_CTS_HMAC_SHA256_128, "aes-128-sha2", 128, 16, sizeof(struct _krb5_evp_schedule), NULL, _krb5_evp_schedule, _krb5_AES_SHA2_salt, NULL, _krb5_evp_cleanup, EVP_aes_128_cbc }; static struct _krb5_key_type keytype_aes256_sha2 = { KRB5_ENCTYPE_AES256_CTS_HMAC_SHA384_192, "aes-256-sha2", 256, 32, sizeof(struct _krb5_evp_schedule), NULL, _krb5_evp_schedule, _krb5_AES_SHA2_salt, NULL, _krb5_evp_cleanup, EVP_aes_256_cbc }; struct _krb5_checksum_type _krb5_checksum_hmac_sha256_128_aes128 = { CKSUMTYPE_HMAC_SHA256_128_AES128, "hmac-sha256-128-aes128", 64, 16, F_KEYED | F_CPROOF | F_DERIVED, SP_HMAC_SHA2_checksum, NULL }; struct _krb5_checksum_type _krb5_checksum_hmac_sha384_192_aes256 = { CKSUMTYPE_HMAC_SHA384_192_AES256, "hmac-sha384-192-aes256", 128, 24, F_KEYED | F_CPROOF | F_DERIVED, SP_HMAC_SHA2_checksum, NULL }; static krb5_error_code AES_SHA2_PRF(krb5_context context, krb5_crypto crypto, const krb5_data *in, krb5_data *out) { krb5_error_code ret; krb5_data label; const EVP_MD *md = NULL; ret = _krb5_aes_sha2_md_for_enctype(context, crypto->et->type, &md); if (ret) return ret; label.data = "prf"; label.length = 3; ret = krb5_data_alloc(out, EVP_MD_size(md)); if (ret) return ret; ret = _krb5_SP800_108_HMAC_KDF(context, &crypto->key.key->keyvalue, &label, in, md, out); if (ret) krb5_data_free(out); return ret; } struct _krb5_encryption_type _krb5_enctype_aes128_cts_hmac_sha256_128 = { ETYPE_AES128_CTS_HMAC_SHA256_128, "aes128-cts-hmac-sha256-128", "aes128-cts-sha256", 16, 1, 16, &keytype_aes128_sha2, NULL, /* should never be called */ &_krb5_checksum_hmac_sha256_128_aes128, F_DERIVED | F_ENC_THEN_CKSUM | F_SP800_108_HMAC_KDF, _krb5_evp_encrypt_cts, 16, AES_SHA2_PRF }; struct _krb5_encryption_type _krb5_enctype_aes256_cts_hmac_sha384_192 = { ETYPE_AES256_CTS_HMAC_SHA384_192, "aes256-cts-hmac-sha384-192", "aes256-cts-sha384", 16, 1, 16, &keytype_aes256_sha2, NULL, /* should never be called */ &_krb5_checksum_hmac_sha384_192_aes256, F_DERIVED | F_ENC_THEN_CKSUM | F_SP800_108_HMAC_KDF, _krb5_evp_encrypt_cts, 16, AES_SHA2_PRF }; heimdal-7.5.0/lib/krb5/krb5_krbhst_init.30000644000175000017500000001325212136107750016217 0ustar niknik.\" Copyright (c) 2001-2005 Kungliga Tekniska Högskolan .\" (Royal Institute of Technology, Stockholm, Sweden). .\" All rights reserved. .\" .\" Redistribution and use in source and binary forms, with or without .\" modification, are permitted provided that the following conditions .\" are met: .\" .\" 1. Redistributions of source code must retain the above copyright .\" notice, this list of conditions and the following disclaimer. .\" .\" 2. Redistributions in binary form must reproduce the above copyright .\" notice, this list of conditions and the following disclaimer in the .\" documentation and/or other materials provided with the distribution. .\" .\" 3. Neither the name of the Institute nor the names of its contributors .\" may be used to endorse or promote products derived from this software .\" without specific prior written permission. .\" .\" THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND .\" ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE .\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE .\" ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE .\" FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL .\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS .\" OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) .\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT .\" LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF .\" SUCH DAMAGE. .\" .\" $Id$ .\" .Dd May 10, 2005 .Dt KRB5_KRBHST_INIT 3 .Os HEIMDAL .Sh NAME .Nm krb5_krbhst_init , .Nm krb5_krbhst_init_flags , .Nm krb5_krbhst_next , .Nm krb5_krbhst_next_as_string , .Nm krb5_krbhst_reset , .Nm krb5_krbhst_free , .Nm krb5_krbhst_format_string , .Nm krb5_krbhst_get_addrinfo .Nd lookup Kerberos KDC hosts .Sh LIBRARY Kerberos 5 Library (libkrb5, -lkrb5) .Sh SYNOPSIS .In krb5.h .Ft krb5_error_code .Fn krb5_krbhst_init "krb5_context context" "const char *realm" "unsigned int type" "krb5_krbhst_handle *handle" .Ft krb5_error_code .Fn krb5_krbhst_init_flags "krb5_context context" "const char *realm" "unsigned int type" "int flags" "krb5_krbhst_handle *handle" .Ft krb5_error_code .Fn "krb5_krbhst_next" "krb5_context context" "krb5_krbhst_handle handle" "krb5_krbhst_info **host" .Ft krb5_error_code .Fn krb5_krbhst_next_as_string "krb5_context context" "krb5_krbhst_handle handle" "char *hostname" "size_t hostlen" .Ft void .Fn krb5_krbhst_reset "krb5_context context" "krb5_krbhst_handle handle" .Ft void .Fn krb5_krbhst_free "krb5_context context" "krb5_krbhst_handle handle" .Ft krb5_error_code .Fn krb5_krbhst_format_string "krb5_context context" "const krb5_krbhst_info *host" "char *hostname" "size_t hostlen" .Ft krb5_error_code .Fn krb5_krbhst_get_addrinfo "krb5_context context" "krb5_krbhst_info *host" "struct addrinfo **ai" .Sh DESCRIPTION These functions are used to sequence through all Kerberos hosts of a particular realm and service. The service type can be the KDCs, the administrative servers, the password changing servers, or the servers for Kerberos 4 ticket conversion. .Pp First a handle to a particular service is obtained by calling .Fn krb5_krbhst_init (or .Fn krb5_krbhst_init_flags ) with the .Fa realm of interest and the type of service to lookup. The .Fa type can be one of: .Pp .Bl -tag -width Ds -compact -offset indent .It KRB5_KRBHST_KDC .It KRB5_KRBHST_ADMIN .It KRB5_KRBHST_CHANGEPW .It KRB5_KRBHST_KRB524 .El .Pp The .Fa handle is returned to the caller, and should be passed to the other functions. .Pp The .Fa flag argument to .Nm krb5_krbhst_init_flags is the same flags as .Fn krb5_send_to_kdc_flags uses. Possible values are: .Pp .Bl -tag -width KRB5_KRBHST_FLAGS_LARGE_MSG -compact -offset indent .It KRB5_KRBHST_FLAGS_MASTER only talk to master (readwrite) KDC .It KRB5_KRBHST_FLAGS_LARGE_MSG this is a large message, so use transport that can handle that. .El .Pp For each call to .Fn krb5_krbhst_next information on a new host is returned. The former function returns in .Fa host a pointer to a structure containing information about the host, such as protocol, hostname, and port: .Bd -literal -offset indent typedef struct krb5_krbhst_info { enum { KRB5_KRBHST_UDP, KRB5_KRBHST_TCP, KRB5_KRBHST_HTTP } proto; unsigned short port; struct addrinfo *ai; struct krb5_krbhst_info *next; char hostname[1]; } krb5_krbhst_info; .Ed .Pp The related function, .Fn krb5_krbhst_next_as_string , return the same information as a URL-like string. .Pp When there are no more hosts, these functions return .Dv KRB5_KDC_UNREACH . .Pp To re-iterate over all hosts, call .Fn krb5_krbhst_reset and the next call to .Fn krb5_krbhst_next will return the first host. .Pp When done with the handle, .Fn krb5_krbhst_free should be called. .Pp To use a .Va krb5_krbhst_info , there are two functions: .Fn krb5_krbhst_format_string that will return a printable representation of that struct and .Fn krb5_krbhst_get_addrinfo that will return a .Va struct addrinfo that can then be used for communicating with the server mentioned. .Sh EXAMPLES The following code will print the KDCs of the realm .Dq MY.REALM : .Bd -literal -offset indent krb5_krbhst_handle handle; char host[MAXHOSTNAMELEN]; krb5_krbhst_init(context, "MY.REALM", KRB5_KRBHST_KDC, &handle); while(krb5_krbhst_next_as_string(context, handle, host, sizeof(host)) == 0) printf("%s\\n", host); krb5_krbhst_free(context, handle); .Ed .\" .Sh BUGS .Sh SEE ALSO .Xr getaddrinfo 3 , .Xr krb5_get_krbhst 3 , .Xr krb5_send_to_kdc_flags 3 .Sh HISTORY These functions first appeared in Heimdal 0.3g. heimdal-7.5.0/lib/krb5/crc.c0000644000175000017500000000437713026237312013610 0ustar niknik/* * Copyright (c) 1997 - 2000 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "krb5_locl.h" static u_long table[256]; #define CRC_GEN 0xEDB88320L KRB5_LIB_FUNCTION void KRB5_LIB_CALL _krb5_crc_init_table(void) { static int flag = 0; unsigned long crc, poly; unsigned int i, j; if(flag) return; poly = CRC_GEN; for (i = 0; i < 256; i++) { crc = i; for (j = 8; j > 0; j--) { if (crc & 1) { crc = (crc >> 1) ^ poly; } else { crc >>= 1; } } table[i] = crc; } flag = 1; } KRB5_LIB_FUNCTION uint32_t KRB5_LIB_CALL _krb5_crc_update (const char *p, size_t len, uint32_t res) { while (len--) res = table[(res ^ *p++) & 0xFF] ^ (res >> 8); return res & 0xFFFFFFFF; } heimdal-7.5.0/lib/krb5/test_renew.c0000644000175000017500000000633712136107750015221 0ustar niknik/* * Copyright (c) 2007 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of KTH nor the names of its contributors may be * used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY KTH AND ITS CONTRIBUTORS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL KTH OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "krb5_locl.h" #include #include static int version_flag = 0; static int help_flag = 0; static struct getargs args[] = { {"version", 0, arg_flag, &version_flag, "print version", NULL }, {"help", 0, arg_flag, &help_flag, NULL, NULL } }; static void usage (int ret) { arg_printusage (args, sizeof(args)/sizeof(*args), NULL, "[principal]"); exit (ret); } int main(int argc, char **argv) { krb5_principal client; krb5_context context; const char *in_tkt_service = NULL; krb5_ccache id; krb5_error_code ret; krb5_creds out; int optidx = 0; setprogname(argv[0]); if(getarg(args, sizeof(args) / sizeof(args[0]), argc, argv, &optidx)) usage(1); if (help_flag) usage (0); if(version_flag){ print_version(NULL); exit(0); } argc -= optidx; argv += optidx; if (argc > 0) in_tkt_service = argv[0]; memset(&out, 0, sizeof(out)); ret = krb5_init_context(&context); if (ret) krb5_err(context, 1, ret, "krb5_init_context"); ret = krb5_cc_default(context, &id); if (ret) krb5_err(context, 1, ret, "krb5_cc_default"); ret = krb5_cc_get_principal(context, id, &client); if (ret) krb5_err(context, 1, ret, "krb5_cc_default"); ret = krb5_get_renewed_creds(context, &out, client, id, in_tkt_service); if(ret) krb5_err(context, 1, ret, "krb5_get_renewed_creds"); if (krb5_principal_compare(context, out.client, client) != TRUE) krb5_errx(context, 1, "return principal is not as expected"); krb5_free_cred_contents(context, &out); krb5_free_context(context); return 0; } heimdal-7.5.0/lib/krb5/store_sock.c0000644000175000017500000000777713026237312015223 0ustar niknik/* * Copyright (c) 1997 - 2004 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "krb5_locl.h" #include "store-int.h" #ifdef _WIN32 #include #endif typedef struct socket_storage { krb5_socket_t sock; } socket_storage; #define SOCK(S) (((socket_storage*)(S)->data)->sock) static ssize_t socket_fetch(krb5_storage * sp, void *data, size_t size) { return net_read(SOCK(sp), data, size); } static ssize_t socket_store(krb5_storage * sp, const void *data, size_t size) { return net_write(SOCK(sp), data, size); } static off_t socket_seek(krb5_storage * sp, off_t offset, int whence) { return lseek(SOCK(sp), offset, whence); } static int socket_trunc(krb5_storage * sp, off_t offset) { if (ftruncate(SOCK(sp), offset) == -1) return errno; return 0; } static int socket_sync(krb5_storage * sp) { if (fsync(SOCK(sp)) == -1) return errno; return 0; } static void socket_free(krb5_storage * sp) { int save_errno = errno; if (rk_IS_SOCKET_ERROR(rk_closesocket(SOCK(sp)))) errno = rk_SOCK_ERRNO; else errno = save_errno; } /** * * * @return A krb5_storage on success, or NULL on out of memory error. * * @ingroup krb5_storage * * @sa krb5_storage_emem() * @sa krb5_storage_from_mem() * @sa krb5_storage_from_readonly_mem() * @sa krb5_storage_from_data() * @sa krb5_storage_from_fd() */ KRB5_LIB_FUNCTION krb5_storage * KRB5_LIB_CALL krb5_storage_from_socket(krb5_socket_t sock_in) { krb5_storage *sp; int saved_errno; krb5_socket_t sock; #ifdef _WIN32 WSAPROTOCOL_INFO info; if (WSADuplicateSocket(sock_in, GetCurrentProcessId(), &info) == 0) { sock = WSASocket( FROM_PROTOCOL_INFO, FROM_PROTOCOL_INFO, FROM_PROTOCOL_INFO, &info, 0, 0); } #else sock = dup(sock_in); #endif if (sock == rk_INVALID_SOCKET) return NULL; errno = ENOMEM; sp = malloc(sizeof(krb5_storage)); if (sp == NULL) { saved_errno = errno; rk_closesocket(sock); errno = saved_errno; return NULL; } errno = ENOMEM; sp->data = malloc(sizeof(socket_storage)); if (sp->data == NULL) { saved_errno = errno; rk_closesocket(sock); free(sp); errno = saved_errno; return NULL; } sp->flags = 0; sp->eof_code = HEIM_ERR_EOF; SOCK(sp) = sock; sp->fetch = socket_fetch; sp->store = socket_store; sp->seek = socket_seek; sp->trunc = socket_trunc; sp->fsync = socket_sync; sp->free = socket_free; sp->max_alloc = UINT_MAX/8; return sp; } heimdal-7.5.0/lib/krb5/krb5_check_transited.cat30000644000175000017500000000640213212450756017523 0ustar niknik KRB5_CHECK_TRANSITED(3) BSD Library Functions Manual KRB5_CHECK_TRANSITED(3) NNAAMMEE kkrrbb55__cchheecckk__ttrraannssiitteedd, kkrrbb55__cchheecckk__ttrraannssiitteedd__rreeaallmmss, kkrrbb55__ddoommaaiinn__xx550000__ddeeccooddee, kkrrbb55__ddoommaaiinn__xx550000__eennccooddee -- realm transit verifi- cation and encoding/decoding functions LLIIBBRRAARRYY Kerberos 5 Library (libkrb5, -lkrb5) SSYYNNOOPPSSIISS ##iinncclluuddee <> _k_r_b_5___e_r_r_o_r___c_o_d_e kkrrbb55__cchheecckk__ttrraannssiitteedd(_k_r_b_5___c_o_n_t_e_x_t _c_o_n_t_e_x_t, _k_r_b_5___c_o_n_s_t___r_e_a_l_m _c_l_i_e_n_t___r_e_a_l_m, _k_r_b_5___c_o_n_s_t___r_e_a_l_m _s_e_r_v_e_r___r_e_a_l_m, _k_r_b_5___r_e_a_l_m _*_r_e_a_l_m_s, _i_n_t _n_u_m___r_e_a_l_m_s, _i_n_t _*_b_a_d___r_e_a_l_m); _k_r_b_5___e_r_r_o_r___c_o_d_e kkrrbb55__cchheecckk__ttrraannssiitteedd__rreeaallmmss(_k_r_b_5___c_o_n_t_e_x_t _c_o_n_t_e_x_t, _c_o_n_s_t _c_h_a_r _*_c_o_n_s_t _*_r_e_a_l_m_s, _i_n_t _n_u_m___r_e_a_l_m_s, _i_n_t _*_b_a_d___r_e_a_l_m); _k_r_b_5___e_r_r_o_r___c_o_d_e kkrrbb55__ddoommaaiinn__xx550000__ddeeccooddee(_k_r_b_5___c_o_n_t_e_x_t _c_o_n_t_e_x_t, _k_r_b_5___d_a_t_a _t_r, _c_h_a_r _*_*_*_r_e_a_l_m_s, _i_n_t _*_n_u_m___r_e_a_l_m_s, _c_o_n_s_t _c_h_a_r _*_c_l_i_e_n_t___r_e_a_l_m, _c_o_n_s_t _c_h_a_r _*_s_e_r_v_e_r___r_e_a_l_m); _k_r_b_5___e_r_r_o_r___c_o_d_e kkrrbb55__ddoommaaiinn__xx550000__eennccooddee(_c_h_a_r _*_*_r_e_a_l_m_s, _i_n_t _n_u_m___r_e_a_l_m_s, _k_r_b_5___d_a_t_a _*_e_n_c_o_d_i_n_g); DDEESSCCRRIIPPTTIIOONN kkrrbb55__cchheecckk__ttrraannssiitteedd() checks the path from _c_l_i_e_n_t___r_e_a_l_m to _s_e_r_v_e_r___r_e_a_l_m where _r_e_a_l_m_s and _n_u_m___r_e_a_l_m_s is the realms between them. If the function returns an error value, _b_a_d___r_e_a_l_m will be set to the realm in the list causing the error. kkrrbb55__cchheecckk__ttrraannssiitteedd() is used internally by the KDC and libkrb5 and should not be called by client applications. kkrrbb55__cchheecckk__ttrraannssiitteedd__rreeaallmmss() is deprecated. kkrrbb55__ddoommaaiinn__xx550000__eennccooddee() and kkrrbb55__ddoommaaiinn__xx550000__ddeeccooddee() encodes and decodes the realm names in the X500 format that Kerberos uses to describe the transited realms in krbtgts. SSEEEE AALLSSOO krb5(3), krb5.conf(5) HEIMDAL May 1, 2006 HEIMDAL heimdal-7.5.0/lib/krb5/krb5_auth_context.cat30000644000175000017500000004276213212450756017107 0ustar niknik KRB5_AUTH_CONTEXT(3) BSD Library Functions Manual KRB5_AUTH_CONTEXT(3) NNAAMMEE kkrrbb55__aauutthh__ccoonn__aaddddffllaaggss, kkrrbb55__aauutthh__ccoonn__ffrreeee, kkrrbb55__aauutthh__ccoonn__ggeennaaddddrrss, kkrrbb55__aauutthh__ccoonn__ggeenneerraatteellooccaallssuubbkkeeyy, kkrrbb55__aauutthh__ccoonn__ggeettaaddddrrss, kkrrbb55__aauutthh__ccoonn__ggeettaauutthheennttiiccaattoorr, kkrrbb55__aauutthh__ccoonn__ggeettffllaaggss, kkrrbb55__aauutthh__ccoonn__ggeettkkeeyy, kkrrbb55__aauutthh__ccoonn__ggeettllooccaallssuubbkkeeyy, kkrrbb55__aauutthh__ccoonn__ggeettrrccaacchhee, kkrrbb55__aauutthh__ccoonn__ggeettrreemmootteessuubbkkeeyy, kkrrbb55__aauutthh__ccoonn__ggeettuusseerrkkeeyy, kkrrbb55__aauutthh__ccoonn__iinniitt, kkrrbb55__aauutthh__ccoonn__iinniittiivveeccttoorr, kkrrbb55__aauutthh__ccoonn__rreemmoovveeffllaaggss, kkrrbb55__aauutthh__ccoonn__sseettaaddddrrss, kkrrbb55__aauutthh__ccoonn__sseettaaddddrrss__ffrroomm__ffdd, kkrrbb55__aauutthh__ccoonn__sseettffllaaggss, kkrrbb55__aauutthh__ccoonn__sseettiivveeccttoorr, kkrrbb55__aauutthh__ccoonn__sseettkkeeyy, kkrrbb55__aauutthh__ccoonn__sseettllooccaallssuubbkkeeyy, kkrrbb55__aauutthh__ccoonn__sseettrrccaacchhee, kkrrbb55__aauutthh__ccoonn__sseettrreemmootteessuubbkkeeyy, kkrrbb55__aauutthh__ccoonn__sseettuusseerrkkeeyy, kkrrbb55__aauutthh__ccoonntteexxtt, kkrrbb55__aauutthh__ggeettcckkssuummttyyppee, kkrrbb55__aauutthh__ggeettkkeeyyttyyppee, kkrrbb55__aauutthh__ggeettllooccaallsseeqqnnuummbbeerr, kkrrbb55__aauutthh__ggeettrreemmootteesseeqqnnuummbbeerr, kkrrbb55__aauutthh__sseettcckkssuummttyyppee, kkrrbb55__aauutthh__sseettkkeeyyttyyppee, kkrrbb55__aauutthh__sseettllooccaallsseeqqnnuummbbeerr, kkrrbb55__aauutthh__sseettrreemmootteesseeqqnnuummbbeerr, kkrrbb55__ffrreeee__aauutthheennttiiccaattoorr -- manage authentication on connection level LLIIBBRRAARRYY Kerberos 5 Library (libkrb5, -lkrb5) SSYYNNOOPPSSIISS ##iinncclluuddee <> _k_r_b_5___e_r_r_o_r___c_o_d_e kkrrbb55__aauutthh__ccoonn__iinniitt(_k_r_b_5___c_o_n_t_e_x_t _c_o_n_t_e_x_t, _k_r_b_5___a_u_t_h___c_o_n_t_e_x_t _*_a_u_t_h___c_o_n_t_e_x_t); _v_o_i_d kkrrbb55__aauutthh__ccoonn__ffrreeee(_k_r_b_5___c_o_n_t_e_x_t _c_o_n_t_e_x_t, _k_r_b_5___a_u_t_h___c_o_n_t_e_x_t _a_u_t_h___c_o_n_t_e_x_t); _k_r_b_5___e_r_r_o_r___c_o_d_e kkrrbb55__aauutthh__ccoonn__sseettffllaaggss(_k_r_b_5___c_o_n_t_e_x_t _c_o_n_t_e_x_t, _k_r_b_5___a_u_t_h___c_o_n_t_e_x_t _a_u_t_h___c_o_n_t_e_x_t, _i_n_t_3_2___t _f_l_a_g_s); _k_r_b_5___e_r_r_o_r___c_o_d_e kkrrbb55__aauutthh__ccoonn__ggeettffllaaggss(_k_r_b_5___c_o_n_t_e_x_t _c_o_n_t_e_x_t, _k_r_b_5___a_u_t_h___c_o_n_t_e_x_t _a_u_t_h___c_o_n_t_e_x_t, _i_n_t_3_2___t _*_f_l_a_g_s); _k_r_b_5___e_r_r_o_r___c_o_d_e kkrrbb55__aauutthh__ccoonn__aaddddffllaaggss(_k_r_b_5___c_o_n_t_e_x_t _c_o_n_t_e_x_t, _k_r_b_5___a_u_t_h___c_o_n_t_e_x_t _a_u_t_h___c_o_n_t_e_x_t, _i_n_t_3_2___t _a_d_d_f_l_a_g_s, _i_n_t_3_2___t _*_f_l_a_g_s); _k_r_b_5___e_r_r_o_r___c_o_d_e kkrrbb55__aauutthh__ccoonn__rreemmoovveeffllaaggss(_k_r_b_5___c_o_n_t_e_x_t _c_o_n_t_e_x_t, _k_r_b_5___a_u_t_h___c_o_n_t_e_x_t _a_u_t_h___c_o_n_t_e_x_t, _i_n_t_3_2___t _r_e_m_o_v_e_l_a_g_s, _i_n_t_3_2___t _*_f_l_a_g_s); _k_r_b_5___e_r_r_o_r___c_o_d_e kkrrbb55__aauutthh__ccoonn__sseettaaddddrrss(_k_r_b_5___c_o_n_t_e_x_t _c_o_n_t_e_x_t, _k_r_b_5___a_u_t_h___c_o_n_t_e_x_t _a_u_t_h___c_o_n_t_e_x_t, _k_r_b_5___a_d_d_r_e_s_s _*_l_o_c_a_l___a_d_d_r, _k_r_b_5___a_d_d_r_e_s_s _*_r_e_m_o_t_e___a_d_d_r); _k_r_b_5___e_r_r_o_r___c_o_d_e kkrrbb55__aauutthh__ccoonn__ggeettaaddddrrss(_k_r_b_5___c_o_n_t_e_x_t _c_o_n_t_e_x_t, _k_r_b_5___a_u_t_h___c_o_n_t_e_x_t _a_u_t_h___c_o_n_t_e_x_t, _k_r_b_5___a_d_d_r_e_s_s _*_*_l_o_c_a_l___a_d_d_r, _k_r_b_5___a_d_d_r_e_s_s _*_*_r_e_m_o_t_e___a_d_d_r); _k_r_b_5___e_r_r_o_r___c_o_d_e kkrrbb55__aauutthh__ccoonn__ggeennaaddddrrss(_k_r_b_5___c_o_n_t_e_x_t _c_o_n_t_e_x_t, _k_r_b_5___a_u_t_h___c_o_n_t_e_x_t _a_u_t_h___c_o_n_t_e_x_t, _i_n_t _f_d, _i_n_t _f_l_a_g_s); _k_r_b_5___e_r_r_o_r___c_o_d_e kkrrbb55__aauutthh__ccoonn__sseettaaddddrrss__ffrroomm__ffdd(_k_r_b_5___c_o_n_t_e_x_t _c_o_n_t_e_x_t, _k_r_b_5___a_u_t_h___c_o_n_t_e_x_t _a_u_t_h___c_o_n_t_e_x_t, _v_o_i_d _*_p___f_d); _k_r_b_5___e_r_r_o_r___c_o_d_e kkrrbb55__aauutthh__ccoonn__ggeettkkeeyy(_k_r_b_5___c_o_n_t_e_x_t _c_o_n_t_e_x_t, _k_r_b_5___a_u_t_h___c_o_n_t_e_x_t _a_u_t_h___c_o_n_t_e_x_t, _k_r_b_5___k_e_y_b_l_o_c_k _*_*_k_e_y_b_l_o_c_k); _k_r_b_5___e_r_r_o_r___c_o_d_e kkrrbb55__aauutthh__ccoonn__ggeettllooccaallssuubbkkeeyy(_k_r_b_5___c_o_n_t_e_x_t _c_o_n_t_e_x_t, _k_r_b_5___a_u_t_h___c_o_n_t_e_x_t _a_u_t_h___c_o_n_t_e_x_t, _k_r_b_5___k_e_y_b_l_o_c_k _*_*_k_e_y_b_l_o_c_k); _k_r_b_5___e_r_r_o_r___c_o_d_e kkrrbb55__aauutthh__ccoonn__ggeettrreemmootteessuubbkkeeyy(_k_r_b_5___c_o_n_t_e_x_t _c_o_n_t_e_x_t, _k_r_b_5___a_u_t_h___c_o_n_t_e_x_t _a_u_t_h___c_o_n_t_e_x_t, _k_r_b_5___k_e_y_b_l_o_c_k _*_*_k_e_y_b_l_o_c_k); _k_r_b_5___e_r_r_o_r___c_o_d_e kkrrbb55__aauutthh__ccoonn__ggeenneerraatteellooccaallssuubbkkeeyy(_k_r_b_5___c_o_n_t_e_x_t _c_o_n_t_e_x_t, _k_r_b_5___a_u_t_h___c_o_n_t_e_x_t _a_u_t_h___c_o_n_t_e_x_t, _k_r_b_5___k_e_y_b_l_o_c_k, _*_k_e_y_"); _k_r_b_5___e_r_r_o_r___c_o_d_e kkrrbb55__aauutthh__ccoonn__iinniittiivveeccttoorr(_k_r_b_5___c_o_n_t_e_x_t _c_o_n_t_e_x_t, _k_r_b_5___a_u_t_h___c_o_n_t_e_x_t _a_u_t_h___c_o_n_t_e_x_t); _k_r_b_5___e_r_r_o_r___c_o_d_e kkrrbb55__aauutthh__ccoonn__sseettiivveeccttoorr(_k_r_b_5___c_o_n_t_e_x_t _c_o_n_t_e_x_t, _k_r_b_5___a_u_t_h___c_o_n_t_e_x_t _*_a_u_t_h___c_o_n_t_e_x_t, _k_r_b_5___p_o_i_n_t_e_r _i_v_e_c_t_o_r); _v_o_i_d kkrrbb55__ffrreeee__aauutthheennttiiccaattoorr(_k_r_b_5___c_o_n_t_e_x_t _c_o_n_t_e_x_t, _k_r_b_5___a_u_t_h_e_n_t_i_c_a_t_o_r _*_a_u_t_h_e_n_t_i_c_a_t_o_r); DDEESSCCRRIIPPTTIIOONN The kkrrbb55__aauutthh__ccoonntteexxtt structure holds all context related to an authenti- cated connection, in a similar way to kkrrbb55__ccoonntteexxtt that holds the context for the thread or process. kkrrbb55__aauutthh__ccoonntteexxtt is used by various func- tions that are directly related to authentication between the server/client. Example of data that this structure contains are various flags, addresses of client and server, port numbers, keyblocks (and sub- keys), sequence numbers, replay cache, and checksum-type. kkrrbb55__aauutthh__ccoonn__iinniitt() allocates and initializes the kkrrbb55__aauutthh__ccoonntteexxtt structure. Default values can be changed with kkrrbb55__aauutthh__ccoonn__sseettcckkssuummttyyppee() and kkrrbb55__aauutthh__ccoonn__sseettffllaaggss(). The aauutthh__ccoonntteexxtt structure must be freed by kkrrbb55__aauutthh__ccoonn__ffrreeee(). kkrrbb55__aauutthh__ccoonn__ggeettffllaaggss(), kkrrbb55__aauutthh__ccoonn__sseettffllaaggss(), kkrrbb55__aauutthh__ccoonn__aaddddffllaaggss() and kkrrbb55__aauutthh__ccoonn__rreemmoovveeffllaaggss() gets and modi- fies the flags for a kkrrbb55__aauutthh__ccoonntteexxtt structure. Possible flags to set are: KRB5_AUTH_CONTEXT_DO_SEQUENCE Generate and check sequence-number on each packet. KRB5_AUTH_CONTEXT_DO_TIME Check timestamp on incoming packets. KRB5_AUTH_CONTEXT_RET_SEQUENCE, KRB5_AUTH_CONTEXT_RET_TIME Return sequence numbers and time stamps in the outdata parame- ters. KRB5_AUTH_CONTEXT_CLEAR_FORWARDED_CRED will force kkrrbb55__ggeett__ffoorrwwaarrddeedd__ccrreeddss() and kkrrbb55__ffwwdd__ttggtt__ccrreeddss() to create unencrypted ) KRB5_ENCTYPE_NULL) credentials. This is for use with old MIT server and JAVA based servers as they can't han- dle encrypted KRB-CRED. Note that sending such KRB-CRED is clear exposes crypto keys and tickets and is insecure, make sure the packet is encrypted in the protocol. krb5_rd_cred(3), krb5_rd_priv(3), krb5_rd_safe(3), krb5_mk_priv(3) and krb5_mk_safe(3). Setting this flag requires that parameter to be passed to these functions. The flags KRB5_AUTH_CONTEXT_DO_TIME also modifies the behavior the function kkrrbb55__ggeett__ffoorrwwaarrddeedd__ccrreeddss() by removing the timestamp in the forward credential message, this have backward compatibil- ity problems since not all versions of the heimdal supports time- less credentional messages. Is very useful since it always the sender of the message to cache forward message and thus avoiding a round trip to the KDC for each time a credential is forwarded. The same functionality can be obtained by using address-less tickets. kkrrbb55__aauutthh__ccoonn__sseettaaddddrrss(), kkrrbb55__aauutthh__ccoonn__sseettaaddddrrss__ffrroomm__ffdd() and kkrrbb55__aauutthh__ccoonn__ggeettaaddddrrss() gets and sets the addresses that are checked when a packet is received. It is mandatory to set an address for the remote host. If the local address is not set, it iss deduced from the underlaying operating system. kkrrbb55__aauutthh__ccoonn__ggeettaaddddrrss() will call kkrrbb55__ffrreeee__aaddddrreessss() on any address that is passed in _l_o_c_a_l___a_d_d_r or _r_e_m_o_t_e___a_d_d_r. kkrrbb55__aauutthh__ccoonn__sseettaaddddrr() allows passing in a NULL pointer as _l_o_c_a_l___a_d_d_r and _r_e_m_o_t_e___a_d_d_r, in that case it will just not set that address. kkrrbb55__aauutthh__ccoonn__sseettaaddddrrss__ffrroomm__ffdd() fetches the addresses from a file descriptor. kkrrbb55__aauutthh__ccoonn__ggeennaaddddrrss() fetches the address information from the given file descriptor _f_d depending on the bitmap argument _f_l_a_g_s. Possible values on _f_l_a_g_s are: _K_R_B_5___A_U_T_H___C_O_N_T_E_X_T___G_E_N_E_R_A_T_E___L_O_C_A_L___A_D_D_R fetches the local address from _f_d. _K_R_B_5___A_U_T_H___C_O_N_T_E_X_T___G_E_N_E_R_A_T_E___R_E_M_O_T_E___A_D_D_R fetches the remote address from _f_d. kkrrbb55__aauutthh__ccoonn__sseettkkeeyy(), kkrrbb55__aauutthh__ccoonn__sseettuusseerrkkeeyy() and kkrrbb55__aauutthh__ccoonn__ggeettkkeeyy() gets and sets the key used for this auth context. The keyblock returned by kkrrbb55__aauutthh__ccoonn__ggeettkkeeyy() should be freed with kkrrbb55__ffrreeee__kkeeyybblloocckk(). The keyblock send into kkrrbb55__aauutthh__ccoonn__sseettkkeeyy() is copied into the kkrrbb55__aauutthh__ccoonntteexxtt, and thus no special handling is needed. NULL is not a valid keyblock to kkrrbb55__aauutthh__ccoonn__sseettkkeeyy(). kkrrbb55__aauutthh__ccoonn__sseettuusseerrkkeeyy() is only useful when doing user to user authen- tication. kkrrbb55__aauutthh__ccoonn__sseettkkeeyy() is equivalent to kkrrbb55__aauutthh__ccoonn__sseettuusseerrkkeeyy(). kkrrbb55__aauutthh__ccoonn__ggeettllooccaallssuubbkkeeyy(), kkrrbb55__aauutthh__ccoonn__sseettllooccaallssuubbkkeeyy(), kkrrbb55__aauutthh__ccoonn__ggeettrreemmootteessuubbkkeeyy() and kkrrbb55__aauutthh__ccoonn__sseettrreemmootteessuubbkkeeyy() gets and sets the keyblock for the local and remote subkey. The keyblock returned by kkrrbb55__aauutthh__ccoonn__ggeettllooccaallssuubbkkeeyy() and kkrrbb55__aauutthh__ccoonn__ggeettrreemmootteessuubbkkeeyy() must be freed with kkrrbb55__ffrreeee__kkeeyybblloocckk(). kkrrbb55__aauutthh__sseettcckkssuummttyyppee() and kkrrbb55__aauutthh__ggeettcckkssuummttyyppee() sets and gets the checksum type that should be used for this connection. kkrrbb55__aauutthh__ccoonn__ggeenneerraatteellooccaallssuubbkkeeyy() generates a local subkey that have the same encryption type as _k_e_y. kkrrbb55__aauutthh__ggeettrreemmootteesseeqqnnuummbbeerr() kkrrbb55__aauutthh__sseettrreemmootteesseeqqnnuummbbeerr(), kkrrbb55__aauutthh__ggeettllooccaallsseeqqnnuummbbeerr() and kkrrbb55__aauutthh__sseettllooccaallsseeqqnnuummbbeerr() gets and sets the sequence-number for the local and remote sequence-number counter. kkrrbb55__aauutthh__sseettkkeeyyttyyppee() and kkrrbb55__aauutthh__ggeettkkeeyyttyyppee() gets and gets the key- type of the keyblock in kkrrbb55__aauutthh__ccoonntteexxtt. kkrrbb55__aauutthh__ccoonn__ggeettaauutthheennttiiccaattoorr() Retrieves the authenticator that was used during mutual authentication. The authenticator returned should be freed by calling kkrrbb55__ffrreeee__aauutthheennttiiccaattoorr(). kkrrbb55__aauutthh__ccoonn__ggeettrrccaacchhee() and kkrrbb55__aauutthh__ccoonn__sseettrrccaacchhee() gets and sets the replay-cache. kkrrbb55__aauutthh__ccoonn__iinniittiivveeccttoorr() allocates memory for and zeros the initial vector in the _a_u_t_h___c_o_n_t_e_x_t keyblock. kkrrbb55__aauutthh__ccoonn__sseettiivveeccttoorr() sets the i_vector portion of _a_u_t_h___c_o_n_t_e_x_t to _i_v_e_c_t_o_r. kkrrbb55__ffrreeee__aauutthheennttiiccaattoorr() free the content of _a_u_t_h_e_n_t_i_c_a_t_o_r and _a_u_t_h_e_n_t_i_c_a_t_o_r itself. SSEEEE AALLSSOO krb5_context(3), kerberos(8) HEIMDAL May 17, 2005 HEIMDAL heimdal-7.5.0/lib/krb5/krb5_aname_to_localname.cat30000644000175000017500000000351513212450756020171 0ustar niknik KRB5_ANAME_TO_LOCALNA... BSD Library Functions Manual KRB5_ANAME_TO_LOCALNA... NNAAMMEE kkrrbb55__aannaammee__ttoo__llooccaallnnaammee -- converts a principal to a system local name LLIIBBRRAARRYY Kerberos 5 Library (libkrb5, -lkrb5) SSYYNNOOPPSSIISS ##iinncclluuddee <> _k_r_b_5___b_o_o_l_e_a_n kkrrbb55__aannaammee__ttoo__llooccaallnnaammee(_k_r_b_5___c_o_n_t_e_x_t _c_o_n_t_e_x_t, _k_r_b_5___c_o_n_s_t___p_r_i_n_c_i_p_a_l _n_a_m_e, _s_i_z_e___t _l_n_s_i_z_e, _c_h_a_r _*_l_n_a_m_e); DDEESSCCRRIIPPTTIIOONN This function takes a principal _n_a_m_e, verifies that it is in the local realm (using kkrrbb55__ggeett__ddeeffaauulltt__rreeaallmmss()) and then returns the local name of the principal. If _n_a_m_e isn't in one of the local realms an error is returned. If the size (_l_n_s_i_z_e) of the local name (_l_n_a_m_e) is too small, an error is returned. kkrrbb55__aannaammee__ttoo__llooccaallnnaammee() should only be use by an application that implements protocols that don't transport the login name and thus needs to convert a principal to a local name. Protocols should be designed so that they authenticate using Kerberos, send over the login name and then verify the principal that is authenti- cated is allowed to login and the login name. A way to check if a user is allowed to login is using the function kkrrbb55__kkuusseerrookk(). SSEEEE AALLSSOO krb5_get_default_realms(3), krb5_kuserok(3) HEIMDAL February 18, 2006 HEIMDAL heimdal-7.5.0/lib/krb5/crypto-algs.c0000644000175000017500000000634113026237312015276 0ustar niknik/* * Copyright (c) 1997 - 2008 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "krb5_locl.h" #ifndef HEIMDAL_SMALLER #define DES3_OLD_ENCTYPE 1 #endif struct _krb5_checksum_type *_krb5_checksum_types[] = { &_krb5_checksum_none, #ifdef HEIM_WEAK_CRYPTO &_krb5_checksum_crc32, &_krb5_checksum_rsa_md4, &_krb5_checksum_rsa_md4_des, &_krb5_checksum_rsa_md5_des, #endif #ifdef DES3_OLD_ENCTYPE &_krb5_checksum_rsa_md5_des3, #endif &_krb5_checksum_rsa_md5, &_krb5_checksum_sha1, &_krb5_checksum_hmac_sha1_des3, &_krb5_checksum_hmac_sha1_aes128, &_krb5_checksum_hmac_sha1_aes256, &_krb5_checksum_hmac_sha256_128_aes128, &_krb5_checksum_hmac_sha384_192_aes256, &_krb5_checksum_hmac_md5 }; int _krb5_num_checksums = sizeof(_krb5_checksum_types) / sizeof(_krb5_checksum_types[0]); /* * these should currently be in reverse preference order. * (only relevant for !F_PSEUDO) */ struct _krb5_encryption_type *_krb5_etypes[] = { &_krb5_enctype_aes256_cts_hmac_sha384_192, &_krb5_enctype_aes128_cts_hmac_sha256_128, &_krb5_enctype_aes256_cts_hmac_sha1, &_krb5_enctype_aes128_cts_hmac_sha1, &_krb5_enctype_des3_cbc_sha1, &_krb5_enctype_des3_cbc_none, /* used by the gss-api mech */ &_krb5_enctype_arcfour_hmac_md5, #ifdef DES3_OLD_ENCTYPE &_krb5_enctype_des3_cbc_md5, &_krb5_enctype_old_des3_cbc_sha1, #endif #ifdef HEIM_WEAK_CRYPTO &_krb5_enctype_des_cbc_md5, &_krb5_enctype_des_cbc_md4, &_krb5_enctype_des_cbc_crc, &_krb5_enctype_des_cbc_none, &_krb5_enctype_des_cfb64_none, &_krb5_enctype_des_pcbc_none, #endif &_krb5_enctype_null }; int _krb5_num_etypes = sizeof(_krb5_etypes) / sizeof(_krb5_etypes[0]); heimdal-7.5.0/lib/krb5/crypto-null.c0000644000175000017500000000514413026237312015322 0ustar niknik/* * Copyright (c) 1997 - 2008 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "krb5_locl.h" #ifndef HEIMDAL_SMALLER #define DES3_OLD_ENCTYPE 1 #endif static struct _krb5_key_type keytype_null = { KRB5_ENCTYPE_NULL, "null", 0, 0, 0, NULL, NULL, NULL, NULL, NULL, NULL }; static krb5_error_code NONE_checksum(krb5_context context, struct _krb5_key_data *key, const void *data, size_t len, unsigned usage, Checksum *C) { return 0; } struct _krb5_checksum_type _krb5_checksum_none = { CKSUMTYPE_NONE, "none", 1, 0, 0, NONE_checksum, NULL }; static krb5_error_code NULL_encrypt(krb5_context context, struct _krb5_key_data *key, void *data, size_t len, krb5_boolean encryptp, int usage, void *ivec) { return 0; } struct _krb5_encryption_type _krb5_enctype_null = { ETYPE_NULL, "null", NULL, 1, 1, 0, &keytype_null, &_krb5_checksum_none, NULL, F_DISABLED, NULL_encrypt, 0, NULL }; heimdal-7.5.0/lib/krb5/krb5_get_forwarded_creds.30000644000175000017500000000536312136107750017677 0ustar niknik.\" Copyright (c) 2004 Kungliga Tekniska Högskolan .\" (Royal Institute of Technology, Stockholm, Sweden). .\" All rights reserved. .\" .\" Redistribution and use in source and binary forms, with or without .\" modification, are permitted provided that the following conditions .\" are met: .\" .\" 1. Redistributions of source code must retain the above copyright .\" notice, this list of conditions and the following disclaimer. .\" .\" 2. Redistributions in binary form must reproduce the above copyright .\" notice, this list of conditions and the following disclaimer in the .\" documentation and/or other materials provided with the distribution. .\" .\" 3. Neither the name of the Institute nor the names of its contributors .\" may be used to endorse or promote products derived from this software .\" without specific prior written permission. .\" .\" THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND .\" ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE .\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE .\" ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE .\" FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL .\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS .\" OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) .\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT .\" LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF .\" SUCH DAMAGE. .\" .\" $Id$ .\" .Dd July 26, 2004 .Dt KRB5_GET_FORWARDED_CREDS 3 .Os HEIMDAL .Sh NAME .Nm krb5_get_forwarded_creds , .Nm krb5_fwd_tgt_creds .Nd get forwarded credentials from the KDC .Sh LIBRARY Kerberos 5 Library (libkrb5, -lkrb5) .Sh SYNOPSIS .In krb5.h .Ft krb5_error_code .Fo krb5_get_forwarded_creds .Fa "krb5_context context" .Fa "krb5_auth_context auth_context" .Fa "krb5_ccache ccache" .Fa "krb5_flags flags" .Fa "const char *hostname" .Fa "krb5_creds *in_creds" .Fa "krb5_data *out_data" .Fc .Ft krb5_error_code .Fo krb5_fwd_tgt_creds .Fa "krb5_context context" .Fa "krb5_auth_context auth_context" .Fa "const char *hostname" .Fa "krb5_principal client" .Fa "krb5_principal server" .Fa "krb5_ccache ccache" .Fa "int forwardable" .Fa "krb5_data *out_data" .Fc .Sh DESCRIPTION .Fn krb5_get_forwarded_creds and .Fn krb5_fwd_tgt_creds get tickets forwarded to .Fa hostname. If the tickets that are forwarded are address-less, the forwarded tickets will also be address-less, otherwise .Fa hostname will be used for figure out the address to forward the ticket too. .Sh SEE ALSO .Xr krb5 3 , .Xr krb5_get_credentials 3 , .Xr krb5.conf 5 heimdal-7.5.0/lib/krb5/kerberos.80000644000175000017500000001032013026237312014563 0ustar niknik.\" Copyright (c) 2000 Kungliga Tekniska Högskolan .\" (Royal Institute of Technology, Stockholm, Sweden). .\" All rights reserved. .\" .\" Redistribution and use in source and binary forms, with or without .\" modification, are permitted provided that the following conditions .\" are met: .\" .\" 1. Redistributions of source code must retain the above copyright .\" notice, this list of conditions and the following disclaimer. .\" .\" 2. Redistributions in binary form must reproduce the above copyright .\" notice, this list of conditions and the following disclaimer in the .\" documentation and/or other materials provided with the distribution. .\" .\" 3. Neither the name of the Institute nor the names of its contributors .\" may be used to endorse or promote products derived from this software .\" without specific prior written permission. .\" .\" THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND .\" ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE .\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE .\" ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE .\" FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL .\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS .\" OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) .\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT .\" LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF .\" SUCH DAMAGE. .\" .\" $Id$ .\" .Dd Jun 27, 2013 .Dt KERBEROS 8 .Os HEIMDAL .Sh NAME .Nm kerberos .Nd introduction to the Kerberos system .Sh DESCRIPTION Kerberos is a network authentication system. Its purpose is to securely authenticate users and services in an insecure network environment. .Pp This is done with a Kerberos server acting as a trusted third party, keeping a database with secret keys for all users and services (collectively called .Em principals ) . .Pp Each principal belongs to exactly one .Em realm , which is the administrative domain in Kerberos. A realm usually corresponds to an organisation, and the realm should normally be derived from that organisation's domain name. A realm is served by one or more Kerberos servers. .Pp The authentication process involves exchange of .Sq tickets and .Sq authenticators which together prove the principal's identity. .Pp When you login to the Kerberos system, either through the normal system login or with the .Xr kinit 1 program, you acquire a .Em ticket granting ticket which allows you to get new tickets for other services, such as .Ic telnet or .Ic ftp , without giving your password. .Pp For more information on how Kerberos works, and other general Kerberos questions see the Kerberos FAQ at .Lk http://www.cmf.nrl.navy.mil/krb/kerberos-faq.html . .Pp For setup instructions see the Heimdal Texinfo manual. .Sh SEE ALSO .Xr ftp 1 , .Xr kdestroy 1 , .Xr kinit 1 , .Xr klist 1 , .Xr kpasswd 1 , .Xr telnet 1 , .Xr krb5 3 , .Xr krb5.conf 5 , .Xr kadmin 1 , .Xr kdc 8 , .Xr ktutil 1 .Sh HISTORY The Kerberos authentication system was developed in the late 1980's as part of the Athena Project at the Massachusetts Institute of Technology. Versions one through three never reached outside MIT, but version 4 was (and still is) quite popular, especially in the academic community, but is also used in commercial products like the AFS filesystem. .Pp The problems with version 4 are that it has many limitations, the code was not too well written (since it had been developed over a long time), and it has a number of known security problems. To resolve many of these issues work on version five started, and resulted in IETF RFC 1510 in 1993. IETF RFC 1510 was obsoleted in 2005 with IETF RFC 4120, also known as Kerberos clarifications. With the arrival of IETF RFC 4120, the work on adding extensibility and internationalization have started (Kerberos extensions), and a new RFC will hopefully appear soon. .Pp This manual page is part of the .Nm Heimdal Kerberos 5 distribution, which has been in development at the Royal Institute of Technology in Stockholm, Sweden, since about 1997. heimdal-7.5.0/lib/krb5/krb5_creds.cat30000644000175000017500000000606013212450756015471 0ustar niknik KRB5_CREDS(3) BSD Library Functions Manual KRB5_CREDS(3) NNAAMMEE kkrrbb55__ccrreeddss, kkrrbb55__ccooppyy__ccrreeddss, kkrrbb55__ccooppyy__ccrreeddss__ccoonntteennttss, kkrrbb55__ffrreeee__ccrreeddss, kkrrbb55__ffrreeee__ccrreedd__ccoonntteennttss -- Kerberos 5 credential handling functions LLIIBBRRAARRYY Kerberos 5 Library (libkrb5, -lkrb5) SSYYNNOOPPSSIISS ##iinncclluuddee <> _k_r_b_5___e_r_r_o_r___c_o_d_e kkrrbb55__ccooppyy__ccrreeddss(_k_r_b_5___c_o_n_t_e_x_t _c_o_n_t_e_x_t, _c_o_n_s_t _k_r_b_5___c_r_e_d_s _*_i_n_c_r_e_d, _k_r_b_5___c_r_e_d_s _*_*_o_u_t_c_r_e_d); _k_r_b_5___e_r_r_o_r___c_o_d_e kkrrbb55__ccooppyy__ccrreeddss__ccoonntteennttss(_k_r_b_5___c_o_n_t_e_x_t _c_o_n_t_e_x_t, _c_o_n_s_t _k_r_b_5___c_r_e_d_s _*_i_n_c_r_e_d, _k_r_b_5___c_r_e_d_s _*_o_u_t_c_r_e_d); _k_r_b_5___e_r_r_o_r___c_o_d_e kkrrbb55__ffrreeee__ccrreeddss(_k_r_b_5___c_o_n_t_e_x_t _c_o_n_t_e_x_t, _k_r_b_5___c_r_e_d_s _*_o_u_t_c_r_e_d); _k_r_b_5___e_r_r_o_r___c_o_d_e kkrrbb55__ffrreeee__ccrreedd__ccoonntteennttss(_k_r_b_5___c_o_n_t_e_x_t _c_o_n_t_e_x_t, _k_r_b_5___c_r_e_d_s _*_c_r_e_d); DDEESSCCRRIIPPTTIIOONN _k_r_b_5___c_r_e_d_s holds Kerberos credentials: typedef struct krb5_creds { krb5_principal client; krb5_principal server; krb5_keyblock session; krb5_times times; krb5_data ticket; krb5_data second_ticket; krb5_authdata authdata; krb5_addresses addresses; krb5_ticket_flags flags; } krb5_creds; kkrrbb55__ccooppyy__ccrreeddss() makes a copy of _i_n_c_r_e_d to _o_u_t_c_r_e_d. _o_u_t_c_r_e_d should be freed with kkrrbb55__ffrreeee__ccrreeddss() by the caller. kkrrbb55__ccooppyy__ccrreeddss__ccoonntteennttss() makes a copy of the content of _i_n_c_r_e_d to _o_u_t_c_r_e_d_s. _o_u_t_c_r_e_d_s should be freed by the called with kkrrbb55__ffrreeee__ccrreeddss__ccoonntteennttss(). kkrrbb55__ffrreeee__ccrreeddss() frees the content of the _c_r_e_d structure and the struc- ture itself. kkrrbb55__ffrreeee__ccrreedd__ccoonntteennttss() frees the content of the _c_r_e_d structure. SSEEEE AALLSSOO krb5(3), krb5_compare_creds(3), krb5_get_init_creds(3), kerberos(8) HEIMDAL May 1, 2006 HEIMDAL heimdal-7.5.0/lib/krb5/salt-aes-sha1.c0000644000175000017500000000654713026237312015405 0ustar niknik/* * Copyright (c) 1997 - 2008 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "krb5_locl.h" int _krb5_AES_SHA1_string_to_default_iterator = 4096; static krb5_error_code AES_SHA1_string_to_key(krb5_context context, krb5_enctype enctype, krb5_data password, krb5_salt salt, krb5_data opaque, krb5_keyblock *key) { krb5_error_code ret; uint32_t iter; struct _krb5_encryption_type *et; struct _krb5_key_data kd; if (opaque.length == 0) iter = _krb5_AES_SHA1_string_to_default_iterator; else if (opaque.length == 4) { unsigned long v; _krb5_get_int(opaque.data, &v, 4); iter = ((uint32_t)v); } else return KRB5_PROG_KEYTYPE_NOSUPP; /* XXX */ et = _krb5_find_enctype(enctype); if (et == NULL) return KRB5_PROG_KEYTYPE_NOSUPP; kd.schedule = NULL; ALLOC(kd.key, 1); if (kd.key == NULL) return krb5_enomem(context); kd.key->keytype = enctype; ret = krb5_data_alloc(&kd.key->keyvalue, et->keytype->size); if (ret) { krb5_set_error_message (context, ret, N_("malloc: out of memory", "")); return ret; } ret = PKCS5_PBKDF2_HMAC(password.data, password.length, salt.saltvalue.data, salt.saltvalue.length, iter, EVP_sha1(), et->keytype->size, kd.key->keyvalue.data); if (ret != 1) { _krb5_free_key_data(context, &kd, et); krb5_set_error_message(context, KRB5_PROG_KEYTYPE_NOSUPP, "Error calculating s2k"); return KRB5_PROG_KEYTYPE_NOSUPP; } ret = _krb5_derive_key(context, et, &kd, "kerberos", strlen("kerberos")); if (ret == 0) ret = krb5_copy_keyblock_contents(context, kd.key, key); _krb5_free_key_data(context, &kd, et); return ret; } struct salt_type _krb5_AES_SHA1_salt[] = { { KRB5_PW_SALT, "pw-salt", AES_SHA1_string_to_key }, { 0, NULL, NULL } }; heimdal-7.5.0/lib/krb5/config_file.c0000644000175000017500000007733413212137553015313 0ustar niknik/* * Copyright (c) 1997 - 2004 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Portions Copyright (c) 2009 Apple Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "krb5_locl.h" #ifdef __APPLE__ #include #endif /* Gaah! I want a portable funopen */ struct fileptr { const char *s; FILE *f; }; static char * config_fgets(char *str, size_t len, struct fileptr *ptr) { /* XXX this is not correct, in that they don't do the same if the line is longer than len */ if(ptr->f != NULL) return fgets(str, len, ptr->f); else { /* this is almost strsep_copy */ const char *p; ssize_t l; if(*ptr->s == '\0') return NULL; p = ptr->s + strcspn(ptr->s, "\n"); if(*p == '\n') p++; l = min(len, (size_t)(p - ptr->s)); if(len > 0) { memcpy(str, ptr->s, l); str[l] = '\0'; } ptr->s = p; return str; } } static krb5_error_code parse_section(char *p, krb5_config_section **s, krb5_config_section **res, const char **err_message); static krb5_error_code parse_binding(struct fileptr *f, unsigned *lineno, char *p, krb5_config_binding **b, krb5_config_binding **parent, const char **err_message); static krb5_error_code parse_list(struct fileptr *f, unsigned *lineno, krb5_config_binding **parent, const char **err_message); KRB5_LIB_FUNCTION krb5_config_section * KRB5_LIB_CALL _krb5_config_get_entry(krb5_config_section **parent, const char *name, int type) { krb5_config_section **q; for(q = parent; *q != NULL; q = &(*q)->next) if(type == krb5_config_list && (unsigned)type == (*q)->type && strcmp(name, (*q)->name) == 0) return *q; *q = calloc(1, sizeof(**q)); if(*q == NULL) return NULL; (*q)->name = strdup(name); (*q)->type = type; if((*q)->name == NULL) { free(*q); *q = NULL; return NULL; } return *q; } /* * Parse a section: * * [section] * foo = bar * b = { * a * } * ... * * starting at the line in `p', storing the resulting structure in * `s' and hooking it into `parent'. * Store the error message in `err_message'. */ static krb5_error_code parse_section(char *p, krb5_config_section **s, krb5_config_section **parent, const char **err_message) { char *p1; krb5_config_section *tmp; p1 = strchr (p + 1, ']'); if (p1 == NULL) { *err_message = "missing ]"; return KRB5_CONFIG_BADFORMAT; } *p1 = '\0'; tmp = _krb5_config_get_entry(parent, p + 1, krb5_config_list); if(tmp == NULL) { *err_message = "out of memory"; return KRB5_CONFIG_BADFORMAT; } *s = tmp; return 0; } /* * Parse a brace-enclosed list from `f', hooking in the structure at * `parent'. * Store the error message in `err_message'. */ static krb5_error_code parse_list(struct fileptr *f, unsigned *lineno, krb5_config_binding **parent, const char **err_message) { char buf[KRB5_BUFSIZ]; krb5_error_code ret; krb5_config_binding *b = NULL; unsigned beg_lineno = *lineno; while(config_fgets(buf, sizeof(buf), f) != NULL) { char *p; ++*lineno; buf[strcspn(buf, "\r\n")] = '\0'; p = buf; while(isspace((unsigned char)*p)) ++p; if (*p == '#' || *p == ';' || *p == '\0') continue; while(isspace((unsigned char)*p)) ++p; if (*p == '}') return 0; if (*p == '\0') continue; ret = parse_binding (f, lineno, p, &b, parent, err_message); if (ret) return ret; } *lineno = beg_lineno; *err_message = "unclosed {"; return KRB5_CONFIG_BADFORMAT; } /* * */ static krb5_error_code parse_binding(struct fileptr *f, unsigned *lineno, char *p, krb5_config_binding **b, krb5_config_binding **parent, const char **err_message) { krb5_config_binding *tmp; char *p1, *p2; krb5_error_code ret = 0; p1 = p; while (*p && *p != '=' && !isspace((unsigned char)*p)) ++p; if (*p == '\0') { *err_message = "missing ="; return KRB5_CONFIG_BADFORMAT; } p2 = p; while (isspace((unsigned char)*p)) ++p; if (*p != '=') { *err_message = "missing ="; return KRB5_CONFIG_BADFORMAT; } ++p; while(isspace((unsigned char)*p)) ++p; *p2 = '\0'; if (*p == '{') { tmp = _krb5_config_get_entry(parent, p1, krb5_config_list); if (tmp == NULL) { *err_message = "out of memory"; return KRB5_CONFIG_BADFORMAT; } ret = parse_list (f, lineno, &tmp->u.list, err_message); } else { tmp = _krb5_config_get_entry(parent, p1, krb5_config_string); if (tmp == NULL) { *err_message = "out of memory"; return KRB5_CONFIG_BADFORMAT; } p1 = p; p = p1 + strlen(p1); while(p > p1 && isspace((unsigned char)*(p-1))) --p; *p = '\0'; tmp->u.string = strdup(p1); } *b = tmp; return ret; } #if defined(__APPLE__) #if MAC_OS_X_VERSION_MIN_REQUIRED >= 1060 #define HAVE_CFPROPERTYLISTCREATEWITHSTREAM 1 #endif static char * cfstring2cstring(CFStringRef string) { CFIndex len; char *str; str = (char *) CFStringGetCStringPtr(string, kCFStringEncodingUTF8); if (str) return strdup(str); len = CFStringGetLength(string); len = 1 + CFStringGetMaximumSizeForEncoding(len, kCFStringEncodingUTF8); str = malloc(len); if (str == NULL) return NULL; if (!CFStringGetCString (string, str, len, kCFStringEncodingUTF8)) { free (str); return NULL; } return str; } static void convert_content(const void *key, const void *value, void *context) { krb5_config_section *tmp, **parent = context; char *k; if (CFGetTypeID(key) != CFStringGetTypeID()) return; k = cfstring2cstring(key); if (k == NULL) return; if (CFGetTypeID(value) == CFStringGetTypeID()) { tmp = _krb5_config_get_entry(parent, k, krb5_config_string); tmp->u.string = cfstring2cstring(value); } else if (CFGetTypeID(value) == CFDictionaryGetTypeID()) { tmp = _krb5_config_get_entry(parent, k, krb5_config_list); CFDictionaryApplyFunction(value, convert_content, &tmp->u.list); } else { /* log */ } free(k); } static krb5_error_code parse_plist_config(krb5_context context, const char *path, krb5_config_section **parent) { CFReadStreamRef s; CFDictionaryRef d; CFURLRef url; url = CFURLCreateFromFileSystemRepresentation(kCFAllocatorDefault, (UInt8 *)path, strlen(path), FALSE); if (url == NULL) { krb5_clear_error_message(context); return ENOMEM; } s = CFReadStreamCreateWithFile(kCFAllocatorDefault, url); CFRelease(url); if (s == NULL) { krb5_clear_error_message(context); return ENOMEM; } if (!CFReadStreamOpen(s)) { CFRelease(s); krb5_clear_error_message(context); return ENOENT; } #ifdef HAVE_CFPROPERTYLISTCREATEWITHSTREAM d = (CFDictionaryRef)CFPropertyListCreateWithStream(NULL, s, 0, kCFPropertyListImmutable, NULL, NULL); #else d = (CFDictionaryRef)CFPropertyListCreateFromStream(NULL, s, 0, kCFPropertyListImmutable, NULL, NULL); #endif CFRelease(s); if (d == NULL) { krb5_clear_error_message(context); return ENOENT; } CFDictionaryApplyFunction(d, convert_content, parent); CFRelease(d); return 0; } #endif /* * Parse the config file `fname', generating the structures into `res' * returning error messages in `err_message' */ static krb5_error_code krb5_config_parse_debug (struct fileptr *f, krb5_config_section **res, unsigned *lineno, const char **err_message) { krb5_config_section *s = NULL; krb5_config_binding *b = NULL; char buf[KRB5_BUFSIZ]; krb5_error_code ret; while (config_fgets(buf, sizeof(buf), f) != NULL) { char *p; ++*lineno; buf[strcspn(buf, "\r\n")] = '\0'; p = buf; while(isspace((unsigned char)*p)) ++p; if (*p == '#' || *p == ';') continue; if (*p == '[') { ret = parse_section(p, &s, res, err_message); if (ret) return ret; b = NULL; } else if (*p == '}') { *err_message = "unmatched }"; return KRB5_CONFIG_BADFORMAT; } else if(*p != '\0') { if (s == NULL) { *err_message = "binding before section"; return KRB5_CONFIG_BADFORMAT; } ret = parse_binding(f, lineno, p, &b, &s->u.list, err_message); if (ret) return ret; } } return 0; } static int is_plist_file(const char *fname) { size_t len = strlen(fname); char suffix[] = ".plist"; if (len < sizeof(suffix)) return 0; if (strcasecmp(&fname[len - (sizeof(suffix) - 1)], suffix) != 0) return 0; return 1; } /** * Parse a configuration file and add the result into res. This * interface can be used to parse several configuration files into one * resulting krb5_config_section by calling it repeatably. * * @param context a Kerberos 5 context. * @param fname a file name to a Kerberos configuration file * @param res the returned result, must be free with krb5_free_config_files(). * @return Return an error code or 0, see krb5_get_error_message(). * * @ingroup krb5_support */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_config_parse_file_multi (krb5_context context, const char *fname, krb5_config_section **res) { const char *str; char *newfname = NULL; unsigned lineno = 0; krb5_error_code ret; struct fileptr f; /** * If the fname starts with "~/" parse configuration file in the * current users home directory. The behavior can be disabled and * enabled by calling krb5_set_home_dir_access(). */ if (ISTILDE(fname[0]) && ISPATHSEP(fname[1])) { #ifndef KRB5_USE_PATH_TOKENS const char *home = NULL; if (!_krb5_homedir_access(context)) { krb5_set_error_message(context, EPERM, "Access to home directory not allowed"); return EPERM; } if(!issuid()) home = getenv("HOME"); if (home == NULL) { struct passwd *pw = getpwuid(getuid()); if(pw != NULL) home = pw->pw_dir; } if (home) { int aret; aret = asprintf(&newfname, "%s%s", home, &fname[1]); if (aret == -1 || newfname == NULL) return krb5_enomem(context); fname = newfname; } #else /* KRB5_USE_PATH_TOKENS */ if (asprintf(&newfname, "%%{USERCONFIG}%s", &fname[1]) < 0 || newfname == NULL) return krb5_enomem(context); fname = newfname; #endif } if (is_plist_file(fname)) { #ifdef __APPLE__ ret = parse_plist_config(context, fname, res); if (ret) { krb5_set_error_message(context, ret, "Failed to parse plist %s", fname); if (newfname) free(newfname); return ret; } #else krb5_set_error_message(context, ENOENT, "no support for plist configuration files"); return ENOENT; #endif } else { #ifdef KRB5_USE_PATH_TOKENS char * exp_fname = NULL; ret = _krb5_expand_path_tokens(context, fname, 1, &exp_fname); if (ret) { if (newfname) free(newfname); return ret; } if (newfname) free(newfname); fname = newfname = exp_fname; #endif f.f = fopen(fname, "r"); f.s = NULL; if(f.f == NULL) { ret = errno; krb5_set_error_message (context, ret, "open %s: %s", fname, strerror(ret)); if (newfname) free(newfname); return ret; } ret = krb5_config_parse_debug (&f, res, &lineno, &str); fclose(f.f); if (ret) { krb5_set_error_message (context, ret, "%s:%u: %s", fname, lineno, str); if (newfname) free(newfname); return ret; } } return 0; } KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_config_parse_file (krb5_context context, const char *fname, krb5_config_section **res) { *res = NULL; return krb5_config_parse_file_multi(context, fname, res); } static void free_binding (krb5_context context, krb5_config_binding *b) { krb5_config_binding *next_b; while (b) { free (b->name); if (b->type == krb5_config_string) free (b->u.string); else if (b->type == krb5_config_list) free_binding (context, b->u.list); else krb5_abortx(context, "unknown binding type (%d) in free_binding", b->type); next_b = b->next; free (b); b = next_b; } } /** * Free configuration file section, the result of * krb5_config_parse_file() and krb5_config_parse_file_multi(). * * @param context A Kerberos 5 context * @param s the configuration section to free * * @return returns 0 on successes, otherwise an error code, see * krb5_get_error_message() * * @ingroup krb5_support */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_config_file_free (krb5_context context, krb5_config_section *s) { free_binding (context, s); return 0; } #ifndef HEIMDAL_SMALLER KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL _krb5_config_copy(krb5_context context, krb5_config_section *c, krb5_config_section **head) { krb5_config_binding *d, *previous = NULL; *head = NULL; while (c) { d = calloc(1, sizeof(*d)); if (*head == NULL) *head = d; d->name = strdup(c->name); d->type = c->type; if (d->type == krb5_config_string) d->u.string = strdup(c->u.string); else if (d->type == krb5_config_list) _krb5_config_copy (context, c->u.list, &d->u.list); else krb5_abortx(context, "unknown binding type (%d) in krb5_config_copy", d->type); if (previous) previous->next = d; previous = d; c = c->next; } return 0; } #endif /* HEIMDAL_SMALLER */ KRB5_LIB_FUNCTION const void * KRB5_LIB_CALL _krb5_config_get_next (krb5_context context, const krb5_config_section *c, const krb5_config_binding **pointer, int type, ...) { const char *ret; va_list args; va_start(args, type); ret = _krb5_config_vget_next (context, c, pointer, type, args); va_end(args); return ret; } static const void * vget_next(krb5_context context, const krb5_config_binding *b, const krb5_config_binding **pointer, int type, const char *name, va_list args) { const char *p = va_arg(args, const char *); while(b != NULL) { if(strcmp(b->name, name) == 0) { if(b->type == (unsigned)type && p == NULL) { *pointer = b; return b->u.generic; } else if(b->type == krb5_config_list && p != NULL) { return vget_next(context, b->u.list, pointer, type, p, args); } } b = b->next; } return NULL; } KRB5_LIB_FUNCTION const void * KRB5_LIB_CALL _krb5_config_vget_next (krb5_context context, const krb5_config_section *c, const krb5_config_binding **pointer, int type, va_list args) { const krb5_config_binding *b; const char *p; if(c == NULL) c = context->cf; if (c == NULL) return NULL; if (*pointer == NULL) { /* first time here, walk down the tree looking for the right section */ p = va_arg(args, const char *); if (p == NULL) return NULL; return vget_next(context, c, pointer, type, p, args); } /* we were called again, so just look for more entries with the same name and type */ for (b = (*pointer)->next; b != NULL; b = b->next) { if(strcmp(b->name, (*pointer)->name) == 0 && b->type == (unsigned)type) { *pointer = b; return b->u.generic; } } return NULL; } KRB5_LIB_FUNCTION const void * KRB5_LIB_CALL _krb5_config_get (krb5_context context, const krb5_config_section *c, int type, ...) { const void *ret; va_list args; va_start(args, type); ret = _krb5_config_vget (context, c, type, args); va_end(args); return ret; } KRB5_LIB_FUNCTION const void * KRB5_LIB_CALL _krb5_config_vget (krb5_context context, const krb5_config_section *c, int type, va_list args) { const krb5_config_binding *foo = NULL; return _krb5_config_vget_next (context, c, &foo, type, args); } /** * Get a list of configuration binding list for more processing * * @param context A Kerberos 5 context. * @param c a configuration section, or NULL to use the section from context * @param ... a list of names, terminated with NULL. * * @return NULL if configuration list is not found, a list otherwise * * @ingroup krb5_support */ KRB5_LIB_FUNCTION const krb5_config_binding * KRB5_LIB_CALL krb5_config_get_list (krb5_context context, const krb5_config_section *c, ...) { const krb5_config_binding *ret; va_list args; va_start(args, c); ret = krb5_config_vget_list (context, c, args); va_end(args); return ret; } /** * Get a list of configuration binding list for more processing * * @param context A Kerberos 5 context. * @param c a configuration section, or NULL to use the section from context * @param args a va_list of arguments * * @return NULL if configuration list is not found, a list otherwise * * @ingroup krb5_support */ KRB5_LIB_FUNCTION const krb5_config_binding * KRB5_LIB_CALL krb5_config_vget_list (krb5_context context, const krb5_config_section *c, va_list args) { return _krb5_config_vget (context, c, krb5_config_list, args); } /** * Returns a "const char *" to a string in the configuration database. * The string may not be valid after a reload of the configuration * database so a caller should make a local copy if it needs to keep * the string. * * @param context A Kerberos 5 context. * @param c a configuration section, or NULL to use the section from context * @param ... a list of names, terminated with NULL. * * @return NULL if configuration string not found, a string otherwise * * @ingroup krb5_support */ KRB5_LIB_FUNCTION const char* KRB5_LIB_CALL krb5_config_get_string (krb5_context context, const krb5_config_section *c, ...) { const char *ret; va_list args; va_start(args, c); ret = krb5_config_vget_string (context, c, args); va_end(args); return ret; } /** * Like krb5_config_get_string(), but uses a va_list instead of ... * * @param context A Kerberos 5 context. * @param c a configuration section, or NULL to use the section from context * @param args a va_list of arguments * * @return NULL if configuration string not found, a string otherwise * * @ingroup krb5_support */ KRB5_LIB_FUNCTION const char* KRB5_LIB_CALL krb5_config_vget_string (krb5_context context, const krb5_config_section *c, va_list args) { return _krb5_config_vget (context, c, krb5_config_string, args); } /** * Like krb5_config_vget_string(), but instead of returning NULL, * instead return a default value. * * @param context A Kerberos 5 context. * @param c a configuration section, or NULL to use the section from context * @param def_value the default value to return if no configuration * found in the database. * @param args a va_list of arguments * * @return a configuration string * * @ingroup krb5_support */ KRB5_LIB_FUNCTION const char* KRB5_LIB_CALL krb5_config_vget_string_default (krb5_context context, const krb5_config_section *c, const char *def_value, va_list args) { const char *ret; ret = krb5_config_vget_string (context, c, args); if (ret == NULL) ret = def_value; return ret; } /** * Like krb5_config_get_string(), but instead of returning NULL, * instead return a default value. * * @param context A Kerberos 5 context. * @param c a configuration section, or NULL to use the section from context * @param def_value the default value to return if no configuration * found in the database. * @param ... a list of names, terminated with NULL. * * @return a configuration string * * @ingroup krb5_support */ KRB5_LIB_FUNCTION const char* KRB5_LIB_CALL krb5_config_get_string_default (krb5_context context, const krb5_config_section *c, const char *def_value, ...) { const char *ret; va_list args; va_start(args, def_value); ret = krb5_config_vget_string_default (context, c, def_value, args); va_end(args); return ret; } static char * next_component_string(char * begin, const char * delims, char **state) { char * end; if (begin == NULL) begin = *state; if (*begin == '\0') return NULL; end = begin; while (*end == '"') { char * t = strchr(end + 1, '"'); if (t) end = ++t; else end += strlen(end); } if (*end != '\0') { size_t pos; pos = strcspn(end, delims); end = end + pos; } if (*end != '\0') { *end = '\0'; *state = end + 1; if (*begin == '"' && *(end - 1) == '"' && begin + 1 < end) { begin++; *(end - 1) = '\0'; } return begin; } *state = end; if (*begin == '"' && *(end - 1) == '"' && begin + 1 < end) { begin++; *(end - 1) = '\0'; } return begin; } /** * Get a list of configuration strings, free the result with * krb5_config_free_strings(). * * @param context A Kerberos 5 context. * @param c a configuration section, or NULL to use the section from context * @param args a va_list of arguments * * @return TRUE or FALSE * * @ingroup krb5_support */ KRB5_LIB_FUNCTION char ** KRB5_LIB_CALL krb5_config_vget_strings(krb5_context context, const krb5_config_section *c, va_list args) { char **strings = NULL; int nstr = 0; const krb5_config_binding *b = NULL; const char *p; while((p = _krb5_config_vget_next(context, c, &b, krb5_config_string, args))) { char *tmp = strdup(p); char *pos = NULL; char *s; if(tmp == NULL) goto cleanup; s = next_component_string(tmp, " \t", &pos); while(s){ char **tmp2 = realloc(strings, (nstr + 1) * sizeof(*strings)); if(tmp2 == NULL) { free(tmp); goto cleanup; } strings = tmp2; strings[nstr] = strdup(s); nstr++; if(strings[nstr-1] == NULL) { free(tmp); goto cleanup; } s = next_component_string(NULL, " \t", &pos); } free(tmp); } if(nstr){ char **tmp = realloc(strings, (nstr + 1) * sizeof(*strings)); if(tmp == NULL) goto cleanup; strings = tmp; strings[nstr] = NULL; } return strings; cleanup: while(nstr--) free(strings[nstr]); free(strings); return NULL; } /** * Get a list of configuration strings, free the result with * krb5_config_free_strings(). * * @param context A Kerberos 5 context. * @param c a configuration section, or NULL to use the section from context * @param ... a list of names, terminated with NULL. * * @return TRUE or FALSE * * @ingroup krb5_support */ KRB5_LIB_FUNCTION char** KRB5_LIB_CALL krb5_config_get_strings(krb5_context context, const krb5_config_section *c, ...) { va_list ap; char **ret; va_start(ap, c); ret = krb5_config_vget_strings(context, c, ap); va_end(ap); return ret; } /** * Free the resulting strings from krb5_config-get_strings() and * krb5_config_vget_strings(). * * @param strings strings to free * * @ingroup krb5_support */ KRB5_LIB_FUNCTION void KRB5_LIB_CALL krb5_config_free_strings(char **strings) { char **s = strings; while(s && *s){ free(*s); s++; } free(strings); } /** * Like krb5_config_get_bool_default() but with a va_list list of * configuration selection. * * Configuration value to a boolean value, where yes/true and any * non-zero number means TRUE and other value is FALSE. * * @param context A Kerberos 5 context. * @param c a configuration section, or NULL to use the section from context * @param def_value the default value to return if no configuration * found in the database. * @param args a va_list of arguments * * @return TRUE or FALSE * * @ingroup krb5_support */ KRB5_LIB_FUNCTION krb5_boolean KRB5_LIB_CALL krb5_config_vget_bool_default (krb5_context context, const krb5_config_section *c, krb5_boolean def_value, va_list args) { const char *str; str = krb5_config_vget_string (context, c, args); if(str == NULL) return def_value; if(strcasecmp(str, "yes") == 0 || strcasecmp(str, "true") == 0 || atoi(str)) return TRUE; return FALSE; } /** * krb5_config_get_bool() will convert the configuration * option value to a boolean value, where yes/true and any non-zero * number means TRUE and other value is FALSE. * * @param context A Kerberos 5 context. * @param c a configuration section, or NULL to use the section from context * @param args a va_list of arguments * * @return TRUE or FALSE * * @ingroup krb5_support */ KRB5_LIB_FUNCTION krb5_boolean KRB5_LIB_CALL krb5_config_vget_bool (krb5_context context, const krb5_config_section *c, va_list args) { return krb5_config_vget_bool_default (context, c, FALSE, args); } /** * krb5_config_get_bool_default() will convert the configuration * option value to a boolean value, where yes/true and any non-zero * number means TRUE and other value is FALSE. * * @param context A Kerberos 5 context. * @param c a configuration section, or NULL to use the section from context * @param def_value the default value to return if no configuration * found in the database. * @param ... a list of names, terminated with NULL. * * @return TRUE or FALSE * * @ingroup krb5_support */ KRB5_LIB_FUNCTION krb5_boolean KRB5_LIB_CALL krb5_config_get_bool_default (krb5_context context, const krb5_config_section *c, krb5_boolean def_value, ...) { va_list ap; krb5_boolean ret; va_start(ap, def_value); ret = krb5_config_vget_bool_default(context, c, def_value, ap); va_end(ap); return ret; } /** * Like krb5_config_get_bool() but with a va_list list of * configuration selection. * * Configuration value to a boolean value, where yes/true and any * non-zero number means TRUE and other value is FALSE. * * @param context A Kerberos 5 context. * @param c a configuration section, or NULL to use the section from context * @param ... a list of names, terminated with NULL. * * @return TRUE or FALSE * * @ingroup krb5_support */ KRB5_LIB_FUNCTION krb5_boolean KRB5_LIB_CALL krb5_config_get_bool (krb5_context context, const krb5_config_section *c, ...) { va_list ap; krb5_boolean ret; va_start(ap, c); ret = krb5_config_vget_bool (context, c, ap); va_end(ap); return ret; } /** * Get the time from the configuration file using a relative time. * * Like krb5_config_get_time_default() but with a va_list list of * configuration selection. * * @param context A Kerberos 5 context. * @param c a configuration section, or NULL to use the section from context * @param def_value the default value to return if no configuration * found in the database. * @param args a va_list of arguments * * @return parsed the time (or def_value on parse error) * * @ingroup krb5_support */ KRB5_LIB_FUNCTION int KRB5_LIB_CALL krb5_config_vget_time_default (krb5_context context, const krb5_config_section *c, int def_value, va_list args) { const char *str; krb5_deltat t; str = krb5_config_vget_string (context, c, args); if(str == NULL) return def_value; if (krb5_string_to_deltat(str, &t)) return def_value; return t; } /** * Get the time from the configuration file using a relative time, for example: 1h30s * * @param context A Kerberos 5 context. * @param c a configuration section, or NULL to use the section from context * @param args a va_list of arguments * * @return parsed the time or -1 on error * * @ingroup krb5_support */ KRB5_LIB_FUNCTION int KRB5_LIB_CALL krb5_config_vget_time (krb5_context context, const krb5_config_section *c, va_list args) { return krb5_config_vget_time_default (context, c, -1, args); } /** * Get the time from the configuration file using a relative time, for example: 1h30s * * @param context A Kerberos 5 context. * @param c a configuration section, or NULL to use the section from context * @param def_value the default value to return if no configuration * found in the database. * @param ... a list of names, terminated with NULL. * * @return parsed the time (or def_value on parse error) * * @ingroup krb5_support */ KRB5_LIB_FUNCTION int KRB5_LIB_CALL krb5_config_get_time_default (krb5_context context, const krb5_config_section *c, int def_value, ...) { va_list ap; int ret; va_start(ap, def_value); ret = krb5_config_vget_time_default(context, c, def_value, ap); va_end(ap); return ret; } /** * Get the time from the configuration file using a relative time, for example: 1h30s * * @param context A Kerberos 5 context. * @param c a configuration section, or NULL to use the section from context * @param ... a list of names, terminated with NULL. * * @return parsed the time or -1 on error * * @ingroup krb5_support */ KRB5_LIB_FUNCTION int KRB5_LIB_CALL krb5_config_get_time (krb5_context context, const krb5_config_section *c, ...) { va_list ap; int ret; va_start(ap, c); ret = krb5_config_vget_time (context, c, ap); va_end(ap); return ret; } KRB5_LIB_FUNCTION int KRB5_LIB_CALL krb5_config_vget_int_default (krb5_context context, const krb5_config_section *c, int def_value, va_list args) { const char *str; str = krb5_config_vget_string (context, c, args); if(str == NULL) return def_value; else { char *endptr; long l; l = strtol(str, &endptr, 0); if (endptr == str) return def_value; else return l; } } KRB5_LIB_FUNCTION int KRB5_LIB_CALL krb5_config_vget_int (krb5_context context, const krb5_config_section *c, va_list args) { return krb5_config_vget_int_default (context, c, -1, args); } KRB5_LIB_FUNCTION int KRB5_LIB_CALL krb5_config_get_int_default (krb5_context context, const krb5_config_section *c, int def_value, ...) { va_list ap; int ret; va_start(ap, def_value); ret = krb5_config_vget_int_default(context, c, def_value, ap); va_end(ap); return ret; } KRB5_LIB_FUNCTION int KRB5_LIB_CALL krb5_config_get_int (krb5_context context, const krb5_config_section *c, ...) { va_list ap; int ret; va_start(ap, c); ret = krb5_config_vget_int (context, c, ap); va_end(ap); return ret; } #ifndef HEIMDAL_SMALLER /** * Deprecated: configuration files are not strings * * @ingroup krb5_deprecated */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_config_parse_string_multi(krb5_context context, const char *string, krb5_config_section **res) KRB5_DEPRECATED_FUNCTION("Use X instead") { const char *str; unsigned lineno = 0; krb5_error_code ret; struct fileptr f; f.f = NULL; f.s = string; ret = krb5_config_parse_debug (&f, res, &lineno, &str); if (ret) { krb5_set_error_message (context, ret, "%s:%u: %s", "", lineno, str); return ret; } return 0; } #endif heimdal-7.5.0/lib/krb5/test_rfc3961.c0000644000175000017500000001337713026237312015175 0ustar niknik/* * Copyright (c) 2003-2005 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of KTH nor the names of its contributors may be * used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY KTH AND ITS CONTRIBUTORS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL KTH OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "krb5_locl.h" #include #include static void time_encryption(krb5_context context, size_t size, krb5_enctype etype, int iterations) { struct timeval tv1, tv2; krb5_error_code ret; krb5_keyblock key; krb5_crypto crypto; krb5_data data; char *etype_name; void *buf; int i; ret = krb5_generate_random_keyblock(context, etype, &key); if (ret) krb5_err(context, 1, ret, "krb5_generate_random_keyblock"); ret = krb5_enctype_to_string(context, etype, &etype_name); if (ret) krb5_err(context, 1, ret, "krb5_enctype_to_string"); buf = malloc(size); if (buf == NULL) krb5_errx(context, 1, "out of memory"); memset(buf, 0, size); ret = krb5_crypto_init(context, &key, 0, &crypto); if (ret) krb5_err(context, 1, ret, "krb5_crypto_init"); gettimeofday(&tv1, NULL); for (i = 0; i < iterations; i++) { ret = krb5_encrypt(context, crypto, 0, buf, size, &data); if (ret) krb5_err(context, 1, ret, "encrypt: %d", i); krb5_data_free(&data); } gettimeofday(&tv2, NULL); timevalsub(&tv2, &tv1); printf("%s size: %7lu iterations: %d time: %3ld.%06ld\n", etype_name, (unsigned long)size, iterations, (long)tv2.tv_sec, (long)tv2.tv_usec); free(buf); free(etype_name); krb5_crypto_destroy(context, crypto); krb5_free_keyblock_contents(context, &key); } static void time_s2k(krb5_context context, krb5_enctype etype, const char *password, krb5_salt salt, int iterations) { struct timeval tv1, tv2; krb5_error_code ret; krb5_keyblock key; krb5_data opaque; char *etype_name; int i; ret = krb5_enctype_to_string(context, etype, &etype_name); if (ret) krb5_err(context, 1, ret, "krb5_enctype_to_string"); opaque.data = NULL; opaque.length = 0; gettimeofday(&tv1, NULL); for (i = 0; i < iterations; i++) { ret = krb5_string_to_key_salt_opaque(context, etype, password, salt, opaque, &key); if (ret) krb5_err(context, 1, ret, "krb5_string_to_key_data_salt_opaque"); krb5_free_keyblock_contents(context, &key); } gettimeofday(&tv2, NULL); timevalsub(&tv2, &tv1); printf("%s string2key %d iterations time: %3ld.%06ld\n", etype_name, iterations, (long)tv2.tv_sec, (long)tv2.tv_usec); free(etype_name); } static int version_flag = 0; static int help_flag = 0; static struct getargs args[] = { {"version", 0, arg_flag, &version_flag, "print version", NULL }, {"help", 0, arg_flag, &help_flag, NULL, NULL } }; static void usage (int ret) { arg_printusage (args, sizeof(args)/sizeof(*args), NULL, ""); exit (ret); } int main(int argc, char **argv) { krb5_context context; krb5_error_code ret; int i, enciter, s2kiter; int optidx = 0; krb5_salt salt; krb5_enctype enctypes[] = { ETYPE_DES_CBC_CRC, ETYPE_DES3_CBC_SHA1, ETYPE_ARCFOUR_HMAC_MD5, ETYPE_AES128_CTS_HMAC_SHA1_96, ETYPE_AES256_CTS_HMAC_SHA1_96, ETYPE_AES128_CTS_HMAC_SHA256_128, ETYPE_AES256_CTS_HMAC_SHA384_192 }; setprogname(argv[0]); if(getarg(args, sizeof(args) / sizeof(args[0]), argc, argv, &optidx)) usage(1); if (help_flag) usage (0); if(version_flag){ print_version(NULL); exit(0); } salt.salttype = KRB5_PW_SALT; salt.saltvalue.data = NULL; salt.saltvalue.length = 0; ret = krb5_init_context(&context); if (ret) errx (1, "krb5_init_context failed: %d", ret); enciter = 1000; s2kiter = 100; for (i = 0; i < sizeof(enctypes)/sizeof(enctypes[0]); i++) { krb5_enctype_enable(context, enctypes[i]); time_encryption(context, 16, enctypes[i], enciter); time_encryption(context, 32, enctypes[i], enciter); time_encryption(context, 512, enctypes[i], enciter); time_encryption(context, 1024, enctypes[i], enciter); time_encryption(context, 2048, enctypes[i], enciter); time_encryption(context, 4096, enctypes[i], enciter); time_encryption(context, 8192, enctypes[i], enciter); time_encryption(context, 16384, enctypes[i], enciter); time_encryption(context, 32768, enctypes[i], enciter); time_s2k(context, enctypes[i], "mYsecreitPassword", salt, s2kiter); } krb5_free_context(context); return 0; } heimdal-7.5.0/lib/krb5/krb5_verify_init_creds.30000644000175000017500000000701312136107750017404 0ustar niknik.\" Copyright (c) 2003 - 2006 Kungliga Tekniska Högskolan .\" (Royal Institute of Technology, Stockholm, Sweden). .\" All rights reserved. .\" .\" Redistribution and use in source and binary forms, with or without .\" modification, are permitted provided that the following conditions .\" are met: .\" .\" 1. Redistributions of source code must retain the above copyright .\" notice, this list of conditions and the following disclaimer. .\" .\" 2. Redistributions in binary form must reproduce the above copyright .\" notice, this list of conditions and the following disclaimer in the .\" documentation and/or other materials provided with the distribution. .\" .\" 3. Neither the name of the Institute nor the names of its contributors .\" may be used to endorse or promote products derived from this software .\" without specific prior written permission. .\" .\" THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND .\" ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE .\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE .\" ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE .\" FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL .\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS .\" OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) .\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT .\" LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF .\" SUCH DAMAGE. .\" .\" $Id$ .\" .Dd May 1, 2006 .Dt KRB5_VERIFY_INIT_CREDS 3 .Os HEIMDAL .Sh NAME .Nm krb5_verify_init_creds_opt_init , .Nm krb5_verify_init_creds_opt_set_ap_req_nofail , .Nm krb5_verify_init_creds .Nd "verifies a credential cache is correct by using a local keytab" .Sh LIBRARY Kerberos 5 Library (libkrb5, -lkrb5) .Sh SYNOPSIS .In krb5.h .Pp .Li "struct krb5_verify_init_creds_opt;" .Ft void .Fo krb5_verify_init_creds_opt_init .Fa "krb5_verify_init_creds_opt *options" .Fc .Ft void .Fo krb5_verify_init_creds_opt_set_ap_req_nofail .Fa "krb5_verify_init_creds_opt *options" .Fa "int ap_req_nofail" .Fc .Ft krb5_error_code .Fo krb5_verify_init_creds .Fa "krb5_context context" .Fa "krb5_creds *creds" .Fa "krb5_principal ap_req_server" .Fa "krb5_ccache *ccache" .Fa "krb5_verify_init_creds_opt *options" .Fc .Sh DESCRIPTION The .Nm krb5_verify_init_creds function verifies the initial tickets with the local keytab to make sure the response of the KDC was spoof-ed. .Pp .Nm krb5_verify_init_creds will use principal .Fa ap_req_server from the local keytab, if .Dv NULL is passed in, the code will guess the local hostname and use that to form host/hostname/GUESSED-REALM-FOR-HOSTNAME. .Fa creds is the credential that .Nm krb5_verify_init_creds should verify. If .Fa ccache is given .Fn krb5_verify_init_creds stores all credentials it fetched from the KDC there, otherwise it will use a memory credential cache that is destroyed when done. .Pp .Fn krb5_verify_init_creds_opt_init cleans the the structure, must be used before trying to pass it in to .Fn krb5_verify_init_creds . .Pp .Fn krb5_verify_init_creds_opt_set_ap_req_nofail controls controls the behavior if .Fa ap_req_server doesn't exists in the local keytab or in the KDC's database, if it's true, the error will be ignored. Note that this use is possible insecure. .Sh SEE ALSO .Xr krb5 3 , .Xr krb5_get_init_creds 3 , .Xr krb5_verify_user 3 , .Xr krb5.conf 5 heimdal-7.5.0/lib/krb5/addr_families.c0000644000175000017500000011532113026237312015614 0ustar niknik/* * Copyright (c) 1997-2007 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "krb5_locl.h" struct addr_operations { int af; krb5_address_type atype; size_t max_sockaddr_size; krb5_error_code (*sockaddr2addr)(const struct sockaddr *, krb5_address *); krb5_error_code (*sockaddr2port)(const struct sockaddr *, int16_t *); void (*addr2sockaddr)(const krb5_address *, struct sockaddr *, krb5_socklen_t *sa_size, int port); void (*h_addr2sockaddr)(const char *, struct sockaddr *, krb5_socklen_t *, int); krb5_error_code (*h_addr2addr)(const char *, krb5_address *); krb5_boolean (*uninteresting)(const struct sockaddr *); krb5_boolean (*is_loopback)(const struct sockaddr *); void (*anyaddr)(struct sockaddr *, krb5_socklen_t *, int); int (*print_addr)(const krb5_address *, char *, size_t); int (*parse_addr)(krb5_context, const char*, krb5_address *); int (*order_addr)(krb5_context, const krb5_address*, const krb5_address*); int (*free_addr)(krb5_context, krb5_address*); int (*copy_addr)(krb5_context, const krb5_address*, krb5_address*); int (*mask_boundary)(krb5_context, const krb5_address*, unsigned long, krb5_address*, krb5_address*); }; /* * AF_INET - aka IPv4 implementation */ static krb5_error_code ipv4_sockaddr2addr (const struct sockaddr *sa, krb5_address *a) { const struct sockaddr_in *sin4 = (const struct sockaddr_in *)sa; unsigned char buf[4]; a->addr_type = KRB5_ADDRESS_INET; memcpy (buf, &sin4->sin_addr, 4); return krb5_data_copy(&a->address, buf, 4); } static krb5_error_code ipv4_sockaddr2port (const struct sockaddr *sa, int16_t *port) { const struct sockaddr_in *sin4 = (const struct sockaddr_in *)sa; *port = sin4->sin_port; return 0; } static void ipv4_addr2sockaddr (const krb5_address *a, struct sockaddr *sa, krb5_socklen_t *sa_size, int port) { struct sockaddr_in tmp; memset (&tmp, 0, sizeof(tmp)); tmp.sin_family = AF_INET; memcpy (&tmp.sin_addr, a->address.data, 4); tmp.sin_port = port; memcpy(sa, &tmp, min(sizeof(tmp), *sa_size)); *sa_size = sizeof(tmp); } static void ipv4_h_addr2sockaddr(const char *addr, struct sockaddr *sa, krb5_socklen_t *sa_size, int port) { struct sockaddr_in tmp; memset (&tmp, 0, sizeof(tmp)); tmp.sin_family = AF_INET; tmp.sin_port = port; tmp.sin_addr = *((const struct in_addr *)addr); memcpy(sa, &tmp, min(sizeof(tmp), *sa_size)); *sa_size = sizeof(tmp); } static krb5_error_code ipv4_h_addr2addr (const char *addr, krb5_address *a) { unsigned char buf[4]; a->addr_type = KRB5_ADDRESS_INET; memcpy(buf, addr, 4); return krb5_data_copy(&a->address, buf, 4); } /* * Are there any addresses that should be considered `uninteresting'? */ static krb5_boolean ipv4_uninteresting (const struct sockaddr *sa) { const struct sockaddr_in *sin4 = (const struct sockaddr_in *)sa; if (sin4->sin_addr.s_addr == INADDR_ANY) return TRUE; return FALSE; } static krb5_boolean ipv4_is_loopback (const struct sockaddr *sa) { const struct sockaddr_in *sin4 = (const struct sockaddr_in *)sa; if ((ntohl(sin4->sin_addr.s_addr) >> 24) == IN_LOOPBACKNET) return TRUE; return FALSE; } static void ipv4_anyaddr (struct sockaddr *sa, krb5_socklen_t *sa_size, int port) { struct sockaddr_in tmp; memset (&tmp, 0, sizeof(tmp)); tmp.sin_family = AF_INET; tmp.sin_port = port; tmp.sin_addr.s_addr = INADDR_ANY; memcpy(sa, &tmp, min(sizeof(tmp), *sa_size)); *sa_size = sizeof(tmp); } static int ipv4_print_addr (const krb5_address *addr, char *str, size_t len) { struct in_addr ia; memcpy (&ia, addr->address.data, 4); return snprintf (str, len, "IPv4:%s", inet_ntoa(ia)); } static int ipv4_parse_addr (krb5_context context, const char *address, krb5_address *addr) { const char *p; struct in_addr a; p = strchr(address, ':'); if(p) { p++; if(strncasecmp(address, "ip:", p - address) != 0 && strncasecmp(address, "ip4:", p - address) != 0 && strncasecmp(address, "ipv4:", p - address) != 0 && strncasecmp(address, "inet:", p - address) != 0) return -1; } else p = address; if(inet_aton(p, &a) == 0) return -1; addr->addr_type = KRB5_ADDRESS_INET; if(krb5_data_alloc(&addr->address, 4) != 0) return -1; _krb5_put_int(addr->address.data, ntohl(a.s_addr), addr->address.length); return 0; } static int ipv4_mask_boundary(krb5_context context, const krb5_address *inaddr, unsigned long len, krb5_address *low, krb5_address *high) { unsigned long ia; uint32_t l, h, m = 0xffffffff; if (len > 32) { krb5_set_error_message(context, KRB5_PROG_ATYPE_NOSUPP, N_("IPv4 prefix too large (%ld)", "len"), len); return KRB5_PROG_ATYPE_NOSUPP; } m = m << (32 - len); _krb5_get_int(inaddr->address.data, &ia, inaddr->address.length); l = ia & m; h = l | ~m; low->addr_type = KRB5_ADDRESS_INET; if(krb5_data_alloc(&low->address, 4) != 0) return -1; _krb5_put_int(low->address.data, l, low->address.length); high->addr_type = KRB5_ADDRESS_INET; if(krb5_data_alloc(&high->address, 4) != 0) { krb5_free_address(context, low); return -1; } _krb5_put_int(high->address.data, h, high->address.length); return 0; } /* * AF_INET6 - aka IPv6 implementation */ #ifdef HAVE_IPV6 static krb5_error_code ipv6_sockaddr2addr (const struct sockaddr *sa, krb5_address *a) { const struct sockaddr_in6 *sin6 = (const struct sockaddr_in6 *)sa; if (IN6_IS_ADDR_V4MAPPED(&sin6->sin6_addr)) { unsigned char buf[4]; a->addr_type = KRB5_ADDRESS_INET; #ifndef IN6_ADDR_V6_TO_V4 #ifdef IN6_EXTRACT_V4ADDR #define IN6_ADDR_V6_TO_V4(x) (&IN6_EXTRACT_V4ADDR(x)) #else #define IN6_ADDR_V6_TO_V4(x) ((const struct in_addr *)&(x)->s6_addr[12]) #endif #endif memcpy (buf, IN6_ADDR_V6_TO_V4(&sin6->sin6_addr), 4); return krb5_data_copy(&a->address, buf, 4); } else { a->addr_type = KRB5_ADDRESS_INET6; return krb5_data_copy(&a->address, &sin6->sin6_addr, sizeof(sin6->sin6_addr)); } } static krb5_error_code ipv6_sockaddr2port (const struct sockaddr *sa, int16_t *port) { const struct sockaddr_in6 *sin6 = (const struct sockaddr_in6 *)sa; *port = sin6->sin6_port; return 0; } static void ipv6_addr2sockaddr (const krb5_address *a, struct sockaddr *sa, krb5_socklen_t *sa_size, int port) { struct sockaddr_in6 tmp; memset (&tmp, 0, sizeof(tmp)); tmp.sin6_family = AF_INET6; memcpy (&tmp.sin6_addr, a->address.data, sizeof(tmp.sin6_addr)); tmp.sin6_port = port; memcpy(sa, &tmp, min(sizeof(tmp), *sa_size)); *sa_size = sizeof(tmp); } static void ipv6_h_addr2sockaddr(const char *addr, struct sockaddr *sa, krb5_socklen_t *sa_size, int port) { struct sockaddr_in6 tmp; memset (&tmp, 0, sizeof(tmp)); tmp.sin6_family = AF_INET6; tmp.sin6_port = port; tmp.sin6_addr = *((const struct in6_addr *)addr); memcpy(sa, &tmp, min(sizeof(tmp), *sa_size)); *sa_size = sizeof(tmp); } static krb5_error_code ipv6_h_addr2addr (const char *addr, krb5_address *a) { a->addr_type = KRB5_ADDRESS_INET6; return krb5_data_copy(&a->address, addr, sizeof(struct in6_addr)); } /* * */ static krb5_boolean ipv6_uninteresting (const struct sockaddr *sa) { const struct sockaddr_in6 *sin6 = (const struct sockaddr_in6 *)sa; const struct in6_addr *in6 = (const struct in6_addr *)&sin6->sin6_addr; return IN6_IS_ADDR_LINKLOCAL(in6) || IN6_IS_ADDR_V4COMPAT(in6); } static krb5_boolean ipv6_is_loopback (const struct sockaddr *sa) { const struct sockaddr_in6 *sin6 = (const struct sockaddr_in6 *)sa; const struct in6_addr *in6 = (const struct in6_addr *)&sin6->sin6_addr; return (IN6_IS_ADDR_LOOPBACK(in6)); } static void ipv6_anyaddr (struct sockaddr *sa, krb5_socklen_t *sa_size, int port) { struct sockaddr_in6 tmp; memset (&tmp, 0, sizeof(tmp)); tmp.sin6_family = AF_INET6; tmp.sin6_port = port; tmp.sin6_addr = in6addr_any; *sa_size = sizeof(tmp); } static int ipv6_print_addr (const krb5_address *addr, char *str, size_t len) { char buf[128], buf2[3]; if(inet_ntop(AF_INET6, addr->address.data, buf, sizeof(buf)) == NULL) { /* XXX this is pretty ugly, but better than abort() */ size_t i; unsigned char *p = addr->address.data; buf[0] = '\0'; for(i = 0; i < addr->address.length; i++) { snprintf(buf2, sizeof(buf2), "%02x", p[i]); if(i > 0 && (i & 1) == 0) strlcat(buf, ":", sizeof(buf)); strlcat(buf, buf2, sizeof(buf)); } } return snprintf(str, len, "IPv6:%s", buf); } static int ipv6_parse_addr (krb5_context context, const char *address, krb5_address *addr) { int ret; struct in6_addr in6; const char *p; p = strchr(address, ':'); if(p) { p++; if(strncasecmp(address, "ip6:", p - address) == 0 || strncasecmp(address, "ipv6:", p - address) == 0 || strncasecmp(address, "inet6:", p - address) == 0) address = p; } ret = inet_pton(AF_INET6, address, &in6.s6_addr); if(ret == 1) { addr->addr_type = KRB5_ADDRESS_INET6; ret = krb5_data_alloc(&addr->address, sizeof(in6.s6_addr)); if (ret) return -1; memcpy(addr->address.data, in6.s6_addr, sizeof(in6.s6_addr)); return 0; } return -1; } static int ipv6_mask_boundary(krb5_context context, const krb5_address *inaddr, unsigned long len, krb5_address *low, krb5_address *high) { struct in6_addr addr, laddr, haddr; uint32_t m; int i, sub_len; if (len > 128) { krb5_set_error_message(context, KRB5_PROG_ATYPE_NOSUPP, N_("IPv6 prefix too large (%ld)", "length"), len); return KRB5_PROG_ATYPE_NOSUPP; } if (inaddr->address.length != sizeof(addr)) { krb5_set_error_message(context, KRB5_PROG_ATYPE_NOSUPP, N_("IPv6 addr bad length", "")); return KRB5_PROG_ATYPE_NOSUPP; } memcpy(&addr, inaddr->address.data, inaddr->address.length); for (i = 0; i < 16; i++) { sub_len = min(8, len); m = 0xff << (8 - sub_len); laddr.s6_addr[i] = addr.s6_addr[i] & m; haddr.s6_addr[i] = (addr.s6_addr[i] & m) | ~m; if (len > 8) len -= 8; else len = 0; } low->addr_type = KRB5_ADDRESS_INET6; if (krb5_data_alloc(&low->address, sizeof(laddr.s6_addr)) != 0) return -1; memcpy(low->address.data, laddr.s6_addr, sizeof(laddr.s6_addr)); high->addr_type = KRB5_ADDRESS_INET6; if (krb5_data_alloc(&high->address, sizeof(haddr.s6_addr)) != 0) { krb5_free_address(context, low); return -1; } memcpy(high->address.data, haddr.s6_addr, sizeof(haddr.s6_addr)); return 0; } #endif /* IPv6 */ #ifndef HEIMDAL_SMALLER /* * table */ #define KRB5_ADDRESS_ARANGE (-100) struct arange { krb5_address low; krb5_address high; }; static int arange_parse_addr (krb5_context context, const char *address, krb5_address *addr) { char buf[1024], *p; krb5_address low0, high0; struct arange *a; krb5_error_code ret; if(strncasecmp(address, "RANGE:", 6) != 0) return -1; address += 6; p = strrchr(address, '/'); if (p) { krb5_addresses addrmask; char *q; long num; if (strlcpy(buf, address, sizeof(buf)) > sizeof(buf)) return -1; buf[p - address] = '\0'; ret = krb5_parse_address(context, buf, &addrmask); if (ret) return ret; if(addrmask.len != 1) { krb5_free_addresses(context, &addrmask); return -1; } address += p - address + 1; num = strtol(address, &q, 10); if (q == address || *q != '\0' || num < 0) { krb5_free_addresses(context, &addrmask); return -1; } ret = krb5_address_prefixlen_boundary(context, &addrmask.val[0], num, &low0, &high0); krb5_free_addresses(context, &addrmask); if (ret) return ret; } else { krb5_addresses low, high; strsep_copy(&address, "-", buf, sizeof(buf)); ret = krb5_parse_address(context, buf, &low); if(ret) return ret; if(low.len != 1) { krb5_free_addresses(context, &low); return -1; } strsep_copy(&address, "-", buf, sizeof(buf)); ret = krb5_parse_address(context, buf, &high); if(ret) { krb5_free_addresses(context, &low); return ret; } if(high.len != 1 && high.val[0].addr_type != low.val[0].addr_type) { krb5_free_addresses(context, &low); krb5_free_addresses(context, &high); return -1; } ret = krb5_copy_address(context, &high.val[0], &high0); if (ret == 0) { ret = krb5_copy_address(context, &low.val[0], &low0); if (ret) krb5_free_address(context, &high0); } krb5_free_addresses(context, &low); krb5_free_addresses(context, &high); if (ret) return ret; } krb5_data_alloc(&addr->address, sizeof(*a)); addr->addr_type = KRB5_ADDRESS_ARANGE; a = addr->address.data; if(krb5_address_order(context, &low0, &high0) < 0) { a->low = low0; a->high = high0; } else { a->low = high0; a->high = low0; } return 0; } static int arange_free (krb5_context context, krb5_address *addr) { struct arange *a; a = addr->address.data; krb5_free_address(context, &a->low); krb5_free_address(context, &a->high); krb5_data_free(&addr->address); return 0; } static int arange_copy (krb5_context context, const krb5_address *inaddr, krb5_address *outaddr) { krb5_error_code ret; struct arange *i, *o; outaddr->addr_type = KRB5_ADDRESS_ARANGE; ret = krb5_data_alloc(&outaddr->address, sizeof(*o)); if(ret) return ret; i = inaddr->address.data; o = outaddr->address.data; ret = krb5_copy_address(context, &i->low, &o->low); if(ret) { krb5_data_free(&outaddr->address); return ret; } ret = krb5_copy_address(context, &i->high, &o->high); if(ret) { krb5_free_address(context, &o->low); krb5_data_free(&outaddr->address); return ret; } return 0; } static int arange_print_addr (const krb5_address *addr, char *str, size_t len) { struct arange *a; krb5_error_code ret; size_t l, size, ret_len; a = addr->address.data; l = strlcpy(str, "RANGE:", len); ret_len = l; if (l > len) l = len; size = l; ret = krb5_print_address (&a->low, str + size, len - size, &l); if (ret) return ret; ret_len += l; if (len - size > l) size += l; else size = len; l = strlcat(str + size, "-", len - size); ret_len += l; if (len - size > l) size += l; else size = len; ret = krb5_print_address (&a->high, str + size, len - size, &l); if (ret) return ret; ret_len += l; return ret_len; } static int arange_order_addr(krb5_context context, const krb5_address *addr1, const krb5_address *addr2) { int tmp1, tmp2, sign; struct arange *a; const krb5_address *a2; if(addr1->addr_type == KRB5_ADDRESS_ARANGE) { a = addr1->address.data; a2 = addr2; sign = 1; } else if(addr2->addr_type == KRB5_ADDRESS_ARANGE) { a = addr2->address.data; a2 = addr1; sign = -1; } else { abort(); UNREACHABLE(return 0); } if(a2->addr_type == KRB5_ADDRESS_ARANGE) { struct arange *b = a2->address.data; tmp1 = krb5_address_order(context, &a->low, &b->low); if(tmp1 != 0) return sign * tmp1; return sign * krb5_address_order(context, &a->high, &b->high); } else if(a2->addr_type == a->low.addr_type) { tmp1 = krb5_address_order(context, &a->low, a2); if(tmp1 > 0) return sign; tmp2 = krb5_address_order(context, &a->high, a2); if(tmp2 < 0) return -sign; return 0; } else { return sign * (addr1->addr_type - addr2->addr_type); } } #endif /* HEIMDAL_SMALLER */ static int addrport_print_addr (const krb5_address *addr, char *str, size_t len) { krb5_error_code ret; krb5_address addr1, addr2; uint16_t port = 0; size_t ret_len = 0, l, size = 0; krb5_storage *sp; sp = krb5_storage_from_data((krb5_data*)rk_UNCONST(&addr->address)); if (sp == NULL) return ENOMEM; /* for totally obscure reasons, these are not in network byteorder */ krb5_storage_set_byteorder(sp, KRB5_STORAGE_BYTEORDER_LE); krb5_storage_seek(sp, 2, SEEK_CUR); /* skip first two bytes */ krb5_ret_address(sp, &addr1); krb5_storage_seek(sp, 2, SEEK_CUR); /* skip two bytes */ krb5_ret_address(sp, &addr2); krb5_storage_free(sp); if(addr2.addr_type == KRB5_ADDRESS_IPPORT && addr2.address.length == 2) { unsigned long value; _krb5_get_int(addr2.address.data, &value, 2); port = value; } l = strlcpy(str, "ADDRPORT:", len); ret_len += l; if (len > l) size += l; else size = len; ret = krb5_print_address(&addr1, str + size, len - size, &l); if (ret) return ret; ret_len += l; if (len - size > l) size += l; else size = len; ret = snprintf(str + size, len - size, ",PORT=%u", port); if (ret < 0) return EINVAL; ret_len += ret; return ret_len; } static struct addr_operations at[] = { { AF_INET, KRB5_ADDRESS_INET, sizeof(struct sockaddr_in), ipv4_sockaddr2addr, ipv4_sockaddr2port, ipv4_addr2sockaddr, ipv4_h_addr2sockaddr, ipv4_h_addr2addr, ipv4_uninteresting, ipv4_is_loopback, ipv4_anyaddr, ipv4_print_addr, ipv4_parse_addr, NULL, NULL, NULL, ipv4_mask_boundary }, #ifdef HAVE_IPV6 { AF_INET6, KRB5_ADDRESS_INET6, sizeof(struct sockaddr_in6), ipv6_sockaddr2addr, ipv6_sockaddr2port, ipv6_addr2sockaddr, ipv6_h_addr2sockaddr, ipv6_h_addr2addr, ipv6_uninteresting, ipv6_is_loopback, ipv6_anyaddr, ipv6_print_addr, ipv6_parse_addr, NULL, NULL, NULL, ipv6_mask_boundary } , #endif #ifndef HEIMDAL_SMALLER /* fake address type */ { KRB5_ADDRESS_ARANGE, KRB5_ADDRESS_ARANGE, sizeof(struct arange), NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, arange_print_addr, arange_parse_addr, arange_order_addr, arange_free, arange_copy, NULL }, #endif { KRB5_ADDRESS_ADDRPORT, KRB5_ADDRESS_ADDRPORT, 0, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, addrport_print_addr, NULL, NULL, NULL, NULL, NULL } }; static int num_addrs = sizeof(at) / sizeof(at[0]); static size_t max_sockaddr_size = 0; /* * generic functions */ static struct addr_operations * find_af(int af) { struct addr_operations *a; for (a = at; a < at + num_addrs; ++a) if (af == a->af) return a; return NULL; } static struct addr_operations * find_atype(krb5_address_type atype) { struct addr_operations *a; for (a = at; a < at + num_addrs; ++a) if (atype == a->atype) return a; return NULL; } /** * krb5_sockaddr2address stores a address a "struct sockaddr" sa in * the krb5_address addr. * * @param context a Keberos context * @param sa a struct sockaddr to extract the address from * @param addr an Kerberos 5 address to store the address in. * * @return Return an error code or 0. * * @ingroup krb5_address */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_sockaddr2address (krb5_context context, const struct sockaddr *sa, krb5_address *addr) { struct addr_operations *a = find_af(sa->sa_family); if (a == NULL) { krb5_set_error_message (context, KRB5_PROG_ATYPE_NOSUPP, N_("Address family %d not supported", ""), sa->sa_family); return KRB5_PROG_ATYPE_NOSUPP; } return (*a->sockaddr2addr)(sa, addr); } /** * krb5_sockaddr2port extracts a port (if possible) from a "struct * sockaddr. * * @param context a Keberos context * @param sa a struct sockaddr to extract the port from * @param port a pointer to an int16_t store the port in. * * @return Return an error code or 0. Will return * KRB5_PROG_ATYPE_NOSUPP in case address type is not supported. * * @ingroup krb5_address */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_sockaddr2port (krb5_context context, const struct sockaddr *sa, int16_t *port) { struct addr_operations *a = find_af(sa->sa_family); if (a == NULL) { krb5_set_error_message (context, KRB5_PROG_ATYPE_NOSUPP, N_("Address family %d not supported", ""), sa->sa_family); return KRB5_PROG_ATYPE_NOSUPP; } return (*a->sockaddr2port)(sa, port); } /** * krb5_addr2sockaddr sets the "struct sockaddr sockaddr" from addr * and port. The argument sa_size should initially contain the size of * the sa and after the call, it will contain the actual length of the * address. In case of the sa is too small to fit the whole address, * the up to *sa_size will be stored, and then *sa_size will be set to * the required length. * * @param context a Keberos context * @param addr the address to copy the from * @param sa the struct sockaddr that will be filled in * @param sa_size pointer to length of sa, and after the call, it will * contain the actual length of the address. * @param port set port in sa. * * @return Return an error code or 0. Will return * KRB5_PROG_ATYPE_NOSUPP in case address type is not supported. * * @ingroup krb5_address */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_addr2sockaddr (krb5_context context, const krb5_address *addr, struct sockaddr *sa, krb5_socklen_t *sa_size, int port) { struct addr_operations *a = find_atype(addr->addr_type); if (a == NULL) { krb5_set_error_message (context, KRB5_PROG_ATYPE_NOSUPP, N_("Address type %d not supported", "krb5_address type"), addr->addr_type); return KRB5_PROG_ATYPE_NOSUPP; } if (a->addr2sockaddr == NULL) { krb5_set_error_message (context, KRB5_PROG_ATYPE_NOSUPP, N_("Can't convert address type %d to sockaddr", ""), addr->addr_type); return KRB5_PROG_ATYPE_NOSUPP; } (*a->addr2sockaddr)(addr, sa, sa_size, port); return 0; } /** * krb5_max_sockaddr_size returns the max size of the .Li struct * sockaddr that the Kerberos library will return. * * @return Return an size_t of the maximum struct sockaddr. * * @ingroup krb5_address */ KRB5_LIB_FUNCTION size_t KRB5_LIB_CALL krb5_max_sockaddr_size (void) { if (max_sockaddr_size == 0) { struct addr_operations *a; for(a = at; a < at + num_addrs; ++a) max_sockaddr_size = max(max_sockaddr_size, a->max_sockaddr_size); } return max_sockaddr_size; } /** * krb5_sockaddr_uninteresting returns TRUE for all .Fa sa that the * kerberos library thinks are uninteresting. One example are link * local addresses. * * @param sa pointer to struct sockaddr that might be interesting. * * @return Return a non zero for uninteresting addresses. * * @ingroup krb5_address */ KRB5_LIB_FUNCTION krb5_boolean KRB5_LIB_CALL krb5_sockaddr_uninteresting(const struct sockaddr *sa) { struct addr_operations *a = find_af(sa->sa_family); if (a == NULL || a->uninteresting == NULL) return TRUE; return (*a->uninteresting)(sa); } KRB5_LIB_FUNCTION krb5_boolean KRB5_LIB_CALL krb5_sockaddr_is_loopback(const struct sockaddr *sa) { struct addr_operations *a = find_af(sa->sa_family); if (a == NULL || a->is_loopback == NULL) return TRUE; return (*a->is_loopback)(sa); } /** * krb5_h_addr2sockaddr initializes a "struct sockaddr sa" from af and * the "struct hostent" (see gethostbyname(3) ) h_addr_list * component. The argument sa_size should initially contain the size * of the sa, and after the call, it will contain the actual length of * the address. * * @param context a Keberos context * @param af addresses * @param addr address * @param sa returned struct sockaddr * @param sa_size size of sa * @param port port to set in sa. * * @return Return an error code or 0. * * @ingroup krb5_address */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_h_addr2sockaddr (krb5_context context, int af, const char *addr, struct sockaddr *sa, krb5_socklen_t *sa_size, int port) { struct addr_operations *a = find_af(af); if (a == NULL) { krb5_set_error_message (context, KRB5_PROG_ATYPE_NOSUPP, "Address family %d not supported", af); return KRB5_PROG_ATYPE_NOSUPP; } (*a->h_addr2sockaddr)(addr, sa, sa_size, port); return 0; } /** * krb5_h_addr2addr works like krb5_h_addr2sockaddr with the exception * that it operates on a krb5_address instead of a struct sockaddr. * * @param context a Keberos context * @param af address family * @param haddr host address from struct hostent. * @param addr returned krb5_address. * * @return Return an error code or 0. * * @ingroup krb5_address */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_h_addr2addr (krb5_context context, int af, const char *haddr, krb5_address *addr) { struct addr_operations *a = find_af(af); if (a == NULL) { krb5_set_error_message (context, KRB5_PROG_ATYPE_NOSUPP, N_("Address family %d not supported", ""), af); return KRB5_PROG_ATYPE_NOSUPP; } return (*a->h_addr2addr)(haddr, addr); } /** * krb5_anyaddr fills in a "struct sockaddr sa" that can be used to * bind(2) to. The argument sa_size should initially contain the size * of the sa, and after the call, it will contain the actual length * of the address. * * @param context a Keberos context * @param af address family * @param sa sockaddr * @param sa_size lenght of sa. * @param port for to fill into sa. * * @return Return an error code or 0. * * @ingroup krb5_address */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_anyaddr (krb5_context context, int af, struct sockaddr *sa, krb5_socklen_t *sa_size, int port) { struct addr_operations *a = find_af (af); if (a == NULL) { krb5_set_error_message (context, KRB5_PROG_ATYPE_NOSUPP, N_("Address family %d not supported", ""), af); return KRB5_PROG_ATYPE_NOSUPP; } (*a->anyaddr)(sa, sa_size, port); return 0; } /** * krb5_print_address prints the address in addr to the string string * that have the length len. If ret_len is not NULL, it will be filled * with the length of the string if size were unlimited (not including * the final NUL) . * * @param addr address to be printed * @param str pointer string to print the address into * @param len length that will fit into area pointed to by "str". * @param ret_len return length the str. * * @return Return an error code or 0. * * @ingroup krb5_address */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_print_address (const krb5_address *addr, char *str, size_t len, size_t *ret_len) { struct addr_operations *a = find_atype(addr->addr_type); int ret; if (a == NULL || a->print_addr == NULL) { char *s; int l; size_t i; s = str; l = snprintf(s, len, "TYPE_%d:", addr->addr_type); if (l < 0 || (size_t)l >= len) return EINVAL; s += l; len -= l; for(i = 0; i < addr->address.length; i++) { l = snprintf(s, len, "%02x", ((char*)addr->address.data)[i]); if (l < 0 || (size_t)l >= len) return EINVAL; len -= l; s += l; } if(ret_len != NULL) *ret_len = s - str; return 0; } ret = (*a->print_addr)(addr, str, len); if (ret < 0) return EINVAL; if(ret_len != NULL) *ret_len = ret; return 0; } /** * krb5_parse_address returns the resolved hostname in string to the * krb5_addresses addresses . * * @param context a Keberos context * @param string * @param addresses * * @return Return an error code or 0. * * @ingroup krb5_address */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_parse_address(krb5_context context, const char *string, krb5_addresses *addresses) { int i, n; struct addrinfo *ai, *a; struct addrinfo hint; int error; int save_errno; addresses->len = 0; addresses->val = NULL; for(i = 0; i < num_addrs; i++) { if(at[i].parse_addr) { krb5_address addr; if((*at[i].parse_addr)(context, string, &addr) == 0) { ALLOC_SEQ(addresses, 1); if (addresses->val == NULL) return krb5_enomem(context); addresses->val[0] = addr; return 0; } } } /* if not parsed as numeric address, do a name lookup */ memset(&hint, 0, sizeof(hint)); hint.ai_family = AF_UNSPEC; error = getaddrinfo (string, NULL, &hint, &ai); if (error) { krb5_error_code ret2; save_errno = errno; ret2 = krb5_eai_to_heim_errno(error, save_errno); krb5_set_error_message (context, ret2, "%s: %s", string, gai_strerror(error)); return ret2; } n = 0; for (a = ai; a != NULL; a = a->ai_next) ++n; ALLOC_SEQ(addresses, n); if (addresses->val == NULL) { freeaddrinfo(ai); return krb5_enomem(context); } addresses->len = 0; for (a = ai, i = 0; a != NULL; a = a->ai_next) { if (krb5_sockaddr2address (context, a->ai_addr, &addresses->val[i])) continue; if(krb5_address_search(context, &addresses->val[i], addresses)) { krb5_free_address(context, &addresses->val[i]); continue; } i++; addresses->len = i; } freeaddrinfo (ai); return 0; } /** * krb5_address_order compares the addresses addr1 and addr2 so that * it can be used for sorting addresses. If the addresses are the same * address krb5_address_order will return 0. Behavies like memcmp(2). * * @param context a Keberos context * @param addr1 krb5_address to compare * @param addr2 krb5_address to compare * * @return < 0 if address addr1 in "less" then addr2. 0 if addr1 and * addr2 is the same address, > 0 if addr2 is "less" then addr1. * * @ingroup krb5_address */ KRB5_LIB_FUNCTION int KRB5_LIB_CALL krb5_address_order(krb5_context context, const krb5_address *addr1, const krb5_address *addr2) { /* this sucks; what if both addresses have order functions, which should we call? this works for now, though */ struct addr_operations *a; a = find_atype(addr1->addr_type); if(a == NULL) { krb5_set_error_message (context, KRB5_PROG_ATYPE_NOSUPP, N_("Address family %d not supported", ""), addr1->addr_type); return KRB5_PROG_ATYPE_NOSUPP; } if(a->order_addr != NULL) return (*a->order_addr)(context, addr1, addr2); a = find_atype(addr2->addr_type); if(a == NULL) { krb5_set_error_message (context, KRB5_PROG_ATYPE_NOSUPP, N_("Address family %d not supported", ""), addr2->addr_type); return KRB5_PROG_ATYPE_NOSUPP; } if(a->order_addr != NULL) return (*a->order_addr)(context, addr1, addr2); if(addr1->addr_type != addr2->addr_type) return addr1->addr_type - addr2->addr_type; if(addr1->address.length != addr2->address.length) return addr1->address.length - addr2->address.length; return memcmp (addr1->address.data, addr2->address.data, addr1->address.length); } /** * krb5_address_compare compares the addresses addr1 and addr2. * Returns TRUE if the two addresses are the same. * * @param context a Keberos context * @param addr1 address to compare * @param addr2 address to compare * * @return Return an TRUE is the address are the same FALSE if not * * @ingroup krb5_address */ KRB5_LIB_FUNCTION krb5_boolean KRB5_LIB_CALL krb5_address_compare(krb5_context context, const krb5_address *addr1, const krb5_address *addr2) { return krb5_address_order (context, addr1, addr2) == 0; } /** * krb5_address_search checks if the address addr is a member of the * address set list addrlist . * * @param context a Keberos context. * @param addr address to search for. * @param addrlist list of addresses to look in for addr. * * @return Return an error code or 0. * * @ingroup krb5_address */ KRB5_LIB_FUNCTION krb5_boolean KRB5_LIB_CALL krb5_address_search(krb5_context context, const krb5_address *addr, const krb5_addresses *addrlist) { size_t i; for (i = 0; i < addrlist->len; ++i) if (krb5_address_compare (context, addr, &addrlist->val[i])) return TRUE; return FALSE; } /** * krb5_free_address frees the data stored in the address that is * alloced with any of the krb5_address functions. * * @param context a Keberos context * @param address addresss to be freed. * * @return Return an error code or 0. * * @ingroup krb5_address */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_free_address(krb5_context context, krb5_address *address) { struct addr_operations *a = find_atype (address->addr_type); if(a != NULL && a->free_addr != NULL) return (*a->free_addr)(context, address); krb5_data_free (&address->address); memset(address, 0, sizeof(*address)); return 0; } /** * krb5_free_addresses frees the data stored in the address that is * alloced with any of the krb5_address functions. * * @param context a Keberos context * @param addresses addressses to be freed. * * @return Return an error code or 0. * * @ingroup krb5_address */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_free_addresses(krb5_context context, krb5_addresses *addresses) { size_t i; for(i = 0; i < addresses->len; i++) krb5_free_address(context, &addresses->val[i]); free(addresses->val); addresses->len = 0; addresses->val = NULL; return 0; } /** * krb5_copy_address copies the content of address * inaddr to outaddr. * * @param context a Keberos context * @param inaddr pointer to source address * @param outaddr pointer to destination address * * @return Return an error code or 0. * * @ingroup krb5_address */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_copy_address(krb5_context context, const krb5_address *inaddr, krb5_address *outaddr) { struct addr_operations *a = find_af (inaddr->addr_type); if(a != NULL && a->copy_addr != NULL) return (*a->copy_addr)(context, inaddr, outaddr); return copy_HostAddress(inaddr, outaddr); } /** * krb5_copy_addresses copies the content of addresses * inaddr to outaddr. * * @param context a Keberos context * @param inaddr pointer to source addresses * @param outaddr pointer to destination addresses * * @return Return an error code or 0. * * @ingroup krb5_address */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_copy_addresses(krb5_context context, const krb5_addresses *inaddr, krb5_addresses *outaddr) { size_t i; ALLOC_SEQ(outaddr, inaddr->len); if(inaddr->len > 0 && outaddr->val == NULL) return krb5_enomem(context); for(i = 0; i < inaddr->len; i++) krb5_copy_address(context, &inaddr->val[i], &outaddr->val[i]); return 0; } /** * krb5_append_addresses adds the set of addresses in source to * dest. While copying the addresses, duplicates are also sorted out. * * @param context a Keberos context * @param dest destination of copy operation * @param source adresses that are going to be added to dest * * @return Return an error code or 0. * * @ingroup krb5_address */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_append_addresses(krb5_context context, krb5_addresses *dest, const krb5_addresses *source) { krb5_address *tmp; krb5_error_code ret; size_t i; if(source->len > 0) { tmp = realloc(dest->val, (dest->len + source->len) * sizeof(*tmp)); if (tmp == NULL) return krb5_enomem(context); dest->val = tmp; for(i = 0; i < source->len; i++) { /* skip duplicates */ if(krb5_address_search(context, &source->val[i], dest)) continue; ret = krb5_copy_address(context, &source->val[i], &dest->val[dest->len]); if(ret) return ret; dest->len++; } } return 0; } /** * Create an address of type KRB5_ADDRESS_ADDRPORT from (addr, port) * * @param context a Keberos context * @param res built address from addr/port * @param addr address to use * @param port port to use * * @return Return an error code or 0. * * @ingroup krb5_address */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_make_addrport (krb5_context context, krb5_address **res, const krb5_address *addr, int16_t port) { krb5_error_code ret; size_t len = addr->address.length + 2 + 4 * 4; u_char *p; *res = malloc (sizeof(**res)); if (*res == NULL) return krb5_enomem(context); (*res)->addr_type = KRB5_ADDRESS_ADDRPORT; ret = krb5_data_alloc (&(*res)->address, len); if (ret) { free (*res); *res = NULL; return krb5_enomem(context); } p = (*res)->address.data; *p++ = 0; *p++ = 0; *p++ = (addr->addr_type ) & 0xFF; *p++ = (addr->addr_type >> 8) & 0xFF; *p++ = (addr->address.length ) & 0xFF; *p++ = (addr->address.length >> 8) & 0xFF; *p++ = (addr->address.length >> 16) & 0xFF; *p++ = (addr->address.length >> 24) & 0xFF; memcpy (p, addr->address.data, addr->address.length); p += addr->address.length; *p++ = 0; *p++ = 0; *p++ = (KRB5_ADDRESS_IPPORT ) & 0xFF; *p++ = (KRB5_ADDRESS_IPPORT >> 8) & 0xFF; *p++ = (2 ) & 0xFF; *p++ = (2 >> 8) & 0xFF; *p++ = (2 >> 16) & 0xFF; *p++ = (2 >> 24) & 0xFF; memcpy (p, &port, 2); return 0; } /** * Calculate the boundary addresses of `inaddr'/`prefixlen' and store * them in `low' and `high'. * * @param context a Keberos context * @param inaddr address in prefixlen that the bondery searched * @param prefixlen width of boundery * @param low lowest address * @param high highest address * * @return Return an error code or 0. * * @ingroup krb5_address */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_address_prefixlen_boundary(krb5_context context, const krb5_address *inaddr, unsigned long prefixlen, krb5_address *low, krb5_address *high) { struct addr_operations *a = find_atype (inaddr->addr_type); if(a != NULL && a->mask_boundary != NULL) return (*a->mask_boundary)(context, inaddr, prefixlen, low, high); krb5_set_error_message(context, KRB5_PROG_ATYPE_NOSUPP, N_("Address family %d doesn't support " "address mask operation", ""), inaddr->addr_type); return KRB5_PROG_ATYPE_NOSUPP; } heimdal-7.5.0/lib/krb5/crypto-arcfour.c0000644000175000017500000002233113212137553016011 0ustar niknik/* * Copyright (c) 1997 - 2008 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ /* * ARCFOUR */ #include "krb5_locl.h" static struct _krb5_key_type keytype_arcfour = { KRB5_ENCTYPE_ARCFOUR_HMAC_MD5, "arcfour", 128, 16, sizeof(struct _krb5_evp_schedule), NULL, _krb5_evp_schedule, _krb5_arcfour_salt, NULL, _krb5_evp_cleanup, EVP_rc4 }; /* * checksum according to section 5. of draft-brezak-win2k-krb-rc4-hmac-03.txt */ krb5_error_code _krb5_HMAC_MD5_checksum(krb5_context context, struct _krb5_key_data *key, const void *data, size_t len, unsigned usage, Checksum *result) { EVP_MD_CTX *m; struct _krb5_checksum_type *c = _krb5_find_checksum (CKSUMTYPE_RSA_MD5); const char signature[] = "signaturekey"; Checksum ksign_c; struct _krb5_key_data ksign; krb5_keyblock kb; unsigned char t[4]; unsigned char tmp[16]; unsigned char ksign_c_data[16]; krb5_error_code ret; m = EVP_MD_CTX_create(); if (m == NULL) return krb5_enomem(context); ksign_c.checksum.length = sizeof(ksign_c_data); ksign_c.checksum.data = ksign_c_data; ret = _krb5_internal_hmac(context, c, signature, sizeof(signature), 0, key, &ksign_c); if (ret) { EVP_MD_CTX_destroy(m); return ret; } ksign.key = &kb; kb.keyvalue = ksign_c.checksum; EVP_DigestInit_ex(m, EVP_md5(), NULL); t[0] = (usage >> 0) & 0xFF; t[1] = (usage >> 8) & 0xFF; t[2] = (usage >> 16) & 0xFF; t[3] = (usage >> 24) & 0xFF; EVP_DigestUpdate(m, t, 4); EVP_DigestUpdate(m, data, len); EVP_DigestFinal_ex (m, tmp, NULL); EVP_MD_CTX_destroy(m); ret = _krb5_internal_hmac(context, c, tmp, sizeof(tmp), 0, &ksign, result); if (ret) return ret; return 0; } struct _krb5_checksum_type _krb5_checksum_hmac_md5 = { CKSUMTYPE_HMAC_MD5, "hmac-md5", 64, 16, F_KEYED | F_CPROOF, _krb5_HMAC_MD5_checksum, NULL }; /* * section 6 of draft-brezak-win2k-krb-rc4-hmac-03 * * warning: not for small children */ static krb5_error_code ARCFOUR_subencrypt(krb5_context context, struct _krb5_key_data *key, void *data, size_t len, unsigned usage, void *ivec) { EVP_CIPHER_CTX ctx; struct _krb5_checksum_type *c = _krb5_find_checksum (CKSUMTYPE_RSA_MD5); Checksum k1_c, k2_c, k3_c, cksum; struct _krb5_key_data ke; krb5_keyblock kb; unsigned char t[4]; unsigned char *cdata = data; unsigned char k1_c_data[16], k2_c_data[16], k3_c_data[16]; krb5_error_code ret; t[0] = (usage >> 0) & 0xFF; t[1] = (usage >> 8) & 0xFF; t[2] = (usage >> 16) & 0xFF; t[3] = (usage >> 24) & 0xFF; k1_c.checksum.length = sizeof(k1_c_data); k1_c.checksum.data = k1_c_data; ret = _krb5_internal_hmac(context, c, t, sizeof(t), 0, key, &k1_c); if (ret) krb5_abortx(context, "hmac failed"); memcpy (k2_c_data, k1_c_data, sizeof(k1_c_data)); k2_c.checksum.length = sizeof(k2_c_data); k2_c.checksum.data = k2_c_data; ke.key = &kb; kb.keyvalue = k2_c.checksum; cksum.checksum.length = 16; cksum.checksum.data = data; ret = _krb5_internal_hmac(context, c, cdata + 16, len - 16, 0, &ke, &cksum); if (ret) krb5_abortx(context, "hmac failed"); ke.key = &kb; kb.keyvalue = k1_c.checksum; k3_c.checksum.length = sizeof(k3_c_data); k3_c.checksum.data = k3_c_data; ret = _krb5_internal_hmac(context, c, data, 16, 0, &ke, &k3_c); if (ret) krb5_abortx(context, "hmac failed"); EVP_CIPHER_CTX_init(&ctx); EVP_CipherInit_ex(&ctx, EVP_rc4(), NULL, k3_c.checksum.data, NULL, 1); EVP_Cipher(&ctx, cdata + 16, cdata + 16, len - 16); EVP_CIPHER_CTX_cleanup(&ctx); memset (k1_c_data, 0, sizeof(k1_c_data)); memset (k2_c_data, 0, sizeof(k2_c_data)); memset (k3_c_data, 0, sizeof(k3_c_data)); return 0; } static krb5_error_code ARCFOUR_subdecrypt(krb5_context context, struct _krb5_key_data *key, void *data, size_t len, unsigned usage, void *ivec) { EVP_CIPHER_CTX ctx; struct _krb5_checksum_type *c = _krb5_find_checksum (CKSUMTYPE_RSA_MD5); Checksum k1_c, k2_c, k3_c, cksum; struct _krb5_key_data ke; krb5_keyblock kb; unsigned char t[4]; unsigned char *cdata = data; unsigned char k1_c_data[16], k2_c_data[16], k3_c_data[16]; unsigned char cksum_data[16]; krb5_error_code ret; t[0] = (usage >> 0) & 0xFF; t[1] = (usage >> 8) & 0xFF; t[2] = (usage >> 16) & 0xFF; t[3] = (usage >> 24) & 0xFF; k1_c.checksum.length = sizeof(k1_c_data); k1_c.checksum.data = k1_c_data; ret = _krb5_internal_hmac(context, c, t, sizeof(t), 0, key, &k1_c); if (ret) krb5_abortx(context, "hmac failed"); memcpy (k2_c_data, k1_c_data, sizeof(k1_c_data)); k2_c.checksum.length = sizeof(k2_c_data); k2_c.checksum.data = k2_c_data; ke.key = &kb; kb.keyvalue = k1_c.checksum; k3_c.checksum.length = sizeof(k3_c_data); k3_c.checksum.data = k3_c_data; ret = _krb5_internal_hmac(context, c, cdata, 16, 0, &ke, &k3_c); if (ret) krb5_abortx(context, "hmac failed"); EVP_CIPHER_CTX_init(&ctx); EVP_CipherInit_ex(&ctx, EVP_rc4(), NULL, k3_c.checksum.data, NULL, 0); EVP_Cipher(&ctx, cdata + 16, cdata + 16, len - 16); EVP_CIPHER_CTX_cleanup(&ctx); ke.key = &kb; kb.keyvalue = k2_c.checksum; cksum.checksum.length = 16; cksum.checksum.data = cksum_data; ret = _krb5_internal_hmac(context, c, cdata + 16, len - 16, 0, &ke, &cksum); if (ret) krb5_abortx(context, "hmac failed"); memset (k1_c_data, 0, sizeof(k1_c_data)); memset (k2_c_data, 0, sizeof(k2_c_data)); memset (k3_c_data, 0, sizeof(k3_c_data)); if (ct_memcmp (cksum.checksum.data, data, 16) != 0) { krb5_clear_error_message (context); return KRB5KRB_AP_ERR_BAD_INTEGRITY; } else { return 0; } } /* * convert the usage numbers used in * draft-ietf-cat-kerb-key-derivation-00.txt to the ones in * draft-brezak-win2k-krb-rc4-hmac-04.txt */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL _krb5_usage2arcfour(krb5_context context, unsigned *usage) { switch (*usage) { case KRB5_KU_AS_REP_ENC_PART : /* 3 */ *usage = 8; return 0; case KRB5_KU_USAGE_SEAL : /* 22 */ *usage = 13; return 0; case KRB5_KU_USAGE_SIGN : /* 23 */ *usage = 15; return 0; case KRB5_KU_USAGE_SEQ: /* 24 */ *usage = 0; return 0; default : return 0; } } static krb5_error_code ARCFOUR_encrypt(krb5_context context, struct _krb5_key_data *key, void *data, size_t len, krb5_boolean encryptp, int usage, void *ivec) { krb5_error_code ret; unsigned keyusage = usage; if((ret = _krb5_usage2arcfour (context, &keyusage)) != 0) return ret; if (encryptp) return ARCFOUR_subencrypt (context, key, data, len, keyusage, ivec); else return ARCFOUR_subdecrypt (context, key, data, len, keyusage, ivec); } static krb5_error_code ARCFOUR_prf(krb5_context context, krb5_crypto crypto, const krb5_data *in, krb5_data *out) { struct _krb5_checksum_type *c = _krb5_find_checksum(CKSUMTYPE_SHA1); krb5_error_code ret; Checksum res; ret = krb5_data_alloc(out, c->checksumsize); if (ret) return ret; res.checksum.data = out->data; res.checksum.length = out->length; ret = _krb5_internal_hmac(context, c, in->data, in->length, 0, &crypto->key, &res); if (ret) krb5_data_free(out); return 0; } struct _krb5_encryption_type _krb5_enctype_arcfour_hmac_md5 = { ETYPE_ARCFOUR_HMAC_MD5, "arcfour-hmac-md5", "rc4-hmac", 1, 1, 8, &keytype_arcfour, &_krb5_checksum_hmac_md5, &_krb5_checksum_hmac_md5, F_SPECIAL | F_WEAK, ARCFOUR_encrypt, 0, ARCFOUR_prf }; heimdal-7.5.0/lib/krb5/fcache.c0000644000175000017500000010022113212137553014236 0ustar niknik/* * Copyright (c) 1997 - 2008 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Portions Copyright (c) 2009 Apple Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "krb5_locl.h" typedef struct krb5_fcache{ char *filename; int version; }krb5_fcache; struct fcc_cursor { int fd; off_t cred_start; off_t cred_end; krb5_storage *sp; }; #define KRB5_FCC_FVNO_1 1 #define KRB5_FCC_FVNO_2 2 #define KRB5_FCC_FVNO_3 3 #define KRB5_FCC_FVNO_4 4 #define FCC_TAG_DELTATIME 1 #define FCACHE(X) ((krb5_fcache*)(X)->data.data) #define FILENAME(X) (FCACHE(X)->filename) #define FCC_CURSOR(C) ((struct fcc_cursor*)(C)) static const char* KRB5_CALLCONV fcc_get_name(krb5_context context, krb5_ccache id) { if (FCACHE(id) == NULL) return NULL; return FILENAME(id); } KRB5_LIB_FUNCTION int KRB5_LIB_CALL _krb5_xlock(krb5_context context, int fd, krb5_boolean exclusive, const char *filename) { int ret; #ifdef HAVE_FCNTL struct flock l; l.l_start = 0; l.l_len = 0; l.l_type = exclusive ? F_WRLCK : F_RDLCK; l.l_whence = SEEK_SET; ret = fcntl(fd, F_SETLKW, &l); #else ret = flock(fd, exclusive ? LOCK_EX : LOCK_SH); #endif if(ret < 0) ret = errno; if(ret == EACCES) /* fcntl can return EACCES instead of EAGAIN */ ret = EAGAIN; switch (ret) { case 0: break; case EINVAL: /* filesystem doesn't support locking, let the user have it */ ret = 0; break; case EAGAIN: krb5_set_error_message(context, ret, N_("timed out locking cache file %s", "file"), filename); break; default: { char buf[128]; rk_strerror_r(ret, buf, sizeof(buf)); krb5_set_error_message(context, ret, N_("error locking cache file %s: %s", "file, error"), filename, buf); break; } } return ret; } KRB5_LIB_FUNCTION int KRB5_LIB_CALL _krb5_xunlock(krb5_context context, int fd) { int ret; #ifdef HAVE_FCNTL struct flock l; l.l_start = 0; l.l_len = 0; l.l_type = F_UNLCK; l.l_whence = SEEK_SET; ret = fcntl(fd, F_SETLKW, &l); #else ret = flock(fd, LOCK_UN); #endif if (ret < 0) ret = errno; switch (ret) { case 0: break; case EINVAL: /* filesystem doesn't support locking, let the user have it */ ret = 0; break; default: { char buf[128]; rk_strerror_r(ret, buf, sizeof(buf)); krb5_set_error_message(context, ret, N_("Failed to unlock file: %s", ""), buf); break; } } return ret; } static krb5_error_code write_storage(krb5_context context, krb5_storage *sp, int fd) { krb5_error_code ret; krb5_data data; ssize_t sret; ret = krb5_storage_to_data(sp, &data); if (ret) { krb5_set_error_message(context, ret, N_("malloc: out of memory", "")); return ret; } sret = write(fd, data.data, data.length); ret = (sret != (ssize_t)data.length); krb5_data_free(&data); if (ret) { ret = errno; krb5_set_error_message(context, ret, N_("Failed to write FILE credential data", "")); return ret; } return 0; } static krb5_error_code KRB5_CALLCONV fcc_lock(krb5_context context, krb5_ccache id, int fd, krb5_boolean exclusive) { return _krb5_xlock(context, fd, exclusive, fcc_get_name(context, id)); } static krb5_error_code KRB5_CALLCONV fcc_unlock(krb5_context context, int fd) { return _krb5_xunlock(context, fd); } static krb5_error_code KRB5_CALLCONV fcc_resolve(krb5_context context, krb5_ccache *id, const char *res) { krb5_fcache *f; f = malloc(sizeof(*f)); if(f == NULL) { krb5_set_error_message(context, KRB5_CC_NOMEM, N_("malloc: out of memory", "")); return KRB5_CC_NOMEM; } f->filename = strdup(res); if(f->filename == NULL){ free(f); krb5_set_error_message(context, KRB5_CC_NOMEM, N_("malloc: out of memory", "")); return KRB5_CC_NOMEM; } f->version = 0; (*id)->data.data = f; (*id)->data.length = sizeof(*f); return 0; } /* * Try to scrub the contents of `filename' safely. */ static int scrub_file (int fd) { off_t pos; char buf[128]; pos = lseek(fd, 0, SEEK_END); if (pos < 0) return errno; if (lseek(fd, 0, SEEK_SET) < 0) return errno; memset(buf, 0, sizeof(buf)); while(pos > 0) { ssize_t tmp; size_t wr = sizeof(buf); if (wr > pos) wr = (size_t)pos; tmp = write(fd, buf, wr); if (tmp < 0) return errno; pos -= tmp; } #ifdef _MSC_VER _commit (fd); #else fsync (fd); #endif return 0; } /* * Erase `filename' if it exists, trying to remove the contents if * it's `safe'. We always try to remove the file, it it exists. It's * only overwritten if it's a regular file (not a symlink and not a * hardlink) */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL _krb5_erase_file(krb5_context context, const char *filename) { int fd; struct stat sb1, sb2; int ret; ret = lstat (filename, &sb1); if (ret < 0) return errno; fd = open(filename, O_RDWR | O_BINARY | O_CLOEXEC | O_NOFOLLOW); if(fd < 0) { if(errno == ENOENT) return 0; else return errno; } rk_cloexec(fd); ret = _krb5_xlock(context, fd, 1, filename); if (ret) { close(fd); return ret; } if (unlink(filename) < 0) { ret = errno; _krb5_xunlock(context, fd); close (fd); krb5_set_error_message(context, errno, N_("krb5_cc_destroy: unlinking \"%s\": %s", ""), filename, strerror(ret)); return ret; } ret = fstat(fd, &sb2); if (ret < 0) { ret = errno; _krb5_xunlock(context, fd); close (fd); return ret; } /* check if someone was playing with symlinks */ if (sb1.st_dev != sb2.st_dev || sb1.st_ino != sb2.st_ino) { _krb5_xunlock(context, fd); close(fd); return EPERM; } /* there are still hard links to this file */ if (sb2.st_nlink != 0) { _krb5_xunlock(context, fd); close(fd); return 0; } ret = scrub_file(fd); if (ret) { _krb5_xunlock(context, fd); close(fd); return ret; } ret = _krb5_xunlock(context, fd); close(fd); return ret; } static krb5_error_code KRB5_CALLCONV fcc_gen_new(krb5_context context, krb5_ccache *id) { char *file = NULL, *exp_file = NULL; krb5_error_code ret; krb5_fcache *f; int fd; f = malloc(sizeof(*f)); if(f == NULL) { krb5_set_error_message(context, KRB5_CC_NOMEM, N_("malloc: out of memory", "")); return KRB5_CC_NOMEM; } ret = asprintf(&file, "%sXXXXXX", KRB5_DEFAULT_CCFILE_ROOT); if(ret < 0 || file == NULL) { free(f); krb5_set_error_message(context, KRB5_CC_NOMEM, N_("malloc: out of memory", "")); return KRB5_CC_NOMEM; } ret = _krb5_expand_path_tokens(context, file, 1, &exp_file); free(file); if (ret) { free(f); return ret; } file = exp_file; fd = mkstemp(exp_file); if(fd < 0) { ret = (krb5_error_code)errno; krb5_set_error_message(context, ret, N_("mkstemp %s failed", ""), exp_file); free(f); free(exp_file); return ret; } close(fd); f->filename = exp_file; f->version = 0; (*id)->data.data = f; (*id)->data.length = sizeof(*f); return 0; } static void storage_set_flags(krb5_context context, krb5_storage *sp, int vno) { int flags = 0; switch(vno) { case KRB5_FCC_FVNO_1: flags |= KRB5_STORAGE_PRINCIPAL_WRONG_NUM_COMPONENTS; flags |= KRB5_STORAGE_PRINCIPAL_NO_NAME_TYPE; flags |= KRB5_STORAGE_HOST_BYTEORDER; break; case KRB5_FCC_FVNO_2: flags |= KRB5_STORAGE_HOST_BYTEORDER; break; case KRB5_FCC_FVNO_3: flags |= KRB5_STORAGE_KEYBLOCK_KEYTYPE_TWICE; break; case KRB5_FCC_FVNO_4: break; default: krb5_abortx(context, "storage_set_flags called with bad vno (%x)", vno); } krb5_storage_set_flags(sp, flags); } static krb5_error_code KRB5_CALLCONV fcc_open(krb5_context context, krb5_ccache id, const char *operation, int *fd_ret, int flags, mode_t mode) { krb5_boolean exclusive = ((flags | O_WRONLY) == flags || (flags | O_RDWR) == flags); krb5_error_code ret; const char *filename; struct stat sb1, sb2; #ifndef _WIN32 struct stat sb3; size_t tries = 3; #endif int strict_checking; int fd; flags |= O_BINARY | O_CLOEXEC | O_NOFOLLOW; *fd_ret = -1; if (FCACHE(id) == NULL) return krb5_einval(context, 2); filename = FILENAME(id); strict_checking = (flags & O_CREAT) == 0 && (context->flags & KRB5_CTX_F_FCACHE_STRICT_CHECKING) != 0; again: memset(&sb1, 0, sizeof(sb1)); ret = lstat(filename, &sb1); if (ret == 0) { if (!S_ISREG(sb1.st_mode)) { krb5_set_error_message(context, EPERM, N_("Refuses to open symlinks for caches FILE:%s", ""), filename); return EPERM; } } else if (errno != ENOENT || !(flags & O_CREAT)) { krb5_set_error_message(context, errno, N_("%s lstat(%s)", "file, error"), operation, filename); return errno; } fd = open(filename, flags, mode); if(fd < 0) { char buf[128]; ret = errno; rk_strerror_r(ret, buf, sizeof(buf)); krb5_set_error_message(context, ret, N_("%s open(%s): %s", "file, error"), operation, filename, buf); return ret; } rk_cloexec(fd); ret = fstat(fd, &sb2); if (ret < 0) { krb5_clear_error_message(context); close(fd); return errno; } if (!S_ISREG(sb2.st_mode)) { krb5_set_error_message(context, EPERM, N_("Refuses to open non files caches: FILE:%s", ""), filename); close(fd); return EPERM; } #ifndef _WIN32 if (sb1.st_dev && sb1.st_ino && (sb1.st_dev != sb2.st_dev || sb1.st_ino != sb2.st_ino)) { /* * Perhaps we raced with a rename(). To complain about * symlinks in that case would cause unnecessary concern, so * we check for that possibility and loop. This has no * TOCTOU problems because we redo the open(). We could also * not do any of this checking if O_NOFOLLOW != 0... */ close(fd); ret = lstat(filename, &sb3); if (ret || sb1.st_dev != sb2.st_dev || sb3.st_dev != sb2.st_dev || sb3.st_ino != sb2.st_ino) { krb5_set_error_message(context, EPERM, N_("Refuses to open possible symlink for caches: FILE:%s", ""), filename); return EPERM; } if (--tries == 0) { krb5_set_error_message(context, EPERM, N_("Raced too many times with renames of FILE:%s", ""), filename); return EPERM; } goto again; } #endif /* * /tmp (or wherever default ccaches go) might not be on its own * filesystem, or on a filesystem different /etc, say, and even if * it were, suppose a user hard-links another's ccache to her * default ccache, then runs a set-uid program that will user her * default ccache (even if it ignores KRB5CCNAME)... * * Default ccache locations should really be on per-user non-tmp * locations on tmpfs "run" directories. But we don't know here * that this is the case. Thus: no hard-links, no symlinks. */ if (sb2.st_nlink != 1) { krb5_set_error_message(context, EPERM, N_("Refuses to open hardlinks for caches FILE:%s", ""), filename); close(fd); return EPERM; } if (strict_checking) { #ifndef _WIN32 /* * XXX WIN32: Needs to have ACL checking code! * st_mode comes out as 100666, and st_uid is no use. */ /* * XXX Should probably add options to improve control over this * check. We might want strict checking of everything except * this. */ if (sb2.st_uid != geteuid()) { krb5_set_error_message(context, EPERM, N_("Refuses to open cache files not own by myself FILE:%s (owned by %d)", ""), filename, (int)sb2.st_uid); close(fd); return EPERM; } if ((sb2.st_mode & 077) != 0) { krb5_set_error_message(context, EPERM, N_("Refuses to open group/other readable files FILE:%s", ""), filename); close(fd); return EPERM; } #endif } if((ret = fcc_lock(context, id, fd, exclusive)) != 0) { close(fd); return ret; } *fd_ret = fd; return 0; } static krb5_error_code KRB5_CALLCONV fcc_initialize(krb5_context context, krb5_ccache id, krb5_principal primary_principal) { krb5_fcache *f = FCACHE(id); int ret = 0; int fd; if (f == NULL) return krb5_einval(context, 2); unlink (f->filename); ret = fcc_open(context, id, "initialize", &fd, O_RDWR | O_CREAT | O_EXCL, 0600); if(ret) return ret; { krb5_storage *sp; sp = krb5_storage_emem(); krb5_storage_set_eof_code(sp, KRB5_CC_END); if(context->fcache_vno != 0) f->version = context->fcache_vno; else f->version = KRB5_FCC_FVNO_4; ret |= krb5_store_int8(sp, 5); ret |= krb5_store_int8(sp, f->version); storage_set_flags(context, sp, f->version); if(f->version == KRB5_FCC_FVNO_4 && ret == 0) { /* V4 stuff */ if (context->kdc_sec_offset) { ret |= krb5_store_int16 (sp, 12); /* length */ ret |= krb5_store_int16 (sp, FCC_TAG_DELTATIME); /* Tag */ ret |= krb5_store_int16 (sp, 8); /* length of data */ ret |= krb5_store_int32 (sp, context->kdc_sec_offset); ret |= krb5_store_int32 (sp, context->kdc_usec_offset); } else { ret |= krb5_store_int16 (sp, 0); } } ret |= krb5_store_principal(sp, primary_principal); ret |= write_storage(context, sp, fd); krb5_storage_free(sp); } fcc_unlock(context, fd); if (close(fd) < 0) if (ret == 0) { char buf[128]; ret = errno; rk_strerror_r(ret, buf, sizeof(buf)); krb5_set_error_message(context, ret, N_("close %s: %s", ""), FILENAME(id), buf); } return ret; } static krb5_error_code KRB5_CALLCONV fcc_close(krb5_context context, krb5_ccache id) { if (FCACHE(id) == NULL) return krb5_einval(context, 2); free (FILENAME(id)); krb5_data_free(&id->data); return 0; } static krb5_error_code KRB5_CALLCONV fcc_destroy(krb5_context context, krb5_ccache id) { if (FCACHE(id) == NULL) return krb5_einval(context, 2); return _krb5_erase_file(context, FILENAME(id)); } static krb5_error_code KRB5_CALLCONV fcc_store_cred(krb5_context context, krb5_ccache id, krb5_creds *creds) { int ret; int fd; ret = fcc_open(context, id, "store", &fd, O_WRONLY | O_APPEND, 0); if(ret) return ret; { krb5_storage *sp; sp = krb5_storage_emem(); krb5_storage_set_eof_code(sp, KRB5_CC_END); storage_set_flags(context, sp, FCACHE(id)->version); ret = krb5_store_creds(sp, creds); if (ret == 0) ret = write_storage(context, sp, fd); krb5_storage_free(sp); } fcc_unlock(context, fd); if (close(fd) < 0) { if (ret == 0) { char buf[128]; ret = errno; rk_strerror_r(ret, buf, sizeof(buf)); krb5_set_error_message(context, ret, N_("close %s: %s", ""), FILENAME(id), buf); } } return ret; } static krb5_error_code init_fcc(krb5_context context, krb5_ccache id, const char *operation, krb5_storage **ret_sp, int *ret_fd, krb5_deltat *kdc_offset) { int fd; int8_t pvno, tag; krb5_storage *sp; krb5_error_code ret; *ret_fd = -1; *ret_sp = NULL; if (kdc_offset) *kdc_offset = 0; ret = fcc_open(context, id, operation, &fd, O_RDONLY, 0); if(ret) return ret; sp = krb5_storage_from_fd(fd); if(sp == NULL) { krb5_clear_error_message(context); ret = ENOMEM; goto out; } krb5_storage_set_eof_code(sp, KRB5_CC_END); ret = krb5_ret_int8(sp, &pvno); if (ret != 0) { if(ret == KRB5_CC_END) { ret = ENOENT; krb5_set_error_message(context, ret, N_("Empty credential cache file: %s", ""), FILENAME(id)); } else krb5_set_error_message(context, ret, N_("Error reading pvno " "in cache file: %s", ""), FILENAME(id)); goto out; } if (pvno != 5) { ret = KRB5_CCACHE_BADVNO; krb5_set_error_message(context, ret, N_("Bad version number in credential " "cache file: %s", ""), FILENAME(id)); goto out; } ret = krb5_ret_int8(sp, &tag); /* should not be host byte order */ if (ret != 0) { ret = KRB5_CC_FORMAT; krb5_set_error_message(context, ret, "Error reading tag in " "cache file: %s", FILENAME(id)); goto out; } FCACHE(id)->version = tag; storage_set_flags(context, sp, FCACHE(id)->version); switch (tag) { case KRB5_FCC_FVNO_4: { int16_t length; ret = krb5_ret_int16 (sp, &length); if(ret) { ret = KRB5_CC_FORMAT; krb5_set_error_message(context, ret, N_("Error reading tag length in " "cache file: %s", ""), FILENAME(id)); goto out; } while(length > 0) { int16_t dtag, data_len; int i; int8_t dummy; ret = krb5_ret_int16 (sp, &dtag); if(ret) { ret = KRB5_CC_FORMAT; krb5_set_error_message(context, ret, N_("Error reading dtag in " "cache file: %s", ""), FILENAME(id)); goto out; } ret = krb5_ret_int16 (sp, &data_len); if(ret) { ret = KRB5_CC_FORMAT; krb5_set_error_message(context, ret, N_("Error reading dlength " "in cache file: %s",""), FILENAME(id)); goto out; } switch (dtag) { case FCC_TAG_DELTATIME : { int32_t offset; ret = krb5_ret_int32 (sp, &offset); ret |= krb5_ret_int32 (sp, &context->kdc_usec_offset); if(ret) { ret = KRB5_CC_FORMAT; krb5_set_error_message(context, ret, N_("Error reading kdc_sec in " "cache file: %s", ""), FILENAME(id)); goto out; } context->kdc_sec_offset = offset; if (kdc_offset) *kdc_offset = offset; break; } default : for (i = 0; i < data_len; ++i) { ret = krb5_ret_int8 (sp, &dummy); if(ret) { ret = KRB5_CC_FORMAT; krb5_set_error_message(context, ret, N_("Error reading unknown " "tag in cache file: %s", ""), FILENAME(id)); goto out; } } break; } length -= 4 + data_len; } break; } case KRB5_FCC_FVNO_3: case KRB5_FCC_FVNO_2: case KRB5_FCC_FVNO_1: break; default : ret = KRB5_CCACHE_BADVNO; krb5_set_error_message(context, ret, N_("Unknown version number (%d) in " "credential cache file: %s", ""), (int)tag, FILENAME(id)); goto out; } *ret_sp = sp; *ret_fd = fd; return 0; out: if(sp != NULL) krb5_storage_free(sp); fcc_unlock(context, fd); close(fd); return ret; } static krb5_error_code KRB5_CALLCONV fcc_get_principal(krb5_context context, krb5_ccache id, krb5_principal *principal) { krb5_error_code ret; int fd; krb5_storage *sp; ret = init_fcc (context, id, "get-principal", &sp, &fd, NULL); if (ret) return ret; ret = krb5_ret_principal(sp, principal); if (ret) krb5_clear_error_message(context); krb5_storage_free(sp); fcc_unlock(context, fd); close(fd); return ret; } static krb5_error_code KRB5_CALLCONV fcc_end_get (krb5_context context, krb5_ccache id, krb5_cc_cursor *cursor); static krb5_error_code KRB5_CALLCONV fcc_get_first (krb5_context context, krb5_ccache id, krb5_cc_cursor *cursor) { krb5_error_code ret; krb5_principal principal; if (FCACHE(id) == NULL) return krb5_einval(context, 2); *cursor = malloc(sizeof(struct fcc_cursor)); if (*cursor == NULL) { krb5_set_error_message(context, ENOMEM, N_("malloc: out of memory", "")); return ENOMEM; } memset(*cursor, 0, sizeof(struct fcc_cursor)); ret = init_fcc(context, id, "get-frist", &FCC_CURSOR(*cursor)->sp, &FCC_CURSOR(*cursor)->fd, NULL); if (ret) { free(*cursor); *cursor = NULL; return ret; } ret = krb5_ret_principal (FCC_CURSOR(*cursor)->sp, &principal); if(ret) { krb5_clear_error_message(context); fcc_end_get(context, id, cursor); return ret; } krb5_free_principal (context, principal); fcc_unlock(context, FCC_CURSOR(*cursor)->fd); return 0; } static krb5_error_code KRB5_CALLCONV fcc_get_next (krb5_context context, krb5_ccache id, krb5_cc_cursor *cursor, krb5_creds *creds) { krb5_error_code ret; if (FCACHE(id) == NULL) return krb5_einval(context, 2); if (FCC_CURSOR(*cursor) == NULL) return krb5_einval(context, 3); if((ret = fcc_lock(context, id, FCC_CURSOR(*cursor)->fd, FALSE)) != 0) return ret; FCC_CURSOR(*cursor)->cred_start = lseek(FCC_CURSOR(*cursor)->fd, 0, SEEK_CUR); ret = krb5_ret_creds(FCC_CURSOR(*cursor)->sp, creds); if (ret) krb5_clear_error_message(context); FCC_CURSOR(*cursor)->cred_end = lseek(FCC_CURSOR(*cursor)->fd, 0, SEEK_CUR); fcc_unlock(context, FCC_CURSOR(*cursor)->fd); return ret; } static krb5_error_code KRB5_CALLCONV fcc_end_get (krb5_context context, krb5_ccache id, krb5_cc_cursor *cursor) { if (FCACHE(id) == NULL) return krb5_einval(context, 2); if (FCC_CURSOR(*cursor) == NULL) return krb5_einval(context, 3); krb5_storage_free(FCC_CURSOR(*cursor)->sp); close (FCC_CURSOR(*cursor)->fd); free(*cursor); *cursor = NULL; return 0; } static void KRB5_CALLCONV cred_delete(krb5_context context, krb5_ccache id, krb5_cc_cursor *cursor, krb5_creds *cred) { krb5_error_code ret; krb5_storage *sp; krb5_data orig_cred_data; unsigned char *cred_data_in_file = NULL; off_t new_cred_sz; struct stat sb1, sb2; int fd = -1; ssize_t bytes; krb5_const_realm srealm = krb5_principal_get_realm(context, cred->server); /* This is best-effort code; if we lose track of errors here it's OK */ heim_assert(FCC_CURSOR(*cursor)->cred_start < FCC_CURSOR(*cursor)->cred_end, "fcache internal error"); krb5_data_zero(&orig_cred_data); sp = krb5_storage_emem(); if (sp == NULL) return; krb5_storage_set_eof_code(sp, KRB5_CC_END); storage_set_flags(context, sp, FCACHE(id)->version); /* Get a copy of what the cred should look like in the file; see below */ ret = krb5_store_creds(sp, cred); if (ret) goto out; ret = krb5_storage_to_data(sp, &orig_cred_data); if (ret) goto out; krb5_storage_free(sp); cred_data_in_file = malloc(orig_cred_data.length); if (cred_data_in_file == NULL) goto out; /* * Mark the cred expired; krb5_cc_retrieve_cred() callers should use * KRB5_TC_MATCH_TIMES, so this should be good enough... */ cred->times.endtime = 0; /* ...except for config creds because we don't check their endtimes */ if (srealm && strcmp(srealm, "X-CACHECONF:") == 0) { ret = krb5_principal_set_realm(context, cred->server, "X-RMED-CONF:"); if (ret) goto out; } sp = krb5_storage_emem(); if (sp == NULL) goto out; krb5_storage_set_eof_code(sp, KRB5_CC_END); storage_set_flags(context, sp, FCACHE(id)->version); ret = krb5_store_creds(sp, cred); /* The new cred must be the same size as the old cred */ new_cred_sz = krb5_storage_seek(sp, 0, SEEK_END); if (new_cred_sz != orig_cred_data.length || new_cred_sz != (FCC_CURSOR(*cursor)->cred_end - FCC_CURSOR(*cursor)->cred_start)) { /* XXX This really can't happen. Assert like above? */ krb5_set_error_message(context, EINVAL, N_("Credential deletion failed on ccache " "FILE:%s: new credential size did not " "match old credential size", ""), FILENAME(id)); goto out; } ret = fcc_open(context, id, "remove_cred", &fd, O_RDWR, 0); if (ret) goto out; /* * Check that we're updating the same file where we got the * cred's offset, else we'd be corrupting a new ccache. */ if (fstat(FCC_CURSOR(*cursor)->fd, &sb1) == -1 || fstat(fd, &sb2) == -1) goto out; if (sb1.st_dev != sb2.st_dev || sb1.st_ino != sb2.st_ino) goto out; /* * Make sure what we overwrite is what we expected. * * FIXME: We *really* need the ccache v4 tag for ccache ID. This * check that we're only overwriting something that looks exactly * like what we want to is probably good enough in practice, but * it's not guaranteed to work. */ if (lseek(fd, FCC_CURSOR(*cursor)->cred_start, SEEK_SET) == (off_t)-1) goto out; bytes = read(fd, cred_data_in_file, orig_cred_data.length); if (bytes != orig_cred_data.length) goto out; if (memcmp(orig_cred_data.data, cred_data_in_file, bytes) != 0) goto out; if (lseek(fd, FCC_CURSOR(*cursor)->cred_start, SEEK_SET) == (off_t)-1) goto out; ret = write_storage(context, sp, fd); out: if (fd > -1) { fcc_unlock(context, fd); if (close(fd) < 0 && ret == 0) { krb5_set_error_message(context, errno, N_("close %s", ""), FILENAME(id)); } } krb5_data_free(&orig_cred_data); free(cred_data_in_file); krb5_storage_free(sp); return; } static krb5_error_code KRB5_CALLCONV fcc_remove_cred(krb5_context context, krb5_ccache id, krb5_flags which, krb5_creds *mcred) { krb5_error_code ret, ret2; krb5_cc_cursor cursor; krb5_creds found_cred; if (FCACHE(id) == NULL) return krb5_einval(context, 2); ret = krb5_cc_start_seq_get(context, id, &cursor); if (ret) return ret; while ((ret = krb5_cc_next_cred(context, id, &cursor, &found_cred)) == 0) { if (!krb5_compare_creds(context, which, mcred, &found_cred)) { krb5_free_cred_contents(context, &found_cred); continue; } cred_delete(context, id, &cursor, &found_cred); krb5_free_cred_contents(context, &found_cred); } ret2 = krb5_cc_end_seq_get(context, id, &cursor); if (ret == 0) return ret2; if (ret == KRB5_CC_END) return 0; return ret; } static krb5_error_code KRB5_CALLCONV fcc_set_flags(krb5_context context, krb5_ccache id, krb5_flags flags) { if (FCACHE(id) == NULL) return krb5_einval(context, 2); return 0; /* XXX */ } static int KRB5_CALLCONV fcc_get_version(krb5_context context, krb5_ccache id) { if (FCACHE(id) == NULL) return -1; return FCACHE(id)->version; } struct fcache_iter { int first; }; static krb5_error_code KRB5_CALLCONV fcc_get_cache_first(krb5_context context, krb5_cc_cursor *cursor) { struct fcache_iter *iter; iter = calloc(1, sizeof(*iter)); if (iter == NULL) { krb5_set_error_message(context, ENOMEM, N_("malloc: out of memory", "")); return ENOMEM; } iter->first = 1; *cursor = iter; return 0; } static krb5_error_code KRB5_CALLCONV fcc_get_cache_next(krb5_context context, krb5_cc_cursor cursor, krb5_ccache *id) { struct fcache_iter *iter = cursor; krb5_error_code ret; const char *fn, *cc_type; krb5_ccache cc; if (iter == NULL) return krb5_einval(context, 2); if (!iter->first) { krb5_clear_error_message(context); return KRB5_CC_END; } iter->first = 0; /* * Note: do not allow krb5_cc_default_name() to recurse via * krb5_cc_cache_match(). * Note that context->default_cc_name will be NULL even though * KRB5CCNAME is set in the environment if * krb5_cc_set_default_name() hasn't */ fn = krb5_cc_default_name(context); ret = krb5_cc_resolve(context, fn, &cc); if (ret != 0) return ret; cc_type = krb5_cc_get_type(context, cc); if (strcmp(cc_type, "FILE") != 0) { krb5_cc_close(context, cc); return KRB5_CC_END; } *id = cc; return 0; } static krb5_error_code KRB5_CALLCONV fcc_end_cache_get(krb5_context context, krb5_cc_cursor cursor) { struct fcache_iter *iter = cursor; if (iter == NULL) return krb5_einval(context, 2); free(iter); return 0; } static krb5_error_code KRB5_CALLCONV fcc_move(krb5_context context, krb5_ccache from, krb5_ccache to) { krb5_error_code ret = 0; ret = rk_rename(FILENAME(from), FILENAME(to)); if (ret && errno != EXDEV) { char buf[128]; ret = errno; rk_strerror_r(ret, buf, sizeof(buf)); krb5_set_error_message(context, ret, N_("Rename of file from %s " "to %s failed: %s", ""), FILENAME(from), FILENAME(to), buf); return ret; } else if (ret && errno == EXDEV) { /* make a copy and delete the orignal */ krb5_ssize_t sz1, sz2; int fd1, fd2; char buf[BUFSIZ]; ret = fcc_open(context, from, "move/from", &fd1, O_RDONLY, 0); if(ret) return ret; unlink(FILENAME(to)); ret = fcc_open(context, to, "move/to", &fd2, O_WRONLY | O_CREAT | O_EXCL, 0600); if(ret) goto out1; while((sz1 = read(fd1, buf, sizeof(buf))) > 0) { sz2 = write(fd2, buf, sz1); if (sz1 != sz2) { ret = EIO; krb5_set_error_message(context, ret, N_("Failed to write data from one file " "credential cache to the other", "")); goto out2; } } if (sz1 < 0) { ret = EIO; krb5_set_error_message(context, ret, N_("Failed to read data from one file " "credential cache to the other", "")); goto out2; } out2: fcc_unlock(context, fd2); close(fd2); out1: fcc_unlock(context, fd1); close(fd1); _krb5_erase_file(context, FILENAME(from)); if (ret) { _krb5_erase_file(context, FILENAME(to)); return ret; } } /* make sure ->version is uptodate */ { krb5_storage *sp; int fd; if ((ret = init_fcc (context, to, "move", &sp, &fd, NULL)) == 0) { if (sp) krb5_storage_free(sp); fcc_unlock(context, fd); close(fd); } } fcc_close(context, from); return ret; } static krb5_error_code KRB5_CALLCONV fcc_get_default_name(krb5_context context, char **str) { return _krb5_expand_default_cc_name(context, KRB5_DEFAULT_CCNAME_FILE, str); } static krb5_error_code KRB5_CALLCONV fcc_lastchange(krb5_context context, krb5_ccache id, krb5_timestamp *mtime) { krb5_error_code ret; struct stat sb; int fd; ret = fcc_open(context, id, "lastchange", &fd, O_RDONLY, 0); if(ret) return ret; ret = fstat(fd, &sb); close(fd); if (ret) { ret = errno; krb5_set_error_message(context, ret, N_("Failed to stat cache file", "")); return ret; } *mtime = sb.st_mtime; return 0; } static krb5_error_code KRB5_CALLCONV fcc_set_kdc_offset(krb5_context context, krb5_ccache id, krb5_deltat kdc_offset) { return 0; } static krb5_error_code KRB5_CALLCONV fcc_get_kdc_offset(krb5_context context, krb5_ccache id, krb5_deltat *kdc_offset) { krb5_error_code ret; krb5_storage *sp = NULL; int fd; ret = init_fcc(context, id, "get-kdc-offset", &sp, &fd, kdc_offset); if (sp) krb5_storage_free(sp); fcc_unlock(context, fd); close(fd); return ret; } /** * Variable containing the FILE based credential cache implemention. * * @ingroup krb5_ccache */ KRB5_LIB_VARIABLE const krb5_cc_ops krb5_fcc_ops = { KRB5_CC_OPS_VERSION, "FILE", fcc_get_name, fcc_resolve, fcc_gen_new, fcc_initialize, fcc_destroy, fcc_close, fcc_store_cred, NULL, /* fcc_retrieve */ fcc_get_principal, fcc_get_first, fcc_get_next, fcc_end_get, fcc_remove_cred, fcc_set_flags, fcc_get_version, fcc_get_cache_first, fcc_get_cache_next, fcc_end_cache_get, fcc_move, fcc_get_default_name, NULL, fcc_lastchange, fcc_set_kdc_offset, fcc_get_kdc_offset }; heimdal-7.5.0/lib/krb5/error_string.c0000644000175000017500000002045013062303006015540 0ustar niknik/* * Copyright (c) 2001, 2003, 2005 - 2006 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "krb5_locl.h" #undef __attribute__ #define __attribute__(x) /** * Clears the error message from the Kerberos 5 context. * * @param context The Kerberos 5 context to clear * * @ingroup krb5_error */ KRB5_LIB_FUNCTION void KRB5_LIB_CALL krb5_clear_error_message(krb5_context context) { HEIMDAL_MUTEX_lock(&context->mutex); if (context->error_string) free(context->error_string); context->error_code = 0; context->error_string = NULL; HEIMDAL_MUTEX_unlock(&context->mutex); } /** * Set the context full error string for a specific error code. * The error that is stored should be internationalized. * * The if context is NULL, no error string is stored. * * @param context Kerberos 5 context * @param ret The error code * @param fmt Error string for the error code * @param ... printf(3) style parameters. * * @ingroup krb5_error */ KRB5_LIB_FUNCTION void KRB5_LIB_CALL krb5_set_error_message(krb5_context context, krb5_error_code ret, const char *fmt, ...) __attribute__ ((__format__ (__printf__, 3, 4))) { va_list ap; va_start(ap, fmt); krb5_vset_error_message (context, ret, fmt, ap); va_end(ap); } /** * Set the context full error string for a specific error code. * * The if context is NULL, no error string is stored. * * @param context Kerberos 5 context * @param ret The error code * @param fmt Error string for the error code * @param args printf(3) style parameters. * * @ingroup krb5_error */ KRB5_LIB_FUNCTION void KRB5_LIB_CALL krb5_vset_error_message (krb5_context context, krb5_error_code ret, const char *fmt, va_list args) __attribute__ ((__format__ (__printf__, 3, 0))) { int r; if (context == NULL) return; HEIMDAL_MUTEX_lock(&context->mutex); if (context->error_string) { free(context->error_string); context->error_string = NULL; } context->error_code = ret; r = vasprintf(&context->error_string, fmt, args); if (r < 0) context->error_string = NULL; HEIMDAL_MUTEX_unlock(&context->mutex); if (context->error_string) _krb5_debug(context, 100, "error message: %s: %d", context->error_string, ret); } /** * Prepend the context full error string for a specific error code. * The error that is stored should be internationalized. * * The if context is NULL, no error string is stored. * * @param context Kerberos 5 context * @param ret The error code * @param fmt Error string for the error code * @param ... printf(3) style parameters. * * @ingroup krb5_error */ KRB5_LIB_FUNCTION void KRB5_LIB_CALL krb5_prepend_error_message(krb5_context context, krb5_error_code ret, const char *fmt, ...) __attribute__ ((__format__ (__printf__, 3, 4))) { va_list ap; va_start(ap, fmt); krb5_vprepend_error_message(context, ret, fmt, ap); va_end(ap); } /** * Prepend the contexts's full error string for a specific error code. * * The if context is NULL, no error string is stored. * * @param context Kerberos 5 context * @param ret The error code * @param fmt Error string for the error code * @param args printf(3) style parameters. * * @ingroup krb5_error */ KRB5_LIB_FUNCTION void KRB5_LIB_CALL krb5_vprepend_error_message(krb5_context context, krb5_error_code ret, const char *fmt, va_list args) __attribute__ ((__format__ (__printf__, 3, 0))) { char *str = NULL, *str2 = NULL; if (context == NULL) return; HEIMDAL_MUTEX_lock(&context->mutex); if (context->error_code != ret) { HEIMDAL_MUTEX_unlock(&context->mutex); return; } if (vasprintf(&str, fmt, args) < 0 || str == NULL) { HEIMDAL_MUTEX_unlock(&context->mutex); return; } if (context->error_string) { int e; e = asprintf(&str2, "%s: %s", str, context->error_string); free(context->error_string); if (e < 0 || str2 == NULL) context->error_string = NULL; else context->error_string = str2; free(str); } else context->error_string = str; HEIMDAL_MUTEX_unlock(&context->mutex); } /** * Return the error message for `code' in context. On memory * allocation error the function returns NULL. * * @param context Kerberos 5 context * @param code Error code related to the error * * @return an error string, needs to be freed with * krb5_free_error_message(). The functions return NULL on error. * * @ingroup krb5_error */ KRB5_LIB_FUNCTION const char * KRB5_LIB_CALL krb5_get_error_message(krb5_context context, krb5_error_code code) { char *str = NULL; const char *cstr = NULL; char buf[128]; int free_context = 0; if (code == 0) return strdup("Success"); /* * The MIT version of this function ignores the krb5_context * and several widely deployed applications call krb5_get_error_message() * with a NULL context in order to translate an error code as a * replacement for error_message(). Another reason a NULL context * might be provided is if the krb5_init_context() call itself * failed. */ if (context) { HEIMDAL_MUTEX_lock(&context->mutex); if (context->error_string && (code == context->error_code || context->error_code == 0)) { str = strdup(context->error_string); } HEIMDAL_MUTEX_unlock(&context->mutex); if (str) return str; } else { if (krb5_init_context(&context) == 0) free_context = 1; } if (context) cstr = com_right_r(context->et_list, code, buf, sizeof(buf)); if (free_context) krb5_free_context(context); if (cstr) return strdup(cstr); cstr = error_message(code); if (cstr) return strdup(cstr); if (asprintf(&str, "", (int)code) == -1 || str == NULL) return NULL; return str; } /** * Free the error message returned by krb5_get_error_message(). * * @param context Kerberos context * @param msg error message to free, returned byg * krb5_get_error_message(). * * @ingroup krb5_error */ KRB5_LIB_FUNCTION void KRB5_LIB_CALL krb5_free_error_message(krb5_context context, const char *msg) { free(rk_UNCONST(msg)); } /** * Return the error string for the error code. The caller must not * free the string. * * This function is deprecated since its not threadsafe. * * @param context Kerberos 5 context. * @param code Kerberos error code. * * @return the error message matching code * * @ingroup krb5 */ KRB5_LIB_FUNCTION const char* KRB5_LIB_CALL krb5_get_err_text(krb5_context context, krb5_error_code code) KRB5_DEPRECATED_FUNCTION("Use krb5_get_error_message instead") { const char *p = NULL; if(context != NULL) p = com_right(context->et_list, code); if(p == NULL) p = strerror(code); if (p == NULL) p = "Unknown error"; return p; } heimdal-7.5.0/lib/krb5/context.c0000644000175000017500000012007113212137553014516 0ustar niknik/* * Copyright (c) 1997 - 2010 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Portions Copyright (c) 2009 Apple Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "krb5_locl.h" #include #include #define INIT_FIELD(C, T, E, D, F) \ (C)->E = krb5_config_get_ ## T ## _default ((C), NULL, (D), \ "libdefaults", F, NULL) #define INIT_FLAG(C, O, V, D, F) \ do { \ if (krb5_config_get_bool_default((C), NULL, (D),"libdefaults", F, NULL)) { \ (C)->O |= V; \ } \ } while(0) static krb5_error_code copy_enctypes(krb5_context context, const krb5_enctype *in, krb5_enctype **out); /* * Set the list of etypes `ret_etypes' from the configuration variable * `name' */ static krb5_error_code set_etypes (krb5_context context, const char *name, krb5_enctype **ret_enctypes) { char **etypes_str; krb5_enctype *etypes = NULL; etypes_str = krb5_config_get_strings(context, NULL, "libdefaults", name, NULL); if(etypes_str){ int i, j, k; for(i = 0; etypes_str[i]; i++); etypes = malloc((i+1) * sizeof(*etypes)); if (etypes == NULL) { krb5_config_free_strings (etypes_str); return krb5_enomem(context); } for(j = 0, k = 0; j < i; j++) { krb5_enctype e; if(krb5_string_to_enctype(context, etypes_str[j], &e) != 0) continue; if (krb5_enctype_valid(context, e) != 0) continue; etypes[k++] = e; } etypes[k] = ETYPE_NULL; krb5_config_free_strings(etypes_str); } *ret_enctypes = etypes; return 0; } /* * read variables from the configuration file and set in `context' */ static krb5_error_code init_context_from_config_file(krb5_context context) { krb5_error_code ret; const char * tmp; char **s; krb5_enctype *tmptypes; INIT_FIELD(context, time, max_skew, 5 * 60, "clockskew"); INIT_FIELD(context, time, kdc_timeout, 30, "kdc_timeout"); INIT_FIELD(context, time, host_timeout, 3, "host_timeout"); INIT_FIELD(context, int, max_retries, 3, "max_retries"); INIT_FIELD(context, string, http_proxy, NULL, "http_proxy"); ret = krb5_config_get_bool_default(context, NULL, FALSE, "libdefaults", "allow_weak_crypto", NULL); if (ret) { krb5_enctype_enable(context, ETYPE_DES_CBC_CRC); krb5_enctype_enable(context, ETYPE_DES_CBC_MD4); krb5_enctype_enable(context, ETYPE_DES_CBC_MD5); krb5_enctype_enable(context, ETYPE_DES_CBC_NONE); krb5_enctype_enable(context, ETYPE_DES_CFB64_NONE); krb5_enctype_enable(context, ETYPE_DES_PCBC_NONE); } ret = set_etypes (context, "default_etypes", &tmptypes); if(ret) return ret; free(context->etypes); context->etypes = tmptypes; /* The etypes member may change during the lifetime * of the context. To be able to reset it to * config value, we keep another copy. */ free(context->cfg_etypes); context->cfg_etypes = NULL; if (tmptypes) { ret = copy_enctypes(context, tmptypes, &context->cfg_etypes); if (ret) return ret; } ret = set_etypes (context, "default_etypes_des", &tmptypes); if(ret) return ret; free(context->etypes_des); context->etypes_des = tmptypes; ret = set_etypes (context, "default_as_etypes", &tmptypes); if(ret) return ret; free(context->as_etypes); context->as_etypes = tmptypes; ret = set_etypes (context, "default_tgs_etypes", &tmptypes); if(ret) return ret; free(context->tgs_etypes); context->tgs_etypes = tmptypes; ret = set_etypes (context, "permitted_enctypes", &tmptypes); if(ret) return ret; free(context->permitted_enctypes); context->permitted_enctypes = tmptypes; INIT_FIELD(context, string, default_keytab, KEYTAB_DEFAULT, "default_keytab_name"); INIT_FIELD(context, string, default_keytab_modify, NULL, "default_keytab_modify_name"); INIT_FIELD(context, string, time_fmt, "%Y-%m-%dT%H:%M:%S", "time_format"); INIT_FIELD(context, string, date_fmt, "%Y-%m-%d", "date_format"); INIT_FIELD(context, bool, log_utc, FALSE, "log_utc"); /* init dns-proxy slime */ tmp = krb5_config_get_string(context, NULL, "libdefaults", "dns_proxy", NULL); if(tmp) roken_gethostby_setup(context->http_proxy, tmp); krb5_free_host_realm (context, context->default_realms); context->default_realms = NULL; { krb5_addresses addresses; char **adr, **a; krb5_set_extra_addresses(context, NULL); adr = krb5_config_get_strings(context, NULL, "libdefaults", "extra_addresses", NULL); memset(&addresses, 0, sizeof(addresses)); for(a = adr; a && *a; a++) { ret = krb5_parse_address(context, *a, &addresses); if (ret == 0) { krb5_add_extra_addresses(context, &addresses); krb5_free_addresses(context, &addresses); } } krb5_config_free_strings(adr); krb5_set_ignore_addresses(context, NULL); adr = krb5_config_get_strings(context, NULL, "libdefaults", "ignore_addresses", NULL); memset(&addresses, 0, sizeof(addresses)); for(a = adr; a && *a; a++) { ret = krb5_parse_address(context, *a, &addresses); if (ret == 0) { krb5_add_ignore_addresses(context, &addresses); krb5_free_addresses(context, &addresses); } } krb5_config_free_strings(adr); } INIT_FIELD(context, bool, scan_interfaces, TRUE, "scan_interfaces"); INIT_FIELD(context, int, fcache_vno, 0, "fcache_version"); /* prefer dns_lookup_kdc over srv_lookup. */ INIT_FIELD(context, bool, srv_lookup, TRUE, "srv_lookup"); INIT_FIELD(context, bool, srv_lookup, context->srv_lookup, "dns_lookup_kdc"); INIT_FIELD(context, int, large_msg_size, 1400, "large_message_size"); INIT_FIELD(context, int, max_msg_size, 1000 * 1024, "maximum_message_size"); INIT_FLAG(context, flags, KRB5_CTX_F_DNS_CANONICALIZE_HOSTNAME, TRUE, "dns_canonicalize_hostname"); INIT_FLAG(context, flags, KRB5_CTX_F_CHECK_PAC, TRUE, "check_pac"); if (context->default_cc_name) free(context->default_cc_name); context->default_cc_name = NULL; context->default_cc_name_set = 0; s = krb5_config_get_strings(context, NULL, "logging", "krb5", NULL); if(s) { char **p; if (context->debug_dest) krb5_closelog(context, context->debug_dest); krb5_initlog(context, "libkrb5", &context->debug_dest); for(p = s; *p; p++) krb5_addlog_dest(context, context->debug_dest, *p); krb5_config_free_strings(s); } tmp = krb5_config_get_string(context, NULL, "libdefaults", "check-rd-req-server", NULL); if (tmp == NULL && !issuid()) tmp = getenv("KRB5_CHECK_RD_REQ_SERVER"); if(tmp) { if (strcasecmp(tmp, "ignore") == 0) context->flags |= KRB5_CTX_F_RD_REQ_IGNORE; } ret = krb5_config_get_bool_default(context, NULL, TRUE, "libdefaults", "fcache_strict_checking", NULL); if (ret) context->flags |= KRB5_CTX_F_FCACHE_STRICT_CHECKING; return 0; } static krb5_error_code cc_ops_register(krb5_context context) { context->cc_ops = NULL; context->num_cc_ops = 0; #ifndef KCM_IS_API_CACHE krb5_cc_register(context, &krb5_acc_ops, TRUE); #endif krb5_cc_register(context, &krb5_fcc_ops, TRUE); krb5_cc_register(context, &krb5_dcc_ops, TRUE); krb5_cc_register(context, &krb5_mcc_ops, TRUE); #ifdef HAVE_SCC krb5_cc_register(context, &krb5_scc_ops, TRUE); #endif #ifdef HAVE_KCM #ifdef KCM_IS_API_CACHE krb5_cc_register(context, &krb5_akcm_ops, TRUE); #endif krb5_cc_register(context, &krb5_kcm_ops, TRUE); #endif _krb5_load_ccache_plugins(context); return 0; } static krb5_error_code cc_ops_copy(krb5_context context, const krb5_context src_context) { const krb5_cc_ops **cc_ops; context->cc_ops = NULL; context->num_cc_ops = 0; if (src_context->num_cc_ops == 0) return 0; cc_ops = malloc(sizeof(cc_ops[0]) * src_context->num_cc_ops); if (cc_ops == NULL) { krb5_set_error_message(context, KRB5_CC_NOMEM, N_("malloc: out of memory", "")); return KRB5_CC_NOMEM; } memcpy(rk_UNCONST(cc_ops), src_context->cc_ops, sizeof(cc_ops[0]) * src_context->num_cc_ops); context->cc_ops = cc_ops; context->num_cc_ops = src_context->num_cc_ops; return 0; } static krb5_error_code kt_ops_register(krb5_context context) { context->num_kt_types = 0; context->kt_types = NULL; krb5_kt_register (context, &krb5_fkt_ops); krb5_kt_register (context, &krb5_wrfkt_ops); krb5_kt_register (context, &krb5_javakt_ops); krb5_kt_register (context, &krb5_mkt_ops); #ifndef HEIMDAL_SMALLER krb5_kt_register (context, &krb5_akf_ops); #endif krb5_kt_register (context, &krb5_any_ops); return 0; } static krb5_error_code kt_ops_copy(krb5_context context, const krb5_context src_context) { context->num_kt_types = 0; context->kt_types = NULL; if (src_context->num_kt_types == 0) return 0; context->kt_types = malloc(sizeof(context->kt_types[0]) * src_context->num_kt_types); if (context->kt_types == NULL) return krb5_enomem(context); context->num_kt_types = src_context->num_kt_types; memcpy(context->kt_types, src_context->kt_types, sizeof(context->kt_types[0]) * src_context->num_kt_types); return 0; } static const char *sysplugin_dirs[] = { #ifdef _WIN32 "$ORIGIN", #else "$ORIGIN/../lib/plugin/krb5", #endif #ifdef __APPLE__ LIBDIR "/plugin/krb5", #ifdef HEIM_PLUGINS_SEARCH_SYSTEM "/Library/KerberosPlugins/KerberosFrameworkPlugins", "/System/Library/KerberosPlugins/KerberosFrameworkPlugins", #endif #endif NULL }; static void init_context_once(void *ctx) { krb5_context context = ctx; char **dirs; #ifdef _WIN32 dirs = rk_UNCONST(sysplugin_dirs); #else dirs = krb5_config_get_strings(context, NULL, "libdefaults", "plugin_dir", NULL); if (dirs == NULL) dirs = rk_UNCONST(sysplugin_dirs); #endif _krb5_load_plugins(context, "krb5", (const char **)dirs); if (dirs != rk_UNCONST(sysplugin_dirs)) krb5_config_free_strings(dirs); bindtextdomain(HEIMDAL_TEXTDOMAIN, HEIMDAL_LOCALEDIR); } /** * Initializes the context structure and reads the configuration file * /etc/krb5.conf. The structure should be freed by calling * krb5_free_context() when it is no longer being used. * * @param context pointer to returned context * * @return Returns 0 to indicate success. Otherwise an errno code is * returned. Failure means either that something bad happened during * initialization (typically ENOMEM) or that Kerberos should not be * used ENXIO. If the function returns HEIM_ERR_RANDOM_OFFLINE, the * random source is not available and later Kerberos calls might fail. * * @ingroup krb5 */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_init_context(krb5_context *context) { static heim_base_once_t init_context = HEIM_BASE_ONCE_INIT; krb5_context p; krb5_error_code ret; char **files; uint8_t rnd; *context = NULL; /** * krb5_init_context() will get one random byte to make sure our * random is alive. Assumption is that once the non blocking * source allows us to pull bytes, its all seeded and allows us to * pull more bytes. * * Most Kerberos users calls krb5_init_context(), so this is * useful point where we can do the checking. */ ret = krb5_generate_random(&rnd, sizeof(rnd)); if (ret) return ret; p = calloc(1, sizeof(*p)); if(!p) return ENOMEM; HEIMDAL_MUTEX_init(&p->mutex); p->flags |= KRB5_CTX_F_HOMEDIR_ACCESS; ret = krb5_get_default_config_files(&files); if(ret) goto out; ret = krb5_set_config_files(p, files); krb5_free_config_files(files); if(ret) goto out; /* done enough to load plugins */ heim_base_once_f(&init_context, p, init_context_once); /* init error tables */ krb5_init_ets(p); cc_ops_register(p); kt_ops_register(p); #ifdef PKINIT ret = hx509_context_init(&p->hx509ctx); if (ret) goto out; #endif if (rk_SOCK_INIT()) p->flags |= KRB5_CTX_F_SOCKETS_INITIALIZED; out: if(ret) { krb5_free_context(p); p = NULL; } *context = p; return ret; } #ifndef HEIMDAL_SMALLER KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_get_permitted_enctypes(krb5_context context, krb5_enctype **etypes) { return krb5_get_default_in_tkt_etypes(context, KRB5_PDU_NONE, etypes); } /* * */ static krb5_error_code copy_etypes (krb5_context context, krb5_enctype *enctypes, krb5_enctype **ret_enctypes) { unsigned int i; for (i = 0; enctypes[i]; i++) ; i++; *ret_enctypes = malloc(sizeof(enctypes[0]) * i); if (*ret_enctypes == NULL) return krb5_enomem(context); memcpy(*ret_enctypes, enctypes, sizeof(enctypes[0]) * i); return 0; } /** * Make a copy for the Kerberos 5 context, the new krb5_context shoud * be freed with krb5_free_context(). * * @param context the Kerberos context to copy * @param out the copy of the Kerberos, set to NULL error. * * @return Returns 0 to indicate success. Otherwise an kerberos et * error code is returned, see krb5_get_error_message(). * * @ingroup krb5 */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_copy_context(krb5_context context, krb5_context *out) { krb5_error_code ret; krb5_context p; *out = NULL; p = calloc(1, sizeof(*p)); if (p == NULL) return krb5_enomem(context); HEIMDAL_MUTEX_init(&p->mutex); if (context->default_cc_name) p->default_cc_name = strdup(context->default_cc_name); if (context->default_cc_name_env) p->default_cc_name_env = strdup(context->default_cc_name_env); if (context->etypes) { ret = copy_etypes(context, context->etypes, &p->etypes); if (ret) goto out; } if (context->cfg_etypes) { ret = copy_etypes(context, context->cfg_etypes, &p->cfg_etypes); if (ret) goto out; } if (context->etypes_des) { ret = copy_etypes(context, context->etypes_des, &p->etypes_des); if (ret) goto out; } if (context->default_realms) { ret = krb5_copy_host_realm(context, context->default_realms, &p->default_realms); if (ret) goto out; } ret = _krb5_config_copy(context, context->cf, &p->cf); if (ret) goto out; /* XXX should copy */ krb5_init_ets(p); cc_ops_copy(p, context); kt_ops_copy(p, context); #if 0 /* XXX */ if(context->warn_dest != NULL) ; if(context->debug_dest != NULL) ; #endif ret = krb5_set_extra_addresses(p, context->extra_addresses); if (ret) goto out; ret = krb5_set_extra_addresses(p, context->ignore_addresses); if (ret) goto out; ret = _krb5_copy_send_to_kdc_func(p, context); if (ret) goto out; *out = p; return 0; out: krb5_free_context(p); return ret; } #endif /** * Frees the krb5_context allocated by krb5_init_context(). * * @param context context to be freed. * * @ingroup krb5 */ KRB5_LIB_FUNCTION void KRB5_LIB_CALL krb5_free_context(krb5_context context) { _krb5_free_name_canon_rules(context, context->name_canon_rules); if (context->default_cc_name) free(context->default_cc_name); if (context->default_cc_name_env) free(context->default_cc_name_env); free(context->etypes); free(context->cfg_etypes); free(context->etypes_des); krb5_free_host_realm (context, context->default_realms); krb5_config_file_free (context, context->cf); free_error_table (context->et_list); free(rk_UNCONST(context->cc_ops)); free(context->kt_types); krb5_clear_error_message(context); if(context->warn_dest != NULL) krb5_closelog(context, context->warn_dest); if(context->debug_dest != NULL) krb5_closelog(context, context->debug_dest); krb5_set_extra_addresses(context, NULL); krb5_set_ignore_addresses(context, NULL); krb5_set_send_to_kdc_func(context, NULL, NULL); #ifdef PKINIT if (context->hx509ctx) hx509_context_free(&context->hx509ctx); #endif HEIMDAL_MUTEX_destroy(&context->mutex); if (context->flags & KRB5_CTX_F_SOCKETS_INITIALIZED) { rk_SOCK_EXIT(); } memset(context, 0, sizeof(*context)); free(context); } /** * Reinit the context from a new set of filenames. * * @param context context to add configuration too. * @param filenames array of filenames, end of list is indicated with a NULL filename. * * @return Returns 0 to indicate success. Otherwise an kerberos et * error code is returned, see krb5_get_error_message(). * * @ingroup krb5 */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_set_config_files(krb5_context context, char **filenames) { krb5_error_code ret; krb5_config_binding *tmp = NULL; while(filenames != NULL && *filenames != NULL && **filenames != '\0') { ret = krb5_config_parse_file_multi(context, *filenames, &tmp); if (ret != 0 && ret != ENOENT && ret != EACCES && ret != EPERM && ret != KRB5_CONFIG_BADFORMAT) { krb5_config_file_free(context, tmp); return ret; } filenames++; } #if 0 /* with this enabled and if there are no config files, Kerberos is considererd disabled */ if(tmp == NULL) return ENXIO; #endif #ifdef _WIN32 _krb5_load_config_from_registry(context, &tmp); #endif krb5_config_file_free(context, context->cf); context->cf = tmp; ret = init_context_from_config_file(context); return ret; } static krb5_error_code add_file(char ***pfilenames, int *len, char *file) { char **pp = *pfilenames; int i; for(i = 0; i < *len; i++) { if(strcmp(pp[i], file) == 0) { free(file); return 0; } } pp = realloc(*pfilenames, (*len + 2) * sizeof(*pp)); if (pp == NULL) { free(file); return ENOMEM; } pp[*len] = file; pp[*len + 1] = NULL; *pfilenames = pp; *len += 1; return 0; } /* * `pq' isn't free, it's up the the caller */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_prepend_config_files(const char *filelist, char **pq, char ***ret_pp) { krb5_error_code ret; const char *p, *q; char **pp; int len; char *fn; pp = NULL; len = 0; p = filelist; while(1) { ssize_t l; q = p; l = strsep_copy(&q, PATH_SEP, NULL, 0); if(l == -1) break; fn = malloc(l + 1); if(fn == NULL) { krb5_free_config_files(pp); return ENOMEM; } (void)strsep_copy(&p, PATH_SEP, fn, l + 1); ret = add_file(&pp, &len, fn); if (ret) { krb5_free_config_files(pp); return ret; } } if (pq != NULL) { int i; for (i = 0; pq[i] != NULL; i++) { fn = strdup(pq[i]); if (fn == NULL) { krb5_free_config_files(pp); return ENOMEM; } ret = add_file(&pp, &len, fn); if (ret) { krb5_free_config_files(pp); return ret; } } } *ret_pp = pp; return 0; } /** * Prepend the filename to the global configuration list. * * @param filelist a filename to add to the default list of filename * @param pfilenames return array of filenames, should be freed with krb5_free_config_files(). * * @return Returns 0 to indicate success. Otherwise an kerberos et * error code is returned, see krb5_get_error_message(). * * @ingroup krb5 */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_prepend_config_files_default(const char *filelist, char ***pfilenames) { krb5_error_code ret; char **defpp, **pp = NULL; ret = krb5_get_default_config_files(&defpp); if (ret) return ret; ret = krb5_prepend_config_files(filelist, defpp, &pp); krb5_free_config_files(defpp); if (ret) { return ret; } *pfilenames = pp; return 0; } #ifdef _WIN32 /** * Checks the registry for configuration file location * * Kerberos for Windows and other legacy Kerberos applications expect * to find the configuration file location in the * SOFTWARE\MIT\Kerberos registry key under the value "config". */ KRB5_LIB_FUNCTION char * KRB5_LIB_CALL _krb5_get_default_config_config_files_from_registry() { static const char * KeyName = "Software\\MIT\\Kerberos"; char *config_file = NULL; LONG rcode; HKEY key; rcode = RegOpenKeyEx(HKEY_CURRENT_USER, KeyName, 0, KEY_READ, &key); if (rcode == ERROR_SUCCESS) { config_file = _krb5_parse_reg_value_as_multi_string(NULL, key, "config", REG_NONE, 0, PATH_SEP); RegCloseKey(key); } if (config_file) return config_file; rcode = RegOpenKeyEx(HKEY_LOCAL_MACHINE, KeyName, 0, KEY_READ, &key); if (rcode == ERROR_SUCCESS) { config_file = _krb5_parse_reg_value_as_multi_string(NULL, key, "config", REG_NONE, 0, PATH_SEP); RegCloseKey(key); } return config_file; } #endif /** * Get the global configuration list. * * @param pfilenames return array of filenames, should be freed with krb5_free_config_files(). * * @return Returns 0 to indicate success. Otherwise an kerberos et * error code is returned, see krb5_get_error_message(). * * @ingroup krb5 */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_get_default_config_files(char ***pfilenames) { const char *files = NULL; if (pfilenames == NULL) return EINVAL; if(!issuid()) files = getenv("KRB5_CONFIG"); #ifdef _WIN32 if (files == NULL) { char * reg_files; reg_files = _krb5_get_default_config_config_files_from_registry(); if (reg_files != NULL) { krb5_error_code code; code = krb5_prepend_config_files(reg_files, NULL, pfilenames); free(reg_files); return code; } } #endif if (files == NULL) files = krb5_config_file; return krb5_prepend_config_files(files, NULL, pfilenames); } /** * Free a list of configuration files. * * @param filenames list, terminated with a NULL pointer, to be * freed. NULL is an valid argument. * * @return Returns 0 to indicate success. Otherwise an kerberos et * error code is returned, see krb5_get_error_message(). * * @ingroup krb5 */ KRB5_LIB_FUNCTION void KRB5_LIB_CALL krb5_free_config_files(char **filenames) { char **p; for(p = filenames; p && *p != NULL; p++) free(*p); free(filenames); } /** * Returns the list of Kerberos encryption types sorted in order of * most preferred to least preferred encryption type. Note that some * encryption types might be disabled, so you need to check with * krb5_enctype_valid() before using the encryption type. * * @return list of enctypes, terminated with ETYPE_NULL. Its a static * array completed into the Kerberos library so the content doesn't * need to be freed. * * @ingroup krb5 */ KRB5_LIB_FUNCTION const krb5_enctype * KRB5_LIB_CALL krb5_kerberos_enctypes(krb5_context context) { static const krb5_enctype p[] = { ETYPE_AES256_CTS_HMAC_SHA1_96, ETYPE_AES128_CTS_HMAC_SHA1_96, ETYPE_AES256_CTS_HMAC_SHA384_192, ETYPE_AES128_CTS_HMAC_SHA256_128, ETYPE_DES3_CBC_SHA1, ETYPE_ARCFOUR_HMAC_MD5, ETYPE_NULL }; static const krb5_enctype weak[] = { ETYPE_AES256_CTS_HMAC_SHA1_96, ETYPE_AES128_CTS_HMAC_SHA1_96, ETYPE_AES256_CTS_HMAC_SHA384_192, ETYPE_AES128_CTS_HMAC_SHA256_128, ETYPE_DES3_CBC_SHA1, ETYPE_DES3_CBC_MD5, ETYPE_ARCFOUR_HMAC_MD5, ETYPE_DES_CBC_MD5, ETYPE_DES_CBC_MD4, ETYPE_DES_CBC_CRC, ETYPE_NULL }; /* * if the list of enctypes enabled by "allow_weak_crypto" * are valid, then return the former default enctype list * that contained the weak entries. */ if (krb5_enctype_valid(context, ETYPE_DES_CBC_CRC) == 0 && krb5_enctype_valid(context, ETYPE_DES_CBC_MD4) == 0 && krb5_enctype_valid(context, ETYPE_DES_CBC_MD5) == 0 && krb5_enctype_valid(context, ETYPE_DES_CBC_NONE) == 0 && krb5_enctype_valid(context, ETYPE_DES_CFB64_NONE) == 0 && krb5_enctype_valid(context, ETYPE_DES_PCBC_NONE) == 0) return weak; return p; } /* * */ static krb5_error_code copy_enctypes(krb5_context context, const krb5_enctype *in, krb5_enctype **out) { krb5_enctype *p = NULL; size_t m, n; for (n = 0; in[n]; n++) ; n++; ALLOC(p, n); if(p == NULL) return krb5_enomem(context); for (n = 0, m = 0; in[n]; n++) { if (krb5_enctype_valid(context, in[n]) != 0) continue; p[m++] = in[n]; } p[m] = KRB5_ENCTYPE_NULL; if (m == 0) { free(p); krb5_set_error_message (context, KRB5_PROG_ETYPE_NOSUPP, N_("no valid enctype set", "")); return KRB5_PROG_ETYPE_NOSUPP; } *out = p; return 0; } /* * set `etype' to a malloced list of the default enctypes */ static krb5_error_code default_etypes(krb5_context context, krb5_enctype **etype) { const krb5_enctype *p = krb5_kerberos_enctypes(context); return copy_enctypes(context, p, etype); } /** * Set the default encryption types that will be use in communcation * with the KDC, clients and servers. * * @param context Kerberos 5 context. * @param etypes Encryption types, array terminated with ETYPE_NULL (0). * A value of NULL resets the encryption types to the defaults set in the * configuration file. * * @return Returns 0 to indicate success. Otherwise an kerberos et * error code is returned, see krb5_get_error_message(). * * @ingroup krb5 */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_set_default_in_tkt_etypes(krb5_context context, const krb5_enctype *etypes) { krb5_error_code ret; krb5_enctype *p = NULL; if(!etypes) { etypes = context->cfg_etypes; } if(etypes) { ret = copy_enctypes(context, etypes, &p); if (ret) return ret; } if(context->etypes) free(context->etypes); context->etypes = p; return 0; } /** * Get the default encryption types that will be use in communcation * with the KDC, clients and servers. * * @param context Kerberos 5 context. * @param pdu_type request type (AS, TGS or none) * @param etypes Encryption types, array terminated with * ETYPE_NULL(0), caller should free array with krb5_xfree(): * * @return Returns 0 to indicate success. Otherwise an kerberos et * error code is returned, see krb5_get_error_message(). * * @ingroup krb5 */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_get_default_in_tkt_etypes(krb5_context context, krb5_pdu pdu_type, krb5_enctype **etypes) { krb5_enctype *enctypes = NULL; krb5_error_code ret; krb5_enctype *p; heim_assert(pdu_type == KRB5_PDU_AS_REQUEST || pdu_type == KRB5_PDU_TGS_REQUEST || pdu_type == KRB5_PDU_NONE, "unexpected pdu type"); if (pdu_type == KRB5_PDU_AS_REQUEST && context->as_etypes != NULL) enctypes = context->as_etypes; else if (pdu_type == KRB5_PDU_TGS_REQUEST && context->tgs_etypes != NULL) enctypes = context->tgs_etypes; else if (context->etypes != NULL) enctypes = context->etypes; if (enctypes != NULL) { ret = copy_enctypes(context, enctypes, &p); if (ret) return ret; } else { ret = default_etypes(context, &p); if (ret) return ret; } *etypes = p; return 0; } /** * Init the built-in ets in the Kerberos library. * * @param context kerberos context to add the ets too * * @ingroup krb5 */ KRB5_LIB_FUNCTION void KRB5_LIB_CALL krb5_init_ets(krb5_context context) { if(context->et_list == NULL){ krb5_add_et_list(context, initialize_krb5_error_table_r); krb5_add_et_list(context, initialize_asn1_error_table_r); krb5_add_et_list(context, initialize_heim_error_table_r); krb5_add_et_list(context, initialize_k524_error_table_r); #ifdef COM_ERR_BINDDOMAIN_krb5 bindtextdomain(COM_ERR_BINDDOMAIN_krb5, HEIMDAL_LOCALEDIR); bindtextdomain(COM_ERR_BINDDOMAIN_asn1, HEIMDAL_LOCALEDIR); bindtextdomain(COM_ERR_BINDDOMAIN_heim, HEIMDAL_LOCALEDIR); bindtextdomain(COM_ERR_BINDDOMAIN_k524, HEIMDAL_LOCALEDIR); #endif #ifdef PKINIT krb5_add_et_list(context, initialize_hx_error_table_r); #ifdef COM_ERR_BINDDOMAIN_hx bindtextdomain(COM_ERR_BINDDOMAIN_hx, HEIMDAL_LOCALEDIR); #endif #endif } } /** * Make the kerberos library default to the admin KDC. * * @param context Kerberos 5 context. * @param flag boolean flag to select if the use the admin KDC or not. * * @ingroup krb5 */ KRB5_LIB_FUNCTION void KRB5_LIB_CALL krb5_set_use_admin_kdc (krb5_context context, krb5_boolean flag) { context->use_admin_kdc = flag; } /** * Make the kerberos library default to the admin KDC. * * @param context Kerberos 5 context. * * @return boolean flag to telling the context will use admin KDC as the default KDC. * * @ingroup krb5 */ KRB5_LIB_FUNCTION krb5_boolean KRB5_LIB_CALL krb5_get_use_admin_kdc (krb5_context context) { return context->use_admin_kdc; } /** * Add extra address to the address list that the library will add to * the client's address list when communicating with the KDC. * * @param context Kerberos 5 context. * @param addresses addreses to add * * @return Returns 0 to indicate success. Otherwise an kerberos et * error code is returned, see krb5_get_error_message(). * * @ingroup krb5 */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_add_extra_addresses(krb5_context context, krb5_addresses *addresses) { if(context->extra_addresses) return krb5_append_addresses(context, context->extra_addresses, addresses); else return krb5_set_extra_addresses(context, addresses); } /** * Set extra address to the address list that the library will add to * the client's address list when communicating with the KDC. * * @param context Kerberos 5 context. * @param addresses addreses to set * * @return Returns 0 to indicate success. Otherwise an kerberos et * error code is returned, see krb5_get_error_message(). * * @ingroup krb5 */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_set_extra_addresses(krb5_context context, const krb5_addresses *addresses) { if(context->extra_addresses) krb5_free_addresses(context, context->extra_addresses); if(addresses == NULL) { if(context->extra_addresses != NULL) { free(context->extra_addresses); context->extra_addresses = NULL; } return 0; } if(context->extra_addresses == NULL) { context->extra_addresses = malloc(sizeof(*context->extra_addresses)); if (context->extra_addresses == NULL) return krb5_enomem(context); } return krb5_copy_addresses(context, addresses, context->extra_addresses); } /** * Get extra address to the address list that the library will add to * the client's address list when communicating with the KDC. * * @param context Kerberos 5 context. * @param addresses addreses to set * * @return Returns 0 to indicate success. Otherwise an kerberos et * error code is returned, see krb5_get_error_message(). * * @ingroup krb5 */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_get_extra_addresses(krb5_context context, krb5_addresses *addresses) { if(context->extra_addresses == NULL) { memset(addresses, 0, sizeof(*addresses)); return 0; } return krb5_copy_addresses(context,context->extra_addresses, addresses); } /** * Add extra addresses to ignore when fetching addresses from the * underlaying operating system. * * @param context Kerberos 5 context. * @param addresses addreses to ignore * * @return Returns 0 to indicate success. Otherwise an kerberos et * error code is returned, see krb5_get_error_message(). * * @ingroup krb5 */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_add_ignore_addresses(krb5_context context, krb5_addresses *addresses) { if(context->ignore_addresses) return krb5_append_addresses(context, context->ignore_addresses, addresses); else return krb5_set_ignore_addresses(context, addresses); } /** * Set extra addresses to ignore when fetching addresses from the * underlaying operating system. * * @param context Kerberos 5 context. * @param addresses addreses to ignore * * @return Returns 0 to indicate success. Otherwise an kerberos et * error code is returned, see krb5_get_error_message(). * * @ingroup krb5 */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_set_ignore_addresses(krb5_context context, const krb5_addresses *addresses) { if(context->ignore_addresses) krb5_free_addresses(context, context->ignore_addresses); if(addresses == NULL) { if(context->ignore_addresses != NULL) { free(context->ignore_addresses); context->ignore_addresses = NULL; } return 0; } if(context->ignore_addresses == NULL) { context->ignore_addresses = malloc(sizeof(*context->ignore_addresses)); if (context->ignore_addresses == NULL) return krb5_enomem(context); } return krb5_copy_addresses(context, addresses, context->ignore_addresses); } /** * Get extra addresses to ignore when fetching addresses from the * underlaying operating system. * * @param context Kerberos 5 context. * @param addresses list addreses ignored * * @return Returns 0 to indicate success. Otherwise an kerberos et * error code is returned, see krb5_get_error_message(). * * @ingroup krb5 */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_get_ignore_addresses(krb5_context context, krb5_addresses *addresses) { if(context->ignore_addresses == NULL) { memset(addresses, 0, sizeof(*addresses)); return 0; } return krb5_copy_addresses(context, context->ignore_addresses, addresses); } /** * Set version of fcache that the library should use. * * @param context Kerberos 5 context. * @param version version number. * * @return Returns 0 to indicate success. Otherwise an kerberos et * error code is returned, see krb5_get_error_message(). * * @ingroup krb5 */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_set_fcache_version(krb5_context context, int version) { context->fcache_vno = version; return 0; } /** * Get version of fcache that the library should use. * * @param context Kerberos 5 context. * @param version version number. * * @return Returns 0 to indicate success. Otherwise an kerberos et * error code is returned, see krb5_get_error_message(). * * @ingroup krb5 */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_get_fcache_version(krb5_context context, int *version) { *version = context->fcache_vno; return 0; } /** * Runtime check if the Kerberos library was complied with thread support. * * @return TRUE if the library was compiled with thread support, FALSE if not. * * @ingroup krb5 */ KRB5_LIB_FUNCTION krb5_boolean KRB5_LIB_CALL krb5_is_thread_safe(void) { #ifdef ENABLE_PTHREAD_SUPPORT return TRUE; #else return FALSE; #endif } /** * Set if the library should use DNS to canonicalize hostnames. * * @param context Kerberos 5 context. * @param flag if its dns canonicalizion is used or not. * * @ingroup krb5 */ KRB5_LIB_FUNCTION void KRB5_LIB_CALL krb5_set_dns_canonicalize_hostname (krb5_context context, krb5_boolean flag) { if (flag) context->flags |= KRB5_CTX_F_DNS_CANONICALIZE_HOSTNAME; else context->flags &= ~KRB5_CTX_F_DNS_CANONICALIZE_HOSTNAME; } /** * Get if the library uses DNS to canonicalize hostnames. * * @param context Kerberos 5 context. * * @return return non zero if the library uses DNS to canonicalize hostnames. * * @ingroup krb5 */ KRB5_LIB_FUNCTION krb5_boolean KRB5_LIB_CALL krb5_get_dns_canonicalize_hostname (krb5_context context) { return (context->flags & KRB5_CTX_F_DNS_CANONICALIZE_HOSTNAME) ? 1 : 0; } /** * Get current offset in time to the KDC. * * @param context Kerberos 5 context. * @param sec seconds part of offset. * @param usec micro seconds part of offset. * * @return returns zero * * @ingroup krb5 */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_get_kdc_sec_offset (krb5_context context, int32_t *sec, int32_t *usec) { if (sec) *sec = context->kdc_sec_offset; if (usec) *usec = context->kdc_usec_offset; return 0; } /** * Set current offset in time to the KDC. * * @param context Kerberos 5 context. * @param sec seconds part of offset. * @param usec micro seconds part of offset. * * @return returns zero * * @ingroup krb5 */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_set_kdc_sec_offset (krb5_context context, int32_t sec, int32_t usec) { context->kdc_sec_offset = sec; if (usec >= 0) context->kdc_usec_offset = usec; return 0; } /** * Get max time skew allowed. * * @param context Kerberos 5 context. * * @return timeskew in seconds. * * @ingroup krb5 */ KRB5_LIB_FUNCTION time_t KRB5_LIB_CALL krb5_get_max_time_skew (krb5_context context) { return context->max_skew; } /** * Set max time skew allowed. * * @param context Kerberos 5 context. * @param t timeskew in seconds. * * @ingroup krb5 */ KRB5_LIB_FUNCTION void KRB5_LIB_CALL krb5_set_max_time_skew (krb5_context context, time_t t) { context->max_skew = t; } /* * Init encryption types in len, val with etypes. * * @param context Kerberos 5 context. * @param pdu_type type of pdu * @param len output length of val. * @param val output array of enctypes. * @param etypes etypes to set val and len to, if NULL, use default enctypes. * @return Returns 0 to indicate success. Otherwise an kerberos et * error code is returned, see krb5_get_error_message(). * * @ingroup krb5 */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL _krb5_init_etype(krb5_context context, krb5_pdu pdu_type, unsigned *len, krb5_enctype **val, const krb5_enctype *etypes) { krb5_error_code ret; if (etypes == NULL) ret = krb5_get_default_in_tkt_etypes(context, pdu_type, val); else ret = copy_enctypes(context, etypes, val); if (ret) return ret; if (len) { *len = 0; while ((*val)[*len] != KRB5_ENCTYPE_NULL) (*len)++; } return 0; } /* * Allow homedir accces */ static HEIMDAL_MUTEX homedir_mutex = HEIMDAL_MUTEX_INITIALIZER; static krb5_boolean allow_homedir = TRUE; KRB5_LIB_FUNCTION krb5_boolean KRB5_LIB_CALL _krb5_homedir_access(krb5_context context) { krb5_boolean allow; if (context && (context->flags & KRB5_CTX_F_HOMEDIR_ACCESS) == 0) return FALSE; HEIMDAL_MUTEX_lock(&homedir_mutex); allow = allow_homedir; HEIMDAL_MUTEX_unlock(&homedir_mutex); return allow; } /** * Enable and disable home directory access on either the global state * or the krb5_context state. By calling krb5_set_home_dir_access() * with context set to NULL, the global state is configured otherwise * the state for the krb5_context is modified. * * For home directory access to be allowed, both the global state and * the krb5_context state have to be allowed. * * @param context a Kerberos 5 context or NULL * @param allow allow if TRUE home directory * @return the old value * * @ingroup krb5 */ KRB5_LIB_FUNCTION krb5_boolean KRB5_LIB_CALL krb5_set_home_dir_access(krb5_context context, krb5_boolean allow) { krb5_boolean old; if (context) { old = (context->flags & KRB5_CTX_F_HOMEDIR_ACCESS) ? TRUE : FALSE; if (allow) context->flags |= KRB5_CTX_F_HOMEDIR_ACCESS; else context->flags &= ~KRB5_CTX_F_HOMEDIR_ACCESS; } else { HEIMDAL_MUTEX_lock(&homedir_mutex); old = allow_homedir; allow_homedir = allow; HEIMDAL_MUTEX_unlock(&homedir_mutex); } return old; } heimdal-7.5.0/lib/krb5/cache.c0000644000175000017500000013430413212137553014101 0ustar niknik/* * Copyright (c) 1997 - 2008 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Portions Copyright (c) 2009 Apple Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "krb5_locl.h" /** * @page krb5_ccache_intro The credential cache functions * @section section_krb5_ccache Kerberos credential caches * * krb5_ccache structure holds a Kerberos credential cache. * * Heimdal support the follow types of credential caches: * * - SCC * Store the credential in a database * - FILE * Store the credential in memory * - MEMORY * Store the credential in memory * - API * A credential cache server based solution for Mac OS X * - KCM * A credential cache server based solution for all platforms * * @subsection Example * * This is a minimalistic version of klist: @code #include int main (int argc, char **argv) { krb5_context context; krb5_cc_cursor cursor; krb5_error_code ret; krb5_ccache id; krb5_creds creds; if (krb5_init_context (&context) != 0) errx(1, "krb5_context"); ret = krb5_cc_default (context, &id); if (ret) krb5_err(context, 1, ret, "krb5_cc_default"); ret = krb5_cc_start_seq_get(context, id, &cursor); if (ret) krb5_err(context, 1, ret, "krb5_cc_start_seq_get"); while((ret = krb5_cc_next_cred(context, id, &cursor, &creds)) == 0){ char *principal; krb5_unparse_name(context, creds.server, &principal); printf("principal: %s\\n", principal); free(principal); krb5_free_cred_contents (context, &creds); } ret = krb5_cc_end_seq_get(context, id, &cursor); if (ret) krb5_err(context, 1, ret, "krb5_cc_end_seq_get"); krb5_cc_close(context, id); krb5_free_context(context); return 0; } * @endcode */ /** * Add a new ccache type with operations `ops', overwriting any * existing one if `override'. * * @param context a Keberos context * @param ops type of plugin symbol * @param override flag to select if the registration is to overide * an existing ops with the same name. * * @return Return an error code or 0, see krb5_get_error_message(). * * @ingroup krb5_ccache */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_cc_register(krb5_context context, const krb5_cc_ops *ops, krb5_boolean override) { int i; for(i = 0; i < context->num_cc_ops && context->cc_ops[i]->prefix; i++) { if(strcmp(context->cc_ops[i]->prefix, ops->prefix) == 0) { if(!override) { krb5_set_error_message(context, KRB5_CC_TYPE_EXISTS, N_("cache type %s already exists", "type"), ops->prefix); return KRB5_CC_TYPE_EXISTS; } break; } } if(i == context->num_cc_ops) { const krb5_cc_ops **o = realloc(rk_UNCONST(context->cc_ops), (context->num_cc_ops + 1) * sizeof(context->cc_ops[0])); if(o == NULL) { krb5_set_error_message(context, KRB5_CC_NOMEM, N_("malloc: out of memory", "")); return KRB5_CC_NOMEM; } context->cc_ops = o; context->cc_ops[context->num_cc_ops] = NULL; context->num_cc_ops++; } context->cc_ops[i] = ops; return 0; } /* * Allocate the memory for a `id' and the that function table to * `ops'. Returns 0 or and error code. */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL _krb5_cc_allocate(krb5_context context, const krb5_cc_ops *ops, krb5_ccache *id) { krb5_ccache p; p = calloc(1, sizeof(*p)); if (p == NULL) { krb5_set_error_message(context, KRB5_CC_NOMEM, N_("malloc: out of memory", "")); return KRB5_CC_NOMEM; } p->ops = ops; *id = p; return 0; } /* * Allocate memory for a new ccache in `id' with operations `ops' * and name `residual'. Return 0 or an error code. */ static krb5_error_code allocate_ccache (krb5_context context, const krb5_cc_ops *ops, const char *residual, krb5_ccache *id) { krb5_error_code ret; #ifdef KRB5_USE_PATH_TOKENS char * exp_residual = NULL; int filepath; filepath = (strcmp("FILE", ops->prefix) == 0 || strcmp("DIR", ops->prefix) == 0 || strcmp("SCC", ops->prefix) == 0); ret = _krb5_expand_path_tokens(context, residual, filepath, &exp_residual); if (ret) return ret; residual = exp_residual; #endif ret = _krb5_cc_allocate(context, ops, id); if (ret) { #ifdef KRB5_USE_PATH_TOKENS if (exp_residual) free(exp_residual); #endif return ret; } ret = (*id)->ops->resolve(context, id, residual); if(ret) { free(*id); *id = NULL; } #ifdef KRB5_USE_PATH_TOKENS if (exp_residual) free(exp_residual); #endif return ret; } static int is_possible_path_name(const char * name) { const char * colon; if ((colon = strchr(name, ':')) == NULL) return TRUE; #ifdef _WIN32 /* :\path\to\cache ? */ if (colon == name + 1 && strchr(colon + 1, ':') == NULL) return TRUE; #endif return FALSE; } /** * Find and allocate a ccache in `id' from the specification in `residual'. * If the ccache name doesn't contain any colon, interpret it as a file name. * * @param context a Keberos context. * @param name string name of a credential cache. * @param id return pointer to a found credential cache. * * @return Return 0 or an error code. In case of an error, id is set * to NULL, see krb5_get_error_message(). * * @ingroup krb5_ccache */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_cc_resolve(krb5_context context, const char *name, krb5_ccache *id) { int i; *id = NULL; for(i = 0; i < context->num_cc_ops && context->cc_ops[i]->prefix; i++) { size_t prefix_len = strlen(context->cc_ops[i]->prefix); if(strncmp(context->cc_ops[i]->prefix, name, prefix_len) == 0 && name[prefix_len] == ':') { return allocate_ccache (context, context->cc_ops[i], name + prefix_len + 1, id); } } if (is_possible_path_name(name)) return allocate_ccache (context, &krb5_fcc_ops, name, id); else { krb5_set_error_message(context, KRB5_CC_UNKNOWN_TYPE, N_("unknown ccache type %s", "name"), name); return KRB5_CC_UNKNOWN_TYPE; } } /** * Generates a new unique ccache of `type` in `id'. If `type' is NULL, * the library chooses the default credential cache type. The supplied * `hint' (that can be NULL) is a string that the credential cache * type can use to base the name of the credential on, this is to make * it easier for the user to differentiate the credentials. * * @return Return an error code or 0, see krb5_get_error_message(). * * @ingroup krb5_ccache */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_cc_new_unique(krb5_context context, const char *type, const char *hint, krb5_ccache *id) { const krb5_cc_ops *ops; krb5_error_code ret; ops = krb5_cc_get_prefix_ops(context, type); if (ops == NULL) { krb5_set_error_message(context, KRB5_CC_UNKNOWN_TYPE, "Credential cache type %s is unknown", type); return KRB5_CC_UNKNOWN_TYPE; } ret = _krb5_cc_allocate(context, ops, id); if (ret) return ret; ret = (*id)->ops->gen_new(context, id); if (ret) { free(*id); *id = NULL; } return ret; } /** * Return the name of the ccache `id' * * @ingroup krb5_ccache */ KRB5_LIB_FUNCTION const char* KRB5_LIB_CALL krb5_cc_get_name(krb5_context context, krb5_ccache id) { return id->ops->get_name(context, id); } /** * Return the type of the ccache `id'. * * @ingroup krb5_ccache */ KRB5_LIB_FUNCTION const char* KRB5_LIB_CALL krb5_cc_get_type(krb5_context context, krb5_ccache id) { return id->ops->prefix; } /** * Return the complete resolvable name the cache * @param context a Keberos context * @param id return pointer to a found credential cache * @param str the returned name of a credential cache, free with krb5_xfree() * * @return Returns 0 or an error (and then *str is set to NULL). * * @ingroup krb5_ccache */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_cc_get_full_name(krb5_context context, krb5_ccache id, char **str) { const char *type, *name; *str = NULL; type = krb5_cc_get_type(context, id); if (type == NULL) { krb5_set_error_message(context, KRB5_CC_UNKNOWN_TYPE, "cache have no name of type"); return KRB5_CC_UNKNOWN_TYPE; } name = krb5_cc_get_name(context, id); if (name == NULL) { krb5_set_error_message(context, KRB5_CC_BADNAME, "cache of type %s have no name", type); return KRB5_CC_BADNAME; } if (asprintf(str, "%s:%s", type, name) == -1) { *str = NULL; return krb5_enomem(context); } return 0; } /** * Return krb5_cc_ops of a the ccache `id'. * * @ingroup krb5_ccache */ KRB5_LIB_FUNCTION const krb5_cc_ops * KRB5_LIB_CALL krb5_cc_get_ops(krb5_context context, krb5_ccache id) { return id->ops; } /* * Expand variables in `str' into `res' */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL _krb5_expand_default_cc_name(krb5_context context, const char *str, char **res) { int filepath; filepath = (strncmp("FILE:", str, 5) == 0 || strncmp("DIR:", str, 4) == 0 || strncmp("SCC:", str, 4) == 0); return _krb5_expand_path_tokens(context, str, filepath, res); } /* * Return non-zero if envirnoment that will determine default krb5cc * name has changed. */ static int environment_changed(krb5_context context) { const char *e; /* if the cc name was set, don't change it */ if (context->default_cc_name_set) return 0; /* XXX performance: always ask KCM/API if default name has changed */ if (context->default_cc_name && (strncmp(context->default_cc_name, "KCM:", 4) == 0 || strncmp(context->default_cc_name, "API:", 4) == 0)) return 1; if(issuid()) return 0; e = getenv("KRB5CCNAME"); if (e == NULL) { if (context->default_cc_name_env) { free(context->default_cc_name_env); context->default_cc_name_env = NULL; return 1; } } else { if (context->default_cc_name_env == NULL) return 1; if (strcmp(e, context->default_cc_name_env) != 0) return 1; } return 0; } /** * Switch the default default credential cache for a specific * credcache type (and name for some implementations). * * @return Return an error code or 0, see krb5_get_error_message(). * * @ingroup krb5_ccache */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_cc_switch(krb5_context context, krb5_ccache id) { #ifdef _WIN32 _krb5_set_default_cc_name_to_registry(context, id); #endif if (id->ops->set_default == NULL) return 0; return (*id->ops->set_default)(context, id); } /** * Return true if the default credential cache support switch * * @ingroup krb5_ccache */ KRB5_LIB_FUNCTION krb5_boolean KRB5_LIB_CALL krb5_cc_support_switch(krb5_context context, const char *type) { const krb5_cc_ops *ops; ops = krb5_cc_get_prefix_ops(context, type); if (ops && ops->set_default) return 1; return FALSE; } /** * Set the default cc name for `context' to `name'. * * @ingroup krb5_ccache */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_cc_set_default_name(krb5_context context, const char *name) { krb5_error_code ret = 0; char *p = NULL, *exp_p = NULL; int filepath; const krb5_cc_ops *ops = KRB5_DEFAULT_CCTYPE; if (name == NULL) { const char *e = NULL; if (!issuid()) { e = getenv("KRB5CCNAME"); if (e) { p = strdup(e); if (context->default_cc_name_env) free(context->default_cc_name_env); context->default_cc_name_env = strdup(e); } } #ifdef _WIN32 if (p == NULL) { p = _krb5_get_default_cc_name_from_registry(context); } #endif if (p == NULL) { e = krb5_config_get_string(context, NULL, "libdefaults", "default_cc_name", NULL); if (e) { ret = _krb5_expand_default_cc_name(context, e, &p); if (ret) return ret; } } if (p == NULL) { e = krb5_config_get_string(context, NULL, "libdefaults", "default_cc_type", NULL); if (e) { ops = krb5_cc_get_prefix_ops(context, e); if (ops == NULL) { krb5_set_error_message(context, KRB5_CC_UNKNOWN_TYPE, "Credential cache type %s " "is unknown", e); return KRB5_CC_UNKNOWN_TYPE; } } } #ifdef _WIN32 if (p == NULL) { /* * If the MSLSA ccache type has a principal name, * use it as the default. */ krb5_ccache id; ret = krb5_cc_resolve(context, "MSLSA:", &id); if (ret == 0) { krb5_principal princ; ret = krb5_cc_get_principal(context, id, &princ); if (ret == 0) { krb5_free_principal(context, princ); p = strdup("MSLSA:"); } krb5_cc_close(context, id); } } if (p == NULL) { /* * If the API:krb5cc ccache can be resolved, * use it as the default. */ krb5_ccache api_id; ret = krb5_cc_resolve(context, "API:krb5cc", &api_id); if (ret == 0) krb5_cc_close(context, api_id); } /* Otherwise, fallback to the FILE ccache */ #endif if (p == NULL) { ret = (*ops->get_default_name)(context, &p); if (ret) return ret; } context->default_cc_name_set = 0; } else { p = strdup(name); if (p == NULL) return krb5_enomem(context); context->default_cc_name_set = 1; } filepath = (strncmp("FILE:", p, 5) == 0 || strncmp("DIR:", p, 4) == 0 || strncmp("SCC:", p, 4) == 0); ret = _krb5_expand_path_tokens(context, p, filepath, &exp_p); free(p); p = exp_p; if (ret) return ret; if (context->default_cc_name) free(context->default_cc_name); context->default_cc_name = p; return 0; } /** * Return a pointer to a context static string containing the default * ccache name. * * @return String to the default credential cache name. * * @ingroup krb5_ccache */ KRB5_LIB_FUNCTION const char* KRB5_LIB_CALL krb5_cc_default_name(krb5_context context) { if (context->default_cc_name == NULL || environment_changed(context)) krb5_cc_set_default_name(context, NULL); return context->default_cc_name; } /** * Open the default ccache in `id'. * * @return Return an error code or 0, see krb5_get_error_message(). * * @ingroup krb5_ccache */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_cc_default(krb5_context context, krb5_ccache *id) { const char *p = krb5_cc_default_name(context); if (p == NULL) return krb5_enomem(context); return krb5_cc_resolve(context, p, id); } /** * Create a new ccache in `id' for `primary_principal'. * * @return Return an error code or 0, see krb5_get_error_message(). * * @ingroup krb5_ccache */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_cc_initialize(krb5_context context, krb5_ccache id, krb5_principal primary_principal) { krb5_error_code ret; ret = (*id->ops->init)(context, id, primary_principal); if (ret == 0) id->initialized = 1; return ret; } /** * Remove the ccache `id'. * * @return Return an error code or 0, see krb5_get_error_message(). * * @ingroup krb5_ccache */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_cc_destroy(krb5_context context, krb5_ccache id) { krb5_error_code ret; ret = (*id->ops->destroy)(context, id); krb5_cc_close (context, id); return ret; } /** * Stop using the ccache `id' and free the related resources. * * @return Return an error code or 0, see krb5_get_error_message(). * * @ingroup krb5_ccache */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_cc_close(krb5_context context, krb5_ccache id) { krb5_error_code ret; ret = (*id->ops->close)(context, id); free(id); return ret; } /** * Store `creds' in the ccache `id'. * * @return Return an error code or 0, see krb5_get_error_message(). * * @ingroup krb5_ccache */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_cc_store_cred(krb5_context context, krb5_ccache id, krb5_creds *creds) { krb5_error_code ret; krb5_data realm; ret = (*id->ops->store)(context, id, creds); /* Look for and mark the first root TGT's realm as the start realm */ if (ret == 0 && id->initialized && krb5_principal_is_root_krbtgt(context, creds->server)) { id->initialized = 0; realm.length = strlen(creds->server->realm); realm.data = creds->server->realm; (void) krb5_cc_set_config(context, id, NULL, "start_realm", &realm); } else if (ret == 0 && id->initialized && krb5_is_config_principal(context, creds->server) && strcmp(creds->server->name.name_string.val[1], "start_realm") == 0) { /* * But if the caller is storing a start_realm ccconfig, then * stop looking for root TGTs to mark as the start_realm. * * By honoring any start_realm cc config stored, we interop * both, with ccache implementations that don't preserve * insertion order, and Kerberos implementations that store this * cc config before the TGT. */ id->initialized = 0; } return ret; } /** * Retrieve the credential identified by `mcreds' (and `whichfields') * from `id' in `creds'. 'creds' must be free by the caller using * krb5_free_cred_contents. * * @param context A Kerberos 5 context * @param id a Kerberos 5 credential cache * @param whichfields what fields to use for matching credentials, same * flags as whichfields in krb5_compare_creds() * @param mcreds template credential to use for comparing * @param creds returned credential, free with krb5_free_cred_contents() * * @return Return an error code or 0, see krb5_get_error_message(). * * @ingroup krb5_ccache */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_cc_retrieve_cred(krb5_context context, krb5_ccache id, krb5_flags whichfields, const krb5_creds *mcreds, krb5_creds *creds) { krb5_error_code ret; krb5_cc_cursor cursor; if (id->ops->retrieve != NULL) { return (*id->ops->retrieve)(context, id, whichfields, mcreds, creds); } ret = krb5_cc_start_seq_get(context, id, &cursor); if (ret) return ret; while((ret = krb5_cc_next_cred(context, id, &cursor, creds)) == 0){ if(krb5_compare_creds(context, whichfields, mcreds, creds)){ ret = 0; break; } krb5_free_cred_contents (context, creds); } krb5_cc_end_seq_get(context, id, &cursor); return ret; } /** * Return the principal of `id' in `principal'. * * @return Return an error code or 0, see krb5_get_error_message(). * * @ingroup krb5_ccache */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_cc_get_principal(krb5_context context, krb5_ccache id, krb5_principal *principal) { return (*id->ops->get_princ)(context, id, principal); } /** * Start iterating over `id', `cursor' is initialized to the * beginning. Caller must free the cursor with krb5_cc_end_seq_get(). * * @return Return an error code or 0, see krb5_get_error_message(). * * @ingroup krb5_ccache */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_cc_start_seq_get (krb5_context context, const krb5_ccache id, krb5_cc_cursor *cursor) { return (*id->ops->get_first)(context, id, cursor); } /** * Retrieve the next cred pointed to by (`id', `cursor') in `creds' * and advance `cursor'. * * @return Return an error code or 0, see krb5_get_error_message(). * * @ingroup krb5_ccache */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_cc_next_cred (krb5_context context, const krb5_ccache id, krb5_cc_cursor *cursor, krb5_creds *creds) { return (*id->ops->get_next)(context, id, cursor, creds); } /** * Destroy the cursor `cursor'. * * @ingroup krb5_ccache */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_cc_end_seq_get (krb5_context context, const krb5_ccache id, krb5_cc_cursor *cursor) { return (*id->ops->end_get)(context, id, cursor); } /** * Remove the credential identified by `cred', `which' from `id'. * * @ingroup krb5_ccache */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_cc_remove_cred(krb5_context context, krb5_ccache id, krb5_flags which, krb5_creds *cred) { if(id->ops->remove_cred == NULL) { krb5_set_error_message(context, EACCES, "ccache %s does not support remove_cred", id->ops->prefix); return EACCES; /* XXX */ } return (*id->ops->remove_cred)(context, id, which, cred); } /** * Set the flags of `id' to `flags'. * * @ingroup krb5_ccache */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_cc_set_flags(krb5_context context, krb5_ccache id, krb5_flags flags) { return (*id->ops->set_flags)(context, id, flags); } /** * Get the flags of `id', store them in `flags'. * * @ingroup krb5_ccache */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_cc_get_flags(krb5_context context, krb5_ccache id, krb5_flags *flags) { *flags = 0; return 0; } /** * Copy the contents of `from' to `to' if the given match function * return true. * * @param context A Kerberos 5 context. * @param from the cache to copy data from. * @param to the cache to copy data to. * @param match a match function that should return TRUE if cred argument should be copied, if NULL, all credentials are copied. * @param matchctx context passed to match function. * @param matched set to true if there was a credential that matched, may be NULL. * * @return Return an error code or 0, see krb5_get_error_message(). * * @ingroup krb5_ccache */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_cc_copy_match_f(krb5_context context, const krb5_ccache from, krb5_ccache to, krb5_boolean (*match)(krb5_context, void *, const krb5_creds *), void *matchctx, unsigned int *matched) { krb5_error_code ret; krb5_cc_cursor cursor; krb5_creds cred; krb5_principal princ; if (matched) *matched = 0; ret = krb5_cc_get_principal(context, from, &princ); if (ret) return ret; ret = krb5_cc_initialize(context, to, princ); if (ret) { krb5_free_principal(context, princ); return ret; } ret = krb5_cc_start_seq_get(context, from, &cursor); if (ret) { krb5_free_principal(context, princ); return ret; } while ((ret = krb5_cc_next_cred(context, from, &cursor, &cred)) == 0) { if (match == NULL || (*match)(context, matchctx, &cred)) { if (matched) (*matched)++; ret = krb5_cc_store_cred(context, to, &cred); if (ret) break; } krb5_free_cred_contents(context, &cred); } krb5_cc_end_seq_get(context, from, &cursor); krb5_free_principal(context, princ); if (ret == KRB5_CC_END) ret = 0; return ret; } /** * Just like krb5_cc_copy_match_f(), but copy everything. * * @ingroup @krb5_ccache */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_cc_copy_cache(krb5_context context, const krb5_ccache from, krb5_ccache to) { return krb5_cc_copy_match_f(context, from, to, NULL, NULL, NULL); } /** * Return the version of `id'. * * @ingroup krb5_ccache */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_cc_get_version(krb5_context context, const krb5_ccache id) { if(id->ops->get_version) return (*id->ops->get_version)(context, id); else return 0; } /** * Clear `mcreds' so it can be used with krb5_cc_retrieve_cred * * @ingroup krb5_ccache */ KRB5_LIB_FUNCTION void KRB5_LIB_CALL krb5_cc_clear_mcred(krb5_creds *mcred) { memset(mcred, 0, sizeof(*mcred)); } /** * Get the cc ops that is registered in `context' to handle the * prefix. prefix can be a complete credential cache name or a * prefix, the function will only use part up to the first colon (:) * if there is one. If prefix the argument is NULL, the default ccache * implemtation is returned. * * @return Returns NULL if ops not found. * * @ingroup krb5_ccache */ KRB5_LIB_FUNCTION const krb5_cc_ops * KRB5_LIB_CALL krb5_cc_get_prefix_ops(krb5_context context, const char *prefix) { char *p, *p1; int i; if (prefix == NULL) return KRB5_DEFAULT_CCTYPE; /* Is absolute path? Or UNC path? */ if (ISPATHSEP(prefix[0])) return &krb5_fcc_ops; #ifdef _WIN32 /* Is drive letter? */ if (isalpha(prefix[0]) && prefix[1] == ':') return &krb5_fcc_ops; #endif p = strdup(prefix); if (p == NULL) { krb5_enomem(context); return NULL; } p1 = strchr(p, ':'); if (p1) *p1 = '\0'; for(i = 0; i < context->num_cc_ops && context->cc_ops[i]->prefix; i++) { if(strcmp(context->cc_ops[i]->prefix, p) == 0) { free(p); return context->cc_ops[i]; } } free(p); return NULL; } struct krb5_cc_cache_cursor_data { const krb5_cc_ops *ops; krb5_cc_cursor cursor; }; /** * Start iterating over all caches of specified type. See also * krb5_cccol_cursor_new(). * @param context A Kerberos 5 context * @param type optional type to iterate over, if NULL, the default cache is used. * @param cursor cursor should be freed with krb5_cc_cache_end_seq_get(). * * @return Return an error code or 0, see krb5_get_error_message(). * * @ingroup krb5_ccache */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_cc_cache_get_first (krb5_context context, const char *type, krb5_cc_cache_cursor *cursor) { const krb5_cc_ops *ops; krb5_error_code ret; if (type == NULL) type = krb5_cc_default_name(context); ops = krb5_cc_get_prefix_ops(context, type); if (ops == NULL) { krb5_set_error_message(context, KRB5_CC_UNKNOWN_TYPE, "Unknown type \"%s\" when iterating " "trying to iterate the credential caches", type); return KRB5_CC_UNKNOWN_TYPE; } if (ops->get_cache_first == NULL) { krb5_set_error_message(context, KRB5_CC_NOSUPP, N_("Credential cache type %s doesn't support " "iterations over caches", "type"), ops->prefix); return KRB5_CC_NOSUPP; } *cursor = calloc(1, sizeof(**cursor)); if (*cursor == NULL) return krb5_enomem(context); (*cursor)->ops = ops; ret = ops->get_cache_first(context, &(*cursor)->cursor); if (ret) { free(*cursor); *cursor = NULL; } return ret; } /** * Retrieve the next cache pointed to by (`cursor') in `id' * and advance `cursor'. * * @param context A Kerberos 5 context * @param cursor the iterator cursor, returned by krb5_cc_cache_get_first() * @param id next ccache * * @return Return 0 or an error code. Returns KRB5_CC_END when the end * of caches is reached, see krb5_get_error_message(). * * @ingroup krb5_ccache */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_cc_cache_next (krb5_context context, krb5_cc_cache_cursor cursor, krb5_ccache *id) { return cursor->ops->get_cache_next(context, cursor->cursor, id); } /** * Destroy the cursor `cursor'. * * @return Return an error code or 0, see krb5_get_error_message(). * * @ingroup krb5_ccache */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_cc_cache_end_seq_get (krb5_context context, krb5_cc_cache_cursor cursor) { krb5_error_code ret; ret = cursor->ops->end_cache_get(context, cursor->cursor); cursor->ops = NULL; free(cursor); return ret; } /** * Search for a matching credential cache that have the * `principal' as the default principal. On success, `id' needs to be * freed with krb5_cc_close() or krb5_cc_destroy(). * * @param context A Kerberos 5 context * @param client The principal to search for * @param id the returned credential cache * * @return On failure, error code is returned and `id' is set to NULL. * * @ingroup krb5_ccache */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_cc_cache_match (krb5_context context, krb5_principal client, krb5_ccache *id) { krb5_cccol_cursor cursor; krb5_error_code ret; krb5_ccache cache = NULL; krb5_ccache expired_match = NULL; *id = NULL; ret = krb5_cccol_cursor_new (context, &cursor); if (ret) return ret; while (krb5_cccol_cursor_next(context, cursor, &cache) == 0 && cache != NULL) { krb5_principal principal; krb5_boolean match; time_t lifetime; ret = krb5_cc_get_principal(context, cache, &principal); if (ret) goto next; if (client->name.name_string.len == 0) match = (strcmp(client->realm, principal->realm) == 0); else match = krb5_principal_compare(context, principal, client); krb5_free_principal(context, principal); if (!match) goto next; if (expired_match == NULL && (krb5_cc_get_lifetime(context, cache, &lifetime) != 0 || lifetime == 0)) { expired_match = cache; cache = NULL; goto next; } break; next: if (cache) krb5_cc_close(context, cache); cache = NULL; } krb5_cccol_cursor_free(context, &cursor); if (cache == NULL && expired_match) { cache = expired_match; expired_match = NULL; } else if (expired_match) { krb5_cc_close(context, expired_match); } else if (cache == NULL) { char *str; krb5_unparse_name(context, client, &str); krb5_set_error_message(context, KRB5_CC_NOTFOUND, N_("Principal %s not found in any " "credential cache", ""), str ? str : ""); if (str) free(str); return KRB5_CC_NOTFOUND; } *id = cache; return 0; } /** * Move the content from one credential cache to another. The * operation is an atomic switch. * * @param context a Keberos context * @param from the credential cache to move the content from * @param to the credential cache to move the content to * @return On sucess, from is freed. On failure, error code is * returned and from and to are both still allocated, see krb5_get_error_message(). * * @ingroup krb5_ccache */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_cc_move(krb5_context context, krb5_ccache from, krb5_ccache to) { krb5_error_code ret; if (strcmp(from->ops->prefix, to->ops->prefix) != 0) { krb5_set_error_message(context, KRB5_CC_NOSUPP, N_("Moving credentials between diffrent " "types not yet supported", "")); return KRB5_CC_NOSUPP; } ret = (*to->ops->move)(context, from, to); if (ret == 0) { memset(from, 0, sizeof(*from)); free(from); } return ret; } #define KRB5_CONF_NAME "krb5_ccache_conf_data" #define KRB5_REALM_NAME "X-CACHECONF:" static krb5_error_code build_conf_principals(krb5_context context, krb5_ccache id, krb5_const_principal principal, const char *name, krb5_creds *cred) { krb5_principal client; krb5_error_code ret; char *pname = NULL; memset(cred, 0, sizeof(*cred)); ret = krb5_cc_get_principal(context, id, &client); if (ret) return ret; if (principal) { ret = krb5_unparse_name(context, principal, &pname); if (ret) return ret; } ret = krb5_make_principal(context, &cred->server, KRB5_REALM_NAME, KRB5_CONF_NAME, name, pname, NULL); free(pname); if (ret) { krb5_free_principal(context, client); return ret; } ret = krb5_copy_principal(context, client, &cred->client); krb5_free_principal(context, client); return ret; } /** * Return TRUE (non zero) if the principal is a configuration * principal (generated part of krb5_cc_set_config()). Returns FALSE * (zero) if not a configuration principal. * * @param context a Keberos context * @param principal principal to check if it a configuration principal * * @ingroup krb5_ccache */ KRB5_LIB_FUNCTION krb5_boolean KRB5_LIB_CALL krb5_is_config_principal(krb5_context context, krb5_const_principal principal) { if (strcmp(principal->realm, KRB5_REALM_NAME) != 0) return FALSE; if (principal->name.name_string.len == 0 || strcmp(principal->name.name_string.val[0], KRB5_CONF_NAME) != 0) return FALSE; return TRUE; } /** * Store some configuration for the credential cache in the cache. * Existing configuration under the same name is over-written. * * @param context a Keberos context * @param id the credential cache to store the data for * @param principal configuration for a specific principal, if * NULL, global for the whole cache. * @param name name under which the configuraion is stored. * @param data data to store, if NULL, configure is removed. * * @ingroup krb5_ccache */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_cc_set_config(krb5_context context, krb5_ccache id, krb5_const_principal principal, const char *name, krb5_data *data) { krb5_error_code ret; krb5_creds cred; ret = build_conf_principals(context, id, principal, name, &cred); if (ret) goto out; /* Remove old configuration */ ret = krb5_cc_remove_cred(context, id, 0, &cred); if (ret && ret != KRB5_CC_NOTFOUND) goto out; if (data) { /* not that anyone care when this expire */ cred.times.authtime = time(NULL); cred.times.endtime = cred.times.authtime + 3600 * 24 * 30; ret = krb5_data_copy(&cred.ticket, data->data, data->length); if (ret) goto out; ret = krb5_cc_store_cred(context, id, &cred); } out: krb5_free_cred_contents (context, &cred); return ret; } /** * Get some configuration for the credential cache in the cache. * * @param context a Keberos context * @param id the credential cache to store the data for * @param principal configuration for a specific principal, if * NULL, global for the whole cache. * @param name name under which the configuraion is stored. * @param data data to fetched, free with krb5_data_free() * * @ingroup krb5_ccache */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_cc_get_config(krb5_context context, krb5_ccache id, krb5_const_principal principal, const char *name, krb5_data *data) { krb5_creds mcred, cred; krb5_error_code ret; memset(&cred, 0, sizeof(cred)); krb5_data_zero(data); ret = build_conf_principals(context, id, principal, name, &mcred); if (ret) goto out; ret = krb5_cc_retrieve_cred(context, id, 0, &mcred, &cred); if (ret) goto out; ret = krb5_data_copy(data, cred.ticket.data, cred.ticket.length); out: krb5_free_cred_contents (context, &cred); krb5_free_cred_contents (context, &mcred); return ret; } /* * */ struct krb5_cccol_cursor_data { int idx; krb5_cc_cache_cursor cursor; }; /** * Get a new cache interation cursor that will interate over all * credentials caches independent of type. * * @param context a Keberos context * @param cursor passed into krb5_cccol_cursor_next() and free with krb5_cccol_cursor_free(). * * @return Returns 0 or and error code, see krb5_get_error_message(). * * @ingroup krb5_ccache */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_cccol_cursor_new(krb5_context context, krb5_cccol_cursor *cursor) { *cursor = calloc(1, sizeof(**cursor)); if (*cursor == NULL) return krb5_enomem(context); (*cursor)->idx = 0; (*cursor)->cursor = NULL; return 0; } /** * Get next credential cache from the iteration. * * @param context A Kerberos 5 context * @param cursor the iteration cursor * @param cache the returned cursor, pointer is set to NULL on failure * and a cache on success. The returned cache needs to be freed * with krb5_cc_close() or destroyed with krb5_cc_destroy(). * MIT Kerberos behavies slightly diffrent and sets cache to NULL * when all caches are iterated over and return 0. * * @return Return 0 or and error, KRB5_CC_END is returned at the end * of iteration. See krb5_get_error_message(). * * @ingroup krb5_ccache */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_cccol_cursor_next(krb5_context context, krb5_cccol_cursor cursor, krb5_ccache *cache) { krb5_error_code ret; *cache = NULL; while (cursor->idx < context->num_cc_ops) { if (cursor->cursor == NULL) { ret = krb5_cc_cache_get_first (context, context->cc_ops[cursor->idx]->prefix, &cursor->cursor); if (ret) { cursor->idx++; continue; } } ret = krb5_cc_cache_next(context, cursor->cursor, cache); if (ret == 0) break; krb5_cc_cache_end_seq_get(context, cursor->cursor); cursor->cursor = NULL; if (ret != KRB5_CC_END) break; cursor->idx++; } if (cursor->idx >= context->num_cc_ops) { krb5_set_error_message(context, KRB5_CC_END, N_("Reached end of credential caches", "")); return KRB5_CC_END; } return 0; } /** * End an iteration and free all resources, can be done before end is reached. * * @param context A Kerberos 5 context * @param cursor the iteration cursor to be freed. * * @return Return 0 or and error, KRB5_CC_END is returned at the end * of iteration. See krb5_get_error_message(). * * @ingroup krb5_ccache */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_cccol_cursor_free(krb5_context context, krb5_cccol_cursor *cursor) { krb5_cccol_cursor c = *cursor; *cursor = NULL; if (c) { if (c->cursor) krb5_cc_cache_end_seq_get(context, c->cursor); free(c); } return 0; } /** * Return the last time the credential cache was modified. * * @param context A Kerberos 5 context * @param id The credential cache to probe * @param mtime the last modification time, set to 0 on error. * @return Return 0 or and error. See krb5_get_error_message(). * * @ingroup krb5_ccache */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_cc_last_change_time(krb5_context context, krb5_ccache id, krb5_timestamp *mtime) { *mtime = 0; return (*id->ops->lastchange)(context, id, mtime); } /** * Return the last modfication time for a cache collection. The query * can be limited to a specific cache type. If the function return 0 * and mtime is 0, there was no credentials in the caches. * * @param context A Kerberos 5 context * @param type The credential cache to probe, if NULL, all type are traversed. * @param mtime the last modification time, set to 0 on error. * @return Return 0 or and error. See krb5_get_error_message(). * * @ingroup krb5_ccache */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_cccol_last_change_time(krb5_context context, const char *type, krb5_timestamp *mtime) { krb5_cccol_cursor cursor; krb5_error_code ret; krb5_ccache id; krb5_timestamp t = 0; *mtime = 0; ret = krb5_cccol_cursor_new (context, &cursor); if (ret) return ret; while (krb5_cccol_cursor_next(context, cursor, &id) == 0 && id != NULL) { if (type && strcmp(krb5_cc_get_type(context, id), type) != 0) continue; ret = krb5_cc_last_change_time(context, id, &t); krb5_cc_close(context, id); if (ret) continue; if (t > *mtime) *mtime = t; } krb5_cccol_cursor_free(context, &cursor); return 0; } /** * Return a friendly name on credential cache. Free the result with krb5_xfree(). * * @return Return an error code or 0, see krb5_get_error_message(). * * @ingroup krb5_ccache */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_cc_get_friendly_name(krb5_context context, krb5_ccache id, char **name) { krb5_error_code ret; krb5_data data; ret = krb5_cc_get_config(context, id, NULL, "FriendlyName", &data); if (ret) { krb5_principal principal; ret = krb5_cc_get_principal(context, id, &principal); if (ret) return ret; ret = krb5_unparse_name(context, principal, name); krb5_free_principal(context, principal); } else { ret = asprintf(name, "%.*s", (int)data.length, (char *)data.data); krb5_data_free(&data); if (ret <= 0) ret = krb5_enomem(context); else ret = 0; } return ret; } /** * Set the friendly name on credential cache. * * @return Return an error code or 0, see krb5_get_error_message(). * * @ingroup krb5_ccache */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_cc_set_friendly_name(krb5_context context, krb5_ccache id, const char *name) { krb5_data data; data.data = rk_UNCONST(name); data.length = strlen(name); return krb5_cc_set_config(context, id, NULL, "FriendlyName", &data); } /** * Get the lifetime of the initial ticket in the cache * * Get the lifetime of the initial ticket in the cache, if the initial * ticket was not found, the error code KRB5_CC_END is returned. * * @param context A Kerberos 5 context. * @param id a credential cache * @param t the relative lifetime of the initial ticket * * @return Return an error code or 0, see krb5_get_error_message(). * * @ingroup krb5_ccache */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_cc_get_lifetime(krb5_context context, krb5_ccache id, time_t *t) { krb5_data config_start_realm; char *start_realm; krb5_cc_cursor cursor; krb5_error_code ret; krb5_creds cred; time_t now, endtime = 0; *t = 0; krb5_timeofday(context, &now); ret = krb5_cc_get_config(context, id, NULL, "start_realm", &config_start_realm); if (ret == 0) { start_realm = strndup(config_start_realm.data, config_start_realm.length); krb5_data_free(&config_start_realm); } else { krb5_principal client; ret = krb5_cc_get_principal(context, id, &client); if (ret) return ret; start_realm = strdup(krb5_principal_get_realm(context, client)); krb5_free_principal(context, client); } if (start_realm == NULL) return krb5_enomem(context); ret = krb5_cc_start_seq_get(context, id, &cursor); if (ret) { free(start_realm); return ret; } while ((ret = krb5_cc_next_cred(context, id, &cursor, &cred)) == 0) { /** * If we find the start krbtgt in the cache, use that as the lifespan. */ if (krb5_principal_is_root_krbtgt(context, cred.server) && strcmp(cred.server->realm, start_realm) == 0) { if (now < cred.times.endtime) endtime = cred.times.endtime; krb5_free_cred_contents(context, &cred); break; } /* * Skip config entries */ if (krb5_is_config_principal(context, cred.server)) { krb5_free_cred_contents(context, &cred); continue; } /** * If there was no krbtgt, use the shortest lifetime of * service tickets that have yet to expire. If all * credentials are expired, krb5_cc_get_lifetime() will fail. */ if ((endtime == 0 || cred.times.endtime < endtime) && now < cred.times.endtime) endtime = cred.times.endtime; krb5_free_cred_contents(context, &cred); } free(start_realm); /* if we found an endtime use that */ if (endtime) { *t = endtime - now; ret = 0; } krb5_cc_end_seq_get(context, id, &cursor); return ret; } /** * Set the time offset betwen the client and the KDC * * If the backend doesn't support KDC offset, use the context global setting. * * @param context A Kerberos 5 context. * @param id a credential cache * @param offset the offset in seconds * * @return Return an error code or 0, see krb5_get_error_message(). * * @ingroup krb5_ccache */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_cc_set_kdc_offset(krb5_context context, krb5_ccache id, krb5_deltat offset) { if (id->ops->set_kdc_offset == NULL) { context->kdc_sec_offset = offset; context->kdc_usec_offset = 0; return 0; } return (*id->ops->set_kdc_offset)(context, id, offset); } /** * Get the time offset betwen the client and the KDC * * If the backend doesn't support KDC offset, use the context global setting. * * @param context A Kerberos 5 context. * @param id a credential cache * @param offset the offset in seconds * * @return Return an error code or 0, see krb5_get_error_message(). * * @ingroup krb5_ccache */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_cc_get_kdc_offset(krb5_context context, krb5_ccache id, krb5_deltat *offset) { if (id->ops->get_kdc_offset == NULL) { *offset = context->kdc_sec_offset; return 0; } return (*id->ops->get_kdc_offset)(context, id, offset); } #ifdef _WIN32 #define REGPATH_MIT_KRB5 "SOFTWARE\\MIT\\Kerberos5" static char * _get_default_cc_name_from_registry(krb5_context context, HKEY hkBase) { HKEY hk_k5 = 0; LONG code; char *ccname = NULL; code = RegOpenKeyEx(hkBase, REGPATH_MIT_KRB5, 0, KEY_READ, &hk_k5); if (code != ERROR_SUCCESS) return NULL; ccname = _krb5_parse_reg_value_as_string(context, hk_k5, "ccname", REG_NONE, 0); RegCloseKey(hk_k5); return ccname; } KRB5_LIB_FUNCTION char * KRB5_LIB_CALL _krb5_get_default_cc_name_from_registry(krb5_context context) { char *ccname; ccname = _get_default_cc_name_from_registry(context, HKEY_CURRENT_USER); if (ccname == NULL) ccname = _get_default_cc_name_from_registry(context, HKEY_LOCAL_MACHINE); return ccname; } KRB5_LIB_FUNCTION int KRB5_LIB_CALL _krb5_set_default_cc_name_to_registry(krb5_context context, krb5_ccache id) { HKEY hk_k5 = 0; LONG code; int ret = -1; char * ccname = NULL; code = RegOpenKeyEx(HKEY_CURRENT_USER, REGPATH_MIT_KRB5, 0, KEY_READ|KEY_WRITE, &hk_k5); if (code != ERROR_SUCCESS) return -1; ret = asprintf(&ccname, "%s:%s", krb5_cc_get_type(context, id), krb5_cc_get_name(context, id)); if (ret < 0) goto cleanup; ret = _krb5_store_string_to_reg_value(context, hk_k5, "ccname", REG_SZ, ccname, -1, 0); cleanup: if (ccname) free(ccname); RegCloseKey(hk_k5); return ret; } #endif heimdal-7.5.0/lib/krb5/krb5_find_padata.30000644000175000017500000000504312136107750016130 0ustar niknik.\" Copyright (c) 2004 Kungliga Tekniska Högskolan .\" (Royal Institute of Technology, Stockholm, Sweden). .\" All rights reserved. .\" .\" Redistribution and use in source and binary forms, with or without .\" modification, are permitted provided that the following conditions .\" are met: .\" .\" 1. Redistributions of source code must retain the above copyright .\" notice, this list of conditions and the following disclaimer. .\" .\" 2. Redistributions in binary form must reproduce the above copyright .\" notice, this list of conditions and the following disclaimer in the .\" documentation and/or other materials provided with the distribution. .\" .\" 3. Neither the name of the Institute nor the names of its contributors .\" may be used to endorse or promote products derived from this software .\" without specific prior written permission. .\" .\" THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND .\" ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE .\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE .\" ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE .\" FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL .\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS .\" OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) .\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT .\" LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF .\" SUCH DAMAGE. .\" .\" $Id$ .\" .Dd March 21, 2004 .Dt KRB5_FIND_PADATA 3 .Os HEIMDAL .Sh NAME .Nm krb5_find_padata , .Nm krb5_padata_add .Nd Kerberos 5 pre-authentication data handling functions .Sh LIBRARY Kerberos 5 Library (libkrb5, -lkrb5) .Sh SYNOPSIS .In krb5.h .Pp .Ft "PA_DATA *" .Fo krb5_find_padata .Fa "PA_DATA *val" .Fa "unsigned len" .Fa "int type" .Fa "int *index" .Fc .Ft int .Fo krb5_padata_add .Fa "krb5_context context" .Fa "METHOD_DATA *md" .Fa "int type" .Fa "void *buf" .Fa "size_t len" .Fc .Sh DESCRIPTION .Fn krb5_find_padata tries to find the pre-authentication data entry of type .Fa type in the array .Fa val of length .Fa len . The search is started at entry pointed out by .Fa *index (zero based indexing). If the type isn't found, .Dv NULL is returned. .Pp .Fn krb5_padata_add adds a pre-authentication data entry of type .Fa type pointed out by .Fa buf and .Fa len to .Fa md . .Sh SEE ALSO .Xr krb5 3 , .Xr kerberos 8 heimdal-7.5.0/lib/krb5/rd_rep.c0000644000175000017500000000732413026237312014307 0ustar niknik/* * Copyright (c) 1997 - 2001 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "krb5_locl.h" KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_rd_rep(krb5_context context, krb5_auth_context auth_context, const krb5_data *inbuf, krb5_ap_rep_enc_part **repl) { krb5_error_code ret; AP_REP ap_rep; size_t len; krb5_data data; krb5_crypto crypto; *repl = NULL; krb5_data_zero (&data); ret = decode_AP_REP(inbuf->data, inbuf->length, &ap_rep, &len); if (ret) return ret; if (ap_rep.pvno != 5) { ret = KRB5KRB_AP_ERR_BADVERSION; krb5_clear_error_message (context); goto out; } if (ap_rep.msg_type != krb_ap_rep) { ret = KRB5KRB_AP_ERR_MSG_TYPE; krb5_clear_error_message (context); goto out; } ret = krb5_crypto_init(context, auth_context->keyblock, 0, &crypto); if (ret) goto out; ret = krb5_decrypt_EncryptedData(context, crypto, KRB5_KU_AP_REQ_ENC_PART, &ap_rep.enc_part, &data); krb5_crypto_destroy(context, crypto); if (ret) goto out; *repl = malloc(sizeof(**repl)); if (*repl == NULL) { ret = krb5_enomem(context); goto out; } ret = decode_EncAPRepPart(data.data, data.length, *repl, &len); if (ret) { krb5_set_error_message(context, ret, N_("Failed to decode EncAPRepPart", "")); goto out; } if (auth_context->flags & KRB5_AUTH_CONTEXT_DO_TIME) { if ((*repl)->ctime != auth_context->authenticator->ctime || (*repl)->cusec != auth_context->authenticator->cusec) { ret = KRB5KRB_AP_ERR_MUT_FAIL; krb5_clear_error_message(context); goto out; } } if ((*repl)->seq_number) krb5_auth_con_setremoteseqnumber(context, auth_context, *((*repl)->seq_number)); if ((*repl)->subkey) krb5_auth_con_setremotesubkey(context, auth_context, (*repl)->subkey); out: if (ret) { krb5_free_ap_rep_enc_part(context, *repl); *repl = NULL; } krb5_data_free(&data); free_AP_REP(&ap_rep); return ret; } KRB5_LIB_FUNCTION void KRB5_LIB_CALL krb5_free_ap_rep_enc_part (krb5_context context, krb5_ap_rep_enc_part *val) { if (val) { free_EncAPRepPart (val); free (val); } } heimdal-7.5.0/lib/krb5/enomem.c0000644000175000017500000000342713026237312014314 0ustar niknik/* * Copyright (c) 1997 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "krb5_locl.h" krb5_error_code krb5_enomem(krb5_context context) { krb5_set_error_message(context, ENOMEM, N_("malloc: out of memory", "")); return ENOMEM; } heimdal-7.5.0/lib/krb5/test_crypto_wrapping.c0000644000175000017500000001110113026237312017306 0ustar niknik/* * Copyright (c) 2005 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of KTH nor the names of its contributors may be * used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY KTH AND ITS CONTRIBUTORS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL KTH OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "krb5_locl.h" #include #include static void test_wrapping(krb5_context context, size_t min_size, size_t max_size, size_t step, krb5_enctype etype) { krb5_error_code ret; krb5_keyblock key; krb5_crypto crypto; krb5_data data; char *etype_name; void *buf; size_t size; ret = krb5_generate_random_keyblock(context, etype, &key); if (ret) krb5_err(context, 1, ret, "krb5_generate_random_keyblock"); ret = krb5_enctype_to_string(context, etype, &etype_name); if (ret) krb5_err(context, 1, ret, "krb5_enctype_to_string"); buf = malloc(max_size); if (buf == NULL) krb5_errx(context, 1, "out of memory"); memset(buf, 0, max_size); ret = krb5_crypto_init(context, &key, 0, &crypto); if (ret) krb5_err(context, 1, ret, "krb5_crypto_init"); for (size = min_size; size < max_size; size += step) { size_t wrapped_size; ret = krb5_encrypt(context, crypto, 0, buf, size, &data); if (ret) krb5_err(context, 1, ret, "encrypt size %lu using %s", (unsigned long)size, etype_name); wrapped_size = krb5_get_wrapped_length(context, crypto, size); if (wrapped_size != data.length) krb5_errx(context, 1, "calculated wrapped length %lu != " "real wrapped length %lu for data length %lu using " "enctype %s", (unsigned long)wrapped_size, (unsigned long)data.length, (unsigned long)size, etype_name); krb5_data_free(&data); } free(etype_name); free(buf); krb5_crypto_destroy(context, crypto); krb5_free_keyblock_contents(context, &key); } static int version_flag = 0; static int help_flag = 0; static struct getargs args[] = { {"version", 0, arg_flag, &version_flag, "print version", NULL }, {"help", 0, arg_flag, &help_flag, NULL, NULL } }; static void usage (int ret) { arg_printusage (args, sizeof(args)/sizeof(*args), NULL, ""); exit (ret); } int main(int argc, char **argv) { krb5_context context; krb5_error_code ret; int i, optidx = 0; krb5_enctype enctypes[] = { #ifdef HEIM_WEAK_CRYPTO ETYPE_DES_CBC_CRC, ETYPE_DES_CBC_MD4, ETYPE_DES_CBC_MD5, #endif ETYPE_DES3_CBC_SHA1, ETYPE_ARCFOUR_HMAC_MD5, ETYPE_AES128_CTS_HMAC_SHA1_96, ETYPE_AES256_CTS_HMAC_SHA1_96, KRB5_ENCTYPE_AES128_CTS_HMAC_SHA256_128, KRB5_ENCTYPE_AES256_CTS_HMAC_SHA384_192 }; setprogname(argv[0]); if(getarg(args, sizeof(args) / sizeof(args[0]), argc, argv, &optidx)) usage(1); if (help_flag) usage (0); if(version_flag){ print_version(NULL); exit(0); } argc -= optidx; argv += optidx; ret = krb5_init_context(&context); if (ret) errx (1, "krb5_init_context failed: %d", ret); for (i = 0; i < sizeof(enctypes)/sizeof(enctypes[0]); i++) { krb5_enctype_enable(context, enctypes[i]); test_wrapping(context, 0, 1024, 1, enctypes[i]); test_wrapping(context, 1024, 1024 * 100, 1024, enctypes[i]); } krb5_free_context(context); return 0; } heimdal-7.5.0/lib/krb5/test_pac.c0000644000175000017500000003614213026237312014636 0ustar niknik/* * Copyright (c) 2006 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "krb5_locl.h" /* * This PAC and keys are copied (with permission) from Samba torture * regression test suite, they where created by Andrew Bartlet. */ static const unsigned char saved_pac[] = { 0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0xd8, 0x01, 0x00, 0x00, 0x48, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0a, 0x00, 0x00, 0x00, 0x20, 0x00, 0x00, 0x00, 0x20, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x06, 0x00, 0x00, 0x00, 0x14, 0x00, 0x00, 0x00, 0x40, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x07, 0x00, 0x00, 0x00, 0x14, 0x00, 0x00, 0x00, 0x58, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x10, 0x08, 0x00, 0xcc, 0xcc, 0xcc, 0xcc, 0xc8, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x30, 0xdf, 0xa6, 0xcb, 0x4f, 0x7d, 0xc5, 0x01, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x7f, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x7f, 0xc0, 0x3c, 0x4e, 0x59, 0x62, 0x73, 0xc5, 0x01, 0xc0, 0x3c, 0x4e, 0x59, 0x62, 0x73, 0xc5, 0x01, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x7f, 0x16, 0x00, 0x16, 0x00, 0x04, 0x00, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x08, 0x00, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0c, 0x00, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0x00, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x14, 0x00, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x18, 0x00, 0x02, 0x00, 0x65, 0x00, 0x00, 0x00, 0xed, 0x03, 0x00, 0x00, 0x04, 0x02, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x1c, 0x00, 0x02, 0x00, 0x20, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x14, 0x00, 0x16, 0x00, 0x20, 0x00, 0x02, 0x00, 0x16, 0x00, 0x18, 0x00, 0x24, 0x00, 0x02, 0x00, 0x28, 0x00, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x21, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x2c, 0x00, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0b, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0b, 0x00, 0x00, 0x00, 0x57, 0x00, 0x32, 0x00, 0x30, 0x00, 0x30, 0x00, 0x33, 0x00, 0x46, 0x00, 0x49, 0x00, 0x4e, 0x00, 0x41, 0x00, 0x4c, 0x00, 0x24, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x04, 0x02, 0x00, 0x00, 0x07, 0x00, 0x00, 0x00, 0x0b, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0a, 0x00, 0x00, 0x00, 0x57, 0x00, 0x32, 0x00, 0x30, 0x00, 0x30, 0x00, 0x33, 0x00, 0x46, 0x00, 0x49, 0x00, 0x4e, 0x00, 0x41, 0x00, 0x4c, 0x00, 0x0c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0b, 0x00, 0x00, 0x00, 0x57, 0x00, 0x49, 0x00, 0x4e, 0x00, 0x32, 0x00, 0x4b, 0x00, 0x33, 0x00, 0x54, 0x00, 0x48, 0x00, 0x49, 0x00, 0x4e, 0x00, 0x4b, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x01, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0x05, 0x15, 0x00, 0x00, 0x00, 0x11, 0x2f, 0xaf, 0xb5, 0x90, 0x04, 0x1b, 0xec, 0x50, 0x3b, 0xec, 0xdc, 0x01, 0x00, 0x00, 0x00, 0x30, 0x00, 0x02, 0x00, 0x07, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x05, 0x09, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0x66, 0x28, 0xea, 0x37, 0x80, 0xc5, 0x01, 0x16, 0x00, 0x77, 0x00, 0x32, 0x00, 0x30, 0x00, 0x30, 0x00, 0x33, 0x00, 0x66, 0x00, 0x69, 0x00, 0x6e, 0x00, 0x61, 0x00, 0x6c, 0x00, 0x24, 0x00, 0x76, 0xff, 0xff, 0xff, 0x37, 0xd5, 0xb0, 0xf7, 0x24, 0xf0, 0xd6, 0xd4, 0xec, 0x09, 0x86, 0x5a, 0xa0, 0xe8, 0xc3, 0xa9, 0x00, 0x00, 0x00, 0x00, 0x76, 0xff, 0xff, 0xff, 0xb4, 0xd8, 0xb8, 0xfe, 0x83, 0xb3, 0x13, 0x3f, 0xfc, 0x5c, 0x41, 0xad, 0xe2, 0x64, 0x83, 0xe0, 0x00, 0x00, 0x00, 0x00 }; static int type_1_length = 472; static const krb5_keyblock kdc_keyblock = { ETYPE_ARCFOUR_HMAC_MD5, { 16, "\xB2\x86\x75\x71\x48\xAF\x7F\xD2\x52\xC5\x36\x03\xA1\x50\xB7\xE7" } }; static const krb5_keyblock member_keyblock = { ETYPE_ARCFOUR_HMAC_MD5, { 16, "\xD2\x17\xFA\xEA\xE5\xE6\xB5\xF9\x5C\xCC\x94\x07\x7A\xB8\xA5\xFC" } }; static time_t authtime = 1120440609; static const char *user = "w2003final$"; /* * This pac from Christan Krause */ static const unsigned char saved_pac2[] = "\x05\x00\x00\x00\x00\x00\x00\x00\x01\x00\x00\x00\xc8\x01\x00\x00" "\x58\x00\x00\x00\x00\x00\x00\x00\x0a\x00\x00\x00\x18\x00\x00\x00" "\x20\x02\x00\x00\x00\x00\x00\x00\x0c\x00\x00\x00\x70\x00\x00\x00" "\x38\x02\x00\x00\x00\x00\x00\x00\x06\x00\x00\x00\x14\x00\x00\x00" "\xa8\x02\x00\x00\x00\x00\x00\x00\x07\x00\x00\x00\x14\x00\x00\x00" "\xc0\x02\x00\x00\x00\x00\x00\x00\x01\x10\x08\x00\xcc\xcc\xcc\xcc" "\xb8\x01\x00\x00\x00\x00\x00\x00\x00\x00\x02\x00\x7d\xee\x09\x76" "\xf2\x39\xc9\x01\xff\xff\xff\xff\xff\xff\xff\x7f\xff\xff\xff\xff" "\xff\xff\xff\x7f\x6d\x49\x38\x62\xf2\x39\xc9\x01\x6d\x09\xa2\x8c" "\xbb\x3a\xc9\x01\xff\xff\xff\xff\xff\xff\xff\x7f\x0e\x00\x0e\x00" "\x04\x00\x02\x00\x10\x00\x10\x00\x08\x00\x02\x00\x00\x00\x00\x00" "\x0c\x00\x02\x00\x00\x00\x00\x00\x10\x00\x02\x00\x00\x00\x00\x00" "\x14\x00\x02\x00\x00\x00\x00\x00\x18\x00\x02\x00\x02\x01\x00\x00" "\x52\x04\x00\x00\x01\x02\x00\x00\x03\x00\x00\x00\x1c\x00\x02\x00" "\x20\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" "\x00\x00\x00\x00\x10\x00\x12\x00\x20\x00\x02\x00\x0e\x00\x10\x00" "\x24\x00\x02\x00\x28\x00\x02\x00\x00\x00\x00\x00\x00\x00\x00\x00" "\x10\x02\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" "\x00\x00\x00\x00\x07\x00\x00\x00\x00\x00\x00\x00\x07\x00\x00\x00" "\x6f\x00\x70\x00\x65\x00\x6e\x00\x6d\x00\x73\x00\x70\x00\x00\x00" "\x08\x00\x00\x00\x00\x00\x00\x00\x08\x00\x00\x00\x6f\x00\x70\x00" "\x65\x00\x6e\x00\x20\x00\x6d\x00\x73\x00\x70\x00\x00\x00\x00\x00" "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x03\x00\x00\x00" "\x60\x04\x00\x00\x07\x00\x00\x00\x01\x02\x00\x00\x07\x00\x00\x00" "\x5e\x04\x00\x00\x07\x00\x00\x00\x09\x00\x00\x00\x00\x00\x00\x00" "\x08\x00\x00\x00\x43\x00\x48\x00\x4b\x00\x52\x00\x2d\x00\x41\x00" "\x44\x00\x53\x00\x08\x00\x00\x00\x00\x00\x00\x00\x07\x00\x00\x00" "\x4d\x00\x53\x00\x50\x00\x2d\x00\x41\x00\x44\x00\x53\x00\x00\x00" "\x04\x00\x00\x00\x01\x04\x00\x00\x00\x00\x00\x05\x15\x00\x00\x00" "\x91\xad\xdc\x4c\x63\xb8\xb5\x48\xd5\x53\xd2\xd1\x00\x00\x00\x00" "\x00\x66\xeb\x75\xf2\x39\xc9\x01\x0e\x00\x6f\x00\x70\x00\x65\x00" "\x6e\x00\x6d\x00\x73\x00\x70\x00\x38\x00\x10\x00\x28\x00\x48\x00" "\x00\x00\x00\x00\x00\x00\x00\x00\x6f\x00\x70\x00\x65\x00\x6e\x00" "\x6d\x00\x73\x00\x70\x00\x40\x00\x6d\x00\x73\x00\x70\x00\x2d\x00" "\x61\x00\x64\x00\x73\x00\x2e\x00\x70\x00\x65\x00\x70\x00\x70\x00" "\x65\x00\x72\x00\x63\x00\x6f\x00\x6e\x00\x2e\x00\x64\x00\x65\x00" "\x4d\x00\x53\x00\x50\x00\x2d\x00\x41\x00\x44\x00\x53\x00\x2e\x00" "\x50\x00\x45\x00\x50\x00\x50\x00\x45\x00\x52\x00\x43\x00\x4f\x00" "\x4e\x00\x2e\x00\x44\x00\x45\x00\x76\xff\xff\xff\xb3\x56\x15\x29" "\x37\xc6\x5c\xf7\x97\x35\xfa\xec\x59\xe8\x96\xa0\x00\x00\x00\x00" "\x76\xff\xff\xff\x50\x71\xa2\xb1\xa3\x64\x82\x5c\xfd\x23\xea\x3b" "\xb0\x19\x12\xd4\x00\x00\x00\x00"; static const krb5_keyblock member_keyblock2 = { ETYPE_DES_CBC_MD5, { 8, "\x9e\x37\x83\x25\x4a\x7f\xf2\xf8" } }; static time_t authtime2 = 1225304188; static const char *user2 = "openmsp"; int main(int argc, char **argv) { krb5_error_code ret; krb5_context context; krb5_pac pac; krb5_data data; krb5_principal p, p2; ret = krb5_init_context(&context); if (ret) errx(1, "krb5_init_contex"); krb5_enctype_enable(context, ETYPE_DES_CBC_MD5); ret = krb5_parse_name_flags(context, user, KRB5_PRINCIPAL_PARSE_NO_REALM, &p); if (ret) krb5_err(context, 1, ret, "krb5_parse_name"); ret = krb5_pac_parse(context, saved_pac, sizeof(saved_pac), &pac); if (ret) krb5_err(context, 1, ret, "krb5_pac_parse"); ret = krb5_pac_verify(context, pac, authtime, p, &member_keyblock, &kdc_keyblock); if (ret) krb5_err(context, 1, ret, "krb5_pac_verify"); ret = _krb5_pac_sign(context, pac, authtime, p, &member_keyblock, &kdc_keyblock, &data); if (ret) krb5_err(context, 1, ret, "_krb5_pac_sign"); krb5_pac_free(context, pac); ret = krb5_pac_parse(context, data.data, data.length, &pac); krb5_data_free(&data); if (ret) krb5_err(context, 1, ret, "krb5_pac_parse 2"); ret = krb5_pac_verify(context, pac, authtime, p, &member_keyblock, &kdc_keyblock); if (ret) krb5_err(context, 1, ret, "krb5_pac_verify 2"); /* make a copy and try to reproduce it */ { uint32_t *list; size_t len, i; krb5_pac pac2; ret = krb5_pac_init(context, &pac2); if (ret) krb5_err(context, 1, ret, "krb5_pac_init"); /* our two user buffer plus the three "system" buffers */ ret = krb5_pac_get_types(context, pac, &len, &list); if (ret) krb5_err(context, 1, ret, "krb5_pac_get_types"); for (i = 0; i < len; i++) { /* skip server_cksum, privsvr_cksum, and logon_name */ if (list[i] == 6 || list[i] == 7 || list[i] == 10) continue; ret = krb5_pac_get_buffer(context, pac, list[i], &data); if (ret) krb5_err(context, 1, ret, "krb5_pac_get_buffer"); if (list[i] == 1) { if (type_1_length != data.length) krb5_errx(context, 1, "type 1 have wrong length: %lu", (unsigned long)data.length); } else krb5_errx(context, 1, "unknown type %lu", (unsigned long)list[i]); ret = krb5_pac_add_buffer(context, pac2, list[i], &data); if (ret) krb5_err(context, 1, ret, "krb5_pac_add_buffer"); krb5_data_free(&data); } free(list); ret = _krb5_pac_sign(context, pac2, authtime, p, &member_keyblock, &kdc_keyblock, &data); if (ret) krb5_err(context, 1, ret, "_krb5_pac_sign 4"); krb5_pac_free(context, pac2); ret = krb5_pac_parse(context, data.data, data.length, &pac2); krb5_data_free(&data); if (ret) krb5_err(context, 1, ret, "krb5_pac_parse 4"); ret = krb5_pac_verify(context, pac2, authtime, p, &member_keyblock, &kdc_keyblock); if (ret) krb5_err(context, 1, ret, "krb5_pac_verify 4"); krb5_pac_free(context, pac2); } krb5_pac_free(context, pac); /* * check pac from Christian */ ret = krb5_parse_name_flags(context, user2, KRB5_PRINCIPAL_PARSE_NO_REALM, &p2); if (ret) krb5_err(context, 1, ret, "krb5_parse_name"); ret = krb5_pac_parse(context, saved_pac2, sizeof(saved_pac2) -1, &pac); if (ret) krb5_err(context, 1, ret, "krb5_pac_parse"); ret = krb5_pac_verify(context, pac, authtime2, p2, &member_keyblock2, NULL); if (ret) krb5_err(context, 1, ret, "krb5_pac_verify c1"); krb5_pac_free(context, pac); krb5_free_principal(context, p2); /* * Test empty free */ ret = krb5_pac_init(context, &pac); if (ret) krb5_err(context, 1, ret, "krb5_pac_init"); krb5_pac_free(context, pac); /* * Test add remove buffer */ ret = krb5_pac_init(context, &pac); if (ret) krb5_err(context, 1, ret, "krb5_pac_init"); { const krb5_data cdata = { 2, "\x00\x01" } ; ret = krb5_pac_add_buffer(context, pac, 1, &cdata); if (ret) krb5_err(context, 1, ret, "krb5_pac_add_buffer"); } { ret = krb5_pac_get_buffer(context, pac, 1, &data); if (ret) krb5_err(context, 1, ret, "krb5_pac_get_buffer"); if (data.length != 2 || memcmp(data.data, "\x00\x01", 2) != 0) krb5_errx(context, 1, "krb5_pac_get_buffer data not the same"); krb5_data_free(&data); } { const krb5_data cdata = { 2, "\x02\x00" } ; ret = krb5_pac_add_buffer(context, pac, 2, &cdata); if (ret) krb5_err(context, 1, ret, "krb5_pac_add_buffer"); } { ret = krb5_pac_get_buffer(context, pac, 1, &data); if (ret) krb5_err(context, 1, ret, "krb5_pac_get_buffer"); if (data.length != 2 || memcmp(data.data, "\x00\x01", 2) != 0) krb5_errx(context, 1, "krb5_pac_get_buffer data not the same"); krb5_data_free(&data); /* */ ret = krb5_pac_get_buffer(context, pac, 2, &data); if (ret) krb5_err(context, 1, ret, "krb5_pac_get_buffer"); if (data.length != 2 || memcmp(data.data, "\x02\x00", 2) != 0) krb5_errx(context, 1, "krb5_pac_get_buffer data not the same"); krb5_data_free(&data); } ret = _krb5_pac_sign(context, pac, authtime, p, &member_keyblock, &kdc_keyblock, &data); if (ret) krb5_err(context, 1, ret, "_krb5_pac_sign"); krb5_pac_free(context, pac); ret = krb5_pac_parse(context, data.data, data.length, &pac); krb5_data_free(&data); if (ret) krb5_err(context, 1, ret, "krb5_pac_parse 3"); ret = krb5_pac_verify(context, pac, authtime, p, &member_keyblock, &kdc_keyblock); if (ret) krb5_err(context, 1, ret, "krb5_pac_verify 3"); { uint32_t *list; size_t len; /* our two user buffer plus the three "system" buffers */ ret = krb5_pac_get_types(context, pac, &len, &list); if (ret) krb5_err(context, 1, ret, "krb5_pac_get_types"); if (len != 5) krb5_errx(context, 1, "list wrong length"); free(list); } krb5_pac_free(context, pac); krb5_free_principal(context, p); krb5_free_context(context); return 0; } heimdal-7.5.0/lib/krb5/krb5_rcache.cat30000644000175000017500000001262313212450757015621 0ustar niknik KRB5_RCACHE(3) BSD Library Functions Manual KRB5_RCACHE(3) NNAAMMEE kkrrbb55__rrccaacchhee, kkrrbb55__rrcc__cclloossee, kkrrbb55__rrcc__ddeeffaauulltt, kkrrbb55__rrcc__ddeeffaauulltt__nnaammee, kkrrbb55__rrcc__ddeeffaauulltt__ttyyppee, kkrrbb55__rrcc__ddeessttrrooyy, kkrrbb55__rrcc__eexxppuunnggee, kkrrbb55__rrcc__ggeett__lliiffeessppaann, kkrrbb55__rrcc__ggeett__nnaammee, kkrrbb55__rrcc__ggeett__ttyyppee, kkrrbb55__rrcc__iinniittiiaalliizzee, kkrrbb55__rrcc__rreeccoovveerr, kkrrbb55__rrcc__rreessoollvvee, kkrrbb55__rrcc__rreessoollvvee__ffuullll, kkrrbb55__rrcc__rreessoollvvee__ttyyppee, kkrrbb55__rrcc__ssttoorree, kkrrbb55__ggeett__sseerrvveerr__rrccaacchhee -- Kerberos 5 replay cache LLIIBBRRAARRYY Kerberos 5 Library (libkrb5, -lkrb5) SSYYNNOOPPSSIISS ##iinncclluuddee <> struct krb5_rcache; _k_r_b_5___e_r_r_o_r___c_o_d_e kkrrbb55__rrcc__cclloossee(_k_r_b_5___c_o_n_t_e_x_t _c_o_n_t_e_x_t, _k_r_b_5___r_c_a_c_h_e _i_d); _k_r_b_5___e_r_r_o_r___c_o_d_e kkrrbb55__rrcc__ddeeffaauulltt(_k_r_b_5___c_o_n_t_e_x_t _c_o_n_t_e_x_t, _k_r_b_5___r_c_a_c_h_e _*_i_d); _c_o_n_s_t _c_h_a_r _* kkrrbb55__rrcc__ddeeffaauulltt__nnaammee(_k_r_b_5___c_o_n_t_e_x_t _c_o_n_t_e_x_t); _c_o_n_s_t _c_h_a_r _* kkrrbb55__rrcc__ddeeffaauulltt__ttyyppee(_k_r_b_5___c_o_n_t_e_x_t _c_o_n_t_e_x_t); _k_r_b_5___e_r_r_o_r___c_o_d_e kkrrbb55__rrcc__ddeessttrrooyy(_k_r_b_5___c_o_n_t_e_x_t _c_o_n_t_e_x_t, _k_r_b_5___r_c_a_c_h_e _i_d); _k_r_b_5___e_r_r_o_r___c_o_d_e kkrrbb55__rrcc__eexxppuunnggee(_k_r_b_5___c_o_n_t_e_x_t _c_o_n_t_e_x_t, _k_r_b_5___r_c_a_c_h_e _i_d); _k_r_b_5___e_r_r_o_r___c_o_d_e kkrrbb55__rrcc__ggeett__lliiffeessppaann(_k_r_b_5___c_o_n_t_e_x_t _c_o_n_t_e_x_t, _k_r_b_5___r_c_a_c_h_e _i_d, _k_r_b_5___d_e_l_t_a_t _*_a_u_t_h___l_i_f_e_s_p_a_n); _c_o_n_s_t _c_h_a_r_* kkrrbb55__rrcc__ggeett__nnaammee(_k_r_b_5___c_o_n_t_e_x_t _c_o_n_t_e_x_t, _k_r_b_5___r_c_a_c_h_e _i_d); _c_o_n_s_t _c_h_a_r_* kkrrbb55__rrcc__ggeett__ttyyppee(_k_r_b_5___c_o_n_t_e_x_t _c_o_n_t_e_x_t, _k_r_b_5___r_c_a_c_h_e _i_d); _k_r_b_5___e_r_r_o_r___c_o_d_e kkrrbb55__rrcc__iinniittiiaalliizzee(_k_r_b_5___c_o_n_t_e_x_t _c_o_n_t_e_x_t, _k_r_b_5___r_c_a_c_h_e _i_d, _k_r_b_5___d_e_l_t_a_t _a_u_t_h___l_i_f_e_s_p_a_n); _k_r_b_5___e_r_r_o_r___c_o_d_e kkrrbb55__rrcc__rreeccoovveerr(_k_r_b_5___c_o_n_t_e_x_t _c_o_n_t_e_x_t, _k_r_b_5___r_c_a_c_h_e _i_d); _k_r_b_5___e_r_r_o_r___c_o_d_e kkrrbb55__rrcc__rreessoollvvee(_k_r_b_5___c_o_n_t_e_x_t _c_o_n_t_e_x_t, _k_r_b_5___r_c_a_c_h_e _i_d, _c_o_n_s_t _c_h_a_r _*_n_a_m_e); _k_r_b_5___e_r_r_o_r___c_o_d_e kkrrbb55__rrcc__rreessoollvvee__ffuullll(_k_r_b_5___c_o_n_t_e_x_t _c_o_n_t_e_x_t, _k_r_b_5___r_c_a_c_h_e _*_i_d, _c_o_n_s_t _c_h_a_r _*_s_t_r_i_n_g___n_a_m_e); _k_r_b_5___e_r_r_o_r___c_o_d_e kkrrbb55__rrcc__rreessoollvvee__ttyyppee(_k_r_b_5___c_o_n_t_e_x_t _c_o_n_t_e_x_t, _k_r_b_5___r_c_a_c_h_e _*_i_d, _c_o_n_s_t _c_h_a_r _*_t_y_p_e); _k_r_b_5___e_r_r_o_r___c_o_d_e kkrrbb55__rrcc__ssttoorree(_k_r_b_5___c_o_n_t_e_x_t _c_o_n_t_e_x_t, _k_r_b_5___r_c_a_c_h_e _i_d, _k_r_b_5___d_o_n_o_t___r_e_p_l_a_y _*_r_e_p); _k_r_b_5___e_r_r_o_r___c_o_d_e kkrrbb55__ggeett__sseerrvveerr__rrccaacchhee(_k_r_b_5___c_o_n_t_e_x_t _c_o_n_t_e_x_t, _c_o_n_s_t _k_r_b_5___d_a_t_a _*_p_i_e_c_e, _k_r_b_5___r_c_a_c_h_e _*_i_d); DDEESSCCRRIIPPTTIIOONN The krb5_rcache structure holds a storage element that is used for data manipulation. The structure contains no public accessible elements. kkrrbb55__rrcc__iinniittiiaalliizzee() Creates the reply cache _i_d and sets it lifespan to _a_u_t_h___l_i_f_e_s_p_a_n. If the cache already exists, the content is destroyed. SSEEEE AALLSSOO krb5(3), krb5_data(3), kerberos(8) HEIMDAL May 1, 2006 HEIMDAL heimdal-7.5.0/lib/krb5/acl.c0000644000175000017500000001701413026237312013570 0ustar niknik/* * Copyright (c) 2000 - 2002, 2004 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "krb5_locl.h" #include struct acl_field { enum { acl_string, acl_fnmatch, acl_retval } type; union { const char *cstr; char **retv; } u; struct acl_field *next, **last; }; static void free_retv(struct acl_field *acl) { while(acl != NULL) { if (acl->type == acl_retval) { if (*acl->u.retv) free(*acl->u.retv); *acl->u.retv = NULL; } acl = acl->next; } } static void acl_free_list(struct acl_field *acl, int retv) { struct acl_field *next; if (retv) free_retv(acl); while(acl != NULL) { next = acl->next; free(acl); acl = next; } } static krb5_error_code acl_parse_format(krb5_context context, struct acl_field **acl_ret, const char *format, va_list ap) { const char *p; struct acl_field *acl = NULL, *tmp; for(p = format; *p != '\0'; p++) { tmp = malloc(sizeof(*tmp)); if(tmp == NULL) { acl_free_list(acl, 0); return krb5_enomem(context); } if(*p == 's') { tmp->type = acl_string; tmp->u.cstr = va_arg(ap, const char*); } else if(*p == 'f') { tmp->type = acl_fnmatch; tmp->u.cstr = va_arg(ap, const char*); } else if(*p == 'r') { tmp->type = acl_retval; tmp->u.retv = va_arg(ap, char **); *tmp->u.retv = NULL; } else { krb5_set_error_message(context, EINVAL, N_("Unknown format specifier %c while " "parsing ACL", "specifier"), *p); acl_free_list(acl, 0); free(tmp); return EINVAL; } tmp->next = NULL; if(acl == NULL) acl = tmp; else *acl->last = tmp; acl->last = &tmp->next; } *acl_ret = acl; return 0; } static krb5_boolean acl_match_field(krb5_context context, const char *string, struct acl_field *field) { if(field->type == acl_string) { return !strcmp(field->u.cstr, string); } else if(field->type == acl_fnmatch) { return !fnmatch(field->u.cstr, string, 0); } else if(field->type == acl_retval) { *field->u.retv = strdup(string); return TRUE; } return FALSE; } static krb5_boolean acl_match_acl(krb5_context context, struct acl_field *acl, const char *string) { char buf[256]; while(strsep_copy(&string, " \t", buf, sizeof(buf)) != -1) { if(buf[0] == '\0') continue; /* skip ws */ if (acl == NULL) return FALSE; if(!acl_match_field(context, buf, acl)) { return FALSE; } acl = acl->next; } if (acl) return FALSE; return TRUE; } /** * krb5_acl_match_string matches ACL format against a string. * * The ACL format has three format specifiers: s, f, and r. Each * specifier will retrieve one argument from the variable arguments * for either matching or storing data. The input string is split up * using " " (space) and "\t" (tab) as a delimiter; multiple and "\t" * in a row are considered to be the same. * * List of format specifiers: * - s Matches a string using strcmp(3) (case sensitive). * - f Matches the string with fnmatch(3). Theflags * argument (the last argument) passed to the fnmatch function is 0. * - r Returns a copy of the string in the char ** passed in; the copy * must be freed with free(3). There is no need to free(3) the * string on error: the function will clean up and set the pointer * to NULL. * * @param context Kerberos 5 context * @param string string to match with * @param format format to match * @param ... parameter to format string * * @return Return an error code or 0. * * * @code * char *s; * * ret = krb5_acl_match_string(context, "foo", "s", "foo"); * if (ret) * krb5_errx(context, 1, "acl didn't match"); * ret = krb5_acl_match_string(context, "foo foo baz/kaka", * "ss", "foo", &s, "foo/\\*"); * if (ret) { * // no need to free(s) on error * assert(s == NULL); * krb5_errx(context, 1, "acl didn't match"); * } * free(s); * @endcode * * @sa krb5_acl_match_file * @ingroup krb5_support */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_acl_match_string(krb5_context context, const char *string, const char *format, ...) { krb5_error_code ret; krb5_boolean found; struct acl_field *acl; va_list ap; va_start(ap, format); ret = acl_parse_format(context, &acl, format, ap); va_end(ap); if(ret) return ret; found = acl_match_acl(context, acl, string); acl_free_list(acl, !found); if (found) { return 0; } else { krb5_set_error_message(context, EACCES, N_("ACL did not match", "")); return EACCES; } } /** * krb5_acl_match_file matches ACL format against each line in a file * using krb5_acl_match_string(). Lines starting with # are treated * like comments and ignored. * * @param context Kerberos 5 context. * @param file file with acl listed in the file. * @param format format to match. * @param ... parameter to format string. * * @return Return an error code or 0. * * @sa krb5_acl_match_string * @ingroup krb5_support */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_acl_match_file(krb5_context context, const char *file, const char *format, ...) { krb5_error_code ret; struct acl_field *acl; char buf[256]; va_list ap; FILE *f; krb5_boolean found; f = fopen(file, "r"); if(f == NULL) { int save_errno = errno; rk_strerror_r(save_errno, buf, sizeof(buf)); krb5_set_error_message(context, save_errno, N_("open(%s): %s", "file, errno"), file, buf); return save_errno; } rk_cloexec_file(f); va_start(ap, format); ret = acl_parse_format(context, &acl, format, ap); va_end(ap); if(ret) { fclose(f); return ret; } found = FALSE; while(fgets(buf, sizeof(buf), f)) { if(buf[0] == '#') continue; if(acl_match_acl(context, acl, buf)) { found = TRUE; break; } free_retv(acl); } fclose(f); acl_free_list(acl, !found); if (found) { return 0; } else { krb5_set_error_message(context, EACCES, N_("ACL did not match", "")); return EACCES; } } heimdal-7.5.0/lib/krb5/krb5_get_all_client_addrs.cat30000644000175000017500000000360313212450756020513 0ustar niknik KRB5_GET_ADDRS(3) BSD Library Functions Manual KRB5_GET_ADDRS(3) NNAAMMEE kkrrbb55__ggeett__aallll__cclliieenntt__aaddddrrss, kkrrbb55__ggeett__aallll__sseerrvveerr__aaddddrrss -- return local addresses LLIIBBRRAARRYY Kerberos 5 Library (libkrb5, -lkrb5) SSYYNNOOPPSSIISS ##iinncclluuddee <> _k_r_b_5___e_r_r_o_r___c_o_d_e kkrrbb55__ggeett__aallll__cclliieenntt__aaddddrrss(_k_r_b_5___c_o_n_t_e_x_t _c_o_n_t_e_x_t, _k_r_b_5___a_d_d_r_e_s_s_e_s _*_a_d_d_r_s); _k_r_b_5___e_r_r_o_r___c_o_d_e kkrrbb55__ggeett__aallll__sseerrvveerr__aaddddrrss(_k_r_b_5___c_o_n_t_e_x_t _c_o_n_t_e_x_t, _k_r_b_5___a_d_d_r_e_s_s_e_s _*_a_d_d_r_s); DDEESSCCRRIIPPTTIIOONN These functions return in _a_d_d_r_s a list of addresses associated with the local host. The server variant returns all configured interface addresses (if possi- ble), including loop-back addresses. This is useful if you want to create sockets to listen to. The client version will also scan local interfaces (can be turned off by setting libdefaults/scan_interfaces to false in _k_r_b_5_._c_o_n_f), but will not include loop-back addresses, unless there are no other addresses found. It will remove all addresses included in libdefaults/ignore_addresses but will unconditionally include addresses in libdefaults/extra_addresses. The returned addresses should be freed by calling kkrrbb55__ffrreeee__aaddddrreesssseess(). SSEEEE AALLSSOO krb5_free_addresses(3) HEIMDAL July 1, 2001 HEIMDAL heimdal-7.5.0/lib/krb5/pkinit-ec.c0000644000175000017500000001657413026237312014726 0ustar niknik/* * Copyright (c) 2016 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Portions Copyright (c) 2009 Apple Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include #include #ifdef PKINIT /* * As with the other *-ec.c files in Heimdal, this is a bit of a hack. * * The idea is to use OpenSSL for EC because hcrypto doesn't have the * required functionality at this time. To do this we segregate * EC-using code into separate source files and then we arrange for them * to get the OpenSSL headers and not the conflicting hcrypto ones. * * Because of auto-generated *-private.h headers, we end up needing to * make sure various types are defined before we include them, thus the * strange header include order here. */ #ifdef HAVE_HCRYPTO_W_OPENSSL #include #include #include #include #define HEIM_NO_CRYPTO_HDRS #endif /* * NO_HCRYPTO_POLLUTION -> don't refer to hcrypto type/function names * that we don't need in this file and which would clash with OpenSSL's * in ways that are difficult to address in cleaner ways. * * In the medium- to long-term what we should do is move all PK in * Heimdal to the newer EVP interfaces for PK and then nothing outside * lib/hcrypto should ever have to include OpenSSL headers, and -more * specifically- the only thing that should ever have to include OpenSSL * headers is the OpenSSL backend to hcrypto. */ #define NO_HCRYPTO_POLLUTION #include "krb5_locl.h" #include #include #include #include #include #include #include #include krb5_error_code _krb5_build_authpack_subjectPK_EC(krb5_context context, krb5_pk_init_ctx ctx, AuthPack *a) { #ifdef HAVE_HCRYPTO_W_OPENSSL krb5_error_code ret; ECParameters ecp; unsigned char *p; size_t size; int xlen; /* copy in public key, XXX find the best curve that the server support or use the clients curve if possible */ ecp.element = choice_ECParameters_namedCurve; ret = der_copy_oid(&asn1_oid_id_ec_group_secp256r1, &ecp.u.namedCurve); if (ret) return ret; ALLOC(a->clientPublicValue->algorithm.parameters, 1); if (a->clientPublicValue->algorithm.parameters == NULL) { free_ECParameters(&ecp); return krb5_enomem(context); } ASN1_MALLOC_ENCODE(ECParameters, p, xlen, &ecp, &size, ret); free_ECParameters(&ecp); if (ret) return ret; if ((int)size != xlen) krb5_abortx(context, "asn1 internal error"); a->clientPublicValue->algorithm.parameters->data = p; a->clientPublicValue->algorithm.parameters->length = size; /* copy in public key */ ret = der_copy_oid(&asn1_oid_id_ecPublicKey, &a->clientPublicValue->algorithm.algorithm); if (ret) return ret; ctx->u.eckey = EC_KEY_new_by_curve_name(NID_X9_62_prime256v1); if (ctx->u.eckey == NULL) return krb5_enomem(context); ret = EC_KEY_generate_key(ctx->u.eckey); if (ret != 1) return EINVAL; xlen = i2o_ECPublicKey(ctx->u.eckey, NULL); if (xlen <= 0) return EINVAL; p = malloc(xlen); if (p == NULL) return krb5_enomem(context); a->clientPublicValue->subjectPublicKey.data = p; xlen = i2o_ECPublicKey(ctx->u.eckey, &p); if (xlen <= 0) { a->clientPublicValue->subjectPublicKey.data = NULL; free(p); return EINVAL; } a->clientPublicValue->subjectPublicKey.length = xlen * 8; return 0; /* XXX verify that this is right with RFC3279 */ #else krb5_set_error_message(context, ENOTSUP, N_("PKINIT: ECDH not supported", "")); return ENOTSUP; #endif } krb5_error_code _krb5_pk_rd_pa_reply_ecdh_compute_key(krb5_context context, krb5_pk_init_ctx ctx, const unsigned char *in, size_t in_sz, unsigned char **out, int *out_sz) { #ifdef HAVE_HCRYPTO_W_OPENSSL krb5_error_code ret = 0; int dh_gen_keylen; const EC_GROUP *group; EC_KEY *public = NULL; group = EC_KEY_get0_group(ctx->u.eckey); public = EC_KEY_new(); if (public == NULL) return krb5_enomem(context); if (EC_KEY_set_group(public, group) != 1) { EC_KEY_free(public); return krb5_enomem(context); } if (o2i_ECPublicKey(&public, &in, in_sz) == NULL) { EC_KEY_free(public); ret = KRB5KRB_ERR_GENERIC; krb5_set_error_message(context, ret, N_("PKINIT: Can't parse ECDH public key", "")); return ret; } *out_sz = (EC_GROUP_get_degree(group) + 7) / 8; if (*out_sz < 0) return EOVERFLOW; *out = malloc(*out_sz); if (*out == NULL) { EC_KEY_free(public); return krb5_enomem(context); } dh_gen_keylen = ECDH_compute_key(*out, *out_sz, EC_KEY_get0_public_key(public), ctx->u.eckey, NULL); EC_KEY_free(public); if (dh_gen_keylen <= 0) { ret = KRB5KRB_ERR_GENERIC; dh_gen_keylen = 0; krb5_set_error_message(context, ret, N_("PKINIT: Can't compute ECDH public key", "")); free(*out); *out = NULL; *out_sz = 0; } *out_sz = dh_gen_keylen; return ret; #else krb5_set_error_message(context, ENOTSUP, N_("PKINIT: ECDH not supported", "")); return ENOTSUP; #endif } void _krb5_pk_eckey_free(void *eckey) { #ifdef HAVE_HCRYPTO_W_OPENSSL EC_KEY_free(eckey); #endif } #else static char lib_krb5_pkinit_ec_c = '\0'; #endif heimdal-7.5.0/lib/krb5/plugin.c0000644000175000017500000003634313026237312014335 0ustar niknik/* * Copyright (c) 2006 - 2007 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "krb5_locl.h" #ifdef HAVE_DLFCN_H #include #endif #include struct krb5_plugin { void *symbol; struct krb5_plugin *next; }; struct plugin { enum { DSO, SYMBOL } type; union { struct { char *path; void *dsohandle; } dso; struct { enum krb5_plugin_type type; char *name; char *symbol; } symbol; } u; struct plugin *next; }; static HEIMDAL_MUTEX plugin_mutex = HEIMDAL_MUTEX_INITIALIZER; static struct plugin *registered = NULL; /** * Register a plugin symbol name of specific type. * @param context a Keberos context * @param type type of plugin symbol * @param name name of plugin symbol * @param symbol a pointer to the named symbol * @return In case of error a non zero error com_err error is returned * and the Kerberos error string is set. * * @ingroup krb5_support */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_plugin_register(krb5_context context, enum krb5_plugin_type type, const char *name, void *symbol) { struct plugin *e; HEIMDAL_MUTEX_lock(&plugin_mutex); /* check for duplicates */ for (e = registered; e != NULL; e = e->next) { if (e->type == SYMBOL && strcmp(e->u.symbol.name, name) == 0 && e->u.symbol.type == type && e->u.symbol.symbol == symbol) { HEIMDAL_MUTEX_unlock(&plugin_mutex); return 0; } } e = calloc(1, sizeof(*e)); if (e == NULL) { HEIMDAL_MUTEX_unlock(&plugin_mutex); krb5_set_error_message(context, ENOMEM, "malloc: out of memory"); return ENOMEM; } e->type = SYMBOL; e->u.symbol.type = type; e->u.symbol.name = strdup(name); if (e->u.symbol.name == NULL) { HEIMDAL_MUTEX_unlock(&plugin_mutex); free(e); krb5_set_error_message(context, ENOMEM, "malloc: out of memory"); return ENOMEM; } e->u.symbol.symbol = symbol; e->next = registered; registered = e; HEIMDAL_MUTEX_unlock(&plugin_mutex); return 0; } static krb5_error_code add_symbol(krb5_context context, struct krb5_plugin **list, void *symbol) { struct krb5_plugin *e; e = calloc(1, sizeof(*e)); if (e == NULL) { krb5_set_error_message(context, ENOMEM, "malloc: out of memory"); return ENOMEM; } e->symbol = symbol; e->next = *list; *list = e; return 0; } KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL _krb5_plugin_find(krb5_context context, enum krb5_plugin_type type, const char *name, struct krb5_plugin **list) { struct plugin *e; krb5_error_code ret; *list = NULL; HEIMDAL_MUTEX_lock(&plugin_mutex); for (ret = 0, e = registered; e != NULL; e = e->next) { switch(e->type) { case DSO: { void *sym; if (e->u.dso.dsohandle == NULL) continue; sym = dlsym(e->u.dso.dsohandle, name); if (sym) ret = add_symbol(context, list, sym); break; } case SYMBOL: if (strcmp(e->u.symbol.name, name) == 0 && e->u.symbol.type == type) ret = add_symbol(context, list, e->u.symbol.symbol); break; } if (ret) { _krb5_plugin_free(*list); *list = NULL; } } HEIMDAL_MUTEX_unlock(&plugin_mutex); if (ret) return ret; if (*list == NULL) { krb5_set_error_message(context, ENOENT, "Did not find a plugin for %s", name); return ENOENT; } return 0; } KRB5_LIB_FUNCTION void KRB5_LIB_CALL _krb5_plugin_free(struct krb5_plugin *list) { struct krb5_plugin *next; while (list) { next = list->next; free(list); list = next; } } /* * module - dict of { * ModuleName = [ * plugin = object{ * array = { ptr, ctx } * } * ] * } */ static heim_dict_t modules; struct plugin2 { heim_string_t path; void *dsohandle; heim_dict_t names; }; static void plug_dealloc(void *ptr) { struct plugin2 *p = ptr; heim_release(p->path); heim_release(p->names); if (p->dsohandle) dlclose(p->dsohandle); } static char * resolve_origin(const char *di) { #ifdef HAVE_DLADDR Dl_info dl_info; const char *dname; char *path, *p; #endif if (strncmp(di, "$ORIGIN/", sizeof("$ORIGIN/") - 1) && strcmp(di, "$ORIGIN")) return strdup(di); #ifndef HAVE_DLADDR return strdup(LIBDIR "/plugin/krb5"); #else /* !HAVE_DLADDR */ di += sizeof("$ORIGIN") - 1; if (dladdr(_krb5_load_plugins, &dl_info) == 0) return strdup(LIBDIR "/plugin/krb5"); dname = dl_info.dli_fname; #ifdef _WIN32 p = strrchr(dname, '\\'); if (p == NULL) #endif p = strrchr(dname, '/'); if (p) { if (asprintf(&path, "%.*s%s", (int) (p - dname), dname, di) == -1) return NULL; } else { if (asprintf(&path, "%s%s", dname, di) == -1) return NULL; } return path; #endif /* !HAVE_DLADDR */ } /** * Load plugins (new system) for the given module @name (typically * "krb5") from the given directory @paths. * * Inputs: * * @context A krb5_context * @name Name of plugin module (typically "krb5") * @paths Array of directory paths where to look */ KRB5_LIB_FUNCTION void KRB5_LIB_CALL _krb5_load_plugins(krb5_context context, const char *name, const char **paths) { #ifdef HAVE_DLOPEN heim_string_t s = heim_string_create(name); heim_dict_t module; struct dirent *entry; krb5_error_code ret; const char **di; char *dirname = NULL; DIR *d; #ifdef _WIN32 const char * plugin_prefix; size_t plugin_prefix_len; if (asprintf(&plugin_prefix, "plugin_%s_", name) == -1) return; plugin_prefix_len = (plugin_prefix ? strlen(plugin_prefix) : 0); #endif HEIMDAL_MUTEX_lock(&plugin_mutex); if (modules == NULL) { modules = heim_dict_create(11); if (modules == NULL) { HEIMDAL_MUTEX_unlock(&plugin_mutex); return; } } module = heim_dict_copy_value(modules, s); if (module == NULL) { module = heim_dict_create(11); if (module == NULL) { HEIMDAL_MUTEX_unlock(&plugin_mutex); heim_release(s); return; } heim_dict_set_value(modules, s, module); } heim_release(s); for (di = paths; *di != NULL; di++) { free(dirname); dirname = resolve_origin(*di); if (dirname == NULL) continue; d = opendir(dirname); if (d == NULL) continue; rk_cloexec_dir(d); while ((entry = readdir(d)) != NULL) { char *n = entry->d_name; char *path = NULL; heim_string_t spath; struct plugin2 *p; /* skip . and .. */ if (n[0] == '.' && (n[1] == '\0' || (n[1] == '.' && n[2] == '\0'))) continue; ret = 0; #ifdef _WIN32 /* * On Windows, plugins must be loaded from the same directory as * heimdal.dll (typically the assembly directory) and must have * the name form "plugin__.dll". */ { char *ext; if (strnicmp(n, plugin_prefix, plugin_prefix_len)) continue; ext = strrchr(n, '.'); if (ext == NULL || stricmp(ext, ".dll")) continue; ret = asprintf(&path, "%s\\%s", dirname, n); if (ret < 0 || path == NULL) continue; } #endif #ifdef __APPLE__ { /* support loading bundles on MacOS */ size_t len = strlen(n); if (len > 7 && strcmp(&n[len - 7], ".bundle") == 0) ret = asprintf(&path, "%s/%s/Contents/MacOS/%.*s", dirname, n, (int)(len - 7), n); } #endif if (ret < 0 || path == NULL) ret = asprintf(&path, "%s/%s", dirname, n); if (ret < 0 || path == NULL) continue; spath = heim_string_create(n); if (spath == NULL) { free(path); continue; } /* check if already cached */ p = heim_dict_copy_value(module, spath); if (p == NULL) { p = heim_alloc(sizeof(*p), "krb5-plugin", plug_dealloc); if (p) p->dsohandle = dlopen(path, RTLD_LOCAL|RTLD_LAZY); if (p && p->dsohandle) { p->path = heim_retain(spath); p->names = heim_dict_create(11); heim_dict_set_value(module, spath, p); } } heim_release(p); heim_release(spath); free(path); } closedir(d); } free(dirname); HEIMDAL_MUTEX_unlock(&plugin_mutex); heim_release(module); #ifdef _WIN32 if (plugin_prefix) free(plugin_prefix); #endif #endif /* HAVE_DLOPEN */ } /** * Unload plugins (new system) */ KRB5_LIB_FUNCTION void KRB5_LIB_CALL _krb5_unload_plugins(krb5_context context, const char *name) { HEIMDAL_MUTEX_lock(&plugin_mutex); heim_release(modules); modules = NULL; HEIMDAL_MUTEX_unlock(&plugin_mutex); } /* * */ struct common_plugin_method { int version; krb5_error_code (*init)(krb5_context, void **); void (*fini)(void *); }; struct plug { void *dataptr; void *ctx; }; static void plug_free(void *ptr) { struct plug *pl = ptr; if (pl->dataptr) { struct common_plugin_method *cpm = pl->dataptr; cpm->fini(pl->ctx); } } struct iter_ctx { krb5_context context; heim_string_t n; const char *name; int min_version; int flags; heim_array_t result; krb5_error_code (KRB5_LIB_CALL *func)(krb5_context, const void *, void *, void *); void *userctx; krb5_error_code ret; }; static void search_modules(heim_object_t key, heim_object_t value, void *ctx) { struct iter_ctx *s = ctx; struct plugin2 *p = value; struct plug *pl = heim_dict_copy_value(p->names, s->n); struct common_plugin_method *cpm; if (pl == NULL) { if (p->dsohandle == NULL) return; pl = heim_alloc(sizeof(*pl), "struct-plug", plug_free); cpm = pl->dataptr = dlsym(p->dsohandle, s->name); if (cpm) { int ret; ret = cpm->init(s->context, &pl->ctx); if (ret) cpm = pl->dataptr = NULL; } heim_dict_set_value(p->names, s->n, pl); } else { cpm = pl->dataptr; } if (cpm && cpm->version >= s->min_version) heim_array_append_value(s->result, pl); heim_release(pl); } static void eval_results(heim_object_t value, void *ctx, int *stop) { struct plug *pl = value; struct iter_ctx *s = ctx; if (s->ret != KRB5_PLUGIN_NO_HANDLE) return; s->ret = s->func(s->context, pl->dataptr, pl->ctx, s->userctx); if (s->ret != KRB5_PLUGIN_NO_HANDLE && !(s->flags & KRB5_PLUGIN_INVOKE_ALL)) *stop = 1; } /** * Run plugins for the given @module (e.g., "krb5") and @name (e.g., * "kuserok"). Specifically, the @func is invoked once per-plugin with * four arguments: the @context, the plugin symbol value (a pointer to a * struct whose first three fields are the same as struct common_plugin_method), * a context value produced by the plugin's init method, and @userctx. * * @func should unpack arguments for a plugin function and invoke it * with arguments taken from @userctx. @func should save plugin * outputs, if any, in @userctx. * * All loaded and registered plugins are invoked via @func until @func * returns something other than KRB5_PLUGIN_NO_HANDLE. Plugins that * have nothing to do for the given arguments should return * KRB5_PLUGIN_NO_HANDLE. * * Inputs: * * @context A krb5_context * @module Name of module (typically "krb5") * @name Name of pluggable interface (e.g., "kuserok") * @min_version Lowest acceptable plugin minor version number * @flags Flags (none defined at this time) * @userctx Callback data for the callback function @func * @func A callback function, invoked once per-plugin * * Outputs: None, other than the return value and such outputs as are * gathered by @func. */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL _krb5_plugin_run_f(krb5_context context, const char *module, const char *name, int min_version, int flags, void *userctx, krb5_error_code (KRB5_LIB_CALL *func)(krb5_context, const void *, void *, void *)) { heim_string_t m = heim_string_create(module); heim_dict_t dict; void *plug_ctx; struct common_plugin_method *cpm; struct iter_ctx s; struct krb5_plugin *registered_plugins = NULL; struct krb5_plugin *p; /* Get registered plugins */ (void) _krb5_plugin_find(context, SYMBOL, name, ®istered_plugins); HEIMDAL_MUTEX_lock(&plugin_mutex); s.context = context; s.name = name; s.n = heim_string_create(name); s.flags = flags; s.min_version = min_version; s.result = heim_array_create(); s.func = func; s.userctx = userctx; s.ret = KRB5_PLUGIN_NO_HANDLE; /* Get loaded plugins */ dict = heim_dict_copy_value(modules, m); heim_release(m); /* Add loaded plugins to s.result array */ if (dict) heim_dict_iterate_f(dict, &s, search_modules); /* We don't need to hold plugin_mutex during plugin invocation */ HEIMDAL_MUTEX_unlock(&plugin_mutex); /* Invoke registered plugins (old system) */ for (p = registered_plugins; p; p = p->next) { /* * XXX This is the wrong way to handle registered plugins, as we * call init/fini on each invocation! We do this because we * have nowhere in the struct plugin registered list to store * the context allocated by the plugin's init function. (But at * least we do call init/fini!) * * What we should do is adapt the old plugin system to the new * one and change how we register plugins so that we use the new * struct plug to keep track of their context structures, that * way we can init once, invoke many times, then fini. */ cpm = (struct common_plugin_method *)p->symbol; s.ret = cpm->init(context, &plug_ctx); if (s.ret) continue; s.ret = s.func(s.context, p->symbol, plug_ctx, s.userctx); cpm->fini(plug_ctx); if (s.ret != KRB5_PLUGIN_NO_HANDLE && !(flags & KRB5_PLUGIN_INVOKE_ALL)) break; } _krb5_plugin_free(registered_plugins); /* Invoke loaded plugins (new system) */ if (s.ret == KRB5_PLUGIN_NO_HANDLE) heim_array_iterate_f(s.result, &s, eval_results); heim_release(s.result); heim_release(s.n); heim_release(dict); return s.ret; } heimdal-7.5.0/lib/krb5/version.c0000644000175000017500000000332412136107750014520 0ustar niknik/* * Copyright (c) 1997 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "krb5_locl.h" /* this is just to get a version stamp in the library file */ #include "version.h" heimdal-7.5.0/lib/krb5/free_host_realm.c0000644000175000017500000000415112136107750016170 0ustar niknik/* * Copyright (c) 1997, 1999 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "krb5_locl.h" /** * Free all memory allocated by `realmlist' * * @param context A Kerberos 5 context. * @param realmlist realmlist to free, NULL is ok * * @return a Kerberos error code, always 0. * * @ingroup krb5_support */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_free_host_realm(krb5_context context, krb5_realm *realmlist) { krb5_realm *p; if(realmlist == NULL) return 0; for (p = realmlist; *p; ++p) free (*p); free (realmlist); return 0; } heimdal-7.5.0/lib/krb5/mk_rep.c0000644000175000017500000000757013026237312014314 0ustar niknik/* * Copyright (c) 1997 - 2003 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "krb5_locl.h" KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_mk_rep(krb5_context context, krb5_auth_context auth_context, krb5_data *outbuf) { krb5_error_code ret; AP_REP ap; EncAPRepPart body; u_char *buf = NULL; size_t buf_size; size_t len = 0; krb5_crypto crypto; ap.pvno = 5; ap.msg_type = krb_ap_rep; memset (&body, 0, sizeof(body)); body.ctime = auth_context->authenticator->ctime; body.cusec = auth_context->authenticator->cusec; if (auth_context->flags & KRB5_AUTH_CONTEXT_USE_SUBKEY) { if (auth_context->local_subkey == NULL) { ret = krb5_auth_con_generatelocalsubkey(context, auth_context, auth_context->keyblock); if(ret) { free_EncAPRepPart(&body); return ret; } } ret = krb5_copy_keyblock(context, auth_context->local_subkey, &body.subkey); if (ret) { free_EncAPRepPart(&body); return krb5_enomem(context); } } else body.subkey = NULL; if (auth_context->flags & KRB5_AUTH_CONTEXT_DO_SEQUENCE) { if(auth_context->local_seqnumber == 0) krb5_generate_seq_number (context, auth_context->keyblock, &auth_context->local_seqnumber); ALLOC(body.seq_number, 1); if (body.seq_number == NULL) { free_EncAPRepPart(&body); return krb5_enomem(context); } *(body.seq_number) = auth_context->local_seqnumber; } else body.seq_number = NULL; ap.enc_part.etype = auth_context->keyblock->keytype; ap.enc_part.kvno = NULL; ASN1_MALLOC_ENCODE(EncAPRepPart, buf, buf_size, &body, &len, ret); free_EncAPRepPart (&body); if(ret) return ret; if (buf_size != len) krb5_abortx(context, "internal error in ASN.1 encoder"); ret = krb5_crypto_init(context, auth_context->keyblock, 0 /* ap.enc_part.etype */, &crypto); if (ret) { free (buf); return ret; } ret = krb5_encrypt (context, crypto, KRB5_KU_AP_REQ_ENC_PART, buf + buf_size - len, len, &ap.enc_part.cipher); krb5_crypto_destroy(context, crypto); free(buf); if (ret) return ret; ASN1_MALLOC_ENCODE(AP_REP, outbuf->data, outbuf->length, &ap, &len, ret); if (ret == 0 && outbuf->length != len) krb5_abortx(context, "internal error in ASN.1 encoder"); free_AP_REP (&ap); return ret; } heimdal-7.5.0/lib/krb5/auth_context.c0000644000175000017500000004027413026237312015542 0ustar niknik/* * Copyright (c) 1997 - 2002 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "krb5_locl.h" /** * Allocate and initialize an autentication context. * * @param context A kerberos context. * @param auth_context The authentication context to be initialized. * * Use krb5_auth_con_free() to release the memory when done using the context. * * @return An krb5 error code, see krb5_get_error_message(). */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_auth_con_init(krb5_context context, krb5_auth_context *auth_context) { krb5_auth_context p; ALLOC(p, 1); if (!p) return krb5_enomem(context); memset(p, 0, sizeof(*p)); ALLOC(p->authenticator, 1); if (!p->authenticator) { free(p); return krb5_enomem(context); } memset (p->authenticator, 0, sizeof(*p->authenticator)); p->flags = KRB5_AUTH_CONTEXT_DO_TIME; p->local_address = NULL; p->remote_address = NULL; p->local_port = 0; p->remote_port = 0; p->keytype = KRB5_ENCTYPE_NULL; p->cksumtype = CKSUMTYPE_NONE; p->auth_data = NULL; *auth_context = p; return 0; } /** * Deallocate an authentication context previously initialized with * krb5_auth_con_init(). * * @param context A kerberos context. * @param auth_context The authentication context to be deallocated. * * @return An krb5 error code, see krb5_get_error_message(). */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_auth_con_free(krb5_context context, krb5_auth_context auth_context) { if (auth_context != NULL) { krb5_free_authenticator(context, &auth_context->authenticator); if(auth_context->local_address){ free_HostAddress(auth_context->local_address); free(auth_context->local_address); } if(auth_context->remote_address){ free_HostAddress(auth_context->remote_address); free(auth_context->remote_address); } krb5_free_keyblock(context, auth_context->keyblock); krb5_free_keyblock(context, auth_context->remote_subkey); krb5_free_keyblock(context, auth_context->local_subkey); if (auth_context->auth_data) { free_AuthorizationData(auth_context->auth_data); free(auth_context->auth_data); } free (auth_context); } return 0; } KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_auth_con_setflags(krb5_context context, krb5_auth_context auth_context, int32_t flags) { auth_context->flags = flags; return 0; } KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_auth_con_getflags(krb5_context context, krb5_auth_context auth_context, int32_t *flags) { *flags = auth_context->flags; return 0; } KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_auth_con_addflags(krb5_context context, krb5_auth_context auth_context, int32_t addflags, int32_t *flags) { if (flags) *flags = auth_context->flags; auth_context->flags |= addflags; return 0; } KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_auth_con_removeflags(krb5_context context, krb5_auth_context auth_context, int32_t removeflags, int32_t *flags) { if (flags) *flags = auth_context->flags; auth_context->flags &= ~removeflags; return 0; } KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_auth_con_setaddrs(krb5_context context, krb5_auth_context auth_context, krb5_address *local_addr, krb5_address *remote_addr) { if (local_addr) { if (auth_context->local_address) krb5_free_address (context, auth_context->local_address); else if ((auth_context->local_address = malloc(sizeof(krb5_address))) == NULL) return krb5_enomem(context); krb5_copy_address(context, local_addr, auth_context->local_address); } if (remote_addr) { if (auth_context->remote_address) krb5_free_address (context, auth_context->remote_address); else if ((auth_context->remote_address = malloc(sizeof(krb5_address))) == NULL) return krb5_enomem(context); krb5_copy_address(context, remote_addr, auth_context->remote_address); } return 0; } /** * Update the authentication context \a auth_context with the local * and remote addresses from socket \a fd, according to \a flags. * * @return An krb5 error code, see krb5_get_error_message(). */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_auth_con_genaddrs(krb5_context context, krb5_auth_context auth_context, krb5_socket_t fd, int flags) { krb5_error_code ret; krb5_address local_k_address, remote_k_address; krb5_address *lptr = NULL, *rptr = NULL; struct sockaddr_storage ss_local, ss_remote; struct sockaddr *local = (struct sockaddr *)&ss_local; struct sockaddr *remote = (struct sockaddr *)&ss_remote; socklen_t len; if(flags & KRB5_AUTH_CONTEXT_GENERATE_LOCAL_ADDR) { if (auth_context->local_address == NULL) { len = sizeof(ss_local); if(rk_IS_SOCKET_ERROR(getsockname(fd, local, &len))) { char buf[128]; ret = rk_SOCK_ERRNO; rk_strerror_r(ret, buf, sizeof(buf)); krb5_set_error_message(context, ret, "getsockname: %s", buf); goto out; } ret = krb5_sockaddr2address (context, local, &local_k_address); if(ret) goto out; if(flags & KRB5_AUTH_CONTEXT_GENERATE_LOCAL_FULL_ADDR) { krb5_sockaddr2port (context, local, &auth_context->local_port); } else auth_context->local_port = 0; lptr = &local_k_address; } } if(flags & KRB5_AUTH_CONTEXT_GENERATE_REMOTE_ADDR) { len = sizeof(ss_remote); if(rk_IS_SOCKET_ERROR(getpeername(fd, remote, &len))) { char buf[128]; ret = rk_SOCK_ERRNO; rk_strerror_r(ret, buf, sizeof(buf)); krb5_set_error_message(context, ret, "getpeername: %s", buf); goto out; } ret = krb5_sockaddr2address (context, remote, &remote_k_address); if(ret) goto out; if(flags & KRB5_AUTH_CONTEXT_GENERATE_REMOTE_FULL_ADDR) { krb5_sockaddr2port (context, remote, &auth_context->remote_port); } else auth_context->remote_port = 0; rptr = &remote_k_address; } ret = krb5_auth_con_setaddrs (context, auth_context, lptr, rptr); out: if (lptr) krb5_free_address (context, lptr); if (rptr) krb5_free_address (context, rptr); return ret; } KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_auth_con_setaddrs_from_fd (krb5_context context, krb5_auth_context auth_context, void *p_fd) { krb5_socket_t fd = *(krb5_socket_t *)p_fd; int flags = 0; if(auth_context->local_address == NULL) flags |= KRB5_AUTH_CONTEXT_GENERATE_LOCAL_FULL_ADDR; if(auth_context->remote_address == NULL) flags |= KRB5_AUTH_CONTEXT_GENERATE_REMOTE_FULL_ADDR; return krb5_auth_con_genaddrs(context, auth_context, fd, flags); } KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_auth_con_getaddrs(krb5_context context, krb5_auth_context auth_context, krb5_address **local_addr, krb5_address **remote_addr) { if(*local_addr) krb5_free_address (context, *local_addr); *local_addr = malloc (sizeof(**local_addr)); if (*local_addr == NULL) return krb5_enomem(context); krb5_copy_address(context, auth_context->local_address, *local_addr); if(*remote_addr) krb5_free_address (context, *remote_addr); *remote_addr = malloc (sizeof(**remote_addr)); if (*remote_addr == NULL) { krb5_free_address (context, *local_addr); *local_addr = NULL; return krb5_enomem(context); } krb5_copy_address(context, auth_context->remote_address, *remote_addr); return 0; } /* coverity[+alloc : arg-*2] */ static krb5_error_code copy_key(krb5_context context, krb5_keyblock *in, krb5_keyblock **out) { *out = NULL; if (in) return krb5_copy_keyblock(context, in, out); return 0; } KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_auth_con_getkey(krb5_context context, krb5_auth_context auth_context, krb5_keyblock **keyblock) { return copy_key(context, auth_context->keyblock, keyblock); } KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_auth_con_getlocalsubkey(krb5_context context, krb5_auth_context auth_context, krb5_keyblock **keyblock) { return copy_key(context, auth_context->local_subkey, keyblock); } /* coverity[+alloc : arg-*2] */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_auth_con_getremotesubkey(krb5_context context, krb5_auth_context auth_context, krb5_keyblock **keyblock) { return copy_key(context, auth_context->remote_subkey, keyblock); } KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_auth_con_setkey(krb5_context context, krb5_auth_context auth_context, krb5_keyblock *keyblock) { if(auth_context->keyblock) krb5_free_keyblock(context, auth_context->keyblock); return copy_key(context, keyblock, &auth_context->keyblock); } KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_auth_con_setlocalsubkey(krb5_context context, krb5_auth_context auth_context, krb5_keyblock *keyblock) { if(auth_context->local_subkey) krb5_free_keyblock(context, auth_context->local_subkey); return copy_key(context, keyblock, &auth_context->local_subkey); } KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_auth_con_generatelocalsubkey(krb5_context context, krb5_auth_context auth_context, krb5_keyblock *key) { krb5_error_code ret; krb5_keyblock *subkey; ret = krb5_generate_subkey_extended (context, key, auth_context->keytype, &subkey); if(ret) return ret; if(auth_context->local_subkey) krb5_free_keyblock(context, auth_context->local_subkey); auth_context->local_subkey = subkey; return 0; } KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_auth_con_setremotesubkey(krb5_context context, krb5_auth_context auth_context, krb5_keyblock *keyblock) { if(auth_context->remote_subkey) krb5_free_keyblock(context, auth_context->remote_subkey); return copy_key(context, keyblock, &auth_context->remote_subkey); } KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_auth_con_setcksumtype(krb5_context context, krb5_auth_context auth_context, krb5_cksumtype cksumtype) { auth_context->cksumtype = cksumtype; return 0; } KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_auth_con_getcksumtype(krb5_context context, krb5_auth_context auth_context, krb5_cksumtype *cksumtype) { *cksumtype = auth_context->cksumtype; return 0; } KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_auth_con_setkeytype (krb5_context context, krb5_auth_context auth_context, krb5_keytype keytype) { auth_context->keytype = keytype; return 0; } KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_auth_con_getkeytype (krb5_context context, krb5_auth_context auth_context, krb5_keytype *keytype) { *keytype = auth_context->keytype; return 0; } KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_auth_con_add_AuthorizationData(krb5_context context, krb5_auth_context auth_context, int type, krb5_data *data) { AuthorizationDataElement el; if (auth_context->auth_data == NULL) { auth_context->auth_data = calloc(1, sizeof(*auth_context->auth_data)); if (auth_context->auth_data == NULL) return krb5_enomem(context); } el.ad_type = type; el.ad_data.data = data->data; el.ad_data.length = data->length; return add_AuthorizationData(auth_context->auth_data, &el); } #if 0 KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_auth_con_setenctype(krb5_context context, krb5_auth_context auth_context, krb5_enctype etype) { if(auth_context->keyblock) krb5_free_keyblock(context, auth_context->keyblock); ALLOC(auth_context->keyblock, 1); if(auth_context->keyblock == NULL) return krb5_enomem(context); auth_context->keyblock->keytype = etype; return 0; } KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_auth_con_getenctype(krb5_context context, krb5_auth_context auth_context, krb5_enctype *etype) { krb5_abortx(context, "unimplemented krb5_auth_getenctype called"); } #endif KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_auth_con_getlocalseqnumber(krb5_context context, krb5_auth_context auth_context, int32_t *seqnumber) { *seqnumber = auth_context->local_seqnumber; return 0; } KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_auth_con_setlocalseqnumber (krb5_context context, krb5_auth_context auth_context, int32_t seqnumber) { auth_context->local_seqnumber = seqnumber; return 0; } KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_auth_con_getremoteseqnumber(krb5_context context, krb5_auth_context auth_context, int32_t *seqnumber) { *seqnumber = auth_context->remote_seqnumber; return 0; } KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_auth_con_setremoteseqnumber (krb5_context context, krb5_auth_context auth_context, int32_t seqnumber) { auth_context->remote_seqnumber = seqnumber; return 0; } KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_auth_con_getauthenticator(krb5_context context, krb5_auth_context auth_context, krb5_authenticator *authenticator) { *authenticator = malloc(sizeof(**authenticator)); if (*authenticator == NULL) return krb5_enomem(context); copy_Authenticator(auth_context->authenticator, *authenticator); return 0; } KRB5_LIB_FUNCTION void KRB5_LIB_CALL krb5_free_authenticator(krb5_context context, krb5_authenticator *authenticator) { free_Authenticator (*authenticator); free (*authenticator); *authenticator = NULL; } KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_auth_con_setuserkey(krb5_context context, krb5_auth_context auth_context, krb5_keyblock *keyblock) { if(auth_context->keyblock) krb5_free_keyblock(context, auth_context->keyblock); return krb5_copy_keyblock(context, keyblock, &auth_context->keyblock); } KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_auth_con_getrcache(krb5_context context, krb5_auth_context auth_context, krb5_rcache *rcache) { *rcache = auth_context->rcache; return 0; } KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_auth_con_setrcache(krb5_context context, krb5_auth_context auth_context, krb5_rcache rcache) { auth_context->rcache = rcache; return 0; } #if 0 /* not implemented */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_auth_con_initivector(krb5_context context, krb5_auth_context auth_context) { krb5_abortx(context, "unimplemented krb5_auth_con_initivector called"); } KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_auth_con_setivector(krb5_context context, krb5_auth_context auth_context, krb5_pointer ivector) { krb5_abortx(context, "unimplemented krb5_auth_con_setivector called"); } #endif /* not implemented */ heimdal-7.5.0/lib/krb5/krb5-protos.h0000644000175000017500000072607413212445576015254 0ustar niknik/* This is a generated file */ #ifndef __krb5_protos_h__ #define __krb5_protos_h__ #ifndef DOXY #include #if !defined(__GNUC__) && !defined(__attribute__) #define __attribute__(x) #endif #ifndef KRB5_DEPRECATED_FUNCTION #ifndef __has_extension #define __has_extension(x) 0 #define KRB5_DEPRECATED_FUNCTIONhas_extension 1 #endif #if __has_extension(attribute_deprecated_with_message) #define KRB5_DEPRECATED_FUNCTION(x) __attribute__((__deprecated__(x))) #elif defined(__GNUC__) && ((__GNUC__ > 3) || ((__GNUC__ == 3) && (__GNUC_MINOR__ >= 1 ))) #define KRB5_DEPRECATED_FUNCTION(X) __attribute__((__deprecated__)) #else #define KRB5_DEPRECATED_FUNCTION(X) #endif #ifdef KRB5_DEPRECATED_FUNCTIONhas_extension #undef __has_extension #undef KRB5_DEPRECATED_FUNCTIONhas_extension #endif #endif /* KRB5_DEPRECATED_FUNCTION */ #ifdef __cplusplus extern "C" { #endif #ifndef KRB5_LIB #ifndef KRB5_LIB_FUNCTION #if defined(_WIN32) #define KRB5_LIB_FUNCTION __declspec(dllimport) #define KRB5_LIB_CALL __stdcall #define KRB5_LIB_VARIABLE __declspec(dllimport) #else #define KRB5_LIB_FUNCTION #define KRB5_LIB_CALL #define KRB5_LIB_VARIABLE #endif #endif #endif /** * Convert the v5 credentials in in_cred to v4-dito in v4creds. This * is done by sending them to the 524 function in the KDC. If * `in_cred' doesn't contain a DES session key, then a new one is * gotten from the KDC and stored in the cred cache `ccache'. * * @param context Kerberos 5 context. * @param in_cred the credential to convert * @param v4creds the converted credential * * @return Returns 0 to indicate success. Otherwise an kerberos et * error code is returned, see krb5_get_error_message(). * * @ingroup krb5_v4compat */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb524_convert_creds_kdc ( krb5_context /*context*/, krb5_creds */*in_cred*/, struct credentials */*v4creds*/) KRB5_DEPRECATED_FUNCTION("Use X instead"); /** * Convert the v5 credentials in in_cred to v4-dito in v4creds, * check the credential cache ccache before checking with the KDC. * * @param context Kerberos 5 context. * @param ccache credential cache used to check for des-ticket. * @param in_cred the credential to convert * @param v4creds the converted credential * * @return Returns 0 to indicate success. Otherwise an kerberos et * error code is returned, see krb5_get_error_message(). * * @ingroup krb5_v4compat */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb524_convert_creds_kdc_ccache ( krb5_context /*context*/, krb5_ccache /*ccache*/, krb5_creds */*in_cred*/, struct credentials */*v4creds*/) KRB5_DEPRECATED_FUNCTION("Use X instead"); /** * Log a warning to the log, default stderr, include the error from * the last failure and then abort. * * @param context A Kerberos 5 context * @param code error code of the last error * @param fmt message to print * @param ... arguments for format string * * @ingroup krb5_error */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_abort ( krb5_context /*context*/, krb5_error_code /*code*/, const char */*fmt*/, ...) __attribute__ ((__noreturn__, __format__ (__printf__, 3, 4))); /** * Log a warning to the log, default stderr, and then abort. * * @param context A Kerberos 5 context * @param fmt printf format string of message to print * @param ... arguments for format string * * @ingroup krb5_error */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_abortx ( krb5_context /*context*/, const char */*fmt*/, ...) __attribute__ ((__noreturn__, __format__ (__printf__, 2, 3))); /** * krb5_acl_match_file matches ACL format against each line in a file * using krb5_acl_match_string(). Lines starting with # are treated * like comments and ignored. * * @param context Kerberos 5 context. * @param file file with acl listed in the file. * @param format format to match. * @param ... parameter to format string. * * @return Return an error code or 0. * * @sa krb5_acl_match_string * @ingroup krb5_support */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_acl_match_file ( krb5_context /*context*/, const char */*file*/, const char */*format*/, ...); /** * krb5_acl_match_string matches ACL format against a string. * * The ACL format has three format specifiers: s, f, and r. Each * specifier will retrieve one argument from the variable arguments * for either matching or storing data. The input string is split up * using " " (space) and "\t" (tab) as a delimiter; multiple and "\t" * in a row are considered to be the same. * * List of format specifiers: * - s Matches a string using strcmp(3) (case sensitive). * - f Matches the string with fnmatch(3). Theflags * argument (the last argument) passed to the fnmatch function is 0. * - r Returns a copy of the string in the char ** passed in; the copy * must be freed with free(3). There is no need to free(3) the * string on error: the function will clean up and set the pointer * to NULL. * * @param context Kerberos 5 context * @param string string to match with * @param format format to match * @param ... parameter to format string * * @return Return an error code or 0. * * * @code * char *s; * * ret = krb5_acl_match_string(context, "foo", "s", "foo"); * if (ret) * krb5_errx(context, 1, "acl didn't match"); * ret = krb5_acl_match_string(context, "foo foo baz/kaka", * "ss", "foo", &s, "foo/\\*"); * if (ret) { * // no need to free(s) on error * assert(s == NULL); * krb5_errx(context, 1, "acl didn't match"); * } * free(s); * @endcode * * @sa krb5_acl_match_file * @ingroup krb5_support */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_acl_match_string ( krb5_context /*context*/, const char */*string*/, const char */*format*/, ...); /** * Add a specified list of error messages to the et list in context. * Call func (probably a comerr-generated function) with a pointer to * the current et_list. * * @param context A kerberos context. * @param func The generated com_err et function. * * @return Returns 0 to indicate success. Otherwise an kerberos et * error code is returned, see krb5_get_error_message(). * * @ingroup krb5 */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_add_et_list ( krb5_context /*context*/, void (*/*func*/)(struct et_list **)); /** * Add extra address to the address list that the library will add to * the client's address list when communicating with the KDC. * * @param context Kerberos 5 context. * @param addresses addreses to add * * @return Returns 0 to indicate success. Otherwise an kerberos et * error code is returned, see krb5_get_error_message(). * * @ingroup krb5 */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_add_extra_addresses ( krb5_context /*context*/, krb5_addresses */*addresses*/); /** * Add extra addresses to ignore when fetching addresses from the * underlaying operating system. * * @param context Kerberos 5 context. * @param addresses addreses to ignore * * @return Returns 0 to indicate success. Otherwise an kerberos et * error code is returned, see krb5_get_error_message(). * * @ingroup krb5 */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_add_ignore_addresses ( krb5_context /*context*/, krb5_addresses */*addresses*/); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_addlog_dest ( krb5_context /*context*/, krb5_log_facility */*f*/, const char */*orig*/); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_addlog_func ( krb5_context /*context*/, krb5_log_facility */*fac*/, int /*min*/, int /*max*/, krb5_log_log_func_t /*log_func*/, krb5_log_close_func_t /*close_func*/, void */*data*/); /** * krb5_addr2sockaddr sets the "struct sockaddr sockaddr" from addr * and port. The argument sa_size should initially contain the size of * the sa and after the call, it will contain the actual length of the * address. In case of the sa is too small to fit the whole address, * the up to *sa_size will be stored, and then *sa_size will be set to * the required length. * * @param context a Keberos context * @param addr the address to copy the from * @param sa the struct sockaddr that will be filled in * @param sa_size pointer to length of sa, and after the call, it will * contain the actual length of the address. * @param port set port in sa. * * @return Return an error code or 0. Will return * KRB5_PROG_ATYPE_NOSUPP in case address type is not supported. * * @ingroup krb5_address */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_addr2sockaddr ( krb5_context /*context*/, const krb5_address */*addr*/, struct sockaddr */*sa*/, krb5_socklen_t */*sa_size*/, int /*port*/); /** * krb5_address_compare compares the addresses addr1 and addr2. * Returns TRUE if the two addresses are the same. * * @param context a Keberos context * @param addr1 address to compare * @param addr2 address to compare * * @return Return an TRUE is the address are the same FALSE if not * * @ingroup krb5_address */ KRB5_LIB_FUNCTION krb5_boolean KRB5_LIB_CALL krb5_address_compare ( krb5_context /*context*/, const krb5_address */*addr1*/, const krb5_address */*addr2*/); /** * krb5_address_order compares the addresses addr1 and addr2 so that * it can be used for sorting addresses. If the addresses are the same * address krb5_address_order will return 0. Behavies like memcmp(2). * * @param context a Keberos context * @param addr1 krb5_address to compare * @param addr2 krb5_address to compare * * @return < 0 if address addr1 in "less" then addr2. 0 if addr1 and * addr2 is the same address, > 0 if addr2 is "less" then addr1. * * @ingroup krb5_address */ KRB5_LIB_FUNCTION int KRB5_LIB_CALL krb5_address_order ( krb5_context /*context*/, const krb5_address */*addr1*/, const krb5_address */*addr2*/); /** * Calculate the boundary addresses of `inaddr'/`prefixlen' and store * them in `low' and `high'. * * @param context a Keberos context * @param inaddr address in prefixlen that the bondery searched * @param prefixlen width of boundery * @param low lowest address * @param high highest address * * @return Return an error code or 0. * * @ingroup krb5_address */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_address_prefixlen_boundary ( krb5_context /*context*/, const krb5_address */*inaddr*/, unsigned long /*prefixlen*/, krb5_address */*low*/, krb5_address */*high*/); /** * krb5_address_search checks if the address addr is a member of the * address set list addrlist . * * @param context a Keberos context. * @param addr address to search for. * @param addrlist list of addresses to look in for addr. * * @return Return an error code or 0. * * @ingroup krb5_address */ KRB5_LIB_FUNCTION krb5_boolean KRB5_LIB_CALL krb5_address_search ( krb5_context /*context*/, const krb5_address */*addr*/, const krb5_addresses */*addrlist*/); /** * Enable or disable all weak encryption types * * @param context Kerberos 5 context * @param enable true to enable, false to disable * * @return Return an error code or 0. * * @ingroup krb5_crypto */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_allow_weak_crypto ( krb5_context /*context*/, krb5_boolean /*enable*/); /** * Map a principal name to a local username. * * Returns 0 on success, KRB5_NO_LOCALNAME if no mapping was found, or * some Kerberos or system error. * * Inputs: * * @param context A krb5_context * @param aname A principal name * @param lnsize The size of the buffer into which the username will be written * @param lname The buffer into which the username will be written * * @ingroup krb5_support */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_aname_to_localname ( krb5_context /*context*/, krb5_const_principal /*aname*/, size_t /*lnsize*/, char */*lname*/); /** * krb5_anyaddr fills in a "struct sockaddr sa" that can be used to * bind(2) to. The argument sa_size should initially contain the size * of the sa, and after the call, it will contain the actual length * of the address. * * @param context a Keberos context * @param af address family * @param sa sockaddr * @param sa_size lenght of sa. * @param port for to fill into sa. * * @return Return an error code or 0. * * @ingroup krb5_address */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_anyaddr ( krb5_context /*context*/, int /*af*/, struct sockaddr */*sa*/, krb5_socklen_t */*sa_size*/, int /*port*/); KRB5_LIB_FUNCTION void KRB5_LIB_CALL krb5_appdefault_boolean ( krb5_context /*context*/, const char */*appname*/, krb5_const_realm /*realm*/, const char */*option*/, krb5_boolean /*def_val*/, krb5_boolean */*ret_val*/); KRB5_LIB_FUNCTION void KRB5_LIB_CALL krb5_appdefault_string ( krb5_context /*context*/, const char */*appname*/, krb5_const_realm /*realm*/, const char */*option*/, const char */*def_val*/, char **/*ret_val*/); KRB5_LIB_FUNCTION void KRB5_LIB_CALL krb5_appdefault_time ( krb5_context /*context*/, const char */*appname*/, krb5_const_realm /*realm*/, const char */*option*/, time_t /*def_val*/, time_t */*ret_val*/); /** * krb5_append_addresses adds the set of addresses in source to * dest. While copying the addresses, duplicates are also sorted out. * * @param context a Keberos context * @param dest destination of copy operation * @param source adresses that are going to be added to dest * * @return Return an error code or 0. * * @ingroup krb5_address */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_append_addresses ( krb5_context /*context*/, krb5_addresses */*dest*/, const krb5_addresses */*source*/); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_auth_con_add_AuthorizationData ( krb5_context /*context*/, krb5_auth_context /*auth_context*/, int /*type*/, krb5_data */*data*/); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_auth_con_addflags ( krb5_context /*context*/, krb5_auth_context /*auth_context*/, int32_t /*addflags*/, int32_t */*flags*/); /** * Deallocate an authentication context previously initialized with * krb5_auth_con_init(). * * @param context A kerberos context. * @param auth_context The authentication context to be deallocated. * * @return An krb5 error code, see krb5_get_error_message(). */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_auth_con_free ( krb5_context /*context*/, krb5_auth_context /*auth_context*/); /** * Update the authentication context \a auth_context with the local * and remote addresses from socket \a fd, according to \a flags. * * @return An krb5 error code, see krb5_get_error_message(). */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_auth_con_genaddrs ( krb5_context /*context*/, krb5_auth_context /*auth_context*/, krb5_socket_t /*fd*/, int /*flags*/); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_auth_con_generatelocalsubkey ( krb5_context /*context*/, krb5_auth_context /*auth_context*/, krb5_keyblock */*key*/); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_auth_con_getaddrs ( krb5_context /*context*/, krb5_auth_context /*auth_context*/, krb5_address **/*local_addr*/, krb5_address **/*remote_addr*/); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_auth_con_getauthenticator ( krb5_context /*context*/, krb5_auth_context /*auth_context*/, krb5_authenticator */*authenticator*/); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_auth_con_getcksumtype ( krb5_context /*context*/, krb5_auth_context /*auth_context*/, krb5_cksumtype */*cksumtype*/); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_auth_con_getflags ( krb5_context /*context*/, krb5_auth_context /*auth_context*/, int32_t */*flags*/); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_auth_con_getkey ( krb5_context /*context*/, krb5_auth_context /*auth_context*/, krb5_keyblock **/*keyblock*/); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_auth_con_getkeytype ( krb5_context /*context*/, krb5_auth_context /*auth_context*/, krb5_keytype */*keytype*/); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_auth_con_getlocalseqnumber ( krb5_context /*context*/, krb5_auth_context /*auth_context*/, int32_t */*seqnumber*/); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_auth_con_getlocalsubkey ( krb5_context /*context*/, krb5_auth_context /*auth_context*/, krb5_keyblock **/*keyblock*/); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_auth_con_getrcache ( krb5_context /*context*/, krb5_auth_context /*auth_context*/, krb5_rcache */*rcache*/); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_auth_con_getrecvsubkey ( krb5_context /*context*/, krb5_auth_context /*auth_context*/, krb5_keyblock **/*keyblock*/); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_auth_con_getremoteseqnumber ( krb5_context /*context*/, krb5_auth_context /*auth_context*/, int32_t */*seqnumber*/); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_auth_con_getremotesubkey ( krb5_context /*context*/, krb5_auth_context /*auth_context*/, krb5_keyblock **/*keyblock*/); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_auth_con_getsendsubkey ( krb5_context /*context*/, krb5_auth_context /*auth_context*/, krb5_keyblock **/*keyblock*/); /** * Allocate and initialize an autentication context. * * @param context A kerberos context. * @param auth_context The authentication context to be initialized. * * Use krb5_auth_con_free() to release the memory when done using the context. * * @return An krb5 error code, see krb5_get_error_message(). */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_auth_con_init ( krb5_context /*context*/, krb5_auth_context */*auth_context*/); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_auth_con_removeflags ( krb5_context /*context*/, krb5_auth_context /*auth_context*/, int32_t /*removeflags*/, int32_t */*flags*/); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_auth_con_setaddrs ( krb5_context /*context*/, krb5_auth_context /*auth_context*/, krb5_address */*local_addr*/, krb5_address */*remote_addr*/); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_auth_con_setaddrs_from_fd ( krb5_context /*context*/, krb5_auth_context /*auth_context*/, void */*p_fd*/); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_auth_con_setcksumtype ( krb5_context /*context*/, krb5_auth_context /*auth_context*/, krb5_cksumtype /*cksumtype*/); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_auth_con_setflags ( krb5_context /*context*/, krb5_auth_context /*auth_context*/, int32_t /*flags*/); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_auth_con_setkey ( krb5_context /*context*/, krb5_auth_context /*auth_context*/, krb5_keyblock */*keyblock*/); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_auth_con_setkeytype ( krb5_context /*context*/, krb5_auth_context /*auth_context*/, krb5_keytype /*keytype*/); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_auth_con_setlocalseqnumber ( krb5_context /*context*/, krb5_auth_context /*auth_context*/, int32_t /*seqnumber*/); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_auth_con_setlocalsubkey ( krb5_context /*context*/, krb5_auth_context /*auth_context*/, krb5_keyblock */*keyblock*/); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_auth_con_setrcache ( krb5_context /*context*/, krb5_auth_context /*auth_context*/, krb5_rcache /*rcache*/); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_auth_con_setrecvsubkey ( krb5_context /*context*/, krb5_auth_context /*auth_context*/, krb5_keyblock */*keyblock*/); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_auth_con_setremoteseqnumber ( krb5_context /*context*/, krb5_auth_context /*auth_context*/, int32_t /*seqnumber*/); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_auth_con_setremotesubkey ( krb5_context /*context*/, krb5_auth_context /*auth_context*/, krb5_keyblock */*keyblock*/); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_auth_con_setsendsubkey ( krb5_context /*context*/, krb5_auth_context /*auth_context*/, krb5_keyblock */*keyblock*/); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_auth_con_setuserkey ( krb5_context /*context*/, krb5_auth_context /*auth_context*/, krb5_keyblock */*keyblock*/); /** * Deprecated: use krb5_auth_con_getremoteseqnumber() * * @ingroup krb5_deprecated */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_auth_getremoteseqnumber ( krb5_context /*context*/, krb5_auth_context /*auth_context*/, int32_t */*seqnumber*/) KRB5_DEPRECATED_FUNCTION("Use X instead"); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_build_ap_req ( krb5_context /*context*/, krb5_enctype /*enctype*/, krb5_creds */*cred*/, krb5_flags /*ap_options*/, krb5_data /*authenticator*/, krb5_data */*retdata*/); /** * Build a principal using vararg style building * * @param context A Kerberos context. * @param principal returned principal * @param rlen length of realm * @param realm realm name * @param ... a list of components ended with NULL. * * @return An krb5 error code, see krb5_get_error_message(). * * @ingroup krb5_principal */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_build_principal ( krb5_context /*context*/, krb5_principal */*principal*/, int /*rlen*/, krb5_const_realm /*realm*/, ...); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_build_principal_ext ( krb5_context /*context*/, krb5_principal */*principal*/, int /*rlen*/, krb5_const_realm /*realm*/, ...); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_build_principal_va ( krb5_context /*context*/, krb5_principal */*principal*/, int /*rlen*/, krb5_const_realm /*realm*/, va_list /*ap*/); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_build_principal_va_ext ( krb5_context /*context*/, krb5_principal */*principal*/, int /*rlen*/, krb5_const_realm /*realm*/, va_list /*ap*/); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_c_block_size ( krb5_context /*context*/, krb5_enctype /*enctype*/, size_t */*blocksize*/); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_c_checksum_length ( krb5_context /*context*/, krb5_cksumtype /*cksumtype*/, size_t */*length*/); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_c_decrypt ( krb5_context /*context*/, const krb5_keyblock /*key*/, krb5_keyusage /*usage*/, const krb5_data */*ivec*/, krb5_enc_data */*input*/, krb5_data */*output*/); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_c_encrypt ( krb5_context /*context*/, const krb5_keyblock */*key*/, krb5_keyusage /*usage*/, const krb5_data */*ivec*/, const krb5_data */*input*/, krb5_enc_data */*output*/); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_c_encrypt_length ( krb5_context /*context*/, krb5_enctype /*enctype*/, size_t /*inputlen*/, size_t */*length*/); /** * Deprecated: keytypes doesn't exists, they are really enctypes. * * @ingroup krb5_deprecated */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_c_enctype_compare ( krb5_context /*context*/, krb5_enctype /*e1*/, krb5_enctype /*e2*/, krb5_boolean */*similar*/) KRB5_DEPRECATED_FUNCTION("Use X instead"); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_c_get_checksum ( krb5_context /*context*/, const krb5_checksum */*cksum*/, krb5_cksumtype */*type*/, krb5_data **/*data*/); KRB5_LIB_FUNCTION krb5_boolean KRB5_LIB_CALL krb5_c_is_coll_proof_cksum (krb5_cksumtype /*ctype*/); KRB5_LIB_FUNCTION krb5_boolean KRB5_LIB_CALL krb5_c_is_keyed_cksum (krb5_cksumtype /*ctype*/); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_c_keylengths ( krb5_context /*context*/, krb5_enctype /*enctype*/, size_t */*ilen*/, size_t */*keylen*/); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_c_make_checksum ( krb5_context /*context*/, krb5_cksumtype /*cksumtype*/, const krb5_keyblock */*key*/, krb5_keyusage /*usage*/, const krb5_data */*input*/, krb5_checksum */*cksum*/); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_c_make_random_key ( krb5_context /*context*/, krb5_enctype /*enctype*/, krb5_keyblock */*random_key*/); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_c_prf ( krb5_context /*context*/, const krb5_keyblock */*key*/, const krb5_data */*input*/, krb5_data */*output*/); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_c_prf_length ( krb5_context /*context*/, krb5_enctype /*type*/, size_t */*length*/); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_c_random_make_octets ( krb5_context /*context*/, krb5_data * /*data*/); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_c_set_checksum ( krb5_context /*context*/, krb5_checksum */*cksum*/, krb5_cksumtype /*type*/, const krb5_data */*data*/); KRB5_LIB_FUNCTION krb5_boolean KRB5_LIB_CALL krb5_c_valid_cksumtype (krb5_cksumtype /*ctype*/); KRB5_LIB_FUNCTION krb5_boolean KRB5_LIB_CALL krb5_c_valid_enctype (krb5_enctype /*etype*/); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_c_verify_checksum ( krb5_context /*context*/, const krb5_keyblock */*key*/, krb5_keyusage /*usage*/, const krb5_data */*data*/, const krb5_checksum */*cksum*/, krb5_boolean */*valid*/); /** * Destroy the cursor `cursor'. * * @return Return an error code or 0, see krb5_get_error_message(). * * @ingroup krb5_ccache */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_cc_cache_end_seq_get ( krb5_context /*context*/, krb5_cc_cache_cursor /*cursor*/); /** * Start iterating over all caches of specified type. See also * krb5_cccol_cursor_new(). * @param context A Kerberos 5 context * @param type optional type to iterate over, if NULL, the default cache is used. * @param cursor cursor should be freed with krb5_cc_cache_end_seq_get(). * * @return Return an error code or 0, see krb5_get_error_message(). * * @ingroup krb5_ccache */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_cc_cache_get_first ( krb5_context /*context*/, const char */*type*/, krb5_cc_cache_cursor */*cursor*/); /** * Search for a matching credential cache that have the * `principal' as the default principal. On success, `id' needs to be * freed with krb5_cc_close() or krb5_cc_destroy(). * * @param context A Kerberos 5 context * @param client The principal to search for * @param id the returned credential cache * * @return On failure, error code is returned and `id' is set to NULL. * * @ingroup krb5_ccache */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_cc_cache_match ( krb5_context /*context*/, krb5_principal /*client*/, krb5_ccache */*id*/); /** * Retrieve the next cache pointed to by (`cursor') in `id' * and advance `cursor'. * * @param context A Kerberos 5 context * @param cursor the iterator cursor, returned by krb5_cc_cache_get_first() * @param id next ccache * * @return Return 0 or an error code. Returns KRB5_CC_END when the end * of caches is reached, see krb5_get_error_message(). * * @ingroup krb5_ccache */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_cc_cache_next ( krb5_context /*context*/, krb5_cc_cache_cursor /*cursor*/, krb5_ccache */*id*/); /** * Clear `mcreds' so it can be used with krb5_cc_retrieve_cred * * @ingroup krb5_ccache */ KRB5_LIB_FUNCTION void KRB5_LIB_CALL krb5_cc_clear_mcred (krb5_creds */*mcred*/); /** * Stop using the ccache `id' and free the related resources. * * @return Return an error code or 0, see krb5_get_error_message(). * * @ingroup krb5_ccache */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_cc_close ( krb5_context /*context*/, krb5_ccache /*id*/); /** * Just like krb5_cc_copy_match_f(), but copy everything. * * @ingroup @krb5_ccache */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_cc_copy_cache ( krb5_context /*context*/, const krb5_ccache /*from*/, krb5_ccache /*to*/); /** * MIT compat glue * * @ingroup krb5_ccache */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_cc_copy_creds ( krb5_context /*context*/, const krb5_ccache /*from*/, krb5_ccache /*to*/); /** * Copy the contents of `from' to `to' if the given match function * return true. * * @param context A Kerberos 5 context. * @param from the cache to copy data from. * @param to the cache to copy data to. * @param match a match function that should return TRUE if cred argument should be copied, if NULL, all credentials are copied. * @param matchctx context passed to match function. * @param matched set to true if there was a credential that matched, may be NULL. * * @return Return an error code or 0, see krb5_get_error_message(). * * @ingroup krb5_ccache */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_cc_copy_match_f ( krb5_context /*context*/, const krb5_ccache /*from*/, krb5_ccache /*to*/, krb5_boolean (*/*match*/)(krb5_context, void *, const krb5_creds *), void */*matchctx*/, unsigned int */*matched*/); /** * Open the default ccache in `id'. * * @return Return an error code or 0, see krb5_get_error_message(). * * @ingroup krb5_ccache */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_cc_default ( krb5_context /*context*/, krb5_ccache */*id*/); /** * Return a pointer to a context static string containing the default * ccache name. * * @return String to the default credential cache name. * * @ingroup krb5_ccache */ KRB5_LIB_FUNCTION const char* KRB5_LIB_CALL krb5_cc_default_name (krb5_context /*context*/); /** * Remove the ccache `id'. * * @return Return an error code or 0, see krb5_get_error_message(). * * @ingroup krb5_ccache */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_cc_destroy ( krb5_context /*context*/, krb5_ccache /*id*/); /** * Destroy the cursor `cursor'. * * @ingroup krb5_ccache */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_cc_end_seq_get ( krb5_context /*context*/, const krb5_ccache /*id*/, krb5_cc_cursor */*cursor*/); /** * Generate a new ccache of type `ops' in `id'. * * Deprecated: use krb5_cc_new_unique() instead. * * @return Return an error code or 0, see krb5_get_error_message(). * * @ingroup krb5_ccache */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_cc_gen_new ( krb5_context /*context*/, const krb5_cc_ops */*ops*/, krb5_ccache */*id*/) KRB5_DEPRECATED_FUNCTION("Use X instead"); /** * Get some configuration for the credential cache in the cache. * * @param context a Keberos context * @param id the credential cache to store the data for * @param principal configuration for a specific principal, if * NULL, global for the whole cache. * @param name name under which the configuraion is stored. * @param data data to fetched, free with krb5_data_free() * * @ingroup krb5_ccache */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_cc_get_config ( krb5_context /*context*/, krb5_ccache /*id*/, krb5_const_principal /*principal*/, const char */*name*/, krb5_data */*data*/); /** * Get the flags of `id', store them in `flags'. * * @ingroup krb5_ccache */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_cc_get_flags ( krb5_context /*context*/, krb5_ccache /*id*/, krb5_flags */*flags*/); /** * Return a friendly name on credential cache. Free the result with krb5_xfree(). * * @return Return an error code or 0, see krb5_get_error_message(). * * @ingroup krb5_ccache */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_cc_get_friendly_name ( krb5_context /*context*/, krb5_ccache /*id*/, char **/*name*/); /** * Return the complete resolvable name the cache * @param context a Keberos context * @param id return pointer to a found credential cache * @param str the returned name of a credential cache, free with krb5_xfree() * * @return Returns 0 or an error (and then *str is set to NULL). * * @ingroup krb5_ccache */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_cc_get_full_name ( krb5_context /*context*/, krb5_ccache /*id*/, char **/*str*/); /** * Get the time offset betwen the client and the KDC * * If the backend doesn't support KDC offset, use the context global setting. * * @param context A Kerberos 5 context. * @param id a credential cache * @param offset the offset in seconds * * @return Return an error code or 0, see krb5_get_error_message(). * * @ingroup krb5_ccache */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_cc_get_kdc_offset ( krb5_context /*context*/, krb5_ccache /*id*/, krb5_deltat */*offset*/); /** * Get the lifetime of the initial ticket in the cache * * Get the lifetime of the initial ticket in the cache, if the initial * ticket was not found, the error code KRB5_CC_END is returned. * * @param context A Kerberos 5 context. * @param id a credential cache * @param t the relative lifetime of the initial ticket * * @return Return an error code or 0, see krb5_get_error_message(). * * @ingroup krb5_ccache */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_cc_get_lifetime ( krb5_context /*context*/, krb5_ccache /*id*/, time_t */*t*/); /** * Return the name of the ccache `id' * * @ingroup krb5_ccache */ KRB5_LIB_FUNCTION const char* KRB5_LIB_CALL krb5_cc_get_name ( krb5_context /*context*/, krb5_ccache /*id*/); /** * Return krb5_cc_ops of a the ccache `id'. * * @ingroup krb5_ccache */ KRB5_LIB_FUNCTION const krb5_cc_ops * KRB5_LIB_CALL krb5_cc_get_ops ( krb5_context /*context*/, krb5_ccache /*id*/); /** * Get the cc ops that is registered in `context' to handle the * prefix. prefix can be a complete credential cache name or a * prefix, the function will only use part up to the first colon (:) * if there is one. If prefix the argument is NULL, the default ccache * implemtation is returned. * * @return Returns NULL if ops not found. * * @ingroup krb5_ccache */ KRB5_LIB_FUNCTION const krb5_cc_ops * KRB5_LIB_CALL krb5_cc_get_prefix_ops ( krb5_context /*context*/, const char */*prefix*/); /** * Return the principal of `id' in `principal'. * * @return Return an error code or 0, see krb5_get_error_message(). * * @ingroup krb5_ccache */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_cc_get_principal ( krb5_context /*context*/, krb5_ccache /*id*/, krb5_principal */*principal*/); /** * Return the type of the ccache `id'. * * @ingroup krb5_ccache */ KRB5_LIB_FUNCTION const char* KRB5_LIB_CALL krb5_cc_get_type ( krb5_context /*context*/, krb5_ccache /*id*/); /** * Return the version of `id'. * * @ingroup krb5_ccache */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_cc_get_version ( krb5_context /*context*/, const krb5_ccache /*id*/); /** * Create a new ccache in `id' for `primary_principal'. * * @return Return an error code or 0, see krb5_get_error_message(). * * @ingroup krb5_ccache */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_cc_initialize ( krb5_context /*context*/, krb5_ccache /*id*/, krb5_principal /*primary_principal*/); /** * Return the last time the credential cache was modified. * * @param context A Kerberos 5 context * @param id The credential cache to probe * @param mtime the last modification time, set to 0 on error. * @return Return 0 or and error. See krb5_get_error_message(). * * @ingroup krb5_ccache */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_cc_last_change_time ( krb5_context /*context*/, krb5_ccache /*id*/, krb5_timestamp */*mtime*/); /** * Move the content from one credential cache to another. The * operation is an atomic switch. * * @param context a Keberos context * @param from the credential cache to move the content from * @param to the credential cache to move the content to * @return On sucess, from is freed. On failure, error code is * returned and from and to are both still allocated, see krb5_get_error_message(). * * @ingroup krb5_ccache */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_cc_move ( krb5_context /*context*/, krb5_ccache /*from*/, krb5_ccache /*to*/); /** * Generates a new unique ccache of `type` in `id'. If `type' is NULL, * the library chooses the default credential cache type. The supplied * `hint' (that can be NULL) is a string that the credential cache * type can use to base the name of the credential on, this is to make * it easier for the user to differentiate the credentials. * * @return Return an error code or 0, see krb5_get_error_message(). * * @ingroup krb5_ccache */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_cc_new_unique ( krb5_context /*context*/, const char */*type*/, const char */*hint*/, krb5_ccache */*id*/); /** * Retrieve the next cred pointed to by (`id', `cursor') in `creds' * and advance `cursor'. * * @return Return an error code or 0, see krb5_get_error_message(). * * @ingroup krb5_ccache */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_cc_next_cred ( krb5_context /*context*/, const krb5_ccache /*id*/, krb5_cc_cursor */*cursor*/, krb5_creds */*creds*/); /** * Add a new ccache type with operations `ops', overwriting any * existing one if `override'. * * @param context a Keberos context * @param ops type of plugin symbol * @param override flag to select if the registration is to overide * an existing ops with the same name. * * @return Return an error code or 0, see krb5_get_error_message(). * * @ingroup krb5_ccache */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_cc_register ( krb5_context /*context*/, const krb5_cc_ops */*ops*/, krb5_boolean /*override*/); /** * Remove the credential identified by `cred', `which' from `id'. * * @ingroup krb5_ccache */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_cc_remove_cred ( krb5_context /*context*/, krb5_ccache /*id*/, krb5_flags /*which*/, krb5_creds */*cred*/); /** * Find and allocate a ccache in `id' from the specification in `residual'. * If the ccache name doesn't contain any colon, interpret it as a file name. * * @param context a Keberos context. * @param name string name of a credential cache. * @param id return pointer to a found credential cache. * * @return Return 0 or an error code. In case of an error, id is set * to NULL, see krb5_get_error_message(). * * @ingroup krb5_ccache */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_cc_resolve ( krb5_context /*context*/, const char */*name*/, krb5_ccache */*id*/); /** * Retrieve the credential identified by `mcreds' (and `whichfields') * from `id' in `creds'. 'creds' must be free by the caller using * krb5_free_cred_contents. * * @param context A Kerberos 5 context * @param id a Kerberos 5 credential cache * @param whichfields what fields to use for matching credentials, same * flags as whichfields in krb5_compare_creds() * @param mcreds template credential to use for comparing * @param creds returned credential, free with krb5_free_cred_contents() * * @return Return an error code or 0, see krb5_get_error_message(). * * @ingroup krb5_ccache */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_cc_retrieve_cred ( krb5_context /*context*/, krb5_ccache /*id*/, krb5_flags /*whichfields*/, const krb5_creds */*mcreds*/, krb5_creds */*creds*/); /** * Store some configuration for the credential cache in the cache. * Existing configuration under the same name is over-written. * * @param context a Keberos context * @param id the credential cache to store the data for * @param principal configuration for a specific principal, if * NULL, global for the whole cache. * @param name name under which the configuraion is stored. * @param data data to store, if NULL, configure is removed. * * @ingroup krb5_ccache */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_cc_set_config ( krb5_context /*context*/, krb5_ccache /*id*/, krb5_const_principal /*principal*/, const char */*name*/, krb5_data */*data*/); /** * Set the default cc name for `context' to `name'. * * @ingroup krb5_ccache */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_cc_set_default_name ( krb5_context /*context*/, const char */*name*/); /** * Set the flags of `id' to `flags'. * * @ingroup krb5_ccache */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_cc_set_flags ( krb5_context /*context*/, krb5_ccache /*id*/, krb5_flags /*flags*/); /** * Set the friendly name on credential cache. * * @return Return an error code or 0, see krb5_get_error_message(). * * @ingroup krb5_ccache */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_cc_set_friendly_name ( krb5_context /*context*/, krb5_ccache /*id*/, const char */*name*/); /** * Set the time offset betwen the client and the KDC * * If the backend doesn't support KDC offset, use the context global setting. * * @param context A Kerberos 5 context. * @param id a credential cache * @param offset the offset in seconds * * @return Return an error code or 0, see krb5_get_error_message(). * * @ingroup krb5_ccache */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_cc_set_kdc_offset ( krb5_context /*context*/, krb5_ccache /*id*/, krb5_deltat /*offset*/); /** * Start iterating over `id', `cursor' is initialized to the * beginning. Caller must free the cursor with krb5_cc_end_seq_get(). * * @return Return an error code or 0, see krb5_get_error_message(). * * @ingroup krb5_ccache */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_cc_start_seq_get ( krb5_context /*context*/, const krb5_ccache /*id*/, krb5_cc_cursor */*cursor*/); /** * Store `creds' in the ccache `id'. * * @return Return an error code or 0, see krb5_get_error_message(). * * @ingroup krb5_ccache */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_cc_store_cred ( krb5_context /*context*/, krb5_ccache /*id*/, krb5_creds */*creds*/); /** * Return true if the default credential cache support switch * * @ingroup krb5_ccache */ KRB5_LIB_FUNCTION krb5_boolean KRB5_LIB_CALL krb5_cc_support_switch ( krb5_context /*context*/, const char */*type*/); /** * Switch the default default credential cache for a specific * credcache type (and name for some implementations). * * @return Return an error code or 0, see krb5_get_error_message(). * * @ingroup krb5_ccache */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_cc_switch ( krb5_context /*context*/, krb5_ccache /*id*/); /** * End an iteration and free all resources, can be done before end is reached. * * @param context A Kerberos 5 context * @param cursor the iteration cursor to be freed. * * @return Return 0 or and error, KRB5_CC_END is returned at the end * of iteration. See krb5_get_error_message(). * * @ingroup krb5_ccache */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_cccol_cursor_free ( krb5_context /*context*/, krb5_cccol_cursor */*cursor*/); /** * Get a new cache interation cursor that will interate over all * credentials caches independent of type. * * @param context a Keberos context * @param cursor passed into krb5_cccol_cursor_next() and free with krb5_cccol_cursor_free(). * * @return Returns 0 or and error code, see krb5_get_error_message(). * * @ingroup krb5_ccache */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_cccol_cursor_new ( krb5_context /*context*/, krb5_cccol_cursor */*cursor*/); /** * Get next credential cache from the iteration. * * @param context A Kerberos 5 context * @param cursor the iteration cursor * @param cache the returned cursor, pointer is set to NULL on failure * and a cache on success. The returned cache needs to be freed * with krb5_cc_close() or destroyed with krb5_cc_destroy(). * MIT Kerberos behavies slightly diffrent and sets cache to NULL * when all caches are iterated over and return 0. * * @return Return 0 or and error, KRB5_CC_END is returned at the end * of iteration. See krb5_get_error_message(). * * @ingroup krb5_ccache */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_cccol_cursor_next ( krb5_context /*context*/, krb5_cccol_cursor /*cursor*/, krb5_ccache */*cache*/); /** * Return the last modfication time for a cache collection. The query * can be limited to a specific cache type. If the function return 0 * and mtime is 0, there was no credentials in the caches. * * @param context A Kerberos 5 context * @param type The credential cache to probe, if NULL, all type are traversed. * @param mtime the last modification time, set to 0 on error. * @return Return 0 or and error. See krb5_get_error_message(). * * @ingroup krb5_ccache */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_cccol_last_change_time ( krb5_context /*context*/, const char */*type*/, krb5_timestamp */*mtime*/); /** * Deprecated: krb5_change_password() is deprecated, use krb5_set_password(). * * @param context a Keberos context * @param creds * @param newpw * @param result_code * @param result_code_string * @param result_string * * @return On sucess password is changed. * @ingroup @krb5_deprecated */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_change_password ( krb5_context /*context*/, krb5_creds */*creds*/, const char */*newpw*/, int */*result_code*/, krb5_data */*result_code_string*/, krb5_data */*result_string*/) KRB5_DEPRECATED_FUNCTION("Use X instead"); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_check_transited ( krb5_context /*context*/, krb5_const_realm /*client_realm*/, krb5_const_realm /*server_realm*/, krb5_realm */*realms*/, unsigned int /*num_realms*/, int */*bad_realm*/); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_check_transited_realms ( krb5_context /*context*/, const char *const */*realms*/, unsigned int /*num_realms*/, int */*bad_realm*/); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_checksum_disable ( krb5_context /*context*/, krb5_cksumtype /*type*/); KRB5_LIB_FUNCTION void KRB5_LIB_CALL krb5_checksum_free ( krb5_context /*context*/, krb5_checksum */*cksum*/); KRB5_LIB_FUNCTION krb5_boolean KRB5_LIB_CALL krb5_checksum_is_collision_proof ( krb5_context /*context*/, krb5_cksumtype /*type*/); KRB5_LIB_FUNCTION krb5_boolean KRB5_LIB_CALL krb5_checksum_is_keyed ( krb5_context /*context*/, krb5_cksumtype /*type*/); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_checksumsize ( krb5_context /*context*/, krb5_cksumtype /*type*/, size_t */*size*/); /** * Return the coresponding encryption type for a checksum type. * * @param context Kerberos context * @param ctype The checksum type to get the result enctype for * @param etype The returned encryption, when the matching etype is * not found, etype is set to ETYPE_NULL. * * @return Return an error code for an failure or 0 on success. * @ingroup krb5_crypto */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_cksumtype_to_enctype ( krb5_context /*context*/, krb5_cksumtype /*ctype*/, krb5_enctype */*etype*/); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_cksumtype_valid ( krb5_context /*context*/, krb5_cksumtype /*ctype*/); /** * Clears the error message from the Kerberos 5 context. * * @param context The Kerberos 5 context to clear * * @ingroup krb5_error */ KRB5_LIB_FUNCTION void KRB5_LIB_CALL krb5_clear_error_message (krb5_context /*context*/); /** * Clear the error message returned by krb5_get_error_string(). * * Deprecated: use krb5_clear_error_message() * * @param context Kerberos context * * @ingroup krb5_deprecated */ KRB5_LIB_FUNCTION void KRB5_LIB_CALL krb5_clear_error_string (krb5_context /*context*/) KRB5_DEPRECATED_FUNCTION("Use X instead"); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_closelog ( krb5_context /*context*/, krb5_log_facility */*fac*/); /** * Return TRUE if `mcreds' and `creds' are equal (`whichfields' * determines what equal means). * * * The following flags, set in whichfields affects the comparison: * - KRB5_TC_MATCH_SRV_NAMEONLY Consider all realms equal when comparing the service principal. * - KRB5_TC_MATCH_KEYTYPE Compare enctypes. * - KRB5_TC_MATCH_FLAGS_EXACT Make sure that the ticket flags are identical. * - KRB5_TC_MATCH_FLAGS Make sure that all ticket flags set in mcreds are also present in creds . * - KRB5_TC_MATCH_TIMES_EXACT Compares the ticket times exactly. * - KRB5_TC_MATCH_TIMES Compares only the expiration times of the creds. * - KRB5_TC_MATCH_AUTHDATA Compares the authdata fields. * - KRB5_TC_MATCH_2ND_TKT Compares the second tickets (used by user-to-user authentication). * - KRB5_TC_MATCH_IS_SKEY Compares the existance of the second ticket. * * @param context Kerberos 5 context. * @param whichfields which fields to compare. * @param mcreds cred to compare with. * @param creds cred to compare with. * * @return return TRUE if mcred and creds are equal, FALSE if not. * * @ingroup krb5 */ KRB5_LIB_FUNCTION krb5_boolean KRB5_LIB_CALL krb5_compare_creds ( krb5_context /*context*/, krb5_flags /*whichfields*/, const krb5_creds * /*mcreds*/, const krb5_creds * /*creds*/); /** * Free configuration file section, the result of * krb5_config_parse_file() and krb5_config_parse_file_multi(). * * @param context A Kerberos 5 context * @param s the configuration section to free * * @return returns 0 on successes, otherwise an error code, see * krb5_get_error_message() * * @ingroup krb5_support */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_config_file_free ( krb5_context /*context*/, krb5_config_section */*s*/); /** * Free the resulting strings from krb5_config-get_strings() and * krb5_config_vget_strings(). * * @param strings strings to free * * @ingroup krb5_support */ KRB5_LIB_FUNCTION void KRB5_LIB_CALL krb5_config_free_strings (char **/*strings*/); /** * Like krb5_config_get_bool() but with a va_list list of * configuration selection. * * Configuration value to a boolean value, where yes/true and any * non-zero number means TRUE and other value is FALSE. * * @param context A Kerberos 5 context. * @param c a configuration section, or NULL to use the section from context * @param ... a list of names, terminated with NULL. * * @return TRUE or FALSE * * @ingroup krb5_support */ KRB5_LIB_FUNCTION krb5_boolean KRB5_LIB_CALL krb5_config_get_bool ( krb5_context /*context*/, const krb5_config_section */*c*/, ...); /** * krb5_config_get_bool_default() will convert the configuration * option value to a boolean value, where yes/true and any non-zero * number means TRUE and other value is FALSE. * * @param context A Kerberos 5 context. * @param c a configuration section, or NULL to use the section from context * @param def_value the default value to return if no configuration * found in the database. * @param ... a list of names, terminated with NULL. * * @return TRUE or FALSE * * @ingroup krb5_support */ KRB5_LIB_FUNCTION krb5_boolean KRB5_LIB_CALL krb5_config_get_bool_default ( krb5_context /*context*/, const krb5_config_section */*c*/, krb5_boolean /*def_value*/, ...); KRB5_LIB_FUNCTION int KRB5_LIB_CALL krb5_config_get_int ( krb5_context /*context*/, const krb5_config_section */*c*/, ...); KRB5_LIB_FUNCTION int KRB5_LIB_CALL krb5_config_get_int_default ( krb5_context /*context*/, const krb5_config_section */*c*/, int /*def_value*/, ...); /** * Get a list of configuration binding list for more processing * * @param context A Kerberos 5 context. * @param c a configuration section, or NULL to use the section from context * @param ... a list of names, terminated with NULL. * * @return NULL if configuration list is not found, a list otherwise * * @ingroup krb5_support */ KRB5_LIB_FUNCTION const krb5_config_binding * KRB5_LIB_CALL krb5_config_get_list ( krb5_context /*context*/, const krb5_config_section */*c*/, ...); /** * Returns a "const char *" to a string in the configuration database. * The string may not be valid after a reload of the configuration * database so a caller should make a local copy if it needs to keep * the string. * * @param context A Kerberos 5 context. * @param c a configuration section, or NULL to use the section from context * @param ... a list of names, terminated with NULL. * * @return NULL if configuration string not found, a string otherwise * * @ingroup krb5_support */ KRB5_LIB_FUNCTION const char* KRB5_LIB_CALL krb5_config_get_string ( krb5_context /*context*/, const krb5_config_section */*c*/, ...); /** * Like krb5_config_get_string(), but instead of returning NULL, * instead return a default value. * * @param context A Kerberos 5 context. * @param c a configuration section, or NULL to use the section from context * @param def_value the default value to return if no configuration * found in the database. * @param ... a list of names, terminated with NULL. * * @return a configuration string * * @ingroup krb5_support */ KRB5_LIB_FUNCTION const char* KRB5_LIB_CALL krb5_config_get_string_default ( krb5_context /*context*/, const krb5_config_section */*c*/, const char */*def_value*/, ...); /** * Get a list of configuration strings, free the result with * krb5_config_free_strings(). * * @param context A Kerberos 5 context. * @param c a configuration section, or NULL to use the section from context * @param ... a list of names, terminated with NULL. * * @return TRUE or FALSE * * @ingroup krb5_support */ KRB5_LIB_FUNCTION char** KRB5_LIB_CALL krb5_config_get_strings ( krb5_context /*context*/, const krb5_config_section */*c*/, ...); /** * Get the time from the configuration file using a relative time, for example: 1h30s * * @param context A Kerberos 5 context. * @param c a configuration section, or NULL to use the section from context * @param ... a list of names, terminated with NULL. * * @return parsed the time or -1 on error * * @ingroup krb5_support */ KRB5_LIB_FUNCTION int KRB5_LIB_CALL krb5_config_get_time ( krb5_context /*context*/, const krb5_config_section */*c*/, ...); /** * Get the time from the configuration file using a relative time, for example: 1h30s * * @param context A Kerberos 5 context. * @param c a configuration section, or NULL to use the section from context * @param def_value the default value to return if no configuration * found in the database. * @param ... a list of names, terminated with NULL. * * @return parsed the time (or def_value on parse error) * * @ingroup krb5_support */ KRB5_LIB_FUNCTION int KRB5_LIB_CALL krb5_config_get_time_default ( krb5_context /*context*/, const krb5_config_section */*c*/, int /*def_value*/, ...); /** * If the fname starts with "~/" parse configuration file in the * current users home directory. The behavior can be disabled and * enabled by calling krb5_set_home_dir_access(). */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_config_parse_file ( krb5_context /*context*/, const char */*fname*/, krb5_config_section **/*res*/); /** * Parse a configuration file and add the result into res. This * interface can be used to parse several configuration files into one * resulting krb5_config_section by calling it repeatably. * * @param context a Kerberos 5 context. * @param fname a file name to a Kerberos configuration file * @param res the returned result, must be free with krb5_free_config_files(). * @return Return an error code or 0, see krb5_get_error_message(). * * @ingroup krb5_support */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_config_parse_file_multi ( krb5_context /*context*/, const char */*fname*/, krb5_config_section **/*res*/); /** * Deprecated: configuration files are not strings * * @ingroup krb5_deprecated */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_config_parse_string_multi ( krb5_context /*context*/, const char */*string*/, krb5_config_section **/*res*/) KRB5_DEPRECATED_FUNCTION("Use X instead"); /** * krb5_config_get_bool() will convert the configuration * option value to a boolean value, where yes/true and any non-zero * number means TRUE and other value is FALSE. * * @param context A Kerberos 5 context. * @param c a configuration section, or NULL to use the section from context * @param args a va_list of arguments * * @return TRUE or FALSE * * @ingroup krb5_support */ KRB5_LIB_FUNCTION krb5_boolean KRB5_LIB_CALL krb5_config_vget_bool ( krb5_context /*context*/, const krb5_config_section */*c*/, va_list /*args*/); /** * Like krb5_config_get_bool_default() but with a va_list list of * configuration selection. * * Configuration value to a boolean value, where yes/true and any * non-zero number means TRUE and other value is FALSE. * * @param context A Kerberos 5 context. * @param c a configuration section, or NULL to use the section from context * @param def_value the default value to return if no configuration * found in the database. * @param args a va_list of arguments * * @return TRUE or FALSE * * @ingroup krb5_support */ KRB5_LIB_FUNCTION krb5_boolean KRB5_LIB_CALL krb5_config_vget_bool_default ( krb5_context /*context*/, const krb5_config_section */*c*/, krb5_boolean /*def_value*/, va_list /*args*/); KRB5_LIB_FUNCTION int KRB5_LIB_CALL krb5_config_vget_int ( krb5_context /*context*/, const krb5_config_section */*c*/, va_list /*args*/); KRB5_LIB_FUNCTION int KRB5_LIB_CALL krb5_config_vget_int_default ( krb5_context /*context*/, const krb5_config_section */*c*/, int /*def_value*/, va_list /*args*/); /** * Get a list of configuration binding list for more processing * * @param context A Kerberos 5 context. * @param c a configuration section, or NULL to use the section from context * @param args a va_list of arguments * * @return NULL if configuration list is not found, a list otherwise * * @ingroup krb5_support */ KRB5_LIB_FUNCTION const krb5_config_binding * KRB5_LIB_CALL krb5_config_vget_list ( krb5_context /*context*/, const krb5_config_section */*c*/, va_list /*args*/); /** * Like krb5_config_get_string(), but uses a va_list instead of ... * * @param context A Kerberos 5 context. * @param c a configuration section, or NULL to use the section from context * @param args a va_list of arguments * * @return NULL if configuration string not found, a string otherwise * * @ingroup krb5_support */ KRB5_LIB_FUNCTION const char* KRB5_LIB_CALL krb5_config_vget_string ( krb5_context /*context*/, const krb5_config_section */*c*/, va_list /*args*/); /** * Like krb5_config_vget_string(), but instead of returning NULL, * instead return a default value. * * @param context A Kerberos 5 context. * @param c a configuration section, or NULL to use the section from context * @param def_value the default value to return if no configuration * found in the database. * @param args a va_list of arguments * * @return a configuration string * * @ingroup krb5_support */ KRB5_LIB_FUNCTION const char* KRB5_LIB_CALL krb5_config_vget_string_default ( krb5_context /*context*/, const krb5_config_section */*c*/, const char */*def_value*/, va_list /*args*/); /** * Get a list of configuration strings, free the result with * krb5_config_free_strings(). * * @param context A Kerberos 5 context. * @param c a configuration section, or NULL to use the section from context * @param args a va_list of arguments * * @return TRUE or FALSE * * @ingroup krb5_support */ KRB5_LIB_FUNCTION char ** KRB5_LIB_CALL krb5_config_vget_strings ( krb5_context /*context*/, const krb5_config_section */*c*/, va_list /*args*/); /** * Get the time from the configuration file using a relative time, for example: 1h30s * * @param context A Kerberos 5 context. * @param c a configuration section, or NULL to use the section from context * @param args a va_list of arguments * * @return parsed the time or -1 on error * * @ingroup krb5_support */ KRB5_LIB_FUNCTION int KRB5_LIB_CALL krb5_config_vget_time ( krb5_context /*context*/, const krb5_config_section */*c*/, va_list /*args*/); /** * Get the time from the configuration file using a relative time. * * Like krb5_config_get_time_default() but with a va_list list of * configuration selection. * * @param context A Kerberos 5 context. * @param c a configuration section, or NULL to use the section from context * @param def_value the default value to return if no configuration * found in the database. * @param args a va_list of arguments * * @return parsed the time (or def_value on parse error) * * @ingroup krb5_support */ KRB5_LIB_FUNCTION int KRB5_LIB_CALL krb5_config_vget_time_default ( krb5_context /*context*/, const krb5_config_section */*c*/, int /*def_value*/, va_list /*args*/); /** * krb5_copy_address copies the content of address * inaddr to outaddr. * * @param context a Keberos context * @param inaddr pointer to source address * @param outaddr pointer to destination address * * @return Return an error code or 0. * * @ingroup krb5_address */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_copy_address ( krb5_context /*context*/, const krb5_address */*inaddr*/, krb5_address */*outaddr*/); /** * krb5_copy_addresses copies the content of addresses * inaddr to outaddr. * * @param context a Keberos context * @param inaddr pointer to source addresses * @param outaddr pointer to destination addresses * * @return Return an error code or 0. * * @ingroup krb5_address */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_copy_addresses ( krb5_context /*context*/, const krb5_addresses */*inaddr*/, krb5_addresses */*outaddr*/); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_copy_checksum ( krb5_context /*context*/, const krb5_checksum */*old*/, krb5_checksum **/*new*/); /** * Make a copy for the Kerberos 5 context, the new krb5_context shoud * be freed with krb5_free_context(). * * @param context the Kerberos context to copy * @param out the copy of the Kerberos, set to NULL error. * * @return Returns 0 to indicate success. Otherwise an kerberos et * error code is returned, see krb5_get_error_message(). * * @ingroup krb5 */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_copy_context ( krb5_context /*context*/, krb5_context */*out*/); /** * Copy krb5_creds. * * @param context Kerberos 5 context. * @param incred source credential * @param outcred destination credential, free with krb5_free_creds(). * * @return Returns 0 to indicate success. Otherwise an kerberos et * error code is returned, see krb5_get_error_message(). * * @ingroup krb5 */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_copy_creds ( krb5_context /*context*/, const krb5_creds */*incred*/, krb5_creds **/*outcred*/); /** * Copy content of krb5_creds. * * @param context Kerberos 5 context. * @param incred source credential * @param c destination credential, free with krb5_free_cred_contents(). * * @return Returns 0 to indicate success. Otherwise an kerberos et * error code is returned, see krb5_get_error_message(). * * @ingroup krb5 */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_copy_creds_contents ( krb5_context /*context*/, const krb5_creds */*incred*/, krb5_creds */*c*/); /** * Copy the data into a newly allocated krb5_data. * * @param context Kerberos 5 context. * @param indata the krb5_data data to copy * @param outdata new krb5_date to copy too. Free with krb5_free_data(). * * @return Returns 0 to indicate success. Otherwise an kerberos et * error code is returned. * * @ingroup krb5 */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_copy_data ( krb5_context /*context*/, const krb5_data */*indata*/, krb5_data **/*outdata*/); /** * Copy the list of realms from `from' to `to'. * * @param context Kerberos 5 context. * @param from list of realms to copy from. * @param to list of realms to copy to, free list of krb5_free_host_realm(). * * @return Returns 0 to indicate success. Otherwise an kerberos et * error code is returned, see krb5_get_error_message(). * * @ingroup krb5 */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_copy_host_realm ( krb5_context /*context*/, const krb5_realm */*from*/, krb5_realm **/*to*/); /** * Copy a keyblock, free the output keyblock with * krb5_free_keyblock(). * * @param context a Kerberos 5 context * @param inblock the key to copy * @param to the output key. * * @return 0 on success or a Kerberos 5 error code * * @ingroup krb5_crypto */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_copy_keyblock ( krb5_context /*context*/, const krb5_keyblock */*inblock*/, krb5_keyblock **/*to*/); /** * Copy a keyblock, free the output keyblock with * krb5_free_keyblock_contents(). * * @param context a Kerberos 5 context * @param inblock the key to copy * @param to the output key. * * @return 0 on success or a Kerberos 5 error code * * @ingroup krb5_crypto */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_copy_keyblock_contents ( krb5_context /*context*/, const krb5_keyblock */*inblock*/, krb5_keyblock */*to*/); /** * Copy a principal * * @param context A Kerberos context. * @param inprinc principal to copy * @param outprinc copied principal, free with krb5_free_principal() * * @return An krb5 error code, see krb5_get_error_message(). * * @ingroup krb5_principal */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_copy_principal ( krb5_context /*context*/, krb5_const_principal /*inprinc*/, krb5_principal */*outprinc*/); /** * Copy ticket and content * * @param context a Kerberos 5 context * @param from ticket to copy * @param to new copy of ticket, free with krb5_free_ticket() * * @return Returns 0 to indicate success. Otherwise an kerberos et * error code is returned, see krb5_get_error_message(). * * @ingroup krb5 */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_copy_ticket ( krb5_context /*context*/, const krb5_ticket */*from*/, krb5_ticket **/*to*/); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_create_checksum ( krb5_context /*context*/, krb5_crypto /*crypto*/, krb5_key_usage /*usage*/, int /*type*/, void */*data*/, size_t /*len*/, Checksum */*result*/); /** * Create a Kerberos message checksum. * * @param context Kerberos context * @param crypto Kerberos crypto context * @param usage Key usage for this buffer * @param data array of buffers to process * @param num_data length of array * @param type output data * * @return Return an error code or 0. * @ingroup krb5_crypto */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_create_checksum_iov ( krb5_context /*context*/, krb5_crypto /*crypto*/, unsigned /*usage*/, krb5_crypto_iov */*data*/, unsigned int /*num_data*/, krb5_cksumtype */*type*/); /** * Returns the ticket flags for the credentials in creds. * See also krb5_ticket_get_flags(). * * @param creds credential to get ticket flags from * * @return ticket flags * * @ingroup krb5 */ KRB5_LIB_FUNCTION unsigned long KRB5_LIB_CALL krb5_creds_get_ticket_flags (krb5_creds */*creds*/); /** * Free a crypto context created by krb5_crypto_init(). * * @param context Kerberos context * @param crypto crypto context to free * * @return Return an error code or 0. * * @ingroup krb5_crypto */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_crypto_destroy ( krb5_context /*context*/, krb5_crypto /*crypto*/); /** * The FX-CF2 key derivation function, used in FAST and preauth framework. * * @param context Kerberos 5 context * @param crypto1 first key to combine * @param crypto2 second key to combine * @param pepper1 factor to combine with first key to garante uniqueness * @param pepper2 factor to combine with second key to garante uniqueness * @param enctype the encryption type of the resulting key * @param res allocated key, free with krb5_free_keyblock_contents() * * @return Return an error code or 0. * * @ingroup krb5_crypto */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_crypto_fx_cf2 ( krb5_context /*context*/, const krb5_crypto /*crypto1*/, const krb5_crypto /*crypto2*/, krb5_data */*pepper1*/, krb5_data */*pepper2*/, krb5_enctype /*enctype*/, krb5_keyblock */*res*/); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_crypto_get_checksum_type ( krb5_context /*context*/, krb5_crypto /*crypto*/, krb5_cksumtype */*type*/); /** * Return the blocksize used algorithm referenced by the crypto context * * @param context Kerberos context * @param crypto crypto context to query * @param blocksize the resulting blocksize * * @return Return an error code or 0. * * @ingroup krb5_crypto */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_crypto_getblocksize ( krb5_context /*context*/, krb5_crypto /*crypto*/, size_t */*blocksize*/); /** * Return the confounder size used by the crypto context * * @param context Kerberos context * @param crypto crypto context to query * @param confoundersize the returned confounder size * * @return Return an error code or 0. * * @ingroup krb5_crypto */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_crypto_getconfoundersize ( krb5_context /*context*/, krb5_crypto /*crypto*/, size_t */*confoundersize*/); /** * Return the encryption type used by the crypto context * * @param context Kerberos context * @param crypto crypto context to query * @param enctype the resulting encryption type * * @return Return an error code or 0. * * @ingroup krb5_crypto */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_crypto_getenctype ( krb5_context /*context*/, krb5_crypto /*crypto*/, krb5_enctype */*enctype*/); /** * Return the padding size used by the crypto context * * @param context Kerberos context * @param crypto crypto context to query * @param padsize the return padding size * * @return Return an error code or 0. * * @ingroup krb5_crypto */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_crypto_getpadsize ( krb5_context /*context*/, krb5_crypto /*crypto*/, size_t */*padsize*/); /** * Create a crypto context used for all encryption and signature * operation. The encryption type to use is taken from the key, but * can be overridden with the enctype parameter. This can be useful * for encryptions types which is compatiable (DES for example). * * To free the crypto context, use krb5_crypto_destroy(). * * @param context Kerberos context * @param key the key block information with all key data * @param etype the encryption type * @param crypto the resulting crypto context * * @return Return an error code or 0. * * @ingroup krb5_crypto */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_crypto_init ( krb5_context /*context*/, const krb5_keyblock */*key*/, krb5_enctype /*etype*/, krb5_crypto */*crypto*/); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_crypto_length ( krb5_context /*context*/, krb5_crypto /*crypto*/, int /*type*/, size_t */*len*/); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_crypto_length_iov ( krb5_context /*context*/, krb5_crypto /*crypto*/, krb5_crypto_iov */*data*/, unsigned int /*num_data*/); KRB5_LIB_FUNCTION size_t KRB5_LIB_CALL krb5_crypto_overhead ( krb5_context /*context*/, krb5_crypto /*crypto*/); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_crypto_prf ( krb5_context /*context*/, const krb5_crypto /*crypto*/, const krb5_data */*input*/, krb5_data */*output*/); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_crypto_prf_length ( krb5_context /*context*/, krb5_enctype /*type*/, size_t */*length*/); /** * Allocate data of and krb5_data. * * @param p krb5_data to allocate. * @param len size to allocate. * * @return Returns 0 to indicate success. Otherwise an kerberos et * error code is returned. * * @ingroup krb5 */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_data_alloc ( krb5_data */*p*/, int /*len*/); /** * Compare to data. * * @param data1 krb5_data to compare * @param data2 krb5_data to compare * * @return return the same way as memcmp(), useful when sorting. * * @ingroup krb5 */ KRB5_LIB_FUNCTION int KRB5_LIB_CALL krb5_data_cmp ( const krb5_data */*data1*/, const krb5_data */*data2*/); /** * Copy the data of len into the krb5_data. * * @param p krb5_data to copy into. * @param data data to copy.. * @param len new size. * * @return Returns 0 to indicate success. Otherwise an kerberos et * error code is returned. * * @ingroup krb5 */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_data_copy ( krb5_data */*p*/, const void */*data*/, size_t /*len*/); /** * Compare to data not exposing timing information from the checksum data * * @param data1 krb5_data to compare * @param data2 krb5_data to compare * * @return returns zero for same data, otherwise non zero. * * @ingroup krb5 */ KRB5_LIB_FUNCTION int KRB5_LIB_CALL krb5_data_ct_cmp ( const krb5_data */*data1*/, const krb5_data */*data2*/); /** * Free the content of krb5_data structure, its ok to free a zeroed * structure (with memset() or krb5_data_zero()). When done, the * structure will be zeroed. The same function is called * krb5_free_data_contents() in MIT Kerberos. * * @param p krb5_data to free. * * @ingroup krb5 */ KRB5_LIB_FUNCTION void KRB5_LIB_CALL krb5_data_free (krb5_data */*p*/); /** * Grow (or shrink) the content of krb5_data to a new size. * * @param p krb5_data to free. * @param len new size. * * @return Returns 0 to indicate success. Otherwise an kerberos et * error code is returned. * * @ingroup krb5 */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_data_realloc ( krb5_data */*p*/, int /*len*/); /** * Reset the (potentially uninitalized) krb5_data structure. * * @param p krb5_data to reset. * * @ingroup krb5 */ KRB5_LIB_FUNCTION void KRB5_LIB_CALL krb5_data_zero (krb5_data */*p*/); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_decode_Authenticator ( krb5_context /*context*/, const void */*data*/, size_t /*length*/, Authenticator */*t*/, size_t */*len*/) KRB5_DEPRECATED_FUNCTION("Use X instead"); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_decode_ETYPE_INFO ( krb5_context /*context*/, const void */*data*/, size_t /*length*/, ETYPE_INFO */*t*/, size_t */*len*/) KRB5_DEPRECATED_FUNCTION("Use X instead"); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_decode_ETYPE_INFO2 ( krb5_context /*context*/, const void */*data*/, size_t /*length*/, ETYPE_INFO2 */*t*/, size_t */*len*/) KRB5_DEPRECATED_FUNCTION("Use X instead"); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_decode_EncAPRepPart ( krb5_context /*context*/, const void */*data*/, size_t /*length*/, EncAPRepPart */*t*/, size_t */*len*/) KRB5_DEPRECATED_FUNCTION("Use X instead"); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_decode_EncASRepPart ( krb5_context /*context*/, const void */*data*/, size_t /*length*/, EncASRepPart */*t*/, size_t */*len*/) KRB5_DEPRECATED_FUNCTION("Use X instead"); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_decode_EncKrbCredPart ( krb5_context /*context*/, const void */*data*/, size_t /*length*/, EncKrbCredPart */*t*/, size_t */*len*/) KRB5_DEPRECATED_FUNCTION("Use X instead"); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_decode_EncTGSRepPart ( krb5_context /*context*/, const void */*data*/, size_t /*length*/, EncTGSRepPart */*t*/, size_t */*len*/) KRB5_DEPRECATED_FUNCTION("Use X instead"); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_decode_EncTicketPart ( krb5_context /*context*/, const void */*data*/, size_t /*length*/, EncTicketPart */*t*/, size_t */*len*/) KRB5_DEPRECATED_FUNCTION("Use X instead"); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_decode_ap_req ( krb5_context /*context*/, const krb5_data */*inbuf*/, krb5_ap_req */*ap_req*/); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_decrypt ( krb5_context /*context*/, krb5_crypto /*crypto*/, unsigned /*usage*/, void */*data*/, size_t /*len*/, krb5_data */*result*/); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_decrypt_EncryptedData ( krb5_context /*context*/, krb5_crypto /*crypto*/, unsigned /*usage*/, const EncryptedData */*e*/, krb5_data */*result*/); /** * Inline decrypt a Kerberos message. * * @param context Kerberos context * @param crypto Kerberos crypto context * @param usage Key usage for this buffer * @param data array of buffers to process * @param num_data length of array * @param ivec initial cbc/cts vector * * @return Return an error code or 0. * @ingroup krb5_crypto * * 1. KRB5_CRYPTO_TYPE_HEADER * 2. one KRB5_CRYPTO_TYPE_DATA and array [0,...] of KRB5_CRYPTO_TYPE_SIGN_ONLY in * any order, however the receiver have to aware of the * order. KRB5_CRYPTO_TYPE_SIGN_ONLY is commonly used unencrypoted * protocol headers and trailers. The output data will be of same * size as the input data or shorter. */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_decrypt_iov_ivec ( krb5_context /*context*/, krb5_crypto /*crypto*/, unsigned /*usage*/, krb5_crypto_iov */*data*/, unsigned int /*num_data*/, void */*ivec*/); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_decrypt_ivec ( krb5_context /*context*/, krb5_crypto /*crypto*/, unsigned /*usage*/, void */*data*/, size_t /*len*/, krb5_data */*result*/, void */*ivec*/); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_decrypt_ticket ( krb5_context /*context*/, Ticket */*ticket*/, krb5_keyblock */*key*/, EncTicketPart */*out*/, krb5_flags /*flags*/); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_derive_key ( krb5_context /*context*/, const krb5_keyblock */*key*/, krb5_enctype /*etype*/, const void */*constant*/, size_t /*constant_len*/, krb5_keyblock **/*derived_key*/); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_digest_alloc ( krb5_context /*context*/, krb5_digest */*digest*/); KRB5_LIB_FUNCTION void KRB5_LIB_CALL krb5_digest_free (krb5_digest /*digest*/); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_digest_get_client_binding ( krb5_context /*context*/, krb5_digest /*digest*/, char **/*type*/, char **/*binding*/); KRB5_LIB_FUNCTION const char * KRB5_LIB_CALL krb5_digest_get_identifier ( krb5_context /*context*/, krb5_digest /*digest*/); KRB5_LIB_FUNCTION const char * KRB5_LIB_CALL krb5_digest_get_opaque ( krb5_context /*context*/, krb5_digest /*digest*/); KRB5_LIB_FUNCTION const char * KRB5_LIB_CALL krb5_digest_get_rsp ( krb5_context /*context*/, krb5_digest /*digest*/); KRB5_LIB_FUNCTION const char * KRB5_LIB_CALL krb5_digest_get_server_nonce ( krb5_context /*context*/, krb5_digest /*digest*/); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_digest_get_session_key ( krb5_context /*context*/, krb5_digest /*digest*/, krb5_data */*data*/); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_digest_get_tickets ( krb5_context /*context*/, krb5_digest /*digest*/, Ticket **/*tickets*/); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_digest_init_request ( krb5_context /*context*/, krb5_digest /*digest*/, krb5_realm /*realm*/, krb5_ccache /*ccache*/); /** * Get the supported/allowed mechanism for this principal. * * @param context A Keberos context. * @param realm The realm of the KDC. * @param ccache The credential cache to use when talking to the KDC. * @param flags The supported mechanism. * * @return Return an error code or 0. * * @ingroup krb5_digest */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_digest_probe ( krb5_context /*context*/, krb5_realm /*realm*/, krb5_ccache /*ccache*/, unsigned */*flags*/); KRB5_LIB_FUNCTION krb5_boolean KRB5_LIB_CALL krb5_digest_rep_get_status ( krb5_context /*context*/, krb5_digest /*digest*/); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_digest_request ( krb5_context /*context*/, krb5_digest /*digest*/, krb5_realm /*realm*/, krb5_ccache /*ccache*/); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_digest_set_authentication_user ( krb5_context /*context*/, krb5_digest /*digest*/, krb5_principal /*authentication_user*/); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_digest_set_authid ( krb5_context /*context*/, krb5_digest /*digest*/, const char */*authid*/); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_digest_set_client_nonce ( krb5_context /*context*/, krb5_digest /*digest*/, const char */*nonce*/); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_digest_set_digest ( krb5_context /*context*/, krb5_digest /*digest*/, const char */*dgst*/); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_digest_set_hostname ( krb5_context /*context*/, krb5_digest /*digest*/, const char */*hostname*/); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_digest_set_identifier ( krb5_context /*context*/, krb5_digest /*digest*/, const char */*id*/); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_digest_set_method ( krb5_context /*context*/, krb5_digest /*digest*/, const char */*method*/); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_digest_set_nonceCount ( krb5_context /*context*/, krb5_digest /*digest*/, const char */*nonce_count*/); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_digest_set_opaque ( krb5_context /*context*/, krb5_digest /*digest*/, const char */*opaque*/); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_digest_set_qop ( krb5_context /*context*/, krb5_digest /*digest*/, const char */*qop*/); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_digest_set_realm ( krb5_context /*context*/, krb5_digest /*digest*/, const char */*realm*/); KRB5_LIB_FUNCTION int KRB5_LIB_CALL krb5_digest_set_responseData ( krb5_context /*context*/, krb5_digest /*digest*/, const char */*response*/); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_digest_set_server_cb ( krb5_context /*context*/, krb5_digest /*digest*/, const char */*type*/, const char */*binding*/); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_digest_set_server_nonce ( krb5_context /*context*/, krb5_digest /*digest*/, const char */*nonce*/); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_digest_set_type ( krb5_context /*context*/, krb5_digest /*digest*/, const char */*type*/); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_digest_set_uri ( krb5_context /*context*/, krb5_digest /*digest*/, const char */*uri*/); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_digest_set_username ( krb5_context /*context*/, krb5_digest /*digest*/, const char */*username*/); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_domain_x500_decode ( krb5_context /*context*/, krb5_data /*tr*/, char ***/*realms*/, unsigned int */*num_realms*/, const char */*client_realm*/, const char */*server_realm*/); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_domain_x500_encode ( char **/*realms*/, unsigned int /*num_realms*/, krb5_data */*encoding*/); /** * Convert the getaddrinfo() error code to a Kerberos et error code. * * @param eai_errno contains the error code from getaddrinfo(). * @param system_error should have the value of errno after the failed getaddrinfo(). * * @return Kerberos error code representing the EAI errors. * * @ingroup krb5_error */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_eai_to_heim_errno ( int /*eai_errno*/, int /*system_error*/); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_encode_Authenticator ( krb5_context /*context*/, void */*data*/, size_t /*length*/, Authenticator */*t*/, size_t */*len*/) KRB5_DEPRECATED_FUNCTION("Use X instead"); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_encode_ETYPE_INFO ( krb5_context /*context*/, void */*data*/, size_t /*length*/, ETYPE_INFO */*t*/, size_t */*len*/) KRB5_DEPRECATED_FUNCTION("Use X instead"); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_encode_ETYPE_INFO2 ( krb5_context /*context*/, void */*data*/, size_t /*length*/, ETYPE_INFO2 */*t*/, size_t */*len*/) KRB5_DEPRECATED_FUNCTION("Use X instead"); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_encode_EncAPRepPart ( krb5_context /*context*/, void */*data*/, size_t /*length*/, EncAPRepPart */*t*/, size_t */*len*/) KRB5_DEPRECATED_FUNCTION("Use X instead"); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_encode_EncASRepPart ( krb5_context /*context*/, void */*data*/, size_t /*length*/, EncASRepPart */*t*/, size_t */*len*/) KRB5_DEPRECATED_FUNCTION("Use X instead"); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_encode_EncKrbCredPart ( krb5_context /*context*/, void */*data*/, size_t /*length*/, EncKrbCredPart */*t*/, size_t */*len*/) KRB5_DEPRECATED_FUNCTION("Use X instead"); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_encode_EncTGSRepPart ( krb5_context /*context*/, void */*data*/, size_t /*length*/, EncTGSRepPart */*t*/, size_t */*len*/) KRB5_DEPRECATED_FUNCTION("Use X instead"); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_encode_EncTicketPart ( krb5_context /*context*/, void */*data*/, size_t /*length*/, EncTicketPart */*t*/, size_t */*len*/) KRB5_DEPRECATED_FUNCTION("Use X instead"); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_encrypt ( krb5_context /*context*/, krb5_crypto /*crypto*/, unsigned /*usage*/, const void */*data*/, size_t /*len*/, krb5_data */*result*/); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_encrypt_EncryptedData ( krb5_context /*context*/, krb5_crypto /*crypto*/, unsigned /*usage*/, void */*data*/, size_t /*len*/, int /*kvno*/, EncryptedData */*result*/); /** * Inline encrypt a kerberos message * * @param context Kerberos context * @param crypto Kerberos crypto context * @param usage Key usage for this buffer * @param data array of buffers to process * @param num_data length of array * @param ivec initial cbc/cts vector * * @return Return an error code or 0. * @ingroup krb5_crypto * * Kerberos encrypted data look like this: * * 1. KRB5_CRYPTO_TYPE_HEADER * 2. array [1,...] KRB5_CRYPTO_TYPE_DATA and array [0,...] * KRB5_CRYPTO_TYPE_SIGN_ONLY in any order, however the receiver * have to aware of the order. KRB5_CRYPTO_TYPE_SIGN_ONLY is * commonly used headers and trailers. * 3. KRB5_CRYPTO_TYPE_PADDING, at least on padsize long if padsize > 1 * 4. KRB5_CRYPTO_TYPE_TRAILER */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_encrypt_iov_ivec ( krb5_context /*context*/, krb5_crypto /*crypto*/, unsigned /*usage*/, krb5_crypto_iov */*data*/, int /*num_data*/, void */*ivec*/); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_encrypt_ivec ( krb5_context /*context*/, krb5_crypto /*crypto*/, unsigned /*usage*/, const void */*data*/, size_t /*len*/, krb5_data */*result*/, void */*ivec*/); /** * Disable encryption type * * @param context Kerberos 5 context * @param enctype encryption type to disable * * @return Return an error code or 0. * * @ingroup krb5_crypto */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_enctype_disable ( krb5_context /*context*/, krb5_enctype /*enctype*/); /** * Enable encryption type * * @param context Kerberos 5 context * @param enctype encryption type to enable * * @return Return an error code or 0. * * @ingroup krb5_crypto */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_enctype_enable ( krb5_context /*context*/, krb5_enctype /*enctype*/); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_enctype_keybits ( krb5_context /*context*/, krb5_enctype /*type*/, size_t */*keybits*/); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_enctype_keysize ( krb5_context /*context*/, krb5_enctype /*type*/, size_t */*keysize*/); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_enctype_to_keytype ( krb5_context /*context*/, krb5_enctype /*etype*/, krb5_keytype */*keytype*/); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_enctype_to_string ( krb5_context /*context*/, krb5_enctype /*etype*/, char **/*string*/); /** * Check if a enctype is valid, return 0 if it is. * * @param context Kerberos context * @param etype enctype to check if its valid or not * * @return Return an error code for an failure or 0 on success (enctype valid). * @ingroup krb5_crypto */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_enctype_valid ( krb5_context /*context*/, krb5_enctype /*etype*/); /** * Deprecated: keytypes doesn't exists, they are really enctypes. * * @ingroup krb5_deprecated */ KRB5_LIB_FUNCTION krb5_boolean KRB5_LIB_CALL krb5_enctypes_compatible_keys ( krb5_context /*context*/, krb5_enctype /*etype1*/, krb5_enctype /*etype2*/) KRB5_DEPRECATED_FUNCTION("Use X instead"); krb5_error_code krb5_enomem (krb5_context /*context*/); /** * Log a warning to the log, default stderr, include bthe error from * the last failure and then exit. * * @param context A Kerberos 5 context * @param eval the exit code to exit with * @param code error code of the last error * @param fmt message to print * * @ingroup krb5_error */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_err ( krb5_context /*context*/, int /*eval*/, krb5_error_code /*code*/, const char */*fmt*/, ...) __attribute__ ((__noreturn__, __format__ (__printf__, 4, 5))); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_error_from_rd_error ( krb5_context /*context*/, const krb5_error */*error*/, const krb5_creds */*creds*/); /** * Log a warning to the log, default stderr, and then exit. * * @param context A Kerberos 5 context * @param eval the exit code to exit with * @param fmt message to print * * @ingroup krb5_error */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_errx ( krb5_context /*context*/, int /*eval*/, const char */*fmt*/, ...) __attribute__ ((__noreturn__, __format__ (__printf__, 3, 4))); /** * krb5_expand_hostname() tries to make orig_hostname into a more * canonical one in the newly allocated space returned in * new_hostname. * @param context a Keberos context * @param orig_hostname hostname to canonicalise. * @param new_hostname output hostname, caller must free hostname with * krb5_xfree(). * * @return Return an error code or 0, see krb5_get_error_message(). * * @ingroup krb5_support */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_expand_hostname ( krb5_context /*context*/, const char */*orig_hostname*/, char **/*new_hostname*/); /** * krb5_expand_hostname_realms() expands orig_hostname to a name we * believe to be a hostname in newly allocated space in new_hostname * and return the realms new_hostname is believed to belong to in * realms. * * @param context a Keberos context * @param orig_hostname hostname to canonicalise. * @param new_hostname output hostname, caller must free hostname with * krb5_xfree(). * @param realms output possible realms, is an array that is terminated * with NULL. Caller must free with krb5_free_host_realm(). * * @return Return an error code or 0, see krb5_get_error_message(). * * @ingroup krb5_support */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_expand_hostname_realms ( krb5_context /*context*/, const char */*orig_hostname*/, char **/*new_hostname*/, char ***/*realms*/); KRB5_LIB_FUNCTION PA_DATA * KRB5_LIB_CALL krb5_find_padata ( PA_DATA */*val*/, unsigned /*len*/, int /*type*/, int */*idx*/); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_format_time ( krb5_context /*context*/, time_t /*t*/, char */*s*/, size_t /*len*/, krb5_boolean /*include_time*/); /** * krb5_free_address frees the data stored in the address that is * alloced with any of the krb5_address functions. * * @param context a Keberos context * @param address addresss to be freed. * * @return Return an error code or 0. * * @ingroup krb5_address */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_free_address ( krb5_context /*context*/, krb5_address */*address*/); /** * krb5_free_addresses frees the data stored in the address that is * alloced with any of the krb5_address functions. * * @param context a Keberos context * @param addresses addressses to be freed. * * @return Return an error code or 0. * * @ingroup krb5_address */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_free_addresses ( krb5_context /*context*/, krb5_addresses */*addresses*/); KRB5_LIB_FUNCTION void KRB5_LIB_CALL krb5_free_ap_rep_enc_part ( krb5_context /*context*/, krb5_ap_rep_enc_part */*val*/); KRB5_LIB_FUNCTION void KRB5_LIB_CALL krb5_free_authenticator ( krb5_context /*context*/, krb5_authenticator */*authenticator*/); KRB5_LIB_FUNCTION void KRB5_LIB_CALL krb5_free_checksum ( krb5_context /*context*/, krb5_checksum */*cksum*/); KRB5_LIB_FUNCTION void KRB5_LIB_CALL krb5_free_checksum_contents ( krb5_context /*context*/, krb5_checksum */*cksum*/); /** * Free a list of configuration files. * * @param filenames list, terminated with a NULL pointer, to be * freed. NULL is an valid argument. * * @return Returns 0 to indicate success. Otherwise an kerberos et * error code is returned, see krb5_get_error_message(). * * @ingroup krb5 */ KRB5_LIB_FUNCTION void KRB5_LIB_CALL krb5_free_config_files (char **/*filenames*/); /** * Frees the krb5_context allocated by krb5_init_context(). * * @param context context to be freed. * * @ingroup krb5 */ KRB5_LIB_FUNCTION void KRB5_LIB_CALL krb5_free_context (krb5_context /*context*/); /** * Free content of krb5_creds. * * @param context Kerberos 5 context. * @param c krb5_creds to free. * * @return Returns 0 to indicate success. Otherwise an kerberos et * error code is returned, see krb5_get_error_message(). * * @ingroup krb5 */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_free_cred_contents ( krb5_context /*context*/, krb5_creds */*c*/); /** * Free krb5_creds. * * @param context Kerberos 5 context. * @param c krb5_creds to free. * * @return Returns 0 to indicate success. Otherwise an kerberos et * error code is returned, see krb5_get_error_message(). * * @ingroup krb5 */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_free_creds ( krb5_context /*context*/, krb5_creds */*c*/); /** * Deprecated: use krb5_free_cred_contents() * * @ingroup krb5_deprecated */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_free_creds_contents ( krb5_context /*context*/, krb5_creds */*c*/) KRB5_DEPRECATED_FUNCTION("Use X instead"); /** * Free krb5_data (and its content). * * @param context Kerberos 5 context. * @param p krb5_data to free. * * @ingroup krb5 */ KRB5_LIB_FUNCTION void KRB5_LIB_CALL krb5_free_data ( krb5_context /*context*/, krb5_data */*p*/); /** * Same as krb5_data_free(). MIT compat. * * Deprecated: use krb5_data_free(). * * @param context Kerberos 5 context. * @param data krb5_data to free. * * @ingroup krb5_deprecated */ KRB5_LIB_FUNCTION void KRB5_LIB_CALL krb5_free_data_contents ( krb5_context /*context*/, krb5_data */*data*/) KRB5_DEPRECATED_FUNCTION("Use X instead"); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_free_default_realm ( krb5_context /*context*/, krb5_realm /*realm*/); KRB5_LIB_FUNCTION void KRB5_LIB_CALL krb5_free_error ( krb5_context /*context*/, krb5_error */*error*/); KRB5_LIB_FUNCTION void KRB5_LIB_CALL krb5_free_error_contents ( krb5_context /*context*/, krb5_error */*error*/); /** * Free the error message returned by krb5_get_error_message(). * * @param context Kerberos context * @param msg error message to free, returned byg * krb5_get_error_message(). * * @ingroup krb5_error */ KRB5_LIB_FUNCTION void KRB5_LIB_CALL krb5_free_error_message ( krb5_context /*context*/, const char */*msg*/); /** * Free the error message returned by krb5_get_error_string(). * * Deprecated: use krb5_free_error_message() * * @param context Kerberos context * @param str error message to free * * @ingroup krb5_deprecated */ KRB5_LIB_FUNCTION void KRB5_LIB_CALL krb5_free_error_string ( krb5_context /*context*/, char */*str*/) KRB5_DEPRECATED_FUNCTION("Use X instead"); /** * Free all memory allocated by `realmlist' * * @param context A Kerberos 5 context. * @param realmlist realmlist to free, NULL is ok * * @return a Kerberos error code, always 0. * * @ingroup krb5_support */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_free_host_realm ( krb5_context /*context*/, krb5_realm */*realmlist*/); /** * Variable containing the FILE based credential cache implemention. * * @ingroup krb5_ccache */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_free_kdc_rep ( krb5_context /*context*/, krb5_kdc_rep */*rep*/); /** * Free a keyblock, also zero out the content of the keyblock, uses * krb5_free_keyblock_contents() to free the content. * * @param context a Kerberos 5 context * @param keyblock keyblock to free, NULL is valid argument * * @ingroup krb5_crypto */ KRB5_LIB_FUNCTION void KRB5_LIB_CALL krb5_free_keyblock ( krb5_context /*context*/, krb5_keyblock */*keyblock*/); /** * Free a keyblock's content, also zero out the content of the keyblock. * * @param context a Kerberos 5 context * @param keyblock keyblock content to free, NULL is valid argument * * @ingroup krb5_crypto */ KRB5_LIB_FUNCTION void KRB5_LIB_CALL krb5_free_keyblock_contents ( krb5_context /*context*/, krb5_keyblock */*keyblock*/); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_free_krbhst ( krb5_context /*context*/, char **/*hostlist*/); /** * Free a name canonicalization rule iterator. */ KRB5_LIB_FUNCTION void KRB5_LIB_CALL krb5_free_name_canon_iterator ( krb5_context /*context*/, krb5_name_canon_iterator /*iter*/); /** * Frees a Kerberos principal allocated by the library with * krb5_parse_name(), krb5_make_principal() or any other related * principal functions. * * @param context A Kerberos context. * @param p a principal to free. * * @return An krb5 error code, see krb5_get_error_message(). * * @ingroup krb5_principal */ KRB5_LIB_FUNCTION void KRB5_LIB_CALL krb5_free_principal ( krb5_context /*context*/, krb5_principal /*p*/); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_free_salt ( krb5_context /*context*/, krb5_salt /*salt*/); /** * Free ticket and content * * @param context a Kerberos 5 context * @param ticket ticket to free * * @return Returns 0 to indicate success. Otherwise an kerberos et * error code is returned, see krb5_get_error_message(). * * @ingroup krb5 */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_free_ticket ( krb5_context /*context*/, krb5_ticket */*ticket*/); /** * Deprecated: use krb5_xfree(). * * @ingroup krb5_deprecated */ KRB5_LIB_FUNCTION void KRB5_LIB_CALL krb5_free_unparsed_name ( krb5_context /*context*/, char */*str*/) KRB5_DEPRECATED_FUNCTION("Use X instead"); /** * Forward credentials for client to host hostname , making them * forwardable if forwardable, and returning the blob of data to sent * in out_data. If hostname == NULL, pick it from server. * * @param context A kerberos 5 context. * @param auth_context the auth context with the key to encrypt the out_data. * @param hostname the host to forward the tickets too. * @param client the client to delegate from. * @param server the server to delegate the credential too. * @param ccache credential cache to use. * @param forwardable make the forwarded ticket forwabledable. * @param out_data the resulting credential. * * @return Return an error code or 0. * * @ingroup krb5_credential */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_fwd_tgt_creds ( krb5_context /*context*/, krb5_auth_context /*auth_context*/, const char */*hostname*/, krb5_principal /*client*/, krb5_principal /*server*/, krb5_ccache /*ccache*/, int /*forwardable*/, krb5_data */*out_data*/); /** * Fill buffer buf with len bytes of PRNG randomness that is ok to use * for key generation, padding and public diclosing the randomness w/o * disclosing the randomness source. * * This function can fail, and callers must check the return value. * * @param buf a buffer to fill with randomness * @param len length of memory that buf points to. * * @return return 0 on success or HEIM_ERR_RANDOM_OFFLINE if the * funcation failed to initialize the randomness source. * * @ingroup krb5_crypto */ HEIMDAL_WARN_UNUSED_RESULT_ATTRIBUTE KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_generate_random ( void */*buf*/, size_t /*len*/); /** * Fill buffer buf with len bytes of PRNG randomness that is ok to use * for key generation, padding and public diclosing the randomness w/o * disclosing the randomness source. * * This function can NOT fail, instead it will abort() and program will crash. * * If this function is called after a successful krb5_init_context(), * the chance of it failing is low due to that krb5_init_context() * pulls out some random, and quite commonly the randomness sources * will not fail once it have started to produce good output, * /dev/urandom behavies that way. * * @param buf a buffer to fill with randomness * @param len length of memory that buf points to. * * @ingroup krb5_crypto */ KRB5_LIB_FUNCTION void KRB5_LIB_CALL krb5_generate_random_block ( void */*buf*/, size_t /*len*/); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_generate_random_keyblock ( krb5_context /*context*/, krb5_enctype /*type*/, krb5_keyblock */*key*/); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_generate_seq_number ( krb5_context /*context*/, const krb5_keyblock */*key*/, uint32_t */*seqno*/); /** * Deprecated: use krb5_generate_subkey_extended() * * @ingroup krb5_deprecated */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_generate_subkey ( krb5_context /*context*/, const krb5_keyblock */*key*/, krb5_keyblock **/*subkey*/) KRB5_DEPRECATED_FUNCTION("Use X instead"); /** * Generate subkey, from keyblock * * @param context kerberos context * @param key session key * @param etype encryption type of subkey, if ETYPE_NULL, use key's enctype * @param subkey returned new, free with krb5_free_keyblock(). * * @return 0 on success or a Kerberos 5 error code * * @ingroup krb5_crypto */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_generate_subkey_extended ( krb5_context /*context*/, const krb5_keyblock */*key*/, krb5_enctype /*etype*/, krb5_keyblock **/*subkey*/); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_get_all_client_addrs ( krb5_context /*context*/, krb5_addresses */*res*/); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_get_all_server_addrs ( krb5_context /*context*/, krb5_addresses */*res*/); /** * Deprecated: use krb5_get_credentials_with_flags(). * * @ingroup krb5_deprecated */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_get_cred_from_kdc ( krb5_context /*context*/, krb5_ccache /*ccache*/, krb5_creds */*in_creds*/, krb5_creds **/*out_creds*/, krb5_creds ***/*ret_tgts*/) KRB5_DEPRECATED_FUNCTION("Use X instead"); /** * Deprecated: use krb5_get_credentials_with_flags(). * * @ingroup krb5_deprecated */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_get_cred_from_kdc_opt ( krb5_context /*context*/, krb5_ccache /*ccache*/, krb5_creds */*in_creds*/, krb5_creds **/*out_creds*/, krb5_creds ***/*ret_tgts*/, krb5_flags /*flags*/) KRB5_DEPRECATED_FUNCTION("Use X instead"); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_get_credentials ( krb5_context /*context*/, krb5_flags /*options*/, krb5_ccache /*ccache*/, krb5_creds */*in_creds*/, krb5_creds **/*out_creds*/); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_get_credentials_with_flags ( krb5_context /*context*/, krb5_flags /*options*/, krb5_kdc_flags /*flags*/, krb5_ccache /*ccache*/, krb5_creds */*in_creds*/, krb5_creds **/*out_creds*/); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_get_creds ( krb5_context /*context*/, krb5_get_creds_opt /*opt*/, krb5_ccache /*ccache*/, krb5_const_principal /*inprinc*/, krb5_creds **/*out_creds*/); KRB5_LIB_FUNCTION void KRB5_LIB_CALL krb5_get_creds_opt_add_options ( krb5_context /*context*/, krb5_get_creds_opt /*opt*/, krb5_flags /*options*/); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_get_creds_opt_alloc ( krb5_context /*context*/, krb5_get_creds_opt */*opt*/); KRB5_LIB_FUNCTION void KRB5_LIB_CALL krb5_get_creds_opt_free ( krb5_context /*context*/, krb5_get_creds_opt /*opt*/); KRB5_LIB_FUNCTION void KRB5_LIB_CALL krb5_get_creds_opt_set_enctype ( krb5_context /*context*/, krb5_get_creds_opt /*opt*/, krb5_enctype /*enctype*/); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_get_creds_opt_set_impersonate ( krb5_context /*context*/, krb5_get_creds_opt /*opt*/, krb5_const_principal /*self*/); KRB5_LIB_FUNCTION void KRB5_LIB_CALL krb5_get_creds_opt_set_options ( krb5_context /*context*/, krb5_get_creds_opt /*opt*/, krb5_flags /*options*/); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_get_creds_opt_set_ticket ( krb5_context /*context*/, krb5_get_creds_opt /*opt*/, const Ticket */*ticket*/); /** * Get the global configuration list. * * @param pfilenames return array of filenames, should be freed with krb5_free_config_files(). * * @return Returns 0 to indicate success. Otherwise an kerberos et * error code is returned, see krb5_get_error_message(). * * @ingroup krb5 */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_get_default_config_files (char ***/*pfilenames*/); /** * Get the default encryption types that will be use in communcation * with the KDC, clients and servers. * * @param context Kerberos 5 context. * @param pdu_type request type (AS, TGS or none) * @param etypes Encryption types, array terminated with * ETYPE_NULL(0), caller should free array with krb5_xfree(): * * @return Returns 0 to indicate success. Otherwise an kerberos et * error code is returned, see krb5_get_error_message(). * * @ingroup krb5 */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_get_default_in_tkt_etypes ( krb5_context /*context*/, krb5_pdu /*pdu_type*/, krb5_enctype **/*etypes*/); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_get_default_principal ( krb5_context /*context*/, krb5_principal */*princ*/); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_get_default_realm ( krb5_context /*context*/, krb5_realm */*realm*/); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_get_default_realms ( krb5_context /*context*/, krb5_realm **/*realms*/); /** * Get if the library uses DNS to canonicalize hostnames. * * @param context Kerberos 5 context. * * @return return non zero if the library uses DNS to canonicalize hostnames. * * @ingroup krb5 */ KRB5_LIB_FUNCTION krb5_boolean KRB5_LIB_CALL krb5_get_dns_canonicalize_hostname (krb5_context /*context*/); /** * Return the error string for the error code. The caller must not * free the string. * * This function is deprecated since its not threadsafe. * * @param context Kerberos 5 context. * @param code Kerberos error code. * * @return the error message matching code * * @ingroup krb5 */ KRB5_LIB_FUNCTION const char* KRB5_LIB_CALL krb5_get_err_text ( krb5_context /*context*/, krb5_error_code /*code*/) KRB5_DEPRECATED_FUNCTION("Use krb5_get_error_message instead"); /** * Return the error message for `code' in context. On memory * allocation error the function returns NULL. * * @param context Kerberos 5 context * @param code Error code related to the error * * @return an error string, needs to be freed with * krb5_free_error_message(). The functions return NULL on error. * * @ingroup krb5_error */ KRB5_LIB_FUNCTION const char * KRB5_LIB_CALL krb5_get_error_message ( krb5_context /*context*/, krb5_error_code /*code*/); /** * Return the error message in context. On error or no error string, * the function returns NULL. * * @param context Kerberos 5 context * * @return an error string, needs to be freed with * krb5_free_error_message(). The functions return NULL on error. * * @ingroup krb5_error */ KRB5_LIB_FUNCTION char * KRB5_LIB_CALL krb5_get_error_string (krb5_context /*context*/) KRB5_DEPRECATED_FUNCTION("Use krb5_get_error_message instead"); /** * Get extra address to the address list that the library will add to * the client's address list when communicating with the KDC. * * @param context Kerberos 5 context. * @param addresses addreses to set * * @return Returns 0 to indicate success. Otherwise an kerberos et * error code is returned, see krb5_get_error_message(). * * @ingroup krb5 */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_get_extra_addresses ( krb5_context /*context*/, krb5_addresses */*addresses*/); /** * Get version of fcache that the library should use. * * @param context Kerberos 5 context. * @param version version number. * * @return Returns 0 to indicate success. Otherwise an kerberos et * error code is returned, see krb5_get_error_message(). * * @ingroup krb5 */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_get_fcache_version ( krb5_context /*context*/, int */*version*/); /** * Gets tickets forwarded to hostname. If the tickets that are * forwarded are address-less, the forwarded tickets will also be * address-less. * * If the ticket have any address, hostname will be used for figure * out the address to forward the ticket too. This since this might * use DNS, its insecure and also doesn't represent configured all * addresses of the host. For example, the host might have two * adresses, one IPv4 and one IPv6 address where the later is not * published in DNS. This IPv6 address might be used communications * and thus the resulting ticket useless. * * @param context A kerberos 5 context. * @param auth_context the auth context with the key to encrypt the out_data. * @param ccache credential cache to use * @param flags the flags to control the resulting ticket flags * @param hostname the host to forward the tickets too. * @param in_creds the in client and server ticket names. The client * and server components forwarded to the remote host. * @param out_data the resulting credential. * * @return Return an error code or 0. * * @ingroup krb5_credential */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_get_forwarded_creds ( krb5_context /*context*/, krb5_auth_context /*auth_context*/, krb5_ccache /*ccache*/, krb5_flags /*flags*/, const char */*hostname*/, krb5_creds */*in_creds*/, krb5_data */*out_data*/); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_get_host_realm ( krb5_context /*context*/, const char */*targethost*/, krb5_realm **/*realms*/); /** * Get extra addresses to ignore when fetching addresses from the * underlaying operating system. * * @param context Kerberos 5 context. * @param addresses list addreses ignored * * @return Returns 0 to indicate success. Otherwise an kerberos et * error code is returned, see krb5_get_error_message(). * * @ingroup krb5 */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_get_ignore_addresses ( krb5_context /*context*/, krb5_addresses */*addresses*/); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_get_in_cred ( krb5_context /*context*/, krb5_flags /*options*/, const krb5_addresses */*addrs*/, const krb5_enctype */*etypes*/, const krb5_preauthtype */*ptypes*/, const krb5_preauthdata */*preauth*/, krb5_key_proc /*key_proc*/, krb5_const_pointer /*keyseed*/, krb5_decrypt_proc /*decrypt_proc*/, krb5_const_pointer /*decryptarg*/, krb5_creds */*creds*/, krb5_kdc_rep */*ret_as_reply*/) KRB5_DEPRECATED_FUNCTION("Use X instead"); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_get_in_tkt ( krb5_context /*context*/, krb5_flags /*options*/, const krb5_addresses */*addrs*/, const krb5_enctype */*etypes*/, const krb5_preauthtype */*ptypes*/, krb5_key_proc /*key_proc*/, krb5_const_pointer /*keyseed*/, krb5_decrypt_proc /*decrypt_proc*/, krb5_const_pointer /*decryptarg*/, krb5_creds */*creds*/, krb5_ccache /*ccache*/, krb5_kdc_rep */*ret_as_reply*/) KRB5_DEPRECATED_FUNCTION("Use X instead"); /** * Deprecated: use krb5_get_init_creds() and friends. * * @ingroup krb5_deprecated */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_get_in_tkt_with_keytab ( krb5_context /*context*/, krb5_flags /*options*/, krb5_addresses */*addrs*/, const krb5_enctype */*etypes*/, const krb5_preauthtype */*pre_auth_types*/, krb5_keytab /*keytab*/, krb5_ccache /*ccache*/, krb5_creds */*creds*/, krb5_kdc_rep */*ret_as_reply*/) KRB5_DEPRECATED_FUNCTION("Use X instead"); /** * Deprecated: use krb5_get_init_creds() and friends. * * @ingroup krb5_deprecated */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_get_in_tkt_with_password ( krb5_context /*context*/, krb5_flags /*options*/, krb5_addresses */*addrs*/, const krb5_enctype */*etypes*/, const krb5_preauthtype */*pre_auth_types*/, const char */*password*/, krb5_ccache /*ccache*/, krb5_creds */*creds*/, krb5_kdc_rep */*ret_as_reply*/) KRB5_DEPRECATED_FUNCTION("Use X instead"); /** * Deprecated: use krb5_get_init_creds() and friends. * * @ingroup krb5_deprecated */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_get_in_tkt_with_skey ( krb5_context /*context*/, krb5_flags /*options*/, krb5_addresses */*addrs*/, const krb5_enctype */*etypes*/, const krb5_preauthtype */*pre_auth_types*/, const krb5_keyblock */*key*/, krb5_ccache /*ccache*/, krb5_creds */*creds*/, krb5_kdc_rep */*ret_as_reply*/) KRB5_DEPRECATED_FUNCTION("Use X instead"); /** * Get new credentials using keyblock. * * @ingroup krb5_credential */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_get_init_creds_keyblock ( krb5_context /*context*/, krb5_creds */*creds*/, krb5_principal /*client*/, krb5_keyblock */*keyblock*/, krb5_deltat /*start_time*/, const char */*in_tkt_service*/, krb5_get_init_creds_opt */*options*/); /** * Get new credentials using keytab. * * @ingroup krb5_credential */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_get_init_creds_keytab ( krb5_context /*context*/, krb5_creds */*creds*/, krb5_principal /*client*/, krb5_keytab /*keytab*/, krb5_deltat /*start_time*/, const char */*in_tkt_service*/, krb5_get_init_creds_opt */*options*/); /** * Allocate a new krb5_get_init_creds_opt structure, free with * krb5_get_init_creds_opt_free(). * * @ingroup krb5_credential */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_get_init_creds_opt_alloc ( krb5_context /*context*/, krb5_get_init_creds_opt **/*opt*/); /** * Free krb5_get_init_creds_opt structure. * * @ingroup krb5_credential */ KRB5_LIB_FUNCTION void KRB5_LIB_CALL krb5_get_init_creds_opt_free ( krb5_context /*context*/, krb5_get_init_creds_opt */*opt*/); /** * Deprecated: use the new krb5_init_creds_init() and * krb5_init_creds_get_error(). * * @ingroup krb5_deprecated */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_get_init_creds_opt_get_error ( krb5_context /*context*/, krb5_get_init_creds_opt */*opt*/, KRB_ERROR **/*error*/) KRB5_DEPRECATED_FUNCTION("Use X instead"); /** * Deprecated: use krb5_get_init_creds_opt_alloc(). * * The reason krb5_get_init_creds_opt_init() is deprecated is that * krb5_get_init_creds_opt is a static structure and for ABI reason it * can't grow, ie can't add new functionality. * * @ingroup krb5_deprecated */ KRB5_LIB_FUNCTION void KRB5_LIB_CALL krb5_get_init_creds_opt_init (krb5_get_init_creds_opt */*opt*/) KRB5_DEPRECATED_FUNCTION("Use X instead"); KRB5_LIB_FUNCTION void KRB5_LIB_CALL krb5_get_init_creds_opt_set_address_list ( krb5_get_init_creds_opt */*opt*/, krb5_addresses */*addresses*/); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_get_init_creds_opt_set_addressless ( krb5_context /*context*/, krb5_get_init_creds_opt */*opt*/, krb5_boolean /*addressless*/); KRB5_LIB_FUNCTION void KRB5_LIB_CALL krb5_get_init_creds_opt_set_anonymous ( krb5_get_init_creds_opt */*opt*/, int /*anonymous*/); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_get_init_creds_opt_set_canonicalize ( krb5_context /*context*/, krb5_get_init_creds_opt */*opt*/, krb5_boolean /*req*/); KRB5_LIB_FUNCTION void KRB5_LIB_CALL krb5_get_init_creds_opt_set_change_password_prompt ( krb5_get_init_creds_opt */*opt*/, int /*change_password_prompt*/); KRB5_LIB_FUNCTION void KRB5_LIB_CALL krb5_get_init_creds_opt_set_default_flags ( krb5_context /*context*/, const char */*appname*/, krb5_const_realm /*realm*/, krb5_get_init_creds_opt */*opt*/); KRB5_LIB_FUNCTION void KRB5_LIB_CALL krb5_get_init_creds_opt_set_etype_list ( krb5_get_init_creds_opt */*opt*/, krb5_enctype */*etype_list*/, int /*etype_list_length*/); KRB5_LIB_FUNCTION void KRB5_LIB_CALL krb5_get_init_creds_opt_set_forwardable ( krb5_get_init_creds_opt */*opt*/, int /*forwardable*/); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_get_init_creds_opt_set_pa_password ( krb5_context /*context*/, krb5_get_init_creds_opt */*opt*/, const char */*password*/, krb5_s2k_proc /*key_proc*/); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_get_init_creds_opt_set_pac_request ( krb5_context /*context*/, krb5_get_init_creds_opt */*opt*/, krb5_boolean /*req_pac*/); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_get_init_creds_opt_set_pkinit ( krb5_context /*context*/, krb5_get_init_creds_opt */*opt*/, krb5_principal /*principal*/, const char */*user_id*/, const char */*x509_anchors*/, char * const * /*pool*/, char * const * /*pki_revoke*/, int /*flags*/, krb5_prompter_fct /*prompter*/, void */*prompter_data*/, char */*password*/); krb5_error_code KRB5_LIB_FUNCTION krb5_get_init_creds_opt_set_pkinit_user_certs ( krb5_context /*context*/, krb5_get_init_creds_opt */*opt*/, struct hx509_certs_data */*certs*/); KRB5_LIB_FUNCTION void KRB5_LIB_CALL krb5_get_init_creds_opt_set_preauth_list ( krb5_get_init_creds_opt */*opt*/, krb5_preauthtype */*preauth_list*/, int /*preauth_list_length*/); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_get_init_creds_opt_set_process_last_req ( krb5_context /*context*/, krb5_get_init_creds_opt */*opt*/, krb5_gic_process_last_req /*func*/, void */*ctx*/); KRB5_LIB_FUNCTION void KRB5_LIB_CALL krb5_get_init_creds_opt_set_proxiable ( krb5_get_init_creds_opt */*opt*/, int /*proxiable*/); KRB5_LIB_FUNCTION void KRB5_LIB_CALL krb5_get_init_creds_opt_set_renew_life ( krb5_get_init_creds_opt */*opt*/, krb5_deltat /*renew_life*/); KRB5_LIB_FUNCTION void KRB5_LIB_CALL krb5_get_init_creds_opt_set_salt ( krb5_get_init_creds_opt */*opt*/, krb5_data */*salt*/); KRB5_LIB_FUNCTION void KRB5_LIB_CALL krb5_get_init_creds_opt_set_tkt_life ( krb5_get_init_creds_opt */*opt*/, krb5_deltat /*tkt_life*/); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_get_init_creds_opt_set_win2k ( krb5_context /*context*/, krb5_get_init_creds_opt */*opt*/, krb5_boolean /*req*/); /** * Get new credentials using password. * * @ingroup krb5_credential */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_get_init_creds_password ( krb5_context /*context*/, krb5_creds */*creds*/, krb5_principal /*client*/, const char */*password*/, krb5_prompter_fct /*prompter*/, void */*data*/, krb5_deltat /*start_time*/, const char */*in_tkt_service*/, krb5_get_init_creds_opt */*options*/); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_get_kdc_cred ( krb5_context /*context*/, krb5_ccache /*id*/, krb5_kdc_flags /*flags*/, krb5_addresses */*addresses*/, Ticket */*second_ticket*/, krb5_creds */*in_creds*/, krb5_creds **out_creds ); /** * Get current offset in time to the KDC. * * @param context Kerberos 5 context. * @param sec seconds part of offset. * @param usec micro seconds part of offset. * * @return returns zero * * @ingroup krb5 */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_get_kdc_sec_offset ( krb5_context /*context*/, int32_t */*sec*/, int32_t */*usec*/); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_get_krb524hst ( krb5_context /*context*/, const krb5_realm */*realm*/, char ***/*hostlist*/); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_get_krb_admin_hst ( krb5_context /*context*/, const krb5_realm */*realm*/, char ***/*hostlist*/); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_get_krb_changepw_hst ( krb5_context /*context*/, const krb5_realm */*realm*/, char ***/*hostlist*/); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_get_krbhst ( krb5_context /*context*/, const krb5_realm */*realm*/, char ***/*hostlist*/); /** * Get max time skew allowed. * * @param context Kerberos 5 context. * * @return timeskew in seconds. * * @ingroup krb5 */ KRB5_LIB_FUNCTION time_t KRB5_LIB_CALL krb5_get_max_time_skew (krb5_context /*context*/); /** * krb5_init_context() will get one random byte to make sure our * random is alive. Assumption is that once the non blocking * source allows us to pull bytes, its all seeded and allows us to * pull more bytes. * * Most Kerberos users calls krb5_init_context(), so this is * useful point where we can do the checking. */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_get_permitted_enctypes ( krb5_context /*context*/, krb5_enctype **/*etypes*/); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_get_pw_salt ( krb5_context /*context*/, krb5_const_principal /*principal*/, krb5_salt */*salt*/); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_get_renewed_creds ( krb5_context /*context*/, krb5_creds */*creds*/, krb5_const_principal /*client*/, krb5_ccache /*ccache*/, const char */*in_tkt_service*/); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_get_server_rcache ( krb5_context /*context*/, const krb5_data */*piece*/, krb5_rcache */*id*/); /** * Make the kerberos library default to the admin KDC. * * @param context Kerberos 5 context. * * @return boolean flag to telling the context will use admin KDC as the default KDC. * * @ingroup krb5 */ KRB5_LIB_FUNCTION krb5_boolean KRB5_LIB_CALL krb5_get_use_admin_kdc (krb5_context /*context*/); /** * Validate the newly fetch credential, see also krb5_verify_init_creds(). * * @param context a Kerberos 5 context * @param creds the credentials to verify * @param client the client name to match up * @param ccache the credential cache to use * @param service a service name to use, used with * krb5_sname_to_principal() to build a hostname to use to * verify. * * @ingroup krb5_ccache */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_get_validated_creds ( krb5_context /*context*/, krb5_creds */*creds*/, krb5_principal /*client*/, krb5_ccache /*ccache*/, char */*service*/); /** * Get the default logging facility. * * @param context A Kerberos 5 context * * @ingroup krb5_error */ KRB5_LIB_FUNCTION krb5_log_facility * KRB5_LIB_CALL krb5_get_warn_dest (krb5_context /*context*/); KRB5_LIB_FUNCTION size_t KRB5_LIB_CALL krb5_get_wrapped_length ( krb5_context /*context*/, krb5_crypto /*crypto*/, size_t /*data_len*/); KRB5_LIB_FUNCTION int KRB5_LIB_CALL krb5_getportbyname ( krb5_context /*context*/, const char */*service*/, const char */*proto*/, int /*default_port*/); /** * krb5_h_addr2addr works like krb5_h_addr2sockaddr with the exception * that it operates on a krb5_address instead of a struct sockaddr. * * @param context a Keberos context * @param af address family * @param haddr host address from struct hostent. * @param addr returned krb5_address. * * @return Return an error code or 0. * * @ingroup krb5_address */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_h_addr2addr ( krb5_context /*context*/, int /*af*/, const char */*haddr*/, krb5_address */*addr*/); /** * krb5_h_addr2sockaddr initializes a "struct sockaddr sa" from af and * the "struct hostent" (see gethostbyname(3) ) h_addr_list * component. The argument sa_size should initially contain the size * of the sa, and after the call, it will contain the actual length of * the address. * * @param context a Keberos context * @param af addresses * @param addr address * @param sa returned struct sockaddr * @param sa_size size of sa * @param port port to set in sa. * * @return Return an error code or 0. * * @ingroup krb5_address */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_h_addr2sockaddr ( krb5_context /*context*/, int /*af*/, const char */*addr*/, struct sockaddr */*sa*/, krb5_socklen_t */*sa_size*/, int /*port*/); /** * Convert the gethostname() error code (h_error) to a Kerberos et * error code. * * @param eai_errno contains the error code from gethostname(). * * @return Kerberos error code representing the gethostname errors. * * @ingroup krb5_error */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_h_errno_to_heim_errno (int /*eai_errno*/); KRB5_LIB_FUNCTION krb5_boolean KRB5_LIB_CALL krb5_have_error_string (krb5_context /*context*/) KRB5_DEPRECATED_FUNCTION("Use krb5_get_error_message instead"); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_hmac ( krb5_context /*context*/, krb5_cksumtype /*cktype*/, const void */*data*/, size_t /*len*/, unsigned /*usage*/, krb5_keyblock */*key*/, Checksum */*result*/); /** * Initializes the context structure and reads the configuration file * /etc/krb5.conf. The structure should be freed by calling * krb5_free_context() when it is no longer being used. * * @param context pointer to returned context * * @return Returns 0 to indicate success. Otherwise an errno code is * returned. Failure means either that something bad happened during * initialization (typically ENOMEM) or that Kerberos should not be * used ENXIO. If the function returns HEIM_ERR_RANDOM_OFFLINE, the * random source is not available and later Kerberos calls might fail. * * @ingroup krb5 */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_init_context (krb5_context */*context*/); /** * Free the krb5_init_creds_context allocated by krb5_init_creds_init(). * * @param context A Kerberos 5 context. * @param ctx The krb5_init_creds_context to free. * * @ingroup krb5_credential */ KRB5_LIB_FUNCTION void KRB5_LIB_CALL krb5_init_creds_free ( krb5_context /*context*/, krb5_init_creds_context /*ctx*/); /** * Get new credentials as setup by the krb5_init_creds_context. * * @param context A Kerberos 5 context. * @param ctx The krb5_init_creds_context to process. * * @ingroup krb5_credential */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_init_creds_get ( krb5_context /*context*/, krb5_init_creds_context /*ctx*/); /** * Extract the newly acquired credentials from krb5_init_creds_context * context. * * @param context A Kerberos 5 context. * @param ctx * @param cred credentials, free with krb5_free_cred_contents(). * * @return 0 for sucess or An Kerberos error code, see krb5_get_error_message(). */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_init_creds_get_creds ( krb5_context /*context*/, krb5_init_creds_context /*ctx*/, krb5_creds */*cred*/); /** * Get the last error from the transaction. * * @return Returns 0 or an error code * * @ingroup krb5_credential */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_init_creds_get_error ( krb5_context /*context*/, krb5_init_creds_context /*ctx*/, KRB_ERROR */*error*/); /** * Start a new context to get a new initial credential. * * @param context A Kerberos 5 context. * @param client The Kerberos principal to get the credential for, if * NULL is given, the default principal is used as determined by * krb5_get_default_principal(). * @param prompter * @param prompter_data * @param start_time the time the ticket should start to be valid or 0 for now. * @param options a options structure, can be NULL for default options. * @param rctx A new allocated free with krb5_init_creds_free(). * * @return 0 for success or an Kerberos 5 error code, see krb5_get_error_message(). * * @ingroup krb5_credential */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_init_creds_init ( krb5_context /*context*/, krb5_principal /*client*/, krb5_prompter_fct /*prompter*/, void */*prompter_data*/, krb5_deltat /*start_time*/, krb5_get_init_creds_opt */*options*/, krb5_init_creds_context */*rctx*/); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_init_creds_set_fast_ap_armor_service ( krb5_context /*context*/, krb5_init_creds_context /*ctx*/, krb5_const_principal /*armor_service*/); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_init_creds_set_fast_ccache ( krb5_context /*context*/, krb5_init_creds_context /*ctx*/, krb5_ccache /*fast_ccache*/); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_init_creds_set_keyblock ( krb5_context /*context*/, krb5_init_creds_context /*ctx*/, krb5_keyblock */*keyblock*/); /** * Set the keytab to use for authentication. * * @param context a Kerberos 5 context. * @param ctx ctx krb5_init_creds_context context. * @param keytab the keytab to read the key from. * * @return 0 for success, or an Kerberos 5 error code, see krb5_get_error_message(). * @ingroup krb5_credential */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_init_creds_set_keytab ( krb5_context /*context*/, krb5_init_creds_context /*ctx*/, krb5_keytab /*keytab*/); /** * Sets the password that will use for the request. * * @param context a Kerberos 5 context. * @param ctx ctx krb5_init_creds_context context. * @param password the password to use. * * @return 0 for success, or an Kerberos 5 error code, see krb5_get_error_message(). * @ingroup krb5_credential */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_init_creds_set_password ( krb5_context /*context*/, krb5_init_creds_context /*ctx*/, const char */*password*/); /** * Sets the service that the is requested. This call is only neede for * special initial tickets, by default the a krbtgt is fetched in the default realm. * * @param context a Kerberos 5 context. * @param ctx a krb5_init_creds_context context. * @param service the service given as a string, for example * "kadmind/admin". If NULL, the default krbtgt in the clients * realm is set. * * @return 0 for success, or an Kerberos 5 error code, see krb5_get_error_message(). * @ingroup krb5_credential */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_init_creds_set_service ( krb5_context /*context*/, krb5_init_creds_context /*ctx*/, const char */*service*/); /** * The core loop if krb5_get_init_creds() function family. Create the * packets and have the caller send them off to the KDC. * * If the caller want all work been done for them, use * krb5_init_creds_get() instead. * * @param context a Kerberos 5 context. * @param ctx ctx krb5_init_creds_context context. * @param in input data from KDC, first round it should be reset by krb5_data_zer(). * @param out reply to KDC. * @param hostinfo KDC address info, first round it can be NULL. * @param flags status of the round, if * KRB5_INIT_CREDS_STEP_FLAG_CONTINUE is set, continue one more round. * * @return 0 for success, or an Kerberos 5 error code, see * krb5_get_error_message(). * * @ingroup krb5_credential */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_init_creds_step ( krb5_context /*context*/, krb5_init_creds_context /*ctx*/, krb5_data */*in*/, krb5_data */*out*/, krb5_krbhst_info */*hostinfo*/, unsigned int */*flags*/); /** * * @ingroup krb5_credential */ krb5_error_code krb5_init_creds_store ( krb5_context /*context*/, krb5_init_creds_context /*ctx*/, krb5_ccache /*id*/); /** * Init the built-in ets in the Kerberos library. * * @param context kerberos context to add the ets too * * @ingroup krb5 */ KRB5_LIB_FUNCTION void KRB5_LIB_CALL krb5_init_ets (krb5_context /*context*/); /** @struct krb5plugin_kuserok_ftable_desc * * @brief Description of the krb5_kuserok(3) plugin facility. * * The krb5_kuserok(3) function is pluggable. The plugin is named * KRB5_PLUGIN_KUSEROK ("krb5_plugin_kuserok"), with a single minor * version, KRB5_PLUGIN_KUSEROK_VERSION_0 (0). * * The plugin for krb5_kuserok(3) consists of a data symbol referencing * a structure of type krb5plugin_kuserok_ftable, with four fields: * * @param init Plugin initialization function (see krb5-plugin(7)) * * @param minor_version The plugin minor version number (0) * * @param fini Plugin finalization function * * @param kuserok Plugin kuserok function * * The kuserok field is the plugin entry point that performs the * traditional kuserok operation however the plugin desires. It is * invoked in no particular order relative to other kuserok plugins, but * it has a 'rule' argument that indicates which plugin is intended to * act on the rule. The plugin kuserok function must return * KRB5_PLUGIN_NO_HANDLE if the rule is not applicable to it. * * The plugin kuserok function has the following arguments, in this * order: * * -# plug_ctx, the context value output by the plugin's init function * -# context, a krb5_context * -# rule, the kuserok rule being evaluated (from krb5.conf(5)) * -# flags * -# k5login_dir, configured location of k5login per-user files if any * -# luser, name of the local user account to which principal is attempting to access. * -# principal, the krb5_principal trying to access the luser account * -# result, a krb5_boolean pointer where the plugin will output its result * * @ingroup krb5_support */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_initlog ( krb5_context /*context*/, const char */*program*/, krb5_log_facility **/*fac*/); /** * Return TRUE (non zero) if the principal is a configuration * principal (generated part of krb5_cc_set_config()). Returns FALSE * (zero) if not a configuration principal. * * @param context a Keberos context * @param principal principal to check if it a configuration principal * * @ingroup krb5_ccache */ KRB5_LIB_FUNCTION krb5_boolean KRB5_LIB_CALL krb5_is_config_principal ( krb5_context /*context*/, krb5_const_principal /*principal*/); /** * Returns is the encryption is strong or weak * * @param context Kerberos 5 context * @param enctype encryption type to probe * * @return Returns true if encryption type is weak or is not supported. * * @ingroup krb5_crypto */ KRB5_LIB_FUNCTION krb5_boolean KRB5_LIB_CALL krb5_is_enctype_weak ( krb5_context /*context*/, krb5_enctype /*enctype*/); /** * Runtime check if the Kerberos library was complied with thread support. * * @return TRUE if the library was compiled with thread support, FALSE if not. * * @ingroup krb5 */ KRB5_LIB_FUNCTION krb5_boolean KRB5_LIB_CALL krb5_is_thread_safe (void); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_kcm_call ( krb5_context /*context*/, krb5_storage */*request*/, krb5_storage **/*response_p*/, krb5_data */*response_data_p*/); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_kcm_storage_request ( krb5_context /*context*/, uint16_t /*opcode*/, krb5_storage **/*storage_p*/); /** * Returns the list of Kerberos encryption types sorted in order of * most preferred to least preferred encryption type. Note that some * encryption types might be disabled, so you need to check with * krb5_enctype_valid() before using the encryption type. * * @return list of enctypes, terminated with ETYPE_NULL. Its a static * array completed into the Kerberos library so the content doesn't * need to be freed. * * @ingroup krb5 */ KRB5_LIB_FUNCTION const krb5_enctype * KRB5_LIB_CALL krb5_kerberos_enctypes (krb5_context /*context*/); /** * Get encryption type of a keyblock. * * @ingroup krb5_crypto */ KRB5_LIB_FUNCTION krb5_enctype KRB5_LIB_CALL krb5_keyblock_get_enctype (const krb5_keyblock */*block*/); /** * Fill in `key' with key data of type `enctype' from `data' of length * `size'. Key should be freed using krb5_free_keyblock_contents(). * * @return 0 on success or a Kerberos 5 error code * * @ingroup krb5_crypto */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_keyblock_init ( krb5_context /*context*/, krb5_enctype /*type*/, const void */*data*/, size_t /*size*/, krb5_keyblock */*key*/); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_keyblock_key_proc ( krb5_context /*context*/, krb5_keytype /*type*/, krb5_data */*salt*/, krb5_const_pointer /*keyseed*/, krb5_keyblock **/*key*/); /** * Zero out a keyblock * * @param keyblock keyblock to zero out * * @ingroup krb5_crypto */ KRB5_LIB_FUNCTION void KRB5_LIB_CALL krb5_keyblock_zero (krb5_keyblock */*keyblock*/); /** * Deprecated: use krb5_get_init_creds() and friends. * * @ingroup krb5_deprecated */ KRB5_LIB_FUNCTION krb5_error_code KRB5_CALLCONV krb5_keytab_key_proc ( krb5_context /*context*/, krb5_enctype /*enctype*/, krb5_salt /*salt*/, krb5_const_pointer /*keyseed*/, krb5_keyblock **/*key*/) KRB5_DEPRECATED_FUNCTION("Use X instead"); /** * Deprecated: keytypes doesn't exists, they are really enctypes. * * @ingroup krb5_deprecated */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_keytype_to_enctypes ( krb5_context /*context*/, krb5_keytype /*keytype*/, unsigned */*len*/, krb5_enctype **/*val*/) KRB5_DEPRECATED_FUNCTION("Use X instead"); /** * Deprecated: keytypes doesn't exists, they are really enctypes. * * @ingroup krb5_deprecated */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_keytype_to_enctypes_default ( krb5_context /*context*/, krb5_keytype /*keytype*/, unsigned */*len*/, krb5_enctype **/*val*/) KRB5_DEPRECATED_FUNCTION("Use X instead"); /** * Deprecated: keytypes doesn't exists, they are really enctypes in * most cases, use krb5_enctype_to_string(). * * @ingroup krb5_deprecated */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_keytype_to_string ( krb5_context /*context*/, krb5_keytype /*keytype*/, char **/*string*/) KRB5_DEPRECATED_FUNCTION("Use X instead"); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_krbhst_format_string ( krb5_context /*context*/, const krb5_krbhst_info */*host*/, char */*hostname*/, size_t /*hostlen*/); KRB5_LIB_FUNCTION void KRB5_LIB_CALL krb5_krbhst_free ( krb5_context /*context*/, krb5_krbhst_handle /*handle*/); /** * Return an `struct addrinfo *' for a KDC host. * * Returns an the struct addrinfo in in that corresponds to the * information in `host'. free:ing is handled by krb5_krbhst_free, so * the returned ai must not be released. * * @ingroup krb5 */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_krbhst_get_addrinfo ( krb5_context /*context*/, krb5_krbhst_info */*host*/, struct addrinfo **/*ai*/); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_krbhst_init ( krb5_context /*context*/, const char */*realm*/, unsigned int /*type*/, krb5_krbhst_handle */*handle*/); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_krbhst_init_flags ( krb5_context /*context*/, const char */*realm*/, unsigned int /*type*/, int /*flags*/, krb5_krbhst_handle */*handle*/); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_krbhst_next ( krb5_context /*context*/, krb5_krbhst_handle /*handle*/, krb5_krbhst_info **/*host*/); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_krbhst_next_as_string ( krb5_context /*context*/, krb5_krbhst_handle /*handle*/, char */*hostname*/, size_t /*hostlen*/); KRB5_LIB_FUNCTION void KRB5_LIB_CALL krb5_krbhst_reset ( krb5_context /*context*/, krb5_krbhst_handle /*handle*/); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_krbhst_set_hostname ( krb5_context /*context*/, krb5_krbhst_handle /*handle*/, const char */*hostname*/); /** * Add the entry in `entry' to the keytab `id'. * * @param context a Keberos context. * @param id a keytab. * @param entry the entry to add * * @return Return an error code or 0, see krb5_get_error_message(). * * @ingroup krb5_keytab */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_kt_add_entry ( krb5_context /*context*/, krb5_keytab /*id*/, krb5_keytab_entry */*entry*/); /** * Finish using the keytab in `id'. All resources will be released, * even on errors. * * @param context a Keberos context. * @param id keytab to close. * * @return Return an error code or 0, see krb5_get_error_message(). * * @ingroup krb5_keytab */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_kt_close ( krb5_context /*context*/, krb5_keytab /*id*/); /** * Compare `entry' against `principal, vno, enctype'. * Any of `principal, vno, enctype' might be 0 which acts as a wildcard. * Return TRUE if they compare the same, FALSE otherwise. * * @param context a Keberos context. * @param entry an entry to match with. * @param principal principal to match, NULL matches all principals. * @param vno key version to match, 0 matches all key version numbers. * @param enctype encryption type to match, 0 matches all encryption types. * * @return Return TRUE or match, FALSE if not matched. * * @ingroup krb5_keytab */ KRB5_LIB_FUNCTION krb5_boolean KRB5_LIB_CALL krb5_kt_compare ( krb5_context /*context*/, krb5_keytab_entry */*entry*/, krb5_const_principal /*principal*/, krb5_kvno /*vno*/, krb5_enctype /*enctype*/); /** * Copy the contents of `in' into `out'. * * @param context a Keberos context. * @param in the keytab entry to copy. * @param out the copy of the keytab entry, free with krb5_kt_free_entry(). * * @return Return an error code or 0, see krb5_get_error_message(). * * @ingroup krb5_keytab */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_kt_copy_entry_contents ( krb5_context /*context*/, const krb5_keytab_entry */*in*/, krb5_keytab_entry */*out*/); /** * Set `id' to the default keytab. * * @param context a Keberos context. * @param id the new default keytab. * * @return Return an error code or 0, see krb5_get_error_message(). * * @ingroup krb5_keytab */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_kt_default ( krb5_context /*context*/, krb5_keytab */*id*/); /** * Copy the name of the default modify keytab into `name'. * * @param context a Keberos context. * @param name buffer where the name will be written * @param namesize length of name * * @return Return an error code or 0, see krb5_get_error_message(). * * @ingroup krb5_keytab */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_kt_default_modify_name ( krb5_context /*context*/, char */*name*/, size_t /*namesize*/); /** * copy the name of the default keytab into `name'. * * @param context a Keberos context. * @param name buffer where the name will be written * @param namesize length of name * * @return Return an error code or 0, see krb5_get_error_message(). * * @ingroup krb5_keytab */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_kt_default_name ( krb5_context /*context*/, char */*name*/, size_t /*namesize*/); /** * Destroy (remove) the keytab in `id'. All resources will be released, * even on errors, does the equvalment of krb5_kt_close() on the resources. * * @param context a Keberos context. * @param id keytab to destroy. * * @return Return an error code or 0, see krb5_get_error_message(). * * @ingroup krb5_keytab */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_kt_destroy ( krb5_context /*context*/, krb5_keytab /*id*/); /** * Release all resources associated with `cursor'. * * @param context a Keberos context. * @param id a keytab. * @param cursor the cursor to free. * * @return Return an error code or 0, see krb5_get_error_message(). * * @ingroup krb5_keytab */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_kt_end_seq_get ( krb5_context /*context*/, krb5_keytab /*id*/, krb5_kt_cursor */*cursor*/); /** * Free the contents of `entry'. * * @param context a Keberos context. * @param entry the entry to free * * @return Return an error code or 0, see krb5_get_error_message(). * * @ingroup krb5_keytab */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_kt_free_entry ( krb5_context /*context*/, krb5_keytab_entry */*entry*/); /** * Retrieve the keytab entry for `principal, kvno, enctype' into `entry' * from the keytab `id'. Matching is done like krb5_kt_compare(). * * @param context a Keberos context. * @param id a keytab. * @param principal principal to match, NULL matches all principals. * @param kvno key version to match, 0 matches all key version numbers. * @param enctype encryption type to match, 0 matches all encryption types. * @param entry the returned entry, free with krb5_kt_free_entry(). * * @return Return an error code or 0, see krb5_get_error_message(). * * @ingroup krb5_keytab */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_kt_get_entry ( krb5_context /*context*/, krb5_keytab /*id*/, krb5_const_principal /*principal*/, krb5_kvno /*kvno*/, krb5_enctype /*enctype*/, krb5_keytab_entry */*entry*/); /** * Retrieve the full name of the keytab `keytab' and store the name in * `str'. * * @param context a Keberos context. * @param keytab keytab to get name for. * @param str the name of the keytab name, usee krb5_xfree() to free * the string. On error, *str is set to NULL. * * @return Return an error code or 0, see krb5_get_error_message(). * * @ingroup krb5_keytab */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_kt_get_full_name ( krb5_context /*context*/, krb5_keytab /*keytab*/, char **/*str*/); /** * Retrieve the name of the keytab `keytab' into `name', `namesize' * * @param context a Keberos context. * @param keytab the keytab to get the name for. * @param name name buffer. * @param namesize size of name buffer. * * @return Return an error code or 0, see krb5_get_error_message(). * * @ingroup krb5_keytab */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_kt_get_name ( krb5_context /*context*/, krb5_keytab /*keytab*/, char */*name*/, size_t /*namesize*/); /** * Return the type of the `keytab' in the string `prefix of length * `prefixsize'. * * @param context a Keberos context. * @param keytab the keytab to get the prefix for * @param prefix prefix buffer * @param prefixsize length of prefix buffer * * @return Return an error code or 0, see krb5_get_error_message(). * * @ingroup krb5_keytab */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_kt_get_type ( krb5_context /*context*/, krb5_keytab /*keytab*/, char */*prefix*/, size_t /*prefixsize*/); /** * Return true if the keytab exists and have entries * * @param context a Keberos context. * @param id a keytab. * * @return Return an error code or 0, see krb5_get_error_message(). * * @ingroup krb5_keytab */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_kt_have_content ( krb5_context /*context*/, krb5_keytab /*id*/); /** * Get the next entry from keytab, advance the cursor. On last entry * the function will return KRB5_KT_END. * * @param context a Keberos context. * @param id a keytab. * @param entry the returned entry, free with krb5_kt_free_entry(). * @param cursor the cursor of the iteration. * * @return Return an error code or 0, see krb5_get_error_message(). * * @ingroup krb5_keytab */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_kt_next_entry ( krb5_context /*context*/, krb5_keytab /*id*/, krb5_keytab_entry */*entry*/, krb5_kt_cursor */*cursor*/); /** * Read the key identified by `(principal, vno, enctype)' from the * keytab in `keyprocarg' (the default if == NULL) into `*key'. * * @param context a Keberos context. * @param keyprocarg * @param principal * @param vno * @param enctype * @param key * * @return Return an error code or 0, see krb5_get_error_message(). * * @ingroup krb5_keytab */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_kt_read_service_key ( krb5_context /*context*/, krb5_pointer /*keyprocarg*/, krb5_principal /*principal*/, krb5_kvno /*vno*/, krb5_enctype /*enctype*/, krb5_keyblock **/*key*/); /** * Register a new keytab backend. * * @param context a Keberos context. * @param ops a backend to register. * * @return Return an error code or 0, see krb5_get_error_message(). * * @ingroup krb5_keytab */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_kt_register ( krb5_context /*context*/, const krb5_kt_ops */*ops*/); /** * Remove an entry from the keytab, matching is done using * krb5_kt_compare(). * @param context a Keberos context. * @param id a keytab. * @param entry the entry to remove * * @return Return an error code or 0, see krb5_get_error_message(). * * @ingroup krb5_keytab */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_kt_remove_entry ( krb5_context /*context*/, krb5_keytab /*id*/, krb5_keytab_entry */*entry*/); /** * Resolve the keytab name (of the form `type:residual') in `name' * into a keytab in `id'. * * @param context a Keberos context. * @param name name to resolve * @param id resulting keytab, free with krb5_kt_close(). * * @return Return an error code or 0, see krb5_get_error_message(). * * @ingroup krb5_keytab */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_kt_resolve ( krb5_context /*context*/, const char */*name*/, krb5_keytab */*id*/); /** * Set `cursor' to point at the beginning of `id'. * * @param context a Keberos context. * @param id a keytab. * @param cursor a newly allocated cursor, free with krb5_kt_end_seq_get(). * * @return Return an error code or 0, see krb5_get_error_message(). * * @ingroup krb5_keytab */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_kt_start_seq_get ( krb5_context /*context*/, krb5_keytab /*id*/, krb5_kt_cursor */*cursor*/); /** * This function takes the name of a local user and checks if * principal is allowed to log in as that user. * * The user may have a ~/.k5login file listing principals that are * allowed to login as that user. If that file does not exist, all * principals with a only one component that is identical to the * username, and a realm considered local, are allowed access. * * The .k5login file must contain one principal per line, be owned by * user and not be writable by group or other (but must be readable by * anyone). * * Note that if the file exists, no implicit access rights are given * to user@@LOCALREALM. * * Optionally, a set of files may be put in ~/.k5login.d (a * directory), in which case they will all be checked in the same * manner as .k5login. The files may be called anything, but files * starting with a hash (#) , or ending with a tilde (~) are * ignored. Subdirectories are not traversed. Note that this directory * may not be checked by other Kerberos implementations. * * If no configuration file exists, match user against local domains, * ie luser@@LOCAL-REALMS-IN-CONFIGURATION-FILES. * * @param context Kerberos 5 context. * @param principal principal to check if allowed to login * @param luser local user id * * @return returns TRUE if access should be granted, FALSE otherwise. * * @ingroup krb5_support */ KRB5_LIB_FUNCTION krb5_boolean KRB5_LIB_CALL krb5_kuserok ( krb5_context /*context*/, krb5_principal /*principal*/, const char */*luser*/); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_log ( krb5_context /*context*/, krb5_log_facility */*fac*/, int /*level*/, const char */*fmt*/, ...) __attribute__ ((__format__ (__printf__, 4, 5))); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_log_msg ( krb5_context /*context*/, krb5_log_facility */*fac*/, int /*level*/, char **/*reply*/, const char */*fmt*/, ...) __attribute__ ((__format__ (__printf__, 5, 6))); /** * Create an address of type KRB5_ADDRESS_ADDRPORT from (addr, port) * * @param context a Keberos context * @param res built address from addr/port * @param addr address to use * @param port port to use * * @return Return an error code or 0. * * @ingroup krb5_address */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_make_addrport ( krb5_context /*context*/, krb5_address **/*res*/, const krb5_address */*addr*/, int16_t /*port*/); /** * Build a principal using vararg style building * * @param context A Kerberos context. * @param principal returned principal * @param realm realm name * @param ... a list of components ended with NULL. * * @return An krb5 error code, see krb5_get_error_message(). * * @ingroup krb5_principal */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_make_principal ( krb5_context /*context*/, krb5_principal */*principal*/, krb5_const_realm /*realm*/, ...); /** * krb5_max_sockaddr_size returns the max size of the .Li struct * sockaddr that the Kerberos library will return. * * @return Return an size_t of the maximum struct sockaddr. * * @ingroup krb5_address */ KRB5_LIB_FUNCTION size_t KRB5_LIB_CALL krb5_max_sockaddr_size (void); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_mk_error ( krb5_context /*context*/, krb5_error_code /*error_code*/, const char */*e_text*/, const krb5_data */*e_data*/, const krb5_principal /*client*/, const krb5_principal /*server*/, time_t */*client_time*/, int */*client_usec*/, krb5_data */*reply*/); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_mk_error_ext ( krb5_context /*context*/, krb5_error_code /*error_code*/, const char */*e_text*/, const krb5_data */*e_data*/, const krb5_principal /*server*/, const PrincipalName */*client_name*/, const Realm */*client_realm*/, time_t */*client_time*/, int */*client_usec*/, krb5_data */*reply*/); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_mk_priv ( krb5_context /*context*/, krb5_auth_context /*auth_context*/, const krb5_data */*userdata*/, krb5_data */*outbuf*/, krb5_replay_data */*outdata*/); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_mk_rep ( krb5_context /*context*/, krb5_auth_context /*auth_context*/, krb5_data */*outbuf*/); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_mk_req ( krb5_context /*context*/, krb5_auth_context */*auth_context*/, const krb5_flags /*ap_req_options*/, const char */*service*/, const char */*hostname*/, krb5_data */*in_data*/, krb5_ccache /*ccache*/, krb5_data */*outbuf*/); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_mk_req_exact ( krb5_context /*context*/, krb5_auth_context */*auth_context*/, const krb5_flags /*ap_req_options*/, const krb5_principal /*server*/, krb5_data */*in_data*/, krb5_ccache /*ccache*/, krb5_data */*outbuf*/); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_mk_req_extended ( krb5_context /*context*/, krb5_auth_context */*auth_context*/, const krb5_flags /*ap_req_options*/, krb5_data */*in_data*/, krb5_creds */*in_creds*/, krb5_data */*outbuf*/); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_mk_safe ( krb5_context /*context*/, krb5_auth_context /*auth_context*/, const krb5_data */*userdata*/, krb5_data */*outbuf*/, krb5_replay_data */*outdata*/); /** * Iteratively apply name canon rules, outputing a principal and rule * options each time. Iteration completes when the @iter is NULL on * return or when an error is returned. Callers must free the iterator * if they abandon it mid-way. * * @param context Kerberos context * @param iter name canon rule iterator (input/output) * @param try_princ output principal name * @param rule_opts output rule options */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_name_canon_iterate ( krb5_context /*context*/, krb5_name_canon_iterator */*iter*/, krb5_const_principal */*try_princ*/, krb5_name_canon_rule_options */*rule_opts*/); /** * Initialize name canonicalization iterator. * * @param context Kerberos context * @param in_princ principal name to be canonicalized OR * @param iter output iterator object */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_name_canon_iterator_start ( krb5_context /*context*/, krb5_const_principal /*in_princ*/, krb5_name_canon_iterator */*iter*/); /** * Read \a len bytes from socket \a p_fd into buffer \a buf. * Block until \a len bytes are read or until an error. * * @return If successful, the number of bytes read: \a len. * On end-of-file, 0. * On error, less than 0 (if single-threaded, the error can be found * in the errno global variable). */ KRB5_LIB_FUNCTION krb5_ssize_t KRB5_LIB_CALL krb5_net_read ( krb5_context /*context*/, void */*p_fd*/, void */*buf*/, size_t /*len*/); KRB5_LIB_FUNCTION krb5_ssize_t KRB5_LIB_CALL krb5_net_write ( krb5_context /*context*/, void */*p_fd*/, const void */*buf*/, size_t /*len*/); KRB5_LIB_FUNCTION krb5_ssize_t KRB5_LIB_CALL krb5_net_write_block ( krb5_context /*context*/, void */*p_fd*/, const void */*buf*/, size_t /*len*/, time_t /*timeout*/); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_ntlm_alloc ( krb5_context /*context*/, krb5_ntlm */*ntlm*/); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_ntlm_free ( krb5_context /*context*/, krb5_ntlm /*ntlm*/); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_ntlm_init_get_challenge ( krb5_context /*context*/, krb5_ntlm /*ntlm*/, krb5_data */*challenge*/); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_ntlm_init_get_flags ( krb5_context /*context*/, krb5_ntlm /*ntlm*/, uint32_t */*flags*/); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_ntlm_init_get_opaque ( krb5_context /*context*/, krb5_ntlm /*ntlm*/, krb5_data */*opaque*/); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_ntlm_init_get_targetinfo ( krb5_context /*context*/, krb5_ntlm /*ntlm*/, krb5_data */*data*/); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_ntlm_init_get_targetname ( krb5_context /*context*/, krb5_ntlm /*ntlm*/, char **/*name*/); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_ntlm_init_request ( krb5_context /*context*/, krb5_ntlm /*ntlm*/, krb5_realm /*realm*/, krb5_ccache /*ccache*/, uint32_t /*flags*/, const char */*hostname*/, const char */*domainname*/); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_ntlm_rep_get_sessionkey ( krb5_context /*context*/, krb5_ntlm /*ntlm*/, krb5_data */*data*/); KRB5_LIB_FUNCTION krb5_boolean KRB5_LIB_CALL krb5_ntlm_rep_get_status ( krb5_context /*context*/, krb5_ntlm /*ntlm*/); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_ntlm_req_set_flags ( krb5_context /*context*/, krb5_ntlm /*ntlm*/, uint32_t /*flags*/); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_ntlm_req_set_lm ( krb5_context /*context*/, krb5_ntlm /*ntlm*/, void */*hash*/, size_t /*len*/); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_ntlm_req_set_ntlm ( krb5_context /*context*/, krb5_ntlm /*ntlm*/, void */*hash*/, size_t /*len*/); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_ntlm_req_set_opaque ( krb5_context /*context*/, krb5_ntlm /*ntlm*/, krb5_data */*opaque*/); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_ntlm_req_set_session ( krb5_context /*context*/, krb5_ntlm /*ntlm*/, void */*sessionkey*/, size_t /*length*/); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_ntlm_req_set_targetname ( krb5_context /*context*/, krb5_ntlm /*ntlm*/, const char */*targetname*/); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_ntlm_req_set_username ( krb5_context /*context*/, krb5_ntlm /*ntlm*/, const char */*username*/); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_ntlm_request ( krb5_context /*context*/, krb5_ntlm /*ntlm*/, krb5_realm /*realm*/, krb5_ccache /*ccache*/); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_openlog ( krb5_context /*context*/, const char */*program*/, krb5_log_facility **/*fac*/); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_pac_add_buffer ( krb5_context /*context*/, krb5_pac /*p*/, uint32_t /*type*/, const krb5_data */*data*/); KRB5_LIB_FUNCTION void KRB5_LIB_CALL krb5_pac_free ( krb5_context /*context*/, krb5_pac /*pac*/); /** * Get the PAC buffer of specific type from the pac. * * @param context Kerberos 5 context. * @param p the pac structure returned by krb5_pac_parse(). * @param type type of buffer to get * @param data return data, free with krb5_data_free(). * * @return Returns 0 to indicate success. Otherwise an kerberos et * error code is returned, see krb5_get_error_message(). * * @ingroup krb5_pac */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_pac_get_buffer ( krb5_context /*context*/, krb5_pac /*p*/, uint32_t /*type*/, krb5_data */*data*/); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_pac_get_types ( krb5_context /*context*/, krb5_pac /*p*/, size_t */*len*/, uint32_t **/*types*/); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_pac_init ( krb5_context /*context*/, krb5_pac */*pac*/); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_pac_parse ( krb5_context /*context*/, const void */*ptr*/, size_t /*len*/, krb5_pac */*pac*/); /** * Verify the PAC. * * @param context Kerberos 5 context. * @param pac the pac structure returned by krb5_pac_parse(). * @param authtime The time of the ticket the PAC belongs to. * @param principal the principal to verify. * @param server The service key, most always be given. * @param privsvr The KDC key, may be given. * @return Returns 0 to indicate success. Otherwise an kerberos et * error code is returned, see krb5_get_error_message(). * * @ingroup krb5_pac */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_pac_verify ( krb5_context /*context*/, const krb5_pac /*pac*/, time_t /*authtime*/, krb5_const_principal /*principal*/, const krb5_keyblock */*server*/, const krb5_keyblock */*privsvr*/); KRB5_LIB_FUNCTION int KRB5_LIB_CALL krb5_padata_add ( krb5_context /*context*/, METHOD_DATA */*md*/, int /*type*/, void */*buf*/, size_t /*len*/); /** * krb5_parse_address returns the resolved hostname in string to the * krb5_addresses addresses . * * @param context a Keberos context * @param string * @param addresses * * @return Return an error code or 0. * * @ingroup krb5_address */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_parse_address ( krb5_context /*context*/, const char */*string*/, krb5_addresses */*addresses*/); /** * Parse a name into a krb5_principal structure * * @param context Kerberos 5 context * @param name name to parse into a Kerberos principal * @param principal returned principal, free with krb5_free_principal(). * * @return An krb5 error code, see krb5_get_error_message(). * * @ingroup krb5_principal */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_parse_name ( krb5_context /*context*/, const char */*name*/, krb5_principal */*principal*/); /** * Parse a name into a krb5_principal structure, flags controls the behavior. * * @param context Kerberos 5 context * @param name name to parse into a Kerberos principal * @param flags flags to control the behavior * @param principal returned principal, free with krb5_free_principal(). * * @return An krb5 error code, see krb5_get_error_message(). * * @ingroup krb5_principal */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_parse_name_flags ( krb5_context /*context*/, const char */*name*/, int /*flags*/, krb5_principal */*principal*/); /** * Parse nametype string and return a nametype integer * * @ingroup krb5_principal */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_parse_nametype ( krb5_context /*context*/, const char */*str*/, int32_t */*nametype*/); KRB5_LIB_FUNCTION const char* KRB5_LIB_CALL krb5_passwd_result_to_string ( krb5_context /*context*/, int /*result*/); /** * Deprecated: use krb5_get_init_creds() and friends. * * @ingroup krb5_deprecated */ KRB5_LIB_FUNCTION krb5_error_code KRB5_CALLCONV krb5_password_key_proc ( krb5_context /*context*/, krb5_enctype /*type*/, krb5_salt /*salt*/, krb5_const_pointer /*keyseed*/, krb5_keyblock **/*key*/) KRB5_DEPRECATED_FUNCTION("Use X instead"); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_pk_enterprise_cert ( krb5_context /*context*/, const char */*user_id*/, krb5_const_realm /*realm*/, krb5_principal */*principal*/, struct hx509_certs_data **/*res*/); /** * Register a plugin symbol name of specific type. * @param context a Keberos context * @param type type of plugin symbol * @param name name of plugin symbol * @param symbol a pointer to the named symbol * @return In case of error a non zero error com_err error is returned * and the Kerberos error string is set. * * @ingroup krb5_support */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_plugin_register ( krb5_context /*context*/, enum krb5_plugin_type /*type*/, const char */*name*/, void */*symbol*/); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_prepend_config_files ( const char */*filelist*/, char **/*pq*/, char ***/*ret_pp*/); /** * Prepend the filename to the global configuration list. * * @param filelist a filename to add to the default list of filename * @param pfilenames return array of filenames, should be freed with krb5_free_config_files(). * * @return Returns 0 to indicate success. Otherwise an kerberos et * error code is returned, see krb5_get_error_message(). * * @ingroup krb5 */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_prepend_config_files_default ( const char */*filelist*/, char ***/*pfilenames*/); /** * Prepend the context full error string for a specific error code. * The error that is stored should be internationalized. * * The if context is NULL, no error string is stored. * * @param context Kerberos 5 context * @param ret The error code * @param fmt Error string for the error code * @param ... printf(3) style parameters. * * @ingroup krb5_error */ KRB5_LIB_FUNCTION void KRB5_LIB_CALL krb5_prepend_error_message ( krb5_context /*context*/, krb5_error_code /*ret*/, const char */*fmt*/, ...) __attribute__ ((__format__ (__printf__, 3, 4))); /** * Deprecated: use krb5_principal_get_realm() * * @ingroup krb5_deprecated */ KRB5_LIB_FUNCTION krb5_realm * KRB5_LIB_CALL krb5_princ_realm ( krb5_context /*context*/, krb5_principal /*principal*/) KRB5_DEPRECATED_FUNCTION("Use X instead"); /** * Deprecated: use krb5_principal_set_realm() * * @ingroup krb5_deprecated */ KRB5_LIB_FUNCTION void KRB5_LIB_CALL krb5_princ_set_realm ( krb5_context /*context*/, krb5_principal /*principal*/, krb5_realm */*realm*/) KRB5_DEPRECATED_FUNCTION("Use X instead"); /** * Compares the two principals, including realm of the principals and returns * TRUE if they are the same and FALSE if not. * * @param context Kerberos 5 context * @param princ1 first principal to compare * @param princ2 second principal to compare * * @ingroup krb5_principal * @see krb5_principal_compare_any_realm() * @see krb5_realm_compare() */ KRB5_LIB_FUNCTION krb5_boolean KRB5_LIB_CALL krb5_principal_compare ( krb5_context /*context*/, krb5_const_principal /*princ1*/, krb5_const_principal /*princ2*/); /** * Return TRUE iff princ1 == princ2 (without considering the realm) * * @param context Kerberos 5 context * @param princ1 first principal to compare * @param princ2 second principal to compare * * @return non zero if equal, 0 if not * * @ingroup krb5_principal * @see krb5_principal_compare() * @see krb5_realm_compare() */ KRB5_LIB_FUNCTION krb5_boolean KRB5_LIB_CALL krb5_principal_compare_any_realm ( krb5_context /*context*/, krb5_const_principal /*princ1*/, krb5_const_principal /*princ2*/); KRB5_LIB_FUNCTION const char* KRB5_LIB_CALL krb5_principal_get_comp_string ( krb5_context /*context*/, krb5_const_principal /*principal*/, unsigned int /*component*/); /** * Get number of component is principal. * * @param context Kerberos 5 context * @param principal principal to query * * @return number of components in string * * @ingroup krb5_principal */ KRB5_LIB_FUNCTION unsigned int KRB5_LIB_CALL krb5_principal_get_num_comp ( krb5_context /*context*/, krb5_const_principal /*principal*/); /** * Get the realm of the principal * * @param context A Kerberos context. * @param principal principal to get the realm for * * @return realm of the principal, don't free or use after krb5_principal is freed * * @ingroup krb5_principal */ KRB5_LIB_FUNCTION const char* KRB5_LIB_CALL krb5_principal_get_realm ( krb5_context /*context*/, krb5_const_principal /*principal*/); /** * Get the type of the principal * * @param context A Kerberos context. * @param principal principal to get the type for * * @return the type of principal * * @ingroup krb5_principal */ KRB5_LIB_FUNCTION int KRB5_LIB_CALL krb5_principal_get_type ( krb5_context /*context*/, krb5_const_principal /*principal*/); /** * Returns true iff name is an WELLKNOWN:ORG.H5L.HOSTBASED-SERVICE * * @ingroup krb5_principal */ krb5_boolean KRB5_LIB_FUNCTION krb5_principal_is_gss_hostbased_service ( krb5_context /*context*/, krb5_const_principal /*principal*/); /** * Check if the cname part of the principal is a krbtgt principal * * @ingroup krb5_principal */ KRB5_LIB_FUNCTION krb5_boolean KRB5_LIB_CALL krb5_principal_is_krbtgt ( krb5_context /*context*/, krb5_const_principal /*p*/); /** * Returns true if name is Kerberos an LKDC realm * * @ingroup krb5_principal */ krb5_boolean KRB5_LIB_FUNCTION krb5_principal_is_lkdc ( krb5_context /*context*/, krb5_const_principal /*principal*/); /** * Returns true if name is Kerberos NULL name * * @ingroup krb5_principal */ krb5_boolean KRB5_LIB_FUNCTION krb5_principal_is_null ( krb5_context /*context*/, krb5_const_principal /*principal*/); /** * Returns true if name is Kerberos an LKDC realm * * @ingroup krb5_principal */ krb5_boolean KRB5_LIB_FUNCTION krb5_principal_is_pku2u ( krb5_context /*context*/, krb5_const_principal /*principal*/); /** * Check if the cname part of the principal is a initial or renewed krbtgt principal * * @ingroup krb5_principal */ krb5_boolean KRB5_LIB_FUNCTION krb5_principal_is_root_krbtgt ( krb5_context /*context*/, krb5_const_principal /*p*/); /** * return TRUE iff princ matches pattern * * @ingroup krb5_principal */ KRB5_LIB_FUNCTION krb5_boolean KRB5_LIB_CALL krb5_principal_match ( krb5_context /*context*/, krb5_const_principal /*princ*/, krb5_const_principal /*pattern*/); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_principal_set_comp_string ( krb5_context /*context*/, krb5_principal /*principal*/, unsigned int /*k*/, const char */*component*/); /** * Set a new realm for a principal, and as a side-effect free the * previous realm. * * @param context A Kerberos context. * @param principal principal set the realm for * @param realm the new realm to set * * @return An krb5 error code, see krb5_get_error_message(). * * @ingroup krb5_principal */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_principal_set_realm ( krb5_context /*context*/, krb5_principal /*principal*/, krb5_const_realm /*realm*/); /** * Set the type of the principal * * @param context A Kerberos context. * @param principal principal to set the type for * @param type the new type * * @return An krb5 error code, see krb5_get_error_message(). * * @ingroup krb5_principal */ KRB5_LIB_FUNCTION void KRB5_LIB_CALL krb5_principal_set_type ( krb5_context /*context*/, krb5_principal /*principal*/, int /*type*/); /** * krb5_print_address prints the address in addr to the string string * that have the length len. If ret_len is not NULL, it will be filled * with the length of the string if size were unlimited (not including * the final NUL) . * * @param addr address to be printed * @param str pointer string to print the address into * @param len length that will fit into area pointed to by "str". * @param ret_len return length the str. * * @return Return an error code or 0. * * @ingroup krb5_address */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_print_address ( const krb5_address */*addr*/, char */*str*/, size_t /*len*/, size_t */*ret_len*/); krb5_error_code krb5_process_last_request ( krb5_context /*context*/, krb5_get_init_creds_opt */*options*/, krb5_init_creds_context /*ctx*/); KRB5_LIB_FUNCTION int KRB5_LIB_CALL krb5_program_setup ( krb5_context */*context*/, int /*argc*/, char **/*argv*/, struct getargs */*args*/, int /*num_args*/, void (KRB5_LIB_CALL *usage)(int, struct getargs*, int)); KRB5_LIB_FUNCTION int KRB5_CALLCONV krb5_prompter_posix ( krb5_context /*context*/, void */*data*/, const char */*name*/, const char */*banner*/, int /*num_prompts*/, krb5_prompt prompts[]); /** * Converts the random bytestring to a protocol key according to * Kerberos crypto frame work. It may be assumed that all the bits of * the input string are equally random, even though the entropy * present in the random source may be limited. * * @param context Kerberos 5 context * @param type the enctype resulting key will be of * @param data input random data to convert to a key * @param size size of input random data, at least krb5_enctype_keysize() long * @param key key, output key, free with krb5_free_keyblock_contents() * * @return Return an error code or 0. * * @ingroup krb5_crypto */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_random_to_key ( krb5_context /*context*/, krb5_enctype /*type*/, const void */*data*/, size_t /*size*/, krb5_keyblock */*key*/); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_rc_close ( krb5_context /*context*/, krb5_rcache /*id*/); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_rc_default ( krb5_context /*context*/, krb5_rcache */*id*/); KRB5_LIB_FUNCTION const char* KRB5_LIB_CALL krb5_rc_default_name (krb5_context /*context*/); KRB5_LIB_FUNCTION const char* KRB5_LIB_CALL krb5_rc_default_type (krb5_context /*context*/); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_rc_destroy ( krb5_context /*context*/, krb5_rcache /*id*/); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_rc_expunge ( krb5_context /*context*/, krb5_rcache /*id*/); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_rc_get_lifespan ( krb5_context /*context*/, krb5_rcache /*id*/, krb5_deltat */*auth_lifespan*/); KRB5_LIB_FUNCTION const char* KRB5_LIB_CALL krb5_rc_get_name ( krb5_context /*context*/, krb5_rcache /*id*/); KRB5_LIB_FUNCTION const char* KRB5_LIB_CALL krb5_rc_get_type ( krb5_context /*context*/, krb5_rcache /*id*/); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_rc_initialize ( krb5_context /*context*/, krb5_rcache /*id*/, krb5_deltat /*auth_lifespan*/); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_rc_recover ( krb5_context /*context*/, krb5_rcache /*id*/); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_rc_resolve ( krb5_context /*context*/, krb5_rcache /*id*/, const char */*name*/); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_rc_resolve_full ( krb5_context /*context*/, krb5_rcache */*id*/, const char */*string_name*/); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_rc_resolve_type ( krb5_context /*context*/, krb5_rcache */*id*/, const char */*type*/); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_rc_store ( krb5_context /*context*/, krb5_rcache /*id*/, krb5_donot_replay */*rep*/); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_rd_cred ( krb5_context /*context*/, krb5_auth_context /*auth_context*/, krb5_data */*in_data*/, krb5_creds ***/*ret_creds*/, krb5_replay_data */*outdata*/); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_rd_cred2 ( krb5_context /*context*/, krb5_auth_context /*auth_context*/, krb5_ccache /*ccache*/, krb5_data */*in_data*/); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_rd_error ( krb5_context /*context*/, const krb5_data */*msg*/, KRB_ERROR */*result*/); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_rd_priv ( krb5_context /*context*/, krb5_auth_context /*auth_context*/, const krb5_data */*inbuf*/, krb5_data */*outbuf*/, krb5_replay_data */*outdata*/); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_rd_rep ( krb5_context /*context*/, krb5_auth_context /*auth_context*/, const krb5_data */*inbuf*/, krb5_ap_rep_enc_part **/*repl*/); /** * Process an AP_REQ message. * * @param context Kerberos 5 context. * @param auth_context authentication context of the peer. * @param inbuf the AP_REQ message, obtained for example with krb5_read_message(). * @param server server principal. * @param keytab server keytab. * @param ap_req_options set to the AP_REQ options. See the AP_OPTS_* defines. * @param ticket on success, set to the authenticated client credentials. * Must be deallocated with krb5_free_ticket(). If not * interested, pass a NULL value. * * @return 0 to indicate success. Otherwise a Kerberos error code is * returned, see krb5_get_error_message(). */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_rd_req ( krb5_context /*context*/, krb5_auth_context */*auth_context*/, const krb5_data */*inbuf*/, krb5_const_principal /*server*/, krb5_keytab /*keytab*/, krb5_flags */*ap_req_options*/, krb5_ticket **/*ticket*/); /** * The core server function that verify application authentication * requests from clients. * * @param context Keberos 5 context. * @param auth_context the authentication context, can be NULL, then * default values for the authentication context will used. * @param inbuf the (AP-REQ) authentication buffer * * @param server the server to authenticate to. If NULL the function * will try to find any available credential in the keytab * that will verify the reply. The function will prefer the * server specified in the AP-REQ, but if * there is no mach, it will try all keytab entries for a * match. This has serious performance issues for large keytabs. * * @param inctx control the behavior of the function, if NULL, the * default behavior is used. * @param outctx the return outctx, free with krb5_rd_req_out_ctx_free(). * @return Kerberos 5 error code, see krb5_get_error_message(). * * @ingroup krb5_auth */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_rd_req_ctx ( krb5_context /*context*/, krb5_auth_context */*auth_context*/, const krb5_data */*inbuf*/, krb5_const_principal /*server*/, krb5_rd_req_in_ctx /*inctx*/, krb5_rd_req_out_ctx */*outctx*/); /** * Allocate a krb5_rd_req_in_ctx as an input parameter to * krb5_rd_req_ctx(). The caller should free the context with * krb5_rd_req_in_ctx_free() when done with the context. * * @param context Keberos 5 context. * @param ctx in ctx to krb5_rd_req_ctx(). * * @return Kerberos 5 error code, see krb5_get_error_message(). * * @ingroup krb5_auth */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_rd_req_in_ctx_alloc ( krb5_context /*context*/, krb5_rd_req_in_ctx */*ctx*/); KRB5_LIB_FUNCTION void KRB5_LIB_CALL krb5_rd_req_in_ctx_free ( krb5_context /*context*/, krb5_rd_req_in_ctx /*ctx*/); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_rd_req_in_set_keyblock ( krb5_context /*context*/, krb5_rd_req_in_ctx /*in*/, krb5_keyblock */*keyblock*/); /** * Set the keytab that krb5_rd_req_ctx() will use. * * @param context Keberos 5 context. * @param in in ctx to krb5_rd_req_ctx(). * @param keytab keytab that krb5_rd_req_ctx() will use, only copy the * pointer, so the caller must free they keytab after * krb5_rd_req_in_ctx_free() is called. * * @return Kerberos 5 error code, see krb5_get_error_message(). * * @ingroup krb5_auth */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_rd_req_in_set_keytab ( krb5_context /*context*/, krb5_rd_req_in_ctx /*in*/, krb5_keytab /*keytab*/); /** * Set if krb5_rq_red() is going to check the Windows PAC or not * * @param context Keberos 5 context. * @param in krb5_rd_req_in_ctx to check the option on. * @param flag flag to select if to check the pac (TRUE) or not (FALSE). * * @return Kerberos 5 error code, see krb5_get_error_message(). * * @ingroup krb5_auth */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_rd_req_in_set_pac_check ( krb5_context /*context*/, krb5_rd_req_in_ctx /*in*/, krb5_boolean /*flag*/); /** * Free the krb5_rd_req_out_ctx. * * @param context Keberos 5 context. * @param ctx krb5_rd_req_out_ctx context to free. * * @ingroup krb5_auth */ KRB5_LIB_FUNCTION void KRB5_LIB_CALL krb5_rd_req_out_ctx_free ( krb5_context /*context*/, krb5_rd_req_out_ctx /*ctx*/); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_rd_req_out_get_ap_req_options ( krb5_context /*context*/, krb5_rd_req_out_ctx /*out*/, krb5_flags */*ap_req_options*/); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_rd_req_out_get_keyblock ( krb5_context /*context*/, krb5_rd_req_out_ctx /*out*/, krb5_keyblock **/*keyblock*/); /** * Get the principal that was used in the request from the * client. Might not match whats in the ticket if krb5_rd_req_ctx() * searched in the keytab for a matching key. * * @param context a Kerberos 5 context. * @param out a krb5_rd_req_out_ctx from krb5_rd_req_ctx(). * @param principal return principal, free with krb5_free_principal(). * * @ingroup krb5_auth */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_rd_req_out_get_server ( krb5_context /*context*/, krb5_rd_req_out_ctx /*out*/, krb5_principal */*principal*/); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_rd_req_out_get_ticket ( krb5_context /*context*/, krb5_rd_req_out_ctx /*out*/, krb5_ticket **/*ticket*/); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_rd_req_with_keyblock ( krb5_context /*context*/, krb5_auth_context */*auth_context*/, const krb5_data */*inbuf*/, krb5_const_principal /*server*/, krb5_keyblock */*keyblock*/, krb5_flags */*ap_req_options*/, krb5_ticket **/*ticket*/); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_rd_safe ( krb5_context /*context*/, krb5_auth_context /*auth_context*/, const krb5_data */*inbuf*/, krb5_data */*outbuf*/, krb5_replay_data */*outdata*/); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_read_message ( krb5_context /*context*/, krb5_pointer /*p_fd*/, krb5_data */*data*/); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_read_priv_message ( krb5_context /*context*/, krb5_auth_context /*ac*/, krb5_pointer /*p_fd*/, krb5_data */*data*/); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_read_safe_message ( krb5_context /*context*/, krb5_auth_context /*ac*/, krb5_pointer /*p_fd*/, krb5_data */*data*/); /** * return TRUE iff realm(princ1) == realm(princ2) * * @param context Kerberos 5 context * @param princ1 first principal to compare * @param princ2 second principal to compare * * @ingroup krb5_principal * @see krb5_principal_compare_any_realm() * @see krb5_principal_compare() */ KRB5_LIB_FUNCTION krb5_boolean KRB5_LIB_CALL krb5_realm_compare ( krb5_context /*context*/, krb5_const_principal /*princ1*/, krb5_const_principal /*princ2*/); /** * Returns true if name is Kerberos an LKDC realm * * @ingroup krb5_principal */ krb5_boolean KRB5_LIB_FUNCTION krb5_realm_is_lkdc (const char */*realm*/); /** * Perform the server side of the sendauth protocol. * * @param context Kerberos 5 context. * @param auth_context authentication context of the peer. * @param p_fd socket associated to the connection. * @param appl_version server-specific string. * @param server server principal. * @param flags if KRB5_RECVAUTH_IGNORE_VERSION is set, skip the sendauth version * part of the protocol. * @param keytab server keytab. * @param ticket on success, set to the authenticated client credentials. * Must be deallocated with krb5_free_ticket(). If not * interested, pass a NULL value. * * @return 0 to indicate success. Otherwise a Kerberos error code is * returned, see krb5_get_error_message(). */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_recvauth ( krb5_context /*context*/, krb5_auth_context */*auth_context*/, krb5_pointer /*p_fd*/, const char */*appl_version*/, krb5_principal /*server*/, int32_t /*flags*/, krb5_keytab /*keytab*/, krb5_ticket **/*ticket*/); /** * Perform the server side of the sendauth protocol like krb5_recvauth(), but support * a user-specified callback, \a match_appl_version, to perform the match of the application * version \a match_data. */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_recvauth_match_version ( krb5_context /*context*/, krb5_auth_context */*auth_context*/, krb5_pointer /*p_fd*/, krb5_boolean (*/*match_appl_version*/)(const void *, const char*), const void */*match_data*/, krb5_principal /*server*/, int32_t /*flags*/, krb5_keytab /*keytab*/, krb5_ticket **/*ticket*/); /** * Read a address block from the storage. * * @param sp the storage buffer to write to * @param adr the address block read from storage * * @return 0 on success, a Kerberos 5 error code on failure. * * @ingroup krb5_storage */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_ret_address ( krb5_storage */*sp*/, krb5_address */*adr*/); /** * Read a addresses block from the storage. * * @param sp the storage buffer to write to * @param adr the addresses block read from storage * * @return 0 on success, a Kerberos 5 error code on failure. * * @ingroup krb5_storage */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_ret_addrs ( krb5_storage */*sp*/, krb5_addresses */*adr*/); /** * Read a auth data from the storage. * * @param sp the storage buffer to write to * @param auth the auth data block read from storage * * @return 0 on success, a Kerberos 5 error code on failure. * * @ingroup krb5_storage */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_ret_authdata ( krb5_storage */*sp*/, krb5_authdata */*auth*/); /** * Read a credentials block from the storage. * * @param sp the storage buffer to write to * @param creds the credentials block read from storage * * @return 0 on success, a Kerberos 5 error code on failure. * * @ingroup krb5_storage */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_ret_creds ( krb5_storage */*sp*/, krb5_creds */*creds*/); /** * Read a tagged credentials block from the storage. * * @param sp the storage buffer to write to * @param creds the credentials block read from storage * * @return 0 on success, a Kerberos 5 error code on failure. * * @ingroup krb5_storage */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_ret_creds_tag ( krb5_storage */*sp*/, krb5_creds */*creds*/); /** * Parse a data from the storage. * * @param sp the storage buffer to read from * @param data the parsed data * * @return 0 on success, a Kerberos 5 error code on failure. * * @ingroup krb5_storage */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_ret_data ( krb5_storage */*sp*/, krb5_data */*data*/); /** * Read a int16 from storage, byte order is controlled by the settings * on the storage, see krb5_storage_set_byteorder(). * * @param sp the storage to write too * @param value the value read from the buffer * * @return 0 for success, or a Kerberos 5 error code on failure. * * @ingroup krb5_storage */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_ret_int16 ( krb5_storage */*sp*/, int16_t */*value*/); /** * Read a int32 from storage, byte order is controlled by the settings * on the storage, see krb5_storage_set_byteorder(). * * @param sp the storage to write too * @param value the value read from the buffer * * @return 0 for success, or a Kerberos 5 error code on failure. * * @ingroup krb5_storage */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_ret_int32 ( krb5_storage */*sp*/, int32_t */*value*/); /** * Read a int64 from storage, byte order is controlled by the settings * on the storage, see krb5_storage_set_byteorder(). * * @param sp the storage to write too * @param value the value read from the buffer * * @return 0 for success, or a Kerberos 5 error code on failure. * * @ingroup krb5_storage */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_ret_int64 ( krb5_storage */*sp*/, int64_t */*value*/); /** * Read a int8 from storage * * @param sp the storage to write too * @param value the value read from the buffer * * @return 0 for success, or a Kerberos 5 error code on failure. * * @ingroup krb5_storage */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_ret_int8 ( krb5_storage */*sp*/, int8_t */*value*/); /** * Read a keyblock from the storage. * * @param sp the storage buffer to write to * @param p the keyblock read from storage, free using krb5_free_keyblock() * * @return 0 on success, a Kerberos 5 error code on failure. * * @ingroup krb5_storage */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_ret_keyblock ( krb5_storage */*sp*/, krb5_keyblock */*p*/); /** * Parse principal from the storage. * * @param sp the storage buffer to read from * @param princ the parsed principal * * @return 0 on success, a Kerberos 5 error code on failure. * * @ingroup krb5_storage */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_ret_principal ( krb5_storage */*sp*/, krb5_principal */*princ*/); /** * Parse a string from the storage. * * @param sp the storage buffer to read from * @param string the parsed string * * @return 0 on success, a Kerberos 5 error code on failure. * * @ingroup krb5_storage */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_ret_string ( krb5_storage */*sp*/, char **/*string*/); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_ret_stringnl ( krb5_storage */*sp*/, char **/*string*/); /** * Parse zero terminated string from the storage. * * @param sp the storage buffer to read from * @param string the parsed string * * @return 0 on success, a Kerberos 5 error code on failure. * * @ingroup krb5_storage */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_ret_stringz ( krb5_storage */*sp*/, char **/*string*/); /** * Read a times block from the storage. * * @param sp the storage buffer to write to * @param times the times block read from storage * * @return 0 on success, a Kerberos 5 error code on failure. * * @ingroup krb5_storage */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_ret_times ( krb5_storage */*sp*/, krb5_times */*times*/); /** * Read a int16 from storage, byte order is controlled by the settings * on the storage, see krb5_storage_set_byteorder(). * * @param sp the storage to write too * @param value the value read from the buffer * * @return 0 for success, or a Kerberos 5 error code on failure. * * @ingroup krb5_storage */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_ret_uint16 ( krb5_storage */*sp*/, uint16_t */*value*/); /** * Read a uint32 from storage, byte order is controlled by the settings * on the storage, see krb5_storage_set_byteorder(). * * @param sp the storage to write too * @param value the value read from the buffer * * @return 0 for success, or a Kerberos 5 error code on failure. * * @ingroup krb5_storage */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_ret_uint32 ( krb5_storage */*sp*/, uint32_t */*value*/); /** * Read a uint64 from storage, byte order is controlled by the settings * on the storage, see krb5_storage_set_byteorder(). * * @param sp the storage to write too * @param value the value read from the buffer * * @return 0 for success, or a Kerberos 5 error code on failure. * * @ingroup krb5_storage */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_ret_uint64 ( krb5_storage */*sp*/, uint64_t */*value*/); /** * Read a uint8 from storage * * @param sp the storage to write too * @param value the value read from the buffer * * @return 0 for success, or a Kerberos 5 error code on failure. * * @ingroup krb5_storage */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_ret_uint8 ( krb5_storage */*sp*/, uint8_t */*value*/); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_salttype_to_string ( krb5_context /*context*/, krb5_enctype /*etype*/, krb5_salttype /*stype*/, char **/*string*/); /** * Perform the client side of the sendauth protocol. * * @param context Kerberos 5 context. * @param auth_context Authentication context of the peer. * @param p_fd Socket associated to the connection. * @param appl_version Server-specific string. * @param client Client principal. If NULL, use the credentials in \a ccache. * @param server Server principal. * @param ap_req_options Options for the AP_REQ message. See the AP_OPTS_* defines in krb5.h. * @param in_data FIXME * @param in_creds FIXME * @param ccache Credentials cache. If NULL, use the default credentials cache. * @param ret_error If not NULL, will be set to the error reported by server, if any. * Must be deallocated with krb5_free_error_contents(). * @param rep_result If not NULL, will be set to the EncApRepPart of the AP_REP message. * Must be deallocated with krb5_free_ap_rep_enc_part(). * @param out_creds FIXME If not NULL, will be set to FIXME. Must be deallocated with * krb5_free_creds(). * * @return 0 to indicate success. Otherwise a Kerberos error code is * returned, see krb5_get_error_message(). */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_sendauth ( krb5_context /*context*/, krb5_auth_context */*auth_context*/, krb5_pointer /*p_fd*/, const char */*appl_version*/, krb5_principal /*client*/, krb5_principal /*server*/, krb5_flags /*ap_req_options*/, krb5_data */*in_data*/, krb5_creds */*in_creds*/, krb5_ccache /*ccache*/, krb5_error **/*ret_error*/, krb5_ap_rep_enc_part **/*rep_result*/, krb5_creds **/*out_creds*/); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_sendto ( krb5_context /*context*/, const krb5_data */*send_data*/, krb5_krbhst_handle /*handle*/, krb5_data */*receive*/); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_sendto_context ( krb5_context /*context*/, krb5_sendto_ctx /*ctx*/, const krb5_data */*send_data*/, krb5_const_realm /*realm*/, krb5_data */*receive*/); KRB5_LIB_FUNCTION void KRB5_LIB_CALL krb5_sendto_ctx_add_flags ( krb5_sendto_ctx /*ctx*/, int /*flags*/); /** * @section send_to_kdc Locating and sending packets to the KDC * * The send to kdc code is responsible to request the list of KDC from * the locate-kdc subsystem and then send requests to each of them. * * - Each second a new hostname is tried. * - If the hostname have several addresses, the first will be tried * directly then in turn the other will be tried every 3 seconds * (host_timeout). * - UDP requests are tried 3 times, and it tried with a individual timeout of kdc_timeout / 3. * - TCP and HTTP requests are tried 1 time. * * Total wait time shorter then (number of addresses * 3) + kdc_timeout seconds. * */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_sendto_ctx_alloc ( krb5_context /*context*/, krb5_sendto_ctx */*ctx*/); KRB5_LIB_FUNCTION void KRB5_LIB_CALL krb5_sendto_ctx_free ( krb5_context /*context*/, krb5_sendto_ctx /*ctx*/); KRB5_LIB_FUNCTION int KRB5_LIB_CALL krb5_sendto_ctx_get_flags (krb5_sendto_ctx /*ctx*/); KRB5_LIB_FUNCTION void KRB5_LIB_CALL krb5_sendto_ctx_set_func ( krb5_sendto_ctx /*ctx*/, krb5_sendto_ctx_func /*func*/, void */*data*/); KRB5_LIB_FUNCTION void KRB5_LIB_CALL krb5_sendto_ctx_set_type ( krb5_sendto_ctx /*ctx*/, int /*type*/); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_sendto_kdc ( krb5_context /*context*/, const krb5_data */*send_data*/, const krb5_realm */*realm*/, krb5_data */*receive*/); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_sendto_kdc_flags ( krb5_context /*context*/, const krb5_data */*send_data*/, const krb5_realm */*realm*/, krb5_data */*receive*/, int /*flags*/); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_sendto_set_hostname ( krb5_context /*context*/, krb5_sendto_ctx /*ctx*/, const char */*hostname*/); /** * Reinit the context from a new set of filenames. * * @param context context to add configuration too. * @param filenames array of filenames, end of list is indicated with a NULL filename. * * @return Returns 0 to indicate success. Otherwise an kerberos et * error code is returned, see krb5_get_error_message(). * * @ingroup krb5 */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_set_config_files ( krb5_context /*context*/, char **/*filenames*/); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_set_debug_dest ( krb5_context /*context*/, const char */*program*/, const char */*log_spec*/); /** * Set the default encryption types that will be use in communcation * with the KDC, clients and servers. * * @param context Kerberos 5 context. * @param etypes Encryption types, array terminated with ETYPE_NULL (0). * A value of NULL resets the encryption types to the defaults set in the * configuration file. * * @return Returns 0 to indicate success. Otherwise an kerberos et * error code is returned, see krb5_get_error_message(). * * @ingroup krb5 */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_set_default_in_tkt_etypes ( krb5_context /*context*/, const krb5_enctype */*etypes*/); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_set_default_realm ( krb5_context /*context*/, const char */*realm*/); /** * Set if the library should use DNS to canonicalize hostnames. * * @param context Kerberos 5 context. * @param flag if its dns canonicalizion is used or not. * * @ingroup krb5 */ KRB5_LIB_FUNCTION void KRB5_LIB_CALL krb5_set_dns_canonicalize_hostname ( krb5_context /*context*/, krb5_boolean /*flag*/); /** * Set the context full error string for a specific error code. * The error that is stored should be internationalized. * * The if context is NULL, no error string is stored. * * @param context Kerberos 5 context * @param ret The error code * @param fmt Error string for the error code * @param ... printf(3) style parameters. * * @ingroup krb5_error */ KRB5_LIB_FUNCTION void KRB5_LIB_CALL krb5_set_error_message ( krb5_context /*context*/, krb5_error_code /*ret*/, const char */*fmt*/, ...) __attribute__ ((__format__ (__printf__, 3, 4))); /** * Set the error message returned by krb5_get_error_string(). * * Deprecated: use krb5_get_error_message() * * @param context Kerberos context * @param fmt error message to free * * @return Return an error code or 0. * * @ingroup krb5_deprecated */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_set_error_string ( krb5_context /*context*/, const char */*fmt*/, ...) __attribute__ ((__format__ (__printf__, 2, 3))) KRB5_DEPRECATED_FUNCTION("Use X instead"); /** * Set extra address to the address list that the library will add to * the client's address list when communicating with the KDC. * * @param context Kerberos 5 context. * @param addresses addreses to set * * @return Returns 0 to indicate success. Otherwise an kerberos et * error code is returned, see krb5_get_error_message(). * * @ingroup krb5 */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_set_extra_addresses ( krb5_context /*context*/, const krb5_addresses */*addresses*/); /** * Set version of fcache that the library should use. * * @param context Kerberos 5 context. * @param version version number. * * @return Returns 0 to indicate success. Otherwise an kerberos et * error code is returned, see krb5_get_error_message(). * * @ingroup krb5 */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_set_fcache_version ( krb5_context /*context*/, int /*version*/); /** * Enable and disable home directory access on either the global state * or the krb5_context state. By calling krb5_set_home_dir_access() * with context set to NULL, the global state is configured otherwise * the state for the krb5_context is modified. * * For home directory access to be allowed, both the global state and * the krb5_context state have to be allowed. * * @param context a Kerberos 5 context or NULL * @param allow allow if TRUE home directory * @return the old value * * @ingroup krb5 */ KRB5_LIB_FUNCTION krb5_boolean KRB5_LIB_CALL krb5_set_home_dir_access ( krb5_context /*context*/, krb5_boolean /*allow*/); /** * Set extra addresses to ignore when fetching addresses from the * underlaying operating system. * * @param context Kerberos 5 context. * @param addresses addreses to ignore * * @return Returns 0 to indicate success. Otherwise an kerberos et * error code is returned, see krb5_get_error_message(). * * @ingroup krb5 */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_set_ignore_addresses ( krb5_context /*context*/, const krb5_addresses */*addresses*/); /** * Set current offset in time to the KDC. * * @param context Kerberos 5 context. * @param sec seconds part of offset. * @param usec micro seconds part of offset. * * @return returns zero * * @ingroup krb5 */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_set_kdc_sec_offset ( krb5_context /*context*/, int32_t /*sec*/, int32_t /*usec*/); /** * Set max time skew allowed. * * @param context Kerberos 5 context. * @param t timeskew in seconds. * * @ingroup krb5 */ KRB5_LIB_FUNCTION void KRB5_LIB_CALL krb5_set_max_time_skew ( krb5_context /*context*/, time_t /*t*/); /** * Change password using creds. * * @param context a Keberos context * @param creds The initial kadmin/passwd for the principal or an admin principal * @param newpw The new password to set * @param targprinc if unset, the default principal is used. * @param result_code Result code, KRB5_KPASSWD_SUCCESS is when password is changed. * @param result_code_string binary message from the server, contains * at least the result_code. * @param result_string A message from the kpasswd service or the * library in human printable form. The string is NUL terminated. * * @return On sucess and *result_code is KRB5_KPASSWD_SUCCESS, the password is changed. * @ingroup @krb5 */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_set_password ( krb5_context /*context*/, krb5_creds */*creds*/, const char */*newpw*/, krb5_principal /*targprinc*/, int */*result_code*/, krb5_data */*result_code_string*/, krb5_data */*result_string*/); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_set_password_using_ccache ( krb5_context /*context*/, krb5_ccache /*ccache*/, const char */*newpw*/, krb5_principal /*targprinc*/, int */*result_code*/, krb5_data */*result_code_string*/, krb5_data */*result_string*/); /** * Set the absolute time that the caller knows the kdc has so the * kerberos library can calculate the relative diffrence beteen the * KDC time and local system time. * * @param context Keberos 5 context. * @param sec The applications new of "now" in seconds * @param usec The applications new of "now" in micro seconds * @return Kerberos 5 error code, see krb5_get_error_message(). * * @ingroup krb5 */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_set_real_time ( krb5_context /*context*/, krb5_timestamp /*sec*/, int32_t /*usec*/); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_set_send_to_kdc_func ( krb5_context /*context*/, krb5_send_to_kdc_func /*func*/, void */*data*/); /** * Make the kerberos library default to the admin KDC. * * @param context Kerberos 5 context. * @param flag boolean flag to select if the use the admin KDC or not. * * @ingroup krb5 */ KRB5_LIB_FUNCTION void KRB5_LIB_CALL krb5_set_use_admin_kdc ( krb5_context /*context*/, krb5_boolean /*flag*/); /** * Set the default logging facility. * * @param context A Kerberos 5 context * @param fac Facility to use for logging. * * @ingroup krb5_error */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_set_warn_dest ( krb5_context /*context*/, krb5_log_facility */*fac*/); /** * Create a principal for the given service running on the given * hostname. If KRB5_NT_SRV_HST is used, the hostname is canonicalized * according the configured name canonicalization rules, with * canonicalization delayed in some cases. One rule involves DNS, which * is insecure unless DNSSEC is used, but we don't use DNSSEC-capable * resolver APIs here, so that if DNSSEC is used we wouldn't know it. * * Canonicalization is immediate (not delayed) only when there is only * one canonicalization rule and that rule indicates that we should do a * host lookup by name (i.e., DNS). * * @param context A Kerberos context. * @param hostname hostname to use * @param sname Service name to use * @param type name type of principal, use KRB5_NT_SRV_HST or KRB5_NT_UNKNOWN. * @param ret_princ return principal, free with krb5_free_principal(). * * @return An krb5 error code, see krb5_get_error_message(). * * @ingroup krb5_principal */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_sname_to_principal ( krb5_context /*context*/, const char */*hostname*/, const char */*sname*/, int32_t /*type*/, krb5_principal */*ret_princ*/); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_sock_to_principal ( krb5_context /*context*/, int /*sock*/, const char */*sname*/, int32_t /*type*/, krb5_principal */*ret_princ*/); /** * krb5_sockaddr2address stores a address a "struct sockaddr" sa in * the krb5_address addr. * * @param context a Keberos context * @param sa a struct sockaddr to extract the address from * @param addr an Kerberos 5 address to store the address in. * * @return Return an error code or 0. * * @ingroup krb5_address */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_sockaddr2address ( krb5_context /*context*/, const struct sockaddr */*sa*/, krb5_address */*addr*/); /** * krb5_sockaddr2port extracts a port (if possible) from a "struct * sockaddr. * * @param context a Keberos context * @param sa a struct sockaddr to extract the port from * @param port a pointer to an int16_t store the port in. * * @return Return an error code or 0. Will return * KRB5_PROG_ATYPE_NOSUPP in case address type is not supported. * * @ingroup krb5_address */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_sockaddr2port ( krb5_context /*context*/, const struct sockaddr */*sa*/, int16_t */*port*/); KRB5_LIB_FUNCTION krb5_boolean KRB5_LIB_CALL krb5_sockaddr_is_loopback (const struct sockaddr */*sa*/); /** * krb5_sockaddr_uninteresting returns TRUE for all .Fa sa that the * kerberos library thinks are uninteresting. One example are link * local addresses. * * @param sa pointer to struct sockaddr that might be interesting. * * @return Return a non zero for uninteresting addresses. * * @ingroup krb5_address */ KRB5_LIB_FUNCTION krb5_boolean KRB5_LIB_CALL krb5_sockaddr_uninteresting (const struct sockaddr */*sa*/); KRB5_LIB_FUNCTION void KRB5_LIB_CALL krb5_std_usage ( int /*code*/, struct getargs */*args*/, int /*num_args*/); /** * Clear the flags on a storage buffer * * @param sp the storage buffer to clear the flags on * @param flags the flags to clear * * @ingroup krb5_storage */ KRB5_LIB_FUNCTION void KRB5_LIB_CALL krb5_storage_clear_flags ( krb5_storage */*sp*/, krb5_flags /*flags*/); /** * Create a elastic (allocating) memory storage backend. Memory is * allocated on demand. Free returned krb5_storage with * krb5_storage_free(). * * @return A krb5_storage on success, or NULL on out of memory error. * * @ingroup krb5_storage * * @sa krb5_storage_from_mem() * @sa krb5_storage_from_readonly_mem() * @sa krb5_storage_from_fd() * @sa krb5_storage_from_data() * @sa krb5_storage_from_socket() */ KRB5_LIB_FUNCTION krb5_storage * KRB5_LIB_CALL krb5_storage_emem (void); /** * Free a krb5 storage. * * @param sp the storage to free. * * @return An Kerberos 5 error code. * * @ingroup krb5_storage */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_storage_free (krb5_storage */*sp*/); /** * Create a fixed size memory storage block * * @return A krb5_storage on success, or NULL on out of memory error. * * @ingroup krb5_storage * * @sa krb5_storage_mem() * @sa krb5_storage_from_mem() * @sa krb5_storage_from_readonly_mem() * @sa krb5_storage_from_fd() */ KRB5_LIB_FUNCTION krb5_storage * KRB5_LIB_CALL krb5_storage_from_data (krb5_data */*data*/); /** * * * @return A krb5_storage on success, or NULL on out of memory error. * * @ingroup krb5_storage * * @sa krb5_storage_emem() * @sa krb5_storage_from_mem() * @sa krb5_storage_from_readonly_mem() * @sa krb5_storage_from_data() * @sa krb5_storage_from_socket() */ KRB5_LIB_FUNCTION krb5_storage * KRB5_LIB_CALL krb5_storage_from_fd (int /*fd_in*/); /** * Create a fixed size memory storage block * * @return A krb5_storage on success, or NULL on out of memory error. * * @ingroup krb5_storage * * @sa krb5_storage_mem() * @sa krb5_storage_from_readonly_mem() * @sa krb5_storage_from_data() * @sa krb5_storage_from_fd() * @sa krb5_storage_from_socket() */ KRB5_LIB_FUNCTION krb5_storage * KRB5_LIB_CALL krb5_storage_from_mem ( void */*buf*/, size_t /*len*/); /** * Create a fixed size memory storage block that is read only * * @return A krb5_storage on success, or NULL on out of memory error. * * @ingroup krb5_storage * * @sa krb5_storage_mem() * @sa krb5_storage_from_mem() * @sa krb5_storage_from_data() * @sa krb5_storage_from_fd() */ KRB5_LIB_FUNCTION krb5_storage * KRB5_LIB_CALL krb5_storage_from_readonly_mem ( const void */*buf*/, size_t /*len*/); /** * * * @return A krb5_storage on success, or NULL on out of memory error. * * @ingroup krb5_storage * * @sa krb5_storage_emem() * @sa krb5_storage_from_mem() * @sa krb5_storage_from_readonly_mem() * @sa krb5_storage_from_data() * @sa krb5_storage_from_fd() */ KRB5_LIB_FUNCTION krb5_storage * KRB5_LIB_CALL krb5_storage_from_socket (krb5_socket_t /*sock_in*/); /** * Sync the storage buffer to its backing store. If there is no * backing store this function will return success. * * @param sp the storage buffer to sync * * @return A Kerberos 5 error code * * @ingroup krb5_storage */ KRB5_LIB_FUNCTION int KRB5_LIB_CALL krb5_storage_fsync (krb5_storage */*sp*/); /** * Return the current byteorder for the buffer. See krb5_storage_set_byteorder() for the list or byte order contants. * * @ingroup krb5_storage */ KRB5_LIB_FUNCTION krb5_flags KRB5_LIB_CALL krb5_storage_get_byteorder (krb5_storage */*sp*/); /** * Get the return code that will be used when end of storage is reached. * * @param sp the storage * * @return storage error code * * @ingroup krb5_storage */ KRB5_LIB_FUNCTION int KRB5_LIB_CALL krb5_storage_get_eof_code (krb5_storage */*sp*/); /** * Return true or false depending on if the storage flags is set or * not. NB testing for the flag 0 always return true. * * @param sp the storage buffer to check flags on * @param flags The flags to test for * * @return true if all the flags are set, false if not. * * @ingroup krb5_storage */ KRB5_LIB_FUNCTION krb5_boolean KRB5_LIB_CALL krb5_storage_is_flags ( krb5_storage */*sp*/, krb5_flags /*flags*/); /** * Read to the storage buffer. * * @param sp the storage buffer to read from * @param buf the buffer to store the data in * @param len the length to read * * @return The length of data read (can be shorter then len), or negative on error. * * @ingroup krb5_storage */ KRB5_LIB_FUNCTION krb5_ssize_t KRB5_LIB_CALL krb5_storage_read ( krb5_storage */*sp*/, void */*buf*/, size_t /*len*/); /** * Seek to a new offset. * * @param sp the storage buffer to seek in. * @param offset the offset to seek * @param whence relateive searching, SEEK_CUR from the current * position, SEEK_END from the end, SEEK_SET absolute from the start. * * @return The new current offset * * @ingroup krb5_storage */ KRB5_LIB_FUNCTION off_t KRB5_LIB_CALL krb5_storage_seek ( krb5_storage */*sp*/, off_t /*offset*/, int /*whence*/); /** * Set the new byte order of the storage buffer. * * @param sp the storage buffer to set the byte order for. * @param byteorder the new byte order. * * The byte order are: KRB5_STORAGE_BYTEORDER_BE, * KRB5_STORAGE_BYTEORDER_LE and KRB5_STORAGE_BYTEORDER_HOST. * * @ingroup krb5_storage */ KRB5_LIB_FUNCTION void KRB5_LIB_CALL krb5_storage_set_byteorder ( krb5_storage */*sp*/, krb5_flags /*byteorder*/); /** * Set the return code that will be used when end of storage is reached. * * @param sp the storage * @param code the error code to return on end of storage * * @ingroup krb5_storage */ KRB5_LIB_FUNCTION void KRB5_LIB_CALL krb5_storage_set_eof_code ( krb5_storage */*sp*/, int /*code*/); /** * Add the flags on a storage buffer by or-ing in the flags to the buffer. * * @param sp the storage buffer to set the flags on * @param flags the flags to set * * @ingroup krb5_storage */ KRB5_LIB_FUNCTION void KRB5_LIB_CALL krb5_storage_set_flags ( krb5_storage */*sp*/, krb5_flags /*flags*/); /** * Set the max alloc value * * @param sp the storage buffer set the max allow for * @param size maximum size to allocate, use 0 to remove limit * * @ingroup krb5_storage */ KRB5_LIB_FUNCTION void KRB5_LIB_CALL krb5_storage_set_max_alloc ( krb5_storage */*sp*/, size_t /*size*/); /** * Copy the contnent of storage * * @param sp the storage to copy to a data * @param data the copied data, free with krb5_data_free() * * @return 0 for success, or a Kerberos 5 error code on failure. * * @ingroup krb5_storage */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_storage_to_data ( krb5_storage */*sp*/, krb5_data */*data*/); /** * Truncate the storage buffer in sp to offset. * * @param sp the storage buffer to truncate. * @param offset the offset to truncate too. * * @return An Kerberos 5 error code. * * @ingroup krb5_storage */ KRB5_LIB_FUNCTION int KRB5_LIB_CALL krb5_storage_truncate ( krb5_storage */*sp*/, off_t /*offset*/); /** * Write to the storage buffer. * * @param sp the storage buffer to write to * @param buf the buffer to write to the storage buffer * @param len the length to write * * @return The length of data written (can be shorter then len), or negative on error. * * @ingroup krb5_storage */ KRB5_LIB_FUNCTION krb5_ssize_t KRB5_LIB_CALL krb5_storage_write ( krb5_storage */*sp*/, const void */*buf*/, size_t /*len*/); /** * Write a address block to storage. * * @param sp the storage buffer to write to * @param p the address block to write. * * @return 0 on success, a Kerberos 5 error code on failure. * * @ingroup krb5_storage */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_store_address ( krb5_storage */*sp*/, krb5_address /*p*/); /** * Write a addresses block to storage. * * @param sp the storage buffer to write to * @param p the addresses block to write. * * @return 0 on success, a Kerberos 5 error code on failure. * * @ingroup krb5_storage */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_store_addrs ( krb5_storage */*sp*/, krb5_addresses /*p*/); /** * Write a auth data block to storage. * * @param sp the storage buffer to write to * @param auth the auth data block to write. * * @return 0 on success, a Kerberos 5 error code on failure. * * @ingroup krb5_storage */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_store_authdata ( krb5_storage */*sp*/, krb5_authdata /*auth*/); /** * Write a credentials block to storage. * * @param sp the storage buffer to write to * @param creds the creds block to write. * * @return 0 on success, a Kerberos 5 error code on failure. * * @ingroup krb5_storage */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_store_creds ( krb5_storage */*sp*/, krb5_creds */*creds*/); /** * Write a tagged credentials block to storage. * * @param sp the storage buffer to write to * @param creds the creds block to write. * * @return 0 on success, a Kerberos 5 error code on failure. * * @ingroup krb5_storage */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_store_creds_tag ( krb5_storage */*sp*/, krb5_creds */*creds*/); /** * Store a data to the storage. The data is stored with an int32 as * lenght plus the data (not padded). * * @param sp the storage buffer to write to * @param data the buffer to store. * * @return 0 on success, a Kerberos 5 error code on failure. * * @ingroup krb5_storage */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_store_data ( krb5_storage */*sp*/, krb5_data /*data*/); /** * Store a int16 to storage, byte order is controlled by the settings * on the storage, see krb5_storage_set_byteorder(). * * @param sp the storage to write too * @param value the value to store * * @return 0 for success, or a Kerberos 5 error code on failure. * * @ingroup krb5_storage */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_store_int16 ( krb5_storage */*sp*/, int16_t /*value*/); /** * Store a int32 to storage, byte order is controlled by the settings * on the storage, see krb5_storage_set_byteorder(). * * @param sp the storage to write too * @param value the value to store * * @return 0 for success, or a Kerberos 5 error code on failure. * * @ingroup krb5_storage */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_store_int32 ( krb5_storage */*sp*/, int32_t /*value*/); /** * Store a int64 to storage, byte order is controlled by the settings * on the storage, see krb5_storage_set_byteorder(). * * @param sp the storage to write too * @param value the value to store * * @return 0 for success, or a Kerberos 5 error code on failure. * * @ingroup krb5_storage */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_store_int64 ( krb5_storage */*sp*/, int64_t /*value*/); /** * Store a int8 to storage. * * @param sp the storage to write too * @param value the value to store * * @return 0 for success, or a Kerberos 5 error code on failure. * * @ingroup krb5_storage */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_store_int8 ( krb5_storage */*sp*/, int8_t /*value*/); /** * Store a keyblock to the storage. * * @param sp the storage buffer to write to * @param p the keyblock to write * * @return 0 on success, a Kerberos 5 error code on failure. * * @ingroup krb5_storage */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_store_keyblock ( krb5_storage */*sp*/, krb5_keyblock /*p*/); /** * Write a principal block to storage. * * @param sp the storage buffer to write to * @param p the principal block to write. * * @return 0 on success, a Kerberos 5 error code on failure. * * @ingroup krb5_storage */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_store_principal ( krb5_storage */*sp*/, krb5_const_principal /*p*/); /** * Store a string to the buffer. The data is formated as an len:uint32 * plus the string itself (not padded). * * @param sp the storage buffer to write to * @param s the string to store. * * @return 0 on success, a Kerberos 5 error code on failure. * * @ingroup krb5_storage */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_store_string ( krb5_storage */*sp*/, const char */*s*/); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_store_stringnl ( krb5_storage */*sp*/, const char */*s*/); /** * Store a zero terminated string to the buffer. The data is stored * one character at a time until a NUL is stored. * * @param sp the storage buffer to write to * @param s the string to store. * * @return 0 on success, a Kerberos 5 error code on failure. * * @ingroup krb5_storage */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_store_stringz ( krb5_storage */*sp*/, const char */*s*/); /** * Write a times block to storage. * * @param sp the storage buffer to write to * @param times the times block to write. * * @return 0 on success, a Kerberos 5 error code on failure. * * @ingroup krb5_storage */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_store_times ( krb5_storage */*sp*/, krb5_times /*times*/); /** * Store a uint16 to storage, byte order is controlled by the settings * on the storage, see krb5_storage_set_byteorder(). * * @param sp the storage to write too * @param value the value to store * * @return 0 for success, or a Kerberos 5 error code on failure. * * @ingroup krb5_storage */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_store_uint16 ( krb5_storage */*sp*/, uint16_t /*value*/); /** * Store a uint32 to storage, byte order is controlled by the settings * on the storage, see krb5_storage_set_byteorder(). * * @param sp the storage to write too * @param value the value to store * * @return 0 for success, or a Kerberos 5 error code on failure. * * @ingroup krb5_storage */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_store_uint32 ( krb5_storage */*sp*/, uint32_t /*value*/); /** * Store a uint64 to storage, byte order is controlled by the settings * on the storage, see krb5_storage_set_byteorder(). * * @param sp the storage to write too * @param value the value to store * * @return 0 for success, or a Kerberos 5 error code on failure. * * @ingroup krb5_storage */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_store_uint64 ( krb5_storage */*sp*/, uint64_t /*value*/); /** * Store a uint8 to storage. * * @param sp the storage to write too * @param value the value to store * * @return 0 for success, or a Kerberos 5 error code on failure. * * @ingroup krb5_storage */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_store_uint8 ( krb5_storage */*sp*/, uint8_t /*value*/); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_string_to_deltat ( const char */*string*/, krb5_deltat */*deltat*/); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_string_to_enctype ( krb5_context /*context*/, const char */*string*/, krb5_enctype */*etype*/); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_string_to_key ( krb5_context /*context*/, krb5_enctype /*enctype*/, const char */*password*/, krb5_principal /*principal*/, krb5_keyblock */*key*/); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_string_to_key_data ( krb5_context /*context*/, krb5_enctype /*enctype*/, krb5_data /*password*/, krb5_principal /*principal*/, krb5_keyblock */*key*/); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_string_to_key_data_salt ( krb5_context /*context*/, krb5_enctype /*enctype*/, krb5_data /*password*/, krb5_salt /*salt*/, krb5_keyblock */*key*/); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_string_to_key_data_salt_opaque ( krb5_context /*context*/, krb5_enctype /*enctype*/, krb5_data /*password*/, krb5_salt /*salt*/, krb5_data /*opaque*/, krb5_keyblock */*key*/); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_string_to_key_derived ( krb5_context /*context*/, const void */*str*/, size_t /*len*/, krb5_enctype /*etype*/, krb5_keyblock */*key*/); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_string_to_key_salt ( krb5_context /*context*/, krb5_enctype /*enctype*/, const char */*password*/, krb5_salt /*salt*/, krb5_keyblock */*key*/); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_string_to_key_salt_opaque ( krb5_context /*context*/, krb5_enctype /*enctype*/, const char */*password*/, krb5_salt /*salt*/, krb5_data /*opaque*/, krb5_keyblock */*key*/); /** * Deprecated: keytypes doesn't exists, they are really enctypes in * most cases, use krb5_string_to_enctype(). * * @ingroup krb5_deprecated */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_string_to_keytype ( krb5_context /*context*/, const char */*string*/, krb5_keytype */*keytype*/) KRB5_DEPRECATED_FUNCTION("Use X instead"); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_string_to_salttype ( krb5_context /*context*/, krb5_enctype /*etype*/, const char */*string*/, krb5_salttype */*salttype*/); /** * Extract the authorization data type of type from the ticket. Store * the field in data. This function is to use for kerberos * applications. * * @param context a Kerberos 5 context * @param ticket Kerberos ticket * @param type type to fetch * @param data returned data, free with krb5_data_free() * * @ingroup krb5 */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_ticket_get_authorization_data_type ( krb5_context /*context*/, krb5_ticket */*ticket*/, int /*type*/, krb5_data */*data*/); /** * Return client principal in ticket * * @param context a Kerberos 5 context * @param ticket ticket to copy * @param client client principal, free with krb5_free_principal() * * @return Returns 0 to indicate success. Otherwise an kerberos et * error code is returned, see krb5_get_error_message(). * * @ingroup krb5 */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_ticket_get_client ( krb5_context /*context*/, const krb5_ticket */*ticket*/, krb5_principal */*client*/); /** * Return end time of ticket * * @param context a Kerberos 5 context * @param ticket ticket to copy * * @return end time of ticket * * @ingroup krb5 */ KRB5_LIB_FUNCTION time_t KRB5_LIB_CALL krb5_ticket_get_endtime ( krb5_context /*context*/, const krb5_ticket */*ticket*/); /** * Get the flags from the Kerberos ticket * * @param context Kerberos context * @param ticket Kerberos ticket * * @return ticket flags * * @ingroup krb5_ticket */ KRB5_LIB_FUNCTION unsigned long KRB5_LIB_CALL krb5_ticket_get_flags ( krb5_context /*context*/, const krb5_ticket */*ticket*/); /** * Return server principal in ticket * * @param context a Kerberos 5 context * @param ticket ticket to copy * @param server server principal, free with krb5_free_principal() * * @return Returns 0 to indicate success. Otherwise an kerberos et * error code is returned, see krb5_get_error_message(). * * @ingroup krb5 */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_ticket_get_server ( krb5_context /*context*/, const krb5_ticket */*ticket*/, krb5_principal */*server*/); /** * If the caller passes in a negative usec, its assumed to be * unknown and the function will use the current time usec. */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_timeofday ( krb5_context /*context*/, krb5_timestamp */*timeret*/); /** * Unparse the Kerberos name into a string * * @param context Kerberos 5 context * @param principal principal to query * @param name resulting string, free with krb5_xfree() * * @return An krb5 error code, see krb5_get_error_message(). * * @ingroup krb5_principal */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_unparse_name ( krb5_context /*context*/, krb5_const_principal /*principal*/, char **/*name*/); /** * Unparse the principal name to a fixed buffer * * @param context A Kerberos context. * @param principal principal to unparse * @param name buffer to write name to * @param len length of buffer * * @return An krb5 error code, see krb5_get_error_message(). * * @ingroup krb5_principal */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_unparse_name_fixed ( krb5_context /*context*/, krb5_const_principal /*principal*/, char */*name*/, size_t /*len*/); /** * Unparse the principal name with unparse flags to a fixed buffer. * * @param context A Kerberos context. * @param principal principal to unparse * @param flags unparse flags * @param name buffer to write name to * @param len length of buffer * * @return An krb5 error code, see krb5_get_error_message(). * * @ingroup krb5_principal */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_unparse_name_fixed_flags ( krb5_context /*context*/, krb5_const_principal /*principal*/, int /*flags*/, char */*name*/, size_t /*len*/); /** * Unparse the principal name to a fixed buffer. The realm is skipped * if its a default realm. * * @param context A Kerberos context. * @param principal principal to unparse * @param name buffer to write name to * @param len length of buffer * * @return An krb5 error code, see krb5_get_error_message(). * * @ingroup krb5_principal */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_unparse_name_fixed_short ( krb5_context /*context*/, krb5_const_principal /*principal*/, char */*name*/, size_t /*len*/); /** * Unparse the Kerberos name into a string * * @param context Kerberos 5 context * @param principal principal to query * @param flags flag to determine the behavior * @param name resulting string, free with krb5_xfree() * * @return An krb5 error code, see krb5_get_error_message(). * * @ingroup krb5_principal */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_unparse_name_flags ( krb5_context /*context*/, krb5_const_principal /*principal*/, int /*flags*/, char **/*name*/); /** * Unparse the principal name to a allocated buffer. The realm is * skipped if its a default realm. * * @param context A Kerberos context. * @param principal principal to unparse * @param name returned buffer, free with krb5_xfree() * * @return An krb5 error code, see krb5_get_error_message(). * * @ingroup krb5_principal */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_unparse_name_short ( krb5_context /*context*/, krb5_const_principal /*principal*/, char **/*name*/); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_us_timeofday ( krb5_context /*context*/, krb5_timestamp */*sec*/, int32_t */*usec*/); /** * Log a warning to the log, default stderr, include bthe error from * the last failure and then abort. * * @param context A Kerberos 5 context * @param code error code of the last error * @param fmt message to print * @param ap arguments * * @ingroup krb5_error */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_vabort ( krb5_context /*context*/, krb5_error_code /*code*/, const char */*fmt*/, va_list /*ap*/) __attribute__ ((__noreturn__, __format__ (__printf__, 3, 0))); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_vabortx ( krb5_context /*context*/, const char */*fmt*/, va_list /*ap*/) __attribute__ ((__noreturn__, __format__ (__printf__, 2, 0))); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_verify_ap_req ( krb5_context /*context*/, krb5_auth_context */*auth_context*/, krb5_ap_req */*ap_req*/, krb5_const_principal /*server*/, krb5_keyblock */*keyblock*/, krb5_flags /*flags*/, krb5_flags */*ap_req_options*/, krb5_ticket **/*ticket*/); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_verify_ap_req2 ( krb5_context /*context*/, krb5_auth_context */*auth_context*/, krb5_ap_req */*ap_req*/, krb5_const_principal /*server*/, krb5_keyblock */*keyblock*/, krb5_flags /*flags*/, krb5_flags */*ap_req_options*/, krb5_ticket **/*ticket*/, krb5_key_usage /*usage*/); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_verify_authenticator_checksum ( krb5_context /*context*/, krb5_auth_context /*ac*/, void */*data*/, size_t /*len*/); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_verify_checksum ( krb5_context /*context*/, krb5_crypto /*crypto*/, krb5_key_usage /*usage*/, void */*data*/, size_t /*len*/, Checksum */*cksum*/); /** * Verify a Kerberos message checksum. * * @param context Kerberos context * @param crypto Kerberos crypto context * @param usage Key usage for this buffer * @param data array of buffers to process * @param num_data length of array * @param type return checksum type if not NULL * * @return Return an error code or 0. * @ingroup krb5_crypto */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_verify_checksum_iov ( krb5_context /*context*/, krb5_crypto /*crypto*/, unsigned /*usage*/, krb5_crypto_iov */*data*/, unsigned int /*num_data*/, krb5_cksumtype */*type*/); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_verify_init_creds ( krb5_context /*context*/, krb5_creds */*creds*/, krb5_principal /*ap_req_server*/, krb5_keytab /*ap_req_keytab*/, krb5_ccache */*ccache*/, krb5_verify_init_creds_opt */*options*/); KRB5_LIB_FUNCTION void KRB5_LIB_CALL krb5_verify_init_creds_opt_init (krb5_verify_init_creds_opt */*options*/); KRB5_LIB_FUNCTION void KRB5_LIB_CALL krb5_verify_init_creds_opt_set_ap_req_nofail ( krb5_verify_init_creds_opt */*options*/, int /*ap_req_nofail*/); KRB5_LIB_FUNCTION int KRB5_LIB_CALL krb5_verify_opt_alloc ( krb5_context /*context*/, krb5_verify_opt **/*opt*/); KRB5_LIB_FUNCTION void KRB5_LIB_CALL krb5_verify_opt_free (krb5_verify_opt */*opt*/); KRB5_LIB_FUNCTION void KRB5_LIB_CALL krb5_verify_opt_init (krb5_verify_opt */*opt*/); KRB5_LIB_FUNCTION void KRB5_LIB_CALL krb5_verify_opt_set_ccache ( krb5_verify_opt */*opt*/, krb5_ccache /*ccache*/); KRB5_LIB_FUNCTION void KRB5_LIB_CALL krb5_verify_opt_set_flags ( krb5_verify_opt */*opt*/, unsigned int /*flags*/); KRB5_LIB_FUNCTION void KRB5_LIB_CALL krb5_verify_opt_set_keytab ( krb5_verify_opt */*opt*/, krb5_keytab /*keytab*/); KRB5_LIB_FUNCTION void KRB5_LIB_CALL krb5_verify_opt_set_secure ( krb5_verify_opt */*opt*/, krb5_boolean /*secure*/); KRB5_LIB_FUNCTION void KRB5_LIB_CALL krb5_verify_opt_set_service ( krb5_verify_opt */*opt*/, const char */*service*/); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_verify_user ( krb5_context /*context*/, krb5_principal /*principal*/, krb5_ccache /*ccache*/, const char */*password*/, krb5_boolean /*secure*/, const char */*service*/); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_verify_user_lrealm ( krb5_context /*context*/, krb5_principal /*principal*/, krb5_ccache /*ccache*/, const char */*password*/, krb5_boolean /*secure*/, const char */*service*/); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_verify_user_opt ( krb5_context /*context*/, krb5_principal /*principal*/, const char */*password*/, krb5_verify_opt */*opt*/); /** * Log a warning to the log, default stderr, include bthe error from * the last failure and then exit. * * @param context A Kerberos 5 context * @param eval the exit code to exit with * @param code error code of the last error * @param fmt message to print * @param ap arguments * * @ingroup krb5_error */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_verr ( krb5_context /*context*/, int /*eval*/, krb5_error_code /*code*/, const char */*fmt*/, va_list /*ap*/) __attribute__ ((__noreturn__, __format__ (__printf__, 4, 0))); /** * Log a warning to the log, default stderr, and then exit. * * @param context A Kerberos 5 context * @param eval the exit code to exit with * @param fmt message to print * @param ap arguments * * @ingroup krb5_error */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_verrx ( krb5_context /*context*/, int /*eval*/, const char */*fmt*/, va_list /*ap*/) __attribute__ ((__noreturn__, __format__ (__printf__, 3, 0))); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_vlog ( krb5_context /*context*/, krb5_log_facility */*fac*/, int /*level*/, const char */*fmt*/, va_list /*ap*/) __attribute__ ((__format__ (__printf__, 4, 0))); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_vlog_msg ( krb5_context /*context*/, krb5_log_facility */*fac*/, char **/*reply*/, int /*level*/, const char */*fmt*/, va_list /*ap*/) __attribute__ ((__format__ (__printf__, 5, 0))); /** * Prepend the contexts's full error string for a specific error code. * * The if context is NULL, no error string is stored. * * @param context Kerberos 5 context * @param ret The error code * @param fmt Error string for the error code * @param args printf(3) style parameters. * * @ingroup krb5_error */ KRB5_LIB_FUNCTION void KRB5_LIB_CALL krb5_vprepend_error_message ( krb5_context /*context*/, krb5_error_code /*ret*/, const char */*fmt*/, va_list /*args*/) __attribute__ ((__format__ (__printf__, 3, 0))); /** * Set the context full error string for a specific error code. * * The if context is NULL, no error string is stored. * * @param context Kerberos 5 context * @param ret The error code * @param fmt Error string for the error code * @param args printf(3) style parameters. * * @ingroup krb5_error */ KRB5_LIB_FUNCTION void KRB5_LIB_CALL krb5_vset_error_message ( krb5_context /*context*/, krb5_error_code /*ret*/, const char */*fmt*/, va_list /*args*/) __attribute__ ((__format__ (__printf__, 3, 0))); /** * Set the error message returned by krb5_get_error_string(), * deprecated, use krb5_set_error_message(). * * Deprecated: use krb5_vset_error_message() * * @param context Kerberos context * @param fmt error message to free * @param args variable argument list vector * * @return Return an error code or 0. * * @ingroup krb5_deprecated */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_vset_error_string ( krb5_context /*context*/, const char */*fmt*/, va_list /*args*/) __attribute__ ((__format__ (__printf__, 2, 0))) KRB5_DEPRECATED_FUNCTION("Use X instead"); /** * Log a warning to the log, default stderr, include the error from * the last failure. * * @param context A Kerberos 5 context. * @param code error code of the last error * @param fmt message to print * @param ap arguments * * @ingroup krb5_error */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_vwarn ( krb5_context /*context*/, krb5_error_code /*code*/, const char */*fmt*/, va_list /*ap*/) __attribute__ ((__format__ (__printf__, 3, 0))); /** * Log a warning to the log, default stderr. * * @param context A Kerberos 5 context. * @param fmt message to print * @param ap arguments * * @ingroup krb5_error */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_vwarnx ( krb5_context /*context*/, const char */*fmt*/, va_list /*ap*/) __attribute__ ((__format__ (__printf__, 2, 0))); /** * Log a warning to the log, default stderr, include the error from * the last failure. * * @param context A Kerberos 5 context. * @param code error code of the last error * @param fmt message to print * * @ingroup krb5_error */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_warn ( krb5_context /*context*/, krb5_error_code /*code*/, const char */*fmt*/, ...) __attribute__ ((__format__ (__printf__, 3, 4))); /** * Log a warning to the log, default stderr. * * @param context A Kerberos 5 context. * @param fmt message to print * * @ingroup krb5_error */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_warnx ( krb5_context /*context*/, const char */*fmt*/, ...) __attribute__ ((__format__ (__printf__, 2, 3))); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_write_message ( krb5_context /*context*/, krb5_pointer /*p_fd*/, krb5_data */*data*/); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_write_priv_message ( krb5_context /*context*/, krb5_auth_context /*ac*/, krb5_pointer /*p_fd*/, krb5_data */*data*/); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_write_safe_message ( krb5_context /*context*/, krb5_auth_context /*ac*/, krb5_pointer /*p_fd*/, krb5_data */*data*/); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_xfree (void */*ptr*/); #ifdef __cplusplus } #endif #undef KRB5_DEPRECATED_FUNCTION #endif /* DOXY */ #endif /* __krb5_protos_h__ */ heimdal-7.5.0/lib/krb5/version-script.map0000644000175000017500000004651113212137553016362 0ustar niknikHEIMDAL_KRB5_2.0 { global: krb524_convert_creds_kdc; krb524_convert_creds_kdc_ccache; krb5_abort; krb5_abortx; krb5_acl_match_file; krb5_acl_match_string; krb5_add_et_list; krb5_add_extra_addresses; krb5_add_ignore_addresses; krb5_addlog_dest; krb5_addlog_func; krb5_addr2sockaddr; krb5_address_compare; krb5_address_order; krb5_address_prefixlen_boundary; krb5_address_search; krb5_allow_weak_crypto; krb5_aname_to_localname; krb5_anyaddr; krb5_appdefault_boolean; krb5_appdefault_string; krb5_appdefault_time; krb5_append_addresses; krb5_auth_con_addflags; krb5_auth_con_free; krb5_auth_con_genaddrs; krb5_auth_con_generatelocalsubkey; krb5_auth_con_getaddrs; krb5_auth_con_getauthenticator; krb5_auth_con_getcksumtype; krb5_auth_con_getflags; krb5_auth_con_getkey; krb5_auth_con_getkeytype; krb5_auth_con_getlocalseqnumber; krb5_auth_con_getlocalsubkey; krb5_auth_con_getrcache; krb5_auth_con_getremoteseqnumber; krb5_auth_con_getremotesubkey; krb5_auth_con_getsendsubkey; krb5_auth_con_init; krb5_auth_con_removeflags; krb5_auth_con_setaddrs; krb5_auth_con_setaddrs_from_fd; krb5_auth_con_setcksumtype; krb5_auth_con_setflags; krb5_auth_con_setkey; krb5_auth_con_setkeytype; krb5_auth_con_setlocalseqnumber; krb5_auth_con_setlocalsubkey; krb5_auth_con_setrcache; krb5_auth_con_setremoteseqnumber; krb5_auth_con_setremotesubkey; krb5_auth_con_setuserkey; krb5_auth_getremoteseqnumber; krb5_build_ap_req; krb5_build_principal; krb5_build_principal_ext; krb5_build_principal_va; krb5_build_principal_va_ext; krb5_c_block_size; krb5_c_checksum_length; krb5_c_decrypt; krb5_c_encrypt; krb5_c_encrypt_length; krb5_c_enctype_compare; krb5_c_get_checksum; krb5_c_is_coll_proof_cksum; krb5_c_is_keyed_cksum; krb5_c_keylengths; krb5_c_make_checksum; krb5_c_make_random_key; krb5_c_prf; krb5_c_prf_length; krb5_c_set_checksum; krb5_c_valid_cksumtype; krb5_c_valid_enctype; krb5_c_verify_checksum; krb5_cc_cache_end_seq_get; krb5_cc_cache_get_first; krb5_cc_cache_match; krb5_cc_cache_next; krb5_cc_clear_mcred; krb5_cc_close; krb5_cc_copy_cache; krb5_cc_copy_match_f; krb5_cc_default; krb5_cc_default_name; krb5_cc_destroy; krb5_cc_end_seq_get; krb5_cc_gen_new; krb5_cc_get_config; krb5_cc_get_friendly_name; krb5_cc_get_full_name; krb5_cc_get_kdc_offset; krb5_cc_get_lifetime; krb5_cc_get_name; krb5_cc_get_ops; krb5_cc_get_prefix_ops; krb5_cc_get_principal; krb5_cc_get_type; krb5_cc_get_version; krb5_cc_initialize; krb5_cc_last_change_time; krb5_cc_move; krb5_cc_new_unique; krb5_cc_next_cred; krb5_cc_next_cred_match; krb5_cc_register; krb5_cc_remove_cred; krb5_cc_resolve; krb5_cc_retrieve_cred; krb5_cc_set_config; krb5_cc_set_default_name; krb5_cc_set_flags; krb5_cc_set_kdc_offset; krb5_cc_start_seq_get; krb5_cc_store_cred; krb5_cc_support_switch; krb5_cc_switch; krb5_cc_set_friendly_name; krb5_change_password; krb5_check_transited; krb5_check_transited_realms; krb5_checksum_disable; krb5_checksum_free; krb5_checksum_is_collision_proof; krb5_checksum_is_keyed; krb5_checksumsize; krb5_cksumtype_to_enctype; krb5_cksumtype_valid; krb5_clear_error_string; krb5_clear_error_message; krb5_closelog; krb5_compare_creds; krb5_config_file_free; krb5_config_free_strings; krb5_config_get_bool; krb5_config_get_bool_default; krb5_config_get_int; krb5_config_get_int_default; krb5_config_get_list; krb5_config_get_string; krb5_config_get_string_default; krb5_config_get_strings; krb5_config_get_time; krb5_config_get_time_default; krb5_config_parse_file; krb5_config_parse_file_multi; krb5_config_parse_string_multi; krb5_config_vget_bool; krb5_config_vget_bool_default; krb5_config_vget_int; krb5_config_vget_int_default; krb5_config_vget_list; krb5_config_vget_string; krb5_config_vget_string_default; krb5_config_vget_strings; krb5_config_vget_time; krb5_config_vget_time_default; krb5_copy_address; krb5_copy_addresses; krb5_copy_checksum; krb5_copy_creds; krb5_copy_creds_contents; krb5_copy_context; krb5_copy_data; krb5_copy_host_realm; krb5_copy_keyblock; krb5_copy_keyblock_contents; krb5_copy_principal; krb5_copy_ticket; krb5_create_checksum; krb5_create_checksum_iov; krb5_crypto_destroy; krb5_crypto_fx_cf2; krb5_crypto_get_checksum_type; krb5_crypto_getblocksize; krb5_crypto_getconfoundersize; krb5_crypto_getenctype; krb5_crypto_getpadsize; krb5_crypto_init; krb5_crypto_overhead; krb5_crypto_prf; krb5_crypto_prf_length; krb5_crypto_length; krb5_crypto_length_iov; krb5_decrypt_iov_ivec; krb5_encrypt_iov_ivec; krb5_enomem; krb5_data_alloc; krb5_data_ct_cmp; krb5_data_cmp; krb5_data_copy; krb5_data_free; krb5_data_realloc; krb5_data_zero; krb5_decode_Authenticator; krb5_decode_ETYPE_INFO2; krb5_decode_ETYPE_INFO; krb5_decode_EncAPRepPart; krb5_decode_EncASRepPart; krb5_decode_EncKrbCredPart; krb5_decode_EncTGSRepPart; krb5_decode_EncTicketPart; krb5_decode_ap_req; krb5_decrypt; krb5_decrypt_EncryptedData; krb5_decrypt_ivec; krb5_decrypt_ticket; krb5_derive_key; krb5_digest_alloc; krb5_digest_free; krb5_digest_get_client_binding; krb5_digest_get_identifier; krb5_digest_get_opaque; krb5_digest_get_rsp; krb5_digest_get_server_nonce; krb5_digest_get_session_key; krb5_digest_get_tickets; krb5_digest_init_request; krb5_digest_probe; krb5_digest_rep_get_status; krb5_digest_request; krb5_digest_set_authentication_user; krb5_digest_set_authid; krb5_digest_set_client_nonce; krb5_digest_set_digest; krb5_digest_set_hostname; krb5_digest_set_identifier; krb5_digest_set_method; krb5_digest_set_nonceCount; krb5_digest_set_opaque; krb5_digest_set_qop; krb5_digest_set_realm; krb5_digest_set_responseData; krb5_digest_set_server_cb; krb5_digest_set_server_nonce; krb5_digest_set_type; krb5_digest_set_uri; krb5_digest_set_username; krb5_domain_x500_decode; krb5_domain_x500_encode; krb5_eai_to_heim_errno; krb5_encode_Authenticator; krb5_encode_ETYPE_INFO2; krb5_encode_ETYPE_INFO; krb5_encode_EncAPRepPart; krb5_encode_EncASRepPart; krb5_encode_EncKrbCredPart; krb5_encode_EncTGSRepPart; krb5_encode_EncTicketPart; krb5_encrypt; krb5_encrypt_EncryptedData; krb5_encrypt_ivec; krb5_enctype_enable; krb5_enctype_disable; krb5_enctype_keybits; krb5_enctype_keysize; krb5_enctype_to_keytype; krb5_enctype_to_string; krb5_enctype_valid; krb5_enctypes_compatible_keys; krb5_err; krb5_error_from_rd_error; krb5_errx; krb5_expand_hostname; krb5_expand_hostname_realms; krb5_find_padata; krb5_format_time; krb5_free_address; krb5_free_addresses; krb5_free_ap_rep_enc_part; krb5_free_authenticator; krb5_free_checksum; krb5_free_checksum_contents; krb5_free_config_files; krb5_free_context; krb5_free_cred_contents; krb5_free_creds; krb5_free_creds_contents; krb5_free_data; krb5_free_data_contents; krb5_free_default_realm; krb5_free_error; krb5_free_error_contents; krb5_free_error_string; krb5_free_error_message; krb5_free_host_realm; krb5_free_kdc_rep; krb5_free_keyblock; krb5_free_keyblock_contents; krb5_free_krbhst; krb5_free_principal; krb5_free_salt; krb5_free_ticket; krb5_free_unparsed_name; krb5_fwd_tgt_creds; krb5_generate_random_block; krb5_generate_random_keyblock; krb5_generate_seq_number; krb5_generate_subkey; krb5_generate_subkey_extended; krb5_get_all_client_addrs; krb5_get_all_server_addrs; krb5_get_cred_from_kdc; krb5_get_cred_from_kdc_opt; krb5_get_credentials; krb5_get_credentials_with_flags; krb5_get_creds; krb5_get_creds_opt_add_options; krb5_get_creds_opt_alloc; krb5_get_creds_opt_free; krb5_get_creds_opt_set_enctype; krb5_get_creds_opt_set_impersonate; krb5_get_creds_opt_set_options; krb5_get_creds_opt_set_ticket; krb5_get_default_config_files; krb5_get_default_in_tkt_etypes; krb5_get_default_principal; krb5_get_default_realm; krb5_get_default_realms; krb5_get_dns_canonicalize_hostname; krb5_get_err_text; krb5_get_error_message; krb5_get_error_string; krb5_get_extra_addresses; krb5_get_fcache_version; krb5_get_forwarded_creds; krb5_get_host_realm; krb5_get_ignore_addresses; krb5_get_in_cred; krb5_cccol_last_change_time; krb5_get_in_tkt; krb5_get_in_tkt_with_keytab; krb5_get_in_tkt_with_password; krb5_get_in_tkt_with_skey; krb5_get_init_creds; krb5_get_init_creds_keyblock; krb5_get_init_creds_keytab; krb5_get_init_creds_opt_alloc; krb5_get_init_creds_opt_free; krb5_get_init_creds_opt_get_error; krb5_get_init_creds_opt_init; krb5_get_init_creds_opt_set_address_list; krb5_get_init_creds_opt_set_addressless; krb5_get_init_creds_opt_set_anonymous; krb5_get_init_creds_opt_set_change_password_prompt; krb5_get_init_creds_opt_set_canonicalize; krb5_get_init_creds_opt_set_default_flags; krb5_get_init_creds_opt_set_etype_list; krb5_get_init_creds_opt_set_forwardable; krb5_get_init_creds_opt_set_pa_password; krb5_get_init_creds_opt_set_pac_request; krb5_get_init_creds_opt_set_pkinit; krb5_get_init_creds_opt_set_preauth_list; krb5_get_init_creds_opt_set_process_last_req; krb5_get_init_creds_opt_set_proxiable; krb5_get_init_creds_opt_set_renew_life; krb5_get_init_creds_opt_set_salt; krb5_get_init_creds_opt_set_tkt_life; krb5_get_init_creds_opt_set_win2k; krb5_get_init_creds_password; krb5_get_kdc_cred; krb5_get_kdc_sec_offset; krb5_get_krb524hst; krb5_get_krb_admin_hst; krb5_get_krb_changepw_hst; krb5_get_krbhst; krb5_get_max_time_skew; krb5_get_pw_salt; krb5_get_renewed_creds; krb5_get_server_rcache; krb5_get_use_admin_kdc; krb5_get_warn_dest; krb5_get_wrapped_length; krb5_getportbyname; krb5_h_addr2addr; krb5_h_addr2sockaddr; krb5_h_errno_to_heim_errno; krb5_have_error_string; krb5_hmac; krb5_init_context; krb5_init_ets; krb5_initlog; krb5_is_config_principal; krb5_is_enctype_weak; krb5_is_thread_safe; krb5_kcm_call; krb5_kcm_storage_request; krb5_kerberos_enctypes; krb5_keyblock_get_enctype; krb5_keyblock_init; krb5_keyblock_key_proc; krb5_keyblock_zero; krb5_keytab_key_proc; krb5_keytype_to_enctypes; krb5_keytype_to_enctypes_default; krb5_keytype_to_string; krb5_krbhst_format_string; krb5_krbhst_free; krb5_krbhst_get_addrinfo; krb5_krbhst_init; krb5_krbhst_init_flags; krb5_krbhst_next; krb5_krbhst_next_as_string; krb5_krbhst_reset; krb5_kt_add_entry; krb5_kt_close; krb5_kt_compare; krb5_kt_copy_entry_contents; krb5_kt_default; krb5_kt_default_modify_name; krb5_kt_default_name; krb5_kt_destroy; krb5_kt_end_seq_get; krb5_kt_free_entry; krb5_kt_get_entry; krb5_kt_get_full_name; krb5_kt_get_name; krb5_kt_get_type; krb5_kt_have_content; krb5_kt_next_entry; krb5_kt_read_service_key; krb5_kt_register; krb5_kt_remove_entry; krb5_kt_resolve; krb5_kt_start_seq_get; krb5_kuserok; krb5_log; krb5_log_msg; krb5_make_addrport; krb5_make_principal; krb5_max_sockaddr_size; krb5_mk_error; krb5_mk_error_ext; krb5_mk_priv; krb5_mk_rep; krb5_mk_req; krb5_mk_req_exact; krb5_mk_req_extended; krb5_mk_safe; krb5_net_read; krb5_net_write; krb5_net_write_block; krb5_ntlm_alloc; krb5_ntlm_free; krb5_ntlm_init_get_challenge; krb5_ntlm_init_get_flags; krb5_ntlm_init_get_opaque; krb5_ntlm_init_get_targetinfo; krb5_ntlm_init_get_targetname; krb5_ntlm_init_request; krb5_ntlm_rep_get_sessionkey; krb5_ntlm_rep_get_status; krb5_ntlm_req_set_flags; krb5_ntlm_req_set_lm; krb5_ntlm_req_set_ntlm; krb5_ntlm_req_set_opaque; krb5_ntlm_req_set_session; krb5_ntlm_req_set_targetname; krb5_ntlm_req_set_username; krb5_ntlm_request; krb5_openlog; krb5_pac_add_buffer; krb5_pac_free; krb5_pac_get_buffer; krb5_pac_get_types; krb5_pac_init; krb5_pac_parse; krb5_pac_verify; krb5_padata_add; krb5_parse_address; krb5_parse_name; krb5_parse_name_flags; krb5_parse_nametype; krb5_passwd_result_to_string; krb5_password_key_proc; krb5_get_permitted_enctypes; krb5_plugin_register; krb5_prepend_config_files; krb5_prepend_config_files_default; krb5_prepend_error_message; krb5_princ_realm; krb5_princ_set_realm; krb5_principal_compare; krb5_principal_compare_any_realm; krb5_principal_get_comp_string; krb5_principal_get_num_comp; krb5_principal_get_realm; krb5_principal_get_type; krb5_principal_match; krb5_principal_set_comp_string; krb5_principal_set_realm; krb5_principal_set_type; krb5_principal_is_krbtgt; krb5_print_address; krb5_program_setup; krb5_prompter_posix; krb5_random_to_key; krb5_rc_close; krb5_rc_default; krb5_rc_default_name; krb5_rc_default_type; krb5_rc_destroy; krb5_rc_expunge; krb5_rc_get_lifespan; krb5_rc_get_name; krb5_rc_get_type; krb5_rc_initialize; krb5_rc_recover; krb5_rc_resolve; krb5_rc_resolve_full; krb5_rc_resolve_type; krb5_rc_store; krb5_rd_cred2; krb5_rd_cred; krb5_rd_error; krb5_rd_priv; krb5_rd_rep; krb5_rd_req; krb5_rd_req_ctx; krb5_rd_req_in_ctx_alloc; krb5_rd_req_in_ctx_free; krb5_rd_req_in_set_keyblock; krb5_rd_req_in_set_keytab; krb5_rd_req_in_set_pac_check; krb5_rd_req_out_ctx_free; krb5_rd_req_out_get_ap_req_options; krb5_rd_req_out_get_keyblock; krb5_rd_req_out_get_ticket; krb5_rd_req_with_keyblock; krb5_rd_safe; krb5_read_message; krb5_read_priv_message; krb5_read_safe_message; krb5_realm_compare; krb5_recvauth; krb5_recvauth_match_version; krb5_ret_address; krb5_ret_addrs; krb5_ret_authdata; krb5_ret_creds; krb5_ret_creds_tag; krb5_ret_data; krb5_ret_int16; krb5_ret_int32; krb5_ret_int64; krb5_ret_int8; krb5_ret_keyblock; krb5_ret_principal; krb5_ret_string; krb5_ret_stringnl; krb5_ret_stringz; krb5_ret_times; krb5_ret_uint16; krb5_ret_uint32; krb5_ret_uint64; krb5_ret_uint8; krb5_salttype_to_string; krb5_sendauth; krb5_sendto; krb5_sendto_context; krb5_sendto_ctx_add_flags; krb5_sendto_ctx_alloc; krb5_sendto_ctx_free; krb5_sendto_ctx_get_flags; krb5_sendto_ctx_set_func; krb5_sendto_ctx_set_type; krb5_sendto_kdc; krb5_sendto_kdc_flags; krb5_set_config_files; krb5_set_debug_dest; krb5_set_default_in_tkt_etypes; krb5_set_default_realm; krb5_set_dns_canonicalize_hostname; krb5_set_error_message; krb5_set_error_string; krb5_set_extra_addresses; krb5_set_fcache_version; krb5_set_home_dir_access; krb5_set_ignore_addresses; krb5_set_kdc_sec_offset; krb5_set_max_time_skew; krb5_set_password; krb5_set_password_using_ccache; krb5_set_real_time; krb5_set_send_to_kdc_func; krb5_set_use_admin_kdc; krb5_set_warn_dest; krb5_sname_to_principal; krb5_sock_to_principal; krb5_sockaddr2address; krb5_sockaddr2port; krb5_sockaddr_uninteresting; krb5_std_usage; krb5_storage_clear_flags; krb5_storage_emem; krb5_storage_free; krb5_storage_from_data; krb5_storage_from_fd; krb5_storage_from_mem; krb5_storage_from_readonly_mem; krb5_storage_from_socket; krb5_storage_fsync; krb5_storage_get_byteorder; krb5_storage_get_eof_code; krb5_storage_is_flags; krb5_storage_read; krb5_storage_seek; krb5_storage_set_byteorder; krb5_storage_set_eof_code; krb5_storage_set_flags; krb5_storage_set_max_alloc; krb5_storage_to_data; krb5_storage_truncate; krb5_storage_write; krb5_store_address; krb5_store_addrs; krb5_store_authdata; krb5_store_creds; krb5_store_creds_tag; krb5_store_data; krb5_store_int16; krb5_store_int32; krb5_store_int64; krb5_store_int8; krb5_store_keyblock; krb5_store_principal; krb5_store_string; krb5_store_stringnl; krb5_store_stringz; krb5_store_times; krb5_store_uint16; krb5_store_uint32; krb5_store_uint64; krb5_store_uint8; krb5_string_to_deltat; krb5_string_to_enctype; krb5_string_to_key; krb5_string_to_key_data; krb5_string_to_key_data_salt; krb5_string_to_key_data_salt_opaque; krb5_string_to_key_derived; krb5_string_to_key_salt; krb5_string_to_key_salt_opaque; krb5_string_to_keytype; krb5_string_to_salttype; krb5_ticket_get_authorization_data_type; krb5_ticket_get_client; krb5_ticket_get_endtime; krb5_ticket_get_server; krb5_timeofday; krb5_unparse_name; krb5_unparse_name_fixed; krb5_unparse_name_fixed_flags; krb5_unparse_name_fixed_short; krb5_unparse_name_flags; krb5_unparse_name_short; krb5_us_timeofday; krb5_vabort; krb5_vabortx; krb5_verify_ap_req2; krb5_verify_ap_req; krb5_verify_authenticator_checksum; krb5_verify_checksum; krb5_verify_checksum_iov; krb5_verify_init_creds; krb5_verify_init_creds_opt_init; krb5_verify_init_creds_opt_set_ap_req_nofail; krb5_verify_opt_alloc; krb5_verify_opt_free; krb5_verify_opt_init; krb5_verify_opt_set_ccache; krb5_verify_opt_set_flags; krb5_verify_opt_set_keytab; krb5_verify_opt_set_secure; krb5_verify_opt_set_service; krb5_verify_user; krb5_verify_user_lrealm; krb5_verify_user_opt; krb5_verr; krb5_verrx; krb5_vlog; krb5_vlog_msg; krb5_vprepend_error_message; krb5_vset_error_message; krb5_vset_error_string; krb5_vwarn; krb5_vwarnx; krb5_warn; krb5_warnx; krb5_write_message; krb5_write_priv_message; krb5_write_safe_message; krb5_xfree; krb5_cccol_cursor_new; krb5_cccol_cursor_next; krb5_cccol_cursor_free; # com_err error tables initialize_krb5_error_table_r; initialize_krb5_error_table; initialize_krb_error_table_r; initialize_krb_error_table; initialize_heim_error_table_r; initialize_heim_error_table; initialize_k524_error_table_r; initialize_k524_error_table; # variables krb5_dcc_ops; krb5_mcc_ops; krb5_acc_ops; krb5_fcc_ops; krb5_scc_ops; krb5_kcm_ops; krb5_wrfkt_ops; krb5_mkt_ops; krb5_akf_ops; krb5_any_ops; heimdal_version; heimdal_long_version; krb5_config_file; krb5_defkeyname; krb5_cc_type_api; krb5_cc_type_dcc; krb5_cc_type_file; krb5_cc_type_memory; krb5_cc_type_kcm; krb5_cc_type_scc; # shared with HDB _krb5_plugin_run_f; _krb5_enctype_requires_random_salt; # Shared with GSSAPI krb5 _krb5_crc_init_table; _krb5_crc_update; _krb5_get_krbtgt; _krb5_build_authenticator; # Shared with libkdc _krb5_AES_SHA1_string_to_default_iterator; _krb5_AES_SHA2_string_to_default_iterator; _krb5_dh_group_ok; _krb5_get_host_realm_int; _krb5_get_int; _krb5_get_int64; _krb5_pac_sign; _krb5_parse_moduli; _krb5_pk_kdf; _krb5_pk_load_id; _krb5_pk_mk_ContentInfo; _krb5_pk_octetstring2key; _krb5_plugin_find; _krb5_plugin_free; _krb5_plugin_run_f; _krb5_principal2principalname; _krb5_principalname2krb5_principal; _krb5_put_int; _krb5_s4u2self_to_checksumdata; # kinit helper krb5_get_init_creds_opt_set_pkinit_user_certs; krb5_pk_enterprise_cert; krb5_process_last_request; krb5_init_creds_init; krb5_init_creds_set_service; krb5_init_creds_set_fast_ccache; krb5_init_creds_set_keytab; krb5_init_creds_get; krb5_init_creds_get_creds; krb5_init_creds_get_error; krb5_init_creds_set_password; krb5_init_creds_store; krb5_init_creds_free; # testing _krb5_aes_cts_encrypt; _krb5_n_fold; _krb5_expand_default_cc_name; _krb5_expand_path_tokensv; # FAST _krb5_fast_cf2; _krb5_fast_armor_key; # TGS _krb5_find_capath; _krb5_free_capath; local: *; }; heimdal-7.5.0/lib/krb5/krb5_verify_init_creds.cat30000644000175000017500000000650013212450757020100 0ustar niknik KRB5_VERIFY_INIT_CRED... BSD Library Functions Manual KRB5_VERIFY_INIT_CRED... NNAAMMEE kkrrbb55__vveerriiffyy__iinniitt__ccrreeddss__oopptt__iinniitt, kkrrbb55__vveerriiffyy__iinniitt__ccrreeddss__oopptt__sseett__aapp__rreeqq__nnooffaaiill, kkrrbb55__vveerriiffyy__iinniitt__ccrreeddss -- verifies a credential cache is correct by using a local keytab LLIIBBRRAARRYY Kerberos 5 Library (libkrb5, -lkrb5) SSYYNNOOPPSSIISS ##iinncclluuddee <> struct krb5_verify_init_creds_opt; _v_o_i_d kkrrbb55__vveerriiffyy__iinniitt__ccrreeddss__oopptt__iinniitt(_k_r_b_5___v_e_r_i_f_y___i_n_i_t___c_r_e_d_s___o_p_t _*_o_p_t_i_o_n_s); _v_o_i_d kkrrbb55__vveerriiffyy__iinniitt__ccrreeddss__oopptt__sseett__aapp__rreeqq__nnooffaaiill(_k_r_b_5___v_e_r_i_f_y___i_n_i_t___c_r_e_d_s___o_p_t _*_o_p_t_i_o_n_s, _i_n_t _a_p___r_e_q___n_o_f_a_i_l); _k_r_b_5___e_r_r_o_r___c_o_d_e kkrrbb55__vveerriiffyy__iinniitt__ccrreeddss(_k_r_b_5___c_o_n_t_e_x_t _c_o_n_t_e_x_t, _k_r_b_5___c_r_e_d_s _*_c_r_e_d_s, _k_r_b_5___p_r_i_n_c_i_p_a_l _a_p___r_e_q___s_e_r_v_e_r, _k_r_b_5___c_c_a_c_h_e _*_c_c_a_c_h_e, _k_r_b_5___v_e_r_i_f_y___i_n_i_t___c_r_e_d_s___o_p_t _*_o_p_t_i_o_n_s); DDEESSCCRRIIPPTTIIOONN The kkrrbb55__vveerriiffyy__iinniitt__ccrreeddss function verifies the initial tickets with the local keytab to make sure the response of the KDC was spoof-ed. kkrrbb55__vveerriiffyy__iinniitt__ccrreeddss will use principal _a_p___r_e_q___s_e_r_v_e_r from the local keytab, if NULL is passed in, the code will guess the local hostname and use that to form host/hostname/GUESSED-REALM-FOR-HOSTNAME. _c_r_e_d_s is the credential that kkrrbb55__vveerriiffyy__iinniitt__ccrreeddss should verify. If _c_c_a_c_h_e is given kkrrbb55__vveerriiffyy__iinniitt__ccrreeddss() stores all credentials it fetched from the KDC there, otherwise it will use a memory credential cache that is destroyed when done. kkrrbb55__vveerriiffyy__iinniitt__ccrreeddss__oopptt__iinniitt() cleans the the structure, must be used before trying to pass it in to kkrrbb55__vveerriiffyy__iinniitt__ccrreeddss(). kkrrbb55__vveerriiffyy__iinniitt__ccrreeddss__oopptt__sseett__aapp__rreeqq__nnooffaaiill() controls controls the behavior if _a_p___r_e_q___s_e_r_v_e_r doesn't exists in the local keytab or in the KDC's database, if it's true, the error will be ignored. Note that this use is possible insecure. SSEEEE AALLSSOO krb5(3), krb5_get_init_creds(3), krb5_verify_user(3), krb5.conf(5) HEIMDAL May 1, 2006 HEIMDAL heimdal-7.5.0/lib/krb5/verify_krb5_conf.c0000644000175000017500000006324413026237312016273 0ustar niknik/* * Copyright (c) 1999 - 2005 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "krb5_locl.h" #include #include #include /* verify krb5.conf */ static int dumpconfig_flag = 0; static int version_flag = 0; static int help_flag = 0; static int warn_mit_syntax_flag = 0; static struct getargs args[] = { {"dumpconfig", 0, arg_flag, &dumpconfig_flag, "show the parsed config files", NULL }, {"warn-mit-syntax", 0, arg_flag, &warn_mit_syntax_flag, "show the parsed config files", NULL }, {"version", 0, arg_flag, &version_flag, "print version", NULL }, {"help", 0, arg_flag, &help_flag, NULL, NULL } }; static void usage (int ret) { arg_printusage (args, sizeof(args)/sizeof(*args), NULL, "[config-file]"); exit (ret); } static int check_bytes(krb5_context context, const char *path, char *data) { if(parse_bytes(data, NULL) == -1) { krb5_warnx(context, "%s: failed to parse \"%s\" as size", path, data); return 1; } return 0; } static int check_time(krb5_context context, const char *path, char *data) { if(parse_time(data, NULL) == -1) { krb5_warnx(context, "%s: failed to parse \"%s\" as time", path, data); return 1; } return 0; } static int check_numeric(krb5_context context, const char *path, char *data) { long v; char *end; v = strtol(data, &end, 0); if ((v == LONG_MIN || v == LONG_MAX) && errno != 0) { krb5_warnx(context, "%s: over/under flow for \"%s\"", path, data); return 1; } if(*end != '\0') { krb5_warnx(context, "%s: failed to parse \"%s\" as a number", path, data); return 1; } return 0; } static int check_boolean(krb5_context context, const char *path, char *data) { long int v; char *end; if(strcasecmp(data, "yes") == 0 || strcasecmp(data, "true") == 0 || strcasecmp(data, "no") == 0 || strcasecmp(data, "false") == 0) return 0; v = strtol(data, &end, 0); if(*end != '\0') { krb5_warnx(context, "%s: failed to parse \"%s\" as a boolean", path, data); return 1; } if(v != 0 && v != 1) krb5_warnx(context, "%s: numeric value \"%s\" is treated as \"true\"", path, data); return 0; } static int check_524(krb5_context context, const char *path, char *data) { if(strcasecmp(data, "yes") == 0 || strcasecmp(data, "no") == 0 || strcasecmp(data, "2b") == 0 || strcasecmp(data, "local") == 0) return 0; krb5_warnx(context, "%s: didn't contain a valid option `%s'", path, data); return 1; } static int check_host(krb5_context context, const char *path, char *data) { int ret; char hostname[128]; const char *p = data; struct addrinfo hints; char service[32]; int defport; struct addrinfo *ai; hints.ai_flags = 0; hints.ai_family = PF_UNSPEC; hints.ai_socktype = 0; hints.ai_protocol = 0; hints.ai_addrlen = 0; hints.ai_canonname = NULL; hints.ai_addr = NULL; hints.ai_next = NULL; /* XXX data could be a list of hosts that this code can't handle */ /* XXX copied from krbhst.c */ if (strncmp(p, "http://", 7) == 0){ p += 7; hints.ai_socktype = SOCK_STREAM; strlcpy(service, "http", sizeof(service)); defport = 80; } else if (strncmp(p, "http/", 5) == 0) { p += 5; hints.ai_socktype = SOCK_STREAM; strlcpy(service, "http", sizeof(service)); defport = 80; } else if (strncmp(p, "tcp/", 4) == 0){ p += 4; hints.ai_socktype = SOCK_STREAM; strlcpy(service, "kerberos", sizeof(service)); defport = 88; } else if (strncmp(p, "udp/", 4) == 0) { p += 4; hints.ai_socktype = SOCK_DGRAM; strlcpy(service, "kerberos", sizeof(service)); defport = 88; } else { hints.ai_socktype = SOCK_DGRAM; strlcpy(service, "kerberos", sizeof(service)); defport = 88; } if (strsep_copy(&p, ":", hostname, sizeof(hostname)) < 0) { return 1; } hostname[strcspn(hostname, "/")] = '\0'; if (p != NULL) { char *end; int tmp = strtol(p, &end, 0); if (end == p) { krb5_warnx(context, "%s: failed to parse port number in %s", path, data); return 1; } defport = tmp; snprintf(service, sizeof(service), "%u", defport); } ret = getaddrinfo(hostname, service, &hints, &ai); if (ret == EAI_SERVICE && !isdigit((unsigned char)service[0])) { snprintf(service, sizeof(service), "%u", defport); ret = getaddrinfo(hostname, service, &hints, &ai); } if (ret != 0) { krb5_warnx(context, "%s: %s (%s)", path, gai_strerror(ret), hostname); return 1; } freeaddrinfo(ai); return 0; } static int mit_entry(krb5_context context, const char *path, char *data) { if (warn_mit_syntax_flag) krb5_warnx(context, "%s is only used by MIT Kerberos", path); return 0; } struct s2i { const char *s; int val; }; #define L(X) { #X, LOG_ ## X } static struct s2i syslogvals[] = { /* severity */ L(EMERG), L(ALERT), L(CRIT), L(ERR), L(WARNING), L(NOTICE), L(INFO), L(DEBUG), /* facility */ L(AUTH), #ifdef LOG_AUTHPRIV L(AUTHPRIV), #endif #ifdef LOG_CRON L(CRON), #endif L(DAEMON), #ifdef LOG_FTP L(FTP), #endif L(KERN), L(LPR), L(MAIL), #ifdef LOG_NEWS L(NEWS), #endif L(SYSLOG), L(USER), #ifdef LOG_UUCP L(UUCP), #endif L(LOCAL0), L(LOCAL1), L(LOCAL2), L(LOCAL3), L(LOCAL4), L(LOCAL5), L(LOCAL6), L(LOCAL7), { NULL, -1 } }; static int find_value(const char *s, struct s2i *table) { while(table->s && strcasecmp(table->s, s)) table++; return table->val; } static int check_log(krb5_context context, const char *path, char *data) { /* XXX sync with log.c */ int min = 0, max = -1, n; char c; const char *p = data; #ifdef _WIN32 const char *q; #endif n = sscanf(p, "%d%c%d/", &min, &c, &max); if(n == 2){ if(ISPATHSEP(c)) { if(min < 0){ max = -min; min = 0; }else{ max = min; } } } if(n){ #ifdef _WIN32 q = strrchr(p, '\\'); if (q != NULL) p = q; else #endif p = strchr(p, '/'); if(p == NULL) { krb5_warnx(context, "%s: failed to parse \"%s\"", path, data); return 1; } p++; } if(strcmp(p, "STDERR") == 0 || strcmp(p, "CONSOLE") == 0 || (strncmp(p, "FILE", 4) == 0 && (p[4] == ':' || p[4] == '=')) || (strncmp(p, "DEVICE", 6) == 0 && p[6] == '=')) return 0; if(strncmp(p, "SYSLOG", 6) == 0){ int ret = 0; char severity[128] = ""; char facility[128] = ""; p += 6; if(*p != '\0') p++; if(strsep_copy(&p, ":", severity, sizeof(severity)) != -1) strsep_copy(&p, ":", facility, sizeof(facility)); if(*severity == '\0') strlcpy(severity, "ERR", sizeof(severity)); if(*facility == '\0') strlcpy(facility, "AUTH", sizeof(facility)); if(find_value(facility, syslogvals) == -1) { krb5_warnx(context, "%s: unknown syslog facility \"%s\"", path, facility); ret++; } if(find_value(severity, syslogvals) == -1) { krb5_warnx(context, "%s: unknown syslog severity \"%s\"", path, severity); ret++; } return ret; }else{ krb5_warnx(context, "%s: unknown log type: \"%s\"", path, data); return 1; } } typedef int (*check_func_t)(krb5_context, const char*, char*); struct entry { const char *name; int type; void *check_data; int deprecated; }; struct entry all_strings[] = { { "", krb5_config_string, NULL, 0 }, { NULL, 0, NULL, 0 } }; struct entry all_boolean[] = { { "", krb5_config_string, check_boolean, 0 }, { NULL, 0, NULL, 0 } }; struct entry v4_name_convert_entries[] = { { "host", krb5_config_list, all_strings, 0 }, { "plain", krb5_config_list, all_strings, 0 }, { NULL, 0, NULL, 0 } }; struct entry libdefaults_entries[] = { { "accept_null_addresses", krb5_config_string, check_boolean, 0 }, { "allow_weak_crypto", krb5_config_string, check_boolean, 0 }, { "capath", krb5_config_list, all_strings, 1 }, { "ccapi_library", krb5_config_string, NULL, 0 }, { "check_pac", krb5_config_string, check_boolean, 0 }, { "check-rd-req-server", krb5_config_string, check_boolean, 0 }, { "clockskew", krb5_config_string, check_time, 0 }, { "date_format", krb5_config_string, NULL, 0 }, { "default_as_etypes", krb5_config_string, NULL, 0 }, { "default_cc_name", krb5_config_string, NULL, 0 }, { "default_cc_type", krb5_config_string, NULL, 0 }, { "default_etypes", krb5_config_string, NULL, 0 }, { "default_etypes_des", krb5_config_string, NULL, 0 }, { "default_keytab_modify_name", krb5_config_string, NULL, 0 }, { "default_keytab_name", krb5_config_string, NULL, 0 }, { "default_keytab_modify_name", krb5_config_string, NULL, 0 }, { "default_realm", krb5_config_string, NULL, 0 }, { "default_tgs_etypes", krb5_config_string, NULL, 0 }, { "dns_canonize_hostname", krb5_config_string, check_boolean, 0 }, { "dns_proxy", krb5_config_string, NULL, 0 }, { "dns_lookup_kdc", krb5_config_string, check_boolean, 0 }, { "dns_lookup_realm", krb5_config_string, check_boolean, 0 }, { "dns_lookup_realm_labels", krb5_config_string, NULL, 0 }, { "egd_socket", krb5_config_string, NULL, 0 }, { "encrypt", krb5_config_string, check_boolean, 0 }, { "extra_addresses", krb5_config_string, NULL, 0 }, { "fcache_version", krb5_config_string, check_numeric, 0 }, { "fcache_strict_checking", krb5_config_string, check_boolean, 0 }, { "fcc-mit-ticketflags", krb5_config_string, check_boolean, 0 }, { "forward", krb5_config_string, check_boolean, 0 }, { "forwardable", krb5_config_string, check_boolean, 0 }, { "allow_hierarchical_capaths", krb5_config_string, check_boolean, 0 }, { "host_timeout", krb5_config_string, check_time, 0 }, { "http_proxy", krb5_config_string, check_host /* XXX */, 0 }, { "ignore_addresses", krb5_config_string, NULL, 0 }, { "k5login_authoritative", krb5_config_string, check_boolean, 0 }, { "k5login_directory", krb5_config_string, NULL, 0 }, { "kdc_timeout", krb5_config_string, check_time, 0 }, { "kdc_timesync", krb5_config_string, check_boolean, 0 }, { "kuserok", krb5_config_string, NULL, 0 }, { "large_message_size", krb5_config_string, check_numeric, 0 }, { "log_utc", krb5_config_string, check_boolean, 0 }, { "max_retries", krb5_config_string, check_numeric, 0 }, { "maximum_message_size", krb5_config_string, check_numeric, 0 }, { "moduli", krb5_config_string, NULL, 0 }, { "name_canon_rules", krb5_config_string, NULL, 0 }, { "no-addresses", krb5_config_string, check_boolean, 0 }, { "pkinit_dh_min_bits", krb5_config_string, NULL, 0 }, { "proxiable", krb5_config_string, check_boolean, 0 }, { "renew_lifetime", krb5_config_string, check_time, 0 }, { "scan_interfaces", krb5_config_string, check_boolean, 0 }, { "srv_lookup", krb5_config_string, check_boolean, 0 }, { "srv_try_txt", krb5_config_string, check_boolean, 0 }, { "ticket_lifetime", krb5_config_string, check_time, 0 }, { "time_format", krb5_config_string, NULL, 0 }, { "transited_realms_reject", krb5_config_string, NULL, 0 }, { "use_fallback", krb5_config_string, check_boolean, 0 }, { "v4_instance_resolve", krb5_config_string, check_boolean, 0 }, { "v4_name_convert", krb5_config_list, v4_name_convert_entries, 0 }, { "verify_ap_req_nofail", krb5_config_string, check_boolean, 0 }, { "warn_pwexpire", krb5_config_string, check_time, 0 }, /* MIT stuff */ { "permitted_enctypes", krb5_config_string, mit_entry, 0 }, { "default_tgs_enctypes", krb5_config_string, mit_entry, 0 }, { "default_tkt_enctypes", krb5_config_string, mit_entry, 0 }, { NULL, 0, NULL, 0 } }; struct entry appdefaults_entries[] = { { "afslog", krb5_config_string, check_boolean, 0 }, { "afs-use-524", krb5_config_string, check_524, 0 }, #if 0 { "anonymous", krb5_config_string, check_boolean, 0 }, #endif { "encrypt", krb5_config_string, check_boolean, 0 }, { "forward", krb5_config_string, check_boolean, 0 }, { "forwardable", krb5_config_string, check_boolean, 0 }, { "krb4_get_tickets", krb5_config_string, check_boolean, 0 }, { "proxiable", krb5_config_string, check_boolean, 0 }, { "renew_lifetime", krb5_config_string, check_time, 0 }, { "no-addresses", krb5_config_string, check_boolean, 0 }, { "pkinit_anchors", krb5_config_string, NULL, 0 }, { "pkinit_pool", krb5_config_string, NULL, 0 }, { "pkinit_require_eku", krb5_config_string, NULL, 0 }, { "pkinit_require_hostname_match", krb5_config_string, NULL, 0 }, { "pkinit_require_krbtgt_otherName", krb5_config_string, NULL, 0 }, { "pkinit_revoke", krb5_config_string, NULL, 0 }, { "pkinit_trustedCertifiers", krb5_config_string, check_boolean, 0 }, { "pkinit_win2k", krb5_config_string, NULL, 0 }, { "pkinit_win2k_require_binding", krb5_config_string, NULL, 0 }, { "ticket_lifetime", krb5_config_string, check_time, 0 }, { "", krb5_config_list, appdefaults_entries, 0 }, { NULL, 0, NULL, 0 } }; struct entry realms_entries[] = { { "admin_server", krb5_config_string, check_host, 0 }, { "auth_to_local", krb5_config_string, NULL, 0 }, { "auth_to_local_names", krb5_config_string, NULL, 0 }, { "default_domain", krb5_config_string, NULL, 0 }, { "forwardable", krb5_config_string, check_boolean, 0 }, { "allow_hierarchical_capaths", krb5_config_string, check_boolean, 0 }, { "kdc", krb5_config_string, check_host, 0 }, { "kpasswd_server", krb5_config_string, check_host, 0 }, { "krb524_server", krb5_config_string, check_host, 0 }, { "kx509_ca", krb5_config_string, NULL, 0 }, { "kx509_include_pkinit_san", krb5_config_string, check_boolean, 0 }, { "name_canon_rules", krb5_config_string, NULL, 0 }, { "no-addresses", krb5_config_string, check_boolean, 0 }, { "pkinit_anchors", krb5_config_string, NULL, 0 }, { "pkinit_require_eku", krb5_config_string, NULL, 0 }, { "pkinit_require_hostname_match", krb5_config_string, NULL, 0 }, { "pkinit_require_krbtgt_otherName", krb5_config_string, NULL, 0 }, { "pkinit_trustedCertifiers", krb5_config_string, check_boolean, 0 }, { "pkinit_win2k", krb5_config_string, NULL, 0 }, { "pkinit_win2k_require_binding", krb5_config_string, NULL, 0 }, { "proxiable", krb5_config_string, check_boolean, 0 }, { "renew_lifetime", krb5_config_string, check_time, 0 }, { "require_initial_kca_tickets", krb5_config_string, check_boolean, 0 }, { "ticket_lifetime", krb5_config_string, check_time, 0 }, { "v4_domains", krb5_config_string, NULL, 0 }, { "v4_instance_convert", krb5_config_list, all_strings, 0 }, { "v4_name_convert", krb5_config_list, v4_name_convert_entries, 0 }, { "warn_pwexpire", krb5_config_string, check_time, 0 }, { "win2k_pkinit", krb5_config_string, NULL, 0 }, /* MIT stuff */ { "admin_keytab", krb5_config_string, mit_entry, 0 }, { "acl_file", krb5_config_string, mit_entry, 0 }, { "database_name", krb5_config_string, mit_entry, 0 }, { "default_principal_expiration", krb5_config_string, mit_entry, 0 }, { "default_principal_flags", krb5_config_string, mit_entry, 0 }, { "dict_file", krb5_config_string, mit_entry, 0 }, { "kadmind_port", krb5_config_string, mit_entry, 0 }, { "kpasswd_port", krb5_config_string, mit_entry, 0 }, { "master_kdc", krb5_config_string, mit_entry, 0 }, { "master_key_name", krb5_config_string, mit_entry, 0 }, { "master_key_type", krb5_config_string, mit_entry, 0 }, { "key_stash_file", krb5_config_string, mit_entry, 0 }, { "max_life", krb5_config_string, mit_entry, 0 }, { "max_renewable_life", krb5_config_string, mit_entry, 0 }, { "supported_enctypes", krb5_config_string, mit_entry, 0 }, { NULL, 0, NULL, 0 } }; struct entry realms_foobar[] = { { "", krb5_config_list, realms_entries, 0 }, { NULL, 0, NULL, 0 } }; struct entry kdc_database_entries[] = { { "acl_file", krb5_config_string, NULL, 0 }, { "dbname", krb5_config_string, NULL, 0 }, { "log_file", krb5_config_string, NULL, 0 }, { "mkey_file", krb5_config_string, NULL, 0 }, { "realm", krb5_config_string, NULL, 0 }, { NULL, 0, NULL, 0 } }; struct entry kdc_entries[] = { { "addresses", krb5_config_string, NULL, 0 }, { "allow-anonymous", krb5_config_string, check_boolean, 0 }, { "allow-null-ticket-addresses", krb5_config_string, check_boolean, 0 }, { "check-ticket-addresses", krb5_config_string, check_boolean, 0 }, { "database", krb5_config_list, kdc_database_entries, 0 }, { "detach", krb5_config_string, check_boolean, 0 }, { "digests_allowed", krb5_config_string, NULL, 0 }, { "disable-des", krb5_config_string, check_boolean, 0 }, { "enable-524", krb5_config_string, check_boolean, 0 }, { "enable-digest", krb5_config_string, check_boolean, 0 }, { "enable-kaserver", krb5_config_string, check_boolean, 1 }, { "enable-kerberos4", krb5_config_string, check_boolean, 1 }, { "enable-kx509", krb5_config_string, check_boolean, 0 }, { "enable-http", krb5_config_string, check_boolean, 0 }, { "enable-pkinit", krb5_config_string, check_boolean, 0 }, { "encode_as_rep_as_tgs_rep", krb5_config_string, check_boolean, 0 }, { "enforce-transited-policy", krb5_config_string, NULL, 1 }, { "hdb-ldap-create-base", krb5_config_string, NULL, 0 }, { "iprop-acl", krb5_config_string, NULL, 0 }, { "iprop-stats", krb5_config_string, NULL, 0 }, { "kdc-request-log", krb5_config_string, NULL, 0 }, { "kdc_warn_pwexpire", krb5_config_string, check_time, 0 }, { "key-file", krb5_config_string, NULL, 0 }, { "kx509_ca", krb5_config_string, NULL, 0 }, { "kx509_include_pkinit_san", krb5_config_string, check_boolean, 0 }, { "kx509_template", krb5_config_string, NULL, 0 }, { "logging", krb5_config_string, check_log, 0 }, { "max-kdc-datagram-reply-length", krb5_config_string, check_bytes, 0 }, { "max-request", krb5_config_string, check_bytes, 0 }, { "pkinit_allow_proxy_certificate", krb5_config_string, check_boolean, 0 }, { "pkinit_anchors", krb5_config_string, NULL, 0 }, { "pkinit_dh_min_bits", krb5_config_string, check_numeric, 0 }, { "pkinit_identity", krb5_config_string, NULL, 0 }, { "pkinit_kdc_friendly_name", krb5_config_string, NULL, 0 }, { "pkinit_kdc_ocsp", krb5_config_string, NULL, 0 }, { "pkinit_mappings_file", krb5_config_string, NULL, 0 }, { "pkinit_pool", krb5_config_string, NULL, 0 }, { "pkinit_principal_in_certificate", krb5_config_string, check_boolean, 0 }, { "pkinit_revoke", krb5_config_string, NULL, 0 }, { "pkinit_win2k_require_binding", krb5_config_string, check_boolean, 0 }, { "ports", krb5_config_string, NULL, 0 }, { "preauth-use-strongest-session-key", krb5_config_string, check_boolean, 0 }, { "require_initial_kca_tickets", krb5_config_string, check_boolean, 0 }, { "require-preauth", krb5_config_string, check_boolean, 0 }, { "svc-use-strongest-session-key", krb5_config_string, check_boolean, 0 }, { "tgt-use-strongest-session-key", krb5_config_string, check_boolean, 0 }, { "transited-policy", krb5_config_string, NULL, 0 }, { "use_2b", krb5_config_list, NULL, 0 }, { "use-strongest-server-key", krb5_config_string, check_boolean, 0 }, { "v4_realm", krb5_config_string, NULL, 0 }, { NULL, 0, NULL, 0 } }; struct entry kadmin_entries[] = { { "allow_self_change_password", krb5_config_string, check_boolean, 0 }, { "default_keys", krb5_config_string, NULL, 0 }, { "password_lifetime", krb5_config_string, check_time, 0 }, { "require-preauth", krb5_config_string, check_boolean, 0 }, { "save-password", krb5_config_string, check_boolean, 0 }, { "use_v4_salt", krb5_config_string, NULL, 0 }, { NULL, 0, NULL, 0 } }; struct entry log_strings[] = { { "", krb5_config_string, check_log, 0 }, { NULL, 0, NULL, 0 } }; /* MIT stuff */ struct entry kdcdefaults_entries[] = { { "kdc_ports", krb5_config_string, mit_entry, 0 }, { "v4_mode", krb5_config_string, mit_entry, 0 }, { NULL, 0, NULL, 0 } }; struct entry capaths_entries[] = { { "", krb5_config_list, all_strings, 0 }, { NULL, 0, NULL, 0 } }; struct entry kcm_entries[] = { { "detach", krb5_config_string, check_boolean, 0 }, { "disallow-getting-krbtgt", krb5_config_string, check_boolean, 0 }, { "logging", krb5_config_string, NULL, 0 }, { "max-request", krb5_config_string, NULL, 0 }, { "system_ccache", krb5_config_string, NULL, 0 }, { NULL, 0, NULL, 0 } }; struct entry password_quality_entries[] = { { "check_function", krb5_config_string, NULL, 0 }, { "check_library", krb5_config_string, NULL, 0 }, { "external_program", krb5_config_string, NULL, 0 }, { "min_classes", krb5_config_string, check_numeric, 0 }, { "min_length", krb5_config_string, check_numeric, 0 }, { "policies", krb5_config_string, NULL, 0 }, { "policy_libraries", krb5_config_string, NULL, 0 }, { "", krb5_config_list, all_strings, 0 }, { NULL, 0, NULL, 0 } }; struct entry toplevel_sections[] = { { "appdefaults", krb5_config_list, appdefaults_entries, 0 }, { "capaths", krb5_config_list, capaths_entries, 0 }, { "domain_realm", krb5_config_list, all_strings, 0 }, { "gssapi", krb5_config_list, NULL, 0 }, { "kadmin", krb5_config_list, kadmin_entries, 0 }, { "kcm", krb5_config_list, kcm_entries, 0 }, { "kdc", krb5_config_list, kdc_entries, 0 }, { "libdefaults" , krb5_config_list, libdefaults_entries, 0 }, { "logging", krb5_config_list, log_strings, 0 }, { "password_quality", krb5_config_list, password_quality_entries, 0 }, { "realms", krb5_config_list, realms_foobar, 0 }, /* MIT stuff */ { "kdcdefaults", krb5_config_list, kdcdefaults_entries, 0 }, { NULL, 0, NULL, 0 } }; static int check_section(krb5_context context, const char *path, krb5_config_section *cf, struct entry *entries) { int error = 0; krb5_config_section *p; struct entry *e; char *local; for(p = cf; p != NULL; p = p->next) { local = NULL; if (asprintf(&local, "%s/%s", path, p->name) < 0 || local == NULL) errx(1, "out of memory"); for(e = entries; e->name != NULL; e++) { if(*e->name == '\0' || strcmp(e->name, p->name) == 0) { if(e->type != p->type) { krb5_warnx(context, "%s: unknown or wrong type", local); error |= 1; } else if(p->type == krb5_config_string && e->check_data != NULL) { error |= (*(check_func_t)e->check_data)(context, local, p->u.string); } else if(p->type == krb5_config_list && e->check_data != NULL) { error |= check_section(context, local, p->u.list, e->check_data); } if(e->deprecated) { krb5_warnx(context, "%s: is a deprecated entry", local); error |= 1; } break; } } if(e->name == NULL) { krb5_warnx(context, "%s: unknown entry", local); error |= 1; } free(local); } return error; } static void dumpconfig(int level, krb5_config_section *top) { krb5_config_section *x; for(x = top; x; x = x->next) { switch(x->type) { case krb5_config_list: if(level == 0) { printf("[%s]\n", x->name); } else { printf("%*s%s = {\n", 4 * level, " ", x->name); } dumpconfig(level + 1, x->u.list); if(level > 0) printf("%*s}\n", 4 * level, " "); break; case krb5_config_string: printf("%*s%s = %s\n", 4 * level, " ", x->name, x->u.string); break; } } } int main(int argc, char **argv) { krb5_context context; krb5_error_code ret; krb5_config_section *tmp_cf; int optidx = 0; setprogname (argv[0]); ret = krb5_init_context(&context); if (ret == KRB5_CONFIG_BADFORMAT) errx (1, "krb5_init_context failed to parse configuration file"); else if (ret) errx (1, "krb5_init_context failed with %d", ret); if(getarg(args, sizeof(args) / sizeof(args[0]), argc, argv, &optidx)) usage(1); if (help_flag) usage (0); if(version_flag){ print_version(NULL); exit(0); } argc -= optidx; argv += optidx; tmp_cf = NULL; if(argc == 0) krb5_get_default_config_files(&argv); while(*argv) { ret = krb5_config_parse_file_multi(context, *argv, &tmp_cf); if (ret != 0) krb5_warn (context, ret, "krb5_config_parse_file"); argv++; } if(dumpconfig_flag) dumpconfig(0, tmp_cf); return check_section(context, "", tmp_cf, toplevel_sections); } heimdal-7.5.0/lib/krb5/keytab_memory.c0000644000175000017500000001413413026237312015700 0ustar niknik/* * Copyright (c) 1997 - 2001 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "krb5_locl.h" /* memory operations -------------------------------------------- */ struct mkt_data { krb5_keytab_entry *entries; int num_entries; char *name; int refcount; struct mkt_data *next; }; /* this mutex protects mkt_head, ->refcount, and ->next * content is not protected (name is static and need no protection) */ static HEIMDAL_MUTEX mkt_mutex = HEIMDAL_MUTEX_INITIALIZER; static struct mkt_data *mkt_head; static krb5_error_code KRB5_CALLCONV mkt_resolve(krb5_context context, const char *name, krb5_keytab id) { struct mkt_data *d; HEIMDAL_MUTEX_lock(&mkt_mutex); for (d = mkt_head; d != NULL; d = d->next) if (strcmp(d->name, name) == 0) break; if (d) { if (d->refcount < 1) krb5_abortx(context, "Double close on memory keytab, " "refcount < 1 %d", d->refcount); d->refcount++; id->data = d; HEIMDAL_MUTEX_unlock(&mkt_mutex); return 0; } d = calloc(1, sizeof(*d)); if(d == NULL) { HEIMDAL_MUTEX_unlock(&mkt_mutex); return krb5_enomem(context); } d->name = strdup(name); if (d->name == NULL) { HEIMDAL_MUTEX_unlock(&mkt_mutex); free(d); return krb5_enomem(context); } d->entries = NULL; d->num_entries = 0; d->refcount = 1; d->next = mkt_head; mkt_head = d; HEIMDAL_MUTEX_unlock(&mkt_mutex); id->data = d; return 0; } static krb5_error_code KRB5_CALLCONV mkt_close(krb5_context context, krb5_keytab id) { struct mkt_data *d = id->data, **dp; int i; HEIMDAL_MUTEX_lock(&mkt_mutex); if (d->refcount < 1) krb5_abortx(context, "krb5 internal error, memory keytab refcount < 1 on close"); if (--d->refcount > 0) { HEIMDAL_MUTEX_unlock(&mkt_mutex); return 0; } for (dp = &mkt_head; *dp != NULL; dp = &(*dp)->next) { if (*dp == d) { *dp = d->next; break; } } HEIMDAL_MUTEX_unlock(&mkt_mutex); free(d->name); for(i = 0; i < d->num_entries; i++) krb5_kt_free_entry(context, &d->entries[i]); free(d->entries); free(d); return 0; } static krb5_error_code KRB5_CALLCONV mkt_get_name(krb5_context context, krb5_keytab id, char *name, size_t namesize) { struct mkt_data *d = id->data; strlcpy(name, d->name, namesize); return 0; } static krb5_error_code KRB5_CALLCONV mkt_start_seq_get(krb5_context context, krb5_keytab id, krb5_kt_cursor *c) { /* XXX */ c->fd = 0; return 0; } static krb5_error_code KRB5_CALLCONV mkt_next_entry(krb5_context context, krb5_keytab id, krb5_keytab_entry *entry, krb5_kt_cursor *c) { struct mkt_data *d = id->data; if(c->fd >= d->num_entries) return KRB5_KT_END; return krb5_kt_copy_entry_contents(context, &d->entries[c->fd++], entry); } static krb5_error_code KRB5_CALLCONV mkt_end_seq_get(krb5_context context, krb5_keytab id, krb5_kt_cursor *cursor) { return 0; } static krb5_error_code KRB5_CALLCONV mkt_add_entry(krb5_context context, krb5_keytab id, krb5_keytab_entry *entry) { struct mkt_data *d = id->data; krb5_keytab_entry *tmp; tmp = realloc(d->entries, (d->num_entries + 1) * sizeof(*d->entries)); if (tmp == NULL) return krb5_enomem(context); d->entries = tmp; return krb5_kt_copy_entry_contents(context, entry, &d->entries[d->num_entries++]); } static krb5_error_code KRB5_CALLCONV mkt_remove_entry(krb5_context context, krb5_keytab id, krb5_keytab_entry *entry) { struct mkt_data *d = id->data; krb5_keytab_entry *e, *end; int found = 0; if (d->num_entries == 0) { krb5_clear_error_message(context); return KRB5_KT_NOTFOUND; } /* do this backwards to minimize copying */ for(end = d->entries + d->num_entries, e = end - 1; e >= d->entries; e--) { if(krb5_kt_compare(context, e, entry->principal, entry->vno, entry->keyblock.keytype)) { krb5_kt_free_entry(context, e); memmove(e, e + 1, (end - e - 1) * sizeof(*e)); memset(end - 1, 0, sizeof(*end)); d->num_entries--; end--; found = 1; } } if (!found) { krb5_clear_error_message (context); return KRB5_KT_NOTFOUND; } e = realloc(d->entries, d->num_entries * sizeof(*d->entries)); if(e != NULL || d->num_entries == 0) d->entries = e; return 0; } const krb5_kt_ops krb5_mkt_ops = { "MEMORY", mkt_resolve, mkt_get_name, mkt_close, NULL, /* destroy */ NULL, /* get */ mkt_start_seq_get, mkt_next_entry, mkt_end_seq_get, mkt_add_entry, mkt_remove_entry, NULL, 0 }; heimdal-7.5.0/lib/krb5/asn1_glue.c0000644000175000017500000000463513026237312014714 0ustar niknik/* * Copyright (c) 1997 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ /* * */ #include "krb5_locl.h" KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL _krb5_principal2principalname (PrincipalName *p, const krb5_principal from) { return copy_PrincipalName(&from->name, p); } KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL _krb5_principalname2krb5_principal (krb5_context context, krb5_principal *principal, const PrincipalName from, const Realm realm) { krb5_error_code ret; krb5_principal p; p = calloc(1, sizeof(*p)); if (p == NULL) return krb5_enomem(context); ret = copy_PrincipalName(&from, &p->name); if (ret) { free(p); return ret; } p->realm = strdup(realm); if (p->realm == NULL) { free_PrincipalName(&p->name); free(p); return krb5_enomem(context); } *principal = p; return 0; } heimdal-7.5.0/lib/krb5/krb5_get_in_cred.cat30000644000175000017500000002465313212450756016643 0ustar niknik KRB5_GET_IN_TKT(3) BSD Library Functions Manual KRB5_GET_IN_TKT(3) NNAAMMEE kkrrbb55__ggeett__iinn__ttkktt, kkrrbb55__ggeett__iinn__ccrreedd, kkrrbb55__ggeett__iinn__ttkktt__wwiitthh__ppaasssswwoorrdd, kkrrbb55__ggeett__iinn__ttkktt__wwiitthh__kkeeyyttaabb, kkrrbb55__ggeett__iinn__ttkktt__wwiitthh__sskkeeyy, kkrrbb55__ffrreeee__kkddcc__rreepp, kkrrbb55__ppaasssswwoorrdd__kkeeyy__pprroocc -- deprecated initial authenti- cation functions LLIIBBRRAARRYY Kerberos 5 Library (libkrb5, -lkrb5) SSYYNNOOPPSSIISS ##iinncclluuddee <> _k_r_b_5___e_r_r_o_r___c_o_d_e kkrrbb55__ggeett__iinn__ttkktt(_k_r_b_5___c_o_n_t_e_x_t _c_o_n_t_e_x_t, _k_r_b_5___f_l_a_g_s _o_p_t_i_o_n_s, _c_o_n_s_t _k_r_b_5___a_d_d_r_e_s_s_e_s _*_a_d_d_r_s, _c_o_n_s_t _k_r_b_5___e_n_c_t_y_p_e _*_e_t_y_p_e_s, _c_o_n_s_t _k_r_b_5___p_r_e_a_u_t_h_t_y_p_e _*_p_t_y_p_e_s, _k_r_b_5___k_e_y___p_r_o_c _k_e_y___p_r_o_c, _k_r_b_5___c_o_n_s_t___p_o_i_n_t_e_r _k_e_y_s_e_e_d, _k_r_b_5___d_e_c_r_y_p_t___p_r_o_c _d_e_c_r_y_p_t___p_r_o_c, _k_r_b_5___c_o_n_s_t___p_o_i_n_t_e_r _d_e_c_r_y_p_t_a_r_g, _k_r_b_5___c_r_e_d_s _*_c_r_e_d_s, _k_r_b_5___c_c_a_c_h_e _c_c_a_c_h_e, _k_r_b_5___k_d_c___r_e_p _*_r_e_t___a_s___r_e_p_l_y); _k_r_b_5___e_r_r_o_r___c_o_d_e kkrrbb55__ggeett__iinn__ccrreedd(_k_r_b_5___c_o_n_t_e_x_t _c_o_n_t_e_x_t, _k_r_b_5___f_l_a_g_s _o_p_t_i_o_n_s, _c_o_n_s_t _k_r_b_5___a_d_d_r_e_s_s_e_s _*_a_d_d_r_s, _c_o_n_s_t _k_r_b_5___e_n_c_t_y_p_e _*_e_t_y_p_e_s, _c_o_n_s_t _k_r_b_5___p_r_e_a_u_t_h_t_y_p_e _*_p_t_y_p_e_s, _c_o_n_s_t _k_r_b_5___p_r_e_a_u_t_h_d_a_t_a _*_p_r_e_a_u_t_h, _k_r_b_5___k_e_y___p_r_o_c _k_e_y___p_r_o_c, _k_r_b_5___c_o_n_s_t___p_o_i_n_t_e_r _k_e_y_s_e_e_d, _k_r_b_5___d_e_c_r_y_p_t___p_r_o_c _d_e_c_r_y_p_t___p_r_o_c, _k_r_b_5___c_o_n_s_t___p_o_i_n_t_e_r _d_e_c_r_y_p_t_a_r_g, _k_r_b_5___c_r_e_d_s _*_c_r_e_d_s, _k_r_b_5___k_d_c___r_e_p _*_r_e_t___a_s___r_e_p_l_y); _k_r_b_5___e_r_r_o_r___c_o_d_e kkrrbb55__ggeett__iinn__ttkktt__wwiitthh__ppaasssswwoorrdd(_k_r_b_5___c_o_n_t_e_x_t _c_o_n_t_e_x_t, _k_r_b_5___f_l_a_g_s _o_p_t_i_o_n_s, _k_r_b_5___a_d_d_r_e_s_s_e_s _*_a_d_d_r_s, _c_o_n_s_t _k_r_b_5___e_n_c_t_y_p_e _*_e_t_y_p_e_s, _c_o_n_s_t _k_r_b_5___p_r_e_a_u_t_h_t_y_p_e _*_p_r_e___a_u_t_h___t_y_p_e_s, _c_o_n_s_t _c_h_a_r _*_p_a_s_s_w_o_r_d, _k_r_b_5___c_c_a_c_h_e _c_c_a_c_h_e, _k_r_b_5___c_r_e_d_s _*_c_r_e_d_s, _k_r_b_5___k_d_c___r_e_p _*_r_e_t___a_s___r_e_p_l_y); _k_r_b_5___e_r_r_o_r___c_o_d_e kkrrbb55__ggeett__iinn__ttkktt__wwiitthh__kkeeyyttaabb(_k_r_b_5___c_o_n_t_e_x_t _c_o_n_t_e_x_t, _k_r_b_5___f_l_a_g_s _o_p_t_i_o_n_s, _k_r_b_5___a_d_d_r_e_s_s_e_s _*_a_d_d_r_s, _c_o_n_s_t _k_r_b_5___e_n_c_t_y_p_e _*_e_t_y_p_e_s, _c_o_n_s_t _k_r_b_5___p_r_e_a_u_t_h_t_y_p_e _*_p_r_e___a_u_t_h___t_y_p_e_s, _k_r_b_5___k_e_y_t_a_b _k_e_y_t_a_b, _k_r_b_5___c_c_a_c_h_e _c_c_a_c_h_e, _k_r_b_5___c_r_e_d_s _*_c_r_e_d_s, _k_r_b_5___k_d_c___r_e_p _*_r_e_t___a_s___r_e_p_l_y); _k_r_b_5___e_r_r_o_r___c_o_d_e kkrrbb55__ggeett__iinn__ttkktt__wwiitthh__sskkeeyy(_k_r_b_5___c_o_n_t_e_x_t _c_o_n_t_e_x_t, _k_r_b_5___f_l_a_g_s _o_p_t_i_o_n_s, _k_r_b_5___a_d_d_r_e_s_s_e_s _*_a_d_d_r_s, _c_o_n_s_t _k_r_b_5___e_n_c_t_y_p_e _*_e_t_y_p_e_s, _c_o_n_s_t _k_r_b_5___p_r_e_a_u_t_h_t_y_p_e _*_p_r_e___a_u_t_h___t_y_p_e_s, _c_o_n_s_t _k_r_b_5___k_e_y_b_l_o_c_k _*_k_e_y, _k_r_b_5___c_c_a_c_h_e _c_c_a_c_h_e, _k_r_b_5___c_r_e_d_s _*_c_r_e_d_s, _k_r_b_5___k_d_c___r_e_p _*_r_e_t___a_s___r_e_p_l_y); _k_r_b_5___e_r_r_o_r___c_o_d_e kkrrbb55__ffrreeee__kkddcc__rreepp(_k_r_b_5___c_o_n_t_e_x_t _c_o_n_t_e_x_t, _k_r_b_5___k_d_c___r_e_p _*_r_e_p); _k_r_b_5___e_r_r_o_r___c_o_d_e kkrrbb55__ppaasssswwoorrdd__kkeeyy__pprroocc(_k_r_b_5___c_o_n_t_e_x_t _c_o_n_t_e_x_t, _k_r_b_5___e_n_c_t_y_p_e _t_y_p_e, _k_r_b_5___s_a_l_t _s_a_l_t, _k_r_b_5___c_o_n_s_t___p_o_i_n_t_e_r _k_e_y_s_e_e_d, _k_r_b_5___k_e_y_b_l_o_c_k _*_*_k_e_y); DDEESSCCRRIIPPTTIIOONN _A_l_l _t_h_e _f_u_n_c_t_i_o_n_s _i_n _t_h_i_s _m_a_n_u_a_l _p_a_g_e _a_r_e _d_e_p_r_e_c_a_t_e_d _i_n _t_h_e _M_I_T _i_m_p_l_e_m_e_n_- _t_a_t_i_o_n_, _a_n_d _w_i_l_l _s_o_o_n _b_e _d_e_p_r_e_c_a_t_e_d _i_n _H_e_i_m_d_a_l _t_o_o_, _d_o_n_'_t _u_s_e _t_h_e_m_. Getting initial credential ticket for a principal. kkrrbb55__ggeett__iinn__ccrreedd is the function all other krb5_get_in function uses to fetch tickets. The other krb5_get_in function are more specialized and therefor somewhat easier to use. If your need is only to verify a user and password, consider using krb5_verify_user(3) instead, it have a much simpler interface. kkrrbb55__ggeett__iinn__ttkktt and kkrrbb55__ggeett__iinn__ccrreedd fetches initial credential, queries after key using the _k_e_y___p_r_o_c argument. The differences between the two function is that kkrrbb55__ggeett__iinn__ttkktt stores the credential in a krb5_creds while kkrrbb55__ggeett__iinn__ccrreedd stores the credential in a krb5_ccache. kkrrbb55__ggeett__iinn__ttkktt__wwiitthh__ppaasssswwoorrdd, kkrrbb55__ggeett__iinn__ttkktt__wwiitthh__kkeeyyttaabb, and kkrrbb55__ggeett__iinn__ttkktt__wwiitthh__sskkeeyy does the same work as kkrrbb55__ggeett__iinn__ccrreedd but are more specialized. kkrrbb55__ggeett__iinn__ttkktt__wwiitthh__ppaasssswwoorrdd uses the clients password to authenticate. If the password argument is NULL the user user queried with the default password query function. kkrrbb55__ggeett__iinn__ttkktt__wwiitthh__kkeeyyttaabb searches the given keytab for a service entry for the client principal. If the keytab is NULL the default keytab is used. kkrrbb55__ggeett__iinn__ttkktt__wwiitthh__sskkeeyy uses a key to get the initial credential. There are some common arguments to the krb5_get_in functions, these are: _o_p_t_i_o_n_s are the KDC_OPT flags. _e_t_y_p_e_s is a NULL terminated array of encryption types that the client approves. _a_d_d_r_s a list of the addresses that the initial ticket. If it is NULL the list will be generated by the library. _p_r_e___a_u_t_h___t_y_p_e_s a NULL terminated array of pre-authentication types. If _p_r_e___a_u_t_h___t_y_p_e_s is NULL the function will try without pre-authentication and return those pre-authentication that the KDC returned. _r_e_t___a_s___r_e_p_l_y will (if not NULL) be filled in with the response of the KDC and should be free with kkrrbb55__ffrreeee__kkddcc__rreepp(). _k_e_y___p_r_o_c is a pointer to a function that should return a key salted appropriately. Using NULL will use the default password query function. _d_e_c_r_y_p_t___p_r_o_c Using NULL will use the default decryption function. _d_e_c_r_y_p_t_a_r_g will be passed to the decryption function _d_e_c_r_y_p_t___p_r_o_c. _c_r_e_d_s creds should be filled in with the template for a credential that should be requested. The client and server elements of the creds struc- ture must be filled in. Upon return of the function it will be contain the content of the requested credential (_k_r_b_5___g_e_t___i_n___c_r_e_d), or it will be freed with krb5_free_creds(3) (all the other krb5_get_in functions). _c_c_a_c_h_e will store the credential in the credential cache _c_c_a_c_h_e. The credential cache will not be initialized, thats up the the caller. kkrrbb55__ppaasssswwoorrdd__kkeeyy__pprroocc is a library function that is suitable using as the _k_r_b_5___k_e_y___p_r_o_c argument to kkrrbb55__ggeett__iinn__ccrreedd or kkrrbb55__ggeett__iinn__ttkktt. _k_e_y_s_e_e_d should be a pointer to a NUL terminated string or NULL. kkrrbb55__ppaasssswwoorrdd__kkeeyy__pprroocc will query the user for the pass on the console if the password isn't given as the argument _k_e_y_s_e_e_d. kkrrbb55__ffrreeee__kkddcc__rreepp() frees the content of _r_e_p. SSEEEE AALLSSOO krb5(3), krb5_verify_user(3), krb5.conf(5), kerberos(8) HEIMDAL May 31, 2003 HEIMDAL heimdal-7.5.0/lib/krb5/test_x500.c0000644000175000017500000000643013026237312014564 0ustar niknik/* * Copyright (c) 2011 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of KTH nor the names of its contributors may be * used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY KTH AND ITS CONTRIBUTORS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL KTH OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "krb5_locl.h" #include /* * */ static void check_linear(krb5_context context, const char *client_realm, const char *server_realm, const char *realm, ...) { unsigned int num_inrealms = 0, num_realms = 0, n; char **inrealms = NULL; char **realms = NULL; krb5_error_code ret; krb5_data tr; va_list va; krb5_data_zero(&tr); va_start(va, realm); while (realm) { inrealms = erealloc(inrealms, (num_inrealms + 2) * sizeof(inrealms[0])); inrealms[num_inrealms] = rk_UNCONST(realm); num_inrealms++; realm = va_arg(va, const char *); } if (inrealms) inrealms[num_inrealms] = NULL; ret = krb5_domain_x500_encode(inrealms, num_inrealms, &tr); if (ret) krb5_err(context, 1, ret, "krb5_domain_x500_encode"); ret = krb5_domain_x500_decode(context, tr, &realms, &num_realms, client_realm, server_realm); if (ret) krb5_err(context, 1, ret, "krb5_domain_x500_decode"); krb5_data_free(&tr); if (num_inrealms != num_realms) errx(1, "num_inrealms != num_realms"); for(n = 0; n < num_realms; n++) free(realms[n]); free(realms); free(inrealms); } int main(int argc, char **argv) { krb5_context context; krb5_error_code ret; setprogname(argv[0]); ret = krb5_init_context(&context); if (ret) errx(1, "krb5_init_context"); check_linear(context, "KTH1.SE", "KTH1.SE", NULL); check_linear(context, "KTH1.SE", "KTH2.SE", NULL); check_linear(context, "KTH1.SE", "KTH3.SE", "KTH2.SE", NULL); check_linear(context, "KTH1.SE", "KTH4.SE", "KTH3.SE", "KTH2.SE", NULL); check_linear(context, "KTH1.SE", "KTH5.SE", "KTH4.SE", "KTH3.SE", "KTH2.SE", NULL); return 0; } heimdal-7.5.0/lib/krb5/rd_priv.c0000644000175000017500000001260513026237312014477 0ustar niknik/* * Copyright (c) 1997-2007 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "krb5_locl.h" KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_rd_priv(krb5_context context, krb5_auth_context auth_context, const krb5_data *inbuf, krb5_data *outbuf, krb5_replay_data *outdata) { krb5_error_code ret; KRB_PRIV priv; EncKrbPrivPart part; size_t len; krb5_data plain; krb5_keyblock *key; krb5_crypto crypto; krb5_data_zero(outbuf); if ((auth_context->flags & (KRB5_AUTH_CONTEXT_RET_TIME | KRB5_AUTH_CONTEXT_RET_SEQUENCE))) { if (outdata == NULL) { krb5_clear_error_message (context); return KRB5_RC_REQUIRED; /* XXX better error, MIT returns this */ } /* if these fields are not present in the priv-part, silently return zero */ memset(outdata, 0, sizeof(*outdata)); } memset(&priv, 0, sizeof(priv)); ret = decode_KRB_PRIV (inbuf->data, inbuf->length, &priv, &len); if (ret) { krb5_clear_error_message (context); goto failure; } if (priv.pvno != 5) { krb5_clear_error_message (context); ret = KRB5KRB_AP_ERR_BADVERSION; goto failure; } if (priv.msg_type != krb_priv) { krb5_clear_error_message (context); ret = KRB5KRB_AP_ERR_MSG_TYPE; goto failure; } if (auth_context->remote_subkey) key = auth_context->remote_subkey; else if (auth_context->local_subkey) key = auth_context->local_subkey; else key = auth_context->keyblock; ret = krb5_crypto_init(context, key, 0, &crypto); if (ret) goto failure; ret = krb5_decrypt_EncryptedData(context, crypto, KRB5_KU_KRB_PRIV, &priv.enc_part, &plain); krb5_crypto_destroy(context, crypto); if (ret) goto failure; ret = decode_EncKrbPrivPart (plain.data, plain.length, &part, &len); krb5_data_free (&plain); if (ret) { krb5_clear_error_message (context); goto failure; } /* check sender address */ if (part.s_address && auth_context->remote_address && !krb5_address_compare (context, auth_context->remote_address, part.s_address)) { krb5_clear_error_message (context); ret = KRB5KRB_AP_ERR_BADADDR; goto failure_part; } /* check receiver address */ if (part.r_address && auth_context->local_address && !krb5_address_compare (context, auth_context->local_address, part.r_address)) { krb5_clear_error_message (context); ret = KRB5KRB_AP_ERR_BADADDR; goto failure_part; } /* check timestamp */ if (auth_context->flags & KRB5_AUTH_CONTEXT_DO_TIME) { krb5_timestamp sec; krb5_timeofday (context, &sec); if (part.timestamp == NULL || part.usec == NULL || labs(*part.timestamp - sec) > context->max_skew) { krb5_clear_error_message (context); ret = KRB5KRB_AP_ERR_SKEW; goto failure_part; } } /* XXX - check replay cache */ /* check sequence number. since MIT krb5 cannot generate a sequence number of zero but instead generates no sequence number, we accept that */ if (auth_context->flags & KRB5_AUTH_CONTEXT_DO_SEQUENCE) { if ((part.seq_number == NULL && auth_context->remote_seqnumber != 0) || (part.seq_number != NULL && *part.seq_number != auth_context->remote_seqnumber)) { krb5_clear_error_message (context); ret = KRB5KRB_AP_ERR_BADORDER; goto failure_part; } auth_context->remote_seqnumber++; } ret = krb5_data_copy (outbuf, part.user_data.data, part.user_data.length); if (ret) goto failure_part; if ((auth_context->flags & (KRB5_AUTH_CONTEXT_RET_TIME | KRB5_AUTH_CONTEXT_RET_SEQUENCE))) { if(part.timestamp) outdata->timestamp = *part.timestamp; if(part.usec) outdata->usec = *part.usec; if(part.seq_number) outdata->seq = *part.seq_number; } failure_part: free_EncKrbPrivPart (&part); failure: free_KRB_PRIV (&priv); return ret; } heimdal-7.5.0/lib/krb5/krb5_getportbyname.cat30000644000175000017500000000226013212450756017247 0ustar niknik NAME(3) BSD Library Functions Manual NAME(3) NNAAMMEE kkrrbb55__ggeettppoorrttbbyynnaammee -- get port number by name LLIIBBRRAARRYY Kerberos 5 Library (libkrb5, -lkrb5) SSYYNNOOPPSSIISS ##iinncclluuddee <> _i_n_t kkrrbb55__ggeettppoorrttbbyynnaammee(_k_r_b_5___c_o_n_t_e_x_t _c_o_n_t_e_x_t, _c_o_n_s_t _c_h_a_r _*_s_e_r_v_i_c_e, _c_o_n_s_t _c_h_a_r _*_p_r_o_t_o, _i_n_t _d_e_f_a_u_l_t___p_o_r_t); DDEESSCCRRIIPPTTIIOONN kkrrbb55__ggeettppoorrttbbyynnaammee() gets the port number for _s_e_r_v_i_c_e _/ _p_r_o_t_o pair from the global service table for and returns it in network order. If it isn't found in the global table, the _d_e_f_a_u_l_t___p_o_r_t (given in host order) is returned. EEXXAAMMPPLLEE int port = krb5_getportbyname(context, "kerberos", "tcp", 88); SSEEEE AALLSSOO krb5(3) HEIMDAL August 15, 2004 HEIMDAL heimdal-7.5.0/lib/krb5/krb5_parse_name.cat30000644000175000017500000000270513212450757016506 0ustar niknik KRB5_PARSE_NAME(3) BSD Library Functions Manual KRB5_PARSE_NAME(3) NNAAMMEE kkrrbb55__ppaarrssee__nnaammee -- string to principal conversion LLIIBBRRAARRYY Kerberos 5 Library (libkrb5, -lkrb5) SSYYNNOOPPSSIISS ##iinncclluuddee <> _k_r_b_5___e_r_r_o_r___c_o_d_e kkrrbb55__ppaarrssee__nnaammee(_k_r_b_5___c_o_n_t_e_x_t _c_o_n_t_e_x_t, _c_o_n_s_t _c_h_a_r _*_n_a_m_e, _k_r_b_5___p_r_i_n_c_i_p_a_l _*_p_r_i_n_c_i_p_a_l); DDEESSCCRRIIPPTTIIOONN kkrrbb55__ppaarrssee__nnaammee() converts a string representation of a principal name to kkrrbb55__pprriinncciippaall. The _p_r_i_n_c_i_p_a_l will point to allocated data that should be freed with kkrrbb55__ffrreeee__pprriinncciippaall(). The string should consist of one or more name components separated with slashes (``/''), optionally followed with an ``@'' and a realm name. A slash or @ may be contained in a name component by quoting it with a backslash (``\''). A realm should not contain slashes or colons. SSEEEE AALLSSOO krb5_build_principal(3), krb5_free_principal(3), krb5_sname_to_principal(3), krb5_unparse_name(3) HEIMDAL May 1, 2006 HEIMDAL heimdal-7.5.0/lib/krb5/n-fold-test.c0000644000175000017500000001022013026237312015155 0ustar niknik/* * Copyright (c) 1999 - 2001 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of KTH nor the names of its contributors may be * used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY KTH AND ITS CONTRIBUTORS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL KTH OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "krb5_locl.h" enum { MAXSIZE = 24 }; static struct testcase { const char *str; unsigned n; unsigned char res[MAXSIZE]; } tests[] = { {"012345", 8, {0xbe, 0x07, 0x26, 0x31, 0x27, 0x6b, 0x19, 0x55} }, {"basch", 24, {0x1a, 0xab, 0x6b, 0x42, 0x96, 0x4b, 0x98, 0xb2, 0x1f, 0x8c, 0xde, 0x2d, 0x24, 0x48, 0xba, 0x34, 0x55, 0xd7, 0x86, 0x2c, 0x97, 0x31, 0x64, 0x3f} }, {"eichin", 24, {0x65, 0x69, 0x63, 0x68, 0x69, 0x6e, 0x4b, 0x73, 0x2b, 0x4b, 0x1b, 0x43, 0xda, 0x1a, 0x5b, 0x99, 0x5a, 0x58, 0xd2, 0xc6, 0xd0, 0xd2, 0xdc, 0xca} }, {"sommerfeld", 24, {0x2f, 0x7a, 0x98, 0x55, 0x7c, 0x6e, 0xe4, 0xab, 0xad, 0xf4, 0xe7, 0x11, 0x92, 0xdd, 0x44, 0x2b, 0xd4, 0xff, 0x53, 0x25, 0xa5, 0xde, 0xf7, 0x5c} }, {"MASSACHVSETTS INSTITVTE OF TECHNOLOGY", 24, {0xdb, 0x3b, 0x0d, 0x8f, 0x0b, 0x06, 0x1e, 0x60, 0x32, 0x82, 0xb3, 0x08, 0xa5, 0x08, 0x41, 0x22, 0x9a, 0xd7, 0x98, 0xfa, 0xb9, 0x54, 0x0c, 0x1b} }, {"assar@NADA.KTH.SE", 24, {0x5c, 0x06, 0xc3, 0x4d, 0x2c, 0x89, 0x05, 0xbe, 0x7a, 0x51, 0x83, 0x6c, 0xd6, 0xf8, 0x1c, 0x4b, 0x7a, 0x93, 0x49, 0x16, 0x5a, 0xb3, 0xfa, 0xa9} }, {"testKRBTEST.MIT.EDUtestkey", 24, {0x50, 0x2c, 0xf8, 0x29, 0x78, 0xe5, 0xfb, 0x1a, 0x29, 0x06, 0xbd, 0x22, 0x28, 0x91, 0x56, 0xc0, 0x06, 0xa0, 0xdc, 0xf5, 0xb6, 0xc2, 0xda, 0x6c} }, {"password", 7, {0x78, 0xa0, 0x7b, 0x6c, 0xaf, 0x85, 0xfa} }, {"Rough Consensus, and Running Code", 8, {0xbb, 0x6e, 0xd3, 0x08, 0x70, 0xb7, 0xf0, 0xe0}, }, {"password", 21, {0x59, 0xe4, 0xa8, 0xca, 0x7c, 0x03, 0x85, 0xc3, 0xc3, 0x7b, 0x3f, 0x6d, 0x20, 0x00, 0x24, 0x7c, 0xb6, 0xe6, 0xbd, 0x5b, 0x3e}, }, {"MASSACHVSETTS INSTITVTE OF TECHNOLOGY", 24, {0xdb, 0x3b, 0x0d, 0x8f, 0x0b, 0x06, 0x1e, 0x60, 0x32, 0x82, 0xb3, 0x08, 0xa5, 0x08, 0x41, 0x22, 0x9a, 0xd7, 0x98, 0xfa, 0xb9, 0x54, 0x0c, 0x1b} }, {NULL, 0, {0}} }; int main(int argc, char **argv) { unsigned char data[MAXSIZE]; struct testcase *t; int ret = 0; for (t = tests; t->str; ++t) { int i; ret = _krb5_n_fold (t->str, strlen(t->str), data, t->n); if (ret) errx(1, "out of memory"); if (memcmp (data, t->res, t->n) != 0) { printf ("n-fold(\"%s\", %d) failed\n", t->str, t->n); printf ("should be: "); for (i = 0; i < t->n; ++i) printf ("%02x", t->res[i]); printf ("\nresult was: "); for (i = 0; i < t->n; ++i) printf ("%02x", data[i]); printf ("\n"); ret = 1; } } return ret; } heimdal-7.5.0/lib/krb5/get_cred.c0000644000175000017500000013133313212137553014611 0ustar niknik/* * Copyright (c) 1997 - 2008 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Portions Copyright (c) 2009 Apple Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "krb5_locl.h" #include static krb5_error_code get_cred_kdc_capath(krb5_context, krb5_kdc_flags, krb5_ccache, krb5_creds *, krb5_principal, Ticket *, krb5_creds **, krb5_creds ***); /* * Take the `body' and encode it into `padata' using the credentials * in `creds'. */ static krb5_error_code make_pa_tgs_req(krb5_context context, krb5_auth_context ac, KDC_REQ_BODY *body, PA_DATA *padata, krb5_creds *creds) { u_char *buf; size_t buf_size; size_t len = 0; krb5_data in_data; krb5_error_code ret; ASN1_MALLOC_ENCODE(KDC_REQ_BODY, buf, buf_size, body, &len, ret); if (ret) goto out; if(buf_size != len) krb5_abortx(context, "internal error in ASN.1 encoder"); in_data.length = len; in_data.data = buf; ret = _krb5_mk_req_internal(context, &ac, 0, &in_data, creds, &padata->padata_value, KRB5_KU_TGS_REQ_AUTH_CKSUM, KRB5_KU_TGS_REQ_AUTH); out: free (buf); if(ret) return ret; padata->padata_type = KRB5_PADATA_TGS_REQ; return 0; } /* * Set the `enc-authorization-data' in `req_body' based on `authdata' */ static krb5_error_code set_auth_data (krb5_context context, KDC_REQ_BODY *req_body, krb5_authdata *authdata, krb5_keyblock *subkey) { if(authdata->len) { size_t len = 0, buf_size; unsigned char *buf; krb5_crypto crypto; krb5_error_code ret; ASN1_MALLOC_ENCODE(AuthorizationData, buf, buf_size, authdata, &len, ret); if (ret) return ret; if (buf_size != len) krb5_abortx(context, "internal error in ASN.1 encoder"); ALLOC(req_body->enc_authorization_data, 1); if (req_body->enc_authorization_data == NULL) { free (buf); return krb5_enomem(context); } ret = krb5_crypto_init(context, subkey, 0, &crypto); if (ret) { free (buf); free (req_body->enc_authorization_data); req_body->enc_authorization_data = NULL; return ret; } krb5_encrypt_EncryptedData(context, crypto, KRB5_KU_TGS_REQ_AUTH_DAT_SUBKEY, buf, len, 0, req_body->enc_authorization_data); free (buf); krb5_crypto_destroy(context, crypto); } else { req_body->enc_authorization_data = NULL; } return 0; } /* * Create a tgs-req in `t' with `addresses', `flags', `second_ticket' * (if not-NULL), `in_creds', `krbtgt', and returning the generated * subkey in `subkey'. */ static krb5_error_code init_tgs_req (krb5_context context, krb5_ccache ccache, krb5_addresses *addresses, krb5_kdc_flags flags, Ticket *second_ticket, krb5_creds *in_creds, krb5_creds *krbtgt, unsigned nonce, const METHOD_DATA *padata, krb5_keyblock **subkey, TGS_REQ *t) { krb5_auth_context ac = NULL; krb5_error_code ret = 0; memset(t, 0, sizeof(*t)); t->pvno = 5; t->msg_type = krb_tgs_req; if (in_creds->session.keytype) { ALLOC_SEQ(&t->req_body.etype, 1); if(t->req_body.etype.val == NULL) { ret = krb5_enomem(context); goto fail; } t->req_body.etype.val[0] = in_creds->session.keytype; } else { ret = _krb5_init_etype(context, KRB5_PDU_TGS_REQUEST, &t->req_body.etype.len, &t->req_body.etype.val, NULL); } if (ret) goto fail; t->req_body.addresses = addresses; t->req_body.kdc_options = flags.b; t->req_body.kdc_options.forwardable = krbtgt->flags.b.forwardable; t->req_body.kdc_options.renewable = krbtgt->flags.b.renewable; t->req_body.kdc_options.proxiable = krbtgt->flags.b.proxiable; ret = copy_Realm(&in_creds->server->realm, &t->req_body.realm); if (ret) goto fail; ALLOC(t->req_body.sname, 1); if (t->req_body.sname == NULL) { ret = krb5_enomem(context); goto fail; } /* some versions of some code might require that the client be present in TGS-REQs, but this is clearly against the spec */ ret = copy_PrincipalName(&in_creds->server->name, t->req_body.sname); if (ret) goto fail; if (krbtgt->times.starttime) { ALLOC(t->req_body.from, 1); if(t->req_body.from == NULL){ ret = krb5_enomem(context); goto fail; } *t->req_body.from = in_creds->times.starttime; } /* req_body.till should be NULL if there is no endtime specified, but old MIT code (like DCE secd) doesn't like that */ ALLOC(t->req_body.till, 1); if(t->req_body.till == NULL){ ret = krb5_enomem(context); goto fail; } *t->req_body.till = in_creds->times.endtime; if (t->req_body.kdc_options.renewable && krbtgt->times.renew_till) { ALLOC(t->req_body.rtime, 1); if(t->req_body.rtime == NULL){ ret = krb5_enomem(context); goto fail; } *t->req_body.rtime = in_creds->times.renew_till; } t->req_body.nonce = nonce; if(second_ticket){ ALLOC(t->req_body.additional_tickets, 1); if (t->req_body.additional_tickets == NULL) { ret = krb5_enomem(context); goto fail; } ALLOC_SEQ(t->req_body.additional_tickets, 1); if (t->req_body.additional_tickets->val == NULL) { ret = krb5_enomem(context); goto fail; } ret = copy_Ticket(second_ticket, t->req_body.additional_tickets->val); if (ret) goto fail; } ALLOC(t->padata, 1); if (t->padata == NULL) { ret = krb5_enomem(context); goto fail; } ALLOC_SEQ(t->padata, 1 + padata->len); if (t->padata->val == NULL) { ret = krb5_enomem(context); goto fail; } { size_t i; for (i = 0; i < padata->len; i++) { ret = copy_PA_DATA(&padata->val[i], &t->padata->val[i + 1]); if (ret) { krb5_set_error_message(context, ret, N_("malloc: out of memory", "")); goto fail; } } } ret = krb5_auth_con_init(context, &ac); if(ret) goto fail; ret = krb5_auth_con_generatelocalsubkey(context, ac, &krbtgt->session); if (ret) goto fail; ret = set_auth_data (context, &t->req_body, &in_creds->authdata, ac->local_subkey); if (ret) goto fail; ret = make_pa_tgs_req(context, ac, &t->req_body, &t->padata->val[0], krbtgt); if(ret) goto fail; ret = krb5_auth_con_getlocalsubkey(context, ac, subkey); if (ret) goto fail; fail: if (ac) krb5_auth_con_free(context, ac); if (ret) { t->req_body.addresses = NULL; free_TGS_REQ (t); } return ret; } KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL _krb5_get_krbtgt(krb5_context context, krb5_ccache id, krb5_realm realm, krb5_creds **cred) { krb5_error_code ret; krb5_creds tmp_cred; memset(&tmp_cred, 0, sizeof(tmp_cred)); ret = krb5_cc_get_principal(context, id, &tmp_cred.client); if (ret) return ret; ret = krb5_make_principal(context, &tmp_cred.server, realm, KRB5_TGS_NAME, realm, NULL); if(ret) { krb5_free_principal(context, tmp_cred.client); return ret; } /* * The forwardable TGT might not be the start TGT, in which case, it is * generally, but not always already cached. Just in case, get it again if * lost. */ ret = krb5_get_credentials(context, 0, id, &tmp_cred, cred); krb5_free_principal(context, tmp_cred.client); krb5_free_principal(context, tmp_cred.server); if(ret) return ret; return 0; } /* DCE compatible decrypt proc */ static krb5_error_code KRB5_CALLCONV decrypt_tkt_with_subkey (krb5_context context, krb5_keyblock *key, krb5_key_usage usage, krb5_const_pointer skey, krb5_kdc_rep *dec_rep) { const krb5_keyblock *subkey = skey; krb5_error_code ret = 0; krb5_data data; size_t size; krb5_crypto crypto; assert(usage == 0); krb5_data_zero(&data); /* * start out with trying with subkey if we have one */ if (subkey) { ret = krb5_crypto_init(context, subkey, 0, &crypto); if (ret) return ret; ret = krb5_decrypt_EncryptedData (context, crypto, KRB5_KU_TGS_REP_ENC_PART_SUB_KEY, &dec_rep->kdc_rep.enc_part, &data); /* * If the is Windows 2000 DC, we need to retry with key usage * 8 when doing ARCFOUR. */ if (ret && subkey->keytype == ETYPE_ARCFOUR_HMAC_MD5) { ret = krb5_decrypt_EncryptedData(context, crypto, 8, &dec_rep->kdc_rep.enc_part, &data); } krb5_crypto_destroy(context, crypto); } if (subkey == NULL || ret) { ret = krb5_crypto_init(context, key, 0, &crypto); if (ret) return ret; ret = krb5_decrypt_EncryptedData (context, crypto, KRB5_KU_TGS_REP_ENC_PART_SESSION, &dec_rep->kdc_rep.enc_part, &data); krb5_crypto_destroy(context, crypto); } if (ret) return ret; ret = decode_EncASRepPart(data.data, data.length, &dec_rep->enc_part, &size); if (ret) ret = decode_EncTGSRepPart(data.data, data.length, &dec_rep->enc_part, &size); if (ret) krb5_set_error_message(context, ret, N_("Failed to decode encpart in ticket", "")); krb5_data_free (&data); return ret; } static krb5_error_code get_cred_kdc(krb5_context context, krb5_ccache id, krb5_kdc_flags flags, krb5_addresses *addresses, krb5_creds *in_creds, krb5_creds *krbtgt, krb5_principal impersonate_principal, Ticket *second_ticket, krb5_creds *out_creds) { TGS_REQ req; krb5_data enc; krb5_data resp; krb5_kdc_rep rep; KRB_ERROR error; krb5_error_code ret; unsigned nonce; krb5_keyblock *subkey = NULL; size_t len = 0; Ticket second_ticket_data; METHOD_DATA padata; krb5_data_zero(&resp); krb5_data_zero(&enc); padata.val = NULL; padata.len = 0; krb5_generate_random_block(&nonce, sizeof(nonce)); nonce &= 0xffffffff; if(flags.b.enc_tkt_in_skey && second_ticket == NULL){ ret = decode_Ticket(in_creds->second_ticket.data, in_creds->second_ticket.length, &second_ticket_data, &len); if(ret) return ret; second_ticket = &second_ticket_data; } if (impersonate_principal) { krb5_crypto crypto; PA_S4U2Self self; krb5_data data; void *buf; size_t size = 0; self.name = impersonate_principal->name; self.realm = impersonate_principal->realm; self.auth = estrdup("Kerberos"); ret = _krb5_s4u2self_to_checksumdata(context, &self, &data); if (ret) { free(self.auth); goto out; } ret = krb5_crypto_init(context, &krbtgt->session, 0, &crypto); if (ret) { free(self.auth); krb5_data_free(&data); goto out; } ret = krb5_create_checksum(context, crypto, KRB5_KU_OTHER_CKSUM, 0, data.data, data.length, &self.cksum); krb5_crypto_destroy(context, crypto); krb5_data_free(&data); if (ret) { free(self.auth); goto out; } ASN1_MALLOC_ENCODE(PA_S4U2Self, buf, len, &self, &size, ret); free(self.auth); free_Checksum(&self.cksum); if (ret) goto out; if (len != size) krb5_abortx(context, "internal asn1 error"); ret = krb5_padata_add(context, &padata, KRB5_PADATA_FOR_USER, buf, len); if (ret) goto out; } ret = init_tgs_req (context, id, addresses, flags, second_ticket, in_creds, krbtgt, nonce, &padata, &subkey, &req); if (ret) goto out; ASN1_MALLOC_ENCODE(TGS_REQ, enc.data, enc.length, &req, &len, ret); if (ret) goto out; if(enc.length != len) krb5_abortx(context, "internal error in ASN.1 encoder"); /* don't free addresses */ req.req_body.addresses = NULL; free_TGS_REQ(&req); /* * Send and receive */ { krb5_sendto_ctx stctx; ret = krb5_sendto_ctx_alloc(context, &stctx); if (ret) return ret; krb5_sendto_ctx_set_func(stctx, _krb5_kdc_retry, NULL); ret = krb5_sendto_context (context, stctx, &enc, krbtgt->server->name.name_string.val[1], &resp); krb5_sendto_ctx_free(context, stctx); } if(ret) goto out; memset(&rep, 0, sizeof(rep)); if(decode_TGS_REP(resp.data, resp.length, &rep.kdc_rep, &len) == 0) { unsigned eflags = 0; ret = krb5_copy_principal(context, in_creds->client, &out_creds->client); if(ret) goto out2; ret = krb5_copy_principal(context, in_creds->server, &out_creds->server); if(ret) goto out2; /* this should go someplace else */ out_creds->times.endtime = in_creds->times.endtime; /* XXX should do better testing */ if (flags.b.constrained_delegation || impersonate_principal) eflags |= EXTRACT_TICKET_ALLOW_CNAME_MISMATCH; ret = _krb5_extract_ticket(context, &rep, out_creds, &krbtgt->session, NULL, 0, &krbtgt->addresses, nonce, eflags, NULL, decrypt_tkt_with_subkey, subkey); out2: krb5_free_kdc_rep(context, &rep); } else if(krb5_rd_error(context, &resp, &error) == 0) { ret = krb5_error_from_rd_error(context, &error, in_creds); krb5_free_error_contents(context, &error); } else if(resp.length > 0 && ((char*)resp.data)[0] == 4) { ret = KRB5KRB_AP_ERR_V4_REPLY; krb5_clear_error_message(context); } else { ret = KRB5KRB_AP_ERR_MSG_TYPE; krb5_clear_error_message(context); } out: if (second_ticket == &second_ticket_data) free_Ticket(&second_ticket_data); free_METHOD_DATA(&padata); krb5_data_free(&resp); krb5_data_free(&enc); if(subkey) krb5_free_keyblock(context, subkey); return ret; } /* * same as above, just get local addresses first if the krbtgt have * them and the realm is not addressless */ static krb5_error_code get_cred_kdc_address(krb5_context context, krb5_ccache id, krb5_kdc_flags flags, krb5_addresses *addrs, krb5_creds *in_creds, krb5_creds *krbtgt, krb5_principal impersonate_principal, Ticket *second_ticket, krb5_creds *out_creds) { krb5_error_code ret; krb5_addresses addresses = { 0, NULL }; /* * Inherit the address-ness of the krbtgt if the address is not * specified. */ if (addrs == NULL && krbtgt->addresses.len != 0) { krb5_boolean noaddr; krb5_appdefault_boolean(context, NULL, krbtgt->server->realm, "no-addresses", FALSE, &noaddr); if (!noaddr) { krb5_get_all_client_addrs(context, &addresses); /* XXX this sucks. */ addrs = &addresses; if(addresses.len == 0) addrs = NULL; } } ret = get_cred_kdc(context, id, flags, addrs, in_creds, krbtgt, impersonate_principal, second_ticket, out_creds); krb5_free_addresses(context, &addresses); return ret; } KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_get_kdc_cred(krb5_context context, krb5_ccache id, krb5_kdc_flags flags, krb5_addresses *addresses, Ticket *second_ticket, krb5_creds *in_creds, krb5_creds **out_creds ) { krb5_error_code ret; krb5_creds *krbtgt; *out_creds = calloc(1, sizeof(**out_creds)); if(*out_creds == NULL) return krb5_enomem(context); ret = _krb5_get_krbtgt (context, id, in_creds->server->realm, &krbtgt); if(ret) { free(*out_creds); *out_creds = NULL; return ret; } ret = get_cred_kdc(context, id, flags, addresses, in_creds, krbtgt, NULL, NULL, *out_creds); krb5_free_creds (context, krbtgt); if(ret) { free(*out_creds); *out_creds = NULL; } return ret; } static int not_found(krb5_context context, krb5_const_principal p, krb5_error_code code) { krb5_error_code ret; char *str; ret = krb5_unparse_name(context, p, &str); if(ret) { krb5_clear_error_message(context); return code; } krb5_set_error_message(context, code, N_("Matching credential (%s) not found", ""), str); free(str); return code; } static krb5_error_code find_cred(krb5_context context, krb5_ccache id, krb5_principal server, krb5_creds **tgts, krb5_creds *out_creds) { krb5_error_code ret; krb5_creds mcreds; krb5_cc_clear_mcred(&mcreds); mcreds.server = server; krb5_timeofday(context, &mcreds.times.endtime); ret = krb5_cc_retrieve_cred(context, id, KRB5_TC_DONT_MATCH_REALM | KRB5_TC_MATCH_TIMES, &mcreds, out_creds); if(ret == 0) return 0; while(tgts && *tgts){ if(krb5_compare_creds(context, KRB5_TC_DONT_MATCH_REALM, &mcreds, *tgts)){ ret = krb5_copy_creds_contents(context, *tgts, out_creds); return ret; } tgts++; } return not_found(context, server, KRB5_CC_NOTFOUND); } static krb5_error_code add_cred(krb5_context context, krb5_creds const *tkt, krb5_creds ***tgts) { int i; krb5_error_code ret; krb5_creds **tmp = *tgts; for(i = 0; tmp && tmp[i]; i++); /* XXX */ tmp = realloc(tmp, (i+2)*sizeof(*tmp)); if(tmp == NULL) return krb5_enomem(context); *tgts = tmp; ret = krb5_copy_creds(context, tkt, &tmp[i]); tmp[i+1] = NULL; return ret; } static krb5_error_code get_cred_kdc_capath_worker(krb5_context context, krb5_kdc_flags flags, krb5_ccache ccache, krb5_creds *in_creds, krb5_const_realm try_realm, krb5_principal impersonate_principal, Ticket *second_ticket, krb5_creds **out_creds, krb5_creds ***ret_tgts) { krb5_error_code ret; krb5_creds *tgt = NULL; krb5_creds tmp_creds; krb5_const_realm client_realm, server_realm; int ok_as_delegate = 1; *out_creds = calloc(1, sizeof(**out_creds)); if (*out_creds == NULL) return krb5_enomem(context); memset(&tmp_creds, 0, sizeof(tmp_creds)); client_realm = krb5_principal_get_realm(context, in_creds->client); server_realm = krb5_principal_get_realm(context, in_creds->server); ret = krb5_copy_principal(context, in_creds->client, &tmp_creds.client); if (ret) goto out; ret = krb5_make_principal(context, &tmp_creds.server, try_realm, KRB5_TGS_NAME, server_realm, NULL); if (ret) goto out; { krb5_creds tgts; /* * If we have krbtgt/server_realm@try_realm cached, use it and we're * done. */ ret = find_cred(context, ccache, tmp_creds.server, *ret_tgts, &tgts); if (ret == 0) { /* only allow implicit ok_as_delegate if the realm is the clients realm */ if (strcmp(try_realm, client_realm) != 0 || strcmp(try_realm, server_realm) != 0) { ok_as_delegate = tgts.flags.b.ok_as_delegate; } ret = get_cred_kdc_address(context, ccache, flags, NULL, in_creds, &tgts, impersonate_principal, second_ticket, *out_creds); krb5_free_cred_contents(context, &tgts); if (ret == 0 && !krb5_principal_compare(context, in_creds->server, (*out_creds)->server)) { ret = KRB5KDC_ERR_S_PRINCIPAL_UNKNOWN; } if (ret == 0 && ok_as_delegate == 0) (*out_creds)->flags.b.ok_as_delegate = 0; goto out; } } if (krb5_realm_compare(context, in_creds->client, in_creds->server)) { ret = not_found(context, in_creds->server, KRB5_CC_NOTFOUND); goto out; } /* * XXX This can loop forever, plus we recurse, so we can't just keep a * count here. The count would have to get passed around by reference. * * The KDCs check for transit loops for us, and capath data is finite, so * in fact we'll fall out of this loop at some point. We should do our own * transit loop checking (like get_cred_kdc_referral()), and we should * impose a max number of iterations altogether. But barring malicious or * broken KDCs, this is good enough. */ while (1) { heim_general_string tgt_inst; ret = get_cred_kdc_capath(context, flags, ccache, &tmp_creds, NULL, NULL, &tgt, ret_tgts); if (ret) goto out; /* * if either of the chain or the ok_as_delegate was stripped * by the kdc, make sure we strip it too. */ if (ok_as_delegate == 0 || tgt->flags.b.ok_as_delegate == 0) { ok_as_delegate = 0; tgt->flags.b.ok_as_delegate = 0; } ret = add_cred(context, tgt, ret_tgts); if (ret) goto out; tgt_inst = tgt->server->name.name_string.val[1]; if (strcmp(tgt_inst, server_realm) == 0) break; krb5_free_principal(context, tmp_creds.server); tmp_creds.server = NULL; ret = krb5_make_principal(context, &tmp_creds.server, tgt_inst, KRB5_TGS_NAME, server_realm, NULL); if (ret) goto out; ret = krb5_free_creds(context, tgt); tgt = NULL; if (ret) goto out; } ret = get_cred_kdc_address(context, ccache, flags, NULL, in_creds, tgt, impersonate_principal, second_ticket, *out_creds); if (ret == 0 && !krb5_principal_compare(context, in_creds->server, (*out_creds)->server)) { krb5_free_cred_contents(context, *out_creds); ret = KRB5KDC_ERR_S_PRINCIPAL_UNKNOWN; } if (ret == 0 && ok_as_delegate == 0) (*out_creds)->flags.b.ok_as_delegate = 0; out: if (ret) { krb5_free_creds(context, *out_creds); *out_creds = NULL; } if (tmp_creds.server) krb5_free_principal(context, tmp_creds.server); if (tmp_creds.client) krb5_free_principal(context, tmp_creds.client); if (tgt) krb5_free_creds(context, tgt); return ret; } /* get_cred(server) creds = cc_get_cred(server) if(creds) return creds tgt = cc_get_cred(krbtgt/server_realm@any_realm) if(tgt) return get_cred_tgt(server, tgt) if(client_realm == server_realm) return NULL tgt = get_cred(krbtgt/server_realm@client_realm) while(tgt_inst != server_realm) tgt = get_cred(krbtgt/server_realm@tgt_inst) return get_cred_tgt(server, tgt) */ static krb5_error_code get_cred_kdc_capath(krb5_context context, krb5_kdc_flags flags, krb5_ccache ccache, krb5_creds *in_creds, krb5_principal impersonate_principal, Ticket *second_ticket, krb5_creds **out_creds, krb5_creds ***ret_tgts) { krb5_error_code ret; krb5_const_realm client_realm, server_realm, try_realm; client_realm = krb5_principal_get_realm(context, in_creds->client); server_realm = krb5_principal_get_realm(context, in_creds->server); try_realm = client_realm; ret = get_cred_kdc_capath_worker(context, flags, ccache, in_creds, try_realm, impersonate_principal, second_ticket, out_creds, ret_tgts); if (ret == KRB5KDC_ERR_S_PRINCIPAL_UNKNOWN) { try_realm = krb5_config_get_string(context, NULL, "capaths", client_realm, server_realm, NULL); if (try_realm != NULL && strcmp(try_realm, client_realm)) { ret = get_cred_kdc_capath_worker(context, flags, ccache, in_creds, try_realm, impersonate_principal, second_ticket, out_creds, ret_tgts); } } return ret; } /* * Get a service ticket from a KDC by chasing referrals from a start realm. * * All referral TGTs produced in the process are thrown away when we're done. * We don't store them, and we don't allow other search mechanisms (capaths) to * use referral TGTs produced here. */ static krb5_error_code get_cred_kdc_referral(krb5_context context, krb5_kdc_flags flags, krb5_ccache ccache, krb5_creds *in_creds, krb5_principal impersonate_principal, Ticket *second_ticket, krb5_creds **out_creds) { krb5_realm start_realm = NULL; krb5_data config_start_realm; krb5_error_code ret; krb5_creds tgt, referral, ticket; krb5_creds **referral_tgts = NULL; /* used for loop detection */ int loop = 0; int ok_as_delegate = 1; size_t i; if (in_creds->server->name.name_string.len < 2 && !flags.b.canonicalize) { krb5_set_error_message(context, KRB5KDC_ERR_PATH_NOT_ACCEPTED, N_("Name too short to do referals, skipping", "")); return KRB5KDC_ERR_PATH_NOT_ACCEPTED; } memset(&tgt, 0, sizeof(tgt)); memset(&ticket, 0, sizeof(ticket)); flags.b.canonicalize = 1; *out_creds = NULL; ret = krb5_cc_get_config(context, ccache, NULL, "start_realm", &config_start_realm); if (ret == 0) { start_realm = strndup(config_start_realm.data, config_start_realm.length); krb5_data_free(&config_start_realm); } else { start_realm = strdup(krb5_principal_get_realm(context, in_creds->client)); } if (start_realm == NULL) return krb5_enomem(context); /* find tgt for the clients base realm */ { krb5_principal tgtname; ret = krb5_make_principal(context, &tgtname, start_realm, KRB5_TGS_NAME, start_realm, NULL); if (ret) { free(start_realm); return ret; } ret = find_cred(context, ccache, tgtname, NULL, &tgt); krb5_free_principal(context, tgtname); if (ret) { free(start_realm); return ret; } } referral = *in_creds; ret = krb5_copy_principal(context, in_creds->server, &referral.server); if (ret) { krb5_free_cred_contents(context, &tgt); free(start_realm); return ret; } ret = krb5_principal_set_realm(context, referral.server, start_realm); free(start_realm); start_realm = NULL; if (ret) { krb5_free_cred_contents(context, &tgt); krb5_free_principal(context, referral.server); return ret; } while (loop++ < 17) { krb5_creds **tickets; krb5_creds mcreds; char *referral_realm; /* Use cache if we are not doing impersonation or contrained deleg */ if (impersonate_principal == NULL || flags.b.constrained_delegation) { krb5_cc_clear_mcred(&mcreds); mcreds.server = referral.server; krb5_timeofday(context, &mcreds.times.endtime); ret = krb5_cc_retrieve_cred(context, ccache, KRB5_TC_MATCH_TIMES, &mcreds, &ticket); } else ret = EINVAL; if (ret) { ret = get_cred_kdc_address(context, ccache, flags, NULL, &referral, &tgt, impersonate_principal, second_ticket, &ticket); if (ret) goto out; } /* Did we get the right ticket ? */ if (krb5_principal_compare_any_realm(context, referral.server, ticket.server)) break; if (!krb5_principal_is_krbtgt(context, ticket.server)) { krb5_set_error_message(context, KRB5KRB_AP_ERR_NOT_US, N_("Got back an non krbtgt " "ticket referrals", "")); ret = KRB5KRB_AP_ERR_NOT_US; goto out; } referral_realm = ticket.server->name.name_string.val[1]; /* check that there are no referrals loops */ tickets = referral_tgts; krb5_cc_clear_mcred(&mcreds); mcreds.server = ticket.server; while (tickets && *tickets){ if (krb5_compare_creds(context, KRB5_TC_DONT_MATCH_REALM, &mcreds, *tickets)) { krb5_set_error_message(context, KRB5_GET_IN_TKT_LOOP, N_("Referral from %s " "loops back to realm %s", ""), tgt.server->realm, referral_realm); ret = KRB5_GET_IN_TKT_LOOP; goto out; } tickets++; } /* * if either of the chain or the ok_as_delegate was stripped * by the kdc, make sure we strip it too. */ if (ok_as_delegate == 0 || ticket.flags.b.ok_as_delegate == 0) { ok_as_delegate = 0; ticket.flags.b.ok_as_delegate = 0; } _krb5_debug(context, 6, "get_cred_kdc_referral: got referral " "to %s from %s", referral_realm, referral.server->realm); ret = add_cred(context, &ticket, &referral_tgts); if (ret) goto out; /* try realm in the referral */ ret = krb5_principal_set_realm(context, referral.server, referral_realm); krb5_free_cred_contents(context, &tgt); tgt = ticket; memset(&ticket, 0, sizeof(ticket)); if (ret) goto out; } ret = krb5_copy_creds(context, &ticket, out_creds); out: for (i = 0; referral_tgts && referral_tgts[i]; i++) krb5_free_creds(context, referral_tgts[i]); free(referral_tgts); krb5_free_principal(context, referral.server); krb5_free_cred_contents(context, &tgt); krb5_free_cred_contents(context, &ticket); return ret; } /* * Glue function between referrals version and old client chasing * codebase. */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL _krb5_get_cred_kdc_any(krb5_context context, krb5_kdc_flags flags, krb5_ccache ccache, krb5_creds *in_creds, krb5_principal impersonate_principal, Ticket *second_ticket, krb5_creds **out_creds, krb5_creds ***ret_tgts) { krb5_error_code ret; krb5_deltat offset; ret = krb5_cc_get_kdc_offset(context, ccache, &offset); if (ret == 0) { context->kdc_sec_offset = offset; context->kdc_usec_offset = 0; } if (strcmp(in_creds->server->realm, "") != 0) { /* * Non-empty realm? Try capaths first. We might have local * policy (capaths) to honor. */ ret = get_cred_kdc_capath(context, flags, ccache, in_creds, impersonate_principal, second_ticket, out_creds, ret_tgts); if (ret == 0) return ret; } /* Otherwise try referrals */ return get_cred_kdc_referral(context, flags, ccache, in_creds, impersonate_principal, second_ticket, out_creds); } static krb5_error_code check_cc(krb5_context context, krb5_flags options, krb5_ccache ccache, krb5_creds *in_creds, krb5_creds *out_creds) { krb5_error_code ret; krb5_timestamp now; krb5_times save_times = in_creds->times; NAME_TYPE save_type = in_creds->server->name.name_type; krb5_timeofday(context, &now); if (!(options & KRB5_GC_EXPIRED_OK) && in_creds->times.endtime < now) { in_creds->times.renew_till = 0; krb5_timeofday(context, &in_creds->times.endtime); options |= KRB5_TC_MATCH_TIMES; } if (save_type == KRB5_NT_SRV_HST_NEEDS_CANON) { /* Avoid name canonicalization in krb5_cc_retrieve_cred() */ krb5_principal_set_type(context, in_creds->server, KRB5_NT_SRV_HST); } ret = krb5_cc_retrieve_cred(context, ccache, (options & (KRB5_TC_DONT_MATCH_REALM | KRB5_TC_MATCH_KEYTYPE | KRB5_TC_MATCH_TIMES)), in_creds, out_creds); in_creds->server->name.name_type = save_type; in_creds->times = save_times; return ret; } static void store_cred(krb5_context context, krb5_ccache ccache, krb5_const_principal server_princ, krb5_creds *creds) { if (!krb5_principal_compare(context, creds->server, server_princ)) { krb5_principal tmp_princ = creds->server; /* * Store the cred with the pre-canon server princ first so it * can be found quickly in the future. */ creds->server = (krb5_principal)server_princ; krb5_cc_store_cred(context, ccache, creds); creds->server = tmp_princ; /* Then store again with the canonicalized server princ */ } krb5_cc_store_cred(context, ccache, creds); } KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_get_credentials_with_flags(krb5_context context, krb5_flags options, krb5_kdc_flags flags, krb5_ccache ccache, krb5_creds *in_creds, krb5_creds **out_creds) { krb5_error_code ret; krb5_name_canon_iterator name_canon_iter = NULL; krb5_name_canon_rule_options rule_opts; krb5_const_principal try_princ = NULL; krb5_principal save_princ = in_creds->server; krb5_creds **tgts; krb5_creds *res_creds; int i; if (_krb5_have_debug(context, 5)) { char *unparsed; ret = krb5_unparse_name(context, in_creds->server, &unparsed); if (ret) { _krb5_debug(context, 5, "krb5_get_creds: unable to display " "requested service principal"); } else { _krb5_debug(context, 5, "krb5_get_creds: requesting a ticket " "for %s", unparsed); free(unparsed); } } if (in_creds->session.keytype) { ret = krb5_enctype_valid(context, in_creds->session.keytype); if (ret) return ret; options |= KRB5_TC_MATCH_KEYTYPE; } *out_creds = NULL; res_creds = calloc(1, sizeof(*res_creds)); if (res_creds == NULL) return krb5_enomem(context); ret = krb5_name_canon_iterator_start(context, in_creds->server, &name_canon_iter); if (ret) return ret; next_rule: krb5_free_cred_contents(context, res_creds); memset(res_creds, 0, sizeof (*res_creds)); ret = krb5_name_canon_iterate(context, &name_canon_iter, &try_princ, &rule_opts); in_creds->server = rk_UNCONST(try_princ); if (ret) goto out; if (name_canon_iter == NULL) { if (options & KRB5_GC_CACHED) ret = KRB5_CC_NOTFOUND; else ret = KRB5KDC_ERR_S_PRINCIPAL_UNKNOWN; goto out; } ret = check_cc(context, options, ccache, in_creds, res_creds); if (ret == 0) { *out_creds = res_creds; res_creds = NULL; goto out; } else if(ret != KRB5_CC_END) { goto out; } if (options & KRB5_GC_CACHED) goto next_rule; if(options & KRB5_GC_USER_USER) flags.b.enc_tkt_in_skey = 1; if (flags.b.enc_tkt_in_skey) options |= KRB5_GC_NO_STORE; tgts = NULL; ret = _krb5_get_cred_kdc_any(context, flags, ccache, in_creds, NULL, NULL, out_creds, &tgts); for (i = 0; tgts && tgts[i]; i++) { if ((options & KRB5_GC_NO_STORE) == 0) krb5_cc_store_cred(context, ccache, tgts[i]); krb5_free_creds(context, tgts[i]); } free(tgts); /* We don't yet have TGS w/ FAST, so we can't protect KBR-ERRORs */ if (ret == KRB5KDC_ERR_S_PRINCIPAL_UNKNOWN && !(rule_opts & KRB5_NCRO_USE_FAST)) goto next_rule; if(ret == 0 && (options & KRB5_GC_NO_STORE) == 0) store_cred(context, ccache, in_creds->server, *out_creds); if (ret == 0 && _krb5_have_debug(context, 5)) { char *unparsed; ret = krb5_unparse_name(context, (*out_creds)->server, &unparsed); if (ret) { _krb5_debug(context, 5, "krb5_get_creds: unable to display " "service principal"); } else { _krb5_debug(context, 5, "krb5_get_creds: got a ticket for %s", unparsed); free(unparsed); } } out: in_creds->server = save_princ; krb5_free_creds(context, res_creds); krb5_free_name_canon_iterator(context, name_canon_iter); if (ret) return not_found(context, in_creds->server, ret); return 0; } KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_get_credentials(krb5_context context, krb5_flags options, krb5_ccache ccache, krb5_creds *in_creds, krb5_creds **out_creds) { krb5_kdc_flags flags; flags.i = 0; return krb5_get_credentials_with_flags(context, options, flags, ccache, in_creds, out_creds); } struct krb5_get_creds_opt_data { krb5_principal self; krb5_flags options; krb5_enctype enctype; Ticket *ticket; }; KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_get_creds_opt_alloc(krb5_context context, krb5_get_creds_opt *opt) { *opt = calloc(1, sizeof(**opt)); if (*opt == NULL) return krb5_enomem(context); return 0; } KRB5_LIB_FUNCTION void KRB5_LIB_CALL krb5_get_creds_opt_free(krb5_context context, krb5_get_creds_opt opt) { if (opt->self) krb5_free_principal(context, opt->self); if (opt->ticket) { free_Ticket(opt->ticket); free(opt->ticket); } memset(opt, 0, sizeof(*opt)); free(opt); } KRB5_LIB_FUNCTION void KRB5_LIB_CALL krb5_get_creds_opt_set_options(krb5_context context, krb5_get_creds_opt opt, krb5_flags options) { opt->options = options; } KRB5_LIB_FUNCTION void KRB5_LIB_CALL krb5_get_creds_opt_add_options(krb5_context context, krb5_get_creds_opt opt, krb5_flags options) { opt->options |= options; } KRB5_LIB_FUNCTION void KRB5_LIB_CALL krb5_get_creds_opt_set_enctype(krb5_context context, krb5_get_creds_opt opt, krb5_enctype enctype) { opt->enctype = enctype; } KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_get_creds_opt_set_impersonate(krb5_context context, krb5_get_creds_opt opt, krb5_const_principal self) { if (opt->self) krb5_free_principal(context, opt->self); return krb5_copy_principal(context, self, &opt->self); } KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_get_creds_opt_set_ticket(krb5_context context, krb5_get_creds_opt opt, const Ticket *ticket) { if (opt->ticket) { free_Ticket(opt->ticket); free(opt->ticket); opt->ticket = NULL; } if (ticket) { krb5_error_code ret; opt->ticket = malloc(sizeof(*ticket)); if (opt->ticket == NULL) return krb5_enomem(context); ret = copy_Ticket(ticket, opt->ticket); if (ret) { free(opt->ticket); opt->ticket = NULL; krb5_set_error_message(context, ret, N_("malloc: out of memory", "")); return ret; } } return 0; } KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_get_creds(krb5_context context, krb5_get_creds_opt opt, krb5_ccache ccache, krb5_const_principal inprinc, krb5_creds **out_creds) { krb5_kdc_flags flags; krb5_flags options; krb5_creds in_creds; krb5_error_code ret; krb5_creds **tgts; krb5_creds *res_creds; krb5_const_principal try_princ = NULL; krb5_name_canon_iterator name_canon_iter = NULL; krb5_name_canon_rule_options rule_opts; int i; int type; const char *comp; memset(&in_creds, 0, sizeof(in_creds)); in_creds.server = rk_UNCONST(inprinc); if (_krb5_have_debug(context, 5)) { char *unparsed; ret = krb5_unparse_name(context, in_creds.server, &unparsed); if (ret) { _krb5_debug(context, 5, "krb5_get_creds: unable to display " "requested service principal"); } else { _krb5_debug(context, 5, "krb5_get_creds: requesting a ticket " "for %s", unparsed); free(unparsed); } } if (opt && opt->enctype) { ret = krb5_enctype_valid(context, opt->enctype); if (ret) return ret; } ret = krb5_cc_get_principal(context, ccache, &in_creds.client); if (ret) return ret; if (opt) options = opt->options; else options = 0; flags.i = 0; *out_creds = NULL; res_creds = calloc(1, sizeof(*res_creds)); if (res_creds == NULL) { krb5_free_principal(context, in_creds.client); return krb5_enomem(context); } if (opt && opt->enctype) { in_creds.session.keytype = opt->enctype; options |= KRB5_TC_MATCH_KEYTYPE; } ret = krb5_name_canon_iterator_start(context, in_creds.server, &name_canon_iter); if (ret) goto out; next_rule: ret = krb5_name_canon_iterate(context, &name_canon_iter, &try_princ, &rule_opts); in_creds.server = rk_UNCONST(try_princ); if (ret) goto out; if (name_canon_iter == NULL) { if (options & KRB5_GC_CACHED) ret = KRB5_CC_NOTFOUND; else ret = KRB5KDC_ERR_S_PRINCIPAL_UNKNOWN; goto out; } ret = check_cc(context, options, ccache, &in_creds, res_creds); if (ret == 0) { *out_creds = res_creds; res_creds = NULL; goto out; } else if (ret != KRB5_CC_END) { goto out; } if (options & KRB5_GC_CACHED) goto next_rule; type = krb5_principal_get_type(context, try_princ); comp = krb5_principal_get_comp_string(context, try_princ, 0); if ((type == KRB5_NT_SRV_HST || type == KRB5_NT_UNKNOWN) && comp != NULL && strcmp(comp, "host") == 0) flags.b.canonicalize = 1; if (rule_opts & KRB5_NCRO_NO_REFERRALS) flags.b.canonicalize = 0; else flags.b.canonicalize = (options & KRB5_GC_CANONICALIZE) ? 1 : 0; if (options & KRB5_GC_USER_USER) { flags.b.enc_tkt_in_skey = 1; options |= KRB5_GC_NO_STORE; } if (options & KRB5_GC_FORWARDABLE) flags.b.forwardable = 1; if (options & KRB5_GC_NO_TRANSIT_CHECK) flags.b.disable_transited_check = 1; if (options & KRB5_GC_CONSTRAINED_DELEGATION) { flags.b.request_anonymous = 1; /* XXX ARGH confusion */ flags.b.constrained_delegation = 1; } tgts = NULL; ret = _krb5_get_cred_kdc_any(context, flags, ccache, &in_creds, opt ? opt->self : 0, opt ? opt->ticket : 0, out_creds, &tgts); for (i = 0; tgts && tgts[i]; i++) { if ((options & KRB5_GC_NO_STORE) == 0) krb5_cc_store_cred(context, ccache, tgts[i]); krb5_free_creds(context, tgts[i]); } free(tgts); /* We don't yet have TGS w/ FAST, so we can't protect KBR-ERRORs */ if (ret == KRB5KDC_ERR_S_PRINCIPAL_UNKNOWN && !(rule_opts & KRB5_NCRO_USE_FAST)) goto next_rule; if (ret == 0 && (options & KRB5_GC_NO_STORE) == 0) store_cred(context, ccache, inprinc, *out_creds); if (ret == 0 && _krb5_have_debug(context, 5)) { char *unparsed; ret = krb5_unparse_name(context, (*out_creds)->server, &unparsed); if (ret) { _krb5_debug(context, 5, "krb5_get_creds: unable to display " "service principal"); } else { _krb5_debug(context, 5, "krb5_get_creds: got a ticket for %s", unparsed); free(unparsed); } } out: krb5_free_creds(context, res_creds); krb5_free_principal(context, in_creds.client); krb5_free_name_canon_iterator(context, name_canon_iter); if (ret) return not_found(context, inprinc, ret); return ret; } /* * */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_get_renewed_creds(krb5_context context, krb5_creds *creds, krb5_const_principal client, krb5_ccache ccache, const char *in_tkt_service) { krb5_error_code ret; krb5_kdc_flags flags; krb5_creds in, *template, *out = NULL; memset(&in, 0, sizeof(in)); memset(creds, 0, sizeof(*creds)); ret = krb5_copy_principal(context, client, &in.client); if (ret) return ret; if (in_tkt_service) { ret = krb5_parse_name(context, in_tkt_service, &in.server); if (ret) { krb5_free_principal(context, in.client); return ret; } } else { const char *realm = krb5_principal_get_realm(context, client); ret = krb5_make_principal(context, &in.server, realm, KRB5_TGS_NAME, realm, NULL); if (ret) { krb5_free_principal(context, in.client); return ret; } } flags.i = 0; flags.b.renewable = flags.b.renew = 1; /* * Get template from old credential cache for the same entry, if * this failes, no worries. */ ret = krb5_get_credentials(context, KRB5_GC_CACHED, ccache, &in, &template); if (ret == 0) { flags.b.forwardable = template->flags.b.forwardable; flags.b.proxiable = template->flags.b.proxiable; krb5_free_creds (context, template); } ret = krb5_get_kdc_cred(context, ccache, flags, NULL, NULL, &in, &out); krb5_free_principal(context, in.client); krb5_free_principal(context, in.server); if (ret) return ret; ret = krb5_copy_creds_contents(context, out, creds); krb5_free_creds(context, out); return ret; } heimdal-7.5.0/lib/krb5/principal.c0000644000175000017500000015724713212137553015032 0ustar niknik/* * Copyright (c) 1997-2007 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ /** * @page krb5_principal_intro The principal handing functions. * * A Kerberos principal is a email address looking string that * contains two parts separated by @. The second part is the kerberos * realm the principal belongs to and the first is a list of 0 or * more components. For example * @verbatim lha@SU.SE host/hummel.it.su.se@SU.SE host/admin@H5L.ORG @endverbatim * * See the library functions here: @ref krb5_principal */ #include "krb5_locl.h" #ifdef HAVE_RES_SEARCH #define USE_RESOLVER #endif #ifdef HAVE_ARPA_NAMESER_H #include #endif #include #include "resolve.h" #define princ_num_comp(P) ((P)->name.name_string.len) #define princ_type(P) ((P)->name.name_type) #define princ_comp(P) ((P)->name.name_string.val) #define princ_ncomp(P, N) ((P)->name.name_string.val[(N)]) #define princ_realm(P) ((P)->realm) static krb5_error_code set_default_princ_type(krb5_principal p, NAME_TYPE defnt) { if (princ_num_comp(p) > 1 && strcmp(princ_ncomp(p, 0), KRB5_TGS_NAME) == 0) princ_type(p) = KRB5_NT_SRV_INST; else if (princ_num_comp(p) > 1 && strcmp(princ_ncomp(p, 0), "host") == 0) princ_type(p) = KRB5_NT_SRV_HST; else if (princ_num_comp(p) > 1 && strcmp(princ_ncomp(p, 0), "kca_service") == 0) princ_type(p) = KRB5_NT_SRV_HST; else if (princ_num_comp(p) == 2 && strcmp(princ_ncomp(p, 0), KRB5_WELLKNOWN_NAME) == 0) princ_type(p) = KRB5_NT_WELLKNOWN; else if (princ_num_comp(p) == 1 && strchr(princ_ncomp(p, 0), '@') != NULL) princ_type(p) = KRB5_NT_SMTP_NAME; else princ_type(p) = defnt; return 0; } static krb5_error_code append_component(krb5_context, krb5_principal, const char *, size_t); /** * Frees a Kerberos principal allocated by the library with * krb5_parse_name(), krb5_make_principal() or any other related * principal functions. * * @param context A Kerberos context. * @param p a principal to free. * * @return An krb5 error code, see krb5_get_error_message(). * * @ingroup krb5_principal */ KRB5_LIB_FUNCTION void KRB5_LIB_CALL krb5_free_principal(krb5_context context, krb5_principal p) { if(p){ free_Principal(p); free(p); } } /** * Set the type of the principal * * @param context A Kerberos context. * @param principal principal to set the type for * @param type the new type * * @return An krb5 error code, see krb5_get_error_message(). * * @ingroup krb5_principal */ KRB5_LIB_FUNCTION void KRB5_LIB_CALL krb5_principal_set_type(krb5_context context, krb5_principal principal, int type) { princ_type(principal) = type; } /** * Get the type of the principal * * @param context A Kerberos context. * @param principal principal to get the type for * * @return the type of principal * * @ingroup krb5_principal */ KRB5_LIB_FUNCTION int KRB5_LIB_CALL krb5_principal_get_type(krb5_context context, krb5_const_principal principal) { return princ_type(principal); } /** * Get the realm of the principal * * @param context A Kerberos context. * @param principal principal to get the realm for * * @return realm of the principal, don't free or use after krb5_principal is freed * * @ingroup krb5_principal */ KRB5_LIB_FUNCTION const char* KRB5_LIB_CALL krb5_principal_get_realm(krb5_context context, krb5_const_principal principal) { return princ_realm(principal); } KRB5_LIB_FUNCTION const char* KRB5_LIB_CALL krb5_principal_get_comp_string(krb5_context context, krb5_const_principal principal, unsigned int component) { if(component >= princ_num_comp(principal)) return NULL; return princ_ncomp(principal, component); } /** * Get number of component is principal. * * @param context Kerberos 5 context * @param principal principal to query * * @return number of components in string * * @ingroup krb5_principal */ KRB5_LIB_FUNCTION unsigned int KRB5_LIB_CALL krb5_principal_get_num_comp(krb5_context context, krb5_const_principal principal) { return princ_num_comp(principal); } /** * Parse a name into a krb5_principal structure, flags controls the behavior. * * @param context Kerberos 5 context * @param name name to parse into a Kerberos principal * @param flags flags to control the behavior * @param principal returned principal, free with krb5_free_principal(). * * @return An krb5 error code, see krb5_get_error_message(). * * @ingroup krb5_principal */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_parse_name_flags(krb5_context context, const char *name, int flags, krb5_principal *principal) { krb5_error_code ret; heim_general_string *comp; heim_general_string realm = NULL; int ncomp; const char *p; char *q; char *s; char *start; int n; char c; int got_realm = 0; int first_at = 1; int no_realm = flags & KRB5_PRINCIPAL_PARSE_NO_REALM; int require_realm = flags & KRB5_PRINCIPAL_PARSE_REQUIRE_REALM; int enterprise = flags & KRB5_PRINCIPAL_PARSE_ENTERPRISE; int ignore_realm = flags & KRB5_PRINCIPAL_PARSE_IGNORE_REALM; int no_def_realm = flags & KRB5_PRINCIPAL_PARSE_NO_DEF_REALM; *principal = NULL; if (no_realm && require_realm) { krb5_set_error_message(context, KRB5_ERR_NO_SERVICE, N_("Can't require both realm and " "no realm at the same time", "")); return KRB5_ERR_NO_SERVICE; } /* count number of component, * enterprise names only have one component */ ncomp = 1; if (!enterprise) { for (p = name; *p; p++) { if (*p=='\\') { if (!p[1]) { krb5_set_error_message(context, KRB5_PARSE_MALFORMED, N_("trailing \\ in principal name", "")); return KRB5_PARSE_MALFORMED; } p++; } else if (*p == '/') ncomp++; else if (*p == '@') break; } } comp = calloc(ncomp, sizeof(*comp)); if (comp == NULL) return krb5_enomem(context); n = 0; p = start = q = s = strdup(name); if (start == NULL) { free(comp); return krb5_enomem(context); } while (*p) { c = *p++; if (c == '\\') { c = *p++; if (c == 'n') c = '\n'; else if (c == 't') c = '\t'; else if (c == 'b') c = '\b'; else if (c == '0') c = '\0'; else if (c == '\0') { ret = KRB5_PARSE_MALFORMED; krb5_set_error_message(context, ret, N_("trailing \\ in principal name", "")); goto exit; } } else if (enterprise && first_at) { if (c == '@') first_at = 0; } else if ((c == '/' && !enterprise) || c == '@') { if (got_realm) { ret = KRB5_PARSE_MALFORMED; krb5_set_error_message(context, ret, N_("part after realm in principal name", "")); goto exit; } else { comp[n] = malloc(q - start + 1); if (comp[n] == NULL) { ret = krb5_enomem(context); goto exit; } memcpy(comp[n], start, q - start); comp[n][q - start] = 0; n++; } if (c == '@') got_realm = 1; start = q; continue; } if (got_realm && (c == '/' || c == '\0')) { ret = KRB5_PARSE_MALFORMED; krb5_set_error_message(context, ret, N_("part after realm in principal name", "")); goto exit; } *q++ = c; } if (got_realm) { if (no_realm) { ret = KRB5_PARSE_MALFORMED; krb5_set_error_message(context, ret, N_("realm found in 'short' principal " "expected to be without one", "")); goto exit; } if (!ignore_realm) { realm = malloc(q - start + 1); if (realm == NULL) { ret = krb5_enomem(context); goto exit; } memcpy(realm, start, q - start); realm[q - start] = 0; } } else { if (require_realm) { ret = KRB5_PARSE_MALFORMED; krb5_set_error_message(context, ret, N_("realm NOT found in principal " "expected to be with one", "")); goto exit; } else if (no_realm || no_def_realm) { realm = NULL; } else { ret = krb5_get_default_realm(context, &realm); if (ret) goto exit; } comp[n] = malloc(q - start + 1); if (comp[n] == NULL) { ret = krb5_enomem(context); goto exit; } memcpy(comp[n], start, q - start); comp[n][q - start] = 0; n++; } *principal = calloc(1, sizeof(**principal)); if (*principal == NULL) { ret = krb5_enomem(context); goto exit; } (*principal)->name.name_string.val = comp; princ_num_comp(*principal) = n; (*principal)->realm = realm; if (enterprise) princ_type(*principal) = KRB5_NT_ENTERPRISE_PRINCIPAL; else set_default_princ_type(*principal, KRB5_NT_PRINCIPAL); free(s); return 0; exit: while (n>0) { free(comp[--n]); } free(comp); krb5_free_default_realm(context, realm); free(s); return ret; } /** * Parse a name into a krb5_principal structure * * @param context Kerberos 5 context * @param name name to parse into a Kerberos principal * @param principal returned principal, free with krb5_free_principal(). * * @return An krb5 error code, see krb5_get_error_message(). * * @ingroup krb5_principal */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_parse_name(krb5_context context, const char *name, krb5_principal *principal) { return krb5_parse_name_flags(context, name, 0, principal); } static const char quotable_chars[] = " \n\t\b\\/@"; static const char replace_chars[] = " ntb\\/@"; #define add_char(BASE, INDEX, LEN, C) do { if((INDEX) < (LEN)) (BASE)[(INDEX)++] = (C); }while(0); static size_t quote_string(const char *s, char *out, size_t idx, size_t len, int display) { const char *p, *q; for(p = s; *p && idx < len; p++){ q = strchr(quotable_chars, *p); if (q && display) { add_char(out, idx, len, replace_chars[q - quotable_chars]); } else if (q) { add_char(out, idx, len, '\\'); add_char(out, idx, len, replace_chars[q - quotable_chars]); }else add_char(out, idx, len, *p); } if(idx < len) out[idx] = '\0'; return idx; } static krb5_error_code unparse_name_fixed(krb5_context context, krb5_const_principal principal, char *name, size_t len, int flags) { size_t idx = 0; size_t i; int short_form = (flags & KRB5_PRINCIPAL_UNPARSE_SHORT) != 0; int no_realm = (flags & KRB5_PRINCIPAL_UNPARSE_NO_REALM) != 0; int display = (flags & KRB5_PRINCIPAL_UNPARSE_DISPLAY) != 0; if (!no_realm && princ_realm(principal) == NULL) { krb5_set_error_message(context, ERANGE, N_("Realm missing from principal, " "can't unparse", "")); return ERANGE; } for(i = 0; i < princ_num_comp(principal); i++){ if(i) add_char(name, idx, len, '/'); idx = quote_string(princ_ncomp(principal, i), name, idx, len, display); if(idx == len) { krb5_set_error_message(context, ERANGE, N_("Out of space printing principal", "")); return ERANGE; } } /* add realm if different from default realm */ if(short_form && !no_realm) { krb5_realm r; krb5_error_code ret; ret = krb5_get_default_realm(context, &r); if(ret) return ret; if(strcmp(princ_realm(principal), r) != 0) short_form = 0; krb5_free_default_realm(context, r); } if(!short_form && !no_realm) { add_char(name, idx, len, '@'); idx = quote_string(princ_realm(principal), name, idx, len, display); if(idx == len) { krb5_set_error_message(context, ERANGE, N_("Out of space printing " "realm of principal", "")); return ERANGE; } } return 0; } /** * Unparse the principal name to a fixed buffer * * @param context A Kerberos context. * @param principal principal to unparse * @param name buffer to write name to * @param len length of buffer * * @return An krb5 error code, see krb5_get_error_message(). * * @ingroup krb5_principal */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_unparse_name_fixed(krb5_context context, krb5_const_principal principal, char *name, size_t len) { return unparse_name_fixed(context, principal, name, len, 0); } /** * Unparse the principal name to a fixed buffer. The realm is skipped * if its a default realm. * * @param context A Kerberos context. * @param principal principal to unparse * @param name buffer to write name to * @param len length of buffer * * @return An krb5 error code, see krb5_get_error_message(). * * @ingroup krb5_principal */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_unparse_name_fixed_short(krb5_context context, krb5_const_principal principal, char *name, size_t len) { return unparse_name_fixed(context, principal, name, len, KRB5_PRINCIPAL_UNPARSE_SHORT); } /** * Unparse the principal name with unparse flags to a fixed buffer. * * @param context A Kerberos context. * @param principal principal to unparse * @param flags unparse flags * @param name buffer to write name to * @param len length of buffer * * @return An krb5 error code, see krb5_get_error_message(). * * @ingroup krb5_principal */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_unparse_name_fixed_flags(krb5_context context, krb5_const_principal principal, int flags, char *name, size_t len) { return unparse_name_fixed(context, principal, name, len, flags); } static krb5_error_code unparse_name(krb5_context context, krb5_const_principal principal, char **name, int flags) { size_t len = 0, plen; size_t i; krb5_error_code ret; /* count length */ if (princ_realm(principal)) { plen = strlen(princ_realm(principal)); if(strcspn(princ_realm(principal), quotable_chars) == plen) len += plen; else len += 2*plen; len++; /* '@' */ } for(i = 0; i < princ_num_comp(principal); i++){ plen = strlen(princ_ncomp(principal, i)); if(strcspn(princ_ncomp(principal, i), quotable_chars) == plen) len += plen; else len += 2*plen; len++; } len++; /* '\0' */ *name = malloc(len); if(*name == NULL) return krb5_enomem(context); ret = unparse_name_fixed(context, principal, *name, len, flags); if(ret) { free(*name); *name = NULL; } return ret; } /** * Unparse the Kerberos name into a string * * @param context Kerberos 5 context * @param principal principal to query * @param name resulting string, free with krb5_xfree() * * @return An krb5 error code, see krb5_get_error_message(). * * @ingroup krb5_principal */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_unparse_name(krb5_context context, krb5_const_principal principal, char **name) { return unparse_name(context, principal, name, 0); } /** * Unparse the Kerberos name into a string * * @param context Kerberos 5 context * @param principal principal to query * @param flags flag to determine the behavior * @param name resulting string, free with krb5_xfree() * * @return An krb5 error code, see krb5_get_error_message(). * * @ingroup krb5_principal */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_unparse_name_flags(krb5_context context, krb5_const_principal principal, int flags, char **name) { return unparse_name(context, principal, name, flags); } /** * Unparse the principal name to a allocated buffer. The realm is * skipped if its a default realm. * * @param context A Kerberos context. * @param principal principal to unparse * @param name returned buffer, free with krb5_xfree() * * @return An krb5 error code, see krb5_get_error_message(). * * @ingroup krb5_principal */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_unparse_name_short(krb5_context context, krb5_const_principal principal, char **name) { return unparse_name(context, principal, name, KRB5_PRINCIPAL_UNPARSE_SHORT); } /** * Set a new realm for a principal, and as a side-effect free the * previous realm. * * @param context A Kerberos context. * @param principal principal set the realm for * @param realm the new realm to set * * @return An krb5 error code, see krb5_get_error_message(). * * @ingroup krb5_principal */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_principal_set_realm(krb5_context context, krb5_principal principal, krb5_const_realm realm) { if (princ_realm(principal)) free(princ_realm(principal)); if (realm == NULL) princ_realm(principal) = NULL; else if ((princ_realm(principal) = strdup(realm)) == NULL) return krb5_enomem(context); return 0; } KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_principal_set_comp_string(krb5_context context, krb5_principal principal, unsigned int k, const char *component) { char *s; size_t i; for (i = princ_num_comp(principal); i <= k; i++) append_component(context, principal, "", 0); s = strdup(component); if (s == NULL) return krb5_enomem(context); free(princ_ncomp(principal, k)); princ_ncomp(principal, k) = s; return 0; } #ifndef HEIMDAL_SMALLER /** * Build a principal using vararg style building * * @param context A Kerberos context. * @param principal returned principal * @param rlen length of realm * @param realm realm name * @param ... a list of components ended with NULL. * * @return An krb5 error code, see krb5_get_error_message(). * * @ingroup krb5_principal */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_build_principal(krb5_context context, krb5_principal *principal, int rlen, krb5_const_realm realm, ...) { krb5_error_code ret; va_list ap; va_start(ap, realm); ret = krb5_build_principal_va(context, principal, rlen, realm, ap); va_end(ap); return ret; } #endif /** * Build a principal using vararg style building * * @param context A Kerberos context. * @param principal returned principal * @param realm realm name * @param ... a list of components ended with NULL. * * @return An krb5 error code, see krb5_get_error_message(). * * @ingroup krb5_principal */ /* coverity[+alloc : arg-*1] */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_make_principal(krb5_context context, krb5_principal *principal, krb5_const_realm realm, ...) { krb5_error_code ret; krb5_realm r = NULL; va_list ap; if(realm == NULL) { ret = krb5_get_default_realm(context, &r); if(ret) return ret; realm = r; } va_start(ap, realm); ret = krb5_build_principal_va(context, principal, strlen(realm), realm, ap); va_end(ap); if(r) krb5_free_default_realm(context, r); return ret; } static krb5_error_code append_component(krb5_context context, krb5_principal p, const char *comp, size_t comp_len) { heim_general_string *tmp; size_t len = princ_num_comp(p); tmp = realloc(princ_comp(p), (len + 1) * sizeof(*tmp)); if(tmp == NULL) return krb5_enomem(context); princ_comp(p) = tmp; princ_ncomp(p, len) = malloc(comp_len + 1); if (princ_ncomp(p, len) == NULL) return krb5_enomem(context); memcpy (princ_ncomp(p, len), comp, comp_len); princ_ncomp(p, len)[comp_len] = '\0'; princ_num_comp(p)++; return 0; } static krb5_error_code va_ext_princ(krb5_context context, krb5_principal p, va_list ap) { krb5_error_code ret = 0; while (1){ const char *s; int len; if ((len = va_arg(ap, int)) == 0) break; s = va_arg(ap, const char*); if ((ret = append_component(context, p, s, len)) != 0) break; } return ret; } static krb5_error_code va_princ(krb5_context context, krb5_principal p, va_list ap) { krb5_error_code ret = 0; while (1){ const char *s; if ((s = va_arg(ap, const char*)) == NULL) break; if ((ret = append_component(context, p, s, strlen(s))) != 0) break; } return ret; } static krb5_error_code build_principal(krb5_context context, krb5_principal *principal, int rlen, krb5_const_realm realm, krb5_error_code (*func)(krb5_context, krb5_principal, va_list), va_list ap) { krb5_error_code ret; krb5_principal p; *principal = NULL; p = calloc(1, sizeof(*p)); if (p == NULL) return krb5_enomem(context); princ_realm(p) = strdup(realm); if (p->realm == NULL) { free(p); return krb5_enomem(context); } ret = func(context, p, ap); if (ret == 0) { *principal = p; set_default_princ_type(p, KRB5_NT_PRINCIPAL); } else krb5_free_principal(context, p); return ret; } KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_build_principal_va(krb5_context context, krb5_principal *principal, int rlen, krb5_const_realm realm, va_list ap) { return build_principal(context, principal, rlen, realm, va_princ, ap); } KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_build_principal_va_ext(krb5_context context, krb5_principal *principal, int rlen, krb5_const_realm realm, va_list ap) { return build_principal(context, principal, rlen, realm, va_ext_princ, ap); } KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_build_principal_ext(krb5_context context, krb5_principal *principal, int rlen, krb5_const_realm realm, ...) { krb5_error_code ret; va_list ap; va_start(ap, realm); ret = krb5_build_principal_va_ext(context, principal, rlen, realm, ap); va_end(ap); return ret; } /** * Copy a principal * * @param context A Kerberos context. * @param inprinc principal to copy * @param outprinc copied principal, free with krb5_free_principal() * * @return An krb5 error code, see krb5_get_error_message(). * * @ingroup krb5_principal */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_copy_principal(krb5_context context, krb5_const_principal inprinc, krb5_principal *outprinc) { krb5_principal p = malloc(sizeof(*p)); if (p == NULL) return krb5_enomem(context); if(copy_Principal(inprinc, p)) { free(p); return krb5_enomem(context); } *outprinc = p; return 0; } /** * Return TRUE iff princ1 == princ2 (without considering the realm) * * @param context Kerberos 5 context * @param princ1 first principal to compare * @param princ2 second principal to compare * * @return non zero if equal, 0 if not * * @ingroup krb5_principal * @see krb5_principal_compare() * @see krb5_realm_compare() */ KRB5_LIB_FUNCTION krb5_boolean KRB5_LIB_CALL krb5_principal_compare_any_realm(krb5_context context, krb5_const_principal princ1, krb5_const_principal princ2) { size_t i; if(princ_num_comp(princ1) != princ_num_comp(princ2)) return FALSE; for(i = 0; i < princ_num_comp(princ1); i++){ if(strcmp(princ_ncomp(princ1, i), princ_ncomp(princ2, i)) != 0) return FALSE; } return TRUE; } KRB5_LIB_FUNCTION krb5_boolean KRB5_LIB_CALL _krb5_principal_compare_PrincipalName(krb5_context context, krb5_const_principal princ1, PrincipalName *princ2) { size_t i; if (princ_num_comp(princ1) != princ2->name_string.len) return FALSE; for(i = 0; i < princ_num_comp(princ1); i++){ if(strcmp(princ_ncomp(princ1, i), princ2->name_string.val[i]) != 0) return FALSE; } return TRUE; } /** * Compares the two principals, including realm of the principals and returns * TRUE if they are the same and FALSE if not. * * @param context Kerberos 5 context * @param princ1 first principal to compare * @param princ2 second principal to compare * * @ingroup krb5_principal * @see krb5_principal_compare_any_realm() * @see krb5_realm_compare() */ /* * return TRUE iff princ1 == princ2 */ KRB5_LIB_FUNCTION krb5_boolean KRB5_LIB_CALL krb5_principal_compare(krb5_context context, krb5_const_principal princ1, krb5_const_principal princ2) { if (!krb5_realm_compare(context, princ1, princ2)) return FALSE; return krb5_principal_compare_any_realm(context, princ1, princ2); } /** * return TRUE iff realm(princ1) == realm(princ2) * * @param context Kerberos 5 context * @param princ1 first principal to compare * @param princ2 second principal to compare * * @ingroup krb5_principal * @see krb5_principal_compare_any_realm() * @see krb5_principal_compare() */ KRB5_LIB_FUNCTION krb5_boolean KRB5_LIB_CALL krb5_realm_compare(krb5_context context, krb5_const_principal princ1, krb5_const_principal princ2) { return strcmp(princ_realm(princ1), princ_realm(princ2)) == 0; } /** * return TRUE iff princ matches pattern * * @ingroup krb5_principal */ KRB5_LIB_FUNCTION krb5_boolean KRB5_LIB_CALL krb5_principal_match(krb5_context context, krb5_const_principal princ, krb5_const_principal pattern) { size_t i; if(princ_num_comp(princ) != princ_num_comp(pattern)) return FALSE; if(fnmatch(princ_realm(pattern), princ_realm(princ), 0) != 0) return FALSE; for(i = 0; i < princ_num_comp(princ); i++){ if(fnmatch(princ_ncomp(pattern, i), princ_ncomp(princ, i), 0) != 0) return FALSE; } return TRUE; } /* * This is the original krb5_sname_to_principal(), renamed to be a * helper of the new one. */ static krb5_error_code krb5_sname_to_principal_old(krb5_context context, const char *realm, const char *hostname, const char *sname, int32_t type, krb5_principal *ret_princ) { krb5_error_code ret; char localhost[MAXHOSTNAMELEN]; char **realms = NULL, *host = NULL; if(type != KRB5_NT_SRV_HST && type != KRB5_NT_UNKNOWN) { krb5_set_error_message(context, KRB5_SNAME_UNSUPP_NAMETYPE, N_("unsupported name type %d", ""), (int)type); return KRB5_SNAME_UNSUPP_NAMETYPE; } if(hostname == NULL) { ret = gethostname(localhost, sizeof(localhost) - 1); if (ret != 0) { ret = errno; krb5_set_error_message(context, ret, N_("Failed to get local hostname", "")); return ret; } localhost[sizeof(localhost) - 1] = '\0'; hostname = localhost; } if(sname == NULL) sname = "host"; if(type == KRB5_NT_SRV_HST) { if (realm) ret = krb5_expand_hostname(context, hostname, &host); else ret = krb5_expand_hostname_realms(context, hostname, &host, &realms); if (ret) return ret; strlwr(host); hostname = host; if (!realm) realm = realms[0]; } else if (!realm) { ret = krb5_get_host_realm(context, hostname, &realms); if(ret) return ret; realm = realms[0]; } ret = krb5_make_principal(context, ret_princ, realm, sname, hostname, NULL); if(host) free(host); if (realms) krb5_free_host_realm(context, realms); return ret; } static const struct { const char *type; int32_t value; } nametypes[] = { { "UNKNOWN", KRB5_NT_UNKNOWN }, { "PRINCIPAL", KRB5_NT_PRINCIPAL }, { "SRV_INST", KRB5_NT_SRV_INST }, { "SRV_HST", KRB5_NT_SRV_HST }, { "SRV_XHST", KRB5_NT_SRV_XHST }, { "UID", KRB5_NT_UID }, { "X500_PRINCIPAL", KRB5_NT_X500_PRINCIPAL }, { "SMTP_NAME", KRB5_NT_SMTP_NAME }, { "ENTERPRISE_PRINCIPAL", KRB5_NT_ENTERPRISE_PRINCIPAL }, { "WELLKNOWN", KRB5_NT_WELLKNOWN }, { "SRV_HST_DOMAIN", KRB5_NT_SRV_HST_DOMAIN }, { "ENT_PRINCIPAL_AND_ID", KRB5_NT_ENT_PRINCIPAL_AND_ID }, { "MS_PRINCIPAL", KRB5_NT_MS_PRINCIPAL }, { "MS_PRINCIPAL_AND_ID", KRB5_NT_MS_PRINCIPAL_AND_ID }, { "SRV_HST_NEEDS_CANON", KRB5_NT_SRV_HST_NEEDS_CANON }, { NULL, 0 } }; /** * Parse nametype string and return a nametype integer * * @ingroup krb5_principal */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_parse_nametype(krb5_context context, const char *str, int32_t *nametype) { size_t i; for(i = 0; nametypes[i].type; i++) { if (strcasecmp(nametypes[i].type, str) == 0) { *nametype = nametypes[i].value; return 0; } } krb5_set_error_message(context, KRB5_PARSE_MALFORMED, N_("Failed to find name type %s", ""), str); return KRB5_PARSE_MALFORMED; } /** * Returns true if name is Kerberos NULL name * * @ingroup krb5_principal */ krb5_boolean KRB5_LIB_FUNCTION krb5_principal_is_null(krb5_context context, krb5_const_principal principal) { if (principal->name.name_type == KRB5_NT_WELLKNOWN && principal->name.name_string.len == 2 && strcmp(principal->name.name_string.val[0], "WELLKNOWN") == 0 && strcmp(principal->name.name_string.val[1], "NULL") == 0) return TRUE; return FALSE; } const char _krb5_wellknown_lkdc[] = "WELLKNOWN:COM.APPLE.LKDC"; static const char lkdc_prefix[] = "LKDC:"; /** * Returns true if name is Kerberos an LKDC realm * * @ingroup krb5_principal */ krb5_boolean KRB5_LIB_FUNCTION krb5_realm_is_lkdc(const char *realm) { return strncmp(realm, lkdc_prefix, sizeof(lkdc_prefix)-1) == 0 || strncmp(realm, _krb5_wellknown_lkdc, sizeof(_krb5_wellknown_lkdc) - 1) == 0; } /** * Returns true if name is Kerberos an LKDC realm * * @ingroup krb5_principal */ krb5_boolean KRB5_LIB_FUNCTION krb5_principal_is_lkdc(krb5_context context, krb5_const_principal principal) { return krb5_realm_is_lkdc(principal->realm); } /** * Returns true if name is Kerberos an LKDC realm * * @ingroup krb5_principal */ krb5_boolean KRB5_LIB_FUNCTION krb5_principal_is_pku2u(krb5_context context, krb5_const_principal principal) { return strcmp(principal->realm, KRB5_PKU2U_REALM_NAME) == 0; } /** * Check if the cname part of the principal is a krbtgt principal * * @ingroup krb5_principal */ KRB5_LIB_FUNCTION krb5_boolean KRB5_LIB_CALL krb5_principal_is_krbtgt(krb5_context context, krb5_const_principal p) { return p->name.name_string.len == 2 && strcmp(p->name.name_string.val[0], KRB5_TGS_NAME) == 0; } /** * Returns true iff name is an WELLKNOWN:ORG.H5L.HOSTBASED-SERVICE * * @ingroup krb5_principal */ krb5_boolean KRB5_LIB_FUNCTION krb5_principal_is_gss_hostbased_service(krb5_context context, krb5_const_principal principal) { if (principal == NULL) return FALSE; if (principal->name.name_string.len != 2) return FALSE; if (strcmp(principal->name.name_string.val[1], KRB5_GSS_HOSTBASED_SERVICE_NAME) != 0) return FALSE; return TRUE; } /** * Check if the cname part of the principal is a initial or renewed krbtgt principal * * @ingroup krb5_principal */ krb5_boolean KRB5_LIB_FUNCTION krb5_principal_is_root_krbtgt(krb5_context context, krb5_const_principal p) { return p->name.name_string.len == 2 && strcmp(p->name.name_string.val[0], KRB5_TGS_NAME) == 0 && strcmp(p->name.name_string.val[1], p->realm) == 0; } static int tolower_ascii(int c) { if (c >= 'A' || c <= 'Z') return 'a' + (c - 'A'); return c; } typedef enum krb5_name_canon_rule_type { KRB5_NCRT_BOGUS = 0, KRB5_NCRT_AS_IS, KRB5_NCRT_QUALIFY, KRB5_NCRT_NSS } krb5_name_canon_rule_type; #ifdef UINT8_MAX #define MAXDOTS UINT8_MAX #else #define MAXDOTS (255U) #endif #ifdef UINT16_MAX #define MAXORDER UINT16_MAX #else #define MAXORDER (65535U) #endif struct krb5_name_canon_rule_data { krb5_name_canon_rule_type type; krb5_name_canon_rule_options options; uint8_t mindots; /* match this many dots or more */ uint8_t maxdots; /* match no more than this many dots */ uint16_t explicit_order; /* given order */ uint16_t order; /* actual order */ char *match_domain; /* match this stem */ char *match_realm; /* match this realm */ char *domain; /* qualify with this domain */ char *realm; /* qualify with this realm */ }; /** * Create a principal for the given service running on the given * hostname. If KRB5_NT_SRV_HST is used, the hostname is canonicalized * according the configured name canonicalization rules, with * canonicalization delayed in some cases. One rule involves DNS, which * is insecure unless DNSSEC is used, but we don't use DNSSEC-capable * resolver APIs here, so that if DNSSEC is used we wouldn't know it. * * Canonicalization is immediate (not delayed) only when there is only * one canonicalization rule and that rule indicates that we should do a * host lookup by name (i.e., DNS). * * @param context A Kerberos context. * @param hostname hostname to use * @param sname Service name to use * @param type name type of principal, use KRB5_NT_SRV_HST or KRB5_NT_UNKNOWN. * @param ret_princ return principal, free with krb5_free_principal(). * * @return An krb5 error code, see krb5_get_error_message(). * * @ingroup krb5_principal */ /* coverity[+alloc : arg-*4] */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_sname_to_principal(krb5_context context, const char *hostname, const char *sname, int32_t type, krb5_principal *ret_princ) { char *realm, *remote_host; krb5_error_code ret; register char *cp; char localname[MAXHOSTNAMELEN]; *ret_princ = NULL; if ((type != KRB5_NT_UNKNOWN) && (type != KRB5_NT_SRV_HST)) return KRB5_SNAME_UNSUPP_NAMETYPE; /* if hostname is NULL, use local hostname */ if (hostname == NULL) { if (gethostname(localname, MAXHOSTNAMELEN)) return errno; hostname = localname; } /* if sname is NULL, use "host" */ if (sname == NULL) sname = "host"; remote_host = strdup(hostname); if (remote_host == NULL) return krb5_enomem(context); if (type == KRB5_NT_SRV_HST) { krb5_name_canon_rule rules; /* Lower-case the hostname, because that's the convention */ for (cp = remote_host; *cp; cp++) if (isupper((int) (*cp))) *cp = tolower((int) (*cp)); /* * If there is only one name canon rule and it says to * canonicalize the old way, do that now, as we used to. */ ret = _krb5_get_name_canon_rules(context, &rules); if (ret) { _krb5_debug(context, 5, "Failed to get name canon rules: ret = %d", ret); free(remote_host); return ret; } if (rules[0].type == KRB5_NCRT_NSS && rules[1].type == KRB5_NCRT_BOGUS) { _krb5_debug(context, 5, "Using nss for name canon immediately"); ret = krb5_sname_to_principal_old(context, rules[0].realm, remote_host, sname, KRB5_NT_SRV_HST, ret_princ); free(remote_host); return ret; } } /* Remove trailing dots */ if (remote_host[0]) { for (cp = remote_host + strlen(remote_host)-1; *cp == '.' && cp > remote_host; cp--) { *cp = '\0'; } } realm = ""; /* "Referral realm" */ ret = krb5_build_principal(context, ret_princ, strlen(realm), realm, sname, remote_host, (char *)0); if (ret == 0 && type == KRB5_NT_SRV_HST) { /* * Hostname canonicalization is done elsewhere (in * krb5_get_credentials() and krb5_kt_get_entry()). * * We overload the name type to indicate to those functions that * this principal name requires canonicalization. * * We can't use the empty realm to denote the need to * canonicalize the hostname too: it would mean that users who * want to assert knowledge of a service's realm must also know * the canonical hostname, but in practice they don't. */ (*ret_princ)->name.name_type = KRB5_NT_SRV_HST_NEEDS_CANON; _krb5_debug(context, 5, "Building a delayed canon principal for %s/%s@", sname, remote_host); } free(remote_host); return ret; } static void tolower_str(char *s) { for (; *s != '\0'; s++) { if (isupper(*s)) *s = tolower_ascii(*s); } } static krb5_error_code rule_parse_token(krb5_context context, krb5_name_canon_rule rule, const char *tok) { long int n; int needs_type = rule->type == KRB5_NCRT_BOGUS; /* * Rules consist of a sequence of tokens, some of which indicate * what type of rule the rule is, and some of which set rule options * or ancilliary data. Last rule type token wins. */ /* Rule type tokens: */ if (needs_type && strcmp(tok, "as-is") == 0) { rule->type = KRB5_NCRT_AS_IS; } else if (needs_type && strcmp(tok, "qualify") == 0) { rule->type = KRB5_NCRT_QUALIFY; } else if (needs_type && strcmp(tok, "nss") == 0) { rule->type = KRB5_NCRT_NSS; /* Rule options: */ } else if (strcmp(tok, "use_fast") == 0) { rule->options |= KRB5_NCRO_USE_FAST; } else if (strcmp(tok, "use_dnssec") == 0) { rule->options |= KRB5_NCRO_USE_DNSSEC; } else if (strcmp(tok, "ccache_only") == 0) { rule->options |= KRB5_NCRO_GC_ONLY; } else if (strcmp(tok, "no_referrals") == 0) { rule->options |= KRB5_NCRO_NO_REFERRALS; } else if (strcmp(tok, "use_referrals") == 0) { rule->options &= ~KRB5_NCRO_NO_REFERRALS; if (rule->realm == NULL) { rule->realm = strdup(""); if (rule->realm == NULL) return krb5_enomem(context); } } else if (strcmp(tok, "lookup_realm") == 0) { rule->options |= KRB5_NCRO_LOOKUP_REALM; free(rule->realm); rule->realm = NULL; /* Rule ancilliary data: */ } else if (strncmp(tok, "domain=", strlen("domain=")) == 0) { free(rule->domain); rule->domain = strdup(tok + strlen("domain=")); if (rule->domain == NULL) return krb5_enomem(context); tolower_str(rule->domain); } else if (strncmp(tok, "realm=", strlen("realm=")) == 0) { free(rule->realm); rule->realm = strdup(tok + strlen("realm=")); if (rule->realm == NULL) return krb5_enomem(context); } else if (strncmp(tok, "match_domain=", strlen("match_domain=")) == 0) { free(rule->match_domain); rule->match_domain = strdup(tok + strlen("match_domain=")); if (rule->match_domain == NULL) return krb5_enomem(context); tolower_str(rule->match_domain); } else if (strncmp(tok, "match_realm=", strlen("match_realm=")) == 0) { free(rule->match_realm); rule->match_realm = strdup(tok + strlen("match_realm=")); if (rule->match_realm == NULL) return krb5_enomem(context); } else if (strncmp(tok, "mindots=", strlen("mindots=")) == 0) { errno = 0; n = strtol(tok + strlen("mindots="), NULL, 10); if (errno == 0 && n > 0 && n <= MAXDOTS) rule->mindots = n; } else if (strncmp(tok, "maxdots=", strlen("maxdots=")) == 0) { errno = 0; n = strtol(tok + strlen("maxdots="), NULL, 10); if (errno == 0 && n > 0 && n <= MAXDOTS) rule->maxdots = n; } else if (strncmp(tok, "order=", strlen("order=")) == 0) { errno = 0; n = strtol(tok + strlen("order="), NULL, 10); if (errno == 0 && n > 0 && n <= MAXORDER) rule->explicit_order = n; } else { _krb5_debug(context, 5, "Unrecognized name canonicalization rule token %s", tok); return EINVAL; } return 0; } static int rule_cmp(const void *a, const void *b) { krb5_const_name_canon_rule left = a; krb5_const_name_canon_rule right = b; if (left->type == KRB5_NCRT_BOGUS && right->type == KRB5_NCRT_BOGUS) return 0; if (left->type == KRB5_NCRT_BOGUS) return 1; if (right->type == KRB5_NCRT_BOGUS) return -1; if (left->explicit_order < right->explicit_order) return -1; if (left->explicit_order > right->explicit_order) return 1; return left->order - right->order; } static krb5_error_code parse_name_canon_rules(krb5_context context, char **rulestrs, krb5_name_canon_rule *rules) { krb5_error_code ret; char *tok; char *cp; char **cpp; size_t n; size_t i, k; int do_sort = 0; krb5_name_canon_rule r; *rules = NULL; for (n =0, cpp = rulestrs; cpp != NULL && *cpp != NULL; cpp++) n++; n += 2; /* Always at least one rule; two for the default case */ if ((r = calloc(n, sizeof (*r))) == NULL) return krb5_enomem(context); for (k = 0; k < n; k++) { r[k].type = KRB5_NCRT_BOGUS; r[k].match_domain = NULL; r[k].match_realm = NULL; r[k].domain = NULL; r[k].realm = NULL; } for (i = 0, k = 0; i < n && rulestrs != NULL && rulestrs[i] != NULL; i++) { cp = rulestrs[i]; r[k].explicit_order = MAXORDER; /* mark order, see below */ r[k].maxdots = MAXDOTS; r[k].order = k; /* default order */ /* Tokenize and parse value */ do { tok = cp; cp = strchr(cp, ':'); /* XXX use strtok_r() */ if (cp) *cp++ = '\0'; /* delimit token */ ret = rule_parse_token(context, &r[k], tok); if (ret == EINVAL) { r[k].type = KRB5_NCRT_BOGUS; break; } if (ret) { _krb5_free_name_canon_rules(context, r); return ret; } } while (cp && *cp); if (r[k].explicit_order != MAXORDER) do_sort = 1; /* Validate parsed rule */ if (r[k].type == KRB5_NCRT_BOGUS || (r[k].type == KRB5_NCRT_QUALIFY && !r[k].domain) || (r[k].type == KRB5_NCRT_NSS && r[k].domain)) { /* Invalid rule; mark it so and clean up */ r[k].type = KRB5_NCRT_BOGUS; free(r[k].match_domain); free(r[k].match_realm); free(r[k].domain); free(r[k].realm); r[k].realm = NULL; r[k].domain = NULL; r[k].match_domain = NULL; r[k].match_realm = NULL; _krb5_debug(context, 5, "Ignoring invalid name canonicalization rule %lu", (unsigned long)i); continue; } k++; /* good rule */ } if (do_sort) { /* * Note that we make make this a stable sort by using appareance * and explicit order. */ qsort(r, n, sizeof(r[0]), rule_cmp); } if (r[0].type == KRB5_NCRT_BOGUS) { /* No rules, or no valid rules */ r[0].type = KRB5_NCRT_NSS; } *rules = r; return 0; /* We don't communicate bad rule errors here */ } /* * This exists only because the hostname canonicalization behavior in Heimdal * (and other implementations of Kerberos) has been to use getaddrinfo(), * unsafe though it is, for ages. We can't fix it in one day. */ static void make_rules_safe(krb5_context context, krb5_name_canon_rule rules) { /* * If the only rule were to use the name service (getaddrinfo()) then we're * bound to fail. We could try to convert that rule to an as-is rule, but * when we do get a validating resolver we'd be unhappy that we did such a * conversion. Better let the user get failures and make them think about * their naming rules. */ if (rules == NULL) return; for (; rules[0].type != KRB5_NCRT_BOGUS; rules++) { if (rules->type == KRB5_NCRT_NSS) rules->options |= KRB5_NCRO_USE_DNSSEC; else rules->options |= KRB5_NCRO_USE_FAST; } } /** * This function returns an array of host-based service name * canonicalization rules. The array of rules is organized as a list. * See the definition of krb5_name_canon_rule. * * @param context A Kerberos context. * @param rules Output location for array of rules. */ KRB5_LIB_FUNCTION krb5_error_code _krb5_get_name_canon_rules(krb5_context context, krb5_name_canon_rule *rules) { krb5_error_code ret; char **values = NULL; *rules = context->name_canon_rules; if (*rules != NULL) return 0; values = krb5_config_get_strings(context, NULL, "libdefaults", "name_canon_rules", NULL); ret = parse_name_canon_rules(context, values, rules); krb5_config_free_strings(values); if (ret) return ret; if (krb5_config_get_bool_default(context, NULL, FALSE, "libdefaults", "safe_name_canon", NULL)) make_rules_safe(context, *rules); heim_assert(rules != NULL && (*rules)[0].type != KRB5_NCRT_BOGUS, "internal error in parsing principal name " "canonicalization rules"); /* Memoize */ context->name_canon_rules = *rules; return 0; } static krb5_error_code get_host_realm(krb5_context context, const char *hostname, char **realm) { krb5_error_code ret; char **hrealms = NULL; *realm = NULL; ret = krb5_get_host_realm(context, hostname, &hrealms); if (ret) return ret; if (hrealms == NULL) return KRB5_ERR_HOST_REALM_UNKNOWN; /* krb5_set_error() already done */ if (hrealms[0] == NULL) { krb5_free_host_realm(context, hrealms); return KRB5_ERR_HOST_REALM_UNKNOWN; /* krb5_set_error() already done */ } *realm = strdup(hrealms[0]); krb5_free_host_realm(context, hrealms); if (*realm == NULL) return krb5_enomem(context); return 0; } static int is_domain_suffix(const char *domain, const char *suffix) { size_t dlen = strlen(domain); size_t slen = strlen(suffix); if (dlen < slen + 2) return 0; if (strcasecmp(domain + (dlen - slen), suffix) != 0) return 0; if (domain[(dlen - slen) - 1] != '.') return 0; return 1; } /* * Applies a name canonicalization rule to a principal. * * Returns zero and no out_princ if the rule does not match. * Returns zero and an out_princ if the rule does match. */ static krb5_error_code apply_name_canon_rule(krb5_context context, krb5_name_canon_rule rules, size_t rule_idx, krb5_const_principal in_princ, krb5_principal *out_princ, krb5_name_canon_rule_options *rule_opts) { krb5_name_canon_rule rule = &rules[rule_idx]; krb5_error_code ret; unsigned int ndots = 0; krb5_principal nss = NULL; const char *sname = NULL; const char *orig_hostname = NULL; const char *new_hostname = NULL; const char *new_realm = NULL; const char *port = ""; const char *cp; char *hostname_sans_port = NULL; char *hostname_with_port = NULL; char *tmp_hostname = NULL; char *tmp_realm = NULL; *out_princ = NULL; /* Signal no match */ if (rule_opts != NULL) *rule_opts = rule->options; if (rule->type == KRB5_NCRT_BOGUS) return 0; /* rule doesn't apply */ sname = krb5_principal_get_comp_string(context, in_princ, 0); orig_hostname = krb5_principal_get_comp_string(context, in_princ, 1); /* * Some apps want to use the very non-standard svc/hostname:port@REALM * form. We do our best to support that here :( */ port = strchr(orig_hostname, ':'); if (port != NULL) { hostname_sans_port = strndup(orig_hostname, port - orig_hostname); if (hostname_sans_port == NULL) return krb5_enomem(context); orig_hostname = hostname_sans_port; } _krb5_debug(context, 5, N_("Applying a name rule (type %d) to %s", ""), rule->type, orig_hostname); if (rule->mindots > 0 || rule->maxdots > 0) { for (cp = strchr(orig_hostname, '.'); cp && *cp; cp = strchr(cp + 1, '.')) ndots++; } if (rule->mindots > 0 && ndots < rule->mindots) return 0; if (ndots > rule->maxdots) return 0; if (rule->match_domain != NULL && !is_domain_suffix(orig_hostname, rule->match_domain)) return 0; if (rule->match_realm != NULL && strcmp(rule->match_realm, in_princ->realm) != 0) return 0; new_realm = rule->realm; switch (rule->type) { case KRB5_NCRT_AS_IS: break; case KRB5_NCRT_QUALIFY: heim_assert(rule->domain != NULL, "missing domain for qualify name canon rule"); if (asprintf(&tmp_hostname, "%s.%s", orig_hostname, rule->domain) == -1 || tmp_hostname == NULL) { ret = krb5_enomem(context); goto out; } new_hostname = tmp_hostname; break; case KRB5_NCRT_NSS: if ((rule->options & KRB5_NCRO_USE_DNSSEC)) { ret = KRB5KDC_ERR_S_PRINCIPAL_UNKNOWN; krb5_set_error_message(context, ret, "Secure hostname resolution not supported"); goto out; } _krb5_debug(context, 5, "Using name service lookups"); ret = krb5_sname_to_principal_old(context, rule->realm, orig_hostname, sname, KRB5_NT_SRV_HST, &nss); if (rules[rule_idx + 1].type != KRB5_NCRT_BOGUS && (ret == KRB5_ERR_BAD_HOSTNAME || ret == KRB5_ERR_HOST_REALM_UNKNOWN)) { /* * Bad hostname / realm unknown -> rule inapplicable if * there's more rules. If it's the last rule then we want * to return all errors from krb5_sname_to_principal_old() * here. */ ret = 0; goto out; } if (ret) goto out; new_hostname = krb5_principal_get_comp_string(context, nss, 1); new_realm = krb5_principal_get_realm(context, nss); break; default: /* Can't happen */ ret = 0; goto out; } /* * This rule applies. * * Copy in_princ and mutate the copy per the matched rule. * * This way we apply to principals with two or more components, such as * domain-based names. */ ret = krb5_copy_principal(context, in_princ, out_princ); if (ret) goto out; if (new_realm == NULL && (rule->options & KRB5_NCRO_LOOKUP_REALM) != 0) { ret = get_host_realm(context, new_hostname, &tmp_realm); if (ret) goto out; new_realm = tmp_realm; } /* If we stripped off a :port, add it back in */ if (port != NULL && new_hostname != NULL) { if (asprintf(&hostname_with_port, "%s%s", new_hostname, port) == -1 || hostname_with_port == NULL) { ret = krb5_enomem(context); goto out; } new_hostname = hostname_with_port; } if (new_realm != NULL) krb5_principal_set_realm(context, *out_princ, new_realm); if (new_hostname != NULL) krb5_principal_set_comp_string(context, *out_princ, 1, new_hostname); if (princ_type(*out_princ) == KRB5_NT_SRV_HST_NEEDS_CANON) princ_type(*out_princ) = KRB5_NT_SRV_HST; /* Trace rule application */ { krb5_error_code ret2; char *unparsed; ret2 = krb5_unparse_name(context, *out_princ, &unparsed); if (ret2) { _krb5_debug(context, 5, N_("Couldn't unparse canonicalized princicpal (%d)", ""), ret); } else { _krb5_debug(context, 5, N_("Name canon rule application yields %s", ""), unparsed); free(unparsed); } } out: free(hostname_sans_port); free(hostname_with_port); free(tmp_hostname); free(tmp_realm); krb5_free_principal(context, nss); if (ret) krb5_set_error_message(context, ret, N_("Name canon rule application failed", "")); return ret; } /** * Free name canonicalization rules */ KRB5_LIB_FUNCTION void _krb5_free_name_canon_rules(krb5_context context, krb5_name_canon_rule rules) { size_t k; if (rules == NULL) return; for (k = 0; rules[k].type != KRB5_NCRT_BOGUS; k++) { free(rules[k].match_domain); free(rules[k].match_realm); free(rules[k].domain); free(rules[k].realm); } free(rules); } struct krb5_name_canon_iterator_data { krb5_name_canon_rule rules; krb5_const_principal in_princ; /* given princ */ krb5_const_principal out_princ; /* princ to be output */ krb5_principal tmp_princ; /* to be freed */ int is_trivial; /* no canon to be done */ int done; /* no more rules to be applied */ size_t cursor; /* current/next rule */ }; /** * Initialize name canonicalization iterator. * * @param context Kerberos context * @param in_princ principal name to be canonicalized OR * @param iter output iterator object */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_name_canon_iterator_start(krb5_context context, krb5_const_principal in_princ, krb5_name_canon_iterator *iter) { krb5_error_code ret; krb5_name_canon_iterator state; *iter = NULL; state = calloc(1, sizeof (*state)); if (state == NULL) return krb5_enomem(context); state->in_princ = in_princ; if (princ_type(state->in_princ) == KRB5_NT_SRV_HST_NEEDS_CANON) { ret = _krb5_get_name_canon_rules(context, &state->rules); if (ret) goto out; } else { /* Name needs no canon -> trivial iterator: in_princ is canonical */ state->is_trivial = 1; } *iter = state; return 0; out: krb5_free_name_canon_iterator(context, state); return krb5_enomem(context); } /* * Helper for name canon iteration. */ static krb5_error_code name_canon_iterate(krb5_context context, krb5_name_canon_iterator *iter, krb5_name_canon_rule_options *rule_opts) { krb5_error_code ret; krb5_name_canon_iterator state = *iter; if (rule_opts) *rule_opts = 0; if (state == NULL) return 0; if (state->done) { krb5_free_name_canon_iterator(context, state); *iter = NULL; return 0; } if (state->is_trivial && !state->done) { state->out_princ = state->in_princ; state->done = 1; return 0; } heim_assert(state->rules != NULL && state->rules[state->cursor].type != KRB5_NCRT_BOGUS, "Internal error during name canonicalization"); do { krb5_free_principal(context, state->tmp_princ); ret = apply_name_canon_rule(context, state->rules, state->cursor, state->in_princ, &state->tmp_princ, rule_opts); if (ret) { krb5_free_name_canon_iterator(context, state); *iter = NULL; return ret; } state->cursor++; } while (state->tmp_princ == NULL && state->rules[state->cursor].type != KRB5_NCRT_BOGUS); if (state->rules[state->cursor].type == KRB5_NCRT_BOGUS) state->done = 1; state->out_princ = state->tmp_princ; if (state->tmp_princ == NULL) { krb5_free_name_canon_iterator(context, state); *iter = NULL; return 0; } return 0; } /** * Iteratively apply name canon rules, outputing a principal and rule * options each time. Iteration completes when the @iter is NULL on * return or when an error is returned. Callers must free the iterator * if they abandon it mid-way. * * @param context Kerberos context * @param iter name canon rule iterator (input/output) * @param try_princ output principal name * @param rule_opts output rule options */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_name_canon_iterate(krb5_context context, krb5_name_canon_iterator *iter, krb5_const_principal *try_princ, krb5_name_canon_rule_options *rule_opts) { krb5_error_code ret; *try_princ = NULL; ret = name_canon_iterate(context, iter, rule_opts); if (*iter) *try_princ = (*iter)->out_princ; return ret; } /** * Free a name canonicalization rule iterator. */ KRB5_LIB_FUNCTION void KRB5_LIB_CALL krb5_free_name_canon_iterator(krb5_context context, krb5_name_canon_iterator iter) { if (iter == NULL) return; if (iter->tmp_princ) krb5_free_principal(context, iter->tmp_princ); free(iter); } heimdal-7.5.0/lib/krb5/salt-des3.c0000644000175000017500000001041513212137553014631 0ustar niknik/* * Copyright (c) 1997 - 2008 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "krb5_locl.h" #ifdef DES3_OLD_ENCTYPE static krb5_error_code DES3_string_to_key(krb5_context context, krb5_enctype enctype, krb5_data password, krb5_salt salt, krb5_data opaque, krb5_keyblock *key) { char *str; size_t len; unsigned char tmp[24]; DES_cblock keys[3]; krb5_error_code ret; len = password.length + salt.saltvalue.length; str = malloc(len); if (len != 0 && str == NULL) return krb5_enomem(context); memcpy(str, password.data, password.length); memcpy(str + password.length, salt.saltvalue.data, salt.saltvalue.length); { DES_cblock ivec; DES_key_schedule s[3]; int i; ret = _krb5_n_fold(str, len, tmp, 24); if (ret) { memset(str, 0, len); free(str); krb5_set_error_message(context, ret, N_("malloc: out of memory", "")); return ret; } for(i = 0; i < 3; i++){ memcpy(keys + i, tmp + i * 8, sizeof(keys[i])); DES_set_odd_parity(keys + i); if(DES_is_weak_key(keys + i)) _krb5_xor8(*(keys + i), (const unsigned char*)"\0\0\0\0\0\0\0\xf0"); DES_set_key_unchecked(keys + i, &s[i]); } memset(&ivec, 0, sizeof(ivec)); DES_ede3_cbc_encrypt(tmp, tmp, sizeof(tmp), &s[0], &s[1], &s[2], &ivec, DES_ENCRYPT); memset(s, 0, sizeof(s)); memset(&ivec, 0, sizeof(ivec)); for(i = 0; i < 3; i++){ memcpy(keys + i, tmp + i * 8, sizeof(keys[i])); DES_set_odd_parity(keys + i); if(DES_is_weak_key(keys + i)) _krb5_xor8(*(keys + i), (const unsigned char*)"\0\0\0\0\0\0\0\xf0"); } memset(tmp, 0, sizeof(tmp)); } key->keytype = enctype; krb5_data_copy(&key->keyvalue, keys, sizeof(keys)); memset(keys, 0, sizeof(keys)); memset(str, 0, len); free(str); return 0; } #endif static krb5_error_code DES3_string_to_key_derived(krb5_context context, krb5_enctype enctype, krb5_data password, krb5_salt salt, krb5_data opaque, krb5_keyblock *key) { krb5_error_code ret; size_t len = password.length + salt.saltvalue.length; char *s; s = malloc(len); if (len != 0 && s == NULL) return krb5_enomem(context); memcpy(s, password.data, password.length); memcpy(s + password.length, salt.saltvalue.data, salt.saltvalue.length); ret = krb5_string_to_key_derived(context, s, len, enctype, key); memset(s, 0, len); free(s); return ret; } #ifdef DES3_OLD_ENCTYPE struct salt_type _krb5_des3_salt[] = { { KRB5_PW_SALT, "pw-salt", DES3_string_to_key }, { 0, NULL, NULL } }; #endif struct salt_type _krb5_des3_salt_derived[] = { { KRB5_PW_SALT, "pw-salt", DES3_string_to_key_derived }, { 0, NULL, NULL } }; heimdal-7.5.0/lib/krb5/crypto-pk.c0000644000175000017500000002033113212137553014760 0ustar niknik/* * Copyright (c) 1997 - 2008 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "krb5_locl.h" #include KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL _krb5_pk_octetstring2key(krb5_context context, krb5_enctype type, const void *dhdata, size_t dhsize, const heim_octet_string *c_n, const heim_octet_string *k_n, krb5_keyblock *key) { struct _krb5_encryption_type *et = _krb5_find_enctype(type); krb5_error_code ret; size_t keylen, offset; void *keydata; unsigned char counter; unsigned char shaoutput[SHA_DIGEST_LENGTH]; EVP_MD_CTX *m; if(et == NULL) { krb5_set_error_message(context, KRB5_PROG_ETYPE_NOSUPP, N_("encryption type %d not supported", ""), type); return KRB5_PROG_ETYPE_NOSUPP; } keylen = (et->keytype->bits + 7) / 8; keydata = malloc(keylen); if (keydata == NULL) return krb5_enomem(context); m = EVP_MD_CTX_create(); if (m == NULL) { free(keydata); return krb5_enomem(context); } counter = 0; offset = 0; do { EVP_DigestInit_ex(m, EVP_sha1(), NULL); EVP_DigestUpdate(m, &counter, 1); EVP_DigestUpdate(m, dhdata, dhsize); if (c_n) EVP_DigestUpdate(m, c_n->data, c_n->length); if (k_n) EVP_DigestUpdate(m, k_n->data, k_n->length); EVP_DigestFinal_ex(m, shaoutput, NULL); memcpy((unsigned char *)keydata + offset, shaoutput, min(keylen - offset, sizeof(shaoutput))); offset += sizeof(shaoutput); counter++; } while(offset < keylen); memset(shaoutput, 0, sizeof(shaoutput)); EVP_MD_CTX_destroy(m); ret = krb5_random_to_key(context, type, keydata, keylen, key); memset(keydata, 0, sizeof(keylen)); free(keydata); return ret; } static krb5_error_code encode_uvinfo(krb5_context context, krb5_const_principal p, krb5_data *data) { KRB5PrincipalName pn; krb5_error_code ret; size_t size = 0; pn.principalName = p->name; pn.realm = p->realm; ASN1_MALLOC_ENCODE(KRB5PrincipalName, data->data, data->length, &pn, &size, ret); if (ret) { krb5_data_zero(data); krb5_set_error_message(context, ret, N_("Failed to encode KRB5PrincipalName", "")); return ret; } if (data->length != size) krb5_abortx(context, "asn1 compiler internal error"); return 0; } static krb5_error_code encode_otherinfo(krb5_context context, const AlgorithmIdentifier *ai, krb5_const_principal client, krb5_const_principal server, krb5_enctype enctype, const krb5_data *as_req, const krb5_data *pk_as_rep, const Ticket *ticket, krb5_data *other) { PkinitSP80056AOtherInfo otherinfo; PkinitSuppPubInfo pubinfo; krb5_error_code ret; krb5_data pub; size_t size = 0; krb5_data_zero(other); memset(&otherinfo, 0, sizeof(otherinfo)); memset(&pubinfo, 0, sizeof(pubinfo)); pubinfo.enctype = enctype; pubinfo.as_REQ = *as_req; pubinfo.pk_as_rep = *pk_as_rep; pubinfo.ticket = *ticket; ASN1_MALLOC_ENCODE(PkinitSuppPubInfo, pub.data, pub.length, &pubinfo, &size, ret); if (ret) { krb5_set_error_message(context, ret, N_("malloc: out of memory", "")); return ret; } if (pub.length != size) krb5_abortx(context, "asn1 compiler internal error"); ret = encode_uvinfo(context, client, &otherinfo.partyUInfo); if (ret) { free(pub.data); return ret; } ret = encode_uvinfo(context, server, &otherinfo.partyVInfo); if (ret) { free(otherinfo.partyUInfo.data); free(pub.data); return ret; } otherinfo.algorithmID = *ai; otherinfo.suppPubInfo = &pub; ASN1_MALLOC_ENCODE(PkinitSP80056AOtherInfo, other->data, other->length, &otherinfo, &size, ret); free(otherinfo.partyUInfo.data); free(otherinfo.partyVInfo.data); free(pub.data); if (ret) { krb5_set_error_message(context, ret, N_("malloc: out of memory", "")); return ret; } if (other->length != size) krb5_abortx(context, "asn1 compiler internal error"); return 0; } KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL _krb5_pk_kdf(krb5_context context, const struct AlgorithmIdentifier *ai, const void *dhdata, size_t dhsize, krb5_const_principal client, krb5_const_principal server, krb5_enctype enctype, const krb5_data *as_req, const krb5_data *pk_as_rep, const Ticket *ticket, krb5_keyblock *key) { struct _krb5_encryption_type *et; krb5_error_code ret; krb5_data other; size_t keylen, offset; uint32_t counter; unsigned char *keydata; unsigned char shaoutput[SHA512_DIGEST_LENGTH]; const EVP_MD *md; EVP_MD_CTX *m; if (der_heim_oid_cmp(&asn1_oid_id_pkinit_kdf_ah_sha1, &ai->algorithm) == 0) { md = EVP_sha1(); } else if (der_heim_oid_cmp(&asn1_oid_id_pkinit_kdf_ah_sha256, &ai->algorithm) == 0) { md = EVP_sha256(); } else if (der_heim_oid_cmp(&asn1_oid_id_pkinit_kdf_ah_sha512, &ai->algorithm) == 0) { md = EVP_sha512(); } else { krb5_set_error_message(context, KRB5_PROG_ETYPE_NOSUPP, N_("KDF not supported", "")); return KRB5_PROG_ETYPE_NOSUPP; } if (ai->parameters != NULL && (ai->parameters->length != 2 || memcmp(ai->parameters->data, "\x05\x00", 2) != 0)) { krb5_set_error_message(context, KRB5_PROG_ETYPE_NOSUPP, N_("kdf params not NULL or the NULL-type", "")); return KRB5_PROG_ETYPE_NOSUPP; } et = _krb5_find_enctype(enctype); if(et == NULL) { krb5_set_error_message(context, KRB5_PROG_ETYPE_NOSUPP, N_("encryption type %d not supported", ""), enctype); return KRB5_PROG_ETYPE_NOSUPP; } keylen = (et->keytype->bits + 7) / 8; keydata = malloc(keylen); if (keydata == NULL) return krb5_enomem(context); ret = encode_otherinfo(context, ai, client, server, enctype, as_req, pk_as_rep, ticket, &other); if (ret) { free(keydata); return ret; } m = EVP_MD_CTX_create(); if (m == NULL) { free(keydata); free(other.data); return krb5_enomem(context); } offset = 0; counter = 1; do { unsigned char cdata[4]; EVP_DigestInit_ex(m, md, NULL); _krb5_put_int(cdata, counter, 4); EVP_DigestUpdate(m, cdata, 4); EVP_DigestUpdate(m, dhdata, dhsize); EVP_DigestUpdate(m, other.data, other.length); EVP_DigestFinal_ex(m, shaoutput, NULL); memcpy((unsigned char *)keydata + offset, shaoutput, min(keylen - offset, EVP_MD_CTX_size(m))); offset += EVP_MD_CTX_size(m); counter++; } while(offset < keylen); memset(shaoutput, 0, sizeof(shaoutput)); EVP_MD_CTX_destroy(m); free(other.data); ret = krb5_random_to_key(context, enctype, keydata, keylen, key); memset(keydata, 0, sizeof(keylen)); free(keydata); return ret; } heimdal-7.5.0/lib/krb5/test_ap-req.c0000644000175000017500000001365013026237312015257 0ustar niknik/* * Copyright (c) 2006 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of KTH nor the names of its contributors may be * used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY KTH AND ITS CONTRIBUTORS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL KTH OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include #include #include #include #include #include #include static int verify_pac = 0; static int server_any = 0; static int version_flag = 0; static int help_flag = 0; static struct getargs args[] = { {"verify-pac",0, arg_flag, &verify_pac, "verify the PAC", NULL }, {"server-any",0, arg_flag, &server_any, "let server pick the principal", NULL }, {"version", 0, arg_flag, &version_flag, "print version", NULL }, {"help", 0, arg_flag, &help_flag, NULL, NULL } }; static void usage (int ret) { arg_printusage (args, sizeof(args)/sizeof(*args), NULL, "..."); exit (ret); } static void test_ap(krb5_context context, krb5_principal target, krb5_principal server, krb5_keytab keytab, krb5_ccache ccache, const krb5_flags client_flags) { krb5_error_code ret; krb5_auth_context client_ac = NULL, server_ac = NULL; krb5_data data; krb5_flags server_flags; krb5_ticket *ticket = NULL; int32_t server_seq, client_seq; ret = krb5_mk_req_exact(context, &client_ac, client_flags, target, NULL, ccache, &data); if (ret) krb5_err(context, 1, ret, "krb5_mk_req_exact"); ret = krb5_rd_req(context, &server_ac, &data, server, keytab, &server_flags, &ticket); if (ret) krb5_err(context, 1, ret, "krb5_rd_req"); if (server_flags & AP_OPTS_MUTUAL_REQUIRED) { krb5_ap_rep_enc_part *repl; krb5_data_free(&data); if ((client_flags & AP_OPTS_MUTUAL_REQUIRED) == 0) krb5_errx(context, 1, "client flag missing mutual req"); ret = krb5_mk_rep (context, server_ac, &data); if (ret) krb5_err(context, 1, ret, "krb5_mk_rep"); ret = krb5_rd_rep (context, client_ac, &data, &repl); if (ret) krb5_err(context, 1, ret, "krb5_rd_rep"); krb5_free_ap_rep_enc_part (context, repl); } else { if (client_flags & AP_OPTS_MUTUAL_REQUIRED) krb5_errx(context, 1, "server flag missing mutual req"); } krb5_auth_con_getremoteseqnumber(context, server_ac, &server_seq); krb5_auth_con_getremoteseqnumber(context, client_ac, &client_seq); if (server_seq != client_seq) krb5_errx(context, 1, "seq num differ"); krb5_auth_con_getlocalseqnumber(context, server_ac, &server_seq); krb5_auth_con_getlocalseqnumber(context, client_ac, &client_seq); if (server_seq != client_seq) krb5_errx(context, 1, "seq num differ"); krb5_data_free(&data); krb5_auth_con_free(context, client_ac); krb5_auth_con_free(context, server_ac); if (verify_pac) { krb5_pac pac; ret = krb5_ticket_get_authorization_data_type(context, ticket, KRB5_AUTHDATA_WIN2K_PAC, &data); if (ret) krb5_err(context, 1, ret, "get pac"); ret = krb5_pac_parse(context, data.data, data.length, &pac); if (ret) krb5_err(context, 1, ret, "pac parse"); krb5_pac_free(context, pac); } krb5_free_ticket(context, ticket); } int main(int argc, char **argv) { krb5_context context; krb5_error_code ret; int optidx = 0; const char *principal, *keytab, *ccache; krb5_ccache id; krb5_keytab kt; krb5_principal sprincipal, server; setprogname(argv[0]); if(getarg(args, sizeof(args) / sizeof(args[0]), argc, argv, &optidx)) usage(1); if (help_flag) usage (0); if(version_flag){ print_version(NULL); exit(0); } argc -= optidx; argv += optidx; if (argc < 3) usage(1); principal = argv[0]; keytab = argv[1]; ccache = argv[2]; ret = krb5_init_context(&context); if (ret) errx (1, "krb5_init_context failed: %d", ret); ret = krb5_cc_resolve(context, ccache, &id); if (ret) krb5_err(context, 1, ret, "krb5_cc_resolve"); ret = krb5_parse_name(context, principal, &sprincipal); if (ret) krb5_err(context, 1, ret, "krb5_parse_name"); ret = krb5_kt_resolve(context, keytab, &kt); if (ret) krb5_err(context, 1, ret, "krb5_kt_resolve"); if (server_any) server = NULL; else server = sprincipal; test_ap(context, sprincipal, server, kt, id, 0); test_ap(context, sprincipal, server, kt, id, AP_OPTS_MUTUAL_REQUIRED); krb5_cc_close(context, id); krb5_kt_close(context, kt); krb5_free_principal(context, sprincipal); krb5_free_context(context); return ret; } heimdal-7.5.0/lib/krb5/krb5_set_password.30000644000175000017500000001015412136107750016412 0ustar niknik.\" Copyright (c) 2003 - 2004 Kungliga Tekniska Högskolan .\" (Royal Institute of Technology, Stockholm, Sweden). .\" All rights reserved. .\" .\" Redistribution and use in source and binary forms, with or without .\" modification, are permitted provided that the following conditions .\" are met: .\" .\" 1. Redistributions of source code must retain the above copyright .\" notice, this list of conditions and the following disclaimer. .\" .\" 2. Redistributions in binary form must reproduce the above copyright .\" notice, this list of conditions and the following disclaimer in the .\" documentation and/or other materials provided with the distribution. .\" .\" 3. Neither the name of the Institute nor the names of its contributors .\" may be used to endorse or promote products derived from this software .\" without specific prior written permission. .\" .\" THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND .\" ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE .\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE .\" ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE .\" FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL .\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS .\" OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) .\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT .\" LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF .\" SUCH DAMAGE. .\" .\" $Id$ .\" .Dd July 15, 2004 .Dt KRB5_SET_PASSWORD 3 .Os HEIMDAL .Sh NAME .Nm krb5_change_password , .Nm krb5_set_password , .Nm krb5_set_password_using_ccache , .Nm krb5_passwd_result_to_string .Nd change password functions .Sh LIBRARY Kerberos 5 Library (libkrb5, -lkrb5) .Sh SYNOPSIS .In krb5.h .Ft krb5_error_code .Fo krb5_change_password .Fa "krb5_context context" .Fa "krb5_creds *creds" .Fa "char *newpw" .Fa "int *result_code" .Fa "krb5_data *result_code_string" .Fa "krb5_data *result_string" .Fc .Ft krb5_error_code .Fo krb5_set_password .Fa "krb5_context context" .Fa "krb5_creds *creds" .Fa "char *newpw" .Fa "krb5_principal targprinc" .Fa "int *result_code" .Fa "krb5_data *result_code_string" .Fa "krb5_data *result_string" .Fc .Ft krb5_error_code .Fo krb5_set_password_using_ccache .Fa "krb5_context context" .Fa "krb5_ccache ccache" .Fa "char *newpw" .Fa "krb5_principal targprinc" .Fa "int *result_code" .Fa "krb5_data *result_code_string" .Fa "krb5_data *result_string" .Fc .Ft "const char *" .Fo krb5_passwd_result_to_string .Fa "krb5_context context" .Fa "int result" .Fc .Sh DESCRIPTION These functions change the password for a given principal. .Pp .Fn krb5_set_password and .Fn krb5_set_password_using_ccache are the newer of the three functions, and use a newer version of the protocol (and also fall back to the older set-password protocol if the newer protocol doesn't work). .Pp .Fn krb5_change_password sets the password .Fa newpasswd for the client principal in .Fa creds . The server principal of creds must be .Li kadmin/changepw . .Pp .Fn krb5_set_password and .Fn krb5_set_password_using_ccache change the password for the principal .Fa targprinc . .Pp .Fn krb5_set_password requires that the credential for .Li kadmin/changepw@REALM is in .Fa creds . If the user caller isn't an administrator, this credential needs to be an initial credential, see .Xr krb5_get_init_creds 3 how to get such credentials. .Pp .Fn krb5_set_password_using_ccache will get the credential from .Fa ccache . .Pp If .Fa targprinc is .Dv NULL , .Fn krb5_set_password_using_ccache uses the the default principal in .Fa ccache and .Fn krb5_set_password uses the global the default principal. .Pp All three functions return an error in .Fa result_code and maybe an error string to print in .Fa result_string . .Pp .Fn krb5_passwd_result_to_string returns an human readable string describing the error code in .Fa result_code from the .Fn krb5_set_password functions. .Sh SEE ALSO .Xr krb5_ccache 3 , .Xr krb5_init_context 3 heimdal-7.5.0/lib/krb5/kcm.c0000644000175000017500000006447613212137553013624 0ustar niknik/* * Copyright (c) 2005, PADL Software Pty Ltd. * All rights reserved. * * Portions Copyright (c) 2009 Apple Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of PADL Software nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY PADL SOFTWARE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL PADL SOFTWARE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "krb5_locl.h" #ifdef HAVE_KCM /* * Client library for Kerberos Credentials Manager (KCM) daemon */ #include "kcm.h" #include static krb5_error_code kcm_set_kdc_offset(krb5_context, krb5_ccache, krb5_deltat); static const char *kcm_ipc_name = "ANY:org.h5l.kcm"; typedef struct krb5_kcmcache { char *name; } krb5_kcmcache; typedef struct krb5_kcm_cursor { unsigned long offset; unsigned long length; kcmuuid_t *uuids; } *krb5_kcm_cursor; #define KCMCACHE(X) ((krb5_kcmcache *)(X)->data.data) #define CACHENAME(X) (KCMCACHE(X)->name) #define KCMCURSOR(C) ((krb5_kcm_cursor)(C)) static HEIMDAL_MUTEX kcm_mutex = HEIMDAL_MUTEX_INITIALIZER; static heim_ipc kcm_ipc = NULL; static krb5_error_code kcm_send_request(krb5_context context, krb5_storage *request, krb5_data *response_data) { krb5_error_code ret = 0; krb5_data request_data; HEIMDAL_MUTEX_lock(&kcm_mutex); if (kcm_ipc == NULL) ret = heim_ipc_init_context(kcm_ipc_name, &kcm_ipc); HEIMDAL_MUTEX_unlock(&kcm_mutex); if (ret) return KRB5_CC_NOSUPP; ret = krb5_storage_to_data(request, &request_data); if (ret) { krb5_clear_error_message(context); return KRB5_CC_NOMEM; } ret = heim_ipc_call(kcm_ipc, &request_data, response_data, NULL); krb5_data_free(&request_data); if (ret) { krb5_clear_error_message(context); ret = KRB5_CC_NOSUPP; } return ret; } KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_kcm_storage_request(krb5_context context, uint16_t opcode, krb5_storage **storage_p) { krb5_storage *sp; krb5_error_code ret; *storage_p = NULL; sp = krb5_storage_emem(); if (sp == NULL) { krb5_set_error_message(context, KRB5_CC_NOMEM, N_("malloc: out of memory", "")); return KRB5_CC_NOMEM; } /* Send MAJOR | VERSION | OPCODE */ ret = krb5_store_int8(sp, KCM_PROTOCOL_VERSION_MAJOR); if (ret) goto fail; ret = krb5_store_int8(sp, KCM_PROTOCOL_VERSION_MINOR); if (ret) goto fail; ret = krb5_store_int16(sp, opcode); if (ret) goto fail; *storage_p = sp; fail: if (ret) { krb5_set_error_message(context, ret, N_("Failed to encode KCM request", "")); krb5_storage_free(sp); } return ret; } static krb5_error_code kcm_alloc(krb5_context context, const char *name, krb5_ccache *id) { krb5_kcmcache *k; k = malloc(sizeof(*k)); if (k == NULL) { krb5_set_error_message(context, KRB5_CC_NOMEM, N_("malloc: out of memory", "")); return KRB5_CC_NOMEM; } if (name != NULL) { k->name = strdup(name); if (k->name == NULL) { free(k); krb5_set_error_message(context, KRB5_CC_NOMEM, N_("malloc: out of memory", "")); return KRB5_CC_NOMEM; } } else k->name = NULL; (*id)->data.data = k; (*id)->data.length = sizeof(*k); return 0; } KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_kcm_call(krb5_context context, krb5_storage *request, krb5_storage **response_p, krb5_data *response_data_p) { krb5_data response_data; krb5_error_code ret; int32_t status; krb5_storage *response; if (response_p != NULL) *response_p = NULL; krb5_data_zero(&response_data); ret = kcm_send_request(context, request, &response_data); if (ret) return ret; response = krb5_storage_from_data(&response_data); if (response == NULL) { krb5_data_free(&response_data); return KRB5_CC_IO; } ret = krb5_ret_int32(response, &status); if (ret) { krb5_storage_free(response); krb5_data_free(&response_data); return KRB5_CC_FORMAT; } if (status) { krb5_storage_free(response); krb5_data_free(&response_data); return status; } if (response_p != NULL) { *response_data_p = response_data; *response_p = response; return 0; } krb5_storage_free(response); krb5_data_free(&response_data); return 0; } static void kcm_free(krb5_context context, krb5_ccache *id) { krb5_kcmcache *k = KCMCACHE(*id); if (k != NULL) { if (k->name != NULL) free(k->name); memset(k, 0, sizeof(*k)); krb5_data_free(&(*id)->data); } } static const char * kcm_get_name(krb5_context context, krb5_ccache id) { return CACHENAME(id); } static krb5_error_code kcm_resolve(krb5_context context, krb5_ccache *id, const char *res) { return kcm_alloc(context, res, id); } /* * Request: * * Response: * NameZ */ static krb5_error_code kcm_gen_new(krb5_context context, krb5_ccache *id) { krb5_kcmcache *k; krb5_error_code ret; krb5_storage *request, *response; krb5_data response_data; ret = kcm_alloc(context, NULL, id); if (ret) return ret; k = KCMCACHE(*id); ret = krb5_kcm_storage_request(context, KCM_OP_GEN_NEW, &request); if (ret) { kcm_free(context, id); return ret; } ret = krb5_kcm_call(context, request, &response, &response_data); if (ret) { krb5_storage_free(request); kcm_free(context, id); return ret; } ret = krb5_ret_stringz(response, &k->name); if (ret) ret = KRB5_CC_IO; krb5_storage_free(request); krb5_storage_free(response); krb5_data_free(&response_data); if (ret) kcm_free(context, id); return ret; } /* * Request: * NameZ * Principal * * Response: * */ static krb5_error_code kcm_initialize(krb5_context context, krb5_ccache id, krb5_principal primary_principal) { krb5_error_code ret; krb5_kcmcache *k = KCMCACHE(id); krb5_storage *request; ret = krb5_kcm_storage_request(context, KCM_OP_INITIALIZE, &request); if (ret) return ret; ret = krb5_store_stringz(request, k->name); if (ret) { krb5_storage_free(request); return ret; } ret = krb5_store_principal(request, primary_principal); if (ret) { krb5_storage_free(request); return ret; } ret = krb5_kcm_call(context, request, NULL, NULL); krb5_storage_free(request); if (context->kdc_sec_offset) kcm_set_kdc_offset(context, id, context->kdc_sec_offset); return ret; } static krb5_error_code kcm_close(krb5_context context, krb5_ccache id) { kcm_free(context, &id); return 0; } /* * Request: * NameZ * * Response: * */ static krb5_error_code kcm_destroy(krb5_context context, krb5_ccache id) { krb5_error_code ret; krb5_kcmcache *k = KCMCACHE(id); krb5_storage *request; ret = krb5_kcm_storage_request(context, KCM_OP_DESTROY, &request); if (ret) return ret; ret = krb5_store_stringz(request, k->name); if (ret) { krb5_storage_free(request); return ret; } ret = krb5_kcm_call(context, request, NULL, NULL); krb5_storage_free(request); return ret; } /* * Request: * NameZ * Creds * * Response: * */ static krb5_error_code kcm_store_cred(krb5_context context, krb5_ccache id, krb5_creds *creds) { krb5_error_code ret; krb5_kcmcache *k = KCMCACHE(id); krb5_storage *request; ret = krb5_kcm_storage_request(context, KCM_OP_STORE, &request); if (ret) return ret; ret = krb5_store_stringz(request, k->name); if (ret) { krb5_storage_free(request); return ret; } ret = krb5_store_creds(request, creds); if (ret) { krb5_storage_free(request); return ret; } ret = krb5_kcm_call(context, request, NULL, NULL); krb5_storage_free(request); return ret; } #if 0 /* * Request: * NameZ * WhichFields * MatchCreds * * Response: * Creds * */ static krb5_error_code kcm_retrieve(krb5_context context, krb5_ccache id, krb5_flags which, const krb5_creds *mcred, krb5_creds *creds) { krb5_error_code ret; krb5_kcmcache *k = KCMCACHE(id); krb5_storage *request, *response; krb5_data response_data; ret = krb5_kcm_storage_request(context, KCM_OP_RETRIEVE, &request); if (ret) return ret; ret = krb5_store_stringz(request, k->name); if (ret) { krb5_storage_free(request); return ret; } ret = krb5_store_int32(request, which); if (ret) { krb5_storage_free(request); return ret; } ret = krb5_store_creds_tag(request, rk_UNCONST(mcred)); if (ret) { krb5_storage_free(request); return ret; } ret = krb5_kcm_call(context, request, &response, &response_data); if (ret) { krb5_storage_free(request); return ret; } ret = krb5_ret_creds(response, creds); if (ret) ret = KRB5_CC_IO; krb5_storage_free(request); krb5_storage_free(response); krb5_data_free(&response_data); return ret; } #endif /* * Request: * NameZ * * Response: * Principal */ static krb5_error_code kcm_get_principal(krb5_context context, krb5_ccache id, krb5_principal *principal) { krb5_error_code ret; krb5_kcmcache *k = KCMCACHE(id); krb5_storage *request, *response; krb5_data response_data; ret = krb5_kcm_storage_request(context, KCM_OP_GET_PRINCIPAL, &request); if (ret) return ret; ret = krb5_store_stringz(request, k->name); if (ret) { krb5_storage_free(request); return ret; } ret = krb5_kcm_call(context, request, &response, &response_data); if (ret) { krb5_storage_free(request); return ret; } ret = krb5_ret_principal(response, principal); if (ret) ret = KRB5_CC_IO; krb5_storage_free(request); krb5_storage_free(response); krb5_data_free(&response_data); return ret; } /* * Request: * NameZ * * Response: * Cursor * */ static krb5_error_code kcm_get_first (krb5_context context, krb5_ccache id, krb5_cc_cursor *cursor) { krb5_error_code ret; krb5_kcm_cursor c; krb5_kcmcache *k = KCMCACHE(id); krb5_storage *request, *response; krb5_data response_data; ret = krb5_kcm_storage_request(context, KCM_OP_GET_CRED_UUID_LIST, &request); if (ret) return ret; ret = krb5_store_stringz(request, k->name); if (ret) { krb5_storage_free(request); return ret; } ret = krb5_kcm_call(context, request, &response, &response_data); krb5_storage_free(request); if (ret) return ret; c = calloc(1, sizeof(*c)); if (c == NULL) { ret = krb5_enomem(context); return ret; } while (1) { ssize_t sret; kcmuuid_t uuid; void *ptr; sret = krb5_storage_read(response, &uuid, sizeof(uuid)); if (sret == 0) { ret = 0; break; } else if (sret != sizeof(uuid)) { ret = EINVAL; break; } ptr = realloc(c->uuids, sizeof(c->uuids[0]) * (c->length + 1)); if (ptr == NULL) { free(c->uuids); free(c); return krb5_enomem(context); } c->uuids = ptr; memcpy(&c->uuids[c->length], &uuid, sizeof(uuid)); c->length += 1; } krb5_storage_free(response); krb5_data_free(&response_data); if (ret) { free(c->uuids); free(c); return ret; } *cursor = c; return 0; } /* * Request: * NameZ * Cursor * * Response: * Creds */ static krb5_error_code kcm_get_next (krb5_context context, krb5_ccache id, krb5_cc_cursor *cursor, krb5_creds *creds) { krb5_error_code ret; krb5_kcmcache *k = KCMCACHE(id); krb5_kcm_cursor c = KCMCURSOR(*cursor); krb5_storage *request, *response; krb5_data response_data; ssize_t sret; again: if (c->offset >= c->length) return KRB5_CC_END; ret = krb5_kcm_storage_request(context, KCM_OP_GET_CRED_BY_UUID, &request); if (ret) return ret; ret = krb5_store_stringz(request, k->name); if (ret) { krb5_storage_free(request); return ret; } sret = krb5_storage_write(request, &c->uuids[c->offset], sizeof(c->uuids[c->offset])); c->offset++; if (sret != sizeof(c->uuids[c->offset])) { krb5_storage_free(request); krb5_clear_error_message(context); return ENOMEM; } ret = krb5_kcm_call(context, request, &response, &response_data); krb5_storage_free(request); if (ret == KRB5_CC_END) { goto again; } ret = krb5_ret_creds(response, creds); if (ret) ret = KRB5_CC_IO; krb5_storage_free(response); krb5_data_free(&response_data); return ret; } /* * Request: * NameZ * Cursor * * Response: * */ static krb5_error_code kcm_end_get (krb5_context context, krb5_ccache id, krb5_cc_cursor *cursor) { krb5_kcm_cursor c = KCMCURSOR(*cursor); free(c->uuids); free(c); *cursor = NULL; return 0; } /* * Request: * NameZ * WhichFields * MatchCreds * * Response: * */ static krb5_error_code kcm_remove_cred(krb5_context context, krb5_ccache id, krb5_flags which, krb5_creds *cred) { krb5_error_code ret; krb5_kcmcache *k = KCMCACHE(id); krb5_storage *request; ret = krb5_kcm_storage_request(context, KCM_OP_REMOVE_CRED, &request); if (ret) return ret; ret = krb5_store_stringz(request, k->name); if (ret) { krb5_storage_free(request); return ret; } ret = krb5_store_int32(request, which); if (ret) { krb5_storage_free(request); return ret; } ret = krb5_store_creds_tag(request, cred); if (ret) { krb5_storage_free(request); return ret; } ret = krb5_kcm_call(context, request, NULL, NULL); krb5_storage_free(request); return ret; } static krb5_error_code kcm_set_flags(krb5_context context, krb5_ccache id, krb5_flags flags) { krb5_error_code ret; krb5_kcmcache *k = KCMCACHE(id); krb5_storage *request; ret = krb5_kcm_storage_request(context, KCM_OP_SET_FLAGS, &request); if (ret) return ret; ret = krb5_store_stringz(request, k->name); if (ret) { krb5_storage_free(request); return ret; } ret = krb5_store_int32(request, flags); if (ret) { krb5_storage_free(request); return ret; } ret = krb5_kcm_call(context, request, NULL, NULL); krb5_storage_free(request); return ret; } static int kcm_get_version(krb5_context context, krb5_ccache id) { return 0; } /* * Send nothing * get back list of uuids */ static krb5_error_code kcm_get_cache_first(krb5_context context, krb5_cc_cursor *cursor) { krb5_error_code ret; krb5_kcm_cursor c; krb5_storage *request, *response; krb5_data response_data; *cursor = NULL; c = calloc(1, sizeof(*c)); if (c == NULL) { ret = krb5_enomem(context); goto out; } ret = krb5_kcm_storage_request(context, KCM_OP_GET_CACHE_UUID_LIST, &request); if (ret) goto out; ret = krb5_kcm_call(context, request, &response, &response_data); krb5_storage_free(request); if (ret) goto out; while (1) { ssize_t sret; kcmuuid_t uuid; void *ptr; sret = krb5_storage_read(response, &uuid, sizeof(uuid)); if (sret == 0) { ret = 0; break; } else if (sret != sizeof(uuid)) { ret = EINVAL; goto out; } ptr = realloc(c->uuids, sizeof(c->uuids[0]) * (c->length + 1)); if (ptr == NULL) { ret = krb5_enomem(context); goto out; } c->uuids = ptr; memcpy(&c->uuids[c->length], &uuid, sizeof(uuid)); c->length += 1; } krb5_storage_free(response); krb5_data_free(&response_data); out: if (ret && c) { free(c->uuids); free(c); } else *cursor = c; return ret; } /* * Send uuid * Recv cache name */ static krb5_error_code kcm_get_cache_next(krb5_context context, krb5_cc_cursor cursor, const krb5_cc_ops *ops, krb5_ccache *id) { krb5_error_code ret; krb5_kcm_cursor c = KCMCURSOR(cursor); krb5_storage *request, *response; krb5_data response_data; ssize_t sret; char *name; *id = NULL; again: if (c->offset >= c->length) return KRB5_CC_END; ret = krb5_kcm_storage_request(context, KCM_OP_GET_CACHE_BY_UUID, &request); if (ret) return ret; sret = krb5_storage_write(request, &c->uuids[c->offset], sizeof(c->uuids[c->offset])); c->offset++; if (sret != sizeof(c->uuids[c->offset])) { krb5_storage_free(request); krb5_clear_error_message(context); return ENOMEM; } ret = krb5_kcm_call(context, request, &response, &response_data); krb5_storage_free(request); if (ret == KRB5_CC_END) goto again; ret = krb5_ret_stringz(response, &name); krb5_storage_free(response); krb5_data_free(&response_data); if (ret == 0) { ret = _krb5_cc_allocate(context, ops, id); if (ret == 0) ret = kcm_alloc(context, name, id); krb5_xfree(name); } return ret; } static krb5_error_code kcm_get_cache_next_kcm(krb5_context context, krb5_cc_cursor cursor, krb5_ccache *id) { #ifndef KCM_IS_API_CACHE return kcm_get_cache_next(context, cursor, &krb5_kcm_ops, id); #else return KRB5_CC_END; #endif } static krb5_error_code kcm_get_cache_next_api(krb5_context context, krb5_cc_cursor cursor, krb5_ccache *id) { return kcm_get_cache_next(context, cursor, &krb5_akcm_ops, id); } static krb5_error_code kcm_end_cache_get(krb5_context context, krb5_cc_cursor cursor) { krb5_kcm_cursor c = KCMCURSOR(cursor); free(c->uuids); free(c); return 0; } static krb5_error_code kcm_move(krb5_context context, krb5_ccache from, krb5_ccache to) { krb5_error_code ret; krb5_kcmcache *oldk = KCMCACHE(from); krb5_kcmcache *newk = KCMCACHE(to); krb5_storage *request; ret = krb5_kcm_storage_request(context, KCM_OP_MOVE_CACHE, &request); if (ret) return ret; ret = krb5_store_stringz(request, oldk->name); if (ret) { krb5_storage_free(request); return ret; } ret = krb5_store_stringz(request, newk->name); if (ret) { krb5_storage_free(request); return ret; } ret = krb5_kcm_call(context, request, NULL, NULL); krb5_storage_free(request); return ret; } static krb5_error_code kcm_get_default_name(krb5_context context, const krb5_cc_ops *ops, const char *defstr, char **str) { krb5_error_code ret; krb5_storage *request, *response; krb5_data response_data; char *name; int aret; *str = NULL; ret = krb5_kcm_storage_request(context, KCM_OP_GET_DEFAULT_CACHE, &request); if (ret) return ret; ret = krb5_kcm_call(context, request, &response, &response_data); krb5_storage_free(request); if (ret) return _krb5_expand_default_cc_name(context, defstr, str); ret = krb5_ret_stringz(response, &name); krb5_storage_free(response); krb5_data_free(&response_data); if (ret) return ret; aret = asprintf(str, "%s:%s", ops->prefix, name); free(name); if (aret == -1 || str == NULL) return ENOMEM; return 0; } static krb5_error_code kcm_get_default_name_api(krb5_context context, char **str) { return kcm_get_default_name(context, &krb5_akcm_ops, KRB5_DEFAULT_CCNAME_KCM_API, str); } static krb5_error_code kcm_get_default_name_kcm(krb5_context context, char **str) { return kcm_get_default_name(context, &krb5_kcm_ops, KRB5_DEFAULT_CCNAME_KCM_KCM, str); } static krb5_error_code kcm_set_default(krb5_context context, krb5_ccache id) { krb5_error_code ret; krb5_storage *request; krb5_kcmcache *k = KCMCACHE(id); ret = krb5_kcm_storage_request(context, KCM_OP_SET_DEFAULT_CACHE, &request); if (ret) return ret; ret = krb5_store_stringz(request, k->name); if (ret) { krb5_storage_free(request); return ret; } ret = krb5_kcm_call(context, request, NULL, NULL); krb5_storage_free(request); return ret; } static krb5_error_code kcm_lastchange(krb5_context context, krb5_ccache id, krb5_timestamp *mtime) { *mtime = time(NULL); return 0; } static krb5_error_code kcm_set_kdc_offset(krb5_context context, krb5_ccache id, krb5_deltat kdc_offset) { krb5_kcmcache *k = KCMCACHE(id); krb5_error_code ret; krb5_storage *request; ret = krb5_kcm_storage_request(context, KCM_OP_SET_KDC_OFFSET, &request); if (ret) return ret; ret = krb5_store_stringz(request, k->name); if (ret) { krb5_storage_free(request); return ret; } ret = krb5_store_int32(request, kdc_offset); if (ret) { krb5_storage_free(request); return ret; } ret = krb5_kcm_call(context, request, NULL, NULL); krb5_storage_free(request); return ret; } static krb5_error_code kcm_get_kdc_offset(krb5_context context, krb5_ccache id, krb5_deltat *kdc_offset) { krb5_kcmcache *k = KCMCACHE(id); krb5_error_code ret; krb5_storage *request, *response; krb5_data response_data; int32_t offset; ret = krb5_kcm_storage_request(context, KCM_OP_GET_KDC_OFFSET, &request); if (ret) return ret; ret = krb5_store_stringz(request, k->name); if (ret) { krb5_storage_free(request); return ret; } ret = krb5_kcm_call(context, request, &response, &response_data); krb5_storage_free(request); if (ret) return ret; ret = krb5_ret_int32(response, &offset); krb5_storage_free(response); krb5_data_free(&response_data); if (ret) return ret; *kdc_offset = offset; return 0; } /** * Variable containing the KCM based credential cache implemention. * * @ingroup krb5_ccache */ KRB5_LIB_VARIABLE const krb5_cc_ops krb5_kcm_ops = { KRB5_CC_OPS_VERSION, "KCM", kcm_get_name, kcm_resolve, kcm_gen_new, kcm_initialize, kcm_destroy, kcm_close, kcm_store_cred, NULL /* kcm_retrieve */, kcm_get_principal, kcm_get_first, kcm_get_next, kcm_end_get, kcm_remove_cred, kcm_set_flags, kcm_get_version, kcm_get_cache_first, kcm_get_cache_next_kcm, kcm_end_cache_get, kcm_move, kcm_get_default_name_kcm, kcm_set_default, kcm_lastchange, kcm_set_kdc_offset, kcm_get_kdc_offset }; KRB5_LIB_VARIABLE const krb5_cc_ops krb5_akcm_ops = { KRB5_CC_OPS_VERSION, "API", kcm_get_name, kcm_resolve, kcm_gen_new, kcm_initialize, kcm_destroy, kcm_close, kcm_store_cred, NULL /* kcm_retrieve */, kcm_get_principal, kcm_get_first, kcm_get_next, kcm_end_get, kcm_remove_cred, kcm_set_flags, kcm_get_version, kcm_get_cache_first, kcm_get_cache_next_api, kcm_end_cache_get, kcm_move, kcm_get_default_name_api, kcm_set_default, kcm_lastchange, NULL, NULL }; KRB5_LIB_FUNCTION krb5_boolean KRB5_LIB_CALL _krb5_kcm_is_running(krb5_context context) { krb5_error_code ret; krb5_ccache_data ccdata; krb5_ccache id = &ccdata; krb5_boolean running; ret = kcm_alloc(context, NULL, &id); if (ret) return 0; running = (_krb5_kcm_noop(context, id) == 0); kcm_free(context, &id); return running; } /* * Request: * * Response: * */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL _krb5_kcm_noop(krb5_context context, krb5_ccache id) { krb5_error_code ret; krb5_storage *request; ret = krb5_kcm_storage_request(context, KCM_OP_NOOP, &request); if (ret) return ret; ret = krb5_kcm_call(context, request, NULL, NULL); krb5_storage_free(request); return ret; } /* * Request: * NameZ * ServerPrincipalPresent * ServerPrincipal OPTIONAL * Key * * Repsonse: * */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL _krb5_kcm_get_initial_ticket(krb5_context context, krb5_ccache id, krb5_principal server, krb5_keyblock *key) { krb5_kcmcache *k = KCMCACHE(id); krb5_error_code ret; krb5_storage *request; ret = krb5_kcm_storage_request(context, KCM_OP_GET_INITIAL_TICKET, &request); if (ret) return ret; ret = krb5_store_stringz(request, k->name); if (ret) { krb5_storage_free(request); return ret; } ret = krb5_store_int8(request, (server == NULL) ? 0 : 1); if (ret) { krb5_storage_free(request); return ret; } if (server != NULL) { ret = krb5_store_principal(request, server); if (ret) { krb5_storage_free(request); return ret; } } ret = krb5_store_keyblock(request, *key); if (ret) { krb5_storage_free(request); return ret; } ret = krb5_kcm_call(context, request, NULL, NULL); krb5_storage_free(request); return ret; } /* * Request: * NameZ * KDCFlags * EncryptionType * ServerPrincipal * * Repsonse: * */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL _krb5_kcm_get_ticket(krb5_context context, krb5_ccache id, krb5_kdc_flags flags, krb5_enctype enctype, krb5_principal server) { krb5_error_code ret; krb5_kcmcache *k = KCMCACHE(id); krb5_storage *request; ret = krb5_kcm_storage_request(context, KCM_OP_GET_TICKET, &request); if (ret) return ret; ret = krb5_store_stringz(request, k->name); if (ret) { krb5_storage_free(request); return ret; } ret = krb5_store_int32(request, flags.i); if (ret) { krb5_storage_free(request); return ret; } ret = krb5_store_int32(request, enctype); if (ret) { krb5_storage_free(request); return ret; } ret = krb5_store_principal(request, server); if (ret) { krb5_storage_free(request); return ret; } ret = krb5_kcm_call(context, request, NULL, NULL); krb5_storage_free(request); return ret; } #endif /* HAVE_KCM */ heimdal-7.5.0/lib/krb5/krb5_locl.h0000644000175000017500000002275513212137553014725 0ustar niknik/* * Copyright (c) 1997-2016 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Portions Copyright (c) 2009 Apple Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ /* $Id$ */ #ifndef __KRB5_LOCL_H__ #define __KRB5_LOCL_H__ #include #include #include #ifdef HAVE_POLL_H #include #endif #include #ifdef HAVE_SYS_TYPES_H #include #endif #ifdef HAVE_SYS_MMAN_H #include #endif #if defined(HAVE_SYS_IOCTL_H) && SunOS != 40 #include #endif #ifdef HAVE_PWD_H #undef _POSIX_PTHREAD_SEMANTICS /* This gets us the 5-arg getpwnam_r on Solaris 9. */ #define _POSIX_PTHREAD_SEMANTICS #include #endif #ifdef HAVE_SYS_SELECT_H #include #endif #ifdef _AIX struct mbuf; #endif #ifdef HAVE_SYS_FILIO_H #include #endif #ifdef HAVE_SYS_FILE_H #include #endif #include #include #define HEIMDAL_TEXTDOMAIN "heimdal_krb5" #ifdef LIBINTL #include #define N_(x,y) dgettext(HEIMDAL_TEXTDOMAIN, x) #else #define N_(x,y) (x) #define bindtextdomain(package, localedir) #endif #ifdef HAVE_CRYPT_H #undef des_encrypt #define des_encrypt wingless_pigs_mostly_fail_to_fly #include #undef des_encrypt #endif #ifdef HAVE_DOOR_CREATE #include #endif #include #include #include /* * We use OpenSSL for EC, but to do this we need to disable cross-references * between OpenSSL and hcrypto bn.h and such. Source files that use OpenSSL EC * must define HEIM_NO_CRYPTO_HDRS before including this file. */ #define HC_DEPRECATED_CRYPTO #ifndef HEIM_NO_CRYPTO_HDRS #include "crypto-headers.h" #endif #include #include struct send_to_kdc; /* XXX glue for pkinit */ struct hx509_certs_data; struct krb5_pk_identity; struct krb5_pk_cert; struct ContentInfo; struct AlgorithmIdentifier; typedef struct krb5_pk_init_ctx_data *krb5_pk_init_ctx; struct krb5_dh_moduli; /* v4 glue */ struct _krb5_krb_auth_data; #include #include #include #include #ifdef PKINIT #include #endif #include "crypto.h" #include #include "heim_threads.h" #define ALLOC(X, N) (X) = calloc((N), sizeof(*(X))) #define ALLOC_SEQ(X, N) do { (X)->len = (N); ALLOC((X)->val, (N)); } while(0) #ifndef __func__ #define __func__ "unknown-function" #endif #define krb5_einval(context, argnum) _krb5_einval((context), __func__, (argnum)) #ifndef PATH_SEP #define PATH_SEP ":" #endif /* should this be public? */ #define KEYTAB_DEFAULT "FILE:" SYSCONFDIR "/krb5.keytab" #define KEYTAB_DEFAULT_MODIFY "FILE:" SYSCONFDIR "/krb5.keytab" #define MODULI_FILE SYSCONFDIR "/krb5.moduli" #ifndef O_BINARY #define O_BINARY 0 #endif #ifndef O_CLOEXEC #define O_CLOEXEC 0 #endif #ifndef SOCK_CLOEXEC #define SOCK_CLOEXEC 0 #endif #define KRB5_BUFSIZ 2048 typedef enum { KRB5_INIT_CREDS_TRISTATE_UNSET = 0, KRB5_INIT_CREDS_TRISTATE_TRUE, KRB5_INIT_CREDS_TRISTATE_FALSE } krb5_get_init_creds_tristate; struct _krb5_get_init_creds_opt_private { int refcount; /* ENC_TIMESTAMP */ const char *password; krb5_s2k_proc key_proc; /* PA_PAC_REQUEST */ krb5_get_init_creds_tristate req_pac; /* PKINIT */ krb5_pk_init_ctx pk_init_ctx; krb5_get_init_creds_tristate addressless; int flags; #define KRB5_INIT_CREDS_CANONICALIZE 1 #define KRB5_INIT_CREDS_NO_C_CANON_CHECK 2 #define KRB5_INIT_CREDS_NO_C_NO_EKU_CHECK 4 struct { krb5_gic_process_last_req func; void *ctx; } lr; }; typedef uint32_t krb5_enctype_set; typedef struct krb5_context_data { krb5_enctype *etypes; krb5_enctype *cfg_etypes; krb5_enctype *etypes_des;/* deprecated */ krb5_enctype *as_etypes; krb5_enctype *tgs_etypes; krb5_enctype *permitted_enctypes; char **default_realms; time_t max_skew; time_t kdc_timeout; time_t host_timeout; unsigned max_retries; int32_t kdc_sec_offset; int32_t kdc_usec_offset; krb5_config_section *cf; struct et_list *et_list; struct krb5_log_facility *warn_dest; struct krb5_log_facility *debug_dest; const krb5_cc_ops **cc_ops; int num_cc_ops; const char *http_proxy; const char *time_fmt; krb5_boolean log_utc; const char *default_keytab; const char *default_keytab_modify; krb5_boolean use_admin_kdc; krb5_addresses *extra_addresses; krb5_boolean scan_interfaces; /* `ifconfig -a' */ krb5_boolean srv_lookup; /* do SRV lookups */ krb5_boolean srv_try_txt; /* try TXT records also */ int32_t fcache_vno; /* create cache files w/ this version */ int num_kt_types; /* # of registered keytab types */ struct krb5_keytab_data *kt_types; /* registered keytab types */ const char *date_fmt; char *error_string; krb5_error_code error_code; krb5_addresses *ignore_addresses; char *default_cc_name; char *default_cc_name_env; int default_cc_name_set; HEIMDAL_MUTEX mutex; /* protects error_string */ int large_msg_size; int max_msg_size; int tgs_negative_timeout; /* timeout for TGS negative cache */ int flags; #define KRB5_CTX_F_DNS_CANONICALIZE_HOSTNAME 1 #define KRB5_CTX_F_CHECK_PAC 2 #define KRB5_CTX_F_HOMEDIR_ACCESS 4 #define KRB5_CTX_F_SOCKETS_INITIALIZED 8 #define KRB5_CTX_F_RD_REQ_IGNORE 16 #define KRB5_CTX_F_FCACHE_STRICT_CHECKING 32 struct send_to_kdc *send_to_kdc; #ifdef PKINIT hx509_context hx509ctx; #endif unsigned int num_kdc_requests; krb5_name_canon_rule name_canon_rules; } krb5_context_data; #ifndef KRB5_USE_PATH_TOKENS #define KRB5_DEFAULT_CCNAME_FILE "FILE:/tmp/krb5cc_%{uid}" #define KRB5_DEFAULT_CCNAME_DIR "DIR:/tmp/krb5cc_%{uid}_dir/" #else #define KRB5_DEFAULT_CCNAME_FILE "FILE:%{TEMP}/krb5cc_%{uid}" #define KRB5_DEFAULT_CCNAME_DIR "DIR:%{TEMP}/krb5cc_%{uid}_dir/" #endif #define KRB5_DEFAULT_CCNAME_API "API:" #define KRB5_DEFAULT_CCNAME_KCM_KCM "KCM:%{uid}" #define KRB5_DEFAULT_CCNAME_KCM_API "API:%{uid}" #define EXTRACT_TICKET_ALLOW_CNAME_MISMATCH 1 #define EXTRACT_TICKET_ALLOW_SERVER_MISMATCH 2 #define EXTRACT_TICKET_MATCH_REALM 4 #define EXTRACT_TICKET_AS_REQ 8 #define EXTRACT_TICKET_TIMESYNC 16 /* * Configurable options */ #ifndef KRB5_DEFAULT_CCTYPE #ifdef __APPLE__ #define KRB5_DEFAULT_CCTYPE (&krb5_acc_ops) #else #define KRB5_DEFAULT_CCTYPE (&krb5_fcc_ops) #endif #endif #ifndef KRB5_ADDRESSLESS_DEFAULT #define KRB5_ADDRESSLESS_DEFAULT TRUE #endif #ifndef KRB5_FORWARDABLE_DEFAULT #define KRB5_FORWARDABLE_DEFAULT TRUE #endif #ifndef KRB5_CONFIGURATION_CHANGE_NOTIFY_NAME #define KRB5_CONFIGURATION_CHANGE_NOTIFY_NAME "org.h5l.Kerberos.configuration-changed" #endif #ifndef KRB5_FALLBACK_DEFAULT #define KRB5_FALLBACK_DEFAULT TRUE #endif #ifndef KRB5_TKT_LIFETIME_DEFAULT # define KRB5_TKT_LIFETIME_DEFAULT 15778800 /* seconds */ #endif #ifndef KRB5_TKT_RENEW_LIFETIME_DEFAULT # define KRB5_TKT_RENEW_LIFETIME_DEFAULT 15778800 /* seconds */ #endif #ifdef PKINIT struct krb5_pk_identity { hx509_verify_ctx verify_ctx; hx509_certs certs; hx509_cert cert; hx509_certs anchors; hx509_certs certpool; hx509_revoke_ctx revokectx; int flags; #define PKINIT_BTMM 1 }; enum krb5_pk_type { PKINIT_WIN2K = 1, PKINIT_27 = 2 }; enum keyex_enum { USE_RSA, USE_DH, USE_ECDH }; struct krb5_pk_init_ctx_data { struct krb5_pk_identity *id; enum keyex_enum keyex; union { DH *dh; void *eckey; } u; krb5_data *clientDHNonce; struct krb5_dh_moduli **m; hx509_peer_info peer; enum krb5_pk_type type; unsigned int require_binding:1; unsigned int require_eku:1; unsigned int require_krbtgt_otherName:1; unsigned int require_hostname_match:1; unsigned int trustedCertifiers:1; unsigned int anonymous:1; }; #endif /* PKINIT */ #define ISTILDE(x) (x == '~') #ifdef _WIN32 # define ISPATHSEP(x) (x == '/' || x =='\\') #else # define ISPATHSEP(x) (x == '/') #endif #endif /* __KRB5_LOCL_H__ */ heimdal-7.5.0/lib/krb5/crypto-des3.c0000644000175000017500000001546013026237312015210 0ustar niknik/* * Copyright (c) 1997 - 2008 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "krb5_locl.h" /* * */ static void DES3_random_key(krb5_context context, krb5_keyblock *key) { DES_cblock *k = key->keyvalue.data; do { krb5_generate_random_block(k, 3 * sizeof(DES_cblock)); DES_set_odd_parity(&k[0]); DES_set_odd_parity(&k[1]); DES_set_odd_parity(&k[2]); } while(DES_is_weak_key(&k[0]) || DES_is_weak_key(&k[1]) || DES_is_weak_key(&k[2])); } static krb5_error_code DES3_prf(krb5_context context, krb5_crypto crypto, const krb5_data *in, krb5_data *out) { struct _krb5_checksum_type *ct = crypto->et->checksum; krb5_error_code ret; Checksum result; krb5_keyblock *derived; result.cksumtype = ct->type; ret = krb5_data_alloc(&result.checksum, ct->checksumsize); if (ret) { krb5_set_error_message(context, ret, N_("malloc: out memory", "")); return ret; } ret = (*ct->checksum)(context, NULL, in->data, in->length, 0, &result); if (ret) { krb5_data_free(&result.checksum); return ret; } if (result.checksum.length < crypto->et->blocksize) krb5_abortx(context, "internal prf error"); derived = NULL; ret = krb5_derive_key(context, crypto->key.key, crypto->et->type, "prf", 3, &derived); if (ret) krb5_abortx(context, "krb5_derive_key"); ret = krb5_data_alloc(out, crypto->et->prf_length); if (ret) krb5_abortx(context, "malloc failed"); { const EVP_CIPHER *c = (*crypto->et->keytype->evp)(); EVP_CIPHER_CTX ctx; EVP_CIPHER_CTX_init(&ctx); /* ivec all zero */ EVP_CipherInit_ex(&ctx, c, NULL, derived->keyvalue.data, NULL, 1); EVP_Cipher(&ctx, out->data, result.checksum.data, crypto->et->prf_length); EVP_CIPHER_CTX_cleanup(&ctx); } krb5_data_free(&result.checksum); krb5_free_keyblock(context, derived); return ret; } #ifdef DES3_OLD_ENCTYPE static struct _krb5_key_type keytype_des3 = { ETYPE_OLD_DES3_CBC_SHA1, "des3", 168, 24, sizeof(struct _krb5_evp_schedule), DES3_random_key, _krb5_evp_schedule, _krb5_des3_salt, _krb5_DES3_random_to_key, _krb5_evp_cleanup, EVP_des_ede3_cbc }; #endif static struct _krb5_key_type keytype_des3_derived = { ETYPE_OLD_DES3_CBC_SHA1, "des3", 168, 24, sizeof(struct _krb5_evp_schedule), DES3_random_key, _krb5_evp_schedule, _krb5_des3_salt_derived, _krb5_DES3_random_to_key, _krb5_evp_cleanup, EVP_des_ede3_cbc }; #ifdef DES3_OLD_ENCTYPE static krb5_error_code RSA_MD5_DES3_checksum(krb5_context context, struct _krb5_key_data *key, const void *data, size_t len, unsigned usage, Checksum *C) { return _krb5_des_checksum(context, EVP_md5(), key, data, len, C); } static krb5_error_code RSA_MD5_DES3_verify(krb5_context context, struct _krb5_key_data *key, const void *data, size_t len, unsigned usage, Checksum *C) { return _krb5_des_verify(context, EVP_md5(), key, data, len, C); } struct _krb5_checksum_type _krb5_checksum_rsa_md5_des3 = { CKSUMTYPE_RSA_MD5_DES3, "rsa-md5-des3", 64, 24, F_KEYED | F_CPROOF | F_VARIANT, RSA_MD5_DES3_checksum, RSA_MD5_DES3_verify }; #endif struct _krb5_checksum_type _krb5_checksum_hmac_sha1_des3 = { CKSUMTYPE_HMAC_SHA1_DES3, "hmac-sha1-des3", 64, 20, F_KEYED | F_CPROOF | F_DERIVED, _krb5_SP_HMAC_SHA1_checksum, NULL }; #ifdef DES3_OLD_ENCTYPE struct _krb5_encryption_type _krb5_enctype_des3_cbc_md5 = { ETYPE_DES3_CBC_MD5, "des3-cbc-md5", NULL, 8, 8, 8, &keytype_des3, &_krb5_checksum_rsa_md5, &_krb5_checksum_rsa_md5_des3, 0, _krb5_evp_encrypt, 0, NULL }; #endif struct _krb5_encryption_type _krb5_enctype_des3_cbc_sha1 = { ETYPE_DES3_CBC_SHA1, "des3-cbc-sha1", NULL, 8, 8, 8, &keytype_des3_derived, &_krb5_checksum_sha1, &_krb5_checksum_hmac_sha1_des3, F_DERIVED | F_RFC3961_ENC | F_RFC3961_KDF, _krb5_evp_encrypt, 16, DES3_prf }; #ifdef DES3_OLD_ENCTYPE struct _krb5_encryption_type _krb5_enctype_old_des3_cbc_sha1 = { ETYPE_OLD_DES3_CBC_SHA1, "old-des3-cbc-sha1", NULL, 8, 8, 8, &keytype_des3, &_krb5_checksum_sha1, &_krb5_checksum_hmac_sha1_des3, 0, _krb5_evp_encrypt, 0, NULL }; #endif struct _krb5_encryption_type _krb5_enctype_des3_cbc_none = { ETYPE_DES3_CBC_NONE, "des3-cbc-none", NULL, 8, 8, 0, &keytype_des3_derived, &_krb5_checksum_none, NULL, F_PSEUDO, _krb5_evp_encrypt, 0, NULL }; void _krb5_DES3_random_to_key(krb5_context context, krb5_keyblock *key, const void *data, size_t size) { unsigned char *x = key->keyvalue.data; const u_char *q = data; DES_cblock *k; int i, j; memset(key->keyvalue.data, 0, key->keyvalue.length); for (i = 0; i < 3; ++i) { unsigned char foo; for (j = 0; j < 7; ++j) { unsigned char b = q[7 * i + j]; x[8 * i + j] = b; } foo = 0; for (j = 6; j >= 0; --j) { foo |= q[7 * i + j] & 1; foo <<= 1; } x[8 * i + 7] = foo; } k = key->keyvalue.data; for (i = 0; i < 3; i++) { DES_set_odd_parity(&k[i]); if(DES_is_weak_key(&k[i])) _krb5_xor8(k[i], (const unsigned char*)"\0\0\0\0\0\0\0\xf0"); } } heimdal-7.5.0/lib/krb5/verify_user.c0000644000175000017500000001565513026237312015404 0ustar niknik/* * Copyright (c) 1997-2004 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "krb5_locl.h" static krb5_error_code verify_common (krb5_context context, krb5_principal principal, krb5_ccache ccache, krb5_keytab keytab, krb5_boolean secure, const char *service, krb5_creds cred) { krb5_error_code ret; krb5_principal server; krb5_verify_init_creds_opt vopt; krb5_ccache id; ret = krb5_sname_to_principal (context, NULL, service, KRB5_NT_SRV_HST, &server); if(ret) return ret; krb5_verify_init_creds_opt_init(&vopt); krb5_verify_init_creds_opt_set_ap_req_nofail(&vopt, secure); ret = krb5_verify_init_creds(context, &cred, server, keytab, NULL, &vopt); krb5_free_principal(context, server); if(ret) return ret; if(ccache == NULL) ret = krb5_cc_default (context, &id); else id = ccache; if(ret == 0){ ret = krb5_cc_initialize(context, id, principal); if(ret == 0){ ret = krb5_cc_store_cred(context, id, &cred); } if(ccache == NULL) krb5_cc_close(context, id); } krb5_free_cred_contents(context, &cred); return ret; } /* * Verify user `principal' with `password'. * * If `secure', also verify against local service key for `service'. * * As a side effect, fresh tickets are obtained and stored in `ccache'. */ KRB5_LIB_FUNCTION void KRB5_LIB_CALL krb5_verify_opt_init(krb5_verify_opt *opt) { memset(opt, 0, sizeof(*opt)); opt->secure = TRUE; opt->service = "host"; } KRB5_LIB_FUNCTION int KRB5_LIB_CALL krb5_verify_opt_alloc(krb5_context context, krb5_verify_opt **opt) { *opt = calloc(1, sizeof(**opt)); if ((*opt) == NULL) return krb5_enomem(context); krb5_verify_opt_init(*opt); return 0; } KRB5_LIB_FUNCTION void KRB5_LIB_CALL krb5_verify_opt_free(krb5_verify_opt *opt) { free(opt); } KRB5_LIB_FUNCTION void KRB5_LIB_CALL krb5_verify_opt_set_ccache(krb5_verify_opt *opt, krb5_ccache ccache) { opt->ccache = ccache; } KRB5_LIB_FUNCTION void KRB5_LIB_CALL krb5_verify_opt_set_keytab(krb5_verify_opt *opt, krb5_keytab keytab) { opt->keytab = keytab; } KRB5_LIB_FUNCTION void KRB5_LIB_CALL krb5_verify_opt_set_secure(krb5_verify_opt *opt, krb5_boolean secure) { opt->secure = secure; } KRB5_LIB_FUNCTION void KRB5_LIB_CALL krb5_verify_opt_set_service(krb5_verify_opt *opt, const char *service) { opt->service = service; } KRB5_LIB_FUNCTION void KRB5_LIB_CALL krb5_verify_opt_set_flags(krb5_verify_opt *opt, unsigned int flags) { opt->flags |= flags; } static krb5_error_code verify_user_opt_int(krb5_context context, krb5_principal principal, const char *password, krb5_verify_opt *vopt) { krb5_error_code ret; krb5_get_init_creds_opt *opt; krb5_creds cred; ret = krb5_get_init_creds_opt_alloc (context, &opt); if (ret) return ret; krb5_get_init_creds_opt_set_default_flags(context, NULL, krb5_principal_get_realm(context, principal), opt); ret = krb5_get_init_creds_password (context, &cred, principal, password, krb5_prompter_posix, NULL, 0, NULL, opt); krb5_get_init_creds_opt_free(context, opt); if(ret) return ret; #define OPT(V, D) ((vopt && (vopt->V)) ? (vopt->V) : (D)) return verify_common (context, principal, OPT(ccache, NULL), OPT(keytab, NULL), vopt ? vopt->secure : TRUE, OPT(service, "host"), cred); #undef OPT } KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_verify_user_opt(krb5_context context, krb5_principal principal, const char *password, krb5_verify_opt *opt) { krb5_error_code ret; if(opt && (opt->flags & KRB5_VERIFY_LREALMS)) { krb5_realm *realms, *r; ret = krb5_get_default_realms (context, &realms); if (ret) return ret; ret = KRB5_CONFIG_NODEFREALM; for (r = realms; *r != NULL && ret != 0; ++r) { ret = krb5_principal_set_realm(context, principal, *r); if (ret) { krb5_free_host_realm (context, realms); return ret; } ret = verify_user_opt_int(context, principal, password, opt); } krb5_free_host_realm (context, realms); if(ret) return ret; } else ret = verify_user_opt_int(context, principal, password, opt); return ret; } /* compat function that calls above */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_verify_user(krb5_context context, krb5_principal principal, krb5_ccache ccache, const char *password, krb5_boolean secure, const char *service) { krb5_verify_opt opt; krb5_verify_opt_init(&opt); krb5_verify_opt_set_ccache(&opt, ccache); krb5_verify_opt_set_secure(&opt, secure); krb5_verify_opt_set_service(&opt, service); return krb5_verify_user_opt(context, principal, password, &opt); } /* * A variant of `krb5_verify_user'. The realm of `principal' is * ignored and all the local realms are tried. */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_verify_user_lrealm(krb5_context context, krb5_principal principal, krb5_ccache ccache, const char *password, krb5_boolean secure, const char *service) { krb5_verify_opt opt; krb5_verify_opt_init(&opt); krb5_verify_opt_set_ccache(&opt, ccache); krb5_verify_opt_set_secure(&opt, secure); krb5_verify_opt_set_service(&opt, service); krb5_verify_opt_set_flags(&opt, KRB5_VERIFY_LREALMS); return krb5_verify_user_opt(context, principal, password, &opt); } heimdal-7.5.0/lib/krb5/test_set_kvno0.c0000644000175000017500000001161213026237312015776 0ustar niknik/* * Copyright (c) 2011, Secure Endpoints Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * - Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. * */ #include "krb5_locl.h" #include #include #if 0 #include #include #include #include #include #include #endif int main(int argc, char **argv) { krb5_error_code ret; krb5_context context; krb5_ccache src_cc = NULL; krb5_ccache dst_cc = NULL; krb5_cc_cursor cursor; krb5_principal me = NULL; krb5_creds cred; const char *during; Ticket t; size_t len; int make_kvno_absent = 0; int opt; memset(&cred, 0, sizeof (cred)); during = "init_context"; ret = krb5_init_context(&context); if (ret) goto err; while ((opt = getopt(argc, argv, "c:n")) != -1) { switch (opt) { case 'c': during = "cc_resolve of source ccache"; ret = krb5_cc_resolve(context, optarg, &src_cc); if (ret) goto err; break; case 'n': make_kvno_absent++; break; case 'h': default: fprintf(stderr, "Usage: %s [-n] [-c ccache]\n" "\tThis utility edits a ccache, setting all ticket\n" "\tenc_part kvnos to zero or absent (if -n is set).\n", argv[0]); return 1; } } if (!src_cc) { during = "cc_default"; ret = krb5_cc_default(context, &src_cc); if (ret) goto err; } during = "cc_get_principal"; ret = krb5_cc_get_principal(context, src_cc, &me); if (ret) goto err; if (optind != argc) { fprintf(stderr, "Usage: %s [-n] [-c ccache]\n" "\tThis utility edits a ccache, setting all ticket\n" "\tenc_part kvnos to zero or absent (if -n is set).\n", argv[0]); return 1; } during = "cc_new_unique of temporary ccache"; ret = krb5_cc_new_unique(context, krb5_cc_get_type(context, src_cc), NULL, &dst_cc); during = "cc_initialize of temporary ccache"; ret = krb5_cc_initialize(context, dst_cc, me); if (ret) goto err; during = "cc_start_seq_get"; ret = krb5_cc_start_seq_get(context, src_cc, &cursor); if (ret) goto err; while ((ret = krb5_cc_next_cred(context, src_cc, &cursor, &cred)) == 0) { krb5_data data; during = "decode_Ticket"; memset(&t, 0, sizeof (t)); ret = decode_Ticket(cred.ticket.data, cred.ticket.length, &t, &len); if (ret == ASN1_MISSING_FIELD) continue; if (ret) goto err; if (t.enc_part.kvno) { *t.enc_part.kvno = 0; if (make_kvno_absent) { free(t.enc_part.kvno); t.enc_part.kvno = NULL; } /* * The new Ticket has to need less or same space as before, so * we reuse cred->icket.data. */ during = "encode_Ticket"; ASN1_MALLOC_ENCODE(Ticket, data.data, data.length, &t, &len, ret); if (ret) { free_Ticket(&t); goto err; } krb5_data_free(&cred.ticket); cred.ticket = data; } free_Ticket(&t); during = "cc_store_cred"; ret = krb5_cc_store_cred(context, dst_cc, &cred); if (ret) goto err; krb5_free_cred_contents(context, &cred); memset(&cred, 0, sizeof (cred)); } during = "cc_next_cred"; if (ret != KRB5_CC_END) goto err; during = "cc_end_seq_get"; ret = krb5_cc_end_seq_get(context, src_cc, &cursor); if (ret) goto err; during = "cc_move"; ret = krb5_cc_move(context, dst_cc, src_cc); if (ret) goto err; dst_cc = NULL; during = "cc_switch"; ret = krb5_cc_switch(context, src_cc); if (ret) goto err; err: (void) krb5_free_principal(context, me); if (src_cc) (void) krb5_cc_close(context, src_cc); if (dst_cc) (void) krb5_cc_destroy(context, dst_cc); if (ret) { fprintf(stderr, "Failed while doing %s (%d)\n", during, ret); ret = 1; } return (ret); } heimdal-7.5.0/lib/krb5/verify_krb5_conf-version.rc0000644000175000017500000000325012136107750020132 0ustar niknik/*********************************************************************** * Copyright (c) 2010, Secure Endpoints Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * - Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. * **********************************************************************/ #define RC_FILE_TYPE VFT_APP #define RC_FILE_DESC_0409 "Krb5.conf Verification Tool" #define RC_FILE_ORIG_0409 "verify_krb5_conf.exe" #include "../../windows/version.rc" heimdal-7.5.0/lib/krb5/rd_error.c0000644000175000017500000000752412136107750014657 0ustar niknik/* * Copyright (c) 1997 - 2001 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "krb5_locl.h" KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_rd_error(krb5_context context, const krb5_data *msg, KRB_ERROR *result) { size_t len; krb5_error_code ret; ret = decode_KRB_ERROR(msg->data, msg->length, result, &len); if(ret) { krb5_clear_error_message(context); return ret; } result->error_code += KRB5KDC_ERR_NONE; return 0; } KRB5_LIB_FUNCTION void KRB5_LIB_CALL krb5_free_error_contents (krb5_context context, krb5_error *error) { free_KRB_ERROR(error); memset(error, 0, sizeof(*error)); } KRB5_LIB_FUNCTION void KRB5_LIB_CALL krb5_free_error (krb5_context context, krb5_error *error) { krb5_free_error_contents (context, error); free (error); } KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_error_from_rd_error(krb5_context context, const krb5_error *error, const krb5_creds *creds) { krb5_error_code ret; ret = error->error_code; if (error->e_text != NULL) { krb5_set_error_message(context, ret, "%s", *error->e_text); } else { char clientname[256], servername[256]; if (creds != NULL) { krb5_unparse_name_fixed(context, creds->client, clientname, sizeof(clientname)); krb5_unparse_name_fixed(context, creds->server, servername, sizeof(servername)); } switch (ret) { case KRB5KDC_ERR_NAME_EXP : krb5_set_error_message(context, ret, N_("Client %s%s%s expired", ""), creds ? "(" : "", creds ? clientname : "", creds ? ")" : ""); break; case KRB5KDC_ERR_SERVICE_EXP : krb5_set_error_message(context, ret, N_("Server %s%s%s expired", ""), creds ? "(" : "", creds ? servername : "", creds ? ")" : ""); break; case KRB5KDC_ERR_C_PRINCIPAL_UNKNOWN : krb5_set_error_message(context, ret, N_("Client %s%s%s unknown", ""), creds ? "(" : "", creds ? clientname : "", creds ? ")" : ""); break; case KRB5KDC_ERR_S_PRINCIPAL_UNKNOWN : krb5_set_error_message(context, ret, N_("Server %s%s%s unknown", ""), creds ? "(" : "", creds ? servername : "", creds ? ")" : ""); break; default : krb5_clear_error_message(context); break; } } return ret; } heimdal-7.5.0/lib/krb5/keytab.c0000644000175000017500000006266313212137553014325 0ustar niknik/* * Copyright (c) 1997 - 2005 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "krb5_locl.h" /** * @page krb5_keytab_intro The keytab handing functions * @section section_krb5_keytab Kerberos Keytabs * * See the library functions here: @ref krb5_keytab * * Keytabs are long term key storage for servers, their equvalment of * password files. * * Normally the only function that useful for server are to specify * what keytab to use to other core functions like krb5_rd_req() * krb5_kt_resolve(), and krb5_kt_close(). * * @subsection krb5_keytab_names Keytab names * * A keytab name is on the form type:residual. The residual part is * specific to each keytab-type. * * When a keytab-name is resolved, the type is matched with an internal * list of keytab types. If there is no matching keytab type, * the default keytab is used. The current default type is FILE. * * The default value can be changed in the configuration file * /etc/krb5.conf by setting the variable * [defaults]default_keytab_name. * * The keytab types that are implemented in Heimdal are: * - file * store the keytab in a file, the type's name is FILE . The * residual part is a filename. For compatibility with other * Kerberos implemtation WRFILE and JAVA14 is also accepted. WRFILE * has the same format as FILE. JAVA14 have a format that is * compatible with older versions of MIT kerberos and SUN's Java * based installation. They store a truncted kvno, so when the knvo * excess 255, they are truncted in this format. * * - keytab * store the keytab in a AFS keyfile (usually /usr/afs/etc/KeyFile ), * the type's name is AFSKEYFILE. The residual part is a filename. * * - memory * The keytab is stored in a memory segment. This allows sensitive * and/or temporary data not to be stored on disk. The type's name * is MEMORY. Each MEMORY keytab is referenced counted by and * opened by the residual name, so two handles can point to the * same memory area. When the last user closes using krb5_kt_close() * the keytab, the keys in they keytab is memset() to zero and freed * and can no longer be looked up by name. * * * @subsection krb5_keytab_example Keytab example * * This is a minimalistic version of ktutil. * * @code int main (int argc, char **argv) { krb5_context context; krb5_keytab keytab; krb5_kt_cursor cursor; krb5_keytab_entry entry; krb5_error_code ret; char *principal; if (krb5_init_context (&context) != 0) errx(1, "krb5_context"); ret = krb5_kt_default (context, &keytab); if (ret) krb5_err(context, 1, ret, "krb5_kt_default"); ret = krb5_kt_start_seq_get(context, keytab, &cursor); if (ret) krb5_err(context, 1, ret, "krb5_kt_start_seq_get"); while((ret = krb5_kt_next_entry(context, keytab, &entry, &cursor)) == 0){ krb5_unparse_name(context, entry.principal, &principal); printf("principal: %s\n", principal); free(principal); krb5_kt_free_entry(context, &entry); } ret = krb5_kt_end_seq_get(context, keytab, &cursor); if (ret) krb5_err(context, 1, ret, "krb5_kt_end_seq_get"); ret = krb5_kt_close(context, keytab); if (ret) krb5_err(context, 1, ret, "krb5_kt_close"); krb5_free_context(context); return 0; } * @endcode * */ /** * Register a new keytab backend. * * @param context a Keberos context. * @param ops a backend to register. * * @return Return an error code or 0, see krb5_get_error_message(). * * @ingroup krb5_keytab */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_kt_register(krb5_context context, const krb5_kt_ops *ops) { struct krb5_keytab_data *tmp; if (strlen(ops->prefix) > KRB5_KT_PREFIX_MAX_LEN - 1) { krb5_set_error_message(context, KRB5_KT_BADNAME, N_("can't register cache type, prefix too long", "")); return KRB5_KT_BADNAME; } tmp = realloc(context->kt_types, (context->num_kt_types + 1) * sizeof(*context->kt_types)); if(tmp == NULL) return krb5_enomem(context); memcpy(&tmp[context->num_kt_types], ops, sizeof(tmp[context->num_kt_types])); context->kt_types = tmp; context->num_kt_types++; return 0; } static const char * keytab_name(const char *name, const char **type, size_t *type_len) { const char *residual; residual = strchr(name, ':'); if (residual == NULL || ISPATHSEP(name[0]) #ifdef _WIN32 /* Avoid treating : as a keytab type * specification */ || name + 1 == residual #endif ) { *type = "FILE"; *type_len = strlen(*type); residual = name; } else { *type = name; *type_len = residual - name; residual++; } return residual; } /** * Resolve the keytab name (of the form `type:residual') in `name' * into a keytab in `id'. * * @param context a Keberos context. * @param name name to resolve * @param id resulting keytab, free with krb5_kt_close(). * * @return Return an error code or 0, see krb5_get_error_message(). * * @ingroup krb5_keytab */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_kt_resolve(krb5_context context, const char *name, krb5_keytab *id) { krb5_keytab k; int i; const char *type, *residual; size_t type_len; krb5_error_code ret; residual = keytab_name(name, &type, &type_len); for(i = 0; i < context->num_kt_types; i++) { if(strncasecmp(type, context->kt_types[i].prefix, type_len) == 0) break; } if(i == context->num_kt_types) { krb5_set_error_message(context, KRB5_KT_UNKNOWN_TYPE, N_("unknown keytab type %.*s", "type"), (int)type_len, type); return KRB5_KT_UNKNOWN_TYPE; } k = malloc (sizeof(*k)); if (k == NULL) return krb5_enomem(context); memcpy(k, &context->kt_types[i], sizeof(*k)); k->data = NULL; ret = (*k->resolve)(context, residual, k); if(ret) { free(k); k = NULL; } *id = k; return ret; } /* * Default ktname from context with possible environment * override */ static const char *default_ktname(krb5_context context) { const char *tmp = NULL; if(!issuid()) tmp = getenv("KRB5_KTNAME"); if(tmp != NULL) return tmp; return context->default_keytab; } /** * copy the name of the default keytab into `name'. * * @param context a Keberos context. * @param name buffer where the name will be written * @param namesize length of name * * @return Return an error code or 0, see krb5_get_error_message(). * * @ingroup krb5_keytab */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_kt_default_name(krb5_context context, char *name, size_t namesize) { if (strlcpy (name, default_ktname(context), namesize) >= namesize) { krb5_clear_error_message (context); return KRB5_CONFIG_NOTENUFSPACE; } return 0; } /** * Copy the name of the default modify keytab into `name'. * * @param context a Keberos context. * @param name buffer where the name will be written * @param namesize length of name * * @return Return an error code or 0, see krb5_get_error_message(). * * @ingroup krb5_keytab */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_kt_default_modify_name(krb5_context context, char *name, size_t namesize) { const char *kt; if(context->default_keytab_modify == NULL) { kt = default_ktname(context); if (strncasecmp(kt, "ANY:", 4) == 0) { size_t len = strcspn(kt + 4, ","); if (len >= namesize) { krb5_clear_error_message(context); return KRB5_CONFIG_NOTENUFSPACE; } strlcpy(name, kt + 4, namesize); name[len] = '\0'; return 0; } } else kt = context->default_keytab_modify; if (strlcpy (name, kt, namesize) >= namesize) { krb5_clear_error_message (context); return KRB5_CONFIG_NOTENUFSPACE; } return 0; } /** * Set `id' to the default keytab. * * @param context a Keberos context. * @param id the new default keytab. * * @return Return an error code or 0, see krb5_get_error_message(). * * @ingroup krb5_keytab */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_kt_default(krb5_context context, krb5_keytab *id) { return krb5_kt_resolve (context, default_ktname(context), id); } /** * Read the key identified by `(principal, vno, enctype)' from the * keytab in `keyprocarg' (the default if == NULL) into `*key'. * * @param context a Keberos context. * @param keyprocarg * @param principal * @param vno * @param enctype * @param key * * @return Return an error code or 0, see krb5_get_error_message(). * * @ingroup krb5_keytab */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_kt_read_service_key(krb5_context context, krb5_pointer keyprocarg, krb5_principal principal, krb5_kvno vno, krb5_enctype enctype, krb5_keyblock **key) { krb5_keytab keytab; krb5_keytab_entry entry; krb5_error_code ret; if (keyprocarg) ret = krb5_kt_resolve (context, keyprocarg, &keytab); else ret = krb5_kt_default (context, &keytab); if (ret) return ret; ret = krb5_kt_get_entry (context, keytab, principal, vno, enctype, &entry); krb5_kt_close (context, keytab); if (ret) return ret; ret = krb5_copy_keyblock (context, &entry.keyblock, key); krb5_kt_free_entry(context, &entry); return ret; } /** * Return the type of the `keytab' in the string `prefix of length * `prefixsize'. * * @param context a Keberos context. * @param keytab the keytab to get the prefix for * @param prefix prefix buffer * @param prefixsize length of prefix buffer * * @return Return an error code or 0, see krb5_get_error_message(). * * @ingroup krb5_keytab */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_kt_get_type(krb5_context context, krb5_keytab keytab, char *prefix, size_t prefixsize) { strlcpy(prefix, keytab->prefix, prefixsize); return 0; } /** * Retrieve the name of the keytab `keytab' into `name', `namesize' * * @param context a Keberos context. * @param keytab the keytab to get the name for. * @param name name buffer. * @param namesize size of name buffer. * * @return Return an error code or 0, see krb5_get_error_message(). * * @ingroup krb5_keytab */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_kt_get_name(krb5_context context, krb5_keytab keytab, char *name, size_t namesize) { return (*keytab->get_name)(context, keytab, name, namesize); } /** * Retrieve the full name of the keytab `keytab' and store the name in * `str'. * * @param context a Keberos context. * @param keytab keytab to get name for. * @param str the name of the keytab name, usee krb5_xfree() to free * the string. On error, *str is set to NULL. * * @return Return an error code or 0, see krb5_get_error_message(). * * @ingroup krb5_keytab */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_kt_get_full_name(krb5_context context, krb5_keytab keytab, char **str) { char type[KRB5_KT_PREFIX_MAX_LEN]; char name[MAXPATHLEN]; krb5_error_code ret; *str = NULL; ret = krb5_kt_get_type(context, keytab, type, sizeof(type)); if (ret) return ret; ret = krb5_kt_get_name(context, keytab, name, sizeof(name)); if (ret) return ret; if (asprintf(str, "%s:%s", type, name) == -1) { *str = NULL; return krb5_enomem(context); } return 0; } /** * Finish using the keytab in `id'. All resources will be released, * even on errors. * * @param context a Keberos context. * @param id keytab to close. * * @return Return an error code or 0, see krb5_get_error_message(). * * @ingroup krb5_keytab */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_kt_close(krb5_context context, krb5_keytab id) { krb5_error_code ret; ret = (*id->close)(context, id); memset(id, 0, sizeof(*id)); free(id); return ret; } /** * Destroy (remove) the keytab in `id'. All resources will be released, * even on errors, does the equvalment of krb5_kt_close() on the resources. * * @param context a Keberos context. * @param id keytab to destroy. * * @return Return an error code or 0, see krb5_get_error_message(). * * @ingroup krb5_keytab */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_kt_destroy(krb5_context context, krb5_keytab id) { krb5_error_code ret; ret = (*id->destroy)(context, id); krb5_kt_close(context, id); return ret; } /* * Match any aliases in keytab `entry' with `principal'. */ static krb5_boolean compare_aliases(krb5_context context, krb5_keytab_entry *entry, krb5_const_principal principal) { unsigned int i; if (entry->aliases == NULL) return FALSE; for (i = 0; i < entry->aliases->len; i++) if (krb5_principal_compare(context, &entry->aliases->val[i], principal)) return TRUE; return FALSE; } /** * Compare `entry' against `principal, vno, enctype'. * Any of `principal, vno, enctype' might be 0 which acts as a wildcard. * Return TRUE if they compare the same, FALSE otherwise. * * @param context a Keberos context. * @param entry an entry to match with. * @param principal principal to match, NULL matches all principals. * @param vno key version to match, 0 matches all key version numbers. * @param enctype encryption type to match, 0 matches all encryption types. * * @return Return TRUE or match, FALSE if not matched. * * @ingroup krb5_keytab */ KRB5_LIB_FUNCTION krb5_boolean KRB5_LIB_CALL krb5_kt_compare(krb5_context context, krb5_keytab_entry *entry, krb5_const_principal principal, krb5_kvno vno, krb5_enctype enctype) { /* krb5_principal_compare() does not special-case the referral realm */ if (principal != NULL && strcmp(principal->realm, "") == 0 && !(krb5_principal_compare_any_realm(context, entry->principal, principal) || compare_aliases(context, entry, principal))) { return FALSE; } else if (principal != NULL && strcmp(principal->realm, "") != 0 && !(krb5_principal_compare(context, entry->principal, principal) || compare_aliases(context, entry, principal))) { return FALSE; } if (vno && vno != entry->vno) return FALSE; if (enctype && enctype != entry->keyblock.keytype) return FALSE; return TRUE; } KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL _krb5_kt_principal_not_found(krb5_context context, krb5_error_code ret, krb5_keytab id, krb5_const_principal principal, krb5_enctype enctype, int kvno) { char princ[256], kvno_str[25], *kt_name; char *enctype_str = NULL; krb5_unparse_name_fixed (context, principal, princ, sizeof(princ)); krb5_kt_get_full_name (context, id, &kt_name); if (enctype) krb5_enctype_to_string(context, enctype, &enctype_str); if (kvno) snprintf(kvno_str, sizeof(kvno_str), "(kvno %d)", kvno); else kvno_str[0] = '\0'; krb5_set_error_message (context, ret, N_("Failed to find %s%s in keytab %s (%s)", "principal, kvno, keytab file, enctype"), princ, kvno_str, kt_name ? kt_name : "unknown keytab", enctype_str ? enctype_str : "unknown enctype"); free(kt_name); if (enctype_str) free(enctype_str); return ret; } static krb5_error_code krb5_kt_get_entry_wrapped(krb5_context context, krb5_keytab id, krb5_const_principal principal, krb5_kvno kvno, krb5_enctype enctype, krb5_keytab_entry *entry) { krb5_keytab_entry tmp; krb5_error_code ret; krb5_kt_cursor cursor; if(id->get) return (*id->get)(context, id, principal, kvno, enctype, entry); ret = krb5_kt_start_seq_get (context, id, &cursor); if (ret) { /* This is needed for krb5_verify_init_creds, but keep error * string from previous error for the human. */ context->error_code = KRB5_KT_NOTFOUND; return KRB5_KT_NOTFOUND; } entry->vno = 0; while (krb5_kt_next_entry(context, id, &tmp, &cursor) == 0) { if (krb5_kt_compare(context, &tmp, principal, 0, enctype)) { /* the file keytab might only store the lower 8 bits of the kvno, so only compare those bits */ if (kvno == tmp.vno || (tmp.vno < 256 && kvno % 256 == tmp.vno)) { krb5_kt_copy_entry_contents (context, &tmp, entry); krb5_kt_free_entry (context, &tmp); krb5_kt_end_seq_get(context, id, &cursor); return 0; } else if (kvno == 0 && tmp.vno > entry->vno) { if (entry->vno) krb5_kt_free_entry (context, entry); krb5_kt_copy_entry_contents (context, &tmp, entry); } } krb5_kt_free_entry(context, &tmp); } krb5_kt_end_seq_get (context, id, &cursor); if (entry->vno == 0) return _krb5_kt_principal_not_found(context, KRB5_KT_NOTFOUND, id, principal, enctype, kvno); return 0; } /** * Retrieve the keytab entry for `principal, kvno, enctype' into `entry' * from the keytab `id'. Matching is done like krb5_kt_compare(). * * @param context a Keberos context. * @param id a keytab. * @param principal principal to match, NULL matches all principals. * @param kvno key version to match, 0 matches all key version numbers. * @param enctype encryption type to match, 0 matches all encryption types. * @param entry the returned entry, free with krb5_kt_free_entry(). * * @return Return an error code or 0, see krb5_get_error_message(). * * @ingroup krb5_keytab */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_kt_get_entry(krb5_context context, krb5_keytab id, krb5_const_principal principal, krb5_kvno kvno, krb5_enctype enctype, krb5_keytab_entry *entry) { krb5_error_code ret; krb5_const_principal try_princ; krb5_name_canon_iterator name_canon_iter; if (!principal) return krb5_kt_get_entry_wrapped(context, id, principal, kvno, enctype, entry); ret = krb5_name_canon_iterator_start(context, principal, &name_canon_iter); if (ret) return ret; do { ret = krb5_name_canon_iterate(context, &name_canon_iter, &try_princ, NULL); if (ret) break; if (try_princ == NULL) { ret = KRB5_KT_NOTFOUND; continue; } ret = krb5_kt_get_entry_wrapped(context, id, try_princ, kvno, enctype, entry); } while (ret == KRB5_KT_NOTFOUND && name_canon_iter); if (ret != KRB5_KT_NOTFOUND) krb5_set_error_message(context, ret, N_("Name canon failed while searching keytab", "")); krb5_free_name_canon_iterator(context, name_canon_iter); return ret; } /** * Copy the contents of `in' into `out'. * * @param context a Keberos context. * @param in the keytab entry to copy. * @param out the copy of the keytab entry, free with krb5_kt_free_entry(). * * @return Return an error code or 0, see krb5_get_error_message(). * * @ingroup krb5_keytab */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_kt_copy_entry_contents(krb5_context context, const krb5_keytab_entry *in, krb5_keytab_entry *out) { krb5_error_code ret; memset(out, 0, sizeof(*out)); out->vno = in->vno; ret = krb5_copy_principal (context, in->principal, &out->principal); if (ret) goto fail; ret = krb5_copy_keyblock_contents (context, &in->keyblock, &out->keyblock); if (ret) goto fail; out->timestamp = in->timestamp; return 0; fail: krb5_kt_free_entry (context, out); return ret; } /** * Free the contents of `entry'. * * @param context a Keberos context. * @param entry the entry to free * * @return Return an error code or 0, see krb5_get_error_message(). * * @ingroup krb5_keytab */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_kt_free_entry(krb5_context context, krb5_keytab_entry *entry) { krb5_free_principal (context, entry->principal); krb5_free_keyblock_contents (context, &entry->keyblock); memset(entry, 0, sizeof(*entry)); return 0; } /** * Set `cursor' to point at the beginning of `id'. * * @param context a Keberos context. * @param id a keytab. * @param cursor a newly allocated cursor, free with krb5_kt_end_seq_get(). * * @return Return an error code or 0, see krb5_get_error_message(). * * @ingroup krb5_keytab */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_kt_start_seq_get(krb5_context context, krb5_keytab id, krb5_kt_cursor *cursor) { if(id->start_seq_get == NULL) { krb5_set_error_message(context, HEIM_ERR_OPNOTSUPP, N_("start_seq_get is not supported " "in the %s keytab type", ""), id->prefix); return HEIM_ERR_OPNOTSUPP; } return (*id->start_seq_get)(context, id, cursor); } /** * Get the next entry from keytab, advance the cursor. On last entry * the function will return KRB5_KT_END. * * @param context a Keberos context. * @param id a keytab. * @param entry the returned entry, free with krb5_kt_free_entry(). * @param cursor the cursor of the iteration. * * @return Return an error code or 0, see krb5_get_error_message(). * * @ingroup krb5_keytab */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_kt_next_entry(krb5_context context, krb5_keytab id, krb5_keytab_entry *entry, krb5_kt_cursor *cursor) { if(id->next_entry == NULL) { krb5_set_error_message(context, HEIM_ERR_OPNOTSUPP, N_("next_entry is not supported in the %s " " keytab", ""), id->prefix); return HEIM_ERR_OPNOTSUPP; } return (*id->next_entry)(context, id, entry, cursor); } /** * Release all resources associated with `cursor'. * * @param context a Keberos context. * @param id a keytab. * @param cursor the cursor to free. * * @return Return an error code or 0, see krb5_get_error_message(). * * @ingroup krb5_keytab */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_kt_end_seq_get(krb5_context context, krb5_keytab id, krb5_kt_cursor *cursor) { if(id->end_seq_get == NULL) { krb5_set_error_message(context, HEIM_ERR_OPNOTSUPP, "end_seq_get is not supported in the %s " " keytab", id->prefix); return HEIM_ERR_OPNOTSUPP; } return (*id->end_seq_get)(context, id, cursor); } /** * Add the entry in `entry' to the keytab `id'. * * @param context a Keberos context. * @param id a keytab. * @param entry the entry to add * * @return Return an error code or 0, see krb5_get_error_message(). * * @ingroup krb5_keytab */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_kt_add_entry(krb5_context context, krb5_keytab id, krb5_keytab_entry *entry) { if(id->add == NULL) { krb5_set_error_message(context, KRB5_KT_NOWRITE, N_("Add is not supported in the %s keytab", ""), id->prefix); return KRB5_KT_NOWRITE; } entry->timestamp = time(NULL); return (*id->add)(context, id,entry); } /** * Remove an entry from the keytab, matching is done using * krb5_kt_compare(). * @param context a Keberos context. * @param id a keytab. * @param entry the entry to remove * * @return Return an error code or 0, see krb5_get_error_message(). * * @ingroup krb5_keytab */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_kt_remove_entry(krb5_context context, krb5_keytab id, krb5_keytab_entry *entry) { if(id->remove == NULL) { krb5_set_error_message(context, KRB5_KT_NOWRITE, N_("Remove is not supported in the %s keytab", ""), id->prefix); return KRB5_KT_NOWRITE; } return (*id->remove)(context, id, entry); } /** * Return true if the keytab exists and have entries * * @param context a Keberos context. * @param id a keytab. * * @return Return an error code or 0, see krb5_get_error_message(). * * @ingroup krb5_keytab */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_kt_have_content(krb5_context context, krb5_keytab id) { krb5_keytab_entry entry; krb5_kt_cursor cursor; krb5_error_code ret; char *name; ret = krb5_kt_start_seq_get(context, id, &cursor); if (ret) goto notfound; ret = krb5_kt_next_entry(context, id, &entry, &cursor); krb5_kt_end_seq_get(context, id, &cursor); if (ret) goto notfound; krb5_kt_free_entry(context, &entry); return 0; notfound: ret = krb5_kt_get_full_name(context, id, &name); if (ret == 0) { krb5_set_error_message(context, KRB5_KT_NOTFOUND, N_("No entry in keytab: %s", ""), name); free(name); } return KRB5_KT_NOTFOUND; } heimdal-7.5.0/lib/krb5/eai_to_heim_errno.c0000644000175000017500000000672713026237312016511 0ustar niknik/* * Copyright (c) 2000 - 2001 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "krb5_locl.h" /** * Convert the getaddrinfo() error code to a Kerberos et error code. * * @param eai_errno contains the error code from getaddrinfo(). * @param system_error should have the value of errno after the failed getaddrinfo(). * * @return Kerberos error code representing the EAI errors. * * @ingroup krb5_error */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_eai_to_heim_errno(int eai_errno, int system_error) { switch(eai_errno) { case EAI_NOERROR: return 0; #ifdef EAI_ADDRFAMILY case EAI_ADDRFAMILY: return HEIM_EAI_ADDRFAMILY; #endif case EAI_AGAIN: return HEIM_EAI_AGAIN; case EAI_BADFLAGS: return HEIM_EAI_BADFLAGS; case EAI_FAIL: return HEIM_EAI_FAIL; case EAI_FAMILY: return HEIM_EAI_FAMILY; case EAI_MEMORY: return HEIM_EAI_MEMORY; #if defined(EAI_NODATA) && EAI_NODATA != EAI_NONAME case EAI_NODATA: return HEIM_EAI_NODATA; #endif #ifdef WSANO_DATA case WSANO_DATA: return HEIM_EAI_NODATA; #endif case EAI_NONAME: return HEIM_EAI_NONAME; case EAI_SERVICE: return HEIM_EAI_SERVICE; case EAI_SOCKTYPE: return HEIM_EAI_SOCKTYPE; #ifdef EAI_SYSTEM case EAI_SYSTEM: return system_error; #endif default: return HEIM_EAI_UNKNOWN; /* XXX */ } } /** * Convert the gethostname() error code (h_error) to a Kerberos et * error code. * * @param eai_errno contains the error code from gethostname(). * * @return Kerberos error code representing the gethostname errors. * * @ingroup krb5_error */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_h_errno_to_heim_errno(int eai_errno) { switch(eai_errno) { case 0: return 0; case HOST_NOT_FOUND: return HEIM_EAI_NONAME; case TRY_AGAIN: return HEIM_EAI_AGAIN; case NO_RECOVERY: return HEIM_EAI_FAIL; case NO_DATA: return HEIM_EAI_NONAME; default: return HEIM_EAI_UNKNOWN; /* XXX */ } } heimdal-7.5.0/lib/krb5/krb5_auth_context.30000644000175000017500000002547113026237312016407 0ustar niknik.\" Copyright (c) 2001 - 2005 Kungliga Tekniska Högskolan .\" (Royal Institute of Technology, Stockholm, Sweden). .\" All rights reserved. .\" .\" Redistribution and use in source and binary forms, with or without .\" modification, are permitted provided that the following conditions .\" are met: .\" .\" 1. Redistributions of source code must retain the above copyright .\" notice, this list of conditions and the following disclaimer. .\" .\" 2. Redistributions in binary form must reproduce the above copyright .\" notice, this list of conditions and the following disclaimer in the .\" documentation and/or other materials provided with the distribution. .\" .\" 3. Neither the name of the Institute nor the names of its contributors .\" may be used to endorse or promote products derived from this software .\" without specific prior written permission. .\" .\" THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND .\" ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE .\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE .\" ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE .\" FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL .\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS .\" OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) .\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT .\" LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF .\" SUCH DAMAGE. .\" .\" $Id$ .\" .Dd May 17, 2005 .Dt KRB5_AUTH_CONTEXT 3 .Os HEIMDAL .Sh NAME .Nm krb5_auth_con_addflags , .Nm krb5_auth_con_free , .Nm krb5_auth_con_genaddrs , .Nm krb5_auth_con_generatelocalsubkey , .Nm krb5_auth_con_getaddrs , .Nm krb5_auth_con_getauthenticator , .Nm krb5_auth_con_getflags , .Nm krb5_auth_con_getkey , .Nm krb5_auth_con_getlocalsubkey , .Nm krb5_auth_con_getrcache , .Nm krb5_auth_con_getremotesubkey , .Nm krb5_auth_con_getuserkey , .Nm krb5_auth_con_init , .Nm krb5_auth_con_initivector , .Nm krb5_auth_con_removeflags , .Nm krb5_auth_con_setaddrs , .Nm krb5_auth_con_setaddrs_from_fd , .Nm krb5_auth_con_setflags , .Nm krb5_auth_con_setivector , .Nm krb5_auth_con_setkey , .Nm krb5_auth_con_setlocalsubkey , .Nm krb5_auth_con_setrcache , .Nm krb5_auth_con_setremotesubkey , .Nm krb5_auth_con_setuserkey , .Nm krb5_auth_context , .Nm krb5_auth_getcksumtype , .Nm krb5_auth_getkeytype , .Nm krb5_auth_getlocalseqnumber , .Nm krb5_auth_getremoteseqnumber , .Nm krb5_auth_setcksumtype , .Nm krb5_auth_setkeytype , .Nm krb5_auth_setlocalseqnumber , .Nm krb5_auth_setremoteseqnumber , .Nm krb5_free_authenticator .Nd manage authentication on connection level .Sh LIBRARY Kerberos 5 Library (libkrb5, -lkrb5) .Sh SYNOPSIS .In krb5.h .Ft krb5_error_code .Fo krb5_auth_con_init .Fa "krb5_context context" .Fa "krb5_auth_context *auth_context" .Fc .Ft void .Fo krb5_auth_con_free .Fa "krb5_context context" .Fa "krb5_auth_context auth_context" .Fc .Ft krb5_error_code .Fo krb5_auth_con_setflags .Fa "krb5_context context" .Fa "krb5_auth_context auth_context" .Fa "int32_t flags" .Fc .Ft krb5_error_code .Fo krb5_auth_con_getflags .Fa "krb5_context context" .Fa "krb5_auth_context auth_context" .Fa "int32_t *flags" .Fc .Ft krb5_error_code .Fo krb5_auth_con_addflags .Fa "krb5_context context" .Fa "krb5_auth_context auth_context" .Fa "int32_t addflags" .Fa "int32_t *flags" .Fc .Ft krb5_error_code .Fo krb5_auth_con_removeflags .Fa "krb5_context context" .Fa "krb5_auth_context auth_context" .Fa "int32_t removelags" .Fa "int32_t *flags" .Fc .Ft krb5_error_code .Fo krb5_auth_con_setaddrs .Fa "krb5_context context" .Fa "krb5_auth_context auth_context" .Fa "krb5_address *local_addr" .Fa "krb5_address *remote_addr" .Fc .Ft krb5_error_code .Fo krb5_auth_con_getaddrs .Fa "krb5_context context" .Fa "krb5_auth_context auth_context" .Fa "krb5_address **local_addr" .Fa "krb5_address **remote_addr" .Fc .Ft krb5_error_code .Fo krb5_auth_con_genaddrs .Fa "krb5_context context" .Fa "krb5_auth_context auth_context" .Fa "int fd" .Fa "int flags" .Fc .Ft krb5_error_code .Fo krb5_auth_con_setaddrs_from_fd .Fa "krb5_context context" .Fa "krb5_auth_context auth_context" .Fa "void *p_fd" .Fc .Ft krb5_error_code .Fo krb5_auth_con_getkey .Fa "krb5_context context" .Fa "krb5_auth_context auth_context" .Fa "krb5_keyblock **keyblock" .Fc .Ft krb5_error_code .Fo krb5_auth_con_getlocalsubkey .Fa "krb5_context context" .Fa "krb5_auth_context auth_context" .Fa "krb5_keyblock **keyblock" .Fc .Ft krb5_error_code .Fo krb5_auth_con_getremotesubkey .Fa "krb5_context context" .Fa "krb5_auth_context auth_context" .Fa "krb5_keyblock **keyblock" .Fc .Ft krb5_error_code .Fo krb5_auth_con_generatelocalsubkey .Fa "krb5_context context" .Fa "krb5_auth_context auth_context" .Fa krb5_keyblock *key" .Fc .Ft krb5_error_code .Fo krb5_auth_con_initivector .Fa "krb5_context context" .Fa "krb5_auth_context auth_context" .Fc .Ft krb5_error_code .Fo krb5_auth_con_setivector .Fa "krb5_context context" .Fa "krb5_auth_context *auth_context" .Fa "krb5_pointer ivector" .Fc .Ft void .Fo krb5_free_authenticator .Fa "krb5_context context" .Fa "krb5_authenticator *authenticator" .Fc .Sh DESCRIPTION The .Nm krb5_auth_context structure holds all context related to an authenticated connection, in a similar way to .Nm krb5_context that holds the context for the thread or process. .Nm krb5_auth_context is used by various functions that are directly related to authentication between the server/client. Example of data that this structure contains are various flags, addresses of client and server, port numbers, keyblocks (and subkeys), sequence numbers, replay cache, and checksum-type. .Pp .Fn krb5_auth_con_init allocates and initializes the .Nm krb5_auth_context structure. Default values can be changed with .Fn krb5_auth_con_setcksumtype and .Fn krb5_auth_con_setflags . The .Nm auth_context structure must be freed by .Fn krb5_auth_con_free . .Pp .Fn krb5_auth_con_getflags , .Fn krb5_auth_con_setflags , .Fn krb5_auth_con_addflags and .Fn krb5_auth_con_removeflags gets and modifies the flags for a .Nm krb5_auth_context structure. Possible flags to set are: .Bl -tag -width Ds .It Dv KRB5_AUTH_CONTEXT_DO_SEQUENCE Generate and check sequence-number on each packet. .It Dv KRB5_AUTH_CONTEXT_DO_TIME Check timestamp on incoming packets. .It Dv KRB5_AUTH_CONTEXT_RET_SEQUENCE , Dv KRB5_AUTH_CONTEXT_RET_TIME Return sequence numbers and time stamps in the outdata parameters. .It Dv KRB5_AUTH_CONTEXT_CLEAR_FORWARDED_CRED will force .Fn krb5_get_forwarded_creds and .Fn krb5_fwd_tgt_creds to create unencrypted ) .Dv KRB5_ENCTYPE_NULL ) credentials. This is for use with old MIT server and JAVA based servers as they can't handle encrypted .Dv KRB-CRED . Note that sending such .Dv KRB-CRED is clear exposes crypto keys and tickets and is insecure, make sure the packet is encrypted in the protocol. .Xr krb5_rd_cred 3 , .Xr krb5_rd_priv 3 , .Xr krb5_rd_safe 3 , .Xr krb5_mk_priv 3 and .Xr krb5_mk_safe 3 . Setting this flag requires that parameter to be passed to these functions. .Pp The flags .Dv KRB5_AUTH_CONTEXT_DO_TIME also modifies the behavior the function .Fn krb5_get_forwarded_creds by removing the timestamp in the forward credential message, this have backward compatibility problems since not all versions of the heimdal supports timeless credentional messages. Is very useful since it always the sender of the message to cache forward message and thus avoiding a round trip to the KDC for each time a credential is forwarded. The same functionality can be obtained by using address-less tickets. .\".It Dv KRB5_AUTH_CONTEXT_PERMIT_ALL .El .Pp .Fn krb5_auth_con_setaddrs , .Fn krb5_auth_con_setaddrs_from_fd and .Fn krb5_auth_con_getaddrs gets and sets the addresses that are checked when a packet is received. It is mandatory to set an address for the remote host. If the local address is not set, it iss deduced from the underlaying operating system. .Fn krb5_auth_con_getaddrs will call .Fn krb5_free_address on any address that is passed in .Fa local_addr or .Fa remote_addr . .Fn krb5_auth_con_setaddr allows passing in a .Dv NULL pointer as .Fa local_addr and .Fa remote_addr , in that case it will just not set that address. .Pp .Fn krb5_auth_con_setaddrs_from_fd fetches the addresses from a file descriptor. .Pp .Fn krb5_auth_con_genaddrs fetches the address information from the given file descriptor .Fa fd depending on the bitmap argument .Fa flags . .Pp Possible values on .Fa flags are: .Bl -tag -width Ds .It Va KRB5_AUTH_CONTEXT_GENERATE_LOCAL_ADDR fetches the local address from .Fa fd . .It Va KRB5_AUTH_CONTEXT_GENERATE_REMOTE_ADDR fetches the remote address from .Fa fd . .El .Pp .Fn krb5_auth_con_setkey , .Fn krb5_auth_con_setuserkey and .Fn krb5_auth_con_getkey gets and sets the key used for this auth context. The keyblock returned by .Fn krb5_auth_con_getkey should be freed with .Fn krb5_free_keyblock . The keyblock send into .Fn krb5_auth_con_setkey is copied into the .Nm krb5_auth_context , and thus no special handling is needed. .Dv NULL is not a valid keyblock to .Fn krb5_auth_con_setkey . .Pp .Fn krb5_auth_con_setuserkey is only useful when doing user to user authentication. .Fn krb5_auth_con_setkey is equivalent to .Fn krb5_auth_con_setuserkey . .Pp .Fn krb5_auth_con_getlocalsubkey , .Fn krb5_auth_con_setlocalsubkey , .Fn krb5_auth_con_getremotesubkey and .Fn krb5_auth_con_setremotesubkey gets and sets the keyblock for the local and remote subkey. The keyblock returned by .Fn krb5_auth_con_getlocalsubkey and .Fn krb5_auth_con_getremotesubkey must be freed with .Fn krb5_free_keyblock . .Pp .Fn krb5_auth_setcksumtype and .Fn krb5_auth_getcksumtype sets and gets the checksum type that should be used for this connection. .Pp .Fn krb5_auth_con_generatelocalsubkey generates a local subkey that have the same encryption type as .Fa key . .Pp .Fn krb5_auth_getremoteseqnumber .Fn krb5_auth_setremoteseqnumber , .Fn krb5_auth_getlocalseqnumber and .Fn krb5_auth_setlocalseqnumber gets and sets the sequence-number for the local and remote sequence-number counter. .Pp .Fn krb5_auth_setkeytype and .Fn krb5_auth_getkeytype gets and gets the keytype of the keyblock in .Nm krb5_auth_context . .Pp .Fn krb5_auth_con_getauthenticator Retrieves the authenticator that was used during mutual authentication. The .Dv authenticator returned should be freed by calling .Fn krb5_free_authenticator . .Pp .Fn krb5_auth_con_getrcache and .Fn krb5_auth_con_setrcache gets and sets the replay-cache. .Pp .Fn krb5_auth_con_initivector allocates memory for and zeros the initial vector in the .Fa auth_context keyblock. .Pp .Fn krb5_auth_con_setivector sets the i_vector portion of .Fa auth_context to .Fa ivector . .Pp .Fn krb5_free_authenticator free the content of .Fa authenticator and .Fa authenticator itself. .Sh SEE ALSO .Xr krb5_context 3 , .Xr kerberos 8 heimdal-7.5.0/lib/krb5/krb5_eai_to_heim_errno.cat30000644000175000017500000000256513212450756020046 0ustar niknik KRB5_EAI_TO_HEIM_ERRN... BSD Library Functions Manual KRB5_EAI_TO_HEIM_ERRN... NNAAMMEE kkrrbb55__eeaaii__ttoo__hheeiimm__eerrrrnnoo, kkrrbb55__hh__eerrrrnnoo__ttoo__hheeiimm__eerrrrnnoo -- convert resolver error code to com_err error codes LLIIBBRRAARRYY Kerberos 5 Library (libkrb5, -lkrb5) SSYYNNOOPPSSIISS ##iinncclluuddee <> _k_r_b_5___e_r_r_o_r___c_o_d_e kkrrbb55__eeaaii__ttoo__hheeiimm__eerrrrnnoo(_i_n_t _e_a_i___e_r_r_n_o, _i_n_t _s_y_s_t_e_m___e_r_r_o_r); _k_r_b_5___e_r_r_o_r___c_o_d_e kkrrbb55__hh__eerrrrnnoo__ttoo__hheeiimm__eerrrrnnoo(_i_n_t _e_a_i___e_r_r_n_o); DDEESSCCRRIIPPTTIIOONN kkrrbb55__eeaaii__ttoo__hheeiimm__eerrrrnnoo() and kkrrbb55__hh__eerrrrnnoo__ttoo__hheeiimm__eerrrrnnoo() convert getaddrinfo(3), getnameinfo(3), and h_errno(3) to com_err error code that are used by Heimdal, this is useful for for function returning kerberos errors and needs to communicate failures from resolver function. SSEEEE AALLSSOO krb5(3), kerberos(8) HEIMDAL April 13, 2004 HEIMDAL heimdal-7.5.0/lib/krb5/krb5_verify_user.30000644000175000017500000001532712136107750016246 0ustar niknik.\" Copyright (c) 2001 - 2006 Kungliga Tekniska Högskolan .\" (Royal Institute of Technology, Stockholm, Sweden). .\" All rights reserved. .\" .\" Redistribution and use in source and binary forms, with or without .\" modification, are permitted provided that the following conditions .\" are met: .\" .\" 1. Redistributions of source code must retain the above copyright .\" notice, this list of conditions and the following disclaimer. .\" .\" 2. Redistributions in binary form must reproduce the above copyright .\" notice, this list of conditions and the following disclaimer in the .\" documentation and/or other materials provided with the distribution. .\" .\" 3. Neither the name of the Institute nor the names of its contributors .\" may be used to endorse or promote products derived from this software .\" without specific prior written permission. .\" .\" THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND .\" ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE .\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE .\" ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE .\" FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL .\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS .\" OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) .\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT .\" LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF .\" SUCH DAMAGE. .\" .\" $Id$ .\" .Dd May 1, 2006 .Dt KRB5_VERIFY_USER 3 .Os HEIMDAL .Sh NAME .Nm krb5_verify_user , .Nm krb5_verify_user_lrealm , .Nm krb5_verify_user_opt , .Nm krb5_verify_opt_init , .Nm krb5_verify_opt_alloc , .Nm krb5_verify_opt_free , .Nm krb5_verify_opt_set_ccache , .Nm krb5_verify_opt_set_flags , .Nm krb5_verify_opt_set_service , .Nm krb5_verify_opt_set_secure , .Nm krb5_verify_opt_set_keytab .Nd Heimdal password verifying functions .Sh LIBRARY Kerberos 5 Library (libkrb5, -lkrb5) .Sh SYNOPSIS .In krb5.h .Ft krb5_error_code .Fn "krb5_verify_user" "krb5_context context" " krb5_principal principal" "krb5_ccache ccache" "const char *password" "krb5_boolean secure" "const char *service" .Ft krb5_error_code .Fn "krb5_verify_user_lrealm" "krb5_context context" "krb5_principal principal" "krb5_ccache ccache" "const char *password" "krb5_boolean secure" "const char *service" .Ft void .Fn krb5_verify_opt_init "krb5_verify_opt *opt" .Ft void .Fn krb5_verify_opt_alloc "krb5_verify_opt **opt" .Ft void .Fn krb5_verify_opt_free "krb5_verify_opt *opt" .Ft void .Fn krb5_verify_opt_set_ccache "krb5_verify_opt *opt" "krb5_ccache ccache" .Ft void .Fn krb5_verify_opt_set_keytab "krb5_verify_opt *opt" "krb5_keytab keytab" .Ft void .Fn krb5_verify_opt_set_secure "krb5_verify_opt *opt" "krb5_boolean secure" .Ft void .Fn krb5_verify_opt_set_service "krb5_verify_opt *opt" "const char *service" .Ft void .Fn krb5_verify_opt_set_flags "krb5_verify_opt *opt" "unsigned int flags" .Ft krb5_error_code .Fo krb5_verify_user_opt .Fa "krb5_context context" .Fa "krb5_principal principal" .Fa "const char *password" .Fa "krb5_verify_opt *opt" .Fc .Sh DESCRIPTION The .Nm krb5_verify_user function verifies the password supplied by a user. The principal whose password will be verified is specified in .Fa principal . New tickets will be obtained as a side-effect and stored in .Fa ccache (if .Dv NULL , the default ccache is used). .Fn krb5_verify_user will call .Fn krb5_cc_initialize on the given .Fa ccache , so .Fa ccache must only initialized with .Fn krb5_cc_resolve or .Fn krb5_cc_gen_new . If the password is not supplied in .Fa password (and is given as .Dv NULL ) the user will be prompted for it. If .Fa secure the ticket will be verified against the locally stored service key .Fa service (by default .Ql host if given as .Dv NULL ). .Pp The .Fn krb5_verify_user_lrealm function does the same, except that it ignores the realm in .Fa principal and tries all the local realms (see .Xr krb5.conf 5 ) . After a successful return, the principal is set to the authenticated realm. If the call fails, the principal will not be meaningful, and should only be freed with .Xr krb5_free_principal 3 . .Pp .Fn krb5_verify_opt_alloc and .Fn krb5_verify_opt_free allocates and frees a .Li krb5_verify_opt . You should use the the alloc and free function instead of allocation the structure yourself, this is because in a future release the structure wont be exported. .Pp .Fn krb5_verify_opt_init resets all opt to default values. .Pp None of the krb5_verify_opt_set function makes a copy of the data structure that they are called with. It's up the caller to free them after the .Fn krb5_verify_user_opt is called. .Pp .Fn krb5_verify_opt_set_ccache sets the .Fa ccache that user of .Fa opt will use. If not set, the default credential cache will be used. .Pp .Fn krb5_verify_opt_set_keytab sets the .Fa keytab that user of .Fa opt will use. If not set, the default keytab will be used. .Pp .Fn krb5_verify_opt_set_secure if .Fa secure if true, the password verification will require that the ticket will be verified against the locally stored service key. If not set, default value is true. .Pp .Fn krb5_verify_opt_set_service sets the .Fa service principal that user of .Fa opt will use. If not set, the .Ql host service will be used. .Pp .Fn krb5_verify_opt_set_flags sets .Fa flags that user of .Fa opt will use. If the flag .Dv KRB5_VERIFY_LREALMS is used, the .Fa principal will be modified like .Fn krb5_verify_user_lrealm modifies it. .Pp .Fn krb5_verify_user_opt function verifies the .Fa password supplied by a user. The principal whose password will be verified is specified in .Fa principal . Options the to the verification process is pass in in .Fa opt . .Sh EXAMPLES Here is a example program that verifies a password. it uses the .Ql host/`hostname` service principal in .Pa krb5.keytab . .Bd -literal #include int main(int argc, char **argv) { char *user; krb5_error_code error; krb5_principal princ; krb5_context context; if (argc != 2) errx(1, "usage: verify_passwd "); user = argv[1]; if (krb5_init_context(&context) < 0) errx(1, "krb5_init_context"); if ((error = krb5_parse_name(context, user, &princ)) != 0) krb5_err(context, 1, error, "krb5_parse_name"); error = krb5_verify_user(context, princ, NULL, NULL, TRUE, NULL); if (error) krb5_err(context, 1, error, "krb5_verify_user"); return 0; } .Ed .Sh SEE ALSO .Xr krb5_cc_gen_new 3 , .Xr krb5_cc_initialize 3 , .Xr krb5_cc_resolve 3 , .Xr krb5_err 3 , .Xr krb5_free_principal 3 , .Xr krb5_init_context 3 , .Xr krb5_kt_default 3 , .Xr krb5.conf 5 heimdal-7.5.0/lib/krb5/crypto-aes-sha1.c0000644000175000017500000001135613026237312015754 0ustar niknik/* * Copyright (c) 1997 - 2008 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "krb5_locl.h" /* * AES */ static struct _krb5_key_type keytype_aes128_sha1 = { KRB5_ENCTYPE_AES128_CTS_HMAC_SHA1_96, "aes-128", 128, 16, sizeof(struct _krb5_evp_schedule), NULL, _krb5_evp_schedule, _krb5_AES_SHA1_salt, NULL, _krb5_evp_cleanup, EVP_aes_128_cbc }; static struct _krb5_key_type keytype_aes256_sha1 = { KRB5_ENCTYPE_AES256_CTS_HMAC_SHA1_96, "aes-256", 256, 32, sizeof(struct _krb5_evp_schedule), NULL, _krb5_evp_schedule, _krb5_AES_SHA1_salt, NULL, _krb5_evp_cleanup, EVP_aes_256_cbc }; struct _krb5_checksum_type _krb5_checksum_hmac_sha1_aes128 = { CKSUMTYPE_HMAC_SHA1_96_AES_128, "hmac-sha1-96-aes128", 64, 12, F_KEYED | F_CPROOF | F_DERIVED, _krb5_SP_HMAC_SHA1_checksum, NULL }; struct _krb5_checksum_type _krb5_checksum_hmac_sha1_aes256 = { CKSUMTYPE_HMAC_SHA1_96_AES_256, "hmac-sha1-96-aes256", 64, 12, F_KEYED | F_CPROOF | F_DERIVED, _krb5_SP_HMAC_SHA1_checksum, NULL }; static krb5_error_code AES_SHA1_PRF(krb5_context context, krb5_crypto crypto, const krb5_data *in, krb5_data *out) { struct _krb5_checksum_type *ct = crypto->et->checksum; krb5_error_code ret; Checksum result; krb5_keyblock *derived; result.cksumtype = ct->type; ret = krb5_data_alloc(&result.checksum, ct->checksumsize); if (ret) { krb5_set_error_message(context, ret, N_("malloc: out memory", "")); return ret; } ret = (*ct->checksum)(context, NULL, in->data, in->length, 0, &result); if (ret) { krb5_data_free(&result.checksum); return ret; } if (result.checksum.length < crypto->et->blocksize) krb5_abortx(context, "internal prf error"); derived = NULL; ret = krb5_derive_key(context, crypto->key.key, crypto->et->type, "prf", 3, &derived); if (ret) krb5_abortx(context, "krb5_derive_key"); ret = krb5_data_alloc(out, crypto->et->blocksize); if (ret) krb5_abortx(context, "malloc failed"); { const EVP_CIPHER *c = (*crypto->et->keytype->evp)(); EVP_CIPHER_CTX ctx; EVP_CIPHER_CTX_init(&ctx); /* ivec all zero */ EVP_CipherInit_ex(&ctx, c, NULL, derived->keyvalue.data, NULL, 1); EVP_Cipher(&ctx, out->data, result.checksum.data, crypto->et->blocksize); EVP_CIPHER_CTX_cleanup(&ctx); } krb5_data_free(&result.checksum); krb5_free_keyblock(context, derived); return ret; } struct _krb5_encryption_type _krb5_enctype_aes128_cts_hmac_sha1 = { ETYPE_AES128_CTS_HMAC_SHA1_96, "aes128-cts-hmac-sha1-96", "aes128-cts", 16, 1, 16, &keytype_aes128_sha1, &_krb5_checksum_sha1, &_krb5_checksum_hmac_sha1_aes128, F_DERIVED | F_RFC3961_ENC | F_RFC3961_KDF, _krb5_evp_encrypt_cts, 16, AES_SHA1_PRF }; struct _krb5_encryption_type _krb5_enctype_aes256_cts_hmac_sha1 = { ETYPE_AES256_CTS_HMAC_SHA1_96, "aes256-cts-hmac-sha1-96", "aes256-cts", 16, 1, 16, &keytype_aes256_sha1, &_krb5_checksum_sha1, &_krb5_checksum_hmac_sha1_aes256, F_DERIVED | F_RFC3961_ENC | F_RFC3961_KDF, _krb5_evp_encrypt_cts, 16, AES_SHA1_PRF }; heimdal-7.5.0/lib/krb5/krb5_openlog.cat30000644000175000017500000002352413212450757016041 0ustar niknik KRB5_OPENLOG(3) BSD Library Functions Manual KRB5_OPENLOG(3) NNAAMMEE kkrrbb55__iinniittlloogg, kkrrbb55__ooppeennlloogg, kkrrbb55__cclloosseelloogg, kkrrbb55__aaddddlloogg__ddeesstt, kkrrbb55__aaddddlloogg__ffuunncc, kkrrbb55__lloogg, kkrrbb55__vvlloogg, kkrrbb55__lloogg__mmssgg, kkrrbb55__vvlloogg__mmssgg -- Heimdal logging functions LLIIBBRRAARRYY Kerberos 5 Library (libkrb5, -lkrb5) SSYYNNOOPPSSIISS ##iinncclluuddee <> _t_y_p_e_d_e_f _v_o_i_d (**kkrrbb55__lloogg__lloogg__ffuunncc__tt)(_c_o_n_s_t _c_h_a_r _*_t_i_m_e, _c_o_n_s_t _c_h_a_r _*_m_e_s_s_a_g_e, _v_o_i_d _*_d_a_t_a); _t_y_p_e_d_e_f _v_o_i_d (**kkrrbb55__lloogg__cclloossee__ffuunncc__tt)(_v_o_i_d _*_d_a_t_a); _k_r_b_5___e_r_r_o_r___c_o_d_e kkrrbb55__aaddddlloogg__ddeesstt(_k_r_b_5___c_o_n_t_e_x_t _c_o_n_t_e_x_t, _k_r_b_5___l_o_g___f_a_c_i_l_i_t_y _*_f_a_c_i_l_i_t_y, _c_o_n_s_t _c_h_a_r _*_d_e_s_t_i_n_a_t_i_o_n); _k_r_b_5___e_r_r_o_r___c_o_d_e kkrrbb55__aaddddlloogg__ffuunncc(_k_r_b_5___c_o_n_t_e_x_t _c_o_n_t_e_x_t, _k_r_b_5___l_o_g___f_a_c_i_l_i_t_y _*_f_a_c_i_l_i_t_y, _i_n_t _m_i_n, _i_n_t _m_a_x, _k_r_b_5___l_o_g___l_o_g___f_u_n_c___t _l_o_g, _k_r_b_5___l_o_g___c_l_o_s_e___f_u_n_c___t _c_l_o_s_e, _v_o_i_d _*_d_a_t_a); _k_r_b_5___e_r_r_o_r___c_o_d_e kkrrbb55__cclloosseelloogg(_k_r_b_5___c_o_n_t_e_x_t _c_o_n_t_e_x_t, _k_r_b_5___l_o_g___f_a_c_i_l_i_t_y _*_f_a_c_i_l_i_t_y); _k_r_b_5___e_r_r_o_r___c_o_d_e kkrrbb55__iinniittlloogg(_k_r_b_5___c_o_n_t_e_x_t _c_o_n_t_e_x_t, _c_o_n_s_t _c_h_a_r _*_p_r_o_g_r_a_m, _k_r_b_5___l_o_g___f_a_c_i_l_i_t_y _*_*_f_a_c_i_l_i_t_y); _k_r_b_5___e_r_r_o_r___c_o_d_e kkrrbb55__lloogg(_k_r_b_5___c_o_n_t_e_x_t _c_o_n_t_e_x_t, _k_r_b_5___l_o_g___f_a_c_i_l_i_t_y _*_f_a_c_i_l_i_t_y, _i_n_t _l_e_v_e_l, _c_o_n_s_t _c_h_a_r _*_f_o_r_m_a_t, _._._.); _k_r_b_5___e_r_r_o_r___c_o_d_e kkrrbb55__lloogg__mmssgg(_k_r_b_5___c_o_n_t_e_x_t _c_o_n_t_e_x_t, _k_r_b_5___l_o_g___f_a_c_i_l_i_t_y _*_f_a_c_i_l_i_t_y, _c_h_a_r _*_*_r_e_p_l_y, _i_n_t _l_e_v_e_l, _c_o_n_s_t _c_h_a_r _*_f_o_r_m_a_t, _._._.); _k_r_b_5___e_r_r_o_r___c_o_d_e kkrrbb55__ooppeennlloogg(_k_r_b_5___c_o_n_t_e_x_t _c_o_n_t_e_x_t, _c_o_n_s_t _c_h_a_r _*_p_r_o_g_r_a_m, _k_r_b_5___l_o_g___f_a_c_i_l_i_t_y _*_*_f_a_c_i_l_i_t_y); _k_r_b_5___e_r_r_o_r___c_o_d_e kkrrbb55__vvlloogg(_k_r_b_5___c_o_n_t_e_x_t _c_o_n_t_e_x_t, _k_r_b_5___l_o_g___f_a_c_i_l_i_t_y _*_f_a_c_i_l_i_t_y, _i_n_t _l_e_v_e_l, _c_o_n_s_t _c_h_a_r _*_f_o_r_m_a_t, _v_a___l_i_s_t _a_r_g_l_i_s_t); _k_r_b_5___e_r_r_o_r___c_o_d_e kkrrbb55__vvlloogg__mmssgg(_k_r_b_5___c_o_n_t_e_x_t _c_o_n_t_e_x_t, _k_r_b_5___l_o_g___f_a_c_i_l_i_t_y _*_f_a_c_i_l_i_t_y, _c_h_a_r _*_*_r_e_p_l_y, _i_n_t _l_e_v_e_l, _c_o_n_s_t _c_h_a_r _*_f_o_r_m_a_t, _v_a___l_i_s_t _a_r_g_l_i_s_t); DDEESSCCRRIIPPTTIIOONN These functions logs messages to one or more destinations. The kkrrbb55__ooppeennlloogg() function creates a logging _f_a_c_i_l_i_t_y, that is used to log messages. A facility consists of one or more destinations (which can be files or syslog or some other device). The _p_r_o_g_r_a_m parameter should be the generic name of the program that is doing the logging. This name is used to lookup which destinations to use. This information is contained in the logging section of the _k_r_b_5_._c_o_n_f configuration file. If no entry is found for _p_r_o_g_r_a_m, the entry for default is used, or if that is miss- ing too, SYSLOG will be used as destination. To close a logging facility, use the kkrrbb55__cclloosseelloogg() function. To log a message to a facility use one of the functions kkrrbb55__lloogg(), kkrrbb55__lloogg__mmssgg(), kkrrbb55__vvlloogg(), or kkrrbb55__vvlloogg__mmssgg(). The functions ending in _msg return in _r_e_p_l_y a pointer to the message that just got logged. This string is allocated, and should be freed with ffrreeee(). The _f_o_r_m_a_t is a standard pprriinnttff() style format string (but see the BUGS section). If you want better control of where things gets logged, you can instead of using kkrrbb55__ooppeennlloogg() call kkrrbb55__iinniittlloogg(), which just initializes a facility, but doesn't define any actual logging destinations. You can then add destinations with the kkrrbb55__aaddddlloogg__ddeesstt() and kkrrbb55__aaddddlloogg__ffuunncc() functions. The first of these takes a string specifying a logging desti- nation, and adds this to the facility. If you want to do some non-stan- dard logging you can use the kkrrbb55__aaddddlloogg__ffuunncc() function, which takes a function to use when logging. The _l_o_g function is called for each mes- sage with _t_i_m_e being a string specifying the current time, and _m_e_s_s_a_g_e the message to log. _c_l_o_s_e is called when the facility is closed. You can pass application specific data in the _d_a_t_a parameter. The _m_i_n and _m_a_x parameter are the same as in a destination (defined below). To specify a max of infinity, pass -1. kkrrbb55__ooppeennlloogg() calls kkrrbb55__iinniittlloogg() and then calls kkrrbb55__aaddddlloogg__ddeesstt() for each destination found. DDeessttiinnaattiioonnss The defined destinations (as specified in _k_r_b_5_._c_o_n_f) follows: STDERR This logs to the program's stderr. FILE:_/_f_i_l_e FILE=_/_f_i_l_e Log to the specified file. The form using a colon appends to the file, the form with an equal truncates the file. The trun- cating form keeps the file open, while the appending form closes it after each log message (which makes it possible to rotate logs). The truncating form is mainly for compatibility with the MIT libkrb5. DEVICE=_/_d_e_v_i_c_e This logs to the specified device, at present this is the same as FILE:/device. CONSOLE Log to the console, this is the same as DEVICE=/dev/console. SYSLOG[:priority[:facility]] Send messages to the syslog system, using priority, and facil- ity. To get the name for one of these, you take the name of the macro passed to syslog(3), and remove the leading LOG_ (LOG_NOTICE becomes NOTICE). The default values (as well as the values used for unrecognised values), are ERR, and AUTH, respectively. See syslog(3) for a list of priorities and facilities. Each destination may optionally be prepended with a range of logging lev- els, specified as min-max/. If the _l_e_v_e_l parameter to kkrrbb55__lloogg() is within this range (inclusive) the message gets logged to this destina- tion, otherwise not. Either of the min and max valued may be omitted, in this case min is assumed to be zero, and max is assumed to be infinity. If you don't include a dash, both min and max gets set to the specified value. If no range is specified, all messages gets logged. EEXXAAMMPPLLEESS [logging] kdc = 0/FILE:/var/log/kdc.log kdc = 1-/SYSLOG:INFO:USER default = STDERR This will log all messages from the kkddcc program with level 0 to _/_v_a_r_/_l_o_g_/_k_d_c_._l_o_g, other messages will be logged to syslog with priority LOG_INFO, and facility LOG_USER. All other programs will log all mes- sages to their stderr. SSEEEE AALLSSOO syslog(3), krb5.conf(5) BBUUGGSS These functions use aasspprriinnttff() to format the message. If your operating system does not have a working aasspprriinnttff(), a replacement will be used. At present this replacement does not handle some correct conversion specifi- cations (like floating point numbers). Until this is fixed, the use of these conversions should be avoided. If logging is done to the syslog facility, these functions might not be thread-safe, depending on the implementation of ooppeennlloogg(), and ssyysslloogg(). HEIMDAL August 6, 1997 HEIMDAL heimdal-7.5.0/lib/krb5/free.c0000644000175000017500000000400612136107750013752 0ustar niknik/* * Copyright (c) 1997 - 1999, 2004 - 2005 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "krb5_locl.h" KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_free_kdc_rep(krb5_context context, krb5_kdc_rep *rep) { free_KDC_REP(&rep->kdc_rep); free_EncTGSRepPart(&rep->enc_part); free_KRB_ERROR(&rep->error); memset(rep, 0, sizeof(*rep)); return 0; } KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_xfree (void *ptr) { free (ptr); return 0; } heimdal-7.5.0/lib/krb5/kerberos.cat80000644000175000017500000000602413212450757015270 0ustar niknik KERBEROS(8) BSD System Manager's Manual KERBEROS(8) NNAAMMEE kkeerrbbeerrooss -- introduction to the Kerberos system DDEESSCCRRIIPPTTIIOONN Kerberos is a network authentication system. Its purpose is to securely authenticate users and services in an insecure network environment. This is done with a Kerberos server acting as a trusted third party, keeping a database with secret keys for all users and services (collec- tively called _p_r_i_n_c_i_p_a_l_s). Each principal belongs to exactly one _r_e_a_l_m, which is the administrative domain in Kerberos. A realm usually corresponds to an organisation, and the realm should normally be derived from that organisation's domain name. A realm is served by one or more Kerberos servers. The authentication process involves exchange of `tickets' and `authenticators' which together prove the principal's identity. When you login to the Kerberos system, either through the normal system login or with the kinit(1) program, you acquire a _t_i_c_k_e_t _g_r_a_n_t_i_n_g _t_i_c_k_e_t which allows you to get new tickets for other services, such as tteellnneett or ffttpp, without giving your password. For more information on how Kerberos works, and other general Kerberos questions see the Kerberos FAQ at hhttttpp::////wwwwww..ccmmff..nnrrll..nnaavvyy..mmiill//kkrrbb//kkeerrbbeerrooss--ffaaqq..hhttmmll. For setup instructions see the Heimdal Texinfo manual. SSEEEE AALLSSOO ftp(1), kdestroy(1), kinit(1), klist(1), kpasswd(1), telnet(1), krb5(3), krb5.conf(5), kadmin(1), kdc(8), ktutil(1) HHIISSTTOORRYY The Kerberos authentication system was developed in the late 1980's as part of the Athena Project at the Massachusetts Institute of Technology. Versions one through three never reached outside MIT, but version 4 was (and still is) quite popular, especially in the academic community, but is also used in commercial products like the AFS filesystem. The problems with version 4 are that it has many limitations, the code was not too well written (since it had been developed over a long time), and it has a number of known security problems. To resolve many of these issues work on version five started, and resulted in IETF RFC 1510 in 1993. IETF RFC 1510 was obsoleted in 2005 with IETF RFC 4120, also known as Kerberos clarifications. With the arrival of IETF RFC 4120, the work on adding extensibility and internationalization have started (Kerberos extensions), and a new RFC will hopefully appear soon. This manual page is part of the HHeeiimmddaall Kerberos 5 distribution, which has been in development at the Royal Institute of Technology in Stock- holm, Sweden, since about 1997. HEIMDAL Jun 27, 2013 HEIMDAL heimdal-7.5.0/lib/krb5/convert_creds.c0000644000175000017500000000672513026237312015700 0ustar niknik/* * Copyright (c) 1997 - 2004 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "krb5_locl.h" #include "krb5-v4compat.h" #ifndef HEIMDAL_SMALLER /** * Convert the v5 credentials in in_cred to v4-dito in v4creds. This * is done by sending them to the 524 function in the KDC. If * `in_cred' doesn't contain a DES session key, then a new one is * gotten from the KDC and stored in the cred cache `ccache'. * * @param context Kerberos 5 context. * @param in_cred the credential to convert * @param v4creds the converted credential * * @return Returns 0 to indicate success. Otherwise an kerberos et * error code is returned, see krb5_get_error_message(). * * @ingroup krb5_v4compat */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb524_convert_creds_kdc(krb5_context context, krb5_creds *in_cred, struct credentials *v4creds) KRB5_DEPRECATED_FUNCTION("Use X instead") { memset(v4creds, 0, sizeof(*v4creds)); krb5_set_error_message(context, EINVAL, N_("krb524_convert_creds_kdc not supported", "")); return EINVAL; } /** * Convert the v5 credentials in in_cred to v4-dito in v4creds, * check the credential cache ccache before checking with the KDC. * * @param context Kerberos 5 context. * @param ccache credential cache used to check for des-ticket. * @param in_cred the credential to convert * @param v4creds the converted credential * * @return Returns 0 to indicate success. Otherwise an kerberos et * error code is returned, see krb5_get_error_message(). * * @ingroup krb5_v4compat */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb524_convert_creds_kdc_ccache(krb5_context context, krb5_ccache ccache, krb5_creds *in_cred, struct credentials *v4creds) KRB5_DEPRECATED_FUNCTION("Use X instead") { memset(v4creds, 0, sizeof(*v4creds)); krb5_set_error_message(context, EINVAL, N_("krb524_convert_creds_kdc_ccache not supported", "")); return EINVAL; } #endif heimdal-7.5.0/lib/krb5/time.c0000644000175000017500000000753612136107750014002 0ustar niknik/* * Copyright (c) 1997-2004 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "krb5_locl.h" /** * Set the absolute time that the caller knows the kdc has so the * kerberos library can calculate the relative diffrence beteen the * KDC time and local system time. * * @param context Keberos 5 context. * @param sec The applications new of "now" in seconds * @param usec The applications new of "now" in micro seconds * @return Kerberos 5 error code, see krb5_get_error_message(). * * @ingroup krb5 */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_set_real_time (krb5_context context, krb5_timestamp sec, int32_t usec) { struct timeval tv; gettimeofday(&tv, NULL); context->kdc_sec_offset = sec - tv.tv_sec; /** * If the caller passes in a negative usec, its assumed to be * unknown and the function will use the current time usec. */ if (usec >= 0) { context->kdc_usec_offset = usec - tv.tv_usec; if (context->kdc_usec_offset < 0) { context->kdc_sec_offset--; context->kdc_usec_offset += 1000000; } } else context->kdc_usec_offset = tv.tv_usec; return 0; } /* * return ``corrected'' time in `timeret'. */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_timeofday (krb5_context context, krb5_timestamp *timeret) { *timeret = time(NULL) + context->kdc_sec_offset; return 0; } /* * like gettimeofday but with time correction to the KDC */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_us_timeofday (krb5_context context, krb5_timestamp *sec, int32_t *usec) { struct timeval tv; gettimeofday (&tv, NULL); *sec = tv.tv_sec + context->kdc_sec_offset; *usec = tv.tv_usec; /* XXX */ return 0; } KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_format_time(krb5_context context, time_t t, char *s, size_t len, krb5_boolean include_time) { struct tm *tm; if(context->log_utc) tm = gmtime (&t); else tm = localtime(&t); if(tm == NULL || strftime(s, len, include_time ? context->time_fmt : context->date_fmt, tm) == 0) snprintf(s, len, "%ld", (long)t); return 0; } KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_string_to_deltat(const char *string, krb5_deltat *deltat) { if((*deltat = parse_time(string, "s")) == -1) return KRB5_DELTAT_BADFORMAT; return 0; } heimdal-7.5.0/lib/krb5/krb5_set_password.cat30000644000175000017500000001105213212450757017104 0ustar niknik KRB5_SET_PASSWORD(3) BSD Library Functions Manual KRB5_SET_PASSWORD(3) NNAAMMEE kkrrbb55__cchhaannggee__ppaasssswwoorrdd, kkrrbb55__sseett__ppaasssswwoorrdd, kkrrbb55__sseett__ppaasssswwoorrdd__uussiinngg__ccccaacchhee, kkrrbb55__ppaasssswwdd__rreessuulltt__ttoo__ssttrriinngg -- change password functions LLIIBBRRAARRYY Kerberos 5 Library (libkrb5, -lkrb5) SSYYNNOOPPSSIISS ##iinncclluuddee <> _k_r_b_5___e_r_r_o_r___c_o_d_e kkrrbb55__cchhaannggee__ppaasssswwoorrdd(_k_r_b_5___c_o_n_t_e_x_t _c_o_n_t_e_x_t, _k_r_b_5___c_r_e_d_s _*_c_r_e_d_s, _c_h_a_r _*_n_e_w_p_w, _i_n_t _*_r_e_s_u_l_t___c_o_d_e, _k_r_b_5___d_a_t_a _*_r_e_s_u_l_t___c_o_d_e___s_t_r_i_n_g, _k_r_b_5___d_a_t_a _*_r_e_s_u_l_t___s_t_r_i_n_g); _k_r_b_5___e_r_r_o_r___c_o_d_e kkrrbb55__sseett__ppaasssswwoorrdd(_k_r_b_5___c_o_n_t_e_x_t _c_o_n_t_e_x_t, _k_r_b_5___c_r_e_d_s _*_c_r_e_d_s, _c_h_a_r _*_n_e_w_p_w, _k_r_b_5___p_r_i_n_c_i_p_a_l _t_a_r_g_p_r_i_n_c, _i_n_t _*_r_e_s_u_l_t___c_o_d_e, _k_r_b_5___d_a_t_a _*_r_e_s_u_l_t___c_o_d_e___s_t_r_i_n_g, _k_r_b_5___d_a_t_a _*_r_e_s_u_l_t___s_t_r_i_n_g); _k_r_b_5___e_r_r_o_r___c_o_d_e kkrrbb55__sseett__ppaasssswwoorrdd__uussiinngg__ccccaacchhee(_k_r_b_5___c_o_n_t_e_x_t _c_o_n_t_e_x_t, _k_r_b_5___c_c_a_c_h_e _c_c_a_c_h_e, _c_h_a_r _*_n_e_w_p_w, _k_r_b_5___p_r_i_n_c_i_p_a_l _t_a_r_g_p_r_i_n_c, _i_n_t _*_r_e_s_u_l_t___c_o_d_e, _k_r_b_5___d_a_t_a _*_r_e_s_u_l_t___c_o_d_e___s_t_r_i_n_g, _k_r_b_5___d_a_t_a _*_r_e_s_u_l_t___s_t_r_i_n_g); _c_o_n_s_t _c_h_a_r _* kkrrbb55__ppaasssswwdd__rreessuulltt__ttoo__ssttrriinngg(_k_r_b_5___c_o_n_t_e_x_t _c_o_n_t_e_x_t, _i_n_t _r_e_s_u_l_t); DDEESSCCRRIIPPTTIIOONN These functions change the password for a given principal. kkrrbb55__sseett__ppaasssswwoorrdd() and kkrrbb55__sseett__ppaasssswwoorrdd__uussiinngg__ccccaacchhee() are the newer of the three functions, and use a newer version of the protocol (and also fall back to the older set-password protocol if the newer protocol doesn't work). kkrrbb55__cchhaannggee__ppaasssswwoorrdd() sets the password _n_e_w_p_a_s_s_w_d for the client princi- pal in _c_r_e_d_s. The server principal of creds must be kadmin/changepw. kkrrbb55__sseett__ppaasssswwoorrdd() and kkrrbb55__sseett__ppaasssswwoorrdd__uussiinngg__ccccaacchhee() change the pass- word for the principal _t_a_r_g_p_r_i_n_c. kkrrbb55__sseett__ppaasssswwoorrdd() requires that the credential for kadmin/changepw@REALM is in _c_r_e_d_s. If the user caller isn't an adminis- trator, this credential needs to be an initial credential, see krb5_get_init_creds(3) how to get such credentials. kkrrbb55__sseett__ppaasssswwoorrdd__uussiinngg__ccccaacchhee() will get the credential from _c_c_a_c_h_e. If _t_a_r_g_p_r_i_n_c is NULL, kkrrbb55__sseett__ppaasssswwoorrdd__uussiinngg__ccccaacchhee() uses the the default principal in _c_c_a_c_h_e and kkrrbb55__sseett__ppaasssswwoorrdd() uses the global the default principal. All three functions return an error in _r_e_s_u_l_t___c_o_d_e and maybe an error string to print in _r_e_s_u_l_t___s_t_r_i_n_g. kkrrbb55__ppaasssswwdd__rreessuulltt__ttoo__ssttrriinngg() returns an human readable string describ- ing the error code in _r_e_s_u_l_t___c_o_d_e from the kkrrbb55__sseett__ppaasssswwoorrdd() functions. SSEEEE AALLSSOO krb5_ccache(3), krb5_init_context(3) HEIMDAL July 15, 2004 HEIMDAL heimdal-7.5.0/lib/krb5/fast.c0000644000175000017500000000607013026237312013766 0ustar niknik/* * Copyright (c) 2011 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "krb5_locl.h" KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL _krb5_fast_cf2(krb5_context context, krb5_keyblock *key1, const char *pepper1, krb5_keyblock *key2, const char *pepper2, krb5_keyblock *armorkey, krb5_crypto *armor_crypto) { krb5_crypto crypto1, crypto2; krb5_data pa1, pa2; krb5_error_code ret; ret = krb5_crypto_init(context, key1, 0, &crypto1); if (ret) return ret; ret = krb5_crypto_init(context, key2, 0, &crypto2); if (ret) { krb5_crypto_destroy(context, crypto1); return ret; } pa1.data = rk_UNCONST(pepper1); pa1.length = strlen(pepper1); pa2.data = rk_UNCONST(pepper2); pa2.length = strlen(pepper2); ret = krb5_crypto_fx_cf2(context, crypto1, crypto2, &pa1, &pa2, key1->keytype, armorkey); krb5_crypto_destroy(context, crypto1); krb5_crypto_destroy(context, crypto2); if (ret) return ret; if (armor_crypto) { ret = krb5_crypto_init(context, armorkey, 0, armor_crypto); if (ret) krb5_free_keyblock_contents(context, armorkey); } return ret; } KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL _krb5_fast_armor_key(krb5_context context, krb5_keyblock *subkey, krb5_keyblock *sessionkey, krb5_keyblock *armorkey, krb5_crypto *armor_crypto) { return _krb5_fast_cf2(context, subkey, "subkeyarmor", sessionkey, "ticketarmor", armorkey, armor_crypto); } heimdal-7.5.0/lib/krb5/store-int.h0000644000175000017500000000416013026237312014760 0ustar niknik/* * Copyright (c) 2002 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #ifndef __store_int_h__ #define __store_int_h__ struct krb5_storage_data { void *data; ssize_t (*fetch)(struct krb5_storage_data*, void*, size_t); ssize_t (*store)(struct krb5_storage_data*, const void*, size_t); off_t (*seek)(struct krb5_storage_data*, off_t, int); int (*trunc)(struct krb5_storage_data*, off_t); int (*fsync)(struct krb5_storage_data*); void (*free)(struct krb5_storage_data*); krb5_flags flags; int eof_code; size_t max_alloc; }; #endif /* __store_int_h__ */ heimdal-7.5.0/lib/krb5/get_default_realm.c0000644000175000017500000000524313026237312016475 0ustar niknik/* * Copyright (c) 1997 - 2001, 2004 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "krb5_locl.h" /* * Return a NULL-terminated list of default realms in `realms'. * Free this memory with krb5_free_host_realm. */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_get_default_realms (krb5_context context, krb5_realm **realms) { if (context->default_realms == NULL) { krb5_error_code ret = krb5_set_default_realm (context, NULL); if (ret) return KRB5_CONFIG_NODEFREALM; } return krb5_copy_host_realm (context, context->default_realms, realms); } /* * Return the first default realm. For compatibility. */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_get_default_realm(krb5_context context, krb5_realm *realm) { krb5_error_code ret; char *res; if (context->default_realms == NULL || context->default_realms[0] == NULL) { krb5_clear_error_message(context); ret = krb5_set_default_realm (context, NULL); if (ret) return ret; } res = strdup (context->default_realms[0]); if (res == NULL) return krb5_enomem(context); *realm = res; return 0; } heimdal-7.5.0/lib/krb5/ccache_plugin.h0000644000175000017500000000326012136107750015623 0ustar niknik/*********************************************************************** * Copyright (c) 2010, Secure Endpoints Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * - Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. * **********************************************************************/ #ifndef HEIMDAL_KRB5_CCACHE_PLUGIN_H #define HEIMDAL_KRB5_CCACHE_PLUGIN_H 1 #include #define KRB5_PLUGIN_CCACHE "ccache_ops" #endif /* HEIMDAL_KRB5_CCACHE_PLUGIN_H */ heimdal-7.5.0/lib/krb5/warn.c0000644000175000017500000002257613062303006014003 0ustar niknik/* * Copyright (c) 1997 - 2001 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "krb5_locl.h" #include static krb5_error_code _warnerr(krb5_context context, int do_errtext, krb5_error_code code, int level, const char *fmt, va_list ap) __attribute__ ((__format__ (__printf__, 5, 0))); static krb5_error_code _warnerr(krb5_context context, int do_errtext, krb5_error_code code, int level, const char *fmt, va_list ap) { char xfmt[7] = ""; const char *args[2], **arg; char *msg = NULL; const char *err_str = NULL; krb5_error_code ret; args[0] = args[1] = NULL; arg = args; if(fmt){ strlcat(xfmt, "%s", sizeof(xfmt)); if(do_errtext) strlcat(xfmt, ": ", sizeof(xfmt)); ret = vasprintf(&msg, fmt, ap); if(ret < 0 || msg == NULL) return ENOMEM; *arg++ = msg; } if(context && do_errtext){ strlcat(xfmt, "%s", sizeof(xfmt)); err_str = krb5_get_error_message(context, code); if (err_str != NULL) { *arg = err_str; } else { *arg= ""; } } if(context && context->warn_dest) krb5_log(context, context->warn_dest, level, xfmt, args[0], args[1]); else warnx(xfmt, args[0], args[1]); free(msg); krb5_free_error_message(context, err_str); return 0; } #define FUNC(ETEXT, CODE, LEVEL) \ krb5_error_code ret; \ va_list ap; \ va_start(ap, fmt); \ ret = _warnerr(context, ETEXT, CODE, LEVEL, fmt, ap); \ va_end(ap); #define FUNC_NORET(ETEXT, CODE, LEVEL) \ va_list ap; \ va_start(ap, fmt); \ (void) _warnerr(context, ETEXT, CODE, LEVEL, fmt, ap); \ va_end(ap); #undef __attribute__ #define __attribute__(X) /** * Log a warning to the log, default stderr, include the error from * the last failure. * * @param context A Kerberos 5 context. * @param code error code of the last error * @param fmt message to print * @param ap arguments * * @ingroup krb5_error */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_vwarn(krb5_context context, krb5_error_code code, const char *fmt, va_list ap) __attribute__ ((__format__ (__printf__, 3, 0))) { return _warnerr(context, 1, code, 1, fmt, ap); } /** * Log a warning to the log, default stderr, include the error from * the last failure. * * @param context A Kerberos 5 context. * @param code error code of the last error * @param fmt message to print * * @ingroup krb5_error */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_warn(krb5_context context, krb5_error_code code, const char *fmt, ...) __attribute__ ((__format__ (__printf__, 3, 4))) { FUNC(1, code, 1); return ret; } /** * Log a warning to the log, default stderr. * * @param context A Kerberos 5 context. * @param fmt message to print * @param ap arguments * * @ingroup krb5_error */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_vwarnx(krb5_context context, const char *fmt, va_list ap) __attribute__ ((__format__ (__printf__, 2, 0))) { return _warnerr(context, 0, 0, 1, fmt, ap); } /** * Log a warning to the log, default stderr. * * @param context A Kerberos 5 context. * @param fmt message to print * * @ingroup krb5_error */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_warnx(krb5_context context, const char *fmt, ...) __attribute__ ((__format__ (__printf__, 2, 3))) { FUNC(0, 0, 1); return ret; } /** * Log a warning to the log, default stderr, include bthe error from * the last failure and then exit. * * @param context A Kerberos 5 context * @param eval the exit code to exit with * @param code error code of the last error * @param fmt message to print * @param ap arguments * * @ingroup krb5_error */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_verr(krb5_context context, int eval, krb5_error_code code, const char *fmt, va_list ap) __attribute__ ((__noreturn__, __format__ (__printf__, 4, 0))) { _warnerr(context, 1, code, 0, fmt, ap); exit(eval); UNREACHABLE(return 0); } /** * Log a warning to the log, default stderr, include bthe error from * the last failure and then exit. * * @param context A Kerberos 5 context * @param eval the exit code to exit with * @param code error code of the last error * @param fmt message to print * * @ingroup krb5_error */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_err(krb5_context context, int eval, krb5_error_code code, const char *fmt, ...) __attribute__ ((__noreturn__, __format__ (__printf__, 4, 5))) { FUNC_NORET(1, code, 0); exit(eval); UNREACHABLE(return 0); } /** * Log a warning to the log, default stderr, and then exit. * * @param context A Kerberos 5 context * @param eval the exit code to exit with * @param fmt message to print * @param ap arguments * * @ingroup krb5_error */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_verrx(krb5_context context, int eval, const char *fmt, va_list ap) __attribute__ ((__noreturn__, __format__ (__printf__, 3, 0))) { _warnerr(context, 0, 0, 0, fmt, ap); exit(eval); UNREACHABLE(return 0); } /** * Log a warning to the log, default stderr, and then exit. * * @param context A Kerberos 5 context * @param eval the exit code to exit with * @param fmt message to print * * @ingroup krb5_error */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_errx(krb5_context context, int eval, const char *fmt, ...) __attribute__ ((__noreturn__, __format__ (__printf__, 3, 4))) { FUNC_NORET(0, 0, 0); exit(eval); UNREACHABLE(return 0); } /** * Log a warning to the log, default stderr, include bthe error from * the last failure and then abort. * * @param context A Kerberos 5 context * @param code error code of the last error * @param fmt message to print * @param ap arguments * * @ingroup krb5_error */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_vabort(krb5_context context, krb5_error_code code, const char *fmt, va_list ap) __attribute__ ((__noreturn__, __format__ (__printf__, 3, 0))) { _warnerr(context, 1, code, 0, fmt, ap); abort(); UNREACHABLE(return 0); } /** * Log a warning to the log, default stderr, include the error from * the last failure and then abort. * * @param context A Kerberos 5 context * @param code error code of the last error * @param fmt message to print * @param ... arguments for format string * * @ingroup krb5_error */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_abort(krb5_context context, krb5_error_code code, const char *fmt, ...) __attribute__ ((__noreturn__, __format__ (__printf__, 3, 4))) { FUNC_NORET(1, code, 0); abort(); UNREACHABLE(return 0); } KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_vabortx(krb5_context context, const char *fmt, va_list ap) __attribute__ ((__noreturn__, __format__ (__printf__, 2, 0))) { _warnerr(context, 0, 0, 0, fmt, ap); abort(); UNREACHABLE(return 0); } /** * Log a warning to the log, default stderr, and then abort. * * @param context A Kerberos 5 context * @param fmt printf format string of message to print * @param ... arguments for format string * * @ingroup krb5_error */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_abortx(krb5_context context, const char *fmt, ...) __attribute__ ((__noreturn__, __format__ (__printf__, 2, 3))) { FUNC_NORET(0, 0, 0); abort(); UNREACHABLE(return 0); } /** * Set the default logging facility. * * @param context A Kerberos 5 context * @param fac Facility to use for logging. * * @ingroup krb5_error */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_set_warn_dest(krb5_context context, krb5_log_facility *fac) { context->warn_dest = fac; return 0; } /** * Get the default logging facility. * * @param context A Kerberos 5 context * * @ingroup krb5_error */ KRB5_LIB_FUNCTION krb5_log_facility * KRB5_LIB_CALL krb5_get_warn_dest(krb5_context context) { return context->warn_dest; } heimdal-7.5.0/lib/krb5/krb5_set_default_realm.30000644000175000017500000001045613026237312017356 0ustar niknik.\" Copyright (c) 2003 - 2005 Kungliga Tekniska Högskolan .\" (Royal Institute of Technology, Stockholm, Sweden). .\" All rights reserved. .\" .\" Redistribution and use in source and binary forms, with or without .\" modification, are permitted provided that the following conditions .\" are met: .\" .\" 1. Redistributions of source code must retain the above copyright .\" notice, this list of conditions and the following disclaimer. .\" .\" 2. Redistributions in binary form must reproduce the above copyright .\" notice, this list of conditions and the following disclaimer in the .\" documentation and/or other materials provided with the distribution. .\" .\" 3. Neither the name of the Institute nor the names of its contributors .\" may be used to endorse or promote products derived from this software .\" without specific prior written permission. .\" .\" THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND .\" ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE .\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE .\" ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE .\" FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL .\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS .\" OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) .\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT .\" LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF .\" SUCH DAMAGE. .\" .\" $Id$ .\" .Dd April 24, 2005 .Dt KRB5_SET_DEFAULT_REALM 3 .Os HEIMDAL .Sh NAME .Nm krb5_copy_host_realm , .Nm krb5_free_host_realm , .Nm krb5_get_default_realm , .Nm krb5_get_default_realms , .Nm krb5_get_host_realm , .Nm krb5_set_default_realm .Nd default and host realm read and manipulation routines .Sh LIBRARY Kerberos 5 Library (libkrb5, -lkrb5) .Sh SYNOPSIS .In krb5.h .Ft krb5_error_code .Fo krb5_copy_host_realm .Fa "krb5_context context" .Fa "const krb5_realm *from" .Fa "krb5_realm **to" .Fc .Ft krb5_error_code .Fo krb5_free_host_realm .Fa "krb5_context context" .Fa "krb5_realm *realmlist" .Fc .Ft krb5_error_code .Fo krb5_get_default_realm .Fa "krb5_context context" .Fa "krb5_realm *realm" .Fc .Ft krb5_error_code .Fo krb5_get_default_realms .Fa "krb5_context context" .Fa "krb5_realm **realm" .Fc .Ft krb5_error_code .Fo krb5_get_host_realm .Fa "krb5_context context" .Fa "const char *host" .Fa "krb5_realm **realms" .Fc .Ft krb5_error_code .Fo krb5_set_default_realm .Fa "krb5_context context" .Fa "const char *realm" .Fc .Sh DESCRIPTION .Fn krb5_copy_host_realm copies the list of realms from .Fa from to .Fa to . .Fa to should be freed by the caller using .Fa krb5_free_host_realm . .Pp .Fn krb5_free_host_realm frees all memory allocated by .Fa realmlist . .Pp .Fn krb5_get_default_realm returns the first default realm for this host. The realm returned should be freed with .Fn krb5_xfree . .Pp .Fn krb5_get_default_realms returns a .Dv NULL terminated list of default realms for this context. Realms returned by .Fn krb5_get_default_realms should be freed with .Fn krb5_free_host_realm . .Pp .Fn krb5_get_host_realm returns a .Dv NULL terminated list of realms for .Fa host by looking up the information in the .Li [domain_realm] in .Pa krb5.conf or in .Li DNS . If the mapping in .Li [domain_realm] results in the string .Li dns_locate , DNS is used to lookup the realm. .Pp When using .Li DNS to a resolve the domain for the host a.b.c, .Fn krb5_get_host_realm looks for a .Dv TXT resource record named .Li _kerberos.a.b.c , and if not found, it strips off the first component and tries a again (_kerberos.b.c) until it reaches the root. .Pp If there is no configuration or DNS information found, .Fn krb5_get_host_realm assumes it can use the domain part of the .Fa host to form a realm. Caller must free .Fa realmlist with .Fn krb5_free_host_realm . .Pp .Fn krb5_set_default_realm sets the default realm for the .Fa context . If .Dv NULL is used as a .Fa realm , the .Li [libdefaults]default_realm stanza in .Pa krb5.conf is used. If there is no such stanza in the configuration file, the .Fn krb5_get_host_realm function is used to form a default realm. .Sh SEE ALSO .Xr free 3 , .Xr krb5.conf 5 heimdal-7.5.0/lib/krb5/ticket.c0000644000175000017500000005305413131335114014314 0ustar niknik/* * Copyright (c) 1997 - 2001 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Portions Copyright (c) 2009 Apple Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "krb5_locl.h" /** * Free ticket and content * * @param context a Kerberos 5 context * @param ticket ticket to free * * @return Returns 0 to indicate success. Otherwise an kerberos et * error code is returned, see krb5_get_error_message(). * * @ingroup krb5 */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_free_ticket(krb5_context context, krb5_ticket *ticket) { free_EncTicketPart(&ticket->ticket); krb5_free_principal(context, ticket->client); krb5_free_principal(context, ticket->server); free(ticket); return 0; } /** * Copy ticket and content * * @param context a Kerberos 5 context * @param from ticket to copy * @param to new copy of ticket, free with krb5_free_ticket() * * @return Returns 0 to indicate success. Otherwise an kerberos et * error code is returned, see krb5_get_error_message(). * * @ingroup krb5 */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_copy_ticket(krb5_context context, const krb5_ticket *from, krb5_ticket **to) { krb5_error_code ret; krb5_ticket *tmp; *to = NULL; tmp = malloc(sizeof(*tmp)); if (tmp == NULL) return krb5_enomem(context); if((ret = copy_EncTicketPart(&from->ticket, &tmp->ticket))){ free(tmp); return ret; } ret = krb5_copy_principal(context, from->client, &tmp->client); if(ret){ free_EncTicketPart(&tmp->ticket); free(tmp); return ret; } ret = krb5_copy_principal(context, from->server, &tmp->server); if(ret){ krb5_free_principal(context, tmp->client); free_EncTicketPart(&tmp->ticket); free(tmp); return ret; } *to = tmp; return 0; } /** * Return client principal in ticket * * @param context a Kerberos 5 context * @param ticket ticket to copy * @param client client principal, free with krb5_free_principal() * * @return Returns 0 to indicate success. Otherwise an kerberos et * error code is returned, see krb5_get_error_message(). * * @ingroup krb5 */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_ticket_get_client(krb5_context context, const krb5_ticket *ticket, krb5_principal *client) { return krb5_copy_principal(context, ticket->client, client); } /** * Return server principal in ticket * * @param context a Kerberos 5 context * @param ticket ticket to copy * @param server server principal, free with krb5_free_principal() * * @return Returns 0 to indicate success. Otherwise an kerberos et * error code is returned, see krb5_get_error_message(). * * @ingroup krb5 */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_ticket_get_server(krb5_context context, const krb5_ticket *ticket, krb5_principal *server) { return krb5_copy_principal(context, ticket->server, server); } /** * Return end time of ticket * * @param context a Kerberos 5 context * @param ticket ticket to copy * * @return end time of ticket * * @ingroup krb5 */ KRB5_LIB_FUNCTION time_t KRB5_LIB_CALL krb5_ticket_get_endtime(krb5_context context, const krb5_ticket *ticket) { return ticket->ticket.endtime; } /** * Get the flags from the Kerberos ticket * * @param context Kerberos context * @param ticket Kerberos ticket * * @return ticket flags * * @ingroup krb5_ticket */ KRB5_LIB_FUNCTION unsigned long KRB5_LIB_CALL krb5_ticket_get_flags(krb5_context context, const krb5_ticket *ticket) { return TicketFlags2int(ticket->ticket.flags); } static int find_type_in_ad(krb5_context context, int type, krb5_data *data, krb5_boolean *found, krb5_boolean failp, krb5_keyblock *sessionkey, const AuthorizationData *ad, int level) { krb5_error_code ret = 0; size_t i; if (level > 9) { ret = ENOENT; /* XXX */ krb5_set_error_message(context, ret, N_("Authorization data nested deeper " "then %d levels, stop searching", ""), level); goto out; } /* * Only copy out the element the first time we get to it, we need * to run over the whole authorization data fields to check if * there are any container clases we need to care about. */ for (i = 0; i < ad->len; i++) { if (!*found && ad->val[i].ad_type == type) { ret = der_copy_octet_string(&ad->val[i].ad_data, data); if (ret) { krb5_set_error_message(context, ret, N_("malloc: out of memory", "")); goto out; } *found = TRUE; continue; } switch (ad->val[i].ad_type) { case KRB5_AUTHDATA_IF_RELEVANT: { AuthorizationData child; ret = decode_AuthorizationData(ad->val[i].ad_data.data, ad->val[i].ad_data.length, &child, NULL); if (ret) { krb5_set_error_message(context, ret, N_("Failed to decode " "IF_RELEVANT with %d", ""), (int)ret); goto out; } ret = find_type_in_ad(context, type, data, found, FALSE, sessionkey, &child, level + 1); free_AuthorizationData(&child); if (ret) goto out; break; } #if 0 /* XXX test */ case KRB5_AUTHDATA_KDC_ISSUED: { AD_KDCIssued child; ret = decode_AD_KDCIssued(ad->val[i].ad_data.data, ad->val[i].ad_data.length, &child, NULL); if (ret) { krb5_set_error_message(context, ret, N_("Failed to decode " "AD_KDCIssued with %d", ""), ret); goto out; } if (failp) { krb5_boolean valid; krb5_data buf; size_t len; ASN1_MALLOC_ENCODE(AuthorizationData, buf.data, buf.length, &child.elements, &len, ret); if (ret) { free_AD_KDCIssued(&child); krb5_clear_error_message(context); goto out; } if(buf.length != len) krb5_abortx(context, "internal error in ASN.1 encoder"); ret = krb5_c_verify_checksum(context, sessionkey, 19, &buf, &child.ad_checksum, &valid); krb5_data_free(&buf); if (ret) { free_AD_KDCIssued(&child); goto out; } if (!valid) { krb5_clear_error_message(context); ret = ENOENT; free_AD_KDCIssued(&child); goto out; } } ret = find_type_in_ad(context, type, data, found, failp, sessionkey, &child.elements, level + 1); free_AD_KDCIssued(&child); if (ret) goto out; break; } #endif case KRB5_AUTHDATA_AND_OR: if (!failp) break; ret = ENOENT; /* XXX */ krb5_set_error_message(context, ret, N_("Authorization data contains " "AND-OR element that is unknown to the " "application", "")); goto out; default: if (!failp) break; ret = ENOENT; /* XXX */ krb5_set_error_message(context, ret, N_("Authorization data contains " "unknown type (%d) ", ""), ad->val[i].ad_type); goto out; } } out: if (ret) { if (*found) { krb5_data_free(data); *found = 0; } } return ret; } KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL _krb5_get_ad(krb5_context context, const AuthorizationData *ad, krb5_keyblock *sessionkey, int type, krb5_data *data) { krb5_boolean found = FALSE; krb5_error_code ret; krb5_data_zero(data); if (ad == NULL) { krb5_set_error_message(context, ENOENT, N_("No authorization data", "")); return ENOENT; /* XXX */ } ret = find_type_in_ad(context, type, data, &found, TRUE, sessionkey, ad, 0); if (ret) return ret; if (!found) { krb5_set_error_message(context, ENOENT, N_("Have no authorization data of type %d", ""), type); return ENOENT; /* XXX */ } return 0; } /** * Extract the authorization data type of type from the ticket. Store * the field in data. This function is to use for kerberos * applications. * * @param context a Kerberos 5 context * @param ticket Kerberos ticket * @param type type to fetch * @param data returned data, free with krb5_data_free() * * @ingroup krb5 */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_ticket_get_authorization_data_type(krb5_context context, krb5_ticket *ticket, int type, krb5_data *data) { AuthorizationData *ad; krb5_error_code ret; krb5_boolean found = FALSE; krb5_data_zero(data); ad = ticket->ticket.authorization_data; if (ticket->ticket.authorization_data == NULL) { krb5_set_error_message(context, ENOENT, N_("Ticket have not authorization data", "")); return ENOENT; /* XXX */ } ret = find_type_in_ad(context, type, data, &found, TRUE, &ticket->ticket.key, ad, 0); if (ret) return ret; if (!found) { krb5_set_error_message(context, ENOENT, N_("Ticket have not " "authorization data of type %d", ""), type); return ENOENT; /* XXX */ } return 0; } static krb5_error_code check_server_referral(krb5_context context, krb5_kdc_rep *rep, unsigned flags, krb5_const_principal requested, krb5_const_principal returned, krb5_keyblock * key) { krb5_error_code ret; PA_ServerReferralData ref; krb5_crypto session; EncryptedData ed; size_t len; krb5_data data; PA_DATA *pa; int i = 0, cmp; if (rep->kdc_rep.padata == NULL) goto noreferral; pa = krb5_find_padata(rep->kdc_rep.padata->val, rep->kdc_rep.padata->len, KRB5_PADATA_SERVER_REFERRAL, &i); if (pa == NULL) goto noreferral; memset(&ed, 0, sizeof(ed)); memset(&ref, 0, sizeof(ref)); ret = decode_EncryptedData(pa->padata_value.data, pa->padata_value.length, &ed, &len); if (ret) return ret; if (len != pa->padata_value.length) { free_EncryptedData(&ed); krb5_set_error_message(context, KRB5KRB_AP_ERR_MODIFIED, N_("Referral EncryptedData wrong for realm %s", "realm"), requested->realm); return KRB5KRB_AP_ERR_MODIFIED; } ret = krb5_crypto_init(context, key, 0, &session); if (ret) { free_EncryptedData(&ed); return ret; } ret = krb5_decrypt_EncryptedData(context, session, KRB5_KU_PA_SERVER_REFERRAL, &ed, &data); free_EncryptedData(&ed); krb5_crypto_destroy(context, session); if (ret) return ret; ret = decode_PA_ServerReferralData(data.data, data.length, &ref, &len); if (ret) { krb5_data_free(&data); return ret; } krb5_data_free(&data); if (strcmp(requested->realm, returned->realm) != 0) { free_PA_ServerReferralData(&ref); krb5_set_error_message(context, KRB5KRB_AP_ERR_MODIFIED, N_("server ref realm mismatch, " "requested realm %s got back %s", ""), requested->realm, returned->realm); return KRB5KRB_AP_ERR_MODIFIED; } if (krb5_principal_is_krbtgt(context, returned)) { const char *realm = returned->name.name_string.val[1]; if (ref.referred_realm == NULL || strcmp(*ref.referred_realm, realm) != 0) { free_PA_ServerReferralData(&ref); krb5_set_error_message(context, KRB5KRB_AP_ERR_MODIFIED, N_("tgt returned with wrong ref", "")); return KRB5KRB_AP_ERR_MODIFIED; } } else if (krb5_principal_compare(context, returned, requested) == 0) { free_PA_ServerReferralData(&ref); krb5_set_error_message(context, KRB5KRB_AP_ERR_MODIFIED, N_("req princ no same as returned", "")); return KRB5KRB_AP_ERR_MODIFIED; } if (ref.requested_principal_name) { cmp = _krb5_principal_compare_PrincipalName(context, requested, ref.requested_principal_name); if (!cmp) { free_PA_ServerReferralData(&ref); krb5_set_error_message(context, KRB5KRB_AP_ERR_MODIFIED, N_("referred principal not same " "as requested", "")); return KRB5KRB_AP_ERR_MODIFIED; } } else if (flags & EXTRACT_TICKET_AS_REQ) { free_PA_ServerReferralData(&ref); krb5_set_error_message(context, KRB5KRB_AP_ERR_MODIFIED, N_("Requested principal missing on AS-REQ", "")); return KRB5KRB_AP_ERR_MODIFIED; } free_PA_ServerReferralData(&ref); return ret; noreferral: /* * Expect excact match or that we got a krbtgt */ if (krb5_principal_compare(context, requested, returned) != TRUE && (krb5_realm_compare(context, requested, returned) != TRUE && krb5_principal_is_krbtgt(context, returned) != TRUE)) { krb5_set_error_message(context, KRB5KRB_AP_ERR_MODIFIED, N_("Not same server principal returned " "as requested", "")); return KRB5KRB_AP_ERR_MODIFIED; } return 0; } /* * Verify referral data */ static krb5_error_code check_client_referral(krb5_context context, krb5_kdc_rep *rep, krb5_const_principal requested, krb5_const_principal mapped, krb5_keyblock const * key) { if (krb5_principal_compare(context, requested, mapped) == FALSE && !rep->enc_part.flags.enc_pa_rep) { krb5_set_error_message(context, KRB5KRB_AP_ERR_MODIFIED, N_("Not same client principal returned " "as requested", "")); return KRB5KRB_AP_ERR_MODIFIED; } return 0; } static krb5_error_code KRB5_CALLCONV decrypt_tkt (krb5_context context, krb5_keyblock *key, krb5_key_usage usage, krb5_const_pointer decrypt_arg, krb5_kdc_rep *dec_rep) { krb5_error_code ret; krb5_data data; size_t size; krb5_crypto crypto; ret = krb5_crypto_init(context, key, 0, &crypto); if (ret) return ret; ret = krb5_decrypt_EncryptedData (context, crypto, usage, &dec_rep->kdc_rep.enc_part, &data); krb5_crypto_destroy(context, crypto); if (ret) return ret; ret = decode_EncASRepPart(data.data, data.length, &dec_rep->enc_part, &size); if (ret) ret = decode_EncTGSRepPart(data.data, data.length, &dec_rep->enc_part, &size); krb5_data_free (&data); if (ret) { krb5_set_error_message(context, ret, N_("Failed to decode encpart in ticket", "")); return ret; } return 0; } KRB5_LIB_FUNCTION int KRB5_LIB_CALL _krb5_extract_ticket(krb5_context context, krb5_kdc_rep *rep, krb5_creds *creds, krb5_keyblock *key, krb5_const_pointer keyseed, krb5_key_usage key_usage, krb5_addresses *addrs, unsigned nonce, unsigned flags, krb5_data *request, krb5_decrypt_proc decrypt_proc, krb5_const_pointer decryptarg) { krb5_error_code ret; krb5_principal tmp_principal; size_t len = 0; time_t tmp_time; krb5_timestamp sec_now; /* decrypt */ if (decrypt_proc == NULL) decrypt_proc = decrypt_tkt; ret = (*decrypt_proc)(context, key, key_usage, decryptarg, rep); if (ret) goto out; if (rep->enc_part.flags.enc_pa_rep && request) { krb5_crypto crypto = NULL; Checksum cksum; PA_DATA *pa = NULL; int idx = 0; _krb5_debug(context, 5, "processing enc-ap-rep"); if (rep->enc_part.encrypted_pa_data == NULL || (pa = krb5_find_padata(rep->enc_part.encrypted_pa_data->val, rep->enc_part.encrypted_pa_data->len, KRB5_PADATA_REQ_ENC_PA_REP, &idx)) == NULL) { _krb5_debug(context, 5, "KRB5_PADATA_REQ_ENC_PA_REP missing"); ret = KRB5KRB_AP_ERR_MODIFIED; goto out; } ret = krb5_crypto_init(context, key, 0, &crypto); if (ret) goto out; ret = decode_Checksum(pa->padata_value.data, pa->padata_value.length, &cksum, NULL); if (ret) { krb5_crypto_destroy(context, crypto); goto out; } ret = krb5_verify_checksum(context, crypto, KRB5_KU_AS_REQ, request->data, request->length, &cksum); krb5_crypto_destroy(context, crypto); free_Checksum(&cksum); _krb5_debug(context, 5, "enc-ap-rep: %svalid", (ret == 0) ? "" : "in"); if (ret) goto out; } /* save session key */ creds->session.keyvalue.length = 0; creds->session.keyvalue.data = NULL; creds->session.keytype = rep->enc_part.key.keytype; ret = krb5_data_copy (&creds->session.keyvalue, rep->enc_part.key.keyvalue.data, rep->enc_part.key.keyvalue.length); if (ret) { krb5_clear_error_message(context); goto out; } /* compare client and save */ ret = _krb5_principalname2krb5_principal(context, &tmp_principal, rep->kdc_rep.cname, rep->kdc_rep.crealm); if (ret) goto out; /* check client referral and save principal */ /* anonymous here ? */ if((flags & EXTRACT_TICKET_ALLOW_CNAME_MISMATCH) == 0) { ret = check_client_referral(context, rep, creds->client, tmp_principal, &creds->session); if (ret) { krb5_free_principal (context, tmp_principal); goto out; } } krb5_free_principal (context, creds->client); creds->client = tmp_principal; /* check server referral and save principal */ ret = _krb5_principalname2krb5_principal (context, &tmp_principal, rep->enc_part.sname, rep->enc_part.srealm); if (ret) goto out; if((flags & EXTRACT_TICKET_ALLOW_SERVER_MISMATCH) == 0){ ret = check_server_referral(context, rep, flags, creds->server, tmp_principal, &creds->session); if (ret) { krb5_free_principal (context, tmp_principal); goto out; } } krb5_free_principal(context, creds->server); creds->server = tmp_principal; /* verify names */ if(flags & EXTRACT_TICKET_MATCH_REALM){ const char *srealm = krb5_principal_get_realm(context, creds->server); const char *crealm = krb5_principal_get_realm(context, creds->client); if (strcmp(rep->enc_part.srealm, srealm) != 0 || strcmp(rep->enc_part.srealm, crealm) != 0) { ret = KRB5KRB_AP_ERR_MODIFIED; krb5_clear_error_message(context); goto out; } } /* compare nonces */ if (nonce != (unsigned)rep->enc_part.nonce) { ret = KRB5KRB_AP_ERR_MODIFIED; krb5_set_error_message(context, ret, N_("malloc: out of memory", "")); goto out; } /* set kdc-offset */ krb5_timeofday (context, &sec_now); if (rep->enc_part.flags.initial && (flags & EXTRACT_TICKET_TIMESYNC) && context->kdc_sec_offset == 0 && krb5_config_get_bool (context, NULL, "libdefaults", "kdc_timesync", NULL)) { context->kdc_sec_offset = rep->enc_part.authtime - sec_now; krb5_timeofday (context, &sec_now); } /* check all times */ if (rep->enc_part.starttime) { tmp_time = *rep->enc_part.starttime; } else tmp_time = rep->enc_part.authtime; if (creds->times.starttime == 0 && labs(tmp_time - sec_now) > context->max_skew) { ret = KRB5KRB_AP_ERR_SKEW; krb5_set_error_message (context, ret, N_("time skew (%ld) larger than max (%ld)", ""), labs(tmp_time - sec_now), (long)context->max_skew); goto out; } if (creds->times.starttime != 0 && tmp_time != creds->times.starttime) { krb5_clear_error_message (context); ret = KRB5KRB_AP_ERR_MODIFIED; goto out; } creds->times.starttime = tmp_time; if (rep->enc_part.renew_till) { tmp_time = *rep->enc_part.renew_till; } else tmp_time = 0; if (creds->times.renew_till != 0 && tmp_time > creds->times.renew_till) { krb5_clear_error_message (context); ret = KRB5KRB_AP_ERR_MODIFIED; goto out; } creds->times.renew_till = tmp_time; creds->times.authtime = rep->enc_part.authtime; if (creds->times.endtime != 0 && rep->enc_part.endtime > creds->times.endtime) { krb5_clear_error_message (context); ret = KRB5KRB_AP_ERR_MODIFIED; goto out; } creds->times.endtime = rep->enc_part.endtime; if(rep->enc_part.caddr) krb5_copy_addresses (context, rep->enc_part.caddr, &creds->addresses); else if(addrs) krb5_copy_addresses (context, addrs, &creds->addresses); else { creds->addresses.len = 0; creds->addresses.val = NULL; } creds->flags.b = rep->enc_part.flags; creds->authdata.len = 0; creds->authdata.val = NULL; /* extract ticket */ ASN1_MALLOC_ENCODE(Ticket, creds->ticket.data, creds->ticket.length, &rep->kdc_rep.ticket, &len, ret); if(ret) goto out; if (creds->ticket.length != len) krb5_abortx(context, "internal error in ASN.1 encoder"); creds->second_ticket.length = 0; creds->second_ticket.data = NULL; out: memset (rep->enc_part.key.keyvalue.data, 0, rep->enc_part.key.keyvalue.length); return ret; } heimdal-7.5.0/lib/krb5/krb5_get_init_creds.cat30000644000175000017500000004545613212450756017367 0ustar niknik KRB5_GET_INIT_CREDS(3) BSD Library Functions Manual KRB5_GET_INIT_CREDS(3) NNAAMMEE kkrrbb55__ggeett__iinniitt__ccrreeddss, kkrrbb55__ggeett__iinniitt__ccrreeddss__kkeeyyttaabb, kkrrbb55__ggeett__iinniitt__ccrreeddss__oopptt, kkrrbb55__ggeett__iinniitt__ccrreeddss__oopptt__aalllloocc, kkrrbb55__ggeett__iinniitt__ccrreeddss__oopptt__ffrreeee, kkrrbb55__ggeett__iinniitt__ccrreeddss__oopptt__iinniitt, kkrrbb55__ggeett__iinniitt__ccrreeddss__oopptt__sseett__aaddddrreessss__lliisstt, kkrrbb55__ggeett__iinniitt__ccrreeddss__oopptt__sseett__aaddddrreesssslleessss, kkrrbb55__ggeett__iinniitt__ccrreeddss__oopptt__sseett__aannoonnyymmoouuss, kkrrbb55__ggeett__iinniitt__ccrreeddss__oopptt__sseett__ddeeffaauulltt__ffllaaggss, kkrrbb55__ggeett__iinniitt__ccrreeddss__oopptt__sseett__eettyyppee__lliisstt, kkrrbb55__ggeett__iinniitt__ccrreeddss__oopptt__sseett__ffoorrwwaarrddaabbllee, kkrrbb55__ggeett__iinniitt__ccrreeddss__oopptt__sseett__ppaa__ppaasssswwoorrdd, kkrrbb55__ggeett__iinniitt__ccrreeddss__oopptt__sseett__ppaaqq__rreeqquueesstt, kkrrbb55__ggeett__iinniitt__ccrreeddss__oopptt__sseett__pprreeaauutthh__lliisstt, kkrrbb55__ggeett__iinniitt__ccrreeddss__oopptt__sseett__pprrooxxiiaabbllee, kkrrbb55__ggeett__iinniitt__ccrreeddss__oopptt__sseett__rreenneeww__lliiffee, kkrrbb55__ggeett__iinniitt__ccrreeddss__oopptt__sseett__ssaalltt, kkrrbb55__ggeett__iinniitt__ccrreeddss__oopptt__sseett__ttkktt__lliiffee, kkrrbb55__ggeett__iinniitt__ccrreeddss__oopptt__sseett__ccaannoonniiccaalliizzee, kkrrbb55__ggeett__iinniitt__ccrreeddss__oopptt__sseett__wwiinn22kk, kkrrbb55__ggeett__iinniitt__ccrreeddss__ppaasssswwoorrdd, kkrrbb55__pprroommpptt, kkrrbb55__pprroommpptteerr__ppoossiixx -- Kerberos 5 initial authentication functions LLIIBBRRAARRYY Kerberos 5 Library (libkrb5, -lkrb5) SSYYNNOOPPSSIISS ##iinncclluuddee <> _k_r_b_5___g_e_t___i_n_i_t___c_r_e_d_s___o_p_t_; _k_r_b_5___e_r_r_o_r___c_o_d_e kkrrbb55__ggeett__iinniitt__ccrreeddss__oopptt__aalllloocc(_k_r_b_5___c_o_n_t_e_x_t _c_o_n_t_e_x_t, _k_r_b_5___g_e_t___i_n_i_t___c_r_e_d_s___o_p_t _*_*_o_p_t); _v_o_i_d kkrrbb55__ggeett__iinniitt__ccrreeddss__oopptt__ffrreeee(_k_r_b_5___c_o_n_t_e_x_t _c_o_n_t_e_x_t, _k_r_b_5___g_e_t___i_n_i_t___c_r_e_d_s___o_p_t _*_o_p_t); _v_o_i_d kkrrbb55__ggeett__iinniitt__ccrreeddss__oopptt__iinniitt(_k_r_b_5___g_e_t___i_n_i_t___c_r_e_d_s___o_p_t _*_o_p_t); _v_o_i_d kkrrbb55__ggeett__iinniitt__ccrreeddss__oopptt__sseett__aaddddrreessss__lliisstt(_k_r_b_5___g_e_t___i_n_i_t___c_r_e_d_s___o_p_t _*_o_p_t, _k_r_b_5___a_d_d_r_e_s_s_e_s _*_a_d_d_r_e_s_s_e_s); _v_o_i_d kkrrbb55__ggeett__iinniitt__ccrreeddss__oopptt__sseett__aaddddrreesssslleessss(_k_r_b_5___g_e_t___i_n_i_t___c_r_e_d_s___o_p_t _*_o_p_t, _k_r_b_5___b_o_o_l_e_a_n _a_d_d_r_e_s_s_l_e_s_s); _v_o_i_d kkrrbb55__ggeett__iinniitt__ccrreeddss__oopptt__sseett__aannoonnyymmoouuss(_k_r_b_5___g_e_t___i_n_i_t___c_r_e_d_s___o_p_t _*_o_p_t, _i_n_t _a_n_o_n_y_m_o_u_s); _v_o_i_d kkrrbb55__ggeett__iinniitt__ccrreeddss__oopptt__sseett__cchhaannggee__ppaasssswwoorrdd__pprroommpptt(_k_r_b_5___g_e_t___i_n_i_t___c_r_e_d_s___o_p_t _*_o_p_t, _i_n_t _c_h_a_n_g_e___p_a_s_s_w_o_r_d___p_r_o_m_p_t); _v_o_i_d kkrrbb55__ggeett__iinniitt__ccrreeddss__oopptt__sseett__ddeeffaauulltt__ffllaaggss(_k_r_b_5___c_o_n_t_e_x_t _c_o_n_t_e_x_t, _c_o_n_s_t _c_h_a_r _*_a_p_p_n_a_m_e, _k_r_b_5___c_o_n_s_t___r_e_a_l_m _r_e_a_l_m, _k_r_b_5___g_e_t___i_n_i_t___c_r_e_d_s___o_p_t _*_o_p_t); _v_o_i_d kkrrbb55__ggeett__iinniitt__ccrreeddss__oopptt__sseett__eettyyppee__lliisstt(_k_r_b_5___g_e_t___i_n_i_t___c_r_e_d_s___o_p_t _*_o_p_t, _k_r_b_5___e_n_c_t_y_p_e _*_e_t_y_p_e___l_i_s_t, _i_n_t _e_t_y_p_e___l_i_s_t___l_e_n_g_t_h); _v_o_i_d kkrrbb55__ggeett__iinniitt__ccrreeddss__oopptt__sseett__ffoorrwwaarrddaabbllee(_k_r_b_5___g_e_t___i_n_i_t___c_r_e_d_s___o_p_t _*_o_p_t, _i_n_t _f_o_r_w_a_r_d_a_b_l_e); _k_r_b_5___e_r_r_o_r___c_o_d_e kkrrbb55__ggeett__iinniitt__ccrreeddss__oopptt__sseett__ppaa__ppaasssswwoorrdd(_k_r_b_5___c_o_n_t_e_x_t _c_o_n_t_e_x_t, _k_r_b_5___g_e_t___i_n_i_t___c_r_e_d_s___o_p_t _*_o_p_t, _c_o_n_s_t _c_h_a_r _*_p_a_s_s_w_o_r_d, _k_r_b_5___s_2_k___p_r_o_c _k_e_y___p_r_o_c); _k_r_b_5___e_r_r_o_r___c_o_d_e kkrrbb55__ggeett__iinniitt__ccrreeddss__oopptt__sseett__ppaaqq__rreeqquueesstt(_k_r_b_5___c_o_n_t_e_x_t _c_o_n_t_e_x_t, _k_r_b_5___g_e_t___i_n_i_t___c_r_e_d_s___o_p_t _*_o_p_t, _k_r_b_5___b_o_o_l_e_a_n _r_e_q___p_a_c); _k_r_b_5___e_r_r_o_r___c_o_d_e kkrrbb55__ggeett__iinniitt__ccrreeddss__oopptt__sseett__ppkkiinniitt(_k_r_b_5___c_o_n_t_e_x_t _c_o_n_t_e_x_t, _k_r_b_5___g_e_t___i_n_i_t___c_r_e_d_s___o_p_t _*_o_p_t, _c_o_n_s_t _c_h_a_r _*_c_e_r_t___f_i_l_e, _c_o_n_s_t _c_h_a_r _*_k_e_y___f_i_l_e, _c_o_n_s_t _c_h_a_r _*_x_5_0_9___a_n_c_h_o_r_s, _i_n_t _f_l_a_g_s, _c_h_a_r _*_p_a_s_s_w_o_r_d); _v_o_i_d kkrrbb55__ggeett__iinniitt__ccrreeddss__oopptt__sseett__pprreeaauutthh__lliisstt(_k_r_b_5___g_e_t___i_n_i_t___c_r_e_d_s___o_p_t _*_o_p_t, _k_r_b_5___p_r_e_a_u_t_h_t_y_p_e _*_p_r_e_a_u_t_h___l_i_s_t, _i_n_t _p_r_e_a_u_t_h___l_i_s_t___l_e_n_g_t_h); _v_o_i_d kkrrbb55__ggeett__iinniitt__ccrreeddss__oopptt__sseett__pprrooxxiiaabbllee(_k_r_b_5___g_e_t___i_n_i_t___c_r_e_d_s___o_p_t _*_o_p_t, _i_n_t _p_r_o_x_i_a_b_l_e); _v_o_i_d kkrrbb55__ggeett__iinniitt__ccrreeddss__oopptt__sseett__rreenneeww__lliiffee(_k_r_b_5___g_e_t___i_n_i_t___c_r_e_d_s___o_p_t _*_o_p_t, _k_r_b_5___d_e_l_t_a_t _r_e_n_e_w___l_i_f_e); _v_o_i_d kkrrbb55__ggeett__iinniitt__ccrreeddss__oopptt__sseett__ssaalltt(_k_r_b_5___g_e_t___i_n_i_t___c_r_e_d_s___o_p_t _*_o_p_t, _k_r_b_5___d_a_t_a _*_s_a_l_t); _v_o_i_d kkrrbb55__ggeett__iinniitt__ccrreeddss__oopptt__sseett__ttkktt__lliiffee(_k_r_b_5___g_e_t___i_n_i_t___c_r_e_d_s___o_p_t _*_o_p_t, _k_r_b_5___d_e_l_t_a_t _t_k_t___l_i_f_e); _k_r_b_5___e_r_r_o_r___c_o_d_e kkrrbb55__ggeett__iinniitt__ccrreeddss__oopptt__sseett__ccaannoonniiccaalliizzee(_k_r_b_5___c_o_n_t_e_x_t _c_o_n_t_e_x_t, _k_r_b_5___g_e_t___i_n_i_t___c_r_e_d_s___o_p_t _*_o_p_t, _k_r_b_5___b_o_o_l_e_a_n _r_e_q); _k_r_b_5___e_r_r_o_r___c_o_d_e kkrrbb55__ggeett__iinniitt__ccrreeddss__oopptt__sseett__wwiinn22kk(_k_r_b_5___c_o_n_t_e_x_t _c_o_n_t_e_x_t, _k_r_b_5___g_e_t___i_n_i_t___c_r_e_d_s___o_p_t _*_o_p_t, _k_r_b_5___b_o_o_l_e_a_n _r_e_q); _k_r_b_5___e_r_r_o_r___c_o_d_e kkrrbb55__ggeett__iinniitt__ccrreeddss(_k_r_b_5___c_o_n_t_e_x_t _c_o_n_t_e_x_t, _k_r_b_5___c_r_e_d_s _*_c_r_e_d_s, _k_r_b_5___p_r_i_n_c_i_p_a_l _c_l_i_e_n_t, _k_r_b_5___p_r_o_m_p_t_e_r___f_c_t _p_r_o_m_p_t_e_r, _v_o_i_d _*_p_r_o_m_p_t_e_r___d_a_t_a, _k_r_b_5___d_e_l_t_a_t _s_t_a_r_t___t_i_m_e, _c_o_n_s_t _c_h_a_r _*_i_n___t_k_t___s_e_r_v_i_c_e, _k_r_b_5___g_e_t___i_n_i_t___c_r_e_d_s___o_p_t _*_o_p_t_i_o_n_s); _k_r_b_5___e_r_r_o_r___c_o_d_e kkrrbb55__ggeett__iinniitt__ccrreeddss__ppaasssswwoorrdd(_k_r_b_5___c_o_n_t_e_x_t _c_o_n_t_e_x_t, _k_r_b_5___c_r_e_d_s _*_c_r_e_d_s, _k_r_b_5___p_r_i_n_c_i_p_a_l _c_l_i_e_n_t, _c_o_n_s_t _c_h_a_r _*_p_a_s_s_w_o_r_d, _k_r_b_5___p_r_o_m_p_t_e_r___f_c_t _p_r_o_m_p_t_e_r, _v_o_i_d _*_p_r_o_m_p_t_e_r___d_a_t_a, _k_r_b_5___d_e_l_t_a_t _s_t_a_r_t___t_i_m_e, _c_o_n_s_t _c_h_a_r _*_i_n___t_k_t___s_e_r_v_i_c_e, _k_r_b_5___g_e_t___i_n_i_t___c_r_e_d_s___o_p_t _*_i_n___o_p_t_i_o_n_s); _k_r_b_5___e_r_r_o_r___c_o_d_e kkrrbb55__ggeett__iinniitt__ccrreeddss__kkeeyyttaabb(_k_r_b_5___c_o_n_t_e_x_t _c_o_n_t_e_x_t, _k_r_b_5___c_r_e_d_s _*_c_r_e_d_s, _k_r_b_5___p_r_i_n_c_i_p_a_l _c_l_i_e_n_t, _k_r_b_5___k_e_y_t_a_b _k_e_y_t_a_b, _k_r_b_5___d_e_l_t_a_t _s_t_a_r_t___t_i_m_e, _c_o_n_s_t _c_h_a_r _*_i_n___t_k_t___s_e_r_v_i_c_e, _k_r_b_5___g_e_t___i_n_i_t___c_r_e_d_s___o_p_t _*_o_p_t_i_o_n_s); _i_n_t kkrrbb55__pprroommpptteerr__ppoossiixx(_k_r_b_5___c_o_n_t_e_x_t _c_o_n_t_e_x_t, _v_o_i_d _*_d_a_t_a, _c_o_n_s_t _c_h_a_r _*_n_a_m_e, _c_o_n_s_t _c_h_a_r _*_b_a_n_n_e_r, _i_n_t _n_u_m___p_r_o_m_p_t_s, _k_r_b_5___p_r_o_m_p_t _p_r_o_m_p_t_s_[_]); DDEESSCCRRIIPPTTIIOONN Getting initial credential ticket for a principal. That may include changing an expired password, and doing preauthentication. This inter- face that replaces the deprecated _k_r_b_5___i_n___t_k_t and _k_r_b_5___i_n___c_r_e_d functions. If you only want to verify a username and password, consider using krb5_verify_user(3) instead, since it also verifies that initial creden- tials with using a keytab to make sure the response was from the KDC. First a krb5_get_init_creds_opt structure is initialized with kkrrbb55__ggeett__iinniitt__ccrreeddss__oopptt__aalllloocc() or kkrrbb55__ggeett__iinniitt__ccrreeddss__oopptt__iinniitt(). kkrrbb55__ggeett__iinniitt__ccrreeddss__oopptt__aalllloocc() allocates a extendible structures that needs to be freed with kkrrbb55__ggeett__iinniitt__ccrreeddss__oopptt__ffrreeee(). The structure may be modified by any of the kkrrbb55__ggeett__iinniitt__ccrreeddss__oopptt__sseett() functions to change request parameters and authentication information. If the caller want to use the default options, NULL can be passed instead. The the actual request to the KDC is done by any of the kkrrbb55__ggeett__iinniitt__ccrreeddss(), kkrrbb55__ggeett__iinniitt__ccrreeddss__ppaasssswwoorrdd(), or kkrrbb55__ggeett__iinniitt__ccrreeddss__kkeeyyttaabb() functions. kkrrbb55__ggeett__iinniitt__ccrreeddss() is the least specialized function and can, with the right in data, behave like the latter two. The latter two are there for compatibility with older releases and they are slightly easier to use. krb5_prompt is a structure containing the following elements: typedef struct { const char *prompt; int hidden; krb5_data *reply; krb5_prompt_type type } krb5_prompt; _p_r_o_m_p_t is the prompt that should shown to the user If _h_i_d_d_e_n is set, the prompter function shouldn't echo the output to the display device. _r_e_p_l_y must be preallocated; it will not be allocated by the prompter function. Possible values for the _t_y_p_e element are: KRB5_PROMPT_TYPE_PASSWORD KRB5_PROMPT_TYPE_NEW_PASSWORD KRB5_PROMPT_TYPE_NEW_PASSWORD_AGAIN KRB5_PROMPT_TYPE_PREAUTH KRB5_PROMPT_TYPE_INFO kkrrbb55__pprroommpptteerr__ppoossiixx() is the default prompter function in a POSIX envi- ronment. It matches the _k_r_b_5___p_r_o_m_p_t_e_r___f_c_t and can be used in the _k_r_b_5___g_e_t___i_n_i_t___c_r_e_d_s functions. kkrrbb55__pprroommpptteerr__ppoossiixx() doesn't require _p_r_o_m_p_t_e_r___d_a_t_a_. If the _s_t_a_r_t___t_i_m_e is zero, then the requested ticket will be valid begin- ning immediately. Otherwise, the _s_t_a_r_t___t_i_m_e indicates how far in the future the ticket should be postdated. If the _i_n___t_k_t___s_e_r_v_i_c_e name is non-NULL, that principal name will be used as the server name for the initial ticket request. The realm of the name specified will be ignored and will be set to the realm of the client name. If no in_tkt_service name is specified, krbtgt/CLIENT- REALM@CLIENT-REALM will be used. For the rest of arguments, a configuration or library default will be used if no value is specified in the options structure. kkrrbb55__ggeett__iinniitt__ccrreeddss__oopptt__sseett__aaddddrreessss__lliisstt() sets the list of _a_d_d_r_e_s_s_e_s that is should be stored in the ticket. kkrrbb55__ggeett__iinniitt__ccrreeddss__oopptt__sseett__aaddddrreesssslleessss() controls if the ticket is requested with addresses or not, kkrrbb55__ggeett__iinniitt__ccrreeddss__oopptt__sseett__aaddddrreessss__lliisstt() overrides this option. kkrrbb55__ggeett__iinniitt__ccrreeddss__oopptt__sseett__aannoonnyymmoouuss() make the request anonymous if the _a_n_o_n_y_m_o_u_s parameter is non-zero. kkrrbb55__ggeett__iinniitt__ccrreeddss__oopptt__sseett__ddeeffaauulltt__ffllaaggss() sets the default flags using the configuration file. kkrrbb55__ggeett__iinniitt__ccrreeddss__oopptt__sseett__eettyyppee__lliisstt() set a list of enctypes that the client is willing to support in the request. kkrrbb55__ggeett__iinniitt__ccrreeddss__oopptt__sseett__ffoorrwwaarrddaabbllee() request a forwardable ticket. kkrrbb55__ggeett__iinniitt__ccrreeddss__oopptt__sseett__ppaa__ppaasssswwoorrdd() set the _p_a_s_s_w_o_r_d and _k_e_y___p_r_o_c that is going to be used to get a new ticket. _p_a_s_s_w_o_r_d or _k_e_y___p_r_o_c can be NULL if the caller wants to use the default values. If the _p_a_s_s_w_o_r_d is unset and needed, the user will be prompted for it. kkrrbb55__ggeett__iinniitt__ccrreeddss__oopptt__sseett__ppaaqq__rreeqquueesstt() sets the password that is going to be used to get a new ticket. kkrrbb55__ggeett__iinniitt__ccrreeddss__oopptt__sseett__pprreeaauutthh__lliisstt() sets the list of client-sup- ported preauth types. kkrrbb55__ggeett__iinniitt__ccrreeddss__oopptt__sseett__pprrooxxiiaabbllee() makes the request proxiable. kkrrbb55__ggeett__iinniitt__ccrreeddss__oopptt__sseett__rreenneeww__lliiffee() sets the requested renewable lifetime. kkrrbb55__ggeett__iinniitt__ccrreeddss__oopptt__sseett__ssaalltt() sets the salt that is going to be used in the request. kkrrbb55__ggeett__iinniitt__ccrreeddss__oopptt__sseett__ttkktt__lliiffee() sets requested ticket lifetime. kkrrbb55__ggeett__iinniitt__ccrreeddss__oopptt__sseett__ccaannoonniiccaalliizzee() requests that the KDC canoni- calize the client principal if possible. kkrrbb55__ggeett__iinniitt__ccrreeddss__oopptt__sseett__wwiinn22kk() turns on compatibility with Windows 2000. SSEEEE AALLSSOO krb5(3), krb5_creds(3), krb5_verify_user(3), krb5.conf(5), kerberos(8) HEIMDAL Sep 16, 2006 HEIMDAL heimdal-7.5.0/lib/krb5/pac.c0000644000175000017500000007401213212137553013600 0ustar niknik/* * Copyright (c) 2006 - 2007 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "krb5_locl.h" #include struct PAC_INFO_BUFFER { uint32_t type; uint32_t buffersize; uint32_t offset_hi; uint32_t offset_lo; }; struct PACTYPE { uint32_t numbuffers; uint32_t version; struct PAC_INFO_BUFFER buffers[1]; }; struct krb5_pac_data { struct PACTYPE *pac; krb5_data data; struct PAC_INFO_BUFFER *server_checksum; struct PAC_INFO_BUFFER *privsvr_checksum; struct PAC_INFO_BUFFER *logon_name; }; #define PAC_ALIGNMENT 8 #define PACTYPE_SIZE 8 #define PAC_INFO_BUFFER_SIZE 16 #define PAC_SERVER_CHECKSUM 6 #define PAC_PRIVSVR_CHECKSUM 7 #define PAC_LOGON_NAME 10 #define PAC_CONSTRAINED_DELEGATION 11 #define CHECK(r,f,l) \ do { \ if (((r) = f ) != 0) { \ krb5_clear_error_message(context); \ goto l; \ } \ } while(0) static const char zeros[PAC_ALIGNMENT] = { 0 }; /* * HMAC-MD5 checksum over any key (needed for the PAC routines) */ static krb5_error_code HMAC_MD5_any_checksum(krb5_context context, const krb5_keyblock *key, const void *data, size_t len, unsigned usage, Checksum *result) { struct _krb5_key_data local_key; krb5_error_code ret; memset(&local_key, 0, sizeof(local_key)); ret = krb5_copy_keyblock(context, key, &local_key.key); if (ret) return ret; ret = krb5_data_alloc (&result->checksum, 16); if (ret) { krb5_free_keyblock(context, local_key.key); return ret; } result->cksumtype = CKSUMTYPE_HMAC_MD5; ret = _krb5_HMAC_MD5_checksum(context, &local_key, data, len, usage, result); if (ret) krb5_data_free(&result->checksum); krb5_free_keyblock(context, local_key.key); return ret; } /* * */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_pac_parse(krb5_context context, const void *ptr, size_t len, krb5_pac *pac) { krb5_error_code ret; krb5_pac p; krb5_storage *sp = NULL; uint32_t i, tmp, tmp2, header_end; p = calloc(1, sizeof(*p)); if (p == NULL) { ret = krb5_enomem(context); goto out; } sp = krb5_storage_from_readonly_mem(ptr, len); if (sp == NULL) { ret = krb5_enomem(context); goto out; } krb5_storage_set_flags(sp, KRB5_STORAGE_BYTEORDER_LE); CHECK(ret, krb5_ret_uint32(sp, &tmp), out); CHECK(ret, krb5_ret_uint32(sp, &tmp2), out); if (tmp < 1) { ret = EINVAL; /* Too few buffers */ krb5_set_error_message(context, ret, N_("PAC have too few buffer", "")); goto out; } if (tmp2 != 0) { ret = EINVAL; /* Wrong version */ krb5_set_error_message(context, ret, N_("PAC have wrong version %d", ""), (int)tmp2); goto out; } p->pac = calloc(1, sizeof(*p->pac) + (sizeof(p->pac->buffers[0]) * (tmp - 1))); if (p->pac == NULL) { ret = krb5_enomem(context); goto out; } p->pac->numbuffers = tmp; p->pac->version = tmp2; header_end = PACTYPE_SIZE + (PAC_INFO_BUFFER_SIZE * p->pac->numbuffers); if (header_end > len) { ret = EINVAL; goto out; } for (i = 0; i < p->pac->numbuffers; i++) { CHECK(ret, krb5_ret_uint32(sp, &p->pac->buffers[i].type), out); CHECK(ret, krb5_ret_uint32(sp, &p->pac->buffers[i].buffersize), out); CHECK(ret, krb5_ret_uint32(sp, &p->pac->buffers[i].offset_lo), out); CHECK(ret, krb5_ret_uint32(sp, &p->pac->buffers[i].offset_hi), out); /* consistency checks */ if (p->pac->buffers[i].offset_lo & (PAC_ALIGNMENT - 1)) { ret = EINVAL; krb5_set_error_message(context, ret, N_("PAC out of allignment", "")); goto out; } if (p->pac->buffers[i].offset_hi) { ret = EINVAL; krb5_set_error_message(context, ret, N_("PAC high offset set", "")); goto out; } if (p->pac->buffers[i].offset_lo > len) { ret = EINVAL; krb5_set_error_message(context, ret, N_("PAC offset off end", "")); goto out; } if (p->pac->buffers[i].offset_lo < header_end) { ret = EINVAL; krb5_set_error_message(context, ret, N_("PAC offset inside header: %lu %lu", ""), (unsigned long)p->pac->buffers[i].offset_lo, (unsigned long)header_end); goto out; } if (p->pac->buffers[i].buffersize > len - p->pac->buffers[i].offset_lo){ ret = EINVAL; krb5_set_error_message(context, ret, N_("PAC length off end", "")); goto out; } /* let save pointer to data we need later */ if (p->pac->buffers[i].type == PAC_SERVER_CHECKSUM) { if (p->server_checksum) { ret = EINVAL; krb5_set_error_message(context, ret, N_("PAC have two server checksums", "")); goto out; } p->server_checksum = &p->pac->buffers[i]; } else if (p->pac->buffers[i].type == PAC_PRIVSVR_CHECKSUM) { if (p->privsvr_checksum) { ret = EINVAL; krb5_set_error_message(context, ret, N_("PAC have two KDC checksums", "")); goto out; } p->privsvr_checksum = &p->pac->buffers[i]; } else if (p->pac->buffers[i].type == PAC_LOGON_NAME) { if (p->logon_name) { ret = EINVAL; krb5_set_error_message(context, ret, N_("PAC have two logon names", "")); goto out; } p->logon_name = &p->pac->buffers[i]; } } ret = krb5_data_copy(&p->data, ptr, len); if (ret) goto out; krb5_storage_free(sp); *pac = p; return 0; out: if (sp) krb5_storage_free(sp); if (p) { if (p->pac) free(p->pac); free(p); } *pac = NULL; return ret; } KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_pac_init(krb5_context context, krb5_pac *pac) { krb5_error_code ret; krb5_pac p; p = calloc(1, sizeof(*p)); if (p == NULL) { return krb5_enomem(context); } p->pac = calloc(1, sizeof(*p->pac)); if (p->pac == NULL) { free(p); return krb5_enomem(context); } ret = krb5_data_alloc(&p->data, PACTYPE_SIZE); if (ret) { free (p->pac); free(p); return krb5_enomem(context); } *pac = p; return 0; } KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_pac_add_buffer(krb5_context context, krb5_pac p, uint32_t type, const krb5_data *data) { krb5_error_code ret; void *ptr; size_t len, offset, header_end, old_end; uint32_t i; len = p->pac->numbuffers; ptr = realloc(p->pac, sizeof(*p->pac) + (sizeof(p->pac->buffers[0]) * len)); if (ptr == NULL) return krb5_enomem(context); p->pac = ptr; for (i = 0; i < len; i++) p->pac->buffers[i].offset_lo += PAC_INFO_BUFFER_SIZE; offset = p->data.length + PAC_INFO_BUFFER_SIZE; p->pac->buffers[len].type = type; p->pac->buffers[len].buffersize = data->length; p->pac->buffers[len].offset_lo = offset; p->pac->buffers[len].offset_hi = 0; old_end = p->data.length; len = p->data.length + data->length + PAC_INFO_BUFFER_SIZE; if (len < p->data.length) { krb5_set_error_message(context, EINVAL, "integer overrun"); return EINVAL; } /* align to PAC_ALIGNMENT */ len = ((len + PAC_ALIGNMENT - 1) / PAC_ALIGNMENT) * PAC_ALIGNMENT; ret = krb5_data_realloc(&p->data, len); if (ret) { krb5_set_error_message(context, ret, N_("malloc: out of memory", "")); return ret; } /* * make place for new PAC INFO BUFFER header */ header_end = PACTYPE_SIZE + (PAC_INFO_BUFFER_SIZE * p->pac->numbuffers); memmove((unsigned char *)p->data.data + header_end + PAC_INFO_BUFFER_SIZE, (unsigned char *)p->data.data + header_end , old_end - header_end); memset((unsigned char *)p->data.data + header_end, 0, PAC_INFO_BUFFER_SIZE); /* * copy in new data part */ memcpy((unsigned char *)p->data.data + offset, data->data, data->length); memset((unsigned char *)p->data.data + offset + data->length, 0, p->data.length - offset - data->length); p->pac->numbuffers += 1; return 0; } /** * Get the PAC buffer of specific type from the pac. * * @param context Kerberos 5 context. * @param p the pac structure returned by krb5_pac_parse(). * @param type type of buffer to get * @param data return data, free with krb5_data_free(). * * @return Returns 0 to indicate success. Otherwise an kerberos et * error code is returned, see krb5_get_error_message(). * * @ingroup krb5_pac */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_pac_get_buffer(krb5_context context, krb5_pac p, uint32_t type, krb5_data *data) { krb5_error_code ret; uint32_t i; for (i = 0; i < p->pac->numbuffers; i++) { const size_t len = p->pac->buffers[i].buffersize; const size_t offset = p->pac->buffers[i].offset_lo; if (p->pac->buffers[i].type != type) continue; ret = krb5_data_copy(data, (unsigned char *)p->data.data + offset, len); if (ret) { krb5_set_error_message(context, ret, N_("malloc: out of memory", "")); return ret; } return 0; } krb5_set_error_message(context, ENOENT, "No PAC buffer of type %lu was found", (unsigned long)type); return ENOENT; } /* * */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_pac_get_types(krb5_context context, krb5_pac p, size_t *len, uint32_t **types) { size_t i; *types = calloc(p->pac->numbuffers, sizeof(**types)); if (*types == NULL) { *len = 0; return krb5_enomem(context); } for (i = 0; i < p->pac->numbuffers; i++) (*types)[i] = p->pac->buffers[i].type; *len = p->pac->numbuffers; return 0; } /* * */ KRB5_LIB_FUNCTION void KRB5_LIB_CALL krb5_pac_free(krb5_context context, krb5_pac pac) { krb5_data_free(&pac->data); free(pac->pac); free(pac); } /* * */ static krb5_error_code verify_checksum(krb5_context context, const struct PAC_INFO_BUFFER *sig, const krb5_data *data, void *ptr, size_t len, const krb5_keyblock *key) { krb5_storage *sp = NULL; uint32_t type; krb5_error_code ret; Checksum cksum; memset(&cksum, 0, sizeof(cksum)); sp = krb5_storage_from_mem((char *)data->data + sig->offset_lo, sig->buffersize); if (sp == NULL) return krb5_enomem(context); krb5_storage_set_flags(sp, KRB5_STORAGE_BYTEORDER_LE); CHECK(ret, krb5_ret_uint32(sp, &type), out); cksum.cksumtype = type; cksum.checksum.length = sig->buffersize - krb5_storage_seek(sp, 0, SEEK_CUR); cksum.checksum.data = malloc(cksum.checksum.length); if (cksum.checksum.data == NULL) { ret = krb5_enomem(context); goto out; } ret = krb5_storage_read(sp, cksum.checksum.data, cksum.checksum.length); if (ret != (int)cksum.checksum.length) { ret = EINVAL; krb5_set_error_message(context, ret, "PAC checksum missing checksum"); goto out; } if (!krb5_checksum_is_keyed(context, cksum.cksumtype)) { ret = EINVAL; krb5_set_error_message(context, ret, "Checksum type %d not keyed", cksum.cksumtype); goto out; } /* If the checksum is HMAC-MD5, the checksum type is not tied to * the key type, instead the HMAC-MD5 checksum is applied blindly * on whatever key is used for this connection, avoiding issues * with unkeyed checksums on des-cbc-md5 and des-cbc-crc. See * http://comments.gmane.org/gmane.comp.encryption.kerberos.devel/8743 * for the same issue in MIT, and * http://blogs.msdn.com/b/openspecification/archive/2010/01/01/verifying-the-server-signature-in-kerberos-privilege-account-certificate.aspx * for Microsoft's explaination */ if (cksum.cksumtype == CKSUMTYPE_HMAC_MD5) { Checksum local_checksum; memset(&local_checksum, 0, sizeof(local_checksum)); ret = HMAC_MD5_any_checksum(context, key, ptr, len, KRB5_KU_OTHER_CKSUM, &local_checksum); if (ret != 0 || krb5_data_ct_cmp(&local_checksum.checksum, &cksum.checksum) != 0) { ret = KRB5KRB_AP_ERR_BAD_INTEGRITY; krb5_set_error_message(context, ret, N_("PAC integrity check failed for " "hmac-md5 checksum", "")); } krb5_data_free(&local_checksum.checksum); } else { krb5_crypto crypto = NULL; ret = krb5_crypto_init(context, key, 0, &crypto); if (ret) goto out; ret = krb5_verify_checksum(context, crypto, KRB5_KU_OTHER_CKSUM, ptr, len, &cksum); krb5_crypto_destroy(context, crypto); } free(cksum.checksum.data); krb5_storage_free(sp); return ret; out: if (cksum.checksum.data) free(cksum.checksum.data); if (sp) krb5_storage_free(sp); return ret; } static krb5_error_code create_checksum(krb5_context context, const krb5_keyblock *key, uint32_t cksumtype, void *data, size_t datalen, void *sig, size_t siglen) { krb5_crypto crypto = NULL; krb5_error_code ret; Checksum cksum; /* If the checksum is HMAC-MD5, the checksum type is not tied to * the key type, instead the HMAC-MD5 checksum is applied blindly * on whatever key is used for this connection, avoiding issues * with unkeyed checksums on des-cbc-md5 and des-cbc-crc. See * http://comments.gmane.org/gmane.comp.encryption.kerberos.devel/8743 * for the same issue in MIT, and * http://blogs.msdn.com/b/openspecification/archive/2010/01/01/verifying-the-server-signature-in-kerberos-privilege-account-certificate.aspx * for Microsoft's explaination */ if (cksumtype == (uint32_t)CKSUMTYPE_HMAC_MD5) { ret = HMAC_MD5_any_checksum(context, key, data, datalen, KRB5_KU_OTHER_CKSUM, &cksum); if (ret) return ret; } else { ret = krb5_crypto_init(context, key, 0, &crypto); if (ret) return ret; ret = krb5_create_checksum(context, crypto, KRB5_KU_OTHER_CKSUM, 0, data, datalen, &cksum); krb5_crypto_destroy(context, crypto); if (ret) return ret; } if (cksum.checksum.length != siglen) { krb5_set_error_message(context, EINVAL, "pac checksum wrong length"); free_Checksum(&cksum); return EINVAL; } memcpy(sig, cksum.checksum.data, siglen); free_Checksum(&cksum); return 0; } /* * */ #define NTTIME_EPOCH 0x019DB1DED53E8000LL static uint64_t unix2nttime(time_t unix_time) { long long wt; wt = unix_time * (uint64_t)10000000 + (uint64_t)NTTIME_EPOCH; return wt; } static krb5_error_code verify_logonname(krb5_context context, const struct PAC_INFO_BUFFER *logon_name, const krb5_data *data, time_t authtime, krb5_const_principal principal) { krb5_error_code ret; uint32_t time1, time2; krb5_storage *sp; uint16_t len; char *s = NULL; char *principal_string = NULL; char *logon_string = NULL; sp = krb5_storage_from_readonly_mem((const char *)data->data + logon_name->offset_lo, logon_name->buffersize); if (sp == NULL) return krb5_enomem(context); krb5_storage_set_flags(sp, KRB5_STORAGE_BYTEORDER_LE); CHECK(ret, krb5_ret_uint32(sp, &time1), out); CHECK(ret, krb5_ret_uint32(sp, &time2), out); { uint64_t t1, t2; t1 = unix2nttime(authtime); t2 = ((uint64_t)time2 << 32) | time1; /* * When neither the ticket nor the PAC set an explicit authtime, * both times are zero, but relative to different time scales. * So we must compare "not set" values without converting to a * common time reference. */ if (t1 != t2 && (t2 != 0 && authtime != 0)) { krb5_storage_free(sp); krb5_set_error_message(context, EINVAL, "PAC timestamp mismatch"); return EINVAL; } } CHECK(ret, krb5_ret_uint16(sp, &len), out); if (len == 0) { krb5_storage_free(sp); krb5_set_error_message(context, EINVAL, "PAC logon name length missing"); return EINVAL; } s = malloc(len); if (s == NULL) { krb5_storage_free(sp); return krb5_enomem(context); } ret = krb5_storage_read(sp, s, len); if (ret != len) { krb5_storage_free(sp); krb5_set_error_message(context, EINVAL, "Failed to read PAC logon name"); return EINVAL; } krb5_storage_free(sp); { size_t ucs2len = len / 2; uint16_t *ucs2; size_t u8len; unsigned int flags = WIND_RW_LE; ucs2 = malloc(sizeof(ucs2[0]) * ucs2len); if (ucs2 == NULL) return krb5_enomem(context); ret = wind_ucs2read(s, len, &flags, ucs2, &ucs2len); free(s); if (ret) { free(ucs2); krb5_set_error_message(context, ret, "Failed to convert string to UCS-2"); return ret; } ret = wind_ucs2utf8_length(ucs2, ucs2len, &u8len); if (ret) { free(ucs2); krb5_set_error_message(context, ret, "Failed to count length of UCS-2 string"); return ret; } u8len += 1; /* Add space for NUL */ logon_string = malloc(u8len); if (logon_string == NULL) { free(ucs2); return krb5_enomem(context); } ret = wind_ucs2utf8(ucs2, ucs2len, logon_string, &u8len); free(ucs2); if (ret) { free(logon_string); krb5_set_error_message(context, ret, "Failed to convert to UTF-8"); return ret; } } ret = krb5_unparse_name_flags(context, principal, KRB5_PRINCIPAL_UNPARSE_NO_REALM | KRB5_PRINCIPAL_UNPARSE_DISPLAY, &principal_string); if (ret) { free(logon_string); return ret; } ret = strcmp(logon_string, principal_string); if (ret != 0) { ret = EINVAL; krb5_set_error_message(context, ret, "PAC logon name [%s] mismatch principal name [%s]", logon_string, principal_string); } free(logon_string); free(principal_string); return ret; out: return ret; } /* * */ static krb5_error_code build_logon_name(krb5_context context, time_t authtime, krb5_const_principal principal, krb5_data *logon) { krb5_error_code ret; krb5_storage *sp; uint64_t t; char *s, *s2; size_t s2_len; t = unix2nttime(authtime); krb5_data_zero(logon); sp = krb5_storage_emem(); if (sp == NULL) return krb5_enomem(context); krb5_storage_set_flags(sp, KRB5_STORAGE_BYTEORDER_LE); CHECK(ret, krb5_store_uint32(sp, t & 0xffffffff), out); CHECK(ret, krb5_store_uint32(sp, t >> 32), out); ret = krb5_unparse_name_flags(context, principal, KRB5_PRINCIPAL_UNPARSE_NO_REALM | KRB5_PRINCIPAL_UNPARSE_DISPLAY, &s); if (ret) goto out; { size_t ucs2_len; uint16_t *ucs2; unsigned int flags; ret = wind_utf8ucs2_length(s, &ucs2_len); if (ret) { krb5_set_error_message(context, ret, "Principal %s is not valid UTF-8", s); free(s); return ret; } ucs2 = malloc(sizeof(ucs2[0]) * ucs2_len); if (ucs2 == NULL) { free(s); return krb5_enomem(context); } ret = wind_utf8ucs2(s, ucs2, &ucs2_len); if (ret) { free(ucs2); krb5_set_error_message(context, ret, "Principal %s is not valid UTF-8", s); free(s); return ret; } else free(s); s2_len = (ucs2_len + 1) * 2; s2 = malloc(s2_len); if (s2 == NULL) { free(ucs2); return krb5_enomem(context); } flags = WIND_RW_LE; ret = wind_ucs2write(ucs2, ucs2_len, &flags, s2, &s2_len); free(ucs2); if (ret) { free(s2); krb5_set_error_message(context, ret, "Failed to write to UCS-2 buffer"); return ret; } /* * we do not want zero termination */ s2_len = ucs2_len * 2; } CHECK(ret, krb5_store_uint16(sp, s2_len), out); ret = krb5_storage_write(sp, s2, s2_len); free(s2); if (ret != (int)s2_len) { ret = krb5_enomem(context); goto out; } ret = krb5_storage_to_data(sp, logon); if (ret) goto out; krb5_storage_free(sp); return 0; out: krb5_storage_free(sp); return ret; } /** * Verify the PAC. * * @param context Kerberos 5 context. * @param pac the pac structure returned by krb5_pac_parse(). * @param authtime The time of the ticket the PAC belongs to. * @param principal the principal to verify. * @param server The service key, most always be given. * @param privsvr The KDC key, may be given. * @return Returns 0 to indicate success. Otherwise an kerberos et * error code is returned, see krb5_get_error_message(). * * @ingroup krb5_pac */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_pac_verify(krb5_context context, const krb5_pac pac, time_t authtime, krb5_const_principal principal, const krb5_keyblock *server, const krb5_keyblock *privsvr) { krb5_error_code ret; if (pac->server_checksum == NULL) { krb5_set_error_message(context, EINVAL, "PAC missing server checksum"); return EINVAL; } if (pac->privsvr_checksum == NULL) { krb5_set_error_message(context, EINVAL, "PAC missing kdc checksum"); return EINVAL; } if (pac->logon_name == NULL) { krb5_set_error_message(context, EINVAL, "PAC missing logon name"); return EINVAL; } ret = verify_logonname(context, pac->logon_name, &pac->data, authtime, principal); if (ret) return ret; /* * in the service case, clean out data option of the privsvr and * server checksum before checking the checksum. */ { krb5_data *copy; if (pac->server_checksum->buffersize < 4 || pac->privsvr_checksum->buffersize < 4) return EINVAL; ret = krb5_copy_data(context, &pac->data, ©); if (ret) return ret; memset((char *)copy->data + pac->server_checksum->offset_lo + 4, 0, pac->server_checksum->buffersize - 4); memset((char *)copy->data + pac->privsvr_checksum->offset_lo + 4, 0, pac->privsvr_checksum->buffersize - 4); ret = verify_checksum(context, pac->server_checksum, &pac->data, copy->data, copy->length, server); krb5_free_data(context, copy); if (ret) return ret; } if (privsvr) { /* The priv checksum covers the server checksum */ ret = verify_checksum(context, pac->privsvr_checksum, &pac->data, (char *)pac->data.data + pac->server_checksum->offset_lo + 4, pac->server_checksum->buffersize - 4, privsvr); if (ret) return ret; } return 0; } /* * */ static krb5_error_code fill_zeros(krb5_context context, krb5_storage *sp, size_t len) { ssize_t sret; size_t l; while (len) { l = len; if (l > sizeof(zeros)) l = sizeof(zeros); sret = krb5_storage_write(sp, zeros, l); if (sret <= 0) return krb5_enomem(context); len -= sret; } return 0; } static krb5_error_code pac_checksum(krb5_context context, const krb5_keyblock *key, uint32_t *cksumtype, size_t *cksumsize) { krb5_cksumtype cktype; krb5_error_code ret; krb5_crypto crypto = NULL; ret = krb5_crypto_init(context, key, 0, &crypto); if (ret) return ret; ret = krb5_crypto_get_checksum_type(context, crypto, &cktype); krb5_crypto_destroy(context, crypto); if (ret) return ret; if (krb5_checksum_is_keyed(context, cktype) == FALSE) { *cksumtype = CKSUMTYPE_HMAC_MD5; *cksumsize = 16; } ret = krb5_checksumsize(context, cktype, cksumsize); if (ret) return ret; *cksumtype = (uint32_t)cktype; return 0; } KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL _krb5_pac_sign(krb5_context context, krb5_pac p, time_t authtime, krb5_principal principal, const krb5_keyblock *server_key, const krb5_keyblock *priv_key, krb5_data *data) { krb5_error_code ret; krb5_storage *sp = NULL, *spdata = NULL; uint32_t end; size_t server_size, priv_size; uint32_t server_offset = 0, priv_offset = 0; uint32_t server_cksumtype = 0, priv_cksumtype = 0; int num = 0; size_t i; krb5_data logon, d; krb5_data_zero(&logon); for (i = 0; i < p->pac->numbuffers; i++) { if (p->pac->buffers[i].type == PAC_SERVER_CHECKSUM) { if (p->server_checksum == NULL) { p->server_checksum = &p->pac->buffers[i]; } if (p->server_checksum != &p->pac->buffers[i]) { ret = EINVAL; krb5_set_error_message(context, ret, N_("PAC have two server checksums", "")); goto out; } } else if (p->pac->buffers[i].type == PAC_PRIVSVR_CHECKSUM) { if (p->privsvr_checksum == NULL) { p->privsvr_checksum = &p->pac->buffers[i]; } if (p->privsvr_checksum != &p->pac->buffers[i]) { ret = EINVAL; krb5_set_error_message(context, ret, N_("PAC have two KDC checksums", "")); goto out; } } else if (p->pac->buffers[i].type == PAC_LOGON_NAME) { if (p->logon_name == NULL) { p->logon_name = &p->pac->buffers[i]; } if (p->logon_name != &p->pac->buffers[i]) { ret = EINVAL; krb5_set_error_message(context, ret, N_("PAC have two logon names", "")); goto out; } } } if (p->logon_name == NULL) num++; if (p->server_checksum == NULL) num++; if (p->privsvr_checksum == NULL) num++; if (num) { void *ptr; ptr = realloc(p->pac, sizeof(*p->pac) + (sizeof(p->pac->buffers[0]) * (p->pac->numbuffers + num - 1))); if (ptr == NULL) return krb5_enomem(context); p->pac = ptr; if (p->logon_name == NULL) { p->logon_name = &p->pac->buffers[p->pac->numbuffers++]; memset(p->logon_name, 0, sizeof(*p->logon_name)); p->logon_name->type = PAC_LOGON_NAME; } if (p->server_checksum == NULL) { p->server_checksum = &p->pac->buffers[p->pac->numbuffers++]; memset(p->server_checksum, 0, sizeof(*p->server_checksum)); p->server_checksum->type = PAC_SERVER_CHECKSUM; } if (p->privsvr_checksum == NULL) { p->privsvr_checksum = &p->pac->buffers[p->pac->numbuffers++]; memset(p->privsvr_checksum, 0, sizeof(*p->privsvr_checksum)); p->privsvr_checksum->type = PAC_PRIVSVR_CHECKSUM; } } /* Calculate LOGON NAME */ ret = build_logon_name(context, authtime, principal, &logon); if (ret) goto out; /* Set lengths for checksum */ ret = pac_checksum(context, server_key, &server_cksumtype, &server_size); if (ret) goto out; ret = pac_checksum(context, priv_key, &priv_cksumtype, &priv_size); if (ret) goto out; /* Encode PAC */ sp = krb5_storage_emem(); if (sp == NULL) return krb5_enomem(context); krb5_storage_set_flags(sp, KRB5_STORAGE_BYTEORDER_LE); spdata = krb5_storage_emem(); if (spdata == NULL) { krb5_storage_free(sp); return krb5_enomem(context); } krb5_storage_set_flags(spdata, KRB5_STORAGE_BYTEORDER_LE); CHECK(ret, krb5_store_uint32(sp, p->pac->numbuffers), out); CHECK(ret, krb5_store_uint32(sp, p->pac->version), out); end = PACTYPE_SIZE + (PAC_INFO_BUFFER_SIZE * p->pac->numbuffers); for (i = 0; i < p->pac->numbuffers; i++) { uint32_t len; size_t sret; void *ptr = NULL; /* store data */ if (p->pac->buffers[i].type == PAC_SERVER_CHECKSUM) { len = server_size + 4; server_offset = end + 4; CHECK(ret, krb5_store_uint32(spdata, server_cksumtype), out); CHECK(ret, fill_zeros(context, spdata, server_size), out); } else if (p->pac->buffers[i].type == PAC_PRIVSVR_CHECKSUM) { len = priv_size + 4; priv_offset = end + 4; CHECK(ret, krb5_store_uint32(spdata, priv_cksumtype), out); CHECK(ret, fill_zeros(context, spdata, priv_size), out); } else if (p->pac->buffers[i].type == PAC_LOGON_NAME) { len = krb5_storage_write(spdata, logon.data, logon.length); if (logon.length != len) { ret = EINVAL; goto out; } } else { len = p->pac->buffers[i].buffersize; ptr = (char *)p->data.data + p->pac->buffers[i].offset_lo; sret = krb5_storage_write(spdata, ptr, len); if (sret != len) { ret = krb5_enomem(context); goto out; } /* XXX if not aligned, fill_zeros */ } /* write header */ CHECK(ret, krb5_store_uint32(sp, p->pac->buffers[i].type), out); CHECK(ret, krb5_store_uint32(sp, len), out); CHECK(ret, krb5_store_uint32(sp, end), out); CHECK(ret, krb5_store_uint32(sp, 0), out); /* advance data endpointer and align */ { int32_t e; end += len; e = ((end + PAC_ALIGNMENT - 1) / PAC_ALIGNMENT) * PAC_ALIGNMENT; if ((int32_t)end != e) { CHECK(ret, fill_zeros(context, spdata, e - end), out); } end = e; } } /* assert (server_offset != 0 && priv_offset != 0); */ /* export PAC */ ret = krb5_storage_to_data(spdata, &d); if (ret) { krb5_set_error_message(context, ret, N_("malloc: out of memory", "")); goto out; } ret = krb5_storage_write(sp, d.data, d.length); if (ret != (int)d.length) { krb5_data_free(&d); ret = krb5_enomem(context); goto out; } krb5_data_free(&d); ret = krb5_storage_to_data(sp, &d); if (ret) { ret = krb5_enomem(context); goto out; } /* sign */ ret = create_checksum(context, server_key, server_cksumtype, d.data, d.length, (char *)d.data + server_offset, server_size); if (ret) { krb5_data_free(&d); goto out; } ret = create_checksum(context, priv_key, priv_cksumtype, (char *)d.data + server_offset, server_size, (char *)d.data + priv_offset, priv_size); if (ret) { krb5_data_free(&d); goto out; } /* done */ *data = d; krb5_data_free(&logon); krb5_storage_free(sp); krb5_storage_free(spdata); return 0; out: krb5_data_free(&logon); if (sp) krb5_storage_free(sp); if (spdata) krb5_storage_free(spdata); return ret; } heimdal-7.5.0/lib/krb5/verify_krb5_conf.cat80000644000175000017500000000470513212450757016714 0ustar niknik VERIFY_KRB5_CONF(8) BSD System Manager's Manual VERIFY_KRB5_CONF(8) NNAAMMEE vveerriiffyy__kkrrbb55__ccoonnff -- checks krb5.conf for obvious errors SSYYNNOOPPSSIISS vveerriiffyy__kkrrbb55__ccoonnff _[_c_o_n_f_i_g_-_f_i_l_e_] DDEESSCCRRIIPPTTIIOONN vveerriiffyy__kkrrbb55__ccoonnff reads the configuration file _k_r_b_5_._c_o_n_f, or the file given on the command line, parses it, checking verifying that the syntax is not correctly wrong. If the file is syntactically correct, vveerriiffyy__kkrrbb55__ccoonnff tries to verify that the contents of the file is of relevant nature. EENNVVIIRROONNMMEENNTT KRB5_CONFIG points to the configuration file to read. FFIILLEESS /etc/krb5.conf Kerberos 5 configuration file DDIIAAGGNNOOSSTTIICCSS Possible output from vveerriiffyy__kkrrbb55__ccoonnff include: : failed to parse as size/time/number/boolean Usually means that is misspelled, or that it contains weird characters. The parsing done by vveerriiffyy__kkrrbb55__ccoonnff is more strict than the one performed by libkrb5, so strings that work in real life might be reported as bad. : host not found () Means that is supposed to point to a host, but it can't be recognised as one. : unknown or wrong type Means that is either a string when it should be a list, vice versa, or just that vveerriiffyy__kkrrbb55__ccoonnff is confused. : unknown entry Means that is not known by vveerriiffyy__kkrrbb55__ccoonnff. SSEEEE AALLSSOO krb5.conf(5) BBUUGGSS Since each application can put almost anything in the config file, it's hard to come up with a watertight verification process. Most of the default settings are sanity checked, but this does not mean that every problem is discovered, or that everything that is reported as a possible problem actually is one. This tool should thus be used with some care. It should warn about obsolete data, or bad practice, but currently doesn't. HEIMDAL December 8, 2004 HEIMDAL heimdal-7.5.0/lib/krb5/test_acl.c0000644000175000017500000001107513026237312014630 0ustar niknik/* * Copyright (c) 2004 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of KTH nor the names of its contributors may be * used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY KTH AND ITS CONTRIBUTORS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL KTH OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "krb5_locl.h" #include #define RETVAL(c, r, e, s) \ do { if (r != e) krb5_errx(c, 1, "%s", s); } while (0) #define STRINGMATCH(c, s, _s1, _s2) \ do { \ if (_s1 == NULL || _s2 == NULL) \ krb5_errx(c, 1, "s1 or s2 is NULL"); \ if (strcmp(_s1,_s2) != 0) \ krb5_errx(c, 1, "%s", s); \ } while (0) static void test_match_string(krb5_context context) { krb5_error_code ret; char *s1, *s2; ret = krb5_acl_match_string(context, "foo", "s", "foo"); RETVAL(context, ret, 0, "single s"); ret = krb5_acl_match_string(context, "foo foo", "s", "foo"); RETVAL(context, ret, EACCES, "too many strings"); ret = krb5_acl_match_string(context, "foo bar", "ss", "foo", "bar"); RETVAL(context, ret, 0, "two strings"); ret = krb5_acl_match_string(context, "foo bar", "ss", "foo", "bar"); RETVAL(context, ret, 0, "two strings double space"); ret = krb5_acl_match_string(context, "foo \tbar", "ss", "foo", "bar"); RETVAL(context, ret, 0, "two strings space + tab"); ret = krb5_acl_match_string(context, "foo", "ss", "foo", "bar"); RETVAL(context, ret, EACCES, "one string, two format strings"); ret = krb5_acl_match_string(context, "foo", "ss", "foo", "foo"); RETVAL(context, ret, EACCES, "one string, two format strings (same)"); ret = krb5_acl_match_string(context, "foo \t", "s", "foo"); RETVAL(context, ret, 0, "ending space"); ret = krb5_acl_match_string(context, "foo/bar", "f", "foo/bar"); RETVAL(context, ret, 0, "liternal fnmatch"); ret = krb5_acl_match_string(context, "foo/bar", "f", "foo/*"); RETVAL(context, ret, 0, "foo/*"); ret = krb5_acl_match_string(context, "foo/bar.example.org", "f", "foo/*.example.org"); RETVAL(context, ret, 0, "foo/*.example.org"); ret = krb5_acl_match_string(context, "foo/bar.example.com", "f", "foo/*.example.org"); RETVAL(context, ret, EACCES, "foo/*.example.com"); ret = krb5_acl_match_string(context, "foo/bar/baz", "f", "foo/*/baz"); RETVAL(context, ret, 0, "foo/*/baz"); ret = krb5_acl_match_string(context, "foo", "r", &s1); RETVAL(context, ret, 0, "ret 1"); STRINGMATCH(context, "ret 1 match", s1, "foo"); free(s1); ret = krb5_acl_match_string(context, "foo bar", "rr", &s1, &s2); RETVAL(context, ret, 0, "ret 2"); STRINGMATCH(context, "ret 2 match 1", s1, "foo"); free(s1); STRINGMATCH(context, "ret 2 match 2", s2, "bar"); free(s2); ret = krb5_acl_match_string(context, "foo bar", "sr", "bar", &s1); RETVAL(context, ret, EACCES, "ret mismatch"); if (s1 != NULL) krb5_errx(context, 1, "s1 not NULL"); ret = krb5_acl_match_string(context, "foo", "l", "foo"); RETVAL(context, ret, EINVAL, "unknown letter"); } int main(int argc, char **argv) { krb5_context context; krb5_error_code ret; setprogname(argv[0]); ret = krb5_init_context(&context); if (ret) errx (1, "krb5_init_context failed: %d", ret); test_match_string(context); krb5_free_context(context); return 0; } heimdal-7.5.0/lib/krb5/krb5_425_conv_principal.30000644000175000017500000001602512136107750017300 0ustar niknik.\" Copyright (c) 1997-2003 Kungliga Tekniska Högskolan .\" (Royal Institute of Technology, Stockholm, Sweden). .\" All rights reserved. .\" .\" Redistribution and use in source and binary forms, with or without .\" modification, are permitted provided that the following conditions .\" are met: .\" .\" 1. Redistributions of source code must retain the above copyright .\" notice, this list of conditions and the following disclaimer. .\" .\" 2. Redistributions in binary form must reproduce the above copyright .\" notice, this list of conditions and the following disclaimer in the .\" documentation and/or other materials provided with the distribution. .\" .\" 3. Neither the name of the Institute nor the names of its contributors .\" may be used to endorse or promote products derived from this software .\" without specific prior written permission. .\" .\" THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND .\" ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE .\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE .\" ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE .\" FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL .\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS .\" OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) .\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT .\" LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF .\" SUCH DAMAGE. .\" .\" $Id$ .\" .Dd September 3, 2003 .Dt KRB5_425_CONV_PRINCIPAL 3 .Os HEIMDAL .Sh NAME .Nm krb5_425_conv_principal , .Nm krb5_425_conv_principal_ext , .Nm krb5_524_conv_principal .Nd converts to and from version 4 principals .Sh LIBRARY Kerberos 5 Library (libkrb5, -lkrb5) .Sh SYNOPSIS .In krb5.h .Ft krb5_error_code .Fn krb5_425_conv_principal "krb5_context context" "const char *name" "const char *instance" "const char *realm" "krb5_principal *principal" .Ft krb5_error_code .Fn krb5_425_conv_principal_ext "krb5_context context" "const char *name" "const char *instance" "const char *realm" "krb5_boolean (*func)(krb5_context, krb5_principal)" "krb5_boolean resolve" "krb5_principal *principal" .Ft krb5_error_code .Fn krb5_524_conv_principal "krb5_context context" "const krb5_principal principal" "char *name" "char *instance" "char *realm" .Sh DESCRIPTION Converting between version 4 and version 5 principals can at best be described as a mess. .Pp A version 4 principal consists of a name, an instance, and a realm. A version 5 principal consists of one or more components, and a realm. In some cases also the first component/name will differ between version 4 and version 5. Furthermore the second component of a host principal will be the fully qualified domain name of the host in question, while the instance of a version 4 principal will only contain the first part (short hostname). Because of these problems the conversion between principals will have to be site customized. .Pp .Fn krb5_425_conv_principal_ext will try to convert a version 4 principal, given by .Fa name , .Fa instance , and .Fa realm , to a version 5 principal. This can result in several possible principals, and if .Fa func is non-NULL, it will be called for each candidate principal. .Fa func should return true if the principal was .Dq good . To accomplish this, .Fn krb5_425_conv_principal_ext will look up the name in .Pa krb5.conf . It first looks in the .Li v4_name_convert/host subsection, which should contain a list of version 4 names whose instance should be treated as a hostname. This list can be specified for each realm (in the .Li realms section), or in the .Li libdefaults section. If the name is found the resulting name of the principal will be the value of this binding. The instance is then first looked up in .Li v4_instance_convert for the specified realm. If found the resulting value will be used as instance (this can be used for special cases), no further attempts will be made to find a conversion if this fails (with .Fa func ) . If the .Fa resolve parameter is true, the instance will be looked up with .Fn gethostbyname . This can be a time consuming, error prone, and unsafe operation. Next a list of hostnames will be created from the instance and the .Li v4_domains variable, which should contain a list of possible domains for the specific realm. .Pp On the other hand, if the name is not found in a .Li host section, it is looked up in a .Li v4_name_convert/plain binding. If found here the name will be converted, but the instance will be untouched. .Pp This list of default host-type conversions is compiled-in: .Bd -literal -offset indent v4_name_convert = { host = { ftp = ftp hprop = hprop imap = imap pop = pop rcmd = host smtp = smtp } } .Ed .Pp It will only be used if there isn't an entry for these names in the config file, so you can override these defaults. .Pp .Fn krb5_425_conv_principal will call .Fn krb5_425_conv_principal_ext with .Dv NULL as .Fa func , and the value of .Li v4_instance_resolve (from the .Li libdefaults section) as .Fa resolve . .Pp .Fn krb5_524_conv_principal basically does the opposite of .Fn krb5_425_conv_principal , it just doesn't have to look up any names, but will instead truncate instances found to belong to a host principal. The .Fa name , .Fa instance , and .Fa realm should be at least 40 characters long. .Sh EXAMPLES Since this is confusing an example is in place. .Pp Assume that we have the .Dq foo.com , and .Dq bar.com domains that have shared a single version 4 realm, FOO.COM. The version 4 .Pa krb.realms file looked like: .Bd -literal -offset indent foo.com FOO.COM \&.foo.com FOO.COM \&.bar.com FOO.COM .Ed .Pp A .Pa krb5.conf file that covers this case might look like: .Bd -literal -offset indent [libdefaults] v4_instance_resolve = yes [realms] FOO.COM = { kdc = kerberos.foo.com v4_instance_convert = { foo = foo.com } v4_domains = foo.com } .Ed .Pp With this setup and the following host table: .Bd -literal -offset indent foo.com a-host.foo.com b-host.bar.com .Ed the following conversions will be made: .Bd -literal -offset indent rcmd.a-host -\*(Gt host/a-host.foo.com ftp.b-host -\*(Gt ftp/b-host.bar.com pop.foo -\*(Gt pop/foo.com ftp.other -\*(Gt ftp/other.foo.com other.a-host -\*(Gt other/a-host .Ed .Pp The first three are what you expect. If you remove the .Dq v4_domains , the fourth entry will result in an error (since the host .Dq other can't be found). Even if .Dq a-host is a valid host name, the last entry will not be converted, since the .Dq other name is not known to represent a host-type principal. If you turn off .Dq v4_instance_resolve the second example will result in .Dq ftp/b-host.foo.com (because of the default domain). And all of this is of course only valid if you have working name resolving. .Sh SEE ALSO .Xr krb5_build_principal 3 , .Xr krb5_free_principal 3 , .Xr krb5_parse_name 3 , .Xr krb5_sname_to_principal 3 , .Xr krb5_unparse_name 3 , .Xr krb5.conf 5 heimdal-7.5.0/lib/krb5/net_read.c0000644000175000017500000000430113026237312014605 0ustar niknik/* * Copyright (c) 1997, 1998, 2002 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "krb5_locl.h" /** * Read \a len bytes from socket \a p_fd into buffer \a buf. * Block until \a len bytes are read or until an error. * * @return If successful, the number of bytes read: \a len. * On end-of-file, 0. * On error, less than 0 (if single-threaded, the error can be found * in the errno global variable). */ KRB5_LIB_FUNCTION krb5_ssize_t KRB5_LIB_CALL krb5_net_read (krb5_context context, void *p_fd, void *buf, size_t len) { krb5_socket_t fd = *((krb5_socket_t *)p_fd); return net_read(fd, buf, len); } heimdal-7.5.0/lib/krb5/expand_hostname.c0000644000175000017500000001266313026237312016213 0ustar niknik/* * Copyright (c) 1999 - 2001 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "krb5_locl.h" static krb5_error_code copy_hostname(krb5_context context, const char *orig_hostname, char **new_hostname) { *new_hostname = strdup (orig_hostname); if (*new_hostname == NULL) return krb5_enomem(context); strlwr (*new_hostname); return 0; } /** * krb5_expand_hostname() tries to make orig_hostname into a more * canonical one in the newly allocated space returned in * new_hostname. * @param context a Keberos context * @param orig_hostname hostname to canonicalise. * @param new_hostname output hostname, caller must free hostname with * krb5_xfree(). * * @return Return an error code or 0, see krb5_get_error_message(). * * @ingroup krb5_support */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_expand_hostname (krb5_context context, const char *orig_hostname, char **new_hostname) { struct addrinfo *ai, *a, hints; int error; if ((context->flags & KRB5_CTX_F_DNS_CANONICALIZE_HOSTNAME) == 0) return copy_hostname (context, orig_hostname, new_hostname); memset (&hints, 0, sizeof(hints)); hints.ai_flags = AI_CANONNAME; error = getaddrinfo (orig_hostname, NULL, &hints, &ai); if (error) return copy_hostname (context, orig_hostname, new_hostname); for (a = ai; a != NULL; a = a->ai_next) { if (a->ai_canonname != NULL) { *new_hostname = strdup (a->ai_canonname); freeaddrinfo (ai); if (*new_hostname == NULL) return krb5_enomem(context); else return 0; } } freeaddrinfo (ai); return copy_hostname (context, orig_hostname, new_hostname); } /* * handle the case of the hostname being unresolvable and thus identical */ static krb5_error_code vanilla_hostname (krb5_context context, const char *orig_hostname, char **new_hostname, char ***realms) { krb5_error_code ret; ret = copy_hostname (context, orig_hostname, new_hostname); if (ret) return ret; strlwr (*new_hostname); ret = krb5_get_host_realm (context, *new_hostname, realms); if (ret) { free (*new_hostname); return ret; } return 0; } /** * krb5_expand_hostname_realms() expands orig_hostname to a name we * believe to be a hostname in newly allocated space in new_hostname * and return the realms new_hostname is believed to belong to in * realms. * * @param context a Keberos context * @param orig_hostname hostname to canonicalise. * @param new_hostname output hostname, caller must free hostname with * krb5_xfree(). * @param realms output possible realms, is an array that is terminated * with NULL. Caller must free with krb5_free_host_realm(). * * @return Return an error code or 0, see krb5_get_error_message(). * * @ingroup krb5_support */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_expand_hostname_realms (krb5_context context, const char *orig_hostname, char **new_hostname, char ***realms) { struct addrinfo *ai, *a, hints; int error; krb5_error_code ret = 0; if ((context->flags & KRB5_CTX_F_DNS_CANONICALIZE_HOSTNAME) == 0) return vanilla_hostname (context, orig_hostname, new_hostname, realms); memset (&hints, 0, sizeof(hints)); hints.ai_flags = AI_CANONNAME; error = getaddrinfo (orig_hostname, NULL, &hints, &ai); if (error) return vanilla_hostname (context, orig_hostname, new_hostname, realms); for (a = ai; a != NULL; a = a->ai_next) { if (a->ai_canonname != NULL) { ret = copy_hostname (context, a->ai_canonname, new_hostname); if (ret) { freeaddrinfo (ai); return ret; } strlwr (*new_hostname); ret = krb5_get_host_realm (context, *new_hostname, realms); if (ret == 0) { freeaddrinfo (ai); return 0; } free (*new_hostname); } } freeaddrinfo(ai); return vanilla_hostname (context, orig_hostname, new_hostname, realms); } heimdal-7.5.0/lib/krb5/krb5.conf.50000644000175000017500000006527513212137553014561 0ustar niknik.\" Copyright (c) 1999 - 2005 Kungliga Tekniska Högskolan .\" (Royal Institute of Technology, Stockholm, Sweden). .\" All rights reserved. .\" .\" Redistribution and use in source and binary forms, with or without .\" modification, are permitted provided that the following conditions .\" are met: .\" .\" 1. Redistributions of source code must retain the above copyright .\" notice, this list of conditions and the following disclaimer. .\" .\" 2. Redistributions in binary form must reproduce the above copyright .\" notice, this list of conditions and the following disclaimer in the .\" documentation and/or other materials provided with the distribution. .\" .\" 3. Neither the name of the Institute nor the names of its contributors .\" may be used to endorse or promote products derived from this software .\" without specific prior written permission. .\" .\" THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND .\" ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE .\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE .\" ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE .\" FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL .\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS .\" OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) .\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT .\" LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF .\" SUCH DAMAGE. .\" .\" $Id$ .\" .Dd May 4, 2005 .Dt KRB5.CONF 5 .Os HEIMDAL .Sh NAME .Nm krb5.conf .Nd configuration file for Kerberos 5 .Sh SYNOPSIS .In krb5.h .Sh DESCRIPTION The .Nm file specifies several configuration parameters for the Kerberos 5 library, as well as for some programs. .Pp The file consists of one or more sections, containing a number of bindings. The value of each binding can be either a string or a list of other bindings. The grammar looks like: .Bd -literal -offset indent file: /* empty */ sections sections: section sections section section: '[' section_name ']' bindings section_name: STRING bindings: binding bindings binding binding: name '=' STRING name '=' '{' bindings '}' name: STRING .Ed .Li STRINGs consists of one or more non-whitespace characters. .Pp STRINGs that are specified later in this man-page uses the following notation. .Bl -tag -width "xxx" -offset indent .It boolean values can be either yes/true or no/false. .It time values can be a list of year, month, day, hour, min, second. Example: 1 month 2 days 30 min. If no unit is given, seconds is assumed. .It etypes valid encryption types are: des-cbc-crc, des-cbc-md4, des-cbc-md5, des3-cbc-sha1, arcfour-hmac-md5, aes128-cts-hmac-sha1-96, and aes256-cts-hmac-sha1-96 . .It address an address can be either a IPv4 or a IPv6 address. .El .Pp Currently recognised sections and bindings are: .Bl -tag -width "xxx" -offset indent .It Li [appdefaults] Specifies the default values to be used for Kerberos applications. You can specify defaults per application, realm, or a combination of these. The preference order is: .Bl -enum -compact .It .Va application Va realm Va option .It .Va application Va option .It .Va realm Va option .It .Va option .El .Pp The supported options are: .Bl -tag -width "xxx" -offset indent .It Li forwardable = Va boolean When obtaining initial credentials, make the credentials forwardable. .It Li proxiable = Va boolean When obtaining initial credentials, make the credentials proxiable. .It Li no-addresses = Va boolean When obtaining initial credentials, request them for an empty set of addresses, making the tickets valid from any address. .It Li ticket_lifetime = Va time Default ticket lifetime. .It Li renew_lifetime = Va time Default renewable ticket lifetime. .It Li encrypt = Va boolean Use encryption, when available. .It Li forward = Va boolean Forward credentials to remote host (for .Xr rsh 1 , .Xr telnet 1 , etc). .El .It Li [libdefaults] .Bl -tag -width "xxx" -offset indent .It Li default_realm = Va REALM Default realm to use, this is also known as your .Dq local realm . The default is the result of .Fn krb5_get_host_realm "local hostname" . .It Li allow_weak_crypto = Va boolean are weak crypto algorithms allowed to be used, among others, DES is considered weak. .It Li clockskew = Va time Maximum time differential (in seconds) allowed when comparing times. Default is 300 seconds (five minutes). .It Li kdc_timeout = Va time Maximum time to wait for a reply from the kdc, default is 3 seconds. .It Li capath = { .Bl -tag -width "xxx" -offset indent .It Va destination-realm Li = Va next-hop-realm .It ... .It Li } .El This is deprecated, see the .Li capaths section below. .It Li default_cc_type = Va cctype sets the default credentials type. .It Li default_cc_name = Va ccname the default credentials cache name. If you want to change the type only use .Li default_cc_type . The string can contain variables that are expanded on runtime. The Only supported variable currently is .Li %{uid} which expands to the current user id. .It Li default_etypes = Va etypes ... A list of default encryption types to use. (Default: all enctypes if allow_weak_crypto = TRUE, else all enctypes except single DES enctypes.) .It Li default_as_etypes = Va etypes ... A list of default encryption types to use in AS requests. (Default: the value of default_etypes.) .It Li default_tgs_etypes = Va etypes ... A list of default encryption types to use in TGS requests. (Default: the value of default_etypes.) .It Li default_etypes_des = Va etypes ... A list of default encryption types to use when requesting a DES credential. .It Li default_keytab_name = Va keytab The keytab to use if no other is specified, default is .Dq FILE:/etc/krb5.keytab . .It Li dns_lookup_kdc = Va boolean Use DNS SRV records to lookup KDC services location. .It Li dns_lookup_realm = Va boolean Use DNS TXT records to lookup domain to realm mappings. .It Li kdc_timesync = Va boolean Try to keep track of the time differential between the local machine and the KDC, and then compensate for that when issuing requests. .It Li max_retries = Va number The max number of times to try to contact each KDC. .It Li large_msg_size = Va number The threshold where protocols with tiny maximum message sizes are not considered usable to send messages to the KDC. .It Li ticket_lifetime = Va time Default ticket lifetime. .It Li renew_lifetime = Va time Default renewable ticket lifetime. .It Li forwardable = Va boolean When obtaining initial credentials, make the credentials forwardable. This option is also valid in the [realms] section. .It Li proxiable = Va boolean When obtaining initial credentials, make the credentials proxiable. This option is also valid in the [realms] section. .It Li verify_ap_req_nofail = Va boolean If enabled, failure to verify credentials against a local key is a fatal error. The application has to be able to read the corresponding service key for this to work. Some applications, like .Xr su 1 , enable this option unconditionally. .It Li warn_pwexpire = Va time How soon to warn for expiring password. Default is seven days. .It Li http_proxy = Va proxy-spec A HTTP-proxy to use when talking to the KDC via HTTP. .It Li dns_proxy = Va proxy-spec Enable using DNS via HTTP. .It Li extra_addresses = Va address ... A list of addresses to get tickets for along with all local addresses. .It Li time_format = Va string How to print time strings in logs, this string is passed to .Xr strftime 3 . .It Li date_format = Va string How to print date strings in logs, this string is passed to .Xr strftime 3 . .It Li log_utc = Va boolean Write log-entries using UTC instead of your local time zone. .It Li scan_interfaces = Va boolean Scan all network interfaces for addresses, as opposed to simply using the address associated with the system's host name. .It Li fcache_version = Va int Use file credential cache format version specified. .It Li fcc-mit-ticketflags = Va boolean Use MIT compatible format for file credential cache. It's the field ticketflags that is stored in reverse bit order for older than Heimdal 0.7. Setting this flag to .Dv TRUE makes it store the MIT way, this is default for Heimdal 0.7. .It Li check-rd-req-server If set to "ignore", the framework will ignore any of the server input to .Xr krb5_rd_req 3 , this is very useful when the GSS-API server input the wrong server name into the gss_accept_sec_context call. .It Li k5login_directory = Va directory Alternative location for user .k5login files. This option is provided for compatibility with MIT krb5 configuration files. .It Li k5login_authoritative = Va boolean If true then if a principal is not found in k5login files then .Xr krb5_userok 3 will not fallback on principal to username mapping. This option is provided for compatibility with MIT krb5 configuration files. .It Li kuserok = Va rule ... Specifies .Xr krb5_userok 3 behavior. If multiple values are given, then .Xr krb5_userok 3 will evaluate them in order until one succeeds or all fail. Rules are implemented by plugins, with three built-in plugins described below. Default: USER-K5LOGIN SIMPLE DENY. .It Li kuserok = Va DENY If set and evaluated then .Xr krb5_userok 3 will deny access to the given username no matter what the principal name might be. .It Li kuserok = Va SIMPLE If set and evaluated then .Xr krb5_userok 3 will use principal to username mapping (see auth_to_local below). If the principal maps to the requested username then access is allowed. .It Li kuserok = Va SYSTEM-K5LOGIN[:directory] If set and evaluated then .Xr krb5_userok 3 will use k5login files named after the .Va luser argument to .Xr krb5_userok 3 in the given directory or in .Pa /etc/k5login.d/ . K5login files are text files, with each line containing just a principal name; principals apearing in a user's k5login file are permitted access to the user's account. Note: this rule performs no ownership nor permissions checks on k5login files; proper ownership and permissions/ACLs are expected due to the k5login location being a system location. .It Li kuserok = Va USER-K5LOGIN If set and evaluated then .Xr krb5_userok 3 will use .Pa ~luser/.k5login and .Pa ~luser/.k5login.d/* . User k5login files and directories must be owned by the user and must not have world nor group write permissions. .It Li aname2lname-text-db = Va filename The named file must be a sorted (in increasing order) text file where every line consists of an unparsed principal name optionally followed by whitespace and a username. The aname2lname function will do a binary search on this file, if configured, looking for lines that match the given principal name, and if found the given username will be used, or, if the username is missing, an error will be returned. If the file doesn't exist, or if no matching line is found then other plugins will be allowed to run. .It Li fcache_strict_checking strict checking in FILE credential caches that owner, no symlink and permissions is correct. .It Li name_canon_rules = Va rules One or more service principal name canonicalization rules. Each rule consists of one or more tokens separated by colon (':'). Currently these rules are used only for hostname canonicalization (usually when getting a service ticket, from a ccache or a TGS, but also when acquiring GSS initiator credentials from a keytab). These rules can be used to implement DNS resolver-like search lists without having to use DNS. .Pp NOTE: Name canonicalization rules are an experimental feature. .Pp The first token is a rule type, one of: .Va as-is, .Va qualify, or .Va nss. .Pp Any remaining tokens must be options tokens: .Va use_fast (use FAST to protect TGS exchanges; currently not supported), .Va use_dnssec (use DNSSEC to protect hostname lookups; currently not supported), .Va ccache_only , .Va use_referrals, .Va no_referrals, .Va lookup_realm, .Va mindots=N, .Va maxdots=N, .Va order=N, domain= .Va domain, realm= .Va realm, match_domain= .Va domain, and match_realm= .Va realm. .Pp When trying to obtain a service ticket for a host-based service principal name, name canonicalization rules are applied to that name in the order given, one by one, until one succeds (a service ticket is obtained), or all fail. Similarly when acquiring GSS initiator credentials from a keytab, and when comparing a non-canonical GSS name to a canonical one. .Pp For each rule the system checks that the hostname has at least .Va mindots periods (if given) in it, at most .Va maxdots periods (if given), that the hostname ends in the given .Va match_domain (if given), and that the realm of the principal matches the .Va match_realm (if given). .Pp .Va As-is rules leave the hostname unmodified but may set a realm. .Va Qualify rules qualify the hostname with the given .Va domain and also may set the realm. The .Va nss rule uses the system resolver to lookup the host's canonical name and is usually not secure. Note that using the .Va nss rule type implies having to have principal aliases in the HDB (though not necessarily in keytabs). .Pp The empty realm denotes "ask the client's realm's TGS". The empty realm may be set as well as matched. .Pp The order in which rules are applied is as follows: first all the rules with explicit .Va order then all other rules in the order in which they appear. If any two rules have the same explicit .Va order , their order of appearance in krb5.conf breaks the tie. Explicitly specifying order can be useful where tools read and write the configuration file without preserving parameter order. .Pp Malformed rules are ignored. .It Li allow_hierarchical_capaths = Va boolean When validating cross-realm transit paths, absent any explicit capath from the client realm to the server realm, allow a hierarchical transit path via the common ancestor domain of the two realms. Defaults to true. Note, absent an explicit setting, hierarchical capaths are always used by the KDC when generating a referral to a destination with which is no direct trust. .El .It Li [domain_realm] This is a list of mappings from DNS domain to Kerberos realm. Each binding in this section looks like: .Pp .Dl domain = realm .Pp The domain can be either a full name of a host or a trailing component, in the latter case the domain-string should start with a period. The trailing component only matches hosts that are in the same domain, ie .Dq .example.com matches .Dq foo.example.com , but not .Dq foo.test.example.com . .Pp The realm may be the token `dns_locate', in which case the actual realm will be determined using DNS (independently of the setting of the `dns_lookup_realm' option). .It Li [realms] .Bl -tag -width "xxx" -offset indent .It Va REALM Li = { .Bl -tag -width "xxx" -offset indent .It Li kdc = Va [service/]host[:port] Specifies a list of kdcs for this realm. If the optional .Va port is absent, the default value for the .Dq kerberos/udp .Dq kerberos/tcp , and .Dq http/tcp port (depending on service) will be used. The kdcs will be used in the order that they are specified. .Pp The optional .Va service specifies over what medium the kdc should be contacted. Possible services are .Dq udp , .Dq tcp , and .Dq http . Http can also be written as .Dq http:// . Default service is .Dq udp and .Dq tcp . .It Li admin_server = Va host[:port] Specifies the admin server for this realm, where all the modifications to the database are performed. .It Li kpasswd_server = Va host[:port] Points to the server where all the password changes are performed. If there is no such entry, the kpasswd port on the admin_server host will be tried. .It Li tgs_require_subkey a boolan variable that defaults to false. Old DCE secd (pre 1.1) might need this to be true. .It Li auth_to_local_names = { .Bl -tag -width "xxx" -offset indent .It Va principal_name = Va username The given .Va principal_name will be mapped to the given .Va username if the .Va REALM is a default realm. .El .It Li } .It Li auth_to_local = HEIMDAL_DEFAULT Use the Heimdal default principal to username mapping. Applies to principals from the .Va REALM if and only if .Va REALM is a default realm. .It Li auth_to_local = DEFAULT Use the MIT default principal to username mapping. Applies to principals from the .Va REALM if and only if .Va REALM is a default realm. .It Li auth_to_local = DB:/path/to/db.txt Use a binary search of the given DB. The DB must be a flat-text file sortedf in the "C" locale, with each record being a line (separated by either LF or CRLF) consisting of a principal name followed by whitespace followed by a username. Applies to principals from the .Va REALM if and only if .Va REALM is a default realm. .It Li auth_to_local = DB:/path/to/db Use the given DB, if there's a plugin for it. Applies to principals from the .Va REALM if and only if .Va REALM is a default realm. .It Li auth_to_local = RULE:... Use the given rule, if there's a plugin for it. Applies to principals from the .Va REALM if and only if .Va REALM is a default realm. .It Li auth_to_local = NONE No additional principal to username mapping is done. Note that .Va auth_to_local_names and any preceding .Va auth_to_local rules have precedence. .El .It Li } .El .It Li [capaths] .Bl -tag -width "xxx" -offset indent .It Va client-realm Li = { .Bl -tag -width "xxx" -offset indent .It Va server-realm Li = Va hop-realm ... This serves two purposes. First the first listed .Va hop-realm tells a client which realm it should contact in order to ultimately obtain credentials for a service in the .Va server-realm . Secondly, it tells the KDC (and other servers) which realms are allowed in a multi-hop traversal from .Va client-realm to .Va server-realm . Except for the client case, the order of the realms are not important. .El .It Va } .El .It Li [logging] .Bl -tag -width "xxx" -offset indent .It Va entity Li = Va destination Specifies that .Va entity should use the specified .Li destination for logging. See the .Xr krb5_openlog 3 manual page for a list of defined destinations. .El .It Li [kdc] .Bl -tag -width "xxx" -offset indent .It Li database Li = { .Bl -tag -width "xxx" -offset indent .It Li dbname Li = Va [DATBASETYPE:]DATABASENAME Use this database for this realm. The .Va DATABASETYPE should be one of 'lmdb', 'db3', 'db1', 'db', 'sqlite', or 'ldap'. See the info documetation how to configure different database backends. .It Li realm Li = Va REALM Specifies the realm that will be stored in this database. It realm isn't set, it will used as the default database, there can only be one entry that doesn't have a .Li realm stanza. .It Li mkey_file Li = Pa FILENAME Use this keytab file for the master key of this database. If not specified .Va DATABASENAME Ns .mkey will be used. .It Li acl_file Li = PA FILENAME Use this file for the ACL list of this database. .It Li log_file Li = Pa FILENAME Use this file as the log of changes performed to the database. This file is used by .Nm ipropd-master for propagating changes to slaves. It is also used by .Nm kadmind and .Nm kadmin (when used with the .Li -l option), and by all applications using .Nm libkadm5 with the local backend, for two-phase commit functionality. Slaves also use this. Setting this to .Nm /dev/null disables two-phase commit and incremental propagation. Use .Nm iprop-log to show the contents of this log file. .It Li log-max-size = Pa number When the log reaches this size (in bytes), the log will be truncated, saving some entries, and keeping the latest version number so as to not disrupt incremental propagation. If set to a negative value then automatic log truncation will be disabled. Defaults to 52428800 (50MB). .El .It Li } .It Li max-request = Va SIZE Maximum size of a kdc request. .It Li require-preauth = Va BOOL If set pre-authentication is required. .It Li ports = Va "list of ports" List of ports the kdc should listen to. .It Li addresses = Va "list of interfaces" List of addresses the kdc should bind to. .It Li enable-http = Va BOOL Should the kdc answer kdc-requests over http. .It Li tgt-use-strongest-session-key = Va BOOL If this is TRUE then the KDC will prefer the strongest key from the client's AS-REQ or TGS-REQ enctype list for the ticket session key that is supported by the KDC and the target principal when the target principal is a krbtgt principal. Else it will prefer the first key from the client's AS-REQ enctype list that is also supported by the KDC and the target principal. Defaults to FALSE. .It Li svc-use-strongest-session-key = Va BOOL Like tgt-use-strongest-session-key, but applies to the session key enctype of tickets for services other than krbtgt principals. Defaults to FALSE. .It Li preauth-use-strongest-session-key = Va BOOL If TRUE then select the strongest possible enctype from the client's AS-REQ for PA-ETYPE-INFO2 (i.e., for password-based pre-authentication). Else pick the first supported enctype from the client's AS-REQ. Defaults to FALSE. .It Li use-strongest-server-key = Va BOOL If TRUE then the KDC picks, for the ticket encrypted part's key, the first supported enctype from the target service principal's hdb entry's current keyset. Else the KDC picks the first supported enctype from the target service principal's hdb entry's current keyset. Defaults to TRUE. .It Li check-ticket-addresses = Va BOOL Verify the addresses in the tickets used in tgs requests. .\" XXX .It Li allow-null-ticket-addresses = Va BOOL Allow address-less tickets. .\" XXX .It Li allow-anonymous = Va BOOL If the kdc is allowed to hand out anonymous tickets. .It Li encode_as_rep_as_tgs_rep = Va BOOL Encode as-rep as tgs-rep tobe compatible with mistakes older DCE secd did. .\" XXX .It Li kdc_warn_pwexpire = Va TIME The time before expiration that the user should be warned that her password is about to expire. .It Li logging = Va Logging What type of logging the kdc should use, see also [logging]/kdc. .It Li hdb-ldap-structural-object Va structural object If the LDAP backend is used for storing principals, this is the structural object that will be used when creating and when reading objects. The default value is account . .It Li hdb-ldap-create-base Va creation dn is the dn that will be appended to the principal when creating entries. Default value is the search dn. .It Li enable-digest = Va BOOL Should the kdc answer digest requests. The default is FALSE. .It Li digests_allowed = Va list of digests Specifies the digests the kdc will reply to. The default is .Li ntlm-v2 . .It Li kx509_ca = Va file Specifies the PEM credentials for the kx509 certification authority. .It Li require_initial_kca_tickets = Va boolean Specified whether to require that tickets for the .Li kca_service service principal be INITIAL. This may be set on a per-realm basis as well as globally. Defaults to true for the global setting. .It Li kx509_include_pkinit_san = Va boolean If true then the kx509 client principal's name and realm will be included in an .Li id-pkinit-san certificate extension. This can be set on a per-realm basis as well as globally. Defaults to true for the global setting. .It Li kx509_template = Va file Specifies the PEM file with a template for the certificates to be issued. The following variables can be interpolated in the subject name using ${variable} syntax: .Bl -tag -width "xxx" -offset indent .It principal-name The full name of the kx509 client principal. .It principal-name-without-realm The full name of the kx509 client principal, excluding the realm name. .It principal-name-realm The name of the client principal's realm. .El .El The .Li kx509 , .Li kx509_template , .Li kx509_include_pkinit_san , and .Li require_initial_kca_tickets parameters may be set on a per-realm basis as well. .It Li [kadmin] .Bl -tag -width "xxx" -offset indent .It Li password_lifetime = Va time If a principal already have its password set for expiration, this is the time it will be valid for after a change. .It Li default_keys = Va keytypes... For each entry in .Va default_keys try to parse it as a sequence of .Va etype:salttype:salt syntax of this if something like: .Pp [(des|des3|etype):](pw-salt|afs3-salt)[:string] .Pp If .Ar etype is omitted it means everything, and if string is omitted it means the default salt string (for that principal and encryption type). Additional special values of keytypes are: .Bl -tag -width "xxx" -offset indent .It Li v5 The Kerberos 5 salt .Va pw-salt .El .It Li default_key_rules = Va { .Bl -tag -width "xxx" -offset indent .It Va globing-rule Li = Va keytypes... a globbing rule to matching a principal, and when true, use the keytypes as specified the same format as [kadmin]default_keys . .El .It Li } .It Li prune-key-history = Va BOOL When adding keys to the key history, drop keys that are too old to match unexpired tickets (based on the principal's maximum ticket lifetime). If the KDC keystore is later compromised traffic protected with the discarded older keys may remain protected. This also keeps the HDB records for principals with key history from growing without bound. The default (backwards compatible) value is "false". .It Li use_v4_salt = Va BOOL When true, this is the same as .Pp .Va default_keys = Va des3:pw-salt Va v4 .Pp and is only left for backwards compatibility. .It Li [password_quality] Check the Password quality assurance in the info documentation for more information. .Bl -tag -width "xxx" -offset indent .It Li check_library = Va library-name Library name that contains the password check_function .It Li check_function = Va function-name Function name for checking passwords in check_library .It Li policy_libraries = Va library1 ... libraryN List of libraries that can do password policy checks .It Li policies = Va policy1 ... policyN List of policy names to apply to the password. Builtin policies are among other minimum-length, character-class, external-check. .El .El .El .Sh ENVIRONMENT .Ev KRB5_CONFIG points to the configuration file to read. .Sh FILES .Bl -tag -width "/etc/krb5.conf" .It Pa /etc/krb5.conf configuration file for Kerberos 5. .El .Sh EXAMPLES .Bd -literal -offset indent [libdefaults] default_realm = FOO.SE name_canon_rules = as-is:realm=FOO.SE name_canon_rules = qualify:domain=foo.se:realm=FOO.SE name_canon_rules = qualify:domain=bar.se:realm=FOO.SE name_canon_rules = nss [domain_realm] .foo.se = FOO.SE .bar.se = FOO.SE [realms] FOO.SE = { kdc = kerberos.foo.se default_domain = foo.se } [logging] kdc = FILE:/var/heimdal/kdc.log kdc = SYSLOG:INFO default = SYSLOG:INFO:USER [kadmin] default_key_rules = { */ppp@* = arcfour-hmac-md5:pw-salt } .Ed .Sh DIAGNOSTICS Since .Nm is read and parsed by the krb5 library, there is not a lot of opportunities for programs to report parsing errors in any useful format. To help overcome this problem, there is a program .Nm verify_krb5_conf that reads .Nm and tries to emit useful diagnostics from parsing errors. Note that this program does not have any way of knowing what options are actually used and thus cannot warn about unknown or misspelled ones. .Sh SEE ALSO .Xr kinit 1 , .Xr krb5_openlog 3 , .Xr strftime 3 , .Xr verify_krb5_conf 8 heimdal-7.5.0/lib/krb5/krb5_err.et0000644000175000017500000003171313026237312014734 0ustar niknik# # Error messages for the krb5 library # # This might look like a com_err file, but is not # id "$Id$" error_table krb5 prefix KRB5KDC_ERR error_code NONE, "No error" error_code NAME_EXP, "Client's entry in database has expired" error_code SERVICE_EXP, "Server's entry in database has expired" error_code BAD_PVNO, "Requested protocol version not supported" error_code C_OLD_MAST_KVNO, "Client's key is encrypted in an old master key" error_code S_OLD_MAST_KVNO, "Server's key is encrypted in an old master key" error_code C_PRINCIPAL_UNKNOWN, "Client not found in Kerberos database" error_code S_PRINCIPAL_UNKNOWN, "Server not found in Kerberos database" error_code PRINCIPAL_NOT_UNIQUE,"Principal has multiple entries in Kerberos database" error_code NULL_KEY, "Client or server has a null key" error_code CANNOT_POSTDATE, "Ticket is ineligible for postdating" error_code NEVER_VALID, "Requested effective lifetime is negative or too short" error_code POLICY, "KDC policy rejects request" error_code BADOPTION, "KDC can't fulfill requested option" error_code ETYPE_NOSUPP, "KDC has no support for encryption type" error_code SUMTYPE_NOSUPP, "KDC has no support for checksum type" error_code PADATA_TYPE_NOSUPP, "KDC has no support for padata type" error_code TRTYPE_NOSUPP, "KDC has no support for transited type" error_code CLIENT_REVOKED, "Clients credentials have been revoked" error_code SERVICE_REVOKED, "Credentials for server have been revoked" error_code TGT_REVOKED, "TGT has been revoked" error_code CLIENT_NOTYET, "Client not yet valid - try again later" error_code SERVICE_NOTYET, "Server not yet valid - try again later" error_code KEY_EXPIRED, "Password has expired" error_code PREAUTH_FAILED, "Preauthentication failed" error_code PREAUTH_REQUIRED, "Additional pre-authentication required" error_code SERVER_NOMATCH, "Requested server and ticket don't match" error_code KDC_ERR_MUST_USE_USER2USER, "Server principal valid for user2user only" error_code PATH_NOT_ACCEPTED, "KDC Policy rejects transited path" error_code SVC_UNAVAILABLE, "A service is not available" index 31 prefix KRB5KRB_AP error_code ERR_BAD_INTEGRITY, "Decrypt integrity check failed" error_code ERR_TKT_EXPIRED, "Ticket expired" error_code ERR_TKT_NYV, "Ticket not yet valid" error_code ERR_REPEAT, "Request is a replay" error_code ERR_NOT_US, "The ticket isn't for us" error_code ERR_BADMATCH, "Ticket/authenticator don't match" error_code ERR_SKEW, "Clock skew too great" error_code ERR_BADADDR, "Incorrect net address" error_code ERR_BADVERSION, "Protocol version mismatch" error_code ERR_MSG_TYPE, "Invalid message type" error_code ERR_MODIFIED, "Message stream modified" error_code ERR_BADORDER, "Message out of order" error_code ERR_ILL_CR_TKT, "Invalid cross-realm ticket" error_code ERR_BADKEYVER, "Key version is not available" error_code ERR_NOKEY, "Service key not available" error_code ERR_MUT_FAIL, "Mutual authentication failed" error_code ERR_BADDIRECTION, "Incorrect message direction" error_code ERR_METHOD, "Alternative authentication method required" error_code ERR_BADSEQ, "Incorrect sequence number in message" error_code ERR_INAPP_CKSUM, "Inappropriate type of checksum in message" error_code PATH_NOT_ACCEPTED, "Policy rejects transited path" prefix KRB5KRB_ERR error_code RESPONSE_TOO_BIG, "Response too big for UDP, retry with TCP" # 53-59 are reserved index 60 error_code GENERIC, "Generic error (see e-text)" error_code FIELD_TOOLONG, "Field is too long for this implementation" # pkinit index 62 prefix KRB5_KDC_ERR error_code CLIENT_NOT_TRUSTED, "Client not trusted" error_code KDC_NOT_TRUSTED, "KDC not trusted" error_code INVALID_SIG, "Invalid signature" error_code DH_KEY_PARAMETERS_NOT_ACCEPTED, "DH parameters not accepted" index 68 prefix KRB5_KDC_ERR error_code WRONG_REALM, "Wrong realm" index 69 prefix KRB5_AP_ERR error_code USER_TO_USER_REQUIRED, "User to user required" index 70 prefix KRB5_KDC_ERR error_code CANT_VERIFY_CERTIFICATE, "Cannot verify certificate" error_code INVALID_CERTIFICATE, "Certificate invalid" error_code REVOKED_CERTIFICATE, "Certificate revoked" error_code REVOCATION_STATUS_UNKNOWN, "Revocation status unknown" error_code REVOCATION_STATUS_UNAVAILABLE, "Revocation status unavaible" error_code CLIENT_NAME_MISMATCH, "Client name mismatch in certificate" error_code INCONSISTENT_KEY_PURPOSE, "Inconsistent key purpose" error_code DIGEST_IN_CERT_NOT_ACCEPTED, "Digest in certificate not accepted" error_code PA_CHECKSUM_MUST_BE_INCLUDED, "paChecksum must be included" error_code DIGEST_IN_SIGNED_DATA_NOT_ACCEPTED, "Digest in signedData not accepted" error_code PUBLIC_KEY_ENCRYPTION_NOT_SUPPORTED, "Public key encryption not supported" ## these are never used #index 80 #prefix KRB5_IAKERB #error_code ERR_KDC_NOT_FOUND, "IAKERB proxy could not find a KDC" #error_code ERR_KDC_NO_RESPONSE, "IAKERB proxy never reeived a response from a KDC" # 82-93 are reserved index 94 error_code INVALID_HASH_ALG, "Invalid OTP digest algorithm" error_code INVALID_ITERATION_COUNT, "Invalid OTP iteration count" # 97-99 are reserved index 100 error_code NO_ACCEPTABLE_KDF, "No acceptable KDF offered" # 101-127 are reserved index 128 prefix error_code KRB5_ERR_RCSID, "$Id$" error_code KRB5_LIBOS_BADLOCKFLAG, "Invalid flag for file lock mode" error_code KRB5_LIBOS_CANTREADPWD, "Cannot read password" error_code KRB5_LIBOS_BADPWDMATCH, "Password mismatch" error_code KRB5_LIBOS_PWDINTR, "Password read interrupted" error_code KRB5_PARSE_ILLCHAR, "Invalid character in component name" error_code KRB5_PARSE_MALFORMED, "Malformed representation of principal" error_code KRB5_CONFIG_CANTOPEN, "Can't open/find configuration file" error_code KRB5_CONFIG_BADFORMAT, "Improper format of configuration file" error_code KRB5_CONFIG_NOTENUFSPACE, "Insufficient space to return complete information" error_code KRB5_BADMSGTYPE, "Invalid message type specified for encoding" error_code KRB5_CC_BADNAME, "Credential cache name malformed" error_code KRB5_CC_UNKNOWN_TYPE, "Unknown credential cache type" error_code KRB5_CC_NOTFOUND, "Matching credential not found" error_code KRB5_CC_END, "End of credential cache reached" error_code KRB5_NO_TKT_SUPPLIED, "Request did not supply a ticket" error_code KRB5KRB_AP_WRONG_PRINC, "Wrong principal in request" error_code KRB5KRB_AP_ERR_TKT_INVALID, "Ticket has invalid flag set" error_code KRB5_PRINC_NOMATCH, "Requested principal and ticket don't match" error_code KRB5_KDCREP_MODIFIED, "KDC reply did not match expectations" error_code KRB5_KDCREP_SKEW, "Clock skew too great in KDC reply" error_code KRB5_IN_TKT_REALM_MISMATCH, "Client/server realm mismatch in initial ticket request" error_code KRB5_PROG_ETYPE_NOSUPP, "Program lacks support for encryption type" error_code KRB5_PROG_KEYTYPE_NOSUPP, "Program lacks support for key type" error_code KRB5_WRONG_ETYPE, "Requested encryption type not used in message" error_code KRB5_PROG_SUMTYPE_NOSUPP, "Program lacks support for checksum type" error_code KRB5_REALM_UNKNOWN, "Cannot find KDC for requested realm" error_code KRB5_SERVICE_UNKNOWN, "Kerberos service unknown" error_code KRB5_KDC_UNREACH, "Cannot contact any KDC for requested realm" error_code KRB5_NO_LOCALNAME, "No local name found for principal name" error_code KRB5_MUTUAL_FAILED, "Mutual authentication failed" # some of these should be combined/supplanted by system codes error_code KRB5_RC_TYPE_EXISTS, "Replay cache type is already registered" error_code KRB5_RC_MALLOC, "No more memory to allocate (in replay cache code)" error_code KRB5_RC_TYPE_NOTFOUND, "Replay cache type is unknown" error_code KRB5_RC_UNKNOWN, "Generic unknown RC error" error_code KRB5_RC_REPLAY, "Message is a replay" error_code KRB5_RC_IO, "Replay I/O operation failed XXX" error_code KRB5_RC_NOIO, "Replay cache type does not support non-volatile storage" error_code KRB5_RC_PARSE, "Replay cache name parse/format error" error_code KRB5_RC_IO_EOF, "End-of-file on replay cache I/O" error_code KRB5_RC_IO_MALLOC, "No more memory to allocate (in replay cache I/O code)" error_code KRB5_RC_IO_PERM, "Permission denied in replay cache code" error_code KRB5_RC_IO_IO, "I/O error in replay cache i/o code" error_code KRB5_RC_IO_UNKNOWN, "Generic unknown RC/IO error" error_code KRB5_RC_IO_SPACE, "Insufficient system space to store replay information" error_code KRB5_TRANS_CANTOPEN, "Can't open/find realm translation file" error_code KRB5_TRANS_BADFORMAT, "Improper format of realm translation file" error_code KRB5_LNAME_CANTOPEN, "Can't open/find lname translation database" error_code KRB5_LNAME_NOTRANS, "No translation available for requested principal" error_code KRB5_LNAME_BADFORMAT, "Improper format of translation database entry" error_code KRB5_CRYPTO_INTERNAL, "Cryptosystem internal error" error_code KRB5_KT_BADNAME, "Key table name malformed" error_code KRB5_KT_UNKNOWN_TYPE, "Unknown Key table type" error_code KRB5_KT_NOTFOUND, "Key table entry not found" error_code KRB5_KT_END, "End of key table reached" error_code KRB5_KT_NOWRITE, "Cannot write to specified key table" error_code KRB5_KT_IOERR, "Error writing to key table" error_code KRB5_NO_TKT_IN_RLM, "Cannot find ticket for requested realm" error_code KRB5DES_BAD_KEYPAR, "DES key has bad parity" error_code KRB5DES_WEAK_KEY, "DES key is a weak key" error_code KRB5_BAD_ENCTYPE, "Bad encryption type" error_code KRB5_BAD_KEYSIZE, "Key size is incompatible with encryption type" error_code KRB5_BAD_MSIZE, "Message size is incompatible with encryption type" error_code KRB5_CC_TYPE_EXISTS, "Credentials cache type is already registered." error_code KRB5_KT_TYPE_EXISTS, "Key table type is already registered." error_code KRB5_CC_IO, "Credentials cache I/O operation failed XXX" error_code KRB5_FCC_PERM, "Credentials cache file permissions incorrect" error_code KRB5_FCC_NOFILE, "No credentials cache file found" error_code KRB5_FCC_INTERNAL, "Internal file credentials cache error" error_code KRB5_CC_WRITE, "Error writing to credentials cache file" error_code KRB5_CC_NOMEM, "No more memory to allocate (in credentials cache code)" error_code KRB5_CC_FORMAT, "Bad format in credentials cache" error_code KRB5_CC_NOT_KTYPE, "No credentials found with supported encryption types" # errors for dual tgt library calls error_code KRB5_INVALID_FLAGS, "Invalid KDC option combination (library internal error)" error_code KRB5_NO_2ND_TKT, "Request missing second ticket" error_code KRB5_NOCREDS_SUPPLIED, "No credentials supplied to library routine" # errors for sendauth (and recvauth) error_code KRB5_SENDAUTH_BADAUTHVERS, "Bad sendauth version was sent" error_code KRB5_SENDAUTH_BADAPPLVERS, "Bad application version was sent (via sendauth)" error_code KRB5_SENDAUTH_BADRESPONSE, "Bad response (during sendauth exchange)" error_code KRB5_SENDAUTH_REJECTED, "Server rejected authentication (during sendauth exchange)" # errors for preauthentication error_code KRB5_PREAUTH_BAD_TYPE, "Unsupported preauthentication type" error_code KRB5_PREAUTH_NO_KEY, "Required preauthentication key not supplied" error_code KRB5_PREAUTH_FAILED, "Generic preauthentication failure" # version number errors error_code KRB5_RCACHE_BADVNO, "Unsupported replay cache format version number" error_code KRB5_CCACHE_BADVNO, "Unsupported credentials cache format version number" error_code KRB5_KEYTAB_BADVNO, "Unsupported key table format version number" # # error_code KRB5_PROG_ATYPE_NOSUPP, "Program lacks support for address type" error_code KRB5_RC_REQUIRED, "Message replay detection requires rcache parameter" error_code KRB5_ERR_BAD_HOSTNAME, "Hostname cannot be canonicalized" error_code KRB5_ERR_HOST_REALM_UNKNOWN, "Cannot determine realm for host" error_code KRB5_SNAME_UNSUPP_NAMETYPE, "Conversion to service principal undefined for name type" error_code KRB5KRB_AP_ERR_V4_REPLY, "Initial Ticket response appears to be Version 4" error_code KRB5_REALM_CANT_RESOLVE, "Cannot resolve KDC for requested realm" error_code KRB5_TKT_NOT_FORWARDABLE, "Requesting ticket can't get forwardable tickets" error_code KRB5_FWD_BAD_PRINCIPAL, "Bad principal name while trying to forward credentials" error_code KRB5_GET_IN_TKT_LOOP, "Looping detected inside krb5_get_in_tkt" error_code KRB5_CONFIG_NODEFREALM, "Configuration file does not specify default realm" error_code KRB5_SAM_UNSUPPORTED, "Bad SAM flags in obtain_sam_padata" error_code KRB5_SAM_INVALID_ETYPE, "Invalid encryption type in SAM challenge" error_code KRB5_SAM_NO_CHECKSUM, "Missing checksum in SAM challenge" error_code KRB5_SAM_BAD_CHECKSUM, "Bad checksum in SAM challenge" index 238 error_code KRB5_OBSOLETE_FN, "Program called an obsolete, deleted function" index 245 error_code KRB5_ERR_BAD_S2K_PARAMS, "Invalid key generation parameters from KDC" error_code KRB5_ERR_NO_SERVICE, "Service not available" error_code KRB5_CC_NOSUPP, "Credential cache function not supported" error_code KRB5_DELTAT_BADFORMAT, "Invalid format of Kerberos lifetime or clock skew string" error_code KRB5_PLUGIN_NO_HANDLE, "Supplied data not handled by this plugin" error_code KRB5_PLUGIN_OP_NOTSUPP, "Plugin does not support the operaton" end heimdal-7.5.0/lib/krb5/salt-aes-sha2.c0000644000175000017500000000771513026237312015404 0ustar niknik/* * Copyright (c) 1997 - 2008 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "krb5_locl.h" int _krb5_AES_SHA2_string_to_default_iterator = 32768; static krb5_error_code AES_SHA2_string_to_key(krb5_context context, krb5_enctype enctype, krb5_data password, krb5_salt salt, krb5_data opaque, krb5_keyblock *key) { krb5_error_code ret; uint32_t iter; struct _krb5_encryption_type *et = NULL; struct _krb5_key_data kd; krb5_data saltp; size_t enctypesz; const EVP_MD *md = NULL; krb5_data_zero(&saltp); kd.key = NULL; kd.schedule = NULL; if (opaque.length == 0) { iter = _krb5_AES_SHA2_string_to_default_iterator; } else if (opaque.length == 4) { unsigned long v; _krb5_get_int(opaque.data, &v, 4); iter = ((uint32_t)v); } else { ret = KRB5_PROG_KEYTYPE_NOSUPP; /* XXX */ goto cleanup; } et = _krb5_find_enctype(enctype); if (et == NULL) { ret = KRB5_PROG_KEYTYPE_NOSUPP; goto cleanup; } kd.schedule = NULL; ALLOC(kd.key, 1); if (kd.key == NULL) { ret = krb5_enomem(context); goto cleanup; } kd.key->keytype = enctype; ret = krb5_data_alloc(&kd.key->keyvalue, et->keytype->size); if (ret) { ret = krb5_enomem(context); goto cleanup; } enctypesz = strlen(et->name) + 1; ret = krb5_data_alloc(&saltp, enctypesz + salt.saltvalue.length); if (ret) { ret = krb5_enomem(context); goto cleanup; } memcpy(saltp.data, et->name, enctypesz); memcpy((unsigned char *)saltp.data + enctypesz, salt.saltvalue.data, salt.saltvalue.length); ret = _krb5_aes_sha2_md_for_enctype(context, enctype, &md); if (ret) goto cleanup; ret = PKCS5_PBKDF2_HMAC(password.data, password.length, saltp.data, saltp.length, iter, md, et->keytype->size, kd.key->keyvalue.data); if (ret != 1) { krb5_set_error_message(context, KRB5_PROG_KEYTYPE_NOSUPP, "Error calculating s2k"); ret = KRB5_PROG_KEYTYPE_NOSUPP; goto cleanup; } ret = _krb5_derive_key(context, et, &kd, "kerberos", strlen("kerberos")); if (ret) goto cleanup; ret = krb5_copy_keyblock_contents(context, kd.key, key); if (ret) goto cleanup; cleanup: krb5_data_free(&saltp); _krb5_free_key_data(context, &kd, et); return ret; } struct salt_type _krb5_AES_SHA2_salt[] = { { KRB5_PW_SALT, "pw-salt", AES_SHA2_string_to_key }, { 0, NULL, NULL } }; heimdal-7.5.0/lib/krb5/krb5_mk_req.cat30000644000175000017500000001432413212450757015652 0ustar niknik KRB5_MK_REQ(3) BSD Library Functions Manual KRB5_MK_REQ(3) NNAAMMEE kkrrbb55__mmkk__rreeqq, kkrrbb55__mmkk__rreeqq__eexxaacctt, kkrrbb55__mmkk__rreeqq__eexxtteennddeedd, kkrrbb55__rrdd__rreeqq, kkrrbb55__rrdd__rreeqq__wwiitthh__kkeeyybblloocckk, kkrrbb55__mmkk__rreepp, kkrrbb55__mmkk__rreepp__eexxaacctt, kkrrbb55__mmkk__rreepp__eexxtteennddeedd, kkrrbb55__rrdd__rreepp, kkrrbb55__bbuuiilldd__aapp__rreeqq, kkrrbb55__vveerriiffyy__aapp__rreeqq -- create and read application authentication request LLIIBBRRAARRYY Kerberos 5 Library (libkrb5, -lkrb5) SSYYNNOOPPSSIISS ##iinncclluuddee <> _k_r_b_5___e_r_r_o_r___c_o_d_e kkrrbb55__mmkk__rreeqq(_k_r_b_5___c_o_n_t_e_x_t _c_o_n_t_e_x_t, _k_r_b_5___a_u_t_h___c_o_n_t_e_x_t _*_a_u_t_h___c_o_n_t_e_x_t, _c_o_n_s_t _k_r_b_5___f_l_a_g_s _a_p___r_e_q___o_p_t_i_o_n_s, _c_o_n_s_t _c_h_a_r _*_s_e_r_v_i_c_e, _c_o_n_s_t _c_h_a_r _*_h_o_s_t_n_a_m_e, _k_r_b_5___d_a_t_a _*_i_n___d_a_t_a, _k_r_b_5___c_c_a_c_h_e _c_c_a_c_h_e, _k_r_b_5___d_a_t_a _*_o_u_t_b_u_f); _k_r_b_5___e_r_r_o_r___c_o_d_e kkrrbb55__mmkk__rreeqq__eexxtteennddeedd(_k_r_b_5___c_o_n_t_e_x_t _c_o_n_t_e_x_t, _k_r_b_5___a_u_t_h___c_o_n_t_e_x_t _*_a_u_t_h___c_o_n_t_e_x_t, _c_o_n_s_t _k_r_b_5___f_l_a_g_s _a_p___r_e_q___o_p_t_i_o_n_s, _k_r_b_5___d_a_t_a _*_i_n___d_a_t_a, _k_r_b_5___c_r_e_d_s _*_i_n___c_r_e_d_s, _k_r_b_5___d_a_t_a _*_o_u_t_b_u_f); _k_r_b_5___e_r_r_o_r___c_o_d_e kkrrbb55__rrdd__rreeqq(_k_r_b_5___c_o_n_t_e_x_t _c_o_n_t_e_x_t, _k_r_b_5___a_u_t_h___c_o_n_t_e_x_t _*_a_u_t_h___c_o_n_t_e_x_t, _c_o_n_s_t _k_r_b_5___d_a_t_a _*_i_n_b_u_f, _k_r_b_5___c_o_n_s_t___p_r_i_n_c_i_p_a_l _s_e_r_v_e_r, _k_r_b_5___k_e_y_t_a_b _k_e_y_t_a_b, _k_r_b_5___f_l_a_g_s _*_a_p___r_e_q___o_p_t_i_o_n_s, _k_r_b_5___t_i_c_k_e_t _*_*_t_i_c_k_e_t); _k_r_b_5___e_r_r_o_r___c_o_d_e kkrrbb55__bbuuiilldd__aapp__rreeqq(_k_r_b_5___c_o_n_t_e_x_t _c_o_n_t_e_x_t, _k_r_b_5___e_n_c_t_y_p_e _e_n_c_t_y_p_e, _k_r_b_5___c_r_e_d_s _*_c_r_e_d, _k_r_b_5___f_l_a_g_s _a_p___o_p_t_i_o_n_s, _k_r_b_5___d_a_t_a _a_u_t_h_e_n_t_i_c_a_t_o_r, _k_r_b_5___d_a_t_a _*_r_e_t_d_a_t_a); _k_r_b_5___e_r_r_o_r___c_o_d_e kkrrbb55__vveerriiffyy__aapp__rreeqq(_k_r_b_5___c_o_n_t_e_x_t _c_o_n_t_e_x_t, _k_r_b_5___a_u_t_h___c_o_n_t_e_x_t _*_a_u_t_h___c_o_n_t_e_x_t, _k_r_b_5___a_p___r_e_q _*_a_p___r_e_q, _k_r_b_5___c_o_n_s_t___p_r_i_n_c_i_p_a_l _s_e_r_v_e_r, _k_r_b_5___k_e_y_b_l_o_c_k _*_k_e_y_b_l_o_c_k, _k_r_b_5___f_l_a_g_s _f_l_a_g_s, _k_r_b_5___f_l_a_g_s _*_a_p___r_e_q___o_p_t_i_o_n_s, _k_r_b_5___t_i_c_k_e_t _*_*_t_i_c_k_e_t); DDEESSCCRRIIPPTTIIOONN The functions documented in this manual page document the functions that facilitates the exchange between a Kerberos client and server. They are the core functions used in the authentication exchange between the client and the server. The kkrrbb55__mmkk__rreeqq and kkrrbb55__mmkk__rreeqq__eexxtteennddeedd creates the Kerberos message KRB_AP_REQ that is sent from the client to the server as the first packet in a client/server exchange. The result that should be sent to server is stored in _o_u_t_b_u_f. _a_u_t_h___c_o_n_t_e_x_t should be allocated with kkrrbb55__aauutthh__ccoonn__iinniitt() or NULL passed in, in that case, it will be allocated and freed internally. The input data _i_n___d_a_t_a will have a checksum calculated over it and check- sum will be transported in the message to the server. _a_p___r_e_q___o_p_t_i_o_n_s can be set to one or more of the following flags: AP_OPTS_USE_SESSION_KEY Use the session key when creating the request, used for user to user authentication. AP_OPTS_MUTUAL_REQUIRED Mark the request as mutual authenticate required so that the receiver returns a mutual authentication packet. The kkrrbb55__rrdd__rreeqq read the AP_REQ in _i_n_b_u_f and verify and extract the con- tent. If _s_e_r_v_e_r is specified, that server will be fetched from the _k_e_y_t_a_b and used unconditionally. If _s_e_r_v_e_r is NULL, the _k_e_y_t_a_b will be search for a matching principal. The _k_e_y_t_a_b argument specifies what keytab to search for receiving princi- pals. The arguments _a_p___r_e_q___o_p_t_i_o_n_s and _t_i_c_k_e_t returns the content. When the AS-REQ is a user to user request, neither of _k_e_y_t_a_b or _p_r_i_n_c_i_p_a_l are used, instead kkrrbb55__rrdd__rreeqq() expects the session key to be set in _a_u_t_h___c_o_n_t_e_x_t. The kkrrbb55__vveerriiffyy__aapp__rreeqq and kkrrbb55__bbuuiilldd__aapp__rreeqq both constructs and verify the AP_REQ message, should not be used by external code. SSEEEE AALLSSOO krb5(3), krb5.conf(5) HEIMDAL August 27, 2005 HEIMDAL heimdal-7.5.0/lib/krb5/krb5_parse_name.30000644000175000017500000000505013026237312016003 0ustar niknik.\" Copyright (c) 1997 Kungliga Tekniska Högskolan .\" (Royal Institute of Technology, Stockholm, Sweden). .\" All rights reserved. .\" .\" Redistribution and use in source and binary forms, with or without .\" modification, are permitted provided that the following conditions .\" are met: .\" .\" 1. Redistributions of source code must retain the above copyright .\" notice, this list of conditions and the following disclaimer. .\" .\" 2. Redistributions in binary form must reproduce the above copyright .\" notice, this list of conditions and the following disclaimer in the .\" documentation and/or other materials provided with the distribution. .\" .\" 3. Neither the name of the Institute nor the names of its contributors .\" may be used to endorse or promote products derived from this software .\" without specific prior written permission. .\" .\" THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND .\" ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE .\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE .\" ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE .\" FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL .\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS .\" OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) .\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT .\" LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF .\" SUCH DAMAGE. .\" .\" $Id$ .\" .Dd May 1, 2006 .Dt KRB5_PARSE_NAME 3 .Os HEIMDAL .Sh NAME .Nm krb5_parse_name .Nd string to principal conversion .Sh LIBRARY Kerberos 5 Library (libkrb5, -lkrb5) .Sh SYNOPSIS .In krb5.h .Ft krb5_error_code .Fn krb5_parse_name "krb5_context context" "const char *name" "krb5_principal *principal" .Sh DESCRIPTION .Fn krb5_parse_name converts a string representation of a principal name to .Nm krb5_principal . The .Fa principal will point to allocated data that should be freed with .Fn krb5_free_principal . .Pp The string should consist of one or more name components separated with slashes .Pq Dq / , optionally followed with an .Dq @ and a realm name. A slash or @ may be contained in a name component by quoting it with a backslash .Pq Dq \e . A realm should not contain slashes or colons. .Sh SEE ALSO .Xr krb5_build_principal 3 , .Xr krb5_free_principal 3 , .Xr krb5_sname_to_principal 3 , .Xr krb5_unparse_name 3 heimdal-7.5.0/lib/krb5/test_pkinit_dh2key.c0000644000175000017500000001563612136107750016647 0ustar niknik/* * Copyright (c) 2005 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of KTH nor the names of its contributors may be * used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY KTH AND ITS CONTRIBUTORS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL KTH OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "krb5_locl.h" #include #include static void test_dh2key(int i, krb5_context context, const heim_octet_string *dh, const heim_octet_string *c_n, const heim_octet_string *k_n, krb5_enctype etype, const heim_octet_string *result) { krb5_error_code ret; krb5_keyblock key; ret = _krb5_pk_octetstring2key(context, etype, dh->data, dh->length, c_n, k_n, &key); if (ret != 0) krb5_err(context, 1, ret, "_krb5_pk_octetstring2key: %d", i); if (key.keyvalue.length != result->length || memcmp(key.keyvalue.data, result->data, result->length) != 0) krb5_errx(context, 1, "resulting key wrong: %d", i); krb5_free_keyblock_contents(context, &key); } struct { krb5_enctype type; krb5_data X; krb5_data key; } tests[] = { /* 0 */ { ETYPE_AES256_CTS_HMAC_SHA1_96, { 256, "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" }, { 32, "\x5e\xe5\x0d\x67\x5c\x80\x9f\xe5\x9e\x4a\x77\x62\xc5\x4b\x65\x83" "\x75\x47\xea\xfb\x15\x9b\xd8\xcd\xc7\x5f\xfc\xa5\x91\x1e\x4c\x41" } }, /* 1 */ { ETYPE_AES256_CTS_HMAC_SHA1_96, { 128, "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" }, { 32, "\xac\xf7\x70\x7c\x08\x97\x3d\xdf\xdb\x27\xcd\x36\x14\x42\xcc\xfb" "\xa3\x55\xc8\x88\x4c\xb4\x72\xf3\x7d\xa6\x36\xd0\x7d\x56\x78\x7e" } }, /* 2 */ { ETYPE_AES256_CTS_HMAC_SHA1_96, { 128, "\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f" "\x10\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a\x0b\x0c\x0d\x0e" "\x0f\x10\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a\x0b\x0c\x0d" "\x0e\x0f\x10\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a\x0b\x0c" "\x0d\x0e\x0f\x10\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a\x0b" "\x0c\x0d\x0e\x0f\x10\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a" "\x0b\x0c\x0d\x0e\x0f\x10\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09" "\x0a\x0b\x0c\x0d\x0e\x0f\x10\x00\x01\x02\x03\x04\x05\x06\x07\x08" }, { 32, "\xc4\x42\xda\x58\x5f\xcb\x80\xe4\x3b\x47\x94\x6f\x25\x40\x93\xe3" "\x73\x29\xd9\x90\x01\x38\x0d\xb7\x83\x71\xdb\x3a\xcf\x5c\x79\x7e" } }, /* 3 */ { ETYPE_AES256_CTS_HMAC_SHA1_96, { 77, "\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f" "\x10\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a\x0b\x0c\x0d\x0e" "\x0f\x10\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a\x0b\x0c\x0d" "\x0e\x0f\x10\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a\x0b\x0c" "\x0d\x0e\x0f\x10\x00\x01\x02\x03" "\x04\x05\x06\x07\x08" }, { 32, "\x00\x53\x95\x3b\x84\xc8\x96\xf4\xeb\x38\x5c\x3f\x2e\x75\x1c\x4a" "\x59\x0e\xd6\xff\xad\xca\x6f\xf6\x4f\x47\xeb\xeb\x8d\x78\x0f\xfc" } } }; static int version_flag = 0; static int help_flag = 0; static struct getargs args[] = { {"version", 0, arg_flag, &version_flag, "print version", NULL }, {"help", 0, arg_flag, &help_flag, NULL, NULL } }; static void usage (int ret) { arg_printusage (args, sizeof(args)/sizeof(*args), NULL, ""); exit (ret); } int main(int argc, char **argv) { krb5_context context; krb5_error_code ret; int i, optidx = 0; setprogname(argv[0]); if(getarg(args, sizeof(args) / sizeof(args[0]), argc, argv, &optidx)) usage(1); if (help_flag) usage (0); if(version_flag){ print_version(NULL); exit(0); } argc -= optidx; argv += optidx; ret = krb5_init_context(&context); if (ret) errx (1, "krb5_init_context failed: %d", ret); for (i = 0; i < sizeof(tests)/sizeof(tests[0]); i++) { test_dh2key(i, context, &tests[i].X, NULL, NULL, tests[i].type, &tests[i].key); } krb5_free_context(context); return 0; } heimdal-7.5.0/lib/krb5/aes-test.c0000644000175000017500000006703313026237312014564 0ustar niknik/* * Copyright (c) 2003-2016 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of KTH nor the names of its contributors may be * used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY KTH AND ITS CONTRIBUTORS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL KTH OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "krb5_locl.h" #include #include #include static int verbose = 0; static void hex_dump_data(const void *data, size_t length) { char *p; hex_encode(data, length, &p); printf("%s\n", p); free(p); } struct { char *password; char *salt; int saltlen; int iterations; krb5_enctype enctype; size_t keylen; char *pbkdf2; char *key; } keys[] = { { "password", "\x10\xDF\x9D\xD7\x83\xE5\xBC\x8A\xCE\xA1\x73\x0E\x74\x35\x5F\x61" "ATHENA.MIT.EDUraeburn", 37, 32768, KRB5_ENCTYPE_AES128_CTS_HMAC_SHA256_128, 16, NULL, "\x08\x9B\xCA\x48\xB1\x05\xEA\x6E\xA7\x7C\xA5\xD2\xF3\x9D\xC5\xE7" }, { "password", "\x10\xDF\x9D\xD7\x83\xE5\xBC\x8A\xCE\xA1\x73\x0E\x74\x35\x5F\x61" "ATHENA.MIT.EDUraeburn", 37, 32768, KRB5_ENCTYPE_AES256_CTS_HMAC_SHA384_192, 32, NULL, "\x45\xBD\x80\x6D\xBF\x6A\x83\x3A\x9C\xFF\xC1\xC9\x45\x89\xA2\x22" "\x36\x7A\x79\xBC\x21\xC4\x13\x71\x89\x06\xE9\xF5\x78\xA7\x84\x67" }, { "password", "ATHENA.MIT.EDUraeburn", -1, 1, ETYPE_AES128_CTS_HMAC_SHA1_96, 16, "\xcd\xed\xb5\x28\x1b\xb2\xf8\x01\x56\x5a\x11\x22\xb2\x56\x35\x15", "\x42\x26\x3c\x6e\x89\xf4\xfc\x28\xb8\xdf\x68\xee\x09\x79\x9f\x15" }, { "password", "ATHENA.MIT.EDUraeburn", -1, 1, ETYPE_AES256_CTS_HMAC_SHA1_96, 32, "\xcd\xed\xb5\x28\x1b\xb2\xf8\x01\x56\x5a\x11\x22\xb2\x56\x35\x15" "\x0a\xd1\xf7\xa0\x4b\xb9\xf3\xa3\x33\xec\xc0\xe2\xe1\xf7\x08\x37", "\xfe\x69\x7b\x52\xbc\x0d\x3c\xe1\x44\x32\xba\x03\x6a\x92\xe6\x5b" "\xbb\x52\x28\x09\x90\xa2\xfa\x27\x88\x39\x98\xd7\x2a\xf3\x01\x61" }, { "password", "ATHENA.MIT.EDUraeburn", -1, 2, ETYPE_AES128_CTS_HMAC_SHA1_96, 16, "\x01\xdb\xee\x7f\x4a\x9e\x24\x3e\x98\x8b\x62\xc7\x3c\xda\x93\x5d", "\xc6\x51\xbf\x29\xe2\x30\x0a\xc2\x7f\xa4\x69\xd6\x93\xbd\xda\x13" }, { "password", "ATHENA.MIT.EDUraeburn", -1, 2, ETYPE_AES256_CTS_HMAC_SHA1_96, 32, "\x01\xdb\xee\x7f\x4a\x9e\x24\x3e\x98\x8b\x62\xc7\x3c\xda\x93\x5d" "\xa0\x53\x78\xb9\x32\x44\xec\x8f\x48\xa9\x9e\x61\xad\x79\x9d\x86", "\xa2\xe1\x6d\x16\xb3\x60\x69\xc1\x35\xd5\xe9\xd2\xe2\x5f\x89\x61" "\x02\x68\x56\x18\xb9\x59\x14\xb4\x67\xc6\x76\x22\x22\x58\x24\xff" }, { "password", "ATHENA.MIT.EDUraeburn", -1, 1200, ETYPE_AES128_CTS_HMAC_SHA1_96, 16, "\x5c\x08\xeb\x61\xfd\xf7\x1e\x4e\x4e\xc3\xcf\x6b\xa1\xf5\x51\x2b", "\x4c\x01\xcd\x46\xd6\x32\xd0\x1e\x6d\xbe\x23\x0a\x01\xed\x64\x2a" }, { "password", "ATHENA.MIT.EDUraeburn", -1, 1200, ETYPE_AES256_CTS_HMAC_SHA1_96, 32, "\x5c\x08\xeb\x61\xfd\xf7\x1e\x4e\x4e\xc3\xcf\x6b\xa1\xf5\x51\x2b" "\xa7\xe5\x2d\xdb\xc5\xe5\x14\x2f\x70\x8a\x31\xe2\xe6\x2b\x1e\x13", "\x55\xa6\xac\x74\x0a\xd1\x7b\x48\x46\x94\x10\x51\xe1\xe8\xb0\xa7" "\x54\x8d\x93\xb0\xab\x30\xa8\xbc\x3f\xf1\x62\x80\x38\x2b\x8c\x2a" }, { "password", "\x12\x34\x56\x78\x78\x56\x34\x12", 8, 5, ETYPE_AES128_CTS_HMAC_SHA1_96, 16, "\xd1\xda\xa7\x86\x15\xf2\x87\xe6\xa1\xc8\xb1\x20\xd7\x06\x2a\x49", "\xe9\xb2\x3d\x52\x27\x37\x47\xdd\x5c\x35\xcb\x55\xbe\x61\x9d\x8e" }, { "password", "\x12\x34\x56\x78\x78\x56\x34\x12", 8, 5, ETYPE_AES256_CTS_HMAC_SHA1_96, 32, "\xd1\xda\xa7\x86\x15\xf2\x87\xe6\xa1\xc8\xb1\x20\xd7\x06\x2a\x49" "\x3f\x98\xd2\x03\xe6\xbe\x49\xa6\xad\xf4\xfa\x57\x4b\x6e\x64\xee", "\x97\xa4\xe7\x86\xbe\x20\xd8\x1a\x38\x2d\x5e\xbc\x96\xd5\x90\x9c" "\xab\xcd\xad\xc8\x7c\xa4\x8f\x57\x45\x04\x15\x9f\x16\xc3\x6e\x31" }, { "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", "pass phrase equals block size", -1, 1200, ETYPE_AES128_CTS_HMAC_SHA1_96, 16, "\x13\x9c\x30\xc0\x96\x6b\xc3\x2b\xa5\x5f\xdb\xf2\x12\x53\x0a\xc9", "\x59\xd1\xbb\x78\x9a\x82\x8b\x1a\xa5\x4e\xf9\xc2\x88\x3f\x69\xed" }, { "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", "pass phrase equals block size", -1, 1200, ETYPE_AES256_CTS_HMAC_SHA1_96, 32, "\x13\x9c\x30\xc0\x96\x6b\xc3\x2b\xa5\x5f\xdb\xf2\x12\x53\x0a\xc9" "\xc5\xec\x59\xf1\xa4\x52\xf5\xcc\x9a\xd9\x40\xfe\xa0\x59\x8e\xd1", "\x89\xad\xee\x36\x08\xdb\x8b\xc7\x1f\x1b\xfb\xfe\x45\x94\x86\xb0" "\x56\x18\xb7\x0c\xba\xe2\x20\x92\x53\x4e\x56\xc5\x53\xba\x4b\x34" }, { "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", "pass phrase exceeds block size", -1, 1200, ETYPE_AES128_CTS_HMAC_SHA1_96, 16, "\x9c\xca\xd6\xd4\x68\x77\x0c\xd5\x1b\x10\xe6\xa6\x87\x21\xbe\x61", "\xcb\x80\x05\xdc\x5f\x90\x17\x9a\x7f\x02\x10\x4c\x00\x18\x75\x1d" }, { "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", "pass phrase exceeds block size", -1, 1200, ETYPE_AES256_CTS_HMAC_SHA1_96, 32, "\x9c\xca\xd6\xd4\x68\x77\x0c\xd5\x1b\x10\xe6\xa6\x87\x21\xbe\x61" "\x1a\x8b\x4d\x28\x26\x01\xdb\x3b\x36\xbe\x92\x46\x91\x5e\xc8\x2a", "\xd7\x8c\x5c\x9c\xb8\x72\xa8\xc9\xda\xd4\x69\x7f\x0b\xb5\xb2\xd2" "\x14\x96\xc8\x2b\xeb\x2c\xae\xda\x21\x12\xfc\xee\xa0\x57\x40\x1b" }, { "\xf0\x9d\x84\x9e" /* g-clef */, "EXAMPLE.COMpianist", -1, 50, ETYPE_AES128_CTS_HMAC_SHA1_96, 16, "\x6b\x9c\xf2\x6d\x45\x45\x5a\x43\xa5\xb8\xbb\x27\x6a\x40\x3b\x39", "\xf1\x49\xc1\xf2\xe1\x54\xa7\x34\x52\xd4\x3e\x7f\xe6\x2a\x56\xe5" }, { "\xf0\x9d\x84\x9e" /* g-clef */, "EXAMPLE.COMpianist", -1, 50, ETYPE_AES256_CTS_HMAC_SHA1_96, 32, "\x6b\x9c\xf2\x6d\x45\x45\x5a\x43\xa5\xb8\xbb\x27\x6a\x40\x3b\x39" "\xe7\xfe\x37\xa0\xc4\x1e\x02\xc2\x81\xff\x30\x69\xe1\xe9\x4f\x52", "\x4b\x6d\x98\x39\xf8\x44\x06\xdf\x1f\x09\xcc\x16\x6d\xb4\xb8\x3c" "\x57\x18\x48\xb7\x84\xa3\xd6\xbd\xc3\x46\x58\x9a\x3e\x39\x3f\x9e" }, { "foo", "", -1, 0, ETYPE_ARCFOUR_HMAC_MD5, 16, NULL, "\xac\x8e\x65\x7f\x83\xdf\x82\xbe\xea\x5d\x43\xbd\xaf\x78\x00\xcc" }, { "test", "", -1, 0, ETYPE_ARCFOUR_HMAC_MD5, 16, NULL, "\x0c\xb6\x94\x88\x05\xf7\x97\xbf\x2a\x82\x80\x79\x73\xb8\x95\x37" } }; static int string_to_key_test(krb5_context context) { krb5_data password, opaque; krb5_error_code ret; krb5_salt salt; int i, val = 0; char iter[4]; for (i = 0; i < sizeof(keys)/sizeof(keys[0]); i++) { password.data = keys[i].password; password.length = strlen(password.data); salt.salttype = KRB5_PW_SALT; salt.saltvalue.data = keys[i].salt; if (keys[i].saltlen == -1) salt.saltvalue.length = strlen(salt.saltvalue.data); else salt.saltvalue.length = keys[i].saltlen; opaque.data = iter; opaque.length = sizeof(iter); _krb5_put_int(iter, keys[i].iterations, 4); if (keys[i].pbkdf2) { unsigned char keyout[32]; if (keys[i].keylen > sizeof(keyout)) abort(); PKCS5_PBKDF2_HMAC(password.data, password.length, salt.saltvalue.data, salt.saltvalue.length, keys[i].iterations, EVP_sha1(), keys[i].keylen, keyout); if (memcmp(keyout, keys[i].pbkdf2, keys[i].keylen) != 0) { krb5_warnx(context, "%d: pbkdf2", i); val = 1; hex_dump_data(keyout, keys[i].keylen); continue; } if (verbose) { printf("PBKDF2:\n"); hex_dump_data(keyout, keys[i].keylen); } } { krb5_keyblock key; ret = krb5_string_to_key_data_salt_opaque (context, keys[i].enctype, password, salt, opaque, &key); if (ret) { krb5_warn(context, ret, "%d: string_to_key_data_salt_opaque", i); val = 1; continue; } if (key.keyvalue.length != keys[i].keylen) { krb5_warnx(context, "%d: key wrong length (%lu/%lu)", i, (unsigned long)key.keyvalue.length, (unsigned long)keys[i].keylen); val = 1; continue; } if (memcmp(key.keyvalue.data, keys[i].key, keys[i].keylen) != 0) { krb5_warnx(context, "%d: key wrong", i); val = 1; hex_dump_data(key.keyvalue.data, key.keyvalue.length); hex_dump_data(keys[i].key, keys[i].keylen); continue; } if (verbose) { printf("key:\n"); hex_dump_data(key.keyvalue.data, key.keyvalue.length); } krb5_free_keyblock_contents(context, &key); } } return val; } static int krb_enc(krb5_context context, krb5_crypto crypto, unsigned usage, krb5_data *cipher, krb5_data *clear) { krb5_data decrypt; krb5_error_code ret; krb5_data_zero(&decrypt); ret = krb5_decrypt(context, crypto, usage, cipher->data, cipher->length, &decrypt); if (ret) { krb5_warn(context, ret, "krb5_decrypt"); return ret; } if (decrypt.length != clear->length || memcmp(decrypt.data, clear->data, decrypt.length) != 0) { krb5_warnx(context, "clear text not same"); return EINVAL; } krb5_data_free(&decrypt); return 0; } static int krb_enc_iov2(krb5_context context, krb5_crypto crypto, unsigned usage, size_t cipher_len, krb5_data *clear) { krb5_crypto_iov iov[4]; krb5_data decrypt; int ret; char *p, *q; size_t len, i; p = clear->data; len = clear->length; iov[0].flags = KRB5_CRYPTO_TYPE_HEADER; krb5_crypto_length(context, crypto, iov[0].flags, &iov[0].data.length); iov[0].data.data = emalloc(iov[0].data.length); iov[1].flags = KRB5_CRYPTO_TYPE_DATA; iov[1].data.length = len; iov[1].data.data = emalloc(iov[1].data.length); memcpy(iov[1].data.data, p, iov[1].data.length); /* padding buffer */ iov[2].flags = KRB5_CRYPTO_TYPE_PADDING; krb5_crypto_length(context, crypto, KRB5_CRYPTO_TYPE_PADDING, &iov[2].data.length); iov[2].data.data = emalloc(iov[2].data.length); iov[3].flags = KRB5_CRYPTO_TYPE_TRAILER; krb5_crypto_length(context, crypto, iov[3].flags, &iov[3].data.length); iov[3].data.data = emalloc(iov[3].data.length); ret = krb5_encrypt_iov_ivec(context, crypto, usage, iov, sizeof(iov)/sizeof(iov[0]), NULL); if (ret) errx(1, "encrypt iov failed: %d", ret); /* check len */ for (i = 0, len = 0; i < sizeof(iov)/sizeof(iov[0]); i++) len += iov[i].data.length; if (len != cipher_len) errx(1, "cipher len wrong"); /* * Plain decrypt */ p = q = emalloc(len); for (i = 0; i < sizeof(iov)/sizeof(iov[0]); i++) { memcpy(q, iov[i].data.data, iov[i].data.length); q += iov[i].data.length; } ret = krb5_decrypt(context, crypto, usage, p, len, &decrypt); if (ret) krb5_err(context, 1, ret, "krb5_decrypt"); else krb5_data_free(&decrypt); free(p); /* * Now decrypt use iov */ /* padding turn into data */ p = q = emalloc(iov[1].data.length + iov[2].data.length); memcpy(q, iov[1].data.data, iov[1].data.length); q += iov[1].data.length; memcpy(q, iov[2].data.data, iov[2].data.length); free(iov[1].data.data); free(iov[2].data.data); iov[1].data.data = p; iov[1].data.length += iov[2].data.length; iov[2].flags = KRB5_CRYPTO_TYPE_EMPTY; iov[2].data.length = 0; ret = krb5_decrypt_iov_ivec(context, crypto, usage, iov, sizeof(iov)/sizeof(iov[0]), NULL); free(iov[0].data.data); free(iov[3].data.data); if (ret) krb5_err(context, 1, ret, "decrypt iov failed: %d", ret); if (clear->length != iov[1].data.length) errx(1, "length incorrect"); p = clear->data; if (memcmp(iov[1].data.data, p, iov[1].data.length) != 0) errx(1, "iov[1] incorrect"); free(iov[1].data.data); return 0; } static int krb_enc_iov(krb5_context context, krb5_crypto crypto, unsigned usage, krb5_data *cipher, krb5_data *clear) { krb5_crypto_iov iov[3]; int ret; char *p; size_t len; p = cipher->data; len = cipher->length; iov[0].flags = KRB5_CRYPTO_TYPE_HEADER; krb5_crypto_length(context, crypto, iov[0].flags, &iov[0].data.length); iov[0].data.data = emalloc(iov[0].data.length); memcpy(iov[0].data.data, p, iov[0].data.length); p += iov[0].data.length; len -= iov[0].data.length; iov[1].flags = KRB5_CRYPTO_TYPE_TRAILER; krb5_crypto_length(context, crypto, iov[1].flags, &iov[1].data.length); iov[1].data.data = emalloc(iov[1].data.length); memcpy(iov[1].data.data, p + len - iov[1].data.length, iov[1].data.length); len -= iov[1].data.length; iov[2].flags = KRB5_CRYPTO_TYPE_DATA; iov[2].data.length = len; iov[2].data.data = emalloc(len); memcpy(iov[2].data.data, p, len); ret = krb5_decrypt_iov_ivec(context, crypto, usage, iov, sizeof(iov)/sizeof(iov[0]), NULL); if (ret) krb5_err(context, 1, ret, "krb_enc_iov decrypt iov failed: %d", ret); if (clear->length != iov[2].data.length) errx(1, "length incorrect"); p = clear->data; if (memcmp(iov[2].data.data, p, iov[2].data.length) != 0) errx(1, "iov[2] incorrect"); free(iov[0].data.data); free(iov[1].data.data); free(iov[2].data.data); return 0; } static int krb_checksum_iov(krb5_context context, krb5_crypto crypto, unsigned usage, krb5_data *plain, krb5_data *verify) { krb5_crypto_iov iov[3]; int ret; char *p; size_t len; p = plain->data; len = plain->length; iov[0].flags = KRB5_CRYPTO_TYPE_CHECKSUM; if (verify) { iov[0].data = *verify; } else { krb5_crypto_length(context, crypto, iov[0].flags, &iov[0].data.length); iov[0].data.data = emalloc(iov[0].data.length); } iov[1].flags = KRB5_CRYPTO_TYPE_DATA; iov[1].data.length = len; iov[1].data.data = p; iov[2].flags = KRB5_CRYPTO_TYPE_TRAILER; krb5_crypto_length(context, crypto, iov[0].flags, &iov[2].data.length); iov[2].data.data = malloc(iov[2].data.length); if (verify == NULL) { ret = krb5_create_checksum_iov(context, crypto, usage, iov, sizeof(iov)/sizeof(iov[0]), NULL); if (ret) krb5_err(context, 1, ret, "krb5_create_checksum_iov failed"); } ret = krb5_verify_checksum_iov(context, crypto, usage, iov, sizeof(iov)/sizeof(iov[0]), NULL); if (ret) krb5_err(context, 1, ret, "krb5_verify_checksum_iov"); if (verify == NULL) free(iov[0].data.data); free(iov[2].data.data); return 0; } static int krb_enc_mit(krb5_context context, krb5_enctype enctype, krb5_keyblock *key, unsigned usage, krb5_data *cipher, krb5_data *clear) { #ifndef HEIMDAL_SMALLER krb5_error_code ret; krb5_enc_data e; krb5_data decrypt; size_t len; e.kvno = 0; e.enctype = enctype; e.ciphertext = *cipher; ret = krb5_c_decrypt(context, *key, usage, NULL, &e, &decrypt); if (ret) return ret; if (decrypt.length != clear->length || memcmp(decrypt.data, clear->data, decrypt.length) != 0) { krb5_warnx(context, "clear text not same"); return EINVAL; } krb5_data_free(&decrypt); ret = krb5_c_encrypt_length(context, enctype, clear->length, &len); if (ret) return ret; if (len != cipher->length) { krb5_warnx(context, "c_encrypt_length wrong %lu != %lu", (unsigned long)len, (unsigned long)cipher->length); return EINVAL; } #endif /* HEIMDAL_SMALLER */ return 0; } struct { krb5_enctype enctype; unsigned usage; size_t keylen; void *key; size_t elen; void* edata; size_t plen; void *pdata; size_t clen; /* checksum length */ void *cdata; /* checksum data */ } krbencs[] = { { ETYPE_AES256_CTS_HMAC_SHA1_96, 7, 32, "\x47\x75\x69\x64\x65\x6c\x69\x6e\x65\x73\x20\x74\x6f\x20\x41\x75" "\x74\x68\x6f\x72\x73\x20\x6f\x66\x20\x49\x6e\x74\x65\x72\x6e\x65", 44, "\xcf\x79\x8f\x0d\x76\xf3\xe0\xbe\x8e\x66\x94\x70\xfa\xcc\x9e\x91" "\xa9\xec\x1c\x5c\x21\xfb\x6e\xef\x1a\x7a\xc8\xc1\xcc\x5a\x95\x24" "\x6f\x9f\xf4\xd5\xbe\x5d\x59\x97\x44\xd8\x47\xcd", 16, "\x54\x68\x69\x73\x20\x69\x73\x20\x61\x20\x74\x65\x73\x74\x2e\x0a", 0, NULL }, { KRB5_ENCTYPE_AES128_CTS_HMAC_SHA256_128, 2, 16, "\x37\x05\xD9\x60\x80\xC1\x77\x28\xA0\xE8\x00\xEA\xB6\xE0\xD2\x3C", 32, "\xEF\x85\xFB\x89\x0B\xB8\x47\x2F\x4D\xAB\x20\x39\x4D\xCA\x78\x1D" "\xAD\x87\x7E\xDA\x39\xD5\x0C\x87\x0C\x0D\x5A\x0A\x8E\x48\xC7\x18", 0, "", 0, NULL }, { KRB5_ENCTYPE_AES128_CTS_HMAC_SHA256_128, 2, 16, "\x37\x05\xD9\x60\x80\xC1\x77\x28\xA0\xE8\x00\xEA\xB6\xE0\xD2\x3C", 38, "\x84\xD7\xF3\x07\x54\xED\x98\x7B\xAB\x0B\xF3\x50\x6B\xEB\x09\xCF" "\xB5\x54\x02\xCE\xF7\xE6\x87\x7C\xE9\x9E\x24\x7E\x52\xD1\x6E\xD4" "\x42\x1D\xFD\xF8\x97\x6C", 6, "\x00\x01\x02\x03\x04\x05", 0, NULL }, { KRB5_ENCTYPE_AES128_CTS_HMAC_SHA256_128, 2, 16, "\x37\x05\xD9\x60\x80\xC1\x77\x28\xA0\xE8\x00\xEA\xB6\xE0\xD2\x3C", 48, "\x35\x17\xD6\x40\xF5\x0D\xDC\x8A\xD3\x62\x87\x22\xB3\x56\x9D\x2A" "\xE0\x74\x93\xFA\x82\x63\x25\x40\x80\xEA\x65\xC1\x00\x8E\x8F\xC2" "\x95\xFB\x48\x52\xE7\xD8\x3E\x1E\x7C\x48\xC3\x7E\xEB\xE6\xB0\xD3", 16, "\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0A\x0B\x0C\x0D\x0E\x0F", 0, NULL }, { KRB5_ENCTYPE_AES128_CTS_HMAC_SHA256_128, 2, 16, "\x37\x05\xD9\x60\x80\xC1\x77\x28\xA0\xE8\x00\xEA\xB6\xE0\xD2\x3C", 53, "\x72\x0F\x73\xB1\x8D\x98\x59\xCD\x6C\xCB\x43\x46\x11\x5C\xD3\x36" "\xC7\x0F\x58\xED\xC0\xC4\x43\x7C\x55\x73\x54\x4C\x31\xC8\x13\xBC" "\xE1\xE6\xD0\x72\xC1\x86\xB3\x9A\x41\x3C\x2F\x92\xCA\x9B\x83\x34" "\xA2\x87\xFF\xCB\xFC", 21, "\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0A\x0B\x0C\x0D\x0E\x0F" "\x10\x11\x12\x13\x14", 16, "\xD7\x83\x67\x18\x66\x43\xD6\x7B\x41\x1C\xBA\x91\x39\xFC\x1D\xEE" }, { KRB5_ENCTYPE_AES256_CTS_HMAC_SHA384_192, 2, 32, "\x6D\x40\x4D\x37\xFA\xF7\x9F\x9D\xF0\xD3\x35\x68\xD3\x20\x66\x98" "\x00\xEB\x48\x36\x47\x2E\xA8\xA0\x26\xD1\x6B\x71\x82\x46\x0C\x52", 40, "\x41\xF5\x3F\xA5\xBF\xE7\x02\x6D\x91\xFA\xF9\xBE\x95\x91\x95\xA0" "\x58\x70\x72\x73\xA9\x6A\x40\xF0\xA0\x19\x60\x62\x1A\xC6\x12\x74" "\x8B\x9B\xBF\xBE\x7E\xB4\xCE\x3C", 0, "", 0, NULL }, { KRB5_ENCTYPE_AES256_CTS_HMAC_SHA384_192, 2, 32, "\x6D\x40\x4D\x37\xFA\xF7\x9F\x9D\xF0\xD3\x35\x68\xD3\x20\x66\x98" "\x00\xEB\x48\x36\x47\x2E\xA8\xA0\x26\xD1\x6B\x71\x82\x46\x0C\x52", 46, "\x4E\xD7\xB3\x7C\x2B\xCA\xC8\xF7\x4F\x23\xC1\xCF\x07\xE6\x2B\xC7" "\xB7\x5F\xB3\xF6\x37\xB9\xF5\x59\xC7\xF6\x64\xF6\x9E\xAB\x7B\x60" "\x92\x23\x75\x26\xEA\x0D\x1F\x61\xCB\x20\xD6\x9D\x10\xF2", 6, "\x00\x01\x02\x03\x04\x05", 0, NULL }, { KRB5_ENCTYPE_AES256_CTS_HMAC_SHA384_192, 2, 32, "\x6D\x40\x4D\x37\xFA\xF7\x9F\x9D\xF0\xD3\x35\x68\xD3\x20\x66\x98" "\x00\xEB\x48\x36\x47\x2E\xA8\xA0\x26\xD1\x6B\x71\x82\x46\x0C\x52", 56, "\xBC\x47\xFF\xEC\x79\x98\xEB\x91\xE8\x11\x5C\xF8\xD1\x9D\xAC\x4B" "\xBB\xE2\xE1\x63\xE8\x7D\xD3\x7F\x49\xBE\xCA\x92\x02\x77\x64\xF6" "\x8C\xF5\x1F\x14\xD7\x98\xC2\x27\x3F\x35\xDF\x57\x4D\x1F\x93\x2E" "\x40\xC4\xFF\x25\x5B\x36\xA2\x66", 16, "\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0A\x0B\x0C\x0D\x0E\x0F", 0, NULL }, { KRB5_ENCTYPE_AES256_CTS_HMAC_SHA384_192, 2, 32, "\x6D\x40\x4D\x37\xFA\xF7\x9F\x9D\xF0\xD3\x35\x68\xD3\x20\x66\x98" "\x00\xEB\x48\x36\x47\x2E\xA8\xA0\x26\xD1\x6B\x71\x82\x46\x0C\x52", 61, "\x40\x01\x3E\x2D\xF5\x8E\x87\x51\x95\x7D\x28\x78\xBC\xD2\xD6\xFE" "\x10\x1C\xCF\xD5\x56\xCB\x1E\xAE\x79\xDB\x3C\x3E\xE8\x64\x29\xF2" "\xB2\xA6\x02\xAC\x86\xFE\xF6\xEC\xB6\x47\xD6\x29\x5F\xAE\x07\x7A" "\x1F\xEB\x51\x75\x08\xD2\xC1\x6B\x41\x92\xE0\x1F\x62", 21, "\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0A\x0B\x0C\x0D\x0E\x0F" "\x10\x11\x12\x13\x14", 24, "\x45\xEE\x79\x15\x67\xEE\xFC\xA3\x7F\x4A\xC1\xE0\x22\x2D\xE8\x0D" "\x43\xC3\xBF\xA0\x66\x99\x67\x2A" } }; static int krb_enc_test(krb5_context context) { krb5_error_code ret; krb5_crypto crypto; krb5_keyblock kb; krb5_data cipher, plain; int i; for (i = 0; i < sizeof(krbencs)/sizeof(krbencs[0]); i++) { kb.keytype = krbencs[i].enctype; kb.keyvalue.length = krbencs[i].keylen; kb.keyvalue.data = krbencs[i].key; ret = krb5_crypto_init(context, &kb, krbencs[i].enctype, &crypto); cipher.length = krbencs[i].elen; cipher.data = krbencs[i].edata; plain.length = krbencs[i].plen; plain.data = krbencs[i].pdata; ret = krb_enc(context, crypto, krbencs[i].usage, &cipher, &plain); if (ret) errx(1, "krb_enc failed with %d for test %d", ret, i); ret = krb_enc_iov(context, crypto, krbencs[i].usage, &cipher, &plain); if (ret) errx(1, "krb_enc_iov failed with %d for test %d", ret, i); ret = krb_enc_iov2(context, crypto, krbencs[i].usage, cipher.length, &plain); if (ret) errx(1, "krb_enc_iov2 failed with %d for test %d", ret, i); ret = krb_checksum_iov(context, crypto, krbencs[i].usage, &plain, NULL); if (ret) errx(1, "krb_checksum_iov failed with %d for test %d", ret, i); if (krbencs[i].cdata) { krb5_data checksum; checksum.length = krbencs[i].clen; checksum.data = krbencs[i].cdata; ret = krb_checksum_iov(context, crypto, krbencs[i].usage, &plain, &checksum); if (ret) errx(1, "krb_checksum_iov(2) failed with %d for test %d", ret, i); } krb5_crypto_destroy(context, crypto); ret = krb_enc_mit(context, krbencs[i].enctype, &kb, krbencs[i].usage, &cipher, &plain); if (ret) errx(1, "krb_enc_mit failed with %d for test %d", ret, i); } return 0; } static int iov_test(krb5_context context, krb5_enctype enctype) { krb5_error_code ret; krb5_crypto crypto; krb5_keyblock key; krb5_data signonly, in, in2; krb5_crypto_iov iov[6]; size_t len, i; unsigned char *base, *p; ret = krb5_generate_random_keyblock(context, enctype, &key); if (ret) krb5_err(context, 1, ret, "krb5_generate_random_keyblock"); ret = krb5_crypto_init(context, &key, 0, &crypto); if (ret) krb5_err(context, 1, ret, "krb5_crypto_init"); ret = krb5_crypto_length(context, crypto, KRB5_CRYPTO_TYPE_HEADER, &len); if (ret) krb5_err(context, 1, ret, "krb5_crypto_length"); signonly.data = "This should be signed"; signonly.length = strlen(signonly.data); in.data = "inputdata"; in.length = strlen(in.data); in2.data = "INPUTDATA"; in2.length = strlen(in2.data); memset(iov, 0, sizeof(iov)); iov[0].flags = KRB5_CRYPTO_TYPE_HEADER; iov[1].flags = KRB5_CRYPTO_TYPE_DATA; iov[1].data = in; iov[2].flags = KRB5_CRYPTO_TYPE_SIGN_ONLY; iov[2].data = signonly; iov[3].flags = KRB5_CRYPTO_TYPE_EMPTY; iov[4].flags = KRB5_CRYPTO_TYPE_PADDING; iov[5].flags = KRB5_CRYPTO_TYPE_TRAILER; ret = krb5_crypto_length_iov(context, crypto, iov, sizeof(iov)/sizeof(iov[0])); if (ret) krb5_err(context, 1, ret, "krb5_crypto_length_iov"); for (len = 0, i = 0; i < sizeof(iov)/sizeof(iov[0]); i++) { if (iov[i].flags == KRB5_CRYPTO_TYPE_SIGN_ONLY) continue; len += iov[i].data.length; } base = emalloc(len); /* * Allocate data for the fields */ for (p = base, i = 0; i < sizeof(iov)/sizeof(iov[0]); i++) { if (iov[i].flags == KRB5_CRYPTO_TYPE_SIGN_ONLY) continue;; iov[i].data.data = p; p += iov[i].data.length; } assert(iov[1].data.length == in.length); memcpy(iov[1].data.data, in.data, iov[1].data.length); /* * Encrypt */ ret = krb5_encrypt_iov_ivec(context, crypto, 7, iov, sizeof(iov)/sizeof(iov[0]), NULL); if (ret) krb5_err(context, 1, ret, "krb5_encrypt_iov_ivec"); /* * Decrypt */ ret = krb5_decrypt_iov_ivec(context, crypto, 7, iov, sizeof(iov)/sizeof(iov[0]), NULL); if (ret) krb5_err(context, 1, ret, "krb5_decrypt_iov_ivec"); /* * Verify data */ if (krb5_data_cmp(&iov[1].data, &in) != 0) krb5_errx(context, 1, "decrypted data not same"); /* * Free memory */ free(base); /* Set up for second try */ iov[3].flags = KRB5_CRYPTO_TYPE_DATA; iov[3].data = in; ret = krb5_crypto_length_iov(context, crypto, iov, sizeof(iov)/sizeof(iov[0])); if (ret) krb5_err(context, 1, ret, "krb5_crypto_length_iov"); for (len = 0, i = 0; i < sizeof(iov)/sizeof(iov[0]); i++) { if (iov[i].flags == KRB5_CRYPTO_TYPE_SIGN_ONLY) continue; len += iov[i].data.length; } base = emalloc(len); /* * Allocate data for the fields */ for (p = base, i = 0; i < sizeof(iov)/sizeof(iov[0]); i++) { if (iov[i].flags == KRB5_CRYPTO_TYPE_SIGN_ONLY) continue;; iov[i].data.data = p; p += iov[i].data.length; } assert(iov[1].data.length == in.length); memcpy(iov[1].data.data, in.data, iov[1].data.length); assert(iov[3].data.length == in2.length); memcpy(iov[3].data.data, in2.data, iov[3].data.length); /* * Encrypt */ ret = krb5_encrypt_iov_ivec(context, crypto, 7, iov, sizeof(iov)/sizeof(iov[0]), NULL); if (ret) krb5_err(context, 1, ret, "krb5_encrypt_iov_ivec"); /* * Decrypt */ ret = krb5_decrypt_iov_ivec(context, crypto, 7, iov, sizeof(iov)/sizeof(iov[0]), NULL); if (ret) krb5_err(context, 1, ret, "krb5_decrypt_iov_ivec"); /* * Verify data */ if (krb5_data_cmp(&iov[1].data, &in) != 0) krb5_errx(context, 1, "decrypted data 2.1 not same"); if (krb5_data_cmp(&iov[3].data, &in2) != 0) krb5_errx(context, 1, "decrypted data 2.2 not same"); /* * Free memory */ free(base); krb5_crypto_destroy(context, crypto); krb5_free_keyblock_contents(context, &key); return 0; } static int random_to_key(krb5_context context) { krb5_error_code ret; krb5_keyblock key; ret = krb5_random_to_key(context, ETYPE_DES3_CBC_SHA1, "\x21\x39\x04\x58\x6A\xBD\x7F" "\x21\x39\x04\x58\x6A\xBD\x7F" "\x21\x39\x04\x58\x6A\xBD\x7F", 21, &key); if (ret){ krb5_warn(context, ret, "random_to_key"); return 1; } if (key.keyvalue.length != 24) return 1; if (memcmp(key.keyvalue.data, "\x20\x38\x04\x58\x6b\xbc\x7f\xc7" "\x20\x38\x04\x58\x6b\xbc\x7f\xc7" "\x20\x38\x04\x58\x6b\xbc\x7f\xc7", 24) != 0) return 1; krb5_free_keyblock_contents(context, &key); return 0; } int main(int argc, char **argv) { krb5_error_code ret; krb5_context context; int val = 0; if (argc > 1 && strcmp(argv[1], "-v") == 0) verbose = 1; ret = krb5_init_context (&context); if (ret) errx (1, "krb5_init_context failed: %d", ret); val |= string_to_key_test(context); val |= krb_enc_test(context); val |= random_to_key(context); val |= iov_test(context, KRB5_ENCTYPE_AES256_CTS_HMAC_SHA1_96); val |= iov_test(context, KRB5_ENCTYPE_AES128_CTS_HMAC_SHA256_128); val |= iov_test(context, KRB5_ENCTYPE_AES256_CTS_HMAC_SHA384_192); if (verbose && val == 0) printf("all ok\n"); if (val) printf("tests failed\n"); krb5_free_context(context); return val; } heimdal-7.5.0/lib/krb5/pseudo-random-test.c0000644000175000017500000001003313026237312016555 0ustar niknik/* * Copyright (c) 2001 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of KTH nor the names of its contributors may be * used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY KTH AND ITS CONTRIBUTORS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL KTH OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "krb5_locl.h" #include enum { MAXSIZE = 48 }; static struct testcase { krb5_enctype enctype; unsigned char constant[MAXSIZE]; size_t constant_len; unsigned char key[MAXSIZE]; unsigned char res[MAXSIZE]; } tests[] = { {ETYPE_AES128_CTS_HMAC_SHA256_128, "test", 4, {0x37, 0x05, 0xD9, 0x60, 0x80, 0xC1, 0x77, 0x28, 0xA0, 0xE8, 0x00, 0xEA, 0xB6, 0xE0, 0xD2, 0x3C}, {0x9D, 0x18, 0x86, 0x16, 0xF6, 0x38, 0x52, 0xFE, 0x86, 0x91, 0x5B, 0xB8, 0x40, 0xB4, 0xA8, 0x86, 0xFF, 0x3E, 0x6B, 0xB0, 0xF8, 0x19, 0xB4, 0x9B, 0x89, 0x33, 0x93, 0xD3, 0x93, 0x85, 0x42, 0x95}}, {ETYPE_AES256_CTS_HMAC_SHA384_192, "test", 4, {0x6D, 0x40, 0x4D, 0x37, 0xFA, 0xF7, 0x9F, 0x9D, 0xF0, 0xD3, 0x35, 0x68, 0xD3, 0x20, 0x66, 0x98, 0x00, 0xEB, 0x48, 0x36, 0x47, 0x2E, 0xA8, 0xA0, 0x26, 0xD1, 0x6B, 0x71, 0x82, 0x46, 0x0C, 0x52}, {0x98, 0x01, 0xF6, 0x9A, 0x36, 0x8C, 0x2B, 0xF6, 0x75, 0xE5, 0x95, 0x21, 0xE1, 0x77, 0xD9, 0xA0, 0x7F, 0x67, 0xEF, 0xE1, 0xCF, 0xDE, 0x8D, 0x3C, 0x8D, 0x6F, 0x6A, 0x02, 0x56, 0xE3, 0xB1, 0x7D, 0xB3, 0xC1, 0xB6, 0x2A, 0xD1, 0xB8, 0x55, 0x33, 0x60, 0xD1, 0x73, 0x67, 0xEB, 0x15, 0x14, 0xD2}}, {0, {0}, 0, {0}, {0}} }; int main(int argc, char **argv) { struct testcase *t; krb5_context context; krb5_error_code ret; int val = 0; ret = krb5_init_context (&context); if (ret) errx (1, "krb5_init_context failed: %d", ret); for (t = tests; t->enctype != 0; ++t) { krb5_keyblock key; krb5_crypto crypto; krb5_data constant, prf; krb5_data_zero(&prf); key.keytype = t->enctype; krb5_enctype_keysize(context, t->enctype, &key.keyvalue.length); key.keyvalue.data = t->key; ret = krb5_crypto_init(context, &key, 0, &crypto); if (ret) krb5_err (context, 1, ret, "krb5_crypto_init"); constant.data = t->constant; constant.length = t->constant_len; ret = krb5_crypto_prf(context, crypto, &constant, &prf); if (ret) krb5_err (context, 1, ret, "krb5_crypto_prf"); if (memcmp(prf.data, t->res, prf.length) != 0) { const unsigned char *p = prf.data; int i; printf ("PRF failed (enctype %d)\n", t->enctype); printf ("should be: "); for (i = 0; i < prf.length; ++i) printf ("%02x", t->res[i]); printf ("\nresult was: "); for (i = 0; i < prf.length; ++i) printf ("%02x", p[i]); printf ("\n"); val = 1; } krb5_data_free(&prf); krb5_crypto_destroy(context, crypto); } krb5_free_context(context); return val; } heimdal-7.5.0/lib/krb5/krb5.moduli0000644000175000017500000000216312136107750014745 0ustar niknik# $Id$ # comment security-bits-decimal secure-prime(p)-hex generator(g)-hex (q)-hex rfc3526-MODP-group14 1760 FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E088A67CC74020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7EDEE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3DC2007CB8A163BF0598DA48361C55D39A69163FA8FD24CF5F83655D23DCA3AD961C62F356208552BB9ED529077096966D670C354E4ABC9804F1746C08CA18217C32905E462E36CE3BE39E772C180E86039B2783A2EC07A28FB5C55DF06F4C52C9DE2BCBF6955817183995497CEA956AE515D2261898FA051015728E5A8AACAA68FFFFFFFFFFFFFFFF 02 7FFFFFFFFFFFFFFFE487ED5110B4611A62633145C06E0E68948127044533E63A0105DF531D89CD9128A5043CC71A026EF7CA8CD9E69D218D98158536F92F8A1BA7F09AB6B6A8E122F242DABB312F3F637A262174D31BF6B585FFAE5B7A035BF6F71C35FDAD44CFD2D74F9208BE258FF324943328F6722D9EE1003E5C50B1DF82CC6D241B0E2AE9CD348B1FD47E9267AFC1B2AE91EE51D6CB0E3179AB1042A95DCF6A9483B84B4B36B3861AA7255E4C0278BA3604650C10BE19482F23171B671DF1CF3B960C074301CD93C1D17603D147DAE2AEF837A62964EF15E5FB4AAC0B8C1CCAA4BE754AB5728AE9130C4C7D02880AB9472D455655347FFFFFFFFFFFFFFF heimdal-7.5.0/lib/krb5/prog_setup.c0000644000175000017500000000454012136107750015223 0ustar niknik/* * Copyright (c) 1997 - 2001 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "krb5_locl.h" #include #include KRB5_LIB_FUNCTION void KRB5_LIB_CALL krb5_std_usage(int code, struct getargs *args, int num_args) { arg_printusage(args, num_args, NULL, ""); exit(code); } KRB5_LIB_FUNCTION int KRB5_LIB_CALL krb5_program_setup(krb5_context *context, int argc, char **argv, struct getargs *args, int num_args, void (KRB5_LIB_CALL *usage)(int, struct getargs*, int)) { krb5_error_code ret; int optidx = 0; if(usage == NULL) usage = krb5_std_usage; setprogname(argv[0]); ret = krb5_init_context(context); if (ret) errx (1, "krb5_init_context failed: %d", ret); if(getarg(args, num_args, argc, argv, &optidx)) (*usage)(1, args, num_args); return optidx; } heimdal-7.5.0/lib/krb5/krb5_mk_safe.30000644000175000017500000000543212136107750015305 0ustar niknik.\" Copyright (c) 2003 Kungliga Tekniska Högskolan .\" (Royal Institute of Technology, Stockholm, Sweden). .\" All rights reserved. .\" .\" Redistribution and use in source and binary forms, with or without .\" modification, are permitted provided that the following conditions .\" are met: .\" .\" 1. Redistributions of source code must retain the above copyright .\" notice, this list of conditions and the following disclaimer. .\" .\" 2. Redistributions in binary form must reproduce the above copyright .\" notice, this list of conditions and the following disclaimer in the .\" documentation and/or other materials provided with the distribution. .\" .\" 3. Neither the name of the Institute nor the names of its contributors .\" may be used to endorse or promote products derived from this software .\" without specific prior written permission. .\" .\" THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND .\" ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE .\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE .\" ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE .\" FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL .\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS .\" OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) .\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT .\" LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF .\" SUCH DAMAGE. .\" .\" $Id$ .\" .Dd May 1, 2006 .Dt KRB5_MK_SAFE 3 .Os HEIMDAL .Sh NAME .Nm krb5_mk_safe , .Nm krb5_mk_priv .Nd generates integrity protected and/or encrypted messages .Sh LIBRARY Kerberos 5 Library (libkrb5, -lkrb5) .Sh SYNOPSIS .In krb5.h .Pp .Ft krb5_error_code .Fn krb5_mk_priv "krb5_context context" "krb5_auth_context auth_context" "const krb5_data *userdata" "krb5_data *outbuf" "krb5_replay_data *outdata" .Ft krb5_error_code .Fn krb5_mk_safe "krb5_context context" "krb5_auth_context auth_context" "const krb5_data *userdata" "krb5_data *outbuf" "krb5_replay_data *outdata" .Sh DESCRIPTION .Fn krb5_mk_safe and .Fn krb5_mk_priv formats .Li KRB-SAFE (integrity protected) and .Li KRB-PRIV (also encrypted) messages into .Fa outbuf . The actual message data is taken from .Fa userdata . If the .Dv KRB5_AUTH_CONTEXT_DO_SEQUENCE or .Dv KRB5_AUTH_CONTEXT_DO_TIME flags are set in the .Fa auth_context , sequence numbers and time stamps are generated. If the .Dv KRB5_AUTH_CONTEXT_RET_SEQUENCE or .Dv KRB5_AUTH_CONTEXT_RET_TIME flags are set they are also returned in the .Fa outdata parameter. .Sh SEE ALSO .Xr krb5_auth_con_init 3 , .Xr krb5_rd_priv 3 , .Xr krb5_rd_safe 3 heimdal-7.5.0/lib/krb5/krb5_init_context.cat30000644000175000017500000003010613212450756017076 0ustar niknik KRB5_CONTEXT(3) BSD Library Functions Manual KRB5_CONTEXT(3) NNAAMMEE kkrrbb55__aadddd__eett__lliisstt, kkrrbb55__aadddd__eexxttrraa__aaddddrreesssseess, kkrrbb55__aadddd__iiggnnoorree__aaddddrreesssseess, kkrrbb55__ccoonntteexxtt, kkrrbb55__ffrreeee__ccoonnffiigg__ffiilleess, kkrrbb55__ffrreeee__ccoonntteexxtt, kkrrbb55__ggeett__ddeeffaauulltt__ccoonnffiigg__ffiilleess, kkrrbb55__ggeett__ddnnss__ccaannoonniizzee__hhoossttnnaammee, kkrrbb55__ggeett__eexxttrraa__aaddddrreesssseess, kkrrbb55__ggeett__ffccaacchhee__vveerrssiioonn, kkrrbb55__ggeett__iiggnnoorree__aaddddrreesssseess, kkrrbb55__ggeett__kkddcc__sseecc__ooffffsseett, kkrrbb55__ggeett__mmaaxx__ttiimmee__sskkeeww, kkrrbb55__ggeett__uussee__aaddmmiinn__kkddcc kkrrbb55__iinniitt__ccoonntteexxtt, kkrrbb55__iinniitt__eettss, kkrrbb55__pprreeppeenndd__ccoonnffiigg__ffiilleess, kkrrbb55__pprreeppeenndd__ccoonnffiigg__ffiilleess__ddeeffaauulltt, kkrrbb55__sseett__ccoonnffiigg__ffiilleess, kkrrbb55__sseett__ddnnss__ccaannoonniizzee__hhoossttnnaammee, kkrrbb55__sseett__eexxttrraa__aaddddrreesssseess, kkrrbb55__sseett__ffccaacchhee__vveerrssiioonn, kkrrbb55__sseett__iiggnnoorree__aaddddrreesssseess, kkrrbb55__sseett__mmaaxx__ttiimmee__sskkeeww, kkrrbb55__sseett__uussee__aaddmmiinn__kkddcc, -- create, modify and delete krb5_context structures LLIIBBRRAARRYY Kerberos 5 Library (libkrb5, -lkrb5) SSYYNNOOPPSSIISS ##iinncclluuddee <> struct krb5_context; _k_r_b_5___e_r_r_o_r___c_o_d_e kkrrbb55__iinniitt__ccoonntteexxtt(_k_r_b_5___c_o_n_t_e_x_t _*_c_o_n_t_e_x_t); _v_o_i_d kkrrbb55__ffrreeee__ccoonntteexxtt(_k_r_b_5___c_o_n_t_e_x_t _c_o_n_t_e_x_t); _v_o_i_d kkrrbb55__iinniitt__eettss(_k_r_b_5___c_o_n_t_e_x_t _c_o_n_t_e_x_t); _k_r_b_5___e_r_r_o_r___c_o_d_e kkrrbb55__aadddd__eett__lliisstt(_k_r_b_5___c_o_n_t_e_x_t _c_o_n_t_e_x_t, _v_o_i_d _(_*_f_u_n_c_)_(_s_t_r_u_c_t _e_t___l_i_s_t _*_*_)); _k_r_b_5___e_r_r_o_r___c_o_d_e kkrrbb55__aadddd__eexxttrraa__aaddddrreesssseess(_k_r_b_5___c_o_n_t_e_x_t _c_o_n_t_e_x_t, _k_r_b_5___a_d_d_r_e_s_s_e_s _*_a_d_d_r_e_s_s_e_s); _k_r_b_5___e_r_r_o_r___c_o_d_e kkrrbb55__sseett__eexxttrraa__aaddddrreesssseess(_k_r_b_5___c_o_n_t_e_x_t _c_o_n_t_e_x_t, _c_o_n_s_t _k_r_b_5___a_d_d_r_e_s_s_e_s _*_a_d_d_r_e_s_s_e_s); _k_r_b_5___e_r_r_o_r___c_o_d_e kkrrbb55__ggeett__eexxttrraa__aaddddrreesssseess(_k_r_b_5___c_o_n_t_e_x_t _c_o_n_t_e_x_t, _k_r_b_5___a_d_d_r_e_s_s_e_s _*_a_d_d_r_e_s_s_e_s); _k_r_b_5___e_r_r_o_r___c_o_d_e kkrrbb55__aadddd__iiggnnoorree__aaddddrreesssseess(_k_r_b_5___c_o_n_t_e_x_t _c_o_n_t_e_x_t, _k_r_b_5___a_d_d_r_e_s_s_e_s _*_a_d_d_r_e_s_s_e_s); _k_r_b_5___e_r_r_o_r___c_o_d_e kkrrbb55__sseett__iiggnnoorree__aaddddrreesssseess(_k_r_b_5___c_o_n_t_e_x_t _c_o_n_t_e_x_t, _c_o_n_s_t _k_r_b_5___a_d_d_r_e_s_s_e_s _*_a_d_d_r_e_s_s_e_s); _k_r_b_5___e_r_r_o_r___c_o_d_e kkrrbb55__ggeett__iiggnnoorree__aaddddrreesssseess(_k_r_b_5___c_o_n_t_e_x_t _c_o_n_t_e_x_t, _k_r_b_5___a_d_d_r_e_s_s_e_s _*_a_d_d_r_e_s_s_e_s); _k_r_b_5___e_r_r_o_r___c_o_d_e kkrrbb55__sseett__ffccaacchhee__vveerrssiioonn(_k_r_b_5___c_o_n_t_e_x_t _c_o_n_t_e_x_t, _i_n_t _v_e_r_s_i_o_n); _k_r_b_5___e_r_r_o_r___c_o_d_e kkrrbb55__ggeett__ffccaacchhee__vveerrssiioonn(_k_r_b_5___c_o_n_t_e_x_t _c_o_n_t_e_x_t, _i_n_t _*_v_e_r_s_i_o_n); _v_o_i_d kkrrbb55__sseett__ddnnss__ccaannoonniizzee__hhoossttnnaammee(_k_r_b_5___c_o_n_t_e_x_t _c_o_n_t_e_x_t, _k_r_b_5___b_o_o_l_e_a_n _f_l_a_g); _k_r_b_5___b_o_o_l_e_a_n kkrrbb55__ggeett__ddnnss__ccaannoonniizzee__hhoossttnnaammee(_k_r_b_5___c_o_n_t_e_x_t _c_o_n_t_e_x_t); _k_r_b_5___e_r_r_o_r___c_o_d_e kkrrbb55__ggeett__kkddcc__sseecc__ooffffsseett(_k_r_b_5___c_o_n_t_e_x_t _c_o_n_t_e_x_t, _i_n_t_3_2___t _*_s_e_c, _i_n_t_3_2___t _*_u_s_e_c); _k_r_b_5___e_r_r_o_r___c_o_d_e kkrrbb55__sseett__ccoonnffiigg__ffiilleess(_k_r_b_5___c_o_n_t_e_x_t _c_o_n_t_e_x_t, _c_h_a_r _*_*_f_i_l_e_n_a_m_e_s); _k_r_b_5___e_r_r_o_r___c_o_d_e kkrrbb55__pprreeppeenndd__ccoonnffiigg__ffiilleess(_c_o_n_s_t _c_h_a_r _*_f_i_l_e_l_i_s_t, _c_h_a_r _*_*_p_q, _c_h_a_r _*_*_*_r_e_t___p_p); _k_r_b_5___e_r_r_o_r___c_o_d_e kkrrbb55__pprreeppeenndd__ccoonnffiigg__ffiilleess__ddeeffaauulltt(_c_o_n_s_t _c_h_a_r _*_f_i_l_e_l_i_s_t, _c_h_a_r _*_*_*_p_f_i_l_e_n_a_m_e_s); _k_r_b_5___e_r_r_o_r___c_o_d_e kkrrbb55__ggeett__ddeeffaauulltt__ccoonnffiigg__ffiilleess(_c_h_a_r _*_*_*_p_f_i_l_e_n_a_m_e_s); _v_o_i_d kkrrbb55__ffrreeee__ccoonnffiigg__ffiilleess(_c_h_a_r _*_*_f_i_l_e_n_a_m_e_s); _v_o_i_d kkrrbb55__sseett__uussee__aaddmmiinn__kkddcc(_k_r_b_5___c_o_n_t_e_x_t _c_o_n_t_e_x_t, _k_r_b_5___b_o_o_l_e_a_n _f_l_a_g); _k_r_b_5___b_o_o_l_e_a_n kkrrbb55__ggeett__uussee__aaddmmiinn__kkddcc(_k_r_b_5___c_o_n_t_e_x_t _c_o_n_t_e_x_t); _t_i_m_e___t kkrrbb55__ggeett__mmaaxx__ttiimmee__sskkeeww(_k_r_b_5___c_o_n_t_e_x_t _c_o_n_t_e_x_t); _k_r_b_5___e_r_r_o_r___c_o_d_e kkrrbb55__sseett__mmaaxx__ttiimmee__sskkeeww(_k_r_b_5___c_o_n_t_e_x_t _c_o_n_t_e_x_t, _t_i_m_e___t _t_i_m_e); DDEESSCCRRIIPPTTIIOONN The kkrrbb55__iinniitt__ccoonntteexxtt() function initializes the _c_o_n_t_e_x_t structure and reads the configuration file _/_e_t_c_/_k_r_b_5_._c_o_n_f. The structure should be freed by calling kkrrbb55__ffrreeee__ccoonntteexxtt() when it is no longer being used. kkrrbb55__iinniitt__ccoonntteexxtt() returns 0 to indicate success. Otherwise an errno code is returned. Failure means either that something bad happened dur- ing initialization (typically [ENOMEM]) or that Kerberos should not be used [ENXIO]. kkrrbb55__iinniitt__eettss() adds all com_err(3) libs to _c_o_n_t_e_x_t. This is done by kkrrbb55__iinniitt__ccoonntteexxtt(). kkrrbb55__aadddd__eett__lliisstt() adds a com_err(3) error-code handler _f_u_n_c to the spec- ified _c_o_n_t_e_x_t. The error handler must generated by the the re-rentrant version of the compile_et(1) program. kkrrbb55__aadddd__eexxttrraa__aaddddrreesssseess() add a list of addresses that should be added when requesting tickets. kkrrbb55__aadddd__iiggnnoorree__aaddddrreesssseess() add a list of addresses that should be ignored when requesting tickets. kkrrbb55__ggeett__eexxttrraa__aaddddrreesssseess() get the list of addresses that should be added when requesting tickets. kkrrbb55__ggeett__iiggnnoorree__aaddddrreesssseess() get the list of addresses that should be ignored when requesting tickets. kkrrbb55__sseett__iiggnnoorree__aaddddrreesssseess() set the list of addresses that should be ignored when requesting tickets. kkrrbb55__sseett__eexxttrraa__aaddddrreesssseess() set the list of addresses that should be added when requesting tickets. kkrrbb55__sseett__ffccaacchhee__vveerrssiioonn() sets the version of file credentials caches that should be used. kkrrbb55__ggeett__ffccaacchhee__vveerrssiioonn() gets the version of file credentials caches that should be used. kkrrbb55__sseett__ddnnss__ccaannoonniizzee__hhoossttnnaammee() sets if the context is configured to canonicalize hostnames using DNS. kkrrbb55__ggeett__ddnnss__ccaannoonniizzee__hhoossttnnaammee() returns if the context is configured to canonicalize hostnames using DNS. kkrrbb55__ggeett__kkddcc__sseecc__ooffffsseett() returns the offset between the localtime and the KDC's time. _s_e_c and _u_s_e_c are both optional argument and NULL can be passed in. kkrrbb55__sseett__ccoonnffiigg__ffiilleess() set the list of configuration files to use and re-initialize the configuration from the files. kkrrbb55__pprreeppeenndd__ccoonnffiigg__ffiilleess() parse the _f_i_l_e_l_i_s_t and prepend the result to the already existing list _p_q The result is returned in _r_e_t___p_p and should be freed with kkrrbb55__ffrreeee__ccoonnffiigg__ffiilleess(). kkrrbb55__pprreeppeenndd__ccoonnffiigg__ffiilleess__ddeeffaauulltt() parse the _f_i_l_e_l_i_s_t and append that to the default list of configuration files. kkrrbb55__ggeett__ddeeffaauulltt__ccoonnffiigg__ffiilleess() get a list of default configuration files. kkrrbb55__ffrreeee__ccoonnffiigg__ffiilleess() free a list of configuration files returned by kkrrbb55__ggeett__ddeeffaauulltt__ccoonnffiigg__ffiilleess(), kkrrbb55__pprreeppeenndd__ccoonnffiigg__ffiilleess__ddeeffaauulltt(), or kkrrbb55__pprreeppeenndd__ccoonnffiigg__ffiilleess(). kkrrbb55__sseett__uussee__aaddmmiinn__kkddcc() sets if all KDC requests should go admin KDC. kkrrbb55__ggeett__uussee__aaddmmiinn__kkddcc() gets if all KDC requests should go admin KDC. kkrrbb55__ggeett__mmaaxx__ttiimmee__sskkeeww() and kkrrbb55__sseett__mmaaxx__ttiimmee__sskkeeww() get and sets the maximum allowed time skew between client and server. SSEEEE AALLSSOO errno(2), krb5(3), krb5_config(3), krb5_context(3), kerberos(8) HEIMDAL December 8, 2004 HEIMDAL heimdal-7.5.0/lib/krb5/test_get_addrs.c0000644000175000017500000000632312136107750016030 0ustar niknik/* * Copyright (c) 2000 - 2002 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of KTH nor the names of its contributors may be * used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY KTH AND ITS CONTRIBUTORS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL KTH OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "krb5_locl.h" #include #include /* print all addresses that we find */ static void print_addresses (krb5_context context, const krb5_addresses *addrs) { int i; char buf[256]; size_t len; for (i = 0; i < addrs->len; ++i) { krb5_print_address (&addrs->val[i], buf, sizeof(buf), &len); printf ("%s\n", buf); } } static int version_flag = 0; static int help_flag = 0; static struct getargs args[] = { {"version", 0, arg_flag, &version_flag, "print version", NULL }, {"help", 0, arg_flag, &help_flag, NULL, NULL } }; static void usage (int ret) { arg_printusage (args, sizeof(args)/sizeof(*args), NULL, ""); exit (ret); } int main(int argc, char **argv) { krb5_context context; krb5_error_code ret; krb5_addresses addrs; int optidx = 0; setprogname (argv[0]); if(getarg(args, sizeof(args) / sizeof(args[0]), argc, argv, &optidx)) usage(1); if (help_flag) usage (0); if(version_flag){ print_version(NULL); exit(0); } ret = krb5_init_context(&context); if (ret) errx (1, "krb5_init_context failed: %d", ret); ret = krb5_get_all_client_addrs (context, &addrs); if (ret) krb5_err (context, 1, ret, "krb5_get_all_client_addrs"); printf ("client addresses\n"); print_addresses (context, &addrs); krb5_free_addresses (context, &addrs); ret = krb5_get_all_server_addrs (context, &addrs); if (ret) krb5_err (context, 1, ret, "krb5_get_all_server_addrs"); printf ("server addresses\n"); print_addresses (context, &addrs); krb5_free_addresses (context, &addrs); return 0; } heimdal-7.5.0/lib/krb5/kuserok.c0000644000175000017500000005165113026237312014521 0ustar niknik/* * Copyright (c) 1997 - 2005 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "krb5_locl.h" #include "kuserok_plugin.h" #include #ifndef SYSTEM_K5LOGIN_DIR /* * System k5login location. File namess in this directory are expected * to be usernames and to contain a list of principals allowed to login * as the user named the same as the file. */ #define SYSTEM_K5LOGIN_DIR SYSCONFDIR "/k5login.d" #endif /* Plugin framework bits */ struct plctx { const char *rule; const char *k5login_dir; const char *luser; krb5_const_principal principal; unsigned int flags; krb5_boolean result; }; static krb5_error_code KRB5_LIB_CALL plcallback(krb5_context context, const void *plug, void *plugctx, void *userctx) { const krb5plugin_kuserok_ftable *locate = plug; struct plctx *plctx = userctx; return locate->kuserok(plugctx, context, plctx->rule, plctx->flags, plctx->k5login_dir, plctx->luser, plctx->principal, &plctx->result); } static krb5_error_code plugin_reg_ret; static krb5plugin_kuserok_ftable kuserok_simple_plug; static krb5plugin_kuserok_ftable kuserok_sys_k5login_plug; static krb5plugin_kuserok_ftable kuserok_user_k5login_plug; static krb5plugin_kuserok_ftable kuserok_deny_plug; static void reg_def_plugins_once(void *ctx) { krb5_error_code ret; krb5_context context = ctx; plugin_reg_ret = krb5_plugin_register(context, PLUGIN_TYPE_DATA, KRB5_PLUGIN_KUSEROK, &kuserok_simple_plug); ret = krb5_plugin_register(context, PLUGIN_TYPE_DATA, KRB5_PLUGIN_KUSEROK, &kuserok_sys_k5login_plug); if (!plugin_reg_ret) plugin_reg_ret = ret; ret = krb5_plugin_register(context, PLUGIN_TYPE_DATA, KRB5_PLUGIN_KUSEROK, &kuserok_user_k5login_plug); if (!plugin_reg_ret) plugin_reg_ret = ret; ret = krb5_plugin_register(context, PLUGIN_TYPE_DATA, KRB5_PLUGIN_KUSEROK, &kuserok_deny_plug); if (!plugin_reg_ret) plugin_reg_ret = ret; } /** * This function is designed to be portable for Win32 and POSIX. The * design does lead to multiple getpwnam_r() calls, but this is probably * not a big deal. * * Inputs: * * @param context A krb5_context * @param filename Name of item to introspection * @param is_system_location TRUE if the dir/file are system locations or * FALSE if they are user home directory locations * @param dir Directory (optional) * @param dirlstat A pointer to struct stat for the directory (optional) * @param file File (optional) * @param owner Name of user that is expected to own the file */ static krb5_error_code check_owner_dir(krb5_context context, const char *filename, krb5_boolean is_system_location, DIR *dir, struct stat *dirlstat, const char *owner) { #ifdef _WIN32 /* * XXX Implement this! * * The thing to do is to call _get_osfhandle() on fileno(file) and * dirfd(dir) to get HANDLEs to the same, then call * GetSecurityInfo() on those HANDLEs to get the security descriptor * (SD), then check the owner and DACL. Checking the DACL sounds * like a lot of work (what, derive a mode from the ACL the way * NFSv4 servers do?). Checking the owner means doing an LSARPC * lookup at least (to get the user's SID). */ if (is_system_location || owner == NULL) return 0; krb5_set_error_message(context, EACCES, "User k5login files not supported on Windows"); return EACCES; #else struct passwd pw, *pwd = NULL; char pwbuf[2048]; struct stat st; heim_assert(owner != NULL, "no directory owner ?"); if (rk_getpwnam_r(owner, &pw, pwbuf, sizeof(pwbuf), &pwd) != 0) { krb5_set_error_message(context, errno, "User unknown %s (getpwnam_r())", owner); return EACCES; } if (pwd == NULL) { krb5_set_error_message(context, EACCES, "no user %s", owner); return EACCES; } if (fstat(dirfd(dir), &st) == -1) { krb5_set_error_message(context, EACCES, "fstat(%s) of k5login.d failed", filename); return EACCES; } if (!S_ISDIR(st.st_mode)) { krb5_set_error_message(context, ENOTDIR, "%s not a directory", filename); return ENOTDIR; } if (st.st_dev != dirlstat->st_dev || st.st_ino != dirlstat->st_ino) { krb5_set_error_message(context, EACCES, "%s was renamed during kuserok " "operation", filename); return EACCES; } if ((st.st_mode & (S_IWGRP | S_IWOTH)) != 0) { krb5_set_error_message(context, EACCES, "%s has world and/or group write " "permissions", filename); return EACCES; } if (pwd->pw_uid != st.st_uid && st.st_uid != 0) { krb5_set_error_message(context, EACCES, "%s not owned by the user (%s) or root", filename, owner); return EACCES; } return 0; #endif } static krb5_error_code check_owner_file(krb5_context context, const char *filename, FILE *file, const char *owner) { #ifdef _WIN32 /* * XXX Implement this! * * The thing to do is to call _get_osfhandle() on fileno(file) and * dirfd(dir) to get HANDLEs to the same, then call * GetSecurityInfo() on those HANDLEs to get the security descriptor * (SD), then check the owner and DACL. Checking the DACL sounds * like a lot of work (what, derive a mode from the ACL the way * NFSv4 servers do?). Checking the owner means doing an LSARPC * lookup at least (to get the user's SID). */ if (owner == NULL) return 0; krb5_set_error_message(context, EACCES, "User k5login files not supported on Windows"); return EACCES; #else struct passwd pw, *pwd = NULL; char pwbuf[2048]; struct stat st; if (owner == NULL) return 0; if (rk_getpwnam_r(owner, &pw, pwbuf, sizeof(pwbuf), &pwd) != 0) { krb5_set_error_message(context, errno, "User unknown %s (getpwnam_r())", owner); return EACCES; } if (pwd == NULL) { krb5_set_error_message(context, EACCES, "no user %s", owner); return EACCES; } if (fstat(fileno(file), &st) == -1) { krb5_set_error_message(context, EACCES, "fstat(%s) of k5login failed", filename); return EACCES; } if (S_ISDIR(st.st_mode)) { krb5_set_error_message(context, EISDIR, "k5login: %s is a directory", filename); return EISDIR; } if ((st.st_mode & (S_IWGRP | S_IWOTH)) != 0) { krb5_set_error_message(context, EISDIR, "k5login %s has world and/or group write " "permissions", filename); return EACCES; } if (pwd->pw_uid != st.st_uid && st.st_uid != 0) { krb5_set_error_message(context, EACCES, "k5login %s not owned by the user or root", filename); return EACCES; } return 0; #endif } /* see if principal is mentioned in the filename access file, return TRUE (in result) if so, FALSE otherwise */ static krb5_error_code check_one_file(krb5_context context, const char *filename, const char *owner, krb5_boolean is_system_location, krb5_const_principal principal, krb5_boolean *result) { FILE *f; char buf[BUFSIZ]; krb5_error_code ret; *result = FALSE; f = fopen(filename, "r"); if (f == NULL) return errno; rk_cloexec_file(f); ret = check_owner_file(context, filename, f, owner); if (ret) goto out; while (fgets(buf, sizeof(buf), f) != NULL) { krb5_principal tmp; char *newline = buf + strcspn(buf, "\n"); if (*newline != '\n') { int c; c = fgetc(f); if (c != EOF) { while (c != EOF && c != '\n') c = fgetc(f); /* line was too long, so ignore it */ continue; } } *newline = '\0'; ret = krb5_parse_name(context, buf, &tmp); if (ret) continue; *result = krb5_principal_compare(context, principal, tmp); krb5_free_principal(context, tmp); if (*result) { fclose (f); return 0; } } out: fclose(f); return 0; } static krb5_error_code check_directory(krb5_context context, const char *dirname, const char *owner, krb5_boolean is_system_location, krb5_const_principal principal, krb5_boolean *result) { DIR *d; struct dirent *dent; char filename[MAXPATHLEN]; size_t len; krb5_error_code ret = 0; struct stat st; *result = FALSE; if (lstat(dirname, &st) < 0) return errno; if (!S_ISDIR(st.st_mode)) { krb5_set_error_message(context, ENOTDIR, "k5login.d not a directory"); return ENOTDIR; } if ((d = opendir(dirname)) == NULL) { krb5_set_error_message(context, ENOTDIR, "Could not open k5login.d"); return errno; } ret = check_owner_dir(context, dirname, is_system_location, d, &st, owner); if (ret) goto out; while ((dent = readdir(d)) != NULL) { /* * XXX: Should we also skip files whose names start with "."? * Vim ".filename.swp" files are also good candidates to skip. * Once we ignore "#*" and "*~", it is not clear what other * heuristics to apply. */ if (strcmp(dent->d_name, ".") == 0 || strcmp(dent->d_name, "..") == 0 || dent->d_name[0] == '#' || /* emacs autosave */ dent->d_name[strlen(dent->d_name) - 1] == '~') /* emacs backup */ continue; len = snprintf(filename, sizeof(filename), "%s/%s", dirname, dent->d_name); /* Skip too-long filenames that got truncated by snprintf() */ if (len < sizeof(filename)) { ret = check_one_file(context, filename, owner, is_system_location, principal, result); if (ret == 0 && *result == TRUE) break; } ret = 0; /* don't propagate errors upstream */ } out: closedir(d); return ret; } static krb5_error_code check_an2ln(krb5_context context, krb5_const_principal principal, const char *luser, krb5_boolean *result) { krb5_error_code ret; char *lname; #if 0 /* XXX Should we make this an option? */ /* multi-component principals can never match */ if (krb5_principal_get_comp_string(context, principal, 1) != NULL) { *result = FALSE; return 0; } #endif lname = malloc(strlen(luser) + 1); if (lname == NULL) return krb5_enomem(context); ret = krb5_aname_to_localname(context, principal, strlen(luser)+1, lname); if (ret) goto out; if (strcmp(lname, luser) == 0) *result = TRUE; else *result = FALSE; out: free(lname); return 0; } /** * This function takes the name of a local user and checks if * principal is allowed to log in as that user. * * The user may have a ~/.k5login file listing principals that are * allowed to login as that user. If that file does not exist, all * principals with a only one component that is identical to the * username, and a realm considered local, are allowed access. * * The .k5login file must contain one principal per line, be owned by * user and not be writable by group or other (but must be readable by * anyone). * * Note that if the file exists, no implicit access rights are given * to user@@LOCALREALM. * * Optionally, a set of files may be put in ~/.k5login.d (a * directory), in which case they will all be checked in the same * manner as .k5login. The files may be called anything, but files * starting with a hash (#) , or ending with a tilde (~) are * ignored. Subdirectories are not traversed. Note that this directory * may not be checked by other Kerberos implementations. * * If no configuration file exists, match user against local domains, * ie luser@@LOCAL-REALMS-IN-CONFIGURATION-FILES. * * @param context Kerberos 5 context. * @param principal principal to check if allowed to login * @param luser local user id * * @return returns TRUE if access should be granted, FALSE otherwise. * * @ingroup krb5_support */ KRB5_LIB_FUNCTION krb5_boolean KRB5_LIB_CALL krb5_kuserok(krb5_context context, krb5_principal principal, const char *luser) { return _krb5_kuserok(context, principal, luser, TRUE); } KRB5_LIB_FUNCTION krb5_boolean KRB5_LIB_CALL _krb5_kuserok(krb5_context context, krb5_principal principal, const char *luser, krb5_boolean an2ln_ok) { static heim_base_once_t reg_def_plugins = HEIM_BASE_ONCE_INIT; krb5_error_code ret; struct plctx ctx; char **rules; /* * XXX we should have a struct with a krb5_context field and a * krb5_error_code fied and pass the address of that as the ctx * argument of heim_base_once_f(). For now we use a static to * communicate failures. Actually, we ignore failures anyways, * since we can't return them. */ heim_base_once_f(®_def_plugins, context, reg_def_plugins_once); ctx.flags = 0; ctx.luser = luser; ctx.principal = principal; ctx.result = FALSE; ctx.k5login_dir = krb5_config_get_string(context, NULL, "libdefaults", "k5login_directory", NULL); if (an2ln_ok) ctx.flags |= KUSEROK_ANAME_TO_LNAME_OK; if (krb5_config_get_bool_default(context, NULL, FALSE, "libdefaults", "k5login_authoritative", NULL)) ctx.flags |= KUSEROK_K5LOGIN_IS_AUTHORITATIVE; if ((ctx.flags & KUSEROK_K5LOGIN_IS_AUTHORITATIVE) && plugin_reg_ret) return plugin_reg_ret; /* fail safe */ rules = krb5_config_get_strings(context, NULL, "libdefaults", "kuserok", NULL); if (rules == NULL) { /* Default: check ~/.k5login */ ctx.rule = "USER-K5LOGIN"; ret = plcallback(context, &kuserok_user_k5login_plug, NULL, &ctx); if (ret == 0) goto out; ctx.rule = "SIMPLE"; ret = plcallback(context, &kuserok_simple_plug, NULL, &ctx); if (ret == 0) goto out; ctx.result = FALSE; } else { size_t n; for (n = 0; rules[n]; n++) { ctx.rule = rules[n]; ret = _krb5_plugin_run_f(context, "krb5", KRB5_PLUGIN_KUSEROK, KRB5_PLUGIN_KUSEROK_VERSION_0, 0, &ctx, plcallback); if (ret != KRB5_PLUGIN_NO_HANDLE) goto out; } } out: krb5_config_free_strings(rules); return ctx.result; } /* * Simple kuserok: check that the lname for the aname matches luser. */ static krb5_error_code KRB5_LIB_CALL kuserok_simple_plug_f(void *plug_ctx, krb5_context context, const char *rule, unsigned int flags, const char *k5login_dir, const char *luser, krb5_const_principal principal, krb5_boolean *result) { krb5_error_code ret; if (strcmp(rule, "SIMPLE") != 0 || (flags & KUSEROK_ANAME_TO_LNAME_OK) == 0) return KRB5_PLUGIN_NO_HANDLE; ret = check_an2ln(context, principal, luser, result); if (ret == 0 && *result == FALSE) return KRB5_PLUGIN_NO_HANDLE; return 0; } /* * Check k5login files in a system location, rather than in home * directories. */ static krb5_error_code KRB5_LIB_CALL kuserok_sys_k5login_plug_f(void *plug_ctx, krb5_context context, const char *rule, unsigned int flags, const char *k5login_dir, const char *luser, krb5_const_principal principal, krb5_boolean *result) { char filename[MAXPATHLEN]; size_t len; const char *profile_dir = NULL; krb5_error_code ret; *result = FALSE; if (strcmp(rule, "SYSTEM-K5LOGIN") != 0 && strncmp(rule, "SYSTEM-K5LOGIN:", strlen("SYSTEM-K5LOGIN:")) != 0) return KRB5_PLUGIN_NO_HANDLE; profile_dir = strchr(rule, ':'); if (profile_dir == NULL) profile_dir = k5login_dir ? k5login_dir : SYSTEM_K5LOGIN_DIR; else profile_dir++; len = snprintf(filename, sizeof(filename), "%s/%s", profile_dir, luser); if (len < sizeof(filename)) { ret = check_one_file(context, filename, NULL, TRUE, principal, result); if (ret == 0 && ((flags & KUSEROK_K5LOGIN_IS_AUTHORITATIVE) || *result == TRUE)) return 0; } *result = FALSE; return KRB5_PLUGIN_NO_HANDLE; } /* * Check ~luser/.k5login and/or ~/luser/.k5login.d */ static krb5_error_code KRB5_LIB_CALL kuserok_user_k5login_plug_f(void *plug_ctx, krb5_context context, const char *rule, unsigned int flags, const char *k5login_dir, const char *luser, krb5_const_principal principal, krb5_boolean *result) { #ifdef _WIN32 return KRB5_PLUGIN_NO_HANDLE; #else char *path; char *path_exp; const char *profile_dir = NULL; krb5_error_code ret; krb5_boolean found_file = FALSE; struct passwd pw, *pwd = NULL; char pwbuf[2048]; if (strcmp(rule, "USER-K5LOGIN") != 0) return KRB5_PLUGIN_NO_HANDLE; profile_dir = k5login_dir; if (profile_dir == NULL) { /* Don't deadlock with gssd or anything of the sort */ if (!_krb5_homedir_access(context)) return KRB5_PLUGIN_NO_HANDLE; if (getpwnam_r(luser, &pw, pwbuf, sizeof(pwbuf), &pwd) != 0) { krb5_set_error_message(context, errno, "User unknown (getpwnam_r())"); return KRB5_PLUGIN_NO_HANDLE; } if (pwd == NULL) { krb5_set_error_message(context, errno, "User unknown (getpwnam())"); return KRB5_PLUGIN_NO_HANDLE; } profile_dir = pwd->pw_dir; } #define KLOGIN "/.k5login" if (asprintf(&path, "%s/.k5login.d", profile_dir) == -1) return krb5_enomem(context); ret = _krb5_expand_path_tokensv(context, path, 1, &path_exp, "luser", luser, NULL); free(path); if (ret) return ret; path = path_exp; /* check user's ~/.k5login */ path[strlen(path) - strlen(".d")] = '\0'; ret = check_one_file(context, path, luser, FALSE, principal, result); /* * A match in ~/.k5login is sufficient. A non-match, falls through to the * .k5login.d code below. */ if (ret == 0 && *result == TRUE) { free(path); return 0; } if (ret != ENOENT) found_file = TRUE; /* * A match in ~/.k5login.d/somefile is sufficient. A non-match, falls * through to the code below that handles negative results. * * XXX: put back the .d; clever|hackish? you decide */ path[strlen(path)] = '.'; ret = check_directory(context, path, luser, FALSE, principal, result); free(path); if (ret == 0 && *result == TRUE) return 0; if (ret != ENOENT && ret != ENOTDIR) found_file = TRUE; /* * When either ~/.k5login or ~/.k5login.d/ exists, but neither matches * and we're authoritative, we're done. Otherwise, give other plugins * a chance. */ *result = FALSE; if (found_file && (flags & KUSEROK_K5LOGIN_IS_AUTHORITATIVE)) return 0; return KRB5_PLUGIN_NO_HANDLE; #endif } static krb5_error_code KRB5_LIB_CALL kuserok_deny_plug_f(void *plug_ctx, krb5_context context, const char *rule, unsigned int flags, const char *k5login_dir, const char *luser, krb5_const_principal principal, krb5_boolean *result) { if (strcmp(rule, "DENY") != 0) return KRB5_PLUGIN_NO_HANDLE; *result = FALSE; return 0; } static krb5_error_code KRB5_LIB_CALL kuser_ok_null_plugin_init(krb5_context context, void **ctx) { *ctx = NULL; return 0; } static void KRB5_LIB_CALL kuser_ok_null_plugin_fini(void *ctx) { return; } static krb5plugin_kuserok_ftable kuserok_simple_plug = { KRB5_PLUGIN_KUSEROK_VERSION_0, kuser_ok_null_plugin_init, kuser_ok_null_plugin_fini, kuserok_simple_plug_f, }; static krb5plugin_kuserok_ftable kuserok_sys_k5login_plug = { KRB5_PLUGIN_KUSEROK_VERSION_0, kuser_ok_null_plugin_init, kuser_ok_null_plugin_fini, kuserok_sys_k5login_plug_f, }; static krb5plugin_kuserok_ftable kuserok_user_k5login_plug = { KRB5_PLUGIN_KUSEROK_VERSION_0, kuser_ok_null_plugin_init, kuser_ok_null_plugin_fini, kuserok_user_k5login_plug_f, }; static krb5plugin_kuserok_ftable kuserok_deny_plug = { KRB5_PLUGIN_KUSEROK_VERSION_0, kuser_ok_null_plugin_init, kuser_ok_null_plugin_fini, kuserok_deny_plug_f, }; heimdal-7.5.0/lib/krb5/mk_req.c0000644000175000017500000000712212136107750014311 0ustar niknik/* * Copyright (c) 1997 - 2004 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "krb5_locl.h" KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_mk_req_exact(krb5_context context, krb5_auth_context *auth_context, const krb5_flags ap_req_options, const krb5_principal server, krb5_data *in_data, krb5_ccache ccache, krb5_data *outbuf) { krb5_error_code ret; krb5_creds this_cred, *cred; memset(&this_cred, 0, sizeof(this_cred)); ret = krb5_cc_get_principal(context, ccache, &this_cred.client); if(ret) return ret; ret = krb5_copy_principal (context, server, &this_cred.server); if (ret) { krb5_free_cred_contents (context, &this_cred); return ret; } this_cred.times.endtime = 0; if (auth_context && *auth_context && (*auth_context)->keytype) this_cred.session.keytype = (*auth_context)->keytype; ret = krb5_get_credentials (context, 0, ccache, &this_cred, &cred); krb5_free_cred_contents(context, &this_cred); if (ret) return ret; ret = krb5_mk_req_extended (context, auth_context, ap_req_options, in_data, cred, outbuf); krb5_free_creds(context, cred); return ret; } KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_mk_req(krb5_context context, krb5_auth_context *auth_context, const krb5_flags ap_req_options, const char *service, const char *hostname, krb5_data *in_data, krb5_ccache ccache, krb5_data *outbuf) { krb5_error_code ret; char **realms; char *real_hostname; krb5_principal server; ret = krb5_expand_hostname_realms (context, hostname, &real_hostname, &realms); if (ret) return ret; ret = krb5_build_principal (context, &server, strlen(*realms), *realms, service, real_hostname, NULL); free (real_hostname); krb5_free_host_realm (context, realms); if (ret) return ret; ret = krb5_mk_req_exact (context, auth_context, ap_req_options, server, in_data, ccache, outbuf); krb5_free_principal (context, server); return ret; } heimdal-7.5.0/lib/krb5/sendauth.c0000644000175000017500000001653513026237312014653 0ustar niknik/* * Copyright (c) 1997 - 2006 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "krb5_locl.h" /* * The format seems to be: * client -> server * * 4 bytes - length * KRB5_SENDAUTH_V1.0 (including zero) * 4 bytes - length * protocol string (with terminating zero) * * server -> client * 1 byte - (0 = OK, else some kind of error) * * client -> server * 4 bytes - length * AP-REQ * * server -> client * 4 bytes - length (0 = OK, else length of error) * (error) * * if(mutual) { * server -> client * 4 bytes - length * AP-REP * } */ /** * Perform the client side of the sendauth protocol. * * @param context Kerberos 5 context. * @param auth_context Authentication context of the peer. * @param p_fd Socket associated to the connection. * @param appl_version Server-specific string. * @param client Client principal. If NULL, use the credentials in \a ccache. * @param server Server principal. * @param ap_req_options Options for the AP_REQ message. See the AP_OPTS_* defines in krb5.h. * @param in_data FIXME * @param in_creds FIXME * @param ccache Credentials cache. If NULL, use the default credentials cache. * @param ret_error If not NULL, will be set to the error reported by server, if any. * Must be deallocated with krb5_free_error_contents(). * @param rep_result If not NULL, will be set to the EncApRepPart of the AP_REP message. * Must be deallocated with krb5_free_ap_rep_enc_part(). * @param out_creds FIXME If not NULL, will be set to FIXME. Must be deallocated with * krb5_free_creds(). * * @return 0 to indicate success. Otherwise a Kerberos error code is * returned, see krb5_get_error_message(). */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_sendauth(krb5_context context, krb5_auth_context *auth_context, krb5_pointer p_fd, const char *appl_version, krb5_principal client, krb5_principal server, krb5_flags ap_req_options, krb5_data *in_data, krb5_creds *in_creds, krb5_ccache ccache, krb5_error **ret_error, krb5_ap_rep_enc_part **rep_result, krb5_creds **out_creds) { krb5_error_code ret; uint32_t len, net_len; const char *version = KRB5_SENDAUTH_VERSION; u_char repl; krb5_data ap_req, error_data; krb5_creds this_cred; krb5_principal this_client = NULL; krb5_creds *creds; ssize_t sret; krb5_boolean my_ccache = FALSE; len = strlen(version) + 1; net_len = htonl(len); if (krb5_net_write (context, p_fd, &net_len, 4) != 4 || krb5_net_write (context, p_fd, version, len) != len) { ret = errno; krb5_set_error_message (context, ret, "write: %s", strerror(ret)); return ret; } len = strlen(appl_version) + 1; net_len = htonl(len); if (krb5_net_write (context, p_fd, &net_len, 4) != 4 || krb5_net_write (context, p_fd, appl_version, len) != len) { ret = errno; krb5_set_error_message (context, ret, "write: %s", strerror(ret)); return ret; } sret = krb5_net_read (context, p_fd, &repl, sizeof(repl)); if (sret < 0) { ret = errno; krb5_set_error_message (context, ret, "read: %s", strerror(ret)); return ret; } else if (sret != sizeof(repl)) { krb5_clear_error_message (context); return KRB5_SENDAUTH_BADRESPONSE; } if (repl != 0) { krb5_clear_error_message (context); return KRB5_SENDAUTH_REJECTED; } if (in_creds == NULL) { if (ccache == NULL) { ret = krb5_cc_default (context, &ccache); if (ret) return ret; my_ccache = TRUE; } if (client == NULL) { ret = krb5_cc_get_principal (context, ccache, &this_client); if (ret) { if(my_ccache) krb5_cc_close(context, ccache); return ret; } client = this_client; } memset(&this_cred, 0, sizeof(this_cred)); this_cred.client = client; this_cred.server = server; this_cred.times.endtime = 0; this_cred.ticket.length = 0; in_creds = &this_cred; } if (in_creds->ticket.length == 0) { ret = krb5_get_credentials (context, 0, ccache, in_creds, &creds); if (ret) { if(my_ccache) krb5_cc_close(context, ccache); return ret; } } else { creds = in_creds; } if(my_ccache) krb5_cc_close(context, ccache); ret = krb5_mk_req_extended (context, auth_context, ap_req_options, in_data, creds, &ap_req); if (out_creds) *out_creds = creds; else krb5_free_creds(context, creds); if(this_client) krb5_free_principal(context, this_client); if (ret) return ret; ret = krb5_write_message (context, p_fd, &ap_req); if (ret) return ret; krb5_data_free (&ap_req); ret = krb5_read_message (context, p_fd, &error_data); if (ret) return ret; if (error_data.length != 0) { KRB_ERROR error; ret = krb5_rd_error (context, &error_data, &error); krb5_data_free (&error_data); if (ret == 0) { ret = krb5_error_from_rd_error(context, &error, NULL); if (ret_error != NULL) { *ret_error = malloc (sizeof(krb5_error)); if (*ret_error == NULL) { krb5_free_error_contents (context, &error); } else { **ret_error = error; } } else { krb5_free_error_contents (context, &error); } return ret; } else { krb5_clear_error_message(context); return ret; } } else krb5_data_free (&error_data); if (ap_req_options & AP_OPTS_MUTUAL_REQUIRED) { krb5_data ap_rep; krb5_ap_rep_enc_part *ignore = NULL; krb5_data_zero (&ap_rep); ret = krb5_read_message (context, p_fd, &ap_rep); if (ret) return ret; ret = krb5_rd_rep (context, *auth_context, &ap_rep, rep_result ? rep_result : &ignore); krb5_data_free (&ap_rep); if (ret) return ret; if (rep_result == NULL) krb5_free_ap_rep_enc_part (context, ignore); } return 0; } heimdal-7.5.0/lib/krb5/krb5_c_make_checksum.cat30000644000175000017500000002377113212450756017502 0ustar niknik KRB5_C_MAKE_CHECKSUM(3) BSD Library Functions Manual KRB5_C_MAKE_CHECKSUM(3) NNAAMMEE kkrrbb55__cc__bblloocckk__ssiizzee, kkrrbb55__cc__ddeeccrryypptt, kkrrbb55__cc__eennccrryypptt, kkrrbb55__cc__eennccrryypptt__lleennggtthh, kkrrbb55__cc__eennccttyyppee__ccoommppaarree, kkrrbb55__cc__ggeett__cchheecckkssuumm, kkrrbb55__cc__iiss__ccoollll__pprrooooff__cckkssuumm, kkrrbb55__cc__iiss__kkeeyyeedd__cckkssuumm, kkrrbb55__cc__kkeeyylleennggtthh, kkrrbb55__cc__mmaakkee__cchheecckkssuumm, kkrrbb55__cc__mmaakkee__rraannddoomm__kkeeyy, kkrrbb55__cc__sseett__cchheecckkssuumm, kkrrbb55__cc__vvaalliidd__cckkssuummttyyppee, kkrrbb55__cc__vvaalliidd__eennccttyyppee, kkrrbb55__cc__vveerriiffyy__cchheecckkssuumm, kkrrbb55__cc__cchheecckkssuumm__lleennggtthh -- Kerberos 5 crypto API LLIIBBRRAARRYY Kerberos 5 Library (libkrb5, -lkrb5) SSYYNNOOPPSSIISS ##iinncclluuddee <> _k_r_b_5___e_r_r_o_r___c_o_d_e kkrrbb55__cc__bblloocckk__ssiizzee(_k_r_b_5___c_o_n_t_e_x_t _c_o_n_t_e_x_t, _k_r_b_5___e_n_c_t_y_p_e _e_n_c_t_y_p_e, _s_i_z_e___t _*_b_l_o_c_k_s_i_z_e); _k_r_b_5___e_r_r_o_r___c_o_d_e kkrrbb55__cc__ddeeccrryypptt(_k_r_b_5___c_o_n_t_e_x_t _c_o_n_t_e_x_t, _c_o_n_s_t _k_r_b_5___k_e_y_b_l_o_c_k _k_e_y, _k_r_b_5___k_e_y_u_s_a_g_e _u_s_a_g_e, _c_o_n_s_t _k_r_b_5___d_a_t_a _*_i_v_e_c, _k_r_b_5___e_n_c___d_a_t_a _*_i_n_p_u_t, _k_r_b_5___d_a_t_a _*_o_u_t_p_u_t); _k_r_b_5___e_r_r_o_r___c_o_d_e kkrrbb55__cc__eennccrryypptt(_k_r_b_5___c_o_n_t_e_x_t _c_o_n_t_e_x_t, _c_o_n_s_t _k_r_b_5___k_e_y_b_l_o_c_k _*_k_e_y, _k_r_b_5___k_e_y_u_s_a_g_e _u_s_a_g_e, _c_o_n_s_t _k_r_b_5___d_a_t_a _*_i_v_e_c, _c_o_n_s_t _k_r_b_5___d_a_t_a _*_i_n_p_u_t, _k_r_b_5___e_n_c___d_a_t_a _*_o_u_t_p_u_t); _k_r_b_5___e_r_r_o_r___c_o_d_e kkrrbb55__cc__eennccrryypptt__lleennggtthh(_k_r_b_5___c_o_n_t_e_x_t _c_o_n_t_e_x_t, _k_r_b_5___e_n_c_t_y_p_e _e_n_c_t_y_p_e, _s_i_z_e___t _i_n_p_u_t_l_e_n, _s_i_z_e___t _*_l_e_n_g_t_h); _k_r_b_5___e_r_r_o_r___c_o_d_e kkrrbb55__cc__eennccttyyppee__ccoommppaarree(_k_r_b_5___c_o_n_t_e_x_t _c_o_n_t_e_x_t, _k_r_b_5___e_n_c_t_y_p_e _e_1, _k_r_b_5___e_n_c_t_y_p_e _e_2, _k_r_b_5___b_o_o_l_e_a_n _*_s_i_m_i_l_a_r); _k_r_b_5___e_r_r_o_r___c_o_d_e kkrrbb55__cc__mmaakkee__rraannddoomm__kkeeyy(_k_r_b_5___c_o_n_t_e_x_t _c_o_n_t_e_x_t, _k_r_b_5___e_n_c_t_y_p_e _e_n_c_t_y_p_e, _k_r_b_5___k_e_y_b_l_o_c_k _*_r_a_n_d_o_m___k_e_y); _k_r_b_5___e_r_r_o_r___c_o_d_e kkrrbb55__cc__mmaakkee__cchheecckkssuumm(_k_r_b_5___c_o_n_t_e_x_t _c_o_n_t_e_x_t, _k_r_b_5___c_k_s_u_m_t_y_p_e _c_k_s_u_m_t_y_p_e, _c_o_n_s_t _k_r_b_5___k_e_y_b_l_o_c_k _*_k_e_y, _k_r_b_5___k_e_y_u_s_a_g_e _u_s_a_g_e, _c_o_n_s_t _k_r_b_5___d_a_t_a _*_i_n_p_u_t, _k_r_b_5___c_h_e_c_k_s_u_m _*_c_k_s_u_m); _k_r_b_5___e_r_r_o_r___c_o_d_e kkrrbb55__cc__vveerriiffyy__cchheecckkssuumm(_k_r_b_5___c_o_n_t_e_x_t _c_o_n_t_e_x_t, _c_o_n_s_t _k_r_b_5___k_e_y_b_l_o_c_k _*_k_e_y, _k_r_b_5___k_e_y_u_s_a_g_e _u_s_a_g_e, _c_o_n_s_t _k_r_b_5___d_a_t_a _*_d_a_t_a, _c_o_n_s_t _k_r_b_5___c_h_e_c_k_s_u_m _*_c_k_s_u_m, _k_r_b_5___b_o_o_l_e_a_n _*_v_a_l_i_d); _k_r_b_5___e_r_r_o_r___c_o_d_e kkrrbb55__cc__cchheecckkssuumm__lleennggtthh(_k_r_b_5___c_o_n_t_e_x_t _c_o_n_t_e_x_t, _k_r_b_5___c_k_s_u_m_t_y_p_e _c_k_s_u_m_t_y_p_e, _s_i_z_e___t _*_l_e_n_g_t_h); _k_r_b_5___e_r_r_o_r___c_o_d_e kkrrbb55__cc__ggeett__cchheecckkssuumm(_k_r_b_5___c_o_n_t_e_x_t _c_o_n_t_e_x_t, _c_o_n_s_t _k_r_b_5___c_h_e_c_k_s_u_m _*_c_k_s_u_m, _k_r_b_5___c_k_s_u_m_t_y_p_e _*_t_y_p_e, _k_r_b_5___d_a_t_a _*_*_d_a_t_a); _k_r_b_5___e_r_r_o_r___c_o_d_e kkrrbb55__cc__sseett__cchheecckkssuumm(_k_r_b_5___c_o_n_t_e_x_t _c_o_n_t_e_x_t, _k_r_b_5___c_h_e_c_k_s_u_m _*_c_k_s_u_m, _k_r_b_5___c_k_s_u_m_t_y_p_e _t_y_p_e, _c_o_n_s_t _k_r_b_5___d_a_t_a _*_d_a_t_a); _k_r_b_5___b_o_o_l_e_a_n kkrrbb55__cc__vvaalliidd__eennccttyyppee(_k_r_b_5___e_n_c_t_y_p_e, _e_t_y_p_e_"); _k_r_b_5___b_o_o_l_e_a_n kkrrbb55__cc__vvaalliidd__cckkssuummttyyppee(_k_r_b_5___c_k_s_u_m_t_y_p_e _c_t_y_p_e); _k_r_b_5___b_o_o_l_e_a_n kkrrbb55__cc__iiss__ccoollll__pprrooooff__cckkssuumm(_k_r_b_5___c_k_s_u_m_t_y_p_e _c_t_y_p_e); _k_r_b_5___b_o_o_l_e_a_n kkrrbb55__cc__iiss__kkeeyyeedd__cckkssuumm(_k_r_b_5___c_k_s_u_m_t_y_p_e _c_t_y_p_e); _k_r_b_5___e_r_r_o_r___c_o_d_e kkrrbb55__cc__kkeeyylleennggtthhss(_k_r_b_5___c_o_n_t_e_x_t _c_o_n_t_e_x_t, _k_r_b_5___e_n_c_t_y_p_e _e_n_c_t_y_p_e, _s_i_z_e___t _*_i_n_l_e_n_g_t_h, _s_i_z_e___t _*_k_e_y_l_e_n_g_t_h); DDEESSCCRRIIPPTTIIOONN The functions starting with krb5_c are compat functions with MIT ker- beros. The krb5_enc_data structure holds and encrypted data. There are two pub- lic accessible members of krb5_enc_data. enctype that holds the encryp- tion type of the data encrypted and ciphertext that is a _k_r_b_5___d_a_t_a that might contain the encrypted data. kkrrbb55__cc__bblloocckk__ssiizzee() returns the blocksize of the encryption type. kkrrbb55__cc__ddeeccrryypptt() decrypts _i_n_p_u_t and store the data in _o_u_t_p_u_t_. If _i_v_e_c is NULL the default initialization vector for that encryption type will be used. kkrrbb55__cc__eennccrryypptt() encrypts the plaintext in _i_n_p_u_t and store the ciphertext in _o_u_t_p_u_t. kkrrbb55__cc__eennccrryypptt__lleennggtthh() returns the length the encrypted data given the plaintext length. kkrrbb55__cc__eennccttyyppee__ccoommppaarree() compares to encryption types and returns if they use compatible encryption key types. kkrrbb55__cc__mmaakkee__cchheecckkssuumm() creates a checksum _c_k_s_u_m with the checksum type _c_k_s_u_m_t_y_p_e of the data in _d_a_t_a. _k_e_y and _u_s_a_g_e are used if the checksum is a keyed checksum type. Returns 0 or an error code. kkrrbb55__cc__vveerriiffyy__cchheecckkssuumm() verifies the checksum of _d_a_t_a in _c_k_s_u_m that was created with _k_e_y using the key usage _u_s_a_g_e. _v_e_r_i_f_y is set to non-zero if the checksum verifies correctly and zero if not. Returns 0 or an error code. kkrrbb55__cc__cchheecckkssuumm__lleennggtthh() returns the length of the checksum. kkrrbb55__cc__sseett__cchheecckkssuumm() sets the krb5_checksum structure given _t_y_p_e and _d_a_t_a. The content of _c_k_s_u_m should be freeed with kkrrbb55__cc__ffrreeee__cchheecckkssuumm__ccoonntteennttss(). kkrrbb55__cc__ggeett__cchheecckkssuumm() retrieves the components of the krb5_checksum. structure. _d_a_t_a should be free with kkrrbb55__ffrreeee__ddaattaa(). If some either of _d_a_t_a or _c_h_e_c_k_s_u_m is not needed for the application, NULL can be passed in. kkrrbb55__cc__vvaalliidd__eennccttyyppee() returns true if _e_t_y_p_e is a valid encryption type. kkrrbb55__cc__vvaalliidd__cckkssuummttyyppee() returns true if _c_t_y_p_e is a valid checksum type. kkrrbb55__cc__iiss__kkeeyyeedd__cckkssuumm() return true if _c_t_y_p_e is a keyed checksum type. kkrrbb55__cc__iiss__ccoollll__pprrooooff__cckkssuumm() returns true if _c_t_y_p_e is a collision proof checksum type. kkrrbb55__cc__kkeeyylleennggtthhss() return the minimum length (_i_n_l_e_n_g_t_h) bytes needed to create a key and the length (_k_e_y_l_e_n_g_t_h) of the resulting key for the _e_n_c_t_y_p_e. SSEEEE AALLSSOO krb5(3), krb5_create_checksum(3), krb5_free_data(3), kerberos(8) HEIMDAL Nov 17, 2006 HEIMDAL heimdal-7.5.0/lib/krb5/crypto.h0000644000175000017500000001675613026237312014372 0ustar niknik/* * Copyright (c) 1997 - 2016 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #ifndef HEIMDAL_SMALLER #define DES3_OLD_ENCTYPE 1 #endif struct _krb5_key_data { krb5_keyblock *key; krb5_data *schedule; }; struct _krb5_key_usage; struct krb5_crypto_data { struct _krb5_encryption_type *et; struct _krb5_key_data key; int num_key_usage; struct _krb5_key_usage *key_usage; }; #define CRYPTO_ETYPE(C) ((C)->et->type) /* bits for `flags' below */ #define F_KEYED 0x0001 /* checksum is keyed */ #define F_CPROOF 0x0002 /* checksum is collision proof */ #define F_DERIVED 0x0004 /* uses derived keys */ #define F_VARIANT 0x0008 /* uses `variant' keys (6.4.3) */ #define F_PSEUDO 0x0010 /* not a real protocol type */ #define F_DISABLED 0x0020 /* enctype/checksum disabled */ #define F_WEAK 0x0040 /* enctype is considered weak */ #define F_RFC3961_ENC 0x0100 /* RFC3961 simplified profile */ #define F_SPECIAL 0x0200 /* backwards */ #define F_ENC_THEN_CKSUM 0x0400 /* checksum is over encrypted data */ #define F_CRYPTO_MASK 0x0F00 #define F_RFC3961_KDF 0x1000 /* RFC3961 KDF */ #define F_SP800_108_HMAC_KDF 0x2000 /* SP800-108 HMAC KDF */ #define F_KDF_MASK 0xF000 struct salt_type { krb5_salttype type; const char *name; krb5_error_code (*string_to_key)(krb5_context, krb5_enctype, krb5_data, krb5_salt, krb5_data, krb5_keyblock*); }; struct _krb5_key_type { krb5_enctype type; const char *name; size_t bits; size_t size; size_t schedule_size; void (*random_key)(krb5_context, krb5_keyblock*); void (*schedule)(krb5_context, struct _krb5_key_type *, struct _krb5_key_data *); struct salt_type *string_to_key; void (*random_to_key)(krb5_context, krb5_keyblock*, const void*, size_t); void (*cleanup)(krb5_context, struct _krb5_key_data *); const EVP_CIPHER *(*evp)(void); }; struct _krb5_checksum_type { krb5_cksumtype type; const char *name; size_t blocksize; size_t checksumsize; unsigned flags; krb5_error_code (*checksum)(krb5_context context, struct _krb5_key_data *key, const void *buf, size_t len, unsigned usage, Checksum *csum); krb5_error_code (*verify)(krb5_context context, struct _krb5_key_data *key, const void *buf, size_t len, unsigned usage, Checksum *csum); }; struct _krb5_encryption_type { krb5_enctype type; const char *name; const char *alias; size_t blocksize; size_t padsize; size_t confoundersize; struct _krb5_key_type *keytype; struct _krb5_checksum_type *checksum; struct _krb5_checksum_type *keyed_checksum; unsigned flags; krb5_error_code (*encrypt)(krb5_context context, struct _krb5_key_data *key, void *data, size_t len, krb5_boolean encryptp, int usage, void *ivec); size_t prf_length; krb5_error_code (*prf)(krb5_context, krb5_crypto, const krb5_data *, krb5_data *); }; #define ENCRYPTION_USAGE(U) (((U) << 8) | 0xAA) #define INTEGRITY_USAGE(U) (((U) << 8) | 0x55) #define CHECKSUM_USAGE(U) (((U) << 8) | 0x99) /* Checksums */ extern struct _krb5_checksum_type _krb5_checksum_none; extern struct _krb5_checksum_type _krb5_checksum_crc32; extern struct _krb5_checksum_type _krb5_checksum_rsa_md4; extern struct _krb5_checksum_type _krb5_checksum_rsa_md4_des; extern struct _krb5_checksum_type _krb5_checksum_rsa_md5_des; extern struct _krb5_checksum_type _krb5_checksum_rsa_md5_des3; extern struct _krb5_checksum_type _krb5_checksum_rsa_md5; extern struct _krb5_checksum_type _krb5_checksum_hmac_sha1_des3; extern struct _krb5_checksum_type _krb5_checksum_hmac_sha1_aes128; extern struct _krb5_checksum_type _krb5_checksum_hmac_sha1_aes256; extern struct _krb5_checksum_type _krb5_checksum_hmac_sha256_128_aes128; extern struct _krb5_checksum_type _krb5_checksum_hmac_sha384_192_aes256; extern struct _krb5_checksum_type _krb5_checksum_hmac_md5; extern struct _krb5_checksum_type _krb5_checksum_sha1; extern struct _krb5_checksum_type _krb5_checksum_sha2; extern struct _krb5_checksum_type *_krb5_checksum_types[]; extern int _krb5_num_checksums; /* Salts */ extern struct salt_type _krb5_AES_SHA1_salt[]; extern struct salt_type _krb5_AES_SHA2_salt[]; extern struct salt_type _krb5_arcfour_salt[]; extern struct salt_type _krb5_des_salt[]; extern struct salt_type _krb5_des3_salt[]; extern struct salt_type _krb5_des3_salt_derived[]; /* Encryption types */ extern struct _krb5_encryption_type _krb5_enctype_aes256_cts_hmac_sha1; extern struct _krb5_encryption_type _krb5_enctype_aes128_cts_hmac_sha1; extern struct _krb5_encryption_type _krb5_enctype_aes128_cts_hmac_sha256_128; extern struct _krb5_encryption_type _krb5_enctype_aes256_cts_hmac_sha384_192; extern struct _krb5_encryption_type _krb5_enctype_des3_cbc_sha1; extern struct _krb5_encryption_type _krb5_enctype_des3_cbc_md5; extern struct _krb5_encryption_type _krb5_enctype_des3_cbc_none; extern struct _krb5_encryption_type _krb5_enctype_arcfour_hmac_md5; extern struct _krb5_encryption_type _krb5_enctype_des_cbc_md5; extern struct _krb5_encryption_type _krb5_enctype_old_des3_cbc_sha1; extern struct _krb5_encryption_type _krb5_enctype_des_cbc_crc; extern struct _krb5_encryption_type _krb5_enctype_des_cbc_md4; extern struct _krb5_encryption_type _krb5_enctype_des_cbc_md5; extern struct _krb5_encryption_type _krb5_enctype_des_cbc_none; extern struct _krb5_encryption_type _krb5_enctype_des_cfb64_none; extern struct _krb5_encryption_type _krb5_enctype_des_pcbc_none; extern struct _krb5_encryption_type _krb5_enctype_null; extern struct _krb5_encryption_type *_krb5_etypes[]; extern int _krb5_num_etypes; /* NO_HCRYPTO_POLLUTION is defined in pkinit-ec.c. See commentary there. */ #ifndef NO_HCRYPTO_POLLUTION /* Interface to the EVP crypto layer provided by hcrypto */ struct _krb5_evp_schedule { /* * Normally we'd say EVP_CIPHER_CTX here, but! this header gets * included in lib/krb5/pkinit-ec.ck */ EVP_CIPHER_CTX ectx; EVP_CIPHER_CTX dctx; }; #endif heimdal-7.5.0/lib/krb5/test_addr.c0000644000175000017500000001643112136107750015007 0ustar niknik/* * Copyright (c) 2005 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of KTH nor the names of its contributors may be * used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY KTH AND ITS CONTRIBUTORS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL KTH OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "krb5_locl.h" #include static void print_addr(krb5_context context, const char *addr) { krb5_addresses addresses; krb5_error_code ret; char buf[38]; char buf2[1000]; size_t len; int i; ret = krb5_parse_address(context, addr, &addresses); if (ret) krb5_err(context, 1, ret, "krb5_parse_address"); if (addresses.len < 1) krb5_err(context, 1, ret, "too few addresses"); for (i = 0; i < addresses.len; i++) { krb5_print_address(&addresses.val[i], buf, sizeof(buf), &len); #if 0 printf("addr %d: %s (%d/%d)\n", i, buf, (int)len, (int)strlen(buf)); #endif if (strlen(buf) > sizeof(buf)) krb5_err(context, 1, ret, "len %d larger then buf %d", (int)strlen(buf), (int)sizeof(buf)); krb5_print_address(&addresses.val[i], buf2, sizeof(buf2), &len); #if 0 printf("addr %d: %s (%d/%d)\n", i, buf2, (int)len, (int)strlen(buf2)); #endif if (strlen(buf2) > sizeof(buf2)) krb5_err(context, 1, ret, "len %d larger then buf %d", (int)strlen(buf2), (int)sizeof(buf2)); } krb5_free_addresses(context, &addresses); } static void truncated_addr(krb5_context context, const char *addr, size_t truncate_len, size_t outlen) { krb5_addresses addresses; krb5_error_code ret; char *buf; size_t len; buf = ecalloc(1, outlen + 1); ret = krb5_parse_address(context, addr, &addresses); if (ret) krb5_err(context, 1, ret, "krb5_parse_address"); if (addresses.len != 1) krb5_err(context, 1, ret, "addresses should be one"); krb5_print_address(&addresses.val[0], buf, truncate_len, &len); #if 0 printf("addr %s (%d/%d) should be %d\n", buf, (int)len, (int)strlen(buf), (int)outlen); #endif if (truncate_len > strlen(buf) + 1) krb5_err(context, 1, ret, "%s truncate_len %d larger then strlen %d source %s", buf, (int)truncate_len, (int)strlen(buf), addr); if (outlen != len) krb5_err(context, 1, ret, "%s: outlen %d != len %d", buf, (int)outlen, (int)strlen(buf)); krb5_print_address(&addresses.val[0], buf, outlen + 1, &len); #if 0 printf("addr %s (%d/%d)\n", buf, (int)len, (int)strlen(buf)); #endif if (len != outlen) abort(); if (strlen(buf) != len) abort(); krb5_free_addresses(context, &addresses); free(buf); } static void check_truncation(krb5_context context, const char *addr) { int i, len = strlen(addr); truncated_addr(context, addr, len, len); for (i = 0; i < len; i++) truncated_addr(context, addr, i, len); } static void match_addr(krb5_context context, const char *range_addr, const char *one_addr, int match) { krb5_addresses range, one; krb5_error_code ret; ret = krb5_parse_address(context, range_addr, &range); if (ret) krb5_err(context, 1, ret, "krb5_parse_address"); if (range.len != 1) krb5_err(context, 1, ret, "wrong num of addresses"); ret = krb5_parse_address(context, one_addr, &one); if (ret) krb5_err(context, 1, ret, "krb5_parse_address"); if (one.len != 1) krb5_err(context, 1, ret, "wrong num of addresses"); if (krb5_address_order(context, &range.val[0], &one.val[0]) == 0) { if (!match) krb5_errx(context, 1, "match when one shouldn't be"); } else { if (match) krb5_errx(context, 1, "no match when one should be"); } krb5_free_addresses(context, &range); krb5_free_addresses(context, &one); } #ifdef _MSC_VER /* For the truncation tests, calling strcpy_s() or strcat_s() with a size of 0 results in the invalid parameter handler being invoked. For the debug version, the runtime also throws an assert. */ static void inv_param_handler(const wchar_t* expression, const wchar_t* function, const wchar_t* file, unsigned int line, uintptr_t pReserved) { printf("Invalid parameter handler invoked for: %S in %S(%d) [%S]\n", function, file, line, expression); } static _invalid_parameter_handler _inv_old = NULL; #define SET_INVALID_PARAM_HANDLER _inv_old = _set_invalid_parameter_handler(inv_param_handler) #else #define SET_INVALID_PARAM_HANDLER ((void) 0) #endif int main(int argc, char **argv) { krb5_context context; krb5_error_code ret; SET_INVALID_PARAM_HANDLER; setprogname(argv[0]); ret = krb5_init_context(&context); if (ret) errx (1, "krb5_init_context failed: %d", ret); print_addr(context, "RANGE:127.0.0.0/8"); print_addr(context, "RANGE:127.0.0.0/24"); print_addr(context, "RANGE:IPv4:127.0.0.0-IPv4:127.0.0.255"); print_addr(context, "RANGE:130.237.237.4/29"); #ifdef HAVE_IPV6 print_addr(context, "RANGE:2001:db8:1:2:3:4:1428:7ab/64"); print_addr(context, "RANGE:IPv6:fe80::209:6bff:fea0:e522/64"); print_addr(context, "RANGE:IPv6:fe80::-IPv6:fe80::ffff:ffff:ffff:ffff"); print_addr(context, "RANGE:fe80::-fe80::ffff:ffff:ffff:ffff"); #endif check_truncation(context, "IPv4:127.0.0.0"); check_truncation(context, "RANGE:IPv4:127.0.0.0-IPv4:127.0.0.255"); #ifdef HAVE_IPV6 check_truncation(context, "IPv6:::"); check_truncation(context, "IPv6:::1"); check_truncation(context, "IPv6:2001:db8:1:2:3:4:1428:7ab"); check_truncation(context, "IPv6:fe80::209:0:0:0"); check_truncation(context, "IPv6:fe80::ffff:ffff:ffff:ffff"); #endif match_addr(context, "RANGE:127.0.0.0/8", "inet:127.0.0.0", 1); match_addr(context, "RANGE:127.0.0.0/8", "inet:127.255.255.255", 1); match_addr(context, "RANGE:127.0.0.0/8", "inet:128.0.0.0", 0); match_addr(context, "RANGE:130.237.237.8/29", "inet:130.237.237.7", 0); match_addr(context, "RANGE:130.237.237.8/29", "inet:130.237.237.8", 1); match_addr(context, "RANGE:130.237.237.8/29", "inet:130.237.237.15", 1); match_addr(context, "RANGE:130.237.237.8/29", "inet:130.237.237.16", 0); krb5_free_context(context); return 0; } heimdal-7.5.0/lib/krb5/krb5_get_forwarded_creds.cat30000644000175000017500000000425713212450756020373 0ustar niknik KRB5_GET_FORWARDED_CR... BSD Library Functions Manual KRB5_GET_FORWARDED_CR... NNAAMMEE kkrrbb55__ggeett__ffoorrwwaarrddeedd__ccrreeddss, kkrrbb55__ffwwdd__ttggtt__ccrreeddss -- get forwarded credentials from the KDC LLIIBBRRAARRYY Kerberos 5 Library (libkrb5, -lkrb5) SSYYNNOOPPSSIISS ##iinncclluuddee <> _k_r_b_5___e_r_r_o_r___c_o_d_e kkrrbb55__ggeett__ffoorrwwaarrddeedd__ccrreeddss(_k_r_b_5___c_o_n_t_e_x_t _c_o_n_t_e_x_t, _k_r_b_5___a_u_t_h___c_o_n_t_e_x_t _a_u_t_h___c_o_n_t_e_x_t, _k_r_b_5___c_c_a_c_h_e _c_c_a_c_h_e, _k_r_b_5___f_l_a_g_s _f_l_a_g_s, _c_o_n_s_t _c_h_a_r _*_h_o_s_t_n_a_m_e, _k_r_b_5___c_r_e_d_s _*_i_n___c_r_e_d_s, _k_r_b_5___d_a_t_a _*_o_u_t___d_a_t_a); _k_r_b_5___e_r_r_o_r___c_o_d_e kkrrbb55__ffwwdd__ttggtt__ccrreeddss(_k_r_b_5___c_o_n_t_e_x_t _c_o_n_t_e_x_t, _k_r_b_5___a_u_t_h___c_o_n_t_e_x_t _a_u_t_h___c_o_n_t_e_x_t, _c_o_n_s_t _c_h_a_r _*_h_o_s_t_n_a_m_e, _k_r_b_5___p_r_i_n_c_i_p_a_l _c_l_i_e_n_t, _k_r_b_5___p_r_i_n_c_i_p_a_l _s_e_r_v_e_r, _k_r_b_5___c_c_a_c_h_e _c_c_a_c_h_e, _i_n_t _f_o_r_w_a_r_d_a_b_l_e, _k_r_b_5___d_a_t_a _*_o_u_t___d_a_t_a); DDEESSCCRRIIPPTTIIOONN kkrrbb55__ggeett__ffoorrwwaarrddeedd__ccrreeddss() and kkrrbb55__ffwwdd__ttggtt__ccrreeddss() get tickets forwarded to _h_o_s_t_n_a_m_e_. If the tickets that are forwarded are address-less, the for- warded tickets will also be address-less, otherwise _h_o_s_t_n_a_m_e will be used for figure out the address to forward the ticket too. SSEEEE AALLSSOO krb5(3), krb5_get_credentials(3), krb5.conf(5) HEIMDAL July 26, 2004 HEIMDAL heimdal-7.5.0/lib/krb5/prompter_posix.c0000644000175000017500000000471512136107750016132 0ustar niknik/* * Copyright (c) 1997 - 2001 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "krb5_locl.h" KRB5_LIB_FUNCTION int KRB5_CALLCONV krb5_prompter_posix (krb5_context context, void *data, const char *name, const char *banner, int num_prompts, krb5_prompt prompts[]) { int i; if (name) fprintf (stderr, "%s\n", name); if (banner) fprintf (stderr, "%s\n", banner); if (name || banner) fflush(stderr); for (i = 0; i < num_prompts; ++i) { if (prompts[i].hidden) { if(UI_UTIL_read_pw_string(prompts[i].reply->data, prompts[i].reply->length, prompts[i].prompt, 0)) return 1; } else { char *s = prompts[i].reply->data; fputs (prompts[i].prompt, stdout); fflush (stdout); if(fgets(prompts[i].reply->data, prompts[i].reply->length, stdin) == NULL) return 1; s[strcspn(s, "\n")] = '\0'; } } return 0; } heimdal-7.5.0/lib/krb5/krb5_principal.30000644000175000017500000002751013026237312015657 0ustar niknik.\" Copyright (c) 2003 - 2007 Kungliga Tekniska Högskolan .\" (Royal Institute of Technology, Stockholm, Sweden). .\" All rights reserved. .\" .\" Redistribution and use in source and binary forms, with or without .\" modification, are permitted provided that the following conditions .\" are met: .\" .\" 1. Redistributions of source code must retain the above copyright .\" notice, this list of conditions and the following disclaimer. .\" .\" 2. Redistributions in binary form must reproduce the above copyright .\" notice, this list of conditions and the following disclaimer in the .\" documentation and/or other materials provided with the distribution. .\" .\" 3. Neither the name of the Institute nor the names of its contributors .\" may be used to endorse or promote products derived from this software .\" without specific prior written permission. .\" .\" THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND .\" ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE .\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE .\" ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE .\" FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL .\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS .\" OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) .\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT .\" LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF .\" SUCH DAMAGE. .\" .\" $Id$ .\" .Dd May 1, 2006 .Dt KRB5_PRINCIPAL 3 .Os HEIMDAL .Sh NAME .Nm krb5_get_default_principal , .Nm krb5_principal , .Nm krb5_build_principal , .Nm krb5_build_principal_ext , .Nm krb5_build_principal_va , .Nm krb5_build_principal_va_ext , .Nm krb5_copy_principal , .Nm krb5_free_principal , .Nm krb5_make_principal , .Nm krb5_parse_name , .Nm krb5_parse_name_flags , .Nm krb5_parse_nametype , .Nm krb5_princ_set_realm , .Nm krb5_principal_compare , .Nm krb5_principal_compare_any_realm , .Nm krb5_principal_get_comp_string , .Nm krb5_principal_get_realm , .Nm krb5_principal_get_type , .Nm krb5_principal_match , .Nm krb5_principal_set_type , .Nm krb5_realm_compare , .Nm krb5_sname_to_principal , .Nm krb5_sock_to_principal , .Nm krb5_unparse_name , .Nm krb5_unparse_name_flags , .Nm krb5_unparse_name_fixed , .Nm krb5_unparse_name_fixed_flags , .Nm krb5_unparse_name_fixed_short , .Nm krb5_unparse_name_short .Nd Kerberos 5 principal handling functions .Sh LIBRARY Kerberos 5 Library (libkrb5, -lkrb5) .Sh SYNOPSIS .In krb5.h .Pp .Li krb5_principal ; .Ft void .Fn krb5_free_principal "krb5_context context" "krb5_principal principal" .Ft krb5_error_code .Fn krb5_parse_name "krb5_context context" "const char *name" "krb5_principal *principal" .Ft krb5_error_code .Fn krb5_parse_name_flags "krb5_context context" "const char *name" "int flags" "krb5_principal *principal" .Ft krb5_error_code .Fn "krb5_unparse_name" "krb5_context context" "krb5_const_principal principal" "char **name" .Ft krb5_error_code .Fn "krb5_unparse_name_flags" "krb5_context context" "krb5_const_principal principal" "int flags" "char **name" .Ft krb5_error_code .Fn krb5_unparse_name_fixed "krb5_context context" "krb5_const_principal principal" "char *name" "size_t len" .Ft krb5_error_code .Fn krb5_unparse_name_fixed_flags "krb5_context context" "krb5_const_principal principal" "int flags" "char *name" "size_t len" .Ft krb5_error_code .Fn "krb5_unparse_name_short" "krb5_context context" "krb5_const_principal principal" "char **name" .Ft krb5_error_code .Fn krb5_unparse_name_fixed_short "krb5_context context" "krb5_const_principal principal" "char *name" "size_t len" .Ft void .Fn krb5_princ_set_realm "krb5_context context" "krb5_principal principal" "krb5_realm *realm" .Ft krb5_error_code .Fn krb5_build_principal "krb5_context context" "krb5_principal *principal" "int rlen" "krb5_const_realm realm" "..." .Ft krb5_error_code .Fn krb5_build_principal_va "krb5_context context" "krb5_principal *principal" "int rlen" "krb5_const_realm realm" "va_list ap" .Ft krb5_error_code .Fn "krb5_build_principal_ext" "krb5_context context" "krb5_principal *principal" "int rlen" "krb5_const_realm realm" "..." .Ft krb5_error_code .Fn krb5_build_principal_va_ext "krb5_context context" "krb5_principal *principal" "int rlen" "krb5_const_realm realm" "va_list ap" .Ft krb5_error_code .Fn krb5_make_principal "krb5_context context" "krb5_principal *principal" "krb5_const_realm realm" "..." .Ft krb5_error_code .Fn krb5_copy_principal "krb5_context context" "krb5_const_principal inprinc" "krb5_principal *outprinc" .Ft krb5_boolean .Fn krb5_principal_compare "krb5_context context" "krb5_const_principal princ1" "krb5_const_principal princ2" .Ft krb5_boolean .Fn krb5_principal_compare_any_realm "krb5_context context" "krb5_const_principal princ1" "krb5_const_principal princ2" .Ft "const char *" .Fn krb5_principal_get_comp_string "krb5_context context" "krb5_const_principal principal" "unsigned int component" .Ft "const char *" .Fn krb5_principal_get_realm "krb5_context context" "krb5_const_principal principal" .Ft int .Fn krb5_principal_get_type "krb5_context context" "krb5_const_principal principal" .Ft krb5_boolean .Fn krb5_principal_match "krb5_context context" "krb5_const_principal principal" "krb5_const_principal pattern" .Ft void .Fn krb5_principal_set_type "krb5_context context" "krb5_principal principal" "int type" .Ft krb5_boolean .Fn krb5_realm_compare "krb5_context context" "krb5_const_principal princ1" "krb5_const_principal princ2" .Ft krb5_error_code .Fn krb5_sname_to_principal "krb5_context context" "const char *hostname" "const char *sname" "int32_t type" "krb5_principal *ret_princ" .Ft krb5_error_code .Fn krb5_sock_to_principal "krb5_context context" "int socket" "const char *sname" "int32_t type" "krb5_principal *principal" .Ft krb5_error_code .Fn krb5_get_default_principal "krb5_context context" "krb5_principal *princ" .Ft krb5_error_code .Fn krb5_parse_nametype "krb5_context context" "const char *str" "int32_t *type" .Sh DESCRIPTION .Li krb5_principal holds the name of a user or service in Kerberos. .Pp A principal has two parts, a .Li PrincipalName and a .Li realm . The PrincipalName consists of one or more components. In printed form, the components are separated by /. The PrincipalName also has a name-type. .Pp Examples of a principal are .Li nisse/root@EXAMPLE.COM and .Li host/datan.kth.se@KTH.SE . .Fn krb5_parse_name and .Fn krb5_parse_name_flags passes a principal name in .Fa name to the kerberos principal structure. .Fn krb5_parse_name_flags takes an extra .Fa flags argument the following flags can be passed in .Bl -tag -width Ds .It Dv KRB5_PRINCIPAL_PARSE_NO_REALM requires the input string to be without a realm, and no realm is stored in the .Fa principal return argument. .It Dv KRB5_PRINCIPAL_PARSE_REQUIRE_REALM requires the input string to with a realm. .El .Pp .Fn krb5_unparse_name and .Fn krb5_unparse_name_flags prints the principal .Fa princ to the string .Fa name . .Fa name should be freed with .Xr free 3 . To the .Fa flags argument the following flags can be passed in .Bl -tag -width Ds .It Dv KRB5_PRINCIPAL_UNPARSE_SHORT no realm if the realm is one of the local realms. .It Dv KRB5_PRINCIPAL_UNPARSE_NO_REALM never include any realm in the principal name. .It Dv KRB5_PRINCIPAL_UNPARSE_DISPLAY don't quote .El On failure .Fa name is set to .Dv NULL . .Fn krb5_unparse_name_fixed and .Fn krb5_unparse_name_fixed_flags behaves just like .Fn krb5_unparse , but instead unparses the principal into a fixed size buffer. .Pp .Fn krb5_unparse_name_short just returns the principal without the realm if the principal is in the default realm. If the principal isn't, the full name is returned. .Fn krb5_unparse_name_fixed_short works just like .Fn krb5_unparse_name_short but on a fixed size buffer. .Pp .Fn krb5_build_principal builds a principal from the realm .Fa realm that has the length .Fa rlen . The following arguments form the components of the principal. The list of components is terminated with .Dv NULL . .Pp .Fn krb5_build_principal_va works like .Fn krb5_build_principal using vargs. .Pp .Fn krb5_build_principal_ext and .Fn krb5_build_principal_va_ext take a list of length-value pairs, the list is terminated with a zero length. .Pp .Fn krb5_make_principal works the same way as .Fn krb5_build_principal , except it figures out the length of the realm itself. .Pp .Fn krb5_copy_principal makes a copy of a principal. The copy needs to be freed with .Fn krb5_free_principal . .Pp .Fn krb5_principal_compare compares the two principals, including realm of the principals and returns .Dv TRUE if they are the same and .Dv FALSE if not. .Pp .Fn krb5_principal_compare_any_realm works the same way as .Fn krb5_principal_compare but doesn't compare the realm component of the principal. .Pp .Fn krb5_realm_compare compares the realms of the two principals and returns .Dv TRUE is they are the same, and .Dv FALSE if not. .Pp .Fn krb5_principal_match matches a .Fa principal against a .Fa pattern . The pattern is a globbing expression, where each component (separated by /) is matched against the corresponding component of the principal. .Pp The .Fn krb5_principal_get_realm and .Fn krb5_principal_get_comp_string functions return parts of the .Fa principal , either the realm or a specific component. Both functions return string pointers to data inside the principal, so they are valid only as long as the principal exists. .Pp The .Fa component argument to .Fn krb5_principal_get_comp_string is the index of the component to return, from zero to the total number of components minus one. If the index is out of range .Dv NULL is returned. .Pp .Fn krb5_principal_get_realm and .Fn krb5_principal_get_comp_string are replacements for .Fn krb5_princ_component and related macros, described as internal in the MIT API specification. Unlike the macros, these functions return strings, not .Dv krb5_data . A reason to return .Dv krb5_data was that it was believed that principal components could contain binary data, but this belief was unfounded, and it has been decided that principal components are infact UTF8, so it's safe to use zero terminated strings. .Pp It's generally not necessary to look at the components of a principal. .Pp .Fn krb5_principal_get_type and .Fn krb5_principal_set_type get and sets the name type for a principal. Name type handling is tricky and not often needed, don't use this unless you know what you do. .Pp .Fn krb5_sname_to_principal and .Fn krb5_sock_to_principal are for easy creation of .Dq service principals that can, for instance, be used to lookup a key in a keytab. For both functions the .Fa sname parameter will be used for the first component of the created principal. If .Fa sname is .Dv NULL , .Dq host will be used instead. .Pp .Fn krb5_sname_to_principal will use the passed .Fa hostname for the second component. If .Fa type is .Dv KRB5_NT_SRV_HST this name will be looked up with .Fn gethostbyname . If .Fa hostname is .Dv NULL , the local hostname will be used. .Pp .Fn krb5_sock_to_principal will use the .Dq sockname of the passed .Fa socket , which should be a bound .Dv AF_INET or .Dv AF_INET6 socket. There must be a mapping between the address and .Dq sockname . The function may try to resolve the name in DNS. .Pp .Fn krb5_get_default_principal tries to find out what's a reasonable default principal by looking at the environment it is running in. .Pp .Fn krb5_parse_nametype parses and returns the name type integer value in .Fa type . On failure the function returns an error code and set the error string. .\" .Sh EXAMPLES .Sh SEE ALSO .Xr krb5_config 3 , .Xr krb5.conf 5 .Sh BUGS You can not have a NUL in a component in some of the variable argument functions above. Until someone can give a good example of where it would be a good idea to have NUL's in a component, this will not be fixed. heimdal-7.5.0/lib/krb5/recvauth.c0000644000175000017500000001715013026237312014653 0ustar niknik/* * Copyright (c) 1997-2007 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "krb5_locl.h" /* * See `sendauth.c' for the format. */ static krb5_boolean match_exact(const void *data, const char *appl_version) { return strcmp(data, appl_version) == 0; } /** * Perform the server side of the sendauth protocol. * * @param context Kerberos 5 context. * @param auth_context authentication context of the peer. * @param p_fd socket associated to the connection. * @param appl_version server-specific string. * @param server server principal. * @param flags if KRB5_RECVAUTH_IGNORE_VERSION is set, skip the sendauth version * part of the protocol. * @param keytab server keytab. * @param ticket on success, set to the authenticated client credentials. * Must be deallocated with krb5_free_ticket(). If not * interested, pass a NULL value. * * @return 0 to indicate success. Otherwise a Kerberos error code is * returned, see krb5_get_error_message(). */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_recvauth(krb5_context context, krb5_auth_context *auth_context, krb5_pointer p_fd, const char *appl_version, krb5_principal server, int32_t flags, krb5_keytab keytab, krb5_ticket **ticket) { return krb5_recvauth_match_version(context, auth_context, p_fd, match_exact, appl_version, server, flags, keytab, ticket); } /** * Perform the server side of the sendauth protocol like krb5_recvauth(), but support * a user-specified callback, \a match_appl_version, to perform the match of the application * version \a match_data. */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_recvauth_match_version(krb5_context context, krb5_auth_context *auth_context, krb5_pointer p_fd, krb5_boolean (*match_appl_version)(const void *, const char*), const void *match_data, krb5_principal server, int32_t flags, krb5_keytab keytab, krb5_ticket **ticket) { krb5_error_code ret; const char *version = KRB5_SENDAUTH_VERSION; char her_version[sizeof(KRB5_SENDAUTH_VERSION)]; char *her_appl_version; uint32_t len; u_char repl; krb5_data data; krb5_flags ap_options; ssize_t n; /* * If there are no addresses in auth_context, get them from `fd'. */ if (*auth_context == NULL) { ret = krb5_auth_con_init (context, auth_context); if (ret) return ret; } ret = krb5_auth_con_setaddrs_from_fd (context, *auth_context, p_fd); if (ret) return ret; /* * Expect SENDAUTH protocol version. */ if(!(flags & KRB5_RECVAUTH_IGNORE_VERSION)) { n = krb5_net_read (context, p_fd, &len, 4); if (n < 0) { ret = errno ? errno : EINVAL; krb5_set_error_message(context, ret, "read: %s", strerror(ret)); return ret; } if (n == 0) { krb5_set_error_message(context, KRB5_SENDAUTH_BADAUTHVERS, N_("Failed to receive sendauth data", "")); return KRB5_SENDAUTH_BADAUTHVERS; } len = ntohl(len); if (len != sizeof(her_version) || krb5_net_read (context, p_fd, her_version, len) != len || strncmp (version, her_version, len)) { repl = 1; krb5_net_write (context, p_fd, &repl, 1); krb5_clear_error_message (context); return KRB5_SENDAUTH_BADAUTHVERS; } } /* * Expect application protocol version. */ n = krb5_net_read (context, p_fd, &len, 4); if (n < 0) { ret = errno ? errno : EINVAL; krb5_set_error_message(context, ret, "read: %s", strerror(ret)); return ret; } if (n == 0) { krb5_clear_error_message (context); return KRB5_SENDAUTH_BADAPPLVERS; } len = ntohl(len); her_appl_version = malloc (len); if (her_appl_version == NULL) { repl = 2; krb5_net_write (context, p_fd, &repl, 1); return krb5_enomem(context); } if (krb5_net_read (context, p_fd, her_appl_version, len) != len || !(*match_appl_version)(match_data, her_appl_version)) { repl = 2; krb5_net_write (context, p_fd, &repl, 1); krb5_set_error_message(context, KRB5_SENDAUTH_BADAPPLVERS, N_("wrong sendauth application version (%s)", ""), her_appl_version); free (her_appl_version); return KRB5_SENDAUTH_BADAPPLVERS; } free (her_appl_version); /* * Send OK. */ repl = 0; if (krb5_net_write (context, p_fd, &repl, 1) != 1) { ret = errno ? errno : EINVAL; krb5_set_error_message(context, ret, "write: %s", strerror(ret)); return ret; } /* * Until here, the fields in the message were in cleartext and unauthenticated. * From now on, Kerberos kicks in. */ /* * Expect AP_REQ. */ krb5_data_zero (&data); ret = krb5_read_message (context, p_fd, &data); if (ret) return ret; ret = krb5_rd_req (context, auth_context, &data, server, keytab, &ap_options, ticket); krb5_data_free (&data); if (ret) { krb5_data error_data; krb5_error_code ret2; ret2 = krb5_mk_error (context, ret, NULL, NULL, NULL, server, NULL, NULL, &error_data); if (ret2 == 0) { krb5_write_message (context, p_fd, &error_data); krb5_data_free (&error_data); } return ret; } /* * Send OK. */ len = 0; if (krb5_net_write (context, p_fd, &len, 4) != 4) { ret = errno ? errno : EINVAL; krb5_set_error_message(context, ret, "write: %s", strerror(ret)); krb5_free_ticket(context, *ticket); *ticket = NULL; return ret; } /* * If client requires mutual authentication, send AP_REP. */ if (ap_options & AP_OPTS_MUTUAL_REQUIRED) { ret = krb5_mk_rep (context, *auth_context, &data); if (ret) { krb5_free_ticket(context, *ticket); *ticket = NULL; return ret; } ret = krb5_write_message (context, p_fd, &data); if (ret) { krb5_free_ticket(context, *ticket); *ticket = NULL; return ret; } krb5_data_free (&data); } return 0; } heimdal-7.5.0/lib/krb5/aname_to_localname.c0000644000175000017500000003055413026237312016633 0ustar niknik/* * Copyright (c) 1997 - 1999, 2002 - 2003 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include #include "krb5_locl.h" #include "an2ln_plugin.h" #include "db_plugin.h" /* Default plugin (DB using binary search of sorted text file) follows */ static krb5_error_code KRB5_LIB_CALL an2ln_def_plug_init(krb5_context, void **); static void KRB5_LIB_CALL an2ln_def_plug_fini(void *); static krb5_error_code KRB5_LIB_CALL an2ln_def_plug_an2ln(void *, krb5_context, const char *, krb5_const_principal, set_result_f, void *); static krb5plugin_an2ln_ftable an2ln_def_plug = { 0, an2ln_def_plug_init, an2ln_def_plug_fini, an2ln_def_plug_an2ln, }; /* Plugin engine code follows */ struct plctx { krb5_const_principal aname; heim_string_t luser; const char *rule; }; static krb5_error_code KRB5_LIB_CALL set_res(void *userctx, const char *res) { struct plctx *plctx = userctx; plctx->luser = heim_string_create(res); if (plctx->luser == NULL) return ENOMEM; return 0; } static krb5_error_code KRB5_LIB_CALL plcallback(krb5_context context, const void *plug, void *plugctx, void *userctx) { const krb5plugin_an2ln_ftable *locate = plug; struct plctx *plctx = userctx; if (plctx->luser) return 0; return locate->an2ln(plugctx, context, plctx->rule, plctx->aname, set_res, plctx); } static krb5_error_code an2ln_plugin(krb5_context context, const char *rule, krb5_const_principal aname, size_t lnsize, char *lname) { krb5_error_code ret; struct plctx ctx; ctx.rule = rule; ctx.aname = aname; ctx.luser = NULL; /* * Order of plugin invocation is non-deterministic, but there should * really be no more than one plugin that can handle any given kind * rule, so the effect should be deterministic anyways. */ ret = _krb5_plugin_run_f(context, "krb5", KRB5_PLUGIN_AN2LN, KRB5_PLUGIN_AN2LN_VERSION_0, 0, &ctx, plcallback); if (ret != 0) { heim_release(ctx.luser); return ret; } if (ctx.luser == NULL) return KRB5_PLUGIN_NO_HANDLE; if (strlcpy(lname, heim_string_get_utf8(ctx.luser), lnsize) >= lnsize) ret = KRB5_CONFIG_NOTENUFSPACE; heim_release(ctx.luser); return ret; } static void reg_def_plugins_once(void *ctx) { krb5_context context = ctx; krb5_plugin_register(context, PLUGIN_TYPE_DATA, KRB5_PLUGIN_AN2LN, &an2ln_def_plug); } static int princ_realm_is_default(krb5_context context, krb5_const_principal aname) { krb5_error_code ret; krb5_realm *lrealms = NULL; krb5_realm *r; int valid; ret = krb5_get_default_realms(context, &lrealms); if (ret) return 0; valid = 0; for (r = lrealms; *r != NULL; ++r) { if (strcmp (*r, aname->realm) == 0) { valid = 1; break; } } krb5_free_host_realm (context, lrealms); return valid; } /* * This function implements MIT's auth_to_local_names configuration for * configuration compatibility. Specifically: * * [realms] * = { * auth_to_local_names = { * = * } * } * * If multiple usernames are configured then the last one is taken. * * The configuration can only be expected to hold a relatively small * number of mappings. For lots of mappings use a DB. */ static krb5_error_code an2ln_local_names(krb5_context context, krb5_const_principal aname, size_t lnsize, char *lname) { krb5_error_code ret; char *unparsed; char **values; char *res; size_t i; if (!princ_realm_is_default(context, aname)) return KRB5_PLUGIN_NO_HANDLE; ret = krb5_unparse_name_flags(context, aname, KRB5_PRINCIPAL_UNPARSE_NO_REALM, &unparsed); if (ret) return ret; ret = KRB5_PLUGIN_NO_HANDLE; values = krb5_config_get_strings(context, NULL, "realms", aname->realm, "auth_to_local_names", unparsed, NULL); free(unparsed); if (!values) return ret; /* Take the last value, just like MIT */ for (res = NULL, i = 0; values[i]; i++) res = values[i]; if (res) { ret = 0; if (strlcpy(lname, res, lnsize) >= lnsize) ret = KRB5_CONFIG_NOTENUFSPACE; if (!*res || strcmp(res, ":") == 0) ret = KRB5_NO_LOCALNAME; } krb5_config_free_strings(values); return ret; } /* * Heimdal's default aname2lname mapping. */ static krb5_error_code an2ln_default(krb5_context context, char *rule, krb5_const_principal aname, size_t lnsize, char *lname) { krb5_error_code ret; const char *res; int root_princs_ok; if (strcmp(rule, "NONE") == 0) return KRB5_NO_LOCALNAME; if (strcmp(rule, "DEFAULT") == 0) root_princs_ok = 0; else if (strcmp(rule, "HEIMDAL_DEFAULT") == 0) root_princs_ok = 1; else return KRB5_PLUGIN_NO_HANDLE; if (!princ_realm_is_default(context, aname)) return KRB5_PLUGIN_NO_HANDLE; if (aname->name.name_string.len == 1) { /* * One component principal names in default realm -> the one * component is the username. */ res = aname->name.name_string.val[0]; } else if (root_princs_ok && aname->name.name_string.len == 2 && strcmp (aname->name.name_string.val[1], "root") == 0) { /* * Two-component principal names in default realm where the * first component is "root" -> root IFF the principal is in * root's .k5login (or whatever krb5_kuserok() does). */ krb5_principal rootprinc; krb5_boolean userok; res = "root"; ret = krb5_copy_principal(context, aname, &rootprinc); if (ret) return ret; userok = _krb5_kuserok(context, rootprinc, res, FALSE); krb5_free_principal(context, rootprinc); if (!userok) return KRB5_NO_LOCALNAME; } else { return KRB5_PLUGIN_NO_HANDLE; } if (strlcpy(lname, res, lnsize) >= lnsize) return KRB5_CONFIG_NOTENUFSPACE; return 0; } /** * Map a principal name to a local username. * * Returns 0 on success, KRB5_NO_LOCALNAME if no mapping was found, or * some Kerberos or system error. * * Inputs: * * @param context A krb5_context * @param aname A principal name * @param lnsize The size of the buffer into which the username will be written * @param lname The buffer into which the username will be written * * @ingroup krb5_support */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_aname_to_localname(krb5_context context, krb5_const_principal aname, size_t lnsize, char *lname) { static heim_base_once_t reg_def_plugins = HEIM_BASE_ONCE_INIT; krb5_error_code ret; krb5_realm realm; size_t i; char **rules = NULL; char *rule; if (lnsize) lname[0] = '\0'; heim_base_once_f(®_def_plugins, context, reg_def_plugins_once); /* Try MIT's auth_to_local_names config first */ ret = an2ln_local_names(context, aname, lnsize, lname); if (ret != KRB5_PLUGIN_NO_HANDLE) return ret; ret = krb5_get_default_realm(context, &realm); if (ret) return ret; rules = krb5_config_get_strings(context, NULL, "realms", realm, "auth_to_local", NULL); krb5_xfree(realm); if (!rules) { /* Heimdal's default rule */ ret = an2ln_default(context, "HEIMDAL_DEFAULT", aname, lnsize, lname); if (ret == KRB5_PLUGIN_NO_HANDLE) return KRB5_NO_LOCALNAME; return ret; } /* * MIT rules. * * Note that RULEs and DBs only have white-list functionality, * thus RULEs and DBs that we don't understand we simply ignore. * * This means that plugins that implement black-lists are * dangerous: if a black-list plugin isn't found, the black-list * won't be enforced. But black-lists are dangerous anyways. */ for (ret = KRB5_PLUGIN_NO_HANDLE, i = 0; rules[i]; i++) { rule = rules[i]; /* Try NONE, DEFAULT, and HEIMDAL_DEFAULT rules */ ret = an2ln_default(context, rule, aname, lnsize, lname); if (ret == KRB5_PLUGIN_NO_HANDLE) /* Try DB, RULE, ... plugins */ ret = an2ln_plugin(context, rule, aname, lnsize, lname); if (ret == 0 && lnsize && !lname[0]) continue; /* Success but no lname?! lies! */ else if (ret != KRB5_PLUGIN_NO_HANDLE) break; } if (ret == KRB5_PLUGIN_NO_HANDLE) { if (lnsize) lname[0] = '\0'; ret = KRB5_NO_LOCALNAME; } krb5_config_free_strings(rules); return ret; } static krb5_error_code KRB5_LIB_CALL an2ln_def_plug_init(krb5_context context, void **ctx) { *ctx = NULL; return 0; } static void KRB5_LIB_CALL an2ln_def_plug_fini(void *ctx) { } static heim_base_once_t sorted_text_db_init_once = HEIM_BASE_ONCE_INIT; static void sorted_text_db_init_f(void *arg) { (void) heim_db_register("sorted-text", NULL, &heim_sorted_text_file_dbtype); } static krb5_error_code KRB5_LIB_CALL an2ln_def_plug_an2ln(void *plug_ctx, krb5_context context, const char *rule, krb5_const_principal aname, set_result_f set_res_f, void *set_res_ctx) { krb5_error_code ret; const char *an2ln_db_fname; heim_db_t dbh = NULL; heim_dict_t db_options; heim_data_t k, v; heim_error_t error; char *unparsed = NULL; char *value = NULL; _krb5_load_db_plugins(context); heim_base_once_f(&sorted_text_db_init_once, NULL, sorted_text_db_init_f); if (strncmp(rule, "DB:", strlen("DB:")) != 0) return KRB5_PLUGIN_NO_HANDLE; an2ln_db_fname = &rule[strlen("DB:")]; if (!*an2ln_db_fname) return KRB5_PLUGIN_NO_HANDLE; ret = krb5_unparse_name(context, aname, &unparsed); if (ret) return ret; db_options = heim_dict_create(11); if (db_options != NULL) heim_dict_set_value(db_options, HSTR("read-only"), heim_number_create(1)); dbh = heim_db_create(NULL, an2ln_db_fname, db_options, &error); if (dbh == NULL) { krb5_set_error_message(context, heim_error_get_code(error), N_("Couldn't open aname2lname-text-db", "")); ret = KRB5_PLUGIN_NO_HANDLE; goto cleanup; } /* Binary search; file should be sorted (in C locale) */ k = heim_data_ref_create(unparsed, strlen(unparsed), NULL); if (k == NULL) { ret = krb5_enomem(context); goto cleanup; } v = heim_db_copy_value(dbh, NULL, k, &error); heim_release(k); if (v == NULL && error != NULL) { krb5_set_error_message(context, heim_error_get_code(error), N_("Lookup in aname2lname-text-db failed", "")); ret = heim_error_get_code(error); goto cleanup; } else if (v == NULL) { ret = KRB5_PLUGIN_NO_HANDLE; goto cleanup; } else { /* found */ if (heim_data_get_length(v) == 0) { krb5_set_error_message(context, ret, N_("Principal mapped to empty username", "")); ret = KRB5_NO_LOCALNAME; goto cleanup; } value = strndup(heim_data_get_ptr(v), heim_data_get_length(v)); heim_release(v); if (value == NULL) { ret = krb5_enomem(context); goto cleanup; } ret = set_res_f(set_res_ctx, value); } cleanup: heim_release(dbh); free(unparsed); free(value); return ret; } heimdal-7.5.0/lib/krb5/krb5_principal.cat30000644000175000017500000004653213212450757016363 0ustar niknik KRB5_PRINCIPAL(3) BSD Library Functions Manual KRB5_PRINCIPAL(3) NNAAMMEE kkrrbb55__ggeett__ddeeffaauulltt__pprriinncciippaall, kkrrbb55__pprriinncciippaall, kkrrbb55__bbuuiilldd__pprriinncciippaall, kkrrbb55__bbuuiilldd__pprriinncciippaall__eexxtt, kkrrbb55__bbuuiilldd__pprriinncciippaall__vvaa, kkrrbb55__bbuuiilldd__pprriinncciippaall__vvaa__eexxtt, kkrrbb55__ccooppyy__pprriinncciippaall, kkrrbb55__ffrreeee__pprriinncciippaall, kkrrbb55__mmaakkee__pprriinncciippaall, kkrrbb55__ppaarrssee__nnaammee, kkrrbb55__ppaarrssee__nnaammee__ffllaaggss, kkrrbb55__ppaarrssee__nnaammeettyyppee, kkrrbb55__pprriinncc__sseett__rreeaallmm, kkrrbb55__pprriinncciippaall__ccoommppaarree, kkrrbb55__pprriinncciippaall__ccoommppaarree__aannyy__rreeaallmm, kkrrbb55__pprriinncciippaall__ggeett__ccoommpp__ssttrriinngg, kkrrbb55__pprriinncciippaall__ggeett__rreeaallmm, kkrrbb55__pprriinncciippaall__ggeett__ttyyppee, kkrrbb55__pprriinncciippaall__mmaattcchh, kkrrbb55__pprriinncciippaall__sseett__ttyyppee, kkrrbb55__rreeaallmm__ccoommppaarree, kkrrbb55__ssnnaammee__ttoo__pprriinncciippaall, kkrrbb55__ssoocckk__ttoo__pprriinncciippaall, kkrrbb55__uunnppaarrssee__nnaammee, kkrrbb55__uunnppaarrssee__nnaammee__ffllaaggss, kkrrbb55__uunnppaarrssee__nnaammee__ffiixxeedd, kkrrbb55__uunnppaarrssee__nnaammee__ffiixxeedd__ffllaaggss, kkrrbb55__uunnppaarrssee__nnaammee__ffiixxeedd__sshhoorrtt, kkrrbb55__uunnppaarrssee__nnaammee__sshhoorrtt -- Kerberos 5 principal handling functions LLIIBBRRAARRYY Kerberos 5 Library (libkrb5, -lkrb5) SSYYNNOOPPSSIISS ##iinncclluuddee <> krb5_principal; _v_o_i_d kkrrbb55__ffrreeee__pprriinncciippaall(_k_r_b_5___c_o_n_t_e_x_t _c_o_n_t_e_x_t, _k_r_b_5___p_r_i_n_c_i_p_a_l _p_r_i_n_c_i_p_a_l); _k_r_b_5___e_r_r_o_r___c_o_d_e kkrrbb55__ppaarrssee__nnaammee(_k_r_b_5___c_o_n_t_e_x_t _c_o_n_t_e_x_t, _c_o_n_s_t _c_h_a_r _*_n_a_m_e, _k_r_b_5___p_r_i_n_c_i_p_a_l _*_p_r_i_n_c_i_p_a_l); _k_r_b_5___e_r_r_o_r___c_o_d_e kkrrbb55__ppaarrssee__nnaammee__ffllaaggss(_k_r_b_5___c_o_n_t_e_x_t _c_o_n_t_e_x_t, _c_o_n_s_t _c_h_a_r _*_n_a_m_e, _i_n_t _f_l_a_g_s, _k_r_b_5___p_r_i_n_c_i_p_a_l _*_p_r_i_n_c_i_p_a_l); _k_r_b_5___e_r_r_o_r___c_o_d_e kkrrbb55__uunnppaarrssee__nnaammee(_k_r_b_5___c_o_n_t_e_x_t _c_o_n_t_e_x_t, _k_r_b_5___c_o_n_s_t___p_r_i_n_c_i_p_a_l _p_r_i_n_c_i_p_a_l, _c_h_a_r _*_*_n_a_m_e); _k_r_b_5___e_r_r_o_r___c_o_d_e kkrrbb55__uunnppaarrssee__nnaammee__ffllaaggss(_k_r_b_5___c_o_n_t_e_x_t _c_o_n_t_e_x_t, _k_r_b_5___c_o_n_s_t___p_r_i_n_c_i_p_a_l _p_r_i_n_c_i_p_a_l, _i_n_t _f_l_a_g_s, _c_h_a_r _*_*_n_a_m_e); _k_r_b_5___e_r_r_o_r___c_o_d_e kkrrbb55__uunnppaarrssee__nnaammee__ffiixxeedd(_k_r_b_5___c_o_n_t_e_x_t _c_o_n_t_e_x_t, _k_r_b_5___c_o_n_s_t___p_r_i_n_c_i_p_a_l _p_r_i_n_c_i_p_a_l, _c_h_a_r _*_n_a_m_e, _s_i_z_e___t _l_e_n); _k_r_b_5___e_r_r_o_r___c_o_d_e kkrrbb55__uunnppaarrssee__nnaammee__ffiixxeedd__ffllaaggss(_k_r_b_5___c_o_n_t_e_x_t _c_o_n_t_e_x_t, _k_r_b_5___c_o_n_s_t___p_r_i_n_c_i_p_a_l _p_r_i_n_c_i_p_a_l, _i_n_t _f_l_a_g_s, _c_h_a_r _*_n_a_m_e, _s_i_z_e___t _l_e_n); _k_r_b_5___e_r_r_o_r___c_o_d_e kkrrbb55__uunnppaarrssee__nnaammee__sshhoorrtt(_k_r_b_5___c_o_n_t_e_x_t _c_o_n_t_e_x_t, _k_r_b_5___c_o_n_s_t___p_r_i_n_c_i_p_a_l _p_r_i_n_c_i_p_a_l, _c_h_a_r _*_*_n_a_m_e); _k_r_b_5___e_r_r_o_r___c_o_d_e kkrrbb55__uunnppaarrssee__nnaammee__ffiixxeedd__sshhoorrtt(_k_r_b_5___c_o_n_t_e_x_t _c_o_n_t_e_x_t, _k_r_b_5___c_o_n_s_t___p_r_i_n_c_i_p_a_l _p_r_i_n_c_i_p_a_l, _c_h_a_r _*_n_a_m_e, _s_i_z_e___t _l_e_n); _v_o_i_d kkrrbb55__pprriinncc__sseett__rreeaallmm(_k_r_b_5___c_o_n_t_e_x_t _c_o_n_t_e_x_t, _k_r_b_5___p_r_i_n_c_i_p_a_l _p_r_i_n_c_i_p_a_l, _k_r_b_5___r_e_a_l_m _*_r_e_a_l_m); _k_r_b_5___e_r_r_o_r___c_o_d_e kkrrbb55__bbuuiilldd__pprriinncciippaall(_k_r_b_5___c_o_n_t_e_x_t _c_o_n_t_e_x_t, _k_r_b_5___p_r_i_n_c_i_p_a_l _*_p_r_i_n_c_i_p_a_l, _i_n_t _r_l_e_n, _k_r_b_5___c_o_n_s_t___r_e_a_l_m _r_e_a_l_m, _._._.); _k_r_b_5___e_r_r_o_r___c_o_d_e kkrrbb55__bbuuiilldd__pprriinncciippaall__vvaa(_k_r_b_5___c_o_n_t_e_x_t _c_o_n_t_e_x_t, _k_r_b_5___p_r_i_n_c_i_p_a_l _*_p_r_i_n_c_i_p_a_l, _i_n_t _r_l_e_n, _k_r_b_5___c_o_n_s_t___r_e_a_l_m _r_e_a_l_m, _v_a___l_i_s_t _a_p); _k_r_b_5___e_r_r_o_r___c_o_d_e kkrrbb55__bbuuiilldd__pprriinncciippaall__eexxtt(_k_r_b_5___c_o_n_t_e_x_t _c_o_n_t_e_x_t, _k_r_b_5___p_r_i_n_c_i_p_a_l _*_p_r_i_n_c_i_p_a_l, _i_n_t _r_l_e_n, _k_r_b_5___c_o_n_s_t___r_e_a_l_m _r_e_a_l_m, _._._.); _k_r_b_5___e_r_r_o_r___c_o_d_e kkrrbb55__bbuuiilldd__pprriinncciippaall__vvaa__eexxtt(_k_r_b_5___c_o_n_t_e_x_t _c_o_n_t_e_x_t, _k_r_b_5___p_r_i_n_c_i_p_a_l _*_p_r_i_n_c_i_p_a_l, _i_n_t _r_l_e_n, _k_r_b_5___c_o_n_s_t___r_e_a_l_m _r_e_a_l_m, _v_a___l_i_s_t _a_p); _k_r_b_5___e_r_r_o_r___c_o_d_e kkrrbb55__mmaakkee__pprriinncciippaall(_k_r_b_5___c_o_n_t_e_x_t _c_o_n_t_e_x_t, _k_r_b_5___p_r_i_n_c_i_p_a_l _*_p_r_i_n_c_i_p_a_l, _k_r_b_5___c_o_n_s_t___r_e_a_l_m _r_e_a_l_m, _._._.); _k_r_b_5___e_r_r_o_r___c_o_d_e kkrrbb55__ccooppyy__pprriinncciippaall(_k_r_b_5___c_o_n_t_e_x_t _c_o_n_t_e_x_t, _k_r_b_5___c_o_n_s_t___p_r_i_n_c_i_p_a_l _i_n_p_r_i_n_c, _k_r_b_5___p_r_i_n_c_i_p_a_l _*_o_u_t_p_r_i_n_c); _k_r_b_5___b_o_o_l_e_a_n kkrrbb55__pprriinncciippaall__ccoommppaarree(_k_r_b_5___c_o_n_t_e_x_t _c_o_n_t_e_x_t, _k_r_b_5___c_o_n_s_t___p_r_i_n_c_i_p_a_l _p_r_i_n_c_1, _k_r_b_5___c_o_n_s_t___p_r_i_n_c_i_p_a_l _p_r_i_n_c_2); _k_r_b_5___b_o_o_l_e_a_n kkrrbb55__pprriinncciippaall__ccoommppaarree__aannyy__rreeaallmm(_k_r_b_5___c_o_n_t_e_x_t _c_o_n_t_e_x_t, _k_r_b_5___c_o_n_s_t___p_r_i_n_c_i_p_a_l _p_r_i_n_c_1, _k_r_b_5___c_o_n_s_t___p_r_i_n_c_i_p_a_l _p_r_i_n_c_2); _c_o_n_s_t _c_h_a_r _* kkrrbb55__pprriinncciippaall__ggeett__ccoommpp__ssttrriinngg(_k_r_b_5___c_o_n_t_e_x_t _c_o_n_t_e_x_t, _k_r_b_5___c_o_n_s_t___p_r_i_n_c_i_p_a_l _p_r_i_n_c_i_p_a_l, _u_n_s_i_g_n_e_d _i_n_t _c_o_m_p_o_n_e_n_t); _c_o_n_s_t _c_h_a_r _* kkrrbb55__pprriinncciippaall__ggeett__rreeaallmm(_k_r_b_5___c_o_n_t_e_x_t _c_o_n_t_e_x_t, _k_r_b_5___c_o_n_s_t___p_r_i_n_c_i_p_a_l _p_r_i_n_c_i_p_a_l); _i_n_t kkrrbb55__pprriinncciippaall__ggeett__ttyyppee(_k_r_b_5___c_o_n_t_e_x_t _c_o_n_t_e_x_t, _k_r_b_5___c_o_n_s_t___p_r_i_n_c_i_p_a_l _p_r_i_n_c_i_p_a_l); _k_r_b_5___b_o_o_l_e_a_n kkrrbb55__pprriinncciippaall__mmaattcchh(_k_r_b_5___c_o_n_t_e_x_t _c_o_n_t_e_x_t, _k_r_b_5___c_o_n_s_t___p_r_i_n_c_i_p_a_l _p_r_i_n_c_i_p_a_l, _k_r_b_5___c_o_n_s_t___p_r_i_n_c_i_p_a_l _p_a_t_t_e_r_n); _v_o_i_d kkrrbb55__pprriinncciippaall__sseett__ttyyppee(_k_r_b_5___c_o_n_t_e_x_t _c_o_n_t_e_x_t, _k_r_b_5___p_r_i_n_c_i_p_a_l _p_r_i_n_c_i_p_a_l, _i_n_t _t_y_p_e); _k_r_b_5___b_o_o_l_e_a_n kkrrbb55__rreeaallmm__ccoommppaarree(_k_r_b_5___c_o_n_t_e_x_t _c_o_n_t_e_x_t, _k_r_b_5___c_o_n_s_t___p_r_i_n_c_i_p_a_l _p_r_i_n_c_1, _k_r_b_5___c_o_n_s_t___p_r_i_n_c_i_p_a_l _p_r_i_n_c_2); _k_r_b_5___e_r_r_o_r___c_o_d_e kkrrbb55__ssnnaammee__ttoo__pprriinncciippaall(_k_r_b_5___c_o_n_t_e_x_t _c_o_n_t_e_x_t, _c_o_n_s_t _c_h_a_r _*_h_o_s_t_n_a_m_e, _c_o_n_s_t _c_h_a_r _*_s_n_a_m_e, _i_n_t_3_2___t _t_y_p_e, _k_r_b_5___p_r_i_n_c_i_p_a_l _*_r_e_t___p_r_i_n_c); _k_r_b_5___e_r_r_o_r___c_o_d_e kkrrbb55__ssoocckk__ttoo__pprriinncciippaall(_k_r_b_5___c_o_n_t_e_x_t _c_o_n_t_e_x_t, _i_n_t _s_o_c_k_e_t, _c_o_n_s_t _c_h_a_r _*_s_n_a_m_e, _i_n_t_3_2___t _t_y_p_e, _k_r_b_5___p_r_i_n_c_i_p_a_l _*_p_r_i_n_c_i_p_a_l); _k_r_b_5___e_r_r_o_r___c_o_d_e kkrrbb55__ggeett__ddeeffaauulltt__pprriinncciippaall(_k_r_b_5___c_o_n_t_e_x_t _c_o_n_t_e_x_t, _k_r_b_5___p_r_i_n_c_i_p_a_l _*_p_r_i_n_c); _k_r_b_5___e_r_r_o_r___c_o_d_e kkrrbb55__ppaarrssee__nnaammeettyyppee(_k_r_b_5___c_o_n_t_e_x_t _c_o_n_t_e_x_t, _c_o_n_s_t _c_h_a_r _*_s_t_r, _i_n_t_3_2___t _*_t_y_p_e); DDEESSCCRRIIPPTTIIOONN krb5_principal holds the name of a user or service in Kerberos. A principal has two parts, a PrincipalName and a realm. The Principal- Name consists of one or more components. In printed form, the components are separated by /. The PrincipalName also has a name-type. Examples of a principal are nisse/root@EXAMPLE.COM and host/datan.kth.se@KTH.SE. kkrrbb55__ppaarrssee__nnaammee() and kkrrbb55__ppaarrssee__nnaammee__ffllaaggss() passes a principal name in _n_a_m_e to the kerberos principal structure. kkrrbb55__ppaarrssee__nnaammee__ffllaaggss() takes an extra _f_l_a_g_s argument the following flags can be passed in KRB5_PRINCIPAL_PARSE_NO_REALM requires the input string to be without a realm, and no realm is stored in the _p_r_i_n_c_i_p_a_l return argument. KRB5_PRINCIPAL_PARSE_REQUIRE_REALM requires the input string to with a realm. kkrrbb55__uunnppaarrssee__nnaammee() and kkrrbb55__uunnppaarrssee__nnaammee__ffllaaggss() prints the principal _p_r_i_n_c to the string _n_a_m_e. _n_a_m_e should be freed with free(3). To the _f_l_a_g_s argument the following flags can be passed in KRB5_PRINCIPAL_UNPARSE_SHORT no realm if the realm is one of the local realms. KRB5_PRINCIPAL_UNPARSE_NO_REALM never include any realm in the principal name. KRB5_PRINCIPAL_UNPARSE_DISPLAY don't quote On failure _n_a_m_e is set to NULL. kkrrbb55__uunnppaarrssee__nnaammee__ffiixxeedd() and kkrrbb55__uunnppaarrssee__nnaammee__ffiixxeedd__ffllaaggss() behaves just like kkrrbb55__uunnppaarrssee(), but instead unparses the principal into a fixed size buffer. kkrrbb55__uunnppaarrssee__nnaammee__sshhoorrtt() just returns the principal without the realm if the principal is in the default realm. If the principal isn't, the full name is returned. kkrrbb55__uunnppaarrssee__nnaammee__ffiixxeedd__sshhoorrtt() works just like kkrrbb55__uunnppaarrssee__nnaammee__sshhoorrtt() but on a fixed size buffer. kkrrbb55__bbuuiilldd__pprriinncciippaall() builds a principal from the realm _r_e_a_l_m that has the length _r_l_e_n. The following arguments form the components of the principal. The list of components is terminated with NULL. kkrrbb55__bbuuiilldd__pprriinncciippaall__vvaa() works like kkrrbb55__bbuuiilldd__pprriinncciippaall() using vargs. kkrrbb55__bbuuiilldd__pprriinncciippaall__eexxtt() and kkrrbb55__bbuuiilldd__pprriinncciippaall__vvaa__eexxtt() take a list of length-value pairs, the list is terminated with a zero length. kkrrbb55__mmaakkee__pprriinncciippaall() works the same way as kkrrbb55__bbuuiilldd__pprriinncciippaall(), except it figures out the length of the realm itself. kkrrbb55__ccooppyy__pprriinncciippaall() makes a copy of a principal. The copy needs to be freed with kkrrbb55__ffrreeee__pprriinncciippaall(). kkrrbb55__pprriinncciippaall__ccoommppaarree() compares the two principals, including realm of the principals and returns TRUE if they are the same and FALSE if not. kkrrbb55__pprriinncciippaall__ccoommppaarree__aannyy__rreeaallmm() works the same way as kkrrbb55__pprriinncciippaall__ccoommppaarree() but doesn't compare the realm component of the principal. kkrrbb55__rreeaallmm__ccoommppaarree() compares the realms of the two principals and returns TRUE is they are the same, and FALSE if not. kkrrbb55__pprriinncciippaall__mmaattcchh() matches a _p_r_i_n_c_i_p_a_l against a _p_a_t_t_e_r_n. The pat- tern is a globbing expression, where each component (separated by /) is matched against the corresponding component of the principal. The kkrrbb55__pprriinncciippaall__ggeett__rreeaallmm() and kkrrbb55__pprriinncciippaall__ggeett__ccoommpp__ssttrriinngg() func- tions return parts of the _p_r_i_n_c_i_p_a_l, either the realm or a specific com- ponent. Both functions return string pointers to data inside the princi- pal, so they are valid only as long as the principal exists. The _c_o_m_p_o_n_e_n_t argument to kkrrbb55__pprriinncciippaall__ggeett__ccoommpp__ssttrriinngg() is the index of the component to return, from zero to the total number of components minus one. If the index is out of range NULL is returned. kkrrbb55__pprriinncciippaall__ggeett__rreeaallmm() and kkrrbb55__pprriinncciippaall__ggeett__ccoommpp__ssttrriinngg() are replacements for kkrrbb55__pprriinncc__ccoommppoonneenntt() and related macros, described as internal in the MIT API specification. Unlike the macros, these func- tions return strings, not krb5_data. A reason to return krb5_data was that it was believed that principal components could contain binary data, but this belief was unfounded, and it has been decided that principal components are infact UTF8, so it's safe to use zero terminated strings. It's generally not necessary to look at the components of a principal. kkrrbb55__pprriinncciippaall__ggeett__ttyyppee() and kkrrbb55__pprriinncciippaall__sseett__ttyyppee() get and sets the name type for a principal. Name type handling is tricky and not often needed, don't use this unless you know what you do. kkrrbb55__ssnnaammee__ttoo__pprriinncciippaall() and kkrrbb55__ssoocckk__ttoo__pprriinncciippaall() are for easy cre- ation of ``service'' principals that can, for instance, be used to lookup a key in a keytab. For both functions the _s_n_a_m_e parameter will be used for the first component of the created principal. If _s_n_a_m_e is NULL, ``host'' will be used instead. kkrrbb55__ssnnaammee__ttoo__pprriinncciippaall() will use the passed _h_o_s_t_n_a_m_e for the second component. If _t_y_p_e is KRB5_NT_SRV_HST this name will be looked up with ggeetthhoossttbbyynnaammee(). If _h_o_s_t_n_a_m_e is NULL, the local hostname will be used. kkrrbb55__ssoocckk__ttoo__pprriinncciippaall() will use the ``sockname'' of the passed _s_o_c_k_e_t, which should be a bound AF_INET or AF_INET6 socket. There must be a map- ping between the address and ``sockname''. The function may try to resolve the name in DNS. kkrrbb55__ggeett__ddeeffaauulltt__pprriinncciippaall() tries to find out what's a reasonable default principal by looking at the environment it is running in. kkrrbb55__ppaarrssee__nnaammeettyyppee() parses and returns the name type integer value in _t_y_p_e. On failure the function returns an error code and set the error string. SSEEEE AALLSSOO krb5_config(3), krb5.conf(5) BBUUGGSS You can not have a NUL in a component in some of the variable argument functions above. Until someone can give a good example of where it would be a good idea to have NUL's in a component, this will not be fixed. HEIMDAL May 1, 2006 HEIMDAL heimdal-7.5.0/lib/krb5/krb5_rd_safe.cat30000644000175000017500000000407113212450757015775 0ustar niknik KRB5_RD_SAFE(3) BSD Library Functions Manual KRB5_RD_SAFE(3) NNAAMMEE kkrrbb55__rrdd__ssaaffee, kkrrbb55__rrdd__pprriivv -- verifies authenticity of messages LLIIBBRRAARRYY Kerberos 5 Library (libkrb5, -lkrb5) SSYYNNOOPPSSIISS ##iinncclluuddee <> _k_r_b_5___e_r_r_o_r___c_o_d_e kkrrbb55__rrdd__pprriivv(_k_r_b_5___c_o_n_t_e_x_t _c_o_n_t_e_x_t, _k_r_b_5___a_u_t_h___c_o_n_t_e_x_t _a_u_t_h___c_o_n_t_e_x_t, _c_o_n_s_t _k_r_b_5___d_a_t_a _*_i_n_b_u_f, _k_r_b_5___d_a_t_a _*_o_u_t_b_u_f, _k_r_b_5___r_e_p_l_a_y___d_a_t_a _*_o_u_t_d_a_t_a); _k_r_b_5___e_r_r_o_r___c_o_d_e kkrrbb55__rrdd__ssaaffee(_k_r_b_5___c_o_n_t_e_x_t _c_o_n_t_e_x_t, _k_r_b_5___a_u_t_h___c_o_n_t_e_x_t _a_u_t_h___c_o_n_t_e_x_t, _c_o_n_s_t _k_r_b_5___d_a_t_a _*_i_n_b_u_f, _k_r_b_5___d_a_t_a _*_o_u_t_b_u_f, _k_r_b_5___r_e_p_l_a_y___d_a_t_a _*_o_u_t_d_a_t_a); DDEESSCCRRIIPPTTIIOONN kkrrbb55__rrdd__ssaaffee() and kkrrbb55__rrdd__pprriivv() parses KRB-SAFE and KRB-PRIV messages (as generated by krb5_mk_safe(3) and krb5_mk_priv(3)) from _i_n_b_u_f and ver- ifies its integrity. The user data part of the message in put in _o_u_t_b_u_f. The encryption state, including keyblocks and addresses, is taken from _a_u_t_h___c_o_n_t_e_x_t. If the KRB5_AUTH_CONTEXT_RET_SEQUENCE or KRB5_AUTH_CONTEXT_RET_TIME flags are set in the _a_u_t_h___c_o_n_t_e_x_t the sequence number and time are returned in the _o_u_t_d_a_t_a parameter. SSEEEE AALLSSOO krb5_auth_con_init(3), krb5_mk_priv(3), krb5_mk_safe(3) HEIMDAL May 1, 2006 HEIMDAL heimdal-7.5.0/lib/krb5/an2ln_plugin.h0000644000175000017500000000744013026237312015430 0ustar niknik/* * Copyright (c) 2006 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ /* $Id$ */ #ifndef HEIMDAL_KRB5_AN2LN_PLUGIN_H #define HEIMDAL_KRB5_AN2LN_PLUGIN_H 1 #define KRB5_PLUGIN_AN2LN "an2ln" #define KRB5_PLUGIN_AN2LN_VERSION_0 0 typedef krb5_error_code (KRB5_LIB_CALL *set_result_f)(void *, const char *); /** @struct krb5plugin_an2ln_ftable_desc * * @brief Description of the krb5_aname_to_lname(3) plugin facility. * * The krb5_aname_to_lname(3) function is pluggable. The plugin is * named KRB5_PLUGIN_AN2LN ("an2ln"), with a single minor version, * KRB5_PLUGIN_AN2LN_VERSION_0 (0). * * The plugin for krb5_aname_to_lname(3) consists of a data symbol * referencing a structure of type krb5plugin_an2ln_ftable, with four * fields: * * @param init Plugin initialization function (see krb5-plugin(7)) * * @param minor_version The plugin minor version number (0) * * @param fini Plugin finalization function * * @param an2ln Plugin aname_to_lname function * * The an2ln field is the plugin entry point that performs the * traditional aname_to_lname operation however the plugin desires. It * is invoked in no particular order relative to other an2ln plugins, * but it has a 'rule' argument that indicates which plugin is intended * to act on the rule. The plugin an2ln function must return * KRB5_PLUGIN_NO_HANDLE if the rule is not applicable to it. * * The plugin an2ln function has the following arguments, in this order: * * -# plug_ctx, the context value output by the plugin's init function * -# context, a krb5_context * -# rule, the aname_to_lname rule being evaluated (from krb5.conf(5)) * -# aname, the krb5_principal to be mapped to an lname * -# set_res_f, a function the plugin must call to set its result * -# set_res_ctx, the first argument to set_res_f (the second is the result lname string) * * @ingroup krb5_support */ typedef struct krb5plugin_an2ln_ftable_desc { int minor_version; krb5_error_code (KRB5_LIB_CALL *init)(krb5_context, void **); void (KRB5_LIB_CALL *fini)(void *); krb5_error_code (KRB5_LIB_CALL *an2ln)(void *, krb5_context, const char *, krb5_const_principal, set_result_f, void *); } krb5plugin_an2ln_ftable; #endif /* HEIMDAL_KRB5_AN2LN_PLUGIN_H */ heimdal-7.5.0/lib/krb5/krb5_rd_safe.30000644000175000017500000000542312136107750015303 0ustar niknik.\" Copyright (c) 2003 Kungliga Tekniska Högskolan .\" (Royal Institute of Technology, Stockholm, Sweden). .\" All rights reserved. .\" .\" Redistribution and use in source and binary forms, with or without .\" modification, are permitted provided that the following conditions .\" are met: .\" .\" 1. Redistributions of source code must retain the above copyright .\" notice, this list of conditions and the following disclaimer. .\" .\" 2. Redistributions in binary form must reproduce the above copyright .\" notice, this list of conditions and the following disclaimer in the .\" documentation and/or other materials provided with the distribution. .\" .\" 3. Neither the name of the Institute nor the names of its contributors .\" may be used to endorse or promote products derived from this software .\" without specific prior written permission. .\" .\" THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND .\" ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE .\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE .\" ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE .\" FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL .\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS .\" OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) .\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT .\" LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF .\" SUCH DAMAGE. .\" .\" $Id$ .\" .Dd May 1, 2006 .Dt KRB5_RD_SAFE 3 .Os HEIMDAL .Sh NAME .Nm krb5_rd_safe , .Nm krb5_rd_priv .Nd verifies authenticity of messages .Sh LIBRARY Kerberos 5 Library (libkrb5, -lkrb5) .Sh SYNOPSIS .In krb5.h .Pp .Ft krb5_error_code .Fn krb5_rd_priv "krb5_context context" "krb5_auth_context auth_context" "const krb5_data *inbuf" "krb5_data *outbuf" "krb5_replay_data *outdata" .Ft krb5_error_code .Fn krb5_rd_safe "krb5_context context" "krb5_auth_context auth_context" "const krb5_data *inbuf" "krb5_data *outbuf" "krb5_replay_data *outdata" .Sh DESCRIPTION .Fn krb5_rd_safe and .Fn krb5_rd_priv parses .Li KRB-SAFE and .Li KRB-PRIV messages (as generated by .Xr krb5_mk_safe 3 and .Xr krb5_mk_priv 3 ) from .Fa inbuf and verifies its integrity. The user data part of the message in put in .Fa outbuf . The encryption state, including keyblocks and addresses, is taken from .Fa auth_context . If the .Dv KRB5_AUTH_CONTEXT_RET_SEQUENCE or .Dv KRB5_AUTH_CONTEXT_RET_TIME flags are set in the .Fa auth_context the sequence number and time are returned in the .Fa outdata parameter. .Sh SEE ALSO .Xr krb5_auth_con_init 3 , .Xr krb5_mk_priv 3 , .Xr krb5_mk_safe 3 heimdal-7.5.0/lib/krb5/salt.c0000644000175000017500000002141713026237312013776 0ustar niknik/* * Copyright (c) 1997 - 2008 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "krb5_locl.h" /* coverity[+alloc : arg-*3] */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_salttype_to_string (krb5_context context, krb5_enctype etype, krb5_salttype stype, char **string) { struct _krb5_encryption_type *e; struct salt_type *st; *string = NULL; e = _krb5_find_enctype (etype); if (e == NULL) { krb5_set_error_message(context, KRB5_PROG_ETYPE_NOSUPP, "encryption type %d not supported", etype); return KRB5_PROG_ETYPE_NOSUPP; } for (st = e->keytype->string_to_key; st && st->type; st++) { if (st->type == stype) { *string = strdup (st->name); if (*string == NULL) return krb5_enomem(context); return 0; } } krb5_set_error_message (context, HEIM_ERR_SALTTYPE_NOSUPP, "salttype %d not supported", stype); return HEIM_ERR_SALTTYPE_NOSUPP; } KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_string_to_salttype (krb5_context context, krb5_enctype etype, const char *string, krb5_salttype *salttype) { struct _krb5_encryption_type *e; struct salt_type *st; e = _krb5_find_enctype (etype); if (e == NULL) { krb5_set_error_message(context, KRB5_PROG_ETYPE_NOSUPP, N_("encryption type %d not supported", ""), etype); return KRB5_PROG_ETYPE_NOSUPP; } for (st = e->keytype->string_to_key; st && st->type; st++) { if (strcasecmp (st->name, string) == 0) { *salttype = st->type; return 0; } } krb5_set_error_message(context, HEIM_ERR_SALTTYPE_NOSUPP, N_("salttype %s not supported", ""), string); return HEIM_ERR_SALTTYPE_NOSUPP; } KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_get_pw_salt(krb5_context context, krb5_const_principal principal, krb5_salt *salt) { size_t len; size_t i; krb5_error_code ret; char *p; salt->salttype = KRB5_PW_SALT; len = strlen(principal->realm); for (i = 0; i < principal->name.name_string.len; ++i) len += strlen(principal->name.name_string.val[i]); ret = krb5_data_alloc (&salt->saltvalue, len); if (ret) return ret; p = salt->saltvalue.data; memcpy (p, principal->realm, strlen(principal->realm)); p += strlen(principal->realm); for (i = 0; i < principal->name.name_string.len; ++i) { memcpy (p, principal->name.name_string.val[i], strlen(principal->name.name_string.val[i])); p += strlen(principal->name.name_string.val[i]); } return 0; } KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_free_salt(krb5_context context, krb5_salt salt) { krb5_data_free(&salt.saltvalue); return 0; } KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_string_to_key_data (krb5_context context, krb5_enctype enctype, krb5_data password, krb5_principal principal, krb5_keyblock *key) { krb5_error_code ret; krb5_salt salt; ret = krb5_get_pw_salt(context, principal, &salt); if(ret) return ret; ret = krb5_string_to_key_data_salt(context, enctype, password, salt, key); krb5_free_salt(context, salt); return ret; } KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_string_to_key (krb5_context context, krb5_enctype enctype, const char *password, krb5_principal principal, krb5_keyblock *key) { krb5_data pw; pw.data = rk_UNCONST(password); pw.length = strlen(password); return krb5_string_to_key_data(context, enctype, pw, principal, key); } KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_string_to_key_data_salt (krb5_context context, krb5_enctype enctype, krb5_data password, krb5_salt salt, krb5_keyblock *key) { krb5_data opaque; krb5_data_zero(&opaque); return krb5_string_to_key_data_salt_opaque(context, enctype, password, salt, opaque, key); } /* * Do a string -> key for encryption type `enctype' operation on * `password' (with salt `salt' and the enctype specific data string * `opaque'), returning the resulting key in `key' */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_string_to_key_data_salt_opaque (krb5_context context, krb5_enctype enctype, krb5_data password, krb5_salt salt, krb5_data opaque, krb5_keyblock *key) { struct _krb5_encryption_type *et =_krb5_find_enctype(enctype); struct salt_type *st; if(et == NULL) { krb5_set_error_message(context, KRB5_PROG_ETYPE_NOSUPP, N_("encryption type %d not supported", ""), enctype); return KRB5_PROG_ETYPE_NOSUPP; } for(st = et->keytype->string_to_key; st && st->type; st++) if(st->type == salt.salttype) return (*st->string_to_key)(context, enctype, password, salt, opaque, key); krb5_set_error_message(context, HEIM_ERR_SALTTYPE_NOSUPP, N_("salt type %d not supported", ""), salt.salttype); return HEIM_ERR_SALTTYPE_NOSUPP; } /* * Do a string -> key for encryption type `enctype' operation on the * string `password' (with salt `salt'), returning the resulting key * in `key' */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_string_to_key_salt (krb5_context context, krb5_enctype enctype, const char *password, krb5_salt salt, krb5_keyblock *key) { krb5_data pw; pw.data = rk_UNCONST(password); pw.length = strlen(password); return krb5_string_to_key_data_salt(context, enctype, pw, salt, key); } KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_string_to_key_salt_opaque (krb5_context context, krb5_enctype enctype, const char *password, krb5_salt salt, krb5_data opaque, krb5_keyblock *key) { krb5_data pw; pw.data = rk_UNCONST(password); pw.length = strlen(password); return krb5_string_to_key_data_salt_opaque(context, enctype, pw, salt, opaque, key); } KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_string_to_key_derived(krb5_context context, const void *str, size_t len, krb5_enctype etype, krb5_keyblock *key) { struct _krb5_encryption_type *et = _krb5_find_enctype(etype); krb5_error_code ret; struct _krb5_key_data kd; size_t keylen; u_char *tmp; if(et == NULL) { krb5_set_error_message (context, KRB5_PROG_ETYPE_NOSUPP, N_("encryption type %d not supported", ""), etype); return KRB5_PROG_ETYPE_NOSUPP; } keylen = et->keytype->bits / 8; ALLOC(kd.key, 1); if (kd.key == NULL) return krb5_enomem(context); ret = krb5_data_alloc(&kd.key->keyvalue, et->keytype->size); if(ret) { free(kd.key); return ret; } kd.key->keytype = etype; tmp = malloc (keylen); if(tmp == NULL) { krb5_free_keyblock(context, kd.key); return krb5_enomem(context); } ret = _krb5_n_fold(str, len, tmp, keylen); if (ret) { free(tmp); krb5_enomem(context); return ret; } kd.schedule = NULL; _krb5_DES3_random_to_key(context, kd.key, tmp, keylen); memset(tmp, 0, keylen); free(tmp); ret = _krb5_derive_key(context, et, &kd, "kerberos", /* XXX well known constant */ strlen("kerberos")); if (ret) { _krb5_free_key_data(context, &kd, et); return ret; } ret = krb5_copy_keyblock_contents(context, kd.key, key); _krb5_free_key_data(context, &kd, et); return ret; } heimdal-7.5.0/lib/krb5/test_crypto.c0000644000175000017500000001343213026237312015410 0ustar niknik/* * Copyright (c) 2003-2005 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of KTH nor the names of its contributors may be * used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY KTH AND ITS CONTRIBUTORS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL KTH OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "krb5_locl.h" #include #include static void time_encryption(krb5_context context, size_t size, krb5_enctype etype, int iterations) { struct timeval tv1, tv2; krb5_error_code ret; krb5_keyblock key; krb5_crypto crypto; krb5_data data; char *etype_name; void *buf; int i; ret = krb5_generate_random_keyblock(context, etype, &key); if (ret) krb5_err(context, 1, ret, "krb5_generate_random_keyblock"); ret = krb5_enctype_to_string(context, etype, &etype_name); if (ret) krb5_err(context, 1, ret, "krb5_enctype_to_string"); buf = malloc(size); if (buf == NULL) krb5_errx(context, 1, "out of memory"); memset(buf, 0, size); ret = krb5_crypto_init(context, &key, 0, &crypto); if (ret) krb5_err(context, 1, ret, "krb5_crypto_init"); gettimeofday(&tv1, NULL); for (i = 0; i < iterations; i++) { ret = krb5_encrypt(context, crypto, 0, buf, size, &data); if (ret) krb5_err(context, 1, ret, "encrypt: %d", i); krb5_data_free(&data); } gettimeofday(&tv2, NULL); timevalsub(&tv2, &tv1); printf("%s size: %7lu iterations: %d time: %3ld.%06ld\n", etype_name, (unsigned long)size, iterations, (long)tv2.tv_sec, (long)tv2.tv_usec); free(buf); free(etype_name); krb5_crypto_destroy(context, crypto); krb5_free_keyblock_contents(context, &key); } static void time_s2k(krb5_context context, krb5_enctype etype, const char *password, krb5_salt salt, int iterations) { struct timeval tv1, tv2; krb5_error_code ret; krb5_keyblock key; krb5_data opaque; char *etype_name; int i; ret = krb5_enctype_to_string(context, etype, &etype_name); if (ret) krb5_err(context, 1, ret, "krb5_enctype_to_string"); opaque.data = NULL; opaque.length = 0; gettimeofday(&tv1, NULL); for (i = 0; i < iterations; i++) { ret = krb5_string_to_key_salt_opaque(context, etype, password, salt, opaque, &key); if (ret) krb5_err(context, 1, ret, "krb5_string_to_key_data_salt_opaque"); krb5_free_keyblock_contents(context, &key); } gettimeofday(&tv2, NULL); timevalsub(&tv2, &tv1); printf("%s string2key %d iterations time: %3ld.%06ld\n", etype_name, iterations, (long)tv2.tv_sec, (long)tv2.tv_usec); free(etype_name); } static int version_flag = 0; static int help_flag = 0; static struct getargs args[] = { {"version", 0, arg_flag, &version_flag, "print version", NULL }, {"help", 0, arg_flag, &help_flag, NULL, NULL } }; static void usage (int ret) { arg_printusage (args, sizeof(args)/sizeof(*args), NULL, ""); exit (ret); } int main(int argc, char **argv) { krb5_context context; krb5_error_code ret; int i, enciter, s2kiter; int optidx = 0; krb5_salt salt; krb5_enctype enctypes[] = { #if 0 ETYPE_DES_CBC_CRC, ETYPE_DES3_CBC_SHA1, ETYPE_ARCFOUR_HMAC_MD5, #endif ETYPE_AES128_CTS_HMAC_SHA1_96, ETYPE_AES256_CTS_HMAC_SHA1_96, ETYPE_AES128_CTS_HMAC_SHA256_128, ETYPE_AES256_CTS_HMAC_SHA384_192 }; setprogname(argv[0]); if(getarg(args, sizeof(args) / sizeof(args[0]), argc, argv, &optidx)) usage(1); if (help_flag) usage (0); if(version_flag){ print_version(NULL); exit(0); } salt.salttype = KRB5_PW_SALT; salt.saltvalue.data = NULL; salt.saltvalue.length = 0; ret = krb5_init_context(&context); if (ret) errx (1, "krb5_init_context failed: %d", ret); enciter = 1000; s2kiter = 100; for (i = 0; i < sizeof(enctypes)/sizeof(enctypes[0]); i++) { krb5_enctype_enable(context, enctypes[i]); time_encryption(context, 16, enctypes[i], enciter); time_encryption(context, 32, enctypes[i], enciter); time_encryption(context, 512, enctypes[i], enciter); time_encryption(context, 1024, enctypes[i], enciter); time_encryption(context, 2048, enctypes[i], enciter); time_encryption(context, 4096, enctypes[i], enciter); time_encryption(context, 8192, enctypes[i], enciter); time_encryption(context, 16384, enctypes[i], enciter); time_encryption(context, 32768, enctypes[i], enciter); time_s2k(context, enctypes[i], "mYsecreitPassword", salt, s2kiter); } krb5_free_context(context); return 0; } heimdal-7.5.0/lib/krb5/db_plugin.h0000644000175000017500000000475213026237312015006 0ustar niknik/* * Copyright (c) 2011, Secure Endpoints Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * - Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ /* $Id$ */ #ifndef HEIMDAL_KRB5_DB_PLUGIN_H #define HEIMDAL_KRB5_DB_PLUGIN_H 1 #define KRB5_PLUGIN_DB "krb5_db_plug" #define KRB5_PLUGIN_DB_VERSION_0 0 /** @struct krb5plugin_db_ftable_desc * * @brief Description of the krb5 DB plugin facility. * * The krb5_aname_to_lname(3) function's DB rule is pluggable. The * plugin is named KRB5_PLUGIN_DB ("krb5_db_plug"), with a single minor * version, KRB5_PLUGIN_DB_VERSION_0 (0). * * The plugin consists of a data symbol referencing a structure of type * krb5plugin_db_ftable_desc, with three fields: * * @param init Plugin initialization function (see krb5-plugin(7)) * * @param minor_version The plugin minor version number (0) * * @param fini Plugin finalization function * * The init entry point is expected to call heim_db_register(). The * fini entry point is expected to do nothing. * * @ingroup krb5_support */ typedef struct krb5plugin_db_ftable_desc { int minor_version; krb5_error_code (KRB5_LIB_CALL *init)(krb5_context, void **); void (KRB5_LIB_CALL *fini)(void *); } krb5plugin_db_ftable; #endif /* HEIMDAL_KRB5_DB_PLUGIN_H */ heimdal-7.5.0/lib/krb5/store.c0000644000175000017500000011320013026237312014157 0ustar niknik/* * Copyright (c) 1997-2008 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "krb5_locl.h" #include "store-int.h" #define BYTEORDER_IS(SP, V) (((SP)->flags & KRB5_STORAGE_BYTEORDER_MASK) == (V)) #define BYTEORDER_IS_LE(SP) BYTEORDER_IS((SP), KRB5_STORAGE_BYTEORDER_LE) #define BYTEORDER_IS_BE(SP) BYTEORDER_IS((SP), KRB5_STORAGE_BYTEORDER_BE) #define BYTEORDER_IS_HOST(SP) (BYTEORDER_IS((SP), KRB5_STORAGE_BYTEORDER_HOST) || \ krb5_storage_is_flags((SP), KRB5_STORAGE_HOST_BYTEORDER)) /** * Add the flags on a storage buffer by or-ing in the flags to the buffer. * * @param sp the storage buffer to set the flags on * @param flags the flags to set * * @ingroup krb5_storage */ KRB5_LIB_FUNCTION void KRB5_LIB_CALL krb5_storage_set_flags(krb5_storage *sp, krb5_flags flags) { sp->flags |= flags; } /** * Clear the flags on a storage buffer * * @param sp the storage buffer to clear the flags on * @param flags the flags to clear * * @ingroup krb5_storage */ KRB5_LIB_FUNCTION void KRB5_LIB_CALL krb5_storage_clear_flags(krb5_storage *sp, krb5_flags flags) { sp->flags &= ~flags; } /** * Return true or false depending on if the storage flags is set or * not. NB testing for the flag 0 always return true. * * @param sp the storage buffer to check flags on * @param flags The flags to test for * * @return true if all the flags are set, false if not. * * @ingroup krb5_storage */ KRB5_LIB_FUNCTION krb5_boolean KRB5_LIB_CALL krb5_storage_is_flags(krb5_storage *sp, krb5_flags flags) { return (sp->flags & flags) == flags; } /** * Set the new byte order of the storage buffer. * * @param sp the storage buffer to set the byte order for. * @param byteorder the new byte order. * * The byte order are: KRB5_STORAGE_BYTEORDER_BE, * KRB5_STORAGE_BYTEORDER_LE and KRB5_STORAGE_BYTEORDER_HOST. * * @ingroup krb5_storage */ KRB5_LIB_FUNCTION void KRB5_LIB_CALL krb5_storage_set_byteorder(krb5_storage *sp, krb5_flags byteorder) { sp->flags &= ~KRB5_STORAGE_BYTEORDER_MASK; sp->flags |= byteorder; } /** * Return the current byteorder for the buffer. See krb5_storage_set_byteorder() for the list or byte order contants. * * @ingroup krb5_storage */ KRB5_LIB_FUNCTION krb5_flags KRB5_LIB_CALL krb5_storage_get_byteorder(krb5_storage *sp) { return sp->flags & KRB5_STORAGE_BYTEORDER_MASK; } /** * Set the max alloc value * * @param sp the storage buffer set the max allow for * @param size maximum size to allocate, use 0 to remove limit * * @ingroup krb5_storage */ KRB5_LIB_FUNCTION void KRB5_LIB_CALL krb5_storage_set_max_alloc(krb5_storage *sp, size_t size) { sp->max_alloc = size; } /* don't allocate unresonable amount of memory */ static krb5_error_code size_too_large(krb5_storage *sp, size_t size) { if (sp->max_alloc && sp->max_alloc < size) return HEIM_ERR_TOO_BIG; return 0; } static krb5_error_code size_too_large_num(krb5_storage *sp, size_t count, size_t size) { if (sp->max_alloc == 0 || size == 0) return 0; size = sp->max_alloc / size; if (size < count) return HEIM_ERR_TOO_BIG; return 0; } /** * Seek to a new offset. * * @param sp the storage buffer to seek in. * @param offset the offset to seek * @param whence relateive searching, SEEK_CUR from the current * position, SEEK_END from the end, SEEK_SET absolute from the start. * * @return The new current offset * * @ingroup krb5_storage */ KRB5_LIB_FUNCTION off_t KRB5_LIB_CALL krb5_storage_seek(krb5_storage *sp, off_t offset, int whence) { return (*sp->seek)(sp, offset, whence); } /** * Truncate the storage buffer in sp to offset. * * @param sp the storage buffer to truncate. * @param offset the offset to truncate too. * * @return An Kerberos 5 error code. * * @ingroup krb5_storage */ KRB5_LIB_FUNCTION int KRB5_LIB_CALL krb5_storage_truncate(krb5_storage *sp, off_t offset) { return (*sp->trunc)(sp, offset); } /** * Sync the storage buffer to its backing store. If there is no * backing store this function will return success. * * @param sp the storage buffer to sync * * @return A Kerberos 5 error code * * @ingroup krb5_storage */ KRB5_LIB_FUNCTION int KRB5_LIB_CALL krb5_storage_fsync(krb5_storage *sp) { if (sp->fsync != NULL) return sp->fsync(sp); return 0; } /** * Read to the storage buffer. * * @param sp the storage buffer to read from * @param buf the buffer to store the data in * @param len the length to read * * @return The length of data read (can be shorter then len), or negative on error. * * @ingroup krb5_storage */ KRB5_LIB_FUNCTION krb5_ssize_t KRB5_LIB_CALL krb5_storage_read(krb5_storage *sp, void *buf, size_t len) { return sp->fetch(sp, buf, len); } /** * Write to the storage buffer. * * @param sp the storage buffer to write to * @param buf the buffer to write to the storage buffer * @param len the length to write * * @return The length of data written (can be shorter then len), or negative on error. * * @ingroup krb5_storage */ KRB5_LIB_FUNCTION krb5_ssize_t KRB5_LIB_CALL krb5_storage_write(krb5_storage *sp, const void *buf, size_t len) { return sp->store(sp, buf, len); } /** * Set the return code that will be used when end of storage is reached. * * @param sp the storage * @param code the error code to return on end of storage * * @ingroup krb5_storage */ KRB5_LIB_FUNCTION void KRB5_LIB_CALL krb5_storage_set_eof_code(krb5_storage *sp, int code) { sp->eof_code = code; } /** * Get the return code that will be used when end of storage is reached. * * @param sp the storage * * @return storage error code * * @ingroup krb5_storage */ KRB5_LIB_FUNCTION int KRB5_LIB_CALL krb5_storage_get_eof_code(krb5_storage *sp) { return sp->eof_code; } /** * Free a krb5 storage. * * @param sp the storage to free. * * @return An Kerberos 5 error code. * * @ingroup krb5_storage */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_storage_free(krb5_storage *sp) { if (sp == NULL) return 0; if(sp->free) (*sp->free)(sp); free(sp->data); free(sp); return 0; } /** * Copy the contnent of storage * * @param sp the storage to copy to a data * @param data the copied data, free with krb5_data_free() * * @return 0 for success, or a Kerberos 5 error code on failure. * * @ingroup krb5_storage */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_storage_to_data(krb5_storage *sp, krb5_data *data) { off_t pos, size; krb5_error_code ret; pos = sp->seek(sp, 0, SEEK_CUR); if (pos < 0) return HEIM_ERR_NOT_SEEKABLE; size = sp->seek(sp, 0, SEEK_END); ret = size_too_large(sp, size); if (ret) return ret; ret = krb5_data_alloc(data, size); if (ret) { sp->seek(sp, pos, SEEK_SET); return ret; } if (size) { sp->seek(sp, 0, SEEK_SET); sp->fetch(sp, data->data, data->length); sp->seek(sp, pos, SEEK_SET); } return 0; } static krb5_error_code krb5_store_int(krb5_storage *sp, int64_t value, size_t len) { int ret; unsigned char v[8]; if (len > sizeof(v)) return EINVAL; _krb5_put_int(v, value, len); ret = sp->store(sp, v, len); if (ret < 0) return errno; if ((size_t)ret != len) return sp->eof_code; return 0; } /** * Store a int32 to storage, byte order is controlled by the settings * on the storage, see krb5_storage_set_byteorder(). * * @param sp the storage to write too * @param value the value to store * * @return 0 for success, or a Kerberos 5 error code on failure. * * @ingroup krb5_storage */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_store_int32(krb5_storage *sp, int32_t value) { if(BYTEORDER_IS_HOST(sp)) value = htonl(value); else if(BYTEORDER_IS_LE(sp)) value = bswap32(value); return krb5_store_int(sp, value, 4); } /** * Store a int64 to storage, byte order is controlled by the settings * on the storage, see krb5_storage_set_byteorder(). * * @param sp the storage to write too * @param value the value to store * * @return 0 for success, or a Kerberos 5 error code on failure. * * @ingroup krb5_storage */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_store_int64(krb5_storage *sp, int64_t value) { if (BYTEORDER_IS_HOST(sp)) #ifdef WORDS_BIGENDIAN ; #else value = bswap64(value); /* There's no ntohll() */ #endif else if (BYTEORDER_IS_LE(sp)) value = bswap64(value); return krb5_store_int(sp, value, 8); } /** * Store a uint32 to storage, byte order is controlled by the settings * on the storage, see krb5_storage_set_byteorder(). * * @param sp the storage to write too * @param value the value to store * * @return 0 for success, or a Kerberos 5 error code on failure. * * @ingroup krb5_storage */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_store_uint32(krb5_storage *sp, uint32_t value) { return krb5_store_int32(sp, (int32_t)value); } /** * Store a uint64 to storage, byte order is controlled by the settings * on the storage, see krb5_storage_set_byteorder(). * * @param sp the storage to write too * @param value the value to store * * @return 0 for success, or a Kerberos 5 error code on failure. * * @ingroup krb5_storage */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_store_uint64(krb5_storage *sp, uint64_t value) { return krb5_store_int64(sp, (int64_t)value); } static krb5_error_code krb5_ret_int(krb5_storage *sp, int64_t *value, size_t len) { int ret; unsigned char v[8]; uint64_t w; *value = 0; /* quiets warnings */ ret = sp->fetch(sp, v, len); if (ret < 0) return errno; if ((size_t)ret != len) return sp->eof_code; _krb5_get_int64(v, &w, len); *value = w; return 0; } /** * Read a int64 from storage, byte order is controlled by the settings * on the storage, see krb5_storage_set_byteorder(). * * @param sp the storage to write too * @param value the value read from the buffer * * @return 0 for success, or a Kerberos 5 error code on failure. * * @ingroup krb5_storage */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_ret_int64(krb5_storage *sp, int64_t *value) { krb5_error_code ret = krb5_ret_int(sp, value, 8); if(ret) return ret; if(BYTEORDER_IS_HOST(sp)) #ifdef WORDS_BIGENDIAN ; #else *value = bswap64(*value); /* There's no ntohll() */ #endif else if(BYTEORDER_IS_LE(sp)) *value = bswap64(*value); return 0; } /** * Read a uint64 from storage, byte order is controlled by the settings * on the storage, see krb5_storage_set_byteorder(). * * @param sp the storage to write too * @param value the value read from the buffer * * @return 0 for success, or a Kerberos 5 error code on failure. * * @ingroup krb5_storage */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_ret_uint64(krb5_storage *sp, uint64_t *value) { krb5_error_code ret; int64_t v; ret = krb5_ret_int64(sp, &v); if (ret == 0) *value = (uint64_t)v; return ret; } /** * Read a int32 from storage, byte order is controlled by the settings * on the storage, see krb5_storage_set_byteorder(). * * @param sp the storage to write too * @param value the value read from the buffer * * @return 0 for success, or a Kerberos 5 error code on failure. * * @ingroup krb5_storage */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_ret_int32(krb5_storage *sp, int32_t *value) { int64_t v; krb5_error_code ret = krb5_ret_int(sp, &v, 4); if (ret) return ret; *value = v; if (BYTEORDER_IS_HOST(sp)) *value = htonl(*value); else if (BYTEORDER_IS_LE(sp)) *value = bswap32(*value); return 0; } /** * Read a uint32 from storage, byte order is controlled by the settings * on the storage, see krb5_storage_set_byteorder(). * * @param sp the storage to write too * @param value the value read from the buffer * * @return 0 for success, or a Kerberos 5 error code on failure. * * @ingroup krb5_storage */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_ret_uint32(krb5_storage *sp, uint32_t *value) { krb5_error_code ret; int32_t v; ret = krb5_ret_int32(sp, &v); if (ret == 0) *value = (uint32_t)v; return ret; } /** * Store a int16 to storage, byte order is controlled by the settings * on the storage, see krb5_storage_set_byteorder(). * * @param sp the storage to write too * @param value the value to store * * @return 0 for success, or a Kerberos 5 error code on failure. * * @ingroup krb5_storage */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_store_int16(krb5_storage *sp, int16_t value) { if(BYTEORDER_IS_HOST(sp)) value = htons(value); else if(BYTEORDER_IS_LE(sp)) value = bswap16(value); return krb5_store_int(sp, value, 2); } /** * Store a uint16 to storage, byte order is controlled by the settings * on the storage, see krb5_storage_set_byteorder(). * * @param sp the storage to write too * @param value the value to store * * @return 0 for success, or a Kerberos 5 error code on failure. * * @ingroup krb5_storage */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_store_uint16(krb5_storage *sp, uint16_t value) { return krb5_store_int16(sp, (int16_t)value); } /** * Read a int16 from storage, byte order is controlled by the settings * on the storage, see krb5_storage_set_byteorder(). * * @param sp the storage to write too * @param value the value read from the buffer * * @return 0 for success, or a Kerberos 5 error code on failure. * * @ingroup krb5_storage */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_ret_int16(krb5_storage *sp, int16_t *value) { int64_t v; int ret; ret = krb5_ret_int(sp, &v, 2); if(ret) return ret; *value = v; if(BYTEORDER_IS_HOST(sp)) *value = htons(*value); else if(BYTEORDER_IS_LE(sp)) *value = bswap16(*value); return 0; } /** * Read a int16 from storage, byte order is controlled by the settings * on the storage, see krb5_storage_set_byteorder(). * * @param sp the storage to write too * @param value the value read from the buffer * * @return 0 for success, or a Kerberos 5 error code on failure. * * @ingroup krb5_storage */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_ret_uint16(krb5_storage *sp, uint16_t *value) { krb5_error_code ret; int16_t v; ret = krb5_ret_int16(sp, &v); if (ret == 0) *value = (uint16_t)v; return ret; } /** * Store a int8 to storage. * * @param sp the storage to write too * @param value the value to store * * @return 0 for success, or a Kerberos 5 error code on failure. * * @ingroup krb5_storage */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_store_int8(krb5_storage *sp, int8_t value) { int ret; ret = sp->store(sp, &value, sizeof(value)); if (ret != sizeof(value)) return (ret<0)?errno:sp->eof_code; return 0; } /** * Store a uint8 to storage. * * @param sp the storage to write too * @param value the value to store * * @return 0 for success, or a Kerberos 5 error code on failure. * * @ingroup krb5_storage */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_store_uint8(krb5_storage *sp, uint8_t value) { return krb5_store_int8(sp, (int8_t)value); } /** * Read a int8 from storage * * @param sp the storage to write too * @param value the value read from the buffer * * @return 0 for success, or a Kerberos 5 error code on failure. * * @ingroup krb5_storage */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_ret_int8(krb5_storage *sp, int8_t *value) { int ret; ret = sp->fetch(sp, value, sizeof(*value)); if (ret != sizeof(*value)) return (ret<0)?errno:sp->eof_code; return 0; } /** * Read a uint8 from storage * * @param sp the storage to write too * @param value the value read from the buffer * * @return 0 for success, or a Kerberos 5 error code on failure. * * @ingroup krb5_storage */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_ret_uint8(krb5_storage *sp, uint8_t *value) { krb5_error_code ret; int8_t v; ret = krb5_ret_int8(sp, &v); if (ret == 0) *value = (uint8_t)v; return ret; } /** * Store a data to the storage. The data is stored with an int32 as * lenght plus the data (not padded). * * @param sp the storage buffer to write to * @param data the buffer to store. * * @return 0 on success, a Kerberos 5 error code on failure. * * @ingroup krb5_storage */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_store_data(krb5_storage *sp, krb5_data data) { int ret; ret = krb5_store_int32(sp, data.length); if(ret < 0) return ret; ret = sp->store(sp, data.data, data.length); if(ret < 0) return errno; if((size_t)ret != data.length) return sp->eof_code; return 0; } /** * Parse a data from the storage. * * @param sp the storage buffer to read from * @param data the parsed data * * @return 0 on success, a Kerberos 5 error code on failure. * * @ingroup krb5_storage */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_ret_data(krb5_storage *sp, krb5_data *data) { int ret; int32_t size; ret = krb5_ret_int32(sp, &size); if(ret) return ret; ret = size_too_large(sp, size); if (ret) return ret; ret = krb5_data_alloc (data, size); if (ret) return ret; if (size) { ret = sp->fetch(sp, data->data, size); if(ret != size) { krb5_data_free(data); return (ret < 0)? errno : sp->eof_code; } } return 0; } /** * Store a string to the buffer. The data is formated as an len:uint32 * plus the string itself (not padded). * * @param sp the storage buffer to write to * @param s the string to store. * * @return 0 on success, a Kerberos 5 error code on failure. * * @ingroup krb5_storage */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_store_string(krb5_storage *sp, const char *s) { krb5_data data; data.length = strlen(s); data.data = rk_UNCONST(s); return krb5_store_data(sp, data); } /** * Parse a string from the storage. * * @param sp the storage buffer to read from * @param string the parsed string * * @return 0 on success, a Kerberos 5 error code on failure. * * @ingroup krb5_storage */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_ret_string(krb5_storage *sp, char **string) { int ret; krb5_data data; ret = krb5_ret_data(sp, &data); if(ret) return ret; *string = realloc(data.data, data.length + 1); if(*string == NULL){ free(data.data); return ENOMEM; } (*string)[data.length] = 0; return 0; } /** * Store a zero terminated string to the buffer. The data is stored * one character at a time until a NUL is stored. * * @param sp the storage buffer to write to * @param s the string to store. * * @return 0 on success, a Kerberos 5 error code on failure. * * @ingroup krb5_storage */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_store_stringz(krb5_storage *sp, const char *s) { size_t len = strlen(s) + 1; ssize_t ret; ret = sp->store(sp, s, len); if(ret < 0) return ret; if((size_t)ret != len) return sp->eof_code; return 0; } /** * Parse zero terminated string from the storage. * * @param sp the storage buffer to read from * @param string the parsed string * * @return 0 on success, a Kerberos 5 error code on failure. * * @ingroup krb5_storage */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_ret_stringz(krb5_storage *sp, char **string) { char c; char *s = NULL; size_t len = 0; ssize_t ret; while((ret = sp->fetch(sp, &c, 1)) == 1){ krb5_error_code eret; char *tmp; len++; eret = size_too_large(sp, len); if (eret) { free(s); return eret; } tmp = realloc (s, len); if (tmp == NULL) { free (s); return ENOMEM; } s = tmp; s[len - 1] = c; if(c == 0) break; } if(ret != 1){ free(s); if(ret == 0) return sp->eof_code; return ret; } *string = s; return 0; } KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_store_stringnl(krb5_storage *sp, const char *s) { size_t len = strlen(s); ssize_t ret; ret = sp->store(sp, s, len); if(ret < 0) return ret; if((size_t)ret != len) return sp->eof_code; ret = sp->store(sp, "\n", 1); if(ret != 1) { if(ret < 0) return ret; else return sp->eof_code; } return 0; } KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_ret_stringnl(krb5_storage *sp, char **string) { int expect_nl = 0; char c; char *s = NULL; size_t len = 0; ssize_t ret; while((ret = sp->fetch(sp, &c, 1)) == 1){ krb5_error_code eret; char *tmp; if (c == '\r') { expect_nl = 1; continue; } if (expect_nl && c != '\n') { free(s); return KRB5_BADMSGTYPE; } len++; eret = size_too_large(sp, len); if (eret) { free(s); return eret; } tmp = realloc (s, len); if (tmp == NULL) { free (s); return ENOMEM; } s = tmp; if(c == '\n') { s[len - 1] = '\0'; break; } s[len - 1] = c; } if(ret != 1){ free(s); if(ret == 0) return sp->eof_code; return ret; } *string = s; return 0; } /** * Write a principal block to storage. * * @param sp the storage buffer to write to * @param p the principal block to write. * * @return 0 on success, a Kerberos 5 error code on failure. * * @ingroup krb5_storage */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_store_principal(krb5_storage *sp, krb5_const_principal p) { size_t i; int ret; if(!krb5_storage_is_flags(sp, KRB5_STORAGE_PRINCIPAL_NO_NAME_TYPE)) { ret = krb5_store_int32(sp, p->name.name_type); if(ret) return ret; } if(krb5_storage_is_flags(sp, KRB5_STORAGE_PRINCIPAL_WRONG_NUM_COMPONENTS)) ret = krb5_store_int32(sp, p->name.name_string.len + 1); else ret = krb5_store_int32(sp, p->name.name_string.len); if(ret) return ret; ret = krb5_store_string(sp, p->realm); if(ret) return ret; for(i = 0; i < p->name.name_string.len; i++){ ret = krb5_store_string(sp, p->name.name_string.val[i]); if(ret) return ret; } return 0; } /** * Parse principal from the storage. * * @param sp the storage buffer to read from * @param princ the parsed principal * * @return 0 on success, a Kerberos 5 error code on failure. * * @ingroup krb5_storage */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_ret_principal(krb5_storage *sp, krb5_principal *princ) { int i; int ret; krb5_principal p; int32_t type; int32_t ncomp; p = calloc(1, sizeof(*p)); if(p == NULL) return ENOMEM; if(krb5_storage_is_flags(sp, KRB5_STORAGE_PRINCIPAL_NO_NAME_TYPE)) type = KRB5_NT_UNKNOWN; else if((ret = krb5_ret_int32(sp, &type))){ free(p); return ret; } if((ret = krb5_ret_int32(sp, &ncomp))){ free(p); return ret; } if(krb5_storage_is_flags(sp, KRB5_STORAGE_PRINCIPAL_WRONG_NUM_COMPONENTS)) ncomp--; if (ncomp < 0) { free(p); return EINVAL; } ret = size_too_large_num(sp, ncomp, sizeof(p->name.name_string.val[0])); if (ret) { free(p); return ret; } p->name.name_type = type; p->name.name_string.len = ncomp; ret = krb5_ret_string(sp, &p->realm); if(ret) { free(p); return ret; } p->name.name_string.val = calloc(ncomp, sizeof(p->name.name_string.val[0])); if(p->name.name_string.val == NULL && ncomp != 0){ free(p->realm); free(p); return ENOMEM; } for(i = 0; i < ncomp; i++){ ret = krb5_ret_string(sp, &p->name.name_string.val[i]); if(ret) { while (i >= 0) free(p->name.name_string.val[i--]); free(p->realm); free(p); return ret; } } *princ = p; return 0; } /** * Store a keyblock to the storage. * * @param sp the storage buffer to write to * @param p the keyblock to write * * @return 0 on success, a Kerberos 5 error code on failure. * * @ingroup krb5_storage */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_store_keyblock(krb5_storage *sp, krb5_keyblock p) { int ret; ret = krb5_store_int16(sp, p.keytype); if(ret) return ret; if(krb5_storage_is_flags(sp, KRB5_STORAGE_KEYBLOCK_KEYTYPE_TWICE)){ /* this should really be enctype, but it is the same as keytype nowadays */ ret = krb5_store_int16(sp, p.keytype); if(ret) return ret; } ret = krb5_store_data(sp, p.keyvalue); return ret; } /** * Read a keyblock from the storage. * * @param sp the storage buffer to write to * @param p the keyblock read from storage, free using krb5_free_keyblock() * * @return 0 on success, a Kerberos 5 error code on failure. * * @ingroup krb5_storage */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_ret_keyblock(krb5_storage *sp, krb5_keyblock *p) { int ret; int16_t tmp; ret = krb5_ret_int16(sp, &tmp); if(ret) return ret; p->keytype = tmp; if(krb5_storage_is_flags(sp, KRB5_STORAGE_KEYBLOCK_KEYTYPE_TWICE)){ ret = krb5_ret_int16(sp, &tmp); if(ret) return ret; } ret = krb5_ret_data(sp, &p->keyvalue); return ret; } /** * Write a times block to storage. * * @param sp the storage buffer to write to * @param times the times block to write. * * @return 0 on success, a Kerberos 5 error code on failure. * * @ingroup krb5_storage */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_store_times(krb5_storage *sp, krb5_times times) { int ret; ret = krb5_store_int32(sp, times.authtime); if(ret) return ret; ret = krb5_store_int32(sp, times.starttime); if(ret) return ret; ret = krb5_store_int32(sp, times.endtime); if(ret) return ret; ret = krb5_store_int32(sp, times.renew_till); return ret; } /** * Read a times block from the storage. * * @param sp the storage buffer to write to * @param times the times block read from storage * * @return 0 on success, a Kerberos 5 error code on failure. * * @ingroup krb5_storage */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_ret_times(krb5_storage *sp, krb5_times *times) { int ret; int32_t tmp; ret = krb5_ret_int32(sp, &tmp); times->authtime = tmp; if(ret) return ret; ret = krb5_ret_int32(sp, &tmp); times->starttime = tmp; if(ret) return ret; ret = krb5_ret_int32(sp, &tmp); times->endtime = tmp; if(ret) return ret; ret = krb5_ret_int32(sp, &tmp); times->renew_till = tmp; return ret; } /** * Write a address block to storage. * * @param sp the storage buffer to write to * @param p the address block to write. * * @return 0 on success, a Kerberos 5 error code on failure. * * @ingroup krb5_storage */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_store_address(krb5_storage *sp, krb5_address p) { int ret; ret = krb5_store_int16(sp, p.addr_type); if(ret) return ret; ret = krb5_store_data(sp, p.address); return ret; } /** * Read a address block from the storage. * * @param sp the storage buffer to write to * @param adr the address block read from storage * * @return 0 on success, a Kerberos 5 error code on failure. * * @ingroup krb5_storage */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_ret_address(krb5_storage *sp, krb5_address *adr) { int16_t t; int ret; ret = krb5_ret_int16(sp, &t); if(ret) return ret; adr->addr_type = t; ret = krb5_ret_data(sp, &adr->address); return ret; } /** * Write a addresses block to storage. * * @param sp the storage buffer to write to * @param p the addresses block to write. * * @return 0 on success, a Kerberos 5 error code on failure. * * @ingroup krb5_storage */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_store_addrs(krb5_storage *sp, krb5_addresses p) { size_t i; int ret; ret = krb5_store_int32(sp, p.len); if(ret) return ret; for(i = 0; ival[0])); if (ret) return ret; adr->len = tmp; ALLOC(adr->val, adr->len); if (adr->val == NULL && adr->len != 0) return ENOMEM; for(i = 0; i < adr->len; i++){ ret = krb5_ret_address(sp, &adr->val[i]); if(ret) break; } return ret; } /** * Write a auth data block to storage. * * @param sp the storage buffer to write to * @param auth the auth data block to write. * * @return 0 on success, a Kerberos 5 error code on failure. * * @ingroup krb5_storage */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_store_authdata(krb5_storage *sp, krb5_authdata auth) { krb5_error_code ret; size_t i; ret = krb5_store_int32(sp, auth.len); if(ret) return ret; for(i = 0; i < auth.len; i++){ ret = krb5_store_int16(sp, auth.val[i].ad_type); if(ret) break; ret = krb5_store_data(sp, auth.val[i].ad_data); if(ret) break; } return 0; } /** * Read a auth data from the storage. * * @param sp the storage buffer to write to * @param auth the auth data block read from storage * * @return 0 on success, a Kerberos 5 error code on failure. * * @ingroup krb5_storage */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_ret_authdata(krb5_storage *sp, krb5_authdata *auth) { krb5_error_code ret; int32_t tmp; int16_t tmp2; int i; ret = krb5_ret_int32(sp, &tmp); if(ret) return ret; ret = size_too_large_num(sp, tmp, sizeof(auth->val[0])); if (ret) return ret; ALLOC_SEQ(auth, tmp); if (auth->val == NULL && tmp != 0) return ENOMEM; for(i = 0; i < tmp; i++){ ret = krb5_ret_int16(sp, &tmp2); if(ret) break; auth->val[i].ad_type = tmp2; ret = krb5_ret_data(sp, &auth->val[i].ad_data); if(ret) break; } return ret; } static int32_t bitswap32(int32_t b) { int32_t r = 0; int i; for (i = 0; i < 32; i++) { r = r << 1 | (b & 1); b = b >> 1; } return r; } /** * Write a credentials block to storage. * * @param sp the storage buffer to write to * @param creds the creds block to write. * * @return 0 on success, a Kerberos 5 error code on failure. * * @ingroup krb5_storage */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_store_creds(krb5_storage *sp, krb5_creds *creds) { int ret; ret = krb5_store_principal(sp, creds->client); if(ret) return ret; ret = krb5_store_principal(sp, creds->server); if(ret) return ret; ret = krb5_store_keyblock(sp, creds->session); if(ret) return ret; ret = krb5_store_times(sp, creds->times); if(ret) return ret; ret = krb5_store_int8(sp, creds->second_ticket.length != 0); /* is_skey */ if(ret) return ret; ret = krb5_store_int32(sp, bitswap32(TicketFlags2int(creds->flags.b))); if(ret) return ret; ret = krb5_store_addrs(sp, creds->addresses); if(ret) return ret; ret = krb5_store_authdata(sp, creds->authdata); if(ret) return ret; ret = krb5_store_data(sp, creds->ticket); if(ret) return ret; ret = krb5_store_data(sp, creds->second_ticket); return ret; } /** * Read a credentials block from the storage. * * @param sp the storage buffer to write to * @param creds the credentials block read from storage * * @return 0 on success, a Kerberos 5 error code on failure. * * @ingroup krb5_storage */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_ret_creds(krb5_storage *sp, krb5_creds *creds) { krb5_error_code ret; int8_t dummy8; int32_t dummy32; memset(creds, 0, sizeof(*creds)); ret = krb5_ret_principal (sp, &creds->client); if(ret) goto cleanup; ret = krb5_ret_principal (sp, &creds->server); if(ret) goto cleanup; ret = krb5_ret_keyblock (sp, &creds->session); if(ret) goto cleanup; ret = krb5_ret_times (sp, &creds->times); if(ret) goto cleanup; ret = krb5_ret_int8 (sp, &dummy8); if(ret) goto cleanup; ret = krb5_ret_int32 (sp, &dummy32); if(ret) goto cleanup; creds->flags.b = int2TicketFlags(bitswap32(dummy32)); ret = krb5_ret_addrs (sp, &creds->addresses); if(ret) goto cleanup; ret = krb5_ret_authdata (sp, &creds->authdata); if(ret) goto cleanup; ret = krb5_ret_data (sp, &creds->ticket); if(ret) goto cleanup; ret = krb5_ret_data (sp, &creds->second_ticket); cleanup: if(ret) { #if 0 krb5_free_cred_contents(context, creds); /* XXX */ #endif } return ret; } #define SC_CLIENT_PRINCIPAL 0x0001 #define SC_SERVER_PRINCIPAL 0x0002 #define SC_SESSION_KEY 0x0004 #define SC_TICKET 0x0008 #define SC_SECOND_TICKET 0x0010 #define SC_AUTHDATA 0x0020 #define SC_ADDRESSES 0x0040 /** * Write a tagged credentials block to storage. * * @param sp the storage buffer to write to * @param creds the creds block to write. * * @return 0 on success, a Kerberos 5 error code on failure. * * @ingroup krb5_storage */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_store_creds_tag(krb5_storage *sp, krb5_creds *creds) { int ret; int32_t header = 0; if (creds->client) header |= SC_CLIENT_PRINCIPAL; if (creds->server) header |= SC_SERVER_PRINCIPAL; if (creds->session.keytype != ETYPE_NULL) header |= SC_SESSION_KEY; if (creds->ticket.data) header |= SC_TICKET; if (creds->second_ticket.length) header |= SC_SECOND_TICKET; if (creds->authdata.len) header |= SC_AUTHDATA; if (creds->addresses.len) header |= SC_ADDRESSES; ret = krb5_store_int32(sp, header); if (ret) return ret; if (creds->client) { ret = krb5_store_principal(sp, creds->client); if(ret) return ret; } if (creds->server) { ret = krb5_store_principal(sp, creds->server); if(ret) return ret; } if (creds->session.keytype != ETYPE_NULL) { ret = krb5_store_keyblock(sp, creds->session); if(ret) return ret; } ret = krb5_store_times(sp, creds->times); if(ret) return ret; ret = krb5_store_int8(sp, creds->second_ticket.length != 0); /* is_skey */ if(ret) return ret; ret = krb5_store_int32(sp, bitswap32(TicketFlags2int(creds->flags.b))); if(ret) return ret; if (creds->addresses.len) { ret = krb5_store_addrs(sp, creds->addresses); if(ret) return ret; } if (creds->authdata.len) { ret = krb5_store_authdata(sp, creds->authdata); if(ret) return ret; } if (creds->ticket.data) { ret = krb5_store_data(sp, creds->ticket); if(ret) return ret; } if (creds->second_ticket.data) { ret = krb5_store_data(sp, creds->second_ticket); if (ret) return ret; } return ret; } /** * Read a tagged credentials block from the storage. * * @param sp the storage buffer to write to * @param creds the credentials block read from storage * * @return 0 on success, a Kerberos 5 error code on failure. * * @ingroup krb5_storage */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_ret_creds_tag(krb5_storage *sp, krb5_creds *creds) { krb5_error_code ret; int8_t dummy8; int32_t dummy32, header; memset(creds, 0, sizeof(*creds)); ret = krb5_ret_int32 (sp, &header); if (ret) goto cleanup; if (header & SC_CLIENT_PRINCIPAL) { ret = krb5_ret_principal (sp, &creds->client); if(ret) goto cleanup; } if (header & SC_SERVER_PRINCIPAL) { ret = krb5_ret_principal (sp, &creds->server); if(ret) goto cleanup; } if (header & SC_SESSION_KEY) { ret = krb5_ret_keyblock (sp, &creds->session); if(ret) goto cleanup; } ret = krb5_ret_times (sp, &creds->times); if(ret) goto cleanup; ret = krb5_ret_int8 (sp, &dummy8); if(ret) goto cleanup; ret = krb5_ret_int32 (sp, &dummy32); if(ret) goto cleanup; creds->flags.b = int2TicketFlags(bitswap32(dummy32)); if (header & SC_ADDRESSES) { ret = krb5_ret_addrs (sp, &creds->addresses); if(ret) goto cleanup; } if (header & SC_AUTHDATA) { ret = krb5_ret_authdata (sp, &creds->authdata); if(ret) goto cleanup; } if (header & SC_TICKET) { ret = krb5_ret_data (sp, &creds->ticket); if(ret) goto cleanup; } if (header & SC_SECOND_TICKET) { ret = krb5_ret_data (sp, &creds->second_ticket); if(ret) goto cleanup; } cleanup: if(ret) { #if 0 krb5_free_cred_contents(context, creds); /* XXX */ #endif } return ret; } heimdal-7.5.0/lib/krb5/store_emem.c0000644000175000017500000001217113026237312015167 0ustar niknik/* * Copyright (c) 1997 - 2002 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "krb5_locl.h" #include "store-int.h" typedef struct emem_storage{ unsigned char *base; size_t size; size_t len; unsigned char *ptr; }emem_storage; static ssize_t emem_fetch(krb5_storage *sp, void *data, size_t size) { emem_storage *s = (emem_storage*)sp->data; if((size_t)(s->base + s->len - s->ptr) < size) size = s->base + s->len - s->ptr; memmove(data, s->ptr, size); sp->seek(sp, size, SEEK_CUR); return size; } static ssize_t emem_store(krb5_storage *sp, const void *data, size_t size) { emem_storage *s = (emem_storage*)sp->data; if(size > (size_t)(s->base + s->size - s->ptr)){ void *base; size_t sz, off; off = s->ptr - s->base; sz = off + size; if (sz < 4096) sz *= 2; base = realloc(s->base, sz); if(base == NULL) return -1; s->size = sz; s->base = base; s->ptr = (unsigned char*)base + off; } memmove(s->ptr, data, size); sp->seek(sp, size, SEEK_CUR); return size; } static off_t emem_seek(krb5_storage *sp, off_t offset, int whence) { emem_storage *s = (emem_storage*)sp->data; switch(whence){ case SEEK_SET: if((size_t)offset > s->size) offset = s->size; if(offset < 0) offset = 0; s->ptr = s->base + offset; if((size_t)offset > s->len) s->len = offset; break; case SEEK_CUR: sp->seek(sp,s->ptr - s->base + offset, SEEK_SET); break; case SEEK_END: sp->seek(sp, s->len + offset, SEEK_SET); break; default: errno = EINVAL; return -1; } return s->ptr - s->base; } static int emem_trunc(krb5_storage *sp, off_t offset) { emem_storage *s = (emem_storage*)sp->data; /* * If offset is larget then current size, or current size is * shrunk more then half of the current size, adjust buffer. */ if (offset == 0) { free(s->base); s->size = 0; s->base = NULL; s->ptr = NULL; } else if ((size_t)offset > s->size || (s->size / 2) > (size_t)offset) { void *base; size_t off; off = s->ptr - s->base; base = realloc(s->base, offset); if(base == NULL) return ENOMEM; if ((size_t)offset > s->size) memset((char *)base + s->size, 0, offset - s->size); s->size = offset; s->base = base; s->ptr = (unsigned char *)base + off; } s->len = offset; if ((s->ptr - s->base) > offset) s->ptr = s->base + offset; return 0; } static void emem_free(krb5_storage *sp) { emem_storage *s = sp->data; memset(s->base, 0, s->len); free(s->base); } /** * Create a elastic (allocating) memory storage backend. Memory is * allocated on demand. Free returned krb5_storage with * krb5_storage_free(). * * @return A krb5_storage on success, or NULL on out of memory error. * * @ingroup krb5_storage * * @sa krb5_storage_from_mem() * @sa krb5_storage_from_readonly_mem() * @sa krb5_storage_from_fd() * @sa krb5_storage_from_data() * @sa krb5_storage_from_socket() */ KRB5_LIB_FUNCTION krb5_storage * KRB5_LIB_CALL krb5_storage_emem(void) { krb5_storage *sp; emem_storage *s; sp = malloc(sizeof(krb5_storage)); if (sp == NULL) return NULL; s = malloc(sizeof(*s)); if (s == NULL) { free(sp); return NULL; } sp->data = s; sp->flags = 0; sp->eof_code = HEIM_ERR_EOF; s->size = 1024; s->base = malloc(s->size); if (s->base == NULL) { free(sp); free(s); return NULL; } s->len = 0; s->ptr = s->base; sp->fetch = emem_fetch; sp->store = emem_store; sp->seek = emem_seek; sp->trunc = emem_trunc; sp->fsync = NULL; sp->free = emem_free; sp->max_alloc = UINT_MAX/8; return sp; } heimdal-7.5.0/lib/krb5/test_mem.c0000644000175000017500000000433412136107750014652 0ustar niknik/* * Copyright (c) 2005 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of KTH nor the names of its contributors may be * used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY KTH AND ITS CONTRIBUTORS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL KTH OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "krb5_locl.h" #include /* * Test run functions, to be used with valgrind to detect memoryleaks. */ static void check_log(void) { int i; for (i = 0; i < 10; i++) { krb5_log_facility *logfacility; krb5_context context; krb5_error_code ret; ret = krb5_init_context(&context); if (ret) errx (1, "krb5_init_context failed: %d", ret); krb5_initlog(context, "test-mem", &logfacility); krb5_addlog_dest(context, logfacility, "0/STDERR:"); krb5_set_warn_dest(context, logfacility); krb5_free_context(context); } } int main(int argc, char **argv) { setprogname(argv[0]); check_log(); return 0; } heimdal-7.5.0/lib/krb5/locate_plugin.h0000644000175000017500000000562113026237312015664 0ustar niknik/* * Copyright (c) 2006 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Portions Copyright (c) 2010 Apple Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ /* $Id$ */ #ifndef HEIMDAL_KRB5_LOCATE_PLUGIN_H #define HEIMDAL_KRB5_LOCATE_PLUGIN_H 1 #define KRB5_PLUGIN_LOCATE "service_locator" #define KRB5_PLUGIN_LOCATE_VERSION 1 #define KRB5_PLUGIN_LOCATE_VERSION_0 0 #define KRB5_PLUGIN_LOCATE_VERSION_1 1 #define KRB5_PLUGIN_LOCATE_VERSION_2 2 enum locate_service_type { locate_service_kdc = 1, locate_service_master_kdc, locate_service_kadmin, locate_service_krb524, locate_service_kpasswd }; typedef krb5_error_code (*krb5plugin_service_locate_lookup) (void *, unsigned long, enum locate_service_type, const char *, int, int, int (*)(void *,int,struct sockaddr *), void *); #define KRB5_PLF_ALLOW_HOMEDIR 1 typedef krb5_error_code (*krb5plugin_service_locate_lookup_old) (void *, enum locate_service_type, const char *, int, int, int (*)(void *,int,struct sockaddr *), void *); typedef struct krb5plugin_service_locate_ftable { int minor_version; krb5_error_code (*init)(krb5_context, void **); void (*fini)(void *); krb5plugin_service_locate_lookup_old old_lookup; krb5plugin_service_locate_lookup lookup; /* version 2 */ } krb5plugin_service_locate_ftable; #endif /* HEIMDAL_KRB5_LOCATE_PLUGIN_H */ heimdal-7.5.0/lib/krb5/test_cc.c0000644000175000017500000005144213026237312014460 0ustar niknik/* * Copyright (c) 2003 - 2007 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of KTH nor the names of its contributors may be * used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY KTH AND ITS CONTRIBUTORS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL KTH OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "krb5_locl.h" #include #include static int debug_flag = 0; static int version_flag = 0; static int help_flag = 0; #ifdef KRB5_USE_PATH_TOKENS #define TEST_CC_NAME "%{TEMP}/krb5-cc-test-foo" #else #define TEST_CC_NAME "/tmp/krb5-cc-test-foo" #endif static void test_default_name(krb5_context context) { krb5_error_code ret; const char *p, *test_cc_name = TEST_CC_NAME; char *p1, *p2, *p3; p = krb5_cc_default_name(context); if (p == NULL) krb5_errx (context, 1, "krb5_cc_default_name 1 failed"); p1 = estrdup(p); ret = krb5_cc_set_default_name(context, NULL); if (ret) krb5_errx (context, 1, "krb5_cc_set_default_name failed"); p = krb5_cc_default_name(context); if (p == NULL) krb5_errx (context, 1, "krb5_cc_default_name 2 failed"); p2 = estrdup(p); if (strcmp(p1, p2) != 0) krb5_errx (context, 1, "krb5_cc_default_name no longer same"); ret = krb5_cc_set_default_name(context, test_cc_name); if (ret) krb5_errx (context, 1, "krb5_cc_set_default_name 1 failed"); p = krb5_cc_default_name(context); if (p == NULL) krb5_errx (context, 1, "krb5_cc_default_name 2 failed"); p3 = estrdup(p); #ifndef KRB5_USE_PATH_TOKENS /* If we are using path tokens, we don't expect the p3 and test_cc_name to match since p3 is going to have expanded tokens. */ if (strcmp(p3, test_cc_name) != 0) krb5_errx (context, 1, "krb5_cc_set_default_name 1 failed"); #endif free(p1); free(p2); free(p3); } /* * Check that a closed cc still keeps it data and that it's no longer * there when it's destroyed. */ static void test_mcache(krb5_context context) { krb5_error_code ret; krb5_ccache id, id2; const char *nc, *tc; char *c; krb5_principal p, p2; ret = krb5_parse_name(context, "lha@SU.SE", &p); if (ret) krb5_err(context, 1, ret, "krb5_parse_name"); ret = krb5_cc_new_unique(context, krb5_cc_type_memory, NULL, &id); if (ret) krb5_err(context, 1, ret, "krb5_cc_new_unique"); ret = krb5_cc_initialize(context, id, p); if (ret) krb5_err(context, 1, ret, "krb5_cc_initialize"); nc = krb5_cc_get_name(context, id); if (nc == NULL) krb5_errx(context, 1, "krb5_cc_get_name"); tc = krb5_cc_get_type(context, id); if (tc == NULL) krb5_errx(context, 1, "krb5_cc_get_name"); if (asprintf(&c, "%s:%s", tc, nc) < 0 || c == NULL) errx(1, "malloc"); krb5_cc_close(context, id); ret = krb5_cc_resolve(context, c, &id2); if (ret) krb5_err(context, 1, ret, "krb5_cc_resolve"); ret = krb5_cc_get_principal(context, id2, &p2); if (ret) krb5_err(context, 1, ret, "krb5_cc_get_principal"); if (krb5_principal_compare(context, p, p2) == FALSE) krb5_errx(context, 1, "p != p2"); krb5_cc_destroy(context, id2); krb5_free_principal(context, p); krb5_free_principal(context, p2); ret = krb5_cc_resolve(context, c, &id2); if (ret) krb5_err(context, 1, ret, "krb5_cc_resolve"); ret = krb5_cc_get_principal(context, id2, &p2); if (ret == 0) krb5_errx(context, 1, "krb5_cc_get_principal"); krb5_cc_destroy(context, id2); free(c); } /* * Test that init works on a destroyed cc. */ static void test_init_vs_destroy(krb5_context context, const char *type) { krb5_error_code ret; krb5_ccache id, id2; krb5_principal p, p2; char *n = NULL; ret = krb5_parse_name(context, "lha@SU.SE", &p); if (ret) krb5_err(context, 1, ret, "krb5_parse_name"); ret = krb5_cc_new_unique(context, type, NULL, &id); if (ret) krb5_err(context, 1, ret, "krb5_cc_new_unique: %s", type); if (asprintf(&n, "%s:%s", krb5_cc_get_type(context, id), krb5_cc_get_name(context, id)) < 0 || n == NULL) errx(1, "malloc"); ret = krb5_cc_resolve(context, n, &id2); free(n); if (ret) krb5_err(context, 1, ret, "krb5_cc_resolve"); krb5_cc_destroy(context, id); ret = krb5_cc_initialize(context, id2, p); if (ret) krb5_err(context, 1, ret, "krb5_cc_initialize"); ret = krb5_cc_get_principal(context, id2, &p2); if (ret) krb5_err(context, 1, ret, "krb5_cc_get_principal"); krb5_cc_destroy(context, id2); krb5_free_principal(context, p); krb5_free_principal(context, p2); } static void test_cache_remove(krb5_context context, const char *type) { krb5_error_code ret; krb5_ccache id; krb5_principal p; krb5_creds cred; ret = krb5_parse_name(context, "lha@SU.SE", &p); if (ret) krb5_err(context, 1, ret, "krb5_parse_name"); ret = krb5_cc_new_unique(context, type, NULL, &id); if (ret) krb5_err(context, 1, ret, "krb5_cc_gen_new: %s", type); ret = krb5_cc_initialize(context, id, p); if (ret) krb5_err(context, 1, ret, "krb5_cc_initialize"); /* */ memset(&cred, 0, sizeof(cred)); ret = krb5_parse_name(context, "krbtgt/SU.SE@SU.SE", &cred.server); if (ret) krb5_err(context, 1, ret, "krb5_parse_name"); ret = krb5_parse_name(context, "lha@SU.SE", &cred.client); if (ret) krb5_err(context, 1, ret, "krb5_parse_name"); ret = krb5_cc_store_cred(context, id, &cred); if (ret) krb5_err(context, 1, ret, "krb5_cc_store_cred"); ret = krb5_cc_remove_cred(context, id, 0, &cred); if (ret) krb5_err(context, 1, ret, "krb5_cc_remove_cred"); ret = krb5_cc_destroy(context, id); if (ret) krb5_err(context, 1, ret, "krb5_cc_destroy"); krb5_free_principal(context, p); krb5_free_principal(context, cred.server); krb5_free_principal(context, cred.client); } static void test_mcc_default(void) { krb5_context context; krb5_error_code ret; krb5_ccache id, id2; int i; for (i = 0; i < 10; i++) { ret = krb5_init_context(&context); if (ret) krb5_err(context, 1, ret, "krb5_init_context"); ret = krb5_cc_set_default_name(context, "MEMORY:foo"); if (ret) krb5_err(context, 1, ret, "krb5_cc_set_default_name"); ret = krb5_cc_default(context, &id); if (ret) krb5_err(context, 1, ret, "krb5_cc_default"); ret = krb5_cc_default(context, &id2); if (ret) krb5_err(context, 1, ret, "krb5_cc_default"); ret = krb5_cc_close(context, id); if (ret) krb5_err(context, 1, ret, "krb5_cc_close"); ret = krb5_cc_close(context, id2); if (ret) krb5_err(context, 1, ret, "krb5_cc_close"); krb5_free_context(context); } } struct { char *str; int fail; char *res; } cc_names[] = { { "foo", 0, "foo" }, { "foo%}", 0, "foo%}" }, { "%{uid}", 0, NULL }, { "foo%{null}", 0, "foo" }, { "foo%{null}bar", 0, "foobar" }, { "%{", 1, NULL }, { "%{foo %{", 1, NULL }, { "%{{", 1, NULL }, { "%{{}", 1, NULL }, { "%{nulll}", 1, NULL }, { "%{does not exist}", 1, NULL }, { "%{}", 1, NULL }, #ifdef KRB5_USE_PATH_TOKENS { "%{APPDATA}", 0, NULL }, { "%{COMMON_APPDATA}", 0, NULL}, { "%{LOCAL_APPDATA}", 0, NULL}, { "%{SYSTEM}", 0, NULL}, { "%{WINDOWS}", 0, NULL}, { "%{TEMP}", 0, NULL}, { "%{USERID}", 0, NULL}, { "%{uid}", 0, NULL}, { "%{USERCONFIG}", 0, NULL}, { "%{COMMONCONFIG}", 0, NULL}, { "%{LIBDIR}", 0, NULL}, { "%{BINDIR}", 0, NULL}, { "%{LIBEXEC}", 0, NULL}, { "%{SBINDIR}", 0, NULL}, #endif }; static void test_def_cc_name(krb5_context context) { krb5_error_code ret; char *str; int i; for (i = 0; i < sizeof(cc_names)/sizeof(cc_names[0]); i++) { ret = _krb5_expand_default_cc_name(context, cc_names[i].str, &str); if (ret) { if (cc_names[i].fail == 0) krb5_errx(context, 1, "test %d \"%s\" failed", i, cc_names[i].str); } else { if (cc_names[i].fail) krb5_errx(context, 1, "test %d \"%s\" was successful", i, cc_names[i].str); if (cc_names[i].res && strcmp(cc_names[i].res, str) != 0) krb5_errx(context, 1, "test %d %s != %s", i, cc_names[i].res, str); if (debug_flag) printf("%s => %s\n", cc_names[i].str, str); free(str); } } } static void test_cache_find(krb5_context context, const char *principal, int find) { krb5_principal client; krb5_error_code ret; krb5_ccache id = NULL; ret = krb5_parse_name(context, principal, &client); if (ret) krb5_err(context, 1, ret, "parse_name for %s failed", principal); ret = krb5_cc_cache_match(context, client, &id); if (ret && find) krb5_err(context, 1, ret, "cc_cache_match for %s failed", principal); if (ret == 0 && !find) krb5_err(context, 1, ret, "cc_cache_match for %s found", principal); if (id) krb5_cc_close(context, id); krb5_free_principal(context, client); } static void test_cache_iter(krb5_context context, const char *type, int destroy) { krb5_cc_cache_cursor cursor; krb5_error_code ret; krb5_ccache id; ret = krb5_cc_cache_get_first (context, type, &cursor); if (ret == KRB5_CC_NOSUPP) return; else if (ret) krb5_err(context, 1, ret, "krb5_cc_cache_get_first(%s)", type); while ((ret = krb5_cc_cache_next (context, cursor, &id)) == 0) { krb5_principal principal; char *name; if (debug_flag) printf("name: %s\n", krb5_cc_get_name(context, id)); ret = krb5_cc_get_principal(context, id, &principal); if (ret == 0) { ret = krb5_unparse_name(context, principal, &name); if (ret == 0) { if (debug_flag) printf("\tprincipal: %s\n", name); free(name); } krb5_free_principal(context, principal); } if (destroy) krb5_cc_destroy(context, id); else krb5_cc_close(context, id); } krb5_cc_cache_end_seq_get(context, cursor); } static void test_cache_iter_all(krb5_context context) { krb5_cccol_cursor cursor; krb5_error_code ret; krb5_ccache id; ret = krb5_cccol_cursor_new (context, &cursor); if (ret) krb5_err(context, 1, ret, "krb5_cccol_cursor_new"); while ((ret = krb5_cccol_cursor_next (context, cursor, &id)) == 0 && id != NULL) { krb5_principal principal; char *name; if (debug_flag) printf("name: %s\n", krb5_cc_get_name(context, id)); ret = krb5_cc_get_principal(context, id, &principal); if (ret == 0) { ret = krb5_unparse_name(context, principal, &name); if (ret == 0) { if (debug_flag) printf("\tprincipal: %s\n", name); free(name); } krb5_free_principal(context, principal); } krb5_cc_close(context, id); } krb5_cccol_cursor_free(context, &cursor); } static void test_copy(krb5_context context, const char *from, const char *to) { krb5_ccache fromid, toid; krb5_error_code ret; krb5_principal p, p2; ret = krb5_parse_name(context, "lha@SU.SE", &p); if (ret) krb5_err(context, 1, ret, "krb5_parse_name"); ret = krb5_cc_new_unique(context, from, NULL, &fromid); if (ret) krb5_err(context, 1, ret, "krb5_cc_new_unique: %s", from); ret = krb5_cc_initialize(context, fromid, p); if (ret) krb5_err(context, 1, ret, "krb5_cc_initialize"); ret = krb5_cc_new_unique(context, to, NULL, &toid); if (ret) krb5_err(context, 1, ret, "krb5_cc_gen_new: %s", to); ret = krb5_cc_copy_cache(context, fromid, toid); if (ret) krb5_err(context, 1, ret, "krb5_cc_copy_cache"); ret = krb5_cc_get_principal(context, toid, &p2); if (ret) krb5_err(context, 1, ret, "krb5_cc_get_principal"); if (krb5_principal_compare(context, p, p2) == FALSE) krb5_errx(context, 1, "p != p2"); krb5_free_principal(context, p); krb5_free_principal(context, p2); krb5_cc_destroy(context, fromid); krb5_cc_destroy(context, toid); } static void test_move(krb5_context context, const char *type) { const krb5_cc_ops *ops; krb5_ccache fromid, toid; krb5_error_code ret; krb5_principal p, p2; ops = krb5_cc_get_prefix_ops(context, type); if (ops == NULL) return; ret = krb5_cc_new_unique(context, type, NULL, &fromid); if (ret == KRB5_CC_NOSUPP) return; else if (ret) krb5_err(context, 1, ret, "krb5_cc_new_unique: %s", type); ret = krb5_parse_name(context, "lha@SU.SE", &p); if (ret) krb5_err(context, 1, ret, "krb5_parse_name"); ret = krb5_cc_initialize(context, fromid, p); if (ret) krb5_err(context, 1, ret, "krb5_cc_initialize"); ret = krb5_cc_new_unique(context, type, NULL, &toid); if (ret) krb5_err(context, 1, ret, "krb5_cc_new_unique"); ret = krb5_cc_initialize(context, toid, p); if (ret) krb5_err(context, 1, ret, "krb5_cc_initialize"); ret = krb5_cc_get_principal(context, toid, &p2); if (ret) krb5_err(context, 1, ret, "krb5_cc_get_principal"); if (krb5_principal_compare(context, p, p2) == FALSE) krb5_errx(context, 1, "p != p2"); krb5_free_principal(context, p); krb5_free_principal(context, p2); krb5_cc_destroy(context, toid); krb5_cc_destroy(context, fromid); } static void test_prefix_ops(krb5_context context, const char *name, const krb5_cc_ops *ops) { const krb5_cc_ops *o; o = krb5_cc_get_prefix_ops(context, name); if (o == NULL) krb5_errx(context, 1, "found no match for prefix '%s'", name); if (strcmp(o->prefix, ops->prefix) != 0) krb5_errx(context, 1, "ops for prefix '%s' is not " "the expected %s != %s", name, o->prefix, ops->prefix); } static void test_cc_config(krb5_context context, const char *cc_type, const char *cc_name, size_t count) { krb5_error_code ret; krb5_principal p; krb5_ccache id; unsigned int i; ret = krb5_cc_new_unique(context, cc_type, cc_name, &id); if (ret) krb5_err(context, 1, ret, "krb5_cc_new_unique"); ret = krb5_parse_name(context, "lha@SU.SE", &p); if (ret) krb5_err(context, 1, ret, "krb5_parse_name"); ret = krb5_cc_initialize(context, id, p); if (ret) krb5_err(context, 1, ret, "krb5_cc_initialize"); for (i = 0; i < count; i++) { krb5_data data, data2; const char *name = "foo"; krb5_principal p1 = NULL; if (i & 1) p1 = p; data.data = rk_UNCONST(name); data.length = strlen(name); /* * Because of how krb5_cc_set_config() this will also test * krb5_cc_remove_cred(). */ ret = krb5_cc_set_config(context, id, p1, "FriendlyName", &data); if (ret) krb5_errx(context, 1, "krb5_cc_set_config: add"); ret = krb5_cc_get_config(context, id, p1, "FriendlyName", &data2); if (ret) krb5_errx(context, 1, "krb5_cc_get_config: first"); if (data.length != data2.length || memcmp(data.data, data2.data, data.length) != 0) krb5_errx(context, 1, "krb5_cc_get_config: did not fetch what was set"); krb5_data_free(&data2); data.data = rk_UNCONST("bar"); data.length = strlen("bar"); ret = krb5_cc_set_config(context, id, p1, "FriendlyName", &data); if (ret) krb5_errx(context, 1, "krb5_cc_set_config: add -second"); ret = krb5_cc_get_config(context, id, p1, "FriendlyName", &data2); if (ret) krb5_errx(context, 1, "krb5_cc_get_config: second"); if (data.length != data2.length || memcmp(data.data, data2.data, data.length) != 0) krb5_errx(context, 1, "krb5_cc_get_config: replace failed"); krb5_data_free(&data2); ret = krb5_cc_set_config(context, id, p1, "FriendlyName", NULL); if (ret) krb5_errx(context, 1, "krb5_cc_set_config: delete"); ret = krb5_cc_get_config(context, id, p1, "FriendlyName", &data2); if (ret == 0) krb5_errx(context, 1, "krb5_cc_get_config: non-existant"); if (data2.length) krb5_errx(context, 1, "krb5_cc_get_config: delete failed"); } krb5_cc_destroy(context, id); krb5_free_principal(context, p); } static struct getargs args[] = { {"debug", 'd', arg_flag, &debug_flag, "turn on debuggin", NULL }, {"version", 0, arg_flag, &version_flag, "print version", NULL }, {"help", 0, arg_flag, &help_flag, NULL, NULL } }; static void usage (int ret) { arg_printusage (args, sizeof(args)/sizeof(*args), NULL, "hostname ..."); exit (ret); } int main(int argc, char **argv) { krb5_context context; krb5_error_code ret; int optidx = 0; krb5_ccache id1, id2; setprogname(argv[0]); if(getarg(args, sizeof(args) / sizeof(args[0]), argc, argv, &optidx)) usage(1); if (help_flag) usage (0); if(version_flag){ print_version(NULL); exit(0); } argc -= optidx; argv += optidx; ret = krb5_init_context(&context); if (ret) errx (1, "krb5_init_context failed: %d", ret); test_cache_remove(context, krb5_cc_type_file); test_cache_remove(context, krb5_cc_type_memory); #ifdef USE_SQLITE test_cache_remove(context, krb5_cc_type_scc); #endif test_default_name(context); test_mcache(context); test_init_vs_destroy(context, krb5_cc_type_memory); test_init_vs_destroy(context, krb5_cc_type_file); #if 0 test_init_vs_destroy(context, krb5_cc_type_api); #endif test_init_vs_destroy(context, krb5_cc_type_scc); test_init_vs_destroy(context, krb5_cc_type_dcc); test_mcc_default(); test_def_cc_name(context); test_cache_iter_all(context); test_cache_iter(context, krb5_cc_type_memory, 0); { krb5_principal p; krb5_cc_new_unique(context, krb5_cc_type_memory, "bar", &id1); krb5_cc_new_unique(context, krb5_cc_type_memory, "baz", &id2); krb5_parse_name(context, "lha@SU.SE", &p); krb5_cc_initialize(context, id1, p); krb5_free_principal(context, p); } test_cache_find(context, "lha@SU.SE", 1); test_cache_find(context, "hulabundulahotentot@SU.SE", 0); test_cache_iter(context, krb5_cc_type_memory, 0); test_cache_iter(context, krb5_cc_type_memory, 1); test_cache_iter(context, krb5_cc_type_memory, 0); test_cache_iter(context, krb5_cc_type_file, 0); test_cache_iter(context, krb5_cc_type_api, 0); test_cache_iter(context, krb5_cc_type_scc, 0); test_cache_iter(context, krb5_cc_type_scc, 1); #if 0 test_cache_iter(context, krb5_cc_type_dcc, 0); test_cache_iter(context, krb5_cc_type_dcc, 1); #endif test_copy(context, krb5_cc_type_file, krb5_cc_type_file); test_copy(context, krb5_cc_type_memory, krb5_cc_type_memory); test_copy(context, krb5_cc_type_file, krb5_cc_type_memory); test_copy(context, krb5_cc_type_memory, krb5_cc_type_file); test_copy(context, krb5_cc_type_scc, krb5_cc_type_file); test_copy(context, krb5_cc_type_file, krb5_cc_type_scc); test_copy(context, krb5_cc_type_scc, krb5_cc_type_memory); test_copy(context, krb5_cc_type_memory, krb5_cc_type_scc); #if 0 test_copy(context, krb5_cc_type_dcc, krb5_cc_type_memory); test_copy(context, krb5_cc_type_dcc, krb5_cc_type_file); test_copy(context, krb5_cc_type_dcc, krb5_cc_type_scc); #endif test_move(context, krb5_cc_type_file); test_move(context, krb5_cc_type_memory); #ifdef HAVE_KCM test_move(context, krb5_cc_type_kcm); #endif test_move(context, krb5_cc_type_scc); #if 0 test_move(context, krb5_cc_type_dcc); #endif test_prefix_ops(context, "FILE:/tmp/foo", &krb5_fcc_ops); test_prefix_ops(context, "FILE", &krb5_fcc_ops); test_prefix_ops(context, "MEMORY", &krb5_mcc_ops); test_prefix_ops(context, "MEMORY:foo", &krb5_mcc_ops); test_prefix_ops(context, "/tmp/kaka", &krb5_fcc_ops); #ifdef HAVE_SCC test_prefix_ops(context, "SCC:", &krb5_scc_ops); test_prefix_ops(context, "SCC:foo", &krb5_scc_ops); #endif #if 0 test_prefix_ops(context, "DIR:", &krb5_dcc_ops); test_prefix_ops(context, "DIR:tkt1", &krb5_dcc_ops); #endif krb5_cc_destroy(context, id1); krb5_cc_destroy(context, id2); test_cc_config(context, "MEMORY", "bar", 1000); /* 1000 because fast */ test_cc_config(context, "FILE", "/tmp/foocc", 30); /* 30 because slower */ krb5_free_context(context); #if 0 sleep(60); #endif return 0; } heimdal-7.5.0/lib/krb5/krb5_get_creds.30000644000175000017500000001243313026237312015633 0ustar niknik.\" Copyright (c) 2006 Kungliga Tekniska Högskolan .\" (Royal Institute of Technology, Stockholm, Sweden). .\" All rights reserved. .\" .\" Redistribution and use in source and binary forms, with or without .\" modification, are permitted provided that the following conditions .\" are met: .\" .\" 1. Redistributions of source code must retain the above copyright .\" notice, this list of conditions and the following disclaimer. .\" .\" 2. Redistributions in binary form must reproduce the above copyright .\" notice, this list of conditions and the following disclaimer in the .\" documentation and/or other materials provided with the distribution. .\" .\" 3. Neither the name of the Institute nor the names of its contributors .\" may be used to endorse or promote products derived from this software .\" without specific prior written permission. .\" .\" THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND .\" ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE .\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE .\" ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE .\" FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL .\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS .\" OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) .\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT .\" LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF .\" SUCH DAMAGE. .\" .\" $Id$ .\" .Dd June 15, 2006 .Dt KRB5_GET_CREDS 3 .Os HEIMDAL .Sh NAME .Nm krb5_get_creds , .Nm krb5_get_creds_opt_add_options , .Nm krb5_get_creds_opt_alloc , .Nm krb5_get_creds_opt_free , .Nm krb5_get_creds_opt_set_enctype , .Nm krb5_get_creds_opt_set_impersonate , .Nm krb5_get_creds_opt_set_options , .Nm krb5_get_creds_opt_set_ticket .Nd get credentials from the KDC .Sh LIBRARY Kerberos 5 Library (libkrb5, -lkrb5) .Sh SYNOPSIS .In krb5.h .Ft krb5_error_code .Fo krb5_get_creds .Fa "krb5_context context" .Fa "krb5_get_creds_opt opt" .Fa "krb5_ccache ccache" .Fa "krb5_const_principal inprinc" .Fa "krb5_creds **out_creds" .Fc .Ft void .Fo krb5_get_creds_opt_add_options .Fa "krb5_context context" .Fa "krb5_get_creds_opt opt" .Fa "krb5_flags options" .Fc .Ft krb5_error_code .Fo krb5_get_creds_opt_alloc .Fa "krb5_context context" .Fa "krb5_get_creds_opt *opt" .Fc .Ft void .Fo krb5_get_creds_opt_free .Fa "krb5_context context" .Fa "krb5_get_creds_opt opt" .Fc .Ft void .Fo krb5_get_creds_opt_set_enctype .Fa "krb5_context context" .Fa "krb5_get_creds_opt opt" .Fa "krb5_enctype enctype" .Fc .Ft krb5_error_code .Fo krb5_get_creds_opt_set_impersonate .Fa "krb5_context context" .Fa "krb5_get_creds_opt opt" .Fa "krb5_const_principal self" .Fc .Ft void .Fo krb5_get_creds_opt_set_options .Fa "krb5_context context" .Fa "krb5_get_creds_opt opt" .Fa "krb5_flags options" .Fc .Ft krb5_error_code .Fo krb5_get_creds_opt_set_ticket .Fa "krb5_context context" .Fa "krb5_get_creds_opt opt" .Fa "const Ticket *ticket" .Fc .Sh DESCRIPTION .Fn krb5_get_creds fetches credentials specified by .Fa opt by first looking in the .Fa ccache , and then it doesn't exists, fetch the credential from the KDC using the krbtgts in .Fa ccache . The credential is returned in .Fa out_creds and should be freed using the function .Fn krb5_free_creds . .Pp The structure .Li krb5_get_creds_opt controls the behavior of .Fn krb5_get_creds . The structure is opaque to consumers that can set the content of the structure with accessors functions. All accessor functions make copies of the data that is passed into accessor functions, so external consumers free the memory before calling .Fn krb5_get_creds . .Pp The structure .Li krb5_get_creds_opt is allocated with .Fn krb5_get_creds_opt_alloc and freed with .Fn krb5_get_creds_opt_free . The free function also frees the content of the structure set by the accessor functions. .Pp .Fn krb5_get_creds_opt_add_options and .Fn krb5_get_creds_opt_set_options adds and sets options to the .Li krb5_get_creds_opt structure . The possible options to set are .Bl -tag -width "KRB5_GC_USER_USER" -compact .It KRB5_GC_CACHED Only check the .Fa ccache , don't got out on network to fetch credential. .It KRB5_GC_USER_USER request a user to user ticket. This options doesn't store the resulting user to user credential in the .Fa ccache . .It KRB5_GC_EXPIRED_OK returns the credential even if it is expired, default behavior is trying to refetch the credential from the KDC. .It KRB5_GC_NO_STORE Do not store the resulting credentials in the .Fa ccache . .El .Pp .Fn krb5_get_creds_opt_set_enctype sets the preferred encryption type of the application. Don't set this unless you have to since if there is no match in the KDC, the function call will fail. .Pp .Fn krb5_get_creds_opt_set_impersonate sets the principal to impersonate., Returns a ticket that have the impersonation principal as a client and the requestor as the service. Note that the requested principal have to be the same as the client principal in the krbtgt. .Pp .Fn krb5_get_creds_opt_set_ticket sets the extra ticket used in user-to-user or contrained delegation use case. .Sh SEE ALSO .Xr krb5 3 , .Xr krb5_get_credentials 3 , .Xr krb5.conf 5 heimdal-7.5.0/lib/krb5/krb5_timeofday.cat30000644000175000017500000000577413212450757016366 0ustar niknik KRB5_TIMEOFDAY(3) BSD Library Functions Manual KRB5_TIMEOFDAY(3) NNAAMMEE kkrrbb55__ttiimmeeooffddaayy, kkrrbb55__sseett__rreeaall__ttiimmee, kkrrbb55__uuss__ttiimmeeooffddaayy, kkrrbb55__ffoorrmmaatt__ttiimmee, kkrrbb55__ssttrriinngg__ttoo__ddeellttaatt -- Kerberos 5 time handling functions LLIIBBRRAARRYY Kerberos 5 Library (libkrb5, -lkrb5) SSYYNNOOPPSSIISS ##iinncclluuddee <> krb5_timestamp; krb5_deltat; _k_r_b_5___e_r_r_o_r___c_o_d_e kkrrbb55__sseett__rreeaall__ttiimmee(_k_r_b_5___c_o_n_t_e_x_t _c_o_n_t_e_x_t, _k_r_b_5___t_i_m_e_s_t_a_m_p _s_e_c, _i_n_t_3_2___t _u_s_e_c); _k_r_b_5___e_r_r_o_r___c_o_d_e kkrrbb55__ttiimmeeooffddaayy(_k_r_b_5___c_o_n_t_e_x_t _c_o_n_t_e_x_t, _k_r_b_5___t_i_m_e_s_t_a_m_p _*_t_i_m_e_r_e_t); _k_r_b_5___e_r_r_o_r___c_o_d_e kkrrbb55__uuss__ttiimmeeooffddaayy(_k_r_b_5___c_o_n_t_e_x_t _c_o_n_t_e_x_t, _k_r_b_5___t_i_m_e_s_t_a_m_p _*_s_e_c, _i_n_t_3_2___t _*_u_s_e_c); _k_r_b_5___e_r_r_o_r___c_o_d_e kkrrbb55__ffoorrmmaatt__ttiimmee(_k_r_b_5___c_o_n_t_e_x_t _c_o_n_t_e_x_t, _t_i_m_e___t _t, _c_h_a_r _*_s, _s_i_z_e___t _l_e_n, _k_r_b_5___b_o_o_l_e_a_n _i_n_c_l_u_d_e___t_i_m_e); _k_r_b_5___e_r_r_o_r___c_o_d_e kkrrbb55__ssttrriinngg__ttoo__ddeellttaatt(_c_o_n_s_t _c_h_a_r _*_s_t_r_i_n_g, _k_r_b_5___d_e_l_t_a_t _*_d_e_l_t_a_t); DDEESSCCRRIIPPTTIIOONN kkrrbb55__sseett__rreeaall__ttiimmee sets the absolute time that the caller knows the KDC has. With this the Kerberos library can calculate the relative differ- ence between the KDC time and the local system time and store it in the _c_o_n_t_e_x_t. With this information the Kerberos library can adjust all time stamps in Kerberos packages. kkrrbb55__ttiimmeeooffddaayy() returns the current time, but adjusted with the time difference between the local host and the KDC. kkrrbb55__uuss__ttiimmeeooffddaayy() also returns microseconds. kkrrbb55__ffoorrmmaatt__ttiimmee formats the time _t into the string _s of length _l_e_n. If _i_n_c_l_u_d_e___t_i_m_e is set, the time is set include_time. kkrrbb55__ssttrriinngg__ttoo__ddeellttaatt parses delta time _s_t_r_i_n_g into _d_e_l_t_a_t. SSEEEE AALLSSOO gettimeofday(2), krb5(3) HEIMDAL September 16, 2006 HEIMDAL heimdal-7.5.0/lib/krb5/send_to_kdc.c0000644000175000017500000007410013212137553015307 0ustar niknik/* * Copyright (c) 1997 - 2002 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Portions Copyright (c) 2010 - 2013 Apple Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "krb5_locl.h" #include "send_to_kdc_plugin.h" /** * @section send_to_kdc Locating and sending packets to the KDC * * The send to kdc code is responsible to request the list of KDC from * the locate-kdc subsystem and then send requests to each of them. * * - Each second a new hostname is tried. * - If the hostname have several addresses, the first will be tried * directly then in turn the other will be tried every 3 seconds * (host_timeout). * - UDP requests are tried 3 times, and it tried with a individual timeout of kdc_timeout / 3. * - TCP and HTTP requests are tried 1 time. * * Total wait time shorter then (number of addresses * 3) + kdc_timeout seconds. * */ static int init_port(const char *s, int fallback) { int tmp; if (s && sscanf(s, "%d", &tmp) == 1) return htons(tmp); return fallback; } struct send_via_plugin_s { krb5_const_realm realm; krb5_krbhst_info *hi; time_t timeout; const krb5_data *send_data; krb5_data *receive; }; static krb5_error_code KRB5_LIB_CALL kdccallback(krb5_context context, const void *plug, void *plugctx, void *userctx) { const krb5plugin_send_to_kdc_ftable *service = (const krb5plugin_send_to_kdc_ftable *)plug; struct send_via_plugin_s *ctx = userctx; if (service->send_to_kdc == NULL) return KRB5_PLUGIN_NO_HANDLE; return service->send_to_kdc(context, plugctx, ctx->hi, ctx->timeout, ctx->send_data, ctx->receive); } static krb5_error_code KRB5_LIB_CALL realmcallback(krb5_context context, const void *plug, void *plugctx, void *userctx) { const krb5plugin_send_to_kdc_ftable *service = (const krb5plugin_send_to_kdc_ftable *)plug; struct send_via_plugin_s *ctx = userctx; if (service->send_to_realm == NULL) return KRB5_PLUGIN_NO_HANDLE; return service->send_to_realm(context, plugctx, ctx->realm, ctx->timeout, ctx->send_data, ctx->receive); } static krb5_error_code kdc_via_plugin(krb5_context context, krb5_krbhst_info *hi, time_t timeout, const krb5_data *send_data, krb5_data *receive) { struct send_via_plugin_s userctx; userctx.realm = NULL; userctx.hi = hi; userctx.timeout = timeout; userctx.send_data = send_data; userctx.receive = receive; return _krb5_plugin_run_f(context, "krb5", KRB5_PLUGIN_SEND_TO_KDC, KRB5_PLUGIN_SEND_TO_KDC_VERSION_0, 0, &userctx, kdccallback); } static krb5_error_code realm_via_plugin(krb5_context context, krb5_const_realm realm, time_t timeout, const krb5_data *send_data, krb5_data *receive) { struct send_via_plugin_s userctx; userctx.realm = realm; userctx.hi = NULL; userctx.timeout = timeout; userctx.send_data = send_data; userctx.receive = receive; return _krb5_plugin_run_f(context, "krb5", KRB5_PLUGIN_SEND_TO_KDC, KRB5_PLUGIN_SEND_TO_KDC_VERSION_2, 0, &userctx, realmcallback); } struct krb5_sendto_ctx_data { int flags; int type; krb5_sendto_ctx_func func; void *data; char *hostname; krb5_krbhst_handle krbhst; /* context2 */ const krb5_data *send_data; krb5_data response; heim_array_t hosts; int stateflags; #define KRBHST_COMPLETED 1 /* prexmit */ krb5_sendto_prexmit prexmit_func; void *prexmit_ctx; /* stats */ struct { struct timeval start_time; struct timeval name_resolution; struct timeval krbhst; unsigned long sent_packets; unsigned long num_hosts; } stats; unsigned int stid; }; static void dealloc_sendto_ctx(void *ptr) { krb5_sendto_ctx ctx = (krb5_sendto_ctx)ptr; if (ctx->hostname) free(ctx->hostname); heim_release(ctx->hosts); heim_release(ctx->krbhst); } KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_sendto_ctx_alloc(krb5_context context, krb5_sendto_ctx *ctx) { *ctx = heim_alloc(sizeof(**ctx), "sendto-context", dealloc_sendto_ctx); if (*ctx == NULL) return krb5_enomem(context); (*ctx)->hosts = heim_array_create(); return 0; } KRB5_LIB_FUNCTION void KRB5_LIB_CALL krb5_sendto_ctx_add_flags(krb5_sendto_ctx ctx, int flags) { ctx->flags |= flags; } KRB5_LIB_FUNCTION int KRB5_LIB_CALL krb5_sendto_ctx_get_flags(krb5_sendto_ctx ctx) { return ctx->flags; } KRB5_LIB_FUNCTION void KRB5_LIB_CALL krb5_sendto_ctx_set_type(krb5_sendto_ctx ctx, int type) { ctx->type = type; } KRB5_LIB_FUNCTION void KRB5_LIB_CALL krb5_sendto_ctx_set_func(krb5_sendto_ctx ctx, krb5_sendto_ctx_func func, void *data) { ctx->func = func; ctx->data = data; } KRB5_LIB_FUNCTION void KRB5_LIB_CALL _krb5_sendto_ctx_set_prexmit(krb5_sendto_ctx ctx, krb5_sendto_prexmit prexmit, void *data) { ctx->prexmit_func = prexmit; ctx->prexmit_ctx = data; } KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_sendto_set_hostname(krb5_context context, krb5_sendto_ctx ctx, const char *hostname) { if (ctx->hostname == NULL) free(ctx->hostname); ctx->hostname = strdup(hostname); if (ctx->hostname == NULL) { krb5_set_error_message(context, ENOMEM, N_("malloc: out of memory", "")); return ENOMEM; } return 0; } KRB5_LIB_FUNCTION void KRB5_LIB_CALL _krb5_sendto_ctx_set_krb5hst(krb5_context context, krb5_sendto_ctx ctx, krb5_krbhst_handle handle) { heim_release(ctx->krbhst); ctx->krbhst = heim_retain(handle); } KRB5_LIB_FUNCTION void KRB5_LIB_CALL krb5_sendto_ctx_free(krb5_context context, krb5_sendto_ctx ctx) { heim_release(ctx); } KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL _krb5_kdc_retry(krb5_context context, krb5_sendto_ctx ctx, void *data, const krb5_data *reply, int *action) { krb5_error_code ret; KRB_ERROR error; if(krb5_rd_error(context, reply, &error)) return 0; ret = krb5_error_from_rd_error(context, &error, NULL); krb5_free_error_contents(context, &error); switch(ret) { case KRB5KRB_ERR_RESPONSE_TOO_BIG: { if (krb5_sendto_ctx_get_flags(ctx) & KRB5_KRBHST_FLAGS_LARGE_MSG) break; krb5_sendto_ctx_add_flags(ctx, KRB5_KRBHST_FLAGS_LARGE_MSG); *action = KRB5_SENDTO_RESET; break; } case KRB5KDC_ERR_SVC_UNAVAILABLE: *action = KRB5_SENDTO_CONTINUE; break; } return 0; } /* * */ struct host; struct host_fun { krb5_error_code (*prepare)(krb5_context, struct host *, const krb5_data *); krb5_error_code (*send_fn)(krb5_context, struct host *); krb5_error_code (*recv_fn)(krb5_context, struct host *, krb5_data *); int ntries; }; struct host { enum host_state { CONNECT, CONNECTING, CONNECTED, WAITING_REPLY, DEAD } state; krb5_krbhst_info *hi; struct addrinfo *ai; rk_socket_t fd; struct host_fun *fun; unsigned int tries; time_t timeout; krb5_data data; unsigned int tid; }; static void debug_host(krb5_context context, int level, struct host *host, const char *fmt, ...) __attribute__ ((__format__ (__printf__, 4, 5))); static void debug_host(krb5_context context, int level, struct host *host, const char *fmt, ...) { const char *proto = "unknown"; char name[NI_MAXHOST], port[NI_MAXSERV]; char *text = NULL; va_list ap; int ret; if (!_krb5_have_debug(context, 5)) return; va_start(ap, fmt); ret = vasprintf(&text, fmt, ap); va_end(ap); if (ret == -1 || text == NULL) return; if (host->hi->proto == KRB5_KRBHST_HTTP) proto = "http"; else if (host->hi->proto == KRB5_KRBHST_TCP) proto = "tcp"; else if (host->hi->proto == KRB5_KRBHST_UDP) proto = "udp"; if (getnameinfo(host->ai->ai_addr, host->ai->ai_addrlen, name, sizeof(name), port, sizeof(port), NI_NUMERICHOST) != 0) name[0] = '\0'; _krb5_debug(context, level, "%s: %s %s:%s (%s) tid: %08x", text, proto, name, port, host->hi->hostname, host->tid); free(text); } static void deallocate_host(void *ptr) { struct host *host = ptr; if (!rk_IS_BAD_SOCKET(host->fd)) rk_closesocket(host->fd); krb5_data_free(&host->data); host->ai = NULL; } static void host_dead(krb5_context context, struct host *host, const char *msg) { debug_host(context, 5, host, "%s", msg); rk_closesocket(host->fd); host->fd = rk_INVALID_SOCKET; host->state = DEAD; } static krb5_error_code send_stream(krb5_context context, struct host *host) { ssize_t len; len = krb5_net_write(context, &host->fd, host->data.data, host->data.length); if (len < 0) return errno; else if (len < host->data.length) { host->data.length -= len; memmove(host->data.data, ((uint8_t *)host->data.data) + len, host->data.length - len); return -1; } else { krb5_data_free(&host->data); return 0; } } static krb5_error_code recv_stream(krb5_context context, struct host *host) { krb5_error_code ret; size_t oldlen; ssize_t sret; int nbytes; if (rk_SOCK_IOCTL(host->fd, FIONREAD, &nbytes) != 0 || nbytes <= 0) return HEIM_NET_CONN_REFUSED; if (context->max_msg_size - host->data.length < nbytes) { krb5_set_error_message(context, KRB5KRB_ERR_FIELD_TOOLONG, N_("TCP message from KDC too large %d", ""), (int)(host->data.length + nbytes)); return KRB5KRB_ERR_FIELD_TOOLONG; } oldlen = host->data.length; ret = krb5_data_realloc(&host->data, oldlen + nbytes + 1 /* NUL */); if (ret) return ret; sret = krb5_net_read(context, &host->fd, ((uint8_t *)host->data.data) + oldlen, nbytes); if (sret <= 0) { ret = errno; return ret; } host->data.length = oldlen + sret; /* zero terminate for http transport */ ((uint8_t *)host->data.data)[host->data.length] = '\0'; return 0; } /* * */ static void host_next_timeout(krb5_context context, struct host *host) { host->timeout = context->kdc_timeout / host->fun->ntries; if (host->timeout == 0) host->timeout = 1; host->timeout += time(NULL); } /* * connected host */ static void host_connected(krb5_context context, krb5_sendto_ctx ctx, struct host *host) { krb5_error_code ret; host->state = CONNECTED; /* * Now prepare data to send to host */ if (ctx->prexmit_func) { krb5_data data; krb5_data_zero(&data); ret = ctx->prexmit_func(context, host->hi->proto, ctx->prexmit_ctx, host->fd, &data); if (ret == 0) { if (data.length == 0) { host_dead(context, host, "prexmit function didn't send data"); return; } ret = host->fun->prepare(context, host, &data); krb5_data_free(&data); } } else { ret = host->fun->prepare(context, host, ctx->send_data); } if (ret) debug_host(context, 5, host, "failed to prexmit/prepare"); } /* * connect host */ static void host_connect(krb5_context context, krb5_sendto_ctx ctx, struct host *host) { krb5_krbhst_info *hi = host->hi; struct addrinfo *ai = host->ai; debug_host(context, 5, host, "connecting to host"); if (connect(host->fd, ai->ai_addr, ai->ai_addrlen) < 0) { #ifdef HAVE_WINSOCK if (WSAGetLastError() == WSAEWOULDBLOCK) errno = EINPROGRESS; #endif /* HAVE_WINSOCK */ if (errno == EINPROGRESS && (hi->proto == KRB5_KRBHST_HTTP || hi->proto == KRB5_KRBHST_TCP)) { debug_host(context, 5, host, "connecting to %d", host->fd); host->state = CONNECTING; } else { host_dead(context, host, "failed to connect"); } } else { host_connected(context, ctx, host); } host_next_timeout(context, host); } /* * HTTP transport */ static krb5_error_code prepare_http(krb5_context context, struct host *host, const krb5_data *data) { char *str = NULL, *request = NULL; krb5_error_code ret; int len; heim_assert(host->data.length == 0, "prepare_http called twice"); len = rk_base64_encode(data->data, data->length, &str); if(len < 0) return ENOMEM; if (context->http_proxy) ret = asprintf(&request, "GET http://%s/%s HTTP/1.0\r\n\r\n", host->hi->hostname, str); else ret = asprintf(&request, "GET /%s HTTP/1.0\r\n\r\n", str); free(str); if(ret < 0 || request == NULL) return ENOMEM; host->data.data = request; host->data.length = strlen(request); return 0; } static krb5_error_code recv_http(krb5_context context, struct host *host, krb5_data *data) { krb5_error_code ret; unsigned long rep_len; size_t len; char *p; /* * recv_stream returns a NUL terminated stream */ ret = recv_stream(context, host); if (ret) return ret; p = strstr(host->data.data, "\r\n\r\n"); if (p == NULL) return -1; p += 4; len = host->data.length - (p - (char *)host->data.data); if (len < 4) return -1; _krb5_get_int(p, &rep_len, 4); if (len < rep_len) return -1; p += 4; memmove(host->data.data, p, rep_len); host->data.length = rep_len; *data = host->data; krb5_data_zero(&host->data); return 0; } /* * TCP transport */ static krb5_error_code prepare_tcp(krb5_context context, struct host *host, const krb5_data *data) { krb5_error_code ret; krb5_storage *sp; heim_assert(host->data.length == 0, "prepare_tcp called twice"); sp = krb5_storage_emem(); if (sp == NULL) return ENOMEM; ret = krb5_store_data(sp, *data); if (ret) { krb5_storage_free(sp); return ret; } ret = krb5_storage_to_data(sp, &host->data); krb5_storage_free(sp); return ret; } static krb5_error_code recv_tcp(krb5_context context, struct host *host, krb5_data *data) { krb5_error_code ret; unsigned long pktlen; ret = recv_stream(context, host); if (ret) return ret; if (host->data.length < 4) return -1; _krb5_get_int(host->data.data, &pktlen, 4); if (pktlen > host->data.length - 4) return -1; memmove(host->data.data, ((uint8_t *)host->data.data) + 4, host->data.length - 4); host->data.length -= 4; *data = host->data; krb5_data_zero(&host->data); return 0; } /* * UDP transport */ static krb5_error_code prepare_udp(krb5_context context, struct host *host, const krb5_data *data) { return krb5_data_copy(&host->data, data->data, data->length); } static krb5_error_code send_udp(krb5_context context, struct host *host) { if (send(host->fd, host->data.data, host->data.length, 0) < 0) return errno; return 0; } static krb5_error_code recv_udp(krb5_context context, struct host *host, krb5_data *data) { krb5_error_code ret; int nbytes; if (rk_SOCK_IOCTL(host->fd, FIONREAD, &nbytes) != 0 || nbytes <= 0) return HEIM_NET_CONN_REFUSED; if (context->max_msg_size < nbytes) { krb5_set_error_message(context, KRB5KRB_ERR_FIELD_TOOLONG, N_("UDP message from KDC too large %d", ""), (int)nbytes); return KRB5KRB_ERR_FIELD_TOOLONG; } ret = krb5_data_alloc(data, nbytes); if (ret) return ret; ret = recv(host->fd, data->data, data->length, 0); if (ret < 0) { ret = errno; krb5_data_free(data); return ret; } data->length = ret; return 0; } static struct host_fun http_fun = { prepare_http, send_stream, recv_http, 1 }; static struct host_fun tcp_fun = { prepare_tcp, send_stream, recv_tcp, 1 }; static struct host_fun udp_fun = { prepare_udp, send_udp, recv_udp, 3 }; /* * Host state machine */ static int eval_host_state(krb5_context context, krb5_sendto_ctx ctx, struct host *host, int readable, int writeable) { krb5_error_code ret; if (host->state == CONNECT) { /* check if its this host time to connect */ if (host->timeout < time(NULL)) host_connect(context, ctx, host); return 0; } if (host->state == CONNECTING && writeable) host_connected(context, ctx, host); if (readable) { debug_host(context, 5, host, "reading packet"); ret = host->fun->recv_fn(context, host, &ctx->response); if (ret == -1) { /* not done yet */ } else if (ret == 0) { /* if recv_foo function returns 0, we have a complete reply */ debug_host(context, 5, host, "host completed"); return 1; } else { host_dead(context, host, "host disconnected"); } } /* check if there is anything to send, state might DEAD after read */ if (writeable && host->state == CONNECTED) { ctx->stats.sent_packets++; debug_host(context, 5, host, "writing packet"); ret = host->fun->send_fn(context, host); if (ret == -1) { /* not done yet */ } else if (ret) { host_dead(context, host, "host dead, write failed"); } else host->state = WAITING_REPLY; } return 0; } /* * */ static krb5_error_code submit_request(krb5_context context, krb5_sendto_ctx ctx, krb5_krbhst_info *hi) { unsigned long submitted_host = 0; krb5_boolean freeai = FALSE; struct timeval nrstart, nrstop; krb5_error_code ret; struct addrinfo *ai = NULL, *a; struct host *host; ret = kdc_via_plugin(context, hi, context->kdc_timeout, ctx->send_data, &ctx->response); if (ret == 0) { return 0; } else if (ret != KRB5_PLUGIN_NO_HANDLE) { _krb5_debug(context, 5, "send via plugin failed %s: %d", hi->hostname, ret); return ret; } /* * If we have a proxy, let use the address of the proxy instead of * the KDC and let the proxy deal with the resolving of the KDC. */ gettimeofday(&nrstart, NULL); if (hi->proto == KRB5_KRBHST_HTTP && context->http_proxy) { char *proxy2 = strdup(context->http_proxy); char *el, *proxy = proxy2; struct addrinfo hints; char portstr[NI_MAXSERV]; unsigned short nport; if (proxy == NULL) return ENOMEM; if (strncmp(proxy, "http://", 7) == 0) proxy += 7; /* check for url terminating slash */ el = strchr(proxy, '/'); if (el != NULL) *el = '\0'; /* check for port in hostname, used below as port */ el = strchr(proxy, ':'); if(el != NULL) *el++ = '\0'; memset(&hints, 0, sizeof(hints)); hints.ai_family = PF_UNSPEC; hints.ai_socktype = SOCK_STREAM; /* On some systems ntohs(foo(..., htons(...))) causes shadowing */ nport = init_port(el, htons(80)); snprintf(portstr, sizeof(portstr), "%d", ntohs(nport)); ret = getaddrinfo(proxy, portstr, &hints, &ai); free(proxy2); if (ret) return krb5_eai_to_heim_errno(ret, errno); freeai = TRUE; } else { ret = krb5_krbhst_get_addrinfo(context, hi, &ai); if (ret) return ret; } /* add up times */ gettimeofday(&nrstop, NULL); timevalsub(&nrstop, &nrstart); timevaladd(&ctx->stats.name_resolution, &nrstop); ctx->stats.num_hosts++; for (a = ai; a != NULL; a = a->ai_next) { rk_socket_t fd; fd = socket(a->ai_family, a->ai_socktype | SOCK_CLOEXEC, a->ai_protocol); if (rk_IS_BAD_SOCKET(fd)) continue; rk_cloexec(fd); #ifndef NO_LIMIT_FD_SETSIZE if (fd >= FD_SETSIZE) { _krb5_debug(context, 0, "fd too large for select"); rk_closesocket(fd); continue; } #endif socket_set_nonblocking(fd, 1); host = heim_alloc(sizeof(*host), "sendto-host", deallocate_host); if (host == NULL) { if (freeai) freeaddrinfo(ai); rk_closesocket(fd); return ENOMEM; } host->hi = hi; host->fd = fd; host->ai = a; /* next version of stid */ host->tid = ctx->stid = (ctx->stid & 0xffff0000) | ((ctx->stid & 0xffff) + 1); host->state = CONNECT; switch (host->hi->proto) { case KRB5_KRBHST_HTTP : host->fun = &http_fun; break; case KRB5_KRBHST_TCP : host->fun = &tcp_fun; break; case KRB5_KRBHST_UDP : host->fun = &udp_fun; break; default: heim_abort("undefined http transport protocol: %d", (int)host->hi->proto); } host->tries = host->fun->ntries; /* * Connect directly next host, wait a host_timeout for each next address */ if (submitted_host == 0) host_connect(context, ctx, host); else { debug_host(context, 5, host, "Queuing host in future (in %ds), its the %lu address on the same name", (int)(context->host_timeout * submitted_host), submitted_host + 1); host->timeout = time(NULL) + (submitted_host * context->host_timeout); } heim_array_append_value(ctx->hosts, host); heim_release(host); submitted_host++; } if (freeai) freeaddrinfo(ai); if (!submitted_host) return KRB5_KDC_UNREACH; return 0; } struct wait_ctx { krb5_context context; krb5_sendto_ctx ctx; fd_set rfds; fd_set wfds; unsigned max_fd; int got_reply; time_t timenow; }; static void wait_setup(heim_object_t obj, void *iter_ctx, int *stop) { struct wait_ctx *wait_ctx = iter_ctx; struct host *h = (struct host *)obj; /* skip dead hosts */ if (h->state == DEAD) return; if (h->state == CONNECT) { if (h->timeout < wait_ctx->timenow) host_connect(wait_ctx->context, wait_ctx->ctx, h); return; } /* if host timed out, dec tries and (retry or kill host) */ if (h->timeout < wait_ctx->timenow) { heim_assert(h->tries != 0, "tries should not reach 0"); h->tries--; if (h->tries == 0) { host_dead(wait_ctx->context, h, "host timed out"); return; } else { debug_host(wait_ctx->context, 5, h, "retrying sending to"); host_next_timeout(wait_ctx->context, h); host_connected(wait_ctx->context, wait_ctx->ctx, h); } } #ifndef NO_LIMIT_FD_SETSIZE heim_assert(h->fd < FD_SETSIZE, "fd too large"); #endif switch (h->state) { case WAITING_REPLY: FD_SET(h->fd, &wait_ctx->rfds); break; case CONNECTING: case CONNECTED: FD_SET(h->fd, &wait_ctx->rfds); FD_SET(h->fd, &wait_ctx->wfds); break; default: heim_abort("invalid sendto host state"); } if (h->fd > wait_ctx->max_fd) wait_ctx->max_fd = h->fd; } static int wait_filter_dead(heim_object_t obj, void *ctx) { struct host *h = (struct host *)obj; return (int)((h->state == DEAD) ? true : false); } static void wait_process(heim_object_t obj, void *ctx, int *stop) { struct wait_ctx *wait_ctx = ctx; struct host *h = (struct host *)obj; int readable, writeable; heim_assert(h->state != DEAD, "dead host resurected"); #ifndef NO_LIMIT_FD_SETSIZE heim_assert(h->fd < FD_SETSIZE, "fd too large"); #endif readable = FD_ISSET(h->fd, &wait_ctx->rfds); writeable = FD_ISSET(h->fd, &wait_ctx->wfds); if (readable || writeable || h->state == CONNECT) wait_ctx->got_reply |= eval_host_state(wait_ctx->context, wait_ctx->ctx, h, readable, writeable); /* if there is already a reply, just fall though the array */ if (wait_ctx->got_reply) *stop = 1; } static krb5_error_code wait_response(krb5_context context, int *action, krb5_sendto_ctx ctx) { struct wait_ctx wait_ctx; struct timeval tv; int ret; wait_ctx.context = context; wait_ctx.ctx = ctx; FD_ZERO(&wait_ctx.rfds); FD_ZERO(&wait_ctx.wfds); wait_ctx.max_fd = 0; /* oh, we have a reply, it must be a plugin that got it for us */ if (ctx->response.length) { *action = KRB5_SENDTO_FILTER; return 0; } wait_ctx.timenow = time(NULL); heim_array_iterate_f(ctx->hosts, &wait_ctx, wait_setup); heim_array_filter_f(ctx->hosts, &wait_ctx, wait_filter_dead); if (heim_array_get_length(ctx->hosts) == 0) { if (ctx->stateflags & KRBHST_COMPLETED) { _krb5_debug(context, 5, "no more hosts to send/recv packets to/from " "trying to pulling more hosts"); *action = KRB5_SENDTO_FAILED; } else { _krb5_debug(context, 5, "no more hosts to send/recv packets to/from " "and no more hosts -> failure"); *action = KRB5_SENDTO_TIMEOUT; } return 0; } tv.tv_sec = 1; tv.tv_usec = 0; ret = select(wait_ctx.max_fd + 1, &wait_ctx.rfds, &wait_ctx.wfds, NULL, &tv); if (ret < 0) return errno; if (ret == 0) { *action = KRB5_SENDTO_TIMEOUT; return 0; } wait_ctx.got_reply = 0; heim_array_iterate_f(ctx->hosts, &wait_ctx, wait_process); if (wait_ctx.got_reply) *action = KRB5_SENDTO_FILTER; else *action = KRB5_SENDTO_CONTINUE; return 0; } static void reset_context(krb5_context context, krb5_sendto_ctx ctx) { krb5_data_free(&ctx->response); heim_release(ctx->hosts); ctx->hosts = heim_array_create(); ctx->stateflags = 0; } /* * */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_sendto_context(krb5_context context, krb5_sendto_ctx ctx, const krb5_data *send_data, krb5_const_realm realm, krb5_data *receive) { krb5_error_code ret = 0; krb5_krbhst_handle handle = NULL; struct timeval nrstart, nrstop, stop_time; int type, freectx = 0; int action; int numreset = 0; krb5_data_zero(receive); if (ctx == NULL) { ret = krb5_sendto_ctx_alloc(context, &ctx); if (ret) goto out; freectx = 1; } ctx->stid = (context->num_kdc_requests++) << 16; memset(&ctx->stats, 0, sizeof(ctx->stats)); gettimeofday(&ctx->stats.start_time, NULL); type = ctx->type; if (type == 0) { if ((ctx->flags & KRB5_KRBHST_FLAGS_MASTER) || context->use_admin_kdc) type = KRB5_KRBHST_ADMIN; else type = KRB5_KRBHST_KDC; } ctx->send_data = send_data; if ((int)send_data->length > context->large_msg_size) ctx->flags |= KRB5_KRBHST_FLAGS_LARGE_MSG; /* loop until we get back a appropriate response */ action = KRB5_SENDTO_INITIAL; while (action != KRB5_SENDTO_DONE && action != KRB5_SENDTO_FAILED) { krb5_krbhst_info *hi; switch (action) { case KRB5_SENDTO_INITIAL: ret = realm_via_plugin(context, realm, context->kdc_timeout, send_data, &ctx->response); if (ret == 0 || ret != KRB5_PLUGIN_NO_HANDLE) { action = KRB5_SENDTO_DONE; break; } action = KRB5_SENDTO_KRBHST; /* FALLTHOUGH */ case KRB5_SENDTO_KRBHST: if (ctx->krbhst == NULL) { ret = krb5_krbhst_init_flags(context, realm, type, ctx->flags, &handle); if (ret) goto out; if (ctx->hostname) { ret = krb5_krbhst_set_hostname(context, handle, ctx->hostname); if (ret) goto out; } } else { handle = heim_retain(ctx->krbhst); } action = KRB5_SENDTO_TIMEOUT; /* FALLTHOUGH */ case KRB5_SENDTO_TIMEOUT: /* * If we completed, just got to next step */ if (ctx->stateflags & KRBHST_COMPLETED) { action = KRB5_SENDTO_CONTINUE; break; } /* * Pull out next host, if there is no more, close the * handle and mark as completed. * * Collect time spent in krbhst (dns, plugin, etc) */ gettimeofday(&nrstart, NULL); ret = krb5_krbhst_next(context, handle, &hi); gettimeofday(&nrstop, NULL); timevalsub(&nrstop, &nrstart); timevaladd(&ctx->stats.krbhst, &nrstop); action = KRB5_SENDTO_CONTINUE; if (ret == 0) { _krb5_debug(context, 5, "submissing new requests to new host"); if (submit_request(context, ctx, hi) != 0) action = KRB5_SENDTO_TIMEOUT; } else { _krb5_debug(context, 5, "out of hosts, waiting for replies"); ctx->stateflags |= KRBHST_COMPLETED; } break; case KRB5_SENDTO_CONTINUE: ret = wait_response(context, &action, ctx); if (ret) goto out; break; case KRB5_SENDTO_RESET: /* start over */ _krb5_debug(context, 5, "krb5_sendto trying over again (reset): %d", numreset); reset_context(context, ctx); if (handle) { krb5_krbhst_free(context, handle); handle = NULL; } numreset++; if (numreset >= 3) action = KRB5_SENDTO_FAILED; else action = KRB5_SENDTO_KRBHST; break; case KRB5_SENDTO_FILTER: /* default to next state, the filter function might modify this */ action = KRB5_SENDTO_DONE; if (ctx->func) { ret = (*ctx->func)(context, ctx, ctx->data, &ctx->response, &action); if (ret) goto out; } break; case KRB5_SENDTO_FAILED: ret = KRB5_KDC_UNREACH; break; case KRB5_SENDTO_DONE: ret = 0; break; default: heim_abort("invalid krb5_sendto_context state"); } } out: gettimeofday(&stop_time, NULL); timevalsub(&stop_time, &ctx->stats.start_time); if (ret == 0 && ctx->response.length) { *receive = ctx->response; krb5_data_zero(&ctx->response); } else { krb5_data_free(&ctx->response); krb5_clear_error_message (context); ret = KRB5_KDC_UNREACH; krb5_set_error_message(context, ret, N_("unable to reach any KDC in realm %s", ""), realm); } _krb5_debug(context, 1, "%s %s done: %d hosts: %lu packets: %lu" " wc: %lld.%06lu nr: %lld.%06lu kh: %lld.%06lu tid: %08x", __func__, realm, ret, ctx->stats.num_hosts, ctx->stats.sent_packets, (long long)stop_time.tv_sec, (unsigned long)stop_time.tv_usec, (long long)ctx->stats.name_resolution.tv_sec, (unsigned long)ctx->stats.name_resolution.tv_usec, (long long)ctx->stats.krbhst.tv_sec, (unsigned long)ctx->stats.krbhst.tv_usec, ctx->stid); if (freectx) krb5_sendto_ctx_free(context, ctx); else reset_context(context, ctx); if (handle) krb5_krbhst_free(context, handle); return ret; } heimdal-7.5.0/lib/krb5/mk_priv.c0000644000175000017500000001074713026237312014506 0ustar niknik/* * Copyright (c) 1997 - 2003 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "krb5_locl.h" KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_mk_priv(krb5_context context, krb5_auth_context auth_context, const krb5_data *userdata, krb5_data *outbuf, krb5_replay_data *outdata) { krb5_error_code ret; KRB_PRIV s; EncKrbPrivPart part; u_char *buf = NULL; size_t buf_size; size_t len = 0; krb5_crypto crypto; krb5_keyblock *key; krb5_replay_data rdata; if ((auth_context->flags & (KRB5_AUTH_CONTEXT_RET_TIME | KRB5_AUTH_CONTEXT_RET_SEQUENCE)) && outdata == NULL) return KRB5_RC_REQUIRED; /* XXX better error, MIT returns this */ if (auth_context->local_subkey) key = auth_context->local_subkey; else if (auth_context->remote_subkey) key = auth_context->remote_subkey; else key = auth_context->keyblock; memset(&rdata, 0, sizeof(rdata)); part.user_data = *userdata; krb5_us_timeofday (context, &rdata.timestamp, &rdata.usec); if (auth_context->flags & KRB5_AUTH_CONTEXT_DO_TIME) { part.timestamp = &rdata.timestamp; part.usec = &rdata.usec; } else { part.timestamp = NULL; part.usec = NULL; } if (auth_context->flags & KRB5_AUTH_CONTEXT_RET_TIME) { outdata->timestamp = rdata.timestamp; outdata->usec = rdata.usec; } if (auth_context->flags & KRB5_AUTH_CONTEXT_DO_SEQUENCE) { rdata.seq = auth_context->local_seqnumber; part.seq_number = &rdata.seq; } else part.seq_number = NULL; if (auth_context->flags & KRB5_AUTH_CONTEXT_RET_SEQUENCE) outdata->seq = auth_context->local_seqnumber; part.s_address = auth_context->local_address; part.r_address = auth_context->remote_address; krb5_data_zero (&s.enc_part.cipher); ASN1_MALLOC_ENCODE(EncKrbPrivPart, buf, buf_size, &part, &len, ret); if (ret) goto fail; if (buf_size != len) krb5_abortx(context, "internal error in ASN.1 encoder"); s.pvno = 5; s.msg_type = krb_priv; s.enc_part.etype = key->keytype; s.enc_part.kvno = NULL; ret = krb5_crypto_init(context, key, 0, &crypto); if (ret) { free (buf); return ret; } ret = krb5_encrypt (context, crypto, KRB5_KU_KRB_PRIV, buf + buf_size - len, len, &s.enc_part.cipher); krb5_crypto_destroy(context, crypto); if (ret) { free(buf); return ret; } free(buf); ASN1_MALLOC_ENCODE(KRB_PRIV, buf, buf_size, &s, &len, ret); if (ret) goto fail; if (buf_size != len) krb5_abortx(context, "internal error in ASN.1 encoder"); krb5_data_free (&s.enc_part.cipher); ret = krb5_data_copy(outbuf, buf + buf_size - len, len); if (ret) { free(buf); return krb5_enomem(context); } free (buf); if (auth_context->flags & KRB5_AUTH_CONTEXT_DO_SEQUENCE) auth_context->local_seqnumber = (auth_context->local_seqnumber + 1) & 0xFFFFFFFF; return 0; fail: free (buf); krb5_data_free (&s.enc_part.cipher); return ret; } heimdal-7.5.0/lib/krb5/test_store.c0000644000175000017500000002003513026237312015221 0ustar niknik/* * Copyright (c) 2006 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of KTH nor the names of its contributors may be * used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY KTH AND ITS CONTRIBUTORS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL KTH OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "krb5_locl.h" #include static void test_int8(krb5_context context, krb5_storage *sp) { krb5_error_code ret; int i; int8_t val[] = { 0, 1, -1, 128, -127 }, v; krb5_storage_truncate(sp, 0); for (i = 0; i < sizeof(val)/sizeof(val[0]); i++) { ret = krb5_store_int8(sp, val[i]); if (ret) krb5_err(context, 1, ret, "krb5_store_int8"); krb5_storage_seek(sp, i, SEEK_SET); ret = krb5_ret_int8(sp, &v); if (ret) krb5_err(context, 1, ret, "krb5_ret_int8"); if (v != val[i]) krb5_errx(context, 1, "store and ret mismatch"); } } static void test_int16(krb5_context context, krb5_storage *sp) { krb5_error_code ret; int i; int16_t val[] = { 0, 1, -1, 32768, -32767 }, v; krb5_storage_truncate(sp, 0); for (i = 0; i < sizeof(val)/sizeof(val[0]); i++) { ret = krb5_store_int16(sp, val[i]); if (ret) krb5_err(context, 1, ret, "krb5_store_int16"); krb5_storage_seek(sp, i * sizeof (v), SEEK_SET); ret = krb5_ret_int16(sp, &v); if (ret) krb5_err(context, 1, ret, "krb5_ret_int16"); if (v != val[i]) krb5_errx(context, 1, "store and ret mismatch"); } } static void test_int32(krb5_context context, krb5_storage *sp) { krb5_error_code ret; int i; int32_t val[] = { 0, 1, -1, 2147483647, -2147483646 }, v; krb5_storage_truncate(sp, 0); for (i = 0; i < sizeof(val)/sizeof(val[0]); i++) { ret = krb5_store_int32(sp, val[i]); if (ret) krb5_err(context, 1, ret, "krb5_store_int32"); krb5_storage_seek(sp, i * sizeof (v), SEEK_SET); ret = krb5_ret_int32(sp, &v); if (ret) krb5_err(context, 1, ret, "krb5_ret_int32"); if (v != val[i]) krb5_errx(context, 1, "store and ret mismatch"); } } static void test_uint8(krb5_context context, krb5_storage *sp) { krb5_error_code ret; int i; uint8_t val[] = { 0, 1, 255 }, v; krb5_storage_truncate(sp, 0); for (i = 0; i < sizeof(val)/sizeof(val[0]); i++) { ret = krb5_store_uint8(sp, val[i]); if (ret) krb5_err(context, 1, ret, "krb5_store_uint8"); krb5_storage_seek(sp, i * sizeof (v), SEEK_SET); ret = krb5_ret_uint8(sp, &v); if (ret) krb5_err(context, 1, ret, "krb5_ret_uint8"); if (v != val[i]) krb5_errx(context, 1, "store and ret mismatch"); } } static void test_uint16(krb5_context context, krb5_storage *sp) { krb5_error_code ret; int i; uint16_t val[] = { 0, 1, 65535 }, v; krb5_storage_truncate(sp, 0); for (i = 0; i < sizeof(val)/sizeof(val[0]); i++) { ret = krb5_store_uint16(sp, val[i]); if (ret) krb5_err(context, 1, ret, "krb5_store_uint16"); krb5_storage_seek(sp, i * sizeof (v), SEEK_SET); ret = krb5_ret_uint16(sp, &v); if (ret) krb5_err(context, 1, ret, "krb5_ret_uint16"); if (v != val[i]) krb5_errx(context, 1, "store and ret mismatch"); } } static void test_uint32(krb5_context context, krb5_storage *sp) { krb5_error_code ret; int i; uint32_t val[] = { 0, 1, 4294967295UL }, v; krb5_storage_truncate(sp, 0); for (i = 0; i < sizeof(val)/sizeof(val[0]); i++) { ret = krb5_store_uint32(sp, val[i]); if (ret) krb5_err(context, 1, ret, "krb5_store_uint32"); krb5_storage_seek(sp, i * sizeof (v), SEEK_SET); ret = krb5_ret_uint32(sp, &v); if (ret) krb5_err(context, 1, ret, "krb5_ret_uint32"); if (v != val[i]) krb5_errx(context, 1, "store and ret mismatch"); } } static void test_storage(krb5_context context, krb5_storage *sp) { test_int8(context, sp); test_int16(context, sp); test_int32(context, sp); test_uint8(context, sp); test_uint16(context, sp); test_uint32(context, sp); } static void test_truncate(krb5_context context, krb5_storage *sp, int fd) { struct stat sb; krb5_store_string(sp, "hej"); krb5_storage_truncate(sp, 2); if (fstat(fd, &sb) != 0) krb5_err(context, 1, errno, "fstat"); if (sb.st_size != 2) krb5_errx(context, 1, "length not 2"); krb5_storage_truncate(sp, 1024); if (fstat(fd, &sb) != 0) krb5_err(context, 1, errno, "fstat"); if (sb.st_size != 1024) krb5_errx(context, 1, "length not 2"); } static void check_too_large(krb5_context context, krb5_storage *sp) { uint32_t too_big_sizes[] = { UINT_MAX, UINT_MAX / 2, UINT_MAX / 4, UINT_MAX / 8 + 1}; krb5_error_code ret; krb5_data data; size_t n; for (n = 0; n < sizeof(too_big_sizes) / sizeof(too_big_sizes[0]); n++) { krb5_storage_truncate(sp, 0); krb5_store_uint32(sp, too_big_sizes[n]); krb5_storage_seek(sp, 0, SEEK_SET); ret = krb5_ret_data(sp, &data); if (ret != HEIM_ERR_TOO_BIG) errx(1, "not too big: %lu", (unsigned long)n); } } /* * */ static int version_flag = 0; static int help_flag = 0; static struct getargs args[] = { {"version", 0, arg_flag, &version_flag, "print version", NULL }, {"help", 0, arg_flag, &help_flag, NULL, NULL } }; static void usage (int ret) { arg_printusage (args, sizeof(args)/sizeof(*args), NULL, ""); exit (ret); } int main(int argc, char **argv) { krb5_context context; krb5_error_code ret; int fd, optidx = 0; krb5_storage *sp; const char *fn = "test-store-data"; setprogname(argv[0]); if(getarg(args, sizeof(args) / sizeof(args[0]), argc, argv, &optidx)) usage(1); if (help_flag) usage (0); if(version_flag){ print_version(NULL); exit(0); } argc -= optidx; argv += optidx; ret = krb5_init_context (&context); if (ret) errx (1, "krb5_init_context failed: %d", ret); /* * Test encoding/decoding of primotive types on diffrent backends */ sp = krb5_storage_emem(); if (sp == NULL) krb5_errx(context, 1, "krb5_storage_emem: no mem"); test_storage(context, sp); check_too_large(context, sp); krb5_storage_free(sp); fd = open(fn, O_RDWR|O_CREAT|O_TRUNC, 0600); if (fd < 0) krb5_err(context, 1, errno, "open(%s)", fn); sp = krb5_storage_from_fd(fd); close(fd); if (sp == NULL) krb5_errx(context, 1, "krb5_storage_from_fd: %s no mem", fn); test_storage(context, sp); krb5_storage_free(sp); unlink(fn); /* * test truncate behavior */ fd = open(fn, O_RDWR|O_CREAT|O_TRUNC, 0600); if (fd < 0) krb5_err(context, 1, errno, "open(%s)", fn); sp = krb5_storage_from_fd(fd); if (sp == NULL) krb5_errx(context, 1, "krb5_storage_from_fd: %s no mem", fn); test_truncate(context, sp, fd); krb5_storage_free(sp); close(fd); unlink(fn); krb5_free_context(context); return 0; } heimdal-7.5.0/lib/krb5/krb5_verify_user.cat30000644000175000017500000002105213212450757016732 0ustar niknik KRB5_VERIFY_USER(3) BSD Library Functions Manual KRB5_VERIFY_USER(3) NNAAMMEE kkrrbb55__vveerriiffyy__uusseerr, kkrrbb55__vveerriiffyy__uusseerr__llrreeaallmm, kkrrbb55__vveerriiffyy__uusseerr__oopptt, kkrrbb55__vveerriiffyy__oopptt__iinniitt, kkrrbb55__vveerriiffyy__oopptt__aalllloocc, kkrrbb55__vveerriiffyy__oopptt__ffrreeee, kkrrbb55__vveerriiffyy__oopptt__sseett__ccccaacchhee, kkrrbb55__vveerriiffyy__oopptt__sseett__ffllaaggss, kkrrbb55__vveerriiffyy__oopptt__sseett__sseerrvviiccee, kkrrbb55__vveerriiffyy__oopptt__sseett__sseeccuurree, kkrrbb55__vveerriiffyy__oopptt__sseett__kkeeyyttaabb -- Heimdal password verifying functions LLIIBBRRAARRYY Kerberos 5 Library (libkrb5, -lkrb5) SSYYNNOOPPSSIISS ##iinncclluuddee <> _k_r_b_5___e_r_r_o_r___c_o_d_e kkrrbb55__vveerriiffyy__uusseerr(_k_r_b_5___c_o_n_t_e_x_t _c_o_n_t_e_x_t, _k_r_b_5___p_r_i_n_c_i_p_a_l _p_r_i_n_c_i_p_a_l, _k_r_b_5___c_c_a_c_h_e _c_c_a_c_h_e, _c_o_n_s_t _c_h_a_r _*_p_a_s_s_w_o_r_d, _k_r_b_5___b_o_o_l_e_a_n _s_e_c_u_r_e, _c_o_n_s_t _c_h_a_r _*_s_e_r_v_i_c_e); _k_r_b_5___e_r_r_o_r___c_o_d_e kkrrbb55__vveerriiffyy__uusseerr__llrreeaallmm(_k_r_b_5___c_o_n_t_e_x_t _c_o_n_t_e_x_t, _k_r_b_5___p_r_i_n_c_i_p_a_l _p_r_i_n_c_i_p_a_l, _k_r_b_5___c_c_a_c_h_e _c_c_a_c_h_e, _c_o_n_s_t _c_h_a_r _*_p_a_s_s_w_o_r_d, _k_r_b_5___b_o_o_l_e_a_n _s_e_c_u_r_e, _c_o_n_s_t _c_h_a_r _*_s_e_r_v_i_c_e); _v_o_i_d kkrrbb55__vveerriiffyy__oopptt__iinniitt(_k_r_b_5___v_e_r_i_f_y___o_p_t _*_o_p_t); _v_o_i_d kkrrbb55__vveerriiffyy__oopptt__aalllloocc(_k_r_b_5___v_e_r_i_f_y___o_p_t _*_*_o_p_t); _v_o_i_d kkrrbb55__vveerriiffyy__oopptt__ffrreeee(_k_r_b_5___v_e_r_i_f_y___o_p_t _*_o_p_t); _v_o_i_d kkrrbb55__vveerriiffyy__oopptt__sseett__ccccaacchhee(_k_r_b_5___v_e_r_i_f_y___o_p_t _*_o_p_t, _k_r_b_5___c_c_a_c_h_e _c_c_a_c_h_e); _v_o_i_d kkrrbb55__vveerriiffyy__oopptt__sseett__kkeeyyttaabb(_k_r_b_5___v_e_r_i_f_y___o_p_t _*_o_p_t, _k_r_b_5___k_e_y_t_a_b _k_e_y_t_a_b); _v_o_i_d kkrrbb55__vveerriiffyy__oopptt__sseett__sseeccuurree(_k_r_b_5___v_e_r_i_f_y___o_p_t _*_o_p_t, _k_r_b_5___b_o_o_l_e_a_n _s_e_c_u_r_e); _v_o_i_d kkrrbb55__vveerriiffyy__oopptt__sseett__sseerrvviiccee(_k_r_b_5___v_e_r_i_f_y___o_p_t _*_o_p_t, _c_o_n_s_t _c_h_a_r _*_s_e_r_v_i_c_e); _v_o_i_d kkrrbb55__vveerriiffyy__oopptt__sseett__ffllaaggss(_k_r_b_5___v_e_r_i_f_y___o_p_t _*_o_p_t, _u_n_s_i_g_n_e_d _i_n_t _f_l_a_g_s); _k_r_b_5___e_r_r_o_r___c_o_d_e kkrrbb55__vveerriiffyy__uusseerr__oopptt(_k_r_b_5___c_o_n_t_e_x_t _c_o_n_t_e_x_t, _k_r_b_5___p_r_i_n_c_i_p_a_l _p_r_i_n_c_i_p_a_l, _c_o_n_s_t _c_h_a_r _*_p_a_s_s_w_o_r_d, _k_r_b_5___v_e_r_i_f_y___o_p_t _*_o_p_t); DDEESSCCRRIIPPTTIIOONN The kkrrbb55__vveerriiffyy__uusseerr function verifies the password supplied by a user. The principal whose password will be verified is specified in _p_r_i_n_c_i_p_a_l. New tickets will be obtained as a side-effect and stored in _c_c_a_c_h_e (if NULL, the default ccache is used). kkrrbb55__vveerriiffyy__uusseerr() will call kkrrbb55__cccc__iinniittiiaalliizzee() on the given _c_c_a_c_h_e, so _c_c_a_c_h_e must only initialized with kkrrbb55__cccc__rreessoollvvee() or kkrrbb55__cccc__ggeenn__nneeww(). If the password is not sup- plied in _p_a_s_s_w_o_r_d (and is given as NULL) the user will be prompted for it. If _s_e_c_u_r_e the ticket will be verified against the locally stored service key _s_e_r_v_i_c_e (by default `host' if given as NULL ). The kkrrbb55__vveerriiffyy__uusseerr__llrreeaallmm() function does the same, except that it ignores the realm in _p_r_i_n_c_i_p_a_l and tries all the local realms (see krb5.conf(5)). After a successful return, the principal is set to the authenticated realm. If the call fails, the principal will not be mean- ingful, and should only be freed with krb5_free_principal(3). kkrrbb55__vveerriiffyy__oopptt__aalllloocc() and kkrrbb55__vveerriiffyy__oopptt__ffrreeee() allocates and frees a krb5_verify_opt. You should use the the alloc and free function instead of allocation the structure yourself, this is because in a future release the structure wont be exported. kkrrbb55__vveerriiffyy__oopptt__iinniitt() resets all opt to default values. None of the krb5_verify_opt_set function makes a copy of the data struc- ture that they are called with. It's up the caller to free them after the kkrrbb55__vveerriiffyy__uusseerr__oopptt() is called. kkrrbb55__vveerriiffyy__oopptt__sseett__ccccaacchhee() sets the _c_c_a_c_h_e that user of _o_p_t will use. If not set, the default credential cache will be used. kkrrbb55__vveerriiffyy__oopptt__sseett__kkeeyyttaabb() sets the _k_e_y_t_a_b that user of _o_p_t will use. If not set, the default keytab will be used. kkrrbb55__vveerriiffyy__oopptt__sseett__sseeccuurree() if _s_e_c_u_r_e if true, the password verification will require that the ticket will be verified against the locally stored service key. If not set, default value is true. kkrrbb55__vveerriiffyy__oopptt__sseett__sseerrvviiccee() sets the _s_e_r_v_i_c_e principal that user of _o_p_t will use. If not set, the `host' service will be used. kkrrbb55__vveerriiffyy__oopptt__sseett__ffllaaggss() sets _f_l_a_g_s that user of _o_p_t will use. If the flag KRB5_VERIFY_LREALMS is used, the _p_r_i_n_c_i_p_a_l will be modified like kkrrbb55__vveerriiffyy__uusseerr__llrreeaallmm() modifies it. kkrrbb55__vveerriiffyy__uusseerr__oopptt() function verifies the _p_a_s_s_w_o_r_d supplied by a user. The principal whose password will be verified is specified in _p_r_i_n_c_i_p_a_l. Options the to the verification process is pass in in _o_p_t. EEXXAAMMPPLLEESS Here is a example program that verifies a password. it uses the `host/`hostname`' service principal in _k_r_b_5_._k_e_y_t_a_b. #include int main(int argc, char **argv) { char *user; krb5_error_code error; krb5_principal princ; krb5_context context; if (argc != 2) errx(1, "usage: verify_passwd "); user = argv[1]; if (krb5_init_context(&context) < 0) errx(1, "krb5_init_context"); if ((error = krb5_parse_name(context, user, &princ)) != 0) krb5_err(context, 1, error, "krb5_parse_name"); error = krb5_verify_user(context, princ, NULL, NULL, TRUE, NULL); if (error) krb5_err(context, 1, error, "krb5_verify_user"); return 0; } SSEEEE AALLSSOO krb5_cc_gen_new(3), krb5_cc_initialize(3), krb5_cc_resolve(3), krb5_err(3), krb5_free_principal(3), krb5_init_context(3), krb5_kt_default(3), krb5.conf(5) HEIMDAL May 1, 2006 HEIMDAL heimdal-7.5.0/lib/krb5/crypto-des-common.c0000644000175000017500000001045613212137553016416 0ustar niknik/* * Copyright (c) 1997 - 2008 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ /* Functions which are used by both single and triple DES enctypes */ #include "krb5_locl.h" /* * A = A xor B. A & B are 8 bytes. */ KRB5_LIB_FUNCTION void KRB5_LIB_CALL _krb5_xor8(unsigned char *a, const unsigned char *b) { a[0] ^= b[0]; a[1] ^= b[1]; a[2] ^= b[2]; a[3] ^= b[3]; a[4] ^= b[4]; a[5] ^= b[5]; a[6] ^= b[6]; a[7] ^= b[7]; } #if defined(DES3_OLD_ENCTYPE) || defined(HEIM_WEAK_CRYPTO) KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL _krb5_des_checksum(krb5_context context, const EVP_MD *evp_md, struct _krb5_key_data *key, const void *data, size_t len, Checksum *cksum) { struct _krb5_evp_schedule *ctx = key->schedule->data; EVP_MD_CTX *m; DES_cblock ivec; unsigned char *p = cksum->checksum.data; krb5_generate_random_block(p, 8); m = EVP_MD_CTX_create(); if (m == NULL) return krb5_enomem(context); EVP_DigestInit_ex(m, evp_md, NULL); EVP_DigestUpdate(m, p, 8); EVP_DigestUpdate(m, data, len); EVP_DigestFinal_ex (m, p + 8, NULL); EVP_MD_CTX_destroy(m); memset (&ivec, 0, sizeof(ivec)); EVP_CipherInit_ex(&ctx->ectx, NULL, NULL, NULL, (void *)&ivec, -1); EVP_Cipher(&ctx->ectx, p, p, 24); return 0; } KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL _krb5_des_verify(krb5_context context, const EVP_MD *evp_md, struct _krb5_key_data *key, const void *data, size_t len, Checksum *C) { struct _krb5_evp_schedule *ctx = key->schedule->data; EVP_MD_CTX *m; unsigned char tmp[24]; unsigned char res[16]; DES_cblock ivec; krb5_error_code ret = 0; m = EVP_MD_CTX_create(); if (m == NULL) return krb5_enomem(context); memset(&ivec, 0, sizeof(ivec)); EVP_CipherInit_ex(&ctx->dctx, NULL, NULL, NULL, (void *)&ivec, -1); EVP_Cipher(&ctx->dctx, tmp, C->checksum.data, 24); EVP_DigestInit_ex(m, evp_md, NULL); EVP_DigestUpdate(m, tmp, 8); /* confounder */ EVP_DigestUpdate(m, data, len); EVP_DigestFinal_ex (m, res, NULL); EVP_MD_CTX_destroy(m); if(ct_memcmp(res, tmp + 8, sizeof(res)) != 0) { krb5_clear_error_message (context); ret = KRB5KRB_AP_ERR_BAD_INTEGRITY; } memset(tmp, 0, sizeof(tmp)); memset(res, 0, sizeof(res)); return ret; } #endif static krb5_error_code RSA_MD5_checksum(krb5_context context, struct _krb5_key_data *key, const void *data, size_t len, unsigned usage, Checksum *C) { if (EVP_Digest(data, len, C->checksum.data, NULL, EVP_md5(), NULL) != 1) krb5_abortx(context, "md5 checksum failed"); return 0; } struct _krb5_checksum_type _krb5_checksum_rsa_md5 = { CKSUMTYPE_RSA_MD5, "rsa-md5", 64, 16, F_CPROOF, RSA_MD5_checksum, NULL }; heimdal-7.5.0/lib/krb5/krb5_openlog.30000644000175000017500000001773412136107750015353 0ustar niknik.\" Copyright (c) 1997, 1999, 2001 - 2002 Kungliga Tekniska Högskolan .\" (Royal Institute of Technology, Stockholm, Sweden). .\" All rights reserved. .\" .\" Redistribution and use in source and binary forms, with or without .\" modification, are permitted provided that the following conditions .\" are met: .\" .\" 1. Redistributions of source code must retain the above copyright .\" notice, this list of conditions and the following disclaimer. .\" .\" 2. Redistributions in binary form must reproduce the above copyright .\" notice, this list of conditions and the following disclaimer in the .\" documentation and/or other materials provided with the distribution. .\" .\" 3. Neither the name of the Institute nor the names of its contributors .\" may be used to endorse or promote products derived from this software .\" without specific prior written permission. .\" .\" THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND .\" ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE .\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE .\" ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE .\" FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL .\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS .\" OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) .\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT .\" LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF .\" SUCH DAMAGE. .\" .\" $Id$ .Dd August 6, 1997 .Dt KRB5_OPENLOG 3 .Os HEIMDAL .Sh NAME .Nm krb5_initlog , .Nm krb5_openlog , .Nm krb5_closelog , .Nm krb5_addlog_dest , .Nm krb5_addlog_func , .Nm krb5_log , .Nm krb5_vlog , .Nm krb5_log_msg , .Nm krb5_vlog_msg .Nd Heimdal logging functions .Sh LIBRARY Kerberos 5 Library (libkrb5, -lkrb5) .Sh SYNOPSIS .In krb5.h .Ft "typedef void" .Fn "\*(lp*krb5_log_log_func_t\*(rp" "const char *time" "const char *message" "void *data" .Ft "typedef void" .Fn "\*(lp*krb5_log_close_func_t\*(rp" "void *data" .Ft krb5_error_code .Fn krb5_addlog_dest "krb5_context context" "krb5_log_facility *facility" "const char *destination" .Ft krb5_error_code .Fn krb5_addlog_func "krb5_context context" "krb5_log_facility *facility" "int min" "int max" "krb5_log_log_func_t log" "krb5_log_close_func_t close" "void *data" .Ft krb5_error_code .Fn krb5_closelog "krb5_context context" "krb5_log_facility *facility" .Ft krb5_error_code .Fn krb5_initlog "krb5_context context" "const char *program" "krb5_log_facility **facility" .Ft krb5_error_code .Fn krb5_log "krb5_context context" "krb5_log_facility *facility" "int level" "const char *format" "..." .Ft krb5_error_code .Fn krb5_log_msg "krb5_context context" "krb5_log_facility *facility" "char **reply" "int level" "const char *format" "..." .Ft krb5_error_code .Fn krb5_openlog "krb5_context context" "const char *program" "krb5_log_facility **facility" .Ft krb5_error_code .Fn krb5_vlog "krb5_context context" "krb5_log_facility *facility" "int level" "const char *format" "va_list arglist" .Ft krb5_error_code .Fn krb5_vlog_msg "krb5_context context" "krb5_log_facility *facility" "char **reply" "int level" "const char *format" "va_list arglist" .Sh DESCRIPTION These functions logs messages to one or more destinations. .Pp The .Fn krb5_openlog function creates a logging .Fa facility , that is used to log messages. A facility consists of one or more destinations (which can be files or syslog or some other device). The .Fa program parameter should be the generic name of the program that is doing the logging. This name is used to lookup which destinations to use. This information is contained in the .Li logging section of the .Pa krb5.conf configuration file. If no entry is found for .Fa program , the entry for .Li default is used, or if that is missing too, .Li SYSLOG will be used as destination. .Pp To close a logging facility, use the .Fn krb5_closelog function. .Pp To log a message to a facility use one of the functions .Fn krb5_log , .Fn krb5_log_msg , .Fn krb5_vlog , or .Fn krb5_vlog_msg . The functions ending in .Li _msg return in .Fa reply a pointer to the message that just got logged. This string is allocated, and should be freed with .Fn free . The .Fa format is a standard .Fn printf style format string (but see the BUGS section). .Pp If you want better control of where things gets logged, you can instead of using .Fn krb5_openlog call .Fn krb5_initlog , which just initializes a facility, but doesn't define any actual logging destinations. You can then add destinations with the .Fn krb5_addlog_dest and .Fn krb5_addlog_func functions. The first of these takes a string specifying a logging destination, and adds this to the facility. If you want to do some non-standard logging you can use the .Fn krb5_addlog_func function, which takes a function to use when logging. The .Fa log function is called for each message with .Fa time being a string specifying the current time, and .Fa message the message to log. .Fa close is called when the facility is closed. You can pass application specific data in the .Fa data parameter. The .Fa min and .Fa max parameter are the same as in a destination (defined below). To specify a max of infinity, pass -1. .Pp .Fn krb5_openlog calls .Fn krb5_initlog and then calls .Fn krb5_addlog_dest for each destination found. .Ss Destinations The defined destinations (as specified in .Pa krb5.conf ) follows: .Bl -tag -width "xxx" -offset indent .It Li STDERR This logs to the program's stderr. .It Li FILE: Ns Pa /file .It Li FILE= Ns Pa /file Log to the specified file. The form using a colon appends to the file, the form with an equal truncates the file. The truncating form keeps the file open, while the appending form closes it after each log message (which makes it possible to rotate logs). The truncating form is mainly for compatibility with the MIT libkrb5. .It Li DEVICE= Ns Pa /device This logs to the specified device, at present this is the same as .Li FILE:/device . .It Li CONSOLE Log to the console, this is the same as .Li DEVICE=/dev/console . .It Li SYSLOG Ns Op :priority Ns Op :facility Send messages to the syslog system, using priority, and facility. To get the name for one of these, you take the name of the macro passed to .Xr syslog 3 , and remove the leading .Li LOG_ .No ( Li LOG_NOTICE becomes .Li NOTICE ) . The default values (as well as the values used for unrecognised values), are .Li ERR , and .Li AUTH , respectively. See .Xr syslog 3 for a list of priorities and facilities. .El .Pp Each destination may optionally be prepended with a range of logging levels, specified as .Li min-max/ . If the .Fa level parameter to .Fn krb5_log is within this range (inclusive) the message gets logged to this destination, otherwise not. Either of the min and max valued may be omitted, in this case min is assumed to be zero, and max is assumed to be infinity. If you don't include a dash, both min and max gets set to the specified value. If no range is specified, all messages gets logged. .Sh EXAMPLES .Bd -literal -offset indent [logging] kdc = 0/FILE:/var/log/kdc.log kdc = 1-/SYSLOG:INFO:USER default = STDERR .Ed .Pp This will log all messages from the .Nm kdc program with level 0 to .Pa /var/log/kdc.log , other messages will be logged to syslog with priority .Li LOG_INFO , and facility .Li LOG_USER . All other programs will log all messages to their stderr. .Sh SEE ALSO .Xr syslog 3 , .Xr krb5.conf 5 .Sh BUGS These functions use .Fn asprintf to format the message. If your operating system does not have a working .Fn asprintf , a replacement will be used. At present this replacement does not handle some correct conversion specifications (like floating point numbers). Until this is fixed, the use of these conversions should be avoided. .Pp If logging is done to the syslog facility, these functions might not be thread-safe, depending on the implementation of .Fn openlog , and .Fn syslog . heimdal-7.5.0/lib/krb5/Makefile.am0000644000175000017500000002150213212137553014721 0ustar niknik# $Id$ include $(top_srcdir)/Makefile.am.common AM_CPPFLAGS += -I../com_err -I$(srcdir)/../com_err $(INCLUDE_sqlite3) $(INCLUDE_libintl) $(INCLUDE_openssl_crypto) bin_PROGRAMS = verify_krb5_conf noinst_PROGRAMS = \ krbhst-test \ test_alname \ test_crypto \ test_forward \ test_get_addrs \ test_gic \ test_kuserok \ test_renew \ test_rfc3961 noinst_LTLIBRARIES = \ librfc3961.la TESTS = \ aes-test \ derived-key-test \ n-fold-test \ parse-name-test \ pseudo-random-test \ store-test \ string-to-key-test \ test_acl \ test_addr \ test_cc \ test_config \ test_fx \ test_prf \ test_store \ test_crypto_wrapping \ test_keytab \ test_mem \ test_pac \ test_plugin \ test_princ \ test_pkinit_dh2key \ test_pknistkdf \ test_time \ test_expand_toks \ test_x500 check_DATA = test_config_strings.out check_PROGRAMS = $(TESTS) test_hostname test_ap-req test_canon test_set_kvno0 LDADD = libkrb5.la \ $(LIB_hcrypto) \ $(top_builddir)/lib/asn1/libasn1.la \ $(top_builddir)/lib/wind/libwind.la \ $(LIB_heimbase) $(LIB_roken) if PKINIT LIB_pkinit = ../hx509/libhx509.la endif if have_scc use_sqlite = $(LIB_sqlite3) endif libkrb5_la_LIBADD = \ $(top_builddir)/lib/asn1/libasn1.la \ $(top_builddir)/lib/ipc/libheim-ipcc.la \ $(top_builddir)/lib/wind/libwind.la \ $(top_builddir)/lib/base/libheimbase.la \ $(LIB_pkinit) \ $(LIB_openssl_crypto) \ $(use_sqlite) \ $(LIB_com_err) \ $(LIB_hcrypto) \ $(LIB_libintl) \ $(LIBADD_roken) \ $(PTHREAD_LIBADD) \ $(LIB_door_create) \ $(LIB_dlopen) librfc3961_la_LIBADD = \ $(top_builddir)/lib/asn1/libasn1.la \ $(top_builddir)/lib/ipc/libheim-ipcc.la \ $(top_builddir)/lib/wind/libwind.la \ $(LIB_pkinit) \ $(use_sqlite) \ $(LIB_com_err) \ $(LIB_hcrypto) \ $(LIB_libintl) \ $(LIBADD_roken) \ $(PTHREAD_LIBADD) \ $(LIB_door_create) \ $(LIB_dlopen) lib_LTLIBRARIES = libkrb5.la ERR_FILES = krb5_err.c krb_err.c heim_err.c k524_err.c libkrb5_la_CPPFLAGS = \ -DBUILD_KRB5_LIB \ $(AM_CPPFLAGS) \ -DHEIMDAL_LOCALEDIR='"$(localedir)"' librfc3961_la_CPPFLAGS = \ -DBUILD_KRB5_LIB \ $(AM_CPPFLAGS) \ -DHEIMDAL_LOCALEDIR='"$(localedir)"' dist_libkrb5_la_SOURCES = \ acache.c \ acl.c \ add_et_list.c \ addr_families.c \ an2ln_plugin.h \ aname_to_localname.c \ appdefault.c \ asn1_glue.c \ auth_context.c \ build_ap_req.c \ build_auth.c \ cache.c \ changepw.c \ codec.c \ config_file.c \ convert_creds.c \ constants.c \ context.c \ copy_host_realm.c \ crc.c \ creds.c \ crypto.c \ crypto.h \ crypto-aes-sha1.c \ crypto-aes-sha2.c \ crypto-algs.c \ crypto-arcfour.c \ crypto-des.c \ crypto-des-common.c \ crypto-des3.c \ crypto-evp.c \ crypto-null.c \ crypto-pk.c \ crypto-rand.c \ doxygen.c \ data.c \ db_plugin.c \ db_plugin.h \ dcache.c \ deprecated.c \ digest.c \ eai_to_heim_errno.c \ enomem.c \ error_string.c \ expand_hostname.c \ expand_path.c \ fast.c \ fcache.c \ free.c \ free_host_realm.c \ generate_seq_number.c \ generate_subkey.c \ get_addrs.c \ get_cred.c \ get_default_principal.c \ get_default_realm.c \ get_for_creds.c \ get_host_realm.c \ get_in_tkt.c \ get_port.c \ init_creds.c \ init_creds_pw.c \ kcm.c \ kcm.h \ keyblock.c \ keytab.c \ keytab_any.c \ keytab_file.c \ keytab_keyfile.c \ keytab_memory.c \ krb5_locl.h \ krb5-v4compat.h \ krbhst.c \ kuserok.c \ kuserok_plugin.h \ log.c \ mcache.c \ misc.c \ mk_error.c \ mk_priv.c \ mk_rep.c \ mk_req.c \ mk_req_ext.c \ mk_safe.c \ mit_glue.c \ net_read.c \ net_write.c \ n-fold.c \ pac.c \ padata.c \ pcache.c \ pkinit.c \ pkinit-ec.c \ principal.c \ prog_setup.c \ prompter_posix.c \ rd_cred.c \ rd_error.c \ rd_priv.c \ rd_rep.c \ rd_req.c \ rd_safe.c \ read_message.c \ recvauth.c \ replay.c \ salt.c \ salt-aes-sha1.c \ salt-aes-sha2.c \ salt-arcfour.c \ salt-des.c \ salt-des3.c \ sp800-108-kdf.c \ scache.c \ send_to_kdc.c \ sendauth.c \ set_default_realm.c \ sock_principal.c \ store.c \ store-int.c \ store-int.h \ store_emem.c \ store_fd.c \ store_mem.c \ store_sock.c \ plugin.c \ ticket.c \ time.c \ transited.c \ verify_init.c \ verify_user.c \ version.c \ warn.c \ write_message.c nodist_libkrb5_la_SOURCES = \ $(ERR_FILES) libkrb5_la_DEPENDENCIES = \ version-script.map libkrb5_la_LDFLAGS = -version-info 26:0:0 if versionscript libkrb5_la_LDFLAGS += $(LDFLAGS_VERSION_SCRIPT)$(srcdir)/version-script.map endif ALL_OBJECTS = $(libkrb5_la_OBJECTS) ALL_OBJECTS += $(verify_krb5_conf_OBJECTS) ALL_OBJECTS += $(librfc3961_la_OBJECTS) ALL_OBJECTS += $(librfc3961_la_OBJECTS) ALL_OBJECTS += $(krbhst_test_OBJECTS) ALL_OBJECTS += $(test_alname_OBJECTS) ALL_OBJECTS += $(test_crypto_OBJECTS) ALL_OBJECTS += $(test_forward_OBJECTS) ALL_OBJECTS += $(test_get_addrs_OBJECTS) ALL_OBJECTS += $(test_gic_OBJECTS) ALL_OBJECTS += $(test_kuserok_OBJECTS) ALL_OBJECTS += $(test_renew_OBJECTS) ALL_OBJECTS += $(test_rfc3961_OBJECTS) $(ALL_OBJECTS): $(srcdir)/krb5-protos.h $(srcdir)/krb5-private.h $(ALL_OBJECTS): krb5_err.h heim_err.h k524_err.h krb5_err.h krb_err.h k524_err.h librfc3961_la_SOURCES = \ crc.c \ crypto.c \ crypto.h \ crypto-aes-sha1.c \ crypto-aes-sha2.c \ crypto-algs.c \ crypto-arcfour.c \ crypto-des.c \ crypto-des-common.c \ crypto-des3.c \ crypto-evp.c \ crypto-null.c \ crypto-pk.c \ crypto-rand.c \ crypto-stubs.c \ data.c \ enomem.c \ error_string.c \ keyblock.c \ n-fold.c \ salt.c \ salt-aes-sha1.c \ salt-aes-sha2.c \ salt-arcfour.c \ salt-des.c \ salt-des3.c \ sp800-108-kdf.c \ store-int.c \ warn.c test_rfc3961_LDADD = \ librfc3961.la \ $(top_builddir)/lib/asn1/libasn1.la \ $(top_builddir)/lib/wind/libwind.la \ $(LIB_hcrypto) \ $(LIB_roken) if DEVELOPER_MODE headerdeps = $(dist_libkrb5_la_SOURCES) endif $(srcdir)/krb5-protos.h: $(headerdeps) @cd $(srcdir) && perl ../../cf/make-proto.pl -E KRB5_LIB -q -P comment -o krb5-protos.h $(dist_libkrb5_la_SOURCES) || rm -f krb5-protos.h $(srcdir)/krb5-private.h: $(headerdeps) @cd $(srcdir) && perl ../../cf/make-proto.pl -q -P comment -p krb5-private.h $(dist_libkrb5_la_SOURCES) || rm -f krb5-private.h man_MANS = \ kerberos.8 \ krb5.conf.5 \ krb5-plugin.7 \ krb524_convert_creds_kdc.3 \ krb5_425_conv_principal.3 \ krb5_acl_match_file.3 \ krb5_aname_to_localname.3 \ krb5_appdefault.3 \ krb5_auth_context.3 \ krb5_c_make_checksum.3 \ krb5_check_transited.3 \ krb5_create_checksum.3 \ krb5_creds.3 \ krb5_digest.3 \ krb5_eai_to_heim_errno.3 \ krb5_encrypt.3 \ krb5_find_padata.3 \ krb5_generate_random_block.3 \ krb5_get_all_client_addrs.3 \ krb5_get_credentials.3 \ krb5_get_creds.3 \ krb5_get_forwarded_creds.3 \ krb5_get_in_cred.3 \ krb5_get_init_creds.3 \ krb5_get_krbhst.3 \ krb5_getportbyname.3 \ krb5_init_context.3 \ krb5_is_thread_safe.3 \ krb5_krbhst_init.3 \ krb5_mk_req.3 \ krb5_mk_safe.3 \ krb5_openlog.3 \ krb5_parse_name.3 \ krb5_principal.3 \ krb5_rcache.3 \ krb5_rd_error.3 \ krb5_rd_safe.3 \ krb5_set_default_realm.3 \ krb5_set_password.3 \ krb5_string_to_key.3 \ krb5_timeofday.3 \ krb5_verify_init_creds.3 \ krb5_verify_user.3 \ verify_krb5_conf.8 dist_include_HEADERS = \ krb5.h \ $(srcdir)/krb5-protos.h \ krb5_ccapi.h noinst_HEADERS = $(srcdir)/krb5-private.h nodist_include_HEADERS = krb5_err.h heim_err.h k524_err.h # XXX use nobase_include_HEADERS = krb5/locate_plugin.h krb5dir = $(includedir)/krb5 krb5_HEADERS = locate_plugin.h send_to_kdc_plugin.h ccache_plugin.h an2ln_plugin.h db_plugin.h build_HEADERZ = \ $(krb5_HEADERS) \ krb_err.h CLEANFILES = \ test_config_strings.out \ test-store-data \ krb5_err.c krb5_err.h \ krb_err.c krb_err.h \ heim_err.c heim_err.h \ k524_err.c k524_err.h $(libkrb5_la_OBJECTS): krb5_err.h krb_err.h heim_err.h k524_err.h test_config_strings.out: test_config_strings.cfg $(CP) $(srcdir)/test_config_strings.cfg test_config_strings.out EXTRA_DIST = \ NTMakefile \ config_reg.c \ dll.c \ libkrb5-exports.def.in \ verify_krb5_conf-version.rc \ krb5_err.et \ krb_err.et \ heim_err.et \ k524_err.et \ $(man_MANS) \ version-script.map \ test_config_strings.cfg \ krb5.moduli #sysconf_DATA = krb5.moduli # to help stupid solaris make krb5_err.h: krb5_err.et krb_err.h: krb_err.et heim_err.h: heim_err.et k524_err.h: k524_err.et heimdal-7.5.0/lib/krb5/scache.c0000644000175000017500000010027013026237312014254 0ustar niknik/* * Copyright (c) 2008 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "krb5_locl.h" #ifdef HAVE_SCC #include typedef struct krb5_scache { char *name; char *file; sqlite3 *db; sqlite_uint64 cid; sqlite3_stmt *icred; sqlite3_stmt *dcred; sqlite3_stmt *iprincipal; sqlite3_stmt *icache; sqlite3_stmt *ucachen; sqlite3_stmt *ucachep; sqlite3_stmt *dcache; sqlite3_stmt *scache; sqlite3_stmt *scache_name; sqlite3_stmt *umaster; } krb5_scache; #define SCACHE(X) ((krb5_scache *)(X)->data.data) #define SCACHE_DEF_NAME "Default-cache" #ifdef KRB5_USE_PATH_TOKENS #define KRB5_SCACHE_DB "%{TEMP}/krb5scc_%{uid}" #else #define KRB5_SCACHE_DB "/tmp/krb5scc_%{uid}" #endif #define KRB5_SCACHE_NAME "SCC:" SCACHE_DEF_NAME ":" KRB5_SCACHE_DB #define SCACHE_INVALID_CID ((sqlite_uint64)-1) /* * */ #define SQL_CMASTER "" \ "CREATE TABLE master (" \ "oid INTEGER PRIMARY KEY," \ "version INTEGER NOT NULL," \ "defaultcache TEXT NOT NULL" \ ")" #define SQL_SETUP_MASTER \ "INSERT INTO master (version,defaultcache) VALUES(2, \"" SCACHE_DEF_NAME "\")" #define SQL_UMASTER "UPDATE master SET defaultcache=? WHERE version=2" #define SQL_CCACHE "" \ "CREATE TABLE caches (" \ "oid INTEGER PRIMARY KEY," \ "principal TEXT," \ "name TEXT NOT NULL" \ ")" #define SQL_TCACHE "" \ "CREATE TRIGGER CacheDropCreds AFTER DELETE ON caches " \ "FOR EACH ROW BEGIN " \ "DELETE FROM credentials WHERE cid=old.oid;" \ "END" #define SQL_ICACHE "INSERT INTO caches (name) VALUES(?)" #define SQL_UCACHE_NAME "UPDATE caches SET name=? WHERE OID=?" #define SQL_UCACHE_PRINCIPAL "UPDATE caches SET principal=? WHERE OID=?" #define SQL_DCACHE "DELETE FROM caches WHERE OID=?" #define SQL_SCACHE "SELECT principal,name FROM caches WHERE OID=?" #define SQL_SCACHE_NAME "SELECT oid FROM caches WHERE NAME=?" #define SQL_CCREDS "" \ "CREATE TABLE credentials (" \ "oid INTEGER PRIMARY KEY," \ "cid INTEGER NOT NULL," \ "kvno INTEGER NOT NULL," \ "etype INTEGER NOT NULL," \ "created_at INTEGER NOT NULL," \ "cred BLOB NOT NULL" \ ")" #define SQL_TCRED "" \ "CREATE TRIGGER credDropPrincipal AFTER DELETE ON credentials " \ "FOR EACH ROW BEGIN " \ "DELETE FROM principals WHERE credential_id=old.oid;" \ "END" #define SQL_ICRED "INSERT INTO credentials (cid, kvno, etype, cred, created_at) VALUES (?,?,?,?,?)" #define SQL_DCRED "DELETE FROM credentials WHERE cid=?" #define SQL_CPRINCIPALS "" \ "CREATE TABLE principals (" \ "oid INTEGER PRIMARY KEY," \ "principal TEXT NOT NULL," \ "type INTEGER NOT NULL," \ "credential_id INTEGER NOT NULL" \ ")" #define SQL_IPRINCIPAL "INSERT INTO principals (principal, type, credential_id) VALUES (?,?,?)" /* * sqlite destructors */ static void free_data(void *data) { free(data); } static void free_krb5(void *str) { krb5_xfree(str); } static void scc_free(krb5_scache *s) { if (s->file) free(s->file); if (s->name) free(s->name); if (s->icred) sqlite3_finalize(s->icred); if (s->dcred) sqlite3_finalize(s->dcred); if (s->iprincipal) sqlite3_finalize(s->iprincipal); if (s->icache) sqlite3_finalize(s->icache); if (s->ucachen) sqlite3_finalize(s->ucachen); if (s->ucachep) sqlite3_finalize(s->ucachep); if (s->dcache) sqlite3_finalize(s->dcache); if (s->scache) sqlite3_finalize(s->scache); if (s->scache_name) sqlite3_finalize(s->scache_name); if (s->umaster) sqlite3_finalize(s->umaster); if (s->db) sqlite3_close(s->db); free(s); } #ifdef TRACEME static void trace(void* ptr, const char * str) { printf("SQL: %s\n", str); } #endif static krb5_error_code prepare_stmt(krb5_context context, sqlite3 *db, sqlite3_stmt **stmt, const char *str) { int ret; ret = sqlite3_prepare_v2(db, str, -1, stmt, NULL); if (ret != SQLITE_OK) { krb5_set_error_message(context, ENOENT, N_("Failed to prepare stmt %s: %s", ""), str, sqlite3_errmsg(db)); return ENOENT; } return 0; } static krb5_error_code exec_stmt(krb5_context context, sqlite3 *db, const char *str, krb5_error_code code) { int ret; ret = sqlite3_exec(db, str, NULL, NULL, NULL); if (ret != SQLITE_OK && code) { krb5_set_error_message(context, code, N_("scache execute %s: %s", ""), str, sqlite3_errmsg(db)); return code; } return 0; } static krb5_error_code default_db(krb5_context context, sqlite3 **db) { char *name; int ret; ret = _krb5_expand_default_cc_name(context, KRB5_SCACHE_DB, &name); if (ret) return ret; ret = sqlite3_open_v2(name, db, SQLITE_OPEN_READWRITE, NULL); free(name); if (ret != SQLITE_OK) { krb5_clear_error_message(context); return ENOENT; } #ifdef TRACEME sqlite3_trace(*db, trace, NULL); #endif return 0; } static krb5_error_code get_def_name(krb5_context context, char **str) { krb5_error_code ret; sqlite3_stmt *stmt; const char *name; sqlite3 *db; ret = default_db(context, &db); if (ret) return ret; ret = prepare_stmt(context, db, &stmt, "SELECT defaultcache FROM master"); if (ret) { sqlite3_close(db); return ret; } ret = sqlite3_step(stmt); if (ret != SQLITE_ROW) goto out; if (sqlite3_column_type(stmt, 0) != SQLITE_TEXT) goto out; name = (const char *)sqlite3_column_text(stmt, 0); if (name == NULL) goto out; *str = strdup(name); if (*str == NULL) goto out; sqlite3_finalize(stmt); sqlite3_close(db); return 0; out: sqlite3_finalize(stmt); sqlite3_close(db); krb5_clear_error_message(context); return ENOENT; } static krb5_scache * KRB5_CALLCONV scc_alloc(krb5_context context, const char *name) { krb5_error_code ret; krb5_scache *s; ALLOC(s, 1); if(s == NULL) return NULL; s->cid = SCACHE_INVALID_CID; if (name) { char *file; if (*name == '\0') { ret = get_def_name(context, &s->name); if (ret) s->name = strdup(SCACHE_DEF_NAME); } else s->name = strdup(name); file = strrchr(s->name, ':'); if (file) { *file++ = '\0'; s->file = strdup(file); ret = 0; } else { ret = _krb5_expand_default_cc_name(context, KRB5_SCACHE_DB, &s->file); } } else { _krb5_expand_default_cc_name(context, KRB5_SCACHE_DB, &s->file); ret = asprintf(&s->name, "unique-%p", s); } if (ret < 0 || s->file == NULL || s->name == NULL) { scc_free(s); return NULL; } return s; } static krb5_error_code open_database(krb5_context context, krb5_scache *s, int flags) { int ret; ret = sqlite3_open_v2(s->file, &s->db, SQLITE_OPEN_READWRITE|flags, NULL); if (ret) { if (s->db) { krb5_set_error_message(context, ENOENT, N_("Error opening scache file %s: %s", ""), s->file, sqlite3_errmsg(s->db)); sqlite3_close(s->db); s->db = NULL; } else krb5_set_error_message(context, ENOENT, N_("malloc: out of memory", "")); return ENOENT; } return 0; } static krb5_error_code create_cache(krb5_context context, krb5_scache *s) { int ret; sqlite3_bind_text(s->icache, 1, s->name, -1, NULL); do { ret = sqlite3_step(s->icache); } while (ret == SQLITE_ROW); if (ret != SQLITE_DONE) { krb5_set_error_message(context, KRB5_CC_IO, N_("Failed to add scache: %d", ""), ret); return KRB5_CC_IO; } sqlite3_reset(s->icache); s->cid = sqlite3_last_insert_rowid(s->db); return 0; } static krb5_error_code make_database(krb5_context context, krb5_scache *s) { int created_file = 0; int ret; if (s->db) return 0; ret = open_database(context, s, 0); if (ret) { mode_t oldumask = umask(077); ret = open_database(context, s, SQLITE_OPEN_CREATE); umask(oldumask); if (ret) goto out; created_file = 1; ret = exec_stmt(context, s->db, SQL_CMASTER, KRB5_CC_IO); if (ret) goto out; ret = exec_stmt(context, s->db, SQL_CCACHE, KRB5_CC_IO); if (ret) goto out; ret = exec_stmt(context, s->db, SQL_CCREDS, KRB5_CC_IO); if (ret) goto out; ret = exec_stmt(context, s->db, SQL_CPRINCIPALS, KRB5_CC_IO); if (ret) goto out; ret = exec_stmt(context, s->db, SQL_SETUP_MASTER, KRB5_CC_IO); if (ret) goto out; ret = exec_stmt(context, s->db, SQL_TCACHE, KRB5_CC_IO); if (ret) goto out; ret = exec_stmt(context, s->db, SQL_TCRED, KRB5_CC_IO); if (ret) goto out; } #ifdef TRACEME sqlite3_trace(s->db, trace, NULL); #endif ret = prepare_stmt(context, s->db, &s->icred, SQL_ICRED); if (ret) goto out; ret = prepare_stmt(context, s->db, &s->dcred, SQL_DCRED); if (ret) goto out; ret = prepare_stmt(context, s->db, &s->iprincipal, SQL_IPRINCIPAL); if (ret) goto out; ret = prepare_stmt(context, s->db, &s->icache, SQL_ICACHE); if (ret) goto out; ret = prepare_stmt(context, s->db, &s->ucachen, SQL_UCACHE_NAME); if (ret) goto out; ret = prepare_stmt(context, s->db, &s->ucachep, SQL_UCACHE_PRINCIPAL); if (ret) goto out; ret = prepare_stmt(context, s->db, &s->dcache, SQL_DCACHE); if (ret) goto out; ret = prepare_stmt(context, s->db, &s->scache, SQL_SCACHE); if (ret) goto out; ret = prepare_stmt(context, s->db, &s->scache_name, SQL_SCACHE_NAME); if (ret) goto out; ret = prepare_stmt(context, s->db, &s->umaster, SQL_UMASTER); if (ret) goto out; return 0; out: if (s->db) sqlite3_close(s->db); if (created_file) unlink(s->file); return ret; } static krb5_error_code bind_principal(krb5_context context, sqlite3 *db, sqlite3_stmt *stmt, int col, krb5_const_principal principal) { krb5_error_code ret; char *str; ret = krb5_unparse_name(context, principal, &str); if (ret) return ret; ret = sqlite3_bind_text(stmt, col, str, -1, free_krb5); if (ret != SQLITE_OK) { krb5_xfree(str); krb5_set_error_message(context, ENOMEM, N_("scache bind principal: %s", ""), sqlite3_errmsg(db)); return ENOMEM; } return 0; } /* * */ static const char* KRB5_CALLCONV scc_get_name(krb5_context context, krb5_ccache id) { return SCACHE(id)->name; } static krb5_error_code KRB5_CALLCONV scc_resolve(krb5_context context, krb5_ccache *id, const char *res) { krb5_scache *s; int ret; s = scc_alloc(context, res); if (s == NULL) { krb5_set_error_message(context, KRB5_CC_NOMEM, N_("malloc: out of memory", "")); return KRB5_CC_NOMEM; } ret = make_database(context, s); if (ret) { scc_free(s); return ret; } ret = sqlite3_bind_text(s->scache_name, 1, s->name, -1, NULL); if (ret != SQLITE_OK) { krb5_set_error_message(context, ENOMEM, "bind name: %s", sqlite3_errmsg(s->db)); scc_free(s); return ENOMEM; } if (sqlite3_step(s->scache_name) == SQLITE_ROW) { if (sqlite3_column_type(s->scache_name, 0) != SQLITE_INTEGER) { sqlite3_reset(s->scache_name); krb5_set_error_message(context, KRB5_CC_END, N_("Cache name of wrong type " "for scache %s", ""), s->name); scc_free(s); return KRB5_CC_END; } s->cid = sqlite3_column_int(s->scache_name, 0); } else { s->cid = SCACHE_INVALID_CID; } sqlite3_reset(s->scache_name); (*id)->data.data = s; (*id)->data.length = sizeof(*s); return 0; } static krb5_error_code KRB5_CALLCONV scc_gen_new(krb5_context context, krb5_ccache *id) { krb5_scache *s; s = scc_alloc(context, NULL); if (s == NULL) { krb5_set_error_message(context, KRB5_CC_NOMEM, N_("malloc: out of memory", "")); return KRB5_CC_NOMEM; } (*id)->data.data = s; (*id)->data.length = sizeof(*s); return 0; } static krb5_error_code KRB5_CALLCONV scc_initialize(krb5_context context, krb5_ccache id, krb5_principal primary_principal) { krb5_scache *s = SCACHE(id); krb5_error_code ret; ret = make_database(context, s); if (ret) return ret; ret = exec_stmt(context, s->db, "BEGIN IMMEDIATE TRANSACTION", KRB5_CC_IO); if (ret) return ret; if (s->cid == SCACHE_INVALID_CID) { ret = create_cache(context, s); if (ret) goto rollback; } else { sqlite3_bind_int(s->dcred, 1, s->cid); do { ret = sqlite3_step(s->dcred); } while (ret == SQLITE_ROW); sqlite3_reset(s->dcred); if (ret != SQLITE_DONE) { ret = KRB5_CC_IO; krb5_set_error_message(context, ret, N_("Failed to delete old " "credentials: %s", ""), sqlite3_errmsg(s->db)); goto rollback; } } ret = bind_principal(context, s->db, s->ucachep, 1, primary_principal); if (ret) goto rollback; sqlite3_bind_int(s->ucachep, 2, s->cid); do { ret = sqlite3_step(s->ucachep); } while (ret == SQLITE_ROW); sqlite3_reset(s->ucachep); if (ret != SQLITE_DONE) { ret = KRB5_CC_IO; krb5_set_error_message(context, ret, N_("Failed to bind principal to cache %s", ""), sqlite3_errmsg(s->db)); goto rollback; } ret = exec_stmt(context, s->db, "COMMIT", KRB5_CC_IO); if (ret) return ret; return 0; rollback: exec_stmt(context, s->db, "ROLLBACK", 0); return ret; } static krb5_error_code KRB5_CALLCONV scc_close(krb5_context context, krb5_ccache id) { scc_free(SCACHE(id)); return 0; } static krb5_error_code KRB5_CALLCONV scc_destroy(krb5_context context, krb5_ccache id) { krb5_scache *s = SCACHE(id); int ret; if (s->cid == SCACHE_INVALID_CID) return 0; sqlite3_bind_int(s->dcache, 1, s->cid); do { ret = sqlite3_step(s->dcache); } while (ret == SQLITE_ROW); sqlite3_reset(s->dcache); if (ret != SQLITE_DONE) { krb5_set_error_message(context, KRB5_CC_IO, N_("Failed to destroy cache %s: %s", ""), s->name, sqlite3_errmsg(s->db)); return KRB5_CC_IO; } return 0; } static krb5_error_code encode_creds(krb5_context context, krb5_creds *creds, krb5_data *data) { krb5_error_code ret; krb5_storage *sp; krb5_data_zero(data); sp = krb5_storage_emem(); if (sp == NULL) return krb5_enomem(context); ret = krb5_store_creds(sp, creds); if (ret) { krb5_set_error_message(context, ret, N_("Failed to store credential in scache", "")); krb5_storage_free(sp); return ret; } ret = krb5_storage_to_data(sp, data); krb5_storage_free(sp); if (ret) krb5_set_error_message(context, ret, N_("Failed to encode credential in scache", "")); return ret; } static krb5_error_code decode_creds(krb5_context context, const void *data, size_t length, krb5_creds *creds) { krb5_error_code ret; krb5_storage *sp; sp = krb5_storage_from_readonly_mem(data, length); if (sp == NULL) return krb5_enomem(context); ret = krb5_ret_creds(sp, creds); krb5_storage_free(sp); if (ret) { krb5_set_error_message(context, ret, N_("Failed to read credential in scache", "")); return ret; } return 0; } static krb5_error_code KRB5_CALLCONV scc_store_cred(krb5_context context, krb5_ccache id, krb5_creds *creds) { sqlite_uint64 credid; krb5_scache *s = SCACHE(id); krb5_error_code ret; krb5_data data; ret = make_database(context, s); if (ret) return ret; ret = encode_creds(context, creds, &data); if (ret) return ret; sqlite3_bind_int(s->icred, 1, s->cid); { krb5_enctype etype = 0; int kvno = 0; Ticket t; size_t len; ret = decode_Ticket(creds->ticket.data, creds->ticket.length, &t, &len); if (ret == 0) { if(t.enc_part.kvno) kvno = *t.enc_part.kvno; etype = t.enc_part.etype; free_Ticket(&t); } sqlite3_bind_int(s->icred, 2, kvno); sqlite3_bind_int(s->icred, 3, etype); } sqlite3_bind_blob(s->icred, 4, data.data, data.length, free_data); sqlite3_bind_int(s->icred, 5, time(NULL)); ret = exec_stmt(context, s->db, "BEGIN IMMEDIATE TRANSACTION", KRB5_CC_IO); if (ret) return ret; do { ret = sqlite3_step(s->icred); } while (ret == SQLITE_ROW); sqlite3_reset(s->icred); if (ret != SQLITE_DONE) { ret = KRB5_CC_IO; krb5_set_error_message(context, ret, N_("Failed to add credential: %s", ""), sqlite3_errmsg(s->db)); goto rollback; } credid = sqlite3_last_insert_rowid(s->db); { bind_principal(context, s->db, s->iprincipal, 1, creds->server); sqlite3_bind_int(s->iprincipal, 2, 1); sqlite3_bind_int(s->iprincipal, 3, credid); do { ret = sqlite3_step(s->iprincipal); } while (ret == SQLITE_ROW); sqlite3_reset(s->iprincipal); if (ret != SQLITE_DONE) { ret = KRB5_CC_IO; krb5_set_error_message(context, ret, N_("Failed to add principal: %s", ""), sqlite3_errmsg(s->db)); goto rollback; } } { bind_principal(context, s->db, s->iprincipal, 1, creds->client); sqlite3_bind_int(s->iprincipal, 2, 0); sqlite3_bind_int(s->iprincipal, 3, credid); do { ret = sqlite3_step(s->iprincipal); } while (ret == SQLITE_ROW); sqlite3_reset(s->iprincipal); if (ret != SQLITE_DONE) { ret = KRB5_CC_IO; krb5_set_error_message(context, ret, N_("Failed to add principal: %s", ""), sqlite3_errmsg(s->db)); goto rollback; } } ret = exec_stmt(context, s->db, "COMMIT", KRB5_CC_IO); if (ret) return ret; return 0; rollback: exec_stmt(context, s->db, "ROLLBACK", 0); return ret; } static krb5_error_code KRB5_CALLCONV scc_get_principal(krb5_context context, krb5_ccache id, krb5_principal *principal) { krb5_scache *s = SCACHE(id); krb5_error_code ret; const char *str; *principal = NULL; ret = make_database(context, s); if (ret) return ret; sqlite3_bind_int(s->scache, 1, s->cid); if (sqlite3_step(s->scache) != SQLITE_ROW) { sqlite3_reset(s->scache); krb5_set_error_message(context, KRB5_CC_END, N_("No principal for cache SCC:%s:%s", ""), s->name, s->file); return KRB5_CC_END; } if (sqlite3_column_type(s->scache, 0) != SQLITE_TEXT) { sqlite3_reset(s->scache); krb5_set_error_message(context, KRB5_CC_END, N_("Principal data of wrong type " "for SCC:%s:%s", ""), s->name, s->file); return KRB5_CC_END; } str = (const char *)sqlite3_column_text(s->scache, 0); if (str == NULL) { sqlite3_reset(s->scache); krb5_set_error_message(context, KRB5_CC_END, N_("Principal not set for SCC:%s:%s", ""), s->name, s->file); return KRB5_CC_END; } ret = krb5_parse_name(context, str, principal); sqlite3_reset(s->scache); return ret; } struct cred_ctx { char *drop; sqlite3_stmt *stmt; sqlite3_stmt *credstmt; }; static krb5_error_code KRB5_CALLCONV scc_get_first (krb5_context context, krb5_ccache id, krb5_cc_cursor *cursor) { krb5_scache *s = SCACHE(id); krb5_error_code ret; struct cred_ctx *ctx; char *str = NULL, *name = NULL; *cursor = NULL; ctx = calloc(1, sizeof(*ctx)); if (ctx == NULL) return krb5_enomem(context); ret = make_database(context, s); if (ret) { free(ctx); return ret; } if (s->cid == SCACHE_INVALID_CID) { krb5_set_error_message(context, KRB5_CC_END, N_("Iterating a invalid scache %s", ""), s->name); free(ctx); return KRB5_CC_END; } ret = asprintf(&name, "credIteration%pPid%d", ctx, (int)getpid()); if (ret < 0 || name == NULL) { free(ctx); return krb5_enomem(context); } ret = asprintf(&ctx->drop, "DROP TABLE %s", name); if (ret < 0 || ctx->drop == NULL) { free(name); free(ctx); return krb5_enomem(context); } ret = asprintf(&str, "CREATE TEMPORARY TABLE %s " "AS SELECT oid,created_at FROM credentials WHERE cid = %lu", name, (unsigned long)s->cid); if (ret < 0 || str == NULL) { free(ctx->drop); free(name); free(ctx); return krb5_enomem(context); } ret = exec_stmt(context, s->db, str, KRB5_CC_IO); free(str); str = NULL; if (ret) { free(ctx->drop); free(name); free(ctx); return ret; } ret = asprintf(&str, "SELECT oid FROM %s ORDER BY created_at", name); if (ret < 0 || str == NULL) { exec_stmt(context, s->db, ctx->drop, 0); free(ctx->drop); free(name); free(ctx); return ret; } ret = prepare_stmt(context, s->db, &ctx->stmt, str); free(str); str = NULL; free(name); if (ret) { exec_stmt(context, s->db, ctx->drop, 0); free(ctx->drop); free(ctx); return ret; } ret = prepare_stmt(context, s->db, &ctx->credstmt, "SELECT cred FROM credentials WHERE oid = ?"); if (ret) { sqlite3_finalize(ctx->stmt); exec_stmt(context, s->db, ctx->drop, 0); free(ctx->drop); free(ctx); return ret; } *cursor = ctx; return 0; } static krb5_error_code KRB5_CALLCONV scc_get_next (krb5_context context, krb5_ccache id, krb5_cc_cursor *cursor, krb5_creds *creds) { struct cred_ctx *ctx = *cursor; krb5_scache *s = SCACHE(id); krb5_error_code ret; sqlite_uint64 oid; const void *data = NULL; size_t len = 0; next: ret = sqlite3_step(ctx->stmt); if (ret == SQLITE_DONE) { krb5_clear_error_message(context); return KRB5_CC_END; } else if (ret != SQLITE_ROW) { krb5_set_error_message(context, KRB5_CC_IO, N_("scache Database failed: %s", ""), sqlite3_errmsg(s->db)); return KRB5_CC_IO; } oid = sqlite3_column_int64(ctx->stmt, 0); /* read cred from credentials table */ sqlite3_bind_int(ctx->credstmt, 1, oid); ret = sqlite3_step(ctx->credstmt); if (ret != SQLITE_ROW) { sqlite3_reset(ctx->credstmt); goto next; } if (sqlite3_column_type(ctx->credstmt, 0) != SQLITE_BLOB) { krb5_set_error_message(context, KRB5_CC_END, N_("credential of wrong type for SCC:%s:%s", ""), s->name, s->file); sqlite3_reset(ctx->credstmt); return KRB5_CC_END; } data = sqlite3_column_blob(ctx->credstmt, 0); len = sqlite3_column_bytes(ctx->credstmt, 0); ret = decode_creds(context, data, len, creds); sqlite3_reset(ctx->credstmt); return ret; } static krb5_error_code KRB5_CALLCONV scc_end_get (krb5_context context, krb5_ccache id, krb5_cc_cursor *cursor) { struct cred_ctx *ctx = *cursor; krb5_scache *s = SCACHE(id); sqlite3_finalize(ctx->stmt); sqlite3_finalize(ctx->credstmt); exec_stmt(context, s->db, ctx->drop, 0); free(ctx->drop); free(ctx); return 0; } static krb5_error_code KRB5_CALLCONV scc_remove_cred(krb5_context context, krb5_ccache id, krb5_flags which, krb5_creds *mcreds) { krb5_scache *s = SCACHE(id); krb5_error_code ret; sqlite3_stmt *stmt; sqlite_uint64 credid = 0; const void *data = NULL; size_t len = 0; ret = make_database(context, s); if (ret) return ret; ret = prepare_stmt(context, s->db, &stmt, "SELECT cred,oid FROM credentials " "WHERE cid = ?"); if (ret) return ret; sqlite3_bind_int(stmt, 1, s->cid); /* find credential... */ while (1) { krb5_creds creds; ret = sqlite3_step(stmt); if (ret == SQLITE_DONE) { ret = 0; break; } else if (ret != SQLITE_ROW) { ret = KRB5_CC_IO; krb5_set_error_message(context, ret, N_("scache Database failed: %s", ""), sqlite3_errmsg(s->db)); break; } if (sqlite3_column_type(stmt, 0) != SQLITE_BLOB) { ret = KRB5_CC_END; krb5_set_error_message(context, ret, N_("Credential of wrong type " "for SCC:%s:%s", ""), s->name, s->file); break; } data = sqlite3_column_blob(stmt, 0); len = sqlite3_column_bytes(stmt, 0); ret = decode_creds(context, data, len, &creds); if (ret) break; ret = krb5_compare_creds(context, which, mcreds, &creds); krb5_free_cred_contents(context, &creds); if (ret) { credid = sqlite3_column_int64(stmt, 1); ret = 0; break; } } sqlite3_finalize(stmt); if (id) { ret = prepare_stmt(context, s->db, &stmt, "DELETE FROM credentials WHERE oid=?"); if (ret) return ret; sqlite3_bind_int(stmt, 1, credid); do { ret = sqlite3_step(stmt); } while (ret == SQLITE_ROW); sqlite3_finalize(stmt); if (ret != SQLITE_DONE) { ret = KRB5_CC_IO; krb5_set_error_message(context, ret, N_("failed to delete scache credental", "")); } else ret = 0; } return ret; } static krb5_error_code KRB5_CALLCONV scc_set_flags(krb5_context context, krb5_ccache id, krb5_flags flags) { return 0; /* XXX */ } struct cache_iter { char *drop; sqlite3 *db; sqlite3_stmt *stmt; }; static krb5_error_code KRB5_CALLCONV scc_get_cache_first(krb5_context context, krb5_cc_cursor *cursor) { struct cache_iter *ctx; krb5_error_code ret; char *name = NULL, *str = NULL; *cursor = NULL; ctx = calloc(1, sizeof(*ctx)); if (ctx == NULL) return krb5_enomem(context); ret = default_db(context, &ctx->db); if (ctx->db == NULL) { free(ctx); return ret; } ret = asprintf(&name, "cacheIteration%pPid%d", ctx, (int)getpid()); if (ret < 0 || name == NULL) { sqlite3_close(ctx->db); free(ctx); return krb5_enomem(context); } ret = asprintf(&ctx->drop, "DROP TABLE %s", name); if (ret < 0 || ctx->drop == NULL) { sqlite3_close(ctx->db); free(name); free(ctx); return krb5_enomem(context); } ret = asprintf(&str, "CREATE TEMPORARY TABLE %s AS SELECT name FROM caches", name); if (ret < 0 || str == NULL) { sqlite3_close(ctx->db); free(name); free(ctx->drop); free(ctx); return krb5_enomem(context); } ret = exec_stmt(context, ctx->db, str, KRB5_CC_IO); free(str); str = NULL; if (ret) { sqlite3_close(ctx->db); free(name); free(ctx->drop); free(ctx); return ret; } ret = asprintf(&str, "SELECT name FROM %s", name); if (ret < 0 || str == NULL) { exec_stmt(context, ctx->db, ctx->drop, 0); sqlite3_close(ctx->db); free(name); free(ctx->drop); free(ctx); return krb5_enomem(context); } free(name); ret = prepare_stmt(context, ctx->db, &ctx->stmt, str); free(str); if (ret) { exec_stmt(context, ctx->db, ctx->drop, 0); sqlite3_close(ctx->db); free(ctx->drop); free(ctx); return ret; } *cursor = ctx; return 0; } static krb5_error_code KRB5_CALLCONV scc_get_cache_next(krb5_context context, krb5_cc_cursor cursor, krb5_ccache *id) { struct cache_iter *ctx = cursor; krb5_error_code ret; const char *name; again: ret = sqlite3_step(ctx->stmt); if (ret == SQLITE_DONE) { krb5_clear_error_message(context); return KRB5_CC_END; } else if (ret != SQLITE_ROW) { krb5_set_error_message(context, KRB5_CC_IO, N_("Database failed: %s", ""), sqlite3_errmsg(ctx->db)); return KRB5_CC_IO; } if (sqlite3_column_type(ctx->stmt, 0) != SQLITE_TEXT) goto again; name = (const char *)sqlite3_column_text(ctx->stmt, 0); if (name == NULL) goto again; ret = _krb5_cc_allocate(context, &krb5_scc_ops, id); if (ret) return ret; return scc_resolve(context, id, name); } static krb5_error_code KRB5_CALLCONV scc_end_cache_get(krb5_context context, krb5_cc_cursor cursor) { struct cache_iter *ctx = cursor; exec_stmt(context, ctx->db, ctx->drop, 0); sqlite3_finalize(ctx->stmt); sqlite3_close(ctx->db); free(ctx->drop); free(ctx); return 0; } static krb5_error_code KRB5_CALLCONV scc_move(krb5_context context, krb5_ccache from, krb5_ccache to) { krb5_scache *sfrom = SCACHE(from); krb5_scache *sto = SCACHE(to); krb5_error_code ret; if (strcmp(sfrom->file, sto->file) != 0) { krb5_set_error_message(context, KRB5_CC_BADNAME, N_("Can't handle cross database " "credential move: %s -> %s", ""), sfrom->file, sto->file); return KRB5_CC_BADNAME; } ret = make_database(context, sfrom); if (ret) return ret; ret = exec_stmt(context, sfrom->db, "BEGIN IMMEDIATE TRANSACTION", KRB5_CC_IO); if (ret) return ret; if (sto->cid != SCACHE_INVALID_CID) { /* drop old cache entry */ sqlite3_bind_int(sfrom->dcache, 1, sto->cid); do { ret = sqlite3_step(sfrom->dcache); } while (ret == SQLITE_ROW); sqlite3_reset(sfrom->dcache); if (ret != SQLITE_DONE) { krb5_set_error_message(context, KRB5_CC_IO, N_("Failed to delete old cache: %d", ""), (int)ret); goto rollback; } } sqlite3_bind_text(sfrom->ucachen, 1, sto->name, -1, NULL); sqlite3_bind_int(sfrom->ucachen, 2, sfrom->cid); do { ret = sqlite3_step(sfrom->ucachen); } while (ret == SQLITE_ROW); sqlite3_reset(sfrom->ucachen); if (ret != SQLITE_DONE) { krb5_set_error_message(context, KRB5_CC_IO, N_("Failed to update new cache: %d", ""), (int)ret); goto rollback; } sto->cid = sfrom->cid; ret = exec_stmt(context, sfrom->db, "COMMIT", KRB5_CC_IO); if (ret) return ret; scc_free(sfrom); return 0; rollback: exec_stmt(context, sfrom->db, "ROLLBACK", 0); scc_free(sfrom); return KRB5_CC_IO; } static krb5_error_code KRB5_CALLCONV scc_get_default_name(krb5_context context, char **str) { krb5_error_code ret; char *name; *str = NULL; ret = get_def_name(context, &name); if (ret) return _krb5_expand_default_cc_name(context, KRB5_SCACHE_NAME, str); ret = asprintf(str, "SCC:%s", name); free(name); if (ret < 0 || *str == NULL) return krb5_enomem(context); return 0; } static krb5_error_code KRB5_CALLCONV scc_set_default(krb5_context context, krb5_ccache id) { krb5_scache *s = SCACHE(id); krb5_error_code ret; if (s->cid == SCACHE_INVALID_CID) { krb5_set_error_message(context, KRB5_CC_IO, N_("Trying to set a invalid cache " "as default %s", ""), s->name); return KRB5_CC_IO; } ret = sqlite3_bind_text(s->umaster, 1, s->name, -1, NULL); if (ret) { sqlite3_reset(s->umaster); krb5_set_error_message(context, KRB5_CC_IO, N_("Failed to set name of default cache", "")); return KRB5_CC_IO; } do { ret = sqlite3_step(s->umaster); } while (ret == SQLITE_ROW); sqlite3_reset(s->umaster); if (ret != SQLITE_DONE) { krb5_set_error_message(context, KRB5_CC_IO, N_("Failed to update default cache", "")); return KRB5_CC_IO; } return 0; } /** * Variable containing the SCC based credential cache implemention. * * @ingroup krb5_ccache */ KRB5_LIB_VARIABLE const krb5_cc_ops krb5_scc_ops = { KRB5_CC_OPS_VERSION, "SCC", scc_get_name, scc_resolve, scc_gen_new, scc_initialize, scc_destroy, scc_close, scc_store_cred, NULL, /* scc_retrieve */ scc_get_principal, scc_get_first, scc_get_next, scc_end_get, scc_remove_cred, scc_set_flags, NULL, scc_get_cache_first, scc_get_cache_next, scc_end_cache_get, scc_move, scc_get_default_name, scc_set_default, NULL, NULL, NULL }; #endif heimdal-7.5.0/lib/krb5/mk_req_ext.c0000644000175000017500000001147313026237312015172 0ustar niknik/* * Copyright (c) 1997 - 2002 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "krb5_locl.h" KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL _krb5_mk_req_internal(krb5_context context, krb5_auth_context *auth_context, const krb5_flags ap_req_options, krb5_data *in_data, krb5_creds *in_creds, krb5_data *outbuf, krb5_key_usage checksum_usage, krb5_key_usage encrypt_usage) { krb5_error_code ret; krb5_data authenticator; Checksum c; Checksum *c_opt; krb5_auth_context ac; if(auth_context) { if(*auth_context == NULL) ret = krb5_auth_con_init(context, auth_context); else ret = 0; ac = *auth_context; } else ret = krb5_auth_con_init(context, &ac); if(ret) return ret; if(ac->local_subkey == NULL && (ap_req_options & AP_OPTS_USE_SUBKEY)) { ret = krb5_auth_con_generatelocalsubkey(context, ac, &in_creds->session); if(ret) goto out; } krb5_free_keyblock(context, ac->keyblock); ret = krb5_copy_keyblock(context, &in_creds->session, &ac->keyblock); if (ret) goto out; /* it's unclear what type of checksum we can use. try the best one, except: * a) if it's configured differently for the current realm, or * b) if the session key is des-cbc-crc */ if (in_data) { if(ac->keyblock->keytype == ETYPE_DES_CBC_CRC) { /* this is to make DCE secd (and older MIT kdcs?) happy */ ret = krb5_create_checksum(context, NULL, 0, CKSUMTYPE_RSA_MD4, in_data->data, in_data->length, &c); } else if(ac->keyblock->keytype == ETYPE_ARCFOUR_HMAC_MD5 || ac->keyblock->keytype == ETYPE_ARCFOUR_HMAC_MD5_56 || ac->keyblock->keytype == ETYPE_DES_CBC_MD4 || ac->keyblock->keytype == ETYPE_DES_CBC_MD5) { /* this is to make MS kdc happy */ ret = krb5_create_checksum(context, NULL, 0, CKSUMTYPE_RSA_MD5, in_data->data, in_data->length, &c); } else { krb5_crypto crypto; ret = krb5_crypto_init(context, ac->keyblock, 0, &crypto); if (ret) goto out; ret = krb5_create_checksum(context, crypto, checksum_usage, 0, in_data->data, in_data->length, &c); krb5_crypto_destroy(context, crypto); } c_opt = &c; } else { c_opt = NULL; } if (ret) goto out; ret = _krb5_build_authenticator(context, ac, ac->keyblock->keytype, in_creds, c_opt, &authenticator, encrypt_usage); if (c_opt) free_Checksum (c_opt); if (ret) goto out; ret = krb5_build_ap_req (context, ac->keyblock->keytype, in_creds, ap_req_options, authenticator, outbuf); out: if(auth_context == NULL) krb5_auth_con_free(context, ac); return ret; } KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_mk_req_extended(krb5_context context, krb5_auth_context *auth_context, const krb5_flags ap_req_options, krb5_data *in_data, krb5_creds *in_creds, krb5_data *outbuf) { return _krb5_mk_req_internal (context, auth_context, ap_req_options, in_data, in_creds, outbuf, KRB5_KU_AP_REQ_AUTH_CKSUM, KRB5_KU_AP_REQ_AUTH); } heimdal-7.5.0/lib/krb5/mit_glue.c0000644000175000017500000002624213212137553014644 0ustar niknik/* * Copyright (c) 2003 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "krb5_locl.h" #ifndef HEIMDAL_SMALLER /* * Glue for MIT API */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_c_make_checksum(krb5_context context, krb5_cksumtype cksumtype, const krb5_keyblock *key, krb5_keyusage usage, const krb5_data *input, krb5_checksum *cksum) { krb5_error_code ret; krb5_crypto crypto; ret = krb5_crypto_init(context, key, 0, &crypto); if (ret) return ret; ret = krb5_create_checksum(context, crypto, usage, cksumtype, input->data, input->length, cksum); krb5_crypto_destroy(context, crypto); return ret ; } KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_c_verify_checksum(krb5_context context, const krb5_keyblock *key, krb5_keyusage usage, const krb5_data *data, const krb5_checksum *cksum, krb5_boolean *valid) { krb5_error_code ret; krb5_checksum data_cksum; *valid = 0; ret = krb5_c_make_checksum(context, cksum->cksumtype, key, usage, data, &data_cksum); if (ret) return ret; if (data_cksum.cksumtype == cksum->cksumtype && krb5_data_ct_cmp(&data_cksum.checksum, &cksum->checksum) == 0) *valid = 1; krb5_free_checksum_contents(context, &data_cksum); return 0; } KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_c_get_checksum(krb5_context context, const krb5_checksum *cksum, krb5_cksumtype *type, krb5_data **data) { krb5_error_code ret; if (type) *type = cksum->cksumtype; if (data) { *data = malloc(sizeof(**data)); if (*data == NULL) return krb5_enomem(context); ret = der_copy_octet_string(&cksum->checksum, *data); if (ret) { free(*data); *data = NULL; return ret; } } return 0; } KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_c_set_checksum(krb5_context context, krb5_checksum *cksum, krb5_cksumtype type, const krb5_data *data) { cksum->cksumtype = type; return der_copy_octet_string(data, &cksum->checksum); } KRB5_LIB_FUNCTION void KRB5_LIB_CALL krb5_free_checksum (krb5_context context, krb5_checksum *cksum) { krb5_checksum_free(context, cksum); free(cksum); } KRB5_LIB_FUNCTION void KRB5_LIB_CALL krb5_free_checksum_contents(krb5_context context, krb5_checksum *cksum) { krb5_checksum_free(context, cksum); memset(cksum, 0, sizeof(*cksum)); } KRB5_LIB_FUNCTION void KRB5_LIB_CALL krb5_checksum_free(krb5_context context, krb5_checksum *cksum) { free_Checksum(cksum); } KRB5_LIB_FUNCTION krb5_boolean KRB5_LIB_CALL krb5_c_valid_enctype (krb5_enctype etype) { return !krb5_enctype_valid(NULL, etype); } KRB5_LIB_FUNCTION krb5_boolean KRB5_LIB_CALL krb5_c_valid_cksumtype(krb5_cksumtype ctype) { return krb5_cksumtype_valid(NULL, ctype); } KRB5_LIB_FUNCTION krb5_boolean KRB5_LIB_CALL krb5_c_is_coll_proof_cksum(krb5_cksumtype ctype) { return krb5_checksum_is_collision_proof(NULL, ctype); } KRB5_LIB_FUNCTION krb5_boolean KRB5_LIB_CALL krb5_c_is_keyed_cksum(krb5_cksumtype ctype) { return krb5_checksum_is_keyed(NULL, ctype); } KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_copy_checksum (krb5_context context, const krb5_checksum *old, krb5_checksum **new) { *new = malloc(sizeof(**new)); if (*new == NULL) return krb5_enomem(context); return copy_Checksum(old, *new); } KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_c_checksum_length (krb5_context context, krb5_cksumtype cksumtype, size_t *length) { return krb5_checksumsize(context, cksumtype, length); } KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_c_block_size(krb5_context context, krb5_enctype enctype, size_t *blocksize) { krb5_error_code ret; krb5_crypto crypto; krb5_keyblock key; ret = krb5_generate_random_keyblock(context, enctype, &key); if (ret) return ret; ret = krb5_crypto_init(context, &key, 0, &crypto); krb5_free_keyblock_contents(context, &key); if (ret) return ret; ret = krb5_crypto_getblocksize(context, crypto, blocksize); krb5_crypto_destroy(context, crypto); return ret; } KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_c_decrypt(krb5_context context, const krb5_keyblock key, krb5_keyusage usage, const krb5_data *ivec, krb5_enc_data *input, krb5_data *output) { krb5_error_code ret; krb5_crypto crypto; ret = krb5_crypto_init(context, &key, input->enctype, &crypto); if (ret) return ret; if (ivec) { size_t blocksize; ret = krb5_crypto_getblocksize(context, crypto, &blocksize); if (ret) { krb5_crypto_destroy(context, crypto); return ret; } if (blocksize > ivec->length) { krb5_crypto_destroy(context, crypto); return KRB5_BAD_MSIZE; } } ret = krb5_decrypt_ivec(context, crypto, usage, input->ciphertext.data, input->ciphertext.length, output, ivec ? ivec->data : NULL); krb5_crypto_destroy(context, crypto); return ret ; } KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_c_encrypt(krb5_context context, const krb5_keyblock *key, krb5_keyusage usage, const krb5_data *ivec, const krb5_data *input, krb5_enc_data *output) { krb5_error_code ret; krb5_crypto crypto; ret = krb5_crypto_init(context, key, 0, &crypto); if (ret) return ret; if (ivec) { size_t blocksize; ret = krb5_crypto_getblocksize(context, crypto, &blocksize); if (ret) { krb5_crypto_destroy(context, crypto); return ret; } if (blocksize > ivec->length) { krb5_crypto_destroy(context, crypto); return KRB5_BAD_MSIZE; } } ret = krb5_encrypt_ivec(context, crypto, usage, input->data, input->length, &output->ciphertext, ivec ? ivec->data : NULL); output->kvno = 0; krb5_crypto_getenctype(context, crypto, &output->enctype); krb5_crypto_destroy(context, crypto); return ret ; } KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_c_encrypt_length(krb5_context context, krb5_enctype enctype, size_t inputlen, size_t *length) { krb5_error_code ret; krb5_crypto crypto; krb5_keyblock key; ret = krb5_generate_random_keyblock(context, enctype, &key); if (ret) return ret; ret = krb5_crypto_init(context, &key, 0, &crypto); krb5_free_keyblock_contents(context, &key); if (ret) return ret; *length = krb5_get_wrapped_length(context, crypto, inputlen); krb5_crypto_destroy(context, crypto); return 0; } /** * Deprecated: keytypes doesn't exists, they are really enctypes. * * @ingroup krb5_deprecated */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_c_enctype_compare(krb5_context context, krb5_enctype e1, krb5_enctype e2, krb5_boolean *similar) KRB5_DEPRECATED_FUNCTION("Use X instead") { *similar = (e1 == e2); return 0; } KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_c_make_random_key(krb5_context context, krb5_enctype enctype, krb5_keyblock *random_key) { return krb5_generate_random_keyblock(context, enctype, random_key); } KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_c_keylengths(krb5_context context, krb5_enctype enctype, size_t *ilen, size_t *keylen) { krb5_error_code ret; ret = krb5_enctype_keybits(context, enctype, ilen); if (ret) return ret; *ilen = (*ilen + 7) / 8; return krb5_enctype_keysize(context, enctype, keylen); } KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_c_prf_length(krb5_context context, krb5_enctype type, size_t *length) { return krb5_crypto_prf_length(context, type, length); } KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_c_prf(krb5_context context, const krb5_keyblock *key, const krb5_data *input, krb5_data *output) { krb5_crypto crypto; krb5_error_code ret; ret = krb5_crypto_init(context, key, 0, &crypto); if (ret) return ret; ret = krb5_crypto_prf(context, crypto, input, output); krb5_crypto_destroy(context, crypto); return ret; } KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_c_random_make_octets(krb5_context context, krb5_data * data) { krb5_generate_random_block(data->data, data->length); return 0; } /** * MIT compat glue * * @ingroup krb5_ccache */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_cc_copy_creds(krb5_context context, const krb5_ccache from, krb5_ccache to) { return krb5_cc_copy_cache(context, from, to); } KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_auth_con_getsendsubkey(krb5_context context, krb5_auth_context auth_context, krb5_keyblock **keyblock) { return krb5_auth_con_getlocalsubkey(context, auth_context, keyblock); } KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_auth_con_getrecvsubkey(krb5_context context, krb5_auth_context auth_context, krb5_keyblock **keyblock) { return krb5_auth_con_getremotesubkey(context, auth_context, keyblock); } KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_auth_con_setsendsubkey(krb5_context context, krb5_auth_context auth_context, krb5_keyblock *keyblock) { return krb5_auth_con_setlocalsubkey(context, auth_context, keyblock); } KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_auth_con_setrecvsubkey(krb5_context context, krb5_auth_context auth_context, krb5_keyblock *keyblock) { return krb5_auth_con_setremotesubkey(context, auth_context, keyblock); } KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_free_default_realm(krb5_context context, krb5_realm realm) { return krb5_xfree(realm); } #endif /* HEIMDAL_SMALLER */ heimdal-7.5.0/lib/krb5/krb5_digest.30000644000175000017500000001511113026237312015147 0ustar niknik.\" Copyright (c) 2006 - 2007 Kungliga Tekniska Högskolan .\" (Royal Institute of Technology, Stockholm, Sweden). .\" All rights reserved. .\" .\" Redistribution and use in source and binary forms, with or without .\" modification, are permitted provided that the following conditions .\" are met: .\" .\" 1. Redistributions of source code must retain the above copyright .\" notice, this list of conditions and the following disclaimer. .\" .\" 2. Redistributions in binary form must reproduce the above copyright .\" notice, this list of conditions and the following disclaimer in the .\" documentation and/or other materials provided with the distribution. .\" .\" 3. Neither the name of the Institute nor the names of its contributors .\" may be used to endorse or promote products derived from this software .\" without specific prior written permission. .\" .\" THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND .\" ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE .\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE .\" ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE .\" FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL .\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS .\" OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) .\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT .\" LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF .\" SUCH DAMAGE. .\" .\" $Id$ .\" .Dd February 18, 2007 .Dt KRB5_DIGEST 3 .Os HEIMDAL .Sh NAME .Nm krb5_digest , .Nm krb5_digest_alloc , .Nm krb5_digest_free , .Nm krb5_digest_set_server_cb , .Nm krb5_digest_set_type , .Nm krb5_digest_set_hostname , .Nm krb5_digest_get_server_nonce , .Nm krb5_digest_set_server_nonce , .Nm krb5_digest_get_opaque , .Nm krb5_digest_set_opaque , .Nm krb5_digest_get_identifier , .Nm krb5_digest_set_identifier , .Nm krb5_digest_init_request , .Nm krb5_digest_set_client_nonce , .Nm krb5_digest_set_digest , .Nm krb5_digest_set_username , .Nm krb5_digest_set_authid , .Nm krb5_digest_set_authentication_user , .Nm krb5_digest_set_realm , .Nm krb5_digest_set_method , .Nm krb5_digest_set_uri , .Nm krb5_digest_set_nonceCount , .Nm krb5_digest_set_qop , .Nm krb5_digest_request , .Nm krb5_digest_get_responseData , .Nm krb5_digest_get_rsp , .Nm krb5_digest_get_tickets , .Nm krb5_digest_get_client_binding , .Nm krb5_digest_get_a1_hash .Nd remote digest (HTTP-DIGEST, SASL, CHAP) support .Sh LIBRARY Kerberos 5 Library (libkrb5, -lkrb5) .Sh SYNOPSIS .In krb5.h .Pp .Li "typedef struct krb5_digest *krb5_digest;" .Pp .Ft krb5_error_code .Fo krb5_digest_alloc .Fa "krb5_context context" .Fa "krb5_digest *digest" .Fc .Ft void .Fo krb5_digest_free .Fa "krb5_digest digest" .Fc .Ft krb5_error_code .Fo krb5_digest_set_type .Fa "krb5_context context" .Fa "krb5_digest digest" .Fa "const char *type" .Fc .Ft krb5_error_code .Fo krb5_digest_set_server_cb .Fa "krb5_context context" .Fa "krb5_digest digest" .Fa "const char *type" .Fa "const char *binding" .Fc .Ft krb5_error_code .Fo krb5_digest_set_hostname .Fa "krb5_context context" .Fa "krb5_digest digest" .Fa "const char *hostname" .Fc .Ft "const char *" .Fo krb5_digest_get_server_nonce .Fa "krb5_context context" .Fa "krb5_digest digest" .Fc .Ft krb5_error_code .Fo krb5_digest_set_server_nonce .Fa "krb5_context context" .Fa "krb5_digest digest" .Fa "const char *nonce" .Fc .Ft "const char *" .Fo krb5_digest_get_opaque .Fa "krb5_context context" .Fa "krb5_digest digest" .Fc .Ft krb5_error_code .Fo krb5_digest_set_opaque .Fa "krb5_context context" .Fa "krb5_digest digest" .Fa "const char *opaque" .Fc .Ft "const char *" .Fo krb5_digest_get_identifier .Fa "krb5_context context" .Fa "krb5_digest digest" .Fc .Ft krb5_error_code .Fo krb5_digest_set_identifier .Fa "krb5_context context" .Fa "krb5_digest digest" .Fa "const char *id" .Fc .Ft krb5_error_code .Fo krb5_digest_init_request .Fa "krb5_context context" .Fa "krb5_digest digest" .Fa "krb5_realm realm" .Fa "krb5_ccache ccache" .Fc .Ft krb5_error_code .Fo krb5_digest_set_client_nonce .Fa "krb5_context context" .Fa "krb5_digest digest" .Fa "const char *nonce" .Fc .Ft krb5_error_code .Fo krb5_digest_set_digest .Fa "krb5_context context" .Fa "krb5_digest digest" .Fa "const char *dgst" .Fc .Ft krb5_error_code .Fo krb5_digest_set_username .Fa "krb5_context context" .Fa "krb5_digest digest" .Fa "const char *username" .Fc .Ft krb5_error_code .Fo krb5_digest_set_authid .Fa "krb5_context context" .Fa "krb5_digest digest" .Fa "const char *authid" .Fc .Ft krb5_error_code .Fo krb5_digest_set_authentication_user .Fa "krb5_context context" .Fa "krb5_digest digest" .Fa "krb5_principal authentication_user" .Fc .Ft krb5_error_code .Fo krb5_digest_set_realm .Fa "krb5_context context" .Fa "krb5_digest digest" .Fa "const char *realm" .Fc .Ft krb5_error_code .Fo krb5_digest_set_method .Fa "krb5_context context" .Fa "krb5_digest digest" .Fa "const char *method" .Fc .Ft krb5_error_code .Fo krb5_digest_set_uri .Fa "krb5_context context" .Fa "krb5_digest digest" .Fa "const char *uri" .Fc .Ft krb5_error_code .Fo krb5_digest_set_nonceCount .Fa "krb5_context context" .Fa "krb5_digest digest" .Fa "const char *nonce_count" .Fc .Ft krb5_error_code .Fo krb5_digest_set_qop .Fa "krb5_context context" .Fa "krb5_digest digest" .Fa "const char *qop" .Fc .Ft krb5_error_code .Fo krb5_digest_request .Fa "krb5_context context" .Fa "krb5_digest digest" .Fa "krb5_realm realm" .Fa "krb5_ccache ccache" .Fc .Ft "const char *" .Fo krb5_digest_get_responseData .Fa "krb5_context context" .Fa "krb5_digest digest" .Fc .Ft "const char *" .Fo krb5_digest_get_rsp .Fa "krb5_context context" .Fa "krb5_digest digest" .Fc .Ft krb5_error_code .Fo krb5_digest_get_tickets .Fa "krb5_context context" .Fa "krb5_digest digest" .Fa "Ticket **tickets" .Fc .Ft krb5_error_code .Fo krb5_digest_get_client_binding .Fa "krb5_context context" .Fa "krb5_digest digest" .Fa "char **type" .Fa "char **binding" .Fc .Ft krb5_error_code .Fo krb5_digest_get_a1_hash .Fa "krb5_context context" .Fa "krb5_digest digest" .Fa "krb5_data *data" .Fc .Sh DESCRIPTION The .Fn krb5_digest_alloc function allocatates the .Fa digest structure. The structure should be freed with .Fn krb5_digest_free when it is no longer being used. .Pp .Fn krb5_digest_alloc returns 0 to indicate success. Otherwise an kerberos code is returned and the pointer that .Fa digest points to is set to .Dv NULL . .Pp .Fn krb5_digest_free free the structure .Fa digest . .Sh SEE ALSO .Xr krb5 3 , .Xr kerberos 8 heimdal-7.5.0/lib/krb5/krb5_check_transited.30000644000175000017500000000644313026237312017032 0ustar niknik.\" Copyright (c) 2004, 2006 Kungliga Tekniska Högskolan .\" (Royal Institute of Technology, Stockholm, Sweden). .\" All rights reserved. .\" .\" Redistribution and use in source and binary forms, with or without .\" modification, are permitted provided that the following conditions .\" are met: .\" .\" 1. Redistributions of source code must retain the above copyright .\" notice, this list of conditions and the following disclaimer. .\" .\" 2. Redistributions in binary form must reproduce the above copyright .\" notice, this list of conditions and the following disclaimer in the .\" documentation and/or other materials provided with the distribution. .\" .\" 3. Neither the name of the Institute nor the names of its contributors .\" may be used to endorse or promote products derived from this software .\" without specific prior written permission. .\" .\" THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND .\" ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE .\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE .\" ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE .\" FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL .\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS .\" OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) .\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT .\" LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF .\" SUCH DAMAGE. .\" .\" $Id$ .\" .Dd May 1, 2006 .Dt KRB5_CHECK_TRANSITED 3 .Os HEIMDAL .Sh NAME .Nm krb5_check_transited , .Nm krb5_check_transited_realms , .Nm krb5_domain_x500_decode , .Nm krb5_domain_x500_encode .Nd realm transit verification and encoding/decoding functions .Sh LIBRARY Kerberos 5 Library (libkrb5, -lkrb5) .Sh SYNOPSIS .In krb5.h .Ft krb5_error_code .Fo krb5_check_transited .Fa "krb5_context context" .Fa "krb5_const_realm client_realm" .Fa "krb5_const_realm server_realm" .Fa "krb5_realm *realms" .Fa "int num_realms" .Fa "int *bad_realm" .Fc .Ft krb5_error_code .Fo krb5_check_transited_realms .Fa "krb5_context context" .Fa "const char *const *realms" .Fa "int num_realms" .Fa "int *bad_realm" .Fc .Ft krb5_error_code .Fo krb5_domain_x500_decode .Fa "krb5_context context" .Fa "krb5_data tr" .Fa "char ***realms" .Fa "int *num_realms" .Fa "const char *client_realm" .Fa "const char *server_realm" .Fc .Ft krb5_error_code .Fo krb5_domain_x500_encode .Fa "char **realms" .Fa "int num_realms" .Fa "krb5_data *encoding" .Fc .Sh DESCRIPTION .Fn krb5_check_transited checks the path from .Fa client_realm to .Fa server_realm where .Fa realms and .Fa num_realms is the realms between them. If the function returns an error value, .Fa bad_realm will be set to the realm in the list causing the error. .Fn krb5_check_transited is used internally by the KDC and libkrb5 and should not be called by client applications. .Pp .Fn krb5_check_transited_realms is deprecated. .Pp .Fn krb5_domain_x500_encode and .Fn krb5_domain_x500_decode encodes and decodes the realm names in the X500 format that Kerberos uses to describe the transited realms in krbtgts. .Sh SEE ALSO .Xr krb5 3 , .Xr krb5.conf 5 heimdal-7.5.0/lib/krb5/k524_err.et0000644000175000017500000000110112136107750014545 0ustar niknik# # Error messages for the k524 functions # # This might look like a com_err file, but is not # id "$Id$" error_table k524 prefix KRB524 error_code BADKEY, "wrong keytype in ticket" error_code BADADDR, "incorrect network address" error_code BADPRINC, "cannot convert V5 principal" #unused error_code BADREALM, "V5 realm name longer than V4 maximum" #unused error_code V4ERR, "kerberos V4 error server" error_code ENCFULL, "encoding too large at server" error_code DECEMPTY, "decoding out of data" #unused error_code NOTRESP, "service not responding" #unused end heimdal-7.5.0/lib/krb5/krb5_is_thread_safe.30000644000175000017500000000436513026237312016641 0ustar niknik.\" Copyright (c) 2005 Kungliga Tekniska Högskolan .\" (Royal Institute of Technology, Stockholm, Sweden). .\" All rights reserved. .\" .\" Redistribution and use in source and binary forms, with or without .\" modification, are permitted provided that the following conditions .\" are met: .\" .\" 1. Redistributions of source code must retain the above copyright .\" notice, this list of conditions and the following disclaimer. .\" .\" 2. Redistributions in binary form must reproduce the above copyright .\" notice, this list of conditions and the following disclaimer in the .\" documentation and/or other materials provided with the distribution. .\" .\" 3. Neither the name of the Institute nor the names of its contributors .\" may be used to endorse or promote products derived from this software .\" without specific prior written permission. .\" .\" THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND .\" ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE .\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE .\" ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE .\" FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL .\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS .\" OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) .\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT .\" LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF .\" SUCH DAMAGE. .\" .\" $Id$ .\" .Dd May 5, 2006 .Dt KRB5_IS_THREAD_SAFE 3 .Os HEIMDAL .Sh NAME .Nm krb5_is_thread_safe .Nd "is the Kerberos library compiled with multithread support" .Sh LIBRARY Kerberos 5 Library (libkrb5, -lkrb5) .Sh SYNOPSIS .In krb5.h .Ft krb5_boolean .Fn krb5_is_thread_safe "void" .Sh DESCRIPTION .Nm returns .Dv TRUE if the library was compiled with with multithread support. If the library isn't compiled, the consumer have to use a global lock to make sure Kerboros functions are not called at the same time by different threads. .\" .Sh EXAMPLE .\" .Sh BUGS .Sh SEE ALSO .Xr krb5_create_checksum 3 , .Xr krb5_encrypt 3 heimdal-7.5.0/lib/krb5/add_et_list.c0000644000175000017500000000431112136107750015303 0ustar niknik/* * Copyright (c) 1999 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "krb5_locl.h" /** * Add a specified list of error messages to the et list in context. * Call func (probably a comerr-generated function) with a pointer to * the current et_list. * * @param context A kerberos context. * @param func The generated com_err et function. * * @return Returns 0 to indicate success. Otherwise an kerberos et * error code is returned, see krb5_get_error_message(). * * @ingroup krb5 */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_add_et_list (krb5_context context, void (*func)(struct et_list **)) { (*func)(&context->et_list); return 0; } heimdal-7.5.0/lib/krb5/kuserok_plugin.h0000644000175000017500000000730113026237312016075 0ustar niknik/* * Copyright (c) 2011, Secure Endpoints Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * - Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. * */ #ifndef HEIMDAL_KRB5_KUSEROK_PLUGIN_H #define HEIMDAL_KRB5_KUSEROK_PLUGIN_H 1 #define KRB5_PLUGIN_KUSEROK "krb5_plugin_kuserok" #define KRB5_PLUGIN_KUSEROK_VERSION_0 0 /** @struct krb5plugin_kuserok_ftable_desc * * @brief Description of the krb5_kuserok(3) plugin facility. * * The krb5_kuserok(3) function is pluggable. The plugin is named * KRB5_PLUGIN_KUSEROK ("krb5_plugin_kuserok"), with a single minor * version, KRB5_PLUGIN_KUSEROK_VERSION_0 (0). * * The plugin for krb5_kuserok(3) consists of a data symbol referencing * a structure of type krb5plugin_kuserok_ftable, with four fields: * * @param init Plugin initialization function (see krb5-plugin(7)) * * @param minor_version The plugin minor version number (0) * * @param fini Plugin finalization function * * @param kuserok Plugin kuserok function * * The kuserok field is the plugin entry point that performs the * traditional kuserok operation however the plugin desires. It is * invoked in no particular order relative to other kuserok plugins, but * it has a 'rule' argument that indicates which plugin is intended to * act on the rule. The plugin kuserok function must return * KRB5_PLUGIN_NO_HANDLE if the rule is not applicable to it. * * The plugin kuserok function has the following arguments, in this * order: * * -# plug_ctx, the context value output by the plugin's init function * -# context, a krb5_context * -# rule, the kuserok rule being evaluated (from krb5.conf(5)) * -# flags * -# k5login_dir, configured location of k5login per-user files if any * -# luser, name of the local user account to which principal is attempting to access. * -# principal, the krb5_principal trying to access the luser account * -# result, a krb5_boolean pointer where the plugin will output its result * * @ingroup krb5_support */ typedef struct krb5plugin_kuserok_ftable_desc { int minor_version; krb5_error_code (KRB5_LIB_CALL *init)(krb5_context, void **); void (KRB5_LIB_CALL *fini)(void *); krb5_error_code (KRB5_LIB_CALL *kuserok)(void *, krb5_context, const char *, unsigned int, const char *, const char *, krb5_const_principal, krb5_boolean *); } krb5plugin_kuserok_ftable; #define KUSEROK_ANAME_TO_LNAME_OK 1 #define KUSEROK_K5LOGIN_IS_AUTHORITATIVE 2 #endif /* HEIMDAL_KRB5_KUSEROK_PLUGIN_H */ heimdal-7.5.0/lib/krb5/padata.c0000644000175000017500000000442713026237312014267 0ustar niknik/* * Copyright (c) 1997 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "krb5_locl.h" KRB5_LIB_FUNCTION PA_DATA * KRB5_LIB_CALL krb5_find_padata(PA_DATA *val, unsigned len, int type, int *idx) { for(; *idx < (int)len; (*idx)++) if(val[*idx].padata_type == (unsigned)type) return val + *idx; return NULL; } KRB5_LIB_FUNCTION int KRB5_LIB_CALL krb5_padata_add(krb5_context context, METHOD_DATA *md, int type, void *buf, size_t len) { PA_DATA *pa; pa = realloc (md->val, (md->len + 1) * sizeof(*md->val)); if (pa == NULL) return krb5_enomem(context); md->val = pa; pa[md->len].padata_type = type; pa[md->len].padata_value.length = len; pa[md->len].padata_value.data = buf; md->len++; return 0; } heimdal-7.5.0/lib/krb5/keyblock.c0000644000175000017500000001240413026237312014632 0ustar niknik/* * Copyright (c) 1997 - 2001 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "krb5_locl.h" /** * Zero out a keyblock * * @param keyblock keyblock to zero out * * @ingroup krb5_crypto */ KRB5_LIB_FUNCTION void KRB5_LIB_CALL krb5_keyblock_zero(krb5_keyblock *keyblock) { keyblock->keytype = 0; krb5_data_zero(&keyblock->keyvalue); } /** * Free a keyblock's content, also zero out the content of the keyblock. * * @param context a Kerberos 5 context * @param keyblock keyblock content to free, NULL is valid argument * * @ingroup krb5_crypto */ KRB5_LIB_FUNCTION void KRB5_LIB_CALL krb5_free_keyblock_contents(krb5_context context, krb5_keyblock *keyblock) { if(keyblock) { if (keyblock->keyvalue.data != NULL) memset(keyblock->keyvalue.data, 0, keyblock->keyvalue.length); krb5_data_free (&keyblock->keyvalue); keyblock->keytype = KRB5_ENCTYPE_NULL; } } /** * Free a keyblock, also zero out the content of the keyblock, uses * krb5_free_keyblock_contents() to free the content. * * @param context a Kerberos 5 context * @param keyblock keyblock to free, NULL is valid argument * * @ingroup krb5_crypto */ KRB5_LIB_FUNCTION void KRB5_LIB_CALL krb5_free_keyblock(krb5_context context, krb5_keyblock *keyblock) { if(keyblock){ krb5_free_keyblock_contents(context, keyblock); free(keyblock); } } /** * Copy a keyblock, free the output keyblock with * krb5_free_keyblock_contents(). * * @param context a Kerberos 5 context * @param inblock the key to copy * @param to the output key. * * @return 0 on success or a Kerberos 5 error code * * @ingroup krb5_crypto */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_copy_keyblock_contents (krb5_context context, const krb5_keyblock *inblock, krb5_keyblock *to) { return copy_EncryptionKey(inblock, to); } /** * Copy a keyblock, free the output keyblock with * krb5_free_keyblock(). * * @param context a Kerberos 5 context * @param inblock the key to copy * @param to the output key. * * @return 0 on success or a Kerberos 5 error code * * @ingroup krb5_crypto */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_copy_keyblock (krb5_context context, const krb5_keyblock *inblock, krb5_keyblock **to) { krb5_error_code ret; krb5_keyblock *k; *to = NULL; k = calloc (1, sizeof(*k)); if (k == NULL) return krb5_enomem(context); ret = krb5_copy_keyblock_contents (context, inblock, k); if (ret) { free(k); return ret; } *to = k; return 0; } /** * Get encryption type of a keyblock. * * @ingroup krb5_crypto */ KRB5_LIB_FUNCTION krb5_enctype KRB5_LIB_CALL krb5_keyblock_get_enctype(const krb5_keyblock *block) { return block->keytype; } /** * Fill in `key' with key data of type `enctype' from `data' of length * `size'. Key should be freed using krb5_free_keyblock_contents(). * * @return 0 on success or a Kerberos 5 error code * * @ingroup krb5_crypto */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_keyblock_init(krb5_context context, krb5_enctype type, const void *data, size_t size, krb5_keyblock *key) { krb5_error_code ret; size_t len; memset(key, 0, sizeof(*key)); ret = krb5_enctype_keysize(context, type, &len); if (ret) return ret; if (len != size) { krb5_set_error_message(context, KRB5_PROG_ETYPE_NOSUPP, "Encryption key %d is %lu bytes " "long, %lu was passed in", type, (unsigned long)len, (unsigned long)size); return KRB5_PROG_ETYPE_NOSUPP; } ret = krb5_data_copy(&key->keyvalue, data, len); if(ret) { krb5_set_error_message(context, ret, N_("malloc: out of memory", "")); return ret; } key->keytype = type; return 0; } heimdal-7.5.0/lib/krb5/libkrb5-exports.def.in0000644000175000017500000004461213212137553017015 0ustar niknikEXPORTS krb524_convert_creds_kdc krb524_convert_creds_kdc_ccache krb5_abort krb5_abortx krb5_acl_match_file krb5_acl_match_string krb5_add_et_list krb5_add_extra_addresses krb5_add_ignore_addresses krb5_addlog_dest krb5_addlog_func krb5_addr2sockaddr krb5_address_compare krb5_address_order krb5_address_prefixlen_boundary krb5_address_search krb5_allow_weak_crypto krb5_aname_to_localname krb5_anyaddr krb5_appdefault_boolean krb5_appdefault_string krb5_appdefault_time krb5_append_addresses krb5_auth_con_addflags krb5_auth_con_free krb5_auth_con_genaddrs krb5_auth_con_generatelocalsubkey krb5_auth_con_getaddrs krb5_auth_con_getauthenticator krb5_auth_con_getcksumtype krb5_auth_con_getflags krb5_auth_con_getkey krb5_auth_con_getkeytype krb5_auth_con_getlocalseqnumber krb5_auth_con_getlocalsubkey krb5_auth_con_getrcache krb5_auth_con_getremoteseqnumber krb5_auth_con_getremotesubkey krb5_auth_con_init krb5_auth_con_removeflags krb5_auth_con_setaddrs krb5_auth_con_setaddrs_from_fd krb5_auth_con_setcksumtype krb5_auth_con_setflags krb5_auth_con_setkey krb5_auth_con_setkeytype krb5_auth_con_setlocalseqnumber krb5_auth_con_setlocalsubkey krb5_auth_con_setrcache krb5_auth_con_setremoteseqnumber krb5_auth_con_setremotesubkey krb5_auth_con_setuserkey krb5_auth_getremoteseqnumber krb5_build_ap_req krb5_build_principal krb5_build_principal_ext krb5_build_principal_va krb5_build_principal_va_ext krb5_c_block_size krb5_c_checksum_length krb5_c_decrypt krb5_c_encrypt krb5_c_encrypt_length krb5_c_enctype_compare krb5_c_get_checksum krb5_c_is_coll_proof_cksum krb5_c_is_keyed_cksum krb5_c_keylengths krb5_c_make_checksum krb5_c_make_random_key krb5_c_prf krb5_c_prf_length krb5_c_random_make_octets ;! krb5_c_set_checksum krb5_c_valid_cksumtype krb5_c_valid_enctype krb5_c_verify_checksum krb5_cc_cache_end_seq_get krb5_cc_cache_get_first krb5_cc_cache_match krb5_cc_cache_next krb5_cc_clear_mcred krb5_cc_close krb5_cc_copy_cache krb5_cc_copy_creds ;! krb5_cc_copy_match_f krb5_cc_default krb5_cc_default_name krb5_cc_destroy krb5_cc_end_seq_get krb5_cc_gen_new krb5_cc_get_config krb5_cc_get_friendly_name krb5_cc_get_full_name krb5_cc_get_kdc_offset krb5_cc_get_lifetime krb5_cc_get_name krb5_cc_get_ops krb5_cc_get_prefix_ops krb5_cc_get_principal krb5_cc_get_type krb5_cc_get_version krb5_cc_initialize krb5_cc_last_change_time krb5_cc_move krb5_cc_new_unique krb5_cc_next_cred ;! krb5_cc_next_cred_match krb5_cc_register krb5_cc_remove_cred krb5_cc_resolve krb5_cc_retrieve_cred krb5_cc_set_config krb5_cc_set_default_name krb5_cc_set_flags krb5_cc_set_kdc_offset krb5_cc_start_seq_get krb5_cc_store_cred krb5_cc_support_switch krb5_cc_switch krb5_cc_set_friendly_name krb5_change_password krb5_check_transited krb5_check_transited_realms krb5_checksum_disable krb5_checksum_free krb5_checksum_is_collision_proof krb5_checksum_is_keyed krb5_checksumsize krb5_cksumtype_to_enctype krb5_cksumtype_valid krb5_clear_error_string krb5_clear_error_message krb5_closelog krb5_compare_creds krb5_config_file_free krb5_config_free_strings ; _krb5_config_get krb5_config_get_bool krb5_config_get_bool_default krb5_config_get_int krb5_config_get_int_default krb5_config_get_list ; _krb5_config_get_next krb5_config_get_string krb5_config_get_string_default krb5_config_get_strings krb5_config_get_time krb5_config_get_time_default krb5_config_parse_file krb5_config_parse_file_multi krb5_config_parse_string_multi ; _krb5_config_vget krb5_config_vget_bool krb5_config_vget_bool_default krb5_config_vget_int krb5_config_vget_int_default krb5_config_vget_list ; _krb5_config_vget_next krb5_config_vget_string krb5_config_vget_string_default krb5_config_vget_strings krb5_config_vget_time krb5_config_vget_time_default krb5_copy_address krb5_copy_addresses krb5_copy_checksum krb5_copy_context krb5_copy_creds krb5_copy_creds_contents krb5_copy_data krb5_copy_host_realm krb5_copy_keyblock krb5_copy_keyblock_contents krb5_copy_principal krb5_copy_ticket krb5_create_checksum krb5_create_checksum_iov krb5_crypto_destroy krb5_crypto_fx_cf2 krb5_crypto_get_checksum_type krb5_crypto_getblocksize krb5_crypto_getconfoundersize krb5_crypto_getenctype krb5_crypto_getpadsize krb5_crypto_init krb5_crypto_overhead krb5_crypto_prf krb5_crypto_prf_length krb5_crypto_length krb5_crypto_length_iov krb5_decrypt_iov_ivec krb5_encrypt_iov_ivec krb5_data_alloc krb5_data_cmp krb5_data_copy krb5_data_ct_cmp krb5_data_free krb5_data_realloc krb5_data_zero krb5_decode_Authenticator krb5_decode_ETYPE_INFO2 krb5_decode_ETYPE_INFO krb5_decode_EncAPRepPart krb5_decode_EncASRepPart krb5_decode_EncKrbCredPart krb5_decode_EncTGSRepPart krb5_decode_EncTicketPart krb5_decode_ap_req krb5_decrypt krb5_decrypt_EncryptedData krb5_decrypt_ivec krb5_decrypt_ticket krb5_derive_key krb5_digest_alloc krb5_digest_free krb5_digest_get_client_binding krb5_digest_get_identifier krb5_digest_get_opaque krb5_digest_get_rsp krb5_digest_get_server_nonce krb5_digest_get_session_key krb5_digest_get_tickets krb5_digest_init_request krb5_digest_probe krb5_digest_rep_get_status krb5_digest_request krb5_digest_set_authentication_user krb5_digest_set_authid krb5_digest_set_client_nonce krb5_digest_set_digest krb5_digest_set_hostname krb5_digest_set_identifier krb5_digest_set_method krb5_digest_set_nonceCount krb5_digest_set_opaque krb5_digest_set_qop krb5_digest_set_realm krb5_digest_set_responseData krb5_digest_set_server_cb krb5_digest_set_server_nonce krb5_digest_set_type krb5_digest_set_uri krb5_digest_set_username krb5_domain_x500_decode krb5_domain_x500_encode krb5_eai_to_heim_errno krb5_encode_Authenticator krb5_encode_ETYPE_INFO2 krb5_encode_ETYPE_INFO krb5_encode_EncAPRepPart krb5_encode_EncASRepPart krb5_encode_EncKrbCredPart krb5_encode_EncTGSRepPart krb5_encode_EncTicketPart krb5_encrypt krb5_encrypt_EncryptedData krb5_encrypt_ivec krb5_enctype_enable krb5_enctype_disable krb5_enctype_keybits krb5_enctype_keysize krb5_enctype_to_keytype krb5_enctype_to_string krb5_enctype_valid krb5_enctypes_compatible_keys krb5_enomem krb5_err krb5_error_from_rd_error krb5_errx krb5_expand_hostname krb5_expand_hostname_realms krb5_find_padata krb5_format_time krb5_free_address krb5_free_addresses krb5_free_ap_rep_enc_part krb5_free_authenticator krb5_free_checksum krb5_free_checksum_contents krb5_free_config_files krb5_free_context krb5_free_cred_contents krb5_free_creds krb5_free_creds_contents krb5_free_data krb5_free_data_contents krb5_free_default_realm krb5_free_error krb5_free_error_contents krb5_free_error_string krb5_free_error_message krb5_free_host_realm krb5_free_kdc_rep krb5_free_keyblock krb5_free_keyblock_contents krb5_free_krbhst krb5_free_principal krb5_free_salt krb5_free_ticket krb5_free_unparsed_name krb5_fwd_tgt_creds krb5_generate_random_block krb5_generate_random_keyblock krb5_generate_seq_number krb5_generate_subkey krb5_generate_subkey_extended krb5_get_all_client_addrs krb5_get_all_server_addrs krb5_get_cred_from_kdc krb5_get_cred_from_kdc_opt krb5_get_credentials krb5_get_credentials_with_flags krb5_get_creds krb5_get_creds_opt_add_options krb5_get_creds_opt_alloc krb5_get_creds_opt_free krb5_get_creds_opt_set_enctype krb5_get_creds_opt_set_impersonate krb5_get_creds_opt_set_options krb5_get_creds_opt_set_ticket krb5_get_default_config_files krb5_get_default_in_tkt_etypes krb5_get_default_principal krb5_get_default_realm krb5_get_default_realms krb5_get_dns_canonicalize_hostname krb5_get_err_text krb5_get_error_message krb5_get_error_string krb5_get_extra_addresses krb5_get_fcache_version krb5_get_forwarded_creds krb5_get_host_realm krb5_get_ignore_addresses krb5_get_in_cred ; krb5_cccol_last_change_time krb5_get_in_tkt krb5_get_in_tkt_with_keytab krb5_get_in_tkt_with_password krb5_get_in_tkt_with_skey ;! krb5_get_init_creds krb5_get_init_creds_keyblock krb5_get_init_creds_keytab krb5_get_init_creds_opt_alloc krb5_get_init_creds_opt_free krb5_get_init_creds_opt_get_error krb5_get_init_creds_opt_init krb5_get_init_creds_opt_set_address_list krb5_get_init_creds_opt_set_addressless krb5_get_init_creds_opt_set_anonymous krb5_get_init_creds_opt_set_change_password_prompt krb5_get_init_creds_opt_set_canonicalize krb5_get_init_creds_opt_set_default_flags krb5_get_init_creds_opt_set_etype_list krb5_get_init_creds_opt_set_forwardable krb5_get_init_creds_opt_set_pa_password krb5_get_init_creds_opt_set_pac_request krb5_get_init_creds_opt_set_pkinit krb5_get_init_creds_opt_set_preauth_list krb5_get_init_creds_opt_set_process_last_req krb5_get_init_creds_opt_set_proxiable krb5_get_init_creds_opt_set_renew_life krb5_get_init_creds_opt_set_salt krb5_get_init_creds_opt_set_tkt_life krb5_get_init_creds_opt_set_win2k krb5_get_init_creds_password krb5_get_kdc_cred krb5_get_kdc_sec_offset krb5_get_krb524hst krb5_get_krb_admin_hst krb5_get_krb_changepw_hst krb5_get_krbhst krb5_get_max_time_skew krb5_get_pw_salt krb5_get_renewed_creds krb5_get_server_rcache krb5_get_use_admin_kdc krb5_get_validated_creds ;! krb5_get_warn_dest krb5_get_wrapped_length krb5_getportbyname krb5_h_addr2addr krb5_h_addr2sockaddr krb5_h_errno_to_heim_errno krb5_have_error_string krb5_hmac krb5_init_context krb5_init_ets krb5_initlog krb5_is_config_principal krb5_is_enctype_weak krb5_is_thread_safe #ifdef HAVE_KCM krb5_kcm_call krb5_kcm_storage_request #endif krb5_kerberos_enctypes krb5_keyblock_get_enctype krb5_keyblock_init krb5_keyblock_key_proc krb5_keyblock_zero krb5_keytab_key_proc krb5_keytype_to_enctypes krb5_keytype_to_enctypes_default krb5_keytype_to_string krb5_krbhst_format_string krb5_krbhst_free krb5_krbhst_get_addrinfo krb5_krbhst_init krb5_krbhst_init_flags krb5_krbhst_next krb5_krbhst_next_as_string krb5_krbhst_reset krb5_kt_add_entry krb5_kt_close krb5_kt_compare krb5_kt_copy_entry_contents krb5_kt_default krb5_kt_default_modify_name krb5_kt_default_name krb5_kt_destroy krb5_kt_end_seq_get krb5_kt_free_entry krb5_kt_get_entry krb5_kt_get_full_name krb5_kt_get_name krb5_kt_get_type krb5_kt_have_content krb5_kt_next_entry krb5_kt_read_service_key krb5_kt_register krb5_kt_remove_entry krb5_kt_resolve krb5_kt_start_seq_get krb5_kuserok krb5_log krb5_log_msg krb5_make_addrport krb5_make_principal krb5_max_sockaddr_size krb5_mk_error krb5_mk_error_ext krb5_mk_priv krb5_mk_rep krb5_mk_req krb5_mk_req_exact krb5_mk_req_extended krb5_mk_safe krb5_net_read krb5_net_write krb5_net_write_block krb5_ntlm_alloc krb5_ntlm_free krb5_ntlm_init_get_challenge krb5_ntlm_init_get_flags krb5_ntlm_init_get_opaque krb5_ntlm_init_get_targetinfo krb5_ntlm_init_get_targetname krb5_ntlm_init_request krb5_ntlm_rep_get_sessionkey krb5_ntlm_rep_get_status krb5_ntlm_req_set_flags krb5_ntlm_req_set_lm krb5_ntlm_req_set_ntlm krb5_ntlm_req_set_opaque krb5_ntlm_req_set_session krb5_ntlm_req_set_targetname krb5_ntlm_req_set_username krb5_ntlm_request krb5_openlog krb5_pac_add_buffer krb5_pac_free krb5_pac_get_buffer krb5_pac_get_types krb5_pac_init krb5_pac_parse krb5_pac_verify krb5_padata_add krb5_parse_address krb5_parse_name krb5_parse_name_flags krb5_parse_nametype krb5_passwd_result_to_string krb5_password_key_proc krb5_get_permitted_enctypes krb5_plugin_register krb5_prepend_config_files krb5_prepend_config_files_default krb5_prepend_error_message krb5_princ_realm krb5_princ_set_realm krb5_principal_compare krb5_principal_compare_any_realm krb5_principal_get_comp_string krb5_principal_get_num_comp krb5_principal_get_realm krb5_principal_get_type krb5_principal_is_krbtgt krb5_principal_match krb5_principal_set_comp_string krb5_principal_set_realm krb5_principal_set_type krb5_print_address krb5_program_setup krb5_prompter_posix krb5_random_to_key krb5_rc_close krb5_rc_default krb5_rc_default_name krb5_rc_default_type krb5_rc_destroy krb5_rc_expunge krb5_rc_get_lifespan krb5_rc_get_name krb5_rc_get_type krb5_rc_initialize krb5_rc_recover krb5_rc_resolve krb5_rc_resolve_full krb5_rc_resolve_type krb5_rc_store krb5_rd_cred2 krb5_rd_cred krb5_rd_error krb5_rd_priv krb5_rd_rep krb5_rd_req krb5_rd_req_ctx krb5_rd_req_in_ctx_alloc krb5_rd_req_in_ctx_free krb5_rd_req_in_set_keyblock krb5_rd_req_in_set_keytab krb5_rd_req_in_set_pac_check krb5_rd_req_out_ctx_free krb5_rd_req_out_get_ap_req_options krb5_rd_req_out_get_keyblock krb5_rd_req_out_get_ticket krb5_rd_req_with_keyblock krb5_rd_safe krb5_read_message krb5_read_priv_message krb5_read_safe_message krb5_realm_compare krb5_recvauth krb5_recvauth_match_version krb5_ret_address krb5_ret_addrs krb5_ret_authdata krb5_ret_creds krb5_ret_creds_tag krb5_ret_data krb5_ret_int16 krb5_ret_int32 krb5_ret_int64 krb5_ret_int8 krb5_ret_keyblock krb5_ret_principal krb5_ret_string krb5_ret_stringnl krb5_ret_stringz krb5_ret_times krb5_ret_uint16 krb5_ret_uint32 krb5_ret_uint64 krb5_ret_uint8 krb5_salttype_to_string krb5_sendauth krb5_sendto krb5_sendto_context krb5_sendto_ctx_add_flags krb5_sendto_ctx_alloc krb5_sendto_ctx_free krb5_sendto_ctx_get_flags krb5_sendto_ctx_set_func krb5_sendto_ctx_set_type krb5_sendto_kdc krb5_sendto_kdc_flags krb5_set_config_files krb5_set_debug_dest krb5_set_default_in_tkt_etypes krb5_set_default_realm krb5_set_dns_canonicalize_hostname krb5_set_error_message krb5_set_error_string krb5_set_extra_addresses krb5_set_fcache_version krb5_set_home_dir_access krb5_set_ignore_addresses krb5_set_kdc_sec_offset krb5_set_max_time_skew krb5_set_password krb5_set_password_using_ccache krb5_set_real_time krb5_set_send_to_kdc_func krb5_set_use_admin_kdc krb5_set_warn_dest krb5_sname_to_principal krb5_sock_to_principal krb5_sockaddr2address krb5_sockaddr2port krb5_sockaddr_uninteresting krb5_std_usage krb5_storage_clear_flags krb5_storage_emem krb5_storage_free krb5_storage_from_data krb5_storage_from_fd krb5_storage_from_mem krb5_storage_from_readonly_mem krb5_storage_from_socket krb5_storage_fsync krb5_storage_get_byteorder krb5_storage_get_eof_code krb5_storage_is_flags krb5_storage_read krb5_storage_seek krb5_storage_set_byteorder krb5_storage_set_eof_code krb5_storage_set_flags krb5_storage_set_max_alloc krb5_storage_to_data krb5_storage_truncate krb5_storage_write krb5_store_address krb5_store_addrs krb5_store_authdata krb5_store_creds krb5_store_creds_tag krb5_store_data krb5_store_int16 krb5_store_int32 krb5_store_int64 krb5_store_int8 krb5_store_keyblock krb5_store_principal krb5_store_string krb5_store_stringnl krb5_store_stringz krb5_store_times krb5_store_uint16 krb5_store_uint32 krb5_store_uint64 krb5_store_uint8 krb5_string_to_deltat krb5_string_to_enctype krb5_string_to_key krb5_string_to_key_data krb5_string_to_key_data_salt krb5_string_to_key_data_salt_opaque krb5_string_to_key_derived krb5_string_to_key_salt krb5_string_to_key_salt_opaque krb5_string_to_keytype krb5_string_to_salttype krb5_ticket_get_authorization_data_type krb5_ticket_get_client krb5_ticket_get_endtime krb5_ticket_get_server krb5_timeofday krb5_unparse_name krb5_unparse_name_fixed krb5_unparse_name_fixed_flags krb5_unparse_name_fixed_short krb5_unparse_name_flags krb5_unparse_name_short krb5_us_timeofday krb5_vabort krb5_vabortx krb5_verify_ap_req2 krb5_verify_ap_req krb5_verify_authenticator_checksum krb5_verify_checksum krb5_verify_checksum_iov krb5_verify_init_creds krb5_verify_init_creds_opt_init krb5_verify_init_creds_opt_set_ap_req_nofail krb5_verify_opt_alloc krb5_verify_opt_free krb5_verify_opt_init krb5_verify_opt_set_ccache krb5_verify_opt_set_flags krb5_verify_opt_set_keytab krb5_verify_opt_set_secure krb5_verify_opt_set_service krb5_verify_user krb5_verify_user_lrealm krb5_verify_user_opt krb5_verr krb5_verrx krb5_vlog krb5_vlog_msg krb5_vprepend_error_message krb5_vset_error_message krb5_vset_error_string krb5_vwarn krb5_vwarnx krb5_warn krb5_warnx krb5_write_message krb5_write_priv_message krb5_write_safe_message krb5_xfree krb5_cccol_last_change_time krb5_cccol_cursor_new krb5_cccol_cursor_next krb5_cccol_cursor_free ; com_err error tables initialize_krb5_error_table_r initialize_krb5_error_table initialize_krb_error_table_r initialize_krb_error_table initialize_heim_error_table_r initialize_heim_error_table initialize_k524_error_table_r initialize_k524_error_table ; variables krb5_mcc_ops DATA krb5_acc_ops DATA krb5_fcc_ops DATA #ifdef HAVE_SCC krb5_scc_ops DATA #endif #ifdef HAVE_KCM krb5_kcm_ops DATA #endif krb5_wrfkt_ops DATA krb5_mkt_ops DATA krb5_akf_ops DATA krb5_any_ops DATA heimdal_version DATA heimdal_long_version DATA krb5_config_file DATA krb5_defkeyname DATA krb5_cc_type_api DATA krb5_cc_type_file DATA krb5_cc_type_memory DATA krb5_cc_type_kcm DATA krb5_cc_type_scc DATA ; Shared with GSSAPI krb5 _krb5_crc_init_table _krb5_crc_update _krb5_get_krbtgt _krb5_build_authenticator ; Shared with libkdc _krb5_AES_SHA1_string_to_default_iterator _krb5_AES_SHA2_string_to_default_iterator _krb5_dh_group_ok _krb5_get_host_realm_int _krb5_get_int _krb5_get_int64 _krb5_pac_sign _krb5_parse_moduli _krb5_pk_kdf _krb5_pk_load_id _krb5_pk_mk_ContentInfo _krb5_pk_octetstring2key _krb5_plugin_run_f _krb5_enctype_requires_random_salt _krb5_principal2principalname _krb5_principalname2krb5_principal _krb5_put_int _krb5_s4u2self_to_checksumdata _krb5_expand_path_tokens ;! ; kinit helper krb5_get_init_creds_opt_set_pkinit_user_certs krb5_pk_enterprise_cert krb5_auth_con_getsendsubkey krb5_init_creds_free krb5_init_creds_get krb5_init_creds_get_creds krb5_init_creds_get_error krb5_init_creds_init krb5_init_creds_set_fast_ccache krb5_init_creds_set_keytab krb5_init_creds_set_password krb5_init_creds_set_service krb5_init_creds_store krb5_process_last_request ; testing ;! _krb5_aes_cts_encrypt _krb5_n_fold _krb5_expand_default_cc_name ; FAST _krb5_fast_cf2 _krb5_fast_armor_key ; Recent additions krb5_cc_type_dcc; krb5_dcc_ops; _krb5_plugin_find; _krb5_plugin_free; _krb5_expand_path_tokensv; _krb5_find_capath; _krb5_free_capath; heimdal-7.5.0/lib/krb5/krb5_get_in_cred.30000644000175000017500000001673213026237312016144 0ustar niknik.\" Copyright (c) 2003 Kungliga Tekniska Högskolan .\" (Royal Institute of Technology, Stockholm, Sweden). .\" All rights reserved. .\" .\" Redistribution and use in source and binary forms, with or without .\" modification, are permitted provided that the following conditions .\" are met: .\" .\" 1. Redistributions of source code must retain the above copyright .\" notice, this list of conditions and the following disclaimer. .\" .\" 2. Redistributions in binary form must reproduce the above copyright .\" notice, this list of conditions and the following disclaimer in the .\" documentation and/or other materials provided with the distribution. .\" .\" 3. Neither the name of the Institute nor the names of its contributors .\" may be used to endorse or promote products derived from this software .\" without specific prior written permission. .\" .\" THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND .\" ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE .\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE .\" ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE .\" FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL .\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS .\" OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) .\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT .\" LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF .\" SUCH DAMAGE. .\" .\" $Id$ .\" .Dd May 31, 2003 .Dt KRB5_GET_IN_TKT 3 .Os HEIMDAL .Sh NAME .Nm krb5_get_in_tkt , .Nm krb5_get_in_cred , .Nm krb5_get_in_tkt_with_password , .Nm krb5_get_in_tkt_with_keytab , .Nm krb5_get_in_tkt_with_skey , .Nm krb5_free_kdc_rep , .Nm krb5_password_key_proc .Nd deprecated initial authentication functions .Sh LIBRARY Kerberos 5 Library (libkrb5, -lkrb5) .Sh SYNOPSIS .In krb5.h .Pp .Ft krb5_error_code .Fo krb5_get_in_tkt .Fa "krb5_context context" .Fa "krb5_flags options" .Fa "const krb5_addresses *addrs" .Fa "const krb5_enctype *etypes" .Fa "const krb5_preauthtype *ptypes" .Fa "krb5_key_proc key_proc" .Fa "krb5_const_pointer keyseed" .Fa "krb5_decrypt_proc decrypt_proc" .Fa "krb5_const_pointer decryptarg" .Fa "krb5_creds *creds" .Fa "krb5_ccache ccache" .Fa "krb5_kdc_rep *ret_as_reply" .Fc .Ft krb5_error_code .Fo krb5_get_in_cred .Fa "krb5_context context" .Fa "krb5_flags options" .Fa "const krb5_addresses *addrs" .Fa "const krb5_enctype *etypes" .Fa "const krb5_preauthtype *ptypes" .Fa "const krb5_preauthdata *preauth" .Fa "krb5_key_proc key_proc" .Fa "krb5_const_pointer keyseed" .Fa "krb5_decrypt_proc decrypt_proc" .Fa "krb5_const_pointer decryptarg" .Fa "krb5_creds *creds" .Fa "krb5_kdc_rep *ret_as_reply" .Fc .Ft krb5_error_code .Fo krb5_get_in_tkt_with_password .Fa "krb5_context context" .Fa "krb5_flags options" .Fa "krb5_addresses *addrs" .Fa "const krb5_enctype *etypes" .Fa "const krb5_preauthtype *pre_auth_types" .Fa "const char *password" .Fa "krb5_ccache ccache" .Fa "krb5_creds *creds" .Fa "krb5_kdc_rep *ret_as_reply" .Fc .Ft krb5_error_code .Fo krb5_get_in_tkt_with_keytab .Fa "krb5_context context" .Fa "krb5_flags options" .Fa "krb5_addresses *addrs" .Fa "const krb5_enctype *etypes" .Fa "const krb5_preauthtype *pre_auth_types" .Fa "krb5_keytab keytab" .Fa "krb5_ccache ccache" .Fa "krb5_creds *creds" .Fa "krb5_kdc_rep *ret_as_reply" .Fc .Ft krb5_error_code .Fo krb5_get_in_tkt_with_skey .Fa "krb5_context context" .Fa "krb5_flags options" .Fa "krb5_addresses *addrs" .Fa "const krb5_enctype *etypes" .Fa "const krb5_preauthtype *pre_auth_types" .Fa "const krb5_keyblock *key" .Fa "krb5_ccache ccache" .Fa "krb5_creds *creds" .Fa "krb5_kdc_rep *ret_as_reply" .Fc .Ft krb5_error_code .Fo krb5_free_kdc_rep .Fa "krb5_context context" .Fa "krb5_kdc_rep *rep" .Fc .Ft krb5_error_code .Fo krb5_password_key_proc .Fa "krb5_context context" .Fa "krb5_enctype type" .Fa "krb5_salt salt" .Fa "krb5_const_pointer keyseed" .Fa "krb5_keyblock **key" .Fc .Sh DESCRIPTION .Bf Em All the functions in this manual page are deprecated in the MIT implementation, and will soon be deprecated in Heimdal too, don't use them. .Ef .Pp Getting initial credential ticket for a principal. .Nm krb5_get_in_cred is the function all other krb5_get_in function uses to fetch tickets. The other krb5_get_in function are more specialized and therefor somewhat easier to use. .Pp If your need is only to verify a user and password, consider using .Xr krb5_verify_user 3 instead, it have a much simpler interface. .Pp .Nm krb5_get_in_tkt and .Nm krb5_get_in_cred fetches initial credential, queries after key using the .Fa key_proc argument. The differences between the two function is that .Nm krb5_get_in_tkt stores the credential in a .Li krb5_creds while .Nm krb5_get_in_cred stores the credential in a .Li krb5_ccache . .Pp .Nm krb5_get_in_tkt_with_password , .Nm krb5_get_in_tkt_with_keytab , and .Nm krb5_get_in_tkt_with_skey does the same work as .Nm krb5_get_in_cred but are more specialized. .Pp .Nm krb5_get_in_tkt_with_password uses the clients password to authenticate. If the password argument is .Dv NULL the user user queried with the default password query function. .Pp .Nm krb5_get_in_tkt_with_keytab searches the given keytab for a service entry for the client principal. If the keytab is .Dv NULL the default keytab is used. .Pp .Nm krb5_get_in_tkt_with_skey uses a key to get the initial credential. .Pp There are some common arguments to the krb5_get_in functions, these are: .Pp .Fa options are the .Dv KDC_OPT flags. .Pp .Fa etypes is a .Dv NULL terminated array of encryption types that the client approves. .Pp .Fa addrs a list of the addresses that the initial ticket. If it is .Dv NULL the list will be generated by the library. .Pp .Fa pre_auth_types a .Dv NULL terminated array of pre-authentication types. If .Fa pre_auth_types is .Dv NULL the function will try without pre-authentication and return those pre-authentication that the KDC returned. .Pp .Fa ret_as_reply will (if not .Dv NULL ) be filled in with the response of the KDC and should be free with .Fn krb5_free_kdc_rep . .Pp .Fa key_proc is a pointer to a function that should return a key salted appropriately. Using .Dv NULL will use the default password query function. .Pp .Fa decrypt_proc Using .Dv NULL will use the default decryption function. .Pp .Fa decryptarg will be passed to the decryption function .Fa decrypt_proc . .Pp .Fa creds creds should be filled in with the template for a credential that should be requested. The client and server elements of the creds structure must be filled in. Upon return of the function it will be contain the content of the requested credential .Fa ( krb5_get_in_cred ) , or it will be freed with .Xr krb5_free_creds 3 (all the other krb5_get_in functions). .Pp .Fa ccache will store the credential in the credential cache .Fa ccache . The credential cache will not be initialized, thats up the the caller. .Pp .Nm krb5_password_key_proc is a library function that is suitable using as the .Fa krb5_key_proc argument to .Nm krb5_get_in_cred or .Nm krb5_get_in_tkt . .Fa keyseed should be a pointer to a .Dv NUL terminated string or .Dv NULL . .Nm krb5_password_key_proc will query the user for the pass on the console if the password isn't given as the argument .Fa keyseed . .Pp .Fn krb5_free_kdc_rep frees the content of .Fa rep . .Sh SEE ALSO .Xr krb5 3 , .Xr krb5_verify_user 3 , .Xr krb5.conf 5 , .Xr kerberos 8 heimdal-7.5.0/lib/krb5/init_creds_pw.c0000644000175000017500000021374413212137553015675 0ustar niknik/* * Copyright (c) 1997 - 2008 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Portions Copyright (c) 2009 Apple Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "krb5_locl.h" #ifndef WIN32 #include #endif /* WIN32 */ typedef struct krb5_get_init_creds_ctx { KDCOptions flags; krb5_creds cred; krb5_addresses *addrs; krb5_enctype *etypes; krb5_preauthtype *pre_auth_types; char *in_tkt_service; unsigned nonce; unsigned pk_nonce; krb5_data req_buffer; AS_REQ as_req; int pa_counter; /* password and keytab_data is freed on completion */ char *password; krb5_keytab_key_proc_args *keytab_data; krb5_pointer *keyseed; krb5_s2k_proc keyproc; krb5_get_init_creds_tristate req_pac; krb5_pk_init_ctx pk_init_ctx; int ic_flags; struct { unsigned change_password:1; } runflags; int used_pa_types; #define USED_PKINIT 1 #define USED_PKINIT_W2K 2 #define USED_ENC_TS_GUESS 4 #define USED_ENC_TS_INFO 8 METHOD_DATA md; KRB_ERROR error; AS_REP as_rep; EncKDCRepPart enc_part; krb5_prompter_fct prompter; void *prompter_data; struct pa_info_data *ppaid; struct fast_state { enum PA_FX_FAST_REQUEST_enum type; unsigned int flags; #define KRB5_FAST_REPLY_KEY_USE_TO_ENCRYPT_THE_REPLY 1 #define KRB5_FAST_REPLY_KEY_USE_IN_TRANSACTION 2 #define KRB5_FAST_KDC_REPLY_KEY_REPLACED 4 #define KRB5_FAST_REPLY_REPLY_VERIFED 8 #define KRB5_FAST_STRONG 16 #define KRB5_FAST_EXPECTED 32 /* in exchange with KDC, fast was discovered */ #define KRB5_FAST_REQUIRED 64 /* fast required by action of caller */ #define KRB5_FAST_DISABLED 128 #define KRB5_FAST_AP_ARMOR_SERVICE 256 krb5_keyblock *reply_key; krb5_ccache armor_ccache; krb5_principal armor_service; krb5_crypto armor_crypto; krb5_keyblock armor_key; krb5_keyblock *strengthen_key; } fast_state; } krb5_get_init_creds_ctx; struct pa_info_data { krb5_enctype etype; krb5_salt salt; krb5_data *s2kparams; }; static void free_paid(krb5_context context, struct pa_info_data *ppaid) { krb5_free_salt(context, ppaid->salt); if (ppaid->s2kparams) krb5_free_data(context, ppaid->s2kparams); } static krb5_error_code KRB5_CALLCONV default_s2k_func(krb5_context context, krb5_enctype type, krb5_const_pointer keyseed, krb5_salt salt, krb5_data *s2kparms, krb5_keyblock **key) { krb5_error_code ret; krb5_data password; krb5_data opaque; _krb5_debug(context, 5, "krb5_get_init_creds: using default_s2k_func"); password.data = rk_UNCONST(keyseed); password.length = strlen(keyseed); if (s2kparms) opaque = *s2kparms; else krb5_data_zero(&opaque); *key = malloc(sizeof(**key)); if (*key == NULL) return ENOMEM; ret = krb5_string_to_key_data_salt_opaque(context, type, password, salt, opaque, *key); if (ret) { free(*key); *key = NULL; } return ret; } static void free_init_creds_ctx(krb5_context context, krb5_init_creds_context ctx) { if (ctx->etypes) free(ctx->etypes); if (ctx->pre_auth_types) free (ctx->pre_auth_types); if (ctx->in_tkt_service) free(ctx->in_tkt_service); if (ctx->keytab_data) free(ctx->keytab_data); if (ctx->password) { memset(ctx->password, 0, strlen(ctx->password)); free(ctx->password); } /* * FAST state (we don't close the armor_ccache because we might have * to destroy it, and how would we know? also, the caller should * take care of cleaning up the armor_ccache). */ if (ctx->fast_state.armor_service) krb5_free_principal(context, ctx->fast_state.armor_service); if (ctx->fast_state.armor_crypto) krb5_crypto_destroy(context, ctx->fast_state.armor_crypto); if (ctx->fast_state.strengthen_key) krb5_free_keyblock(context, ctx->fast_state.strengthen_key); krb5_free_keyblock_contents(context, &ctx->fast_state.armor_key); krb5_data_free(&ctx->req_buffer); krb5_free_cred_contents(context, &ctx->cred); free_METHOD_DATA(&ctx->md); free_AS_REP(&ctx->as_rep); free_EncKDCRepPart(&ctx->enc_part); free_KRB_ERROR(&ctx->error); free_AS_REQ(&ctx->as_req); if (ctx->ppaid) { free_paid(context, ctx->ppaid); free(ctx->ppaid); } memset(ctx, 0, sizeof(*ctx)); } static int get_config_time (krb5_context context, const char *realm, const char *name, int def) { int ret; ret = krb5_config_get_time (context, NULL, "realms", realm, name, NULL); if (ret >= 0) return ret; ret = krb5_config_get_time (context, NULL, "libdefaults", name, NULL); if (ret >= 0) return ret; return def; } static krb5_error_code init_cred (krb5_context context, krb5_creds *cred, krb5_principal client, krb5_deltat start_time, krb5_get_init_creds_opt *options) { krb5_error_code ret; int tmp; krb5_timestamp now; krb5_timeofday (context, &now); memset (cred, 0, sizeof(*cred)); if (client) ret = krb5_copy_principal(context, client, &cred->client); else ret = krb5_get_default_principal(context, &cred->client); if (ret) goto out; if (start_time) cred->times.starttime = now + start_time; if (options->flags & KRB5_GET_INIT_CREDS_OPT_TKT_LIFE) tmp = options->tkt_life; else tmp = KRB5_TKT_LIFETIME_DEFAULT; cred->times.endtime = now + tmp; if ((options->flags & KRB5_GET_INIT_CREDS_OPT_RENEW_LIFE)) { if (options->renew_life > 0) tmp = options->renew_life; else tmp = KRB5_TKT_RENEW_LIFETIME_DEFAULT; cred->times.renew_till = now + tmp; } return 0; out: krb5_free_cred_contents (context, cred); return ret; } /* * Print a message (str) to the user about the expiration in `lr' */ static void report_expiration (krb5_context context, krb5_prompter_fct prompter, krb5_data *data, const char *str, time_t now) { char *p = NULL; if (asprintf(&p, "%s%s", str, ctime(&now)) < 0 || p == NULL) return; (*prompter)(context, data, NULL, p, 0, NULL); free(p); } /* * Check the context, and in the case there is a expiration warning, * use the prompter to print the warning. * * @param context A Kerberos 5 context. * @param options An GIC options structure * @param ctx The krb5_init_creds_context check for expiration. */ krb5_error_code krb5_process_last_request(krb5_context context, krb5_get_init_creds_opt *options, krb5_init_creds_context ctx) { krb5_const_realm realm; LastReq *lr; krb5_boolean reported = FALSE; krb5_timestamp sec; time_t t; size_t i; /* * First check if there is a API consumer. */ realm = krb5_principal_get_realm (context, ctx->cred.client); lr = &ctx->enc_part.last_req; if (options && options->opt_private && options->opt_private->lr.func) { krb5_last_req_entry **lre; lre = calloc(lr->len + 1, sizeof(*lre)); if (lre == NULL) return krb5_enomem(context); for (i = 0; i < lr->len; i++) { lre[i] = calloc(1, sizeof(*lre[i])); if (lre[i] == NULL) break; lre[i]->lr_type = lr->val[i].lr_type; lre[i]->value = lr->val[i].lr_value; } (*options->opt_private->lr.func)(context, lre, options->opt_private->lr.ctx); for (i = 0; i < lr->len; i++) free(lre[i]); free(lre); } /* * Now check if we should prompt the user */ if (ctx->prompter == NULL) return 0; krb5_timeofday (context, &sec); t = sec + get_config_time (context, realm, "warn_pwexpire", 7 * 24 * 60 * 60); for (i = 0; i < lr->len; ++i) { if (lr->val[i].lr_value <= t) { switch (lr->val[i].lr_type) { case LR_PW_EXPTIME : report_expiration(context, ctx->prompter, ctx->prompter_data, "Your password will expire at ", lr->val[i].lr_value); reported = TRUE; break; case LR_ACCT_EXPTIME : report_expiration(context, ctx->prompter, ctx->prompter_data, "Your account will expire at ", lr->val[i].lr_value); reported = TRUE; break; default: break; } } } if (!reported && ctx->enc_part.key_expiration && *ctx->enc_part.key_expiration <= t) { report_expiration(context, ctx->prompter, ctx->prompter_data, "Your password/account will expire at ", *ctx->enc_part.key_expiration); } return 0; } static krb5_addresses no_addrs = { 0, NULL }; static krb5_error_code get_init_creds_common(krb5_context context, krb5_principal client, krb5_deltat start_time, krb5_get_init_creds_opt *options, krb5_init_creds_context ctx) { krb5_get_init_creds_opt *default_opt = NULL; krb5_error_code ret; krb5_enctype *etypes; krb5_preauthtype *pre_auth_types; memset(ctx, 0, sizeof(*ctx)); if (options == NULL) { const char *realm = krb5_principal_get_realm(context, client); krb5_get_init_creds_opt_alloc (context, &default_opt); options = default_opt; krb5_get_init_creds_opt_set_default_flags(context, NULL, realm, options); } if (options->opt_private) { if (options->opt_private->password) { ret = krb5_init_creds_set_password(context, ctx, options->opt_private->password); if (ret) goto out; } ctx->keyproc = options->opt_private->key_proc; ctx->req_pac = options->opt_private->req_pac; ctx->pk_init_ctx = options->opt_private->pk_init_ctx; ctx->ic_flags = options->opt_private->flags; } else ctx->req_pac = KRB5_INIT_CREDS_TRISTATE_UNSET; if (ctx->keyproc == NULL) ctx->keyproc = default_s2k_func; /* Enterprise name implicitly turns on canonicalize */ if ((ctx->ic_flags & KRB5_INIT_CREDS_CANONICALIZE) || krb5_principal_get_type(context, client) == KRB5_NT_ENTERPRISE_PRINCIPAL) ctx->flags.canonicalize = 1; ctx->pre_auth_types = NULL; ctx->addrs = NULL; ctx->etypes = NULL; ctx->pre_auth_types = NULL; ret = init_cred(context, &ctx->cred, client, start_time, options); if (ret) { if (default_opt) krb5_get_init_creds_opt_free(context, default_opt); return ret; } ret = krb5_init_creds_set_service(context, ctx, NULL); if (ret) goto out; if (options->flags & KRB5_GET_INIT_CREDS_OPT_FORWARDABLE) ctx->flags.forwardable = options->forwardable; if (options->flags & KRB5_GET_INIT_CREDS_OPT_PROXIABLE) ctx->flags.proxiable = options->proxiable; if (start_time) ctx->flags.postdated = 1; if (ctx->cred.times.renew_till) ctx->flags.renewable = 1; if (options->flags & KRB5_GET_INIT_CREDS_OPT_ADDRESS_LIST) { ctx->addrs = options->address_list; } else if (options->opt_private) { switch (options->opt_private->addressless) { case KRB5_INIT_CREDS_TRISTATE_UNSET: #if KRB5_ADDRESSLESS_DEFAULT == TRUE ctx->addrs = &no_addrs; #else ctx->addrs = NULL; #endif break; case KRB5_INIT_CREDS_TRISTATE_FALSE: ctx->addrs = NULL; break; case KRB5_INIT_CREDS_TRISTATE_TRUE: ctx->addrs = &no_addrs; break; } } if (options->flags & KRB5_GET_INIT_CREDS_OPT_ETYPE_LIST) { if (ctx->etypes) free(ctx->etypes); etypes = malloc((options->etype_list_length + 1) * sizeof(krb5_enctype)); if (etypes == NULL) { ret = krb5_enomem(context); goto out; } memcpy (etypes, options->etype_list, options->etype_list_length * sizeof(krb5_enctype)); etypes[options->etype_list_length] = ETYPE_NULL; ctx->etypes = etypes; } if (options->flags & KRB5_GET_INIT_CREDS_OPT_PREAUTH_LIST) { pre_auth_types = malloc((options->preauth_list_length + 1) * sizeof(krb5_preauthtype)); if (pre_auth_types == NULL) { ret = krb5_enomem(context); goto out; } memcpy (pre_auth_types, options->preauth_list, options->preauth_list_length * sizeof(krb5_preauthtype)); pre_auth_types[options->preauth_list_length] = KRB5_PADATA_NONE; ctx->pre_auth_types = pre_auth_types; } if (options->flags & KRB5_GET_INIT_CREDS_OPT_ANONYMOUS) ctx->flags.request_anonymous = options->anonymous; if (default_opt) krb5_get_init_creds_opt_free(context, default_opt); return 0; out: if (default_opt) krb5_get_init_creds_opt_free(context, default_opt); return ret; } static krb5_error_code change_password (krb5_context context, krb5_principal client, const char *password, char *newpw, size_t newpw_sz, krb5_prompter_fct prompter, void *data, krb5_get_init_creds_opt *old_options) { krb5_prompt prompts[2]; krb5_error_code ret; krb5_creds cpw_cred; char buf1[BUFSIZ], buf2[BUFSIZ]; krb5_data password_data[2]; int result_code; krb5_data result_code_string; krb5_data result_string; char *p; krb5_get_init_creds_opt *options; heim_assert(prompter != NULL, "unexpected NULL prompter"); memset (&cpw_cred, 0, sizeof(cpw_cred)); ret = krb5_get_init_creds_opt_alloc(context, &options); if (ret) return ret; krb5_get_init_creds_opt_set_tkt_life (options, 60); krb5_get_init_creds_opt_set_forwardable (options, FALSE); krb5_get_init_creds_opt_set_proxiable (options, FALSE); if (old_options && (old_options->flags & KRB5_GET_INIT_CREDS_OPT_PREAUTH_LIST)) krb5_get_init_creds_opt_set_preauth_list(options, old_options->preauth_list, old_options->preauth_list_length); if (old_options && (old_options->flags & KRB5_GET_INIT_CREDS_OPT_CHANGE_PASSWORD_PROMPT)) krb5_get_init_creds_opt_set_change_password_prompt(options, old_options->change_password_prompt); krb5_data_zero (&result_code_string); krb5_data_zero (&result_string); ret = krb5_get_init_creds_password (context, &cpw_cred, client, password, prompter, data, 0, "kadmin/changepw", options); krb5_get_init_creds_opt_free(context, options); if (ret) goto out; for(;;) { password_data[0].data = buf1; password_data[0].length = sizeof(buf1); prompts[0].hidden = 1; prompts[0].prompt = "New password: "; prompts[0].reply = &password_data[0]; prompts[0].type = KRB5_PROMPT_TYPE_NEW_PASSWORD; password_data[1].data = buf2; password_data[1].length = sizeof(buf2); prompts[1].hidden = 1; prompts[1].prompt = "Repeat new password: "; prompts[1].reply = &password_data[1]; prompts[1].type = KRB5_PROMPT_TYPE_NEW_PASSWORD_AGAIN; ret = (*prompter) (context, data, NULL, "Changing password", 2, prompts); if (ret) { memset (buf1, 0, sizeof(buf1)); memset (buf2, 0, sizeof(buf2)); goto out; } if (strcmp (buf1, buf2) == 0) break; memset (buf1, 0, sizeof(buf1)); memset (buf2, 0, sizeof(buf2)); } ret = krb5_set_password (context, &cpw_cred, buf1, client, &result_code, &result_code_string, &result_string); if (ret) goto out; if (asprintf(&p, "%s: %.*s\n", result_code ? "Error" : "Success", (int)result_string.length, result_string.length > 0 ? (char*)result_string.data : "") < 0) { ret = ENOMEM; goto out; } /* return the result */ (*prompter) (context, data, NULL, p, 0, NULL); free (p); if (result_code == 0) { strlcpy (newpw, buf1, newpw_sz); ret = 0; } else { ret = ENOTTY; krb5_set_error_message(context, ret, N_("failed changing password", "")); } out: memset (buf1, 0, sizeof(buf1)); memset (buf2, 0, sizeof(buf2)); krb5_data_free (&result_string); krb5_data_free (&result_code_string); krb5_free_cred_contents (context, &cpw_cred); return ret; } KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_keyblock_key_proc (krb5_context context, krb5_keytype type, krb5_data *salt, krb5_const_pointer keyseed, krb5_keyblock **key) { return krb5_copy_keyblock (context, keyseed, key); } /* * */ static krb5_error_code init_as_req (krb5_context context, KDCOptions opts, const krb5_creds *creds, const krb5_addresses *addrs, const krb5_enctype *etypes, AS_REQ *a) { krb5_error_code ret; memset(a, 0, sizeof(*a)); a->pvno = 5; a->msg_type = krb_as_req; a->req_body.kdc_options = opts; a->req_body.cname = malloc(sizeof(*a->req_body.cname)); if (a->req_body.cname == NULL) { ret = krb5_enomem(context); goto fail; } a->req_body.sname = malloc(sizeof(*a->req_body.sname)); if (a->req_body.sname == NULL) { ret = krb5_enomem(context); goto fail; } ret = _krb5_principal2principalname (a->req_body.cname, creds->client); if (ret) goto fail; ret = copy_Realm(&creds->client->realm, &a->req_body.realm); if (ret) goto fail; ret = _krb5_principal2principalname (a->req_body.sname, creds->server); if (ret) goto fail; if(creds->times.starttime) { a->req_body.from = malloc(sizeof(*a->req_body.from)); if (a->req_body.from == NULL) { ret = krb5_enomem(context); goto fail; } *a->req_body.from = creds->times.starttime; } if(creds->times.endtime){ if ((ALLOC(a->req_body.till, 1)) != NULL) *a->req_body.till = creds->times.endtime; else { ret = krb5_enomem(context); goto fail; } } if(creds->times.renew_till){ a->req_body.rtime = malloc(sizeof(*a->req_body.rtime)); if (a->req_body.rtime == NULL) { ret = krb5_enomem(context); goto fail; } *a->req_body.rtime = creds->times.renew_till; } a->req_body.nonce = 0; ret = _krb5_init_etype(context, KRB5_PDU_AS_REQUEST, &a->req_body.etype.len, &a->req_body.etype.val, etypes); if (ret) goto fail; /* * This means no addresses */ if (addrs && addrs->len == 0) { a->req_body.addresses = NULL; } else { a->req_body.addresses = malloc(sizeof(*a->req_body.addresses)); if (a->req_body.addresses == NULL) { ret = krb5_enomem(context); goto fail; } if (addrs) ret = krb5_copy_addresses(context, addrs, a->req_body.addresses); else { ret = krb5_get_all_client_addrs (context, a->req_body.addresses); if(ret == 0 && a->req_body.addresses->len == 0) { free(a->req_body.addresses); a->req_body.addresses = NULL; } } if (ret) goto fail; } a->req_body.enc_authorization_data = NULL; a->req_body.additional_tickets = NULL; a->padata = NULL; return 0; fail: free_AS_REQ(a); memset(a, 0, sizeof(*a)); return ret; } static krb5_error_code set_paid(struct pa_info_data *paid, krb5_context context, krb5_enctype etype, krb5_salttype salttype, void *salt_string, size_t salt_len, krb5_data *s2kparams) { paid->etype = etype; paid->salt.salttype = salttype; paid->salt.saltvalue.data = malloc(salt_len + 1); if (paid->salt.saltvalue.data == NULL) { krb5_clear_error_message(context); return ENOMEM; } memcpy(paid->salt.saltvalue.data, salt_string, salt_len); ((char *)paid->salt.saltvalue.data)[salt_len] = '\0'; paid->salt.saltvalue.length = salt_len; if (s2kparams) { krb5_error_code ret; ret = krb5_copy_data(context, s2kparams, &paid->s2kparams); if (ret) { krb5_clear_error_message(context); krb5_free_salt(context, paid->salt); return ret; } } else paid->s2kparams = NULL; return 0; } static struct pa_info_data * pa_etype_info2(krb5_context context, const krb5_principal client, const AS_REQ *asreq, struct pa_info_data *paid, heim_octet_string *data) { krb5_error_code ret; ETYPE_INFO2 e; size_t sz; size_t i, j; memset(&e, 0, sizeof(e)); ret = decode_ETYPE_INFO2(data->data, data->length, &e, &sz); if (ret) goto out; if (e.len == 0) goto out; for (j = 0; j < asreq->req_body.etype.len; j++) { for (i = 0; i < e.len; i++) { if (asreq->req_body.etype.val[j] == e.val[i].etype) { krb5_salt salt; if (e.val[i].salt == NULL) ret = krb5_get_pw_salt(context, client, &salt); else { salt.saltvalue.data = *e.val[i].salt; salt.saltvalue.length = strlen(*e.val[i].salt); ret = 0; } if (ret == 0) ret = set_paid(paid, context, e.val[i].etype, KRB5_PW_SALT, salt.saltvalue.data, salt.saltvalue.length, e.val[i].s2kparams); if (e.val[i].salt == NULL) krb5_free_salt(context, salt); if (ret == 0) { free_ETYPE_INFO2(&e); return paid; } } } } out: free_ETYPE_INFO2(&e); return NULL; } static struct pa_info_data * pa_etype_info(krb5_context context, const krb5_principal client, const AS_REQ *asreq, struct pa_info_data *paid, heim_octet_string *data) { krb5_error_code ret; ETYPE_INFO e; size_t sz; size_t i, j; memset(&e, 0, sizeof(e)); ret = decode_ETYPE_INFO(data->data, data->length, &e, &sz); if (ret) goto out; if (e.len == 0) goto out; for (j = 0; j < asreq->req_body.etype.len; j++) { for (i = 0; i < e.len; i++) { if (asreq->req_body.etype.val[j] == e.val[i].etype) { krb5_salt salt; salt.salttype = KRB5_PW_SALT; if (e.val[i].salt == NULL) ret = krb5_get_pw_salt(context, client, &salt); else { salt.saltvalue = *e.val[i].salt; ret = 0; } if (e.val[i].salttype) salt.salttype = *e.val[i].salttype; if (ret == 0) { ret = set_paid(paid, context, e.val[i].etype, salt.salttype, salt.saltvalue.data, salt.saltvalue.length, NULL); if (e.val[i].salt == NULL) krb5_free_salt(context, salt); } if (ret == 0) { free_ETYPE_INFO(&e); return paid; } } } } out: free_ETYPE_INFO(&e); return NULL; } static struct pa_info_data * pa_pw_or_afs3_salt(krb5_context context, const krb5_principal client, const AS_REQ *asreq, struct pa_info_data *paid, heim_octet_string *data) { krb5_error_code ret; if (paid->etype == KRB5_ENCTYPE_NULL) return NULL; ret = set_paid(paid, context, paid->etype, paid->salt.salttype, data->data, data->length, NULL); if (ret) return NULL; return paid; } struct pa_info { krb5_preauthtype type; struct pa_info_data *(*salt_info)(krb5_context, const krb5_principal, const AS_REQ *, struct pa_info_data *, heim_octet_string *); }; static struct pa_info pa_prefs[] = { { KRB5_PADATA_ETYPE_INFO2, pa_etype_info2 }, { KRB5_PADATA_ETYPE_INFO, pa_etype_info }, { KRB5_PADATA_PW_SALT, pa_pw_or_afs3_salt }, { KRB5_PADATA_AFS3_SALT, pa_pw_or_afs3_salt } }; static PA_DATA * find_pa_data(const METHOD_DATA *md, unsigned type) { size_t i; if (md == NULL) return NULL; for (i = 0; i < md->len; i++) if (md->val[i].padata_type == type) return &md->val[i]; return NULL; } static struct pa_info_data * process_pa_info(krb5_context context, const krb5_principal client, const AS_REQ *asreq, struct pa_info_data *paid, METHOD_DATA *md) { struct pa_info_data *p = NULL; size_t i; for (i = 0; p == NULL && i < sizeof(pa_prefs)/sizeof(pa_prefs[0]); i++) { PA_DATA *pa = find_pa_data(md, pa_prefs[i].type); if (pa == NULL) continue; paid->salt.salttype = (krb5_salttype)pa_prefs[i].type; p = (*pa_prefs[i].salt_info)(context, client, asreq, paid, &pa->padata_value); } return p; } static krb5_error_code make_pa_enc_timestamp(krb5_context context, METHOD_DATA *md, krb5_enctype etype, krb5_keyblock *key) { PA_ENC_TS_ENC p; unsigned char *buf; size_t buf_size; size_t len = 0; EncryptedData encdata; krb5_error_code ret; int32_t usec; int usec2; krb5_crypto crypto; krb5_us_timeofday (context, &p.patimestamp, &usec); usec2 = usec; p.pausec = &usec2; ASN1_MALLOC_ENCODE(PA_ENC_TS_ENC, buf, buf_size, &p, &len, ret); if (ret) return ret; if(buf_size != len) krb5_abortx(context, "internal error in ASN.1 encoder"); ret = krb5_crypto_init(context, key, 0, &crypto); if (ret) { free(buf); return ret; } ret = krb5_encrypt_EncryptedData(context, crypto, KRB5_KU_PA_ENC_TIMESTAMP, buf, len, 0, &encdata); free(buf); krb5_crypto_destroy(context, crypto); if (ret) return ret; ASN1_MALLOC_ENCODE(EncryptedData, buf, buf_size, &encdata, &len, ret); free_EncryptedData(&encdata); if (ret) return ret; if(buf_size != len) krb5_abortx(context, "internal error in ASN.1 encoder"); ret = krb5_padata_add(context, md, KRB5_PADATA_ENC_TIMESTAMP, buf, len); if (ret) free(buf); return ret; } static krb5_error_code add_enc_ts_padata(krb5_context context, METHOD_DATA *md, krb5_principal client, krb5_s2k_proc keyproc, krb5_const_pointer keyseed, krb5_enctype *enctypes, unsigned netypes, krb5_salt *salt, krb5_data *s2kparams) { krb5_error_code ret; krb5_salt salt2; krb5_enctype *ep; size_t i; if(salt == NULL) { /* default to standard salt */ ret = krb5_get_pw_salt (context, client, &salt2); if (ret) return ret; salt = &salt2; } if (!enctypes) { enctypes = context->etypes; netypes = 0; for (ep = enctypes; *ep != (krb5_enctype)ETYPE_NULL; ep++) netypes++; } for (i = 0; i < netypes; ++i) { krb5_keyblock *key; _krb5_debug(context, 5, "krb5_get_init_creds: using ENC-TS with enctype %d", enctypes[i]); ret = (*keyproc)(context, enctypes[i], keyseed, *salt, s2kparams, &key); if (ret) continue; ret = make_pa_enc_timestamp (context, md, enctypes[i], key); krb5_free_keyblock (context, key); if (ret) return ret; } if(salt == &salt2) krb5_free_salt(context, salt2); return 0; } static krb5_error_code pa_data_to_md_ts_enc(krb5_context context, const AS_REQ *a, const krb5_principal client, krb5_get_init_creds_ctx *ctx, struct pa_info_data *ppaid, METHOD_DATA *md) { if (ctx->keyproc == NULL || ctx->keyseed == NULL) return 0; if (ppaid) { add_enc_ts_padata(context, md, client, ctx->keyproc, ctx->keyseed, &ppaid->etype, 1, &ppaid->salt, ppaid->s2kparams); } else { krb5_salt salt; _krb5_debug(context, 5, "krb5_get_init_creds: pa-info not found, guessing salt"); /* make a v5 salted pa-data */ add_enc_ts_padata(context, md, client, ctx->keyproc, ctx->keyseed, a->req_body.etype.val, a->req_body.etype.len, NULL, NULL); /* make a v4 salted pa-data */ salt.salttype = KRB5_PW_SALT; krb5_data_zero(&salt.saltvalue); add_enc_ts_padata(context, md, client, ctx->keyproc, ctx->keyseed, a->req_body.etype.val, a->req_body.etype.len, &salt, NULL); } return 0; } static krb5_error_code pa_data_to_key_plain(krb5_context context, const krb5_principal client, krb5_get_init_creds_ctx *ctx, krb5_salt salt, krb5_data *s2kparams, krb5_enctype etype, krb5_keyblock **key) { krb5_error_code ret; ret = (*ctx->keyproc)(context, etype, ctx->keyseed, salt, s2kparams, key); return ret; } static krb5_error_code pa_data_to_md_pkinit(krb5_context context, const AS_REQ *a, const krb5_principal client, int win2k, krb5_get_init_creds_ctx *ctx, METHOD_DATA *md) { if (ctx->pk_init_ctx == NULL) return 0; #ifdef PKINIT return _krb5_pk_mk_padata(context, ctx->pk_init_ctx, ctx->ic_flags, win2k, &a->req_body, ctx->pk_nonce, md); #else krb5_set_error_message(context, EINVAL, N_("no support for PKINIT compiled in", "")); return EINVAL; #endif } static krb5_error_code pa_data_add_pac_request(krb5_context context, krb5_get_init_creds_ctx *ctx, METHOD_DATA *md) { size_t len = 0, length; krb5_error_code ret; PA_PAC_REQUEST req; void *buf; switch (ctx->req_pac) { case KRB5_INIT_CREDS_TRISTATE_UNSET: return 0; /* don't bother */ case KRB5_INIT_CREDS_TRISTATE_TRUE: req.include_pac = 1; break; case KRB5_INIT_CREDS_TRISTATE_FALSE: req.include_pac = 0; } ASN1_MALLOC_ENCODE(PA_PAC_REQUEST, buf, length, &req, &len, ret); if (ret) return ret; if(len != length) krb5_abortx(context, "internal error in ASN.1 encoder"); ret = krb5_padata_add(context, md, KRB5_PADATA_PA_PAC_REQUEST, buf, len); if (ret) free(buf); return 0; } /* * Assumes caller always will free `out_md', even on error. */ static krb5_error_code process_pa_data_to_md(krb5_context context, const krb5_creds *creds, const AS_REQ *a, krb5_get_init_creds_ctx *ctx, METHOD_DATA *in_md, METHOD_DATA **out_md, krb5_prompter_fct prompter, void *prompter_data) { krb5_error_code ret; ALLOC(*out_md, 1); if (*out_md == NULL) return krb5_enomem(context); (*out_md)->len = 0; (*out_md)->val = NULL; if (_krb5_have_debug(context, 5)) { unsigned i; _krb5_debug(context, 5, "KDC send %d patypes", in_md->len); for (i = 0; i < in_md->len; i++) _krb5_debug(context, 5, "KDC send PA-DATA type: %d", in_md->val[i].padata_type); } /* * Make sure we don't sent both ENC-TS and PK-INIT pa data, no * need to expose our password protecting our PKCS12 key. */ if (ctx->pk_init_ctx) { _krb5_debug(context, 5, "krb5_get_init_creds: " "prepareing PKINIT padata (%s)", (ctx->used_pa_types & USED_PKINIT_W2K) ? "win2k" : "ietf"); if (ctx->used_pa_types & USED_PKINIT_W2K) { krb5_set_error_message(context, KRB5_GET_IN_TKT_LOOP, "Already tried pkinit, looping"); return KRB5_GET_IN_TKT_LOOP; } ret = pa_data_to_md_pkinit(context, a, creds->client, (ctx->used_pa_types & USED_PKINIT), ctx, *out_md); if (ret) return ret; if (ctx->used_pa_types & USED_PKINIT) ctx->used_pa_types |= USED_PKINIT_W2K; else ctx->used_pa_types |= USED_PKINIT; } else if (in_md->len != 0) { struct pa_info_data *paid, *ppaid; unsigned flag; paid = calloc(1, sizeof(*paid)); if (paid == NULL) return krb5_enomem(context); paid->etype = KRB5_ENCTYPE_NULL; ppaid = process_pa_info(context, creds->client, a, paid, in_md); if (ppaid) flag = USED_ENC_TS_INFO; else flag = USED_ENC_TS_GUESS; if (ctx->used_pa_types & flag) { if (ppaid) free_paid(context, ppaid); free(paid); krb5_set_error_message(context, KRB5_GET_IN_TKT_LOOP, "Already tried ENC-TS-%s, looping", flag == USED_ENC_TS_INFO ? "info" : "guess"); return KRB5_GET_IN_TKT_LOOP; } pa_data_to_md_ts_enc(context, a, creds->client, ctx, ppaid, *out_md); ctx->used_pa_types |= flag; if (ppaid) { if (ctx->ppaid) { free_paid(context, ctx->ppaid); free(ctx->ppaid); } ctx->ppaid = ppaid; } else free(paid); } pa_data_add_pac_request(context, ctx, *out_md); if ((ctx->fast_state.flags & KRB5_FAST_DISABLED) == 0) { ret = krb5_padata_add(context, *out_md, KRB5_PADATA_REQ_ENC_PA_REP, NULL, 0); if (ret) return ret; } if ((*out_md)->len == 0) { free(*out_md); *out_md = NULL; } return 0; } static krb5_error_code process_pa_data_to_key(krb5_context context, krb5_get_init_creds_ctx *ctx, krb5_creds *creds, AS_REQ *a, AS_REP *rep, const krb5_krbhst_info *hi, krb5_keyblock **key) { struct pa_info_data paid, *ppaid = NULL; krb5_error_code ret; krb5_enctype etype; PA_DATA *pa; memset(&paid, 0, sizeof(paid)); etype = rep->enc_part.etype; if (rep->padata) { paid.etype = etype; ppaid = process_pa_info(context, creds->client, a, &paid, rep->padata); } if (ppaid == NULL) ppaid = ctx->ppaid; if (ppaid == NULL) { ret = krb5_get_pw_salt (context, creds->client, &paid.salt); if (ret) return ret; paid.etype = etype; paid.s2kparams = NULL; ppaid = &paid; } pa = NULL; if (rep->padata) { int idx = 0; pa = krb5_find_padata(rep->padata->val, rep->padata->len, KRB5_PADATA_PK_AS_REP, &idx); if (pa == NULL) { idx = 0; pa = krb5_find_padata(rep->padata->val, rep->padata->len, KRB5_PADATA_PK_AS_REP_19, &idx); } } if (pa && ctx->pk_init_ctx) { #ifdef PKINIT _krb5_debug(context, 5, "krb5_get_init_creds: using PKINIT"); ret = _krb5_pk_rd_pa_reply(context, a->req_body.realm, ctx->pk_init_ctx, etype, hi, ctx->pk_nonce, &ctx->req_buffer, pa, key); #else ret = EINVAL; krb5_set_error_message(context, ret, N_("no support for PKINIT compiled in", "")); #endif } else if (ctx->keyseed) { _krb5_debug(context, 5, "krb5_get_init_creds: using keyproc"); ret = pa_data_to_key_plain(context, creds->client, ctx, ppaid->salt, ppaid->s2kparams, etype, key); } else { ret = EINVAL; krb5_set_error_message(context, ret, N_("No usable pa data type", "")); } free_paid(context, &paid); return ret; } /** * Start a new context to get a new initial credential. * * @param context A Kerberos 5 context. * @param client The Kerberos principal to get the credential for, if * NULL is given, the default principal is used as determined by * krb5_get_default_principal(). * @param prompter * @param prompter_data * @param start_time the time the ticket should start to be valid or 0 for now. * @param options a options structure, can be NULL for default options. * @param rctx A new allocated free with krb5_init_creds_free(). * * @return 0 for success or an Kerberos 5 error code, see krb5_get_error_message(). * * @ingroup krb5_credential */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_init_creds_init(krb5_context context, krb5_principal client, krb5_prompter_fct prompter, void *prompter_data, krb5_deltat start_time, krb5_get_init_creds_opt *options, krb5_init_creds_context *rctx) { krb5_init_creds_context ctx; krb5_error_code ret; *rctx = NULL; ctx = calloc(1, sizeof(*ctx)); if (ctx == NULL) return krb5_enomem(context); ret = get_init_creds_common(context, client, start_time, options, ctx); if (ret) { free(ctx); return ret; } /* Set a new nonce. */ krb5_generate_random_block (&ctx->nonce, sizeof(ctx->nonce)); ctx->nonce &= 0x7fffffff; /* XXX these just needs to be the same when using Windows PK-INIT */ ctx->pk_nonce = ctx->nonce; ctx->prompter = prompter; ctx->prompter_data = prompter_data; *rctx = ctx; return ret; } /** * Sets the service that the is requested. This call is only neede for * special initial tickets, by default the a krbtgt is fetched in the default realm. * * @param context a Kerberos 5 context. * @param ctx a krb5_init_creds_context context. * @param service the service given as a string, for example * "kadmind/admin". If NULL, the default krbtgt in the clients * realm is set. * * @return 0 for success, or an Kerberos 5 error code, see krb5_get_error_message(). * @ingroup krb5_credential */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_init_creds_set_service(krb5_context context, krb5_init_creds_context ctx, const char *service) { krb5_const_realm client_realm; krb5_principal principal; krb5_error_code ret; client_realm = krb5_principal_get_realm (context, ctx->cred.client); if (service) { ret = krb5_parse_name (context, service, &principal); if (ret) return ret; krb5_principal_set_realm (context, principal, client_realm); } else { ret = krb5_make_principal(context, &principal, client_realm, KRB5_TGS_NAME, client_realm, NULL); if (ret) return ret; } /* * This is for Windows RODC that are picky about what name type * the server principal have, and the really strange part is that * they are picky about the AS-REQ name type and not the TGS-REQ * later. Oh well. */ if (krb5_principal_is_krbtgt(context, principal)) krb5_principal_set_type(context, principal, KRB5_NT_SRV_INST); krb5_free_principal(context, ctx->cred.server); ctx->cred.server = principal; return 0; } /** * Sets the password that will use for the request. * * @param context a Kerberos 5 context. * @param ctx ctx krb5_init_creds_context context. * @param password the password to use. * * @return 0 for success, or an Kerberos 5 error code, see krb5_get_error_message(). * @ingroup krb5_credential */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_init_creds_set_password(krb5_context context, krb5_init_creds_context ctx, const char *password) { if (ctx->password) { memset(ctx->password, 0, strlen(ctx->password)); free(ctx->password); } if (password) { ctx->password = strdup(password); if (ctx->password == NULL) return krb5_enomem(context); ctx->keyseed = (void *) ctx->password; } else { ctx->keyseed = NULL; ctx->password = NULL; } return 0; } static krb5_error_code KRB5_CALLCONV keytab_key_proc(krb5_context context, krb5_enctype enctype, krb5_const_pointer keyseed, krb5_salt salt, krb5_data *s2kparms, krb5_keyblock **key) { krb5_keytab_key_proc_args *args = rk_UNCONST(keyseed); krb5_keytab keytab = args->keytab; krb5_principal principal = args->principal; krb5_error_code ret; krb5_keytab real_keytab; krb5_keytab_entry entry; if(keytab == NULL) krb5_kt_default(context, &real_keytab); else real_keytab = keytab; ret = krb5_kt_get_entry (context, real_keytab, principal, 0, enctype, &entry); if (keytab == NULL) krb5_kt_close (context, real_keytab); if (ret) return ret; ret = krb5_copy_keyblock (context, &entry.keyblock, key); krb5_kt_free_entry(context, &entry); return ret; } /** * Set the keytab to use for authentication. * * @param context a Kerberos 5 context. * @param ctx ctx krb5_init_creds_context context. * @param keytab the keytab to read the key from. * * @return 0 for success, or an Kerberos 5 error code, see krb5_get_error_message(). * @ingroup krb5_credential */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_init_creds_set_keytab(krb5_context context, krb5_init_creds_context ctx, krb5_keytab keytab) { krb5_keytab_key_proc_args *a; krb5_keytab_entry entry; krb5_kt_cursor cursor; krb5_enctype *etypes = NULL; krb5_error_code ret; size_t netypes = 0; int kvno = 0, found = 0; a = malloc(sizeof(*a)); if (a == NULL) return krb5_enomem(context); a->principal = ctx->cred.client; a->keytab = keytab; ctx->keytab_data = a; ctx->keyseed = (void *)a; ctx->keyproc = keytab_key_proc; /* * We need to the KDC what enctypes we support for this keytab, * esp if the keytab is really a password based entry, then the * KDC might have more enctypes in the database then what we have * in the keytab. */ ret = krb5_kt_start_seq_get(context, keytab, &cursor); if(ret) goto out; while(krb5_kt_next_entry(context, keytab, &entry, &cursor) == 0){ void *ptr; if (!krb5_principal_compare(context, entry.principal, ctx->cred.client)) goto next; found = 1; /* check if we ahve this kvno already */ if (entry.vno > kvno) { /* remove old list of etype */ if (etypes) free(etypes); etypes = NULL; netypes = 0; kvno = entry.vno; } else if (entry.vno != kvno) goto next; /* check if enctype is supported */ if (krb5_enctype_valid(context, entry.keyblock.keytype) != 0) goto next; /* add enctype to supported list */ ptr = realloc(etypes, sizeof(etypes[0]) * (netypes + 2)); if (ptr == NULL) { free(etypes); ret = krb5_enomem(context); goto out; } etypes = ptr; etypes[netypes] = entry.keyblock.keytype; etypes[netypes + 1] = ETYPE_NULL; netypes++; next: krb5_kt_free_entry(context, &entry); } krb5_kt_end_seq_get(context, keytab, &cursor); if (etypes) { if (ctx->etypes) free(ctx->etypes); ctx->etypes = etypes; } out: if (!found) { if (ret == 0) ret = KRB5_KT_NOTFOUND; _krb5_kt_principal_not_found(context, ret, keytab, ctx->cred.client, 0, 0); } return ret; } static krb5_error_code KRB5_CALLCONV keyblock_key_proc(krb5_context context, krb5_enctype enctype, krb5_const_pointer keyseed, krb5_salt salt, krb5_data *s2kparms, krb5_keyblock **key) { return krb5_copy_keyblock (context, keyseed, key); } KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_init_creds_set_keyblock(krb5_context context, krb5_init_creds_context ctx, krb5_keyblock *keyblock) { ctx->keyseed = (void *)keyblock; ctx->keyproc = keyblock_key_proc; return 0; } KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_init_creds_set_fast_ccache(krb5_context context, krb5_init_creds_context ctx, krb5_ccache fast_ccache) { ctx->fast_state.armor_ccache = fast_ccache; ctx->fast_state.flags |= KRB5_FAST_REQUIRED; return 0; } KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_init_creds_set_fast_ap_armor_service(krb5_context context, krb5_init_creds_context ctx, krb5_const_principal armor_service) { krb5_error_code ret; if (ctx->fast_state.armor_service) krb5_free_principal(context, ctx->fast_state.armor_service); if (armor_service) { ret = krb5_copy_principal(context, armor_service, &ctx->fast_state.armor_service); if (ret) return ret; } else { ctx->fast_state.armor_service = NULL; } ctx->fast_state.flags |= KRB5_FAST_REQUIRED | KRB5_FAST_AP_ARMOR_SERVICE; return 0; } /* * FAST */ static krb5_error_code check_fast(krb5_context context, struct fast_state *state) { if (state->flags & KRB5_FAST_EXPECTED) { krb5_set_error_message(context, KRB5KRB_AP_ERR_MODIFIED, "Expected FAST, but no FAST " "was in the response from the KDC"); return KRB5KRB_AP_ERR_MODIFIED; } return 0; } static krb5_error_code fast_unwrap_as_rep(krb5_context context, int32_t nonce, krb5_data *chksumdata, struct fast_state *state, AS_REP *rep) { PA_FX_FAST_REPLY fxfastrep; KrbFastResponse fastrep; krb5_error_code ret; PA_DATA *pa = NULL; int idx = 0; if (state->armor_crypto == NULL || rep->padata == NULL) return check_fast(context, state); /* find PA_FX_FAST_REPLY */ pa = krb5_find_padata(rep->padata->val, rep->padata->len, KRB5_PADATA_FX_FAST, &idx); if (pa == NULL) return check_fast(context, state); memset(&fxfastrep, 0, sizeof(fxfastrep)); memset(&fastrep, 0, sizeof(fastrep)); ret = decode_PA_FX_FAST_REPLY(pa->padata_value.data, pa->padata_value.length, &fxfastrep, NULL); if (ret) return ret; if (fxfastrep.element == choice_PA_FX_FAST_REPLY_armored_data) { krb5_data data; ret = krb5_decrypt_EncryptedData(context, state->armor_crypto, KRB5_KU_FAST_REP, &fxfastrep.u.armored_data.enc_fast_rep, &data); if (ret) goto out; ret = decode_KrbFastResponse(data.data, data.length, &fastrep, NULL); krb5_data_free(&data); if (ret) goto out; } else { ret = KRB5KDC_ERR_PREAUTH_FAILED; goto out; } free_METHOD_DATA(rep->padata); ret = copy_METHOD_DATA(&fastrep.padata, rep->padata); if (ret) goto out; if (fastrep.strengthen_key) { if (state->strengthen_key) krb5_free_keyblock(context, state->strengthen_key); ret = krb5_copy_keyblock(context, fastrep.strengthen_key, &state->strengthen_key); if (ret) goto out; } if (nonce != fastrep.nonce) { ret = KRB5KDC_ERR_PREAUTH_FAILED; goto out; } if (fastrep.finished) { PrincipalName cname; krb5_realm crealm = NULL; if (chksumdata == NULL) { ret = KRB5KDC_ERR_PREAUTH_FAILED; goto out; } ret = krb5_verify_checksum(context, state->armor_crypto, KRB5_KU_FAST_FINISHED, chksumdata->data, chksumdata->length, &fastrep.finished->ticket_checksum); if (ret) goto out; /* update */ ret = copy_Realm(&fastrep.finished->crealm, &crealm); if (ret) goto out; free_Realm(&rep->crealm); rep->crealm = crealm; ret = copy_PrincipalName(&fastrep.finished->cname, &cname); if (ret) goto out; free_PrincipalName(&rep->cname); rep->cname = cname; #if 0 /* store authenticated checksum as kdc-offset */ fastrep->finished.timestamp; fastrep->finished.usec = 0; #endif } else if (chksumdata) { /* expected fastrep.finish but didn't get it */ ret = KRB5KDC_ERR_PREAUTH_FAILED; } out: free_PA_FX_FAST_REPLY(&fxfastrep); return ret; } static krb5_error_code fast_unwrap_error(krb5_context context, struct fast_state *state, KRB_ERROR *error) { if (state->armor_crypto == NULL) return check_fast(context, state); return 0; } krb5_error_code _krb5_make_fast_ap_fxarmor(krb5_context context, krb5_ccache armor_ccache, krb5_data *armor_value, krb5_keyblock *armor_key, krb5_crypto *armor_crypto) { krb5_auth_context auth_context = NULL; krb5_creds cred, *credp = NULL; krb5_error_code ret; krb5_data empty; krb5_data_zero(&empty); memset(&cred, 0, sizeof(cred)); ret = krb5_auth_con_init (context, &auth_context); if (ret) goto out; ret = krb5_cc_get_principal(context, armor_ccache, &cred.client); if (ret) goto out; ret = krb5_make_principal(context, &cred.server, cred.client->realm, KRB5_TGS_NAME, cred.client->realm, NULL); if (ret) { krb5_free_principal(context, cred.client); goto out; } ret = krb5_get_credentials(context, 0, armor_ccache, &cred, &credp); krb5_free_principal(context, cred.server); krb5_free_principal(context, cred.client); if (ret) goto out; ret = krb5_auth_con_add_AuthorizationData(context, auth_context, KRB5_PADATA_FX_FAST_ARMOR, &empty); if (ret) goto out; ret = krb5_mk_req_extended(context, &auth_context, AP_OPTS_USE_SUBKEY, NULL, credp, armor_value); krb5_free_creds(context, credp); if (ret) goto out; ret = _krb5_fast_armor_key(context, auth_context->local_subkey, auth_context->keyblock, armor_key, armor_crypto); if (ret) goto out; out: krb5_auth_con_free(context, auth_context); return ret; } #ifndef WIN32 static heim_base_once_t armor_service_once = HEIM_BASE_ONCE_INIT; static heim_ipc armor_service = NULL; static void fast_armor_init_ipc(void *ctx) { heim_ipc *ipc = ctx; heim_ipc_init_context("ANY:org.h5l.armor-service", ipc); } #endif /* WIN32 */ static krb5_error_code make_fast_ap_fxarmor(krb5_context context, struct fast_state *state, const char *realm, KrbFastArmor **armor) { KrbFastArmor *fxarmor = NULL; krb5_error_code ret; if (state->armor_crypto) krb5_crypto_destroy(context, state->armor_crypto); krb5_free_keyblock_contents(context, &state->armor_key); ALLOC(fxarmor, 1); if (fxarmor == NULL) return krb5_enomem(context); if (state->flags & KRB5_FAST_AP_ARMOR_SERVICE) { #ifdef WIN32 krb5_set_error_message(context, ENOTSUP, "Fast armor IPC service not supportted yet on Windows"); ret = ENOTSUP; goto out; #else /* WIN32 */ KERB_ARMOR_SERVICE_REPLY msg; krb5_data request, reply; heim_base_once_f(&armor_service_once, &armor_service, fast_armor_init_ipc); if (armor_service == NULL) { krb5_set_error_message(context, ENOENT, "Failed to open fast armor service"); ret = ENOENT; goto out; } krb5_data_zero(&reply); request.data = rk_UNCONST(realm); request.length = strlen(realm); ret = heim_ipc_call(armor_service, &request, &reply, NULL); heim_release(send); if (ret) { krb5_set_error_message(context, ret, "Failed to get armor service credential"); goto out; } ret = decode_KERB_ARMOR_SERVICE_REPLY(reply.data, reply.length, &msg, NULL); krb5_data_free(&reply); if (ret) goto out; ret = copy_KrbFastArmor(fxarmor, &msg.armor); if (ret) { free_KERB_ARMOR_SERVICE_REPLY(&msg); goto out; } ret = krb5_copy_keyblock_contents(context, &msg.armor_key, &state->armor_key); free_KERB_ARMOR_SERVICE_REPLY(&msg); if (ret) goto out; ret = krb5_crypto_init(context, &state->armor_key, 0, &state->armor_crypto); if (ret) goto out; #endif /* WIN32 */ } else { fxarmor->armor_type = 1; ret = _krb5_make_fast_ap_fxarmor(context, state->armor_ccache, &fxarmor->armor_value, &state->armor_key, &state->armor_crypto); if (ret) goto out; } *armor = fxarmor; fxarmor = NULL; out: if (fxarmor) { free_KrbFastArmor(fxarmor); free(fxarmor); } return ret; } static krb5_error_code fast_wrap_req(krb5_context context, struct fast_state *state, KDC_REQ *req) { KrbFastArmor *fxarmor = NULL; PA_FX_FAST_REQUEST fxreq; krb5_error_code ret; KrbFastReq fastreq; krb5_data data; size_t size; if (state->flags & KRB5_FAST_DISABLED) { _krb5_debug(context, 10, "fast disabled, not doing any fast wrapping"); return 0; } memset(&fxreq, 0, sizeof(fxreq)); memset(&fastreq, 0, sizeof(fastreq)); krb5_data_zero(&data); if (state->armor_crypto == NULL) { if (state->armor_ccache) { /* * Instead of keeping state in FX_COOKIE in the KDC, we * rebuild a new armor key for every request, because this * is what the MIT KDC expect and RFC6113 is vage about * what the behavior should be. */ state->type = choice_PA_FX_FAST_REQUEST_armored_data; } else { return check_fast(context, state); } } state->flags |= KRB5_FAST_EXPECTED; fastreq.fast_options.hide_client_names = 1; ret = copy_KDC_REQ_BODY(&req->req_body, &fastreq.req_body); free_KDC_REQ_BODY(&req->req_body); req->req_body.realm = strdup(KRB5_ANON_REALM); if ((ALLOC(req->req_body.cname, 1)) != NULL) { req->req_body.cname->name_type = KRB5_NT_WELLKNOWN; if ((ALLOC(req->req_body.cname->name_string.val, 2)) != NULL) { req->req_body.cname->name_string.len = 2; req->req_body.cname->name_string.val[0] = strdup(KRB5_WELLKNOWN_NAME); req->req_body.cname->name_string.val[1] = strdup(KRB5_ANON_NAME); if (req->req_body.cname->name_string.val[0] == NULL || req->req_body.cname->name_string.val[1] == NULL) ret = krb5_enomem(context); } else ret = krb5_enomem(context); } else ret = krb5_enomem(context); if ((ALLOC(req->req_body.till, 1)) != NULL) *req->req_body.till = 0; else ret = krb5_enomem(context); if (ret) goto out; if (req->padata) { ret = copy_METHOD_DATA(req->padata, &fastreq.padata); free_METHOD_DATA(req->padata); } else { if ((ALLOC(req->padata, 1)) == NULL) ret = krb5_enomem(context); } if (ret) goto out; ASN1_MALLOC_ENCODE(KrbFastReq, data.data, data.length, &fastreq, &size, ret); if (ret) goto out; heim_assert(data.length == size, "ASN.1 internal error"); fxreq.element = state->type; if (state->type == choice_PA_FX_FAST_REQUEST_armored_data) { size_t len; void *buf; ret = make_fast_ap_fxarmor(context, state, fastreq.req_body.realm, &fxreq.u.armored_data.armor); if (ret) goto out; heim_assert(state->armor_crypto != NULL, "FAST armor key missing when FAST started"); ASN1_MALLOC_ENCODE(KDC_REQ_BODY, buf, len, &req->req_body, &size, ret); if (ret) goto out; heim_assert(len == size, "ASN.1 internal error"); ret = krb5_create_checksum(context, state->armor_crypto, KRB5_KU_FAST_REQ_CHKSUM, 0, buf, len, &fxreq.u.armored_data.req_checksum); free(buf); if (ret) goto out; ret = krb5_encrypt_EncryptedData(context, state->armor_crypto, KRB5_KU_FAST_ENC, data.data, data.length, 0, &fxreq.u.armored_data.enc_fast_req); krb5_data_free(&data); if (ret) goto out; } else { krb5_data_free(&data); heim_assert(false, "unknown FAST type, internal error"); } ASN1_MALLOC_ENCODE(PA_FX_FAST_REQUEST, data.data, data.length, &fxreq, &size, ret); if (ret) goto out; heim_assert(data.length == size, "ASN.1 internal error"); ret = krb5_padata_add(context, req->padata, KRB5_PADATA_FX_FAST, data.data, data.length); if (ret) goto out; krb5_data_zero(&data); out: free_PA_FX_FAST_REQUEST(&fxreq); free_KrbFastReq(&fastreq); if (fxarmor) { free_KrbFastArmor(fxarmor); free(fxarmor); } krb5_data_free(&data); return ret; } /** * The core loop if krb5_get_init_creds() function family. Create the * packets and have the caller send them off to the KDC. * * If the caller want all work been done for them, use * krb5_init_creds_get() instead. * * @param context a Kerberos 5 context. * @param ctx ctx krb5_init_creds_context context. * @param in input data from KDC, first round it should be reset by krb5_data_zer(). * @param out reply to KDC. * @param hostinfo KDC address info, first round it can be NULL. * @param flags status of the round, if * KRB5_INIT_CREDS_STEP_FLAG_CONTINUE is set, continue one more round. * * @return 0 for success, or an Kerberos 5 error code, see * krb5_get_error_message(). * * @ingroup krb5_credential */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_init_creds_step(krb5_context context, krb5_init_creds_context ctx, krb5_data *in, krb5_data *out, krb5_krbhst_info *hostinfo, unsigned int *flags) { krb5_error_code ret; size_t len = 0; size_t size; AS_REQ req2; krb5_data_zero(out); if (ctx->as_req.req_body.cname == NULL) { ret = init_as_req(context, ctx->flags, &ctx->cred, ctx->addrs, ctx->etypes, &ctx->as_req); if (ret) { free_init_creds_ctx(context, ctx); return ret; } } #define MAX_PA_COUNTER 10 if (ctx->pa_counter > MAX_PA_COUNTER) { krb5_set_error_message(context, KRB5_GET_IN_TKT_LOOP, N_("Looping %d times while getting " "initial credentials", ""), ctx->pa_counter); return KRB5_GET_IN_TKT_LOOP; } ctx->pa_counter++; _krb5_debug(context, 5, "krb5_get_init_creds: loop %d", ctx->pa_counter); /* Lets process the input packet */ if (in && in->length) { krb5_kdc_rep rep; memset(&rep, 0, sizeof(rep)); _krb5_debug(context, 5, "krb5_get_init_creds: processing input"); ret = decode_AS_REP(in->data, in->length, &rep.kdc_rep, &size); if (ret == 0) { unsigned eflags = EXTRACT_TICKET_AS_REQ | EXTRACT_TICKET_TIMESYNC; krb5_data data; /* * Unwrap AS-REP */ ASN1_MALLOC_ENCODE(Ticket, data.data, data.length, &rep.kdc_rep.ticket, &size, ret); if (ret) goto out; heim_assert(data.length == size, "ASN.1 internal error"); ret = fast_unwrap_as_rep(context, ctx->nonce, &data, &ctx->fast_state, &rep.kdc_rep); krb5_data_free(&data); if (ret) goto out; /* * Now check and extract the ticket */ if (ctx->flags.canonicalize) { eflags |= EXTRACT_TICKET_ALLOW_SERVER_MISMATCH; eflags |= EXTRACT_TICKET_MATCH_REALM; } if (ctx->ic_flags & KRB5_INIT_CREDS_NO_C_CANON_CHECK) eflags |= EXTRACT_TICKET_ALLOW_CNAME_MISMATCH; ret = process_pa_data_to_key(context, ctx, &ctx->cred, &ctx->as_req, &rep.kdc_rep, hostinfo, &ctx->fast_state.reply_key); if (ret) { free_AS_REP(&rep.kdc_rep); goto out; } _krb5_debug(context, 5, "krb5_get_init_creds: extracting ticket"); ret = _krb5_extract_ticket(context, &rep, &ctx->cred, ctx->fast_state.reply_key, NULL, KRB5_KU_AS_REP_ENC_PART, NULL, ctx->nonce, eflags, &ctx->req_buffer, NULL, NULL); if (ret == 0) ret = copy_EncKDCRepPart(&rep.enc_part, &ctx->enc_part); krb5_free_keyblock(context, ctx->fast_state.reply_key); ctx->fast_state.reply_key = NULL; *flags = 0; free_AS_REP(&rep.kdc_rep); free_EncASRepPart(&rep.enc_part); return ret; } else { /* let's try to parse it as a KRB-ERROR */ _krb5_debug(context, 5, "krb5_get_init_creds: got an error"); free_KRB_ERROR(&ctx->error); ret = krb5_rd_error(context, in, &ctx->error); if(ret && in->length && ((char*)in->data)[0] == 4) ret = KRB5KRB_AP_ERR_V4_REPLY; if (ret) { _krb5_debug(context, 5, "krb5_get_init_creds: failed to read error"); goto out; } /* * Unwrap KRB-ERROR */ ret = fast_unwrap_error(context, &ctx->fast_state, &ctx->error); if (ret) goto out; /* * */ ret = krb5_error_from_rd_error(context, &ctx->error, &ctx->cred); _krb5_debug(context, 5, "krb5_get_init_creds: KRB-ERROR %d", ret); /* * If no preauth was set and KDC requires it, give it one * more try. */ if (ret == KRB5KDC_ERR_PREAUTH_REQUIRED) { free_METHOD_DATA(&ctx->md); memset(&ctx->md, 0, sizeof(ctx->md)); if (ctx->error.e_data) { ret = decode_METHOD_DATA(ctx->error.e_data->data, ctx->error.e_data->length, &ctx->md, NULL); if (ret) krb5_set_error_message(context, ret, N_("Failed to decode METHOD-DATA", "")); } else { krb5_set_error_message(context, ret, N_("Preauth required but no preauth " "options send by KDC", "")); } } else if (ret == KRB5KRB_AP_ERR_SKEW && context->kdc_sec_offset == 0) { /* * Try adapt to timeskrew when we are using pre-auth, and * if there was a time skew, try again. */ krb5_set_real_time(context, ctx->error.stime, -1); if (context->kdc_sec_offset) ret = 0; _krb5_debug(context, 10, "init_creds: err skew updateing kdc offset to %d", context->kdc_sec_offset); ctx->used_pa_types = 0; } else if (ret == KRB5_KDC_ERR_WRONG_REALM && ctx->flags.canonicalize) { /* client referal to a new realm */ if (ctx->error.crealm == NULL) { krb5_set_error_message(context, ret, N_("Got a client referral, not but no realm", "")); goto out; } _krb5_debug(context, 5, "krb5_get_init_creds: got referal to realm %s", *ctx->error.crealm); ret = krb5_principal_set_realm(context, ctx->cred.client, *ctx->error.crealm); if (ret) goto out; if (krb5_principal_is_krbtgt(context, ctx->cred.server)) { ret = krb5_init_creds_set_service(context, ctx, NULL); if (ret) goto out; } free_AS_REQ(&ctx->as_req); memset(&ctx->as_req, 0, sizeof(ctx->as_req)); ctx->used_pa_types = 0; } else if (ret == KRB5KDC_ERR_KEY_EXP && ctx->runflags.change_password == 0 && ctx->prompter) { char buf2[1024]; ctx->runflags.change_password = 1; ctx->prompter(context, ctx->prompter_data, NULL, N_("Password has expired", ""), 0, NULL); /* try to avoid recursion */ if (ctx->in_tkt_service != NULL && strcmp(ctx->in_tkt_service, "kadmin/changepw") == 0) goto out; /* don't try to change password where then where none */ if (ctx->prompter == NULL) goto out; ret = change_password(context, ctx->cred.client, ctx->password, buf2, sizeof(buf2), ctx->prompter, ctx->prompter_data, NULL); if (ret) goto out; krb5_init_creds_set_password(context, ctx, buf2); ctx->used_pa_types = 0; ret = 0; } else if (ret == KRB5KDC_ERR_PREAUTH_FAILED) { if (ctx->fast_state.flags & KRB5_FAST_DISABLED) goto out; if (ctx->fast_state.flags & (KRB5_FAST_REQUIRED | KRB5_FAST_EXPECTED)) goto out; _krb5_debug(context, 10, "preauth failed with FAST, " "and told by KD or user, trying w/o FAST"); ctx->fast_state.flags |= KRB5_FAST_DISABLED; ctx->used_pa_types = 0; ret = 0; } if (ret) goto out; } } if (ctx->as_req.req_body.cname == NULL) { ret = init_as_req(context, ctx->flags, &ctx->cred, ctx->addrs, ctx->etypes, &ctx->as_req); if (ret) { free_init_creds_ctx(context, ctx); return ret; } } if (ctx->as_req.padata) { free_METHOD_DATA(ctx->as_req.padata); free(ctx->as_req.padata); ctx->as_req.padata = NULL; } /* Set a new nonce. */ ctx->as_req.req_body.nonce = ctx->nonce; /* fill_in_md_data */ ret = process_pa_data_to_md(context, &ctx->cred, &ctx->as_req, ctx, &ctx->md, &ctx->as_req.padata, ctx->prompter, ctx->prompter_data); if (ret) goto out; /* * Wrap with FAST */ copy_AS_REQ(&ctx->as_req, &req2); ret = fast_wrap_req(context, &ctx->fast_state, &req2); if (ret) { free_AS_REQ(&req2); goto out; } krb5_data_free(&ctx->req_buffer); ASN1_MALLOC_ENCODE(AS_REQ, ctx->req_buffer.data, ctx->req_buffer.length, &req2, &len, ret); free_AS_REQ(&req2); if (ret) goto out; if(len != ctx->req_buffer.length) krb5_abortx(context, "internal error in ASN.1 encoder"); out->data = ctx->req_buffer.data; out->length = ctx->req_buffer.length; *flags = KRB5_INIT_CREDS_STEP_FLAG_CONTINUE; return 0; out: return ret; } /** * Extract the newly acquired credentials from krb5_init_creds_context * context. * * @param context A Kerberos 5 context. * @param ctx * @param cred credentials, free with krb5_free_cred_contents(). * * @return 0 for sucess or An Kerberos error code, see krb5_get_error_message(). */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_init_creds_get_creds(krb5_context context, krb5_init_creds_context ctx, krb5_creds *cred) { return krb5_copy_creds_contents(context, &ctx->cred, cred); } /** * Get the last error from the transaction. * * @return Returns 0 or an error code * * @ingroup krb5_credential */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_init_creds_get_error(krb5_context context, krb5_init_creds_context ctx, KRB_ERROR *error) { krb5_error_code ret; ret = copy_KRB_ERROR(&ctx->error, error); if (ret) krb5_enomem(context); return ret; } /** * * @ingroup krb5_credential */ krb5_error_code krb5_init_creds_store(krb5_context context, krb5_init_creds_context ctx, krb5_ccache id) { krb5_error_code ret; if (ctx->cred.client == NULL) { ret = KRB5KDC_ERR_PREAUTH_REQUIRED; krb5_set_error_message(context, ret, "init creds not completed yet"); return ret; } ret = krb5_cc_initialize(context, id, ctx->cred.client); if (ret) return ret; ret = krb5_cc_store_cred(context, id, &ctx->cred); if (ret) return ret; if (ctx->cred.flags.b.enc_pa_rep) { krb5_data data = { 3, rk_UNCONST("yes") }; ret = krb5_cc_set_config(context, id, ctx->cred.server, "fast_avail", &data); if (ret) return ret; } return ret; } /** * Free the krb5_init_creds_context allocated by krb5_init_creds_init(). * * @param context A Kerberos 5 context. * @param ctx The krb5_init_creds_context to free. * * @ingroup krb5_credential */ KRB5_LIB_FUNCTION void KRB5_LIB_CALL krb5_init_creds_free(krb5_context context, krb5_init_creds_context ctx) { free_init_creds_ctx(context, ctx); free(ctx); } /** * Get new credentials as setup by the krb5_init_creds_context. * * @param context A Kerberos 5 context. * @param ctx The krb5_init_creds_context to process. * * @ingroup krb5_credential */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_init_creds_get(krb5_context context, krb5_init_creds_context ctx) { krb5_sendto_ctx stctx = NULL; krb5_krbhst_info *hostinfo = NULL; krb5_error_code ret; krb5_data in, out; unsigned int flags = 0; krb5_data_zero(&in); krb5_data_zero(&out); ret = krb5_sendto_ctx_alloc(context, &stctx); if (ret) goto out; krb5_sendto_ctx_set_func(stctx, _krb5_kdc_retry, NULL); while (1) { flags = 0; ret = krb5_init_creds_step(context, ctx, &in, &out, hostinfo, &flags); krb5_data_free(&in); if (ret) goto out; if ((flags & 1) == 0) break; ret = krb5_sendto_context (context, stctx, &out, ctx->cred.client->realm, &in); if (ret) goto out; } out: if (stctx) krb5_sendto_ctx_free(context, stctx); return ret; } /** * Get new credentials using password. * * @ingroup krb5_credential */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_get_init_creds_password(krb5_context context, krb5_creds *creds, krb5_principal client, const char *password, krb5_prompter_fct prompter, void *data, krb5_deltat start_time, const char *in_tkt_service, krb5_get_init_creds_opt *options) { krb5_init_creds_context ctx; char buf[BUFSIZ], buf2[BUFSIZ]; krb5_error_code ret; int chpw = 0; again: ret = krb5_init_creds_init(context, client, prompter, data, start_time, options, &ctx); if (ret) goto out; ret = krb5_init_creds_set_service(context, ctx, in_tkt_service); if (ret) goto out; if (prompter != NULL && ctx->password == NULL && password == NULL) { krb5_prompt prompt; krb5_data password_data; char *p, *q = NULL; int aret; ret = krb5_unparse_name(context, client, &p); if (ret) goto out; aret = asprintf(&q, "%s's Password: ", p); free (p); if (aret == -1 || q == NULL) { ret = krb5_enomem(context); goto out; } prompt.prompt = q; password_data.data = buf; password_data.length = sizeof(buf); prompt.hidden = 1; prompt.reply = &password_data; prompt.type = KRB5_PROMPT_TYPE_PASSWORD; ret = (*prompter) (context, data, NULL, NULL, 1, &prompt); free (q); if (ret) { memset (buf, 0, sizeof(buf)); ret = KRB5_LIBOS_PWDINTR; krb5_clear_error_message (context); goto out; } password = password_data.data; } if (password) { ret = krb5_init_creds_set_password(context, ctx, password); if (ret) goto out; } ret = krb5_init_creds_get(context, ctx); if (ret == 0) krb5_process_last_request(context, options, ctx); if (ret == KRB5KDC_ERR_KEY_EXPIRED && chpw == 0) { /* try to avoid recursion */ if (in_tkt_service != NULL && strcmp(in_tkt_service, "kadmin/changepw") == 0) goto out; /* don't try to change password where then where none */ if (prompter == NULL) goto out; if ((options->flags & KRB5_GET_INIT_CREDS_OPT_CHANGE_PASSWORD_PROMPT) && !options->change_password_prompt) goto out; ret = change_password (context, client, ctx->password, buf2, sizeof(buf2), prompter, data, options); if (ret) goto out; password = buf2; chpw = 1; krb5_init_creds_free(context, ctx); goto again; } out: if (ret == 0) krb5_init_creds_get_creds(context, ctx, creds); if (ctx) krb5_init_creds_free(context, ctx); memset(buf, 0, sizeof(buf)); memset(buf2, 0, sizeof(buf2)); return ret; } /** * Get new credentials using keyblock. * * @ingroup krb5_credential */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_get_init_creds_keyblock(krb5_context context, krb5_creds *creds, krb5_principal client, krb5_keyblock *keyblock, krb5_deltat start_time, const char *in_tkt_service, krb5_get_init_creds_opt *options) { krb5_init_creds_context ctx; krb5_error_code ret; memset(creds, 0, sizeof(*creds)); ret = krb5_init_creds_init(context, client, NULL, NULL, start_time, options, &ctx); if (ret) goto out; ret = krb5_init_creds_set_service(context, ctx, in_tkt_service); if (ret) goto out; ret = krb5_init_creds_set_keyblock(context, ctx, keyblock); if (ret) goto out; ret = krb5_init_creds_get(context, ctx); if (ret == 0) krb5_process_last_request(context, options, ctx); out: if (ret == 0) krb5_init_creds_get_creds(context, ctx, creds); if (ctx) krb5_init_creds_free(context, ctx); return ret; } /** * Get new credentials using keytab. * * @ingroup krb5_credential */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_get_init_creds_keytab(krb5_context context, krb5_creds *creds, krb5_principal client, krb5_keytab keytab, krb5_deltat start_time, const char *in_tkt_service, krb5_get_init_creds_opt *options) { krb5_init_creds_context ctx; krb5_keytab_entry ktent; krb5_error_code ret; memset(&ktent, 0, sizeof(ktent)); memset(creds, 0, sizeof(*creds)); if (strcmp(client->realm, "") == 0) { /* * Referral realm. We have a keytab, so pick a realm by * matching in the keytab. */ ret = krb5_kt_get_entry(context, keytab, client, 0, 0, &ktent); if (ret == 0) client = ktent.principal; } ret = krb5_init_creds_init(context, client, NULL, NULL, start_time, options, &ctx); if (ret) goto out; ret = krb5_init_creds_set_service(context, ctx, in_tkt_service); if (ret) goto out; ret = krb5_init_creds_set_keytab(context, ctx, keytab); if (ret) goto out; ret = krb5_init_creds_get(context, ctx); if (ret == 0) krb5_process_last_request(context, options, ctx); out: krb5_kt_free_entry(context, &ktent); if (ret == 0) krb5_init_creds_get_creds(context, ctx, creds); if (ctx) krb5_init_creds_free(context, ctx); return ret; } heimdal-7.5.0/lib/krb5/doxygen.c0000644000175000017500000006341413026237312014513 0ustar niknik/* * Copyright (c) 2007-2008 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "krb5_locl.h" /** * */ /*! @mainpage Heimdal Kerberos 5 library * * @section intro Introduction * * Heimdal libkrb5 library is a implementation of the Kerberos * protocol. * * Kerberos is a system for authenticating users and services on a * network. It is built upon the assumption that the network is * ``unsafe''. For example, data sent over the network can be * eavesdropped and altered, and addresses can also be faked. * Therefore they cannot be used for authentication purposes. * * * - @ref krb5_introduction * - @ref krb5_principal_intro * - @ref krb5_ccache_intro * - @ref krb5_keytab_intro * * If you want to know more about the file formats that is used by * Heimdal, please see: @ref krb5_fileformats * * The project web page: http://www.h5l.org/ * */ /** @defgroup krb5 Heimdal Kerberos 5 library */ /** @defgroup krb5_address Heimdal Kerberos 5 address functions */ /** @defgroup krb5_principal Heimdal Kerberos 5 principal functions */ /** @defgroup krb5_ccache Heimdal Kerberos 5 credential cache functions */ /** @defgroup krb5_crypto Heimdal Kerberos 5 cryptography functions */ /** @defgroup krb5_credential Heimdal Kerberos 5 credential handing functions */ /** @defgroup krb5_deprecated Heimdal Kerberos 5 deprecated functions */ /** @defgroup krb5_digest Heimdal Kerberos 5 digest service */ /** @defgroup krb5_error Heimdal Kerberos 5 error reporting functions */ /** @defgroup krb5_keytab Heimdal Kerberos 5 keytab handling functions */ /** @defgroup krb5_ticket Heimdal Kerberos 5 ticket functions */ /** @defgroup krb5_pac Heimdal Kerberos 5 PAC handling functions */ /** @defgroup krb5_v4compat Heimdal Kerberos 4 compatiblity functions */ /** @defgroup krb5_storage Heimdal Kerberos 5 storage functions */ /** @defgroup krb5_support Heimdal Kerberos 5 support functions */ /** @defgroup krb5_auth Heimdal Kerberos 5 authentication functions */ /** * @page krb5_introduction Introduction to the Kerberos 5 API * @section api_overview Kerberos 5 API Overview * * All functions are documented in manual pages. This section tries * to give an overview of the major components used in Kerberos * library, and point to where to look for a specific function. * * @subsection intro_krb5_context Kerberos context * * A kerberos context (krb5_context) holds all per thread state. All * global variables that are context specific are stored in this * structure, including default encryption types, credential cache * (for example, a ticket file), and default realms. * * The internals of the structure should never be accessed directly, * functions exist for extracting information. * * See the manual page for krb5_init_context() how to create a context * and module @ref krb5 for more information about the functions. * * @subsection intro_krb5_auth_context Kerberos authentication context * * Kerberos authentication context (krb5_auth_context) holds all * context related to an authenticated connection, in a similar way to * the kerberos context that holds the context for the thread or * process. * * The krb5_auth_context is used by various functions that are * directly related to authentication between the * server/client. Example of data that this structure contains are * various flags, addresses of client and server, port numbers, * keyblocks (and subkeys), sequence numbers, replay cache, and * checksum types. * * @subsection intro_krb5_principal Kerberos principal * * The Kerberos principal is the structure that identifies a user or * service in Kerberos. The structure that holds the principal is the * krb5_principal. There are function to extract the realm and * elements of the principal, but most applications have no reason to * inspect the content of the structure. * * The are several ways to create a principal (with different degree of * portability), and one way to free it. * * See also the page @ref krb5_principal_intro for more information and also * module @ref krb5_principal. * * @subsection intro_krb5_ccache Credential cache * * A credential cache holds the tickets for a user. A given user can * have several credential caches, one for each realm where the user * have the initial tickets (the first krbtgt). * * The credential cache data can be stored internally in different * way, each of them for different proposes. File credential (FILE) * caches and processes based (KCM) caches are for permanent * storage. While memory caches (MEMORY) are local caches to the local * process. * * Caches are opened with krb5_cc_resolve() or created with * krb5_cc_new_unique(). * * If the cache needs to be opened again (using krb5_cc_resolve()) * krb5_cc_close() will close the handle, but not the remove the * cache. krb5_cc_destroy() will zero out the cache, remove the cache * so it can no longer be referenced. * * See also @ref krb5_ccache_intro and @ref krb5_ccache . * * @subsection intro_krb5_error_code Kerberos errors * * Kerberos errors are based on the com_err library. All error codes are * 32-bit signed numbers, the first 24 bits define what subsystem the * error originates from, and last 8 bits are 255 error codes within the * library. Each error code have fixed string associated with it. For * example, the error-code -1765328383 have the symbolic name * KRB5KDC_ERR_NAME_EXP, and associated error string ``Client's entry in * database has expired''. * * This is a great improvement compared to just getting one of the unix * error-codes back. However, Heimdal have an extention to pass back * customised errors messages. Instead of getting ``Key table entry not * found'', the user might back ``failed to find * host/host.example.com\@EXAMLE.COM(kvno 3) in keytab /etc/krb5.keytab * (des-cbc-crc)''. This improves the chance that the user find the * cause of the error so you should use the customised error message * whenever it's available. * * See also module @ref krb5_error . * * * @subsection intro_krb5_keytab Keytab management * * A keytab is a storage for locally stored keys. Heimdal includes keytab * support for Kerberos 5 keytabs, Kerberos 4 srvtab, AFS-KeyFile's, * and for storing keys in memory. * * Keytabs are used for servers and long-running services. * * See also @ref krb5_keytab_intro and @ref krb5_keytab . * * @subsection intro_krb5_crypto Kerberos crypto * * Heimdal includes a implementation of the Kerberos crypto framework, * all crypto operations. To create a crypto context call krb5_crypto_init(). * * See also module @ref krb5_crypto . * * @section kerberos5_client Walkthrough of a sample Kerberos 5 client * * This example contains parts of a sample TCP Kerberos 5 clients, if you * want a real working client, please look in appl/test directory in * the Heimdal distribution. * * All Kerberos error-codes that are returned from kerberos functions in * this program are passed to krb5_err, that will print a * descriptive text of the error code and exit. Graphical programs can * convert error-code to a human readable error-string with the * krb5_get_error_message() function. * * Note that you should not use any Kerberos function before * krb5_init_context() have completed successfully. That is the * reason err() is used when krb5_init_context() fails. * * First the client needs to call krb5_init_context to initialise * the Kerberos 5 library. This is only needed once per thread * in the program. If the function returns a non-zero value it indicates * that either the Kerberos implementation is failing or it's disabled on * this host. * * @code * #include * * int * main(int argc, char **argv) * { * krb5_context context; * * if (krb5_init_context(&context)) * errx (1, "krb5_context"); * @endcode * * Now the client wants to connect to the host at the other end. The * preferred way of doing this is using getaddrinfo (for * operating system that have this function implemented), since getaddrinfo * is neutral to the address type and can use any protocol that is available. * * @code * struct addrinfo *ai, *a; * struct addrinfo hints; * int error; * * memset (&hints, 0, sizeof(hints)); * hints.ai_socktype = SOCK_STREAM; * hints.ai_protocol = IPPROTO_TCP; * * error = getaddrinfo (hostname, "pop3", &hints, &ai); * if (error) * errx (1, "%s: %s", hostname, gai_strerror(error)); * * for (a = ai; a != NULL; a = a->ai_next) { * int s; * * s = socket (a->ai_family, a->ai_socktype, a->ai_protocol); * if (s < 0) * continue; * if (connect (s, a->ai_addr, a->ai_addrlen) < 0) { * warn ("connect(%s)", hostname); * close (s); * continue; * } * freeaddrinfo (ai); * ai = NULL; * } * if (ai) { * freeaddrinfo (ai); * errx ("failed to contact %s", hostname); * } * @endcode * * Before authenticating, an authentication context needs to be * created. This context keeps all information for one (to be) authenticated * connection (see krb5_auth_context). * * @code * status = krb5_auth_con_init (context, &auth_context); * if (status) * krb5_err (context, 1, status, "krb5_auth_con_init"); * @endcode * * For setting the address in the authentication there is a help function * krb5_auth_con_setaddrs_from_fd() that does everything that is needed * when given a connected file descriptor to the socket. * * @code * status = krb5_auth_con_setaddrs_from_fd (context, * auth_context, * &sock); * if (status) * krb5_err (context, 1, status, * "krb5_auth_con_setaddrs_from_fd"); * @endcode * * The next step is to build a server principal for the service we want * to connect to. (See also krb5_sname_to_principal().) * * @code * status = krb5_sname_to_principal (context, * hostname, * service, * KRB5_NT_SRV_HST, * &server); * if (status) * krb5_err (context, 1, status, "krb5_sname_to_principal"); * @endcode * * The client principal is not passed to krb5_sendauth() * function, this causes the krb5_sendauth() function to try to figure it * out itself. * * The server program is using the function krb5_recvauth() to * receive the Kerberos 5 authenticator. * * In this case, mutual authentication will be tried. That means that the server * will authenticate to the client. Using mutual authentication * is required to avoid man-in-the-middle attacks, since it enables the user to * verify that they are talking to the right server (a server that knows the key). * * If you are using a non-blocking socket you will need to do all work of * krb5_sendauth() yourself. Basically you need to send over the * authenticator from krb5_mk_req() and, in case of mutual * authentication, verifying the result from the server with * krb5_rd_rep(). * * @code * status = krb5_sendauth (context, * &auth_context, * &sock, * VERSION, * NULL, * server, * AP_OPTS_MUTUAL_REQUIRED, * NULL, * NULL, * NULL, * NULL, * NULL, * NULL); * if (status) * krb5_err (context, 1, status, "krb5_sendauth"); * @endcode * * Once authentication has been performed, it is time to send some * data. First we create a krb5_data structure, then we sign it with * krb5_mk_safe() using the auth_context that contains the * session-key that was exchanged in the * krb5_sendauth()/krb5_recvauth() authentication * sequence. * * @code * data.data = "hej"; * data.length = 3; * * krb5_data_zero (&packet); * * status = krb5_mk_safe (context, * auth_context, * &data, * &packet, * NULL); * if (status) * krb5_err (context, 1, status, "krb5_mk_safe"); * @endcode * * And send it over the network. * * @code * len = packet.length; * net_len = htonl(len); * * if (krb5_net_write (context, &sock, &net_len, 4) != 4) * err (1, "krb5_net_write"); * if (krb5_net_write (context, &sock, packet.data, len) != len) * err (1, "krb5_net_write"); * @endcode * * To send encrypted (and signed) data krb5_mk_priv() should be * used instead. krb5_mk_priv() works the same way as * krb5_mk_safe(), with the exception that it encrypts the data * in addition to signing it. * * @code * data.data = "hemligt"; * data.length = 7; * * krb5_data_free (&packet); * * status = krb5_mk_priv (context, * auth_context, * &data, * &packet, * NULL); * if (status) * krb5_err (context, 1, status, "krb5_mk_priv"); * @endcode * * And send it over the network. * * @code * len = packet.length; * net_len = htonl(len); * * if (krb5_net_write (context, &sock, &net_len, 4) != 4) * err (1, "krb5_net_write"); * if (krb5_net_write (context, &sock, packet.data, len) != len) * err (1, "krb5_net_write"); * * @endcode * * The server is using krb5_rd_safe() and * krb5_rd_priv() to verify the signature and decrypt the packet. * * @section intro_krb5_verify_user Validating a password in an application * * See the manual page for krb5_verify_user(). * * @section mit_differences API differences to MIT Kerberos * * This section is somewhat disorganised, but so far there is no overall * structure to the differences, though some of the have their root in * that Heimdal uses an ASN.1 compiler and MIT doesn't. * * @subsection mit_krb5_principal Principal and realms * * Heimdal stores the realm as a krb5_realm, that is a char *. * MIT Kerberos uses a krb5_data to store a realm. * * In Heimdal krb5_principal doesn't contain the component * name_type; it's instead stored in component * name.name_type. To get and set the nametype in Heimdal, use * krb5_principal_get_type() and * krb5_principal_set_type(). * * For more information about principal and realms, see * krb5_principal. * * @subsection mit_krb5_error_code Error messages * * To get the error string, Heimdal uses * krb5_get_error_message(). This is to return custom error messages * (like ``Can't find host/datan.example.com\@CODE.COM in * /etc/krb5.conf.'' instead of a ``Key table entry not found'' that * error_message returns. * * Heimdal uses a threadsafe(r) version of the com_err interface; the * global com_err table isn't initialised. Then * error_message returns quite a boring error string (just * the error code itself). * * */ /** * * * @page krb5_fileformats File formats * * @section fileformats File formats * * This section documents the diffrent file formats that are used in * Heimdal and other Kerberos implementations. * * @subsection file_keytab keytab * * The keytab binary format is not a standard format. The format has * evolved and may continue to. It is however understood by several * Kerberos implementations including Heimdal, MIT, Sun's Java ktab and * are created by the ktpass.exe utility from Windows. So it has * established itself as the defacto format for storing Kerberos keys. * * The following C-like structure definitions illustrate the MIT keytab * file format. All values are in network byte order. All text is ASCII. * * @code * keytab { * uint16_t file_format_version; # 0x502 * keytab_entry entries[*]; * }; * * keytab_entry { * int32_t size; * uint16_t num_components; # subtract 1 if version 0x501 * counted_octet_string realm; * counted_octet_string components[num_components]; * uint32_t name_type; # not present if version 0x501 * uint32_t timestamp; * uint8_t vno8; * keyblock key; * uint32_t vno; #only present if >= 4 bytes left in entry * uint32_t flags; #only present if >= 4 bytes left in entry * }; * * counted_octet_string { * uint16_t length; * uint8_t data[length]; * }; * * keyblock { * uint16_t type; * counted_octet_string; * }; * @endcode * * All numbers are stored in network byteorder (big endian) format. * * The keytab file format begins with the 16 bit file_format_version which * at the time this document was authored is 0x502. The format of older * keytabs is described at the end of this document. * * The file_format_version is immediately followed by an array of * keytab_entry structures which are prefixed with a 32 bit size indicating * the number of bytes that follow in the entry. Note that the size should be * evaluated as signed. This is because a negative value indicates that the * entry is in fact empty (e.g. it has been deleted) and that the negative * value of that negative value (which is of course a positive value) is * the offset to the next keytab_entry. Based on these size values alone * the entire keytab file can be traversed. * * The size is followed by a 16 bit num_components field indicating the * number of counted_octet_string components in the components array. * * The num_components field is followed by a counted_octet_string * representing the realm of the principal. * * A counted_octet_string is simply an array of bytes prefixed with a 16 * bit length. For the realm and name components, the counted_octet_string * bytes are ASCII encoded text with no zero terminator. * * Following the realm is the components array that represents the name of * the principal. The text of these components may be joined with slashs * to construct the typical SPN representation. For example, the service * principal HTTP/www.foo.net\@FOO.NET would consist of name components * "HTTP" followed by "www.foo.net". * * Following the components array is the 32 bit name_type (e.g. 1 is * KRB5_NT_PRINCIPAL, 2 is KRB5_NT_SRV_INST, 5 is KRB5_NT_UID, etc). In * practice the name_type is almost certainly 1 meaning KRB5_NT_PRINCIPAL. * * The 32 bit timestamp indicates the time the key was established for that * principal. The value represents the number of seconds since Jan 1, 1970. * * The 8 bit vno8 field is the version number of the key. This value is * overridden by the 32 bit vno field if it is present. The vno8 field is * filled with the lower 8 bits of the 32 bit protocol kvno field. * * The keyblock structure consists of a 16 bit value indicating the * encryption type and is a counted_octet_string containing the key. The * encryption type is the same as the Kerberos standard (e.g. 3 is * des-cbc-md5, 23 is arcfour-hmac-md5, etc). * * The last field of the keytab_entry structure is optional. If the size of * the keytab_entry indicates that there are at least 4 bytes remaining, * a 32 bit value representing the key version number is present. This * value supersedes the 8 bit vno8 value preceeding the keyblock. * * Older keytabs with a file_format_version of 0x501 are different in * three ways: * * - All integers are in host byte order [1]. * - The num_components field is 1 too large (i.e. after decoding, decrement by 1). * - The 32 bit name_type field is not present. * * [1] The file_format_version field should really be treated as two * separate 8 bit quantities representing the major and minor version * number respectively. * * @subsection file_hdb_dump Heimdal database dump file * * Format of the Heimdal text dump file as of Heimdal 0.6.3: * * Each line in the dump file is one entry in the database. * * Each field of a line is separated by one or more spaces, with the * exception of fields consisting of principals containing spaces, where * space can be quoted with \ and \ is quoted by \. * * Fields and their types are: * * @code * Quoted princial (quote character is \) [string] * Keys [keys] * Created by [event] * Modified by [event optional] * Valid start time [time optional] * Valid end time [time optional] * Password end valid time [time optional] * Max lifetime of ticket [time optional] * Max renew time of ticket [integer optional] * Flags [hdb flags] * Generation number [generation optional] * Extensions [extentions optional] * @endcode * * Fields following these silently are ignored. * * All optional fields will be skipped if they fail to parse (or comprise * the optional field marker of "-", w/o quotes). * * Example: * * @code * fred\@CODE.COM 27:1:16:e8b4c8fc7e60b9e641dcf4cff3f08a701d982a2f89ba373733d26ca59ba6c789666f6b8bfcf169412bb1e5dceb9b33cda29f3412:-:1:3:4498a933881178c744f4232172dcd774c64e81fa6d05ecdf643a7e390624a0ebf3c7407a:-:1:2:b01934b13eb795d76f3a80717d469639b4da0cfb644161340ef44fdeb375e54d684dbb85:-:1:1:ea8e16d8078bf60c781da90f508d4deccba70595258b9d31888d33987cd31af0c9cced2e:- 20020415130120:admin\@CODE.COM 20041221112428:fred\@CODE.COM - - - 86400 604800 126 20020415130120:793707:28 - * @endcode * * Encoding of types are as follows: * * - keys * * @code * kvno:[masterkvno:keytype:keydata:salt]{zero or more separated by :} * @endcode * * kvno is the key version number. * * keydata is hex-encoded * * masterkvno is the kvno of the database master key. If this field is * empty, the kadmin load and merge operations will encrypt the key data * with the master key if there is one. Otherwise the key data will be * imported asis. * * salt is encoded as "-" (no/default salt) or * * @code * salt-type / * salt-type / "string" * salt-type / hex-encoded-data * @endcode * * keytype is the protocol enctype number; see enum ENCTYPE in * include/krb5_asn1.h for values. * * Example: * @code * 27:1:16:e8b4c8fc7e60b9e641dcf4cff3f08a701d982a2f89ba373733d26ca59ba6c789666f6b8bfcf169412bb1e5dceb9b33cda29f3412:-:1:3:4498a933881178c744f4232172dcd774c64e81fa6d05ecdf643a7e390624a0ebf3c7407a:-:1:2:b01934b13eb795d76f3a80717d469639b4da0cfb644161340ef44fdeb375e54d684dbb85:-:1:1:ea8e16d8078bf60c781da90f508d4deccba70595258b9d31888d33987cd31af0c9cced2e:- * @endcode * * * @code * kvno=27,{key: masterkvno=1,keytype=des3-cbc-sha1,keydata=..., default salt}... * @endcode * * - time * * Format of the time is: YYYYmmddHHMMSS, corresponding to strftime * format "%Y%m%d%k%M%S". * * Time is expressed in UTC. * * Time can be optional (using -), when the time 0 is used. * * Example: * * @code * 20041221112428 * @endcode * * - event * * @code * time:principal * @endcode * * time is as given in format time * * principal is a string. Not quoting it may not work in earlier * versions of Heimdal. * * Example: * @code * 20041221112428:bloggs\@CODE.COM * @endcode * * - hdb flags * * Integer encoding of HDB flags, see HDBFlags in lib/hdb/hdb.asn1. Each * bit in the integer is the same as the bit in the specification. * * - generation: * * @code * time:usec:gen * @endcode * * * usec is a the microsecond, integer. * gen is generation number, integer. * * The generation can be defaulted (using '-') or the empty string * * - extensions: * * @code * first-hex-encoded-HDB-Extension[:second-...] * @endcode * * HDB-extension is encoded the DER encoded HDB-Extension from * lib/hdb/hdb.asn1. Consumers HDB extensions should be aware that * unknown entires needs to be preserved even thought the ASN.1 data * content might be unknown. There is a critical flag in the data to show * to the KDC that the entry MUST be understod if the entry is to be * used. * * */ heimdal-7.5.0/lib/krb5/krb5_rcache.30000644000175000017500000001032412136107750015121 0ustar niknik.\" Copyright (c) 2004 Kungliga Tekniska Högskolan .\" (Royal Institute of Technology, Stockholm, Sweden). .\" All rights reserved. .\" .\" Redistribution and use in source and binary forms, with or without .\" modification, are permitted provided that the following conditions .\" are met: .\" .\" 1. Redistributions of source code must retain the above copyright .\" notice, this list of conditions and the following disclaimer. .\" .\" 2. Redistributions in binary form must reproduce the above copyright .\" notice, this list of conditions and the following disclaimer in the .\" documentation and/or other materials provided with the distribution. .\" .\" 3. Neither the name of the Institute nor the names of its contributors .\" may be used to endorse or promote products derived from this software .\" without specific prior written permission. .\" .\" THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND .\" ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE .\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE .\" ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE .\" FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL .\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS .\" OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) .\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT .\" LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF .\" SUCH DAMAGE. .\" .\" $Id$ .\" .Dd May 1, 2006 .Dt KRB5_RCACHE 3 .Os HEIMDAL .Sh NAME .Nm krb5_rcache , .Nm krb5_rc_close , .Nm krb5_rc_default , .Nm krb5_rc_default_name , .Nm krb5_rc_default_type , .Nm krb5_rc_destroy , .Nm krb5_rc_expunge , .Nm krb5_rc_get_lifespan , .Nm krb5_rc_get_name , .Nm krb5_rc_get_type , .Nm krb5_rc_initialize , .Nm krb5_rc_recover , .Nm krb5_rc_resolve , .Nm krb5_rc_resolve_full , .Nm krb5_rc_resolve_type , .Nm krb5_rc_store , .Nm krb5_get_server_rcache .Nd Kerberos 5 replay cache .Sh LIBRARY Kerberos 5 Library (libkrb5, -lkrb5) .Sh SYNOPSIS .In krb5.h .Pp .Li "struct krb5_rcache;" .Pp .Ft krb5_error_code .Fo krb5_rc_close .Fa "krb5_context context" .Fa "krb5_rcache id" .Fc .Ft krb5_error_code .Fo krb5_rc_default .Fa "krb5_context context" .Fa "krb5_rcache *id" .Fc .Ft "const char *" .Fo krb5_rc_default_name .Fa "krb5_context context" .Fc .Ft "const char *" .Fo krb5_rc_default_type .Fa "krb5_context context" .Fc .Ft krb5_error_code .Fo krb5_rc_destroy .Fa "krb5_context context" .Fa "krb5_rcache id" .Fc .Ft krb5_error_code .Fo krb5_rc_expunge .Fa "krb5_context context" .Fa "krb5_rcache id" .Fc .Ft krb5_error_code .Fo krb5_rc_get_lifespan .Fa "krb5_context context" .Fa "krb5_rcache id" .Fa "krb5_deltat *auth_lifespan" .Fc .Ft "const char*" .Fo krb5_rc_get_name .Fa "krb5_context context" .Fa "krb5_rcache id" .Fc .Ft "const char*" .Fo "krb5_rc_get_type" .Fa "krb5_context context" .Fa "krb5_rcache id" .Fc .Ft krb5_error_code .Fo krb5_rc_initialize .Fa "krb5_context context" .Fa "krb5_rcache id" .Fa "krb5_deltat auth_lifespan" .Fc .Ft krb5_error_code .Fo krb5_rc_recover .Fa "krb5_context context" .Fa "krb5_rcache id" .Fc .Ft krb5_error_code .Fo krb5_rc_resolve .Fa "krb5_context context" .Fa "krb5_rcache id" .Fa "const char *name" .Fc .Ft krb5_error_code .Fo krb5_rc_resolve_full .Fa "krb5_context context" .Fa "krb5_rcache *id" .Fa "const char *string_name" .Fc .Ft krb5_error_code .Fo krb5_rc_resolve_type .Fa "krb5_context context" .Fa "krb5_rcache *id" .Fa "const char *type" .Fc .Ft krb5_error_code .Fo krb5_rc_store .Fa "krb5_context context" .Fa "krb5_rcache id" .Fa "krb5_donot_replay *rep" .Fc .Ft krb5_error_code .Fo krb5_get_server_rcache .Fa "krb5_context context" .Fa "const krb5_data *piece" .Fa "krb5_rcache *id" .Fc .Sh DESCRIPTION The .Li krb5_rcache structure holds a storage element that is used for data manipulation. The structure contains no public accessible elements. .Pp .Fn krb5_rc_initialize Creates the reply cache .Fa id and sets it lifespan to .Fa auth_lifespan . If the cache already exists, the content is destroyed. .Sh SEE ALSO .Xr krb5 3 , .Xr krb5_data 3 , .Xr kerberos 8 heimdal-7.5.0/lib/krb5/krb_err.et0000644000175000017500000000506212136107750014650 0ustar niknik# # Error messages for the krb4 library # # This might look like a com_err file, but is not # id "$Id: krb_err.et,v 1.7 1998/03/29 14:19:52 bg Exp $" error_table krb prefix KRB4ET ec KSUCCESS, "Kerberos 4 successful" ec KDC_NAME_EXP, "Kerberos 4 principal expired" ec KDC_SERVICE_EXP, "Kerberos 4 service expired" ec KDC_AUTH_EXP, "Kerberos 4 auth expired" ec KDC_PKT_VER, "Incorrect Kerberos 4 master key version" ec KDC_P_MKEY_VER, "Incorrect Kerberos 4 master key version" ec KDC_S_MKEY_VER, "Incorrect Kerberos 4 master key version" ec KDC_BYTE_ORDER, "Kerberos 4 byte order unknown" ec KDC_PR_UNKNOWN, "Kerberos 4 principal unknown" ec KDC_PR_N_UNIQUE, "Kerberos 4 principal not unique" ec KDC_NULL_KEY, "Kerberos 4 principal has null key" index 20 ec KDC_GEN_ERR, "Generic error from KDC (Kerberos 4)" ec GC_TKFIL, "Can't read Kerberos 4 ticket file" ec GC_NOTKT, "Can't find Kerberos 4 ticket or TGT" index 26 ec MK_AP_TGTEXP, "Kerberos 4 TGT Expired" index 31 ec RD_AP_UNDEC, "Kerberos 4: Can't decode authenticator" ec RD_AP_EXP, "Kerberos 4 ticket expired" ec RD_AP_NYV, "Kerberos 4 ticket not yet valid" ec RD_AP_REPEAT, "Kerberos 4: Repeated request" ec RD_AP_NOT_US, "The Kerberos 4 ticket isn't for us" ec RD_AP_INCON, "Kerberos 4 request inconsistent" ec RD_AP_TIME, "Kerberos 4: delta_t too big" ec RD_AP_BADD, "Kerberos 4: incorrect net address" ec RD_AP_VERSION, "Kerberos protocol not version 4" ec RD_AP_MSG_TYPE, "Kerberos 4: invalid msg type" ec RD_AP_MODIFIED, "Kerberos 4: message stream modified" ec RD_AP_ORDER, "Kerberos 4: message out of order" ec RD_AP_UNAUTHOR, "Kerberos 4: unauthorized request" index 51 ec GT_PW_NULL, "Kerberos 4: current PW is null" ec GT_PW_BADPW, "Kerberos 4: Incorrect current password" ec GT_PW_PROT, "Kerberos 4 protocol error" ec GT_PW_KDCERR, "Error returned by KDC (Kerberos 4)" ec GT_PW_NULLTKT, "Null Kerberos 4 ticket returned by KDC" ec SKDC_RETRY, "Kerberos 4: Retry count exceeded" ec SKDC_CANT, "Kerberos 4: Can't send request" index 61 ec INTK_W_NOTALL, "Kerberos 4: not all tickets returned" ec INTK_BADPW, "Kerberos 4: incorrect password" ec INTK_PROT, "Kerberos 4: Protocol Error" index 70 ec INTK_ERR, "Other error in Kerberos 4" ec AD_NOTGT, "Don't have Kerberos 4 ticket-granting ticket" index 76 ec NO_TKT_FIL, "No Kerberos 4 ticket file found" ec TKT_FIL_ACC, "Couldn't access Kerberos 4 ticket file" ec TKT_FIL_LCK, "Couldn't lock Kerberos 4 ticket file" ec TKT_FIL_FMT, "Bad Kerberos 4 ticket file format" ec TKT_FIL_INI, "Kerberos 4: tf_init not called first" ec KNAME_FMT, "Bad Kerberos 4 name format" heimdal-7.5.0/lib/krb5/copy_host_realm.c0000644000175000017500000000501313026237312016214 0ustar niknik/* * Copyright (c) 1999 - 2001 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "krb5_locl.h" /** * Copy the list of realms from `from' to `to'. * * @param context Kerberos 5 context. * @param from list of realms to copy from. * @param to list of realms to copy to, free list of krb5_free_host_realm(). * * @return Returns 0 to indicate success. Otherwise an kerberos et * error code is returned, see krb5_get_error_message(). * * @ingroup krb5 */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_copy_host_realm(krb5_context context, const krb5_realm *from, krb5_realm **to) { unsigned int n, i; const krb5_realm *p; for (n = 1, p = from; *p != NULL; ++p) ++n; *to = calloc (n, sizeof(**to)); if (*to == NULL) return krb5_enomem(context); for (i = 0, p = from; *p != NULL; ++p, ++i) { (*to)[i] = strdup(*p); if ((*to)[i] == NULL) { krb5_free_host_realm (context, *to); return krb5_enomem(context); } } return 0; } heimdal-7.5.0/lib/krb5/store_fd.c0000644000175000017500000001066513212137553014646 0ustar niknik/* * Copyright (c) 1997 - 2004 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "krb5_locl.h" #include "store-int.h" typedef struct fd_storage { int fd; } fd_storage; #define FD(S) (((fd_storage*)(S)->data)->fd) static ssize_t fd_fetch(krb5_storage * sp, void *data, size_t size) { char *cbuf = (char *)data; ssize_t count; size_t rem = size; /* similar pattern to net_read() to support pipes */ while (rem > 0) { count = read (FD(sp), cbuf, rem); if (count < 0) { if (errno == EINTR) continue; else return count; } else if (count == 0) { return count; } cbuf += count; rem -= count; } return size; } static ssize_t fd_store(krb5_storage * sp, const void *data, size_t size) { const char *cbuf = (const char *)data; ssize_t count; size_t rem = size; /* similar pattern to net_write() to support pipes */ while (rem > 0) { count = write(FD(sp), cbuf, rem); if (count < 0) { if (errno == EINTR) continue; else return count; } cbuf += count; rem -= count; } return size; } static off_t fd_seek(krb5_storage * sp, off_t offset, int whence) { return lseek(FD(sp), offset, whence); } static int fd_trunc(krb5_storage * sp, off_t offset) { if (ftruncate(FD(sp), offset) == -1) return errno; return 0; } static int fd_sync(krb5_storage * sp) { if (fsync(FD(sp)) == -1) return errno; return 0; } static void fd_free(krb5_storage * sp) { int save_errno = errno; if (close(FD(sp)) == 0) errno = save_errno; } /** * * * @return A krb5_storage on success, or NULL on out of memory error. * * @ingroup krb5_storage * * @sa krb5_storage_emem() * @sa krb5_storage_from_mem() * @sa krb5_storage_from_readonly_mem() * @sa krb5_storage_from_data() * @sa krb5_storage_from_socket() */ KRB5_LIB_FUNCTION krb5_storage * KRB5_LIB_CALL krb5_storage_from_fd(int fd_in) { krb5_storage *sp; int saved_errno; int fd; #ifdef _MSC_VER /* * This function used to try to pass the input to * _get_osfhandle() to test if the value is a HANDLE * but this doesn't work because doing so throws an * exception that will result in Watson being triggered * to file a Windows Error Report. */ fd = _dup(fd_in); #else fd = dup(fd_in); #endif if (fd < 0) return NULL; errno = ENOMEM; sp = malloc(sizeof(krb5_storage)); if (sp == NULL) { saved_errno = errno; close(fd); errno = saved_errno; return NULL; } errno = ENOMEM; sp->data = malloc(sizeof(fd_storage)); if (sp->data == NULL) { saved_errno = errno; close(fd); free(sp); errno = saved_errno; return NULL; } sp->flags = 0; sp->eof_code = HEIM_ERR_EOF; FD(sp) = fd; sp->fetch = fd_fetch; sp->store = fd_store; sp->seek = fd_seek; sp->trunc = fd_trunc; sp->fsync = fd_sync; sp->free = fd_free; sp->max_alloc = UINT_MAX/8; return sp; } heimdal-7.5.0/lib/krb5/sp800-108-kdf.c0000755000175000017500000000565613026237312014767 0ustar niknik/* * Copyright (c) 2015, Secure Endpoints Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * - Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. * */ #include "krb5_locl.h" /* * SP800-108 KDF */ /** * As described in SP800-108 5.1 (for HMAC) * * @param context Kerberos 5 context * @param kdf_K1 Base key material. * @param kdf_label A string that identifies the purpose for the derived key. * @param kdf_context A binary string containing parties, nonce, etc. * @param md Message digest function to use for PRF. * @param kdf_K0 Derived key data. * * @return Return an error code for an failure or 0 on success. * @ingroup krb5_crypto */ krb5_error_code _krb5_SP800_108_HMAC_KDF(krb5_context context, const krb5_data *kdf_K1, const krb5_data *kdf_label, const krb5_data *kdf_context, const EVP_MD *md, krb5_data *kdf_K0) { HMAC_CTX c; unsigned char *p = kdf_K0->data; size_t i, n, left = kdf_K0->length; unsigned char hmac[EVP_MAX_MD_SIZE]; unsigned int h = EVP_MD_size(md); const size_t L = kdf_K0->length; heim_assert(md != NULL, "SP800-108 KDF internal error"); HMAC_CTX_init(&c); n = L / h; for (i = 0; i <= n; i++) { unsigned char tmp[4]; size_t len; HMAC_Init_ex(&c, kdf_K1->data, kdf_K1->length, md, NULL); _krb5_put_int(tmp, i + 1, 4); HMAC_Update(&c, tmp, 4); HMAC_Update(&c, kdf_label->data, kdf_label->length); HMAC_Update(&c, (unsigned char *)"", 1); if (kdf_context) HMAC_Update(&c, kdf_context->data, kdf_context->length); _krb5_put_int(tmp, L * 8, 4); HMAC_Update(&c, tmp, 4); HMAC_Final(&c, hmac, &h); len = h > left ? left : h; memcpy(p, hmac, len); p += len; left -= len; } HMAC_CTX_cleanup(&c); return 0; } heimdal-7.5.0/lib/krb5/keytab_any.c0000644000175000017500000001461413026237312015162 0ustar niknik/* * Copyright (c) 2001-2002 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "krb5_locl.h" struct any_data { krb5_keytab kt; char *name; struct any_data *next; }; static void free_list (krb5_context context, struct any_data *a) { struct any_data *next; for (; a != NULL; a = next) { next = a->next; free (a->name); if(a->kt) krb5_kt_close(context, a->kt); free (a); } } static krb5_error_code KRB5_CALLCONV any_resolve(krb5_context context, const char *name, krb5_keytab id) { struct any_data *a, *a0 = NULL, *prev = NULL; krb5_error_code ret; char buf[256]; while (strsep_copy(&name, ",", buf, sizeof(buf)) != -1) { a = calloc(1, sizeof(*a)); if (a == NULL) { ret = krb5_enomem(context); goto fail; } if (a0 == NULL) { a0 = a; a->name = strdup(buf); if (a->name == NULL) { ret = krb5_enomem(context); goto fail; } } else a->name = NULL; if (prev != NULL) prev->next = a; a->next = NULL; ret = krb5_kt_resolve (context, buf, &a->kt); if (ret) goto fail; prev = a; } if (a0 == NULL) { krb5_set_error_message(context, ENOENT, N_("empty ANY: keytab", "")); return ENOENT; } id->data = a0; return 0; fail: free_list (context, a0); return ret; } static krb5_error_code KRB5_CALLCONV any_get_name (krb5_context context, krb5_keytab id, char *name, size_t namesize) { struct any_data *a = id->data; strlcpy(name, a->name, namesize); return 0; } static krb5_error_code KRB5_CALLCONV any_close (krb5_context context, krb5_keytab id) { struct any_data *a = id->data; free_list (context, a); return 0; } struct any_cursor_extra_data { struct any_data *a; krb5_kt_cursor cursor; }; static krb5_error_code KRB5_CALLCONV any_start_seq_get(krb5_context context, krb5_keytab id, krb5_kt_cursor *c) { struct any_data *a = id->data; struct any_cursor_extra_data *ed; krb5_error_code ret; c->data = malloc (sizeof(struct any_cursor_extra_data)); if(c->data == NULL) return krb5_enomem(context); ed = (struct any_cursor_extra_data *)c->data; for (ed->a = a; ed->a != NULL; ed->a = ed->a->next) { ret = krb5_kt_start_seq_get(context, ed->a->kt, &ed->cursor); if (ret == 0) break; } if (ed->a == NULL) { free (c->data); c->data = NULL; krb5_clear_error_message (context); return KRB5_KT_END; } return 0; } static krb5_error_code KRB5_CALLCONV any_next_entry (krb5_context context, krb5_keytab id, krb5_keytab_entry *entry, krb5_kt_cursor *cursor) { krb5_error_code ret, ret2; struct any_cursor_extra_data *ed; ed = (struct any_cursor_extra_data *)cursor->data; do { ret = krb5_kt_next_entry(context, ed->a->kt, entry, &ed->cursor); if (ret == 0) return 0; else if (ret != KRB5_KT_END) return ret; ret2 = krb5_kt_end_seq_get (context, ed->a->kt, &ed->cursor); if (ret2) return ret2; while ((ed->a = ed->a->next) != NULL) { ret2 = krb5_kt_start_seq_get(context, ed->a->kt, &ed->cursor); if (ret2 == 0) break; } if (ed->a == NULL) { krb5_clear_error_message (context); return KRB5_KT_END; } } while (1); } static krb5_error_code KRB5_CALLCONV any_end_seq_get(krb5_context context, krb5_keytab id, krb5_kt_cursor *cursor) { krb5_error_code ret = 0; struct any_cursor_extra_data *ed; ed = (struct any_cursor_extra_data *)cursor->data; if (ed->a != NULL) ret = krb5_kt_end_seq_get(context, ed->a->kt, &ed->cursor); free (ed); cursor->data = NULL; return ret; } static krb5_error_code KRB5_CALLCONV any_add_entry(krb5_context context, krb5_keytab id, krb5_keytab_entry *entry) { struct any_data *a = id->data; krb5_error_code ret; while(a != NULL) { ret = krb5_kt_add_entry(context, a->kt, entry); if(ret != 0 && ret != KRB5_KT_NOWRITE) { krb5_set_error_message(context, ret, N_("failed to add entry to %s", ""), a->name); return ret; } a = a->next; } return 0; } static krb5_error_code KRB5_CALLCONV any_remove_entry(krb5_context context, krb5_keytab id, krb5_keytab_entry *entry) { struct any_data *a = id->data; krb5_error_code ret; int found = 0; while(a != NULL) { ret = krb5_kt_remove_entry(context, a->kt, entry); if(ret == 0) found++; else { if(ret != KRB5_KT_NOWRITE && ret != KRB5_KT_NOTFOUND) { krb5_set_error_message(context, ret, N_("Failed to remove keytab " "entry from %s", "keytab name"), a->name); return ret; } } a = a->next; } if(!found) return KRB5_KT_NOTFOUND; return 0; } const krb5_kt_ops krb5_any_ops = { "ANY", any_resolve, any_get_name, any_close, NULL, /* destroy */ NULL, /* get */ any_start_seq_get, any_next_entry, any_end_seq_get, any_add_entry, any_remove_entry, NULL, 0 }; heimdal-7.5.0/lib/krb5/krb5_timeofday.30000644000175000017500000000653013026237312015656 0ustar niknik.\" $Id$ .\" .\" Copyright (c) 2001, 2003, 2006 Kungliga Tekniska Högskolan .\" (Royal Institute of Technology, Stockholm, Sweden). .\" All rights reserved. .\" .\" Redistribution and use in source and binary forms, with or without .\" modification, are permitted provided that the following conditions .\" are met: .\" .\" 1. Redistributions of source code must retain the above copyright .\" notice, this list of conditions and the following disclaimer. .\" .\" 2. Redistributions in binary form must reproduce the above copyright .\" notice, this list of conditions and the following disclaimer in the .\" documentation and/or other materials provided with the distribution. .\" .\" 3. Neither the name of the Institute nor the names of its contributors .\" may be used to endorse or promote products derived from this software .\" without specific prior written permission. .\" .\" THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND .\" ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE .\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE .\" ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE .\" FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL .\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS .\" OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) .\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT .\" LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF .\" SUCH DAMAGE. .\" .\" $Id$ .\" .Dd September 16, 2006 .Dt KRB5_TIMEOFDAY 3 .Os HEIMDAL .Sh NAME .Nm krb5_timeofday , .Nm krb5_set_real_time , .Nm krb5_us_timeofday , .Nm krb5_format_time , .Nm krb5_string_to_deltat .Nd Kerberos 5 time handling functions .Sh LIBRARY Kerberos 5 Library (libkrb5, -lkrb5) .Sh SYNOPSIS .In krb5.h .Pp .Li krb5_timestamp ; .Pp .Li krb5_deltat ; .Ft krb5_error_code .Fo krb5_set_real_time .Fa "krb5_context context" .Fa "krb5_timestamp sec" .Fa "int32_t usec" .Fc .Ft krb5_error_code .Fo krb5_timeofday .Fa "krb5_context context" .Fa "krb5_timestamp *timeret" .Fc .Ft krb5_error_code .Fo krb5_us_timeofday .Fa "krb5_context context" .Fa "krb5_timestamp *sec" .Fa "int32_t *usec" .Fc .Ft krb5_error_code .Fo krb5_format_time .Fa "krb5_context context" .Fa "time_t t" .Fa "char *s" .Fa "size_t len" .Fa "krb5_boolean include_time" .Fc .Ft krb5_error_code .Fo krb5_string_to_deltat .Fa "const char *string" .Fa "krb5_deltat *deltat" .Fc .Sh DESCRIPTION .Nm krb5_set_real_time sets the absolute time that the caller knows the KDC has. With this the Kerberos library can calculate the relative difference between the KDC time and the local system time and store it in the .Fa context . With this information the Kerberos library can adjust all time stamps in Kerberos packages. .Pp .Fn krb5_timeofday returns the current time, but adjusted with the time difference between the local host and the KDC. .Fn krb5_us_timeofday also returns microseconds. .Pp .Nm krb5_format_time formats the time .Fa t into the string .Fa s of length .Fa len . If .Fa include_time is set, the time is set include_time. .Pp .Nm krb5_string_to_deltat parses delta time .Fa string into .Fa deltat . .Sh SEE ALSO .Xr gettimeofday 2 , .Xr krb5 3 heimdal-7.5.0/lib/krb5/krb5_encrypt.cat30000644000175000017500000002465413212450756016066 0ustar niknik KRB5_ENCRYPT(3) BSD Library Functions Manual KRB5_ENCRYPT(3) NNAAMMEE kkrrbb55__ccrryyppttoo__ggeettbblloocckkssiizzee, kkrrbb55__ccrryyppttoo__ggeettccoonnffoouunnddeerrssiizzee kkrrbb55__ccrryyppttoo__ggeetteennccttyyppee, kkrrbb55__ccrryyppttoo__ggeettppaaddssiizzee, kkrrbb55__ccrryyppttoo__oovveerrhheeaadd, kkrrbb55__ddeeccrryypptt, kkrrbb55__ddeeccrryypptt__EEnnccrryypptteeddDDaattaa, kkrrbb55__ddeeccrryypptt__iivveecc, kkrrbb55__ddeeccrryypptt__ttiicckkeett, kkrrbb55__eennccrryypptt, kkrrbb55__eennccrryypptt__EEnnccrryypptteeddDDaattaa, kkrrbb55__eennccrryypptt__iivveecc, kkrrbb55__eennccttyyppee__ddiissaabbllee, kkrrbb55__eennccttyyppee__kkeeyyssiizzee, kkrrbb55__eennccttyyppee__ttoo__ssttrriinngg, kkrrbb55__eennccttyyppee__vvaalliidd, kkrrbb55__ggeett__wwrraappppeedd__lleennggtthh, kkrrbb55__ssttrriinngg__ttoo__eennccttyyppee -- encrypt and decrypt data, set and get encryp- tion type parameters LLIIBBRRAARRYY Kerberos 5 Library (libkrb5, -lkrb5) SSYYNNOOPPSSIISS ##iinncclluuddee <> _k_r_b_5___e_r_r_o_r___c_o_d_e kkrrbb55__eennccrryypptt(_k_r_b_5___c_o_n_t_e_x_t _c_o_n_t_e_x_t, _k_r_b_5___c_r_y_p_t_o _c_r_y_p_t_o, _u_n_s_i_g_n_e_d _u_s_a_g_e, _v_o_i_d _*_d_a_t_a, _s_i_z_e___t _l_e_n, _k_r_b_5___d_a_t_a _*_r_e_s_u_l_t); _k_r_b_5___e_r_r_o_r___c_o_d_e kkrrbb55__eennccrryypptt__EEnnccrryypptteeddDDaattaa(_k_r_b_5___c_o_n_t_e_x_t _c_o_n_t_e_x_t, _k_r_b_5___c_r_y_p_t_o _c_r_y_p_t_o, _u_n_s_i_g_n_e_d _u_s_a_g_e, _v_o_i_d _*_d_a_t_a, _s_i_z_e___t _l_e_n, _i_n_t _k_v_n_o, _E_n_c_r_y_p_t_e_d_D_a_t_a _*_r_e_s_u_l_t); _k_r_b_5___e_r_r_o_r___c_o_d_e kkrrbb55__eennccrryypptt__iivveecc(_k_r_b_5___c_o_n_t_e_x_t _c_o_n_t_e_x_t, _k_r_b_5___c_r_y_p_t_o _c_r_y_p_t_o, _u_n_s_i_g_n_e_d _u_s_a_g_e, _v_o_i_d _*_d_a_t_a, _s_i_z_e___t _l_e_n, _k_r_b_5___d_a_t_a _*_r_e_s_u_l_t, _v_o_i_d _*_i_v_e_c); _k_r_b_5___e_r_r_o_r___c_o_d_e kkrrbb55__ddeeccrryypptt(_k_r_b_5___c_o_n_t_e_x_t _c_o_n_t_e_x_t, _k_r_b_5___c_r_y_p_t_o _c_r_y_p_t_o, _u_n_s_i_g_n_e_d _u_s_a_g_e, _v_o_i_d _*_d_a_t_a, _s_i_z_e___t _l_e_n, _k_r_b_5___d_a_t_a _*_r_e_s_u_l_t); _k_r_b_5___e_r_r_o_r___c_o_d_e kkrrbb55__ddeeccrryypptt__EEnnccrryypptteeddDDaattaa(_k_r_b_5___c_o_n_t_e_x_t _c_o_n_t_e_x_t, _k_r_b_5___c_r_y_p_t_o _c_r_y_p_t_o, _u_n_s_i_g_n_e_d _u_s_a_g_e, _E_n_c_r_y_p_t_e_d_D_a_t_a _*_e, _k_r_b_5___d_a_t_a _*_r_e_s_u_l_t); _k_r_b_5___e_r_r_o_r___c_o_d_e kkrrbb55__ddeeccrryypptt__iivveecc(_k_r_b_5___c_o_n_t_e_x_t _c_o_n_t_e_x_t, _k_r_b_5___c_r_y_p_t_o _c_r_y_p_t_o, _u_n_s_i_g_n_e_d _u_s_a_g_e, _v_o_i_d _*_d_a_t_a, _s_i_z_e___t _l_e_n, _k_r_b_5___d_a_t_a _*_r_e_s_u_l_t, _v_o_i_d _*_i_v_e_c); _k_r_b_5___e_r_r_o_r___c_o_d_e kkrrbb55__ddeeccrryypptt__ttiicckkeett(_k_r_b_5___c_o_n_t_e_x_t _c_o_n_t_e_x_t, _T_i_c_k_e_t _*_t_i_c_k_e_t, _k_r_b_5___k_e_y_b_l_o_c_k _*_k_e_y, _E_n_c_T_i_c_k_e_t_P_a_r_t _*_o_u_t, _k_r_b_5___f_l_a_g_s _f_l_a_g_s); _k_r_b_5___e_r_r_o_r___c_o_d_e kkrrbb55__ccrryyppttoo__ggeettbblloocckkssiizzee(_k_r_b_5___c_o_n_t_e_x_t _c_o_n_t_e_x_t, _s_i_z_e___t _*_b_l_o_c_k_s_i_z_e); _k_r_b_5___e_r_r_o_r___c_o_d_e kkrrbb55__ccrryyppttoo__ggeetteennccttyyppee(_k_r_b_5___c_o_n_t_e_x_t _c_o_n_t_e_x_t, _k_r_b_5___c_r_y_p_t_o _c_r_y_p_t_o, _k_r_b_5___e_n_c_t_y_p_e _*_e_n_c_t_y_p_e); _k_r_b_5___e_r_r_o_r___c_o_d_e kkrrbb55__ccrryyppttoo__ggeettppaaddssiizzee(_k_r_b_5___c_o_n_t_e_x_t _c_o_n_t_e_x_t, _s_i_z_e___t, _*_p_a_d_s_i_z_e_"); _k_r_b_5___e_r_r_o_r___c_o_d_e kkrrbb55__ccrryyppttoo__ggeettccoonnffoouunnddeerrssiizzee(_k_r_b_5___c_o_n_t_e_x_t _c_o_n_t_e_x_t, _k_r_b_5___c_r_y_p_t_o _c_r_y_p_t_o, _s_i_z_e___t, _*_c_o_n_f_o_u_n_d_e_r_s_i_z_e_"); _k_r_b_5___e_r_r_o_r___c_o_d_e kkrrbb55__eennccttyyppee__kkeeyyssiizzee(_k_r_b_5___c_o_n_t_e_x_t _c_o_n_t_e_x_t, _k_r_b_5___e_n_c_t_y_p_e _t_y_p_e, _s_i_z_e___t _*_k_e_y_s_i_z_e); _k_r_b_5___e_r_r_o_r___c_o_d_e kkrrbb55__ccrryyppttoo__oovveerrhheeaadd(_k_r_b_5___c_o_n_t_e_x_t _c_o_n_t_e_x_t, _s_i_z_e___t, _*_p_a_d_s_i_z_e_"); _k_r_b_5___e_r_r_o_r___c_o_d_e kkrrbb55__ssttrriinngg__ttoo__eennccttyyppee(_k_r_b_5___c_o_n_t_e_x_t _c_o_n_t_e_x_t, _c_o_n_s_t _c_h_a_r _*_s_t_r_i_n_g, _k_r_b_5___e_n_c_t_y_p_e _*_e_t_y_p_e); _k_r_b_5___e_r_r_o_r___c_o_d_e kkrrbb55__eennccttyyppee__ttoo__ssttrriinngg(_k_r_b_5___c_o_n_t_e_x_t _c_o_n_t_e_x_t, _k_r_b_5___e_n_c_t_y_p_e _e_t_y_p_e, _c_h_a_r _*_*_s_t_r_i_n_g); _k_r_b_5___e_r_r_o_r___c_o_d_e kkrrbb55__eennccttyyppee__vvaalliidd(_k_r_b_5___c_o_n_t_e_x_t _c_o_n_t_e_x_t, _k_r_b_5___e_n_c_t_y_p_e _e_t_y_p_e); _v_o_i_d kkrrbb55__eennccttyyppee__ddiissaabbllee(_k_r_b_5___c_o_n_t_e_x_t _c_o_n_t_e_x_t, _k_r_b_5___e_n_c_t_y_p_e _e_t_y_p_e); _s_i_z_e___t kkrrbb55__ggeett__wwrraappppeedd__lleennggtthh(_k_r_b_5___c_o_n_t_e_x_t _c_o_n_t_e_x_t, _k_r_b_5___c_r_y_p_t_o _c_r_y_p_t_o, _s_i_z_e___t _d_a_t_a___l_e_n); DDEESSCCRRIIPPTTIIOONN These functions are used to encrypt and decrypt data. kkrrbb55__eennccrryypptt__iivveecc() puts the encrypted version of _d_a_t_a (of size _l_e_n) in _r_e_s_u_l_t. If the encryption type supports using derived keys, _u_s_a_g_e should be the appropriate key-usage. _i_v_e_c is a pointer to a initial IV, it is modified to the end IV at the end of the round. Ivec should be the size of If NULL is passed in, the default IV is used. kkrrbb55__eennccrryypptt() does the same as kkrrbb55__eennccrryypptt__iivveecc() but with _i_v_e_c being NULL. kkrrbb55__eennccrryypptt__EEnnccrryypptteeddDDaattaa() does the same as kkrrbb55__eennccrryypptt(), but it puts the encrypted data in a _E_n_c_r_y_p_t_e_d_D_a_t_a structure instead. If _k_v_n_o is not zero, it will be put in the (optional) _k_v_n_o field in the _E_n_c_r_y_p_t_e_d_D_a_t_a. kkrrbb55__ddeeccrryypptt__iivveecc(), kkrrbb55__ddeeccrryypptt(), and kkrrbb55__ddeeccrryypptt__EEnnccrryypptteeddDDaattaa() works similarly. kkrrbb55__ddeeccrryypptt__ttiicckkeett() decrypts the encrypted part of _t_i_c_k_e_t with _k_e_y. kkrrbb55__ddeeccrryypptt__ttiicckkeett() also verifies the timestamp in the ticket, invalid flag and if the KDC haven't verified the transited path, the transit path. kkrrbb55__eennccttyyppee__kkeeyyssiizzee(), kkrrbb55__ccrryyppttoo__ggeettccoonnffoouunnddeerrssiizzee(), kkrrbb55__ccrryyppttoo__ggeettbblloocckkssiizzee(), kkrrbb55__ccrryyppttoo__ggeetteennccttyyppee(), kkrrbb55__ccrryyppttoo__ggeettppaaddssiizzee(), kkrrbb55__ccrryyppttoo__oovveerrhheeaadd() all returns various (sometimes) useful information from a crypto context. kkrrbb55__ccrryyppttoo__oovveerrhheeaadd() is the combination of krb5_crypto_getconfounder- size, krb5_crypto_getblocksize and krb5_crypto_getpadsize and return the maximum overhead size. kkrrbb55__eennccttyyppee__ttoo__ssttrriinngg() converts a encryption type number to a string that can be printable and stored. The strings returned should be freed with free(3). kkrrbb55__ssttrriinngg__ttoo__eennccttyyppee() converts a encryption type strings to a encryp- tion type number that can use used for other Kerberos crypto functions. kkrrbb55__eennccttyyppee__vvaalliidd() returns 0 if the encrypt is supported and not dis- abled, otherwise and error code is returned. kkrrbb55__eennccttyyppee__ddiissaabbllee() (globally, for all contextes) disables the _e_n_c_t_y_p_e. kkrrbb55__ggeett__wwrraappppeedd__lleennggtthh() returns the size of an encrypted packet by _c_r_y_p_t_o of length _d_a_t_a___l_e_n. SSEEEE AALLSSOO krb5_create_checksum(3), krb5_crypto_init(3) HEIMDAL March 20, 2004 HEIMDAL heimdal-7.5.0/lib/krb5/krb5_c_make_checksum.30000644000175000017500000001565213026237312017003 0ustar niknik.\" Copyright (c) 2003 - 2006 Kungliga Tekniska Högskolan .\" (Royal Institute of Technology, Stockholm, Sweden). .\" All rights reserved. .\" .\" Redistribution and use in source and binary forms, with or without .\" modification, are permitted provided that the following conditions .\" are met: .\" .\" 1. Redistributions of source code must retain the above copyright .\" notice, this list of conditions and the following disclaimer. .\" .\" 2. Redistributions in binary form must reproduce the above copyright .\" notice, this list of conditions and the following disclaimer in the .\" documentation and/or other materials provided with the distribution. .\" .\" 3. Neither the name of the Institute nor the names of its contributors .\" may be used to endorse or promote products derived from this software .\" without specific prior written permission. .\" .\" THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND .\" ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE .\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE .\" ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE .\" FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL .\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS .\" OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) .\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT .\" LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF .\" SUCH DAMAGE. .\" .\" $Id$ .\" .Dd Nov 17, 2006 .Dt KRB5_C_MAKE_CHECKSUM 3 .Os HEIMDAL .Sh NAME .Nm krb5_c_block_size , .Nm krb5_c_decrypt , .Nm krb5_c_encrypt , .Nm krb5_c_encrypt_length , .Nm krb5_c_enctype_compare , .Nm krb5_c_get_checksum , .Nm krb5_c_is_coll_proof_cksum , .Nm krb5_c_is_keyed_cksum , .Nm krb5_c_keylength , .Nm krb5_c_make_checksum , .Nm krb5_c_make_random_key , .Nm krb5_c_set_checksum , .Nm krb5_c_valid_cksumtype , .Nm krb5_c_valid_enctype , .Nm krb5_c_verify_checksum , .Nm krb5_c_checksum_length .Nd Kerberos 5 crypto API .Sh LIBRARY Kerberos 5 Library (libkrb5, -lkrb5) .Sh SYNOPSIS .In krb5.h .Pp .Ft krb5_error_code .Fo krb5_c_block_size .Fa "krb5_context context" .Fa "krb5_enctype enctype" .Fa "size_t *blocksize" .Fc .Ft krb5_error_code .Fo krb5_c_decrypt .Fa "krb5_context context" .Fa "const krb5_keyblock key" .Fa "krb5_keyusage usage" .Fa "const krb5_data *ivec" .Fa "krb5_enc_data *input" .Fa "krb5_data *output" .Fc .Ft krb5_error_code .Fo krb5_c_encrypt .Fa "krb5_context context" .Fa "const krb5_keyblock *key" .Fa "krb5_keyusage usage" .Fa "const krb5_data *ivec" .Fa "const krb5_data *input" .Fa "krb5_enc_data *output" .Fc .Ft krb5_error_code .Fo krb5_c_encrypt_length .Fa "krb5_context context" .Fa "krb5_enctype enctype" .Fa "size_t inputlen" .Fa "size_t *length" .Fc .Ft krb5_error_code .Fo krb5_c_enctype_compare .Fa "krb5_context context" .Fa "krb5_enctype e1" .Fa "krb5_enctype e2" .Fa "krb5_boolean *similar" .Fc .Ft krb5_error_code .Fo krb5_c_make_random_key .Fa "krb5_context context" .Fa "krb5_enctype enctype" .Fa "krb5_keyblock *random_key" .Fc .Ft krb5_error_code .Fo krb5_c_make_checksum .Fa "krb5_context context" .Fa "krb5_cksumtype cksumtype" .Fa "const krb5_keyblock *key" .Fa "krb5_keyusage usage" .Fa "const krb5_data *input" .Fa "krb5_checksum *cksum" .Fc .Ft krb5_error_code .Fo krb5_c_verify_checksum .Fa "krb5_context context" .Fa "const krb5_keyblock *key" .Fa "krb5_keyusage usage" .Fa "const krb5_data *data" .Fa "const krb5_checksum *cksum" .Fa "krb5_boolean *valid" .Fc .Ft krb5_error_code .Fo krb5_c_checksum_length .Fa "krb5_context context" .Fa "krb5_cksumtype cksumtype" .Fa "size_t *length" .Fc .Ft krb5_error_code .Fo krb5_c_get_checksum .Fa "krb5_context context" .Fa "const krb5_checksum *cksum" .Fa "krb5_cksumtype *type" .Fa "krb5_data **data" .Fc .Ft krb5_error_code .Fo krb5_c_set_checksum .Fa "krb5_context context" .Fa "krb5_checksum *cksum" .Fa "krb5_cksumtype type" .Fa "const krb5_data *data" .Fc .Ft krb5_boolean .Fo krb5_c_valid_enctype .Fa krb5_enctype etype" .Fc .Ft krb5_boolean .Fo krb5_c_valid_cksumtype .Fa "krb5_cksumtype ctype" .Fc .Ft krb5_boolean .Fo krb5_c_is_coll_proof_cksum .Fa "krb5_cksumtype ctype" .Fc .Ft krb5_boolean .Fo krb5_c_is_keyed_cksum .Fa "krb5_cksumtype ctype" .Fc .Ft krb5_error_code .Fo krb5_c_keylengths .Fa "krb5_context context" .Fa "krb5_enctype enctype" .Fa "size_t *inlength" .Fa "size_t *keylength" .Fc .Sh DESCRIPTION The functions starting with krb5_c are compat functions with MIT kerberos. .Pp The .Li krb5_enc_data structure holds and encrypted data. There are two public accessible members of .Li krb5_enc_data . .Li enctype that holds the encryption type of the data encrypted and .Li ciphertext that is a .Ft krb5_data that might contain the encrypted data. .Pp .Fn krb5_c_block_size returns the blocksize of the encryption type. .Pp .Fn krb5_c_decrypt decrypts .Fa input and store the data in .Fa output. If .Fa ivec is .Dv NULL the default initialization vector for that encryption type will be used. .Pp .Fn krb5_c_encrypt encrypts the plaintext in .Fa input and store the ciphertext in .Fa output . .Pp .Fn krb5_c_encrypt_length returns the length the encrypted data given the plaintext length. .Pp .Fn krb5_c_enctype_compare compares to encryption types and returns if they use compatible encryption key types. .Pp .Fn krb5_c_make_checksum creates a checksum .Fa cksum with the checksum type .Fa cksumtype of the data in .Fa data . .Fa key and .Fa usage are used if the checksum is a keyed checksum type. Returns 0 or an error code. .Pp .Fn krb5_c_verify_checksum verifies the checksum of .Fa data in .Fa cksum that was created with .Fa key using the key usage .Fa usage . .Fa verify is set to non-zero if the checksum verifies correctly and zero if not. Returns 0 or an error code. .Pp .Fn krb5_c_checksum_length returns the length of the checksum. .Pp .Fn krb5_c_set_checksum sets the .Li krb5_checksum structure given .Fa type and .Fa data . The content of .Fa cksum should be freeed with .Fn krb5_c_free_checksum_contents . .Pp .Fn krb5_c_get_checksum retrieves the components of the .Li krb5_checksum . structure. .Fa data should be free with .Fn krb5_free_data . If some either of .Fa data or .Fa checksum is not needed for the application, .Dv NULL can be passed in. .Pp .Fn krb5_c_valid_enctype returns true if .Fa etype is a valid encryption type. .Pp .Fn krb5_c_valid_cksumtype returns true if .Fa ctype is a valid checksum type. .Pp .Fn krb5_c_is_keyed_cksum return true if .Fa ctype is a keyed checksum type. .Pp .Fn krb5_c_is_coll_proof_cksum returns true if .Fa ctype is a collision proof checksum type. .Pp .Fn krb5_c_keylengths return the minimum length .Fa ( inlength ) bytes needed to create a key and the length .Fa ( keylength ) of the resulting key for the .Fa enctype . .Sh SEE ALSO .Xr krb5 3 , .Xr krb5_create_checksum 3 , .Xr krb5_free_data 3 , .Xr kerberos 8 heimdal-7.5.0/lib/krb5/build_ap_req.c0000644000175000017500000000542413212137553015464 0ustar niknik/* * Copyright (c) 1997 - 2002 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "krb5_locl.h" KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_build_ap_req (krb5_context context, krb5_enctype enctype, krb5_creds *cred, krb5_flags ap_options, krb5_data authenticator, krb5_data *retdata) { krb5_error_code ret = 0; AP_REQ ap; Ticket t; size_t len; ap.pvno = 5; ap.msg_type = krb_ap_req; memset(&ap.ap_options, 0, sizeof(ap.ap_options)); ap.ap_options.use_session_key = (ap_options & AP_OPTS_USE_SESSION_KEY) > 0; ap.ap_options.mutual_required = (ap_options & AP_OPTS_MUTUAL_REQUIRED) > 0; ap.ticket.tkt_vno = 5; copy_Realm(&cred->server->realm, &ap.ticket.realm); copy_PrincipalName(&cred->server->name, &ap.ticket.sname); decode_Ticket(cred->ticket.data, cred->ticket.length, &t, &len); copy_EncryptedData(&t.enc_part, &ap.ticket.enc_part); free_Ticket(&t); ap.authenticator.etype = enctype; ap.authenticator.kvno = NULL; ap.authenticator.cipher = authenticator; ASN1_MALLOC_ENCODE(AP_REQ, retdata->data, retdata->length, &ap, &len, ret); if(ret == 0 && retdata->length != len) krb5_abortx(context, "internal error in ASN.1 encoder"); free_AP_REQ(&ap); return ret; } heimdal-7.5.0/lib/krb5/rd_cred.c0000644000175000017500000002250613212137553014440 0ustar niknik/* * Copyright (c) 1997 - 2007 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "krb5_locl.h" static krb5_error_code compare_addrs(krb5_context context, krb5_address *a, krb5_address *b, const char *message) { char a_str[64], b_str[64]; size_t len; if(krb5_address_compare (context, a, b)) return 0; krb5_print_address (a, a_str, sizeof(a_str), &len); krb5_print_address (b, b_str, sizeof(b_str), &len); krb5_set_error_message(context, KRB5KRB_AP_ERR_BADADDR, "%s: %s != %s", message, b_str, a_str); return KRB5KRB_AP_ERR_BADADDR; } KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_rd_cred(krb5_context context, krb5_auth_context auth_context, krb5_data *in_data, krb5_creds ***ret_creds, krb5_replay_data *outdata) { krb5_error_code ret; size_t len; KRB_CRED cred; EncKrbCredPart enc_krb_cred_part; krb5_data enc_krb_cred_part_data; krb5_crypto crypto; size_t i; memset(&enc_krb_cred_part, 0, sizeof(enc_krb_cred_part)); krb5_data_zero(&enc_krb_cred_part_data); if ((auth_context->flags & (KRB5_AUTH_CONTEXT_RET_TIME | KRB5_AUTH_CONTEXT_RET_SEQUENCE)) && outdata == NULL) return KRB5_RC_REQUIRED; /* XXX better error, MIT returns this */ *ret_creds = NULL; ret = decode_KRB_CRED(in_data->data, in_data->length, &cred, &len); if(ret) { krb5_clear_error_message(context); return ret; } if (cred.pvno != 5) { ret = KRB5KRB_AP_ERR_BADVERSION; krb5_clear_error_message (context); goto out; } if (cred.msg_type != krb_cred) { ret = KRB5KRB_AP_ERR_MSG_TYPE; krb5_clear_error_message (context); goto out; } if (cred.enc_part.etype == (krb5_enctype)ETYPE_NULL) { /* DK: MIT GSS-API Compatibility */ enc_krb_cred_part_data.length = cred.enc_part.cipher.length; enc_krb_cred_part_data.data = cred.enc_part.cipher.data; } else { /* Try both subkey and session key. * * RFC4120 claims we should use the session key, but Heimdal * before 0.8 used the remote subkey if it was send in the * auth_context. */ if (auth_context->remote_subkey) { ret = krb5_crypto_init(context, auth_context->remote_subkey, 0, &crypto); if (ret) goto out; ret = krb5_decrypt_EncryptedData(context, crypto, KRB5_KU_KRB_CRED, &cred.enc_part, &enc_krb_cred_part_data); krb5_crypto_destroy(context, crypto); } /* * If there was not subkey, or we failed using subkey, * retry using the session key */ if (auth_context->remote_subkey == NULL || ret == KRB5KRB_AP_ERR_BAD_INTEGRITY) { ret = krb5_crypto_init(context, auth_context->keyblock, 0, &crypto); if (ret) goto out; ret = krb5_decrypt_EncryptedData(context, crypto, KRB5_KU_KRB_CRED, &cred.enc_part, &enc_krb_cred_part_data); krb5_crypto_destroy(context, crypto); } if (ret) goto out; } ret = decode_EncKrbCredPart(enc_krb_cred_part_data.data, enc_krb_cred_part_data.length, &enc_krb_cred_part, &len); if (enc_krb_cred_part_data.data != cred.enc_part.cipher.data) krb5_data_free(&enc_krb_cred_part_data); if (ret) { krb5_set_error_message(context, ret, N_("Failed to decode " "encrypte credential part", "")); goto out; } /* check sender address */ if (enc_krb_cred_part.s_address && auth_context->remote_address && auth_context->remote_port) { krb5_address *a; ret = krb5_make_addrport (context, &a, auth_context->remote_address, auth_context->remote_port); if (ret) goto out; ret = compare_addrs(context, a, enc_krb_cred_part.s_address, N_("sender address is wrong " "in received creds", "")); krb5_free_address(context, a); free(a); if(ret) goto out; } /* check receiver address */ if (enc_krb_cred_part.r_address && auth_context->local_address) { if(auth_context->local_port && enc_krb_cred_part.r_address->addr_type == KRB5_ADDRESS_ADDRPORT) { krb5_address *a; ret = krb5_make_addrport (context, &a, auth_context->local_address, auth_context->local_port); if (ret) goto out; ret = compare_addrs(context, a, enc_krb_cred_part.r_address, N_("receiver address is wrong " "in received creds", "")); krb5_free_address(context, a); free(a); if(ret) goto out; } else { ret = compare_addrs(context, auth_context->local_address, enc_krb_cred_part.r_address, N_("receiver address is wrong " "in received creds", "")); if(ret) goto out; } } /* check timestamp */ if (auth_context->flags & KRB5_AUTH_CONTEXT_DO_TIME) { krb5_timestamp sec; krb5_timeofday (context, &sec); if (enc_krb_cred_part.timestamp == NULL || enc_krb_cred_part.usec == NULL || labs(*enc_krb_cred_part.timestamp - sec) > context->max_skew) { krb5_clear_error_message (context); ret = KRB5KRB_AP_ERR_SKEW; goto out; } } if ((auth_context->flags & (KRB5_AUTH_CONTEXT_RET_TIME | KRB5_AUTH_CONTEXT_RET_SEQUENCE))) { /* if these fields are not present in the cred-part, silently return zero */ memset(outdata, 0, sizeof(*outdata)); if(enc_krb_cred_part.timestamp) outdata->timestamp = *enc_krb_cred_part.timestamp; if(enc_krb_cred_part.usec) outdata->usec = *enc_krb_cred_part.usec; if(enc_krb_cred_part.nonce) outdata->seq = *enc_krb_cred_part.nonce; } /* Convert to NULL terminated list of creds */ *ret_creds = calloc(enc_krb_cred_part.ticket_info.len + 1, sizeof(**ret_creds)); if (*ret_creds == NULL) { ret = krb5_enomem(context); goto out; } for (i = 0; i < enc_krb_cred_part.ticket_info.len; ++i) { KrbCredInfo *kci = &enc_krb_cred_part.ticket_info.val[i]; krb5_creds *creds; creds = calloc(1, sizeof(*creds)); if(creds == NULL) { ret = krb5_enomem(context); goto out; } ASN1_MALLOC_ENCODE(Ticket, creds->ticket.data, creds->ticket.length, &cred.tickets.val[i], &len, ret); if (ret) { free(creds); goto out; } if(creds->ticket.length != len) krb5_abortx(context, "internal error in ASN.1 encoder"); copy_EncryptionKey (&kci->key, &creds->session); if (kci->prealm && kci->pname) _krb5_principalname2krb5_principal (context, &creds->client, *kci->pname, *kci->prealm); if (kci->flags) creds->flags.b = *kci->flags; if (kci->authtime) creds->times.authtime = *kci->authtime; if (kci->starttime) creds->times.starttime = *kci->starttime; if (kci->endtime) creds->times.endtime = *kci->endtime; if (kci->renew_till) creds->times.renew_till = *kci->renew_till; if (kci->srealm && kci->sname) _krb5_principalname2krb5_principal (context, &creds->server, *kci->sname, *kci->srealm); if (kci->caddr) krb5_copy_addresses (context, kci->caddr, &creds->addresses); (*ret_creds)[i] = creds; } (*ret_creds)[i] = NULL; free_KRB_CRED (&cred); free_EncKrbCredPart(&enc_krb_cred_part); return 0; out: free_EncKrbCredPart(&enc_krb_cred_part); free_KRB_CRED (&cred); if(*ret_creds) { for(i = 0; (*ret_creds)[i]; i++) krb5_free_creds(context, (*ret_creds)[i]); free(*ret_creds); *ret_creds = NULL; } return ret; } KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_rd_cred2 (krb5_context context, krb5_auth_context auth_context, krb5_ccache ccache, krb5_data *in_data) { krb5_error_code ret; krb5_creds **creds; int i; ret = krb5_rd_cred(context, auth_context, in_data, &creds, NULL); if(ret) return ret; /* Store the creds in the ccache */ for(i = 0; creds && creds[i]; i++) { krb5_cc_store_cred(context, ccache, creds[i]); krb5_free_creds(context, creds[i]); } free(creds); return 0; } heimdal-7.5.0/lib/krb5/krb5_mk_safe.cat30000644000175000017500000000410113212450757015771 0ustar niknik KRB5_MK_SAFE(3) BSD Library Functions Manual KRB5_MK_SAFE(3) NNAAMMEE kkrrbb55__mmkk__ssaaffee, kkrrbb55__mmkk__pprriivv -- generates integrity protected and/or encrypted messages LLIIBBRRAARRYY Kerberos 5 Library (libkrb5, -lkrb5) SSYYNNOOPPSSIISS ##iinncclluuddee <> _k_r_b_5___e_r_r_o_r___c_o_d_e kkrrbb55__mmkk__pprriivv(_k_r_b_5___c_o_n_t_e_x_t _c_o_n_t_e_x_t, _k_r_b_5___a_u_t_h___c_o_n_t_e_x_t _a_u_t_h___c_o_n_t_e_x_t, _c_o_n_s_t _k_r_b_5___d_a_t_a _*_u_s_e_r_d_a_t_a, _k_r_b_5___d_a_t_a _*_o_u_t_b_u_f, _k_r_b_5___r_e_p_l_a_y___d_a_t_a _*_o_u_t_d_a_t_a); _k_r_b_5___e_r_r_o_r___c_o_d_e kkrrbb55__mmkk__ssaaffee(_k_r_b_5___c_o_n_t_e_x_t _c_o_n_t_e_x_t, _k_r_b_5___a_u_t_h___c_o_n_t_e_x_t _a_u_t_h___c_o_n_t_e_x_t, _c_o_n_s_t _k_r_b_5___d_a_t_a _*_u_s_e_r_d_a_t_a, _k_r_b_5___d_a_t_a _*_o_u_t_b_u_f, _k_r_b_5___r_e_p_l_a_y___d_a_t_a _*_o_u_t_d_a_t_a); DDEESSCCRRIIPPTTIIOONN kkrrbb55__mmkk__ssaaffee() and kkrrbb55__mmkk__pprriivv() formats KRB-SAFE (integrity protected) and KRB-PRIV (also encrypted) messages into _o_u_t_b_u_f. The actual message data is taken from _u_s_e_r_d_a_t_a. If the KRB5_AUTH_CONTEXT_DO_SEQUENCE or KRB5_AUTH_CONTEXT_DO_TIME flags are set in the _a_u_t_h___c_o_n_t_e_x_t, sequence numbers and time stamps are generated. If the KRB5_AUTH_CONTEXT_RET_SEQUENCE or KRB5_AUTH_CONTEXT_RET_TIME flags are set they are also returned in the _o_u_t_d_a_t_a parameter. SSEEEE AALLSSOO krb5_auth_con_init(3), krb5_rd_priv(3), krb5_rd_safe(3) HEIMDAL May 1, 2006 HEIMDAL heimdal-7.5.0/lib/krb5/test_pknistkdf.c0000644000175000017500000003012013026237312016056 0ustar niknik/* * Copyright (c) 2008 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of KTH nor the names of its contributors may be * used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY KTH AND ITS CONTRIBUTORS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL KTH OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "krb5_locl.h" #include #include #include #include static int verbose_flag = 0; struct testcase { const heim_oid *oid; krb5_data Z; const char *client; const char *server; krb5_enctype enctype; krb5_data as_req; krb5_data pk_as_rep; krb5_data ticket; krb5_data key; } tests[] = { /* 0 */ { NULL, /* AlgorithmIdentifier */ { /* Z */ 256, "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" }, "lha@SU.SE", /* client, partyUInfo */ "krbtgt/SU.SE@SU.SE", /* server, partyVInfo */ ETYPE_AES256_CTS_HMAC_SHA1_96, /* enctype */ { /* as_req */ 10, "\xAA\xAA\xAA\xAA\xAA\xAA\xAA\xAA\xAA\xAA" }, { /* pk_as_rep */ 9, "\xBB\xBB\xBB\xBB\xBB\xBB\xBB\xBB\xBB" }, { /* ticket */ 55, "\x61\x35\x30\x33\xa0\x03\x02\x01\x05\xa1\x07\x1b\x05\x53\x55\x2e" "\x53\x45\xa2\x10\x30\x0e\xa0\x03\x02\x01\x01\xa1\x07\x30\x05\x1b" "\x03\x6c\x68\x61\xa3\x11\x30\x0f\xa0\x03\x02\x01\x12\xa2\x08\x04" "\x06\x68\x65\x6a\x68\x65\x6a" }, { /* key */ 32, "\xc7\x62\x89\xec\x4b\x28\xa6\x91\xff\xce\x80\xbb\xb7\xec\x82\x41" "\x52\x3f\x99\xb1\x90\xcf\x2d\x34\x8f\x54\xa8\x65\x81\x2c\x32\x73" } }, /* 1 */ { NULL, /* AlgorithmIdentifier */ { /* Z */ 256, "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" }, "lha@SU.SE", /* client, partyUInfo */ "krbtgt/SU.SE@SU.SE", /* server, partyVInfo */ ETYPE_AES256_CTS_HMAC_SHA1_96, /* enctype */ { /* as_req */ 10, "\xAA\xAA\xAA\xAA\xAA\xAA\xAA\xAA\xAA\xAA" }, { /* pk_as_rep */ 9, "\xBB\xBB\xBB\xBB\xBB\xBB\xBB\xBB\xBB" }, { /* ticket */ 55, "\x61\x35\x30\x33\xa0\x03\x02\x01\x05\xa1\x07\x1b\x05\x53\x55\x2e" "\x53\x45\xa2\x10\x30\x0e\xa0\x03\x02\x01\x01\xa1\x07\x30\x05\x1b" "\x03\x6c\x68\x61\xa3\x11\x30\x0f\xa0\x03\x02\x01\x12\xa2\x08\x04" "\x06\x68\x65\x6a\x68\x65\x6a" }, { /* key */ 32, "\x59\xf3\xca\x77\x5b\x20\x17\xe9\xad\x36\x3f\x47\xca\xbd\x43\xb8" "\x8c\xb8\x90\x35\x8d\xc6\x0d\x52\x0d\x11\x9f\xb0\xdc\x24\x0b\x61" } }, /* 2 */ { NULL, /* AlgorithmIdentifier */ { /* Z */ 256, "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" }, "lha@SU.SE", /* client, partyUInfo */ "krbtgt/SU.SE@SU.SE", /* server, partyVInfo */ ETYPE_AES256_CTS_HMAC_SHA1_96, /* enctype */ { /* as_req */ 10, "\xAA\xAA\xAA\xAA\xAA\xAA\xAA\xAA\xAA\xAA" }, { /* pk_as_rep */ 9, "\xBB\xBB\xBB\xBB\xBB\xBB\xBB\xBB\xBB" }, { /* ticket */ 55, "\x61\x35\x30\x33\xa0\x03\x02\x01\x05\xa1\x07\x1b\x05\x53\x55\x2e" "\x53\x45\xa2\x10\x30\x0e\xa0\x03\x02\x01\x01\xa1\x07\x30\x05\x1b" "\x03\x6c\x68\x61\xa3\x11\x30\x0f\xa0\x03\x02\x01\x12\xa2\x08\x04" "\x06\x68\x65\x6a\x68\x65\x6a" }, { /* key */ 32, "\x8a\x9a\xc5\x5f\x45\xda\x1a\x73\xd9\x1e\xe9\x88\x1f\xa9\x48\x81" "\xce\xac\x66\x2d\xb1\xd3\xb9\x0a\x9d\x0e\x52\x83\xdf\xe1\x84\x3d" } } }; #ifdef MAKETICKET static void fooTicket(void) { krb5_error_code ret; krb5_data data; size_t size; Ticket t; t.tkt_vno = 5; t.realm = "SU.SE"; t.sname.name_type = KRB5_NT_PRINCIPAL; t.sname.name_string.len = 1; t.sname.name_string.val = ecalloc(1, sizeof(t.sname.name_string.val[0])); t.sname.name_string.val[0] = estrdup("lha"); t.enc_part.etype = ETYPE_AES256_CTS_HMAC_SHA1_96; t.enc_part.kvno = NULL; t.enc_part.cipher.length = 6; t.enc_part.cipher.data = "hejhej"; ASN1_MALLOC_ENCODE(Ticket, data.data, data.length, &t, &size, ret); if (ret) errx(1, "ASN1_MALLOC_ENCODE(Ticket)"); rk_dumpdata("foo", data.data, data.length); free(data.data); } #endif static void test_dh2key(krb5_context context, int i, struct testcase *c) { krb5_error_code ret; krb5_keyblock key; krb5_principal client, server; Ticket ticket; AlgorithmIdentifier ai; size_t size; memset(&ticket, 0, sizeof(ticket)); ai.algorithm = *c->oid; ai.parameters = NULL; ret = decode_Ticket(c->ticket.data, c->ticket.length, &ticket, &size); if (ret) krb5_errx(context, 1, "decode ticket: %d", ret); ret = krb5_parse_name(context, c->client, &client); if (ret) krb5_err(context, 1, ret, "parse_name: %s", c->client); ret = krb5_parse_name(context, c->server, &server); if (ret) krb5_err(context, 1, ret, "parse_name: %s", c->server); /* * Making krb5_build_principal*() set a reasonable default principal * name type broke the test vectors here. Rather than regenerate * the vectors, and to prove that this was the issue, we coerce the * name types back to their original. */ krb5_principal_set_type(context, client, KRB5_NT_PRINCIPAL); krb5_principal_set_type(context, server, KRB5_NT_PRINCIPAL); if (verbose_flag) { char *str; hex_encode(c->Z.data, c->Z.length, &str); printf("Z: %s\n", str); free(str); printf("client: %s\n", c->client); printf("server: %s\n", c->server); printf("enctype: %d\n", (int)c->enctype); hex_encode(c->as_req.data, c->as_req.length, &str); printf("as-req: %s\n", str); free(str); hex_encode(c->pk_as_rep.data, c->pk_as_rep.length, &str); printf("pk-as-rep: %s\n", str); free(str); hex_encode(c->ticket.data, c->ticket.length, &str); printf("ticket: %s\n", str); free(str); } ret = _krb5_pk_kdf(context, &ai, c->Z.data, c->Z.length, client, server, c->enctype, &c->as_req, &c->pk_as_rep, &ticket, &key); krb5_free_principal(context, client); krb5_free_principal(context, server); if (ret) krb5_err(context, 1, ret, "_krb5_pk_kdf: %d", i); if (verbose_flag) { char *str; hex_encode(key.keyvalue.data, key.keyvalue.length, &str); printf("key: %s\n", str); free(str); } if (key.keyvalue.length != c->key.length || memcmp(key.keyvalue.data, c->key.data, c->key.length) != 0) krb5_errx(context, 1, "resulting key wrong: %d", i); krb5_free_keyblock_contents(context, &key); free_Ticket(&ticket); } static int version_flag = 0; static int help_flag = 0; static struct getargs args[] = { {"verbose", 0, arg_flag, &verbose_flag, "verbose output", NULL }, {"version", 0, arg_flag, &version_flag, "print version", NULL }, {"help", 0, arg_flag, &help_flag, NULL, NULL } }; static void usage (int ret) { arg_printusage (args, sizeof(args)/sizeof(*args), NULL, ""); exit (ret); } int main(int argc, char **argv) { krb5_context context; krb5_error_code ret; int i, optidx = 0; setprogname(argv[0]); if(getarg(args, sizeof(args) / sizeof(args[0]), argc, argv, &optidx)) usage(1); if (help_flag) usage (0); if(version_flag){ print_version(NULL); exit(0); } argc -= optidx; argv += optidx; #ifdef MAKETICKET fooTicket(); #endif ret = krb5_init_context(&context); if (ret) errx (1, "krb5_init_context failed: %d", ret); tests[0].oid = &asn1_oid_id_pkinit_kdf_ah_sha1; tests[1].oid = &asn1_oid_id_pkinit_kdf_ah_sha256; tests[2].oid = &asn1_oid_id_pkinit_kdf_ah_sha512; for (i = 0; i < sizeof(tests)/sizeof(tests[0]); i++) test_dh2key(context, i, &tests[i]); krb5_free_context(context); return 0; } heimdal-7.5.0/lib/krb5/krb5_generate_random_block.cat30000644000175000017500000000155613212450756020702 0ustar niknik KRB5_GENERATE_RANDOM_... BSD Library Functions Manual KRB5_GENERATE_RANDOM_... NNAAMMEE kkrrbb55__ggeenneerraattee__rraannddoomm__bblloocckk -- Kerberos 5 random functions LLIIBBRRAARRYY Kerberos 5 Library (libkrb5, -lkrb5) SSYYNNOOPPSSIISS ##iinncclluuddee <> _v_o_i_d kkrrbb55__ggeenneerraattee__rraannddoomm__bblloocckk(_v_o_i_d _*_b_u_f, _s_i_z_e___t _l_e_n); DDEESSCCRRIIPPTTIIOONN kkrrbb55__ggeenneerraattee__rraannddoomm__bblloocckk() generates a cryptographically strong pseudo- random block into the buffer _b_u_f of length _l_e_n. SSEEEE AALLSSOO krb5(3), krb5.conf(5) HEIMDAL March 21, 2004 HEIMDAL heimdal-7.5.0/lib/krb5/Makefile.in0000644000175000017500000105554413212444522014745 0ustar niknik# Makefile.in generated by automake 1.15.1 from Makefile.am. # @configure_input@ # Copyright (C) 1994-2017 Free Software Foundation, Inc. # This Makefile.in is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, # with or without modifications, as long as this notice is preserved. # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY, to the extent permitted by law; without # even the implied warranty of MERCHANTABILITY or FITNESS FOR A # PARTICULAR PURPOSE. @SET_MAKE@ # $Id$ # $Id$ # $Id$ VPATH = @srcdir@ am__is_gnu_make = { \ if test -z '$(MAKELEVEL)'; then \ false; \ elif test -n '$(MAKE_HOST)'; then \ true; \ elif test -n '$(MAKE_VERSION)' && test -n '$(CURDIR)'; then \ true; \ else \ false; \ fi; \ } am__make_running_with_option = \ case $${target_option-} in \ ?) ;; \ *) echo "am__make_running_with_option: internal error: invalid" \ "target option '$${target_option-}' specified" >&2; \ exit 1;; \ esac; \ has_opt=no; \ sane_makeflags=$$MAKEFLAGS; \ if $(am__is_gnu_make); then \ sane_makeflags=$$MFLAGS; \ else \ case $$MAKEFLAGS in \ *\\[\ \ ]*) \ bs=\\; \ sane_makeflags=`printf '%s\n' "$$MAKEFLAGS" \ | sed "s/$$bs$$bs[$$bs $$bs ]*//g"`;; \ esac; \ fi; \ skip_next=no; \ strip_trailopt () \ { \ flg=`printf '%s\n' "$$flg" | sed "s/$$1.*$$//"`; \ }; \ for flg in $$sane_makeflags; do \ test $$skip_next = yes && { skip_next=no; continue; }; \ case $$flg in \ *=*|--*) continue;; \ -*I) strip_trailopt 'I'; skip_next=yes;; \ -*I?*) strip_trailopt 'I';; \ -*O) strip_trailopt 'O'; skip_next=yes;; \ -*O?*) strip_trailopt 'O';; \ -*l) strip_trailopt 'l'; skip_next=yes;; \ -*l?*) strip_trailopt 'l';; \ -[dEDm]) skip_next=yes;; \ -[JT]) skip_next=yes;; \ esac; \ case $$flg in \ *$$target_option*) has_opt=yes; break;; \ esac; \ done; \ test $$has_opt = yes am__make_dryrun = (target_option=n; $(am__make_running_with_option)) am__make_keepgoing = (target_option=k; $(am__make_running_with_option)) pkgdatadir = $(datadir)/@PACKAGE@ pkgincludedir = $(includedir)/@PACKAGE@ pkglibdir = $(libdir)/@PACKAGE@ pkglibexecdir = $(libexecdir)/@PACKAGE@ am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd install_sh_DATA = $(install_sh) -c -m 644 install_sh_PROGRAM = $(install_sh) -c install_sh_SCRIPT = $(install_sh) -c INSTALL_HEADER = $(INSTALL_DATA) transform = $(program_transform_name) NORMAL_INSTALL = : PRE_INSTALL = : POST_INSTALL = : NORMAL_UNINSTALL = : PRE_UNINSTALL = : POST_UNINSTALL = : build_triplet = @build@ host_triplet = @host@ bin_PROGRAMS = verify_krb5_conf$(EXEEXT) noinst_PROGRAMS = krbhst-test$(EXEEXT) test_alname$(EXEEXT) \ test_crypto$(EXEEXT) test_forward$(EXEEXT) \ test_get_addrs$(EXEEXT) test_gic$(EXEEXT) \ test_kuserok$(EXEEXT) test_renew$(EXEEXT) \ test_rfc3961$(EXEEXT) TESTS = aes-test$(EXEEXT) derived-key-test$(EXEEXT) \ n-fold-test$(EXEEXT) parse-name-test$(EXEEXT) \ pseudo-random-test$(EXEEXT) store-test$(EXEEXT) \ string-to-key-test$(EXEEXT) test_acl$(EXEEXT) \ test_addr$(EXEEXT) test_cc$(EXEEXT) test_config$(EXEEXT) \ test_fx$(EXEEXT) test_prf$(EXEEXT) test_store$(EXEEXT) \ test_crypto_wrapping$(EXEEXT) test_keytab$(EXEEXT) \ test_mem$(EXEEXT) test_pac$(EXEEXT) test_plugin$(EXEEXT) \ test_princ$(EXEEXT) test_pkinit_dh2key$(EXEEXT) \ test_pknistkdf$(EXEEXT) test_time$(EXEEXT) \ test_expand_toks$(EXEEXT) test_x500$(EXEEXT) check_PROGRAMS = $(am__EXEEXT_1) test_hostname$(EXEEXT) \ test_ap-req$(EXEEXT) test_canon$(EXEEXT) \ test_set_kvno0$(EXEEXT) @versionscript_TRUE@am__append_1 = $(LDFLAGS_VERSION_SCRIPT)$(srcdir)/version-script.map subdir = lib/krb5 ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 am__aclocal_m4_deps = $(top_srcdir)/cf/aix.m4 \ $(top_srcdir)/cf/auth-modules.m4 \ $(top_srcdir)/cf/broken-getaddrinfo.m4 \ $(top_srcdir)/cf/broken-glob.m4 \ $(top_srcdir)/cf/broken-realloc.m4 \ $(top_srcdir)/cf/broken-snprintf.m4 $(top_srcdir)/cf/broken.m4 \ $(top_srcdir)/cf/broken2.m4 $(top_srcdir)/cf/c-attribute.m4 \ $(top_srcdir)/cf/capabilities.m4 \ $(top_srcdir)/cf/check-compile-et.m4 \ $(top_srcdir)/cf/check-getpwnam_r-posix.m4 \ $(top_srcdir)/cf/check-man.m4 \ $(top_srcdir)/cf/check-netinet-ip-and-tcp.m4 \ $(top_srcdir)/cf/check-type-extra.m4 \ $(top_srcdir)/cf/check-var.m4 $(top_srcdir)/cf/crypto.m4 \ $(top_srcdir)/cf/db.m4 $(top_srcdir)/cf/destdirs.m4 \ $(top_srcdir)/cf/dispatch.m4 $(top_srcdir)/cf/dlopen.m4 \ $(top_srcdir)/cf/find-func-no-libs.m4 \ $(top_srcdir)/cf/find-func-no-libs2.m4 \ $(top_srcdir)/cf/find-func.m4 \ $(top_srcdir)/cf/find-if-not-broken.m4 \ $(top_srcdir)/cf/framework-security.m4 \ $(top_srcdir)/cf/have-struct-field.m4 \ $(top_srcdir)/cf/have-type.m4 $(top_srcdir)/cf/irix.m4 \ $(top_srcdir)/cf/krb-bigendian.m4 \ $(top_srcdir)/cf/krb-func-getlogin.m4 \ $(top_srcdir)/cf/krb-ipv6.m4 $(top_srcdir)/cf/krb-prog-ln-s.m4 \ $(top_srcdir)/cf/krb-prog-perl.m4 \ $(top_srcdir)/cf/krb-readline.m4 \ $(top_srcdir)/cf/krb-struct-spwd.m4 \ $(top_srcdir)/cf/krb-struct-winsize.m4 \ $(top_srcdir)/cf/largefile.m4 $(top_srcdir)/cf/libtool.m4 \ $(top_srcdir)/cf/ltoptions.m4 $(top_srcdir)/cf/ltsugar.m4 \ $(top_srcdir)/cf/ltversion.m4 $(top_srcdir)/cf/lt~obsolete.m4 \ $(top_srcdir)/cf/mips-abi.m4 $(top_srcdir)/cf/misc.m4 \ $(top_srcdir)/cf/need-proto.m4 $(top_srcdir)/cf/osfc2.m4 \ $(top_srcdir)/cf/otp.m4 $(top_srcdir)/cf/pkg.m4 \ $(top_srcdir)/cf/proto-compat.m4 $(top_srcdir)/cf/pthreads.m4 \ $(top_srcdir)/cf/resolv.m4 $(top_srcdir)/cf/retsigtype.m4 \ $(top_srcdir)/cf/roken-frag.m4 \ $(top_srcdir)/cf/socket-wrapper.m4 $(top_srcdir)/cf/sunos.m4 \ $(top_srcdir)/cf/telnet.m4 $(top_srcdir)/cf/test-package.m4 \ $(top_srcdir)/cf/version-script.m4 $(top_srcdir)/cf/wflags.m4 \ $(top_srcdir)/cf/win32.m4 $(top_srcdir)/cf/with-all.m4 \ $(top_srcdir)/acinclude.m4 $(top_srcdir)/configure.ac am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \ $(ACLOCAL_M4) DIST_COMMON = $(srcdir)/Makefile.am $(dist_include_HEADERS) \ $(krb5_HEADERS) $(noinst_HEADERS) $(am__DIST_COMMON) mkinstalldirs = $(install_sh) -d CONFIG_HEADER = $(top_builddir)/include/config.h CONFIG_CLEAN_FILES = CONFIG_CLEAN_VPATH_FILES = am__vpath_adj_setup = srcdirstrip=`echo "$(srcdir)" | sed 's|.|.|g'`; am__vpath_adj = case $$p in \ $(srcdir)/*) f=`echo "$$p" | sed "s|^$$srcdirstrip/||"`;; \ *) f=$$p;; \ esac; am__strip_dir = f=`echo $$p | sed -e 's|^.*/||'`; am__install_max = 40 am__nobase_strip_setup = \ srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*|]/\\\\&/g'` am__nobase_strip = \ for p in $$list; do echo "$$p"; done | sed -e "s|$$srcdirstrip/||" am__nobase_list = $(am__nobase_strip_setup); \ for p in $$list; do echo "$$p $$p"; done | \ sed "s| $$srcdirstrip/| |;"' / .*\//!s/ .*/ ./; s,\( .*\)/[^/]*$$,\1,' | \ $(AWK) 'BEGIN { files["."] = "" } { files[$$2] = files[$$2] " " $$1; \ if (++n[$$2] == $(am__install_max)) \ { print $$2, files[$$2]; n[$$2] = 0; files[$$2] = "" } } \ END { for (dir in files) print dir, files[dir] }' am__base_list = \ sed '$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;s/\n/ /g' | \ sed '$$!N;$$!N;$$!N;$$!N;s/\n/ /g' am__uninstall_files_from_dir = { \ test -z "$$files" \ || { test ! -d "$$dir" && test ! -f "$$dir" && test ! -r "$$dir"; } \ || { echo " ( cd '$$dir' && rm -f" $$files ")"; \ $(am__cd) "$$dir" && rm -f $$files; }; \ } am__installdirs = "$(DESTDIR)$(libdir)" "$(DESTDIR)$(bindir)" \ "$(DESTDIR)$(man3dir)" "$(DESTDIR)$(man5dir)" \ "$(DESTDIR)$(man7dir)" "$(DESTDIR)$(man8dir)" \ "$(DESTDIR)$(includedir)" "$(DESTDIR)$(krb5dir)" \ "$(DESTDIR)$(includedir)" LTLIBRARIES = $(lib_LTLIBRARIES) $(noinst_LTLIBRARIES) am__DEPENDENCIES_1 = @have_scc_TRUE@am__DEPENDENCIES_2 = $(am__DEPENDENCIES_1) dist_libkrb5_la_OBJECTS = libkrb5_la-acache.lo libkrb5_la-acl.lo \ libkrb5_la-add_et_list.lo libkrb5_la-addr_families.lo \ libkrb5_la-aname_to_localname.lo libkrb5_la-appdefault.lo \ libkrb5_la-asn1_glue.lo libkrb5_la-auth_context.lo \ libkrb5_la-build_ap_req.lo libkrb5_la-build_auth.lo \ libkrb5_la-cache.lo libkrb5_la-changepw.lo libkrb5_la-codec.lo \ libkrb5_la-config_file.lo libkrb5_la-convert_creds.lo \ libkrb5_la-constants.lo libkrb5_la-context.lo \ libkrb5_la-copy_host_realm.lo libkrb5_la-crc.lo \ libkrb5_la-creds.lo libkrb5_la-crypto.lo \ libkrb5_la-crypto-aes-sha1.lo libkrb5_la-crypto-aes-sha2.lo \ libkrb5_la-crypto-algs.lo libkrb5_la-crypto-arcfour.lo \ libkrb5_la-crypto-des.lo libkrb5_la-crypto-des-common.lo \ libkrb5_la-crypto-des3.lo libkrb5_la-crypto-evp.lo \ libkrb5_la-crypto-null.lo libkrb5_la-crypto-pk.lo \ libkrb5_la-crypto-rand.lo libkrb5_la-doxygen.lo \ libkrb5_la-data.lo libkrb5_la-db_plugin.lo \ libkrb5_la-dcache.lo libkrb5_la-deprecated.lo \ libkrb5_la-digest.lo libkrb5_la-eai_to_heim_errno.lo \ libkrb5_la-enomem.lo libkrb5_la-error_string.lo \ libkrb5_la-expand_hostname.lo libkrb5_la-expand_path.lo \ libkrb5_la-fast.lo libkrb5_la-fcache.lo libkrb5_la-free.lo \ libkrb5_la-free_host_realm.lo \ libkrb5_la-generate_seq_number.lo \ libkrb5_la-generate_subkey.lo libkrb5_la-get_addrs.lo \ libkrb5_la-get_cred.lo libkrb5_la-get_default_principal.lo \ libkrb5_la-get_default_realm.lo libkrb5_la-get_for_creds.lo \ libkrb5_la-get_host_realm.lo libkrb5_la-get_in_tkt.lo \ libkrb5_la-get_port.lo libkrb5_la-init_creds.lo \ libkrb5_la-init_creds_pw.lo libkrb5_la-kcm.lo \ libkrb5_la-keyblock.lo libkrb5_la-keytab.lo \ libkrb5_la-keytab_any.lo libkrb5_la-keytab_file.lo \ libkrb5_la-keytab_keyfile.lo libkrb5_la-keytab_memory.lo \ libkrb5_la-krbhst.lo libkrb5_la-kuserok.lo libkrb5_la-log.lo \ libkrb5_la-mcache.lo libkrb5_la-misc.lo libkrb5_la-mk_error.lo \ libkrb5_la-mk_priv.lo libkrb5_la-mk_rep.lo \ libkrb5_la-mk_req.lo libkrb5_la-mk_req_ext.lo \ libkrb5_la-mk_safe.lo libkrb5_la-mit_glue.lo \ libkrb5_la-net_read.lo libkrb5_la-net_write.lo \ libkrb5_la-n-fold.lo libkrb5_la-pac.lo libkrb5_la-padata.lo \ libkrb5_la-pcache.lo libkrb5_la-pkinit.lo \ libkrb5_la-pkinit-ec.lo libkrb5_la-principal.lo \ libkrb5_la-prog_setup.lo libkrb5_la-prompter_posix.lo \ libkrb5_la-rd_cred.lo libkrb5_la-rd_error.lo \ libkrb5_la-rd_priv.lo libkrb5_la-rd_rep.lo \ libkrb5_la-rd_req.lo libkrb5_la-rd_safe.lo \ libkrb5_la-read_message.lo libkrb5_la-recvauth.lo \ libkrb5_la-replay.lo libkrb5_la-salt.lo \ libkrb5_la-salt-aes-sha1.lo libkrb5_la-salt-aes-sha2.lo \ libkrb5_la-salt-arcfour.lo libkrb5_la-salt-des.lo \ libkrb5_la-salt-des3.lo libkrb5_la-sp800-108-kdf.lo \ libkrb5_la-scache.lo libkrb5_la-send_to_kdc.lo \ libkrb5_la-sendauth.lo libkrb5_la-set_default_realm.lo \ libkrb5_la-sock_principal.lo libkrb5_la-store.lo \ libkrb5_la-store-int.lo libkrb5_la-store_emem.lo \ libkrb5_la-store_fd.lo libkrb5_la-store_mem.lo \ libkrb5_la-store_sock.lo libkrb5_la-plugin.lo \ libkrb5_la-ticket.lo libkrb5_la-time.lo \ libkrb5_la-transited.lo libkrb5_la-verify_init.lo \ libkrb5_la-verify_user.lo libkrb5_la-version.lo \ libkrb5_la-warn.lo libkrb5_la-write_message.lo am__objects_1 = libkrb5_la-krb5_err.lo libkrb5_la-krb_err.lo \ libkrb5_la-heim_err.lo libkrb5_la-k524_err.lo nodist_libkrb5_la_OBJECTS = $(am__objects_1) libkrb5_la_OBJECTS = $(dist_libkrb5_la_OBJECTS) \ $(nodist_libkrb5_la_OBJECTS) AM_V_lt = $(am__v_lt_@AM_V@) am__v_lt_ = $(am__v_lt_@AM_DEFAULT_V@) am__v_lt_0 = --silent am__v_lt_1 = libkrb5_la_LINK = $(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) \ $(LIBTOOLFLAGS) --mode=link $(CCLD) $(AM_CFLAGS) $(CFLAGS) \ $(libkrb5_la_LDFLAGS) $(LDFLAGS) -o $@ librfc3961_la_DEPENDENCIES = $(top_builddir)/lib/asn1/libasn1.la \ $(top_builddir)/lib/ipc/libheim-ipcc.la \ $(top_builddir)/lib/wind/libwind.la $(LIB_pkinit) \ $(am__DEPENDENCIES_2) $(am__DEPENDENCIES_1) \ $(am__DEPENDENCIES_1) $(am__DEPENDENCIES_1) \ $(am__DEPENDENCIES_1) $(am__DEPENDENCIES_1) \ $(am__DEPENDENCIES_1) $(am__DEPENDENCIES_1) am_librfc3961_la_OBJECTS = librfc3961_la-crc.lo \ librfc3961_la-crypto.lo librfc3961_la-crypto-aes-sha1.lo \ librfc3961_la-crypto-aes-sha2.lo librfc3961_la-crypto-algs.lo \ librfc3961_la-crypto-arcfour.lo librfc3961_la-crypto-des.lo \ librfc3961_la-crypto-des-common.lo \ librfc3961_la-crypto-des3.lo librfc3961_la-crypto-evp.lo \ librfc3961_la-crypto-null.lo librfc3961_la-crypto-pk.lo \ librfc3961_la-crypto-rand.lo librfc3961_la-crypto-stubs.lo \ librfc3961_la-data.lo librfc3961_la-enomem.lo \ librfc3961_la-error_string.lo librfc3961_la-keyblock.lo \ librfc3961_la-n-fold.lo librfc3961_la-salt.lo \ librfc3961_la-salt-aes-sha1.lo librfc3961_la-salt-aes-sha2.lo \ librfc3961_la-salt-arcfour.lo librfc3961_la-salt-des.lo \ librfc3961_la-salt-des3.lo librfc3961_la-sp800-108-kdf.lo \ librfc3961_la-store-int.lo librfc3961_la-warn.lo librfc3961_la_OBJECTS = $(am_librfc3961_la_OBJECTS) am__EXEEXT_1 = aes-test$(EXEEXT) derived-key-test$(EXEEXT) \ n-fold-test$(EXEEXT) parse-name-test$(EXEEXT) \ pseudo-random-test$(EXEEXT) store-test$(EXEEXT) \ string-to-key-test$(EXEEXT) test_acl$(EXEEXT) \ test_addr$(EXEEXT) test_cc$(EXEEXT) test_config$(EXEEXT) \ test_fx$(EXEEXT) test_prf$(EXEEXT) test_store$(EXEEXT) \ test_crypto_wrapping$(EXEEXT) test_keytab$(EXEEXT) \ test_mem$(EXEEXT) test_pac$(EXEEXT) test_plugin$(EXEEXT) \ test_princ$(EXEEXT) test_pkinit_dh2key$(EXEEXT) \ test_pknistkdf$(EXEEXT) test_time$(EXEEXT) \ test_expand_toks$(EXEEXT) test_x500$(EXEEXT) PROGRAMS = $(bin_PROGRAMS) $(noinst_PROGRAMS) aes_test_SOURCES = aes-test.c aes_test_OBJECTS = aes-test.$(OBJEXT) aes_test_LDADD = $(LDADD) aes_test_DEPENDENCIES = libkrb5.la $(am__DEPENDENCIES_1) \ $(top_builddir)/lib/asn1/libasn1.la \ $(top_builddir)/lib/wind/libwind.la $(LIB_heimbase) \ $(am__DEPENDENCIES_1) derived_key_test_SOURCES = derived-key-test.c derived_key_test_OBJECTS = derived-key-test.$(OBJEXT) derived_key_test_LDADD = $(LDADD) derived_key_test_DEPENDENCIES = libkrb5.la $(am__DEPENDENCIES_1) \ $(top_builddir)/lib/asn1/libasn1.la \ $(top_builddir)/lib/wind/libwind.la $(LIB_heimbase) \ $(am__DEPENDENCIES_1) krbhst_test_SOURCES = krbhst-test.c krbhst_test_OBJECTS = krbhst-test.$(OBJEXT) krbhst_test_LDADD = $(LDADD) krbhst_test_DEPENDENCIES = libkrb5.la $(am__DEPENDENCIES_1) \ $(top_builddir)/lib/asn1/libasn1.la \ $(top_builddir)/lib/wind/libwind.la $(LIB_heimbase) \ $(am__DEPENDENCIES_1) n_fold_test_SOURCES = n-fold-test.c n_fold_test_OBJECTS = n-fold-test.$(OBJEXT) n_fold_test_LDADD = $(LDADD) n_fold_test_DEPENDENCIES = libkrb5.la $(am__DEPENDENCIES_1) \ $(top_builddir)/lib/asn1/libasn1.la \ $(top_builddir)/lib/wind/libwind.la $(LIB_heimbase) \ $(am__DEPENDENCIES_1) parse_name_test_SOURCES = parse-name-test.c parse_name_test_OBJECTS = parse-name-test.$(OBJEXT) parse_name_test_LDADD = $(LDADD) parse_name_test_DEPENDENCIES = libkrb5.la $(am__DEPENDENCIES_1) \ $(top_builddir)/lib/asn1/libasn1.la \ $(top_builddir)/lib/wind/libwind.la $(LIB_heimbase) \ $(am__DEPENDENCIES_1) pseudo_random_test_SOURCES = pseudo-random-test.c pseudo_random_test_OBJECTS = pseudo-random-test.$(OBJEXT) pseudo_random_test_LDADD = $(LDADD) pseudo_random_test_DEPENDENCIES = libkrb5.la $(am__DEPENDENCIES_1) \ $(top_builddir)/lib/asn1/libasn1.la \ $(top_builddir)/lib/wind/libwind.la $(LIB_heimbase) \ $(am__DEPENDENCIES_1) store_test_SOURCES = store-test.c store_test_OBJECTS = store-test.$(OBJEXT) store_test_LDADD = $(LDADD) store_test_DEPENDENCIES = libkrb5.la $(am__DEPENDENCIES_1) \ $(top_builddir)/lib/asn1/libasn1.la \ $(top_builddir)/lib/wind/libwind.la $(LIB_heimbase) \ $(am__DEPENDENCIES_1) string_to_key_test_SOURCES = string-to-key-test.c string_to_key_test_OBJECTS = string-to-key-test.$(OBJEXT) string_to_key_test_LDADD = $(LDADD) string_to_key_test_DEPENDENCIES = libkrb5.la $(am__DEPENDENCIES_1) \ $(top_builddir)/lib/asn1/libasn1.la \ $(top_builddir)/lib/wind/libwind.la $(LIB_heimbase) \ $(am__DEPENDENCIES_1) test_acl_SOURCES = test_acl.c test_acl_OBJECTS = test_acl.$(OBJEXT) test_acl_LDADD = $(LDADD) test_acl_DEPENDENCIES = libkrb5.la $(am__DEPENDENCIES_1) \ $(top_builddir)/lib/asn1/libasn1.la \ $(top_builddir)/lib/wind/libwind.la $(LIB_heimbase) \ $(am__DEPENDENCIES_1) test_addr_SOURCES = test_addr.c test_addr_OBJECTS = test_addr.$(OBJEXT) test_addr_LDADD = $(LDADD) test_addr_DEPENDENCIES = libkrb5.la $(am__DEPENDENCIES_1) \ $(top_builddir)/lib/asn1/libasn1.la \ $(top_builddir)/lib/wind/libwind.la $(LIB_heimbase) \ $(am__DEPENDENCIES_1) test_alname_SOURCES = test_alname.c test_alname_OBJECTS = test_alname.$(OBJEXT) test_alname_LDADD = $(LDADD) test_alname_DEPENDENCIES = libkrb5.la $(am__DEPENDENCIES_1) \ $(top_builddir)/lib/asn1/libasn1.la \ $(top_builddir)/lib/wind/libwind.la $(LIB_heimbase) \ $(am__DEPENDENCIES_1) test_ap_req_SOURCES = test_ap-req.c test_ap_req_OBJECTS = test_ap-req.$(OBJEXT) test_ap_req_LDADD = $(LDADD) test_ap_req_DEPENDENCIES = libkrb5.la $(am__DEPENDENCIES_1) \ $(top_builddir)/lib/asn1/libasn1.la \ $(top_builddir)/lib/wind/libwind.la $(LIB_heimbase) \ $(am__DEPENDENCIES_1) test_canon_SOURCES = test_canon.c test_canon_OBJECTS = test_canon.$(OBJEXT) test_canon_LDADD = $(LDADD) test_canon_DEPENDENCIES = libkrb5.la $(am__DEPENDENCIES_1) \ $(top_builddir)/lib/asn1/libasn1.la \ $(top_builddir)/lib/wind/libwind.la $(LIB_heimbase) \ $(am__DEPENDENCIES_1) test_cc_SOURCES = test_cc.c test_cc_OBJECTS = test_cc.$(OBJEXT) test_cc_LDADD = $(LDADD) test_cc_DEPENDENCIES = libkrb5.la $(am__DEPENDENCIES_1) \ $(top_builddir)/lib/asn1/libasn1.la \ $(top_builddir)/lib/wind/libwind.la $(LIB_heimbase) \ $(am__DEPENDENCIES_1) test_config_SOURCES = test_config.c test_config_OBJECTS = test_config.$(OBJEXT) test_config_LDADD = $(LDADD) test_config_DEPENDENCIES = libkrb5.la $(am__DEPENDENCIES_1) \ $(top_builddir)/lib/asn1/libasn1.la \ $(top_builddir)/lib/wind/libwind.la $(LIB_heimbase) \ $(am__DEPENDENCIES_1) test_crypto_SOURCES = test_crypto.c test_crypto_OBJECTS = test_crypto.$(OBJEXT) test_crypto_LDADD = $(LDADD) test_crypto_DEPENDENCIES = libkrb5.la $(am__DEPENDENCIES_1) \ $(top_builddir)/lib/asn1/libasn1.la \ $(top_builddir)/lib/wind/libwind.la $(LIB_heimbase) \ $(am__DEPENDENCIES_1) test_crypto_wrapping_SOURCES = test_crypto_wrapping.c test_crypto_wrapping_OBJECTS = test_crypto_wrapping.$(OBJEXT) test_crypto_wrapping_LDADD = $(LDADD) test_crypto_wrapping_DEPENDENCIES = libkrb5.la $(am__DEPENDENCIES_1) \ $(top_builddir)/lib/asn1/libasn1.la \ $(top_builddir)/lib/wind/libwind.la $(LIB_heimbase) \ $(am__DEPENDENCIES_1) test_expand_toks_SOURCES = test_expand_toks.c test_expand_toks_OBJECTS = test_expand_toks.$(OBJEXT) test_expand_toks_LDADD = $(LDADD) test_expand_toks_DEPENDENCIES = libkrb5.la $(am__DEPENDENCIES_1) \ $(top_builddir)/lib/asn1/libasn1.la \ $(top_builddir)/lib/wind/libwind.la $(LIB_heimbase) \ $(am__DEPENDENCIES_1) test_forward_SOURCES = test_forward.c test_forward_OBJECTS = test_forward.$(OBJEXT) test_forward_LDADD = $(LDADD) test_forward_DEPENDENCIES = libkrb5.la $(am__DEPENDENCIES_1) \ $(top_builddir)/lib/asn1/libasn1.la \ $(top_builddir)/lib/wind/libwind.la $(LIB_heimbase) \ $(am__DEPENDENCIES_1) test_fx_SOURCES = test_fx.c test_fx_OBJECTS = test_fx.$(OBJEXT) test_fx_LDADD = $(LDADD) test_fx_DEPENDENCIES = libkrb5.la $(am__DEPENDENCIES_1) \ $(top_builddir)/lib/asn1/libasn1.la \ $(top_builddir)/lib/wind/libwind.la $(LIB_heimbase) \ $(am__DEPENDENCIES_1) test_get_addrs_SOURCES = test_get_addrs.c test_get_addrs_OBJECTS = test_get_addrs.$(OBJEXT) test_get_addrs_LDADD = $(LDADD) test_get_addrs_DEPENDENCIES = libkrb5.la $(am__DEPENDENCIES_1) \ $(top_builddir)/lib/asn1/libasn1.la \ $(top_builddir)/lib/wind/libwind.la $(LIB_heimbase) \ $(am__DEPENDENCIES_1) test_gic_SOURCES = test_gic.c test_gic_OBJECTS = test_gic.$(OBJEXT) test_gic_LDADD = $(LDADD) test_gic_DEPENDENCIES = libkrb5.la $(am__DEPENDENCIES_1) \ $(top_builddir)/lib/asn1/libasn1.la \ $(top_builddir)/lib/wind/libwind.la $(LIB_heimbase) \ $(am__DEPENDENCIES_1) test_hostname_SOURCES = test_hostname.c test_hostname_OBJECTS = test_hostname.$(OBJEXT) test_hostname_LDADD = $(LDADD) test_hostname_DEPENDENCIES = libkrb5.la $(am__DEPENDENCIES_1) \ $(top_builddir)/lib/asn1/libasn1.la \ $(top_builddir)/lib/wind/libwind.la $(LIB_heimbase) \ $(am__DEPENDENCIES_1) test_keytab_SOURCES = test_keytab.c test_keytab_OBJECTS = test_keytab.$(OBJEXT) test_keytab_LDADD = $(LDADD) test_keytab_DEPENDENCIES = libkrb5.la $(am__DEPENDENCIES_1) \ $(top_builddir)/lib/asn1/libasn1.la \ $(top_builddir)/lib/wind/libwind.la $(LIB_heimbase) \ $(am__DEPENDENCIES_1) test_kuserok_SOURCES = test_kuserok.c test_kuserok_OBJECTS = test_kuserok.$(OBJEXT) test_kuserok_LDADD = $(LDADD) test_kuserok_DEPENDENCIES = libkrb5.la $(am__DEPENDENCIES_1) \ $(top_builddir)/lib/asn1/libasn1.la \ $(top_builddir)/lib/wind/libwind.la $(LIB_heimbase) \ $(am__DEPENDENCIES_1) test_mem_SOURCES = test_mem.c test_mem_OBJECTS = test_mem.$(OBJEXT) test_mem_LDADD = $(LDADD) test_mem_DEPENDENCIES = libkrb5.la $(am__DEPENDENCIES_1) \ $(top_builddir)/lib/asn1/libasn1.la \ $(top_builddir)/lib/wind/libwind.la $(LIB_heimbase) \ $(am__DEPENDENCIES_1) test_pac_SOURCES = test_pac.c test_pac_OBJECTS = test_pac.$(OBJEXT) test_pac_LDADD = $(LDADD) test_pac_DEPENDENCIES = libkrb5.la $(am__DEPENDENCIES_1) \ $(top_builddir)/lib/asn1/libasn1.la \ $(top_builddir)/lib/wind/libwind.la $(LIB_heimbase) \ $(am__DEPENDENCIES_1) test_pkinit_dh2key_SOURCES = test_pkinit_dh2key.c test_pkinit_dh2key_OBJECTS = test_pkinit_dh2key.$(OBJEXT) test_pkinit_dh2key_LDADD = $(LDADD) test_pkinit_dh2key_DEPENDENCIES = libkrb5.la $(am__DEPENDENCIES_1) \ $(top_builddir)/lib/asn1/libasn1.la \ $(top_builddir)/lib/wind/libwind.la $(LIB_heimbase) \ $(am__DEPENDENCIES_1) test_pknistkdf_SOURCES = test_pknistkdf.c test_pknistkdf_OBJECTS = test_pknistkdf.$(OBJEXT) test_pknistkdf_LDADD = $(LDADD) test_pknistkdf_DEPENDENCIES = libkrb5.la $(am__DEPENDENCIES_1) \ $(top_builddir)/lib/asn1/libasn1.la \ $(top_builddir)/lib/wind/libwind.la $(LIB_heimbase) \ $(am__DEPENDENCIES_1) test_plugin_SOURCES = test_plugin.c test_plugin_OBJECTS = test_plugin.$(OBJEXT) test_plugin_LDADD = $(LDADD) test_plugin_DEPENDENCIES = libkrb5.la $(am__DEPENDENCIES_1) \ $(top_builddir)/lib/asn1/libasn1.la \ $(top_builddir)/lib/wind/libwind.la $(LIB_heimbase) \ $(am__DEPENDENCIES_1) test_prf_SOURCES = test_prf.c test_prf_OBJECTS = test_prf.$(OBJEXT) test_prf_LDADD = $(LDADD) test_prf_DEPENDENCIES = libkrb5.la $(am__DEPENDENCIES_1) \ $(top_builddir)/lib/asn1/libasn1.la \ $(top_builddir)/lib/wind/libwind.la $(LIB_heimbase) \ $(am__DEPENDENCIES_1) test_princ_SOURCES = test_princ.c test_princ_OBJECTS = test_princ.$(OBJEXT) test_princ_LDADD = $(LDADD) test_princ_DEPENDENCIES = libkrb5.la $(am__DEPENDENCIES_1) \ $(top_builddir)/lib/asn1/libasn1.la \ $(top_builddir)/lib/wind/libwind.la $(LIB_heimbase) \ $(am__DEPENDENCIES_1) test_renew_SOURCES = test_renew.c test_renew_OBJECTS = test_renew.$(OBJEXT) test_renew_LDADD = $(LDADD) test_renew_DEPENDENCIES = libkrb5.la $(am__DEPENDENCIES_1) \ $(top_builddir)/lib/asn1/libasn1.la \ $(top_builddir)/lib/wind/libwind.la $(LIB_heimbase) \ $(am__DEPENDENCIES_1) test_rfc3961_SOURCES = test_rfc3961.c test_rfc3961_OBJECTS = test_rfc3961.$(OBJEXT) test_rfc3961_DEPENDENCIES = librfc3961.la \ $(top_builddir)/lib/asn1/libasn1.la \ $(top_builddir)/lib/wind/libwind.la $(am__DEPENDENCIES_1) \ $(am__DEPENDENCIES_1) test_set_kvno0_SOURCES = test_set_kvno0.c test_set_kvno0_OBJECTS = test_set_kvno0.$(OBJEXT) test_set_kvno0_LDADD = $(LDADD) test_set_kvno0_DEPENDENCIES = libkrb5.la $(am__DEPENDENCIES_1) \ $(top_builddir)/lib/asn1/libasn1.la \ $(top_builddir)/lib/wind/libwind.la $(LIB_heimbase) \ $(am__DEPENDENCIES_1) test_store_SOURCES = test_store.c test_store_OBJECTS = test_store.$(OBJEXT) test_store_LDADD = $(LDADD) test_store_DEPENDENCIES = libkrb5.la $(am__DEPENDENCIES_1) \ $(top_builddir)/lib/asn1/libasn1.la \ $(top_builddir)/lib/wind/libwind.la $(LIB_heimbase) \ $(am__DEPENDENCIES_1) test_time_SOURCES = test_time.c test_time_OBJECTS = test_time.$(OBJEXT) test_time_LDADD = $(LDADD) test_time_DEPENDENCIES = libkrb5.la $(am__DEPENDENCIES_1) \ $(top_builddir)/lib/asn1/libasn1.la \ $(top_builddir)/lib/wind/libwind.la $(LIB_heimbase) \ $(am__DEPENDENCIES_1) test_x500_SOURCES = test_x500.c test_x500_OBJECTS = test_x500.$(OBJEXT) test_x500_LDADD = $(LDADD) test_x500_DEPENDENCIES = libkrb5.la $(am__DEPENDENCIES_1) \ $(top_builddir)/lib/asn1/libasn1.la \ $(top_builddir)/lib/wind/libwind.la $(LIB_heimbase) \ $(am__DEPENDENCIES_1) verify_krb5_conf_SOURCES = verify_krb5_conf.c verify_krb5_conf_OBJECTS = verify_krb5_conf.$(OBJEXT) verify_krb5_conf_LDADD = $(LDADD) verify_krb5_conf_DEPENDENCIES = libkrb5.la $(am__DEPENDENCIES_1) \ $(top_builddir)/lib/asn1/libasn1.la \ $(top_builddir)/lib/wind/libwind.la $(LIB_heimbase) \ $(am__DEPENDENCIES_1) AM_V_P = $(am__v_P_@AM_V@) am__v_P_ = $(am__v_P_@AM_DEFAULT_V@) am__v_P_0 = false am__v_P_1 = : AM_V_GEN = $(am__v_GEN_@AM_V@) am__v_GEN_ = $(am__v_GEN_@AM_DEFAULT_V@) am__v_GEN_0 = @echo " GEN " $@; am__v_GEN_1 = AM_V_at = $(am__v_at_@AM_V@) am__v_at_ = $(am__v_at_@AM_DEFAULT_V@) am__v_at_0 = @ am__v_at_1 = depcomp = $(SHELL) $(top_srcdir)/depcomp am__depfiles_maybe = depfiles am__mv = mv -f COMPILE = $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) \ $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) LTCOMPILE = $(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) \ $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) \ $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) \ $(AM_CFLAGS) $(CFLAGS) AM_V_CC = $(am__v_CC_@AM_V@) am__v_CC_ = $(am__v_CC_@AM_DEFAULT_V@) am__v_CC_0 = @echo " CC " $@; am__v_CC_1 = CCLD = $(CC) LINK = $(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) \ $(LIBTOOLFLAGS) --mode=link $(CCLD) $(AM_CFLAGS) $(CFLAGS) \ $(AM_LDFLAGS) $(LDFLAGS) -o $@ AM_V_CCLD = $(am__v_CCLD_@AM_V@) am__v_CCLD_ = $(am__v_CCLD_@AM_DEFAULT_V@) am__v_CCLD_0 = @echo " CCLD " $@; am__v_CCLD_1 = SOURCES = $(dist_libkrb5_la_SOURCES) $(nodist_libkrb5_la_SOURCES) \ $(librfc3961_la_SOURCES) aes-test.c derived-key-test.c \ krbhst-test.c n-fold-test.c parse-name-test.c \ pseudo-random-test.c store-test.c string-to-key-test.c \ test_acl.c test_addr.c test_alname.c test_ap-req.c \ test_canon.c test_cc.c test_config.c test_crypto.c \ test_crypto_wrapping.c test_expand_toks.c test_forward.c \ test_fx.c test_get_addrs.c test_gic.c test_hostname.c \ test_keytab.c test_kuserok.c test_mem.c test_pac.c \ test_pkinit_dh2key.c test_pknistkdf.c test_plugin.c test_prf.c \ test_princ.c test_renew.c test_rfc3961.c test_set_kvno0.c \ test_store.c test_time.c test_x500.c verify_krb5_conf.c DIST_SOURCES = $(dist_libkrb5_la_SOURCES) $(librfc3961_la_SOURCES) \ aes-test.c derived-key-test.c krbhst-test.c n-fold-test.c \ parse-name-test.c pseudo-random-test.c store-test.c \ string-to-key-test.c test_acl.c test_addr.c test_alname.c \ test_ap-req.c test_canon.c test_cc.c test_config.c \ test_crypto.c test_crypto_wrapping.c test_expand_toks.c \ test_forward.c test_fx.c test_get_addrs.c test_gic.c \ test_hostname.c test_keytab.c test_kuserok.c test_mem.c \ test_pac.c test_pkinit_dh2key.c test_pknistkdf.c test_plugin.c \ test_prf.c test_princ.c test_renew.c test_rfc3961.c \ test_set_kvno0.c test_store.c test_time.c test_x500.c \ verify_krb5_conf.c am__can_run_installinfo = \ case $$AM_UPDATE_INFO_DIR in \ n|no|NO) false;; \ *) (install-info --version) >/dev/null 2>&1;; \ esac man3dir = $(mandir)/man3 man5dir = $(mandir)/man5 man7dir = $(mandir)/man7 man8dir = $(mandir)/man8 MANS = $(man_MANS) HEADERS = $(dist_include_HEADERS) $(krb5_HEADERS) \ $(nodist_include_HEADERS) $(noinst_HEADERS) am__tagged_files = $(HEADERS) $(SOURCES) $(TAGS_FILES) $(LISP) # Read a list of newline-separated strings from the standard input, # and print each of them once, without duplicates. Input order is # *not* preserved. am__uniquify_input = $(AWK) '\ BEGIN { nonempty = 0; } \ { items[$$0] = 1; nonempty = 1; } \ END { if (nonempty) { for (i in items) print i; }; } \ ' # Make sure the list of sources is unique. This is necessary because, # e.g., the same source file might be shared among _SOURCES variables # for different programs/libraries. am__define_uniq_tagged_files = \ list='$(am__tagged_files)'; \ unique=`for i in $$list; do \ if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ done | $(am__uniquify_input)` ETAGS = etags CTAGS = ctags am__tty_colors_dummy = \ mgn= red= grn= lgn= blu= brg= std=; \ am__color_tests=no am__tty_colors = { \ $(am__tty_colors_dummy); \ if test "X$(AM_COLOR_TESTS)" = Xno; then \ am__color_tests=no; \ elif test "X$(AM_COLOR_TESTS)" = Xalways; then \ am__color_tests=yes; \ elif test "X$$TERM" != Xdumb && { test -t 1; } 2>/dev/null; then \ am__color_tests=yes; \ fi; \ if test $$am__color_tests = yes; then \ red=''; \ grn=''; \ lgn=''; \ blu=''; \ mgn=''; \ brg=''; \ std=''; \ fi; \ } am__recheck_rx = ^[ ]*:recheck:[ ]* am__global_test_result_rx = ^[ ]*:global-test-result:[ ]* am__copy_in_global_log_rx = ^[ ]*:copy-in-global-log:[ ]* # A command that, given a newline-separated list of test names on the # standard input, print the name of the tests that are to be re-run # upon "make recheck". am__list_recheck_tests = $(AWK) '{ \ recheck = 1; \ while ((rc = (getline line < ($$0 ".trs"))) != 0) \ { \ if (rc < 0) \ { \ if ((getline line2 < ($$0 ".log")) < 0) \ recheck = 0; \ break; \ } \ else if (line ~ /$(am__recheck_rx)[nN][Oo]/) \ { \ recheck = 0; \ break; \ } \ else if (line ~ /$(am__recheck_rx)[yY][eE][sS]/) \ { \ break; \ } \ }; \ if (recheck) \ print $$0; \ close ($$0 ".trs"); \ close ($$0 ".log"); \ }' # A command that, given a newline-separated list of test names on the # standard input, create the global log from their .trs and .log files. am__create_global_log = $(AWK) ' \ function fatal(msg) \ { \ print "fatal: making $@: " msg | "cat >&2"; \ exit 1; \ } \ function rst_section(header) \ { \ print header; \ len = length(header); \ for (i = 1; i <= len; i = i + 1) \ printf "="; \ printf "\n\n"; \ } \ { \ copy_in_global_log = 1; \ global_test_result = "RUN"; \ while ((rc = (getline line < ($$0 ".trs"))) != 0) \ { \ if (rc < 0) \ fatal("failed to read from " $$0 ".trs"); \ if (line ~ /$(am__global_test_result_rx)/) \ { \ sub("$(am__global_test_result_rx)", "", line); \ sub("[ ]*$$", "", line); \ global_test_result = line; \ } \ else if (line ~ /$(am__copy_in_global_log_rx)[nN][oO]/) \ copy_in_global_log = 0; \ }; \ if (copy_in_global_log) \ { \ rst_section(global_test_result ": " $$0); \ while ((rc = (getline line < ($$0 ".log"))) != 0) \ { \ if (rc < 0) \ fatal("failed to read from " $$0 ".log"); \ print line; \ }; \ printf "\n"; \ }; \ close ($$0 ".trs"); \ close ($$0 ".log"); \ }' # Restructured Text title. am__rst_title = { sed 's/.*/ & /;h;s/./=/g;p;x;s/ *$$//;p;g' && echo; } # Solaris 10 'make', and several other traditional 'make' implementations, # pass "-e" to $(SHELL), and POSIX 2008 even requires this. Work around it # by disabling -e (using the XSI extension "set +e") if it's set. am__sh_e_setup = case $$- in *e*) set +e;; esac # Default flags passed to test drivers. am__common_driver_flags = \ --color-tests "$$am__color_tests" \ --enable-hard-errors "$$am__enable_hard_errors" \ --expect-failure "$$am__expect_failure" # To be inserted before the command running the test. Creates the # directory for the log if needed. Stores in $dir the directory # containing $f, in $tst the test, in $log the log. Executes the # developer- defined test setup AM_TESTS_ENVIRONMENT (if any), and # passes TESTS_ENVIRONMENT. Set up options for the wrapper that # will run the test scripts (or their associated LOG_COMPILER, if # thy have one). am__check_pre = \ $(am__sh_e_setup); \ $(am__vpath_adj_setup) $(am__vpath_adj) \ $(am__tty_colors); \ srcdir=$(srcdir); export srcdir; \ case "$@" in \ */*) am__odir=`echo "./$@" | sed 's|/[^/]*$$||'`;; \ *) am__odir=.;; \ esac; \ test "x$$am__odir" = x"." || test -d "$$am__odir" \ || $(MKDIR_P) "$$am__odir" || exit $$?; \ if test -f "./$$f"; then dir=./; \ elif test -f "$$f"; then dir=; \ else dir="$(srcdir)/"; fi; \ tst=$$dir$$f; log='$@'; \ if test -n '$(DISABLE_HARD_ERRORS)'; then \ am__enable_hard_errors=no; \ else \ am__enable_hard_errors=yes; \ fi; \ case " $(XFAIL_TESTS) " in \ *[\ \ ]$$f[\ \ ]* | *[\ \ ]$$dir$$f[\ \ ]*) \ am__expect_failure=yes;; \ *) \ am__expect_failure=no;; \ esac; \ $(AM_TESTS_ENVIRONMENT) $(TESTS_ENVIRONMENT) # A shell command to get the names of the tests scripts with any registered # extension removed (i.e., equivalently, the names of the test logs, with # the '.log' extension removed). The result is saved in the shell variable # '$bases'. This honors runtime overriding of TESTS and TEST_LOGS. Sadly, # we cannot use something simpler, involving e.g., "$(TEST_LOGS:.log=)", # since that might cause problem with VPATH rewrites for suffix-less tests. # See also 'test-harness-vpath-rewrite.sh' and 'test-trs-basic.sh'. am__set_TESTS_bases = \ bases='$(TEST_LOGS)'; \ bases=`for i in $$bases; do echo $$i; done | sed 's/\.log$$//'`; \ bases=`echo $$bases` RECHECK_LOGS = $(TEST_LOGS) AM_RECURSIVE_TARGETS = check recheck TEST_SUITE_LOG = test-suite.log TEST_EXTENSIONS = @EXEEXT@ .test LOG_DRIVER = $(SHELL) $(top_srcdir)/test-driver LOG_COMPILE = $(LOG_COMPILER) $(AM_LOG_FLAGS) $(LOG_FLAGS) am__set_b = \ case '$@' in \ */*) \ case '$*' in \ */*) b='$*';; \ *) b=`echo '$@' | sed 's/\.log$$//'`; \ esac;; \ *) \ b='$*';; \ esac am__test_logs1 = $(TESTS:=.log) am__test_logs2 = $(am__test_logs1:@EXEEXT@.log=.log) TEST_LOGS = $(am__test_logs2:.test.log=.log) TEST_LOG_DRIVER = $(SHELL) $(top_srcdir)/test-driver TEST_LOG_COMPILE = $(TEST_LOG_COMPILER) $(AM_TEST_LOG_FLAGS) \ $(TEST_LOG_FLAGS) am__DIST_COMMON = $(srcdir)/Makefile.in \ $(top_srcdir)/Makefile.am.common \ $(top_srcdir)/cf/Makefile.am.common $(top_srcdir)/depcomp \ $(top_srcdir)/test-driver DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST) ACLOCAL = @ACLOCAL@ AIX_EXTRA_KAFS = @AIX_EXTRA_KAFS@ AMTAR = @AMTAR@ AM_DEFAULT_VERBOSITY = @AM_DEFAULT_VERBOSITY@ AR = @AR@ AS = @AS@ ASN1_COMPILE = @ASN1_COMPILE@ ASN1_COMPILE_DEP = @ASN1_COMPILE_DEP@ AUTOCONF = @AUTOCONF@ AUTOHEADER = @AUTOHEADER@ AUTOMAKE = @AUTOMAKE@ AWK = @AWK@ CANONICAL_HOST = @CANONICAL_HOST@ CAPNG_CFLAGS = @CAPNG_CFLAGS@ CAPNG_LIBS = @CAPNG_LIBS@ CATMAN = @CATMAN@ CATMANEXT = @CATMANEXT@ CC = @CC@ CCDEPMODE = @CCDEPMODE@ CFLAGS = @CFLAGS@ COMPILE_ET = @COMPILE_ET@ CPP = @CPP@ CPPFLAGS = @CPPFLAGS@ CYGPATH_W = @CYGPATH_W@ DB1LIB = @DB1LIB@ DB3LIB = @DB3LIB@ DBHEADER = @DBHEADER@ DEFS = @DEFS@ DEPDIR = @DEPDIR@ DIR_com_err = @DIR_com_err@ DIR_hdbdir = @DIR_hdbdir@ DIR_roken = @DIR_roken@ DLLTOOL = @DLLTOOL@ DSYMUTIL = @DSYMUTIL@ DUMPBIN = @DUMPBIN@ ECHO_C = @ECHO_C@ ECHO_N = @ECHO_N@ ECHO_T = @ECHO_T@ EGREP = @EGREP@ ENABLE_AFS_STRING_TO_KEY = @ENABLE_AFS_STRING_TO_KEY@ EXEEXT = @EXEEXT@ FGREP = @FGREP@ GCD_MIG = @GCD_MIG@ GREP = @GREP@ GROFF = @GROFF@ INCLUDES_roken = @INCLUDES_roken@ INCLUDE_libedit = @INCLUDE_libedit@ INCLUDE_libintl = @INCLUDE_libintl@ INCLUDE_openldap = @INCLUDE_openldap@ INCLUDE_openssl_crypto = @INCLUDE_openssl_crypto@ INCLUDE_readline = @INCLUDE_readline@ INCLUDE_sqlite3 = @INCLUDE_sqlite3@ INSTALL = @INSTALL@ INSTALL_DATA = @INSTALL_DATA@ INSTALL_PROGRAM = @INSTALL_PROGRAM@ INSTALL_SCRIPT = @INSTALL_SCRIPT@ INSTALL_STRIP_PROGRAM = @INSTALL_STRIP_PROGRAM@ LD = @LD@ LDFLAGS = @LDFLAGS@ LDFLAGS_VERSION_SCRIPT = @LDFLAGS_VERSION_SCRIPT@ LEX = @LEX@ LEXLIB = @LEXLIB@ LEX_OUTPUT_ROOT = @LEX_OUTPUT_ROOT@ LIBADD_roken = @LIBADD_roken@ LIBOBJS = @LIBOBJS@ LIBS = @LIBS@ LIBTOOL = @LIBTOOL@ LIB_AUTH_SUBDIRS = @LIB_AUTH_SUBDIRS@ LIB_bswap16 = @LIB_bswap16@ LIB_bswap32 = @LIB_bswap32@ LIB_bswap64 = @LIB_bswap64@ LIB_com_err = @LIB_com_err@ LIB_com_err_a = @LIB_com_err_a@ LIB_com_err_so = @LIB_com_err_so@ LIB_crypt = @LIB_crypt@ LIB_db_create = @LIB_db_create@ LIB_dbm_firstkey = @LIB_dbm_firstkey@ LIB_dbopen = @LIB_dbopen@ LIB_dispatch_async_f = @LIB_dispatch_async_f@ LIB_dladdr = @LIB_dladdr@ LIB_dlopen = @LIB_dlopen@ LIB_dn_expand = @LIB_dn_expand@ LIB_dns_search = @LIB_dns_search@ LIB_door_create = @LIB_door_create@ LIB_freeaddrinfo = @LIB_freeaddrinfo@ LIB_gai_strerror = @LIB_gai_strerror@ LIB_getaddrinfo = @LIB_getaddrinfo@ LIB_gethostbyname = @LIB_gethostbyname@ LIB_gethostbyname2 = @LIB_gethostbyname2@ LIB_getnameinfo = @LIB_getnameinfo@ LIB_getpwnam_r = @LIB_getpwnam_r@ LIB_getsockopt = @LIB_getsockopt@ LIB_hcrypto = @LIB_hcrypto@ LIB_hcrypto_a = @LIB_hcrypto_a@ LIB_hcrypto_appl = @LIB_hcrypto_appl@ LIB_hcrypto_so = @LIB_hcrypto_so@ LIB_hstrerror = @LIB_hstrerror@ LIB_kdb = @LIB_kdb@ LIB_libedit = @LIB_libedit@ LIB_libintl = @LIB_libintl@ LIB_loadquery = @LIB_loadquery@ LIB_logout = @LIB_logout@ LIB_logwtmp = @LIB_logwtmp@ LIB_openldap = @LIB_openldap@ LIB_openpty = @LIB_openpty@ LIB_openssl_crypto = @LIB_openssl_crypto@ LIB_otp = @LIB_otp@ LIB_pidfile = @LIB_pidfile@ LIB_readline = @LIB_readline@ LIB_res_ndestroy = @LIB_res_ndestroy@ LIB_res_nsearch = @LIB_res_nsearch@ LIB_res_search = @LIB_res_search@ LIB_roken = @LIB_roken@ LIB_security = @LIB_security@ LIB_setsockopt = @LIB_setsockopt@ LIB_socket = @LIB_socket@ LIB_sqlite3 = @LIB_sqlite3@ LIB_syslog = @LIB_syslog@ LIB_tgetent = @LIB_tgetent@ LIPO = @LIPO@ LMDBLIB = @LMDBLIB@ LN_S = @LN_S@ LTLIBOBJS = @LTLIBOBJS@ LT_SYS_LIBRARY_PATH = @LT_SYS_LIBRARY_PATH@ MAINT = @MAINT@ MAKEINFO = @MAKEINFO@ MANIFEST_TOOL = @MANIFEST_TOOL@ MKDIR_P = @MKDIR_P@ NDBMLIB = @NDBMLIB@ NM = @NM@ NMEDIT = @NMEDIT@ NO_AFS = @NO_AFS@ NROFF = @NROFF@ OBJDUMP = @OBJDUMP@ OBJEXT = @OBJEXT@ OTOOL = @OTOOL@ OTOOL64 = @OTOOL64@ PACKAGE = @PACKAGE@ PACKAGE_BUGREPORT = @PACKAGE_BUGREPORT@ PACKAGE_NAME = @PACKAGE_NAME@ PACKAGE_STRING = @PACKAGE_STRING@ PACKAGE_TARNAME = @PACKAGE_TARNAME@ PACKAGE_URL = @PACKAGE_URL@ PACKAGE_VERSION = @PACKAGE_VERSION@ PATH_SEPARATOR = @PATH_SEPARATOR@ PERL = @PERL@ PKG_CONFIG = @PKG_CONFIG@ PTHREAD_CFLAGS = @PTHREAD_CFLAGS@ PTHREAD_LDADD = @PTHREAD_LDADD@ PTHREAD_LIBADD = @PTHREAD_LIBADD@ RANLIB = @RANLIB@ SED = @SED@ SET_MAKE = @SET_MAKE@ SHELL = @SHELL@ SLC = @SLC@ SLC_DEP = @SLC_DEP@ STRIP = @STRIP@ VERSION = @VERSION@ VERSIONING = @VERSIONING@ WFLAGS = @WFLAGS@ WFLAGS_LITE = @WFLAGS_LITE@ YACC = @YACC@ YFLAGS = @YFLAGS@ abs_builddir = @abs_builddir@ abs_srcdir = @abs_srcdir@ abs_top_builddir = @abs_top_builddir@ abs_top_srcdir = @abs_top_srcdir@ ac_ct_AR = @ac_ct_AR@ ac_ct_CC = @ac_ct_CC@ ac_ct_DUMPBIN = @ac_ct_DUMPBIN@ am__include = @am__include@ am__leading_dot = @am__leading_dot@ am__quote = @am__quote@ am__tar = @am__tar@ am__untar = @am__untar@ bindir = @bindir@ build = @build@ build_alias = @build_alias@ build_cpu = @build_cpu@ build_os = @build_os@ build_vendor = @build_vendor@ builddir = @builddir@ datadir = @datadir@ datarootdir = @datarootdir@ db_type = @db_type@ db_type_preference = @db_type_preference@ docdir = @docdir@ dpagaix_cflags = @dpagaix_cflags@ dpagaix_ldadd = @dpagaix_ldadd@ dpagaix_ldflags = @dpagaix_ldflags@ dvidir = @dvidir@ exec_prefix = @exec_prefix@ host = @host@ host_alias = @host_alias@ host_cpu = @host_cpu@ host_os = @host_os@ host_vendor = @host_vendor@ htmldir = @htmldir@ includedir = @includedir@ infodir = @infodir@ install_sh = @install_sh@ libdir = @libdir@ libexecdir = @libexecdir@ localedir = @localedir@ localstatedir = @localstatedir@ mandir = @mandir@ mkdir_p = @mkdir_p@ oldincludedir = @oldincludedir@ pdfdir = @pdfdir@ prefix = @prefix@ program_transform_name = @program_transform_name@ psdir = @psdir@ sbindir = @sbindir@ sharedstatedir = @sharedstatedir@ srcdir = @srcdir@ subdirs = @subdirs@ sysconfdir = @sysconfdir@ target_alias = @target_alias@ top_build_prefix = @top_build_prefix@ top_builddir = @top_builddir@ top_srcdir = @top_srcdir@ SUFFIXES = .et .h .pc.in .pc .x .z .hx .1 .3 .5 .7 .8 .cat1 .cat3 \ .cat5 .cat7 .cat8 DEFAULT_INCLUDES = -I. -I$(srcdir) -I$(top_builddir)/include -I$(top_srcdir)/include AM_CPPFLAGS = $(INCLUDES_roken) -I../com_err -I$(srcdir)/../com_err \ $(INCLUDE_sqlite3) $(INCLUDE_libintl) \ $(INCLUDE_openssl_crypto) @do_roken_rename_TRUE@ROKEN_RENAME = -DROKEN_RENAME AM_CFLAGS = $(WFLAGS) CP = cp buildinclude = $(top_builddir)/include LIB_XauReadAuth = @LIB_XauReadAuth@ LIB_el_init = @LIB_el_init@ LIB_getattr = @LIB_getattr@ LIB_getpwent_r = @LIB_getpwent_r@ LIB_odm_initialize = @LIB_odm_initialize@ LIB_setpcred = @LIB_setpcred@ INCLUDE_krb4 = @INCLUDE_krb4@ LIB_krb4 = @LIB_krb4@ libexec_heimdaldir = $(libexecdir)/heimdal NROFF_MAN = groff -mandoc -Tascii @NO_AFS_FALSE@LIB_kafs = $(top_builddir)/lib/kafs/libkafs.la $(AIX_EXTRA_KAFS) @NO_AFS_TRUE@LIB_kafs = @KRB5_TRUE@LIB_krb5 = $(top_builddir)/lib/krb5/libkrb5.la \ @KRB5_TRUE@ $(top_builddir)/lib/asn1/libasn1.la @KRB5_TRUE@LIB_gssapi = $(top_builddir)/lib/gssapi/libgssapi.la LIB_heimbase = $(top_builddir)/lib/base/libheimbase.la @DCE_TRUE@LIB_kdfs = $(top_builddir)/lib/kdfs/libkdfs.la #silent-rules heim_verbose = $(heim_verbose_$(V)) heim_verbose_ = $(heim_verbose_$(AM_DEFAULT_VERBOSITY)) heim_verbose_0 = @echo " GEN "$@; noinst_LTLIBRARIES = \ librfc3961.la check_DATA = test_config_strings.out LDADD = libkrb5.la \ $(LIB_hcrypto) \ $(top_builddir)/lib/asn1/libasn1.la \ $(top_builddir)/lib/wind/libwind.la \ $(LIB_heimbase) $(LIB_roken) @PKINIT_TRUE@LIB_pkinit = ../hx509/libhx509.la @have_scc_TRUE@use_sqlite = $(LIB_sqlite3) libkrb5_la_LIBADD = \ $(top_builddir)/lib/asn1/libasn1.la \ $(top_builddir)/lib/ipc/libheim-ipcc.la \ $(top_builddir)/lib/wind/libwind.la \ $(top_builddir)/lib/base/libheimbase.la \ $(LIB_pkinit) \ $(LIB_openssl_crypto) \ $(use_sqlite) \ $(LIB_com_err) \ $(LIB_hcrypto) \ $(LIB_libintl) \ $(LIBADD_roken) \ $(PTHREAD_LIBADD) \ $(LIB_door_create) \ $(LIB_dlopen) librfc3961_la_LIBADD = \ $(top_builddir)/lib/asn1/libasn1.la \ $(top_builddir)/lib/ipc/libheim-ipcc.la \ $(top_builddir)/lib/wind/libwind.la \ $(LIB_pkinit) \ $(use_sqlite) \ $(LIB_com_err) \ $(LIB_hcrypto) \ $(LIB_libintl) \ $(LIBADD_roken) \ $(PTHREAD_LIBADD) \ $(LIB_door_create) \ $(LIB_dlopen) lib_LTLIBRARIES = libkrb5.la ERR_FILES = krb5_err.c krb_err.c heim_err.c k524_err.c libkrb5_la_CPPFLAGS = \ -DBUILD_KRB5_LIB \ $(AM_CPPFLAGS) \ -DHEIMDAL_LOCALEDIR='"$(localedir)"' librfc3961_la_CPPFLAGS = \ -DBUILD_KRB5_LIB \ $(AM_CPPFLAGS) \ -DHEIMDAL_LOCALEDIR='"$(localedir)"' dist_libkrb5_la_SOURCES = \ acache.c \ acl.c \ add_et_list.c \ addr_families.c \ an2ln_plugin.h \ aname_to_localname.c \ appdefault.c \ asn1_glue.c \ auth_context.c \ build_ap_req.c \ build_auth.c \ cache.c \ changepw.c \ codec.c \ config_file.c \ convert_creds.c \ constants.c \ context.c \ copy_host_realm.c \ crc.c \ creds.c \ crypto.c \ crypto.h \ crypto-aes-sha1.c \ crypto-aes-sha2.c \ crypto-algs.c \ crypto-arcfour.c \ crypto-des.c \ crypto-des-common.c \ crypto-des3.c \ crypto-evp.c \ crypto-null.c \ crypto-pk.c \ crypto-rand.c \ doxygen.c \ data.c \ db_plugin.c \ db_plugin.h \ dcache.c \ deprecated.c \ digest.c \ eai_to_heim_errno.c \ enomem.c \ error_string.c \ expand_hostname.c \ expand_path.c \ fast.c \ fcache.c \ free.c \ free_host_realm.c \ generate_seq_number.c \ generate_subkey.c \ get_addrs.c \ get_cred.c \ get_default_principal.c \ get_default_realm.c \ get_for_creds.c \ get_host_realm.c \ get_in_tkt.c \ get_port.c \ init_creds.c \ init_creds_pw.c \ kcm.c \ kcm.h \ keyblock.c \ keytab.c \ keytab_any.c \ keytab_file.c \ keytab_keyfile.c \ keytab_memory.c \ krb5_locl.h \ krb5-v4compat.h \ krbhst.c \ kuserok.c \ kuserok_plugin.h \ log.c \ mcache.c \ misc.c \ mk_error.c \ mk_priv.c \ mk_rep.c \ mk_req.c \ mk_req_ext.c \ mk_safe.c \ mit_glue.c \ net_read.c \ net_write.c \ n-fold.c \ pac.c \ padata.c \ pcache.c \ pkinit.c \ pkinit-ec.c \ principal.c \ prog_setup.c \ prompter_posix.c \ rd_cred.c \ rd_error.c \ rd_priv.c \ rd_rep.c \ rd_req.c \ rd_safe.c \ read_message.c \ recvauth.c \ replay.c \ salt.c \ salt-aes-sha1.c \ salt-aes-sha2.c \ salt-arcfour.c \ salt-des.c \ salt-des3.c \ sp800-108-kdf.c \ scache.c \ send_to_kdc.c \ sendauth.c \ set_default_realm.c \ sock_principal.c \ store.c \ store-int.c \ store-int.h \ store_emem.c \ store_fd.c \ store_mem.c \ store_sock.c \ plugin.c \ ticket.c \ time.c \ transited.c \ verify_init.c \ verify_user.c \ version.c \ warn.c \ write_message.c nodist_libkrb5_la_SOURCES = \ $(ERR_FILES) libkrb5_la_DEPENDENCIES = \ version-script.map libkrb5_la_LDFLAGS = -version-info 26:0:0 $(am__append_1) ALL_OBJECTS = $(libkrb5_la_OBJECTS) $(verify_krb5_conf_OBJECTS) \ $(librfc3961_la_OBJECTS) $(librfc3961_la_OBJECTS) \ $(krbhst_test_OBJECTS) $(test_alname_OBJECTS) \ $(test_crypto_OBJECTS) $(test_forward_OBJECTS) \ $(test_get_addrs_OBJECTS) $(test_gic_OBJECTS) \ $(test_kuserok_OBJECTS) $(test_renew_OBJECTS) \ $(test_rfc3961_OBJECTS) librfc3961_la_SOURCES = \ crc.c \ crypto.c \ crypto.h \ crypto-aes-sha1.c \ crypto-aes-sha2.c \ crypto-algs.c \ crypto-arcfour.c \ crypto-des.c \ crypto-des-common.c \ crypto-des3.c \ crypto-evp.c \ crypto-null.c \ crypto-pk.c \ crypto-rand.c \ crypto-stubs.c \ data.c \ enomem.c \ error_string.c \ keyblock.c \ n-fold.c \ salt.c \ salt-aes-sha1.c \ salt-aes-sha2.c \ salt-arcfour.c \ salt-des.c \ salt-des3.c \ sp800-108-kdf.c \ store-int.c \ warn.c test_rfc3961_LDADD = \ librfc3961.la \ $(top_builddir)/lib/asn1/libasn1.la \ $(top_builddir)/lib/wind/libwind.la \ $(LIB_hcrypto) \ $(LIB_roken) @DEVELOPER_MODE_TRUE@headerdeps = $(dist_libkrb5_la_SOURCES) man_MANS = \ kerberos.8 \ krb5.conf.5 \ krb5-plugin.7 \ krb524_convert_creds_kdc.3 \ krb5_425_conv_principal.3 \ krb5_acl_match_file.3 \ krb5_aname_to_localname.3 \ krb5_appdefault.3 \ krb5_auth_context.3 \ krb5_c_make_checksum.3 \ krb5_check_transited.3 \ krb5_create_checksum.3 \ krb5_creds.3 \ krb5_digest.3 \ krb5_eai_to_heim_errno.3 \ krb5_encrypt.3 \ krb5_find_padata.3 \ krb5_generate_random_block.3 \ krb5_get_all_client_addrs.3 \ krb5_get_credentials.3 \ krb5_get_creds.3 \ krb5_get_forwarded_creds.3 \ krb5_get_in_cred.3 \ krb5_get_init_creds.3 \ krb5_get_krbhst.3 \ krb5_getportbyname.3 \ krb5_init_context.3 \ krb5_is_thread_safe.3 \ krb5_krbhst_init.3 \ krb5_mk_req.3 \ krb5_mk_safe.3 \ krb5_openlog.3 \ krb5_parse_name.3 \ krb5_principal.3 \ krb5_rcache.3 \ krb5_rd_error.3 \ krb5_rd_safe.3 \ krb5_set_default_realm.3 \ krb5_set_password.3 \ krb5_string_to_key.3 \ krb5_timeofday.3 \ krb5_verify_init_creds.3 \ krb5_verify_user.3 \ verify_krb5_conf.8 dist_include_HEADERS = \ krb5.h \ $(srcdir)/krb5-protos.h \ krb5_ccapi.h noinst_HEADERS = $(srcdir)/krb5-private.h nodist_include_HEADERS = krb5_err.h heim_err.h k524_err.h # XXX use nobase_include_HEADERS = krb5/locate_plugin.h krb5dir = $(includedir)/krb5 krb5_HEADERS = locate_plugin.h send_to_kdc_plugin.h ccache_plugin.h an2ln_plugin.h db_plugin.h build_HEADERZ = \ $(krb5_HEADERS) \ krb_err.h CLEANFILES = \ test_config_strings.out \ test-store-data \ krb5_err.c krb5_err.h \ krb_err.c krb_err.h \ heim_err.c heim_err.h \ k524_err.c k524_err.h EXTRA_DIST = \ NTMakefile \ config_reg.c \ dll.c \ libkrb5-exports.def.in \ verify_krb5_conf-version.rc \ krb5_err.et \ krb_err.et \ heim_err.et \ k524_err.et \ $(man_MANS) \ version-script.map \ test_config_strings.cfg \ krb5.moduli all: all-am .SUFFIXES: .SUFFIXES: .et .h .pc.in .pc .x .z .hx .1 .3 .5 .7 .8 .cat1 .cat3 .cat5 .cat7 .cat8 .c .lo .log .o .obj .test .test$(EXEEXT) .trs $(srcdir)/Makefile.in: @MAINTAINER_MODE_TRUE@ $(srcdir)/Makefile.am $(top_srcdir)/Makefile.am.common $(top_srcdir)/cf/Makefile.am.common $(am__configure_deps) @for dep in $?; do \ case '$(am__configure_deps)' in \ *$$dep*) \ ( cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh ) \ && { if test -f $@; then exit 0; else break; fi; }; \ exit 1;; \ esac; \ done; \ echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign lib/krb5/Makefile'; \ $(am__cd) $(top_srcdir) && \ $(AUTOMAKE) --foreign lib/krb5/Makefile Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status @case '$?' in \ *config.status*) \ cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh;; \ *) \ echo ' cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe)'; \ cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe);; \ esac; $(top_srcdir)/Makefile.am.common $(top_srcdir)/cf/Makefile.am.common $(am__empty): $(top_builddir)/config.status: $(top_srcdir)/configure $(CONFIG_STATUS_DEPENDENCIES) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(top_srcdir)/configure: @MAINTAINER_MODE_TRUE@ $(am__configure_deps) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(ACLOCAL_M4): @MAINTAINER_MODE_TRUE@ $(am__aclocal_m4_deps) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(am__aclocal_m4_deps): install-libLTLIBRARIES: $(lib_LTLIBRARIES) @$(NORMAL_INSTALL) @list='$(lib_LTLIBRARIES)'; test -n "$(libdir)" || list=; \ list2=; for p in $$list; do \ if test -f $$p; then \ list2="$$list2 $$p"; \ else :; fi; \ done; \ test -z "$$list2" || { \ echo " $(MKDIR_P) '$(DESTDIR)$(libdir)'"; \ $(MKDIR_P) "$(DESTDIR)$(libdir)" || exit 1; \ echo " $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=install $(INSTALL) $(INSTALL_STRIP_FLAG) $$list2 '$(DESTDIR)$(libdir)'"; \ $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=install $(INSTALL) $(INSTALL_STRIP_FLAG) $$list2 "$(DESTDIR)$(libdir)"; \ } uninstall-libLTLIBRARIES: @$(NORMAL_UNINSTALL) @list='$(lib_LTLIBRARIES)'; test -n "$(libdir)" || list=; \ for p in $$list; do \ $(am__strip_dir) \ echo " $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=uninstall rm -f '$(DESTDIR)$(libdir)/$$f'"; \ $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=uninstall rm -f "$(DESTDIR)$(libdir)/$$f"; \ done clean-libLTLIBRARIES: -test -z "$(lib_LTLIBRARIES)" || rm -f $(lib_LTLIBRARIES) @list='$(lib_LTLIBRARIES)'; \ locs=`for p in $$list; do echo $$p; done | \ sed 's|^[^/]*$$|.|; s|/[^/]*$$||; s|$$|/so_locations|' | \ sort -u`; \ test -z "$$locs" || { \ echo rm -f $${locs}; \ rm -f $${locs}; \ } clean-noinstLTLIBRARIES: -test -z "$(noinst_LTLIBRARIES)" || rm -f $(noinst_LTLIBRARIES) @list='$(noinst_LTLIBRARIES)'; \ locs=`for p in $$list; do echo $$p; done | \ sed 's|^[^/]*$$|.|; s|/[^/]*$$||; s|$$|/so_locations|' | \ sort -u`; \ test -z "$$locs" || { \ echo rm -f $${locs}; \ rm -f $${locs}; \ } libkrb5.la: $(libkrb5_la_OBJECTS) $(libkrb5_la_DEPENDENCIES) $(EXTRA_libkrb5_la_DEPENDENCIES) $(AM_V_CCLD)$(libkrb5_la_LINK) -rpath $(libdir) $(libkrb5_la_OBJECTS) $(libkrb5_la_LIBADD) $(LIBS) librfc3961.la: $(librfc3961_la_OBJECTS) $(librfc3961_la_DEPENDENCIES) $(EXTRA_librfc3961_la_DEPENDENCIES) $(AM_V_CCLD)$(LINK) $(librfc3961_la_OBJECTS) $(librfc3961_la_LIBADD) $(LIBS) install-binPROGRAMS: $(bin_PROGRAMS) @$(NORMAL_INSTALL) @list='$(bin_PROGRAMS)'; test -n "$(bindir)" || list=; \ if test -n "$$list"; then \ echo " $(MKDIR_P) '$(DESTDIR)$(bindir)'"; \ $(MKDIR_P) "$(DESTDIR)$(bindir)" || exit 1; \ fi; \ for p in $$list; do echo "$$p $$p"; done | \ sed 's/$(EXEEXT)$$//' | \ while read p p1; do if test -f $$p \ || test -f $$p1 \ ; then echo "$$p"; echo "$$p"; else :; fi; \ done | \ sed -e 'p;s,.*/,,;n;h' \ -e 's|.*|.|' \ -e 'p;x;s,.*/,,;s/$(EXEEXT)$$//;$(transform);s/$$/$(EXEEXT)/' | \ sed 'N;N;N;s,\n, ,g' | \ $(AWK) 'BEGIN { files["."] = ""; dirs["."] = 1 } \ { d=$$3; if (dirs[d] != 1) { print "d", d; dirs[d] = 1 } \ if ($$2 == $$4) files[d] = files[d] " " $$1; \ else { print "f", $$3 "/" $$4, $$1; } } \ END { for (d in files) print "f", d, files[d] }' | \ while read type dir files; do \ if test "$$dir" = .; then dir=; else dir=/$$dir; fi; \ test -z "$$files" || { \ echo " $(INSTALL_PROGRAM_ENV) $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=install $(INSTALL_PROGRAM) $$files '$(DESTDIR)$(bindir)$$dir'"; \ $(INSTALL_PROGRAM_ENV) $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=install $(INSTALL_PROGRAM) $$files "$(DESTDIR)$(bindir)$$dir" || exit $$?; \ } \ ; done uninstall-binPROGRAMS: @$(NORMAL_UNINSTALL) @list='$(bin_PROGRAMS)'; test -n "$(bindir)" || list=; \ files=`for p in $$list; do echo "$$p"; done | \ sed -e 'h;s,^.*/,,;s/$(EXEEXT)$$//;$(transform)' \ -e 's/$$/$(EXEEXT)/' \ `; \ test -n "$$list" || exit 0; \ echo " ( cd '$(DESTDIR)$(bindir)' && rm -f" $$files ")"; \ cd "$(DESTDIR)$(bindir)" && rm -f $$files clean-binPROGRAMS: @list='$(bin_PROGRAMS)'; test -n "$$list" || exit 0; \ echo " rm -f" $$list; \ rm -f $$list || exit $$?; \ test -n "$(EXEEXT)" || exit 0; \ list=`for p in $$list; do echo "$$p"; done | sed 's/$(EXEEXT)$$//'`; \ echo " rm -f" $$list; \ rm -f $$list clean-checkPROGRAMS: @list='$(check_PROGRAMS)'; test -n "$$list" || exit 0; \ echo " rm -f" $$list; \ rm -f $$list || exit $$?; \ test -n "$(EXEEXT)" || exit 0; \ list=`for p in $$list; do echo "$$p"; done | sed 's/$(EXEEXT)$$//'`; \ echo " rm -f" $$list; \ rm -f $$list clean-noinstPROGRAMS: @list='$(noinst_PROGRAMS)'; test -n "$$list" || exit 0; \ echo " rm -f" $$list; \ rm -f $$list || exit $$?; \ test -n "$(EXEEXT)" || exit 0; \ list=`for p in $$list; do echo "$$p"; done | sed 's/$(EXEEXT)$$//'`; \ echo " rm -f" $$list; \ rm -f $$list aes-test$(EXEEXT): $(aes_test_OBJECTS) $(aes_test_DEPENDENCIES) $(EXTRA_aes_test_DEPENDENCIES) @rm -f aes-test$(EXEEXT) $(AM_V_CCLD)$(LINK) $(aes_test_OBJECTS) $(aes_test_LDADD) $(LIBS) derived-key-test$(EXEEXT): $(derived_key_test_OBJECTS) $(derived_key_test_DEPENDENCIES) $(EXTRA_derived_key_test_DEPENDENCIES) @rm -f derived-key-test$(EXEEXT) $(AM_V_CCLD)$(LINK) $(derived_key_test_OBJECTS) $(derived_key_test_LDADD) $(LIBS) krbhst-test$(EXEEXT): $(krbhst_test_OBJECTS) $(krbhst_test_DEPENDENCIES) $(EXTRA_krbhst_test_DEPENDENCIES) @rm -f krbhst-test$(EXEEXT) $(AM_V_CCLD)$(LINK) $(krbhst_test_OBJECTS) $(krbhst_test_LDADD) $(LIBS) n-fold-test$(EXEEXT): $(n_fold_test_OBJECTS) $(n_fold_test_DEPENDENCIES) $(EXTRA_n_fold_test_DEPENDENCIES) @rm -f n-fold-test$(EXEEXT) $(AM_V_CCLD)$(LINK) $(n_fold_test_OBJECTS) $(n_fold_test_LDADD) $(LIBS) parse-name-test$(EXEEXT): $(parse_name_test_OBJECTS) $(parse_name_test_DEPENDENCIES) $(EXTRA_parse_name_test_DEPENDENCIES) @rm -f parse-name-test$(EXEEXT) $(AM_V_CCLD)$(LINK) $(parse_name_test_OBJECTS) $(parse_name_test_LDADD) $(LIBS) pseudo-random-test$(EXEEXT): $(pseudo_random_test_OBJECTS) $(pseudo_random_test_DEPENDENCIES) $(EXTRA_pseudo_random_test_DEPENDENCIES) @rm -f pseudo-random-test$(EXEEXT) $(AM_V_CCLD)$(LINK) $(pseudo_random_test_OBJECTS) $(pseudo_random_test_LDADD) $(LIBS) store-test$(EXEEXT): $(store_test_OBJECTS) $(store_test_DEPENDENCIES) $(EXTRA_store_test_DEPENDENCIES) @rm -f store-test$(EXEEXT) $(AM_V_CCLD)$(LINK) $(store_test_OBJECTS) $(store_test_LDADD) $(LIBS) string-to-key-test$(EXEEXT): $(string_to_key_test_OBJECTS) $(string_to_key_test_DEPENDENCIES) $(EXTRA_string_to_key_test_DEPENDENCIES) @rm -f string-to-key-test$(EXEEXT) $(AM_V_CCLD)$(LINK) $(string_to_key_test_OBJECTS) $(string_to_key_test_LDADD) $(LIBS) test_acl$(EXEEXT): $(test_acl_OBJECTS) $(test_acl_DEPENDENCIES) $(EXTRA_test_acl_DEPENDENCIES) @rm -f test_acl$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_acl_OBJECTS) $(test_acl_LDADD) $(LIBS) test_addr$(EXEEXT): $(test_addr_OBJECTS) $(test_addr_DEPENDENCIES) $(EXTRA_test_addr_DEPENDENCIES) @rm -f test_addr$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_addr_OBJECTS) $(test_addr_LDADD) $(LIBS) test_alname$(EXEEXT): $(test_alname_OBJECTS) $(test_alname_DEPENDENCIES) $(EXTRA_test_alname_DEPENDENCIES) @rm -f test_alname$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_alname_OBJECTS) $(test_alname_LDADD) $(LIBS) test_ap-req$(EXEEXT): $(test_ap_req_OBJECTS) $(test_ap_req_DEPENDENCIES) $(EXTRA_test_ap_req_DEPENDENCIES) @rm -f test_ap-req$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_ap_req_OBJECTS) $(test_ap_req_LDADD) $(LIBS) test_canon$(EXEEXT): $(test_canon_OBJECTS) $(test_canon_DEPENDENCIES) $(EXTRA_test_canon_DEPENDENCIES) @rm -f test_canon$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_canon_OBJECTS) $(test_canon_LDADD) $(LIBS) test_cc$(EXEEXT): $(test_cc_OBJECTS) $(test_cc_DEPENDENCIES) $(EXTRA_test_cc_DEPENDENCIES) @rm -f test_cc$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_cc_OBJECTS) $(test_cc_LDADD) $(LIBS) test_config$(EXEEXT): $(test_config_OBJECTS) $(test_config_DEPENDENCIES) $(EXTRA_test_config_DEPENDENCIES) @rm -f test_config$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_config_OBJECTS) $(test_config_LDADD) $(LIBS) test_crypto$(EXEEXT): $(test_crypto_OBJECTS) $(test_crypto_DEPENDENCIES) $(EXTRA_test_crypto_DEPENDENCIES) @rm -f test_crypto$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_crypto_OBJECTS) $(test_crypto_LDADD) $(LIBS) test_crypto_wrapping$(EXEEXT): $(test_crypto_wrapping_OBJECTS) $(test_crypto_wrapping_DEPENDENCIES) $(EXTRA_test_crypto_wrapping_DEPENDENCIES) @rm -f test_crypto_wrapping$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_crypto_wrapping_OBJECTS) $(test_crypto_wrapping_LDADD) $(LIBS) test_expand_toks$(EXEEXT): $(test_expand_toks_OBJECTS) $(test_expand_toks_DEPENDENCIES) $(EXTRA_test_expand_toks_DEPENDENCIES) @rm -f test_expand_toks$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_expand_toks_OBJECTS) $(test_expand_toks_LDADD) $(LIBS) test_forward$(EXEEXT): $(test_forward_OBJECTS) $(test_forward_DEPENDENCIES) $(EXTRA_test_forward_DEPENDENCIES) @rm -f test_forward$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_forward_OBJECTS) $(test_forward_LDADD) $(LIBS) test_fx$(EXEEXT): $(test_fx_OBJECTS) $(test_fx_DEPENDENCIES) $(EXTRA_test_fx_DEPENDENCIES) @rm -f test_fx$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_fx_OBJECTS) $(test_fx_LDADD) $(LIBS) test_get_addrs$(EXEEXT): $(test_get_addrs_OBJECTS) $(test_get_addrs_DEPENDENCIES) $(EXTRA_test_get_addrs_DEPENDENCIES) @rm -f test_get_addrs$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_get_addrs_OBJECTS) $(test_get_addrs_LDADD) $(LIBS) test_gic$(EXEEXT): $(test_gic_OBJECTS) $(test_gic_DEPENDENCIES) $(EXTRA_test_gic_DEPENDENCIES) @rm -f test_gic$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_gic_OBJECTS) $(test_gic_LDADD) $(LIBS) test_hostname$(EXEEXT): $(test_hostname_OBJECTS) $(test_hostname_DEPENDENCIES) $(EXTRA_test_hostname_DEPENDENCIES) @rm -f test_hostname$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_hostname_OBJECTS) $(test_hostname_LDADD) $(LIBS) test_keytab$(EXEEXT): $(test_keytab_OBJECTS) $(test_keytab_DEPENDENCIES) $(EXTRA_test_keytab_DEPENDENCIES) @rm -f test_keytab$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_keytab_OBJECTS) $(test_keytab_LDADD) $(LIBS) test_kuserok$(EXEEXT): $(test_kuserok_OBJECTS) $(test_kuserok_DEPENDENCIES) $(EXTRA_test_kuserok_DEPENDENCIES) @rm -f test_kuserok$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_kuserok_OBJECTS) $(test_kuserok_LDADD) $(LIBS) test_mem$(EXEEXT): $(test_mem_OBJECTS) $(test_mem_DEPENDENCIES) $(EXTRA_test_mem_DEPENDENCIES) @rm -f test_mem$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_mem_OBJECTS) $(test_mem_LDADD) $(LIBS) test_pac$(EXEEXT): $(test_pac_OBJECTS) $(test_pac_DEPENDENCIES) $(EXTRA_test_pac_DEPENDENCIES) @rm -f test_pac$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_pac_OBJECTS) $(test_pac_LDADD) $(LIBS) test_pkinit_dh2key$(EXEEXT): $(test_pkinit_dh2key_OBJECTS) $(test_pkinit_dh2key_DEPENDENCIES) $(EXTRA_test_pkinit_dh2key_DEPENDENCIES) @rm -f test_pkinit_dh2key$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_pkinit_dh2key_OBJECTS) $(test_pkinit_dh2key_LDADD) $(LIBS) test_pknistkdf$(EXEEXT): $(test_pknistkdf_OBJECTS) $(test_pknistkdf_DEPENDENCIES) $(EXTRA_test_pknistkdf_DEPENDENCIES) @rm -f test_pknistkdf$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_pknistkdf_OBJECTS) $(test_pknistkdf_LDADD) $(LIBS) test_plugin$(EXEEXT): $(test_plugin_OBJECTS) $(test_plugin_DEPENDENCIES) $(EXTRA_test_plugin_DEPENDENCIES) @rm -f test_plugin$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_plugin_OBJECTS) $(test_plugin_LDADD) $(LIBS) test_prf$(EXEEXT): $(test_prf_OBJECTS) $(test_prf_DEPENDENCIES) $(EXTRA_test_prf_DEPENDENCIES) @rm -f test_prf$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_prf_OBJECTS) $(test_prf_LDADD) $(LIBS) test_princ$(EXEEXT): $(test_princ_OBJECTS) $(test_princ_DEPENDENCIES) $(EXTRA_test_princ_DEPENDENCIES) @rm -f test_princ$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_princ_OBJECTS) $(test_princ_LDADD) $(LIBS) test_renew$(EXEEXT): $(test_renew_OBJECTS) $(test_renew_DEPENDENCIES) $(EXTRA_test_renew_DEPENDENCIES) @rm -f test_renew$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_renew_OBJECTS) $(test_renew_LDADD) $(LIBS) test_rfc3961$(EXEEXT): $(test_rfc3961_OBJECTS) $(test_rfc3961_DEPENDENCIES) $(EXTRA_test_rfc3961_DEPENDENCIES) @rm -f test_rfc3961$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_rfc3961_OBJECTS) $(test_rfc3961_LDADD) $(LIBS) test_set_kvno0$(EXEEXT): $(test_set_kvno0_OBJECTS) $(test_set_kvno0_DEPENDENCIES) $(EXTRA_test_set_kvno0_DEPENDENCIES) @rm -f test_set_kvno0$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_set_kvno0_OBJECTS) $(test_set_kvno0_LDADD) $(LIBS) test_store$(EXEEXT): $(test_store_OBJECTS) $(test_store_DEPENDENCIES) $(EXTRA_test_store_DEPENDENCIES) @rm -f test_store$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_store_OBJECTS) $(test_store_LDADD) $(LIBS) test_time$(EXEEXT): $(test_time_OBJECTS) $(test_time_DEPENDENCIES) $(EXTRA_test_time_DEPENDENCIES) @rm -f test_time$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_time_OBJECTS) $(test_time_LDADD) $(LIBS) test_x500$(EXEEXT): $(test_x500_OBJECTS) $(test_x500_DEPENDENCIES) $(EXTRA_test_x500_DEPENDENCIES) @rm -f test_x500$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_x500_OBJECTS) $(test_x500_LDADD) $(LIBS) verify_krb5_conf$(EXEEXT): $(verify_krb5_conf_OBJECTS) $(verify_krb5_conf_DEPENDENCIES) $(EXTRA_verify_krb5_conf_DEPENDENCIES) @rm -f verify_krb5_conf$(EXEEXT) $(AM_V_CCLD)$(LINK) $(verify_krb5_conf_OBJECTS) $(verify_krb5_conf_LDADD) $(LIBS) mostlyclean-compile: -rm -f *.$(OBJEXT) distclean-compile: -rm -f *.tab.c @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/aes-test.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/derived-key-test.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/krbhst-test.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libkrb5_la-acache.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libkrb5_la-acl.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libkrb5_la-add_et_list.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libkrb5_la-addr_families.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libkrb5_la-aname_to_localname.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libkrb5_la-appdefault.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libkrb5_la-asn1_glue.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libkrb5_la-auth_context.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libkrb5_la-build_ap_req.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libkrb5_la-build_auth.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libkrb5_la-cache.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libkrb5_la-changepw.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libkrb5_la-codec.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libkrb5_la-config_file.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libkrb5_la-constants.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libkrb5_la-context.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libkrb5_la-convert_creds.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libkrb5_la-copy_host_realm.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libkrb5_la-crc.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libkrb5_la-creds.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libkrb5_la-crypto-aes-sha1.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libkrb5_la-crypto-aes-sha2.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libkrb5_la-crypto-algs.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libkrb5_la-crypto-arcfour.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libkrb5_la-crypto-des-common.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libkrb5_la-crypto-des.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libkrb5_la-crypto-des3.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libkrb5_la-crypto-evp.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libkrb5_la-crypto-null.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libkrb5_la-crypto-pk.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libkrb5_la-crypto-rand.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libkrb5_la-crypto.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libkrb5_la-data.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libkrb5_la-db_plugin.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libkrb5_la-dcache.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libkrb5_la-deprecated.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libkrb5_la-digest.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libkrb5_la-doxygen.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libkrb5_la-eai_to_heim_errno.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libkrb5_la-enomem.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libkrb5_la-error_string.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libkrb5_la-expand_hostname.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libkrb5_la-expand_path.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libkrb5_la-fast.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libkrb5_la-fcache.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libkrb5_la-free.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libkrb5_la-free_host_realm.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libkrb5_la-generate_seq_number.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libkrb5_la-generate_subkey.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libkrb5_la-get_addrs.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libkrb5_la-get_cred.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libkrb5_la-get_default_principal.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libkrb5_la-get_default_realm.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libkrb5_la-get_for_creds.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libkrb5_la-get_host_realm.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libkrb5_la-get_in_tkt.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libkrb5_la-get_port.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libkrb5_la-heim_err.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libkrb5_la-init_creds.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libkrb5_la-init_creds_pw.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libkrb5_la-k524_err.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libkrb5_la-kcm.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libkrb5_la-keyblock.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libkrb5_la-keytab.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libkrb5_la-keytab_any.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libkrb5_la-keytab_file.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libkrb5_la-keytab_keyfile.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libkrb5_la-keytab_memory.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libkrb5_la-krb5_err.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libkrb5_la-krb_err.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libkrb5_la-krbhst.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libkrb5_la-kuserok.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libkrb5_la-log.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libkrb5_la-mcache.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libkrb5_la-misc.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libkrb5_la-mit_glue.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libkrb5_la-mk_error.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libkrb5_la-mk_priv.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libkrb5_la-mk_rep.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libkrb5_la-mk_req.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libkrb5_la-mk_req_ext.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libkrb5_la-mk_safe.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libkrb5_la-n-fold.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libkrb5_la-net_read.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libkrb5_la-net_write.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libkrb5_la-pac.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libkrb5_la-padata.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libkrb5_la-pcache.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libkrb5_la-pkinit-ec.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libkrb5_la-pkinit.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libkrb5_la-plugin.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libkrb5_la-principal.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libkrb5_la-prog_setup.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libkrb5_la-prompter_posix.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libkrb5_la-rd_cred.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libkrb5_la-rd_error.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libkrb5_la-rd_priv.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libkrb5_la-rd_rep.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libkrb5_la-rd_req.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libkrb5_la-rd_safe.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libkrb5_la-read_message.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libkrb5_la-recvauth.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libkrb5_la-replay.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libkrb5_la-salt-aes-sha1.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libkrb5_la-salt-aes-sha2.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libkrb5_la-salt-arcfour.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libkrb5_la-salt-des.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libkrb5_la-salt-des3.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libkrb5_la-salt.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libkrb5_la-scache.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libkrb5_la-send_to_kdc.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libkrb5_la-sendauth.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libkrb5_la-set_default_realm.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libkrb5_la-sock_principal.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libkrb5_la-sp800-108-kdf.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libkrb5_la-store-int.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libkrb5_la-store.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libkrb5_la-store_emem.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libkrb5_la-store_fd.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libkrb5_la-store_mem.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libkrb5_la-store_sock.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libkrb5_la-ticket.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libkrb5_la-time.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libkrb5_la-transited.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libkrb5_la-verify_init.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libkrb5_la-verify_user.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libkrb5_la-version.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libkrb5_la-warn.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libkrb5_la-write_message.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/librfc3961_la-crc.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/librfc3961_la-crypto-aes-sha1.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/librfc3961_la-crypto-aes-sha2.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/librfc3961_la-crypto-algs.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/librfc3961_la-crypto-arcfour.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/librfc3961_la-crypto-des-common.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/librfc3961_la-crypto-des.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/librfc3961_la-crypto-des3.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/librfc3961_la-crypto-evp.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/librfc3961_la-crypto-null.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/librfc3961_la-crypto-pk.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/librfc3961_la-crypto-rand.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/librfc3961_la-crypto-stubs.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/librfc3961_la-crypto.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/librfc3961_la-data.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/librfc3961_la-enomem.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/librfc3961_la-error_string.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/librfc3961_la-keyblock.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/librfc3961_la-n-fold.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/librfc3961_la-salt-aes-sha1.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/librfc3961_la-salt-aes-sha2.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/librfc3961_la-salt-arcfour.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/librfc3961_la-salt-des.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/librfc3961_la-salt-des3.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/librfc3961_la-salt.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/librfc3961_la-sp800-108-kdf.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/librfc3961_la-store-int.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/librfc3961_la-warn.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/n-fold-test.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/parse-name-test.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/pseudo-random-test.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/store-test.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/string-to-key-test.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_acl.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_addr.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_alname.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_ap-req.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_canon.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_cc.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_config.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_crypto.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_crypto_wrapping.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_expand_toks.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_forward.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_fx.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_get_addrs.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_gic.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_hostname.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_keytab.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_kuserok.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_mem.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_pac.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_pkinit_dh2key.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_pknistkdf.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_plugin.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_prf.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_princ.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_renew.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_rfc3961.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_set_kvno0.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_store.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_time.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_x500.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/verify_krb5_conf.Po@am__quote@ .c.o: @am__fastdepCC_TRUE@ $(AM_V_CC)$(COMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o $@ $< @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='$<' object='$@' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(COMPILE) -c -o $@ $< .c.obj: @am__fastdepCC_TRUE@ $(AM_V_CC)$(COMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o $@ `$(CYGPATH_W) '$<'` @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='$<' object='$@' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(COMPILE) -c -o $@ `$(CYGPATH_W) '$<'` .c.lo: @am__fastdepCC_TRUE@ $(AM_V_CC)$(LTCOMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o $@ $< @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='$<' object='$@' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LTCOMPILE) -c -o $@ $< libkrb5_la-acache.lo: acache.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libkrb5_la-acache.lo -MD -MP -MF $(DEPDIR)/libkrb5_la-acache.Tpo -c -o libkrb5_la-acache.lo `test -f 'acache.c' || echo '$(srcdir)/'`acache.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libkrb5_la-acache.Tpo $(DEPDIR)/libkrb5_la-acache.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='acache.c' object='libkrb5_la-acache.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-acache.lo `test -f 'acache.c' || echo '$(srcdir)/'`acache.c libkrb5_la-acl.lo: acl.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libkrb5_la-acl.lo -MD -MP -MF $(DEPDIR)/libkrb5_la-acl.Tpo -c -o libkrb5_la-acl.lo `test -f 'acl.c' || echo '$(srcdir)/'`acl.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libkrb5_la-acl.Tpo $(DEPDIR)/libkrb5_la-acl.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='acl.c' object='libkrb5_la-acl.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-acl.lo `test -f 'acl.c' || echo '$(srcdir)/'`acl.c libkrb5_la-add_et_list.lo: add_et_list.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libkrb5_la-add_et_list.lo -MD -MP -MF $(DEPDIR)/libkrb5_la-add_et_list.Tpo -c -o libkrb5_la-add_et_list.lo `test -f 'add_et_list.c' || echo '$(srcdir)/'`add_et_list.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libkrb5_la-add_et_list.Tpo $(DEPDIR)/libkrb5_la-add_et_list.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='add_et_list.c' object='libkrb5_la-add_et_list.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-add_et_list.lo `test -f 'add_et_list.c' || echo '$(srcdir)/'`add_et_list.c libkrb5_la-addr_families.lo: addr_families.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libkrb5_la-addr_families.lo -MD -MP -MF $(DEPDIR)/libkrb5_la-addr_families.Tpo -c -o libkrb5_la-addr_families.lo `test -f 'addr_families.c' || echo '$(srcdir)/'`addr_families.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libkrb5_la-addr_families.Tpo $(DEPDIR)/libkrb5_la-addr_families.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='addr_families.c' object='libkrb5_la-addr_families.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-addr_families.lo `test -f 'addr_families.c' || echo '$(srcdir)/'`addr_families.c libkrb5_la-aname_to_localname.lo: aname_to_localname.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libkrb5_la-aname_to_localname.lo -MD -MP -MF $(DEPDIR)/libkrb5_la-aname_to_localname.Tpo -c -o libkrb5_la-aname_to_localname.lo `test -f 'aname_to_localname.c' || echo '$(srcdir)/'`aname_to_localname.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libkrb5_la-aname_to_localname.Tpo $(DEPDIR)/libkrb5_la-aname_to_localname.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='aname_to_localname.c' object='libkrb5_la-aname_to_localname.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-aname_to_localname.lo `test -f 'aname_to_localname.c' || echo '$(srcdir)/'`aname_to_localname.c libkrb5_la-appdefault.lo: appdefault.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libkrb5_la-appdefault.lo -MD -MP -MF $(DEPDIR)/libkrb5_la-appdefault.Tpo -c -o libkrb5_la-appdefault.lo `test -f 'appdefault.c' || echo '$(srcdir)/'`appdefault.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libkrb5_la-appdefault.Tpo $(DEPDIR)/libkrb5_la-appdefault.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='appdefault.c' object='libkrb5_la-appdefault.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-appdefault.lo `test -f 'appdefault.c' || echo '$(srcdir)/'`appdefault.c libkrb5_la-asn1_glue.lo: asn1_glue.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libkrb5_la-asn1_glue.lo -MD -MP -MF $(DEPDIR)/libkrb5_la-asn1_glue.Tpo -c -o libkrb5_la-asn1_glue.lo `test -f 'asn1_glue.c' || echo '$(srcdir)/'`asn1_glue.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libkrb5_la-asn1_glue.Tpo $(DEPDIR)/libkrb5_la-asn1_glue.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='asn1_glue.c' object='libkrb5_la-asn1_glue.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-asn1_glue.lo `test -f 'asn1_glue.c' || echo '$(srcdir)/'`asn1_glue.c libkrb5_la-auth_context.lo: auth_context.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libkrb5_la-auth_context.lo -MD -MP -MF $(DEPDIR)/libkrb5_la-auth_context.Tpo -c -o libkrb5_la-auth_context.lo `test -f 'auth_context.c' || echo '$(srcdir)/'`auth_context.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libkrb5_la-auth_context.Tpo $(DEPDIR)/libkrb5_la-auth_context.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='auth_context.c' object='libkrb5_la-auth_context.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-auth_context.lo `test -f 'auth_context.c' || echo '$(srcdir)/'`auth_context.c libkrb5_la-build_ap_req.lo: build_ap_req.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libkrb5_la-build_ap_req.lo -MD -MP -MF $(DEPDIR)/libkrb5_la-build_ap_req.Tpo -c -o libkrb5_la-build_ap_req.lo `test -f 'build_ap_req.c' || echo '$(srcdir)/'`build_ap_req.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libkrb5_la-build_ap_req.Tpo $(DEPDIR)/libkrb5_la-build_ap_req.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='build_ap_req.c' object='libkrb5_la-build_ap_req.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-build_ap_req.lo `test -f 'build_ap_req.c' || echo '$(srcdir)/'`build_ap_req.c libkrb5_la-build_auth.lo: build_auth.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libkrb5_la-build_auth.lo -MD -MP -MF $(DEPDIR)/libkrb5_la-build_auth.Tpo -c -o libkrb5_la-build_auth.lo `test -f 'build_auth.c' || echo '$(srcdir)/'`build_auth.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libkrb5_la-build_auth.Tpo $(DEPDIR)/libkrb5_la-build_auth.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='build_auth.c' object='libkrb5_la-build_auth.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-build_auth.lo `test -f 'build_auth.c' || echo '$(srcdir)/'`build_auth.c libkrb5_la-cache.lo: cache.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libkrb5_la-cache.lo -MD -MP -MF $(DEPDIR)/libkrb5_la-cache.Tpo -c -o libkrb5_la-cache.lo `test -f 'cache.c' || echo '$(srcdir)/'`cache.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libkrb5_la-cache.Tpo $(DEPDIR)/libkrb5_la-cache.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='cache.c' object='libkrb5_la-cache.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-cache.lo `test -f 'cache.c' || echo '$(srcdir)/'`cache.c libkrb5_la-changepw.lo: changepw.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libkrb5_la-changepw.lo -MD -MP -MF $(DEPDIR)/libkrb5_la-changepw.Tpo -c -o libkrb5_la-changepw.lo `test -f 'changepw.c' || echo '$(srcdir)/'`changepw.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libkrb5_la-changepw.Tpo $(DEPDIR)/libkrb5_la-changepw.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='changepw.c' object='libkrb5_la-changepw.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-changepw.lo `test -f 'changepw.c' || echo '$(srcdir)/'`changepw.c libkrb5_la-codec.lo: codec.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libkrb5_la-codec.lo -MD -MP -MF $(DEPDIR)/libkrb5_la-codec.Tpo -c -o libkrb5_la-codec.lo `test -f 'codec.c' || echo '$(srcdir)/'`codec.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libkrb5_la-codec.Tpo $(DEPDIR)/libkrb5_la-codec.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='codec.c' object='libkrb5_la-codec.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-codec.lo `test -f 'codec.c' || echo '$(srcdir)/'`codec.c libkrb5_la-config_file.lo: config_file.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libkrb5_la-config_file.lo -MD -MP -MF $(DEPDIR)/libkrb5_la-config_file.Tpo -c -o libkrb5_la-config_file.lo `test -f 'config_file.c' || echo '$(srcdir)/'`config_file.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libkrb5_la-config_file.Tpo $(DEPDIR)/libkrb5_la-config_file.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='config_file.c' object='libkrb5_la-config_file.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-config_file.lo `test -f 'config_file.c' || echo '$(srcdir)/'`config_file.c libkrb5_la-convert_creds.lo: convert_creds.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libkrb5_la-convert_creds.lo -MD -MP -MF $(DEPDIR)/libkrb5_la-convert_creds.Tpo -c -o libkrb5_la-convert_creds.lo `test -f 'convert_creds.c' || echo '$(srcdir)/'`convert_creds.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libkrb5_la-convert_creds.Tpo $(DEPDIR)/libkrb5_la-convert_creds.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='convert_creds.c' object='libkrb5_la-convert_creds.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-convert_creds.lo `test -f 'convert_creds.c' || echo '$(srcdir)/'`convert_creds.c libkrb5_la-constants.lo: constants.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libkrb5_la-constants.lo -MD -MP -MF $(DEPDIR)/libkrb5_la-constants.Tpo -c -o libkrb5_la-constants.lo `test -f 'constants.c' || echo '$(srcdir)/'`constants.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libkrb5_la-constants.Tpo $(DEPDIR)/libkrb5_la-constants.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='constants.c' object='libkrb5_la-constants.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-constants.lo `test -f 'constants.c' || echo '$(srcdir)/'`constants.c libkrb5_la-context.lo: context.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libkrb5_la-context.lo -MD -MP -MF $(DEPDIR)/libkrb5_la-context.Tpo -c -o libkrb5_la-context.lo `test -f 'context.c' || echo '$(srcdir)/'`context.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libkrb5_la-context.Tpo $(DEPDIR)/libkrb5_la-context.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='context.c' object='libkrb5_la-context.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-context.lo `test -f 'context.c' || echo '$(srcdir)/'`context.c libkrb5_la-copy_host_realm.lo: copy_host_realm.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libkrb5_la-copy_host_realm.lo -MD -MP -MF $(DEPDIR)/libkrb5_la-copy_host_realm.Tpo -c -o libkrb5_la-copy_host_realm.lo `test -f 'copy_host_realm.c' || echo '$(srcdir)/'`copy_host_realm.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libkrb5_la-copy_host_realm.Tpo $(DEPDIR)/libkrb5_la-copy_host_realm.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='copy_host_realm.c' object='libkrb5_la-copy_host_realm.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-copy_host_realm.lo `test -f 'copy_host_realm.c' || echo '$(srcdir)/'`copy_host_realm.c libkrb5_la-crc.lo: crc.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libkrb5_la-crc.lo -MD -MP -MF $(DEPDIR)/libkrb5_la-crc.Tpo -c -o libkrb5_la-crc.lo `test -f 'crc.c' || echo '$(srcdir)/'`crc.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libkrb5_la-crc.Tpo $(DEPDIR)/libkrb5_la-crc.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='crc.c' object='libkrb5_la-crc.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-crc.lo `test -f 'crc.c' || echo '$(srcdir)/'`crc.c libkrb5_la-creds.lo: creds.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libkrb5_la-creds.lo -MD -MP -MF $(DEPDIR)/libkrb5_la-creds.Tpo -c -o libkrb5_la-creds.lo `test -f 'creds.c' || echo '$(srcdir)/'`creds.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libkrb5_la-creds.Tpo $(DEPDIR)/libkrb5_la-creds.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='creds.c' object='libkrb5_la-creds.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-creds.lo `test -f 'creds.c' || echo '$(srcdir)/'`creds.c libkrb5_la-crypto.lo: crypto.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libkrb5_la-crypto.lo -MD -MP -MF $(DEPDIR)/libkrb5_la-crypto.Tpo -c -o libkrb5_la-crypto.lo `test -f 'crypto.c' || echo '$(srcdir)/'`crypto.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libkrb5_la-crypto.Tpo $(DEPDIR)/libkrb5_la-crypto.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='crypto.c' object='libkrb5_la-crypto.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-crypto.lo `test -f 'crypto.c' || echo '$(srcdir)/'`crypto.c libkrb5_la-crypto-aes-sha1.lo: crypto-aes-sha1.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libkrb5_la-crypto-aes-sha1.lo -MD -MP -MF $(DEPDIR)/libkrb5_la-crypto-aes-sha1.Tpo -c -o libkrb5_la-crypto-aes-sha1.lo `test -f 'crypto-aes-sha1.c' || echo '$(srcdir)/'`crypto-aes-sha1.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libkrb5_la-crypto-aes-sha1.Tpo $(DEPDIR)/libkrb5_la-crypto-aes-sha1.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='crypto-aes-sha1.c' object='libkrb5_la-crypto-aes-sha1.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-crypto-aes-sha1.lo `test -f 'crypto-aes-sha1.c' || echo '$(srcdir)/'`crypto-aes-sha1.c libkrb5_la-crypto-aes-sha2.lo: crypto-aes-sha2.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libkrb5_la-crypto-aes-sha2.lo -MD -MP -MF $(DEPDIR)/libkrb5_la-crypto-aes-sha2.Tpo -c -o libkrb5_la-crypto-aes-sha2.lo `test -f 'crypto-aes-sha2.c' || echo '$(srcdir)/'`crypto-aes-sha2.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libkrb5_la-crypto-aes-sha2.Tpo $(DEPDIR)/libkrb5_la-crypto-aes-sha2.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='crypto-aes-sha2.c' object='libkrb5_la-crypto-aes-sha2.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-crypto-aes-sha2.lo `test -f 'crypto-aes-sha2.c' || echo '$(srcdir)/'`crypto-aes-sha2.c libkrb5_la-crypto-algs.lo: crypto-algs.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libkrb5_la-crypto-algs.lo -MD -MP -MF $(DEPDIR)/libkrb5_la-crypto-algs.Tpo -c -o libkrb5_la-crypto-algs.lo `test -f 'crypto-algs.c' || echo '$(srcdir)/'`crypto-algs.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libkrb5_la-crypto-algs.Tpo $(DEPDIR)/libkrb5_la-crypto-algs.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='crypto-algs.c' object='libkrb5_la-crypto-algs.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-crypto-algs.lo `test -f 'crypto-algs.c' || echo '$(srcdir)/'`crypto-algs.c libkrb5_la-crypto-arcfour.lo: crypto-arcfour.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libkrb5_la-crypto-arcfour.lo -MD -MP -MF $(DEPDIR)/libkrb5_la-crypto-arcfour.Tpo -c -o libkrb5_la-crypto-arcfour.lo `test -f 'crypto-arcfour.c' || echo '$(srcdir)/'`crypto-arcfour.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libkrb5_la-crypto-arcfour.Tpo $(DEPDIR)/libkrb5_la-crypto-arcfour.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='crypto-arcfour.c' object='libkrb5_la-crypto-arcfour.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-crypto-arcfour.lo `test -f 'crypto-arcfour.c' || echo '$(srcdir)/'`crypto-arcfour.c libkrb5_la-crypto-des.lo: crypto-des.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libkrb5_la-crypto-des.lo -MD -MP -MF $(DEPDIR)/libkrb5_la-crypto-des.Tpo -c -o libkrb5_la-crypto-des.lo `test -f 'crypto-des.c' || echo '$(srcdir)/'`crypto-des.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libkrb5_la-crypto-des.Tpo $(DEPDIR)/libkrb5_la-crypto-des.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='crypto-des.c' object='libkrb5_la-crypto-des.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-crypto-des.lo `test -f 'crypto-des.c' || echo '$(srcdir)/'`crypto-des.c libkrb5_la-crypto-des-common.lo: crypto-des-common.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libkrb5_la-crypto-des-common.lo -MD -MP -MF $(DEPDIR)/libkrb5_la-crypto-des-common.Tpo -c -o libkrb5_la-crypto-des-common.lo `test -f 'crypto-des-common.c' || echo '$(srcdir)/'`crypto-des-common.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libkrb5_la-crypto-des-common.Tpo $(DEPDIR)/libkrb5_la-crypto-des-common.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='crypto-des-common.c' object='libkrb5_la-crypto-des-common.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-crypto-des-common.lo `test -f 'crypto-des-common.c' || echo '$(srcdir)/'`crypto-des-common.c libkrb5_la-crypto-des3.lo: crypto-des3.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libkrb5_la-crypto-des3.lo -MD -MP -MF $(DEPDIR)/libkrb5_la-crypto-des3.Tpo -c -o libkrb5_la-crypto-des3.lo `test -f 'crypto-des3.c' || echo '$(srcdir)/'`crypto-des3.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libkrb5_la-crypto-des3.Tpo $(DEPDIR)/libkrb5_la-crypto-des3.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='crypto-des3.c' object='libkrb5_la-crypto-des3.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-crypto-des3.lo `test -f 'crypto-des3.c' || echo '$(srcdir)/'`crypto-des3.c libkrb5_la-crypto-evp.lo: crypto-evp.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libkrb5_la-crypto-evp.lo -MD -MP -MF $(DEPDIR)/libkrb5_la-crypto-evp.Tpo -c -o libkrb5_la-crypto-evp.lo `test -f 'crypto-evp.c' || echo '$(srcdir)/'`crypto-evp.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libkrb5_la-crypto-evp.Tpo $(DEPDIR)/libkrb5_la-crypto-evp.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='crypto-evp.c' object='libkrb5_la-crypto-evp.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-crypto-evp.lo `test -f 'crypto-evp.c' || echo '$(srcdir)/'`crypto-evp.c libkrb5_la-crypto-null.lo: crypto-null.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libkrb5_la-crypto-null.lo -MD -MP -MF $(DEPDIR)/libkrb5_la-crypto-null.Tpo -c -o libkrb5_la-crypto-null.lo `test -f 'crypto-null.c' || echo '$(srcdir)/'`crypto-null.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libkrb5_la-crypto-null.Tpo $(DEPDIR)/libkrb5_la-crypto-null.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='crypto-null.c' object='libkrb5_la-crypto-null.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-crypto-null.lo `test -f 'crypto-null.c' || echo '$(srcdir)/'`crypto-null.c libkrb5_la-crypto-pk.lo: crypto-pk.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libkrb5_la-crypto-pk.lo -MD -MP -MF $(DEPDIR)/libkrb5_la-crypto-pk.Tpo -c -o libkrb5_la-crypto-pk.lo `test -f 'crypto-pk.c' || echo '$(srcdir)/'`crypto-pk.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libkrb5_la-crypto-pk.Tpo $(DEPDIR)/libkrb5_la-crypto-pk.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='crypto-pk.c' object='libkrb5_la-crypto-pk.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-crypto-pk.lo `test -f 'crypto-pk.c' || echo '$(srcdir)/'`crypto-pk.c libkrb5_la-crypto-rand.lo: crypto-rand.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libkrb5_la-crypto-rand.lo -MD -MP -MF $(DEPDIR)/libkrb5_la-crypto-rand.Tpo -c -o libkrb5_la-crypto-rand.lo `test -f 'crypto-rand.c' || echo '$(srcdir)/'`crypto-rand.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libkrb5_la-crypto-rand.Tpo $(DEPDIR)/libkrb5_la-crypto-rand.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='crypto-rand.c' object='libkrb5_la-crypto-rand.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-crypto-rand.lo `test -f 'crypto-rand.c' || echo '$(srcdir)/'`crypto-rand.c libkrb5_la-doxygen.lo: doxygen.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libkrb5_la-doxygen.lo -MD -MP -MF $(DEPDIR)/libkrb5_la-doxygen.Tpo -c -o libkrb5_la-doxygen.lo `test -f 'doxygen.c' || echo '$(srcdir)/'`doxygen.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libkrb5_la-doxygen.Tpo $(DEPDIR)/libkrb5_la-doxygen.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='doxygen.c' object='libkrb5_la-doxygen.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-doxygen.lo `test -f 'doxygen.c' || echo '$(srcdir)/'`doxygen.c libkrb5_la-data.lo: data.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libkrb5_la-data.lo -MD -MP -MF $(DEPDIR)/libkrb5_la-data.Tpo -c -o libkrb5_la-data.lo `test -f 'data.c' || echo '$(srcdir)/'`data.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libkrb5_la-data.Tpo $(DEPDIR)/libkrb5_la-data.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='data.c' object='libkrb5_la-data.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-data.lo `test -f 'data.c' || echo '$(srcdir)/'`data.c libkrb5_la-db_plugin.lo: db_plugin.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libkrb5_la-db_plugin.lo -MD -MP -MF $(DEPDIR)/libkrb5_la-db_plugin.Tpo -c -o libkrb5_la-db_plugin.lo `test -f 'db_plugin.c' || echo '$(srcdir)/'`db_plugin.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libkrb5_la-db_plugin.Tpo $(DEPDIR)/libkrb5_la-db_plugin.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='db_plugin.c' object='libkrb5_la-db_plugin.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-db_plugin.lo `test -f 'db_plugin.c' || echo '$(srcdir)/'`db_plugin.c libkrb5_la-dcache.lo: dcache.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libkrb5_la-dcache.lo -MD -MP -MF $(DEPDIR)/libkrb5_la-dcache.Tpo -c -o libkrb5_la-dcache.lo `test -f 'dcache.c' || echo '$(srcdir)/'`dcache.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libkrb5_la-dcache.Tpo $(DEPDIR)/libkrb5_la-dcache.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='dcache.c' object='libkrb5_la-dcache.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-dcache.lo `test -f 'dcache.c' || echo '$(srcdir)/'`dcache.c libkrb5_la-deprecated.lo: deprecated.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libkrb5_la-deprecated.lo -MD -MP -MF $(DEPDIR)/libkrb5_la-deprecated.Tpo -c -o libkrb5_la-deprecated.lo `test -f 'deprecated.c' || echo '$(srcdir)/'`deprecated.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libkrb5_la-deprecated.Tpo $(DEPDIR)/libkrb5_la-deprecated.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='deprecated.c' object='libkrb5_la-deprecated.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-deprecated.lo `test -f 'deprecated.c' || echo '$(srcdir)/'`deprecated.c libkrb5_la-digest.lo: digest.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libkrb5_la-digest.lo -MD -MP -MF $(DEPDIR)/libkrb5_la-digest.Tpo -c -o libkrb5_la-digest.lo `test -f 'digest.c' || echo '$(srcdir)/'`digest.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libkrb5_la-digest.Tpo $(DEPDIR)/libkrb5_la-digest.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='digest.c' object='libkrb5_la-digest.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-digest.lo `test -f 'digest.c' || echo '$(srcdir)/'`digest.c libkrb5_la-eai_to_heim_errno.lo: eai_to_heim_errno.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libkrb5_la-eai_to_heim_errno.lo -MD -MP -MF $(DEPDIR)/libkrb5_la-eai_to_heim_errno.Tpo -c -o libkrb5_la-eai_to_heim_errno.lo `test -f 'eai_to_heim_errno.c' || echo '$(srcdir)/'`eai_to_heim_errno.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libkrb5_la-eai_to_heim_errno.Tpo $(DEPDIR)/libkrb5_la-eai_to_heim_errno.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='eai_to_heim_errno.c' object='libkrb5_la-eai_to_heim_errno.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-eai_to_heim_errno.lo `test -f 'eai_to_heim_errno.c' || echo '$(srcdir)/'`eai_to_heim_errno.c libkrb5_la-enomem.lo: enomem.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libkrb5_la-enomem.lo -MD -MP -MF $(DEPDIR)/libkrb5_la-enomem.Tpo -c -o libkrb5_la-enomem.lo `test -f 'enomem.c' || echo '$(srcdir)/'`enomem.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libkrb5_la-enomem.Tpo $(DEPDIR)/libkrb5_la-enomem.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='enomem.c' object='libkrb5_la-enomem.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-enomem.lo `test -f 'enomem.c' || echo '$(srcdir)/'`enomem.c libkrb5_la-error_string.lo: error_string.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libkrb5_la-error_string.lo -MD -MP -MF $(DEPDIR)/libkrb5_la-error_string.Tpo -c -o libkrb5_la-error_string.lo `test -f 'error_string.c' || echo '$(srcdir)/'`error_string.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libkrb5_la-error_string.Tpo $(DEPDIR)/libkrb5_la-error_string.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='error_string.c' object='libkrb5_la-error_string.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-error_string.lo `test -f 'error_string.c' || echo '$(srcdir)/'`error_string.c libkrb5_la-expand_hostname.lo: expand_hostname.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libkrb5_la-expand_hostname.lo -MD -MP -MF $(DEPDIR)/libkrb5_la-expand_hostname.Tpo -c -o libkrb5_la-expand_hostname.lo `test -f 'expand_hostname.c' || echo '$(srcdir)/'`expand_hostname.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libkrb5_la-expand_hostname.Tpo $(DEPDIR)/libkrb5_la-expand_hostname.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='expand_hostname.c' object='libkrb5_la-expand_hostname.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-expand_hostname.lo `test -f 'expand_hostname.c' || echo '$(srcdir)/'`expand_hostname.c libkrb5_la-expand_path.lo: expand_path.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libkrb5_la-expand_path.lo -MD -MP -MF $(DEPDIR)/libkrb5_la-expand_path.Tpo -c -o libkrb5_la-expand_path.lo `test -f 'expand_path.c' || echo '$(srcdir)/'`expand_path.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libkrb5_la-expand_path.Tpo $(DEPDIR)/libkrb5_la-expand_path.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='expand_path.c' object='libkrb5_la-expand_path.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-expand_path.lo `test -f 'expand_path.c' || echo '$(srcdir)/'`expand_path.c libkrb5_la-fast.lo: fast.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libkrb5_la-fast.lo -MD -MP -MF $(DEPDIR)/libkrb5_la-fast.Tpo -c -o libkrb5_la-fast.lo `test -f 'fast.c' || echo '$(srcdir)/'`fast.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libkrb5_la-fast.Tpo $(DEPDIR)/libkrb5_la-fast.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='fast.c' object='libkrb5_la-fast.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-fast.lo `test -f 'fast.c' || echo '$(srcdir)/'`fast.c libkrb5_la-fcache.lo: fcache.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libkrb5_la-fcache.lo -MD -MP -MF $(DEPDIR)/libkrb5_la-fcache.Tpo -c -o libkrb5_la-fcache.lo `test -f 'fcache.c' || echo '$(srcdir)/'`fcache.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libkrb5_la-fcache.Tpo $(DEPDIR)/libkrb5_la-fcache.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='fcache.c' object='libkrb5_la-fcache.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-fcache.lo `test -f 'fcache.c' || echo '$(srcdir)/'`fcache.c libkrb5_la-free.lo: free.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libkrb5_la-free.lo -MD -MP -MF $(DEPDIR)/libkrb5_la-free.Tpo -c -o libkrb5_la-free.lo `test -f 'free.c' || echo '$(srcdir)/'`free.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libkrb5_la-free.Tpo $(DEPDIR)/libkrb5_la-free.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='free.c' object='libkrb5_la-free.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-free.lo `test -f 'free.c' || echo '$(srcdir)/'`free.c libkrb5_la-free_host_realm.lo: free_host_realm.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libkrb5_la-free_host_realm.lo -MD -MP -MF $(DEPDIR)/libkrb5_la-free_host_realm.Tpo -c -o libkrb5_la-free_host_realm.lo `test -f 'free_host_realm.c' || echo '$(srcdir)/'`free_host_realm.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libkrb5_la-free_host_realm.Tpo $(DEPDIR)/libkrb5_la-free_host_realm.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='free_host_realm.c' object='libkrb5_la-free_host_realm.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-free_host_realm.lo `test -f 'free_host_realm.c' || echo '$(srcdir)/'`free_host_realm.c libkrb5_la-generate_seq_number.lo: generate_seq_number.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libkrb5_la-generate_seq_number.lo -MD -MP -MF $(DEPDIR)/libkrb5_la-generate_seq_number.Tpo -c -o libkrb5_la-generate_seq_number.lo `test -f 'generate_seq_number.c' || echo '$(srcdir)/'`generate_seq_number.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libkrb5_la-generate_seq_number.Tpo $(DEPDIR)/libkrb5_la-generate_seq_number.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='generate_seq_number.c' object='libkrb5_la-generate_seq_number.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-generate_seq_number.lo `test -f 'generate_seq_number.c' || echo '$(srcdir)/'`generate_seq_number.c libkrb5_la-generate_subkey.lo: generate_subkey.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libkrb5_la-generate_subkey.lo -MD -MP -MF $(DEPDIR)/libkrb5_la-generate_subkey.Tpo -c -o libkrb5_la-generate_subkey.lo `test -f 'generate_subkey.c' || echo '$(srcdir)/'`generate_subkey.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libkrb5_la-generate_subkey.Tpo $(DEPDIR)/libkrb5_la-generate_subkey.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='generate_subkey.c' object='libkrb5_la-generate_subkey.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-generate_subkey.lo `test -f 'generate_subkey.c' || echo '$(srcdir)/'`generate_subkey.c libkrb5_la-get_addrs.lo: get_addrs.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libkrb5_la-get_addrs.lo -MD -MP -MF $(DEPDIR)/libkrb5_la-get_addrs.Tpo -c -o libkrb5_la-get_addrs.lo `test -f 'get_addrs.c' || echo '$(srcdir)/'`get_addrs.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libkrb5_la-get_addrs.Tpo $(DEPDIR)/libkrb5_la-get_addrs.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='get_addrs.c' object='libkrb5_la-get_addrs.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-get_addrs.lo `test -f 'get_addrs.c' || echo '$(srcdir)/'`get_addrs.c libkrb5_la-get_cred.lo: get_cred.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libkrb5_la-get_cred.lo -MD -MP -MF $(DEPDIR)/libkrb5_la-get_cred.Tpo -c -o libkrb5_la-get_cred.lo `test -f 'get_cred.c' || echo '$(srcdir)/'`get_cred.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libkrb5_la-get_cred.Tpo $(DEPDIR)/libkrb5_la-get_cred.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='get_cred.c' object='libkrb5_la-get_cred.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-get_cred.lo `test -f 'get_cred.c' || echo '$(srcdir)/'`get_cred.c libkrb5_la-get_default_principal.lo: get_default_principal.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libkrb5_la-get_default_principal.lo -MD -MP -MF $(DEPDIR)/libkrb5_la-get_default_principal.Tpo -c -o libkrb5_la-get_default_principal.lo `test -f 'get_default_principal.c' || echo '$(srcdir)/'`get_default_principal.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libkrb5_la-get_default_principal.Tpo $(DEPDIR)/libkrb5_la-get_default_principal.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='get_default_principal.c' object='libkrb5_la-get_default_principal.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-get_default_principal.lo `test -f 'get_default_principal.c' || echo '$(srcdir)/'`get_default_principal.c libkrb5_la-get_default_realm.lo: get_default_realm.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libkrb5_la-get_default_realm.lo -MD -MP -MF $(DEPDIR)/libkrb5_la-get_default_realm.Tpo -c -o libkrb5_la-get_default_realm.lo `test -f 'get_default_realm.c' || echo '$(srcdir)/'`get_default_realm.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libkrb5_la-get_default_realm.Tpo $(DEPDIR)/libkrb5_la-get_default_realm.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='get_default_realm.c' object='libkrb5_la-get_default_realm.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-get_default_realm.lo `test -f 'get_default_realm.c' || echo '$(srcdir)/'`get_default_realm.c libkrb5_la-get_for_creds.lo: get_for_creds.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libkrb5_la-get_for_creds.lo -MD -MP -MF $(DEPDIR)/libkrb5_la-get_for_creds.Tpo -c -o libkrb5_la-get_for_creds.lo `test -f 'get_for_creds.c' || echo '$(srcdir)/'`get_for_creds.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libkrb5_la-get_for_creds.Tpo $(DEPDIR)/libkrb5_la-get_for_creds.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='get_for_creds.c' object='libkrb5_la-get_for_creds.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-get_for_creds.lo `test -f 'get_for_creds.c' || echo '$(srcdir)/'`get_for_creds.c libkrb5_la-get_host_realm.lo: get_host_realm.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libkrb5_la-get_host_realm.lo -MD -MP -MF $(DEPDIR)/libkrb5_la-get_host_realm.Tpo -c -o libkrb5_la-get_host_realm.lo `test -f 'get_host_realm.c' || echo '$(srcdir)/'`get_host_realm.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libkrb5_la-get_host_realm.Tpo $(DEPDIR)/libkrb5_la-get_host_realm.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='get_host_realm.c' object='libkrb5_la-get_host_realm.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-get_host_realm.lo `test -f 'get_host_realm.c' || echo '$(srcdir)/'`get_host_realm.c libkrb5_la-get_in_tkt.lo: get_in_tkt.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libkrb5_la-get_in_tkt.lo -MD -MP -MF $(DEPDIR)/libkrb5_la-get_in_tkt.Tpo -c -o libkrb5_la-get_in_tkt.lo `test -f 'get_in_tkt.c' || echo '$(srcdir)/'`get_in_tkt.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libkrb5_la-get_in_tkt.Tpo $(DEPDIR)/libkrb5_la-get_in_tkt.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='get_in_tkt.c' object='libkrb5_la-get_in_tkt.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-get_in_tkt.lo `test -f 'get_in_tkt.c' || echo '$(srcdir)/'`get_in_tkt.c libkrb5_la-get_port.lo: get_port.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libkrb5_la-get_port.lo -MD -MP -MF $(DEPDIR)/libkrb5_la-get_port.Tpo -c -o libkrb5_la-get_port.lo `test -f 'get_port.c' || echo '$(srcdir)/'`get_port.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libkrb5_la-get_port.Tpo $(DEPDIR)/libkrb5_la-get_port.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='get_port.c' object='libkrb5_la-get_port.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-get_port.lo `test -f 'get_port.c' || echo '$(srcdir)/'`get_port.c libkrb5_la-init_creds.lo: init_creds.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libkrb5_la-init_creds.lo -MD -MP -MF $(DEPDIR)/libkrb5_la-init_creds.Tpo -c -o libkrb5_la-init_creds.lo `test -f 'init_creds.c' || echo '$(srcdir)/'`init_creds.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libkrb5_la-init_creds.Tpo $(DEPDIR)/libkrb5_la-init_creds.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='init_creds.c' object='libkrb5_la-init_creds.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-init_creds.lo `test -f 'init_creds.c' || echo '$(srcdir)/'`init_creds.c libkrb5_la-init_creds_pw.lo: init_creds_pw.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libkrb5_la-init_creds_pw.lo -MD -MP -MF $(DEPDIR)/libkrb5_la-init_creds_pw.Tpo -c -o libkrb5_la-init_creds_pw.lo `test -f 'init_creds_pw.c' || echo '$(srcdir)/'`init_creds_pw.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libkrb5_la-init_creds_pw.Tpo $(DEPDIR)/libkrb5_la-init_creds_pw.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='init_creds_pw.c' object='libkrb5_la-init_creds_pw.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-init_creds_pw.lo `test -f 'init_creds_pw.c' || echo '$(srcdir)/'`init_creds_pw.c libkrb5_la-kcm.lo: kcm.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libkrb5_la-kcm.lo -MD -MP -MF $(DEPDIR)/libkrb5_la-kcm.Tpo -c -o libkrb5_la-kcm.lo `test -f 'kcm.c' || echo '$(srcdir)/'`kcm.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libkrb5_la-kcm.Tpo $(DEPDIR)/libkrb5_la-kcm.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='kcm.c' object='libkrb5_la-kcm.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-kcm.lo `test -f 'kcm.c' || echo '$(srcdir)/'`kcm.c libkrb5_la-keyblock.lo: keyblock.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libkrb5_la-keyblock.lo -MD -MP -MF $(DEPDIR)/libkrb5_la-keyblock.Tpo -c -o libkrb5_la-keyblock.lo `test -f 'keyblock.c' || echo '$(srcdir)/'`keyblock.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libkrb5_la-keyblock.Tpo $(DEPDIR)/libkrb5_la-keyblock.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='keyblock.c' object='libkrb5_la-keyblock.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-keyblock.lo `test -f 'keyblock.c' || echo '$(srcdir)/'`keyblock.c libkrb5_la-keytab.lo: keytab.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libkrb5_la-keytab.lo -MD -MP -MF $(DEPDIR)/libkrb5_la-keytab.Tpo -c -o libkrb5_la-keytab.lo `test -f 'keytab.c' || echo '$(srcdir)/'`keytab.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libkrb5_la-keytab.Tpo $(DEPDIR)/libkrb5_la-keytab.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='keytab.c' object='libkrb5_la-keytab.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-keytab.lo `test -f 'keytab.c' || echo '$(srcdir)/'`keytab.c libkrb5_la-keytab_any.lo: keytab_any.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libkrb5_la-keytab_any.lo -MD -MP -MF $(DEPDIR)/libkrb5_la-keytab_any.Tpo -c -o libkrb5_la-keytab_any.lo `test -f 'keytab_any.c' || echo '$(srcdir)/'`keytab_any.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libkrb5_la-keytab_any.Tpo $(DEPDIR)/libkrb5_la-keytab_any.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='keytab_any.c' object='libkrb5_la-keytab_any.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-keytab_any.lo `test -f 'keytab_any.c' || echo '$(srcdir)/'`keytab_any.c libkrb5_la-keytab_file.lo: keytab_file.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libkrb5_la-keytab_file.lo -MD -MP -MF $(DEPDIR)/libkrb5_la-keytab_file.Tpo -c -o libkrb5_la-keytab_file.lo `test -f 'keytab_file.c' || echo '$(srcdir)/'`keytab_file.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libkrb5_la-keytab_file.Tpo $(DEPDIR)/libkrb5_la-keytab_file.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='keytab_file.c' object='libkrb5_la-keytab_file.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-keytab_file.lo `test -f 'keytab_file.c' || echo '$(srcdir)/'`keytab_file.c libkrb5_la-keytab_keyfile.lo: keytab_keyfile.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libkrb5_la-keytab_keyfile.lo -MD -MP -MF $(DEPDIR)/libkrb5_la-keytab_keyfile.Tpo -c -o libkrb5_la-keytab_keyfile.lo `test -f 'keytab_keyfile.c' || echo '$(srcdir)/'`keytab_keyfile.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libkrb5_la-keytab_keyfile.Tpo $(DEPDIR)/libkrb5_la-keytab_keyfile.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='keytab_keyfile.c' object='libkrb5_la-keytab_keyfile.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-keytab_keyfile.lo `test -f 'keytab_keyfile.c' || echo '$(srcdir)/'`keytab_keyfile.c libkrb5_la-keytab_memory.lo: keytab_memory.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libkrb5_la-keytab_memory.lo -MD -MP -MF $(DEPDIR)/libkrb5_la-keytab_memory.Tpo -c -o libkrb5_la-keytab_memory.lo `test -f 'keytab_memory.c' || echo '$(srcdir)/'`keytab_memory.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libkrb5_la-keytab_memory.Tpo $(DEPDIR)/libkrb5_la-keytab_memory.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='keytab_memory.c' object='libkrb5_la-keytab_memory.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-keytab_memory.lo `test -f 'keytab_memory.c' || echo '$(srcdir)/'`keytab_memory.c libkrb5_la-krbhst.lo: krbhst.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libkrb5_la-krbhst.lo -MD -MP -MF $(DEPDIR)/libkrb5_la-krbhst.Tpo -c -o libkrb5_la-krbhst.lo `test -f 'krbhst.c' || echo '$(srcdir)/'`krbhst.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libkrb5_la-krbhst.Tpo $(DEPDIR)/libkrb5_la-krbhst.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='krbhst.c' object='libkrb5_la-krbhst.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-krbhst.lo `test -f 'krbhst.c' || echo '$(srcdir)/'`krbhst.c libkrb5_la-kuserok.lo: kuserok.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libkrb5_la-kuserok.lo -MD -MP -MF $(DEPDIR)/libkrb5_la-kuserok.Tpo -c -o libkrb5_la-kuserok.lo `test -f 'kuserok.c' || echo '$(srcdir)/'`kuserok.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libkrb5_la-kuserok.Tpo $(DEPDIR)/libkrb5_la-kuserok.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='kuserok.c' object='libkrb5_la-kuserok.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-kuserok.lo `test -f 'kuserok.c' || echo '$(srcdir)/'`kuserok.c libkrb5_la-log.lo: log.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libkrb5_la-log.lo -MD -MP -MF $(DEPDIR)/libkrb5_la-log.Tpo -c -o libkrb5_la-log.lo `test -f 'log.c' || echo '$(srcdir)/'`log.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libkrb5_la-log.Tpo $(DEPDIR)/libkrb5_la-log.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='log.c' object='libkrb5_la-log.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-log.lo `test -f 'log.c' || echo '$(srcdir)/'`log.c libkrb5_la-mcache.lo: mcache.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libkrb5_la-mcache.lo -MD -MP -MF $(DEPDIR)/libkrb5_la-mcache.Tpo -c -o libkrb5_la-mcache.lo `test -f 'mcache.c' || echo '$(srcdir)/'`mcache.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libkrb5_la-mcache.Tpo $(DEPDIR)/libkrb5_la-mcache.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='mcache.c' object='libkrb5_la-mcache.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-mcache.lo `test -f 'mcache.c' || echo '$(srcdir)/'`mcache.c libkrb5_la-misc.lo: misc.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libkrb5_la-misc.lo -MD -MP -MF $(DEPDIR)/libkrb5_la-misc.Tpo -c -o libkrb5_la-misc.lo `test -f 'misc.c' || echo '$(srcdir)/'`misc.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libkrb5_la-misc.Tpo $(DEPDIR)/libkrb5_la-misc.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='misc.c' object='libkrb5_la-misc.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-misc.lo `test -f 'misc.c' || echo '$(srcdir)/'`misc.c libkrb5_la-mk_error.lo: mk_error.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libkrb5_la-mk_error.lo -MD -MP -MF $(DEPDIR)/libkrb5_la-mk_error.Tpo -c -o libkrb5_la-mk_error.lo `test -f 'mk_error.c' || echo '$(srcdir)/'`mk_error.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libkrb5_la-mk_error.Tpo $(DEPDIR)/libkrb5_la-mk_error.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='mk_error.c' object='libkrb5_la-mk_error.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-mk_error.lo `test -f 'mk_error.c' || echo '$(srcdir)/'`mk_error.c libkrb5_la-mk_priv.lo: mk_priv.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libkrb5_la-mk_priv.lo -MD -MP -MF $(DEPDIR)/libkrb5_la-mk_priv.Tpo -c -o libkrb5_la-mk_priv.lo `test -f 'mk_priv.c' || echo '$(srcdir)/'`mk_priv.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libkrb5_la-mk_priv.Tpo $(DEPDIR)/libkrb5_la-mk_priv.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='mk_priv.c' object='libkrb5_la-mk_priv.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-mk_priv.lo `test -f 'mk_priv.c' || echo '$(srcdir)/'`mk_priv.c libkrb5_la-mk_rep.lo: mk_rep.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libkrb5_la-mk_rep.lo -MD -MP -MF $(DEPDIR)/libkrb5_la-mk_rep.Tpo -c -o libkrb5_la-mk_rep.lo `test -f 'mk_rep.c' || echo '$(srcdir)/'`mk_rep.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libkrb5_la-mk_rep.Tpo $(DEPDIR)/libkrb5_la-mk_rep.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='mk_rep.c' object='libkrb5_la-mk_rep.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-mk_rep.lo `test -f 'mk_rep.c' || echo '$(srcdir)/'`mk_rep.c libkrb5_la-mk_req.lo: mk_req.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libkrb5_la-mk_req.lo -MD -MP -MF $(DEPDIR)/libkrb5_la-mk_req.Tpo -c -o libkrb5_la-mk_req.lo `test -f 'mk_req.c' || echo '$(srcdir)/'`mk_req.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libkrb5_la-mk_req.Tpo $(DEPDIR)/libkrb5_la-mk_req.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='mk_req.c' object='libkrb5_la-mk_req.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-mk_req.lo `test -f 'mk_req.c' || echo '$(srcdir)/'`mk_req.c libkrb5_la-mk_req_ext.lo: mk_req_ext.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libkrb5_la-mk_req_ext.lo -MD -MP -MF $(DEPDIR)/libkrb5_la-mk_req_ext.Tpo -c -o libkrb5_la-mk_req_ext.lo `test -f 'mk_req_ext.c' || echo '$(srcdir)/'`mk_req_ext.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libkrb5_la-mk_req_ext.Tpo $(DEPDIR)/libkrb5_la-mk_req_ext.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='mk_req_ext.c' object='libkrb5_la-mk_req_ext.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-mk_req_ext.lo `test -f 'mk_req_ext.c' || echo '$(srcdir)/'`mk_req_ext.c libkrb5_la-mk_safe.lo: mk_safe.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libkrb5_la-mk_safe.lo -MD -MP -MF $(DEPDIR)/libkrb5_la-mk_safe.Tpo -c -o libkrb5_la-mk_safe.lo `test -f 'mk_safe.c' || echo '$(srcdir)/'`mk_safe.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libkrb5_la-mk_safe.Tpo $(DEPDIR)/libkrb5_la-mk_safe.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='mk_safe.c' object='libkrb5_la-mk_safe.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-mk_safe.lo `test -f 'mk_safe.c' || echo '$(srcdir)/'`mk_safe.c libkrb5_la-mit_glue.lo: mit_glue.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libkrb5_la-mit_glue.lo -MD -MP -MF $(DEPDIR)/libkrb5_la-mit_glue.Tpo -c -o libkrb5_la-mit_glue.lo `test -f 'mit_glue.c' || echo '$(srcdir)/'`mit_glue.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libkrb5_la-mit_glue.Tpo $(DEPDIR)/libkrb5_la-mit_glue.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='mit_glue.c' object='libkrb5_la-mit_glue.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-mit_glue.lo `test -f 'mit_glue.c' || echo '$(srcdir)/'`mit_glue.c libkrb5_la-net_read.lo: net_read.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libkrb5_la-net_read.lo -MD -MP -MF $(DEPDIR)/libkrb5_la-net_read.Tpo -c -o libkrb5_la-net_read.lo `test -f 'net_read.c' || echo '$(srcdir)/'`net_read.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libkrb5_la-net_read.Tpo $(DEPDIR)/libkrb5_la-net_read.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='net_read.c' object='libkrb5_la-net_read.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-net_read.lo `test -f 'net_read.c' || echo '$(srcdir)/'`net_read.c libkrb5_la-net_write.lo: net_write.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libkrb5_la-net_write.lo -MD -MP -MF $(DEPDIR)/libkrb5_la-net_write.Tpo -c -o libkrb5_la-net_write.lo `test -f 'net_write.c' || echo '$(srcdir)/'`net_write.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libkrb5_la-net_write.Tpo $(DEPDIR)/libkrb5_la-net_write.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='net_write.c' object='libkrb5_la-net_write.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-net_write.lo `test -f 'net_write.c' || echo '$(srcdir)/'`net_write.c libkrb5_la-n-fold.lo: n-fold.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libkrb5_la-n-fold.lo -MD -MP -MF $(DEPDIR)/libkrb5_la-n-fold.Tpo -c -o libkrb5_la-n-fold.lo `test -f 'n-fold.c' || echo '$(srcdir)/'`n-fold.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libkrb5_la-n-fold.Tpo $(DEPDIR)/libkrb5_la-n-fold.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='n-fold.c' object='libkrb5_la-n-fold.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-n-fold.lo `test -f 'n-fold.c' || echo '$(srcdir)/'`n-fold.c libkrb5_la-pac.lo: pac.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libkrb5_la-pac.lo -MD -MP -MF $(DEPDIR)/libkrb5_la-pac.Tpo -c -o libkrb5_la-pac.lo `test -f 'pac.c' || echo '$(srcdir)/'`pac.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libkrb5_la-pac.Tpo $(DEPDIR)/libkrb5_la-pac.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='pac.c' object='libkrb5_la-pac.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-pac.lo `test -f 'pac.c' || echo '$(srcdir)/'`pac.c libkrb5_la-padata.lo: padata.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libkrb5_la-padata.lo -MD -MP -MF $(DEPDIR)/libkrb5_la-padata.Tpo -c -o libkrb5_la-padata.lo `test -f 'padata.c' || echo '$(srcdir)/'`padata.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libkrb5_la-padata.Tpo $(DEPDIR)/libkrb5_la-padata.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='padata.c' object='libkrb5_la-padata.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-padata.lo `test -f 'padata.c' || echo '$(srcdir)/'`padata.c libkrb5_la-pcache.lo: pcache.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libkrb5_la-pcache.lo -MD -MP -MF $(DEPDIR)/libkrb5_la-pcache.Tpo -c -o libkrb5_la-pcache.lo `test -f 'pcache.c' || echo '$(srcdir)/'`pcache.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libkrb5_la-pcache.Tpo $(DEPDIR)/libkrb5_la-pcache.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='pcache.c' object='libkrb5_la-pcache.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-pcache.lo `test -f 'pcache.c' || echo '$(srcdir)/'`pcache.c libkrb5_la-pkinit.lo: pkinit.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libkrb5_la-pkinit.lo -MD -MP -MF $(DEPDIR)/libkrb5_la-pkinit.Tpo -c -o libkrb5_la-pkinit.lo `test -f 'pkinit.c' || echo '$(srcdir)/'`pkinit.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libkrb5_la-pkinit.Tpo $(DEPDIR)/libkrb5_la-pkinit.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='pkinit.c' object='libkrb5_la-pkinit.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-pkinit.lo `test -f 'pkinit.c' || echo '$(srcdir)/'`pkinit.c libkrb5_la-pkinit-ec.lo: pkinit-ec.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libkrb5_la-pkinit-ec.lo -MD -MP -MF $(DEPDIR)/libkrb5_la-pkinit-ec.Tpo -c -o libkrb5_la-pkinit-ec.lo `test -f 'pkinit-ec.c' || echo '$(srcdir)/'`pkinit-ec.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libkrb5_la-pkinit-ec.Tpo $(DEPDIR)/libkrb5_la-pkinit-ec.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='pkinit-ec.c' object='libkrb5_la-pkinit-ec.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-pkinit-ec.lo `test -f 'pkinit-ec.c' || echo '$(srcdir)/'`pkinit-ec.c libkrb5_la-principal.lo: principal.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libkrb5_la-principal.lo -MD -MP -MF $(DEPDIR)/libkrb5_la-principal.Tpo -c -o libkrb5_la-principal.lo `test -f 'principal.c' || echo '$(srcdir)/'`principal.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libkrb5_la-principal.Tpo $(DEPDIR)/libkrb5_la-principal.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='principal.c' object='libkrb5_la-principal.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-principal.lo `test -f 'principal.c' || echo '$(srcdir)/'`principal.c libkrb5_la-prog_setup.lo: prog_setup.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libkrb5_la-prog_setup.lo -MD -MP -MF $(DEPDIR)/libkrb5_la-prog_setup.Tpo -c -o libkrb5_la-prog_setup.lo `test -f 'prog_setup.c' || echo '$(srcdir)/'`prog_setup.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libkrb5_la-prog_setup.Tpo $(DEPDIR)/libkrb5_la-prog_setup.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='prog_setup.c' object='libkrb5_la-prog_setup.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-prog_setup.lo `test -f 'prog_setup.c' || echo '$(srcdir)/'`prog_setup.c libkrb5_la-prompter_posix.lo: prompter_posix.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libkrb5_la-prompter_posix.lo -MD -MP -MF $(DEPDIR)/libkrb5_la-prompter_posix.Tpo -c -o libkrb5_la-prompter_posix.lo `test -f 'prompter_posix.c' || echo '$(srcdir)/'`prompter_posix.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libkrb5_la-prompter_posix.Tpo $(DEPDIR)/libkrb5_la-prompter_posix.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='prompter_posix.c' object='libkrb5_la-prompter_posix.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-prompter_posix.lo `test -f 'prompter_posix.c' || echo '$(srcdir)/'`prompter_posix.c libkrb5_la-rd_cred.lo: rd_cred.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libkrb5_la-rd_cred.lo -MD -MP -MF $(DEPDIR)/libkrb5_la-rd_cred.Tpo -c -o libkrb5_la-rd_cred.lo `test -f 'rd_cred.c' || echo '$(srcdir)/'`rd_cred.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libkrb5_la-rd_cred.Tpo $(DEPDIR)/libkrb5_la-rd_cred.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='rd_cred.c' object='libkrb5_la-rd_cred.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-rd_cred.lo `test -f 'rd_cred.c' || echo '$(srcdir)/'`rd_cred.c libkrb5_la-rd_error.lo: rd_error.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libkrb5_la-rd_error.lo -MD -MP -MF $(DEPDIR)/libkrb5_la-rd_error.Tpo -c -o libkrb5_la-rd_error.lo `test -f 'rd_error.c' || echo '$(srcdir)/'`rd_error.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libkrb5_la-rd_error.Tpo $(DEPDIR)/libkrb5_la-rd_error.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='rd_error.c' object='libkrb5_la-rd_error.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-rd_error.lo `test -f 'rd_error.c' || echo '$(srcdir)/'`rd_error.c libkrb5_la-rd_priv.lo: rd_priv.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libkrb5_la-rd_priv.lo -MD -MP -MF $(DEPDIR)/libkrb5_la-rd_priv.Tpo -c -o libkrb5_la-rd_priv.lo `test -f 'rd_priv.c' || echo '$(srcdir)/'`rd_priv.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libkrb5_la-rd_priv.Tpo $(DEPDIR)/libkrb5_la-rd_priv.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='rd_priv.c' object='libkrb5_la-rd_priv.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-rd_priv.lo `test -f 'rd_priv.c' || echo '$(srcdir)/'`rd_priv.c libkrb5_la-rd_rep.lo: rd_rep.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libkrb5_la-rd_rep.lo -MD -MP -MF $(DEPDIR)/libkrb5_la-rd_rep.Tpo -c -o libkrb5_la-rd_rep.lo `test -f 'rd_rep.c' || echo '$(srcdir)/'`rd_rep.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libkrb5_la-rd_rep.Tpo $(DEPDIR)/libkrb5_la-rd_rep.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='rd_rep.c' object='libkrb5_la-rd_rep.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-rd_rep.lo `test -f 'rd_rep.c' || echo '$(srcdir)/'`rd_rep.c libkrb5_la-rd_req.lo: rd_req.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libkrb5_la-rd_req.lo -MD -MP -MF $(DEPDIR)/libkrb5_la-rd_req.Tpo -c -o libkrb5_la-rd_req.lo `test -f 'rd_req.c' || echo '$(srcdir)/'`rd_req.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libkrb5_la-rd_req.Tpo $(DEPDIR)/libkrb5_la-rd_req.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='rd_req.c' object='libkrb5_la-rd_req.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-rd_req.lo `test -f 'rd_req.c' || echo '$(srcdir)/'`rd_req.c libkrb5_la-rd_safe.lo: rd_safe.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libkrb5_la-rd_safe.lo -MD -MP -MF $(DEPDIR)/libkrb5_la-rd_safe.Tpo -c -o libkrb5_la-rd_safe.lo `test -f 'rd_safe.c' || echo '$(srcdir)/'`rd_safe.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libkrb5_la-rd_safe.Tpo $(DEPDIR)/libkrb5_la-rd_safe.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='rd_safe.c' object='libkrb5_la-rd_safe.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-rd_safe.lo `test -f 'rd_safe.c' || echo '$(srcdir)/'`rd_safe.c libkrb5_la-read_message.lo: read_message.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libkrb5_la-read_message.lo -MD -MP -MF $(DEPDIR)/libkrb5_la-read_message.Tpo -c -o libkrb5_la-read_message.lo `test -f 'read_message.c' || echo '$(srcdir)/'`read_message.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libkrb5_la-read_message.Tpo $(DEPDIR)/libkrb5_la-read_message.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='read_message.c' object='libkrb5_la-read_message.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-read_message.lo `test -f 'read_message.c' || echo '$(srcdir)/'`read_message.c libkrb5_la-recvauth.lo: recvauth.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libkrb5_la-recvauth.lo -MD -MP -MF $(DEPDIR)/libkrb5_la-recvauth.Tpo -c -o libkrb5_la-recvauth.lo `test -f 'recvauth.c' || echo '$(srcdir)/'`recvauth.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libkrb5_la-recvauth.Tpo $(DEPDIR)/libkrb5_la-recvauth.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='recvauth.c' object='libkrb5_la-recvauth.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-recvauth.lo `test -f 'recvauth.c' || echo '$(srcdir)/'`recvauth.c libkrb5_la-replay.lo: replay.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libkrb5_la-replay.lo -MD -MP -MF $(DEPDIR)/libkrb5_la-replay.Tpo -c -o libkrb5_la-replay.lo `test -f 'replay.c' || echo '$(srcdir)/'`replay.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libkrb5_la-replay.Tpo $(DEPDIR)/libkrb5_la-replay.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='replay.c' object='libkrb5_la-replay.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-replay.lo `test -f 'replay.c' || echo '$(srcdir)/'`replay.c libkrb5_la-salt.lo: salt.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libkrb5_la-salt.lo -MD -MP -MF $(DEPDIR)/libkrb5_la-salt.Tpo -c -o libkrb5_la-salt.lo `test -f 'salt.c' || echo '$(srcdir)/'`salt.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libkrb5_la-salt.Tpo $(DEPDIR)/libkrb5_la-salt.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='salt.c' object='libkrb5_la-salt.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-salt.lo `test -f 'salt.c' || echo '$(srcdir)/'`salt.c libkrb5_la-salt-aes-sha1.lo: salt-aes-sha1.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libkrb5_la-salt-aes-sha1.lo -MD -MP -MF $(DEPDIR)/libkrb5_la-salt-aes-sha1.Tpo -c -o libkrb5_la-salt-aes-sha1.lo `test -f 'salt-aes-sha1.c' || echo '$(srcdir)/'`salt-aes-sha1.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libkrb5_la-salt-aes-sha1.Tpo $(DEPDIR)/libkrb5_la-salt-aes-sha1.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='salt-aes-sha1.c' object='libkrb5_la-salt-aes-sha1.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-salt-aes-sha1.lo `test -f 'salt-aes-sha1.c' || echo '$(srcdir)/'`salt-aes-sha1.c libkrb5_la-salt-aes-sha2.lo: salt-aes-sha2.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libkrb5_la-salt-aes-sha2.lo -MD -MP -MF $(DEPDIR)/libkrb5_la-salt-aes-sha2.Tpo -c -o libkrb5_la-salt-aes-sha2.lo `test -f 'salt-aes-sha2.c' || echo '$(srcdir)/'`salt-aes-sha2.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libkrb5_la-salt-aes-sha2.Tpo $(DEPDIR)/libkrb5_la-salt-aes-sha2.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='salt-aes-sha2.c' object='libkrb5_la-salt-aes-sha2.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-salt-aes-sha2.lo `test -f 'salt-aes-sha2.c' || echo '$(srcdir)/'`salt-aes-sha2.c libkrb5_la-salt-arcfour.lo: salt-arcfour.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libkrb5_la-salt-arcfour.lo -MD -MP -MF $(DEPDIR)/libkrb5_la-salt-arcfour.Tpo -c -o libkrb5_la-salt-arcfour.lo `test -f 'salt-arcfour.c' || echo '$(srcdir)/'`salt-arcfour.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libkrb5_la-salt-arcfour.Tpo $(DEPDIR)/libkrb5_la-salt-arcfour.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='salt-arcfour.c' object='libkrb5_la-salt-arcfour.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-salt-arcfour.lo `test -f 'salt-arcfour.c' || echo '$(srcdir)/'`salt-arcfour.c libkrb5_la-salt-des.lo: salt-des.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libkrb5_la-salt-des.lo -MD -MP -MF $(DEPDIR)/libkrb5_la-salt-des.Tpo -c -o libkrb5_la-salt-des.lo `test -f 'salt-des.c' || echo '$(srcdir)/'`salt-des.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libkrb5_la-salt-des.Tpo $(DEPDIR)/libkrb5_la-salt-des.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='salt-des.c' object='libkrb5_la-salt-des.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-salt-des.lo `test -f 'salt-des.c' || echo '$(srcdir)/'`salt-des.c libkrb5_la-salt-des3.lo: salt-des3.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libkrb5_la-salt-des3.lo -MD -MP -MF $(DEPDIR)/libkrb5_la-salt-des3.Tpo -c -o libkrb5_la-salt-des3.lo `test -f 'salt-des3.c' || echo '$(srcdir)/'`salt-des3.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libkrb5_la-salt-des3.Tpo $(DEPDIR)/libkrb5_la-salt-des3.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='salt-des3.c' object='libkrb5_la-salt-des3.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-salt-des3.lo `test -f 'salt-des3.c' || echo '$(srcdir)/'`salt-des3.c libkrb5_la-sp800-108-kdf.lo: sp800-108-kdf.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libkrb5_la-sp800-108-kdf.lo -MD -MP -MF $(DEPDIR)/libkrb5_la-sp800-108-kdf.Tpo -c -o libkrb5_la-sp800-108-kdf.lo `test -f 'sp800-108-kdf.c' || echo '$(srcdir)/'`sp800-108-kdf.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libkrb5_la-sp800-108-kdf.Tpo $(DEPDIR)/libkrb5_la-sp800-108-kdf.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='sp800-108-kdf.c' object='libkrb5_la-sp800-108-kdf.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-sp800-108-kdf.lo `test -f 'sp800-108-kdf.c' || echo '$(srcdir)/'`sp800-108-kdf.c libkrb5_la-scache.lo: scache.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libkrb5_la-scache.lo -MD -MP -MF $(DEPDIR)/libkrb5_la-scache.Tpo -c -o libkrb5_la-scache.lo `test -f 'scache.c' || echo '$(srcdir)/'`scache.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libkrb5_la-scache.Tpo $(DEPDIR)/libkrb5_la-scache.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='scache.c' object='libkrb5_la-scache.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-scache.lo `test -f 'scache.c' || echo '$(srcdir)/'`scache.c libkrb5_la-send_to_kdc.lo: send_to_kdc.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libkrb5_la-send_to_kdc.lo -MD -MP -MF $(DEPDIR)/libkrb5_la-send_to_kdc.Tpo -c -o libkrb5_la-send_to_kdc.lo `test -f 'send_to_kdc.c' || echo '$(srcdir)/'`send_to_kdc.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libkrb5_la-send_to_kdc.Tpo $(DEPDIR)/libkrb5_la-send_to_kdc.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='send_to_kdc.c' object='libkrb5_la-send_to_kdc.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-send_to_kdc.lo `test -f 'send_to_kdc.c' || echo '$(srcdir)/'`send_to_kdc.c libkrb5_la-sendauth.lo: sendauth.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libkrb5_la-sendauth.lo -MD -MP -MF $(DEPDIR)/libkrb5_la-sendauth.Tpo -c -o libkrb5_la-sendauth.lo `test -f 'sendauth.c' || echo '$(srcdir)/'`sendauth.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libkrb5_la-sendauth.Tpo $(DEPDIR)/libkrb5_la-sendauth.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='sendauth.c' object='libkrb5_la-sendauth.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-sendauth.lo `test -f 'sendauth.c' || echo '$(srcdir)/'`sendauth.c libkrb5_la-set_default_realm.lo: set_default_realm.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libkrb5_la-set_default_realm.lo -MD -MP -MF $(DEPDIR)/libkrb5_la-set_default_realm.Tpo -c -o libkrb5_la-set_default_realm.lo `test -f 'set_default_realm.c' || echo '$(srcdir)/'`set_default_realm.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libkrb5_la-set_default_realm.Tpo $(DEPDIR)/libkrb5_la-set_default_realm.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='set_default_realm.c' object='libkrb5_la-set_default_realm.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-set_default_realm.lo `test -f 'set_default_realm.c' || echo '$(srcdir)/'`set_default_realm.c libkrb5_la-sock_principal.lo: sock_principal.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libkrb5_la-sock_principal.lo -MD -MP -MF $(DEPDIR)/libkrb5_la-sock_principal.Tpo -c -o libkrb5_la-sock_principal.lo `test -f 'sock_principal.c' || echo '$(srcdir)/'`sock_principal.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libkrb5_la-sock_principal.Tpo $(DEPDIR)/libkrb5_la-sock_principal.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='sock_principal.c' object='libkrb5_la-sock_principal.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-sock_principal.lo `test -f 'sock_principal.c' || echo '$(srcdir)/'`sock_principal.c libkrb5_la-store.lo: store.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libkrb5_la-store.lo -MD -MP -MF $(DEPDIR)/libkrb5_la-store.Tpo -c -o libkrb5_la-store.lo `test -f 'store.c' || echo '$(srcdir)/'`store.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libkrb5_la-store.Tpo $(DEPDIR)/libkrb5_la-store.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='store.c' object='libkrb5_la-store.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-store.lo `test -f 'store.c' || echo '$(srcdir)/'`store.c libkrb5_la-store-int.lo: store-int.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libkrb5_la-store-int.lo -MD -MP -MF $(DEPDIR)/libkrb5_la-store-int.Tpo -c -o libkrb5_la-store-int.lo `test -f 'store-int.c' || echo '$(srcdir)/'`store-int.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libkrb5_la-store-int.Tpo $(DEPDIR)/libkrb5_la-store-int.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='store-int.c' object='libkrb5_la-store-int.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-store-int.lo `test -f 'store-int.c' || echo '$(srcdir)/'`store-int.c libkrb5_la-store_emem.lo: store_emem.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libkrb5_la-store_emem.lo -MD -MP -MF $(DEPDIR)/libkrb5_la-store_emem.Tpo -c -o libkrb5_la-store_emem.lo `test -f 'store_emem.c' || echo '$(srcdir)/'`store_emem.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libkrb5_la-store_emem.Tpo $(DEPDIR)/libkrb5_la-store_emem.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='store_emem.c' object='libkrb5_la-store_emem.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-store_emem.lo `test -f 'store_emem.c' || echo '$(srcdir)/'`store_emem.c libkrb5_la-store_fd.lo: store_fd.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libkrb5_la-store_fd.lo -MD -MP -MF $(DEPDIR)/libkrb5_la-store_fd.Tpo -c -o libkrb5_la-store_fd.lo `test -f 'store_fd.c' || echo '$(srcdir)/'`store_fd.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libkrb5_la-store_fd.Tpo $(DEPDIR)/libkrb5_la-store_fd.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='store_fd.c' object='libkrb5_la-store_fd.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-store_fd.lo `test -f 'store_fd.c' || echo '$(srcdir)/'`store_fd.c libkrb5_la-store_mem.lo: store_mem.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libkrb5_la-store_mem.lo -MD -MP -MF $(DEPDIR)/libkrb5_la-store_mem.Tpo -c -o libkrb5_la-store_mem.lo `test -f 'store_mem.c' || echo '$(srcdir)/'`store_mem.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libkrb5_la-store_mem.Tpo $(DEPDIR)/libkrb5_la-store_mem.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='store_mem.c' object='libkrb5_la-store_mem.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-store_mem.lo `test -f 'store_mem.c' || echo '$(srcdir)/'`store_mem.c libkrb5_la-store_sock.lo: store_sock.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libkrb5_la-store_sock.lo -MD -MP -MF $(DEPDIR)/libkrb5_la-store_sock.Tpo -c -o libkrb5_la-store_sock.lo `test -f 'store_sock.c' || echo '$(srcdir)/'`store_sock.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libkrb5_la-store_sock.Tpo $(DEPDIR)/libkrb5_la-store_sock.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='store_sock.c' object='libkrb5_la-store_sock.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-store_sock.lo `test -f 'store_sock.c' || echo '$(srcdir)/'`store_sock.c libkrb5_la-plugin.lo: plugin.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libkrb5_la-plugin.lo -MD -MP -MF $(DEPDIR)/libkrb5_la-plugin.Tpo -c -o libkrb5_la-plugin.lo `test -f 'plugin.c' || echo '$(srcdir)/'`plugin.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libkrb5_la-plugin.Tpo $(DEPDIR)/libkrb5_la-plugin.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='plugin.c' object='libkrb5_la-plugin.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-plugin.lo `test -f 'plugin.c' || echo '$(srcdir)/'`plugin.c libkrb5_la-ticket.lo: ticket.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libkrb5_la-ticket.lo -MD -MP -MF $(DEPDIR)/libkrb5_la-ticket.Tpo -c -o libkrb5_la-ticket.lo `test -f 'ticket.c' || echo '$(srcdir)/'`ticket.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libkrb5_la-ticket.Tpo $(DEPDIR)/libkrb5_la-ticket.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='ticket.c' object='libkrb5_la-ticket.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-ticket.lo `test -f 'ticket.c' || echo '$(srcdir)/'`ticket.c libkrb5_la-time.lo: time.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libkrb5_la-time.lo -MD -MP -MF $(DEPDIR)/libkrb5_la-time.Tpo -c -o libkrb5_la-time.lo `test -f 'time.c' || echo '$(srcdir)/'`time.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libkrb5_la-time.Tpo $(DEPDIR)/libkrb5_la-time.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='time.c' object='libkrb5_la-time.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-time.lo `test -f 'time.c' || echo '$(srcdir)/'`time.c libkrb5_la-transited.lo: transited.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libkrb5_la-transited.lo -MD -MP -MF $(DEPDIR)/libkrb5_la-transited.Tpo -c -o libkrb5_la-transited.lo `test -f 'transited.c' || echo '$(srcdir)/'`transited.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libkrb5_la-transited.Tpo $(DEPDIR)/libkrb5_la-transited.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='transited.c' object='libkrb5_la-transited.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-transited.lo `test -f 'transited.c' || echo '$(srcdir)/'`transited.c libkrb5_la-verify_init.lo: verify_init.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libkrb5_la-verify_init.lo -MD -MP -MF $(DEPDIR)/libkrb5_la-verify_init.Tpo -c -o libkrb5_la-verify_init.lo `test -f 'verify_init.c' || echo '$(srcdir)/'`verify_init.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libkrb5_la-verify_init.Tpo $(DEPDIR)/libkrb5_la-verify_init.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='verify_init.c' object='libkrb5_la-verify_init.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-verify_init.lo `test -f 'verify_init.c' || echo '$(srcdir)/'`verify_init.c libkrb5_la-verify_user.lo: verify_user.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libkrb5_la-verify_user.lo -MD -MP -MF $(DEPDIR)/libkrb5_la-verify_user.Tpo -c -o libkrb5_la-verify_user.lo `test -f 'verify_user.c' || echo '$(srcdir)/'`verify_user.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libkrb5_la-verify_user.Tpo $(DEPDIR)/libkrb5_la-verify_user.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='verify_user.c' object='libkrb5_la-verify_user.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-verify_user.lo `test -f 'verify_user.c' || echo '$(srcdir)/'`verify_user.c libkrb5_la-version.lo: version.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libkrb5_la-version.lo -MD -MP -MF $(DEPDIR)/libkrb5_la-version.Tpo -c -o libkrb5_la-version.lo `test -f 'version.c' || echo '$(srcdir)/'`version.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libkrb5_la-version.Tpo $(DEPDIR)/libkrb5_la-version.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='version.c' object='libkrb5_la-version.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-version.lo `test -f 'version.c' || echo '$(srcdir)/'`version.c libkrb5_la-warn.lo: warn.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libkrb5_la-warn.lo -MD -MP -MF $(DEPDIR)/libkrb5_la-warn.Tpo -c -o libkrb5_la-warn.lo `test -f 'warn.c' || echo '$(srcdir)/'`warn.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libkrb5_la-warn.Tpo $(DEPDIR)/libkrb5_la-warn.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='warn.c' object='libkrb5_la-warn.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-warn.lo `test -f 'warn.c' || echo '$(srcdir)/'`warn.c libkrb5_la-write_message.lo: write_message.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libkrb5_la-write_message.lo -MD -MP -MF $(DEPDIR)/libkrb5_la-write_message.Tpo -c -o libkrb5_la-write_message.lo `test -f 'write_message.c' || echo '$(srcdir)/'`write_message.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libkrb5_la-write_message.Tpo $(DEPDIR)/libkrb5_la-write_message.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='write_message.c' object='libkrb5_la-write_message.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-write_message.lo `test -f 'write_message.c' || echo '$(srcdir)/'`write_message.c libkrb5_la-krb5_err.lo: krb5_err.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libkrb5_la-krb5_err.lo -MD -MP -MF $(DEPDIR)/libkrb5_la-krb5_err.Tpo -c -o libkrb5_la-krb5_err.lo `test -f 'krb5_err.c' || echo '$(srcdir)/'`krb5_err.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libkrb5_la-krb5_err.Tpo $(DEPDIR)/libkrb5_la-krb5_err.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='krb5_err.c' object='libkrb5_la-krb5_err.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-krb5_err.lo `test -f 'krb5_err.c' || echo '$(srcdir)/'`krb5_err.c libkrb5_la-krb_err.lo: krb_err.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libkrb5_la-krb_err.lo -MD -MP -MF $(DEPDIR)/libkrb5_la-krb_err.Tpo -c -o libkrb5_la-krb_err.lo `test -f 'krb_err.c' || echo '$(srcdir)/'`krb_err.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libkrb5_la-krb_err.Tpo $(DEPDIR)/libkrb5_la-krb_err.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='krb_err.c' object='libkrb5_la-krb_err.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-krb_err.lo `test -f 'krb_err.c' || echo '$(srcdir)/'`krb_err.c libkrb5_la-heim_err.lo: heim_err.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libkrb5_la-heim_err.lo -MD -MP -MF $(DEPDIR)/libkrb5_la-heim_err.Tpo -c -o libkrb5_la-heim_err.lo `test -f 'heim_err.c' || echo '$(srcdir)/'`heim_err.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libkrb5_la-heim_err.Tpo $(DEPDIR)/libkrb5_la-heim_err.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='heim_err.c' object='libkrb5_la-heim_err.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-heim_err.lo `test -f 'heim_err.c' || echo '$(srcdir)/'`heim_err.c libkrb5_la-k524_err.lo: k524_err.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libkrb5_la-k524_err.lo -MD -MP -MF $(DEPDIR)/libkrb5_la-k524_err.Tpo -c -o libkrb5_la-k524_err.lo `test -f 'k524_err.c' || echo '$(srcdir)/'`k524_err.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libkrb5_la-k524_err.Tpo $(DEPDIR)/libkrb5_la-k524_err.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='k524_err.c' object='libkrb5_la-k524_err.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-k524_err.lo `test -f 'k524_err.c' || echo '$(srcdir)/'`k524_err.c librfc3961_la-crc.lo: crc.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(librfc3961_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT librfc3961_la-crc.lo -MD -MP -MF $(DEPDIR)/librfc3961_la-crc.Tpo -c -o librfc3961_la-crc.lo `test -f 'crc.c' || echo '$(srcdir)/'`crc.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/librfc3961_la-crc.Tpo $(DEPDIR)/librfc3961_la-crc.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='crc.c' object='librfc3961_la-crc.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(librfc3961_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o librfc3961_la-crc.lo `test -f 'crc.c' || echo '$(srcdir)/'`crc.c librfc3961_la-crypto.lo: crypto.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(librfc3961_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT librfc3961_la-crypto.lo -MD -MP -MF $(DEPDIR)/librfc3961_la-crypto.Tpo -c -o librfc3961_la-crypto.lo `test -f 'crypto.c' || echo '$(srcdir)/'`crypto.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/librfc3961_la-crypto.Tpo $(DEPDIR)/librfc3961_la-crypto.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='crypto.c' object='librfc3961_la-crypto.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(librfc3961_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o librfc3961_la-crypto.lo `test -f 'crypto.c' || echo '$(srcdir)/'`crypto.c librfc3961_la-crypto-aes-sha1.lo: crypto-aes-sha1.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(librfc3961_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT librfc3961_la-crypto-aes-sha1.lo -MD -MP -MF $(DEPDIR)/librfc3961_la-crypto-aes-sha1.Tpo -c -o librfc3961_la-crypto-aes-sha1.lo `test -f 'crypto-aes-sha1.c' || echo '$(srcdir)/'`crypto-aes-sha1.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/librfc3961_la-crypto-aes-sha1.Tpo $(DEPDIR)/librfc3961_la-crypto-aes-sha1.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='crypto-aes-sha1.c' object='librfc3961_la-crypto-aes-sha1.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(librfc3961_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o librfc3961_la-crypto-aes-sha1.lo `test -f 'crypto-aes-sha1.c' || echo '$(srcdir)/'`crypto-aes-sha1.c librfc3961_la-crypto-aes-sha2.lo: crypto-aes-sha2.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(librfc3961_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT librfc3961_la-crypto-aes-sha2.lo -MD -MP -MF $(DEPDIR)/librfc3961_la-crypto-aes-sha2.Tpo -c -o librfc3961_la-crypto-aes-sha2.lo `test -f 'crypto-aes-sha2.c' || echo '$(srcdir)/'`crypto-aes-sha2.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/librfc3961_la-crypto-aes-sha2.Tpo $(DEPDIR)/librfc3961_la-crypto-aes-sha2.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='crypto-aes-sha2.c' object='librfc3961_la-crypto-aes-sha2.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(librfc3961_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o librfc3961_la-crypto-aes-sha2.lo `test -f 'crypto-aes-sha2.c' || echo '$(srcdir)/'`crypto-aes-sha2.c librfc3961_la-crypto-algs.lo: crypto-algs.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(librfc3961_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT librfc3961_la-crypto-algs.lo -MD -MP -MF $(DEPDIR)/librfc3961_la-crypto-algs.Tpo -c -o librfc3961_la-crypto-algs.lo `test -f 'crypto-algs.c' || echo '$(srcdir)/'`crypto-algs.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/librfc3961_la-crypto-algs.Tpo $(DEPDIR)/librfc3961_la-crypto-algs.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='crypto-algs.c' object='librfc3961_la-crypto-algs.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(librfc3961_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o librfc3961_la-crypto-algs.lo `test -f 'crypto-algs.c' || echo '$(srcdir)/'`crypto-algs.c librfc3961_la-crypto-arcfour.lo: crypto-arcfour.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(librfc3961_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT librfc3961_la-crypto-arcfour.lo -MD -MP -MF $(DEPDIR)/librfc3961_la-crypto-arcfour.Tpo -c -o librfc3961_la-crypto-arcfour.lo `test -f 'crypto-arcfour.c' || echo '$(srcdir)/'`crypto-arcfour.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/librfc3961_la-crypto-arcfour.Tpo $(DEPDIR)/librfc3961_la-crypto-arcfour.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='crypto-arcfour.c' object='librfc3961_la-crypto-arcfour.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(librfc3961_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o librfc3961_la-crypto-arcfour.lo `test -f 'crypto-arcfour.c' || echo '$(srcdir)/'`crypto-arcfour.c librfc3961_la-crypto-des.lo: crypto-des.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(librfc3961_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT librfc3961_la-crypto-des.lo -MD -MP -MF $(DEPDIR)/librfc3961_la-crypto-des.Tpo -c -o librfc3961_la-crypto-des.lo `test -f 'crypto-des.c' || echo '$(srcdir)/'`crypto-des.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/librfc3961_la-crypto-des.Tpo $(DEPDIR)/librfc3961_la-crypto-des.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='crypto-des.c' object='librfc3961_la-crypto-des.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(librfc3961_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o librfc3961_la-crypto-des.lo `test -f 'crypto-des.c' || echo '$(srcdir)/'`crypto-des.c librfc3961_la-crypto-des-common.lo: crypto-des-common.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(librfc3961_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT librfc3961_la-crypto-des-common.lo -MD -MP -MF $(DEPDIR)/librfc3961_la-crypto-des-common.Tpo -c -o librfc3961_la-crypto-des-common.lo `test -f 'crypto-des-common.c' || echo '$(srcdir)/'`crypto-des-common.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/librfc3961_la-crypto-des-common.Tpo $(DEPDIR)/librfc3961_la-crypto-des-common.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='crypto-des-common.c' object='librfc3961_la-crypto-des-common.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(librfc3961_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o librfc3961_la-crypto-des-common.lo `test -f 'crypto-des-common.c' || echo '$(srcdir)/'`crypto-des-common.c librfc3961_la-crypto-des3.lo: crypto-des3.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(librfc3961_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT librfc3961_la-crypto-des3.lo -MD -MP -MF $(DEPDIR)/librfc3961_la-crypto-des3.Tpo -c -o librfc3961_la-crypto-des3.lo `test -f 'crypto-des3.c' || echo '$(srcdir)/'`crypto-des3.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/librfc3961_la-crypto-des3.Tpo $(DEPDIR)/librfc3961_la-crypto-des3.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='crypto-des3.c' object='librfc3961_la-crypto-des3.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(librfc3961_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o librfc3961_la-crypto-des3.lo `test -f 'crypto-des3.c' || echo '$(srcdir)/'`crypto-des3.c librfc3961_la-crypto-evp.lo: crypto-evp.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(librfc3961_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT librfc3961_la-crypto-evp.lo -MD -MP -MF $(DEPDIR)/librfc3961_la-crypto-evp.Tpo -c -o librfc3961_la-crypto-evp.lo `test -f 'crypto-evp.c' || echo '$(srcdir)/'`crypto-evp.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/librfc3961_la-crypto-evp.Tpo $(DEPDIR)/librfc3961_la-crypto-evp.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='crypto-evp.c' object='librfc3961_la-crypto-evp.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(librfc3961_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o librfc3961_la-crypto-evp.lo `test -f 'crypto-evp.c' || echo '$(srcdir)/'`crypto-evp.c librfc3961_la-crypto-null.lo: crypto-null.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(librfc3961_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT librfc3961_la-crypto-null.lo -MD -MP -MF $(DEPDIR)/librfc3961_la-crypto-null.Tpo -c -o librfc3961_la-crypto-null.lo `test -f 'crypto-null.c' || echo '$(srcdir)/'`crypto-null.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/librfc3961_la-crypto-null.Tpo $(DEPDIR)/librfc3961_la-crypto-null.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='crypto-null.c' object='librfc3961_la-crypto-null.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(librfc3961_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o librfc3961_la-crypto-null.lo `test -f 'crypto-null.c' || echo '$(srcdir)/'`crypto-null.c librfc3961_la-crypto-pk.lo: crypto-pk.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(librfc3961_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT librfc3961_la-crypto-pk.lo -MD -MP -MF $(DEPDIR)/librfc3961_la-crypto-pk.Tpo -c -o librfc3961_la-crypto-pk.lo `test -f 'crypto-pk.c' || echo '$(srcdir)/'`crypto-pk.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/librfc3961_la-crypto-pk.Tpo $(DEPDIR)/librfc3961_la-crypto-pk.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='crypto-pk.c' object='librfc3961_la-crypto-pk.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(librfc3961_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o librfc3961_la-crypto-pk.lo `test -f 'crypto-pk.c' || echo '$(srcdir)/'`crypto-pk.c librfc3961_la-crypto-rand.lo: crypto-rand.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(librfc3961_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT librfc3961_la-crypto-rand.lo -MD -MP -MF $(DEPDIR)/librfc3961_la-crypto-rand.Tpo -c -o librfc3961_la-crypto-rand.lo `test -f 'crypto-rand.c' || echo '$(srcdir)/'`crypto-rand.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/librfc3961_la-crypto-rand.Tpo $(DEPDIR)/librfc3961_la-crypto-rand.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='crypto-rand.c' object='librfc3961_la-crypto-rand.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(librfc3961_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o librfc3961_la-crypto-rand.lo `test -f 'crypto-rand.c' || echo '$(srcdir)/'`crypto-rand.c librfc3961_la-crypto-stubs.lo: crypto-stubs.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(librfc3961_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT librfc3961_la-crypto-stubs.lo -MD -MP -MF $(DEPDIR)/librfc3961_la-crypto-stubs.Tpo -c -o librfc3961_la-crypto-stubs.lo `test -f 'crypto-stubs.c' || echo '$(srcdir)/'`crypto-stubs.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/librfc3961_la-crypto-stubs.Tpo $(DEPDIR)/librfc3961_la-crypto-stubs.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='crypto-stubs.c' object='librfc3961_la-crypto-stubs.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(librfc3961_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o librfc3961_la-crypto-stubs.lo `test -f 'crypto-stubs.c' || echo '$(srcdir)/'`crypto-stubs.c librfc3961_la-data.lo: data.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(librfc3961_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT librfc3961_la-data.lo -MD -MP -MF $(DEPDIR)/librfc3961_la-data.Tpo -c -o librfc3961_la-data.lo `test -f 'data.c' || echo '$(srcdir)/'`data.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/librfc3961_la-data.Tpo $(DEPDIR)/librfc3961_la-data.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='data.c' object='librfc3961_la-data.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(librfc3961_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o librfc3961_la-data.lo `test -f 'data.c' || echo '$(srcdir)/'`data.c librfc3961_la-enomem.lo: enomem.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(librfc3961_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT librfc3961_la-enomem.lo -MD -MP -MF $(DEPDIR)/librfc3961_la-enomem.Tpo -c -o librfc3961_la-enomem.lo `test -f 'enomem.c' || echo '$(srcdir)/'`enomem.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/librfc3961_la-enomem.Tpo $(DEPDIR)/librfc3961_la-enomem.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='enomem.c' object='librfc3961_la-enomem.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(librfc3961_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o librfc3961_la-enomem.lo `test -f 'enomem.c' || echo '$(srcdir)/'`enomem.c librfc3961_la-error_string.lo: error_string.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(librfc3961_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT librfc3961_la-error_string.lo -MD -MP -MF $(DEPDIR)/librfc3961_la-error_string.Tpo -c -o librfc3961_la-error_string.lo `test -f 'error_string.c' || echo '$(srcdir)/'`error_string.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/librfc3961_la-error_string.Tpo $(DEPDIR)/librfc3961_la-error_string.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='error_string.c' object='librfc3961_la-error_string.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(librfc3961_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o librfc3961_la-error_string.lo `test -f 'error_string.c' || echo '$(srcdir)/'`error_string.c librfc3961_la-keyblock.lo: keyblock.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(librfc3961_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT librfc3961_la-keyblock.lo -MD -MP -MF $(DEPDIR)/librfc3961_la-keyblock.Tpo -c -o librfc3961_la-keyblock.lo `test -f 'keyblock.c' || echo '$(srcdir)/'`keyblock.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/librfc3961_la-keyblock.Tpo $(DEPDIR)/librfc3961_la-keyblock.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='keyblock.c' object='librfc3961_la-keyblock.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(librfc3961_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o librfc3961_la-keyblock.lo `test -f 'keyblock.c' || echo '$(srcdir)/'`keyblock.c librfc3961_la-n-fold.lo: n-fold.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(librfc3961_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT librfc3961_la-n-fold.lo -MD -MP -MF $(DEPDIR)/librfc3961_la-n-fold.Tpo -c -o librfc3961_la-n-fold.lo `test -f 'n-fold.c' || echo '$(srcdir)/'`n-fold.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/librfc3961_la-n-fold.Tpo $(DEPDIR)/librfc3961_la-n-fold.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='n-fold.c' object='librfc3961_la-n-fold.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(librfc3961_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o librfc3961_la-n-fold.lo `test -f 'n-fold.c' || echo '$(srcdir)/'`n-fold.c librfc3961_la-salt.lo: salt.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(librfc3961_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT librfc3961_la-salt.lo -MD -MP -MF $(DEPDIR)/librfc3961_la-salt.Tpo -c -o librfc3961_la-salt.lo `test -f 'salt.c' || echo '$(srcdir)/'`salt.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/librfc3961_la-salt.Tpo $(DEPDIR)/librfc3961_la-salt.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='salt.c' object='librfc3961_la-salt.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(librfc3961_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o librfc3961_la-salt.lo `test -f 'salt.c' || echo '$(srcdir)/'`salt.c librfc3961_la-salt-aes-sha1.lo: salt-aes-sha1.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(librfc3961_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT librfc3961_la-salt-aes-sha1.lo -MD -MP -MF $(DEPDIR)/librfc3961_la-salt-aes-sha1.Tpo -c -o librfc3961_la-salt-aes-sha1.lo `test -f 'salt-aes-sha1.c' || echo '$(srcdir)/'`salt-aes-sha1.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/librfc3961_la-salt-aes-sha1.Tpo $(DEPDIR)/librfc3961_la-salt-aes-sha1.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='salt-aes-sha1.c' object='librfc3961_la-salt-aes-sha1.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(librfc3961_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o librfc3961_la-salt-aes-sha1.lo `test -f 'salt-aes-sha1.c' || echo '$(srcdir)/'`salt-aes-sha1.c librfc3961_la-salt-aes-sha2.lo: salt-aes-sha2.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(librfc3961_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT librfc3961_la-salt-aes-sha2.lo -MD -MP -MF $(DEPDIR)/librfc3961_la-salt-aes-sha2.Tpo -c -o librfc3961_la-salt-aes-sha2.lo `test -f 'salt-aes-sha2.c' || echo '$(srcdir)/'`salt-aes-sha2.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/librfc3961_la-salt-aes-sha2.Tpo $(DEPDIR)/librfc3961_la-salt-aes-sha2.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='salt-aes-sha2.c' object='librfc3961_la-salt-aes-sha2.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(librfc3961_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o librfc3961_la-salt-aes-sha2.lo `test -f 'salt-aes-sha2.c' || echo '$(srcdir)/'`salt-aes-sha2.c librfc3961_la-salt-arcfour.lo: salt-arcfour.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(librfc3961_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT librfc3961_la-salt-arcfour.lo -MD -MP -MF $(DEPDIR)/librfc3961_la-salt-arcfour.Tpo -c -o librfc3961_la-salt-arcfour.lo `test -f 'salt-arcfour.c' || echo '$(srcdir)/'`salt-arcfour.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/librfc3961_la-salt-arcfour.Tpo $(DEPDIR)/librfc3961_la-salt-arcfour.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='salt-arcfour.c' object='librfc3961_la-salt-arcfour.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(librfc3961_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o librfc3961_la-salt-arcfour.lo `test -f 'salt-arcfour.c' || echo '$(srcdir)/'`salt-arcfour.c librfc3961_la-salt-des.lo: salt-des.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(librfc3961_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT librfc3961_la-salt-des.lo -MD -MP -MF $(DEPDIR)/librfc3961_la-salt-des.Tpo -c -o librfc3961_la-salt-des.lo `test -f 'salt-des.c' || echo '$(srcdir)/'`salt-des.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/librfc3961_la-salt-des.Tpo $(DEPDIR)/librfc3961_la-salt-des.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='salt-des.c' object='librfc3961_la-salt-des.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(librfc3961_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o librfc3961_la-salt-des.lo `test -f 'salt-des.c' || echo '$(srcdir)/'`salt-des.c librfc3961_la-salt-des3.lo: salt-des3.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(librfc3961_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT librfc3961_la-salt-des3.lo -MD -MP -MF $(DEPDIR)/librfc3961_la-salt-des3.Tpo -c -o librfc3961_la-salt-des3.lo `test -f 'salt-des3.c' || echo '$(srcdir)/'`salt-des3.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/librfc3961_la-salt-des3.Tpo $(DEPDIR)/librfc3961_la-salt-des3.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='salt-des3.c' object='librfc3961_la-salt-des3.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(librfc3961_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o librfc3961_la-salt-des3.lo `test -f 'salt-des3.c' || echo '$(srcdir)/'`salt-des3.c librfc3961_la-sp800-108-kdf.lo: sp800-108-kdf.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(librfc3961_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT librfc3961_la-sp800-108-kdf.lo -MD -MP -MF $(DEPDIR)/librfc3961_la-sp800-108-kdf.Tpo -c -o librfc3961_la-sp800-108-kdf.lo `test -f 'sp800-108-kdf.c' || echo '$(srcdir)/'`sp800-108-kdf.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/librfc3961_la-sp800-108-kdf.Tpo $(DEPDIR)/librfc3961_la-sp800-108-kdf.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='sp800-108-kdf.c' object='librfc3961_la-sp800-108-kdf.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(librfc3961_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o librfc3961_la-sp800-108-kdf.lo `test -f 'sp800-108-kdf.c' || echo '$(srcdir)/'`sp800-108-kdf.c librfc3961_la-store-int.lo: store-int.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(librfc3961_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT librfc3961_la-store-int.lo -MD -MP -MF $(DEPDIR)/librfc3961_la-store-int.Tpo -c -o librfc3961_la-store-int.lo `test -f 'store-int.c' || echo '$(srcdir)/'`store-int.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/librfc3961_la-store-int.Tpo $(DEPDIR)/librfc3961_la-store-int.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='store-int.c' object='librfc3961_la-store-int.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(librfc3961_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o librfc3961_la-store-int.lo `test -f 'store-int.c' || echo '$(srcdir)/'`store-int.c librfc3961_la-warn.lo: warn.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(librfc3961_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT librfc3961_la-warn.lo -MD -MP -MF $(DEPDIR)/librfc3961_la-warn.Tpo -c -o librfc3961_la-warn.lo `test -f 'warn.c' || echo '$(srcdir)/'`warn.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/librfc3961_la-warn.Tpo $(DEPDIR)/librfc3961_la-warn.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='warn.c' object='librfc3961_la-warn.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(librfc3961_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o librfc3961_la-warn.lo `test -f 'warn.c' || echo '$(srcdir)/'`warn.c mostlyclean-libtool: -rm -f *.lo clean-libtool: -rm -rf .libs _libs install-man3: $(man_MANS) @$(NORMAL_INSTALL) @list1=''; \ list2='$(man_MANS)'; \ test -n "$(man3dir)" \ && test -n "`echo $$list1$$list2`" \ || exit 0; \ echo " $(MKDIR_P) '$(DESTDIR)$(man3dir)'"; \ $(MKDIR_P) "$(DESTDIR)$(man3dir)" || exit 1; \ { for i in $$list1; do echo "$$i"; done; \ if test -n "$$list2"; then \ for i in $$list2; do echo "$$i"; done \ | sed -n '/\.3[a-z]*$$/p'; \ fi; \ } | while read p; do \ if test -f $$p; then d=; else d="$(srcdir)/"; fi; \ echo "$$d$$p"; echo "$$p"; \ done | \ sed -e 'n;s,.*/,,;p;h;s,.*\.,,;s,^[^3][0-9a-z]*$$,3,;x' \ -e 's,\.[0-9a-z]*$$,,;$(transform);G;s,\n,.,' | \ sed 'N;N;s,\n, ,g' | { \ list=; while read file base inst; do \ if test "$$base" = "$$inst"; then list="$$list $$file"; else \ echo " $(INSTALL_DATA) '$$file' '$(DESTDIR)$(man3dir)/$$inst'"; \ $(INSTALL_DATA) "$$file" "$(DESTDIR)$(man3dir)/$$inst" || exit $$?; \ fi; \ done; \ for i in $$list; do echo "$$i"; done | $(am__base_list) | \ while read files; do \ test -z "$$files" || { \ echo " $(INSTALL_DATA) $$files '$(DESTDIR)$(man3dir)'"; \ $(INSTALL_DATA) $$files "$(DESTDIR)$(man3dir)" || exit $$?; }; \ done; } uninstall-man3: @$(NORMAL_UNINSTALL) @list=''; test -n "$(man3dir)" || exit 0; \ files=`{ for i in $$list; do echo "$$i"; done; \ l2='$(man_MANS)'; for i in $$l2; do echo "$$i"; done | \ sed -n '/\.3[a-z]*$$/p'; \ } | sed -e 's,.*/,,;h;s,.*\.,,;s,^[^3][0-9a-z]*$$,3,;x' \ -e 's,\.[0-9a-z]*$$,,;$(transform);G;s,\n,.,'`; \ dir='$(DESTDIR)$(man3dir)'; $(am__uninstall_files_from_dir) install-man5: $(man_MANS) @$(NORMAL_INSTALL) @list1=''; \ list2='$(man_MANS)'; \ test -n "$(man5dir)" \ && test -n "`echo $$list1$$list2`" \ || exit 0; \ echo " $(MKDIR_P) '$(DESTDIR)$(man5dir)'"; \ $(MKDIR_P) "$(DESTDIR)$(man5dir)" || exit 1; \ { for i in $$list1; do echo "$$i"; done; \ if test -n "$$list2"; then \ for i in $$list2; do echo "$$i"; done \ | sed -n '/\.5[a-z]*$$/p'; \ fi; \ } | while read p; do \ if test -f $$p; then d=; else d="$(srcdir)/"; fi; \ echo "$$d$$p"; echo "$$p"; \ done | \ sed -e 'n;s,.*/,,;p;h;s,.*\.,,;s,^[^5][0-9a-z]*$$,5,;x' \ -e 's,\.[0-9a-z]*$$,,;$(transform);G;s,\n,.,' | \ sed 'N;N;s,\n, ,g' | { \ list=; while read file base inst; do \ if test "$$base" = "$$inst"; then list="$$list $$file"; else \ echo " $(INSTALL_DATA) '$$file' '$(DESTDIR)$(man5dir)/$$inst'"; \ $(INSTALL_DATA) "$$file" "$(DESTDIR)$(man5dir)/$$inst" || exit $$?; \ fi; \ done; \ for i in $$list; do echo "$$i"; done | $(am__base_list) | \ while read files; do \ test -z "$$files" || { \ echo " $(INSTALL_DATA) $$files '$(DESTDIR)$(man5dir)'"; \ $(INSTALL_DATA) $$files "$(DESTDIR)$(man5dir)" || exit $$?; }; \ done; } uninstall-man5: @$(NORMAL_UNINSTALL) @list=''; test -n "$(man5dir)" || exit 0; \ files=`{ for i in $$list; do echo "$$i"; done; \ l2='$(man_MANS)'; for i in $$l2; do echo "$$i"; done | \ sed -n '/\.5[a-z]*$$/p'; \ } | sed -e 's,.*/,,;h;s,.*\.,,;s,^[^5][0-9a-z]*$$,5,;x' \ -e 's,\.[0-9a-z]*$$,,;$(transform);G;s,\n,.,'`; \ dir='$(DESTDIR)$(man5dir)'; $(am__uninstall_files_from_dir) install-man7: $(man_MANS) @$(NORMAL_INSTALL) @list1=''; \ list2='$(man_MANS)'; \ test -n "$(man7dir)" \ && test -n "`echo $$list1$$list2`" \ || exit 0; \ echo " $(MKDIR_P) '$(DESTDIR)$(man7dir)'"; \ $(MKDIR_P) "$(DESTDIR)$(man7dir)" || exit 1; \ { for i in $$list1; do echo "$$i"; done; \ if test -n "$$list2"; then \ for i in $$list2; do echo "$$i"; done \ | sed -n '/\.7[a-z]*$$/p'; \ fi; \ } | while read p; do \ if test -f $$p; then d=; else d="$(srcdir)/"; fi; \ echo "$$d$$p"; echo "$$p"; \ done | \ sed -e 'n;s,.*/,,;p;h;s,.*\.,,;s,^[^7][0-9a-z]*$$,7,;x' \ -e 's,\.[0-9a-z]*$$,,;$(transform);G;s,\n,.,' | \ sed 'N;N;s,\n, ,g' | { \ list=; while read file base inst; do \ if test "$$base" = "$$inst"; then list="$$list $$file"; else \ echo " $(INSTALL_DATA) '$$file' '$(DESTDIR)$(man7dir)/$$inst'"; \ $(INSTALL_DATA) "$$file" "$(DESTDIR)$(man7dir)/$$inst" || exit $$?; \ fi; \ done; \ for i in $$list; do echo "$$i"; done | $(am__base_list) | \ while read files; do \ test -z "$$files" || { \ echo " $(INSTALL_DATA) $$files '$(DESTDIR)$(man7dir)'"; \ $(INSTALL_DATA) $$files "$(DESTDIR)$(man7dir)" || exit $$?; }; \ done; } uninstall-man7: @$(NORMAL_UNINSTALL) @list=''; test -n "$(man7dir)" || exit 0; \ files=`{ for i in $$list; do echo "$$i"; done; \ l2='$(man_MANS)'; for i in $$l2; do echo "$$i"; done | \ sed -n '/\.7[a-z]*$$/p'; \ } | sed -e 's,.*/,,;h;s,.*\.,,;s,^[^7][0-9a-z]*$$,7,;x' \ -e 's,\.[0-9a-z]*$$,,;$(transform);G;s,\n,.,'`; \ dir='$(DESTDIR)$(man7dir)'; $(am__uninstall_files_from_dir) install-man8: $(man_MANS) @$(NORMAL_INSTALL) @list1=''; \ list2='$(man_MANS)'; \ test -n "$(man8dir)" \ && test -n "`echo $$list1$$list2`" \ || exit 0; \ echo " $(MKDIR_P) '$(DESTDIR)$(man8dir)'"; \ $(MKDIR_P) "$(DESTDIR)$(man8dir)" || exit 1; \ { for i in $$list1; do echo "$$i"; done; \ if test -n "$$list2"; then \ for i in $$list2; do echo "$$i"; done \ | sed -n '/\.8[a-z]*$$/p'; \ fi; \ } | while read p; do \ if test -f $$p; then d=; else d="$(srcdir)/"; fi; \ echo "$$d$$p"; echo "$$p"; \ done | \ sed -e 'n;s,.*/,,;p;h;s,.*\.,,;s,^[^8][0-9a-z]*$$,8,;x' \ -e 's,\.[0-9a-z]*$$,,;$(transform);G;s,\n,.,' | \ sed 'N;N;s,\n, ,g' | { \ list=; while read file base inst; do \ if test "$$base" = "$$inst"; then list="$$list $$file"; else \ echo " $(INSTALL_DATA) '$$file' '$(DESTDIR)$(man8dir)/$$inst'"; \ $(INSTALL_DATA) "$$file" "$(DESTDIR)$(man8dir)/$$inst" || exit $$?; \ fi; \ done; \ for i in $$list; do echo "$$i"; done | $(am__base_list) | \ while read files; do \ test -z "$$files" || { \ echo " $(INSTALL_DATA) $$files '$(DESTDIR)$(man8dir)'"; \ $(INSTALL_DATA) $$files "$(DESTDIR)$(man8dir)" || exit $$?; }; \ done; } uninstall-man8: @$(NORMAL_UNINSTALL) @list=''; test -n "$(man8dir)" || exit 0; \ files=`{ for i in $$list; do echo "$$i"; done; \ l2='$(man_MANS)'; for i in $$l2; do echo "$$i"; done | \ sed -n '/\.8[a-z]*$$/p'; \ } | sed -e 's,.*/,,;h;s,.*\.,,;s,^[^8][0-9a-z]*$$,8,;x' \ -e 's,\.[0-9a-z]*$$,,;$(transform);G;s,\n,.,'`; \ dir='$(DESTDIR)$(man8dir)'; $(am__uninstall_files_from_dir) install-dist_includeHEADERS: $(dist_include_HEADERS) @$(NORMAL_INSTALL) @list='$(dist_include_HEADERS)'; test -n "$(includedir)" || list=; \ if test -n "$$list"; then \ echo " $(MKDIR_P) '$(DESTDIR)$(includedir)'"; \ $(MKDIR_P) "$(DESTDIR)$(includedir)" || exit 1; \ fi; \ for p in $$list; do \ if test -f "$$p"; then d=; else d="$(srcdir)/"; fi; \ echo "$$d$$p"; \ done | $(am__base_list) | \ while read files; do \ echo " $(INSTALL_HEADER) $$files '$(DESTDIR)$(includedir)'"; \ $(INSTALL_HEADER) $$files "$(DESTDIR)$(includedir)" || exit $$?; \ done uninstall-dist_includeHEADERS: @$(NORMAL_UNINSTALL) @list='$(dist_include_HEADERS)'; test -n "$(includedir)" || list=; \ files=`for p in $$list; do echo $$p; done | sed -e 's|^.*/||'`; \ dir='$(DESTDIR)$(includedir)'; $(am__uninstall_files_from_dir) install-krb5HEADERS: $(krb5_HEADERS) @$(NORMAL_INSTALL) @list='$(krb5_HEADERS)'; test -n "$(krb5dir)" || list=; \ if test -n "$$list"; then \ echo " $(MKDIR_P) '$(DESTDIR)$(krb5dir)'"; \ $(MKDIR_P) "$(DESTDIR)$(krb5dir)" || exit 1; \ fi; \ for p in $$list; do \ if test -f "$$p"; then d=; else d="$(srcdir)/"; fi; \ echo "$$d$$p"; \ done | $(am__base_list) | \ while read files; do \ echo " $(INSTALL_HEADER) $$files '$(DESTDIR)$(krb5dir)'"; \ $(INSTALL_HEADER) $$files "$(DESTDIR)$(krb5dir)" || exit $$?; \ done uninstall-krb5HEADERS: @$(NORMAL_UNINSTALL) @list='$(krb5_HEADERS)'; test -n "$(krb5dir)" || list=; \ files=`for p in $$list; do echo $$p; done | sed -e 's|^.*/||'`; \ dir='$(DESTDIR)$(krb5dir)'; $(am__uninstall_files_from_dir) install-nodist_includeHEADERS: $(nodist_include_HEADERS) @$(NORMAL_INSTALL) @list='$(nodist_include_HEADERS)'; test -n "$(includedir)" || list=; \ if test -n "$$list"; then \ echo " $(MKDIR_P) '$(DESTDIR)$(includedir)'"; \ $(MKDIR_P) "$(DESTDIR)$(includedir)" || exit 1; \ fi; \ for p in $$list; do \ if test -f "$$p"; then d=; else d="$(srcdir)/"; fi; \ echo "$$d$$p"; \ done | $(am__base_list) | \ while read files; do \ echo " $(INSTALL_HEADER) $$files '$(DESTDIR)$(includedir)'"; \ $(INSTALL_HEADER) $$files "$(DESTDIR)$(includedir)" || exit $$?; \ done uninstall-nodist_includeHEADERS: @$(NORMAL_UNINSTALL) @list='$(nodist_include_HEADERS)'; test -n "$(includedir)" || list=; \ files=`for p in $$list; do echo $$p; done | sed -e 's|^.*/||'`; \ dir='$(DESTDIR)$(includedir)'; $(am__uninstall_files_from_dir) ID: $(am__tagged_files) $(am__define_uniq_tagged_files); mkid -fID $$unique tags: tags-am TAGS: tags tags-am: $(TAGS_DEPENDENCIES) $(am__tagged_files) set x; \ here=`pwd`; \ $(am__define_uniq_tagged_files); \ shift; \ if test -z "$(ETAGS_ARGS)$$*$$unique"; then :; else \ test -n "$$unique" || unique=$$empty_fix; \ if test $$# -gt 0; then \ $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ "$$@" $$unique; \ else \ $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ $$unique; \ fi; \ fi ctags: ctags-am CTAGS: ctags ctags-am: $(TAGS_DEPENDENCIES) $(am__tagged_files) $(am__define_uniq_tagged_files); \ test -z "$(CTAGS_ARGS)$$unique" \ || $(CTAGS) $(CTAGSFLAGS) $(AM_CTAGSFLAGS) $(CTAGS_ARGS) \ $$unique GTAGS: here=`$(am__cd) $(top_builddir) && pwd` \ && $(am__cd) $(top_srcdir) \ && gtags -i $(GTAGS_ARGS) "$$here" cscopelist: cscopelist-am cscopelist-am: $(am__tagged_files) list='$(am__tagged_files)'; \ case "$(srcdir)" in \ [\\/]* | ?:[\\/]*) sdir="$(srcdir)" ;; \ *) sdir=$(subdir)/$(srcdir) ;; \ esac; \ for i in $$list; do \ if test -f "$$i"; then \ echo "$(subdir)/$$i"; \ else \ echo "$$sdir/$$i"; \ fi; \ done >> $(top_builddir)/cscope.files distclean-tags: -rm -f TAGS ID GTAGS GRTAGS GSYMS GPATH tags # Recover from deleted '.trs' file; this should ensure that # "rm -f foo.log; make foo.trs" re-run 'foo.test', and re-create # both 'foo.log' and 'foo.trs'. Break the recipe in two subshells # to avoid problems with "make -n". .log.trs: rm -f $< $@ $(MAKE) $(AM_MAKEFLAGS) $< # Leading 'am--fnord' is there to ensure the list of targets does not # expand to empty, as could happen e.g. with make check TESTS=''. am--fnord $(TEST_LOGS) $(TEST_LOGS:.log=.trs): $(am__force_recheck) am--force-recheck: @: $(TEST_SUITE_LOG): $(TEST_LOGS) @$(am__set_TESTS_bases); \ am__f_ok () { test -f "$$1" && test -r "$$1"; }; \ redo_bases=`for i in $$bases; do \ am__f_ok $$i.trs && am__f_ok $$i.log || echo $$i; \ done`; \ if test -n "$$redo_bases"; then \ redo_logs=`for i in $$redo_bases; do echo $$i.log; done`; \ redo_results=`for i in $$redo_bases; do echo $$i.trs; done`; \ if $(am__make_dryrun); then :; else \ rm -f $$redo_logs && rm -f $$redo_results || exit 1; \ fi; \ fi; \ if test -n "$$am__remaking_logs"; then \ echo "fatal: making $(TEST_SUITE_LOG): possible infinite" \ "recursion detected" >&2; \ elif test -n "$$redo_logs"; then \ am__remaking_logs=yes $(MAKE) $(AM_MAKEFLAGS) $$redo_logs; \ fi; \ if $(am__make_dryrun); then :; else \ st=0; \ errmsg="fatal: making $(TEST_SUITE_LOG): failed to create"; \ for i in $$redo_bases; do \ test -f $$i.trs && test -r $$i.trs \ || { echo "$$errmsg $$i.trs" >&2; st=1; }; \ test -f $$i.log && test -r $$i.log \ || { echo "$$errmsg $$i.log" >&2; st=1; }; \ done; \ test $$st -eq 0 || exit 1; \ fi @$(am__sh_e_setup); $(am__tty_colors); $(am__set_TESTS_bases); \ ws='[ ]'; \ results=`for b in $$bases; do echo $$b.trs; done`; \ test -n "$$results" || results=/dev/null; \ all=` grep "^$$ws*:test-result:" $$results | wc -l`; \ pass=` grep "^$$ws*:test-result:$$ws*PASS" $$results | wc -l`; \ fail=` grep "^$$ws*:test-result:$$ws*FAIL" $$results | wc -l`; \ skip=` grep "^$$ws*:test-result:$$ws*SKIP" $$results | wc -l`; \ xfail=`grep "^$$ws*:test-result:$$ws*XFAIL" $$results | wc -l`; \ xpass=`grep "^$$ws*:test-result:$$ws*XPASS" $$results | wc -l`; \ error=`grep "^$$ws*:test-result:$$ws*ERROR" $$results | wc -l`; \ if test `expr $$fail + $$xpass + $$error` -eq 0; then \ success=true; \ else \ success=false; \ fi; \ br='==================='; br=$$br$$br$$br$$br; \ result_count () \ { \ if test x"$$1" = x"--maybe-color"; then \ maybe_colorize=yes; \ elif test x"$$1" = x"--no-color"; then \ maybe_colorize=no; \ else \ echo "$@: invalid 'result_count' usage" >&2; exit 4; \ fi; \ shift; \ desc=$$1 count=$$2; \ if test $$maybe_colorize = yes && test $$count -gt 0; then \ color_start=$$3 color_end=$$std; \ else \ color_start= color_end=; \ fi; \ echo "$${color_start}# $$desc $$count$${color_end}"; \ }; \ create_testsuite_report () \ { \ result_count $$1 "TOTAL:" $$all "$$brg"; \ result_count $$1 "PASS: " $$pass "$$grn"; \ result_count $$1 "SKIP: " $$skip "$$blu"; \ result_count $$1 "XFAIL:" $$xfail "$$lgn"; \ result_count $$1 "FAIL: " $$fail "$$red"; \ result_count $$1 "XPASS:" $$xpass "$$red"; \ result_count $$1 "ERROR:" $$error "$$mgn"; \ }; \ { \ echo "$(PACKAGE_STRING): $(subdir)/$(TEST_SUITE_LOG)" | \ $(am__rst_title); \ create_testsuite_report --no-color; \ echo; \ echo ".. contents:: :depth: 2"; \ echo; \ for b in $$bases; do echo $$b; done \ | $(am__create_global_log); \ } >$(TEST_SUITE_LOG).tmp || exit 1; \ mv $(TEST_SUITE_LOG).tmp $(TEST_SUITE_LOG); \ if $$success; then \ col="$$grn"; \ else \ col="$$red"; \ test x"$$VERBOSE" = x || cat $(TEST_SUITE_LOG); \ fi; \ echo "$${col}$$br$${std}"; \ echo "$${col}Testsuite summary for $(PACKAGE_STRING)$${std}"; \ echo "$${col}$$br$${std}"; \ create_testsuite_report --maybe-color; \ echo "$$col$$br$$std"; \ if $$success; then :; else \ echo "$${col}See $(subdir)/$(TEST_SUITE_LOG)$${std}"; \ if test -n "$(PACKAGE_BUGREPORT)"; then \ echo "$${col}Please report to $(PACKAGE_BUGREPORT)$${std}"; \ fi; \ echo "$$col$$br$$std"; \ fi; \ $$success || exit 1 check-TESTS: @list='$(RECHECK_LOGS)'; test -z "$$list" || rm -f $$list @list='$(RECHECK_LOGS:.log=.trs)'; test -z "$$list" || rm -f $$list @test -z "$(TEST_SUITE_LOG)" || rm -f $(TEST_SUITE_LOG) @set +e; $(am__set_TESTS_bases); \ log_list=`for i in $$bases; do echo $$i.log; done`; \ trs_list=`for i in $$bases; do echo $$i.trs; done`; \ log_list=`echo $$log_list`; trs_list=`echo $$trs_list`; \ $(MAKE) $(AM_MAKEFLAGS) $(TEST_SUITE_LOG) TEST_LOGS="$$log_list"; \ exit $$?; recheck: all $(check_PROGRAMS) $(check_DATA) @test -z "$(TEST_SUITE_LOG)" || rm -f $(TEST_SUITE_LOG) @set +e; $(am__set_TESTS_bases); \ bases=`for i in $$bases; do echo $$i; done \ | $(am__list_recheck_tests)` || exit 1; \ log_list=`for i in $$bases; do echo $$i.log; done`; \ log_list=`echo $$log_list`; \ $(MAKE) $(AM_MAKEFLAGS) $(TEST_SUITE_LOG) \ am__force_recheck=am--force-recheck \ TEST_LOGS="$$log_list"; \ exit $$? aes-test.log: aes-test$(EXEEXT) @p='aes-test$(EXEEXT)'; \ b='aes-test'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) derived-key-test.log: derived-key-test$(EXEEXT) @p='derived-key-test$(EXEEXT)'; \ b='derived-key-test'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) n-fold-test.log: n-fold-test$(EXEEXT) @p='n-fold-test$(EXEEXT)'; \ b='n-fold-test'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) parse-name-test.log: parse-name-test$(EXEEXT) @p='parse-name-test$(EXEEXT)'; \ b='parse-name-test'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) pseudo-random-test.log: pseudo-random-test$(EXEEXT) @p='pseudo-random-test$(EXEEXT)'; \ b='pseudo-random-test'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) store-test.log: store-test$(EXEEXT) @p='store-test$(EXEEXT)'; \ b='store-test'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) string-to-key-test.log: string-to-key-test$(EXEEXT) @p='string-to-key-test$(EXEEXT)'; \ b='string-to-key-test'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_acl.log: test_acl$(EXEEXT) @p='test_acl$(EXEEXT)'; \ b='test_acl'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_addr.log: test_addr$(EXEEXT) @p='test_addr$(EXEEXT)'; \ b='test_addr'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_cc.log: test_cc$(EXEEXT) @p='test_cc$(EXEEXT)'; \ b='test_cc'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_config.log: test_config$(EXEEXT) @p='test_config$(EXEEXT)'; \ b='test_config'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_fx.log: test_fx$(EXEEXT) @p='test_fx$(EXEEXT)'; \ b='test_fx'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_prf.log: test_prf$(EXEEXT) @p='test_prf$(EXEEXT)'; \ b='test_prf'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_store.log: test_store$(EXEEXT) @p='test_store$(EXEEXT)'; \ b='test_store'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_crypto_wrapping.log: test_crypto_wrapping$(EXEEXT) @p='test_crypto_wrapping$(EXEEXT)'; \ b='test_crypto_wrapping'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_keytab.log: test_keytab$(EXEEXT) @p='test_keytab$(EXEEXT)'; \ b='test_keytab'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_mem.log: test_mem$(EXEEXT) @p='test_mem$(EXEEXT)'; \ b='test_mem'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_pac.log: test_pac$(EXEEXT) @p='test_pac$(EXEEXT)'; \ b='test_pac'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_plugin.log: test_plugin$(EXEEXT) @p='test_plugin$(EXEEXT)'; \ b='test_plugin'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_princ.log: test_princ$(EXEEXT) @p='test_princ$(EXEEXT)'; \ b='test_princ'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_pkinit_dh2key.log: test_pkinit_dh2key$(EXEEXT) @p='test_pkinit_dh2key$(EXEEXT)'; \ b='test_pkinit_dh2key'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_pknistkdf.log: test_pknistkdf$(EXEEXT) @p='test_pknistkdf$(EXEEXT)'; \ b='test_pknistkdf'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_time.log: test_time$(EXEEXT) @p='test_time$(EXEEXT)'; \ b='test_time'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_expand_toks.log: test_expand_toks$(EXEEXT) @p='test_expand_toks$(EXEEXT)'; \ b='test_expand_toks'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_x500.log: test_x500$(EXEEXT) @p='test_x500$(EXEEXT)'; \ b='test_x500'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) .test.log: @p='$<'; \ $(am__set_b); \ $(am__check_pre) $(TEST_LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_TEST_LOG_DRIVER_FLAGS) $(TEST_LOG_DRIVER_FLAGS) -- $(TEST_LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) @am__EXEEXT_TRUE@.test$(EXEEXT).log: @am__EXEEXT_TRUE@ @p='$<'; \ @am__EXEEXT_TRUE@ $(am__set_b); \ @am__EXEEXT_TRUE@ $(am__check_pre) $(TEST_LOG_DRIVER) --test-name "$$f" \ @am__EXEEXT_TRUE@ --log-file $$b.log --trs-file $$b.trs \ @am__EXEEXT_TRUE@ $(am__common_driver_flags) $(AM_TEST_LOG_DRIVER_FLAGS) $(TEST_LOG_DRIVER_FLAGS) -- $(TEST_LOG_COMPILE) \ @am__EXEEXT_TRUE@ "$$tst" $(AM_TESTS_FD_REDIRECT) distdir: $(DISTFILES) @srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ topsrcdirstrip=`echo "$(top_srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ list='$(DISTFILES)'; \ dist_files=`for file in $$list; do echo $$file; done | \ sed -e "s|^$$srcdirstrip/||;t" \ -e "s|^$$topsrcdirstrip/|$(top_builddir)/|;t"`; \ case $$dist_files in \ */*) $(MKDIR_P) `echo "$$dist_files" | \ sed '/\//!d;s|^|$(distdir)/|;s,/[^/]*$$,,' | \ sort -u` ;; \ esac; \ for file in $$dist_files; do \ if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \ if test -d $$d/$$file; then \ dir=`echo "/$$file" | sed -e 's,/[^/]*$$,,'`; \ if test -d "$(distdir)/$$file"; then \ find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ fi; \ if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \ cp -fpR $(srcdir)/$$file "$(distdir)$$dir" || exit 1; \ find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ fi; \ cp -fpR $$d/$$file "$(distdir)$$dir" || exit 1; \ else \ test -f "$(distdir)/$$file" \ || cp -p $$d/$$file "$(distdir)/$$file" \ || exit 1; \ fi; \ done $(MAKE) $(AM_MAKEFLAGS) \ top_distdir="$(top_distdir)" distdir="$(distdir)" \ dist-hook check-am: all-am $(MAKE) $(AM_MAKEFLAGS) $(check_PROGRAMS) $(check_DATA) $(MAKE) $(AM_MAKEFLAGS) check-TESTS check-local check: check-am all-am: Makefile $(LTLIBRARIES) $(PROGRAMS) $(MANS) $(HEADERS) \ all-local install-binPROGRAMS: install-libLTLIBRARIES installdirs: for dir in "$(DESTDIR)$(libdir)" "$(DESTDIR)$(bindir)" "$(DESTDIR)$(man3dir)" "$(DESTDIR)$(man5dir)" "$(DESTDIR)$(man7dir)" "$(DESTDIR)$(man8dir)" "$(DESTDIR)$(includedir)" "$(DESTDIR)$(krb5dir)" "$(DESTDIR)$(includedir)"; do \ test -z "$$dir" || $(MKDIR_P) "$$dir"; \ done install: install-am install-exec: install-exec-am install-data: install-data-am uninstall: uninstall-am install-am: all-am @$(MAKE) $(AM_MAKEFLAGS) install-exec-am install-data-am installcheck: installcheck-am install-strip: if test -z '$(STRIP)'; then \ $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ install; \ else \ $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'" install; \ fi mostlyclean-generic: -test -z "$(TEST_LOGS)" || rm -f $(TEST_LOGS) -test -z "$(TEST_LOGS:.log=.trs)" || rm -f $(TEST_LOGS:.log=.trs) -test -z "$(TEST_SUITE_LOG)" || rm -f $(TEST_SUITE_LOG) clean-generic: -test -z "$(CLEANFILES)" || rm -f $(CLEANFILES) distclean-generic: -test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES) -test . = "$(srcdir)" || test -z "$(CONFIG_CLEAN_VPATH_FILES)" || rm -f $(CONFIG_CLEAN_VPATH_FILES) maintainer-clean-generic: @echo "This command is intended for maintainers to use" @echo "it deletes files that may require special tools to rebuild." clean: clean-am clean-am: clean-binPROGRAMS clean-checkPROGRAMS clean-generic \ clean-libLTLIBRARIES clean-libtool clean-noinstLTLIBRARIES \ clean-noinstPROGRAMS mostlyclean-am distclean: distclean-am -rm -rf ./$(DEPDIR) -rm -f Makefile distclean-am: clean-am distclean-compile distclean-generic \ distclean-tags dvi: dvi-am dvi-am: html: html-am html-am: info: info-am info-am: install-data-am: install-dist_includeHEADERS install-krb5HEADERS \ install-man install-nodist_includeHEADERS @$(NORMAL_INSTALL) $(MAKE) $(AM_MAKEFLAGS) install-data-hook install-dvi: install-dvi-am install-dvi-am: install-exec-am: install-binPROGRAMS install-exec-local \ install-libLTLIBRARIES install-html: install-html-am install-html-am: install-info: install-info-am install-info-am: install-man: install-man3 install-man5 install-man7 install-man8 install-pdf: install-pdf-am install-pdf-am: install-ps: install-ps-am install-ps-am: installcheck-am: maintainer-clean: maintainer-clean-am -rm -rf ./$(DEPDIR) -rm -f Makefile maintainer-clean-am: distclean-am maintainer-clean-generic mostlyclean: mostlyclean-am mostlyclean-am: mostlyclean-compile mostlyclean-generic \ mostlyclean-libtool pdf: pdf-am pdf-am: ps: ps-am ps-am: uninstall-am: uninstall-binPROGRAMS uninstall-dist_includeHEADERS \ uninstall-krb5HEADERS uninstall-libLTLIBRARIES uninstall-man \ uninstall-nodist_includeHEADERS @$(NORMAL_INSTALL) $(MAKE) $(AM_MAKEFLAGS) uninstall-hook uninstall-man: uninstall-man3 uninstall-man5 uninstall-man7 \ uninstall-man8 .MAKE: check-am install-am install-data-am install-strip uninstall-am .PHONY: CTAGS GTAGS TAGS all all-am all-local check check-TESTS \ check-am check-local clean clean-binPROGRAMS \ clean-checkPROGRAMS clean-generic clean-libLTLIBRARIES \ clean-libtool clean-noinstLTLIBRARIES clean-noinstPROGRAMS \ cscopelist-am ctags ctags-am dist-hook distclean \ distclean-compile distclean-generic distclean-libtool \ distclean-tags distdir dvi dvi-am html html-am info info-am \ install install-am install-binPROGRAMS install-data \ install-data-am install-data-hook install-dist_includeHEADERS \ install-dvi install-dvi-am install-exec install-exec-am \ install-exec-local install-html install-html-am install-info \ install-info-am install-krb5HEADERS install-libLTLIBRARIES \ install-man install-man3 install-man5 install-man7 \ install-man8 install-nodist_includeHEADERS install-pdf \ install-pdf-am install-ps install-ps-am install-strip \ installcheck installcheck-am installdirs maintainer-clean \ maintainer-clean-generic mostlyclean mostlyclean-compile \ mostlyclean-generic mostlyclean-libtool pdf pdf-am ps ps-am \ recheck tags tags-am uninstall uninstall-am \ uninstall-binPROGRAMS uninstall-dist_includeHEADERS \ uninstall-hook uninstall-krb5HEADERS uninstall-libLTLIBRARIES \ uninstall-man uninstall-man3 uninstall-man5 uninstall-man7 \ uninstall-man8 uninstall-nodist_includeHEADERS .PRECIOUS: Makefile install-suid-programs: @foo='$(bin_SUIDS)'; \ for file in $$foo; do \ x=$(DESTDIR)$(bindir)/$$file; \ if chown 0:0 $$x && chmod u+s $$x; then :; else \ echo "*"; \ echo "* Failed to install $$x setuid root"; \ echo "*"; \ fi; \ done install-exec-local: install-suid-programs codesign-all: @if [ X"$$CODE_SIGN_IDENTITY" != X ] ; then \ foo='$(bin_PROGRAMS) $(sbin_PROGRAMS) $(libexec_PROGRAMS)' ; \ for file in $$foo ; do \ echo "CODESIGN $$file" ; \ codesign -f -s "$$CODE_SIGN_IDENTITY" $$file || exit 1 ; \ done ; \ fi all-local: codesign-all install-build-headers:: $(include_HEADERS) $(dist_include_HEADERS) $(nodist_include_HEADERS) $(build_HEADERZ) $(nobase_include_HEADERS) $(noinst_HEADERS) @foo='$(include_HEADERS) $(dist_include_HEADERS) $(nodist_include_HEADERS) $(build_HEADERZ) $(noinst_HEADERS)'; \ for f in $$foo; do \ f=`basename $$f`; \ if test -f "$(srcdir)/$$f"; then file="$(srcdir)/$$f"; \ else file="$$f"; fi; \ if cmp -s $$file $(buildinclude)/$$f 2> /dev/null ; then \ : ; else \ echo " $(CP) $$file $(buildinclude)/$$f"; \ $(CP) $$file $(buildinclude)/$$f || true; \ fi ; \ done ; \ foo='$(nobase_include_HEADERS)'; \ for f in $$foo; do \ if test -f "$(srcdir)/$$f"; then file="$(srcdir)/$$f"; \ else file="$$f"; fi; \ $(mkdir_p) $(buildinclude)/`dirname $$f` ; \ if cmp -s $$file $(buildinclude)/$$f 2> /dev/null ; then \ : ; else \ echo " $(CP) $$file $(buildinclude)/$$f"; \ $(CP) $$file $(buildinclude)/$$f; \ fi ; \ done all-local: install-build-headers check-local:: @if test '$(CHECK_LOCAL)' = "no-check-local"; then \ foo=''; elif test '$(CHECK_LOCAL)'; then \ foo='$(CHECK_LOCAL)'; else \ foo='$(PROGRAMS)'; fi; \ if test "$$foo"; then \ failed=0; all=0; \ for i in $$foo; do \ all=`expr $$all + 1`; \ if (./$$i --version && ./$$i --help) > /dev/null 2>&1; then \ echo "PASS: $$i"; \ else \ echo "FAIL: $$i"; \ failed=`expr $$failed + 1`; \ fi; \ done; \ if test "$$failed" -eq 0; then \ banner="All $$all tests passed"; \ else \ banner="$$failed of $$all tests failed"; \ fi; \ dashes=`echo "$$banner" | sed s/./=/g`; \ echo "$$dashes"; \ echo "$$banner"; \ echo "$$dashes"; \ test "$$failed" -eq 0 || exit 1; \ fi .x.c: @cmp -s $< $@ 2> /dev/null || cp $< $@ .hx.h: @cmp -s $< $@ 2> /dev/null || cp $< $@ #NROFF_MAN = nroff -man .1.cat1: $(NROFF_MAN) $< > $@ .3.cat3: $(NROFF_MAN) $< > $@ .5.cat5: $(NROFF_MAN) $< > $@ .7.cat7: $(NROFF_MAN) $< > $@ .8.cat8: $(NROFF_MAN) $< > $@ dist-cat1-mans: @foo='$(man1_MANS)'; \ bar='$(man_MANS)'; \ for i in $$bar; do \ case $$i in \ *.1) foo="$$foo $$i";; \ esac; done ;\ for i in $$foo; do \ x=`echo $$i | sed 's/\.[^.]*$$/.cat1/'`; \ echo "$(NROFF_MAN) $(srcdir)/$$i > $(distdir)/$$x"; \ $(NROFF_MAN) $(srcdir)/$$i > $(distdir)/$$x; \ done dist-cat3-mans: @foo='$(man3_MANS)'; \ bar='$(man_MANS)'; \ for i in $$bar; do \ case $$i in \ *.3) foo="$$foo $$i";; \ esac; done ;\ for i in $$foo; do \ x=`echo $$i | sed 's/\.[^.]*$$/.cat3/'`; \ echo "$(NROFF_MAN) $(srcdir)/$$i > $(distdir)/$$x"; \ $(NROFF_MAN) $(srcdir)/$$i > $(distdir)/$$x; \ done dist-cat5-mans: @foo='$(man5_MANS)'; \ bar='$(man_MANS)'; \ for i in $$bar; do \ case $$i in \ *.5) foo="$$foo $$i";; \ esac; done ;\ for i in $$foo; do \ x=`echo $$i | sed 's/\.[^.]*$$/.cat5/'`; \ echo "$(NROFF_MAN) $(srcdir)/$$i > $(distdir)/$$x"; \ $(NROFF_MAN) $(srcdir)/$$i > $(distdir)/$$x; \ done dist-cat7-mans: @foo='$(man7_MANS)'; \ bar='$(man_MANS)'; \ for i in $$bar; do \ case $$i in \ *.7) foo="$$foo $$i";; \ esac; done ;\ for i in $$foo; do \ x=`echo $$i | sed 's/\.[^.]*$$/.cat7/'`; \ echo "$(NROFF_MAN) $(srcdir)/$$i > $(distdir)/$$x"; \ $(NROFF_MAN) $(srcdir)/$$i > $(distdir)/$$x; \ done dist-cat8-mans: @foo='$(man8_MANS)'; \ bar='$(man_MANS)'; \ for i in $$bar; do \ case $$i in \ *.8) foo="$$foo $$i";; \ esac; done ;\ for i in $$foo; do \ x=`echo $$i | sed 's/\.[^.]*$$/.cat8/'`; \ echo "$(NROFF_MAN) $(srcdir)/$$i > $(distdir)/$$x"; \ $(NROFF_MAN) $(srcdir)/$$i > $(distdir)/$$x; \ done dist-hook: dist-cat1-mans dist-cat3-mans dist-cat5-mans dist-cat7-mans dist-cat8-mans install-cat-mans: $(SHELL) $(top_srcdir)/cf/install-catman.sh install "$(INSTALL_DATA)" "$(mkinstalldirs)" "$(srcdir)" "$(DESTDIR)$(mandir)" '$(CATMANEXT)' $(man_MANS) $(man1_MANS) $(man3_MANS) $(man5_MANS) $(man7_MANS) $(man8_MANS) uninstall-cat-mans: $(SHELL) $(top_srcdir)/cf/install-catman.sh uninstall "$(INSTALL_DATA)" "$(mkinstalldirs)" "$(srcdir)" "$(DESTDIR)$(mandir)" '$(CATMANEXT)' $(man_MANS) $(man1_MANS) $(man3_MANS) $(man5_MANS) $(man7_MANS) $(man8_MANS) install-data-hook: install-cat-mans uninstall-hook: uninstall-cat-mans .et.h: $(COMPILE_ET) $< .et.c: $(COMPILE_ET) $< # # Useful target for debugging # check-valgrind: tobjdir=`cd $(top_builddir) && pwd` ; \ tsrcdir=`cd $(top_srcdir) && pwd` ; \ env TESTS_ENVIRONMENT="$${tsrcdir}/cf/maybe-valgrind.sh -s $${tsrcdir} -o $${tobjdir}" make check # # Target to please samba build farm, builds distfiles in-tree. # Will break when automake changes... # distdir-in-tree: $(DISTFILES) $(INFO_DEPS) list='$(DIST_SUBDIRS)'; for subdir in $$list; do \ if test "$$subdir" != .; then \ (cd $$subdir && $(MAKE) $(AM_MAKEFLAGS) distdir-in-tree) ; \ fi ; \ done $(ALL_OBJECTS): $(srcdir)/krb5-protos.h $(srcdir)/krb5-private.h $(ALL_OBJECTS): krb5_err.h heim_err.h k524_err.h krb5_err.h krb_err.h k524_err.h $(srcdir)/krb5-protos.h: $(headerdeps) @cd $(srcdir) && perl ../../cf/make-proto.pl -E KRB5_LIB -q -P comment -o krb5-protos.h $(dist_libkrb5_la_SOURCES) || rm -f krb5-protos.h $(srcdir)/krb5-private.h: $(headerdeps) @cd $(srcdir) && perl ../../cf/make-proto.pl -q -P comment -p krb5-private.h $(dist_libkrb5_la_SOURCES) || rm -f krb5-private.h $(libkrb5_la_OBJECTS): krb5_err.h krb_err.h heim_err.h k524_err.h test_config_strings.out: test_config_strings.cfg $(CP) $(srcdir)/test_config_strings.cfg test_config_strings.out #sysconf_DATA = krb5.moduli # to help stupid solaris make krb5_err.h: krb5_err.et krb_err.h: krb_err.et heim_err.h: heim_err.et k524_err.h: k524_err.et # Tell versions [3.59,3.63) of GNU make to not export all variables. # Otherwise a system limit (for SysV at least) may be exceeded. .NOEXPORT: heimdal-7.5.0/lib/krb5/send_to_kdc_plugin.h0000644000175000017500000000517713026237312016677 0ustar niknik/* * Copyright (c) 2008 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ /* $Id$ */ #ifndef HEIMDAL_KRB5_SEND_TO_KDC_PLUGIN_H #define HEIMDAL_KRB5_SEND_TO_KDC_PLUGIN_H 1 #include #define KRB5_PLUGIN_SEND_TO_KDC "send_to_kdc" #define KRB5_PLUGIN_SEND_TO_KDC_VERSION_0 0 #define KRB5_PLUGIN_SEND_TO_KDC_VERSION_2 2 #define KRB5_PLUGIN_SEND_TO_KDC_VERSION KRB5_PLUGIN_SEND_TO_KDC_VERSION_2 typedef krb5_error_code (*krb5plugin_send_to_kdc_func)(krb5_context, void *, krb5_krbhst_info *, time_t timeout, const krb5_data *, krb5_data *); typedef krb5_error_code (*krb5plugin_send_to_realm_func)(krb5_context, void *, krb5_const_realm, time_t timeout, const krb5_data *, krb5_data *); typedef struct krb5plugin_send_to_kdc_ftable { int minor_version; krb5_error_code (*init)(krb5_context, void **); void (*fini)(void *); krb5plugin_send_to_kdc_func send_to_kdc; krb5plugin_send_to_realm_func send_to_realm; /* added in version 2 */ } krb5plugin_send_to_kdc_ftable; #endif /* HEIMDAL_KRB5_SEND_TO_KDC_PLUGIN_H */ heimdal-7.5.0/lib/krb5/changepw.c0000644000175000017500000005140713212137553014634 0ustar niknik/* * Copyright (c) 1997 - 2005 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "krb5_locl.h" #undef __attribute__ #define __attribute__(X) static void str2data (krb5_data *d, const char *fmt, ...) __attribute__ ((__format__ (__printf__, 2, 3))); static void str2data (krb5_data *d, const char *fmt, ...) { va_list args; char *str; va_start(args, fmt); d->length = vasprintf (&str, fmt, args); va_end(args); d->data = str; } /* * Change password protocol defined by * draft-ietf-cat-kerb-chg-password-02.txt * * Share the response part of the protocol with MS set password * (RFC3244) */ static krb5_error_code chgpw_send_request (krb5_context context, krb5_auth_context *auth_context, krb5_creds *creds, krb5_principal targprinc, int is_stream, rk_socket_t sock, const char *passwd, const char *host) { krb5_error_code ret; krb5_data ap_req_data; krb5_data krb_priv_data; krb5_data passwd_data; size_t len; u_char header[6]; struct iovec iov[3]; struct msghdr msghdr; if (is_stream) return KRB5_KPASSWD_MALFORMED; if (targprinc && krb5_principal_compare(context, creds->client, targprinc) != TRUE) return KRB5_KPASSWD_MALFORMED; krb5_data_zero (&ap_req_data); ret = krb5_mk_req_extended (context, auth_context, AP_OPTS_MUTUAL_REQUIRED | AP_OPTS_USE_SUBKEY, NULL, /* in_data */ creds, &ap_req_data); if (ret) return ret; passwd_data.data = rk_UNCONST(passwd); passwd_data.length = strlen(passwd); krb5_data_zero (&krb_priv_data); ret = krb5_mk_priv (context, *auth_context, &passwd_data, &krb_priv_data, NULL); if (ret) goto out2; len = 6 + ap_req_data.length + krb_priv_data.length; header[0] = (len >> 8) & 0xFF; header[1] = (len >> 0) & 0xFF; header[2] = 0; header[3] = 1; header[4] = (ap_req_data.length >> 8) & 0xFF; header[5] = (ap_req_data.length >> 0) & 0xFF; memset(&msghdr, 0, sizeof(msghdr)); msghdr.msg_name = NULL; msghdr.msg_namelen = 0; msghdr.msg_iov = iov; msghdr.msg_iovlen = sizeof(iov)/sizeof(*iov); #if 0 msghdr.msg_control = NULL; msghdr.msg_controllen = 0; #endif iov[0].iov_base = (void*)header; iov[0].iov_len = 6; iov[1].iov_base = ap_req_data.data; iov[1].iov_len = ap_req_data.length; iov[2].iov_base = krb_priv_data.data; iov[2].iov_len = krb_priv_data.length; if (rk_IS_SOCKET_ERROR( sendmsg (sock, &msghdr, 0) )) { ret = rk_SOCK_ERRNO; krb5_set_error_message(context, ret, "sendmsg %s: %s", host, strerror(ret)); } krb5_data_free (&krb_priv_data); out2: krb5_data_free (&ap_req_data); return ret; } /* * Set password protocol as defined by RFC3244 -- * Microsoft Windows 2000 Kerberos Change Password and Set Password Protocols */ static krb5_error_code setpw_send_request (krb5_context context, krb5_auth_context *auth_context, krb5_creds *creds, krb5_principal targprinc, int is_stream, rk_socket_t sock, const char *passwd, const char *host) { krb5_error_code ret; krb5_data ap_req_data; krb5_data krb_priv_data; krb5_data pwd_data; ChangePasswdDataMS chpw; size_t len = 0; u_char header[4 + 6]; u_char *p; struct iovec iov[3]; struct msghdr msghdr; krb5_data_zero (&ap_req_data); ret = krb5_mk_req_extended (context, auth_context, AP_OPTS_MUTUAL_REQUIRED | AP_OPTS_USE_SUBKEY, NULL, /* in_data */ creds, &ap_req_data); if (ret) return ret; chpw.newpasswd.length = strlen(passwd); chpw.newpasswd.data = rk_UNCONST(passwd); if (targprinc) { chpw.targname = &targprinc->name; chpw.targrealm = &targprinc->realm; } else { chpw.targname = NULL; chpw.targrealm = NULL; } ASN1_MALLOC_ENCODE(ChangePasswdDataMS, pwd_data.data, pwd_data.length, &chpw, &len, ret); if (ret) { krb5_data_free (&ap_req_data); return ret; } if(pwd_data.length != len) krb5_abortx(context, "internal error in ASN.1 encoder"); ret = krb5_mk_priv (context, *auth_context, &pwd_data, &krb_priv_data, NULL); if (ret) goto out2; len = 6 + ap_req_data.length + krb_priv_data.length; p = header; if (is_stream) { _krb5_put_int(p, len, 4); p += 4; } *p++ = (len >> 8) & 0xFF; *p++ = (len >> 0) & 0xFF; *p++ = 0xff; *p++ = 0x80; *p++ = (ap_req_data.length >> 8) & 0xFF; *p = (ap_req_data.length >> 0) & 0xFF; memset(&msghdr, 0, sizeof(msghdr)); msghdr.msg_name = NULL; msghdr.msg_namelen = 0; msghdr.msg_iov = iov; msghdr.msg_iovlen = sizeof(iov)/sizeof(*iov); #if 0 msghdr.msg_control = NULL; msghdr.msg_controllen = 0; #endif iov[0].iov_base = (void*)header; if (is_stream) iov[0].iov_len = 10; else iov[0].iov_len = 6; iov[1].iov_base = ap_req_data.data; iov[1].iov_len = ap_req_data.length; iov[2].iov_base = krb_priv_data.data; iov[2].iov_len = krb_priv_data.length; if (rk_IS_SOCKET_ERROR( sendmsg (sock, &msghdr, 0) )) { ret = rk_SOCK_ERRNO; krb5_set_error_message(context, ret, "sendmsg %s: %s", host, strerror(ret)); } krb5_data_free (&krb_priv_data); out2: krb5_data_free (&ap_req_data); krb5_data_free (&pwd_data); return ret; } static krb5_error_code process_reply (krb5_context context, krb5_auth_context auth_context, int is_stream, rk_socket_t sock, int *result_code, krb5_data *result_code_string, krb5_data *result_string, const char *host) { krb5_error_code ret; u_char reply[1024 * 3]; size_t len; uint16_t pkt_len, pkt_ver; krb5_data ap_rep_data; int save_errno; len = 0; if (is_stream) { while (len < sizeof(reply)) { unsigned long size; ret = recvfrom (sock, reply + len, sizeof(reply) - len, 0, NULL, NULL); if (rk_IS_SOCKET_ERROR(ret)) { save_errno = rk_SOCK_ERRNO; krb5_set_error_message(context, save_errno, "recvfrom %s: %s", host, strerror(save_errno)); return save_errno; } else if (ret == 0) { krb5_set_error_message(context, 1,"recvfrom timeout %s", host); return 1; } len += ret; if (len < 4) continue; _krb5_get_int(reply, &size, 4); if (size + 4 < len) continue; if (sizeof(reply) - 4 < size) { krb5_set_error_message(context, ERANGE, "size from server too large %s", host); return ERANGE; } memmove(reply, reply + 4, size); len = size; break; } if (len == sizeof(reply)) { krb5_set_error_message(context, ENOMEM, N_("Message too large from %s", "host"), host); return ENOMEM; } } else { ret = recvfrom (sock, reply, sizeof(reply), 0, NULL, NULL); if (rk_IS_SOCKET_ERROR(ret)) { save_errno = rk_SOCK_ERRNO; krb5_set_error_message(context, save_errno, "recvfrom %s: %s", host, strerror(save_errno)); return save_errno; } len = ret; } if (len < 6) { str2data (result_string, "server %s sent to too short message " "(%llu bytes)", host, (unsigned long long)len); *result_code = KRB5_KPASSWD_MALFORMED; return 0; } pkt_len = (reply[0] << 8) | (reply[1]); pkt_ver = (reply[2] << 8) | (reply[3]); if ((pkt_len != len) || (reply[1] == 0x7e || reply[1] == 0x5e)) { KRB_ERROR error; size_t size; u_char *p; memset(&error, 0, sizeof(error)); ret = decode_KRB_ERROR(reply, len, &error, &size); if (ret) return ret; if (error.e_data->length < 2) { str2data(result_string, "server %s sent too short " "e_data to print anything usable", host); free_KRB_ERROR(&error); *result_code = KRB5_KPASSWD_MALFORMED; return 0; } p = error.e_data->data; *result_code = (p[0] << 8) | p[1]; if (error.e_data->length == 2) str2data(result_string, "server only sent error code"); else krb5_data_copy (result_string, p + 2, error.e_data->length - 2); free_KRB_ERROR(&error); return 0; } if (pkt_len != len) { str2data (result_string, "client: wrong len in reply"); *result_code = KRB5_KPASSWD_MALFORMED; return 0; } if (pkt_ver != KRB5_KPASSWD_VERS_CHANGEPW) { str2data (result_string, "client: wrong version number (%d)", pkt_ver); *result_code = KRB5_KPASSWD_MALFORMED; return 0; } ap_rep_data.data = reply + 6; ap_rep_data.length = (reply[4] << 8) | (reply[5]); if (reply + len < (u_char *)ap_rep_data.data + ap_rep_data.length) { str2data (result_string, "client: wrong AP len in reply"); *result_code = KRB5_KPASSWD_MALFORMED; return 0; } if (ap_rep_data.length) { krb5_ap_rep_enc_part *ap_rep; krb5_data priv_data; u_char *p; priv_data.data = (u_char*)ap_rep_data.data + ap_rep_data.length; priv_data.length = len - ap_rep_data.length - 6; ret = krb5_rd_rep (context, auth_context, &ap_rep_data, &ap_rep); if (ret) return ret; krb5_free_ap_rep_enc_part (context, ap_rep); ret = krb5_rd_priv (context, auth_context, &priv_data, result_code_string, NULL); if (ret) { krb5_data_free (result_code_string); return ret; } if (result_code_string->length < 2) { *result_code = KRB5_KPASSWD_MALFORMED; str2data (result_string, "client: bad length in result"); return 0; } p = result_code_string->data; *result_code = (p[0] << 8) | p[1]; krb5_data_copy (result_string, (unsigned char*)result_code_string->data + 2, result_code_string->length - 2); return 0; } else { KRB_ERROR error; size_t size; u_char *p; ret = decode_KRB_ERROR(reply + 6, len - 6, &error, &size); if (ret) { return ret; } if (error.e_data->length < 2) { krb5_warnx (context, "too short e_data to print anything usable"); return 1; /* XXX */ } p = error.e_data->data; *result_code = (p[0] << 8) | p[1]; krb5_data_copy (result_string, p + 2, error.e_data->length - 2); return 0; } } /* * change the password using the credentials in `creds' (for the * principal indicated in them) to `newpw', storing the result of * the operation in `result_*' and an error code or 0. */ typedef krb5_error_code (*kpwd_send_request) (krb5_context, krb5_auth_context *, krb5_creds *, krb5_principal, int, rk_socket_t, const char *, const char *); typedef krb5_error_code (*kpwd_process_reply) (krb5_context, krb5_auth_context, int, rk_socket_t, int *, krb5_data *, krb5_data *, const char *); static struct kpwd_proc { const char *name; int flags; #define SUPPORT_TCP 1 #define SUPPORT_UDP 2 kpwd_send_request send_req; kpwd_process_reply process_rep; } procs[] = { { "MS set password", SUPPORT_TCP|SUPPORT_UDP, setpw_send_request, process_reply }, { "change password", SUPPORT_UDP, chgpw_send_request, process_reply }, { NULL, 0, NULL, NULL } }; /* * */ static krb5_error_code change_password_loop (krb5_context context, krb5_creds *creds, krb5_principal targprinc, const char *newpw, int *result_code, krb5_data *result_code_string, krb5_data *result_string, struct kpwd_proc *proc) { krb5_error_code ret; krb5_auth_context auth_context = NULL; krb5_krbhst_handle handle = NULL; krb5_krbhst_info *hi; rk_socket_t sock; unsigned int i; int done = 0; krb5_realm realm; if (targprinc) realm = targprinc->realm; else realm = creds->client->realm; ret = krb5_auth_con_init (context, &auth_context); if (ret) return ret; krb5_auth_con_setflags (context, auth_context, KRB5_AUTH_CONTEXT_DO_SEQUENCE); ret = krb5_krbhst_init (context, realm, KRB5_KRBHST_CHANGEPW, &handle); if (ret) goto out; while (!done && (ret = krb5_krbhst_next(context, handle, &hi)) == 0) { struct addrinfo *ai, *a; int is_stream; switch (hi->proto) { case KRB5_KRBHST_UDP: if ((proc->flags & SUPPORT_UDP) == 0) continue; is_stream = 0; break; case KRB5_KRBHST_TCP: if ((proc->flags & SUPPORT_TCP) == 0) continue; is_stream = 1; break; default: continue; } ret = krb5_krbhst_get_addrinfo(context, hi, &ai); if (ret) continue; for (a = ai; !done && a != NULL; a = a->ai_next) { int replied = 0; sock = socket (a->ai_family, a->ai_socktype | SOCK_CLOEXEC, a->ai_protocol); if (rk_IS_BAD_SOCKET(sock)) continue; rk_cloexec(sock); ret = connect(sock, a->ai_addr, a->ai_addrlen); if (rk_IS_SOCKET_ERROR(ret)) { rk_closesocket (sock); goto out; } ret = krb5_auth_con_genaddrs (context, auth_context, sock, KRB5_AUTH_CONTEXT_GENERATE_LOCAL_ADDR); if (ret) { rk_closesocket (sock); goto out; } for (i = 0; !done && i < 5; ++i) { fd_set fdset; struct timeval tv; if (!replied) { replied = 0; ret = (*proc->send_req) (context, &auth_context, creds, targprinc, is_stream, sock, newpw, hi->hostname); if (ret) { rk_closesocket(sock); goto out; } } #ifndef NO_LIMIT_FD_SETSIZE if (sock >= FD_SETSIZE) { ret = ERANGE; krb5_set_error_message(context, ret, "fd %d too large", sock); rk_closesocket (sock); goto out; } #endif FD_ZERO(&fdset); FD_SET(sock, &fdset); tv.tv_usec = 0; tv.tv_sec = 1 + (1 << i); ret = select (sock + 1, &fdset, NULL, NULL, &tv); if (rk_IS_SOCKET_ERROR(ret) && rk_SOCK_ERRNO != EINTR) { rk_closesocket(sock); goto out; } if (ret == 1) { ret = (*proc->process_rep) (context, auth_context, is_stream, sock, result_code, result_code_string, result_string, hi->hostname); if (ret == 0) done = 1; else if (i > 0 && ret == KRB5KRB_AP_ERR_MUT_FAIL) replied = 1; } else { ret = KRB5_KDC_UNREACH; } } rk_closesocket (sock); } } out: krb5_krbhst_free (context, handle); krb5_auth_con_free (context, auth_context); if (ret == KRB5_KDC_UNREACH) { krb5_set_error_message(context, ret, N_("Unable to reach any changepw server " " in realm %s", "realm"), realm); *result_code = KRB5_KPASSWD_HARDERROR; } return ret; } #ifndef HEIMDAL_SMALLER static struct kpwd_proc * find_chpw_proto(const char *name) { struct kpwd_proc *p; for (p = procs; p->name != NULL; p++) { if (strcmp(p->name, name) == 0) return p; } return NULL; } /** * Deprecated: krb5_change_password() is deprecated, use krb5_set_password(). * * @param context a Keberos context * @param creds * @param newpw * @param result_code * @param result_code_string * @param result_string * * @return On sucess password is changed. * @ingroup @krb5_deprecated */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_change_password (krb5_context context, krb5_creds *creds, const char *newpw, int *result_code, krb5_data *result_code_string, krb5_data *result_string) KRB5_DEPRECATED_FUNCTION("Use X instead") { struct kpwd_proc *p = find_chpw_proto("change password"); *result_code = KRB5_KPASSWD_MALFORMED; result_code_string->data = result_string->data = NULL; result_code_string->length = result_string->length = 0; if (p == NULL) return KRB5_KPASSWD_MALFORMED; return change_password_loop(context, creds, NULL, newpw, result_code, result_code_string, result_string, p); } #endif /* HEIMDAL_SMALLER */ /** * Change password using creds. * * @param context a Keberos context * @param creds The initial kadmin/passwd for the principal or an admin principal * @param newpw The new password to set * @param targprinc if unset, the default principal is used. * @param result_code Result code, KRB5_KPASSWD_SUCCESS is when password is changed. * @param result_code_string binary message from the server, contains * at least the result_code. * @param result_string A message from the kpasswd service or the * library in human printable form. The string is NUL terminated. * * @return On sucess and *result_code is KRB5_KPASSWD_SUCCESS, the password is changed. * @ingroup @krb5 */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_set_password(krb5_context context, krb5_creds *creds, const char *newpw, krb5_principal targprinc, int *result_code, krb5_data *result_code_string, krb5_data *result_string) { krb5_principal principal = NULL; krb5_error_code ret = 0; int i; *result_code = KRB5_KPASSWD_MALFORMED; krb5_data_zero(result_code_string); krb5_data_zero(result_string); if (targprinc == NULL) { ret = krb5_get_default_principal(context, &principal); if (ret) return ret; } else principal = targprinc; for (i = 0; procs[i].name != NULL; i++) { *result_code = 0; ret = change_password_loop(context, creds, principal, newpw, result_code, result_code_string, result_string, &procs[i]); if (ret == 0 && *result_code == 0) break; } if (targprinc == NULL) krb5_free_principal(context, principal); return ret; } /* * */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_set_password_using_ccache(krb5_context context, krb5_ccache ccache, const char *newpw, krb5_principal targprinc, int *result_code, krb5_data *result_code_string, krb5_data *result_string) { krb5_creds creds, *credsp; krb5_error_code ret; krb5_principal principal = NULL; *result_code = KRB5_KPASSWD_MALFORMED; result_code_string->data = result_string->data = NULL; result_code_string->length = result_string->length = 0; memset(&creds, 0, sizeof(creds)); if (targprinc == NULL) { ret = krb5_cc_get_principal(context, ccache, &principal); if (ret) return ret; } else principal = targprinc; ret = krb5_make_principal(context, &creds.server, krb5_principal_get_realm(context, principal), "kadmin", "changepw", NULL); if (ret) goto out; ret = krb5_cc_get_principal(context, ccache, &creds.client); if (ret) { krb5_free_principal(context, creds.server); goto out; } ret = krb5_get_credentials(context, 0, ccache, &creds, &credsp); krb5_free_principal(context, creds.server); krb5_free_principal(context, creds.client); if (ret) goto out; ret = krb5_set_password(context, credsp, newpw, principal, result_code, result_code_string, result_string); krb5_free_creds(context, credsp); return ret; out: if (targprinc == NULL) krb5_free_principal(context, principal); return ret; } /* * */ KRB5_LIB_FUNCTION const char* KRB5_LIB_CALL krb5_passwd_result_to_string (krb5_context context, int result) { static const char *strings[] = { "Success", "Malformed", "Hard error", "Auth error", "Soft error" , "Access denied", "Bad version", "Initial flag needed" }; if (result < 0 || result > KRB5_KPASSWD_INITIAL_FLAG_NEEDED) return "unknown result code"; else return strings[result]; } heimdal-7.5.0/lib/krb5/test_canon.c0000755000175000017500000001171213026237312015170 0ustar niknik/* * Copyright (c) 2011, Secure Endpoints Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * - Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. * */ #include "krb5_locl.h" #include #include #if 0 #include #include #include #include #include #include #endif int main(int argc, char **argv) { krb5_error_code retval; krb5_context context; krb5_principal princ = NULL; krb5_principal me = NULL; krb5_principal cmp_to_princ = NULL; krb5_ccache cc = NULL; krb5_creds *out_creds = NULL; krb5_keytab kt = NULL; krb5_keytab_entry ktent; krb5_creds in_creds; char *hostname = NULL; char *unparsed = NULL; char *unparsed_canon = NULL; char *during; char *cmp_to = NULL;; int do_kt = 0; int do_get_creds = 0; int opt; int ret = 1; memset(&ktent, 0, sizeof(ktent)); while ((opt = getopt(argc, argv, "hgkc:")) != -1) { switch (opt) { case 'g': do_get_creds++; break; case 'k': do_kt++; break; case 'c': cmp_to = optarg; break; case 'h': default: fprintf(stderr, "Usage: %s [-g] [-k] [-c compare-to-principal] " "[principal]\n", argv[0]); return 1; } } if (!do_get_creds && !do_kt && !cmp_to) do_get_creds++; if (optind < argc) hostname = argv[optind]; during = "init_context"; retval = krb5_init_context(&context); if (retval) goto err; during = "sn2p"; retval = krb5_sname_to_principal(context, hostname, "host", KRB5_NT_SRV_HST, &princ); if (retval) goto err; during = "unparse of sname2princ"; retval = krb5_unparse_name(context, princ, &unparsed); if (retval) goto err; printf("krb5_sname_to_principal() output: %s\n", unparsed); if (cmp_to) { krb5_boolean eq; during = "parsing principal name for comparison compare"; retval = krb5_parse_name(context, cmp_to, &cmp_to_princ); if (retval) goto err; eq = krb5_principal_compare(context, princ, cmp_to_princ); printf("%s %s %s\n", unparsed, eq ? "==" : "!=", cmp_to); } if (do_get_creds) { during = "ccdefault"; retval = krb5_cc_default(context, &cc); if (retval) goto err; during = "ccprinc"; retval = krb5_cc_get_principal(context, cc, &me); if (retval) goto err; memset(&in_creds, 0, sizeof(in_creds)); in_creds.client = me; in_creds.server = princ; during = "getcreds"; retval = krb5_get_credentials(context, 0, cc, &in_creds, &out_creds); if (retval) goto err; during = "unparsing principal name canonicalized by krb5_get_credentials()"; retval = krb5_unparse_name(context, in_creds.server, &unparsed_canon); if (retval) goto err; printf("Principal name as canonicalized by krb5_get_credentials() is %s\n", unparsed_canon); } if (do_kt) { during = "getting keytab"; retval = krb5_kt_default(context, &kt); if (retval) goto err; during = "getting keytab ktent"; retval = krb5_kt_get_entry(context, kt, princ, 0, 0, &ktent); if (retval) goto err; during = "unparsing principal name canonicalized by krb5_kt_get_entry()"; retval = krb5_unparse_name(context, ktent.principal, &unparsed_canon); if (retval) goto err; printf("Principal name as canonicalized by krb5_kt_get_entry() is %s\n", unparsed_canon); } ret = 0; err: krb5_free_principal(context, princ); krb5_free_principal(context, me); krb5_free_principal(context, cmp_to_princ); krb5_xfree(unparsed); krb5_xfree(unparsed_canon); if (do_get_creds) { krb5_free_creds(context, out_creds); (void) krb5_cc_close(context, cc); } krb5_kt_free_entry(context, &ktent); if (kt) krb5_kt_close(context, kt); krb5_free_context(context); if (ret) fprintf(stderr, "Failed while doing %s (%d)\n", during, retval); return (ret); } heimdal-7.5.0/lib/krb5/krb5_acl_match_file.30000644000175000017500000000677112136107750016621 0ustar niknik.\" Copyright (c) 2004, 2006 Kungliga Tekniska Högskolan .\" (Royal Institute of Technology, Stockholm, Sweden). .\" All rights reserved. .\" .\" Redistribution and use in source and binary forms, with or without .\" modification, are permitted provided that the following conditions .\" are met: .\" .\" 1. Redistributions of source code must retain the above copyright .\" notice, this list of conditions and the following disclaimer. .\" .\" 2. Redistributions in binary form must reproduce the above copyright .\" notice, this list of conditions and the following disclaimer in the .\" documentation and/or other materials provided with the distribution. .\" .\" 3. Neither the name of the Institute nor the names of its contributors .\" may be used to endorse or promote products derived from this software .\" without specific prior written permission. .\" .\" THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND .\" ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE .\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE .\" ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE .\" FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL .\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS .\" OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) .\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT .\" LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF .\" SUCH DAMAGE. .\" .\" $Id$ .\" .Dd May 12, 2006 .Dt KRB5_ACL_MATCH_FILE 3 .Os HEIMDAL .Sh NAME .Nm krb5_acl_match_file , .Nm krb5_acl_match_string .Nd ACL matching functions .Sh LIBRARY Kerberos 5 Library (libkrb5, -lkrb5) .Sh SYNOPSIS .Ft krb5_error_code .Fo krb5_acl_match_file .Fa "krb5_context context" .Fa "const char *file" .Fa "const char *format" .Fa "..." .Fc .Ft krb5_error_code .Fo krb5_acl_match_string .Fa "krb5_context context" .Fa "const char *string" .Fa "const char *format" .Fa "..." .Fc .Sh DESCRIPTION .Nm krb5_acl_match_file matches ACL format against each line in a file. Lines starting with # are treated like comments and ignored. .Pp .Nm krb5_acl_match_string matches ACL format against a string. .Pp The ACL format has three format specifiers: s, f, and r. Each specifier will retrieve one argument from the variable arguments for either matching or storing data. The input string is split up using " " and "\et" as a delimiter; multiple " " and "\et" in a row are considered to be the same. .Pp .Bl -tag -width "fXX" -offset indent .It s Matches a string using .Xr strcmp 3 (case sensitive). .It f Matches the string with .Xr fnmatch 3 . The .Fa flags argument (the last argument) passed to the fnmatch function is 0. .It r Returns a copy of the string in the char ** passed in; the copy must be freed with .Xr free 3 . There is no need to .Xr free 3 the string on error: the function will clean up and set the pointer to .Dv NULL . .El .Pp All unknown format specifiers cause an error. .Sh EXAMPLES .Bd -literal -offset indent char *s; ret = krb5_acl_match_string(context, "foo", "s", "foo"); if (ret) krb5_errx(context, 1, "acl didn't match"); ret = krb5_acl_match_string(context, "foo foo baz/kaka", "ss", "foo", &s, "foo/*"); if (ret) { /* no need to free(s) on error */ assert(s == NULL); krb5_errx(context, 1, "acl didn't match"); } free(s); .Ed .Sh SEE ALSO .Xr krb5 3 heimdal-7.5.0/lib/krb5/store-test.c0000644000175000017500000000720613026237312015144 0ustar niknik/* * Copyright (c) 2001 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of KTH nor the names of its contributors may be * used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY KTH AND ITS CONTRIBUTORS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL KTH OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "krb5_locl.h" static void print_data(unsigned char *data, size_t len) { int i; for(i = 0; i < len; i++) { if(i > 0 && (i % 16) == 0) printf("\n "); printf("%02x ", data[i]); } printf("\n"); } static int compare(const char *name, krb5_storage *sp, void *expected, size_t len) { int ret = 0; krb5_data data; if (krb5_storage_to_data(sp, &data)) errx(1, "krb5_storage_to_data failed"); krb5_storage_free(sp); if(data.length != len || memcmp(data.data, expected, len) != 0) { printf("%s mismatch\n", name); printf(" Expected: "); print_data(expected, len); printf(" Actual: "); print_data(data.data, data.length); ret++; } krb5_data_free(&data); return ret; } int main(int argc, char **argv) { int nerr = 0; krb5_storage *sp; krb5_context context; krb5_principal principal; krb5_init_context(&context); sp = krb5_storage_emem(); krb5_store_int32(sp, 0x01020304); nerr += compare("Integer", sp, "\x1\x2\x3\x4", 4); sp = krb5_storage_emem(); krb5_storage_set_byteorder(sp, KRB5_STORAGE_BYTEORDER_LE); krb5_store_int32(sp, 0x01020304); nerr += compare("Integer (LE)", sp, "\x4\x3\x2\x1", 4); sp = krb5_storage_emem(); krb5_storage_set_byteorder(sp, KRB5_STORAGE_BYTEORDER_BE); krb5_store_int32(sp, 0x01020304); nerr += compare("Integer (BE)", sp, "\x1\x2\x3\x4", 4); sp = krb5_storage_emem(); krb5_storage_set_byteorder(sp, KRB5_STORAGE_BYTEORDER_HOST); krb5_store_int32(sp, 0x01020304); { int test = 1; void *data; if(*(char*)&test) data = "\x4\x3\x2\x1"; else data = "\x1\x2\x3\x4"; nerr += compare("Integer (host)", sp, data, 4); } sp = krb5_storage_emem(); krb5_make_principal(context, &principal, "TEST", "foobar", NULL); krb5_store_principal(sp, principal); krb5_free_principal(context, principal); nerr += compare("Principal", sp, "\x0\x0\x0\x1" "\x0\x0\x0\x1" "\x0\x0\x0\x4TEST" "\x0\x0\x0\x6""foobar", 26); krb5_free_context(context); return nerr ? 1 : 0; } heimdal-7.5.0/lib/krb5/test_expand_toks.c0000644000175000017500000000604413026237312016410 0ustar niknik/* * Copyright (c) 2003 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of KTH nor the names of its contributors may be * used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY KTH AND ITS CONTRIBUTORS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL KTH OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "krb5_locl.h" #include #include static int version_flag = 0; static int help_flag = 0; static struct getargs args[] = { {"help", 0, arg_flag, &help_flag, NULL, NULL } }; static void usage (int ret) { arg_printusage (args, sizeof(args)/sizeof(*args), NULL, ""); exit (ret); } int main(int argc, char **argv) { krb5_context context; krb5_error_code ret; int optidx = 0; char *expanded; setprogname(argv[0]); if (getarg(args, sizeof(args) / sizeof(args[0]), argc, argv, &optidx)) usage(1); if (help_flag) usage (0); if (version_flag){ print_version(NULL); exit(0); } argc -= optidx; argv += optidx; ret = krb5_init_context(&context); if (ret) errx (1, "krb5_init_context failed: %d", ret); ret = _krb5_expand_path_tokensv(context, "/tmp/%{foo}/%{bar}%{baz}/x", 0, &expanded, "foo", "abc", "bar", "dce", "baz", "fgh", NULL); if (ret) krb5_err(context, ret, 1, "Token expansion failed"); #ifdef _WIN32 #define EXPANDED_SHOULD_BE "\\tmp\\abc\\dcefgh\\x" #else #define EXPANDED_SHOULD_BE "/tmp/abc/dcefgh/x" #endif if (strcmp(expanded, EXPANDED_SHOULD_BE)) krb5_errx(context, 1, "Token expansion incorrect"); krb5_free_context(context); return 0; } heimdal-7.5.0/lib/krb5/n-fold.c0000644000175000017500000001000113026237312014175 0ustar niknik/* * Copyright (c) 1999 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of KTH nor the names of its contributors may be * used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY KTH AND ITS CONTRIBUTORS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL KTH OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "krb5_locl.h" static void rr13(uint8_t *dst1, uint8_t *dst2, uint8_t *src, size_t len) { int bytes = (len + 7) / 8; int i; const int bits = 13 % len; for (i = 0; i < bytes; i++) { int bb; int b1, s1, b2, s2; /* calculate first bit position of this byte */ bb = 8 * i - bits; while(bb < 0) bb += len; /* byte offset and shift count */ b1 = bb / 8; s1 = bb % 8; if (bb + 8 > bytes * 8) /* watch for wraparound */ s2 = (len + 8 - s1) % 8; else s2 = 8 - s1; b2 = (b1 + 1) % bytes; dst1[i] = (src[b1] << s1) | (src[b2] >> s2); dst2[i] = dst1[i]; } return; } /* * Add `b' to `a', both being one's complement numbers. * This function assumes that inputs *a, *b are aligned * to 4 bytes. */ static void add1(uint8_t *a, uint8_t *b, size_t len) { int i; int carry = 0; uint32_t x; uint32_t left, right; for (i = len - 1; (i+1) % 4; i--) { x = a[i] + b[i] + carry; carry = x > 0xff; a[i] = x & 0xff; } for (i = len / 4 - 1; i >= 0; i--) { left = ntohl(((uint32_t *)a)[i]); right = ntohl(((uint32_t *)b)[i]); x = left + right + carry; carry = x < left || x < right; ((uint32_t *)a)[i] = x; } for (i = len - 1; (i+1) % 4; i--) { x = a[i] + carry; carry = x > 0xff; a[i] = x & 0xff; } for (i = len / 4 - 1; carry && i >= 0; i--) { left = ((uint32_t *)a)[i]; x = left + carry; carry = x < left; ((uint32_t *)a)[i] = x; } for (i = len / 4 - 1; i >=0; i--) ((uint32_t *)a)[i] = htonl(((uint32_t *)a)[i]); } KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL _krb5_n_fold(const void *str, size_t len, void *key, size_t size) { /* if len < size we need at most N * len bytes, ie < 2 * size; if len > size we need at most 2 * len */ size_t maxlen = 2 * max(size, len); size_t l = 0; uint8_t *tmp; uint8_t *tmpbuf; uint8_t *buf1; uint8_t *buf2; tmp = malloc(maxlen + 2 * len); if (tmp == NULL) return ENOMEM; buf1 = tmp + maxlen; buf2 = tmp + maxlen + len; memset(key, 0, size); memcpy(buf1, str, len); memcpy(tmp, buf1, len); do { l += len; while(l >= size) { add1(key, tmp, size); l -= size; if(l == 0) break; memmove(tmp, tmp + size, l); } rr13(tmp + l, buf2, buf1, len * 8); tmpbuf = buf1; buf1 = buf2; buf2 = tmpbuf; } while(l != 0); memset(tmp, 0, maxlen + 2 * len); free(tmp); return 0; } heimdal-7.5.0/lib/krb5/krb5_425_conv_principal.cat30000644000175000017500000001723013212450756017772 0ustar niknik KRB5_425_CONV_PRINCIP... BSD Library Functions Manual KRB5_425_CONV_PRINCIP... NNAAMMEE kkrrbb55__442255__ccoonnvv__pprriinncciippaall, kkrrbb55__442255__ccoonnvv__pprriinncciippaall__eexxtt, kkrrbb55__552244__ccoonnvv__pprriinncciippaall -- converts to and from version 4 principals LLIIBBRRAARRYY Kerberos 5 Library (libkrb5, -lkrb5) SSYYNNOOPPSSIISS ##iinncclluuddee <> _k_r_b_5___e_r_r_o_r___c_o_d_e kkrrbb55__442255__ccoonnvv__pprriinncciippaall(_k_r_b_5___c_o_n_t_e_x_t _c_o_n_t_e_x_t, _c_o_n_s_t _c_h_a_r _*_n_a_m_e, _c_o_n_s_t _c_h_a_r _*_i_n_s_t_a_n_c_e, _c_o_n_s_t _c_h_a_r _*_r_e_a_l_m, _k_r_b_5___p_r_i_n_c_i_p_a_l _*_p_r_i_n_c_i_p_a_l); _k_r_b_5___e_r_r_o_r___c_o_d_e kkrrbb55__442255__ccoonnvv__pprriinncciippaall__eexxtt(_k_r_b_5___c_o_n_t_e_x_t _c_o_n_t_e_x_t, _c_o_n_s_t _c_h_a_r _*_n_a_m_e, _c_o_n_s_t _c_h_a_r _*_i_n_s_t_a_n_c_e, _c_o_n_s_t _c_h_a_r _*_r_e_a_l_m, _k_r_b_5___b_o_o_l_e_a_n _(_*_f_u_n_c_)_(_k_r_b_5___c_o_n_t_e_x_t_, _k_r_b_5___p_r_i_n_c_i_p_a_l_), _k_r_b_5___b_o_o_l_e_a_n _r_e_s_o_l_v_e, _k_r_b_5___p_r_i_n_c_i_p_a_l _*_p_r_i_n_c_i_p_a_l); _k_r_b_5___e_r_r_o_r___c_o_d_e kkrrbb55__552244__ccoonnvv__pprriinncciippaall(_k_r_b_5___c_o_n_t_e_x_t _c_o_n_t_e_x_t, _c_o_n_s_t _k_r_b_5___p_r_i_n_c_i_p_a_l _p_r_i_n_c_i_p_a_l, _c_h_a_r _*_n_a_m_e, _c_h_a_r _*_i_n_s_t_a_n_c_e, _c_h_a_r _*_r_e_a_l_m); DDEESSCCRRIIPPTTIIOONN Converting between version 4 and version 5 principals can at best be described as a mess. A version 4 principal consists of a name, an instance, and a realm. A version 5 principal consists of one or more components, and a realm. In some cases also the first component/name will differ between version 4 and version 5. Furthermore the second component of a host principal will be the fully qualified domain name of the host in question, while the instance of a version 4 principal will only contain the first part (short hostname). Because of these problems the conversion between principals will have to be site customized. kkrrbb55__442255__ccoonnvv__pprriinncciippaall__eexxtt() will try to convert a version 4 principal, given by _n_a_m_e, _i_n_s_t_a_n_c_e, and _r_e_a_l_m, to a version 5 principal. This can result in several possible principals, and if _f_u_n_c is non-NULL, it will be called for each candidate principal. _f_u_n_c should return true if the principal was ``good''. To accomplish this, kkrrbb55__442255__ccoonnvv__pprriinncciippaall__eexxtt() will look up the name in _k_r_b_5_._c_o_n_f. It first looks in the v4_name_convert/host subsection, which should contain a list of version 4 names whose instance should be treated as a hostname. This list can be specified for each realm (in the realms section), or in the libdefaults section. If the name is found the resulting name of the principal will be the value of this binding. The instance is then first looked up in v4_instance_convert for the specified realm. If found the resulting value will be used as instance (this can be used for special cases), no further attempts will be made to find a conversion if this fails (with _f_u_n_c). If the _r_e_s_o_l_v_e parameter is true, the instance will be looked up with ggeetthhoossttbbyynnaammee(). This can be a time consuming, error prone, and unsafe operation. Next a list of hostnames will be created from the instance and the v4_domains variable, which should contain a list of possible domains for the specific realm. On the other hand, if the name is not found in a host section, it is looked up in a v4_name_convert/plain binding. If found here the name will be converted, but the instance will be untouched. This list of default host-type conversions is compiled-in: v4_name_convert = { host = { ftp = ftp hprop = hprop imap = imap pop = pop rcmd = host smtp = smtp } } It will only be used if there isn't an entry for these names in the con- fig file, so you can override these defaults. kkrrbb55__442255__ccoonnvv__pprriinncciippaall() will call kkrrbb55__442255__ccoonnvv__pprriinncciippaall__eexxtt() with NULL as _f_u_n_c, and the value of v4_instance_resolve (from the libdefaults section) as _r_e_s_o_l_v_e. kkrrbb55__552244__ccoonnvv__pprriinncciippaall() basically does the opposite of kkrrbb55__442255__ccoonnvv__pprriinncciippaall(), it just doesn't have to look up any names, but will instead truncate instances found to belong to a host principal. The _n_a_m_e, _i_n_s_t_a_n_c_e, and _r_e_a_l_m should be at least 40 characters long. EEXXAAMMPPLLEESS Since this is confusing an example is in place. Assume that we have the ``foo.com'', and ``bar.com'' domains that have shared a single version 4 realm, FOO.COM. The version 4 _k_r_b_._r_e_a_l_m_s file looked like: foo.com FOO.COM .foo.com FOO.COM .bar.com FOO.COM A _k_r_b_5_._c_o_n_f file that covers this case might look like: [libdefaults] v4_instance_resolve = yes [realms] FOO.COM = { kdc = kerberos.foo.com v4_instance_convert = { foo = foo.com } v4_domains = foo.com } With this setup and the following host table: foo.com a-host.foo.com b-host.bar.com the following conversions will be made: rcmd.a-host -> host/a-host.foo.com ftp.b-host -> ftp/b-host.bar.com pop.foo -> pop/foo.com ftp.other -> ftp/other.foo.com other.a-host -> other/a-host The first three are what you expect. If you remove the ``v4_domains'', the fourth entry will result in an error (since the host ``other'' can't be found). Even if ``a-host'' is a valid host name, the last entry will not be converted, since the ``other'' name is not known to represent a host-type principal. If you turn off ``v4_instance_resolve'' the second example will result in ``ftp/b-host.foo.com'' (because of the default domain). And all of this is of course only valid if you have working name resolving. SSEEEE AALLSSOO krb5_build_principal(3), krb5_free_principal(3), krb5_parse_name(3), krb5_sname_to_principal(3), krb5_unparse_name(3), krb5.conf(5) HEIMDAL September 3, 2003 HEIMDAL heimdal-7.5.0/lib/krb5/krb5-v4compat.h0000644000175000017500000001070512136107750015437 0ustar niknik/* * Copyright (c) 1997 - 2003 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ /* $Id$ */ #ifndef __KRB5_V4COMPAT_H__ #define __KRB5_V4COMPAT_H__ #include "krb_err.h" /* * This file must only be included with v4 compat glue stuff in * heimdal sources. * * It MUST NOT be installed. */ #define KRB_PROT_VERSION 4 #define AUTH_MSG_KDC_REQUEST (1<<1) #define AUTH_MSG_KDC_REPLY (2<<1) #define AUTH_MSG_APPL_REQUEST (3<<1) #define AUTH_MSG_APPL_REQUEST_MUTUAL (4<<1) #define AUTH_MSG_ERR_REPLY (5<<1) #define AUTH_MSG_PRIVATE (6<<1) #define AUTH_MSG_SAFE (7<<1) #define AUTH_MSG_APPL_ERR (8<<1) #define AUTH_MSG_KDC_FORWARD (9<<1) #define AUTH_MSG_KDC_RENEW (10<<1) #define AUTH_MSG_DIE (63<<1) /* General definitions */ #define KSUCCESS 0 #define KFAILURE 255 /* */ #define MAX_KTXT_LEN 1250 #define ANAME_SZ 40 #define REALM_SZ 40 #define SNAME_SZ 40 #define INST_SZ 40 struct ktext { unsigned int length; /* Length of the text */ unsigned char dat[MAX_KTXT_LEN]; /* The data itself */ uint32_t mbz; /* zero to catch runaway strings */ }; struct credentials { char service[ANAME_SZ]; /* Service name */ char instance[INST_SZ]; /* Instance */ char realm[REALM_SZ]; /* Auth domain */ char session[8]; /* Session key */ int lifetime; /* Lifetime */ int kvno; /* Key version number */ struct ktext ticket_st; /* The ticket itself */ int32_t issue_date; /* The issue time */ char pname[ANAME_SZ]; /* Principal's name */ char pinst[INST_SZ]; /* Principal's instance */ }; #define TKTLIFENUMFIXED 64 #define TKTLIFEMINFIXED 0x80 #define TKTLIFEMAXFIXED 0xBF #define TKTLIFENOEXPIRE 0xFF #define MAXTKTLIFETIME (30*24*3600) /* 30 days */ #ifndef NEVERDATE #define NEVERDATE ((time_t)0x7fffffffL) #endif #define KERB_ERR_NULL_KEY 10 #define CLOCK_SKEW 5*60 #ifndef TKT_ROOT #ifdef KRB5_USE_PATH_TOKENS #define TKT_ROOT "%{TEMP}/tkt" #else #define TKT_ROOT "/tmp/tkt" #endif #endif struct _krb5_krb_auth_data { int8_t k_flags; /* Flags from ticket */ char *pname; /* Principal's name */ char *pinst; /* His Instance */ char *prealm; /* His Realm */ uint32_t checksum; /* Data checksum (opt) */ krb5_keyblock session; /* Session Key */ unsigned char life; /* Life of ticket */ uint32_t time_sec; /* Time ticket issued */ uint32_t address; /* Address in ticket */ }; KRB5_LIB_FUNCTION time_t KRB5_LIB_CALL _krb5_krb_life_to_time (int, int); KRB5_LIB_FUNCTION int KRB5_LIB_CALL _krb5_krb_time_to_life (time_t, time_t); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL _krb5_krb_tf_setup (krb5_context, struct credentials *, const char *, int); KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL _krb5_krb_dest_tkt(krb5_context, const char *); #define krb_time_to_life _krb5_krb_time_to_life #define krb_life_to_time _krb5_krb_life_to_time #endif /* __KRB5_V4COMPAT_H__ */ heimdal-7.5.0/lib/krb5/krb5_ccapi.h0000644000175000017500000001702312664131275015050 0ustar niknik/* * Copyright (c) 2004 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ /* $Id$ */ #ifndef KRB5_CCAPI_H #define KRB5_CCAPI_H 1 #include #ifdef __APPLE__ #pragma pack(push,2) #endif enum { cc_credentials_v5 = 2 }; enum { ccapi_version_3 = 3, ccapi_version_4 = 4 }; enum { ccNoError = 0, ccIteratorEnd = 201, ccErrBadParam, ccErrNoMem, ccErrInvalidContext, ccErrInvalidCCache, ccErrInvalidString, /* 206 */ ccErrInvalidCredentials, ccErrInvalidCCacheIterator, ccErrInvalidCredentialsIterator, ccErrInvalidLock, ccErrBadName, /* 211 */ ccErrBadCredentialsVersion, ccErrBadAPIVersion, ccErrContextLocked, ccErrContextUnlocked, ccErrCCacheLocked, /* 216 */ ccErrCCacheUnlocked, ccErrBadLockType, ccErrNeverDefault, ccErrCredentialsNotFound, ccErrCCacheNotFound, /* 221 */ ccErrContextNotFound, ccErrServerUnavailable, ccErrServerInsecure, ccErrServerCantBecomeUID, ccErrTimeOffsetNotSet /* 226 */ }; typedef int32_t cc_int32; typedef uint32_t cc_uint32; typedef struct cc_context_t *cc_context_t; typedef struct cc_ccache_t *cc_ccache_t; typedef struct cc_ccache_iterator_t *cc_ccache_iterator_t; typedef struct cc_credentials_v5_t cc_credentials_v5_t; typedef struct cc_credentials_t *cc_credentials_t; typedef struct cc_credentials_iterator_t *cc_credentials_iterator_t; typedef struct cc_string_t *cc_string_t; typedef cc_uint32 cc_time_t; typedef struct cc_data { cc_uint32 type; cc_uint32 length; void *data; } cc_data; struct cc_credentials_v5_t { char *client; char *server; cc_data keyblock; cc_time_t authtime; cc_time_t starttime; cc_time_t endtime; cc_time_t renew_till; cc_uint32 is_skey; cc_uint32 ticket_flags; #define KRB5_CCAPI_TKT_FLG_FORWARDABLE 0x40000000 #define KRB5_CCAPI_TKT_FLG_FORWARDED 0x20000000 #define KRB5_CCAPI_TKT_FLG_PROXIABLE 0x10000000 #define KRB5_CCAPI_TKT_FLG_PROXY 0x08000000 #define KRB5_CCAPI_TKT_FLG_MAY_POSTDATE 0x04000000 #define KRB5_CCAPI_TKT_FLG_POSTDATED 0x02000000 #define KRB5_CCAPI_TKT_FLG_INVALID 0x01000000 #define KRB5_CCAPI_TKT_FLG_RENEWABLE 0x00800000 #define KRB5_CCAPI_TKT_FLG_INITIAL 0x00400000 #define KRB5_CCAPI_TKT_FLG_PRE_AUTH 0x00200000 #define KRB5_CCAPI_TKT_FLG_HW_AUTH 0x00100000 #define KRB5_CCAPI_TKT_FLG_TRANSIT_POLICY_CHECKED 0x00080000 #define KRB5_CCAPI_TKT_FLG_OK_AS_DELEGATE 0x00040000 #define KRB5_CCAPI_TKT_FLG_ANONYMOUS 0x00020000 cc_data **addresses; cc_data ticket; cc_data second_ticket; cc_data **authdata; }; typedef struct cc_string_functions { cc_int32 (*release)(cc_string_t); } cc_string_functions; struct cc_string_t { const char *data; const cc_string_functions *func; }; typedef struct cc_credentials_union { cc_int32 version; union { cc_credentials_v5_t* credentials_v5; } credentials; } cc_credentials_union; struct cc_credentials_functions { cc_int32 (*release)(cc_credentials_t); cc_int32 (*compare)(cc_credentials_t, cc_credentials_t, cc_uint32*); }; struct cc_credentials_t { const cc_credentials_union* data; const struct cc_credentials_functions* func; }; struct cc_credentials_iterator_functions { cc_int32 (*release)(cc_credentials_iterator_t); cc_int32 (*next)(cc_credentials_iterator_t, cc_credentials_t*); }; struct cc_credentials_iterator_t { const struct cc_credentials_iterator_functions *func; }; struct cc_ccache_iterator_functions { cc_int32 (*release) (cc_ccache_iterator_t); cc_int32 (*next)(cc_ccache_iterator_t, cc_ccache_t*); }; struct cc_ccache_iterator_t { const struct cc_ccache_iterator_functions* func; }; typedef struct cc_ccache_functions { cc_int32 (*release)(cc_ccache_t); cc_int32 (*destroy)(cc_ccache_t); cc_int32 (*set_default)(cc_ccache_t); cc_int32 (*get_credentials_version)(cc_ccache_t, cc_uint32*); cc_int32 (*get_name)(cc_ccache_t, cc_string_t*); cc_int32 (*get_principal)(cc_ccache_t, cc_uint32, cc_string_t*); cc_int32 (*set_principal)(cc_ccache_t, cc_uint32, const char*); cc_int32 (*store_credentials)(cc_ccache_t, const cc_credentials_union*); cc_int32 (*remove_credentials)(cc_ccache_t, cc_credentials_t); cc_int32 (*new_credentials_iterator)(cc_ccache_t, cc_credentials_iterator_t*); cc_int32 (*move)(cc_ccache_t, cc_ccache_t); cc_int32 (*lock)(cc_ccache_t, cc_uint32, cc_uint32); cc_int32 (*unlock)(cc_ccache_t); cc_int32 (*get_last_default_time)(cc_ccache_t, cc_time_t*); cc_int32 (*get_change_time)(cc_ccache_t, cc_time_t*); cc_int32 (*compare)(cc_ccache_t, cc_ccache_t, cc_uint32*); cc_int32 (*get_kdc_time_offset)(cc_ccache_t, cc_int32, cc_time_t *); cc_int32 (*set_kdc_time_offset)(cc_ccache_t, cc_int32, cc_time_t); cc_int32 (*clear_kdc_time_offset)(cc_ccache_t, cc_int32); } cc_ccache_functions; struct cc_ccache_t { const cc_ccache_functions *func; }; struct cc_context_functions { cc_int32 (*release)(cc_context_t); cc_int32 (*get_change_time)(cc_context_t, cc_time_t *); cc_int32 (*get_default_ccache_name)(cc_context_t, cc_string_t*); cc_int32 (*open_ccache)(cc_context_t, const char*, cc_ccache_t *); cc_int32 (*open_default_ccache)(cc_context_t, cc_ccache_t*); cc_int32 (*create_ccache)(cc_context_t,const char*, cc_uint32, const char*, cc_ccache_t*); cc_int32 (*create_default_ccache)(cc_context_t, cc_uint32, const char*, cc_ccache_t*); cc_int32 (*create_new_ccache)(cc_context_t, cc_uint32, const char*, cc_ccache_t*); cc_int32 (*new_ccache_iterator)(cc_context_t, cc_ccache_iterator_t*); cc_int32 (*lock)(cc_context_t, cc_uint32, cc_uint32); cc_int32 (*unlock)(cc_context_t); cc_int32 (*compare)(cc_context_t, cc_context_t, cc_uint32*); }; struct cc_context_t { const struct cc_context_functions* func; }; typedef cc_int32 (*cc_initialize_func)(cc_context_t*, cc_int32, cc_int32 *, char const **); #ifdef __APPLE__ #pragma pack(pop) #endif #endif /* KRB5_CCAPI_H */ heimdal-7.5.0/lib/krb5/krb5_eai_to_heim_errno.30000644000175000017500000000462512136107750017352 0ustar niknik.\" Copyright (c) 2004 Kungliga Tekniska Högskolan .\" (Royal Institute of Technology, Stockholm, Sweden). .\" All rights reserved. .\" .\" Redistribution and use in source and binary forms, with or without .\" modification, are permitted provided that the following conditions .\" are met: .\" .\" 1. Redistributions of source code must retain the above copyright .\" notice, this list of conditions and the following disclaimer. .\" .\" 2. Redistributions in binary form must reproduce the above copyright .\" notice, this list of conditions and the following disclaimer in the .\" documentation and/or other materials provided with the distribution. .\" .\" 3. Neither the name of the Institute nor the names of its contributors .\" may be used to endorse or promote products derived from this software .\" without specific prior written permission. .\" .\" THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND .\" ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE .\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE .\" ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE .\" FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL .\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS .\" OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) .\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT .\" LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF .\" SUCH DAMAGE. .\" .\" $Id$ .\" .Dd April 13, 2004 .Dt KRB5_EAI_TO_HEIM_ERRNO 3 .Os HEIMDAL .Sh NAME .Nm krb5_eai_to_heim_errno , .Nm krb5_h_errno_to_heim_errno .Nd convert resolver error code to com_err error codes .Sh LIBRARY Kerberos 5 Library (libkrb5, -lkrb5) .Sh SYNOPSIS .In krb5.h .Ft krb5_error_code .Fo krb5_eai_to_heim_errno .Fa "int eai_errno" .Fa "int system_error" .Fc .Ft krb5_error_code .Fo krb5_h_errno_to_heim_errno .Fa "int eai_errno" .Fc .Sh DESCRIPTION .Fn krb5_eai_to_heim_errno and .Fn krb5_h_errno_to_heim_errno convert .Xr getaddrinfo 3 , .Xr getnameinfo 3 , and .Xr h_errno 3 to com_err error code that are used by Heimdal, this is useful for for function returning kerberos errors and needs to communicate failures from resolver function. .Sh SEE ALSO .Xr krb5 3 , .Xr kerberos 8 heimdal-7.5.0/lib/krb5/test_plugin.c0000644000175000017500000000704613026237312015372 0ustar niknik/* * Copyright (c) 2006 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include #include "locate_plugin.h" static krb5_error_code resolve_init(krb5_context context, void **ctx) { *ctx = NULL; return 0; } static void resolve_fini(void *ctx) { } static krb5_error_code resolve_lookup(void *ctx, enum locate_service_type service, const char *realm, int domain, int type, int (*add)(void *,int,struct sockaddr *), void *addctx) { struct sockaddr_in s; memset(&s, 0, sizeof(s)); #ifdef HAVE_STRUCT_SOCKADDR_SA_LEN s.sin_len = sizeof(s); #endif s.sin_family = AF_INET; s.sin_port = htons(88); s.sin_addr.s_addr = htonl(0x7f000002); if (strcmp(realm, "NOTHERE.H5L.SE") == 0) (*add)(addctx, type, (struct sockaddr *)&s); return 0; } krb5plugin_service_locate_ftable resolve = { 0, resolve_init, resolve_fini, resolve_lookup, NULL }; int main(int argc, char **argv) { krb5_error_code ret; krb5_context context; krb5_krbhst_handle handle; char host[MAXHOSTNAMELEN]; int found = 0; setprogname(argv[0]); ret = krb5_init_context(&context); if (ret) errx(1, "krb5_init_contex"); ret = krb5_plugin_register(context, PLUGIN_TYPE_DATA, KRB5_PLUGIN_LOCATE, &resolve); if (ret) krb5_err(context, 1, ret, "krb5_plugin_register"); ret = krb5_krbhst_init_flags(context, "NOTHERE.H5L.SE", KRB5_KRBHST_KDC, 0, &handle); if (ret) krb5_err(context, 1, ret, "krb5_krbhst_init_flags"); while(krb5_krbhst_next_as_string(context, handle, host, sizeof(host)) == 0){ found++; if (!found && strcmp(host, "127.0.0.2") != 0 && strcmp(host, "tcp/127.0.0.2") != 0) krb5_errx(context, 1, "wrong address: %s", host); } if (!found) krb5_errx(context, 1, "failed to find host"); if (found < 2) krb5_errx(context, 1, "did not get the two expected results"); krb5_krbhst_free(context, handle); krb5_free_context(context); return 0; } heimdal-7.5.0/lib/krb5/derived-key-test.c0000644000175000017500000002132313026237312016214 0ustar niknik/* * Copyright (c) 2001 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of KTH nor the names of its contributors may be * used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY KTH AND ITS CONTRIBUTORS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL KTH OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "krb5_locl.h" #include enum { MAXSIZE = 32 }; static struct testcase { krb5_enctype enctype; unsigned char constant[MAXSIZE]; size_t constant_len; unsigned char key[MAXSIZE]; unsigned char res[MAXSIZE]; } tests[] = { {ETYPE_DES3_CBC_SHA1, {0x00, 0x00, 0x00, 0x01, 0x55}, 5, {0xdc, 0xe0, 0x6b, 0x1f, 0x64, 0xc8, 0x57, 0xa1, 0x1c, 0x3d, 0xb5, 0x7c, 0x51, 0x89, 0x9b, 0x2c, 0xc1, 0x79, 0x10, 0x08, 0xce, 0x97, 0x3b, 0x92}, {0x92, 0x51, 0x79, 0xd0, 0x45, 0x91, 0xa7, 0x9b, 0x5d, 0x31, 0x92, 0xc4, 0xa7, 0xe9, 0xc2, 0x89, 0xb0, 0x49, 0xc7, 0x1f, 0x6e, 0xe6, 0x04, 0xcd}}, {ETYPE_DES3_CBC_SHA1, {0x00, 0x00, 0x00, 0x01, 0xaa}, 5, {0x5e, 0x13, 0xd3, 0x1c, 0x70, 0xef, 0x76, 0x57, 0x46, 0x57, 0x85, 0x31, 0xcb, 0x51, 0xc1, 0x5b, 0xf1, 0x1c, 0xa8, 0x2c, 0x97, 0xce, 0xe9, 0xf2}, {0x9e, 0x58, 0xe5, 0xa1, 0x46, 0xd9, 0x94, 0x2a, 0x10, 0x1c, 0x46, 0x98, 0x45, 0xd6, 0x7a, 0x20, 0xe3, 0xc4, 0x25, 0x9e, 0xd9, 0x13, 0xf2, 0x07}}, {ETYPE_DES3_CBC_SHA1, {0x00, 0x00, 0x00, 0x01, 0x55}, 5, {0x98, 0xe6, 0xfd, 0x8a, 0x04, 0xa4, 0xb6, 0x85, 0x9b, 0x75, 0xa1, 0x76, 0x54, 0x0b, 0x97, 0x52, 0xba, 0xd3, 0xec, 0xd6, 0x10, 0xa2, 0x52, 0xbc}, {0x13, 0xfe, 0xf8, 0x0d, 0x76, 0x3e, 0x94, 0xec, 0x6d, 0x13, 0xfd, 0x2c, 0xa1, 0xd0, 0x85, 0x07, 0x02, 0x49, 0xda, 0xd3, 0x98, 0x08, 0xea, 0xbf}}, {ETYPE_DES3_CBC_SHA1, {0x00, 0x00, 0x00, 0x01, 0xaa}, 5, {0x62, 0x2a, 0xec, 0x25, 0xa2, 0xfe, 0x2c, 0xad, 0x70, 0x94, 0x68, 0x0b, 0x7c, 0x64, 0x94, 0x02, 0x80, 0x08, 0x4c, 0x1a, 0x7c, 0xec, 0x92, 0xb5}, {0xf8, 0xdf, 0xbf, 0x04, 0xb0, 0x97, 0xe6, 0xd9, 0xdc, 0x07, 0x02, 0x68, 0x6b, 0xcb, 0x34, 0x89, 0xd9, 0x1f, 0xd9, 0xa4, 0x51, 0x6b, 0x70, 0x3e}}, {ETYPE_DES3_CBC_SHA1, {0x6b, 0x65, 0x72, 0x62, 0x65, 0x72, 0x6f, 0x73}, 8, {0xd3, 0xf8, 0x29, 0x8c, 0xcb, 0x16, 0x64, 0x38, 0xdc, 0xb9, 0xb9, 0x3e, 0xe5, 0xa7, 0x62, 0x92, 0x86, 0xa4, 0x91, 0xf8, 0x38, 0xf8, 0x02, 0xfb}, {0x23, 0x70, 0xda, 0x57, 0x5d, 0x2a, 0x3d, 0xa8, 0x64, 0xce, 0xbf, 0xdc, 0x52, 0x04, 0xd5, 0x6d, 0xf7, 0x79, 0xa7, 0xdf, 0x43, 0xd9, 0xda, 0x43}}, {ETYPE_DES3_CBC_SHA1, {0x63, 0x6f, 0x6d, 0x62, 0x69, 0x6e, 0x65}, 7, {0xb5, 0x5e, 0x98, 0x34, 0x67, 0xe5, 0x51, 0xb3, 0xe5, 0xd0, 0xe5, 0xb6, 0xc8, 0x0d, 0x45, 0x76, 0x94, 0x23, 0xa8, 0x73, 0xdc, 0x62, 0xb3, 0x0e}, {0x01, 0x26, 0x38, 0x8a, 0xad, 0xc8, 0x1a, 0x1f, 0x2a, 0x62, 0xbc, 0x45, 0xf8, 0xd5, 0xc1, 0x91, 0x51, 0xba, 0xcd, 0xd5, 0xcb, 0x79, 0x8a, 0x3e}}, {ETYPE_DES3_CBC_SHA1, {0x00, 0x00, 0x00, 0x01, 0x55}, 5, {0xc1, 0x08, 0x16, 0x49, 0xad, 0xa7, 0x43, 0x62, 0xe6, 0xa1, 0x45, 0x9d, 0x01, 0xdf, 0xd3, 0x0d, 0x67, 0xc2, 0x23, 0x4c, 0x94, 0x07, 0x04, 0xda}, {0x34, 0x80, 0x57, 0xec, 0x98, 0xfd, 0xc4, 0x80, 0x16, 0x16, 0x1c, 0x2a, 0x4c, 0x7a, 0x94, 0x3e, 0x92, 0xae, 0x49, 0x2c, 0x98, 0x91, 0x75, 0xf7}}, {ETYPE_DES3_CBC_SHA1, {0x00, 0x00, 0x00, 0x01, 0xaa}, 5, {0x5d, 0x15, 0x4a, 0xf2, 0x38, 0xf4, 0x67, 0x13, 0x15, 0x57, 0x19, 0xd5, 0x5e, 0x2f, 0x1f, 0x79, 0x0d, 0xd6, 0x61, 0xf2, 0x79, 0xa7, 0x91, 0x7c}, {0xa8, 0x80, 0x8a, 0xc2, 0x67, 0xda, 0xda, 0x3d, 0xcb, 0xe9, 0xa7, 0xc8, 0x46, 0x26, 0xfb, 0xc7, 0x61, 0xc2, 0x94, 0xb0, 0x13, 0x15, 0xe5, 0xc1}}, {ETYPE_DES3_CBC_SHA1, {0x00, 0x00, 0x00, 0x01, 0x55}, 5, {0x79, 0x85, 0x62, 0xe0, 0x49, 0x85, 0x2f, 0x57, 0xdc, 0x8c, 0x34, 0x3b, 0xa1, 0x7f, 0x2c, 0xa1, 0xd9, 0x73, 0x94, 0xef, 0xc8, 0xad, 0xc4, 0x43}, {0xc8, 0x13, 0xf8, 0x8a, 0x3b, 0xe3, 0xb3, 0x34, 0xf7, 0x54, 0x25, 0xce, 0x91, 0x75, 0xfb, 0xe3, 0xc8, 0x49, 0x3b, 0x89, 0xc8, 0x70, 0x3b, 0x49}}, {ETYPE_DES3_CBC_SHA1, {0x00, 0x00, 0x00, 0x01, 0xaa}, 5, {0x26, 0xdc, 0xe3, 0x34, 0xb5, 0x45, 0x29, 0x2f, 0x2f, 0xea, 0xb9, 0xa8, 0x70, 0x1a, 0x89, 0xa4, 0xb9, 0x9e, 0xb9, 0x94, 0x2c, 0xec, 0xd0, 0x16}, {0xf4, 0x8f, 0xfd, 0x6e, 0x83, 0xf8, 0x3e, 0x73, 0x54, 0xe6, 0x94, 0xfd, 0x25, 0x2c, 0xf8, 0x3b, 0xfe, 0x58, 0xf7, 0xd5, 0xba, 0x37, 0xec, 0x5d}}, {ETYPE_AES128_CTS_HMAC_SHA256_128, {0x00, 0x00, 0x00, 0x02, 0x99}, 5, {0x37, 0x05, 0xD9, 0x60, 0x80, 0xC1, 0x77, 0x28, 0xA0, 0xE8, 0x00, 0xEA, 0xB6, 0xE0, 0xD2, 0x3C}, {0xB3, 0x1A, 0x01, 0x8A, 0x48, 0xF5, 0x47, 0x76, 0xF4, 0x03, 0xE9, 0xA3, 0x96, 0x32, 0x5D, 0xC3}}, {ETYPE_AES128_CTS_HMAC_SHA256_128, {0x00, 0x00, 0x00, 0x02, 0xAA}, 5, {0x37, 0x05, 0xD9, 0x60, 0x80, 0xC1, 0x77, 0x28, 0xA0, 0xE8, 0x00, 0xEA, 0xB6, 0xE0, 0xD2, 0x3C}, {0x9B, 0x19, 0x7D, 0xD1, 0xE8, 0xC5, 0x60, 0x9D, 0x6E, 0x67, 0xC3, 0xE3, 0x7C, 0x62, 0xC7, 0x2E}}, {ETYPE_AES128_CTS_HMAC_SHA256_128, {0x00, 0x00, 0x00, 0x02, 0x55}, 5, {0x37, 0x05, 0xD9, 0x60, 0x80, 0xC1, 0x77, 0x28, 0xA0, 0xE8, 0x00, 0xEA, 0xB6, 0xE0, 0xD2, 0x3C}, {0x9F, 0xDA, 0x0E, 0x56, 0xAB, 0x2D, 0x85, 0xE1, 0x56, 0x9A, 0x68, 0x86, 0x96, 0xC2, 0x6A, 0x6C}}, {ETYPE_AES256_CTS_HMAC_SHA384_192, {0x00, 0x00, 0x00, 0x02, 0x99}, 5, {0x6D, 0x40, 0x4D, 0x37, 0xFA, 0xF7, 0x9F, 0x9D, 0xF0, 0xD3, 0x35, 0x68, 0xD3, 0x20, 0x66, 0x98, 0x00, 0xEB, 0x48, 0x36, 0x47, 0x2E, 0xA8, 0xA0, 0x26, 0xD1, 0x6B, 0x71, 0x82, 0x46, 0x0C, 0x52}, {0xEF, 0x57, 0x18, 0xBE, 0x86, 0xCC, 0x84, 0x96, 0x3D, 0x8B, 0xBB, 0x50, 0x31, 0xE9, 0xF5, 0xC4, 0xBA, 0x41, 0xF2, 0x8F, 0xAF, 0x69, 0xE7, 0x3D }}, {ETYPE_AES256_CTS_HMAC_SHA384_192, {0x00, 0x00, 0x00, 0x02, 0xAA}, 5, {0x6D, 0x40, 0x4D, 0x37, 0xFA, 0xF7, 0x9F, 0x9D, 0xF0, 0xD3, 0x35, 0x68, 0xD3, 0x20, 0x66, 0x98, 0x00, 0xEB, 0x48, 0x36, 0x47, 0x2E, 0xA8, 0xA0, 0x26, 0xD1, 0x6B, 0x71, 0x82, 0x46, 0x0C, 0x52}, {0x56, 0xAB, 0x22, 0xBE, 0xE6, 0x3D, 0x82, 0xD7, 0xBC, 0x52, 0x27, 0xF6, 0x77, 0x3F, 0x8E, 0xA7, 0xA5, 0xEB, 0x1C, 0x82, 0x51, 0x60, 0xC3, 0x83, 0x12, 0x98, 0x0C, 0x44, 0x2E, 0x5C, 0x7E, 0x49}}, {ETYPE_AES256_CTS_HMAC_SHA384_192, {0x00, 0x00, 0x00, 0x02, 0x55}, 5, {0x6D, 0x40, 0x4D, 0x37, 0xFA, 0xF7, 0x9F, 0x9D, 0xF0, 0xD3, 0x35, 0x68, 0xD3, 0x20, 0x66, 0x98, 0x00, 0xEB, 0x48, 0x36, 0x47, 0x2E, 0xA8, 0xA0, 0x26, 0xD1, 0x6B, 0x71, 0x82, 0x46, 0x0C, 0x52}, {0x69, 0xB1, 0x65, 0x14, 0xE3, 0xCD, 0x8E, 0x56, 0xB8, 0x20, 0x10, 0xD5, 0xC7, 0x30, 0x12, 0xB6, 0x22, 0xC4, 0xD0, 0x0F, 0xFC, 0x23, 0xED, 0x1F}}, {0, {0}, 0, {0}, {0}} }; int main(int argc, char **argv) { struct testcase *t; krb5_context context; krb5_error_code ret; int val = 0; ret = krb5_init_context (&context); if (ret) errx (1, "krb5_init_context failed: %d", ret); for (t = tests; t->enctype != 0; ++t) { krb5_keyblock key; krb5_keyblock *dkey; key.keytype = t->enctype; krb5_enctype_keysize(context, t->enctype, &key.keyvalue.length); key.keyvalue.data = t->key; ret = krb5_derive_key(context, &key, t->enctype, t->constant, t->constant_len, &dkey); if (ret) krb5_err (context, 1, ret, "krb5_derive_key"); if (memcmp (dkey->keyvalue.data, t->res, dkey->keyvalue.length) != 0) { const unsigned char *p = dkey->keyvalue.data; int i; printf ("derive_key failed (enctype %d)\n", t->enctype); printf ("should be: "); for (i = 0; i < dkey->keyvalue.length; ++i) printf ("%02x", t->res[i]); printf ("\nresult was: "); for (i = 0; i < dkey->keyvalue.length; ++i) printf ("%02x", p[i]); printf ("\n"); val = 1; } krb5_free_keyblock(context, dkey); } krb5_free_context(context); return val; } heimdal-7.5.0/lib/krb5/crypto-evp.c0000644000175000017500000001253313026237312015142 0ustar niknik/* * Copyright (c) 1997 - 2008 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "krb5_locl.h" void _krb5_evp_schedule(krb5_context context, struct _krb5_key_type *kt, struct _krb5_key_data *kd) { struct _krb5_evp_schedule *key = kd->schedule->data; const EVP_CIPHER *c = (*kt->evp)(); EVP_CIPHER_CTX_init(&key->ectx); EVP_CIPHER_CTX_init(&key->dctx); EVP_CipherInit_ex(&key->ectx, c, NULL, kd->key->keyvalue.data, NULL, 1); EVP_CipherInit_ex(&key->dctx, c, NULL, kd->key->keyvalue.data, NULL, 0); } void _krb5_evp_cleanup(krb5_context context, struct _krb5_key_data *kd) { struct _krb5_evp_schedule *key = kd->schedule->data; EVP_CIPHER_CTX_cleanup(&key->ectx); EVP_CIPHER_CTX_cleanup(&key->dctx); } krb5_error_code _krb5_evp_encrypt(krb5_context context, struct _krb5_key_data *key, void *data, size_t len, krb5_boolean encryptp, int usage, void *ivec) { struct _krb5_evp_schedule *ctx = key->schedule->data; EVP_CIPHER_CTX *c; c = encryptp ? &ctx->ectx : &ctx->dctx; if (ivec == NULL) { /* alloca ? */ size_t len2 = EVP_CIPHER_CTX_iv_length(c); void *loiv = malloc(len2); if (loiv == NULL) return krb5_enomem(context); memset(loiv, 0, len2); EVP_CipherInit_ex(c, NULL, NULL, NULL, loiv, -1); free(loiv); } else EVP_CipherInit_ex(c, NULL, NULL, NULL, ivec, -1); EVP_Cipher(c, data, data, len); return 0; } static const unsigned char zero_ivec[EVP_MAX_BLOCK_LENGTH] = { 0 }; krb5_error_code _krb5_evp_encrypt_cts(krb5_context context, struct _krb5_key_data *key, void *data, size_t len, krb5_boolean encryptp, int usage, void *ivec) { size_t i, blocksize; struct _krb5_evp_schedule *ctx = key->schedule->data; unsigned char tmp[EVP_MAX_BLOCK_LENGTH], ivec2[EVP_MAX_BLOCK_LENGTH]; EVP_CIPHER_CTX *c; unsigned char *p; c = encryptp ? &ctx->ectx : &ctx->dctx; blocksize = EVP_CIPHER_CTX_block_size(c); if (len < blocksize) { krb5_set_error_message(context, EINVAL, "message block too short"); return EINVAL; } else if (len == blocksize) { EVP_CipherInit_ex(c, NULL, NULL, NULL, zero_ivec, -1); EVP_Cipher(c, data, data, len); return 0; } if (ivec) EVP_CipherInit_ex(c, NULL, NULL, NULL, ivec, -1); else EVP_CipherInit_ex(c, NULL, NULL, NULL, zero_ivec, -1); if (encryptp) { p = data; i = ((len - 1) / blocksize) * blocksize; EVP_Cipher(c, p, p, i); p += i - blocksize; len -= i; memcpy(ivec2, p, blocksize); for (i = 0; i < len; i++) tmp[i] = p[i + blocksize] ^ ivec2[i]; for (; i < blocksize; i++) tmp[i] = 0 ^ ivec2[i]; EVP_CipherInit_ex(c, NULL, NULL, NULL, zero_ivec, -1); EVP_Cipher(c, p, tmp, blocksize); memcpy(p + blocksize, ivec2, len); if (ivec) memcpy(ivec, p, blocksize); } else { unsigned char tmp2[EVP_MAX_BLOCK_LENGTH], tmp3[EVP_MAX_BLOCK_LENGTH]; p = data; if (len > blocksize * 2) { /* remove last two blocks and round up, decrypt this with cbc, then do cts dance */ i = ((((len - blocksize * 2) + blocksize - 1) / blocksize) * blocksize); memcpy(ivec2, p + i - blocksize, blocksize); EVP_Cipher(c, p, p, i); p += i; len -= i + blocksize; } else { if (ivec) memcpy(ivec2, ivec, blocksize); else memcpy(ivec2, zero_ivec, blocksize); len -= blocksize; } memcpy(tmp, p, blocksize); EVP_CipherInit_ex(c, NULL, NULL, NULL, zero_ivec, -1); EVP_Cipher(c, tmp2, p, blocksize); memcpy(tmp3, p + blocksize, len); memcpy(tmp3 + len, tmp2 + len, blocksize - len); /* xor 0 */ for (i = 0; i < len; i++) p[i + blocksize] = tmp2[i] ^ tmp3[i]; EVP_CipherInit_ex(c, NULL, NULL, NULL, zero_ivec, -1); EVP_Cipher(c, p, tmp3, blocksize); for (i = 0; i < blocksize; i++) p[i] ^= ivec2[i]; if (ivec) memcpy(ivec, tmp, blocksize); } return 0; } heimdal-7.5.0/lib/krb5/kcm.h0000644000175000017500000000552313026237312013612 0ustar niknik/* * Copyright (c) 2005, PADL Software Pty Ltd. * All rights reserved. * * Portions Copyright (c) 2009 Apple Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of PADL Software nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY PADL SOFTWARE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL PADL SOFTWARE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #ifndef __KCM_H__ #define __KCM_H__ /* * KCM protocol definitions */ #define KCM_PROTOCOL_VERSION_MAJOR 2 #define KCM_PROTOCOL_VERSION_MINOR 0 typedef unsigned char kcmuuid_t[16]; typedef enum kcm_operation { KCM_OP_NOOP, KCM_OP_GET_NAME, KCM_OP_RESOLVE, KCM_OP_GEN_NEW, KCM_OP_INITIALIZE, KCM_OP_DESTROY, KCM_OP_STORE, KCM_OP_RETRIEVE, KCM_OP_GET_PRINCIPAL, KCM_OP_GET_CRED_UUID_LIST, KCM_OP_GET_CRED_BY_UUID, KCM_OP_REMOVE_CRED, KCM_OP_SET_FLAGS, KCM_OP_CHOWN, KCM_OP_CHMOD, KCM_OP_GET_INITIAL_TICKET, KCM_OP_GET_TICKET, KCM_OP_MOVE_CACHE, KCM_OP_GET_CACHE_UUID_LIST, KCM_OP_GET_CACHE_BY_UUID, KCM_OP_GET_DEFAULT_CACHE, KCM_OP_SET_DEFAULT_CACHE, KCM_OP_GET_KDC_OFFSET, KCM_OP_SET_KDC_OFFSET, /* NTLM operations */ KCM_OP_ADD_NTLM_CRED, KCM_OP_HAVE_NTLM_CRED, KCM_OP_DEL_NTLM_CRED, KCM_OP_DO_NTLM_AUTH, KCM_OP_GET_NTLM_USER_LIST, KCM_OP_MAX } kcm_operation; #define _PATH_KCM_SOCKET "/var/run/.kcm_socket" #define _PATH_KCM_DOOR "/var/run/.kcm_door" #define KCM_NTLM_FLAG_SESSIONKEY 1 #define KCM_NTLM_FLAG_NTLM2_SESSION 2 #define KCM_NTLM_FLAG_KEYEX 4 #define KCM_NTLM_FLAG_AV_GUEST 8 #endif /* __KCM_H__ */ heimdal-7.5.0/lib/krb5/get_addrs.c0000644000175000017500000002015213026237312014762 0ustar niknik/* * Copyright (c) 1997 - 2002 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "krb5_locl.h" #ifdef __osf__ /* hate */ struct rtentry; struct mbuf; #endif #ifdef HAVE_NET_IF_H #include #endif #include static krb5_error_code gethostname_fallback (krb5_context context, krb5_addresses *res) { krb5_error_code ret; char hostname[MAXHOSTNAMELEN]; struct hostent *hostent; if (gethostname (hostname, sizeof(hostname))) { ret = errno; krb5_set_error_message(context, ret, "gethostname: %s", strerror(ret)); return ret; } hostent = roken_gethostbyname (hostname); if (hostent == NULL) { ret = errno; krb5_set_error_message (context, ret, "gethostbyname %s: %s", hostname, strerror(ret)); return ret; } res->len = 1; res->val = malloc (sizeof(*res->val)); if (res->val == NULL) return krb5_enomem(context); res->val[0].addr_type = hostent->h_addrtype; res->val[0].address.data = NULL; res->val[0].address.length = 0; ret = krb5_data_copy (&res->val[0].address, hostent->h_addr, hostent->h_length); if (ret) { free (res->val); return ret; } return 0; } enum { LOOP = 1, /* do include loopback addrs */ LOOP_IF_NONE = 2, /* include loopback addrs if no others */ EXTRA_ADDRESSES = 4, /* include extra addresses */ SCAN_INTERFACES = 8 /* scan interfaces for addresses */ }; /* * Try to figure out the addresses of all configured interfaces with a * lot of magic ioctls. */ static krb5_error_code find_all_addresses (krb5_context context, krb5_addresses *res, int flags) { struct sockaddr sa_zero; struct ifaddrs *ifa0, *ifa; krb5_error_code ret = ENXIO; unsigned int num, idx; krb5_addresses ignore_addresses; if (getifaddrs(&ifa0) == -1) { ret = errno; krb5_set_error_message(context, ret, "getifaddrs: %s", strerror(ret)); return (ret); } memset(&sa_zero, 0, sizeof(sa_zero)); /* First, count all the ifaddrs. */ for (ifa = ifa0, num = 0; ifa != NULL; ifa = ifa->ifa_next, num++) /* nothing */; if (num == 0) { freeifaddrs(ifa0); krb5_set_error_message(context, ENXIO, N_("no addresses found", "")); return (ENXIO); } if (flags & EXTRA_ADDRESSES) { /* we'll remove the addresses we don't care about */ ret = krb5_get_ignore_addresses(context, &ignore_addresses); if(ret) return ret; } /* Allocate storage for them. */ res->val = calloc(num, sizeof(*res->val)); if (res->val == NULL) { if (flags & EXTRA_ADDRESSES) krb5_free_addresses(context, &ignore_addresses); freeifaddrs(ifa0); return krb5_enomem(context); } /* Now traverse the list. */ for (ifa = ifa0, idx = 0; ifa != NULL; ifa = ifa->ifa_next) { if ((ifa->ifa_flags & IFF_UP) == 0) continue; if (ifa->ifa_addr == NULL) continue; if (memcmp(ifa->ifa_addr, &sa_zero, sizeof(sa_zero)) == 0) continue; if (krb5_sockaddr_uninteresting(ifa->ifa_addr)) continue; if (krb5_sockaddr_is_loopback(ifa->ifa_addr) && (flags & LOOP) == 0) /* We'll deal with the LOOP_IF_NONE case later. */ continue; ret = krb5_sockaddr2address(context, ifa->ifa_addr, &res->val[idx]); if (ret) { /* * The most likely error here is going to be "Program * lacks support for address type". This is no big * deal -- just continue, and we'll listen on the * addresses who's type we *do* support. */ continue; } /* possibly skip this address? */ if((flags & EXTRA_ADDRESSES) && krb5_address_search(context, &res->val[idx], &ignore_addresses)) { krb5_free_address(context, &res->val[idx]); flags &= ~LOOP_IF_NONE; /* we actually found an address, so don't add any loop-back addresses */ continue; } idx++; } /* * If no addresses were found, and LOOP_IF_NONE is set, then find * the loopback addresses and add them to our list. */ if ((flags & LOOP_IF_NONE) != 0 && idx == 0) { for (ifa = ifa0; ifa != NULL; ifa = ifa->ifa_next) { if ((ifa->ifa_flags & IFF_UP) == 0) continue; if (ifa->ifa_addr == NULL) continue; if (memcmp(ifa->ifa_addr, &sa_zero, sizeof(sa_zero)) == 0) continue; if (krb5_sockaddr_uninteresting(ifa->ifa_addr)) continue; if (!krb5_sockaddr_is_loopback(ifa->ifa_addr)) continue; if ((ifa->ifa_flags & IFF_LOOPBACK) == 0) /* Presumably loopback addrs are only used on loopback ifs! */ continue; ret = krb5_sockaddr2address(context, ifa->ifa_addr, &res->val[idx]); if (ret) continue; /* We don't consider this failure fatal */ if((flags & EXTRA_ADDRESSES) && krb5_address_search(context, &res->val[idx], &ignore_addresses)) { krb5_free_address(context, &res->val[idx]); continue; } idx++; } } if (flags & EXTRA_ADDRESSES) krb5_free_addresses(context, &ignore_addresses); freeifaddrs(ifa0); if (ret) { free(res->val); res->val = NULL; } else res->len = idx; /* Now a count. */ return (ret); } static krb5_error_code get_addrs_int (krb5_context context, krb5_addresses *res, int flags) { krb5_error_code ret = -1; res->len = 0; res->val = NULL; if (flags & SCAN_INTERFACES) { ret = find_all_addresses (context, res, flags); if(ret || res->len == 0) ret = gethostname_fallback (context, res); } else { ret = 0; } if(ret == 0 && (flags & EXTRA_ADDRESSES)) { krb5_addresses a; /* append user specified addresses */ ret = krb5_get_extra_addresses(context, &a); if(ret) { krb5_free_addresses(context, res); return ret; } ret = krb5_append_addresses(context, res, &a); if(ret) { krb5_free_addresses(context, res); return ret; } krb5_free_addresses(context, &a); } if(res->len == 0) { free(res->val); res->val = NULL; } return ret; } /* * Try to get all addresses, but return the one corresponding to * `hostname' if we fail. * * Only include loopback address if there are no other. */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_get_all_client_addrs (krb5_context context, krb5_addresses *res) { int flags = LOOP_IF_NONE | EXTRA_ADDRESSES; if (context->scan_interfaces) flags |= SCAN_INTERFACES; return get_addrs_int (context, res, flags); } /* * Try to get all local addresses that a server should listen to. * If that fails, we return the address corresponding to `hostname'. */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_get_all_server_addrs (krb5_context context, krb5_addresses *res) { return get_addrs_int (context, res, LOOP | SCAN_INTERFACES); } heimdal-7.5.0/lib/krb5/krb5_create_checksum.cat30000644000175000017500000001744613212450756017530 0ustar niknik NAME(3) BSD Library Functions Manual NAME(3) NNAAMMEE kkrrbb55__cchheecckkssuumm, kkrrbb55__cchheecckkssuumm__ddiissaabbllee, kkrrbb55__cchheecckkssuumm__iiss__ccoolllliissiioonn__pprrooooff, kkrrbb55__cchheecckkssuumm__iiss__kkeeyyeedd, kkrrbb55__cchheecckkssuummssiizzee, kkrrbb55__cckkssuummttyyppee__vvaalliidd, kkrrbb55__ccooppyy__cchheecckkssuumm, kkrrbb55__ccrreeaattee__cchheecckkssuumm, kkrrbb55__ccrryyppttoo__ggeett__cchheecckkssuumm__ttyyppee kkrrbb55__ffrreeee__cchheecckkssuumm, kkrrbb55__ffrreeee__cchheecckkssuumm__ccoonntteennttss, kkrrbb55__hhmmaacc, kkrrbb55__vveerriiffyy__cchheecckkssuumm -- creates, handles and verifies checksums LLIIBBRRAARRYY Kerberos 5 Library (libkrb5, -lkrb5) SSYYNNOOPPSSIISS ##iinncclluuddee <> typedef Checksum krb5_checksum; _v_o_i_d kkrrbb55__cchheecckkssuumm__ddiissaabbllee(_k_r_b_5___c_o_n_t_e_x_t _c_o_n_t_e_x_t, _k_r_b_5___c_k_s_u_m_t_y_p_e _t_y_p_e); _k_r_b_5___b_o_o_l_e_a_n kkrrbb55__cchheecckkssuumm__iiss__ccoolllliissiioonn__pprrooooff(_k_r_b_5___c_o_n_t_e_x_t _c_o_n_t_e_x_t, _k_r_b_5___c_k_s_u_m_t_y_p_e _t_y_p_e); _k_r_b_5___b_o_o_l_e_a_n kkrrbb55__cchheecckkssuumm__iiss__kkeeyyeedd(_k_r_b_5___c_o_n_t_e_x_t _c_o_n_t_e_x_t, _k_r_b_5___c_k_s_u_m_t_y_p_e _t_y_p_e); _k_r_b_5___e_r_r_o_r___c_o_d_e kkrrbb55__cckkssuummttyyppee__vvaalliidd(_k_r_b_5___c_o_n_t_e_x_t _c_o_n_t_e_x_t, _k_r_b_5___c_k_s_u_m_t_y_p_e _c_t_y_p_e); _k_r_b_5___e_r_r_o_r___c_o_d_e kkrrbb55__cchheecckkssuummssiizzee(_k_r_b_5___c_o_n_t_e_x_t _c_o_n_t_e_x_t, _k_r_b_5___c_k_s_u_m_t_y_p_e _t_y_p_e, _s_i_z_e___t _*_s_i_z_e); _k_r_b_5___e_r_r_o_r___c_o_d_e kkrrbb55__ccrreeaattee__cchheecckkssuumm(_k_r_b_5___c_o_n_t_e_x_t _c_o_n_t_e_x_t, _k_r_b_5___c_r_y_p_t_o _c_r_y_p_t_o, _k_r_b_5___k_e_y___u_s_a_g_e _u_s_a_g_e, _i_n_t _t_y_p_e, _v_o_i_d _*_d_a_t_a, _s_i_z_e___t _l_e_n, _C_h_e_c_k_s_u_m _*_r_e_s_u_l_t); _k_r_b_5___e_r_r_o_r___c_o_d_e kkrrbb55__vveerriiffyy__cchheecckkssuumm(_k_r_b_5___c_o_n_t_e_x_t _c_o_n_t_e_x_t, _k_r_b_5___c_r_y_p_t_o _c_r_y_p_t_o, _k_r_b_5___k_e_y___u_s_a_g_e _u_s_a_g_e, _v_o_i_d _*_d_a_t_a, _s_i_z_e___t _l_e_n, _C_h_e_c_k_s_u_m _*_c_k_s_u_m); _k_r_b_5___e_r_r_o_r___c_o_d_e kkrrbb55__ccrryyppttoo__ggeett__cchheecckkssuumm__ttyyppee(_k_r_b_5___c_o_n_t_e_x_t _c_o_n_t_e_x_t, _k_r_b_5___c_r_y_p_t_o _c_r_y_p_t_o, _k_r_b_5___c_k_s_u_m_t_y_p_e _*_t_y_p_e); _v_o_i_d kkrrbb55__ffrreeee__cchheecckkssuumm(_k_r_b_5___c_o_n_t_e_x_t _c_o_n_t_e_x_t, _k_r_b_5___c_h_e_c_k_s_u_m _*_c_k_s_u_m); _v_o_i_d kkrrbb55__ffrreeee__cchheecckkssuumm__ccoonntteennttss(_k_r_b_5___c_o_n_t_e_x_t _c_o_n_t_e_x_t, _k_r_b_5___c_h_e_c_k_s_u_m _*_c_k_s_u_m); _k_r_b_5___e_r_r_o_r___c_o_d_e kkrrbb55__hhmmaacc(_k_r_b_5___c_o_n_t_e_x_t _c_o_n_t_e_x_t, _k_r_b_5___c_k_s_u_m_t_y_p_e _c_k_t_y_p_e, _c_o_n_s_t _v_o_i_d _*_d_a_t_a, _s_i_z_e___t _l_e_n, _u_n_s_i_g_n_e_d _u_s_a_g_e, _k_r_b_5___k_e_y_b_l_o_c_k _*_k_e_y, _C_h_e_c_k_s_u_m _*_r_e_s_u_l_t); _k_r_b_5___e_r_r_o_r___c_o_d_e kkrrbb55__ccooppyy__cchheecckkssuumm(_k_r_b_5___c_o_n_t_e_x_t _c_o_n_t_e_x_t, _c_o_n_s_t _k_r_b_5___c_h_e_c_k_s_u_m _*_o_l_d, _k_r_b_5___c_h_e_c_k_s_u_m _*_*_n_e_w); DDEESSCCRRIIPPTTIIOONN The krb5_checksum structure holds a Kerberos checksum. There is no com- ponent inside krb5_checksum that is directly referable. The functions are used to create and verify checksums. kkrrbb55__ccrreeaattee__cchheecckkssuumm() creates a checksum of the specified data, and puts it in _r_e_s_u_l_t. If _c_r_y_p_t_o is NULL, _u_s_a_g_e___o_r___t_y_p_e specifies the checksum type to use; it must not be keyed. Otherwise _c_r_y_p_t_o is an encryption con- text created by kkrrbb55__ccrryyppttoo__iinniitt(), and _u_s_a_g_e___o_r___t_y_p_e specifies a key- usage. kkrrbb55__vveerriiffyy__cchheecckkssuumm() verifies the _c_h_e_c_k_s_u_m against the provided data. kkrrbb55__cchheecckkssuumm__iiss__ccoolllliissiioonn__pprrooooff() returns true is the specified checksum is collision proof (that it's very unlikely that two strings has the same hash value, and that it's hard to find two strings that has the same hash). Examples of collision proof checksums are MD5, and SHA1, while CRC32 is not. kkrrbb55__cchheecckkssuumm__iiss__kkeeyyeedd() returns true if the specified checksum type is keyed (that the hash value is a function of both the data, and a separate key). Examples of keyed hash algorithms are HMAC-SHA1-DES3, and RSA- MD5-DES. The ``plain'' hash functions MD5, and SHA1 are not keyed. kkrrbb55__ccrryyppttoo__ggeett__cchheecckkssuumm__ttyyppee() returns the checksum type that will be used when creating a checksum for the given _c_r_y_p_t_o context. This func- tion is useful in combination with kkrrbb55__cchheecckkssuummssiizzee() when you want to know the size a checksum will use when you create it. kkrrbb55__cckkssuummttyyppee__vvaalliidd() returns 0 or an error if the checksumtype is implemented and not currently disabled in this kerberos library. kkrrbb55__cchheecckkssuummssiizzee() returns the size of the outdata of checksum function. kkrrbb55__ccooppyy__cchheecckkssuumm() returns a copy of the checksum kkrrbb55__ffrreeee__cchheecckkssuumm() should use used to free the _n_e_w checksum. kkrrbb55__ffrreeee__cchheecckkssuumm() free the checksum and the content of the checksum. kkrrbb55__ffrreeee__cchheecckkssuumm__ccoonntteennttss() frees the content of checksum in _c_k_s_u_m. kkrrbb55__hhmmaacc() calculates the HMAC over _d_a_t_a (with length _l_e_n) using the keyusage _u_s_a_g_e and keyblock _k_e_y. Note that keyusage is not always used in checksums. kkrrbb55__cchheecckkssuumm__ddiissaabbllee globally disables the checksum type. SSEEEE AALLSSOO krb5_crypto_init(3), krb5_c_encrypt(3), krb5_encrypt(3) HEIMDAL August 12, 2005 HEIMDAL heimdal-7.5.0/lib/krb5/krb5.conf.cat50000644000175000017500000012511213212450757015240 0ustar niknik KRB5.CONF(5) BSD File Formats Manual KRB5.CONF(5) NNAAMMEE kkrrbb55..ccoonnff -- configuration file for Kerberos 5 SSYYNNOOPPSSIISS ##iinncclluuddee <> DDEESSCCRRIIPPTTIIOONN The kkrrbb55..ccoonnff file specifies several configuration parameters for the Kerberos 5 library, as well as for some programs. The file consists of one or more sections, containing a number of bind- ings. The value of each binding can be either a string or a list of other bindings. The grammar looks like: file: /* empty */ sections sections: section sections section section: '[' section_name ']' bindings section_name: STRING bindings: binding bindings binding binding: name '=' STRING name '=' '{' bindings '}' name: STRING STRINGs consists of one or more non-whitespace characters. STRINGs that are specified later in this man-page uses the following notation. boolean values can be either yes/true or no/false. time values can be a list of year, month, day, hour, min, second. Example: 1 month 2 days 30 min. If no unit is given, seconds is assumed. etypes valid encryption types are: des-cbc-crc, des-cbc-md4, des-cbc- md5, des3-cbc-sha1, arcfour-hmac-md5, aes128-cts-hmac-sha1-96, and aes256-cts-hmac-sha1-96 . address an address can be either a IPv4 or a IPv6 address. Currently recognised sections and bindings are: [appdefaults] Specifies the default values to be used for Kerberos applica- tions. You can specify defaults per application, realm, or a combination of these. The preference order is: 1. _a_p_p_l_i_c_a_t_i_o_n _r_e_a_l_m _o_p_t_i_o_n 2. _a_p_p_l_i_c_a_t_i_o_n _o_p_t_i_o_n 3. _r_e_a_l_m _o_p_t_i_o_n 4. _o_p_t_i_o_n The supported options are: forwardable = _b_o_o_l_e_a_n When obtaining initial credentials, make the cre- dentials forwardable. proxiable = _b_o_o_l_e_a_n When obtaining initial credentials, make the cre- dentials proxiable. no-addresses = _b_o_o_l_e_a_n When obtaining initial credentials, request them for an empty set of addresses, making the tickets valid from any address. ticket_lifetime = _t_i_m_e Default ticket lifetime. renew_lifetime = _t_i_m_e Default renewable ticket lifetime. encrypt = _b_o_o_l_e_a_n Use encryption, when available. forward = _b_o_o_l_e_a_n Forward credentials to remote host (for rsh(1), telnet(1), etc). [libdefaults] default_realm = _R_E_A_L_M Default realm to use, this is also known as your ``local realm''. The default is the result of kkrrbb55__ggeett__hhoosstt__rreeaallmm(_l_o_c_a_l _h_o_s_t_n_a_m_e). allow_weak_crypto = _b_o_o_l_e_a_n are weak crypto algorithms allowed to be used, among others, DES is considered weak. clockskew = _t_i_m_e Maximum time differential (in seconds) allowed when comparing times. Default is 300 seconds (five min- utes). kdc_timeout = _t_i_m_e Maximum time to wait for a reply from the kdc, default is 3 seconds. capath = { _d_e_s_t_i_n_a_t_i_o_n_-_r_e_a_l_m = _n_e_x_t_-_h_o_p_-_r_e_a_l_m ... } This is deprecated, see the capaths section below. default_cc_type = _c_c_t_y_p_e sets the default credentials type. default_cc_name = _c_c_n_a_m_e the default credentials cache name. If you want to change the type only use default_cc_type. The string can contain variables that are expanded on runtime. The Only supported variable currently is %{uid} which expands to the current user id. default_etypes = _e_t_y_p_e_s _._._. A list of default encryption types to use. (Default: all enctypes if allow_weak_crypto = TRUE, else all enctypes except single DES enctypes.) default_as_etypes = _e_t_y_p_e_s _._._. A list of default encryption types to use in AS requests. (Default: the value of default_etypes.) default_tgs_etypes = _e_t_y_p_e_s _._._. A list of default encryption types to use in TGS requests. (Default: the value of default_etypes.) default_etypes_des = _e_t_y_p_e_s _._._. A list of default encryption types to use when requesting a DES credential. default_keytab_name = _k_e_y_t_a_b The keytab to use if no other is specified, default is ``FILE:/etc/krb5.keytab''. dns_lookup_kdc = _b_o_o_l_e_a_n Use DNS SRV records to lookup KDC services loca- tion. dns_lookup_realm = _b_o_o_l_e_a_n Use DNS TXT records to lookup domain to realm map- pings. kdc_timesync = _b_o_o_l_e_a_n Try to keep track of the time differential between the local machine and the KDC, and then compensate for that when issuing requests. max_retries = _n_u_m_b_e_r The max number of times to try to contact each KDC. large_msg_size = _n_u_m_b_e_r The threshold where protocols with tiny maximum message sizes are not considered usable to send messages to the KDC. ticket_lifetime = _t_i_m_e Default ticket lifetime. renew_lifetime = _t_i_m_e Default renewable ticket lifetime. forwardable = _b_o_o_l_e_a_n When obtaining initial credentials, make the cre- dentials forwardable. This option is also valid in the [realms] section. proxiable = _b_o_o_l_e_a_n When obtaining initial credentials, make the cre- dentials proxiable. This option is also valid in the [realms] section. verify_ap_req_nofail = _b_o_o_l_e_a_n If enabled, failure to verify credentials against a local key is a fatal error. The application has to be able to read the corresponding service key for this to work. Some applications, like su(1), enable this option unconditionally. warn_pwexpire = _t_i_m_e How soon to warn for expiring password. Default is seven days. http_proxy = _p_r_o_x_y_-_s_p_e_c A HTTP-proxy to use when talking to the KDC via HTTP. dns_proxy = _p_r_o_x_y_-_s_p_e_c Enable using DNS via HTTP. extra_addresses = _a_d_d_r_e_s_s _._._. A list of addresses to get tickets for along with all local addresses. time_format = _s_t_r_i_n_g How to print time strings in logs, this string is passed to strftime(3). date_format = _s_t_r_i_n_g How to print date strings in logs, this string is passed to strftime(3). log_utc = _b_o_o_l_e_a_n Write log-entries using UTC instead of your local time zone. scan_interfaces = _b_o_o_l_e_a_n Scan all network interfaces for addresses, as opposed to simply using the address associated with the system's host name. fcache_version = _i_n_t Use file credential cache format version specified. fcc-mit-ticketflags = _b_o_o_l_e_a_n Use MIT compatible format for file credential cache. It's the field ticketflags that is stored in reverse bit order for older than Heimdal 0.7. Setting this flag to TRUE makes it store the MIT way, this is default for Heimdal 0.7. check-rd-req-server If set to "ignore", the framework will ignore any of the server input to krb5_rd_req(3), this is very useful when the GSS-API server input the wrong server name into the gss_accept_sec_context call. k5login_directory = _d_i_r_e_c_t_o_r_y Alternative location for user .k5login files. This option is provided for compatibility with MIT krb5 configuration files. k5login_authoritative = _b_o_o_l_e_a_n If true then if a principal is not found in k5login files then krb5_userok(3) will not fallback on principal to username mapping. This option is pro- vided for compatibility with MIT krb5 configuration files. kuserok = _r_u_l_e _._._. Specifies krb5_userok(3) behavior. If multiple values are given, then krb5_userok(3) will evaluate them in order until one succeeds or all fail. Rules are implemented by plugins, with three built- in plugins described below. Default: USER-K5LOGIN SIMPLE DENY. kuserok = _D_E_N_Y If set and evaluated then krb5_userok(3) will deny access to the given username no matter what the principal name might be. kuserok = _S_I_M_P_L_E If set and evaluated then krb5_userok(3) will use principal to username mapping (see auth_to_local below). If the principal maps to the requested username then access is allowed. kuserok = _S_Y_S_T_E_M_-_K_5_L_O_G_I_N_[_:_d_i_r_e_c_t_o_r_y_] If set and evaluated then krb5_userok(3) will use k5login files named after the _l_u_s_e_r argument to krb5_userok(3) in the given directory or in _/_e_t_c_/_k_5_l_o_g_i_n_._d_/. K5login files are text files, with each line containing just a principal name; principals apearing in a user's k5login file are permitted access to the user's account. Note: this rule performs no ownership nor permissions checks on k5login files; proper ownership and permis- sions/ACLs are expected due to the k5login location being a system location. kuserok = _U_S_E_R_-_K_5_L_O_G_I_N If set and evaluated then krb5_userok(3) will use _~_l_u_s_e_r_/_._k_5_l_o_g_i_n and _~_l_u_s_e_r_/_._k_5_l_o_g_i_n_._d_/_*. User k5login files and directories must be owned by the user and must not have world nor group write per- missions. aname2lname-text-db = _f_i_l_e_n_a_m_e The named file must be a sorted (in increasing order) text file where every line consists of an unparsed principal name optionally followed by whitespace and a username. The aname2lname func- tion will do a binary search on this file, if con- figured, looking for lines that match the given principal name, and if found the given username will be used, or, if the username is missing, an error will be returned. If the file doesn't exist, or if no matching line is found then other plugins will be allowed to run. fcache_strict_checking strict checking in FILE credential caches that owner, no symlink and permissions is correct. name_canon_rules = _r_u_l_e_s One or more service principal name canonicalization rules. Each rule consists of one or more tokens separated by colon (':'). Currently these rules are used only for hostname canonicalization (usu- ally when getting a service ticket, from a ccache or a TGS, but also when acquiring GSS initiator credentials from a keytab). These rules can be used to implement DNS resolver-like search lists without having to use DNS. NOTE: Name canonicalization rules are an experimen- tal feature. The first token is a rule type, one of: _a_s_-_i_s_, _q_u_a_l_i_f_y_, _o_r _n_s_s_. Any remaining tokens must be options tokens: _u_s_e___f_a_s_t (use FAST to protect TGS exchanges; cur- rently not supported), _u_s_e___d_n_s_s_e_c (use DNSSEC to protect hostname lookups; currently not supported), _c_c_a_c_h_e___o_n_l_y , _u_s_e___r_e_f_e_r_r_a_l_s_, _n_o___r_e_f_e_r_r_a_l_s_, _l_o_o_k_u_p___r_e_a_l_m_, _m_i_n_d_o_t_s_=_N_, _m_a_x_d_o_t_s_=_N_, _o_r_d_e_r_=_N_, domain= _d_o_m_a_i_n_, realm= _r_e_a_l_m_, match_domain= _d_o_m_a_i_n_, and match_realm= _r_e_a_l_m_. When trying to obtain a service ticket for a host- based service principal name, name canonicalization rules are applied to that name in the order given, one by one, until one succeds (a service ticket is obtained), or all fail. Similarly when acquiring GSS initiator credentials from a keytab, and when comparing a non-canonical GSS name to a canonical one. For each rule the system checks that the hostname has at least _m_i_n_d_o_t_s periods (if given) in it, at most _m_a_x_d_o_t_s periods (if given), that the hostname ends in the given _m_a_t_c_h___d_o_m_a_i_n (if given), and that the realm of the principal matches the _m_a_t_c_h___r_e_a_l_m (if given). _A_s_-_i_s rules leave the hostname unmodified but may set a realm. _Q_u_a_l_i_f_y rules qualify the hostname with the given _d_o_m_a_i_n and also may set the realm. The _n_s_s rule uses the system resolver to lookup the host's canonical name and is usually not secure. Note that using the _n_s_s rule type implies having to have principal aliases in the HDB (though not nec- essarily in keytabs). The empty realm denotes "ask the client's realm's TGS". The empty realm may be set as well as matched. The order in which rules are applied is as follows: first all the rules with explicit _o_r_d_e_r then all other rules in the order in which they appear. If any two rules have the same explicit _o_r_d_e_r, their order of appearance in krb5.conf breaks the tie. Explicitly specifying order can be useful where tools read and write the configuration file without preserving parameter order. Malformed rules are ignored. allow_hierarchical_capaths = _b_o_o_l_e_a_n When validating cross-realm transit paths, absent any explicit capath from the client realm to the server realm, allow a hierarchical transit path via the common ancestor domain of the two realms. Defaults to true. Note, absent an explicit set- ting, hierarchical capaths are always used by the KDC when generating a referral to a destination with which is no direct trust. [domain_realm] This is a list of mappings from DNS domain to Kerberos realm. Each binding in this section looks like: domain = realm The domain can be either a full name of a host or a trailing component, in the latter case the domain-string should start with a period. The trailing component only matches hosts that are in the same domain, ie ``.example.com'' matches ``foo.example.com'', but not ``foo.test.example.com''. The realm may be the token `dns_locate', in which case the actual realm will be determined using DNS (independently of the setting of the `dns_lookup_realm' option). [realms] _R_E_A_L_M = { kdc = _[_s_e_r_v_i_c_e_/_]_h_o_s_t_[_:_p_o_r_t_] Specifies a list of kdcs for this realm. If the optional _p_o_r_t is absent, the default value for the ``kerberos/udp'' ``kerberos/tcp'', and ``http/tcp'' port (depending on service) will be used. The kdcs will be used in the order that they are specified. The optional _s_e_r_v_i_c_e specifies over what medium the kdc should be contacted. Possible services are ``udp'', ``tcp'', and ``http''. Http can also be written as ``http://''. Default service is ``udp'' and ``tcp''. admin_server = _h_o_s_t_[_:_p_o_r_t_] Specifies the admin server for this realm, where all the modifications to the database are performed. kpasswd_server = _h_o_s_t_[_:_p_o_r_t_] Points to the server where all the pass- word changes are performed. If there is no such entry, the kpasswd port on the admin_server host will be tried. tgs_require_subkey a boolan variable that defaults to false. Old DCE secd (pre 1.1) might need this to be true. auth_to_local_names = { _p_r_i_n_c_i_p_a_l___n_a_m_e _= _u_s_e_r_n_a_m_e The given _p_r_i_n_c_i_p_a_l___n_a_m_e will be mapped to the given _u_s_e_r_n_a_m_e if the _R_E_A_L_M is a default realm. } auth_to_local = HEIMDAL_DEFAULT Use the Heimdal default principal to username mapping. Applies to principals from the _R_E_A_L_M if and only if _R_E_A_L_M is a default realm. auth_to_local = DEFAULT Use the MIT default principal to user- name mapping. Applies to principals from the _R_E_A_L_M if and only if _R_E_A_L_M is a default realm. auth_to_local = DB:/path/to/db.txt Use a binary search of the given DB. The DB must be a flat-text file sortedf in the "C" locale, with each record being a line (separated by either LF or CRLF) consisting of a principal name followed by whitespace followed by a username. Applies to principals from the _R_E_A_L_M if and only if _R_E_A_L_M is a default realm. auth_to_local = DB:/path/to/db Use the given DB, if there's a plugin for it. Applies to principals from the _R_E_A_L_M if and only if _R_E_A_L_M is a default realm. auth_to_local = RULE:... Use the given rule, if there's a plugin for it. Applies to principals from the _R_E_A_L_M if and only if _R_E_A_L_M is a default realm. auth_to_local = NONE No additional principal to username map- ping is done. Note that _a_u_t_h___t_o___l_o_c_a_l___n_a_m_e_s and any preceding _a_u_t_h___t_o___l_o_c_a_l rules have precedence. } [capaths] _c_l_i_e_n_t_-_r_e_a_l_m = { _s_e_r_v_e_r_-_r_e_a_l_m = _h_o_p_-_r_e_a_l_m _._._. This serves two purposes. First the first listed _h_o_p_-_r_e_a_l_m tells a client which realm it should contact in order to ultimately obtain credentials for a service in the _s_e_r_v_e_r_-_r_e_a_l_m. Secondly, it tells the KDC (and other servers) which realms are allowed in a multi-hop traversal from _c_l_i_e_n_t_-_r_e_a_l_m to _s_e_r_v_e_r_-_r_e_a_l_m. Except for the client case, the order of the realms are not important. _} [logging] _e_n_t_i_t_y = _d_e_s_t_i_n_a_t_i_o_n Specifies that _e_n_t_i_t_y should use the specified destination for logging. See the krb5_openlog(3) manual page for a list of defined destinations. [kdc] database = { dbname = _[_D_A_T_B_A_S_E_T_Y_P_E_:_]_D_A_T_A_B_A_S_E_N_A_M_E Use this database for this realm. The _D_A_T_A_B_A_S_E_T_Y_P_E should be one of 'lmdb', 'db3', 'db1', 'db', 'sqlite', or 'ldap'. See the info documetation how to config- ure different database backends. realm = _R_E_A_L_M Specifies the realm that will be stored in this database. It realm isn't set, it will used as the default database, there can only be one entry that doesn't have a realm stanza. mkey_file = _F_I_L_E_N_A_M_E Use this keytab file for the master key of this database. If not specified _D_A_T_A_B_A_S_E_N_A_M_E.mkey will be used. acl_file = PA FILENAME Use this file for the ACL list of this database. log_file = _F_I_L_E_N_A_M_E Use this file as the log of changes per- formed to the database. This file is used by iipprrooppdd--mmaasstteerr for propagating changes to slaves. It is also used by kkaaddmmiinndd and kkaaddmmiinn (when used with the -l option), and by all applications using lliibbkkaaddmm55 with the local backend, for two-phase commit functionality. Slaves also use this. Setting this to //ddeevv//nnuullll disables two-phase commit and incremental propagation. Use iipprroopp--lloogg to show the contents of this log file. log-max-size = _n_u_m_b_e_r When the log reaches this size (in bytes), the log will be truncated, sav- ing some entries, and keeping the latest version number so as to not disrupt incremental propagation. If set to a negative value then automatic log trun- cation will be disabled. Defaults to 52428800 (50MB). } max-request = _S_I_Z_E Maximum size of a kdc request. require-preauth = _B_O_O_L If set pre-authentication is required. ports = _l_i_s_t _o_f _p_o_r_t_s List of ports the kdc should listen to. addresses = _l_i_s_t _o_f _i_n_t_e_r_f_a_c_e_s List of addresses the kdc should bind to. enable-http = _B_O_O_L Should the kdc answer kdc-requests over http. tgt-use-strongest-session-key = _B_O_O_L If this is TRUE then the KDC will prefer the strongest key from the client's AS-REQ or TGS-REQ enctype list for the ticket session key that is supported by the KDC and the target principal when the target principal is a krbtgt principal. Else it will prefer the first key from the client's AS- REQ enctype list that is also supported by the KDC and the target principal. Defaults to FALSE. svc-use-strongest-session-key = _B_O_O_L Like tgt-use-strongest-session-key, but applies to the session key enctype of tickets for services other than krbtgt principals. Defaults to FALSE. preauth-use-strongest-session-key = _B_O_O_L If TRUE then select the strongest possible enctype from the client's AS-REQ for PA-ETYPE-INFO2 (i.e., for password-based pre-authentication). Else pick the first supported enctype from the client's AS- REQ. Defaults to FALSE. use-strongest-server-key = _B_O_O_L If TRUE then the KDC picks, for the ticket encrypted part's key, the first supported enctype from the target service principal's hdb entry's current keyset. Else the KDC picks the first sup- ported enctype from the target service principal's hdb entry's current keyset. Defaults to TRUE. check-ticket-addresses = _B_O_O_L Verify the addresses in the tickets used in tgs requests. allow-null-ticket-addresses = _B_O_O_L Allow address-less tickets. allow-anonymous = _B_O_O_L If the kdc is allowed to hand out anonymous tick- ets. encode_as_rep_as_tgs_rep = _B_O_O_L Encode as-rep as tgs-rep tobe compatible with mis- takes older DCE secd did. kdc_warn_pwexpire = _T_I_M_E The time before expiration that the user should be warned that her password is about to expire. logging = _L_o_g_g_i_n_g What type of logging the kdc should use, see also [logging]/kdc. hdb-ldap-structural-object _s_t_r_u_c_t_u_r_a_l _o_b_j_e_c_t If the LDAP backend is used for storing principals, this is the structural object that will be used when creating and when reading objects. The default value is account . hdb-ldap-create-base _c_r_e_a_t_i_o_n _d_n is the dn that will be appended to the principal when creating entries. Default value is the search dn. enable-digest = _B_O_O_L Should the kdc answer digest requests. The default is FALSE. digests_allowed = _l_i_s_t _o_f _d_i_g_e_s_t_s Specifies the digests the kdc will reply to. The default is ntlm-v2. kx509_ca = _f_i_l_e Specifies the PEM credentials for the kx509 certi- fication authority. require_initial_kca_tickets = _b_o_o_l_e_a_n Specified whether to require that tickets for the kca_service service principal be INITIAL. This may be set on a per-realm basis as well as globally. Defaults to true for the global setting. kx509_include_pkinit_san = _b_o_o_l_e_a_n If true then the kx509 client principal's name and realm will be included in an id-pkinit-san certifi- cate extension. This can be set on a per-realm basis as well as globally. Defaults to true for the global setting. kx509_template = _f_i_l_e Specifies the PEM file with a template for the cer- tificates to be issued. The following variables can be interpolated in the subject name using ${variable} syntax: principal-name The full name of the kx509 client prin- cipal. principal-name-without-realm The full name of the kx509 client prin- cipal, excluding the realm name. principal-name-realm The name of the client principal's realm. The kx509, kx509_template, kx509_include_pkinit_san, and require_initial_kca_tickets parameters may be set on a per- realm basis as well. [kadmin] password_lifetime = _t_i_m_e If a principal already have its password set for expiration, this is the time it will be valid for after a change. default_keys = _k_e_y_t_y_p_e_s_._._. For each entry in _d_e_f_a_u_l_t___k_e_y_s try to parse it as a sequence of _e_t_y_p_e_:_s_a_l_t_t_y_p_e_:_s_a_l_t syntax of this if something like: [(des|des3|etype):](pw-salt|afs3-salt)[:string] If _e_t_y_p_e is omitted it means everything, and if string is omitted it means the default salt string (for that principal and encryption type). Addi- tional special values of keytypes are: v5 The Kerberos 5 salt _p_w_-_s_a_l_t default_key_rules = _{ _g_l_o_b_i_n_g_-_r_u_l_e = _k_e_y_t_y_p_e_s_._._. a globbing rule to matching a principal, and when true, use the keytypes as spec- ified the same format as [kad- min]default_keys . } prune-key-history = _B_O_O_L When adding keys to the key history, drop keys that are too old to match unexpired tickets (based on the principal's maximum ticket lifetime). If the KDC keystore is later compromised traffic protected with the discarded older keys may remain protected. This also keeps the HDB records for principals with key history from growing without bound. The default (backwards compatible) value is "false". use_v4_salt = _B_O_O_L When true, this is the same as _d_e_f_a_u_l_t___k_e_y_s _= _d_e_s_3_:_p_w_-_s_a_l_t _v_4 and is only left for backwards compatibility. [password_quality] Check the Password quality assurance in the info documentation for more information. check_library = _l_i_b_r_a_r_y_-_n_a_m_e Library name that contains the password check_function check_function = _f_u_n_c_t_i_o_n_-_n_a_m_e Function name for checking passwords in check_library policy_libraries = _l_i_b_r_a_r_y_1 _._._. _l_i_b_r_a_r_y_N List of libraries that can do password policy checks policies = _p_o_l_i_c_y_1 _._._. _p_o_l_i_c_y_N List of policy names to apply to the password. Builtin policies are among other minimum-length, character-class, external-check. EENNVVIIRROONNMMEENNTT KRB5_CONFIG points to the configuration file to read. FFIILLEESS /etc/krb5.conf configuration file for Kerberos 5. EEXXAAMMPPLLEESS [libdefaults] default_realm = FOO.SE name_canon_rules = as-is:realm=FOO.SE name_canon_rules = qualify:domain=foo.se:realm=FOO.SE name_canon_rules = qualify:domain=bar.se:realm=FOO.SE name_canon_rules = nss [domain_realm] .foo.se = FOO.SE .bar.se = FOO.SE [realms] FOO.SE = { kdc = kerberos.foo.se default_domain = foo.se } [logging] kdc = FILE:/var/heimdal/kdc.log kdc = SYSLOG:INFO default = SYSLOG:INFO:USER [kadmin] default_key_rules = { */ppp@* = arcfour-hmac-md5:pw-salt } DDIIAAGGNNOOSSTTIICCSS Since kkrrbb55..ccoonnff is read and parsed by the krb5 library, there is not a lot of opportunities for programs to report parsing errors in any useful format. To help overcome this problem, there is a program vveerriiffyy__kkrrbb55__ccoonnff that reads kkrrbb55..ccoonnff and tries to emit useful diagnos- tics from parsing errors. Note that this program does not have any way of knowing what options are actually used and thus cannot warn about unknown or misspelled ones. SSEEEE AALLSSOO kinit(1), krb5_openlog(3), strftime(3), verify_krb5_conf(8) HEIMDAL May 4, 2005 HEIMDAL heimdal-7.5.0/lib/krb5/krbhst.c0000644000175000017500000007055313026237312014335 0ustar niknik/* * Copyright (c) 2001 - 2003 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Portions Copyright (c) 2010 Apple Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "krb5_locl.h" #include #include "locate_plugin.h" static int string_to_proto(const char *string) { if(strcasecmp(string, "udp") == 0) return KRB5_KRBHST_UDP; else if(strcasecmp(string, "tcp") == 0) return KRB5_KRBHST_TCP; else if(strcasecmp(string, "http") == 0) return KRB5_KRBHST_HTTP; return -1; } static int is_invalid_tld_srv_target(const char *target) { return (strncmp("your-dns-needs-immediate-attention.", target, 35) == 0 && strchr(&target[35], '.') == NULL); } /* * set `res' and `count' to the result of looking up SRV RR in DNS for * `proto', `proto', `realm' using `dns_type'. * if `port' != 0, force that port number */ static krb5_error_code srv_find_realm(krb5_context context, krb5_krbhst_info ***res, int *count, const char *realm, const char *dns_type, const char *proto, const char *service, int port) { char domain[1024]; struct rk_dns_reply *r; struct rk_resource_record *rr; int num_srv; int proto_num; int def_port; *res = NULL; *count = 0; proto_num = string_to_proto(proto); if(proto_num < 0) { krb5_set_error_message(context, EINVAL, N_("unknown protocol `%s' to lookup", ""), proto); return EINVAL; } if(proto_num == KRB5_KRBHST_HTTP) def_port = ntohs(krb5_getportbyname (context, "http", "tcp", 80)); else if(port == 0) def_port = ntohs(krb5_getportbyname (context, service, proto, 88)); else def_port = port; snprintf(domain, sizeof(domain), "_%s._%s.%s.", service, proto, realm); r = rk_dns_lookup(domain, dns_type); if(r == NULL) { _krb5_debug(context, 0, "DNS lookup failed domain: %s", domain); return KRB5_KDC_UNREACH; } for(num_srv = 0, rr = r->head; rr; rr = rr->next) if(rr->type == rk_ns_t_srv) num_srv++; *res = malloc(num_srv * sizeof(**res)); if(*res == NULL) { rk_dns_free_data(r); return krb5_enomem(context); } rk_dns_srv_order(r); for(num_srv = 0, rr = r->head; rr; rr = rr->next) if(rr->type == rk_ns_t_srv) { krb5_krbhst_info *hi = NULL; size_t len; int invalid_tld = 1; /* Test for top-level domain controlled interruptions */ if (!is_invalid_tld_srv_target(rr->u.srv->target)) { invalid_tld = 0; len = strlen(rr->u.srv->target); hi = calloc(1, sizeof(*hi) + len); } if(hi == NULL) { rk_dns_free_data(r); while(--num_srv >= 0) free((*res)[num_srv]); free(*res); *res = NULL; if (invalid_tld) { krb5_warnx(context, "Domain lookup failed: " "Realm %s needs immediate attention " "see https://icann.org/namecollision", realm); return KRB5_KDC_UNREACH; } return krb5_enomem(context); } (*res)[num_srv++] = hi; hi->proto = proto_num; hi->def_port = def_port; if (port != 0) hi->port = port; else hi->port = rr->u.srv->port; strlcpy(hi->hostname, rr->u.srv->target, len + 1); } *count = num_srv; rk_dns_free_data(r); return 0; } struct krb5_krbhst_data { char *realm; unsigned int flags; int def_port; int port; /* hardwired port number if != 0 */ #define KD_CONFIG 1 #define KD_SRV_UDP 2 #define KD_SRV_TCP 4 #define KD_SRV_HTTP 8 #define KD_FALLBACK 16 #define KD_CONFIG_EXISTS 32 #define KD_LARGE_MSG 64 #define KD_PLUGIN 128 #define KD_HOSTNAMES 256 krb5_error_code (*get_next)(krb5_context, struct krb5_krbhst_data *, krb5_krbhst_info**); char *hostname; unsigned int fallback_count; struct krb5_krbhst_info *hosts, **index, **end; }; static krb5_boolean krbhst_empty(const struct krb5_krbhst_data *kd) { return kd->index == &kd->hosts; } /* * Return the default protocol for the `kd' (either TCP or UDP) */ static int krbhst_get_default_proto(struct krb5_krbhst_data *kd) { if (kd->flags & KD_LARGE_MSG) return KRB5_KRBHST_TCP; return KRB5_KRBHST_UDP; } static int krbhst_get_default_port(struct krb5_krbhst_data *kd) { return kd->def_port; } /* * */ KRB5_LIB_FUNCTION const char * KRB5_LIB_CALL _krb5_krbhst_get_realm(krb5_krbhst_handle handle) { return handle->realm; } /* * parse `spec' into a krb5_krbhst_info, defaulting the port to `def_port' * and forcing it to `port' if port != 0 */ static struct krb5_krbhst_info* parse_hostspec(krb5_context context, struct krb5_krbhst_data *kd, const char *spec, int def_port, int port) { const char *p = spec, *q; struct krb5_krbhst_info *hi; hi = calloc(1, sizeof(*hi) + strlen(spec)); if(hi == NULL) return NULL; hi->proto = krbhst_get_default_proto(kd); if(strncmp(p, "http://", 7) == 0){ hi->proto = KRB5_KRBHST_HTTP; p += 7; } else if(strncmp(p, "http/", 5) == 0) { hi->proto = KRB5_KRBHST_HTTP; p += 5; def_port = ntohs(krb5_getportbyname (context, "http", "tcp", 80)); }else if(strncmp(p, "tcp/", 4) == 0){ hi->proto = KRB5_KRBHST_TCP; p += 4; } else if(strncmp(p, "udp/", 4) == 0) { hi->proto = KRB5_KRBHST_UDP; p += 4; } if (p[0] == '[' && (q = strchr(p, ']')) != NULL) { /* if address looks like [foo:bar] or [foo:bar]: its a ipv6 adress, strip of [] */ memcpy(hi->hostname, &p[1], q - p - 1); hi->hostname[q - p - 1] = '\0'; p = q + 1; /* get trailing : */ if (p[0] == ':') p++; } else if(strsep_copy(&p, ":", hi->hostname, strlen(spec) + 1) < 0) { /* copy everything before : */ free(hi); return NULL; } /* get rid of trailing /, and convert to lower case */ hi->hostname[strcspn(hi->hostname, "/")] = '\0'; strlwr(hi->hostname); hi->port = hi->def_port = def_port; if(p != NULL && p[0]) { char *end; hi->port = strtol(p, &end, 0); if(end == p) { free(hi); return NULL; } } if (port) hi->port = port; return hi; } KRB5_LIB_FUNCTION void KRB5_LIB_CALL _krb5_free_krbhst_info(krb5_krbhst_info *hi) { if (hi->ai != NULL) freeaddrinfo(hi->ai); free(hi); } KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL _krb5_krbhost_info_move(krb5_context context, krb5_krbhst_info *from, krb5_krbhst_info **to) { size_t hostnamelen = strlen(from->hostname); /* trailing NUL is included in structure */ *to = calloc(1, sizeof(**to) + hostnamelen); if (*to == NULL) return krb5_enomem(context); (*to)->proto = from->proto; (*to)->port = from->port; (*to)->def_port = from->def_port; (*to)->ai = from->ai; from->ai = NULL; (*to)->next = NULL; memcpy((*to)->hostname, from->hostname, hostnamelen + 1); return 0; } static void append_host_hostinfo(struct krb5_krbhst_data *kd, struct krb5_krbhst_info *host) { struct krb5_krbhst_info *h; for(h = kd->hosts; h; h = h->next) if(h->proto == host->proto && h->port == host->port && strcmp(h->hostname, host->hostname) == 0) { _krb5_free_krbhst_info(host); return; } *kd->end = host; kd->end = &host->next; } static krb5_error_code append_host_string(krb5_context context, struct krb5_krbhst_data *kd, const char *host, int def_port, int port) { struct krb5_krbhst_info *hi; hi = parse_hostspec(context, kd, host, def_port, port); if(hi == NULL) return krb5_enomem(context); append_host_hostinfo(kd, hi); return 0; } /* * return a readable representation of `host' in `hostname, hostlen' */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_krbhst_format_string(krb5_context context, const krb5_krbhst_info *host, char *hostname, size_t hostlen) { const char *proto = ""; char portstr[7] = ""; if(host->proto == KRB5_KRBHST_TCP) proto = "tcp/"; else if(host->proto == KRB5_KRBHST_HTTP) proto = "http://"; if(host->port != host->def_port) snprintf(portstr, sizeof(portstr), ":%d", host->port); snprintf(hostname, hostlen, "%s%s%s", proto, host->hostname, portstr); return 0; } /* * create a getaddrinfo `hints' based on `proto' */ static void make_hints(struct addrinfo *hints, int proto) { memset(hints, 0, sizeof(*hints)); hints->ai_family = AF_UNSPEC; switch(proto) { case KRB5_KRBHST_UDP : hints->ai_socktype = SOCK_DGRAM; break; case KRB5_KRBHST_HTTP : case KRB5_KRBHST_TCP : hints->ai_socktype = SOCK_STREAM; break; } } /** * Return an `struct addrinfo *' for a KDC host. * * Returns an the struct addrinfo in in that corresponds to the * information in `host'. free:ing is handled by krb5_krbhst_free, so * the returned ai must not be released. * * @ingroup krb5 */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_krbhst_get_addrinfo(krb5_context context, krb5_krbhst_info *host, struct addrinfo **ai) { int ret = 0; if (host->ai == NULL) { struct addrinfo hints; char portstr[NI_MAXSERV]; snprintf (portstr, sizeof(portstr), "%d", host->port); make_hints(&hints, host->proto); ret = getaddrinfo(host->hostname, portstr, &hints, &host->ai); if (ret) { ret = krb5_eai_to_heim_errno(ret, errno); goto out; } } out: *ai = host->ai; return ret; } static krb5_boolean get_next(struct krb5_krbhst_data *kd, krb5_krbhst_info **host) { struct krb5_krbhst_info *hi = *kd->index; if(hi != NULL) { *host = hi; kd->index = &(*kd->index)->next; return TRUE; } return FALSE; } static void srv_get_hosts(krb5_context context, struct krb5_krbhst_data *kd, const char *proto, const char *service) { krb5_error_code ret; krb5_krbhst_info **res; int count, i; if (krb5_realm_is_lkdc(kd->realm)) return; ret = srv_find_realm(context, &res, &count, kd->realm, "SRV", proto, service, kd->port); _krb5_debug(context, 2, "searching DNS for realm %s %s.%s -> %d", kd->realm, proto, service, ret); if (ret) return; for(i = 0; i < count; i++) append_host_hostinfo(kd, res[i]); free(res); } /* * read the configuration for `conf_string', defaulting to kd->def_port and * forcing it to `kd->port' if kd->port != 0 */ static void config_get_hosts(krb5_context context, struct krb5_krbhst_data *kd, const char *conf_string) { int i; char **hostlist; hostlist = krb5_config_get_strings(context, NULL, "realms", kd->realm, conf_string, NULL); _krb5_debug(context, 2, "configuration file for realm %s%s found", kd->realm, hostlist ? "" : " not"); if(hostlist == NULL) return; kd->flags |= KD_CONFIG_EXISTS; for(i = 0; hostlist && hostlist[i] != NULL; i++) append_host_string(context, kd, hostlist[i], kd->def_port, kd->port); krb5_config_free_strings(hostlist); } /* * as a fallback, look for `serv_string.kd->realm' (typically * kerberos.REALM, kerberos-1.REALM, ... * `port' is the default port for the service, and `proto' the * protocol */ static krb5_error_code fallback_get_hosts(krb5_context context, struct krb5_krbhst_data *kd, const char *serv_string, int port, int proto) { char *host = NULL; int ret; struct addrinfo *ai; struct addrinfo hints; char portstr[NI_MAXSERV]; ret = krb5_config_get_bool_default(context, NULL, KRB5_FALLBACK_DEFAULT, "libdefaults", "use_fallback", NULL); if (!ret) { kd->flags |= KD_FALLBACK; return 0; } _krb5_debug(context, 2, "fallback lookup %d for realm %s (service %s)", kd->fallback_count, kd->realm, serv_string); /* * Don't try forever in case the DNS server keep returning us * entries (like wildcard entries or the .nu TLD) * * Also don't try LKDC realms since fallback wont work on them at all. */ if(kd->fallback_count >= 5 || krb5_realm_is_lkdc(kd->realm)) { kd->flags |= KD_FALLBACK; return 0; } if(kd->fallback_count == 0) ret = asprintf(&host, "%s.%s.", serv_string, kd->realm); else ret = asprintf(&host, "%s-%d.%s.", serv_string, kd->fallback_count, kd->realm); if (ret < 0 || host == NULL) return krb5_enomem(context); make_hints(&hints, proto); snprintf(portstr, sizeof(portstr), "%d", port); ret = getaddrinfo(host, portstr, &hints, &ai); if (ret) { /* no more hosts, so we're done here */ free(host); kd->flags |= KD_FALLBACK; } else { struct krb5_krbhst_info *hi; size_t hostlen; /* Check for ICANN gTLD Name Collision address (127.0.53.53) */ if (ai->ai_family == AF_INET) { struct sockaddr_in *sin = (struct sockaddr_in *)ai->ai_addr; if (sin->sin_addr.s_addr == htonl(0x7f003535)) { krb5_warnx(context, "Fallback lookup failed: " "Realm %s needs immediate attention " "see https://icann.org/namecollision", kd->realm); return KRB5_KDC_UNREACH; } } hostlen = strlen(host); hi = calloc(1, sizeof(*hi) + hostlen); if(hi == NULL) { free(host); return krb5_enomem(context); } hi->proto = proto; hi->port = hi->def_port = port; hi->ai = ai; memmove(hi->hostname, host, hostlen); hi->hostname[hostlen] = '\0'; free(host); append_host_hostinfo(kd, hi); kd->fallback_count++; } return 0; } /* * Fetch hosts from plugin */ static krb5_error_code add_plugin_host(struct krb5_krbhst_data *kd, const char *host, const char *port, int portnum, int proto) { struct krb5_krbhst_info *hi; struct addrinfo hints, *ai; size_t hostlen; int ret; make_hints(&hints, proto); ret = getaddrinfo(host, port, &hints, &ai); if (ret) return 0; hostlen = strlen(host); hi = calloc(1, sizeof(*hi) + hostlen); if (hi == NULL) { freeaddrinfo(ai); return ENOMEM; } hi->proto = proto; hi->port = hi->def_port = portnum; hi->ai = ai; memmove(hi->hostname, host, hostlen); hi->hostname[hostlen] = '\0'; append_host_hostinfo(kd, hi); return 0; } static krb5_error_code add_locate(void *ctx, int type, struct sockaddr *addr) { struct krb5_krbhst_data *kd = ctx; char host[NI_MAXHOST], port[NI_MAXSERV]; socklen_t socklen; krb5_error_code ret; int proto, portnum; socklen = socket_sockaddr_size(addr); portnum = socket_get_port(addr); ret = getnameinfo(addr, socklen, host, sizeof(host), port, sizeof(port), NI_NUMERICHOST|NI_NUMERICSERV); if (ret != 0) return 0; if (kd->port) snprintf(port, sizeof(port), "%d", kd->port); else if (atoi(port) == 0) snprintf(port, sizeof(port), "%d", krbhst_get_default_port(kd)); proto = krbhst_get_default_proto(kd); ret = add_plugin_host(kd, host, port, portnum, proto); if (ret) return ret; /* * This is really kind of broken and should be solved a different * way, some sites block UDP, and we don't, in the general case, * fall back to TCP, that should also be done. But since that * should require us to invert the whole "find kdc" stack, let put * this in for now. */ if (proto == KRB5_KRBHST_UDP) { ret = add_plugin_host(kd, host, port, portnum, KRB5_KRBHST_TCP); if (ret) return ret; } return 0; } struct plctx { enum locate_service_type type; struct krb5_krbhst_data *kd; unsigned long flags; }; static KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL plcallback(krb5_context context, const void *plug, void *plugctx, void *userctx) { const krb5plugin_service_locate_ftable *locate = plug; struct plctx *plctx = userctx; if (locate->minor_version >= KRB5_PLUGIN_LOCATE_VERSION_2) return locate->lookup(plugctx, plctx->flags, plctx->type, plctx->kd->realm, 0, 0, add_locate, plctx->kd); if (plctx->flags & KRB5_PLF_ALLOW_HOMEDIR) return locate->old_lookup(plugctx, plctx->type, plctx->kd->realm, 0, 0, add_locate, plctx->kd); return KRB5_PLUGIN_NO_HANDLE; } static void plugin_get_hosts(krb5_context context, struct krb5_krbhst_data *kd, enum locate_service_type type) { struct plctx ctx = { type, kd, 0 }; if (_krb5_homedir_access(context)) ctx.flags |= KRB5_PLF_ALLOW_HOMEDIR; _krb5_plugin_run_f(context, "krb5", KRB5_PLUGIN_LOCATE, KRB5_PLUGIN_LOCATE_VERSION_0, 0, &ctx, plcallback); } /* * */ static void hostnames_get_hosts(krb5_context context, struct krb5_krbhst_data *kd, const char *type) { kd->flags |= KD_HOSTNAMES; if (kd->hostname) append_host_string(context, kd, kd->hostname, kd->def_port, kd->port); } /* * */ static krb5_error_code kdc_get_next(krb5_context context, struct krb5_krbhst_data *kd, krb5_krbhst_info **host) { krb5_error_code ret; if ((kd->flags & KD_HOSTNAMES) == 0) { hostnames_get_hosts(context, kd, "kdc"); if(get_next(kd, host)) return 0; } if ((kd->flags & KD_PLUGIN) == 0) { plugin_get_hosts(context, kd, locate_service_kdc); kd->flags |= KD_PLUGIN; if(get_next(kd, host)) return 0; } if((kd->flags & KD_CONFIG) == 0) { config_get_hosts(context, kd, "kdc"); kd->flags |= KD_CONFIG; if(get_next(kd, host)) return 0; } if (kd->flags & KD_CONFIG_EXISTS) { _krb5_debug(context, 1, "Configuration exists for realm %s, wont go to DNS", kd->realm); return KRB5_KDC_UNREACH; } if(context->srv_lookup) { if((kd->flags & KD_SRV_UDP) == 0 && (kd->flags & KD_LARGE_MSG) == 0) { srv_get_hosts(context, kd, "udp", "kerberos"); kd->flags |= KD_SRV_UDP; if(get_next(kd, host)) return 0; } if((kd->flags & KD_SRV_TCP) == 0) { srv_get_hosts(context, kd, "tcp", "kerberos"); kd->flags |= KD_SRV_TCP; if(get_next(kd, host)) return 0; } if((kd->flags & KD_SRV_HTTP) == 0) { srv_get_hosts(context, kd, "http", "kerberos"); kd->flags |= KD_SRV_HTTP; if(get_next(kd, host)) return 0; } } while((kd->flags & KD_FALLBACK) == 0) { ret = fallback_get_hosts(context, kd, "kerberos", kd->def_port, krbhst_get_default_proto(kd)); if(ret) return ret; if(get_next(kd, host)) return 0; } _krb5_debug(context, 0, "No KDC entries found for %s", kd->realm); return KRB5_KDC_UNREACH; /* XXX */ } static krb5_error_code admin_get_next(krb5_context context, struct krb5_krbhst_data *kd, krb5_krbhst_info **host) { krb5_error_code ret; if ((kd->flags & KD_PLUGIN) == 0) { plugin_get_hosts(context, kd, locate_service_kadmin); kd->flags |= KD_PLUGIN; if(get_next(kd, host)) return 0; } if((kd->flags & KD_CONFIG) == 0) { config_get_hosts(context, kd, "admin_server"); kd->flags |= KD_CONFIG; if(get_next(kd, host)) return 0; } if (kd->flags & KD_CONFIG_EXISTS) { _krb5_debug(context, 1, "Configuration exists for realm %s, wont go to DNS", kd->realm); return KRB5_KDC_UNREACH; } if(context->srv_lookup) { if((kd->flags & KD_SRV_TCP) == 0) { srv_get_hosts(context, kd, "tcp", "kerberos-adm"); kd->flags |= KD_SRV_TCP; if(get_next(kd, host)) return 0; } } if (krbhst_empty(kd) && (kd->flags & KD_FALLBACK) == 0) { ret = fallback_get_hosts(context, kd, "kerberos", kd->def_port, krbhst_get_default_proto(kd)); if(ret) return ret; kd->flags |= KD_FALLBACK; if(get_next(kd, host)) return 0; } _krb5_debug(context, 0, "No admin entries found for realm %s", kd->realm); return KRB5_KDC_UNREACH; /* XXX */ } static krb5_error_code kpasswd_get_next(krb5_context context, struct krb5_krbhst_data *kd, krb5_krbhst_info **host) { krb5_error_code ret; if ((kd->flags & KD_PLUGIN) == 0) { plugin_get_hosts(context, kd, locate_service_kpasswd); kd->flags |= KD_PLUGIN; if(get_next(kd, host)) return 0; } if((kd->flags & KD_CONFIG) == 0) { config_get_hosts(context, kd, "kpasswd_server"); kd->flags |= KD_CONFIG; if(get_next(kd, host)) return 0; } if (kd->flags & KD_CONFIG_EXISTS) { _krb5_debug(context, 1, "Configuration exists for realm %s, wont go to DNS", kd->realm); return KRB5_KDC_UNREACH; } if(context->srv_lookup) { if((kd->flags & KD_SRV_UDP) == 0) { srv_get_hosts(context, kd, "udp", "kpasswd"); kd->flags |= KD_SRV_UDP; if(get_next(kd, host)) return 0; } if((kd->flags & KD_SRV_TCP) == 0) { srv_get_hosts(context, kd, "tcp", "kpasswd"); kd->flags |= KD_SRV_TCP; if(get_next(kd, host)) return 0; } } /* no matches -> try admin */ if (krbhst_empty(kd)) { kd->flags = 0; kd->port = kd->def_port; kd->get_next = admin_get_next; ret = (*kd->get_next)(context, kd, host); if (ret == 0) (*host)->proto = krbhst_get_default_proto(kd); return ret; } _krb5_debug(context, 0, "No kpasswd entries found for realm %s", kd->realm); return KRB5_KDC_UNREACH; } static void krbhost_dealloc(void *ptr) { struct krb5_krbhst_data *handle = (struct krb5_krbhst_data *)ptr; krb5_krbhst_info *h, *next; for (h = handle->hosts; h != NULL; h = next) { next = h->next; _krb5_free_krbhst_info(h); } if (handle->hostname) free(handle->hostname); free(handle->realm); } static struct krb5_krbhst_data* common_init(krb5_context context, const char *service, const char *realm, int flags) { struct krb5_krbhst_data *kd; if ((kd = heim_alloc(sizeof(*kd), "krbhst-context", krbhost_dealloc)) == NULL) return NULL; if((kd->realm = strdup(realm)) == NULL) { heim_release(kd); return NULL; } _krb5_debug(context, 2, "Trying to find service %s for realm %s flags %x", service, realm, flags); /* For 'realms' without a . do not even think of going to DNS */ if (!strchr(realm, '.')) kd->flags |= KD_CONFIG_EXISTS; if (flags & KRB5_KRBHST_FLAGS_LARGE_MSG) kd->flags |= KD_LARGE_MSG; kd->end = kd->index = &kd->hosts; return kd; } /* * initialize `handle' to look for hosts of type `type' in realm `realm' */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_krbhst_init(krb5_context context, const char *realm, unsigned int type, krb5_krbhst_handle *handle) { return krb5_krbhst_init_flags(context, realm, type, 0, handle); } KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_krbhst_init_flags(krb5_context context, const char *realm, unsigned int type, int flags, krb5_krbhst_handle *handle) { struct krb5_krbhst_data *kd; krb5_error_code (*next)(krb5_context, struct krb5_krbhst_data *, krb5_krbhst_info **); int def_port; const char *service; *handle = NULL; switch(type) { case KRB5_KRBHST_KDC: next = kdc_get_next; def_port = ntohs(krb5_getportbyname (context, "kerberos", "udp", 88)); service = "kdc"; break; case KRB5_KRBHST_ADMIN: next = admin_get_next; def_port = ntohs(krb5_getportbyname (context, "kerberos-adm", "tcp", 749)); service = "admin"; break; case KRB5_KRBHST_CHANGEPW: next = kpasswd_get_next; def_port = ntohs(krb5_getportbyname (context, "kpasswd", "udp", KPASSWD_PORT)); service = "change_password"; break; default: krb5_set_error_message(context, ENOTTY, N_("unknown krbhst type (%u)", ""), type); return ENOTTY; } if((kd = common_init(context, service, realm, flags)) == NULL) return ENOMEM; kd->get_next = next; kd->def_port = def_port; *handle = kd; return 0; } /* * return the next host information from `handle' in `host' */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_krbhst_next(krb5_context context, krb5_krbhst_handle handle, krb5_krbhst_info **host) { if(get_next(handle, host)) return 0; return (*handle->get_next)(context, handle, host); } /* * return the next host information from `handle' as a host name * in `hostname' (or length `hostlen) */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_krbhst_next_as_string(krb5_context context, krb5_krbhst_handle handle, char *hostname, size_t hostlen) { krb5_error_code ret; krb5_krbhst_info *host; ret = krb5_krbhst_next(context, handle, &host); if(ret) return ret; return krb5_krbhst_format_string(context, host, hostname, hostlen); } /* * */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_krbhst_set_hostname(krb5_context context, krb5_krbhst_handle handle, const char *hostname) { if (handle->hostname) free(handle->hostname); handle->hostname = strdup(hostname); if (handle->hostname == NULL) return ENOMEM; return 0; } KRB5_LIB_FUNCTION void KRB5_LIB_CALL krb5_krbhst_reset(krb5_context context, krb5_krbhst_handle handle) { handle->index = &handle->hosts; } KRB5_LIB_FUNCTION void KRB5_LIB_CALL krb5_krbhst_free(krb5_context context, krb5_krbhst_handle handle) { heim_release(handle); } #ifndef HEIMDAL_SMALLER /* backwards compatibility ahead */ static krb5_error_code gethostlist(krb5_context context, const char *realm, unsigned int type, char ***hostlist) { krb5_error_code ret; int nhost = 0; krb5_krbhst_handle handle; char host[MAXHOSTNAMELEN]; krb5_krbhst_info *hostinfo; ret = krb5_krbhst_init(context, realm, type, &handle); if (ret) return ret; while(krb5_krbhst_next(context, handle, &hostinfo) == 0) nhost++; if(nhost == 0) { krb5_set_error_message(context, KRB5_KDC_UNREACH, N_("No KDC found for realm %s", ""), realm); return KRB5_KDC_UNREACH; } *hostlist = calloc(nhost + 1, sizeof(**hostlist)); if(*hostlist == NULL) { krb5_krbhst_free(context, handle); return krb5_enomem(context); } krb5_krbhst_reset(context, handle); nhost = 0; while(krb5_krbhst_next_as_string(context, handle, host, sizeof(host)) == 0) { if(((*hostlist)[nhost++] = strdup(host)) == NULL) { krb5_free_krbhst(context, *hostlist); krb5_krbhst_free(context, handle); return krb5_enomem(context); } } (*hostlist)[nhost] = NULL; krb5_krbhst_free(context, handle); return 0; } /* * return an malloced list of kadmin-hosts for `realm' in `hostlist' */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_get_krb_admin_hst (krb5_context context, const krb5_realm *realm, char ***hostlist) { return gethostlist(context, *realm, KRB5_KRBHST_ADMIN, hostlist); } /* * return an malloced list of changepw-hosts for `realm' in `hostlist' */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_get_krb_changepw_hst (krb5_context context, const krb5_realm *realm, char ***hostlist) { return gethostlist(context, *realm, KRB5_KRBHST_CHANGEPW, hostlist); } /* * return an malloced list of 524-hosts for `realm' in `hostlist' */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_get_krb524hst (krb5_context context, const krb5_realm *realm, char ***hostlist) { return gethostlist(context, *realm, KRB5_KRBHST_KRB524, hostlist); } /* * return an malloced list of KDC's for `realm' in `hostlist' */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_get_krbhst (krb5_context context, const krb5_realm *realm, char ***hostlist) { return gethostlist(context, *realm, KRB5_KRBHST_KDC, hostlist); } /* * free all the memory allocated in `hostlist' */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_free_krbhst (krb5_context context, char **hostlist) { char **p; for (p = hostlist; *p; ++p) free (*p); free (hostlist); return 0; } #endif /* HEIMDAL_SMALLER */ heimdal-7.5.0/lib/krb5/deprecated.c0000644000175000017500000004405213212137553015136 0ustar niknik/* * Copyright (c) 1997 - 2009 Kungliga Tekniska Hgskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #ifdef __GNUC__ /* For some GCCs there's no way to shut them up about deprecated functions */ #define KRB5_DEPRECATED_FUNCTION(x) #endif #include "krb5_locl.h" #undef __attribute__ #define __attribute__(x) #ifndef HEIMDAL_SMALLER /** * Same as krb5_data_free(). MIT compat. * * Deprecated: use krb5_data_free(). * * @param context Kerberos 5 context. * @param data krb5_data to free. * * @ingroup krb5_deprecated */ KRB5_LIB_FUNCTION void KRB5_LIB_CALL krb5_free_data_contents(krb5_context context, krb5_data *data) KRB5_DEPRECATED_FUNCTION("Use X instead") { krb5_data_free(data); } /** * Deprecated: keytypes doesn't exists, they are really enctypes. * * @ingroup krb5_deprecated */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_keytype_to_enctypes_default (krb5_context context, krb5_keytype keytype, unsigned *len, krb5_enctype **val) KRB5_DEPRECATED_FUNCTION("Use X instead") { unsigned int i, n; krb5_enctype *ret; if (keytype != (krb5_keytype)KEYTYPE_DES || context->etypes_des == NULL) return krb5_keytype_to_enctypes (context, keytype, len, val); for (n = 0; context->etypes_des[n]; ++n) ; ret = malloc (n * sizeof(*ret)); if (ret == NULL && n != 0) return krb5_enomem(context); for (i = 0; i < n; ++i) ret[i] = context->etypes_des[i]; *len = n; *val = ret; return 0; } static struct { const char *name; krb5_keytype type; } keys[] = { { "null", KRB5_ENCTYPE_NULL }, { "des", KRB5_ENCTYPE_DES_CBC_CRC }, { "des3", KRB5_ENCTYPE_OLD_DES3_CBC_SHA1 }, { "aes-128", KRB5_ENCTYPE_AES128_CTS_HMAC_SHA1_96 }, { "aes-256", KRB5_ENCTYPE_AES256_CTS_HMAC_SHA1_96 }, { "arcfour", KRB5_ENCTYPE_ARCFOUR_HMAC_MD5 }, { "arcfour-56", KRB5_ENCTYPE_ARCFOUR_HMAC_MD5_56 } }; static int num_keys = sizeof(keys) / sizeof(keys[0]); /** * Deprecated: keytypes doesn't exists, they are really enctypes in * most cases, use krb5_enctype_to_string(). * * @ingroup krb5_deprecated */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_keytype_to_string(krb5_context context, krb5_keytype keytype, char **string) KRB5_DEPRECATED_FUNCTION("Use X instead") { const char *name = NULL; int i; for(i = 0; i < num_keys; i++) { if(keys[i].type == keytype) { name = keys[i].name; break; } } if(i >= num_keys) { krb5_set_error_message(context, KRB5_PROG_KEYTYPE_NOSUPP, "key type %d not supported", keytype); return KRB5_PROG_KEYTYPE_NOSUPP; } *string = strdup(name); if (*string == NULL) return krb5_enomem(context); return 0; } /** * Deprecated: keytypes doesn't exists, they are really enctypes in * most cases, use krb5_string_to_enctype(). * * @ingroup krb5_deprecated */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_string_to_keytype(krb5_context context, const char *string, krb5_keytype *keytype) KRB5_DEPRECATED_FUNCTION("Use X instead") { char *end; int i; for(i = 0; i < num_keys; i++) if(strcasecmp(keys[i].name, string) == 0){ *keytype = keys[i].type; return 0; } /* check if the enctype is a number */ *keytype = strtol(string, &end, 0); if(*end == '\0' && *keytype != 0) { if (krb5_enctype_valid(context, *keytype) == 0) return 0; } krb5_set_error_message(context, KRB5_PROG_KEYTYPE_NOSUPP, "key type %s not supported", string); return KRB5_PROG_KEYTYPE_NOSUPP; } /** * Deprecated: use krb5_get_init_creds() and friends. * * @ingroup krb5_deprecated */ KRB5_LIB_FUNCTION krb5_error_code KRB5_CALLCONV krb5_password_key_proc (krb5_context context, krb5_enctype type, krb5_salt salt, krb5_const_pointer keyseed, krb5_keyblock **key) KRB5_DEPRECATED_FUNCTION("Use X instead") { krb5_error_code ret; const char *password = (const char *)keyseed; char buf[BUFSIZ]; *key = malloc (sizeof (**key)); if (*key == NULL) return krb5_enomem(context); if (password == NULL) { if(UI_UTIL_read_pw_string (buf, sizeof(buf), "Password: ", 0)) { free (*key); krb5_clear_error_message(context); return KRB5_LIBOS_PWDINTR; } password = buf; } ret = krb5_string_to_key_salt (context, type, password, salt, *key); memset (buf, 0, sizeof(buf)); return ret; } /** * Deprecated: use krb5_get_init_creds() and friends. * * @ingroup krb5_deprecated */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_get_in_tkt_with_password (krb5_context context, krb5_flags options, krb5_addresses *addrs, const krb5_enctype *etypes, const krb5_preauthtype *pre_auth_types, const char *password, krb5_ccache ccache, krb5_creds *creds, krb5_kdc_rep *ret_as_reply) KRB5_DEPRECATED_FUNCTION("Use X instead") { return krb5_get_in_tkt (context, options, addrs, etypes, pre_auth_types, krb5_password_key_proc, password, NULL, NULL, creds, ccache, ret_as_reply); } static krb5_error_code KRB5_CALLCONV krb5_skey_key_proc (krb5_context context, krb5_enctype type, krb5_salt salt, krb5_const_pointer keyseed, krb5_keyblock **key) { return krb5_copy_keyblock (context, keyseed, key); } /** * Deprecated: use krb5_get_init_creds() and friends. * * @ingroup krb5_deprecated */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_get_in_tkt_with_skey (krb5_context context, krb5_flags options, krb5_addresses *addrs, const krb5_enctype *etypes, const krb5_preauthtype *pre_auth_types, const krb5_keyblock *key, krb5_ccache ccache, krb5_creds *creds, krb5_kdc_rep *ret_as_reply) KRB5_DEPRECATED_FUNCTION("Use X instead") { if(key == NULL) return krb5_get_in_tkt_with_keytab (context, options, addrs, etypes, pre_auth_types, NULL, ccache, creds, ret_as_reply); else return krb5_get_in_tkt (context, options, addrs, etypes, pre_auth_types, krb5_skey_key_proc, key, NULL, NULL, creds, ccache, ret_as_reply); } /** * Deprecated: use krb5_get_init_creds() and friends. * * @ingroup krb5_deprecated */ KRB5_LIB_FUNCTION krb5_error_code KRB5_CALLCONV krb5_keytab_key_proc (krb5_context context, krb5_enctype enctype, krb5_salt salt, krb5_const_pointer keyseed, krb5_keyblock **key) KRB5_DEPRECATED_FUNCTION("Use X instead") { krb5_keytab_key_proc_args *args = rk_UNCONST(keyseed); krb5_keytab keytab = args->keytab; krb5_principal principal = args->principal; krb5_error_code ret; krb5_keytab real_keytab; krb5_keytab_entry entry; if(keytab == NULL) krb5_kt_default(context, &real_keytab); else real_keytab = keytab; ret = krb5_kt_get_entry (context, real_keytab, principal, 0, enctype, &entry); if (keytab == NULL) krb5_kt_close (context, real_keytab); if (ret) return ret; ret = krb5_copy_keyblock (context, &entry.keyblock, key); krb5_kt_free_entry(context, &entry); return ret; } /** * Deprecated: use krb5_get_init_creds() and friends. * * @ingroup krb5_deprecated */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_get_in_tkt_with_keytab (krb5_context context, krb5_flags options, krb5_addresses *addrs, const krb5_enctype *etypes, const krb5_preauthtype *pre_auth_types, krb5_keytab keytab, krb5_ccache ccache, krb5_creds *creds, krb5_kdc_rep *ret_as_reply) KRB5_DEPRECATED_FUNCTION("Use X instead") { krb5_keytab_key_proc_args a; a.principal = creds->client; a.keytab = keytab; return krb5_get_in_tkt (context, options, addrs, etypes, pre_auth_types, krb5_keytab_key_proc, &a, NULL, NULL, creds, ccache, ret_as_reply); } /** * Generate a new ccache of type `ops' in `id'. * * Deprecated: use krb5_cc_new_unique() instead. * * @return Return an error code or 0, see krb5_get_error_message(). * * @ingroup krb5_ccache */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_cc_gen_new(krb5_context context, const krb5_cc_ops *ops, krb5_ccache *id) KRB5_DEPRECATED_FUNCTION("Use X instead") { return krb5_cc_new_unique(context, ops->prefix, NULL, id); } /** * Deprecated: use krb5_principal_get_realm() * * @ingroup krb5_deprecated */ KRB5_LIB_FUNCTION krb5_realm * KRB5_LIB_CALL krb5_princ_realm(krb5_context context, krb5_principal principal) KRB5_DEPRECATED_FUNCTION("Use X instead") { return &principal->realm; } /** * Deprecated: use krb5_principal_set_realm() * * @ingroup krb5_deprecated */ KRB5_LIB_FUNCTION void KRB5_LIB_CALL krb5_princ_set_realm(krb5_context context, krb5_principal principal, krb5_realm *realm) KRB5_DEPRECATED_FUNCTION("Use X instead") { principal->realm = *realm; } /** * Deprecated: use krb5_free_cred_contents() * * @ingroup krb5_deprecated */ /* keep this for compatibility with older code */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_free_creds_contents (krb5_context context, krb5_creds *c) KRB5_DEPRECATED_FUNCTION("Use X instead") { return krb5_free_cred_contents (context, c); } /** * Free the error message returned by krb5_get_error_string(). * * Deprecated: use krb5_free_error_message() * * @param context Kerberos context * @param str error message to free * * @ingroup krb5_deprecated */ KRB5_LIB_FUNCTION void KRB5_LIB_CALL krb5_free_error_string(krb5_context context, char *str) KRB5_DEPRECATED_FUNCTION("Use X instead") { krb5_free_error_message(context, str); } /** * Set the error message returned by krb5_get_error_string(). * * Deprecated: use krb5_get_error_message() * * @param context Kerberos context * @param fmt error message to free * * @return Return an error code or 0. * * @ingroup krb5_deprecated */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_set_error_string(krb5_context context, const char *fmt, ...) __attribute__ ((__format__ (__printf__, 2, 3))) KRB5_DEPRECATED_FUNCTION("Use X instead") { va_list ap; va_start(ap, fmt); krb5_vset_error_message (context, 0, fmt, ap); va_end(ap); return 0; } /** * Set the error message returned by krb5_get_error_string(), * deprecated, use krb5_set_error_message(). * * Deprecated: use krb5_vset_error_message() * * @param context Kerberos context * @param fmt error message to free * @param args variable argument list vector * * @return Return an error code or 0. * * @ingroup krb5_deprecated */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_vset_error_string(krb5_context context, const char *fmt, va_list args) __attribute__ ((__format__ (__printf__, 2, 0))) KRB5_DEPRECATED_FUNCTION("Use X instead") { krb5_vset_error_message(context, 0, fmt, args); return 0; } /** * Clear the error message returned by krb5_get_error_string(). * * Deprecated: use krb5_clear_error_message() * * @param context Kerberos context * * @ingroup krb5_deprecated */ KRB5_LIB_FUNCTION void KRB5_LIB_CALL krb5_clear_error_string(krb5_context context) KRB5_DEPRECATED_FUNCTION("Use X instead") { krb5_clear_error_message(context); } /** * Deprecated: use krb5_get_credentials_with_flags(). * * @ingroup krb5_deprecated */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_get_cred_from_kdc_opt(krb5_context context, krb5_ccache ccache, krb5_creds *in_creds, krb5_creds **out_creds, krb5_creds ***ret_tgts, krb5_flags flags) KRB5_DEPRECATED_FUNCTION("Use X instead") { krb5_kdc_flags f; f.i = flags; return _krb5_get_cred_kdc_any(context, f, ccache, in_creds, NULL, NULL, out_creds, ret_tgts); } /** * Deprecated: use krb5_get_credentials_with_flags(). * * @ingroup krb5_deprecated */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_get_cred_from_kdc(krb5_context context, krb5_ccache ccache, krb5_creds *in_creds, krb5_creds **out_creds, krb5_creds ***ret_tgts) KRB5_DEPRECATED_FUNCTION("Use X instead") { return krb5_get_cred_from_kdc_opt(context, ccache, in_creds, out_creds, ret_tgts, 0); } /** * Deprecated: use krb5_xfree(). * * @ingroup krb5_deprecated */ KRB5_LIB_FUNCTION void KRB5_LIB_CALL krb5_free_unparsed_name(krb5_context context, char *str) KRB5_DEPRECATED_FUNCTION("Use X instead") { krb5_xfree(str); } /** * Deprecated: use krb5_generate_subkey_extended() * * @ingroup krb5_deprecated */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_generate_subkey(krb5_context context, const krb5_keyblock *key, krb5_keyblock **subkey) KRB5_DEPRECATED_FUNCTION("Use X instead") { return krb5_generate_subkey_extended(context, key, ETYPE_NULL, subkey); } /** * Deprecated: use krb5_auth_con_getremoteseqnumber() * * @ingroup krb5_deprecated */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_auth_getremoteseqnumber(krb5_context context, krb5_auth_context auth_context, int32_t *seqnumber) KRB5_DEPRECATED_FUNCTION("Use X instead") { *seqnumber = auth_context->remote_seqnumber; return 0; } /** * Return the error message in context. On error or no error string, * the function returns NULL. * * @param context Kerberos 5 context * * @return an error string, needs to be freed with * krb5_free_error_message(). The functions return NULL on error. * * @ingroup krb5_error */ KRB5_LIB_FUNCTION char * KRB5_LIB_CALL krb5_get_error_string(krb5_context context) KRB5_DEPRECATED_FUNCTION("Use krb5_get_error_message instead") { char *ret = NULL; HEIMDAL_MUTEX_lock(&context->mutex); if (context->error_string) ret = strdup(context->error_string); HEIMDAL_MUTEX_unlock(&context->mutex); return ret; } KRB5_LIB_FUNCTION krb5_boolean KRB5_LIB_CALL krb5_have_error_string(krb5_context context) KRB5_DEPRECATED_FUNCTION("Use krb5_get_error_message instead") { char *str; HEIMDAL_MUTEX_lock(&context->mutex); str = context->error_string; HEIMDAL_MUTEX_unlock(&context->mutex); return str != NULL; } struct send_to_kdc { krb5_send_to_kdc_func func; void *data; }; /* * Send the data `send' to one host from `handle` and get back the reply * in `receive'. */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_sendto (krb5_context context, const krb5_data *send_data, krb5_krbhst_handle handle, krb5_data *receive) { krb5_error_code ret; krb5_sendto_ctx ctx; ret = krb5_sendto_ctx_alloc(context, &ctx); if (ret) return ret; _krb5_sendto_ctx_set_krb5hst(context, ctx, handle); ret = krb5_sendto_context(context, ctx, send_data, (char *)_krb5_krbhst_get_realm(handle), receive); krb5_sendto_ctx_free(context, ctx); return ret; } KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_sendto_kdc(krb5_context context, const krb5_data *send_data, const krb5_realm *realm, krb5_data *receive) { return krb5_sendto_kdc_flags(context, send_data, realm, receive, 0); } KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_sendto_kdc_flags(krb5_context context, const krb5_data *send_data, const krb5_realm *realm, krb5_data *receive, int flags) { krb5_error_code ret; krb5_sendto_ctx ctx; ret = krb5_sendto_ctx_alloc(context, &ctx); if (ret) return ret; krb5_sendto_ctx_add_flags(ctx, flags); krb5_sendto_ctx_set_func(ctx, _krb5_kdc_retry, NULL); ret = krb5_sendto_context(context, ctx, send_data, *realm, receive); krb5_sendto_ctx_free(context, ctx); return ret; } KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_set_send_to_kdc_func(krb5_context context, krb5_send_to_kdc_func func, void *data) { free(context->send_to_kdc); if (func == NULL) { context->send_to_kdc = NULL; return 0; } context->send_to_kdc = malloc(sizeof(*context->send_to_kdc)); if (context->send_to_kdc == NULL) { krb5_set_error_message(context, ENOMEM, N_("malloc: out of memory", "")); return ENOMEM; } context->send_to_kdc->func = func; context->send_to_kdc->data = data; return 0; } KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL _krb5_copy_send_to_kdc_func(krb5_context context, krb5_context to) { if (context->send_to_kdc) return krb5_set_send_to_kdc_func(to, context->send_to_kdc->func, context->send_to_kdc->data); else return krb5_set_send_to_kdc_func(to, NULL, NULL); } #endif /* HEIMDAL_SMALLER */ heimdal-7.5.0/lib/krb5/test_gic.c0000644000175000017500000001004513026237312014627 0ustar niknik/* * Copyright (c) 2009 Kungliga Tekniska Hgskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of KTH nor the names of its contributors may be * used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY KTH AND ITS CONTRIBUTORS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL KTH OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "krb5_locl.h" #include #include static char *password_str; static krb5_error_code lr_proc(krb5_context context, krb5_last_req_entry **e, void *ctx) { while (e && *e) { printf("e type: %d value: %d\n", (*e)->lr_type, (int)(*e)->value); e++; } return 0; } static void test_get_init_creds(krb5_context context, krb5_principal client) { krb5_error_code ret; krb5_get_init_creds_opt *opt; krb5_creds cred; ret = krb5_get_init_creds_opt_alloc(context, &opt); if (ret) krb5_err(context, 1, ret, "krb5_get_init_creds_opt_alloc"); ret = krb5_get_init_creds_opt_set_process_last_req(context, opt, lr_proc, NULL); if (ret) krb5_err(context, 1, ret, "krb5_get_init_creds_opt_set_process_last_req"); ret = krb5_get_init_creds_password(context, &cred, client, password_str, krb5_prompter_posix, NULL, 0, NULL, opt); if (ret) krb5_err(context, 1, ret, "krb5_get_init_creds_password"); krb5_get_init_creds_opt_free(context, opt); } static char *client_str = NULL; static int debug_flag = 0; static int version_flag = 0; static int help_flag = 0; static struct getargs args[] = { {"client", 0, arg_string, &client_str, "client principal to use", NULL }, {"password",0, arg_string, &password_str, "password", NULL }, {"debug", 'd', arg_flag, &debug_flag, "turn on debuggin", NULL }, {"version", 0, arg_flag, &version_flag, "print version", NULL }, {"help", 0, arg_flag, &help_flag, NULL, NULL } }; static void usage (int ret) { arg_printusage (args, sizeof(args)/sizeof(*args), NULL, "hostname ..."); exit (ret); } int main(int argc, char **argv) { krb5_context context; krb5_error_code ret; int optidx = 0, errors = 0; krb5_principal client; setprogname(argv[0]); if(getarg(args, sizeof(args) / sizeof(args[0]), argc, argv, &optidx)) usage(1); if (help_flag) usage (0); if(version_flag){ print_version(NULL); exit(0); } if(client_str == NULL) errx(1, "client is not set"); ret = krb5_init_context(&context); if (ret) errx (1, "krb5_init_context failed: %d", ret); ret = krb5_parse_name(context, client_str, &client); if (ret) krb5_err(context, 1, ret, "krb5_parse_name: %d", ret); test_get_init_creds(context, client); krb5_free_context(context); return errors; } heimdal-7.5.0/lib/krb5/test_keytab.c0000644000175000017500000001666213026237312015357 0ustar niknik/* * Copyright (c) 2005 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of KTH nor the names of its contributors may be * used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY KTH AND ITS CONTRIBUTORS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL KTH OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "krb5_locl.h" #include #include /* * Test that removal entry from of empty keytab doesn't corrupts * memory. */ static void test_empty_keytab(krb5_context context, const char *keytab) { krb5_error_code ret; krb5_keytab id; krb5_keytab_entry entry; ret = krb5_kt_resolve(context, keytab, &id); if (ret) krb5_err(context, 1, ret, "krb5_kt_resolve"); memset(&entry, 0, sizeof(entry)); krb5_kt_remove_entry(context, id, &entry); ret = krb5_kt_have_content(context, id); if (ret == 0) krb5_errx(context, 1, "supposed to be empty keytab isn't"); ret = krb5_kt_close(context, id); if (ret) krb5_err(context, 1, ret, "krb5_kt_close"); } /* * Test that memory keytab are refcounted. */ static void test_memory_keytab(krb5_context context, const char *keytab, const char *keytab2) { krb5_error_code ret; krb5_keytab id, id2, id3; krb5_keytab_entry entry, entry2, entry3; ret = krb5_kt_resolve(context, keytab, &id); if (ret) krb5_err(context, 1, ret, "krb5_kt_resolve"); memset(&entry, 0, sizeof(entry)); ret = krb5_parse_name(context, "lha@SU.SE", &entry.principal); if (ret) krb5_err(context, 1, ret, "krb5_parse_name"); entry.vno = 1; ret = krb5_generate_random_keyblock(context, ETYPE_AES256_CTS_HMAC_SHA1_96, &entry.keyblock); if (ret) krb5_err(context, 1, ret, "krb5_generate_random_keyblock"); krb5_kt_add_entry(context, id, &entry); ret = krb5_kt_resolve(context, keytab, &id2); if (ret) krb5_err(context, 1, ret, "krb5_kt_resolve"); ret = krb5_kt_get_entry(context, id, entry.principal, 0, ETYPE_AES256_CTS_HMAC_SHA1_96, &entry2); if (ret) krb5_err(context, 1, ret, "krb5_kt_get_entry"); krb5_kt_free_entry(context, &entry2); ret = krb5_kt_close(context, id); if (ret) krb5_err(context, 1, ret, "krb5_kt_close"); ret = krb5_kt_get_entry(context, id2, entry.principal, 0, ETYPE_AES256_CTS_HMAC_SHA1_96, &entry2); if (ret) krb5_err(context, 1, ret, "krb5_kt_get_entry"); krb5_kt_free_entry(context, &entry2); ret = krb5_kt_close(context, id2); if (ret) krb5_err(context, 1, ret, "krb5_kt_close"); ret = krb5_kt_resolve(context, keytab2, &id3); if (ret) krb5_err(context, 1, ret, "krb5_kt_resolve"); memset(&entry3, 0, sizeof(entry3)); ret = krb5_parse_name(context, "lha3@SU.SE", &entry3.principal); if (ret) krb5_err(context, 1, ret, "krb5_parse_name"); entry3.vno = 1; ret = krb5_generate_random_keyblock(context, ETYPE_AES256_CTS_HMAC_SHA1_96, &entry3.keyblock); if (ret) krb5_err(context, 1, ret, "krb5_generate_random_keyblock"); krb5_kt_add_entry(context, id3, &entry3); ret = krb5_kt_resolve(context, keytab, &id); if (ret) krb5_err(context, 1, ret, "krb5_kt_resolve"); ret = krb5_kt_get_entry(context, id, entry.principal, 0, ETYPE_AES256_CTS_HMAC_SHA1_96, &entry2); if (ret == 0) krb5_errx(context, 1, "krb5_kt_get_entry when if should fail"); krb5_kt_remove_entry(context, id, &entry); ret = krb5_kt_close(context, id); if (ret) krb5_err(context, 1, ret, "krb5_kt_close"); krb5_kt_free_entry(context, &entry); krb5_kt_remove_entry(context, id3, &entry3); ret = krb5_kt_close(context, id3); if (ret) krb5_err(context, 1, ret, "krb5_kt_close"); krb5_free_principal(context, entry3.principal); krb5_free_keyblock_contents(context, &entry3.keyblock); } static void perf_add(krb5_context context, krb5_keytab id, int times) { } static void perf_find(krb5_context context, krb5_keytab id, int times) { } static void perf_delete(krb5_context context, krb5_keytab id, int forward, int times) { } static int version_flag = 0; static int help_flag = 0; static char *perf_str = NULL; static int times = 1000; static struct getargs args[] = { {"performance", 0, arg_string, &perf_str, "test performance for named keytab", "keytab" }, {"times", 0, arg_integer, ×, "number of times to run the perforamce test", "number" }, {"version", 0, arg_flag, &version_flag, "print version", NULL }, {"help", 0, arg_flag, &help_flag, NULL, NULL } }; static void usage (int ret) { arg_printusage (args, sizeof(args)/sizeof(*args), NULL, ""); exit (ret); } int main(int argc, char **argv) { krb5_context context; krb5_error_code ret; int optidx = 0; setprogname(argv[0]); if(getarg(args, sizeof(args) / sizeof(args[0]), argc, argv, &optidx)) usage(1); if (help_flag) usage (0); if(version_flag){ print_version(NULL); exit(0); } argc -= optidx; argv += optidx; if (argc != 0) errx(1, "argc != 0"); ret = krb5_init_context(&context); if (ret) errx (1, "krb5_init_context failed: %d", ret); if (perf_str) { krb5_keytab id; ret = krb5_kt_resolve(context, perf_str, &id); if (ret) krb5_err(context, 1, ret, "krb5_kt_resolve: %s", perf_str); /* add, find, delete on keytab */ perf_add(context, id, times); perf_find(context, id, times); perf_delete(context, id, 0, times); /* add and find again on used keytab */ perf_add(context, id, times); perf_find(context, id, times); ret = krb5_kt_destroy(context, id); if (ret) krb5_err(context, 1, ret, "krb5_kt_destroy: %s", perf_str); ret = krb5_kt_resolve(context, perf_str, &id); if (ret) krb5_err(context, 1, ret, "krb5_kt_resolve: %s", perf_str); /* try delete backwards */ #if 0 perf_add(context, id, times); perf_delete(context, id, 1, times); #endif ret = krb5_kt_destroy(context, id); if (ret) krb5_err(context, 1, ret, "krb5_kt_destroy"); } else { test_empty_keytab(context, "MEMORY:foo"); test_empty_keytab(context, "FILE:foo"); test_memory_keytab(context, "MEMORY:foo", "MEMORY:foo2"); } krb5_free_context(context); return 0; } heimdal-7.5.0/lib/krb5/krb5_appdefault.cat30000644000175000017500000000552413212450756016522 0ustar niknik KRB5_APPDEFAULT(3) BSD Library Functions Manual KRB5_APPDEFAULT(3) NNAAMMEE kkrrbb55__aappppddeeffaauulltt__bboooolleeaann, kkrrbb55__aappppddeeffaauulltt__ssttrriinngg, kkrrbb55__aappppddeeffaauulltt__ttiimmee -- get application configuration value LLIIBBRRAARRYY Kerberos 5 Library (libkrb5, -lkrb5) SSYYNNOOPPSSIISS ##iinncclluuddee <> _v_o_i_d kkrrbb55__aappppddeeffaauulltt__bboooolleeaann(_k_r_b_5___c_o_n_t_e_x_t _c_o_n_t_e_x_t, _c_o_n_s_t _c_h_a_r _*_a_p_p_n_a_m_e, _k_r_b_5___r_e_a_l_m _r_e_a_l_m, _c_o_n_s_t _c_h_a_r _*_o_p_t_i_o_n, _k_r_b_5___b_o_o_l_e_a_n _d_e_f___v_a_l, _k_r_b_5___b_o_o_l_e_a_n _*_r_e_t___v_a_l); _v_o_i_d kkrrbb55__aappppddeeffaauulltt__ssttrriinngg(_k_r_b_5___c_o_n_t_e_x_t _c_o_n_t_e_x_t, _c_o_n_s_t _c_h_a_r _*_a_p_p_n_a_m_e, _k_r_b_5___r_e_a_l_m _r_e_a_l_m, _c_o_n_s_t _c_h_a_r _*_o_p_t_i_o_n, _c_o_n_s_t _c_h_a_r _*_d_e_f___v_a_l, _c_h_a_r _*_*_r_e_t___v_a_l); _v_o_i_d kkrrbb55__aappppddeeffaauulltt__ttiimmee(_k_r_b_5___c_o_n_t_e_x_t _c_o_n_t_e_x_t, _c_o_n_s_t _c_h_a_r _*_a_p_p_n_a_m_e, _k_r_b_5___r_e_a_l_m _r_e_a_l_m, _c_o_n_s_t _c_h_a_r _*_o_p_t_i_o_n, _t_i_m_e___t _d_e_f___v_a_l, _t_i_m_e___t _*_r_e_t___v_a_l); DDEESSCCRRIIPPTTIIOONN These functions get application defaults from the appdefaults section of the krb5.conf(5) configuration file. These defaults can be specified per application, and/or per realm. These values will be looked for in krb5.conf(5), in order of descending importance. [appdefaults] appname = { realm = { option = value } } appname = { option = value } realm = { option = value } option = value _a_p_p_n_a_m_e is the name of the application, and _r_e_a_l_m is the realm name. If the realm is omitted it will not be used for resolving values. _d_e_f___v_a_l is the value to return if no value is found in krb5.conf(5). SSEEEE AALLSSOO krb5_config(3), krb5.conf(5) HEIMDAL July 25, 2000 HEIMDAL heimdal-7.5.0/lib/krb5/krb5-plugin.70000644000175000017500000001716113026237312015117 0ustar niknik.\" Copyright (c) 1999 - 2005 Kungliga Tekniska Högskolan .\" (Royal Institute of Technology, Stockholm, Sweden). .\" All rights reserved. .\" .\" Redistribution and use in source and binary forms, with or without .\" modification, are permitted provided that the following conditions .\" are met: .\" .\" 1. Redistributions of source code must retain the above copyright .\" notice, this list of conditions and the following disclaimer. .\" .\" 2. Redistributions in binary form must reproduce the above copyright .\" notice, this list of conditions and the following disclaimer in the .\" documentation and/or other materials provided with the distribution. .\" .\" 3. Neither the name of the Institute nor the names of its contributors .\" may be used to endorse or promote products derived from this software .\" without specific prior written permission. .\" .\" THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND .\" ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE .\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE .\" ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE .\" FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL .\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS .\" OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) .\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT .\" LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF .\" SUCH DAMAGE. .\" .\" $Id$ .\" .Dd December 21, 2011 .Dt KRB5-PLUGIN 7 .Os HEIMDAL .Sh NAME .Nm krb5-plugin .Nd plugin interface for Heimdal .Sh SYNOPSIS .In krb5.h .In krb5/an2ln_plugin.h .In krb5/ccache_plugin.h .In krb5/db_plugin.h .In krb5/kuserok_plugin.h .In krb5/locate_plugin.h .In krb5/send_to_kdc_plugin.h .Sh DESCRIPTION Heimdal has a plugin interface. Plugins may be statically linked into Heimdal and registered via the .Xr krb5_plugin_register 3 function, or they may be dynamically loaded from shared objects present in the Heimdal plugins directories. .Pp Plugins consist of a C struct whose struct name is given in the associated header file, such as, for example, .Va krb5plugin_kuserok_ftable and a pointer to which is either registered via .Xr krb5_plugin_register 3 or found in a shared object via a symbol lookup for the symbol name defined in the associated header file (e.g., "kuserok" for the plugin for .Xr krb5_kuserok 3 ). .Pp The plugin structs for all plugin types always begin with the same three common fields: .Bl -enum -compact .It .Va minor_version , an int. Plugin minor versions are defined in each plugin type's associated header file. .It .Va init , a pointer to a function with two arguments, a krb5_context and a void **, returning a krb5_error_code. This function will be called to initialize a plugin-specific context in the form of a void * that will be output through the init function's second argument. .It .Va fini , a pointer to a function of one argument, a void *, consisting of the plugin's context to be destroyed, and returning void. .El .Pp Each plugin type must add zero or more fields to this struct following the above three. Plugins are typically invoked in no particular order until one succeeds or fails, or all return a special return value such as KRB5_PLUGIN_NO_HANDLE to indicate that the plugin was not applicable. Most plugin types obtain deterministic plugin behavior in spite of the non-deterministic invocation order by, for example, invoking all plugins for each "rule" and passing the rule to each plugin with the expectation that just one plugin will match any given rule. .Pp There is a database plugin system intended for many of the uses of databases in Heimdal. The plugin is expected to call .Xr heim_db_register 3 from its .Va init entry point to register a DB type. The DB plugin's .Va fini function must do nothing, and the plugin must not provide any other entry points. .Pp The krb5_kuserok plugin adds a single field to its struct: a pointer to a function that implements kuserok functionality with the following form: .Bd -literal -offset indent static krb5_error_code kuserok(void *plug_ctx, krb5_context context, const char *rule, unsigned int flags, const char *k5login_dir, const char *luser, krb5_const_principal principal, krb5_boolean *result) .Ed .Pp The .Va luser , .Va principal and .Va result arguments are self-explanatory (see .Xr krb5_kuserok 3 ). The .Va plug_ctx argument is the context output by the plugin's init function. The .Va rule argument is a kuserok rule from the krb5.conf file; each plugin is invoked once for each rule until all plugins fail or one succeeds. The .Va k5login_dir argument provides an alternative k5login file location, if not NULL. The .Va flags argument indicates whether the plugin may call .Xr krb5_aname_to_localname 3 (KUSEROK_ANAME_TO_LNAME_OK), and whether k5login databases are expected to be authoritative (KUSEROK_K5LOGIN_IS_AUTHORITATIVE). .Pp The plugin for .Xr krb5_aname_to_localname 3 is named "an2ln" and has a single extra field for the plugin struct: .Bd -literal -offset indent typedef krb5_error_code (*set_result_f)(void *, const char *); static krb5_error_code an2ln(void *plug_ctx, krb5_context context, const char *rule, krb5_const_principal aname, set_result_f set_res_f, void *set_res_ctx) .Ed .Pp The arguments for the .Va an2ln plugin are similar to those of the kuserok plugin, but the result, being a string, is set by calling the .Va set_res_f function argument with the .Va set_res_ctx and result string as arguments. The .Va set_res_f function will make a copy of the string. .Sh FILES .Bl -tag -compact .It Pa libdir/plugin/krb5/* Shared objects containing plugins for Heimdal. .El .Sh EXAMPLES .Pp An example an2ln plugin that maps principals to a constant "nouser" follows: .Pp .Bd -literal -offset indent #include static krb5_error_code nouser_plug_init(krb5_context context, void **ctx) { *ctx = NULL; return 0; } static void nouser_plug_fini(void *ctx) { } static krb5_error_code nouser_plug_an2ln(void *plug_ctx, krb5_context context, const char *rule, krb5_const_principal aname, set_result_f set_res_f, void *set_res_ctx) { krb5_error_code ret; if (strcmp(rule, "NOUSER") != 0) return KRB5_PLUGIN_NO_HANDLE; ret = set_res_f(set_res_ctx, "nouser"); return ret; } krb5plugin_an2ln_ftable an2ln = { KRB5_PLUGIN_AN2LN_VERSION_0, nouser_plug_init, nouser_plug_fini, nouser_plug_an2ln, }; .Ed .Pp An example kuserok plugin that rejects all requests follows. (Note that there exists a built-in plugin with this functionality; see .Xr krb5_kuserok 3 ). .Pp .Bd -literal -offset indent #include static krb5_error_code reject_plug_init(krb5_context context, void **ctx) { *ctx = NULL; return 0; } static void reject_plug_fini(void *ctx) { } static krb5_error_code reject_plug_kuserok(void *plug_ctx, krb5_context context, const char *rule, unsigned int flags, const char *k5login_dir, const char *luser, krb5_const_principal principal, krb5_boolean *result) { if (strcmp(rule, "REJECT") != 0) return KRB5_PLUGIN_NO_HANDLE; *result = FALSE; return 0; } krb5plugin_kuserok_ftable kuserok = { KRB5_PLUGIN_KUSEROK_VERSION_0, reject_plug_init, reject_plug_fini, reject_plug_kuserok, }; .Ed .Sh SEE ALSO .Xr krb5_plugin_register 3 .Xr krb5_kuserok 3 .Xr krb5_aname_to_localname 3 heimdal-7.5.0/lib/krb5/verify_krb5_conf.80000644000175000017500000000664212136107750016222 0ustar niknik.\" Copyright (c) 2000 - 2004 Kungliga Tekniska Högskolan .\" (Royal Institute of Technology, Stockholm, Sweden). .\" All rights reserved. .\" .\" Redistribution and use in source and binary forms, with or without .\" modification, are permitted provided that the following conditions .\" are met: .\" .\" 1. Redistributions of source code must retain the above copyright .\" notice, this list of conditions and the following disclaimer. .\" .\" 2. Redistributions in binary form must reproduce the above copyright .\" notice, this list of conditions and the following disclaimer in the .\" documentation and/or other materials provided with the distribution. .\" .\" 3. Neither the name of the Institute nor the names of its contributors .\" may be used to endorse or promote products derived from this software .\" without specific prior written permission. .\" .\" THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND .\" ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE .\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE .\" ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE .\" FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL .\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS .\" OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) .\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT .\" LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF .\" SUCH DAMAGE. .\" .\" $Id$ .\" .Dd December 8, 2004 .Dt VERIFY_KRB5_CONF 8 .Os HEIMDAL .Sh NAME .Nm verify_krb5_conf .Nd checks krb5.conf for obvious errors .Sh SYNOPSIS .Nm .Ar [config-file] .Sh DESCRIPTION .Nm reads the configuration file .Pa krb5.conf , or the file given on the command line, parses it, checking verifying that the syntax is not correctly wrong. .Pp If the file is syntactically correct, .Nm tries to verify that the contents of the file is of relevant nature. .Sh ENVIRONMENT .Ev KRB5_CONFIG points to the configuration file to read. .Sh FILES .Bl -tag -width /etc/krb5.conf -compact .It Pa /etc/krb5.conf Kerberos 5 configuration file .El .Sh DIAGNOSTICS Possible output from .Nm include: .Bl -tag -width "FpathF" .It ": failed to parse as size/time/number/boolean" Usually means that is misspelled, or that it contains weird characters. The parsing done by .Nm is more strict than the one performed by libkrb5, so strings that work in real life might be reported as bad. .It ": host not found ()" Means that is supposed to point to a host, but it can't be recognised as one. .It : unknown or wrong type Means that is either a string when it should be a list, vice versa, or just that .Nm is confused. .It : unknown entry Means that is not known by .Nm . .El .Sh SEE ALSO .Xr krb5.conf 5 .Sh BUGS Since each application can put almost anything in the config file, it's hard to come up with a watertight verification process. Most of the default settings are sanity checked, but this does not mean that every problem is discovered, or that everything that is reported as a possible problem actually is one. This tool should thus be used with some care. .Pp It should warn about obsolete data, or bad practice, but currently doesn't. heimdal-7.5.0/lib/krb5/salt-des.c0000644000175000017500000001517713212137553014560 0ustar niknik/* * Copyright (c) 1997 - 2008 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "krb5_locl.h" #ifdef HEIM_WEAK_CRYPTO #ifdef ENABLE_AFS_STRING_TO_KEY /* This defines the Andrew string_to_key function. It accepts a password * string as input and converts it via a one-way encryption algorithm to a DES * encryption key. It is compatible with the original Andrew authentication * service password database. */ /* * Short passwords, i.e 8 characters or less. */ static void krb5_DES_AFS3_CMU_string_to_key (krb5_data pw, krb5_data cell, DES_cblock *key) { char password[8+1]; /* crypt is limited to 8 chars anyway */ size_t i; for(i = 0; i < 8; i++) { char c = ((i < pw.length) ? ((char*)pw.data)[i] : 0) ^ ((i < cell.length) ? tolower(((unsigned char*)cell.data)[i]) : 0); password[i] = c ? c : 'X'; } password[8] = '\0'; memcpy(key, crypt(password, "p1") + 2, sizeof(DES_cblock)); /* parity is inserted into the LSB so left shift each byte up one bit. This allows ascii characters with a zero MSB to retain as much significance as possible. */ for (i = 0; i < sizeof(DES_cblock); i++) ((unsigned char*)key)[i] <<= 1; DES_set_odd_parity (key); } /* * Long passwords, i.e 9 characters or more. */ static void krb5_DES_AFS3_Transarc_string_to_key (krb5_data pw, krb5_data cell, DES_cblock *key) { DES_key_schedule schedule; DES_cblock temp_key; DES_cblock ivec; char password[512]; size_t passlen; memcpy(password, pw.data, min(pw.length, sizeof(password))); if(pw.length < sizeof(password)) { int len = min(cell.length, sizeof(password) - pw.length); size_t i; memcpy(password + pw.length, cell.data, len); for (i = pw.length; i < pw.length + len; ++i) password[i] = tolower((unsigned char)password[i]); } passlen = min(sizeof(password), pw.length + cell.length); memcpy(&ivec, "kerberos", 8); memcpy(&temp_key, "kerberos", 8); DES_set_odd_parity (&temp_key); DES_set_key_unchecked (&temp_key, &schedule); DES_cbc_cksum ((void*)password, &ivec, passlen, &schedule, &ivec); memcpy(&temp_key, &ivec, 8); DES_set_odd_parity (&temp_key); DES_set_key_unchecked (&temp_key, &schedule); DES_cbc_cksum ((void*)password, key, passlen, &schedule, &ivec); memset(&schedule, 0, sizeof(schedule)); memset(&temp_key, 0, sizeof(temp_key)); memset(&ivec, 0, sizeof(ivec)); memset(password, 0, sizeof(password)); DES_set_odd_parity (key); } static krb5_error_code DES_AFS3_string_to_key(krb5_context context, krb5_enctype enctype, krb5_data password, krb5_salt salt, krb5_data opaque, krb5_keyblock *key) { DES_cblock tmp; if(password.length > 8) krb5_DES_AFS3_Transarc_string_to_key(password, salt.saltvalue, &tmp); else krb5_DES_AFS3_CMU_string_to_key(password, salt.saltvalue, &tmp); key->keytype = enctype; krb5_data_copy(&key->keyvalue, tmp, sizeof(tmp)); memset(&key, 0, sizeof(key)); return 0; } #endif /* ENABLE_AFS_STRING_TO_KEY */ static void DES_string_to_key_int(unsigned char *data, size_t length, DES_cblock *key) { DES_key_schedule schedule; size_t i; int reverse = 0; unsigned char *p; unsigned char swap[] = { 0x0, 0x8, 0x4, 0xc, 0x2, 0xa, 0x6, 0xe, 0x1, 0x9, 0x5, 0xd, 0x3, 0xb, 0x7, 0xf }; memset(key, 0, 8); p = (unsigned char*)key; for (i = 0; i < length; i++) { unsigned char tmp = data[i]; if (!reverse) *p++ ^= (tmp << 1); else *--p ^= (swap[tmp & 0xf] << 4) | swap[(tmp & 0xf0) >> 4]; if((i % 8) == 7) reverse = !reverse; } DES_set_odd_parity(key); if(DES_is_weak_key(key)) (*key)[7] ^= 0xF0; DES_set_key_unchecked(key, &schedule); DES_cbc_cksum((void*)data, key, length, &schedule, key); memset(&schedule, 0, sizeof(schedule)); DES_set_odd_parity(key); if(DES_is_weak_key(key)) (*key)[7] ^= 0xF0; } static krb5_error_code krb5_DES_string_to_key(krb5_context context, krb5_enctype enctype, krb5_data password, krb5_salt salt, krb5_data opaque, krb5_keyblock *key) { unsigned char *s; size_t len; DES_cblock tmp; #ifdef ENABLE_AFS_STRING_TO_KEY if (opaque.length == 1) { unsigned long v; _krb5_get_int(opaque.data, &v, 1); if (v == 1) return DES_AFS3_string_to_key(context, enctype, password, salt, opaque, key); } #endif len = password.length + salt.saltvalue.length; s = malloc(len); if (len > 0 && s == NULL) return krb5_enomem(context); memcpy(s, password.data, password.length); memcpy(s + password.length, salt.saltvalue.data, salt.saltvalue.length); DES_string_to_key_int(s, len, &tmp); key->keytype = enctype; krb5_data_copy(&key->keyvalue, tmp, sizeof(tmp)); memset(&tmp, 0, sizeof(tmp)); memset(s, 0, len); free(s); return 0; } struct salt_type _krb5_des_salt[] = { { KRB5_PW_SALT, "pw-salt", krb5_DES_string_to_key }, #ifdef ENABLE_AFS_STRING_TO_KEY { KRB5_AFS3_SALT, "afs3-salt", DES_AFS3_string_to_key }, #endif { 0, NULL, NULL } }; #endif heimdal-7.5.0/lib/krb5/NTMakefile0000644000175000017500000003202213212137553014566 0ustar niknik######################################################################## # # Copyright (c) 2009 - 2016, Secure Endpoints Inc. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # - Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # # - Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in # the documentation and/or other materials provided with the # distribution. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS # FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE # COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, # BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN # ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. # RELDIR=lib\krb5 !include ../../windows/NTMakefile.w32 libkrb5_OBJS = \ $(OBJ)\acache.obj \ $(OBJ)\acl.obj \ $(OBJ)\add_et_list.obj \ $(OBJ)\addr_families.obj \ $(OBJ)\aname_to_localname.obj \ $(OBJ)\appdefault.obj \ $(OBJ)\asn1_glue.obj \ $(OBJ)\auth_context.obj \ $(OBJ)\build_ap_req.obj \ $(OBJ)\build_auth.obj \ $(OBJ)\cache.obj \ $(OBJ)\changepw.obj \ $(OBJ)\codec.obj \ $(OBJ)\config_file.obj \ $(OBJ)\config_reg.obj \ $(OBJ)\constants.obj \ $(OBJ)\context.obj \ $(OBJ)\convert_creds.obj \ $(OBJ)\copy_host_realm.obj \ $(OBJ)\crc.obj \ $(OBJ)\creds.obj \ $(OBJ)\crypto.obj \ $(OBJ)\crypto-aes-sha1.obj \ $(OBJ)\crypto-aes-sha2.obj \ $(OBJ)\crypto-algs.obj \ $(OBJ)\crypto-arcfour.obj \ $(OBJ)\crypto-des-common.obj \ $(OBJ)\crypto-des.obj \ $(OBJ)\crypto-des3.obj \ $(OBJ)\crypto-evp.obj \ $(OBJ)\crypto-null.obj \ $(OBJ)\crypto-pk.obj \ $(OBJ)\crypto-rand.obj \ $(OBJ)\data.obj \ $(OBJ)\dcache.obj \ $(OBJ)\db_plugin.obj \ $(OBJ)\deprecated.obj \ $(OBJ)\digest.obj \ $(OBJ)\dll.obj \ $(OBJ)\eai_to_heim_errno.obj \ $(OBJ)\enomem.obj \ $(OBJ)\error_string.obj \ $(OBJ)\expand_hostname.obj \ $(OBJ)\expand_path.obj \ $(OBJ)\fast.obj \ $(OBJ)\fcache.obj \ $(OBJ)\free.obj \ $(OBJ)\free_host_realm.obj \ $(OBJ)\generate_seq_number.obj \ $(OBJ)\generate_subkey.obj \ $(OBJ)\get_addrs.obj \ $(OBJ)\get_cred.obj \ $(OBJ)\get_default_principal.obj \ $(OBJ)\get_default_realm.obj \ $(OBJ)\get_for_creds.obj \ $(OBJ)\get_host_realm.obj \ $(OBJ)\get_in_tkt.obj \ $(OBJ)\get_port.obj \ $(OBJ)\init_creds.obj \ $(OBJ)\init_creds_pw.obj \ $(OBJ)\kcm.obj \ $(OBJ)\keyblock.obj \ $(OBJ)\keytab.obj \ $(OBJ)\keytab_any.obj \ $(OBJ)\keytab_file.obj \ $(OBJ)\keytab_keyfile.obj \ $(OBJ)\keytab_memory.obj \ $(OBJ)\krbhst.obj \ $(OBJ)\kuserok.obj \ $(OBJ)\log.obj \ $(OBJ)\mcache.obj \ $(OBJ)\misc.obj \ $(OBJ)\mit_glue.obj \ $(OBJ)\mk_error.obj \ $(OBJ)\mk_priv.obj \ $(OBJ)\mk_rep.obj \ $(OBJ)\mk_req.obj \ $(OBJ)\mk_req_ext.obj \ $(OBJ)\mk_safe.obj \ $(OBJ)\net_read.obj \ $(OBJ)\net_write.obj \ $(OBJ)\n-fold.obj \ $(OBJ)\pac.obj \ $(OBJ)\padata.obj \ $(OBJ)\pcache.obj \ $(OBJ)\pkinit.obj \ $(OBJ)\pkinit-ec.obj \ $(OBJ)\plugin.obj \ $(OBJ)\principal.obj \ $(OBJ)\prog_setup.obj \ $(OBJ)\prompter_posix.obj \ $(OBJ)\rd_cred.obj \ $(OBJ)\rd_error.obj \ $(OBJ)\rd_priv.obj \ $(OBJ)\rd_rep.obj \ $(OBJ)\rd_req.obj \ $(OBJ)\rd_safe.obj \ $(OBJ)\read_message.obj \ $(OBJ)\recvauth.obj \ $(OBJ)\replay.obj \ $(OBJ)\salt-aes-sha1.obj \ $(OBJ)\salt-aes-sha2.obj \ $(OBJ)\salt-arcfour.obj \ $(OBJ)\salt-des.obj \ $(OBJ)\salt-des3.obj \ $(OBJ)\salt.obj \ $(OBJ)\scache.obj \ $(OBJ)\send_to_kdc.obj \ $(OBJ)\sendauth.obj \ $(OBJ)\set_default_realm.obj \ $(OBJ)\sock_principal.obj \ $(OBJ)\sp800-108-kdf.obj \ $(OBJ)\store.obj \ $(OBJ)\store-int.obj \ $(OBJ)\store_emem.obj \ $(OBJ)\store_fd.obj \ $(OBJ)\store_mem.obj \ $(OBJ)\store_sock.obj \ $(OBJ)\ticket.obj \ $(OBJ)\time.obj \ $(OBJ)\transited.obj \ $(OBJ)\verify_init.obj \ $(OBJ)\verify_user.obj \ $(OBJ)\version.obj \ $(OBJ)\warn.obj \ $(OBJ)\write_message.obj libkrb5_gen_OBJS= \ $(OBJ)\krb5_err.obj \ $(OBJ)\krb_err.obj \ $(OBJ)\heim_err.obj \ $(OBJ)\k524_err.obj INCFILES= \ $(INCDIR)\heim_err.h \ $(INCDIR)\k524_err.h \ $(INCDIR)\kcm.h \ $(INCDIR)\krb_err.h \ $(INCDIR)\krb5.h \ $(INCDIR)\krb5_ccapi.h \ $(INCDIR)\krb5_err.h \ $(INCDIR)\krb5_locl.h \ $(INCDIR)\krb5-protos.h \ $(INCDIR)\krb5-private.h \ $(INCDIR)\krb5-v4compat.h \ $(INCDIR)\crypto.h all:: $(INCFILES) clean:: -$(RM) $(INCFILES) dist_libkrb5_la_SOURCES = \ acache.c \ acl.c \ add_et_list.c \ addr_families.c \ aname_to_localname.c \ appdefault.c \ asn1_glue.c \ auth_context.c \ build_ap_req.c \ build_auth.c \ cache.c \ changepw.c \ codec.c \ config_file.c \ config_reg.c \ constants.c \ context.c \ copy_host_realm.c \ crc.c \ creds.c \ crypto.c \ crypto.h \ crypto-aes-sha1.c \ crypto-aes-sha2.c \ crypto-algs.c \ crypto-arcfour.c \ crypto-des.c \ crypto-des-common.c \ crypto-des3.c \ crypto-evp.c \ crypto-pk.c \ crypto-rand.c \ db_plugin.c \ doxygen.c \ data.c \ dcache.c \ deprecated.c \ digest.c \ eai_to_heim_errno.c \ enomem.c \ error_string.c \ expand_hostname.c \ expand_path.c \ fast.c \ fcache.c \ free.c \ free_host_realm.c \ generate_seq_number.c \ generate_subkey.c \ get_addrs.c \ get_cred.c \ get_default_principal.c \ get_default_realm.c \ get_for_creds.c \ get_host_realm.c \ get_in_tkt.c \ get_port.c \ init_creds.c \ init_creds_pw.c \ kcm.c \ kcm.h \ keyblock.c \ keytab.c \ keytab_any.c \ keytab_file.c \ keytab_keyfile.c \ keytab_memory.c \ krb5_locl.h \ krb5-v4compat.h \ krbhst.c \ kuserok.c \ log.c \ mcache.c \ misc.c \ mk_error.c \ mk_priv.c \ mk_rep.c \ mk_req.c \ mk_req_ext.c \ mk_safe.c \ mit_glue.c \ net_read.c \ net_write.c \ n-fold.c \ pac.c \ padata.c \ pkinit.c \ pkinit-ec.c \ plugin.c \ principal.c \ prog_setup.c \ prompter_posix.c \ rd_cred.c \ rd_error.c \ rd_priv.c \ rd_rep.c \ rd_req.c \ rd_safe.c \ read_message.c \ recvauth.c \ replay.c \ salt.c \ salt-aes-sha1.c \ salt-aes-sha2.c \ salt-arcfour.c \ salt-des.c \ salt-des3.c \ scache.c \ send_to_kdc.c \ sendauth.c \ set_default_realm.c \ sock_principal.c \ sp800-108-kdf.c \ store.c \ store-int.c \ store-int.h \ store_emem.c \ store_fd.c \ store_mem.c \ store_sock.c \ pcache.c \ plugin.c \ ticket.c \ time.c \ transited.c \ verify_init.c \ verify_user.c \ version.c \ warn.c \ write_message.c $(OBJ)\krb5-protos.h: $(dist_libkrb5_la_SOURCES) $(PERL) ..\..\cf\make-proto.pl -E KRB5_LIB -q -P remove -o $(OBJ)\krb5-protos.h $(dist_libkrb5_la_SOURCES) || $(RM) -f $(OBJ)\krb5-protos.h $(OBJ)\krb5-private.h: $(dist_libkrb5_la_SOURCES) $(PERL) ..\..\cf\make-proto.pl -q -P remove -p $(OBJ)\krb5-private.h $(dist_libkrb5_la_SOURCES) || $(RM) -f $(OBJ)\krb5-private.h $(OBJ)\krb5_err.c $(OBJ)\krb5_err.h: krb5_err.et cd $(OBJ) $(BINDIR)\compile_et.exe $(SRCDIR)\krb5_err.et cd $(SRCDIR) $(OBJ)\krb_err.c $(OBJ)\krb_err.h: krb_err.et cd $(OBJ) $(BINDIR)\compile_et.exe $(SRCDIR)\krb_err.et cd $(SRCDIR) $(OBJ)\heim_err.c $(OBJ)\heim_err.h: heim_err.et cd $(OBJ) $(BINDIR)\compile_et.exe $(SRCDIR)\heim_err.et cd $(SRCDIR) $(OBJ)\k524_err.c $(OBJ)\k524_err.h: k524_err.et cd $(OBJ) $(BINDIR)\compile_et.exe $(SRCDIR)\k524_err.et cd $(SRCDIR) #---------------------------------------------------------------------- # libkrb5 $(LIBKRB5): $(libkrb5_OBJS) $(libkrb5_gen_OBJS) $(LIBCON_C) -OUT:$@ $(LIBHEIMBASE) $(LIB_openssl_crypto) @<< $(libkrb5_OBJS: = ) $(libkrb5_gen_OBJS: = ) << all:: $(LIBKRB5) clean:: -$(RM) $(LIBKRB5) $(OBJ)\libkrb5-exports.def: libkrb5-exports.def.in $(INCDIR)\config.h $(CPREPROCESSOUT) libkrb5-exports.def.in > $@ || $(RM) $@ all:: $(OBJ)\libkrb5-exports.def clean:: -$(RM) $(OBJ)\libkrb5-exports.def #---------------------------------------------------------------------- # librfc3961 librfc3961_OBJS=\ $(OBJ)\crc.obj \ $(OBJ)\crypto.obj \ $(OBJ)\crypto-aes-sha1.obj \ $(OBJ)\crypto-aes-sha2.obj \ $(OBJ)\crypto-algs.obj \ $(OBJ)\crypto-arcfour.obj \ $(OBJ)\crypto-des.obj \ $(OBJ)\crypto-des-common.obj \ $(OBJ)\crypto-des3.obj \ $(OBJ)\crypto-evp.obj \ $(OBJ)\crypto-null.obj \ $(OBJ)\crypto-pk.obj \ $(OBJ)\crypto-rand.obj \ $(OBJ)\crypto-stubs.obj \ $(OBJ)\data.obj \ $(OBJ)\error_string.obj \ $(OBJ)\keyblock.obj \ $(OBJ)\n-fold.obj \ $(OBJ)\salt.obj \ $(OBJ)\salt-aes-sha1.obj \ $(OBJ)\salt-aes-sha2.obj \ $(OBJ)\salt-arcfour.obj \ $(OBJ)\salt-des.obj \ $(OBJ)\salt-des3.obj \ $(OBJ)\sp800-108-kdf.obj \ $(OBJ)\store-int.obj \ $(OBJ)\warn.obj $(LIBRFC3961): $(librfc3961_OBJS) $(LIBCON) all:: $(LIBRFC3961) clean:: -$(RM) $(LIBRFC3961) #---------------------------------------------------------------------- # Tools all-tools:: $(BINDIR)\verify_krb5_conf.exe clean:: -$(RM) $(BINDIR)\verify_krb5_conf.* $(BINDIR)\verify_krb5_conf.exe: $(OBJ)\verify_krb5_conf.obj $(LIBHEIMDAL) $(LIBROKEN) $(LIBVERS) $(OBJ)\verify_krb5_conf-version.res $(EXECONLINK) $(EXEPREP) {}.c{$(OBJ)}.obj:: $(C2OBJ_P) -DBUILD_KRB5_LIB -DASN1_LIB {$(OBJ)}.c{$(OBJ)}.obj:: $(C2OBJ_P) -DBUILD_KRB5_LIB -DASN1_LIB #---------------------------------------------------------------------- # Tests test:: test-binaries test-files test-run test_binaries = \ $(OBJ)\aes-test.exe \ $(OBJ)\derived-key-test.exe \ $(OBJ)\krbhst-test.exe \ $(OBJ)\n-fold-test.exe \ $(OBJ)\parse-name-test.exe \ $(OBJ)\pseudo-random-test.exe \ $(OBJ)\store-test.exe \ $(OBJ)\string-to-key-test.exe \ $(OBJ)\test_acl.exe \ $(OBJ)\test_addr.exe \ $(OBJ)\test_alname.exe \ $(OBJ)\test_cc.exe \ $(OBJ)\test_config.exe \ $(OBJ)\test_crypto.exe \ $(OBJ)\test_crypto_wrapping.exe \ $(OBJ)\test_forward.exe \ $(OBJ)\test_get_addrs.exe \ $(OBJ)\test_hostname.exe \ $(OBJ)\test_keytab.exe \ $(OBJ)\test_kuserok.exe \ $(OBJ)\test_mem.exe \ $(OBJ)\test_pac.exe \ $(OBJ)\test_pkinit_dh2key.exe \ $(OBJ)\test_pknistkdf.exe \ $(OBJ)\test_plugin.exe \ $(OBJ)\test_prf.exe \ $(OBJ)\test_princ.exe \ $(OBJ)\test_renew.exe \ $(OBJ)\test_store.exe \ $(OBJ)\test_time.exe \ test-binaries: $(test_binaries) $(OBJ)\test_rfc3961.exe test-files: $(OBJ)\test_config_strings.out $(OBJ)\test_config_strings.out: test_config_strings.cfg $(CP) $** $@ test-run: cd $(OBJ) -aes-test.exe -derived-key-test.exe -krbhst-test.exe -n-fold-test.exe -parse-name-test.exe -pseudo-random-test.exe -store-test.exe -string-to-key-test.exe -test_acl.exe -test_addr.exe # Skip alname due to lack of .k5login and "root" # -test_alname.exe -test_cc.exe -test_config.exe -test_crypto.exe -test_crypto_wrapping.exe # Skip forward due to need for existing hostname # -test_forward.exe -test_get_addrs.exe -test_hostname.exe -test_keytab.exe # Skip kuserok requires principal and localname # -test_kuserok.exe -test_mem.exe -test_pac.exe -test_pkinit_dh2key.exe -test_pknistkdf.exe -test_plugin.exe -test_prf.exe -test_renew.exe -test_rfc3961.exe -test_store.exe -test_time.exe cd $(SRCDIR) $(test_binaries): $$(@R).obj $(LIBHEIMDAL) $(LIBVERS) $(LIBROKEN) $(LIBHEIMBASE) $(EXECONLINK) $(EXEPREP_NODIST) $(OBJ)\test_rfc3961.exe: $(OBJ)\test_rfc3961.obj $(LIBRFC3961) $(LIBHEIMDAL) $(LIBVERS) $(LIBCOMERR) $(LIBROKEN) $(LIBHEIMBASE) $(EXECONLINK) $(EXEPREP_NODIST) $(test_binaries:.exe=.obj): $$(@B).c $(C2OBJ_C) -Fo$@ -Fd$(@D)\ $** -DBlah test-exports: $(PERL) ..\..\cf\w32-check-exported-symbols.pl --vs version-script.map --def libkrb5-exports.def.in test:: test-exports heimdal-7.5.0/lib/krb5/test_fx.c0000644000175000017500000001563213026237312014511 0ustar niknik/* * Copyright (c) 2009 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of KTH nor the names of its contributors may be * used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY KTH AND ITS CONTRIBUTORS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL KTH OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "krb5_locl.h" #include #include struct { char *p1; char *pepper1; krb5_enctype e1; char *p2; char *pepper2; krb5_enctype e2; krb5_enctype e3; char *key; size_t len; } cf2[] = { { "key1", "a", ETYPE_AES128_CTS_HMAC_SHA1_96, "key2", "b", ETYPE_AES128_CTS_HMAC_SHA1_96, ETYPE_AES128_CTS_HMAC_SHA1_96, "\x97\xdf\x97\xe4\xb7\x98\xb2\x9e\xb3\x1e\xd7\x28\x02\x87\xa9\x2a", 16 }, { "key1", "a", ETYPE_AES256_CTS_HMAC_SHA1_96, "key2", "b", ETYPE_AES256_CTS_HMAC_SHA1_96, ETYPE_AES256_CTS_HMAC_SHA1_96, "\x4d\x6c\xa4\xe6\x29\x78\x5c\x1f\x01\xba\xf5\x5e\x2e\x54\x85\x66" "\xb9\x61\x7a\xe3\xa9\x68\x68\xc3\x37\xcb\x93\xb5\xe7\x2b\x1c\x7b", 32 }, { "key1", "a", ETYPE_AES128_CTS_HMAC_SHA1_96, "key2", "b", ETYPE_AES128_CTS_HMAC_SHA1_96, ETYPE_AES256_CTS_HMAC_SHA1_96, "\x97\xdf\x97\xe4\xb7\x98\xb2\x9e\xb3\x1e\xd7\x28\x2\x87\xa9\x2a" "\x1\x96\xfa\xf2\x44\xf8\x11\x20\xc2\x1c\x51\x17\xb3\xe6\xeb\x98", 32 }, { "key1", "a", ETYPE_AES256_CTS_HMAC_SHA1_96, "key2", "b", ETYPE_AES256_CTS_HMAC_SHA1_96, ETYPE_AES128_CTS_HMAC_SHA1_96, "\x4d\x6c\xa4\xe6\x29\x78\x5c\x1f\x01\xba\xf5\x5e\x2e\x54\x85\x66", 16 }, { "key1", "a", ETYPE_AES128_CTS_HMAC_SHA1_96, "key2", "b", ETYPE_AES256_CTS_HMAC_SHA1_96, ETYPE_AES256_CTS_HMAC_SHA1_96, "\x88\xbd\xb2\xa9\xf\x3e\x52\x5a\xb0\x5f\x68\xc5\x43\x9a\x4d\x5e" "\x9c\x2b\xfd\x2b\x02\x24\xde\x39\xb5\x82\xf4\xbb\x05\xfe\x2\x2e", 32 }, { "key1", "a", ETYPE_ARCFOUR_HMAC_MD5, "key2", "b", ETYPE_ARCFOUR_HMAC_MD5, ETYPE_ARCFOUR_HMAC_MD5, "\x24\xd7\xf6\xb6\xba\xe4\xe5\xc0\x0d\x20\x82\xc5\xeb\xab\x36\x72", 16 }, /* We don't yet have a PRF for 1DES in Heimdal */ { "key1", "a", ETYPE_DES_CBC_CRC, "key2", "b", ETYPE_DES_CBC_CRC, ETYPE_DES_CBC_CRC, "\x43\xba\xe3\x73\x8c\x94\x67\xe6", 8 }, { "key1", "a", ETYPE_DES3_CBC_SHA1, "key2", "b", ETYPE_DES3_CBC_SHA1, ETYPE_DES3_CBC_SHA1, "\xe5\x8f\x9e\xb6\x43\x86\x2c\x13\xad\x38\xe5\x29\x31\x34\x62\xa7" "\xf7\x3e\x62\x83\x4f\xe5\x4a\x01", 24 }, }; static void test_cf2(krb5_context context) { krb5_error_code ret; krb5_data pw, p1, p2; krb5_salt salt; krb5_keyblock k1, k2, k3; krb5_crypto c1, c2; unsigned int i; unsigned int errors = 0; ret = krb5_allow_weak_crypto(context, 1); if (ret) krb5_err(context, 1, ret, "krb5_allow_weak_crypto"); for (i = 0; i < sizeof(cf2)/sizeof(cf2[0]); i++) { pw.data = cf2[i].p1; pw.length = strlen(cf2[i].p1); salt.salttype = (krb5_salttype)KRB5_PADATA_PW_SALT; salt.saltvalue.data = cf2[i].p1; salt.saltvalue.length = strlen(cf2[i].p1); ret = krb5_string_to_key_data_salt(context, cf2[i].e1, pw, salt, &k1); if (ret) krb5_err(context, 1, ret, "krb5_string_to_key_data_salt"); ret = krb5_crypto_init(context, &k1, 0, &c1); if (ret) krb5_err(context, 1, ret, "krb5_crypto_init"); pw.data = cf2[i].p2; pw.length = strlen(cf2[i].p2); salt.saltvalue.data = cf2[i].p2; salt.saltvalue.length = strlen(cf2[i].p2); ret = krb5_string_to_key_data_salt(context, cf2[i].e2, pw, salt, &k2); if (ret) krb5_err(context, 1, ret, "krb5_string_to_key_data_salt"); ret = krb5_crypto_init(context, &k2, 0, &c2); if (ret) krb5_err(context, 1, ret, "krb5_crypto_init"); p1.data = cf2[i].pepper1; p1.length = strlen(cf2[i].pepper1); p2.data = cf2[i].pepper2; p2.length = strlen(cf2[i].pepper2); ret = krb5_crypto_fx_cf2(context, c1, c2, &p1, &p2, cf2[i].e3, &k3); if (ret == KRB5_PROG_ETYPE_NOSUPP) { krb5_warn(context, ret, "KRB-FX-CF2 not supported for enctype %d", cf2[i].e1); continue; } else if (ret) { krb5_err(context, 1, ret, "krb5_crypto_fx_cf2"); } if (k3.keytype != cf2[i].e3) { errors++; krb5_warnx(context, "length not right for enctype %d", cf2[i].e3); continue; } if (k3.keyvalue.length != cf2[i].len || memcmp(k3.keyvalue.data, cf2[i].key, cf2[i].len) != 0) { errors++; krb5_warnx(context, "key not same for enctypes %d %d %d", cf2[i].e1, cf2[i].e2, cf2[i].e3); continue; } krb5_crypto_destroy(context, c1); krb5_crypto_destroy(context, c2); krb5_free_keyblock_contents(context, &k1); krb5_free_keyblock_contents(context, &k2); krb5_free_keyblock_contents(context, &k3); } if (errors) krb5_errx(context, 1, "%u KRB-FX-CF2 vectors failed", errors); } static int version_flag = 0; static int help_flag = 0; static struct getargs args[] = { {"version", 0, arg_flag, &version_flag, "print version", NULL }, {"help", 0, arg_flag, &help_flag, NULL, NULL } }; static void usage (int ret) { arg_printusage (args, sizeof(args)/sizeof(*args), NULL, ""); exit (ret); } int main(int argc, char **argv) { krb5_context context; krb5_error_code ret; int optidx = 0; setprogname(argv[0]); if(getarg(args, sizeof(args) / sizeof(args[0]), argc, argv, &optidx)) usage(1); if (help_flag) usage (0); if(version_flag){ print_version(NULL); exit(0); } ret = krb5_init_context(&context); if (ret) errx (1, "krb5_init_context failed: %d", ret); test_cf2(context); krb5_free_context(context); return 0; } heimdal-7.5.0/lib/krb5/crypto-rand.c0000644000175000017500000001131513026237312015271 0ustar niknik/* * Copyright (c) 1997 - 2008 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "krb5_locl.h" #undef HEIMDAL_WARN_UNUSED_RESULT_ATTRIBUTE #define HEIMDAL_WARN_UNUSED_RESULT_ATTRIBUTE #define ENTROPY_NEEDED 128 static HEIMDAL_MUTEX crypto_mutex = HEIMDAL_MUTEX_INITIALIZER; static int seed_something(void) { #ifndef NO_RANDFILE char buf[1024], seedfile[256]; /* If there is a seed file, load it. But such a file cannot be trusted, so use 0 for the entropy estimate */ if (RAND_file_name(seedfile, sizeof(seedfile))) { int fd; fd = open(seedfile, O_RDONLY | O_BINARY | O_CLOEXEC); if (fd >= 0) { ssize_t ret; rk_cloexec(fd); ret = read(fd, buf, sizeof(buf)); if (ret > 0) RAND_add(buf, ret, 0.0); close(fd); } else seedfile[0] = '\0'; } else seedfile[0] = '\0'; #endif /* Calling RAND_status() will try to use /dev/urandom if it exists so we do not have to deal with it. */ if (RAND_status() != 1) { /* TODO: Once a Windows CryptoAPI RAND method is defined, we can use that and failover to another method. */ } if (RAND_status() == 1) { #ifndef NO_RANDFILE /* Update the seed file */ if (seedfile[0]) RAND_write_file(seedfile); #endif return 0; } else return -1; } /** * Fill buffer buf with len bytes of PRNG randomness that is ok to use * for key generation, padding and public diclosing the randomness w/o * disclosing the randomness source. * * This function can fail, and callers must check the return value. * * @param buf a buffer to fill with randomness * @param len length of memory that buf points to. * * @return return 0 on success or HEIM_ERR_RANDOM_OFFLINE if the * funcation failed to initialize the randomness source. * * @ingroup krb5_crypto */ HEIMDAL_WARN_UNUSED_RESULT_ATTRIBUTE KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_generate_random(void *buf, size_t len) { static int rng_initialized = 0; int ret; HEIMDAL_MUTEX_lock(&crypto_mutex); if (!rng_initialized) { if (seed_something()) { HEIMDAL_MUTEX_unlock(&crypto_mutex); return HEIM_ERR_RANDOM_OFFLINE; } rng_initialized = 1; } if (RAND_bytes(buf, len) <= 0) ret = HEIM_ERR_RANDOM_OFFLINE; else ret = 0; HEIMDAL_MUTEX_unlock(&crypto_mutex); return ret; } /** * Fill buffer buf with len bytes of PRNG randomness that is ok to use * for key generation, padding and public diclosing the randomness w/o * disclosing the randomness source. * * This function can NOT fail, instead it will abort() and program will crash. * * If this function is called after a successful krb5_init_context(), * the chance of it failing is low due to that krb5_init_context() * pulls out some random, and quite commonly the randomness sources * will not fail once it have started to produce good output, * /dev/urandom behavies that way. * * @param buf a buffer to fill with randomness * @param len length of memory that buf points to. * * @ingroup krb5_crypto */ KRB5_LIB_FUNCTION void KRB5_LIB_CALL krb5_generate_random_block(void *buf, size_t len) { int ret = krb5_generate_random(buf, len); if (ret) krb5_abortx(NULL, "Failed to generate random block"); } heimdal-7.5.0/lib/krb5/krb5_get_krbhst.30000644000175000017500000000641212136107750016033 0ustar niknik.\" Copyright (c) 2001 Kungliga Tekniska Högskolan .\" (Royal Institute of Technology, Stockholm, Sweden). .\" All rights reserved. .\" .\" Redistribution and use in source and binary forms, with or without .\" modification, are permitted provided that the following conditions .\" are met: .\" .\" 1. Redistributions of source code must retain the above copyright .\" notice, this list of conditions and the following disclaimer. .\" .\" 2. Redistributions in binary form must reproduce the above copyright .\" notice, this list of conditions and the following disclaimer in the .\" documentation and/or other materials provided with the distribution. .\" .\" 3. Neither the name of the Institute nor the names of its contributors .\" may be used to endorse or promote products derived from this software .\" without specific prior written permission. .\" .\" THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND .\" ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE .\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE .\" ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE .\" FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL .\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS .\" OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) .\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT .\" LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF .\" SUCH DAMAGE. .\" .\" $Id$ .\" .Dd April 24, 2005 .Dt KRB5_GET_KRBHST 3 .Os HEIMDAL .Sh NAME .Nm krb5_get_krbhst , .Nm krb5_get_krb_admin_hst , .Nm krb5_get_krb_changepw_hst , .Nm krb5_get_krb524hst , .Nm krb5_free_krbhst .Nd lookup Kerberos KDC hosts .Sh LIBRARY Kerberos 5 Library (libkrb5, -lkrb5) .Sh SYNOPSIS .In krb5.h .Ft krb5_error_code .Fn krb5_get_krbhst "krb5_context context" "const krb5_realm *realm" "char ***hostlist" .Ft krb5_error_code .Fn krb5_get_krb_admin_hst "krb5_context context" "const krb5_realm *realm" "char ***hostlist" .Ft krb5_error_code .Fn krb5_get_krb_changepw_hst "krb5_context context" "const krb5_realm *realm" "char ***hostlist" .Ft krb5_error_code .Fn krb5_get_krb524hst "krb5_context context" "const krb5_realm *realm" "char ***hostlist" .Ft krb5_error_code .Fn krb5_free_krbhst "krb5_context context" "char **hostlist" .Sh DESCRIPTION These functions implement the old API to get a list of Kerberos hosts, and are thus similar to the .Fn krb5_krbhst_init functions. However, since these functions returns .Em all hosts in one go, they potentially have to do more lookups than necessary. These functions remain for compatibility reasons. .Pp After a call to one of these functions, .Fa hostlist is a .Dv NULL terminated list of strings, pointing to the requested Kerberos hosts. These should be freed with .Fn krb5_free_krbhst when done with. .Sh EXAMPLES The following code will print the KDCs of the realm .Dq MY.REALM . .Bd -literal -offset indent char **hosts, **p; krb5_get_krbhst(context, "MY.REALM", &hosts); for(p = hosts; *p; p++) printf("%s\\n", *p); krb5_free_krbhst(context, hosts); .Ed .\" .Sh BUGS .Sh SEE ALSO .Xr krb5_krbhst_init 3 heimdal-7.5.0/lib/krb5/parse-name-test.c0000644000175000017500000001347712136107750016052 0ustar niknik/* * Copyright (c) 2002 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of KTH nor the names of its contributors may be * used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY KTH AND ITS CONTRIBUTORS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL KTH OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "krb5_locl.h" #include enum { MAX_COMPONENTS = 3 }; static struct testcase { const char *input_string; const char *output_string; krb5_realm realm; unsigned ncomponents; char *comp_val[MAX_COMPONENTS]; int realmp; } tests[] = { {"", "@", "", 1, {""}, FALSE}, {"a", "a@", "", 1, {"a"}, FALSE}, {"\\n", "\\n@", "", 1, {"\n"}, FALSE}, {"\\ ", "\\ @", "", 1, {" "}, FALSE}, {"\\t", "\\t@", "", 1, {"\t"}, FALSE}, {"\\b", "\\b@", "", 1, {"\b"}, FALSE}, {"\\\\", "\\\\@", "", 1, {"\\"}, FALSE}, {"\\/", "\\/@", "", 1, {"/"}, FALSE}, {"\\@", "\\@@", "", 1, {"@"}, FALSE}, {"@", "@", "", 1, {""}, TRUE}, {"a/b", "a/b@", "", 2, {"a", "b"}, FALSE}, {"a/", "a/@", "", 2, {"a", ""}, FALSE}, {"a\\//\\/", "a\\//\\/@", "", 2, {"a/", "/"}, FALSE}, {"/a", "/a@", "", 2, {"", "a"}, FALSE}, {"\\@@\\@", "\\@@\\@", "@", 1, {"@"}, TRUE}, {"a/b/c", "a/b/c@", "", 3, {"a", "b", "c"}, FALSE}, {NULL, NULL, "", 0, { NULL }, FALSE}}; int main(int argc, char **argv) { struct testcase *t; krb5_context context; krb5_error_code ret; int val = 0; ret = krb5_init_context (&context); if (ret) errx (1, "krb5_init_context failed: %d", ret); /* to enable realm-less principal name above */ krb5_set_default_realm(context, ""); for (t = tests; t->input_string; ++t) { krb5_principal princ; int i, j; char name_buf[1024]; char *s; ret = krb5_parse_name(context, t->input_string, &princ); if (ret) krb5_err (context, 1, ret, "krb5_parse_name %s", t->input_string); if (strcmp (t->realm, princ->realm) != 0) { printf ("wrong realm (\"%s\" should be \"%s\")" " for \"%s\"\n", princ->realm, t->realm, t->input_string); val = 1; } if (t->ncomponents != princ->name.name_string.len) { printf ("wrong number of components (%u should be %u)" " for \"%s\"\n", princ->name.name_string.len, t->ncomponents, t->input_string); val = 1; } else { for (i = 0; i < t->ncomponents; ++i) { if (strcmp(t->comp_val[i], princ->name.name_string.val[i]) != 0) { printf ("bad component %d (\"%s\" should be \"%s\")" " for \"%s\"\n", i, princ->name.name_string.val[i], t->comp_val[i], t->input_string); val = 1; } } } for (j = 0; j < strlen(t->output_string); ++j) { ret = krb5_unparse_name_fixed(context, princ, name_buf, j); if (ret != ERANGE) { printf ("unparse_name %s with length %d should have failed\n", t->input_string, j); val = 1; break; } } ret = krb5_unparse_name_fixed(context, princ, name_buf, sizeof(name_buf)); if (ret) krb5_err (context, 1, ret, "krb5_unparse_name_fixed"); if (strcmp (t->output_string, name_buf) != 0) { printf ("failed comparing the re-parsed" " (\"%s\" should be \"%s\")\n", name_buf, t->output_string); val = 1; } ret = krb5_unparse_name(context, princ, &s); if (ret) krb5_err (context, 1, ret, "krb5_unparse_name"); if (strcmp (t->output_string, s) != 0) { printf ("failed comparing the re-parsed" " (\"%s\" should be \"%s\"\n", s, t->output_string); val = 1; } free(s); if (!t->realmp) { for (j = 0; j < strlen(t->input_string); ++j) { ret = krb5_unparse_name_fixed_short(context, princ, name_buf, j); if (ret != ERANGE) { printf ("unparse_name_short %s with length %d" " should have failed\n", t->input_string, j); val = 1; break; } } ret = krb5_unparse_name_fixed_short(context, princ, name_buf, sizeof(name_buf)); if (ret) krb5_err (context, 1, ret, "krb5_unparse_name_fixed"); if (strcmp (t->input_string, name_buf) != 0) { printf ("failed comparing the re-parsed" " (\"%s\" should be \"%s\")\n", name_buf, t->input_string); val = 1; } ret = krb5_unparse_name_short(context, princ, &s); if (ret) krb5_err (context, 1, ret, "krb5_unparse_name_short"); if (strcmp (t->input_string, s) != 0) { printf ("failed comparing the re-parsed" " (\"%s\" should be \"%s\"\n", s, t->input_string); val = 1; } free(s); } krb5_free_principal (context, princ); } krb5_free_context(context); return val; } heimdal-7.5.0/lib/krb5/generate_subkey.c0000644000175000017500000000505413026237312016206 0ustar niknik/* * Copyright (c) 1997 - 2001 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "krb5_locl.h" /** * Generate subkey, from keyblock * * @param context kerberos context * @param key session key * @param etype encryption type of subkey, if ETYPE_NULL, use key's enctype * @param subkey returned new, free with krb5_free_keyblock(). * * @return 0 on success or a Kerberos 5 error code * * @ingroup krb5_crypto */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_generate_subkey_extended(krb5_context context, const krb5_keyblock *key, krb5_enctype etype, krb5_keyblock **subkey) { krb5_error_code ret; ALLOC(*subkey, 1); if (*subkey == NULL) return krb5_enomem(context); if (etype == (krb5_enctype)ETYPE_NULL) etype = key->keytype; /* use session key etype */ /* XXX should we use the session key as input to the RF? */ ret = krb5_generate_random_keyblock(context, etype, *subkey); if (ret != 0) { free(*subkey); *subkey = NULL; } return ret; } heimdal-7.5.0/lib/krb5/test_config.c0000644000175000017500000001766313026237312015347 0ustar niknik/* * Copyright (c) 2003 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of KTH nor the names of its contributors may be * used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY KTH AND ITS CONTRIBUTORS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL KTH OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "krb5_locl.h" #include static int check_config_file(krb5_context context, char *filelist, char **res, int def) { krb5_error_code ret; char **pp; int i; pp = NULL; if (def) ret = krb5_prepend_config_files_default(filelist, &pp); else ret = krb5_prepend_config_files(filelist, NULL, &pp); if (ret) krb5_err(context, 1, ret, "prepend_config_files"); for (i = 0; res[i] && pp[i]; i++) if (strcmp(pp[i], res[i]) != 0) krb5_errx(context, 1, "'%s' != '%s'", pp[i], res[i]); if (res[i] != NULL) krb5_errx(context, 1, "pp ended before res list"); if (def) { char **deflist; int j; ret = krb5_get_default_config_files(&deflist); if (ret) krb5_err(context, 1, ret, "get_default_config_files"); for (j = 0 ; pp[i] && deflist[j]; i++, j++) if (strcmp(pp[i], deflist[j]) != 0) krb5_errx(context, 1, "'%s' != '%s'", pp[i], deflist[j]); if (deflist[j] != NULL) krb5_errx(context, 1, "pp ended before def list"); krb5_free_config_files(deflist); } if (pp[i] != NULL) krb5_errx(context, 1, "pp ended after res (and def) list"); krb5_free_config_files(pp); return 0; } char *list0[] = { "/tmp/foo", NULL }; char *list1[] = { "/tmp/foo", "/tmp/foo/bar", NULL }; char *list2[] = { "", NULL }; struct { char *fl; char **res; } test[] = { { "/tmp/foo", NULL }, { "/tmp/foo" PATH_SEP "/tmp/foo/bar", NULL }, { "", NULL } }; static void check_config_files(void) { krb5_context context; krb5_error_code ret; int i; ret = krb5_init_context(&context); if (ret) errx(1, "krb5_init_context %d", ret); test[0].res = list0; test[1].res = list1; test[2].res = list2; for (i = 0; i < sizeof(test)/sizeof(*test); i++) { check_config_file(context, test[i].fl, test[i].res, 0); check_config_file(context, test[i].fl, test[i].res, 1); } krb5_free_context(context); } const char *config_string_result0[] = { "A", "B", "C", "D", NULL }; const char *config_string_result1[] = { "A", "B", "C D", NULL }; const char *config_string_result2[] = { "A", "B", "", NULL }; const char *config_string_result3[] = { "A B;C: D", NULL }; const char *config_string_result4[] = { "\"\"", "", "\"\"", NULL }; const char *config_string_result5[] = { "A\"BQd", NULL }; const char *config_string_result6[] = { "efgh\"", "ABC", NULL }; const char *config_string_result7[] = { "SnapeKills\\", "Dumbledore", NULL }; const char *config_string_result8[] = { "\"TownOf Sandwich: Massachusetts\"Oldest", "Town", "In", "Cape Cod", NULL }; const char *config_string_result9[] = { "\"Begins and\"ends", "In", "One", "String", NULL }; const char *config_string_result10[] = { "Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:", "1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.", "2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.", "3. Neither the name of the Institute nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.", "THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.", "Why do we test with such long strings? Because some people have config files", "That", "look", "Like this.", NULL }; const struct { const char * name; const char ** expected; } config_strings_tests[] = { { "foo", config_string_result0 }, { "bar", config_string_result1 }, { "baz", config_string_result2 }, { "quux", config_string_result3 }, { "questionable", config_string_result4 }, { "mismatch1", config_string_result5 }, { "mismatch2", config_string_result6 }, { "internal1", config_string_result7 }, { "internal2", config_string_result8 }, { "internal3", config_string_result9 }, { "longer_strings", config_string_result10 } }; static void check_escaped_strings(void) { krb5_context context; krb5_config_section *c = NULL; krb5_error_code ret; int i; ret = krb5_init_context(&context); if (ret) errx(1, "krb5_init_context %d", ret); ret = krb5_config_parse_file(context, "test_config_strings.out", &c); if (ret) krb5_errx(context, 1, "krb5_config_parse_file()"); for (i=0; i < sizeof(config_strings_tests)/sizeof(config_strings_tests[0]); i++) { char **ps; const char **s; const char **e; ps = krb5_config_get_strings(context, c, "escapes", config_strings_tests[i].name, NULL); if (ps == NULL) errx(1, "Failed to read string value %s", config_strings_tests[i].name); e = config_strings_tests[i].expected; for (s = (const char **)ps; *s && *e; s++, e++) { if (strcmp(*s, *e)) errx(1, "Unexpected configuration string at value [%s].\n" "Actual=[%s]\n" "Expected=[%s]\n", config_strings_tests[i].name, *s, *e); } if (*s || *e) errx(1, "Configuation string list for value [%s] has incorrect length.", config_strings_tests[i].name); krb5_config_free_strings(ps); } ret = krb5_config_file_free(context, c); if (ret) krb5_errx(context, 1, "krb5_config_file_free()"); krb5_free_context(context); } int main(int argc, char **argv) { check_config_files(); check_escaped_strings(); return 0; } heimdal-7.5.0/lib/krb5/keytab_keyfile.c0000644000175000017500000002451513026237312016024 0ustar niknik/* * Copyright (c) 1997 - 2007 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "krb5_locl.h" #ifndef HEIMDAL_SMALLER /* afs keyfile operations --------------------------------------- */ /* * Minimum tools to handle the AFS KeyFile. * * Format of the KeyFile is: * {[ ] * numkeys} * * It just adds to the end of the keyfile, deleting isn't implemented. * Use your favorite text/hex editor to delete keys. * */ #define AFS_SERVERTHISCELL "/usr/afs/etc/ThisCell" #define AFS_SERVERMAGICKRBCONF "/usr/afs/etc/krb.conf" struct akf_data { uint32_t num_entries; char *filename; char *cell; char *realm; }; /* * set `d->cell' and `d->realm' */ static int get_cell_and_realm (krb5_context context, struct akf_data *d) { FILE *f; char buf[BUFSIZ], *cp; int ret; f = fopen (AFS_SERVERTHISCELL, "r"); if (f == NULL) { ret = errno; krb5_set_error_message (context, ret, N_("Open ThisCell %s: %s", ""), AFS_SERVERTHISCELL, strerror(ret)); return ret; } if (fgets (buf, sizeof(buf), f) == NULL) { fclose (f); krb5_set_error_message (context, EINVAL, N_("No cell in ThisCell file %s", ""), AFS_SERVERTHISCELL); return EINVAL; } buf[strcspn(buf, "\n")] = '\0'; fclose(f); d->cell = strdup (buf); if (d->cell == NULL) return krb5_enomem(context); f = fopen (AFS_SERVERMAGICKRBCONF, "r"); if (f != NULL) { if (fgets (buf, sizeof(buf), f) == NULL) { free (d->cell); d->cell = NULL; fclose (f); krb5_set_error_message (context, EINVAL, N_("No realm in ThisCell file %s", ""), AFS_SERVERMAGICKRBCONF); return EINVAL; } buf[strcspn(buf, "\n")] = '\0'; fclose(f); } /* uppercase */ for (cp = buf; *cp != '\0'; cp++) *cp = toupper((unsigned char)*cp); d->realm = strdup (buf); if (d->realm == NULL) { free (d->cell); d->cell = NULL; return krb5_enomem(context); } return 0; } /* * init and get filename */ static krb5_error_code KRB5_CALLCONV akf_resolve(krb5_context context, const char *name, krb5_keytab id) { int ret; struct akf_data *d = calloc(1, sizeof (struct akf_data)); if (d == NULL) return krb5_enomem(context); d->num_entries = 0; ret = get_cell_and_realm (context, d); if (ret) { free (d); return ret; } d->filename = strdup (name); if (d->filename == NULL) { free (d->cell); free (d->realm); free (d); return krb5_enomem(context); } id->data = d; return 0; } /* * cleanup */ static krb5_error_code KRB5_CALLCONV akf_close(krb5_context context, krb5_keytab id) { struct akf_data *d = id->data; free (d->filename); free (d->cell); free (d); return 0; } /* * Return filename */ static krb5_error_code KRB5_CALLCONV akf_get_name(krb5_context context, krb5_keytab id, char *name, size_t name_sz) { struct akf_data *d = id->data; strlcpy (name, d->filename, name_sz); return 0; } /* * Init */ static krb5_error_code KRB5_CALLCONV akf_start_seq_get(krb5_context context, krb5_keytab id, krb5_kt_cursor *c) { int32_t ret; struct akf_data *d = id->data; c->fd = open (d->filename, O_RDONLY | O_BINARY | O_CLOEXEC, 0600); if (c->fd < 0) { ret = errno; krb5_set_error_message(context, ret, N_("keytab afs keyfile open %s failed: %s", ""), d->filename, strerror(ret)); return ret; } c->data = NULL; c->sp = krb5_storage_from_fd(c->fd); if (c->sp == NULL) { close(c->fd); krb5_clear_error_message (context); return KRB5_KT_NOTFOUND; } krb5_storage_set_eof_code(c->sp, KRB5_KT_END); ret = krb5_ret_uint32(c->sp, &d->num_entries); if(ret || d->num_entries > INT_MAX / 8) { krb5_storage_free(c->sp); close(c->fd); krb5_clear_error_message (context); if(ret == KRB5_KT_END) return KRB5_KT_NOTFOUND; return ret; } return 0; } static krb5_error_code KRB5_CALLCONV akf_next_entry(krb5_context context, krb5_keytab id, krb5_keytab_entry *entry, krb5_kt_cursor *cursor) { struct akf_data *d = id->data; int32_t kvno; off_t pos; int ret; pos = krb5_storage_seek(cursor->sp, 0, SEEK_CUR); if ((pos - 4) / (4 + 8) >= d->num_entries) return KRB5_KT_END; ret = krb5_make_principal (context, &entry->principal, d->realm, "afs", d->cell, NULL); if (ret) goto out; ret = krb5_ret_int32(cursor->sp, &kvno); if (ret) { krb5_free_principal (context, entry->principal); goto out; } entry->vno = kvno; if (cursor->data) entry->keyblock.keytype = ETYPE_DES_CBC_MD5; else entry->keyblock.keytype = ETYPE_DES_CBC_CRC; entry->keyblock.keyvalue.length = 8; entry->keyblock.keyvalue.data = malloc (8); if (entry->keyblock.keyvalue.data == NULL) { krb5_free_principal (context, entry->principal); ret = krb5_enomem(context); goto out; } ret = krb5_storage_read(cursor->sp, entry->keyblock.keyvalue.data, 8); if(ret != 8) ret = (ret < 0) ? errno : KRB5_KT_END; else ret = 0; entry->timestamp = time(NULL); entry->flags = 0; entry->aliases = NULL; out: if (cursor->data) { krb5_storage_seek(cursor->sp, pos + 4 + 8, SEEK_SET); cursor->data = NULL; } else cursor->data = cursor; return ret; } static krb5_error_code KRB5_CALLCONV akf_end_seq_get(krb5_context context, krb5_keytab id, krb5_kt_cursor *cursor) { krb5_storage_free(cursor->sp); close(cursor->fd); cursor->data = NULL; return 0; } static krb5_error_code KRB5_CALLCONV akf_add_entry(krb5_context context, krb5_keytab id, krb5_keytab_entry *entry) { struct akf_data *d = id->data; int fd, created = 0; krb5_error_code ret; int32_t len; krb5_storage *sp; if (entry->keyblock.keyvalue.length != 8) return 0; switch(entry->keyblock.keytype) { case ETYPE_DES_CBC_CRC: case ETYPE_DES_CBC_MD4: case ETYPE_DES_CBC_MD5: break; default: return 0; } fd = open (d->filename, O_RDWR | O_BINARY | O_CLOEXEC); if (fd < 0) { fd = open (d->filename, O_RDWR | O_BINARY | O_CREAT | O_EXCL | O_CLOEXEC, 0600); if (fd < 0) { ret = errno; krb5_set_error_message(context, ret, N_("open keyfile(%s): %s", ""), d->filename, strerror(ret)); return ret; } created = 1; } sp = krb5_storage_from_fd(fd); if(sp == NULL) { close(fd); return krb5_enomem(context); } if (created) len = 0; else { if(krb5_storage_seek(sp, 0, SEEK_SET) < 0) { ret = errno; krb5_storage_free(sp); close(fd); krb5_set_error_message(context, ret, N_("seeking in keyfile: %s", ""), strerror(ret)); return ret; } ret = krb5_ret_int32(sp, &len); if(ret) { krb5_storage_free(sp); close(fd); return ret; } } /* * Make sure we don't add the entry twice, assumes the DES * encryption types are all the same key. */ if (len > 0) { int32_t kvno; int i; for (i = 0; i < len; i++) { ret = krb5_ret_int32(sp, &kvno); if (ret) { krb5_set_error_message (context, ret, N_("Failed getting kvno from keyfile", "")); goto out; } if(krb5_storage_seek(sp, 8, SEEK_CUR) < 0) { ret = errno; krb5_set_error_message (context, ret, N_("Failed seeing in keyfile: %s", ""), strerror(ret)); goto out; } if (kvno == entry->vno) { ret = 0; goto out; } } } len++; if(krb5_storage_seek(sp, 0, SEEK_SET) < 0) { ret = errno; krb5_set_error_message (context, ret, N_("Failed seeing in keyfile: %s", ""), strerror(ret)); goto out; } ret = krb5_store_int32(sp, len); if(ret) { ret = errno; krb5_set_error_message (context, ret, N_("keytab keyfile failed new length", "")); return ret; } if(krb5_storage_seek(sp, (len - 1) * (8 + 4), SEEK_CUR) < 0) { ret = errno; krb5_set_error_message (context, ret, N_("seek to end: %s", ""), strerror(ret)); goto out; } ret = krb5_store_int32(sp, entry->vno); if(ret) { krb5_set_error_message(context, ret, N_("keytab keyfile failed store kvno", "")); goto out; } ret = krb5_storage_write(sp, entry->keyblock.keyvalue.data, entry->keyblock.keyvalue.length); if(ret != entry->keyblock.keyvalue.length) { if (ret < 0) ret = errno; else ret = ENOTTY; krb5_set_error_message(context, ret, N_("keytab keyfile failed to add key", "")); goto out; } ret = 0; out: krb5_storage_free(sp); close (fd); return ret; } const krb5_kt_ops krb5_akf_ops = { "AFSKEYFILE", akf_resolve, akf_get_name, akf_close, NULL, /* destroy */ NULL, /* get */ akf_start_seq_get, akf_next_entry, akf_end_seq_get, akf_add_entry, NULL, /* remove */ NULL, 0 }; #endif /* HEIMDAL_SMALLER */ heimdal-7.5.0/lib/krb5/krb5_string_to_key.cat30000644000175000017500000001301313212450757017246 0ustar niknik KRB5_STRING_TO_KEY(3) BSD Library Functions Manual KRB5_STRING_TO_KEY(3) NNAAMMEE kkrrbb55__ssttrriinngg__ttoo__kkeeyy, kkrrbb55__ssttrriinngg__ttoo__kkeeyy__ddaattaa, kkrrbb55__ssttrriinngg__ttoo__kkeeyy__ddaattaa__ssaalltt, kkrrbb55__ssttrriinngg__ttoo__kkeeyy__ddaattaa__ssaalltt__ooppaaqquuee, kkrrbb55__ssttrriinngg__ttoo__kkeeyy__ssaalltt, kkrrbb55__ssttrriinngg__ttoo__kkeeyy__ssaalltt__ooppaaqquuee, kkrrbb55__ggeett__ppww__ssaalltt, kkrrbb55__ffrreeee__ssaalltt -- turns a string to a Kerberos key LLIIBBRRAARRYY Kerberos 5 Library (libkrb5, -lkrb5) SSYYNNOOPPSSIISS ##iinncclluuddee <> _k_r_b_5___e_r_r_o_r___c_o_d_e kkrrbb55__ssttrriinngg__ttoo__kkeeyy(_k_r_b_5___c_o_n_t_e_x_t _c_o_n_t_e_x_t, _k_r_b_5___e_n_c_t_y_p_e _e_n_c_t_y_p_e, _c_o_n_s_t _c_h_a_r _*_p_a_s_s_w_o_r_d, _k_r_b_5___p_r_i_n_c_i_p_a_l _p_r_i_n_c_i_p_a_l, _k_r_b_5___k_e_y_b_l_o_c_k _*_k_e_y); _k_r_b_5___e_r_r_o_r___c_o_d_e kkrrbb55__ssttrriinngg__ttoo__kkeeyy__ddaattaa(_k_r_b_5___c_o_n_t_e_x_t _c_o_n_t_e_x_t, _k_r_b_5___e_n_c_t_y_p_e _e_n_c_t_y_p_e, _k_r_b_5___d_a_t_a _p_a_s_s_w_o_r_d, _k_r_b_5___p_r_i_n_c_i_p_a_l _p_r_i_n_c_i_p_a_l, _k_r_b_5___k_e_y_b_l_o_c_k _*_k_e_y); _k_r_b_5___e_r_r_o_r___c_o_d_e kkrrbb55__ssttrriinngg__ttoo__kkeeyy__ddaattaa__ssaalltt(_k_r_b_5___c_o_n_t_e_x_t _c_o_n_t_e_x_t, _k_r_b_5___e_n_c_t_y_p_e _e_n_c_t_y_p_e, _k_r_b_5___d_a_t_a _p_a_s_s_w_o_r_d, _k_r_b_5___s_a_l_t _s_a_l_t, _k_r_b_5___k_e_y_b_l_o_c_k _*_k_e_y); _k_r_b_5___e_r_r_o_r___c_o_d_e kkrrbb55__ssttrriinngg__ttoo__kkeeyy__ddaattaa__ssaalltt__ooppaaqquuee(_k_r_b_5___c_o_n_t_e_x_t _c_o_n_t_e_x_t, _k_r_b_5___e_n_c_t_y_p_e _e_n_c_t_y_p_e, _k_r_b_5___d_a_t_a _p_a_s_s_w_o_r_d, _k_r_b_5___s_a_l_t _s_a_l_t, _k_r_b_5___d_a_t_a _o_p_a_q_u_e, _k_r_b_5___k_e_y_b_l_o_c_k _*_k_e_y); _k_r_b_5___e_r_r_o_r___c_o_d_e kkrrbb55__ssttrriinngg__ttoo__kkeeyy__ssaalltt(_k_r_b_5___c_o_n_t_e_x_t _c_o_n_t_e_x_t, _k_r_b_5___e_n_c_t_y_p_e _e_n_c_t_y_p_e, _c_o_n_s_t _c_h_a_r _*_p_a_s_s_w_o_r_d, _k_r_b_5___s_a_l_t _s_a_l_t, _k_r_b_5___k_e_y_b_l_o_c_k _*_k_e_y); _k_r_b_5___e_r_r_o_r___c_o_d_e kkrrbb55__ssttrriinngg__ttoo__kkeeyy__ssaalltt__ooppaaqquuee(_k_r_b_5___c_o_n_t_e_x_t _c_o_n_t_e_x_t, _k_r_b_5___e_n_c_t_y_p_e _e_n_c_t_y_p_e, _c_o_n_s_t _c_h_a_r _*_p_a_s_s_w_o_r_d, _k_r_b_5___s_a_l_t _s_a_l_t, _k_r_b_5___d_a_t_a _o_p_a_q_u_e, _k_r_b_5___k_e_y_b_l_o_c_k _*_k_e_y); _k_r_b_5___e_r_r_o_r___c_o_d_e kkrrbb55__ggeett__ppww__ssaalltt(_k_r_b_5___c_o_n_t_e_x_t _c_o_n_t_e_x_t, _k_r_b_5___c_o_n_s_t___p_r_i_n_c_i_p_a_l _p_r_i_n_c_i_p_a_l, _k_r_b_5___s_a_l_t _*_s_a_l_t); _k_r_b_5___e_r_r_o_r___c_o_d_e kkrrbb55__ffrreeee__ssaalltt(_k_r_b_5___c_o_n_t_e_x_t _c_o_n_t_e_x_t, _k_r_b_5___s_a_l_t _s_a_l_t); DDEESSCCRRIIPPTTIIOONN The string to key functions convert a string to a kerberos key. kkrrbb55__ssttrriinngg__ttoo__kkeeyy__ddaattaa__ssaalltt__ooppaaqquuee() is the function that does all the work, the rest of the functions are just wrappers around kkrrbb55__ssttrriinngg__ttoo__kkeeyy__ddaattaa__ssaalltt__ooppaaqquuee() that calls it with default values. kkrrbb55__ssttrriinngg__ttoo__kkeeyy__ddaattaa__ssaalltt__ooppaaqquuee() transforms the _p_a_s_s_w_o_r_d with the given salt-string _s_a_l_t and the opaque, encryption type specific parameter _o_p_a_q_u_e to a encryption key _k_e_y according to the string to key function associated with _e_n_c_t_y_p_e. The _k_e_y should be freed with kkrrbb55__ffrreeee__kkeeyybblloocckk__ccoonntteennttss(). If one of the functions that doesn't take a krb5_salt as it argument kkrrbb55__ggeett__ppww__ssaalltt() is used to get the salt value. kkrrbb55__ggeett__ppww__ssaalltt() get the default password salt for a principal, use kkrrbb55__ffrreeee__ssaalltt() to free the salt when done. kkrrbb55__ffrreeee__ssaalltt() frees the content of _s_a_l_t. SSEEEE AALLSSOO krb5(3), krb5_data(3), krb5_keyblock(3), kerberos(8) HEIMDAL July 10, 2006 HEIMDAL heimdal-7.5.0/lib/krb5/krb5_creds.30000644000175000017500000000647313026237312015003 0ustar niknik.\" Copyright (c) 2004, 2006 Kungliga Tekniska Högskolan .\" (Royal Institute of Technology, Stockholm, Sweden). .\" All rights reserved. .\" .\" Redistribution and use in source and binary forms, with or without .\" modification, are permitted provided that the following conditions .\" are met: .\" .\" 1. Redistributions of source code must retain the above copyright .\" notice, this list of conditions and the following disclaimer. .\" .\" 2. Redistributions in binary form must reproduce the above copyright .\" notice, this list of conditions and the following disclaimer in the .\" documentation and/or other materials provided with the distribution. .\" .\" 3. Neither the name of the Institute nor the names of its contributors .\" may be used to endorse or promote products derived from this software .\" without specific prior written permission. .\" .\" THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND .\" ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE .\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE .\" ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE .\" FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL .\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS .\" OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) .\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT .\" LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF .\" SUCH DAMAGE. .\" .\" $Id$ .\" .Dd May 1, 2006 .Dt KRB5_CREDS 3 .Os HEIMDAL .Sh NAME .Nm krb5_creds , .Nm krb5_copy_creds , .Nm krb5_copy_creds_contents , .Nm krb5_free_creds , .Nm krb5_free_cred_contents .Nd Kerberos 5 credential handling functions .Sh LIBRARY Kerberos 5 Library (libkrb5, -lkrb5) .Sh SYNOPSIS .In krb5.h .Ft krb5_error_code .Fo krb5_copy_creds .Fa "krb5_context context" .Fa "const krb5_creds *incred" .Fa "krb5_creds **outcred" .Fc .Ft krb5_error_code .Fo krb5_copy_creds_contents .Fa "krb5_context context" .Fa "const krb5_creds *incred" .Fa "krb5_creds *outcred" .Fc .Ft krb5_error_code .Fo krb5_free_creds .Fa "krb5_context context" .Fa "krb5_creds *outcred" .Fc .Ft krb5_error_code .Fo krb5_free_cred_contents .Fa "krb5_context context" .Fa "krb5_creds *cred" .Fc .Sh DESCRIPTION .Vt krb5_creds holds Kerberos credentials: .Bd -literal -offset typedef struct krb5_creds { krb5_principal client; krb5_principal server; krb5_keyblock session; krb5_times times; krb5_data ticket; krb5_data second_ticket; krb5_authdata authdata; krb5_addresses addresses; krb5_ticket_flags flags; } krb5_creds; .Ed .Pp .Fn krb5_copy_creds makes a copy of .Fa incred to .Fa outcred . .Fa outcred should be freed with .Fn krb5_free_creds by the caller. .Pp .Fn krb5_copy_creds_contents makes a copy of the content of .Fa incred to .Fa outcreds . .Fa outcreds should be freed by the called with .Fn krb5_free_creds_contents . .Pp .Fn krb5_free_creds frees the content of the .Fa cred structure and the structure itself. .Pp .Fn krb5_free_cred_contents frees the content of the .Fa cred structure. .Sh SEE ALSO .Xr krb5 3 , .Xr krb5_compare_creds 3 , .Xr krb5_get_init_creds 3 , .Xr kerberos 8 heimdal-7.5.0/lib/krb5/mk_error.c0000644000175000017500000000761613211617637014670 0ustar niknik/* * Copyright (c) 1997 - 2003 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "krb5_locl.h" KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_mk_error_ext(krb5_context context, krb5_error_code error_code, const char *e_text, const krb5_data *e_data, const krb5_principal server, const PrincipalName *client_name, const Realm *client_realm, time_t *client_time, int *client_usec, krb5_data *reply) { const char *e_text2 = NULL; KRB_ERROR msg; krb5_timestamp sec; int32_t usec; size_t len = 0; krb5_error_code ret = 0; krb5_us_timeofday (context, &sec, &usec); memset(&msg, 0, sizeof(msg)); msg.pvno = 5; msg.msg_type = krb_error; msg.stime = sec; msg.susec = usec; msg.ctime = client_time; msg.cusec = client_usec; /* Make sure we only send `protocol' error codes */ if(error_code < KRB5KDC_ERR_NONE || error_code >= KRB5_ERR_RCSID) { if(e_text == NULL) e_text = e_text2 = krb5_get_error_message(context, error_code); error_code = KRB5KRB_ERR_GENERIC; } msg.error_code = error_code - KRB5KDC_ERR_NONE; if (e_text) msg.e_text = rk_UNCONST(&e_text); if (e_data) msg.e_data = rk_UNCONST(e_data); if(server){ msg.realm = server->realm; msg.sname = server->name; }else{ static char unspec[] = ""; msg.realm = unspec; } msg.crealm = rk_UNCONST(client_realm); msg.cname = rk_UNCONST(client_name); ASN1_MALLOC_ENCODE(KRB_ERROR, reply->data, reply->length, &msg, &len, ret); if (e_text2) krb5_free_error_message(context, e_text2); if (ret) return ret; if(reply->length != len) krb5_abortx(context, "internal error in ASN.1 encoder"); return 0; } KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_mk_error(krb5_context context, krb5_error_code error_code, const char *e_text, const krb5_data *e_data, const krb5_principal client, const krb5_principal server, time_t *client_time, int *client_usec, krb5_data *reply) { const PrincipalName *client_name = NULL; const Realm *client_realm = NULL; if (client) { client_realm = &client->realm; client_name = &client->name; } return krb5_mk_error_ext(context, error_code, e_text, e_data, server, client_name, client_realm, client_time, client_usec, reply); } heimdal-7.5.0/lib/krb5/krb5_rd_error.30000644000175000017500000000652512136107750015522 0ustar niknik.\" Copyright (c) 2004 Kungliga Tekniska Högskolan .\" (Royal Institute of Technology, Stockholm, Sweden). .\" All rights reserved. .\" .\" Redistribution and use in source and binary forms, with or without .\" modification, are permitted provided that the following conditions .\" are met: .\" .\" 1. Redistributions of source code must retain the above copyright .\" notice, this list of conditions and the following disclaimer. .\" .\" 2. Redistributions in binary form must reproduce the above copyright .\" notice, this list of conditions and the following disclaimer in the .\" documentation and/or other materials provided with the distribution. .\" .\" 3. Neither the name of the Institute nor the names of its contributors .\" may be used to endorse or promote products derived from this software .\" without specific prior written permission. .\" .\" THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND .\" ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE .\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE .\" ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE .\" FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL .\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS .\" OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) .\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT .\" LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF .\" SUCH DAMAGE. .\" .\" $Id$ .\" .Dd July 26, 2004 .Dt KRB5_RD_ERROR 3 .Os HEIMDAL .Sh NAME .Nm krb5_rd_error , .Nm krb5_free_error , .Nm krb5_free_error_contents , .Nm krb5_error_from_rd_error .Nd parse, free and read error from KRB-ERROR message .Sh LIBRARY Kerberos 5 Library (libkrb5, -lkrb5) .Sh SYNOPSIS .In krb5.h .Ft krb5_error_code .Fo krb5_rd_error .Fa "krb5_context context" .Fa "const krb5_data *msg" .Fa "KRB_ERROR *result" .Fc .Ft void .Fo krb5_free_error .Fa "krb5_context context" .Fa "krb5_error *error" .Fc .Ft void .Fo krb5_free_error_contents .Fa "krb5_context context" .Fa "krb5_error *error" .Fc .Ft krb5_error_code .Fo krb5_error_from_rd_error .Fa "krb5_context context" .Fa "const krb5_error *error" .Fa "const krb5_creds *creds" .Fc .Sh DESCRIPTION Usually applications never needs to parse and understand Kerberos error messages since higher level functions will parse and push up the error in the krb5_context. These functions are described for completeness. .Pp .Fn krb5_rd_error parses and returns the kerboeros error message, the structure should be freed with .Fn krb5_free_error_contents when the caller is done with the structure. .Pp .Fn krb5_free_error frees the content and the memory region holding the structure iself. .Pp .Fn krb5_free_error_contents free the content of the KRB-ERROR message. .Pp .Fn krb5_error_from_rd_error will parse the error message and set the error buffer in krb5_context to the error string passed back or the matching error code in the KRB-ERROR message. Caller should pick up the message with .Fn krb5_get_error_string 3 (don't forget to free the returned string with .Fn krb5_free_error_string ) . .Sh SEE ALSO .Xr krb5 3 , .Xr krb5_set_error_string 3 , .Xr krb5_get_error_string 3 , .Xr krb5.conf 5 heimdal-7.5.0/lib/krb5/krb5_rd_error.cat30000644000175000017500000000565113212450757016215 0ustar niknik KRB5_RD_ERROR(3) BSD Library Functions Manual KRB5_RD_ERROR(3) NNAAMMEE kkrrbb55__rrdd__eerrrroorr, kkrrbb55__ffrreeee__eerrrroorr, kkrrbb55__ffrreeee__eerrrroorr__ccoonntteennttss, kkrrbb55__eerrrroorr__ffrroomm__rrdd__eerrrroorr -- parse, free and read error from KRB-ERROR message LLIIBBRRAARRYY Kerberos 5 Library (libkrb5, -lkrb5) SSYYNNOOPPSSIISS ##iinncclluuddee <> _k_r_b_5___e_r_r_o_r___c_o_d_e kkrrbb55__rrdd__eerrrroorr(_k_r_b_5___c_o_n_t_e_x_t _c_o_n_t_e_x_t, _c_o_n_s_t _k_r_b_5___d_a_t_a _*_m_s_g, _K_R_B___E_R_R_O_R _*_r_e_s_u_l_t); _v_o_i_d kkrrbb55__ffrreeee__eerrrroorr(_k_r_b_5___c_o_n_t_e_x_t _c_o_n_t_e_x_t, _k_r_b_5___e_r_r_o_r _*_e_r_r_o_r); _v_o_i_d kkrrbb55__ffrreeee__eerrrroorr__ccoonntteennttss(_k_r_b_5___c_o_n_t_e_x_t _c_o_n_t_e_x_t, _k_r_b_5___e_r_r_o_r _*_e_r_r_o_r); _k_r_b_5___e_r_r_o_r___c_o_d_e kkrrbb55__eerrrroorr__ffrroomm__rrdd__eerrrroorr(_k_r_b_5___c_o_n_t_e_x_t _c_o_n_t_e_x_t, _c_o_n_s_t _k_r_b_5___e_r_r_o_r _*_e_r_r_o_r, _c_o_n_s_t _k_r_b_5___c_r_e_d_s _*_c_r_e_d_s); DDEESSCCRRIIPPTTIIOONN Usually applications never needs to parse and understand Kerberos error messages since higher level functions will parse and push up the error in the krb5_context. These functions are described for completeness. kkrrbb55__rrdd__eerrrroorr() parses and returns the kerboeros error message, the structure should be freed with kkrrbb55__ffrreeee__eerrrroorr__ccoonntteennttss() when the caller is done with the structure. kkrrbb55__ffrreeee__eerrrroorr() frees the content and the memory region holding the structure iself. kkrrbb55__ffrreeee__eerrrroorr__ccoonntteennttss() free the content of the KRB-ERROR message. kkrrbb55__eerrrroorr__ffrroomm__rrdd__eerrrroorr() will parse the error message and set the error buffer in krb5_context to the error string passed back or the matching error code in the KRB-ERROR message. Caller should pick up the message with kkrrbb55__ggeett__eerrrroorr__ssttrriinngg(_3) (don't forget to free the returned string with kkrrbb55__ffrreeee__eerrrroorr__ssttrriinngg()). SSEEEE AALLSSOO krb5(3), krb5_set_error_string(3), krb5_get_error_string(3), krb5.conf(5) HEIMDAL July 26, 2004 HEIMDAL heimdal-7.5.0/lib/krb5/appdefault.c0000644000175000017500000001064213026237312015156 0ustar niknik/* * Copyright (c) 2000 - 2001 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "krb5_locl.h" KRB5_LIB_FUNCTION void KRB5_LIB_CALL krb5_appdefault_boolean(krb5_context context, const char *appname, krb5_const_realm realm, const char *option, krb5_boolean def_val, krb5_boolean *ret_val) { if(appname == NULL) appname = getprogname(); def_val = krb5_config_get_bool_default(context, NULL, def_val, "libdefaults", option, NULL); if(realm != NULL) def_val = krb5_config_get_bool_default(context, NULL, def_val, "realms", realm, option, NULL); def_val = krb5_config_get_bool_default(context, NULL, def_val, "appdefaults", option, NULL); if(realm != NULL) def_val = krb5_config_get_bool_default(context, NULL, def_val, "appdefaults", realm, option, NULL); if(appname != NULL) { def_val = krb5_config_get_bool_default(context, NULL, def_val, "appdefaults", appname, option, NULL); if(realm != NULL) def_val = krb5_config_get_bool_default(context, NULL, def_val, "appdefaults", appname, realm, option, NULL); } *ret_val = def_val; } KRB5_LIB_FUNCTION void KRB5_LIB_CALL krb5_appdefault_string(krb5_context context, const char *appname, krb5_const_realm realm, const char *option, const char *def_val, char **ret_val) { if(appname == NULL) appname = getprogname(); def_val = krb5_config_get_string_default(context, NULL, def_val, "libdefaults", option, NULL); if(realm != NULL) def_val = krb5_config_get_string_default(context, NULL, def_val, "realms", realm, option, NULL); def_val = krb5_config_get_string_default(context, NULL, def_val, "appdefaults", option, NULL); if(realm != NULL) def_val = krb5_config_get_string_default(context, NULL, def_val, "appdefaults", realm, option, NULL); if(appname != NULL) { def_val = krb5_config_get_string_default(context, NULL, def_val, "appdefaults", appname, option, NULL); if(realm != NULL) def_val = krb5_config_get_string_default(context, NULL, def_val, "appdefaults", appname, realm, option, NULL); } if(def_val != NULL) *ret_val = strdup(def_val); else *ret_val = NULL; } KRB5_LIB_FUNCTION void KRB5_LIB_CALL krb5_appdefault_time(krb5_context context, const char *appname, krb5_const_realm realm, const char *option, time_t def_val, time_t *ret_val) { krb5_deltat t; char *val; krb5_appdefault_string(context, appname, realm, option, NULL, &val); if (val == NULL) { *ret_val = def_val; return; } if (krb5_string_to_deltat(val, &t)) *ret_val = def_val; else *ret_val = t; free(val); } heimdal-7.5.0/lib/krb5/generate_seq_number.c0000644000175000017500000000404312136107750017044 0ustar niknik/* * Copyright (c) 1997 - 2001 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "krb5_locl.h" KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_generate_seq_number(krb5_context context, const krb5_keyblock *key, uint32_t *seqno) { if (RAND_bytes((void *)seqno, sizeof(*seqno)) <= 0) krb5_abortx(context, "Failed to generate random block"); /* MIT used signed numbers, lets not stomp into that space directly */ *seqno &= 0x3fffffff; if (*seqno == 0) *seqno = 1; return 0; } heimdal-7.5.0/lib/krb5/test_hostname.c0000644000175000017500000000751112136107750015712 0ustar niknik/* * Copyright (c) 2005 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of KTH nor the names of its contributors may be * used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY KTH AND ITS CONTRIBUTORS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL KTH OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "krb5_locl.h" #include #include static int debug_flag = 0; static int version_flag = 0; static int help_flag = 0; static int expand_hostname(krb5_context context, const char *host) { krb5_error_code ret; char *h, **r; ret = krb5_expand_hostname(context, host, &h); if (ret) krb5_err(context, 1, ret, "krb5_expand_hostname(%s)", host); free(h); if (debug_flag) printf("hostname: %s -> %s\n", host, h); ret = krb5_expand_hostname_realms(context, host, &h, &r); if (ret) krb5_err(context, 1, ret, "krb5_expand_hostname_realms(%s)", host); if (debug_flag) { int j; printf("hostname: %s -> %s\n", host, h); for (j = 0; r[j]; j++) { printf("\trealm: %s\n", r[j]); } } free(h); krb5_free_host_realm(context, r); return 0; } static int test_expand_hostname(krb5_context context) { int i, errors = 0; struct t { krb5_error_code ret; const char *orig_hostname; const char *new_hostname; } tests[] = { { 0, "pstn1.su.se", "pstn1.su.se" }, { 0, "pstnproxy.su.se", "pstnproxy.su.se" }, }; for (i = 0; i < sizeof(tests)/sizeof(tests[0]); i++) { errors += expand_hostname(context, tests[i].orig_hostname); } return errors; } static struct getargs args[] = { {"debug", 'd', arg_flag, &debug_flag, "turn on debuggin", NULL }, {"version", 0, arg_flag, &version_flag, "print version", NULL }, {"help", 0, arg_flag, &help_flag, NULL, NULL } }; static void usage (int ret) { arg_printusage (args, sizeof(args)/sizeof(*args), NULL, "hostname ..."); exit (ret); } int main(int argc, char **argv) { krb5_context context; krb5_error_code ret; int optidx = 0, errors = 0; setprogname(argv[0]); if(getarg(args, sizeof(args) / sizeof(args[0]), argc, argv, &optidx)) usage(1); if (help_flag) usage (0); if(version_flag){ print_version(NULL); exit(0); } argc -= optidx; argv += optidx; ret = krb5_init_context(&context); if (ret) errx (1, "krb5_init_context failed: %d", ret); if (argc > 0) { while (argc-- > 0) errors += expand_hostname(context, *argv++); return errors; } errors += test_expand_hostname(context); krb5_free_context(context); return errors; } heimdal-7.5.0/lib/krb5/krb5_get_krbhst.cat30000644000175000017500000000600613212450756016525 0ustar niknik KRB5_GET_KRBHST(3) BSD Library Functions Manual KRB5_GET_KRBHST(3) NNAAMMEE kkrrbb55__ggeett__kkrrbbhhsstt, kkrrbb55__ggeett__kkrrbb__aaddmmiinn__hhsstt, kkrrbb55__ggeett__kkrrbb__cchhaannggeeppww__hhsstt, kkrrbb55__ggeett__kkrrbb552244hhsstt, kkrrbb55__ffrreeee__kkrrbbhhsstt -- lookup Kerberos KDC hosts LLIIBBRRAARRYY Kerberos 5 Library (libkrb5, -lkrb5) SSYYNNOOPPSSIISS ##iinncclluuddee <> _k_r_b_5___e_r_r_o_r___c_o_d_e kkrrbb55__ggeett__kkrrbbhhsstt(_k_r_b_5___c_o_n_t_e_x_t _c_o_n_t_e_x_t, _c_o_n_s_t _k_r_b_5___r_e_a_l_m _*_r_e_a_l_m, _c_h_a_r _*_*_*_h_o_s_t_l_i_s_t); _k_r_b_5___e_r_r_o_r___c_o_d_e kkrrbb55__ggeett__kkrrbb__aaddmmiinn__hhsstt(_k_r_b_5___c_o_n_t_e_x_t _c_o_n_t_e_x_t, _c_o_n_s_t _k_r_b_5___r_e_a_l_m _*_r_e_a_l_m, _c_h_a_r _*_*_*_h_o_s_t_l_i_s_t); _k_r_b_5___e_r_r_o_r___c_o_d_e kkrrbb55__ggeett__kkrrbb__cchhaannggeeppww__hhsstt(_k_r_b_5___c_o_n_t_e_x_t _c_o_n_t_e_x_t, _c_o_n_s_t _k_r_b_5___r_e_a_l_m _*_r_e_a_l_m, _c_h_a_r _*_*_*_h_o_s_t_l_i_s_t); _k_r_b_5___e_r_r_o_r___c_o_d_e kkrrbb55__ggeett__kkrrbb552244hhsstt(_k_r_b_5___c_o_n_t_e_x_t _c_o_n_t_e_x_t, _c_o_n_s_t _k_r_b_5___r_e_a_l_m _*_r_e_a_l_m, _c_h_a_r _*_*_*_h_o_s_t_l_i_s_t); _k_r_b_5___e_r_r_o_r___c_o_d_e kkrrbb55__ffrreeee__kkrrbbhhsstt(_k_r_b_5___c_o_n_t_e_x_t _c_o_n_t_e_x_t, _c_h_a_r _*_*_h_o_s_t_l_i_s_t); DDEESSCCRRIIPPTTIIOONN These functions implement the old API to get a list of Kerberos hosts, and are thus similar to the kkrrbb55__kkrrbbhhsstt__iinniitt() functions. However, since these functions returns _a_l_l hosts in one go, they potentially have to do more lookups than necessary. These functions remain for compatibility reasons. After a call to one of these functions, _h_o_s_t_l_i_s_t is a NULL terminated list of strings, pointing to the requested Kerberos hosts. These should be freed with kkrrbb55__ffrreeee__kkrrbbhhsstt() when done with. EEXXAAMMPPLLEESS The following code will print the KDCs of the realm ``MY.REALM''. char **hosts, **p; krb5_get_krbhst(context, "MY.REALM", &hosts); for(p = hosts; *p; p++) printf("%s\n", *p); krb5_free_krbhst(context, hosts); SSEEEE AALLSSOO krb5_krbhst_init(3) HEIMDAL April 24, 2005 HEIMDAL heimdal-7.5.0/lib/krb5/test_prf.c0000644000175000017500000000632612136107750014666 0ustar niknik/* * Copyright (c) 2007 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of KTH nor the names of its contributors may be * used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY KTH AND ITS CONTRIBUTORS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL KTH OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "krb5_locl.h" #include #include /* * key: string2key(aes256, "testkey", "testkey", default_params) * input: unhex(1122334455667788) * output: 58b594b8a61df6e9439b7baa991ff5c1 * * key: string2key(aes128, "testkey", "testkey", default_params) * input: unhex(1122334455667788) * output: ffa2f823aa7f83a8ce3c5fb730587129 */ int main(int argc, char **argv) { krb5_context context; krb5_error_code ret; krb5_keyblock key; krb5_crypto crypto; size_t length; krb5_data input, output, output2; krb5_enctype etype = ETYPE_AES256_CTS_HMAC_SHA1_96; ret = krb5_init_context(&context); if (ret) errx(1, "krb5_init_context %d", ret); ret = krb5_generate_random_keyblock(context, etype, &key); if (ret) krb5_err(context, 1, ret, "krb5_generate_random_keyblock"); ret = krb5_crypto_prf_length(context, etype, &length); if (ret) krb5_err(context, 1, ret, "krb5_crypto_prf_length"); ret = krb5_crypto_init(context, &key, 0, &crypto); if (ret) krb5_err(context, 1, ret, "krb5_crypto_init"); input.data = rk_UNCONST("foo"); input.length = 3; ret = krb5_crypto_prf(context, crypto, &input, &output); if (ret) krb5_err(context, 1, ret, "krb5_crypto_prf"); ret = krb5_crypto_prf(context, crypto, &input, &output2); if (ret) krb5_err(context, 1, ret, "krb5_crypto_prf"); if (krb5_data_cmp(&output, &output2) != 0) krb5_errx(context, 1, "krb5_data_cmp"); krb5_data_free(&output); krb5_data_free(&output2); krb5_crypto_destroy(context, crypto); krb5_free_keyblock_contents(context, &key); krb5_free_context(context); return 0; } heimdal-7.5.0/lib/krb5/mk_safe.c0000644000175000017500000001055613026237312014442 0ustar niknik/* * Copyright (c) 1997 - 2003 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "krb5_locl.h" KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_mk_safe(krb5_context context, krb5_auth_context auth_context, const krb5_data *userdata, krb5_data *outbuf, krb5_replay_data *outdata) { krb5_error_code ret; KRB_SAFE s; u_char *buf = NULL; size_t buf_size; size_t len = 0; krb5_crypto crypto; krb5_keyblock *key; krb5_replay_data rdata; if ((auth_context->flags & (KRB5_AUTH_CONTEXT_RET_TIME | KRB5_AUTH_CONTEXT_RET_SEQUENCE)) && outdata == NULL) return KRB5_RC_REQUIRED; /* XXX better error, MIT returns this */ if (auth_context->local_subkey) key = auth_context->local_subkey; else if (auth_context->remote_subkey) key = auth_context->remote_subkey; else key = auth_context->keyblock; s.pvno = 5; s.msg_type = krb_safe; memset(&rdata, 0, sizeof(rdata)); s.safe_body.user_data = *userdata; krb5_us_timeofday (context, &rdata.timestamp, &rdata.usec); if (auth_context->flags & KRB5_AUTH_CONTEXT_DO_TIME) { s.safe_body.timestamp = &rdata.timestamp; s.safe_body.usec = &rdata.usec; } else { s.safe_body.timestamp = NULL; s.safe_body.usec = NULL; } if (auth_context->flags & KRB5_AUTH_CONTEXT_RET_TIME) { outdata->timestamp = rdata.timestamp; outdata->usec = rdata.usec; } if (auth_context->flags & KRB5_AUTH_CONTEXT_DO_SEQUENCE) { rdata.seq = auth_context->local_seqnumber; s.safe_body.seq_number = &rdata.seq; } else s.safe_body.seq_number = NULL; if (auth_context->flags & KRB5_AUTH_CONTEXT_RET_SEQUENCE) outdata->seq = auth_context->local_seqnumber; s.safe_body.s_address = auth_context->local_address; s.safe_body.r_address = auth_context->remote_address; s.cksum.cksumtype = 0; s.cksum.checksum.data = NULL; s.cksum.checksum.length = 0; ASN1_MALLOC_ENCODE(KRB_SAFE, buf, buf_size, &s, &len, ret); if (ret) return ret; if(buf_size != len) krb5_abortx(context, "internal error in ASN.1 encoder"); ret = krb5_crypto_init(context, key, 0, &crypto); if (ret) { free (buf); return ret; } ret = krb5_create_checksum(context, crypto, KRB5_KU_KRB_SAFE_CKSUM, 0, buf, len, &s.cksum); krb5_crypto_destroy(context, crypto); if (ret) { free (buf); return ret; } free(buf); ASN1_MALLOC_ENCODE(KRB_SAFE, buf, buf_size, &s, &len, ret); free_Checksum (&s.cksum); if(ret) return ret; if(buf_size != len) krb5_abortx(context, "internal error in ASN.1 encoder"); outbuf->length = len; outbuf->data = buf; if (auth_context->flags & KRB5_AUTH_CONTEXT_DO_SEQUENCE) auth_context->local_seqnumber = (auth_context->local_seqnumber + 1) & 0xFFFFFFFF; return 0; } heimdal-7.5.0/lib/krb5/keytab_file.c0000644000175000017500000004643113212137553015317 0ustar niknik/* * Copyright (c) 1997 - 2008 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "krb5_locl.h" #define KRB5_KT_VNO_1 1 #define KRB5_KT_VNO_2 2 #define KRB5_KT_VNO KRB5_KT_VNO_2 #define KRB5_KT_FL_JAVA 1 /* file operations -------------------------------------------- */ struct fkt_data { char *filename; int flags; }; static krb5_error_code krb5_kt_ret_data(krb5_context context, krb5_storage *sp, krb5_data *data) { int ret; int16_t size; ret = krb5_ret_int16(sp, &size); if(ret) return ret; data->length = size; data->data = malloc(size); if (data->data == NULL) return krb5_enomem(context); ret = krb5_storage_read(sp, data->data, size); if(ret != size) return (ret < 0)? errno : KRB5_KT_END; return 0; } static krb5_error_code krb5_kt_ret_string(krb5_context context, krb5_storage *sp, heim_general_string *data) { int ret; int16_t size; ret = krb5_ret_int16(sp, &size); if(ret) return ret; *data = malloc(size + 1); if (*data == NULL) return krb5_enomem(context); ret = krb5_storage_read(sp, *data, size); (*data)[size] = '\0'; if(ret != size) return (ret < 0)? errno : KRB5_KT_END; return 0; } static krb5_error_code krb5_kt_store_data(krb5_context context, krb5_storage *sp, krb5_data data) { int ret; ret = krb5_store_int16(sp, data.length); if(ret < 0) return ret; ret = krb5_storage_write(sp, data.data, data.length); if(ret != (int)data.length){ if(ret < 0) return errno; return KRB5_KT_END; } return 0; } static krb5_error_code krb5_kt_store_string(krb5_storage *sp, heim_general_string data) { int ret; size_t len = strlen(data); ret = krb5_store_int16(sp, len); if(ret < 0) return ret; ret = krb5_storage_write(sp, data, len); if(ret != (int)len){ if(ret < 0) return errno; return KRB5_KT_END; } return 0; } static krb5_error_code krb5_kt_ret_keyblock(krb5_context context, struct fkt_data *fkt, krb5_storage *sp, krb5_keyblock *p) { int ret; int16_t tmp; ret = krb5_ret_int16(sp, &tmp); /* keytype + etype */ if(ret) { krb5_set_error_message(context, ret, N_("Cant read keyblock from file %s", ""), fkt->filename); return ret; } p->keytype = tmp; ret = krb5_kt_ret_data(context, sp, &p->keyvalue); if (ret) krb5_set_error_message(context, ret, N_("Cant read keyblock from file %s", ""), fkt->filename); return ret; } static krb5_error_code krb5_kt_store_keyblock(krb5_context context, struct fkt_data *fkt, krb5_storage *sp, krb5_keyblock *p) { int ret; ret = krb5_store_int16(sp, p->keytype); /* keytype + etype */ if(ret) { krb5_set_error_message(context, ret, N_("Cant store keyblock to file %s", ""), fkt->filename); return ret; } ret = krb5_kt_store_data(context, sp, p->keyvalue); if (ret) krb5_set_error_message(context, ret, N_("Cant store keyblock to file %s", ""), fkt->filename); return ret; } static krb5_error_code krb5_kt_ret_principal(krb5_context context, struct fkt_data *fkt, krb5_storage *sp, krb5_principal *princ) { size_t i; int ret; krb5_principal p; int16_t len; ALLOC(p, 1); if(p == NULL) return krb5_enomem(context); ret = krb5_ret_int16(sp, &len); if(ret) { krb5_set_error_message(context, ret, N_("Failed decoding length of " "keytab principal in keytab file %s", ""), fkt->filename); goto out; } if(krb5_storage_is_flags(sp, KRB5_STORAGE_PRINCIPAL_WRONG_NUM_COMPONENTS)) len--; if (len < 0) { ret = KRB5_KT_END; krb5_set_error_message(context, ret, N_("Keytab principal contains " "invalid length in keytab %s", ""), fkt->filename); goto out; } ret = krb5_kt_ret_string(context, sp, &p->realm); if(ret) { krb5_set_error_message(context, ret, N_("Can't read realm from keytab: %s", ""), fkt->filename); goto out; } p->name.name_string.val = calloc(len, sizeof(*p->name.name_string.val)); if(p->name.name_string.val == NULL) { ret = krb5_enomem(context); goto out; } p->name.name_string.len = len; for(i = 0; i < p->name.name_string.len; i++){ ret = krb5_kt_ret_string(context, sp, p->name.name_string.val + i); if(ret) { krb5_set_error_message(context, ret, N_("Can't read principal from " "keytab: %s", ""), fkt->filename); goto out; } } if (krb5_storage_is_flags(sp, KRB5_STORAGE_PRINCIPAL_NO_NAME_TYPE)) p->name.name_type = KRB5_NT_UNKNOWN; else { int32_t tmp32; ret = krb5_ret_int32(sp, &tmp32); p->name.name_type = tmp32; if (ret) { krb5_set_error_message(context, ret, N_("Can't read name-type from " "keytab: %s", ""), fkt->filename); goto out; } } *princ = p; return 0; out: krb5_free_principal(context, p); return ret; } static krb5_error_code krb5_kt_store_principal(krb5_context context, krb5_storage *sp, krb5_principal p) { size_t i; int ret; if(krb5_storage_is_flags(sp, KRB5_STORAGE_PRINCIPAL_WRONG_NUM_COMPONENTS)) ret = krb5_store_int16(sp, p->name.name_string.len + 1); else ret = krb5_store_int16(sp, p->name.name_string.len); if(ret) return ret; ret = krb5_kt_store_string(sp, p->realm); if(ret) return ret; for(i = 0; i < p->name.name_string.len; i++){ ret = krb5_kt_store_string(sp, p->name.name_string.val[i]); if(ret) return ret; } if(!krb5_storage_is_flags(sp, KRB5_STORAGE_PRINCIPAL_NO_NAME_TYPE)) { ret = krb5_store_int32(sp, p->name.name_type); if(ret) return ret; } return 0; } static krb5_error_code KRB5_CALLCONV fkt_resolve(krb5_context context, const char *name, krb5_keytab id) { struct fkt_data *d; d = malloc(sizeof(*d)); if(d == NULL) return krb5_enomem(context); d->filename = strdup(name); if(d->filename == NULL) { free(d); return krb5_enomem(context); } d->flags = 0; id->data = d; return 0; } static krb5_error_code KRB5_CALLCONV fkt_resolve_java14(krb5_context context, const char *name, krb5_keytab id) { krb5_error_code ret; ret = fkt_resolve(context, name, id); if (ret == 0) { struct fkt_data *d = id->data; d->flags |= KRB5_KT_FL_JAVA; } return ret; } static krb5_error_code KRB5_CALLCONV fkt_close(krb5_context context, krb5_keytab id) { struct fkt_data *d = id->data; free(d->filename); free(d); return 0; } static krb5_error_code KRB5_CALLCONV fkt_destroy(krb5_context context, krb5_keytab id) { struct fkt_data *d = id->data; _krb5_erase_file(context, d->filename); return 0; } static krb5_error_code KRB5_CALLCONV fkt_get_name(krb5_context context, krb5_keytab id, char *name, size_t namesize) { /* This function is XXX */ struct fkt_data *d = id->data; strlcpy(name, d->filename, namesize); return 0; } static void storage_set_flags(krb5_context context, krb5_storage *sp, int vno) { int flags = 0; switch(vno) { case KRB5_KT_VNO_1: flags |= KRB5_STORAGE_PRINCIPAL_WRONG_NUM_COMPONENTS; flags |= KRB5_STORAGE_PRINCIPAL_NO_NAME_TYPE; flags |= KRB5_STORAGE_HOST_BYTEORDER; break; case KRB5_KT_VNO_2: break; default: krb5_warnx(context, "storage_set_flags called with bad vno (%d)", vno); } krb5_storage_set_flags(sp, flags); } static krb5_error_code fkt_start_seq_get_int(krb5_context context, krb5_keytab id, int flags, int exclusive, krb5_kt_cursor *c) { int8_t pvno, tag; krb5_error_code ret; struct fkt_data *d = id->data; c->fd = open (d->filename, flags); if (c->fd < 0) { ret = errno; krb5_set_error_message(context, ret, N_("keytab %s open failed: %s", ""), d->filename, strerror(ret)); return ret; } rk_cloexec(c->fd); ret = _krb5_xlock(context, c->fd, exclusive, d->filename); if (ret) { close(c->fd); return ret; } c->sp = krb5_storage_from_fd(c->fd); if (c->sp == NULL) { _krb5_xunlock(context, c->fd); close(c->fd); return krb5_enomem(context); } krb5_storage_set_eof_code(c->sp, KRB5_KT_END); ret = krb5_ret_int8(c->sp, &pvno); if(ret) { krb5_storage_free(c->sp); _krb5_xunlock(context, c->fd); close(c->fd); krb5_clear_error_message(context); return ret; } if(pvno != 5) { krb5_storage_free(c->sp); _krb5_xunlock(context, c->fd); close(c->fd); krb5_clear_error_message (context); return KRB5_KEYTAB_BADVNO; } ret = krb5_ret_int8(c->sp, &tag); if (ret) { krb5_storage_free(c->sp); _krb5_xunlock(context, c->fd); close(c->fd); krb5_clear_error_message(context); return ret; } id->version = tag; storage_set_flags(context, c->sp, id->version); return 0; } static krb5_error_code KRB5_CALLCONV fkt_start_seq_get(krb5_context context, krb5_keytab id, krb5_kt_cursor *c) { return fkt_start_seq_get_int(context, id, O_RDONLY | O_BINARY | O_CLOEXEC, 0, c); } static krb5_error_code fkt_next_entry_int(krb5_context context, krb5_keytab id, krb5_keytab_entry *entry, krb5_kt_cursor *cursor, off_t *start, off_t *end) { struct fkt_data *d = id->data; int32_t len; int ret; int8_t tmp8; int32_t tmp32; uint32_t utmp32; off_t pos, curpos; pos = krb5_storage_seek(cursor->sp, 0, SEEK_CUR); loop: ret = krb5_ret_int32(cursor->sp, &len); if (ret) return ret; if(len < 0) { pos = krb5_storage_seek(cursor->sp, -len, SEEK_CUR); goto loop; } ret = krb5_kt_ret_principal (context, d, cursor->sp, &entry->principal); if (ret) goto out; ret = krb5_ret_uint32(cursor->sp, &utmp32); entry->timestamp = utmp32; if (ret) goto out; ret = krb5_ret_int8(cursor->sp, &tmp8); if (ret) goto out; entry->vno = tmp8; ret = krb5_kt_ret_keyblock (context, d, cursor->sp, &entry->keyblock); if (ret) goto out; /* there might be a 32 bit kvno here * if it's zero, assume that the 8bit one was right, * otherwise trust the new value */ curpos = krb5_storage_seek(cursor->sp, 0, SEEK_CUR); if(len + 4 + pos - curpos >= 4) { ret = krb5_ret_int32(cursor->sp, &tmp32); if (ret == 0 && tmp32 != 0) entry->vno = tmp32; } /* there might be a flags field here */ if(len + 4 + pos - curpos >= 8) { ret = krb5_ret_uint32(cursor->sp, &utmp32); if (ret == 0) entry->flags = utmp32; } else entry->flags = 0; entry->aliases = NULL; if(start) *start = pos; if(end) *end = pos + 4 + len; out: if (ret) krb5_kt_free_entry(context, entry); krb5_storage_seek(cursor->sp, pos + 4 + len, SEEK_SET); return ret; } static krb5_error_code KRB5_CALLCONV fkt_next_entry(krb5_context context, krb5_keytab id, krb5_keytab_entry *entry, krb5_kt_cursor *cursor) { return fkt_next_entry_int(context, id, entry, cursor, NULL, NULL); } static krb5_error_code KRB5_CALLCONV fkt_end_seq_get(krb5_context context, krb5_keytab id, krb5_kt_cursor *cursor) { krb5_storage_free(cursor->sp); _krb5_xunlock(context, cursor->fd); close(cursor->fd); return 0; } static krb5_error_code KRB5_CALLCONV fkt_setup_keytab(krb5_context context, krb5_keytab id, krb5_storage *sp) { krb5_error_code ret; ret = krb5_store_int8(sp, 5); if(ret) return ret; if(id->version == 0) id->version = KRB5_KT_VNO; return krb5_store_int8 (sp, id->version); } static krb5_error_code KRB5_CALLCONV fkt_add_entry(krb5_context context, krb5_keytab id, krb5_keytab_entry *entry) { int ret; int fd; krb5_storage *sp; struct fkt_data *d = id->data; krb5_data keytab; int32_t len; fd = open (d->filename, O_RDWR | O_BINARY | O_CLOEXEC); if (fd < 0) { fd = open (d->filename, O_RDWR | O_CREAT | O_EXCL | O_BINARY | O_CLOEXEC, 0600); if (fd < 0) { ret = errno; krb5_set_error_message(context, ret, N_("open(%s): %s", ""), d->filename, strerror(ret)); return ret; } rk_cloexec(fd); ret = _krb5_xlock(context, fd, 1, d->filename); if (ret) { close(fd); return ret; } sp = krb5_storage_from_fd(fd); krb5_storage_set_eof_code(sp, KRB5_KT_END); ret = fkt_setup_keytab(context, id, sp); if(ret) { goto out; } storage_set_flags(context, sp, id->version); } else { int8_t pvno, tag; rk_cloexec(fd); ret = _krb5_xlock(context, fd, 1, d->filename); if (ret) { close(fd); return ret; } sp = krb5_storage_from_fd(fd); krb5_storage_set_eof_code(sp, KRB5_KT_END); ret = krb5_ret_int8(sp, &pvno); if(ret) { /* we probably have a zero byte file, so try to set it up properly */ ret = fkt_setup_keytab(context, id, sp); if(ret) { krb5_set_error_message(context, ret, N_("%s: keytab is corrupted: %s", ""), d->filename, strerror(ret)); goto out; } storage_set_flags(context, sp, id->version); } else { if(pvno != 5) { ret = KRB5_KEYTAB_BADVNO; krb5_set_error_message(context, ret, N_("Bad version in keytab %s", ""), d->filename); goto out; } ret = krb5_ret_int8 (sp, &tag); if (ret) { krb5_set_error_message(context, ret, N_("failed reading tag from " "keytab %s", ""), d->filename); goto out; } id->version = tag; storage_set_flags(context, sp, id->version); } } { krb5_storage *emem; emem = krb5_storage_emem(); if(emem == NULL) { ret = krb5_enomem(context); goto out; } ret = krb5_kt_store_principal(context, emem, entry->principal); if(ret) { krb5_set_error_message(context, ret, N_("Failed storing principal " "in keytab %s", ""), d->filename); krb5_storage_free(emem); goto out; } ret = krb5_store_int32 (emem, entry->timestamp); if(ret) { krb5_set_error_message(context, ret, N_("Failed storing timpstamp " "in keytab %s", ""), d->filename); krb5_storage_free(emem); goto out; } ret = krb5_store_int8 (emem, entry->vno % 256); if(ret) { krb5_set_error_message(context, ret, N_("Failed storing kvno " "in keytab %s", ""), d->filename); krb5_storage_free(emem); goto out; } ret = krb5_kt_store_keyblock (context, d, emem, &entry->keyblock); if(ret) { krb5_storage_free(emem); goto out; } if ((d->flags & KRB5_KT_FL_JAVA) == 0) { ret = krb5_store_int32 (emem, entry->vno); if (ret) { krb5_set_error_message(context, ret, N_("Failed storing extended kvno " "in keytab %s", ""), d->filename); krb5_storage_free(emem); goto out; } ret = krb5_store_uint32 (emem, entry->flags); if (ret) { krb5_set_error_message(context, ret, N_("Failed storing extended kvno " "in keytab %s", ""), d->filename); krb5_storage_free(emem); goto out; } } ret = krb5_storage_to_data(emem, &keytab); krb5_storage_free(emem); if(ret) { krb5_set_error_message(context, ret, N_("Failed converting keytab entry " "to memory block for keytab %s", ""), d->filename); goto out; } } while(1) { ret = krb5_ret_int32(sp, &len); if(ret == KRB5_KT_END) { len = keytab.length; break; } if(len < 0) { len = -len; if(len >= (int)keytab.length) { krb5_storage_seek(sp, -4, SEEK_CUR); break; } } krb5_storage_seek(sp, len, SEEK_CUR); } ret = krb5_store_int32(sp, len); if(krb5_storage_write(sp, keytab.data, keytab.length) < 0) { ret = errno; krb5_set_error_message(context, ret, N_("Failed writing keytab block " "in keytab %s: %s", ""), d->filename, strerror(ret)); } memset(keytab.data, 0, keytab.length); krb5_data_free(&keytab); out: krb5_storage_free(sp); _krb5_xunlock(context, fd); close(fd); return ret; } static krb5_error_code KRB5_CALLCONV fkt_remove_entry(krb5_context context, krb5_keytab id, krb5_keytab_entry *entry) { krb5_keytab_entry e; krb5_kt_cursor cursor; off_t pos_start, pos_end; int found = 0; krb5_error_code ret; ret = fkt_start_seq_get_int(context, id, O_RDWR | O_BINARY | O_CLOEXEC, 1, &cursor); if(ret != 0) goto out; /* return other error here? */ while(fkt_next_entry_int(context, id, &e, &cursor, &pos_start, &pos_end) == 0) { if(krb5_kt_compare(context, &e, entry->principal, entry->vno, entry->keyblock.keytype)) { int32_t len; unsigned char buf[128]; found = 1; krb5_storage_seek(cursor.sp, pos_start, SEEK_SET); len = pos_end - pos_start - 4; krb5_store_int32(cursor.sp, -len); memset(buf, 0, sizeof(buf)); while(len > 0) { krb5_storage_write(cursor.sp, buf, min((size_t)len, sizeof(buf))); len -= min((size_t)len, sizeof(buf)); } } krb5_kt_free_entry(context, &e); } krb5_kt_end_seq_get(context, id, &cursor); out: if (!found) { krb5_clear_error_message (context); return KRB5_KT_NOTFOUND; } return 0; } const krb5_kt_ops krb5_fkt_ops = { "FILE", fkt_resolve, fkt_get_name, fkt_close, fkt_destroy, NULL, /* get */ fkt_start_seq_get, fkt_next_entry, fkt_end_seq_get, fkt_add_entry, fkt_remove_entry, NULL, 0 }; const krb5_kt_ops krb5_wrfkt_ops = { "WRFILE", fkt_resolve, fkt_get_name, fkt_close, fkt_destroy, NULL, /* get */ fkt_start_seq_get, fkt_next_entry, fkt_end_seq_get, fkt_add_entry, fkt_remove_entry, NULL, 0 }; const krb5_kt_ops krb5_javakt_ops = { "JAVA14", fkt_resolve_java14, fkt_get_name, fkt_close, fkt_destroy, NULL, /* get */ fkt_start_seq_get, fkt_next_entry, fkt_end_seq_get, fkt_add_entry, fkt_remove_entry, NULL, 0 }; heimdal-7.5.0/lib/krb5/krb524_convert_creds_kdc.30000644000175000017500000000617113026237312017525 0ustar niknik.\" Copyright (c) 2004 Kungliga Tekniska Högskolan .\" (Royal Institute of Technology, Stockholm, Sweden). .\" All rights reserved. .\" .\" Redistribution and use in source and binary forms, with or without .\" modification, are permitted provided that the following conditions .\" are met: .\" .\" 1. Redistributions of source code must retain the above copyright .\" notice, this list of conditions and the following disclaimer. .\" .\" 2. Redistributions in binary form must reproduce the above copyright .\" notice, this list of conditions and the following disclaimer in the .\" documentation and/or other materials provided with the distribution. .\" .\" 3. Neither the name of the Institute nor the names of its contributors .\" may be used to endorse or promote products derived from this software .\" without specific prior written permission. .\" .\" THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND .\" ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE .\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE .\" ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE .\" FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL .\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS .\" OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) .\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT .\" LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF .\" SUCH DAMAGE. .\" .\" $Id$ .\" .Dd March 20, 2004 .Dt KRB524_CONVERT_CREDS_KDC 3 .Os HEIMDAL .Sh NAME .Nm krb524_convert_creds_kdc , .Nm krb524_convert_creds_kdc_ccache .Nd converts Kerberos 5 credentials to Kerberos 4 credentials .Sh LIBRARY Kerberos 5 Library (libkrb5, -lkrb5) .Sh SYNOPSIS .In krb5.h .Ft krb5_error_code .Fo krb524_convert_creds_kdc .Fa "krb5_context context" .Fa "krb5_creds *in_cred" .Fa "struct credentials *v4creds" .Fc .Ft krb5_error_code .Fo krb524_convert_creds_kdc_ccache .Fa "krb5_context context" .Fa "krb5_ccache ccache" .Fa "krb5_creds *in_cred" .Fa "struct credentials *v4creds" .Fc .Sh DESCRIPTION Convert the Kerberos 5 credential to Kerberos 4 credential. This is done by sending them to the 524 service in the KDC. .Pp .Fn krb524_convert_creds_kdc converts the Kerberos 5 credential in .Fa in_cred to Kerberos 4 credential that is stored in .Fa credentials . .Pp .Fn krb524_convert_creds_kdc_ccache is different from .Fn krb524_convert_creds_kdc in that way that if .Fa in_cred doesn't contain a DES session key, then a new one is fetched from the KDC and stored in the cred cache .Fa ccache , and then the KDC is queried to convert the credential. .Pp This interfaces are used to make the migration to Kerberos 5 from Kerberos 4 easier. There are few services that still need Kerberos 4, and this is mainly for compatibility for those services. Some services, like AFS, really have Kerberos 5 supports, but still uses the 524 interface to make the migration easier. .Sh SEE ALSO .Xr krb5 3 , .Xr krb5.conf 5 heimdal-7.5.0/lib/krb5/pkinit.c0000644000175000017500000017106413062303006014327 0ustar niknik/* * Copyright (c) 2003 - 2016 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Portions Copyright (c) 2009 Apple Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "krb5_locl.h" struct krb5_dh_moduli { char *name; unsigned long bits; heim_integer p; heim_integer g; heim_integer q; }; #ifdef PKINIT #include #include #include #include #include #include #include struct krb5_pk_cert { hx509_cert cert; }; static void pk_copy_error(krb5_context context, hx509_context hx509ctx, int hxret, const char *fmt, ...) __attribute__ ((__format__ (__printf__, 4, 5))); /* * */ KRB5_LIB_FUNCTION void KRB5_LIB_CALL _krb5_pk_cert_free(struct krb5_pk_cert *cert) { if (cert->cert) { hx509_cert_free(cert->cert); } free(cert); } static krb5_error_code BN_to_integer(krb5_context context, BIGNUM *bn, heim_integer *integer) { integer->length = BN_num_bytes(bn); integer->data = malloc(integer->length); if (integer->data == NULL) { krb5_clear_error_message(context); return ENOMEM; } BN_bn2bin(bn, integer->data); integer->negative = BN_is_negative(bn); return 0; } static BIGNUM * integer_to_BN(krb5_context context, const char *field, const heim_integer *f) { BIGNUM *bn; bn = BN_bin2bn((const unsigned char *)f->data, f->length, NULL); if (bn == NULL) { krb5_set_error_message(context, ENOMEM, N_("PKINIT: parsing BN failed %s", ""), field); return NULL; } BN_set_negative(bn, f->negative); return bn; } static krb5_error_code select_dh_group(krb5_context context, DH *dh, unsigned long bits, struct krb5_dh_moduli **moduli) { const struct krb5_dh_moduli *m; if (bits == 0) { m = moduli[1]; /* XXX */ if (m == NULL) m = moduli[0]; /* XXX */ } else { int i; for (i = 0; moduli[i] != NULL; i++) { if (bits < moduli[i]->bits) break; } if (moduli[i] == NULL) { krb5_set_error_message(context, EINVAL, N_("Did not find a DH group parameter " "matching requirement of %lu bits", ""), bits); return EINVAL; } m = moduli[i]; } dh->p = integer_to_BN(context, "p", &m->p); if (dh->p == NULL) return ENOMEM; dh->g = integer_to_BN(context, "g", &m->g); if (dh->g == NULL) return ENOMEM; dh->q = integer_to_BN(context, "q", &m->q); if (dh->q == NULL) return ENOMEM; return 0; } struct certfind { const char *type; const heim_oid *oid; }; /* * Try searchin the key by to use by first looking for for PK-INIT * EKU, then the Microsoft smart card EKU and last, no special EKU at all. */ static krb5_error_code find_cert(krb5_context context, struct krb5_pk_identity *id, hx509_query *q, hx509_cert *cert) { struct certfind cf[4] = { { "MobileMe EKU", NULL }, { "PKINIT EKU", NULL }, { "MS EKU", NULL }, { "any (or no)", NULL } }; int ret = HX509_CERT_NOT_FOUND; size_t i, start = 1; unsigned oids[] = { 1, 2, 840, 113635, 100, 3, 2, 1 }; const heim_oid mobileMe = { sizeof(oids)/sizeof(oids[0]), oids }; if (id->flags & PKINIT_BTMM) start = 0; cf[0].oid = &mobileMe; cf[1].oid = &asn1_oid_id_pkekuoid; cf[2].oid = &asn1_oid_id_pkinit_ms_eku; cf[3].oid = NULL; for (i = start; i < sizeof(cf)/sizeof(cf[0]); i++) { ret = hx509_query_match_eku(q, cf[i].oid); if (ret) { pk_copy_error(context, context->hx509ctx, ret, "Failed setting %s OID", cf[i].type); return ret; } ret = hx509_certs_find(context->hx509ctx, id->certs, q, cert); if (ret == 0) break; pk_copy_error(context, context->hx509ctx, ret, "Failed finding certificate with %s OID", cf[i].type); } return ret; } static krb5_error_code create_signature(krb5_context context, const heim_oid *eContentType, krb5_data *eContent, struct krb5_pk_identity *id, hx509_peer_info peer, krb5_data *sd_data) { int ret, flags = 0; if (id->cert == NULL) flags |= HX509_CMS_SIGNATURE_NO_SIGNER; ret = hx509_cms_create_signed_1(context->hx509ctx, flags, eContentType, eContent->data, eContent->length, NULL, id->cert, peer, NULL, id->certs, sd_data); if (ret) { pk_copy_error(context, context->hx509ctx, ret, "Create CMS signedData"); return ret; } return 0; } static int cert2epi(hx509_context context, void *ctx, hx509_cert c) { ExternalPrincipalIdentifiers *ids = ctx; ExternalPrincipalIdentifier id; hx509_name subject = NULL; void *p; int ret; if (ids->len > 10) return 0; memset(&id, 0, sizeof(id)); ret = hx509_cert_get_subject(c, &subject); if (ret) return ret; if (hx509_name_is_null_p(subject) != 0) { id.subjectName = calloc(1, sizeof(*id.subjectName)); if (id.subjectName == NULL) { hx509_name_free(&subject); free_ExternalPrincipalIdentifier(&id); return ENOMEM; } ret = hx509_name_binary(subject, id.subjectName); if (ret) { hx509_name_free(&subject); free_ExternalPrincipalIdentifier(&id); return ret; } } hx509_name_free(&subject); id.issuerAndSerialNumber = calloc(1, sizeof(*id.issuerAndSerialNumber)); if (id.issuerAndSerialNumber == NULL) { free_ExternalPrincipalIdentifier(&id); return ENOMEM; } { IssuerAndSerialNumber iasn; hx509_name issuer; size_t size = 0; memset(&iasn, 0, sizeof(iasn)); ret = hx509_cert_get_issuer(c, &issuer); if (ret) { free_ExternalPrincipalIdentifier(&id); return ret; } ret = hx509_name_to_Name(issuer, &iasn.issuer); hx509_name_free(&issuer); if (ret) { free_ExternalPrincipalIdentifier(&id); return ret; } ret = hx509_cert_get_serialnumber(c, &iasn.serialNumber); if (ret) { free_IssuerAndSerialNumber(&iasn); free_ExternalPrincipalIdentifier(&id); return ret; } ASN1_MALLOC_ENCODE(IssuerAndSerialNumber, id.issuerAndSerialNumber->data, id.issuerAndSerialNumber->length, &iasn, &size, ret); free_IssuerAndSerialNumber(&iasn); if (ret) { free_ExternalPrincipalIdentifier(&id); return ret; } if (id.issuerAndSerialNumber->length != size) abort(); } id.subjectKeyIdentifier = NULL; p = realloc(ids->val, sizeof(ids->val[0]) * (ids->len + 1)); if (p == NULL) { free_ExternalPrincipalIdentifier(&id); return ENOMEM; } ids->val = p; ids->val[ids->len] = id; ids->len++; return 0; } static krb5_error_code build_edi(krb5_context context, hx509_context hx509ctx, hx509_certs certs, ExternalPrincipalIdentifiers *ids) { return hx509_certs_iter_f(hx509ctx, certs, cert2epi, ids); } static krb5_error_code build_auth_pack(krb5_context context, unsigned nonce, krb5_pk_init_ctx ctx, const KDC_REQ_BODY *body, AuthPack *a) { size_t buf_size, len = 0; krb5_error_code ret; void *buf; krb5_timestamp sec; int32_t usec; Checksum checksum; krb5_clear_error_message(context); memset(&checksum, 0, sizeof(checksum)); krb5_us_timeofday(context, &sec, &usec); a->pkAuthenticator.ctime = sec; a->pkAuthenticator.nonce = nonce; ASN1_MALLOC_ENCODE(KDC_REQ_BODY, buf, buf_size, body, &len, ret); if (ret) return ret; if (buf_size != len) krb5_abortx(context, "internal error in ASN.1 encoder"); ret = krb5_create_checksum(context, NULL, 0, CKSUMTYPE_SHA1, buf, len, &checksum); free(buf); if (ret) return ret; ALLOC(a->pkAuthenticator.paChecksum, 1); if (a->pkAuthenticator.paChecksum == NULL) { return krb5_enomem(context); } ret = krb5_data_copy(a->pkAuthenticator.paChecksum, checksum.checksum.data, checksum.checksum.length); free_Checksum(&checksum); if (ret) return ret; if (ctx->keyex == USE_DH || ctx->keyex == USE_ECDH) { const char *moduli_file; unsigned long dh_min_bits; krb5_data dhbuf; size_t size = 0; krb5_data_zero(&dhbuf); moduli_file = krb5_config_get_string(context, NULL, "libdefaults", "moduli", NULL); dh_min_bits = krb5_config_get_int_default(context, NULL, 0, "libdefaults", "pkinit_dh_min_bits", NULL); ret = _krb5_parse_moduli(context, moduli_file, &ctx->m); if (ret) return ret; ctx->u.dh = DH_new(); if (ctx->u.dh == NULL) return krb5_enomem(context); ret = select_dh_group(context, ctx->u.dh, dh_min_bits, ctx->m); if (ret) return ret; if (DH_generate_key(ctx->u.dh) != 1) { krb5_set_error_message(context, ENOMEM, N_("pkinit: failed to generate DH key", "")); return ENOMEM; } if (1 /* support_cached_dh */) { ALLOC(a->clientDHNonce, 1); if (a->clientDHNonce == NULL) { krb5_clear_error_message(context); return ENOMEM; } ret = krb5_data_alloc(a->clientDHNonce, 40); if (a->clientDHNonce == NULL) { krb5_clear_error_message(context); return ret; } RAND_bytes(a->clientDHNonce->data, a->clientDHNonce->length); ret = krb5_copy_data(context, a->clientDHNonce, &ctx->clientDHNonce); if (ret) return ret; } ALLOC(a->clientPublicValue, 1); if (a->clientPublicValue == NULL) return ENOMEM; if (ctx->keyex == USE_DH) { DH *dh = ctx->u.dh; DomainParameters dp; heim_integer dh_pub_key; ret = der_copy_oid(&asn1_oid_id_dhpublicnumber, &a->clientPublicValue->algorithm.algorithm); if (ret) return ret; memset(&dp, 0, sizeof(dp)); ret = BN_to_integer(context, dh->p, &dp.p); if (ret) { free_DomainParameters(&dp); return ret; } ret = BN_to_integer(context, dh->g, &dp.g); if (ret) { free_DomainParameters(&dp); return ret; } dp.q = calloc(1, sizeof(*dp.q)); if (dp.q == NULL) { free_DomainParameters(&dp); return ENOMEM; } ret = BN_to_integer(context, dh->q, dp.q); if (ret) { free_DomainParameters(&dp); return ret; } dp.j = NULL; dp.validationParms = NULL; a->clientPublicValue->algorithm.parameters = malloc(sizeof(*a->clientPublicValue->algorithm.parameters)); if (a->clientPublicValue->algorithm.parameters == NULL) { free_DomainParameters(&dp); return ret; } ASN1_MALLOC_ENCODE(DomainParameters, a->clientPublicValue->algorithm.parameters->data, a->clientPublicValue->algorithm.parameters->length, &dp, &size, ret); free_DomainParameters(&dp); if (ret) return ret; if (size != a->clientPublicValue->algorithm.parameters->length) krb5_abortx(context, "Internal ASN1 encoder error"); ret = BN_to_integer(context, dh->pub_key, &dh_pub_key); if (ret) return ret; ASN1_MALLOC_ENCODE(DHPublicKey, dhbuf.data, dhbuf.length, &dh_pub_key, &size, ret); der_free_heim_integer(&dh_pub_key); if (ret) return ret; if (size != dhbuf.length) krb5_abortx(context, "asn1 internal error"); a->clientPublicValue->subjectPublicKey.length = dhbuf.length * 8; a->clientPublicValue->subjectPublicKey.data = dhbuf.data; } else if (ctx->keyex == USE_ECDH) { ret = _krb5_build_authpack_subjectPK_EC(context, ctx, a); if (ret) return ret; } else krb5_abortx(context, "internal error"); } { a->supportedCMSTypes = calloc(1, sizeof(*a->supportedCMSTypes)); if (a->supportedCMSTypes == NULL) return ENOMEM; ret = hx509_crypto_available(context->hx509ctx, HX509_SELECT_ALL, ctx->id->cert, &a->supportedCMSTypes->val, &a->supportedCMSTypes->len); if (ret) return ret; } return ret; } KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL _krb5_pk_mk_ContentInfo(krb5_context context, const krb5_data *buf, const heim_oid *oid, struct ContentInfo *content_info) { krb5_error_code ret; ret = der_copy_oid(oid, &content_info->contentType); if (ret) return ret; ALLOC(content_info->content, 1); if (content_info->content == NULL) return ENOMEM; content_info->content->data = malloc(buf->length); if (content_info->content->data == NULL) return ENOMEM; memcpy(content_info->content->data, buf->data, buf->length); content_info->content->length = buf->length; return 0; } static krb5_error_code pk_mk_padata(krb5_context context, krb5_pk_init_ctx ctx, const KDC_REQ_BODY *req_body, unsigned nonce, METHOD_DATA *md) { struct ContentInfo content_info; krb5_error_code ret; const heim_oid *oid = NULL; size_t size = 0; krb5_data buf, sd_buf; int pa_type = -1; krb5_data_zero(&buf); krb5_data_zero(&sd_buf); memset(&content_info, 0, sizeof(content_info)); if (ctx->type == PKINIT_WIN2K) { AuthPack_Win2k ap; krb5_timestamp sec; int32_t usec; memset(&ap, 0, sizeof(ap)); /* fill in PKAuthenticator */ ret = copy_PrincipalName(req_body->sname, &ap.pkAuthenticator.kdcName); if (ret) { free_AuthPack_Win2k(&ap); krb5_clear_error_message(context); goto out; } ret = copy_Realm(&req_body->realm, &ap.pkAuthenticator.kdcRealm); if (ret) { free_AuthPack_Win2k(&ap); krb5_clear_error_message(context); goto out; } krb5_us_timeofday(context, &sec, &usec); ap.pkAuthenticator.ctime = sec; ap.pkAuthenticator.cusec = usec; ap.pkAuthenticator.nonce = nonce; ASN1_MALLOC_ENCODE(AuthPack_Win2k, buf.data, buf.length, &ap, &size, ret); free_AuthPack_Win2k(&ap); if (ret) { krb5_set_error_message(context, ret, N_("Failed encoding AuthPackWin: %d", ""), (int)ret); goto out; } if (buf.length != size) krb5_abortx(context, "internal ASN1 encoder error"); oid = &asn1_oid_id_pkcs7_data; } else if (ctx->type == PKINIT_27) { AuthPack ap; memset(&ap, 0, sizeof(ap)); ret = build_auth_pack(context, nonce, ctx, req_body, &ap); if (ret) { free_AuthPack(&ap); goto out; } ASN1_MALLOC_ENCODE(AuthPack, buf.data, buf.length, &ap, &size, ret); free_AuthPack(&ap); if (ret) { krb5_set_error_message(context, ret, N_("Failed encoding AuthPack: %d", ""), (int)ret); goto out; } if (buf.length != size) krb5_abortx(context, "internal ASN1 encoder error"); oid = &asn1_oid_id_pkauthdata; } else krb5_abortx(context, "internal pkinit error"); ret = create_signature(context, oid, &buf, ctx->id, ctx->peer, &sd_buf); krb5_data_free(&buf); if (ret) goto out; ret = hx509_cms_wrap_ContentInfo(&asn1_oid_id_pkcs7_signedData, &sd_buf, &buf); krb5_data_free(&sd_buf); if (ret) { krb5_set_error_message(context, ret, N_("ContentInfo wrapping of signedData failed","")); goto out; } if (ctx->type == PKINIT_WIN2K) { PA_PK_AS_REQ_Win2k winreq; pa_type = KRB5_PADATA_PK_AS_REQ_WIN; memset(&winreq, 0, sizeof(winreq)); winreq.signed_auth_pack = buf; ASN1_MALLOC_ENCODE(PA_PK_AS_REQ_Win2k, buf.data, buf.length, &winreq, &size, ret); free_PA_PK_AS_REQ_Win2k(&winreq); } else if (ctx->type == PKINIT_27) { PA_PK_AS_REQ req; pa_type = KRB5_PADATA_PK_AS_REQ; memset(&req, 0, sizeof(req)); req.signedAuthPack = buf; if (ctx->trustedCertifiers) { req.trustedCertifiers = calloc(1, sizeof(*req.trustedCertifiers)); if (req.trustedCertifiers == NULL) { ret = krb5_enomem(context); free_PA_PK_AS_REQ(&req); goto out; } ret = build_edi(context, context->hx509ctx, ctx->id->anchors, req.trustedCertifiers); if (ret) { krb5_set_error_message(context, ret, N_("pk-init: failed to build " "trustedCertifiers", "")); free_PA_PK_AS_REQ(&req); goto out; } } req.kdcPkId = NULL; ASN1_MALLOC_ENCODE(PA_PK_AS_REQ, buf.data, buf.length, &req, &size, ret); free_PA_PK_AS_REQ(&req); } else krb5_abortx(context, "internal pkinit error"); if (ret) { krb5_set_error_message(context, ret, "PA-PK-AS-REQ %d", (int)ret); goto out; } if (buf.length != size) krb5_abortx(context, "Internal ASN1 encoder error"); ret = krb5_padata_add(context, md, pa_type, buf.data, buf.length); if (ret) free(buf.data); if (ret == 0) krb5_padata_add(context, md, KRB5_PADATA_PK_AS_09_BINDING, NULL, 0); out: free_ContentInfo(&content_info); return ret; } KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL _krb5_pk_mk_padata(krb5_context context, void *c, int ic_flags, int win2k, const KDC_REQ_BODY *req_body, unsigned nonce, METHOD_DATA *md) { krb5_pk_init_ctx ctx = c; int win2k_compat; if (ctx->id->certs == NULL && ctx->anonymous == 0) { krb5_set_error_message(context, HEIM_PKINIT_NO_PRIVATE_KEY, N_("PKINIT: No user certificate given", "")); return HEIM_PKINIT_NO_PRIVATE_KEY; } win2k_compat = krb5_config_get_bool_default(context, NULL, win2k, "realms", req_body->realm, "pkinit_win2k", NULL); if (win2k_compat) { ctx->require_binding = krb5_config_get_bool_default(context, NULL, TRUE, "realms", req_body->realm, "pkinit_win2k_require_binding", NULL); ctx->type = PKINIT_WIN2K; } else ctx->type = PKINIT_27; ctx->require_eku = krb5_config_get_bool_default(context, NULL, TRUE, "realms", req_body->realm, "pkinit_require_eku", NULL); if (ic_flags & KRB5_INIT_CREDS_NO_C_NO_EKU_CHECK) ctx->require_eku = 0; if (ctx->id->flags & PKINIT_BTMM) ctx->require_eku = 0; ctx->require_krbtgt_otherName = krb5_config_get_bool_default(context, NULL, TRUE, "realms", req_body->realm, "pkinit_require_krbtgt_otherName", NULL); ctx->require_hostname_match = krb5_config_get_bool_default(context, NULL, FALSE, "realms", req_body->realm, "pkinit_require_hostname_match", NULL); ctx->trustedCertifiers = krb5_config_get_bool_default(context, NULL, TRUE, "realms", req_body->realm, "pkinit_trustedCertifiers", NULL); return pk_mk_padata(context, ctx, req_body, nonce, md); } static krb5_error_code pk_verify_sign(krb5_context context, const void *data, size_t length, struct krb5_pk_identity *id, heim_oid *contentType, krb5_data *content, struct krb5_pk_cert **signer) { hx509_certs signer_certs; int ret, flags = 0; /* BTMM is broken in Leo and SnowLeo */ if (id->flags & PKINIT_BTMM) { flags |= HX509_CMS_VS_ALLOW_DATA_OID_MISMATCH; flags |= HX509_CMS_VS_NO_KU_CHECK; flags |= HX509_CMS_VS_NO_VALIDATE; } *signer = NULL; ret = hx509_cms_verify_signed(context->hx509ctx, id->verify_ctx, flags, data, length, NULL, id->certpool, contentType, content, &signer_certs); if (ret) { pk_copy_error(context, context->hx509ctx, ret, "CMS verify signed failed"); return ret; } *signer = calloc(1, sizeof(**signer)); if (*signer == NULL) { krb5_clear_error_message(context); ret = ENOMEM; goto out; } ret = hx509_get_one_cert(context->hx509ctx, signer_certs, &(*signer)->cert); if (ret) { pk_copy_error(context, context->hx509ctx, ret, "Failed to get on of the signer certs"); goto out; } out: hx509_certs_free(&signer_certs); if (ret) { if (*signer) { hx509_cert_free((*signer)->cert); free(*signer); *signer = NULL; } } return ret; } static krb5_error_code get_reply_key_win(krb5_context context, const krb5_data *content, unsigned nonce, krb5_keyblock **key) { ReplyKeyPack_Win2k key_pack; krb5_error_code ret; size_t size; ret = decode_ReplyKeyPack_Win2k(content->data, content->length, &key_pack, &size); if (ret) { krb5_set_error_message(context, ret, N_("PKINIT decoding reply key failed", "")); free_ReplyKeyPack_Win2k(&key_pack); return ret; } if ((unsigned)key_pack.nonce != nonce) { krb5_set_error_message(context, ret, N_("PKINIT enckey nonce is wrong", "")); free_ReplyKeyPack_Win2k(&key_pack); return KRB5KRB_AP_ERR_MODIFIED; } *key = malloc (sizeof (**key)); if (*key == NULL) { free_ReplyKeyPack_Win2k(&key_pack); return krb5_enomem(context); } ret = copy_EncryptionKey(&key_pack.replyKey, *key); free_ReplyKeyPack_Win2k(&key_pack); if (ret) { krb5_set_error_message(context, ret, N_("PKINIT failed copying reply key", "")); free(*key); *key = NULL; } return ret; } static krb5_error_code get_reply_key(krb5_context context, const krb5_data *content, const krb5_data *req_buffer, krb5_keyblock **key) { ReplyKeyPack key_pack; krb5_error_code ret; size_t size; ret = decode_ReplyKeyPack(content->data, content->length, &key_pack, &size); if (ret) { krb5_set_error_message(context, ret, N_("PKINIT decoding reply key failed", "")); free_ReplyKeyPack(&key_pack); return ret; } { krb5_crypto crypto; /* * XXX Verify kp.replyKey is a allowed enctype in the * configuration file */ ret = krb5_crypto_init(context, &key_pack.replyKey, 0, &crypto); if (ret) { free_ReplyKeyPack(&key_pack); return ret; } ret = krb5_verify_checksum(context, crypto, 6, req_buffer->data, req_buffer->length, &key_pack.asChecksum); krb5_crypto_destroy(context, crypto); if (ret) { free_ReplyKeyPack(&key_pack); return ret; } } *key = malloc (sizeof (**key)); if (*key == NULL) { free_ReplyKeyPack(&key_pack); return krb5_enomem(context); } ret = copy_EncryptionKey(&key_pack.replyKey, *key); free_ReplyKeyPack(&key_pack); if (ret) { krb5_set_error_message(context, ret, N_("PKINIT failed copying reply key", "")); free(*key); *key = NULL; } return ret; } static krb5_error_code pk_verify_host(krb5_context context, const char *realm, const krb5_krbhst_info *hi, struct krb5_pk_init_ctx_data *ctx, struct krb5_pk_cert *host) { krb5_error_code ret = 0; if (ctx->require_eku) { ret = hx509_cert_check_eku(context->hx509ctx, host->cert, &asn1_oid_id_pkkdcekuoid, 0); if (ret) { krb5_set_error_message(context, ret, N_("No PK-INIT KDC EKU in kdc certificate", "")); return ret; } } if (ctx->require_krbtgt_otherName) { hx509_octet_string_list list; size_t i; int matched = 0; ret = hx509_cert_find_subjectAltName_otherName(context->hx509ctx, host->cert, &asn1_oid_id_pkinit_san, &list); if (ret) { krb5_set_error_message(context, ret, N_("Failed to find the PK-INIT " "subjectAltName in the KDC " "certificate", "")); return ret; } /* * subjectAltNames are multi-valued, and a single KDC may serve * multiple realms. The SAN validation here must accept * the KDC's cert if *any* of the SANs match the expected KDC. * It is OK for *some* of the SANs to not match, provided at least * one does. */ for (i = 0; matched == 0 && i < list.len; i++) { KRB5PrincipalName r; ret = decode_KRB5PrincipalName(list.val[i].data, list.val[i].length, &r, NULL); if (ret) { krb5_set_error_message(context, ret, N_("Failed to decode the PK-INIT " "subjectAltName in the " "KDC certificate", "")); break; } if (r.principalName.name_string.len == 2 && strcmp(r.principalName.name_string.val[0], KRB5_TGS_NAME) == 0 && strcmp(r.principalName.name_string.val[1], realm) == 0 && strcmp(r.realm, realm) == 0) matched = 1; free_KRB5PrincipalName(&r); } hx509_free_octet_string_list(&list); if (matched == 0) { ret = KRB5_KDC_ERR_INVALID_CERTIFICATE; /* XXX: Lost in translation... */ krb5_set_error_message(context, ret, N_("KDC have wrong realm name in " "the certificate", "")); } } if (ret) return ret; if (hi) { ret = hx509_verify_hostname(context->hx509ctx, host->cert, ctx->require_hostname_match, HX509_HN_HOSTNAME, hi->hostname, hi->ai->ai_addr, hi->ai->ai_addrlen); if (ret) krb5_set_error_message(context, ret, N_("Address mismatch in " "the KDC certificate", "")); } return ret; } static krb5_error_code pk_rd_pa_reply_enckey(krb5_context context, int type, const heim_octet_string *indata, const heim_oid *dataType, const char *realm, krb5_pk_init_ctx ctx, krb5_enctype etype, const krb5_krbhst_info *hi, unsigned nonce, const krb5_data *req_buffer, PA_DATA *pa, krb5_keyblock **key) { krb5_error_code ret; struct krb5_pk_cert *host = NULL; krb5_data content; heim_oid contentType = { 0, NULL }; int flags = HX509_CMS_UE_DONT_REQUIRE_KU_ENCIPHERMENT; if (der_heim_oid_cmp(&asn1_oid_id_pkcs7_envelopedData, dataType)) { krb5_set_error_message(context, EINVAL, N_("PKINIT: Invalid content type", "")); return EINVAL; } if (ctx->type == PKINIT_WIN2K) flags |= HX509_CMS_UE_ALLOW_WEAK; ret = hx509_cms_unenvelope(context->hx509ctx, ctx->id->certs, flags, indata->data, indata->length, NULL, 0, &contentType, &content); if (ret) { pk_copy_error(context, context->hx509ctx, ret, "Failed to unenvelope CMS data in PK-INIT reply"); return ret; } der_free_oid(&contentType); /* win2k uses ContentInfo */ if (type == PKINIT_WIN2K) { heim_oid type2; heim_octet_string out; ret = hx509_cms_unwrap_ContentInfo(&content, &type2, &out, NULL); if (ret) { /* windows LH with interesting CMS packets */ size_t ph = 1 + der_length_len(content.length); unsigned char *ptr = malloc(content.length + ph); size_t l; memcpy(ptr + ph, content.data, content.length); ret = der_put_length_and_tag (ptr + ph - 1, ph, content.length, ASN1_C_UNIV, CONS, UT_Sequence, &l); if (ret) { free(ptr); return ret; } free(content.data); content.data = ptr; content.length += ph; ret = hx509_cms_unwrap_ContentInfo(&content, &type2, &out, NULL); if (ret) goto out; } if (der_heim_oid_cmp(&type2, &asn1_oid_id_pkcs7_signedData)) { ret = EINVAL; /* XXX */ krb5_set_error_message(context, ret, N_("PKINIT: Invalid content type", "")); der_free_oid(&type2); der_free_octet_string(&out); goto out; } der_free_oid(&type2); krb5_data_free(&content); ret = krb5_data_copy(&content, out.data, out.length); der_free_octet_string(&out); if (ret) { krb5_set_error_message(context, ret, N_("malloc: out of memory", "")); goto out; } } ret = pk_verify_sign(context, content.data, content.length, ctx->id, &contentType, &content, &host); if (ret) goto out; /* make sure that it is the kdc's certificate */ ret = pk_verify_host(context, realm, hi, ctx, host); if (ret) { goto out; } #if 0 if (type == PKINIT_WIN2K) { if (der_heim_oid_cmp(&contentType, &asn1_oid_id_pkcs7_data) != 0) { ret = KRB5KRB_AP_ERR_MSG_TYPE; krb5_set_error_message(context, ret, "PKINIT: reply key, wrong oid"); goto out; } } else { if (der_heim_oid_cmp(&contentType, &asn1_oid_id_pkrkeydata) != 0) { ret = KRB5KRB_AP_ERR_MSG_TYPE; krb5_set_error_message(context, ret, "PKINIT: reply key, wrong oid"); goto out; } } #endif switch(type) { case PKINIT_WIN2K: ret = get_reply_key(context, &content, req_buffer, key); if (ret != 0 && ctx->require_binding == 0) ret = get_reply_key_win(context, &content, nonce, key); break; case PKINIT_27: ret = get_reply_key(context, &content, req_buffer, key); break; } if (ret) goto out; /* XXX compare given etype with key->etype */ out: if (host) _krb5_pk_cert_free(host); der_free_oid(&contentType); krb5_data_free(&content); return ret; } static krb5_error_code pk_rd_pa_reply_dh(krb5_context context, const heim_octet_string *indata, const heim_oid *dataType, const char *realm, krb5_pk_init_ctx ctx, krb5_enctype etype, const krb5_krbhst_info *hi, const DHNonce *c_n, const DHNonce *k_n, unsigned nonce, PA_DATA *pa, krb5_keyblock **key) { const unsigned char *p; unsigned char *dh_gen_key = NULL; struct krb5_pk_cert *host = NULL; BIGNUM *kdc_dh_pubkey = NULL; KDCDHKeyInfo kdc_dh_info; heim_oid contentType = { 0, NULL }; krb5_data content; krb5_error_code ret; int dh_gen_keylen = 0; size_t size; krb5_data_zero(&content); memset(&kdc_dh_info, 0, sizeof(kdc_dh_info)); if (der_heim_oid_cmp(&asn1_oid_id_pkcs7_signedData, dataType)) { krb5_set_error_message(context, EINVAL, N_("PKINIT: Invalid content type", "")); return EINVAL; } ret = pk_verify_sign(context, indata->data, indata->length, ctx->id, &contentType, &content, &host); if (ret) goto out; /* make sure that it is the kdc's certificate */ ret = pk_verify_host(context, realm, hi, ctx, host); if (ret) goto out; if (der_heim_oid_cmp(&contentType, &asn1_oid_id_pkdhkeydata)) { ret = KRB5KRB_AP_ERR_MSG_TYPE; krb5_set_error_message(context, ret, N_("pkinit - dh reply contains wrong oid", "")); goto out; } ret = decode_KDCDHKeyInfo(content.data, content.length, &kdc_dh_info, &size); if (ret) { krb5_set_error_message(context, ret, N_("pkinit - failed to decode " "KDC DH Key Info", "")); goto out; } if (kdc_dh_info.nonce != nonce) { ret = KRB5KRB_AP_ERR_MODIFIED; krb5_set_error_message(context, ret, N_("PKINIT: DH nonce is wrong", "")); goto out; } if (kdc_dh_info.dhKeyExpiration) { if (k_n == NULL) { ret = KRB5KRB_ERR_GENERIC; krb5_set_error_message(context, ret, N_("pkinit; got key expiration " "without server nonce", "")); goto out; } if (c_n == NULL) { ret = KRB5KRB_ERR_GENERIC; krb5_set_error_message(context, ret, N_("pkinit; got DH reuse but no " "client nonce", "")); goto out; } } else { if (k_n) { ret = KRB5KRB_ERR_GENERIC; krb5_set_error_message(context, ret, N_("pkinit: got server nonce " "without key expiration", "")); goto out; } c_n = NULL; } p = kdc_dh_info.subjectPublicKey.data; size = (kdc_dh_info.subjectPublicKey.length + 7) / 8; if (ctx->keyex == USE_DH) { DHPublicKey k; ret = decode_DHPublicKey(p, size, &k, NULL); if (ret) { krb5_set_error_message(context, ret, N_("pkinit: can't decode " "without key expiration", "")); goto out; } kdc_dh_pubkey = integer_to_BN(context, "DHPublicKey", &k); free_DHPublicKey(&k); if (kdc_dh_pubkey == NULL) { ret = ENOMEM; goto out; } size = DH_size(ctx->u.dh); dh_gen_key = malloc(size); if (dh_gen_key == NULL) { ret = krb5_enomem(context); goto out; } dh_gen_keylen = DH_compute_key(dh_gen_key, kdc_dh_pubkey, ctx->u.dh); if (dh_gen_keylen == -1) { ret = KRB5KRB_ERR_GENERIC; dh_gen_keylen = 0; krb5_set_error_message(context, ret, N_("PKINIT: Can't compute Diffie-Hellman key", "")); goto out; } if (dh_gen_keylen < (int)size) { size -= dh_gen_keylen; memmove(dh_gen_key + size, dh_gen_key, dh_gen_keylen); memset(dh_gen_key, 0, size); } } else { ret = _krb5_pk_rd_pa_reply_ecdh_compute_key(context, ctx, p, size, &dh_gen_key, &dh_gen_keylen); if (ret) goto out; } if (dh_gen_keylen <= 0) { ret = EINVAL; krb5_set_error_message(context, ret, N_("PKINIT: resulting DH key <= 0", "")); dh_gen_keylen = 0; goto out; } *key = malloc (sizeof (**key)); if (*key == NULL) { ret = krb5_enomem(context); goto out; } ret = _krb5_pk_octetstring2key(context, etype, dh_gen_key, dh_gen_keylen, c_n, k_n, *key); if (ret) { krb5_set_error_message(context, ret, N_("PKINIT: can't create key from DH key", "")); free(*key); *key = NULL; goto out; } out: if (kdc_dh_pubkey) BN_free(kdc_dh_pubkey); if (dh_gen_key) { memset(dh_gen_key, 0, dh_gen_keylen); free(dh_gen_key); } if (host) _krb5_pk_cert_free(host); if (content.data) krb5_data_free(&content); der_free_oid(&contentType); free_KDCDHKeyInfo(&kdc_dh_info); return ret; } KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL _krb5_pk_rd_pa_reply(krb5_context context, const char *realm, void *c, krb5_enctype etype, const krb5_krbhst_info *hi, unsigned nonce, const krb5_data *req_buffer, PA_DATA *pa, krb5_keyblock **key) { krb5_pk_init_ctx ctx = c; krb5_error_code ret; size_t size; /* Check for IETF PK-INIT first */ if (ctx->type == PKINIT_27) { PA_PK_AS_REP rep; heim_octet_string os, data; heim_oid oid; if (pa->padata_type != KRB5_PADATA_PK_AS_REP) { krb5_set_error_message(context, EINVAL, N_("PKINIT: wrong padata recv", "")); return EINVAL; } ret = decode_PA_PK_AS_REP(pa->padata_value.data, pa->padata_value.length, &rep, &size); if (ret) { krb5_set_error_message(context, ret, N_("Failed to decode pkinit AS rep", "")); return ret; } switch (rep.element) { case choice_PA_PK_AS_REP_dhInfo: _krb5_debug(context, 5, "krb5_get_init_creds: using pkinit dh"); os = rep.u.dhInfo.dhSignedData; break; case choice_PA_PK_AS_REP_encKeyPack: _krb5_debug(context, 5, "krb5_get_init_creds: using kinit enc reply key"); os = rep.u.encKeyPack; break; default: { PA_PK_AS_REP_BTMM btmm; free_PA_PK_AS_REP(&rep); memset(&rep, 0, sizeof(rep)); _krb5_debug(context, 5, "krb5_get_init_creds: using BTMM kinit enc reply key"); ret = decode_PA_PK_AS_REP_BTMM(pa->padata_value.data, pa->padata_value.length, &btmm, &size); if (ret) { krb5_set_error_message(context, EINVAL, N_("PKINIT: -27 reply " "invalid content type", "")); return EINVAL; } if (btmm.dhSignedData || btmm.encKeyPack == NULL) { free_PA_PK_AS_REP_BTMM(&btmm); ret = EINVAL; krb5_set_error_message(context, ret, N_("DH mode not supported for BTMM mode", "")); return ret; } /* * Transform to IETF style PK-INIT reply so that free works below */ rep.element = choice_PA_PK_AS_REP_encKeyPack; rep.u.encKeyPack.data = btmm.encKeyPack->data; rep.u.encKeyPack.length = btmm.encKeyPack->length; btmm.encKeyPack->data = NULL; btmm.encKeyPack->length = 0; free_PA_PK_AS_REP_BTMM(&btmm); os = rep.u.encKeyPack; } } ret = hx509_cms_unwrap_ContentInfo(&os, &oid, &data, NULL); if (ret) { free_PA_PK_AS_REP(&rep); krb5_set_error_message(context, ret, N_("PKINIT: failed to unwrap CI", "")); return ret; } switch (rep.element) { case choice_PA_PK_AS_REP_dhInfo: ret = pk_rd_pa_reply_dh(context, &data, &oid, realm, ctx, etype, hi, ctx->clientDHNonce, rep.u.dhInfo.serverDHNonce, nonce, pa, key); break; case choice_PA_PK_AS_REP_encKeyPack: ret = pk_rd_pa_reply_enckey(context, PKINIT_27, &data, &oid, realm, ctx, etype, hi, nonce, req_buffer, pa, key); break; default: krb5_abortx(context, "pk-init as-rep case not possible to happen"); } der_free_octet_string(&data); der_free_oid(&oid); free_PA_PK_AS_REP(&rep); } else if (ctx->type == PKINIT_WIN2K) { PA_PK_AS_REP_Win2k w2krep; /* Check for Windows encoding of the AS-REP pa data */ #if 0 /* should this be ? */ if (pa->padata_type != KRB5_PADATA_PK_AS_REP) { krb5_set_error_message(context, EINVAL, "PKINIT: wrong padata recv"); return EINVAL; } #endif memset(&w2krep, 0, sizeof(w2krep)); ret = decode_PA_PK_AS_REP_Win2k(pa->padata_value.data, pa->padata_value.length, &w2krep, &size); if (ret) { krb5_set_error_message(context, ret, N_("PKINIT: Failed decoding windows " "pkinit reply %d", ""), (int)ret); return ret; } krb5_clear_error_message(context); switch (w2krep.element) { case choice_PA_PK_AS_REP_Win2k_encKeyPack: { heim_octet_string data; heim_oid oid; ret = hx509_cms_unwrap_ContentInfo(&w2krep.u.encKeyPack, &oid, &data, NULL); free_PA_PK_AS_REP_Win2k(&w2krep); if (ret) { krb5_set_error_message(context, ret, N_("PKINIT: failed to unwrap CI", "")); return ret; } ret = pk_rd_pa_reply_enckey(context, PKINIT_WIN2K, &data, &oid, realm, ctx, etype, hi, nonce, req_buffer, pa, key); der_free_octet_string(&data); der_free_oid(&oid); break; } default: free_PA_PK_AS_REP_Win2k(&w2krep); ret = EINVAL; krb5_set_error_message(context, ret, N_("PKINIT: win2k reply invalid " "content type", "")); break; } } else { ret = EINVAL; krb5_set_error_message(context, ret, N_("PKINIT: unknown reply type", "")); } return ret; } struct prompter { krb5_context context; krb5_prompter_fct prompter; void *prompter_data; }; static int hx_pass_prompter(void *data, const hx509_prompt *prompter) { krb5_error_code ret; krb5_prompt prompt; krb5_data password_data; struct prompter *p = data; password_data.data = prompter->reply.data; password_data.length = prompter->reply.length; prompt.prompt = prompter->prompt; prompt.hidden = hx509_prompt_hidden(prompter->type); prompt.reply = &password_data; switch (prompter->type) { case HX509_PROMPT_TYPE_INFO: prompt.type = KRB5_PROMPT_TYPE_INFO; break; case HX509_PROMPT_TYPE_PASSWORD: case HX509_PROMPT_TYPE_QUESTION: default: prompt.type = KRB5_PROMPT_TYPE_PASSWORD; break; } ret = (*p->prompter)(p->context, p->prompter_data, NULL, NULL, 1, &prompt); if (ret) { memset (prompter->reply.data, 0, prompter->reply.length); return 1; } return 0; } static krb5_error_code _krb5_pk_set_user_id(krb5_context context, krb5_principal principal, krb5_pk_init_ctx ctx, struct hx509_certs_data *certs) { hx509_certs c = hx509_certs_ref(certs); hx509_query *q = NULL; int ret; if (ctx->id->certs) hx509_certs_free(&ctx->id->certs); if (ctx->id->cert) { hx509_cert_free(ctx->id->cert); ctx->id->cert = NULL; } ctx->id->certs = c; ctx->anonymous = 0; ret = hx509_query_alloc(context->hx509ctx, &q); if (ret) { pk_copy_error(context, context->hx509ctx, ret, "Allocate query to find signing certificate"); return ret; } hx509_query_match_option(q, HX509_QUERY_OPTION_PRIVATE_KEY); hx509_query_match_option(q, HX509_QUERY_OPTION_KU_DIGITALSIGNATURE); if (principal && strncmp("LKDC:SHA1.", krb5_principal_get_realm(context, principal), 9) == 0) { ctx->id->flags |= PKINIT_BTMM; } ret = find_cert(context, ctx->id, q, &ctx->id->cert); hx509_query_free(context->hx509ctx, q); if (ret == 0 && _krb5_have_debug(context, 2)) { hx509_name name; char *str, *sn; heim_integer i; ret = hx509_cert_get_subject(ctx->id->cert, &name); if (ret) goto out; ret = hx509_name_to_string(name, &str); hx509_name_free(&name); if (ret) goto out; ret = hx509_cert_get_serialnumber(ctx->id->cert, &i); if (ret) { free(str); goto out; } ret = der_print_hex_heim_integer(&i, &sn); der_free_heim_integer(&i); if (ret) { free(name); goto out; } _krb5_debug(context, 2, "using cert: subject: %s sn: %s", str, sn); free(str); free(sn); } out: return ret; } KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL _krb5_pk_load_id(krb5_context context, struct krb5_pk_identity **ret_id, const char *user_id, const char *anchor_id, char * const *chain_list, char * const *revoke_list, krb5_prompter_fct prompter, void *prompter_data, char *password) { struct krb5_pk_identity *id = NULL; struct prompter p; int ret; *ret_id = NULL; if (anchor_id == NULL) { krb5_set_error_message(context, HEIM_PKINIT_NO_VALID_CA, N_("PKINIT: No anchor given", "")); return HEIM_PKINIT_NO_VALID_CA; } /* load cert */ id = calloc(1, sizeof(*id)); if (id == NULL) return krb5_enomem(context); if (user_id) { hx509_lock lock; ret = hx509_lock_init(context->hx509ctx, &lock); if (ret) { pk_copy_error(context, context->hx509ctx, ret, "Failed init lock"); goto out; } if (password && password[0]) hx509_lock_add_password(lock, password); if (prompter) { p.context = context; p.prompter = prompter; p.prompter_data = prompter_data; ret = hx509_lock_set_prompter(lock, hx_pass_prompter, &p); if (ret) { hx509_lock_free(lock); goto out; } } ret = hx509_certs_init(context->hx509ctx, user_id, 0, lock, &id->certs); hx509_lock_free(lock); if (ret) { pk_copy_error(context, context->hx509ctx, ret, "Failed to init cert certs"); goto out; } } else { id->certs = NULL; } ret = hx509_certs_init(context->hx509ctx, anchor_id, 0, NULL, &id->anchors); if (ret) { pk_copy_error(context, context->hx509ctx, ret, "Failed to init anchors"); goto out; } ret = hx509_certs_init(context->hx509ctx, "MEMORY:pkinit-cert-chain", 0, NULL, &id->certpool); if (ret) { pk_copy_error(context, context->hx509ctx, ret, "Failed to init chain"); goto out; } while (chain_list && *chain_list) { ret = hx509_certs_append(context->hx509ctx, id->certpool, NULL, *chain_list); if (ret) { pk_copy_error(context, context->hx509ctx, ret, "Failed to laod chain %s", *chain_list); goto out; } chain_list++; } if (revoke_list) { ret = hx509_revoke_init(context->hx509ctx, &id->revokectx); if (ret) { pk_copy_error(context, context->hx509ctx, ret, "Failed init revoke list"); goto out; } while (*revoke_list) { ret = hx509_revoke_add_crl(context->hx509ctx, id->revokectx, *revoke_list); if (ret) { pk_copy_error(context, context->hx509ctx, ret, "Failed load revoke list"); goto out; } revoke_list++; } } else hx509_context_set_missing_revoke(context->hx509ctx, 1); ret = hx509_verify_init_ctx(context->hx509ctx, &id->verify_ctx); if (ret) { pk_copy_error(context, context->hx509ctx, ret, "Failed init verify context"); goto out; } hx509_verify_attach_anchors(id->verify_ctx, id->anchors); hx509_verify_attach_revoke(id->verify_ctx, id->revokectx); out: if (ret) { hx509_verify_destroy_ctx(id->verify_ctx); hx509_certs_free(&id->certs); hx509_certs_free(&id->anchors); hx509_certs_free(&id->certpool); hx509_revoke_free(&id->revokectx); free(id); } else *ret_id = id; return ret; } /* * */ static void pk_copy_error(krb5_context context, hx509_context hx509ctx, int hxret, const char *fmt, ...) { va_list va; char *s, *f; int ret; va_start(va, fmt); ret = vasprintf(&f, fmt, va); va_end(va); if (ret == -1 || f == NULL) { krb5_clear_error_message(context); return; } s = hx509_get_error_string(hx509ctx, hxret); if (s == NULL) { krb5_clear_error_message(context); free(f); return; } krb5_set_error_message(context, hxret, "%s: %s", f, s); free(s); free(f); } static int parse_integer(krb5_context context, char **p, const char *file, int lineno, const char *name, heim_integer *integer) { int ret; char *p1; p1 = strsep(p, " \t"); if (p1 == NULL) { krb5_set_error_message(context, EINVAL, N_("moduli file %s missing %s on line %d", ""), file, name, lineno); return EINVAL; } ret = der_parse_hex_heim_integer(p1, integer); if (ret) { krb5_set_error_message(context, ret, N_("moduli file %s failed parsing %s " "on line %d", ""), file, name, lineno); return ret; } return 0; } KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL _krb5_parse_moduli_line(krb5_context context, const char *file, int lineno, char *p, struct krb5_dh_moduli **m) { struct krb5_dh_moduli *m1; char *p1; int ret; *m = NULL; m1 = calloc(1, sizeof(*m1)); if (m1 == NULL) return krb5_enomem(context); while (isspace((unsigned char)*p)) p++; if (*p == '#') { free(m1); return 0; } ret = EINVAL; p1 = strsep(&p, " \t"); if (p1 == NULL) { krb5_set_error_message(context, ret, N_("moduli file %s missing name on line %d", ""), file, lineno); goto out; } m1->name = strdup(p1); if (m1->name == NULL) { ret = krb5_enomem(context); goto out; } p1 = strsep(&p, " \t"); if (p1 == NULL) { krb5_set_error_message(context, ret, N_("moduli file %s missing bits on line %d", ""), file, lineno); goto out; } m1->bits = atoi(p1); if (m1->bits == 0) { krb5_set_error_message(context, ret, N_("moduli file %s have un-parsable " "bits on line %d", ""), file, lineno); goto out; } ret = parse_integer(context, &p, file, lineno, "p", &m1->p); if (ret) goto out; ret = parse_integer(context, &p, file, lineno, "g", &m1->g); if (ret) goto out; ret = parse_integer(context, &p, file, lineno, "q", &m1->q); if (ret) goto out; *m = m1; return 0; out: free(m1->name); der_free_heim_integer(&m1->p); der_free_heim_integer(&m1->g); der_free_heim_integer(&m1->q); free(m1); return ret; } KRB5_LIB_FUNCTION void KRB5_LIB_CALL _krb5_free_moduli(struct krb5_dh_moduli **moduli) { int i; for (i = 0; moduli[i] != NULL; i++) { free(moduli[i]->name); der_free_heim_integer(&moduli[i]->p); der_free_heim_integer(&moduli[i]->g); der_free_heim_integer(&moduli[i]->q); free(moduli[i]); } free(moduli); } static const char *default_moduli_RFC2412_MODP_group2 = /* name */ "RFC2412-MODP-group2 " /* bits */ "1024 " /* p */ "FFFFFFFF" "FFFFFFFF" "C90FDAA2" "2168C234" "C4C6628B" "80DC1CD1" "29024E08" "8A67CC74" "020BBEA6" "3B139B22" "514A0879" "8E3404DD" "EF9519B3" "CD3A431B" "302B0A6D" "F25F1437" "4FE1356D" "6D51C245" "E485B576" "625E7EC6" "F44C42E9" "A637ED6B" "0BFF5CB6" "F406B7ED" "EE386BFB" "5A899FA5" "AE9F2411" "7C4B1FE6" "49286651" "ECE65381" "FFFFFFFF" "FFFFFFFF " /* g */ "02 " /* q */ "7FFFFFFF" "FFFFFFFF" "E487ED51" "10B4611A" "62633145" "C06E0E68" "94812704" "4533E63A" "0105DF53" "1D89CD91" "28A5043C" "C71A026E" "F7CA8CD9" "E69D218D" "98158536" "F92F8A1B" "A7F09AB6" "B6A8E122" "F242DABB" "312F3F63" "7A262174" "D31BF6B5" "85FFAE5B" "7A035BF6" "F71C35FD" "AD44CFD2" "D74F9208" "BE258FF3" "24943328" "F67329C0" "FFFFFFFF" "FFFFFFFF"; static const char *default_moduli_rfc3526_MODP_group14 = /* name */ "rfc3526-MODP-group14 " /* bits */ "1760 " /* p */ "FFFFFFFF" "FFFFFFFF" "C90FDAA2" "2168C234" "C4C6628B" "80DC1CD1" "29024E08" "8A67CC74" "020BBEA6" "3B139B22" "514A0879" "8E3404DD" "EF9519B3" "CD3A431B" "302B0A6D" "F25F1437" "4FE1356D" "6D51C245" "E485B576" "625E7EC6" "F44C42E9" "A637ED6B" "0BFF5CB6" "F406B7ED" "EE386BFB" "5A899FA5" "AE9F2411" "7C4B1FE6" "49286651" "ECE45B3D" "C2007CB8" "A163BF05" "98DA4836" "1C55D39A" "69163FA8" "FD24CF5F" "83655D23" "DCA3AD96" "1C62F356" "208552BB" "9ED52907" "7096966D" "670C354E" "4ABC9804" "F1746C08" "CA18217C" "32905E46" "2E36CE3B" "E39E772C" "180E8603" "9B2783A2" "EC07A28F" "B5C55DF0" "6F4C52C9" "DE2BCBF6" "95581718" "3995497C" "EA956AE5" "15D22618" "98FA0510" "15728E5A" "8AACAA68" "FFFFFFFF" "FFFFFFFF " /* g */ "02 " /* q */ "7FFFFFFF" "FFFFFFFF" "E487ED51" "10B4611A" "62633145" "C06E0E68" "94812704" "4533E63A" "0105DF53" "1D89CD91" "28A5043C" "C71A026E" "F7CA8CD9" "E69D218D" "98158536" "F92F8A1B" "A7F09AB6" "B6A8E122" "F242DABB" "312F3F63" "7A262174" "D31BF6B5" "85FFAE5B" "7A035BF6" "F71C35FD" "AD44CFD2" "D74F9208" "BE258FF3" "24943328" "F6722D9E" "E1003E5C" "50B1DF82" "CC6D241B" "0E2AE9CD" "348B1FD4" "7E9267AF" "C1B2AE91" "EE51D6CB" "0E3179AB" "1042A95D" "CF6A9483" "B84B4B36" "B3861AA7" "255E4C02" "78BA3604" "650C10BE" "19482F23" "171B671D" "F1CF3B96" "0C074301" "CD93C1D1" "7603D147" "DAE2AEF8" "37A62964" "EF15E5FB" "4AAC0B8C" "1CCAA4BE" "754AB572" "8AE9130C" "4C7D0288" "0AB9472D" "45565534" "7FFFFFFF" "FFFFFFFF"; KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL _krb5_parse_moduli(krb5_context context, const char *file, struct krb5_dh_moduli ***moduli) { /* name bits P G Q */ krb5_error_code ret; struct krb5_dh_moduli **m = NULL, **m2; char buf[4096]; FILE *f; int lineno = 0, n = 0; *moduli = NULL; m = calloc(1, sizeof(m[0]) * 3); if (m == NULL) return krb5_enomem(context); strlcpy(buf, default_moduli_rfc3526_MODP_group14, sizeof(buf)); ret = _krb5_parse_moduli_line(context, "builtin", 1, buf, &m[0]); if (ret) { _krb5_free_moduli(m); return ret; } n++; strlcpy(buf, default_moduli_RFC2412_MODP_group2, sizeof(buf)); ret = _krb5_parse_moduli_line(context, "builtin", 1, buf, &m[1]); if (ret) { _krb5_free_moduli(m); return ret; } n++; if (file == NULL) file = MODULI_FILE; #ifdef KRB5_USE_PATH_TOKENS { char * exp_file; if (_krb5_expand_path_tokens(context, file, 1, &exp_file) == 0) { f = fopen(exp_file, "r"); krb5_xfree(exp_file); } else { f = NULL; } } #else f = fopen(file, "r"); #endif if (f == NULL) { *moduli = m; return 0; } rk_cloexec_file(f); while(fgets(buf, sizeof(buf), f) != NULL) { struct krb5_dh_moduli *element; buf[strcspn(buf, "\n")] = '\0'; lineno++; m2 = realloc(m, (n + 2) * sizeof(m[0])); if (m2 == NULL) { _krb5_free_moduli(m); return krb5_enomem(context); } m = m2; m[n] = NULL; ret = _krb5_parse_moduli_line(context, file, lineno, buf, &element); if (ret) { _krb5_free_moduli(m); return ret; } if (element == NULL) continue; m[n] = element; m[n + 1] = NULL; n++; } *moduli = m; return 0; } KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL _krb5_dh_group_ok(krb5_context context, unsigned long bits, heim_integer *p, heim_integer *g, heim_integer *q, struct krb5_dh_moduli **moduli, char **name) { int i; if (name) *name = NULL; for (i = 0; moduli[i] != NULL; i++) { if (der_heim_integer_cmp(&moduli[i]->g, g) == 0 && der_heim_integer_cmp(&moduli[i]->p, p) == 0 && (q == NULL || der_heim_integer_cmp(&moduli[i]->q, q) == 0)) { if (bits && bits > moduli[i]->bits) { krb5_set_error_message(context, KRB5_KDC_ERR_DH_KEY_PARAMETERS_NOT_ACCEPTED, N_("PKINIT: DH group parameter %s " "no accepted, not enough bits " "generated", ""), moduli[i]->name); return KRB5_KDC_ERR_DH_KEY_PARAMETERS_NOT_ACCEPTED; } if (name) *name = strdup(moduli[i]->name); return 0; } } krb5_set_error_message(context, KRB5_KDC_ERR_DH_KEY_PARAMETERS_NOT_ACCEPTED, N_("PKINIT: DH group parameter no ok", "")); return KRB5_KDC_ERR_DH_KEY_PARAMETERS_NOT_ACCEPTED; } #endif /* PKINIT */ KRB5_LIB_FUNCTION void KRB5_LIB_CALL _krb5_get_init_creds_opt_free_pkinit(krb5_get_init_creds_opt *opt) { #ifdef PKINIT krb5_pk_init_ctx ctx; if (opt->opt_private == NULL || opt->opt_private->pk_init_ctx == NULL) return; ctx = opt->opt_private->pk_init_ctx; switch (ctx->keyex) { case USE_DH: if (ctx->u.dh) DH_free(ctx->u.dh); break; case USE_RSA: break; case USE_ECDH: if (ctx->u.eckey) _krb5_pk_eckey_free(ctx->u.eckey); break; } if (ctx->id) { hx509_verify_destroy_ctx(ctx->id->verify_ctx); hx509_certs_free(&ctx->id->certs); hx509_cert_free(ctx->id->cert); hx509_certs_free(&ctx->id->anchors); hx509_certs_free(&ctx->id->certpool); if (ctx->clientDHNonce) { krb5_free_data(NULL, ctx->clientDHNonce); ctx->clientDHNonce = NULL; } if (ctx->m) _krb5_free_moduli(ctx->m); free(ctx->id); ctx->id = NULL; } free(opt->opt_private->pk_init_ctx); opt->opt_private->pk_init_ctx = NULL; #endif } KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_get_init_creds_opt_set_pkinit(krb5_context context, krb5_get_init_creds_opt *opt, krb5_principal principal, const char *user_id, const char *x509_anchors, char * const * pool, char * const * pki_revoke, int flags, krb5_prompter_fct prompter, void *prompter_data, char *password) { #ifdef PKINIT krb5_error_code ret; char *anchors = NULL; if (opt->opt_private == NULL) { krb5_set_error_message(context, EINVAL, N_("PKINIT: on non extendable opt", "")); return EINVAL; } opt->opt_private->pk_init_ctx = calloc(1, sizeof(*opt->opt_private->pk_init_ctx)); if (opt->opt_private->pk_init_ctx == NULL) return krb5_enomem(context); opt->opt_private->pk_init_ctx->require_binding = 0; opt->opt_private->pk_init_ctx->require_eku = 1; opt->opt_private->pk_init_ctx->require_krbtgt_otherName = 1; opt->opt_private->pk_init_ctx->peer = NULL; /* XXX implement krb5_appdefault_strings */ if (pool == NULL) pool = krb5_config_get_strings(context, NULL, "appdefaults", "pkinit_pool", NULL); if (pki_revoke == NULL) pki_revoke = krb5_config_get_strings(context, NULL, "appdefaults", "pkinit_revoke", NULL); if (x509_anchors == NULL) { krb5_appdefault_string(context, "kinit", krb5_principal_get_realm(context, principal), "pkinit_anchors", NULL, &anchors); x509_anchors = anchors; } if (flags & 4) opt->opt_private->pk_init_ctx->anonymous = 1; ret = _krb5_pk_load_id(context, &opt->opt_private->pk_init_ctx->id, user_id, x509_anchors, pool, pki_revoke, prompter, prompter_data, password); if (ret) { free(opt->opt_private->pk_init_ctx); opt->opt_private->pk_init_ctx = NULL; return ret; } if (opt->opt_private->pk_init_ctx->id->certs) { _krb5_pk_set_user_id(context, principal, opt->opt_private->pk_init_ctx, opt->opt_private->pk_init_ctx->id->certs); } else opt->opt_private->pk_init_ctx->id->cert = NULL; if ((flags & 2) == 0) { hx509_context hx509ctx = context->hx509ctx; hx509_cert cert = opt->opt_private->pk_init_ctx->id->cert; opt->opt_private->pk_init_ctx->keyex = USE_DH; /* * If its a ECDSA certs, lets select ECDSA as the keyex algorithm. */ if (cert) { AlgorithmIdentifier alg; ret = hx509_cert_get_SPKI_AlgorithmIdentifier(hx509ctx, cert, &alg); if (ret == 0) { if (der_heim_oid_cmp(&alg.algorithm, &asn1_oid_id_ecPublicKey) == 0) opt->opt_private->pk_init_ctx->keyex = USE_ECDH; free_AlgorithmIdentifier(&alg); } } } else { opt->opt_private->pk_init_ctx->keyex = USE_RSA; if (opt->opt_private->pk_init_ctx->id->certs == NULL) { krb5_set_error_message(context, EINVAL, N_("No anonymous pkinit support in RSA mode", "")); return EINVAL; } } return 0; #else krb5_set_error_message(context, EINVAL, N_("no support for PKINIT compiled in", "")); return EINVAL; #endif } krb5_error_code KRB5_LIB_FUNCTION krb5_get_init_creds_opt_set_pkinit_user_certs(krb5_context context, krb5_get_init_creds_opt *opt, struct hx509_certs_data *certs) { #ifdef PKINIT if (opt->opt_private == NULL) { krb5_set_error_message(context, EINVAL, N_("PKINIT: on non extendable opt", "")); return EINVAL; } if (opt->opt_private->pk_init_ctx == NULL) { krb5_set_error_message(context, EINVAL, N_("PKINIT: on pkinit context", "")); return EINVAL; } _krb5_pk_set_user_id(context, NULL, opt->opt_private->pk_init_ctx, certs); return 0; #else krb5_set_error_message(context, EINVAL, N_("no support for PKINIT compiled in", "")); return EINVAL; #endif } #ifdef PKINIT static int get_ms_san(hx509_context context, hx509_cert cert, char **upn) { hx509_octet_string_list list; int ret; *upn = NULL; ret = hx509_cert_find_subjectAltName_otherName(context, cert, &asn1_oid_id_pkinit_ms_san, &list); if (ret) return 0; if (list.len > 0 && list.val[0].length > 0) ret = decode_MS_UPN_SAN(list.val[0].data, list.val[0].length, upn, NULL); else ret = 1; hx509_free_octet_string_list(&list); return ret; } static int find_ms_san(hx509_context context, hx509_cert cert, void *ctx) { char *upn; int ret; ret = get_ms_san(context, cert, &upn); if (ret == 0) free(upn); return ret; } #endif /* * Private since it need to be redesigned using krb5_get_init_creds() */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_pk_enterprise_cert(krb5_context context, const char *user_id, krb5_const_realm realm, krb5_principal *principal, struct hx509_certs_data **res) { #ifdef PKINIT krb5_error_code ret; hx509_certs certs, result; hx509_cert cert = NULL; hx509_query *q; char *name; *principal = NULL; if (res) *res = NULL; if (user_id == NULL) { krb5_set_error_message(context, ENOENT, "no user id"); return ENOENT; } ret = hx509_certs_init(context->hx509ctx, user_id, 0, NULL, &certs); if (ret) { pk_copy_error(context, context->hx509ctx, ret, "Failed to init cert certs"); goto out; } ret = hx509_query_alloc(context->hx509ctx, &q); if (ret) { krb5_set_error_message(context, ret, "out of memory"); hx509_certs_free(&certs); goto out; } hx509_query_match_option(q, HX509_QUERY_OPTION_PRIVATE_KEY); hx509_query_match_option(q, HX509_QUERY_OPTION_KU_DIGITALSIGNATURE); hx509_query_match_eku(q, &asn1_oid_id_pkinit_ms_eku); hx509_query_match_cmp_func(q, find_ms_san, NULL); ret = hx509_certs_filter(context->hx509ctx, certs, q, &result); hx509_query_free(context->hx509ctx, q); hx509_certs_free(&certs); if (ret) { pk_copy_error(context, context->hx509ctx, ret, "Failed to find PKINIT certificate"); return ret; } ret = hx509_get_one_cert(context->hx509ctx, result, &cert); hx509_certs_free(&result); if (ret) { pk_copy_error(context, context->hx509ctx, ret, "Failed to get one cert"); goto out; } ret = get_ms_san(context->hx509ctx, cert, &name); if (ret) { pk_copy_error(context, context->hx509ctx, ret, "Failed to get MS SAN"); goto out; } ret = krb5_make_principal(context, principal, realm, name, NULL); free(name); if (ret) goto out; krb5_principal_set_type(context, *principal, KRB5_NT_ENTERPRISE_PRINCIPAL); if (res) { ret = hx509_certs_init(context->hx509ctx, "MEMORY:", 0, NULL, res); if (ret) goto out; ret = hx509_certs_add(context->hx509ctx, *res, cert); if (ret) { hx509_certs_free(res); goto out; } } out: hx509_cert_free(cert); return ret; #else krb5_set_error_message(context, EINVAL, N_("no support for PKINIT compiled in", "")); return EINVAL; #endif } heimdal-7.5.0/lib/krb5/codec.c0000644000175000017500000001414713026237312014112 0ustar niknik/* * Copyright (c) 1998 - 2001 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "krb5_locl.h" #ifndef HEIMDAL_SMALLER KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_decode_EncTicketPart (krb5_context context, const void *data, size_t length, EncTicketPart *t, size_t *len) KRB5_DEPRECATED_FUNCTION("Use X instead") { return decode_EncTicketPart(data, length, t, len); } KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_encode_EncTicketPart (krb5_context context, void *data, size_t length, EncTicketPart *t, size_t *len) KRB5_DEPRECATED_FUNCTION("Use X instead") { return encode_EncTicketPart(data, length, t, len); } KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_decode_EncASRepPart (krb5_context context, const void *data, size_t length, EncASRepPart *t, size_t *len) KRB5_DEPRECATED_FUNCTION("Use X instead") { return decode_EncASRepPart(data, length, t, len); } KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_encode_EncASRepPart (krb5_context context, void *data, size_t length, EncASRepPart *t, size_t *len) KRB5_DEPRECATED_FUNCTION("Use X instead") { return encode_EncASRepPart(data, length, t, len); } KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_decode_EncTGSRepPart (krb5_context context, const void *data, size_t length, EncTGSRepPart *t, size_t *len) KRB5_DEPRECATED_FUNCTION("Use X instead") { return decode_EncTGSRepPart(data, length, t, len); } KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_encode_EncTGSRepPart (krb5_context context, void *data, size_t length, EncTGSRepPart *t, size_t *len) KRB5_DEPRECATED_FUNCTION("Use X instead") { return encode_EncTGSRepPart(data, length, t, len); } KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_decode_EncAPRepPart (krb5_context context, const void *data, size_t length, EncAPRepPart *t, size_t *len) KRB5_DEPRECATED_FUNCTION("Use X instead") { return decode_EncAPRepPart(data, length, t, len); } KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_encode_EncAPRepPart (krb5_context context, void *data, size_t length, EncAPRepPart *t, size_t *len) KRB5_DEPRECATED_FUNCTION("Use X instead") { return encode_EncAPRepPart(data, length, t, len); } KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_decode_Authenticator (krb5_context context, const void *data, size_t length, Authenticator *t, size_t *len) KRB5_DEPRECATED_FUNCTION("Use X instead") { return decode_Authenticator(data, length, t, len); } KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_encode_Authenticator (krb5_context context, void *data, size_t length, Authenticator *t, size_t *len) KRB5_DEPRECATED_FUNCTION("Use X instead") { return encode_Authenticator(data, length, t, len); } KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_decode_EncKrbCredPart (krb5_context context, const void *data, size_t length, EncKrbCredPart *t, size_t *len) KRB5_DEPRECATED_FUNCTION("Use X instead") { return decode_EncKrbCredPart(data, length, t, len); } KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_encode_EncKrbCredPart (krb5_context context, void *data, size_t length, EncKrbCredPart *t, size_t *len) KRB5_DEPRECATED_FUNCTION("Use X instead") { return encode_EncKrbCredPart (data, length, t, len); } KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_decode_ETYPE_INFO (krb5_context context, const void *data, size_t length, ETYPE_INFO *t, size_t *len) KRB5_DEPRECATED_FUNCTION("Use X instead") { return decode_ETYPE_INFO(data, length, t, len); } KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_encode_ETYPE_INFO (krb5_context context, void *data, size_t length, ETYPE_INFO *t, size_t *len) KRB5_DEPRECATED_FUNCTION("Use X instead") { return encode_ETYPE_INFO (data, length, t, len); } KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_decode_ETYPE_INFO2 (krb5_context context, const void *data, size_t length, ETYPE_INFO2 *t, size_t *len) KRB5_DEPRECATED_FUNCTION("Use X instead") { return decode_ETYPE_INFO2(data, length, t, len); } KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_encode_ETYPE_INFO2 (krb5_context context, void *data, size_t length, ETYPE_INFO2 *t, size_t *len) KRB5_DEPRECATED_FUNCTION("Use X instead") { return encode_ETYPE_INFO2 (data, length, t, len); } #endif /* HEIMDAL_SMALLER */ heimdal-7.5.0/lib/krb5/constants.c0000644000175000017500000000527513026237312015053 0ustar niknik/* * Copyright (c) 1997-2004 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Portions Copyright (c) 2009 Apple Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "krb5_locl.h" KRB5_LIB_VARIABLE const char *krb5_config_file = #ifdef KRB5_DEFAULT_CONFIG_FILE KRB5_DEFAULT_CONFIG_FILE #else #ifdef __APPLE__ "~/Library/Preferences/com.apple.Kerberos.plist" PATH_SEP "/Library/Preferences/com.apple.Kerberos.plist" PATH_SEP "~/Library/Preferences/edu.mit.Kerberos" PATH_SEP "/Library/Preferences/edu.mit.Kerberos" PATH_SEP #endif /* __APPLE__ */ "~/.krb5/config" PATH_SEP SYSCONFDIR "/krb5.conf" PATH_SEP #ifdef _WIN32 "%{COMMON_APPDATA}/Kerberos/krb5.conf" PATH_SEP "%{WINDOWS}/krb5.ini" #else /* _WIN32 */ "/etc/krb5.conf" #endif /* _WIN32 */ #endif /* KRB5_DEFAULT_CONFIG_FILE */ ; KRB5_LIB_VARIABLE const char *krb5_defkeyname = KEYTAB_DEFAULT; KRB5_LIB_VARIABLE const char *krb5_cc_type_api = "API"; KRB5_LIB_VARIABLE const char *krb5_cc_type_file = "FILE"; KRB5_LIB_VARIABLE const char *krb5_cc_type_memory = "MEMORY"; KRB5_LIB_VARIABLE const char *krb5_cc_type_kcm = "KCM"; KRB5_LIB_VARIABLE const char *krb5_cc_type_scc = "SCC"; KRB5_LIB_VARIABLE const char *krb5_cc_type_dcc = "DIR"; heimdal-7.5.0/lib/krb5/crypto-des.c0000644000175000017500000002156513026237312015130 0ustar niknik/* * Copyright (c) 1997 - 2008 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "krb5_locl.h" #ifdef HEIM_WEAK_CRYPTO static void krb5_DES_random_key(krb5_context context, krb5_keyblock *key) { DES_cblock *k = key->keyvalue.data; do { krb5_generate_random_block(k, sizeof(DES_cblock)); DES_set_odd_parity(k); } while(DES_is_weak_key(k)); } static void krb5_DES_schedule_old(krb5_context context, struct _krb5_key_type *kt, struct _krb5_key_data *key) { DES_set_key_unchecked(key->key->keyvalue.data, key->schedule->data); } static void krb5_DES_random_to_key(krb5_context context, krb5_keyblock *key, const void *data, size_t size) { DES_cblock *k = key->keyvalue.data; memcpy(k, data, key->keyvalue.length); DES_set_odd_parity(k); if(DES_is_weak_key(k)) _krb5_xor8(*k, (const unsigned char*)"\0\0\0\0\0\0\0\xf0"); } static struct _krb5_key_type keytype_des_old = { ETYPE_DES_CBC_CRC, "des-old", 56, 8, sizeof(DES_key_schedule), krb5_DES_random_key, krb5_DES_schedule_old, _krb5_des_salt, krb5_DES_random_to_key, NULL, NULL }; static struct _krb5_key_type keytype_des = { ETYPE_DES_CBC_CRC, "des", 56, 8, sizeof(struct _krb5_evp_schedule), krb5_DES_random_key, _krb5_evp_schedule, _krb5_des_salt, krb5_DES_random_to_key, _krb5_evp_cleanup, EVP_des_cbc }; static krb5_error_code CRC32_checksum(krb5_context context, struct _krb5_key_data *key, const void *data, size_t len, unsigned usage, Checksum *C) { uint32_t crc; unsigned char *r = C->checksum.data; _krb5_crc_init_table (); crc = _krb5_crc_update (data, len, 0); r[0] = crc & 0xff; r[1] = (crc >> 8) & 0xff; r[2] = (crc >> 16) & 0xff; r[3] = (crc >> 24) & 0xff; return 0; } static krb5_error_code RSA_MD4_checksum(krb5_context context, struct _krb5_key_data *key, const void *data, size_t len, unsigned usage, Checksum *C) { if (EVP_Digest(data, len, C->checksum.data, NULL, EVP_md4(), NULL) != 1) krb5_abortx(context, "md4 checksum failed"); return 0; } static krb5_error_code RSA_MD4_DES_checksum(krb5_context context, struct _krb5_key_data *key, const void *data, size_t len, unsigned usage, Checksum *cksum) { return _krb5_des_checksum(context, EVP_md4(), key, data, len, cksum); } static krb5_error_code RSA_MD4_DES_verify(krb5_context context, struct _krb5_key_data *key, const void *data, size_t len, unsigned usage, Checksum *C) { return _krb5_des_verify(context, EVP_md4(), key, data, len, C); } static krb5_error_code RSA_MD5_DES_checksum(krb5_context context, struct _krb5_key_data *key, const void *data, size_t len, unsigned usage, Checksum *C) { return _krb5_des_checksum(context, EVP_md5(), key, data, len, C); } static krb5_error_code RSA_MD5_DES_verify(krb5_context context, struct _krb5_key_data *key, const void *data, size_t len, unsigned usage, Checksum *C) { return _krb5_des_verify(context, EVP_md5(), key, data, len, C); } struct _krb5_checksum_type _krb5_checksum_crc32 = { CKSUMTYPE_CRC32, "crc32", 1, 4, 0, CRC32_checksum, NULL }; struct _krb5_checksum_type _krb5_checksum_rsa_md4 = { CKSUMTYPE_RSA_MD4, "rsa-md4", 64, 16, F_CPROOF, RSA_MD4_checksum, NULL }; struct _krb5_checksum_type _krb5_checksum_rsa_md4_des = { CKSUMTYPE_RSA_MD4_DES, "rsa-md4-des", 64, 24, F_KEYED | F_CPROOF | F_VARIANT, RSA_MD4_DES_checksum, RSA_MD4_DES_verify }; struct _krb5_checksum_type _krb5_checksum_rsa_md5_des = { CKSUMTYPE_RSA_MD5_DES, "rsa-md5-des", 64, 24, F_KEYED | F_CPROOF | F_VARIANT, RSA_MD5_DES_checksum, RSA_MD5_DES_verify }; static krb5_error_code evp_des_encrypt_null_ivec(krb5_context context, struct _krb5_key_data *key, void *data, size_t len, krb5_boolean encryptp, int usage, void *ignore_ivec) { struct _krb5_evp_schedule *ctx = key->schedule->data; EVP_CIPHER_CTX *c; DES_cblock ivec; memset(&ivec, 0, sizeof(ivec)); c = encryptp ? &ctx->ectx : &ctx->dctx; EVP_CipherInit_ex(c, NULL, NULL, NULL, (void *)&ivec, -1); EVP_Cipher(c, data, data, len); return 0; } static krb5_error_code evp_des_encrypt_key_ivec(krb5_context context, struct _krb5_key_data *key, void *data, size_t len, krb5_boolean encryptp, int usage, void *ignore_ivec) { struct _krb5_evp_schedule *ctx = key->schedule->data; EVP_CIPHER_CTX *c; DES_cblock ivec; memcpy(&ivec, key->key->keyvalue.data, sizeof(ivec)); c = encryptp ? &ctx->ectx : &ctx->dctx; EVP_CipherInit_ex(c, NULL, NULL, NULL, (void *)&ivec, -1); EVP_Cipher(c, data, data, len); return 0; } static krb5_error_code DES_CFB64_encrypt_null_ivec(krb5_context context, struct _krb5_key_data *key, void *data, size_t len, krb5_boolean encryptp, int usage, void *ignore_ivec) { DES_cblock ivec; int num = 0; DES_key_schedule *s = key->schedule->data; memset(&ivec, 0, sizeof(ivec)); DES_cfb64_encrypt(data, data, len, s, &ivec, &num, encryptp); return 0; } static krb5_error_code DES_PCBC_encrypt_key_ivec(krb5_context context, struct _krb5_key_data *key, void *data, size_t len, krb5_boolean encryptp, int usage, void *ignore_ivec) { DES_cblock ivec; DES_key_schedule *s = key->schedule->data; memcpy(&ivec, key->key->keyvalue.data, sizeof(ivec)); DES_pcbc_encrypt(data, data, len, s, &ivec, encryptp); return 0; } struct _krb5_encryption_type _krb5_enctype_des_cbc_crc = { ETYPE_DES_CBC_CRC, "des-cbc-crc", NULL, 8, 8, 8, &keytype_des, &_krb5_checksum_crc32, NULL, F_DISABLED|F_WEAK, evp_des_encrypt_key_ivec, 0, NULL }; struct _krb5_encryption_type _krb5_enctype_des_cbc_md4 = { ETYPE_DES_CBC_MD4, "des-cbc-md4", NULL, 8, 8, 8, &keytype_des, &_krb5_checksum_rsa_md4, &_krb5_checksum_rsa_md4_des, F_DISABLED|F_WEAK, evp_des_encrypt_null_ivec, 0, NULL }; struct _krb5_encryption_type _krb5_enctype_des_cbc_md5 = { ETYPE_DES_CBC_MD5, "des-cbc-md5", NULL, 8, 8, 8, &keytype_des, &_krb5_checksum_rsa_md5, &_krb5_checksum_rsa_md5_des, F_DISABLED|F_WEAK, evp_des_encrypt_null_ivec, 0, NULL }; struct _krb5_encryption_type _krb5_enctype_des_cbc_none = { ETYPE_DES_CBC_NONE, "des-cbc-none", NULL, 8, 8, 0, &keytype_des, &_krb5_checksum_none, NULL, F_PSEUDO|F_DISABLED|F_WEAK, evp_des_encrypt_null_ivec, 0, NULL }; struct _krb5_encryption_type _krb5_enctype_des_cfb64_none = { ETYPE_DES_CFB64_NONE, "des-cfb64-none", NULL, 1, 1, 0, &keytype_des_old, &_krb5_checksum_none, NULL, F_PSEUDO|F_DISABLED|F_WEAK, DES_CFB64_encrypt_null_ivec, 0, NULL }; struct _krb5_encryption_type _krb5_enctype_des_pcbc_none = { ETYPE_DES_PCBC_NONE, "des-pcbc-none", NULL, 8, 8, 0, &keytype_des_old, &_krb5_checksum_none, NULL, F_PSEUDO|F_DISABLED|F_WEAK, DES_PCBC_encrypt_key_ivec, 0, NULL }; #endif /* HEIM_WEAK_CRYPTO */ heimdal-7.5.0/lib/krb5/mcache.c0000644000175000017500000003351013026237312014250 0ustar niknik/* * Copyright (c) 1997-2004 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Portions Copyright (c) 2009 Apple Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "krb5_locl.h" typedef struct krb5_mcache { char *name; unsigned int refcnt; int dead; krb5_principal primary_principal; struct link { krb5_creds cred; struct link *next; } *creds; struct krb5_mcache *next; time_t mtime; krb5_deltat kdc_offset; HEIMDAL_MUTEX mutex; } krb5_mcache; static HEIMDAL_MUTEX mcc_mutex = HEIMDAL_MUTEX_INITIALIZER; static struct krb5_mcache *mcc_head; #define MCACHE(X) ((krb5_mcache *)(X)->data.data) #define MISDEAD(X) ((X)->dead) static const char* KRB5_CALLCONV mcc_get_name(krb5_context context, krb5_ccache id) { return MCACHE(id)->name; } static krb5_mcache * KRB5_CALLCONV mcc_alloc(const char *name) { krb5_mcache *m, *m_c; int ret = 0; ALLOC(m, 1); if(m == NULL) return NULL; if(name == NULL) ret = asprintf(&m->name, "%p", m); else m->name = strdup(name); if(ret < 0 || m->name == NULL) { free(m); return NULL; } /* check for dups first */ HEIMDAL_MUTEX_lock(&mcc_mutex); for (m_c = mcc_head; m_c != NULL; m_c = m_c->next) if (strcmp(m->name, m_c->name) == 0) break; if (m_c) { free(m->name); free(m); HEIMDAL_MUTEX_unlock(&mcc_mutex); return NULL; } m->dead = 0; m->refcnt = 1; m->primary_principal = NULL; m->creds = NULL; m->mtime = time(NULL); m->kdc_offset = 0; m->next = mcc_head; HEIMDAL_MUTEX_init(&(m->mutex)); mcc_head = m; HEIMDAL_MUTEX_unlock(&mcc_mutex); return m; } static krb5_error_code KRB5_CALLCONV mcc_resolve(krb5_context context, krb5_ccache *id, const char *res) { krb5_mcache *m; HEIMDAL_MUTEX_lock(&mcc_mutex); for (m = mcc_head; m != NULL; m = m->next) if (strcmp(m->name, res) == 0) break; HEIMDAL_MUTEX_unlock(&mcc_mutex); if (m != NULL) { HEIMDAL_MUTEX_lock(&(m->mutex)); m->refcnt++; HEIMDAL_MUTEX_unlock(&(m->mutex)); (*id)->data.data = m; (*id)->data.length = sizeof(*m); return 0; } m = mcc_alloc(res); if (m == NULL) { krb5_set_error_message(context, KRB5_CC_NOMEM, N_("malloc: out of memory", "")); return KRB5_CC_NOMEM; } (*id)->data.data = m; (*id)->data.length = sizeof(*m); return 0; } static krb5_error_code KRB5_CALLCONV mcc_gen_new(krb5_context context, krb5_ccache *id) { krb5_mcache *m; m = mcc_alloc(NULL); if (m == NULL) { krb5_set_error_message(context, KRB5_CC_NOMEM, N_("malloc: out of memory", "")); return KRB5_CC_NOMEM; } (*id)->data.data = m; (*id)->data.length = sizeof(*m); return 0; } static void KRB5_CALLCONV mcc_destroy_internal(krb5_context context, krb5_mcache *m) { struct link *l; if (m->primary_principal != NULL) { krb5_free_principal (context, m->primary_principal); m->primary_principal = NULL; } m->dead = 1; l = m->creds; while (l != NULL) { struct link *old; krb5_free_cred_contents (context, &l->cred); old = l; l = l->next; free (old); } m->creds = NULL; return; } static krb5_error_code KRB5_CALLCONV mcc_initialize(krb5_context context, krb5_ccache id, krb5_principal primary_principal) { krb5_mcache *m = MCACHE(id); krb5_error_code ret = 0; HEIMDAL_MUTEX_lock(&(m->mutex)); heim_assert(m->refcnt != 0, "resurection released mcache"); /* * It's important to destroy any existing * creds here, that matches the baheviour * of all other backends and also the * MEMORY: backend in MIT. */ mcc_destroy_internal(context, m); m->dead = 0; m->kdc_offset = 0; m->mtime = time(NULL); ret = krb5_copy_principal (context, primary_principal, &m->primary_principal); HEIMDAL_MUTEX_unlock(&(m->mutex)); return ret; } static int mcc_close_internal(krb5_mcache *m) { HEIMDAL_MUTEX_lock(&(m->mutex)); heim_assert(m->refcnt != 0, "closed dead cache mcache"); if (--m->refcnt != 0) { HEIMDAL_MUTEX_unlock(&(m->mutex)); return 0; } if (MISDEAD(m)) { free (m->name); HEIMDAL_MUTEX_unlock(&(m->mutex)); return 1; } HEIMDAL_MUTEX_unlock(&(m->mutex)); return 0; } static krb5_error_code KRB5_CALLCONV mcc_close(krb5_context context, krb5_ccache id) { krb5_mcache *m = MCACHE(id); if (mcc_close_internal(MCACHE(id))) { HEIMDAL_MUTEX_destroy(&(m->mutex)); krb5_data_free(&id->data); } return 0; } static krb5_error_code KRB5_CALLCONV mcc_destroy(krb5_context context, krb5_ccache id) { krb5_mcache **n, *m = MCACHE(id); HEIMDAL_MUTEX_lock(&(m->mutex)); if (m->refcnt == 0) { HEIMDAL_MUTEX_unlock(&(m->mutex)); krb5_abortx(context, "mcc_destroy: refcnt already 0"); } if (!MISDEAD(m)) { /* if this is an active mcache, remove it from the linked list, and free all data */ HEIMDAL_MUTEX_lock(&mcc_mutex); for(n = &mcc_head; n && *n; n = &(*n)->next) { if(m == *n) { *n = m->next; break; } } HEIMDAL_MUTEX_unlock(&mcc_mutex); mcc_destroy_internal(context, m); } HEIMDAL_MUTEX_unlock(&(m->mutex)); return 0; } static krb5_error_code KRB5_CALLCONV mcc_store_cred(krb5_context context, krb5_ccache id, krb5_creds *creds) { krb5_mcache *m = MCACHE(id); krb5_error_code ret; struct link *l; HEIMDAL_MUTEX_lock(&(m->mutex)); if (MISDEAD(m)) { HEIMDAL_MUTEX_unlock(&(m->mutex)); return ENOENT; } l = malloc (sizeof(*l)); if (l == NULL) { krb5_set_error_message(context, KRB5_CC_NOMEM, N_("malloc: out of memory", "")); HEIMDAL_MUTEX_unlock(&(m->mutex)); return KRB5_CC_NOMEM; } l->next = m->creds; m->creds = l; memset (&l->cred, 0, sizeof(l->cred)); ret = krb5_copy_creds_contents (context, creds, &l->cred); if (ret) { m->creds = l->next; free (l); HEIMDAL_MUTEX_unlock(&(m->mutex)); return ret; } m->mtime = time(NULL); HEIMDAL_MUTEX_unlock(&(m->mutex)); return 0; } static krb5_error_code KRB5_CALLCONV mcc_get_principal(krb5_context context, krb5_ccache id, krb5_principal *principal) { krb5_mcache *m = MCACHE(id); krb5_error_code ret = 0; HEIMDAL_MUTEX_lock(&(m->mutex)); if (MISDEAD(m) || m->primary_principal == NULL) { HEIMDAL_MUTEX_unlock(&(m->mutex)); return ENOENT; } ret = krb5_copy_principal (context, m->primary_principal, principal); HEIMDAL_MUTEX_unlock(&(m->mutex)); return ret; } static krb5_error_code KRB5_CALLCONV mcc_get_first (krb5_context context, krb5_ccache id, krb5_cc_cursor *cursor) { krb5_mcache *m = MCACHE(id); HEIMDAL_MUTEX_lock(&(m->mutex)); if (MISDEAD(m)) { HEIMDAL_MUTEX_unlock(&(m->mutex)); return ENOENT; } *cursor = m->creds; HEIMDAL_MUTEX_unlock(&(m->mutex)); return 0; } static krb5_error_code KRB5_CALLCONV mcc_get_next (krb5_context context, krb5_ccache id, krb5_cc_cursor *cursor, krb5_creds *creds) { krb5_mcache *m = MCACHE(id); struct link *l; HEIMDAL_MUTEX_lock(&(m->mutex)); if (MISDEAD(m)) { HEIMDAL_MUTEX_unlock(&(m->mutex)); return ENOENT; } HEIMDAL_MUTEX_unlock(&(m->mutex)); l = *cursor; if (l != NULL) { *cursor = l->next; return krb5_copy_creds_contents (context, &l->cred, creds); } else return KRB5_CC_END; } static krb5_error_code KRB5_CALLCONV mcc_end_get (krb5_context context, krb5_ccache id, krb5_cc_cursor *cursor) { return 0; } static krb5_error_code KRB5_CALLCONV mcc_remove_cred(krb5_context context, krb5_ccache id, krb5_flags which, krb5_creds *mcreds) { krb5_mcache *m = MCACHE(id); struct link **q, *p; HEIMDAL_MUTEX_lock(&(m->mutex)); for(q = &m->creds, p = *q; p; p = *q) { if(krb5_compare_creds(context, which, mcreds, &p->cred)) { *q = p->next; krb5_free_cred_contents(context, &p->cred); free(p); m->mtime = time(NULL); } else q = &p->next; } HEIMDAL_MUTEX_unlock(&(m->mutex)); return 0; } static krb5_error_code KRB5_CALLCONV mcc_set_flags(krb5_context context, krb5_ccache id, krb5_flags flags) { return 0; /* XXX */ } struct mcache_iter { krb5_mcache *cache; }; static krb5_error_code KRB5_CALLCONV mcc_get_cache_first(krb5_context context, krb5_cc_cursor *cursor) { struct mcache_iter *iter; iter = calloc(1, sizeof(*iter)); if (iter == NULL) return krb5_enomem(context); HEIMDAL_MUTEX_lock(&mcc_mutex); iter->cache = mcc_head; if (iter->cache) { HEIMDAL_MUTEX_lock(&(iter->cache->mutex)); iter->cache->refcnt++; HEIMDAL_MUTEX_unlock(&(iter->cache->mutex)); } HEIMDAL_MUTEX_unlock(&mcc_mutex); *cursor = iter; return 0; } static krb5_error_code KRB5_CALLCONV mcc_get_cache_next(krb5_context context, krb5_cc_cursor cursor, krb5_ccache *id) { struct mcache_iter *iter = cursor; krb5_error_code ret; krb5_mcache *m; if (iter->cache == NULL) return KRB5_CC_END; HEIMDAL_MUTEX_lock(&mcc_mutex); m = iter->cache; if (m->next) { HEIMDAL_MUTEX_lock(&(m->next->mutex)); m->next->refcnt++; HEIMDAL_MUTEX_unlock(&(m->next->mutex)); } iter->cache = m->next; HEIMDAL_MUTEX_unlock(&mcc_mutex); ret = _krb5_cc_allocate(context, &krb5_mcc_ops, id); if (ret) return ret; (*id)->data.data = m; (*id)->data.length = sizeof(*m); return 0; } static krb5_error_code KRB5_CALLCONV mcc_end_cache_get(krb5_context context, krb5_cc_cursor cursor) { struct mcache_iter *iter = cursor; if (iter->cache) mcc_close_internal(iter->cache); iter->cache = NULL; free(iter); return 0; } static krb5_error_code KRB5_CALLCONV mcc_move(krb5_context context, krb5_ccache from, krb5_ccache to) { krb5_mcache *mfrom = MCACHE(from), *mto = MCACHE(to); struct link *creds; krb5_principal principal; krb5_mcache **n; HEIMDAL_MUTEX_lock(&mcc_mutex); /* drop the from cache from the linked list to avoid lookups */ for(n = &mcc_head; n && *n; n = &(*n)->next) { if(mfrom == *n) { *n = mfrom->next; break; } } HEIMDAL_MUTEX_lock(&(mfrom->mutex)); HEIMDAL_MUTEX_lock(&(mto->mutex)); /* swap creds */ creds = mto->creds; mto->creds = mfrom->creds; mfrom->creds = creds; /* swap principal */ principal = mto->primary_principal; mto->primary_principal = mfrom->primary_principal; mfrom->primary_principal = principal; mto->mtime = mfrom->mtime = time(NULL); HEIMDAL_MUTEX_unlock(&(mfrom->mutex)); HEIMDAL_MUTEX_unlock(&(mto->mutex)); HEIMDAL_MUTEX_unlock(&mcc_mutex); mcc_destroy(context, from); return 0; } static krb5_error_code KRB5_CALLCONV mcc_default_name(krb5_context context, char **str) { *str = strdup("MEMORY:"); if (*str == NULL) return krb5_enomem(context); return 0; } static krb5_error_code KRB5_CALLCONV mcc_lastchange(krb5_context context, krb5_ccache id, krb5_timestamp *mtime) { krb5_mcache *m = MCACHE(id); HEIMDAL_MUTEX_lock(&(m->mutex)); *mtime = m->mtime; HEIMDAL_MUTEX_unlock(&(m->mutex)); return 0; } static krb5_error_code KRB5_CALLCONV mcc_set_kdc_offset(krb5_context context, krb5_ccache id, krb5_deltat kdc_offset) { krb5_mcache *m = MCACHE(id); HEIMDAL_MUTEX_lock(&(m->mutex)); m->kdc_offset = kdc_offset; HEIMDAL_MUTEX_unlock(&(m->mutex)); return 0; } static krb5_error_code KRB5_CALLCONV mcc_get_kdc_offset(krb5_context context, krb5_ccache id, krb5_deltat *kdc_offset) { krb5_mcache *m = MCACHE(id); HEIMDAL_MUTEX_lock(&(m->mutex)); *kdc_offset = m->kdc_offset; HEIMDAL_MUTEX_unlock(&(m->mutex)); return 0; } /** * Variable containing the MEMORY based credential cache implemention. * * @ingroup krb5_ccache */ KRB5_LIB_VARIABLE const krb5_cc_ops krb5_mcc_ops = { KRB5_CC_OPS_VERSION, "MEMORY", mcc_get_name, mcc_resolve, mcc_gen_new, mcc_initialize, mcc_destroy, mcc_close, mcc_store_cred, NULL, /* mcc_retrieve */ mcc_get_principal, mcc_get_first, mcc_get_next, mcc_end_get, mcc_remove_cred, mcc_set_flags, NULL, mcc_get_cache_first, mcc_get_cache_next, mcc_end_cache_get, mcc_move, mcc_default_name, NULL, mcc_lastchange, mcc_set_kdc_offset, mcc_get_kdc_offset }; heimdal-7.5.0/lib/krb5/init_creds.c0000644000175000017500000003034013026237312015151 0ustar niknik/* * Copyright (c) 1997 - 2004 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Portions Copyright (c) 2009 Apple Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "krb5_locl.h" #undef __attribute__ #define __attribute__(x) /** * @page krb5_init_creds_intro The initial credential handing functions * @section section_krb5_init_creds Initial credential * * Functions to get initial credentials: @ref krb5_credential . */ /** * Allocate a new krb5_get_init_creds_opt structure, free with * krb5_get_init_creds_opt_free(). * * @ingroup krb5_credential */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_get_init_creds_opt_alloc(krb5_context context, krb5_get_init_creds_opt **opt) { krb5_get_init_creds_opt *o; *opt = NULL; o = calloc(1, sizeof(*o)); if (o == NULL) return krb5_enomem(context); o->opt_private = calloc(1, sizeof(*o->opt_private)); if (o->opt_private == NULL) { free(o); return krb5_enomem(context); } o->opt_private->refcount = 1; *opt = o; return 0; } /** * Free krb5_get_init_creds_opt structure. * * @ingroup krb5_credential */ KRB5_LIB_FUNCTION void KRB5_LIB_CALL krb5_get_init_creds_opt_free(krb5_context context, krb5_get_init_creds_opt *opt) { if (opt == NULL || opt->opt_private == NULL) return; if (opt->opt_private->refcount < 1) /* abort ? */ return; if (--opt->opt_private->refcount == 0) { _krb5_get_init_creds_opt_free_pkinit(opt); free(opt->opt_private); } memset(opt, 0, sizeof(*opt)); free(opt); } static int get_config_time (krb5_context context, const char *realm, const char *name, int def) { int ret; ret = krb5_config_get_time (context, NULL, "realms", realm, name, NULL); if (ret >= 0) return ret; ret = krb5_config_get_time (context, NULL, "libdefaults", name, NULL); if (ret >= 0) return ret; return def; } static krb5_boolean get_config_bool (krb5_context context, krb5_boolean def_value, const char *realm, const char *name) { krb5_boolean b; b = krb5_config_get_bool_default(context, NULL, def_value, "realms", realm, name, NULL); if (b != def_value) return b; b = krb5_config_get_bool_default (context, NULL, def_value, "libdefaults", name, NULL); if (b != def_value) return b; return def_value; } /* * set all the values in `opt' to the appropriate values for * application `appname' (default to getprogname() if NULL), and realm * `realm'. First looks in [appdefaults] but falls back to * [realms] or [libdefaults] for some of the values. */ KRB5_LIB_FUNCTION void KRB5_LIB_CALL krb5_get_init_creds_opt_set_default_flags(krb5_context context, const char *appname, krb5_const_realm realm, krb5_get_init_creds_opt *opt) { krb5_boolean b; time_t t; b = get_config_bool (context, KRB5_FORWARDABLE_DEFAULT, realm, "forwardable"); krb5_appdefault_boolean(context, appname, realm, "forwardable", b, &b); krb5_get_init_creds_opt_set_forwardable(opt, b); b = get_config_bool (context, FALSE, realm, "proxiable"); krb5_appdefault_boolean(context, appname, realm, "proxiable", b, &b); krb5_get_init_creds_opt_set_proxiable (opt, b); krb5_appdefault_time(context, appname, realm, "ticket_lifetime", 0, &t); if (t == 0) t = get_config_time (context, realm, "ticket_lifetime", 0); if(t != 0) krb5_get_init_creds_opt_set_tkt_life(opt, t); krb5_appdefault_time(context, appname, realm, "renew_lifetime", 0, &t); if (t == 0) t = get_config_time (context, realm, "renew_lifetime", 0); if(t != 0) krb5_get_init_creds_opt_set_renew_life(opt, t); krb5_appdefault_boolean(context, appname, realm, "no-addresses", KRB5_ADDRESSLESS_DEFAULT, &b); krb5_get_init_creds_opt_set_addressless (context, opt, b); #if 0 krb5_appdefault_boolean(context, appname, realm, "anonymous", FALSE, &b); krb5_get_init_creds_opt_set_anonymous (opt, b); krb5_get_init_creds_opt_set_etype_list(opt, enctype, etype_str.num_strings); krb5_get_init_creds_opt_set_salt(krb5_get_init_creds_opt *opt, krb5_data *salt); krb5_get_init_creds_opt_set_preauth_list(krb5_get_init_creds_opt *opt, krb5_preauthtype *preauth_list, int preauth_list_length); #endif } KRB5_LIB_FUNCTION void KRB5_LIB_CALL krb5_get_init_creds_opt_set_change_password_prompt(krb5_get_init_creds_opt *opt, int change_password_prompt) { opt->flags |= KRB5_GET_INIT_CREDS_OPT_CHANGE_PASSWORD_PROMPT; opt->change_password_prompt = change_password_prompt; } KRB5_LIB_FUNCTION void KRB5_LIB_CALL krb5_get_init_creds_opt_set_tkt_life(krb5_get_init_creds_opt *opt, krb5_deltat tkt_life) { opt->flags |= KRB5_GET_INIT_CREDS_OPT_TKT_LIFE; opt->tkt_life = tkt_life; } KRB5_LIB_FUNCTION void KRB5_LIB_CALL krb5_get_init_creds_opt_set_renew_life(krb5_get_init_creds_opt *opt, krb5_deltat renew_life) { opt->flags |= KRB5_GET_INIT_CREDS_OPT_RENEW_LIFE; opt->renew_life = renew_life; } KRB5_LIB_FUNCTION void KRB5_LIB_CALL krb5_get_init_creds_opt_set_forwardable(krb5_get_init_creds_opt *opt, int forwardable) { opt->flags |= KRB5_GET_INIT_CREDS_OPT_FORWARDABLE; opt->forwardable = forwardable; } KRB5_LIB_FUNCTION void KRB5_LIB_CALL krb5_get_init_creds_opt_set_proxiable(krb5_get_init_creds_opt *opt, int proxiable) { opt->flags |= KRB5_GET_INIT_CREDS_OPT_PROXIABLE; opt->proxiable = proxiable; } KRB5_LIB_FUNCTION void KRB5_LIB_CALL krb5_get_init_creds_opt_set_etype_list(krb5_get_init_creds_opt *opt, krb5_enctype *etype_list, int etype_list_length) { opt->flags |= KRB5_GET_INIT_CREDS_OPT_ETYPE_LIST; opt->etype_list = etype_list; opt->etype_list_length = etype_list_length; } KRB5_LIB_FUNCTION void KRB5_LIB_CALL krb5_get_init_creds_opt_set_address_list(krb5_get_init_creds_opt *opt, krb5_addresses *addresses) { opt->flags |= KRB5_GET_INIT_CREDS_OPT_ADDRESS_LIST; opt->address_list = addresses; } KRB5_LIB_FUNCTION void KRB5_LIB_CALL krb5_get_init_creds_opt_set_preauth_list(krb5_get_init_creds_opt *opt, krb5_preauthtype *preauth_list, int preauth_list_length) { opt->flags |= KRB5_GET_INIT_CREDS_OPT_PREAUTH_LIST; opt->preauth_list_length = preauth_list_length; opt->preauth_list = preauth_list; } KRB5_LIB_FUNCTION void KRB5_LIB_CALL krb5_get_init_creds_opt_set_salt(krb5_get_init_creds_opt *opt, krb5_data *salt) { opt->flags |= KRB5_GET_INIT_CREDS_OPT_SALT; opt->salt = salt; } KRB5_LIB_FUNCTION void KRB5_LIB_CALL krb5_get_init_creds_opt_set_anonymous(krb5_get_init_creds_opt *opt, int anonymous) { opt->flags |= KRB5_GET_INIT_CREDS_OPT_ANONYMOUS; opt->anonymous = anonymous; } static krb5_error_code require_ext_opt(krb5_context context, krb5_get_init_creds_opt *opt, const char *type) { if (opt->opt_private == NULL) { krb5_set_error_message(context, EINVAL, N_("%s on non extendable opt", ""), type); return EINVAL; } return 0; } KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_get_init_creds_opt_set_pa_password(krb5_context context, krb5_get_init_creds_opt *opt, const char *password, krb5_s2k_proc key_proc) { krb5_error_code ret; ret = require_ext_opt(context, opt, "init_creds_opt_set_pa_password"); if (ret) return ret; opt->opt_private->password = password; opt->opt_private->key_proc = key_proc; return 0; } KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_get_init_creds_opt_set_pac_request(krb5_context context, krb5_get_init_creds_opt *opt, krb5_boolean req_pac) { krb5_error_code ret; ret = require_ext_opt(context, opt, "init_creds_opt_set_pac_req"); if (ret) return ret; opt->opt_private->req_pac = req_pac ? KRB5_INIT_CREDS_TRISTATE_TRUE : KRB5_INIT_CREDS_TRISTATE_FALSE; return 0; } KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_get_init_creds_opt_set_addressless(krb5_context context, krb5_get_init_creds_opt *opt, krb5_boolean addressless) { krb5_error_code ret; ret = require_ext_opt(context, opt, "init_creds_opt_set_pac_req"); if (ret) return ret; if (addressless) opt->opt_private->addressless = KRB5_INIT_CREDS_TRISTATE_TRUE; else opt->opt_private->addressless = KRB5_INIT_CREDS_TRISTATE_FALSE; return 0; } KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_get_init_creds_opt_set_canonicalize(krb5_context context, krb5_get_init_creds_opt *opt, krb5_boolean req) { krb5_error_code ret; ret = require_ext_opt(context, opt, "init_creds_opt_set_canonicalize"); if (ret) return ret; if (req) opt->opt_private->flags |= KRB5_INIT_CREDS_CANONICALIZE; else opt->opt_private->flags &= ~KRB5_INIT_CREDS_CANONICALIZE; return 0; } KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_get_init_creds_opt_set_win2k(krb5_context context, krb5_get_init_creds_opt *opt, krb5_boolean req) { krb5_error_code ret; ret = require_ext_opt(context, opt, "init_creds_opt_set_win2k"); if (ret) return ret; if (req) { opt->opt_private->flags |= KRB5_INIT_CREDS_NO_C_CANON_CHECK; opt->opt_private->flags |= KRB5_INIT_CREDS_NO_C_NO_EKU_CHECK; } else { opt->opt_private->flags &= ~KRB5_INIT_CREDS_NO_C_CANON_CHECK; opt->opt_private->flags &= ~KRB5_INIT_CREDS_NO_C_NO_EKU_CHECK; } return 0; } KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_get_init_creds_opt_set_process_last_req(krb5_context context, krb5_get_init_creds_opt *opt, krb5_gic_process_last_req func, void *ctx) { krb5_error_code ret; ret = require_ext_opt(context, opt, "init_creds_opt_set_process_last_req"); if (ret) return ret; opt->opt_private->lr.func = func; opt->opt_private->lr.ctx = ctx; return 0; } #ifndef HEIMDAL_SMALLER /** * Deprecated: use krb5_get_init_creds_opt_alloc(). * * The reason krb5_get_init_creds_opt_init() is deprecated is that * krb5_get_init_creds_opt is a static structure and for ABI reason it * can't grow, ie can't add new functionality. * * @ingroup krb5_deprecated */ KRB5_LIB_FUNCTION void KRB5_LIB_CALL krb5_get_init_creds_opt_init(krb5_get_init_creds_opt *opt) KRB5_DEPRECATED_FUNCTION("Use X instead") { memset (opt, 0, sizeof(*opt)); } /** * Deprecated: use the new krb5_init_creds_init() and * krb5_init_creds_get_error(). * * @ingroup krb5_deprecated */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_get_init_creds_opt_get_error(krb5_context context, krb5_get_init_creds_opt *opt, KRB_ERROR **error) KRB5_DEPRECATED_FUNCTION("Use X instead") { *error = calloc(1, sizeof(**error)); if (*error == NULL) return krb5_enomem(context); return 0; } #endif /* HEIMDAL_SMALLER */ heimdal-7.5.0/lib/krb5/krb5_digest.cat30000644000175000017500000002606213212450756015654 0ustar niknik KRB5_DIGEST(3) BSD Library Functions Manual KRB5_DIGEST(3) NNAAMMEE kkrrbb55__ddiiggeesstt, kkrrbb55__ddiiggeesstt__aalllloocc, kkrrbb55__ddiiggeesstt__ffrreeee, kkrrbb55__ddiiggeesstt__sseett__sseerrvveerr__ccbb, kkrrbb55__ddiiggeesstt__sseett__ttyyppee, kkrrbb55__ddiiggeesstt__sseett__hhoossttnnaammee, kkrrbb55__ddiiggeesstt__ggeett__sseerrvveerr__nnoonnccee, kkrrbb55__ddiiggeesstt__sseett__sseerrvveerr__nnoonnccee, kkrrbb55__ddiiggeesstt__ggeett__ooppaaqquuee, kkrrbb55__ddiiggeesstt__sseett__ooppaaqquuee, kkrrbb55__ddiiggeesstt__ggeett__iiddeennttiiffiieerr, kkrrbb55__ddiiggeesstt__sseett__iiddeennttiiffiieerr, kkrrbb55__ddiiggeesstt__iinniitt__rreeqquueesstt, kkrrbb55__ddiiggeesstt__sseett__cclliieenntt__nnoonnccee, kkrrbb55__ddiiggeesstt__sseett__ddiiggeesstt, kkrrbb55__ddiiggeesstt__sseett__uusseerrnnaammee, kkrrbb55__ddiiggeesstt__sseett__aauutthhiidd, kkrrbb55__ddiiggeesstt__sseett__aauutthheennttiiccaattiioonn__uusseerr, kkrrbb55__ddiiggeesstt__sseett__rreeaallmm, kkrrbb55__ddiiggeesstt__sseett__mmeetthhoodd, kkrrbb55__ddiiggeesstt__sseett__uurrii, kkrrbb55__ddiiggeesstt__sseett__nnoonncceeCCoouunntt, kkrrbb55__ddiiggeesstt__sseett__qqoopp, kkrrbb55__ddiiggeesstt__rreeqquueesstt, kkrrbb55__ddiiggeesstt__ggeett__rreessppoonnsseeDDaattaa, kkrrbb55__ddiiggeesstt__ggeett__rrsspp, kkrrbb55__ddiiggeesstt__ggeett__ttiicckkeettss, kkrrbb55__ddiiggeesstt__ggeett__cclliieenntt__bbiinnddiinngg, kkrrbb55__ddiiggeesstt__ggeett__aa11__hhaasshh -- remote digest (HTTP-DIGEST, SASL, CHAP) support LLIIBBRRAARRYY Kerberos 5 Library (libkrb5, -lkrb5) SSYYNNOOPPSSIISS ##iinncclluuddee <> typedef struct krb5_digest *krb5_digest; _k_r_b_5___e_r_r_o_r___c_o_d_e kkrrbb55__ddiiggeesstt__aalllloocc(_k_r_b_5___c_o_n_t_e_x_t _c_o_n_t_e_x_t, _k_r_b_5___d_i_g_e_s_t _*_d_i_g_e_s_t); _v_o_i_d kkrrbb55__ddiiggeesstt__ffrreeee(_k_r_b_5___d_i_g_e_s_t _d_i_g_e_s_t); _k_r_b_5___e_r_r_o_r___c_o_d_e kkrrbb55__ddiiggeesstt__sseett__ttyyppee(_k_r_b_5___c_o_n_t_e_x_t _c_o_n_t_e_x_t, _k_r_b_5___d_i_g_e_s_t _d_i_g_e_s_t, _c_o_n_s_t _c_h_a_r _*_t_y_p_e); _k_r_b_5___e_r_r_o_r___c_o_d_e kkrrbb55__ddiiggeesstt__sseett__sseerrvveerr__ccbb(_k_r_b_5___c_o_n_t_e_x_t _c_o_n_t_e_x_t, _k_r_b_5___d_i_g_e_s_t _d_i_g_e_s_t, _c_o_n_s_t _c_h_a_r _*_t_y_p_e, _c_o_n_s_t _c_h_a_r _*_b_i_n_d_i_n_g); _k_r_b_5___e_r_r_o_r___c_o_d_e kkrrbb55__ddiiggeesstt__sseett__hhoossttnnaammee(_k_r_b_5___c_o_n_t_e_x_t _c_o_n_t_e_x_t, _k_r_b_5___d_i_g_e_s_t _d_i_g_e_s_t, _c_o_n_s_t _c_h_a_r _*_h_o_s_t_n_a_m_e); _c_o_n_s_t _c_h_a_r _* kkrrbb55__ddiiggeesstt__ggeett__sseerrvveerr__nnoonnccee(_k_r_b_5___c_o_n_t_e_x_t _c_o_n_t_e_x_t, _k_r_b_5___d_i_g_e_s_t _d_i_g_e_s_t); _k_r_b_5___e_r_r_o_r___c_o_d_e kkrrbb55__ddiiggeesstt__sseett__sseerrvveerr__nnoonnccee(_k_r_b_5___c_o_n_t_e_x_t _c_o_n_t_e_x_t, _k_r_b_5___d_i_g_e_s_t _d_i_g_e_s_t, _c_o_n_s_t _c_h_a_r _*_n_o_n_c_e); _c_o_n_s_t _c_h_a_r _* kkrrbb55__ddiiggeesstt__ggeett__ooppaaqquuee(_k_r_b_5___c_o_n_t_e_x_t _c_o_n_t_e_x_t, _k_r_b_5___d_i_g_e_s_t _d_i_g_e_s_t); _k_r_b_5___e_r_r_o_r___c_o_d_e kkrrbb55__ddiiggeesstt__sseett__ooppaaqquuee(_k_r_b_5___c_o_n_t_e_x_t _c_o_n_t_e_x_t, _k_r_b_5___d_i_g_e_s_t _d_i_g_e_s_t, _c_o_n_s_t _c_h_a_r _*_o_p_a_q_u_e); _c_o_n_s_t _c_h_a_r _* kkrrbb55__ddiiggeesstt__ggeett__iiddeennttiiffiieerr(_k_r_b_5___c_o_n_t_e_x_t _c_o_n_t_e_x_t, _k_r_b_5___d_i_g_e_s_t _d_i_g_e_s_t); _k_r_b_5___e_r_r_o_r___c_o_d_e kkrrbb55__ddiiggeesstt__sseett__iiddeennttiiffiieerr(_k_r_b_5___c_o_n_t_e_x_t _c_o_n_t_e_x_t, _k_r_b_5___d_i_g_e_s_t _d_i_g_e_s_t, _c_o_n_s_t _c_h_a_r _*_i_d); _k_r_b_5___e_r_r_o_r___c_o_d_e kkrrbb55__ddiiggeesstt__iinniitt__rreeqquueesstt(_k_r_b_5___c_o_n_t_e_x_t _c_o_n_t_e_x_t, _k_r_b_5___d_i_g_e_s_t _d_i_g_e_s_t, _k_r_b_5___r_e_a_l_m _r_e_a_l_m, _k_r_b_5___c_c_a_c_h_e _c_c_a_c_h_e); _k_r_b_5___e_r_r_o_r___c_o_d_e kkrrbb55__ddiiggeesstt__sseett__cclliieenntt__nnoonnccee(_k_r_b_5___c_o_n_t_e_x_t _c_o_n_t_e_x_t, _k_r_b_5___d_i_g_e_s_t _d_i_g_e_s_t, _c_o_n_s_t _c_h_a_r _*_n_o_n_c_e); _k_r_b_5___e_r_r_o_r___c_o_d_e kkrrbb55__ddiiggeesstt__sseett__ddiiggeesstt(_k_r_b_5___c_o_n_t_e_x_t _c_o_n_t_e_x_t, _k_r_b_5___d_i_g_e_s_t _d_i_g_e_s_t, _c_o_n_s_t _c_h_a_r _*_d_g_s_t); _k_r_b_5___e_r_r_o_r___c_o_d_e kkrrbb55__ddiiggeesstt__sseett__uusseerrnnaammee(_k_r_b_5___c_o_n_t_e_x_t _c_o_n_t_e_x_t, _k_r_b_5___d_i_g_e_s_t _d_i_g_e_s_t, _c_o_n_s_t _c_h_a_r _*_u_s_e_r_n_a_m_e); _k_r_b_5___e_r_r_o_r___c_o_d_e kkrrbb55__ddiiggeesstt__sseett__aauutthhiidd(_k_r_b_5___c_o_n_t_e_x_t _c_o_n_t_e_x_t, _k_r_b_5___d_i_g_e_s_t _d_i_g_e_s_t, _c_o_n_s_t _c_h_a_r _*_a_u_t_h_i_d); _k_r_b_5___e_r_r_o_r___c_o_d_e kkrrbb55__ddiiggeesstt__sseett__aauutthheennttiiccaattiioonn__uusseerr(_k_r_b_5___c_o_n_t_e_x_t _c_o_n_t_e_x_t, _k_r_b_5___d_i_g_e_s_t _d_i_g_e_s_t, _k_r_b_5___p_r_i_n_c_i_p_a_l _a_u_t_h_e_n_t_i_c_a_t_i_o_n___u_s_e_r); _k_r_b_5___e_r_r_o_r___c_o_d_e kkrrbb55__ddiiggeesstt__sseett__rreeaallmm(_k_r_b_5___c_o_n_t_e_x_t _c_o_n_t_e_x_t, _k_r_b_5___d_i_g_e_s_t _d_i_g_e_s_t, _c_o_n_s_t _c_h_a_r _*_r_e_a_l_m); _k_r_b_5___e_r_r_o_r___c_o_d_e kkrrbb55__ddiiggeesstt__sseett__mmeetthhoodd(_k_r_b_5___c_o_n_t_e_x_t _c_o_n_t_e_x_t, _k_r_b_5___d_i_g_e_s_t _d_i_g_e_s_t, _c_o_n_s_t _c_h_a_r _*_m_e_t_h_o_d); _k_r_b_5___e_r_r_o_r___c_o_d_e kkrrbb55__ddiiggeesstt__sseett__uurrii(_k_r_b_5___c_o_n_t_e_x_t _c_o_n_t_e_x_t, _k_r_b_5___d_i_g_e_s_t _d_i_g_e_s_t, _c_o_n_s_t _c_h_a_r _*_u_r_i); _k_r_b_5___e_r_r_o_r___c_o_d_e kkrrbb55__ddiiggeesstt__sseett__nnoonncceeCCoouunntt(_k_r_b_5___c_o_n_t_e_x_t _c_o_n_t_e_x_t, _k_r_b_5___d_i_g_e_s_t _d_i_g_e_s_t, _c_o_n_s_t _c_h_a_r _*_n_o_n_c_e___c_o_u_n_t); _k_r_b_5___e_r_r_o_r___c_o_d_e kkrrbb55__ddiiggeesstt__sseett__qqoopp(_k_r_b_5___c_o_n_t_e_x_t _c_o_n_t_e_x_t, _k_r_b_5___d_i_g_e_s_t _d_i_g_e_s_t, _c_o_n_s_t _c_h_a_r _*_q_o_p); _k_r_b_5___e_r_r_o_r___c_o_d_e kkrrbb55__ddiiggeesstt__rreeqquueesstt(_k_r_b_5___c_o_n_t_e_x_t _c_o_n_t_e_x_t, _k_r_b_5___d_i_g_e_s_t _d_i_g_e_s_t, _k_r_b_5___r_e_a_l_m _r_e_a_l_m, _k_r_b_5___c_c_a_c_h_e _c_c_a_c_h_e); _c_o_n_s_t _c_h_a_r _* kkrrbb55__ddiiggeesstt__ggeett__rreessppoonnsseeDDaattaa(_k_r_b_5___c_o_n_t_e_x_t _c_o_n_t_e_x_t, _k_r_b_5___d_i_g_e_s_t _d_i_g_e_s_t); _c_o_n_s_t _c_h_a_r _* kkrrbb55__ddiiggeesstt__ggeett__rrsspp(_k_r_b_5___c_o_n_t_e_x_t _c_o_n_t_e_x_t, _k_r_b_5___d_i_g_e_s_t _d_i_g_e_s_t); _k_r_b_5___e_r_r_o_r___c_o_d_e kkrrbb55__ddiiggeesstt__ggeett__ttiicckkeettss(_k_r_b_5___c_o_n_t_e_x_t _c_o_n_t_e_x_t, _k_r_b_5___d_i_g_e_s_t _d_i_g_e_s_t, _T_i_c_k_e_t _*_*_t_i_c_k_e_t_s); _k_r_b_5___e_r_r_o_r___c_o_d_e kkrrbb55__ddiiggeesstt__ggeett__cclliieenntt__bbiinnddiinngg(_k_r_b_5___c_o_n_t_e_x_t _c_o_n_t_e_x_t, _k_r_b_5___d_i_g_e_s_t _d_i_g_e_s_t, _c_h_a_r _*_*_t_y_p_e, _c_h_a_r _*_*_b_i_n_d_i_n_g); _k_r_b_5___e_r_r_o_r___c_o_d_e kkrrbb55__ddiiggeesstt__ggeett__aa11__hhaasshh(_k_r_b_5___c_o_n_t_e_x_t _c_o_n_t_e_x_t, _k_r_b_5___d_i_g_e_s_t _d_i_g_e_s_t, _k_r_b_5___d_a_t_a _*_d_a_t_a); DDEESSCCRRIIPPTTIIOONN The kkrrbb55__ddiiggeesstt__aalllloocc() function allocatates the _d_i_g_e_s_t structure. The structure should be freed with kkrrbb55__ddiiggeesstt__ffrreeee() when it is no longer being used. kkrrbb55__ddiiggeesstt__aalllloocc() returns 0 to indicate success. Otherwise an kerberos code is returned and the pointer that _d_i_g_e_s_t points to is set to NULL. kkrrbb55__ddiiggeesstt__ffrreeee() free the structure _d_i_g_e_s_t. SSEEEE AALLSSOO krb5(3), kerberos(8) HEIMDAL February 18, 2007 HEIMDAL heimdal-7.5.0/lib/krb5/sock_principal.c0000644000175000017500000000503112136107750016030 0ustar niknik/* * Copyright (c) 1997 - 2001 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "krb5_locl.h" KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_sock_to_principal (krb5_context context, int sock, const char *sname, int32_t type, krb5_principal *ret_princ) { krb5_error_code ret; struct sockaddr_storage __ss; struct sockaddr *sa = (struct sockaddr *)&__ss; socklen_t salen = sizeof(__ss); char hostname[NI_MAXHOST]; if (getsockname (sock, sa, &salen) < 0) { ret = errno; krb5_set_error_message (context, ret, "getsockname: %s", strerror(ret)); return ret; } ret = getnameinfo (sa, salen, hostname, sizeof(hostname), NULL, 0, 0); if (ret) { int save_errno = errno; krb5_error_code ret2 = krb5_eai_to_heim_errno(ret, save_errno); krb5_set_error_message (context, ret2, "getnameinfo: %s", gai_strerror(ret)); return ret2; } ret = krb5_sname_to_principal (context, hostname, sname, type, ret_princ); return ret; } heimdal-7.5.0/lib/krb5/krb5_appdefault.30000644000175000017500000000612412136107750016024 0ustar niknik.\" Copyright (c) 2000 Kungliga Tekniska Högskolan .\" (Royal Institute of Technology, Stockholm, Sweden). .\" All rights reserved. .\" .\" Redistribution and use in source and binary forms, with or without .\" modification, are permitted provided that the following conditions .\" are met: .\" .\" 1. Redistributions of source code must retain the above copyright .\" notice, this list of conditions and the following disclaimer. .\" .\" 2. Redistributions in binary form must reproduce the above copyright .\" notice, this list of conditions and the following disclaimer in the .\" documentation and/or other materials provided with the distribution. .\" .\" 3. Neither the name of the Institute nor the names of its contributors .\" may be used to endorse or promote products derived from this software .\" without specific prior written permission. .\" .\" THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND .\" ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE .\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE .\" ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE .\" FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL .\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS .\" OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) .\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT .\" LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF .\" SUCH DAMAGE. .\" .\" $Id$ .\" .Dd July 25, 2000 .Dt KRB5_APPDEFAULT 3 .Os HEIMDAL .Sh NAME .Nm krb5_appdefault_boolean , .Nm krb5_appdefault_string , .Nm krb5_appdefault_time .Nd get application configuration value .Sh LIBRARY Kerberos 5 Library (libkrb5, -lkrb5) .Sh SYNOPSIS .In krb5.h .Ft void .Fn krb5_appdefault_boolean "krb5_context context" "const char *appname" "krb5_realm realm" "const char *option" "krb5_boolean def_val" "krb5_boolean *ret_val" .Ft void .Fn krb5_appdefault_string "krb5_context context" "const char *appname" "krb5_realm realm" "const char *option" "const char *def_val" "char **ret_val" .Ft void .Fn krb5_appdefault_time "krb5_context context" "const char *appname" "krb5_realm realm" "const char *option" "time_t def_val" "time_t *ret_val" .Sh DESCRIPTION These functions get application defaults from the .Dv appdefaults section of the .Xr krb5.conf 5 configuration file. These defaults can be specified per application, and/or per realm. .Pp These values will be looked for in .Xr krb5.conf 5 , in order of descending importance. .Bd -literal -offset indent [appdefaults] appname = { realm = { option = value } } appname = { option = value } realm = { option = value } option = value .Ed .Fa appname is the name of the application, and .Fa realm is the realm name. If the realm is omitted it will not be used for resolving values. .Fa def_val is the value to return if no value is found in .Xr krb5.conf 5 . .Sh SEE ALSO .Xr krb5_config 3 , .Xr krb5.conf 5 heimdal-7.5.0/lib/krb5/creds.c0000644000175000017500000002125313026237312014131 0ustar niknik/* * Copyright (c) 1997 - 2005 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "krb5_locl.h" /** * Free content of krb5_creds. * * @param context Kerberos 5 context. * @param c krb5_creds to free. * * @return Returns 0 to indicate success. Otherwise an kerberos et * error code is returned, see krb5_get_error_message(). * * @ingroup krb5 */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_free_cred_contents (krb5_context context, krb5_creds *c) { krb5_free_principal (context, c->client); c->client = NULL; krb5_free_principal (context, c->server); c->server = NULL; krb5_free_keyblock_contents (context, &c->session); krb5_data_free (&c->ticket); krb5_data_free (&c->second_ticket); free_AuthorizationData (&c->authdata); krb5_free_addresses (context, &c->addresses); memset(c, 0, sizeof(*c)); return 0; } /** * Copy content of krb5_creds. * * @param context Kerberos 5 context. * @param incred source credential * @param c destination credential, free with krb5_free_cred_contents(). * * @return Returns 0 to indicate success. Otherwise an kerberos et * error code is returned, see krb5_get_error_message(). * * @ingroup krb5 */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_copy_creds_contents (krb5_context context, const krb5_creds *incred, krb5_creds *c) { krb5_error_code ret; memset(c, 0, sizeof(*c)); ret = krb5_copy_principal (context, incred->client, &c->client); if (ret) goto fail; ret = krb5_copy_principal (context, incred->server, &c->server); if (ret) goto fail; ret = krb5_copy_keyblock_contents (context, &incred->session, &c->session); if (ret) goto fail; c->times = incred->times; ret = krb5_data_copy (&c->ticket, incred->ticket.data, incred->ticket.length); if (ret) goto fail; ret = krb5_data_copy (&c->second_ticket, incred->second_ticket.data, incred->second_ticket.length); if (ret) goto fail; ret = copy_AuthorizationData(&incred->authdata, &c->authdata); if (ret) goto fail; ret = krb5_copy_addresses (context, &incred->addresses, &c->addresses); if (ret) goto fail; c->flags = incred->flags; return 0; fail: krb5_free_cred_contents (context, c); return ret; } /** * Copy krb5_creds. * * @param context Kerberos 5 context. * @param incred source credential * @param outcred destination credential, free with krb5_free_creds(). * * @return Returns 0 to indicate success. Otherwise an kerberos et * error code is returned, see krb5_get_error_message(). * * @ingroup krb5 */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_copy_creds (krb5_context context, const krb5_creds *incred, krb5_creds **outcred) { krb5_creds *c; c = calloc(1, sizeof(*c)); if (c == NULL) return krb5_enomem(context); *outcred = c; return krb5_copy_creds_contents (context, incred, c); } /** * Free krb5_creds. * * @param context Kerberos 5 context. * @param c krb5_creds to free. * * @return Returns 0 to indicate success. Otherwise an kerberos et * error code is returned, see krb5_get_error_message(). * * @ingroup krb5 */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_free_creds (krb5_context context, krb5_creds *c) { if (c != NULL) krb5_free_cred_contents(context, c); free(c); return 0; } /* XXX this do not belong here */ static krb5_boolean krb5_times_equal(const krb5_times *a, const krb5_times *b) { return a->starttime == b->starttime && a->authtime == b->authtime && a->endtime == b->endtime && a->renew_till == b->renew_till; } /** * Return TRUE if `mcreds' and `creds' are equal (`whichfields' * determines what equal means). * * * The following flags, set in whichfields affects the comparison: * - KRB5_TC_MATCH_SRV_NAMEONLY Consider all realms equal when comparing the service principal. * - KRB5_TC_MATCH_KEYTYPE Compare enctypes. * - KRB5_TC_MATCH_FLAGS_EXACT Make sure that the ticket flags are identical. * - KRB5_TC_MATCH_FLAGS Make sure that all ticket flags set in mcreds are also present in creds . * - KRB5_TC_MATCH_TIMES_EXACT Compares the ticket times exactly. * - KRB5_TC_MATCH_TIMES Compares only the expiration times of the creds. * - KRB5_TC_MATCH_AUTHDATA Compares the authdata fields. * - KRB5_TC_MATCH_2ND_TKT Compares the second tickets (used by user-to-user authentication). * - KRB5_TC_MATCH_IS_SKEY Compares the existance of the second ticket. * * @param context Kerberos 5 context. * @param whichfields which fields to compare. * @param mcreds cred to compare with. * @param creds cred to compare with. * * @return return TRUE if mcred and creds are equal, FALSE if not. * * @ingroup krb5 */ KRB5_LIB_FUNCTION krb5_boolean KRB5_LIB_CALL krb5_compare_creds(krb5_context context, krb5_flags whichfields, const krb5_creds * mcreds, const krb5_creds * creds) { krb5_boolean match = TRUE; if (match && mcreds->server) { if (whichfields & (KRB5_TC_DONT_MATCH_REALM | KRB5_TC_MATCH_SRV_NAMEONLY)) match = krb5_principal_compare_any_realm (context, mcreds->server, creds->server); else match = krb5_principal_compare (context, mcreds->server, creds->server); } if (match && mcreds->client) { if(whichfields & KRB5_TC_DONT_MATCH_REALM) match = krb5_principal_compare_any_realm (context, mcreds->client, creds->client); else match = krb5_principal_compare (context, mcreds->client, creds->client); } if (match && (whichfields & KRB5_TC_MATCH_KEYTYPE)) match = mcreds->session.keytype == creds->session.keytype; if (match && (whichfields & KRB5_TC_MATCH_FLAGS_EXACT)) match = mcreds->flags.i == creds->flags.i; if (match && (whichfields & KRB5_TC_MATCH_FLAGS)) match = (creds->flags.i & mcreds->flags.i) == mcreds->flags.i; if (match && (whichfields & KRB5_TC_MATCH_TIMES_EXACT)) match = krb5_times_equal(&mcreds->times, &creds->times); if (match && (whichfields & KRB5_TC_MATCH_TIMES)) /* compare only expiration times */ match = (mcreds->times.renew_till <= creds->times.renew_till) && (mcreds->times.endtime <= creds->times.endtime); if (match && (whichfields & KRB5_TC_MATCH_AUTHDATA)) { unsigned int i; if(mcreds->authdata.len != creds->authdata.len) match = FALSE; else for(i = 0; match && i < mcreds->authdata.len; i++) match = (mcreds->authdata.val[i].ad_type == creds->authdata.val[i].ad_type) && (krb5_data_cmp(&mcreds->authdata.val[i].ad_data, &creds->authdata.val[i].ad_data) == 0); } if (match && (whichfields & KRB5_TC_MATCH_2ND_TKT)) match = (krb5_data_cmp(&mcreds->second_ticket, &creds->second_ticket) == 0); if (match && (whichfields & KRB5_TC_MATCH_IS_SKEY)) match = ((mcreds->second_ticket.length == 0) == (creds->second_ticket.length == 0)); return match; } /** * Returns the ticket flags for the credentials in creds. * See also krb5_ticket_get_flags(). * * @param creds credential to get ticket flags from * * @return ticket flags * * @ingroup krb5 */ KRB5_LIB_FUNCTION unsigned long KRB5_LIB_CALL krb5_creds_get_ticket_flags(krb5_creds *creds) { return TicketFlags2int(creds->flags.b); } heimdal-7.5.0/lib/krb5/acache.c0000644000175000017500000006537413026237312014251 0ustar niknik/* * Copyright (c) 2004 - 2007 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Portions Copyright (c) 2009 Apple Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "krb5_locl.h" #include #ifdef HAVE_DLFCN_H #include #endif #ifndef KCM_IS_API_CACHE static HEIMDAL_MUTEX acc_mutex = HEIMDAL_MUTEX_INITIALIZER; static cc_initialize_func init_func; static void (KRB5_CALLCONV *set_target_uid)(uid_t); static void (KRB5_CALLCONV *clear_target)(void); #ifdef HAVE_DLOPEN static void *cc_handle; #endif typedef struct krb5_acc { char *cache_name; cc_context_t context; cc_ccache_t ccache; } krb5_acc; static krb5_error_code KRB5_CALLCONV acc_close(krb5_context, krb5_ccache); #define ACACHE(X) ((krb5_acc *)(X)->data.data) static const struct { cc_int32 error; krb5_error_code ret; } cc_errors[] = { { ccErrBadName, KRB5_CC_BADNAME }, { ccErrCredentialsNotFound, KRB5_CC_NOTFOUND }, { ccErrCCacheNotFound, KRB5_FCC_NOFILE }, { ccErrContextNotFound, KRB5_CC_NOTFOUND }, { ccIteratorEnd, KRB5_CC_END }, { ccErrNoMem, KRB5_CC_NOMEM }, { ccErrServerUnavailable, KRB5_CC_NOSUPP }, { ccErrInvalidCCache, KRB5_CC_BADNAME }, { ccNoError, 0 } }; static krb5_error_code translate_cc_error(krb5_context context, cc_int32 error) { size_t i; krb5_clear_error_message(context); for(i = 0; i < sizeof(cc_errors)/sizeof(cc_errors[0]); i++) if (cc_errors[i].error == error) return cc_errors[i].ret; return KRB5_FCC_INTERNAL; } static krb5_error_code init_ccapi(krb5_context context) { const char *lib = NULL; HEIMDAL_MUTEX_lock(&acc_mutex); if (init_func) { HEIMDAL_MUTEX_unlock(&acc_mutex); if (context) krb5_clear_error_message(context); return 0; } if (context) lib = krb5_config_get_string(context, NULL, "libdefaults", "ccapi_library", NULL); if (lib == NULL) { #ifdef __APPLE__ lib = "/System/Library/Frameworks/Kerberos.framework/Kerberos"; #elif defined(KRB5_USE_PATH_TOKENS) && defined(_WIN32) lib = "%{LIBDIR}/libkrb5_cc.dll"; #else lib = "/usr/lib/libkrb5_cc.so"; #endif } #ifdef HAVE_DLOPEN #ifndef RTLD_LAZY #define RTLD_LAZY 0 #endif #ifndef RTLD_LOCAL #define RTLD_LOCAL 0 #endif #ifdef KRB5_USE_PATH_TOKENS { char * explib = NULL; if (_krb5_expand_path_tokens(context, lib, 0, &explib) == 0) { cc_handle = dlopen(explib, RTLD_LAZY|RTLD_LOCAL); free(explib); } } #else cc_handle = dlopen(lib, RTLD_LAZY|RTLD_LOCAL); #endif if (cc_handle == NULL) { HEIMDAL_MUTEX_unlock(&acc_mutex); if (context) krb5_set_error_message(context, KRB5_CC_NOSUPP, N_("Failed to load API cache module %s", "file"), lib); return KRB5_CC_NOSUPP; } init_func = (cc_initialize_func)dlsym(cc_handle, "cc_initialize"); set_target_uid = (void (KRB5_CALLCONV *)(uid_t)) dlsym(cc_handle, "krb5_ipc_client_set_target_uid"); clear_target = (void (KRB5_CALLCONV *)(void)) dlsym(cc_handle, "krb5_ipc_client_clear_target"); HEIMDAL_MUTEX_unlock(&acc_mutex); if (init_func == NULL) { if (context) krb5_set_error_message(context, KRB5_CC_NOSUPP, N_("Failed to find cc_initialize" "in %s: %s", "file, error"), lib, dlerror()); dlclose(cc_handle); return KRB5_CC_NOSUPP; } return 0; #else HEIMDAL_MUTEX_unlock(&acc_mutex); if (context) krb5_set_error_message(context, KRB5_CC_NOSUPP, N_("no support for shared object", "")); return KRB5_CC_NOSUPP; #endif } KRB5_LIB_FUNCTION void KRB5_LIB_CALL _heim_krb5_ipc_client_set_target_uid(uid_t uid) { init_ccapi(NULL); if (set_target_uid != NULL) (*set_target_uid)(uid); } KRB5_LIB_FUNCTION void KRB5_LIB_CALL _heim_krb5_ipc_client_clear_target(void) { init_ccapi(NULL); if (clear_target != NULL) (*clear_target)(); } static krb5_error_code make_cred_from_ccred(krb5_context context, const cc_credentials_v5_t *incred, krb5_creds *cred) { krb5_error_code ret; unsigned int i; memset(cred, 0, sizeof(*cred)); ret = krb5_parse_name(context, incred->client, &cred->client); if (ret) goto fail; ret = krb5_parse_name(context, incred->server, &cred->server); if (ret) goto fail; cred->session.keytype = incred->keyblock.type; cred->session.keyvalue.length = incred->keyblock.length; cred->session.keyvalue.data = malloc(incred->keyblock.length); if (cred->session.keyvalue.data == NULL) goto nomem; memcpy(cred->session.keyvalue.data, incred->keyblock.data, incred->keyblock.length); cred->times.authtime = incred->authtime; cred->times.starttime = incred->starttime; cred->times.endtime = incred->endtime; cred->times.renew_till = incred->renew_till; ret = krb5_data_copy(&cred->ticket, incred->ticket.data, incred->ticket.length); if (ret) goto nomem; ret = krb5_data_copy(&cred->second_ticket, incred->second_ticket.data, incred->second_ticket.length); if (ret) goto nomem; cred->authdata.val = NULL; cred->authdata.len = 0; cred->addresses.val = NULL; cred->addresses.len = 0; for (i = 0; incred->authdata && incred->authdata[i]; i++) ; if (i) { cred->authdata.val = calloc(i, sizeof(cred->authdata.val[0])); if (cred->authdata.val == NULL) goto nomem; cred->authdata.len = i; for (i = 0; i < cred->authdata.len; i++) { cred->authdata.val[i].ad_type = incred->authdata[i]->type; ret = krb5_data_copy(&cred->authdata.val[i].ad_data, incred->authdata[i]->data, incred->authdata[i]->length); if (ret) goto nomem; } } for (i = 0; incred->addresses && incred->addresses[i]; i++) ; if (i) { cred->addresses.val = calloc(i, sizeof(cred->addresses.val[0])); if (cred->addresses.val == NULL) goto nomem; cred->addresses.len = i; for (i = 0; i < cred->addresses.len; i++) { cred->addresses.val[i].addr_type = incred->addresses[i]->type; ret = krb5_data_copy(&cred->addresses.val[i].address, incred->addresses[i]->data, incred->addresses[i]->length); if (ret) goto nomem; } } cred->flags.i = 0; if (incred->ticket_flags & KRB5_CCAPI_TKT_FLG_FORWARDABLE) cred->flags.b.forwardable = 1; if (incred->ticket_flags & KRB5_CCAPI_TKT_FLG_FORWARDED) cred->flags.b.forwarded = 1; if (incred->ticket_flags & KRB5_CCAPI_TKT_FLG_PROXIABLE) cred->flags.b.proxiable = 1; if (incred->ticket_flags & KRB5_CCAPI_TKT_FLG_PROXY) cred->flags.b.proxy = 1; if (incred->ticket_flags & KRB5_CCAPI_TKT_FLG_MAY_POSTDATE) cred->flags.b.may_postdate = 1; if (incred->ticket_flags & KRB5_CCAPI_TKT_FLG_POSTDATED) cred->flags.b.postdated = 1; if (incred->ticket_flags & KRB5_CCAPI_TKT_FLG_INVALID) cred->flags.b.invalid = 1; if (incred->ticket_flags & KRB5_CCAPI_TKT_FLG_RENEWABLE) cred->flags.b.renewable = 1; if (incred->ticket_flags & KRB5_CCAPI_TKT_FLG_INITIAL) cred->flags.b.initial = 1; if (incred->ticket_flags & KRB5_CCAPI_TKT_FLG_PRE_AUTH) cred->flags.b.pre_authent = 1; if (incred->ticket_flags & KRB5_CCAPI_TKT_FLG_HW_AUTH) cred->flags.b.hw_authent = 1; if (incred->ticket_flags & KRB5_CCAPI_TKT_FLG_TRANSIT_POLICY_CHECKED) cred->flags.b.transited_policy_checked = 1; if (incred->ticket_flags & KRB5_CCAPI_TKT_FLG_OK_AS_DELEGATE) cred->flags.b.ok_as_delegate = 1; if (incred->ticket_flags & KRB5_CCAPI_TKT_FLG_ANONYMOUS) cred->flags.b.anonymous = 1; return 0; nomem: ret = krb5_enomem(context); fail: krb5_free_cred_contents(context, cred); return ret; } static void free_ccred(cc_credentials_v5_t *cred) { int i; if (cred->addresses) { for (i = 0; cred->addresses[i] != 0; i++) { if (cred->addresses[i]->data) free(cred->addresses[i]->data); free(cred->addresses[i]); } free(cred->addresses); } if (cred->server) free(cred->server); if (cred->client) free(cred->client); memset(cred, 0, sizeof(*cred)); } static krb5_error_code make_ccred_from_cred(krb5_context context, const krb5_creds *incred, cc_credentials_v5_t *cred) { krb5_error_code ret; size_t i; memset(cred, 0, sizeof(*cred)); ret = krb5_unparse_name(context, incred->client, &cred->client); if (ret) goto fail; ret = krb5_unparse_name(context, incred->server, &cred->server); if (ret) goto fail; cred->keyblock.type = incred->session.keytype; cred->keyblock.length = incred->session.keyvalue.length; cred->keyblock.data = incred->session.keyvalue.data; cred->authtime = incred->times.authtime; cred->starttime = incred->times.starttime; cred->endtime = incred->times.endtime; cred->renew_till = incred->times.renew_till; cred->ticket.length = incred->ticket.length; cred->ticket.data = incred->ticket.data; cred->second_ticket.length = incred->second_ticket.length; cred->second_ticket.data = incred->second_ticket.data; /* XXX this one should also be filled in */ cred->authdata = NULL; cred->addresses = calloc(incred->addresses.len + 1, sizeof(cred->addresses[0])); if (cred->addresses == NULL) { ret = ENOMEM; goto fail; } for (i = 0; i < incred->addresses.len; i++) { cc_data *addr; addr = malloc(sizeof(*addr)); if (addr == NULL) { ret = ENOMEM; goto fail; } addr->type = incred->addresses.val[i].addr_type; addr->length = incred->addresses.val[i].address.length; addr->data = malloc(addr->length); if (addr->data == NULL) { free(addr); ret = ENOMEM; goto fail; } memcpy(addr->data, incred->addresses.val[i].address.data, addr->length); cred->addresses[i] = addr; } cred->addresses[i] = NULL; cred->ticket_flags = 0; if (incred->flags.b.forwardable) cred->ticket_flags |= KRB5_CCAPI_TKT_FLG_FORWARDABLE; if (incred->flags.b.forwarded) cred->ticket_flags |= KRB5_CCAPI_TKT_FLG_FORWARDED; if (incred->flags.b.proxiable) cred->ticket_flags |= KRB5_CCAPI_TKT_FLG_PROXIABLE; if (incred->flags.b.proxy) cred->ticket_flags |= KRB5_CCAPI_TKT_FLG_PROXY; if (incred->flags.b.may_postdate) cred->ticket_flags |= KRB5_CCAPI_TKT_FLG_MAY_POSTDATE; if (incred->flags.b.postdated) cred->ticket_flags |= KRB5_CCAPI_TKT_FLG_POSTDATED; if (incred->flags.b.invalid) cred->ticket_flags |= KRB5_CCAPI_TKT_FLG_INVALID; if (incred->flags.b.renewable) cred->ticket_flags |= KRB5_CCAPI_TKT_FLG_RENEWABLE; if (incred->flags.b.initial) cred->ticket_flags |= KRB5_CCAPI_TKT_FLG_INITIAL; if (incred->flags.b.pre_authent) cred->ticket_flags |= KRB5_CCAPI_TKT_FLG_PRE_AUTH; if (incred->flags.b.hw_authent) cred->ticket_flags |= KRB5_CCAPI_TKT_FLG_HW_AUTH; if (incred->flags.b.transited_policy_checked) cred->ticket_flags |= KRB5_CCAPI_TKT_FLG_TRANSIT_POLICY_CHECKED; if (incred->flags.b.ok_as_delegate) cred->ticket_flags |= KRB5_CCAPI_TKT_FLG_OK_AS_DELEGATE; if (incred->flags.b.anonymous) cred->ticket_flags |= KRB5_CCAPI_TKT_FLG_ANONYMOUS; return 0; fail: free_ccred(cred); krb5_clear_error_message(context); return ret; } static cc_int32 get_cc_name(krb5_acc *a) { cc_string_t name; cc_int32 error; error = (*a->ccache->func->get_name)(a->ccache, &name); if (error) return error; a->cache_name = strdup(name->data); (*name->func->release)(name); if (a->cache_name == NULL) return ccErrNoMem; return ccNoError; } static const char* KRB5_CALLCONV acc_get_name(krb5_context context, krb5_ccache id) { krb5_acc *a = ACACHE(id); int32_t error; if (a->cache_name == NULL) { krb5_error_code ret; krb5_principal principal; char *name; ret = _krb5_get_default_principal_local(context, &principal); if (ret) return NULL; ret = krb5_unparse_name(context, principal, &name); krb5_free_principal(context, principal); if (ret) return NULL; error = (*a->context->func->create_new_ccache)(a->context, cc_credentials_v5, name, &a->ccache); krb5_xfree(name); if (error) return NULL; error = get_cc_name(a); if (error) return NULL; } return a->cache_name; } static krb5_error_code KRB5_CALLCONV acc_alloc(krb5_context context, krb5_ccache *id) { krb5_error_code ret; cc_int32 error; krb5_acc *a; ret = init_ccapi(context); if (ret) return ret; ret = krb5_data_alloc(&(*id)->data, sizeof(*a)); if (ret) { krb5_clear_error_message(context); return ret; } a = ACACHE(*id); error = (*init_func)(&a->context, ccapi_version_3, NULL, NULL); if (error) { krb5_data_free(&(*id)->data); return translate_cc_error(context, error); } a->cache_name = NULL; return 0; } static krb5_error_code KRB5_CALLCONV acc_resolve(krb5_context context, krb5_ccache *id, const char *res) { krb5_error_code ret; cc_int32 error; krb5_acc *a; ret = acc_alloc(context, id); if (ret) return ret; a = ACACHE(*id); error = (*a->context->func->open_ccache)(a->context, res, &a->ccache); if (error == ccNoError) { cc_time_t offset; error = get_cc_name(a); if (error != ccNoError) { acc_close(context, *id); *id = NULL; return translate_cc_error(context, error); } error = (*a->ccache->func->get_kdc_time_offset)(a->ccache, cc_credentials_v5, &offset); if (error == 0) context->kdc_sec_offset = offset; } else if (error == ccErrCCacheNotFound) { a->ccache = NULL; a->cache_name = NULL; } else { *id = NULL; return translate_cc_error(context, error); } return 0; } static krb5_error_code KRB5_CALLCONV acc_gen_new(krb5_context context, krb5_ccache *id) { krb5_error_code ret; krb5_acc *a; ret = acc_alloc(context, id); if (ret) return ret; a = ACACHE(*id); a->ccache = NULL; a->cache_name = NULL; return 0; } static krb5_error_code KRB5_CALLCONV acc_initialize(krb5_context context, krb5_ccache id, krb5_principal primary_principal) { krb5_acc *a = ACACHE(id); krb5_error_code ret; int32_t error; char *name; ret = krb5_unparse_name(context, primary_principal, &name); if (ret) return ret; if (a->cache_name == NULL) { error = (*a->context->func->create_new_ccache)(a->context, cc_credentials_v5, name, &a->ccache); free(name); if (error == ccNoError) error = get_cc_name(a); } else { cc_credentials_iterator_t iter; cc_credentials_t ccred; error = (*a->ccache->func->new_credentials_iterator)(a->ccache, &iter); if (error) { free(name); return translate_cc_error(context, error); } while (1) { error = (*iter->func->next)(iter, &ccred); if (error) break; (*a->ccache->func->remove_credentials)(a->ccache, ccred); (*ccred->func->release)(ccred); } (*iter->func->release)(iter); error = (*a->ccache->func->set_principal)(a->ccache, cc_credentials_v5, name); } if (error == 0 && context->kdc_sec_offset) error = (*a->ccache->func->set_kdc_time_offset)(a->ccache, cc_credentials_v5, context->kdc_sec_offset); return translate_cc_error(context, error); } static krb5_error_code KRB5_CALLCONV acc_close(krb5_context context, krb5_ccache id) { krb5_acc *a = ACACHE(id); if (a->ccache) { (*a->ccache->func->release)(a->ccache); a->ccache = NULL; } if (a->cache_name) { free(a->cache_name); a->cache_name = NULL; } if (a->context) { (*a->context->func->release)(a->context); a->context = NULL; } krb5_data_free(&id->data); return 0; } static krb5_error_code KRB5_CALLCONV acc_destroy(krb5_context context, krb5_ccache id) { krb5_acc *a = ACACHE(id); cc_int32 error = 0; if (a->ccache) { error = (*a->ccache->func->destroy)(a->ccache); a->ccache = NULL; } if (a->context) { error = (a->context->func->release)(a->context); a->context = NULL; } return translate_cc_error(context, error); } static krb5_error_code KRB5_CALLCONV acc_store_cred(krb5_context context, krb5_ccache id, krb5_creds *creds) { krb5_acc *a = ACACHE(id); cc_credentials_union cred; cc_credentials_v5_t v5cred; krb5_error_code ret; cc_int32 error; if (a->ccache == NULL) { krb5_set_error_message(context, KRB5_CC_NOTFOUND, N_("No API credential found", "")); return KRB5_CC_NOTFOUND; } cred.version = cc_credentials_v5; cred.credentials.credentials_v5 = &v5cred; ret = make_ccred_from_cred(context, creds, &v5cred); if (ret) return ret; error = (*a->ccache->func->store_credentials)(a->ccache, &cred); if (error) ret = translate_cc_error(context, error); free_ccred(&v5cred); return ret; } static krb5_error_code KRB5_CALLCONV acc_get_principal(krb5_context context, krb5_ccache id, krb5_principal *principal) { krb5_acc *a = ACACHE(id); krb5_error_code ret; int32_t error; cc_string_t name; if (a->ccache == NULL) { krb5_set_error_message(context, KRB5_CC_NOTFOUND, N_("No API credential found", "")); return KRB5_CC_NOTFOUND; } error = (*a->ccache->func->get_principal)(a->ccache, cc_credentials_v5, &name); if (error) return translate_cc_error(context, error); ret = krb5_parse_name(context, name->data, principal); (*name->func->release)(name); return ret; } static krb5_error_code KRB5_CALLCONV acc_get_first (krb5_context context, krb5_ccache id, krb5_cc_cursor *cursor) { cc_credentials_iterator_t iter; krb5_acc *a = ACACHE(id); int32_t error; if (a->ccache == NULL) { krb5_set_error_message(context, KRB5_CC_NOTFOUND, N_("No API credential found", "")); return KRB5_CC_NOTFOUND; } error = (*a->ccache->func->new_credentials_iterator)(a->ccache, &iter); if (error) { krb5_clear_error_message(context); return ENOENT; } *cursor = iter; return 0; } static krb5_error_code KRB5_CALLCONV acc_get_next (krb5_context context, krb5_ccache id, krb5_cc_cursor *cursor, krb5_creds *creds) { cc_credentials_iterator_t iter = *cursor; cc_credentials_t cred; krb5_error_code ret; int32_t error; while (1) { error = (*iter->func->next)(iter, &cred); if (error) return translate_cc_error(context, error); if (cred->data->version == cc_credentials_v5) break; (*cred->func->release)(cred); } ret = make_cred_from_ccred(context, cred->data->credentials.credentials_v5, creds); (*cred->func->release)(cred); return ret; } static krb5_error_code KRB5_CALLCONV acc_end_get (krb5_context context, krb5_ccache id, krb5_cc_cursor *cursor) { cc_credentials_iterator_t iter = *cursor; (*iter->func->release)(iter); return 0; } static krb5_error_code KRB5_CALLCONV acc_remove_cred(krb5_context context, krb5_ccache id, krb5_flags which, krb5_creds *cred) { cc_credentials_iterator_t iter; krb5_acc *a = ACACHE(id); cc_credentials_t ccred; krb5_error_code ret; cc_int32 error; char *client, *server; if (a->ccache == NULL) { krb5_set_error_message(context, KRB5_CC_NOTFOUND, N_("No API credential found", "")); return KRB5_CC_NOTFOUND; } if (cred->client) { ret = krb5_unparse_name(context, cred->client, &client); if (ret) return ret; } else client = NULL; ret = krb5_unparse_name(context, cred->server, &server); if (ret) { free(client); return ret; } error = (*a->ccache->func->new_credentials_iterator)(a->ccache, &iter); if (error) { free(server); free(client); return translate_cc_error(context, error); } ret = KRB5_CC_NOTFOUND; while (1) { cc_credentials_v5_t *v5cred; error = (*iter->func->next)(iter, &ccred); if (error) break; if (ccred->data->version != cc_credentials_v5) goto next; v5cred = ccred->data->credentials.credentials_v5; if (client && strcmp(v5cred->client, client) != 0) goto next; if (strcmp(v5cred->server, server) != 0) goto next; (*a->ccache->func->remove_credentials)(a->ccache, ccred); ret = 0; next: (*ccred->func->release)(ccred); } (*iter->func->release)(iter); if (ret) krb5_set_error_message(context, ret, N_("Can't find credential %s in cache", "principal"), server); free(server); free(client); return ret; } static krb5_error_code KRB5_CALLCONV acc_set_flags(krb5_context context, krb5_ccache id, krb5_flags flags) { return 0; } static int KRB5_CALLCONV acc_get_version(krb5_context context, krb5_ccache id) { return 0; } struct cache_iter { cc_context_t context; cc_ccache_iterator_t iter; }; static krb5_error_code KRB5_CALLCONV acc_get_cache_first(krb5_context context, krb5_cc_cursor *cursor) { struct cache_iter *iter; krb5_error_code ret; cc_int32 error; ret = init_ccapi(context); if (ret) return ret; iter = calloc(1, sizeof(*iter)); if (iter == NULL) return krb5_enomem(context); error = (*init_func)(&iter->context, ccapi_version_3, NULL, NULL); if (error) { free(iter); return translate_cc_error(context, error); } error = (*iter->context->func->new_ccache_iterator)(iter->context, &iter->iter); if (error) { free(iter); krb5_clear_error_message(context); return ENOENT; } *cursor = iter; return 0; } static krb5_error_code KRB5_CALLCONV acc_get_cache_next(krb5_context context, krb5_cc_cursor cursor, krb5_ccache *id) { struct cache_iter *iter = cursor; cc_ccache_t cache; krb5_acc *a; krb5_error_code ret; int32_t error; error = (*iter->iter->func->next)(iter->iter, &cache); if (error) return translate_cc_error(context, error); ret = _krb5_cc_allocate(context, &krb5_acc_ops, id); if (ret) { (*cache->func->release)(cache); return ret; } ret = acc_alloc(context, id); if (ret) { (*cache->func->release)(cache); free(*id); return ret; } a = ACACHE(*id); a->ccache = cache; error = get_cc_name(a); if (error) { acc_close(context, *id); *id = NULL; return translate_cc_error(context, error); } return 0; } static krb5_error_code KRB5_CALLCONV acc_end_cache_get(krb5_context context, krb5_cc_cursor cursor) { struct cache_iter *iter = cursor; (*iter->iter->func->release)(iter->iter); iter->iter = NULL; (*iter->context->func->release)(iter->context); iter->context = NULL; free(iter); return 0; } static krb5_error_code KRB5_CALLCONV acc_move(krb5_context context, krb5_ccache from, krb5_ccache to) { krb5_acc *afrom = ACACHE(from); krb5_acc *ato = ACACHE(to); int32_t error; if (ato->ccache == NULL) { cc_string_t name; error = (*afrom->ccache->func->get_principal)(afrom->ccache, cc_credentials_v5, &name); if (error) return translate_cc_error(context, error); error = (*ato->context->func->create_new_ccache)(ato->context, cc_credentials_v5, name->data, &ato->ccache); (*name->func->release)(name); if (error) return translate_cc_error(context, error); } error = (*ato->ccache->func->move)(afrom->ccache, ato->ccache); acc_destroy(context, from); return translate_cc_error(context, error); } static krb5_error_code KRB5_CALLCONV acc_get_default_name(krb5_context context, char **str) { krb5_error_code ret; cc_context_t cc; cc_string_t name; int32_t error; ret = init_ccapi(context); if (ret) return ret; error = (*init_func)(&cc, ccapi_version_3, NULL, NULL); if (error) return translate_cc_error(context, error); error = (*cc->func->get_default_ccache_name)(cc, &name); if (error) { (*cc->func->release)(cc); return translate_cc_error(context, error); } error = asprintf(str, "API:%s", name->data); (*name->func->release)(name); (*cc->func->release)(cc); if (error < 0 || *str == NULL) return krb5_enomem(context); return 0; } static krb5_error_code KRB5_CALLCONV acc_set_default(krb5_context context, krb5_ccache id) { krb5_acc *a = ACACHE(id); cc_int32 error; if (a->ccache == NULL) { krb5_set_error_message(context, KRB5_CC_NOTFOUND, N_("No API credential found", "")); return KRB5_CC_NOTFOUND; } error = (*a->ccache->func->set_default)(a->ccache); if (error) return translate_cc_error(context, error); return 0; } static krb5_error_code KRB5_CALLCONV acc_lastchange(krb5_context context, krb5_ccache id, krb5_timestamp *mtime) { krb5_acc *a = ACACHE(id); cc_int32 error; cc_time_t t; if (a->ccache == NULL) { krb5_set_error_message(context, KRB5_CC_NOTFOUND, N_("No API credential found", "")); return KRB5_CC_NOTFOUND; } error = (*a->ccache->func->get_change_time)(a->ccache, &t); if (error) return translate_cc_error(context, error); *mtime = t; return 0; } /** * Variable containing the API based credential cache implemention. * * @ingroup krb5_ccache */ KRB5_LIB_VARIABLE const krb5_cc_ops krb5_acc_ops = { KRB5_CC_OPS_VERSION, "API", acc_get_name, acc_resolve, acc_gen_new, acc_initialize, acc_destroy, acc_close, acc_store_cred, NULL, /* acc_retrieve */ acc_get_principal, acc_get_first, acc_get_next, acc_end_get, acc_remove_cred, acc_set_flags, acc_get_version, acc_get_cache_first, acc_get_cache_next, acc_end_cache_get, acc_move, acc_get_default_name, acc_set_default, acc_lastchange, NULL, NULL, }; #endif heimdal-7.5.0/lib/krb5/log.c0000644000175000017500000003053013062303006013602 0ustar niknik/* * Copyright (c) 1997-2006 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Portions Copyright (c) 2009 Apple Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "krb5_locl.h" #include struct facility { int min; int max; krb5_log_log_func_t log_func; krb5_log_close_func_t close_func; void *data; }; static struct facility* log_realloc(krb5_log_facility *f) { struct facility *fp; fp = realloc(f->val, (f->len + 1) * sizeof(*f->val)); if(fp == NULL) return NULL; f->len++; f->val = fp; fp += f->len - 1; return fp; } struct s2i { const char *s; int val; }; #define L(X) { #X, LOG_ ## X } static struct s2i syslogvals[] = { L(EMERG), L(ALERT), L(CRIT), L(ERR), L(WARNING), L(NOTICE), L(INFO), L(DEBUG), L(AUTH), #ifdef LOG_AUTHPRIV L(AUTHPRIV), #endif #ifdef LOG_CRON L(CRON), #endif L(DAEMON), #ifdef LOG_FTP L(FTP), #endif L(KERN), L(LPR), L(MAIL), #ifdef LOG_NEWS L(NEWS), #endif L(SYSLOG), L(USER), #ifdef LOG_UUCP L(UUCP), #endif L(LOCAL0), L(LOCAL1), L(LOCAL2), L(LOCAL3), L(LOCAL4), L(LOCAL5), L(LOCAL6), L(LOCAL7), { NULL, -1 } }; static int find_value(const char *s, struct s2i *table) { while(table->s && strcasecmp(table->s, s)) table++; return table->val; } KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_initlog(krb5_context context, const char *program, krb5_log_facility **fac) { krb5_log_facility *f = calloc(1, sizeof(*f)); if (f == NULL) return krb5_enomem(context); f->program = strdup(program); if(f->program == NULL){ free(f); return krb5_enomem(context); } *fac = f; return 0; } KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_addlog_func(krb5_context context, krb5_log_facility *fac, int min, int max, krb5_log_log_func_t log_func, krb5_log_close_func_t close_func, void *data) { struct facility *fp = log_realloc(fac); if (fp == NULL) return krb5_enomem(context); fp->min = min; fp->max = max; fp->log_func = log_func; fp->close_func = close_func; fp->data = data; return 0; } struct _heimdal_syslog_data{ int priority; }; static void KRB5_CALLCONV log_syslog(const char *timestr, const char *msg, void *data) { struct _heimdal_syslog_data *s = data; syslog(s->priority, "%s", msg); } static void KRB5_CALLCONV close_syslog(void *data) { free(data); closelog(); } static krb5_error_code open_syslog(krb5_context context, krb5_log_facility *facility, int min, int max, const char *sev, const char *fac) { struct _heimdal_syslog_data *sd = malloc(sizeof(*sd)); int i; if (sd == NULL) return krb5_enomem(context); i = find_value(sev, syslogvals); if(i == -1) i = LOG_ERR; sd->priority = i; i = find_value(fac, syslogvals); if(i == -1) i = LOG_AUTH; sd->priority |= i; roken_openlog(facility->program, LOG_PID | LOG_NDELAY, i); return krb5_addlog_func(context, facility, min, max, log_syslog, close_syslog, sd); } struct file_data{ const char *filename; const char *mode; FILE *fd; int keep_open; int freefilename; }; static void KRB5_CALLCONV log_file(const char *timestr, const char *msg, void *data) { struct file_data *f = data; char *msgclean; size_t len = strlen(msg); if(f->keep_open == 0) f->fd = fopen(f->filename, f->mode); if(f->fd == NULL) return; /* make sure the log doesn't contain special chars */ msgclean = malloc((len + 1) * 4); if (msgclean == NULL) goto out; strvisx(msgclean, rk_UNCONST(msg), len, VIS_OCTAL); fprintf(f->fd, "%s %s\n", timestr, msgclean); free(msgclean); out: if(f->keep_open == 0) { fclose(f->fd); f->fd = NULL; } } static void KRB5_CALLCONV close_file(void *data) { struct file_data *f = data; if(f->keep_open && f->filename) fclose(f->fd); if (f->filename && f->freefilename) free((char *)f->filename); free(data); } static krb5_error_code open_file(krb5_context context, krb5_log_facility *fac, int min, int max, const char *filename, const char *mode, FILE *f, int keep_open, int freefilename) { struct file_data *fd = malloc(sizeof(*fd)); if (fd == NULL) { if (freefilename && filename) free((char *)filename); return krb5_enomem(context); } fd->filename = filename; fd->mode = mode; fd->fd = f; fd->keep_open = keep_open; fd->freefilename = freefilename; return krb5_addlog_func(context, fac, min, max, log_file, close_file, fd); } KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_addlog_dest(krb5_context context, krb5_log_facility *f, const char *orig) { krb5_error_code ret = 0; int min = 0, max = -1, n; char c; const char *p = orig; #ifdef _WIN32 const char *q; #endif n = sscanf(p, "%d%c%d/", &min, &c, &max); if(n == 2){ if(ISPATHSEP(c)) { if(min < 0){ max = -min; min = 0; }else{ max = min; } } } if(n){ #ifdef _WIN32 q = strrchr(p, '\\'); if (q != NULL) p = q; else #endif p = strchr(p, '/'); if(p == NULL) { krb5_set_error_message(context, HEIM_ERR_LOG_PARSE, N_("failed to parse \"%s\"", ""), orig); return HEIM_ERR_LOG_PARSE; } p++; } if(strcmp(p, "STDERR") == 0){ ret = open_file(context, f, min, max, NULL, NULL, stderr, 1, 0); }else if(strcmp(p, "CONSOLE") == 0){ ret = open_file(context, f, min, max, "/dev/console", "w", NULL, 0, 0); }else if(strncmp(p, "FILE", 4) == 0 && (p[4] == ':' || p[4] == '=')){ char *fn; FILE *file = NULL; int keep_open = 0; fn = strdup(p + 5); if (fn == NULL) return krb5_enomem(context); if(p[4] == '='){ int i = open(fn, O_WRONLY | O_CREAT | O_TRUNC | O_APPEND, 0666); if(i < 0) { ret = errno; krb5_set_error_message(context, ret, N_("open(%s) logfile: %s", ""), fn, strerror(ret)); free(fn); return ret; } rk_cloexec(i); file = fdopen(i, "a"); if(file == NULL){ ret = errno; close(i); krb5_set_error_message(context, ret, N_("fdopen(%s) logfile: %s", ""), fn, strerror(ret)); free(fn); return ret; } keep_open = 1; } ret = open_file(context, f, min, max, fn, "a", file, keep_open, 1); }else if(strncmp(p, "DEVICE", 6) == 0 && (p[6] == ':' || p[6] == '=')){ ret = open_file(context, f, min, max, strdup(p + 7), "w", NULL, 0, 1); }else if(strncmp(p, "SYSLOG", 6) == 0 && (p[6] == '\0' || p[6] == ':')){ char severity[128] = ""; char facility[128] = ""; p += 6; if(*p != '\0') p++; if(strsep_copy(&p, ":", severity, sizeof(severity)) != -1) strsep_copy(&p, ":", facility, sizeof(facility)); if(*severity == '\0') strlcpy(severity, "ERR", sizeof(severity)); if(*facility == '\0') strlcpy(facility, "AUTH", sizeof(facility)); ret = open_syslog(context, f, min, max, severity, facility); }else{ ret = HEIM_ERR_LOG_PARSE; /* XXX */ krb5_set_error_message (context, ret, N_("unknown log type: %s", ""), p); } return ret; } KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_openlog(krb5_context context, const char *program, krb5_log_facility **fac) { krb5_error_code ret; char **p, **q; ret = krb5_initlog(context, program, fac); if(ret) return ret; p = krb5_config_get_strings(context, NULL, "logging", program, NULL); if(p == NULL) p = krb5_config_get_strings(context, NULL, "logging", "default", NULL); if(p){ for(q = p; *q && ret == 0; q++) ret = krb5_addlog_dest(context, *fac, *q); krb5_config_free_strings(p); }else ret = krb5_addlog_dest(context, *fac, "SYSLOG"); return ret; } KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_closelog(krb5_context context, krb5_log_facility *fac) { int i; for(i = 0; i < fac->len; i++) (*fac->val[i].close_func)(fac->val[i].data); free(fac->val); free(fac->program); fac->val = NULL; fac->len = 0; fac->program = NULL; free(fac); return 0; } #undef __attribute__ #define __attribute__(X) KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_vlog_msg(krb5_context context, krb5_log_facility *fac, char **reply, int level, const char *fmt, va_list ap) __attribute__ ((__format__ (__printf__, 5, 0))) { char *msg = NULL; const char *actual = NULL; char buf[64]; time_t t = 0; int i; for(i = 0; fac && i < fac->len; i++) if(fac->val[i].min <= level && (fac->val[i].max < 0 || fac->val[i].max >= level)) { if(t == 0) { t = time(NULL); krb5_format_time(context, t, buf, sizeof(buf), TRUE); } if(actual == NULL) { int ret = vasprintf(&msg, fmt, ap); if(ret < 0 || msg == NULL) actual = fmt; else actual = msg; } (*fac->val[i].log_func)(buf, actual, fac->val[i].data); } if(reply == NULL) free(msg); else *reply = msg; return 0; } KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_vlog(krb5_context context, krb5_log_facility *fac, int level, const char *fmt, va_list ap) __attribute__ ((__format__ (__printf__, 4, 0))) { return krb5_vlog_msg(context, fac, NULL, level, fmt, ap); } KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_log_msg(krb5_context context, krb5_log_facility *fac, int level, char **reply, const char *fmt, ...) __attribute__ ((__format__ (__printf__, 5, 6))) { va_list ap; krb5_error_code ret; va_start(ap, fmt); ret = krb5_vlog_msg(context, fac, reply, level, fmt, ap); va_end(ap); return ret; } KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_log(krb5_context context, krb5_log_facility *fac, int level, const char *fmt, ...) __attribute__ ((__format__ (__printf__, 4, 5))) { va_list ap; krb5_error_code ret; va_start(ap, fmt); ret = krb5_vlog(context, fac, level, fmt, ap); va_end(ap); return ret; } void KRB5_LIB_FUNCTION _krb5_debug(krb5_context context, int level, const char *fmt, ...) __attribute__ ((__format__ (__printf__, 3, 4))) { va_list ap; if (context == NULL || context->debug_dest == NULL) return; va_start(ap, fmt); krb5_vlog(context, context->debug_dest, level, fmt, ap); va_end(ap); } KRB5_LIB_FUNCTION krb5_boolean KRB5_LIB_CALL _krb5_have_debug(krb5_context context, int level) { if (context == NULL || context->debug_dest == NULL) return 0 ; return 1; } KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_set_debug_dest(krb5_context context, const char *program, const char *log_spec) { krb5_error_code ret; if (context->debug_dest == NULL) { ret = krb5_initlog(context, program, &context->debug_dest); if (ret) return ret; } ret = krb5_addlog_dest(context, context->debug_dest, log_spec); if (ret) return ret; return 0; } heimdal-7.5.0/lib/krb5/expand_path.c0000644000175000017500000003543213212137553015333 0ustar niknik /*********************************************************************** * Copyright (c) 2009, Secure Endpoints Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * - Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. * **********************************************************************/ #include "krb5_locl.h" #include typedef int PTYPE; #ifdef _WIN32 #include #include /* * Expand a %{TEMP} token * * The %{TEMP} token expands to the temporary path for the current * user as returned by GetTempPath(). * * @note: Since the GetTempPath() function relies on the TMP or TEMP * environment variables, this function will failover to the system * temporary directory until the user profile is loaded. In addition, * the returned path may or may not exist. */ static krb5_error_code _expand_temp_folder(krb5_context context, PTYPE param, const char *postfix, char **ret) { TCHAR tpath[MAX_PATH]; size_t len; if (!GetTempPath(sizeof(tpath)/sizeof(tpath[0]), tpath)) { if (context) krb5_set_error_message(context, EINVAL, "Failed to get temporary path (GLE=%d)", GetLastError()); return EINVAL; } len = strlen(tpath); if (len > 0 && tpath[len - 1] == '\\') tpath[len - 1] = '\0'; *ret = strdup(tpath); if (*ret == NULL) return krb5_enomem(context); return 0; } extern HINSTANCE _krb5_hInstance; /* * Expand a %{BINDIR} token * * This is also used to expand a few other tokens on Windows, since * most of the executable binaries end up in the same directory. The * "bin" directory is considered to be the directory in which the * krb5.dll is located. */ static krb5_error_code _expand_bin_dir(krb5_context context, PTYPE param, const char *postfix, char **ret) { TCHAR path[MAX_PATH]; TCHAR *lastSlash; DWORD nc; nc = GetModuleFileName(_krb5_hInstance, path, sizeof(path)/sizeof(path[0])); if (nc == 0 || nc == sizeof(path)/sizeof(path[0])) { return EINVAL; } lastSlash = strrchr(path, '\\'); if (lastSlash != NULL) { TCHAR *fslash = strrchr(lastSlash, '/'); if (fslash != NULL) lastSlash = fslash; *lastSlash = '\0'; } if (postfix) { if (strlcat(path, postfix, sizeof(path)/sizeof(path[0])) >= sizeof(path)/sizeof(path[0])) return EINVAL; } *ret = strdup(path); if (*ret == NULL) return krb5_enomem(context); return 0; } /* * Expand a %{USERID} token * * The %{USERID} token expands to the string representation of the * user's SID. The user account that will be used is the account * corresponding to the current thread's security token. This means * that: * * - If the current thread token has the anonymous impersonation * level, the call will fail. * * - If the current thread is impersonating a token at * SecurityIdentification level the call will fail. * */ static krb5_error_code _expand_userid(krb5_context context, PTYPE param, const char *postfix, char **ret) { int rv = EINVAL; HANDLE hThread = NULL; HANDLE hToken = NULL; PTOKEN_OWNER pOwner = NULL; DWORD len = 0; LPTSTR strSid = NULL; hThread = GetCurrentThread(); if (!OpenThreadToken(hThread, TOKEN_QUERY, FALSE, /* Open the thread token as the current thread user. */ &hToken)) { DWORD le = GetLastError(); if (le == ERROR_NO_TOKEN) { HANDLE hProcess = GetCurrentProcess(); le = 0; if (!OpenProcessToken(hProcess, TOKEN_QUERY, &hToken)) le = GetLastError(); } if (le != 0) { if (context) krb5_set_error_message(context, rv, "Can't open thread token (GLE=%d)", le); goto _exit; } } if (!GetTokenInformation(hToken, TokenOwner, NULL, 0, &len)) { if (GetLastError() != ERROR_INSUFFICIENT_BUFFER) { if (context) krb5_set_error_message(context, rv, "Unexpected error reading token information (GLE=%d)", GetLastError()); goto _exit; } if (len == 0) { if (context) krb5_set_error_message(context, rv, "GetTokenInformation() returned truncated buffer"); goto _exit; } pOwner = malloc(len); if (pOwner == NULL) { if (context) krb5_set_error_message(context, rv, "Out of memory"); goto _exit; } } else { if (context) krb5_set_error_message(context, rv, "GetTokenInformation() returned truncated buffer"); goto _exit; } if (!GetTokenInformation(hToken, TokenOwner, pOwner, len, &len)) { if (context) krb5_set_error_message(context, rv, "GetTokenInformation() failed. GLE=%d", GetLastError()); goto _exit; } if (!ConvertSidToStringSid(pOwner->Owner, &strSid)) { if (context) krb5_set_error_message(context, rv, "Can't convert SID to string. GLE=%d", GetLastError()); goto _exit; } *ret = strdup(strSid); if (*ret == NULL && context) krb5_set_error_message(context, rv, "Out of memory"); rv = 0; _exit: if (hToken != NULL) CloseHandle(hToken); if (pOwner != NULL) free (pOwner); if (strSid != NULL) LocalFree(strSid); return rv; } /* * Expand a folder identified by a CSIDL */ static krb5_error_code _expand_csidl(krb5_context context, PTYPE folder, const char *postfix, char **ret) { TCHAR path[MAX_PATH]; size_t len; if (SHGetFolderPath(NULL, folder, NULL, SHGFP_TYPE_CURRENT, path) != S_OK) { if (context) krb5_set_error_message(context, EINVAL, "Unable to determine folder path"); return EINVAL; } len = strlen(path); if (len > 0 && path[len - 1] == '\\') path[len - 1] = '\0'; if (postfix && strlcat(path, postfix, sizeof(path)/sizeof(path[0])) >= sizeof(path)/sizeof(path[0])) return krb5_enomem(context); *ret = strdup(path); if (*ret == NULL) return krb5_enomem(context); return 0; } #else static krb5_error_code _expand_path(krb5_context context, PTYPE param, const char *postfix, char **ret) { *ret = strdup(postfix); if (*ret == NULL) return krb5_enomem(context); return 0; } static krb5_error_code _expand_temp_folder(krb5_context context, PTYPE param, const char *postfix, char **ret) { const char *p = NULL; if (!issuid()) p = getenv("TEMP"); if (p) *ret = strdup(p); else *ret = strdup("/tmp"); if (*ret == NULL) return krb5_enomem(context); return 0; } static krb5_error_code _expand_userid(krb5_context context, PTYPE param, const char *postfix, char **str) { int ret = asprintf(str, "%ld", (unsigned long)getuid()); if (ret < 0 || *str == NULL) return krb5_enomem(context); return 0; } #endif /* _WIN32 */ /** * Expand an extra token */ static krb5_error_code _expand_extra_token(krb5_context context, const char *value, char **ret) { *ret = strdup(value); if (*ret == NULL) return krb5_enomem(context); return 0; } /** * Expand a %{null} token * * The expansion of a %{null} token is always the empty string. */ static krb5_error_code _expand_null(krb5_context context, PTYPE param, const char *postfix, char **ret) { *ret = strdup(""); if (*ret == NULL) return krb5_enomem(context); return 0; } static const struct { const char * tok; int ftype; #define FTYPE_CSIDL 0 #define FTYPE_SPECIAL 1 PTYPE param; const char * postfix; int (*exp_func)(krb5_context, PTYPE, const char *, char **); #define SPECIALP(f, P) FTYPE_SPECIAL, 0, P, f #define SPECIAL(f) SPECIALP(f, NULL) } tokens[] = { #ifdef _WIN32 #define CSIDLP(C,P) FTYPE_CSIDL, C, P, _expand_csidl #define CSIDL(C) CSIDLP(C, NULL) {"APPDATA", CSIDL(CSIDL_APPDATA)}, /* Roaming application data (for current user) */ {"COMMON_APPDATA", CSIDL(CSIDL_COMMON_APPDATA)}, /* Application data (all users) */ {"LOCAL_APPDATA", CSIDL(CSIDL_LOCAL_APPDATA)}, /* Local application data (for current user) */ {"SYSTEM", CSIDL(CSIDL_SYSTEM)}, /* Windows System folder (e.g. %WINDIR%\System32) */ {"WINDOWS", CSIDL(CSIDL_WINDOWS)}, /* Windows folder */ {"USERCONFIG", CSIDLP(CSIDL_APPDATA, "\\" PACKAGE)}, /* Per user Heimdal configuration file path */ {"COMMONCONFIG", CSIDLP(CSIDL_COMMON_APPDATA, "\\" PACKAGE)}, /* Common Heimdal configuration file path */ {"LIBDIR", SPECIAL(_expand_bin_dir)}, {"BINDIR", SPECIAL(_expand_bin_dir)}, {"LIBEXEC", SPECIAL(_expand_bin_dir)}, {"SBINDIR", SPECIAL(_expand_bin_dir)}, #else {"LIBDIR", FTYPE_SPECIAL, 0, LIBDIR, _expand_path}, {"BINDIR", FTYPE_SPECIAL, 0, BINDIR, _expand_path}, {"LIBEXEC", FTYPE_SPECIAL, 0, LIBEXECDIR, _expand_path}, {"SBINDIR", FTYPE_SPECIAL, 0, SBINDIR, _expand_path}, #endif {"TEMP", SPECIAL(_expand_temp_folder)}, {"USERID", SPECIAL(_expand_userid)}, {"uid", SPECIAL(_expand_userid)}, {"null", SPECIAL(_expand_null)} }; static krb5_error_code _expand_token(krb5_context context, const char *token, const char *token_end, char **extra_tokens, char **ret) { size_t i; char **p; *ret = NULL; if (token[0] != '%' || token[1] != '{' || token_end[0] != '}' || token_end - token <= 2) { if (context) krb5_set_error_message(context, EINVAL,"Invalid token."); return EINVAL; } for (p = extra_tokens; p && p[0]; p += 2) { if (strncmp(token+2, p[0], (token_end - token) - 2) == 0) return _expand_extra_token(context, p[1], ret); } for (i = 0; i < sizeof(tokens)/sizeof(tokens[0]); i++) { if (!strncmp(token+2, tokens[i].tok, (token_end - token) - 2)) return tokens[i].exp_func(context, tokens[i].param, tokens[i].postfix, ret); } if (context) krb5_set_error_message(context, EINVAL, "Invalid token."); return EINVAL; } /** * Internal function to expand tokens in paths. * * Inputs: * * @context A krb5_context * @path_in The path to expand tokens from * * Outputs: * * @ppath_out Path with expanded tokens (caller must free() this) */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL _krb5_expand_path_tokens(krb5_context context, const char *path_in, int filepath, char **ppath_out) { return _krb5_expand_path_tokensv(context, path_in, filepath, ppath_out, NULL); } static void free_extra_tokens(char **extra_tokens) { char **p; for (p = extra_tokens; p && *p; p++) free(*p); free(extra_tokens); } /** * Internal function to expand tokens in paths. * * Inputs: * * @context A krb5_context * @path_in The path to expand tokens from * @ppath_out The expanded path * @... Variable number of pairs of strings, the first of each * being a token (e.g., "luser") and the second a string to * replace it with. The list is terminated by a NULL. * * Outputs: * * @ppath_out Path with expanded tokens (caller must free() this) */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL _krb5_expand_path_tokensv(krb5_context context, const char *path_in, int filepath, char **ppath_out, ...) { char *tok_begin, *tok_end, *append; char **extra_tokens = NULL; const char *path_left; size_t nargs = 0; size_t len = 0; va_list ap; if (path_in == NULL || *path_in == '\0') { *ppath_out = strdup(""); return 0; } *ppath_out = NULL; va_start(ap, ppath_out); while (va_arg(ap, const char *)) { nargs++; va_arg(ap, const char *); } va_end(ap); nargs *= 2; /* Get extra tokens */ if (nargs) { size_t i; extra_tokens = calloc(nargs + 1, sizeof (*extra_tokens)); if (extra_tokens == NULL) return krb5_enomem(context); va_start(ap, ppath_out); for (i = 0; i < nargs; i++) { const char *s = va_arg(ap, const char *); /* token key */ if (s == NULL) break; extra_tokens[i] = strdup(s); if (extra_tokens[i++] == NULL) { va_end(ap); free_extra_tokens(extra_tokens); return krb5_enomem(context); } s = va_arg(ap, const char *); /* token value */ if (s == NULL) s = ""; extra_tokens[i] = strdup(s); if (extra_tokens[i] == NULL) { va_end(ap); free_extra_tokens(extra_tokens); return krb5_enomem(context); } } va_end(ap); } for (path_left = path_in; path_left && *path_left; ) { tok_begin = strstr(path_left, "%{"); if (tok_begin && tok_begin != path_left) { append = malloc((tok_begin - path_left) + 1); if (append) { memcpy(append, path_left, tok_begin - path_left); append[tok_begin - path_left] = '\0'; } path_left = tok_begin; } else if (tok_begin) { tok_end = strchr(tok_begin, '}'); if (tok_end == NULL) { free_extra_tokens(extra_tokens); if (*ppath_out) free(*ppath_out); *ppath_out = NULL; if (context) krb5_set_error_message(context, EINVAL, "variable missing }"); return EINVAL; } if (_expand_token(context, tok_begin, tok_end, extra_tokens, &append)) { free_extra_tokens(extra_tokens); if (*ppath_out) free(*ppath_out); *ppath_out = NULL; return EINVAL; } path_left = tok_end + 1; } else { append = strdup(path_left); path_left = NULL; } if (append == NULL) { free_extra_tokens(extra_tokens); if (*ppath_out) free(*ppath_out); *ppath_out = NULL; return krb5_enomem(context); } { size_t append_len = strlen(append); char * new_str = realloc(*ppath_out, len + append_len + 1); if (new_str == NULL) { free_extra_tokens(extra_tokens); free(append); if (*ppath_out) free(*ppath_out); *ppath_out = NULL; return krb5_enomem(context); } *ppath_out = new_str; memcpy(*ppath_out + len, append, append_len + 1); len = len + append_len; free(append); } } #ifdef _WIN32 /* Also deal with slashes */ if (filepath && *ppath_out) { char * c; for (c = *ppath_out; *c; c++) if (*c == '/') *c = '\\'; } #endif free_extra_tokens(extra_tokens); return 0; } heimdal-7.5.0/lib/krb5/rd_req.c0000644000175000017500000006306013026237312014307 0ustar niknik /* * Copyright (c) 1997 - 2007 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "krb5_locl.h" static krb5_error_code decrypt_tkt_enc_part (krb5_context context, krb5_keyblock *key, EncryptedData *enc_part, EncTicketPart *decr_part) { krb5_error_code ret; krb5_data plain; size_t len; krb5_crypto crypto; ret = krb5_crypto_init(context, key, 0, &crypto); if (ret) return ret; ret = krb5_decrypt_EncryptedData (context, crypto, KRB5_KU_TICKET, enc_part, &plain); krb5_crypto_destroy(context, crypto); if (ret) return ret; ret = decode_EncTicketPart(plain.data, plain.length, decr_part, &len); if (ret) krb5_set_error_message(context, ret, N_("Failed to decode encrypted " "ticket part", "")); krb5_data_free (&plain); return ret; } static krb5_error_code decrypt_authenticator (krb5_context context, EncryptionKey *key, EncryptedData *enc_part, Authenticator *authenticator, krb5_key_usage usage) { krb5_error_code ret; krb5_data plain; size_t len; krb5_crypto crypto; ret = krb5_crypto_init(context, key, 0, &crypto); if (ret) return ret; ret = krb5_decrypt_EncryptedData (context, crypto, usage /* KRB5_KU_AP_REQ_AUTH */, enc_part, &plain); /* for backwards compatibility, also try the old usage */ if (ret && usage == KRB5_KU_TGS_REQ_AUTH) ret = krb5_decrypt_EncryptedData (context, crypto, KRB5_KU_AP_REQ_AUTH, enc_part, &plain); krb5_crypto_destroy(context, crypto); if (ret) return ret; ret = decode_Authenticator(plain.data, plain.length, authenticator, &len); krb5_data_free (&plain); return ret; } KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_decode_ap_req(krb5_context context, const krb5_data *inbuf, krb5_ap_req *ap_req) { krb5_error_code ret; size_t len; ret = decode_AP_REQ(inbuf->data, inbuf->length, ap_req, &len); if (ret) return ret; if (ap_req->pvno != 5){ free_AP_REQ(ap_req); krb5_clear_error_message (context); return KRB5KRB_AP_ERR_BADVERSION; } if (ap_req->msg_type != krb_ap_req){ free_AP_REQ(ap_req); krb5_clear_error_message (context); return KRB5KRB_AP_ERR_MSG_TYPE; } if (ap_req->ticket.tkt_vno != 5){ free_AP_REQ(ap_req); krb5_clear_error_message (context); return KRB5KRB_AP_ERR_BADVERSION; } return 0; } static krb5_error_code check_transited(krb5_context context, Ticket *ticket, EncTicketPart *enc) { char **realms; unsigned int num_realms, n; krb5_error_code ret; /* * Windows 2000 and 2003 uses this inside their TGT so it's normaly * not seen by others, however, samba4 joined with a Windows AD as * a Domain Controller gets exposed to this. */ if(enc->transited.tr_type == 0 && enc->transited.contents.length == 0) return 0; if(enc->transited.tr_type != DOMAIN_X500_COMPRESS) return KRB5KDC_ERR_TRTYPE_NOSUPP; if(enc->transited.contents.length == 0) return 0; ret = krb5_domain_x500_decode(context, enc->transited.contents, &realms, &num_realms, enc->crealm, ticket->realm); if(ret) return ret; ret = krb5_check_transited(context, enc->crealm, ticket->realm, realms, num_realms, NULL); for (n = 0; n < num_realms; n++) free(realms[n]); free(realms); return ret; } static krb5_error_code find_etypelist(krb5_context context, krb5_auth_context auth_context, EtypeList *etypes) { krb5_error_code ret; krb5_data data; ret = _krb5_get_ad(context, auth_context->authenticator->authorization_data, NULL, KRB5_AUTHDATA_GSS_API_ETYPE_NEGOTIATION, &data); if (ret) return 0; ret = decode_EtypeList(data.data, data.length, etypes, NULL); krb5_data_free(&data); if (ret) krb5_clear_error_message(context); return ret; } KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_decrypt_ticket(krb5_context context, Ticket *ticket, krb5_keyblock *key, EncTicketPart *out, krb5_flags flags) { EncTicketPart t; krb5_error_code ret; ret = decrypt_tkt_enc_part (context, key, &ticket->enc_part, &t); if (ret) return ret; { krb5_timestamp now; time_t start = t.authtime; krb5_timeofday (context, &now); if(t.starttime) start = *t.starttime; if(start - now > context->max_skew || (t.flags.invalid && !(flags & KRB5_VERIFY_AP_REQ_IGNORE_INVALID))) { free_EncTicketPart(&t); krb5_clear_error_message (context); return KRB5KRB_AP_ERR_TKT_NYV; } if(now - t.endtime > context->max_skew) { free_EncTicketPart(&t); krb5_clear_error_message (context); return KRB5KRB_AP_ERR_TKT_EXPIRED; } if(!t.flags.transited_policy_checked) { ret = check_transited(context, ticket, &t); if(ret) { free_EncTicketPart(&t); return ret; } } } if(out) *out = t; else free_EncTicketPart(&t); return 0; } KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_verify_authenticator_checksum(krb5_context context, krb5_auth_context ac, void *data, size_t len) { krb5_error_code ret; krb5_keyblock *key = NULL; krb5_authenticator authenticator; krb5_crypto crypto; ret = krb5_auth_con_getauthenticator(context, ac, &authenticator); if (ret) return ret; if (authenticator->cksum == NULL) { ret = -17; goto out; } ret = krb5_auth_con_getkey(context, ac, &key); if (ret) goto out; ret = krb5_crypto_init(context, key, 0, &crypto); if (ret) goto out; ret = krb5_verify_checksum(context, crypto, KRB5_KU_AP_REQ_AUTH_CKSUM, data, len, authenticator->cksum); krb5_crypto_destroy(context, crypto); out: krb5_free_authenticator(context, &authenticator); krb5_free_keyblock(context, key); return ret; } KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_verify_ap_req(krb5_context context, krb5_auth_context *auth_context, krb5_ap_req *ap_req, krb5_const_principal server, krb5_keyblock *keyblock, krb5_flags flags, krb5_flags *ap_req_options, krb5_ticket **ticket) { return krb5_verify_ap_req2 (context, auth_context, ap_req, server, keyblock, flags, ap_req_options, ticket, KRB5_KU_AP_REQ_AUTH); } KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_verify_ap_req2(krb5_context context, krb5_auth_context *auth_context, krb5_ap_req *ap_req, krb5_const_principal server, krb5_keyblock *keyblock, krb5_flags flags, krb5_flags *ap_req_options, krb5_ticket **ticket, krb5_key_usage usage) { krb5_ticket *t; krb5_auth_context ac; krb5_error_code ret; EtypeList etypes; memset(&etypes, 0, sizeof(etypes)); if (ticket) *ticket = NULL; if (auth_context && *auth_context) { ac = *auth_context; } else { ret = krb5_auth_con_init (context, &ac); if (ret) return ret; } t = calloc(1, sizeof(*t)); if (t == NULL) { ret = krb5_enomem(context); goto out; } if (ap_req->ap_options.use_session_key && ac->keyblock){ ret = krb5_decrypt_ticket(context, &ap_req->ticket, ac->keyblock, &t->ticket, flags); krb5_free_keyblock(context, ac->keyblock); ac->keyblock = NULL; }else ret = krb5_decrypt_ticket(context, &ap_req->ticket, keyblock, &t->ticket, flags); if(ret) goto out; ret = _krb5_principalname2krb5_principal(context, &t->server, ap_req->ticket.sname, ap_req->ticket.realm); if (ret) goto out; ret = _krb5_principalname2krb5_principal(context, &t->client, t->ticket.cname, t->ticket.crealm); if (ret) goto out; ret = decrypt_authenticator (context, &t->ticket.key, &ap_req->authenticator, ac->authenticator, usage); if (ret) goto out; { krb5_principal p1, p2; krb5_boolean res; _krb5_principalname2krb5_principal(context, &p1, ac->authenticator->cname, ac->authenticator->crealm); _krb5_principalname2krb5_principal(context, &p2, t->ticket.cname, t->ticket.crealm); res = krb5_principal_compare (context, p1, p2); krb5_free_principal (context, p1); krb5_free_principal (context, p2); if (!res) { ret = KRB5KRB_AP_ERR_BADMATCH; krb5_clear_error_message (context); goto out; } } /* check addresses */ if (t->ticket.caddr && ac->remote_address && !krb5_address_search (context, ac->remote_address, t->ticket.caddr)) { ret = KRB5KRB_AP_ERR_BADADDR; krb5_clear_error_message (context); goto out; } /* check timestamp in authenticator */ { krb5_timestamp now; krb5_timeofday (context, &now); if (labs(ac->authenticator->ctime - now) > context->max_skew) { ret = KRB5KRB_AP_ERR_SKEW; krb5_clear_error_message (context); goto out; } } if (ac->authenticator->seq_number) krb5_auth_con_setremoteseqnumber(context, ac, *ac->authenticator->seq_number); /* XXX - Xor sequence numbers */ if (ac->authenticator->subkey) { ret = krb5_auth_con_setremotesubkey(context, ac, ac->authenticator->subkey); if (ret) goto out; } ret = find_etypelist(context, ac, &etypes); if (ret) goto out; ac->keytype = ETYPE_NULL; if (etypes.val) { size_t i; for (i = 0; i < etypes.len; i++) { if (krb5_enctype_valid(context, etypes.val[i]) == 0) { ac->keytype = etypes.val[i]; break; } } } /* save key */ ret = krb5_copy_keyblock(context, &t->ticket.key, &ac->keyblock); if (ret) goto out; if (ap_req_options) { *ap_req_options = 0; if (ac->keytype != (krb5_enctype)ETYPE_NULL) *ap_req_options |= AP_OPTS_USE_SUBKEY; if (ap_req->ap_options.use_session_key) *ap_req_options |= AP_OPTS_USE_SESSION_KEY; if (ap_req->ap_options.mutual_required) *ap_req_options |= AP_OPTS_MUTUAL_REQUIRED; } if(ticket) *ticket = t; else krb5_free_ticket (context, t); if (auth_context) { if (*auth_context == NULL) *auth_context = ac; } else krb5_auth_con_free (context, ac); free_EtypeList(&etypes); return 0; out: free_EtypeList(&etypes); if (t) krb5_free_ticket (context, t); if (auth_context == NULL || *auth_context == NULL) krb5_auth_con_free (context, ac); return ret; } /* * */ struct krb5_rd_req_in_ctx_data { krb5_keytab keytab; krb5_keyblock *keyblock; krb5_boolean check_pac; }; struct krb5_rd_req_out_ctx_data { krb5_keyblock *keyblock; krb5_flags ap_req_options; krb5_ticket *ticket; krb5_principal server; }; /** * Allocate a krb5_rd_req_in_ctx as an input parameter to * krb5_rd_req_ctx(). The caller should free the context with * krb5_rd_req_in_ctx_free() when done with the context. * * @param context Keberos 5 context. * @param ctx in ctx to krb5_rd_req_ctx(). * * @return Kerberos 5 error code, see krb5_get_error_message(). * * @ingroup krb5_auth */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_rd_req_in_ctx_alloc(krb5_context context, krb5_rd_req_in_ctx *ctx) { *ctx = calloc(1, sizeof(**ctx)); if (*ctx == NULL) return krb5_enomem(context); (*ctx)->check_pac = (context->flags & KRB5_CTX_F_CHECK_PAC) ? 1 : 0; return 0; } /** * Set the keytab that krb5_rd_req_ctx() will use. * * @param context Keberos 5 context. * @param in in ctx to krb5_rd_req_ctx(). * @param keytab keytab that krb5_rd_req_ctx() will use, only copy the * pointer, so the caller must free they keytab after * krb5_rd_req_in_ctx_free() is called. * * @return Kerberos 5 error code, see krb5_get_error_message(). * * @ingroup krb5_auth */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_rd_req_in_set_keytab(krb5_context context, krb5_rd_req_in_ctx in, krb5_keytab keytab) { in->keytab = keytab; return 0; } /** * Set if krb5_rq_red() is going to check the Windows PAC or not * * @param context Keberos 5 context. * @param in krb5_rd_req_in_ctx to check the option on. * @param flag flag to select if to check the pac (TRUE) or not (FALSE). * * @return Kerberos 5 error code, see krb5_get_error_message(). * * @ingroup krb5_auth */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_rd_req_in_set_pac_check(krb5_context context, krb5_rd_req_in_ctx in, krb5_boolean flag) { in->check_pac = flag; return 0; } KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_rd_req_in_set_keyblock(krb5_context context, krb5_rd_req_in_ctx in, krb5_keyblock *keyblock) { in->keyblock = keyblock; /* XXX should make copy */ return 0; } KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_rd_req_out_get_ap_req_options(krb5_context context, krb5_rd_req_out_ctx out, krb5_flags *ap_req_options) { *ap_req_options = out->ap_req_options; return 0; } KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_rd_req_out_get_ticket(krb5_context context, krb5_rd_req_out_ctx out, krb5_ticket **ticket) { return krb5_copy_ticket(context, out->ticket, ticket); } KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_rd_req_out_get_keyblock(krb5_context context, krb5_rd_req_out_ctx out, krb5_keyblock **keyblock) { return krb5_copy_keyblock(context, out->keyblock, keyblock); } /** * Get the principal that was used in the request from the * client. Might not match whats in the ticket if krb5_rd_req_ctx() * searched in the keytab for a matching key. * * @param context a Kerberos 5 context. * @param out a krb5_rd_req_out_ctx from krb5_rd_req_ctx(). * @param principal return principal, free with krb5_free_principal(). * * @ingroup krb5_auth */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_rd_req_out_get_server(krb5_context context, krb5_rd_req_out_ctx out, krb5_principal *principal) { return krb5_copy_principal(context, out->server, principal); } KRB5_LIB_FUNCTION void KRB5_LIB_CALL krb5_rd_req_in_ctx_free(krb5_context context, krb5_rd_req_in_ctx ctx) { free(ctx); } /** * Free the krb5_rd_req_out_ctx. * * @param context Keberos 5 context. * @param ctx krb5_rd_req_out_ctx context to free. * * @ingroup krb5_auth */ KRB5_LIB_FUNCTION void KRB5_LIB_CALL krb5_rd_req_out_ctx_free(krb5_context context, krb5_rd_req_out_ctx ctx) { if (ctx->ticket) krb5_free_ticket(context, ctx->ticket); if (ctx->keyblock) krb5_free_keyblock(context, ctx->keyblock); if (ctx->server) krb5_free_principal(context, ctx->server); free(ctx); } /** * Process an AP_REQ message. * * @param context Kerberos 5 context. * @param auth_context authentication context of the peer. * @param inbuf the AP_REQ message, obtained for example with krb5_read_message(). * @param server server principal. * @param keytab server keytab. * @param ap_req_options set to the AP_REQ options. See the AP_OPTS_* defines. * @param ticket on success, set to the authenticated client credentials. * Must be deallocated with krb5_free_ticket(). If not * interested, pass a NULL value. * * @return 0 to indicate success. Otherwise a Kerberos error code is * returned, see krb5_get_error_message(). */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_rd_req(krb5_context context, krb5_auth_context *auth_context, const krb5_data *inbuf, krb5_const_principal server, krb5_keytab keytab, krb5_flags *ap_req_options, krb5_ticket **ticket) { krb5_error_code ret; krb5_rd_req_in_ctx in; krb5_rd_req_out_ctx out; ret = krb5_rd_req_in_ctx_alloc(context, &in); if (ret) return ret; ret = krb5_rd_req_in_set_keytab(context, in, keytab); if (ret) { krb5_rd_req_in_ctx_free(context, in); return ret; } ret = krb5_rd_req_ctx(context, auth_context, inbuf, server, in, &out); krb5_rd_req_in_ctx_free(context, in); if (ret) return ret; if (ap_req_options) *ap_req_options = out->ap_req_options; if (ticket) { ret = krb5_copy_ticket(context, out->ticket, ticket); if (ret) goto out; } out: krb5_rd_req_out_ctx_free(context, out); return ret; } /* * */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_rd_req_with_keyblock(krb5_context context, krb5_auth_context *auth_context, const krb5_data *inbuf, krb5_const_principal server, krb5_keyblock *keyblock, krb5_flags *ap_req_options, krb5_ticket **ticket) { krb5_error_code ret; krb5_rd_req_in_ctx in; krb5_rd_req_out_ctx out; ret = krb5_rd_req_in_ctx_alloc(context, &in); if (ret) return ret; ret = krb5_rd_req_in_set_keyblock(context, in, keyblock); if (ret) { krb5_rd_req_in_ctx_free(context, in); return ret; } ret = krb5_rd_req_ctx(context, auth_context, inbuf, server, in, &out); krb5_rd_req_in_ctx_free(context, in); if (ret) return ret; if (ap_req_options) *ap_req_options = out->ap_req_options; if (ticket) { ret = krb5_copy_ticket(context, out->ticket, ticket); if (ret) goto out; } out: krb5_rd_req_out_ctx_free(context, out); return ret; } /* * */ static krb5_error_code get_key_from_keytab(krb5_context context, krb5_ap_req *ap_req, krb5_const_principal server, krb5_keytab keytab, krb5_keyblock **out_key) { krb5_keytab_entry entry; krb5_error_code ret; int kvno; krb5_keytab real_keytab; if(keytab == NULL) krb5_kt_default(context, &real_keytab); else real_keytab = keytab; if (ap_req->ticket.enc_part.kvno) kvno = *ap_req->ticket.enc_part.kvno; else kvno = 0; ret = krb5_kt_get_entry (context, real_keytab, server, kvno, ap_req->ticket.enc_part.etype, &entry); if(ret) goto out; ret = krb5_copy_keyblock(context, &entry.keyblock, out_key); krb5_kt_free_entry (context, &entry); out: if(keytab == NULL) krb5_kt_close(context, real_keytab); return ret; } /** * The core server function that verify application authentication * requests from clients. * * @param context Keberos 5 context. * @param auth_context the authentication context, can be NULL, then * default values for the authentication context will used. * @param inbuf the (AP-REQ) authentication buffer * * @param server the server to authenticate to. If NULL the function * will try to find any available credential in the keytab * that will verify the reply. The function will prefer the * server specified in the AP-REQ, but if * there is no mach, it will try all keytab entries for a * match. This has serious performance issues for large keytabs. * * @param inctx control the behavior of the function, if NULL, the * default behavior is used. * @param outctx the return outctx, free with krb5_rd_req_out_ctx_free(). * @return Kerberos 5 error code, see krb5_get_error_message(). * * @ingroup krb5_auth */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_rd_req_ctx(krb5_context context, krb5_auth_context *auth_context, const krb5_data *inbuf, krb5_const_principal server, krb5_rd_req_in_ctx inctx, krb5_rd_req_out_ctx *outctx) { krb5_error_code ret; krb5_ap_req ap_req; krb5_rd_req_out_ctx o = NULL; krb5_keytab id = NULL, keytab = NULL; krb5_principal service = NULL; *outctx = NULL; o = calloc(1, sizeof(*o)); if (o == NULL) return krb5_enomem(context); if (*auth_context == NULL) { ret = krb5_auth_con_init(context, auth_context); if (ret) goto out; } ret = krb5_decode_ap_req(context, inbuf, &ap_req); if(ret) goto out; /* Save the principal that was in the request */ ret = _krb5_principalname2krb5_principal(context, &o->server, ap_req.ticket.sname, ap_req.ticket.realm); if (ret) goto out; if (ap_req.ap_options.use_session_key && (*auth_context)->keyblock == NULL) { ret = KRB5KRB_AP_ERR_NOKEY; krb5_set_error_message(context, ret, N_("krb5_rd_req: user to user auth " "without session key given", "")); goto out; } if (inctx && inctx->keytab) id = inctx->keytab; if((*auth_context)->keyblock){ ret = krb5_copy_keyblock(context, (*auth_context)->keyblock, &o->keyblock); if (ret) goto out; } else if(inctx && inctx->keyblock){ ret = krb5_copy_keyblock(context, inctx->keyblock, &o->keyblock); if (ret) goto out; } else { if(id == NULL) { krb5_kt_default(context, &keytab); id = keytab; } if (id == NULL) goto out; if (server == NULL) { ret = _krb5_principalname2krb5_principal(context, &service, ap_req.ticket.sname, ap_req.ticket.realm); if (ret) goto out; server = service; } ret = get_key_from_keytab(context, &ap_req, server, id, &o->keyblock); if (ret) { /* If caller specified a server, fail. */ if (service == NULL && (context->flags & KRB5_CTX_F_RD_REQ_IGNORE) == 0) goto out; /* Otherwise, fall back to iterating over the keytab. This * have serious performace issues for larger keytab. */ o->keyblock = NULL; } } if (o->keyblock) { /* * We got an exact keymatch, use that. */ ret = krb5_verify_ap_req2(context, auth_context, &ap_req, server, o->keyblock, 0, &o->ap_req_options, &o->ticket, KRB5_KU_AP_REQ_AUTH); if (ret) goto out; } else { /* * Interate over keytab to find a key that can decrypt the request. */ krb5_keytab_entry entry; krb5_kt_cursor cursor; int done = 0, kvno = 0; memset(&cursor, 0, sizeof(cursor)); if (ap_req.ticket.enc_part.kvno) kvno = *ap_req.ticket.enc_part.kvno; ret = krb5_kt_start_seq_get(context, id, &cursor); if (ret) goto out; done = 0; while (!done) { krb5_principal p; ret = krb5_kt_next_entry(context, id, &entry, &cursor); if (ret) { _krb5_kt_principal_not_found(context, ret, id, o->server, ap_req.ticket.enc_part.etype, kvno); break; } if (entry.keyblock.keytype != ap_req.ticket.enc_part.etype) { krb5_kt_free_entry (context, &entry); continue; } ret = krb5_verify_ap_req2(context, auth_context, &ap_req, server, &entry.keyblock, 0, &o->ap_req_options, &o->ticket, KRB5_KU_AP_REQ_AUTH); if (ret) { krb5_kt_free_entry (context, &entry); continue; } /* * Found a match, save the keyblock for PAC processing, * and update the service principal in the ticket to match * whatever is in the keytab. */ ret = krb5_copy_keyblock(context, &entry.keyblock, &o->keyblock); if (ret) { krb5_kt_free_entry (context, &entry); break; } ret = krb5_copy_principal(context, entry.principal, &p); if (ret) { krb5_kt_free_entry (context, &entry); break; } krb5_free_principal(context, o->ticket->server); o->ticket->server = p; krb5_kt_free_entry (context, &entry); done = 1; } krb5_kt_end_seq_get (context, id, &cursor); if (ret) goto out; } /* If there is a PAC, verify its server signature */ if (inctx == NULL || inctx->check_pac) { krb5_pac pac; krb5_data data; ret = krb5_ticket_get_authorization_data_type(context, o->ticket, KRB5_AUTHDATA_WIN2K_PAC, &data); if (ret == 0) { ret = krb5_pac_parse(context, data.data, data.length, &pac); krb5_data_free(&data); if (ret) goto out; ret = krb5_pac_verify(context, pac, o->ticket->ticket.authtime, o->ticket->client, o->keyblock, NULL); krb5_pac_free(context, pac); if (ret) goto out; } else ret = 0; } out: if (ret || outctx == NULL) { krb5_rd_req_out_ctx_free(context, o); } else *outctx = o; free_AP_REQ(&ap_req); if (service) krb5_free_principal(context, service); if (keytab) krb5_kt_close(context, keytab); return ret; } heimdal-7.5.0/lib/krb5/read_message.c0000644000175000017500000000634112136107750015454 0ustar niknik/* * Copyright (c) 1997 - 2001 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "krb5_locl.h" KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_read_message (krb5_context context, krb5_pointer p_fd, krb5_data *data) { krb5_error_code ret; uint32_t len; uint8_t buf[4]; krb5_data_zero(data); ret = krb5_net_read (context, p_fd, buf, 4); if(ret == -1) { ret = errno; krb5_clear_error_message (context); return ret; } if(ret < 4) { krb5_clear_error_message(context); return HEIM_ERR_EOF; } len = (buf[0] << 24) | (buf[1] << 16) | (buf[2] << 8) | buf[3]; ret = krb5_data_alloc (data, len); if (ret) { krb5_clear_error_message(context); return ret; } if (krb5_net_read (context, p_fd, data->data, len) != len) { ret = errno; krb5_data_free (data); krb5_clear_error_message (context); return ret; } return 0; } KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_read_priv_message(krb5_context context, krb5_auth_context ac, krb5_pointer p_fd, krb5_data *data) { krb5_error_code ret; krb5_data packet; ret = krb5_read_message(context, p_fd, &packet); if(ret) return ret; ret = krb5_rd_priv (context, ac, &packet, data, NULL); krb5_data_free(&packet); return ret; } KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_read_safe_message(krb5_context context, krb5_auth_context ac, krb5_pointer p_fd, krb5_data *data) { krb5_error_code ret; krb5_data packet; ret = krb5_read_message(context, p_fd, &packet); if(ret) return ret; ret = krb5_rd_safe (context, ac, &packet, data, NULL); krb5_data_free(&packet); return ret; } heimdal-7.5.0/lib/krb5/krb524_convert_creds_kdc.cat30000644000175000017500000000473113212450756020223 0ustar niknik KRB524_CONVERT_CREDS_... BSD Library Functions Manual KRB524_CONVERT_CREDS_... NNAAMMEE kkrrbb552244__ccoonnvveerrtt__ccrreeddss__kkddcc, kkrrbb552244__ccoonnvveerrtt__ccrreeddss__kkddcc__ccccaacchhee -- converts Kerberos 5 credentials to Kerberos 4 credentials LLIIBBRRAARRYY Kerberos 5 Library (libkrb5, -lkrb5) SSYYNNOOPPSSIISS ##iinncclluuddee <> _k_r_b_5___e_r_r_o_r___c_o_d_e kkrrbb552244__ccoonnvveerrtt__ccrreeddss__kkddcc(_k_r_b_5___c_o_n_t_e_x_t _c_o_n_t_e_x_t, _k_r_b_5___c_r_e_d_s _*_i_n___c_r_e_d, _s_t_r_u_c_t _c_r_e_d_e_n_t_i_a_l_s _*_v_4_c_r_e_d_s); _k_r_b_5___e_r_r_o_r___c_o_d_e kkrrbb552244__ccoonnvveerrtt__ccrreeddss__kkddcc__ccccaacchhee(_k_r_b_5___c_o_n_t_e_x_t _c_o_n_t_e_x_t, _k_r_b_5___c_c_a_c_h_e _c_c_a_c_h_e, _k_r_b_5___c_r_e_d_s _*_i_n___c_r_e_d, _s_t_r_u_c_t _c_r_e_d_e_n_t_i_a_l_s _*_v_4_c_r_e_d_s); DDEESSCCRRIIPPTTIIOONN Convert the Kerberos 5 credential to Kerberos 4 credential. This is done by sending them to the 524 service in the KDC. kkrrbb552244__ccoonnvveerrtt__ccrreeddss__kkddcc() converts the Kerberos 5 credential in _i_n___c_r_e_d to Kerberos 4 credential that is stored in _c_r_e_d_e_n_t_i_a_l_s. kkrrbb552244__ccoonnvveerrtt__ccrreeddss__kkddcc__ccccaacchhee() is different from kkrrbb552244__ccoonnvveerrtt__ccrreeddss__kkddcc() in that way that if _i_n___c_r_e_d doesn't contain a DES session key, then a new one is fetched from the KDC and stored in the cred cache _c_c_a_c_h_e, and then the KDC is queried to convert the credential. This interfaces are used to make the migration to Kerberos 5 from Ker- beros 4 easier. There are few services that still need Kerberos 4, and this is mainly for compatibility for those services. Some services, like AFS, really have Kerberos 5 supports, but still uses the 524 interface to make the migration easier. SSEEEE AALLSSOO krb5(3), krb5.conf(5) HEIMDAL March 20, 2004 HEIMDAL heimdal-7.5.0/lib/krb5/replay.c0000644000175000017500000002031013026237312014316 0ustar niknik/* * Copyright (c) 1997-2001 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "krb5_locl.h" #include struct krb5_rcache_data { char *name; }; KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_rc_resolve(krb5_context context, krb5_rcache id, const char *name) { id->name = strdup(name); if(id->name == NULL) { krb5_set_error_message(context, KRB5_RC_MALLOC, N_("malloc: out of memory", "")); return KRB5_RC_MALLOC; } return 0; } KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_rc_resolve_type(krb5_context context, krb5_rcache *id, const char *type) { *id = NULL; if(strcmp(type, "FILE")) { krb5_set_error_message (context, KRB5_RC_TYPE_NOTFOUND, N_("replay cache type %s not supported", ""), type); return KRB5_RC_TYPE_NOTFOUND; } *id = calloc(1, sizeof(**id)); if(*id == NULL) { krb5_set_error_message(context, KRB5_RC_MALLOC, N_("malloc: out of memory", "")); return KRB5_RC_MALLOC; } return 0; } KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_rc_resolve_full(krb5_context context, krb5_rcache *id, const char *string_name) { krb5_error_code ret; *id = NULL; if(strncmp(string_name, "FILE:", 5)) { krb5_set_error_message(context, KRB5_RC_TYPE_NOTFOUND, N_("replay cache type %s not supported", ""), string_name); return KRB5_RC_TYPE_NOTFOUND; } ret = krb5_rc_resolve_type(context, id, "FILE"); if(ret) return ret; ret = krb5_rc_resolve(context, *id, string_name + 5); if (ret) { krb5_rc_close(context, *id); *id = NULL; } return ret; } KRB5_LIB_FUNCTION const char* KRB5_LIB_CALL krb5_rc_default_name(krb5_context context) { return "FILE:/var/run/default_rcache"; } KRB5_LIB_FUNCTION const char* KRB5_LIB_CALL krb5_rc_default_type(krb5_context context) { return "FILE"; } KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_rc_default(krb5_context context, krb5_rcache *id) { return krb5_rc_resolve_full(context, id, krb5_rc_default_name(context)); } struct rc_entry{ time_t stamp; unsigned char data[16]; }; KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_rc_initialize(krb5_context context, krb5_rcache id, krb5_deltat auth_lifespan) { FILE *f = fopen(id->name, "w"); struct rc_entry tmp; int ret; if(f == NULL) { char buf[128]; ret = errno; rk_strerror_r(ret, buf, sizeof(buf)); krb5_set_error_message(context, ret, "open(%s): %s", id->name, buf); return ret; } memset(&tmp, 0, sizeof(tmp)); tmp.stamp = auth_lifespan; fwrite(&tmp, 1, sizeof(tmp), f); fclose(f); return 0; } KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_rc_recover(krb5_context context, krb5_rcache id) { return 0; } KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_rc_destroy(krb5_context context, krb5_rcache id) { int ret; if(remove(id->name) < 0) { char buf[128]; ret = errno; rk_strerror_r(ret, buf, sizeof(buf)); krb5_set_error_message(context, ret, "remove(%s): %s", id->name, buf); return ret; } return krb5_rc_close(context, id); } KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_rc_close(krb5_context context, krb5_rcache id) { free(id->name); free(id); return 0; } static void checksum_authenticator(Authenticator *auth, void *data) { EVP_MD_CTX *m = EVP_MD_CTX_create(); unsigned i; EVP_DigestInit_ex(m, EVP_md5(), NULL); EVP_DigestUpdate(m, auth->crealm, strlen(auth->crealm)); for(i = 0; i < auth->cname.name_string.len; i++) EVP_DigestUpdate(m, auth->cname.name_string.val[i], strlen(auth->cname.name_string.val[i])); EVP_DigestUpdate(m, &auth->ctime, sizeof(auth->ctime)); EVP_DigestUpdate(m, &auth->cusec, sizeof(auth->cusec)); EVP_DigestFinal_ex(m, data, NULL); EVP_MD_CTX_destroy(m); } KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_rc_store(krb5_context context, krb5_rcache id, krb5_donot_replay *rep) { struct rc_entry ent, tmp; time_t t; FILE *f; int ret; size_t count; ent.stamp = time(NULL); checksum_authenticator(rep, ent.data); f = fopen(id->name, "r"); if(f == NULL) { char buf[128]; ret = errno; rk_strerror_r(ret, buf, sizeof(buf)); krb5_set_error_message(context, ret, "open(%s): %s", id->name, buf); return ret; } rk_cloexec_file(f); count = fread(&tmp, sizeof(ent), 1, f); if(count != 1) return KRB5_RC_IO_UNKNOWN; t = ent.stamp - tmp.stamp; while(fread(&tmp, sizeof(ent), 1, f)){ if(tmp.stamp < t) continue; if(memcmp(tmp.data, ent.data, sizeof(ent.data)) == 0){ fclose(f); krb5_clear_error_message (context); return KRB5_RC_REPLAY; } } if(ferror(f)){ char buf[128]; ret = errno; fclose(f); rk_strerror_r(ret, buf, sizeof(buf)); krb5_set_error_message(context, ret, "%s: %s", id->name, buf); return ret; } fclose(f); f = fopen(id->name, "a"); if(f == NULL) { char buf[128]; rk_strerror_r(errno, buf, sizeof(buf)); krb5_set_error_message(context, KRB5_RC_IO_UNKNOWN, "open(%s): %s", id->name, buf); return KRB5_RC_IO_UNKNOWN; } fwrite(&ent, 1, sizeof(ent), f); fclose(f); return 0; } KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_rc_expunge(krb5_context context, krb5_rcache id) { return 0; } KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_rc_get_lifespan(krb5_context context, krb5_rcache id, krb5_deltat *auth_lifespan) { FILE *f = fopen(id->name, "r"); int r; struct rc_entry ent; r = fread(&ent, sizeof(ent), 1, f); fclose(f); if(r){ *auth_lifespan = ent.stamp; return 0; } krb5_clear_error_message (context); return KRB5_RC_IO_UNKNOWN; } KRB5_LIB_FUNCTION const char* KRB5_LIB_CALL krb5_rc_get_name(krb5_context context, krb5_rcache id) { return id->name; } KRB5_LIB_FUNCTION const char* KRB5_LIB_CALL krb5_rc_get_type(krb5_context context, krb5_rcache id) { return "FILE"; } KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_get_server_rcache(krb5_context context, const krb5_data *piece, krb5_rcache *id) { krb5_rcache rcache; krb5_error_code ret; char *tmp = malloc(4 * piece->length + 1); char *name; if (tmp == NULL) return krb5_enomem(context); strvisx(tmp, piece->data, piece->length, VIS_WHITE | VIS_OCTAL); #ifdef HAVE_GETEUID ret = asprintf(&name, "FILE:rc_%s_%u", tmp, (unsigned)geteuid()); #else ret = asprintf(&name, "FILE:rc_%s", tmp); #endif free(tmp); if (ret < 0 || name == NULL) return krb5_enomem(context); ret = krb5_rc_resolve_full(context, &rcache, name); free(name); if(ret) return ret; *id = rcache; return ret; } heimdal-7.5.0/lib/krb5/krb5_get_all_client_addrs.30000644000175000017500000000551512136107750020024 0ustar niknik.\" Copyright (c) 2001 Kungliga Tekniska Högskolan .\" (Royal Institute of Technology, Stockholm, Sweden). .\" All rights reserved. .\" .\" Redistribution and use in source and binary forms, with or without .\" modification, are permitted provided that the following conditions .\" are met: .\" .\" 1. Redistributions of source code must retain the above copyright .\" notice, this list of conditions and the following disclaimer. .\" .\" 2. Redistributions in binary form must reproduce the above copyright .\" notice, this list of conditions and the following disclaimer in the .\" documentation and/or other materials provided with the distribution. .\" .\" 3. Neither the name of the Institute nor the names of its contributors .\" may be used to endorse or promote products derived from this software .\" without specific prior written permission. .\" .\" THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND .\" ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE .\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE .\" ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE .\" FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL .\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS .\" OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) .\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT .\" LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF .\" SUCH DAMAGE. .\" .\" $Id$ .\" .Dd July 1, 2001 .Dt KRB5_GET_ADDRS 3 .Os HEIMDAL .Sh NAME .Nm krb5_get_all_client_addrs , .Nm krb5_get_all_server_addrs .Nd return local addresses .Sh LIBRARY Kerberos 5 Library (libkrb5, -lkrb5) .Sh SYNOPSIS .In krb5.h .Ft "krb5_error_code" .Fn krb5_get_all_client_addrs "krb5_context context" "krb5_addresses *addrs" .Ft "krb5_error_code" .Fn krb5_get_all_server_addrs "krb5_context context" "krb5_addresses *addrs" .Sh DESCRIPTION These functions return in .Fa addrs a list of addresses associated with the local host. .Pp The server variant returns all configured interface addresses (if possible), including loop-back addresses. This is useful if you want to create sockets to listen to. .Pp The client version will also scan local interfaces (can be turned off by setting .Li libdefaults/scan_interfaces to false in .Pa krb5.conf ) , but will not include loop-back addresses, unless there are no other addresses found. It will remove all addresses included in .Li libdefaults/ignore_addresses but will unconditionally include addresses in .Li libdefaults/extra_addresses . .Pp The returned addresses should be freed by calling .Fn krb5_free_addresses . .\".Sh EXAMPLE .Sh SEE ALSO .Xr krb5_free_addresses 3 heimdal-7.5.0/lib/krb5/store-int.c0000644000175000017500000000455013026237312014756 0ustar niknik/* * Copyright (c) 1997-2008 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "krb5_locl.h" KRB5_LIB_FUNCTION krb5_ssize_t KRB5_LIB_CALL _krb5_put_int(void *buffer, uint64_t value, size_t size) { unsigned char *p = buffer; int i; for (i = size - 1; i >= 0; i--) { p[i] = value & 0xff; value >>= 8; } return size; } KRB5_LIB_FUNCTION krb5_ssize_t KRB5_LIB_CALL _krb5_get_int64(void *buffer, uint64_t *value, size_t size) { unsigned char *p = buffer; unsigned long v = 0; size_t i; for (i = 0; i < size; i++) v = (v << 8) + p[i]; *value = v; return size; } KRB5_LIB_FUNCTION krb5_ssize_t KRB5_LIB_CALL _krb5_get_int(void *buffer, unsigned long *value, size_t size) { uint64_t v64; krb5_ssize_t bytes = _krb5_get_int64(buffer, &v64, size); *value = v64; return bytes; } heimdal-7.5.0/lib/krb5/transited.c0000644000175000017500000004234313026237312015031 0ustar niknik/* * Copyright (c) 1997 - 2001, 2003 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "krb5_locl.h" /* this is an attempt at one of the most horrible `compression' schemes that has ever been invented; it's so amazingly brain-dead that words can not describe it, and all this just to save a few silly bytes */ struct tr_realm { char *realm; unsigned leading_space:1; unsigned leading_slash:1; unsigned trailing_dot:1; struct tr_realm *next; }; static void free_realms(struct tr_realm *r) { struct tr_realm *p; while(r){ p = r; r = r->next; free(p->realm); free(p); } } static int make_path(krb5_context context, struct tr_realm *r, const char *from, const char *to) { struct tr_realm *tmp; const char *p; if(strlen(from) < strlen(to)){ const char *str; str = from; from = to; to = str; } if(strcmp(from + strlen(from) - strlen(to), to) == 0){ p = from; while(1){ p = strchr(p, '.'); if(p == NULL) { krb5_clear_error_message (context); return KRB5KDC_ERR_POLICY; } p++; if(strcmp(p, to) == 0) break; tmp = calloc(1, sizeof(*tmp)); if(tmp == NULL) return krb5_enomem(context); tmp->next = r->next; r->next = tmp; tmp->realm = strdup(p); if(tmp->realm == NULL){ r->next = tmp->next; free(tmp); return krb5_enomem(context); } } }else if(strncmp(from, to, strlen(to)) == 0){ p = from + strlen(from); while(1){ while(p >= from && *p != '/') p--; if(p == from) return KRB5KDC_ERR_POLICY; if(strncmp(to, from, p - from) == 0) break; tmp = calloc(1, sizeof(*tmp)); if(tmp == NULL) return krb5_enomem(context); tmp->next = r->next; r->next = tmp; tmp->realm = malloc(p - from + 1); if(tmp->realm == NULL){ r->next = tmp->next; free(tmp); return krb5_enomem(context); } memcpy(tmp->realm, from, p - from); tmp->realm[p - from] = '\0'; p--; } } else { krb5_clear_error_message (context); return KRB5KDC_ERR_POLICY; } return 0; } static int make_paths(krb5_context context, struct tr_realm *realms, const char *client_realm, const char *server_realm) { struct tr_realm *r; int ret; const char *prev_realm = client_realm; const char *next_realm = NULL; for(r = realms; r; r = r->next){ /* it *might* be that you can have more than one empty component in a row, at least that's how I interpret the "," exception in 1510 */ if(r->realm[0] == '\0'){ while(r->next && r->next->realm[0] == '\0') r = r->next; if(r->next) next_realm = r->next->realm; else next_realm = server_realm; ret = make_path(context, r, prev_realm, next_realm); if(ret){ free_realms(realms); return ret; } } prev_realm = r->realm; } return 0; } static int expand_realms(krb5_context context, struct tr_realm *realms, const char *client_realm) { struct tr_realm *r; const char *prev_realm = NULL; for(r = realms; r; r = r->next){ if(r->trailing_dot){ char *tmp; size_t len; if(prev_realm == NULL) prev_realm = client_realm; len = strlen(r->realm) + strlen(prev_realm) + 1; tmp = realloc(r->realm, len); if(tmp == NULL){ free_realms(realms); return krb5_enomem(context); } r->realm = tmp; strlcat(r->realm, prev_realm, len); }else if(r->leading_slash && !r->leading_space && prev_realm){ /* yet another exception: if you use x500-names, the leading realm doesn't have to be "quoted" with a space */ char *tmp; size_t len = strlen(r->realm) + strlen(prev_realm) + 1; tmp = malloc(len); if(tmp == NULL){ free_realms(realms); return krb5_enomem(context); } strlcpy(tmp, prev_realm, len); strlcat(tmp, r->realm, len); free(r->realm); r->realm = tmp; } prev_realm = r->realm; } return 0; } static struct tr_realm * make_realm(char *realm) { struct tr_realm *r; char *p, *q; int quote = 0; r = calloc(1, sizeof(*r)); if(r == NULL){ free(realm); return NULL; } r->realm = realm; for(p = q = r->realm; *p; p++){ if(p == r->realm && *p == ' '){ r->leading_space = 1; continue; } if(q == r->realm && *p == '/') r->leading_slash = 1; if(quote){ *q++ = *p; quote = 0; continue; } if(*p == '\\'){ quote = 1; continue; } if(p[0] == '.' && p[1] == '\0') r->trailing_dot = 1; *q++ = *p; } *q = '\0'; return r; } static struct tr_realm* append_realm(struct tr_realm *head, struct tr_realm *r) { struct tr_realm *p; if(head == NULL){ r->next = NULL; return r; } p = head; while(p->next) p = p->next; p->next = r; return head; } static int decode_realms(krb5_context context, const char *tr, int length, struct tr_realm **realms) { struct tr_realm *r = NULL; char *tmp; int quote = 0; const char *start = tr; int i; for(i = 0; i < length; i++){ if(quote){ quote = 0; continue; } if(tr[i] == '\\'){ quote = 1; continue; } if(tr[i] == ','){ tmp = malloc(tr + i - start + 1); if(tmp == NULL) return krb5_enomem(context); memcpy(tmp, start, tr + i - start); tmp[tr + i - start] = '\0'; r = make_realm(tmp); if(r == NULL){ free_realms(*realms); return krb5_enomem(context); } *realms = append_realm(*realms, r); start = tr + i + 1; } } tmp = malloc(tr + i - start + 1); if(tmp == NULL){ free(*realms); return krb5_enomem(context); } memcpy(tmp, start, tr + i - start); tmp[tr + i - start] = '\0'; r = make_realm(tmp); if(r == NULL){ free_realms(*realms); return krb5_enomem(context); } *realms = append_realm(*realms, r); return 0; } KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_domain_x500_decode(krb5_context context, krb5_data tr, char ***realms, unsigned int *num_realms, const char *client_realm, const char *server_realm) { struct tr_realm *r = NULL; struct tr_realm *p, **q; int ret; if(tr.length == 0) { *realms = NULL; *num_realms = 0; return 0; } /* split string in components */ ret = decode_realms(context, tr.data, tr.length, &r); if(ret) return ret; /* apply prefix rule */ ret = expand_realms(context, r, client_realm); if(ret) return ret; ret = make_paths(context, r, client_realm, server_realm); if(ret) return ret; /* remove empty components and count realms */ *num_realms = 0; for(q = &r; *q; ){ if((*q)->realm[0] == '\0'){ p = *q; *q = (*q)->next; free(p->realm); free(p); }else{ q = &(*q)->next; (*num_realms)++; } } if (*num_realms + 1 > UINT_MAX/sizeof(**realms)) return ERANGE; { char **R; R = malloc((*num_realms + 1) * sizeof(*R)); if (R == NULL) return krb5_enomem(context); *realms = R; while(r){ *R++ = r->realm; p = r->next; free(r); r = p; } } return 0; } KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_domain_x500_encode(char **realms, unsigned int num_realms, krb5_data *encoding) { char *s = NULL; int len = 0; unsigned int i; krb5_data_zero(encoding); if (num_realms == 0) return 0; for(i = 0; i < num_realms; i++){ len += strlen(realms[i]); if(realms[i][0] == '/') len++; } len += num_realms - 1; s = malloc(len + 1); if (s == NULL) return ENOMEM; *s = '\0'; for(i = 0; i < num_realms; i++){ if(i) strlcat(s, ",", len + 1); if(realms[i][0] == '/') strlcat(s, " ", len + 1); strlcat(s, realms[i], len + 1); } encoding->data = s; encoding->length = strlen(s); return 0; } KRB5_LIB_FUNCTION void KRB5_LIB_CALL _krb5_free_capath(krb5_context context, char **capath) { char **s; for (s = capath; s && *s; ++s) free(*s); free(capath); } struct hier_iter { const char *local_realm; const char *server_realm; const char *lr; /* Pointer into tail of local realm */ const char *sr; /* Pointer into tail of server realm */ size_t llen; /* Length of local_realm */ size_t slen; /* Length of server_realm */ size_t len; /* Length of common suffix */ size_t num; /* Path element count */ }; /* * Step up from local_realm to common suffix, or else down to server_realm. */ static const char * hier_next(struct hier_iter *state) { const char *lr = state->lr; const char *sr = state->sr; const char *lsuffix = state->local_realm + state->llen - state->len; const char *server_realm = state->server_realm; if (lr != NULL) { while (lr < lsuffix) if (*lr++ == '.') return state->lr = lr; state->lr = NULL; } if (sr != NULL) { while (--sr >= server_realm) if (sr == server_realm || sr[-1] == '.') return state->sr = sr; state->sr = NULL; } return NULL; } static void hier_init(struct hier_iter *state, const char *local_realm, const char *server_realm) { size_t llen; size_t slen; size_t len = 0; const char *lr; const char *sr; state->local_realm = local_realm; state->server_realm = server_realm; state->llen = llen = strlen(local_realm); state->slen = slen = strlen(server_realm); state->len = 0; state->num = 0; if (slen == 0 || llen == 0) return; /* Find first difference from the back */ for (lr = local_realm + llen, sr = server_realm + slen; lr != local_realm && sr != server_realm; --lr, --sr) { if (lr[-1] != sr[-1]) break; if (lr[-1] == '.') len = llen - (lr - local_realm); } /* Nothing in common? */ if (*lr == '\0') return; /* Everything in common? */ if (llen == slen && lr == local_realm) return; /* Is one realm is a suffix of the other? */ if ((llen < slen && lr == local_realm && sr[-1] == '.') || (llen > slen && sr == server_realm && lr[-1] == '.')) len = llen - (lr - local_realm); state->len = len; /* `lr` starts at local realm and walks up the tree to common suffix */ state->lr = local_realm; /* `sr` starts at common suffix in server realm and walks down the tree */ state->sr = server_realm + slen - len; /* Count elements and reset */ while (hier_next(state) != NULL) ++state->num; state->lr = local_realm; state->sr = server_realm + slen - len; } /* * Find a referral path from client_realm to server_realm via local_realm. * Either via [capaths] or hierarchicaly. */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL _krb5_find_capath(krb5_context context, const char *client_realm, const char *local_realm, const char *server_realm, krb5_boolean use_hierarchical, char ***rpath, size_t *npath) { char **confpath; char **capath; struct hier_iter hier_state; char **rp; const char *r; *rpath = NULL; *npath = 0; confpath = krb5_config_get_strings(context, NULL, "capaths", client_realm, server_realm, NULL); if (confpath == NULL) confpath = krb5_config_get_strings(context, NULL, "capaths", local_realm, server_realm, NULL); /* * With a [capaths] setting from the client to the server we look for our * own realm in the list. If our own realm is not present, we return the * full list. Otherwise, we return our realm's successors, or possibly * NULL. Ignoring a [capaths] settings risks loops plus would violate * explicit policy and the principle of least surpise. */ if (confpath != NULL) { char **start = confpath; size_t i; size_t n; for (rp = start; *rp; rp++) if (strcmp(*rp, local_realm) == 0) start = rp+1; n = rp - start; if (n == 0) { krb5_config_free_strings(confpath); return 0; } capath = calloc(n + 1, sizeof(*capath)); if (capath == NULL) { krb5_config_free_strings(confpath); return krb5_enomem(context); } for (i = 0, rp = start; *rp; rp++) { if ((capath[i++] = strdup(*rp)) == NULL) { _krb5_free_capath(context, capath); krb5_config_free_strings(confpath); return krb5_enomem(context); } } krb5_config_free_strings(confpath); capath[i] = NULL; *rpath = capath; *npath = n; return 0; } /* The use_hierarchical flag makes hierarchical path lookup unconditional */ if (! use_hierarchical && ! krb5_config_get_bool_default(context, NULL, TRUE, "libdefaults", "allow_hierarchical_capaths", NULL)) return 0; /* * When validating transit paths, local_realm == client_realm. Otherwise, * with hierarchical referrals, they may differ, and we may be building a * path forward from our own realm! */ hier_init(&hier_state, local_realm, server_realm); if (hier_state.num == 0) return 0; rp = capath = calloc(hier_state.num + 1, sizeof(*capath)); if (capath == NULL) return krb5_enomem(context); while ((r = hier_next(&hier_state)) != NULL) { if ((*rp++ = strdup(r)) == NULL) { _krb5_free_capath(context, capath); return krb5_enomem(context); } } *rp = NULL; *rpath = capath; *npath = hier_state.num; return 0; } KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_check_transited(krb5_context context, krb5_const_realm client_realm, krb5_const_realm server_realm, krb5_realm *realms, unsigned int num_realms, int *bad_realm) { krb5_error_code ret = 0; char **capath = NULL; size_t num_capath = 0; size_t i = 0; size_t j = 0; /* In transit checks hierarchical capaths are optional */ ret = _krb5_find_capath(context, client_realm, client_realm, server_realm, FALSE, &capath, &num_capath); if (ret) return ret; for (i = 0; i < num_realms; i++) { for (j = 0; j < num_capath; ++j) { if (strcmp(realms[i], capath[j]) == 0) break; } if (j == num_capath) { _krb5_free_capath(context, capath); krb5_set_error_message (context, KRB5KRB_AP_ERR_ILL_CR_TKT, N_("no transit allowed " "through realm %s from %s to %s", ""), realms[i], client_realm, server_realm); if (bad_realm) *bad_realm = i; return KRB5KRB_AP_ERR_ILL_CR_TKT; } } _krb5_free_capath(context, capath); return 0; } KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_check_transited_realms(krb5_context context, const char *const *realms, unsigned int num_realms, int *bad_realm) { size_t i; int ret = 0; char **bad_realms = krb5_config_get_strings(context, NULL, "libdefaults", "transited_realms_reject", NULL); if(bad_realms == NULL) return 0; for(i = 0; i < num_realms; i++) { char **p; for(p = bad_realms; *p; p++) if(strcmp(*p, realms[i]) == 0) { ret = KRB5KRB_AP_ERR_ILL_CR_TKT; krb5_set_error_message (context, ret, N_("no transit allowed " "through realm %s", ""), *p); if(bad_realm) *bad_realm = i; break; } } krb5_config_free_strings(bad_realms); return ret; } #if 0 int main(int argc, char **argv) { krb5_data x; char **r; int num, i; x.data = argv[1]; x.length = strlen(x.data); if(domain_expand(x, &r, &num, argv[2], argv[3])) exit(1); for(i = 0; i < num; i++) printf("%s\n", r[i]); return 0; } #endif heimdal-7.5.0/lib/krb5/test_config_strings.cfg0000644000175000017500000000356713026237312017433 0ustar niknik[escapes] foo = A B C D bar = A B "C D" baz = A B "" quux = "A B;C: D" questionable="""" "" """" mismatch1 = A"BQd mismatch2 = efgh" ABC internal1 = "SnapeKills\" "Dumbledore" internal2 = "TownOf Sandwich: Massachusetts"Oldest Town In "Cape Cod" internal3 = "Begins and"ends In One String longer_strings = "Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:" "1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer." "2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution." "3. Neither the name of the Institute nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission." "THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." "Why do we test with such long strings? Because some people have config files" That look "Like this." heimdal-7.5.0/lib/krb5/set_default_realm.c0000644000175000017500000000556513026237312016520 0ustar niknik/* * Copyright (c) 1997 - 2001 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "krb5_locl.h" /* * Convert the simple string `s' into a NULL-terminated and freshly allocated * list in `list'. Return an error code. */ static krb5_error_code string_to_list (krb5_context context, const char *s, krb5_realm **list) { *list = malloc (2 * sizeof(**list)); if (*list == NULL) return krb5_enomem(context); (*list)[0] = strdup (s); if ((*list)[0] == NULL) { free (*list); return krb5_enomem(context); } (*list)[1] = NULL; return 0; } /* * Set the knowledge of the default realm(s) in `context'. * If realm != NULL, that's the new default realm. * Otherwise, the realm(s) are figured out from configuration or DNS. */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_set_default_realm(krb5_context context, const char *realm) { krb5_error_code ret = 0; krb5_realm *realms = NULL; if (realm == NULL) { realms = krb5_config_get_strings (context, NULL, "libdefaults", "default_realm", NULL); if (realms == NULL) ret = krb5_get_host_realm(context, NULL, &realms); } else { ret = string_to_list (context, realm, &realms); } if (ret) return ret; krb5_free_host_realm (context, context->default_realms); context->default_realms = realms; return 0; } heimdal-7.5.0/lib/kafs/0000755000175000017500000000000013214604041012737 5ustar niknikheimdal-7.5.0/lib/kafs/kafs.cat30000644000175000017500000002230613212450760014447 0ustar niknik KAFS(3) BSD Library Functions Manual KAFS(3) NNAAMMEE kk__hhaassaaffss, kk__hhaassaaffss__rreecchheecckk, kk__ppiiooccttll, kk__uunnlloogg, kk__sseettppaagg, kk__aaffss__cceellll__ooff__ffiillee, kkaaffss__sseett__vveerrbboossee, kkaaffss__sseettttookkeenn__rrxxkkaadd, kkaaffss__sseettttookkeenn, kkrrbb__aaffsslloogg, kkrrbb__aaffsslloogg__uuiidd, kkaaffss__sseettttookkeenn55, kkrrbb55__aaffsslloogg, kkrrbb55__aaffsslloogg__uuiidd -- AFS library LLIIBBRRAARRYY AFS cache manager access library (libkafs, -lkafs) SSYYNNOOPPSSIISS ##iinncclluuddee <> _i_n_t kk__aaffss__cceellll__ooff__ffiillee(_c_o_n_s_t _c_h_a_r _*_p_a_t_h, _c_h_a_r _*_c_e_l_l, _i_n_t _l_e_n); _i_n_t kk__hhaassaaffss(_v_o_i_d); _i_n_t kk__hhaassaaffss__rreecchheecckk(_v_o_i_d); _i_n_t kk__ppiiooccttll(_c_h_a_r _*_a___p_a_t_h, _i_n_t _o___o_p_c_o_d_e, _s_t_r_u_c_t _V_i_c_e_I_o_c_t_l _*_a___p_a_r_a_m_s_P, _i_n_t _a___f_o_l_l_o_w_S_y_m_l_i_n_k_s); _i_n_t kk__sseettppaagg(_v_o_i_d); _i_n_t kk__uunnlloogg(_v_o_i_d); _v_o_i_d kkaaffss__sseett__vveerrbboossee(_v_o_i_d _(_*_f_u_n_c_)_(_v_o_i_d _*_, _c_o_n_s_t _c_h_a_r _*_, _i_n_t_), _v_o_i_d _*); _i_n_t kkaaffss__sseettttookkeenn__rrxxkkaadd(_c_o_n_s_t _c_h_a_r _*_c_e_l_l, _s_t_r_u_c_t _C_l_e_a_r_T_o_k_e_n _*_t_o_k_e_n, _v_o_i_d _*_t_i_c_k_e_t, _s_i_z_e___t _t_i_c_k_e_t___l_e_n); _i_n_t kkaaffss__sseettttookkeenn(_c_o_n_s_t _c_h_a_r _*_c_e_l_l, _u_i_d___t _u_i_d, _C_R_E_D_E_N_T_I_A_L_S _*_c); kkrrbb__aaffsslloogg(_c_h_a_r _*_c_e_l_l, _c_h_a_r _*_r_e_a_l_m); _i_n_t kkrrbb__aaffsslloogg__uuiidd(_c_h_a_r _*_c_e_l_l, _c_h_a_r _*_r_e_a_l_m, _u_i_d___t _u_i_d); _k_r_b_5___e_r_r_o_r___c_o_d_e kkrrbb55__aaffsslloogg__uuiidd(_k_r_b_5___c_o_n_t_e_x_t _c_o_n_t_e_x_t, _k_r_b_5___c_c_a_c_h_e _i_d, _c_o_n_s_t _c_h_a_r _*_c_e_l_l, _k_r_b_5___c_o_n_s_t___r_e_a_l_m _r_e_a_l_m, _u_i_d___t _u_i_d); _i_n_t kkaaffss__sseettttookkeenn55(_c_o_n_s_t _c_h_a_r _*_c_e_l_l, _u_i_d___t _u_i_d, _k_r_b_5___c_r_e_d_s _*_c); _k_r_b_5___e_r_r_o_r___c_o_d_e kkrrbb55__aaffsslloogg(_k_r_b_5___c_o_n_t_e_x_t _c_o_n_t_e_x_t, _k_r_b_5___c_c_a_c_h_e _i_d, _c_o_n_s_t _c_h_a_r _*_c_e_l_l, _k_r_b_5___c_o_n_s_t___r_e_a_l_m _r_e_a_l_m); DDEESSCCRRIIPPTTIIOONN kk__hhaassaaffss() initializes some library internal structures, and tests for the presence of AFS in the kernel, none of the other functions should be called before kk__hhaassaaffss() is called, or if it fails. kk__hhaassaaffss__rreecchheecckk() forces a recheck if a AFS client has started since last time kk__hhaassaaffss() or kk__hhaassaaffss__rreecchheecckk() was called. kkaaffss__sseett__vveerrbboossee() set a log function that will be called each time the kafs library does something important so that the application using libkafs can output verbose logging. Calling the function _k_a_f_s___s_e_t___v_e_r_b_o_s_e with the function argument set to NULL will stop libkafs from calling the logging function (if set). kkaaffss__sseettttookkeenn__rrxxkkaadd() set rxkad with the _t_o_k_e_n and _t_i_c_k_e_t (that have the length _t_i_c_k_e_t___l_e_n) for a given _c_e_l_l. kkaaffss__sseettttookkeenn() and kkaaffss__sseettttookkeenn55() work the same way as kkaaffss__sseettttookkeenn__rrxxkkaadd() but internally converts the Kerberos 4 or 5 creden- tial to a afs cleartoken and ticket. kkrrbb__aaffsslloogg(), and kkrrbb__aaffsslloogg__uuiidd() obtains new tokens (and possibly tick- ets) for the specified _c_e_l_l and _r_e_a_l_m. If _c_e_l_l is NULL, the local cell is used. If _r_e_a_l_m is NULL, the function tries to guess what realm to use. Unless you have some good knowledge of what cell or realm to use, you should pass NULL. kkrrbb__aaffsslloogg() will use the real user-id for the ViceId field in the token, kkrrbb__aaffsslloogg__uuiidd() will use _u_i_d. kkrrbb55__aaffsslloogg(), and kkrrbb55__aaffsslloogg__uuiidd() are the Kerberos 5 equivalents of kkrrbb__aaffsslloogg(), and kkrrbb__aaffsslloogg__uuiidd(). kkrrbb55__aaffsslloogg(), kkaaffss__sseettttookkeenn55() can be configured to behave differently via a kkrrbb55__aappppddeeffaauulltt option afs-use-524 in _k_r_b_5_._c_o_n_f. Possible values for afs-use-524 are: yes use the 524 server in the realm to convert the ticket no use the Kerberos 5 ticket directly, can be used with if the afs cell support 2b token. local, 2b convert the Kerberos 5 credential to a 2b token locally (the same work as a 2b 524 server should have done). Example: [appdefaults] SU.SE = { afs-use-524 = local } PDC.KTH.SE = { afs-use-524 = yes } afs-use-524 = yes libkafs will use the libkafs as application name when running the kkrrbb55__aappppddeeffaauulltt function call. The (uppercased) cell name is used as the realm to the kkrrbb55__aappppddeeffaauulltt ffuunnccttiioonn.. kk__aaffss__cceellll__ooff__ffiillee() will in _c_e_l_l return the cell of a specified file, no more than _l_e_n characters is put in _c_e_l_l. kk__ppiiooccttll() does a ppiiooccttll() system call with the specified arguments. This function is equivalent to llppiiooccttll(). kk__sseettppaagg() initializes a new PAG. kk__uunnlloogg() removes destroys all tokens in the current PAG. RREETTUURRNN VVAALLUUEESS kk__hhaassaaffss() returns 1 if AFS is present in the kernel, 0 otherwise. kkrrbb__aaffsslloogg() and kkrrbb__aaffsslloogg__uuiidd() returns 0 on success, or a Kerberos error number on failure. kk__aaffss__cceellll__ooff__ffiillee(), kk__ppiiooccttll(), kk__sseettppaagg(), and kk__uunnlloogg() all return the value of the underlaying system call, 0 on success. EENNVVIIRROONNMMEENNTT The following environment variable affect the mode of operation of kkaaffss: AFS_SYSCALL Normally, kkaaffss will try to figure out the correct system call(s) that are used by AFS by itself. If it does not man- age to do that, or does it incorrectly, you can set this variable to the system call number or list of system call numbers that should be used. EEXXAAMMPPLLEESS The following code from llooggiinn will obtain a new PAG and tokens for the local cell and the cell of the users home directory. if (k_hasafs()) { char cell[64]; k_setpag(); if(k_afs_cell_of_file(pwd->pw_dir, cell, sizeof(cell)) == 0) krb_afslog(cell, NULL); krb_afslog(NULL, NULL); } EERRRROORRSS If any of these functions (apart from kk__hhaassaaffss()) is called without AFS being present in the kernel, the process will usually (depending on the operating system) receive a SIGSYS signal. SSEEEE AALLSSOO krb5_appdefault(3), krb5.conf(5) Transarc Corporation, "File Server/Cache Manager Interface", _A_F_S_-_3 _P_r_o_g_r_a_m_m_e_r_'_s _R_e_f_e_r_e_n_c_e, 1991. FFIILLEESS libkafs will search for _T_h_i_s_C_e_l_l _a_n_d _T_h_e_s_e_C_e_l_l_s in the following loca- tions: _/_u_s_r_/_v_i_c_e_/_e_t_c, _/_e_t_c_/_o_p_e_n_a_f_s, _/_v_a_r_/_d_b_/_o_p_e_n_a_f_s_/_e_t_c, _/_u_s_r_/_a_r_l_a_/_e_t_c, _/_e_t_c_/_a_r_l_a, and _/_e_t_c_/_a_f_s BBUUGGSS AFS_SYSCALL has no effect under AIX. HEIMDAL May 1, 2006 HEIMDAL heimdal-7.5.0/lib/kafs/kafs.h0000644000175000017500000001627113026237312014047 0ustar niknik/* * Copyright (c) 1995 - 2001, 2003 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ /* $Id$ */ #ifndef __KAFS_H #define __KAFS_H /* XXX must include krb5.h or krb.h */ /* sys/ioctl.h must be included manually before kafs.h */ /* */ #define AFSCALL_PIOCTL 20 #define AFSCALL_SETPAG 21 #ifndef _VICEIOCTL #ifdef __GNU__ #define _IOT_ViceIoctl _IOT(_IOTS(caddr_t), 2, _IOTS(short), 2, 0, 0) #endif #define _VICEIOCTL(id) ((unsigned int ) _IOW('V', id, struct ViceIoctl)) #define _AFSCIOCTL(id) ((unsigned int ) _IOW('C', id, struct ViceIoctl)) #endif /* _VICEIOCTL */ #define VIOCSETAL _VICEIOCTL(1) #define VIOCGETAL _VICEIOCTL(2) #define VIOCSETTOK _VICEIOCTL(3) #define VIOCGETVOLSTAT _VICEIOCTL(4) #define VIOCSETVOLSTAT _VICEIOCTL(5) #define VIOCFLUSH _VICEIOCTL(6) #define VIOCGETTOK _VICEIOCTL(8) #define VIOCUNLOG _VICEIOCTL(9) #define VIOCCKSERV _VICEIOCTL(10) #define VIOCCKBACK _VICEIOCTL(11) #define VIOCCKCONN _VICEIOCTL(12) #define VIOCWHEREIS _VICEIOCTL(14) #define VIOCACCESS _VICEIOCTL(20) #define VIOCUNPAG _VICEIOCTL(21) #define VIOCGETFID _VICEIOCTL(22) #define VIOCSETCACHESIZE _VICEIOCTL(24) #define VIOCFLUSHCB _VICEIOCTL(25) #define VIOCNEWCELL _VICEIOCTL(26) #define VIOCGETCELL _VICEIOCTL(27) #define VIOC_AFS_DELETE_MT_PT _VICEIOCTL(28) #define VIOC_AFS_STAT_MT_PT _VICEIOCTL(29) #define VIOC_FILE_CELL_NAME _VICEIOCTL(30) #define VIOC_GET_WS_CELL _VICEIOCTL(31) #define VIOC_AFS_MARINER_HOST _VICEIOCTL(32) #define VIOC_GET_PRIMARY_CELL _VICEIOCTL(33) #define VIOC_VENUSLOG _VICEIOCTL(34) #define VIOC_GETCELLSTATUS _VICEIOCTL(35) #define VIOC_SETCELLSTATUS _VICEIOCTL(36) #define VIOC_FLUSHVOLUME _VICEIOCTL(37) #define VIOC_AFS_SYSNAME _VICEIOCTL(38) #define VIOC_EXPORTAFS _VICEIOCTL(39) #define VIOCGETCACHEPARAMS _VICEIOCTL(40) #define VIOC_GCPAGS _VICEIOCTL(48) #define VIOCGETTOK2 _AFSCIOCTL(7) #define VIOCSETTOK2 _AFSCIOCTL(8) struct ViceIoctl { caddr_t in, out; unsigned short in_size; unsigned short out_size; }; struct ClearToken { int32_t AuthHandle; char HandShakeKey[8]; int32_t ViceId; int32_t BeginTimestamp; int32_t EndTimestamp; }; /* Use k_hasafs() to probe if the machine supports AFS syscalls. The other functions will generate a SIGSYS if AFS is not supported */ int k_hasafs (void); int k_hasafs_recheck (void); int krb_afslog (const char *cell, const char *realm); int krb_afslog_uid (const char *cell, const char *realm, uid_t uid); int krb_afslog_home (const char *cell, const char *realm, const char *homedir); int krb_afslog_uid_home (const char *cell, const char *realm, uid_t uid, const char *homedir); int krb_realm_of_cell (const char *cell, char **realm); /* compat */ #define k_afsklog krb_afslog #define k_afsklog_uid krb_afslog_uid int k_pioctl (char *a_path, int o_opcode, struct ViceIoctl *a_paramsP, int a_followSymlinks); int k_unlog (void); int k_setpag (void); int k_afs_cell_of_file (const char *path, char *cell, int len); /* XXX */ #ifdef KFAILURE #define KRB_H_INCLUDED #endif #ifdef KRB5_RECVAUTH_IGNORE_VERSION #define KRB5_H_INCLUDED #endif void kafs_set_verbose (void (*kafs_verbose)(void *, const char *), void *); int kafs_settoken_rxkad (const char *, struct ClearToken *, void *ticket, size_t ticket_len); #ifdef KRB_H_INCLUDED int kafs_settoken (const char*, uid_t, CREDENTIALS*); #endif #ifdef KRB5_H_INCLUDED int kafs_settoken5 (krb5_context, const char*, uid_t, krb5_creds*); #endif #ifdef KRB5_H_INCLUDED krb5_error_code krb5_afslog_uid (krb5_context context, krb5_ccache id, const char *cell, krb5_const_realm realm, uid_t uid); krb5_error_code krb5_afslog (krb5_context context, krb5_ccache id, const char *cell, krb5_const_realm realm); krb5_error_code krb5_afslog_uid_home (krb5_context context, krb5_ccache id, const char *cell, krb5_const_realm realm, uid_t uid, const char *homedir); krb5_error_code krb5_afslog_home (krb5_context context, krb5_ccache id, const char *cell, krb5_const_realm realm, const char *homedir); krb5_error_code krb5_realm_of_cell (const char *cell, char **realm); #endif #define _PATH_VICE "/usr/vice/etc/" #define _PATH_THISCELL _PATH_VICE "ThisCell" #define _PATH_CELLSERVDB _PATH_VICE "CellServDB" #define _PATH_THESECELLS _PATH_VICE "TheseCells" #define _PATH_ARLA_VICE "/usr/arla/etc/" #define _PATH_ARLA_THISCELL _PATH_ARLA_VICE "ThisCell" #define _PATH_ARLA_CELLSERVDB _PATH_ARLA_VICE "CellServDB" #define _PATH_ARLA_THESECELLS _PATH_ARLA_VICE "TheseCells" #define _PATH_OPENAFS_DEBIAN_VICE "/etc/openafs/" #define _PATH_OPENAFS_DEBIAN_THISCELL _PATH_OPENAFS_DEBIAN_VICE "ThisCell" #define _PATH_OPENAFS_DEBIAN_CELLSERVDB _PATH_OPENAFS_DEBIAN_VICE "CellServDB" #define _PATH_OPENAFS_DEBIAN_THESECELLS _PATH_OPENAFS_DEBIAN_VICE "TheseCells" #define _PATH_OPENAFS_MACOSX_VICE "/var/db/openafs/etc/" #define _PATH_OPENAFS_MACOSX_THISCELL _PATH_OPENAFS_MACOSX_VICE "ThisCell" #define _PATH_OPENAFS_MACOSX_CELLSERVDB _PATH_OPENAFS_MACOSX_VICE "CellServDB" #define _PATH_OPENAFS_MACOSX_THESECELLS _PATH_OPENAFS_MACOSX_VICE "TheseCells" #define _PATH_ARLA_DEBIAN_VICE "/etc/arla/" #define _PATH_ARLA_DEBIAN_THISCELL _PATH_ARLA_DEBIAN_VICE "ThisCell" #define _PATH_ARLA_DEBIAN_CELLSERVDB _PATH_ARLA_DEBIAN_VICE "CellServDB" #define _PATH_ARLA_DEBIAN_THESECELLS _PATH_ARLA_DEBIAN_VICE "TheseCells" #define _PATH_ARLA_OPENBSD_VICE "/etc/afs/" #define _PATH_ARLA_OPENBSD_THISCELL _PATH_ARLA_OPENBSD_VICE "ThisCell" #define _PATH_ARLA_OPENBSD_CELLSERVDB _PATH_ARLA_OPENBSD_VICE "CellServDB" #define _PATH_ARLA_OPENBSD_THESECELLS _PATH_ARLA_OPENBSD_VICE "TheseCells" extern int _kafs_debug; #endif /* __KAFS_H */ heimdal-7.5.0/lib/kafs/roken_rename.h0000644000175000017500000000454612136107750015575 0ustar niknik/* * Copyright (c) 2001-2002 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ /* $Id$ */ #ifndef __roken_rename_h__ #define __roken_rename_h__ /* * Libroken routines that are added libkafs */ #define _resolve_debug _kafs_resolve_debug #define rk_dns_free_data _kafs_dns_free_data #define rk_dns_lookup _kafs_dns_lookup #define rk_dns_string_to_type _kafs_dns_string_to_type #define rk_dns_type_to_string _kafs_dns_type_to_string #define rk_dns_srv_order _kafs_dns_srv_order #define rk_dns_make_query _kafs_dns_make_query #define rk_dns_free_query _kafs_dns_free_query #define rk_dns_parse_reply _kafs_dns_parse_reply #ifndef HAVE_STRTOK_R #define rk_strtok_r _kafs_strtok_r #endif #ifndef HAVE_STRLCPY #define rk_strlcpy _kafs_strlcpy #endif #ifndef HAVE_STRSEP #define rk_strsep _kafs_strsep #endif #endif /* __roken_rename_h__ */ heimdal-7.5.0/lib/kafs/afskrb5.c0000644000175000017500000002070213026237312014445 0ustar niknik/* * Copyright (c) 1995-2003 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "kafs_locl.h" struct krb5_kafs_data { krb5_context context; krb5_ccache id; krb5_const_realm realm; }; enum { KAFS_RXKAD_2B_KVNO = 213, KAFS_RXKAD_K5_KVNO = 256 }; static int v5_to_kt(krb5_creds *cred, uid_t uid, struct kafs_token *kt, int local524) { int kvno, ret; kt->ticket = NULL; if (local524) { Ticket t; unsigned char *buf; size_t buf_len; size_t len; kvno = KAFS_RXKAD_2B_KVNO; ret = decode_Ticket(cred->ticket.data, cred->ticket.length, &t, &len); if (ret) return ret; if (t.tkt_vno != 5) return -1; ASN1_MALLOC_ENCODE(EncryptedData, buf, buf_len, &t.enc_part, &len, ret); free_Ticket(&t); if (ret) return ret; if(buf_len != len) { free(buf); return KRB5KRB_ERR_GENERIC; } kt->ticket = buf; kt->ticket_len = buf_len; } else { kvno = KAFS_RXKAD_K5_KVNO; kt->ticket = malloc(cred->ticket.length); if (kt->ticket == NULL) return ENOMEM; kt->ticket_len = cred->ticket.length; memcpy(kt->ticket, cred->ticket.data, kt->ticket_len); ret = 0; } /* * Build a struct ClearToken */ ret = _kafs_derive_des_key(cred->session.keytype, cred->session.keyvalue.data, cred->session.keyvalue.length, kt->ct.HandShakeKey); if (ret) { free(kt->ticket); kt->ticket = NULL; return ret; } kt->ct.AuthHandle = kvno; kt->ct.ViceId = uid; kt->ct.BeginTimestamp = cred->times.starttime; kt->ct.EndTimestamp = cred->times.endtime; _kafs_fixup_viceid(&kt->ct, uid); return 0; } static krb5_error_code v5_convert(krb5_context context, krb5_ccache id, krb5_creds *cred, uid_t uid, const char *cell, struct kafs_token *kt) { krb5_error_code ret; char *c, *val; c = strdup(cell); if (c == NULL) return ENOMEM; _kafs_foldup(c, c); krb5_appdefault_string (context, "libkafs", c, "afs-use-524", "2b", &val); free(c); if (strcasecmp(val, "local") == 0 || strcasecmp(val, "2b") == 0) ret = v5_to_kt(cred, uid, kt, 1); else ret = v5_to_kt(cred, uid, kt, 0); free(val); return ret; } /* * */ static int get_cred(struct kafs_data *data, const char *name, const char *inst, const char *realm, uid_t uid, struct kafs_token *kt) { krb5_error_code ret; krb5_creds in_creds, *out_creds; struct krb5_kafs_data *d = data->data; int invalid; memset(&in_creds, 0, sizeof(in_creds)); ret = krb5_make_principal(d->context, &in_creds.server, realm, name, inst, NULL); if(ret) return ret; ret = krb5_cc_get_principal(d->context, d->id, &in_creds.client); if(ret){ krb5_free_principal(d->context, in_creds.server); return ret; } /* check if des is disable, and in that case enable it for afs */ invalid = krb5_enctype_valid(d->context, ETYPE_DES_CBC_CRC); if (invalid) krb5_enctype_enable(d->context, ETYPE_DES_CBC_CRC); ret = krb5_get_credentials(d->context, 0, d->id, &in_creds, &out_creds); if (invalid) krb5_enctype_disable(d->context, ETYPE_DES_CBC_CRC); krb5_free_principal(d->context, in_creds.server); krb5_free_principal(d->context, in_creds.client); if(ret) return ret; ret = v5_convert(d->context, d->id, out_creds, uid, (inst != NULL && inst[0] != '\0') ? inst : realm, kt); krb5_free_creds(d->context, out_creds); return ret; } static const char * get_error(struct kafs_data *data, int error) { struct krb5_kafs_data *d = data->data; return krb5_get_error_message(d->context, error); } static void free_error(struct kafs_data *data, const char *str) { struct krb5_kafs_data *d = data->data; krb5_free_error_message(d->context, str); } static krb5_error_code afslog_uid_int(struct kafs_data *data, const char *cell, const char *rh, uid_t uid, const char *homedir) { krb5_error_code ret; struct kafs_token kt; krb5_principal princ; const char *trealm; /* ticket realm */ struct krb5_kafs_data *d = data->data; if (cell == 0 || cell[0] == 0) return _kafs_afslog_all_local_cells (data, uid, homedir); ret = krb5_cc_get_principal (d->context, d->id, &princ); if (ret) return ret; trealm = krb5_principal_get_realm (d->context, princ); kt.ticket = NULL; ret = _kafs_get_cred(data, cell, d->realm, trealm, uid, &kt); krb5_free_principal (d->context, princ); if(ret == 0) { ret = kafs_settoken_rxkad(cell, &kt.ct, kt.ticket, kt.ticket_len); free(kt.ticket); } return ret; } static char * get_realm(struct kafs_data *data, const char *host) { struct krb5_kafs_data *d = data->data; krb5_realm *realms; char *r; if(krb5_get_host_realm(d->context, host, &realms)) return NULL; r = strdup(realms[0]); krb5_free_host_realm(d->context, realms); return r; } krb5_error_code krb5_afslog_uid_home(krb5_context context, krb5_ccache id, const char *cell, krb5_const_realm realm, uid_t uid, const char *homedir) { struct kafs_data kd; struct krb5_kafs_data d; krb5_error_code ret; kd.name = "krb5"; kd.afslog_uid = afslog_uid_int; kd.get_cred = get_cred; kd.get_realm = get_realm; kd.get_error = get_error; kd.free_error = free_error; kd.data = &d; if (context == NULL) { ret = krb5_init_context(&d.context); if (ret) return ret; } else d.context = context; if (id == NULL) { ret = krb5_cc_default(d.context, &d.id); if (ret) goto out; } else d.id = id; d.realm = realm; ret = afslog_uid_int(&kd, cell, 0, uid, homedir); if (id == NULL) krb5_cc_close(context, d.id); out: if (context == NULL) krb5_free_context(d.context); return ret; } krb5_error_code krb5_afslog_uid(krb5_context context, krb5_ccache id, const char *cell, krb5_const_realm realm, uid_t uid) { return krb5_afslog_uid_home (context, id, cell, realm, uid, NULL); } krb5_error_code krb5_afslog(krb5_context context, krb5_ccache id, const char *cell, krb5_const_realm realm) { return krb5_afslog_uid (context, id, cell, realm, getuid()); } krb5_error_code krb5_afslog_home(krb5_context context, krb5_ccache id, const char *cell, krb5_const_realm realm, const char *homedir) { return krb5_afslog_uid_home (context, id, cell, realm, getuid(), homedir); } /* * */ krb5_error_code krb5_realm_of_cell(const char *cell, char **realm) { struct kafs_data kd; kd.name = "krb5"; kd.get_realm = get_realm; kd.get_error = get_error; kd.free_error = free_error; return _kafs_realm_of_cell(&kd, cell, realm); } /* * */ int kafs_settoken5(krb5_context context, const char *cell, uid_t uid, krb5_creds *cred) { struct kafs_token kt; int ret; ret = v5_convert(context, NULL, cred, uid, cell, &kt); if (ret) return ret; ret = kafs_settoken_rxkad(cell, &kt.ct, kt.ticket, kt.ticket_len); free(kt.ticket); return ret; } heimdal-7.5.0/lib/kafs/afssys.c0000644000175000017500000003515213212137553014430 0ustar niknik/* * Copyright (c) 1995 - 2000, 2002, 2004, 2005 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "kafs_locl.h" struct procdata { unsigned long param4; unsigned long param3; unsigned long param2; unsigned long param1; unsigned long syscall; }; #ifdef __GNU__ #define _IOT_procdata _IOT(_IOTS(long), 5, 0, 0, 0, 0) #define VIOC_SYSCALL_PROC _IOW('C', 1, struct procdata) #else #define VIOC_SYSCALL_PROC _IOW('C', 1, void *) #endif struct devdata { unsigned long syscall; unsigned long param1; unsigned long param2; unsigned long param3; unsigned long param4; unsigned long param5; unsigned long param6; unsigned long retval; }; #ifdef __GNU__ #define _IOT_devdata _IOT(_IOTS(long), 8, 0, 0, 0, 0) #endif #ifdef _IOWR #define VIOC_SYSCALL_DEV _IOWR('C', 2, struct devdata) #define VIOC_SYSCALL_DEV_OPENAFS _IOWR('C', 1, struct devdata) #endif #ifdef _IOW #ifdef _ILP32 struct sundevdata { uint32_t param6; uint32_t param5; uint32_t param4; uint32_t param3; uint32_t param2; uint32_t param1; uint32_t syscall; }; #define VIOC_SUN_SYSCALL_DEV _IOW('C', 2, struct sundevdata) #else struct sundevdata { uint64_t param6; uint64_t param5; uint64_t param4; uint64_t param3; uint64_t param2; uint64_t param1; uint64_t syscall; }; #define VIOC_SUN_SYSCALL_DEV _IOW('C', 1, struct sundevdata) #endif #endif /* _IOW */ int _kafs_debug; /* this should be done in a better way */ #define UNKNOWN_ENTRY_POINT (-1) #define NO_ENTRY_POINT 0 #define SINGLE_ENTRY_POINT 1 #define MULTIPLE_ENTRY_POINT 2 #define SINGLE_ENTRY_POINT2 3 #define SINGLE_ENTRY_POINT3 4 #define LINUX_PROC_POINT 5 #define AIX_ENTRY_POINTS 6 #define MACOS_DEV_POINT 7 #define SUN_PROC_POINT 8 static int afs_entry_point = UNKNOWN_ENTRY_POINT; static int afs_syscalls[2]; static char *afs_ioctlpath; static unsigned long afs_ioctlnum; /* Magic to get AIX syscalls to work */ #ifdef _AIX static int (*Pioctl)(char*, int, struct ViceIoctl*, int); static int (*Setpag)(void); #include "dlfcn.h" /* * */ static int try_aix(void) { #ifdef STATIC_AFS_SYSCALLS Pioctl = aix_pioctl; Setpag = aix_setpag; #else void *ptr; char path[MaxPathLen], *p; /* * If we are root or running setuid don't trust AFSLIBPATH! */ if (getuid() != 0 && !issuid() && (p = getenv("AFSLIBPATH")) != NULL) strlcpy(path, p, sizeof(path)); else snprintf(path, sizeof(path), "%s/afslib.so", LIBDIR); ptr = dlopen(path, RTLD_NOW); if(ptr == NULL) { if(_kafs_debug) { if(errno == ENOEXEC && (p = dlerror()) != NULL) fprintf(stderr, "dlopen(%s): %s\n", path, p); else if (errno != ENOENT) fprintf(stderr, "dlopen(%s): %s\n", path, strerror(errno)); } return 1; } Setpag = (int (*)(void))dlsym(ptr, "aix_setpag"); Pioctl = (int (*)(char*, int, struct ViceIoctl*, int))dlsym(ptr, "aix_pioctl"); #endif afs_entry_point = AIX_ENTRY_POINTS; return 0; } #endif /* _AIX */ /* * This probably only works under Solaris and could get confused if * there's a /etc/name_to_sysnum file. */ #if defined(AFS_SYSCALL) || defined(AFS_SYSCALL2) || defined(AFS_SYSCALL3) #define _PATH_ETC_NAME_TO_SYSNUM "/etc/name_to_sysnum" static int map_syscall_name_to_number (const char *str, int *res) { FILE *f; char buf[256]; size_t str_len = strlen (str); f = fopen (_PATH_ETC_NAME_TO_SYSNUM, "r"); if (f == NULL) return -1; while (fgets (buf, sizeof(buf), f) != NULL) { if (buf[0] == '#') continue; if (strncmp (str, buf, str_len) == 0) { char *begptr = buf + str_len; char *endptr; long val = strtol (begptr, &endptr, 0); if (val != 0 && endptr != begptr) { fclose (f); *res = val; return 0; } } } fclose (f); return -1; } #endif static int try_ioctlpath(const char *path, unsigned long ioctlnum, int entrypoint) { int fd, ret, saved_errno; fd = open(path, O_RDWR); if (fd < 0) return 1; switch (entrypoint) { case LINUX_PROC_POINT: { struct procdata data = { 0, 0, 0, 0, AFSCALL_PIOCTL }; data.param2 = (unsigned long)VIOCGETTOK; ret = ioctl(fd, ioctlnum, &data); break; } case MACOS_DEV_POINT: { struct devdata data = { AFSCALL_PIOCTL, 0, 0, 0, 0, 0, 0, 0 }; data.param2 = (unsigned long)VIOCGETTOK; ret = ioctl(fd, ioctlnum, &data); break; } case SUN_PROC_POINT: { struct sundevdata data = { 0, 0, 0, 0, 0, 0, AFSCALL_PIOCTL }; data.param2 = (unsigned long)VIOCGETTOK; ret = ioctl(fd, ioctlnum, &data); break; } default: abort(); } saved_errno = errno; close(fd); /* * Be quite liberal in what error are ok, the first is the one * that should trigger given that params is NULL. */ if (ret && (saved_errno != EFAULT && saved_errno != EDOM && saved_errno != ENOTCONN)) return 1; afs_ioctlnum = ioctlnum; afs_ioctlpath = strdup(path); if (afs_ioctlpath == NULL) return 1; afs_entry_point = entrypoint; return 0; } static int do_ioctl(void *data) { int fd, ret, saved_errno; fd = open(afs_ioctlpath, O_RDWR); if (fd < 0) { errno = EINVAL; return -1; } ret = ioctl(fd, afs_ioctlnum, data); saved_errno = errno; close(fd); errno = saved_errno; return ret; } int k_pioctl(char *a_path, int o_opcode, struct ViceIoctl *a_paramsP, int a_followSymlinks) { #ifndef NO_AFS switch(afs_entry_point){ #if defined(AFS_SYSCALL) || defined(AFS_SYSCALL2) || defined(AFS_SYSCALL3) case SINGLE_ENTRY_POINT: case SINGLE_ENTRY_POINT2: case SINGLE_ENTRY_POINT3: return syscall(afs_syscalls[0], AFSCALL_PIOCTL, a_path, o_opcode, a_paramsP, a_followSymlinks); #endif #if defined(AFS_PIOCTL) case MULTIPLE_ENTRY_POINT: return syscall(afs_syscalls[0], a_path, o_opcode, a_paramsP, a_followSymlinks); #endif case LINUX_PROC_POINT: { struct procdata data = { 0, 0, 0, 0, AFSCALL_PIOCTL }; data.param1 = (unsigned long)a_path; data.param2 = (unsigned long)o_opcode; data.param3 = (unsigned long)a_paramsP; data.param4 = (unsigned long)a_followSymlinks; return do_ioctl(&data); } case MACOS_DEV_POINT: { struct devdata data = { AFSCALL_PIOCTL, 0, 0, 0, 0, 0, 0, 0 }; int ret; data.param1 = (unsigned long)a_path; data.param2 = (unsigned long)o_opcode; data.param3 = (unsigned long)a_paramsP; data.param4 = (unsigned long)a_followSymlinks; ret = do_ioctl(&data); if (ret) return ret; return data.retval; } case SUN_PROC_POINT: { struct sundevdata data = { 0, 0, 0, 0, 0, 0, AFSCALL_PIOCTL }; data.param1 = (unsigned long)a_path; data.param2 = (unsigned long)o_opcode; data.param3 = (unsigned long)a_paramsP; data.param4 = (unsigned long)a_followSymlinks; return do_ioctl(&data); } #ifdef _AIX case AIX_ENTRY_POINTS: return Pioctl(a_path, o_opcode, a_paramsP, a_followSymlinks); #endif } errno = ENOSYS; #ifdef SIGSYS kill(getpid(), SIGSYS); /* You lose! */ #endif #endif /* NO_AFS */ return -1; } int k_afs_cell_of_file(const char *path, char *cell, int len) { struct ViceIoctl parms; parms.in = NULL; parms.in_size = 0; parms.out = cell; parms.out_size = len; return k_pioctl(rk_UNCONST(path), VIOC_FILE_CELL_NAME, &parms, 1); } int k_unlog(void) { struct ViceIoctl parms; memset(&parms, 0, sizeof(parms)); return k_pioctl(0, VIOCUNLOG, &parms, 0); } int k_setpag(void) { #ifndef NO_AFS switch(afs_entry_point){ #if defined(AFS_SYSCALL) || defined(AFS_SYSCALL2) || defined(AFS_SYSCALL3) case SINGLE_ENTRY_POINT: case SINGLE_ENTRY_POINT2: case SINGLE_ENTRY_POINT3: return syscall(afs_syscalls[0], AFSCALL_SETPAG); #endif #if defined(AFS_PIOCTL) case MULTIPLE_ENTRY_POINT: return syscall(afs_syscalls[1]); #endif case LINUX_PROC_POINT: { struct procdata data = { 0, 0, 0, 0, AFSCALL_SETPAG }; return do_ioctl(&data); } case MACOS_DEV_POINT: { struct devdata data = { AFSCALL_SETPAG, 0, 0, 0, 0, 0, 0, 0 }; int ret = do_ioctl(&data); if (ret) return ret; return data.retval; } case SUN_PROC_POINT: { struct sundevdata data = { 0, 0, 0, 0, 0, 0, AFSCALL_SETPAG }; return do_ioctl(&data); } #ifdef _AIX case AIX_ENTRY_POINTS: return Setpag(); #endif } errno = ENOSYS; #ifdef SIGSYS kill(getpid(), SIGSYS); /* You lose! */ #endif #endif /* NO_AFS */ return -1; } static jmp_buf catch_SIGSYS; #ifdef SIGSYS static RETSIGTYPE SIGSYS_handler(int sig) { errno = 0; signal(SIGSYS, SIGSYS_handler); /* Need to reinstall handler on SYSV */ longjmp(catch_SIGSYS, 1); } #endif /* * Try to see if `syscall' is a pioctl. Return 0 iff succesful. */ #if defined(AFS_SYSCALL) || defined(AFS_SYSCALL2) || defined(AFS_SYSCALL3) static int try_one (int syscall_num) { struct ViceIoctl parms; memset(&parms, 0, sizeof(parms)); if (setjmp(catch_SIGSYS) == 0) { syscall(syscall_num, AFSCALL_PIOCTL, 0, VIOCSETTOK, &parms, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0); if (errno == EINVAL) { afs_entry_point = SINGLE_ENTRY_POINT; afs_syscalls[0] = syscall_num; return 0; } } return 1; } #endif /* * Try to see if `syscall_pioctl' is a pioctl syscall. Return 0 iff * succesful. * */ #ifdef AFS_PIOCTL static int try_two (int syscall_pioctl, int syscall_setpag) { struct ViceIoctl parms; memset(&parms, 0, sizeof(parms)); if (setjmp(catch_SIGSYS) == 0) { syscall(syscall_pioctl, 0, VIOCSETTOK, &parms, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0); if (errno == EINVAL) { afs_entry_point = MULTIPLE_ENTRY_POINT; afs_syscalls[0] = syscall_pioctl; afs_syscalls[1] = syscall_setpag; return 0; } } return 1; } #endif int k_hasafs(void) { #if !defined(NO_AFS) && defined(SIGSYS) RETSIGTYPE (*saved_func)(int); #endif int saved_errno, ret; char *env = NULL; if (!issuid()) env = getenv ("AFS_SYSCALL"); /* * Already checked presence of AFS syscalls? */ if (afs_entry_point != UNKNOWN_ENTRY_POINT) return afs_entry_point != NO_ENTRY_POINT; /* * Probe kernel for AFS specific syscalls, * they (currently) come in two flavors. * If the syscall is absent we recive a SIGSYS. */ afs_entry_point = NO_ENTRY_POINT; saved_errno = errno; #ifndef NO_AFS #ifdef SIGSYS saved_func = signal(SIGSYS, SIGSYS_handler); #endif if (env && strstr(env, "..") == NULL) { if (strncmp("/proc/", env, 6) == 0) { if (try_ioctlpath(env, VIOC_SYSCALL_PROC, LINUX_PROC_POINT) == 0) goto done; } if (strncmp("/dev/", env, 5) == 0) { #ifdef VIOC_SYSCALL_DEV if (try_ioctlpath(env, VIOC_SYSCALL_DEV, MACOS_DEV_POINT) == 0) goto done; #endif #ifdef VIOC_SYSCALL_DEV_OPENAFS if (try_ioctlpath(env,VIOC_SYSCALL_DEV_OPENAFS,MACOS_DEV_POINT) ==0) goto done; #endif } } ret = try_ioctlpath("/proc/fs/openafs/afs_ioctl", VIOC_SYSCALL_PROC, LINUX_PROC_POINT); if (ret == 0) goto done; ret = try_ioctlpath("/proc/fs/nnpfs/afs_ioctl", VIOC_SYSCALL_PROC, LINUX_PROC_POINT); if (ret == 0) goto done; #ifdef VIOC_SYSCALL_DEV_OPENAFS ret = try_ioctlpath("/dev/openafs_ioctl", VIOC_SYSCALL_DEV_OPENAFS, MACOS_DEV_POINT); if (ret == 0) goto done; #endif #ifdef VIOC_SYSCALL_DEV ret = try_ioctlpath("/dev/nnpfs_ioctl", VIOC_SYSCALL_DEV, MACOS_DEV_POINT); if (ret == 0) goto done; #endif #ifdef VIOC_SUN_SYSCALL_DEV ret = try_ioctlpath("/dev/afs", VIOC_SUN_SYSCALL_DEV, SUN_PROC_POINT); if (ret == 0) goto done; #endif #if defined(AFS_SYSCALL) || defined(AFS_SYSCALL2) || defined(AFS_SYSCALL3) { int tmp; if (env != NULL) { if (sscanf (env, "%d", &tmp) == 1) { if (try_one (tmp) == 0) goto done; } else { char *end = NULL; char *p; char *s = strdup (env); if (s != NULL) { for (p = strtok_r (s, ",", &end); p != NULL; p = strtok_r (NULL, ",", &end)) { if (map_syscall_name_to_number (p, &tmp) == 0) if (try_one (tmp) == 0) { free (s); goto done; } } free (s); } } } } #endif /* AFS_SYSCALL || AFS_SYSCALL2 || AFS_SYSCALL3 */ #ifdef AFS_SYSCALL if (try_one (AFS_SYSCALL) == 0) goto done; #endif /* AFS_SYSCALL */ #ifdef AFS_PIOCTL { int tmp[2]; if (env != NULL && sscanf (env, "%d%d", &tmp[0], &tmp[1]) == 2) if (try_two (tmp[0], tmp[1]) == 2) goto done; } #endif /* AFS_PIOCTL */ #ifdef AFS_PIOCTL if (try_two (AFS_PIOCTL, AFS_SETPAG) == 0) goto done; #endif /* AFS_PIOCTL */ #ifdef AFS_SYSCALL2 if (try_one (AFS_SYSCALL2) == 0) goto done; #endif /* AFS_SYSCALL2 */ #ifdef AFS_SYSCALL3 if (try_one (AFS_SYSCALL3) == 0) goto done; #endif /* AFS_SYSCALL3 */ #ifdef _AIX #if 0 if (env != NULL) { char *pos = NULL; char *pioctl_name; char *setpag_name; pioctl_name = strtok_r (env, ", \t", &pos); if (pioctl_name != NULL) { setpag_name = strtok_r (NULL, ", \t", &pos); if (setpag_name != NULL) if (try_aix (pioctl_name, setpag_name) == 0) goto done; } } #endif if(try_aix() == 0) goto done; #endif done: #ifdef SIGSYS signal(SIGSYS, saved_func); #endif #endif /* NO_AFS */ errno = saved_errno; return afs_entry_point != NO_ENTRY_POINT; } int k_hasafs_recheck(void) { afs_entry_point = UNKNOWN_ENTRY_POINT; return k_hasafs(); } heimdal-7.5.0/lib/kafs/afssysdefs.h0000644000175000017500000000561312664131275015303 0ustar niknik/* * Copyright (c) 1995 - 2003 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ /* $Id$ */ /* * This section is for machines using single entry point AFS syscalls! * and/or * This section is for machines using multiple entry point AFS syscalls! * * SunOS 4 is an example of single entry point and sgi of multiple * entry point syscalls. */ #if SunOS == 40 #define AFS_SYSCALL 31 #endif #if SunOS >= 50 && SunOS < 57 #define AFS_SYSCALL 105 #endif #if SunOS == 57 #define AFS_SYSCALL 73 #endif #if SunOS >= 58 #define AFS_SYSCALL 65 #endif #if defined(__hpux) #define AFS_SYSCALL 50 #define AFS_SYSCALL2 49 #define AFS_SYSCALL3 48 #endif #if defined(_AIX) /* _AIX is too weird */ #endif #if defined(__sgi) #define AFS_PIOCTL (64+1000) #define AFS_SETPAG (65+1000) #endif #if defined(__osf__) #define AFS_SYSCALL 232 #define AFS_SYSCALL2 258 #endif #if defined(__ultrix) #define AFS_SYSCALL 31 #endif #if defined(__FreeBSD__) #if __FreeBSD_version >= 500000 #define AFS_SYSCALL 339 #else #define AFS_SYSCALL 210 #endif #endif /* __FreeBSD__ */ #ifdef __DragonFly__ #ifndef AFS_SYSCALL #define AFS_SYSCALL 339 #endif #endif #ifdef __OpenBSD__ #define AFS_SYSCALL 208 #endif #if defined(__NetBSD__) #define AFS_SYSCALL 210 #endif #ifdef __APPLE__ /* MacOS X */ #define AFS_SYSCALL 230 #endif #ifdef SYS_afs_syscall #define AFS_SYSCALL3 SYS_afs_syscall #endif heimdal-7.5.0/lib/kafs/ChangeLog0000644000175000017500000004033212136107750014522 0ustar niknik2008-07-17 Love Hörnquist Åstrand * common.c: Try afs/cell@REALM before afs@REALM since that is what OpenAFS folks have been saying is best pratices for some time now. Patch from Derrick Brashear. 2008-04-15 Love Hörnquist Åstrand * afssys.c: Avoid using entry points depending on _IOWR if there is no _IOWR (on cygwin). 2007-07-10 Love Hörnquist Åstrand * Makefile.am: New library version. 2007-05-10 Love Hörnquist Åstrand * kafs.h: Add VIOCSETTOK2 2006-10-21 Love Hörnquist Åstrand * Makefile.am: unbreak previous * Makefile.am: split dist and nodist sources 2006-10-20 Love Hörnquist Åstrand * Makefile.am: add more files 2006-05-01 Love Hörnquist Åstrand * kafs.3: Spelling, from Björn Sandell. 2006-04-11 Love Hörnquist Åstrand * afssys.c: use afs_ioctlnum, From Tomas Olsson 2006-04-10 Love Hörnquist Åstrand * afssys.c: Try harder to get the pioctl to work via the /proc or /dev interface, OpenAFS choose to reuse the same ioctl number, while Arla didn't. Also, try new ioctl before the the old syscalls. * afskrb5.c (afslog_uid_int): use the simpler krb5_principal_get_realm function. 2005-12-21 Love Hörnquist Åstrand * Makefile.am: Remove dependency on config.h, breaks IRIX build, could depend on libkafs_la_OBJECTS, but that is just asking for trubble. 2005-10-20 Love Hörnquist Åstrand * afssys.c (k_hasafs_recheck): new function, allow rechecking if AFS client have started now, internaly it resets the internal state from k_hasafs() and retry retry the probing. The problem with calling k_hasaf() is that is plays around with signals, and that cases problem for some systems/applications. 2005-10-02 Love Hörnquist Åstrand * kafs_locl.h: Maybe include . * afssys.c: Mac OS X 10.4 needs a runtime check if we are going to use the syscall, there is no cpp define to use to check the version. Every after 10.0 (darwin 8.0) uses the /dev/ version of the pioctl. 2005-10-01 Love Hörnquist Åstrand * afssys.c: Support the new MacOS X 10.4 ioctl interface that is a device node. Patched from Tomas Olson . 2005-08-26 Love Hörnquist Åstrand * afskrb5.c: Default to use 2b tokens. 2005-06-17 Love Hörnquist Åstrand * common.c: rename index to idx * afssys.c (k_afs_cell_of_file): unconst path 2005-06-02 Love Hörnquist Åstrand * use struct kafs_data everywhere, don't mix with the typedef kafs_data * roken_rename.h: rename more resolve.c symbols * afssys.c: Don't building map_syscall_name_to_number where its not used. 2005-02-24 Love Hörnquist Åstrand * Makefile.am: bump version to 4:1:4 2005-02-03 Love Hörnquist Åstrand * kafs.h: de-__P 2004-12-06 Love Hörnquist Åstrand * afskrb5.c: s/KEYTYPE_DES/ETYPE_DES_CBC_CRC/ 2004-08-09 Love Hörnquist Åstrand * afssysdefs.h: ifdef protect AFS_SYSCALL for DragonFly since they still define __FreeBSD__ (and __FreeBSD_version), but claim that they will stop doing it some time... * afssysdefs.h: dragonflybsd uses 339 just like freebsd5 2004-06-22 Love Hörnquist Åstrand * afssys.c: s/arla/nnpfs/ * afssys.c: support the linux /proc/fs/mumel/afs_ioctl afs "syscall" interface 2004-01-22 Love Hörnquist Åstrand * common.c: search paths for AFS configuration files for the OpenAFS MacOS X, fix comment * kafs.h: search paths for AFS configuration files for the OpenAFS MacOS X 2003-12-02 Love Hörnquist Åstrand * common.c: add _PATH_ARLA_OPENBSD & c/o * kafs.h: add _PATH_ARLA_OPENBSD & c/o 2003-11-14 Love Hörnquist Åstrand * common.c: typo, Bruno Rohee 2003-11-08 Love Hörnquist Åstrand * kafs.3: spelling, partly from jmc 2003-09-30 Love Hörnquist Åstrand * afskrb5.c (krb5_afslog_uid_home): be even more friendly to the user and fetch context and id ourself 2003-09-23 Love Hörnquist Åstrand * afskrb5.c (afslog_uid_int): just belive that realm hint the user passed us 2003-07-23 Love Hörnquist Åstrand * Makefile.am: always include v4 symbols * afskrb.c: provide dummy krb_ function to there is no need to bump major 2003-06-22 Love Hörnquist Åstrand * afskrb5.c (v5_convert): rename one of the two c to cred4 2003-04-23 Love Hörnquist Åstrand * common.c, kafs.h: drop the int argument (the error code) from the logging function 2003-04-22 Johan Danielsson * afskrb5.c (v5_convert): better match what other functions do with values from krb5.conf, like case insensitivity 2003-04-16 Love Hörnquist Åstrand * kafs.3: Change .Fd #include to .In header.h from Thomas Klausner 2003-04-14 Love Hörnquist Åstrand * Makefile.am: (libkafs_la_LDFLAGS): update version * Makefile.am (ROKEN_SRCS): drop strupr.c * kafs.3: document kafs_set_verbose * common.c (kafs_set_verbose): add function that (re)sets the logging function (_kafs_try_get_cred): add function that does (krb_data->get_cred) to make logging easier (that is now done in this function) (*): use _kafs_try_get_cred * afskrb5.c (get_cred): handle that inst can be the empty string too (v5_convert): use _kafs_foldup (krb5_afslog_uid_home): set name (krb5_afslog_uid_home): ditto * afskrb.c (krb_afslog_uid_home): set name (krb_afslog_uid_home): ditto * kafs_locl.h (kafs_data): add name (_kafs_foldup): internally export 2003-04-11 Love Hörnquist Åstrand * kafs.3: tell that cell-name is uppercased * Makefile.am: add INCLUDE_krb4 when using krb4, add INCLUDE_des when using krb5, add strupr.c * afskrb5.c: Check the cell part of the name, not the realm part when checking if 2b should be used. The reson is afs@REALM might have updated their servers but not afs/cell@REALM. Add constant KAFS_RXKAD_2B_KVNO. 2003-04-06 Love Hörnquist Åstrand * kafs.3: s/kerberos/Kerberos/ 2003-03-19 Love Hörnquist Åstrand * kafs.3: spelling, from * kafs.3: document the kafs_settoken functions write about the krb5_appdefault option for kerberos 5 afs tokens fix prototypes 2003-03-18 Love Hörnquist Åstrand * afskrb5.c (kafs_settoken5): change signature to include a krb5_context, use v5_convert (v5_convert): new function, converts a krb5_ccreds to a kafs_token in three diffrent ways, not at all, local 524/2b, and using 524 (v5_to_kt): add code to do local 524/2b (get_cred): use v5_convert * kafs.h (kafs_settoken5): change signature to include a krb5_context * Makefile.am: always build the libkafs library now that the kerberos 5 can stand on their own * kafs.3: expose the krb5 functions * common.c (kafs_settoken_rxkad): move all content kerberos version from kafs_settoken to kafs_settoken_rxkad (_kafs_fixup_viceid): move the fixup the timestamp to make client happy code here. (_kafs_v4_to_kt): move all the kerberos 4 dependant parts from kafs_settoken here. (*): adapt to kafs_token * afskrb5.c (kafs_settoken5): new function, inserts a krb5_creds into kernel (v5_to_kt): new function, stores a krb5_creds in struct kafs_token (get_cred): add a appdefault boolean ("libkafs", realm, "afs-use-524") that can used to toggle if there should v5 token should be used directly or converted via 524 first. * afskrb.c: move kafs_settoken here, use struct kafs_token * kafs_locl.h: include krb5-v4compat.h if needed, define an internal structure struct kafs_token that carries around for rxkad data that is independant of kerberos version 2003-02-18 Love Hörnquist Åstrand * dlfcn.h: s/intialize/initialize, from 2003-02-08 Assar Westerlund * afssysdefs.h: fix FreeBSD section 2003-02-06 Love Hörnquist Åstrand * afssysdefs.h: use syscall 208 on openbsd (all version) use syscall 339 on freebsd 5.0 and later, use 210 on 4.x and earlier 2002-08-28 Johan Danielsson * kafs.3: move around sections (from NetBSD) 2002-05-31 Assar Westerlund * common.c: remove the trial of afs@REALM for cell != realm, it tries to use the wrong key for foreign cells 2002-05-20 Johan Danielsson * Makefile.am: version number 2002-04-18 Johan Danielsson * common.c (find_cells): make file parameter const 2001-11-01 Assar Westerlund * add strsep, and bump version to 3:3:3 2001-10-27 Assar Westerlund * Makefile.am (libkafs_la_LDFLAGS): set version to 3:2:3 2001-10-24 Assar Westerlund * afskrb.c (afslog_uid_int): handle krb_get_tf_fullname that cannot take NULLs (such as the MIT one) 2001-10-22 Assar Westerlund * Makefile.am (ROKEN_SRCS): add strlcpy.c 2001-10-09 Assar Westerlund * Makefile.am (ROKEN_SRCS): add strtok_r.c * roken_rename.h (dns_srv_order): rename correctly (strtok_r): add renaming 2001-09-10 Assar Westerlund * kafs.h, common.c: look for configuration files in /etc/arla (the location in debian's arla package) 2001-08-26 Assar Westerlund * Makefile.am: handle both krb5 and krb4 cases 2001-07-19 Assar Westerlund * Makefile.am (libkafs_la_LDFLAGS): set version to 3:0:3 2001-07-12 Assar Westerlund * common.c: look in /etc/openafs for debian openafs * kafs.h: add paths for openafs debian (/etc/openafs) * Makefile.am: add required library dependencies 2001-07-03 Assar Westerlund * Makefile.am (libkafs_la_LDFLAGS): set versoin to 2:4:2 2001-06-19 Assar Westerlund * common.c (_kafs_realm_of_cell): changed to first try exact match in CellServDB, then exact match in DNS, and finally in-exact match in CellServDB 2001-05-18 Johan Danielsson * Makefile.am: only build resolve.c if doing renaming 2001-02-12 Assar Westerlund * Makefile.am, roken_rename.h: add rename of dns functions 2000-12-11 Assar Westerlund * Makefile.am (libkafs_la_LDFLAGS): set version to 2:3:2 2000-11-17 Assar Westerlund * afssysdefs.h: solaris 8 apperently uses 65 2000-09-19 Assar Westerlund * Makefile.am (libkafs_la_LDFLAGS): bump version to 2:2:2 2000-09-12 Johan Danielsson * dlfcn.c: correct arguments to some snprintf:s 2000-07-25 Johan Danielsson * Makefile.am: bump version to 2:1:2 2000-04-03 Assar Westerlund * Makefile.am: set version to 2:0:2 2000-03-20 Assar Westerlund * afssysdefs.h: make versions later than 5.7 of solaris also use 73 2000-03-16 Assar Westerlund * afskrb.c (afslog_uid_int): use krb_get_tf_fullname instead of krb_get_default_principal 2000-03-15 Assar Westerlund * afssys.c (map_syscall_name_to_number): ignore # at beginning-of-line 2000-03-13 Assar Westerlund * afssysdefs.h: add 230 for MacOS X per information from 1999-12-06 Assar Westerlund * Makefile.am: set version to 1:2:1 1999-11-22 Assar Westerlund * afskrb5.c (afslog_uid_int): handle d->realm == NULL 1999-11-17 Assar Westerlund * afskrb5.c (afslog_uid_int): don't look at the local realm at all. just use the realm from the ticket file. 1999-10-20 Assar Westerlund * Makefile.am: set version to 1:1:1 * afskrb5.c (get_cred): always request a DES key Mon Oct 18 17:40:21 1999 Bjoern Groenvall * common.c (find_cells): Trim trailing whitespace from cellname. Lines starting with # are regarded as comments. Fri Oct 8 18:17:22 1999 Bjoern Groenvall * afskrb.c, common.c : Change code to make a clear distinction between hinted realm and ticket realm. * kafs_locl.h: Added argument realm_hint. * common.c (_kafs_get_cred): Change code to acquire the ``best'' possible ticket. Use cross-cell authentication only as method of last resort. * afskrb.c (afslog_uid_int): Add realm_hint argument and extract realm from ticket file. * afskrb5.c (afslog_uid_int): Added argument realm_hint. 1999-10-03 Assar Westerlund * afskrb5.c (get_cred): update to new krb524_convert_creds_kdc 1999-08-12 Johan Danielsson * Makefile.am: ignore the comlicated aix construct if !krb4 1999-07-26 Assar Westerlund * Makefile.am: set version to 1:0:1 1999-07-22 Assar Westerlund * afssysdefs.h: define AFS_SYSCALL to 73 for Solaris 2.7 1999-07-07 Assar Westerlund * afskrb5.c (krb5_realm_of_cell): new function * afskrb.c (krb_realm_of_cell): new function (afslog_uid_int): call krb_get_lrealm correctly 1999-06-15 Assar Westerlund * common.c (realm_of_cell): rename to _kafs_realm_of_cell and un-staticize Fri Mar 19 14:52:29 1999 Johan Danielsson * Makefile.am: add version-info Thu Mar 18 11:24:02 1999 Johan Danielsson * Makefile.am: include Makefile.am.common Sat Feb 27 19:46:21 1999 Johan Danielsson * Makefile.am: remove EXTRA_DATA (as of autoconf 2.13/automake 1.4) Thu Feb 11 22:57:37 1999 Johan Danielsson * Makefile.am: set AIX_SRC also if !AIX Tue Dec 1 14:45:15 1998 Johan Danielsson * Makefile.am: fix AIX linkage Sun Nov 22 10:40:44 1998 Assar Westerlund * Makefile.in (WFLAGS): set Sat Nov 21 16:55:19 1998 Johan Danielsson * afskrb5.c: add homedir support Sun Sep 6 20:16:27 1998 Assar Westerlund * add new functionality for specifying the homedir to krb_afslog et al Thu Jul 16 01:27:19 1998 Assar Westerlund * afssys.c: reorganize order of definitions. (try_one, try_two): conditionalize Thu Jul 9 18:31:52 1998 Johan Danielsson * common.c (realm_of_cell): make the dns fallback work Wed Jul 8 01:39:44 1998 Assar Westerlund * afssys.c (map_syscall_name_to_number): new function for finding the number of a syscall given the name on solaris (k_hasafs): try using map_syscall_name_to_number Tue Jun 30 17:19:00 1998 Assar Westerlund * afssys.c: rewrite and add support for environment variable AFS_SYSCALL * Makefile.in (distclean): don't remove roken_rename.h Fri May 29 19:03:20 1998 Assar Westerlund * Makefile.in (roken_rename.h): remove dependency Mon May 25 05:25:54 1998 Assar Westerlund * Makefile.in (clean): try to remove shared library debris Sun Apr 19 09:58:40 1998 Assar Westerlund * Makefile.in: add symlink magic for linux Sat Apr 4 15:08:48 1998 Assar Westerlund * kafs.h: add arla paths * common.c (_kafs_afslog_all_local_cells): Try _PATH_ARLA_* (_realm_of_cell): Try _PATH_ARLA_CELLSERVDB Thu Feb 19 14:50:22 1998 Johan Danielsson * common.c: Don't store expired tokens (this broke when using pag-less rsh-sessions, and `non-standard' ticket files). Thu Feb 12 11:20:15 1998 Johan Danielsson * Makefile.in: Install/uninstall one library at a time. Thu Feb 12 05:38:58 1998 Assar Westerlund * Makefile.in (install): one library at a time. Mon Feb 9 23:40:32 1998 Assar Westerlund * common.c (find_cells): ignore empty lines Tue Jan 6 04:25:58 1998 Assar Westerlund * afssysdefs.h (AFS_SYSCALL): add FreeBSD Fri Jan 2 17:08:24 1998 Assar Westerlund * kafs.h: new VICEIOCTL's. From * afssysdefs.h: Add OpenBSD heimdal-7.5.0/lib/kafs/afslib.c0000644000175000017500000000362712136107750014362 0ustar niknik/* * Copyright (c) 1995, 1996, 1997 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ /* * This file is only used with AIX */ #include "kafs_locl.h" int aix_pioctl(char *a_path, int o_opcode, struct ViceIoctl *a_paramsP, int a_followSymlinks) { return lpioctl(a_path, o_opcode, a_paramsP, a_followSymlinks); } int aix_setpag(void) { return lsetpag(); } heimdal-7.5.0/lib/kafs/afslib.exp0000644000175000017500000000003112136107750014716 0ustar niknik#! aix_pioctl aix_setpag heimdal-7.5.0/lib/kafs/Makefile.am0000644000175000017500000000327213026237312015003 0ustar niknik# $Id$ include $(top_srcdir)/Makefile.am.common AM_CPPFLAGS += $(AFS_EXTRA_DEFS) $(ROKEN_RENAME) if KRB5 DEPLIB_krb5 = ../krb5/libkrb5.la $(LIB_hcrypto) krb5_am_workaround = -I$(top_srcdir)/lib/krb5 else DEPLIB_krb5 = krb5_am_workaround = endif # KRB5 AM_CPPFLAGS += $(krb5_am_workaround) if AIX AFSL_EXP = $(srcdir)/afsl.exp if AIX4 AFS_EXTRA_LD = -bnoentry else AFS_EXTRA_LD = -e _nostart endif if AIX_DYNAMIC_AFS AIX_SRC = AFS_EXTRA_LIBS = afslib.so AFS_EXTRA_DEFS = else AIX_SRC = afslib.c AFS_EXTRA_LIBS = AFS_EXTRA_DEFS = -DSTATIC_AFS endif else AFSL_EXP = AIX_SRC = endif # AIX libkafs_la_LIBADD = $(DEPLIB_krb5) $(LIBADD_roken) lib_LTLIBRARIES = libkafs.la libkafs_la_LDFLAGS = -version-info 5:1:5 foodir = $(libdir) foo_DATA = $(AFS_EXTRA_LIBS) # EXTRA_DATA = afslib.so CLEANFILES= $(AFS_EXTRA_LIBS) $(ROKEN_SRCS) include_HEADERS = kafs.h if KRB5 afskrb5_c = endif if do_roken_rename ROKEN_SRCS = resolve.c strtok_r.c strlcpy.c strsep.c endif dist_libkafs_la_SOURCES = \ afssys.c \ afskrb5.c \ rxkad_kdf.c \ common.c \ $(AIX_SRC) \ kafs_locl.h \ afssysdefs.h \ roken_rename.h nodist_libkafs_la_SOURCES = $(ROKEN_SRCS) EXTRA_libkafs_la_SOURCES = afskrb5.c afslib.c EXTRA_DIST = NTMakefile afsl.exp afslib.exp $(man_MANS) man_MANS = kafs.3 # AIX: this almost works with gcc, but somehow it fails to use the # correct ld, use ld instead afslib.so: afslib.o ld -o $@ -bM:SRE -bI:$(srcdir)/afsl.exp -bE:$(srcdir)/afslib.exp $(AFS_EXTRA_LD) afslib.o -lc resolve.c: $(LN_S) $(srcdir)/../roken/resolve.c . strtok_r.c: $(LN_S) $(srcdir)/../roken/strtok_r.c . strlcpy.c: $(LN_S) $(srcdir)/../roken/strlcpy.c . strsep.c: $(LN_S) $(srcdir)/../roken/strsep.c . heimdal-7.5.0/lib/kafs/kafs.30000644000175000017500000001750513026237312013763 0ustar niknik.\" Copyright (c) 1998 - 2006 Kungliga Tekniska Högskolan .\" (Royal Institute of Technology, Stockholm, Sweden). .\" All rights reserved. .\" .\" Redistribution and use in source and binary forms, with or without .\" modification, are permitted provided that the following conditions .\" are met: .\" .\" 1. Redistributions of source code must retain the above copyright .\" notice, this list of conditions and the following disclaimer. .\" .\" 2. Redistributions in binary form must reproduce the above copyright .\" notice, this list of conditions and the following disclaimer in the .\" documentation and/or other materials provided with the distribution. .\" .\" 3. Neither the name of the Institute nor the names of its contributors .\" may be used to endorse or promote products derived from this software .\" without specific prior written permission. .\" .\" THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND .\" ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE .\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE .\" ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE .\" FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL .\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS .\" OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) .\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT .\" LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF .\" SUCH DAMAGE. .\" .\" $Id$ .\" .Dd May 1, 2006 .Os HEIMDAL .Dt KAFS 3 .Sh NAME .Nm k_hasafs , .Nm k_hasafs_recheck , .Nm k_pioctl , .Nm k_unlog , .Nm k_setpag , .Nm k_afs_cell_of_file , .Nm kafs_set_verbose , .Nm kafs_settoken_rxkad , .Nm kafs_settoken , .Nm krb_afslog , .Nm krb_afslog_uid , .Nm kafs_settoken5 , .Nm krb5_afslog , .Nm krb5_afslog_uid .Nd AFS library .Sh LIBRARY AFS cache manager access library (libkafs, -lkafs) .Sh SYNOPSIS .In kafs.h .Ft int .Fn k_afs_cell_of_file "const char *path" "char *cell" "int len" .Ft int .Fn k_hasafs "void" .Ft int .Fn k_hasafs_recheck "void" .Ft int .Fn k_pioctl "char *a_path" "int o_opcode" "struct ViceIoctl *a_paramsP" "int a_followSymlinks" .Ft int .Fn k_setpag "void" .Ft int .Fn k_unlog "void" .Ft void .Fn kafs_set_verbose "void (*func)(void *, const char *, int)" "void *" .Ft int .Fn kafs_settoken_rxkad "const char *cell" "struct ClearToken *token" "void *ticket" "size_t ticket_len" .Ft int .Fn kafs_settoken "const char *cell" "uid_t uid" "CREDENTIALS *c" .Fn krb_afslog "char *cell" "char *realm" .Ft int .Fn krb_afslog_uid "char *cell" "char *realm" "uid_t uid" .Ft krb5_error_code .Fn krb5_afslog_uid "krb5_context context" "krb5_ccache id" "const char *cell" "krb5_const_realm realm" "uid_t uid" .Ft int .Fn kafs_settoken5 "const char *cell" "uid_t uid" "krb5_creds *c" .Ft krb5_error_code .Fn krb5_afslog "krb5_context context" "krb5_ccache id" "const char *cell" "krb5_const_realm realm" .Sh DESCRIPTION .Fn k_hasafs initializes some library internal structures, and tests for the presence of AFS in the kernel, none of the other functions should be called before .Fn k_hasafs is called, or if it fails. .Pp .Fn k_hasafs_recheck forces a recheck if a AFS client has started since last time .Fn k_hasafs or .Fn k_hasafs_recheck was called. .Pp .Fn kafs_set_verbose set a log function that will be called each time the kafs library does something important so that the application using libkafs can output verbose logging. Calling the function .Fa kafs_set_verbose with the function argument set to .Dv NULL will stop libkafs from calling the logging function (if set). .Pp .Fn kafs_settoken_rxkad set .Li rxkad with the .Fa token and .Fa ticket (that have the length .Fa ticket_len ) for a given .Fa cell . .Pp .Fn kafs_settoken and .Fn kafs_settoken5 work the same way as .Fn kafs_settoken_rxkad but internally converts the Kerberos 4 or 5 credential to a afs cleartoken and ticket. .Pp .Fn krb_afslog , and .Fn krb_afslog_uid obtains new tokens (and possibly tickets) for the specified .Fa cell and .Fa realm . If .Fa cell is .Dv NULL , the local cell is used. If .Fa realm is .Dv NULL , the function tries to guess what realm to use. Unless you have some good knowledge of what cell or realm to use, you should pass .Dv NULL . .Fn krb_afslog will use the real user-id for the .Dv ViceId field in the token, .Fn krb_afslog_uid will use .Fa uid . .Pp .Fn krb5_afslog , and .Fn krb5_afslog_uid are the Kerberos 5 equivalents of .Fn krb_afslog , and .Fn krb_afslog_uid . .Pp .Fn krb5_afslog , .Fn kafs_settoken5 can be configured to behave differently via a .Nm krb5_appdefault option .Li afs-use-524 in .Pa krb5.conf . Possible values for .Li afs-use-524 are: .Bl -tag -width local .It yes use the 524 server in the realm to convert the ticket .It no use the Kerberos 5 ticket directly, can be used with if the afs cell support 2b token. .It local, 2b convert the Kerberos 5 credential to a 2b token locally (the same work as a 2b 524 server should have done). .El .Pp Example: .Pp .Bd -literal [appdefaults] SU.SE = { afs-use-524 = local } PDC.KTH.SE = { afs-use-524 = yes } afs-use-524 = yes .Ed .Pp libkafs will use the .Li libkafs as application name when running the .Nm krb5_appdefault function call. .Pp The (uppercased) cell name is used as the realm to the .Nm krb5_appdefault function. .Pp .\" The extra arguments are the ubiquitous context, and the cache id where .\" to store any obtained tickets. Since AFS servers normally can't handle .\" Kerberos 5 tickets directly, these functions will first obtain version .\" 5 tickets for the requested cells, and then convert them to version 4 .\" tickets, that can be stashed in the kernel. To convert tickets the .\" .Fn krb524_convert_creds_kdc .\" function will be used. .\" .Pp .Fn k_afs_cell_of_file will in .Fa cell return the cell of a specified file, no more than .Fa len characters is put in .Fa cell . .Pp .Fn k_pioctl does a .Fn pioctl system call with the specified arguments. This function is equivalent to .Fn lpioctl . .Pp .Fn k_setpag initializes a new PAG. .Pp .Fn k_unlog removes destroys all tokens in the current PAG. .Sh RETURN VALUES .Fn k_hasafs returns 1 if AFS is present in the kernel, 0 otherwise. .Fn krb_afslog and .Fn krb_afslog_uid returns 0 on success, or a Kerberos error number on failure. .Fn k_afs_cell_of_file , .Fn k_pioctl , .Fn k_setpag , and .Fn k_unlog all return the value of the underlaying system call, 0 on success. .Sh ENVIRONMENT The following environment variable affect the mode of operation of .Nm kafs : .Bl -tag -width AFS_SYSCALL .It Ev AFS_SYSCALL Normally, .Nm kafs will try to figure out the correct system call(s) that are used by AFS by itself. If it does not manage to do that, or does it incorrectly, you can set this variable to the system call number or list of system call numbers that should be used. .El .Sh EXAMPLES The following code from .Nm login will obtain a new PAG and tokens for the local cell and the cell of the users home directory. .Bd -literal if (k_hasafs()) { char cell[64]; k_setpag(); if(k_afs_cell_of_file(pwd->pw_dir, cell, sizeof(cell)) == 0) krb_afslog(cell, NULL); krb_afslog(NULL, NULL); } .Ed .Sh ERRORS If any of these functions (apart from .Fn k_hasafs ) is called without AFS being present in the kernel, the process will usually (depending on the operating system) receive a SIGSYS signal. .Sh SEE ALSO .Xr krb5_appdefault 3 , .Xr krb5.conf 5 .Rs .%A Transarc Corporation .%J AFS-3 Programmer's Reference .%T File Server/Cache Manager Interface .%D 1991 .Re .Sh FILES libkafs will search for .Pa ThisCell and .Pa TheseCells in the following locations: .Pa /usr/vice/etc , .Pa /etc/openafs , .Pa /var/db/openafs/etc , .Pa /usr/arla/etc , .Pa /etc/arla , and .Pa /etc/afs .Sh BUGS .Ev AFS_SYSCALL has no effect under AIX. heimdal-7.5.0/lib/kafs/rxkad_kdf.c0000644000175000017500000001724213026237312015052 0ustar niknik/* * Copyright (c) 1995-2003 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Portions Copyright (c) 2013-2014 Carnegie Mellon University * All rights reserved. * * Portions Copyright (c) 2013 by the Massachusetts Institute of Technology * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "kafs_locl.h" static int rxkad_derive_des_key(const void *, size_t, char[8]); static int compress_parity_bits(void *, size_t *); /** * Use NIST SP800-108 with HMAC(MD5) in counter mode as the PRF to derive a * des key from another type of key. * * L is 64, as we take 64 random bits and turn them into a 56-bit des key. * The output of hmac_md5 is 128 bits; we take the first 64 only, so n * properly should be 1. However, we apply a slight variation due to the * possibility of producing a weak des key. If the output key is weak, do NOT * simply correct it, instead, the counter is advanced and the next output * used. As such, we code so as to have n be the full 255 permitted by our * encoding of the counter i in an 8-bit field. L itself is encoded as a * 32-bit field, big-endian. We use the constant string "rxkad" as a label * for this key derivation, the standard NUL byte separator, and omit a * key-derivation context. The input key is unique to the krb5 service ticket, * which is unlikely to be used in an other location. If it is used in such * a fashion, both locations will derive the same des key from the PRF, but * this is no different from if a krb5 des key had been used in the same way, * as traditional krb5 rxkad uses the ticket session key directly as the token * key. * * @param[in] in pointer to input key data * @param[in] insize length of input key data * @param[out] out 8-byte buffer to hold the derived key * * @return Returns 0 to indicate success, or an error code. * * @retval KRB5DES_WEAK_KEY Successive derivation attempts with all * 255 possible counter values each produced weak DES keys. This input * cannot be used to produce a usable key. */ static int rxkad_derive_des_key(const void *in, size_t insize, char out[8]) { unsigned char i; static unsigned char label[] = "rxkad"; /* bits of output, as 32 bit word, MSB first */ static unsigned char Lbuf[4] = { 0, 0, 0, 64 }; /* only needs to be 16 for md5, but lets be sure it fits */ unsigned char tmp[64]; unsigned int mdsize; DES_cblock ktmp; HMAC_CTX mctx; /* stop when 8 bit counter wraps to 0 */ for (i = 1; i; i++) { HMAC_CTX_init(&mctx); HMAC_Init_ex(&mctx, in, insize, EVP_md5(), NULL); HMAC_Update(&mctx, &i, 1); HMAC_Update(&mctx, label, sizeof(label)); /* includes label and separator */ HMAC_Update(&mctx, Lbuf, 4); mdsize = sizeof(tmp); HMAC_Final(&mctx, tmp, &mdsize); memcpy(ktmp, tmp, 8); DES_set_odd_parity(&ktmp); if (!DES_is_weak_key(&ktmp)) { memcpy(out, ktmp, 8); return 0; } } return KRB5DES_WEAK_KEY; } /** * This is the inverse of the random-to-key for 3des specified in * rfc3961, converting blocks of 8 bytes to blocks of 7 bytes by distributing * the bits of each 8th byte as the lsb of the previous 7 bytes. * * @param[in,out] buffer Buffer containing the key to be converted * @param[in,out] bufsiz Points to the size of the key data. On * return, this is updated to reflect the size of the compressed data. * * @return Returns 0 to indicate success, or an error code. * * @retval KRB5_BAD_KEYSIZE The key size was not a multiple of 8 bytes. */ static int compress_parity_bits(void *buffer, size_t *bufsiz) { unsigned char *cb, tmp; int i, j, nk; if (*bufsiz % 8 != 0) return KRB5_BAD_KEYSIZE; cb = (unsigned char *)buffer; nk = *bufsiz / 8; for (i = 0; i < nk; i++) { tmp = cb[8 * i + 7] >> 1; for (j = 0; j < 7; j++) { cb[8 * i + j] &= 0xfe; cb[8 * i + j] |= tmp & 0x1; tmp >>= 1; } } for (i = 1; i < nk; i++) memmove(cb + 7 * i, cb + 8 * i, 7); *bufsiz = 7 * nk; return 0; } /** * Derive a DES key for use with rxkad and fcrypt from a given Kerberos * key of (almost) any type. This function encodes enctype-specific * knowledge about how to derive a DES key from a given key type. * If given a des key, use it directly; otherwise, perform any parity * fixup that may be needed and pass through to the hmad-md5 bits. * * @param[in] enctype Kerberos enctype of the input key * @param[in] keydata Input key data * @param[in] keylen Size of input key data * @param[out] output 8-byte buffer to hold the derived key * * @return Returns 0 to indicate success, or an error code. * * @retval KRB5_PROG_ETYPE_NOSUPP The enctype is one for which rxkad-kdf * is not supported. This includes several reserved enctypes, enctype * values used in PKINIT to stand for CMS algorithm identifiers, and all * private-use (negative) enctypes. * * @retval KRB5_BAD_KEYSIZE The key size was not a multiple of 8 bytes * (for 3DES key types), exactly 8 bytes (for DES key types), or at least * 8 bytes (for other key types). * * @retval KRB5DES_WEAK_KEY Successive derivation attempts with all * 255 possible counter values each produced weak DES keys. This input * cannot be used to produce a usable key. */ int _kafs_derive_des_key(krb5_enctype enctype, void *keydata, size_t keylen, char output[8]) { int ret = 0; switch ((int)enctype) { case ETYPE_DES_CBC_CRC: case ETYPE_DES_CBC_MD4: case ETYPE_DES_CBC_MD5: if (keylen != 8) return KRB5_BAD_KEYSIZE; /* Extract session key */ memcpy(output, keydata, 8); break; case ETYPE_NULL: case 4: case 6: case 8: case 9: case 10: case 11: case 12: case 13: case 14: case 15: return KRB5_PROG_ETYPE_NOSUPP; /*In order to become a "Cryptographic Key" as specified in * SP800-108, it must be indistinguishable from a random bitstring. */ case ETYPE_DES3_CBC_MD5: case ETYPE_OLD_DES3_CBC_SHA1: case ETYPE_DES3_CBC_SHA1: ret = compress_parity_bits(keydata, &keylen); if (ret) return ret; /* FALLTHROUGH */ default: if (enctype < 0) return KRB5_PROG_ETYPE_NOSUPP; if (keylen < 7) return KRB5_BAD_KEYSIZE; ret = rxkad_derive_des_key(keydata, keylen, output); } return ret; } heimdal-7.5.0/lib/kafs/kafs_locl.h0000644000175000017500000001017213026237312015052 0ustar niknik/* * Copyright (c) 1995, 1996, 1997, 1998, 1999 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ /* $Id$ */ #ifndef __KAFS_LOCL_H__ #define __KAFS_LOCL_H__ #ifdef HAVE_CONFIG_H #include #endif #include #include #include #include #include #include #ifdef HAVE_SYS_TYPES_H #include #endif #ifdef HAVE_UNISTD_H #include #endif #if defined(HAVE_SYS_IOCTL_H) && SunOS != 40 #include #endif #ifdef HAVE_SYS_FILIO_H #include #endif #ifdef HAVE_SYS_SYSCTL_H #include #endif #ifdef HAVE_SYS_SYSCALL_H #include #endif #ifdef HAVE_SYS_SOCKET_H #include #endif #ifdef HAVE_NETINET_IN_H #include #endif #ifdef HAVE_NETINET_IN6_H #include #endif #ifdef HAVE_NETINET6_IN6_H #include #endif #ifdef HAVE_NETDB_H #include #endif #ifdef HAVE_ARPA_NAMESER_H #include #endif #ifdef HAVE_RESOLV_H #include #endif #include #ifdef KRB5 #include #endif #ifdef KRB5 #include "crypto-headers.h" #include typedef struct credentials CREDENTIALS; #endif /* KRB5 */ #ifndef NO_AFS #include #endif #include #include "afssysdefs.h" struct kafs_data; struct kafs_token; typedef int (*afslog_uid_func_t)(struct kafs_data *, const char *, const char *, uid_t, const char *); typedef int (*get_cred_func_t)(struct kafs_data*, const char*, const char*, const char*, uid_t, struct kafs_token *); typedef char* (*get_realm_func_t)(struct kafs_data*, const char*); struct kafs_data { const char *name; afslog_uid_func_t afslog_uid; get_cred_func_t get_cred; get_realm_func_t get_realm; const char *(*get_error)(struct kafs_data *, int); void (*free_error)(struct kafs_data *, const char *); void *data; }; struct kafs_token { struct ClearToken ct; void *ticket; size_t ticket_len; }; void _kafs_foldup(char *, const char *); int _kafs_afslog_all_local_cells(struct kafs_data*, uid_t, const char*); int _kafs_get_cred(struct kafs_data*, const char*, const char*, const char *, uid_t, struct kafs_token *); int _kafs_realm_of_cell(struct kafs_data *, const char *, char **); int _kafs_v4_to_kt(CREDENTIALS *, uid_t, struct kafs_token *); void _kafs_fixup_viceid(struct ClearToken *, uid_t); int _kafs_derive_des_key(krb5_enctype, void *, size_t, char[8]); #ifdef _AIX int aix_pioctl(char*, int, struct ViceIoctl*, int); int aix_setpag(void); #endif #endif /* __KAFS_LOCL_H__ */ heimdal-7.5.0/lib/kafs/Makefile.in0000644000175000017500000011451113212444522015013 0ustar niknik# Makefile.in generated by automake 1.15.1 from Makefile.am. # @configure_input@ # Copyright (C) 1994-2017 Free Software Foundation, Inc. # This Makefile.in is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, # with or without modifications, as long as this notice is preserved. # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY, to the extent permitted by law; without # even the implied warranty of MERCHANTABILITY or FITNESS FOR A # PARTICULAR PURPOSE. @SET_MAKE@ # $Id$ # $Id$ # $Id$ VPATH = @srcdir@ am__is_gnu_make = { \ if test -z '$(MAKELEVEL)'; then \ false; \ elif test -n '$(MAKE_HOST)'; then \ true; \ elif test -n '$(MAKE_VERSION)' && test -n '$(CURDIR)'; then \ true; \ else \ false; \ fi; \ } am__make_running_with_option = \ case $${target_option-} in \ ?) ;; \ *) echo "am__make_running_with_option: internal error: invalid" \ "target option '$${target_option-}' specified" >&2; \ exit 1;; \ esac; \ has_opt=no; \ sane_makeflags=$$MAKEFLAGS; \ if $(am__is_gnu_make); then \ sane_makeflags=$$MFLAGS; \ else \ case $$MAKEFLAGS in \ *\\[\ \ ]*) \ bs=\\; \ sane_makeflags=`printf '%s\n' "$$MAKEFLAGS" \ | sed "s/$$bs$$bs[$$bs $$bs ]*//g"`;; \ esac; \ fi; \ skip_next=no; \ strip_trailopt () \ { \ flg=`printf '%s\n' "$$flg" | sed "s/$$1.*$$//"`; \ }; \ for flg in $$sane_makeflags; do \ test $$skip_next = yes && { skip_next=no; continue; }; \ case $$flg in \ *=*|--*) continue;; \ -*I) strip_trailopt 'I'; skip_next=yes;; \ -*I?*) strip_trailopt 'I';; \ -*O) strip_trailopt 'O'; skip_next=yes;; \ -*O?*) strip_trailopt 'O';; \ -*l) strip_trailopt 'l'; skip_next=yes;; \ -*l?*) strip_trailopt 'l';; \ -[dEDm]) skip_next=yes;; \ -[JT]) skip_next=yes;; \ esac; \ case $$flg in \ *$$target_option*) has_opt=yes; break;; \ esac; \ done; \ test $$has_opt = yes am__make_dryrun = (target_option=n; $(am__make_running_with_option)) am__make_keepgoing = (target_option=k; $(am__make_running_with_option)) pkgdatadir = $(datadir)/@PACKAGE@ pkgincludedir = $(includedir)/@PACKAGE@ pkglibdir = $(libdir)/@PACKAGE@ pkglibexecdir = $(libexecdir)/@PACKAGE@ am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd install_sh_DATA = $(install_sh) -c -m 644 install_sh_PROGRAM = $(install_sh) -c install_sh_SCRIPT = $(install_sh) -c INSTALL_HEADER = $(INSTALL_DATA) transform = $(program_transform_name) NORMAL_INSTALL = : PRE_INSTALL = : POST_INSTALL = : NORMAL_UNINSTALL = : PRE_UNINSTALL = : POST_UNINSTALL = : build_triplet = @build@ host_triplet = @host@ subdir = lib/kafs ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 am__aclocal_m4_deps = $(top_srcdir)/cf/aix.m4 \ $(top_srcdir)/cf/auth-modules.m4 \ $(top_srcdir)/cf/broken-getaddrinfo.m4 \ $(top_srcdir)/cf/broken-glob.m4 \ $(top_srcdir)/cf/broken-realloc.m4 \ $(top_srcdir)/cf/broken-snprintf.m4 $(top_srcdir)/cf/broken.m4 \ $(top_srcdir)/cf/broken2.m4 $(top_srcdir)/cf/c-attribute.m4 \ $(top_srcdir)/cf/capabilities.m4 \ $(top_srcdir)/cf/check-compile-et.m4 \ $(top_srcdir)/cf/check-getpwnam_r-posix.m4 \ $(top_srcdir)/cf/check-man.m4 \ $(top_srcdir)/cf/check-netinet-ip-and-tcp.m4 \ $(top_srcdir)/cf/check-type-extra.m4 \ $(top_srcdir)/cf/check-var.m4 $(top_srcdir)/cf/crypto.m4 \ $(top_srcdir)/cf/db.m4 $(top_srcdir)/cf/destdirs.m4 \ $(top_srcdir)/cf/dispatch.m4 $(top_srcdir)/cf/dlopen.m4 \ $(top_srcdir)/cf/find-func-no-libs.m4 \ $(top_srcdir)/cf/find-func-no-libs2.m4 \ $(top_srcdir)/cf/find-func.m4 \ $(top_srcdir)/cf/find-if-not-broken.m4 \ $(top_srcdir)/cf/framework-security.m4 \ $(top_srcdir)/cf/have-struct-field.m4 \ $(top_srcdir)/cf/have-type.m4 $(top_srcdir)/cf/irix.m4 \ $(top_srcdir)/cf/krb-bigendian.m4 \ $(top_srcdir)/cf/krb-func-getlogin.m4 \ $(top_srcdir)/cf/krb-ipv6.m4 $(top_srcdir)/cf/krb-prog-ln-s.m4 \ $(top_srcdir)/cf/krb-prog-perl.m4 \ $(top_srcdir)/cf/krb-readline.m4 \ $(top_srcdir)/cf/krb-struct-spwd.m4 \ $(top_srcdir)/cf/krb-struct-winsize.m4 \ $(top_srcdir)/cf/largefile.m4 $(top_srcdir)/cf/libtool.m4 \ $(top_srcdir)/cf/ltoptions.m4 $(top_srcdir)/cf/ltsugar.m4 \ $(top_srcdir)/cf/ltversion.m4 $(top_srcdir)/cf/lt~obsolete.m4 \ $(top_srcdir)/cf/mips-abi.m4 $(top_srcdir)/cf/misc.m4 \ $(top_srcdir)/cf/need-proto.m4 $(top_srcdir)/cf/osfc2.m4 \ $(top_srcdir)/cf/otp.m4 $(top_srcdir)/cf/pkg.m4 \ $(top_srcdir)/cf/proto-compat.m4 $(top_srcdir)/cf/pthreads.m4 \ $(top_srcdir)/cf/resolv.m4 $(top_srcdir)/cf/retsigtype.m4 \ $(top_srcdir)/cf/roken-frag.m4 \ $(top_srcdir)/cf/socket-wrapper.m4 $(top_srcdir)/cf/sunos.m4 \ $(top_srcdir)/cf/telnet.m4 $(top_srcdir)/cf/test-package.m4 \ $(top_srcdir)/cf/version-script.m4 $(top_srcdir)/cf/wflags.m4 \ $(top_srcdir)/cf/win32.m4 $(top_srcdir)/cf/with-all.m4 \ $(top_srcdir)/acinclude.m4 $(top_srcdir)/configure.ac am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \ $(ACLOCAL_M4) DIST_COMMON = $(srcdir)/Makefile.am $(include_HEADERS) \ $(am__DIST_COMMON) mkinstalldirs = $(install_sh) -d CONFIG_HEADER = $(top_builddir)/include/config.h CONFIG_CLEAN_FILES = CONFIG_CLEAN_VPATH_FILES = am__vpath_adj_setup = srcdirstrip=`echo "$(srcdir)" | sed 's|.|.|g'`; am__vpath_adj = case $$p in \ $(srcdir)/*) f=`echo "$$p" | sed "s|^$$srcdirstrip/||"`;; \ *) f=$$p;; \ esac; am__strip_dir = f=`echo $$p | sed -e 's|^.*/||'`; am__install_max = 40 am__nobase_strip_setup = \ srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*|]/\\\\&/g'` am__nobase_strip = \ for p in $$list; do echo "$$p"; done | sed -e "s|$$srcdirstrip/||" am__nobase_list = $(am__nobase_strip_setup); \ for p in $$list; do echo "$$p $$p"; done | \ sed "s| $$srcdirstrip/| |;"' / .*\//!s/ .*/ ./; s,\( .*\)/[^/]*$$,\1,' | \ $(AWK) 'BEGIN { files["."] = "" } { files[$$2] = files[$$2] " " $$1; \ if (++n[$$2] == $(am__install_max)) \ { print $$2, files[$$2]; n[$$2] = 0; files[$$2] = "" } } \ END { for (dir in files) print dir, files[dir] }' am__base_list = \ sed '$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;s/\n/ /g' | \ sed '$$!N;$$!N;$$!N;$$!N;s/\n/ /g' am__uninstall_files_from_dir = { \ test -z "$$files" \ || { test ! -d "$$dir" && test ! -f "$$dir" && test ! -r "$$dir"; } \ || { echo " ( cd '$$dir' && rm -f" $$files ")"; \ $(am__cd) "$$dir" && rm -f $$files; }; \ } am__installdirs = "$(DESTDIR)$(libdir)" "$(DESTDIR)$(man3dir)" \ "$(DESTDIR)$(foodir)" "$(DESTDIR)$(includedir)" LTLIBRARIES = $(lib_LTLIBRARIES) am__DEPENDENCIES_1 = @KRB5_TRUE@am__DEPENDENCIES_2 = ../krb5/libkrb5.la \ @KRB5_TRUE@ $(am__DEPENDENCIES_1) libkafs_la_DEPENDENCIES = $(am__DEPENDENCIES_2) $(am__DEPENDENCIES_1) am__dist_libkafs_la_SOURCES_DIST = afssys.c afskrb5.c rxkad_kdf.c \ common.c afslib.c kafs_locl.h afssysdefs.h roken_rename.h @AIX_DYNAMIC_AFS_FALSE@@AIX_TRUE@am__objects_1 = afslib.lo dist_libkafs_la_OBJECTS = afssys.lo afskrb5.lo rxkad_kdf.lo common.lo \ $(am__objects_1) @do_roken_rename_TRUE@am__objects_2 = resolve.lo strtok_r.lo \ @do_roken_rename_TRUE@ strlcpy.lo strsep.lo nodist_libkafs_la_OBJECTS = $(am__objects_2) libkafs_la_OBJECTS = $(dist_libkafs_la_OBJECTS) \ $(nodist_libkafs_la_OBJECTS) AM_V_lt = $(am__v_lt_@AM_V@) am__v_lt_ = $(am__v_lt_@AM_DEFAULT_V@) am__v_lt_0 = --silent am__v_lt_1 = libkafs_la_LINK = $(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) \ $(LIBTOOLFLAGS) --mode=link $(CCLD) $(AM_CFLAGS) $(CFLAGS) \ $(libkafs_la_LDFLAGS) $(LDFLAGS) -o $@ AM_V_P = $(am__v_P_@AM_V@) am__v_P_ = $(am__v_P_@AM_DEFAULT_V@) am__v_P_0 = false am__v_P_1 = : AM_V_GEN = $(am__v_GEN_@AM_V@) am__v_GEN_ = $(am__v_GEN_@AM_DEFAULT_V@) am__v_GEN_0 = @echo " GEN " $@; am__v_GEN_1 = AM_V_at = $(am__v_at_@AM_V@) am__v_at_ = $(am__v_at_@AM_DEFAULT_V@) am__v_at_0 = @ am__v_at_1 = depcomp = $(SHELL) $(top_srcdir)/depcomp am__depfiles_maybe = depfiles am__mv = mv -f COMPILE = $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) \ $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) LTCOMPILE = $(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) \ $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) \ $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) \ $(AM_CFLAGS) $(CFLAGS) AM_V_CC = $(am__v_CC_@AM_V@) am__v_CC_ = $(am__v_CC_@AM_DEFAULT_V@) am__v_CC_0 = @echo " CC " $@; am__v_CC_1 = CCLD = $(CC) LINK = $(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) \ $(LIBTOOLFLAGS) --mode=link $(CCLD) $(AM_CFLAGS) $(CFLAGS) \ $(AM_LDFLAGS) $(LDFLAGS) -o $@ AM_V_CCLD = $(am__v_CCLD_@AM_V@) am__v_CCLD_ = $(am__v_CCLD_@AM_DEFAULT_V@) am__v_CCLD_0 = @echo " CCLD " $@; am__v_CCLD_1 = SOURCES = $(EXTRA_libkafs_la_SOURCES) $(dist_libkafs_la_SOURCES) \ $(nodist_libkafs_la_SOURCES) DIST_SOURCES = $(EXTRA_libkafs_la_SOURCES) \ $(am__dist_libkafs_la_SOURCES_DIST) am__can_run_installinfo = \ case $$AM_UPDATE_INFO_DIR in \ n|no|NO) false;; \ *) (install-info --version) >/dev/null 2>&1;; \ esac man3dir = $(mandir)/man3 MANS = $(man_MANS) DATA = $(foo_DATA) HEADERS = $(include_HEADERS) am__tagged_files = $(HEADERS) $(SOURCES) $(TAGS_FILES) $(LISP) # Read a list of newline-separated strings from the standard input, # and print each of them once, without duplicates. Input order is # *not* preserved. am__uniquify_input = $(AWK) '\ BEGIN { nonempty = 0; } \ { items[$$0] = 1; nonempty = 1; } \ END { if (nonempty) { for (i in items) print i; }; } \ ' # Make sure the list of sources is unique. This is necessary because, # e.g., the same source file might be shared among _SOURCES variables # for different programs/libraries. am__define_uniq_tagged_files = \ list='$(am__tagged_files)'; \ unique=`for i in $$list; do \ if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ done | $(am__uniquify_input)` ETAGS = etags CTAGS = ctags am__DIST_COMMON = $(srcdir)/Makefile.in \ $(top_srcdir)/Makefile.am.common \ $(top_srcdir)/cf/Makefile.am.common $(top_srcdir)/depcomp \ ChangeLog DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST) ACLOCAL = @ACLOCAL@ AIX_EXTRA_KAFS = @AIX_EXTRA_KAFS@ AMTAR = @AMTAR@ AM_DEFAULT_VERBOSITY = @AM_DEFAULT_VERBOSITY@ AR = @AR@ AS = @AS@ ASN1_COMPILE = @ASN1_COMPILE@ ASN1_COMPILE_DEP = @ASN1_COMPILE_DEP@ AUTOCONF = @AUTOCONF@ AUTOHEADER = @AUTOHEADER@ AUTOMAKE = @AUTOMAKE@ AWK = @AWK@ CANONICAL_HOST = @CANONICAL_HOST@ CAPNG_CFLAGS = @CAPNG_CFLAGS@ CAPNG_LIBS = @CAPNG_LIBS@ CATMAN = @CATMAN@ CATMANEXT = @CATMANEXT@ CC = @CC@ CCDEPMODE = @CCDEPMODE@ CFLAGS = @CFLAGS@ COMPILE_ET = @COMPILE_ET@ CPP = @CPP@ CPPFLAGS = @CPPFLAGS@ CYGPATH_W = @CYGPATH_W@ DB1LIB = @DB1LIB@ DB3LIB = @DB3LIB@ DBHEADER = @DBHEADER@ DEFS = @DEFS@ DEPDIR = @DEPDIR@ DIR_com_err = @DIR_com_err@ DIR_hdbdir = @DIR_hdbdir@ DIR_roken = @DIR_roken@ DLLTOOL = @DLLTOOL@ DSYMUTIL = @DSYMUTIL@ DUMPBIN = @DUMPBIN@ ECHO_C = @ECHO_C@ ECHO_N = @ECHO_N@ ECHO_T = @ECHO_T@ EGREP = @EGREP@ ENABLE_AFS_STRING_TO_KEY = @ENABLE_AFS_STRING_TO_KEY@ EXEEXT = @EXEEXT@ FGREP = @FGREP@ GCD_MIG = @GCD_MIG@ GREP = @GREP@ GROFF = @GROFF@ INCLUDES_roken = @INCLUDES_roken@ INCLUDE_libedit = @INCLUDE_libedit@ INCLUDE_libintl = @INCLUDE_libintl@ INCLUDE_openldap = @INCLUDE_openldap@ INCLUDE_openssl_crypto = @INCLUDE_openssl_crypto@ INCLUDE_readline = @INCLUDE_readline@ INCLUDE_sqlite3 = @INCLUDE_sqlite3@ INSTALL = @INSTALL@ INSTALL_DATA = @INSTALL_DATA@ INSTALL_PROGRAM = @INSTALL_PROGRAM@ INSTALL_SCRIPT = @INSTALL_SCRIPT@ INSTALL_STRIP_PROGRAM = @INSTALL_STRIP_PROGRAM@ LD = @LD@ LDFLAGS = @LDFLAGS@ LDFLAGS_VERSION_SCRIPT = @LDFLAGS_VERSION_SCRIPT@ LEX = @LEX@ LEXLIB = @LEXLIB@ LEX_OUTPUT_ROOT = @LEX_OUTPUT_ROOT@ LIBADD_roken = @LIBADD_roken@ LIBOBJS = @LIBOBJS@ LIBS = @LIBS@ LIBTOOL = @LIBTOOL@ LIB_AUTH_SUBDIRS = @LIB_AUTH_SUBDIRS@ LIB_bswap16 = @LIB_bswap16@ LIB_bswap32 = @LIB_bswap32@ LIB_bswap64 = @LIB_bswap64@ LIB_com_err = @LIB_com_err@ LIB_com_err_a = @LIB_com_err_a@ LIB_com_err_so = @LIB_com_err_so@ LIB_crypt = @LIB_crypt@ LIB_db_create = @LIB_db_create@ LIB_dbm_firstkey = @LIB_dbm_firstkey@ LIB_dbopen = @LIB_dbopen@ LIB_dispatch_async_f = @LIB_dispatch_async_f@ LIB_dladdr = @LIB_dladdr@ LIB_dlopen = @LIB_dlopen@ LIB_dn_expand = @LIB_dn_expand@ LIB_dns_search = @LIB_dns_search@ LIB_door_create = @LIB_door_create@ LIB_freeaddrinfo = @LIB_freeaddrinfo@ LIB_gai_strerror = @LIB_gai_strerror@ LIB_getaddrinfo = @LIB_getaddrinfo@ LIB_gethostbyname = @LIB_gethostbyname@ LIB_gethostbyname2 = @LIB_gethostbyname2@ LIB_getnameinfo = @LIB_getnameinfo@ LIB_getpwnam_r = @LIB_getpwnam_r@ LIB_getsockopt = @LIB_getsockopt@ LIB_hcrypto = @LIB_hcrypto@ LIB_hcrypto_a = @LIB_hcrypto_a@ LIB_hcrypto_appl = @LIB_hcrypto_appl@ LIB_hcrypto_so = @LIB_hcrypto_so@ LIB_hstrerror = @LIB_hstrerror@ LIB_kdb = @LIB_kdb@ LIB_libedit = @LIB_libedit@ LIB_libintl = @LIB_libintl@ LIB_loadquery = @LIB_loadquery@ LIB_logout = @LIB_logout@ LIB_logwtmp = @LIB_logwtmp@ LIB_openldap = @LIB_openldap@ LIB_openpty = @LIB_openpty@ LIB_openssl_crypto = @LIB_openssl_crypto@ LIB_otp = @LIB_otp@ LIB_pidfile = @LIB_pidfile@ LIB_readline = @LIB_readline@ LIB_res_ndestroy = @LIB_res_ndestroy@ LIB_res_nsearch = @LIB_res_nsearch@ LIB_res_search = @LIB_res_search@ LIB_roken = @LIB_roken@ LIB_security = @LIB_security@ LIB_setsockopt = @LIB_setsockopt@ LIB_socket = @LIB_socket@ LIB_sqlite3 = @LIB_sqlite3@ LIB_syslog = @LIB_syslog@ LIB_tgetent = @LIB_tgetent@ LIPO = @LIPO@ LMDBLIB = @LMDBLIB@ LN_S = @LN_S@ LTLIBOBJS = @LTLIBOBJS@ LT_SYS_LIBRARY_PATH = @LT_SYS_LIBRARY_PATH@ MAINT = @MAINT@ MAKEINFO = @MAKEINFO@ MANIFEST_TOOL = @MANIFEST_TOOL@ MKDIR_P = @MKDIR_P@ NDBMLIB = @NDBMLIB@ NM = @NM@ NMEDIT = @NMEDIT@ NO_AFS = @NO_AFS@ NROFF = @NROFF@ OBJDUMP = @OBJDUMP@ OBJEXT = @OBJEXT@ OTOOL = @OTOOL@ OTOOL64 = @OTOOL64@ PACKAGE = @PACKAGE@ PACKAGE_BUGREPORT = @PACKAGE_BUGREPORT@ PACKAGE_NAME = @PACKAGE_NAME@ PACKAGE_STRING = @PACKAGE_STRING@ PACKAGE_TARNAME = @PACKAGE_TARNAME@ PACKAGE_URL = @PACKAGE_URL@ PACKAGE_VERSION = @PACKAGE_VERSION@ PATH_SEPARATOR = @PATH_SEPARATOR@ PERL = @PERL@ PKG_CONFIG = @PKG_CONFIG@ PTHREAD_CFLAGS = @PTHREAD_CFLAGS@ PTHREAD_LDADD = @PTHREAD_LDADD@ PTHREAD_LIBADD = @PTHREAD_LIBADD@ RANLIB = @RANLIB@ SED = @SED@ SET_MAKE = @SET_MAKE@ SHELL = @SHELL@ SLC = @SLC@ SLC_DEP = @SLC_DEP@ STRIP = @STRIP@ VERSION = @VERSION@ VERSIONING = @VERSIONING@ WFLAGS = @WFLAGS@ WFLAGS_LITE = @WFLAGS_LITE@ YACC = @YACC@ YFLAGS = @YFLAGS@ abs_builddir = @abs_builddir@ abs_srcdir = @abs_srcdir@ abs_top_builddir = @abs_top_builddir@ abs_top_srcdir = @abs_top_srcdir@ ac_ct_AR = @ac_ct_AR@ ac_ct_CC = @ac_ct_CC@ ac_ct_DUMPBIN = @ac_ct_DUMPBIN@ am__include = @am__include@ am__leading_dot = @am__leading_dot@ am__quote = @am__quote@ am__tar = @am__tar@ am__untar = @am__untar@ bindir = @bindir@ build = @build@ build_alias = @build_alias@ build_cpu = @build_cpu@ build_os = @build_os@ build_vendor = @build_vendor@ builddir = @builddir@ datadir = @datadir@ datarootdir = @datarootdir@ db_type = @db_type@ db_type_preference = @db_type_preference@ docdir = @docdir@ dpagaix_cflags = @dpagaix_cflags@ dpagaix_ldadd = @dpagaix_ldadd@ dpagaix_ldflags = @dpagaix_ldflags@ dvidir = @dvidir@ exec_prefix = @exec_prefix@ host = @host@ host_alias = @host_alias@ host_cpu = @host_cpu@ host_os = @host_os@ host_vendor = @host_vendor@ htmldir = @htmldir@ includedir = @includedir@ infodir = @infodir@ install_sh = @install_sh@ libdir = @libdir@ libexecdir = @libexecdir@ localedir = @localedir@ localstatedir = @localstatedir@ mandir = @mandir@ mkdir_p = @mkdir_p@ oldincludedir = @oldincludedir@ pdfdir = @pdfdir@ prefix = @prefix@ program_transform_name = @program_transform_name@ psdir = @psdir@ sbindir = @sbindir@ sharedstatedir = @sharedstatedir@ srcdir = @srcdir@ subdirs = @subdirs@ sysconfdir = @sysconfdir@ target_alias = @target_alias@ top_build_prefix = @top_build_prefix@ top_builddir = @top_builddir@ top_srcdir = @top_srcdir@ SUFFIXES = .et .h .pc.in .pc .x .z .hx .1 .3 .5 .7 .8 .cat1 .cat3 \ .cat5 .cat7 .cat8 DEFAULT_INCLUDES = -I. -I$(srcdir) -I$(top_builddir)/include -I$(top_srcdir)/include AM_CPPFLAGS = $(INCLUDES_roken) $(AFS_EXTRA_DEFS) $(ROKEN_RENAME) \ $(krb5_am_workaround) @do_roken_rename_TRUE@ROKEN_RENAME = -DROKEN_RENAME AM_CFLAGS = $(WFLAGS) CP = cp buildinclude = $(top_builddir)/include LIB_XauReadAuth = @LIB_XauReadAuth@ LIB_el_init = @LIB_el_init@ LIB_getattr = @LIB_getattr@ LIB_getpwent_r = @LIB_getpwent_r@ LIB_odm_initialize = @LIB_odm_initialize@ LIB_setpcred = @LIB_setpcred@ INCLUDE_krb4 = @INCLUDE_krb4@ LIB_krb4 = @LIB_krb4@ libexec_heimdaldir = $(libexecdir)/heimdal NROFF_MAN = groff -mandoc -Tascii @NO_AFS_FALSE@LIB_kafs = $(top_builddir)/lib/kafs/libkafs.la $(AIX_EXTRA_KAFS) @NO_AFS_TRUE@LIB_kafs = @KRB5_TRUE@LIB_krb5 = $(top_builddir)/lib/krb5/libkrb5.la \ @KRB5_TRUE@ $(top_builddir)/lib/asn1/libasn1.la @KRB5_TRUE@LIB_gssapi = $(top_builddir)/lib/gssapi/libgssapi.la LIB_heimbase = $(top_builddir)/lib/base/libheimbase.la @DCE_TRUE@LIB_kdfs = $(top_builddir)/lib/kdfs/libkdfs.la #silent-rules heim_verbose = $(heim_verbose_$(V)) heim_verbose_ = $(heim_verbose_$(AM_DEFAULT_VERBOSITY)) heim_verbose_0 = @echo " GEN "$@; @KRB5_FALSE@DEPLIB_krb5 = @KRB5_TRUE@DEPLIB_krb5 = ../krb5/libkrb5.la $(LIB_hcrypto) @KRB5_FALSE@krb5_am_workaround = @KRB5_TRUE@krb5_am_workaround = -I$(top_srcdir)/lib/krb5 @AIX_FALSE@AFSL_EXP = @AIX_TRUE@AFSL_EXP = $(srcdir)/afsl.exp @AIX4_FALSE@@AIX_TRUE@AFS_EXTRA_LD = -e _nostart @AIX4_TRUE@@AIX_TRUE@AFS_EXTRA_LD = -bnoentry @AIX_DYNAMIC_AFS_FALSE@@AIX_TRUE@AIX_SRC = afslib.c @AIX_DYNAMIC_AFS_TRUE@@AIX_TRUE@AIX_SRC = @AIX_FALSE@AIX_SRC = @AIX_DYNAMIC_AFS_FALSE@@AIX_TRUE@AFS_EXTRA_LIBS = @AIX_DYNAMIC_AFS_TRUE@@AIX_TRUE@AFS_EXTRA_LIBS = afslib.so @AIX_DYNAMIC_AFS_FALSE@@AIX_TRUE@AFS_EXTRA_DEFS = -DSTATIC_AFS @AIX_DYNAMIC_AFS_TRUE@@AIX_TRUE@AFS_EXTRA_DEFS = libkafs_la_LIBADD = $(DEPLIB_krb5) $(LIBADD_roken) lib_LTLIBRARIES = libkafs.la libkafs_la_LDFLAGS = -version-info 5:1:5 foodir = $(libdir) foo_DATA = $(AFS_EXTRA_LIBS) # EXTRA_DATA = afslib.so CLEANFILES = $(AFS_EXTRA_LIBS) $(ROKEN_SRCS) include_HEADERS = kafs.h @KRB5_TRUE@afskrb5_c = @do_roken_rename_TRUE@ROKEN_SRCS = resolve.c strtok_r.c strlcpy.c strsep.c dist_libkafs_la_SOURCES = \ afssys.c \ afskrb5.c \ rxkad_kdf.c \ common.c \ $(AIX_SRC) \ kafs_locl.h \ afssysdefs.h \ roken_rename.h nodist_libkafs_la_SOURCES = $(ROKEN_SRCS) EXTRA_libkafs_la_SOURCES = afskrb5.c afslib.c EXTRA_DIST = NTMakefile afsl.exp afslib.exp $(man_MANS) man_MANS = kafs.3 all: all-am .SUFFIXES: .SUFFIXES: .et .h .pc.in .pc .x .z .hx .1 .3 .5 .7 .8 .cat1 .cat3 .cat5 .cat7 .cat8 .c .lo .o .obj $(srcdir)/Makefile.in: @MAINTAINER_MODE_TRUE@ $(srcdir)/Makefile.am $(top_srcdir)/Makefile.am.common $(top_srcdir)/cf/Makefile.am.common $(am__configure_deps) @for dep in $?; do \ case '$(am__configure_deps)' in \ *$$dep*) \ ( cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh ) \ && { if test -f $@; then exit 0; else break; fi; }; \ exit 1;; \ esac; \ done; \ echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign lib/kafs/Makefile'; \ $(am__cd) $(top_srcdir) && \ $(AUTOMAKE) --foreign lib/kafs/Makefile Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status @case '$?' in \ *config.status*) \ cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh;; \ *) \ echo ' cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe)'; \ cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe);; \ esac; $(top_srcdir)/Makefile.am.common $(top_srcdir)/cf/Makefile.am.common $(am__empty): $(top_builddir)/config.status: $(top_srcdir)/configure $(CONFIG_STATUS_DEPENDENCIES) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(top_srcdir)/configure: @MAINTAINER_MODE_TRUE@ $(am__configure_deps) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(ACLOCAL_M4): @MAINTAINER_MODE_TRUE@ $(am__aclocal_m4_deps) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(am__aclocal_m4_deps): install-libLTLIBRARIES: $(lib_LTLIBRARIES) @$(NORMAL_INSTALL) @list='$(lib_LTLIBRARIES)'; test -n "$(libdir)" || list=; \ list2=; for p in $$list; do \ if test -f $$p; then \ list2="$$list2 $$p"; \ else :; fi; \ done; \ test -z "$$list2" || { \ echo " $(MKDIR_P) '$(DESTDIR)$(libdir)'"; \ $(MKDIR_P) "$(DESTDIR)$(libdir)" || exit 1; \ echo " $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=install $(INSTALL) $(INSTALL_STRIP_FLAG) $$list2 '$(DESTDIR)$(libdir)'"; \ $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=install $(INSTALL) $(INSTALL_STRIP_FLAG) $$list2 "$(DESTDIR)$(libdir)"; \ } uninstall-libLTLIBRARIES: @$(NORMAL_UNINSTALL) @list='$(lib_LTLIBRARIES)'; test -n "$(libdir)" || list=; \ for p in $$list; do \ $(am__strip_dir) \ echo " $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=uninstall rm -f '$(DESTDIR)$(libdir)/$$f'"; \ $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=uninstall rm -f "$(DESTDIR)$(libdir)/$$f"; \ done clean-libLTLIBRARIES: -test -z "$(lib_LTLIBRARIES)" || rm -f $(lib_LTLIBRARIES) @list='$(lib_LTLIBRARIES)'; \ locs=`for p in $$list; do echo $$p; done | \ sed 's|^[^/]*$$|.|; s|/[^/]*$$||; s|$$|/so_locations|' | \ sort -u`; \ test -z "$$locs" || { \ echo rm -f $${locs}; \ rm -f $${locs}; \ } libkafs.la: $(libkafs_la_OBJECTS) $(libkafs_la_DEPENDENCIES) $(EXTRA_libkafs_la_DEPENDENCIES) $(AM_V_CCLD)$(libkafs_la_LINK) -rpath $(libdir) $(libkafs_la_OBJECTS) $(libkafs_la_LIBADD) $(LIBS) mostlyclean-compile: -rm -f *.$(OBJEXT) distclean-compile: -rm -f *.tab.c @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/afskrb5.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/afslib.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/afssys.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/common.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/resolve.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/rxkad_kdf.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/strlcpy.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/strsep.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/strtok_r.Plo@am__quote@ .c.o: @am__fastdepCC_TRUE@ $(AM_V_CC)$(COMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o $@ $< @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='$<' object='$@' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(COMPILE) -c -o $@ $< .c.obj: @am__fastdepCC_TRUE@ $(AM_V_CC)$(COMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o $@ `$(CYGPATH_W) '$<'` @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='$<' object='$@' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(COMPILE) -c -o $@ `$(CYGPATH_W) '$<'` .c.lo: @am__fastdepCC_TRUE@ $(AM_V_CC)$(LTCOMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o $@ $< @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='$<' object='$@' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LTCOMPILE) -c -o $@ $< mostlyclean-libtool: -rm -f *.lo clean-libtool: -rm -rf .libs _libs install-man3: $(man_MANS) @$(NORMAL_INSTALL) @list1=''; \ list2='$(man_MANS)'; \ test -n "$(man3dir)" \ && test -n "`echo $$list1$$list2`" \ || exit 0; \ echo " $(MKDIR_P) '$(DESTDIR)$(man3dir)'"; \ $(MKDIR_P) "$(DESTDIR)$(man3dir)" || exit 1; \ { for i in $$list1; do echo "$$i"; done; \ if test -n "$$list2"; then \ for i in $$list2; do echo "$$i"; done \ | sed -n '/\.3[a-z]*$$/p'; \ fi; \ } | while read p; do \ if test -f $$p; then d=; else d="$(srcdir)/"; fi; \ echo "$$d$$p"; echo "$$p"; \ done | \ sed -e 'n;s,.*/,,;p;h;s,.*\.,,;s,^[^3][0-9a-z]*$$,3,;x' \ -e 's,\.[0-9a-z]*$$,,;$(transform);G;s,\n,.,' | \ sed 'N;N;s,\n, ,g' | { \ list=; while read file base inst; do \ if test "$$base" = "$$inst"; then list="$$list $$file"; else \ echo " $(INSTALL_DATA) '$$file' '$(DESTDIR)$(man3dir)/$$inst'"; \ $(INSTALL_DATA) "$$file" "$(DESTDIR)$(man3dir)/$$inst" || exit $$?; \ fi; \ done; \ for i in $$list; do echo "$$i"; done | $(am__base_list) | \ while read files; do \ test -z "$$files" || { \ echo " $(INSTALL_DATA) $$files '$(DESTDIR)$(man3dir)'"; \ $(INSTALL_DATA) $$files "$(DESTDIR)$(man3dir)" || exit $$?; }; \ done; } uninstall-man3: @$(NORMAL_UNINSTALL) @list=''; test -n "$(man3dir)" || exit 0; \ files=`{ for i in $$list; do echo "$$i"; done; \ l2='$(man_MANS)'; for i in $$l2; do echo "$$i"; done | \ sed -n '/\.3[a-z]*$$/p'; \ } | sed -e 's,.*/,,;h;s,.*\.,,;s,^[^3][0-9a-z]*$$,3,;x' \ -e 's,\.[0-9a-z]*$$,,;$(transform);G;s,\n,.,'`; \ dir='$(DESTDIR)$(man3dir)'; $(am__uninstall_files_from_dir) install-fooDATA: $(foo_DATA) @$(NORMAL_INSTALL) @list='$(foo_DATA)'; test -n "$(foodir)" || list=; \ if test -n "$$list"; then \ echo " $(MKDIR_P) '$(DESTDIR)$(foodir)'"; \ $(MKDIR_P) "$(DESTDIR)$(foodir)" || exit 1; \ fi; \ for p in $$list; do \ if test -f "$$p"; then d=; else d="$(srcdir)/"; fi; \ echo "$$d$$p"; \ done | $(am__base_list) | \ while read files; do \ echo " $(INSTALL_DATA) $$files '$(DESTDIR)$(foodir)'"; \ $(INSTALL_DATA) $$files "$(DESTDIR)$(foodir)" || exit $$?; \ done uninstall-fooDATA: @$(NORMAL_UNINSTALL) @list='$(foo_DATA)'; test -n "$(foodir)" || list=; \ files=`for p in $$list; do echo $$p; done | sed -e 's|^.*/||'`; \ dir='$(DESTDIR)$(foodir)'; $(am__uninstall_files_from_dir) install-includeHEADERS: $(include_HEADERS) @$(NORMAL_INSTALL) @list='$(include_HEADERS)'; test -n "$(includedir)" || list=; \ if test -n "$$list"; then \ echo " $(MKDIR_P) '$(DESTDIR)$(includedir)'"; \ $(MKDIR_P) "$(DESTDIR)$(includedir)" || exit 1; \ fi; \ for p in $$list; do \ if test -f "$$p"; then d=; else d="$(srcdir)/"; fi; \ echo "$$d$$p"; \ done | $(am__base_list) | \ while read files; do \ echo " $(INSTALL_HEADER) $$files '$(DESTDIR)$(includedir)'"; \ $(INSTALL_HEADER) $$files "$(DESTDIR)$(includedir)" || exit $$?; \ done uninstall-includeHEADERS: @$(NORMAL_UNINSTALL) @list='$(include_HEADERS)'; test -n "$(includedir)" || list=; \ files=`for p in $$list; do echo $$p; done | sed -e 's|^.*/||'`; \ dir='$(DESTDIR)$(includedir)'; $(am__uninstall_files_from_dir) ID: $(am__tagged_files) $(am__define_uniq_tagged_files); mkid -fID $$unique tags: tags-am TAGS: tags tags-am: $(TAGS_DEPENDENCIES) $(am__tagged_files) set x; \ here=`pwd`; \ $(am__define_uniq_tagged_files); \ shift; \ if test -z "$(ETAGS_ARGS)$$*$$unique"; then :; else \ test -n "$$unique" || unique=$$empty_fix; \ if test $$# -gt 0; then \ $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ "$$@" $$unique; \ else \ $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ $$unique; \ fi; \ fi ctags: ctags-am CTAGS: ctags ctags-am: $(TAGS_DEPENDENCIES) $(am__tagged_files) $(am__define_uniq_tagged_files); \ test -z "$(CTAGS_ARGS)$$unique" \ || $(CTAGS) $(CTAGSFLAGS) $(AM_CTAGSFLAGS) $(CTAGS_ARGS) \ $$unique GTAGS: here=`$(am__cd) $(top_builddir) && pwd` \ && $(am__cd) $(top_srcdir) \ && gtags -i $(GTAGS_ARGS) "$$here" cscopelist: cscopelist-am cscopelist-am: $(am__tagged_files) list='$(am__tagged_files)'; \ case "$(srcdir)" in \ [\\/]* | ?:[\\/]*) sdir="$(srcdir)" ;; \ *) sdir=$(subdir)/$(srcdir) ;; \ esac; \ for i in $$list; do \ if test -f "$$i"; then \ echo "$(subdir)/$$i"; \ else \ echo "$$sdir/$$i"; \ fi; \ done >> $(top_builddir)/cscope.files distclean-tags: -rm -f TAGS ID GTAGS GRTAGS GSYMS GPATH tags distdir: $(DISTFILES) @srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ topsrcdirstrip=`echo "$(top_srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ list='$(DISTFILES)'; \ dist_files=`for file in $$list; do echo $$file; done | \ sed -e "s|^$$srcdirstrip/||;t" \ -e "s|^$$topsrcdirstrip/|$(top_builddir)/|;t"`; \ case $$dist_files in \ */*) $(MKDIR_P) `echo "$$dist_files" | \ sed '/\//!d;s|^|$(distdir)/|;s,/[^/]*$$,,' | \ sort -u` ;; \ esac; \ for file in $$dist_files; do \ if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \ if test -d $$d/$$file; then \ dir=`echo "/$$file" | sed -e 's,/[^/]*$$,,'`; \ if test -d "$(distdir)/$$file"; then \ find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ fi; \ if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \ cp -fpR $(srcdir)/$$file "$(distdir)$$dir" || exit 1; \ find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ fi; \ cp -fpR $$d/$$file "$(distdir)$$dir" || exit 1; \ else \ test -f "$(distdir)/$$file" \ || cp -p $$d/$$file "$(distdir)/$$file" \ || exit 1; \ fi; \ done $(MAKE) $(AM_MAKEFLAGS) \ top_distdir="$(top_distdir)" distdir="$(distdir)" \ dist-hook check-am: all-am $(MAKE) $(AM_MAKEFLAGS) check-local check: check-am all-am: Makefile $(LTLIBRARIES) $(MANS) $(DATA) $(HEADERS) all-local installdirs: for dir in "$(DESTDIR)$(libdir)" "$(DESTDIR)$(man3dir)" "$(DESTDIR)$(foodir)" "$(DESTDIR)$(includedir)"; do \ test -z "$$dir" || $(MKDIR_P) "$$dir"; \ done install: install-am install-exec: install-exec-am install-data: install-data-am uninstall: uninstall-am install-am: all-am @$(MAKE) $(AM_MAKEFLAGS) install-exec-am install-data-am installcheck: installcheck-am install-strip: if test -z '$(STRIP)'; then \ $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ install; \ else \ $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'" install; \ fi mostlyclean-generic: clean-generic: -test -z "$(CLEANFILES)" || rm -f $(CLEANFILES) distclean-generic: -test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES) -test . = "$(srcdir)" || test -z "$(CONFIG_CLEAN_VPATH_FILES)" || rm -f $(CONFIG_CLEAN_VPATH_FILES) maintainer-clean-generic: @echo "This command is intended for maintainers to use" @echo "it deletes files that may require special tools to rebuild." clean: clean-am clean-am: clean-generic clean-libLTLIBRARIES clean-libtool \ mostlyclean-am distclean: distclean-am -rm -rf ./$(DEPDIR) -rm -f Makefile distclean-am: clean-am distclean-compile distclean-generic \ distclean-tags dvi: dvi-am dvi-am: html: html-am html-am: info: info-am info-am: install-data-am: install-fooDATA install-includeHEADERS install-man @$(NORMAL_INSTALL) $(MAKE) $(AM_MAKEFLAGS) install-data-hook install-dvi: install-dvi-am install-dvi-am: install-exec-am: install-exec-local install-libLTLIBRARIES install-html: install-html-am install-html-am: install-info: install-info-am install-info-am: install-man: install-man3 install-pdf: install-pdf-am install-pdf-am: install-ps: install-ps-am install-ps-am: installcheck-am: maintainer-clean: maintainer-clean-am -rm -rf ./$(DEPDIR) -rm -f Makefile maintainer-clean-am: distclean-am maintainer-clean-generic mostlyclean: mostlyclean-am mostlyclean-am: mostlyclean-compile mostlyclean-generic \ mostlyclean-libtool pdf: pdf-am pdf-am: ps: ps-am ps-am: uninstall-am: uninstall-fooDATA uninstall-includeHEADERS \ uninstall-libLTLIBRARIES uninstall-man @$(NORMAL_INSTALL) $(MAKE) $(AM_MAKEFLAGS) uninstall-hook uninstall-man: uninstall-man3 .MAKE: check-am install-am install-data-am install-strip uninstall-am .PHONY: CTAGS GTAGS TAGS all all-am all-local check check-am \ check-local clean clean-generic clean-libLTLIBRARIES \ clean-libtool cscopelist-am ctags ctags-am dist-hook distclean \ distclean-compile distclean-generic distclean-libtool \ distclean-tags distdir dvi dvi-am html html-am info info-am \ install install-am install-data install-data-am \ install-data-hook install-dvi install-dvi-am install-exec \ install-exec-am install-exec-local install-fooDATA \ install-html install-html-am install-includeHEADERS \ install-info install-info-am install-libLTLIBRARIES \ install-man install-man3 install-pdf install-pdf-am install-ps \ install-ps-am install-strip installcheck installcheck-am \ installdirs maintainer-clean maintainer-clean-generic \ mostlyclean mostlyclean-compile mostlyclean-generic \ mostlyclean-libtool pdf pdf-am ps ps-am tags tags-am uninstall \ uninstall-am uninstall-fooDATA uninstall-hook \ uninstall-includeHEADERS uninstall-libLTLIBRARIES \ uninstall-man uninstall-man3 .PRECIOUS: Makefile install-suid-programs: @foo='$(bin_SUIDS)'; \ for file in $$foo; do \ x=$(DESTDIR)$(bindir)/$$file; \ if chown 0:0 $$x && chmod u+s $$x; then :; else \ echo "*"; \ echo "* Failed to install $$x setuid root"; \ echo "*"; \ fi; \ done install-exec-local: install-suid-programs codesign-all: @if [ X"$$CODE_SIGN_IDENTITY" != X ] ; then \ foo='$(bin_PROGRAMS) $(sbin_PROGRAMS) $(libexec_PROGRAMS)' ; \ for file in $$foo ; do \ echo "CODESIGN $$file" ; \ codesign -f -s "$$CODE_SIGN_IDENTITY" $$file || exit 1 ; \ done ; \ fi all-local: codesign-all install-build-headers:: $(include_HEADERS) $(dist_include_HEADERS) $(nodist_include_HEADERS) $(build_HEADERZ) $(nobase_include_HEADERS) $(noinst_HEADERS) @foo='$(include_HEADERS) $(dist_include_HEADERS) $(nodist_include_HEADERS) $(build_HEADERZ) $(noinst_HEADERS)'; \ for f in $$foo; do \ f=`basename $$f`; \ if test -f "$(srcdir)/$$f"; then file="$(srcdir)/$$f"; \ else file="$$f"; fi; \ if cmp -s $$file $(buildinclude)/$$f 2> /dev/null ; then \ : ; else \ echo " $(CP) $$file $(buildinclude)/$$f"; \ $(CP) $$file $(buildinclude)/$$f || true; \ fi ; \ done ; \ foo='$(nobase_include_HEADERS)'; \ for f in $$foo; do \ if test -f "$(srcdir)/$$f"; then file="$(srcdir)/$$f"; \ else file="$$f"; fi; \ $(mkdir_p) $(buildinclude)/`dirname $$f` ; \ if cmp -s $$file $(buildinclude)/$$f 2> /dev/null ; then \ : ; else \ echo " $(CP) $$file $(buildinclude)/$$f"; \ $(CP) $$file $(buildinclude)/$$f; \ fi ; \ done all-local: install-build-headers check-local:: @if test '$(CHECK_LOCAL)' = "no-check-local"; then \ foo=''; elif test '$(CHECK_LOCAL)'; then \ foo='$(CHECK_LOCAL)'; else \ foo='$(PROGRAMS)'; fi; \ if test "$$foo"; then \ failed=0; all=0; \ for i in $$foo; do \ all=`expr $$all + 1`; \ if (./$$i --version && ./$$i --help) > /dev/null 2>&1; then \ echo "PASS: $$i"; \ else \ echo "FAIL: $$i"; \ failed=`expr $$failed + 1`; \ fi; \ done; \ if test "$$failed" -eq 0; then \ banner="All $$all tests passed"; \ else \ banner="$$failed of $$all tests failed"; \ fi; \ dashes=`echo "$$banner" | sed s/./=/g`; \ echo "$$dashes"; \ echo "$$banner"; \ echo "$$dashes"; \ test "$$failed" -eq 0 || exit 1; \ fi .x.c: @cmp -s $< $@ 2> /dev/null || cp $< $@ .hx.h: @cmp -s $< $@ 2> /dev/null || cp $< $@ #NROFF_MAN = nroff -man .1.cat1: $(NROFF_MAN) $< > $@ .3.cat3: $(NROFF_MAN) $< > $@ .5.cat5: $(NROFF_MAN) $< > $@ .7.cat7: $(NROFF_MAN) $< > $@ .8.cat8: $(NROFF_MAN) $< > $@ dist-cat1-mans: @foo='$(man1_MANS)'; \ bar='$(man_MANS)'; \ for i in $$bar; do \ case $$i in \ *.1) foo="$$foo $$i";; \ esac; done ;\ for i in $$foo; do \ x=`echo $$i | sed 's/\.[^.]*$$/.cat1/'`; \ echo "$(NROFF_MAN) $(srcdir)/$$i > $(distdir)/$$x"; \ $(NROFF_MAN) $(srcdir)/$$i > $(distdir)/$$x; \ done dist-cat3-mans: @foo='$(man3_MANS)'; \ bar='$(man_MANS)'; \ for i in $$bar; do \ case $$i in \ *.3) foo="$$foo $$i";; \ esac; done ;\ for i in $$foo; do \ x=`echo $$i | sed 's/\.[^.]*$$/.cat3/'`; \ echo "$(NROFF_MAN) $(srcdir)/$$i > $(distdir)/$$x"; \ $(NROFF_MAN) $(srcdir)/$$i > $(distdir)/$$x; \ done dist-cat5-mans: @foo='$(man5_MANS)'; \ bar='$(man_MANS)'; \ for i in $$bar; do \ case $$i in \ *.5) foo="$$foo $$i";; \ esac; done ;\ for i in $$foo; do \ x=`echo $$i | sed 's/\.[^.]*$$/.cat5/'`; \ echo "$(NROFF_MAN) $(srcdir)/$$i > $(distdir)/$$x"; \ $(NROFF_MAN) $(srcdir)/$$i > $(distdir)/$$x; \ done dist-cat7-mans: @foo='$(man7_MANS)'; \ bar='$(man_MANS)'; \ for i in $$bar; do \ case $$i in \ *.7) foo="$$foo $$i";; \ esac; done ;\ for i in $$foo; do \ x=`echo $$i | sed 's/\.[^.]*$$/.cat7/'`; \ echo "$(NROFF_MAN) $(srcdir)/$$i > $(distdir)/$$x"; \ $(NROFF_MAN) $(srcdir)/$$i > $(distdir)/$$x; \ done dist-cat8-mans: @foo='$(man8_MANS)'; \ bar='$(man_MANS)'; \ for i in $$bar; do \ case $$i in \ *.8) foo="$$foo $$i";; \ esac; done ;\ for i in $$foo; do \ x=`echo $$i | sed 's/\.[^.]*$$/.cat8/'`; \ echo "$(NROFF_MAN) $(srcdir)/$$i > $(distdir)/$$x"; \ $(NROFF_MAN) $(srcdir)/$$i > $(distdir)/$$x; \ done dist-hook: dist-cat1-mans dist-cat3-mans dist-cat5-mans dist-cat7-mans dist-cat8-mans install-cat-mans: $(SHELL) $(top_srcdir)/cf/install-catman.sh install "$(INSTALL_DATA)" "$(mkinstalldirs)" "$(srcdir)" "$(DESTDIR)$(mandir)" '$(CATMANEXT)' $(man_MANS) $(man1_MANS) $(man3_MANS) $(man5_MANS) $(man7_MANS) $(man8_MANS) uninstall-cat-mans: $(SHELL) $(top_srcdir)/cf/install-catman.sh uninstall "$(INSTALL_DATA)" "$(mkinstalldirs)" "$(srcdir)" "$(DESTDIR)$(mandir)" '$(CATMANEXT)' $(man_MANS) $(man1_MANS) $(man3_MANS) $(man5_MANS) $(man7_MANS) $(man8_MANS) install-data-hook: install-cat-mans uninstall-hook: uninstall-cat-mans .et.h: $(COMPILE_ET) $< .et.c: $(COMPILE_ET) $< # # Useful target for debugging # check-valgrind: tobjdir=`cd $(top_builddir) && pwd` ; \ tsrcdir=`cd $(top_srcdir) && pwd` ; \ env TESTS_ENVIRONMENT="$${tsrcdir}/cf/maybe-valgrind.sh -s $${tsrcdir} -o $${tobjdir}" make check # # Target to please samba build farm, builds distfiles in-tree. # Will break when automake changes... # distdir-in-tree: $(DISTFILES) $(INFO_DEPS) list='$(DIST_SUBDIRS)'; for subdir in $$list; do \ if test "$$subdir" != .; then \ (cd $$subdir && $(MAKE) $(AM_MAKEFLAGS) distdir-in-tree) ; \ fi ; \ done # AIX: this almost works with gcc, but somehow it fails to use the # correct ld, use ld instead afslib.so: afslib.o ld -o $@ -bM:SRE -bI:$(srcdir)/afsl.exp -bE:$(srcdir)/afslib.exp $(AFS_EXTRA_LD) afslib.o -lc resolve.c: $(LN_S) $(srcdir)/../roken/resolve.c . strtok_r.c: $(LN_S) $(srcdir)/../roken/strtok_r.c . strlcpy.c: $(LN_S) $(srcdir)/../roken/strlcpy.c . strsep.c: $(LN_S) $(srcdir)/../roken/strsep.c . # Tell versions [3.59,3.63) of GNU make to not export all variables. # Otherwise a system limit (for SysV at least) may be exceeded. .NOEXPORT: heimdal-7.5.0/lib/kafs/NTMakefile0000644000175000017500000000273112136107750014653 0ustar niknik######################################################################## # # Copyright (c) 2009, Secure Endpoints Inc. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # - Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # # - Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in # the documentation and/or other materials provided with the # distribution. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS # FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE # COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, # BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN # ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. # RELDIR=lib\kafs !include ../../windows/NTMakefile.w32 heimdal-7.5.0/lib/kafs/afsl.exp0000644000175000017500000000014612136107750014412 0ustar niknik#!/unix * This mumbo jumbo creates entry points to syscalls in _AIX lpioctl syscall lsetpag syscall heimdal-7.5.0/lib/kafs/common.c0000644000175000017500000002774313026237312014414 0ustar niknik/* * Copyright (c) 1997 - 2005 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "kafs_locl.h" #define AUTH_SUPERUSER "afs" /* * Here only ASCII characters are relevant. */ #define IsAsciiLower(c) ('a' <= (c) && (c) <= 'z') #define ToAsciiUpper(c) ((c) - 'a' + 'A') static void (*kafs_verbose)(void *, const char *); static void *kafs_verbose_ctx; void _kafs_foldup(char *a, const char *b) { for (; *b; a++, b++) if (IsAsciiLower(*b)) *a = ToAsciiUpper(*b); else *a = *b; *a = '\0'; } void kafs_set_verbose(void (*f)(void *, const char *), void *ctx) { if (f) { kafs_verbose = f; kafs_verbose_ctx = ctx; } } int kafs_settoken_rxkad(const char *cell, struct ClearToken *ct, void *ticket, size_t ticket_len) { struct ViceIoctl parms; char buf[2048], *t; int32_t sizeof_x; t = buf; /* * length of secret token followed by secret token */ sizeof_x = ticket_len; memcpy(t, &sizeof_x, sizeof(sizeof_x)); t += sizeof(sizeof_x); memcpy(t, ticket, sizeof_x); t += sizeof_x; /* * length of clear token followed by clear token */ sizeof_x = sizeof(*ct); memcpy(t, &sizeof_x, sizeof(sizeof_x)); t += sizeof(sizeof_x); memcpy(t, ct, sizeof_x); t += sizeof_x; /* * do *not* mark as primary cell */ sizeof_x = 0; memcpy(t, &sizeof_x, sizeof(sizeof_x)); t += sizeof(sizeof_x); /* * follow with cell name */ sizeof_x = strlen(cell) + 1; memcpy(t, cell, sizeof_x); t += sizeof_x; /* * Build argument block */ parms.in = buf; parms.in_size = t - buf; parms.out = 0; parms.out_size = 0; return k_pioctl(0, VIOCSETTOK, &parms, 0); } void _kafs_fixup_viceid(struct ClearToken *ct, uid_t uid) { #define ODD(x) ((x) & 1) /* According to Transarc conventions ViceId is valid iff * (EndTimestamp - BeginTimestamp) is odd. By decrementing EndTime * the transformations: * * (issue_date, life) -> (StartTime, EndTime) -> (issue_date, life) * preserves the original values. */ if (uid != 0) /* valid ViceId */ { if (!ODD(ct->EndTimestamp - ct->BeginTimestamp)) ct->EndTimestamp--; } else /* not valid ViceId */ { if (ODD(ct->EndTimestamp - ct->BeginTimestamp)) ct->EndTimestamp--; } } /* Try to get a db-server for an AFS cell from a AFSDB record */ static int dns_find_cell(const char *cell, char *dbserver, size_t len) { struct rk_dns_reply *r; int ok = -1; r = rk_dns_lookup(cell, "afsdb"); if(r){ struct rk_resource_record *rr = r->head; while(rr){ if(rr->type == rk_ns_t_afsdb && rr->u.afsdb->preference == 1){ strlcpy(dbserver, rr->u.afsdb->domain, len); ok = 0; break; } rr = rr->next; } rk_dns_free_data(r); } return ok; } /* * Try to find the cells we should try to klog to in "file". */ static void find_cells(const char *file, char ***cells, int *idx) { FILE *f; char cell[64]; int i; int ind = *idx; f = fopen(file, "r"); if (f == NULL) return; while (fgets(cell, sizeof(cell), f)) { char *t; t = cell + strlen(cell); for (; t >= cell; t--) if (*t == '\n' || *t == '\t' || *t == ' ') *t = 0; if (cell[0] == '\0' || cell[0] == '#') continue; for(i = 0; i < ind; i++) if(strcmp((*cells)[i], cell) == 0) break; if(i == ind){ char **tmp; tmp = realloc(*cells, (ind + 1) * sizeof(**cells)); if (tmp == NULL) break; *cells = tmp; (*cells)[ind] = strdup(cell); if ((*cells)[ind] == NULL) break; ++ind; } } fclose(f); *idx = ind; } /* * Get tokens for all cells[] */ static int afslog_cells(struct kafs_data *data, char **cells, int max, uid_t uid, const char *homedir) { int ret = 0; int i; for (i = 0; i < max; i++) { int er = (*data->afslog_uid)(data, cells[i], 0, uid, homedir); if (er) ret = er; } return ret; } int _kafs_afslog_all_local_cells(struct kafs_data *data, uid_t uid, const char *homedir) { int ret; char **cells = NULL; int idx = 0; if (homedir == NULL) homedir = getenv("HOME"); if (homedir != NULL) { char home[MaxPathLen]; snprintf(home, sizeof(home), "%s/.TheseCells", homedir); find_cells(home, &cells, &idx); } find_cells(_PATH_THESECELLS, &cells, &idx); find_cells(_PATH_THISCELL, &cells, &idx); find_cells(_PATH_ARLA_THESECELLS, &cells, &idx); find_cells(_PATH_ARLA_THISCELL, &cells, &idx); find_cells(_PATH_OPENAFS_DEBIAN_THESECELLS, &cells, &idx); find_cells(_PATH_OPENAFS_DEBIAN_THISCELL, &cells, &idx); find_cells(_PATH_OPENAFS_MACOSX_THESECELLS, &cells, &idx); find_cells(_PATH_OPENAFS_MACOSX_THISCELL, &cells, &idx); find_cells(_PATH_ARLA_DEBIAN_THESECELLS, &cells, &idx); find_cells(_PATH_ARLA_DEBIAN_THISCELL, &cells, &idx); find_cells(_PATH_ARLA_OPENBSD_THESECELLS, &cells, &idx); find_cells(_PATH_ARLA_OPENBSD_THISCELL, &cells, &idx); ret = afslog_cells(data, cells, idx, uid, homedir); while(idx > 0) free(cells[--idx]); free(cells); return ret; } static int file_find_cell(struct kafs_data *data, const char *cell, char **realm, int exact) { FILE *F; char buf[1024]; char *p; int ret = -1; if ((F = fopen(_PATH_CELLSERVDB, "r")) || (F = fopen(_PATH_ARLA_CELLSERVDB, "r")) || (F = fopen(_PATH_OPENAFS_DEBIAN_CELLSERVDB, "r")) || (F = fopen(_PATH_OPENAFS_MACOSX_CELLSERVDB, "r")) || (F = fopen(_PATH_ARLA_DEBIAN_CELLSERVDB, "r"))) { while (fgets(buf, sizeof(buf), F)) { int cmp; if (buf[0] != '>') continue; /* Not a cell name line, try next line */ p = buf; strsep(&p, " \t\n#"); if (exact) cmp = strcmp(buf + 1, cell); else cmp = strncmp(buf + 1, cell, strlen(cell)); if (cmp == 0) { /* * We found the cell name we're looking for. * Read next line on the form ip-address '#' hostname */ if (fgets(buf, sizeof(buf), F) == NULL) break; /* Read failed, give up */ p = strchr(buf, '#'); if (p == NULL) break; /* No '#', give up */ p++; if (buf[strlen(buf) - 1] == '\n') buf[strlen(buf) - 1] = '\0'; *realm = (*data->get_realm)(data, p); if (*realm && **realm != '\0') ret = 0; break; /* Won't try any more */ } } fclose(F); } return ret; } /* Find the realm associated with cell. Do this by opening CellServDB file and getting the realm-of-host for the first VL-server for the cell. This does not work when the VL-server is living in one realm, but the cell it is serving is living in another realm. Return 0 on success, -1 otherwise. */ int _kafs_realm_of_cell(struct kafs_data *data, const char *cell, char **realm) { char buf[1024]; int ret; ret = file_find_cell(data, cell, realm, 1); if (ret == 0) return ret; if (dns_find_cell(cell, buf, sizeof(buf)) == 0) { *realm = (*data->get_realm)(data, buf); if(*realm != NULL) return 0; } return file_find_cell(data, cell, realm, 0); } static int _kafs_try_get_cred(struct kafs_data *data, const char *user, const char *cell, const char *realm, uid_t uid, struct kafs_token *kt) { int ret; ret = (*data->get_cred)(data, user, cell, realm, uid, kt); if (kafs_verbose) { const char *estr = (*data->get_error)(data, ret); char *str; int aret; aret = asprintf(&str, "%s tried afs%s%s@%s -> %s (%d)", data->name, cell ? "/" : "", cell ? cell : "", realm, estr ? estr : "unknown", ret); if (aret != -1) { (*kafs_verbose)(kafs_verbose_ctx, str); free(str); } else { (*kafs_verbose)(kafs_verbose_ctx, "out of memory"); } if (estr) (*data->free_error)(data, estr); } return ret; } int _kafs_get_cred(struct kafs_data *data, const char *cell, const char *realm_hint, const char *realm, uid_t uid, struct kafs_token *kt) { int ret = -1; char *vl_realm; char CELL[64]; /* We're about to find the realm that holds the key for afs in * the specified cell. The problem is that null-instance * afs-principals are common and that hitting the wrong realm might * yield the wrong afs key. The following assumptions were made. * * Any realm passed to us is preferred. * * If there is a realm with the same name as the cell, it is most * likely the correct realm to talk to. * * In most (maybe even all) cases the database servers of the cell * will live in the realm we are looking for. * * Try the local realm, but if the previous cases fail, this is * really a long shot. * */ /* comments on the ordering of these tests */ /* If the user passes a realm, she probably knows something we don't * know and we should try afs@realm_hint. */ if (realm_hint) { ret = _kafs_try_get_cred(data, AUTH_SUPERUSER, cell, realm_hint, uid, kt); if (ret == 0) return 0; ret = _kafs_try_get_cred(data, AUTH_SUPERUSER, NULL, realm_hint, uid, kt); if (ret == 0) return 0; } _kafs_foldup(CELL, cell); /* * If the AFS servers have a file /usr/afs/etc/krb.conf containing * REALM we still don't have to resort to cross-cell authentication. * Try afs.cell@REALM. */ ret = _kafs_try_get_cred(data, AUTH_SUPERUSER, cell, realm, uid, kt); if (ret == 0) return 0; /* * If cell == realm we don't need no cross-cell authentication. * Try afs@REALM. */ if (strcmp(CELL, realm) == 0) { ret = _kafs_try_get_cred(data, AUTH_SUPERUSER, NULL, realm, uid, kt); if (ret == 0) return 0; } /* * We failed to get ``first class tickets'' for afs, * fall back to cross-cell authentication. * Try afs@CELL. * Try afs.cell@CELL. */ ret = _kafs_try_get_cred(data, AUTH_SUPERUSER, NULL, CELL, uid, kt); if (ret == 0) return 0; ret = _kafs_try_get_cred(data, AUTH_SUPERUSER, cell, CELL, uid, kt); if (ret == 0) return 0; /* * Perhaps the cell doesn't correspond to any realm? * Use realm of first volume location DB server. * Try afs.cell@VL_REALM. * Try afs@VL_REALM??? */ if (_kafs_realm_of_cell(data, cell, &vl_realm) == 0 && strcmp(vl_realm, realm) != 0 && strcmp(vl_realm, CELL) != 0) { ret = _kafs_try_get_cred(data, AUTH_SUPERUSER, cell, vl_realm, uid, kt); if (ret) ret = _kafs_try_get_cred(data, AUTH_SUPERUSER, NULL, vl_realm, uid, kt); free(vl_realm); if (ret == 0) return 0; } return ret; } heimdal-7.5.0/lib/heimdal/0000755000175000017500000000000013214604041013416 5ustar niknikheimdal-7.5.0/lib/heimdal/heimdal-version.rc0000644000175000017500000000323412136107747017051 0ustar niknik/*********************************************************************** * Copyright (c) 2010, Secure Endpoints Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * - Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. * **********************************************************************/ #define RC_FILE_TYPE VFT_DLL #define RC_FILE_DESC_0409 "Heimdal Kerberos Library" #define RC_FILE_ORIG_0409 "heimdal.dll" #include "../../windows/version.rc" heimdal-7.5.0/lib/heimdal/NTMakefile0000644000175000017500000000501113026237312015321 0ustar niknik######################################################################## # # Copyright (c) 2009, 2010 Secure Endpoints Inc. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # - Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # # - Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in # the documentation and/or other materials provided with the # distribution. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS # FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE # COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, # BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN # ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. # RELDIR = lib\heimdal !include ../../windows/NTMakefile.w32 !ifndef STATICLIBS DLLDEPS= \ $(LIBASN1) \ $(LIBCOMERR) \ $(LIBHCRYPTO) \ $(LIBHX509) \ $(LIBKRB5) \ $(LIBROKEN) \ $(LIBSQLITE) \ $(LIBWIND) \ $(LIBLTM) \ $(LIBHEIMBASE) DLLSDKDEPS= \ $(PTHREAD_LIB) \ secur32.lib \ shell32.lib \ dnsapi.lib \ shlwapi.lib dlllflags=$(dlllflags) /DELAYLOAD:bcrypt.dll DLLSDKDEPS=$(DLLSDKDEPS)\ bcrypt.lib \ delayimp.lib DEF=$(OBJ)\heimdal.def RES=$(OBJ)\heimdal-version.res DEFSRC= ..\asn1\libasn1-exports.def \ ..\wind\libwind-exports.def \ ..\hcrypto\libhcrypto-exports.def \ ..\hx509\libhx509-exports.def \ $(OBJDIR)\lib\krb5\libkrb5-exports.def $(DEF): $(DEFSRC) copy $(DEFSRC: = + ) $(DEF) DLL=$(BINDIR)\heimdal.dll $(LIBHEIMDAL): $(BINDIR)\heimdal.dll $(DLL): $(DLLDEPS) $(DEF) $(RES) $(DLLGUILINK_C) $(DLLDEPS) $(DLLSDKDEPS) $(RES) \ -def:$(DEF) -out:$(DLL) \ -implib:$(LIBHEIMDAL) $(DLLPREP_NODIST) clean:: -$(RM) $(BINDIR)\heimdal.* !else $(LIBHEIMDAL): $(LIBASN1) $(LIBWIND) $(LIBHCRYPTO) $(LIBHX509) $(LIBKRB5) $(LIBHEIMBASE) $(LIBCON) !endif all:: $(LIBHEIMDAL) heimdal-7.5.0/lib/libedit/0000755000175000017500000000000013214604041013427 5ustar niknikheimdal-7.5.0/lib/libedit/src/0000755000175000017500000000000013212450752014224 5ustar niknikheimdal-7.5.0/lib/libedit/src/el.c0000644000175000017500000002764213026237312015001 0ustar niknik/* $NetBSD: el.c,v 1.92 2016/05/22 19:44:26 christos Exp $ */ /*- * Copyright (c) 1992, 1993 * The Regents of the University of California. All rights reserved. * * This code is derived from software contributed to Berkeley by * Christos Zoulas of Cornell University. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the University nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "config.h" #if !defined(lint) && !defined(SCCSID) #if 0 static char sccsid[] = "@(#)el.c 8.2 (Berkeley) 1/3/94"; #else __RCSID("$NetBSD: el.c,v 1.92 2016/05/22 19:44:26 christos Exp $"); #endif #endif /* not lint && not SCCSID */ /* * el.c: EditLine interface functions */ #include #include #include #include #include #include #include #include #include "el.h" #include "parse.h" #include "read.h" /* el_init(): * Initialize editline and set default parameters. */ EditLine * el_init(const char *prog, FILE *fin, FILE *fout, FILE *ferr) { return el_init_fd(prog, fin, fout, ferr, fileno(fin), fileno(fout), fileno(ferr)); } EditLine * el_init_fd(const char *prog, FILE *fin, FILE *fout, FILE *ferr, int fdin, int fdout, int fderr) { EditLine *el = el_malloc(sizeof(*el)); if (el == NULL) return NULL; memset(el, 0, sizeof(EditLine)); el->el_infile = fin; el->el_outfile = fout; el->el_errfile = ferr; el->el_infd = fdin; el->el_outfd = fdout; el->el_errfd = fderr; el->el_prog = wcsdup(ct_decode_string(prog, &el->el_scratch)); if (el->el_prog == NULL) { el_free(el); return NULL; } /* * Initialize all the modules. Order is important!!! */ el->el_flags = 0; if (setlocale(LC_CTYPE, NULL) != NULL){ if (strcmp(nl_langinfo(CODESET), "UTF-8") == 0) el->el_flags |= CHARSET_IS_UTF8; } if (terminal_init(el) == -1) { el_free(el->el_prog); el_free(el); return NULL; } (void) keymacro_init(el); (void) map_init(el); if (tty_init(el) == -1) el->el_flags |= NO_TTY; (void) ch_init(el); (void) search_init(el); (void) hist_init(el); (void) prompt_init(el); (void) sig_init(el); if (read_init(el) == -1) { el_end(el); return NULL; } return el; } /* el_end(): * Clean up. */ void el_end(EditLine *el) { if (el == NULL) return; el_reset(el); terminal_end(el); keymacro_end(el); map_end(el); if (!(el->el_flags & NO_TTY)) tty_end(el); ch_end(el); read_end(el->el_read); search_end(el); hist_end(el); prompt_end(el); sig_end(el); el_free(el->el_prog); el_free(el->el_visual.cbuff); el_free(el->el_visual.wbuff); el_free(el->el_scratch.cbuff); el_free(el->el_scratch.wbuff); el_free(el->el_lgcyconv.cbuff); el_free(el->el_lgcyconv.wbuff); el_free(el); } /* el_reset(): * Reset the tty and the parser */ void el_reset(EditLine *el) { tty_cookedmode(el); ch_reset(el); /* XXX: Do we want that? */ } /* el_set(): * set the editline parameters */ int el_wset(EditLine *el, int op, ...) { va_list ap; int rv = 0; if (el == NULL) return -1; va_start(ap, op); switch (op) { case EL_PROMPT: case EL_RPROMPT: { el_pfunc_t p = va_arg(ap, el_pfunc_t); rv = prompt_set(el, p, 0, op, 1); break; } case EL_RESIZE: { el_zfunc_t p = va_arg(ap, el_zfunc_t); void *arg = va_arg(ap, void *); rv = ch_resizefun(el, p, arg); break; } case EL_ALIAS_TEXT: { el_afunc_t p = va_arg(ap, el_afunc_t); void *arg = va_arg(ap, void *); rv = ch_aliasfun(el, p, arg); break; } case EL_PROMPT_ESC: case EL_RPROMPT_ESC: { el_pfunc_t p = va_arg(ap, el_pfunc_t); int c = va_arg(ap, int); rv = prompt_set(el, p, (wchar_t)c, op, 1); break; } case EL_TERMINAL: rv = terminal_set(el, va_arg(ap, char *)); break; case EL_EDITOR: rv = map_set_editor(el, va_arg(ap, wchar_t *)); break; case EL_SIGNAL: if (va_arg(ap, int)) el->el_flags |= HANDLE_SIGNALS; else el->el_flags &= ~HANDLE_SIGNALS; break; case EL_BIND: case EL_TELLTC: case EL_SETTC: case EL_ECHOTC: case EL_SETTY: { const wchar_t *argv[20]; int i; for (i = 1; i < (int)__arraycount(argv); i++) if ((argv[i] = va_arg(ap, wchar_t *)) == NULL) break; switch (op) { case EL_BIND: argv[0] = L"bind"; rv = map_bind(el, i, argv); break; case EL_TELLTC: argv[0] = L"telltc"; rv = terminal_telltc(el, i, argv); break; case EL_SETTC: argv[0] = L"settc"; rv = terminal_settc(el, i, argv); break; case EL_ECHOTC: argv[0] = L"echotc"; rv = terminal_echotc(el, i, argv); break; case EL_SETTY: argv[0] = L"setty"; rv = tty_stty(el, i, argv); break; default: rv = -1; EL_ABORT((el->el_errfile, "Bad op %d\n", op)); break; } break; } case EL_ADDFN: { wchar_t *name = va_arg(ap, wchar_t *); wchar_t *help = va_arg(ap, wchar_t *); el_func_t func = va_arg(ap, el_func_t); rv = map_addfunc(el, name, help, func); break; } case EL_HIST: { hist_fun_t func = va_arg(ap, hist_fun_t); void *ptr = va_arg(ap, void *); rv = hist_set(el, func, ptr); if (!(el->el_flags & CHARSET_IS_UTF8)) el->el_flags &= ~NARROW_HISTORY; break; } case EL_EDITMODE: if (va_arg(ap, int)) el->el_flags &= ~EDIT_DISABLED; else el->el_flags |= EDIT_DISABLED; rv = 0; break; case EL_GETCFN: { el_rfunc_t rc = va_arg(ap, el_rfunc_t); rv = el_read_setfn(el->el_read, rc); break; } case EL_CLIENTDATA: el->el_data = va_arg(ap, void *); break; case EL_UNBUFFERED: rv = va_arg(ap, int); if (rv && !(el->el_flags & UNBUFFERED)) { el->el_flags |= UNBUFFERED; read_prepare(el); } else if (!rv && (el->el_flags & UNBUFFERED)) { el->el_flags &= ~UNBUFFERED; read_finish(el); } rv = 0; break; case EL_PREP_TERM: rv = va_arg(ap, int); if (rv) (void) tty_rawmode(el); else (void) tty_cookedmode(el); rv = 0; break; case EL_SETFP: { FILE *fp; int what; what = va_arg(ap, int); fp = va_arg(ap, FILE *); rv = 0; switch (what) { case 0: el->el_infile = fp; el->el_infd = fileno(fp); break; case 1: el->el_outfile = fp; el->el_outfd = fileno(fp); break; case 2: el->el_errfile = fp; el->el_errfd = fileno(fp); break; default: rv = -1; break; } break; } case EL_REFRESH: re_clear_display(el); re_refresh(el); terminal__flush(el); break; default: rv = -1; break; } va_end(ap); return rv; } /* el_get(): * retrieve the editline parameters */ int el_wget(EditLine *el, int op, ...) { va_list ap; int rv; if (el == NULL) return -1; va_start(ap, op); switch (op) { case EL_PROMPT: case EL_RPROMPT: { el_pfunc_t *p = va_arg(ap, el_pfunc_t *); rv = prompt_get(el, p, 0, op); break; } case EL_PROMPT_ESC: case EL_RPROMPT_ESC: { el_pfunc_t *p = va_arg(ap, el_pfunc_t *); wchar_t *c = va_arg(ap, wchar_t *); rv = prompt_get(el, p, c, op); break; } case EL_EDITOR: rv = map_get_editor(el, va_arg(ap, const wchar_t **)); break; case EL_SIGNAL: *va_arg(ap, int *) = (el->el_flags & HANDLE_SIGNALS); rv = 0; break; case EL_EDITMODE: *va_arg(ap, int *) = !(el->el_flags & EDIT_DISABLED); rv = 0; break; case EL_TERMINAL: terminal_get(el, va_arg(ap, const char **)); rv = 0; break; case EL_GETTC: { static char name[] = "gettc"; char *argv[20]; int i; for (i = 1; i < (int)__arraycount(argv); i++) if ((argv[i] = va_arg(ap, char *)) == NULL) break; argv[0] = name; rv = terminal_gettc(el, i, argv); break; } case EL_GETCFN: *va_arg(ap, el_rfunc_t *) = el_read_getfn(el->el_read); rv = 0; break; case EL_CLIENTDATA: *va_arg(ap, void **) = el->el_data; rv = 0; break; case EL_UNBUFFERED: *va_arg(ap, int *) = (el->el_flags & UNBUFFERED) != 0; rv = 0; break; case EL_GETFP: { int what; FILE **fpp; what = va_arg(ap, int); fpp = va_arg(ap, FILE **); rv = 0; switch (what) { case 0: *fpp = el->el_infile; break; case 1: *fpp = el->el_outfile; break; case 2: *fpp = el->el_errfile; break; default: rv = -1; break; } break; } default: rv = -1; break; } va_end(ap); return rv; } /* el_line(): * Return editing info */ const LineInfoW * el_wline(EditLine *el) { return (const LineInfoW *)(void *)&el->el_line; } /* el_source(): * Source a file */ int el_source(EditLine *el, const char *fname) { FILE *fp; size_t len; ssize_t slen; char *ptr; char *path = NULL; const wchar_t *dptr; int error = 0; fp = NULL; if (fname == NULL) { #ifdef HAVE_ISSETUGID static const char elpath[] = "/.editrc"; size_t plen = sizeof(elpath); if (issetugid()) return -1; if ((ptr = getenv("HOME")) == NULL) return -1; plen += strlen(ptr); if ((path = el_malloc(plen * sizeof(*path))) == NULL) return -1; (void)snprintf(path, plen, "%s%s", ptr, elpath); fname = path; #else /* * If issetugid() is missing, always return an error, in order * to keep from inadvertently opening up the user to a security * hole. */ return -1; #endif } if (fp == NULL) fp = fopen(fname, "r"); if (fp == NULL) { el_free(path); return -1; } ptr = NULL; len = 0; while ((slen = getline(&ptr, &len, fp)) != -1) { if (*ptr == '\n') continue; /* Empty line. */ if (slen > 0 && ptr[--slen] == '\n') ptr[slen] = '\0'; dptr = ct_decode_string(ptr, &el->el_scratch); if (!dptr) continue; /* loop until first non-space char or EOL */ while (*dptr != '\0' && iswspace(*dptr)) dptr++; if (*dptr == '#') continue; /* ignore, this is a comment line */ if ((error = parse_line(el, dptr)) == -1) break; } free(ptr); el_free(path); (void) fclose(fp); return error; } /* el_resize(): * Called from program when terminal is resized */ void el_resize(EditLine *el) { int lins, cols; sigset_t oset, nset; (void) sigemptyset(&nset); (void) sigaddset(&nset, SIGWINCH); (void) sigprocmask(SIG_BLOCK, &nset, &oset); /* get the correct window size */ if (terminal_get_size(el, &lins, &cols)) terminal_change_size(el, lins, cols); (void) sigprocmask(SIG_SETMASK, &oset, NULL); } /* el_beep(): * Called from the program to beep */ void el_beep(EditLine *el) { terminal_beep(el); } /* el_editmode() * Set the state of EDIT_DISABLED from the `edit' command. */ libedit_private int /*ARGSUSED*/ el_editmode(EditLine *el, int argc, const wchar_t **argv) { const wchar_t *how; if (argv == NULL || argc != 2 || argv[1] == NULL) return -1; how = argv[1]; if (wcscmp(how, L"on") == 0) { el->el_flags &= ~EDIT_DISABLED; tty_rawmode(el); } else if (wcscmp(how, L"off") == 0) { tty_cookedmode(el); el->el_flags |= EDIT_DISABLED; } else { (void) fprintf(el->el_errfile, "edit: Bad value `%ls'.\n", how); return -1; } return 0; } heimdal-7.5.0/lib/libedit/src/tokenizer.c0000644000175000017500000002416713026237312016412 0ustar niknik/* $NetBSD: tokenizer.c,v 1.28 2016/04/11 18:56:31 christos Exp $ */ /*- * Copyright (c) 1992, 1993 * The Regents of the University of California. All rights reserved. * * This code is derived from software contributed to Berkeley by * Christos Zoulas of Cornell University. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the University nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "config.h" #if !defined(lint) && !defined(SCCSID) #if 0 static char sccsid[] = "@(#)tokenizer.c 8.1 (Berkeley) 6/4/93"; #else __RCSID("$NetBSD: tokenizer.c,v 1.28 2016/04/11 18:56:31 christos Exp $"); #endif #endif /* not lint && not SCCSID */ /* We build this file twice, once as NARROW, once as WIDE. */ /* * tokenize.c: Bourne shell like tokenizer */ #include #include #include "histedit.h" typedef enum { Q_none, Q_single, Q_double, Q_one, Q_doubleone } quote_t; #define TOK_KEEP 1 #define TOK_EAT 2 #define WINCR 20 #define AINCR 10 #define IFS STR("\t \n") #define tok_malloc(a) malloc(a) #define tok_free(a) free(a) #define tok_realloc(a, b) realloc(a, b) #ifdef NARROWCHAR #define Char char #define FUN(prefix, rest) prefix ## _ ## rest #define TYPE(type) type #define STR(x) x #define Strchr(s, c) strchr(s, c) #define tok_strdup(s) strdup(s) #else #define Char wchar_t #define FUN(prefix, rest) prefix ## _w ## rest #define TYPE(type) type ## W #define STR(x) L ## x #define Strchr(s, c) wcschr(s, c) #define tok_strdup(s) wcsdup(s) #endif struct TYPE(tokenizer) { Char *ifs; /* In field separator */ size_t argc, amax; /* Current and maximum number of args */ Char **argv; /* Argument list */ Char *wptr, *wmax; /* Space and limit on the word buffer */ Char *wstart; /* Beginning of next word */ Char *wspace; /* Space of word buffer */ quote_t quote; /* Quoting state */ int flags; /* flags; */ }; static void FUN(tok,finish)(TYPE(Tokenizer) *); /* FUN(tok,finish)(): * Finish a word in the tokenizer. */ static void FUN(tok,finish)(TYPE(Tokenizer) *tok) { *tok->wptr = '\0'; if ((tok->flags & TOK_KEEP) || tok->wptr != tok->wstart) { tok->argv[tok->argc++] = tok->wstart; tok->argv[tok->argc] = NULL; tok->wstart = ++tok->wptr; } tok->flags &= ~TOK_KEEP; } /* FUN(tok,init)(): * Initialize the tokenizer */ TYPE(Tokenizer) * FUN(tok,init)(const Char *ifs) { TYPE(Tokenizer) *tok = tok_malloc(sizeof(*tok)); if (tok == NULL) return NULL; tok->ifs = tok_strdup(ifs ? ifs : IFS); if (tok->ifs == NULL) { tok_free(tok); return NULL; } tok->argc = 0; tok->amax = AINCR; tok->argv = tok_malloc(sizeof(*tok->argv) * tok->amax); if (tok->argv == NULL) { tok_free(tok->ifs); tok_free(tok); return NULL; } tok->argv[0] = NULL; tok->wspace = tok_malloc(WINCR * sizeof(*tok->wspace)); if (tok->wspace == NULL) { tok_free(tok->argv); tok_free(tok->ifs); tok_free(tok); return NULL; } tok->wmax = tok->wspace + WINCR; tok->wstart = tok->wspace; tok->wptr = tok->wspace; tok->flags = 0; tok->quote = Q_none; return tok; } /* FUN(tok,reset)(): * Reset the tokenizer */ void FUN(tok,reset)(TYPE(Tokenizer) *tok) { tok->argc = 0; tok->wstart = tok->wspace; tok->wptr = tok->wspace; tok->flags = 0; tok->quote = Q_none; } /* FUN(tok,end)(): * Clean up */ void FUN(tok,end)(TYPE(Tokenizer) *tok) { tok_free(tok->ifs); tok_free(tok->wspace); tok_free(tok->argv); tok_free(tok); } /* FUN(tok,line)(): * Bourne shell (sh(1)) like tokenizing * Arguments: * tok current tokenizer state (setup with FUN(tok,init)()) * line line to parse * Returns: * -1 Internal error * 3 Quoted return * 2 Unmatched double quote * 1 Unmatched single quote * 0 Ok * Modifies (if return value is 0): * argc number of arguments * argv argument array * cursorc if !NULL, argv element containing cursor * cursorv if !NULL, offset in argv[cursorc] of cursor */ int FUN(tok,line)(TYPE(Tokenizer) *tok, const TYPE(LineInfo) *line, int *argc, const Char ***argv, int *cursorc, int *cursoro) { const Char *ptr; int cc, co; cc = co = -1; ptr = line->buffer; for (ptr = line->buffer; ;ptr++) { if (ptr >= line->lastchar) ptr = STR(""); if (ptr == line->cursor) { cc = (int)tok->argc; co = (int)(tok->wptr - tok->wstart); } switch (*ptr) { case '\'': tok->flags |= TOK_KEEP; tok->flags &= ~TOK_EAT; switch (tok->quote) { case Q_none: tok->quote = Q_single; /* Enter single quote * mode */ break; case Q_single: /* Exit single quote mode */ tok->quote = Q_none; break; case Q_one: /* Quote this ' */ tok->quote = Q_none; *tok->wptr++ = *ptr; break; case Q_double: /* Stay in double quote mode */ *tok->wptr++ = *ptr; break; case Q_doubleone: /* Quote this ' */ tok->quote = Q_double; *tok->wptr++ = *ptr; break; default: return -1; } break; case '"': tok->flags &= ~TOK_EAT; tok->flags |= TOK_KEEP; switch (tok->quote) { case Q_none: /* Enter double quote mode */ tok->quote = Q_double; break; case Q_double: /* Exit double quote mode */ tok->quote = Q_none; break; case Q_one: /* Quote this " */ tok->quote = Q_none; *tok->wptr++ = *ptr; break; case Q_single: /* Stay in single quote mode */ *tok->wptr++ = *ptr; break; case Q_doubleone: /* Quote this " */ tok->quote = Q_double; *tok->wptr++ = *ptr; break; default: return -1; } break; case '\\': tok->flags |= TOK_KEEP; tok->flags &= ~TOK_EAT; switch (tok->quote) { case Q_none: /* Quote next character */ tok->quote = Q_one; break; case Q_double: /* Quote next character */ tok->quote = Q_doubleone; break; case Q_one: /* Quote this, restore state */ *tok->wptr++ = *ptr; tok->quote = Q_none; break; case Q_single: /* Stay in single quote mode */ *tok->wptr++ = *ptr; break; case Q_doubleone: /* Quote this \ */ tok->quote = Q_double; *tok->wptr++ = *ptr; break; default: return -1; } break; case '\n': tok->flags &= ~TOK_EAT; switch (tok->quote) { case Q_none: goto tok_line_outok; case Q_single: case Q_double: *tok->wptr++ = *ptr; /* Add the return */ break; case Q_doubleone: /* Back to double, eat the '\n' */ tok->flags |= TOK_EAT; tok->quote = Q_double; break; case Q_one: /* No quote, more eat the '\n' */ tok->flags |= TOK_EAT; tok->quote = Q_none; break; default: return 0; } break; case '\0': switch (tok->quote) { case Q_none: /* Finish word and return */ if (tok->flags & TOK_EAT) { tok->flags &= ~TOK_EAT; return 3; } goto tok_line_outok; case Q_single: return 1; case Q_double: return 2; case Q_doubleone: tok->quote = Q_double; *tok->wptr++ = *ptr; break; case Q_one: tok->quote = Q_none; *tok->wptr++ = *ptr; break; default: return -1; } break; default: tok->flags &= ~TOK_EAT; switch (tok->quote) { case Q_none: if (Strchr(tok->ifs, *ptr) != NULL) FUN(tok,finish)(tok); else *tok->wptr++ = *ptr; break; case Q_single: case Q_double: *tok->wptr++ = *ptr; break; case Q_doubleone: *tok->wptr++ = '\\'; tok->quote = Q_double; *tok->wptr++ = *ptr; break; case Q_one: tok->quote = Q_none; *tok->wptr++ = *ptr; break; default: return -1; } break; } if (tok->wptr >= tok->wmax - 4) { size_t size = (size_t)(tok->wmax - tok->wspace + WINCR); Char *s = tok_realloc(tok->wspace, size * sizeof(*s)); if (s == NULL) return -1; if (s != tok->wspace) { size_t i; for (i = 0; i < tok->argc; i++) { tok->argv[i] = (tok->argv[i] - tok->wspace) + s; } tok->wptr = (tok->wptr - tok->wspace) + s; tok->wstart = (tok->wstart - tok->wspace) + s; tok->wspace = s; } tok->wmax = s + size; } if (tok->argc >= tok->amax - 4) { Char **p; tok->amax += AINCR; p = tok_realloc(tok->argv, tok->amax * sizeof(*p)); if (p == NULL) { tok->amax -= AINCR; return -1; } tok->argv = p; } } tok_line_outok: if (cc == -1 && co == -1) { cc = (int)tok->argc; co = (int)(tok->wptr - tok->wstart); } if (cursorc != NULL) *cursorc = cc; if (cursoro != NULL) *cursoro = co; FUN(tok,finish)(tok); *argv = (const Char **)tok->argv; *argc = (int)tok->argc; return 0; } /* FUN(tok,str)(): * Simpler version of tok_line, taking a NUL terminated line * and splitting into words, ignoring cursor state. */ int FUN(tok,str)(TYPE(Tokenizer) *tok, const Char *line, int *argc, const Char ***argv) { TYPE(LineInfo) li; memset(&li, 0, sizeof(li)); li.buffer = line; li.cursor = li.lastchar = Strchr(line, '\0'); return FUN(tok,line)(tok, &li, argc, argv, NULL, NULL); } heimdal-7.5.0/lib/libedit/src/prompt.h0000644000175000017500000000470313026237312015720 0ustar niknik/* $NetBSD: prompt.h,v 1.15 2016/05/09 21:46:56 christos Exp $ */ /*- * Copyright (c) 1992, 1993 * The Regents of the University of California. All rights reserved. * * This code is derived from software contributed to Berkeley by * Christos Zoulas of Cornell University. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the University nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * * @(#)prompt.h 8.1 (Berkeley) 6/4/93 */ /* * el.prompt.h: Prompt printing stuff */ #ifndef _h_el_prompt #define _h_el_prompt typedef wchar_t *(*el_pfunc_t)(EditLine *); typedef struct el_prompt_t { el_pfunc_t p_func; /* Function to return the prompt */ coord_t p_pos; /* position in the line after prompt */ wchar_t p_ignore; /* character to start/end literal */ int p_wide; } el_prompt_t; libedit_private void prompt_print(EditLine *, int); libedit_private int prompt_set(EditLine *, el_pfunc_t, wchar_t, int, int); libedit_private int prompt_get(EditLine *, el_pfunc_t *, wchar_t *, int); libedit_private int prompt_init(EditLine *); libedit_private void prompt_end(EditLine *); #endif /* _h_el_prompt */ heimdal-7.5.0/lib/libedit/src/chartype.c0000644000175000017500000001715513026237312016216 0ustar niknik/* $NetBSD: chartype.c,v 1.30 2016/05/09 21:46:56 christos Exp $ */ /*- * Copyright (c) 2009 The NetBSD Foundation, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ /* * chartype.c: character classification and meta information */ #include "config.h" #if !defined(lint) && !defined(SCCSID) __RCSID("$NetBSD: chartype.c,v 1.30 2016/05/09 21:46:56 christos Exp $"); #endif /* not lint && not SCCSID */ #include #include #include #include "el.h" #define CT_BUFSIZ ((size_t)1024) static int ct_conv_cbuff_resize(ct_buffer_t *, size_t); static int ct_conv_wbuff_resize(ct_buffer_t *, size_t); static int ct_conv_cbuff_resize(ct_buffer_t *conv, size_t csize) { void *p; if (csize <= conv->csize) return 0; conv->csize = csize; p = el_realloc(conv->cbuff, conv->csize * sizeof(*conv->cbuff)); if (p == NULL) { conv->csize = 0; el_free(conv->cbuff); conv->cbuff = NULL; return -1; } conv->cbuff = p; return 0; } static int ct_conv_wbuff_resize(ct_buffer_t *conv, size_t wsize) { void *p; if (wsize <= conv->wsize) return 0; conv->wsize = wsize; p = el_realloc(conv->wbuff, conv->wsize * sizeof(*conv->wbuff)); if (p == NULL) { conv->wsize = 0; el_free(conv->wbuff); conv->wbuff = NULL; return -1; } conv->wbuff = p; return 0; } char * ct_encode_string(const wchar_t *s, ct_buffer_t *conv) { char *dst; ssize_t used; if (!s) return NULL; dst = conv->cbuff; for (;;) { used = (ssize_t)(dst - conv->cbuff); if ((conv->csize - (size_t)used) < 5) { if (ct_conv_cbuff_resize(conv, conv->csize + CT_BUFSIZ) == -1) return NULL; dst = conv->cbuff + used; } if (!*s) break; used = ct_encode_char(dst, (size_t)5, *s); if (used == -1) /* failed to encode, need more buffer space */ abort(); ++s; dst += used; } *dst = '\0'; return conv->cbuff; } wchar_t * ct_decode_string(const char *s, ct_buffer_t *conv) { size_t len; if (!s) return NULL; len = mbstowcs(NULL, s, (size_t)0); if (len == (size_t)-1) return NULL; if (conv->wsize < ++len) if (ct_conv_wbuff_resize(conv, len + CT_BUFSIZ) == -1) return NULL; mbstowcs(conv->wbuff, s, conv->wsize); return conv->wbuff; } libedit_private wchar_t ** ct_decode_argv(int argc, const char *argv[], ct_buffer_t *conv) { size_t bufspace; int i; wchar_t *p; wchar_t **wargv; ssize_t bytes; /* Make sure we have enough space in the conversion buffer to store all * the argv strings. */ for (i = 0, bufspace = 0; i < argc; ++i) bufspace += argv[i] ? strlen(argv[i]) + 1 : 0; if (conv->wsize < ++bufspace) if (ct_conv_wbuff_resize(conv, bufspace + CT_BUFSIZ) == -1) return NULL; wargv = el_malloc((size_t)argc * sizeof(*wargv)); for (i = 0, p = conv->wbuff; i < argc; ++i) { if (!argv[i]) { /* don't pass null pointers to mbstowcs */ wargv[i] = NULL; continue; } else { wargv[i] = p; bytes = (ssize_t)mbstowcs(p, argv[i], bufspace); } if (bytes == -1) { el_free(wargv); return NULL; } else bytes++; /* include '\0' in the count */ bufspace -= (size_t)bytes; p += bytes; } return wargv; } libedit_private size_t ct_enc_width(wchar_t c) { /* UTF-8 encoding specific values */ if (c < 0x80) return 1; else if (c < 0x0800) return 2; else if (c < 0x10000) return 3; else if (c < 0x110000) return 4; else return 0; /* not a valid codepoint */ } libedit_private ssize_t ct_encode_char(char *dst, size_t len, wchar_t c) { ssize_t l = 0; if (len < ct_enc_width(c)) return -1; l = wctomb(dst, c); if (l < 0) { wctomb(NULL, L'\0'); l = 0; } return l; } libedit_private const wchar_t * ct_visual_string(const wchar_t *s, ct_buffer_t *conv) { wchar_t *dst; ssize_t used; if (!s) return NULL; if (ct_conv_wbuff_resize(conv, CT_BUFSIZ) == -1) return NULL; used = 0; dst = conv->wbuff; while (*s) { used = ct_visual_char(dst, conv->wsize - (size_t)(dst - conv->wbuff), *s); if (used != -1) { ++s; dst += used; continue; } /* failed to encode, need more buffer space */ used = dst - conv->wbuff; if (ct_conv_wbuff_resize(conv, conv->wsize + CT_BUFSIZ) == -1) return NULL; dst = conv->wbuff + used; } if (dst >= (conv->wbuff + conv->wsize)) { /* sigh */ used = dst - conv->wbuff; if (ct_conv_wbuff_resize(conv, conv->wsize + CT_BUFSIZ) == -1) return NULL; dst = conv->wbuff + used; } *dst = L'\0'; return conv->wbuff; } libedit_private int ct_visual_width(wchar_t c) { int t = ct_chr_class(c); switch (t) { case CHTYPE_ASCIICTL: return 2; /* ^@ ^? etc. */ case CHTYPE_TAB: return 1; /* Hmm, this really need to be handled outside! */ case CHTYPE_NL: return 0; /* Should this be 1 instead? */ case CHTYPE_PRINT: return wcwidth(c); case CHTYPE_NONPRINT: if (c > 0xffff) /* prefer standard 4-byte display over 5-byte */ return 8; /* \U+12345 */ else return 7; /* \U+1234 */ default: return 0; /* should not happen */ } } libedit_private ssize_t ct_visual_char(wchar_t *dst, size_t len, wchar_t c) { int t = ct_chr_class(c); switch (t) { case CHTYPE_TAB: case CHTYPE_NL: case CHTYPE_ASCIICTL: if (len < 2) return -1; /* insufficient space */ *dst++ = '^'; if (c == '\177') *dst = '?'; /* DEL -> ^? */ else *dst = c | 0100; /* uncontrolify it */ return 2; case CHTYPE_PRINT: if (len < 1) return -1; /* insufficient space */ *dst = c; return 1; case CHTYPE_NONPRINT: /* we only use single-width glyphs for display, * so this is right */ if ((ssize_t)len < ct_visual_width(c)) return -1; /* insufficient space */ *dst++ = '\\'; *dst++ = 'U'; *dst++ = '+'; #define tohexdigit(v) "0123456789ABCDEF"[v] if (c > 0xffff) /* prefer standard 4-byte display over 5-byte */ *dst++ = tohexdigit(((unsigned int) c >> 16) & 0xf); *dst++ = tohexdigit(((unsigned int) c >> 12) & 0xf); *dst++ = tohexdigit(((unsigned int) c >> 8) & 0xf); *dst++ = tohexdigit(((unsigned int) c >> 4) & 0xf); *dst = tohexdigit(((unsigned int) c ) & 0xf); return c > 0xffff ? 8 : 7; /*FALLTHROUGH*/ /* these two should be handled outside this function */ default: /* we should never hit the default */ return 0; } } libedit_private int ct_chr_class(wchar_t c) { if (c == '\t') return CHTYPE_TAB; else if (c == '\n') return CHTYPE_NL; else if (c < 0x100 && iswcntrl(c)) return CHTYPE_ASCIICTL; else if (iswprint(c)) return CHTYPE_PRINT; else return CHTYPE_NONPRINT; } heimdal-7.5.0/lib/libedit/src/chared.c0000644000175000017500000004124113026237312015616 0ustar niknik/* $NetBSD: chared.c,v 1.56 2016/05/22 19:44:26 christos Exp $ */ /*- * Copyright (c) 1992, 1993 * The Regents of the University of California. All rights reserved. * * This code is derived from software contributed to Berkeley by * Christos Zoulas of Cornell University. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the University nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "config.h" #if !defined(lint) && !defined(SCCSID) #if 0 static char sccsid[] = "@(#)chared.c 8.1 (Berkeley) 6/4/93"; #else __RCSID("$NetBSD: chared.c,v 1.56 2016/05/22 19:44:26 christos Exp $"); #endif #endif /* not lint && not SCCSID */ /* * chared.c: Character editor utilities */ #include #include #include #include "el.h" #include "common.h" #include "fcns.h" /* value to leave unused in line buffer */ #define EL_LEAVE 2 /* cv_undo(): * Handle state for the vi undo command */ libedit_private void cv_undo(EditLine *el) { c_undo_t *vu = &el->el_chared.c_undo; c_redo_t *r = &el->el_chared.c_redo; size_t size; /* Save entire line for undo */ size = (size_t)(el->el_line.lastchar - el->el_line.buffer); vu->len = (ssize_t)size; vu->cursor = (int)(el->el_line.cursor - el->el_line.buffer); (void)memcpy(vu->buf, el->el_line.buffer, size * sizeof(*vu->buf)); /* save command info for redo */ r->count = el->el_state.doingarg ? el->el_state.argument : 0; r->action = el->el_chared.c_vcmd.action; r->pos = r->buf; r->cmd = el->el_state.thiscmd; r->ch = el->el_state.thisch; } /* cv_yank(): * Save yank/delete data for paste */ libedit_private void cv_yank(EditLine *el, const wchar_t *ptr, int size) { c_kill_t *k = &el->el_chared.c_kill; (void)memcpy(k->buf, ptr, (size_t)size * sizeof(*k->buf)); k->last = k->buf + size; } /* c_insert(): * Insert num characters */ libedit_private void c_insert(EditLine *el, int num) { wchar_t *cp; if (el->el_line.lastchar + num >= el->el_line.limit) { if (!ch_enlargebufs(el, (size_t)num)) return; /* can't go past end of buffer */ } if (el->el_line.cursor < el->el_line.lastchar) { /* if I must move chars */ for (cp = el->el_line.lastchar; cp >= el->el_line.cursor; cp--) cp[num] = *cp; } el->el_line.lastchar += num; } /* c_delafter(): * Delete num characters after the cursor */ libedit_private void c_delafter(EditLine *el, int num) { if (el->el_line.cursor + num > el->el_line.lastchar) num = (int)(el->el_line.lastchar - el->el_line.cursor); if (el->el_map.current != el->el_map.emacs) { cv_undo(el); cv_yank(el, el->el_line.cursor, num); } if (num > 0) { wchar_t *cp; for (cp = el->el_line.cursor; cp <= el->el_line.lastchar; cp++) *cp = cp[num]; el->el_line.lastchar -= num; } } /* c_delafter1(): * Delete the character after the cursor, do not yank */ libedit_private void c_delafter1(EditLine *el) { wchar_t *cp; for (cp = el->el_line.cursor; cp <= el->el_line.lastchar; cp++) *cp = cp[1]; el->el_line.lastchar--; } /* c_delbefore(): * Delete num characters before the cursor */ libedit_private void c_delbefore(EditLine *el, int num) { if (el->el_line.cursor - num < el->el_line.buffer) num = (int)(el->el_line.cursor - el->el_line.buffer); if (el->el_map.current != el->el_map.emacs) { cv_undo(el); cv_yank(el, el->el_line.cursor - num, num); } if (num > 0) { wchar_t *cp; for (cp = el->el_line.cursor - num; cp <= el->el_line.lastchar; cp++) *cp = cp[num]; el->el_line.lastchar -= num; } } /* c_delbefore1(): * Delete the character before the cursor, do not yank */ libedit_private void c_delbefore1(EditLine *el) { wchar_t *cp; for (cp = el->el_line.cursor - 1; cp <= el->el_line.lastchar; cp++) *cp = cp[1]; el->el_line.lastchar--; } /* ce__isword(): * Return if p is part of a word according to emacs */ libedit_private int ce__isword(wint_t p) { return iswalnum(p) || wcschr(L"*?_-.[]~=", p) != NULL; } /* cv__isword(): * Return if p is part of a word according to vi */ libedit_private int cv__isword(wint_t p) { if (iswalnum(p) || p == L'_') return 1; if (iswgraph(p)) return 2; return 0; } /* cv__isWord(): * Return if p is part of a big word according to vi */ libedit_private int cv__isWord(wint_t p) { return !iswspace(p); } /* c__prev_word(): * Find the previous word */ libedit_private wchar_t * c__prev_word(wchar_t *p, wchar_t *low, int n, int (*wtest)(wint_t)) { p--; while (n--) { while ((p >= low) && !(*wtest)(*p)) p--; while ((p >= low) && (*wtest)(*p)) p--; } /* cp now points to one character before the word */ p++; if (p < low) p = low; /* cp now points where we want it */ return p; } /* c__next_word(): * Find the next word */ libedit_private wchar_t * c__next_word(wchar_t *p, wchar_t *high, int n, int (*wtest)(wint_t)) { while (n--) { while ((p < high) && !(*wtest)(*p)) p++; while ((p < high) && (*wtest)(*p)) p++; } if (p > high) p = high; /* p now points where we want it */ return p; } /* cv_next_word(): * Find the next word vi style */ libedit_private wchar_t * cv_next_word(EditLine *el, wchar_t *p, wchar_t *high, int n, int (*wtest)(wint_t)) { int test; while (n--) { test = (*wtest)(*p); while ((p < high) && (*wtest)(*p) == test) p++; /* * vi historically deletes with cw only the word preserving the * trailing whitespace! This is not what 'w' does.. */ if (n || el->el_chared.c_vcmd.action != (DELETE|INSERT)) while ((p < high) && iswspace(*p)) p++; } /* p now points where we want it */ if (p > high) return high; else return p; } /* cv_prev_word(): * Find the previous word vi style */ libedit_private wchar_t * cv_prev_word(wchar_t *p, wchar_t *low, int n, int (*wtest)(wint_t)) { int test; p--; while (n--) { while ((p > low) && iswspace(*p)) p--; test = (*wtest)(*p); while ((p >= low) && (*wtest)(*p) == test) p--; } p++; /* p now points where we want it */ if (p < low) return low; else return p; } /* cv_delfini(): * Finish vi delete action */ libedit_private void cv_delfini(EditLine *el) { int size; int action = el->el_chared.c_vcmd.action; if (action & INSERT) el->el_map.current = el->el_map.key; if (el->el_chared.c_vcmd.pos == 0) /* sanity */ return; size = (int)(el->el_line.cursor - el->el_chared.c_vcmd.pos); if (size == 0) size = 1; el->el_line.cursor = el->el_chared.c_vcmd.pos; if (action & YANK) { if (size > 0) cv_yank(el, el->el_line.cursor, size); else cv_yank(el, el->el_line.cursor + size, -size); } else { if (size > 0) { c_delafter(el, size); re_refresh_cursor(el); } else { c_delbefore(el, -size); el->el_line.cursor += size; } } el->el_chared.c_vcmd.action = NOP; } /* cv__endword(): * Go to the end of this word according to vi */ libedit_private wchar_t * cv__endword(wchar_t *p, wchar_t *high, int n, int (*wtest)(wint_t)) { int test; p++; while (n--) { while ((p < high) && iswspace(*p)) p++; test = (*wtest)(*p); while ((p < high) && (*wtest)(*p) == test) p++; } p--; return p; } /* ch_init(): * Initialize the character editor */ libedit_private int ch_init(EditLine *el) { el->el_line.buffer = el_malloc(EL_BUFSIZ * sizeof(*el->el_line.buffer)); if (el->el_line.buffer == NULL) return -1; (void) memset(el->el_line.buffer, 0, EL_BUFSIZ * sizeof(*el->el_line.buffer)); el->el_line.cursor = el->el_line.buffer; el->el_line.lastchar = el->el_line.buffer; el->el_line.limit = &el->el_line.buffer[EL_BUFSIZ - EL_LEAVE]; el->el_chared.c_undo.buf = el_malloc(EL_BUFSIZ * sizeof(*el->el_chared.c_undo.buf)); if (el->el_chared.c_undo.buf == NULL) return -1; (void) memset(el->el_chared.c_undo.buf, 0, EL_BUFSIZ * sizeof(*el->el_chared.c_undo.buf)); el->el_chared.c_undo.len = -1; el->el_chared.c_undo.cursor = 0; el->el_chared.c_redo.buf = el_malloc(EL_BUFSIZ * sizeof(*el->el_chared.c_redo.buf)); if (el->el_chared.c_redo.buf == NULL) return -1; el->el_chared.c_redo.pos = el->el_chared.c_redo.buf; el->el_chared.c_redo.lim = el->el_chared.c_redo.buf + EL_BUFSIZ; el->el_chared.c_redo.cmd = ED_UNASSIGNED; el->el_chared.c_vcmd.action = NOP; el->el_chared.c_vcmd.pos = el->el_line.buffer; el->el_chared.c_kill.buf = el_malloc(EL_BUFSIZ * sizeof(*el->el_chared.c_kill.buf)); if (el->el_chared.c_kill.buf == NULL) return -1; (void) memset(el->el_chared.c_kill.buf, 0, EL_BUFSIZ * sizeof(*el->el_chared.c_kill.buf)); el->el_chared.c_kill.mark = el->el_line.buffer; el->el_chared.c_kill.last = el->el_chared.c_kill.buf; el->el_chared.c_resizefun = NULL; el->el_chared.c_resizearg = NULL; el->el_chared.c_aliasfun = NULL; el->el_chared.c_aliasarg = NULL; el->el_map.current = el->el_map.key; el->el_state.inputmode = MODE_INSERT; /* XXX: save a default */ el->el_state.doingarg = 0; el->el_state.metanext = 0; el->el_state.argument = 1; el->el_state.lastcmd = ED_UNASSIGNED; return 0; } /* ch_reset(): * Reset the character editor */ libedit_private void ch_reset(EditLine *el) { el->el_line.cursor = el->el_line.buffer; el->el_line.lastchar = el->el_line.buffer; el->el_chared.c_undo.len = -1; el->el_chared.c_undo.cursor = 0; el->el_chared.c_vcmd.action = NOP; el->el_chared.c_vcmd.pos = el->el_line.buffer; el->el_chared.c_kill.mark = el->el_line.buffer; el->el_map.current = el->el_map.key; el->el_state.inputmode = MODE_INSERT; /* XXX: save a default */ el->el_state.doingarg = 0; el->el_state.metanext = 0; el->el_state.argument = 1; el->el_state.lastcmd = ED_UNASSIGNED; el->el_history.eventno = 0; } /* ch_enlargebufs(): * Enlarge line buffer to be able to hold twice as much characters. * Returns 1 if successful, 0 if not. */ libedit_private int ch_enlargebufs(EditLine *el, size_t addlen) { size_t sz, newsz; wchar_t *newbuffer, *oldbuf, *oldkbuf; sz = (size_t)(el->el_line.limit - el->el_line.buffer + EL_LEAVE); newsz = sz * 2; /* * If newly required length is longer than current buffer, we need * to make the buffer big enough to hold both old and new stuff. */ if (addlen > sz) { while(newsz - sz < addlen) newsz *= 2; } /* * Reallocate line buffer. */ newbuffer = el_realloc(el->el_line.buffer, newsz * sizeof(*newbuffer)); if (!newbuffer) return 0; /* zero the newly added memory, leave old data in */ (void) memset(&newbuffer[sz], 0, (newsz - sz) * sizeof(*newbuffer)); oldbuf = el->el_line.buffer; el->el_line.buffer = newbuffer; el->el_line.cursor = newbuffer + (el->el_line.cursor - oldbuf); el->el_line.lastchar = newbuffer + (el->el_line.lastchar - oldbuf); /* don't set new size until all buffers are enlarged */ el->el_line.limit = &newbuffer[sz - EL_LEAVE]; /* * Reallocate kill buffer. */ newbuffer = el_realloc(el->el_chared.c_kill.buf, newsz * sizeof(*newbuffer)); if (!newbuffer) return 0; /* zero the newly added memory, leave old data in */ (void) memset(&newbuffer[sz], 0, (newsz - sz) * sizeof(*newbuffer)); oldkbuf = el->el_chared.c_kill.buf; el->el_chared.c_kill.buf = newbuffer; el->el_chared.c_kill.last = newbuffer + (el->el_chared.c_kill.last - oldkbuf); el->el_chared.c_kill.mark = el->el_line.buffer + (el->el_chared.c_kill.mark - oldbuf); /* * Reallocate undo buffer. */ newbuffer = el_realloc(el->el_chared.c_undo.buf, newsz * sizeof(*newbuffer)); if (!newbuffer) return 0; /* zero the newly added memory, leave old data in */ (void) memset(&newbuffer[sz], 0, (newsz - sz) * sizeof(*newbuffer)); el->el_chared.c_undo.buf = newbuffer; newbuffer = el_realloc(el->el_chared.c_redo.buf, newsz * sizeof(*newbuffer)); if (!newbuffer) return 0; el->el_chared.c_redo.pos = newbuffer + (el->el_chared.c_redo.pos - el->el_chared.c_redo.buf); el->el_chared.c_redo.lim = newbuffer + (el->el_chared.c_redo.lim - el->el_chared.c_redo.buf); el->el_chared.c_redo.buf = newbuffer; if (!hist_enlargebuf(el, sz, newsz)) return 0; /* Safe to set enlarged buffer size */ el->el_line.limit = &el->el_line.buffer[newsz - EL_LEAVE]; if (el->el_chared.c_resizefun) (*el->el_chared.c_resizefun)(el, el->el_chared.c_resizearg); return 1; } /* ch_end(): * Free the data structures used by the editor */ libedit_private void ch_end(EditLine *el) { el_free(el->el_line.buffer); el->el_line.buffer = NULL; el->el_line.limit = NULL; el_free(el->el_chared.c_undo.buf); el->el_chared.c_undo.buf = NULL; el_free(el->el_chared.c_redo.buf); el->el_chared.c_redo.buf = NULL; el->el_chared.c_redo.pos = NULL; el->el_chared.c_redo.lim = NULL; el->el_chared.c_redo.cmd = ED_UNASSIGNED; el_free(el->el_chared.c_kill.buf); el->el_chared.c_kill.buf = NULL; ch_reset(el); } /* el_insertstr(): * Insert string at cursorI */ int el_winsertstr(EditLine *el, const wchar_t *s) { size_t len; if (s == NULL || (len = wcslen(s)) == 0) return -1; if (el->el_line.lastchar + len >= el->el_line.limit) { if (!ch_enlargebufs(el, len)) return -1; } c_insert(el, (int)len); while (*s) *el->el_line.cursor++ = *s++; return 0; } /* el_deletestr(): * Delete num characters before the cursor */ void el_deletestr(EditLine *el, int n) { if (n <= 0) return; if (el->el_line.cursor < &el->el_line.buffer[n]) return; c_delbefore(el, n); /* delete before dot */ el->el_line.cursor -= n; if (el->el_line.cursor < el->el_line.buffer) el->el_line.cursor = el->el_line.buffer; } /* el_cursor(): * Move the cursor to the left or the right of the current position */ int el_cursor(EditLine *el, int n) { if (n == 0) goto out; el->el_line.cursor += n; if (el->el_line.cursor < el->el_line.buffer) el->el_line.cursor = el->el_line.buffer; if (el->el_line.cursor > el->el_line.lastchar) el->el_line.cursor = el->el_line.lastchar; out: return (int)(el->el_line.cursor - el->el_line.buffer); } /* c_gets(): * Get a string */ libedit_private int c_gets(EditLine *el, wchar_t *buf, const wchar_t *prompt) { ssize_t len; wchar_t *cp = el->el_line.buffer, ch; if (prompt) { len = (ssize_t)wcslen(prompt); (void)memcpy(cp, prompt, (size_t)len * sizeof(*cp)); cp += len; } len = 0; for (;;) { el->el_line.cursor = cp; *cp = ' '; el->el_line.lastchar = cp + 1; re_refresh(el); if (el_wgetc(el, &ch) != 1) { ed_end_of_file(el, 0); len = -1; break; } switch (ch) { case L'\b': /* Delete and backspace */ case 0177: if (len == 0) { len = -1; break; } len--; cp--; continue; case 0033: /* ESC */ case L'\r': /* Newline */ case L'\n': buf[len] = ch; break; default: if (len >= (ssize_t)(EL_BUFSIZ - 16)) terminal_beep(el); else { buf[len++] = ch; *cp++ = ch; } continue; } break; } el->el_line.buffer[0] = '\0'; el->el_line.lastchar = el->el_line.buffer; el->el_line.cursor = el->el_line.buffer; return (int)len; } /* c_hpos(): * Return the current horizontal position of the cursor */ libedit_private int c_hpos(EditLine *el) { wchar_t *ptr; /* * Find how many characters till the beginning of this line. */ if (el->el_line.cursor == el->el_line.buffer) return 0; else { for (ptr = el->el_line.cursor - 1; ptr >= el->el_line.buffer && *ptr != '\n'; ptr--) continue; return (int)(el->el_line.cursor - ptr - 1); } } libedit_private int ch_resizefun(EditLine *el, el_zfunc_t f, void *a) { el->el_chared.c_resizefun = f; el->el_chared.c_resizearg = a; return 0; } libedit_private int ch_aliasfun(EditLine *el, el_afunc_t f, void *a) { el->el_chared.c_aliasfun = f; el->el_chared.c_aliasarg = a; return 0; } heimdal-7.5.0/lib/libedit/src/search.h0000644000175000017500000000544713026237312015652 0ustar niknik/* $NetBSD: search.h,v 1.14 2016/05/09 21:46:56 christos Exp $ */ /*- * Copyright (c) 1992, 1993 * The Regents of the University of California. All rights reserved. * * This code is derived from software contributed to Berkeley by * Christos Zoulas of Cornell University. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the University nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * * @(#)search.h 8.1 (Berkeley) 6/4/93 */ /* * el.search.h: Line and history searching utilities */ #ifndef _h_el_search #define _h_el_search typedef struct el_search_t { wchar_t *patbuf; /* The pattern buffer */ size_t patlen; /* Length of the pattern buffer */ int patdir; /* Direction of the last search */ int chadir; /* Character search direction */ wchar_t chacha; /* Character we are looking for */ char chatflg; /* 0 if f, 1 if t */ } el_search_t; libedit_private int el_match(const wchar_t *, const wchar_t *); libedit_private int search_init(EditLine *); libedit_private void search_end(EditLine *); libedit_private int c_hmatch(EditLine *, const wchar_t *); libedit_private void c_setpat(EditLine *); libedit_private el_action_t ce_inc_search(EditLine *, int); libedit_private el_action_t cv_search(EditLine *, int); libedit_private el_action_t ce_search_line(EditLine *, int); libedit_private el_action_t cv_repeat_srch(EditLine *, wint_t); libedit_private el_action_t cv_csearch(EditLine *, int, wint_t, int, int); #endif /* _h_el_search */ heimdal-7.5.0/lib/libedit/src/read.h0000644000175000017500000000370613026237312015314 0ustar niknik/* $NetBSD: read.h,v 1.12 2016/05/22 19:44:26 christos Exp $ */ /*- * Copyright (c) 2001 The NetBSD Foundation, Inc. * All rights reserved. * * This code is derived from software contributed to The NetBSD Foundation * by Anthony Mallet. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ /* * el.read.h: Character reading functions */ #ifndef _h_el_read #define _h_el_read libedit_private int read_init(EditLine *); libedit_private void read_end(struct el_read_t *); libedit_private void read_prepare(EditLine *); libedit_private void read_finish(EditLine *); libedit_private int el_read_setfn(struct el_read_t *, el_rfunc_t); libedit_private el_rfunc_t el_read_getfn(struct el_read_t *); #endif /* _h_el_read */ heimdal-7.5.0/lib/libedit/src/historyn.c0000644000175000017500000000007413026237312016246 0ustar niknik#include "config.h" #define NARROWCHAR #include "history.c" heimdal-7.5.0/lib/libedit/src/makelist0000644000175000017500000001071413026237312015761 0ustar niknik#!/bin/sh - # $NetBSD: makelist,v 1.29 2016/05/09 21:46:56 christos Exp $ # # Copyright (c) 1992, 1993 # The Regents of the University of California. All rights reserved. # # This code is derived from software contributed to Berkeley by # Christos Zoulas of Cornell University. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # 1. Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # 2. Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # 3. Neither the name of the University nor the names of its contributors # may be used to endorse or promote products derived from this software # without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE # ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS # OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) # HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY # OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF # SUCH DAMAGE. # # @(#)makelist 5.3 (Berkeley) 6/4/93 # makelist.sh: Automatically generate header files... AWK=awk USAGE="Usage: $0 -h|-fc|-fh|-bh " if [ "x$1" = "x" ] then echo $USAGE 1>&2 exit 1 fi FLAG="$1" shift FILES="$@" case $FLAG in -h) set - `echo $FILES | sed -e 's/\\./_/g'` hdr="_h_`basename $1`" cat $FILES | $AWK ' BEGIN { printf("/* Automatically generated file, do not edit */\n"); printf("#ifndef %s\n#define %s\n", "'$hdr'", "'$hdr'"); } /\(\):/ { pr = substr($2, 1, 2); if (pr == "vi" || pr == "em" || pr == "ed") { name = substr($2, 1, length($2) - 3); # # XXX: need a space between name and prototype so that -fc and -fh # parsing is much easier # printf("libedit_private el_action_t\t%s (EditLine *, wint_t);\n", name); } } END { printf("#endif /* %s */\n", "'$hdr'"); }' ;; # generate help.h from various .c files # -bh) cat $FILES | $AWK ' BEGIN { printf("/* Automatically generated file, do not edit */\n"); printf("static const struct el_bindings_t el_func_help[] = {\n"); low = "abcdefghijklmnopqrstuvwxyz_"; high = "ABCDEFGHIJKLMNOPQRSTUVWXYZ_"; for (i = 1; i <= length(low); i++) tr[substr(low, i, 1)] = substr(high, i, 1); } /\(\):/ { pr = substr($2, 1, 2); if (pr == "vi" || pr == "em" || pr == "ed") { name = substr($2, 1, length($2) - 3); uname = ""; fname = ""; for (i = 1; i <= length(name); i++) { s = substr(name, i, 1); uname = uname tr[s]; if (s == "_") s = "-"; fname = fname s; } printf(" { %-30.30s %-30.30s\n","L\"" fname "\",", uname ","); ok = 1; } } /^ \*/ { if (ok) { printf(" L\""); for (i = 2; i < NF; i++) printf("%s ", $i); printf("%s\" },\n", $i); ok = 0; } } END { printf("};\n"); }' ;; # generate fcns.h from various .h files # -fh) cat $FILES | $AWK '/el_action_t/ { print $3 }' | \ sort | tr '[:lower:]' '[:upper:]' | $AWK ' BEGIN { printf("/* Automatically generated file, do not edit */\n"); count = 0; } { printf("#define\t%-30.30s\t%3d\n", $1, count++); } END { printf("#define\t%-30.30s\t%3d\n", "EL_NUM_FCNS", count); }' ;; # generate func.h from various .h files # -fc) cat $FILES | $AWK '/el_action_t/ { print $3 }' | sort | $AWK ' BEGIN { printf("/* Automatically generated file, do not edit */\n"); printf("static const el_func_t el_func[] = {"); maxlen = 80; needn = 1; len = 0; } { clen = 25 + 2; len += clen; if (len >= maxlen) needn = 1; if (needn) { printf("\n "); needn = 0; len = 4 + clen; } s = $1 ","; printf("%-26.26s ", s); } END { printf("\n};\n"); }' ;; *) echo $USAGE 1>&2 exit 1 ;; esac heimdal-7.5.0/lib/libedit/src/parse.c0000644000175000017500000001406113026237312015502 0ustar niknik/* $NetBSD: parse.c,v 1.40 2016/05/09 21:46:56 christos Exp $ */ /*- * Copyright (c) 1992, 1993 * The Regents of the University of California. All rights reserved. * * This code is derived from software contributed to Berkeley by * Christos Zoulas of Cornell University. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the University nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "config.h" #if !defined(lint) && !defined(SCCSID) #if 0 static char sccsid[] = "@(#)parse.c 8.1 (Berkeley) 6/4/93"; #else __RCSID("$NetBSD: parse.c,v 1.40 2016/05/09 21:46:56 christos Exp $"); #endif #endif /* not lint && not SCCSID */ /* * parse.c: parse an editline extended command * * commands are: * * bind * echotc * edit * gettc * history * settc * setty */ #include #include #include "el.h" #include "parse.h" static const struct { const wchar_t *name; int (*func)(EditLine *, int, const wchar_t **); } cmds[] = { { L"bind", map_bind }, { L"echotc", terminal_echotc }, { L"edit", el_editmode }, { L"history", hist_command }, { L"telltc", terminal_telltc }, { L"settc", terminal_settc }, { L"setty", tty_stty }, { NULL, NULL } }; /* parse_line(): * Parse a line and dispatch it */ libedit_private int parse_line(EditLine *el, const wchar_t *line) { const wchar_t **argv; int argc; TokenizerW *tok; tok = tok_winit(NULL); tok_wstr(tok, line, &argc, &argv); argc = el_wparse(el, argc, argv); tok_wend(tok); return argc; } /* el_parse(): * Command dispatcher */ int el_wparse(EditLine *el, int argc, const wchar_t *argv[]) { const wchar_t *ptr; int i; if (argc < 1) return -1; ptr = wcschr(argv[0], L':'); if (ptr != NULL) { wchar_t *tprog; size_t l; if (ptr == argv[0]) return 0; l = (size_t)(ptr - argv[0] - 1); tprog = el_malloc((l + 1) * sizeof(*tprog)); if (tprog == NULL) return 0; (void) wcsncpy(tprog, argv[0], l); tprog[l] = '\0'; ptr++; l = (size_t)el_match(el->el_prog, tprog); el_free(tprog); if (!l) return 0; } else ptr = argv[0]; for (i = 0; cmds[i].name != NULL; i++) if (wcscmp(cmds[i].name, ptr) == 0) { i = (*cmds[i].func) (el, argc, argv); return -i; } return -1; } /* parse__escape(): * Parse a string of the form ^ \ \ \U+xxxx and return * the appropriate character or -1 if the escape is not valid */ libedit_private int parse__escape(const wchar_t **ptr) { const wchar_t *p; wint_t c; p = *ptr; if (p[1] == 0) return -1; if (*p == '\\') { p++; switch (*p) { case 'a': c = '\007'; /* Bell */ break; case 'b': c = '\010'; /* Backspace */ break; case 't': c = '\011'; /* Horizontal Tab */ break; case 'n': c = '\012'; /* New Line */ break; case 'v': c = '\013'; /* Vertical Tab */ break; case 'f': c = '\014'; /* Form Feed */ break; case 'r': c = '\015'; /* Carriage Return */ break; case 'e': c = '\033'; /* Escape */ break; case 'U': /* Unicode \U+xxxx or \U+xxxxx format */ { int i; const wchar_t hex[] = L"0123456789ABCDEF"; const wchar_t *h; ++p; if (*p++ != '+') return -1; c = 0; for (i = 0; i < 5; ++i) { h = wcschr(hex, *p++); if (!h && i < 4) return -1; else if (h) c = (c << 4) | ((int)(h - hex)); else --p; } if (c > 0x10FFFF) /* outside valid character range */ return -1; break; } case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': { int cnt, ch; for (cnt = 0, c = 0; cnt < 3; cnt++) { ch = *p++; if (ch < '0' || ch > '7') { p--; break; } c = (c << 3) | (ch - '0'); } if ((c & (wint_t)0xffffff00) != (wint_t)0) return -1; --p; break; } default: c = *p; break; } } else if (*p == '^') { p++; c = (*p == '?') ? '\177' : (*p & 0237); } else c = *p; *ptr = ++p; return c; } /* parse__string(): * Parse the escapes from in and put the raw string out */ libedit_private wchar_t * parse__string(wchar_t *out, const wchar_t *in) { wchar_t *rv = out; int n; for (;;) switch (*in) { case '\0': *out = '\0'; return rv; case '\\': case '^': if ((n = parse__escape(&in)) == -1) return NULL; *out++ = (wchar_t)n; break; case 'M': if (in[1] == '-' && in[2] != '\0') { *out++ = '\033'; in += 2; break; } /*FALLTHROUGH*/ default: *out++ = *in++; break; } } /* parse_cmd(): * Return the command number for the command string given * or -1 if one is not found */ libedit_private int parse_cmd(EditLine *el, const wchar_t *cmd) { el_bindings_t *b = el->el_map.help; size_t i; for (i = 0; i < el->el_map.nfunc; i++) if (wcscmp(b[i].name, cmd) == 0) return b[i].func; return -1; } heimdal-7.5.0/lib/libedit/src/filecomplete.c0000644000175000017500000003540313026237312017043 0ustar niknik/* $NetBSD: filecomplete.c,v 1.44 2016/10/31 17:46:32 abhinav Exp $ */ /*- * Copyright (c) 1997 The NetBSD Foundation, Inc. * All rights reserved. * * This code is derived from software contributed to The NetBSD Foundation * by Jaromir Dolecek. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include "config.h" #if !defined(lint) && !defined(SCCSID) __RCSID("$NetBSD: filecomplete.c,v 1.44 2016/10/31 17:46:32 abhinav Exp $"); #endif /* not lint && not SCCSID */ #include #include #include #include #include #include #include #include #include #include #include #include "el.h" #include "filecomplete.h" static const wchar_t break_chars[] = L" \t\n\"\\'`@$><=;|&{("; /********************************/ /* completion functions */ /* * does tilde expansion of strings of type ``~user/foo'' * if ``user'' isn't valid user name or ``txt'' doesn't start * w/ '~', returns pointer to strdup()ed copy of ``txt'' * * it's the caller's responsibility to free() the returned string */ char * fn_tilde_expand(const char *txt) { #if defined(HAVE_GETPW_R_POSIX) || defined(HAVE_GETPW_R_DRAFT) struct passwd pwres; char pwbuf[1024]; #endif struct passwd *pass; char *temp; size_t len = 0; if (txt[0] != '~') return strdup(txt); temp = strchr(txt + 1, '/'); if (temp == NULL) { temp = strdup(txt + 1); if (temp == NULL) return NULL; } else { /* text until string after slash */ len = (size_t)(temp - txt + 1); temp = el_malloc(len * sizeof(*temp)); if (temp == NULL) return NULL; (void)strncpy(temp, txt + 1, len - 2); temp[len - 2] = '\0'; } if (temp[0] == 0) { #ifdef HAVE_GETPW_R_POSIX if (getpwuid_r(getuid(), &pwres, pwbuf, sizeof(pwbuf), &pass) != 0) pass = NULL; #elif HAVE_GETPW_R_DRAFT pass = getpwuid_r(getuid(), &pwres, pwbuf, sizeof(pwbuf)); #else pass = getpwuid(getuid()); #endif } else { #ifdef HAVE_GETPW_R_POSIX if (getpwnam_r(temp, &pwres, pwbuf, sizeof(pwbuf), &pass) != 0) pass = NULL; #elif HAVE_GETPW_R_DRAFT pass = getpwnam_r(temp, &pwres, pwbuf, sizeof(pwbuf)); #else pass = getpwnam(temp); #endif } el_free(temp); /* value no more needed */ if (pass == NULL) return strdup(txt); /* update pointer txt to point at string immedially following */ /* first slash */ txt += len; len = strlen(pass->pw_dir) + 1 + strlen(txt) + 1; temp = el_malloc(len * sizeof(*temp)); if (temp == NULL) return NULL; (void)snprintf(temp, len, "%s/%s", pass->pw_dir, txt); return temp; } /* * return first found file name starting by the ``text'' or NULL if no * such file can be found * value of ``state'' is ignored * * it's the caller's responsibility to free the returned string */ char * fn_filename_completion_function(const char *text, int state) { static DIR *dir = NULL; static char *filename = NULL, *dirname = NULL, *dirpath = NULL; static size_t filename_len = 0; struct dirent *entry; char *temp; size_t len; if (state == 0 || dir == NULL) { temp = strrchr(text, '/'); if (temp) { char *nptr; temp++; nptr = el_realloc(filename, (strlen(temp) + 1) * sizeof(*nptr)); if (nptr == NULL) { el_free(filename); filename = NULL; return NULL; } filename = nptr; (void)strcpy(filename, temp); len = (size_t)(temp - text); /* including last slash */ nptr = el_realloc(dirname, (len + 1) * sizeof(*nptr)); if (nptr == NULL) { el_free(dirname); dirname = NULL; return NULL; } dirname = nptr; (void)strncpy(dirname, text, len); dirname[len] = '\0'; } else { el_free(filename); if (*text == 0) filename = NULL; else { filename = strdup(text); if (filename == NULL) return NULL; } el_free(dirname); dirname = NULL; } if (dir != NULL) { (void)closedir(dir); dir = NULL; } /* support for ``~user'' syntax */ el_free(dirpath); dirpath = NULL; if (dirname == NULL) { if ((dirname = strdup("")) == NULL) return NULL; dirpath = strdup("./"); } else if (*dirname == '~') dirpath = fn_tilde_expand(dirname); else dirpath = strdup(dirname); if (dirpath == NULL) return NULL; dir = opendir(dirpath); if (!dir) return NULL; /* cannot open the directory */ /* will be used in cycle */ filename_len = filename ? strlen(filename) : 0; } /* find the match */ while ((entry = readdir(dir)) != NULL) { /* skip . and .. */ if (entry->d_name[0] == '.' && (!entry->d_name[1] || (entry->d_name[1] == '.' && !entry->d_name[2]))) continue; if (filename_len == 0) break; /* otherwise, get first entry where first */ /* filename_len characters are equal */ if (entry->d_name[0] == filename[0] #if HAVE_STRUCT_DIRENT_D_NAMLEN && entry->d_namlen >= filename_len #else && strlen(entry->d_name) >= filename_len #endif && strncmp(entry->d_name, filename, filename_len) == 0) break; } if (entry) { /* match found */ #if HAVE_STRUCT_DIRENT_D_NAMLEN len = entry->d_namlen; #else len = strlen(entry->d_name); #endif len = strlen(dirname) + len + 1; temp = el_malloc(len * sizeof(*temp)); if (temp == NULL) return NULL; (void)snprintf(temp, len, "%s%s", dirname, entry->d_name); } else { (void)closedir(dir); dir = NULL; temp = NULL; } return temp; } static const char * append_char_function(const char *name) { struct stat stbuf; char *expname = *name == '~' ? fn_tilde_expand(name) : NULL; const char *rs = " "; if (stat(expname ? expname : name, &stbuf) == -1) goto out; if (S_ISDIR(stbuf.st_mode)) rs = "/"; out: if (expname) el_free(expname); return rs; } /* * returns list of completions for text given * non-static for readline. */ char ** completion_matches(const char *, char *(*)(const char *, int)); char ** completion_matches(const char *text, char *(*genfunc)(const char *, int)) { char **match_list = NULL, *retstr, *prevstr; size_t match_list_len, max_equal, which, i; size_t matches; matches = 0; match_list_len = 1; while ((retstr = (*genfunc) (text, (int)matches)) != NULL) { /* allow for list terminator here */ if (matches + 3 >= match_list_len) { char **nmatch_list; while (matches + 3 >= match_list_len) match_list_len <<= 1; nmatch_list = el_realloc(match_list, match_list_len * sizeof(*nmatch_list)); if (nmatch_list == NULL) { el_free(match_list); return NULL; } match_list = nmatch_list; } match_list[++matches] = retstr; } if (!match_list) return NULL; /* nothing found */ /* find least denominator and insert it to match_list[0] */ which = 2; prevstr = match_list[1]; max_equal = strlen(prevstr); for (; which <= matches; which++) { for (i = 0; i < max_equal && prevstr[i] == match_list[which][i]; i++) continue; max_equal = i; } retstr = el_malloc((max_equal + 1) * sizeof(*retstr)); if (retstr == NULL) { el_free(match_list); return NULL; } (void)strncpy(retstr, match_list[1], max_equal); retstr[max_equal] = '\0'; match_list[0] = retstr; /* add NULL as last pointer to the array */ match_list[matches + 1] = NULL; return match_list; } /* * Sort function for qsort(). Just wrapper around strcasecmp(). */ static int _fn_qsort_string_compare(const void *i1, const void *i2) { const char *s1 = ((const char * const *)i1)[0]; const char *s2 = ((const char * const *)i2)[0]; return strcasecmp(s1, s2); } /* * Display list of strings in columnar format on readline's output stream. * 'matches' is list of strings, 'num' is number of strings in 'matches', * 'width' is maximum length of string in 'matches'. * * matches[0] is not one of the match strings, but it is counted in * num, so the strings are matches[1] *through* matches[num-1]. */ void fn_display_match_list (EditLine *el, char **matches, size_t num, size_t width) { size_t line, lines, col, cols, thisguy; int screenwidth = el->el_terminal.t_size.h; /* Ignore matches[0]. Avoid 1-based array logic below. */ matches++; num--; /* * Find out how many entries can be put on one line; count * with one space between strings the same way it's printed. */ cols = (size_t)screenwidth / (width + 1); if (cols == 0) cols = 1; /* how many lines of output, rounded up */ lines = (num + cols - 1) / cols; /* Sort the items. */ qsort(matches, num, sizeof(char *), _fn_qsort_string_compare); /* * On the ith line print elements i, i+lines, i+lines*2, etc. */ for (line = 0; line < lines; line++) { for (col = 0; col < cols; col++) { thisguy = line + col * lines; if (thisguy >= num) break; (void)fprintf(el->el_outfile, "%s%-*s", col == 0 ? "" : " ", (int)width, matches[thisguy]); } (void)fprintf(el->el_outfile, "\n"); } } /* * Complete the word at or before point, * 'what_to_do' says what to do with the completion. * \t means do standard completion. * `?' means list the possible completions. * `*' means insert all of the possible completions. * `!' means to do standard completion, and list all possible completions if * there is more than one. * * Note: '*' support is not implemented * '!' could never be invoked */ int fn_complete(EditLine *el, char *(*complet_func)(const char *, int), char **(*attempted_completion_function)(const char *, int, int), const wchar_t *word_break, const wchar_t *special_prefixes, const char *(*app_func)(const char *), size_t query_items, int *completion_type, int *over, int *point, int *end) { const LineInfoW *li; wchar_t *temp; char **matches; const wchar_t *ctemp; size_t len; int what_to_do = '\t'; int retval = CC_NORM; if (el->el_state.lastcmd == el->el_state.thiscmd) what_to_do = '?'; /* readline's rl_complete() has to be told what we did... */ if (completion_type != NULL) *completion_type = what_to_do; if (!complet_func) complet_func = fn_filename_completion_function; if (!app_func) app_func = append_char_function; /* We now look backwards for the start of a filename/variable word */ li = el_wline(el); ctemp = li->cursor; while (ctemp > li->buffer && !wcschr(word_break, ctemp[-1]) && (!special_prefixes || !wcschr(special_prefixes, ctemp[-1]) ) ) ctemp--; len = (size_t)(li->cursor - ctemp); temp = el_malloc((len + 1) * sizeof(*temp)); (void)wcsncpy(temp, ctemp, len); temp[len] = '\0'; /* these can be used by function called in completion_matches() */ /* or (*attempted_completion_function)() */ if (point != NULL) *point = (int)(li->cursor - li->buffer); if (end != NULL) *end = (int)(li->lastchar - li->buffer); if (attempted_completion_function) { int cur_off = (int)(li->cursor - li->buffer); matches = (*attempted_completion_function)( ct_encode_string(temp, &el->el_scratch), cur_off - (int)len, cur_off); } else matches = NULL; if (!attempted_completion_function || (over != NULL && !*over && !matches)) matches = completion_matches( ct_encode_string(temp, &el->el_scratch), complet_func); if (over != NULL) *over = 0; if (matches) { int i; size_t matches_num, maxlen, match_len, match_display=1; retval = CC_REFRESH; /* * Only replace the completed string with common part of * possible matches if there is possible completion. */ if (matches[0][0] != '\0') { el_deletestr(el, (int) len); el_winsertstr(el, ct_decode_string(matches[0], &el->el_scratch)); } if (matches[2] == NULL && (matches[1] == NULL || strcmp(matches[0], matches[1]) == 0)) { /* * We found exact match. Add a space after * it, unless we do filename completion and the * object is a directory. */ el_winsertstr(el, ct_decode_string((*app_func)(matches[0]), &el->el_scratch)); } else if (what_to_do == '!' || what_to_do == '?') { /* * More than one match and requested to list possible * matches. */ for(i = 1, maxlen = 0; matches[i]; i++) { match_len = strlen(matches[i]); if (match_len > maxlen) maxlen = match_len; } /* matches[1] through matches[i-1] are available */ matches_num = (size_t)(i - 1); /* newline to get on next line from command line */ (void)fprintf(el->el_outfile, "\n"); /* * If there are too many items, ask user for display * confirmation. */ if (matches_num > query_items) { (void)fprintf(el->el_outfile, "Display all %zu possibilities? (y or n) ", matches_num); (void)fflush(el->el_outfile); if (getc(stdin) != 'y') match_display = 0; (void)fprintf(el->el_outfile, "\n"); } if (match_display) { /* * Interface of this function requires the * strings be matches[1..num-1] for compat. * We have matches_num strings not counting * the prefix in matches[0], so we need to * add 1 to matches_num for the call. */ fn_display_match_list(el, matches, matches_num+1, maxlen); } retval = CC_REDISPLAY; } else if (matches[0][0]) { /* * There was some common match, but the name was * not complete enough. Next tab will print possible * completions. */ el_beep(el); } else { /* lcd is not a valid object - further specification */ /* is needed */ el_beep(el); retval = CC_NORM; } /* free elements of array and the array itself */ for (i = 0; matches[i]; i++) el_free(matches[i]); el_free(matches); matches = NULL; } el_free(temp); return retval; } /* * el-compatible wrapper around rl_complete; needed for key binding */ /* ARGSUSED */ unsigned char _el_fn_complete(EditLine *el, int ch __attribute__((__unused__))) { return (unsigned char)fn_complete(el, NULL, NULL, break_chars, NULL, NULL, (size_t)100, NULL, NULL, NULL, NULL); } heimdal-7.5.0/lib/libedit/src/tty.c0000644000175000017500000007366013026237312015222 0ustar niknik/* $NetBSD: tty.c,v 1.65 2016/05/09 21:46:56 christos Exp $ */ /*- * Copyright (c) 1992, 1993 * The Regents of the University of California. All rights reserved. * * This code is derived from software contributed to Berkeley by * Christos Zoulas of Cornell University. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the University nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "config.h" #if !defined(lint) && !defined(SCCSID) #if 0 static char sccsid[] = "@(#)tty.c 8.1 (Berkeley) 6/4/93"; #else __RCSID("$NetBSD: tty.c,v 1.65 2016/05/09 21:46:56 christos Exp $"); #endif #endif /* not lint && not SCCSID */ /* * tty.c: tty interface stuff */ #include #include #include /* for abort */ #include #include /* for ffs */ #include /* for isatty */ #include "el.h" #include "fcns.h" #include "parse.h" typedef struct ttymodes_t { const char *m_name; unsigned int m_value; int m_type; } ttymodes_t; typedef struct ttymap_t { wint_t nch, och; /* Internal and termio rep of chars */ el_action_t bind[3]; /* emacs, vi, and vi-cmd */ } ttymap_t; static const ttyperm_t ttyperm = { { {"iflag:", ICRNL, (INLCR | IGNCR)}, {"oflag:", (OPOST | ONLCR), ONLRET}, {"cflag:", 0, 0}, {"lflag:", (ISIG | ICANON | ECHO | ECHOE | ECHOCTL | IEXTEN), (NOFLSH | ECHONL | EXTPROC | FLUSHO)}, {"chars:", 0, 0}, }, { {"iflag:", (INLCR | ICRNL), IGNCR}, {"oflag:", (OPOST | ONLCR), ONLRET}, {"cflag:", 0, 0}, {"lflag:", ISIG, (NOFLSH | ICANON | ECHO | ECHOK | ECHONL | EXTPROC | IEXTEN | FLUSHO)}, {"chars:", (C_SH(C_MIN) | C_SH(C_TIME) | C_SH(C_SWTCH) | C_SH(C_DSWTCH) | C_SH(C_SUSP) | C_SH(C_DSUSP) | C_SH(C_EOL) | C_SH(C_DISCARD) | C_SH(C_PGOFF) | C_SH(C_PAGE) | C_SH(C_STATUS)), 0} }, { {"iflag:", 0, IXON | IXOFF | INLCR | ICRNL}, {"oflag:", 0, 0}, {"cflag:", 0, 0}, {"lflag:", 0, ISIG | IEXTEN}, {"chars:", 0, 0}, } }; static const ttychar_t ttychar = { { CINTR, CQUIT, CERASE, CKILL, CEOF, CEOL, CEOL2, CSWTCH, CDSWTCH, CERASE2, CSTART, CSTOP, CWERASE, CSUSP, CDSUSP, CREPRINT, CDISCARD, CLNEXT, CSTATUS, CPAGE, CPGOFF, CKILL2, CBRK, CMIN, CTIME }, { CINTR, CQUIT, CERASE, CKILL, _POSIX_VDISABLE, _POSIX_VDISABLE, _POSIX_VDISABLE, _POSIX_VDISABLE, _POSIX_VDISABLE, CERASE2, CSTART, CSTOP, _POSIX_VDISABLE, CSUSP, _POSIX_VDISABLE, _POSIX_VDISABLE, CDISCARD, _POSIX_VDISABLE, _POSIX_VDISABLE, _POSIX_VDISABLE, _POSIX_VDISABLE, _POSIX_VDISABLE, _POSIX_VDISABLE, 1, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 } }; static const ttymap_t tty_map[] = { #ifdef VERASE {C_ERASE, VERASE, {EM_DELETE_PREV_CHAR, VI_DELETE_PREV_CHAR, ED_PREV_CHAR}}, #endif /* VERASE */ #ifdef VERASE2 {C_ERASE2, VERASE2, {EM_DELETE_PREV_CHAR, VI_DELETE_PREV_CHAR, ED_PREV_CHAR}}, #endif /* VERASE2 */ #ifdef VKILL {C_KILL, VKILL, {EM_KILL_LINE, VI_KILL_LINE_PREV, ED_UNASSIGNED}}, #endif /* VKILL */ #ifdef VKILL2 {C_KILL2, VKILL2, {EM_KILL_LINE, VI_KILL_LINE_PREV, ED_UNASSIGNED}}, #endif /* VKILL2 */ #ifdef VEOF {C_EOF, VEOF, {EM_DELETE_OR_LIST, VI_LIST_OR_EOF, ED_UNASSIGNED}}, #endif /* VEOF */ #ifdef VWERASE {C_WERASE, VWERASE, {ED_DELETE_PREV_WORD, ED_DELETE_PREV_WORD, ED_PREV_WORD}}, #endif /* VWERASE */ #ifdef VREPRINT {C_REPRINT, VREPRINT, {ED_REDISPLAY, ED_INSERT, ED_REDISPLAY}}, #endif /* VREPRINT */ #ifdef VLNEXT {C_LNEXT, VLNEXT, {ED_QUOTED_INSERT, ED_QUOTED_INSERT, ED_UNASSIGNED}}, #endif /* VLNEXT */ {(wint_t)-1, (wint_t)-1, {ED_UNASSIGNED, ED_UNASSIGNED, ED_UNASSIGNED}} }; static const ttymodes_t ttymodes[] = { #ifdef IGNBRK {"ignbrk", IGNBRK, MD_INP}, #endif /* IGNBRK */ #ifdef BRKINT {"brkint", BRKINT, MD_INP}, #endif /* BRKINT */ #ifdef IGNPAR {"ignpar", IGNPAR, MD_INP}, #endif /* IGNPAR */ #ifdef PARMRK {"parmrk", PARMRK, MD_INP}, #endif /* PARMRK */ #ifdef INPCK {"inpck", INPCK, MD_INP}, #endif /* INPCK */ #ifdef ISTRIP {"istrip", ISTRIP, MD_INP}, #endif /* ISTRIP */ #ifdef INLCR {"inlcr", INLCR, MD_INP}, #endif /* INLCR */ #ifdef IGNCR {"igncr", IGNCR, MD_INP}, #endif /* IGNCR */ #ifdef ICRNL {"icrnl", ICRNL, MD_INP}, #endif /* ICRNL */ #ifdef IUCLC {"iuclc", IUCLC, MD_INP}, #endif /* IUCLC */ #ifdef IXON {"ixon", IXON, MD_INP}, #endif /* IXON */ #ifdef IXANY {"ixany", IXANY, MD_INP}, #endif /* IXANY */ #ifdef IXOFF {"ixoff", IXOFF, MD_INP}, #endif /* IXOFF */ #ifdef IMAXBEL {"imaxbel", IMAXBEL, MD_INP}, #endif /* IMAXBEL */ #ifdef OPOST {"opost", OPOST, MD_OUT}, #endif /* OPOST */ #ifdef OLCUC {"olcuc", OLCUC, MD_OUT}, #endif /* OLCUC */ #ifdef ONLCR {"onlcr", ONLCR, MD_OUT}, #endif /* ONLCR */ #ifdef OCRNL {"ocrnl", OCRNL, MD_OUT}, #endif /* OCRNL */ #ifdef ONOCR {"onocr", ONOCR, MD_OUT}, #endif /* ONOCR */ #ifdef ONOEOT {"onoeot", ONOEOT, MD_OUT}, #endif /* ONOEOT */ #ifdef ONLRET {"onlret", ONLRET, MD_OUT}, #endif /* ONLRET */ #ifdef OFILL {"ofill", OFILL, MD_OUT}, #endif /* OFILL */ #ifdef OFDEL {"ofdel", OFDEL, MD_OUT}, #endif /* OFDEL */ #ifdef NLDLY {"nldly", NLDLY, MD_OUT}, #endif /* NLDLY */ #ifdef CRDLY {"crdly", CRDLY, MD_OUT}, #endif /* CRDLY */ #ifdef TABDLY {"tabdly", TABDLY, MD_OUT}, #endif /* TABDLY */ #ifdef XTABS {"xtabs", XTABS, MD_OUT}, #endif /* XTABS */ #ifdef BSDLY {"bsdly", BSDLY, MD_OUT}, #endif /* BSDLY */ #ifdef VTDLY {"vtdly", VTDLY, MD_OUT}, #endif /* VTDLY */ #ifdef FFDLY {"ffdly", FFDLY, MD_OUT}, #endif /* FFDLY */ #ifdef PAGEOUT {"pageout", PAGEOUT, MD_OUT}, #endif /* PAGEOUT */ #ifdef WRAP {"wrap", WRAP, MD_OUT}, #endif /* WRAP */ #ifdef CIGNORE {"cignore", CIGNORE, MD_CTL}, #endif /* CBAUD */ #ifdef CBAUD {"cbaud", CBAUD, MD_CTL}, #endif /* CBAUD */ #ifdef CSTOPB {"cstopb", CSTOPB, MD_CTL}, #endif /* CSTOPB */ #ifdef CREAD {"cread", CREAD, MD_CTL}, #endif /* CREAD */ #ifdef PARENB {"parenb", PARENB, MD_CTL}, #endif /* PARENB */ #ifdef PARODD {"parodd", PARODD, MD_CTL}, #endif /* PARODD */ #ifdef HUPCL {"hupcl", HUPCL, MD_CTL}, #endif /* HUPCL */ #ifdef CLOCAL {"clocal", CLOCAL, MD_CTL}, #endif /* CLOCAL */ #ifdef LOBLK {"loblk", LOBLK, MD_CTL}, #endif /* LOBLK */ #ifdef CIBAUD {"cibaud", CIBAUD, MD_CTL}, #endif /* CIBAUD */ #ifdef CRTSCTS #ifdef CCTS_OFLOW {"ccts_oflow", CCTS_OFLOW, MD_CTL}, #else {"crtscts", CRTSCTS, MD_CTL}, #endif /* CCTS_OFLOW */ #endif /* CRTSCTS */ #ifdef CRTS_IFLOW {"crts_iflow", CRTS_IFLOW, MD_CTL}, #endif /* CRTS_IFLOW */ #ifdef CDTRCTS {"cdtrcts", CDTRCTS, MD_CTL}, #endif /* CDTRCTS */ #ifdef MDMBUF {"mdmbuf", MDMBUF, MD_CTL}, #endif /* MDMBUF */ #ifdef RCV1EN {"rcv1en", RCV1EN, MD_CTL}, #endif /* RCV1EN */ #ifdef XMT1EN {"xmt1en", XMT1EN, MD_CTL}, #endif /* XMT1EN */ #ifdef ISIG {"isig", ISIG, MD_LIN}, #endif /* ISIG */ #ifdef ICANON {"icanon", ICANON, MD_LIN}, #endif /* ICANON */ #ifdef XCASE {"xcase", XCASE, MD_LIN}, #endif /* XCASE */ #ifdef ECHO {"echo", ECHO, MD_LIN}, #endif /* ECHO */ #ifdef ECHOE {"echoe", ECHOE, MD_LIN}, #endif /* ECHOE */ #ifdef ECHOK {"echok", ECHOK, MD_LIN}, #endif /* ECHOK */ #ifdef ECHONL {"echonl", ECHONL, MD_LIN}, #endif /* ECHONL */ #ifdef NOFLSH {"noflsh", NOFLSH, MD_LIN}, #endif /* NOFLSH */ #ifdef TOSTOP {"tostop", TOSTOP, MD_LIN}, #endif /* TOSTOP */ #ifdef ECHOCTL {"echoctl", ECHOCTL, MD_LIN}, #endif /* ECHOCTL */ #ifdef ECHOPRT {"echoprt", ECHOPRT, MD_LIN}, #endif /* ECHOPRT */ #ifdef ECHOKE {"echoke", ECHOKE, MD_LIN}, #endif /* ECHOKE */ #ifdef DEFECHO {"defecho", DEFECHO, MD_LIN}, #endif /* DEFECHO */ #ifdef FLUSHO {"flusho", FLUSHO, MD_LIN}, #endif /* FLUSHO */ #ifdef PENDIN {"pendin", PENDIN, MD_LIN}, #endif /* PENDIN */ #ifdef IEXTEN {"iexten", IEXTEN, MD_LIN}, #endif /* IEXTEN */ #ifdef NOKERNINFO {"nokerninfo", NOKERNINFO, MD_LIN}, #endif /* NOKERNINFO */ #ifdef ALTWERASE {"altwerase", ALTWERASE, MD_LIN}, #endif /* ALTWERASE */ #ifdef EXTPROC {"extproc", EXTPROC, MD_LIN}, #endif /* EXTPROC */ #if defined(VINTR) {"intr", C_SH(C_INTR), MD_CHAR}, #endif /* VINTR */ #if defined(VQUIT) {"quit", C_SH(C_QUIT), MD_CHAR}, #endif /* VQUIT */ #if defined(VERASE) {"erase", C_SH(C_ERASE), MD_CHAR}, #endif /* VERASE */ #if defined(VKILL) {"kill", C_SH(C_KILL), MD_CHAR}, #endif /* VKILL */ #if defined(VEOF) {"eof", C_SH(C_EOF), MD_CHAR}, #endif /* VEOF */ #if defined(VEOL) {"eol", C_SH(C_EOL), MD_CHAR}, #endif /* VEOL */ #if defined(VEOL2) {"eol2", C_SH(C_EOL2), MD_CHAR}, #endif /* VEOL2 */ #if defined(VSWTCH) {"swtch", C_SH(C_SWTCH), MD_CHAR}, #endif /* VSWTCH */ #if defined(VDSWTCH) {"dswtch", C_SH(C_DSWTCH), MD_CHAR}, #endif /* VDSWTCH */ #if defined(VERASE2) {"erase2", C_SH(C_ERASE2), MD_CHAR}, #endif /* VERASE2 */ #if defined(VSTART) {"start", C_SH(C_START), MD_CHAR}, #endif /* VSTART */ #if defined(VSTOP) {"stop", C_SH(C_STOP), MD_CHAR}, #endif /* VSTOP */ #if defined(VWERASE) {"werase", C_SH(C_WERASE), MD_CHAR}, #endif /* VWERASE */ #if defined(VSUSP) {"susp", C_SH(C_SUSP), MD_CHAR}, #endif /* VSUSP */ #if defined(VDSUSP) {"dsusp", C_SH(C_DSUSP), MD_CHAR}, #endif /* VDSUSP */ #if defined(VREPRINT) {"reprint", C_SH(C_REPRINT), MD_CHAR}, #endif /* VREPRINT */ #if defined(VDISCARD) {"discard", C_SH(C_DISCARD), MD_CHAR}, #endif /* VDISCARD */ #if defined(VLNEXT) {"lnext", C_SH(C_LNEXT), MD_CHAR}, #endif /* VLNEXT */ #if defined(VSTATUS) {"status", C_SH(C_STATUS), MD_CHAR}, #endif /* VSTATUS */ #if defined(VPAGE) {"page", C_SH(C_PAGE), MD_CHAR}, #endif /* VPAGE */ #if defined(VPGOFF) {"pgoff", C_SH(C_PGOFF), MD_CHAR}, #endif /* VPGOFF */ #if defined(VKILL2) {"kill2", C_SH(C_KILL2), MD_CHAR}, #endif /* VKILL2 */ #if defined(VBRK) {"brk", C_SH(C_BRK), MD_CHAR}, #endif /* VBRK */ #if defined(VMIN) {"min", C_SH(C_MIN), MD_CHAR}, #endif /* VMIN */ #if defined(VTIME) {"time", C_SH(C_TIME), MD_CHAR}, #endif /* VTIME */ {NULL, 0, -1}, }; #define tty__gettabs(td) ((((td)->c_oflag & TAB3) == TAB3) ? 0 : 1) #define tty__geteightbit(td) (((td)->c_cflag & CSIZE) == CS8) #define tty__cooked_mode(td) ((td)->c_lflag & ICANON) static int tty_getty(EditLine *, struct termios *); static int tty_setty(EditLine *, int, const struct termios *); static int tty__getcharindex(int); static void tty__getchar(struct termios *, unsigned char *); static void tty__setchar(struct termios *, unsigned char *); static speed_t tty__getspeed(struct termios *); static int tty_setup(EditLine *); static void tty_setup_flags(EditLine *, struct termios *, int); #define t_qu t_ts /* tty_getty(): * Wrapper for tcgetattr to handle EINTR */ static int tty_getty(EditLine *el, struct termios *t) { int rv; while ((rv = tcgetattr(el->el_infd, t)) == -1 && errno == EINTR) continue; return rv; } /* tty_setty(): * Wrapper for tcsetattr to handle EINTR */ static int tty_setty(EditLine *el, int action, const struct termios *t) { int rv; while ((rv = tcsetattr(el->el_infd, action, t)) == -1 && errno == EINTR) continue; return rv; } /* tty_setup(): * Get the tty parameters and initialize the editing state */ static int tty_setup(EditLine *el) { int rst = 1; if (el->el_flags & EDIT_DISABLED) return 0; if (el->el_tty.t_initialized) return -1; if (!isatty(el->el_outfd)) { #ifdef DEBUG_TTY (void) fprintf(el->el_errfile, "%s: isatty: %s\n", __func__, strerror(errno)); #endif /* DEBUG_TTY */ return -1; } if (tty_getty(el, &el->el_tty.t_or) == -1) { #ifdef DEBUG_TTY (void) fprintf(el->el_errfile, "%s: tty_getty: %s\n", __func__, strerror(errno)); #endif /* DEBUG_TTY */ return -1; } el->el_tty.t_ts = el->el_tty.t_ex = el->el_tty.t_ed = el->el_tty.t_or; el->el_tty.t_speed = tty__getspeed(&el->el_tty.t_ex); el->el_tty.t_tabs = tty__gettabs(&el->el_tty.t_ex); el->el_tty.t_eight = tty__geteightbit(&el->el_tty.t_ex); tty_setup_flags(el, &el->el_tty.t_ex, EX_IO); /* * Reset the tty chars to reasonable defaults * If they are disabled, then enable them. */ if (rst) { if (tty__cooked_mode(&el->el_tty.t_ts)) { tty__getchar(&el->el_tty.t_ts, el->el_tty.t_c[TS_IO]); /* * Don't affect CMIN and CTIME for the editor mode */ for (rst = 0; rst < C_NCC - 2; rst++) if (el->el_tty.t_c[TS_IO][rst] != el->el_tty.t_vdisable && el->el_tty.t_c[ED_IO][rst] != el->el_tty.t_vdisable) el->el_tty.t_c[ED_IO][rst] = el->el_tty.t_c[TS_IO][rst]; for (rst = 0; rst < C_NCC; rst++) if (el->el_tty.t_c[TS_IO][rst] != el->el_tty.t_vdisable) el->el_tty.t_c[EX_IO][rst] = el->el_tty.t_c[TS_IO][rst]; } tty__setchar(&el->el_tty.t_ex, el->el_tty.t_c[EX_IO]); if (tty_setty(el, TCSADRAIN, &el->el_tty.t_ex) == -1) { #ifdef DEBUG_TTY (void) fprintf(el->el_errfile, "%s: tty_setty: %s\n", __func__, strerror(errno)); #endif /* DEBUG_TTY */ return -1; } } tty_setup_flags(el, &el->el_tty.t_ed, ED_IO); tty__setchar(&el->el_tty.t_ed, el->el_tty.t_c[ED_IO]); tty_bind_char(el, 1); el->el_tty.t_initialized = 1; return 0; } libedit_private int tty_init(EditLine *el) { el->el_tty.t_mode = EX_IO; el->el_tty.t_vdisable = _POSIX_VDISABLE; el->el_tty.t_initialized = 0; (void) memcpy(el->el_tty.t_t, ttyperm, sizeof(ttyperm_t)); (void) memcpy(el->el_tty.t_c, ttychar, sizeof(ttychar_t)); return tty_setup(el); } /* tty_end(): * Restore the tty to its original settings */ libedit_private void /*ARGSUSED*/ tty_end(EditLine *el) { if (el->el_flags & EDIT_DISABLED) return; if (!el->el_tty.t_initialized) return; if (tty_setty(el, TCSAFLUSH, &el->el_tty.t_or) == -1) { #ifdef DEBUG_TTY (void) fprintf(el->el_errfile, "%s: tty_setty: %s\n", __func__, strerror(errno)); #endif /* DEBUG_TTY */ } } /* tty__getspeed(): * Get the tty speed */ static speed_t tty__getspeed(struct termios *td) { speed_t spd; if ((spd = cfgetispeed(td)) == 0) spd = cfgetospeed(td); return spd; } /* tty__getspeed(): * Return the index of the asked char in the c_cc array */ static int tty__getcharindex(int i) { switch (i) { #ifdef VINTR case C_INTR: return VINTR; #endif /* VINTR */ #ifdef VQUIT case C_QUIT: return VQUIT; #endif /* VQUIT */ #ifdef VERASE case C_ERASE: return VERASE; #endif /* VERASE */ #ifdef VKILL case C_KILL: return VKILL; #endif /* VKILL */ #ifdef VEOF case C_EOF: return VEOF; #endif /* VEOF */ #ifdef VEOL case C_EOL: return VEOL; #endif /* VEOL */ #ifdef VEOL2 case C_EOL2: return VEOL2; #endif /* VEOL2 */ #ifdef VSWTCH case C_SWTCH: return VSWTCH; #endif /* VSWTCH */ #ifdef VDSWTCH case C_DSWTCH: return VDSWTCH; #endif /* VDSWTCH */ #ifdef VERASE2 case C_ERASE2: return VERASE2; #endif /* VERASE2 */ #ifdef VSTART case C_START: return VSTART; #endif /* VSTART */ #ifdef VSTOP case C_STOP: return VSTOP; #endif /* VSTOP */ #ifdef VWERASE case C_WERASE: return VWERASE; #endif /* VWERASE */ #ifdef VSUSP case C_SUSP: return VSUSP; #endif /* VSUSP */ #ifdef VDSUSP case C_DSUSP: return VDSUSP; #endif /* VDSUSP */ #ifdef VREPRINT case C_REPRINT: return VREPRINT; #endif /* VREPRINT */ #ifdef VDISCARD case C_DISCARD: return VDISCARD; #endif /* VDISCARD */ #ifdef VLNEXT case C_LNEXT: return VLNEXT; #endif /* VLNEXT */ #ifdef VSTATUS case C_STATUS: return VSTATUS; #endif /* VSTATUS */ #ifdef VPAGE case C_PAGE: return VPAGE; #endif /* VPAGE */ #ifdef VPGOFF case C_PGOFF: return VPGOFF; #endif /* VPGOFF */ #ifdef VKILL2 case C_KILL2: return VKILL2; #endif /* KILL2 */ #ifdef VMIN case C_MIN: return VMIN; #endif /* VMIN */ #ifdef VTIME case C_TIME: return VTIME; #endif /* VTIME */ default: return -1; } } /* tty__getchar(): * Get the tty characters */ static void tty__getchar(struct termios *td, unsigned char *s) { #ifdef VINTR s[C_INTR] = td->c_cc[VINTR]; #endif /* VINTR */ #ifdef VQUIT s[C_QUIT] = td->c_cc[VQUIT]; #endif /* VQUIT */ #ifdef VERASE s[C_ERASE] = td->c_cc[VERASE]; #endif /* VERASE */ #ifdef VKILL s[C_KILL] = td->c_cc[VKILL]; #endif /* VKILL */ #ifdef VEOF s[C_EOF] = td->c_cc[VEOF]; #endif /* VEOF */ #ifdef VEOL s[C_EOL] = td->c_cc[VEOL]; #endif /* VEOL */ #ifdef VEOL2 s[C_EOL2] = td->c_cc[VEOL2]; #endif /* VEOL2 */ #ifdef VSWTCH s[C_SWTCH] = td->c_cc[VSWTCH]; #endif /* VSWTCH */ #ifdef VDSWTCH s[C_DSWTCH] = td->c_cc[VDSWTCH]; #endif /* VDSWTCH */ #ifdef VERASE2 s[C_ERASE2] = td->c_cc[VERASE2]; #endif /* VERASE2 */ #ifdef VSTART s[C_START] = td->c_cc[VSTART]; #endif /* VSTART */ #ifdef VSTOP s[C_STOP] = td->c_cc[VSTOP]; #endif /* VSTOP */ #ifdef VWERASE s[C_WERASE] = td->c_cc[VWERASE]; #endif /* VWERASE */ #ifdef VSUSP s[C_SUSP] = td->c_cc[VSUSP]; #endif /* VSUSP */ #ifdef VDSUSP s[C_DSUSP] = td->c_cc[VDSUSP]; #endif /* VDSUSP */ #ifdef VREPRINT s[C_REPRINT] = td->c_cc[VREPRINT]; #endif /* VREPRINT */ #ifdef VDISCARD s[C_DISCARD] = td->c_cc[VDISCARD]; #endif /* VDISCARD */ #ifdef VLNEXT s[C_LNEXT] = td->c_cc[VLNEXT]; #endif /* VLNEXT */ #ifdef VSTATUS s[C_STATUS] = td->c_cc[VSTATUS]; #endif /* VSTATUS */ #ifdef VPAGE s[C_PAGE] = td->c_cc[VPAGE]; #endif /* VPAGE */ #ifdef VPGOFF s[C_PGOFF] = td->c_cc[VPGOFF]; #endif /* VPGOFF */ #ifdef VKILL2 s[C_KILL2] = td->c_cc[VKILL2]; #endif /* KILL2 */ #ifdef VMIN s[C_MIN] = td->c_cc[VMIN]; #endif /* VMIN */ #ifdef VTIME s[C_TIME] = td->c_cc[VTIME]; #endif /* VTIME */ } /* tty__getchar */ /* tty__setchar(): * Set the tty characters */ static void tty__setchar(struct termios *td, unsigned char *s) { #ifdef VINTR td->c_cc[VINTR] = s[C_INTR]; #endif /* VINTR */ #ifdef VQUIT td->c_cc[VQUIT] = s[C_QUIT]; #endif /* VQUIT */ #ifdef VERASE td->c_cc[VERASE] = s[C_ERASE]; #endif /* VERASE */ #ifdef VKILL td->c_cc[VKILL] = s[C_KILL]; #endif /* VKILL */ #ifdef VEOF td->c_cc[VEOF] = s[C_EOF]; #endif /* VEOF */ #ifdef VEOL td->c_cc[VEOL] = s[C_EOL]; #endif /* VEOL */ #ifdef VEOL2 td->c_cc[VEOL2] = s[C_EOL2]; #endif /* VEOL2 */ #ifdef VSWTCH td->c_cc[VSWTCH] = s[C_SWTCH]; #endif /* VSWTCH */ #ifdef VDSWTCH td->c_cc[VDSWTCH] = s[C_DSWTCH]; #endif /* VDSWTCH */ #ifdef VERASE2 td->c_cc[VERASE2] = s[C_ERASE2]; #endif /* VERASE2 */ #ifdef VSTART td->c_cc[VSTART] = s[C_START]; #endif /* VSTART */ #ifdef VSTOP td->c_cc[VSTOP] = s[C_STOP]; #endif /* VSTOP */ #ifdef VWERASE td->c_cc[VWERASE] = s[C_WERASE]; #endif /* VWERASE */ #ifdef VSUSP td->c_cc[VSUSP] = s[C_SUSP]; #endif /* VSUSP */ #ifdef VDSUSP td->c_cc[VDSUSP] = s[C_DSUSP]; #endif /* VDSUSP */ #ifdef VREPRINT td->c_cc[VREPRINT] = s[C_REPRINT]; #endif /* VREPRINT */ #ifdef VDISCARD td->c_cc[VDISCARD] = s[C_DISCARD]; #endif /* VDISCARD */ #ifdef VLNEXT td->c_cc[VLNEXT] = s[C_LNEXT]; #endif /* VLNEXT */ #ifdef VSTATUS td->c_cc[VSTATUS] = s[C_STATUS]; #endif /* VSTATUS */ #ifdef VPAGE td->c_cc[VPAGE] = s[C_PAGE]; #endif /* VPAGE */ #ifdef VPGOFF td->c_cc[VPGOFF] = s[C_PGOFF]; #endif /* VPGOFF */ #ifdef VKILL2 td->c_cc[VKILL2] = s[C_KILL2]; #endif /* VKILL2 */ #ifdef VMIN td->c_cc[VMIN] = s[C_MIN]; #endif /* VMIN */ #ifdef VTIME td->c_cc[VTIME] = s[C_TIME]; #endif /* VTIME */ } /* tty__setchar */ /* tty_bind_char(): * Rebind the editline functions */ libedit_private void tty_bind_char(EditLine *el, int force) { unsigned char *t_n = el->el_tty.t_c[ED_IO]; unsigned char *t_o = el->el_tty.t_ed.c_cc; wchar_t new[2], old[2]; const ttymap_t *tp; el_action_t *map, *alt; const el_action_t *dmap, *dalt; new[1] = old[1] = '\0'; map = el->el_map.key; alt = el->el_map.alt; if (el->el_map.type == MAP_VI) { dmap = el->el_map.vii; dalt = el->el_map.vic; } else { dmap = el->el_map.emacs; dalt = NULL; } for (tp = tty_map; tp->nch != (wint_t)-1; tp++) { new[0] = (wchar_t)t_n[tp->nch]; old[0] = (wchar_t)t_o[tp->och]; if (new[0] == old[0] && !force) continue; /* Put the old default binding back, and set the new binding */ keymacro_clear(el, map, old); map[(unsigned char)old[0]] = dmap[(unsigned char)old[0]]; keymacro_clear(el, map, new); /* MAP_VI == 1, MAP_EMACS == 0... */ map[(unsigned char)new[0]] = tp->bind[el->el_map.type]; if (dalt) { keymacro_clear(el, alt, old); alt[(unsigned char)old[0]] = dalt[(unsigned char)old[0]]; keymacro_clear(el, alt, new); alt[(unsigned char)new[0]] = tp->bind[el->el_map.type + 1]; } } } static tcflag_t * tty__get_flag(struct termios *t, int kind) { switch (kind) { case MD_INP: return &t->c_iflag; case MD_OUT: return &t->c_oflag; case MD_CTL: return &t->c_cflag; case MD_LIN: return &t->c_lflag; default: abort(); /*NOTREACHED*/ } } static tcflag_t tty_update_flag(EditLine *el, tcflag_t f, int mode, int kind) { f &= ~el->el_tty.t_t[mode][kind].t_clrmask; f |= el->el_tty.t_t[mode][kind].t_setmask; return f; } static void tty_update_flags(EditLine *el, int kind) { tcflag_t *tt, *ed, *ex; tt = tty__get_flag(&el->el_tty.t_ts, kind); ed = tty__get_flag(&el->el_tty.t_ed, kind); ex = tty__get_flag(&el->el_tty.t_ex, kind); if (*tt != *ex && (kind != MD_CTL || *tt != *ed)) { *ed = tty_update_flag(el, *tt, ED_IO, kind); *ex = tty_update_flag(el, *tt, EX_IO, kind); } } static void tty_update_char(EditLine *el, int mode, int c) { if (!((el->el_tty.t_t[mode][MD_CHAR].t_setmask & C_SH(c))) && (el->el_tty.t_c[TS_IO][c] != el->el_tty.t_c[EX_IO][c])) el->el_tty.t_c[mode][c] = el->el_tty.t_c[TS_IO][c]; if (el->el_tty.t_t[mode][MD_CHAR].t_clrmask & C_SH(c)) el->el_tty.t_c[mode][c] = el->el_tty.t_vdisable; } /* tty_rawmode(): * Set terminal into 1 character at a time mode. */ libedit_private int tty_rawmode(EditLine *el) { if (el->el_tty.t_mode == ED_IO || el->el_tty.t_mode == QU_IO) return 0; if (el->el_flags & EDIT_DISABLED) return 0; if (tty_getty(el, &el->el_tty.t_ts) == -1) { #ifdef DEBUG_TTY (void) fprintf(el->el_errfile, "%s: tty_getty: %s\n", __func__, strerror(errno)); #endif /* DEBUG_TTY */ return -1; } /* * We always keep up with the eight bit setting and the speed of the * tty. But we only believe changes that are made to cooked mode! */ el->el_tty.t_eight = tty__geteightbit(&el->el_tty.t_ts); el->el_tty.t_speed = tty__getspeed(&el->el_tty.t_ts); if (tty__getspeed(&el->el_tty.t_ex) != el->el_tty.t_speed || tty__getspeed(&el->el_tty.t_ed) != el->el_tty.t_speed) { (void) cfsetispeed(&el->el_tty.t_ex, el->el_tty.t_speed); (void) cfsetospeed(&el->el_tty.t_ex, el->el_tty.t_speed); (void) cfsetispeed(&el->el_tty.t_ed, el->el_tty.t_speed); (void) cfsetospeed(&el->el_tty.t_ed, el->el_tty.t_speed); } if (tty__cooked_mode(&el->el_tty.t_ts)) { int i; for (i = MD_INP; i <= MD_LIN; i++) tty_update_flags(el, i); if (tty__gettabs(&el->el_tty.t_ex) == 0) el->el_tty.t_tabs = 0; else el->el_tty.t_tabs = EL_CAN_TAB ? 1 : 0; tty__getchar(&el->el_tty.t_ts, el->el_tty.t_c[TS_IO]); /* * Check if the user made any changes. * If he did, then propagate the changes to the * edit and execute data structures. */ for (i = 0; i < C_NCC; i++) if (el->el_tty.t_c[TS_IO][i] != el->el_tty.t_c[EX_IO][i]) break; if (i != C_NCC) { /* * Propagate changes only to the unlibedit_private * chars that have been modified just now. */ for (i = 0; i < C_NCC; i++) tty_update_char(el, ED_IO, i); tty_bind_char(el, 0); tty__setchar(&el->el_tty.t_ed, el->el_tty.t_c[ED_IO]); for (i = 0; i < C_NCC; i++) tty_update_char(el, EX_IO, i); tty__setchar(&el->el_tty.t_ex, el->el_tty.t_c[EX_IO]); } } if (tty_setty(el, TCSADRAIN, &el->el_tty.t_ed) == -1) { #ifdef DEBUG_TTY (void) fprintf(el->el_errfile, "%s: tty_setty: %s\n", __func__, strerror(errno)); #endif /* DEBUG_TTY */ return -1; } el->el_tty.t_mode = ED_IO; return 0; } /* tty_cookedmode(): * Set the tty back to normal mode */ libedit_private int tty_cookedmode(EditLine *el) { /* set tty in normal setup */ if (el->el_tty.t_mode == EX_IO) return 0; if (el->el_flags & EDIT_DISABLED) return 0; if (tty_setty(el, TCSADRAIN, &el->el_tty.t_ex) == -1) { #ifdef DEBUG_TTY (void) fprintf(el->el_errfile, "%s: tty_setty: %s\n", __func__, strerror(errno)); #endif /* DEBUG_TTY */ return -1; } el->el_tty.t_mode = EX_IO; return 0; } /* tty_quotemode(): * Turn on quote mode */ libedit_private int tty_quotemode(EditLine *el) { if (el->el_tty.t_mode == QU_IO) return 0; el->el_tty.t_qu = el->el_tty.t_ed; tty_setup_flags(el, &el->el_tty.t_qu, QU_IO); if (tty_setty(el, TCSADRAIN, &el->el_tty.t_qu) == -1) { #ifdef DEBUG_TTY (void) fprintf(el->el_errfile, "%s: tty_setty: %s\n", __func__, strerror(errno)); #endif /* DEBUG_TTY */ return -1; } el->el_tty.t_mode = QU_IO; return 0; } /* tty_noquotemode(): * Turn off quote mode */ libedit_private int tty_noquotemode(EditLine *el) { if (el->el_tty.t_mode != QU_IO) return 0; if (tty_setty(el, TCSADRAIN, &el->el_tty.t_ed) == -1) { #ifdef DEBUG_TTY (void) fprintf(el->el_errfile, "%s: tty_setty: %s\n", __func__, strerror(errno)); #endif /* DEBUG_TTY */ return -1; } el->el_tty.t_mode = ED_IO; return 0; } /* tty_stty(): * Stty builtin */ libedit_private int /*ARGSUSED*/ tty_stty(EditLine *el, int argc __attribute__((__unused__)), const wchar_t **argv) { const ttymodes_t *m; char x; int aflag = 0; const wchar_t *s, *d; char name[EL_BUFSIZ]; struct termios *tios = &el->el_tty.t_ex; int z = EX_IO; if (argv == NULL) return -1; strncpy(name, ct_encode_string(*argv++, &el->el_scratch), sizeof(name)); name[sizeof(name) - 1] = '\0'; while (argv && *argv && argv[0][0] == '-' && argv[0][2] == '\0') switch (argv[0][1]) { case 'a': aflag++; argv++; break; case 'd': argv++; tios = &el->el_tty.t_ed; z = ED_IO; break; case 'x': argv++; tios = &el->el_tty.t_ex; z = EX_IO; break; case 'q': argv++; tios = &el->el_tty.t_ts; z = QU_IO; break; default: (void) fprintf(el->el_errfile, "%s: Unknown switch `%lc'.\n", name, (wint_t)argv[0][1]); return -1; } if (!argv || !*argv) { int i = -1; size_t len = 0, st = 0, cu; for (m = ttymodes; m->m_name; m++) { if (m->m_type != i) { (void) fprintf(el->el_outfile, "%s%s", i != -1 ? "\n" : "", el->el_tty.t_t[z][m->m_type].t_name); i = m->m_type; st = len = strlen(el->el_tty.t_t[z][m->m_type].t_name); } if (i != -1) { x = (el->el_tty.t_t[z][i].t_setmask & m->m_value) ? '+' : '\0'; if (el->el_tty.t_t[z][i].t_clrmask & m->m_value) x = '-'; } else { x = '\0'; } if (x != '\0' || aflag) { cu = strlen(m->m_name) + (x != '\0') + 1; if (len + cu >= (size_t)el->el_terminal.t_size.h) { (void) fprintf(el->el_outfile, "\n%*s", (int)st, ""); len = st + cu; } else len += cu; if (x != '\0') (void) fprintf(el->el_outfile, "%c%s ", x, m->m_name); else (void) fprintf(el->el_outfile, "%s ", m->m_name); } } (void) fprintf(el->el_outfile, "\n"); return 0; } while (argv && (s = *argv++)) { const wchar_t *p; switch (*s) { case '+': case '-': x = (char)*s++; break; default: x = '\0'; break; } d = s; p = wcschr(s, L'='); for (m = ttymodes; m->m_name; m++) if ((p ? strncmp(m->m_name, ct_encode_string(d, &el->el_scratch), (size_t)(p - d)) : strcmp(m->m_name, ct_encode_string(d, &el->el_scratch))) == 0 && (p == NULL || m->m_type == MD_CHAR)) break; if (!m->m_name) { (void) fprintf(el->el_errfile, "%s: Invalid argument `%ls'.\n", name, d); return -1; } if (p) { int c = ffs((int)m->m_value); int v = *++p ? parse__escape(&p) : el->el_tty.t_vdisable; assert(c != 0); c--; c = tty__getcharindex(c); assert(c != -1); tios->c_cc[c] = (cc_t)v; continue; } switch (x) { case '+': el->el_tty.t_t[z][m->m_type].t_setmask |= m->m_value; el->el_tty.t_t[z][m->m_type].t_clrmask &= ~m->m_value; break; case '-': el->el_tty.t_t[z][m->m_type].t_setmask &= ~m->m_value; el->el_tty.t_t[z][m->m_type].t_clrmask |= m->m_value; break; default: el->el_tty.t_t[z][m->m_type].t_setmask &= ~m->m_value; el->el_tty.t_t[z][m->m_type].t_clrmask &= ~m->m_value; break; } } tty_setup_flags(el, tios, z); if (el->el_tty.t_mode == z) { if (tty_setty(el, TCSADRAIN, tios) == -1) { #ifdef DEBUG_TTY (void) fprintf(el->el_errfile, "%s: tty_setty: %s\n", __func__, strerror(errno)); #endif /* DEBUG_TTY */ return -1; } } return 0; } #ifdef notyet /* tty_printchar(): * DEbugging routine to print the tty characters */ static void tty_printchar(EditLine *el, unsigned char *s) { ttyperm_t *m; int i; for (i = 0; i < C_NCC; i++) { for (m = el->el_tty.t_t; m->m_name; m++) if (m->m_type == MD_CHAR && C_SH(i) == m->m_value) break; if (m->m_name) (void) fprintf(el->el_errfile, "%s ^%c ", m->m_name, s[i] + 'A' - 1); if (i % 5 == 0) (void) fprintf(el->el_errfile, "\n"); } (void) fprintf(el->el_errfile, "\n"); } #endif /* notyet */ static void tty_setup_flags(EditLine *el, struct termios *tios, int mode) { int kind; for (kind = MD_INP; kind <= MD_LIN; kind++) { tcflag_t *f = tty__get_flag(tios, kind); *f = tty_update_flag(el, *f, mode, kind); } } heimdal-7.5.0/lib/libedit/src/sys.h0000644000175000017500000000634013212137553015217 0ustar niknik/* $NetBSD: sys.h,v 1.27 2016/05/09 21:46:56 christos Exp $ */ /*- * Copyright (c) 1992, 1993 * The Regents of the University of California. All rights reserved. * * This code is derived from software contributed to Berkeley by * Christos Zoulas of Cornell University. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the University nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * * @(#)sys.h 8.1 (Berkeley) 6/4/93 */ /* * sys.h: Put all the stupid compiler and system dependencies here... */ #ifndef _h_sys #define _h_sys #ifdef HAVE_SYS_CDEFS_H #include #endif #ifdef HAVE_STDINT_H #include #endif #if !defined(__attribute__) && (defined(__cplusplus) || !defined(__GNUC__) || __GNUC__ == 2 && __GNUC_MINOR__ < 8) # define __attribute__(A) #endif #ifndef __BEGIN_DECLS # ifdef __cplusplus # define __BEGIN_DECLS extern "C" { # define __END_DECLS } # else # define __BEGIN_DECLS # define __END_DECLS # endif #endif /* If your compiler does not support this, define it to be empty. */ #define libedit_private __attribute__((__visibility__("hidden"))) #ifndef __arraycount # define __arraycount(a) (sizeof(a) / sizeof(*(a))) #endif #include #ifndef HAVE_STRLCAT #define strlcat libedit_strlcat size_t strlcat(char *dst, const char *src, size_t size); #endif #ifndef HAVE_STRLCPY #define strlcpy libedit_strlcpy size_t strlcpy(char *dst, const char *src, size_t size); #endif #ifndef HAVE_GETLINE #define getline libedit_getline ssize_t getline(char **line, size_t *len, FILE *fp); #endif #ifndef _DIAGASSERT #define _DIAGASSERT(x) #endif #ifndef __RCSID #define __RCSID(x) #endif #ifndef HAVE_U_INT32_T typedef unsigned int u_int32_t; #endif #ifndef HAVE_SIZE_MAX #define SIZE_MAX ((size_t)-1) #endif #define REGEX /* Use POSIX.2 regular expression functions */ #undef REGEXP /* Use UNIX V8 regular expression functions */ #endif /* _h_sys */ heimdal-7.5.0/lib/libedit/src/tokenizern.c0000644000175000017500000000007613026237312016561 0ustar niknik#include "config.h" #define NARROWCHAR #include "tokenizer.c" heimdal-7.5.0/lib/libedit/src/emacs.c0000644000175000017500000003040513026237312015460 0ustar niknik/* $NetBSD: emacs.c,v 1.36 2016/05/09 21:46:56 christos Exp $ */ /*- * Copyright (c) 1992, 1993 * The Regents of the University of California. All rights reserved. * * This code is derived from software contributed to Berkeley by * Christos Zoulas of Cornell University. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the University nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "config.h" #if !defined(lint) && !defined(SCCSID) #if 0 static char sccsid[] = "@(#)emacs.c 8.1 (Berkeley) 6/4/93"; #else __RCSID("$NetBSD: emacs.c,v 1.36 2016/05/09 21:46:56 christos Exp $"); #endif #endif /* not lint && not SCCSID */ /* * emacs.c: Emacs functions */ #include #include "el.h" #include "emacs.h" #include "fcns.h" /* em_delete_or_list(): * Delete character under cursor or list completions if at end of line * [^D] */ libedit_private el_action_t /*ARGSUSED*/ em_delete_or_list(EditLine *el, wint_t c) { if (el->el_line.cursor == el->el_line.lastchar) { /* if I'm at the end */ if (el->el_line.cursor == el->el_line.buffer) { /* and the beginning */ terminal_writec(el, c); /* then do an EOF */ return CC_EOF; } else { /* * Here we could list completions, but it is an * error right now */ terminal_beep(el); return CC_ERROR; } } else { if (el->el_state.doingarg) c_delafter(el, el->el_state.argument); else c_delafter1(el); if (el->el_line.cursor > el->el_line.lastchar) el->el_line.cursor = el->el_line.lastchar; /* bounds check */ return CC_REFRESH; } } /* em_delete_next_word(): * Cut from cursor to end of current word * [M-d] */ libedit_private el_action_t /*ARGSUSED*/ em_delete_next_word(EditLine *el, wint_t c __attribute__((__unused__))) { wchar_t *cp, *p, *kp; if (el->el_line.cursor == el->el_line.lastchar) return CC_ERROR; cp = c__next_word(el->el_line.cursor, el->el_line.lastchar, el->el_state.argument, ce__isword); for (p = el->el_line.cursor, kp = el->el_chared.c_kill.buf; p < cp; p++) /* save the text */ *kp++ = *p; el->el_chared.c_kill.last = kp; c_delafter(el, (int)(cp - el->el_line.cursor)); /* delete after dot */ if (el->el_line.cursor > el->el_line.lastchar) el->el_line.cursor = el->el_line.lastchar; /* bounds check */ return CC_REFRESH; } /* em_yank(): * Paste cut buffer at cursor position * [^Y] */ libedit_private el_action_t /*ARGSUSED*/ em_yank(EditLine *el, wint_t c __attribute__((__unused__))) { wchar_t *kp, *cp; if (el->el_chared.c_kill.last == el->el_chared.c_kill.buf) return CC_NORM; if (el->el_line.lastchar + (el->el_chared.c_kill.last - el->el_chared.c_kill.buf) >= el->el_line.limit) return CC_ERROR; el->el_chared.c_kill.mark = el->el_line.cursor; cp = el->el_line.cursor; /* open the space, */ c_insert(el, (int)(el->el_chared.c_kill.last - el->el_chared.c_kill.buf)); /* copy the chars */ for (kp = el->el_chared.c_kill.buf; kp < el->el_chared.c_kill.last; kp++) *cp++ = *kp; /* if an arg, cursor at beginning else cursor at end */ if (el->el_state.argument == 1) el->el_line.cursor = cp; return CC_REFRESH; } /* em_kill_line(): * Cut the entire line and save in cut buffer * [^U] */ libedit_private el_action_t /*ARGSUSED*/ em_kill_line(EditLine *el, wint_t c __attribute__((__unused__))) { wchar_t *kp, *cp; cp = el->el_line.buffer; kp = el->el_chared.c_kill.buf; while (cp < el->el_line.lastchar) *kp++ = *cp++; /* copy it */ el->el_chared.c_kill.last = kp; /* zap! -- delete all of it */ el->el_line.lastchar = el->el_line.buffer; el->el_line.cursor = el->el_line.buffer; return CC_REFRESH; } /* em_kill_region(): * Cut area between mark and cursor and save in cut buffer * [^W] */ libedit_private el_action_t /*ARGSUSED*/ em_kill_region(EditLine *el, wint_t c __attribute__((__unused__))) { wchar_t *kp, *cp; if (!el->el_chared.c_kill.mark) return CC_ERROR; if (el->el_chared.c_kill.mark > el->el_line.cursor) { cp = el->el_line.cursor; kp = el->el_chared.c_kill.buf; while (cp < el->el_chared.c_kill.mark) *kp++ = *cp++; /* copy it */ el->el_chared.c_kill.last = kp; c_delafter(el, (int)(cp - el->el_line.cursor)); } else { /* mark is before cursor */ cp = el->el_chared.c_kill.mark; kp = el->el_chared.c_kill.buf; while (cp < el->el_line.cursor) *kp++ = *cp++; /* copy it */ el->el_chared.c_kill.last = kp; c_delbefore(el, (int)(cp - el->el_chared.c_kill.mark)); el->el_line.cursor = el->el_chared.c_kill.mark; } return CC_REFRESH; } /* em_copy_region(): * Copy area between mark and cursor to cut buffer * [M-W] */ libedit_private el_action_t /*ARGSUSED*/ em_copy_region(EditLine *el, wint_t c __attribute__((__unused__))) { wchar_t *kp, *cp; if (!el->el_chared.c_kill.mark) return CC_ERROR; if (el->el_chared.c_kill.mark > el->el_line.cursor) { cp = el->el_line.cursor; kp = el->el_chared.c_kill.buf; while (cp < el->el_chared.c_kill.mark) *kp++ = *cp++; /* copy it */ el->el_chared.c_kill.last = kp; } else { cp = el->el_chared.c_kill.mark; kp = el->el_chared.c_kill.buf; while (cp < el->el_line.cursor) *kp++ = *cp++; /* copy it */ el->el_chared.c_kill.last = kp; } return CC_NORM; } /* em_gosmacs_transpose(): * Exchange the two characters before the cursor * Gosling emacs transpose chars [^T] */ libedit_private el_action_t em_gosmacs_transpose(EditLine *el, wint_t c) { if (el->el_line.cursor > &el->el_line.buffer[1]) { /* must have at least two chars entered */ c = el->el_line.cursor[-2]; el->el_line.cursor[-2] = el->el_line.cursor[-1]; el->el_line.cursor[-1] = c; return CC_REFRESH; } else return CC_ERROR; } /* em_next_word(): * Move next to end of current word * [M-f] */ libedit_private el_action_t /*ARGSUSED*/ em_next_word(EditLine *el, wint_t c __attribute__((__unused__))) { if (el->el_line.cursor == el->el_line.lastchar) return CC_ERROR; el->el_line.cursor = c__next_word(el->el_line.cursor, el->el_line.lastchar, el->el_state.argument, ce__isword); if (el->el_map.type == MAP_VI) if (el->el_chared.c_vcmd.action != NOP) { cv_delfini(el); return CC_REFRESH; } return CC_CURSOR; } /* em_upper_case(): * Uppercase the characters from cursor to end of current word * [M-u] */ libedit_private el_action_t /*ARGSUSED*/ em_upper_case(EditLine *el, wint_t c __attribute__((__unused__))) { wchar_t *cp, *ep; ep = c__next_word(el->el_line.cursor, el->el_line.lastchar, el->el_state.argument, ce__isword); for (cp = el->el_line.cursor; cp < ep; cp++) if (iswlower(*cp)) *cp = towupper(*cp); el->el_line.cursor = ep; if (el->el_line.cursor > el->el_line.lastchar) el->el_line.cursor = el->el_line.lastchar; return CC_REFRESH; } /* em_capitol_case(): * Capitalize the characters from cursor to end of current word * [M-c] */ libedit_private el_action_t /*ARGSUSED*/ em_capitol_case(EditLine *el, wint_t c __attribute__((__unused__))) { wchar_t *cp, *ep; ep = c__next_word(el->el_line.cursor, el->el_line.lastchar, el->el_state.argument, ce__isword); for (cp = el->el_line.cursor; cp < ep; cp++) { if (iswalpha(*cp)) { if (iswlower(*cp)) *cp = towupper(*cp); cp++; break; } } for (; cp < ep; cp++) if (iswupper(*cp)) *cp = towlower(*cp); el->el_line.cursor = ep; if (el->el_line.cursor > el->el_line.lastchar) el->el_line.cursor = el->el_line.lastchar; return CC_REFRESH; } /* em_lower_case(): * Lowercase the characters from cursor to end of current word * [M-l] */ libedit_private el_action_t /*ARGSUSED*/ em_lower_case(EditLine *el, wint_t c __attribute__((__unused__))) { wchar_t *cp, *ep; ep = c__next_word(el->el_line.cursor, el->el_line.lastchar, el->el_state.argument, ce__isword); for (cp = el->el_line.cursor; cp < ep; cp++) if (iswupper(*cp)) *cp = towlower(*cp); el->el_line.cursor = ep; if (el->el_line.cursor > el->el_line.lastchar) el->el_line.cursor = el->el_line.lastchar; return CC_REFRESH; } /* em_set_mark(): * Set the mark at cursor * [^@] */ libedit_private el_action_t /*ARGSUSED*/ em_set_mark(EditLine *el, wint_t c __attribute__((__unused__))) { el->el_chared.c_kill.mark = el->el_line.cursor; return CC_NORM; } /* em_exchange_mark(): * Exchange the cursor and mark * [^X^X] */ libedit_private el_action_t /*ARGSUSED*/ em_exchange_mark(EditLine *el, wint_t c __attribute__((__unused__))) { wchar_t *cp; cp = el->el_line.cursor; el->el_line.cursor = el->el_chared.c_kill.mark; el->el_chared.c_kill.mark = cp; return CC_CURSOR; } /* em_universal_argument(): * Universal argument (argument times 4) * [^U] */ libedit_private el_action_t /*ARGSUSED*/ em_universal_argument(EditLine *el, wint_t c __attribute__((__unused__))) { /* multiply current argument by 4 */ if (el->el_state.argument > 1000000) return CC_ERROR; el->el_state.doingarg = 1; el->el_state.argument *= 4; return CC_ARGHACK; } /* em_meta_next(): * Add 8th bit to next character typed * [] */ libedit_private el_action_t /*ARGSUSED*/ em_meta_next(EditLine *el, wint_t c __attribute__((__unused__))) { el->el_state.metanext = 1; return CC_ARGHACK; } /* em_toggle_overwrite(): * Switch from insert to overwrite mode or vice versa */ libedit_private el_action_t /*ARGSUSED*/ em_toggle_overwrite(EditLine *el, wint_t c __attribute__((__unused__))) { el->el_state.inputmode = (el->el_state.inputmode == MODE_INSERT) ? MODE_REPLACE : MODE_INSERT; return CC_NORM; } /* em_copy_prev_word(): * Copy current word to cursor */ libedit_private el_action_t /*ARGSUSED*/ em_copy_prev_word(EditLine *el, wint_t c __attribute__((__unused__))) { wchar_t *cp, *oldc, *dp; if (el->el_line.cursor == el->el_line.buffer) return CC_ERROR; oldc = el->el_line.cursor; /* does a bounds check */ cp = c__prev_word(el->el_line.cursor, el->el_line.buffer, el->el_state.argument, ce__isword); c_insert(el, (int)(oldc - cp)); for (dp = oldc; cp < oldc && dp < el->el_line.lastchar; cp++) *dp++ = *cp; el->el_line.cursor = dp;/* put cursor at end */ return CC_REFRESH; } /* em_inc_search_next(): * Emacs incremental next search */ libedit_private el_action_t /*ARGSUSED*/ em_inc_search_next(EditLine *el, wint_t c __attribute__((__unused__))) { el->el_search.patlen = 0; return ce_inc_search(el, ED_SEARCH_NEXT_HISTORY); } /* em_inc_search_prev(): * Emacs incremental reverse search */ libedit_private el_action_t /*ARGSUSED*/ em_inc_search_prev(EditLine *el, wint_t c __attribute__((__unused__))) { el->el_search.patlen = 0; return ce_inc_search(el, ED_SEARCH_PREV_HISTORY); } /* em_delete_prev_char(): * Delete the character to the left of the cursor * [^?] */ libedit_private el_action_t /*ARGSUSED*/ em_delete_prev_char(EditLine *el, wint_t c __attribute__((__unused__))) { if (el->el_line.cursor <= el->el_line.buffer) return CC_ERROR; if (el->el_state.doingarg) c_delbefore(el, el->el_state.argument); else c_delbefore1(el); el->el_line.cursor -= el->el_state.argument; if (el->el_line.cursor < el->el_line.buffer) el->el_line.cursor = el->el_line.buffer; return CC_REFRESH; } heimdal-7.5.0/lib/libedit/src/map.c0000644000175000017500000012352713026237312015155 0ustar niknik/* $NetBSD: map.c,v 1.51 2016/05/09 21:46:56 christos Exp $ */ /*- * Copyright (c) 1992, 1993 * The Regents of the University of California. All rights reserved. * * This code is derived from software contributed to Berkeley by * Christos Zoulas of Cornell University. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the University nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "config.h" #if !defined(lint) && !defined(SCCSID) #if 0 static char sccsid[] = "@(#)map.c 8.1 (Berkeley) 6/4/93"; #else __RCSID("$NetBSD: map.c,v 1.51 2016/05/09 21:46:56 christos Exp $"); #endif #endif /* not lint && not SCCSID */ /* * map.c: Editor function definitions */ #include #include #include #include "el.h" #include "common.h" #include "emacs.h" #include "vi.h" #include "fcns.h" #include "func.h" #include "help.h" #include "parse.h" static void map_print_key(EditLine *, el_action_t *, const wchar_t *); static void map_print_some_keys(EditLine *, el_action_t *, wint_t, wint_t); static void map_print_all_keys(EditLine *); static void map_init_nls(EditLine *); static void map_init_meta(EditLine *); /* keymap tables ; should be N_KEYS*sizeof(KEYCMD) bytes long */ static const el_action_t el_map_emacs[] = { /* 0 */ EM_SET_MARK, /* ^@ */ /* 1 */ ED_MOVE_TO_BEG, /* ^A */ /* 2 */ ED_PREV_CHAR, /* ^B */ /* 3 */ ED_IGNORE, /* ^C */ /* 4 */ EM_DELETE_OR_LIST, /* ^D */ /* 5 */ ED_MOVE_TO_END, /* ^E */ /* 6 */ ED_NEXT_CHAR, /* ^F */ /* 7 */ ED_UNASSIGNED, /* ^G */ /* 8 */ EM_DELETE_PREV_CHAR, /* ^H */ /* 9 */ ED_UNASSIGNED, /* ^I */ /* 10 */ ED_NEWLINE, /* ^J */ /* 11 */ ED_KILL_LINE, /* ^K */ /* 12 */ ED_CLEAR_SCREEN, /* ^L */ /* 13 */ ED_NEWLINE, /* ^M */ /* 14 */ ED_NEXT_HISTORY, /* ^N */ /* 15 */ ED_IGNORE, /* ^O */ /* 16 */ ED_PREV_HISTORY, /* ^P */ /* 17 */ ED_IGNORE, /* ^Q */ /* 18 */ ED_REDISPLAY, /* ^R */ /* 19 */ ED_IGNORE, /* ^S */ /* 20 */ ED_TRANSPOSE_CHARS, /* ^T */ /* 21 */ EM_KILL_LINE, /* ^U */ /* 22 */ ED_QUOTED_INSERT, /* ^V */ /* 23 */ EM_KILL_REGION, /* ^W */ /* 24 */ ED_SEQUENCE_LEAD_IN, /* ^X */ /* 25 */ EM_YANK, /* ^Y */ /* 26 */ ED_IGNORE, /* ^Z */ /* 27 */ EM_META_NEXT, /* ^[ */ /* 28 */ ED_IGNORE, /* ^\ */ /* 29 */ ED_IGNORE, /* ^] */ /* 30 */ ED_UNASSIGNED, /* ^^ */ /* 31 */ ED_UNASSIGNED, /* ^_ */ /* 32 */ ED_INSERT, /* SPACE */ /* 33 */ ED_INSERT, /* ! */ /* 34 */ ED_INSERT, /* " */ /* 35 */ ED_INSERT, /* # */ /* 36 */ ED_INSERT, /* $ */ /* 37 */ ED_INSERT, /* % */ /* 38 */ ED_INSERT, /* & */ /* 39 */ ED_INSERT, /* ' */ /* 40 */ ED_INSERT, /* ( */ /* 41 */ ED_INSERT, /* ) */ /* 42 */ ED_INSERT, /* * */ /* 43 */ ED_INSERT, /* + */ /* 44 */ ED_INSERT, /* , */ /* 45 */ ED_INSERT, /* - */ /* 46 */ ED_INSERT, /* . */ /* 47 */ ED_INSERT, /* / */ /* 48 */ ED_DIGIT, /* 0 */ /* 49 */ ED_DIGIT, /* 1 */ /* 50 */ ED_DIGIT, /* 2 */ /* 51 */ ED_DIGIT, /* 3 */ /* 52 */ ED_DIGIT, /* 4 */ /* 53 */ ED_DIGIT, /* 5 */ /* 54 */ ED_DIGIT, /* 6 */ /* 55 */ ED_DIGIT, /* 7 */ /* 56 */ ED_DIGIT, /* 8 */ /* 57 */ ED_DIGIT, /* 9 */ /* 58 */ ED_INSERT, /* : */ /* 59 */ ED_INSERT, /* ; */ /* 60 */ ED_INSERT, /* < */ /* 61 */ ED_INSERT, /* = */ /* 62 */ ED_INSERT, /* > */ /* 63 */ ED_INSERT, /* ? */ /* 64 */ ED_INSERT, /* @ */ /* 65 */ ED_INSERT, /* A */ /* 66 */ ED_INSERT, /* B */ /* 67 */ ED_INSERT, /* C */ /* 68 */ ED_INSERT, /* D */ /* 69 */ ED_INSERT, /* E */ /* 70 */ ED_INSERT, /* F */ /* 71 */ ED_INSERT, /* G */ /* 72 */ ED_INSERT, /* H */ /* 73 */ ED_INSERT, /* I */ /* 74 */ ED_INSERT, /* J */ /* 75 */ ED_INSERT, /* K */ /* 76 */ ED_INSERT, /* L */ /* 77 */ ED_INSERT, /* M */ /* 78 */ ED_INSERT, /* N */ /* 79 */ ED_INSERT, /* O */ /* 80 */ ED_INSERT, /* P */ /* 81 */ ED_INSERT, /* Q */ /* 82 */ ED_INSERT, /* R */ /* 83 */ ED_INSERT, /* S */ /* 84 */ ED_INSERT, /* T */ /* 85 */ ED_INSERT, /* U */ /* 86 */ ED_INSERT, /* V */ /* 87 */ ED_INSERT, /* W */ /* 88 */ ED_INSERT, /* X */ /* 89 */ ED_INSERT, /* Y */ /* 90 */ ED_INSERT, /* Z */ /* 91 */ ED_INSERT, /* [ */ /* 92 */ ED_INSERT, /* \ */ /* 93 */ ED_INSERT, /* ] */ /* 94 */ ED_INSERT, /* ^ */ /* 95 */ ED_INSERT, /* _ */ /* 96 */ ED_INSERT, /* ` */ /* 97 */ ED_INSERT, /* a */ /* 98 */ ED_INSERT, /* b */ /* 99 */ ED_INSERT, /* c */ /* 100 */ ED_INSERT, /* d */ /* 101 */ ED_INSERT, /* e */ /* 102 */ ED_INSERT, /* f */ /* 103 */ ED_INSERT, /* g */ /* 104 */ ED_INSERT, /* h */ /* 105 */ ED_INSERT, /* i */ /* 106 */ ED_INSERT, /* j */ /* 107 */ ED_INSERT, /* k */ /* 108 */ ED_INSERT, /* l */ /* 109 */ ED_INSERT, /* m */ /* 110 */ ED_INSERT, /* n */ /* 111 */ ED_INSERT, /* o */ /* 112 */ ED_INSERT, /* p */ /* 113 */ ED_INSERT, /* q */ /* 114 */ ED_INSERT, /* r */ /* 115 */ ED_INSERT, /* s */ /* 116 */ ED_INSERT, /* t */ /* 117 */ ED_INSERT, /* u */ /* 118 */ ED_INSERT, /* v */ /* 119 */ ED_INSERT, /* w */ /* 120 */ ED_INSERT, /* x */ /* 121 */ ED_INSERT, /* y */ /* 122 */ ED_INSERT, /* z */ /* 123 */ ED_INSERT, /* { */ /* 124 */ ED_INSERT, /* | */ /* 125 */ ED_INSERT, /* } */ /* 126 */ ED_INSERT, /* ~ */ /* 127 */ EM_DELETE_PREV_CHAR, /* ^? */ /* 128 */ ED_UNASSIGNED, /* M-^@ */ /* 129 */ ED_UNASSIGNED, /* M-^A */ /* 130 */ ED_UNASSIGNED, /* M-^B */ /* 131 */ ED_UNASSIGNED, /* M-^C */ /* 132 */ ED_UNASSIGNED, /* M-^D */ /* 133 */ ED_UNASSIGNED, /* M-^E */ /* 134 */ ED_UNASSIGNED, /* M-^F */ /* 135 */ ED_UNASSIGNED, /* M-^G */ /* 136 */ ED_DELETE_PREV_WORD, /* M-^H */ /* 137 */ ED_UNASSIGNED, /* M-^I */ /* 138 */ ED_UNASSIGNED, /* M-^J */ /* 139 */ ED_UNASSIGNED, /* M-^K */ /* 140 */ ED_CLEAR_SCREEN, /* M-^L */ /* 141 */ ED_UNASSIGNED, /* M-^M */ /* 142 */ ED_UNASSIGNED, /* M-^N */ /* 143 */ ED_UNASSIGNED, /* M-^O */ /* 144 */ ED_UNASSIGNED, /* M-^P */ /* 145 */ ED_UNASSIGNED, /* M-^Q */ /* 146 */ ED_UNASSIGNED, /* M-^R */ /* 147 */ ED_UNASSIGNED, /* M-^S */ /* 148 */ ED_UNASSIGNED, /* M-^T */ /* 149 */ ED_UNASSIGNED, /* M-^U */ /* 150 */ ED_UNASSIGNED, /* M-^V */ /* 151 */ ED_UNASSIGNED, /* M-^W */ /* 152 */ ED_UNASSIGNED, /* M-^X */ /* 153 */ ED_UNASSIGNED, /* M-^Y */ /* 154 */ ED_UNASSIGNED, /* M-^Z */ /* 155 */ ED_UNASSIGNED, /* M-^[ */ /* 156 */ ED_UNASSIGNED, /* M-^\ */ /* 157 */ ED_UNASSIGNED, /* M-^] */ /* 158 */ ED_UNASSIGNED, /* M-^^ */ /* 159 */ EM_COPY_PREV_WORD, /* M-^_ */ /* 160 */ ED_UNASSIGNED, /* M-SPACE */ /* 161 */ ED_UNASSIGNED, /* M-! */ /* 162 */ ED_UNASSIGNED, /* M-" */ /* 163 */ ED_UNASSIGNED, /* M-# */ /* 164 */ ED_UNASSIGNED, /* M-$ */ /* 165 */ ED_UNASSIGNED, /* M-% */ /* 166 */ ED_UNASSIGNED, /* M-& */ /* 167 */ ED_UNASSIGNED, /* M-' */ /* 168 */ ED_UNASSIGNED, /* M-( */ /* 169 */ ED_UNASSIGNED, /* M-) */ /* 170 */ ED_UNASSIGNED, /* M-* */ /* 171 */ ED_UNASSIGNED, /* M-+ */ /* 172 */ ED_UNASSIGNED, /* M-, */ /* 173 */ ED_UNASSIGNED, /* M-- */ /* 174 */ ED_UNASSIGNED, /* M-. */ /* 175 */ ED_UNASSIGNED, /* M-/ */ /* 176 */ ED_ARGUMENT_DIGIT, /* M-0 */ /* 177 */ ED_ARGUMENT_DIGIT, /* M-1 */ /* 178 */ ED_ARGUMENT_DIGIT, /* M-2 */ /* 179 */ ED_ARGUMENT_DIGIT, /* M-3 */ /* 180 */ ED_ARGUMENT_DIGIT, /* M-4 */ /* 181 */ ED_ARGUMENT_DIGIT, /* M-5 */ /* 182 */ ED_ARGUMENT_DIGIT, /* M-6 */ /* 183 */ ED_ARGUMENT_DIGIT, /* M-7 */ /* 184 */ ED_ARGUMENT_DIGIT, /* M-8 */ /* 185 */ ED_ARGUMENT_DIGIT, /* M-9 */ /* 186 */ ED_UNASSIGNED, /* M-: */ /* 187 */ ED_UNASSIGNED, /* M-; */ /* 188 */ ED_UNASSIGNED, /* M-< */ /* 189 */ ED_UNASSIGNED, /* M-= */ /* 190 */ ED_UNASSIGNED, /* M-> */ /* 191 */ ED_UNASSIGNED, /* M-? */ /* 192 */ ED_UNASSIGNED, /* M-@ */ /* 193 */ ED_UNASSIGNED, /* M-A */ /* 194 */ ED_PREV_WORD, /* M-B */ /* 195 */ EM_CAPITOL_CASE, /* M-C */ /* 196 */ EM_DELETE_NEXT_WORD, /* M-D */ /* 197 */ ED_UNASSIGNED, /* M-E */ /* 198 */ EM_NEXT_WORD, /* M-F */ /* 199 */ ED_UNASSIGNED, /* M-G */ /* 200 */ ED_UNASSIGNED, /* M-H */ /* 201 */ ED_UNASSIGNED, /* M-I */ /* 202 */ ED_UNASSIGNED, /* M-J */ /* 203 */ ED_UNASSIGNED, /* M-K */ /* 204 */ EM_LOWER_CASE, /* M-L */ /* 205 */ ED_UNASSIGNED, /* M-M */ /* 206 */ ED_SEARCH_NEXT_HISTORY, /* M-N */ /* 207 */ ED_SEQUENCE_LEAD_IN, /* M-O */ /* 208 */ ED_SEARCH_PREV_HISTORY, /* M-P */ /* 209 */ ED_UNASSIGNED, /* M-Q */ /* 210 */ ED_UNASSIGNED, /* M-R */ /* 211 */ ED_UNASSIGNED, /* M-S */ /* 212 */ ED_UNASSIGNED, /* M-T */ /* 213 */ EM_UPPER_CASE, /* M-U */ /* 214 */ ED_UNASSIGNED, /* M-V */ /* 215 */ EM_COPY_REGION, /* M-W */ /* 216 */ ED_COMMAND, /* M-X */ /* 217 */ ED_UNASSIGNED, /* M-Y */ /* 218 */ ED_UNASSIGNED, /* M-Z */ /* 219 */ ED_SEQUENCE_LEAD_IN, /* M-[ */ /* 220 */ ED_UNASSIGNED, /* M-\ */ /* 221 */ ED_UNASSIGNED, /* M-] */ /* 222 */ ED_UNASSIGNED, /* M-^ */ /* 223 */ ED_UNASSIGNED, /* M-_ */ /* 223 */ ED_UNASSIGNED, /* M-` */ /* 224 */ ED_UNASSIGNED, /* M-a */ /* 225 */ ED_PREV_WORD, /* M-b */ /* 226 */ EM_CAPITOL_CASE, /* M-c */ /* 227 */ EM_DELETE_NEXT_WORD, /* M-d */ /* 228 */ ED_UNASSIGNED, /* M-e */ /* 229 */ EM_NEXT_WORD, /* M-f */ /* 230 */ ED_UNASSIGNED, /* M-g */ /* 231 */ ED_UNASSIGNED, /* M-h */ /* 232 */ ED_UNASSIGNED, /* M-i */ /* 233 */ ED_UNASSIGNED, /* M-j */ /* 234 */ ED_UNASSIGNED, /* M-k */ /* 235 */ EM_LOWER_CASE, /* M-l */ /* 236 */ ED_UNASSIGNED, /* M-m */ /* 237 */ ED_SEARCH_NEXT_HISTORY, /* M-n */ /* 238 */ ED_UNASSIGNED, /* M-o */ /* 239 */ ED_SEARCH_PREV_HISTORY, /* M-p */ /* 240 */ ED_UNASSIGNED, /* M-q */ /* 241 */ ED_UNASSIGNED, /* M-r */ /* 242 */ ED_UNASSIGNED, /* M-s */ /* 243 */ ED_UNASSIGNED, /* M-t */ /* 244 */ EM_UPPER_CASE, /* M-u */ /* 245 */ ED_UNASSIGNED, /* M-v */ /* 246 */ EM_COPY_REGION, /* M-w */ /* 247 */ ED_COMMAND, /* M-x */ /* 248 */ ED_UNASSIGNED, /* M-y */ /* 249 */ ED_UNASSIGNED, /* M-z */ /* 250 */ ED_UNASSIGNED, /* M-{ */ /* 251 */ ED_UNASSIGNED, /* M-| */ /* 252 */ ED_UNASSIGNED, /* M-} */ /* 253 */ ED_UNASSIGNED, /* M-~ */ /* 254 */ ED_DELETE_PREV_WORD /* M-^? */ /* 255 */ }; /* * keymap table for vi. Each index into above tbl; should be * N_KEYS entries long. Vi mode uses a sticky-extend to do command mode: * insert mode characters are in the normal keymap, and command mode * in the extended keymap. */ static const el_action_t el_map_vi_insert[] = { #ifdef KSHVI /* 0 */ ED_UNASSIGNED, /* ^@ */ /* 1 */ ED_INSERT, /* ^A */ /* 2 */ ED_INSERT, /* ^B */ /* 3 */ ED_INSERT, /* ^C */ /* 4 */ VI_LIST_OR_EOF, /* ^D */ /* 5 */ ED_INSERT, /* ^E */ /* 6 */ ED_INSERT, /* ^F */ /* 7 */ ED_INSERT, /* ^G */ /* 8 */ VI_DELETE_PREV_CHAR, /* ^H */ /* BackSpace key */ /* 9 */ ED_INSERT, /* ^I */ /* Tab Key */ /* 10 */ ED_NEWLINE, /* ^J */ /* 11 */ ED_INSERT, /* ^K */ /* 12 */ ED_INSERT, /* ^L */ /* 13 */ ED_NEWLINE, /* ^M */ /* 14 */ ED_INSERT, /* ^N */ /* 15 */ ED_INSERT, /* ^O */ /* 16 */ ED_INSERT, /* ^P */ /* 17 */ ED_IGNORE, /* ^Q */ /* 18 */ ED_INSERT, /* ^R */ /* 19 */ ED_IGNORE, /* ^S */ /* 20 */ ED_INSERT, /* ^T */ /* 21 */ VI_KILL_LINE_PREV, /* ^U */ /* 22 */ ED_QUOTED_INSERT, /* ^V */ /* 23 */ ED_DELETE_PREV_WORD, /* ^W */ /* ED_DELETE_PREV_WORD: Only until strt edit pos */ /* 24 */ ED_INSERT, /* ^X */ /* 25 */ ED_INSERT, /* ^Y */ /* 26 */ ED_INSERT, /* ^Z */ /* 27 */ VI_COMMAND_MODE, /* ^[ */ /* [ Esc ] key */ /* 28 */ ED_IGNORE, /* ^\ */ /* 29 */ ED_INSERT, /* ^] */ /* 30 */ ED_INSERT, /* ^^ */ /* 31 */ ED_INSERT, /* ^_ */ #else /* !KSHVI */ /* * NOTE: These mappings do NOT Correspond well * to the KSH VI editing assignments. * On the other and they are convenient and * many people have have gotten used to them. */ /* 0 */ ED_UNASSIGNED, /* ^@ */ /* 1 */ ED_MOVE_TO_BEG, /* ^A */ /* 2 */ ED_PREV_CHAR, /* ^B */ /* 3 */ ED_IGNORE, /* ^C */ /* 4 */ VI_LIST_OR_EOF, /* ^D */ /* 5 */ ED_MOVE_TO_END, /* ^E */ /* 6 */ ED_NEXT_CHAR, /* ^F */ /* 7 */ ED_UNASSIGNED, /* ^G */ /* 8 */ VI_DELETE_PREV_CHAR, /* ^H */ /* BackSpace key */ /* 9 */ ED_UNASSIGNED, /* ^I */ /* Tab Key */ /* 10 */ ED_NEWLINE, /* ^J */ /* 11 */ ED_KILL_LINE, /* ^K */ /* 12 */ ED_CLEAR_SCREEN, /* ^L */ /* 13 */ ED_NEWLINE, /* ^M */ /* 14 */ ED_NEXT_HISTORY, /* ^N */ /* 15 */ ED_IGNORE, /* ^O */ /* 16 */ ED_PREV_HISTORY, /* ^P */ /* 17 */ ED_IGNORE, /* ^Q */ /* 18 */ ED_REDISPLAY, /* ^R */ /* 19 */ ED_IGNORE, /* ^S */ /* 20 */ ED_TRANSPOSE_CHARS, /* ^T */ /* 21 */ VI_KILL_LINE_PREV, /* ^U */ /* 22 */ ED_QUOTED_INSERT, /* ^V */ /* 23 */ ED_DELETE_PREV_WORD, /* ^W */ /* 24 */ ED_UNASSIGNED, /* ^X */ /* 25 */ ED_IGNORE, /* ^Y */ /* 26 */ ED_IGNORE, /* ^Z */ /* 27 */ VI_COMMAND_MODE, /* ^[ */ /* 28 */ ED_IGNORE, /* ^\ */ /* 29 */ ED_UNASSIGNED, /* ^] */ /* 30 */ ED_UNASSIGNED, /* ^^ */ /* 31 */ ED_UNASSIGNED, /* ^_ */ #endif /* KSHVI */ /* 32 */ ED_INSERT, /* SPACE */ /* 33 */ ED_INSERT, /* ! */ /* 34 */ ED_INSERT, /* " */ /* 35 */ ED_INSERT, /* # */ /* 36 */ ED_INSERT, /* $ */ /* 37 */ ED_INSERT, /* % */ /* 38 */ ED_INSERT, /* & */ /* 39 */ ED_INSERT, /* ' */ /* 40 */ ED_INSERT, /* ( */ /* 41 */ ED_INSERT, /* ) */ /* 42 */ ED_INSERT, /* * */ /* 43 */ ED_INSERT, /* + */ /* 44 */ ED_INSERT, /* , */ /* 45 */ ED_INSERT, /* - */ /* 46 */ ED_INSERT, /* . */ /* 47 */ ED_INSERT, /* / */ /* 48 */ ED_INSERT, /* 0 */ /* 49 */ ED_INSERT, /* 1 */ /* 50 */ ED_INSERT, /* 2 */ /* 51 */ ED_INSERT, /* 3 */ /* 52 */ ED_INSERT, /* 4 */ /* 53 */ ED_INSERT, /* 5 */ /* 54 */ ED_INSERT, /* 6 */ /* 55 */ ED_INSERT, /* 7 */ /* 56 */ ED_INSERT, /* 8 */ /* 57 */ ED_INSERT, /* 9 */ /* 58 */ ED_INSERT, /* : */ /* 59 */ ED_INSERT, /* ; */ /* 60 */ ED_INSERT, /* < */ /* 61 */ ED_INSERT, /* = */ /* 62 */ ED_INSERT, /* > */ /* 63 */ ED_INSERT, /* ? */ /* 64 */ ED_INSERT, /* @ */ /* 65 */ ED_INSERT, /* A */ /* 66 */ ED_INSERT, /* B */ /* 67 */ ED_INSERT, /* C */ /* 68 */ ED_INSERT, /* D */ /* 69 */ ED_INSERT, /* E */ /* 70 */ ED_INSERT, /* F */ /* 71 */ ED_INSERT, /* G */ /* 72 */ ED_INSERT, /* H */ /* 73 */ ED_INSERT, /* I */ /* 74 */ ED_INSERT, /* J */ /* 75 */ ED_INSERT, /* K */ /* 76 */ ED_INSERT, /* L */ /* 77 */ ED_INSERT, /* M */ /* 78 */ ED_INSERT, /* N */ /* 79 */ ED_INSERT, /* O */ /* 80 */ ED_INSERT, /* P */ /* 81 */ ED_INSERT, /* Q */ /* 82 */ ED_INSERT, /* R */ /* 83 */ ED_INSERT, /* S */ /* 84 */ ED_INSERT, /* T */ /* 85 */ ED_INSERT, /* U */ /* 86 */ ED_INSERT, /* V */ /* 87 */ ED_INSERT, /* W */ /* 88 */ ED_INSERT, /* X */ /* 89 */ ED_INSERT, /* Y */ /* 90 */ ED_INSERT, /* Z */ /* 91 */ ED_INSERT, /* [ */ /* 92 */ ED_INSERT, /* \ */ /* 93 */ ED_INSERT, /* ] */ /* 94 */ ED_INSERT, /* ^ */ /* 95 */ ED_INSERT, /* _ */ /* 96 */ ED_INSERT, /* ` */ /* 97 */ ED_INSERT, /* a */ /* 98 */ ED_INSERT, /* b */ /* 99 */ ED_INSERT, /* c */ /* 100 */ ED_INSERT, /* d */ /* 101 */ ED_INSERT, /* e */ /* 102 */ ED_INSERT, /* f */ /* 103 */ ED_INSERT, /* g */ /* 104 */ ED_INSERT, /* h */ /* 105 */ ED_INSERT, /* i */ /* 106 */ ED_INSERT, /* j */ /* 107 */ ED_INSERT, /* k */ /* 108 */ ED_INSERT, /* l */ /* 109 */ ED_INSERT, /* m */ /* 110 */ ED_INSERT, /* n */ /* 111 */ ED_INSERT, /* o */ /* 112 */ ED_INSERT, /* p */ /* 113 */ ED_INSERT, /* q */ /* 114 */ ED_INSERT, /* r */ /* 115 */ ED_INSERT, /* s */ /* 116 */ ED_INSERT, /* t */ /* 117 */ ED_INSERT, /* u */ /* 118 */ ED_INSERT, /* v */ /* 119 */ ED_INSERT, /* w */ /* 120 */ ED_INSERT, /* x */ /* 121 */ ED_INSERT, /* y */ /* 122 */ ED_INSERT, /* z */ /* 123 */ ED_INSERT, /* { */ /* 124 */ ED_INSERT, /* | */ /* 125 */ ED_INSERT, /* } */ /* 126 */ ED_INSERT, /* ~ */ /* 127 */ VI_DELETE_PREV_CHAR, /* ^? */ /* 128 */ ED_INSERT, /* M-^@ */ /* 129 */ ED_INSERT, /* M-^A */ /* 130 */ ED_INSERT, /* M-^B */ /* 131 */ ED_INSERT, /* M-^C */ /* 132 */ ED_INSERT, /* M-^D */ /* 133 */ ED_INSERT, /* M-^E */ /* 134 */ ED_INSERT, /* M-^F */ /* 135 */ ED_INSERT, /* M-^G */ /* 136 */ ED_INSERT, /* M-^H */ /* 137 */ ED_INSERT, /* M-^I */ /* 138 */ ED_INSERT, /* M-^J */ /* 139 */ ED_INSERT, /* M-^K */ /* 140 */ ED_INSERT, /* M-^L */ /* 141 */ ED_INSERT, /* M-^M */ /* 142 */ ED_INSERT, /* M-^N */ /* 143 */ ED_INSERT, /* M-^O */ /* 144 */ ED_INSERT, /* M-^P */ /* 145 */ ED_INSERT, /* M-^Q */ /* 146 */ ED_INSERT, /* M-^R */ /* 147 */ ED_INSERT, /* M-^S */ /* 148 */ ED_INSERT, /* M-^T */ /* 149 */ ED_INSERT, /* M-^U */ /* 150 */ ED_INSERT, /* M-^V */ /* 151 */ ED_INSERT, /* M-^W */ /* 152 */ ED_INSERT, /* M-^X */ /* 153 */ ED_INSERT, /* M-^Y */ /* 154 */ ED_INSERT, /* M-^Z */ /* 155 */ ED_INSERT, /* M-^[ */ /* 156 */ ED_INSERT, /* M-^\ */ /* 157 */ ED_INSERT, /* M-^] */ /* 158 */ ED_INSERT, /* M-^^ */ /* 159 */ ED_INSERT, /* M-^_ */ /* 160 */ ED_INSERT, /* M-SPACE */ /* 161 */ ED_INSERT, /* M-! */ /* 162 */ ED_INSERT, /* M-" */ /* 163 */ ED_INSERT, /* M-# */ /* 164 */ ED_INSERT, /* M-$ */ /* 165 */ ED_INSERT, /* M-% */ /* 166 */ ED_INSERT, /* M-& */ /* 167 */ ED_INSERT, /* M-' */ /* 168 */ ED_INSERT, /* M-( */ /* 169 */ ED_INSERT, /* M-) */ /* 170 */ ED_INSERT, /* M-* */ /* 171 */ ED_INSERT, /* M-+ */ /* 172 */ ED_INSERT, /* M-, */ /* 173 */ ED_INSERT, /* M-- */ /* 174 */ ED_INSERT, /* M-. */ /* 175 */ ED_INSERT, /* M-/ */ /* 176 */ ED_INSERT, /* M-0 */ /* 177 */ ED_INSERT, /* M-1 */ /* 178 */ ED_INSERT, /* M-2 */ /* 179 */ ED_INSERT, /* M-3 */ /* 180 */ ED_INSERT, /* M-4 */ /* 181 */ ED_INSERT, /* M-5 */ /* 182 */ ED_INSERT, /* M-6 */ /* 183 */ ED_INSERT, /* M-7 */ /* 184 */ ED_INSERT, /* M-8 */ /* 185 */ ED_INSERT, /* M-9 */ /* 186 */ ED_INSERT, /* M-: */ /* 187 */ ED_INSERT, /* M-; */ /* 188 */ ED_INSERT, /* M-< */ /* 189 */ ED_INSERT, /* M-= */ /* 190 */ ED_INSERT, /* M-> */ /* 191 */ ED_INSERT, /* M-? */ /* 192 */ ED_INSERT, /* M-@ */ /* 193 */ ED_INSERT, /* M-A */ /* 194 */ ED_INSERT, /* M-B */ /* 195 */ ED_INSERT, /* M-C */ /* 196 */ ED_INSERT, /* M-D */ /* 197 */ ED_INSERT, /* M-E */ /* 198 */ ED_INSERT, /* M-F */ /* 199 */ ED_INSERT, /* M-G */ /* 200 */ ED_INSERT, /* M-H */ /* 201 */ ED_INSERT, /* M-I */ /* 202 */ ED_INSERT, /* M-J */ /* 203 */ ED_INSERT, /* M-K */ /* 204 */ ED_INSERT, /* M-L */ /* 205 */ ED_INSERT, /* M-M */ /* 206 */ ED_INSERT, /* M-N */ /* 207 */ ED_INSERT, /* M-O */ /* 208 */ ED_INSERT, /* M-P */ /* 209 */ ED_INSERT, /* M-Q */ /* 210 */ ED_INSERT, /* M-R */ /* 211 */ ED_INSERT, /* M-S */ /* 212 */ ED_INSERT, /* M-T */ /* 213 */ ED_INSERT, /* M-U */ /* 214 */ ED_INSERT, /* M-V */ /* 215 */ ED_INSERT, /* M-W */ /* 216 */ ED_INSERT, /* M-X */ /* 217 */ ED_INSERT, /* M-Y */ /* 218 */ ED_INSERT, /* M-Z */ /* 219 */ ED_INSERT, /* M-[ */ /* 220 */ ED_INSERT, /* M-\ */ /* 221 */ ED_INSERT, /* M-] */ /* 222 */ ED_INSERT, /* M-^ */ /* 223 */ ED_INSERT, /* M-_ */ /* 224 */ ED_INSERT, /* M-` */ /* 225 */ ED_INSERT, /* M-a */ /* 226 */ ED_INSERT, /* M-b */ /* 227 */ ED_INSERT, /* M-c */ /* 228 */ ED_INSERT, /* M-d */ /* 229 */ ED_INSERT, /* M-e */ /* 230 */ ED_INSERT, /* M-f */ /* 231 */ ED_INSERT, /* M-g */ /* 232 */ ED_INSERT, /* M-h */ /* 233 */ ED_INSERT, /* M-i */ /* 234 */ ED_INSERT, /* M-j */ /* 235 */ ED_INSERT, /* M-k */ /* 236 */ ED_INSERT, /* M-l */ /* 237 */ ED_INSERT, /* M-m */ /* 238 */ ED_INSERT, /* M-n */ /* 239 */ ED_INSERT, /* M-o */ /* 240 */ ED_INSERT, /* M-p */ /* 241 */ ED_INSERT, /* M-q */ /* 242 */ ED_INSERT, /* M-r */ /* 243 */ ED_INSERT, /* M-s */ /* 244 */ ED_INSERT, /* M-t */ /* 245 */ ED_INSERT, /* M-u */ /* 246 */ ED_INSERT, /* M-v */ /* 247 */ ED_INSERT, /* M-w */ /* 248 */ ED_INSERT, /* M-x */ /* 249 */ ED_INSERT, /* M-y */ /* 250 */ ED_INSERT, /* M-z */ /* 251 */ ED_INSERT, /* M-{ */ /* 252 */ ED_INSERT, /* M-| */ /* 253 */ ED_INSERT, /* M-} */ /* 254 */ ED_INSERT, /* M-~ */ /* 255 */ ED_INSERT /* M-^? */ }; static const el_action_t el_map_vi_command[] = { /* 0 */ ED_UNASSIGNED, /* ^@ */ /* 1 */ ED_MOVE_TO_BEG, /* ^A */ /* 2 */ ED_UNASSIGNED, /* ^B */ /* 3 */ ED_IGNORE, /* ^C */ /* 4 */ ED_UNASSIGNED, /* ^D */ /* 5 */ ED_MOVE_TO_END, /* ^E */ /* 6 */ ED_UNASSIGNED, /* ^F */ /* 7 */ ED_UNASSIGNED, /* ^G */ /* 8 */ ED_DELETE_PREV_CHAR, /* ^H */ /* 9 */ ED_UNASSIGNED, /* ^I */ /* 10 */ ED_NEWLINE, /* ^J */ /* 11 */ ED_KILL_LINE, /* ^K */ /* 12 */ ED_CLEAR_SCREEN, /* ^L */ /* 13 */ ED_NEWLINE, /* ^M */ /* 14 */ ED_NEXT_HISTORY, /* ^N */ /* 15 */ ED_IGNORE, /* ^O */ /* 16 */ ED_PREV_HISTORY, /* ^P */ /* 17 */ ED_IGNORE, /* ^Q */ /* 18 */ ED_REDISPLAY, /* ^R */ /* 19 */ ED_IGNORE, /* ^S */ /* 20 */ ED_UNASSIGNED, /* ^T */ /* 21 */ VI_KILL_LINE_PREV, /* ^U */ /* 22 */ ED_UNASSIGNED, /* ^V */ /* 23 */ ED_DELETE_PREV_WORD, /* ^W */ /* 24 */ ED_UNASSIGNED, /* ^X */ /* 25 */ ED_UNASSIGNED, /* ^Y */ /* 26 */ ED_UNASSIGNED, /* ^Z */ /* 27 */ EM_META_NEXT, /* ^[ */ /* 28 */ ED_IGNORE, /* ^\ */ /* 29 */ ED_UNASSIGNED, /* ^] */ /* 30 */ ED_UNASSIGNED, /* ^^ */ /* 31 */ ED_UNASSIGNED, /* ^_ */ /* 32 */ ED_NEXT_CHAR, /* SPACE */ /* 33 */ ED_UNASSIGNED, /* ! */ /* 34 */ ED_UNASSIGNED, /* " */ /* 35 */ VI_COMMENT_OUT, /* # */ /* 36 */ ED_MOVE_TO_END, /* $ */ /* 37 */ VI_MATCH, /* % */ /* 38 */ ED_UNASSIGNED, /* & */ /* 39 */ ED_UNASSIGNED, /* ' */ /* 40 */ ED_UNASSIGNED, /* ( */ /* 41 */ ED_UNASSIGNED, /* ) */ /* 42 */ ED_UNASSIGNED, /* * */ /* 43 */ ED_NEXT_HISTORY, /* + */ /* 44 */ VI_REPEAT_PREV_CHAR, /* , */ /* 45 */ ED_PREV_HISTORY, /* - */ /* 46 */ VI_REDO, /* . */ /* 47 */ VI_SEARCH_PREV, /* / */ /* 48 */ VI_ZERO, /* 0 */ /* 49 */ ED_ARGUMENT_DIGIT, /* 1 */ /* 50 */ ED_ARGUMENT_DIGIT, /* 2 */ /* 51 */ ED_ARGUMENT_DIGIT, /* 3 */ /* 52 */ ED_ARGUMENT_DIGIT, /* 4 */ /* 53 */ ED_ARGUMENT_DIGIT, /* 5 */ /* 54 */ ED_ARGUMENT_DIGIT, /* 6 */ /* 55 */ ED_ARGUMENT_DIGIT, /* 7 */ /* 56 */ ED_ARGUMENT_DIGIT, /* 8 */ /* 57 */ ED_ARGUMENT_DIGIT, /* 9 */ /* 58 */ ED_COMMAND, /* : */ /* 59 */ VI_REPEAT_NEXT_CHAR, /* ; */ /* 60 */ ED_UNASSIGNED, /* < */ /* 61 */ ED_UNASSIGNED, /* = */ /* 62 */ ED_UNASSIGNED, /* > */ /* 63 */ VI_SEARCH_NEXT, /* ? */ /* 64 */ VI_ALIAS, /* @ */ /* 65 */ VI_ADD_AT_EOL, /* A */ /* 66 */ VI_PREV_BIG_WORD, /* B */ /* 67 */ VI_CHANGE_TO_EOL, /* C */ /* 68 */ ED_KILL_LINE, /* D */ /* 69 */ VI_END_BIG_WORD, /* E */ /* 70 */ VI_PREV_CHAR, /* F */ /* 71 */ VI_TO_HISTORY_LINE, /* G */ /* 72 */ ED_UNASSIGNED, /* H */ /* 73 */ VI_INSERT_AT_BOL, /* I */ /* 74 */ ED_SEARCH_NEXT_HISTORY, /* J */ /* 75 */ ED_SEARCH_PREV_HISTORY, /* K */ /* 76 */ ED_UNASSIGNED, /* L */ /* 77 */ ED_UNASSIGNED, /* M */ /* 78 */ VI_REPEAT_SEARCH_PREV, /* N */ /* 79 */ ED_SEQUENCE_LEAD_IN, /* O */ /* 80 */ VI_PASTE_PREV, /* P */ /* 81 */ ED_UNASSIGNED, /* Q */ /* 82 */ VI_REPLACE_MODE, /* R */ /* 83 */ VI_SUBSTITUTE_LINE, /* S */ /* 84 */ VI_TO_PREV_CHAR, /* T */ /* 85 */ VI_UNDO_LINE, /* U */ /* 86 */ ED_UNASSIGNED, /* V */ /* 87 */ VI_NEXT_BIG_WORD, /* W */ /* 88 */ ED_DELETE_PREV_CHAR, /* X */ /* 89 */ VI_YANK_END, /* Y */ /* 90 */ ED_UNASSIGNED, /* Z */ /* 91 */ ED_SEQUENCE_LEAD_IN, /* [ */ /* 92 */ ED_UNASSIGNED, /* \ */ /* 93 */ ED_UNASSIGNED, /* ] */ /* 94 */ ED_MOVE_TO_BEG, /* ^ */ /* 95 */ VI_HISTORY_WORD, /* _ */ /* 96 */ ED_UNASSIGNED, /* ` */ /* 97 */ VI_ADD, /* a */ /* 98 */ VI_PREV_WORD, /* b */ /* 99 */ VI_CHANGE_META, /* c */ /* 100 */ VI_DELETE_META, /* d */ /* 101 */ VI_END_WORD, /* e */ /* 102 */ VI_NEXT_CHAR, /* f */ /* 103 */ ED_UNASSIGNED, /* g */ /* 104 */ ED_PREV_CHAR, /* h */ /* 105 */ VI_INSERT, /* i */ /* 106 */ ED_NEXT_HISTORY, /* j */ /* 107 */ ED_PREV_HISTORY, /* k */ /* 108 */ ED_NEXT_CHAR, /* l */ /* 109 */ ED_UNASSIGNED, /* m */ /* 110 */ VI_REPEAT_SEARCH_NEXT, /* n */ /* 111 */ ED_UNASSIGNED, /* o */ /* 112 */ VI_PASTE_NEXT, /* p */ /* 113 */ ED_UNASSIGNED, /* q */ /* 114 */ VI_REPLACE_CHAR, /* r */ /* 115 */ VI_SUBSTITUTE_CHAR, /* s */ /* 116 */ VI_TO_NEXT_CHAR, /* t */ /* 117 */ VI_UNDO, /* u */ /* 118 */ VI_HISTEDIT, /* v */ /* 119 */ VI_NEXT_WORD, /* w */ /* 120 */ ED_DELETE_NEXT_CHAR, /* x */ /* 121 */ VI_YANK, /* y */ /* 122 */ ED_UNASSIGNED, /* z */ /* 123 */ ED_UNASSIGNED, /* { */ /* 124 */ VI_TO_COLUMN, /* | */ /* 125 */ ED_UNASSIGNED, /* } */ /* 126 */ VI_CHANGE_CASE, /* ~ */ /* 127 */ ED_DELETE_PREV_CHAR, /* ^? */ /* 128 */ ED_UNASSIGNED, /* M-^@ */ /* 129 */ ED_UNASSIGNED, /* M-^A */ /* 130 */ ED_UNASSIGNED, /* M-^B */ /* 131 */ ED_UNASSIGNED, /* M-^C */ /* 132 */ ED_UNASSIGNED, /* M-^D */ /* 133 */ ED_UNASSIGNED, /* M-^E */ /* 134 */ ED_UNASSIGNED, /* M-^F */ /* 135 */ ED_UNASSIGNED, /* M-^G */ /* 136 */ ED_UNASSIGNED, /* M-^H */ /* 137 */ ED_UNASSIGNED, /* M-^I */ /* 138 */ ED_UNASSIGNED, /* M-^J */ /* 139 */ ED_UNASSIGNED, /* M-^K */ /* 140 */ ED_UNASSIGNED, /* M-^L */ /* 141 */ ED_UNASSIGNED, /* M-^M */ /* 142 */ ED_UNASSIGNED, /* M-^N */ /* 143 */ ED_UNASSIGNED, /* M-^O */ /* 144 */ ED_UNASSIGNED, /* M-^P */ /* 145 */ ED_UNASSIGNED, /* M-^Q */ /* 146 */ ED_UNASSIGNED, /* M-^R */ /* 147 */ ED_UNASSIGNED, /* M-^S */ /* 148 */ ED_UNASSIGNED, /* M-^T */ /* 149 */ ED_UNASSIGNED, /* M-^U */ /* 150 */ ED_UNASSIGNED, /* M-^V */ /* 151 */ ED_UNASSIGNED, /* M-^W */ /* 152 */ ED_UNASSIGNED, /* M-^X */ /* 153 */ ED_UNASSIGNED, /* M-^Y */ /* 154 */ ED_UNASSIGNED, /* M-^Z */ /* 155 */ ED_UNASSIGNED, /* M-^[ */ /* 156 */ ED_UNASSIGNED, /* M-^\ */ /* 157 */ ED_UNASSIGNED, /* M-^] */ /* 158 */ ED_UNASSIGNED, /* M-^^ */ /* 159 */ ED_UNASSIGNED, /* M-^_ */ /* 160 */ ED_UNASSIGNED, /* M-SPACE */ /* 161 */ ED_UNASSIGNED, /* M-! */ /* 162 */ ED_UNASSIGNED, /* M-" */ /* 163 */ ED_UNASSIGNED, /* M-# */ /* 164 */ ED_UNASSIGNED, /* M-$ */ /* 165 */ ED_UNASSIGNED, /* M-% */ /* 166 */ ED_UNASSIGNED, /* M-& */ /* 167 */ ED_UNASSIGNED, /* M-' */ /* 168 */ ED_UNASSIGNED, /* M-( */ /* 169 */ ED_UNASSIGNED, /* M-) */ /* 170 */ ED_UNASSIGNED, /* M-* */ /* 171 */ ED_UNASSIGNED, /* M-+ */ /* 172 */ ED_UNASSIGNED, /* M-, */ /* 173 */ ED_UNASSIGNED, /* M-- */ /* 174 */ ED_UNASSIGNED, /* M-. */ /* 175 */ ED_UNASSIGNED, /* M-/ */ /* 176 */ ED_UNASSIGNED, /* M-0 */ /* 177 */ ED_UNASSIGNED, /* M-1 */ /* 178 */ ED_UNASSIGNED, /* M-2 */ /* 179 */ ED_UNASSIGNED, /* M-3 */ /* 180 */ ED_UNASSIGNED, /* M-4 */ /* 181 */ ED_UNASSIGNED, /* M-5 */ /* 182 */ ED_UNASSIGNED, /* M-6 */ /* 183 */ ED_UNASSIGNED, /* M-7 */ /* 184 */ ED_UNASSIGNED, /* M-8 */ /* 185 */ ED_UNASSIGNED, /* M-9 */ /* 186 */ ED_UNASSIGNED, /* M-: */ /* 187 */ ED_UNASSIGNED, /* M-; */ /* 188 */ ED_UNASSIGNED, /* M-< */ /* 189 */ ED_UNASSIGNED, /* M-= */ /* 190 */ ED_UNASSIGNED, /* M-> */ /* 191 */ ED_UNASSIGNED, /* M-? */ /* 192 */ ED_UNASSIGNED, /* M-@ */ /* 193 */ ED_UNASSIGNED, /* M-A */ /* 194 */ ED_UNASSIGNED, /* M-B */ /* 195 */ ED_UNASSIGNED, /* M-C */ /* 196 */ ED_UNASSIGNED, /* M-D */ /* 197 */ ED_UNASSIGNED, /* M-E */ /* 198 */ ED_UNASSIGNED, /* M-F */ /* 199 */ ED_UNASSIGNED, /* M-G */ /* 200 */ ED_UNASSIGNED, /* M-H */ /* 201 */ ED_UNASSIGNED, /* M-I */ /* 202 */ ED_UNASSIGNED, /* M-J */ /* 203 */ ED_UNASSIGNED, /* M-K */ /* 204 */ ED_UNASSIGNED, /* M-L */ /* 205 */ ED_UNASSIGNED, /* M-M */ /* 206 */ ED_UNASSIGNED, /* M-N */ /* 207 */ ED_SEQUENCE_LEAD_IN, /* M-O */ /* 208 */ ED_UNASSIGNED, /* M-P */ /* 209 */ ED_UNASSIGNED, /* M-Q */ /* 210 */ ED_UNASSIGNED, /* M-R */ /* 211 */ ED_UNASSIGNED, /* M-S */ /* 212 */ ED_UNASSIGNED, /* M-T */ /* 213 */ ED_UNASSIGNED, /* M-U */ /* 214 */ ED_UNASSIGNED, /* M-V */ /* 215 */ ED_UNASSIGNED, /* M-W */ /* 216 */ ED_UNASSIGNED, /* M-X */ /* 217 */ ED_UNASSIGNED, /* M-Y */ /* 218 */ ED_UNASSIGNED, /* M-Z */ /* 219 */ ED_SEQUENCE_LEAD_IN, /* M-[ */ /* 220 */ ED_UNASSIGNED, /* M-\ */ /* 221 */ ED_UNASSIGNED, /* M-] */ /* 222 */ ED_UNASSIGNED, /* M-^ */ /* 223 */ ED_UNASSIGNED, /* M-_ */ /* 224 */ ED_UNASSIGNED, /* M-` */ /* 225 */ ED_UNASSIGNED, /* M-a */ /* 226 */ ED_UNASSIGNED, /* M-b */ /* 227 */ ED_UNASSIGNED, /* M-c */ /* 228 */ ED_UNASSIGNED, /* M-d */ /* 229 */ ED_UNASSIGNED, /* M-e */ /* 230 */ ED_UNASSIGNED, /* M-f */ /* 231 */ ED_UNASSIGNED, /* M-g */ /* 232 */ ED_UNASSIGNED, /* M-h */ /* 233 */ ED_UNASSIGNED, /* M-i */ /* 234 */ ED_UNASSIGNED, /* M-j */ /* 235 */ ED_UNASSIGNED, /* M-k */ /* 236 */ ED_UNASSIGNED, /* M-l */ /* 237 */ ED_UNASSIGNED, /* M-m */ /* 238 */ ED_UNASSIGNED, /* M-n */ /* 239 */ ED_UNASSIGNED, /* M-o */ /* 240 */ ED_UNASSIGNED, /* M-p */ /* 241 */ ED_UNASSIGNED, /* M-q */ /* 242 */ ED_UNASSIGNED, /* M-r */ /* 243 */ ED_UNASSIGNED, /* M-s */ /* 244 */ ED_UNASSIGNED, /* M-t */ /* 245 */ ED_UNASSIGNED, /* M-u */ /* 246 */ ED_UNASSIGNED, /* M-v */ /* 247 */ ED_UNASSIGNED, /* M-w */ /* 248 */ ED_UNASSIGNED, /* M-x */ /* 249 */ ED_UNASSIGNED, /* M-y */ /* 250 */ ED_UNASSIGNED, /* M-z */ /* 251 */ ED_UNASSIGNED, /* M-{ */ /* 252 */ ED_UNASSIGNED, /* M-| */ /* 253 */ ED_UNASSIGNED, /* M-} */ /* 254 */ ED_UNASSIGNED, /* M-~ */ /* 255 */ ED_UNASSIGNED /* M-^? */ }; /* map_init(): * Initialize and allocate the maps */ libedit_private int map_init(EditLine *el) { /* * Make sure those are correct before starting. */ #ifdef MAP_DEBUG if (sizeof(el_map_emacs) != N_KEYS * sizeof(el_action_t)) EL_ABORT((el->errfile, "Emacs map incorrect\n")); if (sizeof(el_map_vi_command) != N_KEYS * sizeof(el_action_t)) EL_ABORT((el->errfile, "Vi command map incorrect\n")); if (sizeof(el_map_vi_insert) != N_KEYS * sizeof(el_action_t)) EL_ABORT((el->errfile, "Vi insert map incorrect\n")); #endif el->el_map.alt = el_malloc(sizeof(*el->el_map.alt) * N_KEYS); if (el->el_map.alt == NULL) return -1; el->el_map.key = el_malloc(sizeof(*el->el_map.key) * N_KEYS); if (el->el_map.key == NULL) return -1; el->el_map.emacs = el_map_emacs; el->el_map.vic = el_map_vi_command; el->el_map.vii = el_map_vi_insert; el->el_map.help = el_malloc(sizeof(*el->el_map.help) * EL_NUM_FCNS); if (el->el_map.help == NULL) return -1; (void) memcpy(el->el_map.help, el_func_help, sizeof(*el->el_map.help) * EL_NUM_FCNS); el->el_map.func = el_malloc(sizeof(*el->el_map.func) * EL_NUM_FCNS); if (el->el_map.func == NULL) return -1; memcpy(el->el_map.func, el_func, sizeof(*el->el_map.func) * EL_NUM_FCNS); el->el_map.nfunc = EL_NUM_FCNS; #ifdef VIDEFAULT map_init_vi(el); #else map_init_emacs(el); #endif /* VIDEFAULT */ return 0; } /* map_end(): * Free the space taken by the editor maps */ libedit_private void map_end(EditLine *el) { el_free(el->el_map.alt); el->el_map.alt = NULL; el_free(el->el_map.key); el->el_map.key = NULL; el->el_map.emacs = NULL; el->el_map.vic = NULL; el->el_map.vii = NULL; el_free(el->el_map.help); el->el_map.help = NULL; el_free(el->el_map.func); el->el_map.func = NULL; } /* map_init_nls(): * Find all the printable keys and bind them to self insert */ static void map_init_nls(EditLine *el) { int i; el_action_t *map = el->el_map.key; for (i = 0200; i <= 0377; i++) if (iswprint(i)) map[i] = ED_INSERT; } /* map_init_meta(): * Bind all the meta keys to the appropriate ESC- sequence */ static void map_init_meta(EditLine *el) { wchar_t buf[3]; int i; el_action_t *map = el->el_map.key; el_action_t *alt = el->el_map.alt; for (i = 0; i <= 0377 && map[i] != EM_META_NEXT; i++) continue; if (i > 0377) { for (i = 0; i <= 0377 && alt[i] != EM_META_NEXT; i++) continue; if (i > 0377) { i = 033; if (el->el_map.type == MAP_VI) map = alt; } else map = alt; } buf[0] = (wchar_t)i; buf[2] = 0; for (i = 0200; i <= 0377; i++) switch (map[i]) { case ED_INSERT: case ED_UNASSIGNED: case ED_SEQUENCE_LEAD_IN: break; default: buf[1] = i & 0177; keymacro_add(el, buf, keymacro_map_cmd(el, (int) map[i]), XK_CMD); break; } map[(int) buf[0]] = ED_SEQUENCE_LEAD_IN; } /* map_init_vi(): * Initialize the vi bindings */ libedit_private void map_init_vi(EditLine *el) { int i; el_action_t *key = el->el_map.key; el_action_t *alt = el->el_map.alt; const el_action_t *vii = el->el_map.vii; const el_action_t *vic = el->el_map.vic; el->el_map.type = MAP_VI; el->el_map.current = el->el_map.key; keymacro_reset(el); for (i = 0; i < N_KEYS; i++) { key[i] = vii[i]; alt[i] = vic[i]; } map_init_meta(el); map_init_nls(el); tty_bind_char(el, 1); terminal_bind_arrow(el); } /* map_init_emacs(): * Initialize the emacs bindings */ libedit_private void map_init_emacs(EditLine *el) { int i; wchar_t buf[3]; el_action_t *key = el->el_map.key; el_action_t *alt = el->el_map.alt; const el_action_t *emacs = el->el_map.emacs; el->el_map.type = MAP_EMACS; el->el_map.current = el->el_map.key; keymacro_reset(el); for (i = 0; i < N_KEYS; i++) { key[i] = emacs[i]; alt[i] = ED_UNASSIGNED; } map_init_meta(el); map_init_nls(el); buf[0] = CONTROL('X'); buf[1] = CONTROL('X'); buf[2] = 0; keymacro_add(el, buf, keymacro_map_cmd(el, EM_EXCHANGE_MARK), XK_CMD); tty_bind_char(el, 1); terminal_bind_arrow(el); } /* map_set_editor(): * Set the editor */ libedit_private int map_set_editor(EditLine *el, wchar_t *editor) { if (wcscmp(editor, L"emacs") == 0) { map_init_emacs(el); return 0; } if (wcscmp(editor, L"vi") == 0) { map_init_vi(el); return 0; } return -1; } /* map_get_editor(): * Retrieve the editor */ libedit_private int map_get_editor(EditLine *el, const wchar_t **editor) { if (editor == NULL) return -1; switch (el->el_map.type) { case MAP_EMACS: *editor = L"emacs"; return 0; case MAP_VI: *editor = L"vi"; return 0; } return -1; } /* map_print_key(): * Print the function description for 1 key */ static void map_print_key(EditLine *el, el_action_t *map, const wchar_t *in) { char outbuf[EL_BUFSIZ]; el_bindings_t *bp, *ep; if (in[0] == '\0' || in[1] == '\0') { (void) keymacro__decode_str(in, outbuf, sizeof(outbuf), ""); ep = &el->el_map.help[el->el_map.nfunc]; for (bp = el->el_map.help; bp < ep; bp++) if (bp->func == map[(unsigned char) *in]) { (void) fprintf(el->el_outfile, "%s\t->\t%ls\n", outbuf, bp->name); return; } } else keymacro_print(el, in); } /* map_print_some_keys(): * Print keys from first to last */ static void map_print_some_keys(EditLine *el, el_action_t *map, wint_t first, wint_t last) { el_bindings_t *bp, *ep; wchar_t firstbuf[2], lastbuf[2]; char unparsbuf[EL_BUFSIZ], extrabuf[EL_BUFSIZ]; firstbuf[0] = first; firstbuf[1] = 0; lastbuf[0] = last; lastbuf[1] = 0; if (map[first] == ED_UNASSIGNED) { if (first == last) { (void) keymacro__decode_str(firstbuf, unparsbuf, sizeof(unparsbuf), STRQQ); (void) fprintf(el->el_outfile, "%-15s-> is undefined\n", unparsbuf); } return; } ep = &el->el_map.help[el->el_map.nfunc]; for (bp = el->el_map.help; bp < ep; bp++) { if (bp->func == map[first]) { if (first == last) { (void) keymacro__decode_str(firstbuf, unparsbuf, sizeof(unparsbuf), STRQQ); (void) fprintf(el->el_outfile, "%-15s-> %ls\n", unparsbuf, bp->name); } else { (void) keymacro__decode_str(firstbuf, unparsbuf, sizeof(unparsbuf), STRQQ); (void) keymacro__decode_str(lastbuf, extrabuf, sizeof(extrabuf), STRQQ); (void) fprintf(el->el_outfile, "%-4s to %-7s-> %ls\n", unparsbuf, extrabuf, bp->name); } return; } } #ifdef MAP_DEBUG if (map == el->el_map.key) { (void) keymacro__decode_str(firstbuf, unparsbuf, sizeof(unparsbuf), STRQQ); (void) fprintf(el->el_outfile, "BUG!!! %s isn't bound to anything.\n", unparsbuf); (void) fprintf(el->el_outfile, "el->el_map.key[%d] == %d\n", first, el->el_map.key[first]); } else { (void) keymacro__decode_str(firstbuf, unparsbuf, sizeof(unparsbuf), STRQQ); (void) fprintf(el->el_outfile, "BUG!!! %s isn't bound to anything.\n", unparsbuf); (void) fprintf(el->el_outfile, "el->el_map.alt[%d] == %d\n", first, el->el_map.alt[first]); } #endif EL_ABORT((el->el_errfile, "Error printing keys\n")); } /* map_print_all_keys(): * Print the function description for all keys. */ static void map_print_all_keys(EditLine *el) { int prev, i; (void) fprintf(el->el_outfile, "Standard key bindings\n"); prev = 0; for (i = 0; i < N_KEYS; i++) { if (el->el_map.key[prev] == el->el_map.key[i]) continue; map_print_some_keys(el, el->el_map.key, prev, i - 1); prev = i; } map_print_some_keys(el, el->el_map.key, prev, i - 1); (void) fprintf(el->el_outfile, "Alternative key bindings\n"); prev = 0; for (i = 0; i < N_KEYS; i++) { if (el->el_map.alt[prev] == el->el_map.alt[i]) continue; map_print_some_keys(el, el->el_map.alt, prev, i - 1); prev = i; } map_print_some_keys(el, el->el_map.alt, prev, i - 1); (void) fprintf(el->el_outfile, "Multi-character bindings\n"); keymacro_print(el, L""); (void) fprintf(el->el_outfile, "Arrow key bindings\n"); terminal_print_arrow(el, L""); } /* map_bind(): * Add/remove/change bindings */ libedit_private int map_bind(EditLine *el, int argc, const wchar_t **argv) { el_action_t *map; int ntype, rem; const wchar_t *p; wchar_t inbuf[EL_BUFSIZ]; wchar_t outbuf[EL_BUFSIZ]; const wchar_t *in = NULL; wchar_t *out; el_bindings_t *bp, *ep; int cmd; int key; if (argv == NULL) return -1; map = el->el_map.key; ntype = XK_CMD; key = rem = 0; for (argc = 1; (p = argv[argc]) != NULL; argc++) if (p[0] == '-') switch (p[1]) { case 'a': map = el->el_map.alt; break; case 's': ntype = XK_STR; break; case 'k': key = 1; break; case 'r': rem = 1; break; case 'v': map_init_vi(el); return 0; case 'e': map_init_emacs(el); return 0; case 'l': ep = &el->el_map.help[el->el_map.nfunc]; for (bp = el->el_map.help; bp < ep; bp++) (void) fprintf(el->el_outfile, "%ls\n\t%ls\n", bp->name, bp->description); return 0; default: (void) fprintf(el->el_errfile, "%ls: Invalid switch `%lc'.\n", argv[0], (wint_t)p[1]); } else break; if (argv[argc] == NULL) { map_print_all_keys(el); return 0; } if (key) in = argv[argc++]; else if ((in = parse__string(inbuf, argv[argc++])) == NULL) { (void) fprintf(el->el_errfile, "%ls: Invalid \\ or ^ in instring.\n", argv[0]); return -1; } if (rem) { if (key) { (void) terminal_clear_arrow(el, in); return -1; } if (in[1]) (void) keymacro_delete(el, in); else if (map[(unsigned char) *in] == ED_SEQUENCE_LEAD_IN) (void) keymacro_delete(el, in); else map[(unsigned char) *in] = ED_UNASSIGNED; return 0; } if (argv[argc] == NULL) { if (key) terminal_print_arrow(el, in); else map_print_key(el, map, in); return 0; } #ifdef notyet if (argv[argc + 1] != NULL) { bindkeymacro_usage(); return -1; } #endif switch (ntype) { case XK_STR: if ((out = parse__string(outbuf, argv[argc])) == NULL) { (void) fprintf(el->el_errfile, "%ls: Invalid \\ or ^ in outstring.\n", argv[0]); return -1; } if (key) terminal_set_arrow(el, in, keymacro_map_str(el, out), ntype); else keymacro_add(el, in, keymacro_map_str(el, out), ntype); map[(unsigned char) *in] = ED_SEQUENCE_LEAD_IN; break; case XK_CMD: if ((cmd = parse_cmd(el, argv[argc])) == -1) { (void) fprintf(el->el_errfile, "%ls: Invalid command `%ls'.\n", argv[0], argv[argc]); return -1; } if (key) terminal_set_arrow(el, in, keymacro_map_cmd(el, cmd), ntype); else { if (in[1]) { keymacro_add(el, in, keymacro_map_cmd(el, cmd), ntype); map[(unsigned char) *in] = ED_SEQUENCE_LEAD_IN; } else { keymacro_clear(el, map, in); map[(unsigned char) *in] = (el_action_t)cmd; } } break; /* coverity[dead_error_begin] */ default: EL_ABORT((el->el_errfile, "Bad XK_ type %d\n", ntype)); break; } return 0; } /* map_addfunc(): * add a user defined function */ libedit_private int map_addfunc(EditLine *el, const wchar_t *name, const wchar_t *help, el_func_t func) { void *p; size_t nf = el->el_map.nfunc + 1; if (name == NULL || help == NULL || func == NULL) return -1; if ((p = el_realloc(el->el_map.func, nf * sizeof(*el->el_map.func))) == NULL) return -1; el->el_map.func = p; if ((p = el_realloc(el->el_map.help, nf * sizeof(*el->el_map.help))) == NULL) return -1; el->el_map.help = p; nf = (size_t)el->el_map.nfunc; el->el_map.func[nf] = func; el->el_map.help[nf].name = name; el->el_map.help[nf].func = (int)nf; el->el_map.help[nf].description = help; el->el_map.nfunc++; return 0; } heimdal-7.5.0/lib/libedit/src/readline.c0000644000175000017500000013644613026237312016167 0ustar niknik/* $NetBSD: readline.c,v 1.139 2016/10/28 18:32:26 christos Exp $ */ /*- * Copyright (c) 1997 The NetBSD Foundation, Inc. * All rights reserved. * * This code is derived from software contributed to The NetBSD Foundation * by Jaromir Dolecek. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include "config.h" #if !defined(lint) && !defined(SCCSID) __RCSID("$NetBSD: readline.c,v 1.139 2016/10/28 18:32:26 christos Exp $"); #endif /* not lint && not SCCSID */ #include "config.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include "readline/readline.h" #include "el.h" #include "fcns.h" #include "filecomplete.h" void rl_prep_terminal(int); void rl_deprep_terminal(void); /* for rl_complete() */ #define TAB '\r' /* see comment at the #ifdef for sense of this */ /* #define GDB_411_HACK */ /* readline compatibility stuff - look at readline sources/documentation */ /* to see what these variables mean */ const char *rl_library_version = "EditLine wrapper"; int rl_readline_version = RL_READLINE_VERSION; static char empty[] = { '\0' }; static char expand_chars[] = { ' ', '\t', '\n', '=', '(', '\0' }; static char break_chars[] = { ' ', '\t', '\n', '"', '\\', '\'', '`', '@', '$', '>', '<', '=', ';', '|', '&', '{', '(', '\0' }; char *rl_readline_name = empty; FILE *rl_instream = NULL; FILE *rl_outstream = NULL; int rl_point = 0; int rl_end = 0; char *rl_line_buffer = NULL; rl_vcpfunc_t *rl_linefunc = NULL; int rl_done = 0; VFunction *rl_event_hook = NULL; KEYMAP_ENTRY_ARRAY emacs_standard_keymap, emacs_meta_keymap, emacs_ctlx_keymap; /* * The following is not implemented; we always catch signals in the * libedit fashion: set handlers on entry to el_gets() and clear them * on the way out. This simplistic approach works for most cases; if * it does not work for your application, please let us know. */ int rl_catch_signals = 1; int rl_catch_sigwinch = 1; int history_base = 1; /* probably never subject to change */ int history_length = 0; int history_offset = 0; int max_input_history = 0; char history_expansion_char = '!'; char history_subst_char = '^'; char *history_no_expand_chars = expand_chars; Function *history_inhibit_expansion_function = NULL; char *history_arg_extract(int start, int end, const char *str); int rl_inhibit_completion = 0; int rl_attempted_completion_over = 0; char *rl_basic_word_break_characters = break_chars; char *rl_completer_word_break_characters = NULL; char *rl_completer_quote_characters = NULL; rl_compentry_func_t *rl_completion_entry_function = NULL; char *(*rl_completion_word_break_hook)(void) = NULL; rl_completion_func_t *rl_attempted_completion_function = NULL; Function *rl_pre_input_hook = NULL; Function *rl_startup1_hook = NULL; int (*rl_getc_function)(FILE *) = NULL; char *rl_terminal_name = NULL; int rl_already_prompted = 0; int rl_filename_completion_desired = 0; int rl_ignore_completion_duplicates = 0; int readline_echoing_p = 1; int _rl_print_completions_horizontally = 0; VFunction *rl_redisplay_function = NULL; Function *rl_startup_hook = NULL; VFunction *rl_completion_display_matches_hook = NULL; VFunction *rl_prep_term_function = (VFunction *)rl_prep_terminal; VFunction *rl_deprep_term_function = (VFunction *)rl_deprep_terminal; KEYMAP_ENTRY_ARRAY emacs_meta_keymap; /* * The current prompt string. */ char *rl_prompt = NULL; /* * This is set to character indicating type of completion being done by * rl_complete_internal(); this is available for application completion * functions. */ int rl_completion_type = 0; /* * If more than this number of items results from query for possible * completions, we ask user if they are sure to really display the list. */ int rl_completion_query_items = 100; /* * List of characters which are word break characters, but should be left * in the parsed text when it is passed to the completion function. * Shell uses this to help determine what kind of completing to do. */ char *rl_special_prefixes = NULL; /* * This is the character appended to the completed words if at the end of * the line. Default is ' ' (a space). */ int rl_completion_append_character = ' '; /* stuff below is used internally by libedit for readline emulation */ static History *h = NULL; static EditLine *e = NULL; static rl_command_func_t *map[256]; static jmp_buf topbuf; /* internal functions */ static unsigned char _el_rl_complete(EditLine *, int); static unsigned char _el_rl_tstp(EditLine *, int); static char *_get_prompt(EditLine *); static int _getc_function(EditLine *, wchar_t *); static int _history_expand_command(const char *, size_t, size_t, char **); static char *_rl_compat_sub(const char *, const char *, const char *, int); static int _rl_event_read_char(EditLine *, wchar_t *); static void _rl_update_pos(void); static HIST_ENTRY rl_he; /* ARGSUSED */ static char * _get_prompt(EditLine *el __attribute__((__unused__))) { rl_already_prompted = 1; return rl_prompt; } /* * read one key from user defined input function */ static int /*ARGSUSED*/ _getc_function(EditLine *el __attribute__((__unused__)), wchar_t *c) { int i; i = (*rl_getc_function)(rl_instream); if (i == -1) return 0; *c = (wchar_t)i; return 1; } static void _resize_fun(EditLine *el, void *a) { const LineInfo *li; char **ap = a; li = el_line(el); /* a cheesy way to get rid of const cast. */ *ap = memchr(li->buffer, *li->buffer, (size_t)1); } static const char * _default_history_file(void) { struct passwd *p; static char *path; size_t len; if (path) return path; if ((p = getpwuid(getuid())) == NULL) return NULL; len = strlen(p->pw_dir) + sizeof("/.history"); if ((path = malloc(len)) == NULL) return NULL; (void)snprintf(path, len, "%s/.history", p->pw_dir); return path; } /* * READLINE compatibility stuff */ /* * Set the prompt */ int rl_set_prompt(const char *prompt) { char *p; if (!prompt) prompt = ""; if (rl_prompt != NULL && strcmp(rl_prompt, prompt) == 0) return 0; if (rl_prompt) el_free(rl_prompt); rl_prompt = strdup(prompt); if (rl_prompt == NULL) return -1; while ((p = strchr(rl_prompt, RL_PROMPT_END_IGNORE)) != NULL) *p = RL_PROMPT_START_IGNORE; return 0; } /* * initialize rl compat stuff */ int rl_initialize(void) { HistEvent ev; int editmode = 1; struct termios t; if (e != NULL) el_end(e); if (h != NULL) history_end(h); if (!rl_instream) rl_instream = stdin; if (!rl_outstream) rl_outstream = stdout; /* * See if we don't really want to run the editor */ if (tcgetattr(fileno(rl_instream), &t) != -1 && (t.c_lflag & ECHO) == 0) editmode = 0; e = el_init(rl_readline_name, rl_instream, rl_outstream, stderr); if (!editmode) el_set(e, EL_EDITMODE, 0); h = history_init(); if (!e || !h) return -1; history(h, &ev, H_SETSIZE, INT_MAX); /* unlimited */ history_length = 0; max_input_history = INT_MAX; el_set(e, EL_HIST, history, h); /* Setup resize function */ el_set(e, EL_RESIZE, _resize_fun, &rl_line_buffer); /* setup getc function if valid */ if (rl_getc_function) el_set(e, EL_GETCFN, _getc_function); /* for proper prompt printing in readline() */ if (rl_set_prompt("") == -1) { history_end(h); el_end(e); return -1; } el_set(e, EL_PROMPT, _get_prompt, RL_PROMPT_START_IGNORE); el_set(e, EL_SIGNAL, rl_catch_signals); /* set default mode to "emacs"-style and read setting afterwards */ /* so this can be overridden */ el_set(e, EL_EDITOR, "emacs"); if (rl_terminal_name != NULL) el_set(e, EL_TERMINAL, rl_terminal_name); else el_get(e, EL_TERMINAL, &rl_terminal_name); /* * Word completion - this has to go AFTER rebinding keys * to emacs-style. */ el_set(e, EL_ADDFN, "rl_complete", "ReadLine compatible completion function", _el_rl_complete); el_set(e, EL_BIND, "^I", "rl_complete", NULL); /* * Send TSTP when ^Z is pressed. */ el_set(e, EL_ADDFN, "rl_tstp", "ReadLine compatible suspend function", _el_rl_tstp); el_set(e, EL_BIND, "^Z", "rl_tstp", NULL); /* * Set some readline compatible key-bindings. */ el_set(e, EL_BIND, "^R", "em-inc-search-prev", NULL); /* * Allow the use of Home/End keys. */ el_set(e, EL_BIND, "\\e[1~", "ed-move-to-beg", NULL); el_set(e, EL_BIND, "\\e[4~", "ed-move-to-end", NULL); el_set(e, EL_BIND, "\\e[7~", "ed-move-to-beg", NULL); el_set(e, EL_BIND, "\\e[8~", "ed-move-to-end", NULL); el_set(e, EL_BIND, "\\e[H", "ed-move-to-beg", NULL); el_set(e, EL_BIND, "\\e[F", "ed-move-to-end", NULL); /* * Allow the use of the Delete/Insert keys. */ el_set(e, EL_BIND, "\\e[3~", "ed-delete-next-char", NULL); el_set(e, EL_BIND, "\\e[2~", "ed-quoted-insert", NULL); /* * Ctrl-left-arrow and Ctrl-right-arrow for word moving. */ el_set(e, EL_BIND, "\\e[1;5C", "em-next-word", NULL); el_set(e, EL_BIND, "\\e[1;5D", "ed-prev-word", NULL); el_set(e, EL_BIND, "\\e[5C", "em-next-word", NULL); el_set(e, EL_BIND, "\\e[5D", "ed-prev-word", NULL); el_set(e, EL_BIND, "\\e\\e[C", "em-next-word", NULL); el_set(e, EL_BIND, "\\e\\e[D", "ed-prev-word", NULL); /* read settings from configuration file */ el_source(e, NULL); /* * Unfortunately, some applications really do use rl_point * and rl_line_buffer directly. */ _resize_fun(e, &rl_line_buffer); _rl_update_pos(); if (rl_startup_hook) (*rl_startup_hook)(NULL, 0); return 0; } /* * read one line from input stream and return it, chomping * trailing newline (if there is any) */ char * readline(const char *p) { HistEvent ev; const char * volatile prompt = p; int count; const char *ret; char *buf; static int used_event_hook; if (e == NULL || h == NULL) rl_initialize(); rl_done = 0; (void)setjmp(topbuf); /* update prompt accordingly to what has been passed */ if (rl_set_prompt(prompt) == -1) return NULL; if (rl_pre_input_hook) (*rl_pre_input_hook)(NULL, 0); if (rl_event_hook && !(e->el_flags&NO_TTY)) { el_set(e, EL_GETCFN, _rl_event_read_char); used_event_hook = 1; } if (!rl_event_hook && used_event_hook) { el_set(e, EL_GETCFN, EL_BUILTIN_GETCFN); used_event_hook = 0; } rl_already_prompted = 0; /* get one line from input stream */ ret = el_gets(e, &count); if (ret && count > 0) { int lastidx; buf = strdup(ret); if (buf == NULL) return NULL; lastidx = count - 1; if (buf[lastidx] == '\n') buf[lastidx] = '\0'; } else buf = NULL; history(h, &ev, H_GETSIZE); history_length = ev.num; return buf; } /* * history functions */ /* * is normally called before application starts to use * history expansion functions */ void using_history(void) { if (h == NULL || e == NULL) rl_initialize(); history_offset = history_length; } /* * substitute ``what'' with ``with'', returning resulting string; if * globally == 1, substitutes all occurrences of what, otherwise only the * first one */ static char * _rl_compat_sub(const char *str, const char *what, const char *with, int globally) { const char *s; char *r, *result; size_t len, with_len, what_len; len = strlen(str); with_len = strlen(with); what_len = strlen(what); /* calculate length we need for result */ s = str; while (*s) { if (*s == *what && !strncmp(s, what, what_len)) { len += with_len - what_len; if (!globally) break; s += what_len; } else s++; } r = result = el_malloc((len + 1) * sizeof(*r)); if (result == NULL) return NULL; s = str; while (*s) { if (*s == *what && !strncmp(s, what, what_len)) { (void)strncpy(r, with, with_len); r += with_len; s += what_len; if (!globally) { (void)strcpy(r, s); return result; } } else *r++ = *s++; } *r = '\0'; return result; } static char *last_search_pat; /* last !?pat[?] search pattern */ static char *last_search_match; /* last !?pat[?] that matched */ const char * get_history_event(const char *cmd, int *cindex, int qchar) { int idx, sign, sub, num, begin, ret; size_t len; char *pat; const char *rptr; HistEvent ev; idx = *cindex; if (cmd[idx++] != history_expansion_char) return NULL; /* find out which event to take */ if (cmd[idx] == history_expansion_char || cmd[idx] == '\0') { if (history(h, &ev, H_FIRST) != 0) return NULL; *cindex = cmd[idx]? (idx + 1):idx; return ev.str; } sign = 0; if (cmd[idx] == '-') { sign = 1; idx++; } if ('0' <= cmd[idx] && cmd[idx] <= '9') { HIST_ENTRY *he; num = 0; while (cmd[idx] && '0' <= cmd[idx] && cmd[idx] <= '9') { num = num * 10 + cmd[idx] - '0'; idx++; } if (sign) num = history_length - num + 1; if (!(he = history_get(num))) return NULL; *cindex = idx; return he->line; } sub = 0; if (cmd[idx] == '?') { sub = 1; idx++; } begin = idx; while (cmd[idx]) { if (cmd[idx] == '\n') break; if (sub && cmd[idx] == '?') break; if (!sub && (cmd[idx] == ':' || cmd[idx] == ' ' || cmd[idx] == '\t' || cmd[idx] == qchar)) break; idx++; } len = (size_t)idx - (size_t)begin; if (sub && cmd[idx] == '?') idx++; if (sub && len == 0 && last_search_pat && *last_search_pat) pat = last_search_pat; else if (len == 0) return NULL; else { if ((pat = el_malloc((len + 1) * sizeof(*pat))) == NULL) return NULL; (void)strncpy(pat, cmd + begin, len); pat[len] = '\0'; } if (history(h, &ev, H_CURR) != 0) { if (pat != last_search_pat) el_free(pat); return NULL; } num = ev.num; if (sub) { if (pat != last_search_pat) { if (last_search_pat) el_free(last_search_pat); last_search_pat = pat; } ret = history_search(pat, -1); } else ret = history_search_prefix(pat, -1); if (ret == -1) { /* restore to end of list on failed search */ history(h, &ev, H_FIRST); (void)fprintf(rl_outstream, "%s: Event not found\n", pat); if (pat != last_search_pat) el_free(pat); return NULL; } if (sub && len) { if (last_search_match && last_search_match != pat) el_free(last_search_match); last_search_match = pat; } if (pat != last_search_pat) el_free(pat); if (history(h, &ev, H_CURR) != 0) return NULL; *cindex = idx; rptr = ev.str; /* roll back to original position */ (void)history(h, &ev, H_SET, num); return rptr; } /* * the real function doing history expansion - takes as argument command * to do and data upon which the command should be executed * does expansion the way I've understood readline documentation * * returns 0 if data was not modified, 1 if it was and 2 if the string * should be only printed and not executed; in case of error, * returns -1 and *result points to NULL * it's the caller's responsibility to free() the string returned in *result */ static int _history_expand_command(const char *command, size_t offs, size_t cmdlen, char **result) { char *tmp, *search = NULL, *aptr; const char *ptr, *cmd; static char *from = NULL, *to = NULL; int start, end, idx, has_mods = 0; int p_on = 0, g_on = 0; *result = NULL; aptr = NULL; ptr = NULL; /* First get event specifier */ idx = 0; if (strchr(":^*$", command[offs + 1])) { char str[4]; /* * "!:" is shorthand for "!!:". * "!^", "!*" and "!$" are shorthand for * "!!:^", "!!:*" and "!!:$" respectively. */ str[0] = str[1] = '!'; str[2] = '0'; ptr = get_history_event(str, &idx, 0); idx = (command[offs + 1] == ':')? 1:0; has_mods = 1; } else { if (command[offs + 1] == '#') { /* use command so far */ if ((aptr = el_malloc((offs + 1) * sizeof(*aptr))) == NULL) return -1; (void)strncpy(aptr, command, offs); aptr[offs] = '\0'; idx = 1; } else { int qchar; qchar = (offs > 0 && command[offs - 1] == '"')? '"':0; ptr = get_history_event(command + offs, &idx, qchar); } has_mods = command[offs + (size_t)idx] == ':'; } if (ptr == NULL && aptr == NULL) return -1; if (!has_mods) { *result = strdup(aptr ? aptr : ptr); if (aptr) el_free(aptr); if (*result == NULL) return -1; return 1; } cmd = command + offs + idx + 1; /* Now parse any word designators */ if (*cmd == '%') /* last word matched by ?pat? */ tmp = strdup(last_search_match? last_search_match:""); else if (strchr("^*$-0123456789", *cmd)) { start = end = -1; if (*cmd == '^') start = end = 1, cmd++; else if (*cmd == '$') start = -1, cmd++; else if (*cmd == '*') start = 1, cmd++; else if (*cmd == '-' || isdigit((unsigned char) *cmd)) { start = 0; while (*cmd && '0' <= *cmd && *cmd <= '9') start = start * 10 + *cmd++ - '0'; if (*cmd == '-') { if (isdigit((unsigned char) cmd[1])) { cmd++; end = 0; while (*cmd && '0' <= *cmd && *cmd <= '9') end = end * 10 + *cmd++ - '0'; } else if (cmd[1] == '$') { cmd += 2; end = -1; } else { cmd++; end = -2; } } else if (*cmd == '*') end = -1, cmd++; else end = start; } tmp = history_arg_extract(start, end, aptr? aptr:ptr); if (tmp == NULL) { (void)fprintf(rl_outstream, "%s: Bad word specifier", command + offs + idx); if (aptr) el_free(aptr); return -1; } } else tmp = strdup(aptr? aptr:ptr); if (aptr) el_free(aptr); if (*cmd == '\0' || ((size_t)(cmd - (command + offs)) >= cmdlen)) { *result = tmp; return 1; } for (; *cmd; cmd++) { if (*cmd == ':') continue; else if (*cmd == 'h') { /* remove trailing path */ if ((aptr = strrchr(tmp, '/')) != NULL) *aptr = '\0'; } else if (*cmd == 't') { /* remove leading path */ if ((aptr = strrchr(tmp, '/')) != NULL) { aptr = strdup(aptr + 1); el_free(tmp); tmp = aptr; } } else if (*cmd == 'r') { /* remove trailing suffix */ if ((aptr = strrchr(tmp, '.')) != NULL) *aptr = '\0'; } else if (*cmd == 'e') { /* remove all but suffix */ if ((aptr = strrchr(tmp, '.')) != NULL) { aptr = strdup(aptr); el_free(tmp); tmp = aptr; } } else if (*cmd == 'p') /* print only */ p_on = 1; else if (*cmd == 'g') g_on = 2; else if (*cmd == 's' || *cmd == '&') { char *what, *with, delim; size_t len, from_len; size_t size; if (*cmd == '&' && (from == NULL || to == NULL)) continue; else if (*cmd == 's') { delim = *(++cmd), cmd++; size = 16; what = el_realloc(from, size * sizeof(*what)); if (what == NULL) { el_free(from); el_free(tmp); return 0; } len = 0; for (; *cmd && *cmd != delim; cmd++) { if (*cmd == '\\' && cmd[1] == delim) cmd++; if (len >= size) { char *nwhat; nwhat = el_realloc(what, (size <<= 1) * sizeof(*nwhat)); if (nwhat == NULL) { el_free(what); el_free(tmp); return 0; } what = nwhat; } what[len++] = *cmd; } what[len] = '\0'; from = what; if (*what == '\0') { el_free(what); if (search) { from = strdup(search); if (from == NULL) { el_free(tmp); return 0; } } else { from = NULL; el_free(tmp); return -1; } } cmd++; /* shift after delim */ if (!*cmd) continue; size = 16; with = el_realloc(to, size * sizeof(*with)); if (with == NULL) { el_free(to); el_free(tmp); return -1; } len = 0; from_len = strlen(from); for (; *cmd && *cmd != delim; cmd++) { if (len + from_len + 1 >= size) { char *nwith; size += from_len + 1; nwith = el_realloc(with, size * sizeof(*nwith)); if (nwith == NULL) { el_free(with); el_free(tmp); return -1; } with = nwith; } if (*cmd == '&') { /* safe */ (void)strcpy(&with[len], from); len += from_len; continue; } if (*cmd == '\\' && (*(cmd + 1) == delim || *(cmd + 1) == '&')) cmd++; with[len++] = *cmd; } with[len] = '\0'; to = with; } aptr = _rl_compat_sub(tmp, from, to, g_on); if (aptr) { el_free(tmp); tmp = aptr; } g_on = 0; } } *result = tmp; return p_on? 2:1; } /* * csh-style history expansion */ int history_expand(char *str, char **output) { int ret = 0; size_t idx, i, size; char *tmp, *result; if (h == NULL || e == NULL) rl_initialize(); if (history_expansion_char == 0) { *output = strdup(str); return 0; } *output = NULL; if (str[0] == history_subst_char) { /* ^foo^foo2^ is equivalent to !!:s^foo^foo2^ */ *output = el_malloc((strlen(str) + 4 + 1) * sizeof(**output)); if (*output == NULL) return 0; (*output)[0] = (*output)[1] = history_expansion_char; (*output)[2] = ':'; (*output)[3] = 's'; (void)strcpy((*output) + 4, str); str = *output; } else { *output = strdup(str); if (*output == NULL) return 0; } #define ADD_STRING(what, len, fr) \ { \ if (idx + len + 1 > size) { \ char *nresult = el_realloc(result, \ (size += len + 1) * sizeof(*nresult)); \ if (nresult == NULL) { \ el_free(*output); \ if (/*CONSTCOND*/fr) \ el_free(tmp); \ return 0; \ } \ result = nresult; \ } \ (void)strncpy(&result[idx], what, len); \ idx += len; \ result[idx] = '\0'; \ } result = NULL; size = idx = 0; tmp = NULL; for (i = 0; str[i];) { int qchar, loop_again; size_t len, start, j; qchar = 0; loop_again = 1; start = j = i; loop: for (; str[j]; j++) { if (str[j] == '\\' && str[j + 1] == history_expansion_char) { len = strlen(&str[j + 1]) + 1; memmove(&str[j], &str[j + 1], len); continue; } if (!loop_again) { if (isspace((unsigned char) str[j]) || str[j] == qchar) break; } if (str[j] == history_expansion_char && !strchr(history_no_expand_chars, str[j + 1]) && (!history_inhibit_expansion_function || (*history_inhibit_expansion_function)(str, (int)j) == 0)) break; } if (str[j] && loop_again) { i = j; qchar = (j > 0 && str[j - 1] == '"' )? '"':0; j++; if (str[j] == history_expansion_char) j++; loop_again = 0; goto loop; } len = i - start; ADD_STRING(&str[start], len, 0); if (str[i] == '\0' || str[i] != history_expansion_char) { len = j - i; ADD_STRING(&str[i], len, 0); if (start == 0) ret = 0; else ret = 1; break; } ret = _history_expand_command (str, i, (j - i), &tmp); if (ret > 0 && tmp) { len = strlen(tmp); ADD_STRING(tmp, len, 1); } if (tmp) { el_free(tmp); tmp = NULL; } i = j; } /* ret is 2 for "print only" option */ if (ret == 2) { add_history(result); #ifdef GDB_411_HACK /* gdb 4.11 has been shipped with readline, where */ /* history_expand() returned -1 when the line */ /* should not be executed; in readline 2.1+ */ /* it should return 2 in such a case */ ret = -1; #endif } el_free(*output); *output = result; return ret; } /* * Return a string consisting of arguments of "str" from "start" to "end". */ char * history_arg_extract(int start, int end, const char *str) { size_t i, len, max; char **arr, *result = NULL; arr = history_tokenize(str); if (!arr) return NULL; if (arr && *arr == NULL) goto out; for (max = 0; arr[max]; max++) continue; max--; if (start == '$') start = (int)max; if (end == '$') end = (int)max; if (end < 0) end = (int)max + end + 1; if (start < 0) start = end; if (start < 0 || end < 0 || (size_t)start > max || (size_t)end > max || start > end) goto out; for (i = (size_t)start, len = 0; i <= (size_t)end; i++) len += strlen(arr[i]) + 1; len++; result = el_malloc(len * sizeof(*result)); if (result == NULL) goto out; for (i = (size_t)start, len = 0; i <= (size_t)end; i++) { (void)strcpy(result + len, arr[i]); len += strlen(arr[i]); if (i < (size_t)end) result[len++] = ' '; } result[len] = '\0'; out: for (i = 0; arr[i]; i++) el_free(arr[i]); el_free(arr); return result; } /* * Parse the string into individual tokens, * similar to how shell would do it. */ char ** history_tokenize(const char *str) { int size = 1, idx = 0, i, start; size_t len; char **result = NULL, *temp, delim = '\0'; for (i = 0; str[i];) { while (isspace((unsigned char) str[i])) i++; start = i; for (; str[i];) { if (str[i] == '\\') { if (str[i+1] != '\0') i++; } else if (str[i] == delim) delim = '\0'; else if (!delim && (isspace((unsigned char) str[i]) || strchr("()<>;&|$", str[i]))) break; else if (!delim && strchr("'`\"", str[i])) delim = str[i]; if (str[i]) i++; } if (idx + 2 >= size) { char **nresult; size <<= 1; nresult = el_realloc(result, (size_t)size * sizeof(*nresult)); if (nresult == NULL) { el_free(result); return NULL; } result = nresult; } len = (size_t)i - (size_t)start; temp = el_malloc((size_t)(len + 1) * sizeof(*temp)); if (temp == NULL) { for (i = 0; i < idx; i++) el_free(result[i]); el_free(result); return NULL; } (void)strncpy(temp, &str[start], len); temp[len] = '\0'; result[idx++] = temp; result[idx] = NULL; if (str[i]) i++; } return result; } /* * limit size of history record to ``max'' events */ void stifle_history(int max) { HistEvent ev; HIST_ENTRY *he; if (h == NULL || e == NULL) rl_initialize(); if (history(h, &ev, H_SETSIZE, max) == 0) { max_input_history = max; if (history_length > max) history_base = history_length - max; while (history_length > max) { he = remove_history(0); el_free(he->data); el_free((void *)(unsigned long)he->line); el_free(he); } } } /* * "unlimit" size of history - set the limit to maximum allowed int value */ int unstifle_history(void) { HistEvent ev; int omax; history(h, &ev, H_SETSIZE, INT_MAX); omax = max_input_history; max_input_history = INT_MAX; return omax; /* some value _must_ be returned */ } int history_is_stifled(void) { /* cannot return true answer */ return max_input_history != INT_MAX; } static const char _history_tmp_template[] = "/tmp/.historyXXXXXX"; int history_truncate_file (const char *filename, int nlines) { int ret = 0; FILE *fp, *tp; char template[sizeof(_history_tmp_template)]; char buf[4096]; int fd; char *cp; off_t off; int count = 0; ssize_t left = 0; if (filename == NULL && (filename = _default_history_file()) == NULL) return errno; if ((fp = fopen(filename, "r+")) == NULL) return errno; strcpy(template, _history_tmp_template); if ((fd = mkstemp(template)) == -1) { ret = errno; goto out1; } if ((tp = fdopen(fd, "r+")) == NULL) { close(fd); ret = errno; goto out2; } for(;;) { if (fread(buf, sizeof(buf), (size_t)1, fp) != 1) { if (ferror(fp)) { ret = errno; break; } if (fseeko(fp, (off_t)sizeof(buf) * count, SEEK_SET) == (off_t)-1) { ret = errno; break; } left = (ssize_t)fread(buf, (size_t)1, sizeof(buf), fp); if (ferror(fp)) { ret = errno; break; } if (left == 0) { count--; left = sizeof(buf); } else if (fwrite(buf, (size_t)left, (size_t)1, tp) != 1) { ret = errno; break; } fflush(tp); break; } if (fwrite(buf, sizeof(buf), (size_t)1, tp) != 1) { ret = errno; break; } count++; } if (ret) goto out3; cp = buf + left - 1; if(*cp != '\n') cp++; for(;;) { while (--cp >= buf) { if (*cp == '\n') { if (--nlines == 0) { if (++cp >= buf + sizeof(buf)) { count++; cp = buf; } break; } } } if (nlines <= 0 || count == 0) break; count--; if (fseeko(tp, (off_t)sizeof(buf) * count, SEEK_SET) < 0) { ret = errno; break; } if (fread(buf, sizeof(buf), (size_t)1, tp) != 1) { if (ferror(tp)) { ret = errno; break; } ret = EAGAIN; break; } cp = buf + sizeof(buf); } if (ret || nlines > 0) goto out3; if (fseeko(fp, (off_t)0, SEEK_SET) == (off_t)-1) { ret = errno; goto out3; } if (fseeko(tp, (off_t)sizeof(buf) * count + (cp - buf), SEEK_SET) == (off_t)-1) { ret = errno; goto out3; } for(;;) { if ((left = (ssize_t)fread(buf, (size_t)1, sizeof(buf), tp)) == 0) { if (ferror(fp)) ret = errno; break; } if (fwrite(buf, (size_t)left, (size_t)1, fp) != 1) { ret = errno; break; } } fflush(fp); if((off = ftello(fp)) > 0) (void)ftruncate(fileno(fp), off); out3: fclose(tp); out2: unlink(template); out1: fclose(fp); return ret; } /* * read history from a file given */ int read_history(const char *filename) { HistEvent ev; if (h == NULL || e == NULL) rl_initialize(); if (filename == NULL && (filename = _default_history_file()) == NULL) return errno; return history(h, &ev, H_LOAD, filename) == -1 ? (errno ? errno : EINVAL) : 0; } /* * write history to a file given */ int write_history(const char *filename) { HistEvent ev; if (h == NULL || e == NULL) rl_initialize(); if (filename == NULL && (filename = _default_history_file()) == NULL) return errno; return history(h, &ev, H_SAVE, filename) == -1 ? (errno ? errno : EINVAL) : 0; } /* * returns history ``num''th event * * returned pointer points to static variable */ HIST_ENTRY * history_get(int num) { static HIST_ENTRY she; HistEvent ev; int curr_num; if (h == NULL || e == NULL) rl_initialize(); if (num < history_base) return NULL; /* save current position */ if (history(h, &ev, H_CURR) != 0) return NULL; curr_num = ev.num; /* * use H_DELDATA to set to nth history (without delete) by passing * (void **)-1 -- as in history_set_pos */ if (history(h, &ev, H_DELDATA, num - history_base, (void **)-1) != 0) goto out; /* get current entry */ if (history(h, &ev, H_CURR) != 0) goto out; if (history(h, &ev, H_NEXT_EVDATA, ev.num, &she.data) != 0) goto out; she.line = ev.str; /* restore pointer to where it was */ (void)history(h, &ev, H_SET, curr_num); return &she; out: /* restore pointer to where it was */ (void)history(h, &ev, H_SET, curr_num); return NULL; } /* * add the line to history table */ int add_history(const char *line) { HistEvent ev; if (h == NULL || e == NULL) rl_initialize(); if (history(h, &ev, H_ENTER, line) == -1) return 0; (void)history(h, &ev, H_GETSIZE); if (ev.num == history_length) history_base++; else history_length = ev.num; return 0; } /* * remove the specified entry from the history list and return it. */ HIST_ENTRY * remove_history(int num) { HIST_ENTRY *he; HistEvent ev; if (h == NULL || e == NULL) rl_initialize(); if ((he = el_malloc(sizeof(*he))) == NULL) return NULL; if (history(h, &ev, H_DELDATA, num, &he->data) != 0) { el_free(he); return NULL; } he->line = ev.str; if (history(h, &ev, H_GETSIZE) == 0) history_length = ev.num; return he; } /* * replace the line and data of the num-th entry */ HIST_ENTRY * replace_history_entry(int num, const char *line, histdata_t data) { HIST_ENTRY *he; HistEvent ev; int curr_num; if (h == NULL || e == NULL) rl_initialize(); /* save current position */ if (history(h, &ev, H_CURR) != 0) return NULL; curr_num = ev.num; /* start from the oldest */ if (history(h, &ev, H_LAST) != 0) return NULL; /* error */ if ((he = el_malloc(sizeof(*he))) == NULL) return NULL; /* look forwards for event matching specified offset */ if (history(h, &ev, H_NEXT_EVDATA, num, &he->data)) goto out; he->line = strdup(ev.str); if (he->line == NULL) goto out; if (history(h, &ev, H_REPLACE, line, data)) goto out; /* restore pointer to where it was */ if (history(h, &ev, H_SET, curr_num)) goto out; return he; out: el_free(he); return NULL; } /* * clear the history list - delete all entries */ void clear_history(void) { HistEvent ev; if (h == NULL || e == NULL) rl_initialize(); (void)history(h, &ev, H_CLEAR); history_offset = history_length = 0; } /* * returns offset of the current history event */ int where_history(void) { return history_offset; } static HIST_ENTRY **_history_listp; static HIST_ENTRY *_history_list; HIST_ENTRY ** history_list(void) { HistEvent ev; HIST_ENTRY **nlp, *nl; int i; if (history(h, &ev, H_LAST) != 0) return NULL; if ((nlp = el_realloc(_history_listp, (size_t)history_length * sizeof(*nlp))) == NULL) return NULL; _history_listp = nlp; if ((nl = el_realloc(_history_list, (size_t)history_length * sizeof(*nl))) == NULL) return NULL; _history_list = nl; i = 0; do { _history_listp[i] = &_history_list[i]; _history_list[i].line = ev.str; _history_list[i].data = NULL; if (i++ == history_length) abort(); } while (history(h, &ev, H_PREV) == 0); return _history_listp; } /* * returns current history event or NULL if there is no such event */ HIST_ENTRY * current_history(void) { HistEvent ev; if (history(h, &ev, H_PREV_EVENT, history_offset + 1) != 0) return NULL; rl_he.line = ev.str; rl_he.data = NULL; return &rl_he; } /* * returns total number of bytes history events' data are using */ int history_total_bytes(void) { HistEvent ev; int curr_num; size_t size; if (history(h, &ev, H_CURR) != 0) return -1; curr_num = ev.num; (void)history(h, &ev, H_FIRST); size = 0; do size += strlen(ev.str) * sizeof(*ev.str); while (history(h, &ev, H_NEXT) == 0); /* get to the same position as before */ history(h, &ev, H_PREV_EVENT, curr_num); return (int)size; } /* * sets the position in the history list to ``pos'' */ int history_set_pos(int pos) { if (pos >= history_length || pos < 0) return 0; history_offset = pos; return 1; } /* * returns previous event in history and shifts pointer accordingly * Note that readline and editline define directions in opposite ways. */ HIST_ENTRY * previous_history(void) { HistEvent ev; if (history_offset == 0) return NULL; if (history(h, &ev, H_LAST) != 0) return NULL; history_offset--; return current_history(); } /* * returns next event in history and shifts pointer accordingly */ HIST_ENTRY * next_history(void) { HistEvent ev; if (history_offset >= history_length) return NULL; if (history(h, &ev, H_LAST) != 0) return NULL; history_offset++; return current_history(); } /* * searches for first history event containing the str */ int history_search(const char *str, int direction) { HistEvent ev; const char *strp; int curr_num; if (history(h, &ev, H_CURR) != 0) return -1; curr_num = ev.num; for (;;) { if ((strp = strstr(ev.str, str)) != NULL) return (int)(strp - ev.str); if (history(h, &ev, direction < 0 ? H_NEXT:H_PREV) != 0) break; } (void)history(h, &ev, H_SET, curr_num); return -1; } /* * searches for first history event beginning with str */ int history_search_prefix(const char *str, int direction) { HistEvent ev; return (history(h, &ev, direction < 0 ? H_PREV_STR : H_NEXT_STR, str)); } /* * search for event in history containing str, starting at offset * abs(pos); continue backward, if pos<0, forward otherwise */ /* ARGSUSED */ int history_search_pos(const char *str, int direction __attribute__((__unused__)), int pos) { HistEvent ev; int curr_num, off; off = (pos > 0) ? pos : -pos; pos = (pos > 0) ? 1 : -1; if (history(h, &ev, H_CURR) != 0) return -1; curr_num = ev.num; if (!history_set_pos(off) || history(h, &ev, H_CURR) != 0) return -1; for (;;) { if (strstr(ev.str, str)) return off; if (history(h, &ev, (pos < 0) ? H_PREV : H_NEXT) != 0) break; } /* set "current" pointer back to previous state */ (void)history(h, &ev, pos < 0 ? H_NEXT_EVENT : H_PREV_EVENT, curr_num); return -1; } /********************************/ /* completion functions */ char * tilde_expand(char *name) { return fn_tilde_expand(name); } char * filename_completion_function(const char *name, int state) { return fn_filename_completion_function(name, state); } /* * a completion generator for usernames; returns _first_ username * which starts with supplied text * text contains a partial username preceded by random character * (usually '~'); state resets search from start (??? should we do that anyway) * it's the caller's responsibility to free the returned value */ char * username_completion_function(const char *text, int state) { #if defined(HAVE_GETPW_R_POSIX) || defined(HAVE_GETPW_R_DRAFT) struct passwd pwres; char pwbuf[1024]; #endif struct passwd *pass = NULL; if (text[0] == '\0') return NULL; if (*text == '~') text++; if (state == 0) setpwent(); while ( (pass = getpwent()) != NULL && text[0] == pass->pw_name[0] && strcmp(text, pass->pw_name) == 0) continue; if (pass == NULL) { endpwent(); return NULL; } return strdup(pass->pw_name); } /* * el-compatible wrapper to send TSTP on ^Z */ /* ARGSUSED */ static unsigned char _el_rl_tstp(EditLine *el __attribute__((__unused__)), int ch __attribute__((__unused__))) { (void)kill(0, SIGTSTP); return CC_NORM; } /* * Display list of strings in columnar format on readline's output stream. * 'matches' is list of strings, 'len' is number of strings in 'matches', * 'max' is maximum length of string in 'matches'. */ void rl_display_match_list(char **matches, int len, int max) { fn_display_match_list(e, matches, (size_t)len, (size_t)max); } static const char * /*ARGSUSED*/ _rl_completion_append_character_function(const char *dummy __attribute__((__unused__))) { static char buf[2]; buf[0] = (char)rl_completion_append_character; buf[1] = '\0'; return buf; } /* * complete word at current point */ /* ARGSUSED */ int rl_complete(int ignore __attribute__((__unused__)), int invoking_key) { static ct_buffer_t wbreak_conv, sprefix_conv; char *breakchars; if (h == NULL || e == NULL) rl_initialize(); if (rl_inhibit_completion) { char arr[2]; arr[0] = (char)invoking_key; arr[1] = '\0'; el_insertstr(e, arr); return CC_REFRESH; } if (rl_completion_word_break_hook != NULL) breakchars = (*rl_completion_word_break_hook)(); else breakchars = rl_basic_word_break_characters; _rl_update_pos(); /* Just look at how many global variables modify this operation! */ return fn_complete(e, (rl_compentry_func_t *)rl_completion_entry_function, rl_attempted_completion_function, ct_decode_string(rl_basic_word_break_characters, &wbreak_conv), ct_decode_string(breakchars, &sprefix_conv), _rl_completion_append_character_function, (size_t)rl_completion_query_items, &rl_completion_type, &rl_attempted_completion_over, &rl_point, &rl_end); } /* ARGSUSED */ static unsigned char _el_rl_complete(EditLine *el __attribute__((__unused__)), int ch) { return (unsigned char)rl_complete(0, ch); } /* * misc other functions */ /* * bind key c to readline-type function func */ int rl_bind_key(int c, rl_command_func_t *func) { int retval = -1; if (h == NULL || e == NULL) rl_initialize(); if (func == rl_insert) { /* XXX notice there is no range checking of ``c'' */ e->el_map.key[c] = ED_INSERT; retval = 0; } return retval; } /* * read one key from input - handles chars pushed back * to input stream also */ int rl_read_key(void) { char fooarr[2 * sizeof(int)]; if (e == NULL || h == NULL) rl_initialize(); return el_getc(e, fooarr); } /* * reset the terminal */ /* ARGSUSED */ void rl_reset_terminal(const char *p __attribute__((__unused__))) { if (h == NULL || e == NULL) rl_initialize(); el_reset(e); } /* * insert character ``c'' back into input stream, ``count'' times */ int rl_insert(int count, int c) { char arr[2]; if (h == NULL || e == NULL) rl_initialize(); /* XXX - int -> char conversion can lose on multichars */ arr[0] = (char)c; arr[1] = '\0'; for (; count > 0; count--) el_push(e, arr); return 0; } int rl_insert_text(const char *text) { if (!text || *text == 0) return 0; if (h == NULL || e == NULL) rl_initialize(); if (el_insertstr(e, text) < 0) return 0; return (int)strlen(text); } /*ARGSUSED*/ int rl_newline(int count __attribute__((__unused__)), int c __attribute__((__unused__))) { /* * Readline-4.0 appears to ignore the args. */ return rl_insert(1, '\n'); } /*ARGSUSED*/ static unsigned char rl_bind_wrapper(EditLine *el __attribute__((__unused__)), unsigned char c) { if (map[c] == NULL) return CC_ERROR; _rl_update_pos(); (*map[c])(1, c); /* If rl_done was set by the above call, deal with it here */ if (rl_done) return CC_EOF; return CC_NORM; } int rl_add_defun(const char *name, rl_command_func_t *fun, int c) { char dest[8]; if ((size_t)c >= sizeof(map) / sizeof(map[0]) || c < 0) return -1; map[(unsigned char)c] = fun; el_set(e, EL_ADDFN, name, name, rl_bind_wrapper); vis(dest, c, VIS_WHITE|VIS_NOSLASH, 0); el_set(e, EL_BIND, dest, name, NULL); return 0; } void rl_callback_read_char(void) { int count = 0, done = 0; const char *buf = el_gets(e, &count); char *wbuf; if (buf == NULL || count-- <= 0) return; if (count == 0 && buf[0] == e->el_tty.t_c[TS_IO][C_EOF]) done = 1; if (buf[count] == '\n' || buf[count] == '\r') done = 2; if (done && rl_linefunc != NULL) { el_set(e, EL_UNBUFFERED, 0); if (done == 2) { if ((wbuf = strdup(buf)) != NULL) wbuf[count] = '\0'; } else wbuf = NULL; (*(void (*)(const char *))rl_linefunc)(wbuf); el_set(e, EL_UNBUFFERED, 1); } } void rl_callback_handler_install(const char *prompt, rl_vcpfunc_t *linefunc) { if (e == NULL) { rl_initialize(); } (void)rl_set_prompt(prompt); rl_linefunc = linefunc; el_set(e, EL_UNBUFFERED, 1); } void rl_callback_handler_remove(void) { el_set(e, EL_UNBUFFERED, 0); rl_linefunc = NULL; } void rl_redisplay(void) { char a[2]; a[0] = (char)e->el_tty.t_c[TS_IO][C_REPRINT]; a[1] = '\0'; el_push(e, a); } int rl_get_previous_history(int count, int key) { char a[2]; a[0] = (char)key; a[1] = '\0'; while (count--) el_push(e, a); return 0; } void /*ARGSUSED*/ rl_prep_terminal(int meta_flag __attribute__((__unused__))) { el_set(e, EL_PREP_TERM, 1); } void rl_deprep_terminal(void) { el_set(e, EL_PREP_TERM, 0); } int rl_read_init_file(const char *s) { return el_source(e, s); } int rl_parse_and_bind(const char *line) { const char **argv; int argc; Tokenizer *tok; tok = tok_init(NULL); tok_str(tok, line, &argc, &argv); argc = el_parse(e, argc, argv); tok_end(tok); return argc ? 1 : 0; } int rl_variable_bind(const char *var, const char *value) { /* * The proper return value is undocument, but this is what the * readline source seems to do. */ return el_set(e, EL_BIND, "", var, value, NULL) == -1 ? 1 : 0; } void rl_stuff_char(int c) { char buf[2]; buf[0] = (char)c; buf[1] = '\0'; el_insertstr(e, buf); } static int _rl_event_read_char(EditLine *el, wchar_t *wc) { char ch; int n; ssize_t num_read = 0; ch = '\0'; *wc = L'\0'; while (rl_event_hook) { (*rl_event_hook)(); #if defined(FIONREAD) if (ioctl(el->el_infd, FIONREAD, &n) < 0) return -1; if (n) num_read = read(el->el_infd, &ch, (size_t)1); else num_read = 0; #elif defined(F_SETFL) && defined(O_NDELAY) if ((n = fcntl(el->el_infd, F_GETFL, 0)) < 0) return -1; if (fcntl(el->el_infd, F_SETFL, n|O_NDELAY) < 0) return -1; num_read = read(el->el_infd, &ch, 1); if (fcntl(el->el_infd, F_SETFL, n)) return -1; #else /* not non-blocking, but what you gonna do? */ num_read = read(el->el_infd, &ch, 1); return -1; #endif if (num_read < 0 && errno == EAGAIN) continue; if (num_read == 0) continue; break; } if (!rl_event_hook) el_set(el, EL_GETCFN, EL_BUILTIN_GETCFN); *wc = (wchar_t)ch; return (int)num_read; } static void _rl_update_pos(void) { const LineInfo *li = el_line(e); rl_point = (int)(li->cursor - li->buffer); rl_end = (int)(li->lastchar - li->buffer); } void rl_get_screen_size(int *rows, int *cols) { if (rows) el_get(e, EL_GETTC, "li", rows, (void *)0); if (cols) el_get(e, EL_GETTC, "co", cols, (void *)0); } void rl_set_screen_size(int rows, int cols) { char buf[64]; (void)snprintf(buf, sizeof(buf), "%d", rows); el_set(e, EL_SETTC, "li", buf, NULL); (void)snprintf(buf, sizeof(buf), "%d", cols); el_set(e, EL_SETTC, "co", buf, NULL); } char ** rl_completion_matches(const char *str, rl_compentry_func_t *fun) { size_t len, max, i, j, min; char **list, *match, *a, *b; len = 1; max = 10; if ((list = el_malloc(max * sizeof(*list))) == NULL) return NULL; while ((match = (*fun)(str, (int)(len - 1))) != NULL) { list[len++] = match; if (len == max) { char **nl; max += 10; if ((nl = el_realloc(list, max * sizeof(*nl))) == NULL) goto out; list = nl; } } if (len == 1) goto out; list[len] = NULL; if (len == 2) { if ((list[0] = strdup(list[1])) == NULL) goto out; return list; } qsort(&list[1], len - 1, sizeof(*list), (int (*)(const void *, const void *)) strcmp); min = SIZE_MAX; for (i = 1, a = list[i]; i < len - 1; i++, a = b) { b = list[i + 1]; for (j = 0; a[j] && a[j] == b[j]; j++) continue; if (min > j) min = j; } if (min == 0 && *str) { if ((list[0] = strdup(str)) == NULL) goto out; } else { if ((list[0] = el_malloc((min + 1) * sizeof(*list[0]))) == NULL) goto out; (void)memcpy(list[0], list[1], min); list[0][min] = '\0'; } return list; out: el_free(list); return NULL; } char * rl_filename_completion_function (const char *text, int state) { return fn_filename_completion_function(text, state); } void rl_forced_update_display(void) { el_set(e, EL_REFRESH); } int _rl_abort_internal(void) { el_beep(e); longjmp(topbuf, 1); /*NOTREACHED*/ } int _rl_qsort_string_compare(char **s1, char **s2) { return strcoll(*s1, *s2); } HISTORY_STATE * history_get_history_state(void) { HISTORY_STATE *hs; if ((hs = el_malloc(sizeof(*hs))) == NULL) return NULL; hs->length = history_length; return hs; } int /*ARGSUSED*/ rl_kill_text(int from __attribute__((__unused__)), int to __attribute__((__unused__))) { return 0; } Keymap rl_make_bare_keymap(void) { return NULL; } Keymap rl_get_keymap(void) { return NULL; } void /*ARGSUSED*/ rl_set_keymap(Keymap k __attribute__((__unused__))) { } int /*ARGSUSED*/ rl_generic_bind(int type __attribute__((__unused__)), const char * keyseq __attribute__((__unused__)), const char * data __attribute__((__unused__)), Keymap k __attribute__((__unused__))) { return 0; } int /*ARGSUSED*/ rl_bind_key_in_map(int key __attribute__((__unused__)), rl_command_func_t *fun __attribute__((__unused__)), Keymap k __attribute__((__unused__))) { return 0; } /* unsupported, but needed by python */ void rl_cleanup_after_signal(void) { } int rl_on_new_line(void) { return 0; } void rl_free_line_state(void) { } int /*ARGSUSED*/ rl_set_keyboard_input_timeout(int u __attribute__((__unused__))) { return 0; } heimdal-7.5.0/lib/libedit/src/terminal.h0000644000175000017500000001225313026237312016211 0ustar niknik/* $NetBSD: terminal.h,v 1.9 2016/05/09 21:46:56 christos Exp $ */ /*- * Copyright (c) 1992, 1993 * The Regents of the University of California. All rights reserved. * * This code is derived from software contributed to Berkeley by * Christos Zoulas of Cornell University. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the University nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * * @(#)term.h 8.1 (Berkeley) 6/4/93 */ /* * el.term.h: Termcap header */ #ifndef _h_el_terminal #define _h_el_terminal typedef struct { /* Symbolic function key bindings */ const wchar_t *name; /* name of the key */ int key; /* Index in termcap table */ keymacro_value_t fun; /* Function bound to it */ int type; /* Type of function */ } funckey_t; typedef struct { const char *t_name; /* the terminal name */ coord_t t_size; /* # lines and cols */ int t_flags; #define TERM_CAN_INSERT 0x001 /* Has insert cap */ #define TERM_CAN_DELETE 0x002 /* Has delete cap */ #define TERM_CAN_CEOL 0x004 /* Has CEOL cap */ #define TERM_CAN_TAB 0x008 /* Can use tabs */ #define TERM_CAN_ME 0x010 /* Can turn all attrs. */ #define TERM_CAN_UP 0x020 /* Can move up */ #define TERM_HAS_META 0x040 /* Has a meta key */ #define TERM_HAS_AUTO_MARGINS 0x080 /* Has auto margins */ #define TERM_HAS_MAGIC_MARGINS 0x100 /* Has magic margins */ char *t_buf; /* Termcap buffer */ size_t t_loc; /* location used */ char **t_str; /* termcap strings */ int *t_val; /* termcap values */ char *t_cap; /* Termcap buffer */ funckey_t *t_fkey; /* Array of keys */ } el_terminal_t; /* * fKey indexes */ #define A_K_DN 0 #define A_K_UP 1 #define A_K_LT 2 #define A_K_RT 3 #define A_K_HO 4 #define A_K_EN 5 #define A_K_DE 6 #define A_K_NKEYS 7 libedit_private void terminal_move_to_line(EditLine *, int); libedit_private void terminal_move_to_char(EditLine *, int); libedit_private void terminal_clear_EOL(EditLine *, int); libedit_private void terminal_overwrite(EditLine *, const wchar_t *, size_t); libedit_private void terminal_insertwrite(EditLine *, wchar_t *, int); libedit_private void terminal_deletechars(EditLine *, int); libedit_private void terminal_clear_screen(EditLine *); libedit_private void terminal_beep(EditLine *); libedit_private int terminal_change_size(EditLine *, int, int); libedit_private int terminal_get_size(EditLine *, int *, int *); libedit_private int terminal_init(EditLine *); libedit_private void terminal_bind_arrow(EditLine *); libedit_private void terminal_print_arrow(EditLine *, const wchar_t *); libedit_private int terminal_clear_arrow(EditLine *, const wchar_t *); libedit_private int terminal_set_arrow(EditLine *, const wchar_t *, keymacro_value_t *, int); libedit_private void terminal_end(EditLine *); libedit_private void terminal_get(EditLine *, const char **); libedit_private int terminal_set(EditLine *, const char *); libedit_private int terminal_settc(EditLine *, int, const wchar_t **); libedit_private int terminal_gettc(EditLine *, int, char **); libedit_private int terminal_telltc(EditLine *, int, const wchar_t **); libedit_private int terminal_echotc(EditLine *, int, const wchar_t **); libedit_private void terminal_writec(EditLine *, wint_t); libedit_private int terminal__putc(EditLine *, wint_t); libedit_private void terminal__flush(EditLine *); /* * Easy access macros */ #define EL_FLAGS (el)->el_terminal.t_flags #define EL_CAN_INSERT (EL_FLAGS & TERM_CAN_INSERT) #define EL_CAN_DELETE (EL_FLAGS & TERM_CAN_DELETE) #define EL_CAN_CEOL (EL_FLAGS & TERM_CAN_CEOL) #define EL_CAN_TAB (EL_FLAGS & TERM_CAN_TAB) #define EL_CAN_ME (EL_FLAGS & TERM_CAN_ME) #define EL_CAN_UP (EL_FLAGS & TERM_CAN_UP) #define EL_HAS_META (EL_FLAGS & TERM_HAS_META) #define EL_HAS_AUTO_MARGINS (EL_FLAGS & TERM_HAS_AUTO_MARGINS) #define EL_HAS_MAGIC_MARGINS (EL_FLAGS & TERM_HAS_MAGIC_MARGINS) #endif /* _h_el_terminal */ heimdal-7.5.0/lib/libedit/src/unvis.c0000644000175000017500000003503613026237312015541 0ustar niknik/* $NetBSD: unvis.c,v 1.44 2014/09/26 15:43:36 roy Exp $ */ /*- * Copyright (c) 1989, 1993 * The Regents of the University of California. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the University nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "config.h" #if defined(LIBC_SCCS) && !defined(lint) #if 0 static char sccsid[] = "@(#)unvis.c 8.1 (Berkeley) 6/4/93"; #else __RCSID("$NetBSD: unvis.c,v 1.44 2014/09/26 15:43:36 roy Exp $"); #endif #endif /* LIBC_SCCS and not lint */ #include #include #include #include #include #include #if !HAVE_VIS /* * decode driven by state machine */ #define S_GROUND 0 /* haven't seen escape char */ #define S_START 1 /* start decoding special sequence */ #define S_META 2 /* metachar started (M) */ #define S_META1 3 /* metachar more, regular char (-) */ #define S_CTRL 4 /* control char started (^) */ #define S_OCTAL2 5 /* octal digit 2 */ #define S_OCTAL3 6 /* octal digit 3 */ #define S_HEX 7 /* mandatory hex digit */ #define S_HEX1 8 /* http hex digit */ #define S_HEX2 9 /* http hex digit 2 */ #define S_MIME1 10 /* mime hex digit 1 */ #define S_MIME2 11 /* mime hex digit 2 */ #define S_EATCRNL 12 /* mime eating CRNL */ #define S_AMP 13 /* seen & */ #define S_NUMBER 14 /* collecting number */ #define S_STRING 15 /* collecting string */ #define isoctal(c) (((u_char)(c)) >= '0' && ((u_char)(c)) <= '7') #define xtod(c) (isdigit(c) ? (c - '0') : ((tolower(c) - 'a') + 10)) #define XTOD(c) (isdigit(c) ? (c - '0') : ((c - 'A') + 10)) /* * RFC 1866 */ static const struct nv { char name[7]; uint8_t value; } nv[] = { { "AElig", 198 }, /* capital AE diphthong (ligature) */ { "Aacute", 193 }, /* capital A, acute accent */ { "Acirc", 194 }, /* capital A, circumflex accent */ { "Agrave", 192 }, /* capital A, grave accent */ { "Aring", 197 }, /* capital A, ring */ { "Atilde", 195 }, /* capital A, tilde */ { "Auml", 196 }, /* capital A, dieresis or umlaut mark */ { "Ccedil", 199 }, /* capital C, cedilla */ { "ETH", 208 }, /* capital Eth, Icelandic */ { "Eacute", 201 }, /* capital E, acute accent */ { "Ecirc", 202 }, /* capital E, circumflex accent */ { "Egrave", 200 }, /* capital E, grave accent */ { "Euml", 203 }, /* capital E, dieresis or umlaut mark */ { "Iacute", 205 }, /* capital I, acute accent */ { "Icirc", 206 }, /* capital I, circumflex accent */ { "Igrave", 204 }, /* capital I, grave accent */ { "Iuml", 207 }, /* capital I, dieresis or umlaut mark */ { "Ntilde", 209 }, /* capital N, tilde */ { "Oacute", 211 }, /* capital O, acute accent */ { "Ocirc", 212 }, /* capital O, circumflex accent */ { "Ograve", 210 }, /* capital O, grave accent */ { "Oslash", 216 }, /* capital O, slash */ { "Otilde", 213 }, /* capital O, tilde */ { "Ouml", 214 }, /* capital O, dieresis or umlaut mark */ { "THORN", 222 }, /* capital THORN, Icelandic */ { "Uacute", 218 }, /* capital U, acute accent */ { "Ucirc", 219 }, /* capital U, circumflex accent */ { "Ugrave", 217 }, /* capital U, grave accent */ { "Uuml", 220 }, /* capital U, dieresis or umlaut mark */ { "Yacute", 221 }, /* capital Y, acute accent */ { "aacute", 225 }, /* small a, acute accent */ { "acirc", 226 }, /* small a, circumflex accent */ { "acute", 180 }, /* acute accent */ { "aelig", 230 }, /* small ae diphthong (ligature) */ { "agrave", 224 }, /* small a, grave accent */ { "amp", 38 }, /* ampersand */ { "aring", 229 }, /* small a, ring */ { "atilde", 227 }, /* small a, tilde */ { "auml", 228 }, /* small a, dieresis or umlaut mark */ { "brvbar", 166 }, /* broken (vertical) bar */ { "ccedil", 231 }, /* small c, cedilla */ { "cedil", 184 }, /* cedilla */ { "cent", 162 }, /* cent sign */ { "copy", 169 }, /* copyright sign */ { "curren", 164 }, /* general currency sign */ { "deg", 176 }, /* degree sign */ { "divide", 247 }, /* divide sign */ { "eacute", 233 }, /* small e, acute accent */ { "ecirc", 234 }, /* small e, circumflex accent */ { "egrave", 232 }, /* small e, grave accent */ { "eth", 240 }, /* small eth, Icelandic */ { "euml", 235 }, /* small e, dieresis or umlaut mark */ { "frac12", 189 }, /* fraction one-half */ { "frac14", 188 }, /* fraction one-quarter */ { "frac34", 190 }, /* fraction three-quarters */ { "gt", 62 }, /* greater than */ { "iacute", 237 }, /* small i, acute accent */ { "icirc", 238 }, /* small i, circumflex accent */ { "iexcl", 161 }, /* inverted exclamation mark */ { "igrave", 236 }, /* small i, grave accent */ { "iquest", 191 }, /* inverted question mark */ { "iuml", 239 }, /* small i, dieresis or umlaut mark */ { "laquo", 171 }, /* angle quotation mark, left */ { "lt", 60 }, /* less than */ { "macr", 175 }, /* macron */ { "micro", 181 }, /* micro sign */ { "middot", 183 }, /* middle dot */ { "nbsp", 160 }, /* no-break space */ { "not", 172 }, /* not sign */ { "ntilde", 241 }, /* small n, tilde */ { "oacute", 243 }, /* small o, acute accent */ { "ocirc", 244 }, /* small o, circumflex accent */ { "ograve", 242 }, /* small o, grave accent */ { "ordf", 170 }, /* ordinal indicator, feminine */ { "ordm", 186 }, /* ordinal indicator, masculine */ { "oslash", 248 }, /* small o, slash */ { "otilde", 245 }, /* small o, tilde */ { "ouml", 246 }, /* small o, dieresis or umlaut mark */ { "para", 182 }, /* pilcrow (paragraph sign) */ { "plusmn", 177 }, /* plus-or-minus sign */ { "pound", 163 }, /* pound sterling sign */ { "quot", 34 }, /* double quote */ { "raquo", 187 }, /* angle quotation mark, right */ { "reg", 174 }, /* registered sign */ { "sect", 167 }, /* section sign */ { "shy", 173 }, /* soft hyphen */ { "sup1", 185 }, /* superscript one */ { "sup2", 178 }, /* superscript two */ { "sup3", 179 }, /* superscript three */ { "szlig", 223 }, /* small sharp s, German (sz ligature) */ { "thorn", 254 }, /* small thorn, Icelandic */ { "times", 215 }, /* multiply sign */ { "uacute", 250 }, /* small u, acute accent */ { "ucirc", 251 }, /* small u, circumflex accent */ { "ugrave", 249 }, /* small u, grave accent */ { "uml", 168 }, /* umlaut (dieresis) */ { "uuml", 252 }, /* small u, dieresis or umlaut mark */ { "yacute", 253 }, /* small y, acute accent */ { "yen", 165 }, /* yen sign */ { "yuml", 255 }, /* small y, dieresis or umlaut mark */ }; /* * unvis - decode characters previously encoded by vis */ int unvis(char *cp, int c, int *astate, int flag) { unsigned char uc = (unsigned char)c; unsigned char st, ia, is, lc; /* * Bottom 8 bits of astate hold the state machine state. * Top 8 bits hold the current character in the http 1866 nv string decoding */ #define GS(a) ((a) & 0xff) #define SS(a, b) (((uint32_t)(a) << 24) | (b)) #define GI(a) ((uint32_t)(a) >> 24) _DIAGASSERT(cp != NULL); _DIAGASSERT(astate != NULL); st = GS(*astate); if (flag & UNVIS_END) { switch (st) { case S_OCTAL2: case S_OCTAL3: case S_HEX2: *astate = SS(0, S_GROUND); return UNVIS_VALID; case S_GROUND: return UNVIS_NOCHAR; default: return UNVIS_SYNBAD; } } switch (st) { case S_GROUND: *cp = 0; if ((flag & VIS_NOESCAPE) == 0 && c == '\\') { *astate = SS(0, S_START); return UNVIS_NOCHAR; } if ((flag & VIS_HTTP1808) && c == '%') { *astate = SS(0, S_HEX1); return UNVIS_NOCHAR; } if ((flag & VIS_HTTP1866) && c == '&') { *astate = SS(0, S_AMP); return UNVIS_NOCHAR; } if ((flag & VIS_MIMESTYLE) && c == '=') { *astate = SS(0, S_MIME1); return UNVIS_NOCHAR; } *cp = c; return UNVIS_VALID; case S_START: switch(c) { case '\\': *cp = c; *astate = SS(0, S_GROUND); return UNVIS_VALID; case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': *cp = (c - '0'); *astate = SS(0, S_OCTAL2); return UNVIS_NOCHAR; case 'M': *cp = (char)0200; *astate = SS(0, S_META); return UNVIS_NOCHAR; case '^': *astate = SS(0, S_CTRL); return UNVIS_NOCHAR; case 'n': *cp = '\n'; *astate = SS(0, S_GROUND); return UNVIS_VALID; case 'r': *cp = '\r'; *astate = SS(0, S_GROUND); return UNVIS_VALID; case 'b': *cp = '\b'; *astate = SS(0, S_GROUND); return UNVIS_VALID; case 'a': *cp = '\007'; *astate = SS(0, S_GROUND); return UNVIS_VALID; case 'v': *cp = '\v'; *astate = SS(0, S_GROUND); return UNVIS_VALID; case 't': *cp = '\t'; *astate = SS(0, S_GROUND); return UNVIS_VALID; case 'f': *cp = '\f'; *astate = SS(0, S_GROUND); return UNVIS_VALID; case 's': *cp = ' '; *astate = SS(0, S_GROUND); return UNVIS_VALID; case 'E': *cp = '\033'; *astate = SS(0, S_GROUND); return UNVIS_VALID; case 'x': *astate = SS(0, S_HEX); return UNVIS_NOCHAR; case '\n': /* * hidden newline */ *astate = SS(0, S_GROUND); return UNVIS_NOCHAR; case '$': /* * hidden marker */ *astate = SS(0, S_GROUND); return UNVIS_NOCHAR; default: if (isgraph(c)) { *cp = c; *astate = SS(0, S_GROUND); return UNVIS_VALID; } } goto bad; case S_META: if (c == '-') *astate = SS(0, S_META1); else if (c == '^') *astate = SS(0, S_CTRL); else goto bad; return UNVIS_NOCHAR; case S_META1: *astate = SS(0, S_GROUND); *cp |= c; return UNVIS_VALID; case S_CTRL: if (c == '?') *cp |= 0177; else *cp |= c & 037; *astate = SS(0, S_GROUND); return UNVIS_VALID; case S_OCTAL2: /* second possible octal digit */ if (isoctal(uc)) { /* * yes - and maybe a third */ *cp = (*cp << 3) + (c - '0'); *astate = SS(0, S_OCTAL3); return UNVIS_NOCHAR; } /* * no - done with current sequence, push back passed char */ *astate = SS(0, S_GROUND); return UNVIS_VALIDPUSH; case S_OCTAL3: /* third possible octal digit */ *astate = SS(0, S_GROUND); if (isoctal(uc)) { *cp = (*cp << 3) + (c - '0'); return UNVIS_VALID; } /* * we were done, push back passed char */ return UNVIS_VALIDPUSH; case S_HEX: if (!isxdigit(uc)) goto bad; /*FALLTHROUGH*/ case S_HEX1: if (isxdigit(uc)) { *cp = xtod(uc); *astate = SS(0, S_HEX2); return UNVIS_NOCHAR; } /* * no - done with current sequence, push back passed char */ *astate = SS(0, S_GROUND); return UNVIS_VALIDPUSH; case S_HEX2: *astate = S_GROUND; if (isxdigit(uc)) { *cp = xtod(uc) | (*cp << 4); return UNVIS_VALID; } return UNVIS_VALIDPUSH; case S_MIME1: if (uc == '\n' || uc == '\r') { *astate = SS(0, S_EATCRNL); return UNVIS_NOCHAR; } if (isxdigit(uc) && (isdigit(uc) || isupper(uc))) { *cp = XTOD(uc); *astate = SS(0, S_MIME2); return UNVIS_NOCHAR; } goto bad; case S_MIME2: if (isxdigit(uc) && (isdigit(uc) || isupper(uc))) { *astate = SS(0, S_GROUND); *cp = XTOD(uc) | (*cp << 4); return UNVIS_VALID; } goto bad; case S_EATCRNL: switch (uc) { case '\r': case '\n': return UNVIS_NOCHAR; case '=': *astate = SS(0, S_MIME1); return UNVIS_NOCHAR; default: *cp = uc; *astate = SS(0, S_GROUND); return UNVIS_VALID; } case S_AMP: *cp = 0; if (uc == '#') { *astate = SS(0, S_NUMBER); return UNVIS_NOCHAR; } *astate = SS(0, S_STRING); /*FALLTHROUGH*/ case S_STRING: ia = *cp; /* index in the array */ is = GI(*astate); /* index in the string */ lc = is == 0 ? 0 : nv[ia].name[is - 1]; /* last character */ if (uc == ';') uc = '\0'; for (; ia < __arraycount(nv); ia++) { if (is != 0 && nv[ia].name[is - 1] != lc) goto bad; if (nv[ia].name[is] == uc) break; } if (ia == __arraycount(nv)) goto bad; if (uc != 0) { *cp = ia; *astate = SS(is + 1, S_STRING); return UNVIS_NOCHAR; } *cp = nv[ia].value; *astate = SS(0, S_GROUND); return UNVIS_VALID; case S_NUMBER: if (uc == ';') return UNVIS_VALID; if (!isdigit(uc)) goto bad; *cp += (*cp * 10) + uc - '0'; return UNVIS_NOCHAR; default: bad: /* * decoder in unknown state - (probably uninitialized) */ *astate = SS(0, S_GROUND); return UNVIS_SYNBAD; } } /* * strnunvisx - decode src into dst * * Number of chars decoded into dst is returned, -1 on error. * Dst is null terminated. */ int strnunvisx(char *dst, size_t dlen, const char *src, int flag) { char c; char t = '\0', *start = dst; int state = 0; _DIAGASSERT(src != NULL); _DIAGASSERT(dst != NULL); #define CHECKSPACE() \ do { \ if (dlen-- == 0) { \ errno = ENOSPC; \ return -1; \ } \ } while (/*CONSTCOND*/0) while ((c = *src++) != '\0') { again: switch (unvis(&t, c, &state, flag)) { case UNVIS_VALID: CHECKSPACE(); *dst++ = t; break; case UNVIS_VALIDPUSH: CHECKSPACE(); *dst++ = t; goto again; case 0: case UNVIS_NOCHAR: break; case UNVIS_SYNBAD: errno = EINVAL; return -1; default: _DIAGASSERT(/*CONSTCOND*/0); errno = EINVAL; return -1; } } if (unvis(&t, c, &state, UNVIS_END) == UNVIS_VALID) { CHECKSPACE(); *dst++ = t; } CHECKSPACE(); *dst = '\0'; return (int)(dst - start); } int strunvisx(char *dst, const char *src, int flag) { return strnunvisx(dst, (size_t)~0, src, flag); } int strunvis(char *dst, const char *src) { return strnunvisx(dst, (size_t)~0, src, 0); } int strnunvis(char *dst, size_t dlen, const char *src) { return strnunvisx(dst, dlen, src, 0); } #endif heimdal-7.5.0/lib/libedit/src/sig.h0000644000175000017500000000467213026237312015166 0ustar niknik/* $NetBSD: sig.h,v 1.11 2016/05/09 21:46:56 christos Exp $ */ /*- * Copyright (c) 1992, 1993 * The Regents of the University of California. All rights reserved. * * This code is derived from software contributed to Berkeley by * Christos Zoulas of Cornell University. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the University nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * * @(#)sig.h 8.1 (Berkeley) 6/4/93 */ /* * el.sig.h: Signal handling functions */ #ifndef _h_el_sig #define _h_el_sig #include /* * Define here all the signals we are going to handle * The _DO macro is used to iterate in the source code */ #define ALLSIGS \ _DO(SIGINT) \ _DO(SIGTSTP) \ _DO(SIGQUIT) \ _DO(SIGHUP) \ _DO(SIGTERM) \ _DO(SIGCONT) \ _DO(SIGWINCH) #define ALLSIGSNO 7 typedef struct { struct sigaction sig_action[ALLSIGSNO]; sigset_t sig_set; volatile sig_atomic_t sig_no; } *el_signal_t; libedit_private void sig_end(EditLine*); libedit_private int sig_init(EditLine*); libedit_private void sig_set(EditLine*); libedit_private void sig_clr(EditLine*); #endif /* _h_el_sig */ heimdal-7.5.0/lib/libedit/src/keymacro.c0000644000175000017500000004063213026237312016205 0ustar niknik/* $NetBSD: keymacro.c,v 1.23 2016/05/24 15:00:45 christos Exp $ */ /*- * Copyright (c) 1992, 1993 * The Regents of the University of California. All rights reserved. * * This code is derived from software contributed to Berkeley by * Christos Zoulas of Cornell University. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the University nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "config.h" #if !defined(lint) && !defined(SCCSID) #if 0 static char sccsid[] = "@(#)key.c 8.1 (Berkeley) 6/4/93"; #else __RCSID("$NetBSD: keymacro.c,v 1.23 2016/05/24 15:00:45 christos Exp $"); #endif #endif /* not lint && not SCCSID */ /* * keymacro.c: This module contains the procedures for maintaining * the extended-key map. * * An extended-key (key) is a sequence of keystrokes introduced * with a sequence introducer and consisting of an arbitrary * number of characters. This module maintains a map (the * el->el_keymacro.map) * to convert these extended-key sequences into input strs * (XK_STR) or editor functions (XK_CMD). * * Warning: * If key is a substr of some other keys, then the longer * keys are lost!! That is, if the keys "abcd" and "abcef" * are in el->el_keymacro.map, adding the key "abc" will cause * the first two definitions to be lost. * * Restrictions: * ------------- * 1) It is not possible to have one key that is a * substr of another. */ #include #include #include "el.h" #include "fcns.h" /* * The Nodes of the el->el_keymacro.map. The el->el_keymacro.map is a * linked list of these node elements */ struct keymacro_node_t { wchar_t ch; /* single character of key */ int type; /* node type */ keymacro_value_t val; /* command code or pointer to str, */ /* if this is a leaf */ struct keymacro_node_t *next; /* ptr to next char of this key */ struct keymacro_node_t *sibling;/* ptr to another key with same prefix*/ }; static int node_trav(EditLine *, keymacro_node_t *, wchar_t *, keymacro_value_t *); static int node__try(EditLine *, keymacro_node_t *, const wchar_t *, keymacro_value_t *, int); static keymacro_node_t *node__get(wint_t); static void node__free(keymacro_node_t *); static void node__put(EditLine *, keymacro_node_t *); static int node__delete(EditLine *, keymacro_node_t **, const wchar_t *); static int node_lookup(EditLine *, const wchar_t *, keymacro_node_t *, size_t); static int node_enum(EditLine *, keymacro_node_t *, size_t); #define KEY_BUFSIZ EL_BUFSIZ /* keymacro_init(): * Initialize the key maps */ libedit_private int keymacro_init(EditLine *el) { el->el_keymacro.buf = el_malloc(KEY_BUFSIZ * sizeof(*el->el_keymacro.buf)); if (el->el_keymacro.buf == NULL) return -1; el->el_keymacro.map = NULL; keymacro_reset(el); return 0; } /* keymacro_end(): * Free the key maps */ libedit_private void keymacro_end(EditLine *el) { el_free(el->el_keymacro.buf); el->el_keymacro.buf = NULL; node__free(el->el_keymacro.map); } /* keymacro_map_cmd(): * Associate cmd with a key value */ libedit_private keymacro_value_t * keymacro_map_cmd(EditLine *el, int cmd) { el->el_keymacro.val.cmd = (el_action_t) cmd; return &el->el_keymacro.val; } /* keymacro_map_str(): * Associate str with a key value */ libedit_private keymacro_value_t * keymacro_map_str(EditLine *el, wchar_t *str) { el->el_keymacro.val.str = str; return &el->el_keymacro.val; } /* keymacro_reset(): * Takes all nodes on el->el_keymacro.map and puts them on free list. * Then initializes el->el_keymacro.map with arrow keys * [Always bind the ansi arrow keys?] */ libedit_private void keymacro_reset(EditLine *el) { node__put(el, el->el_keymacro.map); el->el_keymacro.map = NULL; return; } /* keymacro_get(): * Calls the recursive function with entry point el->el_keymacro.map * Looks up *ch in map and then reads characters until a * complete match is found or a mismatch occurs. Returns the * type of the match found (XK_STR or XK_CMD). * Returns NULL in val.str and XK_STR for no match. * Returns XK_NOD for end of file or read error. * The last character read is returned in *ch. */ libedit_private int keymacro_get(EditLine *el, wchar_t *ch, keymacro_value_t *val) { return node_trav(el, el->el_keymacro.map, ch, val); } /* keymacro_add(): * Adds key to the el->el_keymacro.map and associates the value in * val with it. If key is already is in el->el_keymacro.map, the new * code is applied to the existing key. Ntype specifies if code is a * command, an out str or a unix command. */ libedit_private void keymacro_add(EditLine *el, const wchar_t *key, keymacro_value_t *val, int ntype) { if (key[0] == '\0') { (void) fprintf(el->el_errfile, "keymacro_add: Null extended-key not allowed.\n"); return; } if (ntype == XK_CMD && val->cmd == ED_SEQUENCE_LEAD_IN) { (void) fprintf(el->el_errfile, "keymacro_add: sequence-lead-in command not allowed\n"); return; } if (el->el_keymacro.map == NULL) /* tree is initially empty. Set up new node to match key[0] */ el->el_keymacro.map = node__get(key[0]); /* it is properly initialized */ /* Now recurse through el->el_keymacro.map */ (void) node__try(el, el->el_keymacro.map, key, val, ntype); return; } /* keymacro_clear(): * */ libedit_private void keymacro_clear(EditLine *el, el_action_t *map, const wchar_t *in) { if (*in > N_KEYS) /* can't be in the map */ return; if ((map[(unsigned char)*in] == ED_SEQUENCE_LEAD_IN) && ((map == el->el_map.key && el->el_map.alt[(unsigned char)*in] != ED_SEQUENCE_LEAD_IN) || (map == el->el_map.alt && el->el_map.key[(unsigned char)*in] != ED_SEQUENCE_LEAD_IN))) (void) keymacro_delete(el, in); } /* keymacro_delete(): * Delete the key and all longer keys staring with key, if * they exists. */ libedit_private int keymacro_delete(EditLine *el, const wchar_t *key) { if (key[0] == '\0') { (void) fprintf(el->el_errfile, "keymacro_delete: Null extended-key not allowed.\n"); return -1; } if (el->el_keymacro.map == NULL) return 0; (void) node__delete(el, &el->el_keymacro.map, key); return 0; } /* keymacro_print(): * Print the binding associated with key key. * Print entire el->el_keymacro.map if null */ libedit_private void keymacro_print(EditLine *el, const wchar_t *key) { /* do nothing if el->el_keymacro.map is empty and null key specified */ if (el->el_keymacro.map == NULL && *key == 0) return; el->el_keymacro.buf[0] = '"'; if (node_lookup(el, key, el->el_keymacro.map, (size_t)1) <= -1) /* key is not bound */ (void) fprintf(el->el_errfile, "Unbound extended key \"%ls" "\"\n", key); return; } /* node_trav(): * recursively traverses node in tree until match or mismatch is * found. May read in more characters. */ static int node_trav(EditLine *el, keymacro_node_t *ptr, wchar_t *ch, keymacro_value_t *val) { if (ptr->ch == *ch) { /* match found */ if (ptr->next) { /* key not complete so get next char */ if (el_wgetc(el, ch) != 1) return XK_NOD; return node_trav(el, ptr->next, ch, val); } else { *val = ptr->val; if (ptr->type != XK_CMD) *ch = '\0'; return ptr->type; } } else { /* no match found here */ if (ptr->sibling) { /* try next sibling */ return node_trav(el, ptr->sibling, ch, val); } else { /* no next sibling -- mismatch */ val->str = NULL; return XK_STR; } } } /* node__try(): * Find a node that matches *str or allocate a new one */ static int node__try(EditLine *el, keymacro_node_t *ptr, const wchar_t *str, keymacro_value_t *val, int ntype) { if (ptr->ch != *str) { keymacro_node_t *xm; for (xm = ptr; xm->sibling != NULL; xm = xm->sibling) if (xm->sibling->ch == *str) break; if (xm->sibling == NULL) xm->sibling = node__get(*str); /* setup new node */ ptr = xm->sibling; } if (*++str == '\0') { /* we're there */ if (ptr->next != NULL) { node__put(el, ptr->next); /* lose longer keys with this prefix */ ptr->next = NULL; } switch (ptr->type) { case XK_CMD: case XK_NOD: break; case XK_STR: if (ptr->val.str) el_free(ptr->val.str); break; default: EL_ABORT((el->el_errfile, "Bad XK_ type %d\n", ptr->type)); break; } switch (ptr->type = ntype) { case XK_CMD: ptr->val = *val; break; case XK_STR: if ((ptr->val.str = wcsdup(val->str)) == NULL) return -1; break; default: EL_ABORT((el->el_errfile, "Bad XK_ type %d\n", ntype)); break; } } else { /* still more chars to go */ if (ptr->next == NULL) ptr->next = node__get(*str); /* setup new node */ (void) node__try(el, ptr->next, str, val, ntype); } return 0; } /* node__delete(): * Delete node that matches str */ static int node__delete(EditLine *el, keymacro_node_t **inptr, const wchar_t *str) { keymacro_node_t *ptr; keymacro_node_t *prev_ptr = NULL; ptr = *inptr; if (ptr->ch != *str) { keymacro_node_t *xm; for (xm = ptr; xm->sibling != NULL; xm = xm->sibling) if (xm->sibling->ch == *str) break; if (xm->sibling == NULL) return 0; prev_ptr = xm; ptr = xm->sibling; } if (*++str == '\0') { /* we're there */ if (prev_ptr == NULL) *inptr = ptr->sibling; else prev_ptr->sibling = ptr->sibling; ptr->sibling = NULL; node__put(el, ptr); return 1; } else if (ptr->next != NULL && node__delete(el, &ptr->next, str) == 1) { if (ptr->next != NULL) return 0; if (prev_ptr == NULL) *inptr = ptr->sibling; else prev_ptr->sibling = ptr->sibling; ptr->sibling = NULL; node__put(el, ptr); return 1; } else { return 0; } } /* node__put(): * Puts a tree of nodes onto free list using free(3). */ static void node__put(EditLine *el, keymacro_node_t *ptr) { if (ptr == NULL) return; if (ptr->next != NULL) { node__put(el, ptr->next); ptr->next = NULL; } node__put(el, ptr->sibling); switch (ptr->type) { case XK_CMD: case XK_NOD: break; case XK_STR: if (ptr->val.str != NULL) el_free(ptr->val.str); break; default: EL_ABORT((el->el_errfile, "Bad XK_ type %d\n", ptr->type)); break; } el_free(ptr); } /* node__get(): * Returns pointer to a keymacro_node_t for ch. */ static keymacro_node_t * node__get(wint_t ch) { keymacro_node_t *ptr; ptr = el_malloc(sizeof(*ptr)); if (ptr == NULL) return NULL; ptr->ch = ch; ptr->type = XK_NOD; ptr->val.str = NULL; ptr->next = NULL; ptr->sibling = NULL; return ptr; } static void node__free(keymacro_node_t *k) { if (k == NULL) return; node__free(k->sibling); node__free(k->next); el_free(k); } /* node_lookup(): * look for the str starting at node ptr. * Print if last node */ static int node_lookup(EditLine *el, const wchar_t *str, keymacro_node_t *ptr, size_t cnt) { ssize_t used; if (ptr == NULL) return -1; /* cannot have null ptr */ if (!str || *str == 0) { /* no more chars in str. node_enum from here. */ (void) node_enum(el, ptr, cnt); return 0; } else { /* If match put this char into el->el_keymacro.buf. Recurse */ if (ptr->ch == *str) { /* match found */ used = ct_visual_char(el->el_keymacro.buf + cnt, KEY_BUFSIZ - cnt, ptr->ch); if (used == -1) return -1; /* ran out of buffer space */ if (ptr->next != NULL) /* not yet at leaf */ return (node_lookup(el, str + 1, ptr->next, (size_t)used + cnt)); else { /* next node is null so key should be complete */ if (str[1] == 0) { size_t px = cnt + (size_t)used; el->el_keymacro.buf[px] = '"'; el->el_keymacro.buf[px + 1] = '\0'; keymacro_kprint(el, el->el_keymacro.buf, &ptr->val, ptr->type); return 0; } else return -1; /* mismatch -- str still has chars */ } } else { /* no match found try sibling */ if (ptr->sibling) return (node_lookup(el, str, ptr->sibling, cnt)); else return -1; } } } /* node_enum(): * Traverse the node printing the characters it is bound in buffer */ static int node_enum(EditLine *el, keymacro_node_t *ptr, size_t cnt) { ssize_t used; if (cnt >= KEY_BUFSIZ - 5) { /* buffer too small */ el->el_keymacro.buf[++cnt] = '"'; el->el_keymacro.buf[++cnt] = '\0'; (void) fprintf(el->el_errfile, "Some extended keys too long for internal print buffer"); (void) fprintf(el->el_errfile, " \"%ls...\"\n", el->el_keymacro.buf); return 0; } if (ptr == NULL) { #ifdef DEBUG_EDIT (void) fprintf(el->el_errfile, "node_enum: BUG!! Null ptr passed\n!"); #endif return -1; } /* put this char at end of str */ used = ct_visual_char(el->el_keymacro.buf + cnt, KEY_BUFSIZ - cnt, ptr->ch); if (ptr->next == NULL) { /* print this key and function */ el->el_keymacro.buf[cnt + (size_t)used ] = '"'; el->el_keymacro.buf[cnt + (size_t)used + 1] = '\0'; keymacro_kprint(el, el->el_keymacro.buf, &ptr->val, ptr->type); } else (void) node_enum(el, ptr->next, cnt + (size_t)used); /* go to sibling if there is one */ if (ptr->sibling) (void) node_enum(el, ptr->sibling, cnt); return 0; } /* keymacro_kprint(): * Print the specified key and its associated * function specified by val */ libedit_private void keymacro_kprint(EditLine *el, const wchar_t *key, keymacro_value_t *val, int ntype) { el_bindings_t *fp; char unparsbuf[EL_BUFSIZ]; static const char fmt[] = "%-15s-> %s\n"; if (val != NULL) switch (ntype) { case XK_STR: (void) keymacro__decode_str(val->str, unparsbuf, sizeof(unparsbuf), ntype == XK_STR ? "\"\"" : "[]"); (void) fprintf(el->el_outfile, fmt, ct_encode_string(key, &el->el_scratch), unparsbuf); break; case XK_CMD: for (fp = el->el_map.help; fp->name; fp++) if (val->cmd == fp->func) { wcstombs(unparsbuf, fp->name, sizeof(unparsbuf)); unparsbuf[sizeof(unparsbuf) -1] = '\0'; (void) fprintf(el->el_outfile, fmt, ct_encode_string(key, &el->el_scratch), unparsbuf); break; } #ifdef DEBUG_KEY if (fp->name == NULL) (void) fprintf(el->el_outfile, "BUG! Command not found.\n"); #endif break; default: EL_ABORT((el->el_errfile, "Bad XK_ type %d\n", ntype)); break; } else (void) fprintf(el->el_outfile, fmt, ct_encode_string(key, &el->el_scratch), "no input"); } #define ADDC(c) \ if (b < eb) \ *b++ = c; \ else \ b++ /* keymacro__decode_str(): * Make a printable version of the ey */ libedit_private size_t keymacro__decode_str(const wchar_t *str, char *buf, size_t len, const char *sep) { char *b = buf, *eb = b + len; const wchar_t *p; b = buf; if (sep[0] != '\0') { ADDC(sep[0]); } if (*str == '\0') { ADDC('^'); ADDC('@'); goto add_endsep; } for (p = str; *p != 0; p++) { wchar_t dbuf[VISUAL_WIDTH_MAX]; wchar_t *p2 = dbuf; ssize_t l = ct_visual_char(dbuf, VISUAL_WIDTH_MAX, *p); while (l-- > 0) { ssize_t n = ct_encode_char(b, (size_t)(eb - b), *p2++); if (n == -1) /* ran out of space */ goto add_endsep; else b += n; } } add_endsep: if (sep[0] != '\0' && sep[1] != '\0') { ADDC(sep[1]); } ADDC('\0'); if ((size_t)(b - buf) >= len) buf[len - 1] = '\0'; return (size_t)(b - buf); } heimdal-7.5.0/lib/libedit/src/hist.c0000644000175000017500000001440013026237312015334 0ustar niknik/* $NetBSD: hist.c,v 1.30 2016/11/07 15:30:18 christos Exp $ */ /*- * Copyright (c) 1992, 1993 * The Regents of the University of California. All rights reserved. * * This code is derived from software contributed to Berkeley by * Christos Zoulas of Cornell University. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the University nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "config.h" #if !defined(lint) && !defined(SCCSID) #if 0 static char sccsid[] = "@(#)hist.c 8.1 (Berkeley) 6/4/93"; #else __RCSID("$NetBSD: hist.c,v 1.30 2016/11/07 15:30:18 christos Exp $"); #endif #endif /* not lint && not SCCSID */ /* * hist.c: History access functions */ #include #include #include #include "el.h" /* hist_init(): * Initialization function. */ libedit_private int hist_init(EditLine *el) { el->el_history.fun = NULL; el->el_history.ref = NULL; el->el_history.buf = el_malloc(EL_BUFSIZ * sizeof(*el->el_history.buf)); el->el_history.sz = EL_BUFSIZ; if (el->el_history.buf == NULL) return -1; el->el_history.last = el->el_history.buf; return 0; } /* hist_end(): * clean up history; */ libedit_private void hist_end(EditLine *el) { el_free(el->el_history.buf); el->el_history.buf = NULL; } /* hist_set(): * Set new history interface */ libedit_private int hist_set(EditLine *el, hist_fun_t fun, void *ptr) { el->el_history.ref = ptr; el->el_history.fun = fun; return 0; } /* hist_get(): * Get a history line and update it in the buffer. * eventno tells us the event to get. */ libedit_private el_action_t hist_get(EditLine *el) { const wchar_t *hp; int h; if (el->el_history.eventno == 0) { /* if really the current line */ (void) wcsncpy(el->el_line.buffer, el->el_history.buf, el->el_history.sz); el->el_line.lastchar = el->el_line.buffer + (el->el_history.last - el->el_history.buf); #ifdef KSHVI if (el->el_map.type == MAP_VI) el->el_line.cursor = el->el_line.buffer; else #endif /* KSHVI */ el->el_line.cursor = el->el_line.lastchar; return CC_REFRESH; } if (el->el_history.ref == NULL) return CC_ERROR; hp = HIST_FIRST(el); if (hp == NULL) return CC_ERROR; for (h = 1; h < el->el_history.eventno; h++) if ((hp = HIST_NEXT(el)) == NULL) { el->el_history.eventno = h; return CC_ERROR; } (void) wcsncpy(el->el_line.buffer, hp, (size_t)(el->el_line.limit - el->el_line.buffer)); el->el_line.buffer[el->el_line.limit - el->el_line.buffer - 1] = '\0'; el->el_line.lastchar = el->el_line.buffer + wcslen(el->el_line.buffer); if (el->el_line.lastchar > el->el_line.buffer && el->el_line.lastchar[-1] == '\n') el->el_line.lastchar--; if (el->el_line.lastchar > el->el_line.buffer && el->el_line.lastchar[-1] == ' ') el->el_line.lastchar--; #ifdef KSHVI if (el->el_map.type == MAP_VI) el->el_line.cursor = el->el_line.buffer; else #endif /* KSHVI */ el->el_line.cursor = el->el_line.lastchar; return CC_REFRESH; } /* hist_command() * process a history command */ libedit_private int hist_command(EditLine *el, int argc, const wchar_t **argv) { const wchar_t *str; int num; HistEventW ev; if (el->el_history.ref == NULL) return -1; if (argc == 1 || wcscmp(argv[1], L"list") == 0) { size_t maxlen = 0; char *buf = NULL; int hno = 1; /* List history entries */ for (str = HIST_LAST(el); str != NULL; str = HIST_PREV(el)) { char *ptr = ct_encode_string(str, &el->el_scratch); size_t len = strlen(ptr); if (len > 0 && ptr[len - 1] == '\n') ptr[--len] = '\0'; len = len * 4 + 1; if (len >= maxlen) { maxlen = len + 1024; char *nbuf = el_realloc(buf, maxlen); if (nbuf == NULL) { el_free(buf); return -1; } buf = nbuf; } strvis(buf, ptr, VIS_NL); (void) fprintf(el->el_outfile, "%d\t%s\n", hno++, buf); } el_free(buf); return 0; } if (argc != 3) return -1; num = (int)wcstol(argv[2], NULL, 0); if (wcscmp(argv[1], L"size") == 0) return history_w(el->el_history.ref, &ev, H_SETSIZE, num); if (wcscmp(argv[1], L"unique") == 0) return history_w(el->el_history.ref, &ev, H_SETUNIQUE, num); return -1; } /* hist_enlargebuf() * Enlarge history buffer to specified value. Called from el_enlargebufs(). * Return 0 for failure, 1 for success. */ libedit_private int /*ARGSUSED*/ hist_enlargebuf(EditLine *el, size_t oldsz, size_t newsz) { wchar_t *newbuf; newbuf = el_realloc(el->el_history.buf, newsz * sizeof(*newbuf)); if (!newbuf) return 0; (void) memset(&newbuf[oldsz], '\0', (newsz - oldsz) * sizeof(*newbuf)); el->el_history.last = newbuf + (el->el_history.last - el->el_history.buf); el->el_history.buf = newbuf; el->el_history.sz = newsz; return 1; } libedit_private wchar_t * hist_convert(EditLine *el, int fn, void *arg) { HistEventW ev; if ((*(el)->el_history.fun)((el)->el_history.ref, &ev, fn, arg) == -1) return NULL; return ct_decode_string((const char *)(const void *)ev.str, &el->el_scratch); } heimdal-7.5.0/lib/libedit/src/refresh.c0000644000175000017500000007752213026237312016041 0ustar niknik/* $NetBSD: refresh.c,v 1.51 2016/05/09 21:46:56 christos Exp $ */ /*- * Copyright (c) 1992, 1993 * The Regents of the University of California. All rights reserved. * * This code is derived from software contributed to Berkeley by * Christos Zoulas of Cornell University. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the University nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "config.h" #if !defined(lint) && !defined(SCCSID) #if 0 static char sccsid[] = "@(#)refresh.c 8.1 (Berkeley) 6/4/93"; #else __RCSID("$NetBSD: refresh.c,v 1.51 2016/05/09 21:46:56 christos Exp $"); #endif #endif /* not lint && not SCCSID */ /* * refresh.c: Lower level screen refreshing functions */ #include #include #include #include "el.h" static void re_nextline(EditLine *); static void re_addc(EditLine *, wint_t); static void re_update_line(EditLine *, wchar_t *, wchar_t *, int); static void re_insert (EditLine *, wchar_t *, int, int, wchar_t *, int); static void re_delete(EditLine *, wchar_t *, int, int, int); static void re_fastputc(EditLine *, wint_t); static void re_clear_eol(EditLine *, int, int, int); static void re__strncopy(wchar_t *, wchar_t *, size_t); static void re__copy_and_pad(wchar_t *, const wchar_t *, size_t); #ifdef DEBUG_REFRESH static void re_printstr(EditLine *, const char *, wchar_t *, wchar_t *); #define __F el->el_errfile #define ELRE_ASSERT(a, b, c) do \ if (/*CONSTCOND*/ a) { \ (void) fprintf b; \ c; \ } \ while (/*CONSTCOND*/0) #define ELRE_DEBUG(a, b) ELRE_ASSERT(a,b,;) /* re_printstr(): * Print a string on the debugging pty */ static void re_printstr(EditLine *el, const char *str, wchar_t *f, wchar_t *t) { ELRE_DEBUG(1, (__F, "%s:\"", str)); while (f < t) ELRE_DEBUG(1, (__F, "%c", *f++ & 0177)); ELRE_DEBUG(1, (__F, "\"\r\n")); } #else #define ELRE_ASSERT(a, b, c) #define ELRE_DEBUG(a, b) #endif /* re_nextline(): * Move to the next line or scroll */ static void re_nextline(EditLine *el) { el->el_refresh.r_cursor.h = 0; /* reset it. */ /* * If we would overflow (input is longer than terminal size), * emulate scroll by dropping first line and shuffling the rest. * We do this via pointer shuffling - it's safe in this case * and we avoid memcpy(). */ if (el->el_refresh.r_cursor.v + 1 >= el->el_terminal.t_size.v) { int i, lins = el->el_terminal.t_size.v; wchar_t *firstline = el->el_vdisplay[0]; for(i = 1; i < lins; i++) el->el_vdisplay[i - 1] = el->el_vdisplay[i]; firstline[0] = '\0'; /* empty the string */ el->el_vdisplay[i - 1] = firstline; } else el->el_refresh.r_cursor.v++; ELRE_ASSERT(el->el_refresh.r_cursor.v >= el->el_terminal.t_size.v, (__F, "\r\nre_putc: overflow! r_cursor.v == %d > %d\r\n", el->el_refresh.r_cursor.v, el->el_terminal.t_size.v), abort()); } /* re_addc(): * Draw c, expanding tabs, control chars etc. */ static void re_addc(EditLine *el, wint_t c) { switch (ct_chr_class(c)) { case CHTYPE_TAB: /* expand the tab */ for (;;) { re_putc(el, ' ', 1); if ((el->el_refresh.r_cursor.h & 07) == 0) break; /* go until tab stop */ } break; case CHTYPE_NL: { int oldv = el->el_refresh.r_cursor.v; re_putc(el, '\0', 0); /* assure end of line */ if (oldv == el->el_refresh.r_cursor.v) /* XXX */ re_nextline(el); break; } case CHTYPE_PRINT: re_putc(el, c, 1); break; default: { wchar_t visbuf[VISUAL_WIDTH_MAX]; ssize_t i, n = ct_visual_char(visbuf, VISUAL_WIDTH_MAX, c); for (i = 0; n-- > 0; ++i) re_putc(el, visbuf[i], 1); break; } } } /* re_putc(): * Draw the character given */ libedit_private void re_putc(EditLine *el, wint_t c, int shift) { int i, w = wcwidth(c); ELRE_DEBUG(1, (__F, "printing %5x '%lc'\r\n", c, c)); if (w == -1) w = 0; while (shift && (el->el_refresh.r_cursor.h + w > el->el_terminal.t_size.h)) re_putc(el, ' ', 1); el->el_vdisplay[el->el_refresh.r_cursor.v] [el->el_refresh.r_cursor.h] = c; /* assumes !shift is only used for single-column chars */ i = w; while (--i > 0) el->el_vdisplay[el->el_refresh.r_cursor.v] [el->el_refresh.r_cursor.h + i] = MB_FILL_CHAR; if (!shift) return; el->el_refresh.r_cursor.h += w; /* advance to next place */ if (el->el_refresh.r_cursor.h >= el->el_terminal.t_size.h) { /* assure end of line */ el->el_vdisplay[el->el_refresh.r_cursor.v][el->el_terminal.t_size.h] = '\0'; re_nextline(el); } } /* re_refresh(): * draws the new virtual screen image from the current input * line, then goes line-by-line changing the real image to the new * virtual image. The routine to re-draw a line can be replaced * easily in hopes of a smarter one being placed there. */ libedit_private void re_refresh(EditLine *el) { int i, rhdiff; wchar_t *cp, *st; coord_t cur; #ifdef notyet size_t termsz; #endif ELRE_DEBUG(1, (__F, "el->el_line.buffer = :%ls:\r\n", el->el_line.buffer)); /* reset the Drawing cursor */ el->el_refresh.r_cursor.h = 0; el->el_refresh.r_cursor.v = 0; /* temporarily draw rprompt to calculate its size */ prompt_print(el, EL_RPROMPT); /* reset the Drawing cursor */ el->el_refresh.r_cursor.h = 0; el->el_refresh.r_cursor.v = 0; if (el->el_line.cursor >= el->el_line.lastchar) { if (el->el_map.current == el->el_map.alt && el->el_line.lastchar != el->el_line.buffer) el->el_line.cursor = el->el_line.lastchar - 1; else el->el_line.cursor = el->el_line.lastchar; } cur.h = -1; /* set flag in case I'm not set */ cur.v = 0; prompt_print(el, EL_PROMPT); /* draw the current input buffer */ #if notyet termsz = el->el_terminal.t_size.h * el->el_terminal.t_size.v; if (el->el_line.lastchar - el->el_line.buffer > termsz) { /* * If line is longer than terminal, process only part * of line which would influence display. */ size_t rem = (el->el_line.lastchar-el->el_line.buffer)%termsz; st = el->el_line.lastchar - rem - (termsz - (((rem / el->el_terminal.t_size.v) - 1) * el->el_terminal.t_size.v)); } else #endif st = el->el_line.buffer; for (cp = st; cp < el->el_line.lastchar; cp++) { if (cp == el->el_line.cursor) { int w = wcwidth(*cp); /* save for later */ cur.h = el->el_refresh.r_cursor.h; cur.v = el->el_refresh.r_cursor.v; /* handle being at a linebroken doublewidth char */ if (w > 1 && el->el_refresh.r_cursor.h + w > el->el_terminal.t_size.h) { cur.h = 0; cur.v++; } } re_addc(el, *cp); } if (cur.h == -1) { /* if I haven't been set yet, I'm at the end */ cur.h = el->el_refresh.r_cursor.h; cur.v = el->el_refresh.r_cursor.v; } rhdiff = el->el_terminal.t_size.h - el->el_refresh.r_cursor.h - el->el_rprompt.p_pos.h; if (el->el_rprompt.p_pos.h && !el->el_rprompt.p_pos.v && !el->el_refresh.r_cursor.v && rhdiff > 1) { /* * have a right-hand side prompt that will fit * on the end of the first line with at least * one character gap to the input buffer. */ while (--rhdiff > 0) /* pad out with spaces */ re_putc(el, ' ', 1); prompt_print(el, EL_RPROMPT); } else { el->el_rprompt.p_pos.h = 0; /* flag "not using rprompt" */ el->el_rprompt.p_pos.v = 0; } re_putc(el, '\0', 0); /* make line ended with NUL, no cursor shift */ el->el_refresh.r_newcv = el->el_refresh.r_cursor.v; ELRE_DEBUG(1, (__F, "term.h=%d vcur.h=%d vcur.v=%d vdisplay[0]=\r\n:%80.80s:\r\n", el->el_terminal.t_size.h, el->el_refresh.r_cursor.h, el->el_refresh.r_cursor.v, ct_encode_string(el->el_vdisplay[0], &el->el_scratch))); ELRE_DEBUG(1, (__F, "updating %d lines.\r\n", el->el_refresh.r_newcv)); for (i = 0; i <= el->el_refresh.r_newcv; i++) { /* NOTE THAT re_update_line MAY CHANGE el_display[i] */ re_update_line(el, el->el_display[i], el->el_vdisplay[i], i); /* * Copy the new line to be the current one, and pad out with * spaces to the full width of the terminal so that if we try * moving the cursor by writing the character that is at the * end of the screen line, it won't be a NUL or some old * leftover stuff. */ re__copy_and_pad(el->el_display[i], el->el_vdisplay[i], (size_t) el->el_terminal.t_size.h); } ELRE_DEBUG(1, (__F, "\r\nel->el_refresh.r_cursor.v=%d,el->el_refresh.r_oldcv=%d i=%d\r\n", el->el_refresh.r_cursor.v, el->el_refresh.r_oldcv, i)); if (el->el_refresh.r_oldcv > el->el_refresh.r_newcv) for (; i <= el->el_refresh.r_oldcv; i++) { terminal_move_to_line(el, i); terminal_move_to_char(el, 0); /* This wcslen should be safe even with MB_FILL_CHARs */ terminal_clear_EOL(el, (int) wcslen(el->el_display[i])); #ifdef DEBUG_REFRESH terminal_overwrite(el, L"C\b", 2); #endif /* DEBUG_REFRESH */ el->el_display[i][0] = '\0'; } el->el_refresh.r_oldcv = el->el_refresh.r_newcv; /* set for next time */ ELRE_DEBUG(1, (__F, "\r\ncursor.h = %d, cursor.v = %d, cur.h = %d, cur.v = %d\r\n", el->el_refresh.r_cursor.h, el->el_refresh.r_cursor.v, cur.h, cur.v)); terminal_move_to_line(el, cur.v); /* go to where the cursor is */ terminal_move_to_char(el, cur.h); } /* re_goto_bottom(): * used to go to last used screen line */ libedit_private void re_goto_bottom(EditLine *el) { terminal_move_to_line(el, el->el_refresh.r_oldcv); terminal__putc(el, '\n'); re_clear_display(el); terminal__flush(el); } /* re_insert(): * insert num characters of s into d (in front of the character) * at dat, maximum length of d is dlen */ static void /*ARGSUSED*/ re_insert(EditLine *el __attribute__((__unused__)), wchar_t *d, int dat, int dlen, wchar_t *s, int num) { wchar_t *a, *b; if (num <= 0) return; if (num > dlen - dat) num = dlen - dat; ELRE_DEBUG(1, (__F, "re_insert() starting: %d at %d max %d, d == \"%s\"\n", num, dat, dlen, ct_encode_string(d, &el->el_scratch))); ELRE_DEBUG(1, (__F, "s == \"%s\"\n", ct_encode_string(s, &el->el_scratch))); /* open up the space for num chars */ if (num > 0) { b = d + dlen - 1; a = b - num; while (a >= &d[dat]) *b-- = *a--; d[dlen] = '\0'; /* just in case */ } ELRE_DEBUG(1, (__F, "re_insert() after insert: %d at %d max %d, d == \"%s\"\n", num, dat, dlen, ct_encode_string(d, &el->el_scratch))); ELRE_DEBUG(1, (__F, "s == \"%s\"\n", ct_encode_string(s, &el->el_scratch))); /* copy the characters */ for (a = d + dat; (a < d + dlen) && (num > 0); num--) *a++ = *s++; #ifdef notyet /* ct_encode_string() uses a static buffer, so we can't conveniently * encode both d & s here */ ELRE_DEBUG(1, (__F, "re_insert() after copy: %d at %d max %d, %s == \"%s\"\n", num, dat, dlen, d, s)); ELRE_DEBUG(1, (__F, "s == \"%s\"\n", s)); #endif } /* re_delete(): * delete num characters d at dat, maximum length of d is dlen */ static void /*ARGSUSED*/ re_delete(EditLine *el __attribute__((__unused__)), wchar_t *d, int dat, int dlen, int num) { wchar_t *a, *b; if (num <= 0) return; if (dat + num >= dlen) { d[dat] = '\0'; return; } ELRE_DEBUG(1, (__F, "re_delete() starting: %d at %d max %d, d == \"%s\"\n", num, dat, dlen, ct_encode_string(d, &el->el_scratch))); /* open up the space for num chars */ if (num > 0) { b = d + dat; a = b + num; while (a < &d[dlen]) *b++ = *a++; d[dlen] = '\0'; /* just in case */ } ELRE_DEBUG(1, (__F, "re_delete() after delete: %d at %d max %d, d == \"%s\"\n", num, dat, dlen, ct_encode_string(d, &el->el_scratch))); } /* re__strncopy(): * Like strncpy without padding. */ static void re__strncopy(wchar_t *a, wchar_t *b, size_t n) { while (n-- && *b) *a++ = *b++; } /* re_clear_eol(): * Find the number of characters we need to clear till the end of line * in order to make sure that we have cleared the previous contents of * the line. fx and sx is the number of characters inserted or deleted * in the first or second diff, diff is the difference between the * number of characters between the new and old line. */ static void re_clear_eol(EditLine *el, int fx, int sx, int diff) { ELRE_DEBUG(1, (__F, "re_clear_eol sx %d, fx %d, diff %d\n", sx, fx, diff)); if (fx < 0) fx = -fx; if (sx < 0) sx = -sx; if (fx > diff) diff = fx; if (sx > diff) diff = sx; ELRE_DEBUG(1, (__F, "re_clear_eol %d\n", diff)); terminal_clear_EOL(el, diff); } /***************************************************************** re_update_line() is based on finding the middle difference of each line on the screen; vis: /old first difference /beginning of line | /old last same /old EOL v v v v old: eddie> Oh, my little gruntle-buggy is to me, as lurgid as new: eddie> Oh, my little buggy says to me, as lurgid as ^ ^ ^ ^ \beginning of line | \new last same \new end of line \new first difference all are character pointers for the sake of speed. Special cases for no differences, as well as for end of line additions must be handled. **************************************************************** */ /* Minimum at which doing an insert it "worth it". This should be about * half the "cost" of going into insert mode, inserting a character, and * going back out. This should really be calculated from the termcap * data... For the moment, a good number for ANSI terminals. */ #define MIN_END_KEEP 4 static void re_update_line(EditLine *el, wchar_t *old, wchar_t *new, int i) { wchar_t *o, *n, *p, c; wchar_t *ofd, *ols, *oe, *nfd, *nls, *ne; wchar_t *osb, *ose, *nsb, *nse; int fx, sx; size_t len; /* * find first diff */ for (o = old, n = new; *o && (*o == *n); o++, n++) continue; ofd = o; nfd = n; /* * Find the end of both old and new */ while (*o) o++; /* * Remove any trailing blanks off of the end, being careful not to * back up past the beginning. */ while (ofd < o) { if (o[-1] != ' ') break; o--; } oe = o; *oe = '\0'; while (*n) n++; /* remove blanks from end of new */ while (nfd < n) { if (n[-1] != ' ') break; n--; } ne = n; *ne = '\0'; /* * if no diff, continue to next line of redraw */ if (*ofd == '\0' && *nfd == '\0') { ELRE_DEBUG(1, (__F, "no difference.\r\n")); return; } /* * find last same pointer */ while ((o > ofd) && (n > nfd) && (*--o == *--n)) continue; ols = ++o; nls = ++n; /* * find same beginning and same end */ osb = ols; nsb = nls; ose = ols; nse = nls; /* * case 1: insert: scan from nfd to nls looking for *ofd */ if (*ofd) { for (c = *ofd, n = nfd; n < nls; n++) { if (c == *n) { for (o = ofd, p = n; p < nls && o < ols && *o == *p; o++, p++) continue; /* * if the new match is longer and it's worth * keeping, then we take it */ if (((nse - nsb) < (p - n)) && (2 * (p - n) > n - nfd)) { nsb = n; nse = p; osb = ofd; ose = o; } } } } /* * case 2: delete: scan from ofd to ols looking for *nfd */ if (*nfd) { for (c = *nfd, o = ofd; o < ols; o++) { if (c == *o) { for (n = nfd, p = o; p < ols && n < nls && *p == *n; p++, n++) continue; /* * if the new match is longer and it's worth * keeping, then we take it */ if (((ose - osb) < (p - o)) && (2 * (p - o) > o - ofd)) { nsb = nfd; nse = n; osb = o; ose = p; } } } } /* * Pragmatics I: If old trailing whitespace or not enough characters to * save to be worth it, then don't save the last same info. */ if ((oe - ols) < MIN_END_KEEP) { ols = oe; nls = ne; } /* * Pragmatics II: if the terminal isn't smart enough, make the data * dumber so the smart update doesn't try anything fancy */ /* * fx is the number of characters we need to insert/delete: in the * beginning to bring the two same begins together */ fx = (int)((nsb - nfd) - (osb - ofd)); /* * sx is the number of characters we need to insert/delete: in the * end to bring the two same last parts together */ sx = (int)((nls - nse) - (ols - ose)); if (!EL_CAN_INSERT) { if (fx > 0) { osb = ols; ose = ols; nsb = nls; nse = nls; } if (sx > 0) { ols = oe; nls = ne; } if ((ols - ofd) < (nls - nfd)) { ols = oe; nls = ne; } } if (!EL_CAN_DELETE) { if (fx < 0) { osb = ols; ose = ols; nsb = nls; nse = nls; } if (sx < 0) { ols = oe; nls = ne; } if ((ols - ofd) > (nls - nfd)) { ols = oe; nls = ne; } } /* * Pragmatics III: make sure the middle shifted pointers are correct if * they don't point to anything (we may have moved ols or nls). */ /* if the change isn't worth it, don't bother */ /* was: if (osb == ose) */ if ((ose - osb) < MIN_END_KEEP) { osb = ols; ose = ols; nsb = nls; nse = nls; } /* * Now that we are done with pragmatics we recompute fx, sx */ fx = (int)((nsb - nfd) - (osb - ofd)); sx = (int)((nls - nse) - (ols - ose)); ELRE_DEBUG(1, (__F, "fx %d, sx %d\n", fx, sx)); ELRE_DEBUG(1, (__F, "ofd %td, osb %td, ose %td, ols %td, oe %td\n", ofd - old, osb - old, ose - old, ols - old, oe - old)); ELRE_DEBUG(1, (__F, "nfd %td, nsb %td, nse %td, nls %td, ne %td\n", nfd - new, nsb - new, nse - new, nls - new, ne - new)); ELRE_DEBUG(1, (__F, "xxx-xxx:\"00000000001111111111222222222233333333334\"\r\n")); ELRE_DEBUG(1, (__F, "xxx-xxx:\"01234567890123456789012345678901234567890\"\r\n")); #ifdef DEBUG_REFRESH re_printstr(el, "old- oe", old, oe); re_printstr(el, "new- ne", new, ne); re_printstr(el, "old-ofd", old, ofd); re_printstr(el, "new-nfd", new, nfd); re_printstr(el, "ofd-osb", ofd, osb); re_printstr(el, "nfd-nsb", nfd, nsb); re_printstr(el, "osb-ose", osb, ose); re_printstr(el, "nsb-nse", nsb, nse); re_printstr(el, "ose-ols", ose, ols); re_printstr(el, "nse-nls", nse, nls); re_printstr(el, "ols- oe", ols, oe); re_printstr(el, "nls- ne", nls, ne); #endif /* DEBUG_REFRESH */ /* * el_cursor.v to this line i MUST be in this routine so that if we * don't have to change the line, we don't move to it. el_cursor.h to * first diff char */ terminal_move_to_line(el, i); /* * at this point we have something like this: * * /old /ofd /osb /ose /ols /oe * v.....................v v..................v v........v * eddie> Oh, my fredded gruntle-buggy is to me, as foo var lurgid as * eddie> Oh, my fredded quiux buggy is to me, as gruntle-lurgid as * ^.....................^ ^..................^ ^........^ * \new \nfd \nsb \nse \nls \ne * * fx is the difference in length between the chars between nfd and * nsb, and the chars between ofd and osb, and is thus the number of * characters to delete if < 0 (new is shorter than old, as above), * or insert (new is longer than short). * * sx is the same for the second differences. */ /* * if we have a net insert on the first difference, AND inserting the * net amount ((nsb-nfd) - (osb-ofd)) won't push the last useful * character (which is ne if nls != ne, otherwise is nse) off the edge * of the screen (el->el_terminal.t_size.h) else we do the deletes first * so that we keep everything we need to. */ /* * if the last same is the same like the end, there is no last same * part, otherwise we want to keep the last same part set p to the * last useful old character */ p = (ols != oe) ? oe : ose; /* * if (There is a diffence in the beginning) && (we need to insert * characters) && (the number of characters to insert is less than * the term width) * We need to do an insert! * else if (we need to delete characters) * We need to delete characters! * else * No insert or delete */ if ((nsb != nfd) && fx > 0 && ((p - old) + fx <= el->el_terminal.t_size.h)) { ELRE_DEBUG(1, (__F, "first diff insert at %td...\r\n", nfd - new)); /* * Move to the first char to insert, where the first diff is. */ terminal_move_to_char(el, (int)(nfd - new)); /* * Check if we have stuff to keep at end */ if (nsb != ne) { ELRE_DEBUG(1, (__F, "with stuff to keep at end\r\n")); /* * insert fx chars of new starting at nfd */ if (fx > 0) { ELRE_DEBUG(!EL_CAN_INSERT, (__F, "ERROR: cannot insert in early first diff\n")); terminal_insertwrite(el, nfd, fx); re_insert(el, old, (int)(ofd - old), el->el_terminal.t_size.h, nfd, fx); } /* * write (nsb-nfd) - fx chars of new starting at * (nfd + fx) */ len = (size_t) ((nsb - nfd) - fx); terminal_overwrite(el, (nfd + fx), len); re__strncopy(ofd + fx, nfd + fx, len); } else { ELRE_DEBUG(1, (__F, "without anything to save\r\n")); len = (size_t)(nsb - nfd); terminal_overwrite(el, nfd, len); re__strncopy(ofd, nfd, len); /* * Done */ return; } } else if (fx < 0) { ELRE_DEBUG(1, (__F, "first diff delete at %td...\r\n", ofd - old)); /* * move to the first char to delete where the first diff is */ terminal_move_to_char(el, (int)(ofd - old)); /* * Check if we have stuff to save */ if (osb != oe) { ELRE_DEBUG(1, (__F, "with stuff to save at end\r\n")); /* * fx is less than zero *always* here but we check * for code symmetry */ if (fx < 0) { ELRE_DEBUG(!EL_CAN_DELETE, (__F, "ERROR: cannot delete in first diff\n")); terminal_deletechars(el, -fx); re_delete(el, old, (int)(ofd - old), el->el_terminal.t_size.h, -fx); } /* * write (nsb-nfd) chars of new starting at nfd */ len = (size_t) (nsb - nfd); terminal_overwrite(el, nfd, len); re__strncopy(ofd, nfd, len); } else { ELRE_DEBUG(1, (__F, "but with nothing left to save\r\n")); /* * write (nsb-nfd) chars of new starting at nfd */ terminal_overwrite(el, nfd, (size_t)(nsb - nfd)); re_clear_eol(el, fx, sx, (int)((oe - old) - (ne - new))); /* * Done */ return; } } else fx = 0; if (sx < 0 && (ose - old) + fx < el->el_terminal.t_size.h) { ELRE_DEBUG(1, (__F, "second diff delete at %td...\r\n", (ose - old) + fx)); /* * Check if we have stuff to delete */ /* * fx is the number of characters inserted (+) or deleted (-) */ terminal_move_to_char(el, (int)((ose - old) + fx)); /* * Check if we have stuff to save */ if (ols != oe) { ELRE_DEBUG(1, (__F, "with stuff to save at end\r\n")); /* * Again a duplicate test. */ if (sx < 0) { ELRE_DEBUG(!EL_CAN_DELETE, (__F, "ERROR: cannot delete in second diff\n")); terminal_deletechars(el, -sx); } /* * write (nls-nse) chars of new starting at nse */ terminal_overwrite(el, nse, (size_t)(nls - nse)); } else { ELRE_DEBUG(1, (__F, "but with nothing left to save\r\n")); terminal_overwrite(el, nse, (size_t)(nls - nse)); re_clear_eol(el, fx, sx, (int)((oe - old) - (ne - new))); } } /* * if we have a first insert AND WE HAVEN'T ALREADY DONE IT... */ if ((nsb != nfd) && (osb - ofd) <= (nsb - nfd) && (fx == 0)) { ELRE_DEBUG(1, (__F, "late first diff insert at %td...\r\n", nfd - new)); terminal_move_to_char(el, (int)(nfd - new)); /* * Check if we have stuff to keep at the end */ if (nsb != ne) { ELRE_DEBUG(1, (__F, "with stuff to keep at end\r\n")); /* * We have to recalculate fx here because we set it * to zero above as a flag saying that we hadn't done * an early first insert. */ fx = (int)((nsb - nfd) - (osb - ofd)); if (fx > 0) { /* * insert fx chars of new starting at nfd */ ELRE_DEBUG(!EL_CAN_INSERT, (__F, "ERROR: cannot insert in late first diff\n")); terminal_insertwrite(el, nfd, fx); re_insert(el, old, (int)(ofd - old), el->el_terminal.t_size.h, nfd, fx); } /* * write (nsb-nfd) - fx chars of new starting at * (nfd + fx) */ len = (size_t) ((nsb - nfd) - fx); terminal_overwrite(el, (nfd + fx), len); re__strncopy(ofd + fx, nfd + fx, len); } else { ELRE_DEBUG(1, (__F, "without anything to save\r\n")); len = (size_t) (nsb - nfd); terminal_overwrite(el, nfd, len); re__strncopy(ofd, nfd, len); } } /* * line is now NEW up to nse */ if (sx >= 0) { ELRE_DEBUG(1, (__F, "second diff insert at %d...\r\n", (int)(nse - new))); terminal_move_to_char(el, (int)(nse - new)); if (ols != oe) { ELRE_DEBUG(1, (__F, "with stuff to keep at end\r\n")); if (sx > 0) { /* insert sx chars of new starting at nse */ ELRE_DEBUG(!EL_CAN_INSERT, (__F, "ERROR: cannot insert in second diff\n")); terminal_insertwrite(el, nse, sx); } /* * write (nls-nse) - sx chars of new starting at * (nse + sx) */ terminal_overwrite(el, (nse + sx), (size_t)((nls - nse) - sx)); } else { ELRE_DEBUG(1, (__F, "without anything to save\r\n")); terminal_overwrite(el, nse, (size_t)(nls - nse)); /* * No need to do a clear-to-end here because we were * doing a second insert, so we will have over * written all of the old string. */ } } ELRE_DEBUG(1, (__F, "done.\r\n")); } /* re__copy_and_pad(): * Copy string and pad with spaces */ static void re__copy_and_pad(wchar_t *dst, const wchar_t *src, size_t width) { size_t i; for (i = 0; i < width; i++) { if (*src == '\0') break; *dst++ = *src++; } for (; i < width; i++) *dst++ = ' '; *dst = '\0'; } /* re_refresh_cursor(): * Move to the new cursor position */ libedit_private void re_refresh_cursor(EditLine *el) { wchar_t *cp; int h, v, th, w; if (el->el_line.cursor >= el->el_line.lastchar) { if (el->el_map.current == el->el_map.alt && el->el_line.lastchar != el->el_line.buffer) el->el_line.cursor = el->el_line.lastchar - 1; else el->el_line.cursor = el->el_line.lastchar; } /* first we must find where the cursor is... */ h = el->el_prompt.p_pos.h; v = el->el_prompt.p_pos.v; th = el->el_terminal.t_size.h; /* optimize for speed */ /* do input buffer to el->el_line.cursor */ for (cp = el->el_line.buffer; cp < el->el_line.cursor; cp++) { switch (ct_chr_class(*cp)) { case CHTYPE_NL: /* handle newline in data part too */ h = 0; v++; break; case CHTYPE_TAB: /* if a tab, to next tab stop */ while (++h & 07) continue; break; default: w = wcwidth(*cp); if (w > 1 && h + w > th) { /* won't fit on line */ h = 0; v++; } h += ct_visual_width(*cp); break; } if (h >= th) { /* check, extra long tabs picked up here also */ h -= th; v++; } } /* if we have a next character, and it's a doublewidth one, we need to * check whether we need to linebreak for it to fit */ if (cp < el->el_line.lastchar && (w = wcwidth(*cp)) > 1) if (h + w > th) { h = 0; v++; } /* now go there */ terminal_move_to_line(el, v); terminal_move_to_char(el, h); terminal__flush(el); } /* re_fastputc(): * Add a character fast. */ static void re_fastputc(EditLine *el, wint_t c) { int w = wcwidth(c); while (w > 1 && el->el_cursor.h + w > el->el_terminal.t_size.h) re_fastputc(el, ' '); terminal__putc(el, c); el->el_display[el->el_cursor.v][el->el_cursor.h++] = c; while (--w > 0) el->el_display[el->el_cursor.v][el->el_cursor.h++] = MB_FILL_CHAR; if (el->el_cursor.h >= el->el_terminal.t_size.h) { /* if we must overflow */ el->el_cursor.h = 0; /* * If we would overflow (input is longer than terminal size), * emulate scroll by dropping first line and shuffling the rest. * We do this via pointer shuffling - it's safe in this case * and we avoid memcpy(). */ if (el->el_cursor.v + 1 >= el->el_terminal.t_size.v) { int i, lins = el->el_terminal.t_size.v; wchar_t *firstline = el->el_display[0]; for(i = 1; i < lins; i++) el->el_display[i - 1] = el->el_display[i]; re__copy_and_pad(firstline, L"", (size_t)0); el->el_display[i - 1] = firstline; } else { el->el_cursor.v++; el->el_refresh.r_oldcv++; } if (EL_HAS_AUTO_MARGINS) { if (EL_HAS_MAGIC_MARGINS) { terminal__putc(el, ' '); terminal__putc(el, '\b'); } } else { terminal__putc(el, '\r'); terminal__putc(el, '\n'); } } } /* re_fastaddc(): * we added just one char, handle it fast. * Assumes that screen cursor == real cursor */ libedit_private void re_fastaddc(EditLine *el) { wchar_t c; int rhdiff; c = el->el_line.cursor[-1]; if (c == '\t' || el->el_line.cursor != el->el_line.lastchar) { re_refresh(el); /* too hard to handle */ return; } rhdiff = el->el_terminal.t_size.h - el->el_cursor.h - el->el_rprompt.p_pos.h; if (el->el_rprompt.p_pos.h && rhdiff < 3) { re_refresh(el); /* clear out rprompt if less than 1 char gap */ return; } /* else (only do at end of line, no TAB) */ switch (ct_chr_class(c)) { case CHTYPE_TAB: /* already handled, should never happen here */ break; case CHTYPE_NL: case CHTYPE_PRINT: re_fastputc(el, c); break; case CHTYPE_ASCIICTL: case CHTYPE_NONPRINT: { wchar_t visbuf[VISUAL_WIDTH_MAX]; ssize_t i, n = ct_visual_char(visbuf, VISUAL_WIDTH_MAX, c); for (i = 0; n-- > 0; ++i) re_fastputc(el, visbuf[i]); break; } } terminal__flush(el); } /* re_clear_display(): * clear the screen buffers so that new new prompt starts fresh. */ libedit_private void re_clear_display(EditLine *el) { int i; el->el_cursor.v = 0; el->el_cursor.h = 0; for (i = 0; i < el->el_terminal.t_size.v; i++) el->el_display[i][0] = '\0'; el->el_refresh.r_oldcv = 0; } /* re_clear_lines(): * Make sure all lines are *really* blank */ libedit_private void re_clear_lines(EditLine *el) { if (EL_CAN_CEOL) { int i; for (i = el->el_refresh.r_oldcv; i >= 0; i--) { /* for each line on the screen */ terminal_move_to_line(el, i); terminal_move_to_char(el, 0); terminal_clear_EOL(el, el->el_terminal.t_size.h); } } else { terminal_move_to_line(el, el->el_refresh.r_oldcv); /* go to last line */ terminal__putc(el, '\r'); /* go to BOL */ terminal__putc(el, '\n'); /* go to new line */ } } heimdal-7.5.0/lib/libedit/src/vis.c0000644000175000017500000004414413026237312015176 0ustar niknik/* $NetBSD: vis.c,v 1.71 2016/01/14 20:41:23 christos Exp $ */ /*- * Copyright (c) 1989, 1993 * The Regents of the University of California. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the University nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ /*- * Copyright (c) 1999, 2005 The NetBSD Foundation, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include "config.h" #if defined(LIBC_SCCS) && !defined(lint) __RCSID("$NetBSD: vis.c,v 1.71 2016/01/14 20:41:23 christos Exp $"); #endif /* LIBC_SCCS and not lint */ #include #include #include #include #include #include #include #include #if !HAVE_VIS || !HAVE_SVIS #include #include #include #include /* * The reason for going through the trouble to deal with character encodings * in vis(3), is that we use this to safe encode output of commands. This * safe encoding varies depending on the character set. For example if we * display ps output in French, we don't want to display French characters * as M-foo. */ static wchar_t *do_svis(wchar_t *, wint_t, int, wint_t, const wchar_t *); #undef BELL #define BELL L'\a' #if defined(LC_C_LOCALE) #define iscgraph(c) isgraph_l(c, LC_C_LOCALE) #else /* Keep it simple for now, no locale stuff */ #define iscgraph(c) isgraph(c) #ifdef notyet #include static int iscgraph(int c) { int rv; char *ol; ol = setlocale(LC_CTYPE, "C"); rv = isgraph(c); if (ol) setlocale(LC_CTYPE, ol); return rv; } #endif #endif #define ISGRAPH(flags, c) \ (((flags) & VIS_NOLOCALE) ? iscgraph(c) : iswgraph(c)) #define iswoctal(c) (((u_char)(c)) >= L'0' && ((u_char)(c)) <= L'7') #define iswwhite(c) (c == L' ' || c == L'\t' || c == L'\n') #define iswsafe(c) (c == L'\b' || c == BELL || c == L'\r') #define xtoa(c) L"0123456789abcdef"[c] #define XTOA(c) L"0123456789ABCDEF"[c] #define MAXEXTRAS 30 static const wchar_t char_shell[] = L"'`\";&<>()|{}]\\$!^~"; static const wchar_t char_glob[] = L"*?[#"; /* * This is do_hvis, for HTTP style (RFC 1808) */ static wchar_t * do_hvis(wchar_t *dst, wint_t c, int flags, wint_t nextc, const wchar_t *extra) { if (iswalnum(c) /* safe */ || c == L'$' || c == L'-' || c == L'_' || c == L'.' || c == L'+' /* extra */ || c == L'!' || c == L'*' || c == L'\'' || c == L'(' || c == L')' || c == L',') dst = do_svis(dst, c, flags, nextc, extra); else { *dst++ = L'%'; *dst++ = xtoa(((unsigned int)c >> 4) & 0xf); *dst++ = xtoa((unsigned int)c & 0xf); } return dst; } /* * This is do_mvis, for Quoted-Printable MIME (RFC 2045) * NB: No handling of long lines or CRLF. */ static wchar_t * do_mvis(wchar_t *dst, wint_t c, int flags, wint_t nextc, const wchar_t *extra) { if ((c != L'\n') && /* Space at the end of the line */ ((iswspace(c) && (nextc == L'\r' || nextc == L'\n')) || /* Out of range */ (!iswspace(c) && (c < 33 || (c > 60 && c < 62) || c > 126)) || /* Specific char to be escaped */ wcschr(L"#$@[\\]^`{|}~", c) != NULL)) { *dst++ = L'='; *dst++ = XTOA(((unsigned int)c >> 4) & 0xf); *dst++ = XTOA((unsigned int)c & 0xf); } else dst = do_svis(dst, c, flags, nextc, extra); return dst; } /* * Output single byte of multibyte character. */ static wchar_t * do_mbyte(wchar_t *dst, wint_t c, int flags, wint_t nextc, int iswextra) { if (flags & VIS_CSTYLE) { switch (c) { case L'\n': *dst++ = L'\\'; *dst++ = L'n'; return dst; case L'\r': *dst++ = L'\\'; *dst++ = L'r'; return dst; case L'\b': *dst++ = L'\\'; *dst++ = L'b'; return dst; case BELL: *dst++ = L'\\'; *dst++ = L'a'; return dst; case L'\v': *dst++ = L'\\'; *dst++ = L'v'; return dst; case L'\t': *dst++ = L'\\'; *dst++ = L't'; return dst; case L'\f': *dst++ = L'\\'; *dst++ = L'f'; return dst; case L' ': *dst++ = L'\\'; *dst++ = L's'; return dst; case L'\0': *dst++ = L'\\'; *dst++ = L'0'; if (iswoctal(nextc)) { *dst++ = L'0'; *dst++ = L'0'; } return dst; /* We cannot encode these characters in VIS_CSTYLE * because they special meaning */ case L'n': case L'r': case L'b': case L'a': case L'v': case L't': case L'f': case L's': case L'0': case L'M': case L'^': case L'$': /* vis(1) -l */ break; default: if (ISGRAPH(flags, c) && !iswoctal(c)) { *dst++ = L'\\'; *dst++ = c; return dst; } } } if (iswextra || ((c & 0177) == L' ') || (flags & VIS_OCTAL)) { *dst++ = L'\\'; *dst++ = (u_char)(((u_int32_t)(u_char)c >> 6) & 03) + L'0'; *dst++ = (u_char)(((u_int32_t)(u_char)c >> 3) & 07) + L'0'; *dst++ = (c & 07) + L'0'; } else { if ((flags & VIS_NOSLASH) == 0) *dst++ = L'\\'; if (c & 0200) { c &= 0177; *dst++ = L'M'; } if (iswcntrl(c)) { *dst++ = L'^'; if (c == 0177) *dst++ = L'?'; else *dst++ = c + L'@'; } else { *dst++ = L'-'; *dst++ = c; } } return dst; } /* * This is do_vis, the central code of vis. * dst: Pointer to the destination buffer * c: Character to encode * flags: Flags word * nextc: The character following 'c' * extra: Pointer to the list of extra characters to be * backslash-protected. */ static wchar_t * do_svis(wchar_t *dst, wint_t c, int flags, wint_t nextc, const wchar_t *extra) { int iswextra, i, shft; uint64_t bmsk, wmsk; iswextra = wcschr(extra, c) != NULL; if (!iswextra && (ISGRAPH(flags, c) || iswwhite(c) || ((flags & VIS_SAFE) && iswsafe(c)))) { *dst++ = c; return dst; } /* See comment in istrsenvisx() output loop, below. */ wmsk = 0; for (i = sizeof(wmsk) - 1; i >= 0; i--) { shft = i * NBBY; bmsk = (uint64_t)0xffLL << shft; wmsk |= bmsk; if ((c & wmsk) || i == 0) dst = do_mbyte(dst, (wint_t)( (uint64_t)(c & bmsk) >> shft), flags, nextc, iswextra); } return dst; } typedef wchar_t *(*visfun_t)(wchar_t *, wint_t, int, wint_t, const wchar_t *); /* * Return the appropriate encoding function depending on the flags given. */ static visfun_t getvisfun(int flags) { if (flags & VIS_HTTPSTYLE) return do_hvis; if (flags & VIS_MIMESTYLE) return do_mvis; return do_svis; } /* * Expand list of extra characters to not visually encode. */ static wchar_t * makeextralist(int flags, const char *src) { wchar_t *dst, *d; size_t len; const wchar_t *s; len = strlen(src); if ((dst = calloc(len + MAXEXTRAS, sizeof(*dst))) == NULL) return NULL; if ((flags & VIS_NOLOCALE) || mbstowcs(dst, src, len) == (size_t)-1) { size_t i; for (i = 0; i < len; i++) dst[i] = (wchar_t)(u_char)src[i]; d = dst + len; } else d = dst + wcslen(dst); if (flags & VIS_GLOB) for (s = char_glob; *s; *d++ = *s++) continue; if (flags & VIS_SHELL) for (s = char_shell; *s; *d++ = *s++) continue; if (flags & VIS_SP) *d++ = L' '; if (flags & VIS_TAB) *d++ = L'\t'; if (flags & VIS_NL) *d++ = L'\n'; if ((flags & VIS_NOSLASH) == 0) *d++ = L'\\'; *d = L'\0'; return dst; } /* * istrsenvisx() * The main internal function. * All user-visible functions call this one. */ static int istrsenvisx(char **mbdstp, size_t *dlen, const char *mbsrc, size_t mblength, int flags, const char *mbextra, int *cerr_ptr) { wchar_t *dst, *src, *pdst, *psrc, *start, *extra; size_t len, olen; uint64_t bmsk, wmsk; wint_t c; visfun_t f; int clen = 0, cerr, error = -1, i, shft; char *mbdst, *mdst; ssize_t mbslength, maxolen; _DIAGASSERT(mbdstp != NULL); _DIAGASSERT(mbsrc != NULL || mblength == 0); _DIAGASSERT(mbextra != NULL); /* * Input (mbsrc) is a char string considered to be multibyte * characters. The input loop will read this string pulling * one character, possibly multiple bytes, from mbsrc and * converting each to wchar_t in src. * * The vis conversion will be done using the wide char * wchar_t string. * * This will then be converted back to a multibyte string to * return to the caller. */ /* Allocate space for the wide char strings */ psrc = pdst = extra = NULL; mdst = NULL; if ((psrc = calloc(mblength + 1, sizeof(*psrc))) == NULL) return -1; if ((pdst = calloc((4 * mblength) + 1, sizeof(*pdst))) == NULL) goto out; if (*mbdstp == NULL) { if ((mdst = calloc((4 * mblength) + 1, sizeof(*mdst))) == NULL) goto out; *mbdstp = mdst; } mbdst = *mbdstp; dst = pdst; src = psrc; if (flags & VIS_NOLOCALE) { /* Do one byte at a time conversion */ cerr = 1; } else { /* Use caller's multibyte conversion error flag. */ cerr = cerr_ptr ? *cerr_ptr : 0; } /* * Input loop. * Handle up to mblength characters (not bytes). We do not * stop at NULs because we may be processing a block of data * that includes NULs. */ mbslength = (ssize_t)mblength; /* * When inputing a single character, must also read in the * next character for nextc, the look-ahead character. */ if (mbslength == 1) mbslength++; while (mbslength > 0) { /* Convert one multibyte character to wchar_t. */ if (!cerr) clen = mbtowc(src, mbsrc, MB_LEN_MAX); if (cerr || clen < 0) { /* Conversion error, process as a byte instead. */ *src = (wint_t)(u_char)*mbsrc; clen = 1; cerr = 1; } if (clen == 0) /* * NUL in input gives 0 return value. process * as single NUL byte and keep going. */ clen = 1; /* Advance buffer character pointer. */ src++; /* Advance input pointer by number of bytes read. */ mbsrc += clen; /* Decrement input byte count. */ mbslength -= clen; } len = src - psrc; src = psrc; /* * In the single character input case, we will have actually * processed two characters, c and nextc. Reset len back to * just a single character. */ if (mblength < len) len = mblength; /* Convert extra argument to list of characters for this mode. */ extra = makeextralist(flags, mbextra); if (!extra) { if (dlen && *dlen == 0) { errno = ENOSPC; goto out; } *mbdst = '\0'; /* can't create extra, return "" */ error = 0; goto out; } /* Look up which processing function to call. */ f = getvisfun(flags); /* * Main processing loop. * Call do_Xvis processing function one character at a time * with next character available for look-ahead. */ for (start = dst; len > 0; len--) { c = *src++; dst = (*f)(dst, c, flags, len >= 1 ? *src : L'\0', extra); if (dst == NULL) { errno = ENOSPC; goto out; } } /* Terminate the string in the buffer. */ *dst = L'\0'; /* * Output loop. * Convert wchar_t string back to multibyte output string. * If we have hit a multi-byte conversion error on input, * output byte-by-byte here. Else use wctomb(). */ len = wcslen(start); maxolen = dlen ? *dlen : (wcslen(start) * MB_LEN_MAX + 1); olen = 0; for (dst = start; len > 0; len--) { if (!cerr) clen = wctomb(mbdst, *dst); if (cerr || clen < 0) { /* * Conversion error, process as a byte(s) instead. * Examine each byte and higher-order bytes for * data. E.g., * 0x000000000000a264 -> a2 64 * 0x000000001f00a264 -> 1f 00 a2 64 */ clen = 0; wmsk = 0; for (i = sizeof(wmsk) - 1; i >= 0; i--) { shft = i * NBBY; bmsk = (uint64_t)0xffLL << shft; wmsk |= bmsk; if ((*dst & wmsk) || i == 0) mbdst[clen++] = (char)( (uint64_t)(*dst & bmsk) >> shft); } cerr = 1; } /* If this character would exceed our output limit, stop. */ if (olen + clen > (size_t)maxolen) break; /* Advance output pointer by number of bytes written. */ mbdst += clen; /* Advance buffer character pointer. */ dst++; /* Incrment output character count. */ olen += clen; } /* Terminate the output string. */ *mbdst = '\0'; if (flags & VIS_NOLOCALE) { /* Pass conversion error flag out. */ if (cerr_ptr) *cerr_ptr = cerr; } free(extra); free(pdst); free(psrc); return (int)olen; out: free(extra); free(pdst); free(psrc); free(mdst); return error; } static int istrsenvisxl(char **mbdstp, size_t *dlen, const char *mbsrc, int flags, const char *mbextra, int *cerr_ptr) { return istrsenvisx(mbdstp, dlen, mbsrc, mbsrc != NULL ? strlen(mbsrc) : 0, flags, mbextra, cerr_ptr); } #endif #if !HAVE_SVIS /* * The "svis" variants all take an "extra" arg that is a pointer * to a NUL-terminated list of characters to be encoded, too. * These functions are useful e. g. to encode strings in such a * way so that they are not interpreted by a shell. */ char * svis(char *mbdst, int c, int flags, int nextc, const char *mbextra) { char cc[2]; int ret; cc[0] = c; cc[1] = nextc; ret = istrsenvisx(&mbdst, NULL, cc, 1, flags, mbextra, NULL); if (ret < 0) return NULL; return mbdst + ret; } char * snvis(char *mbdst, size_t dlen, int c, int flags, int nextc, const char *mbextra) { char cc[2]; int ret; cc[0] = c; cc[1] = nextc; ret = istrsenvisx(&mbdst, &dlen, cc, 1, flags, mbextra, NULL); if (ret < 0) return NULL; return mbdst + ret; } int strsvis(char *mbdst, const char *mbsrc, int flags, const char *mbextra) { return istrsenvisxl(&mbdst, NULL, mbsrc, flags, mbextra, NULL); } int strsnvis(char *mbdst, size_t dlen, const char *mbsrc, int flags, const char *mbextra) { return istrsenvisxl(&mbdst, &dlen, mbsrc, flags, mbextra, NULL); } int strsvisx(char *mbdst, const char *mbsrc, size_t len, int flags, const char *mbextra) { return istrsenvisx(&mbdst, NULL, mbsrc, len, flags, mbextra, NULL); } int strsnvisx(char *mbdst, size_t dlen, const char *mbsrc, size_t len, int flags, const char *mbextra) { return istrsenvisx(&mbdst, &dlen, mbsrc, len, flags, mbextra, NULL); } int strsenvisx(char *mbdst, size_t dlen, const char *mbsrc, size_t len, int flags, const char *mbextra, int *cerr_ptr) { return istrsenvisx(&mbdst, &dlen, mbsrc, len, flags, mbextra, cerr_ptr); } #endif #if !HAVE_VIS /* * vis - visually encode characters */ char * vis(char *mbdst, int c, int flags, int nextc) { char cc[2]; int ret; cc[0] = c; cc[1] = nextc; ret = istrsenvisx(&mbdst, NULL, cc, 1, flags, "", NULL); if (ret < 0) return NULL; return mbdst + ret; } char * nvis(char *mbdst, size_t dlen, int c, int flags, int nextc) { char cc[2]; int ret; cc[0] = c; cc[1] = nextc; ret = istrsenvisx(&mbdst, &dlen, cc, 1, flags, "", NULL); if (ret < 0) return NULL; return mbdst + ret; } /* * strvis - visually encode characters from src into dst * * Dst must be 4 times the size of src to account for possible * expansion. The length of dst, not including the trailing NULL, * is returned. */ int strvis(char *mbdst, const char *mbsrc, int flags) { return istrsenvisxl(&mbdst, NULL, mbsrc, flags, "", NULL); } int strnvis(char *mbdst, size_t dlen, const char *mbsrc, int flags) { return istrsenvisxl(&mbdst, &dlen, mbsrc, flags, "", NULL); } int stravis(char **mbdstp, const char *mbsrc, int flags) { *mbdstp = NULL; return istrsenvisxl(mbdstp, NULL, mbsrc, flags, "", NULL); } /* * strvisx - visually encode characters from src into dst * * Dst must be 4 times the size of src to account for possible * expansion. The length of dst, not including the trailing NULL, * is returned. * * Strvisx encodes exactly len characters from src into dst. * This is useful for encoding a block of data. */ int strvisx(char *mbdst, const char *mbsrc, size_t len, int flags) { return istrsenvisx(&mbdst, NULL, mbsrc, len, flags, "", NULL); } int strnvisx(char *mbdst, size_t dlen, const char *mbsrc, size_t len, int flags) { return istrsenvisx(&mbdst, &dlen, mbsrc, len, flags, "", NULL); } int strenvisx(char *mbdst, size_t dlen, const char *mbsrc, size_t len, int flags, int *cerr_ptr) { return istrsenvisx(&mbdst, &dlen, mbsrc, len, flags, "", cerr_ptr); } #endif heimdal-7.5.0/lib/libedit/src/chartype.h0000644000175000017500000001145113026237312016214 0ustar niknik/* $NetBSD: chartype.h,v 1.34 2016/05/09 21:46:56 christos Exp $ */ /*- * Copyright (c) 2009 The NetBSD Foundation, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #ifndef _h_chartype_f #define _h_chartype_f /* Ideally we should also test the value of the define to see if it * supports non-BMP code points without requiring UTF-16, but nothing * seems to actually advertise this properly, despite Unicode 3.1 having * been around since 2001... */ #if !defined(__NetBSD__) && !defined(__sun) && !(defined(__APPLE__) && defined(__MACH__)) && !defined(__OpenBSD__) && !defined(__FreeBSD__) #ifndef __STDC_ISO_10646__ /* In many places it is assumed that the first 127 code points are ASCII * compatible, so ensure wchar_t indeed does ISO 10646 and not some other * funky encoding that could break us in weird and wonderful ways. */ #error wchar_t must store ISO 10646 characters #endif #endif /* Oh for a with char32_t and __STDC_UTF_32__ in it... * ref: ISO/IEC DTR 19769 */ #if WCHAR_MAX < INT32_MAX #warning Build environment does not support non-BMP characters #endif /* * Conversion buffer */ typedef struct ct_buffer_t { char *cbuff; size_t csize; wchar_t *wbuff; size_t wsize; } ct_buffer_t; /* Encode a wide-character string and return the UTF-8 encoded result. */ char *ct_encode_string(const wchar_t *, ct_buffer_t *); /* Decode a (multi)?byte string and return the wide-character string result. */ wchar_t *ct_decode_string(const char *, ct_buffer_t *); /* Decode a (multi)?byte argv string array. * The pointer returned must be free()d when done. */ libedit_private wchar_t **ct_decode_argv(int, const char *[], ct_buffer_t *); /* Encode a character into the destination buffer, provided there is sufficient * buffer space available. Returns the number of bytes used up (zero if the * character cannot be encoded, -1 if there was not enough space available). */ libedit_private ssize_t ct_encode_char(char *, size_t, wchar_t); libedit_private size_t ct_enc_width(wchar_t); /* The maximum buffer size to hold the most unwieldy visual representation, * in this case \U+nnnnn. */ #define VISUAL_WIDTH_MAX ((size_t)8) /* The terminal is thought of in terms of X columns by Y lines. In the cases * where a wide character takes up more than one column, the adjacent * occupied column entries will contain this faux character. */ #define MB_FILL_CHAR ((wchar_t)-1) /* Visual width of character c, taking into account ^? , \0177 and \U+nnnnn * style visual expansions. */ libedit_private int ct_visual_width(wchar_t); /* Turn the given character into the appropriate visual format, matching * the width given by ct_visual_width(). Returns the number of characters used * up, or -1 if insufficient space. Buffer length is in count of wchar_t's. */ libedit_private ssize_t ct_visual_char(wchar_t *, size_t, wchar_t); /* Convert the given string into visual format, using the ct_visual_char() * function. Uses a static buffer, so not threadsafe. */ libedit_private const wchar_t *ct_visual_string(const wchar_t *, ct_buffer_t *); /* printable character, use ct_visual_width() to find out display width */ #define CHTYPE_PRINT ( 0) /* control character found inside the ASCII portion of the charset */ #define CHTYPE_ASCIICTL (-1) /* a \t */ #define CHTYPE_TAB (-2) /* a \n */ #define CHTYPE_NL (-3) /* non-printable character */ #define CHTYPE_NONPRINT (-4) /* classification of character c, as one of the above defines */ libedit_private int ct_chr_class(wchar_t c); #endif /* _chartype_f */ heimdal-7.5.0/lib/libedit/src/read.c0000644000175000017500000003335313026237312015310 0ustar niknik/* $NetBSD: read.c,v 1.101 2016/05/25 13:01:11 christos Exp $ */ /*- * Copyright (c) 1992, 1993 * The Regents of the University of California. All rights reserved. * * This code is derived from software contributed to Berkeley by * Christos Zoulas of Cornell University. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the University nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "config.h" #if !defined(lint) && !defined(SCCSID) #if 0 static char sccsid[] = "@(#)read.c 8.1 (Berkeley) 6/4/93"; #else __RCSID("$NetBSD: read.c,v 1.101 2016/05/25 13:01:11 christos Exp $"); #endif #endif /* not lint && not SCCSID */ /* * read.c: Terminal read functions */ #include #include #include #include #include #include #include #include "el.h" #include "fcns.h" #include "read.h" #define EL_MAXMACRO 10 struct macros { wchar_t **macro; int level; int offset; }; struct el_read_t { struct macros macros; el_rfunc_t read_char; /* Function to read a character. */ int read_errno; }; static int read__fixio(int, int); static int read_char(EditLine *, wchar_t *); static int read_getcmd(EditLine *, el_action_t *, wchar_t *); static void read_clearmacros(struct macros *); static void read_pop(struct macros *); static const wchar_t *noedit_wgets(EditLine *, int *); /* read_init(): * Initialize the read stuff */ libedit_private int read_init(EditLine *el) { struct macros *ma; if ((el->el_read = el_malloc(sizeof(*el->el_read))) == NULL) return -1; ma = &el->el_read->macros; if ((ma->macro = el_malloc(EL_MAXMACRO * sizeof(*ma->macro))) == NULL) { free(el->el_read); return -1; } ma->level = -1; ma->offset = 0; /* builtin read_char */ el->el_read->read_char = read_char; return 0; } /* el_read_end(): * Free the data structures used by the read stuff. */ libedit_private void read_end(struct el_read_t *el_read) { read_clearmacros(&el_read->macros); el_free(el_read->macros.macro); el_read->macros.macro = NULL; } /* el_read_setfn(): * Set the read char function to the one provided. * If it is set to EL_BUILTIN_GETCFN, then reset to the builtin one. */ libedit_private int el_read_setfn(struct el_read_t *el_read, el_rfunc_t rc) { el_read->read_char = (rc == EL_BUILTIN_GETCFN) ? read_char : rc; return 0; } /* el_read_getfn(): * return the current read char function, or EL_BUILTIN_GETCFN * if it is the default one */ libedit_private el_rfunc_t el_read_getfn(struct el_read_t *el_read) { return el_read->read_char == read_char ? EL_BUILTIN_GETCFN : el_read->read_char; } /* read__fixio(): * Try to recover from a read error */ /* ARGSUSED */ static int read__fixio(int fd __attribute__((__unused__)), int e) { switch (e) { case -1: /* Make sure that the code is reachable */ #ifdef EWOULDBLOCK case EWOULDBLOCK: #ifndef TRY_AGAIN #define TRY_AGAIN #endif #endif /* EWOULDBLOCK */ #if defined(POSIX) && defined(EAGAIN) #if defined(EWOULDBLOCK) && EWOULDBLOCK != EAGAIN case EAGAIN: #ifndef TRY_AGAIN #define TRY_AGAIN #endif #endif /* EWOULDBLOCK && EWOULDBLOCK != EAGAIN */ #endif /* POSIX && EAGAIN */ e = 0; #ifdef TRY_AGAIN #if defined(F_SETFL) && defined(O_NDELAY) if ((e = fcntl(fd, F_GETFL, 0)) == -1) return -1; if (fcntl(fd, F_SETFL, e & ~O_NDELAY) == -1) return -1; else e = 1; #endif /* F_SETFL && O_NDELAY */ #ifdef FIONBIO { int zero = 0; if (ioctl(fd, FIONBIO, &zero) == -1) return -1; else e = 1; } #endif /* FIONBIO */ #endif /* TRY_AGAIN */ return e ? 0 : -1; case EINTR: return 0; default: return -1; } } /* el_push(): * Push a macro */ void el_wpush(EditLine *el, const wchar_t *str) { struct macros *ma = &el->el_read->macros; if (str != NULL && ma->level + 1 < EL_MAXMACRO) { ma->level++; if ((ma->macro[ma->level] = wcsdup(str)) != NULL) return; ma->level--; } terminal_beep(el); terminal__flush(el); } /* read_getcmd(): * Get next command from the input stream, * return 0 on success or -1 on EOF or error. * Character values > 255 are not looked up in the map, but inserted. */ static int read_getcmd(EditLine *el, el_action_t *cmdnum, wchar_t *ch) { static const wchar_t meta = (wchar_t)0x80; el_action_t cmd; int num; do { if ((num = el_wgetc(el, ch)) != 1) return -1; #ifdef KANJI if ((*ch & meta)) { el->el_state.metanext = 0; cmd = CcViMap[' ']; break; } else #endif /* KANJI */ if (el->el_state.metanext) { el->el_state.metanext = 0; *ch |= meta; } if (*ch >= N_KEYS) cmd = ED_INSERT; else cmd = el->el_map.current[(unsigned char) *ch]; if (cmd == ED_SEQUENCE_LEAD_IN) { keymacro_value_t val; switch (keymacro_get(el, ch, &val)) { case XK_CMD: cmd = val.cmd; break; case XK_STR: el_wpush(el, val.str); break; case XK_NOD: return -1; default: EL_ABORT((el->el_errfile, "Bad XK_ type \n")); break; } } } while (cmd == ED_SEQUENCE_LEAD_IN); *cmdnum = cmd; return 0; } /* read_char(): * Read a character from the tty. */ static int read_char(EditLine *el, wchar_t *cp) { ssize_t num_read; int tried = 0; char cbuf[MB_LEN_MAX]; size_t cbp = 0; int save_errno = errno; again: el->el_signal->sig_no = 0; while ((num_read = read(el->el_infd, cbuf + cbp, (size_t)1)) == -1) { int e = errno; switch (el->el_signal->sig_no) { case SIGCONT: el_wset(el, EL_REFRESH); /*FALLTHROUGH*/ case SIGWINCH: sig_set(el); goto again; default: break; } if (!tried && read__fixio(el->el_infd, e) == 0) { errno = save_errno; tried = 1; } else { errno = e; *cp = L'\0'; return -1; } } /* Test for EOF */ if (num_read == 0) { *cp = L'\0'; return 0; } for (;;) { mbstate_t mbs; ++cbp; /* This only works because UTF8 is stateless. */ memset(&mbs, 0, sizeof(mbs)); switch (mbrtowc(cp, cbuf, cbp, &mbs)) { case (size_t)-1: if (cbp > 1) { /* * Invalid sequence, discard all bytes * except the last one. */ cbuf[0] = cbuf[cbp - 1]; cbp = 0; break; } else { /* Invalid byte, discard it. */ cbp = 0; goto again; } case (size_t)-2: /* * We don't support other multibyte charsets. * The second condition shouldn't happen * and is here merely for additional safety. */ if ((el->el_flags & CHARSET_IS_UTF8) == 0 || cbp >= MB_LEN_MAX) { errno = EILSEQ; *cp = L'\0'; return -1; } /* Incomplete sequence, read another byte. */ goto again; default: /* Valid character, process it. */ return 1; } } } /* read_pop(): * Pop a macro from the stack */ static void read_pop(struct macros *ma) { int i; el_free(ma->macro[0]); for (i = 0; i < ma->level; i++) ma->macro[i] = ma->macro[i + 1]; ma->level--; ma->offset = 0; } static void read_clearmacros(struct macros *ma) { while (ma->level >= 0) el_free(ma->macro[ma->level--]); ma->offset = 0; } /* el_wgetc(): * Read a wide character */ int el_wgetc(EditLine *el, wchar_t *cp) { struct macros *ma = &el->el_read->macros; int num_read; terminal__flush(el); for (;;) { if (ma->level < 0) break; if (ma->macro[0][ma->offset] == '\0') { read_pop(ma); continue; } *cp = ma->macro[0][ma->offset++]; if (ma->macro[0][ma->offset] == '\0') { /* Needed for QuoteMode On */ read_pop(ma); } return 1; } if (tty_rawmode(el) < 0)/* make sure the tty is set up correctly */ return 0; num_read = (*el->el_read->read_char)(el, cp); /* * Remember the original reason of a read failure * such that el_wgets() can restore it after doing * various cleanup operation that might change errno. */ if (num_read < 0) el->el_read->read_errno = errno; return num_read; } libedit_private void read_prepare(EditLine *el) { if (el->el_flags & HANDLE_SIGNALS) sig_set(el); if (el->el_flags & NO_TTY) return; if ((el->el_flags & (UNBUFFERED|EDIT_DISABLED)) == UNBUFFERED) tty_rawmode(el); /* This is relatively cheap, and things go terribly wrong if we have the wrong size. */ el_resize(el); re_clear_display(el); /* reset the display stuff */ ch_reset(el); re_refresh(el); /* print the prompt */ if (el->el_flags & UNBUFFERED) terminal__flush(el); } libedit_private void read_finish(EditLine *el) { if ((el->el_flags & UNBUFFERED) == 0) (void) tty_cookedmode(el); if (el->el_flags & HANDLE_SIGNALS) sig_clr(el); } static const wchar_t * noedit_wgets(EditLine *el, int *nread) { el_line_t *lp = &el->el_line; int num; while ((num = (*el->el_read->read_char)(el, lp->lastchar)) == 1) { if (lp->lastchar + 1 >= lp->limit && !ch_enlargebufs(el, (size_t)2)) break; lp->lastchar++; if (el->el_flags & UNBUFFERED || lp->lastchar[-1] == '\r' || lp->lastchar[-1] == '\n') break; } if (num == -1 && errno == EINTR) lp->lastchar = lp->buffer; lp->cursor = lp->lastchar; *lp->lastchar = '\0'; *nread = (int)(lp->lastchar - lp->buffer); return *nread ? lp->buffer : NULL; } const wchar_t * el_wgets(EditLine *el, int *nread) { int retval; el_action_t cmdnum = 0; int num; /* how many chars we have read at NL */ wchar_t ch; int nrb; if (nread == NULL) nread = &nrb; *nread = 0; el->el_read->read_errno = 0; if (el->el_flags & NO_TTY) { el->el_line.lastchar = el->el_line.buffer; return noedit_wgets(el, nread); } #ifdef FIONREAD if (el->el_tty.t_mode == EX_IO && el->el_read->macros.level < 0) { int chrs = 0; (void) ioctl(el->el_infd, FIONREAD, &chrs); if (chrs == 0) { if (tty_rawmode(el) < 0) { errno = 0; *nread = 0; return NULL; } } } #endif /* FIONREAD */ if ((el->el_flags & UNBUFFERED) == 0) read_prepare(el); if (el->el_flags & EDIT_DISABLED) { if ((el->el_flags & UNBUFFERED) == 0) el->el_line.lastchar = el->el_line.buffer; terminal__flush(el); return noedit_wgets(el, nread); } for (num = -1; num == -1;) { /* while still editing this line */ /* if EOF or error */ if (read_getcmd(el, &cmdnum, &ch) == -1) break; if ((size_t)cmdnum >= el->el_map.nfunc) /* BUG CHECK command */ continue; /* try again */ /* now do the real command */ /* vi redo needs these way down the levels... */ el->el_state.thiscmd = cmdnum; el->el_state.thisch = ch; if (el->el_map.type == MAP_VI && el->el_map.current == el->el_map.key && el->el_chared.c_redo.pos < el->el_chared.c_redo.lim) { if (cmdnum == VI_DELETE_PREV_CHAR && el->el_chared.c_redo.pos != el->el_chared.c_redo.buf && iswprint(el->el_chared.c_redo.pos[-1])) el->el_chared.c_redo.pos--; else *el->el_chared.c_redo.pos++ = ch; } retval = (*el->el_map.func[cmdnum]) (el, ch); /* save the last command here */ el->el_state.lastcmd = cmdnum; /* use any return value */ switch (retval) { case CC_CURSOR: re_refresh_cursor(el); break; case CC_REDISPLAY: re_clear_lines(el); re_clear_display(el); /* FALLTHROUGH */ case CC_REFRESH: re_refresh(el); break; case CC_REFRESH_BEEP: re_refresh(el); terminal_beep(el); break; case CC_NORM: /* normal char */ break; case CC_ARGHACK: /* Suggested by Rich Salz */ /* */ continue; /* keep going... */ case CC_EOF: /* end of file typed */ if ((el->el_flags & UNBUFFERED) == 0) num = 0; else if (num == -1) { *el->el_line.lastchar++ = CONTROL('d'); el->el_line.cursor = el->el_line.lastchar; num = 1; } break; case CC_NEWLINE: /* normal end of line */ num = (int)(el->el_line.lastchar - el->el_line.buffer); break; case CC_FATAL: /* fatal error, reset to known state */ /* put (real) cursor in a known place */ re_clear_display(el); /* reset the display stuff */ ch_reset(el); /* reset the input pointers */ read_clearmacros(&el->el_read->macros); re_refresh(el); /* print the prompt again */ break; case CC_ERROR: default: /* functions we don't know about */ terminal_beep(el); terminal__flush(el); break; } el->el_state.argument = 1; el->el_state.doingarg = 0; el->el_chared.c_vcmd.action = NOP; if (el->el_flags & UNBUFFERED) break; } terminal__flush(el); /* flush any buffered output */ /* make sure the tty is set up correctly */ if ((el->el_flags & UNBUFFERED) == 0) { read_finish(el); *nread = num != -1 ? num : 0; } else *nread = (int)(el->el_line.lastchar - el->el_line.buffer); if (*nread == 0) { if (num == -1) { *nread = -1; if (el->el_read->read_errno) errno = el->el_read->read_errno; } return NULL; } else return el->el_line.buffer; } heimdal-7.5.0/lib/libedit/src/search.c0000644000175000017500000003643213026237312015643 0ustar niknik/* $NetBSD: search.c,v 1.47 2016/05/09 21:46:56 christos Exp $ */ /*- * Copyright (c) 1992, 1993 * The Regents of the University of California. All rights reserved. * * This code is derived from software contributed to Berkeley by * Christos Zoulas of Cornell University. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the University nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "config.h" #if !defined(lint) && !defined(SCCSID) #if 0 static char sccsid[] = "@(#)search.c 8.1 (Berkeley) 6/4/93"; #else __RCSID("$NetBSD: search.c,v 1.47 2016/05/09 21:46:56 christos Exp $"); #endif #endif /* not lint && not SCCSID */ /* * search.c: History and character search functions */ #include #include #if defined(REGEX) #include #elif defined(REGEXP) #include #endif #include "el.h" #include "common.h" #include "fcns.h" /* * Adjust cursor in vi mode to include the character under it */ #define EL_CURSOR(el) \ ((el)->el_line.cursor + (((el)->el_map.type == MAP_VI) && \ ((el)->el_map.current == (el)->el_map.alt))) /* search_init(): * Initialize the search stuff */ libedit_private int search_init(EditLine *el) { el->el_search.patbuf = el_malloc(EL_BUFSIZ * sizeof(*el->el_search.patbuf)); if (el->el_search.patbuf == NULL) return -1; el->el_search.patbuf[0] = L'\0'; el->el_search.patlen = 0; el->el_search.patdir = -1; el->el_search.chacha = L'\0'; el->el_search.chadir = CHAR_FWD; el->el_search.chatflg = 0; return 0; } /* search_end(): * Initialize the search stuff */ libedit_private void search_end(EditLine *el) { el_free(el->el_search.patbuf); el->el_search.patbuf = NULL; } #ifdef REGEXP /* regerror(): * Handle regular expression errors */ void /*ARGSUSED*/ regerror(const char *msg) { } #endif /* el_match(): * Return if string matches pattern */ libedit_private int el_match(const wchar_t *str, const wchar_t *pat) { static ct_buffer_t conv; #if defined (REGEX) regex_t re; int rv; #elif defined (REGEXP) regexp *rp; int rv; #else extern char *re_comp(const char *); extern int re_exec(const char *); #endif if (wcsstr(str, pat) != 0) return 1; #if defined(REGEX) if (regcomp(&re, ct_encode_string(pat, &conv), 0) == 0) { rv = regexec(&re, ct_encode_string(str, &conv), (size_t)0, NULL, 0) == 0; regfree(&re); } else { rv = 0; } return rv; #elif defined(REGEXP) if ((re = regcomp(ct_encode_string(pat, &conv))) != NULL) { rv = regexec(re, ct_encode_string(str, &conv)); el_free(re); } else { rv = 0; } return rv; #else if (re_comp(ct_encode_string(pat, &conv)) != NULL) return 0; else return re_exec(ct_encode_string(str, &conv)) == 1; #endif } /* c_hmatch(): * return True if the pattern matches the prefix */ libedit_private int c_hmatch(EditLine *el, const wchar_t *str) { #ifdef SDEBUG (void) fprintf(el->el_errfile, "match `%s' with `%s'\n", el->el_search.patbuf, str); #endif /* SDEBUG */ return el_match(str, el->el_search.patbuf); } /* c_setpat(): * Set the history seatch pattern */ libedit_private void c_setpat(EditLine *el) { if (el->el_state.lastcmd != ED_SEARCH_PREV_HISTORY && el->el_state.lastcmd != ED_SEARCH_NEXT_HISTORY) { el->el_search.patlen = (size_t)(EL_CURSOR(el) - el->el_line.buffer); if (el->el_search.patlen >= EL_BUFSIZ) el->el_search.patlen = EL_BUFSIZ - 1; if (el->el_search.patlen != 0) { (void) wcsncpy(el->el_search.patbuf, el->el_line.buffer, el->el_search.patlen); el->el_search.patbuf[el->el_search.patlen] = '\0'; } else el->el_search.patlen = wcslen(el->el_search.patbuf); } #ifdef SDEBUG (void) fprintf(el->el_errfile, "\neventno = %d\n", el->el_history.eventno); (void) fprintf(el->el_errfile, "patlen = %d\n", el->el_search.patlen); (void) fprintf(el->el_errfile, "patbuf = \"%s\"\n", el->el_search.patbuf); (void) fprintf(el->el_errfile, "cursor %d lastchar %d\n", EL_CURSOR(el) - el->el_line.buffer, el->el_line.lastchar - el->el_line.buffer); #endif } /* ce_inc_search(): * Emacs incremental search */ libedit_private el_action_t ce_inc_search(EditLine *el, int dir) { static const wchar_t STRfwd[] = L"fwd", STRbck[] = L"bck"; static wchar_t pchar = L':'; /* ':' = normal, '?' = failed */ static wchar_t endcmd[2] = {'\0', '\0'}; wchar_t *ocursor = el->el_line.cursor, oldpchar = pchar, ch; const wchar_t *cp; el_action_t ret = CC_NORM; int ohisteventno = el->el_history.eventno; size_t oldpatlen = el->el_search.patlen; int newdir = dir; int done, redo; if (el->el_line.lastchar + sizeof(STRfwd) / sizeof(*el->el_line.lastchar) + 2 + el->el_search.patlen >= el->el_line.limit) return CC_ERROR; for (;;) { if (el->el_search.patlen == 0) { /* first round */ pchar = ':'; #ifdef ANCHOR #define LEN 2 el->el_search.patbuf[el->el_search.patlen++] = '.'; el->el_search.patbuf[el->el_search.patlen++] = '*'; #else #define LEN 0 #endif } done = redo = 0; *el->el_line.lastchar++ = '\n'; for (cp = (newdir == ED_SEARCH_PREV_HISTORY) ? STRbck : STRfwd; *cp; *el->el_line.lastchar++ = *cp++) continue; *el->el_line.lastchar++ = pchar; for (cp = &el->el_search.patbuf[LEN]; cp < &el->el_search.patbuf[el->el_search.patlen]; *el->el_line.lastchar++ = *cp++) continue; *el->el_line.lastchar = '\0'; re_refresh(el); if (el_wgetc(el, &ch) != 1) return ed_end_of_file(el, 0); switch (el->el_map.current[(unsigned char) ch]) { case ED_INSERT: case ED_DIGIT: if (el->el_search.patlen >= EL_BUFSIZ - LEN) terminal_beep(el); else { el->el_search.patbuf[el->el_search.patlen++] = ch; *el->el_line.lastchar++ = ch; *el->el_line.lastchar = '\0'; re_refresh(el); } break; case EM_INC_SEARCH_NEXT: newdir = ED_SEARCH_NEXT_HISTORY; redo++; break; case EM_INC_SEARCH_PREV: newdir = ED_SEARCH_PREV_HISTORY; redo++; break; case EM_DELETE_PREV_CHAR: case ED_DELETE_PREV_CHAR: if (el->el_search.patlen > LEN) done++; else terminal_beep(el); break; default: switch (ch) { case 0007: /* ^G: Abort */ ret = CC_ERROR; done++; break; case 0027: /* ^W: Append word */ /* No can do if globbing characters in pattern */ for (cp = &el->el_search.patbuf[LEN];; cp++) if (cp >= &el->el_search.patbuf[ el->el_search.patlen]) { el->el_line.cursor += el->el_search.patlen - LEN - 1; cp = c__next_word(el->el_line.cursor, el->el_line.lastchar, 1, ce__isword); while (el->el_line.cursor < cp && *el->el_line.cursor != '\n') { if (el->el_search.patlen >= EL_BUFSIZ - LEN) { terminal_beep(el); break; } el->el_search.patbuf[el->el_search.patlen++] = *el->el_line.cursor; *el->el_line.lastchar++ = *el->el_line.cursor++; } el->el_line.cursor = ocursor; *el->el_line.lastchar = '\0'; re_refresh(el); break; } else if (isglob(*cp)) { terminal_beep(el); break; } break; default: /* Terminate and execute cmd */ endcmd[0] = ch; el_wpush(el, endcmd); /* FALLTHROUGH */ case 0033: /* ESC: Terminate */ ret = CC_REFRESH; done++; break; } break; } while (el->el_line.lastchar > el->el_line.buffer && *el->el_line.lastchar != '\n') *el->el_line.lastchar-- = '\0'; *el->el_line.lastchar = '\0'; if (!done) { /* Can't search if unmatched '[' */ for (cp = &el->el_search.patbuf[el->el_search.patlen-1], ch = L']'; cp >= &el->el_search.patbuf[LEN]; cp--) if (*cp == '[' || *cp == ']') { ch = *cp; break; } if (el->el_search.patlen > LEN && ch != L'[') { if (redo && newdir == dir) { if (pchar == '?') { /* wrap around */ el->el_history.eventno = newdir == ED_SEARCH_PREV_HISTORY ? 0 : 0x7fffffff; if (hist_get(el) == CC_ERROR) /* el->el_history.event * no was fixed by * first call */ (void) hist_get(el); el->el_line.cursor = newdir == ED_SEARCH_PREV_HISTORY ? el->el_line.lastchar : el->el_line.buffer; } else el->el_line.cursor += newdir == ED_SEARCH_PREV_HISTORY ? -1 : 1; } #ifdef ANCHOR el->el_search.patbuf[el->el_search.patlen++] = '.'; el->el_search.patbuf[el->el_search.patlen++] = '*'; #endif el->el_search.patbuf[el->el_search.patlen] = '\0'; if (el->el_line.cursor < el->el_line.buffer || el->el_line.cursor > el->el_line.lastchar || (ret = ce_search_line(el, newdir)) == CC_ERROR) { /* avoid c_setpat */ el->el_state.lastcmd = (el_action_t) newdir; ret = (el_action_t) (newdir == ED_SEARCH_PREV_HISTORY ? ed_search_prev_history(el, 0) : ed_search_next_history(el, 0)); if (ret != CC_ERROR) { el->el_line.cursor = newdir == ED_SEARCH_PREV_HISTORY ? el->el_line.lastchar : el->el_line.buffer; (void) ce_search_line(el, newdir); } } el->el_search.patlen -= LEN; el->el_search.patbuf[el->el_search.patlen] = '\0'; if (ret == CC_ERROR) { terminal_beep(el); if (el->el_history.eventno != ohisteventno) { el->el_history.eventno = ohisteventno; if (hist_get(el) == CC_ERROR) return CC_ERROR; } el->el_line.cursor = ocursor; pchar = '?'; } else { pchar = ':'; } } ret = ce_inc_search(el, newdir); if (ret == CC_ERROR && pchar == '?' && oldpchar == ':') /* * break abort of failed search at last * non-failed */ ret = CC_NORM; } if (ret == CC_NORM || (ret == CC_ERROR && oldpatlen == 0)) { /* restore on normal return or error exit */ pchar = oldpchar; el->el_search.patlen = oldpatlen; if (el->el_history.eventno != ohisteventno) { el->el_history.eventno = ohisteventno; if (hist_get(el) == CC_ERROR) return CC_ERROR; } el->el_line.cursor = ocursor; if (ret == CC_ERROR) re_refresh(el); } if (done || ret != CC_NORM) return ret; } } /* cv_search(): * Vi search. */ libedit_private el_action_t cv_search(EditLine *el, int dir) { wchar_t ch; wchar_t tmpbuf[EL_BUFSIZ]; ssize_t tmplen; #ifdef ANCHOR tmpbuf[0] = '.'; tmpbuf[1] = '*'; #endif tmplen = LEN; el->el_search.patdir = dir; tmplen = c_gets(el, &tmpbuf[LEN], dir == ED_SEARCH_PREV_HISTORY ? L"\n/" : L"\n?" ); if (tmplen == -1) return CC_REFRESH; tmplen += LEN; ch = tmpbuf[tmplen]; tmpbuf[tmplen] = '\0'; if (tmplen == LEN) { /* * Use the old pattern, but wild-card it. */ if (el->el_search.patlen == 0) { re_refresh(el); return CC_ERROR; } #ifdef ANCHOR if (el->el_search.patbuf[0] != '.' && el->el_search.patbuf[0] != '*') { (void) wcsncpy(tmpbuf, el->el_search.patbuf, sizeof(tmpbuf) / sizeof(*tmpbuf) - 1); el->el_search.patbuf[0] = '.'; el->el_search.patbuf[1] = '*'; (void) wcsncpy(&el->el_search.patbuf[2], tmpbuf, EL_BUFSIZ - 3); el->el_search.patlen++; el->el_search.patbuf[el->el_search.patlen++] = '.'; el->el_search.patbuf[el->el_search.patlen++] = '*'; el->el_search.patbuf[el->el_search.patlen] = '\0'; } #endif } else { #ifdef ANCHOR tmpbuf[tmplen++] = '.'; tmpbuf[tmplen++] = '*'; #endif tmpbuf[tmplen] = '\0'; (void) wcsncpy(el->el_search.patbuf, tmpbuf, EL_BUFSIZ - 1); el->el_search.patlen = (size_t)tmplen; } el->el_state.lastcmd = (el_action_t) dir; /* avoid c_setpat */ el->el_line.cursor = el->el_line.lastchar = el->el_line.buffer; if ((dir == ED_SEARCH_PREV_HISTORY ? ed_search_prev_history(el, 0) : ed_search_next_history(el, 0)) == CC_ERROR) { re_refresh(el); return CC_ERROR; } if (ch == 0033) { re_refresh(el); return ed_newline(el, 0); } return CC_REFRESH; } /* ce_search_line(): * Look for a pattern inside a line */ libedit_private el_action_t ce_search_line(EditLine *el, int dir) { wchar_t *cp = el->el_line.cursor; wchar_t *pattern = el->el_search.patbuf; wchar_t oc, *ocp; #ifdef ANCHOR ocp = &pattern[1]; oc = *ocp; *ocp = '^'; #else ocp = pattern; oc = *ocp; #endif if (dir == ED_SEARCH_PREV_HISTORY) { for (; cp >= el->el_line.buffer; cp--) { if (el_match(cp, ocp)) { *ocp = oc; el->el_line.cursor = cp; return CC_NORM; } } *ocp = oc; return CC_ERROR; } else { for (; *cp != '\0' && cp < el->el_line.limit; cp++) { if (el_match(cp, ocp)) { *ocp = oc; el->el_line.cursor = cp; return CC_NORM; } } *ocp = oc; return CC_ERROR; } } /* cv_repeat_srch(): * Vi repeat search */ libedit_private el_action_t cv_repeat_srch(EditLine *el, wint_t c) { #ifdef SDEBUG (void) fprintf(el->el_errfile, "dir %d patlen %d patbuf %s\n", c, el->el_search.patlen, ct_encode_string(el->el_search.patbuf)); #endif el->el_state.lastcmd = (el_action_t) c; /* Hack to stop c_setpat */ el->el_line.lastchar = el->el_line.buffer; switch (c) { case ED_SEARCH_NEXT_HISTORY: return ed_search_next_history(el, 0); case ED_SEARCH_PREV_HISTORY: return ed_search_prev_history(el, 0); default: return CC_ERROR; } } /* cv_csearch(): * Vi character search */ libedit_private el_action_t cv_csearch(EditLine *el, int direction, wint_t ch, int count, int tflag) { wchar_t *cp; if (ch == 0) return CC_ERROR; if (ch == (wint_t)-1) { if (el_wgetc(el, &ch) != 1) return ed_end_of_file(el, 0); } /* Save for ';' and ',' commands */ el->el_search.chacha = ch; el->el_search.chadir = direction; el->el_search.chatflg = (char)tflag; cp = el->el_line.cursor; while (count--) { if ((wint_t)*cp == ch) cp += direction; for (;;cp += direction) { if (cp >= el->el_line.lastchar) return CC_ERROR; if (cp < el->el_line.buffer) return CC_ERROR; if ((wint_t)*cp == ch) break; } } if (tflag) cp -= direction; el->el_line.cursor = cp; if (el->el_chared.c_vcmd.action != NOP) { if (direction > 0) el->el_line.cursor++; cv_delfini(el); return CC_REFRESH; } return CC_CURSOR; } heimdal-7.5.0/lib/libedit/src/chared.h0000644000175000017500000001203013026237312015615 0ustar niknik/* $NetBSD: chared.h,v 1.30 2016/05/22 19:44:26 christos Exp $ */ /*- * Copyright (c) 1992, 1993 * The Regents of the University of California. All rights reserved. * * This code is derived from software contributed to Berkeley by * Christos Zoulas of Cornell University. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the University nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * * @(#)chared.h 8.1 (Berkeley) 6/4/93 */ /* * el.chared.h: Character editor interface */ #ifndef _h_el_chared #define _h_el_chared /* * This is an issue of basic "vi" look-and-feel. Defining VI_MOVE works * like real vi: i.e. the transition from command<->insert modes moves * the cursor. * * On the other hand we really don't want to move the cursor, because * all the editing commands don't include the character under the cursor. * Probably the best fix is to make all the editing commands aware of * this fact. */ #define VI_MOVE /* * Undo information for vi - no undo in emacs (yet) */ typedef struct c_undo_t { ssize_t len; /* length of saved line */ int cursor; /* position of saved cursor */ wchar_t *buf; /* full saved text */ } c_undo_t; /* redo for vi */ typedef struct c_redo_t { wchar_t *buf; /* redo insert key sequence */ wchar_t *pos; wchar_t *lim; el_action_t cmd; /* command to redo */ wchar_t ch; /* char that invoked it */ int count; int action; /* from cv_action() */ } c_redo_t; /* * Current action information for vi */ typedef struct c_vcmd_t { int action; wchar_t *pos; } c_vcmd_t; /* * Kill buffer for emacs */ typedef struct c_kill_t { wchar_t *buf; wchar_t *last; wchar_t *mark; } c_kill_t; typedef void (*el_zfunc_t)(EditLine *, void *); typedef const char *(*el_afunc_t)(void *, const char *); /* * Note that we use both data structures because the user can bind * commands from both editors! */ typedef struct el_chared_t { c_undo_t c_undo; c_kill_t c_kill; c_redo_t c_redo; c_vcmd_t c_vcmd; el_zfunc_t c_resizefun; el_afunc_t c_aliasfun; void * c_resizearg; void * c_aliasarg; } el_chared_t; #define STRQQ "\"\"" #define isglob(a) (strchr("*[]?", (a)) != NULL) #define NOP 0x00 #define DELETE 0x01 #define INSERT 0x02 #define YANK 0x04 #define CHAR_FWD (+1) #define CHAR_BACK (-1) #define MODE_INSERT 0 #define MODE_REPLACE 1 #define MODE_REPLACE_1 2 libedit_private int cv__isword(wint_t); libedit_private int cv__isWord(wint_t); libedit_private void cv_delfini(EditLine *); libedit_private wchar_t *cv__endword(wchar_t *, wchar_t *, int, int (*)(wint_t)); libedit_private int ce__isword(wint_t); libedit_private void cv_undo(EditLine *); libedit_private void cv_yank(EditLine *, const wchar_t *, int); libedit_private wchar_t *cv_next_word(EditLine*, wchar_t *, wchar_t *, int, int (*)(wint_t)); libedit_private wchar_t *cv_prev_word(wchar_t *, wchar_t *, int, int (*)(wint_t)); libedit_private wchar_t *c__next_word(wchar_t *, wchar_t *, int, int (*)(wint_t)); libedit_private wchar_t *c__prev_word(wchar_t *, wchar_t *, int, int (*)(wint_t)); libedit_private void c_insert(EditLine *, int); libedit_private void c_delbefore(EditLine *, int); libedit_private void c_delbefore1(EditLine *); libedit_private void c_delafter(EditLine *, int); libedit_private void c_delafter1(EditLine *); libedit_private int c_gets(EditLine *, wchar_t *, const wchar_t *); libedit_private int c_hpos(EditLine *); libedit_private int ch_init(EditLine *); libedit_private void ch_reset(EditLine *); libedit_private int ch_resizefun(EditLine *, el_zfunc_t, void *); libedit_private int ch_aliasfun(EditLine *, el_afunc_t, void *); libedit_private int ch_enlargebufs(EditLine *, size_t); libedit_private void ch_end(EditLine *); #endif /* _h_el_chared */ heimdal-7.5.0/lib/libedit/src/prompt.c0000644000175000017500000001110513026237312015705 0ustar niknik/* $NetBSD: prompt.c,v 1.26 2016/05/09 21:46:56 christos Exp $ */ /*- * Copyright (c) 1992, 1993 * The Regents of the University of California. All rights reserved. * * This code is derived from software contributed to Berkeley by * Christos Zoulas of Cornell University. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the University nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "config.h" #if !defined(lint) && !defined(SCCSID) #if 0 static char sccsid[] = "@(#)prompt.c 8.1 (Berkeley) 6/4/93"; #else __RCSID("$NetBSD: prompt.c,v 1.26 2016/05/09 21:46:56 christos Exp $"); #endif #endif /* not lint && not SCCSID */ /* * prompt.c: Prompt printing functions */ #include #include "el.h" static wchar_t *prompt_default(EditLine *); static wchar_t *prompt_default_r(EditLine *); /* prompt_default(): * Just a default prompt, in case the user did not provide one */ static wchar_t * /*ARGSUSED*/ prompt_default(EditLine *el __attribute__((__unused__))) { static wchar_t a[3] = L"? "; return a; } /* prompt_default_r(): * Just a default rprompt, in case the user did not provide one */ static wchar_t * /*ARGSUSED*/ prompt_default_r(EditLine *el __attribute__((__unused__))) { static wchar_t a[1] = L""; return a; } /* prompt_print(): * Print the prompt and update the prompt position. */ libedit_private void prompt_print(EditLine *el, int op) { el_prompt_t *elp; wchar_t *p; int ignore = 0; if (op == EL_PROMPT) elp = &el->el_prompt; else elp = &el->el_rprompt; if (elp->p_wide) p = (*elp->p_func)(el); else p = ct_decode_string((char *)(void *)(*elp->p_func)(el), &el->el_scratch); for (; *p; p++) { if (elp->p_ignore == *p) { ignore = !ignore; continue; } if (ignore) terminal__putc(el, *p); else re_putc(el, *p, 1); } elp->p_pos.v = el->el_refresh.r_cursor.v; elp->p_pos.h = el->el_refresh.r_cursor.h; } /* prompt_init(): * Initialize the prompt stuff */ libedit_private int prompt_init(EditLine *el) { el->el_prompt.p_func = prompt_default; el->el_prompt.p_pos.v = 0; el->el_prompt.p_pos.h = 0; el->el_prompt.p_ignore = '\0'; el->el_rprompt.p_func = prompt_default_r; el->el_rprompt.p_pos.v = 0; el->el_rprompt.p_pos.h = 0; el->el_rprompt.p_ignore = '\0'; return 0; } /* prompt_end(): * Clean up the prompt stuff */ libedit_private void /*ARGSUSED*/ prompt_end(EditLine *el __attribute__((__unused__))) { } /* prompt_set(): * Install a prompt printing function */ libedit_private int prompt_set(EditLine *el, el_pfunc_t prf, wchar_t c, int op, int wide) { el_prompt_t *p; if (op == EL_PROMPT || op == EL_PROMPT_ESC) p = &el->el_prompt; else p = &el->el_rprompt; if (prf == NULL) { if (op == EL_PROMPT || op == EL_PROMPT_ESC) p->p_func = prompt_default; else p->p_func = prompt_default_r; } else { p->p_func = prf; } p->p_ignore = c; p->p_pos.v = 0; p->p_pos.h = 0; p->p_wide = wide; return 0; } /* prompt_get(): * Retrieve the prompt printing function */ libedit_private int prompt_get(EditLine *el, el_pfunc_t *prf, wchar_t *c, int op) { el_prompt_t *p; if (prf == NULL) return -1; if (op == EL_PROMPT) p = &el->el_prompt; else p = &el->el_rprompt; if (prf) *prf = p->p_func; if (c) *c = p->p_ignore; return 0; } heimdal-7.5.0/lib/libedit/src/el.h0000644000175000017500000001212513026237312014774 0ustar niknik/* $NetBSD: el.h,v 1.41 2016/05/24 15:00:45 christos Exp $ */ /*- * Copyright (c) 1992, 1993 * The Regents of the University of California. All rights reserved. * * This code is derived from software contributed to Berkeley by * Christos Zoulas of Cornell University. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the University nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * * @(#)el.h 8.1 (Berkeley) 6/4/93 */ /* * el.h: Internal structures. */ #ifndef _h_el #define _h_el /* * Local defaults */ #define KSHVI #define VIDEFAULT #define ANCHOR #include "histedit.h" #include "chartype.h" #define EL_BUFSIZ ((size_t)1024) /* Maximum line size */ #define HANDLE_SIGNALS 0x01 #define NO_TTY 0x02 #define EDIT_DISABLED 0x04 #define UNBUFFERED 0x08 #define CHARSET_IS_UTF8 0x10 #define NARROW_HISTORY 0x40 typedef unsigned char el_action_t; /* Index to command array */ typedef struct coord_t { /* Position on the screen */ int h; int v; } coord_t; typedef struct el_line_t { wchar_t *buffer; /* Input line */ wchar_t *cursor; /* Cursor position */ wchar_t *lastchar; /* Last character */ const wchar_t *limit; /* Max position */ } el_line_t; /* * Editor state */ typedef struct el_state_t { int inputmode; /* What mode are we in? */ int doingarg; /* Are we getting an argument? */ int argument; /* Numeric argument */ int metanext; /* Is the next char a meta char */ el_action_t lastcmd; /* Previous command */ el_action_t thiscmd; /* this command */ wchar_t thisch; /* char that generated it */ } el_state_t; /* * Until we come up with something better... */ #define el_malloc(a) malloc(a) #define el_realloc(a,b) realloc(a, b) #define el_free(a) free(a) #include "tty.h" #include "prompt.h" #include "keymacro.h" #include "terminal.h" #include "refresh.h" #include "chared.h" #include "search.h" #include "hist.h" #include "map.h" #include "sig.h" struct el_read_t; struct editline { wchar_t *el_prog; /* the program name */ FILE *el_infile; /* Stdio stuff */ FILE *el_outfile; /* Stdio stuff */ FILE *el_errfile; /* Stdio stuff */ int el_infd; /* Input file descriptor */ int el_outfd; /* Output file descriptor */ int el_errfd; /* Error file descriptor */ int el_flags; /* Various flags. */ coord_t el_cursor; /* Cursor location */ wchar_t **el_display; /* Real screen image = what is there */ wchar_t **el_vdisplay; /* Virtual screen image = what we see */ void *el_data; /* Client data */ el_line_t el_line; /* The current line information */ el_state_t el_state; /* Current editor state */ el_terminal_t el_terminal; /* Terminal dependent stuff */ el_tty_t el_tty; /* Tty dependent stuff */ el_refresh_t el_refresh; /* Refresh stuff */ el_prompt_t el_prompt; /* Prompt stuff */ el_prompt_t el_rprompt; /* Prompt stuff */ el_chared_t el_chared; /* Characted editor stuff */ el_map_t el_map; /* Key mapping stuff */ el_keymacro_t el_keymacro; /* Key binding stuff */ el_history_t el_history; /* History stuff */ el_search_t el_search; /* Search stuff */ el_signal_t el_signal; /* Signal handling stuff */ struct el_read_t *el_read; /* Character reading stuff */ ct_buffer_t el_visual; /* Buffer for displayable str */ ct_buffer_t el_scratch; /* Scratch conversion buffer */ ct_buffer_t el_lgcyconv; /* Buffer for legacy wrappers */ LineInfo el_lgcylinfo; /* Legacy LineInfo buffer */ }; libedit_private int el_editmode(EditLine *, int, const wchar_t **); #ifdef DEBUG #define EL_ABORT(a) do { \ fprintf(el->el_errfile, "%s, %d: ", \ __FILE__, __LINE__); \ fprintf a; \ abort(); \ } while( /*CONSTCOND*/0); #else #define EL_ABORT(a) abort() #endif #endif /* _h_el */ heimdal-7.5.0/lib/libedit/src/eln.c0000644000175000017500000002061213026237312015145 0ustar niknik/* $NetBSD: eln.c,v 1.34 2016/05/09 21:37:34 christos Exp $ */ /*- * Copyright (c) 2009 The NetBSD Foundation, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include "config.h" #if !defined(lint) && !defined(SCCSID) __RCSID("$NetBSD: eln.c,v 1.34 2016/05/09 21:37:34 christos Exp $"); #endif /* not lint && not SCCSID */ #include #include #include #include #include "el.h" int el_getc(EditLine *el, char *cp) { int num_read; wchar_t wc = 0; num_read = el_wgetc(el, &wc); *cp = '\0'; if (num_read <= 0) return num_read; num_read = wctob(wc); if (num_read == EOF) { errno = ERANGE; return -1; } else { *cp = (char)num_read; return 1; } } void el_push(EditLine *el, const char *str) { /* Using multibyte->wide string decoding works fine under single-byte * character sets too, and Does The Right Thing. */ el_wpush(el, ct_decode_string(str, &el->el_lgcyconv)); } const char * el_gets(EditLine *el, int *nread) { const wchar_t *tmp; tmp = el_wgets(el, nread); if (tmp != NULL) { int i; size_t nwread = 0; for (i = 0; i < *nread; i++) nwread += ct_enc_width(tmp[i]); *nread = (int)nwread; } return ct_encode_string(tmp, &el->el_lgcyconv); } int el_parse(EditLine *el, int argc, const char *argv[]) { int ret; const wchar_t **wargv; wargv = (void *)ct_decode_argv(argc, argv, &el->el_lgcyconv); if (!wargv) return -1; ret = el_wparse(el, argc, wargv); el_free(wargv); return ret; } int el_set(EditLine *el, int op, ...) { va_list ap; int ret; if (!el) return -1; va_start(ap, op); switch (op) { case EL_PROMPT: /* el_pfunc_t */ case EL_RPROMPT: { el_pfunc_t p = va_arg(ap, el_pfunc_t); ret = prompt_set(el, p, 0, op, 0); break; } case EL_RESIZE: { el_zfunc_t p = va_arg(ap, el_zfunc_t); void *arg = va_arg(ap, void *); ret = ch_resizefun(el, p, arg); break; } case EL_ALIAS_TEXT: { el_afunc_t p = va_arg(ap, el_afunc_t); void *arg = va_arg(ap, void *); ret = ch_aliasfun(el, p, arg); break; } case EL_PROMPT_ESC: case EL_RPROMPT_ESC: { el_pfunc_t p = va_arg(ap, el_pfunc_t); int c = va_arg(ap, int); ret = prompt_set(el, p, c, op, 0); break; } case EL_TERMINAL: /* const char * */ ret = el_wset(el, op, va_arg(ap, char *)); break; case EL_EDITOR: /* const wchar_t * */ ret = el_wset(el, op, ct_decode_string(va_arg(ap, char *), &el->el_lgcyconv)); break; case EL_SIGNAL: /* int */ case EL_EDITMODE: case EL_UNBUFFERED: case EL_PREP_TERM: ret = el_wset(el, op, va_arg(ap, int)); break; case EL_BIND: /* const char * list -> const wchar_t * list */ case EL_TELLTC: case EL_SETTC: case EL_ECHOTC: case EL_SETTY: { const char *argv[20]; int i; const wchar_t **wargv; for (i = 1; i < (int)__arraycount(argv) - 1; ++i) if ((argv[i] = va_arg(ap, const char *)) == NULL) break; argv[0] = argv[i] = NULL; wargv = (void *)ct_decode_argv(i + 1, argv, &el->el_lgcyconv); if (!wargv) { ret = -1; goto out; } /* * AFAIK we can't portably pass through our new wargv to * el_wset(), so we have to reimplement the body of * el_wset() for these ops. */ switch (op) { case EL_BIND: wargv[0] = L"bind"; ret = map_bind(el, i, wargv); break; case EL_TELLTC: wargv[0] = L"telltc"; ret = terminal_telltc(el, i, wargv); break; case EL_SETTC: wargv[0] = L"settc"; ret = terminal_settc(el, i, wargv); break; case EL_ECHOTC: wargv[0] = L"echotc"; ret = terminal_echotc(el, i, wargv); break; case EL_SETTY: wargv[0] = L"setty"; ret = tty_stty(el, i, wargv); break; default: ret = -1; } el_free(wargv); break; } /* XXX: do we need to change el_func_t too? */ case EL_ADDFN: { /* const char *, const char *, el_func_t */ const char *args[2]; el_func_t func; wchar_t **wargv; args[0] = va_arg(ap, const char *); args[1] = va_arg(ap, const char *); func = va_arg(ap, el_func_t); wargv = ct_decode_argv(2, args, &el->el_lgcyconv); if (!wargv) { ret = -1; goto out; } /* XXX: The two strdup's leak */ ret = map_addfunc(el, wcsdup(wargv[0]), wcsdup(wargv[1]), func); el_free(wargv); break; } case EL_HIST: { /* hist_fun_t, const char * */ hist_fun_t fun = va_arg(ap, hist_fun_t); void *ptr = va_arg(ap, void *); ret = hist_set(el, fun, ptr); el->el_flags |= NARROW_HISTORY; break; } case EL_GETCFN: /* el_rfunc_t */ ret = el_wset(el, op, va_arg(ap, el_rfunc_t)); break; case EL_CLIENTDATA: /* void * */ ret = el_wset(el, op, va_arg(ap, void *)); break; case EL_SETFP: { /* int, FILE * */ int what = va_arg(ap, int); FILE *fp = va_arg(ap, FILE *); ret = el_wset(el, op, what, fp); break; } case EL_REFRESH: re_clear_display(el); re_refresh(el); terminal__flush(el); ret = 0; break; default: ret = -1; break; } out: va_end(ap); return ret; } int el_get(EditLine *el, int op, ...) { va_list ap; int ret; if (!el) return -1; va_start(ap, op); switch (op) { case EL_PROMPT: /* el_pfunc_t * */ case EL_RPROMPT: { el_pfunc_t *p = va_arg(ap, el_pfunc_t *); ret = prompt_get(el, p, 0, op); break; } case EL_PROMPT_ESC: /* el_pfunc_t *, char **/ case EL_RPROMPT_ESC: { el_pfunc_t *p = va_arg(ap, el_pfunc_t *); char *c = va_arg(ap, char *); wchar_t wc = 0; ret = prompt_get(el, p, &wc, op); *c = (char)wc; break; } case EL_EDITOR: { const char **p = va_arg(ap, const char **); const wchar_t *pw; ret = el_wget(el, op, &pw); *p = ct_encode_string(pw, &el->el_lgcyconv); if (!el->el_lgcyconv.csize) ret = -1; break; } case EL_TERMINAL: /* const char ** */ ret = el_wget(el, op, va_arg(ap, const char **)); break; case EL_SIGNAL: /* int * */ case EL_EDITMODE: case EL_UNBUFFERED: case EL_PREP_TERM: ret = el_wget(el, op, va_arg(ap, int *)); break; case EL_GETTC: { char *argv[20]; static char gettc[] = "gettc"; int i; for (i = 1; i < (int)__arraycount(argv); ++i) if ((argv[i] = va_arg(ap, char *)) == NULL) break; argv[0] = gettc; ret = terminal_gettc(el, i, argv); break; } case EL_GETCFN: /* el_rfunc_t */ ret = el_wget(el, op, va_arg(ap, el_rfunc_t *)); break; case EL_CLIENTDATA: /* void ** */ ret = el_wget(el, op, va_arg(ap, void **)); break; case EL_GETFP: { /* int, FILE ** */ int what = va_arg(ap, int); FILE **fpp = va_arg(ap, FILE **); ret = el_wget(el, op, what, fpp); break; } default: ret = -1; break; } va_end(ap); return ret; } const LineInfo * el_line(EditLine *el) { const LineInfoW *winfo = el_wline(el); LineInfo *info = &el->el_lgcylinfo; size_t offset; const wchar_t *p; info->buffer = ct_encode_string(winfo->buffer, &el->el_lgcyconv); offset = 0; for (p = winfo->buffer; p < winfo->cursor; p++) offset += ct_enc_width(*p); info->cursor = info->buffer + offset; offset = 0; for (p = winfo->buffer; p < winfo->lastchar; p++) offset += ct_enc_width(*p); info->lastchar = info->buffer + offset; return info; } int el_insertstr(EditLine *el, const char *str) { return el_winsertstr(el, ct_decode_string(str, &el->el_lgcyconv)); } heimdal-7.5.0/lib/libedit/src/readline/0000755000175000017500000000000013214604041016001 5ustar niknikheimdal-7.5.0/lib/libedit/src/readline/readline.h0000644000175000017500000001672713062055136017760 0ustar niknik/* $NetBSD: readline.h,v 1.41 2016/10/28 18:32:35 christos Exp $ */ /*- * Copyright (c) 1997 The NetBSD Foundation, Inc. * All rights reserved. * * This code is derived from software contributed to The NetBSD Foundation * by Jaromir Dolecek. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #ifndef _READLINE_H_ #define _READLINE_H_ #include #include /* list of readline stuff supported by editline library's readline wrapper */ /* typedefs */ typedef int Function(const char *, int); typedef void VFunction(void); typedef void rl_vcpfunc_t(char *); typedef char **rl_completion_func_t(const char *, int, int); typedef char *rl_compentry_func_t(const char *, int); typedef int rl_command_func_t(int, int); /* only supports length */ typedef struct { int length; } HISTORY_STATE; typedef void *histdata_t; typedef struct _hist_entry { const char *line; histdata_t data; } HIST_ENTRY; typedef struct _keymap_entry { char type; #define ISFUNC 0 #define ISKMAP 1 #define ISMACR 2 Function *function; } KEYMAP_ENTRY; #define KEYMAP_SIZE 256 typedef KEYMAP_ENTRY KEYMAP_ENTRY_ARRAY[KEYMAP_SIZE]; typedef KEYMAP_ENTRY *Keymap; #define control_character_threshold 0x20 #define control_character_bit 0x40 #ifndef CTRL #include #if !defined(__sun) && !defined(__hpux) && !defined(_AIX) && !defined(_CYGWIN_) #include #endif #ifndef CTRL #define CTRL(c) ((c) & 037) #endif #endif #ifndef UNCTRL #define UNCTRL(c) (((c) - 'a' + 'A')|control_character_bit) #endif #define RUBOUT 0x7f #define ABORT_CHAR CTRL('G') #define RL_READLINE_VERSION 0x0402 #define RL_PROMPT_START_IGNORE '\1' #define RL_PROMPT_END_IGNORE '\2' /* global variables used by readline enabled applications */ #ifdef __cplusplus extern "C" { #endif extern const char *rl_library_version; extern int rl_readline_version; extern char *rl_readline_name; extern FILE *rl_instream; extern FILE *rl_outstream; extern char *rl_line_buffer; extern int rl_point, rl_end; extern int history_base, history_length; extern int max_input_history; extern char *rl_basic_word_break_characters; extern char *rl_completer_word_break_characters; extern char *rl_completer_quote_characters; extern rl_compentry_func_t *rl_completion_entry_function; extern char *(*rl_completion_word_break_hook)(void); extern rl_completion_func_t *rl_attempted_completion_function; extern int rl_attempted_completion_over; extern int rl_completion_type; extern int rl_completion_query_items; extern char *rl_special_prefixes; extern int rl_completion_append_character; extern int rl_inhibit_completion; extern Function *rl_pre_input_hook; extern Function *rl_startup_hook; extern char *rl_terminal_name; extern int rl_already_prompted; extern char *rl_prompt; extern int rl_done; /* * The following is not implemented */ extern int rl_catch_signals; extern int rl_catch_sigwinch; extern KEYMAP_ENTRY_ARRAY emacs_standard_keymap, emacs_meta_keymap, emacs_ctlx_keymap; extern int rl_filename_completion_desired; extern int rl_ignore_completion_duplicates; extern int (*rl_getc_function)(FILE *); extern VFunction *rl_redisplay_function; extern VFunction *rl_completion_display_matches_hook; extern VFunction *rl_prep_term_function; extern VFunction *rl_deprep_term_function; extern int readline_echoing_p; extern int _rl_print_completions_horizontally; /* supported functions */ char *readline(const char *); int rl_initialize(void); void using_history(void); int add_history(const char *); void clear_history(void); void stifle_history(int); int unstifle_history(void); int history_is_stifled(void); int where_history(void); HIST_ENTRY *current_history(void); HIST_ENTRY *history_get(int); HIST_ENTRY *remove_history(int); HIST_ENTRY *replace_history_entry(int, const char *, histdata_t); int history_total_bytes(void); int history_set_pos(int); HIST_ENTRY *previous_history(void); HIST_ENTRY *next_history(void); HIST_ENTRY **history_list(void); int history_search(const char *, int); int history_search_prefix(const char *, int); int history_search_pos(const char *, int, int); int read_history(const char *); int write_history(const char *); int history_truncate_file (const char *, int); int history_expand(char *, char **); char **history_tokenize(const char *); const char *get_history_event(const char *, int *, int); char *history_arg_extract(int, int, const char *); char *tilde_expand(char *); char *filename_completion_function(const char *, int); char *username_completion_function(const char *, int); int rl_complete(int, int); int rl_read_key(void); char **completion_matches(const char *, rl_compentry_func_t *); void rl_display_match_list(char **, int, int); int rl_insert(int, int); int rl_insert_text(const char *); void rl_reset_terminal(const char *); int rl_bind_key(int, rl_command_func_t *); int rl_newline(int, int); void rl_callback_read_char(void); void rl_callback_handler_install(const char *, rl_vcpfunc_t *); void rl_callback_handler_remove(void); void rl_redisplay(void); int rl_get_previous_history(int, int); void rl_prep_terminal(int); void rl_deprep_terminal(void); int rl_read_init_file(const char *); int rl_parse_and_bind(const char *); int rl_variable_bind(const char *, const char *); void rl_stuff_char(int); int rl_add_defun(const char *, rl_command_func_t *, int); HISTORY_STATE *history_get_history_state(void); void rl_get_screen_size(int *, int *); void rl_set_screen_size(int, int); char *rl_filename_completion_function (const char *, int); int _rl_abort_internal(void); int _rl_qsort_string_compare(char **, char **); char **rl_completion_matches(const char *, rl_compentry_func_t *); void rl_forced_update_display(void); int rl_set_prompt(const char *); int rl_on_new_line(void); /* * The following are not implemented */ int rl_kill_text(int, int); Keymap rl_get_keymap(void); void rl_set_keymap(Keymap); Keymap rl_make_bare_keymap(void); int rl_generic_bind(int, const char *, const char *, Keymap); int rl_bind_key_in_map(int, rl_command_func_t *, Keymap); void rl_cleanup_after_signal(void); void rl_free_line_state(void); int rl_set_keyboard_input_timeout(int); #ifdef __cplusplus } #endif #endif /* _READLINE_H_ */ heimdal-7.5.0/lib/libedit/src/Makefile.am0000644000175000017500000000276513212137553016273 0ustar niknik BUILT_SOURCES = vi.h emacs.h common.h fcns.h help.h func.h AHDR= vi.h emacs.h common.h ASRC= $(srcdir)/vi.c $(srcdir)/emacs.c $(srcdir)/common.c vi.h: Makefile $(srcdir)/makelist $(srcdir)/vi.c AWK=$(AWK) sh $(srcdir)/makelist -h $(srcdir)/vi.c > $@ emacs.h: Makefile $(srcdir)/makelist $(srcdir)/emacs.c AWK=$(AWK) sh $(srcdir)/makelist -h $(srcdir)/emacs.c > $@ common.h: Makefile $(srcdir)/makelist $(srcdir)/common.c AWK=$(AWK) sh $(srcdir)/makelist -h $(srcdir)/common.c > $@ fcns.h: Makefile $(srcdir)/makelist $(AHDR) AWK=$(AWK) sh $(srcdir)/makelist -fh $(AHDR) > $@ func.h: Makefile $(srcdir)/makelist $(AHDR) AWK=$(AWK) sh $(srcdir)/makelist -fc $(AHDR) > $@ help.h: Makefile $(srcdir)/makelist $(ASRC) AWK=$(AWK) sh $(srcdir)/makelist -bh $(ASRC) > $@ CLEANFILES = $(BUILT_SOURCES) lib_LTLIBRARIES = libheimedit.la libheimedit_la_SOURCES = \ chared.c chartype.c common.c el.c eln.c emacs.c filecomplete.c hist.c \ history.c historyn.c keymacro.c map.c parse.c prompt.c read.c readline.c \ refresh.c search.c sig.c terminal.c tokenizer.c tokenizern.c tty.c \ unvis.c vi.c vis.c wcsdup.c \ chared.h chartype.h readline/readline.h el.h filecomplete.h \ histedit.h hist.h keymacro.h map.h parse.h prompt.h read.h \ refresh.h search.h sig.h sys.h terminal.h tty.h vis.h EXTRA_DIST = makelist shlib_version EXTRA_DIST += histedit.h readline/readline.h nodist_libheimedit_la_SOURCES = $(BUILT_SOURCES) libheimedit_la_LDFLAGS = -no-undefined -version-info $(LT_VERSION) heimdal-7.5.0/lib/libedit/src/vi.c0000644000175000017500000006146313026237312015016 0ustar niknik/* $NetBSD: vi.c,v 1.62 2016/05/09 21:46:56 christos Exp $ */ /*- * Copyright (c) 1992, 1993 * The Regents of the University of California. All rights reserved. * * This code is derived from software contributed to Berkeley by * Christos Zoulas of Cornell University. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the University nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "config.h" #if !defined(lint) && !defined(SCCSID) #if 0 static char sccsid[] = "@(#)vi.c 8.1 (Berkeley) 6/4/93"; #else __RCSID("$NetBSD: vi.c,v 1.62 2016/05/09 21:46:56 christos Exp $"); #endif #endif /* not lint && not SCCSID */ /* * vi.c: Vi mode commands. */ #include #include #include #include #include #include #include "el.h" #include "common.h" #include "emacs.h" #include "fcns.h" #include "vi.h" static el_action_t cv_action(EditLine *, wint_t); static el_action_t cv_paste(EditLine *, wint_t); /* cv_action(): * Handle vi actions. */ static el_action_t cv_action(EditLine *el, wint_t c) { if (el->el_chared.c_vcmd.action != NOP) { /* 'cc', 'dd' and (possibly) friends */ if (c != (wint_t)el->el_chared.c_vcmd.action) return CC_ERROR; if (!(c & YANK)) cv_undo(el); cv_yank(el, el->el_line.buffer, (int)(el->el_line.lastchar - el->el_line.buffer)); el->el_chared.c_vcmd.action = NOP; el->el_chared.c_vcmd.pos = 0; if (!(c & YANK)) { el->el_line.lastchar = el->el_line.buffer; el->el_line.cursor = el->el_line.buffer; } if (c & INSERT) el->el_map.current = el->el_map.key; return CC_REFRESH; } el->el_chared.c_vcmd.pos = el->el_line.cursor; el->el_chared.c_vcmd.action = c; return CC_ARGHACK; } /* cv_paste(): * Paste previous deletion before or after the cursor */ static el_action_t cv_paste(EditLine *el, wint_t c) { c_kill_t *k = &el->el_chared.c_kill; size_t len = (size_t)(k->last - k->buf); if (k->buf == NULL || len == 0) return CC_ERROR; #ifdef DEBUG_PASTE (void) fprintf(el->el_errfile, "Paste: \"%.*ls\"\n", (int)len, k->buf); #endif cv_undo(el); if (!c && el->el_line.cursor < el->el_line.lastchar) el->el_line.cursor++; c_insert(el, (int)len); if (el->el_line.cursor + len > el->el_line.lastchar) return CC_ERROR; (void) memcpy(el->el_line.cursor, k->buf, len * sizeof(*el->el_line.cursor)); return CC_REFRESH; } /* vi_paste_next(): * Vi paste previous deletion to the right of the cursor * [p] */ libedit_private el_action_t /*ARGSUSED*/ vi_paste_next(EditLine *el, wint_t c __attribute__((__unused__))) { return cv_paste(el, 0); } /* vi_paste_prev(): * Vi paste previous deletion to the left of the cursor * [P] */ libedit_private el_action_t /*ARGSUSED*/ vi_paste_prev(EditLine *el, wint_t c __attribute__((__unused__))) { return cv_paste(el, 1); } /* vi_prev_big_word(): * Vi move to the previous space delimited word * [B] */ libedit_private el_action_t /*ARGSUSED*/ vi_prev_big_word(EditLine *el, wint_t c __attribute__((__unused__))) { if (el->el_line.cursor == el->el_line.buffer) return CC_ERROR; el->el_line.cursor = cv_prev_word(el->el_line.cursor, el->el_line.buffer, el->el_state.argument, cv__isWord); if (el->el_chared.c_vcmd.action != NOP) { cv_delfini(el); return CC_REFRESH; } return CC_CURSOR; } /* vi_prev_word(): * Vi move to the previous word * [b] */ libedit_private el_action_t /*ARGSUSED*/ vi_prev_word(EditLine *el, wint_t c __attribute__((__unused__))) { if (el->el_line.cursor == el->el_line.buffer) return CC_ERROR; el->el_line.cursor = cv_prev_word(el->el_line.cursor, el->el_line.buffer, el->el_state.argument, cv__isword); if (el->el_chared.c_vcmd.action != NOP) { cv_delfini(el); return CC_REFRESH; } return CC_CURSOR; } /* vi_next_big_word(): * Vi move to the next space delimited word * [W] */ libedit_private el_action_t /*ARGSUSED*/ vi_next_big_word(EditLine *el, wint_t c __attribute__((__unused__))) { if (el->el_line.cursor >= el->el_line.lastchar - 1) return CC_ERROR; el->el_line.cursor = cv_next_word(el, el->el_line.cursor, el->el_line.lastchar, el->el_state.argument, cv__isWord); if (el->el_map.type == MAP_VI) if (el->el_chared.c_vcmd.action != NOP) { cv_delfini(el); return CC_REFRESH; } return CC_CURSOR; } /* vi_next_word(): * Vi move to the next word * [w] */ libedit_private el_action_t /*ARGSUSED*/ vi_next_word(EditLine *el, wint_t c __attribute__((__unused__))) { if (el->el_line.cursor >= el->el_line.lastchar - 1) return CC_ERROR; el->el_line.cursor = cv_next_word(el, el->el_line.cursor, el->el_line.lastchar, el->el_state.argument, cv__isword); if (el->el_map.type == MAP_VI) if (el->el_chared.c_vcmd.action != NOP) { cv_delfini(el); return CC_REFRESH; } return CC_CURSOR; } /* vi_change_case(): * Vi change case of character under the cursor and advance one character * [~] */ libedit_private el_action_t vi_change_case(EditLine *el, wint_t c) { int i; if (el->el_line.cursor >= el->el_line.lastchar) return CC_ERROR; cv_undo(el); for (i = 0; i < el->el_state.argument; i++) { c = *el->el_line.cursor; if (iswupper(c)) *el->el_line.cursor = towlower(c); else if (iswlower(c)) *el->el_line.cursor = towupper(c); if (++el->el_line.cursor >= el->el_line.lastchar) { el->el_line.cursor--; re_fastaddc(el); break; } re_fastaddc(el); } return CC_NORM; } /* vi_change_meta(): * Vi change prefix command * [c] */ libedit_private el_action_t /*ARGSUSED*/ vi_change_meta(EditLine *el, wint_t c __attribute__((__unused__))) { /* * Delete with insert == change: first we delete and then we leave in * insert mode. */ return cv_action(el, DELETE | INSERT); } /* vi_insert_at_bol(): * Vi enter insert mode at the beginning of line * [I] */ libedit_private el_action_t /*ARGSUSED*/ vi_insert_at_bol(EditLine *el, wint_t c __attribute__((__unused__))) { el->el_line.cursor = el->el_line.buffer; cv_undo(el); el->el_map.current = el->el_map.key; return CC_CURSOR; } /* vi_replace_char(): * Vi replace character under the cursor with the next character typed * [r] */ libedit_private el_action_t /*ARGSUSED*/ vi_replace_char(EditLine *el, wint_t c __attribute__((__unused__))) { if (el->el_line.cursor >= el->el_line.lastchar) return CC_ERROR; el->el_map.current = el->el_map.key; el->el_state.inputmode = MODE_REPLACE_1; cv_undo(el); return CC_ARGHACK; } /* vi_replace_mode(): * Vi enter replace mode * [R] */ libedit_private el_action_t /*ARGSUSED*/ vi_replace_mode(EditLine *el, wint_t c __attribute__((__unused__))) { el->el_map.current = el->el_map.key; el->el_state.inputmode = MODE_REPLACE; cv_undo(el); return CC_NORM; } /* vi_substitute_char(): * Vi replace character under the cursor and enter insert mode * [s] */ libedit_private el_action_t /*ARGSUSED*/ vi_substitute_char(EditLine *el, wint_t c __attribute__((__unused__))) { c_delafter(el, el->el_state.argument); el->el_map.current = el->el_map.key; return CC_REFRESH; } /* vi_substitute_line(): * Vi substitute entire line * [S] */ libedit_private el_action_t /*ARGSUSED*/ vi_substitute_line(EditLine *el, wint_t c __attribute__((__unused__))) { cv_undo(el); cv_yank(el, el->el_line.buffer, (int)(el->el_line.lastchar - el->el_line.buffer)); (void) em_kill_line(el, 0); el->el_map.current = el->el_map.key; return CC_REFRESH; } /* vi_change_to_eol(): * Vi change to end of line * [C] */ libedit_private el_action_t /*ARGSUSED*/ vi_change_to_eol(EditLine *el, wint_t c __attribute__((__unused__))) { cv_undo(el); cv_yank(el, el->el_line.cursor, (int)(el->el_line.lastchar - el->el_line.cursor)); (void) ed_kill_line(el, 0); el->el_map.current = el->el_map.key; return CC_REFRESH; } /* vi_insert(): * Vi enter insert mode * [i] */ libedit_private el_action_t /*ARGSUSED*/ vi_insert(EditLine *el, wint_t c __attribute__((__unused__))) { el->el_map.current = el->el_map.key; cv_undo(el); return CC_NORM; } /* vi_add(): * Vi enter insert mode after the cursor * [a] */ libedit_private el_action_t /*ARGSUSED*/ vi_add(EditLine *el, wint_t c __attribute__((__unused__))) { int ret; el->el_map.current = el->el_map.key; if (el->el_line.cursor < el->el_line.lastchar) { el->el_line.cursor++; if (el->el_line.cursor > el->el_line.lastchar) el->el_line.cursor = el->el_line.lastchar; ret = CC_CURSOR; } else ret = CC_NORM; cv_undo(el); return (el_action_t)ret; } /* vi_add_at_eol(): * Vi enter insert mode at end of line * [A] */ libedit_private el_action_t /*ARGSUSED*/ vi_add_at_eol(EditLine *el, wint_t c __attribute__((__unused__))) { el->el_map.current = el->el_map.key; el->el_line.cursor = el->el_line.lastchar; cv_undo(el); return CC_CURSOR; } /* vi_delete_meta(): * Vi delete prefix command * [d] */ libedit_private el_action_t /*ARGSUSED*/ vi_delete_meta(EditLine *el, wint_t c __attribute__((__unused__))) { return cv_action(el, DELETE); } /* vi_end_big_word(): * Vi move to the end of the current space delimited word * [E] */ libedit_private el_action_t /*ARGSUSED*/ vi_end_big_word(EditLine *el, wint_t c __attribute__((__unused__))) { if (el->el_line.cursor == el->el_line.lastchar) return CC_ERROR; el->el_line.cursor = cv__endword(el->el_line.cursor, el->el_line.lastchar, el->el_state.argument, cv__isWord); if (el->el_chared.c_vcmd.action != NOP) { el->el_line.cursor++; cv_delfini(el); return CC_REFRESH; } return CC_CURSOR; } /* vi_end_word(): * Vi move to the end of the current word * [e] */ libedit_private el_action_t /*ARGSUSED*/ vi_end_word(EditLine *el, wint_t c __attribute__((__unused__))) { if (el->el_line.cursor == el->el_line.lastchar) return CC_ERROR; el->el_line.cursor = cv__endword(el->el_line.cursor, el->el_line.lastchar, el->el_state.argument, cv__isword); if (el->el_chared.c_vcmd.action != NOP) { el->el_line.cursor++; cv_delfini(el); return CC_REFRESH; } return CC_CURSOR; } /* vi_undo(): * Vi undo last change * [u] */ libedit_private el_action_t /*ARGSUSED*/ vi_undo(EditLine *el, wint_t c __attribute__((__unused__))) { c_undo_t un = el->el_chared.c_undo; if (un.len == -1) return CC_ERROR; /* switch line buffer and undo buffer */ el->el_chared.c_undo.buf = el->el_line.buffer; el->el_chared.c_undo.len = el->el_line.lastchar - el->el_line.buffer; el->el_chared.c_undo.cursor = (int)(el->el_line.cursor - el->el_line.buffer); el->el_line.limit = un.buf + (el->el_line.limit - el->el_line.buffer); el->el_line.buffer = un.buf; el->el_line.cursor = un.buf + un.cursor; el->el_line.lastchar = un.buf + un.len; return CC_REFRESH; } /* vi_command_mode(): * Vi enter command mode (use alternative key bindings) * [] */ libedit_private el_action_t /*ARGSUSED*/ vi_command_mode(EditLine *el, wint_t c __attribute__((__unused__))) { /* [Esc] cancels pending action */ el->el_chared.c_vcmd.action = NOP; el->el_chared.c_vcmd.pos = 0; el->el_state.doingarg = 0; el->el_state.inputmode = MODE_INSERT; el->el_map.current = el->el_map.alt; #ifdef VI_MOVE if (el->el_line.cursor > el->el_line.buffer) el->el_line.cursor--; #endif return CC_CURSOR; } /* vi_zero(): * Vi move to the beginning of line * [0] */ libedit_private el_action_t vi_zero(EditLine *el, wint_t c) { if (el->el_state.doingarg) return ed_argument_digit(el, c); el->el_line.cursor = el->el_line.buffer; if (el->el_chared.c_vcmd.action != NOP) { cv_delfini(el); return CC_REFRESH; } return CC_CURSOR; } /* vi_delete_prev_char(): * Vi move to previous character (backspace) * [^H] in insert mode only */ libedit_private el_action_t /*ARGSUSED*/ vi_delete_prev_char(EditLine *el, wint_t c __attribute__((__unused__))) { if (el->el_line.cursor <= el->el_line.buffer) return CC_ERROR; c_delbefore1(el); el->el_line.cursor--; return CC_REFRESH; } /* vi_list_or_eof(): * Vi list choices for completion or indicate end of file if empty line * [^D] */ libedit_private el_action_t /*ARGSUSED*/ vi_list_or_eof(EditLine *el, wint_t c) { if (el->el_line.cursor == el->el_line.lastchar) { if (el->el_line.cursor == el->el_line.buffer) { terminal_writec(el, c); /* then do a EOF */ return CC_EOF; } else { /* * Here we could list completions, but it is an * error right now */ terminal_beep(el); return CC_ERROR; } } else { #ifdef notyet re_goto_bottom(el); *el->el_line.lastchar = '\0'; /* just in case */ return CC_LIST_CHOICES; #else /* * Just complain for now. */ terminal_beep(el); return CC_ERROR; #endif } } /* vi_kill_line_prev(): * Vi cut from beginning of line to cursor * [^U] */ libedit_private el_action_t /*ARGSUSED*/ vi_kill_line_prev(EditLine *el, wint_t c __attribute__((__unused__))) { wchar_t *kp, *cp; cp = el->el_line.buffer; kp = el->el_chared.c_kill.buf; while (cp < el->el_line.cursor) *kp++ = *cp++; /* copy it */ el->el_chared.c_kill.last = kp; c_delbefore(el, (int)(el->el_line.cursor - el->el_line.buffer)); el->el_line.cursor = el->el_line.buffer; /* zap! */ return CC_REFRESH; } /* vi_search_prev(): * Vi search history previous * [?] */ libedit_private el_action_t /*ARGSUSED*/ vi_search_prev(EditLine *el, wint_t c __attribute__((__unused__))) { return cv_search(el, ED_SEARCH_PREV_HISTORY); } /* vi_search_next(): * Vi search history next * [/] */ libedit_private el_action_t /*ARGSUSED*/ vi_search_next(EditLine *el, wint_t c __attribute__((__unused__))) { return cv_search(el, ED_SEARCH_NEXT_HISTORY); } /* vi_repeat_search_next(): * Vi repeat current search in the same search direction * [n] */ libedit_private el_action_t /*ARGSUSED*/ vi_repeat_search_next(EditLine *el, wint_t c __attribute__((__unused__))) { if (el->el_search.patlen == 0) return CC_ERROR; else return cv_repeat_srch(el, el->el_search.patdir); } /* vi_repeat_search_prev(): * Vi repeat current search in the opposite search direction * [N] */ /*ARGSUSED*/ libedit_private el_action_t vi_repeat_search_prev(EditLine *el, wint_t c __attribute__((__unused__))) { if (el->el_search.patlen == 0) return CC_ERROR; else return (cv_repeat_srch(el, el->el_search.patdir == ED_SEARCH_PREV_HISTORY ? ED_SEARCH_NEXT_HISTORY : ED_SEARCH_PREV_HISTORY)); } /* vi_next_char(): * Vi move to the character specified next * [f] */ libedit_private el_action_t /*ARGSUSED*/ vi_next_char(EditLine *el, wint_t c __attribute__((__unused__))) { return cv_csearch(el, CHAR_FWD, -1, el->el_state.argument, 0); } /* vi_prev_char(): * Vi move to the character specified previous * [F] */ libedit_private el_action_t /*ARGSUSED*/ vi_prev_char(EditLine *el, wint_t c __attribute__((__unused__))) { return cv_csearch(el, CHAR_BACK, -1, el->el_state.argument, 0); } /* vi_to_next_char(): * Vi move up to the character specified next * [t] */ libedit_private el_action_t /*ARGSUSED*/ vi_to_next_char(EditLine *el, wint_t c __attribute__((__unused__))) { return cv_csearch(el, CHAR_FWD, -1, el->el_state.argument, 1); } /* vi_to_prev_char(): * Vi move up to the character specified previous * [T] */ libedit_private el_action_t /*ARGSUSED*/ vi_to_prev_char(EditLine *el, wint_t c __attribute__((__unused__))) { return cv_csearch(el, CHAR_BACK, -1, el->el_state.argument, 1); } /* vi_repeat_next_char(): * Vi repeat current character search in the same search direction * [;] */ libedit_private el_action_t /*ARGSUSED*/ vi_repeat_next_char(EditLine *el, wint_t c __attribute__((__unused__))) { return cv_csearch(el, el->el_search.chadir, el->el_search.chacha, el->el_state.argument, el->el_search.chatflg); } /* vi_repeat_prev_char(): * Vi repeat current character search in the opposite search direction * [,] */ libedit_private el_action_t /*ARGSUSED*/ vi_repeat_prev_char(EditLine *el, wint_t c __attribute__((__unused__))) { el_action_t r; int dir = el->el_search.chadir; r = cv_csearch(el, -dir, el->el_search.chacha, el->el_state.argument, el->el_search.chatflg); el->el_search.chadir = dir; return r; } /* vi_match(): * Vi go to matching () {} or [] * [%] */ libedit_private el_action_t /*ARGSUSED*/ vi_match(EditLine *el, wint_t c __attribute__((__unused__))) { const wchar_t match_chars[] = L"()[]{}"; wchar_t *cp; size_t delta, i, count; wchar_t o_ch, c_ch; *el->el_line.lastchar = '\0'; /* just in case */ i = wcscspn(el->el_line.cursor, match_chars); o_ch = el->el_line.cursor[i]; if (o_ch == 0) return CC_ERROR; delta = (size_t)(wcschr(match_chars, o_ch) - match_chars); c_ch = match_chars[delta ^ 1]; count = 1; delta = 1 - (delta & 1) * 2; for (cp = &el->el_line.cursor[i]; count; ) { cp += delta; if (cp < el->el_line.buffer || cp >= el->el_line.lastchar) return CC_ERROR; if (*cp == o_ch) count++; else if (*cp == c_ch) count--; } el->el_line.cursor = cp; if (el->el_chared.c_vcmd.action != NOP) { /* NB posix says char under cursor should NOT be deleted for -ve delta - this is different to netbsd vi. */ if (delta > 0) el->el_line.cursor++; cv_delfini(el); return CC_REFRESH; } return CC_CURSOR; } /* vi_undo_line(): * Vi undo all changes to line * [U] */ libedit_private el_action_t /*ARGSUSED*/ vi_undo_line(EditLine *el, wint_t c __attribute__((__unused__))) { cv_undo(el); return hist_get(el); } /* vi_to_column(): * Vi go to specified column * [|] * NB netbsd vi goes to screen column 'n', posix says nth character */ libedit_private el_action_t /*ARGSUSED*/ vi_to_column(EditLine *el, wint_t c __attribute__((__unused__))) { el->el_line.cursor = el->el_line.buffer; el->el_state.argument--; return ed_next_char(el, 0); } /* vi_yank_end(): * Vi yank to end of line * [Y] */ libedit_private el_action_t /*ARGSUSED*/ vi_yank_end(EditLine *el, wint_t c __attribute__((__unused__))) { cv_yank(el, el->el_line.cursor, (int)(el->el_line.lastchar - el->el_line.cursor)); return CC_REFRESH; } /* vi_yank(): * Vi yank * [y] */ libedit_private el_action_t /*ARGSUSED*/ vi_yank(EditLine *el, wint_t c __attribute__((__unused__))) { return cv_action(el, YANK); } /* vi_comment_out(): * Vi comment out current command * [#] */ libedit_private el_action_t /*ARGSUSED*/ vi_comment_out(EditLine *el, wint_t c __attribute__((__unused__))) { el->el_line.cursor = el->el_line.buffer; c_insert(el, 1); *el->el_line.cursor = '#'; re_refresh(el); return ed_newline(el, 0); } /* vi_alias(): * Vi include shell alias * [@] * NB: posix implies that we should enter insert mode, however * this is against historical precedent... */ libedit_private el_action_t /*ARGSUSED*/ vi_alias(EditLine *el, wint_t c __attribute__((__unused__))) { char alias_name[3]; const char *alias_text; if (el->el_chared.c_aliasfun == NULL) return CC_ERROR; alias_name[0] = '_'; alias_name[2] = 0; if (el_getc(el, &alias_name[1]) != 1) return CC_ERROR; alias_text = (*el->el_chared.c_aliasfun)(el->el_chared.c_aliasarg, alias_name); if (alias_text != NULL) el_wpush(el, ct_decode_string(alias_text, &el->el_scratch)); return CC_NORM; } /* vi_to_history_line(): * Vi go to specified history file line. * [G] */ libedit_private el_action_t /*ARGSUSED*/ vi_to_history_line(EditLine *el, wint_t c __attribute__((__unused__))) { int sv_event_no = el->el_history.eventno; el_action_t rval; if (el->el_history.eventno == 0) { (void) wcsncpy(el->el_history.buf, el->el_line.buffer, EL_BUFSIZ); el->el_history.last = el->el_history.buf + (el->el_line.lastchar - el->el_line.buffer); } /* Lack of a 'count' means oldest, not 1 */ if (!el->el_state.doingarg) { el->el_history.eventno = 0x7fffffff; hist_get(el); } else { /* This is brain dead, all the rest of this code counts * upwards going into the past. Here we need count in the * other direction (to match the output of fc -l). * I could change the world, but this seems to suffice. */ el->el_history.eventno = 1; if (hist_get(el) == CC_ERROR) return CC_ERROR; el->el_history.eventno = 1 + el->el_history.ev.num - el->el_state.argument; if (el->el_history.eventno < 0) { el->el_history.eventno = sv_event_no; return CC_ERROR; } } rval = hist_get(el); if (rval == CC_ERROR) el->el_history.eventno = sv_event_no; return rval; } /* vi_histedit(): * Vi edit history line with vi * [v] */ libedit_private el_action_t /*ARGSUSED*/ vi_histedit(EditLine *el, wint_t c __attribute__((__unused__))) { int fd; pid_t pid; ssize_t st; int status; char tempfile[] = "/tmp/histedit.XXXXXXXXXX"; char *cp = NULL; size_t len; wchar_t *line = NULL; if (el->el_state.doingarg) { if (vi_to_history_line(el, 0) == CC_ERROR) return CC_ERROR; } fd = mkstemp(tempfile); if (fd < 0) return CC_ERROR; len = (size_t)(el->el_line.lastchar - el->el_line.buffer); #define TMP_BUFSIZ (EL_BUFSIZ * MB_LEN_MAX) cp = el_malloc(TMP_BUFSIZ * sizeof(*cp)); if (cp == NULL) goto error; line = el_malloc(len * sizeof(*line) + 1); if (line == NULL) goto error; wcsncpy(line, el->el_line.buffer, len); line[len] = '\0'; wcstombs(cp, line, TMP_BUFSIZ - 1); cp[TMP_BUFSIZ - 1] = '\0'; len = strlen(cp); write(fd, cp, len); write(fd, "\n", (size_t)1); pid = fork(); switch (pid) { case -1: goto error; case 0: close(fd); execlp("vi", "vi", tempfile, (char *)NULL); exit(0); /*NOTREACHED*/ default: while (waitpid(pid, &status, 0) != pid) continue; lseek(fd, (off_t)0, SEEK_SET); st = read(fd, cp, TMP_BUFSIZ - 1); if (st > 0) { cp[st] = '\0'; len = (size_t)(el->el_line.limit - el->el_line.buffer); len = mbstowcs(el->el_line.buffer, cp, len); if (len > 0 && el->el_line.buffer[len - 1] == '\n') --len; } else len = 0; el->el_line.cursor = el->el_line.buffer; el->el_line.lastchar = el->el_line.buffer + len; el_free(cp); el_free(line); break; } close(fd); unlink(tempfile); /* return CC_REFRESH; */ return ed_newline(el, 0); error: el_free(line); el_free(cp); close(fd); unlink(tempfile); return CC_ERROR; } /* vi_history_word(): * Vi append word from previous input line * [_] * Who knows where this one came from! * '_' in vi means 'entire current line', so 'cc' is a synonym for 'c_' */ libedit_private el_action_t /*ARGSUSED*/ vi_history_word(EditLine *el, wint_t c __attribute__((__unused__))) { const wchar_t *wp = HIST_FIRST(el); const wchar_t *wep, *wsp; int len; wchar_t *cp; const wchar_t *lim; if (wp == NULL) return CC_ERROR; wep = wsp = NULL; do { while (iswspace(*wp)) wp++; if (*wp == 0) break; wsp = wp; while (*wp && !iswspace(*wp)) wp++; wep = wp; } while ((!el->el_state.doingarg || --el->el_state.argument > 0) && *wp != 0); if (wsp == NULL || (el->el_state.doingarg && el->el_state.argument != 0)) return CC_ERROR; cv_undo(el); len = (int)(wep - wsp); if (el->el_line.cursor < el->el_line.lastchar) el->el_line.cursor++; c_insert(el, len + 1); cp = el->el_line.cursor; lim = el->el_line.limit; if (cp < lim) *cp++ = ' '; while (wsp < wep && cp < lim) *cp++ = *wsp++; el->el_line.cursor = cp; el->el_map.current = el->el_map.key; return CC_REFRESH; } /* vi_redo(): * Vi redo last non-motion command * [.] */ libedit_private el_action_t /*ARGSUSED*/ vi_redo(EditLine *el, wint_t c __attribute__((__unused__))) { c_redo_t *r = &el->el_chared.c_redo; if (!el->el_state.doingarg && r->count) { el->el_state.doingarg = 1; el->el_state.argument = r->count; } el->el_chared.c_vcmd.pos = el->el_line.cursor; el->el_chared.c_vcmd.action = r->action; if (r->pos != r->buf) { if (r->pos + 1 > r->lim) /* sanity */ r->pos = r->lim - 1; r->pos[0] = 0; el_wpush(el, r->buf); } el->el_state.thiscmd = r->cmd; el->el_state.thisch = r->ch; return (*el->el_map.func[r->cmd])(el, r->ch); } heimdal-7.5.0/lib/libedit/src/parse.h0000644000175000017500000000416213026237312015510 0ustar niknik/* $NetBSD: parse.h,v 1.9 2016/05/09 21:46:56 christos Exp $ */ /*- * Copyright (c) 1992, 1993 * The Regents of the University of California. All rights reserved. * * This code is derived from software contributed to Berkeley by * Christos Zoulas of Cornell University. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the University nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * * @(#)parse.h 8.1 (Berkeley) 6/4/93 */ /* * el.parse.h: Parser functions */ #ifndef _h_el_parse #define _h_el_parse libedit_private int parse_line(EditLine *, const wchar_t *); libedit_private int parse__escape(const wchar_t **); libedit_private wchar_t *parse__string(wchar_t *, const wchar_t *); libedit_private int parse_cmd(EditLine *, const wchar_t *); #endif /* _h_el_parse */ heimdal-7.5.0/lib/libedit/src/Makefile.in0000644000175000017500000005650013212444505016276 0ustar niknik# Makefile.in generated by automake 1.15.1 from Makefile.am. # @configure_input@ # Copyright (C) 1994-2017 Free Software Foundation, Inc. # This Makefile.in is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, # with or without modifications, as long as this notice is preserved. # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY, to the extent permitted by law; without # even the implied warranty of MERCHANTABILITY or FITNESS FOR A # PARTICULAR PURPOSE. @SET_MAKE@ VPATH = @srcdir@ am__is_gnu_make = { \ if test -z '$(MAKELEVEL)'; then \ false; \ elif test -n '$(MAKE_HOST)'; then \ true; \ elif test -n '$(MAKE_VERSION)' && test -n '$(CURDIR)'; then \ true; \ else \ false; \ fi; \ } am__make_running_with_option = \ case $${target_option-} in \ ?) ;; \ *) echo "am__make_running_with_option: internal error: invalid" \ "target option '$${target_option-}' specified" >&2; \ exit 1;; \ esac; \ has_opt=no; \ sane_makeflags=$$MAKEFLAGS; \ if $(am__is_gnu_make); then \ sane_makeflags=$$MFLAGS; \ else \ case $$MAKEFLAGS in \ *\\[\ \ ]*) \ bs=\\; \ sane_makeflags=`printf '%s\n' "$$MAKEFLAGS" \ | sed "s/$$bs$$bs[$$bs $$bs ]*//g"`;; \ esac; \ fi; \ skip_next=no; \ strip_trailopt () \ { \ flg=`printf '%s\n' "$$flg" | sed "s/$$1.*$$//"`; \ }; \ for flg in $$sane_makeflags; do \ test $$skip_next = yes && { skip_next=no; continue; }; \ case $$flg in \ *=*|--*) continue;; \ -*I) strip_trailopt 'I'; skip_next=yes;; \ -*I?*) strip_trailopt 'I';; \ -*O) strip_trailopt 'O'; skip_next=yes;; \ -*O?*) strip_trailopt 'O';; \ -*l) strip_trailopt 'l'; skip_next=yes;; \ -*l?*) strip_trailopt 'l';; \ -[dEDm]) skip_next=yes;; \ -[JT]) skip_next=yes;; \ esac; \ case $$flg in \ *$$target_option*) has_opt=yes; break;; \ esac; \ done; \ test $$has_opt = yes am__make_dryrun = (target_option=n; $(am__make_running_with_option)) am__make_keepgoing = (target_option=k; $(am__make_running_with_option)) pkgdatadir = $(datadir)/@PACKAGE@ pkgincludedir = $(includedir)/@PACKAGE@ pkglibdir = $(libdir)/@PACKAGE@ pkglibexecdir = $(libexecdir)/@PACKAGE@ am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd install_sh_DATA = $(install_sh) -c -m 644 install_sh_PROGRAM = $(install_sh) -c install_sh_SCRIPT = $(install_sh) -c INSTALL_HEADER = $(INSTALL_DATA) transform = $(program_transform_name) NORMAL_INSTALL = : PRE_INSTALL = : POST_INSTALL = : NORMAL_UNINSTALL = : PRE_UNINSTALL = : POST_UNINSTALL = : build_triplet = @build@ host_triplet = @host@ subdir = src ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 am__aclocal_m4_deps = $(top_srcdir)/acinclude.m4 \ $(top_srcdir)/configure.ac am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \ $(ACLOCAL_M4) DIST_COMMON = $(srcdir)/Makefile.am $(am__DIST_COMMON) mkinstalldirs = $(install_sh) -d CONFIG_HEADER = $(top_builddir)/config.h CONFIG_CLEAN_FILES = CONFIG_CLEAN_VPATH_FILES = am__vpath_adj_setup = srcdirstrip=`echo "$(srcdir)" | sed 's|.|.|g'`; am__vpath_adj = case $$p in \ $(srcdir)/*) f=`echo "$$p" | sed "s|^$$srcdirstrip/||"`;; \ *) f=$$p;; \ esac; am__strip_dir = f=`echo $$p | sed -e 's|^.*/||'`; am__install_max = 40 am__nobase_strip_setup = \ srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*|]/\\\\&/g'` am__nobase_strip = \ for p in $$list; do echo "$$p"; done | sed -e "s|$$srcdirstrip/||" am__nobase_list = $(am__nobase_strip_setup); \ for p in $$list; do echo "$$p $$p"; done | \ sed "s| $$srcdirstrip/| |;"' / .*\//!s/ .*/ ./; s,\( .*\)/[^/]*$$,\1,' | \ $(AWK) 'BEGIN { files["."] = "" } { files[$$2] = files[$$2] " " $$1; \ if (++n[$$2] == $(am__install_max)) \ { print $$2, files[$$2]; n[$$2] = 0; files[$$2] = "" } } \ END { for (dir in files) print dir, files[dir] }' am__base_list = \ sed '$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;s/\n/ /g' | \ sed '$$!N;$$!N;$$!N;$$!N;s/\n/ /g' am__uninstall_files_from_dir = { \ test -z "$$files" \ || { test ! -d "$$dir" && test ! -f "$$dir" && test ! -r "$$dir"; } \ || { echo " ( cd '$$dir' && rm -f" $$files ")"; \ $(am__cd) "$$dir" && rm -f $$files; }; \ } am__installdirs = "$(DESTDIR)$(libdir)" LTLIBRARIES = $(lib_LTLIBRARIES) libheimedit_la_LIBADD = am_libheimedit_la_OBJECTS = chared.lo chartype.lo common.lo el.lo \ eln.lo emacs.lo filecomplete.lo hist.lo history.lo historyn.lo \ keymacro.lo map.lo parse.lo prompt.lo read.lo readline.lo \ refresh.lo search.lo sig.lo terminal.lo tokenizer.lo \ tokenizern.lo tty.lo unvis.lo vi.lo vis.lo wcsdup.lo am__objects_1 = nodist_libheimedit_la_OBJECTS = $(am__objects_1) libheimedit_la_OBJECTS = $(am_libheimedit_la_OBJECTS) \ $(nodist_libheimedit_la_OBJECTS) AM_V_lt = $(am__v_lt_@AM_V@) am__v_lt_ = $(am__v_lt_@AM_DEFAULT_V@) am__v_lt_0 = --silent am__v_lt_1 = libheimedit_la_LINK = $(LIBTOOL) $(AM_V_lt) --tag=CC \ $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=link $(CCLD) \ $(AM_CFLAGS) $(CFLAGS) $(libheimedit_la_LDFLAGS) $(LDFLAGS) -o \ $@ AM_V_P = $(am__v_P_@AM_V@) am__v_P_ = $(am__v_P_@AM_DEFAULT_V@) am__v_P_0 = false am__v_P_1 = : AM_V_GEN = $(am__v_GEN_@AM_V@) am__v_GEN_ = $(am__v_GEN_@AM_DEFAULT_V@) am__v_GEN_0 = @echo " GEN " $@; am__v_GEN_1 = AM_V_at = $(am__v_at_@AM_V@) am__v_at_ = $(am__v_at_@AM_DEFAULT_V@) am__v_at_0 = @ am__v_at_1 = DEFAULT_INCLUDES = -I.@am__isrc@ -I$(top_builddir) depcomp = $(SHELL) $(top_srcdir)/depcomp am__depfiles_maybe = depfiles am__mv = mv -f COMPILE = $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) \ $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) LTCOMPILE = $(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) \ $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) \ $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) \ $(AM_CFLAGS) $(CFLAGS) AM_V_CC = $(am__v_CC_@AM_V@) am__v_CC_ = $(am__v_CC_@AM_DEFAULT_V@) am__v_CC_0 = @echo " CC " $@; am__v_CC_1 = CCLD = $(CC) LINK = $(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) \ $(LIBTOOLFLAGS) --mode=link $(CCLD) $(AM_CFLAGS) $(CFLAGS) \ $(AM_LDFLAGS) $(LDFLAGS) -o $@ AM_V_CCLD = $(am__v_CCLD_@AM_V@) am__v_CCLD_ = $(am__v_CCLD_@AM_DEFAULT_V@) am__v_CCLD_0 = @echo " CCLD " $@; am__v_CCLD_1 = SOURCES = $(libheimedit_la_SOURCES) $(nodist_libheimedit_la_SOURCES) DIST_SOURCES = $(libheimedit_la_SOURCES) am__can_run_installinfo = \ case $$AM_UPDATE_INFO_DIR in \ n|no|NO) false;; \ *) (install-info --version) >/dev/null 2>&1;; \ esac am__tagged_files = $(HEADERS) $(SOURCES) $(TAGS_FILES) $(LISP) # Read a list of newline-separated strings from the standard input, # and print each of them once, without duplicates. Input order is # *not* preserved. am__uniquify_input = $(AWK) '\ BEGIN { nonempty = 0; } \ { items[$$0] = 1; nonempty = 1; } \ END { if (nonempty) { for (i in items) print i; }; } \ ' # Make sure the list of sources is unique. This is necessary because, # e.g., the same source file might be shared among _SOURCES variables # for different programs/libraries. am__define_uniq_tagged_files = \ list='$(am__tagged_files)'; \ unique=`for i in $$list; do \ if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ done | $(am__uniquify_input)` ETAGS = etags CTAGS = ctags am__DIST_COMMON = $(srcdir)/Makefile.in $(top_srcdir)/depcomp DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST) ACLOCAL = @ACLOCAL@ AMTAR = @AMTAR@ AM_DEFAULT_VERBOSITY = @AM_DEFAULT_VERBOSITY@ AR = @AR@ AUTOCONF = @AUTOCONF@ AUTOHEADER = @AUTOHEADER@ AUTOMAKE = @AUTOMAKE@ AWK = @AWK@ CC = @CC@ CCDEPMODE = @CCDEPMODE@ CFLAGS = @CFLAGS@ CPP = @CPP@ CPPFLAGS = @CPPFLAGS@ CYGPATH_W = @CYGPATH_W@ DEFS = @DEFS@ DEPDIR = @DEPDIR@ DLLTOOL = @DLLTOOL@ DSYMUTIL = @DSYMUTIL@ DUMPBIN = @DUMPBIN@ ECHO_C = @ECHO_C@ ECHO_N = @ECHO_N@ ECHO_T = @ECHO_T@ EGREP = @EGREP@ EXEEXT = @EXEEXT@ FGREP = @FGREP@ GREP = @GREP@ INSTALL = @INSTALL@ INSTALL_DATA = @INSTALL_DATA@ INSTALL_PROGRAM = @INSTALL_PROGRAM@ INSTALL_SCRIPT = @INSTALL_SCRIPT@ INSTALL_STRIP_PROGRAM = @INSTALL_STRIP_PROGRAM@ LD = @LD@ LDFLAGS = @LDFLAGS@ LIBOBJS = @LIBOBJS@ LIBS = @LIBS@ LIBTOOL = @LIBTOOL@ LIPO = @LIPO@ LN_S = @LN_S@ LTLIBOBJS = @LTLIBOBJS@ LT_SYS_LIBRARY_PATH = @LT_SYS_LIBRARY_PATH@ LT_VERSION = @LT_VERSION@ MAKEINFO = @MAKEINFO@ MANIFEST_TOOL = @MANIFEST_TOOL@ MANTYPE = @MANTYPE@ MKDIR_P = @MKDIR_P@ NM = @NM@ NMEDIT = @NMEDIT@ NROFF = @NROFF@ OBJDUMP = @OBJDUMP@ OBJEXT = @OBJEXT@ OTOOL = @OTOOL@ OTOOL64 = @OTOOL64@ PACKAGE = @PACKAGE@ PACKAGE_BUGREPORT = @PACKAGE_BUGREPORT@ PACKAGE_NAME = @PACKAGE_NAME@ PACKAGE_STRING = @PACKAGE_STRING@ PACKAGE_TARNAME = @PACKAGE_TARNAME@ PACKAGE_URL = @PACKAGE_URL@ PACKAGE_VERSION = @PACKAGE_VERSION@ PATH_SEPARATOR = @PATH_SEPARATOR@ RANLIB = @RANLIB@ SED = @SED@ SET_MAKE = @SET_MAKE@ SHELL = @SHELL@ STRIP = @STRIP@ VERSION = @VERSION@ abs_builddir = @abs_builddir@ abs_srcdir = @abs_srcdir@ abs_top_builddir = @abs_top_builddir@ abs_top_srcdir = @abs_top_srcdir@ ac_ct_AR = @ac_ct_AR@ ac_ct_CC = @ac_ct_CC@ ac_ct_DUMPBIN = @ac_ct_DUMPBIN@ am__include = @am__include@ am__leading_dot = @am__leading_dot@ am__quote = @am__quote@ am__tar = @am__tar@ am__untar = @am__untar@ bindir = @bindir@ build = @build@ build_alias = @build_alias@ build_cpu = @build_cpu@ build_os = @build_os@ build_vendor = @build_vendor@ builddir = @builddir@ datadir = @datadir@ datarootdir = @datarootdir@ docdir = @docdir@ dvidir = @dvidir@ exec_prefix = @exec_prefix@ host = @host@ host_alias = @host_alias@ host_cpu = @host_cpu@ host_os = @host_os@ host_vendor = @host_vendor@ htmldir = @htmldir@ includedir = @includedir@ infodir = @infodir@ install_sh = @install_sh@ libdir = @libdir@ libexecdir = @libexecdir@ localedir = @localedir@ localstatedir = @localstatedir@ mandir = @mandir@ mkdir_p = @mkdir_p@ oldincludedir = @oldincludedir@ pdfdir = @pdfdir@ prefix = @prefix@ program_transform_name = @program_transform_name@ psdir = @psdir@ sbindir = @sbindir@ sharedstatedir = @sharedstatedir@ srcdir = @srcdir@ sysconfdir = @sysconfdir@ target_alias = @target_alias@ top_build_prefix = @top_build_prefix@ top_builddir = @top_builddir@ top_srcdir = @top_srcdir@ BUILT_SOURCES = vi.h emacs.h common.h fcns.h help.h func.h AHDR = vi.h emacs.h common.h ASRC = $(srcdir)/vi.c $(srcdir)/emacs.c $(srcdir)/common.c CLEANFILES = $(BUILT_SOURCES) lib_LTLIBRARIES = libheimedit.la libheimedit_la_SOURCES = \ chared.c chartype.c common.c el.c eln.c emacs.c filecomplete.c hist.c \ history.c historyn.c keymacro.c map.c parse.c prompt.c read.c readline.c \ refresh.c search.c sig.c terminal.c tokenizer.c tokenizern.c tty.c \ unvis.c vi.c vis.c wcsdup.c \ chared.h chartype.h readline/readline.h el.h filecomplete.h \ histedit.h hist.h keymacro.h map.h parse.h prompt.h read.h \ refresh.h search.h sig.h sys.h terminal.h tty.h vis.h EXTRA_DIST = makelist shlib_version histedit.h readline/readline.h nodist_libheimedit_la_SOURCES = $(BUILT_SOURCES) libheimedit_la_LDFLAGS = -no-undefined -version-info $(LT_VERSION) all: $(BUILT_SOURCES) $(MAKE) $(AM_MAKEFLAGS) all-am .SUFFIXES: .SUFFIXES: .c .lo .o .obj $(srcdir)/Makefile.in: $(srcdir)/Makefile.am $(am__configure_deps) @for dep in $?; do \ case '$(am__configure_deps)' in \ *$$dep*) \ ( cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh ) \ && { if test -f $@; then exit 0; else break; fi; }; \ exit 1;; \ esac; \ done; \ echo ' cd $(top_srcdir) && $(AUTOMAKE) --gnu src/Makefile'; \ $(am__cd) $(top_srcdir) && \ $(AUTOMAKE) --gnu src/Makefile Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status @case '$?' in \ *config.status*) \ cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh;; \ *) \ echo ' cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe)'; \ cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe);; \ esac; $(top_builddir)/config.status: $(top_srcdir)/configure $(CONFIG_STATUS_DEPENDENCIES) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(top_srcdir)/configure: $(am__configure_deps) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(ACLOCAL_M4): $(am__aclocal_m4_deps) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(am__aclocal_m4_deps): install-libLTLIBRARIES: $(lib_LTLIBRARIES) @$(NORMAL_INSTALL) @list='$(lib_LTLIBRARIES)'; test -n "$(libdir)" || list=; \ list2=; for p in $$list; do \ if test -f $$p; then \ list2="$$list2 $$p"; \ else :; fi; \ done; \ test -z "$$list2" || { \ echo " $(MKDIR_P) '$(DESTDIR)$(libdir)'"; \ $(MKDIR_P) "$(DESTDIR)$(libdir)" || exit 1; \ echo " $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=install $(INSTALL) $(INSTALL_STRIP_FLAG) $$list2 '$(DESTDIR)$(libdir)'"; \ $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=install $(INSTALL) $(INSTALL_STRIP_FLAG) $$list2 "$(DESTDIR)$(libdir)"; \ } uninstall-libLTLIBRARIES: @$(NORMAL_UNINSTALL) @list='$(lib_LTLIBRARIES)'; test -n "$(libdir)" || list=; \ for p in $$list; do \ $(am__strip_dir) \ echo " $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=uninstall rm -f '$(DESTDIR)$(libdir)/$$f'"; \ $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=uninstall rm -f "$(DESTDIR)$(libdir)/$$f"; \ done clean-libLTLIBRARIES: -test -z "$(lib_LTLIBRARIES)" || rm -f $(lib_LTLIBRARIES) @list='$(lib_LTLIBRARIES)'; \ locs=`for p in $$list; do echo $$p; done | \ sed 's|^[^/]*$$|.|; s|/[^/]*$$||; s|$$|/so_locations|' | \ sort -u`; \ test -z "$$locs" || { \ echo rm -f $${locs}; \ rm -f $${locs}; \ } libheimedit.la: $(libheimedit_la_OBJECTS) $(libheimedit_la_DEPENDENCIES) $(EXTRA_libheimedit_la_DEPENDENCIES) $(AM_V_CCLD)$(libheimedit_la_LINK) -rpath $(libdir) $(libheimedit_la_OBJECTS) $(libheimedit_la_LIBADD) $(LIBS) mostlyclean-compile: -rm -f *.$(OBJEXT) distclean-compile: -rm -f *.tab.c @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/chared.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/chartype.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/common.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/el.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/eln.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/emacs.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/filecomplete.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/hist.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/history.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/historyn.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/keymacro.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/map.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/parse.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/prompt.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/read.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/readline.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/refresh.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/search.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/sig.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/terminal.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/tokenizer.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/tokenizern.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/tty.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/unvis.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/vi.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/vis.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/wcsdup.Plo@am__quote@ .c.o: @am__fastdepCC_TRUE@ $(AM_V_CC)$(COMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o $@ $< @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='$<' object='$@' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(COMPILE) -c -o $@ $< .c.obj: @am__fastdepCC_TRUE@ $(AM_V_CC)$(COMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o $@ `$(CYGPATH_W) '$<'` @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='$<' object='$@' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(COMPILE) -c -o $@ `$(CYGPATH_W) '$<'` .c.lo: @am__fastdepCC_TRUE@ $(AM_V_CC)$(LTCOMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o $@ $< @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='$<' object='$@' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LTCOMPILE) -c -o $@ $< mostlyclean-libtool: -rm -f *.lo clean-libtool: -rm -rf .libs _libs ID: $(am__tagged_files) $(am__define_uniq_tagged_files); mkid -fID $$unique tags: tags-am TAGS: tags tags-am: $(TAGS_DEPENDENCIES) $(am__tagged_files) set x; \ here=`pwd`; \ $(am__define_uniq_tagged_files); \ shift; \ if test -z "$(ETAGS_ARGS)$$*$$unique"; then :; else \ test -n "$$unique" || unique=$$empty_fix; \ if test $$# -gt 0; then \ $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ "$$@" $$unique; \ else \ $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ $$unique; \ fi; \ fi ctags: ctags-am CTAGS: ctags ctags-am: $(TAGS_DEPENDENCIES) $(am__tagged_files) $(am__define_uniq_tagged_files); \ test -z "$(CTAGS_ARGS)$$unique" \ || $(CTAGS) $(CTAGSFLAGS) $(AM_CTAGSFLAGS) $(CTAGS_ARGS) \ $$unique GTAGS: here=`$(am__cd) $(top_builddir) && pwd` \ && $(am__cd) $(top_srcdir) \ && gtags -i $(GTAGS_ARGS) "$$here" cscopelist: cscopelist-am cscopelist-am: $(am__tagged_files) list='$(am__tagged_files)'; \ case "$(srcdir)" in \ [\\/]* | ?:[\\/]*) sdir="$(srcdir)" ;; \ *) sdir=$(subdir)/$(srcdir) ;; \ esac; \ for i in $$list; do \ if test -f "$$i"; then \ echo "$(subdir)/$$i"; \ else \ echo "$$sdir/$$i"; \ fi; \ done >> $(top_builddir)/cscope.files distclean-tags: -rm -f TAGS ID GTAGS GRTAGS GSYMS GPATH tags distdir: $(DISTFILES) @srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ topsrcdirstrip=`echo "$(top_srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ list='$(DISTFILES)'; \ dist_files=`for file in $$list; do echo $$file; done | \ sed -e "s|^$$srcdirstrip/||;t" \ -e "s|^$$topsrcdirstrip/|$(top_builddir)/|;t"`; \ case $$dist_files in \ */*) $(MKDIR_P) `echo "$$dist_files" | \ sed '/\//!d;s|^|$(distdir)/|;s,/[^/]*$$,,' | \ sort -u` ;; \ esac; \ for file in $$dist_files; do \ if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \ if test -d $$d/$$file; then \ dir=`echo "/$$file" | sed -e 's,/[^/]*$$,,'`; \ if test -d "$(distdir)/$$file"; then \ find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ fi; \ if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \ cp -fpR $(srcdir)/$$file "$(distdir)$$dir" || exit 1; \ find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ fi; \ cp -fpR $$d/$$file "$(distdir)$$dir" || exit 1; \ else \ test -f "$(distdir)/$$file" \ || cp -p $$d/$$file "$(distdir)/$$file" \ || exit 1; \ fi; \ done check-am: all-am check: $(BUILT_SOURCES) $(MAKE) $(AM_MAKEFLAGS) check-am all-am: Makefile $(LTLIBRARIES) installdirs: for dir in "$(DESTDIR)$(libdir)"; do \ test -z "$$dir" || $(MKDIR_P) "$$dir"; \ done install: $(BUILT_SOURCES) $(MAKE) $(AM_MAKEFLAGS) install-am install-exec: install-exec-am install-data: install-data-am uninstall: uninstall-am install-am: all-am @$(MAKE) $(AM_MAKEFLAGS) install-exec-am install-data-am installcheck: installcheck-am install-strip: if test -z '$(STRIP)'; then \ $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ install; \ else \ $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'" install; \ fi mostlyclean-generic: clean-generic: -test -z "$(CLEANFILES)" || rm -f $(CLEANFILES) distclean-generic: -test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES) -test . = "$(srcdir)" || test -z "$(CONFIG_CLEAN_VPATH_FILES)" || rm -f $(CONFIG_CLEAN_VPATH_FILES) maintainer-clean-generic: @echo "This command is intended for maintainers to use" @echo "it deletes files that may require special tools to rebuild." -test -z "$(BUILT_SOURCES)" || rm -f $(BUILT_SOURCES) clean: clean-am clean-am: clean-generic clean-libLTLIBRARIES clean-libtool \ mostlyclean-am distclean: distclean-am -rm -rf ./$(DEPDIR) -rm -f Makefile distclean-am: clean-am distclean-compile distclean-generic \ distclean-tags dvi: dvi-am dvi-am: html: html-am html-am: info: info-am info-am: install-data-am: install-dvi: install-dvi-am install-dvi-am: install-exec-am: install-libLTLIBRARIES install-html: install-html-am install-html-am: install-info: install-info-am install-info-am: install-man: install-pdf: install-pdf-am install-pdf-am: install-ps: install-ps-am install-ps-am: installcheck-am: maintainer-clean: maintainer-clean-am -rm -rf ./$(DEPDIR) -rm -f Makefile maintainer-clean-am: distclean-am maintainer-clean-generic mostlyclean: mostlyclean-am mostlyclean-am: mostlyclean-compile mostlyclean-generic \ mostlyclean-libtool pdf: pdf-am pdf-am: ps: ps-am ps-am: uninstall-am: uninstall-libLTLIBRARIES .MAKE: all check install install-am install-strip .PHONY: CTAGS GTAGS TAGS all all-am check check-am clean clean-generic \ clean-libLTLIBRARIES clean-libtool cscopelist-am ctags \ ctags-am distclean distclean-compile distclean-generic \ distclean-libtool distclean-tags distdir dvi dvi-am html \ html-am info info-am install install-am install-data \ install-data-am install-dvi install-dvi-am install-exec \ install-exec-am install-html install-html-am install-info \ install-info-am install-libLTLIBRARIES install-man install-pdf \ install-pdf-am install-ps install-ps-am install-strip \ installcheck installcheck-am installdirs maintainer-clean \ maintainer-clean-generic mostlyclean mostlyclean-compile \ mostlyclean-generic mostlyclean-libtool pdf pdf-am ps ps-am \ tags tags-am uninstall uninstall-am uninstall-libLTLIBRARIES .PRECIOUS: Makefile vi.h: Makefile $(srcdir)/makelist $(srcdir)/vi.c AWK=$(AWK) sh $(srcdir)/makelist -h $(srcdir)/vi.c > $@ emacs.h: Makefile $(srcdir)/makelist $(srcdir)/emacs.c AWK=$(AWK) sh $(srcdir)/makelist -h $(srcdir)/emacs.c > $@ common.h: Makefile $(srcdir)/makelist $(srcdir)/common.c AWK=$(AWK) sh $(srcdir)/makelist -h $(srcdir)/common.c > $@ fcns.h: Makefile $(srcdir)/makelist $(AHDR) AWK=$(AWK) sh $(srcdir)/makelist -fh $(AHDR) > $@ func.h: Makefile $(srcdir)/makelist $(AHDR) AWK=$(AWK) sh $(srcdir)/makelist -fc $(AHDR) > $@ help.h: Makefile $(srcdir)/makelist $(ASRC) AWK=$(AWK) sh $(srcdir)/makelist -bh $(ASRC) > $@ # Tell versions [3.59,3.63) of GNU make to not export all variables. # Otherwise a system limit (for SysV at least) may be exceeded. .NOEXPORT: heimdal-7.5.0/lib/libedit/src/map.h0000644000175000017500000000636513026237312015162 0ustar niknik/* $NetBSD: map.h,v 1.13 2016/05/09 21:46:56 christos Exp $ */ /*- * Copyright (c) 1992, 1993 * The Regents of the University of California. All rights reserved. * * This code is derived from software contributed to Berkeley by * Christos Zoulas of Cornell University. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the University nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * * @(#)map.h 8.1 (Berkeley) 6/4/93 */ /* * el.map.h: Editor maps */ #ifndef _h_el_map #define _h_el_map typedef el_action_t (*el_func_t)(EditLine *, wint_t); typedef struct el_bindings_t { /* for the "bind" shell command */ const wchar_t *name; /* function name for bind command */ int func; /* function numeric value */ const wchar_t *description; /* description of function */ } el_bindings_t; typedef struct el_map_t { el_action_t *alt; /* The current alternate key map */ el_action_t *key; /* The current normal key map */ el_action_t *current; /* The keymap we are using */ const el_action_t *emacs; /* The default emacs key map */ const el_action_t *vic; /* The vi command mode key map */ const el_action_t *vii; /* The vi insert mode key map */ int type; /* Emacs or vi */ el_bindings_t *help; /* The help for the editor functions */ el_func_t *func; /* List of available functions */ size_t nfunc; /* The number of functions/help items */ } el_map_t; #define MAP_EMACS 0 #define MAP_VI 1 #define N_KEYS 256 libedit_private int map_bind(EditLine *, int, const wchar_t **); libedit_private int map_init(EditLine *); libedit_private void map_end(EditLine *); libedit_private void map_init_vi(EditLine *); libedit_private void map_init_emacs(EditLine *); libedit_private int map_set_editor(EditLine *, wchar_t *); libedit_private int map_get_editor(EditLine *, const wchar_t **); libedit_private int map_addfunc(EditLine *, const wchar_t *, const wchar_t *, el_func_t); #endif /* _h_el_map */ heimdal-7.5.0/lib/libedit/src/histedit.h0000644000175000017500000002210313026237312016206 0ustar niknik/* $NetBSD: histedit.h,v 1.56 2016/04/19 19:50:53 christos Exp $ */ /*- * Copyright (c) 1992, 1993 * The Regents of the University of California. All rights reserved. * * This code is derived from software contributed to Berkeley by * Christos Zoulas of Cornell University. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the University nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * * @(#)histedit.h 8.2 (Berkeley) 1/3/94 */ /* * histedit.h: Line editor and history interface. */ #ifndef _HISTEDIT_H_ #define _HISTEDIT_H_ #define LIBEDIT_MAJOR 2 #define LIBEDIT_MINOR 11 #include #include #ifdef __cplusplus extern "C" { #endif /* * ==== Editing ==== */ typedef struct editline EditLine; /* * For user-defined function interface */ typedef struct lineinfo { const char *buffer; const char *cursor; const char *lastchar; } LineInfo; /* * EditLine editor function return codes. * For user-defined function interface */ #define CC_NORM 0 #define CC_NEWLINE 1 #define CC_EOF 2 #define CC_ARGHACK 3 #define CC_REFRESH 4 #define CC_CURSOR 5 #define CC_ERROR 6 #define CC_FATAL 7 #define CC_REDISPLAY 8 #define CC_REFRESH_BEEP 9 /* * Initialization, cleanup, and resetting */ EditLine *el_init(const char *, FILE *, FILE *, FILE *); EditLine *el_init_fd(const char *, FILE *, FILE *, FILE *, int, int, int); void el_end(EditLine *); void el_reset(EditLine *); /* * Get a line, a character or push a string back in the input queue */ const char *el_gets(EditLine *, int *); int el_getc(EditLine *, char *); void el_push(EditLine *, const char *); /* * Beep! */ void el_beep(EditLine *); /* * High level function internals control * Parses argc, argv array and executes builtin editline commands */ int el_parse(EditLine *, int, const char **); /* * Low level editline access functions */ int el_set(EditLine *, int, ...); int el_get(EditLine *, int, ...); unsigned char _el_fn_complete(EditLine *, int); /* * el_set/el_get parameters * * When using el_wset/el_wget (as opposed to el_set/el_get): * Char is wchar_t, otherwise it is char. * prompt_func is el_wpfunc_t, otherwise it is el_pfunc_t . * Prompt function prototypes are: * typedef char *(*el_pfunct_t) (EditLine *); * typedef wchar_t *(*el_wpfunct_t) (EditLine *); * * For operations that support set or set/get, the argument types listed are for * the "set" operation. For "get", each listed type must be a pointer. * E.g. EL_EDITMODE takes an int when set, but an int* when get. * * Operations that only support "get" have the correct argument types listed. */ #define EL_PROMPT 0 /* , prompt_func); set/get */ #define EL_TERMINAL 1 /* , const char *); set/get */ #define EL_EDITOR 2 /* , const Char *); set/get */ #define EL_SIGNAL 3 /* , int); set/get */ #define EL_BIND 4 /* , const Char *, ..., NULL); set */ #define EL_TELLTC 5 /* , const Char *, ..., NULL); set */ #define EL_SETTC 6 /* , const Char *, ..., NULL); set */ #define EL_ECHOTC 7 /* , const Char *, ..., NULL); set */ #define EL_SETTY 8 /* , const Char *, ..., NULL); set */ #define EL_ADDFN 9 /* , const Char *, const Char, set */ /* el_func_t); */ #define EL_HIST 10 /* , hist_fun_t, const void *); set */ #define EL_EDITMODE 11 /* , int); set/get */ #define EL_RPROMPT 12 /* , prompt_func); set/get */ #define EL_GETCFN 13 /* , el_rfunc_t); set/get */ #define EL_CLIENTDATA 14 /* , void *); set/get */ #define EL_UNBUFFERED 15 /* , int); set/get */ #define EL_PREP_TERM 16 /* , int); set */ #define EL_GETTC 17 /* , const Char *, ..., NULL); get */ #define EL_GETFP 18 /* , int, FILE **); get */ #define EL_SETFP 19 /* , int, FILE *); set */ #define EL_REFRESH 20 /* , void); set */ #define EL_PROMPT_ESC 21 /* , prompt_func, Char); set/get */ #define EL_RPROMPT_ESC 22 /* , prompt_func, Char); set/get */ #define EL_RESIZE 23 /* , el_zfunc_t, void *); set */ #define EL_ALIAS_TEXT 24 /* , el_afunc_t, void *); set */ #define EL_BUILTIN_GETCFN (NULL) /* * Source named file or $PWD/.editrc or $HOME/.editrc */ int el_source(EditLine *, const char *); /* * Must be called when the terminal changes size; If EL_SIGNAL * is set this is done automatically otherwise it is the responsibility * of the application */ void el_resize(EditLine *); /* * User-defined function interface. */ const LineInfo *el_line(EditLine *); int el_insertstr(EditLine *, const char *); void el_deletestr(EditLine *, int); /* * ==== History ==== */ typedef struct history History; typedef struct HistEvent { int num; const char *str; } HistEvent; /* * History access functions. */ History * history_init(void); void history_end(History *); int history(History *, HistEvent *, int, ...); #define H_FUNC 0 /* , UTSL */ #define H_SETSIZE 1 /* , const int); */ #define H_GETSIZE 2 /* , void); */ #define H_FIRST 3 /* , void); */ #define H_LAST 4 /* , void); */ #define H_PREV 5 /* , void); */ #define H_NEXT 6 /* , void); */ #define H_CURR 8 /* , const int); */ #define H_SET 7 /* , int); */ #define H_ADD 9 /* , const wchar_t *); */ #define H_ENTER 10 /* , const wchar_t *); */ #define H_APPEND 11 /* , const wchar_t *); */ #define H_END 12 /* , void); */ #define H_NEXT_STR 13 /* , const wchar_t *); */ #define H_PREV_STR 14 /* , const wchar_t *); */ #define H_NEXT_EVENT 15 /* , const int); */ #define H_PREV_EVENT 16 /* , const int); */ #define H_LOAD 17 /* , const char *); */ #define H_SAVE 18 /* , const char *); */ #define H_CLEAR 19 /* , void); */ #define H_SETUNIQUE 20 /* , int); */ #define H_GETUNIQUE 21 /* , void); */ #define H_DEL 22 /* , int); */ #define H_NEXT_EVDATA 23 /* , const int, histdata_t *); */ #define H_DELDATA 24 /* , int, histdata_t *);*/ #define H_REPLACE 25 /* , const char *, histdata_t); */ #define H_SAVE_FP 26 /* , FILE *); */ /* * ==== Tokenization ==== */ typedef struct tokenizer Tokenizer; /* * String tokenization functions, using simplified sh(1) quoting rules */ Tokenizer *tok_init(const char *); void tok_end(Tokenizer *); void tok_reset(Tokenizer *); int tok_line(Tokenizer *, const LineInfo *, int *, const char ***, int *, int *); int tok_str(Tokenizer *, const char *, int *, const char ***); /* * Begin Wide Character Support */ #include #include /* * ==== Editing ==== */ typedef struct lineinfow { const wchar_t *buffer; const wchar_t *cursor; const wchar_t *lastchar; } LineInfoW; typedef int (*el_rfunc_t)(EditLine *, wchar_t *); const wchar_t *el_wgets(EditLine *, int *); int el_wgetc(EditLine *, wchar_t *); void el_wpush(EditLine *, const wchar_t *); int el_wparse(EditLine *, int, const wchar_t **); int el_wset(EditLine *, int, ...); int el_wget(EditLine *, int, ...); int el_cursor(EditLine *, int); const LineInfoW *el_wline(EditLine *); int el_winsertstr(EditLine *, const wchar_t *); #define el_wdeletestr el_deletestr /* * ==== History ==== */ typedef struct histeventW { int num; const wchar_t *str; } HistEventW; typedef struct historyW HistoryW; HistoryW * history_winit(void); void history_wend(HistoryW *); int history_w(HistoryW *, HistEventW *, int, ...); /* * ==== Tokenization ==== */ typedef struct tokenizerW TokenizerW; /* Wide character tokenizer support */ TokenizerW *tok_winit(const wchar_t *); void tok_wend(TokenizerW *); void tok_wreset(TokenizerW *); int tok_wline(TokenizerW *, const LineInfoW *, int *, const wchar_t ***, int *, int *); int tok_wstr(TokenizerW *, const wchar_t *, int *, const wchar_t ***); #ifdef __cplusplus } #endif #endif /* _HISTEDIT_H_ */ heimdal-7.5.0/lib/libedit/src/terminal.c0000644000175000017500000012201413212137553016204 0ustar niknik/* $NetBSD: terminal.c,v 1.32 2016/05/09 21:46:56 christos Exp $ */ /*- * Copyright (c) 1992, 1993 * The Regents of the University of California. All rights reserved. * * This code is derived from software contributed to Berkeley by * Christos Zoulas of Cornell University. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the University nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "config.h" #if !defined(lint) && !defined(SCCSID) #if 0 static char sccsid[] = "@(#)term.c 8.2 (Berkeley) 4/30/95"; #else __RCSID("$NetBSD: terminal.c,v 1.32 2016/05/09 21:46:56 christos Exp $"); #endif #endif /* not lint && not SCCSID */ /* * terminal.c: Editor/termcap-curses interface * We have to declare a static variable here, since the * termcap putchar routine does not take an argument! */ #include #include #include #include #include #include #include #include #ifdef HAVE_TERMCAP_H #include #endif #ifdef HAVE_CURSES_H #include #elif HAVE_NCURSES_H #include #endif /* Solaris's term.h does horrid things. */ #if defined(HAVE_TERM_H) && !defined(__sun) && !defined(HAVE_TERMCAP_H) #include #endif #ifdef _REENTRANT #include #endif #include "el.h" #include "fcns.h" /* * IMPORTANT NOTE: these routines are allowed to look at the current screen * and the current position assuming that it is correct. If this is not * true, then the update will be WRONG! This is (should be) a valid * assumption... */ #define TC_BUFSIZE ((size_t)2048) #define GoodStr(a) (el->el_terminal.t_str[a] != NULL && \ el->el_terminal.t_str[a][0] != '\0') #define Str(a) el->el_terminal.t_str[a] #define Val(a) el->el_terminal.t_val[a] static const struct termcapstr { const char *name; const char *long_name; } tstr[] = { #define T_al 0 { "al", "add new blank line" }, #define T_bl 1 { "bl", "audible bell" }, #define T_cd 2 { "cd", "clear to bottom" }, #define T_ce 3 { "ce", "clear to end of line" }, #define T_ch 4 { "ch", "cursor to horiz pos" }, #define T_cl 5 { "cl", "clear screen" }, #define T_dc 6 { "dc", "delete a character" }, #define T_dl 7 { "dl", "delete a line" }, #define T_dm 8 { "dm", "start delete mode" }, #define T_ed 9 { "ed", "end delete mode" }, #define T_ei 10 { "ei", "end insert mode" }, #define T_fs 11 { "fs", "cursor from status line" }, #define T_ho 12 { "ho", "home cursor" }, #define T_ic 13 { "ic", "insert character" }, #define T_im 14 { "im", "start insert mode" }, #define T_ip 15 { "ip", "insert padding" }, #define T_kd 16 { "kd", "sends cursor down" }, #define T_kl 17 { "kl", "sends cursor left" }, #define T_kr 18 { "kr", "sends cursor right" }, #define T_ku 19 { "ku", "sends cursor up" }, #define T_md 20 { "md", "begin bold" }, #define T_me 21 { "me", "end attributes" }, #define T_nd 22 { "nd", "non destructive space" }, #define T_se 23 { "se", "end standout" }, #define T_so 24 { "so", "begin standout" }, #define T_ts 25 { "ts", "cursor to status line" }, #define T_up 26 { "up", "cursor up one" }, #define T_us 27 { "us", "begin underline" }, #define T_ue 28 { "ue", "end underline" }, #define T_vb 29 { "vb", "visible bell" }, #define T_DC 30 { "DC", "delete multiple chars" }, #define T_DO 31 { "DO", "cursor down multiple" }, #define T_IC 32 { "IC", "insert multiple chars" }, #define T_LE 33 { "LE", "cursor left multiple" }, #define T_RI 34 { "RI", "cursor right multiple" }, #define T_UP 35 { "UP", "cursor up multiple" }, #define T_kh 36 { "kh", "send cursor home" }, #define T_at7 37 { "@7", "send cursor end" }, #define T_kD 38 { "kD", "send cursor delete" }, #define T_str 39 { NULL, NULL } }; static const struct termcapval { const char *name; const char *long_name; } tval[] = { #define T_am 0 { "am", "has automatic margins" }, #define T_pt 1 { "pt", "has physical tabs" }, #define T_li 2 { "li", "Number of lines" }, #define T_co 3 { "co", "Number of columns" }, #define T_km 4 { "km", "Has meta key" }, #define T_xt 5 { "xt", "Tab chars destructive" }, #define T_xn 6 { "xn", "newline ignored at right margin" }, #define T_MT 7 { "MT", "Has meta key" }, /* XXX? */ #define T_val 8 { NULL, NULL, } }; /* do two or more of the attributes use me */ static void terminal_setflags(EditLine *); static int terminal_rebuffer_display(EditLine *); static void terminal_free_display(EditLine *); static int terminal_alloc_display(EditLine *); static void terminal_alloc(EditLine *, const struct termcapstr *, const char *); static void terminal_init_arrow(EditLine *); static void terminal_reset_arrow(EditLine *); static int terminal_putc(int); static void terminal_tputs(EditLine *, const char *, int); #ifdef _REENTRANT static pthread_mutex_t terminal_mutex = PTHREAD_MUTEX_INITIALIZER; #endif static FILE *terminal_outfile = NULL; /* terminal_setflags(): * Set the terminal capability flags */ static void terminal_setflags(EditLine *el) { EL_FLAGS = 0; if (el->el_tty.t_tabs) EL_FLAGS |= (Val(T_pt) && !Val(T_xt)) ? TERM_CAN_TAB : 0; EL_FLAGS |= (Val(T_km) || Val(T_MT)) ? TERM_HAS_META : 0; EL_FLAGS |= GoodStr(T_ce) ? TERM_CAN_CEOL : 0; EL_FLAGS |= (GoodStr(T_dc) || GoodStr(T_DC)) ? TERM_CAN_DELETE : 0; EL_FLAGS |= (GoodStr(T_im) || GoodStr(T_ic) || GoodStr(T_IC)) ? TERM_CAN_INSERT : 0; EL_FLAGS |= (GoodStr(T_up) || GoodStr(T_UP)) ? TERM_CAN_UP : 0; EL_FLAGS |= Val(T_am) ? TERM_HAS_AUTO_MARGINS : 0; EL_FLAGS |= Val(T_xn) ? TERM_HAS_MAGIC_MARGINS : 0; if (GoodStr(T_me) && GoodStr(T_ue)) EL_FLAGS |= (strcmp(Str(T_me), Str(T_ue)) == 0) ? TERM_CAN_ME : 0; else EL_FLAGS &= ~TERM_CAN_ME; if (GoodStr(T_me) && GoodStr(T_se)) EL_FLAGS |= (strcmp(Str(T_me), Str(T_se)) == 0) ? TERM_CAN_ME : 0; #ifdef DEBUG_SCREEN if (!EL_CAN_UP) { (void) fprintf(el->el_errfile, "WARNING: Your terminal cannot move up.\n"); (void) fprintf(el->el_errfile, "Editing may be odd for long lines.\n"); } if (!EL_CAN_CEOL) (void) fprintf(el->el_errfile, "no clear EOL capability.\n"); if (!EL_CAN_DELETE) (void) fprintf(el->el_errfile, "no delete char capability.\n"); if (!EL_CAN_INSERT) (void) fprintf(el->el_errfile, "no insert char capability.\n"); #endif /* DEBUG_SCREEN */ } /* terminal_init(): * Initialize the terminal stuff */ libedit_private int terminal_init(EditLine *el) { el->el_terminal.t_buf = el_malloc(TC_BUFSIZE * sizeof(*el->el_terminal.t_buf)); if (el->el_terminal.t_buf == NULL) goto fail1; el->el_terminal.t_cap = el_malloc(TC_BUFSIZE * sizeof(*el->el_terminal.t_cap)); if (el->el_terminal.t_cap == NULL) goto fail2; el->el_terminal.t_fkey = el_malloc(A_K_NKEYS * sizeof(*el->el_terminal.t_fkey)); if (el->el_terminal.t_fkey == NULL) goto fail3; el->el_terminal.t_loc = 0; el->el_terminal.t_str = el_malloc(T_str * sizeof(*el->el_terminal.t_str)); if (el->el_terminal.t_str == NULL) goto fail4; (void) memset(el->el_terminal.t_str, 0, T_str * sizeof(*el->el_terminal.t_str)); el->el_terminal.t_val = el_malloc(T_val * sizeof(*el->el_terminal.t_val)); if (el->el_terminal.t_val == NULL) goto fail5; (void) memset(el->el_terminal.t_val, 0, T_val * sizeof(*el->el_terminal.t_val)); (void) terminal_set(el, NULL); terminal_init_arrow(el); return 0; fail5: free(el->el_terminal.t_str); el->el_terminal.t_str = NULL; fail4: free(el->el_terminal.t_fkey); el->el_terminal.t_fkey = NULL; fail3: free(el->el_terminal.t_cap); el->el_terminal.t_cap = NULL; fail2: free(el->el_terminal.t_buf); el->el_terminal.t_buf = NULL; fail1: return -1; } /* terminal_end(): * Clean up the terminal stuff */ libedit_private void terminal_end(EditLine *el) { el_free(el->el_terminal.t_buf); el->el_terminal.t_buf = NULL; el_free(el->el_terminal.t_cap); el->el_terminal.t_cap = NULL; el->el_terminal.t_loc = 0; el_free(el->el_terminal.t_str); el->el_terminal.t_str = NULL; el_free(el->el_terminal.t_val); el->el_terminal.t_val = NULL; el_free(el->el_terminal.t_fkey); el->el_terminal.t_fkey = NULL; terminal_free_display(el); } /* terminal_alloc(): * Maintain a string pool for termcap strings */ static void terminal_alloc(EditLine *el, const struct termcapstr *t, const char *cap) { char termbuf[TC_BUFSIZE]; size_t tlen, clen; char **tlist = el->el_terminal.t_str; char **tmp, **str = &tlist[t - tstr]; (void) memset(termbuf, 0, sizeof(termbuf)); if (cap == NULL || *cap == '\0') { *str = NULL; return; } else clen = strlen(cap); tlen = *str == NULL ? 0 : strlen(*str); /* * New string is shorter; no need to allocate space */ if (clen <= tlen) { if (*str) (void) strcpy(*str, cap); /* XXX strcpy is safe */ return; } /* * New string is longer; see if we have enough space to append */ if (el->el_terminal.t_loc + 3 < TC_BUFSIZE) { /* XXX strcpy is safe */ (void) strcpy(*str = &el->el_terminal.t_buf[ el->el_terminal.t_loc], cap); el->el_terminal.t_loc += clen + 1; /* one for \0 */ return; } /* * Compact our buffer; no need to check compaction, cause we know it * fits... */ tlen = 0; for (tmp = tlist; tmp < &tlist[T_str]; tmp++) if (*tmp != NULL && **tmp != '\0' && *tmp != *str) { char *ptr; for (ptr = *tmp; *ptr != '\0'; termbuf[tlen++] = *ptr++) continue; termbuf[tlen++] = '\0'; } memcpy(el->el_terminal.t_buf, termbuf, TC_BUFSIZE); el->el_terminal.t_loc = tlen; if (el->el_terminal.t_loc + 3 >= TC_BUFSIZE) { (void) fprintf(el->el_errfile, "Out of termcap string space.\n"); return; } /* XXX strcpy is safe */ (void) strcpy(*str = &el->el_terminal.t_buf[el->el_terminal.t_loc], cap); el->el_terminal.t_loc += (size_t)clen + 1; /* one for \0 */ return; } /* terminal_rebuffer_display(): * Rebuffer the display after the screen changed size */ static int terminal_rebuffer_display(EditLine *el) { coord_t *c = &el->el_terminal.t_size; terminal_free_display(el); c->h = Val(T_co); c->v = Val(T_li); if (terminal_alloc_display(el) == -1) return -1; return 0; } /* terminal_alloc_display(): * Allocate a new display. */ static int terminal_alloc_display(EditLine *el) { int i; wchar_t **b; coord_t *c = &el->el_terminal.t_size; b = el_malloc(sizeof(*b) * (size_t)(c->v + 1)); if (b == NULL) goto done; for (i = 0; i < c->v; i++) { b[i] = el_malloc(sizeof(**b) * (size_t)(c->h + 1)); if (b[i] == NULL) { while (--i >= 0) el_free(b[i]); el_free(b); goto done; } } b[c->v] = NULL; el->el_display = b; b = el_malloc(sizeof(*b) * (size_t)(c->v + 1)); if (b == NULL) goto done; for (i = 0; i < c->v; i++) { b[i] = el_malloc(sizeof(**b) * (size_t)(c->h + 1)); if (b[i] == NULL) { while (--i >= 0) el_free(b[i]); el_free(b); goto done; } } b[c->v] = NULL; el->el_vdisplay = b; return 0; done: terminal_free_display(el); return -1; } /* terminal_free_display(): * Free the display buffers */ static void terminal_free_display(EditLine *el) { wchar_t **b; wchar_t **bufp; b = el->el_display; el->el_display = NULL; if (b != NULL) { for (bufp = b; *bufp != NULL; bufp++) el_free(*bufp); el_free(b); } b = el->el_vdisplay; el->el_vdisplay = NULL; if (b != NULL) { for (bufp = b; *bufp != NULL; bufp++) el_free(*bufp); el_free(b); } } /* terminal_move_to_line(): * move to line (first line == 0) * as efficiently as possible */ libedit_private void terminal_move_to_line(EditLine *el, int where) { int del; if (where == el->el_cursor.v) return; if (where > el->el_terminal.t_size.v) { #ifdef DEBUG_SCREEN (void) fprintf(el->el_errfile, "%s: where is ridiculous: %d\r\n", __func__, where); #endif /* DEBUG_SCREEN */ return; } if ((del = where - el->el_cursor.v) > 0) { while (del > 0) { if (EL_HAS_AUTO_MARGINS && el->el_display[el->el_cursor.v][0] != '\0') { size_t h = (size_t) (el->el_terminal.t_size.h - 1); for (; h > 0 && el->el_display[el->el_cursor.v][h] == MB_FILL_CHAR; h--) continue; /* move without newline */ terminal_move_to_char(el, (int)h); terminal_overwrite(el, &el->el_display [el->el_cursor.v][el->el_cursor.h], (size_t)(el->el_terminal.t_size.h - el->el_cursor.h)); /* updates Cursor */ del--; } else { if ((del > 1) && GoodStr(T_DO)) { terminal_tputs(el, tgoto(Str(T_DO), del, del), del); del = 0; } else { for (; del > 0; del--) terminal__putc(el, '\n'); /* because the \n will become \r\n */ el->el_cursor.h = 0; } } } } else { /* del < 0 */ if (GoodStr(T_UP) && (-del > 1 || !GoodStr(T_up))) terminal_tputs(el, tgoto(Str(T_UP), -del, -del), -del); else { if (GoodStr(T_up)) for (; del < 0; del++) terminal_tputs(el, Str(T_up), 1); } } el->el_cursor.v = where;/* now where is here */ } /* terminal_move_to_char(): * Move to the character position specified */ libedit_private void terminal_move_to_char(EditLine *el, int where) { int del, i; mc_again: if (where == el->el_cursor.h) return; if (where > el->el_terminal.t_size.h) { #ifdef DEBUG_SCREEN (void) fprintf(el->el_errfile, "%s: where is ridiculous: %d\r\n", __func__, where); #endif /* DEBUG_SCREEN */ return; } if (!where) { /* if where is first column */ terminal__putc(el, '\r'); /* do a CR */ el->el_cursor.h = 0; return; } del = where - el->el_cursor.h; if ((del < -4 || del > 4) && GoodStr(T_ch)) /* go there directly */ terminal_tputs(el, tgoto(Str(T_ch), where, where), where); else { if (del > 0) { /* moving forward */ if ((del > 4) && GoodStr(T_RI)) terminal_tputs(el, tgoto(Str(T_RI), del, del), del); else { /* if I can do tabs, use them */ if (EL_CAN_TAB) { if ((el->el_cursor.h & 0370) != (where & ~0x7) && (el->el_display[ el->el_cursor.v][where & 0370] != MB_FILL_CHAR) ) { /* if not within tab stop */ for (i = (el->el_cursor.h & 0370); i < (where & ~0x7); i += 8) terminal__putc(el, '\t'); /* then tab over */ el->el_cursor.h = where & ~0x7; } } /* * it's usually cheaper to just write the * chars, so we do. */ /* * NOTE THAT terminal_overwrite() WILL CHANGE * el->el_cursor.h!!! */ terminal_overwrite(el, &el->el_display[ el->el_cursor.v][el->el_cursor.h], (size_t)(where - el->el_cursor.h)); } } else { /* del < 0 := moving backward */ if ((-del > 4) && GoodStr(T_LE)) terminal_tputs(el, tgoto(Str(T_LE), -del, -del), -del); else { /* can't go directly there */ /* * if the "cost" is greater than the "cost" * from col 0 */ if (EL_CAN_TAB ? ((unsigned int)-del > (((unsigned int) where >> 3) + (where & 07))) : (-del > where)) { terminal__putc(el, '\r');/* do a CR */ el->el_cursor.h = 0; goto mc_again; /* and try again */ } for (i = 0; i < -del; i++) terminal__putc(el, '\b'); } } } el->el_cursor.h = where; /* now where is here */ } /* terminal_overwrite(): * Overstrike num characters * Assumes MB_FILL_CHARs are present to keep the column count correct */ libedit_private void terminal_overwrite(EditLine *el, const wchar_t *cp, size_t n) { if (n == 0) return; if (n > (size_t)el->el_terminal.t_size.h) { #ifdef DEBUG_SCREEN (void) fprintf(el->el_errfile, "%s: n is ridiculous: %zu\r\n", __func__, n); #endif /* DEBUG_SCREEN */ return; } do { /* terminal__putc() ignores any MB_FILL_CHARs */ terminal__putc(el, *cp++); el->el_cursor.h++; } while (--n); if (el->el_cursor.h >= el->el_terminal.t_size.h) { /* wrap? */ if (EL_HAS_AUTO_MARGINS) { /* yes */ el->el_cursor.h = 0; el->el_cursor.v++; if (EL_HAS_MAGIC_MARGINS) { /* force the wrap to avoid the "magic" * situation */ wchar_t c; if ((c = el->el_display[el->el_cursor.v] [el->el_cursor.h]) != '\0') { terminal_overwrite(el, &c, (size_t)1); while (el->el_display[el->el_cursor.v] [el->el_cursor.h] == MB_FILL_CHAR) el->el_cursor.h++; } else { terminal__putc(el, ' '); el->el_cursor.h = 1; } } } else /* no wrap, but cursor stays on screen */ el->el_cursor.h = el->el_terminal.t_size.h - 1; } } /* terminal_deletechars(): * Delete num characters */ libedit_private void terminal_deletechars(EditLine *el, int num) { if (num <= 0) return; if (!EL_CAN_DELETE) { #ifdef DEBUG_EDIT (void) fprintf(el->el_errfile, " ERROR: cannot delete \n"); #endif /* DEBUG_EDIT */ return; } if (num > el->el_terminal.t_size.h) { #ifdef DEBUG_SCREEN (void) fprintf(el->el_errfile, "%s: num is ridiculous: %d\r\n", __func__, num); #endif /* DEBUG_SCREEN */ return; } if (GoodStr(T_DC)) /* if I have multiple delete */ if ((num > 1) || !GoodStr(T_dc)) { /* if dc would be more * expen. */ terminal_tputs(el, tgoto(Str(T_DC), num, num), num); return; } if (GoodStr(T_dm)) /* if I have delete mode */ terminal_tputs(el, Str(T_dm), 1); if (GoodStr(T_dc)) /* else do one at a time */ while (num--) terminal_tputs(el, Str(T_dc), 1); if (GoodStr(T_ed)) /* if I have delete mode */ terminal_tputs(el, Str(T_ed), 1); } /* terminal_insertwrite(): * Puts terminal in insert character mode or inserts num * characters in the line * Assumes MB_FILL_CHARs are present to keep column count correct */ libedit_private void terminal_insertwrite(EditLine *el, wchar_t *cp, int num) { if (num <= 0) return; if (!EL_CAN_INSERT) { #ifdef DEBUG_EDIT (void) fprintf(el->el_errfile, " ERROR: cannot insert \n"); #endif /* DEBUG_EDIT */ return; } if (num > el->el_terminal.t_size.h) { #ifdef DEBUG_SCREEN (void) fprintf(el->el_errfile, "%s: num is ridiculous: %d\r\n", __func__, num); #endif /* DEBUG_SCREEN */ return; } if (GoodStr(T_IC)) /* if I have multiple insert */ if ((num > 1) || !GoodStr(T_ic)) { /* if ic would be more expensive */ terminal_tputs(el, tgoto(Str(T_IC), num, num), num); terminal_overwrite(el, cp, (size_t)num); /* this updates el_cursor.h */ return; } if (GoodStr(T_im) && GoodStr(T_ei)) { /* if I have insert mode */ terminal_tputs(el, Str(T_im), 1); el->el_cursor.h += num; do terminal__putc(el, *cp++); while (--num); if (GoodStr(T_ip)) /* have to make num chars insert */ terminal_tputs(el, Str(T_ip), 1); terminal_tputs(el, Str(T_ei), 1); return; } do { if (GoodStr(T_ic)) /* have to make num chars insert */ terminal_tputs(el, Str(T_ic), 1); terminal__putc(el, *cp++); el->el_cursor.h++; if (GoodStr(T_ip)) /* have to make num chars insert */ terminal_tputs(el, Str(T_ip), 1); /* pad the inserted char */ } while (--num); } /* terminal_clear_EOL(): * clear to end of line. There are num characters to clear */ libedit_private void terminal_clear_EOL(EditLine *el, int num) { int i; if (EL_CAN_CEOL && GoodStr(T_ce)) terminal_tputs(el, Str(T_ce), 1); else { for (i = 0; i < num; i++) terminal__putc(el, ' '); el->el_cursor.h += num; /* have written num spaces */ } } /* terminal_clear_screen(): * Clear the screen */ libedit_private void terminal_clear_screen(EditLine *el) { /* clear the whole screen and home */ if (GoodStr(T_cl)) /* send the clear screen code */ terminal_tputs(el, Str(T_cl), Val(T_li)); else if (GoodStr(T_ho) && GoodStr(T_cd)) { terminal_tputs(el, Str(T_ho), Val(T_li)); /* home */ /* clear to bottom of screen */ terminal_tputs(el, Str(T_cd), Val(T_li)); } else { terminal__putc(el, '\r'); terminal__putc(el, '\n'); } } /* terminal_beep(): * Beep the way the terminal wants us */ libedit_private void terminal_beep(EditLine *el) { if (GoodStr(T_bl)) /* what termcap says we should use */ terminal_tputs(el, Str(T_bl), 1); else terminal__putc(el, '\007'); /* an ASCII bell; ^G */ } libedit_private void terminal_get(EditLine *el, const char **term) { *term = el->el_terminal.t_name; } /* terminal_set(): * Read in the terminal capabilities from the requested terminal */ libedit_private int terminal_set(EditLine *el, const char *term) { int i; char buf[TC_BUFSIZE]; char *area; const struct termcapstr *t; sigset_t oset, nset; int lins, cols; (void) sigemptyset(&nset); (void) sigaddset(&nset, SIGWINCH); (void) sigprocmask(SIG_BLOCK, &nset, &oset); area = buf; if (term == NULL) term = getenv("TERM"); if (!term || !term[0]) term = "dumb"; if (strcmp(term, "emacs") == 0) el->el_flags |= EDIT_DISABLED; (void) memset(el->el_terminal.t_cap, 0, TC_BUFSIZE); i = tgetent(el->el_terminal.t_cap, term); if (i <= 0) { if (i == -1) (void) fprintf(el->el_errfile, "Cannot read termcap database;\n"); else if (i == 0) (void) fprintf(el->el_errfile, "No entry for terminal type \"%s\";\n", term); (void) fprintf(el->el_errfile, "using dumb terminal settings.\n"); Val(T_co) = 80; /* do a dumb terminal */ Val(T_pt) = Val(T_km) = Val(T_li) = 0; Val(T_xt) = Val(T_MT); for (t = tstr; t->name != NULL; t++) terminal_alloc(el, t, NULL); } else { /* auto/magic margins */ Val(T_am) = tgetflag("am"); Val(T_xn) = tgetflag("xn"); /* Can we tab */ Val(T_pt) = tgetflag("pt"); Val(T_xt) = tgetflag("xt"); /* do we have a meta? */ Val(T_km) = tgetflag("km"); Val(T_MT) = tgetflag("MT"); /* Get the size */ Val(T_co) = tgetnum("co"); Val(T_li) = tgetnum("li"); for (t = tstr; t->name != NULL; t++) { /* XXX: some systems' tgetstr needs non const */ terminal_alloc(el, t, tgetstr(strchr(t->name, *t->name), &area)); } } if (Val(T_co) < 2) Val(T_co) = 80; /* just in case */ if (Val(T_li) < 1) Val(T_li) = 24; el->el_terminal.t_size.v = Val(T_co); el->el_terminal.t_size.h = Val(T_li); terminal_setflags(el); /* get the correct window size */ (void) terminal_get_size(el, &lins, &cols); if (terminal_change_size(el, lins, cols) == -1) return -1; (void) sigprocmask(SIG_SETMASK, &oset, NULL); terminal_bind_arrow(el); el->el_terminal.t_name = term; return i <= 0 ? -1 : 0; } /* terminal_get_size(): * Return the new window size in lines and cols, and * true if the size was changed. */ libedit_private int terminal_get_size(EditLine *el, int *lins, int *cols) { *cols = Val(T_co); *lins = Val(T_li); #ifdef TIOCGWINSZ { struct winsize ws; if (ioctl(el->el_infd, TIOCGWINSZ, &ws) != -1) { if (ws.ws_col) *cols = ws.ws_col; if (ws.ws_row) *lins = ws.ws_row; } } #endif #ifdef TIOCGSIZE { struct ttysize ts; if (ioctl(el->el_infd, TIOCGSIZE, &ts) != -1) { if (ts.ts_cols) *cols = ts.ts_cols; if (ts.ts_lines) *lins = ts.ts_lines; } } #endif return Val(T_co) != *cols || Val(T_li) != *lins; } /* terminal_change_size(): * Change the size of the terminal */ libedit_private int terminal_change_size(EditLine *el, int lins, int cols) { /* * Just in case */ Val(T_co) = (cols < 2) ? 80 : cols; Val(T_li) = (lins < 1) ? 24 : lins; /* re-make display buffers */ if (terminal_rebuffer_display(el) == -1) return -1; re_clear_display(el); return 0; } /* terminal_init_arrow(): * Initialize the arrow key bindings from termcap */ static void terminal_init_arrow(EditLine *el) { funckey_t *arrow = el->el_terminal.t_fkey; arrow[A_K_DN].name = L"down"; arrow[A_K_DN].key = T_kd; arrow[A_K_DN].fun.cmd = ED_NEXT_HISTORY; arrow[A_K_DN].type = XK_CMD; arrow[A_K_UP].name = L"up"; arrow[A_K_UP].key = T_ku; arrow[A_K_UP].fun.cmd = ED_PREV_HISTORY; arrow[A_K_UP].type = XK_CMD; arrow[A_K_LT].name = L"left"; arrow[A_K_LT].key = T_kl; arrow[A_K_LT].fun.cmd = ED_PREV_CHAR; arrow[A_K_LT].type = XK_CMD; arrow[A_K_RT].name = L"right"; arrow[A_K_RT].key = T_kr; arrow[A_K_RT].fun.cmd = ED_NEXT_CHAR; arrow[A_K_RT].type = XK_CMD; arrow[A_K_HO].name = L"home"; arrow[A_K_HO].key = T_kh; arrow[A_K_HO].fun.cmd = ED_MOVE_TO_BEG; arrow[A_K_HO].type = XK_CMD; arrow[A_K_EN].name = L"end"; arrow[A_K_EN].key = T_at7; arrow[A_K_EN].fun.cmd = ED_MOVE_TO_END; arrow[A_K_EN].type = XK_CMD; arrow[A_K_DE].name = L"delete"; arrow[A_K_DE].key = T_kD; arrow[A_K_DE].fun.cmd = ED_DELETE_NEXT_CHAR; arrow[A_K_DE].type = XK_CMD; } /* terminal_reset_arrow(): * Reset arrow key bindings */ static void terminal_reset_arrow(EditLine *el) { funckey_t *arrow = el->el_terminal.t_fkey; static const wchar_t strA[] = L"\033[A"; static const wchar_t strB[] = L"\033[B"; static const wchar_t strC[] = L"\033[C"; static const wchar_t strD[] = L"\033[D"; static const wchar_t strH[] = L"\033[H"; static const wchar_t strF[] = L"\033[F"; static const wchar_t stOA[] = L"\033OA"; static const wchar_t stOB[] = L"\033OB"; static const wchar_t stOC[] = L"\033OC"; static const wchar_t stOD[] = L"\033OD"; static const wchar_t stOH[] = L"\033OH"; static const wchar_t stOF[] = L"\033OF"; keymacro_add(el, strA, &arrow[A_K_UP].fun, arrow[A_K_UP].type); keymacro_add(el, strB, &arrow[A_K_DN].fun, arrow[A_K_DN].type); keymacro_add(el, strC, &arrow[A_K_RT].fun, arrow[A_K_RT].type); keymacro_add(el, strD, &arrow[A_K_LT].fun, arrow[A_K_LT].type); keymacro_add(el, strH, &arrow[A_K_HO].fun, arrow[A_K_HO].type); keymacro_add(el, strF, &arrow[A_K_EN].fun, arrow[A_K_EN].type); keymacro_add(el, stOA, &arrow[A_K_UP].fun, arrow[A_K_UP].type); keymacro_add(el, stOB, &arrow[A_K_DN].fun, arrow[A_K_DN].type); keymacro_add(el, stOC, &arrow[A_K_RT].fun, arrow[A_K_RT].type); keymacro_add(el, stOD, &arrow[A_K_LT].fun, arrow[A_K_LT].type); keymacro_add(el, stOH, &arrow[A_K_HO].fun, arrow[A_K_HO].type); keymacro_add(el, stOF, &arrow[A_K_EN].fun, arrow[A_K_EN].type); if (el->el_map.type != MAP_VI) return; keymacro_add(el, &strA[1], &arrow[A_K_UP].fun, arrow[A_K_UP].type); keymacro_add(el, &strB[1], &arrow[A_K_DN].fun, arrow[A_K_DN].type); keymacro_add(el, &strC[1], &arrow[A_K_RT].fun, arrow[A_K_RT].type); keymacro_add(el, &strD[1], &arrow[A_K_LT].fun, arrow[A_K_LT].type); keymacro_add(el, &strH[1], &arrow[A_K_HO].fun, arrow[A_K_HO].type); keymacro_add(el, &strF[1], &arrow[A_K_EN].fun, arrow[A_K_EN].type); keymacro_add(el, &stOA[1], &arrow[A_K_UP].fun, arrow[A_K_UP].type); keymacro_add(el, &stOB[1], &arrow[A_K_DN].fun, arrow[A_K_DN].type); keymacro_add(el, &stOC[1], &arrow[A_K_RT].fun, arrow[A_K_RT].type); keymacro_add(el, &stOD[1], &arrow[A_K_LT].fun, arrow[A_K_LT].type); keymacro_add(el, &stOH[1], &arrow[A_K_HO].fun, arrow[A_K_HO].type); keymacro_add(el, &stOF[1], &arrow[A_K_EN].fun, arrow[A_K_EN].type); } /* terminal_set_arrow(): * Set an arrow key binding */ libedit_private int terminal_set_arrow(EditLine *el, const wchar_t *name, keymacro_value_t *fun, int type) { funckey_t *arrow = el->el_terminal.t_fkey; int i; for (i = 0; i < A_K_NKEYS; i++) if (wcscmp(name, arrow[i].name) == 0) { arrow[i].fun = *fun; arrow[i].type = type; return 0; } return -1; } /* terminal_clear_arrow(): * Clear an arrow key binding */ libedit_private int terminal_clear_arrow(EditLine *el, const wchar_t *name) { funckey_t *arrow = el->el_terminal.t_fkey; int i; for (i = 0; i < A_K_NKEYS; i++) if (wcscmp(name, arrow[i].name) == 0) { arrow[i].type = XK_NOD; return 0; } return -1; } /* terminal_print_arrow(): * Print the arrow key bindings */ libedit_private void terminal_print_arrow(EditLine *el, const wchar_t *name) { int i; funckey_t *arrow = el->el_terminal.t_fkey; for (i = 0; i < A_K_NKEYS; i++) if (*name == '\0' || wcscmp(name, arrow[i].name) == 0) if (arrow[i].type != XK_NOD) keymacro_kprint(el, arrow[i].name, &arrow[i].fun, arrow[i].type); } /* terminal_bind_arrow(): * Bind the arrow keys */ libedit_private void terminal_bind_arrow(EditLine *el) { el_action_t *map; const el_action_t *dmap; int i, j; char *p; funckey_t *arrow = el->el_terminal.t_fkey; /* Check if the components needed are initialized */ if (el->el_terminal.t_buf == NULL || el->el_map.key == NULL) return; map = el->el_map.type == MAP_VI ? el->el_map.alt : el->el_map.key; dmap = el->el_map.type == MAP_VI ? el->el_map.vic : el->el_map.emacs; terminal_reset_arrow(el); for (i = 0; i < A_K_NKEYS; i++) { wchar_t wt_str[VISUAL_WIDTH_MAX]; wchar_t *px; size_t n; p = el->el_terminal.t_str[arrow[i].key]; if (!p || !*p) continue; for (n = 0; n < VISUAL_WIDTH_MAX && p[n]; ++n) wt_str[n] = p[n]; while (n < VISUAL_WIDTH_MAX) wt_str[n++] = '\0'; px = wt_str; j = (unsigned char) *p; /* * Assign the arrow keys only if: * * 1. They are multi-character arrow keys and the user * has not re-assigned the leading character, or * has re-assigned the leading character to be * ED_SEQUENCE_LEAD_IN * 2. They are single arrow keys pointing to an * unassigned key. */ if (arrow[i].type == XK_NOD) keymacro_clear(el, map, px); else { if (p[1] && (dmap[j] == map[j] || map[j] == ED_SEQUENCE_LEAD_IN)) { keymacro_add(el, px, &arrow[i].fun, arrow[i].type); map[j] = ED_SEQUENCE_LEAD_IN; } else if (map[j] == ED_UNASSIGNED) { keymacro_clear(el, map, px); if (arrow[i].type == XK_CMD) map[j] = arrow[i].fun.cmd; else keymacro_add(el, px, &arrow[i].fun, arrow[i].type); } } } } /* terminal_putc(): * Add a character */ static int terminal_putc(int c) { if (terminal_outfile == NULL) return -1; return fputc(c, terminal_outfile); } static void terminal_tputs(EditLine *el, const char *cap, int affcnt) { #ifdef _REENTRANT pthread_mutex_lock(&terminal_mutex); #endif terminal_outfile = el->el_outfile; (void)tputs(cap, affcnt, terminal_putc); #ifdef _REENTRANT pthread_mutex_unlock(&terminal_mutex); #endif } /* terminal__putc(): * Add a character */ libedit_private int terminal__putc(EditLine *el, wint_t c) { char buf[MB_LEN_MAX +1]; ssize_t i; if (c == (wint_t)MB_FILL_CHAR) return 0; i = ct_encode_char(buf, (size_t)MB_LEN_MAX, c); if (i <= 0) return (int)i; buf[i] = '\0'; return fputs(buf, el->el_outfile); } /* terminal__flush(): * Flush output */ libedit_private void terminal__flush(EditLine *el) { (void) fflush(el->el_outfile); } /* terminal_writec(): * Write the given character out, in a human readable form */ libedit_private void terminal_writec(EditLine *el, wint_t c) { wchar_t visbuf[VISUAL_WIDTH_MAX +1]; ssize_t vcnt = ct_visual_char(visbuf, VISUAL_WIDTH_MAX, c); if (vcnt < 0) vcnt = 0; visbuf[vcnt] = '\0'; terminal_overwrite(el, visbuf, (size_t)vcnt); terminal__flush(el); } /* terminal_telltc(): * Print the current termcap characteristics */ libedit_private int /*ARGSUSED*/ terminal_telltc(EditLine *el, int argc __attribute__((__unused__)), const wchar_t **argv __attribute__((__unused__))) { const struct termcapstr *t; char **ts; (void) fprintf(el->el_outfile, "\n\tYour terminal has the\n"); (void) fprintf(el->el_outfile, "\tfollowing characteristics:\n\n"); (void) fprintf(el->el_outfile, "\tIt has %d columns and %d lines\n", Val(T_co), Val(T_li)); (void) fprintf(el->el_outfile, "\tIt has %s meta key\n", EL_HAS_META ? "a" : "no"); (void) fprintf(el->el_outfile, "\tIt can%suse tabs\n", EL_CAN_TAB ? " " : "not "); (void) fprintf(el->el_outfile, "\tIt %s automatic margins\n", EL_HAS_AUTO_MARGINS ? "has" : "does not have"); if (EL_HAS_AUTO_MARGINS) (void) fprintf(el->el_outfile, "\tIt %s magic margins\n", EL_HAS_MAGIC_MARGINS ? "has" : "does not have"); for (t = tstr, ts = el->el_terminal.t_str; t->name != NULL; t++, ts++) { const char *ub; if (*ts && **ts) { ub = ct_encode_string(ct_visual_string( ct_decode_string(*ts, &el->el_scratch), &el->el_visual), &el->el_scratch); } else { ub = "(empty)"; } (void) fprintf(el->el_outfile, "\t%25s (%s) == %s\n", t->long_name, t->name, ub); } (void) fputc('\n', el->el_outfile); return 0; } /* terminal_settc(): * Change the current terminal characteristics */ libedit_private int /*ARGSUSED*/ terminal_settc(EditLine *el, int argc __attribute__((__unused__)), const wchar_t **argv) { const struct termcapstr *ts; const struct termcapval *tv; char what[8], how[8]; if (argv == NULL || argv[1] == NULL || argv[2] == NULL) return -1; strncpy(what, ct_encode_string(argv[1], &el->el_scratch), sizeof(what)); what[sizeof(what) - 1] = '\0'; strncpy(how, ct_encode_string(argv[2], &el->el_scratch), sizeof(how)); how[sizeof(how) - 1] = '\0'; /* * Do the strings first */ for (ts = tstr; ts->name != NULL; ts++) if (strcmp(ts->name, what) == 0) break; if (ts->name != NULL) { terminal_alloc(el, ts, how); terminal_setflags(el); return 0; } /* * Do the numeric ones second */ for (tv = tval; tv->name != NULL; tv++) if (strcmp(tv->name, what) == 0) break; if (tv->name != NULL) return -1; if (tv == &tval[T_pt] || tv == &tval[T_km] || tv == &tval[T_am] || tv == &tval[T_xn]) { if (strcmp(how, "yes") == 0) el->el_terminal.t_val[tv - tval] = 1; else if (strcmp(how, "no") == 0) el->el_terminal.t_val[tv - tval] = 0; else { (void) fprintf(el->el_errfile, "%ls: Bad value `%s'.\n", argv[0], how); return -1; } terminal_setflags(el); if (terminal_change_size(el, Val(T_li), Val(T_co)) == -1) return -1; return 0; } else { long i; char *ep; i = strtol(how, &ep, 10); if (*ep != '\0') { (void) fprintf(el->el_errfile, "%ls: Bad value `%s'.\n", argv[0], how); return -1; } el->el_terminal.t_val[tv - tval] = (int) i; el->el_terminal.t_size.v = Val(T_co); el->el_terminal.t_size.h = Val(T_li); if (tv == &tval[T_co] || tv == &tval[T_li]) if (terminal_change_size(el, Val(T_li), Val(T_co)) == -1) return -1; return 0; } } /* terminal_gettc(): * Get the current terminal characteristics */ libedit_private int /*ARGSUSED*/ terminal_gettc(EditLine *el, int argc __attribute__((__unused__)), char **argv) { const struct termcapstr *ts; const struct termcapval *tv; char *what; void *how; if (argv == NULL || argv[1] == NULL || argv[2] == NULL) return -1; what = argv[1]; how = argv[2]; /* * Do the strings first */ for (ts = tstr; ts->name != NULL; ts++) if (strcmp(ts->name, what) == 0) break; if (ts->name != NULL) { *(char **)how = el->el_terminal.t_str[ts - tstr]; return 0; } /* * Do the numeric ones second */ for (tv = tval; tv->name != NULL; tv++) if (strcmp(tv->name, what) == 0) break; if (tv->name == NULL) return -1; if (tv == &tval[T_pt] || tv == &tval[T_km] || tv == &tval[T_am] || tv == &tval[T_xn]) { static char yes[] = "yes"; static char no[] = "no"; if (el->el_terminal.t_val[tv - tval]) *(char **)how = yes; else *(char **)how = no; return 0; } else { *(int *)how = el->el_terminal.t_val[tv - tval]; return 0; } } /* terminal_echotc(): * Print the termcap string out with variable substitution */ libedit_private int /*ARGSUSED*/ terminal_echotc(EditLine *el, int argc __attribute__((__unused__)), const wchar_t **argv) { char *cap, *scap; wchar_t *ep; int arg_need, arg_cols, arg_rows; int verbose = 0, silent = 0; char *area; static const char fmts[] = "%s\n", fmtd[] = "%d\n"; const struct termcapstr *t; char buf[TC_BUFSIZE]; long i; area = buf; if (argv == NULL || argv[1] == NULL) return -1; argv++; if (argv[0][0] == '-') { switch (argv[0][1]) { case 'v': verbose = 1; break; case 's': silent = 1; break; default: /* stderror(ERR_NAME | ERR_TCUSAGE); */ break; } argv++; } if (!*argv || *argv[0] == '\0') return 0; if (wcscmp(*argv, L"tabs") == 0) { (void) fprintf(el->el_outfile, fmts, EL_CAN_TAB ? "yes" : "no"); return 0; } else if (wcscmp(*argv, L"meta") == 0) { (void) fprintf(el->el_outfile, fmts, Val(T_km) ? "yes" : "no"); return 0; } else if (wcscmp(*argv, L"xn") == 0) { (void) fprintf(el->el_outfile, fmts, EL_HAS_MAGIC_MARGINS ? "yes" : "no"); return 0; } else if (wcscmp(*argv, L"am") == 0) { (void) fprintf(el->el_outfile, fmts, EL_HAS_AUTO_MARGINS ? "yes" : "no"); return 0; } else if (wcscmp(*argv, L"baud") == 0) { (void) fprintf(el->el_outfile, fmtd, (int)el->el_tty.t_speed); return 0; } else if (wcscmp(*argv, L"rows") == 0 || wcscmp(*argv, L"lines") == 0) { (void) fprintf(el->el_outfile, fmtd, Val(T_li)); return 0; } else if (wcscmp(*argv, L"cols") == 0) { (void) fprintf(el->el_outfile, fmtd, Val(T_co)); return 0; } /* * Try to use our local definition first */ scap = NULL; for (t = tstr; t->name != NULL; t++) if (strcmp(t->name, ct_encode_string(*argv, &el->el_scratch)) == 0) { scap = el->el_terminal.t_str[t - tstr]; break; } if (t->name == NULL) { /* XXX: some systems' tgetstr needs non const */ scap = tgetstr(ct_encode_string(*argv, &el->el_scratch), &area); } if (!scap || scap[0] == '\0') { if (!silent) (void) fprintf(el->el_errfile, "echotc: Termcap parameter `%ls' not found.\n", *argv); return -1; } /* * Count home many values we need for this capability. */ for (cap = scap, arg_need = 0; *cap; cap++) if (*cap == '%') switch (*++cap) { case 'd': case '2': case '3': case '.': case '+': arg_need++; break; case '%': case '>': case 'i': case 'r': case 'n': case 'B': case 'D': break; default: /* * hpux has lot's of them... */ if (verbose) (void) fprintf(el->el_errfile, "echotc: Warning: unknown termcap %% `%c'.\n", *cap); /* This is bad, but I won't complain */ break; } switch (arg_need) { case 0: argv++; if (*argv && *argv[0]) { if (!silent) (void) fprintf(el->el_errfile, "echotc: Warning: Extra argument `%ls'.\n", *argv); return -1; } terminal_tputs(el, scap, 1); break; case 1: argv++; if (!*argv || *argv[0] == '\0') { if (!silent) (void) fprintf(el->el_errfile, "echotc: Warning: Missing argument.\n"); return -1; } arg_cols = 0; i = wcstol(*argv, &ep, 10); if (*ep != '\0' || i < 0) { if (!silent) (void) fprintf(el->el_errfile, "echotc: Bad value `%ls' for rows.\n", *argv); return -1; } arg_rows = (int) i; argv++; if (*argv && *argv[0]) { if (!silent) (void) fprintf(el->el_errfile, "echotc: Warning: Extra argument `%ls" "'.\n", *argv); return -1; } terminal_tputs(el, tgoto(scap, arg_cols, arg_rows), 1); break; default: /* This is wrong, but I will ignore it... */ if (verbose) (void) fprintf(el->el_errfile, "echotc: Warning: Too many required arguments (%d).\n", arg_need); /* FALLTHROUGH */ case 2: argv++; if (!*argv || *argv[0] == '\0') { if (!silent) (void) fprintf(el->el_errfile, "echotc: Warning: Missing argument.\n"); return -1; } i = wcstol(*argv, &ep, 10); if (*ep != '\0' || i < 0) { if (!silent) (void) fprintf(el->el_errfile, "echotc: Bad value `%ls' for cols.\n", *argv); return -1; } arg_cols = (int) i; argv++; if (!*argv || *argv[0] == '\0') { if (!silent) (void) fprintf(el->el_errfile, "echotc: Warning: Missing argument.\n"); return -1; } i = wcstol(*argv, &ep, 10); if (*ep != '\0' || i < 0) { if (!silent) (void) fprintf(el->el_errfile, "echotc: Bad value `%ls' for rows.\n", *argv); return -1; } arg_rows = (int) i; if (*ep != '\0') { if (!silent) (void) fprintf(el->el_errfile, "echotc: Bad value `%ls'.\n", *argv); return -1; } argv++; if (*argv && *argv[0]) { if (!silent) (void) fprintf(el->el_errfile, "echotc: Warning: Extra argument `%ls" "'.\n", *argv); return -1; } terminal_tputs(el, tgoto(scap, arg_cols, arg_rows), arg_rows); break; } return 0; } heimdal-7.5.0/lib/libedit/src/shlib_version0000644000175000017500000000022613026237312017013 0ustar niknik# $NetBSD: shlib_version,v 1.19 2013/01/22 20:23:21 christos Exp $ # Remember to update distrib/sets/lists/base/shl.* when changing # major=3 minor=1 heimdal-7.5.0/lib/libedit/src/tty.h0000644000175000017500000002577113026237312015227 0ustar niknik/* $NetBSD: tty.h,v 1.21 2016/05/09 21:46:56 christos Exp $ */ /*- * Copyright (c) 1992, 1993 * The Regents of the University of California. All rights reserved. * * This code is derived from software contributed to Berkeley by * Christos Zoulas of Cornell University. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the University nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * * @(#)tty.h 8.1 (Berkeley) 6/4/93 */ /* * el.tty.h: Local terminal header */ #ifndef _h_el_tty #define _h_el_tty #include #include /* Define our own since everyone gets it wrong! */ #define CONTROL(A) ((A) & 037) /* * Aix compatible names */ # if defined(VWERSE) && !defined(VWERASE) # define VWERASE VWERSE # endif /* VWERSE && !VWERASE */ # if defined(VDISCRD) && !defined(VDISCARD) # define VDISCARD VDISCRD # endif /* VDISCRD && !VDISCARD */ # if defined(VFLUSHO) && !defined(VDISCARD) # define VDISCARD VFLUSHO # endif /* VFLUSHO && VDISCARD */ # if defined(VSTRT) && !defined(VSTART) # define VSTART VSTRT # endif /* VSTRT && ! VSTART */ # if defined(VSTAT) && !defined(VSTATUS) # define VSTATUS VSTAT # endif /* VSTAT && ! VSTATUS */ # ifndef ONLRET # define ONLRET 0 # endif /* ONLRET */ # ifndef TAB3 # ifdef OXTABS # define TAB3 OXTABS # else # define TAB3 0 # endif /* OXTABS */ # endif /* !TAB3 */ # if defined(OXTABS) && !defined(XTABS) # define XTABS OXTABS # endif /* OXTABS && !XTABS */ # ifndef ONLCR # define ONLCR 0 # endif /* ONLCR */ # ifndef IEXTEN # define IEXTEN 0 # endif /* IEXTEN */ # ifndef ECHOCTL # define ECHOCTL 0 # endif /* ECHOCTL */ # ifndef PARENB # define PARENB 0 # endif /* PARENB */ # ifndef EXTPROC # define EXTPROC 0 # endif /* EXTPROC */ # ifndef FLUSHO # define FLUSHO 0 # endif /* FLUSHO */ # if defined(VDISABLE) && !defined(_POSIX_VDISABLE) # define _POSIX_VDISABLE VDISABLE # endif /* VDISABLE && ! _POSIX_VDISABLE */ /* * Work around ISC's definition of IEXTEN which is * XCASE! */ # ifdef ISC # if defined(IEXTEN) && defined(XCASE) # if IEXTEN == XCASE # undef IEXTEN # define IEXTEN 0 # endif /* IEXTEN == XCASE */ # endif /* IEXTEN && XCASE */ # if defined(IEXTEN) && !defined(XCASE) # define XCASE IEXTEN # undef IEXTEN # define IEXTEN 0 # endif /* IEXTEN && !XCASE */ # endif /* ISC */ /* * Work around convex weirdness where turning off IEXTEN makes us * lose all postprocessing! */ #if defined(convex) || defined(__convex__) # if defined(IEXTEN) && IEXTEN != 0 # undef IEXTEN # define IEXTEN 0 # endif /* IEXTEN != 0 */ #endif /* convex || __convex__ */ /* * So that we don't lose job control. */ #ifdef __SVR4 # undef CSWTCH #endif #ifndef _POSIX_VDISABLE # define _POSIX_VDISABLE ((unsigned char) -1) #endif /* _POSIX_VDISABLE */ #if !defined(CREPRINT) && defined(CRPRNT) # define CREPRINT CRPRNT #endif /* !CREPRINT && CRPRNT */ #if !defined(CDISCARD) && defined(CFLUSH) # define CDISCARD CFLUSH #endif /* !CDISCARD && CFLUSH */ #ifndef CINTR # define CINTR CONTROL('c') #endif /* CINTR */ #ifndef CQUIT # define CQUIT 034 /* ^\ */ #endif /* CQUIT */ #ifndef CERASE # define CERASE 0177 /* ^? */ #endif /* CERASE */ #ifndef CKILL # define CKILL CONTROL('u') #endif /* CKILL */ #ifndef CEOF # define CEOF CONTROL('d') #endif /* CEOF */ #ifndef CEOL # define CEOL _POSIX_VDISABLE #endif /* CEOL */ #ifndef CEOL2 # define CEOL2 _POSIX_VDISABLE #endif /* CEOL2 */ #ifndef CSWTCH # define CSWTCH _POSIX_VDISABLE #endif /* CSWTCH */ #ifndef CDSWTCH # define CDSWTCH _POSIX_VDISABLE #endif /* CDSWTCH */ #ifndef CERASE2 # define CERASE2 _POSIX_VDISABLE #endif /* CERASE2 */ #ifndef CSTART # define CSTART CONTROL('q') #endif /* CSTART */ #ifndef CSTOP # define CSTOP CONTROL('s') #endif /* CSTOP */ #ifndef CSUSP # define CSUSP CONTROL('z') #endif /* CSUSP */ #ifndef CDSUSP # define CDSUSP CONTROL('y') #endif /* CDSUSP */ #ifdef hpux # ifndef CREPRINT # define CREPRINT _POSIX_VDISABLE # endif /* CREPRINT */ # ifndef CDISCARD # define CDISCARD _POSIX_VDISABLE # endif /* CDISCARD */ # ifndef CLNEXT # define CLNEXT _POSIX_VDISABLE # endif /* CLNEXT */ # ifndef CWERASE # define CWERASE _POSIX_VDISABLE # endif /* CWERASE */ #else /* !hpux */ # ifndef CREPRINT # define CREPRINT CONTROL('r') # endif /* CREPRINT */ # ifndef CDISCARD # define CDISCARD CONTROL('o') # endif /* CDISCARD */ # ifndef CLNEXT # define CLNEXT CONTROL('v') # endif /* CLNEXT */ # ifndef CWERASE # define CWERASE CONTROL('w') # endif /* CWERASE */ #endif /* hpux */ #ifndef CSTATUS # define CSTATUS CONTROL('t') #endif /* CSTATUS */ #ifndef CPAGE # define CPAGE ' ' #endif /* CPAGE */ #ifndef CPGOFF # define CPGOFF CONTROL('m') #endif /* CPGOFF */ #ifndef CKILL2 # define CKILL2 _POSIX_VDISABLE #endif /* CKILL2 */ #ifndef CBRK # ifndef masscomp # define CBRK 0377 # else # define CBRK '\0' # endif /* masscomp */ #endif /* CBRK */ #ifndef CMIN # define CMIN CEOF #endif /* CMIN */ #ifndef CTIME # define CTIME CEOL #endif /* CTIME */ /* * Fix for sun inconsistency. On termio VSUSP and the rest of the * ttychars > NCC are defined. So we undefine them. */ #if defined(TERMIO) || defined(POSIX) # if defined(POSIX) && defined(NCCS) # define NUMCC NCCS # else # ifdef NCC # define NUMCC NCC # endif /* NCC */ # endif /* POSIX && NCCS */ # ifdef NUMCC # ifdef VINTR # if NUMCC <= VINTR # undef VINTR # endif /* NUMCC <= VINTR */ # endif /* VINTR */ # ifdef VQUIT # if NUMCC <= VQUIT # undef VQUIT # endif /* NUMCC <= VQUIT */ # endif /* VQUIT */ # ifdef VERASE # if NUMCC <= VERASE # undef VERASE # endif /* NUMCC <= VERASE */ # endif /* VERASE */ # ifdef VKILL # if NUMCC <= VKILL # undef VKILL # endif /* NUMCC <= VKILL */ # endif /* VKILL */ # ifdef VEOF # if NUMCC <= VEOF # undef VEOF # endif /* NUMCC <= VEOF */ # endif /* VEOF */ # ifdef VEOL # if NUMCC <= VEOL # undef VEOL # endif /* NUMCC <= VEOL */ # endif /* VEOL */ # ifdef VEOL2 # if NUMCC <= VEOL2 # undef VEOL2 # endif /* NUMCC <= VEOL2 */ # endif /* VEOL2 */ # ifdef VSWTCH # if NUMCC <= VSWTCH # undef VSWTCH # endif /* NUMCC <= VSWTCH */ # endif /* VSWTCH */ # ifdef VDSWTCH # if NUMCC <= VDSWTCH # undef VDSWTCH # endif /* NUMCC <= VDSWTCH */ # endif /* VDSWTCH */ # ifdef VERASE2 # if NUMCC <= VERASE2 # undef VERASE2 # endif /* NUMCC <= VERASE2 */ # endif /* VERASE2 */ # ifdef VSTART # if NUMCC <= VSTART # undef VSTART # endif /* NUMCC <= VSTART */ # endif /* VSTART */ # ifdef VSTOP # if NUMCC <= VSTOP # undef VSTOP # endif /* NUMCC <= VSTOP */ # endif /* VSTOP */ # ifdef VWERASE # if NUMCC <= VWERASE # undef VWERASE # endif /* NUMCC <= VWERASE */ # endif /* VWERASE */ # ifdef VSUSP # if NUMCC <= VSUSP # undef VSUSP # endif /* NUMCC <= VSUSP */ # endif /* VSUSP */ # ifdef VDSUSP # if NUMCC <= VDSUSP # undef VDSUSP # endif /* NUMCC <= VDSUSP */ # endif /* VDSUSP */ # ifdef VREPRINT # if NUMCC <= VREPRINT # undef VREPRINT # endif /* NUMCC <= VREPRINT */ # endif /* VREPRINT */ # ifdef VDISCARD # if NUMCC <= VDISCARD # undef VDISCARD # endif /* NUMCC <= VDISCARD */ # endif /* VDISCARD */ # ifdef VLNEXT # if NUMCC <= VLNEXT # undef VLNEXT # endif /* NUMCC <= VLNEXT */ # endif /* VLNEXT */ # ifdef VSTATUS # if NUMCC <= VSTATUS # undef VSTATUS # endif /* NUMCC <= VSTATUS */ # endif /* VSTATUS */ # ifdef VPAGE # if NUMCC <= VPAGE # undef VPAGE # endif /* NUMCC <= VPAGE */ # endif /* VPAGE */ # ifdef VPGOFF # if NUMCC <= VPGOFF # undef VPGOFF # endif /* NUMCC <= VPGOFF */ # endif /* VPGOFF */ # ifdef VKILL2 # if NUMCC <= VKILL2 # undef VKILL2 # endif /* NUMCC <= VKILL2 */ # endif /* VKILL2 */ # ifdef VBRK # if NUMCC <= VBRK # undef VBRK # endif /* NUMCC <= VBRK */ # endif /* VBRK */ # ifdef VMIN # if NUMCC <= VMIN # undef VMIN # endif /* NUMCC <= VMIN */ # endif /* VMIN */ # ifdef VTIME # if NUMCC <= VTIME # undef VTIME # endif /* NUMCC <= VTIME */ # endif /* VTIME */ # endif /* NUMCC */ #endif /* !POSIX */ #define C_INTR 0 #define C_QUIT 1 #define C_ERASE 2 #define C_KILL 3 #define C_EOF 4 #define C_EOL 5 #define C_EOL2 6 #define C_SWTCH 7 #define C_DSWTCH 8 #define C_ERASE2 9 #define C_START 10 #define C_STOP 11 #define C_WERASE 12 #define C_SUSP 13 #define C_DSUSP 14 #define C_REPRINT 15 #define C_DISCARD 16 #define C_LNEXT 17 #define C_STATUS 18 #define C_PAGE 19 #define C_PGOFF 20 #define C_KILL2 21 #define C_BRK 22 #define C_MIN 23 #define C_TIME 24 #define C_NCC 25 #define C_SH(A) ((unsigned int)(1 << (A))) /* * Terminal dependend data structures */ #define EX_IO 0 /* while we are executing */ #define ED_IO 1 /* while we are editing */ #define TS_IO 2 /* new mode from terminal */ #define QU_IO 2 /* used only for quoted chars */ #define NN_IO 3 /* The number of entries */ /* Don't re-order */ #define MD_INP 0 #define MD_OUT 1 #define MD_CTL 2 #define MD_LIN 3 #define MD_CHAR 4 #define MD_NN 5 typedef struct { const char *t_name; unsigned int t_setmask; unsigned int t_clrmask; } ttyperm_t[NN_IO][MD_NN]; typedef unsigned char ttychar_t[NN_IO][C_NCC]; libedit_private int tty_init(EditLine *); libedit_private void tty_end(EditLine *); libedit_private int tty_stty(EditLine *, int, const wchar_t **); libedit_private int tty_rawmode(EditLine *); libedit_private int tty_cookedmode(EditLine *); libedit_private int tty_quotemode(EditLine *); libedit_private int tty_noquotemode(EditLine *); libedit_private void tty_bind_char(EditLine *, int); typedef struct { ttyperm_t t_t; ttychar_t t_c; struct termios t_or, t_ex, t_ed, t_ts; int t_tabs; int t_eight; speed_t t_speed; unsigned char t_mode; unsigned char t_vdisable; unsigned char t_initialized; } el_tty_t; #endif /* _h_el_tty */ heimdal-7.5.0/lib/libedit/src/wcsdup.c0000644000175000017500000000162213026237312015674 0ustar niknik/* $NetBSD: wcsdup.c,v 1.3 2008/05/26 13:17:48 haad Exp $ */ /* * Copyright (C) 2006 Aleksey Cheusov * * This material is provided "as is", with absolutely no warranty expressed * or implied. Any use is at your own risk. * * Permission to use or copy this software for any purpose is hereby granted * without fee. Permission to modify the code and to distribute modified * code is also granted without any restrictions. */ #ifndef HAVE_WCSDUP #include "config.h" #if defined(LIBC_SCCS) && !defined(lint) __RCSID("$NetBSD: wcsdup.c,v 1.3 2008/05/26 13:17:48 haad Exp $"); #endif /* LIBC_SCCS and not lint */ #include #include #include wchar_t * wcsdup(const wchar_t *str) { wchar_t *copy; size_t len; _DIAGASSERT(str != NULL); len = wcslen(str) + 1; copy = malloc(len * sizeof (wchar_t)); if (!copy) return NULL; return wmemcpy(copy, str, len); } #endif heimdal-7.5.0/lib/libedit/src/filecomplete.h0000644000175000017500000000371413026237312017050 0ustar niknik/* $NetBSD: filecomplete.h,v 1.10 2016/04/11 00:50:13 christos Exp $ */ /*- * Copyright (c) 1997 The NetBSD Foundation, Inc. * All rights reserved. * * This code is derived from software contributed to The NetBSD Foundation * by Jaromir Dolecek. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #ifndef _FILECOMPLETE_H_ #define _FILECOMPLETE_H_ int fn_complete(EditLine *, char *(*)(const char *, int), char **(*)(const char *, int, int), const wchar_t *, const wchar_t *, const char *(*)(const char *), size_t, int *, int *, int *, int *); void fn_display_match_list(EditLine *, char **, size_t, size_t); char *fn_tilde_expand(const char *); char *fn_filename_completion_function(const char *, int); #endif heimdal-7.5.0/lib/libedit/src/refresh.h0000644000175000017500000000456613026237312016044 0ustar niknik/* $NetBSD: refresh.h,v 1.10 2016/05/09 21:46:56 christos Exp $ */ /*- * Copyright (c) 1992, 1993 * The Regents of the University of California. All rights reserved. * * This code is derived from software contributed to Berkeley by * Christos Zoulas of Cornell University. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the University nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * * @(#)refresh.h 8.1 (Berkeley) 6/4/93 */ /* * el.refresh.h: Screen refresh functions */ #ifndef _h_el_refresh #define _h_el_refresh typedef struct { coord_t r_cursor; /* Refresh cursor position */ int r_oldcv; /* Vertical locations */ int r_newcv; } el_refresh_t; libedit_private void re_putc(EditLine *, wint_t, int); libedit_private void re_clear_lines(EditLine *); libedit_private void re_clear_display(EditLine *); libedit_private void re_refresh(EditLine *); libedit_private void re_refresh_cursor(EditLine *); libedit_private void re_fastaddc(EditLine *); libedit_private void re_goto_bottom(EditLine *); #endif /* _h_el_refresh */ heimdal-7.5.0/lib/libedit/src/vis.h0000644000175000017500000001060113212137553015175 0ustar niknik/* $NetBSD: vis.h,v 1.24 2016/01/14 20:42:14 christos Exp $ */ /*- * Copyright (c) 1990, 1993 * The Regents of the University of California. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the University nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * * @(#)vis.h 8.1 (Berkeley) 6/2/93 */ #ifndef _VIS_H_ #define _VIS_H_ #include /* * to select alternate encoding format */ #define VIS_OCTAL 0x0001 /* use octal \ddd format */ #define VIS_CSTYLE 0x0002 /* use \[nrft0..] where appropiate */ /* * to alter set of characters encoded (default is to encode all * non-graphic except space, tab, and newline). */ #define VIS_SP 0x0004 /* also encode space */ #define VIS_TAB 0x0008 /* also encode tab */ #define VIS_NL 0x0010 /* also encode newline */ #define VIS_WHITE (VIS_SP | VIS_TAB | VIS_NL) #define VIS_SAFE 0x0020 /* only encode "unsafe" characters */ /* * other */ #define VIS_NOSLASH 0x0040 /* inhibit printing '\' */ #define VIS_HTTP1808 0x0080 /* http-style escape % hex hex */ #define VIS_HTTPSTYLE 0x0080 /* http-style escape % hex hex */ #define VIS_MIMESTYLE 0x0100 /* mime-style escape = HEX HEX */ #define VIS_HTTP1866 0x0200 /* http-style &#num; or &string; */ #define VIS_NOESCAPE 0x0400 /* don't decode `\' */ #define _VIS_END 0x0800 /* for unvis */ #define VIS_GLOB 0x1000 /* encode glob(3) magic characters */ #define VIS_SHELL 0x2000 /* encode shell special characters [not glob] */ #define VIS_META (VIS_WHITE | VIS_GLOB | VIS_SHELL) #define VIS_NOLOCALE 0x4000 /* encode using the C locale */ /* * unvis return codes */ #define UNVIS_VALID 1 /* character valid */ #define UNVIS_VALIDPUSH 2 /* character valid, push back passed char */ #define UNVIS_NOCHAR 3 /* valid sequence, no character produced */ #define UNVIS_SYNBAD -1 /* unrecognized escape sequence */ #define UNVIS_ERROR -2 /* decoder in unknown state (unrecoverable) */ /* * unvis flags */ #define UNVIS_END _VIS_END /* no more characters */ #include __BEGIN_DECLS char *vis(char *, int, int, int); char *nvis(char *, size_t, int, int, int); char *svis(char *, int, int, int, const char *); char *snvis(char *, size_t, int, int, int, const char *); int strvis(char *, const char *, int); int stravis(char **, const char *, int); int strnvis(char *, size_t, const char *, int); int strsvis(char *, const char *, int, const char *); int strsnvis(char *, size_t, const char *, int, const char *); int strvisx(char *, const char *, size_t, int); int strnvisx(char *, size_t, const char *, size_t, int); int strenvisx(char *, size_t, const char *, size_t, int, int *); int strsvisx(char *, const char *, size_t, int, const char *); int strsnvisx(char *, size_t, const char *, size_t, int, const char *); int strsenvisx(char *, size_t, const char *, size_t , int, const char *, int *); int strunvis(char *, const char *); int strnunvis(char *, size_t, const char *); int strunvisx(char *, const char *, int); int strnunvisx(char *, size_t, const char *, int); int unvis(char *, int, int *, int); __END_DECLS #endif /* !_VIS_H_ */ heimdal-7.5.0/lib/libedit/src/keymacro.h0000644000175000017500000000622613026237312016213 0ustar niknik/* $NetBSD: keymacro.h,v 1.6 2016/05/09 21:46:56 christos Exp $ */ /*- * Copyright (c) 1992, 1993 * The Regents of the University of California. All rights reserved. * * This code is derived from software contributed to Berkeley by * Christos Zoulas of Cornell University. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the University nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * * @(#)key.h 8.1 (Berkeley) 6/4/93 */ /* * el.keymacro.h: Key macro header */ #ifndef _h_el_keymacro #define _h_el_keymacro typedef union keymacro_value_t { el_action_t cmd; /* If it is a command the # */ wchar_t *str; /* If it is a string... */ } keymacro_value_t; typedef struct keymacro_node_t keymacro_node_t; typedef struct el_keymacro_t { wchar_t *buf; /* Key print buffer */ keymacro_node_t *map; /* Key map */ keymacro_value_t val; /* Local conversion buffer */ } el_keymacro_t; #define XK_CMD 0 #define XK_STR 1 #define XK_NOD 2 libedit_private int keymacro_init(EditLine *); libedit_private void keymacro_end(EditLine *); libedit_private keymacro_value_t *keymacro_map_cmd(EditLine *, int); libedit_private keymacro_value_t *keymacro_map_str(EditLine *, wchar_t *); libedit_private void keymacro_reset(EditLine *); libedit_private int keymacro_get(EditLine *, wchar_t *, keymacro_value_t *); libedit_private void keymacro_add(EditLine *, const wchar_t *, keymacro_value_t *, int); libedit_private void keymacro_clear(EditLine *, el_action_t *, const wchar_t *); libedit_private int keymacro_delete(EditLine *, const wchar_t *); libedit_private void keymacro_print(EditLine *, const wchar_t *); libedit_private void keymacro_kprint(EditLine *, const wchar_t *, keymacro_value_t *, int); libedit_private size_t keymacro__decode_str(const wchar_t *, char *, size_t, const char *); #endif /* _h_el_keymacro */ heimdal-7.5.0/lib/libedit/src/hist.h0000644000175000017500000000657613026237312015360 0ustar niknik/* $NetBSD: hist.h,v 1.22 2016/05/09 21:46:56 christos Exp $ */ /*- * Copyright (c) 1992, 1993 * The Regents of the University of California. All rights reserved. * * This code is derived from software contributed to Berkeley by * Christos Zoulas of Cornell University. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the University nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * * @(#)hist.h 8.1 (Berkeley) 6/4/93 */ /* * el.hist.c: History functions */ #ifndef _h_el_hist #define _h_el_hist typedef int (*hist_fun_t)(void *, HistEventW *, int, ...); typedef struct el_history_t { wchar_t *buf; /* The history buffer */ size_t sz; /* Size of history buffer */ wchar_t *last; /* The last character */ int eventno; /* Event we are looking for */ void *ref; /* Argument for history fcns */ hist_fun_t fun; /* Event access */ HistEventW ev; /* Event cookie */ } el_history_t; #define HIST_FUN_INTERNAL(el, fn, arg) \ ((((*(el)->el_history.fun) ((el)->el_history.ref, &(el)->el_history.ev, \ fn, arg)) == -1) ? NULL : (el)->el_history.ev.str) #define HIST_FUN(el, fn, arg) \ (((el)->el_flags & NARROW_HISTORY) ? hist_convert(el, fn, arg) : \ HIST_FUN_INTERNAL(el, fn, arg)) #define HIST_NEXT(el) HIST_FUN(el, H_NEXT, NULL) #define HIST_FIRST(el) HIST_FUN(el, H_FIRST, NULL) #define HIST_LAST(el) HIST_FUN(el, H_LAST, NULL) #define HIST_PREV(el) HIST_FUN(el, H_PREV, NULL) #define HIST_SET(el, num) HIST_FUN(el, H_SET, num) #define HIST_LOAD(el, fname) HIST_FUN(el, H_LOAD fname) #define HIST_SAVE(el, fname) HIST_FUN(el, H_SAVE fname) #define HIST_SAVE_FP(el, fp) HIST_FUN(el, H_SAVE_FP fp) libedit_private int hist_init(EditLine *); libedit_private void hist_end(EditLine *); libedit_private el_action_t hist_get(EditLine *); libedit_private int hist_set(EditLine *, hist_fun_t, void *); libedit_private int hist_command(EditLine *, int, const wchar_t **); libedit_private int hist_enlargebuf(EditLine *, size_t, size_t); libedit_private wchar_t *hist_convert(EditLine *, int, void *); #endif /* _h_el_hist */ heimdal-7.5.0/lib/libedit/src/common.c0000644000175000017500000004454613026237312015673 0ustar niknik/* $NetBSD: common.c,v 1.47 2016/05/22 19:44:26 christos Exp $ */ /*- * Copyright (c) 1992, 1993 * The Regents of the University of California. All rights reserved. * * This code is derived from software contributed to Berkeley by * Christos Zoulas of Cornell University. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the University nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "config.h" #if !defined(lint) && !defined(SCCSID) #if 0 static char sccsid[] = "@(#)common.c 8.1 (Berkeley) 6/4/93"; #else __RCSID("$NetBSD: common.c,v 1.47 2016/05/22 19:44:26 christos Exp $"); #endif #endif /* not lint && not SCCSID */ /* * common.c: Common Editor functions */ #include #include #include "el.h" #include "common.h" #include "fcns.h" #include "parse.h" #include "vi.h" /* ed_end_of_file(): * Indicate end of file * [^D] */ libedit_private el_action_t /*ARGSUSED*/ ed_end_of_file(EditLine *el, wint_t c __attribute__((__unused__))) { re_goto_bottom(el); *el->el_line.lastchar = '\0'; return CC_EOF; } /* ed_insert(): * Add character to the line * Insert a character [bound to all insert keys] */ libedit_private el_action_t ed_insert(EditLine *el, wint_t c) { int count = el->el_state.argument; if (c == '\0') return CC_ERROR; if (el->el_line.lastchar + el->el_state.argument >= el->el_line.limit) { /* end of buffer space, try to allocate more */ if (!ch_enlargebufs(el, (size_t) count)) return CC_ERROR; /* error allocating more */ } if (count == 1) { if (el->el_state.inputmode == MODE_INSERT || el->el_line.cursor >= el->el_line.lastchar) c_insert(el, 1); *el->el_line.cursor++ = c; re_fastaddc(el); /* fast refresh for one char. */ } else { if (el->el_state.inputmode != MODE_REPLACE_1) c_insert(el, el->el_state.argument); while (count-- && el->el_line.cursor < el->el_line.lastchar) *el->el_line.cursor++ = c; re_refresh(el); } if (el->el_state.inputmode == MODE_REPLACE_1) return vi_command_mode(el, 0); return CC_NORM; } /* ed_delete_prev_word(): * Delete from beginning of current word to cursor * [M-^?] [^W] */ libedit_private el_action_t /*ARGSUSED*/ ed_delete_prev_word(EditLine *el, wint_t c __attribute__((__unused__))) { wchar_t *cp, *p, *kp; if (el->el_line.cursor == el->el_line.buffer) return CC_ERROR; cp = c__prev_word(el->el_line.cursor, el->el_line.buffer, el->el_state.argument, ce__isword); for (p = cp, kp = el->el_chared.c_kill.buf; p < el->el_line.cursor; p++) *kp++ = *p; el->el_chared.c_kill.last = kp; c_delbefore(el, (int)(el->el_line.cursor - cp));/* delete before dot */ el->el_line.cursor = cp; if (el->el_line.cursor < el->el_line.buffer) el->el_line.cursor = el->el_line.buffer; /* bounds check */ return CC_REFRESH; } /* ed_delete_next_char(): * Delete character under cursor * [^D] [x] */ libedit_private el_action_t /*ARGSUSED*/ ed_delete_next_char(EditLine *el, wint_t c __attribute__((__unused__))) { #ifdef DEBUG_EDIT #define EL el->el_line (void) fprintf(el->el_errfile, "\nD(b: %p(%ls) c: %p(%ls) last: %p(%ls) limit: %p(%ls)\n", EL.buffer, EL.buffer, EL.cursor, EL.cursor, EL.lastchar, EL.lastchar, EL.limit, EL.limit); #endif if (el->el_line.cursor == el->el_line.lastchar) { /* if I'm at the end */ if (el->el_map.type == MAP_VI) { if (el->el_line.cursor == el->el_line.buffer) { /* if I'm also at the beginning */ #ifdef KSHVI return CC_ERROR; #else /* then do an EOF */ terminal_writec(el, c); return CC_EOF; #endif } else { #ifdef KSHVI el->el_line.cursor--; #else return CC_ERROR; #endif } } else return CC_ERROR; } c_delafter(el, el->el_state.argument); /* delete after dot */ if (el->el_map.type == MAP_VI && el->el_line.cursor >= el->el_line.lastchar && el->el_line.cursor > el->el_line.buffer) /* bounds check */ el->el_line.cursor = el->el_line.lastchar - 1; return CC_REFRESH; } /* ed_kill_line(): * Cut to the end of line * [^K] [^K] */ libedit_private el_action_t /*ARGSUSED*/ ed_kill_line(EditLine *el, wint_t c __attribute__((__unused__))) { wchar_t *kp, *cp; cp = el->el_line.cursor; kp = el->el_chared.c_kill.buf; while (cp < el->el_line.lastchar) *kp++ = *cp++; /* copy it */ el->el_chared.c_kill.last = kp; /* zap! -- delete to end */ el->el_line.lastchar = el->el_line.cursor; return CC_REFRESH; } /* ed_move_to_end(): * Move cursor to the end of line * [^E] [^E] */ libedit_private el_action_t /*ARGSUSED*/ ed_move_to_end(EditLine *el, wint_t c __attribute__((__unused__))) { el->el_line.cursor = el->el_line.lastchar; if (el->el_map.type == MAP_VI) { if (el->el_chared.c_vcmd.action != NOP) { cv_delfini(el); return CC_REFRESH; } #ifdef VI_MOVE el->el_line.cursor--; #endif } return CC_CURSOR; } /* ed_move_to_beg(): * Move cursor to the beginning of line * [^A] [^A] */ libedit_private el_action_t /*ARGSUSED*/ ed_move_to_beg(EditLine *el, wint_t c __attribute__((__unused__))) { el->el_line.cursor = el->el_line.buffer; if (el->el_map.type == MAP_VI) { /* We want FIRST non space character */ while (iswspace(*el->el_line.cursor)) el->el_line.cursor++; if (el->el_chared.c_vcmd.action != NOP) { cv_delfini(el); return CC_REFRESH; } } return CC_CURSOR; } /* ed_transpose_chars(): * Exchange the character to the left of the cursor with the one under it * [^T] [^T] */ libedit_private el_action_t ed_transpose_chars(EditLine *el, wint_t c) { if (el->el_line.cursor < el->el_line.lastchar) { if (el->el_line.lastchar <= &el->el_line.buffer[1]) return CC_ERROR; else el->el_line.cursor++; } if (el->el_line.cursor > &el->el_line.buffer[1]) { /* must have at least two chars entered */ c = el->el_line.cursor[-2]; el->el_line.cursor[-2] = el->el_line.cursor[-1]; el->el_line.cursor[-1] = c; return CC_REFRESH; } else return CC_ERROR; } /* ed_next_char(): * Move to the right one character * [^F] [^F] */ libedit_private el_action_t /*ARGSUSED*/ ed_next_char(EditLine *el, wint_t c __attribute__((__unused__))) { wchar_t *lim = el->el_line.lastchar; if (el->el_line.cursor >= lim || (el->el_line.cursor == lim - 1 && el->el_map.type == MAP_VI && el->el_chared.c_vcmd.action == NOP)) return CC_ERROR; el->el_line.cursor += el->el_state.argument; if (el->el_line.cursor > lim) el->el_line.cursor = lim; if (el->el_map.type == MAP_VI) if (el->el_chared.c_vcmd.action != NOP) { cv_delfini(el); return CC_REFRESH; } return CC_CURSOR; } /* ed_prev_word(): * Move to the beginning of the current word * [M-b] [b] */ libedit_private el_action_t /*ARGSUSED*/ ed_prev_word(EditLine *el, wint_t c __attribute__((__unused__))) { if (el->el_line.cursor == el->el_line.buffer) return CC_ERROR; el->el_line.cursor = c__prev_word(el->el_line.cursor, el->el_line.buffer, el->el_state.argument, ce__isword); if (el->el_map.type == MAP_VI) if (el->el_chared.c_vcmd.action != NOP) { cv_delfini(el); return CC_REFRESH; } return CC_CURSOR; } /* ed_prev_char(): * Move to the left one character * [^B] [^B] */ libedit_private el_action_t /*ARGSUSED*/ ed_prev_char(EditLine *el, wint_t c __attribute__((__unused__))) { if (el->el_line.cursor > el->el_line.buffer) { el->el_line.cursor -= el->el_state.argument; if (el->el_line.cursor < el->el_line.buffer) el->el_line.cursor = el->el_line.buffer; if (el->el_map.type == MAP_VI) if (el->el_chared.c_vcmd.action != NOP) { cv_delfini(el); return CC_REFRESH; } return CC_CURSOR; } else return CC_ERROR; } /* ed_quoted_insert(): * Add the next character typed verbatim * [^V] [^V] */ libedit_private el_action_t ed_quoted_insert(EditLine *el, wint_t c) { int num; tty_quotemode(el); num = el_wgetc(el, &c); tty_noquotemode(el); if (num == 1) return ed_insert(el, c); else return ed_end_of_file(el, 0); } /* ed_digit(): * Adds to argument or enters a digit */ libedit_private el_action_t ed_digit(EditLine *el, wint_t c) { if (!iswdigit(c)) return CC_ERROR; if (el->el_state.doingarg) { /* if doing an arg, add this in... */ if (el->el_state.lastcmd == EM_UNIVERSAL_ARGUMENT) el->el_state.argument = c - '0'; else { if (el->el_state.argument > 1000000) return CC_ERROR; el->el_state.argument = (el->el_state.argument * 10) + (c - '0'); } return CC_ARGHACK; } return ed_insert(el, c); } /* ed_argument_digit(): * Digit that starts argument * For ESC-n */ libedit_private el_action_t ed_argument_digit(EditLine *el, wint_t c) { if (!iswdigit(c)) return CC_ERROR; if (el->el_state.doingarg) { if (el->el_state.argument > 1000000) return CC_ERROR; el->el_state.argument = (el->el_state.argument * 10) + (c - '0'); } else { /* else starting an argument */ el->el_state.argument = c - '0'; el->el_state.doingarg = 1; } return CC_ARGHACK; } /* ed_unassigned(): * Indicates unbound character * Bound to keys that are not assigned */ libedit_private el_action_t /*ARGSUSED*/ ed_unassigned(EditLine *el __attribute__((__unused__)), wint_t c __attribute__((__unused__))) { return CC_ERROR; } /* ed_ignore(): * Input characters that have no effect * [^C ^O ^Q ^S ^Z ^\ ^]] [^C ^O ^Q ^S ^\] */ libedit_private el_action_t /*ARGSUSED*/ ed_ignore(EditLine *el __attribute__((__unused__)), wint_t c __attribute__((__unused__))) { return CC_NORM; } /* ed_newline(): * Execute command * [^J] */ libedit_private el_action_t /*ARGSUSED*/ ed_newline(EditLine *el, wint_t c __attribute__((__unused__))) { re_goto_bottom(el); *el->el_line.lastchar++ = '\n'; *el->el_line.lastchar = '\0'; return CC_NEWLINE; } /* ed_delete_prev_char(): * Delete the character to the left of the cursor * [^?] */ libedit_private el_action_t /*ARGSUSED*/ ed_delete_prev_char(EditLine *el, wint_t c __attribute__((__unused__))) { if (el->el_line.cursor <= el->el_line.buffer) return CC_ERROR; c_delbefore(el, el->el_state.argument); el->el_line.cursor -= el->el_state.argument; if (el->el_line.cursor < el->el_line.buffer) el->el_line.cursor = el->el_line.buffer; return CC_REFRESH; } /* ed_clear_screen(): * Clear screen leaving current line at the top * [^L] */ libedit_private el_action_t /*ARGSUSED*/ ed_clear_screen(EditLine *el, wint_t c __attribute__((__unused__))) { terminal_clear_screen(el); /* clear the whole real screen */ re_clear_display(el); /* reset everything */ return CC_REFRESH; } /* ed_redisplay(): * Redisplay everything * ^R */ libedit_private el_action_t /*ARGSUSED*/ ed_redisplay(EditLine *el __attribute__((__unused__)), wint_t c __attribute__((__unused__))) { return CC_REDISPLAY; } /* ed_start_over(): * Erase current line and start from scratch * [^G] */ libedit_private el_action_t /*ARGSUSED*/ ed_start_over(EditLine *el, wint_t c __attribute__((__unused__))) { ch_reset(el); return CC_REFRESH; } /* ed_sequence_lead_in(): * First character in a bound sequence * Placeholder for external keys */ libedit_private el_action_t /*ARGSUSED*/ ed_sequence_lead_in(EditLine *el __attribute__((__unused__)), wint_t c __attribute__((__unused__))) { return CC_NORM; } /* ed_prev_history(): * Move to the previous history line * [^P] [k] */ libedit_private el_action_t /*ARGSUSED*/ ed_prev_history(EditLine *el, wint_t c __attribute__((__unused__))) { char beep = 0; int sv_event = el->el_history.eventno; el->el_chared.c_undo.len = -1; *el->el_line.lastchar = '\0'; /* just in case */ if (el->el_history.eventno == 0) { /* save the current buffer * away */ (void) wcsncpy(el->el_history.buf, el->el_line.buffer, EL_BUFSIZ); el->el_history.last = el->el_history.buf + (el->el_line.lastchar - el->el_line.buffer); } el->el_history.eventno += el->el_state.argument; if (hist_get(el) == CC_ERROR) { if (el->el_map.type == MAP_VI) { el->el_history.eventno = sv_event; } beep = 1; /* el->el_history.eventno was fixed by first call */ (void) hist_get(el); } if (beep) return CC_REFRESH_BEEP; return CC_REFRESH; } /* ed_next_history(): * Move to the next history line * [^N] [j] */ libedit_private el_action_t /*ARGSUSED*/ ed_next_history(EditLine *el, wint_t c __attribute__((__unused__))) { el_action_t beep = CC_REFRESH, rval; el->el_chared.c_undo.len = -1; *el->el_line.lastchar = '\0'; /* just in case */ el->el_history.eventno -= el->el_state.argument; if (el->el_history.eventno < 0) { el->el_history.eventno = 0; beep = CC_REFRESH_BEEP; } rval = hist_get(el); if (rval == CC_REFRESH) return beep; return rval; } /* ed_search_prev_history(): * Search previous in history for a line matching the current * next search history [M-P] [K] */ libedit_private el_action_t /*ARGSUSED*/ ed_search_prev_history(EditLine *el, wint_t c __attribute__((__unused__))) { const wchar_t *hp; int h; int found = 0; el->el_chared.c_vcmd.action = NOP; el->el_chared.c_undo.len = -1; *el->el_line.lastchar = '\0'; /* just in case */ if (el->el_history.eventno < 0) { #ifdef DEBUG_EDIT (void) fprintf(el->el_errfile, "e_prev_search_hist(): eventno < 0;\n"); #endif el->el_history.eventno = 0; return CC_ERROR; } if (el->el_history.eventno == 0) { (void) wcsncpy(el->el_history.buf, el->el_line.buffer, EL_BUFSIZ); el->el_history.last = el->el_history.buf + (el->el_line.lastchar - el->el_line.buffer); } if (el->el_history.ref == NULL) return CC_ERROR; hp = HIST_FIRST(el); if (hp == NULL) return CC_ERROR; c_setpat(el); /* Set search pattern !! */ for (h = 1; h <= el->el_history.eventno; h++) hp = HIST_NEXT(el); while (hp != NULL) { #ifdef SDEBUG (void) fprintf(el->el_errfile, "Comparing with \"%s\"\n", hp); #endif if ((wcsncmp(hp, el->el_line.buffer, (size_t) (el->el_line.lastchar - el->el_line.buffer)) || hp[el->el_line.lastchar - el->el_line.buffer]) && c_hmatch(el, hp)) { found = 1; break; } h++; hp = HIST_NEXT(el); } if (!found) { #ifdef SDEBUG (void) fprintf(el->el_errfile, "not found\n"); #endif return CC_ERROR; } el->el_history.eventno = h; return hist_get(el); } /* ed_search_next_history(): * Search next in history for a line matching the current * [M-N] [J] */ libedit_private el_action_t /*ARGSUSED*/ ed_search_next_history(EditLine *el, wint_t c __attribute__((__unused__))) { const wchar_t *hp; int h; int found = 0; el->el_chared.c_vcmd.action = NOP; el->el_chared.c_undo.len = -1; *el->el_line.lastchar = '\0'; /* just in case */ if (el->el_history.eventno == 0) return CC_ERROR; if (el->el_history.ref == NULL) return CC_ERROR; hp = HIST_FIRST(el); if (hp == NULL) return CC_ERROR; c_setpat(el); /* Set search pattern !! */ for (h = 1; h < el->el_history.eventno && hp; h++) { #ifdef SDEBUG (void) fprintf(el->el_errfile, "Comparing with \"%s\"\n", hp); #endif if ((wcsncmp(hp, el->el_line.buffer, (size_t) (el->el_line.lastchar - el->el_line.buffer)) || hp[el->el_line.lastchar - el->el_line.buffer]) && c_hmatch(el, hp)) found = h; hp = HIST_NEXT(el); } if (!found) { /* is it the current history number? */ if (!c_hmatch(el, el->el_history.buf)) { #ifdef SDEBUG (void) fprintf(el->el_errfile, "not found\n"); #endif return CC_ERROR; } } el->el_history.eventno = found; return hist_get(el); } /* ed_prev_line(): * Move up one line * Could be [k] [^p] */ libedit_private el_action_t /*ARGSUSED*/ ed_prev_line(EditLine *el, wint_t c __attribute__((__unused__))) { wchar_t *ptr; int nchars = c_hpos(el); /* * Move to the line requested */ if (*(ptr = el->el_line.cursor) == '\n') ptr--; for (; ptr >= el->el_line.buffer; ptr--) if (*ptr == '\n' && --el->el_state.argument <= 0) break; if (el->el_state.argument > 0) return CC_ERROR; /* * Move to the beginning of the line */ for (ptr--; ptr >= el->el_line.buffer && *ptr != '\n'; ptr--) continue; /* * Move to the character requested */ for (ptr++; nchars-- > 0 && ptr < el->el_line.lastchar && *ptr != '\n'; ptr++) continue; el->el_line.cursor = ptr; return CC_CURSOR; } /* ed_next_line(): * Move down one line * Could be [j] [^n] */ libedit_private el_action_t /*ARGSUSED*/ ed_next_line(EditLine *el, wint_t c __attribute__((__unused__))) { wchar_t *ptr; int nchars = c_hpos(el); /* * Move to the line requested */ for (ptr = el->el_line.cursor; ptr < el->el_line.lastchar; ptr++) if (*ptr == '\n' && --el->el_state.argument <= 0) break; if (el->el_state.argument > 0) return CC_ERROR; /* * Move to the character requested */ for (ptr++; nchars-- > 0 && ptr < el->el_line.lastchar && *ptr != '\n'; ptr++) continue; el->el_line.cursor = ptr; return CC_CURSOR; } /* ed_command(): * Editline extended command * [M-X] [:] */ libedit_private el_action_t /*ARGSUSED*/ ed_command(EditLine *el, wint_t c __attribute__((__unused__))) { wchar_t tmpbuf[EL_BUFSIZ]; int tmplen; tmplen = c_gets(el, tmpbuf, L"\n: "); terminal__putc(el, '\n'); if (tmplen < 0 || (tmpbuf[tmplen] = 0, parse_line(el, tmpbuf)) == -1) terminal_beep(el); el->el_map.current = el->el_map.key; re_clear_display(el); return CC_REFRESH; } heimdal-7.5.0/lib/libedit/src/history.c0000644000175000017500000006407013026237312016076 0ustar niknik/* $NetBSD: history.c,v 1.57 2016/04/11 18:56:31 christos Exp $ */ /*- * Copyright (c) 1992, 1993 * The Regents of the University of California. All rights reserved. * * This code is derived from software contributed to Berkeley by * Christos Zoulas of Cornell University. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the University nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "config.h" #if !defined(lint) && !defined(SCCSID) #if 0 static char sccsid[] = "@(#)history.c 8.1 (Berkeley) 6/4/93"; #else __RCSID("$NetBSD: history.c,v 1.57 2016/04/11 18:56:31 christos Exp $"); #endif #endif /* not lint && not SCCSID */ /* * hist.c: TYPE(History) access functions */ #include #include #include #include #include static const char hist_cookie[] = "_HiStOrY_V2_\n"; #include "histedit.h" #ifdef NARROWCHAR #define Char char #define FUN(prefix, rest) prefix ## _ ## rest #define FUNW(type) type #define TYPE(type) type #define STR(x) x #define Strlen(s) strlen(s) #define Strdup(s) strdup(s) #define Strcmp(d, s) strcmp(d, s) #define Strncmp(d, s, n) strncmp(d, s, n) #define Strncpy(d, s, n) strncpy(d, s, n) #define Strncat(d, s, n) strncat(d, s, n) #define ct_decode_string(s, b) (s) #define ct_encode_string(s, b) (s) #else #include "chartype.h" #define Char wchar_t #define FUN(prefix, rest) prefix ## _w ## rest #define FUNW(type) type ## _w #define TYPE(type) type ## W #define STR(x) L ## x #define Strlen(s) wcslen(s) #define Strdup(s) wcsdup(s) #define Strcmp(d, s) wcscmp(d, s) #define Strncmp(d, s, n) wcsncmp(d, s, n) #define Strncpy(d, s, n) wcsncpy(d, s, n) #define Strncat(d, s, n) wcsncat(d, s, n) #endif typedef int (*history_gfun_t)(void *, TYPE(HistEvent) *); typedef int (*history_efun_t)(void *, TYPE(HistEvent) *, const Char *); typedef void (*history_vfun_t)(void *, TYPE(HistEvent) *); typedef int (*history_sfun_t)(void *, TYPE(HistEvent) *, const int); struct TYPE(history) { void *h_ref; /* Argument for history fcns */ int h_ent; /* Last entry point for history */ history_gfun_t h_first; /* Get the first element */ history_gfun_t h_next; /* Get the next element */ history_gfun_t h_last; /* Get the last element */ history_gfun_t h_prev; /* Get the previous element */ history_gfun_t h_curr; /* Get the current element */ history_sfun_t h_set; /* Set the current element */ history_sfun_t h_del; /* Set the given element */ history_vfun_t h_clear; /* Clear the history list */ history_efun_t h_enter; /* Add an element */ history_efun_t h_add; /* Append to an element */ }; #define HNEXT(h, ev) (*(h)->h_next)((h)->h_ref, ev) #define HFIRST(h, ev) (*(h)->h_first)((h)->h_ref, ev) #define HPREV(h, ev) (*(h)->h_prev)((h)->h_ref, ev) #define HLAST(h, ev) (*(h)->h_last)((h)->h_ref, ev) #define HCURR(h, ev) (*(h)->h_curr)((h)->h_ref, ev) #define HSET(h, ev, n) (*(h)->h_set)((h)->h_ref, ev, n) #define HCLEAR(h, ev) (*(h)->h_clear)((h)->h_ref, ev) #define HENTER(h, ev, str) (*(h)->h_enter)((h)->h_ref, ev, str) #define HADD(h, ev, str) (*(h)->h_add)((h)->h_ref, ev, str) #define HDEL(h, ev, n) (*(h)->h_del)((h)->h_ref, ev, n) #define h_strdup(a) Strdup(a) #define h_malloc(a) malloc(a) #define h_realloc(a, b) realloc((a), (b)) #define h_free(a) free(a) typedef struct { int num; Char *str; } HistEventPrivate; static int history_setsize(TYPE(History) *, TYPE(HistEvent) *, int); static int history_getsize(TYPE(History) *, TYPE(HistEvent) *); static int history_setunique(TYPE(History) *, TYPE(HistEvent) *, int); static int history_getunique(TYPE(History) *, TYPE(HistEvent) *); static int history_set_fun(TYPE(History) *, TYPE(History) *); static int history_load(TYPE(History) *, const char *); static int history_save(TYPE(History) *, const char *); static int history_save_fp(TYPE(History) *, FILE *); static int history_prev_event(TYPE(History) *, TYPE(HistEvent) *, int); static int history_next_event(TYPE(History) *, TYPE(HistEvent) *, int); static int history_next_string(TYPE(History) *, TYPE(HistEvent) *, const Char *); static int history_prev_string(TYPE(History) *, TYPE(HistEvent) *, const Char *); /***********************************************************************/ /* * Builtin- history implementation */ typedef struct hentry_t { TYPE(HistEvent) ev; /* What we return */ void *data; /* data */ struct hentry_t *next; /* Next entry */ struct hentry_t *prev; /* Previous entry */ } hentry_t; typedef struct history_t { hentry_t list; /* Fake list header element */ hentry_t *cursor; /* Current element in the list */ int max; /* Maximum number of events */ int cur; /* Current number of events */ int eventid; /* For generation of unique event id */ int flags; /* TYPE(History) flags */ #define H_UNIQUE 1 /* Store only unique elements */ } history_t; static int history_def_next(void *, TYPE(HistEvent) *); static int history_def_first(void *, TYPE(HistEvent) *); static int history_def_prev(void *, TYPE(HistEvent) *); static int history_def_last(void *, TYPE(HistEvent) *); static int history_def_curr(void *, TYPE(HistEvent) *); static int history_def_set(void *, TYPE(HistEvent) *, const int); static void history_def_clear(void *, TYPE(HistEvent) *); static int history_def_enter(void *, TYPE(HistEvent) *, const Char *); static int history_def_add(void *, TYPE(HistEvent) *, const Char *); static int history_def_del(void *, TYPE(HistEvent) *, const int); static int history_def_init(void **, TYPE(HistEvent) *, int); static int history_def_insert(history_t *, TYPE(HistEvent) *, const Char *); static void history_def_delete(history_t *, TYPE(HistEvent) *, hentry_t *); static int history_deldata_nth(history_t *, TYPE(HistEvent) *, int, void **); static int history_set_nth(void *, TYPE(HistEvent) *, int); #define history_def_setsize(p, num)(void) (((history_t *)p)->max = (num)) #define history_def_getsize(p) (((history_t *)p)->cur) #define history_def_getunique(p) (((((history_t *)p)->flags) & H_UNIQUE) != 0) #define history_def_setunique(p, uni) \ if (uni) \ (((history_t *)p)->flags) |= H_UNIQUE; \ else \ (((history_t *)p)->flags) &= ~H_UNIQUE #define he_strerror(code) he_errlist[code] #define he_seterrev(evp, code) {\ evp->num = code;\ evp->str = he_strerror(code);\ } /* error messages */ static const Char *const he_errlist[] = { STR("OK"), STR("unknown error"), STR("malloc() failed"), STR("first event not found"), STR("last event not found"), STR("empty list"), STR("no next event"), STR("no previous event"), STR("current event is invalid"), STR("event not found"), STR("can't read history from file"), STR("can't write history"), STR("required parameter(s) not supplied"), STR("history size negative"), STR("function not allowed with other history-functions-set the default"), STR("bad parameters") }; /* error codes */ #define _HE_OK 0 #define _HE_UNKNOWN 1 #define _HE_MALLOC_FAILED 2 #define _HE_FIRST_NOTFOUND 3 #define _HE_LAST_NOTFOUND 4 #define _HE_EMPTY_LIST 5 #define _HE_END_REACHED 6 #define _HE_START_REACHED 7 #define _HE_CURR_INVALID 8 #define _HE_NOT_FOUND 9 #define _HE_HIST_READ 10 #define _HE_HIST_WRITE 11 #define _HE_PARAM_MISSING 12 #define _HE_SIZE_NEGATIVE 13 #define _HE_NOT_ALLOWED 14 #define _HE_BAD_PARAM 15 /* history_def_first(): * Default function to return the first event in the history. */ static int history_def_first(void *p, TYPE(HistEvent) *ev) { history_t *h = (history_t *) p; h->cursor = h->list.next; if (h->cursor != &h->list) *ev = h->cursor->ev; else { he_seterrev(ev, _HE_FIRST_NOTFOUND); return -1; } return 0; } /* history_def_last(): * Default function to return the last event in the history. */ static int history_def_last(void *p, TYPE(HistEvent) *ev) { history_t *h = (history_t *) p; h->cursor = h->list.prev; if (h->cursor != &h->list) *ev = h->cursor->ev; else { he_seterrev(ev, _HE_LAST_NOTFOUND); return -1; } return 0; } /* history_def_next(): * Default function to return the next event in the history. */ static int history_def_next(void *p, TYPE(HistEvent) *ev) { history_t *h = (history_t *) p; if (h->cursor == &h->list) { he_seterrev(ev, _HE_EMPTY_LIST); return -1; } if (h->cursor->next == &h->list) { he_seterrev(ev, _HE_END_REACHED); return -1; } h->cursor = h->cursor->next; *ev = h->cursor->ev; return 0; } /* history_def_prev(): * Default function to return the previous event in the history. */ static int history_def_prev(void *p, TYPE(HistEvent) *ev) { history_t *h = (history_t *) p; if (h->cursor == &h->list) { he_seterrev(ev, (h->cur > 0) ? _HE_END_REACHED : _HE_EMPTY_LIST); return -1; } if (h->cursor->prev == &h->list) { he_seterrev(ev, _HE_START_REACHED); return -1; } h->cursor = h->cursor->prev; *ev = h->cursor->ev; return 0; } /* history_def_curr(): * Default function to return the current event in the history. */ static int history_def_curr(void *p, TYPE(HistEvent) *ev) { history_t *h = (history_t *) p; if (h->cursor != &h->list) *ev = h->cursor->ev; else { he_seterrev(ev, (h->cur > 0) ? _HE_CURR_INVALID : _HE_EMPTY_LIST); return -1; } return 0; } /* history_def_set(): * Default function to set the current event in the history to the * given one. */ static int history_def_set(void *p, TYPE(HistEvent) *ev, const int n) { history_t *h = (history_t *) p; if (h->cur == 0) { he_seterrev(ev, _HE_EMPTY_LIST); return -1; } if (h->cursor == &h->list || h->cursor->ev.num != n) { for (h->cursor = h->list.next; h->cursor != &h->list; h->cursor = h->cursor->next) if (h->cursor->ev.num == n) break; } if (h->cursor == &h->list) { he_seterrev(ev, _HE_NOT_FOUND); return -1; } return 0; } /* history_set_nth(): * Default function to set the current event in the history to the * n-th one. */ static int history_set_nth(void *p, TYPE(HistEvent) *ev, int n) { history_t *h = (history_t *) p; if (h->cur == 0) { he_seterrev(ev, _HE_EMPTY_LIST); return -1; } for (h->cursor = h->list.prev; h->cursor != &h->list; h->cursor = h->cursor->prev) if (n-- <= 0) break; if (h->cursor == &h->list) { he_seterrev(ev, _HE_NOT_FOUND); return -1; } return 0; } /* history_def_add(): * Append string to element */ static int history_def_add(void *p, TYPE(HistEvent) *ev, const Char *str) { history_t *h = (history_t *) p; size_t len; Char *s; HistEventPrivate *evp = (void *)&h->cursor->ev; if (h->cursor == &h->list) return history_def_enter(p, ev, str); len = Strlen(evp->str) + Strlen(str) + 1; s = h_malloc(len * sizeof(*s)); if (s == NULL) { he_seterrev(ev, _HE_MALLOC_FAILED); return -1; } (void) Strncpy(s, h->cursor->ev.str, len); s[len - 1] = '\0'; (void) Strncat(s, str, len - Strlen(s) - 1); h_free(evp->str); evp->str = s; *ev = h->cursor->ev; return 0; } static int history_deldata_nth(history_t *h, TYPE(HistEvent) *ev, int num, void **data) { if (history_set_nth(h, ev, num) != 0) return -1; /* magic value to skip delete (just set to n-th history) */ if (data == (void **)-1) return 0; ev->str = Strdup(h->cursor->ev.str); ev->num = h->cursor->ev.num; if (data) *data = h->cursor->data; history_def_delete(h, ev, h->cursor); return 0; } /* history_def_del(): * Delete element hp of the h list */ /* ARGSUSED */ static int history_def_del(void *p, TYPE(HistEvent) *ev __attribute__((__unused__)), const int num) { history_t *h = (history_t *) p; if (history_def_set(h, ev, num) != 0) return -1; ev->str = Strdup(h->cursor->ev.str); ev->num = h->cursor->ev.num; history_def_delete(h, ev, h->cursor); return 0; } /* history_def_delete(): * Delete element hp of the h list */ /* ARGSUSED */ static void history_def_delete(history_t *h, TYPE(HistEvent) *ev __attribute__((__unused__)), hentry_t *hp) { HistEventPrivate *evp = (void *)&hp->ev; if (hp == &h->list) abort(); if (h->cursor == hp) { h->cursor = hp->prev; if (h->cursor == &h->list) h->cursor = hp->next; } hp->prev->next = hp->next; hp->next->prev = hp->prev; h_free(evp->str); h_free(hp); h->cur--; } /* history_def_insert(): * Insert element with string str in the h list */ static int history_def_insert(history_t *h, TYPE(HistEvent) *ev, const Char *str) { hentry_t *c; c = h_malloc(sizeof(*c)); if (c == NULL) goto oomem; if ((c->ev.str = h_strdup(str)) == NULL) { h_free(c); goto oomem; } c->data = NULL; c->ev.num = ++h->eventid; c->next = h->list.next; c->prev = &h->list; h->list.next->prev = c; h->list.next = c; h->cur++; h->cursor = c; *ev = c->ev; return 0; oomem: he_seterrev(ev, _HE_MALLOC_FAILED); return -1; } /* history_def_enter(): * Default function to enter an item in the history */ static int history_def_enter(void *p, TYPE(HistEvent) *ev, const Char *str) { history_t *h = (history_t *) p; if ((h->flags & H_UNIQUE) != 0 && h->list.next != &h->list && Strcmp(h->list.next->ev.str, str) == 0) return 0; if (history_def_insert(h, ev, str) == -1) return -1; /* error, keep error message */ /* * Always keep at least one entry. * This way we don't have to check for the empty list. */ while (h->cur > h->max && h->cur > 0) history_def_delete(h, ev, h->list.prev); return 1; } /* history_def_init(): * Default history initialization function */ /* ARGSUSED */ static int history_def_init(void **p, TYPE(HistEvent) *ev __attribute__((__unused__)), int n) { history_t *h = (history_t *) h_malloc(sizeof(*h)); if (h == NULL) return -1; if (n <= 0) n = 0; h->eventid = 0; h->cur = 0; h->max = n; h->list.next = h->list.prev = &h->list; h->list.ev.str = NULL; h->list.ev.num = 0; h->cursor = &h->list; h->flags = 0; *p = h; return 0; } /* history_def_clear(): * Default history cleanup function */ static void history_def_clear(void *p, TYPE(HistEvent) *ev) { history_t *h = (history_t *) p; while (h->list.prev != &h->list) history_def_delete(h, ev, h->list.prev); h->cursor = &h->list; h->eventid = 0; h->cur = 0; } /************************************************************************/ /* history_init(): * Initialization function. */ TYPE(History) * FUN(history,init)(void) { TYPE(HistEvent) ev; TYPE(History) *h = (TYPE(History) *) h_malloc(sizeof(*h)); if (h == NULL) return NULL; if (history_def_init(&h->h_ref, &ev, 0) == -1) { h_free(h); return NULL; } h->h_ent = -1; h->h_next = history_def_next; h->h_first = history_def_first; h->h_last = history_def_last; h->h_prev = history_def_prev; h->h_curr = history_def_curr; h->h_set = history_def_set; h->h_clear = history_def_clear; h->h_enter = history_def_enter; h->h_add = history_def_add; h->h_del = history_def_del; return h; } /* history_end(): * clean up history; */ void FUN(history,end)(TYPE(History) *h) { TYPE(HistEvent) ev; if (h->h_next == history_def_next) history_def_clear(h->h_ref, &ev); h_free(h->h_ref); h_free(h); } /* history_setsize(): * Set history number of events */ static int history_setsize(TYPE(History) *h, TYPE(HistEvent) *ev, int num) { if (h->h_next != history_def_next) { he_seterrev(ev, _HE_NOT_ALLOWED); return -1; } if (num < 0) { he_seterrev(ev, _HE_BAD_PARAM); return -1; } history_def_setsize(h->h_ref, num); return 0; } /* history_getsize(): * Get number of events currently in history */ static int history_getsize(TYPE(History) *h, TYPE(HistEvent) *ev) { if (h->h_next != history_def_next) { he_seterrev(ev, _HE_NOT_ALLOWED); return -1; } ev->num = history_def_getsize(h->h_ref); if (ev->num < -1) { he_seterrev(ev, _HE_SIZE_NEGATIVE); return -1; } return 0; } /* history_setunique(): * Set if adjacent equal events should not be entered in history. */ static int history_setunique(TYPE(History) *h, TYPE(HistEvent) *ev, int uni) { if (h->h_next != history_def_next) { he_seterrev(ev, _HE_NOT_ALLOWED); return -1; } history_def_setunique(h->h_ref, uni); return 0; } /* history_getunique(): * Get if adjacent equal events should not be entered in history. */ static int history_getunique(TYPE(History) *h, TYPE(HistEvent) *ev) { if (h->h_next != history_def_next) { he_seterrev(ev, _HE_NOT_ALLOWED); return -1; } ev->num = history_def_getunique(h->h_ref); return 0; } /* history_set_fun(): * Set history functions */ static int history_set_fun(TYPE(History) *h, TYPE(History) *nh) { TYPE(HistEvent) ev; if (nh->h_first == NULL || nh->h_next == NULL || nh->h_last == NULL || nh->h_prev == NULL || nh->h_curr == NULL || nh->h_set == NULL || nh->h_enter == NULL || nh->h_add == NULL || nh->h_clear == NULL || nh->h_del == NULL || nh->h_ref == NULL) { if (h->h_next != history_def_next) { if (history_def_init(&h->h_ref, &ev, 0) == -1) return -1; h->h_first = history_def_first; h->h_next = history_def_next; h->h_last = history_def_last; h->h_prev = history_def_prev; h->h_curr = history_def_curr; h->h_set = history_def_set; h->h_clear = history_def_clear; h->h_enter = history_def_enter; h->h_add = history_def_add; h->h_del = history_def_del; } return -1; } if (h->h_next == history_def_next) history_def_clear(h->h_ref, &ev); h->h_ent = -1; h->h_first = nh->h_first; h->h_next = nh->h_next; h->h_last = nh->h_last; h->h_prev = nh->h_prev; h->h_curr = nh->h_curr; h->h_set = nh->h_set; h->h_clear = nh->h_clear; h->h_enter = nh->h_enter; h->h_add = nh->h_add; h->h_del = nh->h_del; return 0; } /* history_load(): * TYPE(History) load function */ static int history_load(TYPE(History) *h, const char *fname) { FILE *fp; char *line; size_t llen; ssize_t sz; size_t max_size; char *ptr; int i = -1; TYPE(HistEvent) ev; #ifndef NARROWCHAR static ct_buffer_t conv; #endif if ((fp = fopen(fname, "r")) == NULL) return i; line = NULL; llen = 0; if ((sz = getline(&line, &llen, fp)) == -1) goto done; if (strncmp(line, hist_cookie, (size_t)sz) != 0) goto done; ptr = h_malloc((max_size = 1024) * sizeof(*ptr)); if (ptr == NULL) goto done; for (i = 0; (sz = getline(&line, &llen, fp)) != -1; i++) { if (sz > 0 && line[sz - 1] == '\n') line[--sz] = '\0'; if (max_size < (size_t)sz) { char *nptr; max_size = ((size_t)sz + 1024) & (size_t)~1023; nptr = h_realloc(ptr, max_size * sizeof(*ptr)); if (nptr == NULL) { i = -1; goto oomem; } ptr = nptr; } (void) strunvis(ptr, line); if (HENTER(h, &ev, ct_decode_string(ptr, &conv)) == -1) { i = -1; goto oomem; } } oomem: h_free(ptr); done: free(line); (void) fclose(fp); return i; } /* history_save_fp(): * TYPE(History) save function */ static int history_save_fp(TYPE(History) *h, FILE *fp) { TYPE(HistEvent) ev; int i = -1, retval; size_t len, max_size; char *ptr; const char *str; #ifndef NARROWCHAR static ct_buffer_t conv; #endif if (fchmod(fileno(fp), S_IRUSR|S_IWUSR) == -1) goto done; if (fputs(hist_cookie, fp) == EOF) goto done; ptr = h_malloc((max_size = 1024) * sizeof(*ptr)); if (ptr == NULL) goto done; for (i = 0, retval = HLAST(h, &ev); retval != -1; retval = HPREV(h, &ev), i++) { str = ct_encode_string(ev.str, &conv); len = strlen(str) * 4 + 1; if (len > max_size) { char *nptr; max_size = (len + 1024) & (size_t)~1023; nptr = h_realloc(ptr, max_size * sizeof(*ptr)); if (nptr == NULL) { i = -1; goto oomem; } ptr = nptr; } (void) strvis(ptr, str, VIS_WHITE); (void) fprintf(fp, "%s\n", ptr); } oomem: h_free(ptr); done: return i; } /* history_save(): * History save function */ static int history_save(TYPE(History) *h, const char *fname) { FILE *fp; int i; if ((fp = fopen(fname, "w")) == NULL) return -1; i = history_save_fp(h, fp); (void) fclose(fp); return i; } /* history_prev_event(): * Find the previous event, with number given */ static int history_prev_event(TYPE(History) *h, TYPE(HistEvent) *ev, int num) { int retval; for (retval = HCURR(h, ev); retval != -1; retval = HPREV(h, ev)) if (ev->num == num) return 0; he_seterrev(ev, _HE_NOT_FOUND); return -1; } static int history_next_evdata(TYPE(History) *h, TYPE(HistEvent) *ev, int num, void **d) { int retval; for (retval = HCURR(h, ev); retval != -1; retval = HPREV(h, ev)) if (ev->num == num) { if (d) *d = ((history_t *)h->h_ref)->cursor->data; return 0; } he_seterrev(ev, _HE_NOT_FOUND); return -1; } /* history_next_event(): * Find the next event, with number given */ static int history_next_event(TYPE(History) *h, TYPE(HistEvent) *ev, int num) { int retval; for (retval = HCURR(h, ev); retval != -1; retval = HNEXT(h, ev)) if (ev->num == num) return 0; he_seterrev(ev, _HE_NOT_FOUND); return -1; } /* history_prev_string(): * Find the previous event beginning with string */ static int history_prev_string(TYPE(History) *h, TYPE(HistEvent) *ev, const Char *str) { size_t len = Strlen(str); int retval; for (retval = HCURR(h, ev); retval != -1; retval = HNEXT(h, ev)) if (Strncmp(str, ev->str, len) == 0) return 0; he_seterrev(ev, _HE_NOT_FOUND); return -1; } /* history_next_string(): * Find the next event beginning with string */ static int history_next_string(TYPE(History) *h, TYPE(HistEvent) *ev, const Char *str) { size_t len = Strlen(str); int retval; for (retval = HCURR(h, ev); retval != -1; retval = HPREV(h, ev)) if (Strncmp(str, ev->str, len) == 0) return 0; he_seterrev(ev, _HE_NOT_FOUND); return -1; } /* history(): * User interface to history functions. */ int FUNW(history)(TYPE(History) *h, TYPE(HistEvent) *ev, int fun, ...) { va_list va; const Char *str; int retval; va_start(va, fun); he_seterrev(ev, _HE_OK); switch (fun) { case H_GETSIZE: retval = history_getsize(h, ev); break; case H_SETSIZE: retval = history_setsize(h, ev, va_arg(va, int)); break; case H_GETUNIQUE: retval = history_getunique(h, ev); break; case H_SETUNIQUE: retval = history_setunique(h, ev, va_arg(va, int)); break; case H_ADD: str = va_arg(va, const Char *); retval = HADD(h, ev, str); break; case H_DEL: retval = HDEL(h, ev, va_arg(va, const int)); break; case H_ENTER: str = va_arg(va, const Char *); if ((retval = HENTER(h, ev, str)) != -1) h->h_ent = ev->num; break; case H_APPEND: str = va_arg(va, const Char *); if ((retval = HSET(h, ev, h->h_ent)) != -1) retval = HADD(h, ev, str); break; case H_FIRST: retval = HFIRST(h, ev); break; case H_NEXT: retval = HNEXT(h, ev); break; case H_LAST: retval = HLAST(h, ev); break; case H_PREV: retval = HPREV(h, ev); break; case H_CURR: retval = HCURR(h, ev); break; case H_SET: retval = HSET(h, ev, va_arg(va, const int)); break; case H_CLEAR: HCLEAR(h, ev); retval = 0; break; case H_LOAD: retval = history_load(h, va_arg(va, const char *)); if (retval == -1) he_seterrev(ev, _HE_HIST_READ); break; case H_SAVE: retval = history_save(h, va_arg(va, const char *)); if (retval == -1) he_seterrev(ev, _HE_HIST_WRITE); break; case H_SAVE_FP: retval = history_save_fp(h, va_arg(va, FILE *)); if (retval == -1) he_seterrev(ev, _HE_HIST_WRITE); break; case H_PREV_EVENT: retval = history_prev_event(h, ev, va_arg(va, int)); break; case H_NEXT_EVENT: retval = history_next_event(h, ev, va_arg(va, int)); break; case H_PREV_STR: retval = history_prev_string(h, ev, va_arg(va, const Char *)); break; case H_NEXT_STR: retval = history_next_string(h, ev, va_arg(va, const Char *)); break; case H_FUNC: { TYPE(History) hf; hf.h_ref = va_arg(va, void *); h->h_ent = -1; hf.h_first = va_arg(va, history_gfun_t); hf.h_next = va_arg(va, history_gfun_t); hf.h_last = va_arg(va, history_gfun_t); hf.h_prev = va_arg(va, history_gfun_t); hf.h_curr = va_arg(va, history_gfun_t); hf.h_set = va_arg(va, history_sfun_t); hf.h_clear = va_arg(va, history_vfun_t); hf.h_enter = va_arg(va, history_efun_t); hf.h_add = va_arg(va, history_efun_t); hf.h_del = va_arg(va, history_sfun_t); if ((retval = history_set_fun(h, &hf)) == -1) he_seterrev(ev, _HE_PARAM_MISSING); break; } case H_END: FUN(history,end)(h); retval = 0; break; case H_NEXT_EVDATA: { int num = va_arg(va, int); void **d = va_arg(va, void **); retval = history_next_evdata(h, ev, num, d); break; } case H_DELDATA: { int num = va_arg(va, int); void **d = va_arg(va, void **); retval = history_deldata_nth((history_t *)h->h_ref, ev, num, d); break; } case H_REPLACE: /* only use after H_NEXT_EVDATA */ { const Char *line = va_arg(va, const Char *); void *d = va_arg(va, void *); const Char *s; if(!line || !(s = Strdup(line))) { retval = -1; break; } ((history_t *)h->h_ref)->cursor->ev.str = s; ((history_t *)h->h_ref)->cursor->data = d; retval = 0; break; } default: retval = -1; he_seterrev(ev, _HE_UNKNOWN); break; } va_end(va); return retval; } heimdal-7.5.0/lib/libedit/src/sig.c0000644000175000017500000001215713026237312015156 0ustar niknik/* $NetBSD: sig.c,v 1.26 2016/05/09 21:46:56 christos Exp $ */ /*- * Copyright (c) 1992, 1993 * The Regents of the University of California. All rights reserved. * * This code is derived from software contributed to Berkeley by * Christos Zoulas of Cornell University. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the University nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "config.h" #if !defined(lint) && !defined(SCCSID) #if 0 static char sccsid[] = "@(#)sig.c 8.1 (Berkeley) 6/4/93"; #else __RCSID("$NetBSD: sig.c,v 1.26 2016/05/09 21:46:56 christos Exp $"); #endif #endif /* not lint && not SCCSID */ /* * sig.c: Signal handling stuff. * our policy is to trap all signals, set a good state * and pass the ball to our caller. */ #include #include #include "el.h" #include "common.h" static EditLine *sel = NULL; static const int sighdl[] = { #define _DO(a) (a), ALLSIGS #undef _DO - 1 }; static void sig_handler(int); /* sig_handler(): * This is the handler called for all signals * XXX: we cannot pass any data so we just store the old editline * state in a private variable */ static void sig_handler(int signo) { int i, save_errno; sigset_t nset, oset; save_errno = errno; (void) sigemptyset(&nset); (void) sigaddset(&nset, signo); (void) sigprocmask(SIG_BLOCK, &nset, &oset); sel->el_signal->sig_no = signo; switch (signo) { case SIGCONT: tty_rawmode(sel); if (ed_redisplay(sel, 0) == CC_REFRESH) re_refresh(sel); terminal__flush(sel); break; case SIGWINCH: el_resize(sel); break; default: tty_cookedmode(sel); break; } for (i = 0; sighdl[i] != -1; i++) if (signo == sighdl[i]) break; (void) sigaction(signo, &sel->el_signal->sig_action[i], NULL); sel->el_signal->sig_action[i].sa_handler = SIG_ERR; sel->el_signal->sig_action[i].sa_flags = 0; sigemptyset(&sel->el_signal->sig_action[i].sa_mask); (void) sigprocmask(SIG_SETMASK, &oset, NULL); (void) kill(0, signo); errno = save_errno; } /* sig_init(): * Initialize all signal stuff */ libedit_private int sig_init(EditLine *el) { size_t i; sigset_t *nset, oset; el->el_signal = el_malloc(sizeof(*el->el_signal)); if (el->el_signal == NULL) return -1; nset = &el->el_signal->sig_set; (void) sigemptyset(nset); #define _DO(a) (void) sigaddset(nset, a); ALLSIGS #undef _DO (void) sigprocmask(SIG_BLOCK, nset, &oset); for (i = 0; sighdl[i] != -1; i++) { el->el_signal->sig_action[i].sa_handler = SIG_ERR; el->el_signal->sig_action[i].sa_flags = 0; sigemptyset(&el->el_signal->sig_action[i].sa_mask); } (void) sigprocmask(SIG_SETMASK, &oset, NULL); return 0; } /* sig_end(): * Clear all signal stuff */ libedit_private void sig_end(EditLine *el) { el_free(el->el_signal); el->el_signal = NULL; } /* sig_set(): * set all the signal handlers */ libedit_private void sig_set(EditLine *el) { size_t i; sigset_t oset; struct sigaction osa, nsa; nsa.sa_handler = sig_handler; nsa.sa_flags = 0; sigemptyset(&nsa.sa_mask); (void) sigprocmask(SIG_BLOCK, &el->el_signal->sig_set, &oset); for (i = 0; sighdl[i] != -1; i++) { /* This could happen if we get interrupted */ if (sigaction(sighdl[i], &nsa, &osa) != -1 && osa.sa_handler != sig_handler) el->el_signal->sig_action[i] = osa; } sel = el; (void) sigprocmask(SIG_SETMASK, &oset, NULL); } /* sig_clr(): * clear all the signal handlers */ libedit_private void sig_clr(EditLine *el) { size_t i; sigset_t oset; (void) sigprocmask(SIG_BLOCK, &el->el_signal->sig_set, &oset); for (i = 0; sighdl[i] != -1; i++) if (el->el_signal->sig_action[i].sa_handler != SIG_ERR) (void)sigaction(sighdl[i], &el->el_signal->sig_action[i], NULL); sel = NULL; /* we are going to die if the handler is * called */ (void)sigprocmask(SIG_SETMASK, &oset, NULL); } heimdal-7.5.0/lib/libedit/aclocal.m40000644000175000017500000132727013212444503015306 0ustar niknik# generated automatically by aclocal 1.15.1 -*- Autoconf -*- # Copyright (C) 1996-2017 Free Software Foundation, Inc. # This file is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, # with or without modifications, as long as this notice is preserved. # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY, to the extent permitted by law; without # even the implied warranty of MERCHANTABILITY or FITNESS FOR A # PARTICULAR PURPOSE. m4_ifndef([AC_CONFIG_MACRO_DIRS], [m4_defun([_AM_CONFIG_MACRO_DIRS], [])m4_defun([AC_CONFIG_MACRO_DIRS], [_AM_CONFIG_MACRO_DIRS($@)])]) m4_ifndef([AC_AUTOCONF_VERSION], [m4_copy([m4_PACKAGE_VERSION], [AC_AUTOCONF_VERSION])])dnl m4_if(m4_defn([AC_AUTOCONF_VERSION]), [2.69],, [m4_warning([this file was generated for autoconf 2.69. You have another version of autoconf. It may work, but is not guaranteed to. If you have problems, you may need to regenerate the build system entirely. To do so, use the procedure documented by the package, typically 'autoreconf'.])]) # libtool.m4 - Configure libtool for the host system. -*-Autoconf-*- # # Copyright (C) 1996-2001, 2003-2015 Free Software Foundation, Inc. # Written by Gordon Matzigkeit, 1996 # # This file is free software; the Free Software Foundation gives # unlimited permission to copy and/or distribute it, with or without # modifications, as long as this notice is preserved. m4_define([_LT_COPYING], [dnl # Copyright (C) 2014 Free Software Foundation, Inc. # This is free software; see the source for copying conditions. There is NO # warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. # GNU Libtool is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of of the License, or # (at your option) any later version. # # As a special exception to the GNU General Public License, if you # distribute this file as part of a program or library that is built # using GNU Libtool, you may include this file under the same # distribution terms that you use for the rest of that program. # # GNU Libtool is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see . ]) # serial 58 LT_INIT # LT_PREREQ(VERSION) # ------------------ # Complain and exit if this libtool version is less that VERSION. m4_defun([LT_PREREQ], [m4_if(m4_version_compare(m4_defn([LT_PACKAGE_VERSION]), [$1]), -1, [m4_default([$3], [m4_fatal([Libtool version $1 or higher is required], 63)])], [$2])]) # _LT_CHECK_BUILDDIR # ------------------ # Complain if the absolute build directory name contains unusual characters m4_defun([_LT_CHECK_BUILDDIR], [case `pwd` in *\ * | *\ *) AC_MSG_WARN([Libtool does not cope well with whitespace in `pwd`]) ;; esac ]) # LT_INIT([OPTIONS]) # ------------------ AC_DEFUN([LT_INIT], [AC_PREREQ([2.62])dnl We use AC_PATH_PROGS_FEATURE_CHECK AC_REQUIRE([AC_CONFIG_AUX_DIR_DEFAULT])dnl AC_BEFORE([$0], [LT_LANG])dnl AC_BEFORE([$0], [LT_OUTPUT])dnl AC_BEFORE([$0], [LTDL_INIT])dnl m4_require([_LT_CHECK_BUILDDIR])dnl dnl Autoconf doesn't catch unexpanded LT_ macros by default: m4_pattern_forbid([^_?LT_[A-Z_]+$])dnl m4_pattern_allow([^(_LT_EOF|LT_DLGLOBAL|LT_DLLAZY_OR_NOW|LT_MULTI_MODULE)$])dnl dnl aclocal doesn't pull ltoptions.m4, ltsugar.m4, or ltversion.m4 dnl unless we require an AC_DEFUNed macro: AC_REQUIRE([LTOPTIONS_VERSION])dnl AC_REQUIRE([LTSUGAR_VERSION])dnl AC_REQUIRE([LTVERSION_VERSION])dnl AC_REQUIRE([LTOBSOLETE_VERSION])dnl m4_require([_LT_PROG_LTMAIN])dnl _LT_SHELL_INIT([SHELL=${CONFIG_SHELL-/bin/sh}]) dnl Parse OPTIONS _LT_SET_OPTIONS([$0], [$1]) # This can be used to rebuild libtool when needed LIBTOOL_DEPS=$ltmain # Always use our own libtool. LIBTOOL='$(SHELL) $(top_builddir)/libtool' AC_SUBST(LIBTOOL)dnl _LT_SETUP # Only expand once: m4_define([LT_INIT]) ])# LT_INIT # Old names: AU_ALIAS([AC_PROG_LIBTOOL], [LT_INIT]) AU_ALIAS([AM_PROG_LIBTOOL], [LT_INIT]) dnl aclocal-1.4 backwards compatibility: dnl AC_DEFUN([AC_PROG_LIBTOOL], []) dnl AC_DEFUN([AM_PROG_LIBTOOL], []) # _LT_PREPARE_CC_BASENAME # ----------------------- m4_defun([_LT_PREPARE_CC_BASENAME], [ # Calculate cc_basename. Skip known compiler wrappers and cross-prefix. func_cc_basename () { for cc_temp in @S|@*""; do case $cc_temp in compile | *[[\\/]]compile | ccache | *[[\\/]]ccache ) ;; distcc | *[[\\/]]distcc | purify | *[[\\/]]purify ) ;; \-*) ;; *) break;; esac done func_cc_basename_result=`$ECHO "$cc_temp" | $SED "s%.*/%%; s%^$host_alias-%%"` } ])# _LT_PREPARE_CC_BASENAME # _LT_CC_BASENAME(CC) # ------------------- # It would be clearer to call AC_REQUIREs from _LT_PREPARE_CC_BASENAME, # but that macro is also expanded into generated libtool script, which # arranges for $SED and $ECHO to be set by different means. m4_defun([_LT_CC_BASENAME], [m4_require([_LT_PREPARE_CC_BASENAME])dnl AC_REQUIRE([_LT_DECL_SED])dnl AC_REQUIRE([_LT_PROG_ECHO_BACKSLASH])dnl func_cc_basename $1 cc_basename=$func_cc_basename_result ]) # _LT_FILEUTILS_DEFAULTS # ---------------------- # It is okay to use these file commands and assume they have been set # sensibly after 'm4_require([_LT_FILEUTILS_DEFAULTS])'. m4_defun([_LT_FILEUTILS_DEFAULTS], [: ${CP="cp -f"} : ${MV="mv -f"} : ${RM="rm -f"} ])# _LT_FILEUTILS_DEFAULTS # _LT_SETUP # --------- m4_defun([_LT_SETUP], [AC_REQUIRE([AC_CANONICAL_HOST])dnl AC_REQUIRE([AC_CANONICAL_BUILD])dnl AC_REQUIRE([_LT_PREPARE_SED_QUOTE_VARS])dnl AC_REQUIRE([_LT_PROG_ECHO_BACKSLASH])dnl _LT_DECL([], [PATH_SEPARATOR], [1], [The PATH separator for the build system])dnl dnl _LT_DECL([], [host_alias], [0], [The host system])dnl _LT_DECL([], [host], [0])dnl _LT_DECL([], [host_os], [0])dnl dnl _LT_DECL([], [build_alias], [0], [The build system])dnl _LT_DECL([], [build], [0])dnl _LT_DECL([], [build_os], [0])dnl dnl AC_REQUIRE([AC_PROG_CC])dnl AC_REQUIRE([LT_PATH_LD])dnl AC_REQUIRE([LT_PATH_NM])dnl dnl AC_REQUIRE([AC_PROG_LN_S])dnl test -z "$LN_S" && LN_S="ln -s" _LT_DECL([], [LN_S], [1], [Whether we need soft or hard links])dnl dnl AC_REQUIRE([LT_CMD_MAX_LEN])dnl _LT_DECL([objext], [ac_objext], [0], [Object file suffix (normally "o")])dnl _LT_DECL([], [exeext], [0], [Executable file suffix (normally "")])dnl dnl m4_require([_LT_FILEUTILS_DEFAULTS])dnl m4_require([_LT_CHECK_SHELL_FEATURES])dnl m4_require([_LT_PATH_CONVERSION_FUNCTIONS])dnl m4_require([_LT_CMD_RELOAD])dnl m4_require([_LT_CHECK_MAGIC_METHOD])dnl m4_require([_LT_CHECK_SHAREDLIB_FROM_LINKLIB])dnl m4_require([_LT_CMD_OLD_ARCHIVE])dnl m4_require([_LT_CMD_GLOBAL_SYMBOLS])dnl m4_require([_LT_WITH_SYSROOT])dnl m4_require([_LT_CMD_TRUNCATE])dnl _LT_CONFIG_LIBTOOL_INIT([ # See if we are running on zsh, and set the options that allow our # commands through without removal of \ escapes INIT. if test -n "\${ZSH_VERSION+set}"; then setopt NO_GLOB_SUBST fi ]) if test -n "${ZSH_VERSION+set}"; then setopt NO_GLOB_SUBST fi _LT_CHECK_OBJDIR m4_require([_LT_TAG_COMPILER])dnl case $host_os in aix3*) # AIX sometimes has problems with the GCC collect2 program. For some # reason, if we set the COLLECT_NAMES environment variable, the problems # vanish in a puff of smoke. if test set != "${COLLECT_NAMES+set}"; then COLLECT_NAMES= export COLLECT_NAMES fi ;; esac # Global variables: ofile=libtool can_build_shared=yes # All known linkers require a '.a' archive for static linking (except MSVC, # which needs '.lib'). libext=a with_gnu_ld=$lt_cv_prog_gnu_ld old_CC=$CC old_CFLAGS=$CFLAGS # Set sane defaults for various variables test -z "$CC" && CC=cc test -z "$LTCC" && LTCC=$CC test -z "$LTCFLAGS" && LTCFLAGS=$CFLAGS test -z "$LD" && LD=ld test -z "$ac_objext" && ac_objext=o _LT_CC_BASENAME([$compiler]) # Only perform the check for file, if the check method requires it test -z "$MAGIC_CMD" && MAGIC_CMD=file case $deplibs_check_method in file_magic*) if test "$file_magic_cmd" = '$MAGIC_CMD'; then _LT_PATH_MAGIC fi ;; esac # Use C for the default configuration in the libtool script LT_SUPPORTED_TAG([CC]) _LT_LANG_C_CONFIG _LT_LANG_DEFAULT_CONFIG _LT_CONFIG_COMMANDS ])# _LT_SETUP # _LT_PREPARE_SED_QUOTE_VARS # -------------------------- # Define a few sed substitution that help us do robust quoting. m4_defun([_LT_PREPARE_SED_QUOTE_VARS], [# Backslashify metacharacters that are still active within # double-quoted strings. sed_quote_subst='s/\([["`$\\]]\)/\\\1/g' # Same as above, but do not quote variable references. double_quote_subst='s/\([["`\\]]\)/\\\1/g' # Sed substitution to delay expansion of an escaped shell variable in a # double_quote_subst'ed string. delay_variable_subst='s/\\\\\\\\\\\$/\\\\\\$/g' # Sed substitution to delay expansion of an escaped single quote. delay_single_quote_subst='s/'\''/'\'\\\\\\\'\''/g' # Sed substitution to avoid accidental globbing in evaled expressions no_glob_subst='s/\*/\\\*/g' ]) # _LT_PROG_LTMAIN # --------------- # Note that this code is called both from 'configure', and 'config.status' # now that we use AC_CONFIG_COMMANDS to generate libtool. Notably, # 'config.status' has no value for ac_aux_dir unless we are using Automake, # so we pass a copy along to make sure it has a sensible value anyway. m4_defun([_LT_PROG_LTMAIN], [m4_ifdef([AC_REQUIRE_AUX_FILE], [AC_REQUIRE_AUX_FILE([ltmain.sh])])dnl _LT_CONFIG_LIBTOOL_INIT([ac_aux_dir='$ac_aux_dir']) ltmain=$ac_aux_dir/ltmain.sh ])# _LT_PROG_LTMAIN # So that we can recreate a full libtool script including additional # tags, we accumulate the chunks of code to send to AC_CONFIG_COMMANDS # in macros and then make a single call at the end using the 'libtool' # label. # _LT_CONFIG_LIBTOOL_INIT([INIT-COMMANDS]) # ---------------------------------------- # Register INIT-COMMANDS to be passed to AC_CONFIG_COMMANDS later. m4_define([_LT_CONFIG_LIBTOOL_INIT], [m4_ifval([$1], [m4_append([_LT_OUTPUT_LIBTOOL_INIT], [$1 ])])]) # Initialize. m4_define([_LT_OUTPUT_LIBTOOL_INIT]) # _LT_CONFIG_LIBTOOL([COMMANDS]) # ------------------------------ # Register COMMANDS to be passed to AC_CONFIG_COMMANDS later. m4_define([_LT_CONFIG_LIBTOOL], [m4_ifval([$1], [m4_append([_LT_OUTPUT_LIBTOOL_COMMANDS], [$1 ])])]) # Initialize. m4_define([_LT_OUTPUT_LIBTOOL_COMMANDS]) # _LT_CONFIG_SAVE_COMMANDS([COMMANDS], [INIT_COMMANDS]) # ----------------------------------------------------- m4_defun([_LT_CONFIG_SAVE_COMMANDS], [_LT_CONFIG_LIBTOOL([$1]) _LT_CONFIG_LIBTOOL_INIT([$2]) ]) # _LT_FORMAT_COMMENT([COMMENT]) # ----------------------------- # Add leading comment marks to the start of each line, and a trailing # full-stop to the whole comment if one is not present already. m4_define([_LT_FORMAT_COMMENT], [m4_ifval([$1], [ m4_bpatsubst([m4_bpatsubst([$1], [^ *], [# ])], [['`$\]], [\\\&])]m4_bmatch([$1], [[!?.]$], [], [.]) )]) # _LT_DECL([CONFIGNAME], VARNAME, VALUE, [DESCRIPTION], [IS-TAGGED?]) # ------------------------------------------------------------------- # CONFIGNAME is the name given to the value in the libtool script. # VARNAME is the (base) name used in the configure script. # VALUE may be 0, 1 or 2 for a computed quote escaped value based on # VARNAME. Any other value will be used directly. m4_define([_LT_DECL], [lt_if_append_uniq([lt_decl_varnames], [$2], [, ], [lt_dict_add_subkey([lt_decl_dict], [$2], [libtool_name], [m4_ifval([$1], [$1], [$2])]) lt_dict_add_subkey([lt_decl_dict], [$2], [value], [$3]) m4_ifval([$4], [lt_dict_add_subkey([lt_decl_dict], [$2], [description], [$4])]) lt_dict_add_subkey([lt_decl_dict], [$2], [tagged?], [m4_ifval([$5], [yes], [no])])]) ]) # _LT_TAGDECL([CONFIGNAME], VARNAME, VALUE, [DESCRIPTION]) # -------------------------------------------------------- m4_define([_LT_TAGDECL], [_LT_DECL([$1], [$2], [$3], [$4], [yes])]) # lt_decl_tag_varnames([SEPARATOR], [VARNAME1...]) # ------------------------------------------------ m4_define([lt_decl_tag_varnames], [_lt_decl_filter([tagged?], [yes], $@)]) # _lt_decl_filter(SUBKEY, VALUE, [SEPARATOR], [VARNAME1..]) # --------------------------------------------------------- m4_define([_lt_decl_filter], [m4_case([$#], [0], [m4_fatal([$0: too few arguments: $#])], [1], [m4_fatal([$0: too few arguments: $#: $1])], [2], [lt_dict_filter([lt_decl_dict], [$1], [$2], [], lt_decl_varnames)], [3], [lt_dict_filter([lt_decl_dict], [$1], [$2], [$3], lt_decl_varnames)], [lt_dict_filter([lt_decl_dict], $@)])[]dnl ]) # lt_decl_quote_varnames([SEPARATOR], [VARNAME1...]) # -------------------------------------------------- m4_define([lt_decl_quote_varnames], [_lt_decl_filter([value], [1], $@)]) # lt_decl_dquote_varnames([SEPARATOR], [VARNAME1...]) # --------------------------------------------------- m4_define([lt_decl_dquote_varnames], [_lt_decl_filter([value], [2], $@)]) # lt_decl_varnames_tagged([SEPARATOR], [VARNAME1...]) # --------------------------------------------------- m4_define([lt_decl_varnames_tagged], [m4_assert([$# <= 2])dnl _$0(m4_quote(m4_default([$1], [[, ]])), m4_ifval([$2], [[$2]], [m4_dquote(lt_decl_tag_varnames)]), m4_split(m4_normalize(m4_quote(_LT_TAGS)), [ ]))]) m4_define([_lt_decl_varnames_tagged], [m4_ifval([$3], [lt_combine([$1], [$2], [_], $3)])]) # lt_decl_all_varnames([SEPARATOR], [VARNAME1...]) # ------------------------------------------------ m4_define([lt_decl_all_varnames], [_$0(m4_quote(m4_default([$1], [[, ]])), m4_if([$2], [], m4_quote(lt_decl_varnames), m4_quote(m4_shift($@))))[]dnl ]) m4_define([_lt_decl_all_varnames], [lt_join($@, lt_decl_varnames_tagged([$1], lt_decl_tag_varnames([[, ]], m4_shift($@))))dnl ]) # _LT_CONFIG_STATUS_DECLARE([VARNAME]) # ------------------------------------ # Quote a variable value, and forward it to 'config.status' so that its # declaration there will have the same value as in 'configure'. VARNAME # must have a single quote delimited value for this to work. m4_define([_LT_CONFIG_STATUS_DECLARE], [$1='`$ECHO "$][$1" | $SED "$delay_single_quote_subst"`']) # _LT_CONFIG_STATUS_DECLARATIONS # ------------------------------ # We delimit libtool config variables with single quotes, so when # we write them to config.status, we have to be sure to quote all # embedded single quotes properly. In configure, this macro expands # each variable declared with _LT_DECL (and _LT_TAGDECL) into: # # ='`$ECHO "$" | $SED "$delay_single_quote_subst"`' m4_defun([_LT_CONFIG_STATUS_DECLARATIONS], [m4_foreach([_lt_var], m4_quote(lt_decl_all_varnames), [m4_n([_LT_CONFIG_STATUS_DECLARE(_lt_var)])])]) # _LT_LIBTOOL_TAGS # ---------------- # Output comment and list of tags supported by the script m4_defun([_LT_LIBTOOL_TAGS], [_LT_FORMAT_COMMENT([The names of the tagged configurations supported by this script])dnl available_tags='_LT_TAGS'dnl ]) # _LT_LIBTOOL_DECLARE(VARNAME, [TAG]) # ----------------------------------- # Extract the dictionary values for VARNAME (optionally with TAG) and # expand to a commented shell variable setting: # # # Some comment about what VAR is for. # visible_name=$lt_internal_name m4_define([_LT_LIBTOOL_DECLARE], [_LT_FORMAT_COMMENT(m4_quote(lt_dict_fetch([lt_decl_dict], [$1], [description])))[]dnl m4_pushdef([_libtool_name], m4_quote(lt_dict_fetch([lt_decl_dict], [$1], [libtool_name])))[]dnl m4_case(m4_quote(lt_dict_fetch([lt_decl_dict], [$1], [value])), [0], [_libtool_name=[$]$1], [1], [_libtool_name=$lt_[]$1], [2], [_libtool_name=$lt_[]$1], [_libtool_name=lt_dict_fetch([lt_decl_dict], [$1], [value])])[]dnl m4_ifval([$2], [_$2])[]m4_popdef([_libtool_name])[]dnl ]) # _LT_LIBTOOL_CONFIG_VARS # ----------------------- # Produce commented declarations of non-tagged libtool config variables # suitable for insertion in the LIBTOOL CONFIG section of the 'libtool' # script. Tagged libtool config variables (even for the LIBTOOL CONFIG # section) are produced by _LT_LIBTOOL_TAG_VARS. m4_defun([_LT_LIBTOOL_CONFIG_VARS], [m4_foreach([_lt_var], m4_quote(_lt_decl_filter([tagged?], [no], [], lt_decl_varnames)), [m4_n([_LT_LIBTOOL_DECLARE(_lt_var)])])]) # _LT_LIBTOOL_TAG_VARS(TAG) # ------------------------- m4_define([_LT_LIBTOOL_TAG_VARS], [m4_foreach([_lt_var], m4_quote(lt_decl_tag_varnames), [m4_n([_LT_LIBTOOL_DECLARE(_lt_var, [$1])])])]) # _LT_TAGVAR(VARNAME, [TAGNAME]) # ------------------------------ m4_define([_LT_TAGVAR], [m4_ifval([$2], [$1_$2], [$1])]) # _LT_CONFIG_COMMANDS # ------------------- # Send accumulated output to $CONFIG_STATUS. Thanks to the lists of # variables for single and double quote escaping we saved from calls # to _LT_DECL, we can put quote escaped variables declarations # into 'config.status', and then the shell code to quote escape them in # for loops in 'config.status'. Finally, any additional code accumulated # from calls to _LT_CONFIG_LIBTOOL_INIT is expanded. m4_defun([_LT_CONFIG_COMMANDS], [AC_PROVIDE_IFELSE([LT_OUTPUT], dnl If the libtool generation code has been placed in $CONFIG_LT, dnl instead of duplicating it all over again into config.status, dnl then we will have config.status run $CONFIG_LT later, so it dnl needs to know what name is stored there: [AC_CONFIG_COMMANDS([libtool], [$SHELL $CONFIG_LT || AS_EXIT(1)], [CONFIG_LT='$CONFIG_LT'])], dnl If the libtool generation code is destined for config.status, dnl expand the accumulated commands and init code now: [AC_CONFIG_COMMANDS([libtool], [_LT_OUTPUT_LIBTOOL_COMMANDS], [_LT_OUTPUT_LIBTOOL_COMMANDS_INIT])]) ])#_LT_CONFIG_COMMANDS # Initialize. m4_define([_LT_OUTPUT_LIBTOOL_COMMANDS_INIT], [ # The HP-UX ksh and POSIX shell print the target directory to stdout # if CDPATH is set. (unset CDPATH) >/dev/null 2>&1 && unset CDPATH sed_quote_subst='$sed_quote_subst' double_quote_subst='$double_quote_subst' delay_variable_subst='$delay_variable_subst' _LT_CONFIG_STATUS_DECLARATIONS LTCC='$LTCC' LTCFLAGS='$LTCFLAGS' compiler='$compiler_DEFAULT' # A function that is used when there is no print builtin or printf. func_fallback_echo () { eval 'cat <<_LTECHO_EOF \$[]1 _LTECHO_EOF' } # Quote evaled strings. for var in lt_decl_all_varnames([[ \ ]], lt_decl_quote_varnames); do case \`eval \\\\\$ECHO \\\\""\\\\\$\$var"\\\\"\` in *[[\\\\\\\`\\"\\\$]]*) eval "lt_\$var=\\\\\\"\\\`\\\$ECHO \\"\\\$\$var\\" | \\\$SED \\"\\\$sed_quote_subst\\"\\\`\\\\\\"" ## exclude from sc_prohibit_nested_quotes ;; *) eval "lt_\$var=\\\\\\"\\\$\$var\\\\\\"" ;; esac done # Double-quote double-evaled strings. for var in lt_decl_all_varnames([[ \ ]], lt_decl_dquote_varnames); do case \`eval \\\\\$ECHO \\\\""\\\\\$\$var"\\\\"\` in *[[\\\\\\\`\\"\\\$]]*) eval "lt_\$var=\\\\\\"\\\`\\\$ECHO \\"\\\$\$var\\" | \\\$SED -e \\"\\\$double_quote_subst\\" -e \\"\\\$sed_quote_subst\\" -e \\"\\\$delay_variable_subst\\"\\\`\\\\\\"" ## exclude from sc_prohibit_nested_quotes ;; *) eval "lt_\$var=\\\\\\"\\\$\$var\\\\\\"" ;; esac done _LT_OUTPUT_LIBTOOL_INIT ]) # _LT_GENERATED_FILE_INIT(FILE, [COMMENT]) # ------------------------------------ # Generate a child script FILE with all initialization necessary to # reuse the environment learned by the parent script, and make the # file executable. If COMMENT is supplied, it is inserted after the # '#!' sequence but before initialization text begins. After this # macro, additional text can be appended to FILE to form the body of # the child script. The macro ends with non-zero status if the # file could not be fully written (such as if the disk is full). m4_ifdef([AS_INIT_GENERATED], [m4_defun([_LT_GENERATED_FILE_INIT],[AS_INIT_GENERATED($@)])], [m4_defun([_LT_GENERATED_FILE_INIT], [m4_require([AS_PREPARE])]dnl [m4_pushdef([AS_MESSAGE_LOG_FD])]dnl [lt_write_fail=0 cat >$1 <<_ASEOF || lt_write_fail=1 #! $SHELL # Generated by $as_me. $2 SHELL=\${CONFIG_SHELL-$SHELL} export SHELL _ASEOF cat >>$1 <<\_ASEOF || lt_write_fail=1 AS_SHELL_SANITIZE _AS_PREPARE exec AS_MESSAGE_FD>&1 _ASEOF test 0 = "$lt_write_fail" && chmod +x $1[]dnl m4_popdef([AS_MESSAGE_LOG_FD])])])# _LT_GENERATED_FILE_INIT # LT_OUTPUT # --------- # This macro allows early generation of the libtool script (before # AC_OUTPUT is called), incase it is used in configure for compilation # tests. AC_DEFUN([LT_OUTPUT], [: ${CONFIG_LT=./config.lt} AC_MSG_NOTICE([creating $CONFIG_LT]) _LT_GENERATED_FILE_INIT(["$CONFIG_LT"], [# Run this file to recreate a libtool stub with the current configuration.]) cat >>"$CONFIG_LT" <<\_LTEOF lt_cl_silent=false exec AS_MESSAGE_LOG_FD>>config.log { echo AS_BOX([Running $as_me.]) } >&AS_MESSAGE_LOG_FD lt_cl_help="\ '$as_me' creates a local libtool stub from the current configuration, for use in further configure time tests before the real libtool is generated. Usage: $[0] [[OPTIONS]] -h, --help print this help, then exit -V, --version print version number, then exit -q, --quiet do not print progress messages -d, --debug don't remove temporary files Report bugs to ." lt_cl_version="\ m4_ifset([AC_PACKAGE_NAME], [AC_PACKAGE_NAME ])config.lt[]dnl m4_ifset([AC_PACKAGE_VERSION], [ AC_PACKAGE_VERSION]) configured by $[0], generated by m4_PACKAGE_STRING. Copyright (C) 2011 Free Software Foundation, Inc. This config.lt script is free software; the Free Software Foundation gives unlimited permision to copy, distribute and modify it." while test 0 != $[#] do case $[1] in --version | --v* | -V ) echo "$lt_cl_version"; exit 0 ;; --help | --h* | -h ) echo "$lt_cl_help"; exit 0 ;; --debug | --d* | -d ) debug=: ;; --quiet | --q* | --silent | --s* | -q ) lt_cl_silent=: ;; -*) AC_MSG_ERROR([unrecognized option: $[1] Try '$[0] --help' for more information.]) ;; *) AC_MSG_ERROR([unrecognized argument: $[1] Try '$[0] --help' for more information.]) ;; esac shift done if $lt_cl_silent; then exec AS_MESSAGE_FD>/dev/null fi _LTEOF cat >>"$CONFIG_LT" <<_LTEOF _LT_OUTPUT_LIBTOOL_COMMANDS_INIT _LTEOF cat >>"$CONFIG_LT" <<\_LTEOF AC_MSG_NOTICE([creating $ofile]) _LT_OUTPUT_LIBTOOL_COMMANDS AS_EXIT(0) _LTEOF chmod +x "$CONFIG_LT" # configure is writing to config.log, but config.lt does its own redirection, # appending to config.log, which fails on DOS, as config.log is still kept # open by configure. Here we exec the FD to /dev/null, effectively closing # config.log, so it can be properly (re)opened and appended to by config.lt. lt_cl_success=: test yes = "$silent" && lt_config_lt_args="$lt_config_lt_args --quiet" exec AS_MESSAGE_LOG_FD>/dev/null $SHELL "$CONFIG_LT" $lt_config_lt_args || lt_cl_success=false exec AS_MESSAGE_LOG_FD>>config.log $lt_cl_success || AS_EXIT(1) ])# LT_OUTPUT # _LT_CONFIG(TAG) # --------------- # If TAG is the built-in tag, create an initial libtool script with a # default configuration from the untagged config vars. Otherwise add code # to config.status for appending the configuration named by TAG from the # matching tagged config vars. m4_defun([_LT_CONFIG], [m4_require([_LT_FILEUTILS_DEFAULTS])dnl _LT_CONFIG_SAVE_COMMANDS([ m4_define([_LT_TAG], m4_if([$1], [], [C], [$1]))dnl m4_if(_LT_TAG, [C], [ # See if we are running on zsh, and set the options that allow our # commands through without removal of \ escapes. if test -n "${ZSH_VERSION+set}"; then setopt NO_GLOB_SUBST fi cfgfile=${ofile}T trap "$RM \"$cfgfile\"; exit 1" 1 2 15 $RM "$cfgfile" cat <<_LT_EOF >> "$cfgfile" #! $SHELL # Generated automatically by $as_me ($PACKAGE) $VERSION # Libtool was configured on host `(hostname || uname -n) 2>/dev/null | sed 1q`: # NOTE: Changes made to this file will be lost: look at ltmain.sh. # Provide generalized library-building support services. # Written by Gordon Matzigkeit, 1996 _LT_COPYING _LT_LIBTOOL_TAGS # Configured defaults for sys_lib_dlsearch_path munging. : \${LT_SYS_LIBRARY_PATH="$configure_time_lt_sys_library_path"} # ### BEGIN LIBTOOL CONFIG _LT_LIBTOOL_CONFIG_VARS _LT_LIBTOOL_TAG_VARS # ### END LIBTOOL CONFIG _LT_EOF cat <<'_LT_EOF' >> "$cfgfile" # ### BEGIN FUNCTIONS SHARED WITH CONFIGURE _LT_PREPARE_MUNGE_PATH_LIST _LT_PREPARE_CC_BASENAME # ### END FUNCTIONS SHARED WITH CONFIGURE _LT_EOF case $host_os in aix3*) cat <<\_LT_EOF >> "$cfgfile" # AIX sometimes has problems with the GCC collect2 program. For some # reason, if we set the COLLECT_NAMES environment variable, the problems # vanish in a puff of smoke. if test set != "${COLLECT_NAMES+set}"; then COLLECT_NAMES= export COLLECT_NAMES fi _LT_EOF ;; esac _LT_PROG_LTMAIN # We use sed instead of cat because bash on DJGPP gets confused if # if finds mixed CR/LF and LF-only lines. Since sed operates in # text mode, it properly converts lines to CR/LF. This bash problem # is reportedly fixed, but why not run on old versions too? sed '$q' "$ltmain" >> "$cfgfile" \ || (rm -f "$cfgfile"; exit 1) mv -f "$cfgfile" "$ofile" || (rm -f "$ofile" && cp "$cfgfile" "$ofile" && rm -f "$cfgfile") chmod +x "$ofile" ], [cat <<_LT_EOF >> "$ofile" dnl Unfortunately we have to use $1 here, since _LT_TAG is not expanded dnl in a comment (ie after a #). # ### BEGIN LIBTOOL TAG CONFIG: $1 _LT_LIBTOOL_TAG_VARS(_LT_TAG) # ### END LIBTOOL TAG CONFIG: $1 _LT_EOF ])dnl /m4_if ], [m4_if([$1], [], [ PACKAGE='$PACKAGE' VERSION='$VERSION' RM='$RM' ofile='$ofile'], []) ])dnl /_LT_CONFIG_SAVE_COMMANDS ])# _LT_CONFIG # LT_SUPPORTED_TAG(TAG) # --------------------- # Trace this macro to discover what tags are supported by the libtool # --tag option, using: # autoconf --trace 'LT_SUPPORTED_TAG:$1' AC_DEFUN([LT_SUPPORTED_TAG], []) # C support is built-in for now m4_define([_LT_LANG_C_enabled], []) m4_define([_LT_TAGS], []) # LT_LANG(LANG) # ------------- # Enable libtool support for the given language if not already enabled. AC_DEFUN([LT_LANG], [AC_BEFORE([$0], [LT_OUTPUT])dnl m4_case([$1], [C], [_LT_LANG(C)], [C++], [_LT_LANG(CXX)], [Go], [_LT_LANG(GO)], [Java], [_LT_LANG(GCJ)], [Fortran 77], [_LT_LANG(F77)], [Fortran], [_LT_LANG(FC)], [Windows Resource], [_LT_LANG(RC)], [m4_ifdef([_LT_LANG_]$1[_CONFIG], [_LT_LANG($1)], [m4_fatal([$0: unsupported language: "$1"])])])dnl ])# LT_LANG # _LT_LANG(LANGNAME) # ------------------ m4_defun([_LT_LANG], [m4_ifdef([_LT_LANG_]$1[_enabled], [], [LT_SUPPORTED_TAG([$1])dnl m4_append([_LT_TAGS], [$1 ])dnl m4_define([_LT_LANG_]$1[_enabled], [])dnl _LT_LANG_$1_CONFIG($1)])dnl ])# _LT_LANG m4_ifndef([AC_PROG_GO], [ # NOTE: This macro has been submitted for inclusion into # # GNU Autoconf as AC_PROG_GO. When it is available in # # a released version of Autoconf we should remove this # # macro and use it instead. # m4_defun([AC_PROG_GO], [AC_LANG_PUSH(Go)dnl AC_ARG_VAR([GOC], [Go compiler command])dnl AC_ARG_VAR([GOFLAGS], [Go compiler flags])dnl _AC_ARG_VAR_LDFLAGS()dnl AC_CHECK_TOOL(GOC, gccgo) if test -z "$GOC"; then if test -n "$ac_tool_prefix"; then AC_CHECK_PROG(GOC, [${ac_tool_prefix}gccgo], [${ac_tool_prefix}gccgo]) fi fi if test -z "$GOC"; then AC_CHECK_PROG(GOC, gccgo, gccgo, false) fi ])#m4_defun ])#m4_ifndef # _LT_LANG_DEFAULT_CONFIG # ----------------------- m4_defun([_LT_LANG_DEFAULT_CONFIG], [AC_PROVIDE_IFELSE([AC_PROG_CXX], [LT_LANG(CXX)], [m4_define([AC_PROG_CXX], defn([AC_PROG_CXX])[LT_LANG(CXX)])]) AC_PROVIDE_IFELSE([AC_PROG_F77], [LT_LANG(F77)], [m4_define([AC_PROG_F77], defn([AC_PROG_F77])[LT_LANG(F77)])]) AC_PROVIDE_IFELSE([AC_PROG_FC], [LT_LANG(FC)], [m4_define([AC_PROG_FC], defn([AC_PROG_FC])[LT_LANG(FC)])]) dnl The call to [A][M_PROG_GCJ] is quoted like that to stop aclocal dnl pulling things in needlessly. AC_PROVIDE_IFELSE([AC_PROG_GCJ], [LT_LANG(GCJ)], [AC_PROVIDE_IFELSE([A][M_PROG_GCJ], [LT_LANG(GCJ)], [AC_PROVIDE_IFELSE([LT_PROG_GCJ], [LT_LANG(GCJ)], [m4_ifdef([AC_PROG_GCJ], [m4_define([AC_PROG_GCJ], defn([AC_PROG_GCJ])[LT_LANG(GCJ)])]) m4_ifdef([A][M_PROG_GCJ], [m4_define([A][M_PROG_GCJ], defn([A][M_PROG_GCJ])[LT_LANG(GCJ)])]) m4_ifdef([LT_PROG_GCJ], [m4_define([LT_PROG_GCJ], defn([LT_PROG_GCJ])[LT_LANG(GCJ)])])])])]) AC_PROVIDE_IFELSE([AC_PROG_GO], [LT_LANG(GO)], [m4_define([AC_PROG_GO], defn([AC_PROG_GO])[LT_LANG(GO)])]) AC_PROVIDE_IFELSE([LT_PROG_RC], [LT_LANG(RC)], [m4_define([LT_PROG_RC], defn([LT_PROG_RC])[LT_LANG(RC)])]) ])# _LT_LANG_DEFAULT_CONFIG # Obsolete macros: AU_DEFUN([AC_LIBTOOL_CXX], [LT_LANG(C++)]) AU_DEFUN([AC_LIBTOOL_F77], [LT_LANG(Fortran 77)]) AU_DEFUN([AC_LIBTOOL_FC], [LT_LANG(Fortran)]) AU_DEFUN([AC_LIBTOOL_GCJ], [LT_LANG(Java)]) AU_DEFUN([AC_LIBTOOL_RC], [LT_LANG(Windows Resource)]) dnl aclocal-1.4 backwards compatibility: dnl AC_DEFUN([AC_LIBTOOL_CXX], []) dnl AC_DEFUN([AC_LIBTOOL_F77], []) dnl AC_DEFUN([AC_LIBTOOL_FC], []) dnl AC_DEFUN([AC_LIBTOOL_GCJ], []) dnl AC_DEFUN([AC_LIBTOOL_RC], []) # _LT_TAG_COMPILER # ---------------- m4_defun([_LT_TAG_COMPILER], [AC_REQUIRE([AC_PROG_CC])dnl _LT_DECL([LTCC], [CC], [1], [A C compiler])dnl _LT_DECL([LTCFLAGS], [CFLAGS], [1], [LTCC compiler flags])dnl _LT_TAGDECL([CC], [compiler], [1], [A language specific compiler])dnl _LT_TAGDECL([with_gcc], [GCC], [0], [Is the compiler the GNU compiler?])dnl # If no C compiler was specified, use CC. LTCC=${LTCC-"$CC"} # If no C compiler flags were specified, use CFLAGS. LTCFLAGS=${LTCFLAGS-"$CFLAGS"} # Allow CC to be a program name with arguments. compiler=$CC ])# _LT_TAG_COMPILER # _LT_COMPILER_BOILERPLATE # ------------------------ # Check for compiler boilerplate output or warnings with # the simple compiler test code. m4_defun([_LT_COMPILER_BOILERPLATE], [m4_require([_LT_DECL_SED])dnl ac_outfile=conftest.$ac_objext echo "$lt_simple_compile_test_code" >conftest.$ac_ext eval "$ac_compile" 2>&1 >/dev/null | $SED '/^$/d; /^ *+/d' >conftest.err _lt_compiler_boilerplate=`cat conftest.err` $RM conftest* ])# _LT_COMPILER_BOILERPLATE # _LT_LINKER_BOILERPLATE # ---------------------- # Check for linker boilerplate output or warnings with # the simple link test code. m4_defun([_LT_LINKER_BOILERPLATE], [m4_require([_LT_DECL_SED])dnl ac_outfile=conftest.$ac_objext echo "$lt_simple_link_test_code" >conftest.$ac_ext eval "$ac_link" 2>&1 >/dev/null | $SED '/^$/d; /^ *+/d' >conftest.err _lt_linker_boilerplate=`cat conftest.err` $RM -r conftest* ])# _LT_LINKER_BOILERPLATE # _LT_REQUIRED_DARWIN_CHECKS # ------------------------- m4_defun_once([_LT_REQUIRED_DARWIN_CHECKS],[ case $host_os in rhapsody* | darwin*) AC_CHECK_TOOL([DSYMUTIL], [dsymutil], [:]) AC_CHECK_TOOL([NMEDIT], [nmedit], [:]) AC_CHECK_TOOL([LIPO], [lipo], [:]) AC_CHECK_TOOL([OTOOL], [otool], [:]) AC_CHECK_TOOL([OTOOL64], [otool64], [:]) _LT_DECL([], [DSYMUTIL], [1], [Tool to manipulate archived DWARF debug symbol files on Mac OS X]) _LT_DECL([], [NMEDIT], [1], [Tool to change global to local symbols on Mac OS X]) _LT_DECL([], [LIPO], [1], [Tool to manipulate fat objects and archives on Mac OS X]) _LT_DECL([], [OTOOL], [1], [ldd/readelf like tool for Mach-O binaries on Mac OS X]) _LT_DECL([], [OTOOL64], [1], [ldd/readelf like tool for 64 bit Mach-O binaries on Mac OS X 10.4]) AC_CACHE_CHECK([for -single_module linker flag],[lt_cv_apple_cc_single_mod], [lt_cv_apple_cc_single_mod=no if test -z "$LT_MULTI_MODULE"; then # By default we will add the -single_module flag. You can override # by either setting the environment variable LT_MULTI_MODULE # non-empty at configure time, or by adding -multi_module to the # link flags. rm -rf libconftest.dylib* echo "int foo(void){return 1;}" > conftest.c echo "$LTCC $LTCFLAGS $LDFLAGS -o libconftest.dylib \ -dynamiclib -Wl,-single_module conftest.c" >&AS_MESSAGE_LOG_FD $LTCC $LTCFLAGS $LDFLAGS -o libconftest.dylib \ -dynamiclib -Wl,-single_module conftest.c 2>conftest.err _lt_result=$? # If there is a non-empty error log, and "single_module" # appears in it, assume the flag caused a linker warning if test -s conftest.err && $GREP single_module conftest.err; then cat conftest.err >&AS_MESSAGE_LOG_FD # Otherwise, if the output was created with a 0 exit code from # the compiler, it worked. elif test -f libconftest.dylib && test 0 = "$_lt_result"; then lt_cv_apple_cc_single_mod=yes else cat conftest.err >&AS_MESSAGE_LOG_FD fi rm -rf libconftest.dylib* rm -f conftest.* fi]) AC_CACHE_CHECK([for -exported_symbols_list linker flag], [lt_cv_ld_exported_symbols_list], [lt_cv_ld_exported_symbols_list=no save_LDFLAGS=$LDFLAGS echo "_main" > conftest.sym LDFLAGS="$LDFLAGS -Wl,-exported_symbols_list,conftest.sym" AC_LINK_IFELSE([AC_LANG_PROGRAM([],[])], [lt_cv_ld_exported_symbols_list=yes], [lt_cv_ld_exported_symbols_list=no]) LDFLAGS=$save_LDFLAGS ]) AC_CACHE_CHECK([for -force_load linker flag],[lt_cv_ld_force_load], [lt_cv_ld_force_load=no cat > conftest.c << _LT_EOF int forced_loaded() { return 2;} _LT_EOF echo "$LTCC $LTCFLAGS -c -o conftest.o conftest.c" >&AS_MESSAGE_LOG_FD $LTCC $LTCFLAGS -c -o conftest.o conftest.c 2>&AS_MESSAGE_LOG_FD echo "$AR cru libconftest.a conftest.o" >&AS_MESSAGE_LOG_FD $AR cru libconftest.a conftest.o 2>&AS_MESSAGE_LOG_FD echo "$RANLIB libconftest.a" >&AS_MESSAGE_LOG_FD $RANLIB libconftest.a 2>&AS_MESSAGE_LOG_FD cat > conftest.c << _LT_EOF int main() { return 0;} _LT_EOF echo "$LTCC $LTCFLAGS $LDFLAGS -o conftest conftest.c -Wl,-force_load,./libconftest.a" >&AS_MESSAGE_LOG_FD $LTCC $LTCFLAGS $LDFLAGS -o conftest conftest.c -Wl,-force_load,./libconftest.a 2>conftest.err _lt_result=$? if test -s conftest.err && $GREP force_load conftest.err; then cat conftest.err >&AS_MESSAGE_LOG_FD elif test -f conftest && test 0 = "$_lt_result" && $GREP forced_load conftest >/dev/null 2>&1; then lt_cv_ld_force_load=yes else cat conftest.err >&AS_MESSAGE_LOG_FD fi rm -f conftest.err libconftest.a conftest conftest.c rm -rf conftest.dSYM ]) case $host_os in rhapsody* | darwin1.[[012]]) _lt_dar_allow_undefined='$wl-undefined ${wl}suppress' ;; darwin1.*) _lt_dar_allow_undefined='$wl-flat_namespace $wl-undefined ${wl}suppress' ;; darwin*) # darwin 5.x on # if running on 10.5 or later, the deployment target defaults # to the OS version, if on x86, and 10.4, the deployment # target defaults to 10.4. Don't you love it? case ${MACOSX_DEPLOYMENT_TARGET-10.0},$host in 10.0,*86*-darwin8*|10.0,*-darwin[[91]]*) _lt_dar_allow_undefined='$wl-undefined ${wl}dynamic_lookup' ;; 10.[[012]][[,.]]*) _lt_dar_allow_undefined='$wl-flat_namespace $wl-undefined ${wl}suppress' ;; 10.*) _lt_dar_allow_undefined='$wl-undefined ${wl}dynamic_lookup' ;; esac ;; esac if test yes = "$lt_cv_apple_cc_single_mod"; then _lt_dar_single_mod='$single_module' fi if test yes = "$lt_cv_ld_exported_symbols_list"; then _lt_dar_export_syms=' $wl-exported_symbols_list,$output_objdir/$libname-symbols.expsym' else _lt_dar_export_syms='~$NMEDIT -s $output_objdir/$libname-symbols.expsym $lib' fi if test : != "$DSYMUTIL" && test no = "$lt_cv_ld_force_load"; then _lt_dsymutil='~$DSYMUTIL $lib || :' else _lt_dsymutil= fi ;; esac ]) # _LT_DARWIN_LINKER_FEATURES([TAG]) # --------------------------------- # Checks for linker and compiler features on darwin m4_defun([_LT_DARWIN_LINKER_FEATURES], [ m4_require([_LT_REQUIRED_DARWIN_CHECKS]) _LT_TAGVAR(archive_cmds_need_lc, $1)=no _LT_TAGVAR(hardcode_direct, $1)=no _LT_TAGVAR(hardcode_automatic, $1)=yes _LT_TAGVAR(hardcode_shlibpath_var, $1)=unsupported if test yes = "$lt_cv_ld_force_load"; then _LT_TAGVAR(whole_archive_flag_spec, $1)='`for conv in $convenience\"\"; do test -n \"$conv\" && new_convenience=\"$new_convenience $wl-force_load,$conv\"; done; func_echo_all \"$new_convenience\"`' m4_case([$1], [F77], [_LT_TAGVAR(compiler_needs_object, $1)=yes], [FC], [_LT_TAGVAR(compiler_needs_object, $1)=yes]) else _LT_TAGVAR(whole_archive_flag_spec, $1)='' fi _LT_TAGVAR(link_all_deplibs, $1)=yes _LT_TAGVAR(allow_undefined_flag, $1)=$_lt_dar_allow_undefined case $cc_basename in ifort*|nagfor*) _lt_dar_can_shared=yes ;; *) _lt_dar_can_shared=$GCC ;; esac if test yes = "$_lt_dar_can_shared"; then output_verbose_link_cmd=func_echo_all _LT_TAGVAR(archive_cmds, $1)="\$CC -dynamiclib \$allow_undefined_flag -o \$lib \$libobjs \$deplibs \$compiler_flags -install_name \$rpath/\$soname \$verstring $_lt_dar_single_mod$_lt_dsymutil" _LT_TAGVAR(module_cmds, $1)="\$CC \$allow_undefined_flag -o \$lib -bundle \$libobjs \$deplibs \$compiler_flags$_lt_dsymutil" _LT_TAGVAR(archive_expsym_cmds, $1)="sed 's|^|_|' < \$export_symbols > \$output_objdir/\$libname-symbols.expsym~\$CC -dynamiclib \$allow_undefined_flag -o \$lib \$libobjs \$deplibs \$compiler_flags -install_name \$rpath/\$soname \$verstring $_lt_dar_single_mod$_lt_dar_export_syms$_lt_dsymutil" _LT_TAGVAR(module_expsym_cmds, $1)="sed -e 's|^|_|' < \$export_symbols > \$output_objdir/\$libname-symbols.expsym~\$CC \$allow_undefined_flag -o \$lib -bundle \$libobjs \$deplibs \$compiler_flags$_lt_dar_export_syms$_lt_dsymutil" m4_if([$1], [CXX], [ if test yes != "$lt_cv_apple_cc_single_mod"; then _LT_TAGVAR(archive_cmds, $1)="\$CC -r -keep_private_externs -nostdlib -o \$lib-master.o \$libobjs~\$CC -dynamiclib \$allow_undefined_flag -o \$lib \$lib-master.o \$deplibs \$compiler_flags -install_name \$rpath/\$soname \$verstring$_lt_dsymutil" _LT_TAGVAR(archive_expsym_cmds, $1)="sed 's|^|_|' < \$export_symbols > \$output_objdir/\$libname-symbols.expsym~\$CC -r -keep_private_externs -nostdlib -o \$lib-master.o \$libobjs~\$CC -dynamiclib \$allow_undefined_flag -o \$lib \$lib-master.o \$deplibs \$compiler_flags -install_name \$rpath/\$soname \$verstring$_lt_dar_export_syms$_lt_dsymutil" fi ],[]) else _LT_TAGVAR(ld_shlibs, $1)=no fi ]) # _LT_SYS_MODULE_PATH_AIX([TAGNAME]) # ---------------------------------- # Links a minimal program and checks the executable # for the system default hardcoded library path. In most cases, # this is /usr/lib:/lib, but when the MPI compilers are used # the location of the communication and MPI libs are included too. # If we don't find anything, use the default library path according # to the aix ld manual. # Store the results from the different compilers for each TAGNAME. # Allow to override them for all tags through lt_cv_aix_libpath. m4_defun([_LT_SYS_MODULE_PATH_AIX], [m4_require([_LT_DECL_SED])dnl if test set = "${lt_cv_aix_libpath+set}"; then aix_libpath=$lt_cv_aix_libpath else AC_CACHE_VAL([_LT_TAGVAR([lt_cv_aix_libpath_], [$1])], [AC_LINK_IFELSE([AC_LANG_PROGRAM],[ lt_aix_libpath_sed='[ /Import File Strings/,/^$/ { /^0/ { s/^0 *\([^ ]*\) *$/\1/ p } }]' _LT_TAGVAR([lt_cv_aix_libpath_], [$1])=`dump -H conftest$ac_exeext 2>/dev/null | $SED -n -e "$lt_aix_libpath_sed"` # Check for a 64-bit object if we didn't find anything. if test -z "$_LT_TAGVAR([lt_cv_aix_libpath_], [$1])"; then _LT_TAGVAR([lt_cv_aix_libpath_], [$1])=`dump -HX64 conftest$ac_exeext 2>/dev/null | $SED -n -e "$lt_aix_libpath_sed"` fi],[]) if test -z "$_LT_TAGVAR([lt_cv_aix_libpath_], [$1])"; then _LT_TAGVAR([lt_cv_aix_libpath_], [$1])=/usr/lib:/lib fi ]) aix_libpath=$_LT_TAGVAR([lt_cv_aix_libpath_], [$1]) fi ])# _LT_SYS_MODULE_PATH_AIX # _LT_SHELL_INIT(ARG) # ------------------- m4_define([_LT_SHELL_INIT], [m4_divert_text([M4SH-INIT], [$1 ])])# _LT_SHELL_INIT # _LT_PROG_ECHO_BACKSLASH # ----------------------- # Find how we can fake an echo command that does not interpret backslash. # In particular, with Autoconf 2.60 or later we add some code to the start # of the generated configure script that will find a shell with a builtin # printf (that we can use as an echo command). m4_defun([_LT_PROG_ECHO_BACKSLASH], [ECHO='\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\' ECHO=$ECHO$ECHO$ECHO$ECHO$ECHO ECHO=$ECHO$ECHO$ECHO$ECHO$ECHO$ECHO AC_MSG_CHECKING([how to print strings]) # Test print first, because it will be a builtin if present. if test "X`( print -r -- -n ) 2>/dev/null`" = X-n && \ test "X`print -r -- $ECHO 2>/dev/null`" = "X$ECHO"; then ECHO='print -r --' elif test "X`printf %s $ECHO 2>/dev/null`" = "X$ECHO"; then ECHO='printf %s\n' else # Use this function as a fallback that always works. func_fallback_echo () { eval 'cat <<_LTECHO_EOF $[]1 _LTECHO_EOF' } ECHO='func_fallback_echo' fi # func_echo_all arg... # Invoke $ECHO with all args, space-separated. func_echo_all () { $ECHO "$*" } case $ECHO in printf*) AC_MSG_RESULT([printf]) ;; print*) AC_MSG_RESULT([print -r]) ;; *) AC_MSG_RESULT([cat]) ;; esac m4_ifdef([_AS_DETECT_SUGGESTED], [_AS_DETECT_SUGGESTED([ test -n "${ZSH_VERSION+set}${BASH_VERSION+set}" || ( ECHO='\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\' ECHO=$ECHO$ECHO$ECHO$ECHO$ECHO ECHO=$ECHO$ECHO$ECHO$ECHO$ECHO$ECHO PATH=/empty FPATH=/empty; export PATH FPATH test "X`printf %s $ECHO`" = "X$ECHO" \ || test "X`print -r -- $ECHO`" = "X$ECHO" )])]) _LT_DECL([], [SHELL], [1], [Shell to use when invoking shell scripts]) _LT_DECL([], [ECHO], [1], [An echo program that protects backslashes]) ])# _LT_PROG_ECHO_BACKSLASH # _LT_WITH_SYSROOT # ---------------- AC_DEFUN([_LT_WITH_SYSROOT], [AC_MSG_CHECKING([for sysroot]) AC_ARG_WITH([sysroot], [AS_HELP_STRING([--with-sysroot@<:@=DIR@:>@], [Search for dependent libraries within DIR (or the compiler's sysroot if not specified).])], [], [with_sysroot=no]) dnl lt_sysroot will always be passed unquoted. We quote it here dnl in case the user passed a directory name. lt_sysroot= case $with_sysroot in #( yes) if test yes = "$GCC"; then lt_sysroot=`$CC --print-sysroot 2>/dev/null` fi ;; #( /*) lt_sysroot=`echo "$with_sysroot" | sed -e "$sed_quote_subst"` ;; #( no|'') ;; #( *) AC_MSG_RESULT([$with_sysroot]) AC_MSG_ERROR([The sysroot must be an absolute path.]) ;; esac AC_MSG_RESULT([${lt_sysroot:-no}]) _LT_DECL([], [lt_sysroot], [0], [The root where to search for ]dnl [dependent libraries, and where our libraries should be installed.])]) # _LT_ENABLE_LOCK # --------------- m4_defun([_LT_ENABLE_LOCK], [AC_ARG_ENABLE([libtool-lock], [AS_HELP_STRING([--disable-libtool-lock], [avoid locking (might break parallel builds)])]) test no = "$enable_libtool_lock" || enable_libtool_lock=yes # Some flags need to be propagated to the compiler or linker for good # libtool support. case $host in ia64-*-hpux*) # Find out what ABI is being produced by ac_compile, and set mode # options accordingly. echo 'int i;' > conftest.$ac_ext if AC_TRY_EVAL(ac_compile); then case `/usr/bin/file conftest.$ac_objext` in *ELF-32*) HPUX_IA64_MODE=32 ;; *ELF-64*) HPUX_IA64_MODE=64 ;; esac fi rm -rf conftest* ;; *-*-irix6*) # Find out what ABI is being produced by ac_compile, and set linker # options accordingly. echo '[#]line '$LINENO' "configure"' > conftest.$ac_ext if AC_TRY_EVAL(ac_compile); then if test yes = "$lt_cv_prog_gnu_ld"; then case `/usr/bin/file conftest.$ac_objext` in *32-bit*) LD="${LD-ld} -melf32bsmip" ;; *N32*) LD="${LD-ld} -melf32bmipn32" ;; *64-bit*) LD="${LD-ld} -melf64bmip" ;; esac else case `/usr/bin/file conftest.$ac_objext` in *32-bit*) LD="${LD-ld} -32" ;; *N32*) LD="${LD-ld} -n32" ;; *64-bit*) LD="${LD-ld} -64" ;; esac fi fi rm -rf conftest* ;; mips64*-*linux*) # Find out what ABI is being produced by ac_compile, and set linker # options accordingly. echo '[#]line '$LINENO' "configure"' > conftest.$ac_ext if AC_TRY_EVAL(ac_compile); then emul=elf case `/usr/bin/file conftest.$ac_objext` in *32-bit*) emul="${emul}32" ;; *64-bit*) emul="${emul}64" ;; esac case `/usr/bin/file conftest.$ac_objext` in *MSB*) emul="${emul}btsmip" ;; *LSB*) emul="${emul}ltsmip" ;; esac case `/usr/bin/file conftest.$ac_objext` in *N32*) emul="${emul}n32" ;; esac LD="${LD-ld} -m $emul" fi rm -rf conftest* ;; x86_64-*kfreebsd*-gnu|x86_64-*linux*|powerpc*-*linux*| \ s390*-*linux*|s390*-*tpf*|sparc*-*linux*) # Find out what ABI is being produced by ac_compile, and set linker # options accordingly. Note that the listed cases only cover the # situations where additional linker options are needed (such as when # doing 32-bit compilation for a host where ld defaults to 64-bit, or # vice versa); the common cases where no linker options are needed do # not appear in the list. echo 'int i;' > conftest.$ac_ext if AC_TRY_EVAL(ac_compile); then case `/usr/bin/file conftest.o` in *32-bit*) case $host in x86_64-*kfreebsd*-gnu) LD="${LD-ld} -m elf_i386_fbsd" ;; x86_64-*linux*) case `/usr/bin/file conftest.o` in *x86-64*) LD="${LD-ld} -m elf32_x86_64" ;; *) LD="${LD-ld} -m elf_i386" ;; esac ;; powerpc64le-*linux*) LD="${LD-ld} -m elf32lppclinux" ;; powerpc64-*linux*) LD="${LD-ld} -m elf32ppclinux" ;; s390x-*linux*) LD="${LD-ld} -m elf_s390" ;; sparc64-*linux*) LD="${LD-ld} -m elf32_sparc" ;; esac ;; *64-bit*) case $host in x86_64-*kfreebsd*-gnu) LD="${LD-ld} -m elf_x86_64_fbsd" ;; x86_64-*linux*) LD="${LD-ld} -m elf_x86_64" ;; powerpcle-*linux*) LD="${LD-ld} -m elf64lppc" ;; powerpc-*linux*) LD="${LD-ld} -m elf64ppc" ;; s390*-*linux*|s390*-*tpf*) LD="${LD-ld} -m elf64_s390" ;; sparc*-*linux*) LD="${LD-ld} -m elf64_sparc" ;; esac ;; esac fi rm -rf conftest* ;; *-*-sco3.2v5*) # On SCO OpenServer 5, we need -belf to get full-featured binaries. SAVE_CFLAGS=$CFLAGS CFLAGS="$CFLAGS -belf" AC_CACHE_CHECK([whether the C compiler needs -belf], lt_cv_cc_needs_belf, [AC_LANG_PUSH(C) AC_LINK_IFELSE([AC_LANG_PROGRAM([[]],[[]])],[lt_cv_cc_needs_belf=yes],[lt_cv_cc_needs_belf=no]) AC_LANG_POP]) if test yes != "$lt_cv_cc_needs_belf"; then # this is probably gcc 2.8.0, egcs 1.0 or newer; no need for -belf CFLAGS=$SAVE_CFLAGS fi ;; *-*solaris*) # Find out what ABI is being produced by ac_compile, and set linker # options accordingly. echo 'int i;' > conftest.$ac_ext if AC_TRY_EVAL(ac_compile); then case `/usr/bin/file conftest.o` in *64-bit*) case $lt_cv_prog_gnu_ld in yes*) case $host in i?86-*-solaris*|x86_64-*-solaris*) LD="${LD-ld} -m elf_x86_64" ;; sparc*-*-solaris*) LD="${LD-ld} -m elf64_sparc" ;; esac # GNU ld 2.21 introduced _sol2 emulations. Use them if available. if ${LD-ld} -V | grep _sol2 >/dev/null 2>&1; then LD=${LD-ld}_sol2 fi ;; *) if ${LD-ld} -64 -r -o conftest2.o conftest.o >/dev/null 2>&1; then LD="${LD-ld} -64" fi ;; esac ;; esac fi rm -rf conftest* ;; esac need_locks=$enable_libtool_lock ])# _LT_ENABLE_LOCK # _LT_PROG_AR # ----------- m4_defun([_LT_PROG_AR], [AC_CHECK_TOOLS(AR, [ar], false) : ${AR=ar} : ${AR_FLAGS=cru} _LT_DECL([], [AR], [1], [The archiver]) _LT_DECL([], [AR_FLAGS], [1], [Flags to create an archive]) AC_CACHE_CHECK([for archiver @FILE support], [lt_cv_ar_at_file], [lt_cv_ar_at_file=no AC_COMPILE_IFELSE([AC_LANG_PROGRAM], [echo conftest.$ac_objext > conftest.lst lt_ar_try='$AR $AR_FLAGS libconftest.a @conftest.lst >&AS_MESSAGE_LOG_FD' AC_TRY_EVAL([lt_ar_try]) if test 0 -eq "$ac_status"; then # Ensure the archiver fails upon bogus file names. rm -f conftest.$ac_objext libconftest.a AC_TRY_EVAL([lt_ar_try]) if test 0 -ne "$ac_status"; then lt_cv_ar_at_file=@ fi fi rm -f conftest.* libconftest.a ]) ]) if test no = "$lt_cv_ar_at_file"; then archiver_list_spec= else archiver_list_spec=$lt_cv_ar_at_file fi _LT_DECL([], [archiver_list_spec], [1], [How to feed a file listing to the archiver]) ])# _LT_PROG_AR # _LT_CMD_OLD_ARCHIVE # ------------------- m4_defun([_LT_CMD_OLD_ARCHIVE], [_LT_PROG_AR AC_CHECK_TOOL(STRIP, strip, :) test -z "$STRIP" && STRIP=: _LT_DECL([], [STRIP], [1], [A symbol stripping program]) AC_CHECK_TOOL(RANLIB, ranlib, :) test -z "$RANLIB" && RANLIB=: _LT_DECL([], [RANLIB], [1], [Commands used to install an old-style archive]) # Determine commands to create old-style static archives. old_archive_cmds='$AR $AR_FLAGS $oldlib$oldobjs' old_postinstall_cmds='chmod 644 $oldlib' old_postuninstall_cmds= if test -n "$RANLIB"; then case $host_os in bitrig* | openbsd*) old_postinstall_cmds="$old_postinstall_cmds~\$RANLIB -t \$tool_oldlib" ;; *) old_postinstall_cmds="$old_postinstall_cmds~\$RANLIB \$tool_oldlib" ;; esac old_archive_cmds="$old_archive_cmds~\$RANLIB \$tool_oldlib" fi case $host_os in darwin*) lock_old_archive_extraction=yes ;; *) lock_old_archive_extraction=no ;; esac _LT_DECL([], [old_postinstall_cmds], [2]) _LT_DECL([], [old_postuninstall_cmds], [2]) _LT_TAGDECL([], [old_archive_cmds], [2], [Commands used to build an old-style archive]) _LT_DECL([], [lock_old_archive_extraction], [0], [Whether to use a lock for old archive extraction]) ])# _LT_CMD_OLD_ARCHIVE # _LT_COMPILER_OPTION(MESSAGE, VARIABLE-NAME, FLAGS, # [OUTPUT-FILE], [ACTION-SUCCESS], [ACTION-FAILURE]) # ---------------------------------------------------------------- # Check whether the given compiler option works AC_DEFUN([_LT_COMPILER_OPTION], [m4_require([_LT_FILEUTILS_DEFAULTS])dnl m4_require([_LT_DECL_SED])dnl AC_CACHE_CHECK([$1], [$2], [$2=no m4_if([$4], , [ac_outfile=conftest.$ac_objext], [ac_outfile=$4]) echo "$lt_simple_compile_test_code" > conftest.$ac_ext lt_compiler_flag="$3" ## exclude from sc_useless_quotes_in_assignment # Insert the option either (1) after the last *FLAGS variable, or # (2) before a word containing "conftest.", or (3) at the end. # Note that $ac_compile itself does not contain backslashes and begins # with a dollar sign (not a hyphen), so the echo should work correctly. # The option is referenced via a variable to avoid confusing sed. lt_compile=`echo "$ac_compile" | $SED \ -e 's:.*FLAGS}\{0,1\} :&$lt_compiler_flag :; t' \ -e 's: [[^ ]]*conftest\.: $lt_compiler_flag&:; t' \ -e 's:$: $lt_compiler_flag:'` (eval echo "\"\$as_me:$LINENO: $lt_compile\"" >&AS_MESSAGE_LOG_FD) (eval "$lt_compile" 2>conftest.err) ac_status=$? cat conftest.err >&AS_MESSAGE_LOG_FD echo "$as_me:$LINENO: \$? = $ac_status" >&AS_MESSAGE_LOG_FD if (exit $ac_status) && test -s "$ac_outfile"; then # The compiler can only warn and ignore the option if not recognized # So say no if there are warnings other than the usual output. $ECHO "$_lt_compiler_boilerplate" | $SED '/^$/d' >conftest.exp $SED '/^$/d; /^ *+/d' conftest.err >conftest.er2 if test ! -s conftest.er2 || diff conftest.exp conftest.er2 >/dev/null; then $2=yes fi fi $RM conftest* ]) if test yes = "[$]$2"; then m4_if([$5], , :, [$5]) else m4_if([$6], , :, [$6]) fi ])# _LT_COMPILER_OPTION # Old name: AU_ALIAS([AC_LIBTOOL_COMPILER_OPTION], [_LT_COMPILER_OPTION]) dnl aclocal-1.4 backwards compatibility: dnl AC_DEFUN([AC_LIBTOOL_COMPILER_OPTION], []) # _LT_LINKER_OPTION(MESSAGE, VARIABLE-NAME, FLAGS, # [ACTION-SUCCESS], [ACTION-FAILURE]) # ---------------------------------------------------- # Check whether the given linker option works AC_DEFUN([_LT_LINKER_OPTION], [m4_require([_LT_FILEUTILS_DEFAULTS])dnl m4_require([_LT_DECL_SED])dnl AC_CACHE_CHECK([$1], [$2], [$2=no save_LDFLAGS=$LDFLAGS LDFLAGS="$LDFLAGS $3" echo "$lt_simple_link_test_code" > conftest.$ac_ext if (eval $ac_link 2>conftest.err) && test -s conftest$ac_exeext; then # The linker can only warn and ignore the option if not recognized # So say no if there are warnings if test -s conftest.err; then # Append any errors to the config.log. cat conftest.err 1>&AS_MESSAGE_LOG_FD $ECHO "$_lt_linker_boilerplate" | $SED '/^$/d' > conftest.exp $SED '/^$/d; /^ *+/d' conftest.err >conftest.er2 if diff conftest.exp conftest.er2 >/dev/null; then $2=yes fi else $2=yes fi fi $RM -r conftest* LDFLAGS=$save_LDFLAGS ]) if test yes = "[$]$2"; then m4_if([$4], , :, [$4]) else m4_if([$5], , :, [$5]) fi ])# _LT_LINKER_OPTION # Old name: AU_ALIAS([AC_LIBTOOL_LINKER_OPTION], [_LT_LINKER_OPTION]) dnl aclocal-1.4 backwards compatibility: dnl AC_DEFUN([AC_LIBTOOL_LINKER_OPTION], []) # LT_CMD_MAX_LEN #--------------- AC_DEFUN([LT_CMD_MAX_LEN], [AC_REQUIRE([AC_CANONICAL_HOST])dnl # find the maximum length of command line arguments AC_MSG_CHECKING([the maximum length of command line arguments]) AC_CACHE_VAL([lt_cv_sys_max_cmd_len], [dnl i=0 teststring=ABCD case $build_os in msdosdjgpp*) # On DJGPP, this test can blow up pretty badly due to problems in libc # (any single argument exceeding 2000 bytes causes a buffer overrun # during glob expansion). Even if it were fixed, the result of this # check would be larger than it should be. lt_cv_sys_max_cmd_len=12288; # 12K is about right ;; gnu*) # Under GNU Hurd, this test is not required because there is # no limit to the length of command line arguments. # Libtool will interpret -1 as no limit whatsoever lt_cv_sys_max_cmd_len=-1; ;; cygwin* | mingw* | cegcc*) # On Win9x/ME, this test blows up -- it succeeds, but takes # about 5 minutes as the teststring grows exponentially. # Worse, since 9x/ME are not pre-emptively multitasking, # you end up with a "frozen" computer, even though with patience # the test eventually succeeds (with a max line length of 256k). # Instead, let's just punt: use the minimum linelength reported by # all of the supported platforms: 8192 (on NT/2K/XP). lt_cv_sys_max_cmd_len=8192; ;; mint*) # On MiNT this can take a long time and run out of memory. lt_cv_sys_max_cmd_len=8192; ;; amigaos*) # On AmigaOS with pdksh, this test takes hours, literally. # So we just punt and use a minimum line length of 8192. lt_cv_sys_max_cmd_len=8192; ;; bitrig* | darwin* | dragonfly* | freebsd* | netbsd* | openbsd*) # This has been around since 386BSD, at least. Likely further. if test -x /sbin/sysctl; then lt_cv_sys_max_cmd_len=`/sbin/sysctl -n kern.argmax` elif test -x /usr/sbin/sysctl; then lt_cv_sys_max_cmd_len=`/usr/sbin/sysctl -n kern.argmax` else lt_cv_sys_max_cmd_len=65536 # usable default for all BSDs fi # And add a safety zone lt_cv_sys_max_cmd_len=`expr $lt_cv_sys_max_cmd_len \/ 4` lt_cv_sys_max_cmd_len=`expr $lt_cv_sys_max_cmd_len \* 3` ;; interix*) # We know the value 262144 and hardcode it with a safety zone (like BSD) lt_cv_sys_max_cmd_len=196608 ;; os2*) # The test takes a long time on OS/2. lt_cv_sys_max_cmd_len=8192 ;; osf*) # Dr. Hans Ekkehard Plesser reports seeing a kernel panic running configure # due to this test when exec_disable_arg_limit is 1 on Tru64. It is not # nice to cause kernel panics so lets avoid the loop below. # First set a reasonable default. lt_cv_sys_max_cmd_len=16384 # if test -x /sbin/sysconfig; then case `/sbin/sysconfig -q proc exec_disable_arg_limit` in *1*) lt_cv_sys_max_cmd_len=-1 ;; esac fi ;; sco3.2v5*) lt_cv_sys_max_cmd_len=102400 ;; sysv5* | sco5v6* | sysv4.2uw2*) kargmax=`grep ARG_MAX /etc/conf/cf.d/stune 2>/dev/null` if test -n "$kargmax"; then lt_cv_sys_max_cmd_len=`echo $kargmax | sed 's/.*[[ ]]//'` else lt_cv_sys_max_cmd_len=32768 fi ;; *) lt_cv_sys_max_cmd_len=`(getconf ARG_MAX) 2> /dev/null` if test -n "$lt_cv_sys_max_cmd_len" && \ test undefined != "$lt_cv_sys_max_cmd_len"; then lt_cv_sys_max_cmd_len=`expr $lt_cv_sys_max_cmd_len \/ 4` lt_cv_sys_max_cmd_len=`expr $lt_cv_sys_max_cmd_len \* 3` else # Make teststring a little bigger before we do anything with it. # a 1K string should be a reasonable start. for i in 1 2 3 4 5 6 7 8; do teststring=$teststring$teststring done SHELL=${SHELL-${CONFIG_SHELL-/bin/sh}} # If test is not a shell built-in, we'll probably end up computing a # maximum length that is only half of the actual maximum length, but # we can't tell. while { test X`env echo "$teststring$teststring" 2>/dev/null` \ = "X$teststring$teststring"; } >/dev/null 2>&1 && test 17 != "$i" # 1/2 MB should be enough do i=`expr $i + 1` teststring=$teststring$teststring done # Only check the string length outside the loop. lt_cv_sys_max_cmd_len=`expr "X$teststring" : ".*" 2>&1` teststring= # Add a significant safety factor because C++ compilers can tack on # massive amounts of additional arguments before passing them to the # linker. It appears as though 1/2 is a usable value. lt_cv_sys_max_cmd_len=`expr $lt_cv_sys_max_cmd_len \/ 2` fi ;; esac ]) if test -n "$lt_cv_sys_max_cmd_len"; then AC_MSG_RESULT($lt_cv_sys_max_cmd_len) else AC_MSG_RESULT(none) fi max_cmd_len=$lt_cv_sys_max_cmd_len _LT_DECL([], [max_cmd_len], [0], [What is the maximum length of a command?]) ])# LT_CMD_MAX_LEN # Old name: AU_ALIAS([AC_LIBTOOL_SYS_MAX_CMD_LEN], [LT_CMD_MAX_LEN]) dnl aclocal-1.4 backwards compatibility: dnl AC_DEFUN([AC_LIBTOOL_SYS_MAX_CMD_LEN], []) # _LT_HEADER_DLFCN # ---------------- m4_defun([_LT_HEADER_DLFCN], [AC_CHECK_HEADERS([dlfcn.h], [], [], [AC_INCLUDES_DEFAULT])dnl ])# _LT_HEADER_DLFCN # _LT_TRY_DLOPEN_SELF (ACTION-IF-TRUE, ACTION-IF-TRUE-W-USCORE, # ACTION-IF-FALSE, ACTION-IF-CROSS-COMPILING) # ---------------------------------------------------------------- m4_defun([_LT_TRY_DLOPEN_SELF], [m4_require([_LT_HEADER_DLFCN])dnl if test yes = "$cross_compiling"; then : [$4] else lt_dlunknown=0; lt_dlno_uscore=1; lt_dlneed_uscore=2 lt_status=$lt_dlunknown cat > conftest.$ac_ext <<_LT_EOF [#line $LINENO "configure" #include "confdefs.h" #if HAVE_DLFCN_H #include #endif #include #ifdef RTLD_GLOBAL # define LT_DLGLOBAL RTLD_GLOBAL #else # ifdef DL_GLOBAL # define LT_DLGLOBAL DL_GLOBAL # else # define LT_DLGLOBAL 0 # endif #endif /* We may have to define LT_DLLAZY_OR_NOW in the command line if we find out it does not work in some platform. */ #ifndef LT_DLLAZY_OR_NOW # ifdef RTLD_LAZY # define LT_DLLAZY_OR_NOW RTLD_LAZY # else # ifdef DL_LAZY # define LT_DLLAZY_OR_NOW DL_LAZY # else # ifdef RTLD_NOW # define LT_DLLAZY_OR_NOW RTLD_NOW # else # ifdef DL_NOW # define LT_DLLAZY_OR_NOW DL_NOW # else # define LT_DLLAZY_OR_NOW 0 # endif # endif # endif # endif #endif /* When -fvisibility=hidden is used, assume the code has been annotated correspondingly for the symbols needed. */ #if defined __GNUC__ && (((__GNUC__ == 3) && (__GNUC_MINOR__ >= 3)) || (__GNUC__ > 3)) int fnord () __attribute__((visibility("default"))); #endif int fnord () { return 42; } int main () { void *self = dlopen (0, LT_DLGLOBAL|LT_DLLAZY_OR_NOW); int status = $lt_dlunknown; if (self) { if (dlsym (self,"fnord")) status = $lt_dlno_uscore; else { if (dlsym( self,"_fnord")) status = $lt_dlneed_uscore; else puts (dlerror ()); } /* dlclose (self); */ } else puts (dlerror ()); return status; }] _LT_EOF if AC_TRY_EVAL(ac_link) && test -s "conftest$ac_exeext" 2>/dev/null; then (./conftest; exit; ) >&AS_MESSAGE_LOG_FD 2>/dev/null lt_status=$? case x$lt_status in x$lt_dlno_uscore) $1 ;; x$lt_dlneed_uscore) $2 ;; x$lt_dlunknown|x*) $3 ;; esac else : # compilation failed $3 fi fi rm -fr conftest* ])# _LT_TRY_DLOPEN_SELF # LT_SYS_DLOPEN_SELF # ------------------ AC_DEFUN([LT_SYS_DLOPEN_SELF], [m4_require([_LT_HEADER_DLFCN])dnl if test yes != "$enable_dlopen"; then enable_dlopen=unknown enable_dlopen_self=unknown enable_dlopen_self_static=unknown else lt_cv_dlopen=no lt_cv_dlopen_libs= case $host_os in beos*) lt_cv_dlopen=load_add_on lt_cv_dlopen_libs= lt_cv_dlopen_self=yes ;; mingw* | pw32* | cegcc*) lt_cv_dlopen=LoadLibrary lt_cv_dlopen_libs= ;; cygwin*) lt_cv_dlopen=dlopen lt_cv_dlopen_libs= ;; darwin*) # if libdl is installed we need to link against it AC_CHECK_LIB([dl], [dlopen], [lt_cv_dlopen=dlopen lt_cv_dlopen_libs=-ldl],[ lt_cv_dlopen=dyld lt_cv_dlopen_libs= lt_cv_dlopen_self=yes ]) ;; tpf*) # Don't try to run any link tests for TPF. We know it's impossible # because TPF is a cross-compiler, and we know how we open DSOs. lt_cv_dlopen=dlopen lt_cv_dlopen_libs= lt_cv_dlopen_self=no ;; *) AC_CHECK_FUNC([shl_load], [lt_cv_dlopen=shl_load], [AC_CHECK_LIB([dld], [shl_load], [lt_cv_dlopen=shl_load lt_cv_dlopen_libs=-ldld], [AC_CHECK_FUNC([dlopen], [lt_cv_dlopen=dlopen], [AC_CHECK_LIB([dl], [dlopen], [lt_cv_dlopen=dlopen lt_cv_dlopen_libs=-ldl], [AC_CHECK_LIB([svld], [dlopen], [lt_cv_dlopen=dlopen lt_cv_dlopen_libs=-lsvld], [AC_CHECK_LIB([dld], [dld_link], [lt_cv_dlopen=dld_link lt_cv_dlopen_libs=-ldld]) ]) ]) ]) ]) ]) ;; esac if test no = "$lt_cv_dlopen"; then enable_dlopen=no else enable_dlopen=yes fi case $lt_cv_dlopen in dlopen) save_CPPFLAGS=$CPPFLAGS test yes = "$ac_cv_header_dlfcn_h" && CPPFLAGS="$CPPFLAGS -DHAVE_DLFCN_H" save_LDFLAGS=$LDFLAGS wl=$lt_prog_compiler_wl eval LDFLAGS=\"\$LDFLAGS $export_dynamic_flag_spec\" save_LIBS=$LIBS LIBS="$lt_cv_dlopen_libs $LIBS" AC_CACHE_CHECK([whether a program can dlopen itself], lt_cv_dlopen_self, [dnl _LT_TRY_DLOPEN_SELF( lt_cv_dlopen_self=yes, lt_cv_dlopen_self=yes, lt_cv_dlopen_self=no, lt_cv_dlopen_self=cross) ]) if test yes = "$lt_cv_dlopen_self"; then wl=$lt_prog_compiler_wl eval LDFLAGS=\"\$LDFLAGS $lt_prog_compiler_static\" AC_CACHE_CHECK([whether a statically linked program can dlopen itself], lt_cv_dlopen_self_static, [dnl _LT_TRY_DLOPEN_SELF( lt_cv_dlopen_self_static=yes, lt_cv_dlopen_self_static=yes, lt_cv_dlopen_self_static=no, lt_cv_dlopen_self_static=cross) ]) fi CPPFLAGS=$save_CPPFLAGS LDFLAGS=$save_LDFLAGS LIBS=$save_LIBS ;; esac case $lt_cv_dlopen_self in yes|no) enable_dlopen_self=$lt_cv_dlopen_self ;; *) enable_dlopen_self=unknown ;; esac case $lt_cv_dlopen_self_static in yes|no) enable_dlopen_self_static=$lt_cv_dlopen_self_static ;; *) enable_dlopen_self_static=unknown ;; esac fi _LT_DECL([dlopen_support], [enable_dlopen], [0], [Whether dlopen is supported]) _LT_DECL([dlopen_self], [enable_dlopen_self], [0], [Whether dlopen of programs is supported]) _LT_DECL([dlopen_self_static], [enable_dlopen_self_static], [0], [Whether dlopen of statically linked programs is supported]) ])# LT_SYS_DLOPEN_SELF # Old name: AU_ALIAS([AC_LIBTOOL_DLOPEN_SELF], [LT_SYS_DLOPEN_SELF]) dnl aclocal-1.4 backwards compatibility: dnl AC_DEFUN([AC_LIBTOOL_DLOPEN_SELF], []) # _LT_COMPILER_C_O([TAGNAME]) # --------------------------- # Check to see if options -c and -o are simultaneously supported by compiler. # This macro does not hard code the compiler like AC_PROG_CC_C_O. m4_defun([_LT_COMPILER_C_O], [m4_require([_LT_DECL_SED])dnl m4_require([_LT_FILEUTILS_DEFAULTS])dnl m4_require([_LT_TAG_COMPILER])dnl AC_CACHE_CHECK([if $compiler supports -c -o file.$ac_objext], [_LT_TAGVAR(lt_cv_prog_compiler_c_o, $1)], [_LT_TAGVAR(lt_cv_prog_compiler_c_o, $1)=no $RM -r conftest 2>/dev/null mkdir conftest cd conftest mkdir out echo "$lt_simple_compile_test_code" > conftest.$ac_ext lt_compiler_flag="-o out/conftest2.$ac_objext" # Insert the option either (1) after the last *FLAGS variable, or # (2) before a word containing "conftest.", or (3) at the end. # Note that $ac_compile itself does not contain backslashes and begins # with a dollar sign (not a hyphen), so the echo should work correctly. lt_compile=`echo "$ac_compile" | $SED \ -e 's:.*FLAGS}\{0,1\} :&$lt_compiler_flag :; t' \ -e 's: [[^ ]]*conftest\.: $lt_compiler_flag&:; t' \ -e 's:$: $lt_compiler_flag:'` (eval echo "\"\$as_me:$LINENO: $lt_compile\"" >&AS_MESSAGE_LOG_FD) (eval "$lt_compile" 2>out/conftest.err) ac_status=$? cat out/conftest.err >&AS_MESSAGE_LOG_FD echo "$as_me:$LINENO: \$? = $ac_status" >&AS_MESSAGE_LOG_FD if (exit $ac_status) && test -s out/conftest2.$ac_objext then # The compiler can only warn and ignore the option if not recognized # So say no if there are warnings $ECHO "$_lt_compiler_boilerplate" | $SED '/^$/d' > out/conftest.exp $SED '/^$/d; /^ *+/d' out/conftest.err >out/conftest.er2 if test ! -s out/conftest.er2 || diff out/conftest.exp out/conftest.er2 >/dev/null; then _LT_TAGVAR(lt_cv_prog_compiler_c_o, $1)=yes fi fi chmod u+w . 2>&AS_MESSAGE_LOG_FD $RM conftest* # SGI C++ compiler will create directory out/ii_files/ for # template instantiation test -d out/ii_files && $RM out/ii_files/* && rmdir out/ii_files $RM out/* && rmdir out cd .. $RM -r conftest $RM conftest* ]) _LT_TAGDECL([compiler_c_o], [lt_cv_prog_compiler_c_o], [1], [Does compiler simultaneously support -c and -o options?]) ])# _LT_COMPILER_C_O # _LT_COMPILER_FILE_LOCKS([TAGNAME]) # ---------------------------------- # Check to see if we can do hard links to lock some files if needed m4_defun([_LT_COMPILER_FILE_LOCKS], [m4_require([_LT_ENABLE_LOCK])dnl m4_require([_LT_FILEUTILS_DEFAULTS])dnl _LT_COMPILER_C_O([$1]) hard_links=nottested if test no = "$_LT_TAGVAR(lt_cv_prog_compiler_c_o, $1)" && test no != "$need_locks"; then # do not overwrite the value of need_locks provided by the user AC_MSG_CHECKING([if we can lock with hard links]) hard_links=yes $RM conftest* ln conftest.a conftest.b 2>/dev/null && hard_links=no touch conftest.a ln conftest.a conftest.b 2>&5 || hard_links=no ln conftest.a conftest.b 2>/dev/null && hard_links=no AC_MSG_RESULT([$hard_links]) if test no = "$hard_links"; then AC_MSG_WARN(['$CC' does not support '-c -o', so 'make -j' may be unsafe]) need_locks=warn fi else need_locks=no fi _LT_DECL([], [need_locks], [1], [Must we lock files when doing compilation?]) ])# _LT_COMPILER_FILE_LOCKS # _LT_CHECK_OBJDIR # ---------------- m4_defun([_LT_CHECK_OBJDIR], [AC_CACHE_CHECK([for objdir], [lt_cv_objdir], [rm -f .libs 2>/dev/null mkdir .libs 2>/dev/null if test -d .libs; then lt_cv_objdir=.libs else # MS-DOS does not allow filenames that begin with a dot. lt_cv_objdir=_libs fi rmdir .libs 2>/dev/null]) objdir=$lt_cv_objdir _LT_DECL([], [objdir], [0], [The name of the directory that contains temporary libtool files])dnl m4_pattern_allow([LT_OBJDIR])dnl AC_DEFINE_UNQUOTED([LT_OBJDIR], "$lt_cv_objdir/", [Define to the sub-directory where libtool stores uninstalled libraries.]) ])# _LT_CHECK_OBJDIR # _LT_LINKER_HARDCODE_LIBPATH([TAGNAME]) # -------------------------------------- # Check hardcoding attributes. m4_defun([_LT_LINKER_HARDCODE_LIBPATH], [AC_MSG_CHECKING([how to hardcode library paths into programs]) _LT_TAGVAR(hardcode_action, $1)= if test -n "$_LT_TAGVAR(hardcode_libdir_flag_spec, $1)" || test -n "$_LT_TAGVAR(runpath_var, $1)" || test yes = "$_LT_TAGVAR(hardcode_automatic, $1)"; then # We can hardcode non-existent directories. if test no != "$_LT_TAGVAR(hardcode_direct, $1)" && # If the only mechanism to avoid hardcoding is shlibpath_var, we # have to relink, otherwise we might link with an installed library # when we should be linking with a yet-to-be-installed one ## test no != "$_LT_TAGVAR(hardcode_shlibpath_var, $1)" && test no != "$_LT_TAGVAR(hardcode_minus_L, $1)"; then # Linking always hardcodes the temporary library directory. _LT_TAGVAR(hardcode_action, $1)=relink else # We can link without hardcoding, and we can hardcode nonexisting dirs. _LT_TAGVAR(hardcode_action, $1)=immediate fi else # We cannot hardcode anything, or else we can only hardcode existing # directories. _LT_TAGVAR(hardcode_action, $1)=unsupported fi AC_MSG_RESULT([$_LT_TAGVAR(hardcode_action, $1)]) if test relink = "$_LT_TAGVAR(hardcode_action, $1)" || test yes = "$_LT_TAGVAR(inherit_rpath, $1)"; then # Fast installation is not supported enable_fast_install=no elif test yes = "$shlibpath_overrides_runpath" || test no = "$enable_shared"; then # Fast installation is not necessary enable_fast_install=needless fi _LT_TAGDECL([], [hardcode_action], [0], [How to hardcode a shared library path into an executable]) ])# _LT_LINKER_HARDCODE_LIBPATH # _LT_CMD_STRIPLIB # ---------------- m4_defun([_LT_CMD_STRIPLIB], [m4_require([_LT_DECL_EGREP]) striplib= old_striplib= AC_MSG_CHECKING([whether stripping libraries is possible]) if test -n "$STRIP" && $STRIP -V 2>&1 | $GREP "GNU strip" >/dev/null; then test -z "$old_striplib" && old_striplib="$STRIP --strip-debug" test -z "$striplib" && striplib="$STRIP --strip-unneeded" AC_MSG_RESULT([yes]) else # FIXME - insert some real tests, host_os isn't really good enough case $host_os in darwin*) if test -n "$STRIP"; then striplib="$STRIP -x" old_striplib="$STRIP -S" AC_MSG_RESULT([yes]) else AC_MSG_RESULT([no]) fi ;; *) AC_MSG_RESULT([no]) ;; esac fi _LT_DECL([], [old_striplib], [1], [Commands to strip libraries]) _LT_DECL([], [striplib], [1]) ])# _LT_CMD_STRIPLIB # _LT_PREPARE_MUNGE_PATH_LIST # --------------------------- # Make sure func_munge_path_list() is defined correctly. m4_defun([_LT_PREPARE_MUNGE_PATH_LIST], [[# func_munge_path_list VARIABLE PATH # ----------------------------------- # VARIABLE is name of variable containing _space_ separated list of # directories to be munged by the contents of PATH, which is string # having a format: # "DIR[:DIR]:" # string "DIR[ DIR]" will be prepended to VARIABLE # ":DIR[:DIR]" # string "DIR[ DIR]" will be appended to VARIABLE # "DIRP[:DIRP]::[DIRA:]DIRA" # string "DIRP[ DIRP]" will be prepended to VARIABLE and string # "DIRA[ DIRA]" will be appended to VARIABLE # "DIR[:DIR]" # VARIABLE will be replaced by "DIR[ DIR]" func_munge_path_list () { case x@S|@2 in x) ;; *:) eval @S|@1=\"`$ECHO @S|@2 | $SED 's/:/ /g'` \@S|@@S|@1\" ;; x:*) eval @S|@1=\"\@S|@@S|@1 `$ECHO @S|@2 | $SED 's/:/ /g'`\" ;; *::*) eval @S|@1=\"\@S|@@S|@1\ `$ECHO @S|@2 | $SED -e 's/.*:://' -e 's/:/ /g'`\" eval @S|@1=\"`$ECHO @S|@2 | $SED -e 's/::.*//' -e 's/:/ /g'`\ \@S|@@S|@1\" ;; *) eval @S|@1=\"`$ECHO @S|@2 | $SED 's/:/ /g'`\" ;; esac } ]])# _LT_PREPARE_PATH_LIST # _LT_SYS_DYNAMIC_LINKER([TAG]) # ----------------------------- # PORTME Fill in your ld.so characteristics m4_defun([_LT_SYS_DYNAMIC_LINKER], [AC_REQUIRE([AC_CANONICAL_HOST])dnl m4_require([_LT_DECL_EGREP])dnl m4_require([_LT_FILEUTILS_DEFAULTS])dnl m4_require([_LT_DECL_OBJDUMP])dnl m4_require([_LT_DECL_SED])dnl m4_require([_LT_CHECK_SHELL_FEATURES])dnl m4_require([_LT_PREPARE_MUNGE_PATH_LIST])dnl AC_MSG_CHECKING([dynamic linker characteristics]) m4_if([$1], [], [ if test yes = "$GCC"; then case $host_os in darwin*) lt_awk_arg='/^libraries:/,/LR/' ;; *) lt_awk_arg='/^libraries:/' ;; esac case $host_os in mingw* | cegcc*) lt_sed_strip_eq='s|=\([[A-Za-z]]:\)|\1|g' ;; *) lt_sed_strip_eq='s|=/|/|g' ;; esac lt_search_path_spec=`$CC -print-search-dirs | awk $lt_awk_arg | $SED -e "s/^libraries://" -e $lt_sed_strip_eq` case $lt_search_path_spec in *\;*) # if the path contains ";" then we assume it to be the separator # otherwise default to the standard path separator (i.e. ":") - it is # assumed that no part of a normal pathname contains ";" but that should # okay in the real world where ";" in dirpaths is itself problematic. lt_search_path_spec=`$ECHO "$lt_search_path_spec" | $SED 's/;/ /g'` ;; *) lt_search_path_spec=`$ECHO "$lt_search_path_spec" | $SED "s/$PATH_SEPARATOR/ /g"` ;; esac # Ok, now we have the path, separated by spaces, we can step through it # and add multilib dir if necessary... lt_tmp_lt_search_path_spec= lt_multi_os_dir=/`$CC $CPPFLAGS $CFLAGS $LDFLAGS -print-multi-os-directory 2>/dev/null` # ...but if some path component already ends with the multilib dir we assume # that all is fine and trust -print-search-dirs as is (GCC 4.2? or newer). case "$lt_multi_os_dir; $lt_search_path_spec " in "/; "* | "/.; "* | "/./; "* | *"$lt_multi_os_dir "* | *"$lt_multi_os_dir/ "*) lt_multi_os_dir= ;; esac for lt_sys_path in $lt_search_path_spec; do if test -d "$lt_sys_path$lt_multi_os_dir"; then lt_tmp_lt_search_path_spec="$lt_tmp_lt_search_path_spec $lt_sys_path$lt_multi_os_dir" elif test -n "$lt_multi_os_dir"; then test -d "$lt_sys_path" && \ lt_tmp_lt_search_path_spec="$lt_tmp_lt_search_path_spec $lt_sys_path" fi done lt_search_path_spec=`$ECHO "$lt_tmp_lt_search_path_spec" | awk ' BEGIN {RS = " "; FS = "/|\n";} { lt_foo = ""; lt_count = 0; for (lt_i = NF; lt_i > 0; lt_i--) { if ($lt_i != "" && $lt_i != ".") { if ($lt_i == "..") { lt_count++; } else { if (lt_count == 0) { lt_foo = "/" $lt_i lt_foo; } else { lt_count--; } } } } if (lt_foo != "") { lt_freq[[lt_foo]]++; } if (lt_freq[[lt_foo]] == 1) { print lt_foo; } }'` # AWK program above erroneously prepends '/' to C:/dos/paths # for these hosts. case $host_os in mingw* | cegcc*) lt_search_path_spec=`$ECHO "$lt_search_path_spec" |\ $SED 's|/\([[A-Za-z]]:\)|\1|g'` ;; esac sys_lib_search_path_spec=`$ECHO "$lt_search_path_spec" | $lt_NL2SP` else sys_lib_search_path_spec="/lib /usr/lib /usr/local/lib" fi]) library_names_spec= libname_spec='lib$name' soname_spec= shrext_cmds=.so postinstall_cmds= postuninstall_cmds= finish_cmds= finish_eval= shlibpath_var= shlibpath_overrides_runpath=unknown version_type=none dynamic_linker="$host_os ld.so" sys_lib_dlsearch_path_spec="/lib /usr/lib" need_lib_prefix=unknown hardcode_into_libs=no # when you set need_version to no, make sure it does not cause -set_version # flags to be left without arguments need_version=unknown AC_ARG_VAR([LT_SYS_LIBRARY_PATH], [User-defined run-time library search path.]) case $host_os in aix3*) version_type=linux # correct to gnu/linux during the next big refactor library_names_spec='$libname$release$shared_ext$versuffix $libname.a' shlibpath_var=LIBPATH # AIX 3 has no versioning support, so we append a major version to the name. soname_spec='$libname$release$shared_ext$major' ;; aix[[4-9]]*) version_type=linux # correct to gnu/linux during the next big refactor need_lib_prefix=no need_version=no hardcode_into_libs=yes if test ia64 = "$host_cpu"; then # AIX 5 supports IA64 library_names_spec='$libname$release$shared_ext$major $libname$release$shared_ext$versuffix $libname$shared_ext' shlibpath_var=LD_LIBRARY_PATH else # With GCC up to 2.95.x, collect2 would create an import file # for dependence libraries. The import file would start with # the line '#! .'. This would cause the generated library to # depend on '.', always an invalid library. This was fixed in # development snapshots of GCC prior to 3.0. case $host_os in aix4 | aix4.[[01]] | aix4.[[01]].*) if { echo '#if __GNUC__ > 2 || (__GNUC__ == 2 && __GNUC_MINOR__ >= 97)' echo ' yes ' echo '#endif'; } | $CC -E - | $GREP yes > /dev/null; then : else can_build_shared=no fi ;; esac # Using Import Files as archive members, it is possible to support # filename-based versioning of shared library archives on AIX. While # this would work for both with and without runtime linking, it will # prevent static linking of such archives. So we do filename-based # shared library versioning with .so extension only, which is used # when both runtime linking and shared linking is enabled. # Unfortunately, runtime linking may impact performance, so we do # not want this to be the default eventually. Also, we use the # versioned .so libs for executables only if there is the -brtl # linker flag in LDFLAGS as well, or --with-aix-soname=svr4 only. # To allow for filename-based versioning support, we need to create # libNAME.so.V as an archive file, containing: # *) an Import File, referring to the versioned filename of the # archive as well as the shared archive member, telling the # bitwidth (32 or 64) of that shared object, and providing the # list of exported symbols of that shared object, eventually # decorated with the 'weak' keyword # *) the shared object with the F_LOADONLY flag set, to really avoid # it being seen by the linker. # At run time we better use the real file rather than another symlink, # but for link time we create the symlink libNAME.so -> libNAME.so.V case $with_aix_soname,$aix_use_runtimelinking in # AIX (on Power*) has no versioning support, so currently we cannot hardcode correct # soname into executable. Probably we can add versioning support to # collect2, so additional links can be useful in future. aix,yes) # traditional libtool dynamic_linker='AIX unversionable lib.so' # If using run time linking (on AIX 4.2 or later) use lib.so # instead of lib.a to let people know that these are not # typical AIX shared libraries. library_names_spec='$libname$release$shared_ext$versuffix $libname$release$shared_ext$major $libname$shared_ext' ;; aix,no) # traditional AIX only dynamic_linker='AIX lib.a[(]lib.so.V[)]' # We preserve .a as extension for shared libraries through AIX4.2 # and later when we are not doing run time linking. library_names_spec='$libname$release.a $libname.a' soname_spec='$libname$release$shared_ext$major' ;; svr4,*) # full svr4 only dynamic_linker="AIX lib.so.V[(]$shared_archive_member_spec.o[)]" library_names_spec='$libname$release$shared_ext$major $libname$shared_ext' # We do not specify a path in Import Files, so LIBPATH fires. shlibpath_overrides_runpath=yes ;; *,yes) # both, prefer svr4 dynamic_linker="AIX lib.so.V[(]$shared_archive_member_spec.o[)], lib.a[(]lib.so.V[)]" library_names_spec='$libname$release$shared_ext$major $libname$shared_ext' # unpreferred sharedlib libNAME.a needs extra handling postinstall_cmds='test -n "$linkname" || linkname="$realname"~func_stripname "" ".so" "$linkname"~$install_shared_prog "$dir/$func_stripname_result.$libext" "$destdir/$func_stripname_result.$libext"~test -z "$tstripme" || test -z "$striplib" || $striplib "$destdir/$func_stripname_result.$libext"' postuninstall_cmds='for n in $library_names $old_library; do :; done~func_stripname "" ".so" "$n"~test "$func_stripname_result" = "$n" || func_append rmfiles " $odir/$func_stripname_result.$libext"' # We do not specify a path in Import Files, so LIBPATH fires. shlibpath_overrides_runpath=yes ;; *,no) # both, prefer aix dynamic_linker="AIX lib.a[(]lib.so.V[)], lib.so.V[(]$shared_archive_member_spec.o[)]" library_names_spec='$libname$release.a $libname.a' soname_spec='$libname$release$shared_ext$major' # unpreferred sharedlib libNAME.so.V and symlink libNAME.so need extra handling postinstall_cmds='test -z "$dlname" || $install_shared_prog $dir/$dlname $destdir/$dlname~test -z "$tstripme" || test -z "$striplib" || $striplib $destdir/$dlname~test -n "$linkname" || linkname=$realname~func_stripname "" ".a" "$linkname"~(cd "$destdir" && $LN_S -f $dlname $func_stripname_result.so)' postuninstall_cmds='test -z "$dlname" || func_append rmfiles " $odir/$dlname"~for n in $old_library $library_names; do :; done~func_stripname "" ".a" "$n"~func_append rmfiles " $odir/$func_stripname_result.so"' ;; esac shlibpath_var=LIBPATH fi ;; amigaos*) case $host_cpu in powerpc) # Since July 2007 AmigaOS4 officially supports .so libraries. # When compiling the executable, add -use-dynld -Lsobjs: to the compileline. library_names_spec='$libname$release$shared_ext$versuffix $libname$release$shared_ext$major $libname$shared_ext' ;; m68k) library_names_spec='$libname.ixlibrary $libname.a' # Create ${libname}_ixlibrary.a entries in /sys/libs. finish_eval='for lib in `ls $libdir/*.ixlibrary 2>/dev/null`; do libname=`func_echo_all "$lib" | $SED '\''s%^.*/\([[^/]]*\)\.ixlibrary$%\1%'\''`; $RM /sys/libs/${libname}_ixlibrary.a; $show "cd /sys/libs && $LN_S $lib ${libname}_ixlibrary.a"; cd /sys/libs && $LN_S $lib ${libname}_ixlibrary.a || exit 1; done' ;; esac ;; beos*) library_names_spec='$libname$shared_ext' dynamic_linker="$host_os ld.so" shlibpath_var=LIBRARY_PATH ;; bsdi[[45]]*) version_type=linux # correct to gnu/linux during the next big refactor need_version=no library_names_spec='$libname$release$shared_ext$versuffix $libname$release$shared_ext$major $libname$shared_ext' soname_spec='$libname$release$shared_ext$major' finish_cmds='PATH="\$PATH:/sbin" ldconfig $libdir' shlibpath_var=LD_LIBRARY_PATH sys_lib_search_path_spec="/shlib /usr/lib /usr/X11/lib /usr/contrib/lib /lib /usr/local/lib" sys_lib_dlsearch_path_spec="/shlib /usr/lib /usr/local/lib" # the default ld.so.conf also contains /usr/contrib/lib and # /usr/X11R6/lib (/usr/X11 is a link to /usr/X11R6), but let us allow # libtool to hard-code these into programs ;; cygwin* | mingw* | pw32* | cegcc*) version_type=windows shrext_cmds=.dll need_version=no need_lib_prefix=no case $GCC,$cc_basename in yes,*) # gcc library_names_spec='$libname.dll.a' # DLL is installed to $(libdir)/../bin by postinstall_cmds postinstall_cmds='base_file=`basename \$file`~ dlpath=`$SHELL 2>&1 -c '\''. $dir/'\''\$base_file'\''i; echo \$dlname'\''`~ dldir=$destdir/`dirname \$dlpath`~ test -d \$dldir || mkdir -p \$dldir~ $install_prog $dir/$dlname \$dldir/$dlname~ chmod a+x \$dldir/$dlname~ if test -n '\''$stripme'\'' && test -n '\''$striplib'\''; then eval '\''$striplib \$dldir/$dlname'\'' || exit \$?; fi' postuninstall_cmds='dldll=`$SHELL 2>&1 -c '\''. $file; echo \$dlname'\''`~ dlpath=$dir/\$dldll~ $RM \$dlpath' shlibpath_overrides_runpath=yes case $host_os in cygwin*) # Cygwin DLLs use 'cyg' prefix rather than 'lib' soname_spec='`echo $libname | sed -e 's/^lib/cyg/'``echo $release | $SED -e 's/[[.]]/-/g'`$versuffix$shared_ext' m4_if([$1], [],[ sys_lib_search_path_spec="$sys_lib_search_path_spec /usr/lib/w32api"]) ;; mingw* | cegcc*) # MinGW DLLs use traditional 'lib' prefix soname_spec='$libname`echo $release | $SED -e 's/[[.]]/-/g'`$versuffix$shared_ext' ;; pw32*) # pw32 DLLs use 'pw' prefix rather than 'lib' library_names_spec='`echo $libname | sed -e 's/^lib/pw/'``echo $release | $SED -e 's/[[.]]/-/g'`$versuffix$shared_ext' ;; esac dynamic_linker='Win32 ld.exe' ;; *,cl*) # Native MSVC libname_spec='$name' soname_spec='$libname`echo $release | $SED -e 's/[[.]]/-/g'`$versuffix$shared_ext' library_names_spec='$libname.dll.lib' case $build_os in mingw*) sys_lib_search_path_spec= lt_save_ifs=$IFS IFS=';' for lt_path in $LIB do IFS=$lt_save_ifs # Let DOS variable expansion print the short 8.3 style file name. lt_path=`cd "$lt_path" 2>/dev/null && cmd //C "for %i in (".") do @echo %~si"` sys_lib_search_path_spec="$sys_lib_search_path_spec $lt_path" done IFS=$lt_save_ifs # Convert to MSYS style. sys_lib_search_path_spec=`$ECHO "$sys_lib_search_path_spec" | sed -e 's|\\\\|/|g' -e 's| \\([[a-zA-Z]]\\):| /\\1|g' -e 's|^ ||'` ;; cygwin*) # Convert to unix form, then to dos form, then back to unix form # but this time dos style (no spaces!) so that the unix form looks # like /cygdrive/c/PROGRA~1:/cygdr... sys_lib_search_path_spec=`cygpath --path --unix "$LIB"` sys_lib_search_path_spec=`cygpath --path --dos "$sys_lib_search_path_spec" 2>/dev/null` sys_lib_search_path_spec=`cygpath --path --unix "$sys_lib_search_path_spec" | $SED -e "s/$PATH_SEPARATOR/ /g"` ;; *) sys_lib_search_path_spec=$LIB if $ECHO "$sys_lib_search_path_spec" | [$GREP ';[c-zC-Z]:/' >/dev/null]; then # It is most probably a Windows format PATH. sys_lib_search_path_spec=`$ECHO "$sys_lib_search_path_spec" | $SED -e 's/;/ /g'` else sys_lib_search_path_spec=`$ECHO "$sys_lib_search_path_spec" | $SED -e "s/$PATH_SEPARATOR/ /g"` fi # FIXME: find the short name or the path components, as spaces are # common. (e.g. "Program Files" -> "PROGRA~1") ;; esac # DLL is installed to $(libdir)/../bin by postinstall_cmds postinstall_cmds='base_file=`basename \$file`~ dlpath=`$SHELL 2>&1 -c '\''. $dir/'\''\$base_file'\''i; echo \$dlname'\''`~ dldir=$destdir/`dirname \$dlpath`~ test -d \$dldir || mkdir -p \$dldir~ $install_prog $dir/$dlname \$dldir/$dlname' postuninstall_cmds='dldll=`$SHELL 2>&1 -c '\''. $file; echo \$dlname'\''`~ dlpath=$dir/\$dldll~ $RM \$dlpath' shlibpath_overrides_runpath=yes dynamic_linker='Win32 link.exe' ;; *) # Assume MSVC wrapper library_names_spec='$libname`echo $release | $SED -e 's/[[.]]/-/g'`$versuffix$shared_ext $libname.lib' dynamic_linker='Win32 ld.exe' ;; esac # FIXME: first we should search . and the directory the executable is in shlibpath_var=PATH ;; darwin* | rhapsody*) dynamic_linker="$host_os dyld" version_type=darwin need_lib_prefix=no need_version=no library_names_spec='$libname$release$major$shared_ext $libname$shared_ext' soname_spec='$libname$release$major$shared_ext' shlibpath_overrides_runpath=yes shlibpath_var=DYLD_LIBRARY_PATH shrext_cmds='`test .$module = .yes && echo .so || echo .dylib`' m4_if([$1], [],[ sys_lib_search_path_spec="$sys_lib_search_path_spec /usr/local/lib"]) sys_lib_dlsearch_path_spec='/usr/local/lib /lib /usr/lib' ;; dgux*) version_type=linux # correct to gnu/linux during the next big refactor need_lib_prefix=no need_version=no library_names_spec='$libname$release$shared_ext$versuffix $libname$release$shared_ext$major $libname$shared_ext' soname_spec='$libname$release$shared_ext$major' shlibpath_var=LD_LIBRARY_PATH ;; freebsd* | dragonfly*) # DragonFly does not have aout. When/if they implement a new # versioning mechanism, adjust this. if test -x /usr/bin/objformat; then objformat=`/usr/bin/objformat` else case $host_os in freebsd[[23]].*) objformat=aout ;; *) objformat=elf ;; esac fi version_type=freebsd-$objformat case $version_type in freebsd-elf*) library_names_spec='$libname$release$shared_ext$versuffix $libname$release$shared_ext$major $libname$shared_ext' soname_spec='$libname$release$shared_ext$major' need_version=no need_lib_prefix=no ;; freebsd-*) library_names_spec='$libname$release$shared_ext$versuffix $libname$shared_ext$versuffix' need_version=yes ;; esac shlibpath_var=LD_LIBRARY_PATH case $host_os in freebsd2.*) shlibpath_overrides_runpath=yes ;; freebsd3.[[01]]* | freebsdelf3.[[01]]*) shlibpath_overrides_runpath=yes hardcode_into_libs=yes ;; freebsd3.[[2-9]]* | freebsdelf3.[[2-9]]* | \ freebsd4.[[0-5]] | freebsdelf4.[[0-5]] | freebsd4.1.1 | freebsdelf4.1.1) shlibpath_overrides_runpath=no hardcode_into_libs=yes ;; *) # from 4.6 on, and DragonFly shlibpath_overrides_runpath=yes hardcode_into_libs=yes ;; esac ;; haiku*) version_type=linux # correct to gnu/linux during the next big refactor need_lib_prefix=no need_version=no dynamic_linker="$host_os runtime_loader" library_names_spec='$libname$release$shared_ext$versuffix $libname$release$shared_ext$major $libname$shared_ext' soname_spec='$libname$release$shared_ext$major' shlibpath_var=LIBRARY_PATH shlibpath_overrides_runpath=no sys_lib_dlsearch_path_spec='/boot/home/config/lib /boot/common/lib /boot/system/lib' hardcode_into_libs=yes ;; hpux9* | hpux10* | hpux11*) # Give a soname corresponding to the major version so that dld.sl refuses to # link against other versions. version_type=sunos need_lib_prefix=no need_version=no case $host_cpu in ia64*) shrext_cmds='.so' hardcode_into_libs=yes dynamic_linker="$host_os dld.so" shlibpath_var=LD_LIBRARY_PATH shlibpath_overrides_runpath=yes # Unless +noenvvar is specified. library_names_spec='$libname$release$shared_ext$versuffix $libname$release$shared_ext$major $libname$shared_ext' soname_spec='$libname$release$shared_ext$major' if test 32 = "$HPUX_IA64_MODE"; then sys_lib_search_path_spec="/usr/lib/hpux32 /usr/local/lib/hpux32 /usr/local/lib" sys_lib_dlsearch_path_spec=/usr/lib/hpux32 else sys_lib_search_path_spec="/usr/lib/hpux64 /usr/local/lib/hpux64" sys_lib_dlsearch_path_spec=/usr/lib/hpux64 fi ;; hppa*64*) shrext_cmds='.sl' hardcode_into_libs=yes dynamic_linker="$host_os dld.sl" shlibpath_var=LD_LIBRARY_PATH # How should we handle SHLIB_PATH shlibpath_overrides_runpath=yes # Unless +noenvvar is specified. library_names_spec='$libname$release$shared_ext$versuffix $libname$release$shared_ext$major $libname$shared_ext' soname_spec='$libname$release$shared_ext$major' sys_lib_search_path_spec="/usr/lib/pa20_64 /usr/ccs/lib/pa20_64" sys_lib_dlsearch_path_spec=$sys_lib_search_path_spec ;; *) shrext_cmds='.sl' dynamic_linker="$host_os dld.sl" shlibpath_var=SHLIB_PATH shlibpath_overrides_runpath=no # +s is required to enable SHLIB_PATH library_names_spec='$libname$release$shared_ext$versuffix $libname$release$shared_ext$major $libname$shared_ext' soname_spec='$libname$release$shared_ext$major' ;; esac # HP-UX runs *really* slowly unless shared libraries are mode 555, ... postinstall_cmds='chmod 555 $lib' # or fails outright, so override atomically: install_override_mode=555 ;; interix[[3-9]]*) version_type=linux # correct to gnu/linux during the next big refactor need_lib_prefix=no need_version=no library_names_spec='$libname$release$shared_ext$versuffix $libname$release$shared_ext$major $libname$shared_ext' soname_spec='$libname$release$shared_ext$major' dynamic_linker='Interix 3.x ld.so.1 (PE, like ELF)' shlibpath_var=LD_LIBRARY_PATH shlibpath_overrides_runpath=no hardcode_into_libs=yes ;; irix5* | irix6* | nonstopux*) case $host_os in nonstopux*) version_type=nonstopux ;; *) if test yes = "$lt_cv_prog_gnu_ld"; then version_type=linux # correct to gnu/linux during the next big refactor else version_type=irix fi ;; esac need_lib_prefix=no need_version=no soname_spec='$libname$release$shared_ext$major' library_names_spec='$libname$release$shared_ext$versuffix $libname$release$shared_ext$major $libname$release$shared_ext $libname$shared_ext' case $host_os in irix5* | nonstopux*) libsuff= shlibsuff= ;; *) case $LD in # libtool.m4 will add one of these switches to LD *-32|*"-32 "|*-melf32bsmip|*"-melf32bsmip ") libsuff= shlibsuff= libmagic=32-bit;; *-n32|*"-n32 "|*-melf32bmipn32|*"-melf32bmipn32 ") libsuff=32 shlibsuff=N32 libmagic=N32;; *-64|*"-64 "|*-melf64bmip|*"-melf64bmip ") libsuff=64 shlibsuff=64 libmagic=64-bit;; *) libsuff= shlibsuff= libmagic=never-match;; esac ;; esac shlibpath_var=LD_LIBRARY${shlibsuff}_PATH shlibpath_overrides_runpath=no sys_lib_search_path_spec="/usr/lib$libsuff /lib$libsuff /usr/local/lib$libsuff" sys_lib_dlsearch_path_spec="/usr/lib$libsuff /lib$libsuff" hardcode_into_libs=yes ;; # No shared lib support for Linux oldld, aout, or coff. linux*oldld* | linux*aout* | linux*coff*) dynamic_linker=no ;; linux*android*) version_type=none # Android doesn't support versioned libraries. need_lib_prefix=no need_version=no library_names_spec='$libname$release$shared_ext' soname_spec='$libname$release$shared_ext' finish_cmds= shlibpath_var=LD_LIBRARY_PATH shlibpath_overrides_runpath=yes # This implies no fast_install, which is unacceptable. # Some rework will be needed to allow for fast_install # before this can be enabled. hardcode_into_libs=yes dynamic_linker='Android linker' # Don't embed -rpath directories since the linker doesn't support them. _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-L$libdir' ;; # This must be glibc/ELF. linux* | k*bsd*-gnu | kopensolaris*-gnu | gnu*) version_type=linux # correct to gnu/linux during the next big refactor need_lib_prefix=no need_version=no library_names_spec='$libname$release$shared_ext$versuffix $libname$release$shared_ext$major $libname$shared_ext' soname_spec='$libname$release$shared_ext$major' finish_cmds='PATH="\$PATH:/sbin" ldconfig -n $libdir' shlibpath_var=LD_LIBRARY_PATH shlibpath_overrides_runpath=no # Some binutils ld are patched to set DT_RUNPATH AC_CACHE_VAL([lt_cv_shlibpath_overrides_runpath], [lt_cv_shlibpath_overrides_runpath=no save_LDFLAGS=$LDFLAGS save_libdir=$libdir eval "libdir=/foo; wl=\"$_LT_TAGVAR(lt_prog_compiler_wl, $1)\"; \ LDFLAGS=\"\$LDFLAGS $_LT_TAGVAR(hardcode_libdir_flag_spec, $1)\"" AC_LINK_IFELSE([AC_LANG_PROGRAM([],[])], [AS_IF([ ($OBJDUMP -p conftest$ac_exeext) 2>/dev/null | grep "RUNPATH.*$libdir" >/dev/null], [lt_cv_shlibpath_overrides_runpath=yes])]) LDFLAGS=$save_LDFLAGS libdir=$save_libdir ]) shlibpath_overrides_runpath=$lt_cv_shlibpath_overrides_runpath # This implies no fast_install, which is unacceptable. # Some rework will be needed to allow for fast_install # before this can be enabled. hardcode_into_libs=yes # Ideally, we could use ldconfig to report *all* directores which are # searched for libraries, however this is still not possible. Aside from not # being certain /sbin/ldconfig is available, command # 'ldconfig -N -X -v | grep ^/' on 64bit Fedora does not report /usr/lib64, # even though it is searched at run-time. Try to do the best guess by # appending ld.so.conf contents (and includes) to the search path. if test -f /etc/ld.so.conf; then lt_ld_extra=`awk '/^include / { system(sprintf("cd /etc; cat %s 2>/dev/null", \[$]2)); skip = 1; } { if (!skip) print \[$]0; skip = 0; }' < /etc/ld.so.conf | $SED -e 's/#.*//;/^[ ]*hwcap[ ]/d;s/[:, ]/ /g;s/=[^=]*$//;s/=[^= ]* / /g;s/"//g;/^$/d' | tr '\n' ' '` sys_lib_dlsearch_path_spec="/lib /usr/lib $lt_ld_extra" fi # We used to test for /lib/ld.so.1 and disable shared libraries on # powerpc, because MkLinux only supported shared libraries with the # GNU dynamic linker. Since this was broken with cross compilers, # most powerpc-linux boxes support dynamic linking these days and # people can always --disable-shared, the test was removed, and we # assume the GNU/Linux dynamic linker is in use. dynamic_linker='GNU/Linux ld.so' ;; netbsd*) version_type=sunos need_lib_prefix=no need_version=no if echo __ELF__ | $CC -E - | $GREP __ELF__ >/dev/null; then library_names_spec='$libname$release$shared_ext$versuffix $libname$shared_ext$versuffix' finish_cmds='PATH="\$PATH:/sbin" ldconfig -m $libdir' dynamic_linker='NetBSD (a.out) ld.so' else library_names_spec='$libname$release$shared_ext$versuffix $libname$release$shared_ext$major $libname$shared_ext' soname_spec='$libname$release$shared_ext$major' dynamic_linker='NetBSD ld.elf_so' fi shlibpath_var=LD_LIBRARY_PATH shlibpath_overrides_runpath=yes hardcode_into_libs=yes ;; newsos6) version_type=linux # correct to gnu/linux during the next big refactor library_names_spec='$libname$release$shared_ext$versuffix $libname$release$shared_ext$major $libname$shared_ext' shlibpath_var=LD_LIBRARY_PATH shlibpath_overrides_runpath=yes ;; *nto* | *qnx*) version_type=qnx need_lib_prefix=no need_version=no library_names_spec='$libname$release$shared_ext$versuffix $libname$release$shared_ext$major $libname$shared_ext' soname_spec='$libname$release$shared_ext$major' shlibpath_var=LD_LIBRARY_PATH shlibpath_overrides_runpath=no hardcode_into_libs=yes dynamic_linker='ldqnx.so' ;; openbsd* | bitrig*) version_type=sunos sys_lib_dlsearch_path_spec=/usr/lib need_lib_prefix=no if test -z "`echo __ELF__ | $CC -E - | $GREP __ELF__`"; then need_version=no else need_version=yes fi library_names_spec='$libname$release$shared_ext$versuffix $libname$shared_ext$versuffix' finish_cmds='PATH="\$PATH:/sbin" ldconfig -m $libdir' shlibpath_var=LD_LIBRARY_PATH shlibpath_overrides_runpath=yes ;; os2*) libname_spec='$name' version_type=windows shrext_cmds=.dll need_version=no need_lib_prefix=no # OS/2 can only load a DLL with a base name of 8 characters or less. soname_spec='`test -n "$os2dllname" && libname="$os2dllname"; v=$($ECHO $release$versuffix | tr -d .-); n=$($ECHO $libname | cut -b -$((8 - ${#v})) | tr . _); $ECHO $n$v`$shared_ext' library_names_spec='${libname}_dll.$libext' dynamic_linker='OS/2 ld.exe' shlibpath_var=BEGINLIBPATH sys_lib_search_path_spec="/lib /usr/lib /usr/local/lib" sys_lib_dlsearch_path_spec=$sys_lib_search_path_spec postinstall_cmds='base_file=`basename \$file`~ dlpath=`$SHELL 2>&1 -c '\''. $dir/'\''\$base_file'\''i; $ECHO \$dlname'\''`~ dldir=$destdir/`dirname \$dlpath`~ test -d \$dldir || mkdir -p \$dldir~ $install_prog $dir/$dlname \$dldir/$dlname~ chmod a+x \$dldir/$dlname~ if test -n '\''$stripme'\'' && test -n '\''$striplib'\''; then eval '\''$striplib \$dldir/$dlname'\'' || exit \$?; fi' postuninstall_cmds='dldll=`$SHELL 2>&1 -c '\''. $file; $ECHO \$dlname'\''`~ dlpath=$dir/\$dldll~ $RM \$dlpath' ;; osf3* | osf4* | osf5*) version_type=osf need_lib_prefix=no need_version=no soname_spec='$libname$release$shared_ext$major' library_names_spec='$libname$release$shared_ext$versuffix $libname$release$shared_ext$major $libname$shared_ext' shlibpath_var=LD_LIBRARY_PATH sys_lib_search_path_spec="/usr/shlib /usr/ccs/lib /usr/lib/cmplrs/cc /usr/lib /usr/local/lib /var/shlib" sys_lib_dlsearch_path_spec=$sys_lib_search_path_spec ;; rdos*) dynamic_linker=no ;; solaris*) version_type=linux # correct to gnu/linux during the next big refactor need_lib_prefix=no need_version=no library_names_spec='$libname$release$shared_ext$versuffix $libname$release$shared_ext$major $libname$shared_ext' soname_spec='$libname$release$shared_ext$major' shlibpath_var=LD_LIBRARY_PATH shlibpath_overrides_runpath=yes hardcode_into_libs=yes # ldd complains unless libraries are executable postinstall_cmds='chmod +x $lib' ;; sunos4*) version_type=sunos library_names_spec='$libname$release$shared_ext$versuffix $libname$shared_ext$versuffix' finish_cmds='PATH="\$PATH:/usr/etc" ldconfig $libdir' shlibpath_var=LD_LIBRARY_PATH shlibpath_overrides_runpath=yes if test yes = "$with_gnu_ld"; then need_lib_prefix=no fi need_version=yes ;; sysv4 | sysv4.3*) version_type=linux # correct to gnu/linux during the next big refactor library_names_spec='$libname$release$shared_ext$versuffix $libname$release$shared_ext$major $libname$shared_ext' soname_spec='$libname$release$shared_ext$major' shlibpath_var=LD_LIBRARY_PATH case $host_vendor in sni) shlibpath_overrides_runpath=no need_lib_prefix=no runpath_var=LD_RUN_PATH ;; siemens) need_lib_prefix=no ;; motorola) need_lib_prefix=no need_version=no shlibpath_overrides_runpath=no sys_lib_search_path_spec='/lib /usr/lib /usr/ccs/lib' ;; esac ;; sysv4*MP*) if test -d /usr/nec; then version_type=linux # correct to gnu/linux during the next big refactor library_names_spec='$libname$shared_ext.$versuffix $libname$shared_ext.$major $libname$shared_ext' soname_spec='$libname$shared_ext.$major' shlibpath_var=LD_LIBRARY_PATH fi ;; sysv5* | sco3.2v5* | sco5v6* | unixware* | OpenUNIX* | sysv4*uw2*) version_type=sco need_lib_prefix=no need_version=no library_names_spec='$libname$release$shared_ext$versuffix $libname$release$shared_ext $libname$shared_ext' soname_spec='$libname$release$shared_ext$major' shlibpath_var=LD_LIBRARY_PATH shlibpath_overrides_runpath=yes hardcode_into_libs=yes if test yes = "$with_gnu_ld"; then sys_lib_search_path_spec='/usr/local/lib /usr/gnu/lib /usr/ccs/lib /usr/lib /lib' else sys_lib_search_path_spec='/usr/ccs/lib /usr/lib' case $host_os in sco3.2v5*) sys_lib_search_path_spec="$sys_lib_search_path_spec /lib" ;; esac fi sys_lib_dlsearch_path_spec='/usr/lib' ;; tpf*) # TPF is a cross-target only. Preferred cross-host = GNU/Linux. version_type=linux # correct to gnu/linux during the next big refactor need_lib_prefix=no need_version=no library_names_spec='$libname$release$shared_ext$versuffix $libname$release$shared_ext$major $libname$shared_ext' shlibpath_var=LD_LIBRARY_PATH shlibpath_overrides_runpath=no hardcode_into_libs=yes ;; uts4*) version_type=linux # correct to gnu/linux during the next big refactor library_names_spec='$libname$release$shared_ext$versuffix $libname$release$shared_ext$major $libname$shared_ext' soname_spec='$libname$release$shared_ext$major' shlibpath_var=LD_LIBRARY_PATH ;; *) dynamic_linker=no ;; esac AC_MSG_RESULT([$dynamic_linker]) test no = "$dynamic_linker" && can_build_shared=no variables_saved_for_relink="PATH $shlibpath_var $runpath_var" if test yes = "$GCC"; then variables_saved_for_relink="$variables_saved_for_relink GCC_EXEC_PREFIX COMPILER_PATH LIBRARY_PATH" fi if test set = "${lt_cv_sys_lib_search_path_spec+set}"; then sys_lib_search_path_spec=$lt_cv_sys_lib_search_path_spec fi if test set = "${lt_cv_sys_lib_dlsearch_path_spec+set}"; then sys_lib_dlsearch_path_spec=$lt_cv_sys_lib_dlsearch_path_spec fi # remember unaugmented sys_lib_dlsearch_path content for libtool script decls... configure_time_dlsearch_path=$sys_lib_dlsearch_path_spec # ... but it needs LT_SYS_LIBRARY_PATH munging for other configure-time code func_munge_path_list sys_lib_dlsearch_path_spec "$LT_SYS_LIBRARY_PATH" # to be used as default LT_SYS_LIBRARY_PATH value in generated libtool configure_time_lt_sys_library_path=$LT_SYS_LIBRARY_PATH _LT_DECL([], [variables_saved_for_relink], [1], [Variables whose values should be saved in libtool wrapper scripts and restored at link time]) _LT_DECL([], [need_lib_prefix], [0], [Do we need the "lib" prefix for modules?]) _LT_DECL([], [need_version], [0], [Do we need a version for libraries?]) _LT_DECL([], [version_type], [0], [Library versioning type]) _LT_DECL([], [runpath_var], [0], [Shared library runtime path variable]) _LT_DECL([], [shlibpath_var], [0],[Shared library path variable]) _LT_DECL([], [shlibpath_overrides_runpath], [0], [Is shlibpath searched before the hard-coded library search path?]) _LT_DECL([], [libname_spec], [1], [Format of library name prefix]) _LT_DECL([], [library_names_spec], [1], [[List of archive names. First name is the real one, the rest are links. The last name is the one that the linker finds with -lNAME]]) _LT_DECL([], [soname_spec], [1], [[The coded name of the library, if different from the real name]]) _LT_DECL([], [install_override_mode], [1], [Permission mode override for installation of shared libraries]) _LT_DECL([], [postinstall_cmds], [2], [Command to use after installation of a shared archive]) _LT_DECL([], [postuninstall_cmds], [2], [Command to use after uninstallation of a shared archive]) _LT_DECL([], [finish_cmds], [2], [Commands used to finish a libtool library installation in a directory]) _LT_DECL([], [finish_eval], [1], [[As "finish_cmds", except a single script fragment to be evaled but not shown]]) _LT_DECL([], [hardcode_into_libs], [0], [Whether we should hardcode library paths into libraries]) _LT_DECL([], [sys_lib_search_path_spec], [2], [Compile-time system search path for libraries]) _LT_DECL([sys_lib_dlsearch_path_spec], [configure_time_dlsearch_path], [2], [Detected run-time system search path for libraries]) _LT_DECL([], [configure_time_lt_sys_library_path], [2], [Explicit LT_SYS_LIBRARY_PATH set during ./configure time]) ])# _LT_SYS_DYNAMIC_LINKER # _LT_PATH_TOOL_PREFIX(TOOL) # -------------------------- # find a file program that can recognize shared library AC_DEFUN([_LT_PATH_TOOL_PREFIX], [m4_require([_LT_DECL_EGREP])dnl AC_MSG_CHECKING([for $1]) AC_CACHE_VAL(lt_cv_path_MAGIC_CMD, [case $MAGIC_CMD in [[\\/*] | ?:[\\/]*]) lt_cv_path_MAGIC_CMD=$MAGIC_CMD # Let the user override the test with a path. ;; *) lt_save_MAGIC_CMD=$MAGIC_CMD lt_save_ifs=$IFS; IFS=$PATH_SEPARATOR dnl $ac_dummy forces splitting on constant user-supplied paths. dnl POSIX.2 word splitting is done only on the output of word expansions, dnl not every word. This closes a longstanding sh security hole. ac_dummy="m4_if([$2], , $PATH, [$2])" for ac_dir in $ac_dummy; do IFS=$lt_save_ifs test -z "$ac_dir" && ac_dir=. if test -f "$ac_dir/$1"; then lt_cv_path_MAGIC_CMD=$ac_dir/"$1" if test -n "$file_magic_test_file"; then case $deplibs_check_method in "file_magic "*) file_magic_regex=`expr "$deplibs_check_method" : "file_magic \(.*\)"` MAGIC_CMD=$lt_cv_path_MAGIC_CMD if eval $file_magic_cmd \$file_magic_test_file 2> /dev/null | $EGREP "$file_magic_regex" > /dev/null; then : else cat <<_LT_EOF 1>&2 *** Warning: the command libtool uses to detect shared libraries, *** $file_magic_cmd, produces output that libtool cannot recognize. *** The result is that libtool may fail to recognize shared libraries *** as such. This will affect the creation of libtool libraries that *** depend on shared libraries, but programs linked with such libtool *** libraries will work regardless of this problem. Nevertheless, you *** may want to report the problem to your system manager and/or to *** bug-libtool@gnu.org _LT_EOF fi ;; esac fi break fi done IFS=$lt_save_ifs MAGIC_CMD=$lt_save_MAGIC_CMD ;; esac]) MAGIC_CMD=$lt_cv_path_MAGIC_CMD if test -n "$MAGIC_CMD"; then AC_MSG_RESULT($MAGIC_CMD) else AC_MSG_RESULT(no) fi _LT_DECL([], [MAGIC_CMD], [0], [Used to examine libraries when file_magic_cmd begins with "file"])dnl ])# _LT_PATH_TOOL_PREFIX # Old name: AU_ALIAS([AC_PATH_TOOL_PREFIX], [_LT_PATH_TOOL_PREFIX]) dnl aclocal-1.4 backwards compatibility: dnl AC_DEFUN([AC_PATH_TOOL_PREFIX], []) # _LT_PATH_MAGIC # -------------- # find a file program that can recognize a shared library m4_defun([_LT_PATH_MAGIC], [_LT_PATH_TOOL_PREFIX(${ac_tool_prefix}file, /usr/bin$PATH_SEPARATOR$PATH) if test -z "$lt_cv_path_MAGIC_CMD"; then if test -n "$ac_tool_prefix"; then _LT_PATH_TOOL_PREFIX(file, /usr/bin$PATH_SEPARATOR$PATH) else MAGIC_CMD=: fi fi ])# _LT_PATH_MAGIC # LT_PATH_LD # ---------- # find the pathname to the GNU or non-GNU linker AC_DEFUN([LT_PATH_LD], [AC_REQUIRE([AC_PROG_CC])dnl AC_REQUIRE([AC_CANONICAL_HOST])dnl AC_REQUIRE([AC_CANONICAL_BUILD])dnl m4_require([_LT_DECL_SED])dnl m4_require([_LT_DECL_EGREP])dnl m4_require([_LT_PROG_ECHO_BACKSLASH])dnl AC_ARG_WITH([gnu-ld], [AS_HELP_STRING([--with-gnu-ld], [assume the C compiler uses GNU ld @<:@default=no@:>@])], [test no = "$withval" || with_gnu_ld=yes], [with_gnu_ld=no])dnl ac_prog=ld if test yes = "$GCC"; then # Check if gcc -print-prog-name=ld gives a path. AC_MSG_CHECKING([for ld used by $CC]) case $host in *-*-mingw*) # gcc leaves a trailing carriage return, which upsets mingw ac_prog=`($CC -print-prog-name=ld) 2>&5 | tr -d '\015'` ;; *) ac_prog=`($CC -print-prog-name=ld) 2>&5` ;; esac case $ac_prog in # Accept absolute paths. [[\\/]]* | ?:[[\\/]]*) re_direlt='/[[^/]][[^/]]*/\.\./' # Canonicalize the pathname of ld ac_prog=`$ECHO "$ac_prog"| $SED 's%\\\\%/%g'` while $ECHO "$ac_prog" | $GREP "$re_direlt" > /dev/null 2>&1; do ac_prog=`$ECHO $ac_prog| $SED "s%$re_direlt%/%"` done test -z "$LD" && LD=$ac_prog ;; "") # If it fails, then pretend we aren't using GCC. ac_prog=ld ;; *) # If it is relative, then search for the first ld in PATH. with_gnu_ld=unknown ;; esac elif test yes = "$with_gnu_ld"; then AC_MSG_CHECKING([for GNU ld]) else AC_MSG_CHECKING([for non-GNU ld]) fi AC_CACHE_VAL(lt_cv_path_LD, [if test -z "$LD"; then lt_save_ifs=$IFS; IFS=$PATH_SEPARATOR for ac_dir in $PATH; do IFS=$lt_save_ifs test -z "$ac_dir" && ac_dir=. if test -f "$ac_dir/$ac_prog" || test -f "$ac_dir/$ac_prog$ac_exeext"; then lt_cv_path_LD=$ac_dir/$ac_prog # Check to see if the program is GNU ld. I'd rather use --version, # but apparently some variants of GNU ld only accept -v. # Break only if it was the GNU/non-GNU ld that we prefer. case `"$lt_cv_path_LD" -v 2>&1 &1 conftest.i cat conftest.i conftest.i >conftest2.i : ${lt_DD:=$DD} AC_PATH_PROGS_FEATURE_CHECK([lt_DD], [dd], [if "$ac_path_lt_DD" bs=32 count=1 conftest.out 2>/dev/null; then cmp -s conftest.i conftest.out \ && ac_cv_path_lt_DD="$ac_path_lt_DD" ac_path_lt_DD_found=: fi]) rm -f conftest.i conftest2.i conftest.out]) ])# _LT_PATH_DD # _LT_CMD_TRUNCATE # ---------------- # find command to truncate a binary pipe m4_defun([_LT_CMD_TRUNCATE], [m4_require([_LT_PATH_DD]) AC_CACHE_CHECK([how to truncate binary pipes], [lt_cv_truncate_bin], [printf 0123456789abcdef0123456789abcdef >conftest.i cat conftest.i conftest.i >conftest2.i lt_cv_truncate_bin= if "$ac_cv_path_lt_DD" bs=32 count=1 conftest.out 2>/dev/null; then cmp -s conftest.i conftest.out \ && lt_cv_truncate_bin="$ac_cv_path_lt_DD bs=4096 count=1" fi rm -f conftest.i conftest2.i conftest.out test -z "$lt_cv_truncate_bin" && lt_cv_truncate_bin="$SED -e 4q"]) _LT_DECL([lt_truncate_bin], [lt_cv_truncate_bin], [1], [Command to truncate a binary pipe]) ])# _LT_CMD_TRUNCATE # _LT_CHECK_MAGIC_METHOD # ---------------------- # how to check for library dependencies # -- PORTME fill in with the dynamic library characteristics m4_defun([_LT_CHECK_MAGIC_METHOD], [m4_require([_LT_DECL_EGREP]) m4_require([_LT_DECL_OBJDUMP]) AC_CACHE_CHECK([how to recognize dependent libraries], lt_cv_deplibs_check_method, [lt_cv_file_magic_cmd='$MAGIC_CMD' lt_cv_file_magic_test_file= lt_cv_deplibs_check_method='unknown' # Need to set the preceding variable on all platforms that support # interlibrary dependencies. # 'none' -- dependencies not supported. # 'unknown' -- same as none, but documents that we really don't know. # 'pass_all' -- all dependencies passed with no checks. # 'test_compile' -- check by making test program. # 'file_magic [[regex]]' -- check by looking for files in library path # that responds to the $file_magic_cmd with a given extended regex. # If you have 'file' or equivalent on your system and you're not sure # whether 'pass_all' will *always* work, you probably want this one. case $host_os in aix[[4-9]]*) lt_cv_deplibs_check_method=pass_all ;; beos*) lt_cv_deplibs_check_method=pass_all ;; bsdi[[45]]*) lt_cv_deplibs_check_method='file_magic ELF [[0-9]][[0-9]]*-bit [[ML]]SB (shared object|dynamic lib)' lt_cv_file_magic_cmd='/usr/bin/file -L' lt_cv_file_magic_test_file=/shlib/libc.so ;; cygwin*) # func_win32_libid is a shell function defined in ltmain.sh lt_cv_deplibs_check_method='file_magic ^x86 archive import|^x86 DLL' lt_cv_file_magic_cmd='func_win32_libid' ;; mingw* | pw32*) # Base MSYS/MinGW do not provide the 'file' command needed by # func_win32_libid shell function, so use a weaker test based on 'objdump', # unless we find 'file', for example because we are cross-compiling. if ( file / ) >/dev/null 2>&1; then lt_cv_deplibs_check_method='file_magic ^x86 archive import|^x86 DLL' lt_cv_file_magic_cmd='func_win32_libid' else # Keep this pattern in sync with the one in func_win32_libid. lt_cv_deplibs_check_method='file_magic file format (pei*-i386(.*architecture: i386)?|pe-arm-wince|pe-x86-64)' lt_cv_file_magic_cmd='$OBJDUMP -f' fi ;; cegcc*) # use the weaker test based on 'objdump'. See mingw*. lt_cv_deplibs_check_method='file_magic file format pe-arm-.*little(.*architecture: arm)?' lt_cv_file_magic_cmd='$OBJDUMP -f' ;; darwin* | rhapsody*) lt_cv_deplibs_check_method=pass_all ;; freebsd* | dragonfly*) if echo __ELF__ | $CC -E - | $GREP __ELF__ > /dev/null; then case $host_cpu in i*86 ) # Not sure whether the presence of OpenBSD here was a mistake. # Let's accept both of them until this is cleared up. lt_cv_deplibs_check_method='file_magic (FreeBSD|OpenBSD|DragonFly)/i[[3-9]]86 (compact )?demand paged shared library' lt_cv_file_magic_cmd=/usr/bin/file lt_cv_file_magic_test_file=`echo /usr/lib/libc.so.*` ;; esac else lt_cv_deplibs_check_method=pass_all fi ;; haiku*) lt_cv_deplibs_check_method=pass_all ;; hpux10.20* | hpux11*) lt_cv_file_magic_cmd=/usr/bin/file case $host_cpu in ia64*) lt_cv_deplibs_check_method='file_magic (s[[0-9]][[0-9]][[0-9]]|ELF-[[0-9]][[0-9]]) shared object file - IA64' lt_cv_file_magic_test_file=/usr/lib/hpux32/libc.so ;; hppa*64*) [lt_cv_deplibs_check_method='file_magic (s[0-9][0-9][0-9]|ELF[ -][0-9][0-9])(-bit)?( [LM]SB)? shared object( file)?[, -]* PA-RISC [0-9]\.[0-9]'] lt_cv_file_magic_test_file=/usr/lib/pa20_64/libc.sl ;; *) lt_cv_deplibs_check_method='file_magic (s[[0-9]][[0-9]][[0-9]]|PA-RISC[[0-9]]\.[[0-9]]) shared library' lt_cv_file_magic_test_file=/usr/lib/libc.sl ;; esac ;; interix[[3-9]]*) # PIC code is broken on Interix 3.x, that's why |\.a not |_pic\.a here lt_cv_deplibs_check_method='match_pattern /lib[[^/]]+(\.so|\.a)$' ;; irix5* | irix6* | nonstopux*) case $LD in *-32|*"-32 ") libmagic=32-bit;; *-n32|*"-n32 ") libmagic=N32;; *-64|*"-64 ") libmagic=64-bit;; *) libmagic=never-match;; esac lt_cv_deplibs_check_method=pass_all ;; # This must be glibc/ELF. linux* | k*bsd*-gnu | kopensolaris*-gnu | gnu*) lt_cv_deplibs_check_method=pass_all ;; netbsd*) if echo __ELF__ | $CC -E - | $GREP __ELF__ > /dev/null; then lt_cv_deplibs_check_method='match_pattern /lib[[^/]]+(\.so\.[[0-9]]+\.[[0-9]]+|_pic\.a)$' else lt_cv_deplibs_check_method='match_pattern /lib[[^/]]+(\.so|_pic\.a)$' fi ;; newos6*) lt_cv_deplibs_check_method='file_magic ELF [[0-9]][[0-9]]*-bit [[ML]]SB (executable|dynamic lib)' lt_cv_file_magic_cmd=/usr/bin/file lt_cv_file_magic_test_file=/usr/lib/libnls.so ;; *nto* | *qnx*) lt_cv_deplibs_check_method=pass_all ;; openbsd* | bitrig*) if test -z "`echo __ELF__ | $CC -E - | $GREP __ELF__`"; then lt_cv_deplibs_check_method='match_pattern /lib[[^/]]+(\.so\.[[0-9]]+\.[[0-9]]+|\.so|_pic\.a)$' else lt_cv_deplibs_check_method='match_pattern /lib[[^/]]+(\.so\.[[0-9]]+\.[[0-9]]+|_pic\.a)$' fi ;; osf3* | osf4* | osf5*) lt_cv_deplibs_check_method=pass_all ;; rdos*) lt_cv_deplibs_check_method=pass_all ;; solaris*) lt_cv_deplibs_check_method=pass_all ;; sysv5* | sco3.2v5* | sco5v6* | unixware* | OpenUNIX* | sysv4*uw2*) lt_cv_deplibs_check_method=pass_all ;; sysv4 | sysv4.3*) case $host_vendor in motorola) lt_cv_deplibs_check_method='file_magic ELF [[0-9]][[0-9]]*-bit [[ML]]SB (shared object|dynamic lib) M[[0-9]][[0-9]]* Version [[0-9]]' lt_cv_file_magic_test_file=`echo /usr/lib/libc.so*` ;; ncr) lt_cv_deplibs_check_method=pass_all ;; sequent) lt_cv_file_magic_cmd='/bin/file' lt_cv_deplibs_check_method='file_magic ELF [[0-9]][[0-9]]*-bit [[LM]]SB (shared object|dynamic lib )' ;; sni) lt_cv_file_magic_cmd='/bin/file' lt_cv_deplibs_check_method="file_magic ELF [[0-9]][[0-9]]*-bit [[LM]]SB dynamic lib" lt_cv_file_magic_test_file=/lib/libc.so ;; siemens) lt_cv_deplibs_check_method=pass_all ;; pc) lt_cv_deplibs_check_method=pass_all ;; esac ;; tpf*) lt_cv_deplibs_check_method=pass_all ;; os2*) lt_cv_deplibs_check_method=pass_all ;; esac ]) file_magic_glob= want_nocaseglob=no if test "$build" = "$host"; then case $host_os in mingw* | pw32*) if ( shopt | grep nocaseglob ) >/dev/null 2>&1; then want_nocaseglob=yes else file_magic_glob=`echo aAbBcCdDeEfFgGhHiIjJkKlLmMnNoOpPqQrRsStTuUvVwWxXyYzZ | $SED -e "s/\(..\)/s\/[[\1]]\/[[\1]]\/g;/g"` fi ;; esac fi file_magic_cmd=$lt_cv_file_magic_cmd deplibs_check_method=$lt_cv_deplibs_check_method test -z "$deplibs_check_method" && deplibs_check_method=unknown _LT_DECL([], [deplibs_check_method], [1], [Method to check whether dependent libraries are shared objects]) _LT_DECL([], [file_magic_cmd], [1], [Command to use when deplibs_check_method = "file_magic"]) _LT_DECL([], [file_magic_glob], [1], [How to find potential files when deplibs_check_method = "file_magic"]) _LT_DECL([], [want_nocaseglob], [1], [Find potential files using nocaseglob when deplibs_check_method = "file_magic"]) ])# _LT_CHECK_MAGIC_METHOD # LT_PATH_NM # ---------- # find the pathname to a BSD- or MS-compatible name lister AC_DEFUN([LT_PATH_NM], [AC_REQUIRE([AC_PROG_CC])dnl AC_CACHE_CHECK([for BSD- or MS-compatible name lister (nm)], lt_cv_path_NM, [if test -n "$NM"; then # Let the user override the test. lt_cv_path_NM=$NM else lt_nm_to_check=${ac_tool_prefix}nm if test -n "$ac_tool_prefix" && test "$build" = "$host"; then lt_nm_to_check="$lt_nm_to_check nm" fi for lt_tmp_nm in $lt_nm_to_check; do lt_save_ifs=$IFS; IFS=$PATH_SEPARATOR for ac_dir in $PATH /usr/ccs/bin/elf /usr/ccs/bin /usr/ucb /bin; do IFS=$lt_save_ifs test -z "$ac_dir" && ac_dir=. tmp_nm=$ac_dir/$lt_tmp_nm if test -f "$tmp_nm" || test -f "$tmp_nm$ac_exeext"; then # Check to see if the nm accepts a BSD-compat flag. # Adding the 'sed 1q' prevents false positives on HP-UX, which says: # nm: unknown option "B" ignored # Tru64's nm complains that /dev/null is an invalid object file # MSYS converts /dev/null to NUL, MinGW nm treats NUL as empty case $build_os in mingw*) lt_bad_file=conftest.nm/nofile ;; *) lt_bad_file=/dev/null ;; esac case `"$tmp_nm" -B $lt_bad_file 2>&1 | sed '1q'` in *$lt_bad_file* | *'Invalid file or object type'*) lt_cv_path_NM="$tmp_nm -B" break 2 ;; *) case `"$tmp_nm" -p /dev/null 2>&1 | sed '1q'` in */dev/null*) lt_cv_path_NM="$tmp_nm -p" break 2 ;; *) lt_cv_path_NM=${lt_cv_path_NM="$tmp_nm"} # keep the first match, but continue # so that we can try to find one that supports BSD flags ;; esac ;; esac fi done IFS=$lt_save_ifs done : ${lt_cv_path_NM=no} fi]) if test no != "$lt_cv_path_NM"; then NM=$lt_cv_path_NM else # Didn't find any BSD compatible name lister, look for dumpbin. if test -n "$DUMPBIN"; then : # Let the user override the test. else AC_CHECK_TOOLS(DUMPBIN, [dumpbin "link -dump"], :) case `$DUMPBIN -symbols -headers /dev/null 2>&1 | sed '1q'` in *COFF*) DUMPBIN="$DUMPBIN -symbols -headers" ;; *) DUMPBIN=: ;; esac fi AC_SUBST([DUMPBIN]) if test : != "$DUMPBIN"; then NM=$DUMPBIN fi fi test -z "$NM" && NM=nm AC_SUBST([NM]) _LT_DECL([], [NM], [1], [A BSD- or MS-compatible name lister])dnl AC_CACHE_CHECK([the name lister ($NM) interface], [lt_cv_nm_interface], [lt_cv_nm_interface="BSD nm" echo "int some_variable = 0;" > conftest.$ac_ext (eval echo "\"\$as_me:$LINENO: $ac_compile\"" >&AS_MESSAGE_LOG_FD) (eval "$ac_compile" 2>conftest.err) cat conftest.err >&AS_MESSAGE_LOG_FD (eval echo "\"\$as_me:$LINENO: $NM \\\"conftest.$ac_objext\\\"\"" >&AS_MESSAGE_LOG_FD) (eval "$NM \"conftest.$ac_objext\"" 2>conftest.err > conftest.out) cat conftest.err >&AS_MESSAGE_LOG_FD (eval echo "\"\$as_me:$LINENO: output\"" >&AS_MESSAGE_LOG_FD) cat conftest.out >&AS_MESSAGE_LOG_FD if $GREP 'External.*some_variable' conftest.out > /dev/null; then lt_cv_nm_interface="MS dumpbin" fi rm -f conftest*]) ])# LT_PATH_NM # Old names: AU_ALIAS([AM_PROG_NM], [LT_PATH_NM]) AU_ALIAS([AC_PROG_NM], [LT_PATH_NM]) dnl aclocal-1.4 backwards compatibility: dnl AC_DEFUN([AM_PROG_NM], []) dnl AC_DEFUN([AC_PROG_NM], []) # _LT_CHECK_SHAREDLIB_FROM_LINKLIB # -------------------------------- # how to determine the name of the shared library # associated with a specific link library. # -- PORTME fill in with the dynamic library characteristics m4_defun([_LT_CHECK_SHAREDLIB_FROM_LINKLIB], [m4_require([_LT_DECL_EGREP]) m4_require([_LT_DECL_OBJDUMP]) m4_require([_LT_DECL_DLLTOOL]) AC_CACHE_CHECK([how to associate runtime and link libraries], lt_cv_sharedlib_from_linklib_cmd, [lt_cv_sharedlib_from_linklib_cmd='unknown' case $host_os in cygwin* | mingw* | pw32* | cegcc*) # two different shell functions defined in ltmain.sh; # decide which one to use based on capabilities of $DLLTOOL case `$DLLTOOL --help 2>&1` in *--identify-strict*) lt_cv_sharedlib_from_linklib_cmd=func_cygming_dll_for_implib ;; *) lt_cv_sharedlib_from_linklib_cmd=func_cygming_dll_for_implib_fallback ;; esac ;; *) # fallback: assume linklib IS sharedlib lt_cv_sharedlib_from_linklib_cmd=$ECHO ;; esac ]) sharedlib_from_linklib_cmd=$lt_cv_sharedlib_from_linklib_cmd test -z "$sharedlib_from_linklib_cmd" && sharedlib_from_linklib_cmd=$ECHO _LT_DECL([], [sharedlib_from_linklib_cmd], [1], [Command to associate shared and link libraries]) ])# _LT_CHECK_SHAREDLIB_FROM_LINKLIB # _LT_PATH_MANIFEST_TOOL # ---------------------- # locate the manifest tool m4_defun([_LT_PATH_MANIFEST_TOOL], [AC_CHECK_TOOL(MANIFEST_TOOL, mt, :) test -z "$MANIFEST_TOOL" && MANIFEST_TOOL=mt AC_CACHE_CHECK([if $MANIFEST_TOOL is a manifest tool], [lt_cv_path_mainfest_tool], [lt_cv_path_mainfest_tool=no echo "$as_me:$LINENO: $MANIFEST_TOOL '-?'" >&AS_MESSAGE_LOG_FD $MANIFEST_TOOL '-?' 2>conftest.err > conftest.out cat conftest.err >&AS_MESSAGE_LOG_FD if $GREP 'Manifest Tool' conftest.out > /dev/null; then lt_cv_path_mainfest_tool=yes fi rm -f conftest*]) if test yes != "$lt_cv_path_mainfest_tool"; then MANIFEST_TOOL=: fi _LT_DECL([], [MANIFEST_TOOL], [1], [Manifest tool])dnl ])# _LT_PATH_MANIFEST_TOOL # _LT_DLL_DEF_P([FILE]) # --------------------- # True iff FILE is a Windows DLL '.def' file. # Keep in sync with func_dll_def_p in the libtool script AC_DEFUN([_LT_DLL_DEF_P], [dnl test DEF = "`$SED -n dnl -e '\''s/^[[ ]]*//'\'' dnl Strip leading whitespace -e '\''/^\(;.*\)*$/d'\'' dnl Delete empty lines and comments -e '\''s/^\(EXPORTS\|LIBRARY\)\([[ ]].*\)*$/DEF/p'\'' dnl -e q dnl Only consider the first "real" line $1`" dnl ])# _LT_DLL_DEF_P # LT_LIB_M # -------- # check for math library AC_DEFUN([LT_LIB_M], [AC_REQUIRE([AC_CANONICAL_HOST])dnl LIBM= case $host in *-*-beos* | *-*-cegcc* | *-*-cygwin* | *-*-haiku* | *-*-pw32* | *-*-darwin*) # These system don't have libm, or don't need it ;; *-ncr-sysv4.3*) AC_CHECK_LIB(mw, _mwvalidcheckl, LIBM=-lmw) AC_CHECK_LIB(m, cos, LIBM="$LIBM -lm") ;; *) AC_CHECK_LIB(m, cos, LIBM=-lm) ;; esac AC_SUBST([LIBM]) ])# LT_LIB_M # Old name: AU_ALIAS([AC_CHECK_LIBM], [LT_LIB_M]) dnl aclocal-1.4 backwards compatibility: dnl AC_DEFUN([AC_CHECK_LIBM], []) # _LT_COMPILER_NO_RTTI([TAGNAME]) # ------------------------------- m4_defun([_LT_COMPILER_NO_RTTI], [m4_require([_LT_TAG_COMPILER])dnl _LT_TAGVAR(lt_prog_compiler_no_builtin_flag, $1)= if test yes = "$GCC"; then case $cc_basename in nvcc*) _LT_TAGVAR(lt_prog_compiler_no_builtin_flag, $1)=' -Xcompiler -fno-builtin' ;; *) _LT_TAGVAR(lt_prog_compiler_no_builtin_flag, $1)=' -fno-builtin' ;; esac _LT_COMPILER_OPTION([if $compiler supports -fno-rtti -fno-exceptions], lt_cv_prog_compiler_rtti_exceptions, [-fno-rtti -fno-exceptions], [], [_LT_TAGVAR(lt_prog_compiler_no_builtin_flag, $1)="$_LT_TAGVAR(lt_prog_compiler_no_builtin_flag, $1) -fno-rtti -fno-exceptions"]) fi _LT_TAGDECL([no_builtin_flag], [lt_prog_compiler_no_builtin_flag], [1], [Compiler flag to turn off builtin functions]) ])# _LT_COMPILER_NO_RTTI # _LT_CMD_GLOBAL_SYMBOLS # ---------------------- m4_defun([_LT_CMD_GLOBAL_SYMBOLS], [AC_REQUIRE([AC_CANONICAL_HOST])dnl AC_REQUIRE([AC_PROG_CC])dnl AC_REQUIRE([AC_PROG_AWK])dnl AC_REQUIRE([LT_PATH_NM])dnl AC_REQUIRE([LT_PATH_LD])dnl m4_require([_LT_DECL_SED])dnl m4_require([_LT_DECL_EGREP])dnl m4_require([_LT_TAG_COMPILER])dnl # Check for command to grab the raw symbol name followed by C symbol from nm. AC_MSG_CHECKING([command to parse $NM output from $compiler object]) AC_CACHE_VAL([lt_cv_sys_global_symbol_pipe], [ # These are sane defaults that work on at least a few old systems. # [They come from Ultrix. What could be older than Ultrix?!! ;)] # Character class describing NM global symbol codes. symcode='[[BCDEGRST]]' # Regexp to match symbols that can be accessed directly from C. sympat='\([[_A-Za-z]][[_A-Za-z0-9]]*\)' # Define system-specific variables. case $host_os in aix*) symcode='[[BCDT]]' ;; cygwin* | mingw* | pw32* | cegcc*) symcode='[[ABCDGISTW]]' ;; hpux*) if test ia64 = "$host_cpu"; then symcode='[[ABCDEGRST]]' fi ;; irix* | nonstopux*) symcode='[[BCDEGRST]]' ;; osf*) symcode='[[BCDEGQRST]]' ;; solaris*) symcode='[[BDRT]]' ;; sco3.2v5*) symcode='[[DT]]' ;; sysv4.2uw2*) symcode='[[DT]]' ;; sysv5* | sco5v6* | unixware* | OpenUNIX*) symcode='[[ABDT]]' ;; sysv4) symcode='[[DFNSTU]]' ;; esac # If we're using GNU nm, then use its standard symbol codes. case `$NM -V 2>&1` in *GNU* | *'with BFD'*) symcode='[[ABCDGIRSTW]]' ;; esac if test "$lt_cv_nm_interface" = "MS dumpbin"; then # Gets list of data symbols to import. lt_cv_sys_global_symbol_to_import="sed -n -e 's/^I .* \(.*\)$/\1/p'" # Adjust the below global symbol transforms to fixup imported variables. lt_cdecl_hook=" -e 's/^I .* \(.*\)$/extern __declspec(dllimport) char \1;/p'" lt_c_name_hook=" -e 's/^I .* \(.*\)$/ {\"\1\", (void *) 0},/p'" lt_c_name_lib_hook="\ -e 's/^I .* \(lib.*\)$/ {\"\1\", (void *) 0},/p'\ -e 's/^I .* \(.*\)$/ {\"lib\1\", (void *) 0},/p'" else # Disable hooks by default. lt_cv_sys_global_symbol_to_import= lt_cdecl_hook= lt_c_name_hook= lt_c_name_lib_hook= fi # Transform an extracted symbol line into a proper C declaration. # Some systems (esp. on ia64) link data and code symbols differently, # so use this general approach. lt_cv_sys_global_symbol_to_cdecl="sed -n"\ $lt_cdecl_hook\ " -e 's/^T .* \(.*\)$/extern int \1();/p'"\ " -e 's/^$symcode$symcode* .* \(.*\)$/extern char \1;/p'" # Transform an extracted symbol line into symbol name and symbol address lt_cv_sys_global_symbol_to_c_name_address="sed -n"\ $lt_c_name_hook\ " -e 's/^: \(.*\) .*$/ {\"\1\", (void *) 0},/p'"\ " -e 's/^$symcode$symcode* .* \(.*\)$/ {\"\1\", (void *) \&\1},/p'" # Transform an extracted symbol line into symbol name with lib prefix and # symbol address. lt_cv_sys_global_symbol_to_c_name_address_lib_prefix="sed -n"\ $lt_c_name_lib_hook\ " -e 's/^: \(.*\) .*$/ {\"\1\", (void *) 0},/p'"\ " -e 's/^$symcode$symcode* .* \(lib.*\)$/ {\"\1\", (void *) \&\1},/p'"\ " -e 's/^$symcode$symcode* .* \(.*\)$/ {\"lib\1\", (void *) \&\1},/p'" # Handle CRLF in mingw tool chain opt_cr= case $build_os in mingw*) opt_cr=`$ECHO 'x\{0,1\}' | tr x '\015'` # option cr in regexp ;; esac # Try without a prefix underscore, then with it. for ac_symprfx in "" "_"; do # Transform symcode, sympat, and symprfx into a raw symbol and a C symbol. symxfrm="\\1 $ac_symprfx\\2 \\2" # Write the raw and C identifiers. if test "$lt_cv_nm_interface" = "MS dumpbin"; then # Fake it for dumpbin and say T for any non-static function, # D for any global variable and I for any imported variable. # Also find C++ and __fastcall symbols from MSVC++, # which start with @ or ?. lt_cv_sys_global_symbol_pipe="$AWK ['"\ " {last_section=section; section=\$ 3};"\ " /^COFF SYMBOL TABLE/{for(i in hide) delete hide[i]};"\ " /Section length .*#relocs.*(pick any)/{hide[last_section]=1};"\ " /^ *Symbol name *: /{split(\$ 0,sn,\":\"); si=substr(sn[2],2)};"\ " /^ *Type *: code/{print \"T\",si,substr(si,length(prfx))};"\ " /^ *Type *: data/{print \"I\",si,substr(si,length(prfx))};"\ " \$ 0!~/External *\|/{next};"\ " / 0+ UNDEF /{next}; / UNDEF \([^|]\)*()/{next};"\ " {if(hide[section]) next};"\ " {f=\"D\"}; \$ 0~/\(\).*\|/{f=\"T\"};"\ " {split(\$ 0,a,/\||\r/); split(a[2],s)};"\ " s[1]~/^[@?]/{print f,s[1],s[1]; next};"\ " s[1]~prfx {split(s[1],t,\"@\"); print f,t[1],substr(t[1],length(prfx))}"\ " ' prfx=^$ac_symprfx]" else lt_cv_sys_global_symbol_pipe="sed -n -e 's/^.*[[ ]]\($symcode$symcode*\)[[ ]][[ ]]*$ac_symprfx$sympat$opt_cr$/$symxfrm/p'" fi lt_cv_sys_global_symbol_pipe="$lt_cv_sys_global_symbol_pipe | sed '/ __gnu_lto/d'" # Check to see that the pipe works correctly. pipe_works=no rm -f conftest* cat > conftest.$ac_ext <<_LT_EOF #ifdef __cplusplus extern "C" { #endif char nm_test_var; void nm_test_func(void); void nm_test_func(void){} #ifdef __cplusplus } #endif int main(){nm_test_var='a';nm_test_func();return(0);} _LT_EOF if AC_TRY_EVAL(ac_compile); then # Now try to grab the symbols. nlist=conftest.nm if AC_TRY_EVAL(NM conftest.$ac_objext \| "$lt_cv_sys_global_symbol_pipe" \> $nlist) && test -s "$nlist"; then # Try sorting and uniquifying the output. if sort "$nlist" | uniq > "$nlist"T; then mv -f "$nlist"T "$nlist" else rm -f "$nlist"T fi # Make sure that we snagged all the symbols we need. if $GREP ' nm_test_var$' "$nlist" >/dev/null; then if $GREP ' nm_test_func$' "$nlist" >/dev/null; then cat <<_LT_EOF > conftest.$ac_ext /* Keep this code in sync between libtool.m4, ltmain, lt_system.h, and tests. */ #if defined _WIN32 || defined __CYGWIN__ || defined _WIN32_WCE /* DATA imports from DLLs on WIN32 can't be const, because runtime relocations are performed -- see ld's documentation on pseudo-relocs. */ # define LT@&t@_DLSYM_CONST #elif defined __osf__ /* This system does not cope well with relocations in const data. */ # define LT@&t@_DLSYM_CONST #else # define LT@&t@_DLSYM_CONST const #endif #ifdef __cplusplus extern "C" { #endif _LT_EOF # Now generate the symbol file. eval "$lt_cv_sys_global_symbol_to_cdecl"' < "$nlist" | $GREP -v main >> conftest.$ac_ext' cat <<_LT_EOF >> conftest.$ac_ext /* The mapping between symbol names and symbols. */ LT@&t@_DLSYM_CONST struct { const char *name; void *address; } lt__PROGRAM__LTX_preloaded_symbols[[]] = { { "@PROGRAM@", (void *) 0 }, _LT_EOF $SED "s/^$symcode$symcode* .* \(.*\)$/ {\"\1\", (void *) \&\1},/" < "$nlist" | $GREP -v main >> conftest.$ac_ext cat <<\_LT_EOF >> conftest.$ac_ext {0, (void *) 0} }; /* This works around a problem in FreeBSD linker */ #ifdef FREEBSD_WORKAROUND static const void *lt_preloaded_setup() { return lt__PROGRAM__LTX_preloaded_symbols; } #endif #ifdef __cplusplus } #endif _LT_EOF # Now try linking the two files. mv conftest.$ac_objext conftstm.$ac_objext lt_globsym_save_LIBS=$LIBS lt_globsym_save_CFLAGS=$CFLAGS LIBS=conftstm.$ac_objext CFLAGS="$CFLAGS$_LT_TAGVAR(lt_prog_compiler_no_builtin_flag, $1)" if AC_TRY_EVAL(ac_link) && test -s conftest$ac_exeext; then pipe_works=yes fi LIBS=$lt_globsym_save_LIBS CFLAGS=$lt_globsym_save_CFLAGS else echo "cannot find nm_test_func in $nlist" >&AS_MESSAGE_LOG_FD fi else echo "cannot find nm_test_var in $nlist" >&AS_MESSAGE_LOG_FD fi else echo "cannot run $lt_cv_sys_global_symbol_pipe" >&AS_MESSAGE_LOG_FD fi else echo "$progname: failed program was:" >&AS_MESSAGE_LOG_FD cat conftest.$ac_ext >&5 fi rm -rf conftest* conftst* # Do not use the global_symbol_pipe unless it works. if test yes = "$pipe_works"; then break else lt_cv_sys_global_symbol_pipe= fi done ]) if test -z "$lt_cv_sys_global_symbol_pipe"; then lt_cv_sys_global_symbol_to_cdecl= fi if test -z "$lt_cv_sys_global_symbol_pipe$lt_cv_sys_global_symbol_to_cdecl"; then AC_MSG_RESULT(failed) else AC_MSG_RESULT(ok) fi # Response file support. if test "$lt_cv_nm_interface" = "MS dumpbin"; then nm_file_list_spec='@' elif $NM --help 2>/dev/null | grep '[[@]]FILE' >/dev/null; then nm_file_list_spec='@' fi _LT_DECL([global_symbol_pipe], [lt_cv_sys_global_symbol_pipe], [1], [Take the output of nm and produce a listing of raw symbols and C names]) _LT_DECL([global_symbol_to_cdecl], [lt_cv_sys_global_symbol_to_cdecl], [1], [Transform the output of nm in a proper C declaration]) _LT_DECL([global_symbol_to_import], [lt_cv_sys_global_symbol_to_import], [1], [Transform the output of nm into a list of symbols to manually relocate]) _LT_DECL([global_symbol_to_c_name_address], [lt_cv_sys_global_symbol_to_c_name_address], [1], [Transform the output of nm in a C name address pair]) _LT_DECL([global_symbol_to_c_name_address_lib_prefix], [lt_cv_sys_global_symbol_to_c_name_address_lib_prefix], [1], [Transform the output of nm in a C name address pair when lib prefix is needed]) _LT_DECL([nm_interface], [lt_cv_nm_interface], [1], [The name lister interface]) _LT_DECL([], [nm_file_list_spec], [1], [Specify filename containing input files for $NM]) ]) # _LT_CMD_GLOBAL_SYMBOLS # _LT_COMPILER_PIC([TAGNAME]) # --------------------------- m4_defun([_LT_COMPILER_PIC], [m4_require([_LT_TAG_COMPILER])dnl _LT_TAGVAR(lt_prog_compiler_wl, $1)= _LT_TAGVAR(lt_prog_compiler_pic, $1)= _LT_TAGVAR(lt_prog_compiler_static, $1)= m4_if([$1], [CXX], [ # C++ specific cases for pic, static, wl, etc. if test yes = "$GXX"; then _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,' _LT_TAGVAR(lt_prog_compiler_static, $1)='-static' case $host_os in aix*) # All AIX code is PIC. if test ia64 = "$host_cpu"; then # AIX 5 now supports IA64 processor _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic' fi _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fPIC' ;; amigaos*) case $host_cpu in powerpc) # see comment about AmigaOS4 .so support _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fPIC' ;; m68k) # FIXME: we need at least 68020 code to build shared libraries, but # adding the '-m68020' flag to GCC prevents building anything better, # like '-m68040'. _LT_TAGVAR(lt_prog_compiler_pic, $1)='-m68020 -resident32 -malways-restore-a4' ;; esac ;; beos* | irix5* | irix6* | nonstopux* | osf3* | osf4* | osf5*) # PIC is the default for these OSes. ;; mingw* | cygwin* | os2* | pw32* | cegcc*) # This hack is so that the source file can tell whether it is being # built for inclusion in a dll (and should export symbols for example). # Although the cygwin gcc ignores -fPIC, still need this for old-style # (--disable-auto-import) libraries m4_if([$1], [GCJ], [], [_LT_TAGVAR(lt_prog_compiler_pic, $1)='-DDLL_EXPORT']) case $host_os in os2*) _LT_TAGVAR(lt_prog_compiler_static, $1)='$wl-static' ;; esac ;; darwin* | rhapsody*) # PIC is the default on this platform # Common symbols not allowed in MH_DYLIB files _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fno-common' ;; *djgpp*) # DJGPP does not support shared libraries at all _LT_TAGVAR(lt_prog_compiler_pic, $1)= ;; haiku*) # PIC is the default for Haiku. # The "-static" flag exists, but is broken. _LT_TAGVAR(lt_prog_compiler_static, $1)= ;; interix[[3-9]]*) # Interix 3.x gcc -fpic/-fPIC options generate broken code. # Instead, we relocate shared libraries at runtime. ;; sysv4*MP*) if test -d /usr/nec; then _LT_TAGVAR(lt_prog_compiler_pic, $1)=-Kconform_pic fi ;; hpux*) # PIC is the default for 64-bit PA HP-UX, but not for 32-bit # PA HP-UX. On IA64 HP-UX, PIC is the default but the pic flag # sets the default TLS model and affects inlining. case $host_cpu in hppa*64*) ;; *) _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fPIC' ;; esac ;; *qnx* | *nto*) # QNX uses GNU C++, but need to define -shared option too, otherwise # it will coredump. _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fPIC -shared' ;; *) _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fPIC' ;; esac else case $host_os in aix[[4-9]]*) # All AIX code is PIC. if test ia64 = "$host_cpu"; then # AIX 5 now supports IA64 processor _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic' else _LT_TAGVAR(lt_prog_compiler_static, $1)='-bnso -bI:/lib/syscalls.exp' fi ;; chorus*) case $cc_basename in cxch68*) # Green Hills C++ Compiler # _LT_TAGVAR(lt_prog_compiler_static, $1)="--no_auto_instantiation -u __main -u __premain -u _abort -r $COOL_DIR/lib/libOrb.a $MVME_DIR/lib/CC/libC.a $MVME_DIR/lib/classix/libcx.s.a" ;; esac ;; mingw* | cygwin* | os2* | pw32* | cegcc*) # This hack is so that the source file can tell whether it is being # built for inclusion in a dll (and should export symbols for example). m4_if([$1], [GCJ], [], [_LT_TAGVAR(lt_prog_compiler_pic, $1)='-DDLL_EXPORT']) ;; dgux*) case $cc_basename in ec++*) _LT_TAGVAR(lt_prog_compiler_pic, $1)='-KPIC' ;; ghcx*) # Green Hills C++ Compiler _LT_TAGVAR(lt_prog_compiler_pic, $1)='-pic' ;; *) ;; esac ;; freebsd* | dragonfly*) # FreeBSD uses GNU C++ ;; hpux9* | hpux10* | hpux11*) case $cc_basename in CC*) _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,' _LT_TAGVAR(lt_prog_compiler_static, $1)='$wl-a ${wl}archive' if test ia64 != "$host_cpu"; then _LT_TAGVAR(lt_prog_compiler_pic, $1)='+Z' fi ;; aCC*) _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,' _LT_TAGVAR(lt_prog_compiler_static, $1)='$wl-a ${wl}archive' case $host_cpu in hppa*64*|ia64*) # +Z the default ;; *) _LT_TAGVAR(lt_prog_compiler_pic, $1)='+Z' ;; esac ;; *) ;; esac ;; interix*) # This is c89, which is MS Visual C++ (no shared libs) # Anyone wants to do a port? ;; irix5* | irix6* | nonstopux*) case $cc_basename in CC*) _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,' _LT_TAGVAR(lt_prog_compiler_static, $1)='-non_shared' # CC pic flag -KPIC is the default. ;; *) ;; esac ;; linux* | k*bsd*-gnu | kopensolaris*-gnu | gnu*) case $cc_basename in KCC*) # KAI C++ Compiler _LT_TAGVAR(lt_prog_compiler_wl, $1)='--backend -Wl,' _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fPIC' ;; ecpc* ) # old Intel C++ for x86_64, which still supported -KPIC. _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,' _LT_TAGVAR(lt_prog_compiler_pic, $1)='-KPIC' _LT_TAGVAR(lt_prog_compiler_static, $1)='-static' ;; icpc* ) # Intel C++, used to be incompatible with GCC. # ICC 10 doesn't accept -KPIC any more. _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,' _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fPIC' _LT_TAGVAR(lt_prog_compiler_static, $1)='-static' ;; pgCC* | pgcpp*) # Portland Group C++ compiler _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,' _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fpic' _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic' ;; cxx*) # Compaq C++ # Make sure the PIC flag is empty. It appears that all Alpha # Linux and Compaq Tru64 Unix objects are PIC. _LT_TAGVAR(lt_prog_compiler_pic, $1)= _LT_TAGVAR(lt_prog_compiler_static, $1)='-non_shared' ;; xlc* | xlC* | bgxl[[cC]]* | mpixl[[cC]]*) # IBM XL 8.0, 9.0 on PPC and BlueGene _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,' _LT_TAGVAR(lt_prog_compiler_pic, $1)='-qpic' _LT_TAGVAR(lt_prog_compiler_static, $1)='-qstaticlink' ;; *) case `$CC -V 2>&1 | sed 5q` in *Sun\ C*) # Sun C++ 5.9 _LT_TAGVAR(lt_prog_compiler_pic, $1)='-KPIC' _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic' _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Qoption ld ' ;; esac ;; esac ;; lynxos*) ;; m88k*) ;; mvs*) case $cc_basename in cxx*) _LT_TAGVAR(lt_prog_compiler_pic, $1)='-W c,exportall' ;; *) ;; esac ;; netbsd*) ;; *qnx* | *nto*) # QNX uses GNU C++, but need to define -shared option too, otherwise # it will coredump. _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fPIC -shared' ;; osf3* | osf4* | osf5*) case $cc_basename in KCC*) _LT_TAGVAR(lt_prog_compiler_wl, $1)='--backend -Wl,' ;; RCC*) # Rational C++ 2.4.1 _LT_TAGVAR(lt_prog_compiler_pic, $1)='-pic' ;; cxx*) # Digital/Compaq C++ _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,' # Make sure the PIC flag is empty. It appears that all Alpha # Linux and Compaq Tru64 Unix objects are PIC. _LT_TAGVAR(lt_prog_compiler_pic, $1)= _LT_TAGVAR(lt_prog_compiler_static, $1)='-non_shared' ;; *) ;; esac ;; psos*) ;; solaris*) case $cc_basename in CC* | sunCC*) # Sun C++ 4.2, 5.x and Centerline C++ _LT_TAGVAR(lt_prog_compiler_pic, $1)='-KPIC' _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic' _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Qoption ld ' ;; gcx*) # Green Hills C++ Compiler _LT_TAGVAR(lt_prog_compiler_pic, $1)='-PIC' ;; *) ;; esac ;; sunos4*) case $cc_basename in CC*) # Sun C++ 4.x _LT_TAGVAR(lt_prog_compiler_pic, $1)='-pic' _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic' ;; lcc*) # Lucid _LT_TAGVAR(lt_prog_compiler_pic, $1)='-pic' ;; *) ;; esac ;; sysv5* | unixware* | sco3.2v5* | sco5v6* | OpenUNIX*) case $cc_basename in CC*) _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,' _LT_TAGVAR(lt_prog_compiler_pic, $1)='-KPIC' _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic' ;; esac ;; tandem*) case $cc_basename in NCC*) # NonStop-UX NCC 3.20 _LT_TAGVAR(lt_prog_compiler_pic, $1)='-KPIC' ;; *) ;; esac ;; vxworks*) ;; *) _LT_TAGVAR(lt_prog_compiler_can_build_shared, $1)=no ;; esac fi ], [ if test yes = "$GCC"; then _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,' _LT_TAGVAR(lt_prog_compiler_static, $1)='-static' case $host_os in aix*) # All AIX code is PIC. if test ia64 = "$host_cpu"; then # AIX 5 now supports IA64 processor _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic' fi _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fPIC' ;; amigaos*) case $host_cpu in powerpc) # see comment about AmigaOS4 .so support _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fPIC' ;; m68k) # FIXME: we need at least 68020 code to build shared libraries, but # adding the '-m68020' flag to GCC prevents building anything better, # like '-m68040'. _LT_TAGVAR(lt_prog_compiler_pic, $1)='-m68020 -resident32 -malways-restore-a4' ;; esac ;; beos* | irix5* | irix6* | nonstopux* | osf3* | osf4* | osf5*) # PIC is the default for these OSes. ;; mingw* | cygwin* | pw32* | os2* | cegcc*) # This hack is so that the source file can tell whether it is being # built for inclusion in a dll (and should export symbols for example). # Although the cygwin gcc ignores -fPIC, still need this for old-style # (--disable-auto-import) libraries m4_if([$1], [GCJ], [], [_LT_TAGVAR(lt_prog_compiler_pic, $1)='-DDLL_EXPORT']) case $host_os in os2*) _LT_TAGVAR(lt_prog_compiler_static, $1)='$wl-static' ;; esac ;; darwin* | rhapsody*) # PIC is the default on this platform # Common symbols not allowed in MH_DYLIB files _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fno-common' ;; haiku*) # PIC is the default for Haiku. # The "-static" flag exists, but is broken. _LT_TAGVAR(lt_prog_compiler_static, $1)= ;; hpux*) # PIC is the default for 64-bit PA HP-UX, but not for 32-bit # PA HP-UX. On IA64 HP-UX, PIC is the default but the pic flag # sets the default TLS model and affects inlining. case $host_cpu in hppa*64*) # +Z the default ;; *) _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fPIC' ;; esac ;; interix[[3-9]]*) # Interix 3.x gcc -fpic/-fPIC options generate broken code. # Instead, we relocate shared libraries at runtime. ;; msdosdjgpp*) # Just because we use GCC doesn't mean we suddenly get shared libraries # on systems that don't support them. _LT_TAGVAR(lt_prog_compiler_can_build_shared, $1)=no enable_shared=no ;; *nto* | *qnx*) # QNX uses GNU C++, but need to define -shared option too, otherwise # it will coredump. _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fPIC -shared' ;; sysv4*MP*) if test -d /usr/nec; then _LT_TAGVAR(lt_prog_compiler_pic, $1)=-Kconform_pic fi ;; *) _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fPIC' ;; esac case $cc_basename in nvcc*) # Cuda Compiler Driver 2.2 _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Xlinker ' if test -n "$_LT_TAGVAR(lt_prog_compiler_pic, $1)"; then _LT_TAGVAR(lt_prog_compiler_pic, $1)="-Xcompiler $_LT_TAGVAR(lt_prog_compiler_pic, $1)" fi ;; esac else # PORTME Check for flag to pass linker flags through the system compiler. case $host_os in aix*) _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,' if test ia64 = "$host_cpu"; then # AIX 5 now supports IA64 processor _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic' else _LT_TAGVAR(lt_prog_compiler_static, $1)='-bnso -bI:/lib/syscalls.exp' fi ;; darwin* | rhapsody*) # PIC is the default on this platform # Common symbols not allowed in MH_DYLIB files _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fno-common' case $cc_basename in nagfor*) # NAG Fortran compiler _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,-Wl,,' _LT_TAGVAR(lt_prog_compiler_pic, $1)='-PIC' _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic' ;; esac ;; mingw* | cygwin* | pw32* | os2* | cegcc*) # This hack is so that the source file can tell whether it is being # built for inclusion in a dll (and should export symbols for example). m4_if([$1], [GCJ], [], [_LT_TAGVAR(lt_prog_compiler_pic, $1)='-DDLL_EXPORT']) case $host_os in os2*) _LT_TAGVAR(lt_prog_compiler_static, $1)='$wl-static' ;; esac ;; hpux9* | hpux10* | hpux11*) _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,' # PIC is the default for IA64 HP-UX and 64-bit HP-UX, but # not for PA HP-UX. case $host_cpu in hppa*64*|ia64*) # +Z the default ;; *) _LT_TAGVAR(lt_prog_compiler_pic, $1)='+Z' ;; esac # Is there a better lt_prog_compiler_static that works with the bundled CC? _LT_TAGVAR(lt_prog_compiler_static, $1)='$wl-a ${wl}archive' ;; irix5* | irix6* | nonstopux*) _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,' # PIC (with -KPIC) is the default. _LT_TAGVAR(lt_prog_compiler_static, $1)='-non_shared' ;; linux* | k*bsd*-gnu | kopensolaris*-gnu | gnu*) case $cc_basename in # old Intel for x86_64, which still supported -KPIC. ecc*) _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,' _LT_TAGVAR(lt_prog_compiler_pic, $1)='-KPIC' _LT_TAGVAR(lt_prog_compiler_static, $1)='-static' ;; # icc used to be incompatible with GCC. # ICC 10 doesn't accept -KPIC any more. icc* | ifort*) _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,' _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fPIC' _LT_TAGVAR(lt_prog_compiler_static, $1)='-static' ;; # Lahey Fortran 8.1. lf95*) _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,' _LT_TAGVAR(lt_prog_compiler_pic, $1)='--shared' _LT_TAGVAR(lt_prog_compiler_static, $1)='--static' ;; nagfor*) # NAG Fortran compiler _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,-Wl,,' _LT_TAGVAR(lt_prog_compiler_pic, $1)='-PIC' _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic' ;; tcc*) # Fabrice Bellard et al's Tiny C Compiler _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,' _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fPIC' _LT_TAGVAR(lt_prog_compiler_static, $1)='-static' ;; pgcc* | pgf77* | pgf90* | pgf95* | pgfortran*) # Portland Group compilers (*not* the Pentium gcc compiler, # which looks to be a dead project) _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,' _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fpic' _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic' ;; ccc*) _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,' # All Alpha code is PIC. _LT_TAGVAR(lt_prog_compiler_static, $1)='-non_shared' ;; xl* | bgxl* | bgf* | mpixl*) # IBM XL C 8.0/Fortran 10.1, 11.1 on PPC and BlueGene _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,' _LT_TAGVAR(lt_prog_compiler_pic, $1)='-qpic' _LT_TAGVAR(lt_prog_compiler_static, $1)='-qstaticlink' ;; *) case `$CC -V 2>&1 | sed 5q` in *Sun\ Ceres\ Fortran* | *Sun*Fortran*\ [[1-7]].* | *Sun*Fortran*\ 8.[[0-3]]*) # Sun Fortran 8.3 passes all unrecognized flags to the linker _LT_TAGVAR(lt_prog_compiler_pic, $1)='-KPIC' _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic' _LT_TAGVAR(lt_prog_compiler_wl, $1)='' ;; *Sun\ F* | *Sun*Fortran*) _LT_TAGVAR(lt_prog_compiler_pic, $1)='-KPIC' _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic' _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Qoption ld ' ;; *Sun\ C*) # Sun C 5.9 _LT_TAGVAR(lt_prog_compiler_pic, $1)='-KPIC' _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic' _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,' ;; *Intel*\ [[CF]]*Compiler*) _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,' _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fPIC' _LT_TAGVAR(lt_prog_compiler_static, $1)='-static' ;; *Portland\ Group*) _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,' _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fpic' _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic' ;; esac ;; esac ;; newsos6) _LT_TAGVAR(lt_prog_compiler_pic, $1)='-KPIC' _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic' ;; *nto* | *qnx*) # QNX uses GNU C++, but need to define -shared option too, otherwise # it will coredump. _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fPIC -shared' ;; osf3* | osf4* | osf5*) _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,' # All OSF/1 code is PIC. _LT_TAGVAR(lt_prog_compiler_static, $1)='-non_shared' ;; rdos*) _LT_TAGVAR(lt_prog_compiler_static, $1)='-non_shared' ;; solaris*) _LT_TAGVAR(lt_prog_compiler_pic, $1)='-KPIC' _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic' case $cc_basename in f77* | f90* | f95* | sunf77* | sunf90* | sunf95*) _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Qoption ld ';; *) _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,';; esac ;; sunos4*) _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Qoption ld ' _LT_TAGVAR(lt_prog_compiler_pic, $1)='-PIC' _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic' ;; sysv4 | sysv4.2uw2* | sysv4.3*) _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,' _LT_TAGVAR(lt_prog_compiler_pic, $1)='-KPIC' _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic' ;; sysv4*MP*) if test -d /usr/nec; then _LT_TAGVAR(lt_prog_compiler_pic, $1)='-Kconform_pic' _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic' fi ;; sysv5* | unixware* | sco3.2v5* | sco5v6* | OpenUNIX*) _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,' _LT_TAGVAR(lt_prog_compiler_pic, $1)='-KPIC' _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic' ;; unicos*) _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,' _LT_TAGVAR(lt_prog_compiler_can_build_shared, $1)=no ;; uts4*) _LT_TAGVAR(lt_prog_compiler_pic, $1)='-pic' _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic' ;; *) _LT_TAGVAR(lt_prog_compiler_can_build_shared, $1)=no ;; esac fi ]) case $host_os in # For platforms that do not support PIC, -DPIC is meaningless: *djgpp*) _LT_TAGVAR(lt_prog_compiler_pic, $1)= ;; *) _LT_TAGVAR(lt_prog_compiler_pic, $1)="$_LT_TAGVAR(lt_prog_compiler_pic, $1)@&t@m4_if([$1],[],[ -DPIC],[m4_if([$1],[CXX],[ -DPIC],[])])" ;; esac AC_CACHE_CHECK([for $compiler option to produce PIC], [_LT_TAGVAR(lt_cv_prog_compiler_pic, $1)], [_LT_TAGVAR(lt_cv_prog_compiler_pic, $1)=$_LT_TAGVAR(lt_prog_compiler_pic, $1)]) _LT_TAGVAR(lt_prog_compiler_pic, $1)=$_LT_TAGVAR(lt_cv_prog_compiler_pic, $1) # # Check to make sure the PIC flag actually works. # if test -n "$_LT_TAGVAR(lt_prog_compiler_pic, $1)"; then _LT_COMPILER_OPTION([if $compiler PIC flag $_LT_TAGVAR(lt_prog_compiler_pic, $1) works], [_LT_TAGVAR(lt_cv_prog_compiler_pic_works, $1)], [$_LT_TAGVAR(lt_prog_compiler_pic, $1)@&t@m4_if([$1],[],[ -DPIC],[m4_if([$1],[CXX],[ -DPIC],[])])], [], [case $_LT_TAGVAR(lt_prog_compiler_pic, $1) in "" | " "*) ;; *) _LT_TAGVAR(lt_prog_compiler_pic, $1)=" $_LT_TAGVAR(lt_prog_compiler_pic, $1)" ;; esac], [_LT_TAGVAR(lt_prog_compiler_pic, $1)= _LT_TAGVAR(lt_prog_compiler_can_build_shared, $1)=no]) fi _LT_TAGDECL([pic_flag], [lt_prog_compiler_pic], [1], [Additional compiler flags for building library objects]) _LT_TAGDECL([wl], [lt_prog_compiler_wl], [1], [How to pass a linker flag through the compiler]) # # Check to make sure the static flag actually works. # wl=$_LT_TAGVAR(lt_prog_compiler_wl, $1) eval lt_tmp_static_flag=\"$_LT_TAGVAR(lt_prog_compiler_static, $1)\" _LT_LINKER_OPTION([if $compiler static flag $lt_tmp_static_flag works], _LT_TAGVAR(lt_cv_prog_compiler_static_works, $1), $lt_tmp_static_flag, [], [_LT_TAGVAR(lt_prog_compiler_static, $1)=]) _LT_TAGDECL([link_static_flag], [lt_prog_compiler_static], [1], [Compiler flag to prevent dynamic linking]) ])# _LT_COMPILER_PIC # _LT_LINKER_SHLIBS([TAGNAME]) # ---------------------------- # See if the linker supports building shared libraries. m4_defun([_LT_LINKER_SHLIBS], [AC_REQUIRE([LT_PATH_LD])dnl AC_REQUIRE([LT_PATH_NM])dnl m4_require([_LT_PATH_MANIFEST_TOOL])dnl m4_require([_LT_FILEUTILS_DEFAULTS])dnl m4_require([_LT_DECL_EGREP])dnl m4_require([_LT_DECL_SED])dnl m4_require([_LT_CMD_GLOBAL_SYMBOLS])dnl m4_require([_LT_TAG_COMPILER])dnl AC_MSG_CHECKING([whether the $compiler linker ($LD) supports shared libraries]) m4_if([$1], [CXX], [ _LT_TAGVAR(export_symbols_cmds, $1)='$NM $libobjs $convenience | $global_symbol_pipe | $SED '\''s/.* //'\'' | sort | uniq > $export_symbols' _LT_TAGVAR(exclude_expsyms, $1)=['_GLOBAL_OFFSET_TABLE_|_GLOBAL__F[ID]_.*'] case $host_os in aix[[4-9]]*) # If we're using GNU nm, then we don't want the "-C" option. # -C means demangle to GNU nm, but means don't demangle to AIX nm. # Without the "-l" option, or with the "-B" option, AIX nm treats # weak defined symbols like other global defined symbols, whereas # GNU nm marks them as "W". # While the 'weak' keyword is ignored in the Export File, we need # it in the Import File for the 'aix-soname' feature, so we have # to replace the "-B" option with "-P" for AIX nm. if $NM -V 2>&1 | $GREP 'GNU' > /dev/null; then _LT_TAGVAR(export_symbols_cmds, $1)='$NM -Bpg $libobjs $convenience | awk '\''{ if (((\$ 2 == "T") || (\$ 2 == "D") || (\$ 2 == "B") || (\$ 2 == "W")) && ([substr](\$ 3,1,1) != ".")) { if (\$ 2 == "W") { print \$ 3 " weak" } else { print \$ 3 } } }'\'' | sort -u > $export_symbols' else _LT_TAGVAR(export_symbols_cmds, $1)='`func_echo_all $NM | $SED -e '\''s/B\([[^B]]*\)$/P\1/'\''` -PCpgl $libobjs $convenience | awk '\''{ if (((\$ 2 == "T") || (\$ 2 == "D") || (\$ 2 == "B") || (\$ 2 == "W") || (\$ 2 == "V") || (\$ 2 == "Z")) && ([substr](\$ 1,1,1) != ".")) { if ((\$ 2 == "W") || (\$ 2 == "V") || (\$ 2 == "Z")) { print \$ 1 " weak" } else { print \$ 1 } } }'\'' | sort -u > $export_symbols' fi ;; pw32*) _LT_TAGVAR(export_symbols_cmds, $1)=$ltdll_cmds ;; cygwin* | mingw* | cegcc*) case $cc_basename in cl*) _LT_TAGVAR(exclude_expsyms, $1)='_NULL_IMPORT_DESCRIPTOR|_IMPORT_DESCRIPTOR_.*' ;; *) _LT_TAGVAR(export_symbols_cmds, $1)='$NM $libobjs $convenience | $global_symbol_pipe | $SED -e '\''/^[[BCDGRS]][[ ]]/s/.*[[ ]]\([[^ ]]*\)/\1 DATA/;s/^.*[[ ]]__nm__\([[^ ]]*\)[[ ]][[^ ]]*/\1 DATA/;/^I[[ ]]/d;/^[[AITW]][[ ]]/s/.* //'\'' | sort | uniq > $export_symbols' _LT_TAGVAR(exclude_expsyms, $1)=['[_]+GLOBAL_OFFSET_TABLE_|[_]+GLOBAL__[FID]_.*|[_]+head_[A-Za-z0-9_]+_dll|[A-Za-z0-9_]+_dll_iname'] ;; esac ;; *) _LT_TAGVAR(export_symbols_cmds, $1)='$NM $libobjs $convenience | $global_symbol_pipe | $SED '\''s/.* //'\'' | sort | uniq > $export_symbols' ;; esac ], [ runpath_var= _LT_TAGVAR(allow_undefined_flag, $1)= _LT_TAGVAR(always_export_symbols, $1)=no _LT_TAGVAR(archive_cmds, $1)= _LT_TAGVAR(archive_expsym_cmds, $1)= _LT_TAGVAR(compiler_needs_object, $1)=no _LT_TAGVAR(enable_shared_with_static_runtimes, $1)=no _LT_TAGVAR(export_dynamic_flag_spec, $1)= _LT_TAGVAR(export_symbols_cmds, $1)='$NM $libobjs $convenience | $global_symbol_pipe | $SED '\''s/.* //'\'' | sort | uniq > $export_symbols' _LT_TAGVAR(hardcode_automatic, $1)=no _LT_TAGVAR(hardcode_direct, $1)=no _LT_TAGVAR(hardcode_direct_absolute, $1)=no _LT_TAGVAR(hardcode_libdir_flag_spec, $1)= _LT_TAGVAR(hardcode_libdir_separator, $1)= _LT_TAGVAR(hardcode_minus_L, $1)=no _LT_TAGVAR(hardcode_shlibpath_var, $1)=unsupported _LT_TAGVAR(inherit_rpath, $1)=no _LT_TAGVAR(link_all_deplibs, $1)=unknown _LT_TAGVAR(module_cmds, $1)= _LT_TAGVAR(module_expsym_cmds, $1)= _LT_TAGVAR(old_archive_from_new_cmds, $1)= _LT_TAGVAR(old_archive_from_expsyms_cmds, $1)= _LT_TAGVAR(thread_safe_flag_spec, $1)= _LT_TAGVAR(whole_archive_flag_spec, $1)= # include_expsyms should be a list of space-separated symbols to be *always* # included in the symbol list _LT_TAGVAR(include_expsyms, $1)= # exclude_expsyms can be an extended regexp of symbols to exclude # it will be wrapped by ' (' and ')$', so one must not match beginning or # end of line. Example: 'a|bc|.*d.*' will exclude the symbols 'a' and 'bc', # as well as any symbol that contains 'd'. _LT_TAGVAR(exclude_expsyms, $1)=['_GLOBAL_OFFSET_TABLE_|_GLOBAL__F[ID]_.*'] # Although _GLOBAL_OFFSET_TABLE_ is a valid symbol C name, most a.out # platforms (ab)use it in PIC code, but their linkers get confused if # the symbol is explicitly referenced. Since portable code cannot # rely on this symbol name, it's probably fine to never include it in # preloaded symbol tables. # Exclude shared library initialization/finalization symbols. dnl Note also adjust exclude_expsyms for C++ above. extract_expsyms_cmds= case $host_os in cygwin* | mingw* | pw32* | cegcc*) # FIXME: the MSVC++ port hasn't been tested in a loooong time # When not using gcc, we currently assume that we are using # Microsoft Visual C++. if test yes != "$GCC"; then with_gnu_ld=no fi ;; interix*) # we just hope/assume this is gcc and not c89 (= MSVC++) with_gnu_ld=yes ;; openbsd* | bitrig*) with_gnu_ld=no ;; esac _LT_TAGVAR(ld_shlibs, $1)=yes # On some targets, GNU ld is compatible enough with the native linker # that we're better off using the native interface for both. lt_use_gnu_ld_interface=no if test yes = "$with_gnu_ld"; then case $host_os in aix*) # The AIX port of GNU ld has always aspired to compatibility # with the native linker. However, as the warning in the GNU ld # block says, versions before 2.19.5* couldn't really create working # shared libraries, regardless of the interface used. case `$LD -v 2>&1` in *\ \(GNU\ Binutils\)\ 2.19.5*) ;; *\ \(GNU\ Binutils\)\ 2.[[2-9]]*) ;; *\ \(GNU\ Binutils\)\ [[3-9]]*) ;; *) lt_use_gnu_ld_interface=yes ;; esac ;; *) lt_use_gnu_ld_interface=yes ;; esac fi if test yes = "$lt_use_gnu_ld_interface"; then # If archive_cmds runs LD, not CC, wlarc should be empty wlarc='$wl' # Set some defaults for GNU ld with shared library support. These # are reset later if shared libraries are not supported. Putting them # here allows them to be overridden if necessary. runpath_var=LD_RUN_PATH _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='$wl-rpath $wl$libdir' _LT_TAGVAR(export_dynamic_flag_spec, $1)='$wl--export-dynamic' # ancient GNU ld didn't support --whole-archive et. al. if $LD --help 2>&1 | $GREP 'no-whole-archive' > /dev/null; then _LT_TAGVAR(whole_archive_flag_spec, $1)=$wlarc'--whole-archive$convenience '$wlarc'--no-whole-archive' else _LT_TAGVAR(whole_archive_flag_spec, $1)= fi supports_anon_versioning=no case `$LD -v | $SED -e 's/([^)]\+)\s\+//' 2>&1` in *GNU\ gold*) supports_anon_versioning=yes ;; *\ [[01]].* | *\ 2.[[0-9]].* | *\ 2.10.*) ;; # catch versions < 2.11 *\ 2.11.93.0.2\ *) supports_anon_versioning=yes ;; # RH7.3 ... *\ 2.11.92.0.12\ *) supports_anon_versioning=yes ;; # Mandrake 8.2 ... *\ 2.11.*) ;; # other 2.11 versions *) supports_anon_versioning=yes ;; esac # See if GNU ld supports shared libraries. case $host_os in aix[[3-9]]*) # On AIX/PPC, the GNU linker is very broken if test ia64 != "$host_cpu"; then _LT_TAGVAR(ld_shlibs, $1)=no cat <<_LT_EOF 1>&2 *** Warning: the GNU linker, at least up to release 2.19, is reported *** to be unable to reliably create shared libraries on AIX. *** Therefore, libtool is disabling shared libraries support. If you *** really care for shared libraries, you may want to install binutils *** 2.20 or above, or modify your PATH so that a non-GNU linker is found. *** You will then need to restart the configuration process. _LT_EOF fi ;; amigaos*) case $host_cpu in powerpc) # see comment about AmigaOS4 .so support _LT_TAGVAR(archive_cmds, $1)='$CC -shared $libobjs $deplibs $compiler_flags $wl-soname $wl$soname -o $lib' _LT_TAGVAR(archive_expsym_cmds, $1)='' ;; m68k) _LT_TAGVAR(archive_cmds, $1)='$RM $output_objdir/a2ixlibrary.data~$ECHO "#define NAME $libname" > $output_objdir/a2ixlibrary.data~$ECHO "#define LIBRARY_ID 1" >> $output_objdir/a2ixlibrary.data~$ECHO "#define VERSION $major" >> $output_objdir/a2ixlibrary.data~$ECHO "#define REVISION $revision" >> $output_objdir/a2ixlibrary.data~$AR $AR_FLAGS $lib $libobjs~$RANLIB $lib~(cd $output_objdir && a2ixlibrary -32)' _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-L$libdir' _LT_TAGVAR(hardcode_minus_L, $1)=yes ;; esac ;; beos*) if $LD --help 2>&1 | $GREP ': supported targets:.* elf' > /dev/null; then _LT_TAGVAR(allow_undefined_flag, $1)=unsupported # Joseph Beckenbach says some releases of gcc # support --undefined. This deserves some investigation. FIXME _LT_TAGVAR(archive_cmds, $1)='$CC -nostart $libobjs $deplibs $compiler_flags $wl-soname $wl$soname -o $lib' else _LT_TAGVAR(ld_shlibs, $1)=no fi ;; cygwin* | mingw* | pw32* | cegcc*) # _LT_TAGVAR(hardcode_libdir_flag_spec, $1) is actually meaningless, # as there is no search path for DLLs. _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-L$libdir' _LT_TAGVAR(export_dynamic_flag_spec, $1)='$wl--export-all-symbols' _LT_TAGVAR(allow_undefined_flag, $1)=unsupported _LT_TAGVAR(always_export_symbols, $1)=no _LT_TAGVAR(enable_shared_with_static_runtimes, $1)=yes _LT_TAGVAR(export_symbols_cmds, $1)='$NM $libobjs $convenience | $global_symbol_pipe | $SED -e '\''/^[[BCDGRS]][[ ]]/s/.*[[ ]]\([[^ ]]*\)/\1 DATA/;s/^.*[[ ]]__nm__\([[^ ]]*\)[[ ]][[^ ]]*/\1 DATA/;/^I[[ ]]/d;/^[[AITW]][[ ]]/s/.* //'\'' | sort | uniq > $export_symbols' _LT_TAGVAR(exclude_expsyms, $1)=['[_]+GLOBAL_OFFSET_TABLE_|[_]+GLOBAL__[FID]_.*|[_]+head_[A-Za-z0-9_]+_dll|[A-Za-z0-9_]+_dll_iname'] if $LD --help 2>&1 | $GREP 'auto-import' > /dev/null; then _LT_TAGVAR(archive_cmds, $1)='$CC -shared $libobjs $deplibs $compiler_flags -o $output_objdir/$soname $wl--enable-auto-image-base -Xlinker --out-implib -Xlinker $lib' # If the export-symbols file already is a .def file, use it as # is; otherwise, prepend EXPORTS... _LT_TAGVAR(archive_expsym_cmds, $1)='if _LT_DLL_DEF_P([$export_symbols]); then cp $export_symbols $output_objdir/$soname.def; else echo EXPORTS > $output_objdir/$soname.def; cat $export_symbols >> $output_objdir/$soname.def; fi~ $CC -shared $output_objdir/$soname.def $libobjs $deplibs $compiler_flags -o $output_objdir/$soname $wl--enable-auto-image-base -Xlinker --out-implib -Xlinker $lib' else _LT_TAGVAR(ld_shlibs, $1)=no fi ;; haiku*) _LT_TAGVAR(archive_cmds, $1)='$CC -shared $libobjs $deplibs $compiler_flags $wl-soname $wl$soname -o $lib' _LT_TAGVAR(link_all_deplibs, $1)=yes ;; os2*) _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-L$libdir' _LT_TAGVAR(hardcode_minus_L, $1)=yes _LT_TAGVAR(allow_undefined_flag, $1)=unsupported shrext_cmds=.dll _LT_TAGVAR(archive_cmds, $1)='$ECHO "LIBRARY ${soname%$shared_ext} INITINSTANCE TERMINSTANCE" > $output_objdir/$libname.def~ $ECHO "DESCRIPTION \"$libname\"" >> $output_objdir/$libname.def~ $ECHO "DATA MULTIPLE NONSHARED" >> $output_objdir/$libname.def~ $ECHO EXPORTS >> $output_objdir/$libname.def~ emxexp $libobjs | $SED /"_DLL_InitTerm"/d >> $output_objdir/$libname.def~ $CC -Zdll -Zcrtdll -o $output_objdir/$soname $libobjs $deplibs $compiler_flags $output_objdir/$libname.def~ emximp -o $lib $output_objdir/$libname.def' _LT_TAGVAR(archive_expsym_cmds, $1)='$ECHO "LIBRARY ${soname%$shared_ext} INITINSTANCE TERMINSTANCE" > $output_objdir/$libname.def~ $ECHO "DESCRIPTION \"$libname\"" >> $output_objdir/$libname.def~ $ECHO "DATA MULTIPLE NONSHARED" >> $output_objdir/$libname.def~ $ECHO EXPORTS >> $output_objdir/$libname.def~ prefix_cmds="$SED"~ if test EXPORTS = "`$SED 1q $export_symbols`"; then prefix_cmds="$prefix_cmds -e 1d"; fi~ prefix_cmds="$prefix_cmds -e \"s/^\(.*\)$/_\1/g\""~ cat $export_symbols | $prefix_cmds >> $output_objdir/$libname.def~ $CC -Zdll -Zcrtdll -o $output_objdir/$soname $libobjs $deplibs $compiler_flags $output_objdir/$libname.def~ emximp -o $lib $output_objdir/$libname.def' _LT_TAGVAR(old_archive_From_new_cmds, $1)='emximp -o $output_objdir/${libname}_dll.a $output_objdir/$libname.def' _LT_TAGVAR(enable_shared_with_static_runtimes, $1)=yes ;; interix[[3-9]]*) _LT_TAGVAR(hardcode_direct, $1)=no _LT_TAGVAR(hardcode_shlibpath_var, $1)=no _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='$wl-rpath,$libdir' _LT_TAGVAR(export_dynamic_flag_spec, $1)='$wl-E' # Hack: On Interix 3.x, we cannot compile PIC because of a broken gcc. # Instead, shared libraries are loaded at an image base (0x10000000 by # default) and relocated if they conflict, which is a slow very memory # consuming and fragmenting process. To avoid this, we pick a random, # 256 KiB-aligned image base between 0x50000000 and 0x6FFC0000 at link # time. Moving up from 0x10000000 also allows more sbrk(2) space. _LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag $libobjs $deplibs $compiler_flags $wl-h,$soname $wl--image-base,`expr ${RANDOM-$$} % 4096 / 2 \* 262144 + 1342177280` -o $lib' _LT_TAGVAR(archive_expsym_cmds, $1)='sed "s|^|_|" $export_symbols >$output_objdir/$soname.expsym~$CC -shared $pic_flag $libobjs $deplibs $compiler_flags $wl-h,$soname $wl--retain-symbols-file,$output_objdir/$soname.expsym $wl--image-base,`expr ${RANDOM-$$} % 4096 / 2 \* 262144 + 1342177280` -o $lib' ;; gnu* | linux* | tpf* | k*bsd*-gnu | kopensolaris*-gnu) tmp_diet=no if test linux-dietlibc = "$host_os"; then case $cc_basename in diet\ *) tmp_diet=yes;; # linux-dietlibc with static linking (!diet-dyn) esac fi if $LD --help 2>&1 | $EGREP ': supported targets:.* elf' > /dev/null \ && test no = "$tmp_diet" then tmp_addflag=' $pic_flag' tmp_sharedflag='-shared' case $cc_basename,$host_cpu in pgcc*) # Portland Group C compiler _LT_TAGVAR(whole_archive_flag_spec, $1)='$wl--whole-archive`for conv in $convenience\"\"; do test -n \"$conv\" && new_convenience=\"$new_convenience,$conv\"; done; func_echo_all \"$new_convenience\"` $wl--no-whole-archive' tmp_addflag=' $pic_flag' ;; pgf77* | pgf90* | pgf95* | pgfortran*) # Portland Group f77 and f90 compilers _LT_TAGVAR(whole_archive_flag_spec, $1)='$wl--whole-archive`for conv in $convenience\"\"; do test -n \"$conv\" && new_convenience=\"$new_convenience,$conv\"; done; func_echo_all \"$new_convenience\"` $wl--no-whole-archive' tmp_addflag=' $pic_flag -Mnomain' ;; ecc*,ia64* | icc*,ia64*) # Intel C compiler on ia64 tmp_addflag=' -i_dynamic' ;; efc*,ia64* | ifort*,ia64*) # Intel Fortran compiler on ia64 tmp_addflag=' -i_dynamic -nofor_main' ;; ifc* | ifort*) # Intel Fortran compiler tmp_addflag=' -nofor_main' ;; lf95*) # Lahey Fortran 8.1 _LT_TAGVAR(whole_archive_flag_spec, $1)= tmp_sharedflag='--shared' ;; nagfor*) # NAGFOR 5.3 tmp_sharedflag='-Wl,-shared' ;; xl[[cC]]* | bgxl[[cC]]* | mpixl[[cC]]*) # IBM XL C 8.0 on PPC (deal with xlf below) tmp_sharedflag='-qmkshrobj' tmp_addflag= ;; nvcc*) # Cuda Compiler Driver 2.2 _LT_TAGVAR(whole_archive_flag_spec, $1)='$wl--whole-archive`for conv in $convenience\"\"; do test -n \"$conv\" && new_convenience=\"$new_convenience,$conv\"; done; func_echo_all \"$new_convenience\"` $wl--no-whole-archive' _LT_TAGVAR(compiler_needs_object, $1)=yes ;; esac case `$CC -V 2>&1 | sed 5q` in *Sun\ C*) # Sun C 5.9 _LT_TAGVAR(whole_archive_flag_spec, $1)='$wl--whole-archive`new_convenience=; for conv in $convenience\"\"; do test -z \"$conv\" || new_convenience=\"$new_convenience,$conv\"; done; func_echo_all \"$new_convenience\"` $wl--no-whole-archive' _LT_TAGVAR(compiler_needs_object, $1)=yes tmp_sharedflag='-G' ;; *Sun\ F*) # Sun Fortran 8.3 tmp_sharedflag='-G' ;; esac _LT_TAGVAR(archive_cmds, $1)='$CC '"$tmp_sharedflag""$tmp_addflag"' $libobjs $deplibs $compiler_flags $wl-soname $wl$soname -o $lib' if test yes = "$supports_anon_versioning"; then _LT_TAGVAR(archive_expsym_cmds, $1)='echo "{ global:" > $output_objdir/$libname.ver~ cat $export_symbols | sed -e "s/\(.*\)/\1;/" >> $output_objdir/$libname.ver~ echo "local: *; };" >> $output_objdir/$libname.ver~ $CC '"$tmp_sharedflag""$tmp_addflag"' $libobjs $deplibs $compiler_flags $wl-soname $wl$soname $wl-version-script $wl$output_objdir/$libname.ver -o $lib' fi case $cc_basename in tcc*) _LT_TAGVAR(export_dynamic_flag_spec, $1)='-rdynamic' ;; xlf* | bgf* | bgxlf* | mpixlf*) # IBM XL Fortran 10.1 on PPC cannot create shared libs itself _LT_TAGVAR(whole_archive_flag_spec, $1)='--whole-archive$convenience --no-whole-archive' _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='$wl-rpath $wl$libdir' _LT_TAGVAR(archive_cmds, $1)='$LD -shared $libobjs $deplibs $linker_flags -soname $soname -o $lib' if test yes = "$supports_anon_versioning"; then _LT_TAGVAR(archive_expsym_cmds, $1)='echo "{ global:" > $output_objdir/$libname.ver~ cat $export_symbols | sed -e "s/\(.*\)/\1;/" >> $output_objdir/$libname.ver~ echo "local: *; };" >> $output_objdir/$libname.ver~ $LD -shared $libobjs $deplibs $linker_flags -soname $soname -version-script $output_objdir/$libname.ver -o $lib' fi ;; esac else _LT_TAGVAR(ld_shlibs, $1)=no fi ;; netbsd*) if echo __ELF__ | $CC -E - | $GREP __ELF__ >/dev/null; then _LT_TAGVAR(archive_cmds, $1)='$LD -Bshareable $libobjs $deplibs $linker_flags -o $lib' wlarc= else _LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag $libobjs $deplibs $compiler_flags $wl-soname $wl$soname -o $lib' _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared $pic_flag $libobjs $deplibs $compiler_flags $wl-soname $wl$soname $wl-retain-symbols-file $wl$export_symbols -o $lib' fi ;; solaris*) if $LD -v 2>&1 | $GREP 'BFD 2\.8' > /dev/null; then _LT_TAGVAR(ld_shlibs, $1)=no cat <<_LT_EOF 1>&2 *** Warning: The releases 2.8.* of the GNU linker cannot reliably *** create shared libraries on Solaris systems. Therefore, libtool *** is disabling shared libraries support. We urge you to upgrade GNU *** binutils to release 2.9.1 or newer. Another option is to modify *** your PATH or compiler configuration so that the native linker is *** used, and then restart. _LT_EOF elif $LD --help 2>&1 | $GREP ': supported targets:.* elf' > /dev/null; then _LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag $libobjs $deplibs $compiler_flags $wl-soname $wl$soname -o $lib' _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared $pic_flag $libobjs $deplibs $compiler_flags $wl-soname $wl$soname $wl-retain-symbols-file $wl$export_symbols -o $lib' else _LT_TAGVAR(ld_shlibs, $1)=no fi ;; sysv5* | sco3.2v5* | sco5v6* | unixware* | OpenUNIX*) case `$LD -v 2>&1` in *\ [[01]].* | *\ 2.[[0-9]].* | *\ 2.1[[0-5]].*) _LT_TAGVAR(ld_shlibs, $1)=no cat <<_LT_EOF 1>&2 *** Warning: Releases of the GNU linker prior to 2.16.91.0.3 cannot *** reliably create shared libraries on SCO systems. Therefore, libtool *** is disabling shared libraries support. We urge you to upgrade GNU *** binutils to release 2.16.91.0.3 or newer. Another option is to modify *** your PATH or compiler configuration so that the native linker is *** used, and then restart. _LT_EOF ;; *) # For security reasons, it is highly recommended that you always # use absolute paths for naming shared libraries, and exclude the # DT_RUNPATH tag from executables and libraries. But doing so # requires that you compile everything twice, which is a pain. if $LD --help 2>&1 | $GREP ': supported targets:.* elf' > /dev/null; then _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='$wl-rpath $wl$libdir' _LT_TAGVAR(archive_cmds, $1)='$CC -shared $libobjs $deplibs $compiler_flags $wl-soname $wl$soname -o $lib' _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared $libobjs $deplibs $compiler_flags $wl-soname $wl$soname $wl-retain-symbols-file $wl$export_symbols -o $lib' else _LT_TAGVAR(ld_shlibs, $1)=no fi ;; esac ;; sunos4*) _LT_TAGVAR(archive_cmds, $1)='$LD -assert pure-text -Bshareable -o $lib $libobjs $deplibs $linker_flags' wlarc= _LT_TAGVAR(hardcode_direct, $1)=yes _LT_TAGVAR(hardcode_shlibpath_var, $1)=no ;; *) if $LD --help 2>&1 | $GREP ': supported targets:.* elf' > /dev/null; then _LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag $libobjs $deplibs $compiler_flags $wl-soname $wl$soname -o $lib' _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared $pic_flag $libobjs $deplibs $compiler_flags $wl-soname $wl$soname $wl-retain-symbols-file $wl$export_symbols -o $lib' else _LT_TAGVAR(ld_shlibs, $1)=no fi ;; esac if test no = "$_LT_TAGVAR(ld_shlibs, $1)"; then runpath_var= _LT_TAGVAR(hardcode_libdir_flag_spec, $1)= _LT_TAGVAR(export_dynamic_flag_spec, $1)= _LT_TAGVAR(whole_archive_flag_spec, $1)= fi else # PORTME fill in a description of your system's linker (not GNU ld) case $host_os in aix3*) _LT_TAGVAR(allow_undefined_flag, $1)=unsupported _LT_TAGVAR(always_export_symbols, $1)=yes _LT_TAGVAR(archive_expsym_cmds, $1)='$LD -o $output_objdir/$soname $libobjs $deplibs $linker_flags -bE:$export_symbols -T512 -H512 -bM:SRE~$AR $AR_FLAGS $lib $output_objdir/$soname' # Note: this linker hardcodes the directories in LIBPATH if there # are no directories specified by -L. _LT_TAGVAR(hardcode_minus_L, $1)=yes if test yes = "$GCC" && test -z "$lt_prog_compiler_static"; then # Neither direct hardcoding nor static linking is supported with a # broken collect2. _LT_TAGVAR(hardcode_direct, $1)=unsupported fi ;; aix[[4-9]]*) if test ia64 = "$host_cpu"; then # On IA64, the linker does run time linking by default, so we don't # have to do anything special. aix_use_runtimelinking=no exp_sym_flag='-Bexport' no_entry_flag= else # If we're using GNU nm, then we don't want the "-C" option. # -C means demangle to GNU nm, but means don't demangle to AIX nm. # Without the "-l" option, or with the "-B" option, AIX nm treats # weak defined symbols like other global defined symbols, whereas # GNU nm marks them as "W". # While the 'weak' keyword is ignored in the Export File, we need # it in the Import File for the 'aix-soname' feature, so we have # to replace the "-B" option with "-P" for AIX nm. if $NM -V 2>&1 | $GREP 'GNU' > /dev/null; then _LT_TAGVAR(export_symbols_cmds, $1)='$NM -Bpg $libobjs $convenience | awk '\''{ if (((\$ 2 == "T") || (\$ 2 == "D") || (\$ 2 == "B") || (\$ 2 == "W")) && ([substr](\$ 3,1,1) != ".")) { if (\$ 2 == "W") { print \$ 3 " weak" } else { print \$ 3 } } }'\'' | sort -u > $export_symbols' else _LT_TAGVAR(export_symbols_cmds, $1)='`func_echo_all $NM | $SED -e '\''s/B\([[^B]]*\)$/P\1/'\''` -PCpgl $libobjs $convenience | awk '\''{ if (((\$ 2 == "T") || (\$ 2 == "D") || (\$ 2 == "B") || (\$ 2 == "W") || (\$ 2 == "V") || (\$ 2 == "Z")) && ([substr](\$ 1,1,1) != ".")) { if ((\$ 2 == "W") || (\$ 2 == "V") || (\$ 2 == "Z")) { print \$ 1 " weak" } else { print \$ 1 } } }'\'' | sort -u > $export_symbols' fi aix_use_runtimelinking=no # Test if we are trying to use run time linking or normal # AIX style linking. If -brtl is somewhere in LDFLAGS, we # have runtime linking enabled, and use it for executables. # For shared libraries, we enable/disable runtime linking # depending on the kind of the shared library created - # when "with_aix_soname,aix_use_runtimelinking" is: # "aix,no" lib.a(lib.so.V) shared, rtl:no, for executables # "aix,yes" lib.so shared, rtl:yes, for executables # lib.a static archive # "both,no" lib.so.V(shr.o) shared, rtl:yes # lib.a(lib.so.V) shared, rtl:no, for executables # "both,yes" lib.so.V(shr.o) shared, rtl:yes, for executables # lib.a(lib.so.V) shared, rtl:no # "svr4,*" lib.so.V(shr.o) shared, rtl:yes, for executables # lib.a static archive case $host_os in aix4.[[23]]|aix4.[[23]].*|aix[[5-9]]*) for ld_flag in $LDFLAGS; do if (test x-brtl = "x$ld_flag" || test x-Wl,-brtl = "x$ld_flag"); then aix_use_runtimelinking=yes break fi done if test svr4,no = "$with_aix_soname,$aix_use_runtimelinking"; then # With aix-soname=svr4, we create the lib.so.V shared archives only, # so we don't have lib.a shared libs to link our executables. # We have to force runtime linking in this case. aix_use_runtimelinking=yes LDFLAGS="$LDFLAGS -Wl,-brtl" fi ;; esac exp_sym_flag='-bexport' no_entry_flag='-bnoentry' fi # When large executables or shared objects are built, AIX ld can # have problems creating the table of contents. If linking a library # or program results in "error TOC overflow" add -mminimal-toc to # CXXFLAGS/CFLAGS for g++/gcc. In the cases where that is not # enough to fix the problem, add -Wl,-bbigtoc to LDFLAGS. _LT_TAGVAR(archive_cmds, $1)='' _LT_TAGVAR(hardcode_direct, $1)=yes _LT_TAGVAR(hardcode_direct_absolute, $1)=yes _LT_TAGVAR(hardcode_libdir_separator, $1)=':' _LT_TAGVAR(link_all_deplibs, $1)=yes _LT_TAGVAR(file_list_spec, $1)='$wl-f,' case $with_aix_soname,$aix_use_runtimelinking in aix,*) ;; # traditional, no import file svr4,* | *,yes) # use import file # The Import File defines what to hardcode. _LT_TAGVAR(hardcode_direct, $1)=no _LT_TAGVAR(hardcode_direct_absolute, $1)=no ;; esac if test yes = "$GCC"; then case $host_os in aix4.[[012]]|aix4.[[012]].*) # We only want to do this on AIX 4.2 and lower, the check # below for broken collect2 doesn't work under 4.3+ collect2name=`$CC -print-prog-name=collect2` if test -f "$collect2name" && strings "$collect2name" | $GREP resolve_lib_name >/dev/null then # We have reworked collect2 : else # We have old collect2 _LT_TAGVAR(hardcode_direct, $1)=unsupported # It fails to find uninstalled libraries when the uninstalled # path is not listed in the libpath. Setting hardcode_minus_L # to unsupported forces relinking _LT_TAGVAR(hardcode_minus_L, $1)=yes _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-L$libdir' _LT_TAGVAR(hardcode_libdir_separator, $1)= fi ;; esac shared_flag='-shared' if test yes = "$aix_use_runtimelinking"; then shared_flag="$shared_flag "'$wl-G' fi # Need to ensure runtime linking is disabled for the traditional # shared library, or the linker may eventually find shared libraries # /with/ Import File - we do not want to mix them. shared_flag_aix='-shared' shared_flag_svr4='-shared $wl-G' else # not using gcc if test ia64 = "$host_cpu"; then # VisualAge C++, Version 5.5 for AIX 5L for IA-64, Beta 3 Release # chokes on -Wl,-G. The following line is correct: shared_flag='-G' else if test yes = "$aix_use_runtimelinking"; then shared_flag='$wl-G' else shared_flag='$wl-bM:SRE' fi shared_flag_aix='$wl-bM:SRE' shared_flag_svr4='$wl-G' fi fi _LT_TAGVAR(export_dynamic_flag_spec, $1)='$wl-bexpall' # It seems that -bexpall does not export symbols beginning with # underscore (_), so it is better to generate a list of symbols to export. _LT_TAGVAR(always_export_symbols, $1)=yes if test aix,yes = "$with_aix_soname,$aix_use_runtimelinking"; then # Warning - without using the other runtime loading flags (-brtl), # -berok will link without error, but may produce a broken library. _LT_TAGVAR(allow_undefined_flag, $1)='-berok' # Determine the default libpath from the value encoded in an # empty executable. _LT_SYS_MODULE_PATH_AIX([$1]) _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='$wl-blibpath:$libdir:'"$aix_libpath" _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -o $output_objdir/$soname $libobjs $deplibs $wl'$no_entry_flag' $compiler_flags `if test -n "$allow_undefined_flag"; then func_echo_all "$wl$allow_undefined_flag"; else :; fi` $wl'$exp_sym_flag:\$export_symbols' '$shared_flag else if test ia64 = "$host_cpu"; then _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='$wl-R $libdir:/usr/lib:/lib' _LT_TAGVAR(allow_undefined_flag, $1)="-z nodefs" _LT_TAGVAR(archive_expsym_cmds, $1)="\$CC $shared_flag"' -o $output_objdir/$soname $libobjs $deplibs '"\$wl$no_entry_flag"' $compiler_flags $wl$allow_undefined_flag '"\$wl$exp_sym_flag:\$export_symbols" else # Determine the default libpath from the value encoded in an # empty executable. _LT_SYS_MODULE_PATH_AIX([$1]) _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='$wl-blibpath:$libdir:'"$aix_libpath" # Warning - without using the other run time loading flags, # -berok will link without error, but may produce a broken library. _LT_TAGVAR(no_undefined_flag, $1)=' $wl-bernotok' _LT_TAGVAR(allow_undefined_flag, $1)=' $wl-berok' if test yes = "$with_gnu_ld"; then # We only use this code for GNU lds that support --whole-archive. _LT_TAGVAR(whole_archive_flag_spec, $1)='$wl--whole-archive$convenience $wl--no-whole-archive' else # Exported symbols can be pulled into shared objects from archives _LT_TAGVAR(whole_archive_flag_spec, $1)='$convenience' fi _LT_TAGVAR(archive_cmds_need_lc, $1)=yes _LT_TAGVAR(archive_expsym_cmds, $1)='$RM -r $output_objdir/$realname.d~$MKDIR $output_objdir/$realname.d' # -brtl affects multiple linker settings, -berok does not and is overridden later compiler_flags_filtered='`func_echo_all "$compiler_flags " | $SED -e "s%-brtl\\([[, ]]\\)%-berok\\1%g"`' if test svr4 != "$with_aix_soname"; then # This is similar to how AIX traditionally builds its shared libraries. _LT_TAGVAR(archive_expsym_cmds, $1)="$_LT_TAGVAR(archive_expsym_cmds, $1)"'~$CC '$shared_flag_aix' -o $output_objdir/$realname.d/$soname $libobjs $deplibs $wl-bnoentry '$compiler_flags_filtered'$wl-bE:$export_symbols$allow_undefined_flag~$AR $AR_FLAGS $output_objdir/$libname$release.a $output_objdir/$realname.d/$soname' fi if test aix != "$with_aix_soname"; then _LT_TAGVAR(archive_expsym_cmds, $1)="$_LT_TAGVAR(archive_expsym_cmds, $1)"'~$CC '$shared_flag_svr4' -o $output_objdir/$realname.d/$shared_archive_member_spec.o $libobjs $deplibs $wl-bnoentry '$compiler_flags_filtered'$wl-bE:$export_symbols$allow_undefined_flag~$STRIP -e $output_objdir/$realname.d/$shared_archive_member_spec.o~( func_echo_all "#! $soname($shared_archive_member_spec.o)"; if test shr_64 = "$shared_archive_member_spec"; then func_echo_all "# 64"; else func_echo_all "# 32"; fi; cat $export_symbols ) > $output_objdir/$realname.d/$shared_archive_member_spec.imp~$AR $AR_FLAGS $output_objdir/$soname $output_objdir/$realname.d/$shared_archive_member_spec.o $output_objdir/$realname.d/$shared_archive_member_spec.imp' else # used by -dlpreopen to get the symbols _LT_TAGVAR(archive_expsym_cmds, $1)="$_LT_TAGVAR(archive_expsym_cmds, $1)"'~$MV $output_objdir/$realname.d/$soname $output_objdir' fi _LT_TAGVAR(archive_expsym_cmds, $1)="$_LT_TAGVAR(archive_expsym_cmds, $1)"'~$RM -r $output_objdir/$realname.d' fi fi ;; amigaos*) case $host_cpu in powerpc) # see comment about AmigaOS4 .so support _LT_TAGVAR(archive_cmds, $1)='$CC -shared $libobjs $deplibs $compiler_flags $wl-soname $wl$soname -o $lib' _LT_TAGVAR(archive_expsym_cmds, $1)='' ;; m68k) _LT_TAGVAR(archive_cmds, $1)='$RM $output_objdir/a2ixlibrary.data~$ECHO "#define NAME $libname" > $output_objdir/a2ixlibrary.data~$ECHO "#define LIBRARY_ID 1" >> $output_objdir/a2ixlibrary.data~$ECHO "#define VERSION $major" >> $output_objdir/a2ixlibrary.data~$ECHO "#define REVISION $revision" >> $output_objdir/a2ixlibrary.data~$AR $AR_FLAGS $lib $libobjs~$RANLIB $lib~(cd $output_objdir && a2ixlibrary -32)' _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-L$libdir' _LT_TAGVAR(hardcode_minus_L, $1)=yes ;; esac ;; bsdi[[45]]*) _LT_TAGVAR(export_dynamic_flag_spec, $1)=-rdynamic ;; cygwin* | mingw* | pw32* | cegcc*) # When not using gcc, we currently assume that we are using # Microsoft Visual C++. # hardcode_libdir_flag_spec is actually meaningless, as there is # no search path for DLLs. case $cc_basename in cl*) # Native MSVC _LT_TAGVAR(hardcode_libdir_flag_spec, $1)=' ' _LT_TAGVAR(allow_undefined_flag, $1)=unsupported _LT_TAGVAR(always_export_symbols, $1)=yes _LT_TAGVAR(file_list_spec, $1)='@' # Tell ltmain to make .lib files, not .a files. libext=lib # Tell ltmain to make .dll files, not .so files. shrext_cmds=.dll # FIXME: Setting linknames here is a bad hack. _LT_TAGVAR(archive_cmds, $1)='$CC -o $output_objdir/$soname $libobjs $compiler_flags $deplibs -Wl,-DLL,-IMPLIB:"$tool_output_objdir$libname.dll.lib"~linknames=' _LT_TAGVAR(archive_expsym_cmds, $1)='if _LT_DLL_DEF_P([$export_symbols]); then cp "$export_symbols" "$output_objdir/$soname.def"; echo "$tool_output_objdir$soname.def" > "$output_objdir/$soname.exp"; else $SED -e '\''s/^/-link -EXPORT:/'\'' < $export_symbols > $output_objdir/$soname.exp; fi~ $CC -o $tool_output_objdir$soname $libobjs $compiler_flags $deplibs "@$tool_output_objdir$soname.exp" -Wl,-DLL,-IMPLIB:"$tool_output_objdir$libname.dll.lib"~ linknames=' # The linker will not automatically build a static lib if we build a DLL. # _LT_TAGVAR(old_archive_from_new_cmds, $1)='true' _LT_TAGVAR(enable_shared_with_static_runtimes, $1)=yes _LT_TAGVAR(exclude_expsyms, $1)='_NULL_IMPORT_DESCRIPTOR|_IMPORT_DESCRIPTOR_.*' _LT_TAGVAR(export_symbols_cmds, $1)='$NM $libobjs $convenience | $global_symbol_pipe | $SED -e '\''/^[[BCDGRS]][[ ]]/s/.*[[ ]]\([[^ ]]*\)/\1,DATA/'\'' | $SED -e '\''/^[[AITW]][[ ]]/s/.*[[ ]]//'\'' | sort | uniq > $export_symbols' # Don't use ranlib _LT_TAGVAR(old_postinstall_cmds, $1)='chmod 644 $oldlib' _LT_TAGVAR(postlink_cmds, $1)='lt_outputfile="@OUTPUT@"~ lt_tool_outputfile="@TOOL_OUTPUT@"~ case $lt_outputfile in *.exe|*.EXE) ;; *) lt_outputfile=$lt_outputfile.exe lt_tool_outputfile=$lt_tool_outputfile.exe ;; esac~ if test : != "$MANIFEST_TOOL" && test -f "$lt_outputfile.manifest"; then $MANIFEST_TOOL -manifest "$lt_tool_outputfile.manifest" -outputresource:"$lt_tool_outputfile" || exit 1; $RM "$lt_outputfile.manifest"; fi' ;; *) # Assume MSVC wrapper _LT_TAGVAR(hardcode_libdir_flag_spec, $1)=' ' _LT_TAGVAR(allow_undefined_flag, $1)=unsupported # Tell ltmain to make .lib files, not .a files. libext=lib # Tell ltmain to make .dll files, not .so files. shrext_cmds=.dll # FIXME: Setting linknames here is a bad hack. _LT_TAGVAR(archive_cmds, $1)='$CC -o $lib $libobjs $compiler_flags `func_echo_all "$deplibs" | $SED '\''s/ -lc$//'\''` -link -dll~linknames=' # The linker will automatically build a .lib file if we build a DLL. _LT_TAGVAR(old_archive_from_new_cmds, $1)='true' # FIXME: Should let the user specify the lib program. _LT_TAGVAR(old_archive_cmds, $1)='lib -OUT:$oldlib$oldobjs$old_deplibs' _LT_TAGVAR(enable_shared_with_static_runtimes, $1)=yes ;; esac ;; darwin* | rhapsody*) _LT_DARWIN_LINKER_FEATURES($1) ;; dgux*) _LT_TAGVAR(archive_cmds, $1)='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags' _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-L$libdir' _LT_TAGVAR(hardcode_shlibpath_var, $1)=no ;; # FreeBSD 2.2.[012] allows us to include c++rt0.o to get C++ constructor # support. Future versions do this automatically, but an explicit c++rt0.o # does not break anything, and helps significantly (at the cost of a little # extra space). freebsd2.2*) _LT_TAGVAR(archive_cmds, $1)='$LD -Bshareable -o $lib $libobjs $deplibs $linker_flags /usr/lib/c++rt0.o' _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-R$libdir' _LT_TAGVAR(hardcode_direct, $1)=yes _LT_TAGVAR(hardcode_shlibpath_var, $1)=no ;; # Unfortunately, older versions of FreeBSD 2 do not have this feature. freebsd2.*) _LT_TAGVAR(archive_cmds, $1)='$LD -Bshareable -o $lib $libobjs $deplibs $linker_flags' _LT_TAGVAR(hardcode_direct, $1)=yes _LT_TAGVAR(hardcode_minus_L, $1)=yes _LT_TAGVAR(hardcode_shlibpath_var, $1)=no ;; # FreeBSD 3 and greater uses gcc -shared to do shared libraries. freebsd* | dragonfly*) _LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag -o $lib $libobjs $deplibs $compiler_flags' _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-R$libdir' _LT_TAGVAR(hardcode_direct, $1)=yes _LT_TAGVAR(hardcode_shlibpath_var, $1)=no ;; hpux9*) if test yes = "$GCC"; then _LT_TAGVAR(archive_cmds, $1)='$RM $output_objdir/$soname~$CC -shared $pic_flag $wl+b $wl$install_libdir -o $output_objdir/$soname $libobjs $deplibs $compiler_flags~test "x$output_objdir/$soname" = "x$lib" || mv $output_objdir/$soname $lib' else _LT_TAGVAR(archive_cmds, $1)='$RM $output_objdir/$soname~$LD -b +b $install_libdir -o $output_objdir/$soname $libobjs $deplibs $linker_flags~test "x$output_objdir/$soname" = "x$lib" || mv $output_objdir/$soname $lib' fi _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='$wl+b $wl$libdir' _LT_TAGVAR(hardcode_libdir_separator, $1)=: _LT_TAGVAR(hardcode_direct, $1)=yes # hardcode_minus_L: Not really in the search PATH, # but as the default location of the library. _LT_TAGVAR(hardcode_minus_L, $1)=yes _LT_TAGVAR(export_dynamic_flag_spec, $1)='$wl-E' ;; hpux10*) if test yes,no = "$GCC,$with_gnu_ld"; then _LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag $wl+h $wl$soname $wl+b $wl$install_libdir -o $lib $libobjs $deplibs $compiler_flags' else _LT_TAGVAR(archive_cmds, $1)='$LD -b +h $soname +b $install_libdir -o $lib $libobjs $deplibs $linker_flags' fi if test no = "$with_gnu_ld"; then _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='$wl+b $wl$libdir' _LT_TAGVAR(hardcode_libdir_separator, $1)=: _LT_TAGVAR(hardcode_direct, $1)=yes _LT_TAGVAR(hardcode_direct_absolute, $1)=yes _LT_TAGVAR(export_dynamic_flag_spec, $1)='$wl-E' # hardcode_minus_L: Not really in the search PATH, # but as the default location of the library. _LT_TAGVAR(hardcode_minus_L, $1)=yes fi ;; hpux11*) if test yes,no = "$GCC,$with_gnu_ld"; then case $host_cpu in hppa*64*) _LT_TAGVAR(archive_cmds, $1)='$CC -shared $wl+h $wl$soname -o $lib $libobjs $deplibs $compiler_flags' ;; ia64*) _LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag $wl+h $wl$soname $wl+nodefaultrpath -o $lib $libobjs $deplibs $compiler_flags' ;; *) _LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag $wl+h $wl$soname $wl+b $wl$install_libdir -o $lib $libobjs $deplibs $compiler_flags' ;; esac else case $host_cpu in hppa*64*) _LT_TAGVAR(archive_cmds, $1)='$CC -b $wl+h $wl$soname -o $lib $libobjs $deplibs $compiler_flags' ;; ia64*) _LT_TAGVAR(archive_cmds, $1)='$CC -b $wl+h $wl$soname $wl+nodefaultrpath -o $lib $libobjs $deplibs $compiler_flags' ;; *) m4_if($1, [], [ # Older versions of the 11.00 compiler do not understand -b yet # (HP92453-01 A.11.01.20 doesn't, HP92453-01 B.11.X.35175-35176.GP does) _LT_LINKER_OPTION([if $CC understands -b], _LT_TAGVAR(lt_cv_prog_compiler__b, $1), [-b], [_LT_TAGVAR(archive_cmds, $1)='$CC -b $wl+h $wl$soname $wl+b $wl$install_libdir -o $lib $libobjs $deplibs $compiler_flags'], [_LT_TAGVAR(archive_cmds, $1)='$LD -b +h $soname +b $install_libdir -o $lib $libobjs $deplibs $linker_flags'])], [_LT_TAGVAR(archive_cmds, $1)='$CC -b $wl+h $wl$soname $wl+b $wl$install_libdir -o $lib $libobjs $deplibs $compiler_flags']) ;; esac fi if test no = "$with_gnu_ld"; then _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='$wl+b $wl$libdir' _LT_TAGVAR(hardcode_libdir_separator, $1)=: case $host_cpu in hppa*64*|ia64*) _LT_TAGVAR(hardcode_direct, $1)=no _LT_TAGVAR(hardcode_shlibpath_var, $1)=no ;; *) _LT_TAGVAR(hardcode_direct, $1)=yes _LT_TAGVAR(hardcode_direct_absolute, $1)=yes _LT_TAGVAR(export_dynamic_flag_spec, $1)='$wl-E' # hardcode_minus_L: Not really in the search PATH, # but as the default location of the library. _LT_TAGVAR(hardcode_minus_L, $1)=yes ;; esac fi ;; irix5* | irix6* | nonstopux*) if test yes = "$GCC"; then _LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag $libobjs $deplibs $compiler_flags $wl-soname $wl$soname `test -n "$verstring" && func_echo_all "$wl-set_version $wl$verstring"` $wl-update_registry $wl$output_objdir/so_locations -o $lib' # Try to use the -exported_symbol ld option, if it does not # work, assume that -exports_file does not work either and # implicitly export all symbols. # This should be the same for all languages, so no per-tag cache variable. AC_CACHE_CHECK([whether the $host_os linker accepts -exported_symbol], [lt_cv_irix_exported_symbol], [save_LDFLAGS=$LDFLAGS LDFLAGS="$LDFLAGS -shared $wl-exported_symbol ${wl}foo $wl-update_registry $wl/dev/null" AC_LINK_IFELSE( [AC_LANG_SOURCE( [AC_LANG_CASE([C], [[int foo (void) { return 0; }]], [C++], [[int foo (void) { return 0; }]], [Fortran 77], [[ subroutine foo end]], [Fortran], [[ subroutine foo end]])])], [lt_cv_irix_exported_symbol=yes], [lt_cv_irix_exported_symbol=no]) LDFLAGS=$save_LDFLAGS]) if test yes = "$lt_cv_irix_exported_symbol"; then _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared $pic_flag $libobjs $deplibs $compiler_flags $wl-soname $wl$soname `test -n "$verstring" && func_echo_all "$wl-set_version $wl$verstring"` $wl-update_registry $wl$output_objdir/so_locations $wl-exports_file $wl$export_symbols -o $lib' fi else _LT_TAGVAR(archive_cmds, $1)='$CC -shared $libobjs $deplibs $compiler_flags -soname $soname `test -n "$verstring" && func_echo_all "-set_version $verstring"` -update_registry $output_objdir/so_locations -o $lib' _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared $libobjs $deplibs $compiler_flags -soname $soname `test -n "$verstring" && func_echo_all "-set_version $verstring"` -update_registry $output_objdir/so_locations -exports_file $export_symbols -o $lib' fi _LT_TAGVAR(archive_cmds_need_lc, $1)='no' _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='$wl-rpath $wl$libdir' _LT_TAGVAR(hardcode_libdir_separator, $1)=: _LT_TAGVAR(inherit_rpath, $1)=yes _LT_TAGVAR(link_all_deplibs, $1)=yes ;; linux*) case $cc_basename in tcc*) # Fabrice Bellard et al's Tiny C Compiler _LT_TAGVAR(ld_shlibs, $1)=yes _LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag -o $lib $libobjs $deplibs $compiler_flags' ;; esac ;; netbsd*) if echo __ELF__ | $CC -E - | $GREP __ELF__ >/dev/null; then _LT_TAGVAR(archive_cmds, $1)='$LD -Bshareable -o $lib $libobjs $deplibs $linker_flags' # a.out else _LT_TAGVAR(archive_cmds, $1)='$LD -shared -o $lib $libobjs $deplibs $linker_flags' # ELF fi _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-R$libdir' _LT_TAGVAR(hardcode_direct, $1)=yes _LT_TAGVAR(hardcode_shlibpath_var, $1)=no ;; newsos6) _LT_TAGVAR(archive_cmds, $1)='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags' _LT_TAGVAR(hardcode_direct, $1)=yes _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='$wl-rpath $wl$libdir' _LT_TAGVAR(hardcode_libdir_separator, $1)=: _LT_TAGVAR(hardcode_shlibpath_var, $1)=no ;; *nto* | *qnx*) ;; openbsd* | bitrig*) if test -f /usr/libexec/ld.so; then _LT_TAGVAR(hardcode_direct, $1)=yes _LT_TAGVAR(hardcode_shlibpath_var, $1)=no _LT_TAGVAR(hardcode_direct_absolute, $1)=yes if test -z "`echo __ELF__ | $CC -E - | $GREP __ELF__`"; then _LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag -o $lib $libobjs $deplibs $compiler_flags' _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared $pic_flag -o $lib $libobjs $deplibs $compiler_flags $wl-retain-symbols-file,$export_symbols' _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='$wl-rpath,$libdir' _LT_TAGVAR(export_dynamic_flag_spec, $1)='$wl-E' else _LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag -o $lib $libobjs $deplibs $compiler_flags' _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='$wl-rpath,$libdir' fi else _LT_TAGVAR(ld_shlibs, $1)=no fi ;; os2*) _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-L$libdir' _LT_TAGVAR(hardcode_minus_L, $1)=yes _LT_TAGVAR(allow_undefined_flag, $1)=unsupported shrext_cmds=.dll _LT_TAGVAR(archive_cmds, $1)='$ECHO "LIBRARY ${soname%$shared_ext} INITINSTANCE TERMINSTANCE" > $output_objdir/$libname.def~ $ECHO "DESCRIPTION \"$libname\"" >> $output_objdir/$libname.def~ $ECHO "DATA MULTIPLE NONSHARED" >> $output_objdir/$libname.def~ $ECHO EXPORTS >> $output_objdir/$libname.def~ emxexp $libobjs | $SED /"_DLL_InitTerm"/d >> $output_objdir/$libname.def~ $CC -Zdll -Zcrtdll -o $output_objdir/$soname $libobjs $deplibs $compiler_flags $output_objdir/$libname.def~ emximp -o $lib $output_objdir/$libname.def' _LT_TAGVAR(archive_expsym_cmds, $1)='$ECHO "LIBRARY ${soname%$shared_ext} INITINSTANCE TERMINSTANCE" > $output_objdir/$libname.def~ $ECHO "DESCRIPTION \"$libname\"" >> $output_objdir/$libname.def~ $ECHO "DATA MULTIPLE NONSHARED" >> $output_objdir/$libname.def~ $ECHO EXPORTS >> $output_objdir/$libname.def~ prefix_cmds="$SED"~ if test EXPORTS = "`$SED 1q $export_symbols`"; then prefix_cmds="$prefix_cmds -e 1d"; fi~ prefix_cmds="$prefix_cmds -e \"s/^\(.*\)$/_\1/g\""~ cat $export_symbols | $prefix_cmds >> $output_objdir/$libname.def~ $CC -Zdll -Zcrtdll -o $output_objdir/$soname $libobjs $deplibs $compiler_flags $output_objdir/$libname.def~ emximp -o $lib $output_objdir/$libname.def' _LT_TAGVAR(old_archive_From_new_cmds, $1)='emximp -o $output_objdir/${libname}_dll.a $output_objdir/$libname.def' _LT_TAGVAR(enable_shared_with_static_runtimes, $1)=yes ;; osf3*) if test yes = "$GCC"; then _LT_TAGVAR(allow_undefined_flag, $1)=' $wl-expect_unresolved $wl\*' _LT_TAGVAR(archive_cmds, $1)='$CC -shared$allow_undefined_flag $libobjs $deplibs $compiler_flags $wl-soname $wl$soname `test -n "$verstring" && func_echo_all "$wl-set_version $wl$verstring"` $wl-update_registry $wl$output_objdir/so_locations -o $lib' else _LT_TAGVAR(allow_undefined_flag, $1)=' -expect_unresolved \*' _LT_TAGVAR(archive_cmds, $1)='$CC -shared$allow_undefined_flag $libobjs $deplibs $compiler_flags -soname $soname `test -n "$verstring" && func_echo_all "-set_version $verstring"` -update_registry $output_objdir/so_locations -o $lib' fi _LT_TAGVAR(archive_cmds_need_lc, $1)='no' _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='$wl-rpath $wl$libdir' _LT_TAGVAR(hardcode_libdir_separator, $1)=: ;; osf4* | osf5*) # as osf3* with the addition of -msym flag if test yes = "$GCC"; then _LT_TAGVAR(allow_undefined_flag, $1)=' $wl-expect_unresolved $wl\*' _LT_TAGVAR(archive_cmds, $1)='$CC -shared$allow_undefined_flag $pic_flag $libobjs $deplibs $compiler_flags $wl-msym $wl-soname $wl$soname `test -n "$verstring" && func_echo_all "$wl-set_version $wl$verstring"` $wl-update_registry $wl$output_objdir/so_locations -o $lib' _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='$wl-rpath $wl$libdir' else _LT_TAGVAR(allow_undefined_flag, $1)=' -expect_unresolved \*' _LT_TAGVAR(archive_cmds, $1)='$CC -shared$allow_undefined_flag $libobjs $deplibs $compiler_flags -msym -soname $soname `test -n "$verstring" && func_echo_all "-set_version $verstring"` -update_registry $output_objdir/so_locations -o $lib' _LT_TAGVAR(archive_expsym_cmds, $1)='for i in `cat $export_symbols`; do printf "%s %s\\n" -exported_symbol "\$i" >> $lib.exp; done; printf "%s\\n" "-hidden">> $lib.exp~ $CC -shared$allow_undefined_flag $wl-input $wl$lib.exp $compiler_flags $libobjs $deplibs -soname $soname `test -n "$verstring" && $ECHO "-set_version $verstring"` -update_registry $output_objdir/so_locations -o $lib~$RM $lib.exp' # Both c and cxx compiler support -rpath directly _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-rpath $libdir' fi _LT_TAGVAR(archive_cmds_need_lc, $1)='no' _LT_TAGVAR(hardcode_libdir_separator, $1)=: ;; solaris*) _LT_TAGVAR(no_undefined_flag, $1)=' -z defs' if test yes = "$GCC"; then wlarc='$wl' _LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag $wl-z ${wl}text $wl-h $wl$soname -o $lib $libobjs $deplibs $compiler_flags' _LT_TAGVAR(archive_expsym_cmds, $1)='echo "{ global:" > $lib.exp~cat $export_symbols | $SED -e "s/\(.*\)/\1;/" >> $lib.exp~echo "local: *; };" >> $lib.exp~ $CC -shared $pic_flag $wl-z ${wl}text $wl-M $wl$lib.exp $wl-h $wl$soname -o $lib $libobjs $deplibs $compiler_flags~$RM $lib.exp' else case `$CC -V 2>&1` in *"Compilers 5.0"*) wlarc='' _LT_TAGVAR(archive_cmds, $1)='$LD -G$allow_undefined_flag -h $soname -o $lib $libobjs $deplibs $linker_flags' _LT_TAGVAR(archive_expsym_cmds, $1)='echo "{ global:" > $lib.exp~cat $export_symbols | $SED -e "s/\(.*\)/\1;/" >> $lib.exp~echo "local: *; };" >> $lib.exp~ $LD -G$allow_undefined_flag -M $lib.exp -h $soname -o $lib $libobjs $deplibs $linker_flags~$RM $lib.exp' ;; *) wlarc='$wl' _LT_TAGVAR(archive_cmds, $1)='$CC -G$allow_undefined_flag -h $soname -o $lib $libobjs $deplibs $compiler_flags' _LT_TAGVAR(archive_expsym_cmds, $1)='echo "{ global:" > $lib.exp~cat $export_symbols | $SED -e "s/\(.*\)/\1;/" >> $lib.exp~echo "local: *; };" >> $lib.exp~ $CC -G$allow_undefined_flag -M $lib.exp -h $soname -o $lib $libobjs $deplibs $compiler_flags~$RM $lib.exp' ;; esac fi _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-R$libdir' _LT_TAGVAR(hardcode_shlibpath_var, $1)=no case $host_os in solaris2.[[0-5]] | solaris2.[[0-5]].*) ;; *) # The compiler driver will combine and reorder linker options, # but understands '-z linker_flag'. GCC discards it without '$wl', # but is careful enough not to reorder. # Supported since Solaris 2.6 (maybe 2.5.1?) if test yes = "$GCC"; then _LT_TAGVAR(whole_archive_flag_spec, $1)='$wl-z ${wl}allextract$convenience $wl-z ${wl}defaultextract' else _LT_TAGVAR(whole_archive_flag_spec, $1)='-z allextract$convenience -z defaultextract' fi ;; esac _LT_TAGVAR(link_all_deplibs, $1)=yes ;; sunos4*) if test sequent = "$host_vendor"; then # Use $CC to link under sequent, because it throws in some extra .o # files that make .init and .fini sections work. _LT_TAGVAR(archive_cmds, $1)='$CC -G $wl-h $soname -o $lib $libobjs $deplibs $compiler_flags' else _LT_TAGVAR(archive_cmds, $1)='$LD -assert pure-text -Bstatic -o $lib $libobjs $deplibs $linker_flags' fi _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-L$libdir' _LT_TAGVAR(hardcode_direct, $1)=yes _LT_TAGVAR(hardcode_minus_L, $1)=yes _LT_TAGVAR(hardcode_shlibpath_var, $1)=no ;; sysv4) case $host_vendor in sni) _LT_TAGVAR(archive_cmds, $1)='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags' _LT_TAGVAR(hardcode_direct, $1)=yes # is this really true??? ;; siemens) ## LD is ld it makes a PLAMLIB ## CC just makes a GrossModule. _LT_TAGVAR(archive_cmds, $1)='$LD -G -o $lib $libobjs $deplibs $linker_flags' _LT_TAGVAR(reload_cmds, $1)='$CC -r -o $output$reload_objs' _LT_TAGVAR(hardcode_direct, $1)=no ;; motorola) _LT_TAGVAR(archive_cmds, $1)='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags' _LT_TAGVAR(hardcode_direct, $1)=no #Motorola manual says yes, but my tests say they lie ;; esac runpath_var='LD_RUN_PATH' _LT_TAGVAR(hardcode_shlibpath_var, $1)=no ;; sysv4.3*) _LT_TAGVAR(archive_cmds, $1)='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags' _LT_TAGVAR(hardcode_shlibpath_var, $1)=no _LT_TAGVAR(export_dynamic_flag_spec, $1)='-Bexport' ;; sysv4*MP*) if test -d /usr/nec; then _LT_TAGVAR(archive_cmds, $1)='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags' _LT_TAGVAR(hardcode_shlibpath_var, $1)=no runpath_var=LD_RUN_PATH hardcode_runpath_var=yes _LT_TAGVAR(ld_shlibs, $1)=yes fi ;; sysv4*uw2* | sysv5OpenUNIX* | sysv5UnixWare7.[[01]].[[10]]* | unixware7* | sco3.2v5.0.[[024]]*) _LT_TAGVAR(no_undefined_flag, $1)='$wl-z,text' _LT_TAGVAR(archive_cmds_need_lc, $1)=no _LT_TAGVAR(hardcode_shlibpath_var, $1)=no runpath_var='LD_RUN_PATH' if test yes = "$GCC"; then _LT_TAGVAR(archive_cmds, $1)='$CC -shared $wl-h,$soname -o $lib $libobjs $deplibs $compiler_flags' _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared $wl-Bexport:$export_symbols $wl-h,$soname -o $lib $libobjs $deplibs $compiler_flags' else _LT_TAGVAR(archive_cmds, $1)='$CC -G $wl-h,$soname -o $lib $libobjs $deplibs $compiler_flags' _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -G $wl-Bexport:$export_symbols $wl-h,$soname -o $lib $libobjs $deplibs $compiler_flags' fi ;; sysv5* | sco3.2v5* | sco5v6*) # Note: We CANNOT use -z defs as we might desire, because we do not # link with -lc, and that would cause any symbols used from libc to # always be unresolved, which means just about no library would # ever link correctly. If we're not using GNU ld we use -z text # though, which does catch some bad symbols but isn't as heavy-handed # as -z defs. _LT_TAGVAR(no_undefined_flag, $1)='$wl-z,text' _LT_TAGVAR(allow_undefined_flag, $1)='$wl-z,nodefs' _LT_TAGVAR(archive_cmds_need_lc, $1)=no _LT_TAGVAR(hardcode_shlibpath_var, $1)=no _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='$wl-R,$libdir' _LT_TAGVAR(hardcode_libdir_separator, $1)=':' _LT_TAGVAR(link_all_deplibs, $1)=yes _LT_TAGVAR(export_dynamic_flag_spec, $1)='$wl-Bexport' runpath_var='LD_RUN_PATH' if test yes = "$GCC"; then _LT_TAGVAR(archive_cmds, $1)='$CC -shared $wl-h,$soname -o $lib $libobjs $deplibs $compiler_flags' _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared $wl-Bexport:$export_symbols $wl-h,$soname -o $lib $libobjs $deplibs $compiler_flags' else _LT_TAGVAR(archive_cmds, $1)='$CC -G $wl-h,$soname -o $lib $libobjs $deplibs $compiler_flags' _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -G $wl-Bexport:$export_symbols $wl-h,$soname -o $lib $libobjs $deplibs $compiler_flags' fi ;; uts4*) _LT_TAGVAR(archive_cmds, $1)='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags' _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-L$libdir' _LT_TAGVAR(hardcode_shlibpath_var, $1)=no ;; *) _LT_TAGVAR(ld_shlibs, $1)=no ;; esac if test sni = "$host_vendor"; then case $host in sysv4 | sysv4.2uw2* | sysv4.3* | sysv5*) _LT_TAGVAR(export_dynamic_flag_spec, $1)='$wl-Blargedynsym' ;; esac fi fi ]) AC_MSG_RESULT([$_LT_TAGVAR(ld_shlibs, $1)]) test no = "$_LT_TAGVAR(ld_shlibs, $1)" && can_build_shared=no _LT_TAGVAR(with_gnu_ld, $1)=$with_gnu_ld _LT_DECL([], [libext], [0], [Old archive suffix (normally "a")])dnl _LT_DECL([], [shrext_cmds], [1], [Shared library suffix (normally ".so")])dnl _LT_DECL([], [extract_expsyms_cmds], [2], [The commands to extract the exported symbol list from a shared archive]) # # Do we need to explicitly link libc? # case "x$_LT_TAGVAR(archive_cmds_need_lc, $1)" in x|xyes) # Assume -lc should be added _LT_TAGVAR(archive_cmds_need_lc, $1)=yes if test yes,yes = "$GCC,$enable_shared"; then case $_LT_TAGVAR(archive_cmds, $1) in *'~'*) # FIXME: we may have to deal with multi-command sequences. ;; '$CC '*) # Test whether the compiler implicitly links with -lc since on some # systems, -lgcc has to come before -lc. If gcc already passes -lc # to ld, don't add -lc before -lgcc. AC_CACHE_CHECK([whether -lc should be explicitly linked in], [lt_cv_]_LT_TAGVAR(archive_cmds_need_lc, $1), [$RM conftest* echo "$lt_simple_compile_test_code" > conftest.$ac_ext if AC_TRY_EVAL(ac_compile) 2>conftest.err; then soname=conftest lib=conftest libobjs=conftest.$ac_objext deplibs= wl=$_LT_TAGVAR(lt_prog_compiler_wl, $1) pic_flag=$_LT_TAGVAR(lt_prog_compiler_pic, $1) compiler_flags=-v linker_flags=-v verstring= output_objdir=. libname=conftest lt_save_allow_undefined_flag=$_LT_TAGVAR(allow_undefined_flag, $1) _LT_TAGVAR(allow_undefined_flag, $1)= if AC_TRY_EVAL(_LT_TAGVAR(archive_cmds, $1) 2\>\&1 \| $GREP \" -lc \" \>/dev/null 2\>\&1) then lt_cv_[]_LT_TAGVAR(archive_cmds_need_lc, $1)=no else lt_cv_[]_LT_TAGVAR(archive_cmds_need_lc, $1)=yes fi _LT_TAGVAR(allow_undefined_flag, $1)=$lt_save_allow_undefined_flag else cat conftest.err 1>&5 fi $RM conftest* ]) _LT_TAGVAR(archive_cmds_need_lc, $1)=$lt_cv_[]_LT_TAGVAR(archive_cmds_need_lc, $1) ;; esac fi ;; esac _LT_TAGDECL([build_libtool_need_lc], [archive_cmds_need_lc], [0], [Whether or not to add -lc for building shared libraries]) _LT_TAGDECL([allow_libtool_libs_with_static_runtimes], [enable_shared_with_static_runtimes], [0], [Whether or not to disallow shared libs when runtime libs are static]) _LT_TAGDECL([], [export_dynamic_flag_spec], [1], [Compiler flag to allow reflexive dlopens]) _LT_TAGDECL([], [whole_archive_flag_spec], [1], [Compiler flag to generate shared objects directly from archives]) _LT_TAGDECL([], [compiler_needs_object], [1], [Whether the compiler copes with passing no objects directly]) _LT_TAGDECL([], [old_archive_from_new_cmds], [2], [Create an old-style archive from a shared archive]) _LT_TAGDECL([], [old_archive_from_expsyms_cmds], [2], [Create a temporary old-style archive to link instead of a shared archive]) _LT_TAGDECL([], [archive_cmds], [2], [Commands used to build a shared archive]) _LT_TAGDECL([], [archive_expsym_cmds], [2]) _LT_TAGDECL([], [module_cmds], [2], [Commands used to build a loadable module if different from building a shared archive.]) _LT_TAGDECL([], [module_expsym_cmds], [2]) _LT_TAGDECL([], [with_gnu_ld], [1], [Whether we are building with GNU ld or not]) _LT_TAGDECL([], [allow_undefined_flag], [1], [Flag that allows shared libraries with undefined symbols to be built]) _LT_TAGDECL([], [no_undefined_flag], [1], [Flag that enforces no undefined symbols]) _LT_TAGDECL([], [hardcode_libdir_flag_spec], [1], [Flag to hardcode $libdir into a binary during linking. This must work even if $libdir does not exist]) _LT_TAGDECL([], [hardcode_libdir_separator], [1], [Whether we need a single "-rpath" flag with a separated argument]) _LT_TAGDECL([], [hardcode_direct], [0], [Set to "yes" if using DIR/libNAME$shared_ext during linking hardcodes DIR into the resulting binary]) _LT_TAGDECL([], [hardcode_direct_absolute], [0], [Set to "yes" if using DIR/libNAME$shared_ext during linking hardcodes DIR into the resulting binary and the resulting library dependency is "absolute", i.e impossible to change by setting $shlibpath_var if the library is relocated]) _LT_TAGDECL([], [hardcode_minus_L], [0], [Set to "yes" if using the -LDIR flag during linking hardcodes DIR into the resulting binary]) _LT_TAGDECL([], [hardcode_shlibpath_var], [0], [Set to "yes" if using SHLIBPATH_VAR=DIR during linking hardcodes DIR into the resulting binary]) _LT_TAGDECL([], [hardcode_automatic], [0], [Set to "yes" if building a shared library automatically hardcodes DIR into the library and all subsequent libraries and executables linked against it]) _LT_TAGDECL([], [inherit_rpath], [0], [Set to yes if linker adds runtime paths of dependent libraries to runtime path list]) _LT_TAGDECL([], [link_all_deplibs], [0], [Whether libtool must link a program against all its dependency libraries]) _LT_TAGDECL([], [always_export_symbols], [0], [Set to "yes" if exported symbols are required]) _LT_TAGDECL([], [export_symbols_cmds], [2], [The commands to list exported symbols]) _LT_TAGDECL([], [exclude_expsyms], [1], [Symbols that should not be listed in the preloaded symbols]) _LT_TAGDECL([], [include_expsyms], [1], [Symbols that must always be exported]) _LT_TAGDECL([], [prelink_cmds], [2], [Commands necessary for linking programs (against libraries) with templates]) _LT_TAGDECL([], [postlink_cmds], [2], [Commands necessary for finishing linking programs]) _LT_TAGDECL([], [file_list_spec], [1], [Specify filename containing input files]) dnl FIXME: Not yet implemented dnl _LT_TAGDECL([], [thread_safe_flag_spec], [1], dnl [Compiler flag to generate thread safe objects]) ])# _LT_LINKER_SHLIBS # _LT_LANG_C_CONFIG([TAG]) # ------------------------ # Ensure that the configuration variables for a C compiler are suitably # defined. These variables are subsequently used by _LT_CONFIG to write # the compiler configuration to 'libtool'. m4_defun([_LT_LANG_C_CONFIG], [m4_require([_LT_DECL_EGREP])dnl lt_save_CC=$CC AC_LANG_PUSH(C) # Source file extension for C test sources. ac_ext=c # Object file extension for compiled C test sources. objext=o _LT_TAGVAR(objext, $1)=$objext # Code to be used in simple compile tests lt_simple_compile_test_code="int some_variable = 0;" # Code to be used in simple link tests lt_simple_link_test_code='int main(){return(0);}' _LT_TAG_COMPILER # Save the default compiler, since it gets overwritten when the other # tags are being tested, and _LT_TAGVAR(compiler, []) is a NOP. compiler_DEFAULT=$CC # save warnings/boilerplate of simple test code _LT_COMPILER_BOILERPLATE _LT_LINKER_BOILERPLATE if test -n "$compiler"; then _LT_COMPILER_NO_RTTI($1) _LT_COMPILER_PIC($1) _LT_COMPILER_C_O($1) _LT_COMPILER_FILE_LOCKS($1) _LT_LINKER_SHLIBS($1) _LT_SYS_DYNAMIC_LINKER($1) _LT_LINKER_HARDCODE_LIBPATH($1) LT_SYS_DLOPEN_SELF _LT_CMD_STRIPLIB # Report what library types will actually be built AC_MSG_CHECKING([if libtool supports shared libraries]) AC_MSG_RESULT([$can_build_shared]) AC_MSG_CHECKING([whether to build shared libraries]) test no = "$can_build_shared" && enable_shared=no # On AIX, shared libraries and static libraries use the same namespace, and # are all built from PIC. case $host_os in aix3*) test yes = "$enable_shared" && enable_static=no if test -n "$RANLIB"; then archive_cmds="$archive_cmds~\$RANLIB \$lib" postinstall_cmds='$RANLIB $lib' fi ;; aix[[4-9]]*) if test ia64 != "$host_cpu"; then case $enable_shared,$with_aix_soname,$aix_use_runtimelinking in yes,aix,yes) ;; # shared object as lib.so file only yes,svr4,*) ;; # shared object as lib.so archive member only yes,*) enable_static=no ;; # shared object in lib.a archive as well esac fi ;; esac AC_MSG_RESULT([$enable_shared]) AC_MSG_CHECKING([whether to build static libraries]) # Make sure either enable_shared or enable_static is yes. test yes = "$enable_shared" || enable_static=yes AC_MSG_RESULT([$enable_static]) _LT_CONFIG($1) fi AC_LANG_POP CC=$lt_save_CC ])# _LT_LANG_C_CONFIG # _LT_LANG_CXX_CONFIG([TAG]) # -------------------------- # Ensure that the configuration variables for a C++ compiler are suitably # defined. These variables are subsequently used by _LT_CONFIG to write # the compiler configuration to 'libtool'. m4_defun([_LT_LANG_CXX_CONFIG], [m4_require([_LT_FILEUTILS_DEFAULTS])dnl m4_require([_LT_DECL_EGREP])dnl m4_require([_LT_PATH_MANIFEST_TOOL])dnl if test -n "$CXX" && ( test no != "$CXX" && ( (test g++ = "$CXX" && `g++ -v >/dev/null 2>&1` ) || (test g++ != "$CXX"))); then AC_PROG_CXXCPP else _lt_caught_CXX_error=yes fi AC_LANG_PUSH(C++) _LT_TAGVAR(archive_cmds_need_lc, $1)=no _LT_TAGVAR(allow_undefined_flag, $1)= _LT_TAGVAR(always_export_symbols, $1)=no _LT_TAGVAR(archive_expsym_cmds, $1)= _LT_TAGVAR(compiler_needs_object, $1)=no _LT_TAGVAR(export_dynamic_flag_spec, $1)= _LT_TAGVAR(hardcode_direct, $1)=no _LT_TAGVAR(hardcode_direct_absolute, $1)=no _LT_TAGVAR(hardcode_libdir_flag_spec, $1)= _LT_TAGVAR(hardcode_libdir_separator, $1)= _LT_TAGVAR(hardcode_minus_L, $1)=no _LT_TAGVAR(hardcode_shlibpath_var, $1)=unsupported _LT_TAGVAR(hardcode_automatic, $1)=no _LT_TAGVAR(inherit_rpath, $1)=no _LT_TAGVAR(module_cmds, $1)= _LT_TAGVAR(module_expsym_cmds, $1)= _LT_TAGVAR(link_all_deplibs, $1)=unknown _LT_TAGVAR(old_archive_cmds, $1)=$old_archive_cmds _LT_TAGVAR(reload_flag, $1)=$reload_flag _LT_TAGVAR(reload_cmds, $1)=$reload_cmds _LT_TAGVAR(no_undefined_flag, $1)= _LT_TAGVAR(whole_archive_flag_spec, $1)= _LT_TAGVAR(enable_shared_with_static_runtimes, $1)=no # Source file extension for C++ test sources. ac_ext=cpp # Object file extension for compiled C++ test sources. objext=o _LT_TAGVAR(objext, $1)=$objext # No sense in running all these tests if we already determined that # the CXX compiler isn't working. Some variables (like enable_shared) # are currently assumed to apply to all compilers on this platform, # and will be corrupted by setting them based on a non-working compiler. if test yes != "$_lt_caught_CXX_error"; then # Code to be used in simple compile tests lt_simple_compile_test_code="int some_variable = 0;" # Code to be used in simple link tests lt_simple_link_test_code='int main(int, char *[[]]) { return(0); }' # ltmain only uses $CC for tagged configurations so make sure $CC is set. _LT_TAG_COMPILER # save warnings/boilerplate of simple test code _LT_COMPILER_BOILERPLATE _LT_LINKER_BOILERPLATE # Allow CC to be a program name with arguments. lt_save_CC=$CC lt_save_CFLAGS=$CFLAGS lt_save_LD=$LD lt_save_GCC=$GCC GCC=$GXX lt_save_with_gnu_ld=$with_gnu_ld lt_save_path_LD=$lt_cv_path_LD if test -n "${lt_cv_prog_gnu_ldcxx+set}"; then lt_cv_prog_gnu_ld=$lt_cv_prog_gnu_ldcxx else $as_unset lt_cv_prog_gnu_ld fi if test -n "${lt_cv_path_LDCXX+set}"; then lt_cv_path_LD=$lt_cv_path_LDCXX else $as_unset lt_cv_path_LD fi test -z "${LDCXX+set}" || LD=$LDCXX CC=${CXX-"c++"} CFLAGS=$CXXFLAGS compiler=$CC _LT_TAGVAR(compiler, $1)=$CC _LT_CC_BASENAME([$compiler]) if test -n "$compiler"; then # We don't want -fno-exception when compiling C++ code, so set the # no_builtin_flag separately if test yes = "$GXX"; then _LT_TAGVAR(lt_prog_compiler_no_builtin_flag, $1)=' -fno-builtin' else _LT_TAGVAR(lt_prog_compiler_no_builtin_flag, $1)= fi if test yes = "$GXX"; then # Set up default GNU C++ configuration LT_PATH_LD # Check if GNU C++ uses GNU ld as the underlying linker, since the # archiving commands below assume that GNU ld is being used. if test yes = "$with_gnu_ld"; then _LT_TAGVAR(archive_cmds, $1)='$CC $pic_flag -shared -nostdlib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags $wl-soname $wl$soname -o $lib' _LT_TAGVAR(archive_expsym_cmds, $1)='$CC $pic_flag -shared -nostdlib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags $wl-soname $wl$soname $wl-retain-symbols-file $wl$export_symbols -o $lib' _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='$wl-rpath $wl$libdir' _LT_TAGVAR(export_dynamic_flag_spec, $1)='$wl--export-dynamic' # If archive_cmds runs LD, not CC, wlarc should be empty # XXX I think wlarc can be eliminated in ltcf-cxx, but I need to # investigate it a little bit more. (MM) wlarc='$wl' # ancient GNU ld didn't support --whole-archive et. al. if eval "`$CC -print-prog-name=ld` --help 2>&1" | $GREP 'no-whole-archive' > /dev/null; then _LT_TAGVAR(whole_archive_flag_spec, $1)=$wlarc'--whole-archive$convenience '$wlarc'--no-whole-archive' else _LT_TAGVAR(whole_archive_flag_spec, $1)= fi else with_gnu_ld=no wlarc= # A generic and very simple default shared library creation # command for GNU C++ for the case where it uses the native # linker, instead of GNU ld. If possible, this setting should # overridden to take advantage of the native linker features on # the platform it is being used on. _LT_TAGVAR(archive_cmds, $1)='$CC -shared -nostdlib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags -o $lib' fi # Commands to make compiler produce verbose output that lists # what "hidden" libraries, object files and flags are used when # linking a shared library. output_verbose_link_cmd='$CC -shared $CFLAGS -v conftest.$objext 2>&1 | $GREP -v "^Configured with:" | $GREP "\-L"' else GXX=no with_gnu_ld=no wlarc= fi # PORTME: fill in a description of your system's C++ link characteristics AC_MSG_CHECKING([whether the $compiler linker ($LD) supports shared libraries]) _LT_TAGVAR(ld_shlibs, $1)=yes case $host_os in aix3*) # FIXME: insert proper C++ library support _LT_TAGVAR(ld_shlibs, $1)=no ;; aix[[4-9]]*) if test ia64 = "$host_cpu"; then # On IA64, the linker does run time linking by default, so we don't # have to do anything special. aix_use_runtimelinking=no exp_sym_flag='-Bexport' no_entry_flag= else aix_use_runtimelinking=no # Test if we are trying to use run time linking or normal # AIX style linking. If -brtl is somewhere in LDFLAGS, we # have runtime linking enabled, and use it for executables. # For shared libraries, we enable/disable runtime linking # depending on the kind of the shared library created - # when "with_aix_soname,aix_use_runtimelinking" is: # "aix,no" lib.a(lib.so.V) shared, rtl:no, for executables # "aix,yes" lib.so shared, rtl:yes, for executables # lib.a static archive # "both,no" lib.so.V(shr.o) shared, rtl:yes # lib.a(lib.so.V) shared, rtl:no, for executables # "both,yes" lib.so.V(shr.o) shared, rtl:yes, for executables # lib.a(lib.so.V) shared, rtl:no # "svr4,*" lib.so.V(shr.o) shared, rtl:yes, for executables # lib.a static archive case $host_os in aix4.[[23]]|aix4.[[23]].*|aix[[5-9]]*) for ld_flag in $LDFLAGS; do case $ld_flag in *-brtl*) aix_use_runtimelinking=yes break ;; esac done if test svr4,no = "$with_aix_soname,$aix_use_runtimelinking"; then # With aix-soname=svr4, we create the lib.so.V shared archives only, # so we don't have lib.a shared libs to link our executables. # We have to force runtime linking in this case. aix_use_runtimelinking=yes LDFLAGS="$LDFLAGS -Wl,-brtl" fi ;; esac exp_sym_flag='-bexport' no_entry_flag='-bnoentry' fi # When large executables or shared objects are built, AIX ld can # have problems creating the table of contents. If linking a library # or program results in "error TOC overflow" add -mminimal-toc to # CXXFLAGS/CFLAGS for g++/gcc. In the cases where that is not # enough to fix the problem, add -Wl,-bbigtoc to LDFLAGS. _LT_TAGVAR(archive_cmds, $1)='' _LT_TAGVAR(hardcode_direct, $1)=yes _LT_TAGVAR(hardcode_direct_absolute, $1)=yes _LT_TAGVAR(hardcode_libdir_separator, $1)=':' _LT_TAGVAR(link_all_deplibs, $1)=yes _LT_TAGVAR(file_list_spec, $1)='$wl-f,' case $with_aix_soname,$aix_use_runtimelinking in aix,*) ;; # no import file svr4,* | *,yes) # use import file # The Import File defines what to hardcode. _LT_TAGVAR(hardcode_direct, $1)=no _LT_TAGVAR(hardcode_direct_absolute, $1)=no ;; esac if test yes = "$GXX"; then case $host_os in aix4.[[012]]|aix4.[[012]].*) # We only want to do this on AIX 4.2 and lower, the check # below for broken collect2 doesn't work under 4.3+ collect2name=`$CC -print-prog-name=collect2` if test -f "$collect2name" && strings "$collect2name" | $GREP resolve_lib_name >/dev/null then # We have reworked collect2 : else # We have old collect2 _LT_TAGVAR(hardcode_direct, $1)=unsupported # It fails to find uninstalled libraries when the uninstalled # path is not listed in the libpath. Setting hardcode_minus_L # to unsupported forces relinking _LT_TAGVAR(hardcode_minus_L, $1)=yes _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-L$libdir' _LT_TAGVAR(hardcode_libdir_separator, $1)= fi esac shared_flag='-shared' if test yes = "$aix_use_runtimelinking"; then shared_flag=$shared_flag' $wl-G' fi # Need to ensure runtime linking is disabled for the traditional # shared library, or the linker may eventually find shared libraries # /with/ Import File - we do not want to mix them. shared_flag_aix='-shared' shared_flag_svr4='-shared $wl-G' else # not using gcc if test ia64 = "$host_cpu"; then # VisualAge C++, Version 5.5 for AIX 5L for IA-64, Beta 3 Release # chokes on -Wl,-G. The following line is correct: shared_flag='-G' else if test yes = "$aix_use_runtimelinking"; then shared_flag='$wl-G' else shared_flag='$wl-bM:SRE' fi shared_flag_aix='$wl-bM:SRE' shared_flag_svr4='$wl-G' fi fi _LT_TAGVAR(export_dynamic_flag_spec, $1)='$wl-bexpall' # It seems that -bexpall does not export symbols beginning with # underscore (_), so it is better to generate a list of symbols to # export. _LT_TAGVAR(always_export_symbols, $1)=yes if test aix,yes = "$with_aix_soname,$aix_use_runtimelinking"; then # Warning - without using the other runtime loading flags (-brtl), # -berok will link without error, but may produce a broken library. # The "-G" linker flag allows undefined symbols. _LT_TAGVAR(no_undefined_flag, $1)='-bernotok' # Determine the default libpath from the value encoded in an empty # executable. _LT_SYS_MODULE_PATH_AIX([$1]) _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='$wl-blibpath:$libdir:'"$aix_libpath" _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -o $output_objdir/$soname $libobjs $deplibs $wl'$no_entry_flag' $compiler_flags `if test -n "$allow_undefined_flag"; then func_echo_all "$wl$allow_undefined_flag"; else :; fi` $wl'$exp_sym_flag:\$export_symbols' '$shared_flag else if test ia64 = "$host_cpu"; then _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='$wl-R $libdir:/usr/lib:/lib' _LT_TAGVAR(allow_undefined_flag, $1)="-z nodefs" _LT_TAGVAR(archive_expsym_cmds, $1)="\$CC $shared_flag"' -o $output_objdir/$soname $libobjs $deplibs '"\$wl$no_entry_flag"' $compiler_flags $wl$allow_undefined_flag '"\$wl$exp_sym_flag:\$export_symbols" else # Determine the default libpath from the value encoded in an # empty executable. _LT_SYS_MODULE_PATH_AIX([$1]) _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='$wl-blibpath:$libdir:'"$aix_libpath" # Warning - without using the other run time loading flags, # -berok will link without error, but may produce a broken library. _LT_TAGVAR(no_undefined_flag, $1)=' $wl-bernotok' _LT_TAGVAR(allow_undefined_flag, $1)=' $wl-berok' if test yes = "$with_gnu_ld"; then # We only use this code for GNU lds that support --whole-archive. _LT_TAGVAR(whole_archive_flag_spec, $1)='$wl--whole-archive$convenience $wl--no-whole-archive' else # Exported symbols can be pulled into shared objects from archives _LT_TAGVAR(whole_archive_flag_spec, $1)='$convenience' fi _LT_TAGVAR(archive_cmds_need_lc, $1)=yes _LT_TAGVAR(archive_expsym_cmds, $1)='$RM -r $output_objdir/$realname.d~$MKDIR $output_objdir/$realname.d' # -brtl affects multiple linker settings, -berok does not and is overridden later compiler_flags_filtered='`func_echo_all "$compiler_flags " | $SED -e "s%-brtl\\([[, ]]\\)%-berok\\1%g"`' if test svr4 != "$with_aix_soname"; then # This is similar to how AIX traditionally builds its shared # libraries. Need -bnortl late, we may have -brtl in LDFLAGS. _LT_TAGVAR(archive_expsym_cmds, $1)="$_LT_TAGVAR(archive_expsym_cmds, $1)"'~$CC '$shared_flag_aix' -o $output_objdir/$realname.d/$soname $libobjs $deplibs $wl-bnoentry '$compiler_flags_filtered'$wl-bE:$export_symbols$allow_undefined_flag~$AR $AR_FLAGS $output_objdir/$libname$release.a $output_objdir/$realname.d/$soname' fi if test aix != "$with_aix_soname"; then _LT_TAGVAR(archive_expsym_cmds, $1)="$_LT_TAGVAR(archive_expsym_cmds, $1)"'~$CC '$shared_flag_svr4' -o $output_objdir/$realname.d/$shared_archive_member_spec.o $libobjs $deplibs $wl-bnoentry '$compiler_flags_filtered'$wl-bE:$export_symbols$allow_undefined_flag~$STRIP -e $output_objdir/$realname.d/$shared_archive_member_spec.o~( func_echo_all "#! $soname($shared_archive_member_spec.o)"; if test shr_64 = "$shared_archive_member_spec"; then func_echo_all "# 64"; else func_echo_all "# 32"; fi; cat $export_symbols ) > $output_objdir/$realname.d/$shared_archive_member_spec.imp~$AR $AR_FLAGS $output_objdir/$soname $output_objdir/$realname.d/$shared_archive_member_spec.o $output_objdir/$realname.d/$shared_archive_member_spec.imp' else # used by -dlpreopen to get the symbols _LT_TAGVAR(archive_expsym_cmds, $1)="$_LT_TAGVAR(archive_expsym_cmds, $1)"'~$MV $output_objdir/$realname.d/$soname $output_objdir' fi _LT_TAGVAR(archive_expsym_cmds, $1)="$_LT_TAGVAR(archive_expsym_cmds, $1)"'~$RM -r $output_objdir/$realname.d' fi fi ;; beos*) if $LD --help 2>&1 | $GREP ': supported targets:.* elf' > /dev/null; then _LT_TAGVAR(allow_undefined_flag, $1)=unsupported # Joseph Beckenbach says some releases of gcc # support --undefined. This deserves some investigation. FIXME _LT_TAGVAR(archive_cmds, $1)='$CC -nostart $libobjs $deplibs $compiler_flags $wl-soname $wl$soname -o $lib' else _LT_TAGVAR(ld_shlibs, $1)=no fi ;; chorus*) case $cc_basename in *) # FIXME: insert proper C++ library support _LT_TAGVAR(ld_shlibs, $1)=no ;; esac ;; cygwin* | mingw* | pw32* | cegcc*) case $GXX,$cc_basename in ,cl* | no,cl*) # Native MSVC # hardcode_libdir_flag_spec is actually meaningless, as there is # no search path for DLLs. _LT_TAGVAR(hardcode_libdir_flag_spec, $1)=' ' _LT_TAGVAR(allow_undefined_flag, $1)=unsupported _LT_TAGVAR(always_export_symbols, $1)=yes _LT_TAGVAR(file_list_spec, $1)='@' # Tell ltmain to make .lib files, not .a files. libext=lib # Tell ltmain to make .dll files, not .so files. shrext_cmds=.dll # FIXME: Setting linknames here is a bad hack. _LT_TAGVAR(archive_cmds, $1)='$CC -o $output_objdir/$soname $libobjs $compiler_flags $deplibs -Wl,-DLL,-IMPLIB:"$tool_output_objdir$libname.dll.lib"~linknames=' _LT_TAGVAR(archive_expsym_cmds, $1)='if _LT_DLL_DEF_P([$export_symbols]); then cp "$export_symbols" "$output_objdir/$soname.def"; echo "$tool_output_objdir$soname.def" > "$output_objdir/$soname.exp"; else $SED -e '\''s/^/-link -EXPORT:/'\'' < $export_symbols > $output_objdir/$soname.exp; fi~ $CC -o $tool_output_objdir$soname $libobjs $compiler_flags $deplibs "@$tool_output_objdir$soname.exp" -Wl,-DLL,-IMPLIB:"$tool_output_objdir$libname.dll.lib"~ linknames=' # The linker will not automatically build a static lib if we build a DLL. # _LT_TAGVAR(old_archive_from_new_cmds, $1)='true' _LT_TAGVAR(enable_shared_with_static_runtimes, $1)=yes # Don't use ranlib _LT_TAGVAR(old_postinstall_cmds, $1)='chmod 644 $oldlib' _LT_TAGVAR(postlink_cmds, $1)='lt_outputfile="@OUTPUT@"~ lt_tool_outputfile="@TOOL_OUTPUT@"~ case $lt_outputfile in *.exe|*.EXE) ;; *) lt_outputfile=$lt_outputfile.exe lt_tool_outputfile=$lt_tool_outputfile.exe ;; esac~ func_to_tool_file "$lt_outputfile"~ if test : != "$MANIFEST_TOOL" && test -f "$lt_outputfile.manifest"; then $MANIFEST_TOOL -manifest "$lt_tool_outputfile.manifest" -outputresource:"$lt_tool_outputfile" || exit 1; $RM "$lt_outputfile.manifest"; fi' ;; *) # g++ # _LT_TAGVAR(hardcode_libdir_flag_spec, $1) is actually meaningless, # as there is no search path for DLLs. _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-L$libdir' _LT_TAGVAR(export_dynamic_flag_spec, $1)='$wl--export-all-symbols' _LT_TAGVAR(allow_undefined_flag, $1)=unsupported _LT_TAGVAR(always_export_symbols, $1)=no _LT_TAGVAR(enable_shared_with_static_runtimes, $1)=yes if $LD --help 2>&1 | $GREP 'auto-import' > /dev/null; then _LT_TAGVAR(archive_cmds, $1)='$CC -shared -nostdlib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags -o $output_objdir/$soname $wl--enable-auto-image-base -Xlinker --out-implib -Xlinker $lib' # If the export-symbols file already is a .def file, use it as # is; otherwise, prepend EXPORTS... _LT_TAGVAR(archive_expsym_cmds, $1)='if _LT_DLL_DEF_P([$export_symbols]); then cp $export_symbols $output_objdir/$soname.def; else echo EXPORTS > $output_objdir/$soname.def; cat $export_symbols >> $output_objdir/$soname.def; fi~ $CC -shared -nostdlib $output_objdir/$soname.def $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags -o $output_objdir/$soname $wl--enable-auto-image-base -Xlinker --out-implib -Xlinker $lib' else _LT_TAGVAR(ld_shlibs, $1)=no fi ;; esac ;; darwin* | rhapsody*) _LT_DARWIN_LINKER_FEATURES($1) ;; os2*) _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-L$libdir' _LT_TAGVAR(hardcode_minus_L, $1)=yes _LT_TAGVAR(allow_undefined_flag, $1)=unsupported shrext_cmds=.dll _LT_TAGVAR(archive_cmds, $1)='$ECHO "LIBRARY ${soname%$shared_ext} INITINSTANCE TERMINSTANCE" > $output_objdir/$libname.def~ $ECHO "DESCRIPTION \"$libname\"" >> $output_objdir/$libname.def~ $ECHO "DATA MULTIPLE NONSHARED" >> $output_objdir/$libname.def~ $ECHO EXPORTS >> $output_objdir/$libname.def~ emxexp $libobjs | $SED /"_DLL_InitTerm"/d >> $output_objdir/$libname.def~ $CC -Zdll -Zcrtdll -o $output_objdir/$soname $libobjs $deplibs $compiler_flags $output_objdir/$libname.def~ emximp -o $lib $output_objdir/$libname.def' _LT_TAGVAR(archive_expsym_cmds, $1)='$ECHO "LIBRARY ${soname%$shared_ext} INITINSTANCE TERMINSTANCE" > $output_objdir/$libname.def~ $ECHO "DESCRIPTION \"$libname\"" >> $output_objdir/$libname.def~ $ECHO "DATA MULTIPLE NONSHARED" >> $output_objdir/$libname.def~ $ECHO EXPORTS >> $output_objdir/$libname.def~ prefix_cmds="$SED"~ if test EXPORTS = "`$SED 1q $export_symbols`"; then prefix_cmds="$prefix_cmds -e 1d"; fi~ prefix_cmds="$prefix_cmds -e \"s/^\(.*\)$/_\1/g\""~ cat $export_symbols | $prefix_cmds >> $output_objdir/$libname.def~ $CC -Zdll -Zcrtdll -o $output_objdir/$soname $libobjs $deplibs $compiler_flags $output_objdir/$libname.def~ emximp -o $lib $output_objdir/$libname.def' _LT_TAGVAR(old_archive_From_new_cmds, $1)='emximp -o $output_objdir/${libname}_dll.a $output_objdir/$libname.def' _LT_TAGVAR(enable_shared_with_static_runtimes, $1)=yes ;; dgux*) case $cc_basename in ec++*) # FIXME: insert proper C++ library support _LT_TAGVAR(ld_shlibs, $1)=no ;; ghcx*) # Green Hills C++ Compiler # FIXME: insert proper C++ library support _LT_TAGVAR(ld_shlibs, $1)=no ;; *) # FIXME: insert proper C++ library support _LT_TAGVAR(ld_shlibs, $1)=no ;; esac ;; freebsd2.*) # C++ shared libraries reported to be fairly broken before # switch to ELF _LT_TAGVAR(ld_shlibs, $1)=no ;; freebsd-elf*) _LT_TAGVAR(archive_cmds_need_lc, $1)=no ;; freebsd* | dragonfly*) # FreeBSD 3 and later use GNU C++ and GNU ld with standard ELF # conventions _LT_TAGVAR(ld_shlibs, $1)=yes ;; haiku*) _LT_TAGVAR(archive_cmds, $1)='$CC -shared $libobjs $deplibs $compiler_flags $wl-soname $wl$soname -o $lib' _LT_TAGVAR(link_all_deplibs, $1)=yes ;; hpux9*) _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='$wl+b $wl$libdir' _LT_TAGVAR(hardcode_libdir_separator, $1)=: _LT_TAGVAR(export_dynamic_flag_spec, $1)='$wl-E' _LT_TAGVAR(hardcode_direct, $1)=yes _LT_TAGVAR(hardcode_minus_L, $1)=yes # Not in the search PATH, # but as the default # location of the library. case $cc_basename in CC*) # FIXME: insert proper C++ library support _LT_TAGVAR(ld_shlibs, $1)=no ;; aCC*) _LT_TAGVAR(archive_cmds, $1)='$RM $output_objdir/$soname~$CC -b $wl+b $wl$install_libdir -o $output_objdir/$soname $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags~test "x$output_objdir/$soname" = "x$lib" || mv $output_objdir/$soname $lib' # Commands to make compiler produce verbose output that lists # what "hidden" libraries, object files and flags are used when # linking a shared library. # # There doesn't appear to be a way to prevent this compiler from # explicitly linking system object files so we need to strip them # from the output so that they don't get included in the library # dependencies. output_verbose_link_cmd='templist=`($CC -b $CFLAGS -v conftest.$objext 2>&1) | $EGREP "\-L"`; list= ; for z in $templist; do case $z in conftest.$objext) list="$list $z";; *.$objext);; *) list="$list $z";;esac; done; func_echo_all "$list"' ;; *) if test yes = "$GXX"; then _LT_TAGVAR(archive_cmds, $1)='$RM $output_objdir/$soname~$CC -shared -nostdlib $pic_flag $wl+b $wl$install_libdir -o $output_objdir/$soname $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags~test "x$output_objdir/$soname" = "x$lib" || mv $output_objdir/$soname $lib' else # FIXME: insert proper C++ library support _LT_TAGVAR(ld_shlibs, $1)=no fi ;; esac ;; hpux10*|hpux11*) if test no = "$with_gnu_ld"; then _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='$wl+b $wl$libdir' _LT_TAGVAR(hardcode_libdir_separator, $1)=: case $host_cpu in hppa*64*|ia64*) ;; *) _LT_TAGVAR(export_dynamic_flag_spec, $1)='$wl-E' ;; esac fi case $host_cpu in hppa*64*|ia64*) _LT_TAGVAR(hardcode_direct, $1)=no _LT_TAGVAR(hardcode_shlibpath_var, $1)=no ;; *) _LT_TAGVAR(hardcode_direct, $1)=yes _LT_TAGVAR(hardcode_direct_absolute, $1)=yes _LT_TAGVAR(hardcode_minus_L, $1)=yes # Not in the search PATH, # but as the default # location of the library. ;; esac case $cc_basename in CC*) # FIXME: insert proper C++ library support _LT_TAGVAR(ld_shlibs, $1)=no ;; aCC*) case $host_cpu in hppa*64*) _LT_TAGVAR(archive_cmds, $1)='$CC -b $wl+h $wl$soname -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags' ;; ia64*) _LT_TAGVAR(archive_cmds, $1)='$CC -b $wl+h $wl$soname $wl+nodefaultrpath -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags' ;; *) _LT_TAGVAR(archive_cmds, $1)='$CC -b $wl+h $wl$soname $wl+b $wl$install_libdir -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags' ;; esac # Commands to make compiler produce verbose output that lists # what "hidden" libraries, object files and flags are used when # linking a shared library. # # There doesn't appear to be a way to prevent this compiler from # explicitly linking system object files so we need to strip them # from the output so that they don't get included in the library # dependencies. output_verbose_link_cmd='templist=`($CC -b $CFLAGS -v conftest.$objext 2>&1) | $GREP "\-L"`; list= ; for z in $templist; do case $z in conftest.$objext) list="$list $z";; *.$objext);; *) list="$list $z";;esac; done; func_echo_all "$list"' ;; *) if test yes = "$GXX"; then if test no = "$with_gnu_ld"; then case $host_cpu in hppa*64*) _LT_TAGVAR(archive_cmds, $1)='$CC -shared -nostdlib -fPIC $wl+h $wl$soname -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags' ;; ia64*) _LT_TAGVAR(archive_cmds, $1)='$CC -shared -nostdlib $pic_flag $wl+h $wl$soname $wl+nodefaultrpath -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags' ;; *) _LT_TAGVAR(archive_cmds, $1)='$CC -shared -nostdlib $pic_flag $wl+h $wl$soname $wl+b $wl$install_libdir -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags' ;; esac fi else # FIXME: insert proper C++ library support _LT_TAGVAR(ld_shlibs, $1)=no fi ;; esac ;; interix[[3-9]]*) _LT_TAGVAR(hardcode_direct, $1)=no _LT_TAGVAR(hardcode_shlibpath_var, $1)=no _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='$wl-rpath,$libdir' _LT_TAGVAR(export_dynamic_flag_spec, $1)='$wl-E' # Hack: On Interix 3.x, we cannot compile PIC because of a broken gcc. # Instead, shared libraries are loaded at an image base (0x10000000 by # default) and relocated if they conflict, which is a slow very memory # consuming and fragmenting process. To avoid this, we pick a random, # 256 KiB-aligned image base between 0x50000000 and 0x6FFC0000 at link # time. Moving up from 0x10000000 also allows more sbrk(2) space. _LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag $libobjs $deplibs $compiler_flags $wl-h,$soname $wl--image-base,`expr ${RANDOM-$$} % 4096 / 2 \* 262144 + 1342177280` -o $lib' _LT_TAGVAR(archive_expsym_cmds, $1)='sed "s|^|_|" $export_symbols >$output_objdir/$soname.expsym~$CC -shared $pic_flag $libobjs $deplibs $compiler_flags $wl-h,$soname $wl--retain-symbols-file,$output_objdir/$soname.expsym $wl--image-base,`expr ${RANDOM-$$} % 4096 / 2 \* 262144 + 1342177280` -o $lib' ;; irix5* | irix6*) case $cc_basename in CC*) # SGI C++ _LT_TAGVAR(archive_cmds, $1)='$CC -shared -all -multigot $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags -soname $soname `test -n "$verstring" && func_echo_all "-set_version $verstring"` -update_registry $output_objdir/so_locations -o $lib' # Archives containing C++ object files must be created using # "CC -ar", where "CC" is the IRIX C++ compiler. This is # necessary to make sure instantiated templates are included # in the archive. _LT_TAGVAR(old_archive_cmds, $1)='$CC -ar -WR,-u -o $oldlib $oldobjs' ;; *) if test yes = "$GXX"; then if test no = "$with_gnu_ld"; then _LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag -nostdlib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags $wl-soname $wl$soname `test -n "$verstring" && func_echo_all "$wl-set_version $wl$verstring"` $wl-update_registry $wl$output_objdir/so_locations -o $lib' else _LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag -nostdlib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags $wl-soname $wl$soname `test -n "$verstring" && func_echo_all "$wl-set_version $wl$verstring"` -o $lib' fi fi _LT_TAGVAR(link_all_deplibs, $1)=yes ;; esac _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='$wl-rpath $wl$libdir' _LT_TAGVAR(hardcode_libdir_separator, $1)=: _LT_TAGVAR(inherit_rpath, $1)=yes ;; linux* | k*bsd*-gnu | kopensolaris*-gnu | gnu*) case $cc_basename in KCC*) # Kuck and Associates, Inc. (KAI) C++ Compiler # KCC will only create a shared library if the output file # ends with ".so" (or ".sl" for HP-UX), so rename the library # to its proper name (with version) after linking. _LT_TAGVAR(archive_cmds, $1)='tempext=`echo $shared_ext | $SED -e '\''s/\([[^()0-9A-Za-z{}]]\)/\\\\\1/g'\''`; templib=`echo $lib | $SED -e "s/\$tempext\..*/.so/"`; $CC $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags --soname $soname -o \$templib; mv \$templib $lib' _LT_TAGVAR(archive_expsym_cmds, $1)='tempext=`echo $shared_ext | $SED -e '\''s/\([[^()0-9A-Za-z{}]]\)/\\\\\1/g'\''`; templib=`echo $lib | $SED -e "s/\$tempext\..*/.so/"`; $CC $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags --soname $soname -o \$templib $wl-retain-symbols-file,$export_symbols; mv \$templib $lib' # Commands to make compiler produce verbose output that lists # what "hidden" libraries, object files and flags are used when # linking a shared library. # # There doesn't appear to be a way to prevent this compiler from # explicitly linking system object files so we need to strip them # from the output so that they don't get included in the library # dependencies. output_verbose_link_cmd='templist=`$CC $CFLAGS -v conftest.$objext -o libconftest$shared_ext 2>&1 | $GREP "ld"`; rm -f libconftest$shared_ext; list= ; for z in $templist; do case $z in conftest.$objext) list="$list $z";; *.$objext);; *) list="$list $z";;esac; done; func_echo_all "$list"' _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='$wl-rpath,$libdir' _LT_TAGVAR(export_dynamic_flag_spec, $1)='$wl--export-dynamic' # Archives containing C++ object files must be created using # "CC -Bstatic", where "CC" is the KAI C++ compiler. _LT_TAGVAR(old_archive_cmds, $1)='$CC -Bstatic -o $oldlib $oldobjs' ;; icpc* | ecpc* ) # Intel C++ with_gnu_ld=yes # version 8.0 and above of icpc choke on multiply defined symbols # if we add $predep_objects and $postdep_objects, however 7.1 and # earlier do not add the objects themselves. case `$CC -V 2>&1` in *"Version 7."*) _LT_TAGVAR(archive_cmds, $1)='$CC -shared $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags $wl-soname $wl$soname -o $lib' _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags $wl-soname $wl$soname $wl-retain-symbols-file $wl$export_symbols -o $lib' ;; *) # Version 8.0 or newer tmp_idyn= case $host_cpu in ia64*) tmp_idyn=' -i_dynamic';; esac _LT_TAGVAR(archive_cmds, $1)='$CC -shared'"$tmp_idyn"' $libobjs $deplibs $compiler_flags $wl-soname $wl$soname -o $lib' _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared'"$tmp_idyn"' $libobjs $deplibs $compiler_flags $wl-soname $wl$soname $wl-retain-symbols-file $wl$export_symbols -o $lib' ;; esac _LT_TAGVAR(archive_cmds_need_lc, $1)=no _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='$wl-rpath,$libdir' _LT_TAGVAR(export_dynamic_flag_spec, $1)='$wl--export-dynamic' _LT_TAGVAR(whole_archive_flag_spec, $1)='$wl--whole-archive$convenience $wl--no-whole-archive' ;; pgCC* | pgcpp*) # Portland Group C++ compiler case `$CC -V` in *pgCC\ [[1-5]].* | *pgcpp\ [[1-5]].*) _LT_TAGVAR(prelink_cmds, $1)='tpldir=Template.dir~ rm -rf $tpldir~ $CC --prelink_objects --instantiation_dir $tpldir $objs $libobjs $compile_deplibs~ compile_command="$compile_command `find $tpldir -name \*.o | sort | $NL2SP`"' _LT_TAGVAR(old_archive_cmds, $1)='tpldir=Template.dir~ rm -rf $tpldir~ $CC --prelink_objects --instantiation_dir $tpldir $oldobjs$old_deplibs~ $AR $AR_FLAGS $oldlib$oldobjs$old_deplibs `find $tpldir -name \*.o | sort | $NL2SP`~ $RANLIB $oldlib' _LT_TAGVAR(archive_cmds, $1)='tpldir=Template.dir~ rm -rf $tpldir~ $CC --prelink_objects --instantiation_dir $tpldir $predep_objects $libobjs $deplibs $convenience $postdep_objects~ $CC -shared $pic_flag $predep_objects $libobjs $deplibs `find $tpldir -name \*.o | sort | $NL2SP` $postdep_objects $compiler_flags $wl-soname $wl$soname -o $lib' _LT_TAGVAR(archive_expsym_cmds, $1)='tpldir=Template.dir~ rm -rf $tpldir~ $CC --prelink_objects --instantiation_dir $tpldir $predep_objects $libobjs $deplibs $convenience $postdep_objects~ $CC -shared $pic_flag $predep_objects $libobjs $deplibs `find $tpldir -name \*.o | sort | $NL2SP` $postdep_objects $compiler_flags $wl-soname $wl$soname $wl-retain-symbols-file $wl$export_symbols -o $lib' ;; *) # Version 6 and above use weak symbols _LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags $wl-soname $wl$soname -o $lib' _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared $pic_flag $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags $wl-soname $wl$soname $wl-retain-symbols-file $wl$export_symbols -o $lib' ;; esac _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='$wl--rpath $wl$libdir' _LT_TAGVAR(export_dynamic_flag_spec, $1)='$wl--export-dynamic' _LT_TAGVAR(whole_archive_flag_spec, $1)='$wl--whole-archive`for conv in $convenience\"\"; do test -n \"$conv\" && new_convenience=\"$new_convenience,$conv\"; done; func_echo_all \"$new_convenience\"` $wl--no-whole-archive' ;; cxx*) # Compaq C++ _LT_TAGVAR(archive_cmds, $1)='$CC -shared $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags $wl-soname $wl$soname -o $lib' _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags $wl-soname $wl$soname -o $lib $wl-retain-symbols-file $wl$export_symbols' runpath_var=LD_RUN_PATH _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-rpath $libdir' _LT_TAGVAR(hardcode_libdir_separator, $1)=: # Commands to make compiler produce verbose output that lists # what "hidden" libraries, object files and flags are used when # linking a shared library. # # There doesn't appear to be a way to prevent this compiler from # explicitly linking system object files so we need to strip them # from the output so that they don't get included in the library # dependencies. output_verbose_link_cmd='templist=`$CC -shared $CFLAGS -v conftest.$objext 2>&1 | $GREP "ld"`; templist=`func_echo_all "$templist" | $SED "s/\(^.*ld.*\)\( .*ld .*$\)/\1/"`; list= ; for z in $templist; do case $z in conftest.$objext) list="$list $z";; *.$objext);; *) list="$list $z";;esac; done; func_echo_all "X$list" | $Xsed' ;; xl* | mpixl* | bgxl*) # IBM XL 8.0 on PPC, with GNU ld _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='$wl-rpath $wl$libdir' _LT_TAGVAR(export_dynamic_flag_spec, $1)='$wl--export-dynamic' _LT_TAGVAR(archive_cmds, $1)='$CC -qmkshrobj $libobjs $deplibs $compiler_flags $wl-soname $wl$soname -o $lib' if test yes = "$supports_anon_versioning"; then _LT_TAGVAR(archive_expsym_cmds, $1)='echo "{ global:" > $output_objdir/$libname.ver~ cat $export_symbols | sed -e "s/\(.*\)/\1;/" >> $output_objdir/$libname.ver~ echo "local: *; };" >> $output_objdir/$libname.ver~ $CC -qmkshrobj $libobjs $deplibs $compiler_flags $wl-soname $wl$soname $wl-version-script $wl$output_objdir/$libname.ver -o $lib' fi ;; *) case `$CC -V 2>&1 | sed 5q` in *Sun\ C*) # Sun C++ 5.9 _LT_TAGVAR(no_undefined_flag, $1)=' -zdefs' _LT_TAGVAR(archive_cmds, $1)='$CC -G$allow_undefined_flag -h$soname -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags' _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -G$allow_undefined_flag -h$soname -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags $wl-retain-symbols-file $wl$export_symbols' _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-R$libdir' _LT_TAGVAR(whole_archive_flag_spec, $1)='$wl--whole-archive`new_convenience=; for conv in $convenience\"\"; do test -z \"$conv\" || new_convenience=\"$new_convenience,$conv\"; done; func_echo_all \"$new_convenience\"` $wl--no-whole-archive' _LT_TAGVAR(compiler_needs_object, $1)=yes # Not sure whether something based on # $CC $CFLAGS -v conftest.$objext -o libconftest$shared_ext 2>&1 # would be better. output_verbose_link_cmd='func_echo_all' # Archives containing C++ object files must be created using # "CC -xar", where "CC" is the Sun C++ compiler. This is # necessary to make sure instantiated templates are included # in the archive. _LT_TAGVAR(old_archive_cmds, $1)='$CC -xar -o $oldlib $oldobjs' ;; esac ;; esac ;; lynxos*) # FIXME: insert proper C++ library support _LT_TAGVAR(ld_shlibs, $1)=no ;; m88k*) # FIXME: insert proper C++ library support _LT_TAGVAR(ld_shlibs, $1)=no ;; mvs*) case $cc_basename in cxx*) # FIXME: insert proper C++ library support _LT_TAGVAR(ld_shlibs, $1)=no ;; *) # FIXME: insert proper C++ library support _LT_TAGVAR(ld_shlibs, $1)=no ;; esac ;; netbsd*) if echo __ELF__ | $CC -E - | $GREP __ELF__ >/dev/null; then _LT_TAGVAR(archive_cmds, $1)='$LD -Bshareable -o $lib $predep_objects $libobjs $deplibs $postdep_objects $linker_flags' wlarc= _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-R$libdir' _LT_TAGVAR(hardcode_direct, $1)=yes _LT_TAGVAR(hardcode_shlibpath_var, $1)=no fi # Workaround some broken pre-1.5 toolchains output_verbose_link_cmd='$CC -shared $CFLAGS -v conftest.$objext 2>&1 | $GREP conftest.$objext | $SED -e "s:-lgcc -lc -lgcc::"' ;; *nto* | *qnx*) _LT_TAGVAR(ld_shlibs, $1)=yes ;; openbsd* | bitrig*) if test -f /usr/libexec/ld.so; then _LT_TAGVAR(hardcode_direct, $1)=yes _LT_TAGVAR(hardcode_shlibpath_var, $1)=no _LT_TAGVAR(hardcode_direct_absolute, $1)=yes _LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags -o $lib' _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='$wl-rpath,$libdir' if test -z "`echo __ELF__ | $CC -E - | grep __ELF__`"; then _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared $pic_flag $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags $wl-retain-symbols-file,$export_symbols -o $lib' _LT_TAGVAR(export_dynamic_flag_spec, $1)='$wl-E' _LT_TAGVAR(whole_archive_flag_spec, $1)=$wlarc'--whole-archive$convenience '$wlarc'--no-whole-archive' fi output_verbose_link_cmd=func_echo_all else _LT_TAGVAR(ld_shlibs, $1)=no fi ;; osf3* | osf4* | osf5*) case $cc_basename in KCC*) # Kuck and Associates, Inc. (KAI) C++ Compiler # KCC will only create a shared library if the output file # ends with ".so" (or ".sl" for HP-UX), so rename the library # to its proper name (with version) after linking. _LT_TAGVAR(archive_cmds, $1)='tempext=`echo $shared_ext | $SED -e '\''s/\([[^()0-9A-Za-z{}]]\)/\\\\\1/g'\''`; templib=`echo "$lib" | $SED -e "s/\$tempext\..*/.so/"`; $CC $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags --soname $soname -o \$templib; mv \$templib $lib' _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='$wl-rpath,$libdir' _LT_TAGVAR(hardcode_libdir_separator, $1)=: # Archives containing C++ object files must be created using # the KAI C++ compiler. case $host in osf3*) _LT_TAGVAR(old_archive_cmds, $1)='$CC -Bstatic -o $oldlib $oldobjs' ;; *) _LT_TAGVAR(old_archive_cmds, $1)='$CC -o $oldlib $oldobjs' ;; esac ;; RCC*) # Rational C++ 2.4.1 # FIXME: insert proper C++ library support _LT_TAGVAR(ld_shlibs, $1)=no ;; cxx*) case $host in osf3*) _LT_TAGVAR(allow_undefined_flag, $1)=' $wl-expect_unresolved $wl\*' _LT_TAGVAR(archive_cmds, $1)='$CC -shared$allow_undefined_flag $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags $wl-soname $soname `test -n "$verstring" && func_echo_all "$wl-set_version $verstring"` -update_registry $output_objdir/so_locations -o $lib' _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='$wl-rpath $wl$libdir' ;; *) _LT_TAGVAR(allow_undefined_flag, $1)=' -expect_unresolved \*' _LT_TAGVAR(archive_cmds, $1)='$CC -shared$allow_undefined_flag $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags -msym -soname $soname `test -n "$verstring" && func_echo_all "-set_version $verstring"` -update_registry $output_objdir/so_locations -o $lib' _LT_TAGVAR(archive_expsym_cmds, $1)='for i in `cat $export_symbols`; do printf "%s %s\\n" -exported_symbol "\$i" >> $lib.exp; done~ echo "-hidden">> $lib.exp~ $CC -shared$allow_undefined_flag $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags -msym -soname $soname $wl-input $wl$lib.exp `test -n "$verstring" && $ECHO "-set_version $verstring"` -update_registry $output_objdir/so_locations -o $lib~ $RM $lib.exp' _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-rpath $libdir' ;; esac _LT_TAGVAR(hardcode_libdir_separator, $1)=: # Commands to make compiler produce verbose output that lists # what "hidden" libraries, object files and flags are used when # linking a shared library. # # There doesn't appear to be a way to prevent this compiler from # explicitly linking system object files so we need to strip them # from the output so that they don't get included in the library # dependencies. output_verbose_link_cmd='templist=`$CC -shared $CFLAGS -v conftest.$objext 2>&1 | $GREP "ld" | $GREP -v "ld:"`; templist=`func_echo_all "$templist" | $SED "s/\(^.*ld.*\)\( .*ld.*$\)/\1/"`; list= ; for z in $templist; do case $z in conftest.$objext) list="$list $z";; *.$objext);; *) list="$list $z";;esac; done; func_echo_all "$list"' ;; *) if test yes,no = "$GXX,$with_gnu_ld"; then _LT_TAGVAR(allow_undefined_flag, $1)=' $wl-expect_unresolved $wl\*' case $host in osf3*) _LT_TAGVAR(archive_cmds, $1)='$CC -shared -nostdlib $allow_undefined_flag $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags $wl-soname $wl$soname `test -n "$verstring" && func_echo_all "$wl-set_version $wl$verstring"` $wl-update_registry $wl$output_objdir/so_locations -o $lib' ;; *) _LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag -nostdlib $allow_undefined_flag $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags $wl-msym $wl-soname $wl$soname `test -n "$verstring" && func_echo_all "$wl-set_version $wl$verstring"` $wl-update_registry $wl$output_objdir/so_locations -o $lib' ;; esac _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='$wl-rpath $wl$libdir' _LT_TAGVAR(hardcode_libdir_separator, $1)=: # Commands to make compiler produce verbose output that lists # what "hidden" libraries, object files and flags are used when # linking a shared library. output_verbose_link_cmd='$CC -shared $CFLAGS -v conftest.$objext 2>&1 | $GREP -v "^Configured with:" | $GREP "\-L"' else # FIXME: insert proper C++ library support _LT_TAGVAR(ld_shlibs, $1)=no fi ;; esac ;; psos*) # FIXME: insert proper C++ library support _LT_TAGVAR(ld_shlibs, $1)=no ;; sunos4*) case $cc_basename in CC*) # Sun C++ 4.x # FIXME: insert proper C++ library support _LT_TAGVAR(ld_shlibs, $1)=no ;; lcc*) # Lucid # FIXME: insert proper C++ library support _LT_TAGVAR(ld_shlibs, $1)=no ;; *) # FIXME: insert proper C++ library support _LT_TAGVAR(ld_shlibs, $1)=no ;; esac ;; solaris*) case $cc_basename in CC* | sunCC*) # Sun C++ 4.2, 5.x and Centerline C++ _LT_TAGVAR(archive_cmds_need_lc,$1)=yes _LT_TAGVAR(no_undefined_flag, $1)=' -zdefs' _LT_TAGVAR(archive_cmds, $1)='$CC -G$allow_undefined_flag -h$soname -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags' _LT_TAGVAR(archive_expsym_cmds, $1)='echo "{ global:" > $lib.exp~cat $export_symbols | $SED -e "s/\(.*\)/\1;/" >> $lib.exp~echo "local: *; };" >> $lib.exp~ $CC -G$allow_undefined_flag $wl-M $wl$lib.exp -h$soname -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags~$RM $lib.exp' _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-R$libdir' _LT_TAGVAR(hardcode_shlibpath_var, $1)=no case $host_os in solaris2.[[0-5]] | solaris2.[[0-5]].*) ;; *) # The compiler driver will combine and reorder linker options, # but understands '-z linker_flag'. # Supported since Solaris 2.6 (maybe 2.5.1?) _LT_TAGVAR(whole_archive_flag_spec, $1)='-z allextract$convenience -z defaultextract' ;; esac _LT_TAGVAR(link_all_deplibs, $1)=yes output_verbose_link_cmd='func_echo_all' # Archives containing C++ object files must be created using # "CC -xar", where "CC" is the Sun C++ compiler. This is # necessary to make sure instantiated templates are included # in the archive. _LT_TAGVAR(old_archive_cmds, $1)='$CC -xar -o $oldlib $oldobjs' ;; gcx*) # Green Hills C++ Compiler _LT_TAGVAR(archive_cmds, $1)='$CC -shared $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags $wl-h $wl$soname -o $lib' # The C++ compiler must be used to create the archive. _LT_TAGVAR(old_archive_cmds, $1)='$CC $LDFLAGS -archive -o $oldlib $oldobjs' ;; *) # GNU C++ compiler with Solaris linker if test yes,no = "$GXX,$with_gnu_ld"; then _LT_TAGVAR(no_undefined_flag, $1)=' $wl-z ${wl}defs' if $CC --version | $GREP -v '^2\.7' > /dev/null; then _LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag -nostdlib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags $wl-h $wl$soname -o $lib' _LT_TAGVAR(archive_expsym_cmds, $1)='echo "{ global:" > $lib.exp~cat $export_symbols | $SED -e "s/\(.*\)/\1;/" >> $lib.exp~echo "local: *; };" >> $lib.exp~ $CC -shared $pic_flag -nostdlib $wl-M $wl$lib.exp $wl-h $wl$soname -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags~$RM $lib.exp' # Commands to make compiler produce verbose output that lists # what "hidden" libraries, object files and flags are used when # linking a shared library. output_verbose_link_cmd='$CC -shared $CFLAGS -v conftest.$objext 2>&1 | $GREP -v "^Configured with:" | $GREP "\-L"' else # g++ 2.7 appears to require '-G' NOT '-shared' on this # platform. _LT_TAGVAR(archive_cmds, $1)='$CC -G -nostdlib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags $wl-h $wl$soname -o $lib' _LT_TAGVAR(archive_expsym_cmds, $1)='echo "{ global:" > $lib.exp~cat $export_symbols | $SED -e "s/\(.*\)/\1;/" >> $lib.exp~echo "local: *; };" >> $lib.exp~ $CC -G -nostdlib $wl-M $wl$lib.exp $wl-h $wl$soname -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags~$RM $lib.exp' # Commands to make compiler produce verbose output that lists # what "hidden" libraries, object files and flags are used when # linking a shared library. output_verbose_link_cmd='$CC -G $CFLAGS -v conftest.$objext 2>&1 | $GREP -v "^Configured with:" | $GREP "\-L"' fi _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='$wl-R $wl$libdir' case $host_os in solaris2.[[0-5]] | solaris2.[[0-5]].*) ;; *) _LT_TAGVAR(whole_archive_flag_spec, $1)='$wl-z ${wl}allextract$convenience $wl-z ${wl}defaultextract' ;; esac fi ;; esac ;; sysv4*uw2* | sysv5OpenUNIX* | sysv5UnixWare7.[[01]].[[10]]* | unixware7* | sco3.2v5.0.[[024]]*) _LT_TAGVAR(no_undefined_flag, $1)='$wl-z,text' _LT_TAGVAR(archive_cmds_need_lc, $1)=no _LT_TAGVAR(hardcode_shlibpath_var, $1)=no runpath_var='LD_RUN_PATH' case $cc_basename in CC*) _LT_TAGVAR(archive_cmds, $1)='$CC -G $wl-h,$soname -o $lib $libobjs $deplibs $compiler_flags' _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -G $wl-Bexport:$export_symbols $wl-h,$soname -o $lib $libobjs $deplibs $compiler_flags' ;; *) _LT_TAGVAR(archive_cmds, $1)='$CC -shared $wl-h,$soname -o $lib $libobjs $deplibs $compiler_flags' _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared $wl-Bexport:$export_symbols $wl-h,$soname -o $lib $libobjs $deplibs $compiler_flags' ;; esac ;; sysv5* | sco3.2v5* | sco5v6*) # Note: We CANNOT use -z defs as we might desire, because we do not # link with -lc, and that would cause any symbols used from libc to # always be unresolved, which means just about no library would # ever link correctly. If we're not using GNU ld we use -z text # though, which does catch some bad symbols but isn't as heavy-handed # as -z defs. _LT_TAGVAR(no_undefined_flag, $1)='$wl-z,text' _LT_TAGVAR(allow_undefined_flag, $1)='$wl-z,nodefs' _LT_TAGVAR(archive_cmds_need_lc, $1)=no _LT_TAGVAR(hardcode_shlibpath_var, $1)=no _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='$wl-R,$libdir' _LT_TAGVAR(hardcode_libdir_separator, $1)=':' _LT_TAGVAR(link_all_deplibs, $1)=yes _LT_TAGVAR(export_dynamic_flag_spec, $1)='$wl-Bexport' runpath_var='LD_RUN_PATH' case $cc_basename in CC*) _LT_TAGVAR(archive_cmds, $1)='$CC -G $wl-h,$soname -o $lib $libobjs $deplibs $compiler_flags' _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -G $wl-Bexport:$export_symbols $wl-h,$soname -o $lib $libobjs $deplibs $compiler_flags' _LT_TAGVAR(old_archive_cmds, $1)='$CC -Tprelink_objects $oldobjs~ '"$_LT_TAGVAR(old_archive_cmds, $1)" _LT_TAGVAR(reload_cmds, $1)='$CC -Tprelink_objects $reload_objs~ '"$_LT_TAGVAR(reload_cmds, $1)" ;; *) _LT_TAGVAR(archive_cmds, $1)='$CC -shared $wl-h,$soname -o $lib $libobjs $deplibs $compiler_flags' _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared $wl-Bexport:$export_symbols $wl-h,$soname -o $lib $libobjs $deplibs $compiler_flags' ;; esac ;; tandem*) case $cc_basename in NCC*) # NonStop-UX NCC 3.20 # FIXME: insert proper C++ library support _LT_TAGVAR(ld_shlibs, $1)=no ;; *) # FIXME: insert proper C++ library support _LT_TAGVAR(ld_shlibs, $1)=no ;; esac ;; vxworks*) # FIXME: insert proper C++ library support _LT_TAGVAR(ld_shlibs, $1)=no ;; *) # FIXME: insert proper C++ library support _LT_TAGVAR(ld_shlibs, $1)=no ;; esac AC_MSG_RESULT([$_LT_TAGVAR(ld_shlibs, $1)]) test no = "$_LT_TAGVAR(ld_shlibs, $1)" && can_build_shared=no _LT_TAGVAR(GCC, $1)=$GXX _LT_TAGVAR(LD, $1)=$LD ## CAVEAT EMPTOR: ## There is no encapsulation within the following macros, do not change ## the running order or otherwise move them around unless you know exactly ## what you are doing... _LT_SYS_HIDDEN_LIBDEPS($1) _LT_COMPILER_PIC($1) _LT_COMPILER_C_O($1) _LT_COMPILER_FILE_LOCKS($1) _LT_LINKER_SHLIBS($1) _LT_SYS_DYNAMIC_LINKER($1) _LT_LINKER_HARDCODE_LIBPATH($1) _LT_CONFIG($1) fi # test -n "$compiler" CC=$lt_save_CC CFLAGS=$lt_save_CFLAGS LDCXX=$LD LD=$lt_save_LD GCC=$lt_save_GCC with_gnu_ld=$lt_save_with_gnu_ld lt_cv_path_LDCXX=$lt_cv_path_LD lt_cv_path_LD=$lt_save_path_LD lt_cv_prog_gnu_ldcxx=$lt_cv_prog_gnu_ld lt_cv_prog_gnu_ld=$lt_save_with_gnu_ld fi # test yes != "$_lt_caught_CXX_error" AC_LANG_POP ])# _LT_LANG_CXX_CONFIG # _LT_FUNC_STRIPNAME_CNF # ---------------------- # func_stripname_cnf prefix suffix name # strip PREFIX and SUFFIX off of NAME. # PREFIX and SUFFIX must not contain globbing or regex special # characters, hashes, percent signs, but SUFFIX may contain a leading # dot (in which case that matches only a dot). # # This function is identical to the (non-XSI) version of func_stripname, # except this one can be used by m4 code that may be executed by configure, # rather than the libtool script. m4_defun([_LT_FUNC_STRIPNAME_CNF],[dnl AC_REQUIRE([_LT_DECL_SED]) AC_REQUIRE([_LT_PROG_ECHO_BACKSLASH]) func_stripname_cnf () { case @S|@2 in .*) func_stripname_result=`$ECHO "@S|@3" | $SED "s%^@S|@1%%; s%\\\\@S|@2\$%%"`;; *) func_stripname_result=`$ECHO "@S|@3" | $SED "s%^@S|@1%%; s%@S|@2\$%%"`;; esac } # func_stripname_cnf ])# _LT_FUNC_STRIPNAME_CNF # _LT_SYS_HIDDEN_LIBDEPS([TAGNAME]) # --------------------------------- # Figure out "hidden" library dependencies from verbose # compiler output when linking a shared library. # Parse the compiler output and extract the necessary # objects, libraries and library flags. m4_defun([_LT_SYS_HIDDEN_LIBDEPS], [m4_require([_LT_FILEUTILS_DEFAULTS])dnl AC_REQUIRE([_LT_FUNC_STRIPNAME_CNF])dnl # Dependencies to place before and after the object being linked: _LT_TAGVAR(predep_objects, $1)= _LT_TAGVAR(postdep_objects, $1)= _LT_TAGVAR(predeps, $1)= _LT_TAGVAR(postdeps, $1)= _LT_TAGVAR(compiler_lib_search_path, $1)= dnl we can't use the lt_simple_compile_test_code here, dnl because it contains code intended for an executable, dnl not a library. It's possible we should let each dnl tag define a new lt_????_link_test_code variable, dnl but it's only used here... m4_if([$1], [], [cat > conftest.$ac_ext <<_LT_EOF int a; void foo (void) { a = 0; } _LT_EOF ], [$1], [CXX], [cat > conftest.$ac_ext <<_LT_EOF class Foo { public: Foo (void) { a = 0; } private: int a; }; _LT_EOF ], [$1], [F77], [cat > conftest.$ac_ext <<_LT_EOF subroutine foo implicit none integer*4 a a=0 return end _LT_EOF ], [$1], [FC], [cat > conftest.$ac_ext <<_LT_EOF subroutine foo implicit none integer a a=0 return end _LT_EOF ], [$1], [GCJ], [cat > conftest.$ac_ext <<_LT_EOF public class foo { private int a; public void bar (void) { a = 0; } }; _LT_EOF ], [$1], [GO], [cat > conftest.$ac_ext <<_LT_EOF package foo func foo() { } _LT_EOF ]) _lt_libdeps_save_CFLAGS=$CFLAGS case "$CC $CFLAGS " in #( *\ -flto*\ *) CFLAGS="$CFLAGS -fno-lto" ;; *\ -fwhopr*\ *) CFLAGS="$CFLAGS -fno-whopr" ;; *\ -fuse-linker-plugin*\ *) CFLAGS="$CFLAGS -fno-use-linker-plugin" ;; esac dnl Parse the compiler output and extract the necessary dnl objects, libraries and library flags. if AC_TRY_EVAL(ac_compile); then # Parse the compiler output and extract the necessary # objects, libraries and library flags. # Sentinel used to keep track of whether or not we are before # the conftest object file. pre_test_object_deps_done=no for p in `eval "$output_verbose_link_cmd"`; do case $prev$p in -L* | -R* | -l*) # Some compilers place space between "-{L,R}" and the path. # Remove the space. if test x-L = "$p" || test x-R = "$p"; then prev=$p continue fi # Expand the sysroot to ease extracting the directories later. if test -z "$prev"; then case $p in -L*) func_stripname_cnf '-L' '' "$p"; prev=-L; p=$func_stripname_result ;; -R*) func_stripname_cnf '-R' '' "$p"; prev=-R; p=$func_stripname_result ;; -l*) func_stripname_cnf '-l' '' "$p"; prev=-l; p=$func_stripname_result ;; esac fi case $p in =*) func_stripname_cnf '=' '' "$p"; p=$lt_sysroot$func_stripname_result ;; esac if test no = "$pre_test_object_deps_done"; then case $prev in -L | -R) # Internal compiler library paths should come after those # provided the user. The postdeps already come after the # user supplied libs so there is no need to process them. if test -z "$_LT_TAGVAR(compiler_lib_search_path, $1)"; then _LT_TAGVAR(compiler_lib_search_path, $1)=$prev$p else _LT_TAGVAR(compiler_lib_search_path, $1)="${_LT_TAGVAR(compiler_lib_search_path, $1)} $prev$p" fi ;; # The "-l" case would never come before the object being # linked, so don't bother handling this case. esac else if test -z "$_LT_TAGVAR(postdeps, $1)"; then _LT_TAGVAR(postdeps, $1)=$prev$p else _LT_TAGVAR(postdeps, $1)="${_LT_TAGVAR(postdeps, $1)} $prev$p" fi fi prev= ;; *.lto.$objext) ;; # Ignore GCC LTO objects *.$objext) # This assumes that the test object file only shows up # once in the compiler output. if test "$p" = "conftest.$objext"; then pre_test_object_deps_done=yes continue fi if test no = "$pre_test_object_deps_done"; then if test -z "$_LT_TAGVAR(predep_objects, $1)"; then _LT_TAGVAR(predep_objects, $1)=$p else _LT_TAGVAR(predep_objects, $1)="$_LT_TAGVAR(predep_objects, $1) $p" fi else if test -z "$_LT_TAGVAR(postdep_objects, $1)"; then _LT_TAGVAR(postdep_objects, $1)=$p else _LT_TAGVAR(postdep_objects, $1)="$_LT_TAGVAR(postdep_objects, $1) $p" fi fi ;; *) ;; # Ignore the rest. esac done # Clean up. rm -f a.out a.exe else echo "libtool.m4: error: problem compiling $1 test program" fi $RM -f confest.$objext CFLAGS=$_lt_libdeps_save_CFLAGS # PORTME: override above test on systems where it is broken m4_if([$1], [CXX], [case $host_os in interix[[3-9]]*) # Interix 3.5 installs completely hosed .la files for C++, so rather than # hack all around it, let's just trust "g++" to DTRT. _LT_TAGVAR(predep_objects,$1)= _LT_TAGVAR(postdep_objects,$1)= _LT_TAGVAR(postdeps,$1)= ;; esac ]) case " $_LT_TAGVAR(postdeps, $1) " in *" -lc "*) _LT_TAGVAR(archive_cmds_need_lc, $1)=no ;; esac _LT_TAGVAR(compiler_lib_search_dirs, $1)= if test -n "${_LT_TAGVAR(compiler_lib_search_path, $1)}"; then _LT_TAGVAR(compiler_lib_search_dirs, $1)=`echo " ${_LT_TAGVAR(compiler_lib_search_path, $1)}" | $SED -e 's! -L! !g' -e 's!^ !!'` fi _LT_TAGDECL([], [compiler_lib_search_dirs], [1], [The directories searched by this compiler when creating a shared library]) _LT_TAGDECL([], [predep_objects], [1], [Dependencies to place before and after the objects being linked to create a shared library]) _LT_TAGDECL([], [postdep_objects], [1]) _LT_TAGDECL([], [predeps], [1]) _LT_TAGDECL([], [postdeps], [1]) _LT_TAGDECL([], [compiler_lib_search_path], [1], [The library search path used internally by the compiler when linking a shared library]) ])# _LT_SYS_HIDDEN_LIBDEPS # _LT_LANG_F77_CONFIG([TAG]) # -------------------------- # Ensure that the configuration variables for a Fortran 77 compiler are # suitably defined. These variables are subsequently used by _LT_CONFIG # to write the compiler configuration to 'libtool'. m4_defun([_LT_LANG_F77_CONFIG], [AC_LANG_PUSH(Fortran 77) if test -z "$F77" || test no = "$F77"; then _lt_disable_F77=yes fi _LT_TAGVAR(archive_cmds_need_lc, $1)=no _LT_TAGVAR(allow_undefined_flag, $1)= _LT_TAGVAR(always_export_symbols, $1)=no _LT_TAGVAR(archive_expsym_cmds, $1)= _LT_TAGVAR(export_dynamic_flag_spec, $1)= _LT_TAGVAR(hardcode_direct, $1)=no _LT_TAGVAR(hardcode_direct_absolute, $1)=no _LT_TAGVAR(hardcode_libdir_flag_spec, $1)= _LT_TAGVAR(hardcode_libdir_separator, $1)= _LT_TAGVAR(hardcode_minus_L, $1)=no _LT_TAGVAR(hardcode_automatic, $1)=no _LT_TAGVAR(inherit_rpath, $1)=no _LT_TAGVAR(module_cmds, $1)= _LT_TAGVAR(module_expsym_cmds, $1)= _LT_TAGVAR(link_all_deplibs, $1)=unknown _LT_TAGVAR(old_archive_cmds, $1)=$old_archive_cmds _LT_TAGVAR(reload_flag, $1)=$reload_flag _LT_TAGVAR(reload_cmds, $1)=$reload_cmds _LT_TAGVAR(no_undefined_flag, $1)= _LT_TAGVAR(whole_archive_flag_spec, $1)= _LT_TAGVAR(enable_shared_with_static_runtimes, $1)=no # Source file extension for f77 test sources. ac_ext=f # Object file extension for compiled f77 test sources. objext=o _LT_TAGVAR(objext, $1)=$objext # No sense in running all these tests if we already determined that # the F77 compiler isn't working. Some variables (like enable_shared) # are currently assumed to apply to all compilers on this platform, # and will be corrupted by setting them based on a non-working compiler. if test yes != "$_lt_disable_F77"; then # Code to be used in simple compile tests lt_simple_compile_test_code="\ subroutine t return end " # Code to be used in simple link tests lt_simple_link_test_code="\ program t end " # ltmain only uses $CC for tagged configurations so make sure $CC is set. _LT_TAG_COMPILER # save warnings/boilerplate of simple test code _LT_COMPILER_BOILERPLATE _LT_LINKER_BOILERPLATE # Allow CC to be a program name with arguments. lt_save_CC=$CC lt_save_GCC=$GCC lt_save_CFLAGS=$CFLAGS CC=${F77-"f77"} CFLAGS=$FFLAGS compiler=$CC _LT_TAGVAR(compiler, $1)=$CC _LT_CC_BASENAME([$compiler]) GCC=$G77 if test -n "$compiler"; then AC_MSG_CHECKING([if libtool supports shared libraries]) AC_MSG_RESULT([$can_build_shared]) AC_MSG_CHECKING([whether to build shared libraries]) test no = "$can_build_shared" && enable_shared=no # On AIX, shared libraries and static libraries use the same namespace, and # are all built from PIC. case $host_os in aix3*) test yes = "$enable_shared" && enable_static=no if test -n "$RANLIB"; then archive_cmds="$archive_cmds~\$RANLIB \$lib" postinstall_cmds='$RANLIB $lib' fi ;; aix[[4-9]]*) if test ia64 != "$host_cpu"; then case $enable_shared,$with_aix_soname,$aix_use_runtimelinking in yes,aix,yes) ;; # shared object as lib.so file only yes,svr4,*) ;; # shared object as lib.so archive member only yes,*) enable_static=no ;; # shared object in lib.a archive as well esac fi ;; esac AC_MSG_RESULT([$enable_shared]) AC_MSG_CHECKING([whether to build static libraries]) # Make sure either enable_shared or enable_static is yes. test yes = "$enable_shared" || enable_static=yes AC_MSG_RESULT([$enable_static]) _LT_TAGVAR(GCC, $1)=$G77 _LT_TAGVAR(LD, $1)=$LD ## CAVEAT EMPTOR: ## There is no encapsulation within the following macros, do not change ## the running order or otherwise move them around unless you know exactly ## what you are doing... _LT_COMPILER_PIC($1) _LT_COMPILER_C_O($1) _LT_COMPILER_FILE_LOCKS($1) _LT_LINKER_SHLIBS($1) _LT_SYS_DYNAMIC_LINKER($1) _LT_LINKER_HARDCODE_LIBPATH($1) _LT_CONFIG($1) fi # test -n "$compiler" GCC=$lt_save_GCC CC=$lt_save_CC CFLAGS=$lt_save_CFLAGS fi # test yes != "$_lt_disable_F77" AC_LANG_POP ])# _LT_LANG_F77_CONFIG # _LT_LANG_FC_CONFIG([TAG]) # ------------------------- # Ensure that the configuration variables for a Fortran compiler are # suitably defined. These variables are subsequently used by _LT_CONFIG # to write the compiler configuration to 'libtool'. m4_defun([_LT_LANG_FC_CONFIG], [AC_LANG_PUSH(Fortran) if test -z "$FC" || test no = "$FC"; then _lt_disable_FC=yes fi _LT_TAGVAR(archive_cmds_need_lc, $1)=no _LT_TAGVAR(allow_undefined_flag, $1)= _LT_TAGVAR(always_export_symbols, $1)=no _LT_TAGVAR(archive_expsym_cmds, $1)= _LT_TAGVAR(export_dynamic_flag_spec, $1)= _LT_TAGVAR(hardcode_direct, $1)=no _LT_TAGVAR(hardcode_direct_absolute, $1)=no _LT_TAGVAR(hardcode_libdir_flag_spec, $1)= _LT_TAGVAR(hardcode_libdir_separator, $1)= _LT_TAGVAR(hardcode_minus_L, $1)=no _LT_TAGVAR(hardcode_automatic, $1)=no _LT_TAGVAR(inherit_rpath, $1)=no _LT_TAGVAR(module_cmds, $1)= _LT_TAGVAR(module_expsym_cmds, $1)= _LT_TAGVAR(link_all_deplibs, $1)=unknown _LT_TAGVAR(old_archive_cmds, $1)=$old_archive_cmds _LT_TAGVAR(reload_flag, $1)=$reload_flag _LT_TAGVAR(reload_cmds, $1)=$reload_cmds _LT_TAGVAR(no_undefined_flag, $1)= _LT_TAGVAR(whole_archive_flag_spec, $1)= _LT_TAGVAR(enable_shared_with_static_runtimes, $1)=no # Source file extension for fc test sources. ac_ext=${ac_fc_srcext-f} # Object file extension for compiled fc test sources. objext=o _LT_TAGVAR(objext, $1)=$objext # No sense in running all these tests if we already determined that # the FC compiler isn't working. Some variables (like enable_shared) # are currently assumed to apply to all compilers on this platform, # and will be corrupted by setting them based on a non-working compiler. if test yes != "$_lt_disable_FC"; then # Code to be used in simple compile tests lt_simple_compile_test_code="\ subroutine t return end " # Code to be used in simple link tests lt_simple_link_test_code="\ program t end " # ltmain only uses $CC for tagged configurations so make sure $CC is set. _LT_TAG_COMPILER # save warnings/boilerplate of simple test code _LT_COMPILER_BOILERPLATE _LT_LINKER_BOILERPLATE # Allow CC to be a program name with arguments. lt_save_CC=$CC lt_save_GCC=$GCC lt_save_CFLAGS=$CFLAGS CC=${FC-"f95"} CFLAGS=$FCFLAGS compiler=$CC GCC=$ac_cv_fc_compiler_gnu _LT_TAGVAR(compiler, $1)=$CC _LT_CC_BASENAME([$compiler]) if test -n "$compiler"; then AC_MSG_CHECKING([if libtool supports shared libraries]) AC_MSG_RESULT([$can_build_shared]) AC_MSG_CHECKING([whether to build shared libraries]) test no = "$can_build_shared" && enable_shared=no # On AIX, shared libraries and static libraries use the same namespace, and # are all built from PIC. case $host_os in aix3*) test yes = "$enable_shared" && enable_static=no if test -n "$RANLIB"; then archive_cmds="$archive_cmds~\$RANLIB \$lib" postinstall_cmds='$RANLIB $lib' fi ;; aix[[4-9]]*) if test ia64 != "$host_cpu"; then case $enable_shared,$with_aix_soname,$aix_use_runtimelinking in yes,aix,yes) ;; # shared object as lib.so file only yes,svr4,*) ;; # shared object as lib.so archive member only yes,*) enable_static=no ;; # shared object in lib.a archive as well esac fi ;; esac AC_MSG_RESULT([$enable_shared]) AC_MSG_CHECKING([whether to build static libraries]) # Make sure either enable_shared or enable_static is yes. test yes = "$enable_shared" || enable_static=yes AC_MSG_RESULT([$enable_static]) _LT_TAGVAR(GCC, $1)=$ac_cv_fc_compiler_gnu _LT_TAGVAR(LD, $1)=$LD ## CAVEAT EMPTOR: ## There is no encapsulation within the following macros, do not change ## the running order or otherwise move them around unless you know exactly ## what you are doing... _LT_SYS_HIDDEN_LIBDEPS($1) _LT_COMPILER_PIC($1) _LT_COMPILER_C_O($1) _LT_COMPILER_FILE_LOCKS($1) _LT_LINKER_SHLIBS($1) _LT_SYS_DYNAMIC_LINKER($1) _LT_LINKER_HARDCODE_LIBPATH($1) _LT_CONFIG($1) fi # test -n "$compiler" GCC=$lt_save_GCC CC=$lt_save_CC CFLAGS=$lt_save_CFLAGS fi # test yes != "$_lt_disable_FC" AC_LANG_POP ])# _LT_LANG_FC_CONFIG # _LT_LANG_GCJ_CONFIG([TAG]) # -------------------------- # Ensure that the configuration variables for the GNU Java Compiler compiler # are suitably defined. These variables are subsequently used by _LT_CONFIG # to write the compiler configuration to 'libtool'. m4_defun([_LT_LANG_GCJ_CONFIG], [AC_REQUIRE([LT_PROG_GCJ])dnl AC_LANG_SAVE # Source file extension for Java test sources. ac_ext=java # Object file extension for compiled Java test sources. objext=o _LT_TAGVAR(objext, $1)=$objext # Code to be used in simple compile tests lt_simple_compile_test_code="class foo {}" # Code to be used in simple link tests lt_simple_link_test_code='public class conftest { public static void main(String[[]] argv) {}; }' # ltmain only uses $CC for tagged configurations so make sure $CC is set. _LT_TAG_COMPILER # save warnings/boilerplate of simple test code _LT_COMPILER_BOILERPLATE _LT_LINKER_BOILERPLATE # Allow CC to be a program name with arguments. lt_save_CC=$CC lt_save_CFLAGS=$CFLAGS lt_save_GCC=$GCC GCC=yes CC=${GCJ-"gcj"} CFLAGS=$GCJFLAGS compiler=$CC _LT_TAGVAR(compiler, $1)=$CC _LT_TAGVAR(LD, $1)=$LD _LT_CC_BASENAME([$compiler]) # GCJ did not exist at the time GCC didn't implicitly link libc in. _LT_TAGVAR(archive_cmds_need_lc, $1)=no _LT_TAGVAR(old_archive_cmds, $1)=$old_archive_cmds _LT_TAGVAR(reload_flag, $1)=$reload_flag _LT_TAGVAR(reload_cmds, $1)=$reload_cmds if test -n "$compiler"; then _LT_COMPILER_NO_RTTI($1) _LT_COMPILER_PIC($1) _LT_COMPILER_C_O($1) _LT_COMPILER_FILE_LOCKS($1) _LT_LINKER_SHLIBS($1) _LT_LINKER_HARDCODE_LIBPATH($1) _LT_CONFIG($1) fi AC_LANG_RESTORE GCC=$lt_save_GCC CC=$lt_save_CC CFLAGS=$lt_save_CFLAGS ])# _LT_LANG_GCJ_CONFIG # _LT_LANG_GO_CONFIG([TAG]) # -------------------------- # Ensure that the configuration variables for the GNU Go compiler # are suitably defined. These variables are subsequently used by _LT_CONFIG # to write the compiler configuration to 'libtool'. m4_defun([_LT_LANG_GO_CONFIG], [AC_REQUIRE([LT_PROG_GO])dnl AC_LANG_SAVE # Source file extension for Go test sources. ac_ext=go # Object file extension for compiled Go test sources. objext=o _LT_TAGVAR(objext, $1)=$objext # Code to be used in simple compile tests lt_simple_compile_test_code="package main; func main() { }" # Code to be used in simple link tests lt_simple_link_test_code='package main; func main() { }' # ltmain only uses $CC for tagged configurations so make sure $CC is set. _LT_TAG_COMPILER # save warnings/boilerplate of simple test code _LT_COMPILER_BOILERPLATE _LT_LINKER_BOILERPLATE # Allow CC to be a program name with arguments. lt_save_CC=$CC lt_save_CFLAGS=$CFLAGS lt_save_GCC=$GCC GCC=yes CC=${GOC-"gccgo"} CFLAGS=$GOFLAGS compiler=$CC _LT_TAGVAR(compiler, $1)=$CC _LT_TAGVAR(LD, $1)=$LD _LT_CC_BASENAME([$compiler]) # Go did not exist at the time GCC didn't implicitly link libc in. _LT_TAGVAR(archive_cmds_need_lc, $1)=no _LT_TAGVAR(old_archive_cmds, $1)=$old_archive_cmds _LT_TAGVAR(reload_flag, $1)=$reload_flag _LT_TAGVAR(reload_cmds, $1)=$reload_cmds if test -n "$compiler"; then _LT_COMPILER_NO_RTTI($1) _LT_COMPILER_PIC($1) _LT_COMPILER_C_O($1) _LT_COMPILER_FILE_LOCKS($1) _LT_LINKER_SHLIBS($1) _LT_LINKER_HARDCODE_LIBPATH($1) _LT_CONFIG($1) fi AC_LANG_RESTORE GCC=$lt_save_GCC CC=$lt_save_CC CFLAGS=$lt_save_CFLAGS ])# _LT_LANG_GO_CONFIG # _LT_LANG_RC_CONFIG([TAG]) # ------------------------- # Ensure that the configuration variables for the Windows resource compiler # are suitably defined. These variables are subsequently used by _LT_CONFIG # to write the compiler configuration to 'libtool'. m4_defun([_LT_LANG_RC_CONFIG], [AC_REQUIRE([LT_PROG_RC])dnl AC_LANG_SAVE # Source file extension for RC test sources. ac_ext=rc # Object file extension for compiled RC test sources. objext=o _LT_TAGVAR(objext, $1)=$objext # Code to be used in simple compile tests lt_simple_compile_test_code='sample MENU { MENUITEM "&Soup", 100, CHECKED }' # Code to be used in simple link tests lt_simple_link_test_code=$lt_simple_compile_test_code # ltmain only uses $CC for tagged configurations so make sure $CC is set. _LT_TAG_COMPILER # save warnings/boilerplate of simple test code _LT_COMPILER_BOILERPLATE _LT_LINKER_BOILERPLATE # Allow CC to be a program name with arguments. lt_save_CC=$CC lt_save_CFLAGS=$CFLAGS lt_save_GCC=$GCC GCC= CC=${RC-"windres"} CFLAGS= compiler=$CC _LT_TAGVAR(compiler, $1)=$CC _LT_CC_BASENAME([$compiler]) _LT_TAGVAR(lt_cv_prog_compiler_c_o, $1)=yes if test -n "$compiler"; then : _LT_CONFIG($1) fi GCC=$lt_save_GCC AC_LANG_RESTORE CC=$lt_save_CC CFLAGS=$lt_save_CFLAGS ])# _LT_LANG_RC_CONFIG # LT_PROG_GCJ # ----------- AC_DEFUN([LT_PROG_GCJ], [m4_ifdef([AC_PROG_GCJ], [AC_PROG_GCJ], [m4_ifdef([A][M_PROG_GCJ], [A][M_PROG_GCJ], [AC_CHECK_TOOL(GCJ, gcj,) test set = "${GCJFLAGS+set}" || GCJFLAGS="-g -O2" AC_SUBST(GCJFLAGS)])])[]dnl ]) # Old name: AU_ALIAS([LT_AC_PROG_GCJ], [LT_PROG_GCJ]) dnl aclocal-1.4 backwards compatibility: dnl AC_DEFUN([LT_AC_PROG_GCJ], []) # LT_PROG_GO # ---------- AC_DEFUN([LT_PROG_GO], [AC_CHECK_TOOL(GOC, gccgo,) ]) # LT_PROG_RC # ---------- AC_DEFUN([LT_PROG_RC], [AC_CHECK_TOOL(RC, windres,) ]) # Old name: AU_ALIAS([LT_AC_PROG_RC], [LT_PROG_RC]) dnl aclocal-1.4 backwards compatibility: dnl AC_DEFUN([LT_AC_PROG_RC], []) # _LT_DECL_EGREP # -------------- # If we don't have a new enough Autoconf to choose the best grep # available, choose the one first in the user's PATH. m4_defun([_LT_DECL_EGREP], [AC_REQUIRE([AC_PROG_EGREP])dnl AC_REQUIRE([AC_PROG_FGREP])dnl test -z "$GREP" && GREP=grep _LT_DECL([], [GREP], [1], [A grep program that handles long lines]) _LT_DECL([], [EGREP], [1], [An ERE matcher]) _LT_DECL([], [FGREP], [1], [A literal string matcher]) dnl Non-bleeding-edge autoconf doesn't subst GREP, so do it here too AC_SUBST([GREP]) ]) # _LT_DECL_OBJDUMP # -------------- # If we don't have a new enough Autoconf to choose the best objdump # available, choose the one first in the user's PATH. m4_defun([_LT_DECL_OBJDUMP], [AC_CHECK_TOOL(OBJDUMP, objdump, false) test -z "$OBJDUMP" && OBJDUMP=objdump _LT_DECL([], [OBJDUMP], [1], [An object symbol dumper]) AC_SUBST([OBJDUMP]) ]) # _LT_DECL_DLLTOOL # ---------------- # Ensure DLLTOOL variable is set. m4_defun([_LT_DECL_DLLTOOL], [AC_CHECK_TOOL(DLLTOOL, dlltool, false) test -z "$DLLTOOL" && DLLTOOL=dlltool _LT_DECL([], [DLLTOOL], [1], [DLL creation program]) AC_SUBST([DLLTOOL]) ]) # _LT_DECL_SED # ------------ # Check for a fully-functional sed program, that truncates # as few characters as possible. Prefer GNU sed if found. m4_defun([_LT_DECL_SED], [AC_PROG_SED test -z "$SED" && SED=sed Xsed="$SED -e 1s/^X//" _LT_DECL([], [SED], [1], [A sed program that does not truncate output]) _LT_DECL([], [Xsed], ["\$SED -e 1s/^X//"], [Sed that helps us avoid accidentally triggering echo(1) options like -n]) ])# _LT_DECL_SED m4_ifndef([AC_PROG_SED], [ # NOTE: This macro has been submitted for inclusion into # # GNU Autoconf as AC_PROG_SED. When it is available in # # a released version of Autoconf we should remove this # # macro and use it instead. # m4_defun([AC_PROG_SED], [AC_MSG_CHECKING([for a sed that does not truncate output]) AC_CACHE_VAL(lt_cv_path_SED, [# Loop through the user's path and test for sed and gsed. # Then use that list of sed's as ones to test for truncation. as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for lt_ac_prog in sed gsed; do for ac_exec_ext in '' $ac_executable_extensions; do if $as_executable_p "$as_dir/$lt_ac_prog$ac_exec_ext"; then lt_ac_sed_list="$lt_ac_sed_list $as_dir/$lt_ac_prog$ac_exec_ext" fi done done done IFS=$as_save_IFS lt_ac_max=0 lt_ac_count=0 # Add /usr/xpg4/bin/sed as it is typically found on Solaris # along with /bin/sed that truncates output. for lt_ac_sed in $lt_ac_sed_list /usr/xpg4/bin/sed; do test ! -f "$lt_ac_sed" && continue cat /dev/null > conftest.in lt_ac_count=0 echo $ECHO_N "0123456789$ECHO_C" >conftest.in # Check for GNU sed and select it if it is found. if "$lt_ac_sed" --version 2>&1 < /dev/null | grep 'GNU' > /dev/null; then lt_cv_path_SED=$lt_ac_sed break fi while true; do cat conftest.in conftest.in >conftest.tmp mv conftest.tmp conftest.in cp conftest.in conftest.nl echo >>conftest.nl $lt_ac_sed -e 's/a$//' < conftest.nl >conftest.out || break cmp -s conftest.out conftest.nl || break # 10000 chars as input seems more than enough test 10 -lt "$lt_ac_count" && break lt_ac_count=`expr $lt_ac_count + 1` if test "$lt_ac_count" -gt "$lt_ac_max"; then lt_ac_max=$lt_ac_count lt_cv_path_SED=$lt_ac_sed fi done done ]) SED=$lt_cv_path_SED AC_SUBST([SED]) AC_MSG_RESULT([$SED]) ])#AC_PROG_SED ])#m4_ifndef # Old name: AU_ALIAS([LT_AC_PROG_SED], [AC_PROG_SED]) dnl aclocal-1.4 backwards compatibility: dnl AC_DEFUN([LT_AC_PROG_SED], []) # _LT_CHECK_SHELL_FEATURES # ------------------------ # Find out whether the shell is Bourne or XSI compatible, # or has some other useful features. m4_defun([_LT_CHECK_SHELL_FEATURES], [if ( (MAIL=60; unset MAIL) || exit) >/dev/null 2>&1; then lt_unset=unset else lt_unset=false fi _LT_DECL([], [lt_unset], [0], [whether the shell understands "unset"])dnl # test EBCDIC or ASCII case `echo X|tr X '\101'` in A) # ASCII based system # \n is not interpreted correctly by Solaris 8 /usr/ucb/tr lt_SP2NL='tr \040 \012' lt_NL2SP='tr \015\012 \040\040' ;; *) # EBCDIC based system lt_SP2NL='tr \100 \n' lt_NL2SP='tr \r\n \100\100' ;; esac _LT_DECL([SP2NL], [lt_SP2NL], [1], [turn spaces into newlines])dnl _LT_DECL([NL2SP], [lt_NL2SP], [1], [turn newlines into spaces])dnl ])# _LT_CHECK_SHELL_FEATURES # _LT_PATH_CONVERSION_FUNCTIONS # ----------------------------- # Determine what file name conversion functions should be used by # func_to_host_file (and, implicitly, by func_to_host_path). These are needed # for certain cross-compile configurations and native mingw. m4_defun([_LT_PATH_CONVERSION_FUNCTIONS], [AC_REQUIRE([AC_CANONICAL_HOST])dnl AC_REQUIRE([AC_CANONICAL_BUILD])dnl AC_MSG_CHECKING([how to convert $build file names to $host format]) AC_CACHE_VAL(lt_cv_to_host_file_cmd, [case $host in *-*-mingw* ) case $build in *-*-mingw* ) # actually msys lt_cv_to_host_file_cmd=func_convert_file_msys_to_w32 ;; *-*-cygwin* ) lt_cv_to_host_file_cmd=func_convert_file_cygwin_to_w32 ;; * ) # otherwise, assume *nix lt_cv_to_host_file_cmd=func_convert_file_nix_to_w32 ;; esac ;; *-*-cygwin* ) case $build in *-*-mingw* ) # actually msys lt_cv_to_host_file_cmd=func_convert_file_msys_to_cygwin ;; *-*-cygwin* ) lt_cv_to_host_file_cmd=func_convert_file_noop ;; * ) # otherwise, assume *nix lt_cv_to_host_file_cmd=func_convert_file_nix_to_cygwin ;; esac ;; * ) # unhandled hosts (and "normal" native builds) lt_cv_to_host_file_cmd=func_convert_file_noop ;; esac ]) to_host_file_cmd=$lt_cv_to_host_file_cmd AC_MSG_RESULT([$lt_cv_to_host_file_cmd]) _LT_DECL([to_host_file_cmd], [lt_cv_to_host_file_cmd], [0], [convert $build file names to $host format])dnl AC_MSG_CHECKING([how to convert $build file names to toolchain format]) AC_CACHE_VAL(lt_cv_to_tool_file_cmd, [#assume ordinary cross tools, or native build. lt_cv_to_tool_file_cmd=func_convert_file_noop case $host in *-*-mingw* ) case $build in *-*-mingw* ) # actually msys lt_cv_to_tool_file_cmd=func_convert_file_msys_to_w32 ;; esac ;; esac ]) to_tool_file_cmd=$lt_cv_to_tool_file_cmd AC_MSG_RESULT([$lt_cv_to_tool_file_cmd]) _LT_DECL([to_tool_file_cmd], [lt_cv_to_tool_file_cmd], [0], [convert $build files to toolchain format])dnl ])# _LT_PATH_CONVERSION_FUNCTIONS # Helper functions for option handling. -*- Autoconf -*- # # Copyright (C) 2004-2005, 2007-2009, 2011-2015 Free Software # Foundation, Inc. # Written by Gary V. Vaughan, 2004 # # This file is free software; the Free Software Foundation gives # unlimited permission to copy and/or distribute it, with or without # modifications, as long as this notice is preserved. # serial 8 ltoptions.m4 # This is to help aclocal find these macros, as it can't see m4_define. AC_DEFUN([LTOPTIONS_VERSION], [m4_if([1])]) # _LT_MANGLE_OPTION(MACRO-NAME, OPTION-NAME) # ------------------------------------------ m4_define([_LT_MANGLE_OPTION], [[_LT_OPTION_]m4_bpatsubst($1__$2, [[^a-zA-Z0-9_]], [_])]) # _LT_SET_OPTION(MACRO-NAME, OPTION-NAME) # --------------------------------------- # Set option OPTION-NAME for macro MACRO-NAME, and if there is a # matching handler defined, dispatch to it. Other OPTION-NAMEs are # saved as a flag. m4_define([_LT_SET_OPTION], [m4_define(_LT_MANGLE_OPTION([$1], [$2]))dnl m4_ifdef(_LT_MANGLE_DEFUN([$1], [$2]), _LT_MANGLE_DEFUN([$1], [$2]), [m4_warning([Unknown $1 option '$2'])])[]dnl ]) # _LT_IF_OPTION(MACRO-NAME, OPTION-NAME, IF-SET, [IF-NOT-SET]) # ------------------------------------------------------------ # Execute IF-SET if OPTION is set, IF-NOT-SET otherwise. m4_define([_LT_IF_OPTION], [m4_ifdef(_LT_MANGLE_OPTION([$1], [$2]), [$3], [$4])]) # _LT_UNLESS_OPTIONS(MACRO-NAME, OPTION-LIST, IF-NOT-SET) # ------------------------------------------------------- # Execute IF-NOT-SET unless all options in OPTION-LIST for MACRO-NAME # are set. m4_define([_LT_UNLESS_OPTIONS], [m4_foreach([_LT_Option], m4_split(m4_normalize([$2])), [m4_ifdef(_LT_MANGLE_OPTION([$1], _LT_Option), [m4_define([$0_found])])])[]dnl m4_ifdef([$0_found], [m4_undefine([$0_found])], [$3 ])[]dnl ]) # _LT_SET_OPTIONS(MACRO-NAME, OPTION-LIST) # ---------------------------------------- # OPTION-LIST is a space-separated list of Libtool options associated # with MACRO-NAME. If any OPTION has a matching handler declared with # LT_OPTION_DEFINE, dispatch to that macro; otherwise complain about # the unknown option and exit. m4_defun([_LT_SET_OPTIONS], [# Set options m4_foreach([_LT_Option], m4_split(m4_normalize([$2])), [_LT_SET_OPTION([$1], _LT_Option)]) m4_if([$1],[LT_INIT],[ dnl dnl Simply set some default values (i.e off) if boolean options were not dnl specified: _LT_UNLESS_OPTIONS([LT_INIT], [dlopen], [enable_dlopen=no ]) _LT_UNLESS_OPTIONS([LT_INIT], [win32-dll], [enable_win32_dll=no ]) dnl dnl If no reference was made to various pairs of opposing options, then dnl we run the default mode handler for the pair. For example, if neither dnl 'shared' nor 'disable-shared' was passed, we enable building of shared dnl archives by default: _LT_UNLESS_OPTIONS([LT_INIT], [shared disable-shared], [_LT_ENABLE_SHARED]) _LT_UNLESS_OPTIONS([LT_INIT], [static disable-static], [_LT_ENABLE_STATIC]) _LT_UNLESS_OPTIONS([LT_INIT], [pic-only no-pic], [_LT_WITH_PIC]) _LT_UNLESS_OPTIONS([LT_INIT], [fast-install disable-fast-install], [_LT_ENABLE_FAST_INSTALL]) _LT_UNLESS_OPTIONS([LT_INIT], [aix-soname=aix aix-soname=both aix-soname=svr4], [_LT_WITH_AIX_SONAME([aix])]) ]) ])# _LT_SET_OPTIONS # _LT_MANGLE_DEFUN(MACRO-NAME, OPTION-NAME) # ----------------------------------------- m4_define([_LT_MANGLE_DEFUN], [[_LT_OPTION_DEFUN_]m4_bpatsubst(m4_toupper([$1__$2]), [[^A-Z0-9_]], [_])]) # LT_OPTION_DEFINE(MACRO-NAME, OPTION-NAME, CODE) # ----------------------------------------------- m4_define([LT_OPTION_DEFINE], [m4_define(_LT_MANGLE_DEFUN([$1], [$2]), [$3])[]dnl ])# LT_OPTION_DEFINE # dlopen # ------ LT_OPTION_DEFINE([LT_INIT], [dlopen], [enable_dlopen=yes ]) AU_DEFUN([AC_LIBTOOL_DLOPEN], [_LT_SET_OPTION([LT_INIT], [dlopen]) AC_DIAGNOSE([obsolete], [$0: Remove this warning and the call to _LT_SET_OPTION when you put the 'dlopen' option into LT_INIT's first parameter.]) ]) dnl aclocal-1.4 backwards compatibility: dnl AC_DEFUN([AC_LIBTOOL_DLOPEN], []) # win32-dll # --------- # Declare package support for building win32 dll's. LT_OPTION_DEFINE([LT_INIT], [win32-dll], [enable_win32_dll=yes case $host in *-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-cegcc*) AC_CHECK_TOOL(AS, as, false) AC_CHECK_TOOL(DLLTOOL, dlltool, false) AC_CHECK_TOOL(OBJDUMP, objdump, false) ;; esac test -z "$AS" && AS=as _LT_DECL([], [AS], [1], [Assembler program])dnl test -z "$DLLTOOL" && DLLTOOL=dlltool _LT_DECL([], [DLLTOOL], [1], [DLL creation program])dnl test -z "$OBJDUMP" && OBJDUMP=objdump _LT_DECL([], [OBJDUMP], [1], [Object dumper program])dnl ])# win32-dll AU_DEFUN([AC_LIBTOOL_WIN32_DLL], [AC_REQUIRE([AC_CANONICAL_HOST])dnl _LT_SET_OPTION([LT_INIT], [win32-dll]) AC_DIAGNOSE([obsolete], [$0: Remove this warning and the call to _LT_SET_OPTION when you put the 'win32-dll' option into LT_INIT's first parameter.]) ]) dnl aclocal-1.4 backwards compatibility: dnl AC_DEFUN([AC_LIBTOOL_WIN32_DLL], []) # _LT_ENABLE_SHARED([DEFAULT]) # ---------------------------- # implement the --enable-shared flag, and supports the 'shared' and # 'disable-shared' LT_INIT options. # DEFAULT is either 'yes' or 'no'. If omitted, it defaults to 'yes'. m4_define([_LT_ENABLE_SHARED], [m4_define([_LT_ENABLE_SHARED_DEFAULT], [m4_if($1, no, no, yes)])dnl AC_ARG_ENABLE([shared], [AS_HELP_STRING([--enable-shared@<:@=PKGS@:>@], [build shared libraries @<:@default=]_LT_ENABLE_SHARED_DEFAULT[@:>@])], [p=${PACKAGE-default} case $enableval in yes) enable_shared=yes ;; no) enable_shared=no ;; *) enable_shared=no # Look at the argument we got. We use all the common list separators. lt_save_ifs=$IFS; IFS=$IFS$PATH_SEPARATOR, for pkg in $enableval; do IFS=$lt_save_ifs if test "X$pkg" = "X$p"; then enable_shared=yes fi done IFS=$lt_save_ifs ;; esac], [enable_shared=]_LT_ENABLE_SHARED_DEFAULT) _LT_DECL([build_libtool_libs], [enable_shared], [0], [Whether or not to build shared libraries]) ])# _LT_ENABLE_SHARED LT_OPTION_DEFINE([LT_INIT], [shared], [_LT_ENABLE_SHARED([yes])]) LT_OPTION_DEFINE([LT_INIT], [disable-shared], [_LT_ENABLE_SHARED([no])]) # Old names: AC_DEFUN([AC_ENABLE_SHARED], [_LT_SET_OPTION([LT_INIT], m4_if([$1], [no], [disable-])[shared]) ]) AC_DEFUN([AC_DISABLE_SHARED], [_LT_SET_OPTION([LT_INIT], [disable-shared]) ]) AU_DEFUN([AM_ENABLE_SHARED], [AC_ENABLE_SHARED($@)]) AU_DEFUN([AM_DISABLE_SHARED], [AC_DISABLE_SHARED($@)]) dnl aclocal-1.4 backwards compatibility: dnl AC_DEFUN([AM_ENABLE_SHARED], []) dnl AC_DEFUN([AM_DISABLE_SHARED], []) # _LT_ENABLE_STATIC([DEFAULT]) # ---------------------------- # implement the --enable-static flag, and support the 'static' and # 'disable-static' LT_INIT options. # DEFAULT is either 'yes' or 'no'. If omitted, it defaults to 'yes'. m4_define([_LT_ENABLE_STATIC], [m4_define([_LT_ENABLE_STATIC_DEFAULT], [m4_if($1, no, no, yes)])dnl AC_ARG_ENABLE([static], [AS_HELP_STRING([--enable-static@<:@=PKGS@:>@], [build static libraries @<:@default=]_LT_ENABLE_STATIC_DEFAULT[@:>@])], [p=${PACKAGE-default} case $enableval in yes) enable_static=yes ;; no) enable_static=no ;; *) enable_static=no # Look at the argument we got. We use all the common list separators. lt_save_ifs=$IFS; IFS=$IFS$PATH_SEPARATOR, for pkg in $enableval; do IFS=$lt_save_ifs if test "X$pkg" = "X$p"; then enable_static=yes fi done IFS=$lt_save_ifs ;; esac], [enable_static=]_LT_ENABLE_STATIC_DEFAULT) _LT_DECL([build_old_libs], [enable_static], [0], [Whether or not to build static libraries]) ])# _LT_ENABLE_STATIC LT_OPTION_DEFINE([LT_INIT], [static], [_LT_ENABLE_STATIC([yes])]) LT_OPTION_DEFINE([LT_INIT], [disable-static], [_LT_ENABLE_STATIC([no])]) # Old names: AC_DEFUN([AC_ENABLE_STATIC], [_LT_SET_OPTION([LT_INIT], m4_if([$1], [no], [disable-])[static]) ]) AC_DEFUN([AC_DISABLE_STATIC], [_LT_SET_OPTION([LT_INIT], [disable-static]) ]) AU_DEFUN([AM_ENABLE_STATIC], [AC_ENABLE_STATIC($@)]) AU_DEFUN([AM_DISABLE_STATIC], [AC_DISABLE_STATIC($@)]) dnl aclocal-1.4 backwards compatibility: dnl AC_DEFUN([AM_ENABLE_STATIC], []) dnl AC_DEFUN([AM_DISABLE_STATIC], []) # _LT_ENABLE_FAST_INSTALL([DEFAULT]) # ---------------------------------- # implement the --enable-fast-install flag, and support the 'fast-install' # and 'disable-fast-install' LT_INIT options. # DEFAULT is either 'yes' or 'no'. If omitted, it defaults to 'yes'. m4_define([_LT_ENABLE_FAST_INSTALL], [m4_define([_LT_ENABLE_FAST_INSTALL_DEFAULT], [m4_if($1, no, no, yes)])dnl AC_ARG_ENABLE([fast-install], [AS_HELP_STRING([--enable-fast-install@<:@=PKGS@:>@], [optimize for fast installation @<:@default=]_LT_ENABLE_FAST_INSTALL_DEFAULT[@:>@])], [p=${PACKAGE-default} case $enableval in yes) enable_fast_install=yes ;; no) enable_fast_install=no ;; *) enable_fast_install=no # Look at the argument we got. We use all the common list separators. lt_save_ifs=$IFS; IFS=$IFS$PATH_SEPARATOR, for pkg in $enableval; do IFS=$lt_save_ifs if test "X$pkg" = "X$p"; then enable_fast_install=yes fi done IFS=$lt_save_ifs ;; esac], [enable_fast_install=]_LT_ENABLE_FAST_INSTALL_DEFAULT) _LT_DECL([fast_install], [enable_fast_install], [0], [Whether or not to optimize for fast installation])dnl ])# _LT_ENABLE_FAST_INSTALL LT_OPTION_DEFINE([LT_INIT], [fast-install], [_LT_ENABLE_FAST_INSTALL([yes])]) LT_OPTION_DEFINE([LT_INIT], [disable-fast-install], [_LT_ENABLE_FAST_INSTALL([no])]) # Old names: AU_DEFUN([AC_ENABLE_FAST_INSTALL], [_LT_SET_OPTION([LT_INIT], m4_if([$1], [no], [disable-])[fast-install]) AC_DIAGNOSE([obsolete], [$0: Remove this warning and the call to _LT_SET_OPTION when you put the 'fast-install' option into LT_INIT's first parameter.]) ]) AU_DEFUN([AC_DISABLE_FAST_INSTALL], [_LT_SET_OPTION([LT_INIT], [disable-fast-install]) AC_DIAGNOSE([obsolete], [$0: Remove this warning and the call to _LT_SET_OPTION when you put the 'disable-fast-install' option into LT_INIT's first parameter.]) ]) dnl aclocal-1.4 backwards compatibility: dnl AC_DEFUN([AC_ENABLE_FAST_INSTALL], []) dnl AC_DEFUN([AM_DISABLE_FAST_INSTALL], []) # _LT_WITH_AIX_SONAME([DEFAULT]) # ---------------------------------- # implement the --with-aix-soname flag, and support the `aix-soname=aix' # and `aix-soname=both' and `aix-soname=svr4' LT_INIT options. DEFAULT # is either `aix', `both' or `svr4'. If omitted, it defaults to `aix'. m4_define([_LT_WITH_AIX_SONAME], [m4_define([_LT_WITH_AIX_SONAME_DEFAULT], [m4_if($1, svr4, svr4, m4_if($1, both, both, aix))])dnl shared_archive_member_spec= case $host,$enable_shared in power*-*-aix[[5-9]]*,yes) AC_MSG_CHECKING([which variant of shared library versioning to provide]) AC_ARG_WITH([aix-soname], [AS_HELP_STRING([--with-aix-soname=aix|svr4|both], [shared library versioning (aka "SONAME") variant to provide on AIX, @<:@default=]_LT_WITH_AIX_SONAME_DEFAULT[@:>@.])], [case $withval in aix|svr4|both) ;; *) AC_MSG_ERROR([Unknown argument to --with-aix-soname]) ;; esac lt_cv_with_aix_soname=$with_aix_soname], [AC_CACHE_VAL([lt_cv_with_aix_soname], [lt_cv_with_aix_soname=]_LT_WITH_AIX_SONAME_DEFAULT) with_aix_soname=$lt_cv_with_aix_soname]) AC_MSG_RESULT([$with_aix_soname]) if test aix != "$with_aix_soname"; then # For the AIX way of multilib, we name the shared archive member # based on the bitwidth used, traditionally 'shr.o' or 'shr_64.o', # and 'shr.imp' or 'shr_64.imp', respectively, for the Import File. # Even when GNU compilers ignore OBJECT_MODE but need '-maix64' flag, # the AIX toolchain works better with OBJECT_MODE set (default 32). if test 64 = "${OBJECT_MODE-32}"; then shared_archive_member_spec=shr_64 else shared_archive_member_spec=shr fi fi ;; *) with_aix_soname=aix ;; esac _LT_DECL([], [shared_archive_member_spec], [0], [Shared archive member basename, for filename based shared library versioning on AIX])dnl ])# _LT_WITH_AIX_SONAME LT_OPTION_DEFINE([LT_INIT], [aix-soname=aix], [_LT_WITH_AIX_SONAME([aix])]) LT_OPTION_DEFINE([LT_INIT], [aix-soname=both], [_LT_WITH_AIX_SONAME([both])]) LT_OPTION_DEFINE([LT_INIT], [aix-soname=svr4], [_LT_WITH_AIX_SONAME([svr4])]) # _LT_WITH_PIC([MODE]) # -------------------- # implement the --with-pic flag, and support the 'pic-only' and 'no-pic' # LT_INIT options. # MODE is either 'yes' or 'no'. If omitted, it defaults to 'both'. m4_define([_LT_WITH_PIC], [AC_ARG_WITH([pic], [AS_HELP_STRING([--with-pic@<:@=PKGS@:>@], [try to use only PIC/non-PIC objects @<:@default=use both@:>@])], [lt_p=${PACKAGE-default} case $withval in yes|no) pic_mode=$withval ;; *) pic_mode=default # Look at the argument we got. We use all the common list separators. lt_save_ifs=$IFS; IFS=$IFS$PATH_SEPARATOR, for lt_pkg in $withval; do IFS=$lt_save_ifs if test "X$lt_pkg" = "X$lt_p"; then pic_mode=yes fi done IFS=$lt_save_ifs ;; esac], [pic_mode=m4_default([$1], [default])]) _LT_DECL([], [pic_mode], [0], [What type of objects to build])dnl ])# _LT_WITH_PIC LT_OPTION_DEFINE([LT_INIT], [pic-only], [_LT_WITH_PIC([yes])]) LT_OPTION_DEFINE([LT_INIT], [no-pic], [_LT_WITH_PIC([no])]) # Old name: AU_DEFUN([AC_LIBTOOL_PICMODE], [_LT_SET_OPTION([LT_INIT], [pic-only]) AC_DIAGNOSE([obsolete], [$0: Remove this warning and the call to _LT_SET_OPTION when you put the 'pic-only' option into LT_INIT's first parameter.]) ]) dnl aclocal-1.4 backwards compatibility: dnl AC_DEFUN([AC_LIBTOOL_PICMODE], []) m4_define([_LTDL_MODE], []) LT_OPTION_DEFINE([LTDL_INIT], [nonrecursive], [m4_define([_LTDL_MODE], [nonrecursive])]) LT_OPTION_DEFINE([LTDL_INIT], [recursive], [m4_define([_LTDL_MODE], [recursive])]) LT_OPTION_DEFINE([LTDL_INIT], [subproject], [m4_define([_LTDL_MODE], [subproject])]) m4_define([_LTDL_TYPE], []) LT_OPTION_DEFINE([LTDL_INIT], [installable], [m4_define([_LTDL_TYPE], [installable])]) LT_OPTION_DEFINE([LTDL_INIT], [convenience], [m4_define([_LTDL_TYPE], [convenience])]) # ltsugar.m4 -- libtool m4 base layer. -*-Autoconf-*- # # Copyright (C) 2004-2005, 2007-2008, 2011-2015 Free Software # Foundation, Inc. # Written by Gary V. Vaughan, 2004 # # This file is free software; the Free Software Foundation gives # unlimited permission to copy and/or distribute it, with or without # modifications, as long as this notice is preserved. # serial 6 ltsugar.m4 # This is to help aclocal find these macros, as it can't see m4_define. AC_DEFUN([LTSUGAR_VERSION], [m4_if([0.1])]) # lt_join(SEP, ARG1, [ARG2...]) # ----------------------------- # Produce ARG1SEPARG2...SEPARGn, omitting [] arguments and their # associated separator. # Needed until we can rely on m4_join from Autoconf 2.62, since all earlier # versions in m4sugar had bugs. m4_define([lt_join], [m4_if([$#], [1], [], [$#], [2], [[$2]], [m4_if([$2], [], [], [[$2]_])$0([$1], m4_shift(m4_shift($@)))])]) m4_define([_lt_join], [m4_if([$#$2], [2], [], [m4_if([$2], [], [], [[$1$2]])$0([$1], m4_shift(m4_shift($@)))])]) # lt_car(LIST) # lt_cdr(LIST) # ------------ # Manipulate m4 lists. # These macros are necessary as long as will still need to support # Autoconf-2.59, which quotes differently. m4_define([lt_car], [[$1]]) m4_define([lt_cdr], [m4_if([$#], 0, [m4_fatal([$0: cannot be called without arguments])], [$#], 1, [], [m4_dquote(m4_shift($@))])]) m4_define([lt_unquote], $1) # lt_append(MACRO-NAME, STRING, [SEPARATOR]) # ------------------------------------------ # Redefine MACRO-NAME to hold its former content plus 'SEPARATOR''STRING'. # Note that neither SEPARATOR nor STRING are expanded; they are appended # to MACRO-NAME as is (leaving the expansion for when MACRO-NAME is invoked). # No SEPARATOR is output if MACRO-NAME was previously undefined (different # than defined and empty). # # This macro is needed until we can rely on Autoconf 2.62, since earlier # versions of m4sugar mistakenly expanded SEPARATOR but not STRING. m4_define([lt_append], [m4_define([$1], m4_ifdef([$1], [m4_defn([$1])[$3]])[$2])]) # lt_combine(SEP, PREFIX-LIST, INFIX, SUFFIX1, [SUFFIX2...]) # ---------------------------------------------------------- # Produce a SEP delimited list of all paired combinations of elements of # PREFIX-LIST with SUFFIX1 through SUFFIXn. Each element of the list # has the form PREFIXmINFIXSUFFIXn. # Needed until we can rely on m4_combine added in Autoconf 2.62. m4_define([lt_combine], [m4_if(m4_eval([$# > 3]), [1], [m4_pushdef([_Lt_sep], [m4_define([_Lt_sep], m4_defn([lt_car]))])]]dnl [[m4_foreach([_Lt_prefix], [$2], [m4_foreach([_Lt_suffix], ]m4_dquote(m4_dquote(m4_shift(m4_shift(m4_shift($@)))))[, [_Lt_sep([$1])[]m4_defn([_Lt_prefix])[$3]m4_defn([_Lt_suffix])])])])]) # lt_if_append_uniq(MACRO-NAME, VARNAME, [SEPARATOR], [UNIQ], [NOT-UNIQ]) # ----------------------------------------------------------------------- # Iff MACRO-NAME does not yet contain VARNAME, then append it (delimited # by SEPARATOR if supplied) and expand UNIQ, else NOT-UNIQ. m4_define([lt_if_append_uniq], [m4_ifdef([$1], [m4_if(m4_index([$3]m4_defn([$1])[$3], [$3$2$3]), [-1], [lt_append([$1], [$2], [$3])$4], [$5])], [lt_append([$1], [$2], [$3])$4])]) # lt_dict_add(DICT, KEY, VALUE) # ----------------------------- m4_define([lt_dict_add], [m4_define([$1($2)], [$3])]) # lt_dict_add_subkey(DICT, KEY, SUBKEY, VALUE) # -------------------------------------------- m4_define([lt_dict_add_subkey], [m4_define([$1($2:$3)], [$4])]) # lt_dict_fetch(DICT, KEY, [SUBKEY]) # ---------------------------------- m4_define([lt_dict_fetch], [m4_ifval([$3], m4_ifdef([$1($2:$3)], [m4_defn([$1($2:$3)])]), m4_ifdef([$1($2)], [m4_defn([$1($2)])]))]) # lt_if_dict_fetch(DICT, KEY, [SUBKEY], VALUE, IF-TRUE, [IF-FALSE]) # ----------------------------------------------------------------- m4_define([lt_if_dict_fetch], [m4_if(lt_dict_fetch([$1], [$2], [$3]), [$4], [$5], [$6])]) # lt_dict_filter(DICT, [SUBKEY], VALUE, [SEPARATOR], KEY, [...]) # -------------------------------------------------------------- m4_define([lt_dict_filter], [m4_if([$5], [], [], [lt_join(m4_quote(m4_default([$4], [[, ]])), lt_unquote(m4_split(m4_normalize(m4_foreach(_Lt_key, lt_car([m4_shiftn(4, $@)]), [lt_if_dict_fetch([$1], _Lt_key, [$2], [$3], [_Lt_key ])])))))])[]dnl ]) # ltversion.m4 -- version numbers -*- Autoconf -*- # # Copyright (C) 2004, 2011-2015 Free Software Foundation, Inc. # Written by Scott James Remnant, 2004 # # This file is free software; the Free Software Foundation gives # unlimited permission to copy and/or distribute it, with or without # modifications, as long as this notice is preserved. # @configure_input@ # serial 4179 ltversion.m4 # This file is part of GNU Libtool m4_define([LT_PACKAGE_VERSION], [2.4.6]) m4_define([LT_PACKAGE_REVISION], [2.4.6]) AC_DEFUN([LTVERSION_VERSION], [macro_version='2.4.6' macro_revision='2.4.6' _LT_DECL(, macro_version, 0, [Which release of libtool.m4 was used?]) _LT_DECL(, macro_revision, 0) ]) # lt~obsolete.m4 -- aclocal satisfying obsolete definitions. -*-Autoconf-*- # # Copyright (C) 2004-2005, 2007, 2009, 2011-2015 Free Software # Foundation, Inc. # Written by Scott James Remnant, 2004. # # This file is free software; the Free Software Foundation gives # unlimited permission to copy and/or distribute it, with or without # modifications, as long as this notice is preserved. # serial 5 lt~obsolete.m4 # These exist entirely to fool aclocal when bootstrapping libtool. # # In the past libtool.m4 has provided macros via AC_DEFUN (or AU_DEFUN), # which have later been changed to m4_define as they aren't part of the # exported API, or moved to Autoconf or Automake where they belong. # # The trouble is, aclocal is a bit thick. It'll see the old AC_DEFUN # in /usr/share/aclocal/libtool.m4 and remember it, then when it sees us # using a macro with the same name in our local m4/libtool.m4 it'll # pull the old libtool.m4 in (it doesn't see our shiny new m4_define # and doesn't know about Autoconf macros at all.) # # So we provide this file, which has a silly filename so it's always # included after everything else. This provides aclocal with the # AC_DEFUNs it wants, but when m4 processes it, it doesn't do anything # because those macros already exist, or will be overwritten later. # We use AC_DEFUN over AU_DEFUN for compatibility with aclocal-1.6. # # Anytime we withdraw an AC_DEFUN or AU_DEFUN, remember to add it here. # Yes, that means every name once taken will need to remain here until # we give up compatibility with versions before 1.7, at which point # we need to keep only those names which we still refer to. # This is to help aclocal find these macros, as it can't see m4_define. AC_DEFUN([LTOBSOLETE_VERSION], [m4_if([1])]) m4_ifndef([AC_LIBTOOL_LINKER_OPTION], [AC_DEFUN([AC_LIBTOOL_LINKER_OPTION])]) m4_ifndef([AC_PROG_EGREP], [AC_DEFUN([AC_PROG_EGREP])]) m4_ifndef([_LT_AC_PROG_ECHO_BACKSLASH], [AC_DEFUN([_LT_AC_PROG_ECHO_BACKSLASH])]) m4_ifndef([_LT_AC_SHELL_INIT], [AC_DEFUN([_LT_AC_SHELL_INIT])]) m4_ifndef([_LT_AC_SYS_LIBPATH_AIX], [AC_DEFUN([_LT_AC_SYS_LIBPATH_AIX])]) m4_ifndef([_LT_PROG_LTMAIN], [AC_DEFUN([_LT_PROG_LTMAIN])]) m4_ifndef([_LT_AC_TAGVAR], [AC_DEFUN([_LT_AC_TAGVAR])]) m4_ifndef([AC_LTDL_ENABLE_INSTALL], [AC_DEFUN([AC_LTDL_ENABLE_INSTALL])]) m4_ifndef([AC_LTDL_PREOPEN], [AC_DEFUN([AC_LTDL_PREOPEN])]) m4_ifndef([_LT_AC_SYS_COMPILER], [AC_DEFUN([_LT_AC_SYS_COMPILER])]) m4_ifndef([_LT_AC_LOCK], [AC_DEFUN([_LT_AC_LOCK])]) m4_ifndef([AC_LIBTOOL_SYS_OLD_ARCHIVE], [AC_DEFUN([AC_LIBTOOL_SYS_OLD_ARCHIVE])]) m4_ifndef([_LT_AC_TRY_DLOPEN_SELF], [AC_DEFUN([_LT_AC_TRY_DLOPEN_SELF])]) m4_ifndef([AC_LIBTOOL_PROG_CC_C_O], [AC_DEFUN([AC_LIBTOOL_PROG_CC_C_O])]) m4_ifndef([AC_LIBTOOL_SYS_HARD_LINK_LOCKS], [AC_DEFUN([AC_LIBTOOL_SYS_HARD_LINK_LOCKS])]) m4_ifndef([AC_LIBTOOL_OBJDIR], [AC_DEFUN([AC_LIBTOOL_OBJDIR])]) m4_ifndef([AC_LTDL_OBJDIR], [AC_DEFUN([AC_LTDL_OBJDIR])]) m4_ifndef([AC_LIBTOOL_PROG_LD_HARDCODE_LIBPATH], [AC_DEFUN([AC_LIBTOOL_PROG_LD_HARDCODE_LIBPATH])]) m4_ifndef([AC_LIBTOOL_SYS_LIB_STRIP], [AC_DEFUN([AC_LIBTOOL_SYS_LIB_STRIP])]) m4_ifndef([AC_PATH_MAGIC], [AC_DEFUN([AC_PATH_MAGIC])]) m4_ifndef([AC_PROG_LD_GNU], [AC_DEFUN([AC_PROG_LD_GNU])]) m4_ifndef([AC_PROG_LD_RELOAD_FLAG], [AC_DEFUN([AC_PROG_LD_RELOAD_FLAG])]) m4_ifndef([AC_DEPLIBS_CHECK_METHOD], [AC_DEFUN([AC_DEPLIBS_CHECK_METHOD])]) m4_ifndef([AC_LIBTOOL_PROG_COMPILER_NO_RTTI], [AC_DEFUN([AC_LIBTOOL_PROG_COMPILER_NO_RTTI])]) m4_ifndef([AC_LIBTOOL_SYS_GLOBAL_SYMBOL_PIPE], [AC_DEFUN([AC_LIBTOOL_SYS_GLOBAL_SYMBOL_PIPE])]) m4_ifndef([AC_LIBTOOL_PROG_COMPILER_PIC], [AC_DEFUN([AC_LIBTOOL_PROG_COMPILER_PIC])]) m4_ifndef([AC_LIBTOOL_PROG_LD_SHLIBS], [AC_DEFUN([AC_LIBTOOL_PROG_LD_SHLIBS])]) m4_ifndef([AC_LIBTOOL_POSTDEP_PREDEP], [AC_DEFUN([AC_LIBTOOL_POSTDEP_PREDEP])]) m4_ifndef([LT_AC_PROG_EGREP], [AC_DEFUN([LT_AC_PROG_EGREP])]) m4_ifndef([LT_AC_PROG_SED], [AC_DEFUN([LT_AC_PROG_SED])]) m4_ifndef([_LT_CC_BASENAME], [AC_DEFUN([_LT_CC_BASENAME])]) m4_ifndef([_LT_COMPILER_BOILERPLATE], [AC_DEFUN([_LT_COMPILER_BOILERPLATE])]) m4_ifndef([_LT_LINKER_BOILERPLATE], [AC_DEFUN([_LT_LINKER_BOILERPLATE])]) m4_ifndef([_AC_PROG_LIBTOOL], [AC_DEFUN([_AC_PROG_LIBTOOL])]) m4_ifndef([AC_LIBTOOL_SETUP], [AC_DEFUN([AC_LIBTOOL_SETUP])]) m4_ifndef([_LT_AC_CHECK_DLFCN], [AC_DEFUN([_LT_AC_CHECK_DLFCN])]) m4_ifndef([AC_LIBTOOL_SYS_DYNAMIC_LINKER], [AC_DEFUN([AC_LIBTOOL_SYS_DYNAMIC_LINKER])]) m4_ifndef([_LT_AC_TAGCONFIG], [AC_DEFUN([_LT_AC_TAGCONFIG])]) m4_ifndef([AC_DISABLE_FAST_INSTALL], [AC_DEFUN([AC_DISABLE_FAST_INSTALL])]) m4_ifndef([_LT_AC_LANG_CXX], [AC_DEFUN([_LT_AC_LANG_CXX])]) m4_ifndef([_LT_AC_LANG_F77], [AC_DEFUN([_LT_AC_LANG_F77])]) m4_ifndef([_LT_AC_LANG_GCJ], [AC_DEFUN([_LT_AC_LANG_GCJ])]) m4_ifndef([AC_LIBTOOL_LANG_C_CONFIG], [AC_DEFUN([AC_LIBTOOL_LANG_C_CONFIG])]) m4_ifndef([_LT_AC_LANG_C_CONFIG], [AC_DEFUN([_LT_AC_LANG_C_CONFIG])]) m4_ifndef([AC_LIBTOOL_LANG_CXX_CONFIG], [AC_DEFUN([AC_LIBTOOL_LANG_CXX_CONFIG])]) m4_ifndef([_LT_AC_LANG_CXX_CONFIG], [AC_DEFUN([_LT_AC_LANG_CXX_CONFIG])]) m4_ifndef([AC_LIBTOOL_LANG_F77_CONFIG], [AC_DEFUN([AC_LIBTOOL_LANG_F77_CONFIG])]) m4_ifndef([_LT_AC_LANG_F77_CONFIG], [AC_DEFUN([_LT_AC_LANG_F77_CONFIG])]) m4_ifndef([AC_LIBTOOL_LANG_GCJ_CONFIG], [AC_DEFUN([AC_LIBTOOL_LANG_GCJ_CONFIG])]) m4_ifndef([_LT_AC_LANG_GCJ_CONFIG], [AC_DEFUN([_LT_AC_LANG_GCJ_CONFIG])]) m4_ifndef([AC_LIBTOOL_LANG_RC_CONFIG], [AC_DEFUN([AC_LIBTOOL_LANG_RC_CONFIG])]) m4_ifndef([_LT_AC_LANG_RC_CONFIG], [AC_DEFUN([_LT_AC_LANG_RC_CONFIG])]) m4_ifndef([AC_LIBTOOL_CONFIG], [AC_DEFUN([AC_LIBTOOL_CONFIG])]) m4_ifndef([_LT_AC_FILE_LTDLL_C], [AC_DEFUN([_LT_AC_FILE_LTDLL_C])]) m4_ifndef([_LT_REQUIRED_DARWIN_CHECKS], [AC_DEFUN([_LT_REQUIRED_DARWIN_CHECKS])]) m4_ifndef([_LT_AC_PROG_CXXCPP], [AC_DEFUN([_LT_AC_PROG_CXXCPP])]) m4_ifndef([_LT_PREPARE_SED_QUOTE_VARS], [AC_DEFUN([_LT_PREPARE_SED_QUOTE_VARS])]) m4_ifndef([_LT_PROG_ECHO_BACKSLASH], [AC_DEFUN([_LT_PROG_ECHO_BACKSLASH])]) m4_ifndef([_LT_PROG_F77], [AC_DEFUN([_LT_PROG_F77])]) m4_ifndef([_LT_PROG_FC], [AC_DEFUN([_LT_PROG_FC])]) m4_ifndef([_LT_PROG_CXX], [AC_DEFUN([_LT_PROG_CXX])]) # Copyright (C) 2002-2017 Free Software Foundation, Inc. # # This file is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, # with or without modifications, as long as this notice is preserved. # AM_AUTOMAKE_VERSION(VERSION) # ---------------------------- # Automake X.Y traces this macro to ensure aclocal.m4 has been # generated from the m4 files accompanying Automake X.Y. # (This private macro should not be called outside this file.) AC_DEFUN([AM_AUTOMAKE_VERSION], [am__api_version='1.15' dnl Some users find AM_AUTOMAKE_VERSION and mistake it for a way to dnl require some minimum version. Point them to the right macro. m4_if([$1], [1.15.1], [], [AC_FATAL([Do not call $0, use AM_INIT_AUTOMAKE([$1]).])])dnl ]) # _AM_AUTOCONF_VERSION(VERSION) # ----------------------------- # aclocal traces this macro to find the Autoconf version. # This is a private macro too. Using m4_define simplifies # the logic in aclocal, which can simply ignore this definition. m4_define([_AM_AUTOCONF_VERSION], []) # AM_SET_CURRENT_AUTOMAKE_VERSION # ------------------------------- # Call AM_AUTOMAKE_VERSION and AM_AUTOMAKE_VERSION so they can be traced. # This function is AC_REQUIREd by AM_INIT_AUTOMAKE. AC_DEFUN([AM_SET_CURRENT_AUTOMAKE_VERSION], [AM_AUTOMAKE_VERSION([1.15.1])dnl m4_ifndef([AC_AUTOCONF_VERSION], [m4_copy([m4_PACKAGE_VERSION], [AC_AUTOCONF_VERSION])])dnl _AM_AUTOCONF_VERSION(m4_defn([AC_AUTOCONF_VERSION]))]) # AM_AUX_DIR_EXPAND -*- Autoconf -*- # Copyright (C) 2001-2017 Free Software Foundation, Inc. # # This file is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, # with or without modifications, as long as this notice is preserved. # For projects using AC_CONFIG_AUX_DIR([foo]), Autoconf sets # $ac_aux_dir to '$srcdir/foo'. In other projects, it is set to # '$srcdir', '$srcdir/..', or '$srcdir/../..'. # # Of course, Automake must honor this variable whenever it calls a # tool from the auxiliary directory. The problem is that $srcdir (and # therefore $ac_aux_dir as well) can be either absolute or relative, # depending on how configure is run. This is pretty annoying, since # it makes $ac_aux_dir quite unusable in subdirectories: in the top # source directory, any form will work fine, but in subdirectories a # relative path needs to be adjusted first. # # $ac_aux_dir/missing # fails when called from a subdirectory if $ac_aux_dir is relative # $top_srcdir/$ac_aux_dir/missing # fails if $ac_aux_dir is absolute, # fails when called from a subdirectory in a VPATH build with # a relative $ac_aux_dir # # The reason of the latter failure is that $top_srcdir and $ac_aux_dir # are both prefixed by $srcdir. In an in-source build this is usually # harmless because $srcdir is '.', but things will broke when you # start a VPATH build or use an absolute $srcdir. # # So we could use something similar to $top_srcdir/$ac_aux_dir/missing, # iff we strip the leading $srcdir from $ac_aux_dir. That would be: # am_aux_dir='\$(top_srcdir)/'`expr "$ac_aux_dir" : "$srcdir//*\(.*\)"` # and then we would define $MISSING as # MISSING="\${SHELL} $am_aux_dir/missing" # This will work as long as MISSING is not called from configure, because # unfortunately $(top_srcdir) has no meaning in configure. # However there are other variables, like CC, which are often used in # configure, and could therefore not use this "fixed" $ac_aux_dir. # # Another solution, used here, is to always expand $ac_aux_dir to an # absolute PATH. The drawback is that using absolute paths prevent a # configured tree to be moved without reconfiguration. AC_DEFUN([AM_AUX_DIR_EXPAND], [AC_REQUIRE([AC_CONFIG_AUX_DIR_DEFAULT])dnl # Expand $ac_aux_dir to an absolute path. am_aux_dir=`cd "$ac_aux_dir" && pwd` ]) # AM_CONDITIONAL -*- Autoconf -*- # Copyright (C) 1997-2017 Free Software Foundation, Inc. # # This file is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, # with or without modifications, as long as this notice is preserved. # AM_CONDITIONAL(NAME, SHELL-CONDITION) # ------------------------------------- # Define a conditional. AC_DEFUN([AM_CONDITIONAL], [AC_PREREQ([2.52])dnl m4_if([$1], [TRUE], [AC_FATAL([$0: invalid condition: $1])], [$1], [FALSE], [AC_FATAL([$0: invalid condition: $1])])dnl AC_SUBST([$1_TRUE])dnl AC_SUBST([$1_FALSE])dnl _AM_SUBST_NOTMAKE([$1_TRUE])dnl _AM_SUBST_NOTMAKE([$1_FALSE])dnl m4_define([_AM_COND_VALUE_$1], [$2])dnl if $2; then $1_TRUE= $1_FALSE='#' else $1_TRUE='#' $1_FALSE= fi AC_CONFIG_COMMANDS_PRE( [if test -z "${$1_TRUE}" && test -z "${$1_FALSE}"; then AC_MSG_ERROR([[conditional "$1" was never defined. Usually this means the macro was only invoked conditionally.]]) fi])]) # Copyright (C) 1999-2017 Free Software Foundation, Inc. # # This file is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, # with or without modifications, as long as this notice is preserved. # There are a few dirty hacks below to avoid letting 'AC_PROG_CC' be # written in clear, in which case automake, when reading aclocal.m4, # will think it sees a *use*, and therefore will trigger all it's # C support machinery. Also note that it means that autoscan, seeing # CC etc. in the Makefile, will ask for an AC_PROG_CC use... # _AM_DEPENDENCIES(NAME) # ---------------------- # See how the compiler implements dependency checking. # NAME is "CC", "CXX", "OBJC", "OBJCXX", "UPC", or "GJC". # We try a few techniques and use that to set a single cache variable. # # We don't AC_REQUIRE the corresponding AC_PROG_CC since the latter was # modified to invoke _AM_DEPENDENCIES(CC); we would have a circular # dependency, and given that the user is not expected to run this macro, # just rely on AC_PROG_CC. AC_DEFUN([_AM_DEPENDENCIES], [AC_REQUIRE([AM_SET_DEPDIR])dnl AC_REQUIRE([AM_OUTPUT_DEPENDENCY_COMMANDS])dnl AC_REQUIRE([AM_MAKE_INCLUDE])dnl AC_REQUIRE([AM_DEP_TRACK])dnl m4_if([$1], [CC], [depcc="$CC" am_compiler_list=], [$1], [CXX], [depcc="$CXX" am_compiler_list=], [$1], [OBJC], [depcc="$OBJC" am_compiler_list='gcc3 gcc'], [$1], [OBJCXX], [depcc="$OBJCXX" am_compiler_list='gcc3 gcc'], [$1], [UPC], [depcc="$UPC" am_compiler_list=], [$1], [GCJ], [depcc="$GCJ" am_compiler_list='gcc3 gcc'], [depcc="$$1" am_compiler_list=]) AC_CACHE_CHECK([dependency style of $depcc], [am_cv_$1_dependencies_compiler_type], [if test -z "$AMDEP_TRUE" && test -f "$am_depcomp"; then # We make a subdir and do the tests there. Otherwise we can end up # making bogus files that we don't know about and never remove. For # instance it was reported that on HP-UX the gcc test will end up # making a dummy file named 'D' -- because '-MD' means "put the output # in D". rm -rf conftest.dir mkdir conftest.dir # Copy depcomp to subdir because otherwise we won't find it if we're # using a relative directory. cp "$am_depcomp" conftest.dir cd conftest.dir # We will build objects and dependencies in a subdirectory because # it helps to detect inapplicable dependency modes. For instance # both Tru64's cc and ICC support -MD to output dependencies as a # side effect of compilation, but ICC will put the dependencies in # the current directory while Tru64 will put them in the object # directory. mkdir sub am_cv_$1_dependencies_compiler_type=none if test "$am_compiler_list" = ""; then am_compiler_list=`sed -n ['s/^#*\([a-zA-Z0-9]*\))$/\1/p'] < ./depcomp` fi am__universal=false m4_case([$1], [CC], [case " $depcc " in #( *\ -arch\ *\ -arch\ *) am__universal=true ;; esac], [CXX], [case " $depcc " in #( *\ -arch\ *\ -arch\ *) am__universal=true ;; esac]) for depmode in $am_compiler_list; do # Setup a source with many dependencies, because some compilers # like to wrap large dependency lists on column 80 (with \), and # we should not choose a depcomp mode which is confused by this. # # We need to recreate these files for each test, as the compiler may # overwrite some of them when testing with obscure command lines. # This happens at least with the AIX C compiler. : > sub/conftest.c for i in 1 2 3 4 5 6; do echo '#include "conftst'$i'.h"' >> sub/conftest.c # Using ": > sub/conftst$i.h" creates only sub/conftst1.h with # Solaris 10 /bin/sh. echo '/* dummy */' > sub/conftst$i.h done echo "${am__include} ${am__quote}sub/conftest.Po${am__quote}" > confmf # We check with '-c' and '-o' for the sake of the "dashmstdout" # mode. It turns out that the SunPro C++ compiler does not properly # handle '-M -o', and we need to detect this. Also, some Intel # versions had trouble with output in subdirs. am__obj=sub/conftest.${OBJEXT-o} am__minus_obj="-o $am__obj" case $depmode in gcc) # This depmode causes a compiler race in universal mode. test "$am__universal" = false || continue ;; nosideeffect) # After this tag, mechanisms are not by side-effect, so they'll # only be used when explicitly requested. if test "x$enable_dependency_tracking" = xyes; then continue else break fi ;; msvc7 | msvc7msys | msvisualcpp | msvcmsys) # This compiler won't grok '-c -o', but also, the minuso test has # not run yet. These depmodes are late enough in the game, and # so weak that their functioning should not be impacted. am__obj=conftest.${OBJEXT-o} am__minus_obj= ;; none) break ;; esac if depmode=$depmode \ source=sub/conftest.c object=$am__obj \ depfile=sub/conftest.Po tmpdepfile=sub/conftest.TPo \ $SHELL ./depcomp $depcc -c $am__minus_obj sub/conftest.c \ >/dev/null 2>conftest.err && grep sub/conftst1.h sub/conftest.Po > /dev/null 2>&1 && grep sub/conftst6.h sub/conftest.Po > /dev/null 2>&1 && grep $am__obj sub/conftest.Po > /dev/null 2>&1 && ${MAKE-make} -s -f confmf > /dev/null 2>&1; then # icc doesn't choke on unknown options, it will just issue warnings # or remarks (even with -Werror). So we grep stderr for any message # that says an option was ignored or not supported. # When given -MP, icc 7.0 and 7.1 complain thusly: # icc: Command line warning: ignoring option '-M'; no argument required # The diagnosis changed in icc 8.0: # icc: Command line remark: option '-MP' not supported if (grep 'ignoring option' conftest.err || grep 'not supported' conftest.err) >/dev/null 2>&1; then :; else am_cv_$1_dependencies_compiler_type=$depmode break fi fi done cd .. rm -rf conftest.dir else am_cv_$1_dependencies_compiler_type=none fi ]) AC_SUBST([$1DEPMODE], [depmode=$am_cv_$1_dependencies_compiler_type]) AM_CONDITIONAL([am__fastdep$1], [ test "x$enable_dependency_tracking" != xno \ && test "$am_cv_$1_dependencies_compiler_type" = gcc3]) ]) # AM_SET_DEPDIR # ------------- # Choose a directory name for dependency files. # This macro is AC_REQUIREd in _AM_DEPENDENCIES. AC_DEFUN([AM_SET_DEPDIR], [AC_REQUIRE([AM_SET_LEADING_DOT])dnl AC_SUBST([DEPDIR], ["${am__leading_dot}deps"])dnl ]) # AM_DEP_TRACK # ------------ AC_DEFUN([AM_DEP_TRACK], [AC_ARG_ENABLE([dependency-tracking], [dnl AS_HELP_STRING( [--enable-dependency-tracking], [do not reject slow dependency extractors]) AS_HELP_STRING( [--disable-dependency-tracking], [speeds up one-time build])]) if test "x$enable_dependency_tracking" != xno; then am_depcomp="$ac_aux_dir/depcomp" AMDEPBACKSLASH='\' am__nodep='_no' fi AM_CONDITIONAL([AMDEP], [test "x$enable_dependency_tracking" != xno]) AC_SUBST([AMDEPBACKSLASH])dnl _AM_SUBST_NOTMAKE([AMDEPBACKSLASH])dnl AC_SUBST([am__nodep])dnl _AM_SUBST_NOTMAKE([am__nodep])dnl ]) # Generate code to set up dependency tracking. -*- Autoconf -*- # Copyright (C) 1999-2017 Free Software Foundation, Inc. # # This file is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, # with or without modifications, as long as this notice is preserved. # _AM_OUTPUT_DEPENDENCY_COMMANDS # ------------------------------ AC_DEFUN([_AM_OUTPUT_DEPENDENCY_COMMANDS], [{ # Older Autoconf quotes --file arguments for eval, but not when files # are listed without --file. Let's play safe and only enable the eval # if we detect the quoting. case $CONFIG_FILES in *\'*) eval set x "$CONFIG_FILES" ;; *) set x $CONFIG_FILES ;; esac shift for mf do # Strip MF so we end up with the name of the file. mf=`echo "$mf" | sed -e 's/:.*$//'` # Check whether this is an Automake generated Makefile or not. # We used to match only the files named 'Makefile.in', but # some people rename them; so instead we look at the file content. # Grep'ing the first line is not enough: some people post-process # each Makefile.in and add a new line on top of each file to say so. # Grep'ing the whole file is not good either: AIX grep has a line # limit of 2048, but all sed's we know have understand at least 4000. if sed -n 's,^#.*generated by automake.*,X,p' "$mf" | grep X >/dev/null 2>&1; then dirpart=`AS_DIRNAME("$mf")` else continue fi # Extract the definition of DEPDIR, am__include, and am__quote # from the Makefile without running 'make'. DEPDIR=`sed -n 's/^DEPDIR = //p' < "$mf"` test -z "$DEPDIR" && continue am__include=`sed -n 's/^am__include = //p' < "$mf"` test -z "$am__include" && continue am__quote=`sed -n 's/^am__quote = //p' < "$mf"` # Find all dependency output files, they are included files with # $(DEPDIR) in their names. We invoke sed twice because it is the # simplest approach to changing $(DEPDIR) to its actual value in the # expansion. for file in `sed -n " s/^$am__include $am__quote\(.*(DEPDIR).*\)$am__quote"'$/\1/p' <"$mf" | \ sed -e 's/\$(DEPDIR)/'"$DEPDIR"'/g'`; do # Make sure the directory exists. test -f "$dirpart/$file" && continue fdir=`AS_DIRNAME(["$file"])` AS_MKDIR_P([$dirpart/$fdir]) # echo "creating $dirpart/$file" echo '# dummy' > "$dirpart/$file" done done } ])# _AM_OUTPUT_DEPENDENCY_COMMANDS # AM_OUTPUT_DEPENDENCY_COMMANDS # ----------------------------- # This macro should only be invoked once -- use via AC_REQUIRE. # # This code is only required when automatic dependency tracking # is enabled. FIXME. This creates each '.P' file that we will # need in order to bootstrap the dependency handling code. AC_DEFUN([AM_OUTPUT_DEPENDENCY_COMMANDS], [AC_CONFIG_COMMANDS([depfiles], [test x"$AMDEP_TRUE" != x"" || _AM_OUTPUT_DEPENDENCY_COMMANDS], [AMDEP_TRUE="$AMDEP_TRUE" ac_aux_dir="$ac_aux_dir"]) ]) # Do all the work for Automake. -*- Autoconf -*- # Copyright (C) 1996-2017 Free Software Foundation, Inc. # # This file is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, # with or without modifications, as long as this notice is preserved. # This macro actually does too much. Some checks are only needed if # your package does certain things. But this isn't really a big deal. dnl Redefine AC_PROG_CC to automatically invoke _AM_PROG_CC_C_O. m4_define([AC_PROG_CC], m4_defn([AC_PROG_CC]) [_AM_PROG_CC_C_O ]) # AM_INIT_AUTOMAKE(PACKAGE, VERSION, [NO-DEFINE]) # AM_INIT_AUTOMAKE([OPTIONS]) # ----------------------------------------------- # The call with PACKAGE and VERSION arguments is the old style # call (pre autoconf-2.50), which is being phased out. PACKAGE # and VERSION should now be passed to AC_INIT and removed from # the call to AM_INIT_AUTOMAKE. # We support both call styles for the transition. After # the next Automake release, Autoconf can make the AC_INIT # arguments mandatory, and then we can depend on a new Autoconf # release and drop the old call support. AC_DEFUN([AM_INIT_AUTOMAKE], [AC_PREREQ([2.65])dnl dnl Autoconf wants to disallow AM_ names. We explicitly allow dnl the ones we care about. m4_pattern_allow([^AM_[A-Z]+FLAGS$])dnl AC_REQUIRE([AM_SET_CURRENT_AUTOMAKE_VERSION])dnl AC_REQUIRE([AC_PROG_INSTALL])dnl if test "`cd $srcdir && pwd`" != "`pwd`"; then # Use -I$(srcdir) only when $(srcdir) != ., so that make's output # is not polluted with repeated "-I." AC_SUBST([am__isrc], [' -I$(srcdir)'])_AM_SUBST_NOTMAKE([am__isrc])dnl # test to see if srcdir already configured if test -f $srcdir/config.status; then AC_MSG_ERROR([source directory already configured; run "make distclean" there first]) fi fi # test whether we have cygpath if test -z "$CYGPATH_W"; then if (cygpath --version) >/dev/null 2>/dev/null; then CYGPATH_W='cygpath -w' else CYGPATH_W=echo fi fi AC_SUBST([CYGPATH_W]) # Define the identity of the package. dnl Distinguish between old-style and new-style calls. m4_ifval([$2], [AC_DIAGNOSE([obsolete], [$0: two- and three-arguments forms are deprecated.]) m4_ifval([$3], [_AM_SET_OPTION([no-define])])dnl AC_SUBST([PACKAGE], [$1])dnl AC_SUBST([VERSION], [$2])], [_AM_SET_OPTIONS([$1])dnl dnl Diagnose old-style AC_INIT with new-style AM_AUTOMAKE_INIT. m4_if( m4_ifdef([AC_PACKAGE_NAME], [ok]):m4_ifdef([AC_PACKAGE_VERSION], [ok]), [ok:ok],, [m4_fatal([AC_INIT should be called with package and version arguments])])dnl AC_SUBST([PACKAGE], ['AC_PACKAGE_TARNAME'])dnl AC_SUBST([VERSION], ['AC_PACKAGE_VERSION'])])dnl _AM_IF_OPTION([no-define],, [AC_DEFINE_UNQUOTED([PACKAGE], ["$PACKAGE"], [Name of package]) AC_DEFINE_UNQUOTED([VERSION], ["$VERSION"], [Version number of package])])dnl # Some tools Automake needs. AC_REQUIRE([AM_SANITY_CHECK])dnl AC_REQUIRE([AC_ARG_PROGRAM])dnl AM_MISSING_PROG([ACLOCAL], [aclocal-${am__api_version}]) AM_MISSING_PROG([AUTOCONF], [autoconf]) AM_MISSING_PROG([AUTOMAKE], [automake-${am__api_version}]) AM_MISSING_PROG([AUTOHEADER], [autoheader]) AM_MISSING_PROG([MAKEINFO], [makeinfo]) AC_REQUIRE([AM_PROG_INSTALL_SH])dnl AC_REQUIRE([AM_PROG_INSTALL_STRIP])dnl AC_REQUIRE([AC_PROG_MKDIR_P])dnl # For better backward compatibility. To be removed once Automake 1.9.x # dies out for good. For more background, see: # # AC_SUBST([mkdir_p], ['$(MKDIR_P)']) # We need awk for the "check" target (and possibly the TAP driver). The # system "awk" is bad on some platforms. AC_REQUIRE([AC_PROG_AWK])dnl AC_REQUIRE([AC_PROG_MAKE_SET])dnl AC_REQUIRE([AM_SET_LEADING_DOT])dnl _AM_IF_OPTION([tar-ustar], [_AM_PROG_TAR([ustar])], [_AM_IF_OPTION([tar-pax], [_AM_PROG_TAR([pax])], [_AM_PROG_TAR([v7])])]) _AM_IF_OPTION([no-dependencies],, [AC_PROVIDE_IFELSE([AC_PROG_CC], [_AM_DEPENDENCIES([CC])], [m4_define([AC_PROG_CC], m4_defn([AC_PROG_CC])[_AM_DEPENDENCIES([CC])])])dnl AC_PROVIDE_IFELSE([AC_PROG_CXX], [_AM_DEPENDENCIES([CXX])], [m4_define([AC_PROG_CXX], m4_defn([AC_PROG_CXX])[_AM_DEPENDENCIES([CXX])])])dnl AC_PROVIDE_IFELSE([AC_PROG_OBJC], [_AM_DEPENDENCIES([OBJC])], [m4_define([AC_PROG_OBJC], m4_defn([AC_PROG_OBJC])[_AM_DEPENDENCIES([OBJC])])])dnl AC_PROVIDE_IFELSE([AC_PROG_OBJCXX], [_AM_DEPENDENCIES([OBJCXX])], [m4_define([AC_PROG_OBJCXX], m4_defn([AC_PROG_OBJCXX])[_AM_DEPENDENCIES([OBJCXX])])])dnl ]) AC_REQUIRE([AM_SILENT_RULES])dnl dnl The testsuite driver may need to know about EXEEXT, so add the dnl 'am__EXEEXT' conditional if _AM_COMPILER_EXEEXT was seen. This dnl macro is hooked onto _AC_COMPILER_EXEEXT early, see below. AC_CONFIG_COMMANDS_PRE(dnl [m4_provide_if([_AM_COMPILER_EXEEXT], [AM_CONDITIONAL([am__EXEEXT], [test -n "$EXEEXT"])])])dnl # POSIX will say in a future version that running "rm -f" with no argument # is OK; and we want to be able to make that assumption in our Makefile # recipes. So use an aggressive probe to check that the usage we want is # actually supported "in the wild" to an acceptable degree. # See automake bug#10828. # To make any issue more visible, cause the running configure to be aborted # by default if the 'rm' program in use doesn't match our expectations; the # user can still override this though. if rm -f && rm -fr && rm -rf; then : OK; else cat >&2 <<'END' Oops! Your 'rm' program seems unable to run without file operands specified on the command line, even when the '-f' option is present. This is contrary to the behaviour of most rm programs out there, and not conforming with the upcoming POSIX standard: Please tell bug-automake@gnu.org about your system, including the value of your $PATH and any error possibly output before this message. This can help us improve future automake versions. END if test x"$ACCEPT_INFERIOR_RM_PROGRAM" = x"yes"; then echo 'Configuration will proceed anyway, since you have set the' >&2 echo 'ACCEPT_INFERIOR_RM_PROGRAM variable to "yes"' >&2 echo >&2 else cat >&2 <<'END' Aborting the configuration process, to ensure you take notice of the issue. You can download and install GNU coreutils to get an 'rm' implementation that behaves properly: . If you want to complete the configuration process using your problematic 'rm' anyway, export the environment variable ACCEPT_INFERIOR_RM_PROGRAM to "yes", and re-run configure. END AC_MSG_ERROR([Your 'rm' program is bad, sorry.]) fi fi dnl The trailing newline in this macro's definition is deliberate, for dnl backward compatibility and to allow trailing 'dnl'-style comments dnl after the AM_INIT_AUTOMAKE invocation. See automake bug#16841. ]) dnl Hook into '_AC_COMPILER_EXEEXT' early to learn its expansion. Do not dnl add the conditional right here, as _AC_COMPILER_EXEEXT may be further dnl mangled by Autoconf and run in a shell conditional statement. m4_define([_AC_COMPILER_EXEEXT], m4_defn([_AC_COMPILER_EXEEXT])[m4_provide([_AM_COMPILER_EXEEXT])]) # When config.status generates a header, we must update the stamp-h file. # This file resides in the same directory as the config header # that is generated. The stamp files are numbered to have different names. # Autoconf calls _AC_AM_CONFIG_HEADER_HOOK (when defined) in the # loop where config.status creates the headers, so we can generate # our stamp files there. AC_DEFUN([_AC_AM_CONFIG_HEADER_HOOK], [# Compute $1's index in $config_headers. _am_arg=$1 _am_stamp_count=1 for _am_header in $config_headers :; do case $_am_header in $_am_arg | $_am_arg:* ) break ;; * ) _am_stamp_count=`expr $_am_stamp_count + 1` ;; esac done echo "timestamp for $_am_arg" >`AS_DIRNAME(["$_am_arg"])`/stamp-h[]$_am_stamp_count]) # Copyright (C) 2001-2017 Free Software Foundation, Inc. # # This file is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, # with or without modifications, as long as this notice is preserved. # AM_PROG_INSTALL_SH # ------------------ # Define $install_sh. AC_DEFUN([AM_PROG_INSTALL_SH], [AC_REQUIRE([AM_AUX_DIR_EXPAND])dnl if test x"${install_sh+set}" != xset; then case $am_aux_dir in *\ * | *\ *) install_sh="\${SHELL} '$am_aux_dir/install-sh'" ;; *) install_sh="\${SHELL} $am_aux_dir/install-sh" esac fi AC_SUBST([install_sh])]) # Copyright (C) 2003-2017 Free Software Foundation, Inc. # # This file is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, # with or without modifications, as long as this notice is preserved. # Check whether the underlying file-system supports filenames # with a leading dot. For instance MS-DOS doesn't. AC_DEFUN([AM_SET_LEADING_DOT], [rm -rf .tst 2>/dev/null mkdir .tst 2>/dev/null if test -d .tst; then am__leading_dot=. else am__leading_dot=_ fi rmdir .tst 2>/dev/null AC_SUBST([am__leading_dot])]) # Check to see how 'make' treats includes. -*- Autoconf -*- # Copyright (C) 2001-2017 Free Software Foundation, Inc. # # This file is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, # with or without modifications, as long as this notice is preserved. # AM_MAKE_INCLUDE() # ----------------- # Check to see how make treats includes. AC_DEFUN([AM_MAKE_INCLUDE], [am_make=${MAKE-make} cat > confinc << 'END' am__doit: @echo this is the am__doit target .PHONY: am__doit END # If we don't find an include directive, just comment out the code. AC_MSG_CHECKING([for style of include used by $am_make]) am__include="#" am__quote= _am_result=none # First try GNU make style include. echo "include confinc" > confmf # Ignore all kinds of additional output from 'make'. case `$am_make -s -f confmf 2> /dev/null` in #( *the\ am__doit\ target*) am__include=include am__quote= _am_result=GNU ;; esac # Now try BSD make style include. if test "$am__include" = "#"; then echo '.include "confinc"' > confmf case `$am_make -s -f confmf 2> /dev/null` in #( *the\ am__doit\ target*) am__include=.include am__quote="\"" _am_result=BSD ;; esac fi AC_SUBST([am__include]) AC_SUBST([am__quote]) AC_MSG_RESULT([$_am_result]) rm -f confinc confmf ]) # Fake the existence of programs that GNU maintainers use. -*- Autoconf -*- # Copyright (C) 1997-2017 Free Software Foundation, Inc. # # This file is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, # with or without modifications, as long as this notice is preserved. # AM_MISSING_PROG(NAME, PROGRAM) # ------------------------------ AC_DEFUN([AM_MISSING_PROG], [AC_REQUIRE([AM_MISSING_HAS_RUN]) $1=${$1-"${am_missing_run}$2"} AC_SUBST($1)]) # AM_MISSING_HAS_RUN # ------------------ # Define MISSING if not defined so far and test if it is modern enough. # If it is, set am_missing_run to use it, otherwise, to nothing. AC_DEFUN([AM_MISSING_HAS_RUN], [AC_REQUIRE([AM_AUX_DIR_EXPAND])dnl AC_REQUIRE_AUX_FILE([missing])dnl if test x"${MISSING+set}" != xset; then case $am_aux_dir in *\ * | *\ *) MISSING="\${SHELL} \"$am_aux_dir/missing\"" ;; *) MISSING="\${SHELL} $am_aux_dir/missing" ;; esac fi # Use eval to expand $SHELL if eval "$MISSING --is-lightweight"; then am_missing_run="$MISSING " else am_missing_run= AC_MSG_WARN(['missing' script is too old or missing]) fi ]) # Helper functions for option handling. -*- Autoconf -*- # Copyright (C) 2001-2017 Free Software Foundation, Inc. # # This file is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, # with or without modifications, as long as this notice is preserved. # _AM_MANGLE_OPTION(NAME) # ----------------------- AC_DEFUN([_AM_MANGLE_OPTION], [[_AM_OPTION_]m4_bpatsubst($1, [[^a-zA-Z0-9_]], [_])]) # _AM_SET_OPTION(NAME) # -------------------- # Set option NAME. Presently that only means defining a flag for this option. AC_DEFUN([_AM_SET_OPTION], [m4_define(_AM_MANGLE_OPTION([$1]), [1])]) # _AM_SET_OPTIONS(OPTIONS) # ------------------------ # OPTIONS is a space-separated list of Automake options. AC_DEFUN([_AM_SET_OPTIONS], [m4_foreach_w([_AM_Option], [$1], [_AM_SET_OPTION(_AM_Option)])]) # _AM_IF_OPTION(OPTION, IF-SET, [IF-NOT-SET]) # ------------------------------------------- # Execute IF-SET if OPTION is set, IF-NOT-SET otherwise. AC_DEFUN([_AM_IF_OPTION], [m4_ifset(_AM_MANGLE_OPTION([$1]), [$2], [$3])]) # Copyright (C) 1999-2017 Free Software Foundation, Inc. # # This file is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, # with or without modifications, as long as this notice is preserved. # _AM_PROG_CC_C_O # --------------- # Like AC_PROG_CC_C_O, but changed for automake. We rewrite AC_PROG_CC # to automatically call this. AC_DEFUN([_AM_PROG_CC_C_O], [AC_REQUIRE([AM_AUX_DIR_EXPAND])dnl AC_REQUIRE_AUX_FILE([compile])dnl AC_LANG_PUSH([C])dnl AC_CACHE_CHECK( [whether $CC understands -c and -o together], [am_cv_prog_cc_c_o], [AC_LANG_CONFTEST([AC_LANG_PROGRAM([])]) # Make sure it works both with $CC and with simple cc. # Following AC_PROG_CC_C_O, we do the test twice because some # compilers refuse to overwrite an existing .o file with -o, # though they will create one. am_cv_prog_cc_c_o=yes for am_i in 1 2; do if AM_RUN_LOG([$CC -c conftest.$ac_ext -o conftest2.$ac_objext]) \ && test -f conftest2.$ac_objext; then : OK else am_cv_prog_cc_c_o=no break fi done rm -f core conftest* unset am_i]) if test "$am_cv_prog_cc_c_o" != yes; then # Losing compiler, so override with the script. # FIXME: It is wrong to rewrite CC. # But if we don't then we get into trouble of one sort or another. # A longer-term fix would be to have automake use am__CC in this case, # and then we could set am__CC="\$(top_srcdir)/compile \$(CC)" CC="$am_aux_dir/compile $CC" fi AC_LANG_POP([C])]) # For backward compatibility. AC_DEFUN_ONCE([AM_PROG_CC_C_O], [AC_REQUIRE([AC_PROG_CC])]) # Copyright (C) 2001-2017 Free Software Foundation, Inc. # # This file is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, # with or without modifications, as long as this notice is preserved. # AM_RUN_LOG(COMMAND) # ------------------- # Run COMMAND, save the exit status in ac_status, and log it. # (This has been adapted from Autoconf's _AC_RUN_LOG macro.) AC_DEFUN([AM_RUN_LOG], [{ echo "$as_me:$LINENO: $1" >&AS_MESSAGE_LOG_FD ($1) >&AS_MESSAGE_LOG_FD 2>&AS_MESSAGE_LOG_FD ac_status=$? echo "$as_me:$LINENO: \$? = $ac_status" >&AS_MESSAGE_LOG_FD (exit $ac_status); }]) # Check to make sure that the build environment is sane. -*- Autoconf -*- # Copyright (C) 1996-2017 Free Software Foundation, Inc. # # This file is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, # with or without modifications, as long as this notice is preserved. # AM_SANITY_CHECK # --------------- AC_DEFUN([AM_SANITY_CHECK], [AC_MSG_CHECKING([whether build environment is sane]) # Reject unsafe characters in $srcdir or the absolute working directory # name. Accept space and tab only in the latter. am_lf=' ' case `pwd` in *[[\\\"\#\$\&\'\`$am_lf]]*) AC_MSG_ERROR([unsafe absolute working directory name]);; esac case $srcdir in *[[\\\"\#\$\&\'\`$am_lf\ \ ]]*) AC_MSG_ERROR([unsafe srcdir value: '$srcdir']);; esac # Do 'set' in a subshell so we don't clobber the current shell's # arguments. Must try -L first in case configure is actually a # symlink; some systems play weird games with the mod time of symlinks # (eg FreeBSD returns the mod time of the symlink's containing # directory). if ( am_has_slept=no for am_try in 1 2; do echo "timestamp, slept: $am_has_slept" > conftest.file set X `ls -Lt "$srcdir/configure" conftest.file 2> /dev/null` if test "$[*]" = "X"; then # -L didn't work. set X `ls -t "$srcdir/configure" conftest.file` fi if test "$[*]" != "X $srcdir/configure conftest.file" \ && test "$[*]" != "X conftest.file $srcdir/configure"; then # If neither matched, then we have a broken ls. This can happen # if, for instance, CONFIG_SHELL is bash and it inherits a # broken ls alias from the environment. This has actually # happened. Such a system could not be considered "sane". AC_MSG_ERROR([ls -t appears to fail. Make sure there is not a broken alias in your environment]) fi if test "$[2]" = conftest.file || test $am_try -eq 2; then break fi # Just in case. sleep 1 am_has_slept=yes done test "$[2]" = conftest.file ) then # Ok. : else AC_MSG_ERROR([newly created file is older than distributed files! Check your system clock]) fi AC_MSG_RESULT([yes]) # If we didn't sleep, we still need to ensure time stamps of config.status and # generated files are strictly newer. am_sleep_pid= if grep 'slept: no' conftest.file >/dev/null 2>&1; then ( sleep 1 ) & am_sleep_pid=$! fi AC_CONFIG_COMMANDS_PRE( [AC_MSG_CHECKING([that generated files are newer than configure]) if test -n "$am_sleep_pid"; then # Hide warnings about reused PIDs. wait $am_sleep_pid 2>/dev/null fi AC_MSG_RESULT([done])]) rm -f conftest.file ]) # Copyright (C) 2009-2017 Free Software Foundation, Inc. # # This file is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, # with or without modifications, as long as this notice is preserved. # AM_SILENT_RULES([DEFAULT]) # -------------------------- # Enable less verbose build rules; with the default set to DEFAULT # ("yes" being less verbose, "no" or empty being verbose). AC_DEFUN([AM_SILENT_RULES], [AC_ARG_ENABLE([silent-rules], [dnl AS_HELP_STRING( [--enable-silent-rules], [less verbose build output (undo: "make V=1")]) AS_HELP_STRING( [--disable-silent-rules], [verbose build output (undo: "make V=0")])dnl ]) case $enable_silent_rules in @%:@ ((( yes) AM_DEFAULT_VERBOSITY=0;; no) AM_DEFAULT_VERBOSITY=1;; *) AM_DEFAULT_VERBOSITY=m4_if([$1], [yes], [0], [1]);; esac dnl dnl A few 'make' implementations (e.g., NonStop OS and NextStep) dnl do not support nested variable expansions. dnl See automake bug#9928 and bug#10237. am_make=${MAKE-make} AC_CACHE_CHECK([whether $am_make supports nested variables], [am_cv_make_support_nested_variables], [if AS_ECHO([['TRUE=$(BAR$(V)) BAR0=false BAR1=true V=1 am__doit: @$(TRUE) .PHONY: am__doit']]) | $am_make -f - >/dev/null 2>&1; then am_cv_make_support_nested_variables=yes else am_cv_make_support_nested_variables=no fi]) if test $am_cv_make_support_nested_variables = yes; then dnl Using '$V' instead of '$(V)' breaks IRIX make. AM_V='$(V)' AM_DEFAULT_V='$(AM_DEFAULT_VERBOSITY)' else AM_V=$AM_DEFAULT_VERBOSITY AM_DEFAULT_V=$AM_DEFAULT_VERBOSITY fi AC_SUBST([AM_V])dnl AM_SUBST_NOTMAKE([AM_V])dnl AC_SUBST([AM_DEFAULT_V])dnl AM_SUBST_NOTMAKE([AM_DEFAULT_V])dnl AC_SUBST([AM_DEFAULT_VERBOSITY])dnl AM_BACKSLASH='\' AC_SUBST([AM_BACKSLASH])dnl _AM_SUBST_NOTMAKE([AM_BACKSLASH])dnl ]) # Copyright (C) 2001-2017 Free Software Foundation, Inc. # # This file is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, # with or without modifications, as long as this notice is preserved. # AM_PROG_INSTALL_STRIP # --------------------- # One issue with vendor 'install' (even GNU) is that you can't # specify the program used to strip binaries. This is especially # annoying in cross-compiling environments, where the build's strip # is unlikely to handle the host's binaries. # Fortunately install-sh will honor a STRIPPROG variable, so we # always use install-sh in "make install-strip", and initialize # STRIPPROG with the value of the STRIP variable (set by the user). AC_DEFUN([AM_PROG_INSTALL_STRIP], [AC_REQUIRE([AM_PROG_INSTALL_SH])dnl # Installed binaries are usually stripped using 'strip' when the user # run "make install-strip". However 'strip' might not be the right # tool to use in cross-compilation environments, therefore Automake # will honor the 'STRIP' environment variable to overrule this program. dnl Don't test for $cross_compiling = yes, because it might be 'maybe'. if test "$cross_compiling" != no; then AC_CHECK_TOOL([STRIP], [strip], :) fi INSTALL_STRIP_PROGRAM="\$(install_sh) -c -s" AC_SUBST([INSTALL_STRIP_PROGRAM])]) # Copyright (C) 2006-2017 Free Software Foundation, Inc. # # This file is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, # with or without modifications, as long as this notice is preserved. # _AM_SUBST_NOTMAKE(VARIABLE) # --------------------------- # Prevent Automake from outputting VARIABLE = @VARIABLE@ in Makefile.in. # This macro is traced by Automake. AC_DEFUN([_AM_SUBST_NOTMAKE]) # AM_SUBST_NOTMAKE(VARIABLE) # -------------------------- # Public sister of _AM_SUBST_NOTMAKE. AC_DEFUN([AM_SUBST_NOTMAKE], [_AM_SUBST_NOTMAKE($@)]) # Check how to create a tarball. -*- Autoconf -*- # Copyright (C) 2004-2017 Free Software Foundation, Inc. # # This file is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, # with or without modifications, as long as this notice is preserved. # _AM_PROG_TAR(FORMAT) # -------------------- # Check how to create a tarball in format FORMAT. # FORMAT should be one of 'v7', 'ustar', or 'pax'. # # Substitute a variable $(am__tar) that is a command # writing to stdout a FORMAT-tarball containing the directory # $tardir. # tardir=directory && $(am__tar) > result.tar # # Substitute a variable $(am__untar) that extract such # a tarball read from stdin. # $(am__untar) < result.tar # AC_DEFUN([_AM_PROG_TAR], [# Always define AMTAR for backward compatibility. Yes, it's still used # in the wild :-( We should find a proper way to deprecate it ... AC_SUBST([AMTAR], ['$${TAR-tar}']) # We'll loop over all known methods to create a tar archive until one works. _am_tools='gnutar m4_if([$1], [ustar], [plaintar]) pax cpio none' m4_if([$1], [v7], [am__tar='$${TAR-tar} chof - "$$tardir"' am__untar='$${TAR-tar} xf -'], [m4_case([$1], [ustar], [# The POSIX 1988 'ustar' format is defined with fixed-size fields. # There is notably a 21 bits limit for the UID and the GID. In fact, # the 'pax' utility can hang on bigger UID/GID (see automake bug#8343 # and bug#13588). am_max_uid=2097151 # 2^21 - 1 am_max_gid=$am_max_uid # The $UID and $GID variables are not portable, so we need to resort # to the POSIX-mandated id(1) utility. Errors in the 'id' calls # below are definitely unexpected, so allow the users to see them # (that is, avoid stderr redirection). am_uid=`id -u || echo unknown` am_gid=`id -g || echo unknown` AC_MSG_CHECKING([whether UID '$am_uid' is supported by ustar format]) if test $am_uid -le $am_max_uid; then AC_MSG_RESULT([yes]) else AC_MSG_RESULT([no]) _am_tools=none fi AC_MSG_CHECKING([whether GID '$am_gid' is supported by ustar format]) if test $am_gid -le $am_max_gid; then AC_MSG_RESULT([yes]) else AC_MSG_RESULT([no]) _am_tools=none fi], [pax], [], [m4_fatal([Unknown tar format])]) AC_MSG_CHECKING([how to create a $1 tar archive]) # Go ahead even if we have the value already cached. We do so because we # need to set the values for the 'am__tar' and 'am__untar' variables. _am_tools=${am_cv_prog_tar_$1-$_am_tools} for _am_tool in $_am_tools; do case $_am_tool in gnutar) for _am_tar in tar gnutar gtar; do AM_RUN_LOG([$_am_tar --version]) && break done am__tar="$_am_tar --format=m4_if([$1], [pax], [posix], [$1]) -chf - "'"$$tardir"' am__tar_="$_am_tar --format=m4_if([$1], [pax], [posix], [$1]) -chf - "'"$tardir"' am__untar="$_am_tar -xf -" ;; plaintar) # Must skip GNU tar: if it does not support --format= it doesn't create # ustar tarball either. (tar --version) >/dev/null 2>&1 && continue am__tar='tar chf - "$$tardir"' am__tar_='tar chf - "$tardir"' am__untar='tar xf -' ;; pax) am__tar='pax -L -x $1 -w "$$tardir"' am__tar_='pax -L -x $1 -w "$tardir"' am__untar='pax -r' ;; cpio) am__tar='find "$$tardir" -print | cpio -o -H $1 -L' am__tar_='find "$tardir" -print | cpio -o -H $1 -L' am__untar='cpio -i -H $1 -d' ;; none) am__tar=false am__tar_=false am__untar=false ;; esac # If the value was cached, stop now. We just wanted to have am__tar # and am__untar set. test -n "${am_cv_prog_tar_$1}" && break # tar/untar a dummy directory, and stop if the command works. rm -rf conftest.dir mkdir conftest.dir echo GrepMe > conftest.dir/file AM_RUN_LOG([tardir=conftest.dir && eval $am__tar_ >conftest.tar]) rm -rf conftest.dir if test -s conftest.tar; then AM_RUN_LOG([$am__untar /dev/null 2>&1 && break fi done rm -rf conftest.dir AC_CACHE_VAL([am_cv_prog_tar_$1], [am_cv_prog_tar_$1=$_am_tool]) AC_MSG_RESULT([$am_cv_prog_tar_$1])]) AC_SUBST([am__tar]) AC_SUBST([am__untar]) ]) # _AM_PROG_TAR m4_include([acinclude.m4]) heimdal-7.5.0/lib/libedit/COPYING0000644000175000017500000000311713026237312014470 0ustar niknikCopyright (c) 1992, 1993 The Regents of the University of California. All rights reserved. This code is derived from software contributed to Berkeley by Christos Zoulas of Cornell University. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the University nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. heimdal-7.5.0/lib/libedit/THANKS0000644000175000017500000000006513026237312014347 0ustar niknikThanks to the NetBSD Project maintainers of libedit! heimdal-7.5.0/lib/libedit/compile0000755000175000017500000001632613212444505015022 0ustar niknik#! /bin/sh # Wrapper for compilers which do not understand '-c -o'. scriptversion=2016-01-11.22; # UTC # Copyright (C) 1999-2017 Free Software Foundation, Inc. # Written by Tom Tromey . # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2, or (at your option) # any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see . # As a special exception to the GNU General Public License, if you # distribute this file as part of a program that contains a # configuration script generated by Autoconf, you may include it under # the same distribution terms that you use for the rest of that program. # This file is maintained in Automake, please report # bugs to or send patches to # . nl=' ' # We need space, tab and new line, in precisely that order. Quoting is # there to prevent tools from complaining about whitespace usage. IFS=" "" $nl" file_conv= # func_file_conv build_file lazy # Convert a $build file to $host form and store it in $file # Currently only supports Windows hosts. If the determined conversion # type is listed in (the comma separated) LAZY, no conversion will # take place. func_file_conv () { file=$1 case $file in / | /[!/]*) # absolute file, and not a UNC file if test -z "$file_conv"; then # lazily determine how to convert abs files case `uname -s` in MINGW*) file_conv=mingw ;; CYGWIN*) file_conv=cygwin ;; *) file_conv=wine ;; esac fi case $file_conv/,$2, in *,$file_conv,*) ;; mingw/*) file=`cmd //C echo "$file " | sed -e 's/"\(.*\) " *$/\1/'` ;; cygwin/*) file=`cygpath -m "$file" || echo "$file"` ;; wine/*) file=`winepath -w "$file" || echo "$file"` ;; esac ;; esac } # func_cl_dashL linkdir # Make cl look for libraries in LINKDIR func_cl_dashL () { func_file_conv "$1" if test -z "$lib_path"; then lib_path=$file else lib_path="$lib_path;$file" fi linker_opts="$linker_opts -LIBPATH:$file" } # func_cl_dashl library # Do a library search-path lookup for cl func_cl_dashl () { lib=$1 found=no save_IFS=$IFS IFS=';' for dir in $lib_path $LIB do IFS=$save_IFS if $shared && test -f "$dir/$lib.dll.lib"; then found=yes lib=$dir/$lib.dll.lib break fi if test -f "$dir/$lib.lib"; then found=yes lib=$dir/$lib.lib break fi if test -f "$dir/lib$lib.a"; then found=yes lib=$dir/lib$lib.a break fi done IFS=$save_IFS if test "$found" != yes; then lib=$lib.lib fi } # func_cl_wrapper cl arg... # Adjust compile command to suit cl func_cl_wrapper () { # Assume a capable shell lib_path= shared=: linker_opts= for arg do if test -n "$eat"; then eat= else case $1 in -o) # configure might choose to run compile as 'compile cc -o foo foo.c'. eat=1 case $2 in *.o | *.[oO][bB][jJ]) func_file_conv "$2" set x "$@" -Fo"$file" shift ;; *) func_file_conv "$2" set x "$@" -Fe"$file" shift ;; esac ;; -I) eat=1 func_file_conv "$2" mingw set x "$@" -I"$file" shift ;; -I*) func_file_conv "${1#-I}" mingw set x "$@" -I"$file" shift ;; -l) eat=1 func_cl_dashl "$2" set x "$@" "$lib" shift ;; -l*) func_cl_dashl "${1#-l}" set x "$@" "$lib" shift ;; -L) eat=1 func_cl_dashL "$2" ;; -L*) func_cl_dashL "${1#-L}" ;; -static) shared=false ;; -Wl,*) arg=${1#-Wl,} save_ifs="$IFS"; IFS=',' for flag in $arg; do IFS="$save_ifs" linker_opts="$linker_opts $flag" done IFS="$save_ifs" ;; -Xlinker) eat=1 linker_opts="$linker_opts $2" ;; -*) set x "$@" "$1" shift ;; *.cc | *.CC | *.cxx | *.CXX | *.[cC]++) func_file_conv "$1" set x "$@" -Tp"$file" shift ;; *.c | *.cpp | *.CPP | *.lib | *.LIB | *.Lib | *.OBJ | *.obj | *.[oO]) func_file_conv "$1" mingw set x "$@" "$file" shift ;; *) set x "$@" "$1" shift ;; esac fi shift done if test -n "$linker_opts"; then linker_opts="-link$linker_opts" fi exec "$@" $linker_opts exit 1 } eat= case $1 in '') echo "$0: No command. Try '$0 --help' for more information." 1>&2 exit 1; ;; -h | --h*) cat <<\EOF Usage: compile [--help] [--version] PROGRAM [ARGS] Wrapper for compilers which do not understand '-c -o'. Remove '-o dest.o' from ARGS, run PROGRAM with the remaining arguments, and rename the output as expected. If you are trying to build a whole package this is not the right script to run: please start by reading the file 'INSTALL'. Report bugs to . EOF exit $? ;; -v | --v*) echo "compile $scriptversion" exit $? ;; cl | *[/\\]cl | cl.exe | *[/\\]cl.exe | \ icl | *[/\\]icl | icl.exe | *[/\\]icl.exe ) func_cl_wrapper "$@" # Doesn't return... ;; esac ofile= cfile= for arg do if test -n "$eat"; then eat= else case $1 in -o) # configure might choose to run compile as 'compile cc -o foo foo.c'. # So we strip '-o arg' only if arg is an object. eat=1 case $2 in *.o | *.obj) ofile=$2 ;; *) set x "$@" -o "$2" shift ;; esac ;; *.c) cfile=$1 set x "$@" "$1" shift ;; *) set x "$@" "$1" shift ;; esac fi shift done if test -z "$ofile" || test -z "$cfile"; then # If no '-o' option was seen then we might have been invoked from a # pattern rule where we don't need one. That is ok -- this is a # normal compilation that the losing compiler can handle. If no # '.c' file was seen then we are probably linking. That is also # ok. exec "$@" fi # Name of file we expect compiler to create. cofile=`echo "$cfile" | sed 's|^.*[\\/]||; s|^[a-zA-Z]:||; s/\.c$/.o/'` # Create the lock directory. # Note: use '[/\\:.-]' here to ensure that we don't use the same name # that we are using for the .o file. Also, base the name on the expected # object file name, since that is what matters with a parallel build. lockdir=`echo "$cofile" | sed -e 's|[/\\:.-]|_|g'`.d while true; do if mkdir "$lockdir" >/dev/null 2>&1; then break fi sleep 1 done # FIXME: race condition here if user kills between mkdir and trap. trap "rmdir '$lockdir'; exit 1" 1 2 15 # Run the compile. "$@" ret=$? if test -f "$cofile"; then test "$cofile" = "$ofile" || mv "$cofile" "$ofile" elif test -f "${cofile}bj"; then test "${cofile}bj" = "$ofile" || mv "${cofile}bj" "$ofile" fi rmdir "$lockdir" exit $ret # Local Variables: # mode: shell-script # sh-indentation: 2 # eval: (add-hook 'write-file-hooks 'time-stamp) # time-stamp-start: "scriptversion=" # time-stamp-format: "%:y-%02m-%02d.%02H" # time-stamp-time-zone: "UTC0" # time-stamp-end: "; # UTC" # End: heimdal-7.5.0/lib/libedit/config.sub0000755000175000017500000010724313212444505015426 0ustar niknik#! /bin/sh # Configuration validation subroutine script. # Copyright 1992-2017 Free Software Foundation, Inc. timestamp='2017-04-02' # This file is free software; you can redistribute it and/or modify it # under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, see . # # As a special exception to the GNU General Public License, if you # distribute this file as part of a program that contains a # configuration script generated by Autoconf, you may include it under # the same distribution terms that you use for the rest of that # program. This Exception is an additional permission under section 7 # of the GNU General Public License, version 3 ("GPLv3"). # Please send patches to . # # Configuration subroutine to validate and canonicalize a configuration type. # Supply the specified configuration type as an argument. # If it is invalid, we print an error message on stderr and exit with code 1. # Otherwise, we print the canonical config type on stdout and succeed. # You can get the latest version of this script from: # http://git.savannah.gnu.org/gitweb/?p=config.git;a=blob_plain;f=config.sub # This file is supposed to be the same for all GNU packages # and recognize all the CPU types, system types and aliases # that are meaningful with *any* GNU software. # Each package is responsible for reporting which valid configurations # it does not support. The user should be able to distinguish # a failure to support a valid configuration from a meaningless # configuration. # The goal of this file is to map all the various variations of a given # machine specification into a single specification in the form: # CPU_TYPE-MANUFACTURER-OPERATING_SYSTEM # or in some cases, the newer four-part form: # CPU_TYPE-MANUFACTURER-KERNEL-OPERATING_SYSTEM # It is wrong to echo any other type of specification. me=`echo "$0" | sed -e 's,.*/,,'` usage="\ Usage: $0 [OPTION] CPU-MFR-OPSYS or ALIAS Canonicalize a configuration name. Operation modes: -h, --help print this help, then exit -t, --time-stamp print date of last modification, then exit -v, --version print version number, then exit Report bugs and patches to ." version="\ GNU config.sub ($timestamp) Copyright 1992-2017 Free Software Foundation, Inc. This is free software; see the source for copying conditions. There is NO warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE." help=" Try \`$me --help' for more information." # Parse command line while test $# -gt 0 ; do case $1 in --time-stamp | --time* | -t ) echo "$timestamp" ; exit ;; --version | -v ) echo "$version" ; exit ;; --help | --h* | -h ) echo "$usage"; exit ;; -- ) # Stop option processing shift; break ;; - ) # Use stdin as input. break ;; -* ) echo "$me: invalid option $1$help" exit 1 ;; *local*) # First pass through any local machine types. echo $1 exit ;; * ) break ;; esac done case $# in 0) echo "$me: missing argument$help" >&2 exit 1;; 1) ;; *) echo "$me: too many arguments$help" >&2 exit 1;; esac # Separate what the user gave into CPU-COMPANY and OS or KERNEL-OS (if any). # Here we must recognize all the valid KERNEL-OS combinations. maybe_os=`echo $1 | sed 's/^\(.*\)-\([^-]*-[^-]*\)$/\2/'` case $maybe_os in nto-qnx* | linux-gnu* | linux-android* | linux-dietlibc | linux-newlib* | \ linux-musl* | linux-uclibc* | uclinux-uclibc* | uclinux-gnu* | kfreebsd*-gnu* | \ knetbsd*-gnu* | netbsd*-gnu* | netbsd*-eabi* | \ kopensolaris*-gnu* | cloudabi*-eabi* | \ storm-chaos* | os2-emx* | rtmk-nova*) os=-$maybe_os basic_machine=`echo $1 | sed 's/^\(.*\)-\([^-]*-[^-]*\)$/\1/'` ;; android-linux) os=-linux-android basic_machine=`echo $1 | sed 's/^\(.*\)-\([^-]*-[^-]*\)$/\1/'`-unknown ;; *) basic_machine=`echo $1 | sed 's/-[^-]*$//'` if [ $basic_machine != $1 ] then os=`echo $1 | sed 's/.*-/-/'` else os=; fi ;; esac ### Let's recognize common machines as not being operating systems so ### that things like config.sub decstation-3100 work. We also ### recognize some manufacturers as not being operating systems, so we ### can provide default operating systems below. case $os in -sun*os*) # Prevent following clause from handling this invalid input. ;; -dec* | -mips* | -sequent* | -encore* | -pc532* | -sgi* | -sony* | \ -att* | -7300* | -3300* | -delta* | -motorola* | -sun[234]* | \ -unicom* | -ibm* | -next | -hp | -isi* | -apollo | -altos* | \ -convergent* | -ncr* | -news | -32* | -3600* | -3100* | -hitachi* |\ -c[123]* | -convex* | -sun | -crds | -omron* | -dg | -ultra | -tti* | \ -harris | -dolphin | -highlevel | -gould | -cbm | -ns | -masscomp | \ -apple | -axis | -knuth | -cray | -microblaze*) os= basic_machine=$1 ;; -bluegene*) os=-cnk ;; -sim | -cisco | -oki | -wec | -winbond) os= basic_machine=$1 ;; -scout) ;; -wrs) os=-vxworks basic_machine=$1 ;; -chorusos*) os=-chorusos basic_machine=$1 ;; -chorusrdb) os=-chorusrdb basic_machine=$1 ;; -hiux*) os=-hiuxwe2 ;; -sco6) os=-sco5v6 basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'` ;; -sco5) os=-sco3.2v5 basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'` ;; -sco4) os=-sco3.2v4 basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'` ;; -sco3.2.[4-9]*) os=`echo $os | sed -e 's/sco3.2./sco3.2v/'` basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'` ;; -sco3.2v[4-9]*) # Don't forget version if it is 3.2v4 or newer. basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'` ;; -sco5v6*) # Don't forget version if it is 3.2v4 or newer. basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'` ;; -sco*) os=-sco3.2v2 basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'` ;; -udk*) basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'` ;; -isc) os=-isc2.2 basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'` ;; -clix*) basic_machine=clipper-intergraph ;; -isc*) basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'` ;; -lynx*178) os=-lynxos178 ;; -lynx*5) os=-lynxos5 ;; -lynx*) os=-lynxos ;; -ptx*) basic_machine=`echo $1 | sed -e 's/86-.*/86-sequent/'` ;; -windowsnt*) os=`echo $os | sed -e 's/windowsnt/winnt/'` ;; -psos*) os=-psos ;; -mint | -mint[0-9]*) basic_machine=m68k-atari os=-mint ;; esac # Decode aliases for certain CPU-COMPANY combinations. case $basic_machine in # Recognize the basic CPU types without company name. # Some are omitted here because they have special meanings below. 1750a | 580 \ | a29k \ | aarch64 | aarch64_be \ | alpha | alphaev[4-8] | alphaev56 | alphaev6[78] | alphapca5[67] \ | alpha64 | alpha64ev[4-8] | alpha64ev56 | alpha64ev6[78] | alpha64pca5[67] \ | am33_2.0 \ | arc | arceb \ | arm | arm[bl]e | arme[lb] | armv[2-8] | armv[3-8][lb] | armv7[arm] \ | avr | avr32 \ | ba \ | be32 | be64 \ | bfin \ | c4x | c8051 | clipper \ | d10v | d30v | dlx | dsp16xx \ | e2k | epiphany \ | fido | fr30 | frv | ft32 \ | h8300 | h8500 | hppa | hppa1.[01] | hppa2.0 | hppa2.0[nw] | hppa64 \ | hexagon \ | i370 | i860 | i960 | ia16 | ia64 \ | ip2k | iq2000 \ | k1om \ | le32 | le64 \ | lm32 \ | m32c | m32r | m32rle | m68000 | m68k | m88k \ | maxq | mb | microblaze | microblazeel | mcore | mep | metag \ | mips | mipsbe | mipseb | mipsel | mipsle \ | mips16 \ | mips64 | mips64el \ | mips64octeon | mips64octeonel \ | mips64orion | mips64orionel \ | mips64r5900 | mips64r5900el \ | mips64vr | mips64vrel \ | mips64vr4100 | mips64vr4100el \ | mips64vr4300 | mips64vr4300el \ | mips64vr5000 | mips64vr5000el \ | mips64vr5900 | mips64vr5900el \ | mipsisa32 | mipsisa32el \ | mipsisa32r2 | mipsisa32r2el \ | mipsisa32r6 | mipsisa32r6el \ | mipsisa64 | mipsisa64el \ | mipsisa64r2 | mipsisa64r2el \ | mipsisa64r6 | mipsisa64r6el \ | mipsisa64sb1 | mipsisa64sb1el \ | mipsisa64sr71k | mipsisa64sr71kel \ | mipsr5900 | mipsr5900el \ | mipstx39 | mipstx39el \ | mn10200 | mn10300 \ | moxie \ | mt \ | msp430 \ | nds32 | nds32le | nds32be \ | nios | nios2 | nios2eb | nios2el \ | ns16k | ns32k \ | open8 | or1k | or1knd | or32 \ | pdp10 | pdp11 | pj | pjl \ | powerpc | powerpc64 | powerpc64le | powerpcle \ | pru \ | pyramid \ | riscv32 | riscv64 \ | rl78 | rx \ | score \ | sh | sh[1234] | sh[24]a | sh[24]aeb | sh[23]e | sh[234]eb | sheb | shbe | shle | sh[1234]le | sh3ele \ | sh64 | sh64le \ | sparc | sparc64 | sparc64b | sparc64v | sparc86x | sparclet | sparclite \ | sparcv8 | sparcv9 | sparcv9b | sparcv9v \ | spu \ | tahoe | tic4x | tic54x | tic55x | tic6x | tic80 | tron \ | ubicom32 \ | v850 | v850e | v850e1 | v850e2 | v850es | v850e2v3 \ | visium \ | wasm32 \ | we32k \ | x86 | xc16x | xstormy16 | xtensa \ | z8k | z80) basic_machine=$basic_machine-unknown ;; c54x) basic_machine=tic54x-unknown ;; c55x) basic_machine=tic55x-unknown ;; c6x) basic_machine=tic6x-unknown ;; leon|leon[3-9]) basic_machine=sparc-$basic_machine ;; m6811 | m68hc11 | m6812 | m68hc12 | m68hcs12x | nvptx | picochip) basic_machine=$basic_machine-unknown os=-none ;; m88110 | m680[12346]0 | m683?2 | m68360 | m5200 | v70 | w65 | z8k) ;; ms1) basic_machine=mt-unknown ;; strongarm | thumb | xscale) basic_machine=arm-unknown ;; xgate) basic_machine=$basic_machine-unknown os=-none ;; xscaleeb) basic_machine=armeb-unknown ;; xscaleel) basic_machine=armel-unknown ;; # We use `pc' rather than `unknown' # because (1) that's what they normally are, and # (2) the word "unknown" tends to confuse beginning users. i*86 | x86_64) basic_machine=$basic_machine-pc ;; # Object if more than one company name word. *-*-*) echo Invalid configuration \`$1\': machine \`$basic_machine\' not recognized 1>&2 exit 1 ;; # Recognize the basic CPU types with company name. 580-* \ | a29k-* \ | aarch64-* | aarch64_be-* \ | alpha-* | alphaev[4-8]-* | alphaev56-* | alphaev6[78]-* \ | alpha64-* | alpha64ev[4-8]-* | alpha64ev56-* | alpha64ev6[78]-* \ | alphapca5[67]-* | alpha64pca5[67]-* | arc-* | arceb-* \ | arm-* | armbe-* | armle-* | armeb-* | armv*-* \ | avr-* | avr32-* \ | ba-* \ | be32-* | be64-* \ | bfin-* | bs2000-* \ | c[123]* | c30-* | [cjt]90-* | c4x-* \ | c8051-* | clipper-* | craynv-* | cydra-* \ | d10v-* | d30v-* | dlx-* \ | e2k-* | elxsi-* \ | f30[01]-* | f700-* | fido-* | fr30-* | frv-* | fx80-* \ | h8300-* | h8500-* \ | hppa-* | hppa1.[01]-* | hppa2.0-* | hppa2.0[nw]-* | hppa64-* \ | hexagon-* \ | i*86-* | i860-* | i960-* | ia16-* | ia64-* \ | ip2k-* | iq2000-* \ | k1om-* \ | le32-* | le64-* \ | lm32-* \ | m32c-* | m32r-* | m32rle-* \ | m68000-* | m680[012346]0-* | m68360-* | m683?2-* | m68k-* \ | m88110-* | m88k-* | maxq-* | mcore-* | metag-* \ | microblaze-* | microblazeel-* \ | mips-* | mipsbe-* | mipseb-* | mipsel-* | mipsle-* \ | mips16-* \ | mips64-* | mips64el-* \ | mips64octeon-* | mips64octeonel-* \ | mips64orion-* | mips64orionel-* \ | mips64r5900-* | mips64r5900el-* \ | mips64vr-* | mips64vrel-* \ | mips64vr4100-* | mips64vr4100el-* \ | mips64vr4300-* | mips64vr4300el-* \ | mips64vr5000-* | mips64vr5000el-* \ | mips64vr5900-* | mips64vr5900el-* \ | mipsisa32-* | mipsisa32el-* \ | mipsisa32r2-* | mipsisa32r2el-* \ | mipsisa32r6-* | mipsisa32r6el-* \ | mipsisa64-* | mipsisa64el-* \ | mipsisa64r2-* | mipsisa64r2el-* \ | mipsisa64r6-* | mipsisa64r6el-* \ | mipsisa64sb1-* | mipsisa64sb1el-* \ | mipsisa64sr71k-* | mipsisa64sr71kel-* \ | mipsr5900-* | mipsr5900el-* \ | mipstx39-* | mipstx39el-* \ | mmix-* \ | mt-* \ | msp430-* \ | nds32-* | nds32le-* | nds32be-* \ | nios-* | nios2-* | nios2eb-* | nios2el-* \ | none-* | np1-* | ns16k-* | ns32k-* \ | open8-* \ | or1k*-* \ | orion-* \ | pdp10-* | pdp11-* | pj-* | pjl-* | pn-* | power-* \ | powerpc-* | powerpc64-* | powerpc64le-* | powerpcle-* \ | pru-* \ | pyramid-* \ | riscv32-* | riscv64-* \ | rl78-* | romp-* | rs6000-* | rx-* \ | sh-* | sh[1234]-* | sh[24]a-* | sh[24]aeb-* | sh[23]e-* | sh[34]eb-* | sheb-* | shbe-* \ | shle-* | sh[1234]le-* | sh3ele-* | sh64-* | sh64le-* \ | sparc-* | sparc64-* | sparc64b-* | sparc64v-* | sparc86x-* | sparclet-* \ | sparclite-* \ | sparcv8-* | sparcv9-* | sparcv9b-* | sparcv9v-* | sv1-* | sx*-* \ | tahoe-* \ | tic30-* | tic4x-* | tic54x-* | tic55x-* | tic6x-* | tic80-* \ | tile*-* \ | tron-* \ | ubicom32-* \ | v850-* | v850e-* | v850e1-* | v850es-* | v850e2-* | v850e2v3-* \ | vax-* \ | visium-* \ | wasm32-* \ | we32k-* \ | x86-* | x86_64-* | xc16x-* | xps100-* \ | xstormy16-* | xtensa*-* \ | ymp-* \ | z8k-* | z80-*) ;; # Recognize the basic CPU types without company name, with glob match. xtensa*) basic_machine=$basic_machine-unknown ;; # Recognize the various machine names and aliases which stand # for a CPU type and a company and sometimes even an OS. 386bsd) basic_machine=i386-unknown os=-bsd ;; 3b1 | 7300 | 7300-att | att-7300 | pc7300 | safari | unixpc) basic_machine=m68000-att ;; 3b*) basic_machine=we32k-att ;; a29khif) basic_machine=a29k-amd os=-udi ;; abacus) basic_machine=abacus-unknown ;; adobe68k) basic_machine=m68010-adobe os=-scout ;; alliant | fx80) basic_machine=fx80-alliant ;; altos | altos3068) basic_machine=m68k-altos ;; am29k) basic_machine=a29k-none os=-bsd ;; amd64) basic_machine=x86_64-pc ;; amd64-*) basic_machine=x86_64-`echo $basic_machine | sed 's/^[^-]*-//'` ;; amdahl) basic_machine=580-amdahl os=-sysv ;; amiga | amiga-*) basic_machine=m68k-unknown ;; amigaos | amigados) basic_machine=m68k-unknown os=-amigaos ;; amigaunix | amix) basic_machine=m68k-unknown os=-sysv4 ;; apollo68) basic_machine=m68k-apollo os=-sysv ;; apollo68bsd) basic_machine=m68k-apollo os=-bsd ;; aros) basic_machine=i386-pc os=-aros ;; asmjs) basic_machine=asmjs-unknown ;; aux) basic_machine=m68k-apple os=-aux ;; balance) basic_machine=ns32k-sequent os=-dynix ;; blackfin) basic_machine=bfin-unknown os=-linux ;; blackfin-*) basic_machine=bfin-`echo $basic_machine | sed 's/^[^-]*-//'` os=-linux ;; bluegene*) basic_machine=powerpc-ibm os=-cnk ;; c54x-*) basic_machine=tic54x-`echo $basic_machine | sed 's/^[^-]*-//'` ;; c55x-*) basic_machine=tic55x-`echo $basic_machine | sed 's/^[^-]*-//'` ;; c6x-*) basic_machine=tic6x-`echo $basic_machine | sed 's/^[^-]*-//'` ;; c90) basic_machine=c90-cray os=-unicos ;; cegcc) basic_machine=arm-unknown os=-cegcc ;; convex-c1) basic_machine=c1-convex os=-bsd ;; convex-c2) basic_machine=c2-convex os=-bsd ;; convex-c32) basic_machine=c32-convex os=-bsd ;; convex-c34) basic_machine=c34-convex os=-bsd ;; convex-c38) basic_machine=c38-convex os=-bsd ;; cray | j90) basic_machine=j90-cray os=-unicos ;; craynv) basic_machine=craynv-cray os=-unicosmp ;; cr16 | cr16-*) basic_machine=cr16-unknown os=-elf ;; crds | unos) basic_machine=m68k-crds ;; crisv32 | crisv32-* | etraxfs*) basic_machine=crisv32-axis ;; cris | cris-* | etrax*) basic_machine=cris-axis ;; crx) basic_machine=crx-unknown os=-elf ;; da30 | da30-*) basic_machine=m68k-da30 ;; decstation | decstation-3100 | pmax | pmax-* | pmin | dec3100 | decstatn) basic_machine=mips-dec ;; decsystem10* | dec10*) basic_machine=pdp10-dec os=-tops10 ;; decsystem20* | dec20*) basic_machine=pdp10-dec os=-tops20 ;; delta | 3300 | motorola-3300 | motorola-delta \ | 3300-motorola | delta-motorola) basic_machine=m68k-motorola ;; delta88) basic_machine=m88k-motorola os=-sysv3 ;; dicos) basic_machine=i686-pc os=-dicos ;; djgpp) basic_machine=i586-pc os=-msdosdjgpp ;; dpx20 | dpx20-*) basic_machine=rs6000-bull os=-bosx ;; dpx2* | dpx2*-bull) basic_machine=m68k-bull os=-sysv3 ;; e500v[12]) basic_machine=powerpc-unknown os=$os"spe" ;; e500v[12]-*) basic_machine=powerpc-`echo $basic_machine | sed 's/^[^-]*-//'` os=$os"spe" ;; ebmon29k) basic_machine=a29k-amd os=-ebmon ;; elxsi) basic_machine=elxsi-elxsi os=-bsd ;; encore | umax | mmax) basic_machine=ns32k-encore ;; es1800 | OSE68k | ose68k | ose | OSE) basic_machine=m68k-ericsson os=-ose ;; fx2800) basic_machine=i860-alliant ;; genix) basic_machine=ns32k-ns ;; gmicro) basic_machine=tron-gmicro os=-sysv ;; go32) basic_machine=i386-pc os=-go32 ;; h3050r* | hiux*) basic_machine=hppa1.1-hitachi os=-hiuxwe2 ;; h8300hms) basic_machine=h8300-hitachi os=-hms ;; h8300xray) basic_machine=h8300-hitachi os=-xray ;; h8500hms) basic_machine=h8500-hitachi os=-hms ;; harris) basic_machine=m88k-harris os=-sysv3 ;; hp300-*) basic_machine=m68k-hp ;; hp300bsd) basic_machine=m68k-hp os=-bsd ;; hp300hpux) basic_machine=m68k-hp os=-hpux ;; hp3k9[0-9][0-9] | hp9[0-9][0-9]) basic_machine=hppa1.0-hp ;; hp9k2[0-9][0-9] | hp9k31[0-9]) basic_machine=m68000-hp ;; hp9k3[2-9][0-9]) basic_machine=m68k-hp ;; hp9k6[0-9][0-9] | hp6[0-9][0-9]) basic_machine=hppa1.0-hp ;; hp9k7[0-79][0-9] | hp7[0-79][0-9]) basic_machine=hppa1.1-hp ;; hp9k78[0-9] | hp78[0-9]) # FIXME: really hppa2.0-hp basic_machine=hppa1.1-hp ;; hp9k8[67]1 | hp8[67]1 | hp9k80[24] | hp80[24] | hp9k8[78]9 | hp8[78]9 | hp9k893 | hp893) # FIXME: really hppa2.0-hp basic_machine=hppa1.1-hp ;; hp9k8[0-9][13679] | hp8[0-9][13679]) basic_machine=hppa1.1-hp ;; hp9k8[0-9][0-9] | hp8[0-9][0-9]) basic_machine=hppa1.0-hp ;; hppa-next) os=-nextstep3 ;; hppaosf) basic_machine=hppa1.1-hp os=-osf ;; hppro) basic_machine=hppa1.1-hp os=-proelf ;; i370-ibm* | ibm*) basic_machine=i370-ibm ;; i*86v32) basic_machine=`echo $1 | sed -e 's/86.*/86-pc/'` os=-sysv32 ;; i*86v4*) basic_machine=`echo $1 | sed -e 's/86.*/86-pc/'` os=-sysv4 ;; i*86v) basic_machine=`echo $1 | sed -e 's/86.*/86-pc/'` os=-sysv ;; i*86sol2) basic_machine=`echo $1 | sed -e 's/86.*/86-pc/'` os=-solaris2 ;; i386mach) basic_machine=i386-mach os=-mach ;; i386-vsta | vsta) basic_machine=i386-unknown os=-vsta ;; iris | iris4d) basic_machine=mips-sgi case $os in -irix*) ;; *) os=-irix4 ;; esac ;; isi68 | isi) basic_machine=m68k-isi os=-sysv ;; leon-*|leon[3-9]-*) basic_machine=sparc-`echo $basic_machine | sed 's/-.*//'` ;; m68knommu) basic_machine=m68k-unknown os=-linux ;; m68knommu-*) basic_machine=m68k-`echo $basic_machine | sed 's/^[^-]*-//'` os=-linux ;; m88k-omron*) basic_machine=m88k-omron ;; magnum | m3230) basic_machine=mips-mips os=-sysv ;; merlin) basic_machine=ns32k-utek os=-sysv ;; microblaze*) basic_machine=microblaze-xilinx ;; mingw64) basic_machine=x86_64-pc os=-mingw64 ;; mingw32) basic_machine=i686-pc os=-mingw32 ;; mingw32ce) basic_machine=arm-unknown os=-mingw32ce ;; miniframe) basic_machine=m68000-convergent ;; *mint | -mint[0-9]* | *MiNT | *MiNT[0-9]*) basic_machine=m68k-atari os=-mint ;; mips3*-*) basic_machine=`echo $basic_machine | sed -e 's/mips3/mips64/'` ;; mips3*) basic_machine=`echo $basic_machine | sed -e 's/mips3/mips64/'`-unknown ;; monitor) basic_machine=m68k-rom68k os=-coff ;; morphos) basic_machine=powerpc-unknown os=-morphos ;; moxiebox) basic_machine=moxie-unknown os=-moxiebox ;; msdos) basic_machine=i386-pc os=-msdos ;; ms1-*) basic_machine=`echo $basic_machine | sed -e 's/ms1-/mt-/'` ;; msys) basic_machine=i686-pc os=-msys ;; mvs) basic_machine=i370-ibm os=-mvs ;; nacl) basic_machine=le32-unknown os=-nacl ;; ncr3000) basic_machine=i486-ncr os=-sysv4 ;; netbsd386) basic_machine=i386-unknown os=-netbsd ;; netwinder) basic_machine=armv4l-rebel os=-linux ;; news | news700 | news800 | news900) basic_machine=m68k-sony os=-newsos ;; news1000) basic_machine=m68030-sony os=-newsos ;; news-3600 | risc-news) basic_machine=mips-sony os=-newsos ;; necv70) basic_machine=v70-nec os=-sysv ;; next | m*-next ) basic_machine=m68k-next case $os in -nextstep* ) ;; -ns2*) os=-nextstep2 ;; *) os=-nextstep3 ;; esac ;; nh3000) basic_machine=m68k-harris os=-cxux ;; nh[45]000) basic_machine=m88k-harris os=-cxux ;; nindy960) basic_machine=i960-intel os=-nindy ;; mon960) basic_machine=i960-intel os=-mon960 ;; nonstopux) basic_machine=mips-compaq os=-nonstopux ;; np1) basic_machine=np1-gould ;; neo-tandem) basic_machine=neo-tandem ;; nse-tandem) basic_machine=nse-tandem ;; nsr-tandem) basic_machine=nsr-tandem ;; nsx-tandem) basic_machine=nsx-tandem ;; op50n-* | op60c-*) basic_machine=hppa1.1-oki os=-proelf ;; openrisc | openrisc-*) basic_machine=or32-unknown ;; os400) basic_machine=powerpc-ibm os=-os400 ;; OSE68000 | ose68000) basic_machine=m68000-ericsson os=-ose ;; os68k) basic_machine=m68k-none os=-os68k ;; pa-hitachi) basic_machine=hppa1.1-hitachi os=-hiuxwe2 ;; paragon) basic_machine=i860-intel os=-osf ;; parisc) basic_machine=hppa-unknown os=-linux ;; parisc-*) basic_machine=hppa-`echo $basic_machine | sed 's/^[^-]*-//'` os=-linux ;; pbd) basic_machine=sparc-tti ;; pbb) basic_machine=m68k-tti ;; pc532 | pc532-*) basic_machine=ns32k-pc532 ;; pc98) basic_machine=i386-pc ;; pc98-*) basic_machine=i386-`echo $basic_machine | sed 's/^[^-]*-//'` ;; pentium | p5 | k5 | k6 | nexgen | viac3) basic_machine=i586-pc ;; pentiumpro | p6 | 6x86 | athlon | athlon_*) basic_machine=i686-pc ;; pentiumii | pentium2 | pentiumiii | pentium3) basic_machine=i686-pc ;; pentium4) basic_machine=i786-pc ;; pentium-* | p5-* | k5-* | k6-* | nexgen-* | viac3-*) basic_machine=i586-`echo $basic_machine | sed 's/^[^-]*-//'` ;; pentiumpro-* | p6-* | 6x86-* | athlon-*) basic_machine=i686-`echo $basic_machine | sed 's/^[^-]*-//'` ;; pentiumii-* | pentium2-* | pentiumiii-* | pentium3-*) basic_machine=i686-`echo $basic_machine | sed 's/^[^-]*-//'` ;; pentium4-*) basic_machine=i786-`echo $basic_machine | sed 's/^[^-]*-//'` ;; pn) basic_machine=pn-gould ;; power) basic_machine=power-ibm ;; ppc | ppcbe) basic_machine=powerpc-unknown ;; ppc-* | ppcbe-*) basic_machine=powerpc-`echo $basic_machine | sed 's/^[^-]*-//'` ;; ppcle | powerpclittle) basic_machine=powerpcle-unknown ;; ppcle-* | powerpclittle-*) basic_machine=powerpcle-`echo $basic_machine | sed 's/^[^-]*-//'` ;; ppc64) basic_machine=powerpc64-unknown ;; ppc64-*) basic_machine=powerpc64-`echo $basic_machine | sed 's/^[^-]*-//'` ;; ppc64le | powerpc64little) basic_machine=powerpc64le-unknown ;; ppc64le-* | powerpc64little-*) basic_machine=powerpc64le-`echo $basic_machine | sed 's/^[^-]*-//'` ;; ps2) basic_machine=i386-ibm ;; pw32) basic_machine=i586-unknown os=-pw32 ;; rdos | rdos64) basic_machine=x86_64-pc os=-rdos ;; rdos32) basic_machine=i386-pc os=-rdos ;; rom68k) basic_machine=m68k-rom68k os=-coff ;; rm[46]00) basic_machine=mips-siemens ;; rtpc | rtpc-*) basic_machine=romp-ibm ;; s390 | s390-*) basic_machine=s390-ibm ;; s390x | s390x-*) basic_machine=s390x-ibm ;; sa29200) basic_machine=a29k-amd os=-udi ;; sb1) basic_machine=mipsisa64sb1-unknown ;; sb1el) basic_machine=mipsisa64sb1el-unknown ;; sde) basic_machine=mipsisa32-sde os=-elf ;; sei) basic_machine=mips-sei os=-seiux ;; sequent) basic_machine=i386-sequent ;; sh) basic_machine=sh-hitachi os=-hms ;; sh5el) basic_machine=sh5le-unknown ;; sh64) basic_machine=sh64-unknown ;; sparclite-wrs | simso-wrs) basic_machine=sparclite-wrs os=-vxworks ;; sps7) basic_machine=m68k-bull os=-sysv2 ;; spur) basic_machine=spur-unknown ;; st2000) basic_machine=m68k-tandem ;; stratus) basic_machine=i860-stratus os=-sysv4 ;; strongarm-* | thumb-*) basic_machine=arm-`echo $basic_machine | sed 's/^[^-]*-//'` ;; sun2) basic_machine=m68000-sun ;; sun2os3) basic_machine=m68000-sun os=-sunos3 ;; sun2os4) basic_machine=m68000-sun os=-sunos4 ;; sun3os3) basic_machine=m68k-sun os=-sunos3 ;; sun3os4) basic_machine=m68k-sun os=-sunos4 ;; sun4os3) basic_machine=sparc-sun os=-sunos3 ;; sun4os4) basic_machine=sparc-sun os=-sunos4 ;; sun4sol2) basic_machine=sparc-sun os=-solaris2 ;; sun3 | sun3-*) basic_machine=m68k-sun ;; sun4) basic_machine=sparc-sun ;; sun386 | sun386i | roadrunner) basic_machine=i386-sun ;; sv1) basic_machine=sv1-cray os=-unicos ;; symmetry) basic_machine=i386-sequent os=-dynix ;; t3e) basic_machine=alphaev5-cray os=-unicos ;; t90) basic_machine=t90-cray os=-unicos ;; tile*) basic_machine=$basic_machine-unknown os=-linux-gnu ;; tx39) basic_machine=mipstx39-unknown ;; tx39el) basic_machine=mipstx39el-unknown ;; toad1) basic_machine=pdp10-xkl os=-tops20 ;; tower | tower-32) basic_machine=m68k-ncr ;; tpf) basic_machine=s390x-ibm os=-tpf ;; udi29k) basic_machine=a29k-amd os=-udi ;; ultra3) basic_machine=a29k-nyu os=-sym1 ;; v810 | necv810) basic_machine=v810-nec os=-none ;; vaxv) basic_machine=vax-dec os=-sysv ;; vms) basic_machine=vax-dec os=-vms ;; vpp*|vx|vx-*) basic_machine=f301-fujitsu ;; vxworks960) basic_machine=i960-wrs os=-vxworks ;; vxworks68) basic_machine=m68k-wrs os=-vxworks ;; vxworks29k) basic_machine=a29k-wrs os=-vxworks ;; wasm32) basic_machine=wasm32-unknown ;; w65*) basic_machine=w65-wdc os=-none ;; w89k-*) basic_machine=hppa1.1-winbond os=-proelf ;; xbox) basic_machine=i686-pc os=-mingw32 ;; xps | xps100) basic_machine=xps100-honeywell ;; xscale-* | xscalee[bl]-*) basic_machine=`echo $basic_machine | sed 's/^xscale/arm/'` ;; ymp) basic_machine=ymp-cray os=-unicos ;; z8k-*-coff) basic_machine=z8k-unknown os=-sim ;; z80-*-coff) basic_machine=z80-unknown os=-sim ;; none) basic_machine=none-none os=-none ;; # Here we handle the default manufacturer of certain CPU types. It is in # some cases the only manufacturer, in others, it is the most popular. w89k) basic_machine=hppa1.1-winbond ;; op50n) basic_machine=hppa1.1-oki ;; op60c) basic_machine=hppa1.1-oki ;; romp) basic_machine=romp-ibm ;; mmix) basic_machine=mmix-knuth ;; rs6000) basic_machine=rs6000-ibm ;; vax) basic_machine=vax-dec ;; pdp10) # there are many clones, so DEC is not a safe bet basic_machine=pdp10-unknown ;; pdp11) basic_machine=pdp11-dec ;; we32k) basic_machine=we32k-att ;; sh[1234] | sh[24]a | sh[24]aeb | sh[34]eb | sh[1234]le | sh[23]ele) basic_machine=sh-unknown ;; sparc | sparcv8 | sparcv9 | sparcv9b | sparcv9v) basic_machine=sparc-sun ;; cydra) basic_machine=cydra-cydrome ;; orion) basic_machine=orion-highlevel ;; orion105) basic_machine=clipper-highlevel ;; mac | mpw | mac-mpw) basic_machine=m68k-apple ;; pmac | pmac-mpw) basic_machine=powerpc-apple ;; *-unknown) # Make sure to match an already-canonicalized machine name. ;; *) echo Invalid configuration \`$1\': machine \`$basic_machine\' not recognized 1>&2 exit 1 ;; esac # Here we canonicalize certain aliases for manufacturers. case $basic_machine in *-digital*) basic_machine=`echo $basic_machine | sed 's/digital.*/dec/'` ;; *-commodore*) basic_machine=`echo $basic_machine | sed 's/commodore.*/cbm/'` ;; *) ;; esac # Decode manufacturer-specific aliases for certain operating systems. if [ x"$os" != x"" ] then case $os in # First match some system type aliases # that might get confused with valid system types. # -solaris* is a basic system type, with this one exception. -auroraux) os=-auroraux ;; -solaris1 | -solaris1.*) os=`echo $os | sed -e 's|solaris1|sunos4|'` ;; -solaris) os=-solaris2 ;; -svr4*) os=-sysv4 ;; -unixware*) os=-sysv4.2uw ;; -gnu/linux*) os=`echo $os | sed -e 's|gnu/linux|linux-gnu|'` ;; # First accept the basic system types. # The portable systems comes first. # Each alternative MUST END IN A *, to match a version number. # -sysv* is not here because it comes later, after sysvr4. -gnu* | -bsd* | -mach* | -minix* | -genix* | -ultrix* | -irix* \ | -*vms* | -sco* | -esix* | -isc* | -aix* | -cnk* | -sunos | -sunos[34]*\ | -hpux* | -unos* | -osf* | -luna* | -dgux* | -auroraux* | -solaris* \ | -sym* | -kopensolaris* | -plan9* \ | -amigaos* | -amigados* | -msdos* | -newsos* | -unicos* | -aof* \ | -aos* | -aros* | -cloudabi* | -sortix* \ | -nindy* | -vxsim* | -vxworks* | -ebmon* | -hms* | -mvs* \ | -clix* | -riscos* | -uniplus* | -iris* | -rtu* | -xenix* \ | -hiux* | -386bsd* | -knetbsd* | -mirbsd* | -netbsd* \ | -bitrig* | -openbsd* | -solidbsd* | -libertybsd* \ | -ekkobsd* | -kfreebsd* | -freebsd* | -riscix* | -lynxos* \ | -bosx* | -nextstep* | -cxux* | -aout* | -elf* | -oabi* \ | -ptx* | -coff* | -ecoff* | -winnt* | -domain* | -vsta* \ | -udi* | -eabi* | -lites* | -ieee* | -go32* | -aux* \ | -chorusos* | -chorusrdb* | -cegcc* | -glidix* \ | -cygwin* | -msys* | -pe* | -psos* | -moss* | -proelf* | -rtems* \ | -midipix* | -mingw32* | -mingw64* | -linux-gnu* | -linux-android* \ | -linux-newlib* | -linux-musl* | -linux-uclibc* \ | -uxpv* | -beos* | -mpeix* | -udk* | -moxiebox* \ | -interix* | -uwin* | -mks* | -rhapsody* | -darwin* | -opened* \ | -openstep* | -oskit* | -conix* | -pw32* | -nonstopux* \ | -storm-chaos* | -tops10* | -tenex* | -tops20* | -its* \ | -os2* | -vos* | -palmos* | -uclinux* | -nucleus* \ | -morphos* | -superux* | -rtmk* | -rtmk-nova* | -windiss* \ | -powermax* | -dnix* | -nx6 | -nx7 | -sei* | -dragonfly* \ | -skyos* | -haiku* | -rdos* | -toppers* | -drops* | -es* \ | -onefs* | -tirtos* | -phoenix* | -fuchsia* | -redox*) # Remember, each alternative MUST END IN *, to match a version number. ;; -qnx*) case $basic_machine in x86-* | i*86-*) ;; *) os=-nto$os ;; esac ;; -nto-qnx*) ;; -nto*) os=`echo $os | sed -e 's|nto|nto-qnx|'` ;; -sim | -es1800* | -hms* | -xray | -os68k* | -none* | -v88r* \ | -windows* | -osx | -abug | -netware* | -os9* | -beos* | -haiku* \ | -macos* | -mpw* | -magic* | -mmixware* | -mon960* | -lnews*) ;; -mac*) os=`echo $os | sed -e 's|mac|macos|'` ;; -linux-dietlibc) os=-linux-dietlibc ;; -linux*) os=`echo $os | sed -e 's|linux|linux-gnu|'` ;; -sunos5*) os=`echo $os | sed -e 's|sunos5|solaris2|'` ;; -sunos6*) os=`echo $os | sed -e 's|sunos6|solaris3|'` ;; -opened*) os=-openedition ;; -os400*) os=-os400 ;; -wince*) os=-wince ;; -osfrose*) os=-osfrose ;; -osf*) os=-osf ;; -utek*) os=-bsd ;; -dynix*) os=-bsd ;; -acis*) os=-aos ;; -atheos*) os=-atheos ;; -syllable*) os=-syllable ;; -386bsd) os=-bsd ;; -ctix* | -uts*) os=-sysv ;; -nova*) os=-rtmk-nova ;; -ns2 ) os=-nextstep2 ;; -nsk*) os=-nsk ;; # Preserve the version number of sinix5. -sinix5.*) os=`echo $os | sed -e 's|sinix|sysv|'` ;; -sinix*) os=-sysv4 ;; -tpf*) os=-tpf ;; -triton*) os=-sysv3 ;; -oss*) os=-sysv3 ;; -svr4) os=-sysv4 ;; -svr3) os=-sysv3 ;; -sysvr4) os=-sysv4 ;; # This must come after -sysvr4. -sysv*) ;; -ose*) os=-ose ;; -es1800*) os=-ose ;; -xenix) os=-xenix ;; -*mint | -mint[0-9]* | -*MiNT | -MiNT[0-9]*) os=-mint ;; -aros*) os=-aros ;; -zvmoe) os=-zvmoe ;; -dicos*) os=-dicos ;; -nacl*) ;; -ios) ;; -none) ;; *) # Get rid of the `-' at the beginning of $os. os=`echo $os | sed 's/[^-]*-//'` echo Invalid configuration \`$1\': system \`$os\' not recognized 1>&2 exit 1 ;; esac else # Here we handle the default operating systems that come with various machines. # The value should be what the vendor currently ships out the door with their # machine or put another way, the most popular os provided with the machine. # Note that if you're going to try to match "-MANUFACTURER" here (say, # "-sun"), then you have to tell the case statement up towards the top # that MANUFACTURER isn't an operating system. Otherwise, code above # will signal an error saying that MANUFACTURER isn't an operating # system, and we'll never get to this point. case $basic_machine in score-*) os=-elf ;; spu-*) os=-elf ;; *-acorn) os=-riscix1.2 ;; arm*-rebel) os=-linux ;; arm*-semi) os=-aout ;; c4x-* | tic4x-*) os=-coff ;; c8051-*) os=-elf ;; hexagon-*) os=-elf ;; tic54x-*) os=-coff ;; tic55x-*) os=-coff ;; tic6x-*) os=-coff ;; # This must come before the *-dec entry. pdp10-*) os=-tops20 ;; pdp11-*) os=-none ;; *-dec | vax-*) os=-ultrix4.2 ;; m68*-apollo) os=-domain ;; i386-sun) os=-sunos4.0.2 ;; m68000-sun) os=-sunos3 ;; m68*-cisco) os=-aout ;; mep-*) os=-elf ;; mips*-cisco) os=-elf ;; mips*-*) os=-elf ;; or32-*) os=-coff ;; *-tti) # must be before sparc entry or we get the wrong os. os=-sysv3 ;; sparc-* | *-sun) os=-sunos4.1.1 ;; pru-*) os=-elf ;; *-be) os=-beos ;; *-haiku) os=-haiku ;; *-ibm) os=-aix ;; *-knuth) os=-mmixware ;; *-wec) os=-proelf ;; *-winbond) os=-proelf ;; *-oki) os=-proelf ;; *-hp) os=-hpux ;; *-hitachi) os=-hiux ;; i860-* | *-att | *-ncr | *-altos | *-motorola | *-convergent) os=-sysv ;; *-cbm) os=-amigaos ;; *-dg) os=-dgux ;; *-dolphin) os=-sysv3 ;; m68k-ccur) os=-rtu ;; m88k-omron*) os=-luna ;; *-next ) os=-nextstep ;; *-sequent) os=-ptx ;; *-crds) os=-unos ;; *-ns) os=-genix ;; i370-*) os=-mvs ;; *-next) os=-nextstep3 ;; *-gould) os=-sysv ;; *-highlevel) os=-bsd ;; *-encore) os=-bsd ;; *-sgi) os=-irix ;; *-siemens) os=-sysv4 ;; *-masscomp) os=-rtu ;; f30[01]-fujitsu | f700-fujitsu) os=-uxpv ;; *-rom68k) os=-coff ;; *-*bug) os=-coff ;; *-apple) os=-macos ;; *-atari*) os=-mint ;; *) os=-none ;; esac fi # Here we handle the case where we know the os, and the CPU type, but not the # manufacturer. We pick the logical manufacturer. vendor=unknown case $basic_machine in *-unknown) case $os in -riscix*) vendor=acorn ;; -sunos*) vendor=sun ;; -cnk*|-aix*) vendor=ibm ;; -beos*) vendor=be ;; -hpux*) vendor=hp ;; -mpeix*) vendor=hp ;; -hiux*) vendor=hitachi ;; -unos*) vendor=crds ;; -dgux*) vendor=dg ;; -luna*) vendor=omron ;; -genix*) vendor=ns ;; -mvs* | -opened*) vendor=ibm ;; -os400*) vendor=ibm ;; -ptx*) vendor=sequent ;; -tpf*) vendor=ibm ;; -vxsim* | -vxworks* | -windiss*) vendor=wrs ;; -aux*) vendor=apple ;; -hms*) vendor=hitachi ;; -mpw* | -macos*) vendor=apple ;; -*mint | -mint[0-9]* | -*MiNT | -MiNT[0-9]*) vendor=atari ;; -vos*) vendor=stratus ;; esac basic_machine=`echo $basic_machine | sed "s/unknown/$vendor/"` ;; esac echo $basic_machine$os exit # Local variables: # eval: (add-hook 'write-file-hooks 'time-stamp) # time-stamp-start: "timestamp='" # time-stamp-format: "%:y-%02m-%02d" # time-stamp-end: "'" # End: heimdal-7.5.0/lib/libedit/ChangeLog0000644000175000017500000001550113026237312015207 0ustar niknik * See also NetBSD changelog: http://cvsweb.netbsd.org/bsdweb.cgi/src/lib/libedit 2011-02-27 Jess Thrysoee * version-info: 0:36:0 * all: sync with upstream source. 2010-04-24 Jess Thrysoee * version-info: 0:35:0 * all: sync with upstream source. Now with UTF-8 support. To enable this run 'configure --enable-widec'. For now an UTF-32 encoded wchar_t is required. This requirement is met on NetBSD, Solaris and OS X for any UTF-8 locale, and any system that define __STDC_ISO_10646__ (e.g. GNU libc on Linux). 2009-09-23 Jess Thrysoee * version-info: 0:34:0 * all: apply Apple patches from: http://opensource.apple.com/source/libedit/libedit-11/patches 2009-09-05 Jess Thrysoee * version-info: 0:33:0 * all: Use predefined macro __sun to identify Solaris * src/el.c: Ignore comment lines in .editrc 2009-07-23 Jess Thrysoee * version-info: 0:32:0 * all: sync with upstream source. 2009-06-10 Jess Thrysoee * version-info: 0:31:0 * all: sync with upstream source. 2009-05-03 Jess Thrysoee * version-info: 0:30:0 * all: sync with upstream source. 2009-04-05 Jess Thrysoee * version-info: 0:29:0 * all: sync with upstream source. 2009-01-11 Jess Thrysoee * version-info: 0:28:0 * all: sync with upstream source. MAJOR.MINOR version is now 3.0. This is due to NetBSD changing time_t and dev_t to 64 bits. It does not really effect this package. * configure.ac: Remove '--enable-debug' configure flag. The autoconf way to control flags is by specifying them when running configure, e.g. 'CFLAGS="-O0 -g" ./configure' 2008-07-12 Jess Thrysoee * version-info: 0:27:0 * configure.ac: Added '--enable-debug' configure flag, to produce debugging information. * examples/fileman.c: cast stat struct members, st_nlink and st_size, appropriately (see also 'man 2 stat'). Patch by Alex Elder. * all: sync with upstream source. MINOR version is now 11. 2007-08-31 Jess Thrysoee * version-info: 0:26:0 * libedit.pc.in,Makefile.am,configure.ac,patches/extra_dist_list.sh: Added pkg-config support for libedit. Patch by Masatake YAMATO. 2007-08-13 Jess Thrysoee * version-info: 0:25:0 * all: sync with upstream source. 2007-03-02 Jess Thrysoee * version-info: 0:24:0 * all: sync with upstream source. 2006-10-22 Jess Thrysoee * version-info: 0:23:0 * src/shlib_version: Upstream bumped minor version from 9 to 10. * all: sync with upstream source. More readline functions. 2006-10-22 Jess Thrysoee * version-info: 0:22:0 * all: sync with upstream source. 2006-08-29 Jess Thrysoee * version-info: 0:21:0 * all: License cleanup. All 4-clause advertising BSD licenses has been changed to the 3-clause version by upstream. * src/fgetln.c: use src/tools/compat/fgetln.c instead of othersrc/libexec/tnftpd/libnetbsd/fgetln.c 2006-08-16 Jess Thrysoee * version-info: 0:20:0 * all: sync with upstream source. 2006-06-03 Jess Thrysoee * version-info: 0:19:0 * COPYING: added global license file * all: sync with upstream source. 2006-02-13 Jess Thrysoee * version-info: 0:18:0 * src/readline.c: Partial rl_getc_function support, patch by Kjeld Borch Egevang. * src/readline.c: Make write_history and read_history returncode readline compatible. Upstream patch. 2006-01-03 Jess Thrysoee * version-info: 0:17:0 * patches/cvs_export.sh: strlcat.c and strlcpy.c was moved to src/common/lib/libc/string in the upstream cvs repository. * all: sync with upstream source. 2005-10-22 Jess Thrysoee * version-info: 0:16:0 * patches/*.patch, configure.ac: define SCCSID, undef LIBC_SCCS. Remove fourteen cosmetic patches. * all: sync with upstream source. 2005-09-11 Jess Thrysoee * version-info: 0:15:0 * src/Makefile.am: fix typo that meant generated files were distributes, and make generated file targets dependent on the the 'makelist' input files. * all: sync with upstream source. This is just a manpage update 2005-08-28 Jess Thrysoee * version-info: 0:14:0 * src/sys.h: include config.h to avoid "redefinition of `u_int32_t'". Patch by Norihiko Murase. * src/search.c: explicitly include sys/types.h, because regex.h on FreeBSD needs it and does not include it itself. Patch by Norihiko Murase. * acinclude.m4: added EL_GETPW_R_DRAFT test and use AC_TRY_LINK instead of AC_TRY_COMPILE. Suggested by Norihiko Murase. * all: sync with upstream source. 2005-08-16 Jess Thrysoee * version-info: 0:13:0 * all: sync with upstream source. 2005-08-05 Jess Thrysoee * version-info: 0:12:0 * all: sync with upstream source. 2005-07-24 Jess Thrysoee * version-info: 0:11:0 * histedit.h, histedit.c, readline.c, editline/readline.h: From upstream; added remove_history(). 2005-07-07 Jess Thrysoee * version-info: 0:10:0 * history.c, key.c: From upstream source; Fix memory leaks found by valgrind. 2005-06-28 Jess Thrysoee * version-info: 0:9:0 * src/readline.c: getpwent_r is not POSIX, always use getpwent. Reported by Gerrit P. Haase. * src/Makefile.am: Added libtool -no-undefined. This is needed on Cygwin to get a shared editline library. Should not affect other platforms. Suggested by Gerrit P. Haase. 2005-06-15 Jess Thrysoee * version-info: 0:8:0 * all: sync with upstream source. 2005-06-01 Jess Thrysoee * version-info: 0:7:0 * all: sync with upstream source. * src/readline.c, src/filecomplete.c: Solaris use POSIX draft versions of getpwent_r, getpwnam_r and getpwuid_r which return 'struct passwd *'. Define HAVE_GETPW_R_POSIX if these functions are (non draft) POSIX compatible. Patch by Julien Torrès. 2005-05-28 Jess Thrysoee * version-info: 0:6:0 * all: sync with upstream source. 2005-03-11 Jess Thrysoee * version-info: 0:5:0 * all: sync with upstream source. 2004-12-07 Jess Thrysoee * version-info: 0:4:0 * src/readline.c: d_namlen (in struct dirent) is not portable, always use strlen. Patch by Scott Rankin. 2004-11-27 Jess Thrysoee * version-info: 0:3:0 * src/history.c: bug #26785 fixed upstream, removed local patch. 2004-11-06 Jess Thrysoee * version-info: 0:2:0 * all: sync with upstream source. * doc/Makefile.am: If mdoc2man fails, remove empty file. Patch by Darren Tucker. 2004-10-14 Jess Thrysoee * version-info: 0:1:0 * doc/Makefile.am: 'make install' twice fails. Remove old links before trying to link the man pages. Patch by Rick Richardson. 2004-09-28 Jess Thrysoee * version-info: 0:0:0 * acinclude.m4 configure.ac src/Makefile.am: Adhere to LibTools library interface versions recommendation. http://www.gnu.org/software/libtool/manual.html#SEC32 * doc/Makefile.am: name all manpage links as el_* (e.g. el_history.3) to avoid conflicts. 2004-09-08 Jess Thrysoee * all: Initial package. heimdal-7.5.0/lib/libedit/missing0000755000175000017500000001533113212444505015036 0ustar niknik#! /bin/sh # Common wrapper for a few potentially missing GNU programs. scriptversion=2016-01-11.22; # UTC # Copyright (C) 1996-2017 Free Software Foundation, Inc. # Originally written by Fran,cois Pinard , 1996. # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2, or (at your option) # any later version. # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # You should have received a copy of the GNU General Public License # along with this program. If not, see . # As a special exception to the GNU General Public License, if you # distribute this file as part of a program that contains a # configuration script generated by Autoconf, you may include it under # the same distribution terms that you use for the rest of that program. if test $# -eq 0; then echo 1>&2 "Try '$0 --help' for more information" exit 1 fi case $1 in --is-lightweight) # Used by our autoconf macros to check whether the available missing # script is modern enough. exit 0 ;; --run) # Back-compat with the calling convention used by older automake. shift ;; -h|--h|--he|--hel|--help) echo "\ $0 [OPTION]... PROGRAM [ARGUMENT]... Run 'PROGRAM [ARGUMENT]...', returning a proper advice when this fails due to PROGRAM being missing or too old. Options: -h, --help display this help and exit -v, --version output version information and exit Supported PROGRAM values: aclocal autoconf autoheader autom4te automake makeinfo bison yacc flex lex help2man Version suffixes to PROGRAM as well as the prefixes 'gnu-', 'gnu', and 'g' are ignored when checking the name. Send bug reports to ." exit $? ;; -v|--v|--ve|--ver|--vers|--versi|--versio|--version) echo "missing $scriptversion (GNU Automake)" exit $? ;; -*) echo 1>&2 "$0: unknown '$1' option" echo 1>&2 "Try '$0 --help' for more information" exit 1 ;; esac # Run the given program, remember its exit status. "$@"; st=$? # If it succeeded, we are done. test $st -eq 0 && exit 0 # Also exit now if we it failed (or wasn't found), and '--version' was # passed; such an option is passed most likely to detect whether the # program is present and works. case $2 in --version|--help) exit $st;; esac # Exit code 63 means version mismatch. This often happens when the user # tries to use an ancient version of a tool on a file that requires a # minimum version. if test $st -eq 63; then msg="probably too old" elif test $st -eq 127; then # Program was missing. msg="missing on your system" else # Program was found and executed, but failed. Give up. exit $st fi perl_URL=http://www.perl.org/ flex_URL=http://flex.sourceforge.net/ gnu_software_URL=http://www.gnu.org/software program_details () { case $1 in aclocal|automake) echo "The '$1' program is part of the GNU Automake package:" echo "<$gnu_software_URL/automake>" echo "It also requires GNU Autoconf, GNU m4 and Perl in order to run:" echo "<$gnu_software_URL/autoconf>" echo "<$gnu_software_URL/m4/>" echo "<$perl_URL>" ;; autoconf|autom4te|autoheader) echo "The '$1' program is part of the GNU Autoconf package:" echo "<$gnu_software_URL/autoconf/>" echo "It also requires GNU m4 and Perl in order to run:" echo "<$gnu_software_URL/m4/>" echo "<$perl_URL>" ;; esac } give_advice () { # Normalize program name to check for. normalized_program=`echo "$1" | sed ' s/^gnu-//; t s/^gnu//; t s/^g//; t'` printf '%s\n' "'$1' is $msg." configure_deps="'configure.ac' or m4 files included by 'configure.ac'" case $normalized_program in autoconf*) echo "You should only need it if you modified 'configure.ac'," echo "or m4 files included by it." program_details 'autoconf' ;; autoheader*) echo "You should only need it if you modified 'acconfig.h' or" echo "$configure_deps." program_details 'autoheader' ;; automake*) echo "You should only need it if you modified 'Makefile.am' or" echo "$configure_deps." program_details 'automake' ;; aclocal*) echo "You should only need it if you modified 'acinclude.m4' or" echo "$configure_deps." program_details 'aclocal' ;; autom4te*) echo "You might have modified some maintainer files that require" echo "the 'autom4te' program to be rebuilt." program_details 'autom4te' ;; bison*|yacc*) echo "You should only need it if you modified a '.y' file." echo "You may want to install the GNU Bison package:" echo "<$gnu_software_URL/bison/>" ;; lex*|flex*) echo "You should only need it if you modified a '.l' file." echo "You may want to install the Fast Lexical Analyzer package:" echo "<$flex_URL>" ;; help2man*) echo "You should only need it if you modified a dependency" \ "of a man page." echo "You may want to install the GNU Help2man package:" echo "<$gnu_software_URL/help2man/>" ;; makeinfo*) echo "You should only need it if you modified a '.texi' file, or" echo "any other file indirectly affecting the aspect of the manual." echo "You might want to install the Texinfo package:" echo "<$gnu_software_URL/texinfo/>" echo "The spurious makeinfo call might also be the consequence of" echo "using a buggy 'make' (AIX, DU, IRIX), in which case you might" echo "want to install GNU make:" echo "<$gnu_software_URL/make/>" ;; *) echo "You might have modified some files without having the proper" echo "tools for further handling them. Check the 'README' file, it" echo "often tells you about the needed prerequisites for installing" echo "this package. You may also peek at any GNU archive site, in" echo "case some other package contains this missing '$1' program." ;; esac } give_advice "$1" | sed -e '1s/^/WARNING: /' \ -e '2,$s/^/ /' >&2 # Propagate the correct exit status (expected to be 127 for a program # not found, 63 for a program that failed due to version mismatch). exit $st # Local variables: # eval: (add-hook 'write-file-hooks 'time-stamp) # time-stamp-start: "scriptversion=" # time-stamp-format: "%:y-%02m-%02d.%02H" # time-stamp-time-zone: "UTC0" # time-stamp-end: "; # UTC" # End: heimdal-7.5.0/lib/libedit/depcomp0000755000175000017500000005601713212444505015022 0ustar niknik#! /bin/sh # depcomp - compile a program generating dependencies as side-effects scriptversion=2016-01-11.22; # UTC # Copyright (C) 1999-2017 Free Software Foundation, Inc. # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2, or (at your option) # any later version. # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # You should have received a copy of the GNU General Public License # along with this program. If not, see . # As a special exception to the GNU General Public License, if you # distribute this file as part of a program that contains a # configuration script generated by Autoconf, you may include it under # the same distribution terms that you use for the rest of that program. # Originally written by Alexandre Oliva . case $1 in '') echo "$0: No command. Try '$0 --help' for more information." 1>&2 exit 1; ;; -h | --h*) cat <<\EOF Usage: depcomp [--help] [--version] PROGRAM [ARGS] Run PROGRAMS ARGS to compile a file, generating dependencies as side-effects. Environment variables: depmode Dependency tracking mode. source Source file read by 'PROGRAMS ARGS'. object Object file output by 'PROGRAMS ARGS'. DEPDIR directory where to store dependencies. depfile Dependency file to output. tmpdepfile Temporary file to use when outputting dependencies. libtool Whether libtool is used (yes/no). Report bugs to . EOF exit $? ;; -v | --v*) echo "depcomp $scriptversion" exit $? ;; esac # Get the directory component of the given path, and save it in the # global variables '$dir'. Note that this directory component will # be either empty or ending with a '/' character. This is deliberate. set_dir_from () { case $1 in */*) dir=`echo "$1" | sed -e 's|/[^/]*$|/|'`;; *) dir=;; esac } # Get the suffix-stripped basename of the given path, and save it the # global variable '$base'. set_base_from () { base=`echo "$1" | sed -e 's|^.*/||' -e 's/\.[^.]*$//'` } # If no dependency file was actually created by the compiler invocation, # we still have to create a dummy depfile, to avoid errors with the # Makefile "include basename.Plo" scheme. make_dummy_depfile () { echo "#dummy" > "$depfile" } # Factor out some common post-processing of the generated depfile. # Requires the auxiliary global variable '$tmpdepfile' to be set. aix_post_process_depfile () { # If the compiler actually managed to produce a dependency file, # post-process it. if test -f "$tmpdepfile"; then # Each line is of the form 'foo.o: dependency.h'. # Do two passes, one to just change these to # $object: dependency.h # and one to simply output # dependency.h: # which is needed to avoid the deleted-header problem. { sed -e "s,^.*\.[$lower]*:,$object:," < "$tmpdepfile" sed -e "s,^.*\.[$lower]*:[$tab ]*,," -e 's,$,:,' < "$tmpdepfile" } > "$depfile" rm -f "$tmpdepfile" else make_dummy_depfile fi } # A tabulation character. tab=' ' # A newline character. nl=' ' # Character ranges might be problematic outside the C locale. # These definitions help. upper=ABCDEFGHIJKLMNOPQRSTUVWXYZ lower=abcdefghijklmnopqrstuvwxyz digits=0123456789 alpha=${upper}${lower} if test -z "$depmode" || test -z "$source" || test -z "$object"; then echo "depcomp: Variables source, object and depmode must be set" 1>&2 exit 1 fi # Dependencies for sub/bar.o or sub/bar.obj go into sub/.deps/bar.Po. depfile=${depfile-`echo "$object" | sed 's|[^\\/]*$|'${DEPDIR-.deps}'/&|;s|\.\([^.]*\)$|.P\1|;s|Pobj$|Po|'`} tmpdepfile=${tmpdepfile-`echo "$depfile" | sed 's/\.\([^.]*\)$/.T\1/'`} rm -f "$tmpdepfile" # Avoid interferences from the environment. gccflag= dashmflag= # Some modes work just like other modes, but use different flags. We # parameterize here, but still list the modes in the big case below, # to make depend.m4 easier to write. Note that we *cannot* use a case # here, because this file can only contain one case statement. if test "$depmode" = hp; then # HP compiler uses -M and no extra arg. gccflag=-M depmode=gcc fi if test "$depmode" = dashXmstdout; then # This is just like dashmstdout with a different argument. dashmflag=-xM depmode=dashmstdout fi cygpath_u="cygpath -u -f -" if test "$depmode" = msvcmsys; then # This is just like msvisualcpp but w/o cygpath translation. # Just convert the backslash-escaped backslashes to single forward # slashes to satisfy depend.m4 cygpath_u='sed s,\\\\,/,g' depmode=msvisualcpp fi if test "$depmode" = msvc7msys; then # This is just like msvc7 but w/o cygpath translation. # Just convert the backslash-escaped backslashes to single forward # slashes to satisfy depend.m4 cygpath_u='sed s,\\\\,/,g' depmode=msvc7 fi if test "$depmode" = xlc; then # IBM C/C++ Compilers xlc/xlC can output gcc-like dependency information. gccflag=-qmakedep=gcc,-MF depmode=gcc fi case "$depmode" in gcc3) ## gcc 3 implements dependency tracking that does exactly what ## we want. Yay! Note: for some reason libtool 1.4 doesn't like ## it if -MD -MP comes after the -MF stuff. Hmm. ## Unfortunately, FreeBSD c89 acceptance of flags depends upon ## the command line argument order; so add the flags where they ## appear in depend2.am. Note that the slowdown incurred here ## affects only configure: in makefiles, %FASTDEP% shortcuts this. for arg do case $arg in -c) set fnord "$@" -MT "$object" -MD -MP -MF "$tmpdepfile" "$arg" ;; *) set fnord "$@" "$arg" ;; esac shift # fnord shift # $arg done "$@" stat=$? if test $stat -ne 0; then rm -f "$tmpdepfile" exit $stat fi mv "$tmpdepfile" "$depfile" ;; gcc) ## Note that this doesn't just cater to obsosete pre-3.x GCC compilers. ## but also to in-use compilers like IMB xlc/xlC and the HP C compiler. ## (see the conditional assignment to $gccflag above). ## There are various ways to get dependency output from gcc. Here's ## why we pick this rather obscure method: ## - Don't want to use -MD because we'd like the dependencies to end ## up in a subdir. Having to rename by hand is ugly. ## (We might end up doing this anyway to support other compilers.) ## - The DEPENDENCIES_OUTPUT environment variable makes gcc act like ## -MM, not -M (despite what the docs say). Also, it might not be ## supported by the other compilers which use the 'gcc' depmode. ## - Using -M directly means running the compiler twice (even worse ## than renaming). if test -z "$gccflag"; then gccflag=-MD, fi "$@" -Wp,"$gccflag$tmpdepfile" stat=$? if test $stat -ne 0; then rm -f "$tmpdepfile" exit $stat fi rm -f "$depfile" echo "$object : \\" > "$depfile" # The second -e expression handles DOS-style file names with drive # letters. sed -e 's/^[^:]*: / /' \ -e 's/^['$alpha']:\/[^:]*: / /' < "$tmpdepfile" >> "$depfile" ## This next piece of magic avoids the "deleted header file" problem. ## The problem is that when a header file which appears in a .P file ## is deleted, the dependency causes make to die (because there is ## typically no way to rebuild the header). We avoid this by adding ## dummy dependencies for each header file. Too bad gcc doesn't do ## this for us directly. ## Some versions of gcc put a space before the ':'. On the theory ## that the space means something, we add a space to the output as ## well. hp depmode also adds that space, but also prefixes the VPATH ## to the object. Take care to not repeat it in the output. ## Some versions of the HPUX 10.20 sed can't process this invocation ## correctly. Breaking it into two sed invocations is a workaround. tr ' ' "$nl" < "$tmpdepfile" \ | sed -e 's/^\\$//' -e '/^$/d' -e "s|.*$object$||" -e '/:$/d' \ | sed -e 's/$/ :/' >> "$depfile" rm -f "$tmpdepfile" ;; hp) # This case exists only to let depend.m4 do its work. It works by # looking at the text of this script. This case will never be run, # since it is checked for above. exit 1 ;; sgi) if test "$libtool" = yes; then "$@" "-Wp,-MDupdate,$tmpdepfile" else "$@" -MDupdate "$tmpdepfile" fi stat=$? if test $stat -ne 0; then rm -f "$tmpdepfile" exit $stat fi rm -f "$depfile" if test -f "$tmpdepfile"; then # yes, the sourcefile depend on other files echo "$object : \\" > "$depfile" # Clip off the initial element (the dependent). Don't try to be # clever and replace this with sed code, as IRIX sed won't handle # lines with more than a fixed number of characters (4096 in # IRIX 6.2 sed, 8192 in IRIX 6.5). We also remove comment lines; # the IRIX cc adds comments like '#:fec' to the end of the # dependency line. tr ' ' "$nl" < "$tmpdepfile" \ | sed -e 's/^.*\.o://' -e 's/#.*$//' -e '/^$/ d' \ | tr "$nl" ' ' >> "$depfile" echo >> "$depfile" # The second pass generates a dummy entry for each header file. tr ' ' "$nl" < "$tmpdepfile" \ | sed -e 's/^.*\.o://' -e 's/#.*$//' -e '/^$/ d' -e 's/$/:/' \ >> "$depfile" else make_dummy_depfile fi rm -f "$tmpdepfile" ;; xlc) # This case exists only to let depend.m4 do its work. It works by # looking at the text of this script. This case will never be run, # since it is checked for above. exit 1 ;; aix) # The C for AIX Compiler uses -M and outputs the dependencies # in a .u file. In older versions, this file always lives in the # current directory. Also, the AIX compiler puts '$object:' at the # start of each line; $object doesn't have directory information. # Version 6 uses the directory in both cases. set_dir_from "$object" set_base_from "$object" if test "$libtool" = yes; then tmpdepfile1=$dir$base.u tmpdepfile2=$base.u tmpdepfile3=$dir.libs/$base.u "$@" -Wc,-M else tmpdepfile1=$dir$base.u tmpdepfile2=$dir$base.u tmpdepfile3=$dir$base.u "$@" -M fi stat=$? if test $stat -ne 0; then rm -f "$tmpdepfile1" "$tmpdepfile2" "$tmpdepfile3" exit $stat fi for tmpdepfile in "$tmpdepfile1" "$tmpdepfile2" "$tmpdepfile3" do test -f "$tmpdepfile" && break done aix_post_process_depfile ;; tcc) # tcc (Tiny C Compiler) understand '-MD -MF file' since version 0.9.26 # FIXME: That version still under development at the moment of writing. # Make that this statement remains true also for stable, released # versions. # It will wrap lines (doesn't matter whether long or short) with a # trailing '\', as in: # # foo.o : \ # foo.c \ # foo.h \ # # It will put a trailing '\' even on the last line, and will use leading # spaces rather than leading tabs (at least since its commit 0394caf7 # "Emit spaces for -MD"). "$@" -MD -MF "$tmpdepfile" stat=$? if test $stat -ne 0; then rm -f "$tmpdepfile" exit $stat fi rm -f "$depfile" # Each non-empty line is of the form 'foo.o : \' or ' dep.h \'. # We have to change lines of the first kind to '$object: \'. sed -e "s|.*:|$object :|" < "$tmpdepfile" > "$depfile" # And for each line of the second kind, we have to emit a 'dep.h:' # dummy dependency, to avoid the deleted-header problem. sed -n -e 's|^ *\(.*\) *\\$|\1:|p' < "$tmpdepfile" >> "$depfile" rm -f "$tmpdepfile" ;; ## The order of this option in the case statement is important, since the ## shell code in configure will try each of these formats in the order ## listed in this file. A plain '-MD' option would be understood by many ## compilers, so we must ensure this comes after the gcc and icc options. pgcc) # Portland's C compiler understands '-MD'. # Will always output deps to 'file.d' where file is the root name of the # source file under compilation, even if file resides in a subdirectory. # The object file name does not affect the name of the '.d' file. # pgcc 10.2 will output # foo.o: sub/foo.c sub/foo.h # and will wrap long lines using '\' : # foo.o: sub/foo.c ... \ # sub/foo.h ... \ # ... set_dir_from "$object" # Use the source, not the object, to determine the base name, since # that's sadly what pgcc will do too. set_base_from "$source" tmpdepfile=$base.d # For projects that build the same source file twice into different object # files, the pgcc approach of using the *source* file root name can cause # problems in parallel builds. Use a locking strategy to avoid stomping on # the same $tmpdepfile. lockdir=$base.d-lock trap " echo '$0: caught signal, cleaning up...' >&2 rmdir '$lockdir' exit 1 " 1 2 13 15 numtries=100 i=$numtries while test $i -gt 0; do # mkdir is a portable test-and-set. if mkdir "$lockdir" 2>/dev/null; then # This process acquired the lock. "$@" -MD stat=$? # Release the lock. rmdir "$lockdir" break else # If the lock is being held by a different process, wait # until the winning process is done or we timeout. while test -d "$lockdir" && test $i -gt 0; do sleep 1 i=`expr $i - 1` done fi i=`expr $i - 1` done trap - 1 2 13 15 if test $i -le 0; then echo "$0: failed to acquire lock after $numtries attempts" >&2 echo "$0: check lockdir '$lockdir'" >&2 exit 1 fi if test $stat -ne 0; then rm -f "$tmpdepfile" exit $stat fi rm -f "$depfile" # Each line is of the form `foo.o: dependent.h', # or `foo.o: dep1.h dep2.h \', or ` dep3.h dep4.h \'. # Do two passes, one to just change these to # `$object: dependent.h' and one to simply `dependent.h:'. sed "s,^[^:]*:,$object :," < "$tmpdepfile" > "$depfile" # Some versions of the HPUX 10.20 sed can't process this invocation # correctly. Breaking it into two sed invocations is a workaround. sed 's,^[^:]*: \(.*\)$,\1,;s/^\\$//;/^$/d;/:$/d' < "$tmpdepfile" \ | sed -e 's/$/ :/' >> "$depfile" rm -f "$tmpdepfile" ;; hp2) # The "hp" stanza above does not work with aCC (C++) and HP's ia64 # compilers, which have integrated preprocessors. The correct option # to use with these is +Maked; it writes dependencies to a file named # 'foo.d', which lands next to the object file, wherever that # happens to be. # Much of this is similar to the tru64 case; see comments there. set_dir_from "$object" set_base_from "$object" if test "$libtool" = yes; then tmpdepfile1=$dir$base.d tmpdepfile2=$dir.libs/$base.d "$@" -Wc,+Maked else tmpdepfile1=$dir$base.d tmpdepfile2=$dir$base.d "$@" +Maked fi stat=$? if test $stat -ne 0; then rm -f "$tmpdepfile1" "$tmpdepfile2" exit $stat fi for tmpdepfile in "$tmpdepfile1" "$tmpdepfile2" do test -f "$tmpdepfile" && break done if test -f "$tmpdepfile"; then sed -e "s,^.*\.[$lower]*:,$object:," "$tmpdepfile" > "$depfile" # Add 'dependent.h:' lines. sed -ne '2,${ s/^ *// s/ \\*$// s/$/:/ p }' "$tmpdepfile" >> "$depfile" else make_dummy_depfile fi rm -f "$tmpdepfile" "$tmpdepfile2" ;; tru64) # The Tru64 compiler uses -MD to generate dependencies as a side # effect. 'cc -MD -o foo.o ...' puts the dependencies into 'foo.o.d'. # At least on Alpha/Redhat 6.1, Compaq CCC V6.2-504 seems to put # dependencies in 'foo.d' instead, so we check for that too. # Subdirectories are respected. set_dir_from "$object" set_base_from "$object" if test "$libtool" = yes; then # Libtool generates 2 separate objects for the 2 libraries. These # two compilations output dependencies in $dir.libs/$base.o.d and # in $dir$base.o.d. We have to check for both files, because # one of the two compilations can be disabled. We should prefer # $dir$base.o.d over $dir.libs/$base.o.d because the latter is # automatically cleaned when .libs/ is deleted, while ignoring # the former would cause a distcleancheck panic. tmpdepfile1=$dir$base.o.d # libtool 1.5 tmpdepfile2=$dir.libs/$base.o.d # Likewise. tmpdepfile3=$dir.libs/$base.d # Compaq CCC V6.2-504 "$@" -Wc,-MD else tmpdepfile1=$dir$base.d tmpdepfile2=$dir$base.d tmpdepfile3=$dir$base.d "$@" -MD fi stat=$? if test $stat -ne 0; then rm -f "$tmpdepfile1" "$tmpdepfile2" "$tmpdepfile3" exit $stat fi for tmpdepfile in "$tmpdepfile1" "$tmpdepfile2" "$tmpdepfile3" do test -f "$tmpdepfile" && break done # Same post-processing that is required for AIX mode. aix_post_process_depfile ;; msvc7) if test "$libtool" = yes; then showIncludes=-Wc,-showIncludes else showIncludes=-showIncludes fi "$@" $showIncludes > "$tmpdepfile" stat=$? grep -v '^Note: including file: ' "$tmpdepfile" if test $stat -ne 0; then rm -f "$tmpdepfile" exit $stat fi rm -f "$depfile" echo "$object : \\" > "$depfile" # The first sed program below extracts the file names and escapes # backslashes for cygpath. The second sed program outputs the file # name when reading, but also accumulates all include files in the # hold buffer in order to output them again at the end. This only # works with sed implementations that can handle large buffers. sed < "$tmpdepfile" -n ' /^Note: including file: *\(.*\)/ { s//\1/ s/\\/\\\\/g p }' | $cygpath_u | sort -u | sed -n ' s/ /\\ /g s/\(.*\)/'"$tab"'\1 \\/p s/.\(.*\) \\/\1:/ H $ { s/.*/'"$tab"'/ G p }' >> "$depfile" echo >> "$depfile" # make sure the fragment doesn't end with a backslash rm -f "$tmpdepfile" ;; msvc7msys) # This case exists only to let depend.m4 do its work. It works by # looking at the text of this script. This case will never be run, # since it is checked for above. exit 1 ;; #nosideeffect) # This comment above is used by automake to tell side-effect # dependency tracking mechanisms from slower ones. dashmstdout) # Important note: in order to support this mode, a compiler *must* # always write the preprocessed file to stdout, regardless of -o. "$@" || exit $? # Remove the call to Libtool. if test "$libtool" = yes; then while test "X$1" != 'X--mode=compile'; do shift done shift fi # Remove '-o $object'. IFS=" " for arg do case $arg in -o) shift ;; $object) shift ;; *) set fnord "$@" "$arg" shift # fnord shift # $arg ;; esac done test -z "$dashmflag" && dashmflag=-M # Require at least two characters before searching for ':' # in the target name. This is to cope with DOS-style filenames: # a dependency such as 'c:/foo/bar' could be seen as target 'c' otherwise. "$@" $dashmflag | sed "s|^[$tab ]*[^:$tab ][^:][^:]*:[$tab ]*|$object: |" > "$tmpdepfile" rm -f "$depfile" cat < "$tmpdepfile" > "$depfile" # Some versions of the HPUX 10.20 sed can't process this sed invocation # correctly. Breaking it into two sed invocations is a workaround. tr ' ' "$nl" < "$tmpdepfile" \ | sed -e 's/^\\$//' -e '/^$/d' -e '/:$/d' \ | sed -e 's/$/ :/' >> "$depfile" rm -f "$tmpdepfile" ;; dashXmstdout) # This case only exists to satisfy depend.m4. It is never actually # run, as this mode is specially recognized in the preamble. exit 1 ;; makedepend) "$@" || exit $? # Remove any Libtool call if test "$libtool" = yes; then while test "X$1" != 'X--mode=compile'; do shift done shift fi # X makedepend shift cleared=no eat=no for arg do case $cleared in no) set ""; shift cleared=yes ;; esac if test $eat = yes; then eat=no continue fi case "$arg" in -D*|-I*) set fnord "$@" "$arg"; shift ;; # Strip any option that makedepend may not understand. Remove # the object too, otherwise makedepend will parse it as a source file. -arch) eat=yes ;; -*|$object) ;; *) set fnord "$@" "$arg"; shift ;; esac done obj_suffix=`echo "$object" | sed 's/^.*\././'` touch "$tmpdepfile" ${MAKEDEPEND-makedepend} -o"$obj_suffix" -f"$tmpdepfile" "$@" rm -f "$depfile" # makedepend may prepend the VPATH from the source file name to the object. # No need to regex-escape $object, excess matching of '.' is harmless. sed "s|^.*\($object *:\)|\1|" "$tmpdepfile" > "$depfile" # Some versions of the HPUX 10.20 sed can't process the last invocation # correctly. Breaking it into two sed invocations is a workaround. sed '1,2d' "$tmpdepfile" \ | tr ' ' "$nl" \ | sed -e 's/^\\$//' -e '/^$/d' -e '/:$/d' \ | sed -e 's/$/ :/' >> "$depfile" rm -f "$tmpdepfile" "$tmpdepfile".bak ;; cpp) # Important note: in order to support this mode, a compiler *must* # always write the preprocessed file to stdout. "$@" || exit $? # Remove the call to Libtool. if test "$libtool" = yes; then while test "X$1" != 'X--mode=compile'; do shift done shift fi # Remove '-o $object'. IFS=" " for arg do case $arg in -o) shift ;; $object) shift ;; *) set fnord "$@" "$arg" shift # fnord shift # $arg ;; esac done "$@" -E \ | sed -n -e '/^# [0-9][0-9]* "\([^"]*\)".*/ s:: \1 \\:p' \ -e '/^#line [0-9][0-9]* "\([^"]*\)".*/ s:: \1 \\:p' \ | sed '$ s: \\$::' > "$tmpdepfile" rm -f "$depfile" echo "$object : \\" > "$depfile" cat < "$tmpdepfile" >> "$depfile" sed < "$tmpdepfile" '/^$/d;s/^ //;s/ \\$//;s/$/ :/' >> "$depfile" rm -f "$tmpdepfile" ;; msvisualcpp) # Important note: in order to support this mode, a compiler *must* # always write the preprocessed file to stdout. "$@" || exit $? # Remove the call to Libtool. if test "$libtool" = yes; then while test "X$1" != 'X--mode=compile'; do shift done shift fi IFS=" " for arg do case "$arg" in -o) shift ;; $object) shift ;; "-Gm"|"/Gm"|"-Gi"|"/Gi"|"-ZI"|"/ZI") set fnord "$@" shift shift ;; *) set fnord "$@" "$arg" shift shift ;; esac done "$@" -E 2>/dev/null | sed -n '/^#line [0-9][0-9]* "\([^"]*\)"/ s::\1:p' | $cygpath_u | sort -u > "$tmpdepfile" rm -f "$depfile" echo "$object : \\" > "$depfile" sed < "$tmpdepfile" -n -e 's% %\\ %g' -e '/^\(.*\)$/ s::'"$tab"'\1 \\:p' >> "$depfile" echo "$tab" >> "$depfile" sed < "$tmpdepfile" -n -e 's% %\\ %g' -e '/^\(.*\)$/ s::\1\::p' >> "$depfile" rm -f "$tmpdepfile" ;; msvcmsys) # This case exists only to let depend.m4 do its work. It works by # looking at the text of this script. This case will never be run, # since it is checked for above. exit 1 ;; none) exec "$@" ;; *) echo "Unknown depmode $depmode" 1>&2 exit 1 ;; esac exit 0 # Local Variables: # mode: shell-script # sh-indentation: 2 # eval: (add-hook 'write-file-hooks 'time-stamp) # time-stamp-start: "scriptversion=" # time-stamp-format: "%:y-%02m-%02d.%02H" # time-stamp-time-zone: "UTC0" # time-stamp-end: "; # UTC" # End: heimdal-7.5.0/lib/libedit/config.guess0000755000175000017500000012634313212444505015765 0ustar niknik#! /bin/sh # Attempt to guess a canonical system name. # Copyright 1992-2017 Free Software Foundation, Inc. timestamp='2017-05-27' # This file is free software; you can redistribute it and/or modify it # under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, see . # # As a special exception to the GNU General Public License, if you # distribute this file as part of a program that contains a # configuration script generated by Autoconf, you may include it under # the same distribution terms that you use for the rest of that # program. This Exception is an additional permission under section 7 # of the GNU General Public License, version 3 ("GPLv3"). # # Originally written by Per Bothner; maintained since 2000 by Ben Elliston. # # You can get the latest version of this script from: # http://git.savannah.gnu.org/gitweb/?p=config.git;a=blob_plain;f=config.guess # # Please send patches to . me=`echo "$0" | sed -e 's,.*/,,'` usage="\ Usage: $0 [OPTION] Output the configuration name of the system \`$me' is run on. Operation modes: -h, --help print this help, then exit -t, --time-stamp print date of last modification, then exit -v, --version print version number, then exit Report bugs and patches to ." version="\ GNU config.guess ($timestamp) Originally written by Per Bothner. Copyright 1992-2017 Free Software Foundation, Inc. This is free software; see the source for copying conditions. There is NO warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE." help=" Try \`$me --help' for more information." # Parse command line while test $# -gt 0 ; do case $1 in --time-stamp | --time* | -t ) echo "$timestamp" ; exit ;; --version | -v ) echo "$version" ; exit ;; --help | --h* | -h ) echo "$usage"; exit ;; -- ) # Stop option processing shift; break ;; - ) # Use stdin as input. break ;; -* ) echo "$me: invalid option $1$help" >&2 exit 1 ;; * ) break ;; esac done if test $# != 0; then echo "$me: too many arguments$help" >&2 exit 1 fi trap 'exit 1' 1 2 15 # CC_FOR_BUILD -- compiler used by this script. Note that the use of a # compiler to aid in system detection is discouraged as it requires # temporary files to be created and, as you can see below, it is a # headache to deal with in a portable fashion. # Historically, `CC_FOR_BUILD' used to be named `HOST_CC'. We still # use `HOST_CC' if defined, but it is deprecated. # Portable tmp directory creation inspired by the Autoconf team. set_cc_for_build=' trap "exitcode=\$?; (rm -f \$tmpfiles 2>/dev/null; rmdir \$tmp 2>/dev/null) && exit \$exitcode" 0 ; trap "rm -f \$tmpfiles 2>/dev/null; rmdir \$tmp 2>/dev/null; exit 1" 1 2 13 15 ; : ${TMPDIR=/tmp} ; { tmp=`(umask 077 && mktemp -d "$TMPDIR/cgXXXXXX") 2>/dev/null` && test -n "$tmp" && test -d "$tmp" ; } || { test -n "$RANDOM" && tmp=$TMPDIR/cg$$-$RANDOM && (umask 077 && mkdir $tmp) ; } || { tmp=$TMPDIR/cg-$$ && (umask 077 && mkdir $tmp) && echo "Warning: creating insecure temp directory" >&2 ; } || { echo "$me: cannot create a temporary directory in $TMPDIR" >&2 ; exit 1 ; } ; dummy=$tmp/dummy ; tmpfiles="$dummy.c $dummy.o $dummy.rel $dummy" ; case $CC_FOR_BUILD,$HOST_CC,$CC in ,,) echo "int x;" > $dummy.c ; for c in cc gcc c89 c99 ; do if ($c -c -o $dummy.o $dummy.c) >/dev/null 2>&1 ; then CC_FOR_BUILD="$c"; break ; fi ; done ; if test x"$CC_FOR_BUILD" = x ; then CC_FOR_BUILD=no_compiler_found ; fi ;; ,,*) CC_FOR_BUILD=$CC ;; ,*,*) CC_FOR_BUILD=$HOST_CC ;; esac ; set_cc_for_build= ;' # This is needed to find uname on a Pyramid OSx when run in the BSD universe. # (ghazi@noc.rutgers.edu 1994-08-24) if (test -f /.attbin/uname) >/dev/null 2>&1 ; then PATH=$PATH:/.attbin ; export PATH fi UNAME_MACHINE=`(uname -m) 2>/dev/null` || UNAME_MACHINE=unknown UNAME_RELEASE=`(uname -r) 2>/dev/null` || UNAME_RELEASE=unknown UNAME_SYSTEM=`(uname -s) 2>/dev/null` || UNAME_SYSTEM=unknown UNAME_VERSION=`(uname -v) 2>/dev/null` || UNAME_VERSION=unknown case "${UNAME_SYSTEM}" in Linux|GNU|GNU/*) # If the system lacks a compiler, then just pick glibc. # We could probably try harder. LIBC=gnu eval $set_cc_for_build cat <<-EOF > $dummy.c #include #if defined(__UCLIBC__) LIBC=uclibc #elif defined(__dietlibc__) LIBC=dietlibc #else LIBC=gnu #endif EOF eval `$CC_FOR_BUILD -E $dummy.c 2>/dev/null | grep '^LIBC' | sed 's, ,,g'` ;; esac # Note: order is significant - the case branches are not exclusive. case "${UNAME_MACHINE}:${UNAME_SYSTEM}:${UNAME_RELEASE}:${UNAME_VERSION}" in *:NetBSD:*:*) # NetBSD (nbsd) targets should (where applicable) match one or # more of the tuples: *-*-netbsdelf*, *-*-netbsdaout*, # *-*-netbsdecoff* and *-*-netbsd*. For targets that recently # switched to ELF, *-*-netbsd* would select the old # object file format. This provides both forward # compatibility and a consistent mechanism for selecting the # object file format. # # Note: NetBSD doesn't particularly care about the vendor # portion of the name. We always set it to "unknown". sysctl="sysctl -n hw.machine_arch" UNAME_MACHINE_ARCH=`(uname -p 2>/dev/null || \ /sbin/$sysctl 2>/dev/null || \ /usr/sbin/$sysctl 2>/dev/null || \ echo unknown)` case "${UNAME_MACHINE_ARCH}" in armeb) machine=armeb-unknown ;; arm*) machine=arm-unknown ;; sh3el) machine=shl-unknown ;; sh3eb) machine=sh-unknown ;; sh5el) machine=sh5le-unknown ;; earmv*) arch=`echo ${UNAME_MACHINE_ARCH} | sed -e 's,^e\(armv[0-9]\).*$,\1,'` endian=`echo ${UNAME_MACHINE_ARCH} | sed -ne 's,^.*\(eb\)$,\1,p'` machine=${arch}${endian}-unknown ;; *) machine=${UNAME_MACHINE_ARCH}-unknown ;; esac # The Operating System including object format, if it has switched # to ELF recently (or will in the future) and ABI. case "${UNAME_MACHINE_ARCH}" in earm*) os=netbsdelf ;; arm*|i386|m68k|ns32k|sh3*|sparc|vax) eval $set_cc_for_build if echo __ELF__ | $CC_FOR_BUILD -E - 2>/dev/null \ | grep -q __ELF__ then # Once all utilities can be ECOFF (netbsdecoff) or a.out (netbsdaout). # Return netbsd for either. FIX? os=netbsd else os=netbsdelf fi ;; *) os=netbsd ;; esac # Determine ABI tags. case "${UNAME_MACHINE_ARCH}" in earm*) expr='s/^earmv[0-9]/-eabi/;s/eb$//' abi=`echo ${UNAME_MACHINE_ARCH} | sed -e "$expr"` ;; esac # The OS release # Debian GNU/NetBSD machines have a different userland, and # thus, need a distinct triplet. However, they do not need # kernel version information, so it can be replaced with a # suitable tag, in the style of linux-gnu. case "${UNAME_VERSION}" in Debian*) release='-gnu' ;; *) release=`echo ${UNAME_RELEASE} | sed -e 's/[-_].*//' | cut -d. -f1,2` ;; esac # Since CPU_TYPE-MANUFACTURER-KERNEL-OPERATING_SYSTEM: # contains redundant information, the shorter form: # CPU_TYPE-MANUFACTURER-OPERATING_SYSTEM is used. echo "${machine}-${os}${release}${abi}" exit ;; *:Bitrig:*:*) UNAME_MACHINE_ARCH=`arch | sed 's/Bitrig.//'` echo ${UNAME_MACHINE_ARCH}-unknown-bitrig${UNAME_RELEASE} exit ;; *:OpenBSD:*:*) UNAME_MACHINE_ARCH=`arch | sed 's/OpenBSD.//'` echo ${UNAME_MACHINE_ARCH}-unknown-openbsd${UNAME_RELEASE} exit ;; *:LibertyBSD:*:*) UNAME_MACHINE_ARCH=`arch | sed 's/^.*BSD\.//'` echo ${UNAME_MACHINE_ARCH}-unknown-libertybsd${UNAME_RELEASE} exit ;; *:ekkoBSD:*:*) echo ${UNAME_MACHINE}-unknown-ekkobsd${UNAME_RELEASE} exit ;; *:SolidBSD:*:*) echo ${UNAME_MACHINE}-unknown-solidbsd${UNAME_RELEASE} exit ;; macppc:MirBSD:*:*) echo powerpc-unknown-mirbsd${UNAME_RELEASE} exit ;; *:MirBSD:*:*) echo ${UNAME_MACHINE}-unknown-mirbsd${UNAME_RELEASE} exit ;; *:Sortix:*:*) echo ${UNAME_MACHINE}-unknown-sortix exit ;; alpha:OSF1:*:*) case $UNAME_RELEASE in *4.0) UNAME_RELEASE=`/usr/sbin/sizer -v | awk '{print $3}'` ;; *5.*) UNAME_RELEASE=`/usr/sbin/sizer -v | awk '{print $4}'` ;; esac # According to Compaq, /usr/sbin/psrinfo has been available on # OSF/1 and Tru64 systems produced since 1995. I hope that # covers most systems running today. This code pipes the CPU # types through head -n 1, so we only detect the type of CPU 0. ALPHA_CPU_TYPE=`/usr/sbin/psrinfo -v | sed -n -e 's/^ The alpha \(.*\) processor.*$/\1/p' | head -n 1` case "$ALPHA_CPU_TYPE" in "EV4 (21064)") UNAME_MACHINE=alpha ;; "EV4.5 (21064)") UNAME_MACHINE=alpha ;; "LCA4 (21066/21068)") UNAME_MACHINE=alpha ;; "EV5 (21164)") UNAME_MACHINE=alphaev5 ;; "EV5.6 (21164A)") UNAME_MACHINE=alphaev56 ;; "EV5.6 (21164PC)") UNAME_MACHINE=alphapca56 ;; "EV5.7 (21164PC)") UNAME_MACHINE=alphapca57 ;; "EV6 (21264)") UNAME_MACHINE=alphaev6 ;; "EV6.7 (21264A)") UNAME_MACHINE=alphaev67 ;; "EV6.8CB (21264C)") UNAME_MACHINE=alphaev68 ;; "EV6.8AL (21264B)") UNAME_MACHINE=alphaev68 ;; "EV6.8CX (21264D)") UNAME_MACHINE=alphaev68 ;; "EV6.9A (21264/EV69A)") UNAME_MACHINE=alphaev69 ;; "EV7 (21364)") UNAME_MACHINE=alphaev7 ;; "EV7.9 (21364A)") UNAME_MACHINE=alphaev79 ;; esac # A Pn.n version is a patched version. # A Vn.n version is a released version. # A Tn.n version is a released field test version. # A Xn.n version is an unreleased experimental baselevel. # 1.2 uses "1.2" for uname -r. echo ${UNAME_MACHINE}-dec-osf`echo ${UNAME_RELEASE} | sed -e 's/^[PVTX]//' | tr ABCDEFGHIJKLMNOPQRSTUVWXYZ abcdefghijklmnopqrstuvwxyz` # Reset EXIT trap before exiting to avoid spurious non-zero exit code. exitcode=$? trap '' 0 exit $exitcode ;; Alpha\ *:Windows_NT*:*) # How do we know it's Interix rather than the generic POSIX subsystem? # Should we change UNAME_MACHINE based on the output of uname instead # of the specific Alpha model? echo alpha-pc-interix exit ;; 21064:Windows_NT:50:3) echo alpha-dec-winnt3.5 exit ;; Amiga*:UNIX_System_V:4.0:*) echo m68k-unknown-sysv4 exit ;; *:[Aa]miga[Oo][Ss]:*:*) echo ${UNAME_MACHINE}-unknown-amigaos exit ;; *:[Mm]orph[Oo][Ss]:*:*) echo ${UNAME_MACHINE}-unknown-morphos exit ;; *:OS/390:*:*) echo i370-ibm-openedition exit ;; *:z/VM:*:*) echo s390-ibm-zvmoe exit ;; *:OS400:*:*) echo powerpc-ibm-os400 exit ;; arm:RISC*:1.[012]*:*|arm:riscix:1.[012]*:*) echo arm-acorn-riscix${UNAME_RELEASE} exit ;; arm*:riscos:*:*|arm*:RISCOS:*:*) echo arm-unknown-riscos exit ;; SR2?01:HI-UX/MPP:*:* | SR8000:HI-UX/MPP:*:*) echo hppa1.1-hitachi-hiuxmpp exit ;; Pyramid*:OSx*:*:* | MIS*:OSx*:*:* | MIS*:SMP_DC-OSx*:*:*) # akee@wpdis03.wpafb.af.mil (Earle F. Ake) contributed MIS and NILE. if test "`(/bin/universe) 2>/dev/null`" = att ; then echo pyramid-pyramid-sysv3 else echo pyramid-pyramid-bsd fi exit ;; NILE*:*:*:dcosx) echo pyramid-pyramid-svr4 exit ;; DRS?6000:unix:4.0:6*) echo sparc-icl-nx6 exit ;; DRS?6000:UNIX_SV:4.2*:7* | DRS?6000:isis:4.2*:7*) case `/usr/bin/uname -p` in sparc) echo sparc-icl-nx7; exit ;; esac ;; s390x:SunOS:*:*) echo ${UNAME_MACHINE}-ibm-solaris2`echo ${UNAME_RELEASE}|sed -e 's/[^.]*//'` exit ;; sun4H:SunOS:5.*:*) echo sparc-hal-solaris2`echo ${UNAME_RELEASE}|sed -e 's/[^.]*//'` exit ;; sun4*:SunOS:5.*:* | tadpole*:SunOS:5.*:*) echo sparc-sun-solaris2`echo ${UNAME_RELEASE}|sed -e 's/[^.]*//'` exit ;; i86pc:AuroraUX:5.*:* | i86xen:AuroraUX:5.*:*) echo i386-pc-auroraux${UNAME_RELEASE} exit ;; i86pc:SunOS:5.*:* | i86xen:SunOS:5.*:*) eval $set_cc_for_build SUN_ARCH=i386 # If there is a compiler, see if it is configured for 64-bit objects. # Note that the Sun cc does not turn __LP64__ into 1 like gcc does. # This test works for both compilers. if [ "$CC_FOR_BUILD" != no_compiler_found ]; then if (echo '#ifdef __amd64'; echo IS_64BIT_ARCH; echo '#endif') | \ (CCOPTS="" $CC_FOR_BUILD -E - 2>/dev/null) | \ grep IS_64BIT_ARCH >/dev/null then SUN_ARCH=x86_64 fi fi echo ${SUN_ARCH}-pc-solaris2`echo ${UNAME_RELEASE}|sed -e 's/[^.]*//'` exit ;; sun4*:SunOS:6*:*) # According to config.sub, this is the proper way to canonicalize # SunOS6. Hard to guess exactly what SunOS6 will be like, but # it's likely to be more like Solaris than SunOS4. echo sparc-sun-solaris3`echo ${UNAME_RELEASE}|sed -e 's/[^.]*//'` exit ;; sun4*:SunOS:*:*) case "`/usr/bin/arch -k`" in Series*|S4*) UNAME_RELEASE=`uname -v` ;; esac # Japanese Language versions have a version number like `4.1.3-JL'. echo sparc-sun-sunos`echo ${UNAME_RELEASE}|sed -e 's/-/_/'` exit ;; sun3*:SunOS:*:*) echo m68k-sun-sunos${UNAME_RELEASE} exit ;; sun*:*:4.2BSD:*) UNAME_RELEASE=`(sed 1q /etc/motd | awk '{print substr($5,1,3)}') 2>/dev/null` test "x${UNAME_RELEASE}" = x && UNAME_RELEASE=3 case "`/bin/arch`" in sun3) echo m68k-sun-sunos${UNAME_RELEASE} ;; sun4) echo sparc-sun-sunos${UNAME_RELEASE} ;; esac exit ;; aushp:SunOS:*:*) echo sparc-auspex-sunos${UNAME_RELEASE} exit ;; # The situation for MiNT is a little confusing. The machine name # can be virtually everything (everything which is not # "atarist" or "atariste" at least should have a processor # > m68000). The system name ranges from "MiNT" over "FreeMiNT" # to the lowercase version "mint" (or "freemint"). Finally # the system name "TOS" denotes a system which is actually not # MiNT. But MiNT is downward compatible to TOS, so this should # be no problem. atarist[e]:*MiNT:*:* | atarist[e]:*mint:*:* | atarist[e]:*TOS:*:*) echo m68k-atari-mint${UNAME_RELEASE} exit ;; atari*:*MiNT:*:* | atari*:*mint:*:* | atarist[e]:*TOS:*:*) echo m68k-atari-mint${UNAME_RELEASE} exit ;; *falcon*:*MiNT:*:* | *falcon*:*mint:*:* | *falcon*:*TOS:*:*) echo m68k-atari-mint${UNAME_RELEASE} exit ;; milan*:*MiNT:*:* | milan*:*mint:*:* | *milan*:*TOS:*:*) echo m68k-milan-mint${UNAME_RELEASE} exit ;; hades*:*MiNT:*:* | hades*:*mint:*:* | *hades*:*TOS:*:*) echo m68k-hades-mint${UNAME_RELEASE} exit ;; *:*MiNT:*:* | *:*mint:*:* | *:*TOS:*:*) echo m68k-unknown-mint${UNAME_RELEASE} exit ;; m68k:machten:*:*) echo m68k-apple-machten${UNAME_RELEASE} exit ;; powerpc:machten:*:*) echo powerpc-apple-machten${UNAME_RELEASE} exit ;; RISC*:Mach:*:*) echo mips-dec-mach_bsd4.3 exit ;; RISC*:ULTRIX:*:*) echo mips-dec-ultrix${UNAME_RELEASE} exit ;; VAX*:ULTRIX*:*:*) echo vax-dec-ultrix${UNAME_RELEASE} exit ;; 2020:CLIX:*:* | 2430:CLIX:*:*) echo clipper-intergraph-clix${UNAME_RELEASE} exit ;; mips:*:*:UMIPS | mips:*:*:RISCos) eval $set_cc_for_build sed 's/^ //' << EOF >$dummy.c #ifdef __cplusplus #include /* for printf() prototype */ int main (int argc, char *argv[]) { #else int main (argc, argv) int argc; char *argv[]; { #endif #if defined (host_mips) && defined (MIPSEB) #if defined (SYSTYPE_SYSV) printf ("mips-mips-riscos%ssysv\n", argv[1]); exit (0); #endif #if defined (SYSTYPE_SVR4) printf ("mips-mips-riscos%ssvr4\n", argv[1]); exit (0); #endif #if defined (SYSTYPE_BSD43) || defined(SYSTYPE_BSD) printf ("mips-mips-riscos%sbsd\n", argv[1]); exit (0); #endif #endif exit (-1); } EOF $CC_FOR_BUILD -o $dummy $dummy.c && dummyarg=`echo "${UNAME_RELEASE}" | sed -n 's/\([0-9]*\).*/\1/p'` && SYSTEM_NAME=`$dummy $dummyarg` && { echo "$SYSTEM_NAME"; exit; } echo mips-mips-riscos${UNAME_RELEASE} exit ;; Motorola:PowerMAX_OS:*:*) echo powerpc-motorola-powermax exit ;; Motorola:*:4.3:PL8-*) echo powerpc-harris-powermax exit ;; Night_Hawk:*:*:PowerMAX_OS | Synergy:PowerMAX_OS:*:*) echo powerpc-harris-powermax exit ;; Night_Hawk:Power_UNIX:*:*) echo powerpc-harris-powerunix exit ;; m88k:CX/UX:7*:*) echo m88k-harris-cxux7 exit ;; m88k:*:4*:R4*) echo m88k-motorola-sysv4 exit ;; m88k:*:3*:R3*) echo m88k-motorola-sysv3 exit ;; AViiON:dgux:*:*) # DG/UX returns AViiON for all architectures UNAME_PROCESSOR=`/usr/bin/uname -p` if [ $UNAME_PROCESSOR = mc88100 ] || [ $UNAME_PROCESSOR = mc88110 ] then if [ ${TARGET_BINARY_INTERFACE}x = m88kdguxelfx ] || \ [ ${TARGET_BINARY_INTERFACE}x = x ] then echo m88k-dg-dgux${UNAME_RELEASE} else echo m88k-dg-dguxbcs${UNAME_RELEASE} fi else echo i586-dg-dgux${UNAME_RELEASE} fi exit ;; M88*:DolphinOS:*:*) # DolphinOS (SVR3) echo m88k-dolphin-sysv3 exit ;; M88*:*:R3*:*) # Delta 88k system running SVR3 echo m88k-motorola-sysv3 exit ;; XD88*:*:*:*) # Tektronix XD88 system running UTekV (SVR3) echo m88k-tektronix-sysv3 exit ;; Tek43[0-9][0-9]:UTek:*:*) # Tektronix 4300 system running UTek (BSD) echo m68k-tektronix-bsd exit ;; *:IRIX*:*:*) echo mips-sgi-irix`echo ${UNAME_RELEASE}|sed -e 's/-/_/g'` exit ;; ????????:AIX?:[12].1:2) # AIX 2.2.1 or AIX 2.1.1 is RT/PC AIX. echo romp-ibm-aix # uname -m gives an 8 hex-code CPU id exit ;; # Note that: echo "'`uname -s`'" gives 'AIX ' i*86:AIX:*:*) echo i386-ibm-aix exit ;; ia64:AIX:*:*) if [ -x /usr/bin/oslevel ] ; then IBM_REV=`/usr/bin/oslevel` else IBM_REV=${UNAME_VERSION}.${UNAME_RELEASE} fi echo ${UNAME_MACHINE}-ibm-aix${IBM_REV} exit ;; *:AIX:2:3) if grep bos325 /usr/include/stdio.h >/dev/null 2>&1; then eval $set_cc_for_build sed 's/^ //' << EOF >$dummy.c #include main() { if (!__power_pc()) exit(1); puts("powerpc-ibm-aix3.2.5"); exit(0); } EOF if $CC_FOR_BUILD -o $dummy $dummy.c && SYSTEM_NAME=`$dummy` then echo "$SYSTEM_NAME" else echo rs6000-ibm-aix3.2.5 fi elif grep bos324 /usr/include/stdio.h >/dev/null 2>&1; then echo rs6000-ibm-aix3.2.4 else echo rs6000-ibm-aix3.2 fi exit ;; *:AIX:*:[4567]) IBM_CPU_ID=`/usr/sbin/lsdev -C -c processor -S available | sed 1q | awk '{ print $1 }'` if /usr/sbin/lsattr -El ${IBM_CPU_ID} | grep ' POWER' >/dev/null 2>&1; then IBM_ARCH=rs6000 else IBM_ARCH=powerpc fi if [ -x /usr/bin/lslpp ] ; then IBM_REV=`/usr/bin/lslpp -Lqc bos.rte.libc | awk -F: '{ print $3 }' | sed s/[0-9]*$/0/` else IBM_REV=${UNAME_VERSION}.${UNAME_RELEASE} fi echo ${IBM_ARCH}-ibm-aix${IBM_REV} exit ;; *:AIX:*:*) echo rs6000-ibm-aix exit ;; ibmrt:4.4BSD:*|romp-ibm:BSD:*) echo romp-ibm-bsd4.4 exit ;; ibmrt:*BSD:*|romp-ibm:BSD:*) # covers RT/PC BSD and echo romp-ibm-bsd${UNAME_RELEASE} # 4.3 with uname added to exit ;; # report: romp-ibm BSD 4.3 *:BOSX:*:*) echo rs6000-bull-bosx exit ;; DPX/2?00:B.O.S.:*:*) echo m68k-bull-sysv3 exit ;; 9000/[34]??:4.3bsd:1.*:*) echo m68k-hp-bsd exit ;; hp300:4.4BSD:*:* | 9000/[34]??:4.3bsd:2.*:*) echo m68k-hp-bsd4.4 exit ;; 9000/[34678]??:HP-UX:*:*) HPUX_REV=`echo ${UNAME_RELEASE}|sed -e 's/[^.]*.[0B]*//'` case "${UNAME_MACHINE}" in 9000/31? ) HP_ARCH=m68000 ;; 9000/[34]?? ) HP_ARCH=m68k ;; 9000/[678][0-9][0-9]) if [ -x /usr/bin/getconf ]; then sc_cpu_version=`/usr/bin/getconf SC_CPU_VERSION 2>/dev/null` sc_kernel_bits=`/usr/bin/getconf SC_KERNEL_BITS 2>/dev/null` case "${sc_cpu_version}" in 523) HP_ARCH=hppa1.0 ;; # CPU_PA_RISC1_0 528) HP_ARCH=hppa1.1 ;; # CPU_PA_RISC1_1 532) # CPU_PA_RISC2_0 case "${sc_kernel_bits}" in 32) HP_ARCH=hppa2.0n ;; 64) HP_ARCH=hppa2.0w ;; '') HP_ARCH=hppa2.0 ;; # HP-UX 10.20 esac ;; esac fi if [ "${HP_ARCH}" = "" ]; then eval $set_cc_for_build sed 's/^ //' << EOF >$dummy.c #define _HPUX_SOURCE #include #include int main () { #if defined(_SC_KERNEL_BITS) long bits = sysconf(_SC_KERNEL_BITS); #endif long cpu = sysconf (_SC_CPU_VERSION); switch (cpu) { case CPU_PA_RISC1_0: puts ("hppa1.0"); break; case CPU_PA_RISC1_1: puts ("hppa1.1"); break; case CPU_PA_RISC2_0: #if defined(_SC_KERNEL_BITS) switch (bits) { case 64: puts ("hppa2.0w"); break; case 32: puts ("hppa2.0n"); break; default: puts ("hppa2.0"); break; } break; #else /* !defined(_SC_KERNEL_BITS) */ puts ("hppa2.0"); break; #endif default: puts ("hppa1.0"); break; } exit (0); } EOF (CCOPTS="" $CC_FOR_BUILD -o $dummy $dummy.c 2>/dev/null) && HP_ARCH=`$dummy` test -z "$HP_ARCH" && HP_ARCH=hppa fi ;; esac if [ ${HP_ARCH} = hppa2.0w ] then eval $set_cc_for_build # hppa2.0w-hp-hpux* has a 64-bit kernel and a compiler generating # 32-bit code. hppa64-hp-hpux* has the same kernel and a compiler # generating 64-bit code. GNU and HP use different nomenclature: # # $ CC_FOR_BUILD=cc ./config.guess # => hppa2.0w-hp-hpux11.23 # $ CC_FOR_BUILD="cc +DA2.0w" ./config.guess # => hppa64-hp-hpux11.23 if echo __LP64__ | (CCOPTS="" $CC_FOR_BUILD -E - 2>/dev/null) | grep -q __LP64__ then HP_ARCH=hppa2.0w else HP_ARCH=hppa64 fi fi echo ${HP_ARCH}-hp-hpux${HPUX_REV} exit ;; ia64:HP-UX:*:*) HPUX_REV=`echo ${UNAME_RELEASE}|sed -e 's/[^.]*.[0B]*//'` echo ia64-hp-hpux${HPUX_REV} exit ;; 3050*:HI-UX:*:*) eval $set_cc_for_build sed 's/^ //' << EOF >$dummy.c #include int main () { long cpu = sysconf (_SC_CPU_VERSION); /* The order matters, because CPU_IS_HP_MC68K erroneously returns true for CPU_PA_RISC1_0. CPU_IS_PA_RISC returns correct results, however. */ if (CPU_IS_PA_RISC (cpu)) { switch (cpu) { case CPU_PA_RISC1_0: puts ("hppa1.0-hitachi-hiuxwe2"); break; case CPU_PA_RISC1_1: puts ("hppa1.1-hitachi-hiuxwe2"); break; case CPU_PA_RISC2_0: puts ("hppa2.0-hitachi-hiuxwe2"); break; default: puts ("hppa-hitachi-hiuxwe2"); break; } } else if (CPU_IS_HP_MC68K (cpu)) puts ("m68k-hitachi-hiuxwe2"); else puts ("unknown-hitachi-hiuxwe2"); exit (0); } EOF $CC_FOR_BUILD -o $dummy $dummy.c && SYSTEM_NAME=`$dummy` && { echo "$SYSTEM_NAME"; exit; } echo unknown-hitachi-hiuxwe2 exit ;; 9000/7??:4.3bsd:*:* | 9000/8?[79]:4.3bsd:*:* ) echo hppa1.1-hp-bsd exit ;; 9000/8??:4.3bsd:*:*) echo hppa1.0-hp-bsd exit ;; *9??*:MPE/iX:*:* | *3000*:MPE/iX:*:*) echo hppa1.0-hp-mpeix exit ;; hp7??:OSF1:*:* | hp8?[79]:OSF1:*:* ) echo hppa1.1-hp-osf exit ;; hp8??:OSF1:*:*) echo hppa1.0-hp-osf exit ;; i*86:OSF1:*:*) if [ -x /usr/sbin/sysversion ] ; then echo ${UNAME_MACHINE}-unknown-osf1mk else echo ${UNAME_MACHINE}-unknown-osf1 fi exit ;; parisc*:Lites*:*:*) echo hppa1.1-hp-lites exit ;; C1*:ConvexOS:*:* | convex:ConvexOS:C1*:*) echo c1-convex-bsd exit ;; C2*:ConvexOS:*:* | convex:ConvexOS:C2*:*) if getsysinfo -f scalar_acc then echo c32-convex-bsd else echo c2-convex-bsd fi exit ;; C34*:ConvexOS:*:* | convex:ConvexOS:C34*:*) echo c34-convex-bsd exit ;; C38*:ConvexOS:*:* | convex:ConvexOS:C38*:*) echo c38-convex-bsd exit ;; C4*:ConvexOS:*:* | convex:ConvexOS:C4*:*) echo c4-convex-bsd exit ;; CRAY*Y-MP:*:*:*) echo ymp-cray-unicos${UNAME_RELEASE} | sed -e 's/\.[^.]*$/.X/' exit ;; CRAY*[A-Z]90:*:*:*) echo ${UNAME_MACHINE}-cray-unicos${UNAME_RELEASE} \ | sed -e 's/CRAY.*\([A-Z]90\)/\1/' \ -e y/ABCDEFGHIJKLMNOPQRSTUVWXYZ/abcdefghijklmnopqrstuvwxyz/ \ -e 's/\.[^.]*$/.X/' exit ;; CRAY*TS:*:*:*) echo t90-cray-unicos${UNAME_RELEASE} | sed -e 's/\.[^.]*$/.X/' exit ;; CRAY*T3E:*:*:*) echo alphaev5-cray-unicosmk${UNAME_RELEASE} | sed -e 's/\.[^.]*$/.X/' exit ;; CRAY*SV1:*:*:*) echo sv1-cray-unicos${UNAME_RELEASE} | sed -e 's/\.[^.]*$/.X/' exit ;; *:UNICOS/mp:*:*) echo craynv-cray-unicosmp${UNAME_RELEASE} | sed -e 's/\.[^.]*$/.X/' exit ;; F30[01]:UNIX_System_V:*:* | F700:UNIX_System_V:*:*) FUJITSU_PROC=`uname -m | tr ABCDEFGHIJKLMNOPQRSTUVWXYZ abcdefghijklmnopqrstuvwxyz` FUJITSU_SYS=`uname -p | tr ABCDEFGHIJKLMNOPQRSTUVWXYZ abcdefghijklmnopqrstuvwxyz | sed -e 's/\///'` FUJITSU_REL=`echo ${UNAME_RELEASE} | sed -e 's/ /_/'` echo "${FUJITSU_PROC}-fujitsu-${FUJITSU_SYS}${FUJITSU_REL}" exit ;; 5000:UNIX_System_V:4.*:*) FUJITSU_SYS=`uname -p | tr ABCDEFGHIJKLMNOPQRSTUVWXYZ abcdefghijklmnopqrstuvwxyz | sed -e 's/\///'` FUJITSU_REL=`echo ${UNAME_RELEASE} | tr ABCDEFGHIJKLMNOPQRSTUVWXYZ abcdefghijklmnopqrstuvwxyz | sed -e 's/ /_/'` echo "sparc-fujitsu-${FUJITSU_SYS}${FUJITSU_REL}" exit ;; i*86:BSD/386:*:* | i*86:BSD/OS:*:* | *:Ascend\ Embedded/OS:*:*) echo ${UNAME_MACHINE}-pc-bsdi${UNAME_RELEASE} exit ;; sparc*:BSD/OS:*:*) echo sparc-unknown-bsdi${UNAME_RELEASE} exit ;; *:BSD/OS:*:*) echo ${UNAME_MACHINE}-unknown-bsdi${UNAME_RELEASE} exit ;; *:FreeBSD:*:*) UNAME_PROCESSOR=`/usr/bin/uname -p` case ${UNAME_PROCESSOR} in amd64) UNAME_PROCESSOR=x86_64 ;; i386) UNAME_PROCESSOR=i586 ;; esac echo ${UNAME_PROCESSOR}-unknown-freebsd`echo ${UNAME_RELEASE}|sed -e 's/[-(].*//'` exit ;; i*:CYGWIN*:*) echo ${UNAME_MACHINE}-pc-cygwin exit ;; *:MINGW64*:*) echo ${UNAME_MACHINE}-pc-mingw64 exit ;; *:MINGW*:*) echo ${UNAME_MACHINE}-pc-mingw32 exit ;; *:MSYS*:*) echo ${UNAME_MACHINE}-pc-msys exit ;; i*:windows32*:*) # uname -m includes "-pc" on this system. echo ${UNAME_MACHINE}-mingw32 exit ;; i*:PW*:*) echo ${UNAME_MACHINE}-pc-pw32 exit ;; *:Interix*:*) case ${UNAME_MACHINE} in x86) echo i586-pc-interix${UNAME_RELEASE} exit ;; authenticamd | genuineintel | EM64T) echo x86_64-unknown-interix${UNAME_RELEASE} exit ;; IA64) echo ia64-unknown-interix${UNAME_RELEASE} exit ;; esac ;; [345]86:Windows_95:* | [345]86:Windows_98:* | [345]86:Windows_NT:*) echo i${UNAME_MACHINE}-pc-mks exit ;; 8664:Windows_NT:*) echo x86_64-pc-mks exit ;; i*:Windows_NT*:* | Pentium*:Windows_NT*:*) # How do we know it's Interix rather than the generic POSIX subsystem? # It also conflicts with pre-2.0 versions of AT&T UWIN. Should we # UNAME_MACHINE based on the output of uname instead of i386? echo i586-pc-interix exit ;; i*:UWIN*:*) echo ${UNAME_MACHINE}-pc-uwin exit ;; amd64:CYGWIN*:*:* | x86_64:CYGWIN*:*:*) echo x86_64-unknown-cygwin exit ;; p*:CYGWIN*:*) echo powerpcle-unknown-cygwin exit ;; prep*:SunOS:5.*:*) echo powerpcle-unknown-solaris2`echo ${UNAME_RELEASE}|sed -e 's/[^.]*//'` exit ;; *:GNU:*:*) # the GNU system echo `echo ${UNAME_MACHINE}|sed -e 's,[-/].*$,,'`-unknown-${LIBC}`echo ${UNAME_RELEASE}|sed -e 's,/.*$,,'` exit ;; *:GNU/*:*:*) # other systems with GNU libc and userland echo ${UNAME_MACHINE}-unknown-`echo ${UNAME_SYSTEM} | sed 's,^[^/]*/,,' | tr "[:upper:]" "[:lower:]"``echo ${UNAME_RELEASE}|sed -e 's/[-(].*//'`-${LIBC} exit ;; i*86:Minix:*:*) echo ${UNAME_MACHINE}-pc-minix exit ;; aarch64:Linux:*:*) echo ${UNAME_MACHINE}-unknown-linux-${LIBC} exit ;; aarch64_be:Linux:*:*) UNAME_MACHINE=aarch64_be echo ${UNAME_MACHINE}-unknown-linux-${LIBC} exit ;; alpha:Linux:*:*) case `sed -n '/^cpu model/s/^.*: \(.*\)/\1/p' < /proc/cpuinfo` in EV5) UNAME_MACHINE=alphaev5 ;; EV56) UNAME_MACHINE=alphaev56 ;; PCA56) UNAME_MACHINE=alphapca56 ;; PCA57) UNAME_MACHINE=alphapca56 ;; EV6) UNAME_MACHINE=alphaev6 ;; EV67) UNAME_MACHINE=alphaev67 ;; EV68*) UNAME_MACHINE=alphaev68 ;; esac objdump --private-headers /bin/sh | grep -q ld.so.1 if test "$?" = 0 ; then LIBC=gnulibc1 ; fi echo ${UNAME_MACHINE}-unknown-linux-${LIBC} exit ;; arc:Linux:*:* | arceb:Linux:*:*) echo ${UNAME_MACHINE}-unknown-linux-${LIBC} exit ;; arm*:Linux:*:*) eval $set_cc_for_build if echo __ARM_EABI__ | $CC_FOR_BUILD -E - 2>/dev/null \ | grep -q __ARM_EABI__ then echo ${UNAME_MACHINE}-unknown-linux-${LIBC} else if echo __ARM_PCS_VFP | $CC_FOR_BUILD -E - 2>/dev/null \ | grep -q __ARM_PCS_VFP then echo ${UNAME_MACHINE}-unknown-linux-${LIBC}eabi else echo ${UNAME_MACHINE}-unknown-linux-${LIBC}eabihf fi fi exit ;; avr32*:Linux:*:*) echo ${UNAME_MACHINE}-unknown-linux-${LIBC} exit ;; cris:Linux:*:*) echo ${UNAME_MACHINE}-axis-linux-${LIBC} exit ;; crisv32:Linux:*:*) echo ${UNAME_MACHINE}-axis-linux-${LIBC} exit ;; e2k:Linux:*:*) echo ${UNAME_MACHINE}-unknown-linux-${LIBC} exit ;; frv:Linux:*:*) echo ${UNAME_MACHINE}-unknown-linux-${LIBC} exit ;; hexagon:Linux:*:*) echo ${UNAME_MACHINE}-unknown-linux-${LIBC} exit ;; i*86:Linux:*:*) echo ${UNAME_MACHINE}-pc-linux-${LIBC} exit ;; ia64:Linux:*:*) echo ${UNAME_MACHINE}-unknown-linux-${LIBC} exit ;; k1om:Linux:*:*) echo ${UNAME_MACHINE}-unknown-linux-${LIBC} exit ;; m32r*:Linux:*:*) echo ${UNAME_MACHINE}-unknown-linux-${LIBC} exit ;; m68*:Linux:*:*) echo ${UNAME_MACHINE}-unknown-linux-${LIBC} exit ;; mips:Linux:*:* | mips64:Linux:*:*) eval $set_cc_for_build sed 's/^ //' << EOF >$dummy.c #undef CPU #undef ${UNAME_MACHINE} #undef ${UNAME_MACHINE}el #if defined(__MIPSEL__) || defined(__MIPSEL) || defined(_MIPSEL) || defined(MIPSEL) CPU=${UNAME_MACHINE}el #else #if defined(__MIPSEB__) || defined(__MIPSEB) || defined(_MIPSEB) || defined(MIPSEB) CPU=${UNAME_MACHINE} #else CPU= #endif #endif EOF eval `$CC_FOR_BUILD -E $dummy.c 2>/dev/null | grep '^CPU'` test x"${CPU}" != x && { echo "${CPU}-unknown-linux-${LIBC}"; exit; } ;; mips64el:Linux:*:*) echo ${UNAME_MACHINE}-unknown-linux-${LIBC} exit ;; openrisc*:Linux:*:*) echo or1k-unknown-linux-${LIBC} exit ;; or32:Linux:*:* | or1k*:Linux:*:*) echo ${UNAME_MACHINE}-unknown-linux-${LIBC} exit ;; padre:Linux:*:*) echo sparc-unknown-linux-${LIBC} exit ;; parisc64:Linux:*:* | hppa64:Linux:*:*) echo hppa64-unknown-linux-${LIBC} exit ;; parisc:Linux:*:* | hppa:Linux:*:*) # Look for CPU level case `grep '^cpu[^a-z]*:' /proc/cpuinfo 2>/dev/null | cut -d' ' -f2` in PA7*) echo hppa1.1-unknown-linux-${LIBC} ;; PA8*) echo hppa2.0-unknown-linux-${LIBC} ;; *) echo hppa-unknown-linux-${LIBC} ;; esac exit ;; ppc64:Linux:*:*) echo powerpc64-unknown-linux-${LIBC} exit ;; ppc:Linux:*:*) echo powerpc-unknown-linux-${LIBC} exit ;; ppc64le:Linux:*:*) echo powerpc64le-unknown-linux-${LIBC} exit ;; ppcle:Linux:*:*) echo powerpcle-unknown-linux-${LIBC} exit ;; riscv32:Linux:*:* | riscv64:Linux:*:*) echo ${UNAME_MACHINE}-unknown-linux-${LIBC} exit ;; s390:Linux:*:* | s390x:Linux:*:*) echo ${UNAME_MACHINE}-ibm-linux-${LIBC} exit ;; sh64*:Linux:*:*) echo ${UNAME_MACHINE}-unknown-linux-${LIBC} exit ;; sh*:Linux:*:*) echo ${UNAME_MACHINE}-unknown-linux-${LIBC} exit ;; sparc:Linux:*:* | sparc64:Linux:*:*) echo ${UNAME_MACHINE}-unknown-linux-${LIBC} exit ;; tile*:Linux:*:*) echo ${UNAME_MACHINE}-unknown-linux-${LIBC} exit ;; vax:Linux:*:*) echo ${UNAME_MACHINE}-dec-linux-${LIBC} exit ;; x86_64:Linux:*:*) echo ${UNAME_MACHINE}-pc-linux-${LIBC} exit ;; xtensa*:Linux:*:*) echo ${UNAME_MACHINE}-unknown-linux-${LIBC} exit ;; i*86:DYNIX/ptx:4*:*) # ptx 4.0 does uname -s correctly, with DYNIX/ptx in there. # earlier versions are messed up and put the nodename in both # sysname and nodename. echo i386-sequent-sysv4 exit ;; i*86:UNIX_SV:4.2MP:2.*) # Unixware is an offshoot of SVR4, but it has its own version # number series starting with 2... # I am not positive that other SVR4 systems won't match this, # I just have to hope. -- rms. # Use sysv4.2uw... so that sysv4* matches it. echo ${UNAME_MACHINE}-pc-sysv4.2uw${UNAME_VERSION} exit ;; i*86:OS/2:*:*) # If we were able to find `uname', then EMX Unix compatibility # is probably installed. echo ${UNAME_MACHINE}-pc-os2-emx exit ;; i*86:XTS-300:*:STOP) echo ${UNAME_MACHINE}-unknown-stop exit ;; i*86:atheos:*:*) echo ${UNAME_MACHINE}-unknown-atheos exit ;; i*86:syllable:*:*) echo ${UNAME_MACHINE}-pc-syllable exit ;; i*86:LynxOS:2.*:* | i*86:LynxOS:3.[01]*:* | i*86:LynxOS:4.[02]*:*) echo i386-unknown-lynxos${UNAME_RELEASE} exit ;; i*86:*DOS:*:*) echo ${UNAME_MACHINE}-pc-msdosdjgpp exit ;; i*86:*:4.*:* | i*86:SYSTEM_V:4.*:*) UNAME_REL=`echo ${UNAME_RELEASE} | sed 's/\/MP$//'` if grep Novell /usr/include/link.h >/dev/null 2>/dev/null; then echo ${UNAME_MACHINE}-univel-sysv${UNAME_REL} else echo ${UNAME_MACHINE}-pc-sysv${UNAME_REL} fi exit ;; i*86:*:5:[678]*) # UnixWare 7.x, OpenUNIX and OpenServer 6. case `/bin/uname -X | grep "^Machine"` in *486*) UNAME_MACHINE=i486 ;; *Pentium) UNAME_MACHINE=i586 ;; *Pent*|*Celeron) UNAME_MACHINE=i686 ;; esac echo ${UNAME_MACHINE}-unknown-sysv${UNAME_RELEASE}${UNAME_SYSTEM}${UNAME_VERSION} exit ;; i*86:*:3.2:*) if test -f /usr/options/cb.name; then UNAME_REL=`sed -n 's/.*Version //p' /dev/null >/dev/null ; then UNAME_REL=`(/bin/uname -X|grep Release|sed -e 's/.*= //')` (/bin/uname -X|grep i80486 >/dev/null) && UNAME_MACHINE=i486 (/bin/uname -X|grep '^Machine.*Pentium' >/dev/null) \ && UNAME_MACHINE=i586 (/bin/uname -X|grep '^Machine.*Pent *II' >/dev/null) \ && UNAME_MACHINE=i686 (/bin/uname -X|grep '^Machine.*Pentium Pro' >/dev/null) \ && UNAME_MACHINE=i686 echo ${UNAME_MACHINE}-pc-sco$UNAME_REL else echo ${UNAME_MACHINE}-pc-sysv32 fi exit ;; pc:*:*:*) # Left here for compatibility: # uname -m prints for DJGPP always 'pc', but it prints nothing about # the processor, so we play safe by assuming i586. # Note: whatever this is, it MUST be the same as what config.sub # prints for the "djgpp" host, or else GDB configure will decide that # this is a cross-build. echo i586-pc-msdosdjgpp exit ;; Intel:Mach:3*:*) echo i386-pc-mach3 exit ;; paragon:*:*:*) echo i860-intel-osf1 exit ;; i860:*:4.*:*) # i860-SVR4 if grep Stardent /usr/include/sys/uadmin.h >/dev/null 2>&1 ; then echo i860-stardent-sysv${UNAME_RELEASE} # Stardent Vistra i860-SVR4 else # Add other i860-SVR4 vendors below as they are discovered. echo i860-unknown-sysv${UNAME_RELEASE} # Unknown i860-SVR4 fi exit ;; mini*:CTIX:SYS*5:*) # "miniframe" echo m68010-convergent-sysv exit ;; mc68k:UNIX:SYSTEM5:3.51m) echo m68k-convergent-sysv exit ;; M680?0:D-NIX:5.3:*) echo m68k-diab-dnix exit ;; M68*:*:R3V[5678]*:*) test -r /sysV68 && { echo 'm68k-motorola-sysv'; exit; } ;; 3[345]??:*:4.0:3.0 | 3[34]??A:*:4.0:3.0 | 3[34]??,*:*:4.0:3.0 | 3[34]??/*:*:4.0:3.0 | 4400:*:4.0:3.0 | 4850:*:4.0:3.0 | SKA40:*:4.0:3.0 | SDS2:*:4.0:3.0 | SHG2:*:4.0:3.0 | S7501*:*:4.0:3.0) OS_REL='' test -r /etc/.relid \ && OS_REL=.`sed -n 's/[^ ]* [^ ]* \([0-9][0-9]\).*/\1/p' < /etc/.relid` /bin/uname -p 2>/dev/null | grep 86 >/dev/null \ && { echo i486-ncr-sysv4.3${OS_REL}; exit; } /bin/uname -p 2>/dev/null | /bin/grep entium >/dev/null \ && { echo i586-ncr-sysv4.3${OS_REL}; exit; } ;; 3[34]??:*:4.0:* | 3[34]??,*:*:4.0:*) /bin/uname -p 2>/dev/null | grep 86 >/dev/null \ && { echo i486-ncr-sysv4; exit; } ;; NCR*:*:4.2:* | MPRAS*:*:4.2:*) OS_REL='.3' test -r /etc/.relid \ && OS_REL=.`sed -n 's/[^ ]* [^ ]* \([0-9][0-9]\).*/\1/p' < /etc/.relid` /bin/uname -p 2>/dev/null | grep 86 >/dev/null \ && { echo i486-ncr-sysv4.3${OS_REL}; exit; } /bin/uname -p 2>/dev/null | /bin/grep entium >/dev/null \ && { echo i586-ncr-sysv4.3${OS_REL}; exit; } /bin/uname -p 2>/dev/null | /bin/grep pteron >/dev/null \ && { echo i586-ncr-sysv4.3${OS_REL}; exit; } ;; m68*:LynxOS:2.*:* | m68*:LynxOS:3.0*:*) echo m68k-unknown-lynxos${UNAME_RELEASE} exit ;; mc68030:UNIX_System_V:4.*:*) echo m68k-atari-sysv4 exit ;; TSUNAMI:LynxOS:2.*:*) echo sparc-unknown-lynxos${UNAME_RELEASE} exit ;; rs6000:LynxOS:2.*:*) echo rs6000-unknown-lynxos${UNAME_RELEASE} exit ;; PowerPC:LynxOS:2.*:* | PowerPC:LynxOS:3.[01]*:* | PowerPC:LynxOS:4.[02]*:*) echo powerpc-unknown-lynxos${UNAME_RELEASE} exit ;; SM[BE]S:UNIX_SV:*:*) echo mips-dde-sysv${UNAME_RELEASE} exit ;; RM*:ReliantUNIX-*:*:*) echo mips-sni-sysv4 exit ;; RM*:SINIX-*:*:*) echo mips-sni-sysv4 exit ;; *:SINIX-*:*:*) if uname -p 2>/dev/null >/dev/null ; then UNAME_MACHINE=`(uname -p) 2>/dev/null` echo ${UNAME_MACHINE}-sni-sysv4 else echo ns32k-sni-sysv fi exit ;; PENTIUM:*:4.0*:*) # Unisys `ClearPath HMP IX 4000' SVR4/MP effort # says echo i586-unisys-sysv4 exit ;; *:UNIX_System_V:4*:FTX*) # From Gerald Hewes . # How about differentiating between stratus architectures? -djm echo hppa1.1-stratus-sysv4 exit ;; *:*:*:FTX*) # From seanf@swdc.stratus.com. echo i860-stratus-sysv4 exit ;; i*86:VOS:*:*) # From Paul.Green@stratus.com. echo ${UNAME_MACHINE}-stratus-vos exit ;; *:VOS:*:*) # From Paul.Green@stratus.com. echo hppa1.1-stratus-vos exit ;; mc68*:A/UX:*:*) echo m68k-apple-aux${UNAME_RELEASE} exit ;; news*:NEWS-OS:6*:*) echo mips-sony-newsos6 exit ;; R[34]000:*System_V*:*:* | R4000:UNIX_SYSV:*:* | R*000:UNIX_SV:*:*) if [ -d /usr/nec ]; then echo mips-nec-sysv${UNAME_RELEASE} else echo mips-unknown-sysv${UNAME_RELEASE} fi exit ;; BeBox:BeOS:*:*) # BeOS running on hardware made by Be, PPC only. echo powerpc-be-beos exit ;; BeMac:BeOS:*:*) # BeOS running on Mac or Mac clone, PPC only. echo powerpc-apple-beos exit ;; BePC:BeOS:*:*) # BeOS running on Intel PC compatible. echo i586-pc-beos exit ;; BePC:Haiku:*:*) # Haiku running on Intel PC compatible. echo i586-pc-haiku exit ;; x86_64:Haiku:*:*) echo x86_64-unknown-haiku exit ;; SX-4:SUPER-UX:*:*) echo sx4-nec-superux${UNAME_RELEASE} exit ;; SX-5:SUPER-UX:*:*) echo sx5-nec-superux${UNAME_RELEASE} exit ;; SX-6:SUPER-UX:*:*) echo sx6-nec-superux${UNAME_RELEASE} exit ;; SX-7:SUPER-UX:*:*) echo sx7-nec-superux${UNAME_RELEASE} exit ;; SX-8:SUPER-UX:*:*) echo sx8-nec-superux${UNAME_RELEASE} exit ;; SX-8R:SUPER-UX:*:*) echo sx8r-nec-superux${UNAME_RELEASE} exit ;; SX-ACE:SUPER-UX:*:*) echo sxace-nec-superux${UNAME_RELEASE} exit ;; Power*:Rhapsody:*:*) echo powerpc-apple-rhapsody${UNAME_RELEASE} exit ;; *:Rhapsody:*:*) echo ${UNAME_MACHINE}-apple-rhapsody${UNAME_RELEASE} exit ;; *:Darwin:*:*) UNAME_PROCESSOR=`uname -p` || UNAME_PROCESSOR=unknown eval $set_cc_for_build if test "$UNAME_PROCESSOR" = unknown ; then UNAME_PROCESSOR=powerpc fi if test `echo "$UNAME_RELEASE" | sed -e 's/\..*//'` -le 10 ; then if [ "$CC_FOR_BUILD" != no_compiler_found ]; then if (echo '#ifdef __LP64__'; echo IS_64BIT_ARCH; echo '#endif') | \ (CCOPTS="" $CC_FOR_BUILD -E - 2>/dev/null) | \ grep IS_64BIT_ARCH >/dev/null then case $UNAME_PROCESSOR in i386) UNAME_PROCESSOR=x86_64 ;; powerpc) UNAME_PROCESSOR=powerpc64 ;; esac fi # On 10.4-10.6 one might compile for PowerPC via gcc -arch ppc if (echo '#ifdef __POWERPC__'; echo IS_PPC; echo '#endif') | \ (CCOPTS="" $CC_FOR_BUILD -E - 2>/dev/null) | \ grep IS_PPC >/dev/null then UNAME_PROCESSOR=powerpc fi fi elif test "$UNAME_PROCESSOR" = i386 ; then # Avoid executing cc on OS X 10.9, as it ships with a stub # that puts up a graphical alert prompting to install # developer tools. Any system running Mac OS X 10.7 or # later (Darwin 11 and later) is required to have a 64-bit # processor. This is not true of the ARM version of Darwin # that Apple uses in portable devices. UNAME_PROCESSOR=x86_64 fi echo ${UNAME_PROCESSOR}-apple-darwin${UNAME_RELEASE} exit ;; *:procnto*:*:* | *:QNX:[0123456789]*:*) UNAME_PROCESSOR=`uname -p` if test "$UNAME_PROCESSOR" = x86; then UNAME_PROCESSOR=i386 UNAME_MACHINE=pc fi echo ${UNAME_PROCESSOR}-${UNAME_MACHINE}-nto-qnx${UNAME_RELEASE} exit ;; *:QNX:*:4*) echo i386-pc-qnx exit ;; NEO-*:NONSTOP_KERNEL:*:*) echo neo-tandem-nsk${UNAME_RELEASE} exit ;; NSE-*:NONSTOP_KERNEL:*:*) echo nse-tandem-nsk${UNAME_RELEASE} exit ;; NSR-*:NONSTOP_KERNEL:*:*) echo nsr-tandem-nsk${UNAME_RELEASE} exit ;; NSX-*:NONSTOP_KERNEL:*:*) echo nsx-tandem-nsk${UNAME_RELEASE} exit ;; *:NonStop-UX:*:*) echo mips-compaq-nonstopux exit ;; BS2000:POSIX*:*:*) echo bs2000-siemens-sysv exit ;; DS/*:UNIX_System_V:*:*) echo ${UNAME_MACHINE}-${UNAME_SYSTEM}-${UNAME_RELEASE} exit ;; *:Plan9:*:*) # "uname -m" is not consistent, so use $cputype instead. 386 # is converted to i386 for consistency with other x86 # operating systems. if test "$cputype" = 386; then UNAME_MACHINE=i386 else UNAME_MACHINE="$cputype" fi echo ${UNAME_MACHINE}-unknown-plan9 exit ;; *:TOPS-10:*:*) echo pdp10-unknown-tops10 exit ;; *:TENEX:*:*) echo pdp10-unknown-tenex exit ;; KS10:TOPS-20:*:* | KL10:TOPS-20:*:* | TYPE4:TOPS-20:*:*) echo pdp10-dec-tops20 exit ;; XKL-1:TOPS-20:*:* | TYPE5:TOPS-20:*:*) echo pdp10-xkl-tops20 exit ;; *:TOPS-20:*:*) echo pdp10-unknown-tops20 exit ;; *:ITS:*:*) echo pdp10-unknown-its exit ;; SEI:*:*:SEIUX) echo mips-sei-seiux${UNAME_RELEASE} exit ;; *:DragonFly:*:*) echo ${UNAME_MACHINE}-unknown-dragonfly`echo ${UNAME_RELEASE}|sed -e 's/[-(].*//'` exit ;; *:*VMS:*:*) UNAME_MACHINE=`(uname -p) 2>/dev/null` case "${UNAME_MACHINE}" in A*) echo alpha-dec-vms ; exit ;; I*) echo ia64-dec-vms ; exit ;; V*) echo vax-dec-vms ; exit ;; esac ;; *:XENIX:*:SysV) echo i386-pc-xenix exit ;; i*86:skyos:*:*) echo ${UNAME_MACHINE}-pc-skyos`echo ${UNAME_RELEASE} | sed -e 's/ .*$//'` exit ;; i*86:rdos:*:*) echo ${UNAME_MACHINE}-pc-rdos exit ;; i*86:AROS:*:*) echo ${UNAME_MACHINE}-pc-aros exit ;; x86_64:VMkernel:*:*) echo ${UNAME_MACHINE}-unknown-esx exit ;; amd64:Isilon\ OneFS:*:*) echo x86_64-unknown-onefs exit ;; esac cat >&2 </dev/null || echo unknown` uname -r = `(uname -r) 2>/dev/null || echo unknown` uname -s = `(uname -s) 2>/dev/null || echo unknown` uname -v = `(uname -v) 2>/dev/null || echo unknown` /usr/bin/uname -p = `(/usr/bin/uname -p) 2>/dev/null` /bin/uname -X = `(/bin/uname -X) 2>/dev/null` hostinfo = `(hostinfo) 2>/dev/null` /bin/universe = `(/bin/universe) 2>/dev/null` /usr/bin/arch -k = `(/usr/bin/arch -k) 2>/dev/null` /bin/arch = `(/bin/arch) 2>/dev/null` /usr/bin/oslevel = `(/usr/bin/oslevel) 2>/dev/null` /usr/convex/getsysinfo = `(/usr/convex/getsysinfo) 2>/dev/null` UNAME_MACHINE = ${UNAME_MACHINE} UNAME_RELEASE = ${UNAME_RELEASE} UNAME_SYSTEM = ${UNAME_SYSTEM} UNAME_VERSION = ${UNAME_VERSION} EOF exit 1 # Local variables: # eval: (add-hook 'write-file-hooks 'time-stamp) # time-stamp-start: "timestamp='" # time-stamp-format: "%:y-%02m-%02d" # time-stamp-end: "'" # End: heimdal-7.5.0/lib/libedit/config.h.in0000644000175000017500000001266613212444504015471 0ustar niknik/* config.h.in. Generated from configure.ac by autoheader. */ /* Define to 1 if you have the header file. */ #undef HAVE_CURSES_H /* Define to 1 if you have the header file, and it defines `DIR'. */ #undef HAVE_DIRENT_H /* Define to 1 if you have the header file. */ #undef HAVE_DLFCN_H /* Define to 1 if you have the header file. */ #undef HAVE_FCNTL_H /* Define to 1 if you have the `fork' function. */ #undef HAVE_FORK /* Define to 1 if you have the `getline' function. */ #undef HAVE_GETLINE /* Define to 1 if you have getpwnam_r and getpwuid_r that are draft POSIX.1 versions. */ #undef HAVE_GETPW_R_DRAFT /* Define to 1 if you have getpwnam_r and getpwuid_r that are POSIX.1 compatible. */ #undef HAVE_GETPW_R_POSIX /* Define to 1 if you have the header file. */ #undef HAVE_INTTYPES_H /* Define to 1 if you have the `isascii' function. */ #undef HAVE_ISASCII /* Define to 1 if you have the `issetugid' function. */ #undef HAVE_ISSETUGID /* Define to 1 if you have the `curses' library (-lcurses). */ #undef HAVE_LIBCURSES /* Define to 1 if you have the `ncurses' library (-lncurses). */ #undef HAVE_LIBNCURSES /* Define to 1 if you have the header file. */ #undef HAVE_LIMITS_H /* Define to 1 if you have the header file. */ #undef HAVE_MEMORY_H /* Define to 1 if you have the header file. */ #undef HAVE_NCURSES_H /* Define to 1 if you have the header file, and it defines `DIR'. */ #undef HAVE_NDIR_H /* Define to 1 if if your system has SIZE_MAX */ #undef HAVE_SIZE_MAX /* Define to 1 if `stat' has the bug that it succeeds when given the zero-length file name argument. */ #undef HAVE_STAT_EMPTY_STRING_BUG /* Define to 1 if you have the header file. */ #undef HAVE_STDINT_H /* Define to 1 if you have the header file. */ #undef HAVE_STDLIB_H /* Define to 1 if you have the header file. */ #undef HAVE_STRINGS_H /* Define to 1 if you have the header file. */ #undef HAVE_STRING_H /* Define to 1 if struct dirent has member d_namlen */ #undef HAVE_STRUCT_DIRENT_D_NAMLEN /* Define to 1 if you have the header file. */ #undef HAVE_SYS_CDEFS_H /* Define to 1 if you have the header file, and it defines `DIR'. */ #undef HAVE_SYS_DIR_H /* Define to 1 if you have the header file. */ #undef HAVE_SYS_IOCTL_H /* Define to 1 if you have the header file, and it defines `DIR'. */ #undef HAVE_SYS_NDIR_H /* Define to 1 if you have the header file. */ #undef HAVE_SYS_PARAM_H /* Define to 1 if you have the header file. */ #undef HAVE_SYS_STAT_H /* Define to 1 if you have the header file. */ #undef HAVE_SYS_TYPES_H /* Define to 1 if you have that is POSIX.1 compatible. */ #undef HAVE_SYS_WAIT_H /* Define to 1 if you have the header file. */ #undef HAVE_TERM_H /* Define to 1 if you have the header file. */ #undef HAVE_UNISTD_H /* Define to 1 if the system has the type `u_int32_t'. */ #undef HAVE_U_INT32_T /* Define to 1 if you have the `vfork' function. */ #undef HAVE_VFORK /* Define to 1 if you have the header file. */ #undef HAVE_VFORK_H /* Define to 1 if you have the `wcsdup' function. */ #undef HAVE_WCSDUP /* Define to 1 if `fork' works. */ #undef HAVE_WORKING_FORK /* Define to 1 if `vfork' works. */ #undef HAVE_WORKING_VFORK /* Define to 1 if `lstat' dereferences a symlink specified with a trailing slash. */ #undef LSTAT_FOLLOWS_SLASHED_SYMLINK /* Define to the sub-directory where libtool stores uninstalled libraries. */ #undef LT_OBJDIR /* Name of package */ #undef PACKAGE /* Define to the address where bug reports for this package should be sent. */ #undef PACKAGE_BUGREPORT /* Define to the full name of this package. */ #undef PACKAGE_NAME /* Define to the full name and version of this package. */ #undef PACKAGE_STRING /* Define to the one symbol short name of this package. */ #undef PACKAGE_TARNAME /* Define to the home page for this package. */ #undef PACKAGE_URL /* Define to the version of this package. */ #undef PACKAGE_VERSION /* Define as the return type of signal handlers (`int' or `void'). */ #undef RETSIGTYPE /* Define to 1 if you have the ANSI C header files. */ #undef STDC_HEADERS /* Enable extensions on AIX 3, Interix. */ #ifndef _ALL_SOURCE # undef _ALL_SOURCE #endif /* Enable GNU extensions on systems that have them. */ #ifndef _GNU_SOURCE # undef _GNU_SOURCE #endif /* Enable threading extensions on Solaris. */ #ifndef _POSIX_PTHREAD_SEMANTICS # undef _POSIX_PTHREAD_SEMANTICS #endif /* Enable extensions on HP NonStop. */ #ifndef _TANDEM_SOURCE # undef _TANDEM_SOURCE #endif /* Enable general extensions on Solaris. */ #ifndef __EXTENSIONS__ # undef __EXTENSIONS__ #endif /* Version number of package */ #undef VERSION /* Define to 1 if on MINIX. */ #undef _MINIX /* Define to 2 if the system does not provide POSIX.1 features except with this defined. */ #undef _POSIX_1_SOURCE /* Define to 1 if you need to in order for `stat' and other things to work. */ #undef _POSIX_SOURCE /* Define to empty if `const' does not conform to ANSI C. */ #undef const /* Define to `int' if does not define. */ #undef pid_t /* Define to `unsigned int' if does not define. */ #undef size_t /* Define as `fork' if `vfork' does not work. */ #undef vfork #include "sys.h" #define SCCSID #undef LIBC_SCCS #define lint heimdal-7.5.0/lib/libedit/INSTALL0000644000175000017500000002203013026237312014461 0ustar niknikCopyright (C) 1994, 1995, 1996, 1999, 2000, 2001, 2002 Free Software Foundation, Inc. This file is free documentation; the Free Software Foundation gives unlimited permission to copy, distribute and modify it. Basic Installation ================== These are generic installation instructions. The `configure' shell script attempts to guess correct values for various system-dependent variables used during compilation. It uses those values to create a `Makefile' in each directory of the package. It may also create one or more `.h' files containing system-dependent definitions. Finally, it creates a shell script `config.status' that you can run in the future to recreate the current configuration, and a file `config.log' containing compiler output (useful mainly for debugging `configure'). It can also use an optional file (typically called `config.cache' and enabled with `--cache-file=config.cache' or simply `-C') that saves the results of its tests to speed up reconfiguring. (Caching is disabled by default to prevent problems with accidental use of stale cache files.) If you need to do unusual things to compile the package, please try to figure out how `configure' could check whether to do them, and mail diffs or instructions to the address given in the `README' so they can be considered for the next release. If you are using the cache, and at some point `config.cache' contains results you don't want to keep, you may remove or edit it. The file `configure.ac' (or `configure.in') is used to create `configure' by a program called `autoconf'. You only need `configure.ac' if you want to change it or regenerate `configure' using a newer version of `autoconf'. The simplest way to compile this package is: 1. `cd' to the directory containing the package's source code and type `./configure' to configure the package for your system. If you're using `csh' on an old version of System V, you might need to type `sh ./configure' instead to prevent `csh' from trying to execute `configure' itself. Running `configure' takes awhile. While running, it prints some messages telling which features it is checking for. 2. Type `make' to compile the package. 3. Optionally, type `make check' to run any self-tests that come with the package. 4. Type `make install' to install the programs and any data files and documentation. 5. You can remove the program binaries and object files from the source code directory by typing `make clean'. To also remove the files that `configure' created (so you can compile the package for a different kind of computer), type `make distclean'. There is also a `make maintainer-clean' target, but that is intended mainly for the package's developers. If you use it, you may have to get all sorts of other programs in order to regenerate files that came with the distribution. Compilers and Options ===================== Some systems require unusual options for compilation or linking that the `configure' script does not know about. Run `./configure --help' for details on some of the pertinent environment variables. You can give `configure' initial values for configuration parameters by setting variables in the command line or in the environment. Here is an example: ./configure CC=c89 CFLAGS=-O2 LIBS=-lposix *Note Defining Variables::, for more details. Compiling For Multiple Architectures ==================================== You can compile the package for more than one kind of computer at the same time, by placing the object files for each architecture in their own directory. To do this, you must use a version of `make' that supports the `VPATH' variable, such as GNU `make'. `cd' to the directory where you want the object files and executables to go and run the `configure' script. `configure' automatically checks for the source code in the directory that `configure' is in and in `..'. If you have to use a `make' that does not support the `VPATH' variable, you have to compile the package for one architecture at a time in the source code directory. After you have installed the package for one architecture, use `make distclean' before reconfiguring for another architecture. Installation Names ================== By default, `make install' will install the package's files in `/usr/local/bin', `/usr/local/man', etc. You can specify an installation prefix other than `/usr/local' by giving `configure' the option `--prefix=PATH'. You can specify separate installation prefixes for architecture-specific files and architecture-independent files. If you give `configure' the option `--exec-prefix=PATH', the package will use PATH as the prefix for installing programs and libraries. Documentation and other data files will still use the regular prefix. In addition, if you use an unusual directory layout you can give options like `--bindir=PATH' to specify different values for particular kinds of files. Run `configure --help' for a list of the directories you can set and what kinds of files go in them. If the package supports it, you can cause programs to be installed with an extra prefix or suffix on their names by giving `configure' the option `--program-prefix=PREFIX' or `--program-suffix=SUFFIX'. Optional Features ================= Some packages pay attention to `--enable-FEATURE' options to `configure', where FEATURE indicates an optional part of the package. They may also pay attention to `--with-PACKAGE' options, where PACKAGE is something like `gnu-as' or `x' (for the X Window System). The `README' should mention any `--enable-' and `--with-' options that the package recognizes. For packages that use the X Window System, `configure' can usually find the X include and library files automatically, but if it doesn't, you can use the `configure' options `--x-includes=DIR' and `--x-libraries=DIR' to specify their locations. Specifying the System Type ========================== There may be some features `configure' cannot figure out automatically, but needs to determine by the type of machine the package will run on. Usually, assuming the package is built to be run on the _same_ architectures, `configure' can figure that out, but if it prints a message saying it cannot guess the machine type, give it the `--build=TYPE' option. TYPE can either be a short name for the system type, such as `sun4', or a canonical name which has the form: CPU-COMPANY-SYSTEM where SYSTEM can have one of these forms: OS KERNEL-OS See the file `config.sub' for the possible values of each field. If `config.sub' isn't included in this package, then this package doesn't need to know the machine type. If you are _building_ compiler tools for cross-compiling, you should use the `--target=TYPE' option to select the type of system they will produce code for. If you want to _use_ a cross compiler, that generates code for a platform different from the build platform, you should specify the "host" platform (i.e., that on which the generated programs will eventually be run) with `--host=TYPE'. Sharing Defaults ================ If you want to set default values for `configure' scripts to share, you can create a site shell script called `config.site' that gives default values for variables like `CC', `cache_file', and `prefix'. `configure' looks for `PREFIX/share/config.site' if it exists, then `PREFIX/etc/config.site' if it exists. Or, you can set the `CONFIG_SITE' environment variable to the location of the site script. A warning: not all `configure' scripts look for a site script. Defining Variables ================== Variables not defined in a site shell script can be set in the environment passed to `configure'. However, some packages may run configure again during the build, and the customized values of these variables may be lost. In order to avoid this problem, you should set them in the `configure' command line, using `VAR=value'. For example: ./configure CC=/usr/local2/bin/gcc will cause the specified gcc to be used as the C compiler (unless it is overridden in the site shell script). `configure' Invocation ====================== `configure' recognizes the following options to control how it operates. `--help' `-h' Print a summary of the options to `configure', and exit. `--version' `-V' Print the version of Autoconf used to generate the `configure' script, and exit. `--cache-file=FILE' Enable the cache: use and save the results of the tests in FILE, traditionally `config.cache'. FILE defaults to `/dev/null' to disable caching. `--config-cache' `-C' Alias for `--cache-file=config.cache'. `--quiet' `--silent' `-q' Do not print messages saying which checks are being made. To suppress all normal output, redirect it to `/dev/null' (any error messages will still be shown). `--srcdir=DIR' Look for the package's source code in directory DIR. Usually `configure' can determine that directory automatically. `configure' also accepts some other, not widely useful, options. Run `configure --help' for more details. heimdal-7.5.0/lib/libedit/Makefile.am0000644000175000017500000000024513026237312015470 0ustar niknik AUTOMAKE_OPTIONS = foreign #SUBDIRS = src examples doc SUBDIRS = src #EXTRA_DIST = libedit.pc.in #pkgconfigdir = $(libdir)/pkgconfig #pkgconfig_DATA = libedit.pc heimdal-7.5.0/lib/libedit/Makefile.in0000644000175000017500000006141513212444505015510 0ustar niknik# Makefile.in generated by automake 1.15.1 from Makefile.am. # @configure_input@ # Copyright (C) 1994-2017 Free Software Foundation, Inc. # This Makefile.in is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, # with or without modifications, as long as this notice is preserved. # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY, to the extent permitted by law; without # even the implied warranty of MERCHANTABILITY or FITNESS FOR A # PARTICULAR PURPOSE. @SET_MAKE@ VPATH = @srcdir@ am__is_gnu_make = { \ if test -z '$(MAKELEVEL)'; then \ false; \ elif test -n '$(MAKE_HOST)'; then \ true; \ elif test -n '$(MAKE_VERSION)' && test -n '$(CURDIR)'; then \ true; \ else \ false; \ fi; \ } am__make_running_with_option = \ case $${target_option-} in \ ?) ;; \ *) echo "am__make_running_with_option: internal error: invalid" \ "target option '$${target_option-}' specified" >&2; \ exit 1;; \ esac; \ has_opt=no; \ sane_makeflags=$$MAKEFLAGS; \ if $(am__is_gnu_make); then \ sane_makeflags=$$MFLAGS; \ else \ case $$MAKEFLAGS in \ *\\[\ \ ]*) \ bs=\\; \ sane_makeflags=`printf '%s\n' "$$MAKEFLAGS" \ | sed "s/$$bs$$bs[$$bs $$bs ]*//g"`;; \ esac; \ fi; \ skip_next=no; \ strip_trailopt () \ { \ flg=`printf '%s\n' "$$flg" | sed "s/$$1.*$$//"`; \ }; \ for flg in $$sane_makeflags; do \ test $$skip_next = yes && { skip_next=no; continue; }; \ case $$flg in \ *=*|--*) continue;; \ -*I) strip_trailopt 'I'; skip_next=yes;; \ -*I?*) strip_trailopt 'I';; \ -*O) strip_trailopt 'O'; skip_next=yes;; \ -*O?*) strip_trailopt 'O';; \ -*l) strip_trailopt 'l'; skip_next=yes;; \ -*l?*) strip_trailopt 'l';; \ -[dEDm]) skip_next=yes;; \ -[JT]) skip_next=yes;; \ esac; \ case $$flg in \ *$$target_option*) has_opt=yes; break;; \ esac; \ done; \ test $$has_opt = yes am__make_dryrun = (target_option=n; $(am__make_running_with_option)) am__make_keepgoing = (target_option=k; $(am__make_running_with_option)) pkgdatadir = $(datadir)/@PACKAGE@ pkgincludedir = $(includedir)/@PACKAGE@ pkglibdir = $(libdir)/@PACKAGE@ pkglibexecdir = $(libexecdir)/@PACKAGE@ am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd install_sh_DATA = $(install_sh) -c -m 644 install_sh_PROGRAM = $(install_sh) -c install_sh_SCRIPT = $(install_sh) -c INSTALL_HEADER = $(INSTALL_DATA) transform = $(program_transform_name) NORMAL_INSTALL = : PRE_INSTALL = : POST_INSTALL = : NORMAL_UNINSTALL = : PRE_UNINSTALL = : POST_UNINSTALL = : build_triplet = @build@ host_triplet = @host@ subdir = . ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 am__aclocal_m4_deps = $(top_srcdir)/acinclude.m4 \ $(top_srcdir)/configure.ac am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \ $(ACLOCAL_M4) DIST_COMMON = $(srcdir)/Makefile.am $(top_srcdir)/configure \ $(am__configure_deps) $(am__DIST_COMMON) am__CONFIG_DISTCLEAN_FILES = config.status config.cache config.log \ configure.lineno config.status.lineno mkinstalldirs = $(install_sh) -d CONFIG_HEADER = config.h CONFIG_CLEAN_FILES = CONFIG_CLEAN_VPATH_FILES = AM_V_P = $(am__v_P_@AM_V@) am__v_P_ = $(am__v_P_@AM_DEFAULT_V@) am__v_P_0 = false am__v_P_1 = : AM_V_GEN = $(am__v_GEN_@AM_V@) am__v_GEN_ = $(am__v_GEN_@AM_DEFAULT_V@) am__v_GEN_0 = @echo " GEN " $@; am__v_GEN_1 = AM_V_at = $(am__v_at_@AM_V@) am__v_at_ = $(am__v_at_@AM_DEFAULT_V@) am__v_at_0 = @ am__v_at_1 = SOURCES = DIST_SOURCES = RECURSIVE_TARGETS = all-recursive check-recursive cscopelist-recursive \ ctags-recursive dvi-recursive html-recursive info-recursive \ install-data-recursive install-dvi-recursive \ install-exec-recursive install-html-recursive \ install-info-recursive install-pdf-recursive \ install-ps-recursive install-recursive installcheck-recursive \ installdirs-recursive pdf-recursive ps-recursive \ tags-recursive uninstall-recursive am__can_run_installinfo = \ case $$AM_UPDATE_INFO_DIR in \ n|no|NO) false;; \ *) (install-info --version) >/dev/null 2>&1;; \ esac RECURSIVE_CLEAN_TARGETS = mostlyclean-recursive clean-recursive \ distclean-recursive maintainer-clean-recursive am__recursive_targets = \ $(RECURSIVE_TARGETS) \ $(RECURSIVE_CLEAN_TARGETS) \ $(am__extra_recursive_targets) AM_RECURSIVE_TARGETS = $(am__recursive_targets:-recursive=) TAGS CTAGS \ cscope distdir dist dist-all distcheck am__tagged_files = $(HEADERS) $(SOURCES) $(TAGS_FILES) \ $(LISP)config.h.in # Read a list of newline-separated strings from the standard input, # and print each of them once, without duplicates. Input order is # *not* preserved. am__uniquify_input = $(AWK) '\ BEGIN { nonempty = 0; } \ { items[$$0] = 1; nonempty = 1; } \ END { if (nonempty) { for (i in items) print i; }; } \ ' # Make sure the list of sources is unique. This is necessary because, # e.g., the same source file might be shared among _SOURCES variables # for different programs/libraries. am__define_uniq_tagged_files = \ list='$(am__tagged_files)'; \ unique=`for i in $$list; do \ if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ done | $(am__uniquify_input)` ETAGS = etags CTAGS = ctags CSCOPE = cscope DIST_SUBDIRS = $(SUBDIRS) am__DIST_COMMON = $(srcdir)/Makefile.in $(srcdir)/config.h.in COPYING \ ChangeLog INSTALL THANKS compile config.guess config.sub \ install-sh ltmain.sh missing DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST) distdir = $(PACKAGE)-$(VERSION) top_distdir = $(distdir) am__remove_distdir = \ if test -d "$(distdir)"; then \ find "$(distdir)" -type d ! -perm -200 -exec chmod u+w {} ';' \ && rm -rf "$(distdir)" \ || { sleep 5 && rm -rf "$(distdir)"; }; \ else :; fi am__post_remove_distdir = $(am__remove_distdir) am__relativize = \ dir0=`pwd`; \ sed_first='s,^\([^/]*\)/.*$$,\1,'; \ sed_rest='s,^[^/]*/*,,'; \ sed_last='s,^.*/\([^/]*\)$$,\1,'; \ sed_butlast='s,/*[^/]*$$,,'; \ while test -n "$$dir1"; do \ first=`echo "$$dir1" | sed -e "$$sed_first"`; \ if test "$$first" != "."; then \ if test "$$first" = ".."; then \ dir2=`echo "$$dir0" | sed -e "$$sed_last"`/"$$dir2"; \ dir0=`echo "$$dir0" | sed -e "$$sed_butlast"`; \ else \ first2=`echo "$$dir2" | sed -e "$$sed_first"`; \ if test "$$first2" = "$$first"; then \ dir2=`echo "$$dir2" | sed -e "$$sed_rest"`; \ else \ dir2="../$$dir2"; \ fi; \ dir0="$$dir0"/"$$first"; \ fi; \ fi; \ dir1=`echo "$$dir1" | sed -e "$$sed_rest"`; \ done; \ reldir="$$dir2" DIST_ARCHIVES = $(distdir).tar.gz GZIP_ENV = --best DIST_TARGETS = dist-gzip distuninstallcheck_listfiles = find . -type f -print am__distuninstallcheck_listfiles = $(distuninstallcheck_listfiles) \ | sed 's|^\./|$(prefix)/|' | grep -v '$(infodir)/dir$$' distcleancheck_listfiles = find . -type f -print ACLOCAL = @ACLOCAL@ AMTAR = @AMTAR@ AM_DEFAULT_VERBOSITY = @AM_DEFAULT_VERBOSITY@ AR = @AR@ AUTOCONF = @AUTOCONF@ AUTOHEADER = @AUTOHEADER@ AUTOMAKE = @AUTOMAKE@ AWK = @AWK@ CC = @CC@ CCDEPMODE = @CCDEPMODE@ CFLAGS = @CFLAGS@ CPP = @CPP@ CPPFLAGS = @CPPFLAGS@ CYGPATH_W = @CYGPATH_W@ DEFS = @DEFS@ DEPDIR = @DEPDIR@ DLLTOOL = @DLLTOOL@ DSYMUTIL = @DSYMUTIL@ DUMPBIN = @DUMPBIN@ ECHO_C = @ECHO_C@ ECHO_N = @ECHO_N@ ECHO_T = @ECHO_T@ EGREP = @EGREP@ EXEEXT = @EXEEXT@ FGREP = @FGREP@ GREP = @GREP@ INSTALL = @INSTALL@ INSTALL_DATA = @INSTALL_DATA@ INSTALL_PROGRAM = @INSTALL_PROGRAM@ INSTALL_SCRIPT = @INSTALL_SCRIPT@ INSTALL_STRIP_PROGRAM = @INSTALL_STRIP_PROGRAM@ LD = @LD@ LDFLAGS = @LDFLAGS@ LIBOBJS = @LIBOBJS@ LIBS = @LIBS@ LIBTOOL = @LIBTOOL@ LIPO = @LIPO@ LN_S = @LN_S@ LTLIBOBJS = @LTLIBOBJS@ LT_SYS_LIBRARY_PATH = @LT_SYS_LIBRARY_PATH@ LT_VERSION = @LT_VERSION@ MAKEINFO = @MAKEINFO@ MANIFEST_TOOL = @MANIFEST_TOOL@ MANTYPE = @MANTYPE@ MKDIR_P = @MKDIR_P@ NM = @NM@ NMEDIT = @NMEDIT@ NROFF = @NROFF@ OBJDUMP = @OBJDUMP@ OBJEXT = @OBJEXT@ OTOOL = @OTOOL@ OTOOL64 = @OTOOL64@ PACKAGE = @PACKAGE@ PACKAGE_BUGREPORT = @PACKAGE_BUGREPORT@ PACKAGE_NAME = @PACKAGE_NAME@ PACKAGE_STRING = @PACKAGE_STRING@ PACKAGE_TARNAME = @PACKAGE_TARNAME@ PACKAGE_URL = @PACKAGE_URL@ PACKAGE_VERSION = @PACKAGE_VERSION@ PATH_SEPARATOR = @PATH_SEPARATOR@ RANLIB = @RANLIB@ SED = @SED@ SET_MAKE = @SET_MAKE@ SHELL = @SHELL@ STRIP = @STRIP@ VERSION = @VERSION@ abs_builddir = @abs_builddir@ abs_srcdir = @abs_srcdir@ abs_top_builddir = @abs_top_builddir@ abs_top_srcdir = @abs_top_srcdir@ ac_ct_AR = @ac_ct_AR@ ac_ct_CC = @ac_ct_CC@ ac_ct_DUMPBIN = @ac_ct_DUMPBIN@ am__include = @am__include@ am__leading_dot = @am__leading_dot@ am__quote = @am__quote@ am__tar = @am__tar@ am__untar = @am__untar@ bindir = @bindir@ build = @build@ build_alias = @build_alias@ build_cpu = @build_cpu@ build_os = @build_os@ build_vendor = @build_vendor@ builddir = @builddir@ datadir = @datadir@ datarootdir = @datarootdir@ docdir = @docdir@ dvidir = @dvidir@ exec_prefix = @exec_prefix@ host = @host@ host_alias = @host_alias@ host_cpu = @host_cpu@ host_os = @host_os@ host_vendor = @host_vendor@ htmldir = @htmldir@ includedir = @includedir@ infodir = @infodir@ install_sh = @install_sh@ libdir = @libdir@ libexecdir = @libexecdir@ localedir = @localedir@ localstatedir = @localstatedir@ mandir = @mandir@ mkdir_p = @mkdir_p@ oldincludedir = @oldincludedir@ pdfdir = @pdfdir@ prefix = @prefix@ program_transform_name = @program_transform_name@ psdir = @psdir@ sbindir = @sbindir@ sharedstatedir = @sharedstatedir@ srcdir = @srcdir@ sysconfdir = @sysconfdir@ target_alias = @target_alias@ top_build_prefix = @top_build_prefix@ top_builddir = @top_builddir@ top_srcdir = @top_srcdir@ AUTOMAKE_OPTIONS = foreign #SUBDIRS = src examples doc SUBDIRS = src all: config.h $(MAKE) $(AM_MAKEFLAGS) all-recursive .SUFFIXES: am--refresh: Makefile @: $(srcdir)/Makefile.in: $(srcdir)/Makefile.am $(am__configure_deps) @for dep in $?; do \ case '$(am__configure_deps)' in \ *$$dep*) \ echo ' cd $(srcdir) && $(AUTOMAKE) --foreign'; \ $(am__cd) $(srcdir) && $(AUTOMAKE) --foreign \ && exit 0; \ exit 1;; \ esac; \ done; \ echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign Makefile'; \ $(am__cd) $(top_srcdir) && \ $(AUTOMAKE) --foreign Makefile Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status @case '$?' in \ *config.status*) \ echo ' $(SHELL) ./config.status'; \ $(SHELL) ./config.status;; \ *) \ echo ' cd $(top_builddir) && $(SHELL) ./config.status $@ $(am__depfiles_maybe)'; \ cd $(top_builddir) && $(SHELL) ./config.status $@ $(am__depfiles_maybe);; \ esac; $(top_builddir)/config.status: $(top_srcdir)/configure $(CONFIG_STATUS_DEPENDENCIES) $(SHELL) ./config.status --recheck $(top_srcdir)/configure: $(am__configure_deps) $(am__cd) $(srcdir) && $(AUTOCONF) $(ACLOCAL_M4): $(am__aclocal_m4_deps) $(am__cd) $(srcdir) && $(ACLOCAL) $(ACLOCAL_AMFLAGS) $(am__aclocal_m4_deps): config.h: stamp-h1 @test -f $@ || rm -f stamp-h1 @test -f $@ || $(MAKE) $(AM_MAKEFLAGS) stamp-h1 stamp-h1: $(srcdir)/config.h.in $(top_builddir)/config.status @rm -f stamp-h1 cd $(top_builddir) && $(SHELL) ./config.status config.h $(srcdir)/config.h.in: $(am__configure_deps) ($(am__cd) $(top_srcdir) && $(AUTOHEADER)) rm -f stamp-h1 touch $@ distclean-hdr: -rm -f config.h stamp-h1 mostlyclean-libtool: -rm -f *.lo clean-libtool: -rm -rf .libs _libs distclean-libtool: -rm -f libtool config.lt # This directory's subdirectories are mostly independent; you can cd # into them and run 'make' without going through this Makefile. # To change the values of 'make' variables: instead of editing Makefiles, # (1) if the variable is set in 'config.status', edit 'config.status' # (which will cause the Makefiles to be regenerated when you run 'make'); # (2) otherwise, pass the desired values on the 'make' command line. $(am__recursive_targets): @fail=; \ if $(am__make_keepgoing); then \ failcom='fail=yes'; \ else \ failcom='exit 1'; \ fi; \ dot_seen=no; \ target=`echo $@ | sed s/-recursive//`; \ case "$@" in \ distclean-* | maintainer-clean-*) list='$(DIST_SUBDIRS)' ;; \ *) list='$(SUBDIRS)' ;; \ esac; \ for subdir in $$list; do \ echo "Making $$target in $$subdir"; \ if test "$$subdir" = "."; then \ dot_seen=yes; \ local_target="$$target-am"; \ else \ local_target="$$target"; \ fi; \ ($(am__cd) $$subdir && $(MAKE) $(AM_MAKEFLAGS) $$local_target) \ || eval $$failcom; \ done; \ if test "$$dot_seen" = "no"; then \ $(MAKE) $(AM_MAKEFLAGS) "$$target-am" || exit 1; \ fi; test -z "$$fail" ID: $(am__tagged_files) $(am__define_uniq_tagged_files); mkid -fID $$unique tags: tags-recursive TAGS: tags tags-am: $(TAGS_DEPENDENCIES) $(am__tagged_files) set x; \ here=`pwd`; \ if ($(ETAGS) --etags-include --version) >/dev/null 2>&1; then \ include_option=--etags-include; \ empty_fix=.; \ else \ include_option=--include; \ empty_fix=; \ fi; \ list='$(SUBDIRS)'; for subdir in $$list; do \ if test "$$subdir" = .; then :; else \ test ! -f $$subdir/TAGS || \ set "$$@" "$$include_option=$$here/$$subdir/TAGS"; \ fi; \ done; \ $(am__define_uniq_tagged_files); \ shift; \ if test -z "$(ETAGS_ARGS)$$*$$unique"; then :; else \ test -n "$$unique" || unique=$$empty_fix; \ if test $$# -gt 0; then \ $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ "$$@" $$unique; \ else \ $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ $$unique; \ fi; \ fi ctags: ctags-recursive CTAGS: ctags ctags-am: $(TAGS_DEPENDENCIES) $(am__tagged_files) $(am__define_uniq_tagged_files); \ test -z "$(CTAGS_ARGS)$$unique" \ || $(CTAGS) $(CTAGSFLAGS) $(AM_CTAGSFLAGS) $(CTAGS_ARGS) \ $$unique GTAGS: here=`$(am__cd) $(top_builddir) && pwd` \ && $(am__cd) $(top_srcdir) \ && gtags -i $(GTAGS_ARGS) "$$here" cscope: cscope.files test ! -s cscope.files \ || $(CSCOPE) -b -q $(AM_CSCOPEFLAGS) $(CSCOPEFLAGS) -i cscope.files $(CSCOPE_ARGS) clean-cscope: -rm -f cscope.files cscope.files: clean-cscope cscopelist cscopelist: cscopelist-recursive cscopelist-am: $(am__tagged_files) list='$(am__tagged_files)'; \ case "$(srcdir)" in \ [\\/]* | ?:[\\/]*) sdir="$(srcdir)" ;; \ *) sdir=$(subdir)/$(srcdir) ;; \ esac; \ for i in $$list; do \ if test -f "$$i"; then \ echo "$(subdir)/$$i"; \ else \ echo "$$sdir/$$i"; \ fi; \ done >> $(top_builddir)/cscope.files distclean-tags: -rm -f TAGS ID GTAGS GRTAGS GSYMS GPATH tags -rm -f cscope.out cscope.in.out cscope.po.out cscope.files distdir: $(DISTFILES) $(am__remove_distdir) test -d "$(distdir)" || mkdir "$(distdir)" @srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ topsrcdirstrip=`echo "$(top_srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ list='$(DISTFILES)'; \ dist_files=`for file in $$list; do echo $$file; done | \ sed -e "s|^$$srcdirstrip/||;t" \ -e "s|^$$topsrcdirstrip/|$(top_builddir)/|;t"`; \ case $$dist_files in \ */*) $(MKDIR_P) `echo "$$dist_files" | \ sed '/\//!d;s|^|$(distdir)/|;s,/[^/]*$$,,' | \ sort -u` ;; \ esac; \ for file in $$dist_files; do \ if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \ if test -d $$d/$$file; then \ dir=`echo "/$$file" | sed -e 's,/[^/]*$$,,'`; \ if test -d "$(distdir)/$$file"; then \ find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ fi; \ if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \ cp -fpR $(srcdir)/$$file "$(distdir)$$dir" || exit 1; \ find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ fi; \ cp -fpR $$d/$$file "$(distdir)$$dir" || exit 1; \ else \ test -f "$(distdir)/$$file" \ || cp -p $$d/$$file "$(distdir)/$$file" \ || exit 1; \ fi; \ done @list='$(DIST_SUBDIRS)'; for subdir in $$list; do \ if test "$$subdir" = .; then :; else \ $(am__make_dryrun) \ || test -d "$(distdir)/$$subdir" \ || $(MKDIR_P) "$(distdir)/$$subdir" \ || exit 1; \ dir1=$$subdir; dir2="$(distdir)/$$subdir"; \ $(am__relativize); \ new_distdir=$$reldir; \ dir1=$$subdir; dir2="$(top_distdir)"; \ $(am__relativize); \ new_top_distdir=$$reldir; \ echo " (cd $$subdir && $(MAKE) $(AM_MAKEFLAGS) top_distdir="$$new_top_distdir" distdir="$$new_distdir" \\"; \ echo " am__remove_distdir=: am__skip_length_check=: am__skip_mode_fix=: distdir)"; \ ($(am__cd) $$subdir && \ $(MAKE) $(AM_MAKEFLAGS) \ top_distdir="$$new_top_distdir" \ distdir="$$new_distdir" \ am__remove_distdir=: \ am__skip_length_check=: \ am__skip_mode_fix=: \ distdir) \ || exit 1; \ fi; \ done -test -n "$(am__skip_mode_fix)" \ || find "$(distdir)" -type d ! -perm -755 \ -exec chmod u+rwx,go+rx {} \; -o \ ! -type d ! -perm -444 -links 1 -exec chmod a+r {} \; -o \ ! -type d ! -perm -400 -exec chmod a+r {} \; -o \ ! -type d ! -perm -444 -exec $(install_sh) -c -m a+r {} {} \; \ || chmod -R a+r "$(distdir)" dist-gzip: distdir tardir=$(distdir) && $(am__tar) | eval GZIP= gzip $(GZIP_ENV) -c >$(distdir).tar.gz $(am__post_remove_distdir) dist-bzip2: distdir tardir=$(distdir) && $(am__tar) | BZIP2=$${BZIP2--9} bzip2 -c >$(distdir).tar.bz2 $(am__post_remove_distdir) dist-lzip: distdir tardir=$(distdir) && $(am__tar) | lzip -c $${LZIP_OPT--9} >$(distdir).tar.lz $(am__post_remove_distdir) dist-xz: distdir tardir=$(distdir) && $(am__tar) | XZ_OPT=$${XZ_OPT--e} xz -c >$(distdir).tar.xz $(am__post_remove_distdir) dist-tarZ: distdir @echo WARNING: "Support for distribution archives compressed with" \ "legacy program 'compress' is deprecated." >&2 @echo WARNING: "It will be removed altogether in Automake 2.0" >&2 tardir=$(distdir) && $(am__tar) | compress -c >$(distdir).tar.Z $(am__post_remove_distdir) dist-shar: distdir @echo WARNING: "Support for shar distribution archives is" \ "deprecated." >&2 @echo WARNING: "It will be removed altogether in Automake 2.0" >&2 shar $(distdir) | eval GZIP= gzip $(GZIP_ENV) -c >$(distdir).shar.gz $(am__post_remove_distdir) dist-zip: distdir -rm -f $(distdir).zip zip -rq $(distdir).zip $(distdir) $(am__post_remove_distdir) dist dist-all: $(MAKE) $(AM_MAKEFLAGS) $(DIST_TARGETS) am__post_remove_distdir='@:' $(am__post_remove_distdir) # This target untars the dist file and tries a VPATH configuration. Then # it guarantees that the distribution is self-contained by making another # tarfile. distcheck: dist case '$(DIST_ARCHIVES)' in \ *.tar.gz*) \ eval GZIP= gzip $(GZIP_ENV) -dc $(distdir).tar.gz | $(am__untar) ;;\ *.tar.bz2*) \ bzip2 -dc $(distdir).tar.bz2 | $(am__untar) ;;\ *.tar.lz*) \ lzip -dc $(distdir).tar.lz | $(am__untar) ;;\ *.tar.xz*) \ xz -dc $(distdir).tar.xz | $(am__untar) ;;\ *.tar.Z*) \ uncompress -c $(distdir).tar.Z | $(am__untar) ;;\ *.shar.gz*) \ eval GZIP= gzip $(GZIP_ENV) -dc $(distdir).shar.gz | unshar ;;\ *.zip*) \ unzip $(distdir).zip ;;\ esac chmod -R a-w $(distdir) chmod u+w $(distdir) mkdir $(distdir)/_build $(distdir)/_build/sub $(distdir)/_inst chmod a-w $(distdir) test -d $(distdir)/_build || exit 0; \ dc_install_base=`$(am__cd) $(distdir)/_inst && pwd | sed -e 's,^[^:\\/]:[\\/],/,'` \ && dc_destdir="$${TMPDIR-/tmp}/am-dc-$$$$/" \ && am__cwd=`pwd` \ && $(am__cd) $(distdir)/_build/sub \ && ../../configure \ $(AM_DISTCHECK_CONFIGURE_FLAGS) \ $(DISTCHECK_CONFIGURE_FLAGS) \ --srcdir=../.. --prefix="$$dc_install_base" \ && $(MAKE) $(AM_MAKEFLAGS) \ && $(MAKE) $(AM_MAKEFLAGS) dvi \ && $(MAKE) $(AM_MAKEFLAGS) check \ && $(MAKE) $(AM_MAKEFLAGS) install \ && $(MAKE) $(AM_MAKEFLAGS) installcheck \ && $(MAKE) $(AM_MAKEFLAGS) uninstall \ && $(MAKE) $(AM_MAKEFLAGS) distuninstallcheck_dir="$$dc_install_base" \ distuninstallcheck \ && chmod -R a-w "$$dc_install_base" \ && ({ \ (cd ../.. && umask 077 && mkdir "$$dc_destdir") \ && $(MAKE) $(AM_MAKEFLAGS) DESTDIR="$$dc_destdir" install \ && $(MAKE) $(AM_MAKEFLAGS) DESTDIR="$$dc_destdir" uninstall \ && $(MAKE) $(AM_MAKEFLAGS) DESTDIR="$$dc_destdir" \ distuninstallcheck_dir="$$dc_destdir" distuninstallcheck; \ } || { rm -rf "$$dc_destdir"; exit 1; }) \ && rm -rf "$$dc_destdir" \ && $(MAKE) $(AM_MAKEFLAGS) dist \ && rm -rf $(DIST_ARCHIVES) \ && $(MAKE) $(AM_MAKEFLAGS) distcleancheck \ && cd "$$am__cwd" \ || exit 1 $(am__post_remove_distdir) @(echo "$(distdir) archives ready for distribution: "; \ list='$(DIST_ARCHIVES)'; for i in $$list; do echo $$i; done) | \ sed -e 1h -e 1s/./=/g -e 1p -e 1x -e '$$p' -e '$$x' distuninstallcheck: @test -n '$(distuninstallcheck_dir)' || { \ echo 'ERROR: trying to run $@ with an empty' \ '$$(distuninstallcheck_dir)' >&2; \ exit 1; \ }; \ $(am__cd) '$(distuninstallcheck_dir)' || { \ echo 'ERROR: cannot chdir into $(distuninstallcheck_dir)' >&2; \ exit 1; \ }; \ test `$(am__distuninstallcheck_listfiles) | wc -l` -eq 0 \ || { echo "ERROR: files left after uninstall:" ; \ if test -n "$(DESTDIR)"; then \ echo " (check DESTDIR support)"; \ fi ; \ $(distuninstallcheck_listfiles) ; \ exit 1; } >&2 distcleancheck: distclean @if test '$(srcdir)' = . ; then \ echo "ERROR: distcleancheck can only run from a VPATH build" ; \ exit 1 ; \ fi @test `$(distcleancheck_listfiles) | wc -l` -eq 0 \ || { echo "ERROR: files left in build directory after distclean:" ; \ $(distcleancheck_listfiles) ; \ exit 1; } >&2 check-am: all-am check: check-recursive all-am: Makefile config.h installdirs: installdirs-recursive installdirs-am: install: install-recursive install-exec: install-exec-recursive install-data: install-data-recursive uninstall: uninstall-recursive install-am: all-am @$(MAKE) $(AM_MAKEFLAGS) install-exec-am install-data-am installcheck: installcheck-recursive install-strip: if test -z '$(STRIP)'; then \ $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ install; \ else \ $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'" install; \ fi mostlyclean-generic: clean-generic: distclean-generic: -test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES) -test . = "$(srcdir)" || test -z "$(CONFIG_CLEAN_VPATH_FILES)" || rm -f $(CONFIG_CLEAN_VPATH_FILES) maintainer-clean-generic: @echo "This command is intended for maintainers to use" @echo "it deletes files that may require special tools to rebuild." clean: clean-recursive clean-am: clean-generic clean-libtool mostlyclean-am distclean: distclean-recursive -rm -f $(am__CONFIG_DISTCLEAN_FILES) -rm -f Makefile distclean-am: clean-am distclean-generic distclean-hdr \ distclean-libtool distclean-tags dvi: dvi-recursive dvi-am: html: html-recursive html-am: info: info-recursive info-am: install-data-am: install-dvi: install-dvi-recursive install-dvi-am: install-exec-am: install-html: install-html-recursive install-html-am: install-info: install-info-recursive install-info-am: install-man: install-pdf: install-pdf-recursive install-pdf-am: install-ps: install-ps-recursive install-ps-am: installcheck-am: maintainer-clean: maintainer-clean-recursive -rm -f $(am__CONFIG_DISTCLEAN_FILES) -rm -rf $(top_srcdir)/autom4te.cache -rm -f Makefile maintainer-clean-am: distclean-am maintainer-clean-generic mostlyclean: mostlyclean-recursive mostlyclean-am: mostlyclean-generic mostlyclean-libtool pdf: pdf-recursive pdf-am: ps: ps-recursive ps-am: uninstall-am: .MAKE: $(am__recursive_targets) all install-am install-strip .PHONY: $(am__recursive_targets) CTAGS GTAGS TAGS all all-am \ am--refresh check check-am clean clean-cscope clean-generic \ clean-libtool cscope cscopelist-am ctags ctags-am dist \ dist-all dist-bzip2 dist-gzip dist-lzip dist-shar dist-tarZ \ dist-xz dist-zip distcheck distclean distclean-generic \ distclean-hdr distclean-libtool distclean-tags distcleancheck \ distdir distuninstallcheck dvi dvi-am html html-am info \ info-am install install-am install-data install-data-am \ install-dvi install-dvi-am install-exec install-exec-am \ install-html install-html-am install-info install-info-am \ install-man install-pdf install-pdf-am install-ps \ install-ps-am install-strip installcheck installcheck-am \ installdirs installdirs-am maintainer-clean \ maintainer-clean-generic mostlyclean mostlyclean-generic \ mostlyclean-libtool pdf pdf-am ps ps-am tags tags-am uninstall \ uninstall-am .PRECIOUS: Makefile #EXTRA_DIST = libedit.pc.in #pkgconfigdir = $(libdir)/pkgconfig #pkgconfig_DATA = libedit.pc # Tell versions [3.59,3.63) of GNU make to not export all variables. # Otherwise a system limit (for SysV at least) may be exceeded. .NOEXPORT: heimdal-7.5.0/lib/libedit/configure0000755000175000017500000162070613212444503015355 0ustar niknik#! /bin/sh # Guess values for system-dependent variables and create Makefiles. # Generated by GNU Autoconf 2.69 for libedit 3.1. # # # Copyright (C) 1992-1996, 1998-2012 Free Software Foundation, Inc. # # # This configure script is free software; the Free Software Foundation # gives unlimited permission to copy, distribute and modify it. ## -------------------- ## ## M4sh Initialization. ## ## -------------------- ## # Be more Bourne compatible DUALCASE=1; export DUALCASE # for MKS sh if test -n "${ZSH_VERSION+set}" && (emulate sh) >/dev/null 2>&1; then : emulate sh NULLCMD=: # Pre-4.2 versions of Zsh do word splitting on ${1+"$@"}, which # is contrary to our usage. Disable this feature. alias -g '${1+"$@"}'='"$@"' setopt NO_GLOB_SUBST else case `(set -o) 2>/dev/null` in #( *posix*) : set -o posix ;; #( *) : ;; esac fi as_nl=' ' export as_nl # Printing a long string crashes Solaris 7 /usr/bin/printf. as_echo='\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\' as_echo=$as_echo$as_echo$as_echo$as_echo$as_echo as_echo=$as_echo$as_echo$as_echo$as_echo$as_echo$as_echo # Prefer a ksh shell builtin over an external printf program on Solaris, # but without wasting forks for bash or zsh. if test -z "$BASH_VERSION$ZSH_VERSION" \ && (test "X`print -r -- $as_echo`" = "X$as_echo") 2>/dev/null; then as_echo='print -r --' as_echo_n='print -rn --' elif (test "X`printf %s $as_echo`" = "X$as_echo") 2>/dev/null; then as_echo='printf %s\n' as_echo_n='printf %s' else if test "X`(/usr/ucb/echo -n -n $as_echo) 2>/dev/null`" = "X-n $as_echo"; then as_echo_body='eval /usr/ucb/echo -n "$1$as_nl"' as_echo_n='/usr/ucb/echo -n' else as_echo_body='eval expr "X$1" : "X\\(.*\\)"' as_echo_n_body='eval arg=$1; case $arg in #( *"$as_nl"*) expr "X$arg" : "X\\(.*\\)$as_nl"; arg=`expr "X$arg" : ".*$as_nl\\(.*\\)"`;; esac; expr "X$arg" : "X\\(.*\\)" | tr -d "$as_nl" ' export as_echo_n_body as_echo_n='sh -c $as_echo_n_body as_echo' fi export as_echo_body as_echo='sh -c $as_echo_body as_echo' fi # The user is always right. if test "${PATH_SEPARATOR+set}" != set; then PATH_SEPARATOR=: (PATH='/bin;/bin'; FPATH=$PATH; sh -c :) >/dev/null 2>&1 && { (PATH='/bin:/bin'; FPATH=$PATH; sh -c :) >/dev/null 2>&1 || PATH_SEPARATOR=';' } fi # IFS # We need space, tab and new line, in precisely that order. Quoting is # there to prevent editors from complaining about space-tab. # (If _AS_PATH_WALK were called with IFS unset, it would disable word # splitting by setting IFS to empty value.) IFS=" "" $as_nl" # Find who we are. Look in the path if we contain no directory separator. as_myself= case $0 in #(( *[\\/]* ) as_myself=$0 ;; *) as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. test -r "$as_dir/$0" && as_myself=$as_dir/$0 && break done IFS=$as_save_IFS ;; esac # We did not find ourselves, most probably we were run as `sh COMMAND' # in which case we are not to be found in the path. if test "x$as_myself" = x; then as_myself=$0 fi if test ! -f "$as_myself"; then $as_echo "$as_myself: error: cannot find myself; rerun with an absolute file name" >&2 exit 1 fi # Unset variables that we do not need and which cause bugs (e.g. in # pre-3.0 UWIN ksh). But do not cause bugs in bash 2.01; the "|| exit 1" # suppresses any "Segmentation fault" message there. '((' could # trigger a bug in pdksh 5.2.14. for as_var in BASH_ENV ENV MAIL MAILPATH do eval test x\${$as_var+set} = xset \ && ( (unset $as_var) || exit 1) >/dev/null 2>&1 && unset $as_var || : done PS1='$ ' PS2='> ' PS4='+ ' # NLS nuisances. LC_ALL=C export LC_ALL LANGUAGE=C export LANGUAGE # CDPATH. (unset CDPATH) >/dev/null 2>&1 && unset CDPATH # Use a proper internal environment variable to ensure we don't fall # into an infinite loop, continuously re-executing ourselves. if test x"${_as_can_reexec}" != xno && test "x$CONFIG_SHELL" != x; then _as_can_reexec=no; export _as_can_reexec; # We cannot yet assume a decent shell, so we have to provide a # neutralization value for shells without unset; and this also # works around shells that cannot unset nonexistent variables. # Preserve -v and -x to the replacement shell. BASH_ENV=/dev/null ENV=/dev/null (unset BASH_ENV) >/dev/null 2>&1 && unset BASH_ENV ENV case $- in # (((( *v*x* | *x*v* ) as_opts=-vx ;; *v* ) as_opts=-v ;; *x* ) as_opts=-x ;; * ) as_opts= ;; esac exec $CONFIG_SHELL $as_opts "$as_myself" ${1+"$@"} # Admittedly, this is quite paranoid, since all the known shells bail # out after a failed `exec'. $as_echo "$0: could not re-execute with $CONFIG_SHELL" >&2 as_fn_exit 255 fi # We don't want this to propagate to other subprocesses. { _as_can_reexec=; unset _as_can_reexec;} if test "x$CONFIG_SHELL" = x; then as_bourne_compatible="if test -n \"\${ZSH_VERSION+set}\" && (emulate sh) >/dev/null 2>&1; then : emulate sh NULLCMD=: # Pre-4.2 versions of Zsh do word splitting on \${1+\"\$@\"}, which # is contrary to our usage. Disable this feature. alias -g '\${1+\"\$@\"}'='\"\$@\"' setopt NO_GLOB_SUBST else case \`(set -o) 2>/dev/null\` in #( *posix*) : set -o posix ;; #( *) : ;; esac fi " as_required="as_fn_return () { (exit \$1); } as_fn_success () { as_fn_return 0; } as_fn_failure () { as_fn_return 1; } as_fn_ret_success () { return 0; } as_fn_ret_failure () { return 1; } exitcode=0 as_fn_success || { exitcode=1; echo as_fn_success failed.; } as_fn_failure && { exitcode=1; echo as_fn_failure succeeded.; } as_fn_ret_success || { exitcode=1; echo as_fn_ret_success failed.; } as_fn_ret_failure && { exitcode=1; echo as_fn_ret_failure succeeded.; } if ( set x; as_fn_ret_success y && test x = \"\$1\" ); then : else exitcode=1; echo positional parameters were not saved. fi test x\$exitcode = x0 || exit 1 test -x / || exit 1" as_suggested=" as_lineno_1=";as_suggested=$as_suggested$LINENO;as_suggested=$as_suggested" as_lineno_1a=\$LINENO as_lineno_2=";as_suggested=$as_suggested$LINENO;as_suggested=$as_suggested" as_lineno_2a=\$LINENO eval 'test \"x\$as_lineno_1'\$as_run'\" != \"x\$as_lineno_2'\$as_run'\" && test \"x\`expr \$as_lineno_1'\$as_run' + 1\`\" = \"x\$as_lineno_2'\$as_run'\"' || exit 1 test \$(( 1 + 1 )) = 2 || exit 1 test -n \"\${ZSH_VERSION+set}\${BASH_VERSION+set}\" || ( ECHO='\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\' ECHO=\$ECHO\$ECHO\$ECHO\$ECHO\$ECHO ECHO=\$ECHO\$ECHO\$ECHO\$ECHO\$ECHO\$ECHO PATH=/empty FPATH=/empty; export PATH FPATH test \"X\`printf %s \$ECHO\`\" = \"X\$ECHO\" \\ || test \"X\`print -r -- \$ECHO\`\" = \"X\$ECHO\" ) || exit 1" if (eval "$as_required") 2>/dev/null; then : as_have_required=yes else as_have_required=no fi if test x$as_have_required = xyes && (eval "$as_suggested") 2>/dev/null; then : else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR as_found=false for as_dir in /bin$PATH_SEPARATOR/usr/bin$PATH_SEPARATOR$PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. as_found=: case $as_dir in #( /*) for as_base in sh bash ksh sh5; do # Try only shells that exist, to save several forks. as_shell=$as_dir/$as_base if { test -f "$as_shell" || test -f "$as_shell.exe"; } && { $as_echo "$as_bourne_compatible""$as_required" | as_run=a "$as_shell"; } 2>/dev/null; then : CONFIG_SHELL=$as_shell as_have_required=yes if { $as_echo "$as_bourne_compatible""$as_suggested" | as_run=a "$as_shell"; } 2>/dev/null; then : break 2 fi fi done;; esac as_found=false done $as_found || { if { test -f "$SHELL" || test -f "$SHELL.exe"; } && { $as_echo "$as_bourne_compatible""$as_required" | as_run=a "$SHELL"; } 2>/dev/null; then : CONFIG_SHELL=$SHELL as_have_required=yes fi; } IFS=$as_save_IFS if test "x$CONFIG_SHELL" != x; then : export CONFIG_SHELL # We cannot yet assume a decent shell, so we have to provide a # neutralization value for shells without unset; and this also # works around shells that cannot unset nonexistent variables. # Preserve -v and -x to the replacement shell. BASH_ENV=/dev/null ENV=/dev/null (unset BASH_ENV) >/dev/null 2>&1 && unset BASH_ENV ENV case $- in # (((( *v*x* | *x*v* ) as_opts=-vx ;; *v* ) as_opts=-v ;; *x* ) as_opts=-x ;; * ) as_opts= ;; esac exec $CONFIG_SHELL $as_opts "$as_myself" ${1+"$@"} # Admittedly, this is quite paranoid, since all the known shells bail # out after a failed `exec'. $as_echo "$0: could not re-execute with $CONFIG_SHELL" >&2 exit 255 fi if test x$as_have_required = xno; then : $as_echo "$0: This script requires a shell more modern than all" $as_echo "$0: the shells that I found on your system." if test x${ZSH_VERSION+set} = xset ; then $as_echo "$0: In particular, zsh $ZSH_VERSION has bugs and should" $as_echo "$0: be upgraded to zsh 4.3.4 or later." else $as_echo "$0: Please tell bug-autoconf@gnu.org about your system, $0: including any error possibly output before this $0: message. Then install a modern shell, or manually run $0: the script under such a shell if you do have one." fi exit 1 fi fi fi SHELL=${CONFIG_SHELL-/bin/sh} export SHELL # Unset more variables known to interfere with behavior of common tools. CLICOLOR_FORCE= GREP_OPTIONS= unset CLICOLOR_FORCE GREP_OPTIONS ## --------------------- ## ## M4sh Shell Functions. ## ## --------------------- ## # as_fn_unset VAR # --------------- # Portably unset VAR. as_fn_unset () { { eval $1=; unset $1;} } as_unset=as_fn_unset # as_fn_set_status STATUS # ----------------------- # Set $? to STATUS, without forking. as_fn_set_status () { return $1 } # as_fn_set_status # as_fn_exit STATUS # ----------------- # Exit the shell with STATUS, even in a "trap 0" or "set -e" context. as_fn_exit () { set +e as_fn_set_status $1 exit $1 } # as_fn_exit # as_fn_mkdir_p # ------------- # Create "$as_dir" as a directory, including parents if necessary. as_fn_mkdir_p () { case $as_dir in #( -*) as_dir=./$as_dir;; esac test -d "$as_dir" || eval $as_mkdir_p || { as_dirs= while :; do case $as_dir in #( *\'*) as_qdir=`$as_echo "$as_dir" | sed "s/'/'\\\\\\\\''/g"`;; #'( *) as_qdir=$as_dir;; esac as_dirs="'$as_qdir' $as_dirs" as_dir=`$as_dirname -- "$as_dir" || $as_expr X"$as_dir" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \ X"$as_dir" : 'X\(//\)[^/]' \| \ X"$as_dir" : 'X\(//\)$' \| \ X"$as_dir" : 'X\(/\)' \| . 2>/dev/null || $as_echo X"$as_dir" | sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{ s//\1/ q } /^X\(\/\/\)[^/].*/{ s//\1/ q } /^X\(\/\/\)$/{ s//\1/ q } /^X\(\/\).*/{ s//\1/ q } s/.*/./; q'` test -d "$as_dir" && break done test -z "$as_dirs" || eval "mkdir $as_dirs" } || test -d "$as_dir" || as_fn_error $? "cannot create directory $as_dir" } # as_fn_mkdir_p # as_fn_executable_p FILE # ----------------------- # Test if FILE is an executable regular file. as_fn_executable_p () { test -f "$1" && test -x "$1" } # as_fn_executable_p # as_fn_append VAR VALUE # ---------------------- # Append the text in VALUE to the end of the definition contained in VAR. Take # advantage of any shell optimizations that allow amortized linear growth over # repeated appends, instead of the typical quadratic growth present in naive # implementations. if (eval "as_var=1; as_var+=2; test x\$as_var = x12") 2>/dev/null; then : eval 'as_fn_append () { eval $1+=\$2 }' else as_fn_append () { eval $1=\$$1\$2 } fi # as_fn_append # as_fn_arith ARG... # ------------------ # Perform arithmetic evaluation on the ARGs, and store the result in the # global $as_val. Take advantage of shells that can avoid forks. The arguments # must be portable across $(()) and expr. if (eval "test \$(( 1 + 1 )) = 2") 2>/dev/null; then : eval 'as_fn_arith () { as_val=$(( $* )) }' else as_fn_arith () { as_val=`expr "$@" || test $? -eq 1` } fi # as_fn_arith # as_fn_error STATUS ERROR [LINENO LOG_FD] # ---------------------------------------- # Output "`basename $0`: error: ERROR" to stderr. If LINENO and LOG_FD are # provided, also output the error to LOG_FD, referencing LINENO. Then exit the # script with STATUS, using 1 if that was 0. as_fn_error () { as_status=$1; test $as_status -eq 0 && as_status=1 if test "$4"; then as_lineno=${as_lineno-"$3"} as_lineno_stack=as_lineno_stack=$as_lineno_stack $as_echo "$as_me:${as_lineno-$LINENO}: error: $2" >&$4 fi $as_echo "$as_me: error: $2" >&2 as_fn_exit $as_status } # as_fn_error if expr a : '\(a\)' >/dev/null 2>&1 && test "X`expr 00001 : '.*\(...\)'`" = X001; then as_expr=expr else as_expr=false fi if (basename -- /) >/dev/null 2>&1 && test "X`basename -- / 2>&1`" = "X/"; then as_basename=basename else as_basename=false fi if (as_dir=`dirname -- /` && test "X$as_dir" = X/) >/dev/null 2>&1; then as_dirname=dirname else as_dirname=false fi as_me=`$as_basename -- "$0" || $as_expr X/"$0" : '.*/\([^/][^/]*\)/*$' \| \ X"$0" : 'X\(//\)$' \| \ X"$0" : 'X\(/\)' \| . 2>/dev/null || $as_echo X/"$0" | sed '/^.*\/\([^/][^/]*\)\/*$/{ s//\1/ q } /^X\/\(\/\/\)$/{ s//\1/ q } /^X\/\(\/\).*/{ s//\1/ q } s/.*/./; q'` # Avoid depending upon Character Ranges. as_cr_letters='abcdefghijklmnopqrstuvwxyz' as_cr_LETTERS='ABCDEFGHIJKLMNOPQRSTUVWXYZ' as_cr_Letters=$as_cr_letters$as_cr_LETTERS as_cr_digits='0123456789' as_cr_alnum=$as_cr_Letters$as_cr_digits as_lineno_1=$LINENO as_lineno_1a=$LINENO as_lineno_2=$LINENO as_lineno_2a=$LINENO eval 'test "x$as_lineno_1'$as_run'" != "x$as_lineno_2'$as_run'" && test "x`expr $as_lineno_1'$as_run' + 1`" = "x$as_lineno_2'$as_run'"' || { # Blame Lee E. McMahon (1931-1989) for sed's syntax. :-) sed -n ' p /[$]LINENO/= ' <$as_myself | sed ' s/[$]LINENO.*/&-/ t lineno b :lineno N :loop s/[$]LINENO\([^'$as_cr_alnum'_].*\n\)\(.*\)/\2\1\2/ t loop s/-\n.*// ' >$as_me.lineno && chmod +x "$as_me.lineno" || { $as_echo "$as_me: error: cannot create $as_me.lineno; rerun with a POSIX shell" >&2; as_fn_exit 1; } # If we had to re-execute with $CONFIG_SHELL, we're ensured to have # already done that, so ensure we don't try to do so again and fall # in an infinite loop. This has already happened in practice. _as_can_reexec=no; export _as_can_reexec # Don't try to exec as it changes $[0], causing all sort of problems # (the dirname of $[0] is not the place where we might find the # original and so on. Autoconf is especially sensitive to this). . "./$as_me.lineno" # Exit status is that of the last command. exit } ECHO_C= ECHO_N= ECHO_T= case `echo -n x` in #((((( -n*) case `echo 'xy\c'` in *c*) ECHO_T=' ';; # ECHO_T is single tab character. xy) ECHO_C='\c';; *) echo `echo ksh88 bug on AIX 6.1` > /dev/null ECHO_T=' ';; esac;; *) ECHO_N='-n';; esac rm -f conf$$ conf$$.exe conf$$.file if test -d conf$$.dir; then rm -f conf$$.dir/conf$$.file else rm -f conf$$.dir mkdir conf$$.dir 2>/dev/null fi if (echo >conf$$.file) 2>/dev/null; then if ln -s conf$$.file conf$$ 2>/dev/null; then as_ln_s='ln -s' # ... but there are two gotchas: # 1) On MSYS, both `ln -s file dir' and `ln file dir' fail. # 2) DJGPP < 2.04 has no symlinks; `ln -s' creates a wrapper executable. # In both cases, we have to default to `cp -pR'. ln -s conf$$.file conf$$.dir 2>/dev/null && test ! -f conf$$.exe || as_ln_s='cp -pR' elif ln conf$$.file conf$$ 2>/dev/null; then as_ln_s=ln else as_ln_s='cp -pR' fi else as_ln_s='cp -pR' fi rm -f conf$$ conf$$.exe conf$$.dir/conf$$.file conf$$.file rmdir conf$$.dir 2>/dev/null if mkdir -p . 2>/dev/null; then as_mkdir_p='mkdir -p "$as_dir"' else test -d ./-p && rmdir ./-p as_mkdir_p=false fi as_test_x='test -x' as_executable_p=as_fn_executable_p # Sed expression to map a string onto a valid CPP name. as_tr_cpp="eval sed 'y%*$as_cr_letters%P$as_cr_LETTERS%;s%[^_$as_cr_alnum]%_%g'" # Sed expression to map a string onto a valid variable name. as_tr_sh="eval sed 'y%*+%pp%;s%[^_$as_cr_alnum]%_%g'" SHELL=${CONFIG_SHELL-/bin/sh} test -n "$DJDIR" || exec 7<&0 &1 # Name of the host. # hostname on some systems (SVR3.2, old GNU/Linux) returns a bogus exit status, # so uname gets run too. ac_hostname=`(hostname || uname -n) 2>/dev/null | sed 1q` # # Initializations. # ac_default_prefix=/usr/local ac_clean_files= ac_config_libobj_dir=. LIBOBJS= cross_compiling=no subdirs= MFLAGS= MAKEFLAGS= # Identity of this package. PACKAGE_NAME='libedit' PACKAGE_TARNAME='libedit-20171208' PACKAGE_VERSION='3.1' PACKAGE_STRING='libedit 3.1' PACKAGE_BUGREPORT='' PACKAGE_URL='' ac_unique_file="src/el.c" # Factoring default headers for most tests. ac_includes_default="\ #include #ifdef HAVE_SYS_TYPES_H # include #endif #ifdef HAVE_SYS_STAT_H # include #endif #ifdef STDC_HEADERS # include # include #else # ifdef HAVE_STDLIB_H # include # endif #endif #ifdef HAVE_STRING_H # if !defined STDC_HEADERS && defined HAVE_MEMORY_H # include # endif # include #endif #ifdef HAVE_STRINGS_H # include #endif #ifdef HAVE_INTTYPES_H # include #endif #ifdef HAVE_STDINT_H # include #endif #ifdef HAVE_UNISTD_H # include #endif" ac_subst_vars='am__EXEEXT_FALSE am__EXEEXT_TRUE LTLIBOBJS LIBOBJS MANTYPE NROFF LT_VERSION LT_SYS_LIBRARY_PATH OTOOL64 OTOOL LIPO NMEDIT DSYMUTIL MANIFEST_TOOL RANLIB ac_ct_AR AR DLLTOOL OBJDUMP LN_S NM ac_ct_DUMPBIN DUMPBIN LD FGREP SED host_os host_vendor host_cpu host build_os build_vendor build_cpu build LIBTOOL AM_BACKSLASH AM_DEFAULT_VERBOSITY AM_DEFAULT_V AM_V am__fastdepCC_FALSE am__fastdepCC_TRUE CCDEPMODE am__nodep AMDEPBACKSLASH AMDEP_FALSE AMDEP_TRUE am__quote am__include DEPDIR am__untar am__tar AMTAR am__leading_dot SET_MAKE AWK mkdir_p MKDIR_P INSTALL_STRIP_PROGRAM STRIP install_sh MAKEINFO AUTOHEADER AUTOMAKE AUTOCONF ACLOCAL VERSION PACKAGE CYGPATH_W am__isrc INSTALL_DATA INSTALL_SCRIPT INSTALL_PROGRAM EGREP GREP CPP OBJEXT EXEEXT ac_ct_CC CPPFLAGS LDFLAGS CFLAGS CC target_alias host_alias build_alias LIBS ECHO_T ECHO_N ECHO_C DEFS mandir localedir libdir psdir pdfdir dvidir htmldir infodir docdir oldincludedir includedir localstatedir sharedstatedir sysconfdir datadir datarootdir libexecdir sbindir bindir program_transform_name prefix exec_prefix PACKAGE_URL PACKAGE_BUGREPORT PACKAGE_STRING PACKAGE_VERSION PACKAGE_TARNAME PACKAGE_NAME PATH_SEPARATOR SHELL' ac_subst_files='' ac_user_opts=' enable_option_checking enable_dependency_tracking enable_silent_rules enable_shared enable_static with_pic enable_fast_install with_aix_soname with_gnu_ld with_sysroot enable_libtool_lock ' ac_precious_vars='build_alias host_alias target_alias CC CFLAGS LDFLAGS LIBS CPPFLAGS CPP LT_SYS_LIBRARY_PATH' # Initialize some variables set by options. ac_init_help= ac_init_version=false ac_unrecognized_opts= ac_unrecognized_sep= # The variables have the same names as the options, with # dashes changed to underlines. cache_file=/dev/null exec_prefix=NONE no_create= no_recursion= prefix=NONE program_prefix=NONE program_suffix=NONE program_transform_name=s,x,x, silent= site= srcdir= verbose= x_includes=NONE x_libraries=NONE # Installation directory options. # These are left unexpanded so users can "make install exec_prefix=/foo" # and all the variables that are supposed to be based on exec_prefix # by default will actually change. # Use braces instead of parens because sh, perl, etc. also accept them. # (The list follows the same order as the GNU Coding Standards.) bindir='${exec_prefix}/bin' sbindir='${exec_prefix}/sbin' libexecdir='${exec_prefix}/libexec' datarootdir='${prefix}/share' datadir='${datarootdir}' sysconfdir='${prefix}/etc' sharedstatedir='${prefix}/com' localstatedir='${prefix}/var' includedir='${prefix}/include' oldincludedir='/usr/include' docdir='${datarootdir}/doc/${PACKAGE_TARNAME}' infodir='${datarootdir}/info' htmldir='${docdir}' dvidir='${docdir}' pdfdir='${docdir}' psdir='${docdir}' libdir='${exec_prefix}/lib' localedir='${datarootdir}/locale' mandir='${datarootdir}/man' ac_prev= ac_dashdash= for ac_option do # If the previous option needs an argument, assign it. if test -n "$ac_prev"; then eval $ac_prev=\$ac_option ac_prev= continue fi case $ac_option in *=?*) ac_optarg=`expr "X$ac_option" : '[^=]*=\(.*\)'` ;; *=) ac_optarg= ;; *) ac_optarg=yes ;; esac # Accept the important Cygnus configure options, so we can diagnose typos. case $ac_dashdash$ac_option in --) ac_dashdash=yes ;; -bindir | --bindir | --bindi | --bind | --bin | --bi) ac_prev=bindir ;; -bindir=* | --bindir=* | --bindi=* | --bind=* | --bin=* | --bi=*) bindir=$ac_optarg ;; -build | --build | --buil | --bui | --bu) ac_prev=build_alias ;; -build=* | --build=* | --buil=* | --bui=* | --bu=*) build_alias=$ac_optarg ;; -cache-file | --cache-file | --cache-fil | --cache-fi \ | --cache-f | --cache- | --cache | --cach | --cac | --ca | --c) ac_prev=cache_file ;; -cache-file=* | --cache-file=* | --cache-fil=* | --cache-fi=* \ | --cache-f=* | --cache-=* | --cache=* | --cach=* | --cac=* | --ca=* | --c=*) cache_file=$ac_optarg ;; --config-cache | -C) cache_file=config.cache ;; -datadir | --datadir | --datadi | --datad) ac_prev=datadir ;; -datadir=* | --datadir=* | --datadi=* | --datad=*) datadir=$ac_optarg ;; -datarootdir | --datarootdir | --datarootdi | --datarootd | --dataroot \ | --dataroo | --dataro | --datar) ac_prev=datarootdir ;; -datarootdir=* | --datarootdir=* | --datarootdi=* | --datarootd=* \ | --dataroot=* | --dataroo=* | --dataro=* | --datar=*) datarootdir=$ac_optarg ;; -disable-* | --disable-*) ac_useropt=`expr "x$ac_option" : 'x-*disable-\(.*\)'` # Reject names that are not valid shell variable names. expr "x$ac_useropt" : ".*[^-+._$as_cr_alnum]" >/dev/null && as_fn_error $? "invalid feature name: $ac_useropt" ac_useropt_orig=$ac_useropt ac_useropt=`$as_echo "$ac_useropt" | sed 's/[-+.]/_/g'` case $ac_user_opts in *" "enable_$ac_useropt" "*) ;; *) ac_unrecognized_opts="$ac_unrecognized_opts$ac_unrecognized_sep--disable-$ac_useropt_orig" ac_unrecognized_sep=', ';; esac eval enable_$ac_useropt=no ;; -docdir | --docdir | --docdi | --doc | --do) ac_prev=docdir ;; -docdir=* | --docdir=* | --docdi=* | --doc=* | --do=*) docdir=$ac_optarg ;; -dvidir | --dvidir | --dvidi | --dvid | --dvi | --dv) ac_prev=dvidir ;; -dvidir=* | --dvidir=* | --dvidi=* | --dvid=* | --dvi=* | --dv=*) dvidir=$ac_optarg ;; -enable-* | --enable-*) ac_useropt=`expr "x$ac_option" : 'x-*enable-\([^=]*\)'` # Reject names that are not valid shell variable names. expr "x$ac_useropt" : ".*[^-+._$as_cr_alnum]" >/dev/null && as_fn_error $? "invalid feature name: $ac_useropt" ac_useropt_orig=$ac_useropt ac_useropt=`$as_echo "$ac_useropt" | sed 's/[-+.]/_/g'` case $ac_user_opts in *" "enable_$ac_useropt" "*) ;; *) ac_unrecognized_opts="$ac_unrecognized_opts$ac_unrecognized_sep--enable-$ac_useropt_orig" ac_unrecognized_sep=', ';; esac eval enable_$ac_useropt=\$ac_optarg ;; -exec-prefix | --exec_prefix | --exec-prefix | --exec-prefi \ | --exec-pref | --exec-pre | --exec-pr | --exec-p | --exec- \ | --exec | --exe | --ex) ac_prev=exec_prefix ;; -exec-prefix=* | --exec_prefix=* | --exec-prefix=* | --exec-prefi=* \ | --exec-pref=* | --exec-pre=* | --exec-pr=* | --exec-p=* | --exec-=* \ | --exec=* | --exe=* | --ex=*) exec_prefix=$ac_optarg ;; -gas | --gas | --ga | --g) # Obsolete; use --with-gas. with_gas=yes ;; -help | --help | --hel | --he | -h) ac_init_help=long ;; -help=r* | --help=r* | --hel=r* | --he=r* | -hr*) ac_init_help=recursive ;; -help=s* | --help=s* | --hel=s* | --he=s* | -hs*) ac_init_help=short ;; -host | --host | --hos | --ho) ac_prev=host_alias ;; -host=* | --host=* | --hos=* | --ho=*) host_alias=$ac_optarg ;; -htmldir | --htmldir | --htmldi | --htmld | --html | --htm | --ht) ac_prev=htmldir ;; -htmldir=* | --htmldir=* | --htmldi=* | --htmld=* | --html=* | --htm=* \ | --ht=*) htmldir=$ac_optarg ;; -includedir | --includedir | --includedi | --included | --include \ | --includ | --inclu | --incl | --inc) ac_prev=includedir ;; -includedir=* | --includedir=* | --includedi=* | --included=* | --include=* \ | --includ=* | --inclu=* | --incl=* | --inc=*) includedir=$ac_optarg ;; -infodir | --infodir | --infodi | --infod | --info | --inf) ac_prev=infodir ;; -infodir=* | --infodir=* | --infodi=* | --infod=* | --info=* | --inf=*) infodir=$ac_optarg ;; -libdir | --libdir | --libdi | --libd) ac_prev=libdir ;; -libdir=* | --libdir=* | --libdi=* | --libd=*) libdir=$ac_optarg ;; -libexecdir | --libexecdir | --libexecdi | --libexecd | --libexec \ | --libexe | --libex | --libe) ac_prev=libexecdir ;; -libexecdir=* | --libexecdir=* | --libexecdi=* | --libexecd=* | --libexec=* \ | --libexe=* | --libex=* | --libe=*) libexecdir=$ac_optarg ;; -localedir | --localedir | --localedi | --localed | --locale) ac_prev=localedir ;; -localedir=* | --localedir=* | --localedi=* | --localed=* | --locale=*) localedir=$ac_optarg ;; -localstatedir | --localstatedir | --localstatedi | --localstated \ | --localstate | --localstat | --localsta | --localst | --locals) ac_prev=localstatedir ;; -localstatedir=* | --localstatedir=* | --localstatedi=* | --localstated=* \ | --localstate=* | --localstat=* | --localsta=* | --localst=* | --locals=*) localstatedir=$ac_optarg ;; -mandir | --mandir | --mandi | --mand | --man | --ma | --m) ac_prev=mandir ;; -mandir=* | --mandir=* | --mandi=* | --mand=* | --man=* | --ma=* | --m=*) mandir=$ac_optarg ;; -nfp | --nfp | --nf) # Obsolete; use --without-fp. with_fp=no ;; -no-create | --no-create | --no-creat | --no-crea | --no-cre \ | --no-cr | --no-c | -n) no_create=yes ;; -no-recursion | --no-recursion | --no-recursio | --no-recursi \ | --no-recurs | --no-recur | --no-recu | --no-rec | --no-re | --no-r) no_recursion=yes ;; -oldincludedir | --oldincludedir | --oldincludedi | --oldincluded \ | --oldinclude | --oldinclud | --oldinclu | --oldincl | --oldinc \ | --oldin | --oldi | --old | --ol | --o) ac_prev=oldincludedir ;; -oldincludedir=* | --oldincludedir=* | --oldincludedi=* | --oldincluded=* \ | --oldinclude=* | --oldinclud=* | --oldinclu=* | --oldincl=* | --oldinc=* \ | --oldin=* | --oldi=* | --old=* | --ol=* | --o=*) oldincludedir=$ac_optarg ;; -prefix | --prefix | --prefi | --pref | --pre | --pr | --p) ac_prev=prefix ;; -prefix=* | --prefix=* | --prefi=* | --pref=* | --pre=* | --pr=* | --p=*) prefix=$ac_optarg ;; -program-prefix | --program-prefix | --program-prefi | --program-pref \ | --program-pre | --program-pr | --program-p) ac_prev=program_prefix ;; -program-prefix=* | --program-prefix=* | --program-prefi=* \ | --program-pref=* | --program-pre=* | --program-pr=* | --program-p=*) program_prefix=$ac_optarg ;; -program-suffix | --program-suffix | --program-suffi | --program-suff \ | --program-suf | --program-su | --program-s) ac_prev=program_suffix ;; -program-suffix=* | --program-suffix=* | --program-suffi=* \ | --program-suff=* | --program-suf=* | --program-su=* | --program-s=*) program_suffix=$ac_optarg ;; -program-transform-name | --program-transform-name \ | --program-transform-nam | --program-transform-na \ | --program-transform-n | --program-transform- \ | --program-transform | --program-transfor \ | --program-transfo | --program-transf \ | --program-trans | --program-tran \ | --progr-tra | --program-tr | --program-t) ac_prev=program_transform_name ;; -program-transform-name=* | --program-transform-name=* \ | --program-transform-nam=* | --program-transform-na=* \ | --program-transform-n=* | --program-transform-=* \ | --program-transform=* | --program-transfor=* \ | --program-transfo=* | --program-transf=* \ | --program-trans=* | --program-tran=* \ | --progr-tra=* | --program-tr=* | --program-t=*) program_transform_name=$ac_optarg ;; -pdfdir | --pdfdir | --pdfdi | --pdfd | --pdf | --pd) ac_prev=pdfdir ;; -pdfdir=* | --pdfdir=* | --pdfdi=* | --pdfd=* | --pdf=* | --pd=*) pdfdir=$ac_optarg ;; -psdir | --psdir | --psdi | --psd | --ps) ac_prev=psdir ;; -psdir=* | --psdir=* | --psdi=* | --psd=* | --ps=*) psdir=$ac_optarg ;; -q | -quiet | --quiet | --quie | --qui | --qu | --q \ | -silent | --silent | --silen | --sile | --sil) silent=yes ;; -sbindir | --sbindir | --sbindi | --sbind | --sbin | --sbi | --sb) ac_prev=sbindir ;; -sbindir=* | --sbindir=* | --sbindi=* | --sbind=* | --sbin=* \ | --sbi=* | --sb=*) sbindir=$ac_optarg ;; -sharedstatedir | --sharedstatedir | --sharedstatedi \ | --sharedstated | --sharedstate | --sharedstat | --sharedsta \ | --sharedst | --shareds | --shared | --share | --shar \ | --sha | --sh) ac_prev=sharedstatedir ;; -sharedstatedir=* | --sharedstatedir=* | --sharedstatedi=* \ | --sharedstated=* | --sharedstate=* | --sharedstat=* | --sharedsta=* \ | --sharedst=* | --shareds=* | --shared=* | --share=* | --shar=* \ | --sha=* | --sh=*) sharedstatedir=$ac_optarg ;; -site | --site | --sit) ac_prev=site ;; -site=* | --site=* | --sit=*) site=$ac_optarg ;; -srcdir | --srcdir | --srcdi | --srcd | --src | --sr) ac_prev=srcdir ;; -srcdir=* | --srcdir=* | --srcdi=* | --srcd=* | --src=* | --sr=*) srcdir=$ac_optarg ;; -sysconfdir | --sysconfdir | --sysconfdi | --sysconfd | --sysconf \ | --syscon | --sysco | --sysc | --sys | --sy) ac_prev=sysconfdir ;; -sysconfdir=* | --sysconfdir=* | --sysconfdi=* | --sysconfd=* | --sysconf=* \ | --syscon=* | --sysco=* | --sysc=* | --sys=* | --sy=*) sysconfdir=$ac_optarg ;; -target | --target | --targe | --targ | --tar | --ta | --t) ac_prev=target_alias ;; -target=* | --target=* | --targe=* | --targ=* | --tar=* | --ta=* | --t=*) target_alias=$ac_optarg ;; -v | -verbose | --verbose | --verbos | --verbo | --verb) verbose=yes ;; -version | --version | --versio | --versi | --vers | -V) ac_init_version=: ;; -with-* | --with-*) ac_useropt=`expr "x$ac_option" : 'x-*with-\([^=]*\)'` # Reject names that are not valid shell variable names. expr "x$ac_useropt" : ".*[^-+._$as_cr_alnum]" >/dev/null && as_fn_error $? "invalid package name: $ac_useropt" ac_useropt_orig=$ac_useropt ac_useropt=`$as_echo "$ac_useropt" | sed 's/[-+.]/_/g'` case $ac_user_opts in *" "with_$ac_useropt" "*) ;; *) ac_unrecognized_opts="$ac_unrecognized_opts$ac_unrecognized_sep--with-$ac_useropt_orig" ac_unrecognized_sep=', ';; esac eval with_$ac_useropt=\$ac_optarg ;; -without-* | --without-*) ac_useropt=`expr "x$ac_option" : 'x-*without-\(.*\)'` # Reject names that are not valid shell variable names. expr "x$ac_useropt" : ".*[^-+._$as_cr_alnum]" >/dev/null && as_fn_error $? "invalid package name: $ac_useropt" ac_useropt_orig=$ac_useropt ac_useropt=`$as_echo "$ac_useropt" | sed 's/[-+.]/_/g'` case $ac_user_opts in *" "with_$ac_useropt" "*) ;; *) ac_unrecognized_opts="$ac_unrecognized_opts$ac_unrecognized_sep--without-$ac_useropt_orig" ac_unrecognized_sep=', ';; esac eval with_$ac_useropt=no ;; --x) # Obsolete; use --with-x. with_x=yes ;; -x-includes | --x-includes | --x-include | --x-includ | --x-inclu \ | --x-incl | --x-inc | --x-in | --x-i) ac_prev=x_includes ;; -x-includes=* | --x-includes=* | --x-include=* | --x-includ=* | --x-inclu=* \ | --x-incl=* | --x-inc=* | --x-in=* | --x-i=*) x_includes=$ac_optarg ;; -x-libraries | --x-libraries | --x-librarie | --x-librari \ | --x-librar | --x-libra | --x-libr | --x-lib | --x-li | --x-l) ac_prev=x_libraries ;; -x-libraries=* | --x-libraries=* | --x-librarie=* | --x-librari=* \ | --x-librar=* | --x-libra=* | --x-libr=* | --x-lib=* | --x-li=* | --x-l=*) x_libraries=$ac_optarg ;; -*) as_fn_error $? "unrecognized option: \`$ac_option' Try \`$0 --help' for more information" ;; *=*) ac_envvar=`expr "x$ac_option" : 'x\([^=]*\)='` # Reject names that are not valid shell variable names. case $ac_envvar in #( '' | [0-9]* | *[!_$as_cr_alnum]* ) as_fn_error $? "invalid variable name: \`$ac_envvar'" ;; esac eval $ac_envvar=\$ac_optarg export $ac_envvar ;; *) # FIXME: should be removed in autoconf 3.0. $as_echo "$as_me: WARNING: you should use --build, --host, --target" >&2 expr "x$ac_option" : ".*[^-._$as_cr_alnum]" >/dev/null && $as_echo "$as_me: WARNING: invalid host type: $ac_option" >&2 : "${build_alias=$ac_option} ${host_alias=$ac_option} ${target_alias=$ac_option}" ;; esac done if test -n "$ac_prev"; then ac_option=--`echo $ac_prev | sed 's/_/-/g'` as_fn_error $? "missing argument to $ac_option" fi if test -n "$ac_unrecognized_opts"; then case $enable_option_checking in no) ;; fatal) as_fn_error $? "unrecognized options: $ac_unrecognized_opts" ;; *) $as_echo "$as_me: WARNING: unrecognized options: $ac_unrecognized_opts" >&2 ;; esac fi # Check all directory arguments for consistency. for ac_var in exec_prefix prefix bindir sbindir libexecdir datarootdir \ datadir sysconfdir sharedstatedir localstatedir includedir \ oldincludedir docdir infodir htmldir dvidir pdfdir psdir \ libdir localedir mandir do eval ac_val=\$$ac_var # Remove trailing slashes. case $ac_val in */ ) ac_val=`expr "X$ac_val" : 'X\(.*[^/]\)' \| "X$ac_val" : 'X\(.*\)'` eval $ac_var=\$ac_val;; esac # Be sure to have absolute directory names. case $ac_val in [\\/$]* | ?:[\\/]* ) continue;; NONE | '' ) case $ac_var in *prefix ) continue;; esac;; esac as_fn_error $? "expected an absolute directory name for --$ac_var: $ac_val" done # There might be people who depend on the old broken behavior: `$host' # used to hold the argument of --host etc. # FIXME: To remove some day. build=$build_alias host=$host_alias target=$target_alias # FIXME: To remove some day. if test "x$host_alias" != x; then if test "x$build_alias" = x; then cross_compiling=maybe elif test "x$build_alias" != "x$host_alias"; then cross_compiling=yes fi fi ac_tool_prefix= test -n "$host_alias" && ac_tool_prefix=$host_alias- test "$silent" = yes && exec 6>/dev/null ac_pwd=`pwd` && test -n "$ac_pwd" && ac_ls_di=`ls -di .` && ac_pwd_ls_di=`cd "$ac_pwd" && ls -di .` || as_fn_error $? "working directory cannot be determined" test "X$ac_ls_di" = "X$ac_pwd_ls_di" || as_fn_error $? "pwd does not report name of working directory" # Find the source files, if location was not specified. if test -z "$srcdir"; then ac_srcdir_defaulted=yes # Try the directory containing this script, then the parent directory. ac_confdir=`$as_dirname -- "$as_myself" || $as_expr X"$as_myself" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \ X"$as_myself" : 'X\(//\)[^/]' \| \ X"$as_myself" : 'X\(//\)$' \| \ X"$as_myself" : 'X\(/\)' \| . 2>/dev/null || $as_echo X"$as_myself" | sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{ s//\1/ q } /^X\(\/\/\)[^/].*/{ s//\1/ q } /^X\(\/\/\)$/{ s//\1/ q } /^X\(\/\).*/{ s//\1/ q } s/.*/./; q'` srcdir=$ac_confdir if test ! -r "$srcdir/$ac_unique_file"; then srcdir=.. fi else ac_srcdir_defaulted=no fi if test ! -r "$srcdir/$ac_unique_file"; then test "$ac_srcdir_defaulted" = yes && srcdir="$ac_confdir or .." as_fn_error $? "cannot find sources ($ac_unique_file) in $srcdir" fi ac_msg="sources are in $srcdir, but \`cd $srcdir' does not work" ac_abs_confdir=`( cd "$srcdir" && test -r "./$ac_unique_file" || as_fn_error $? "$ac_msg" pwd)` # When building in place, set srcdir=. if test "$ac_abs_confdir" = "$ac_pwd"; then srcdir=. fi # Remove unnecessary trailing slashes from srcdir. # Double slashes in file names in object file debugging info # mess up M-x gdb in Emacs. case $srcdir in */) srcdir=`expr "X$srcdir" : 'X\(.*[^/]\)' \| "X$srcdir" : 'X\(.*\)'`;; esac for ac_var in $ac_precious_vars; do eval ac_env_${ac_var}_set=\${${ac_var}+set} eval ac_env_${ac_var}_value=\$${ac_var} eval ac_cv_env_${ac_var}_set=\${${ac_var}+set} eval ac_cv_env_${ac_var}_value=\$${ac_var} done # # Report the --help message. # if test "$ac_init_help" = "long"; then # Omit some internal or obsolete options to make the list less imposing. # This message is too long to be a string in the A/UX 3.1 sh. cat <<_ACEOF \`configure' configures libedit 3.1 to adapt to many kinds of systems. Usage: $0 [OPTION]... [VAR=VALUE]... To assign environment variables (e.g., CC, CFLAGS...), specify them as VAR=VALUE. See below for descriptions of some of the useful variables. Defaults for the options are specified in brackets. Configuration: -h, --help display this help and exit --help=short display options specific to this package --help=recursive display the short help of all the included packages -V, --version display version information and exit -q, --quiet, --silent do not print \`checking ...' messages --cache-file=FILE cache test results in FILE [disabled] -C, --config-cache alias for \`--cache-file=config.cache' -n, --no-create do not create output files --srcdir=DIR find the sources in DIR [configure dir or \`..'] Installation directories: --prefix=PREFIX install architecture-independent files in PREFIX [$ac_default_prefix] --exec-prefix=EPREFIX install architecture-dependent files in EPREFIX [PREFIX] By default, \`make install' will install all the files in \`$ac_default_prefix/bin', \`$ac_default_prefix/lib' etc. You can specify an installation prefix other than \`$ac_default_prefix' using \`--prefix', for instance \`--prefix=\$HOME'. For better control, use the options below. Fine tuning of the installation directories: --bindir=DIR user executables [EPREFIX/bin] --sbindir=DIR system admin executables [EPREFIX/sbin] --libexecdir=DIR program executables [EPREFIX/libexec] --sysconfdir=DIR read-only single-machine data [PREFIX/etc] --sharedstatedir=DIR modifiable architecture-independent data [PREFIX/com] --localstatedir=DIR modifiable single-machine data [PREFIX/var] --libdir=DIR object code libraries [EPREFIX/lib] --includedir=DIR C header files [PREFIX/include] --oldincludedir=DIR C header files for non-gcc [/usr/include] --datarootdir=DIR read-only arch.-independent data root [PREFIX/share] --datadir=DIR read-only architecture-independent data [DATAROOTDIR] --infodir=DIR info documentation [DATAROOTDIR/info] --localedir=DIR locale-dependent data [DATAROOTDIR/locale] --mandir=DIR man documentation [DATAROOTDIR/man] --docdir=DIR documentation root [DATAROOTDIR/doc/libedit-20171208] --htmldir=DIR html documentation [DOCDIR] --dvidir=DIR dvi documentation [DOCDIR] --pdfdir=DIR pdf documentation [DOCDIR] --psdir=DIR ps documentation [DOCDIR] _ACEOF cat <<\_ACEOF Program names: --program-prefix=PREFIX prepend PREFIX to installed program names --program-suffix=SUFFIX append SUFFIX to installed program names --program-transform-name=PROGRAM run sed PROGRAM on installed program names System types: --build=BUILD configure for building on BUILD [guessed] --host=HOST cross-compile to build programs to run on HOST [BUILD] _ACEOF fi if test -n "$ac_init_help"; then case $ac_init_help in short | recursive ) echo "Configuration of libedit 3.1:";; esac cat <<\_ACEOF Optional Features: --disable-option-checking ignore unrecognized --enable/--with options --disable-FEATURE do not include FEATURE (same as --enable-FEATURE=no) --enable-FEATURE[=ARG] include FEATURE [ARG=yes] --enable-dependency-tracking do not reject slow dependency extractors --disable-dependency-tracking speeds up one-time build --enable-silent-rules less verbose build output (undo: "make V=1") --disable-silent-rules verbose build output (undo: "make V=0") --enable-shared[=PKGS] build shared libraries [default=yes] --enable-static[=PKGS] build static libraries [default=yes] --enable-fast-install[=PKGS] optimize for fast installation [default=yes] --disable-libtool-lock avoid locking (might break parallel builds) Optional Packages: --with-PACKAGE[=ARG] use PACKAGE [ARG=yes] --without-PACKAGE do not use PACKAGE (same as --with-PACKAGE=no) --with-pic[=PKGS] try to use only PIC/non-PIC objects [default=use both] --with-aix-soname=aix|svr4|both shared library versioning (aka "SONAME") variant to provide on AIX, [default=aix]. --with-gnu-ld assume the C compiler uses GNU ld [default=no] --with-sysroot[=DIR] Search for dependent libraries within DIR (or the compiler's sysroot if not specified). Some influential environment variables: CC C compiler command CFLAGS C compiler flags LDFLAGS linker flags, e.g. -L if you have libraries in a nonstandard directory LIBS libraries to pass to the linker, e.g. -l CPPFLAGS (Objective) C/C++ preprocessor flags, e.g. -I if you have headers in a nonstandard directory CPP C preprocessor LT_SYS_LIBRARY_PATH User-defined run-time library search path. Use these variables to override the choices made by `configure' or to help it to find libraries and programs with nonstandard names/locations. Report bugs to the package provider. _ACEOF ac_status=$? fi if test "$ac_init_help" = "recursive"; then # If there are subdirs, report their specific --help. for ac_dir in : $ac_subdirs_all; do test "x$ac_dir" = x: && continue test -d "$ac_dir" || { cd "$srcdir" && ac_pwd=`pwd` && srcdir=. && test -d "$ac_dir"; } || continue ac_builddir=. case "$ac_dir" in .) ac_dir_suffix= ac_top_builddir_sub=. ac_top_build_prefix= ;; *) ac_dir_suffix=/`$as_echo "$ac_dir" | sed 's|^\.[\\/]||'` # A ".." for each directory in $ac_dir_suffix. ac_top_builddir_sub=`$as_echo "$ac_dir_suffix" | sed 's|/[^\\/]*|/..|g;s|/||'` case $ac_top_builddir_sub in "") ac_top_builddir_sub=. ac_top_build_prefix= ;; *) ac_top_build_prefix=$ac_top_builddir_sub/ ;; esac ;; esac ac_abs_top_builddir=$ac_pwd ac_abs_builddir=$ac_pwd$ac_dir_suffix # for backward compatibility: ac_top_builddir=$ac_top_build_prefix case $srcdir in .) # We are building in place. ac_srcdir=. ac_top_srcdir=$ac_top_builddir_sub ac_abs_top_srcdir=$ac_pwd ;; [\\/]* | ?:[\\/]* ) # Absolute name. ac_srcdir=$srcdir$ac_dir_suffix; ac_top_srcdir=$srcdir ac_abs_top_srcdir=$srcdir ;; *) # Relative name. ac_srcdir=$ac_top_build_prefix$srcdir$ac_dir_suffix ac_top_srcdir=$ac_top_build_prefix$srcdir ac_abs_top_srcdir=$ac_pwd/$srcdir ;; esac ac_abs_srcdir=$ac_abs_top_srcdir$ac_dir_suffix cd "$ac_dir" || { ac_status=$?; continue; } # Check for guested configure. if test -f "$ac_srcdir/configure.gnu"; then echo && $SHELL "$ac_srcdir/configure.gnu" --help=recursive elif test -f "$ac_srcdir/configure"; then echo && $SHELL "$ac_srcdir/configure" --help=recursive else $as_echo "$as_me: WARNING: no configuration information is in $ac_dir" >&2 fi || ac_status=$? cd "$ac_pwd" || { ac_status=$?; break; } done fi test -n "$ac_init_help" && exit $ac_status if $ac_init_version; then cat <<\_ACEOF libedit configure 3.1 generated by GNU Autoconf 2.69 Copyright (C) 2012 Free Software Foundation, Inc. This configure script is free software; the Free Software Foundation gives unlimited permission to copy, distribute and modify it. _ACEOF exit fi ## ------------------------ ## ## Autoconf initialization. ## ## ------------------------ ## # ac_fn_c_try_compile LINENO # -------------------------- # Try to compile conftest.$ac_ext, and return whether this succeeded. ac_fn_c_try_compile () { as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack rm -f conftest.$ac_objext if { { ac_try="$ac_compile" case "(($ac_try" in *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" $as_echo "$ac_try_echo"; } >&5 (eval "$ac_compile") 2>conftest.err ac_status=$? if test -s conftest.err; then grep -v '^ *+' conftest.err >conftest.er1 cat conftest.er1 >&5 mv -f conftest.er1 conftest.err fi $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 test $ac_status = 0; } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err } && test -s conftest.$ac_objext; then : ac_retval=0 else $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_retval=1 fi eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno as_fn_set_status $ac_retval } # ac_fn_c_try_compile # ac_fn_c_try_cpp LINENO # ---------------------- # Try to preprocess conftest.$ac_ext, and return whether this succeeded. ac_fn_c_try_cpp () { as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack if { { ac_try="$ac_cpp conftest.$ac_ext" case "(($ac_try" in *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" $as_echo "$ac_try_echo"; } >&5 (eval "$ac_cpp conftest.$ac_ext") 2>conftest.err ac_status=$? if test -s conftest.err; then grep -v '^ *+' conftest.err >conftest.er1 cat conftest.er1 >&5 mv -f conftest.er1 conftest.err fi $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 test $ac_status = 0; } > conftest.i && { test -z "$ac_c_preproc_warn_flag$ac_c_werror_flag" || test ! -s conftest.err }; then : ac_retval=0 else $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_retval=1 fi eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno as_fn_set_status $ac_retval } # ac_fn_c_try_cpp # ac_fn_c_check_header_mongrel LINENO HEADER VAR INCLUDES # ------------------------------------------------------- # Tests whether HEADER exists, giving a warning if it cannot be compiled using # the include files in INCLUDES and setting the cache variable VAR # accordingly. ac_fn_c_check_header_mongrel () { as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack if eval \${$3+:} false; then : { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $2" >&5 $as_echo_n "checking for $2... " >&6; } if eval \${$3+:} false; then : $as_echo_n "(cached) " >&6 fi eval ac_res=\$$3 { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_res" >&5 $as_echo "$ac_res" >&6; } else # Is the header compilable? { $as_echo "$as_me:${as_lineno-$LINENO}: checking $2 usability" >&5 $as_echo_n "checking $2 usability... " >&6; } cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ $4 #include <$2> _ACEOF if ac_fn_c_try_compile "$LINENO"; then : ac_header_compiler=yes else ac_header_compiler=no fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_header_compiler" >&5 $as_echo "$ac_header_compiler" >&6; } # Is the header present? { $as_echo "$as_me:${as_lineno-$LINENO}: checking $2 presence" >&5 $as_echo_n "checking $2 presence... " >&6; } cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #include <$2> _ACEOF if ac_fn_c_try_cpp "$LINENO"; then : ac_header_preproc=yes else ac_header_preproc=no fi rm -f conftest.err conftest.i conftest.$ac_ext { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_header_preproc" >&5 $as_echo "$ac_header_preproc" >&6; } # So? What about this header? case $ac_header_compiler:$ac_header_preproc:$ac_c_preproc_warn_flag in #(( yes:no: ) { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $2: accepted by the compiler, rejected by the preprocessor!" >&5 $as_echo "$as_me: WARNING: $2: accepted by the compiler, rejected by the preprocessor!" >&2;} { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $2: proceeding with the compiler's result" >&5 $as_echo "$as_me: WARNING: $2: proceeding with the compiler's result" >&2;} ;; no:yes:* ) { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $2: present but cannot be compiled" >&5 $as_echo "$as_me: WARNING: $2: present but cannot be compiled" >&2;} { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $2: check for missing prerequisite headers?" >&5 $as_echo "$as_me: WARNING: $2: check for missing prerequisite headers?" >&2;} { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $2: see the Autoconf documentation" >&5 $as_echo "$as_me: WARNING: $2: see the Autoconf documentation" >&2;} { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $2: section \"Present But Cannot Be Compiled\"" >&5 $as_echo "$as_me: WARNING: $2: section \"Present But Cannot Be Compiled\"" >&2;} { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $2: proceeding with the compiler's result" >&5 $as_echo "$as_me: WARNING: $2: proceeding with the compiler's result" >&2;} ;; esac { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $2" >&5 $as_echo_n "checking for $2... " >&6; } if eval \${$3+:} false; then : $as_echo_n "(cached) " >&6 else eval "$3=\$ac_header_compiler" fi eval ac_res=\$$3 { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_res" >&5 $as_echo "$ac_res" >&6; } fi eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno } # ac_fn_c_check_header_mongrel # ac_fn_c_try_run LINENO # ---------------------- # Try to link conftest.$ac_ext, and return whether this succeeded. Assumes # that executables *can* be run. ac_fn_c_try_run () { as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack if { { ac_try="$ac_link" case "(($ac_try" in *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" $as_echo "$ac_try_echo"; } >&5 (eval "$ac_link") 2>&5 ac_status=$? $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 test $ac_status = 0; } && { ac_try='./conftest$ac_exeext' { { case "(($ac_try" in *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" $as_echo "$ac_try_echo"; } >&5 (eval "$ac_try") 2>&5 ac_status=$? $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 test $ac_status = 0; }; }; then : ac_retval=0 else $as_echo "$as_me: program exited with status $ac_status" >&5 $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_retval=$ac_status fi rm -rf conftest.dSYM conftest_ipa8_conftest.oo eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno as_fn_set_status $ac_retval } # ac_fn_c_try_run # ac_fn_c_check_header_compile LINENO HEADER VAR INCLUDES # ------------------------------------------------------- # Tests whether HEADER exists and can be compiled using the include files in # INCLUDES, setting the cache variable VAR accordingly. ac_fn_c_check_header_compile () { as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $2" >&5 $as_echo_n "checking for $2... " >&6; } if eval \${$3+:} false; then : $as_echo_n "(cached) " >&6 else cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ $4 #include <$2> _ACEOF if ac_fn_c_try_compile "$LINENO"; then : eval "$3=yes" else eval "$3=no" fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext fi eval ac_res=\$$3 { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_res" >&5 $as_echo "$ac_res" >&6; } eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno } # ac_fn_c_check_header_compile # ac_fn_c_try_link LINENO # ----------------------- # Try to link conftest.$ac_ext, and return whether this succeeded. ac_fn_c_try_link () { as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack rm -f conftest.$ac_objext conftest$ac_exeext if { { ac_try="$ac_link" case "(($ac_try" in *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" $as_echo "$ac_try_echo"; } >&5 (eval "$ac_link") 2>conftest.err ac_status=$? if test -s conftest.err; then grep -v '^ *+' conftest.err >conftest.er1 cat conftest.er1 >&5 mv -f conftest.er1 conftest.err fi $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 test $ac_status = 0; } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err } && test -s conftest$ac_exeext && { test "$cross_compiling" = yes || test -x conftest$ac_exeext }; then : ac_retval=0 else $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_retval=1 fi # Delete the IPA/IPO (Inter Procedural Analysis/Optimization) information # created by the PGI compiler (conftest_ipa8_conftest.oo), as it would # interfere with the next link command; also delete a directory that is # left behind by Apple's compiler. We do this before executing the actions. rm -rf conftest.dSYM conftest_ipa8_conftest.oo eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno as_fn_set_status $ac_retval } # ac_fn_c_try_link # ac_fn_c_check_func LINENO FUNC VAR # ---------------------------------- # Tests whether FUNC exists, setting the cache variable VAR accordingly ac_fn_c_check_func () { as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $2" >&5 $as_echo_n "checking for $2... " >&6; } if eval \${$3+:} false; then : $as_echo_n "(cached) " >&6 else cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ /* Define $2 to an innocuous variant, in case declares $2. For example, HP-UX 11i declares gettimeofday. */ #define $2 innocuous_$2 /* System header to define __stub macros and hopefully few prototypes, which can conflict with char $2 (); below. Prefer to if __STDC__ is defined, since exists even on freestanding compilers. */ #ifdef __STDC__ # include #else # include #endif #undef $2 /* Override any GCC internal prototype to avoid an error. Use char because int might match the return type of a GCC builtin and then its argument prototype would still apply. */ #ifdef __cplusplus extern "C" #endif char $2 (); /* The GNU C library defines this for functions which it implements to always fail with ENOSYS. Some functions are actually named something starting with __ and the normal name is an alias. */ #if defined __stub_$2 || defined __stub___$2 choke me #endif int main () { return $2 (); ; return 0; } _ACEOF if ac_fn_c_try_link "$LINENO"; then : eval "$3=yes" else eval "$3=no" fi rm -f core conftest.err conftest.$ac_objext \ conftest$ac_exeext conftest.$ac_ext fi eval ac_res=\$$3 { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_res" >&5 $as_echo "$ac_res" >&6; } eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno } # ac_fn_c_check_func # ac_fn_c_check_type LINENO TYPE VAR INCLUDES # ------------------------------------------- # Tests whether TYPE exists after having included INCLUDES, setting cache # variable VAR accordingly. ac_fn_c_check_type () { as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $2" >&5 $as_echo_n "checking for $2... " >&6; } if eval \${$3+:} false; then : $as_echo_n "(cached) " >&6 else eval "$3=no" cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ $4 int main () { if (sizeof ($2)) return 0; ; return 0; } _ACEOF if ac_fn_c_try_compile "$LINENO"; then : cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ $4 int main () { if (sizeof (($2))) return 0; ; return 0; } _ACEOF if ac_fn_c_try_compile "$LINENO"; then : else eval "$3=yes" fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext fi eval ac_res=\$$3 { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_res" >&5 $as_echo "$ac_res" >&6; } eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno } # ac_fn_c_check_type # ac_fn_c_check_member LINENO AGGR MEMBER VAR INCLUDES # ---------------------------------------------------- # Tries to find if the field MEMBER exists in type AGGR, after including # INCLUDES, setting cache variable VAR accordingly. ac_fn_c_check_member () { as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $2.$3" >&5 $as_echo_n "checking for $2.$3... " >&6; } if eval \${$4+:} false; then : $as_echo_n "(cached) " >&6 else cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ $5 int main () { static $2 ac_aggr; if (ac_aggr.$3) return 0; ; return 0; } _ACEOF if ac_fn_c_try_compile "$LINENO"; then : eval "$4=yes" else cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ $5 int main () { static $2 ac_aggr; if (sizeof ac_aggr.$3) return 0; ; return 0; } _ACEOF if ac_fn_c_try_compile "$LINENO"; then : eval "$4=yes" else eval "$4=no" fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext fi eval ac_res=\$$4 { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_res" >&5 $as_echo "$ac_res" >&6; } eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno } # ac_fn_c_check_member cat >config.log <<_ACEOF This file contains any messages produced by compilers while running configure, to aid debugging if configure makes a mistake. It was created by libedit $as_me 3.1, which was generated by GNU Autoconf 2.69. Invocation command line was $ $0 $@ _ACEOF exec 5>>config.log { cat <<_ASUNAME ## --------- ## ## Platform. ## ## --------- ## hostname = `(hostname || uname -n) 2>/dev/null | sed 1q` uname -m = `(uname -m) 2>/dev/null || echo unknown` uname -r = `(uname -r) 2>/dev/null || echo unknown` uname -s = `(uname -s) 2>/dev/null || echo unknown` uname -v = `(uname -v) 2>/dev/null || echo unknown` /usr/bin/uname -p = `(/usr/bin/uname -p) 2>/dev/null || echo unknown` /bin/uname -X = `(/bin/uname -X) 2>/dev/null || echo unknown` /bin/arch = `(/bin/arch) 2>/dev/null || echo unknown` /usr/bin/arch -k = `(/usr/bin/arch -k) 2>/dev/null || echo unknown` /usr/convex/getsysinfo = `(/usr/convex/getsysinfo) 2>/dev/null || echo unknown` /usr/bin/hostinfo = `(/usr/bin/hostinfo) 2>/dev/null || echo unknown` /bin/machine = `(/bin/machine) 2>/dev/null || echo unknown` /usr/bin/oslevel = `(/usr/bin/oslevel) 2>/dev/null || echo unknown` /bin/universe = `(/bin/universe) 2>/dev/null || echo unknown` _ASUNAME as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. $as_echo "PATH: $as_dir" done IFS=$as_save_IFS } >&5 cat >&5 <<_ACEOF ## ----------- ## ## Core tests. ## ## ----------- ## _ACEOF # Keep a trace of the command line. # Strip out --no-create and --no-recursion so they do not pile up. # Strip out --silent because we don't want to record it for future runs. # Also quote any args containing shell meta-characters. # Make two passes to allow for proper duplicate-argument suppression. ac_configure_args= ac_configure_args0= ac_configure_args1= ac_must_keep_next=false for ac_pass in 1 2 do for ac_arg do case $ac_arg in -no-create | --no-c* | -n | -no-recursion | --no-r*) continue ;; -q | -quiet | --quiet | --quie | --qui | --qu | --q \ | -silent | --silent | --silen | --sile | --sil) continue ;; *\'*) ac_arg=`$as_echo "$ac_arg" | sed "s/'/'\\\\\\\\''/g"` ;; esac case $ac_pass in 1) as_fn_append ac_configure_args0 " '$ac_arg'" ;; 2) as_fn_append ac_configure_args1 " '$ac_arg'" if test $ac_must_keep_next = true; then ac_must_keep_next=false # Got value, back to normal. else case $ac_arg in *=* | --config-cache | -C | -disable-* | --disable-* \ | -enable-* | --enable-* | -gas | --g* | -nfp | --nf* \ | -q | -quiet | --q* | -silent | --sil* | -v | -verb* \ | -with-* | --with-* | -without-* | --without-* | --x) case "$ac_configure_args0 " in "$ac_configure_args1"*" '$ac_arg' "* ) continue ;; esac ;; -* ) ac_must_keep_next=true ;; esac fi as_fn_append ac_configure_args " '$ac_arg'" ;; esac done done { ac_configure_args0=; unset ac_configure_args0;} { ac_configure_args1=; unset ac_configure_args1;} # When interrupted or exit'd, cleanup temporary files, and complete # config.log. We remove comments because anyway the quotes in there # would cause problems or look ugly. # WARNING: Use '\'' to represent an apostrophe within the trap. # WARNING: Do not start the trap code with a newline, due to a FreeBSD 4.0 bug. trap 'exit_status=$? # Save into config.log some information that might help in debugging. { echo $as_echo "## ---------------- ## ## Cache variables. ## ## ---------------- ##" echo # The following way of writing the cache mishandles newlines in values, ( for ac_var in `(set) 2>&1 | sed -n '\''s/^\([a-zA-Z_][a-zA-Z0-9_]*\)=.*/\1/p'\''`; do eval ac_val=\$$ac_var case $ac_val in #( *${as_nl}*) case $ac_var in #( *_cv_*) { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: cache variable $ac_var contains a newline" >&5 $as_echo "$as_me: WARNING: cache variable $ac_var contains a newline" >&2;} ;; esac case $ac_var in #( _ | IFS | as_nl) ;; #( BASH_ARGV | BASH_SOURCE) eval $ac_var= ;; #( *) { eval $ac_var=; unset $ac_var;} ;; esac ;; esac done (set) 2>&1 | case $as_nl`(ac_space='\'' '\''; set) 2>&1` in #( *${as_nl}ac_space=\ *) sed -n \ "s/'\''/'\''\\\\'\'''\''/g; s/^\\([_$as_cr_alnum]*_cv_[_$as_cr_alnum]*\\)=\\(.*\\)/\\1='\''\\2'\''/p" ;; #( *) sed -n "/^[_$as_cr_alnum]*_cv_[_$as_cr_alnum]*=/p" ;; esac | sort ) echo $as_echo "## ----------------- ## ## Output variables. ## ## ----------------- ##" echo for ac_var in $ac_subst_vars do eval ac_val=\$$ac_var case $ac_val in *\'\''*) ac_val=`$as_echo "$ac_val" | sed "s/'\''/'\''\\\\\\\\'\'''\''/g"`;; esac $as_echo "$ac_var='\''$ac_val'\''" done | sort echo if test -n "$ac_subst_files"; then $as_echo "## ------------------- ## ## File substitutions. ## ## ------------------- ##" echo for ac_var in $ac_subst_files do eval ac_val=\$$ac_var case $ac_val in *\'\''*) ac_val=`$as_echo "$ac_val" | sed "s/'\''/'\''\\\\\\\\'\'''\''/g"`;; esac $as_echo "$ac_var='\''$ac_val'\''" done | sort echo fi if test -s confdefs.h; then $as_echo "## ----------- ## ## confdefs.h. ## ## ----------- ##" echo cat confdefs.h echo fi test "$ac_signal" != 0 && $as_echo "$as_me: caught signal $ac_signal" $as_echo "$as_me: exit $exit_status" } >&5 rm -f core *.core core.conftest.* && rm -f -r conftest* confdefs* conf$$* $ac_clean_files && exit $exit_status ' 0 for ac_signal in 1 2 13 15; do trap 'ac_signal='$ac_signal'; as_fn_exit 1' $ac_signal done ac_signal=0 # confdefs.h avoids OS command line length limits that DEFS can exceed. rm -f -r conftest* confdefs.h $as_echo "/* confdefs.h */" > confdefs.h # Predefined preprocessor variables. cat >>confdefs.h <<_ACEOF #define PACKAGE_NAME "$PACKAGE_NAME" _ACEOF cat >>confdefs.h <<_ACEOF #define PACKAGE_TARNAME "$PACKAGE_TARNAME" _ACEOF cat >>confdefs.h <<_ACEOF #define PACKAGE_VERSION "$PACKAGE_VERSION" _ACEOF cat >>confdefs.h <<_ACEOF #define PACKAGE_STRING "$PACKAGE_STRING" _ACEOF cat >>confdefs.h <<_ACEOF #define PACKAGE_BUGREPORT "$PACKAGE_BUGREPORT" _ACEOF cat >>confdefs.h <<_ACEOF #define PACKAGE_URL "$PACKAGE_URL" _ACEOF # Let the site file select an alternate cache file if it wants to. # Prefer an explicitly selected file to automatically selected ones. ac_site_file1=NONE ac_site_file2=NONE if test -n "$CONFIG_SITE"; then # We do not want a PATH search for config.site. case $CONFIG_SITE in #(( -*) ac_site_file1=./$CONFIG_SITE;; */*) ac_site_file1=$CONFIG_SITE;; *) ac_site_file1=./$CONFIG_SITE;; esac elif test "x$prefix" != xNONE; then ac_site_file1=$prefix/share/config.site ac_site_file2=$prefix/etc/config.site else ac_site_file1=$ac_default_prefix/share/config.site ac_site_file2=$ac_default_prefix/etc/config.site fi for ac_site_file in "$ac_site_file1" "$ac_site_file2" do test "x$ac_site_file" = xNONE && continue if test /dev/null != "$ac_site_file" && test -r "$ac_site_file"; then { $as_echo "$as_me:${as_lineno-$LINENO}: loading site script $ac_site_file" >&5 $as_echo "$as_me: loading site script $ac_site_file" >&6;} sed 's/^/| /' "$ac_site_file" >&5 . "$ac_site_file" \ || { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 $as_echo "$as_me: error: in \`$ac_pwd':" >&2;} as_fn_error $? "failed to load site script $ac_site_file See \`config.log' for more details" "$LINENO" 5; } fi done if test -r "$cache_file"; then # Some versions of bash will fail to source /dev/null (special files # actually), so we avoid doing that. DJGPP emulates it as a regular file. if test /dev/null != "$cache_file" && test -f "$cache_file"; then { $as_echo "$as_me:${as_lineno-$LINENO}: loading cache $cache_file" >&5 $as_echo "$as_me: loading cache $cache_file" >&6;} case $cache_file in [\\/]* | ?:[\\/]* ) . "$cache_file";; *) . "./$cache_file";; esac fi else { $as_echo "$as_me:${as_lineno-$LINENO}: creating cache $cache_file" >&5 $as_echo "$as_me: creating cache $cache_file" >&6;} >$cache_file fi # Check that the precious variables saved in the cache have kept the same # value. ac_cache_corrupted=false for ac_var in $ac_precious_vars; do eval ac_old_set=\$ac_cv_env_${ac_var}_set eval ac_new_set=\$ac_env_${ac_var}_set eval ac_old_val=\$ac_cv_env_${ac_var}_value eval ac_new_val=\$ac_env_${ac_var}_value case $ac_old_set,$ac_new_set in set,) { $as_echo "$as_me:${as_lineno-$LINENO}: error: \`$ac_var' was set to \`$ac_old_val' in the previous run" >&5 $as_echo "$as_me: error: \`$ac_var' was set to \`$ac_old_val' in the previous run" >&2;} ac_cache_corrupted=: ;; ,set) { $as_echo "$as_me:${as_lineno-$LINENO}: error: \`$ac_var' was not set in the previous run" >&5 $as_echo "$as_me: error: \`$ac_var' was not set in the previous run" >&2;} ac_cache_corrupted=: ;; ,);; *) if test "x$ac_old_val" != "x$ac_new_val"; then # differences in whitespace do not lead to failure. ac_old_val_w=`echo x $ac_old_val` ac_new_val_w=`echo x $ac_new_val` if test "$ac_old_val_w" != "$ac_new_val_w"; then { $as_echo "$as_me:${as_lineno-$LINENO}: error: \`$ac_var' has changed since the previous run:" >&5 $as_echo "$as_me: error: \`$ac_var' has changed since the previous run:" >&2;} ac_cache_corrupted=: else { $as_echo "$as_me:${as_lineno-$LINENO}: warning: ignoring whitespace changes in \`$ac_var' since the previous run:" >&5 $as_echo "$as_me: warning: ignoring whitespace changes in \`$ac_var' since the previous run:" >&2;} eval $ac_var=\$ac_old_val fi { $as_echo "$as_me:${as_lineno-$LINENO}: former value: \`$ac_old_val'" >&5 $as_echo "$as_me: former value: \`$ac_old_val'" >&2;} { $as_echo "$as_me:${as_lineno-$LINENO}: current value: \`$ac_new_val'" >&5 $as_echo "$as_me: current value: \`$ac_new_val'" >&2;} fi;; esac # Pass precious variables to config.status. if test "$ac_new_set" = set; then case $ac_new_val in *\'*) ac_arg=$ac_var=`$as_echo "$ac_new_val" | sed "s/'/'\\\\\\\\''/g"` ;; *) ac_arg=$ac_var=$ac_new_val ;; esac case " $ac_configure_args " in *" '$ac_arg' "*) ;; # Avoid dups. Use of quotes ensures accuracy. *) as_fn_append ac_configure_args " '$ac_arg'" ;; esac fi done if $ac_cache_corrupted; then { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 $as_echo "$as_me: error: in \`$ac_pwd':" >&2;} { $as_echo "$as_me:${as_lineno-$LINENO}: error: changes in the environment can compromise the build" >&5 $as_echo "$as_me: error: changes in the environment can compromise the build" >&2;} as_fn_error $? "run \`make distclean' and/or \`rm $cache_file' and start over" "$LINENO" 5 fi ## -------------------- ## ## Main body of script. ## ## -------------------- ## ac_ext=c ac_cpp='$CPP $CPPFLAGS' ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' ac_compiler_gnu=$ac_cv_c_compiler_gnu ac_config_headers="$ac_config_headers config.h" # features of Posix that are extensions to C (define _GNU_SOURCE) ac_aux_dir= for ac_dir in "$srcdir" "$srcdir/.." "$srcdir/../.."; do if test -f "$ac_dir/install-sh"; then ac_aux_dir=$ac_dir ac_install_sh="$ac_aux_dir/install-sh -c" break elif test -f "$ac_dir/install.sh"; then ac_aux_dir=$ac_dir ac_install_sh="$ac_aux_dir/install.sh -c" break elif test -f "$ac_dir/shtool"; then ac_aux_dir=$ac_dir ac_install_sh="$ac_aux_dir/shtool install -c" break fi done if test -z "$ac_aux_dir"; then as_fn_error $? "cannot find install-sh, install.sh, or shtool in \"$srcdir\" \"$srcdir/..\" \"$srcdir/../..\"" "$LINENO" 5 fi # These three variables are undocumented and unsupported, # and are intended to be withdrawn in a future Autoconf release. # They can cause serious problems if a builder's source tree is in a directory # whose full name contains unusual characters. ac_config_guess="$SHELL $ac_aux_dir/config.guess" # Please don't use this var. ac_config_sub="$SHELL $ac_aux_dir/config.sub" # Please don't use this var. ac_configure="$SHELL $ac_aux_dir/configure" # Please don't use this var. # Expand $ac_aux_dir to an absolute path. am_aux_dir=`cd "$ac_aux_dir" && pwd` ac_ext=c ac_cpp='$CPP $CPPFLAGS' ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' ac_compiler_gnu=$ac_cv_c_compiler_gnu if test -n "$ac_tool_prefix"; then # Extract the first word of "${ac_tool_prefix}gcc", so it can be a program name with args. set dummy ${ac_tool_prefix}gcc; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if ${ac_cv_prog_CC+:} false; then : $as_echo_n "(cached) " >&6 else if test -n "$CC"; then ac_cv_prog_CC="$CC" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then ac_cv_prog_CC="${ac_tool_prefix}gcc" $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi fi CC=$ac_cv_prog_CC if test -n "$CC"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $CC" >&5 $as_echo "$CC" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi fi if test -z "$ac_cv_prog_CC"; then ac_ct_CC=$CC # Extract the first word of "gcc", so it can be a program name with args. set dummy gcc; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if ${ac_cv_prog_ac_ct_CC+:} false; then : $as_echo_n "(cached) " >&6 else if test -n "$ac_ct_CC"; then ac_cv_prog_ac_ct_CC="$ac_ct_CC" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then ac_cv_prog_ac_ct_CC="gcc" $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi fi ac_ct_CC=$ac_cv_prog_ac_ct_CC if test -n "$ac_ct_CC"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_ct_CC" >&5 $as_echo "$ac_ct_CC" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi if test "x$ac_ct_CC" = x; then CC="" else case $cross_compiling:$ac_tool_warned in yes:) { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5 $as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} ac_tool_warned=yes ;; esac CC=$ac_ct_CC fi else CC="$ac_cv_prog_CC" fi if test -z "$CC"; then if test -n "$ac_tool_prefix"; then # Extract the first word of "${ac_tool_prefix}cc", so it can be a program name with args. set dummy ${ac_tool_prefix}cc; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if ${ac_cv_prog_CC+:} false; then : $as_echo_n "(cached) " >&6 else if test -n "$CC"; then ac_cv_prog_CC="$CC" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then ac_cv_prog_CC="${ac_tool_prefix}cc" $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi fi CC=$ac_cv_prog_CC if test -n "$CC"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $CC" >&5 $as_echo "$CC" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi fi fi if test -z "$CC"; then # Extract the first word of "cc", so it can be a program name with args. set dummy cc; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if ${ac_cv_prog_CC+:} false; then : $as_echo_n "(cached) " >&6 else if test -n "$CC"; then ac_cv_prog_CC="$CC" # Let the user override the test. else ac_prog_rejected=no as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then if test "$as_dir/$ac_word$ac_exec_ext" = "/usr/ucb/cc"; then ac_prog_rejected=yes continue fi ac_cv_prog_CC="cc" $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS if test $ac_prog_rejected = yes; then # We found a bogon in the path, so make sure we never use it. set dummy $ac_cv_prog_CC shift if test $# != 0; then # We chose a different compiler from the bogus one. # However, it has the same basename, so the bogon will be chosen # first if we set CC to just the basename; use the full file name. shift ac_cv_prog_CC="$as_dir/$ac_word${1+' '}$@" fi fi fi fi CC=$ac_cv_prog_CC if test -n "$CC"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $CC" >&5 $as_echo "$CC" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi fi if test -z "$CC"; then if test -n "$ac_tool_prefix"; then for ac_prog in cl.exe do # Extract the first word of "$ac_tool_prefix$ac_prog", so it can be a program name with args. set dummy $ac_tool_prefix$ac_prog; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if ${ac_cv_prog_CC+:} false; then : $as_echo_n "(cached) " >&6 else if test -n "$CC"; then ac_cv_prog_CC="$CC" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then ac_cv_prog_CC="$ac_tool_prefix$ac_prog" $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi fi CC=$ac_cv_prog_CC if test -n "$CC"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $CC" >&5 $as_echo "$CC" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi test -n "$CC" && break done fi if test -z "$CC"; then ac_ct_CC=$CC for ac_prog in cl.exe do # Extract the first word of "$ac_prog", so it can be a program name with args. set dummy $ac_prog; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if ${ac_cv_prog_ac_ct_CC+:} false; then : $as_echo_n "(cached) " >&6 else if test -n "$ac_ct_CC"; then ac_cv_prog_ac_ct_CC="$ac_ct_CC" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then ac_cv_prog_ac_ct_CC="$ac_prog" $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi fi ac_ct_CC=$ac_cv_prog_ac_ct_CC if test -n "$ac_ct_CC"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_ct_CC" >&5 $as_echo "$ac_ct_CC" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi test -n "$ac_ct_CC" && break done if test "x$ac_ct_CC" = x; then CC="" else case $cross_compiling:$ac_tool_warned in yes:) { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5 $as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} ac_tool_warned=yes ;; esac CC=$ac_ct_CC fi fi fi test -z "$CC" && { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 $as_echo "$as_me: error: in \`$ac_pwd':" >&2;} as_fn_error $? "no acceptable C compiler found in \$PATH See \`config.log' for more details" "$LINENO" 5; } # Provide some information about the compiler. $as_echo "$as_me:${as_lineno-$LINENO}: checking for C compiler version" >&5 set X $ac_compile ac_compiler=$2 for ac_option in --version -v -V -qversion; do { { ac_try="$ac_compiler $ac_option >&5" case "(($ac_try" in *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" $as_echo "$ac_try_echo"; } >&5 (eval "$ac_compiler $ac_option >&5") 2>conftest.err ac_status=$? if test -s conftest.err; then sed '10a\ ... rest of stderr output deleted ... 10q' conftest.err >conftest.er1 cat conftest.er1 >&5 fi rm -f conftest.er1 conftest.err $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 test $ac_status = 0; } done cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ int main () { ; return 0; } _ACEOF ac_clean_files_save=$ac_clean_files ac_clean_files="$ac_clean_files a.out a.out.dSYM a.exe b.out" # Try to create an executable without -o first, disregard a.out. # It will help us diagnose broken compilers, and finding out an intuition # of exeext. { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether the C compiler works" >&5 $as_echo_n "checking whether the C compiler works... " >&6; } ac_link_default=`$as_echo "$ac_link" | sed 's/ -o *conftest[^ ]*//'` # The possible output files: ac_files="a.out conftest.exe conftest a.exe a_out.exe b.out conftest.*" ac_rmfiles= for ac_file in $ac_files do case $ac_file in *.$ac_ext | *.xcoff | *.tds | *.d | *.pdb | *.xSYM | *.bb | *.bbg | *.map | *.inf | *.dSYM | *.o | *.obj ) ;; * ) ac_rmfiles="$ac_rmfiles $ac_file";; esac done rm -f $ac_rmfiles if { { ac_try="$ac_link_default" case "(($ac_try" in *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" $as_echo "$ac_try_echo"; } >&5 (eval "$ac_link_default") 2>&5 ac_status=$? $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 test $ac_status = 0; }; then : # Autoconf-2.13 could set the ac_cv_exeext variable to `no'. # So ignore a value of `no', otherwise this would lead to `EXEEXT = no' # in a Makefile. We should not override ac_cv_exeext if it was cached, # so that the user can short-circuit this test for compilers unknown to # Autoconf. for ac_file in $ac_files '' do test -f "$ac_file" || continue case $ac_file in *.$ac_ext | *.xcoff | *.tds | *.d | *.pdb | *.xSYM | *.bb | *.bbg | *.map | *.inf | *.dSYM | *.o | *.obj ) ;; [ab].out ) # We found the default executable, but exeext='' is most # certainly right. break;; *.* ) if test "${ac_cv_exeext+set}" = set && test "$ac_cv_exeext" != no; then :; else ac_cv_exeext=`expr "$ac_file" : '[^.]*\(\..*\)'` fi # We set ac_cv_exeext here because the later test for it is not # safe: cross compilers may not add the suffix if given an `-o' # argument, so we may need to know it at that point already. # Even if this section looks crufty: it has the advantage of # actually working. break;; * ) break;; esac done test "$ac_cv_exeext" = no && ac_cv_exeext= else ac_file='' fi if test -z "$ac_file"; then : { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 $as_echo "$as_me: error: in \`$ac_pwd':" >&2;} as_fn_error 77 "C compiler cannot create executables See \`config.log' for more details" "$LINENO" 5; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 $as_echo "yes" >&6; } fi { $as_echo "$as_me:${as_lineno-$LINENO}: checking for C compiler default output file name" >&5 $as_echo_n "checking for C compiler default output file name... " >&6; } { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_file" >&5 $as_echo "$ac_file" >&6; } ac_exeext=$ac_cv_exeext rm -f -r a.out a.out.dSYM a.exe conftest$ac_cv_exeext b.out ac_clean_files=$ac_clean_files_save { $as_echo "$as_me:${as_lineno-$LINENO}: checking for suffix of executables" >&5 $as_echo_n "checking for suffix of executables... " >&6; } if { { ac_try="$ac_link" case "(($ac_try" in *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" $as_echo "$ac_try_echo"; } >&5 (eval "$ac_link") 2>&5 ac_status=$? $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 test $ac_status = 0; }; then : # If both `conftest.exe' and `conftest' are `present' (well, observable) # catch `conftest.exe'. For instance with Cygwin, `ls conftest' will # work properly (i.e., refer to `conftest.exe'), while it won't with # `rm'. for ac_file in conftest.exe conftest conftest.*; do test -f "$ac_file" || continue case $ac_file in *.$ac_ext | *.xcoff | *.tds | *.d | *.pdb | *.xSYM | *.bb | *.bbg | *.map | *.inf | *.dSYM | *.o | *.obj ) ;; *.* ) ac_cv_exeext=`expr "$ac_file" : '[^.]*\(\..*\)'` break;; * ) break;; esac done else { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 $as_echo "$as_me: error: in \`$ac_pwd':" >&2;} as_fn_error $? "cannot compute suffix of executables: cannot compile and link See \`config.log' for more details" "$LINENO" 5; } fi rm -f conftest conftest$ac_cv_exeext { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_exeext" >&5 $as_echo "$ac_cv_exeext" >&6; } rm -f conftest.$ac_ext EXEEXT=$ac_cv_exeext ac_exeext=$EXEEXT cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #include int main () { FILE *f = fopen ("conftest.out", "w"); return ferror (f) || fclose (f) != 0; ; return 0; } _ACEOF ac_clean_files="$ac_clean_files conftest.out" # Check that the compiler produces executables we can run. If not, either # the compiler is broken, or we cross compile. { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether we are cross compiling" >&5 $as_echo_n "checking whether we are cross compiling... " >&6; } if test "$cross_compiling" != yes; then { { ac_try="$ac_link" case "(($ac_try" in *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" $as_echo "$ac_try_echo"; } >&5 (eval "$ac_link") 2>&5 ac_status=$? $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 test $ac_status = 0; } if { ac_try='./conftest$ac_cv_exeext' { { case "(($ac_try" in *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" $as_echo "$ac_try_echo"; } >&5 (eval "$ac_try") 2>&5 ac_status=$? $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 test $ac_status = 0; }; }; then cross_compiling=no else if test "$cross_compiling" = maybe; then cross_compiling=yes else { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 $as_echo "$as_me: error: in \`$ac_pwd':" >&2;} as_fn_error $? "cannot run C compiled programs. If you meant to cross compile, use \`--host'. See \`config.log' for more details" "$LINENO" 5; } fi fi fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $cross_compiling" >&5 $as_echo "$cross_compiling" >&6; } rm -f conftest.$ac_ext conftest$ac_cv_exeext conftest.out ac_clean_files=$ac_clean_files_save { $as_echo "$as_me:${as_lineno-$LINENO}: checking for suffix of object files" >&5 $as_echo_n "checking for suffix of object files... " >&6; } if ${ac_cv_objext+:} false; then : $as_echo_n "(cached) " >&6 else cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ int main () { ; return 0; } _ACEOF rm -f conftest.o conftest.obj if { { ac_try="$ac_compile" case "(($ac_try" in *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" $as_echo "$ac_try_echo"; } >&5 (eval "$ac_compile") 2>&5 ac_status=$? $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 test $ac_status = 0; }; then : for ac_file in conftest.o conftest.obj conftest.*; do test -f "$ac_file" || continue; case $ac_file in *.$ac_ext | *.xcoff | *.tds | *.d | *.pdb | *.xSYM | *.bb | *.bbg | *.map | *.inf | *.dSYM ) ;; *) ac_cv_objext=`expr "$ac_file" : '.*\.\(.*\)'` break;; esac done else $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 $as_echo "$as_me: error: in \`$ac_pwd':" >&2;} as_fn_error $? "cannot compute suffix of object files: cannot compile See \`config.log' for more details" "$LINENO" 5; } fi rm -f conftest.$ac_cv_objext conftest.$ac_ext fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_objext" >&5 $as_echo "$ac_cv_objext" >&6; } OBJEXT=$ac_cv_objext ac_objext=$OBJEXT { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether we are using the GNU C compiler" >&5 $as_echo_n "checking whether we are using the GNU C compiler... " >&6; } if ${ac_cv_c_compiler_gnu+:} false; then : $as_echo_n "(cached) " >&6 else cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ int main () { #ifndef __GNUC__ choke me #endif ; return 0; } _ACEOF if ac_fn_c_try_compile "$LINENO"; then : ac_compiler_gnu=yes else ac_compiler_gnu=no fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext ac_cv_c_compiler_gnu=$ac_compiler_gnu fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_c_compiler_gnu" >&5 $as_echo "$ac_cv_c_compiler_gnu" >&6; } if test $ac_compiler_gnu = yes; then GCC=yes else GCC= fi ac_test_CFLAGS=${CFLAGS+set} ac_save_CFLAGS=$CFLAGS { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether $CC accepts -g" >&5 $as_echo_n "checking whether $CC accepts -g... " >&6; } if ${ac_cv_prog_cc_g+:} false; then : $as_echo_n "(cached) " >&6 else ac_save_c_werror_flag=$ac_c_werror_flag ac_c_werror_flag=yes ac_cv_prog_cc_g=no CFLAGS="-g" cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ int main () { ; return 0; } _ACEOF if ac_fn_c_try_compile "$LINENO"; then : ac_cv_prog_cc_g=yes else CFLAGS="" cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ int main () { ; return 0; } _ACEOF if ac_fn_c_try_compile "$LINENO"; then : else ac_c_werror_flag=$ac_save_c_werror_flag CFLAGS="-g" cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ int main () { ; return 0; } _ACEOF if ac_fn_c_try_compile "$LINENO"; then : ac_cv_prog_cc_g=yes fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext ac_c_werror_flag=$ac_save_c_werror_flag fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_prog_cc_g" >&5 $as_echo "$ac_cv_prog_cc_g" >&6; } if test "$ac_test_CFLAGS" = set; then CFLAGS=$ac_save_CFLAGS elif test $ac_cv_prog_cc_g = yes; then if test "$GCC" = yes; then CFLAGS="-g -O2" else CFLAGS="-g" fi else if test "$GCC" = yes; then CFLAGS="-O2" else CFLAGS= fi fi { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $CC option to accept ISO C89" >&5 $as_echo_n "checking for $CC option to accept ISO C89... " >&6; } if ${ac_cv_prog_cc_c89+:} false; then : $as_echo_n "(cached) " >&6 else ac_cv_prog_cc_c89=no ac_save_CC=$CC cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #include #include struct stat; /* Most of the following tests are stolen from RCS 5.7's src/conf.sh. */ struct buf { int x; }; FILE * (*rcsopen) (struct buf *, struct stat *, int); static char *e (p, i) char **p; int i; { return p[i]; } static char *f (char * (*g) (char **, int), char **p, ...) { char *s; va_list v; va_start (v,p); s = g (p, va_arg (v,int)); va_end (v); return s; } /* OSF 4.0 Compaq cc is some sort of almost-ANSI by default. It has function prototypes and stuff, but not '\xHH' hex character constants. These don't provoke an error unfortunately, instead are silently treated as 'x'. The following induces an error, until -std is added to get proper ANSI mode. Curiously '\x00'!='x' always comes out true, for an array size at least. It's necessary to write '\x00'==0 to get something that's true only with -std. */ int osf4_cc_array ['\x00' == 0 ? 1 : -1]; /* IBM C 6 for AIX is almost-ANSI by default, but it replaces macro parameters inside strings and character constants. */ #define FOO(x) 'x' int xlc6_cc_array[FOO(a) == 'x' ? 1 : -1]; int test (int i, double x); struct s1 {int (*f) (int a);}; struct s2 {int (*f) (double a);}; int pairnames (int, char **, FILE *(*)(struct buf *, struct stat *, int), int, int); int argc; char **argv; int main () { return f (e, argv, 0) != argv[0] || f (e, argv, 1) != argv[1]; ; return 0; } _ACEOF for ac_arg in '' -qlanglvl=extc89 -qlanglvl=ansi -std \ -Ae "-Aa -D_HPUX_SOURCE" "-Xc -D__EXTENSIONS__" do CC="$ac_save_CC $ac_arg" if ac_fn_c_try_compile "$LINENO"; then : ac_cv_prog_cc_c89=$ac_arg fi rm -f core conftest.err conftest.$ac_objext test "x$ac_cv_prog_cc_c89" != "xno" && break done rm -f conftest.$ac_ext CC=$ac_save_CC fi # AC_CACHE_VAL case "x$ac_cv_prog_cc_c89" in x) { $as_echo "$as_me:${as_lineno-$LINENO}: result: none needed" >&5 $as_echo "none needed" >&6; } ;; xno) { $as_echo "$as_me:${as_lineno-$LINENO}: result: unsupported" >&5 $as_echo "unsupported" >&6; } ;; *) CC="$CC $ac_cv_prog_cc_c89" { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_prog_cc_c89" >&5 $as_echo "$ac_cv_prog_cc_c89" >&6; } ;; esac if test "x$ac_cv_prog_cc_c89" != xno; then : fi ac_ext=c ac_cpp='$CPP $CPPFLAGS' ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' ac_compiler_gnu=$ac_cv_c_compiler_gnu ac_ext=c ac_cpp='$CPP $CPPFLAGS' ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' ac_compiler_gnu=$ac_cv_c_compiler_gnu { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether $CC understands -c and -o together" >&5 $as_echo_n "checking whether $CC understands -c and -o together... " >&6; } if ${am_cv_prog_cc_c_o+:} false; then : $as_echo_n "(cached) " >&6 else cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ int main () { ; return 0; } _ACEOF # Make sure it works both with $CC and with simple cc. # Following AC_PROG_CC_C_O, we do the test twice because some # compilers refuse to overwrite an existing .o file with -o, # though they will create one. am_cv_prog_cc_c_o=yes for am_i in 1 2; do if { echo "$as_me:$LINENO: $CC -c conftest.$ac_ext -o conftest2.$ac_objext" >&5 ($CC -c conftest.$ac_ext -o conftest2.$ac_objext) >&5 2>&5 ac_status=$? echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } \ && test -f conftest2.$ac_objext; then : OK else am_cv_prog_cc_c_o=no break fi done rm -f core conftest* unset am_i fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $am_cv_prog_cc_c_o" >&5 $as_echo "$am_cv_prog_cc_c_o" >&6; } if test "$am_cv_prog_cc_c_o" != yes; then # Losing compiler, so override with the script. # FIXME: It is wrong to rewrite CC. # But if we don't then we get into trouble of one sort or another. # A longer-term fix would be to have automake use am__CC in this case, # and then we could set am__CC="\$(top_srcdir)/compile \$(CC)" CC="$am_aux_dir/compile $CC" fi ac_ext=c ac_cpp='$CPP $CPPFLAGS' ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' ac_compiler_gnu=$ac_cv_c_compiler_gnu ac_ext=c ac_cpp='$CPP $CPPFLAGS' ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' ac_compiler_gnu=$ac_cv_c_compiler_gnu { $as_echo "$as_me:${as_lineno-$LINENO}: checking how to run the C preprocessor" >&5 $as_echo_n "checking how to run the C preprocessor... " >&6; } # On Suns, sometimes $CPP names a directory. if test -n "$CPP" && test -d "$CPP"; then CPP= fi if test -z "$CPP"; then if ${ac_cv_prog_CPP+:} false; then : $as_echo_n "(cached) " >&6 else # Double quotes because CPP needs to be expanded for CPP in "$CC -E" "$CC -E -traditional-cpp" "/lib/cpp" do ac_preproc_ok=false for ac_c_preproc_warn_flag in '' yes do # Use a header file that comes with gcc, so configuring glibc # with a fresh cross-compiler works. # Prefer to if __STDC__ is defined, since # exists even on freestanding compilers. # On the NeXT, cc -E runs the code through the compiler's parser, # not just through cpp. "Syntax error" is here to catch this case. cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #ifdef __STDC__ # include #else # include #endif Syntax error _ACEOF if ac_fn_c_try_cpp "$LINENO"; then : else # Broken: fails on valid input. continue fi rm -f conftest.err conftest.i conftest.$ac_ext # OK, works on sane cases. Now check whether nonexistent headers # can be detected and how. cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #include _ACEOF if ac_fn_c_try_cpp "$LINENO"; then : # Broken: success on invalid input. continue else # Passes both tests. ac_preproc_ok=: break fi rm -f conftest.err conftest.i conftest.$ac_ext done # Because of `break', _AC_PREPROC_IFELSE's cleaning code was skipped. rm -f conftest.i conftest.err conftest.$ac_ext if $ac_preproc_ok; then : break fi done ac_cv_prog_CPP=$CPP fi CPP=$ac_cv_prog_CPP else ac_cv_prog_CPP=$CPP fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $CPP" >&5 $as_echo "$CPP" >&6; } ac_preproc_ok=false for ac_c_preproc_warn_flag in '' yes do # Use a header file that comes with gcc, so configuring glibc # with a fresh cross-compiler works. # Prefer to if __STDC__ is defined, since # exists even on freestanding compilers. # On the NeXT, cc -E runs the code through the compiler's parser, # not just through cpp. "Syntax error" is here to catch this case. cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #ifdef __STDC__ # include #else # include #endif Syntax error _ACEOF if ac_fn_c_try_cpp "$LINENO"; then : else # Broken: fails on valid input. continue fi rm -f conftest.err conftest.i conftest.$ac_ext # OK, works on sane cases. Now check whether nonexistent headers # can be detected and how. cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #include _ACEOF if ac_fn_c_try_cpp "$LINENO"; then : # Broken: success on invalid input. continue else # Passes both tests. ac_preproc_ok=: break fi rm -f conftest.err conftest.i conftest.$ac_ext done # Because of `break', _AC_PREPROC_IFELSE's cleaning code was skipped. rm -f conftest.i conftest.err conftest.$ac_ext if $ac_preproc_ok; then : else { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 $as_echo "$as_me: error: in \`$ac_pwd':" >&2;} as_fn_error $? "C preprocessor \"$CPP\" fails sanity check See \`config.log' for more details" "$LINENO" 5; } fi ac_ext=c ac_cpp='$CPP $CPPFLAGS' ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' ac_compiler_gnu=$ac_cv_c_compiler_gnu { $as_echo "$as_me:${as_lineno-$LINENO}: checking for grep that handles long lines and -e" >&5 $as_echo_n "checking for grep that handles long lines and -e... " >&6; } if ${ac_cv_path_GREP+:} false; then : $as_echo_n "(cached) " >&6 else if test -z "$GREP"; then ac_path_GREP_found=false # Loop through the user's path and test for each of PROGNAME-LIST as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH$PATH_SEPARATOR/usr/xpg4/bin do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_prog in grep ggrep; do for ac_exec_ext in '' $ac_executable_extensions; do ac_path_GREP="$as_dir/$ac_prog$ac_exec_ext" as_fn_executable_p "$ac_path_GREP" || continue # Check for GNU ac_path_GREP and select it if it is found. # Check for GNU $ac_path_GREP case `"$ac_path_GREP" --version 2>&1` in *GNU*) ac_cv_path_GREP="$ac_path_GREP" ac_path_GREP_found=:;; *) ac_count=0 $as_echo_n 0123456789 >"conftest.in" while : do cat "conftest.in" "conftest.in" >"conftest.tmp" mv "conftest.tmp" "conftest.in" cp "conftest.in" "conftest.nl" $as_echo 'GREP' >> "conftest.nl" "$ac_path_GREP" -e 'GREP$' -e '-(cannot match)-' < "conftest.nl" >"conftest.out" 2>/dev/null || break diff "conftest.out" "conftest.nl" >/dev/null 2>&1 || break as_fn_arith $ac_count + 1 && ac_count=$as_val if test $ac_count -gt ${ac_path_GREP_max-0}; then # Best one so far, save it but keep looking for a better one ac_cv_path_GREP="$ac_path_GREP" ac_path_GREP_max=$ac_count fi # 10*(2^10) chars as input seems more than enough test $ac_count -gt 10 && break done rm -f conftest.in conftest.tmp conftest.nl conftest.out;; esac $ac_path_GREP_found && break 3 done done done IFS=$as_save_IFS if test -z "$ac_cv_path_GREP"; then as_fn_error $? "no acceptable grep could be found in $PATH$PATH_SEPARATOR/usr/xpg4/bin" "$LINENO" 5 fi else ac_cv_path_GREP=$GREP fi fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_path_GREP" >&5 $as_echo "$ac_cv_path_GREP" >&6; } GREP="$ac_cv_path_GREP" { $as_echo "$as_me:${as_lineno-$LINENO}: checking for egrep" >&5 $as_echo_n "checking for egrep... " >&6; } if ${ac_cv_path_EGREP+:} false; then : $as_echo_n "(cached) " >&6 else if echo a | $GREP -E '(a|b)' >/dev/null 2>&1 then ac_cv_path_EGREP="$GREP -E" else if test -z "$EGREP"; then ac_path_EGREP_found=false # Loop through the user's path and test for each of PROGNAME-LIST as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH$PATH_SEPARATOR/usr/xpg4/bin do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_prog in egrep; do for ac_exec_ext in '' $ac_executable_extensions; do ac_path_EGREP="$as_dir/$ac_prog$ac_exec_ext" as_fn_executable_p "$ac_path_EGREP" || continue # Check for GNU ac_path_EGREP and select it if it is found. # Check for GNU $ac_path_EGREP case `"$ac_path_EGREP" --version 2>&1` in *GNU*) ac_cv_path_EGREP="$ac_path_EGREP" ac_path_EGREP_found=:;; *) ac_count=0 $as_echo_n 0123456789 >"conftest.in" while : do cat "conftest.in" "conftest.in" >"conftest.tmp" mv "conftest.tmp" "conftest.in" cp "conftest.in" "conftest.nl" $as_echo 'EGREP' >> "conftest.nl" "$ac_path_EGREP" 'EGREP$' < "conftest.nl" >"conftest.out" 2>/dev/null || break diff "conftest.out" "conftest.nl" >/dev/null 2>&1 || break as_fn_arith $ac_count + 1 && ac_count=$as_val if test $ac_count -gt ${ac_path_EGREP_max-0}; then # Best one so far, save it but keep looking for a better one ac_cv_path_EGREP="$ac_path_EGREP" ac_path_EGREP_max=$ac_count fi # 10*(2^10) chars as input seems more than enough test $ac_count -gt 10 && break done rm -f conftest.in conftest.tmp conftest.nl conftest.out;; esac $ac_path_EGREP_found && break 3 done done done IFS=$as_save_IFS if test -z "$ac_cv_path_EGREP"; then as_fn_error $? "no acceptable egrep could be found in $PATH$PATH_SEPARATOR/usr/xpg4/bin" "$LINENO" 5 fi else ac_cv_path_EGREP=$EGREP fi fi fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_path_EGREP" >&5 $as_echo "$ac_cv_path_EGREP" >&6; } EGREP="$ac_cv_path_EGREP" { $as_echo "$as_me:${as_lineno-$LINENO}: checking for ANSI C header files" >&5 $as_echo_n "checking for ANSI C header files... " >&6; } if ${ac_cv_header_stdc+:} false; then : $as_echo_n "(cached) " >&6 else cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #include #include #include #include int main () { ; return 0; } _ACEOF if ac_fn_c_try_compile "$LINENO"; then : ac_cv_header_stdc=yes else ac_cv_header_stdc=no fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext if test $ac_cv_header_stdc = yes; then # SunOS 4.x string.h does not declare mem*, contrary to ANSI. cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #include _ACEOF if (eval "$ac_cpp conftest.$ac_ext") 2>&5 | $EGREP "memchr" >/dev/null 2>&1; then : else ac_cv_header_stdc=no fi rm -f conftest* fi if test $ac_cv_header_stdc = yes; then # ISC 2.0.2 stdlib.h does not declare free, contrary to ANSI. cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #include _ACEOF if (eval "$ac_cpp conftest.$ac_ext") 2>&5 | $EGREP "free" >/dev/null 2>&1; then : else ac_cv_header_stdc=no fi rm -f conftest* fi if test $ac_cv_header_stdc = yes; then # /bin/cc in Irix-4.0.5 gets non-ANSI ctype macros unless using -ansi. if test "$cross_compiling" = yes; then : : else cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #include #include #if ((' ' & 0x0FF) == 0x020) # define ISLOWER(c) ('a' <= (c) && (c) <= 'z') # define TOUPPER(c) (ISLOWER(c) ? 'A' + ((c) - 'a') : (c)) #else # define ISLOWER(c) \ (('a' <= (c) && (c) <= 'i') \ || ('j' <= (c) && (c) <= 'r') \ || ('s' <= (c) && (c) <= 'z')) # define TOUPPER(c) (ISLOWER(c) ? ((c) | 0x40) : (c)) #endif #define XOR(e, f) (((e) && !(f)) || (!(e) && (f))) int main () { int i; for (i = 0; i < 256; i++) if (XOR (islower (i), ISLOWER (i)) || toupper (i) != TOUPPER (i)) return 2; return 0; } _ACEOF if ac_fn_c_try_run "$LINENO"; then : else ac_cv_header_stdc=no fi rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \ conftest.$ac_objext conftest.beam conftest.$ac_ext fi fi fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_header_stdc" >&5 $as_echo "$ac_cv_header_stdc" >&6; } if test $ac_cv_header_stdc = yes; then $as_echo "#define STDC_HEADERS 1" >>confdefs.h fi # On IRIX 5.3, sys/types and inttypes.h are conflicting. for ac_header in sys/types.h sys/stat.h stdlib.h string.h memory.h strings.h \ inttypes.h stdint.h unistd.h do : as_ac_Header=`$as_echo "ac_cv_header_$ac_header" | $as_tr_sh` ac_fn_c_check_header_compile "$LINENO" "$ac_header" "$as_ac_Header" "$ac_includes_default " if eval test \"x\$"$as_ac_Header"\" = x"yes"; then : cat >>confdefs.h <<_ACEOF #define `$as_echo "HAVE_$ac_header" | $as_tr_cpp` 1 _ACEOF fi done ac_fn_c_check_header_mongrel "$LINENO" "minix/config.h" "ac_cv_header_minix_config_h" "$ac_includes_default" if test "x$ac_cv_header_minix_config_h" = xyes; then : MINIX=yes else MINIX= fi if test "$MINIX" = yes; then $as_echo "#define _POSIX_SOURCE 1" >>confdefs.h $as_echo "#define _POSIX_1_SOURCE 2" >>confdefs.h $as_echo "#define _MINIX 1" >>confdefs.h fi { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether it is safe to define __EXTENSIONS__" >&5 $as_echo_n "checking whether it is safe to define __EXTENSIONS__... " >&6; } if ${ac_cv_safe_to_define___extensions__+:} false; then : $as_echo_n "(cached) " >&6 else cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ # define __EXTENSIONS__ 1 $ac_includes_default int main () { ; return 0; } _ACEOF if ac_fn_c_try_compile "$LINENO"; then : ac_cv_safe_to_define___extensions__=yes else ac_cv_safe_to_define___extensions__=no fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_safe_to_define___extensions__" >&5 $as_echo "$ac_cv_safe_to_define___extensions__" >&6; } test $ac_cv_safe_to_define___extensions__ = yes && $as_echo "#define __EXTENSIONS__ 1" >>confdefs.h $as_echo "#define _ALL_SOURCE 1" >>confdefs.h $as_echo "#define _GNU_SOURCE 1" >>confdefs.h $as_echo "#define _POSIX_PTHREAD_SEMANTICS 1" >>confdefs.h $as_echo "#define _TANDEM_SOURCE 1" >>confdefs.h am__api_version='1.15' # Find a good install program. We prefer a C program (faster), # so one script is as good as another. But avoid the broken or # incompatible versions: # SysV /etc/install, /usr/sbin/install # SunOS /usr/etc/install # IRIX /sbin/install # AIX /bin/install # AmigaOS /C/install, which installs bootblocks on floppy discs # AIX 4 /usr/bin/installbsd, which doesn't work without a -g flag # AFS /usr/afsws/bin/install, which mishandles nonexistent args # SVR4 /usr/ucb/install, which tries to use the nonexistent group "staff" # OS/2's system install, which has a completely different semantic # ./install, which can be erroneously created by make from ./install.sh. # Reject install programs that cannot install multiple files. { $as_echo "$as_me:${as_lineno-$LINENO}: checking for a BSD-compatible install" >&5 $as_echo_n "checking for a BSD-compatible install... " >&6; } if test -z "$INSTALL"; then if ${ac_cv_path_install+:} false; then : $as_echo_n "(cached) " >&6 else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. # Account for people who put trailing slashes in PATH elements. case $as_dir/ in #(( ./ | .// | /[cC]/* | \ /etc/* | /usr/sbin/* | /usr/etc/* | /sbin/* | /usr/afsws/bin/* | \ ?:[\\/]os2[\\/]install[\\/]* | ?:[\\/]OS2[\\/]INSTALL[\\/]* | \ /usr/ucb/* ) ;; *) # OSF1 and SCO ODT 3.0 have their own names for install. # Don't use installbsd from OSF since it installs stuff as root # by default. for ac_prog in ginstall scoinst install; do for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir/$ac_prog$ac_exec_ext"; then if test $ac_prog = install && grep dspmsg "$as_dir/$ac_prog$ac_exec_ext" >/dev/null 2>&1; then # AIX install. It has an incompatible calling convention. : elif test $ac_prog = install && grep pwplus "$as_dir/$ac_prog$ac_exec_ext" >/dev/null 2>&1; then # program-specific install script used by HP pwplus--don't use. : else rm -rf conftest.one conftest.two conftest.dir echo one > conftest.one echo two > conftest.two mkdir conftest.dir if "$as_dir/$ac_prog$ac_exec_ext" -c conftest.one conftest.two "`pwd`/conftest.dir" && test -s conftest.one && test -s conftest.two && test -s conftest.dir/conftest.one && test -s conftest.dir/conftest.two then ac_cv_path_install="$as_dir/$ac_prog$ac_exec_ext -c" break 3 fi fi fi done done ;; esac done IFS=$as_save_IFS rm -rf conftest.one conftest.two conftest.dir fi if test "${ac_cv_path_install+set}" = set; then INSTALL=$ac_cv_path_install else # As a last resort, use the slow shell script. Don't cache a # value for INSTALL within a source directory, because that will # break other packages using the cache if that directory is # removed, or if the value is a relative name. INSTALL=$ac_install_sh fi fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $INSTALL" >&5 $as_echo "$INSTALL" >&6; } # Use test -z because SunOS4 sh mishandles braces in ${var-val}. # It thinks the first close brace ends the variable substitution. test -z "$INSTALL_PROGRAM" && INSTALL_PROGRAM='${INSTALL}' test -z "$INSTALL_SCRIPT" && INSTALL_SCRIPT='${INSTALL}' test -z "$INSTALL_DATA" && INSTALL_DATA='${INSTALL} -m 644' { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether build environment is sane" >&5 $as_echo_n "checking whether build environment is sane... " >&6; } # Reject unsafe characters in $srcdir or the absolute working directory # name. Accept space and tab only in the latter. am_lf=' ' case `pwd` in *[\\\"\#\$\&\'\`$am_lf]*) as_fn_error $? "unsafe absolute working directory name" "$LINENO" 5;; esac case $srcdir in *[\\\"\#\$\&\'\`$am_lf\ \ ]*) as_fn_error $? "unsafe srcdir value: '$srcdir'" "$LINENO" 5;; esac # Do 'set' in a subshell so we don't clobber the current shell's # arguments. Must try -L first in case configure is actually a # symlink; some systems play weird games with the mod time of symlinks # (eg FreeBSD returns the mod time of the symlink's containing # directory). if ( am_has_slept=no for am_try in 1 2; do echo "timestamp, slept: $am_has_slept" > conftest.file set X `ls -Lt "$srcdir/configure" conftest.file 2> /dev/null` if test "$*" = "X"; then # -L didn't work. set X `ls -t "$srcdir/configure" conftest.file` fi if test "$*" != "X $srcdir/configure conftest.file" \ && test "$*" != "X conftest.file $srcdir/configure"; then # If neither matched, then we have a broken ls. This can happen # if, for instance, CONFIG_SHELL is bash and it inherits a # broken ls alias from the environment. This has actually # happened. Such a system could not be considered "sane". as_fn_error $? "ls -t appears to fail. Make sure there is not a broken alias in your environment" "$LINENO" 5 fi if test "$2" = conftest.file || test $am_try -eq 2; then break fi # Just in case. sleep 1 am_has_slept=yes done test "$2" = conftest.file ) then # Ok. : else as_fn_error $? "newly created file is older than distributed files! Check your system clock" "$LINENO" 5 fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 $as_echo "yes" >&6; } # If we didn't sleep, we still need to ensure time stamps of config.status and # generated files are strictly newer. am_sleep_pid= if grep 'slept: no' conftest.file >/dev/null 2>&1; then ( sleep 1 ) & am_sleep_pid=$! fi rm -f conftest.file test "$program_prefix" != NONE && program_transform_name="s&^&$program_prefix&;$program_transform_name" # Use a double $ so make ignores it. test "$program_suffix" != NONE && program_transform_name="s&\$&$program_suffix&;$program_transform_name" # Double any \ or $. # By default was `s,x,x', remove it if useless. ac_script='s/[\\$]/&&/g;s/;s,x,x,$//' program_transform_name=`$as_echo "$program_transform_name" | sed "$ac_script"` if test x"${MISSING+set}" != xset; then case $am_aux_dir in *\ * | *\ *) MISSING="\${SHELL} \"$am_aux_dir/missing\"" ;; *) MISSING="\${SHELL} $am_aux_dir/missing" ;; esac fi # Use eval to expand $SHELL if eval "$MISSING --is-lightweight"; then am_missing_run="$MISSING " else am_missing_run= { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: 'missing' script is too old or missing" >&5 $as_echo "$as_me: WARNING: 'missing' script is too old or missing" >&2;} fi if test x"${install_sh+set}" != xset; then case $am_aux_dir in *\ * | *\ *) install_sh="\${SHELL} '$am_aux_dir/install-sh'" ;; *) install_sh="\${SHELL} $am_aux_dir/install-sh" esac fi # Installed binaries are usually stripped using 'strip' when the user # run "make install-strip". However 'strip' might not be the right # tool to use in cross-compilation environments, therefore Automake # will honor the 'STRIP' environment variable to overrule this program. if test "$cross_compiling" != no; then if test -n "$ac_tool_prefix"; then # Extract the first word of "${ac_tool_prefix}strip", so it can be a program name with args. set dummy ${ac_tool_prefix}strip; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if ${ac_cv_prog_STRIP+:} false; then : $as_echo_n "(cached) " >&6 else if test -n "$STRIP"; then ac_cv_prog_STRIP="$STRIP" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then ac_cv_prog_STRIP="${ac_tool_prefix}strip" $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi fi STRIP=$ac_cv_prog_STRIP if test -n "$STRIP"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $STRIP" >&5 $as_echo "$STRIP" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi fi if test -z "$ac_cv_prog_STRIP"; then ac_ct_STRIP=$STRIP # Extract the first word of "strip", so it can be a program name with args. set dummy strip; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if ${ac_cv_prog_ac_ct_STRIP+:} false; then : $as_echo_n "(cached) " >&6 else if test -n "$ac_ct_STRIP"; then ac_cv_prog_ac_ct_STRIP="$ac_ct_STRIP" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then ac_cv_prog_ac_ct_STRIP="strip" $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi fi ac_ct_STRIP=$ac_cv_prog_ac_ct_STRIP if test -n "$ac_ct_STRIP"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_ct_STRIP" >&5 $as_echo "$ac_ct_STRIP" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi if test "x$ac_ct_STRIP" = x; then STRIP=":" else case $cross_compiling:$ac_tool_warned in yes:) { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5 $as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} ac_tool_warned=yes ;; esac STRIP=$ac_ct_STRIP fi else STRIP="$ac_cv_prog_STRIP" fi fi INSTALL_STRIP_PROGRAM="\$(install_sh) -c -s" { $as_echo "$as_me:${as_lineno-$LINENO}: checking for a thread-safe mkdir -p" >&5 $as_echo_n "checking for a thread-safe mkdir -p... " >&6; } if test -z "$MKDIR_P"; then if ${ac_cv_path_mkdir+:} false; then : $as_echo_n "(cached) " >&6 else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH$PATH_SEPARATOR/opt/sfw/bin do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_prog in mkdir gmkdir; do for ac_exec_ext in '' $ac_executable_extensions; do as_fn_executable_p "$as_dir/$ac_prog$ac_exec_ext" || continue case `"$as_dir/$ac_prog$ac_exec_ext" --version 2>&1` in #( 'mkdir (GNU coreutils) '* | \ 'mkdir (coreutils) '* | \ 'mkdir (fileutils) '4.1*) ac_cv_path_mkdir=$as_dir/$ac_prog$ac_exec_ext break 3;; esac done done done IFS=$as_save_IFS fi test -d ./--version && rmdir ./--version if test "${ac_cv_path_mkdir+set}" = set; then MKDIR_P="$ac_cv_path_mkdir -p" else # As a last resort, use the slow shell script. Don't cache a # value for MKDIR_P within a source directory, because that will # break other packages using the cache if that directory is # removed, or if the value is a relative name. MKDIR_P="$ac_install_sh -d" fi fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $MKDIR_P" >&5 $as_echo "$MKDIR_P" >&6; } for ac_prog in gawk mawk nawk awk do # Extract the first word of "$ac_prog", so it can be a program name with args. set dummy $ac_prog; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if ${ac_cv_prog_AWK+:} false; then : $as_echo_n "(cached) " >&6 else if test -n "$AWK"; then ac_cv_prog_AWK="$AWK" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then ac_cv_prog_AWK="$ac_prog" $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi fi AWK=$ac_cv_prog_AWK if test -n "$AWK"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $AWK" >&5 $as_echo "$AWK" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi test -n "$AWK" && break done { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether ${MAKE-make} sets \$(MAKE)" >&5 $as_echo_n "checking whether ${MAKE-make} sets \$(MAKE)... " >&6; } set x ${MAKE-make} ac_make=`$as_echo "$2" | sed 's/+/p/g; s/[^a-zA-Z0-9_]/_/g'` if eval \${ac_cv_prog_make_${ac_make}_set+:} false; then : $as_echo_n "(cached) " >&6 else cat >conftest.make <<\_ACEOF SHELL = /bin/sh all: @echo '@@@%%%=$(MAKE)=@@@%%%' _ACEOF # GNU make sometimes prints "make[1]: Entering ...", which would confuse us. case `${MAKE-make} -f conftest.make 2>/dev/null` in *@@@%%%=?*=@@@%%%*) eval ac_cv_prog_make_${ac_make}_set=yes;; *) eval ac_cv_prog_make_${ac_make}_set=no;; esac rm -f conftest.make fi if eval test \$ac_cv_prog_make_${ac_make}_set = yes; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 $as_echo "yes" >&6; } SET_MAKE= else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } SET_MAKE="MAKE=${MAKE-make}" fi rm -rf .tst 2>/dev/null mkdir .tst 2>/dev/null if test -d .tst; then am__leading_dot=. else am__leading_dot=_ fi rmdir .tst 2>/dev/null DEPDIR="${am__leading_dot}deps" ac_config_commands="$ac_config_commands depfiles" am_make=${MAKE-make} cat > confinc << 'END' am__doit: @echo this is the am__doit target .PHONY: am__doit END # If we don't find an include directive, just comment out the code. { $as_echo "$as_me:${as_lineno-$LINENO}: checking for style of include used by $am_make" >&5 $as_echo_n "checking for style of include used by $am_make... " >&6; } am__include="#" am__quote= _am_result=none # First try GNU make style include. echo "include confinc" > confmf # Ignore all kinds of additional output from 'make'. case `$am_make -s -f confmf 2> /dev/null` in #( *the\ am__doit\ target*) am__include=include am__quote= _am_result=GNU ;; esac # Now try BSD make style include. if test "$am__include" = "#"; then echo '.include "confinc"' > confmf case `$am_make -s -f confmf 2> /dev/null` in #( *the\ am__doit\ target*) am__include=.include am__quote="\"" _am_result=BSD ;; esac fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $_am_result" >&5 $as_echo "$_am_result" >&6; } rm -f confinc confmf # Check whether --enable-dependency-tracking was given. if test "${enable_dependency_tracking+set}" = set; then : enableval=$enable_dependency_tracking; fi if test "x$enable_dependency_tracking" != xno; then am_depcomp="$ac_aux_dir/depcomp" AMDEPBACKSLASH='\' am__nodep='_no' fi if test "x$enable_dependency_tracking" != xno; then AMDEP_TRUE= AMDEP_FALSE='#' else AMDEP_TRUE='#' AMDEP_FALSE= fi # Check whether --enable-silent-rules was given. if test "${enable_silent_rules+set}" = set; then : enableval=$enable_silent_rules; fi case $enable_silent_rules in # ((( yes) AM_DEFAULT_VERBOSITY=0;; no) AM_DEFAULT_VERBOSITY=1;; *) AM_DEFAULT_VERBOSITY=1;; esac am_make=${MAKE-make} { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether $am_make supports nested variables" >&5 $as_echo_n "checking whether $am_make supports nested variables... " >&6; } if ${am_cv_make_support_nested_variables+:} false; then : $as_echo_n "(cached) " >&6 else if $as_echo 'TRUE=$(BAR$(V)) BAR0=false BAR1=true V=1 am__doit: @$(TRUE) .PHONY: am__doit' | $am_make -f - >/dev/null 2>&1; then am_cv_make_support_nested_variables=yes else am_cv_make_support_nested_variables=no fi fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $am_cv_make_support_nested_variables" >&5 $as_echo "$am_cv_make_support_nested_variables" >&6; } if test $am_cv_make_support_nested_variables = yes; then AM_V='$(V)' AM_DEFAULT_V='$(AM_DEFAULT_VERBOSITY)' else AM_V=$AM_DEFAULT_VERBOSITY AM_DEFAULT_V=$AM_DEFAULT_VERBOSITY fi AM_BACKSLASH='\' if test "`cd $srcdir && pwd`" != "`pwd`"; then # Use -I$(srcdir) only when $(srcdir) != ., so that make's output # is not polluted with repeated "-I." am__isrc=' -I$(srcdir)' # test to see if srcdir already configured if test -f $srcdir/config.status; then as_fn_error $? "source directory already configured; run \"make distclean\" there first" "$LINENO" 5 fi fi # test whether we have cygpath if test -z "$CYGPATH_W"; then if (cygpath --version) >/dev/null 2>/dev/null; then CYGPATH_W='cygpath -w' else CYGPATH_W=echo fi fi # Define the identity of the package. PACKAGE='libedit-20171208' VERSION='3.1' cat >>confdefs.h <<_ACEOF #define PACKAGE "$PACKAGE" _ACEOF cat >>confdefs.h <<_ACEOF #define VERSION "$VERSION" _ACEOF # Some tools Automake needs. ACLOCAL=${ACLOCAL-"${am_missing_run}aclocal-${am__api_version}"} AUTOCONF=${AUTOCONF-"${am_missing_run}autoconf"} AUTOMAKE=${AUTOMAKE-"${am_missing_run}automake-${am__api_version}"} AUTOHEADER=${AUTOHEADER-"${am_missing_run}autoheader"} MAKEINFO=${MAKEINFO-"${am_missing_run}makeinfo"} # For better backward compatibility. To be removed once Automake 1.9.x # dies out for good. For more background, see: # # mkdir_p='$(MKDIR_P)' # We need awk for the "check" target (and possibly the TAP driver). The # system "awk" is bad on some platforms. # Always define AMTAR for backward compatibility. Yes, it's still used # in the wild :-( We should find a proper way to deprecate it ... AMTAR='$${TAR-tar}' # We'll loop over all known methods to create a tar archive until one works. _am_tools='gnutar pax cpio none' am__tar='$${TAR-tar} chof - "$$tardir"' am__untar='$${TAR-tar} xf -' depcc="$CC" am_compiler_list= { $as_echo "$as_me:${as_lineno-$LINENO}: checking dependency style of $depcc" >&5 $as_echo_n "checking dependency style of $depcc... " >&6; } if ${am_cv_CC_dependencies_compiler_type+:} false; then : $as_echo_n "(cached) " >&6 else if test -z "$AMDEP_TRUE" && test -f "$am_depcomp"; then # We make a subdir and do the tests there. Otherwise we can end up # making bogus files that we don't know about and never remove. For # instance it was reported that on HP-UX the gcc test will end up # making a dummy file named 'D' -- because '-MD' means "put the output # in D". rm -rf conftest.dir mkdir conftest.dir # Copy depcomp to subdir because otherwise we won't find it if we're # using a relative directory. cp "$am_depcomp" conftest.dir cd conftest.dir # We will build objects and dependencies in a subdirectory because # it helps to detect inapplicable dependency modes. For instance # both Tru64's cc and ICC support -MD to output dependencies as a # side effect of compilation, but ICC will put the dependencies in # the current directory while Tru64 will put them in the object # directory. mkdir sub am_cv_CC_dependencies_compiler_type=none if test "$am_compiler_list" = ""; then am_compiler_list=`sed -n 's/^#*\([a-zA-Z0-9]*\))$/\1/p' < ./depcomp` fi am__universal=false case " $depcc " in #( *\ -arch\ *\ -arch\ *) am__universal=true ;; esac for depmode in $am_compiler_list; do # Setup a source with many dependencies, because some compilers # like to wrap large dependency lists on column 80 (with \), and # we should not choose a depcomp mode which is confused by this. # # We need to recreate these files for each test, as the compiler may # overwrite some of them when testing with obscure command lines. # This happens at least with the AIX C compiler. : > sub/conftest.c for i in 1 2 3 4 5 6; do echo '#include "conftst'$i'.h"' >> sub/conftest.c # Using ": > sub/conftst$i.h" creates only sub/conftst1.h with # Solaris 10 /bin/sh. echo '/* dummy */' > sub/conftst$i.h done echo "${am__include} ${am__quote}sub/conftest.Po${am__quote}" > confmf # We check with '-c' and '-o' for the sake of the "dashmstdout" # mode. It turns out that the SunPro C++ compiler does not properly # handle '-M -o', and we need to detect this. Also, some Intel # versions had trouble with output in subdirs. am__obj=sub/conftest.${OBJEXT-o} am__minus_obj="-o $am__obj" case $depmode in gcc) # This depmode causes a compiler race in universal mode. test "$am__universal" = false || continue ;; nosideeffect) # After this tag, mechanisms are not by side-effect, so they'll # only be used when explicitly requested. if test "x$enable_dependency_tracking" = xyes; then continue else break fi ;; msvc7 | msvc7msys | msvisualcpp | msvcmsys) # This compiler won't grok '-c -o', but also, the minuso test has # not run yet. These depmodes are late enough in the game, and # so weak that their functioning should not be impacted. am__obj=conftest.${OBJEXT-o} am__minus_obj= ;; none) break ;; esac if depmode=$depmode \ source=sub/conftest.c object=$am__obj \ depfile=sub/conftest.Po tmpdepfile=sub/conftest.TPo \ $SHELL ./depcomp $depcc -c $am__minus_obj sub/conftest.c \ >/dev/null 2>conftest.err && grep sub/conftst1.h sub/conftest.Po > /dev/null 2>&1 && grep sub/conftst6.h sub/conftest.Po > /dev/null 2>&1 && grep $am__obj sub/conftest.Po > /dev/null 2>&1 && ${MAKE-make} -s -f confmf > /dev/null 2>&1; then # icc doesn't choke on unknown options, it will just issue warnings # or remarks (even with -Werror). So we grep stderr for any message # that says an option was ignored or not supported. # When given -MP, icc 7.0 and 7.1 complain thusly: # icc: Command line warning: ignoring option '-M'; no argument required # The diagnosis changed in icc 8.0: # icc: Command line remark: option '-MP' not supported if (grep 'ignoring option' conftest.err || grep 'not supported' conftest.err) >/dev/null 2>&1; then :; else am_cv_CC_dependencies_compiler_type=$depmode break fi fi done cd .. rm -rf conftest.dir else am_cv_CC_dependencies_compiler_type=none fi fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $am_cv_CC_dependencies_compiler_type" >&5 $as_echo "$am_cv_CC_dependencies_compiler_type" >&6; } CCDEPMODE=depmode=$am_cv_CC_dependencies_compiler_type if test "x$enable_dependency_tracking" != xno \ && test "$am_cv_CC_dependencies_compiler_type" = gcc3; then am__fastdepCC_TRUE= am__fastdepCC_FALSE='#' else am__fastdepCC_TRUE='#' am__fastdepCC_FALSE= fi # POSIX will say in a future version that running "rm -f" with no argument # is OK; and we want to be able to make that assumption in our Makefile # recipes. So use an aggressive probe to check that the usage we want is # actually supported "in the wild" to an acceptable degree. # See automake bug#10828. # To make any issue more visible, cause the running configure to be aborted # by default if the 'rm' program in use doesn't match our expectations; the # user can still override this though. if rm -f && rm -fr && rm -rf; then : OK; else cat >&2 <<'END' Oops! Your 'rm' program seems unable to run without file operands specified on the command line, even when the '-f' option is present. This is contrary to the behaviour of most rm programs out there, and not conforming with the upcoming POSIX standard: Please tell bug-automake@gnu.org about your system, including the value of your $PATH and any error possibly output before this message. This can help us improve future automake versions. END if test x"$ACCEPT_INFERIOR_RM_PROGRAM" = x"yes"; then echo 'Configuration will proceed anyway, since you have set the' >&2 echo 'ACCEPT_INFERIOR_RM_PROGRAM variable to "yes"' >&2 echo >&2 else cat >&2 <<'END' Aborting the configuration process, to ensure you take notice of the issue. You can download and install GNU coreutils to get an 'rm' implementation that behaves properly: . If you want to complete the configuration process using your problematic 'rm' anyway, export the environment variable ACCEPT_INFERIOR_RM_PROGRAM to "yes", and re-run configure. END as_fn_error $? "Your 'rm' program is bad, sorry." "$LINENO" 5 fi fi case `pwd` in *\ * | *\ *) { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: Libtool does not cope well with whitespace in \`pwd\`" >&5 $as_echo "$as_me: WARNING: Libtool does not cope well with whitespace in \`pwd\`" >&2;} ;; esac macro_version='2.4.6' macro_revision='2.4.6' ltmain=$ac_aux_dir/ltmain.sh # Make sure we can run config.sub. $SHELL "$ac_aux_dir/config.sub" sun4 >/dev/null 2>&1 || as_fn_error $? "cannot run $SHELL $ac_aux_dir/config.sub" "$LINENO" 5 { $as_echo "$as_me:${as_lineno-$LINENO}: checking build system type" >&5 $as_echo_n "checking build system type... " >&6; } if ${ac_cv_build+:} false; then : $as_echo_n "(cached) " >&6 else ac_build_alias=$build_alias test "x$ac_build_alias" = x && ac_build_alias=`$SHELL "$ac_aux_dir/config.guess"` test "x$ac_build_alias" = x && as_fn_error $? "cannot guess build type; you must specify one" "$LINENO" 5 ac_cv_build=`$SHELL "$ac_aux_dir/config.sub" $ac_build_alias` || as_fn_error $? "$SHELL $ac_aux_dir/config.sub $ac_build_alias failed" "$LINENO" 5 fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_build" >&5 $as_echo "$ac_cv_build" >&6; } case $ac_cv_build in *-*-*) ;; *) as_fn_error $? "invalid value of canonical build" "$LINENO" 5;; esac build=$ac_cv_build ac_save_IFS=$IFS; IFS='-' set x $ac_cv_build shift build_cpu=$1 build_vendor=$2 shift; shift # Remember, the first character of IFS is used to create $*, # except with old shells: build_os=$* IFS=$ac_save_IFS case $build_os in *\ *) build_os=`echo "$build_os" | sed 's/ /-/g'`;; esac { $as_echo "$as_me:${as_lineno-$LINENO}: checking host system type" >&5 $as_echo_n "checking host system type... " >&6; } if ${ac_cv_host+:} false; then : $as_echo_n "(cached) " >&6 else if test "x$host_alias" = x; then ac_cv_host=$ac_cv_build else ac_cv_host=`$SHELL "$ac_aux_dir/config.sub" $host_alias` || as_fn_error $? "$SHELL $ac_aux_dir/config.sub $host_alias failed" "$LINENO" 5 fi fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_host" >&5 $as_echo "$ac_cv_host" >&6; } case $ac_cv_host in *-*-*) ;; *) as_fn_error $? "invalid value of canonical host" "$LINENO" 5;; esac host=$ac_cv_host ac_save_IFS=$IFS; IFS='-' set x $ac_cv_host shift host_cpu=$1 host_vendor=$2 shift; shift # Remember, the first character of IFS is used to create $*, # except with old shells: host_os=$* IFS=$ac_save_IFS case $host_os in *\ *) host_os=`echo "$host_os" | sed 's/ /-/g'`;; esac # Backslashify metacharacters that are still active within # double-quoted strings. sed_quote_subst='s/\(["`$\\]\)/\\\1/g' # Same as above, but do not quote variable references. double_quote_subst='s/\(["`\\]\)/\\\1/g' # Sed substitution to delay expansion of an escaped shell variable in a # double_quote_subst'ed string. delay_variable_subst='s/\\\\\\\\\\\$/\\\\\\$/g' # Sed substitution to delay expansion of an escaped single quote. delay_single_quote_subst='s/'\''/'\'\\\\\\\'\''/g' # Sed substitution to avoid accidental globbing in evaled expressions no_glob_subst='s/\*/\\\*/g' ECHO='\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\' ECHO=$ECHO$ECHO$ECHO$ECHO$ECHO ECHO=$ECHO$ECHO$ECHO$ECHO$ECHO$ECHO { $as_echo "$as_me:${as_lineno-$LINENO}: checking how to print strings" >&5 $as_echo_n "checking how to print strings... " >&6; } # Test print first, because it will be a builtin if present. if test "X`( print -r -- -n ) 2>/dev/null`" = X-n && \ test "X`print -r -- $ECHO 2>/dev/null`" = "X$ECHO"; then ECHO='print -r --' elif test "X`printf %s $ECHO 2>/dev/null`" = "X$ECHO"; then ECHO='printf %s\n' else # Use this function as a fallback that always works. func_fallback_echo () { eval 'cat <<_LTECHO_EOF $1 _LTECHO_EOF' } ECHO='func_fallback_echo' fi # func_echo_all arg... # Invoke $ECHO with all args, space-separated. func_echo_all () { $ECHO "" } case $ECHO in printf*) { $as_echo "$as_me:${as_lineno-$LINENO}: result: printf" >&5 $as_echo "printf" >&6; } ;; print*) { $as_echo "$as_me:${as_lineno-$LINENO}: result: print -r" >&5 $as_echo "print -r" >&6; } ;; *) { $as_echo "$as_me:${as_lineno-$LINENO}: result: cat" >&5 $as_echo "cat" >&6; } ;; esac { $as_echo "$as_me:${as_lineno-$LINENO}: checking for a sed that does not truncate output" >&5 $as_echo_n "checking for a sed that does not truncate output... " >&6; } if ${ac_cv_path_SED+:} false; then : $as_echo_n "(cached) " >&6 else ac_script=s/aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb/ for ac_i in 1 2 3 4 5 6 7; do ac_script="$ac_script$as_nl$ac_script" done echo "$ac_script" 2>/dev/null | sed 99q >conftest.sed { ac_script=; unset ac_script;} if test -z "$SED"; then ac_path_SED_found=false # Loop through the user's path and test for each of PROGNAME-LIST as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_prog in sed gsed; do for ac_exec_ext in '' $ac_executable_extensions; do ac_path_SED="$as_dir/$ac_prog$ac_exec_ext" as_fn_executable_p "$ac_path_SED" || continue # Check for GNU ac_path_SED and select it if it is found. # Check for GNU $ac_path_SED case `"$ac_path_SED" --version 2>&1` in *GNU*) ac_cv_path_SED="$ac_path_SED" ac_path_SED_found=:;; *) ac_count=0 $as_echo_n 0123456789 >"conftest.in" while : do cat "conftest.in" "conftest.in" >"conftest.tmp" mv "conftest.tmp" "conftest.in" cp "conftest.in" "conftest.nl" $as_echo '' >> "conftest.nl" "$ac_path_SED" -f conftest.sed < "conftest.nl" >"conftest.out" 2>/dev/null || break diff "conftest.out" "conftest.nl" >/dev/null 2>&1 || break as_fn_arith $ac_count + 1 && ac_count=$as_val if test $ac_count -gt ${ac_path_SED_max-0}; then # Best one so far, save it but keep looking for a better one ac_cv_path_SED="$ac_path_SED" ac_path_SED_max=$ac_count fi # 10*(2^10) chars as input seems more than enough test $ac_count -gt 10 && break done rm -f conftest.in conftest.tmp conftest.nl conftest.out;; esac $ac_path_SED_found && break 3 done done done IFS=$as_save_IFS if test -z "$ac_cv_path_SED"; then as_fn_error $? "no acceptable sed could be found in \$PATH" "$LINENO" 5 fi else ac_cv_path_SED=$SED fi fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_path_SED" >&5 $as_echo "$ac_cv_path_SED" >&6; } SED="$ac_cv_path_SED" rm -f conftest.sed test -z "$SED" && SED=sed Xsed="$SED -e 1s/^X//" { $as_echo "$as_me:${as_lineno-$LINENO}: checking for fgrep" >&5 $as_echo_n "checking for fgrep... " >&6; } if ${ac_cv_path_FGREP+:} false; then : $as_echo_n "(cached) " >&6 else if echo 'ab*c' | $GREP -F 'ab*c' >/dev/null 2>&1 then ac_cv_path_FGREP="$GREP -F" else if test -z "$FGREP"; then ac_path_FGREP_found=false # Loop through the user's path and test for each of PROGNAME-LIST as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH$PATH_SEPARATOR/usr/xpg4/bin do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_prog in fgrep; do for ac_exec_ext in '' $ac_executable_extensions; do ac_path_FGREP="$as_dir/$ac_prog$ac_exec_ext" as_fn_executable_p "$ac_path_FGREP" || continue # Check for GNU ac_path_FGREP and select it if it is found. # Check for GNU $ac_path_FGREP case `"$ac_path_FGREP" --version 2>&1` in *GNU*) ac_cv_path_FGREP="$ac_path_FGREP" ac_path_FGREP_found=:;; *) ac_count=0 $as_echo_n 0123456789 >"conftest.in" while : do cat "conftest.in" "conftest.in" >"conftest.tmp" mv "conftest.tmp" "conftest.in" cp "conftest.in" "conftest.nl" $as_echo 'FGREP' >> "conftest.nl" "$ac_path_FGREP" FGREP < "conftest.nl" >"conftest.out" 2>/dev/null || break diff "conftest.out" "conftest.nl" >/dev/null 2>&1 || break as_fn_arith $ac_count + 1 && ac_count=$as_val if test $ac_count -gt ${ac_path_FGREP_max-0}; then # Best one so far, save it but keep looking for a better one ac_cv_path_FGREP="$ac_path_FGREP" ac_path_FGREP_max=$ac_count fi # 10*(2^10) chars as input seems more than enough test $ac_count -gt 10 && break done rm -f conftest.in conftest.tmp conftest.nl conftest.out;; esac $ac_path_FGREP_found && break 3 done done done IFS=$as_save_IFS if test -z "$ac_cv_path_FGREP"; then as_fn_error $? "no acceptable fgrep could be found in $PATH$PATH_SEPARATOR/usr/xpg4/bin" "$LINENO" 5 fi else ac_cv_path_FGREP=$FGREP fi fi fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_path_FGREP" >&5 $as_echo "$ac_cv_path_FGREP" >&6; } FGREP="$ac_cv_path_FGREP" test -z "$GREP" && GREP=grep # Check whether --with-gnu-ld was given. if test "${with_gnu_ld+set}" = set; then : withval=$with_gnu_ld; test no = "$withval" || with_gnu_ld=yes else with_gnu_ld=no fi ac_prog=ld if test yes = "$GCC"; then # Check if gcc -print-prog-name=ld gives a path. { $as_echo "$as_me:${as_lineno-$LINENO}: checking for ld used by $CC" >&5 $as_echo_n "checking for ld used by $CC... " >&6; } case $host in *-*-mingw*) # gcc leaves a trailing carriage return, which upsets mingw ac_prog=`($CC -print-prog-name=ld) 2>&5 | tr -d '\015'` ;; *) ac_prog=`($CC -print-prog-name=ld) 2>&5` ;; esac case $ac_prog in # Accept absolute paths. [\\/]* | ?:[\\/]*) re_direlt='/[^/][^/]*/\.\./' # Canonicalize the pathname of ld ac_prog=`$ECHO "$ac_prog"| $SED 's%\\\\%/%g'` while $ECHO "$ac_prog" | $GREP "$re_direlt" > /dev/null 2>&1; do ac_prog=`$ECHO $ac_prog| $SED "s%$re_direlt%/%"` done test -z "$LD" && LD=$ac_prog ;; "") # If it fails, then pretend we aren't using GCC. ac_prog=ld ;; *) # If it is relative, then search for the first ld in PATH. with_gnu_ld=unknown ;; esac elif test yes = "$with_gnu_ld"; then { $as_echo "$as_me:${as_lineno-$LINENO}: checking for GNU ld" >&5 $as_echo_n "checking for GNU ld... " >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: checking for non-GNU ld" >&5 $as_echo_n "checking for non-GNU ld... " >&6; } fi if ${lt_cv_path_LD+:} false; then : $as_echo_n "(cached) " >&6 else if test -z "$LD"; then lt_save_ifs=$IFS; IFS=$PATH_SEPARATOR for ac_dir in $PATH; do IFS=$lt_save_ifs test -z "$ac_dir" && ac_dir=. if test -f "$ac_dir/$ac_prog" || test -f "$ac_dir/$ac_prog$ac_exeext"; then lt_cv_path_LD=$ac_dir/$ac_prog # Check to see if the program is GNU ld. I'd rather use --version, # but apparently some variants of GNU ld only accept -v. # Break only if it was the GNU/non-GNU ld that we prefer. case `"$lt_cv_path_LD" -v 2>&1 &5 $as_echo "$LD" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi test -z "$LD" && as_fn_error $? "no acceptable ld found in \$PATH" "$LINENO" 5 { $as_echo "$as_me:${as_lineno-$LINENO}: checking if the linker ($LD) is GNU ld" >&5 $as_echo_n "checking if the linker ($LD) is GNU ld... " >&6; } if ${lt_cv_prog_gnu_ld+:} false; then : $as_echo_n "(cached) " >&6 else # I'd rather use --version here, but apparently some GNU lds only accept -v. case `$LD -v 2>&1 &5 $as_echo "$lt_cv_prog_gnu_ld" >&6; } with_gnu_ld=$lt_cv_prog_gnu_ld { $as_echo "$as_me:${as_lineno-$LINENO}: checking for BSD- or MS-compatible name lister (nm)" >&5 $as_echo_n "checking for BSD- or MS-compatible name lister (nm)... " >&6; } if ${lt_cv_path_NM+:} false; then : $as_echo_n "(cached) " >&6 else if test -n "$NM"; then # Let the user override the test. lt_cv_path_NM=$NM else lt_nm_to_check=${ac_tool_prefix}nm if test -n "$ac_tool_prefix" && test "$build" = "$host"; then lt_nm_to_check="$lt_nm_to_check nm" fi for lt_tmp_nm in $lt_nm_to_check; do lt_save_ifs=$IFS; IFS=$PATH_SEPARATOR for ac_dir in $PATH /usr/ccs/bin/elf /usr/ccs/bin /usr/ucb /bin; do IFS=$lt_save_ifs test -z "$ac_dir" && ac_dir=. tmp_nm=$ac_dir/$lt_tmp_nm if test -f "$tmp_nm" || test -f "$tmp_nm$ac_exeext"; then # Check to see if the nm accepts a BSD-compat flag. # Adding the 'sed 1q' prevents false positives on HP-UX, which says: # nm: unknown option "B" ignored # Tru64's nm complains that /dev/null is an invalid object file # MSYS converts /dev/null to NUL, MinGW nm treats NUL as empty case $build_os in mingw*) lt_bad_file=conftest.nm/nofile ;; *) lt_bad_file=/dev/null ;; esac case `"$tmp_nm" -B $lt_bad_file 2>&1 | sed '1q'` in *$lt_bad_file* | *'Invalid file or object type'*) lt_cv_path_NM="$tmp_nm -B" break 2 ;; *) case `"$tmp_nm" -p /dev/null 2>&1 | sed '1q'` in */dev/null*) lt_cv_path_NM="$tmp_nm -p" break 2 ;; *) lt_cv_path_NM=${lt_cv_path_NM="$tmp_nm"} # keep the first match, but continue # so that we can try to find one that supports BSD flags ;; esac ;; esac fi done IFS=$lt_save_ifs done : ${lt_cv_path_NM=no} fi fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_path_NM" >&5 $as_echo "$lt_cv_path_NM" >&6; } if test no != "$lt_cv_path_NM"; then NM=$lt_cv_path_NM else # Didn't find any BSD compatible name lister, look for dumpbin. if test -n "$DUMPBIN"; then : # Let the user override the test. else if test -n "$ac_tool_prefix"; then for ac_prog in dumpbin "link -dump" do # Extract the first word of "$ac_tool_prefix$ac_prog", so it can be a program name with args. set dummy $ac_tool_prefix$ac_prog; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if ${ac_cv_prog_DUMPBIN+:} false; then : $as_echo_n "(cached) " >&6 else if test -n "$DUMPBIN"; then ac_cv_prog_DUMPBIN="$DUMPBIN" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then ac_cv_prog_DUMPBIN="$ac_tool_prefix$ac_prog" $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi fi DUMPBIN=$ac_cv_prog_DUMPBIN if test -n "$DUMPBIN"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $DUMPBIN" >&5 $as_echo "$DUMPBIN" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi test -n "$DUMPBIN" && break done fi if test -z "$DUMPBIN"; then ac_ct_DUMPBIN=$DUMPBIN for ac_prog in dumpbin "link -dump" do # Extract the first word of "$ac_prog", so it can be a program name with args. set dummy $ac_prog; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if ${ac_cv_prog_ac_ct_DUMPBIN+:} false; then : $as_echo_n "(cached) " >&6 else if test -n "$ac_ct_DUMPBIN"; then ac_cv_prog_ac_ct_DUMPBIN="$ac_ct_DUMPBIN" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then ac_cv_prog_ac_ct_DUMPBIN="$ac_prog" $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi fi ac_ct_DUMPBIN=$ac_cv_prog_ac_ct_DUMPBIN if test -n "$ac_ct_DUMPBIN"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_ct_DUMPBIN" >&5 $as_echo "$ac_ct_DUMPBIN" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi test -n "$ac_ct_DUMPBIN" && break done if test "x$ac_ct_DUMPBIN" = x; then DUMPBIN=":" else case $cross_compiling:$ac_tool_warned in yes:) { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5 $as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} ac_tool_warned=yes ;; esac DUMPBIN=$ac_ct_DUMPBIN fi fi case `$DUMPBIN -symbols -headers /dev/null 2>&1 | sed '1q'` in *COFF*) DUMPBIN="$DUMPBIN -symbols -headers" ;; *) DUMPBIN=: ;; esac fi if test : != "$DUMPBIN"; then NM=$DUMPBIN fi fi test -z "$NM" && NM=nm { $as_echo "$as_me:${as_lineno-$LINENO}: checking the name lister ($NM) interface" >&5 $as_echo_n "checking the name lister ($NM) interface... " >&6; } if ${lt_cv_nm_interface+:} false; then : $as_echo_n "(cached) " >&6 else lt_cv_nm_interface="BSD nm" echo "int some_variable = 0;" > conftest.$ac_ext (eval echo "\"\$as_me:$LINENO: $ac_compile\"" >&5) (eval "$ac_compile" 2>conftest.err) cat conftest.err >&5 (eval echo "\"\$as_me:$LINENO: $NM \\\"conftest.$ac_objext\\\"\"" >&5) (eval "$NM \"conftest.$ac_objext\"" 2>conftest.err > conftest.out) cat conftest.err >&5 (eval echo "\"\$as_me:$LINENO: output\"" >&5) cat conftest.out >&5 if $GREP 'External.*some_variable' conftest.out > /dev/null; then lt_cv_nm_interface="MS dumpbin" fi rm -f conftest* fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_nm_interface" >&5 $as_echo "$lt_cv_nm_interface" >&6; } { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether ln -s works" >&5 $as_echo_n "checking whether ln -s works... " >&6; } LN_S=$as_ln_s if test "$LN_S" = "ln -s"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 $as_echo "yes" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no, using $LN_S" >&5 $as_echo "no, using $LN_S" >&6; } fi # find the maximum length of command line arguments { $as_echo "$as_me:${as_lineno-$LINENO}: checking the maximum length of command line arguments" >&5 $as_echo_n "checking the maximum length of command line arguments... " >&6; } if ${lt_cv_sys_max_cmd_len+:} false; then : $as_echo_n "(cached) " >&6 else i=0 teststring=ABCD case $build_os in msdosdjgpp*) # On DJGPP, this test can blow up pretty badly due to problems in libc # (any single argument exceeding 2000 bytes causes a buffer overrun # during glob expansion). Even if it were fixed, the result of this # check would be larger than it should be. lt_cv_sys_max_cmd_len=12288; # 12K is about right ;; gnu*) # Under GNU Hurd, this test is not required because there is # no limit to the length of command line arguments. # Libtool will interpret -1 as no limit whatsoever lt_cv_sys_max_cmd_len=-1; ;; cygwin* | mingw* | cegcc*) # On Win9x/ME, this test blows up -- it succeeds, but takes # about 5 minutes as the teststring grows exponentially. # Worse, since 9x/ME are not pre-emptively multitasking, # you end up with a "frozen" computer, even though with patience # the test eventually succeeds (with a max line length of 256k). # Instead, let's just punt: use the minimum linelength reported by # all of the supported platforms: 8192 (on NT/2K/XP). lt_cv_sys_max_cmd_len=8192; ;; mint*) # On MiNT this can take a long time and run out of memory. lt_cv_sys_max_cmd_len=8192; ;; amigaos*) # On AmigaOS with pdksh, this test takes hours, literally. # So we just punt and use a minimum line length of 8192. lt_cv_sys_max_cmd_len=8192; ;; bitrig* | darwin* | dragonfly* | freebsd* | netbsd* | openbsd*) # This has been around since 386BSD, at least. Likely further. if test -x /sbin/sysctl; then lt_cv_sys_max_cmd_len=`/sbin/sysctl -n kern.argmax` elif test -x /usr/sbin/sysctl; then lt_cv_sys_max_cmd_len=`/usr/sbin/sysctl -n kern.argmax` else lt_cv_sys_max_cmd_len=65536 # usable default for all BSDs fi # And add a safety zone lt_cv_sys_max_cmd_len=`expr $lt_cv_sys_max_cmd_len \/ 4` lt_cv_sys_max_cmd_len=`expr $lt_cv_sys_max_cmd_len \* 3` ;; interix*) # We know the value 262144 and hardcode it with a safety zone (like BSD) lt_cv_sys_max_cmd_len=196608 ;; os2*) # The test takes a long time on OS/2. lt_cv_sys_max_cmd_len=8192 ;; osf*) # Dr. Hans Ekkehard Plesser reports seeing a kernel panic running configure # due to this test when exec_disable_arg_limit is 1 on Tru64. It is not # nice to cause kernel panics so lets avoid the loop below. # First set a reasonable default. lt_cv_sys_max_cmd_len=16384 # if test -x /sbin/sysconfig; then case `/sbin/sysconfig -q proc exec_disable_arg_limit` in *1*) lt_cv_sys_max_cmd_len=-1 ;; esac fi ;; sco3.2v5*) lt_cv_sys_max_cmd_len=102400 ;; sysv5* | sco5v6* | sysv4.2uw2*) kargmax=`grep ARG_MAX /etc/conf/cf.d/stune 2>/dev/null` if test -n "$kargmax"; then lt_cv_sys_max_cmd_len=`echo $kargmax | sed 's/.*[ ]//'` else lt_cv_sys_max_cmd_len=32768 fi ;; *) lt_cv_sys_max_cmd_len=`(getconf ARG_MAX) 2> /dev/null` if test -n "$lt_cv_sys_max_cmd_len" && \ test undefined != "$lt_cv_sys_max_cmd_len"; then lt_cv_sys_max_cmd_len=`expr $lt_cv_sys_max_cmd_len \/ 4` lt_cv_sys_max_cmd_len=`expr $lt_cv_sys_max_cmd_len \* 3` else # Make teststring a little bigger before we do anything with it. # a 1K string should be a reasonable start. for i in 1 2 3 4 5 6 7 8; do teststring=$teststring$teststring done SHELL=${SHELL-${CONFIG_SHELL-/bin/sh}} # If test is not a shell built-in, we'll probably end up computing a # maximum length that is only half of the actual maximum length, but # we can't tell. while { test X`env echo "$teststring$teststring" 2>/dev/null` \ = "X$teststring$teststring"; } >/dev/null 2>&1 && test 17 != "$i" # 1/2 MB should be enough do i=`expr $i + 1` teststring=$teststring$teststring done # Only check the string length outside the loop. lt_cv_sys_max_cmd_len=`expr "X$teststring" : ".*" 2>&1` teststring= # Add a significant safety factor because C++ compilers can tack on # massive amounts of additional arguments before passing them to the # linker. It appears as though 1/2 is a usable value. lt_cv_sys_max_cmd_len=`expr $lt_cv_sys_max_cmd_len \/ 2` fi ;; esac fi if test -n "$lt_cv_sys_max_cmd_len"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_sys_max_cmd_len" >&5 $as_echo "$lt_cv_sys_max_cmd_len" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: none" >&5 $as_echo "none" >&6; } fi max_cmd_len=$lt_cv_sys_max_cmd_len : ${CP="cp -f"} : ${MV="mv -f"} : ${RM="rm -f"} if ( (MAIL=60; unset MAIL) || exit) >/dev/null 2>&1; then lt_unset=unset else lt_unset=false fi # test EBCDIC or ASCII case `echo X|tr X '\101'` in A) # ASCII based system # \n is not interpreted correctly by Solaris 8 /usr/ucb/tr lt_SP2NL='tr \040 \012' lt_NL2SP='tr \015\012 \040\040' ;; *) # EBCDIC based system lt_SP2NL='tr \100 \n' lt_NL2SP='tr \r\n \100\100' ;; esac { $as_echo "$as_me:${as_lineno-$LINENO}: checking how to convert $build file names to $host format" >&5 $as_echo_n "checking how to convert $build file names to $host format... " >&6; } if ${lt_cv_to_host_file_cmd+:} false; then : $as_echo_n "(cached) " >&6 else case $host in *-*-mingw* ) case $build in *-*-mingw* ) # actually msys lt_cv_to_host_file_cmd=func_convert_file_msys_to_w32 ;; *-*-cygwin* ) lt_cv_to_host_file_cmd=func_convert_file_cygwin_to_w32 ;; * ) # otherwise, assume *nix lt_cv_to_host_file_cmd=func_convert_file_nix_to_w32 ;; esac ;; *-*-cygwin* ) case $build in *-*-mingw* ) # actually msys lt_cv_to_host_file_cmd=func_convert_file_msys_to_cygwin ;; *-*-cygwin* ) lt_cv_to_host_file_cmd=func_convert_file_noop ;; * ) # otherwise, assume *nix lt_cv_to_host_file_cmd=func_convert_file_nix_to_cygwin ;; esac ;; * ) # unhandled hosts (and "normal" native builds) lt_cv_to_host_file_cmd=func_convert_file_noop ;; esac fi to_host_file_cmd=$lt_cv_to_host_file_cmd { $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_to_host_file_cmd" >&5 $as_echo "$lt_cv_to_host_file_cmd" >&6; } { $as_echo "$as_me:${as_lineno-$LINENO}: checking how to convert $build file names to toolchain format" >&5 $as_echo_n "checking how to convert $build file names to toolchain format... " >&6; } if ${lt_cv_to_tool_file_cmd+:} false; then : $as_echo_n "(cached) " >&6 else #assume ordinary cross tools, or native build. lt_cv_to_tool_file_cmd=func_convert_file_noop case $host in *-*-mingw* ) case $build in *-*-mingw* ) # actually msys lt_cv_to_tool_file_cmd=func_convert_file_msys_to_w32 ;; esac ;; esac fi to_tool_file_cmd=$lt_cv_to_tool_file_cmd { $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_to_tool_file_cmd" >&5 $as_echo "$lt_cv_to_tool_file_cmd" >&6; } { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $LD option to reload object files" >&5 $as_echo_n "checking for $LD option to reload object files... " >&6; } if ${lt_cv_ld_reload_flag+:} false; then : $as_echo_n "(cached) " >&6 else lt_cv_ld_reload_flag='-r' fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_ld_reload_flag" >&5 $as_echo "$lt_cv_ld_reload_flag" >&6; } reload_flag=$lt_cv_ld_reload_flag case $reload_flag in "" | " "*) ;; *) reload_flag=" $reload_flag" ;; esac reload_cmds='$LD$reload_flag -o $output$reload_objs' case $host_os in cygwin* | mingw* | pw32* | cegcc*) if test yes != "$GCC"; then reload_cmds=false fi ;; darwin*) if test yes = "$GCC"; then reload_cmds='$LTCC $LTCFLAGS -nostdlib $wl-r -o $output$reload_objs' else reload_cmds='$LD$reload_flag -o $output$reload_objs' fi ;; esac if test -n "$ac_tool_prefix"; then # Extract the first word of "${ac_tool_prefix}objdump", so it can be a program name with args. set dummy ${ac_tool_prefix}objdump; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if ${ac_cv_prog_OBJDUMP+:} false; then : $as_echo_n "(cached) " >&6 else if test -n "$OBJDUMP"; then ac_cv_prog_OBJDUMP="$OBJDUMP" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then ac_cv_prog_OBJDUMP="${ac_tool_prefix}objdump" $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi fi OBJDUMP=$ac_cv_prog_OBJDUMP if test -n "$OBJDUMP"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $OBJDUMP" >&5 $as_echo "$OBJDUMP" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi fi if test -z "$ac_cv_prog_OBJDUMP"; then ac_ct_OBJDUMP=$OBJDUMP # Extract the first word of "objdump", so it can be a program name with args. set dummy objdump; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if ${ac_cv_prog_ac_ct_OBJDUMP+:} false; then : $as_echo_n "(cached) " >&6 else if test -n "$ac_ct_OBJDUMP"; then ac_cv_prog_ac_ct_OBJDUMP="$ac_ct_OBJDUMP" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then ac_cv_prog_ac_ct_OBJDUMP="objdump" $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi fi ac_ct_OBJDUMP=$ac_cv_prog_ac_ct_OBJDUMP if test -n "$ac_ct_OBJDUMP"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_ct_OBJDUMP" >&5 $as_echo "$ac_ct_OBJDUMP" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi if test "x$ac_ct_OBJDUMP" = x; then OBJDUMP="false" else case $cross_compiling:$ac_tool_warned in yes:) { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5 $as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} ac_tool_warned=yes ;; esac OBJDUMP=$ac_ct_OBJDUMP fi else OBJDUMP="$ac_cv_prog_OBJDUMP" fi test -z "$OBJDUMP" && OBJDUMP=objdump { $as_echo "$as_me:${as_lineno-$LINENO}: checking how to recognize dependent libraries" >&5 $as_echo_n "checking how to recognize dependent libraries... " >&6; } if ${lt_cv_deplibs_check_method+:} false; then : $as_echo_n "(cached) " >&6 else lt_cv_file_magic_cmd='$MAGIC_CMD' lt_cv_file_magic_test_file= lt_cv_deplibs_check_method='unknown' # Need to set the preceding variable on all platforms that support # interlibrary dependencies. # 'none' -- dependencies not supported. # 'unknown' -- same as none, but documents that we really don't know. # 'pass_all' -- all dependencies passed with no checks. # 'test_compile' -- check by making test program. # 'file_magic [[regex]]' -- check by looking for files in library path # that responds to the $file_magic_cmd with a given extended regex. # If you have 'file' or equivalent on your system and you're not sure # whether 'pass_all' will *always* work, you probably want this one. case $host_os in aix[4-9]*) lt_cv_deplibs_check_method=pass_all ;; beos*) lt_cv_deplibs_check_method=pass_all ;; bsdi[45]*) lt_cv_deplibs_check_method='file_magic ELF [0-9][0-9]*-bit [ML]SB (shared object|dynamic lib)' lt_cv_file_magic_cmd='/usr/bin/file -L' lt_cv_file_magic_test_file=/shlib/libc.so ;; cygwin*) # func_win32_libid is a shell function defined in ltmain.sh lt_cv_deplibs_check_method='file_magic ^x86 archive import|^x86 DLL' lt_cv_file_magic_cmd='func_win32_libid' ;; mingw* | pw32*) # Base MSYS/MinGW do not provide the 'file' command needed by # func_win32_libid shell function, so use a weaker test based on 'objdump', # unless we find 'file', for example because we are cross-compiling. if ( file / ) >/dev/null 2>&1; then lt_cv_deplibs_check_method='file_magic ^x86 archive import|^x86 DLL' lt_cv_file_magic_cmd='func_win32_libid' else # Keep this pattern in sync with the one in func_win32_libid. lt_cv_deplibs_check_method='file_magic file format (pei*-i386(.*architecture: i386)?|pe-arm-wince|pe-x86-64)' lt_cv_file_magic_cmd='$OBJDUMP -f' fi ;; cegcc*) # use the weaker test based on 'objdump'. See mingw*. lt_cv_deplibs_check_method='file_magic file format pe-arm-.*little(.*architecture: arm)?' lt_cv_file_magic_cmd='$OBJDUMP -f' ;; darwin* | rhapsody*) lt_cv_deplibs_check_method=pass_all ;; freebsd* | dragonfly*) if echo __ELF__ | $CC -E - | $GREP __ELF__ > /dev/null; then case $host_cpu in i*86 ) # Not sure whether the presence of OpenBSD here was a mistake. # Let's accept both of them until this is cleared up. lt_cv_deplibs_check_method='file_magic (FreeBSD|OpenBSD|DragonFly)/i[3-9]86 (compact )?demand paged shared library' lt_cv_file_magic_cmd=/usr/bin/file lt_cv_file_magic_test_file=`echo /usr/lib/libc.so.*` ;; esac else lt_cv_deplibs_check_method=pass_all fi ;; haiku*) lt_cv_deplibs_check_method=pass_all ;; hpux10.20* | hpux11*) lt_cv_file_magic_cmd=/usr/bin/file case $host_cpu in ia64*) lt_cv_deplibs_check_method='file_magic (s[0-9][0-9][0-9]|ELF-[0-9][0-9]) shared object file - IA64' lt_cv_file_magic_test_file=/usr/lib/hpux32/libc.so ;; hppa*64*) lt_cv_deplibs_check_method='file_magic (s[0-9][0-9][0-9]|ELF[ -][0-9][0-9])(-bit)?( [LM]SB)? shared object( file)?[, -]* PA-RISC [0-9]\.[0-9]' lt_cv_file_magic_test_file=/usr/lib/pa20_64/libc.sl ;; *) lt_cv_deplibs_check_method='file_magic (s[0-9][0-9][0-9]|PA-RISC[0-9]\.[0-9]) shared library' lt_cv_file_magic_test_file=/usr/lib/libc.sl ;; esac ;; interix[3-9]*) # PIC code is broken on Interix 3.x, that's why |\.a not |_pic\.a here lt_cv_deplibs_check_method='match_pattern /lib[^/]+(\.so|\.a)$' ;; irix5* | irix6* | nonstopux*) case $LD in *-32|*"-32 ") libmagic=32-bit;; *-n32|*"-n32 ") libmagic=N32;; *-64|*"-64 ") libmagic=64-bit;; *) libmagic=never-match;; esac lt_cv_deplibs_check_method=pass_all ;; # This must be glibc/ELF. linux* | k*bsd*-gnu | kopensolaris*-gnu | gnu*) lt_cv_deplibs_check_method=pass_all ;; netbsd*) if echo __ELF__ | $CC -E - | $GREP __ELF__ > /dev/null; then lt_cv_deplibs_check_method='match_pattern /lib[^/]+(\.so\.[0-9]+\.[0-9]+|_pic\.a)$' else lt_cv_deplibs_check_method='match_pattern /lib[^/]+(\.so|_pic\.a)$' fi ;; newos6*) lt_cv_deplibs_check_method='file_magic ELF [0-9][0-9]*-bit [ML]SB (executable|dynamic lib)' lt_cv_file_magic_cmd=/usr/bin/file lt_cv_file_magic_test_file=/usr/lib/libnls.so ;; *nto* | *qnx*) lt_cv_deplibs_check_method=pass_all ;; openbsd* | bitrig*) if test -z "`echo __ELF__ | $CC -E - | $GREP __ELF__`"; then lt_cv_deplibs_check_method='match_pattern /lib[^/]+(\.so\.[0-9]+\.[0-9]+|\.so|_pic\.a)$' else lt_cv_deplibs_check_method='match_pattern /lib[^/]+(\.so\.[0-9]+\.[0-9]+|_pic\.a)$' fi ;; osf3* | osf4* | osf5*) lt_cv_deplibs_check_method=pass_all ;; rdos*) lt_cv_deplibs_check_method=pass_all ;; solaris*) lt_cv_deplibs_check_method=pass_all ;; sysv5* | sco3.2v5* | sco5v6* | unixware* | OpenUNIX* | sysv4*uw2*) lt_cv_deplibs_check_method=pass_all ;; sysv4 | sysv4.3*) case $host_vendor in motorola) lt_cv_deplibs_check_method='file_magic ELF [0-9][0-9]*-bit [ML]SB (shared object|dynamic lib) M[0-9][0-9]* Version [0-9]' lt_cv_file_magic_test_file=`echo /usr/lib/libc.so*` ;; ncr) lt_cv_deplibs_check_method=pass_all ;; sequent) lt_cv_file_magic_cmd='/bin/file' lt_cv_deplibs_check_method='file_magic ELF [0-9][0-9]*-bit [LM]SB (shared object|dynamic lib )' ;; sni) lt_cv_file_magic_cmd='/bin/file' lt_cv_deplibs_check_method="file_magic ELF [0-9][0-9]*-bit [LM]SB dynamic lib" lt_cv_file_magic_test_file=/lib/libc.so ;; siemens) lt_cv_deplibs_check_method=pass_all ;; pc) lt_cv_deplibs_check_method=pass_all ;; esac ;; tpf*) lt_cv_deplibs_check_method=pass_all ;; os2*) lt_cv_deplibs_check_method=pass_all ;; esac fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_deplibs_check_method" >&5 $as_echo "$lt_cv_deplibs_check_method" >&6; } file_magic_glob= want_nocaseglob=no if test "$build" = "$host"; then case $host_os in mingw* | pw32*) if ( shopt | grep nocaseglob ) >/dev/null 2>&1; then want_nocaseglob=yes else file_magic_glob=`echo aAbBcCdDeEfFgGhHiIjJkKlLmMnNoOpPqQrRsStTuUvVwWxXyYzZ | $SED -e "s/\(..\)/s\/[\1]\/[\1]\/g;/g"` fi ;; esac fi file_magic_cmd=$lt_cv_file_magic_cmd deplibs_check_method=$lt_cv_deplibs_check_method test -z "$deplibs_check_method" && deplibs_check_method=unknown if test -n "$ac_tool_prefix"; then # Extract the first word of "${ac_tool_prefix}dlltool", so it can be a program name with args. set dummy ${ac_tool_prefix}dlltool; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if ${ac_cv_prog_DLLTOOL+:} false; then : $as_echo_n "(cached) " >&6 else if test -n "$DLLTOOL"; then ac_cv_prog_DLLTOOL="$DLLTOOL" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then ac_cv_prog_DLLTOOL="${ac_tool_prefix}dlltool" $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi fi DLLTOOL=$ac_cv_prog_DLLTOOL if test -n "$DLLTOOL"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $DLLTOOL" >&5 $as_echo "$DLLTOOL" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi fi if test -z "$ac_cv_prog_DLLTOOL"; then ac_ct_DLLTOOL=$DLLTOOL # Extract the first word of "dlltool", so it can be a program name with args. set dummy dlltool; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if ${ac_cv_prog_ac_ct_DLLTOOL+:} false; then : $as_echo_n "(cached) " >&6 else if test -n "$ac_ct_DLLTOOL"; then ac_cv_prog_ac_ct_DLLTOOL="$ac_ct_DLLTOOL" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then ac_cv_prog_ac_ct_DLLTOOL="dlltool" $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi fi ac_ct_DLLTOOL=$ac_cv_prog_ac_ct_DLLTOOL if test -n "$ac_ct_DLLTOOL"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_ct_DLLTOOL" >&5 $as_echo "$ac_ct_DLLTOOL" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi if test "x$ac_ct_DLLTOOL" = x; then DLLTOOL="false" else case $cross_compiling:$ac_tool_warned in yes:) { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5 $as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} ac_tool_warned=yes ;; esac DLLTOOL=$ac_ct_DLLTOOL fi else DLLTOOL="$ac_cv_prog_DLLTOOL" fi test -z "$DLLTOOL" && DLLTOOL=dlltool { $as_echo "$as_me:${as_lineno-$LINENO}: checking how to associate runtime and link libraries" >&5 $as_echo_n "checking how to associate runtime and link libraries... " >&6; } if ${lt_cv_sharedlib_from_linklib_cmd+:} false; then : $as_echo_n "(cached) " >&6 else lt_cv_sharedlib_from_linklib_cmd='unknown' case $host_os in cygwin* | mingw* | pw32* | cegcc*) # two different shell functions defined in ltmain.sh; # decide which one to use based on capabilities of $DLLTOOL case `$DLLTOOL --help 2>&1` in *--identify-strict*) lt_cv_sharedlib_from_linklib_cmd=func_cygming_dll_for_implib ;; *) lt_cv_sharedlib_from_linklib_cmd=func_cygming_dll_for_implib_fallback ;; esac ;; *) # fallback: assume linklib IS sharedlib lt_cv_sharedlib_from_linklib_cmd=$ECHO ;; esac fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_sharedlib_from_linklib_cmd" >&5 $as_echo "$lt_cv_sharedlib_from_linklib_cmd" >&6; } sharedlib_from_linklib_cmd=$lt_cv_sharedlib_from_linklib_cmd test -z "$sharedlib_from_linklib_cmd" && sharedlib_from_linklib_cmd=$ECHO if test -n "$ac_tool_prefix"; then for ac_prog in ar do # Extract the first word of "$ac_tool_prefix$ac_prog", so it can be a program name with args. set dummy $ac_tool_prefix$ac_prog; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if ${ac_cv_prog_AR+:} false; then : $as_echo_n "(cached) " >&6 else if test -n "$AR"; then ac_cv_prog_AR="$AR" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then ac_cv_prog_AR="$ac_tool_prefix$ac_prog" $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi fi AR=$ac_cv_prog_AR if test -n "$AR"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $AR" >&5 $as_echo "$AR" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi test -n "$AR" && break done fi if test -z "$AR"; then ac_ct_AR=$AR for ac_prog in ar do # Extract the first word of "$ac_prog", so it can be a program name with args. set dummy $ac_prog; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if ${ac_cv_prog_ac_ct_AR+:} false; then : $as_echo_n "(cached) " >&6 else if test -n "$ac_ct_AR"; then ac_cv_prog_ac_ct_AR="$ac_ct_AR" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then ac_cv_prog_ac_ct_AR="$ac_prog" $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi fi ac_ct_AR=$ac_cv_prog_ac_ct_AR if test -n "$ac_ct_AR"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_ct_AR" >&5 $as_echo "$ac_ct_AR" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi test -n "$ac_ct_AR" && break done if test "x$ac_ct_AR" = x; then AR="false" else case $cross_compiling:$ac_tool_warned in yes:) { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5 $as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} ac_tool_warned=yes ;; esac AR=$ac_ct_AR fi fi : ${AR=ar} : ${AR_FLAGS=cru} { $as_echo "$as_me:${as_lineno-$LINENO}: checking for archiver @FILE support" >&5 $as_echo_n "checking for archiver @FILE support... " >&6; } if ${lt_cv_ar_at_file+:} false; then : $as_echo_n "(cached) " >&6 else lt_cv_ar_at_file=no cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ int main () { ; return 0; } _ACEOF if ac_fn_c_try_compile "$LINENO"; then : echo conftest.$ac_objext > conftest.lst lt_ar_try='$AR $AR_FLAGS libconftest.a @conftest.lst >&5' { { eval echo "\"\$as_me\":${as_lineno-$LINENO}: \"$lt_ar_try\""; } >&5 (eval $lt_ar_try) 2>&5 ac_status=$? $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 test $ac_status = 0; } if test 0 -eq "$ac_status"; then # Ensure the archiver fails upon bogus file names. rm -f conftest.$ac_objext libconftest.a { { eval echo "\"\$as_me\":${as_lineno-$LINENO}: \"$lt_ar_try\""; } >&5 (eval $lt_ar_try) 2>&5 ac_status=$? $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 test $ac_status = 0; } if test 0 -ne "$ac_status"; then lt_cv_ar_at_file=@ fi fi rm -f conftest.* libconftest.a fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_ar_at_file" >&5 $as_echo "$lt_cv_ar_at_file" >&6; } if test no = "$lt_cv_ar_at_file"; then archiver_list_spec= else archiver_list_spec=$lt_cv_ar_at_file fi if test -n "$ac_tool_prefix"; then # Extract the first word of "${ac_tool_prefix}strip", so it can be a program name with args. set dummy ${ac_tool_prefix}strip; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if ${ac_cv_prog_STRIP+:} false; then : $as_echo_n "(cached) " >&6 else if test -n "$STRIP"; then ac_cv_prog_STRIP="$STRIP" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then ac_cv_prog_STRIP="${ac_tool_prefix}strip" $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi fi STRIP=$ac_cv_prog_STRIP if test -n "$STRIP"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $STRIP" >&5 $as_echo "$STRIP" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi fi if test -z "$ac_cv_prog_STRIP"; then ac_ct_STRIP=$STRIP # Extract the first word of "strip", so it can be a program name with args. set dummy strip; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if ${ac_cv_prog_ac_ct_STRIP+:} false; then : $as_echo_n "(cached) " >&6 else if test -n "$ac_ct_STRIP"; then ac_cv_prog_ac_ct_STRIP="$ac_ct_STRIP" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then ac_cv_prog_ac_ct_STRIP="strip" $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi fi ac_ct_STRIP=$ac_cv_prog_ac_ct_STRIP if test -n "$ac_ct_STRIP"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_ct_STRIP" >&5 $as_echo "$ac_ct_STRIP" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi if test "x$ac_ct_STRIP" = x; then STRIP=":" else case $cross_compiling:$ac_tool_warned in yes:) { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5 $as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} ac_tool_warned=yes ;; esac STRIP=$ac_ct_STRIP fi else STRIP="$ac_cv_prog_STRIP" fi test -z "$STRIP" && STRIP=: if test -n "$ac_tool_prefix"; then # Extract the first word of "${ac_tool_prefix}ranlib", so it can be a program name with args. set dummy ${ac_tool_prefix}ranlib; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if ${ac_cv_prog_RANLIB+:} false; then : $as_echo_n "(cached) " >&6 else if test -n "$RANLIB"; then ac_cv_prog_RANLIB="$RANLIB" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then ac_cv_prog_RANLIB="${ac_tool_prefix}ranlib" $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi fi RANLIB=$ac_cv_prog_RANLIB if test -n "$RANLIB"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $RANLIB" >&5 $as_echo "$RANLIB" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi fi if test -z "$ac_cv_prog_RANLIB"; then ac_ct_RANLIB=$RANLIB # Extract the first word of "ranlib", so it can be a program name with args. set dummy ranlib; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if ${ac_cv_prog_ac_ct_RANLIB+:} false; then : $as_echo_n "(cached) " >&6 else if test -n "$ac_ct_RANLIB"; then ac_cv_prog_ac_ct_RANLIB="$ac_ct_RANLIB" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then ac_cv_prog_ac_ct_RANLIB="ranlib" $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi fi ac_ct_RANLIB=$ac_cv_prog_ac_ct_RANLIB if test -n "$ac_ct_RANLIB"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_ct_RANLIB" >&5 $as_echo "$ac_ct_RANLIB" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi if test "x$ac_ct_RANLIB" = x; then RANLIB=":" else case $cross_compiling:$ac_tool_warned in yes:) { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5 $as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} ac_tool_warned=yes ;; esac RANLIB=$ac_ct_RANLIB fi else RANLIB="$ac_cv_prog_RANLIB" fi test -z "$RANLIB" && RANLIB=: # Determine commands to create old-style static archives. old_archive_cmds='$AR $AR_FLAGS $oldlib$oldobjs' old_postinstall_cmds='chmod 644 $oldlib' old_postuninstall_cmds= if test -n "$RANLIB"; then case $host_os in bitrig* | openbsd*) old_postinstall_cmds="$old_postinstall_cmds~\$RANLIB -t \$tool_oldlib" ;; *) old_postinstall_cmds="$old_postinstall_cmds~\$RANLIB \$tool_oldlib" ;; esac old_archive_cmds="$old_archive_cmds~\$RANLIB \$tool_oldlib" fi case $host_os in darwin*) lock_old_archive_extraction=yes ;; *) lock_old_archive_extraction=no ;; esac # If no C compiler was specified, use CC. LTCC=${LTCC-"$CC"} # If no C compiler flags were specified, use CFLAGS. LTCFLAGS=${LTCFLAGS-"$CFLAGS"} # Allow CC to be a program name with arguments. compiler=$CC # Check for command to grab the raw symbol name followed by C symbol from nm. { $as_echo "$as_me:${as_lineno-$LINENO}: checking command to parse $NM output from $compiler object" >&5 $as_echo_n "checking command to parse $NM output from $compiler object... " >&6; } if ${lt_cv_sys_global_symbol_pipe+:} false; then : $as_echo_n "(cached) " >&6 else # These are sane defaults that work on at least a few old systems. # [They come from Ultrix. What could be older than Ultrix?!! ;)] # Character class describing NM global symbol codes. symcode='[BCDEGRST]' # Regexp to match symbols that can be accessed directly from C. sympat='\([_A-Za-z][_A-Za-z0-9]*\)' # Define system-specific variables. case $host_os in aix*) symcode='[BCDT]' ;; cygwin* | mingw* | pw32* | cegcc*) symcode='[ABCDGISTW]' ;; hpux*) if test ia64 = "$host_cpu"; then symcode='[ABCDEGRST]' fi ;; irix* | nonstopux*) symcode='[BCDEGRST]' ;; osf*) symcode='[BCDEGQRST]' ;; solaris*) symcode='[BDRT]' ;; sco3.2v5*) symcode='[DT]' ;; sysv4.2uw2*) symcode='[DT]' ;; sysv5* | sco5v6* | unixware* | OpenUNIX*) symcode='[ABDT]' ;; sysv4) symcode='[DFNSTU]' ;; esac # If we're using GNU nm, then use its standard symbol codes. case `$NM -V 2>&1` in *GNU* | *'with BFD'*) symcode='[ABCDGIRSTW]' ;; esac if test "$lt_cv_nm_interface" = "MS dumpbin"; then # Gets list of data symbols to import. lt_cv_sys_global_symbol_to_import="sed -n -e 's/^I .* \(.*\)$/\1/p'" # Adjust the below global symbol transforms to fixup imported variables. lt_cdecl_hook=" -e 's/^I .* \(.*\)$/extern __declspec(dllimport) char \1;/p'" lt_c_name_hook=" -e 's/^I .* \(.*\)$/ {\"\1\", (void *) 0},/p'" lt_c_name_lib_hook="\ -e 's/^I .* \(lib.*\)$/ {\"\1\", (void *) 0},/p'\ -e 's/^I .* \(.*\)$/ {\"lib\1\", (void *) 0},/p'" else # Disable hooks by default. lt_cv_sys_global_symbol_to_import= lt_cdecl_hook= lt_c_name_hook= lt_c_name_lib_hook= fi # Transform an extracted symbol line into a proper C declaration. # Some systems (esp. on ia64) link data and code symbols differently, # so use this general approach. lt_cv_sys_global_symbol_to_cdecl="sed -n"\ $lt_cdecl_hook\ " -e 's/^T .* \(.*\)$/extern int \1();/p'"\ " -e 's/^$symcode$symcode* .* \(.*\)$/extern char \1;/p'" # Transform an extracted symbol line into symbol name and symbol address lt_cv_sys_global_symbol_to_c_name_address="sed -n"\ $lt_c_name_hook\ " -e 's/^: \(.*\) .*$/ {\"\1\", (void *) 0},/p'"\ " -e 's/^$symcode$symcode* .* \(.*\)$/ {\"\1\", (void *) \&\1},/p'" # Transform an extracted symbol line into symbol name with lib prefix and # symbol address. lt_cv_sys_global_symbol_to_c_name_address_lib_prefix="sed -n"\ $lt_c_name_lib_hook\ " -e 's/^: \(.*\) .*$/ {\"\1\", (void *) 0},/p'"\ " -e 's/^$symcode$symcode* .* \(lib.*\)$/ {\"\1\", (void *) \&\1},/p'"\ " -e 's/^$symcode$symcode* .* \(.*\)$/ {\"lib\1\", (void *) \&\1},/p'" # Handle CRLF in mingw tool chain opt_cr= case $build_os in mingw*) opt_cr=`$ECHO 'x\{0,1\}' | tr x '\015'` # option cr in regexp ;; esac # Try without a prefix underscore, then with it. for ac_symprfx in "" "_"; do # Transform symcode, sympat, and symprfx into a raw symbol and a C symbol. symxfrm="\\1 $ac_symprfx\\2 \\2" # Write the raw and C identifiers. if test "$lt_cv_nm_interface" = "MS dumpbin"; then # Fake it for dumpbin and say T for any non-static function, # D for any global variable and I for any imported variable. # Also find C++ and __fastcall symbols from MSVC++, # which start with @ or ?. lt_cv_sys_global_symbol_pipe="$AWK '"\ " {last_section=section; section=\$ 3};"\ " /^COFF SYMBOL TABLE/{for(i in hide) delete hide[i]};"\ " /Section length .*#relocs.*(pick any)/{hide[last_section]=1};"\ " /^ *Symbol name *: /{split(\$ 0,sn,\":\"); si=substr(sn[2],2)};"\ " /^ *Type *: code/{print \"T\",si,substr(si,length(prfx))};"\ " /^ *Type *: data/{print \"I\",si,substr(si,length(prfx))};"\ " \$ 0!~/External *\|/{next};"\ " / 0+ UNDEF /{next}; / UNDEF \([^|]\)*()/{next};"\ " {if(hide[section]) next};"\ " {f=\"D\"}; \$ 0~/\(\).*\|/{f=\"T\"};"\ " {split(\$ 0,a,/\||\r/); split(a[2],s)};"\ " s[1]~/^[@?]/{print f,s[1],s[1]; next};"\ " s[1]~prfx {split(s[1],t,\"@\"); print f,t[1],substr(t[1],length(prfx))}"\ " ' prfx=^$ac_symprfx" else lt_cv_sys_global_symbol_pipe="sed -n -e 's/^.*[ ]\($symcode$symcode*\)[ ][ ]*$ac_symprfx$sympat$opt_cr$/$symxfrm/p'" fi lt_cv_sys_global_symbol_pipe="$lt_cv_sys_global_symbol_pipe | sed '/ __gnu_lto/d'" # Check to see that the pipe works correctly. pipe_works=no rm -f conftest* cat > conftest.$ac_ext <<_LT_EOF #ifdef __cplusplus extern "C" { #endif char nm_test_var; void nm_test_func(void); void nm_test_func(void){} #ifdef __cplusplus } #endif int main(){nm_test_var='a';nm_test_func();return(0);} _LT_EOF if { { eval echo "\"\$as_me\":${as_lineno-$LINENO}: \"$ac_compile\""; } >&5 (eval $ac_compile) 2>&5 ac_status=$? $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 test $ac_status = 0; }; then # Now try to grab the symbols. nlist=conftest.nm if { { eval echo "\"\$as_me\":${as_lineno-$LINENO}: \"$NM conftest.$ac_objext \| "$lt_cv_sys_global_symbol_pipe" \> $nlist\""; } >&5 (eval $NM conftest.$ac_objext \| "$lt_cv_sys_global_symbol_pipe" \> $nlist) 2>&5 ac_status=$? $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 test $ac_status = 0; } && test -s "$nlist"; then # Try sorting and uniquifying the output. if sort "$nlist" | uniq > "$nlist"T; then mv -f "$nlist"T "$nlist" else rm -f "$nlist"T fi # Make sure that we snagged all the symbols we need. if $GREP ' nm_test_var$' "$nlist" >/dev/null; then if $GREP ' nm_test_func$' "$nlist" >/dev/null; then cat <<_LT_EOF > conftest.$ac_ext /* Keep this code in sync between libtool.m4, ltmain, lt_system.h, and tests. */ #if defined _WIN32 || defined __CYGWIN__ || defined _WIN32_WCE /* DATA imports from DLLs on WIN32 can't be const, because runtime relocations are performed -- see ld's documentation on pseudo-relocs. */ # define LT_DLSYM_CONST #elif defined __osf__ /* This system does not cope well with relocations in const data. */ # define LT_DLSYM_CONST #else # define LT_DLSYM_CONST const #endif #ifdef __cplusplus extern "C" { #endif _LT_EOF # Now generate the symbol file. eval "$lt_cv_sys_global_symbol_to_cdecl"' < "$nlist" | $GREP -v main >> conftest.$ac_ext' cat <<_LT_EOF >> conftest.$ac_ext /* The mapping between symbol names and symbols. */ LT_DLSYM_CONST struct { const char *name; void *address; } lt__PROGRAM__LTX_preloaded_symbols[] = { { "@PROGRAM@", (void *) 0 }, _LT_EOF $SED "s/^$symcode$symcode* .* \(.*\)$/ {\"\1\", (void *) \&\1},/" < "$nlist" | $GREP -v main >> conftest.$ac_ext cat <<\_LT_EOF >> conftest.$ac_ext {0, (void *) 0} }; /* This works around a problem in FreeBSD linker */ #ifdef FREEBSD_WORKAROUND static const void *lt_preloaded_setup() { return lt__PROGRAM__LTX_preloaded_symbols; } #endif #ifdef __cplusplus } #endif _LT_EOF # Now try linking the two files. mv conftest.$ac_objext conftstm.$ac_objext lt_globsym_save_LIBS=$LIBS lt_globsym_save_CFLAGS=$CFLAGS LIBS=conftstm.$ac_objext CFLAGS="$CFLAGS$lt_prog_compiler_no_builtin_flag" if { { eval echo "\"\$as_me\":${as_lineno-$LINENO}: \"$ac_link\""; } >&5 (eval $ac_link) 2>&5 ac_status=$? $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 test $ac_status = 0; } && test -s conftest$ac_exeext; then pipe_works=yes fi LIBS=$lt_globsym_save_LIBS CFLAGS=$lt_globsym_save_CFLAGS else echo "cannot find nm_test_func in $nlist" >&5 fi else echo "cannot find nm_test_var in $nlist" >&5 fi else echo "cannot run $lt_cv_sys_global_symbol_pipe" >&5 fi else echo "$progname: failed program was:" >&5 cat conftest.$ac_ext >&5 fi rm -rf conftest* conftst* # Do not use the global_symbol_pipe unless it works. if test yes = "$pipe_works"; then break else lt_cv_sys_global_symbol_pipe= fi done fi if test -z "$lt_cv_sys_global_symbol_pipe"; then lt_cv_sys_global_symbol_to_cdecl= fi if test -z "$lt_cv_sys_global_symbol_pipe$lt_cv_sys_global_symbol_to_cdecl"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: failed" >&5 $as_echo "failed" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: ok" >&5 $as_echo "ok" >&6; } fi # Response file support. if test "$lt_cv_nm_interface" = "MS dumpbin"; then nm_file_list_spec='@' elif $NM --help 2>/dev/null | grep '[@]FILE' >/dev/null; then nm_file_list_spec='@' fi { $as_echo "$as_me:${as_lineno-$LINENO}: checking for sysroot" >&5 $as_echo_n "checking for sysroot... " >&6; } # Check whether --with-sysroot was given. if test "${with_sysroot+set}" = set; then : withval=$with_sysroot; else with_sysroot=no fi lt_sysroot= case $with_sysroot in #( yes) if test yes = "$GCC"; then lt_sysroot=`$CC --print-sysroot 2>/dev/null` fi ;; #( /*) lt_sysroot=`echo "$with_sysroot" | sed -e "$sed_quote_subst"` ;; #( no|'') ;; #( *) { $as_echo "$as_me:${as_lineno-$LINENO}: result: $with_sysroot" >&5 $as_echo "$with_sysroot" >&6; } as_fn_error $? "The sysroot must be an absolute path." "$LINENO" 5 ;; esac { $as_echo "$as_me:${as_lineno-$LINENO}: result: ${lt_sysroot:-no}" >&5 $as_echo "${lt_sysroot:-no}" >&6; } { $as_echo "$as_me:${as_lineno-$LINENO}: checking for a working dd" >&5 $as_echo_n "checking for a working dd... " >&6; } if ${ac_cv_path_lt_DD+:} false; then : $as_echo_n "(cached) " >&6 else printf 0123456789abcdef0123456789abcdef >conftest.i cat conftest.i conftest.i >conftest2.i : ${lt_DD:=$DD} if test -z "$lt_DD"; then ac_path_lt_DD_found=false # Loop through the user's path and test for each of PROGNAME-LIST as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_prog in dd; do for ac_exec_ext in '' $ac_executable_extensions; do ac_path_lt_DD="$as_dir/$ac_prog$ac_exec_ext" as_fn_executable_p "$ac_path_lt_DD" || continue if "$ac_path_lt_DD" bs=32 count=1 conftest.out 2>/dev/null; then cmp -s conftest.i conftest.out \ && ac_cv_path_lt_DD="$ac_path_lt_DD" ac_path_lt_DD_found=: fi $ac_path_lt_DD_found && break 3 done done done IFS=$as_save_IFS if test -z "$ac_cv_path_lt_DD"; then : fi else ac_cv_path_lt_DD=$lt_DD fi rm -f conftest.i conftest2.i conftest.out fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_path_lt_DD" >&5 $as_echo "$ac_cv_path_lt_DD" >&6; } { $as_echo "$as_me:${as_lineno-$LINENO}: checking how to truncate binary pipes" >&5 $as_echo_n "checking how to truncate binary pipes... " >&6; } if ${lt_cv_truncate_bin+:} false; then : $as_echo_n "(cached) " >&6 else printf 0123456789abcdef0123456789abcdef >conftest.i cat conftest.i conftest.i >conftest2.i lt_cv_truncate_bin= if "$ac_cv_path_lt_DD" bs=32 count=1 conftest.out 2>/dev/null; then cmp -s conftest.i conftest.out \ && lt_cv_truncate_bin="$ac_cv_path_lt_DD bs=4096 count=1" fi rm -f conftest.i conftest2.i conftest.out test -z "$lt_cv_truncate_bin" && lt_cv_truncate_bin="$SED -e 4q" fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_truncate_bin" >&5 $as_echo "$lt_cv_truncate_bin" >&6; } # Calculate cc_basename. Skip known compiler wrappers and cross-prefix. func_cc_basename () { for cc_temp in $*""; do case $cc_temp in compile | *[\\/]compile | ccache | *[\\/]ccache ) ;; distcc | *[\\/]distcc | purify | *[\\/]purify ) ;; \-*) ;; *) break;; esac done func_cc_basename_result=`$ECHO "$cc_temp" | $SED "s%.*/%%; s%^$host_alias-%%"` } # Check whether --enable-libtool-lock was given. if test "${enable_libtool_lock+set}" = set; then : enableval=$enable_libtool_lock; fi test no = "$enable_libtool_lock" || enable_libtool_lock=yes # Some flags need to be propagated to the compiler or linker for good # libtool support. case $host in ia64-*-hpux*) # Find out what ABI is being produced by ac_compile, and set mode # options accordingly. echo 'int i;' > conftest.$ac_ext if { { eval echo "\"\$as_me\":${as_lineno-$LINENO}: \"$ac_compile\""; } >&5 (eval $ac_compile) 2>&5 ac_status=$? $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 test $ac_status = 0; }; then case `/usr/bin/file conftest.$ac_objext` in *ELF-32*) HPUX_IA64_MODE=32 ;; *ELF-64*) HPUX_IA64_MODE=64 ;; esac fi rm -rf conftest* ;; *-*-irix6*) # Find out what ABI is being produced by ac_compile, and set linker # options accordingly. echo '#line '$LINENO' "configure"' > conftest.$ac_ext if { { eval echo "\"\$as_me\":${as_lineno-$LINENO}: \"$ac_compile\""; } >&5 (eval $ac_compile) 2>&5 ac_status=$? $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 test $ac_status = 0; }; then if test yes = "$lt_cv_prog_gnu_ld"; then case `/usr/bin/file conftest.$ac_objext` in *32-bit*) LD="${LD-ld} -melf32bsmip" ;; *N32*) LD="${LD-ld} -melf32bmipn32" ;; *64-bit*) LD="${LD-ld} -melf64bmip" ;; esac else case `/usr/bin/file conftest.$ac_objext` in *32-bit*) LD="${LD-ld} -32" ;; *N32*) LD="${LD-ld} -n32" ;; *64-bit*) LD="${LD-ld} -64" ;; esac fi fi rm -rf conftest* ;; mips64*-*linux*) # Find out what ABI is being produced by ac_compile, and set linker # options accordingly. echo '#line '$LINENO' "configure"' > conftest.$ac_ext if { { eval echo "\"\$as_me\":${as_lineno-$LINENO}: \"$ac_compile\""; } >&5 (eval $ac_compile) 2>&5 ac_status=$? $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 test $ac_status = 0; }; then emul=elf case `/usr/bin/file conftest.$ac_objext` in *32-bit*) emul="${emul}32" ;; *64-bit*) emul="${emul}64" ;; esac case `/usr/bin/file conftest.$ac_objext` in *MSB*) emul="${emul}btsmip" ;; *LSB*) emul="${emul}ltsmip" ;; esac case `/usr/bin/file conftest.$ac_objext` in *N32*) emul="${emul}n32" ;; esac LD="${LD-ld} -m $emul" fi rm -rf conftest* ;; x86_64-*kfreebsd*-gnu|x86_64-*linux*|powerpc*-*linux*| \ s390*-*linux*|s390*-*tpf*|sparc*-*linux*) # Find out what ABI is being produced by ac_compile, and set linker # options accordingly. Note that the listed cases only cover the # situations where additional linker options are needed (such as when # doing 32-bit compilation for a host where ld defaults to 64-bit, or # vice versa); the common cases where no linker options are needed do # not appear in the list. echo 'int i;' > conftest.$ac_ext if { { eval echo "\"\$as_me\":${as_lineno-$LINENO}: \"$ac_compile\""; } >&5 (eval $ac_compile) 2>&5 ac_status=$? $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 test $ac_status = 0; }; then case `/usr/bin/file conftest.o` in *32-bit*) case $host in x86_64-*kfreebsd*-gnu) LD="${LD-ld} -m elf_i386_fbsd" ;; x86_64-*linux*) case `/usr/bin/file conftest.o` in *x86-64*) LD="${LD-ld} -m elf32_x86_64" ;; *) LD="${LD-ld} -m elf_i386" ;; esac ;; powerpc64le-*linux*) LD="${LD-ld} -m elf32lppclinux" ;; powerpc64-*linux*) LD="${LD-ld} -m elf32ppclinux" ;; s390x-*linux*) LD="${LD-ld} -m elf_s390" ;; sparc64-*linux*) LD="${LD-ld} -m elf32_sparc" ;; esac ;; *64-bit*) case $host in x86_64-*kfreebsd*-gnu) LD="${LD-ld} -m elf_x86_64_fbsd" ;; x86_64-*linux*) LD="${LD-ld} -m elf_x86_64" ;; powerpcle-*linux*) LD="${LD-ld} -m elf64lppc" ;; powerpc-*linux*) LD="${LD-ld} -m elf64ppc" ;; s390*-*linux*|s390*-*tpf*) LD="${LD-ld} -m elf64_s390" ;; sparc*-*linux*) LD="${LD-ld} -m elf64_sparc" ;; esac ;; esac fi rm -rf conftest* ;; *-*-sco3.2v5*) # On SCO OpenServer 5, we need -belf to get full-featured binaries. SAVE_CFLAGS=$CFLAGS CFLAGS="$CFLAGS -belf" { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether the C compiler needs -belf" >&5 $as_echo_n "checking whether the C compiler needs -belf... " >&6; } if ${lt_cv_cc_needs_belf+:} false; then : $as_echo_n "(cached) " >&6 else ac_ext=c ac_cpp='$CPP $CPPFLAGS' ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' ac_compiler_gnu=$ac_cv_c_compiler_gnu cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ int main () { ; return 0; } _ACEOF if ac_fn_c_try_link "$LINENO"; then : lt_cv_cc_needs_belf=yes else lt_cv_cc_needs_belf=no fi rm -f core conftest.err conftest.$ac_objext \ conftest$ac_exeext conftest.$ac_ext ac_ext=c ac_cpp='$CPP $CPPFLAGS' ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' ac_compiler_gnu=$ac_cv_c_compiler_gnu fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_cc_needs_belf" >&5 $as_echo "$lt_cv_cc_needs_belf" >&6; } if test yes != "$lt_cv_cc_needs_belf"; then # this is probably gcc 2.8.0, egcs 1.0 or newer; no need for -belf CFLAGS=$SAVE_CFLAGS fi ;; *-*solaris*) # Find out what ABI is being produced by ac_compile, and set linker # options accordingly. echo 'int i;' > conftest.$ac_ext if { { eval echo "\"\$as_me\":${as_lineno-$LINENO}: \"$ac_compile\""; } >&5 (eval $ac_compile) 2>&5 ac_status=$? $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 test $ac_status = 0; }; then case `/usr/bin/file conftest.o` in *64-bit*) case $lt_cv_prog_gnu_ld in yes*) case $host in i?86-*-solaris*|x86_64-*-solaris*) LD="${LD-ld} -m elf_x86_64" ;; sparc*-*-solaris*) LD="${LD-ld} -m elf64_sparc" ;; esac # GNU ld 2.21 introduced _sol2 emulations. Use them if available. if ${LD-ld} -V | grep _sol2 >/dev/null 2>&1; then LD=${LD-ld}_sol2 fi ;; *) if ${LD-ld} -64 -r -o conftest2.o conftest.o >/dev/null 2>&1; then LD="${LD-ld} -64" fi ;; esac ;; esac fi rm -rf conftest* ;; esac need_locks=$enable_libtool_lock if test -n "$ac_tool_prefix"; then # Extract the first word of "${ac_tool_prefix}mt", so it can be a program name with args. set dummy ${ac_tool_prefix}mt; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if ${ac_cv_prog_MANIFEST_TOOL+:} false; then : $as_echo_n "(cached) " >&6 else if test -n "$MANIFEST_TOOL"; then ac_cv_prog_MANIFEST_TOOL="$MANIFEST_TOOL" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then ac_cv_prog_MANIFEST_TOOL="${ac_tool_prefix}mt" $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi fi MANIFEST_TOOL=$ac_cv_prog_MANIFEST_TOOL if test -n "$MANIFEST_TOOL"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $MANIFEST_TOOL" >&5 $as_echo "$MANIFEST_TOOL" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi fi if test -z "$ac_cv_prog_MANIFEST_TOOL"; then ac_ct_MANIFEST_TOOL=$MANIFEST_TOOL # Extract the first word of "mt", so it can be a program name with args. set dummy mt; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if ${ac_cv_prog_ac_ct_MANIFEST_TOOL+:} false; then : $as_echo_n "(cached) " >&6 else if test -n "$ac_ct_MANIFEST_TOOL"; then ac_cv_prog_ac_ct_MANIFEST_TOOL="$ac_ct_MANIFEST_TOOL" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then ac_cv_prog_ac_ct_MANIFEST_TOOL="mt" $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi fi ac_ct_MANIFEST_TOOL=$ac_cv_prog_ac_ct_MANIFEST_TOOL if test -n "$ac_ct_MANIFEST_TOOL"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_ct_MANIFEST_TOOL" >&5 $as_echo "$ac_ct_MANIFEST_TOOL" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi if test "x$ac_ct_MANIFEST_TOOL" = x; then MANIFEST_TOOL=":" else case $cross_compiling:$ac_tool_warned in yes:) { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5 $as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} ac_tool_warned=yes ;; esac MANIFEST_TOOL=$ac_ct_MANIFEST_TOOL fi else MANIFEST_TOOL="$ac_cv_prog_MANIFEST_TOOL" fi test -z "$MANIFEST_TOOL" && MANIFEST_TOOL=mt { $as_echo "$as_me:${as_lineno-$LINENO}: checking if $MANIFEST_TOOL is a manifest tool" >&5 $as_echo_n "checking if $MANIFEST_TOOL is a manifest tool... " >&6; } if ${lt_cv_path_mainfest_tool+:} false; then : $as_echo_n "(cached) " >&6 else lt_cv_path_mainfest_tool=no echo "$as_me:$LINENO: $MANIFEST_TOOL '-?'" >&5 $MANIFEST_TOOL '-?' 2>conftest.err > conftest.out cat conftest.err >&5 if $GREP 'Manifest Tool' conftest.out > /dev/null; then lt_cv_path_mainfest_tool=yes fi rm -f conftest* fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_path_mainfest_tool" >&5 $as_echo "$lt_cv_path_mainfest_tool" >&6; } if test yes != "$lt_cv_path_mainfest_tool"; then MANIFEST_TOOL=: fi case $host_os in rhapsody* | darwin*) if test -n "$ac_tool_prefix"; then # Extract the first word of "${ac_tool_prefix}dsymutil", so it can be a program name with args. set dummy ${ac_tool_prefix}dsymutil; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if ${ac_cv_prog_DSYMUTIL+:} false; then : $as_echo_n "(cached) " >&6 else if test -n "$DSYMUTIL"; then ac_cv_prog_DSYMUTIL="$DSYMUTIL" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then ac_cv_prog_DSYMUTIL="${ac_tool_prefix}dsymutil" $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi fi DSYMUTIL=$ac_cv_prog_DSYMUTIL if test -n "$DSYMUTIL"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $DSYMUTIL" >&5 $as_echo "$DSYMUTIL" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi fi if test -z "$ac_cv_prog_DSYMUTIL"; then ac_ct_DSYMUTIL=$DSYMUTIL # Extract the first word of "dsymutil", so it can be a program name with args. set dummy dsymutil; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if ${ac_cv_prog_ac_ct_DSYMUTIL+:} false; then : $as_echo_n "(cached) " >&6 else if test -n "$ac_ct_DSYMUTIL"; then ac_cv_prog_ac_ct_DSYMUTIL="$ac_ct_DSYMUTIL" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then ac_cv_prog_ac_ct_DSYMUTIL="dsymutil" $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi fi ac_ct_DSYMUTIL=$ac_cv_prog_ac_ct_DSYMUTIL if test -n "$ac_ct_DSYMUTIL"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_ct_DSYMUTIL" >&5 $as_echo "$ac_ct_DSYMUTIL" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi if test "x$ac_ct_DSYMUTIL" = x; then DSYMUTIL=":" else case $cross_compiling:$ac_tool_warned in yes:) { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5 $as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} ac_tool_warned=yes ;; esac DSYMUTIL=$ac_ct_DSYMUTIL fi else DSYMUTIL="$ac_cv_prog_DSYMUTIL" fi if test -n "$ac_tool_prefix"; then # Extract the first word of "${ac_tool_prefix}nmedit", so it can be a program name with args. set dummy ${ac_tool_prefix}nmedit; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if ${ac_cv_prog_NMEDIT+:} false; then : $as_echo_n "(cached) " >&6 else if test -n "$NMEDIT"; then ac_cv_prog_NMEDIT="$NMEDIT" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then ac_cv_prog_NMEDIT="${ac_tool_prefix}nmedit" $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi fi NMEDIT=$ac_cv_prog_NMEDIT if test -n "$NMEDIT"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $NMEDIT" >&5 $as_echo "$NMEDIT" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi fi if test -z "$ac_cv_prog_NMEDIT"; then ac_ct_NMEDIT=$NMEDIT # Extract the first word of "nmedit", so it can be a program name with args. set dummy nmedit; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if ${ac_cv_prog_ac_ct_NMEDIT+:} false; then : $as_echo_n "(cached) " >&6 else if test -n "$ac_ct_NMEDIT"; then ac_cv_prog_ac_ct_NMEDIT="$ac_ct_NMEDIT" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then ac_cv_prog_ac_ct_NMEDIT="nmedit" $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi fi ac_ct_NMEDIT=$ac_cv_prog_ac_ct_NMEDIT if test -n "$ac_ct_NMEDIT"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_ct_NMEDIT" >&5 $as_echo "$ac_ct_NMEDIT" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi if test "x$ac_ct_NMEDIT" = x; then NMEDIT=":" else case $cross_compiling:$ac_tool_warned in yes:) { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5 $as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} ac_tool_warned=yes ;; esac NMEDIT=$ac_ct_NMEDIT fi else NMEDIT="$ac_cv_prog_NMEDIT" fi if test -n "$ac_tool_prefix"; then # Extract the first word of "${ac_tool_prefix}lipo", so it can be a program name with args. set dummy ${ac_tool_prefix}lipo; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if ${ac_cv_prog_LIPO+:} false; then : $as_echo_n "(cached) " >&6 else if test -n "$LIPO"; then ac_cv_prog_LIPO="$LIPO" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then ac_cv_prog_LIPO="${ac_tool_prefix}lipo" $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi fi LIPO=$ac_cv_prog_LIPO if test -n "$LIPO"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $LIPO" >&5 $as_echo "$LIPO" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi fi if test -z "$ac_cv_prog_LIPO"; then ac_ct_LIPO=$LIPO # Extract the first word of "lipo", so it can be a program name with args. set dummy lipo; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if ${ac_cv_prog_ac_ct_LIPO+:} false; then : $as_echo_n "(cached) " >&6 else if test -n "$ac_ct_LIPO"; then ac_cv_prog_ac_ct_LIPO="$ac_ct_LIPO" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then ac_cv_prog_ac_ct_LIPO="lipo" $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi fi ac_ct_LIPO=$ac_cv_prog_ac_ct_LIPO if test -n "$ac_ct_LIPO"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_ct_LIPO" >&5 $as_echo "$ac_ct_LIPO" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi if test "x$ac_ct_LIPO" = x; then LIPO=":" else case $cross_compiling:$ac_tool_warned in yes:) { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5 $as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} ac_tool_warned=yes ;; esac LIPO=$ac_ct_LIPO fi else LIPO="$ac_cv_prog_LIPO" fi if test -n "$ac_tool_prefix"; then # Extract the first word of "${ac_tool_prefix}otool", so it can be a program name with args. set dummy ${ac_tool_prefix}otool; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if ${ac_cv_prog_OTOOL+:} false; then : $as_echo_n "(cached) " >&6 else if test -n "$OTOOL"; then ac_cv_prog_OTOOL="$OTOOL" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then ac_cv_prog_OTOOL="${ac_tool_prefix}otool" $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi fi OTOOL=$ac_cv_prog_OTOOL if test -n "$OTOOL"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $OTOOL" >&5 $as_echo "$OTOOL" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi fi if test -z "$ac_cv_prog_OTOOL"; then ac_ct_OTOOL=$OTOOL # Extract the first word of "otool", so it can be a program name with args. set dummy otool; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if ${ac_cv_prog_ac_ct_OTOOL+:} false; then : $as_echo_n "(cached) " >&6 else if test -n "$ac_ct_OTOOL"; then ac_cv_prog_ac_ct_OTOOL="$ac_ct_OTOOL" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then ac_cv_prog_ac_ct_OTOOL="otool" $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi fi ac_ct_OTOOL=$ac_cv_prog_ac_ct_OTOOL if test -n "$ac_ct_OTOOL"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_ct_OTOOL" >&5 $as_echo "$ac_ct_OTOOL" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi if test "x$ac_ct_OTOOL" = x; then OTOOL=":" else case $cross_compiling:$ac_tool_warned in yes:) { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5 $as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} ac_tool_warned=yes ;; esac OTOOL=$ac_ct_OTOOL fi else OTOOL="$ac_cv_prog_OTOOL" fi if test -n "$ac_tool_prefix"; then # Extract the first word of "${ac_tool_prefix}otool64", so it can be a program name with args. set dummy ${ac_tool_prefix}otool64; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if ${ac_cv_prog_OTOOL64+:} false; then : $as_echo_n "(cached) " >&6 else if test -n "$OTOOL64"; then ac_cv_prog_OTOOL64="$OTOOL64" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then ac_cv_prog_OTOOL64="${ac_tool_prefix}otool64" $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi fi OTOOL64=$ac_cv_prog_OTOOL64 if test -n "$OTOOL64"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $OTOOL64" >&5 $as_echo "$OTOOL64" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi fi if test -z "$ac_cv_prog_OTOOL64"; then ac_ct_OTOOL64=$OTOOL64 # Extract the first word of "otool64", so it can be a program name with args. set dummy otool64; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if ${ac_cv_prog_ac_ct_OTOOL64+:} false; then : $as_echo_n "(cached) " >&6 else if test -n "$ac_ct_OTOOL64"; then ac_cv_prog_ac_ct_OTOOL64="$ac_ct_OTOOL64" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then ac_cv_prog_ac_ct_OTOOL64="otool64" $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi fi ac_ct_OTOOL64=$ac_cv_prog_ac_ct_OTOOL64 if test -n "$ac_ct_OTOOL64"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_ct_OTOOL64" >&5 $as_echo "$ac_ct_OTOOL64" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi if test "x$ac_ct_OTOOL64" = x; then OTOOL64=":" else case $cross_compiling:$ac_tool_warned in yes:) { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5 $as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} ac_tool_warned=yes ;; esac OTOOL64=$ac_ct_OTOOL64 fi else OTOOL64="$ac_cv_prog_OTOOL64" fi { $as_echo "$as_me:${as_lineno-$LINENO}: checking for -single_module linker flag" >&5 $as_echo_n "checking for -single_module linker flag... " >&6; } if ${lt_cv_apple_cc_single_mod+:} false; then : $as_echo_n "(cached) " >&6 else lt_cv_apple_cc_single_mod=no if test -z "$LT_MULTI_MODULE"; then # By default we will add the -single_module flag. You can override # by either setting the environment variable LT_MULTI_MODULE # non-empty at configure time, or by adding -multi_module to the # link flags. rm -rf libconftest.dylib* echo "int foo(void){return 1;}" > conftest.c echo "$LTCC $LTCFLAGS $LDFLAGS -o libconftest.dylib \ -dynamiclib -Wl,-single_module conftest.c" >&5 $LTCC $LTCFLAGS $LDFLAGS -o libconftest.dylib \ -dynamiclib -Wl,-single_module conftest.c 2>conftest.err _lt_result=$? # If there is a non-empty error log, and "single_module" # appears in it, assume the flag caused a linker warning if test -s conftest.err && $GREP single_module conftest.err; then cat conftest.err >&5 # Otherwise, if the output was created with a 0 exit code from # the compiler, it worked. elif test -f libconftest.dylib && test 0 = "$_lt_result"; then lt_cv_apple_cc_single_mod=yes else cat conftest.err >&5 fi rm -rf libconftest.dylib* rm -f conftest.* fi fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_apple_cc_single_mod" >&5 $as_echo "$lt_cv_apple_cc_single_mod" >&6; } { $as_echo "$as_me:${as_lineno-$LINENO}: checking for -exported_symbols_list linker flag" >&5 $as_echo_n "checking for -exported_symbols_list linker flag... " >&6; } if ${lt_cv_ld_exported_symbols_list+:} false; then : $as_echo_n "(cached) " >&6 else lt_cv_ld_exported_symbols_list=no save_LDFLAGS=$LDFLAGS echo "_main" > conftest.sym LDFLAGS="$LDFLAGS -Wl,-exported_symbols_list,conftest.sym" cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ int main () { ; return 0; } _ACEOF if ac_fn_c_try_link "$LINENO"; then : lt_cv_ld_exported_symbols_list=yes else lt_cv_ld_exported_symbols_list=no fi rm -f core conftest.err conftest.$ac_objext \ conftest$ac_exeext conftest.$ac_ext LDFLAGS=$save_LDFLAGS fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_ld_exported_symbols_list" >&5 $as_echo "$lt_cv_ld_exported_symbols_list" >&6; } { $as_echo "$as_me:${as_lineno-$LINENO}: checking for -force_load linker flag" >&5 $as_echo_n "checking for -force_load linker flag... " >&6; } if ${lt_cv_ld_force_load+:} false; then : $as_echo_n "(cached) " >&6 else lt_cv_ld_force_load=no cat > conftest.c << _LT_EOF int forced_loaded() { return 2;} _LT_EOF echo "$LTCC $LTCFLAGS -c -o conftest.o conftest.c" >&5 $LTCC $LTCFLAGS -c -o conftest.o conftest.c 2>&5 echo "$AR cru libconftest.a conftest.o" >&5 $AR cru libconftest.a conftest.o 2>&5 echo "$RANLIB libconftest.a" >&5 $RANLIB libconftest.a 2>&5 cat > conftest.c << _LT_EOF int main() { return 0;} _LT_EOF echo "$LTCC $LTCFLAGS $LDFLAGS -o conftest conftest.c -Wl,-force_load,./libconftest.a" >&5 $LTCC $LTCFLAGS $LDFLAGS -o conftest conftest.c -Wl,-force_load,./libconftest.a 2>conftest.err _lt_result=$? if test -s conftest.err && $GREP force_load conftest.err; then cat conftest.err >&5 elif test -f conftest && test 0 = "$_lt_result" && $GREP forced_load conftest >/dev/null 2>&1; then lt_cv_ld_force_load=yes else cat conftest.err >&5 fi rm -f conftest.err libconftest.a conftest conftest.c rm -rf conftest.dSYM fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_ld_force_load" >&5 $as_echo "$lt_cv_ld_force_load" >&6; } case $host_os in rhapsody* | darwin1.[012]) _lt_dar_allow_undefined='$wl-undefined ${wl}suppress' ;; darwin1.*) _lt_dar_allow_undefined='$wl-flat_namespace $wl-undefined ${wl}suppress' ;; darwin*) # darwin 5.x on # if running on 10.5 or later, the deployment target defaults # to the OS version, if on x86, and 10.4, the deployment # target defaults to 10.4. Don't you love it? case ${MACOSX_DEPLOYMENT_TARGET-10.0},$host in 10.0,*86*-darwin8*|10.0,*-darwin[91]*) _lt_dar_allow_undefined='$wl-undefined ${wl}dynamic_lookup' ;; 10.[012][,.]*) _lt_dar_allow_undefined='$wl-flat_namespace $wl-undefined ${wl}suppress' ;; 10.*) _lt_dar_allow_undefined='$wl-undefined ${wl}dynamic_lookup' ;; esac ;; esac if test yes = "$lt_cv_apple_cc_single_mod"; then _lt_dar_single_mod='$single_module' fi if test yes = "$lt_cv_ld_exported_symbols_list"; then _lt_dar_export_syms=' $wl-exported_symbols_list,$output_objdir/$libname-symbols.expsym' else _lt_dar_export_syms='~$NMEDIT -s $output_objdir/$libname-symbols.expsym $lib' fi if test : != "$DSYMUTIL" && test no = "$lt_cv_ld_force_load"; then _lt_dsymutil='~$DSYMUTIL $lib || :' else _lt_dsymutil= fi ;; esac # func_munge_path_list VARIABLE PATH # ----------------------------------- # VARIABLE is name of variable containing _space_ separated list of # directories to be munged by the contents of PATH, which is string # having a format: # "DIR[:DIR]:" # string "DIR[ DIR]" will be prepended to VARIABLE # ":DIR[:DIR]" # string "DIR[ DIR]" will be appended to VARIABLE # "DIRP[:DIRP]::[DIRA:]DIRA" # string "DIRP[ DIRP]" will be prepended to VARIABLE and string # "DIRA[ DIRA]" will be appended to VARIABLE # "DIR[:DIR]" # VARIABLE will be replaced by "DIR[ DIR]" func_munge_path_list () { case x$2 in x) ;; *:) eval $1=\"`$ECHO $2 | $SED 's/:/ /g'` \$$1\" ;; x:*) eval $1=\"\$$1 `$ECHO $2 | $SED 's/:/ /g'`\" ;; *::*) eval $1=\"\$$1\ `$ECHO $2 | $SED -e 's/.*:://' -e 's/:/ /g'`\" eval $1=\"`$ECHO $2 | $SED -e 's/::.*//' -e 's/:/ /g'`\ \$$1\" ;; *) eval $1=\"`$ECHO $2 | $SED 's/:/ /g'`\" ;; esac } for ac_header in dlfcn.h do : ac_fn_c_check_header_compile "$LINENO" "dlfcn.h" "ac_cv_header_dlfcn_h" "$ac_includes_default " if test "x$ac_cv_header_dlfcn_h" = xyes; then : cat >>confdefs.h <<_ACEOF #define HAVE_DLFCN_H 1 _ACEOF fi done # Set options enable_dlopen=no enable_win32_dll=no # Check whether --enable-shared was given. if test "${enable_shared+set}" = set; then : enableval=$enable_shared; p=${PACKAGE-default} case $enableval in yes) enable_shared=yes ;; no) enable_shared=no ;; *) enable_shared=no # Look at the argument we got. We use all the common list separators. lt_save_ifs=$IFS; IFS=$IFS$PATH_SEPARATOR, for pkg in $enableval; do IFS=$lt_save_ifs if test "X$pkg" = "X$p"; then enable_shared=yes fi done IFS=$lt_save_ifs ;; esac else enable_shared=yes fi # Check whether --enable-static was given. if test "${enable_static+set}" = set; then : enableval=$enable_static; p=${PACKAGE-default} case $enableval in yes) enable_static=yes ;; no) enable_static=no ;; *) enable_static=no # Look at the argument we got. We use all the common list separators. lt_save_ifs=$IFS; IFS=$IFS$PATH_SEPARATOR, for pkg in $enableval; do IFS=$lt_save_ifs if test "X$pkg" = "X$p"; then enable_static=yes fi done IFS=$lt_save_ifs ;; esac else enable_static=yes fi # Check whether --with-pic was given. if test "${with_pic+set}" = set; then : withval=$with_pic; lt_p=${PACKAGE-default} case $withval in yes|no) pic_mode=$withval ;; *) pic_mode=default # Look at the argument we got. We use all the common list separators. lt_save_ifs=$IFS; IFS=$IFS$PATH_SEPARATOR, for lt_pkg in $withval; do IFS=$lt_save_ifs if test "X$lt_pkg" = "X$lt_p"; then pic_mode=yes fi done IFS=$lt_save_ifs ;; esac else pic_mode=default fi # Check whether --enable-fast-install was given. if test "${enable_fast_install+set}" = set; then : enableval=$enable_fast_install; p=${PACKAGE-default} case $enableval in yes) enable_fast_install=yes ;; no) enable_fast_install=no ;; *) enable_fast_install=no # Look at the argument we got. We use all the common list separators. lt_save_ifs=$IFS; IFS=$IFS$PATH_SEPARATOR, for pkg in $enableval; do IFS=$lt_save_ifs if test "X$pkg" = "X$p"; then enable_fast_install=yes fi done IFS=$lt_save_ifs ;; esac else enable_fast_install=yes fi shared_archive_member_spec= case $host,$enable_shared in power*-*-aix[5-9]*,yes) { $as_echo "$as_me:${as_lineno-$LINENO}: checking which variant of shared library versioning to provide" >&5 $as_echo_n "checking which variant of shared library versioning to provide... " >&6; } # Check whether --with-aix-soname was given. if test "${with_aix_soname+set}" = set; then : withval=$with_aix_soname; case $withval in aix|svr4|both) ;; *) as_fn_error $? "Unknown argument to --with-aix-soname" "$LINENO" 5 ;; esac lt_cv_with_aix_soname=$with_aix_soname else if ${lt_cv_with_aix_soname+:} false; then : $as_echo_n "(cached) " >&6 else lt_cv_with_aix_soname=aix fi with_aix_soname=$lt_cv_with_aix_soname fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $with_aix_soname" >&5 $as_echo "$with_aix_soname" >&6; } if test aix != "$with_aix_soname"; then # For the AIX way of multilib, we name the shared archive member # based on the bitwidth used, traditionally 'shr.o' or 'shr_64.o', # and 'shr.imp' or 'shr_64.imp', respectively, for the Import File. # Even when GNU compilers ignore OBJECT_MODE but need '-maix64' flag, # the AIX toolchain works better with OBJECT_MODE set (default 32). if test 64 = "${OBJECT_MODE-32}"; then shared_archive_member_spec=shr_64 else shared_archive_member_spec=shr fi fi ;; *) with_aix_soname=aix ;; esac # This can be used to rebuild libtool when needed LIBTOOL_DEPS=$ltmain # Always use our own libtool. LIBTOOL='$(SHELL) $(top_builddir)/libtool' test -z "$LN_S" && LN_S="ln -s" if test -n "${ZSH_VERSION+set}"; then setopt NO_GLOB_SUBST fi { $as_echo "$as_me:${as_lineno-$LINENO}: checking for objdir" >&5 $as_echo_n "checking for objdir... " >&6; } if ${lt_cv_objdir+:} false; then : $as_echo_n "(cached) " >&6 else rm -f .libs 2>/dev/null mkdir .libs 2>/dev/null if test -d .libs; then lt_cv_objdir=.libs else # MS-DOS does not allow filenames that begin with a dot. lt_cv_objdir=_libs fi rmdir .libs 2>/dev/null fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_objdir" >&5 $as_echo "$lt_cv_objdir" >&6; } objdir=$lt_cv_objdir cat >>confdefs.h <<_ACEOF #define LT_OBJDIR "$lt_cv_objdir/" _ACEOF case $host_os in aix3*) # AIX sometimes has problems with the GCC collect2 program. For some # reason, if we set the COLLECT_NAMES environment variable, the problems # vanish in a puff of smoke. if test set != "${COLLECT_NAMES+set}"; then COLLECT_NAMES= export COLLECT_NAMES fi ;; esac # Global variables: ofile=libtool can_build_shared=yes # All known linkers require a '.a' archive for static linking (except MSVC, # which needs '.lib'). libext=a with_gnu_ld=$lt_cv_prog_gnu_ld old_CC=$CC old_CFLAGS=$CFLAGS # Set sane defaults for various variables test -z "$CC" && CC=cc test -z "$LTCC" && LTCC=$CC test -z "$LTCFLAGS" && LTCFLAGS=$CFLAGS test -z "$LD" && LD=ld test -z "$ac_objext" && ac_objext=o func_cc_basename $compiler cc_basename=$func_cc_basename_result # Only perform the check for file, if the check method requires it test -z "$MAGIC_CMD" && MAGIC_CMD=file case $deplibs_check_method in file_magic*) if test "$file_magic_cmd" = '$MAGIC_CMD'; then { $as_echo "$as_me:${as_lineno-$LINENO}: checking for ${ac_tool_prefix}file" >&5 $as_echo_n "checking for ${ac_tool_prefix}file... " >&6; } if ${lt_cv_path_MAGIC_CMD+:} false; then : $as_echo_n "(cached) " >&6 else case $MAGIC_CMD in [\\/*] | ?:[\\/]*) lt_cv_path_MAGIC_CMD=$MAGIC_CMD # Let the user override the test with a path. ;; *) lt_save_MAGIC_CMD=$MAGIC_CMD lt_save_ifs=$IFS; IFS=$PATH_SEPARATOR ac_dummy="/usr/bin$PATH_SEPARATOR$PATH" for ac_dir in $ac_dummy; do IFS=$lt_save_ifs test -z "$ac_dir" && ac_dir=. if test -f "$ac_dir/${ac_tool_prefix}file"; then lt_cv_path_MAGIC_CMD=$ac_dir/"${ac_tool_prefix}file" if test -n "$file_magic_test_file"; then case $deplibs_check_method in "file_magic "*) file_magic_regex=`expr "$deplibs_check_method" : "file_magic \(.*\)"` MAGIC_CMD=$lt_cv_path_MAGIC_CMD if eval $file_magic_cmd \$file_magic_test_file 2> /dev/null | $EGREP "$file_magic_regex" > /dev/null; then : else cat <<_LT_EOF 1>&2 *** Warning: the command libtool uses to detect shared libraries, *** $file_magic_cmd, produces output that libtool cannot recognize. *** The result is that libtool may fail to recognize shared libraries *** as such. This will affect the creation of libtool libraries that *** depend on shared libraries, but programs linked with such libtool *** libraries will work regardless of this problem. Nevertheless, you *** may want to report the problem to your system manager and/or to *** bug-libtool@gnu.org _LT_EOF fi ;; esac fi break fi done IFS=$lt_save_ifs MAGIC_CMD=$lt_save_MAGIC_CMD ;; esac fi MAGIC_CMD=$lt_cv_path_MAGIC_CMD if test -n "$MAGIC_CMD"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $MAGIC_CMD" >&5 $as_echo "$MAGIC_CMD" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi if test -z "$lt_cv_path_MAGIC_CMD"; then if test -n "$ac_tool_prefix"; then { $as_echo "$as_me:${as_lineno-$LINENO}: checking for file" >&5 $as_echo_n "checking for file... " >&6; } if ${lt_cv_path_MAGIC_CMD+:} false; then : $as_echo_n "(cached) " >&6 else case $MAGIC_CMD in [\\/*] | ?:[\\/]*) lt_cv_path_MAGIC_CMD=$MAGIC_CMD # Let the user override the test with a path. ;; *) lt_save_MAGIC_CMD=$MAGIC_CMD lt_save_ifs=$IFS; IFS=$PATH_SEPARATOR ac_dummy="/usr/bin$PATH_SEPARATOR$PATH" for ac_dir in $ac_dummy; do IFS=$lt_save_ifs test -z "$ac_dir" && ac_dir=. if test -f "$ac_dir/file"; then lt_cv_path_MAGIC_CMD=$ac_dir/"file" if test -n "$file_magic_test_file"; then case $deplibs_check_method in "file_magic "*) file_magic_regex=`expr "$deplibs_check_method" : "file_magic \(.*\)"` MAGIC_CMD=$lt_cv_path_MAGIC_CMD if eval $file_magic_cmd \$file_magic_test_file 2> /dev/null | $EGREP "$file_magic_regex" > /dev/null; then : else cat <<_LT_EOF 1>&2 *** Warning: the command libtool uses to detect shared libraries, *** $file_magic_cmd, produces output that libtool cannot recognize. *** The result is that libtool may fail to recognize shared libraries *** as such. This will affect the creation of libtool libraries that *** depend on shared libraries, but programs linked with such libtool *** libraries will work regardless of this problem. Nevertheless, you *** may want to report the problem to your system manager and/or to *** bug-libtool@gnu.org _LT_EOF fi ;; esac fi break fi done IFS=$lt_save_ifs MAGIC_CMD=$lt_save_MAGIC_CMD ;; esac fi MAGIC_CMD=$lt_cv_path_MAGIC_CMD if test -n "$MAGIC_CMD"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $MAGIC_CMD" >&5 $as_echo "$MAGIC_CMD" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi else MAGIC_CMD=: fi fi fi ;; esac # Use C for the default configuration in the libtool script lt_save_CC=$CC ac_ext=c ac_cpp='$CPP $CPPFLAGS' ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' ac_compiler_gnu=$ac_cv_c_compiler_gnu # Source file extension for C test sources. ac_ext=c # Object file extension for compiled C test sources. objext=o objext=$objext # Code to be used in simple compile tests lt_simple_compile_test_code="int some_variable = 0;" # Code to be used in simple link tests lt_simple_link_test_code='int main(){return(0);}' # If no C compiler was specified, use CC. LTCC=${LTCC-"$CC"} # If no C compiler flags were specified, use CFLAGS. LTCFLAGS=${LTCFLAGS-"$CFLAGS"} # Allow CC to be a program name with arguments. compiler=$CC # Save the default compiler, since it gets overwritten when the other # tags are being tested, and _LT_TAGVAR(compiler, []) is a NOP. compiler_DEFAULT=$CC # save warnings/boilerplate of simple test code ac_outfile=conftest.$ac_objext echo "$lt_simple_compile_test_code" >conftest.$ac_ext eval "$ac_compile" 2>&1 >/dev/null | $SED '/^$/d; /^ *+/d' >conftest.err _lt_compiler_boilerplate=`cat conftest.err` $RM conftest* ac_outfile=conftest.$ac_objext echo "$lt_simple_link_test_code" >conftest.$ac_ext eval "$ac_link" 2>&1 >/dev/null | $SED '/^$/d; /^ *+/d' >conftest.err _lt_linker_boilerplate=`cat conftest.err` $RM -r conftest* if test -n "$compiler"; then lt_prog_compiler_no_builtin_flag= if test yes = "$GCC"; then case $cc_basename in nvcc*) lt_prog_compiler_no_builtin_flag=' -Xcompiler -fno-builtin' ;; *) lt_prog_compiler_no_builtin_flag=' -fno-builtin' ;; esac { $as_echo "$as_me:${as_lineno-$LINENO}: checking if $compiler supports -fno-rtti -fno-exceptions" >&5 $as_echo_n "checking if $compiler supports -fno-rtti -fno-exceptions... " >&6; } if ${lt_cv_prog_compiler_rtti_exceptions+:} false; then : $as_echo_n "(cached) " >&6 else lt_cv_prog_compiler_rtti_exceptions=no ac_outfile=conftest.$ac_objext echo "$lt_simple_compile_test_code" > conftest.$ac_ext lt_compiler_flag="-fno-rtti -fno-exceptions" ## exclude from sc_useless_quotes_in_assignment # Insert the option either (1) after the last *FLAGS variable, or # (2) before a word containing "conftest.", or (3) at the end. # Note that $ac_compile itself does not contain backslashes and begins # with a dollar sign (not a hyphen), so the echo should work correctly. # The option is referenced via a variable to avoid confusing sed. lt_compile=`echo "$ac_compile" | $SED \ -e 's:.*FLAGS}\{0,1\} :&$lt_compiler_flag :; t' \ -e 's: [^ ]*conftest\.: $lt_compiler_flag&:; t' \ -e 's:$: $lt_compiler_flag:'` (eval echo "\"\$as_me:$LINENO: $lt_compile\"" >&5) (eval "$lt_compile" 2>conftest.err) ac_status=$? cat conftest.err >&5 echo "$as_me:$LINENO: \$? = $ac_status" >&5 if (exit $ac_status) && test -s "$ac_outfile"; then # The compiler can only warn and ignore the option if not recognized # So say no if there are warnings other than the usual output. $ECHO "$_lt_compiler_boilerplate" | $SED '/^$/d' >conftest.exp $SED '/^$/d; /^ *+/d' conftest.err >conftest.er2 if test ! -s conftest.er2 || diff conftest.exp conftest.er2 >/dev/null; then lt_cv_prog_compiler_rtti_exceptions=yes fi fi $RM conftest* fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_prog_compiler_rtti_exceptions" >&5 $as_echo "$lt_cv_prog_compiler_rtti_exceptions" >&6; } if test yes = "$lt_cv_prog_compiler_rtti_exceptions"; then lt_prog_compiler_no_builtin_flag="$lt_prog_compiler_no_builtin_flag -fno-rtti -fno-exceptions" else : fi fi lt_prog_compiler_wl= lt_prog_compiler_pic= lt_prog_compiler_static= if test yes = "$GCC"; then lt_prog_compiler_wl='-Wl,' lt_prog_compiler_static='-static' case $host_os in aix*) # All AIX code is PIC. if test ia64 = "$host_cpu"; then # AIX 5 now supports IA64 processor lt_prog_compiler_static='-Bstatic' fi lt_prog_compiler_pic='-fPIC' ;; amigaos*) case $host_cpu in powerpc) # see comment about AmigaOS4 .so support lt_prog_compiler_pic='-fPIC' ;; m68k) # FIXME: we need at least 68020 code to build shared libraries, but # adding the '-m68020' flag to GCC prevents building anything better, # like '-m68040'. lt_prog_compiler_pic='-m68020 -resident32 -malways-restore-a4' ;; esac ;; beos* | irix5* | irix6* | nonstopux* | osf3* | osf4* | osf5*) # PIC is the default for these OSes. ;; mingw* | cygwin* | pw32* | os2* | cegcc*) # This hack is so that the source file can tell whether it is being # built for inclusion in a dll (and should export symbols for example). # Although the cygwin gcc ignores -fPIC, still need this for old-style # (--disable-auto-import) libraries lt_prog_compiler_pic='-DDLL_EXPORT' case $host_os in os2*) lt_prog_compiler_static='$wl-static' ;; esac ;; darwin* | rhapsody*) # PIC is the default on this platform # Common symbols not allowed in MH_DYLIB files lt_prog_compiler_pic='-fno-common' ;; haiku*) # PIC is the default for Haiku. # The "-static" flag exists, but is broken. lt_prog_compiler_static= ;; hpux*) # PIC is the default for 64-bit PA HP-UX, but not for 32-bit # PA HP-UX. On IA64 HP-UX, PIC is the default but the pic flag # sets the default TLS model and affects inlining. case $host_cpu in hppa*64*) # +Z the default ;; *) lt_prog_compiler_pic='-fPIC' ;; esac ;; interix[3-9]*) # Interix 3.x gcc -fpic/-fPIC options generate broken code. # Instead, we relocate shared libraries at runtime. ;; msdosdjgpp*) # Just because we use GCC doesn't mean we suddenly get shared libraries # on systems that don't support them. lt_prog_compiler_can_build_shared=no enable_shared=no ;; *nto* | *qnx*) # QNX uses GNU C++, but need to define -shared option too, otherwise # it will coredump. lt_prog_compiler_pic='-fPIC -shared' ;; sysv4*MP*) if test -d /usr/nec; then lt_prog_compiler_pic=-Kconform_pic fi ;; *) lt_prog_compiler_pic='-fPIC' ;; esac case $cc_basename in nvcc*) # Cuda Compiler Driver 2.2 lt_prog_compiler_wl='-Xlinker ' if test -n "$lt_prog_compiler_pic"; then lt_prog_compiler_pic="-Xcompiler $lt_prog_compiler_pic" fi ;; esac else # PORTME Check for flag to pass linker flags through the system compiler. case $host_os in aix*) lt_prog_compiler_wl='-Wl,' if test ia64 = "$host_cpu"; then # AIX 5 now supports IA64 processor lt_prog_compiler_static='-Bstatic' else lt_prog_compiler_static='-bnso -bI:/lib/syscalls.exp' fi ;; darwin* | rhapsody*) # PIC is the default on this platform # Common symbols not allowed in MH_DYLIB files lt_prog_compiler_pic='-fno-common' case $cc_basename in nagfor*) # NAG Fortran compiler lt_prog_compiler_wl='-Wl,-Wl,,' lt_prog_compiler_pic='-PIC' lt_prog_compiler_static='-Bstatic' ;; esac ;; mingw* | cygwin* | pw32* | os2* | cegcc*) # This hack is so that the source file can tell whether it is being # built for inclusion in a dll (and should export symbols for example). lt_prog_compiler_pic='-DDLL_EXPORT' case $host_os in os2*) lt_prog_compiler_static='$wl-static' ;; esac ;; hpux9* | hpux10* | hpux11*) lt_prog_compiler_wl='-Wl,' # PIC is the default for IA64 HP-UX and 64-bit HP-UX, but # not for PA HP-UX. case $host_cpu in hppa*64*|ia64*) # +Z the default ;; *) lt_prog_compiler_pic='+Z' ;; esac # Is there a better lt_prog_compiler_static that works with the bundled CC? lt_prog_compiler_static='$wl-a ${wl}archive' ;; irix5* | irix6* | nonstopux*) lt_prog_compiler_wl='-Wl,' # PIC (with -KPIC) is the default. lt_prog_compiler_static='-non_shared' ;; linux* | k*bsd*-gnu | kopensolaris*-gnu | gnu*) case $cc_basename in # old Intel for x86_64, which still supported -KPIC. ecc*) lt_prog_compiler_wl='-Wl,' lt_prog_compiler_pic='-KPIC' lt_prog_compiler_static='-static' ;; # icc used to be incompatible with GCC. # ICC 10 doesn't accept -KPIC any more. icc* | ifort*) lt_prog_compiler_wl='-Wl,' lt_prog_compiler_pic='-fPIC' lt_prog_compiler_static='-static' ;; # Lahey Fortran 8.1. lf95*) lt_prog_compiler_wl='-Wl,' lt_prog_compiler_pic='--shared' lt_prog_compiler_static='--static' ;; nagfor*) # NAG Fortran compiler lt_prog_compiler_wl='-Wl,-Wl,,' lt_prog_compiler_pic='-PIC' lt_prog_compiler_static='-Bstatic' ;; tcc*) # Fabrice Bellard et al's Tiny C Compiler lt_prog_compiler_wl='-Wl,' lt_prog_compiler_pic='-fPIC' lt_prog_compiler_static='-static' ;; pgcc* | pgf77* | pgf90* | pgf95* | pgfortran*) # Portland Group compilers (*not* the Pentium gcc compiler, # which looks to be a dead project) lt_prog_compiler_wl='-Wl,' lt_prog_compiler_pic='-fpic' lt_prog_compiler_static='-Bstatic' ;; ccc*) lt_prog_compiler_wl='-Wl,' # All Alpha code is PIC. lt_prog_compiler_static='-non_shared' ;; xl* | bgxl* | bgf* | mpixl*) # IBM XL C 8.0/Fortran 10.1, 11.1 on PPC and BlueGene lt_prog_compiler_wl='-Wl,' lt_prog_compiler_pic='-qpic' lt_prog_compiler_static='-qstaticlink' ;; *) case `$CC -V 2>&1 | sed 5q` in *Sun\ Ceres\ Fortran* | *Sun*Fortran*\ [1-7].* | *Sun*Fortran*\ 8.[0-3]*) # Sun Fortran 8.3 passes all unrecognized flags to the linker lt_prog_compiler_pic='-KPIC' lt_prog_compiler_static='-Bstatic' lt_prog_compiler_wl='' ;; *Sun\ F* | *Sun*Fortran*) lt_prog_compiler_pic='-KPIC' lt_prog_compiler_static='-Bstatic' lt_prog_compiler_wl='-Qoption ld ' ;; *Sun\ C*) # Sun C 5.9 lt_prog_compiler_pic='-KPIC' lt_prog_compiler_static='-Bstatic' lt_prog_compiler_wl='-Wl,' ;; *Intel*\ [CF]*Compiler*) lt_prog_compiler_wl='-Wl,' lt_prog_compiler_pic='-fPIC' lt_prog_compiler_static='-static' ;; *Portland\ Group*) lt_prog_compiler_wl='-Wl,' lt_prog_compiler_pic='-fpic' lt_prog_compiler_static='-Bstatic' ;; esac ;; esac ;; newsos6) lt_prog_compiler_pic='-KPIC' lt_prog_compiler_static='-Bstatic' ;; *nto* | *qnx*) # QNX uses GNU C++, but need to define -shared option too, otherwise # it will coredump. lt_prog_compiler_pic='-fPIC -shared' ;; osf3* | osf4* | osf5*) lt_prog_compiler_wl='-Wl,' # All OSF/1 code is PIC. lt_prog_compiler_static='-non_shared' ;; rdos*) lt_prog_compiler_static='-non_shared' ;; solaris*) lt_prog_compiler_pic='-KPIC' lt_prog_compiler_static='-Bstatic' case $cc_basename in f77* | f90* | f95* | sunf77* | sunf90* | sunf95*) lt_prog_compiler_wl='-Qoption ld ';; *) lt_prog_compiler_wl='-Wl,';; esac ;; sunos4*) lt_prog_compiler_wl='-Qoption ld ' lt_prog_compiler_pic='-PIC' lt_prog_compiler_static='-Bstatic' ;; sysv4 | sysv4.2uw2* | sysv4.3*) lt_prog_compiler_wl='-Wl,' lt_prog_compiler_pic='-KPIC' lt_prog_compiler_static='-Bstatic' ;; sysv4*MP*) if test -d /usr/nec; then lt_prog_compiler_pic='-Kconform_pic' lt_prog_compiler_static='-Bstatic' fi ;; sysv5* | unixware* | sco3.2v5* | sco5v6* | OpenUNIX*) lt_prog_compiler_wl='-Wl,' lt_prog_compiler_pic='-KPIC' lt_prog_compiler_static='-Bstatic' ;; unicos*) lt_prog_compiler_wl='-Wl,' lt_prog_compiler_can_build_shared=no ;; uts4*) lt_prog_compiler_pic='-pic' lt_prog_compiler_static='-Bstatic' ;; *) lt_prog_compiler_can_build_shared=no ;; esac fi case $host_os in # For platforms that do not support PIC, -DPIC is meaningless: *djgpp*) lt_prog_compiler_pic= ;; *) lt_prog_compiler_pic="$lt_prog_compiler_pic -DPIC" ;; esac { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $compiler option to produce PIC" >&5 $as_echo_n "checking for $compiler option to produce PIC... " >&6; } if ${lt_cv_prog_compiler_pic+:} false; then : $as_echo_n "(cached) " >&6 else lt_cv_prog_compiler_pic=$lt_prog_compiler_pic fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_prog_compiler_pic" >&5 $as_echo "$lt_cv_prog_compiler_pic" >&6; } lt_prog_compiler_pic=$lt_cv_prog_compiler_pic # # Check to make sure the PIC flag actually works. # if test -n "$lt_prog_compiler_pic"; then { $as_echo "$as_me:${as_lineno-$LINENO}: checking if $compiler PIC flag $lt_prog_compiler_pic works" >&5 $as_echo_n "checking if $compiler PIC flag $lt_prog_compiler_pic works... " >&6; } if ${lt_cv_prog_compiler_pic_works+:} false; then : $as_echo_n "(cached) " >&6 else lt_cv_prog_compiler_pic_works=no ac_outfile=conftest.$ac_objext echo "$lt_simple_compile_test_code" > conftest.$ac_ext lt_compiler_flag="$lt_prog_compiler_pic -DPIC" ## exclude from sc_useless_quotes_in_assignment # Insert the option either (1) after the last *FLAGS variable, or # (2) before a word containing "conftest.", or (3) at the end. # Note that $ac_compile itself does not contain backslashes and begins # with a dollar sign (not a hyphen), so the echo should work correctly. # The option is referenced via a variable to avoid confusing sed. lt_compile=`echo "$ac_compile" | $SED \ -e 's:.*FLAGS}\{0,1\} :&$lt_compiler_flag :; t' \ -e 's: [^ ]*conftest\.: $lt_compiler_flag&:; t' \ -e 's:$: $lt_compiler_flag:'` (eval echo "\"\$as_me:$LINENO: $lt_compile\"" >&5) (eval "$lt_compile" 2>conftest.err) ac_status=$? cat conftest.err >&5 echo "$as_me:$LINENO: \$? = $ac_status" >&5 if (exit $ac_status) && test -s "$ac_outfile"; then # The compiler can only warn and ignore the option if not recognized # So say no if there are warnings other than the usual output. $ECHO "$_lt_compiler_boilerplate" | $SED '/^$/d' >conftest.exp $SED '/^$/d; /^ *+/d' conftest.err >conftest.er2 if test ! -s conftest.er2 || diff conftest.exp conftest.er2 >/dev/null; then lt_cv_prog_compiler_pic_works=yes fi fi $RM conftest* fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_prog_compiler_pic_works" >&5 $as_echo "$lt_cv_prog_compiler_pic_works" >&6; } if test yes = "$lt_cv_prog_compiler_pic_works"; then case $lt_prog_compiler_pic in "" | " "*) ;; *) lt_prog_compiler_pic=" $lt_prog_compiler_pic" ;; esac else lt_prog_compiler_pic= lt_prog_compiler_can_build_shared=no fi fi # # Check to make sure the static flag actually works. # wl=$lt_prog_compiler_wl eval lt_tmp_static_flag=\"$lt_prog_compiler_static\" { $as_echo "$as_me:${as_lineno-$LINENO}: checking if $compiler static flag $lt_tmp_static_flag works" >&5 $as_echo_n "checking if $compiler static flag $lt_tmp_static_flag works... " >&6; } if ${lt_cv_prog_compiler_static_works+:} false; then : $as_echo_n "(cached) " >&6 else lt_cv_prog_compiler_static_works=no save_LDFLAGS=$LDFLAGS LDFLAGS="$LDFLAGS $lt_tmp_static_flag" echo "$lt_simple_link_test_code" > conftest.$ac_ext if (eval $ac_link 2>conftest.err) && test -s conftest$ac_exeext; then # The linker can only warn and ignore the option if not recognized # So say no if there are warnings if test -s conftest.err; then # Append any errors to the config.log. cat conftest.err 1>&5 $ECHO "$_lt_linker_boilerplate" | $SED '/^$/d' > conftest.exp $SED '/^$/d; /^ *+/d' conftest.err >conftest.er2 if diff conftest.exp conftest.er2 >/dev/null; then lt_cv_prog_compiler_static_works=yes fi else lt_cv_prog_compiler_static_works=yes fi fi $RM -r conftest* LDFLAGS=$save_LDFLAGS fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_prog_compiler_static_works" >&5 $as_echo "$lt_cv_prog_compiler_static_works" >&6; } if test yes = "$lt_cv_prog_compiler_static_works"; then : else lt_prog_compiler_static= fi { $as_echo "$as_me:${as_lineno-$LINENO}: checking if $compiler supports -c -o file.$ac_objext" >&5 $as_echo_n "checking if $compiler supports -c -o file.$ac_objext... " >&6; } if ${lt_cv_prog_compiler_c_o+:} false; then : $as_echo_n "(cached) " >&6 else lt_cv_prog_compiler_c_o=no $RM -r conftest 2>/dev/null mkdir conftest cd conftest mkdir out echo "$lt_simple_compile_test_code" > conftest.$ac_ext lt_compiler_flag="-o out/conftest2.$ac_objext" # Insert the option either (1) after the last *FLAGS variable, or # (2) before a word containing "conftest.", or (3) at the end. # Note that $ac_compile itself does not contain backslashes and begins # with a dollar sign (not a hyphen), so the echo should work correctly. lt_compile=`echo "$ac_compile" | $SED \ -e 's:.*FLAGS}\{0,1\} :&$lt_compiler_flag :; t' \ -e 's: [^ ]*conftest\.: $lt_compiler_flag&:; t' \ -e 's:$: $lt_compiler_flag:'` (eval echo "\"\$as_me:$LINENO: $lt_compile\"" >&5) (eval "$lt_compile" 2>out/conftest.err) ac_status=$? cat out/conftest.err >&5 echo "$as_me:$LINENO: \$? = $ac_status" >&5 if (exit $ac_status) && test -s out/conftest2.$ac_objext then # The compiler can only warn and ignore the option if not recognized # So say no if there are warnings $ECHO "$_lt_compiler_boilerplate" | $SED '/^$/d' > out/conftest.exp $SED '/^$/d; /^ *+/d' out/conftest.err >out/conftest.er2 if test ! -s out/conftest.er2 || diff out/conftest.exp out/conftest.er2 >/dev/null; then lt_cv_prog_compiler_c_o=yes fi fi chmod u+w . 2>&5 $RM conftest* # SGI C++ compiler will create directory out/ii_files/ for # template instantiation test -d out/ii_files && $RM out/ii_files/* && rmdir out/ii_files $RM out/* && rmdir out cd .. $RM -r conftest $RM conftest* fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_prog_compiler_c_o" >&5 $as_echo "$lt_cv_prog_compiler_c_o" >&6; } { $as_echo "$as_me:${as_lineno-$LINENO}: checking if $compiler supports -c -o file.$ac_objext" >&5 $as_echo_n "checking if $compiler supports -c -o file.$ac_objext... " >&6; } if ${lt_cv_prog_compiler_c_o+:} false; then : $as_echo_n "(cached) " >&6 else lt_cv_prog_compiler_c_o=no $RM -r conftest 2>/dev/null mkdir conftest cd conftest mkdir out echo "$lt_simple_compile_test_code" > conftest.$ac_ext lt_compiler_flag="-o out/conftest2.$ac_objext" # Insert the option either (1) after the last *FLAGS variable, or # (2) before a word containing "conftest.", or (3) at the end. # Note that $ac_compile itself does not contain backslashes and begins # with a dollar sign (not a hyphen), so the echo should work correctly. lt_compile=`echo "$ac_compile" | $SED \ -e 's:.*FLAGS}\{0,1\} :&$lt_compiler_flag :; t' \ -e 's: [^ ]*conftest\.: $lt_compiler_flag&:; t' \ -e 's:$: $lt_compiler_flag:'` (eval echo "\"\$as_me:$LINENO: $lt_compile\"" >&5) (eval "$lt_compile" 2>out/conftest.err) ac_status=$? cat out/conftest.err >&5 echo "$as_me:$LINENO: \$? = $ac_status" >&5 if (exit $ac_status) && test -s out/conftest2.$ac_objext then # The compiler can only warn and ignore the option if not recognized # So say no if there are warnings $ECHO "$_lt_compiler_boilerplate" | $SED '/^$/d' > out/conftest.exp $SED '/^$/d; /^ *+/d' out/conftest.err >out/conftest.er2 if test ! -s out/conftest.er2 || diff out/conftest.exp out/conftest.er2 >/dev/null; then lt_cv_prog_compiler_c_o=yes fi fi chmod u+w . 2>&5 $RM conftest* # SGI C++ compiler will create directory out/ii_files/ for # template instantiation test -d out/ii_files && $RM out/ii_files/* && rmdir out/ii_files $RM out/* && rmdir out cd .. $RM -r conftest $RM conftest* fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_prog_compiler_c_o" >&5 $as_echo "$lt_cv_prog_compiler_c_o" >&6; } hard_links=nottested if test no = "$lt_cv_prog_compiler_c_o" && test no != "$need_locks"; then # do not overwrite the value of need_locks provided by the user { $as_echo "$as_me:${as_lineno-$LINENO}: checking if we can lock with hard links" >&5 $as_echo_n "checking if we can lock with hard links... " >&6; } hard_links=yes $RM conftest* ln conftest.a conftest.b 2>/dev/null && hard_links=no touch conftest.a ln conftest.a conftest.b 2>&5 || hard_links=no ln conftest.a conftest.b 2>/dev/null && hard_links=no { $as_echo "$as_me:${as_lineno-$LINENO}: result: $hard_links" >&5 $as_echo "$hard_links" >&6; } if test no = "$hard_links"; then { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: '$CC' does not support '-c -o', so 'make -j' may be unsafe" >&5 $as_echo "$as_me: WARNING: '$CC' does not support '-c -o', so 'make -j' may be unsafe" >&2;} need_locks=warn fi else need_locks=no fi { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether the $compiler linker ($LD) supports shared libraries" >&5 $as_echo_n "checking whether the $compiler linker ($LD) supports shared libraries... " >&6; } runpath_var= allow_undefined_flag= always_export_symbols=no archive_cmds= archive_expsym_cmds= compiler_needs_object=no enable_shared_with_static_runtimes=no export_dynamic_flag_spec= export_symbols_cmds='$NM $libobjs $convenience | $global_symbol_pipe | $SED '\''s/.* //'\'' | sort | uniq > $export_symbols' hardcode_automatic=no hardcode_direct=no hardcode_direct_absolute=no hardcode_libdir_flag_spec= hardcode_libdir_separator= hardcode_minus_L=no hardcode_shlibpath_var=unsupported inherit_rpath=no link_all_deplibs=unknown module_cmds= module_expsym_cmds= old_archive_from_new_cmds= old_archive_from_expsyms_cmds= thread_safe_flag_spec= whole_archive_flag_spec= # include_expsyms should be a list of space-separated symbols to be *always* # included in the symbol list include_expsyms= # exclude_expsyms can be an extended regexp of symbols to exclude # it will be wrapped by ' (' and ')$', so one must not match beginning or # end of line. Example: 'a|bc|.*d.*' will exclude the symbols 'a' and 'bc', # as well as any symbol that contains 'd'. exclude_expsyms='_GLOBAL_OFFSET_TABLE_|_GLOBAL__F[ID]_.*' # Although _GLOBAL_OFFSET_TABLE_ is a valid symbol C name, most a.out # platforms (ab)use it in PIC code, but their linkers get confused if # the symbol is explicitly referenced. Since portable code cannot # rely on this symbol name, it's probably fine to never include it in # preloaded symbol tables. # Exclude shared library initialization/finalization symbols. extract_expsyms_cmds= case $host_os in cygwin* | mingw* | pw32* | cegcc*) # FIXME: the MSVC++ port hasn't been tested in a loooong time # When not using gcc, we currently assume that we are using # Microsoft Visual C++. if test yes != "$GCC"; then with_gnu_ld=no fi ;; interix*) # we just hope/assume this is gcc and not c89 (= MSVC++) with_gnu_ld=yes ;; openbsd* | bitrig*) with_gnu_ld=no ;; esac ld_shlibs=yes # On some targets, GNU ld is compatible enough with the native linker # that we're better off using the native interface for both. lt_use_gnu_ld_interface=no if test yes = "$with_gnu_ld"; then case $host_os in aix*) # The AIX port of GNU ld has always aspired to compatibility # with the native linker. However, as the warning in the GNU ld # block says, versions before 2.19.5* couldn't really create working # shared libraries, regardless of the interface used. case `$LD -v 2>&1` in *\ \(GNU\ Binutils\)\ 2.19.5*) ;; *\ \(GNU\ Binutils\)\ 2.[2-9]*) ;; *\ \(GNU\ Binutils\)\ [3-9]*) ;; *) lt_use_gnu_ld_interface=yes ;; esac ;; *) lt_use_gnu_ld_interface=yes ;; esac fi if test yes = "$lt_use_gnu_ld_interface"; then # If archive_cmds runs LD, not CC, wlarc should be empty wlarc='$wl' # Set some defaults for GNU ld with shared library support. These # are reset later if shared libraries are not supported. Putting them # here allows them to be overridden if necessary. runpath_var=LD_RUN_PATH hardcode_libdir_flag_spec='$wl-rpath $wl$libdir' export_dynamic_flag_spec='$wl--export-dynamic' # ancient GNU ld didn't support --whole-archive et. al. if $LD --help 2>&1 | $GREP 'no-whole-archive' > /dev/null; then whole_archive_flag_spec=$wlarc'--whole-archive$convenience '$wlarc'--no-whole-archive' else whole_archive_flag_spec= fi supports_anon_versioning=no case `$LD -v | $SED -e 's/(^)\+)\s\+//' 2>&1` in *GNU\ gold*) supports_anon_versioning=yes ;; *\ [01].* | *\ 2.[0-9].* | *\ 2.10.*) ;; # catch versions < 2.11 *\ 2.11.93.0.2\ *) supports_anon_versioning=yes ;; # RH7.3 ... *\ 2.11.92.0.12\ *) supports_anon_versioning=yes ;; # Mandrake 8.2 ... *\ 2.11.*) ;; # other 2.11 versions *) supports_anon_versioning=yes ;; esac # See if GNU ld supports shared libraries. case $host_os in aix[3-9]*) # On AIX/PPC, the GNU linker is very broken if test ia64 != "$host_cpu"; then ld_shlibs=no cat <<_LT_EOF 1>&2 *** Warning: the GNU linker, at least up to release 2.19, is reported *** to be unable to reliably create shared libraries on AIX. *** Therefore, libtool is disabling shared libraries support. If you *** really care for shared libraries, you may want to install binutils *** 2.20 or above, or modify your PATH so that a non-GNU linker is found. *** You will then need to restart the configuration process. _LT_EOF fi ;; amigaos*) case $host_cpu in powerpc) # see comment about AmigaOS4 .so support archive_cmds='$CC -shared $libobjs $deplibs $compiler_flags $wl-soname $wl$soname -o $lib' archive_expsym_cmds='' ;; m68k) archive_cmds='$RM $output_objdir/a2ixlibrary.data~$ECHO "#define NAME $libname" > $output_objdir/a2ixlibrary.data~$ECHO "#define LIBRARY_ID 1" >> $output_objdir/a2ixlibrary.data~$ECHO "#define VERSION $major" >> $output_objdir/a2ixlibrary.data~$ECHO "#define REVISION $revision" >> $output_objdir/a2ixlibrary.data~$AR $AR_FLAGS $lib $libobjs~$RANLIB $lib~(cd $output_objdir && a2ixlibrary -32)' hardcode_libdir_flag_spec='-L$libdir' hardcode_minus_L=yes ;; esac ;; beos*) if $LD --help 2>&1 | $GREP ': supported targets:.* elf' > /dev/null; then allow_undefined_flag=unsupported # Joseph Beckenbach says some releases of gcc # support --undefined. This deserves some investigation. FIXME archive_cmds='$CC -nostart $libobjs $deplibs $compiler_flags $wl-soname $wl$soname -o $lib' else ld_shlibs=no fi ;; cygwin* | mingw* | pw32* | cegcc*) # _LT_TAGVAR(hardcode_libdir_flag_spec, ) is actually meaningless, # as there is no search path for DLLs. hardcode_libdir_flag_spec='-L$libdir' export_dynamic_flag_spec='$wl--export-all-symbols' allow_undefined_flag=unsupported always_export_symbols=no enable_shared_with_static_runtimes=yes export_symbols_cmds='$NM $libobjs $convenience | $global_symbol_pipe | $SED -e '\''/^[BCDGRS][ ]/s/.*[ ]\([^ ]*\)/\1 DATA/;s/^.*[ ]__nm__\([^ ]*\)[ ][^ ]*/\1 DATA/;/^I[ ]/d;/^[AITW][ ]/s/.* //'\'' | sort | uniq > $export_symbols' exclude_expsyms='[_]+GLOBAL_OFFSET_TABLE_|[_]+GLOBAL__[FID]_.*|[_]+head_[A-Za-z0-9_]+_dll|[A-Za-z0-9_]+_dll_iname' if $LD --help 2>&1 | $GREP 'auto-import' > /dev/null; then archive_cmds='$CC -shared $libobjs $deplibs $compiler_flags -o $output_objdir/$soname $wl--enable-auto-image-base -Xlinker --out-implib -Xlinker $lib' # If the export-symbols file already is a .def file, use it as # is; otherwise, prepend EXPORTS... archive_expsym_cmds='if test DEF = "`$SED -n -e '\''s/^[ ]*//'\'' -e '\''/^\(;.*\)*$/d'\'' -e '\''s/^\(EXPORTS\|LIBRARY\)\([ ].*\)*$/DEF/p'\'' -e q $export_symbols`" ; then cp $export_symbols $output_objdir/$soname.def; else echo EXPORTS > $output_objdir/$soname.def; cat $export_symbols >> $output_objdir/$soname.def; fi~ $CC -shared $output_objdir/$soname.def $libobjs $deplibs $compiler_flags -o $output_objdir/$soname $wl--enable-auto-image-base -Xlinker --out-implib -Xlinker $lib' else ld_shlibs=no fi ;; haiku*) archive_cmds='$CC -shared $libobjs $deplibs $compiler_flags $wl-soname $wl$soname -o $lib' link_all_deplibs=yes ;; os2*) hardcode_libdir_flag_spec='-L$libdir' hardcode_minus_L=yes allow_undefined_flag=unsupported shrext_cmds=.dll archive_cmds='$ECHO "LIBRARY ${soname%$shared_ext} INITINSTANCE TERMINSTANCE" > $output_objdir/$libname.def~ $ECHO "DESCRIPTION \"$libname\"" >> $output_objdir/$libname.def~ $ECHO "DATA MULTIPLE NONSHARED" >> $output_objdir/$libname.def~ $ECHO EXPORTS >> $output_objdir/$libname.def~ emxexp $libobjs | $SED /"_DLL_InitTerm"/d >> $output_objdir/$libname.def~ $CC -Zdll -Zcrtdll -o $output_objdir/$soname $libobjs $deplibs $compiler_flags $output_objdir/$libname.def~ emximp -o $lib $output_objdir/$libname.def' archive_expsym_cmds='$ECHO "LIBRARY ${soname%$shared_ext} INITINSTANCE TERMINSTANCE" > $output_objdir/$libname.def~ $ECHO "DESCRIPTION \"$libname\"" >> $output_objdir/$libname.def~ $ECHO "DATA MULTIPLE NONSHARED" >> $output_objdir/$libname.def~ $ECHO EXPORTS >> $output_objdir/$libname.def~ prefix_cmds="$SED"~ if test EXPORTS = "`$SED 1q $export_symbols`"; then prefix_cmds="$prefix_cmds -e 1d"; fi~ prefix_cmds="$prefix_cmds -e \"s/^\(.*\)$/_\1/g\""~ cat $export_symbols | $prefix_cmds >> $output_objdir/$libname.def~ $CC -Zdll -Zcrtdll -o $output_objdir/$soname $libobjs $deplibs $compiler_flags $output_objdir/$libname.def~ emximp -o $lib $output_objdir/$libname.def' old_archive_From_new_cmds='emximp -o $output_objdir/${libname}_dll.a $output_objdir/$libname.def' enable_shared_with_static_runtimes=yes ;; interix[3-9]*) hardcode_direct=no hardcode_shlibpath_var=no hardcode_libdir_flag_spec='$wl-rpath,$libdir' export_dynamic_flag_spec='$wl-E' # Hack: On Interix 3.x, we cannot compile PIC because of a broken gcc. # Instead, shared libraries are loaded at an image base (0x10000000 by # default) and relocated if they conflict, which is a slow very memory # consuming and fragmenting process. To avoid this, we pick a random, # 256 KiB-aligned image base between 0x50000000 and 0x6FFC0000 at link # time. Moving up from 0x10000000 also allows more sbrk(2) space. archive_cmds='$CC -shared $pic_flag $libobjs $deplibs $compiler_flags $wl-h,$soname $wl--image-base,`expr ${RANDOM-$$} % 4096 / 2 \* 262144 + 1342177280` -o $lib' archive_expsym_cmds='sed "s|^|_|" $export_symbols >$output_objdir/$soname.expsym~$CC -shared $pic_flag $libobjs $deplibs $compiler_flags $wl-h,$soname $wl--retain-symbols-file,$output_objdir/$soname.expsym $wl--image-base,`expr ${RANDOM-$$} % 4096 / 2 \* 262144 + 1342177280` -o $lib' ;; gnu* | linux* | tpf* | k*bsd*-gnu | kopensolaris*-gnu) tmp_diet=no if test linux-dietlibc = "$host_os"; then case $cc_basename in diet\ *) tmp_diet=yes;; # linux-dietlibc with static linking (!diet-dyn) esac fi if $LD --help 2>&1 | $EGREP ': supported targets:.* elf' > /dev/null \ && test no = "$tmp_diet" then tmp_addflag=' $pic_flag' tmp_sharedflag='-shared' case $cc_basename,$host_cpu in pgcc*) # Portland Group C compiler whole_archive_flag_spec='$wl--whole-archive`for conv in $convenience\"\"; do test -n \"$conv\" && new_convenience=\"$new_convenience,$conv\"; done; func_echo_all \"$new_convenience\"` $wl--no-whole-archive' tmp_addflag=' $pic_flag' ;; pgf77* | pgf90* | pgf95* | pgfortran*) # Portland Group f77 and f90 compilers whole_archive_flag_spec='$wl--whole-archive`for conv in $convenience\"\"; do test -n \"$conv\" && new_convenience=\"$new_convenience,$conv\"; done; func_echo_all \"$new_convenience\"` $wl--no-whole-archive' tmp_addflag=' $pic_flag -Mnomain' ;; ecc*,ia64* | icc*,ia64*) # Intel C compiler on ia64 tmp_addflag=' -i_dynamic' ;; efc*,ia64* | ifort*,ia64*) # Intel Fortran compiler on ia64 tmp_addflag=' -i_dynamic -nofor_main' ;; ifc* | ifort*) # Intel Fortran compiler tmp_addflag=' -nofor_main' ;; lf95*) # Lahey Fortran 8.1 whole_archive_flag_spec= tmp_sharedflag='--shared' ;; nagfor*) # NAGFOR 5.3 tmp_sharedflag='-Wl,-shared' ;; xl[cC]* | bgxl[cC]* | mpixl[cC]*) # IBM XL C 8.0 on PPC (deal with xlf below) tmp_sharedflag='-qmkshrobj' tmp_addflag= ;; nvcc*) # Cuda Compiler Driver 2.2 whole_archive_flag_spec='$wl--whole-archive`for conv in $convenience\"\"; do test -n \"$conv\" && new_convenience=\"$new_convenience,$conv\"; done; func_echo_all \"$new_convenience\"` $wl--no-whole-archive' compiler_needs_object=yes ;; esac case `$CC -V 2>&1 | sed 5q` in *Sun\ C*) # Sun C 5.9 whole_archive_flag_spec='$wl--whole-archive`new_convenience=; for conv in $convenience\"\"; do test -z \"$conv\" || new_convenience=\"$new_convenience,$conv\"; done; func_echo_all \"$new_convenience\"` $wl--no-whole-archive' compiler_needs_object=yes tmp_sharedflag='-G' ;; *Sun\ F*) # Sun Fortran 8.3 tmp_sharedflag='-G' ;; esac archive_cmds='$CC '"$tmp_sharedflag""$tmp_addflag"' $libobjs $deplibs $compiler_flags $wl-soname $wl$soname -o $lib' if test yes = "$supports_anon_versioning"; then archive_expsym_cmds='echo "{ global:" > $output_objdir/$libname.ver~ cat $export_symbols | sed -e "s/\(.*\)/\1;/" >> $output_objdir/$libname.ver~ echo "local: *; };" >> $output_objdir/$libname.ver~ $CC '"$tmp_sharedflag""$tmp_addflag"' $libobjs $deplibs $compiler_flags $wl-soname $wl$soname $wl-version-script $wl$output_objdir/$libname.ver -o $lib' fi case $cc_basename in tcc*) export_dynamic_flag_spec='-rdynamic' ;; xlf* | bgf* | bgxlf* | mpixlf*) # IBM XL Fortran 10.1 on PPC cannot create shared libs itself whole_archive_flag_spec='--whole-archive$convenience --no-whole-archive' hardcode_libdir_flag_spec='$wl-rpath $wl$libdir' archive_cmds='$LD -shared $libobjs $deplibs $linker_flags -soname $soname -o $lib' if test yes = "$supports_anon_versioning"; then archive_expsym_cmds='echo "{ global:" > $output_objdir/$libname.ver~ cat $export_symbols | sed -e "s/\(.*\)/\1;/" >> $output_objdir/$libname.ver~ echo "local: *; };" >> $output_objdir/$libname.ver~ $LD -shared $libobjs $deplibs $linker_flags -soname $soname -version-script $output_objdir/$libname.ver -o $lib' fi ;; esac else ld_shlibs=no fi ;; netbsd*) if echo __ELF__ | $CC -E - | $GREP __ELF__ >/dev/null; then archive_cmds='$LD -Bshareable $libobjs $deplibs $linker_flags -o $lib' wlarc= else archive_cmds='$CC -shared $pic_flag $libobjs $deplibs $compiler_flags $wl-soname $wl$soname -o $lib' archive_expsym_cmds='$CC -shared $pic_flag $libobjs $deplibs $compiler_flags $wl-soname $wl$soname $wl-retain-symbols-file $wl$export_symbols -o $lib' fi ;; solaris*) if $LD -v 2>&1 | $GREP 'BFD 2\.8' > /dev/null; then ld_shlibs=no cat <<_LT_EOF 1>&2 *** Warning: The releases 2.8.* of the GNU linker cannot reliably *** create shared libraries on Solaris systems. Therefore, libtool *** is disabling shared libraries support. We urge you to upgrade GNU *** binutils to release 2.9.1 or newer. Another option is to modify *** your PATH or compiler configuration so that the native linker is *** used, and then restart. _LT_EOF elif $LD --help 2>&1 | $GREP ': supported targets:.* elf' > /dev/null; then archive_cmds='$CC -shared $pic_flag $libobjs $deplibs $compiler_flags $wl-soname $wl$soname -o $lib' archive_expsym_cmds='$CC -shared $pic_flag $libobjs $deplibs $compiler_flags $wl-soname $wl$soname $wl-retain-symbols-file $wl$export_symbols -o $lib' else ld_shlibs=no fi ;; sysv5* | sco3.2v5* | sco5v6* | unixware* | OpenUNIX*) case `$LD -v 2>&1` in *\ [01].* | *\ 2.[0-9].* | *\ 2.1[0-5].*) ld_shlibs=no cat <<_LT_EOF 1>&2 *** Warning: Releases of the GNU linker prior to 2.16.91.0.3 cannot *** reliably create shared libraries on SCO systems. Therefore, libtool *** is disabling shared libraries support. We urge you to upgrade GNU *** binutils to release 2.16.91.0.3 or newer. Another option is to modify *** your PATH or compiler configuration so that the native linker is *** used, and then restart. _LT_EOF ;; *) # For security reasons, it is highly recommended that you always # use absolute paths for naming shared libraries, and exclude the # DT_RUNPATH tag from executables and libraries. But doing so # requires that you compile everything twice, which is a pain. if $LD --help 2>&1 | $GREP ': supported targets:.* elf' > /dev/null; then hardcode_libdir_flag_spec='$wl-rpath $wl$libdir' archive_cmds='$CC -shared $libobjs $deplibs $compiler_flags $wl-soname $wl$soname -o $lib' archive_expsym_cmds='$CC -shared $libobjs $deplibs $compiler_flags $wl-soname $wl$soname $wl-retain-symbols-file $wl$export_symbols -o $lib' else ld_shlibs=no fi ;; esac ;; sunos4*) archive_cmds='$LD -assert pure-text -Bshareable -o $lib $libobjs $deplibs $linker_flags' wlarc= hardcode_direct=yes hardcode_shlibpath_var=no ;; *) if $LD --help 2>&1 | $GREP ': supported targets:.* elf' > /dev/null; then archive_cmds='$CC -shared $pic_flag $libobjs $deplibs $compiler_flags $wl-soname $wl$soname -o $lib' archive_expsym_cmds='$CC -shared $pic_flag $libobjs $deplibs $compiler_flags $wl-soname $wl$soname $wl-retain-symbols-file $wl$export_symbols -o $lib' else ld_shlibs=no fi ;; esac if test no = "$ld_shlibs"; then runpath_var= hardcode_libdir_flag_spec= export_dynamic_flag_spec= whole_archive_flag_spec= fi else # PORTME fill in a description of your system's linker (not GNU ld) case $host_os in aix3*) allow_undefined_flag=unsupported always_export_symbols=yes archive_expsym_cmds='$LD -o $output_objdir/$soname $libobjs $deplibs $linker_flags -bE:$export_symbols -T512 -H512 -bM:SRE~$AR $AR_FLAGS $lib $output_objdir/$soname' # Note: this linker hardcodes the directories in LIBPATH if there # are no directories specified by -L. hardcode_minus_L=yes if test yes = "$GCC" && test -z "$lt_prog_compiler_static"; then # Neither direct hardcoding nor static linking is supported with a # broken collect2. hardcode_direct=unsupported fi ;; aix[4-9]*) if test ia64 = "$host_cpu"; then # On IA64, the linker does run time linking by default, so we don't # have to do anything special. aix_use_runtimelinking=no exp_sym_flag='-Bexport' no_entry_flag= else # If we're using GNU nm, then we don't want the "-C" option. # -C means demangle to GNU nm, but means don't demangle to AIX nm. # Without the "-l" option, or with the "-B" option, AIX nm treats # weak defined symbols like other global defined symbols, whereas # GNU nm marks them as "W". # While the 'weak' keyword is ignored in the Export File, we need # it in the Import File for the 'aix-soname' feature, so we have # to replace the "-B" option with "-P" for AIX nm. if $NM -V 2>&1 | $GREP 'GNU' > /dev/null; then export_symbols_cmds='$NM -Bpg $libobjs $convenience | awk '\''{ if (((\$ 2 == "T") || (\$ 2 == "D") || (\$ 2 == "B") || (\$ 2 == "W")) && (substr(\$ 3,1,1) != ".")) { if (\$ 2 == "W") { print \$ 3 " weak" } else { print \$ 3 } } }'\'' | sort -u > $export_symbols' else export_symbols_cmds='`func_echo_all $NM | $SED -e '\''s/B\([^B]*\)$/P\1/'\''` -PCpgl $libobjs $convenience | awk '\''{ if (((\$ 2 == "T") || (\$ 2 == "D") || (\$ 2 == "B") || (\$ 2 == "W") || (\$ 2 == "V") || (\$ 2 == "Z")) && (substr(\$ 1,1,1) != ".")) { if ((\$ 2 == "W") || (\$ 2 == "V") || (\$ 2 == "Z")) { print \$ 1 " weak" } else { print \$ 1 } } }'\'' | sort -u > $export_symbols' fi aix_use_runtimelinking=no # Test if we are trying to use run time linking or normal # AIX style linking. If -brtl is somewhere in LDFLAGS, we # have runtime linking enabled, and use it for executables. # For shared libraries, we enable/disable runtime linking # depending on the kind of the shared library created - # when "with_aix_soname,aix_use_runtimelinking" is: # "aix,no" lib.a(lib.so.V) shared, rtl:no, for executables # "aix,yes" lib.so shared, rtl:yes, for executables # lib.a static archive # "both,no" lib.so.V(shr.o) shared, rtl:yes # lib.a(lib.so.V) shared, rtl:no, for executables # "both,yes" lib.so.V(shr.o) shared, rtl:yes, for executables # lib.a(lib.so.V) shared, rtl:no # "svr4,*" lib.so.V(shr.o) shared, rtl:yes, for executables # lib.a static archive case $host_os in aix4.[23]|aix4.[23].*|aix[5-9]*) for ld_flag in $LDFLAGS; do if (test x-brtl = "x$ld_flag" || test x-Wl,-brtl = "x$ld_flag"); then aix_use_runtimelinking=yes break fi done if test svr4,no = "$with_aix_soname,$aix_use_runtimelinking"; then # With aix-soname=svr4, we create the lib.so.V shared archives only, # so we don't have lib.a shared libs to link our executables. # We have to force runtime linking in this case. aix_use_runtimelinking=yes LDFLAGS="$LDFLAGS -Wl,-brtl" fi ;; esac exp_sym_flag='-bexport' no_entry_flag='-bnoentry' fi # When large executables or shared objects are built, AIX ld can # have problems creating the table of contents. If linking a library # or program results in "error TOC overflow" add -mminimal-toc to # CXXFLAGS/CFLAGS for g++/gcc. In the cases where that is not # enough to fix the problem, add -Wl,-bbigtoc to LDFLAGS. archive_cmds='' hardcode_direct=yes hardcode_direct_absolute=yes hardcode_libdir_separator=':' link_all_deplibs=yes file_list_spec='$wl-f,' case $with_aix_soname,$aix_use_runtimelinking in aix,*) ;; # traditional, no import file svr4,* | *,yes) # use import file # The Import File defines what to hardcode. hardcode_direct=no hardcode_direct_absolute=no ;; esac if test yes = "$GCC"; then case $host_os in aix4.[012]|aix4.[012].*) # We only want to do this on AIX 4.2 and lower, the check # below for broken collect2 doesn't work under 4.3+ collect2name=`$CC -print-prog-name=collect2` if test -f "$collect2name" && strings "$collect2name" | $GREP resolve_lib_name >/dev/null then # We have reworked collect2 : else # We have old collect2 hardcode_direct=unsupported # It fails to find uninstalled libraries when the uninstalled # path is not listed in the libpath. Setting hardcode_minus_L # to unsupported forces relinking hardcode_minus_L=yes hardcode_libdir_flag_spec='-L$libdir' hardcode_libdir_separator= fi ;; esac shared_flag='-shared' if test yes = "$aix_use_runtimelinking"; then shared_flag="$shared_flag "'$wl-G' fi # Need to ensure runtime linking is disabled for the traditional # shared library, or the linker may eventually find shared libraries # /with/ Import File - we do not want to mix them. shared_flag_aix='-shared' shared_flag_svr4='-shared $wl-G' else # not using gcc if test ia64 = "$host_cpu"; then # VisualAge C++, Version 5.5 for AIX 5L for IA-64, Beta 3 Release # chokes on -Wl,-G. The following line is correct: shared_flag='-G' else if test yes = "$aix_use_runtimelinking"; then shared_flag='$wl-G' else shared_flag='$wl-bM:SRE' fi shared_flag_aix='$wl-bM:SRE' shared_flag_svr4='$wl-G' fi fi export_dynamic_flag_spec='$wl-bexpall' # It seems that -bexpall does not export symbols beginning with # underscore (_), so it is better to generate a list of symbols to export. always_export_symbols=yes if test aix,yes = "$with_aix_soname,$aix_use_runtimelinking"; then # Warning - without using the other runtime loading flags (-brtl), # -berok will link without error, but may produce a broken library. allow_undefined_flag='-berok' # Determine the default libpath from the value encoded in an # empty executable. if test set = "${lt_cv_aix_libpath+set}"; then aix_libpath=$lt_cv_aix_libpath else if ${lt_cv_aix_libpath_+:} false; then : $as_echo_n "(cached) " >&6 else cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ int main () { ; return 0; } _ACEOF if ac_fn_c_try_link "$LINENO"; then : lt_aix_libpath_sed=' /Import File Strings/,/^$/ { /^0/ { s/^0 *\([^ ]*\) *$/\1/ p } }' lt_cv_aix_libpath_=`dump -H conftest$ac_exeext 2>/dev/null | $SED -n -e "$lt_aix_libpath_sed"` # Check for a 64-bit object if we didn't find anything. if test -z "$lt_cv_aix_libpath_"; then lt_cv_aix_libpath_=`dump -HX64 conftest$ac_exeext 2>/dev/null | $SED -n -e "$lt_aix_libpath_sed"` fi fi rm -f core conftest.err conftest.$ac_objext \ conftest$ac_exeext conftest.$ac_ext if test -z "$lt_cv_aix_libpath_"; then lt_cv_aix_libpath_=/usr/lib:/lib fi fi aix_libpath=$lt_cv_aix_libpath_ fi hardcode_libdir_flag_spec='$wl-blibpath:$libdir:'"$aix_libpath" archive_expsym_cmds='$CC -o $output_objdir/$soname $libobjs $deplibs $wl'$no_entry_flag' $compiler_flags `if test -n "$allow_undefined_flag"; then func_echo_all "$wl$allow_undefined_flag"; else :; fi` $wl'$exp_sym_flag:\$export_symbols' '$shared_flag else if test ia64 = "$host_cpu"; then hardcode_libdir_flag_spec='$wl-R $libdir:/usr/lib:/lib' allow_undefined_flag="-z nodefs" archive_expsym_cmds="\$CC $shared_flag"' -o $output_objdir/$soname $libobjs $deplibs '"\$wl$no_entry_flag"' $compiler_flags $wl$allow_undefined_flag '"\$wl$exp_sym_flag:\$export_symbols" else # Determine the default libpath from the value encoded in an # empty executable. if test set = "${lt_cv_aix_libpath+set}"; then aix_libpath=$lt_cv_aix_libpath else if ${lt_cv_aix_libpath_+:} false; then : $as_echo_n "(cached) " >&6 else cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ int main () { ; return 0; } _ACEOF if ac_fn_c_try_link "$LINENO"; then : lt_aix_libpath_sed=' /Import File Strings/,/^$/ { /^0/ { s/^0 *\([^ ]*\) *$/\1/ p } }' lt_cv_aix_libpath_=`dump -H conftest$ac_exeext 2>/dev/null | $SED -n -e "$lt_aix_libpath_sed"` # Check for a 64-bit object if we didn't find anything. if test -z "$lt_cv_aix_libpath_"; then lt_cv_aix_libpath_=`dump -HX64 conftest$ac_exeext 2>/dev/null | $SED -n -e "$lt_aix_libpath_sed"` fi fi rm -f core conftest.err conftest.$ac_objext \ conftest$ac_exeext conftest.$ac_ext if test -z "$lt_cv_aix_libpath_"; then lt_cv_aix_libpath_=/usr/lib:/lib fi fi aix_libpath=$lt_cv_aix_libpath_ fi hardcode_libdir_flag_spec='$wl-blibpath:$libdir:'"$aix_libpath" # Warning - without using the other run time loading flags, # -berok will link without error, but may produce a broken library. no_undefined_flag=' $wl-bernotok' allow_undefined_flag=' $wl-berok' if test yes = "$with_gnu_ld"; then # We only use this code for GNU lds that support --whole-archive. whole_archive_flag_spec='$wl--whole-archive$convenience $wl--no-whole-archive' else # Exported symbols can be pulled into shared objects from archives whole_archive_flag_spec='$convenience' fi archive_cmds_need_lc=yes archive_expsym_cmds='$RM -r $output_objdir/$realname.d~$MKDIR $output_objdir/$realname.d' # -brtl affects multiple linker settings, -berok does not and is overridden later compiler_flags_filtered='`func_echo_all "$compiler_flags " | $SED -e "s%-brtl\\([, ]\\)%-berok\\1%g"`' if test svr4 != "$with_aix_soname"; then # This is similar to how AIX traditionally builds its shared libraries. archive_expsym_cmds="$archive_expsym_cmds"'~$CC '$shared_flag_aix' -o $output_objdir/$realname.d/$soname $libobjs $deplibs $wl-bnoentry '$compiler_flags_filtered'$wl-bE:$export_symbols$allow_undefined_flag~$AR $AR_FLAGS $output_objdir/$libname$release.a $output_objdir/$realname.d/$soname' fi if test aix != "$with_aix_soname"; then archive_expsym_cmds="$archive_expsym_cmds"'~$CC '$shared_flag_svr4' -o $output_objdir/$realname.d/$shared_archive_member_spec.o $libobjs $deplibs $wl-bnoentry '$compiler_flags_filtered'$wl-bE:$export_symbols$allow_undefined_flag~$STRIP -e $output_objdir/$realname.d/$shared_archive_member_spec.o~( func_echo_all "#! $soname($shared_archive_member_spec.o)"; if test shr_64 = "$shared_archive_member_spec"; then func_echo_all "# 64"; else func_echo_all "# 32"; fi; cat $export_symbols ) > $output_objdir/$realname.d/$shared_archive_member_spec.imp~$AR $AR_FLAGS $output_objdir/$soname $output_objdir/$realname.d/$shared_archive_member_spec.o $output_objdir/$realname.d/$shared_archive_member_spec.imp' else # used by -dlpreopen to get the symbols archive_expsym_cmds="$archive_expsym_cmds"'~$MV $output_objdir/$realname.d/$soname $output_objdir' fi archive_expsym_cmds="$archive_expsym_cmds"'~$RM -r $output_objdir/$realname.d' fi fi ;; amigaos*) case $host_cpu in powerpc) # see comment about AmigaOS4 .so support archive_cmds='$CC -shared $libobjs $deplibs $compiler_flags $wl-soname $wl$soname -o $lib' archive_expsym_cmds='' ;; m68k) archive_cmds='$RM $output_objdir/a2ixlibrary.data~$ECHO "#define NAME $libname" > $output_objdir/a2ixlibrary.data~$ECHO "#define LIBRARY_ID 1" >> $output_objdir/a2ixlibrary.data~$ECHO "#define VERSION $major" >> $output_objdir/a2ixlibrary.data~$ECHO "#define REVISION $revision" >> $output_objdir/a2ixlibrary.data~$AR $AR_FLAGS $lib $libobjs~$RANLIB $lib~(cd $output_objdir && a2ixlibrary -32)' hardcode_libdir_flag_spec='-L$libdir' hardcode_minus_L=yes ;; esac ;; bsdi[45]*) export_dynamic_flag_spec=-rdynamic ;; cygwin* | mingw* | pw32* | cegcc*) # When not using gcc, we currently assume that we are using # Microsoft Visual C++. # hardcode_libdir_flag_spec is actually meaningless, as there is # no search path for DLLs. case $cc_basename in cl*) # Native MSVC hardcode_libdir_flag_spec=' ' allow_undefined_flag=unsupported always_export_symbols=yes file_list_spec='@' # Tell ltmain to make .lib files, not .a files. libext=lib # Tell ltmain to make .dll files, not .so files. shrext_cmds=.dll # FIXME: Setting linknames here is a bad hack. archive_cmds='$CC -o $output_objdir/$soname $libobjs $compiler_flags $deplibs -Wl,-DLL,-IMPLIB:"$tool_output_objdir$libname.dll.lib"~linknames=' archive_expsym_cmds='if test DEF = "`$SED -n -e '\''s/^[ ]*//'\'' -e '\''/^\(;.*\)*$/d'\'' -e '\''s/^\(EXPORTS\|LIBRARY\)\([ ].*\)*$/DEF/p'\'' -e q $export_symbols`" ; then cp "$export_symbols" "$output_objdir/$soname.def"; echo "$tool_output_objdir$soname.def" > "$output_objdir/$soname.exp"; else $SED -e '\''s/^/-link -EXPORT:/'\'' < $export_symbols > $output_objdir/$soname.exp; fi~ $CC -o $tool_output_objdir$soname $libobjs $compiler_flags $deplibs "@$tool_output_objdir$soname.exp" -Wl,-DLL,-IMPLIB:"$tool_output_objdir$libname.dll.lib"~ linknames=' # The linker will not automatically build a static lib if we build a DLL. # _LT_TAGVAR(old_archive_from_new_cmds, )='true' enable_shared_with_static_runtimes=yes exclude_expsyms='_NULL_IMPORT_DESCRIPTOR|_IMPORT_DESCRIPTOR_.*' export_symbols_cmds='$NM $libobjs $convenience | $global_symbol_pipe | $SED -e '\''/^[BCDGRS][ ]/s/.*[ ]\([^ ]*\)/\1,DATA/'\'' | $SED -e '\''/^[AITW][ ]/s/.*[ ]//'\'' | sort | uniq > $export_symbols' # Don't use ranlib old_postinstall_cmds='chmod 644 $oldlib' postlink_cmds='lt_outputfile="@OUTPUT@"~ lt_tool_outputfile="@TOOL_OUTPUT@"~ case $lt_outputfile in *.exe|*.EXE) ;; *) lt_outputfile=$lt_outputfile.exe lt_tool_outputfile=$lt_tool_outputfile.exe ;; esac~ if test : != "$MANIFEST_TOOL" && test -f "$lt_outputfile.manifest"; then $MANIFEST_TOOL -manifest "$lt_tool_outputfile.manifest" -outputresource:"$lt_tool_outputfile" || exit 1; $RM "$lt_outputfile.manifest"; fi' ;; *) # Assume MSVC wrapper hardcode_libdir_flag_spec=' ' allow_undefined_flag=unsupported # Tell ltmain to make .lib files, not .a files. libext=lib # Tell ltmain to make .dll files, not .so files. shrext_cmds=.dll # FIXME: Setting linknames here is a bad hack. archive_cmds='$CC -o $lib $libobjs $compiler_flags `func_echo_all "$deplibs" | $SED '\''s/ -lc$//'\''` -link -dll~linknames=' # The linker will automatically build a .lib file if we build a DLL. old_archive_from_new_cmds='true' # FIXME: Should let the user specify the lib program. old_archive_cmds='lib -OUT:$oldlib$oldobjs$old_deplibs' enable_shared_with_static_runtimes=yes ;; esac ;; darwin* | rhapsody*) archive_cmds_need_lc=no hardcode_direct=no hardcode_automatic=yes hardcode_shlibpath_var=unsupported if test yes = "$lt_cv_ld_force_load"; then whole_archive_flag_spec='`for conv in $convenience\"\"; do test -n \"$conv\" && new_convenience=\"$new_convenience $wl-force_load,$conv\"; done; func_echo_all \"$new_convenience\"`' else whole_archive_flag_spec='' fi link_all_deplibs=yes allow_undefined_flag=$_lt_dar_allow_undefined case $cc_basename in ifort*|nagfor*) _lt_dar_can_shared=yes ;; *) _lt_dar_can_shared=$GCC ;; esac if test yes = "$_lt_dar_can_shared"; then output_verbose_link_cmd=func_echo_all archive_cmds="\$CC -dynamiclib \$allow_undefined_flag -o \$lib \$libobjs \$deplibs \$compiler_flags -install_name \$rpath/\$soname \$verstring $_lt_dar_single_mod$_lt_dsymutil" module_cmds="\$CC \$allow_undefined_flag -o \$lib -bundle \$libobjs \$deplibs \$compiler_flags$_lt_dsymutil" archive_expsym_cmds="sed 's|^|_|' < \$export_symbols > \$output_objdir/\$libname-symbols.expsym~\$CC -dynamiclib \$allow_undefined_flag -o \$lib \$libobjs \$deplibs \$compiler_flags -install_name \$rpath/\$soname \$verstring $_lt_dar_single_mod$_lt_dar_export_syms$_lt_dsymutil" module_expsym_cmds="sed -e 's|^|_|' < \$export_symbols > \$output_objdir/\$libname-symbols.expsym~\$CC \$allow_undefined_flag -o \$lib -bundle \$libobjs \$deplibs \$compiler_flags$_lt_dar_export_syms$_lt_dsymutil" else ld_shlibs=no fi ;; dgux*) archive_cmds='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags' hardcode_libdir_flag_spec='-L$libdir' hardcode_shlibpath_var=no ;; # FreeBSD 2.2.[012] allows us to include c++rt0.o to get C++ constructor # support. Future versions do this automatically, but an explicit c++rt0.o # does not break anything, and helps significantly (at the cost of a little # extra space). freebsd2.2*) archive_cmds='$LD -Bshareable -o $lib $libobjs $deplibs $linker_flags /usr/lib/c++rt0.o' hardcode_libdir_flag_spec='-R$libdir' hardcode_direct=yes hardcode_shlibpath_var=no ;; # Unfortunately, older versions of FreeBSD 2 do not have this feature. freebsd2.*) archive_cmds='$LD -Bshareable -o $lib $libobjs $deplibs $linker_flags' hardcode_direct=yes hardcode_minus_L=yes hardcode_shlibpath_var=no ;; # FreeBSD 3 and greater uses gcc -shared to do shared libraries. freebsd* | dragonfly*) archive_cmds='$CC -shared $pic_flag -o $lib $libobjs $deplibs $compiler_flags' hardcode_libdir_flag_spec='-R$libdir' hardcode_direct=yes hardcode_shlibpath_var=no ;; hpux9*) if test yes = "$GCC"; then archive_cmds='$RM $output_objdir/$soname~$CC -shared $pic_flag $wl+b $wl$install_libdir -o $output_objdir/$soname $libobjs $deplibs $compiler_flags~test "x$output_objdir/$soname" = "x$lib" || mv $output_objdir/$soname $lib' else archive_cmds='$RM $output_objdir/$soname~$LD -b +b $install_libdir -o $output_objdir/$soname $libobjs $deplibs $linker_flags~test "x$output_objdir/$soname" = "x$lib" || mv $output_objdir/$soname $lib' fi hardcode_libdir_flag_spec='$wl+b $wl$libdir' hardcode_libdir_separator=: hardcode_direct=yes # hardcode_minus_L: Not really in the search PATH, # but as the default location of the library. hardcode_minus_L=yes export_dynamic_flag_spec='$wl-E' ;; hpux10*) if test yes,no = "$GCC,$with_gnu_ld"; then archive_cmds='$CC -shared $pic_flag $wl+h $wl$soname $wl+b $wl$install_libdir -o $lib $libobjs $deplibs $compiler_flags' else archive_cmds='$LD -b +h $soname +b $install_libdir -o $lib $libobjs $deplibs $linker_flags' fi if test no = "$with_gnu_ld"; then hardcode_libdir_flag_spec='$wl+b $wl$libdir' hardcode_libdir_separator=: hardcode_direct=yes hardcode_direct_absolute=yes export_dynamic_flag_spec='$wl-E' # hardcode_minus_L: Not really in the search PATH, # but as the default location of the library. hardcode_minus_L=yes fi ;; hpux11*) if test yes,no = "$GCC,$with_gnu_ld"; then case $host_cpu in hppa*64*) archive_cmds='$CC -shared $wl+h $wl$soname -o $lib $libobjs $deplibs $compiler_flags' ;; ia64*) archive_cmds='$CC -shared $pic_flag $wl+h $wl$soname $wl+nodefaultrpath -o $lib $libobjs $deplibs $compiler_flags' ;; *) archive_cmds='$CC -shared $pic_flag $wl+h $wl$soname $wl+b $wl$install_libdir -o $lib $libobjs $deplibs $compiler_flags' ;; esac else case $host_cpu in hppa*64*) archive_cmds='$CC -b $wl+h $wl$soname -o $lib $libobjs $deplibs $compiler_flags' ;; ia64*) archive_cmds='$CC -b $wl+h $wl$soname $wl+nodefaultrpath -o $lib $libobjs $deplibs $compiler_flags' ;; *) # Older versions of the 11.00 compiler do not understand -b yet # (HP92453-01 A.11.01.20 doesn't, HP92453-01 B.11.X.35175-35176.GP does) { $as_echo "$as_me:${as_lineno-$LINENO}: checking if $CC understands -b" >&5 $as_echo_n "checking if $CC understands -b... " >&6; } if ${lt_cv_prog_compiler__b+:} false; then : $as_echo_n "(cached) " >&6 else lt_cv_prog_compiler__b=no save_LDFLAGS=$LDFLAGS LDFLAGS="$LDFLAGS -b" echo "$lt_simple_link_test_code" > conftest.$ac_ext if (eval $ac_link 2>conftest.err) && test -s conftest$ac_exeext; then # The linker can only warn and ignore the option if not recognized # So say no if there are warnings if test -s conftest.err; then # Append any errors to the config.log. cat conftest.err 1>&5 $ECHO "$_lt_linker_boilerplate" | $SED '/^$/d' > conftest.exp $SED '/^$/d; /^ *+/d' conftest.err >conftest.er2 if diff conftest.exp conftest.er2 >/dev/null; then lt_cv_prog_compiler__b=yes fi else lt_cv_prog_compiler__b=yes fi fi $RM -r conftest* LDFLAGS=$save_LDFLAGS fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_prog_compiler__b" >&5 $as_echo "$lt_cv_prog_compiler__b" >&6; } if test yes = "$lt_cv_prog_compiler__b"; then archive_cmds='$CC -b $wl+h $wl$soname $wl+b $wl$install_libdir -o $lib $libobjs $deplibs $compiler_flags' else archive_cmds='$LD -b +h $soname +b $install_libdir -o $lib $libobjs $deplibs $linker_flags' fi ;; esac fi if test no = "$with_gnu_ld"; then hardcode_libdir_flag_spec='$wl+b $wl$libdir' hardcode_libdir_separator=: case $host_cpu in hppa*64*|ia64*) hardcode_direct=no hardcode_shlibpath_var=no ;; *) hardcode_direct=yes hardcode_direct_absolute=yes export_dynamic_flag_spec='$wl-E' # hardcode_minus_L: Not really in the search PATH, # but as the default location of the library. hardcode_minus_L=yes ;; esac fi ;; irix5* | irix6* | nonstopux*) if test yes = "$GCC"; then archive_cmds='$CC -shared $pic_flag $libobjs $deplibs $compiler_flags $wl-soname $wl$soname `test -n "$verstring" && func_echo_all "$wl-set_version $wl$verstring"` $wl-update_registry $wl$output_objdir/so_locations -o $lib' # Try to use the -exported_symbol ld option, if it does not # work, assume that -exports_file does not work either and # implicitly export all symbols. # This should be the same for all languages, so no per-tag cache variable. { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether the $host_os linker accepts -exported_symbol" >&5 $as_echo_n "checking whether the $host_os linker accepts -exported_symbol... " >&6; } if ${lt_cv_irix_exported_symbol+:} false; then : $as_echo_n "(cached) " >&6 else save_LDFLAGS=$LDFLAGS LDFLAGS="$LDFLAGS -shared $wl-exported_symbol ${wl}foo $wl-update_registry $wl/dev/null" cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ int foo (void) { return 0; } _ACEOF if ac_fn_c_try_link "$LINENO"; then : lt_cv_irix_exported_symbol=yes else lt_cv_irix_exported_symbol=no fi rm -f core conftest.err conftest.$ac_objext \ conftest$ac_exeext conftest.$ac_ext LDFLAGS=$save_LDFLAGS fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_irix_exported_symbol" >&5 $as_echo "$lt_cv_irix_exported_symbol" >&6; } if test yes = "$lt_cv_irix_exported_symbol"; then archive_expsym_cmds='$CC -shared $pic_flag $libobjs $deplibs $compiler_flags $wl-soname $wl$soname `test -n "$verstring" && func_echo_all "$wl-set_version $wl$verstring"` $wl-update_registry $wl$output_objdir/so_locations $wl-exports_file $wl$export_symbols -o $lib' fi else archive_cmds='$CC -shared $libobjs $deplibs $compiler_flags -soname $soname `test -n "$verstring" && func_echo_all "-set_version $verstring"` -update_registry $output_objdir/so_locations -o $lib' archive_expsym_cmds='$CC -shared $libobjs $deplibs $compiler_flags -soname $soname `test -n "$verstring" && func_echo_all "-set_version $verstring"` -update_registry $output_objdir/so_locations -exports_file $export_symbols -o $lib' fi archive_cmds_need_lc='no' hardcode_libdir_flag_spec='$wl-rpath $wl$libdir' hardcode_libdir_separator=: inherit_rpath=yes link_all_deplibs=yes ;; linux*) case $cc_basename in tcc*) # Fabrice Bellard et al's Tiny C Compiler ld_shlibs=yes archive_cmds='$CC -shared $pic_flag -o $lib $libobjs $deplibs $compiler_flags' ;; esac ;; netbsd*) if echo __ELF__ | $CC -E - | $GREP __ELF__ >/dev/null; then archive_cmds='$LD -Bshareable -o $lib $libobjs $deplibs $linker_flags' # a.out else archive_cmds='$LD -shared -o $lib $libobjs $deplibs $linker_flags' # ELF fi hardcode_libdir_flag_spec='-R$libdir' hardcode_direct=yes hardcode_shlibpath_var=no ;; newsos6) archive_cmds='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags' hardcode_direct=yes hardcode_libdir_flag_spec='$wl-rpath $wl$libdir' hardcode_libdir_separator=: hardcode_shlibpath_var=no ;; *nto* | *qnx*) ;; openbsd* | bitrig*) if test -f /usr/libexec/ld.so; then hardcode_direct=yes hardcode_shlibpath_var=no hardcode_direct_absolute=yes if test -z "`echo __ELF__ | $CC -E - | $GREP __ELF__`"; then archive_cmds='$CC -shared $pic_flag -o $lib $libobjs $deplibs $compiler_flags' archive_expsym_cmds='$CC -shared $pic_flag -o $lib $libobjs $deplibs $compiler_flags $wl-retain-symbols-file,$export_symbols' hardcode_libdir_flag_spec='$wl-rpath,$libdir' export_dynamic_flag_spec='$wl-E' else archive_cmds='$CC -shared $pic_flag -o $lib $libobjs $deplibs $compiler_flags' hardcode_libdir_flag_spec='$wl-rpath,$libdir' fi else ld_shlibs=no fi ;; os2*) hardcode_libdir_flag_spec='-L$libdir' hardcode_minus_L=yes allow_undefined_flag=unsupported shrext_cmds=.dll archive_cmds='$ECHO "LIBRARY ${soname%$shared_ext} INITINSTANCE TERMINSTANCE" > $output_objdir/$libname.def~ $ECHO "DESCRIPTION \"$libname\"" >> $output_objdir/$libname.def~ $ECHO "DATA MULTIPLE NONSHARED" >> $output_objdir/$libname.def~ $ECHO EXPORTS >> $output_objdir/$libname.def~ emxexp $libobjs | $SED /"_DLL_InitTerm"/d >> $output_objdir/$libname.def~ $CC -Zdll -Zcrtdll -o $output_objdir/$soname $libobjs $deplibs $compiler_flags $output_objdir/$libname.def~ emximp -o $lib $output_objdir/$libname.def' archive_expsym_cmds='$ECHO "LIBRARY ${soname%$shared_ext} INITINSTANCE TERMINSTANCE" > $output_objdir/$libname.def~ $ECHO "DESCRIPTION \"$libname\"" >> $output_objdir/$libname.def~ $ECHO "DATA MULTIPLE NONSHARED" >> $output_objdir/$libname.def~ $ECHO EXPORTS >> $output_objdir/$libname.def~ prefix_cmds="$SED"~ if test EXPORTS = "`$SED 1q $export_symbols`"; then prefix_cmds="$prefix_cmds -e 1d"; fi~ prefix_cmds="$prefix_cmds -e \"s/^\(.*\)$/_\1/g\""~ cat $export_symbols | $prefix_cmds >> $output_objdir/$libname.def~ $CC -Zdll -Zcrtdll -o $output_objdir/$soname $libobjs $deplibs $compiler_flags $output_objdir/$libname.def~ emximp -o $lib $output_objdir/$libname.def' old_archive_From_new_cmds='emximp -o $output_objdir/${libname}_dll.a $output_objdir/$libname.def' enable_shared_with_static_runtimes=yes ;; osf3*) if test yes = "$GCC"; then allow_undefined_flag=' $wl-expect_unresolved $wl\*' archive_cmds='$CC -shared$allow_undefined_flag $libobjs $deplibs $compiler_flags $wl-soname $wl$soname `test -n "$verstring" && func_echo_all "$wl-set_version $wl$verstring"` $wl-update_registry $wl$output_objdir/so_locations -o $lib' else allow_undefined_flag=' -expect_unresolved \*' archive_cmds='$CC -shared$allow_undefined_flag $libobjs $deplibs $compiler_flags -soname $soname `test -n "$verstring" && func_echo_all "-set_version $verstring"` -update_registry $output_objdir/so_locations -o $lib' fi archive_cmds_need_lc='no' hardcode_libdir_flag_spec='$wl-rpath $wl$libdir' hardcode_libdir_separator=: ;; osf4* | osf5*) # as osf3* with the addition of -msym flag if test yes = "$GCC"; then allow_undefined_flag=' $wl-expect_unresolved $wl\*' archive_cmds='$CC -shared$allow_undefined_flag $pic_flag $libobjs $deplibs $compiler_flags $wl-msym $wl-soname $wl$soname `test -n "$verstring" && func_echo_all "$wl-set_version $wl$verstring"` $wl-update_registry $wl$output_objdir/so_locations -o $lib' hardcode_libdir_flag_spec='$wl-rpath $wl$libdir' else allow_undefined_flag=' -expect_unresolved \*' archive_cmds='$CC -shared$allow_undefined_flag $libobjs $deplibs $compiler_flags -msym -soname $soname `test -n "$verstring" && func_echo_all "-set_version $verstring"` -update_registry $output_objdir/so_locations -o $lib' archive_expsym_cmds='for i in `cat $export_symbols`; do printf "%s %s\\n" -exported_symbol "\$i" >> $lib.exp; done; printf "%s\\n" "-hidden">> $lib.exp~ $CC -shared$allow_undefined_flag $wl-input $wl$lib.exp $compiler_flags $libobjs $deplibs -soname $soname `test -n "$verstring" && $ECHO "-set_version $verstring"` -update_registry $output_objdir/so_locations -o $lib~$RM $lib.exp' # Both c and cxx compiler support -rpath directly hardcode_libdir_flag_spec='-rpath $libdir' fi archive_cmds_need_lc='no' hardcode_libdir_separator=: ;; solaris*) no_undefined_flag=' -z defs' if test yes = "$GCC"; then wlarc='$wl' archive_cmds='$CC -shared $pic_flag $wl-z ${wl}text $wl-h $wl$soname -o $lib $libobjs $deplibs $compiler_flags' archive_expsym_cmds='echo "{ global:" > $lib.exp~cat $export_symbols | $SED -e "s/\(.*\)/\1;/" >> $lib.exp~echo "local: *; };" >> $lib.exp~ $CC -shared $pic_flag $wl-z ${wl}text $wl-M $wl$lib.exp $wl-h $wl$soname -o $lib $libobjs $deplibs $compiler_flags~$RM $lib.exp' else case `$CC -V 2>&1` in *"Compilers 5.0"*) wlarc='' archive_cmds='$LD -G$allow_undefined_flag -h $soname -o $lib $libobjs $deplibs $linker_flags' archive_expsym_cmds='echo "{ global:" > $lib.exp~cat $export_symbols | $SED -e "s/\(.*\)/\1;/" >> $lib.exp~echo "local: *; };" >> $lib.exp~ $LD -G$allow_undefined_flag -M $lib.exp -h $soname -o $lib $libobjs $deplibs $linker_flags~$RM $lib.exp' ;; *) wlarc='$wl' archive_cmds='$CC -G$allow_undefined_flag -h $soname -o $lib $libobjs $deplibs $compiler_flags' archive_expsym_cmds='echo "{ global:" > $lib.exp~cat $export_symbols | $SED -e "s/\(.*\)/\1;/" >> $lib.exp~echo "local: *; };" >> $lib.exp~ $CC -G$allow_undefined_flag -M $lib.exp -h $soname -o $lib $libobjs $deplibs $compiler_flags~$RM $lib.exp' ;; esac fi hardcode_libdir_flag_spec='-R$libdir' hardcode_shlibpath_var=no case $host_os in solaris2.[0-5] | solaris2.[0-5].*) ;; *) # The compiler driver will combine and reorder linker options, # but understands '-z linker_flag'. GCC discards it without '$wl', # but is careful enough not to reorder. # Supported since Solaris 2.6 (maybe 2.5.1?) if test yes = "$GCC"; then whole_archive_flag_spec='$wl-z ${wl}allextract$convenience $wl-z ${wl}defaultextract' else whole_archive_flag_spec='-z allextract$convenience -z defaultextract' fi ;; esac link_all_deplibs=yes ;; sunos4*) if test sequent = "$host_vendor"; then # Use $CC to link under sequent, because it throws in some extra .o # files that make .init and .fini sections work. archive_cmds='$CC -G $wl-h $soname -o $lib $libobjs $deplibs $compiler_flags' else archive_cmds='$LD -assert pure-text -Bstatic -o $lib $libobjs $deplibs $linker_flags' fi hardcode_libdir_flag_spec='-L$libdir' hardcode_direct=yes hardcode_minus_L=yes hardcode_shlibpath_var=no ;; sysv4) case $host_vendor in sni) archive_cmds='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags' hardcode_direct=yes # is this really true??? ;; siemens) ## LD is ld it makes a PLAMLIB ## CC just makes a GrossModule. archive_cmds='$LD -G -o $lib $libobjs $deplibs $linker_flags' reload_cmds='$CC -r -o $output$reload_objs' hardcode_direct=no ;; motorola) archive_cmds='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags' hardcode_direct=no #Motorola manual says yes, but my tests say they lie ;; esac runpath_var='LD_RUN_PATH' hardcode_shlibpath_var=no ;; sysv4.3*) archive_cmds='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags' hardcode_shlibpath_var=no export_dynamic_flag_spec='-Bexport' ;; sysv4*MP*) if test -d /usr/nec; then archive_cmds='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags' hardcode_shlibpath_var=no runpath_var=LD_RUN_PATH hardcode_runpath_var=yes ld_shlibs=yes fi ;; sysv4*uw2* | sysv5OpenUNIX* | sysv5UnixWare7.[01].[10]* | unixware7* | sco3.2v5.0.[024]*) no_undefined_flag='$wl-z,text' archive_cmds_need_lc=no hardcode_shlibpath_var=no runpath_var='LD_RUN_PATH' if test yes = "$GCC"; then archive_cmds='$CC -shared $wl-h,$soname -o $lib $libobjs $deplibs $compiler_flags' archive_expsym_cmds='$CC -shared $wl-Bexport:$export_symbols $wl-h,$soname -o $lib $libobjs $deplibs $compiler_flags' else archive_cmds='$CC -G $wl-h,$soname -o $lib $libobjs $deplibs $compiler_flags' archive_expsym_cmds='$CC -G $wl-Bexport:$export_symbols $wl-h,$soname -o $lib $libobjs $deplibs $compiler_flags' fi ;; sysv5* | sco3.2v5* | sco5v6*) # Note: We CANNOT use -z defs as we might desire, because we do not # link with -lc, and that would cause any symbols used from libc to # always be unresolved, which means just about no library would # ever link correctly. If we're not using GNU ld we use -z text # though, which does catch some bad symbols but isn't as heavy-handed # as -z defs. no_undefined_flag='$wl-z,text' allow_undefined_flag='$wl-z,nodefs' archive_cmds_need_lc=no hardcode_shlibpath_var=no hardcode_libdir_flag_spec='$wl-R,$libdir' hardcode_libdir_separator=':' link_all_deplibs=yes export_dynamic_flag_spec='$wl-Bexport' runpath_var='LD_RUN_PATH' if test yes = "$GCC"; then archive_cmds='$CC -shared $wl-h,$soname -o $lib $libobjs $deplibs $compiler_flags' archive_expsym_cmds='$CC -shared $wl-Bexport:$export_symbols $wl-h,$soname -o $lib $libobjs $deplibs $compiler_flags' else archive_cmds='$CC -G $wl-h,$soname -o $lib $libobjs $deplibs $compiler_flags' archive_expsym_cmds='$CC -G $wl-Bexport:$export_symbols $wl-h,$soname -o $lib $libobjs $deplibs $compiler_flags' fi ;; uts4*) archive_cmds='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags' hardcode_libdir_flag_spec='-L$libdir' hardcode_shlibpath_var=no ;; *) ld_shlibs=no ;; esac if test sni = "$host_vendor"; then case $host in sysv4 | sysv4.2uw2* | sysv4.3* | sysv5*) export_dynamic_flag_spec='$wl-Blargedynsym' ;; esac fi fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ld_shlibs" >&5 $as_echo "$ld_shlibs" >&6; } test no = "$ld_shlibs" && can_build_shared=no with_gnu_ld=$with_gnu_ld # # Do we need to explicitly link libc? # case "x$archive_cmds_need_lc" in x|xyes) # Assume -lc should be added archive_cmds_need_lc=yes if test yes,yes = "$GCC,$enable_shared"; then case $archive_cmds in *'~'*) # FIXME: we may have to deal with multi-command sequences. ;; '$CC '*) # Test whether the compiler implicitly links with -lc since on some # systems, -lgcc has to come before -lc. If gcc already passes -lc # to ld, don't add -lc before -lgcc. { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether -lc should be explicitly linked in" >&5 $as_echo_n "checking whether -lc should be explicitly linked in... " >&6; } if ${lt_cv_archive_cmds_need_lc+:} false; then : $as_echo_n "(cached) " >&6 else $RM conftest* echo "$lt_simple_compile_test_code" > conftest.$ac_ext if { { eval echo "\"\$as_me\":${as_lineno-$LINENO}: \"$ac_compile\""; } >&5 (eval $ac_compile) 2>&5 ac_status=$? $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 test $ac_status = 0; } 2>conftest.err; then soname=conftest lib=conftest libobjs=conftest.$ac_objext deplibs= wl=$lt_prog_compiler_wl pic_flag=$lt_prog_compiler_pic compiler_flags=-v linker_flags=-v verstring= output_objdir=. libname=conftest lt_save_allow_undefined_flag=$allow_undefined_flag allow_undefined_flag= if { { eval echo "\"\$as_me\":${as_lineno-$LINENO}: \"$archive_cmds 2\>\&1 \| $GREP \" -lc \" \>/dev/null 2\>\&1\""; } >&5 (eval $archive_cmds 2\>\&1 \| $GREP \" -lc \" \>/dev/null 2\>\&1) 2>&5 ac_status=$? $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 test $ac_status = 0; } then lt_cv_archive_cmds_need_lc=no else lt_cv_archive_cmds_need_lc=yes fi allow_undefined_flag=$lt_save_allow_undefined_flag else cat conftest.err 1>&5 fi $RM conftest* fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_archive_cmds_need_lc" >&5 $as_echo "$lt_cv_archive_cmds_need_lc" >&6; } archive_cmds_need_lc=$lt_cv_archive_cmds_need_lc ;; esac fi ;; esac { $as_echo "$as_me:${as_lineno-$LINENO}: checking dynamic linker characteristics" >&5 $as_echo_n "checking dynamic linker characteristics... " >&6; } if test yes = "$GCC"; then case $host_os in darwin*) lt_awk_arg='/^libraries:/,/LR/' ;; *) lt_awk_arg='/^libraries:/' ;; esac case $host_os in mingw* | cegcc*) lt_sed_strip_eq='s|=\([A-Za-z]:\)|\1|g' ;; *) lt_sed_strip_eq='s|=/|/|g' ;; esac lt_search_path_spec=`$CC -print-search-dirs | awk $lt_awk_arg | $SED -e "s/^libraries://" -e $lt_sed_strip_eq` case $lt_search_path_spec in *\;*) # if the path contains ";" then we assume it to be the separator # otherwise default to the standard path separator (i.e. ":") - it is # assumed that no part of a normal pathname contains ";" but that should # okay in the real world where ";" in dirpaths is itself problematic. lt_search_path_spec=`$ECHO "$lt_search_path_spec" | $SED 's/;/ /g'` ;; *) lt_search_path_spec=`$ECHO "$lt_search_path_spec" | $SED "s/$PATH_SEPARATOR/ /g"` ;; esac # Ok, now we have the path, separated by spaces, we can step through it # and add multilib dir if necessary... lt_tmp_lt_search_path_spec= lt_multi_os_dir=/`$CC $CPPFLAGS $CFLAGS $LDFLAGS -print-multi-os-directory 2>/dev/null` # ...but if some path component already ends with the multilib dir we assume # that all is fine and trust -print-search-dirs as is (GCC 4.2? or newer). case "$lt_multi_os_dir; $lt_search_path_spec " in "/; "* | "/.; "* | "/./; "* | *"$lt_multi_os_dir "* | *"$lt_multi_os_dir/ "*) lt_multi_os_dir= ;; esac for lt_sys_path in $lt_search_path_spec; do if test -d "$lt_sys_path$lt_multi_os_dir"; then lt_tmp_lt_search_path_spec="$lt_tmp_lt_search_path_spec $lt_sys_path$lt_multi_os_dir" elif test -n "$lt_multi_os_dir"; then test -d "$lt_sys_path" && \ lt_tmp_lt_search_path_spec="$lt_tmp_lt_search_path_spec $lt_sys_path" fi done lt_search_path_spec=`$ECHO "$lt_tmp_lt_search_path_spec" | awk ' BEGIN {RS = " "; FS = "/|\n";} { lt_foo = ""; lt_count = 0; for (lt_i = NF; lt_i > 0; lt_i--) { if ($lt_i != "" && $lt_i != ".") { if ($lt_i == "..") { lt_count++; } else { if (lt_count == 0) { lt_foo = "/" $lt_i lt_foo; } else { lt_count--; } } } } if (lt_foo != "") { lt_freq[lt_foo]++; } if (lt_freq[lt_foo] == 1) { print lt_foo; } }'` # AWK program above erroneously prepends '/' to C:/dos/paths # for these hosts. case $host_os in mingw* | cegcc*) lt_search_path_spec=`$ECHO "$lt_search_path_spec" |\ $SED 's|/\([A-Za-z]:\)|\1|g'` ;; esac sys_lib_search_path_spec=`$ECHO "$lt_search_path_spec" | $lt_NL2SP` else sys_lib_search_path_spec="/lib /usr/lib /usr/local/lib" fi library_names_spec= libname_spec='lib$name' soname_spec= shrext_cmds=.so postinstall_cmds= postuninstall_cmds= finish_cmds= finish_eval= shlibpath_var= shlibpath_overrides_runpath=unknown version_type=none dynamic_linker="$host_os ld.so" sys_lib_dlsearch_path_spec="/lib /usr/lib" need_lib_prefix=unknown hardcode_into_libs=no # when you set need_version to no, make sure it does not cause -set_version # flags to be left without arguments need_version=unknown case $host_os in aix3*) version_type=linux # correct to gnu/linux during the next big refactor library_names_spec='$libname$release$shared_ext$versuffix $libname.a' shlibpath_var=LIBPATH # AIX 3 has no versioning support, so we append a major version to the name. soname_spec='$libname$release$shared_ext$major' ;; aix[4-9]*) version_type=linux # correct to gnu/linux during the next big refactor need_lib_prefix=no need_version=no hardcode_into_libs=yes if test ia64 = "$host_cpu"; then # AIX 5 supports IA64 library_names_spec='$libname$release$shared_ext$major $libname$release$shared_ext$versuffix $libname$shared_ext' shlibpath_var=LD_LIBRARY_PATH else # With GCC up to 2.95.x, collect2 would create an import file # for dependence libraries. The import file would start with # the line '#! .'. This would cause the generated library to # depend on '.', always an invalid library. This was fixed in # development snapshots of GCC prior to 3.0. case $host_os in aix4 | aix4.[01] | aix4.[01].*) if { echo '#if __GNUC__ > 2 || (__GNUC__ == 2 && __GNUC_MINOR__ >= 97)' echo ' yes ' echo '#endif'; } | $CC -E - | $GREP yes > /dev/null; then : else can_build_shared=no fi ;; esac # Using Import Files as archive members, it is possible to support # filename-based versioning of shared library archives on AIX. While # this would work for both with and without runtime linking, it will # prevent static linking of such archives. So we do filename-based # shared library versioning with .so extension only, which is used # when both runtime linking and shared linking is enabled. # Unfortunately, runtime linking may impact performance, so we do # not want this to be the default eventually. Also, we use the # versioned .so libs for executables only if there is the -brtl # linker flag in LDFLAGS as well, or --with-aix-soname=svr4 only. # To allow for filename-based versioning support, we need to create # libNAME.so.V as an archive file, containing: # *) an Import File, referring to the versioned filename of the # archive as well as the shared archive member, telling the # bitwidth (32 or 64) of that shared object, and providing the # list of exported symbols of that shared object, eventually # decorated with the 'weak' keyword # *) the shared object with the F_LOADONLY flag set, to really avoid # it being seen by the linker. # At run time we better use the real file rather than another symlink, # but for link time we create the symlink libNAME.so -> libNAME.so.V case $with_aix_soname,$aix_use_runtimelinking in # AIX (on Power*) has no versioning support, so currently we cannot hardcode correct # soname into executable. Probably we can add versioning support to # collect2, so additional links can be useful in future. aix,yes) # traditional libtool dynamic_linker='AIX unversionable lib.so' # If using run time linking (on AIX 4.2 or later) use lib.so # instead of lib.a to let people know that these are not # typical AIX shared libraries. library_names_spec='$libname$release$shared_ext$versuffix $libname$release$shared_ext$major $libname$shared_ext' ;; aix,no) # traditional AIX only dynamic_linker='AIX lib.a(lib.so.V)' # We preserve .a as extension for shared libraries through AIX4.2 # and later when we are not doing run time linking. library_names_spec='$libname$release.a $libname.a' soname_spec='$libname$release$shared_ext$major' ;; svr4,*) # full svr4 only dynamic_linker="AIX lib.so.V($shared_archive_member_spec.o)" library_names_spec='$libname$release$shared_ext$major $libname$shared_ext' # We do not specify a path in Import Files, so LIBPATH fires. shlibpath_overrides_runpath=yes ;; *,yes) # both, prefer svr4 dynamic_linker="AIX lib.so.V($shared_archive_member_spec.o), lib.a(lib.so.V)" library_names_spec='$libname$release$shared_ext$major $libname$shared_ext' # unpreferred sharedlib libNAME.a needs extra handling postinstall_cmds='test -n "$linkname" || linkname="$realname"~func_stripname "" ".so" "$linkname"~$install_shared_prog "$dir/$func_stripname_result.$libext" "$destdir/$func_stripname_result.$libext"~test -z "$tstripme" || test -z "$striplib" || $striplib "$destdir/$func_stripname_result.$libext"' postuninstall_cmds='for n in $library_names $old_library; do :; done~func_stripname "" ".so" "$n"~test "$func_stripname_result" = "$n" || func_append rmfiles " $odir/$func_stripname_result.$libext"' # We do not specify a path in Import Files, so LIBPATH fires. shlibpath_overrides_runpath=yes ;; *,no) # both, prefer aix dynamic_linker="AIX lib.a(lib.so.V), lib.so.V($shared_archive_member_spec.o)" library_names_spec='$libname$release.a $libname.a' soname_spec='$libname$release$shared_ext$major' # unpreferred sharedlib libNAME.so.V and symlink libNAME.so need extra handling postinstall_cmds='test -z "$dlname" || $install_shared_prog $dir/$dlname $destdir/$dlname~test -z "$tstripme" || test -z "$striplib" || $striplib $destdir/$dlname~test -n "$linkname" || linkname=$realname~func_stripname "" ".a" "$linkname"~(cd "$destdir" && $LN_S -f $dlname $func_stripname_result.so)' postuninstall_cmds='test -z "$dlname" || func_append rmfiles " $odir/$dlname"~for n in $old_library $library_names; do :; done~func_stripname "" ".a" "$n"~func_append rmfiles " $odir/$func_stripname_result.so"' ;; esac shlibpath_var=LIBPATH fi ;; amigaos*) case $host_cpu in powerpc) # Since July 2007 AmigaOS4 officially supports .so libraries. # When compiling the executable, add -use-dynld -Lsobjs: to the compileline. library_names_spec='$libname$release$shared_ext$versuffix $libname$release$shared_ext$major $libname$shared_ext' ;; m68k) library_names_spec='$libname.ixlibrary $libname.a' # Create ${libname}_ixlibrary.a entries in /sys/libs. finish_eval='for lib in `ls $libdir/*.ixlibrary 2>/dev/null`; do libname=`func_echo_all "$lib" | $SED '\''s%^.*/\([^/]*\)\.ixlibrary$%\1%'\''`; $RM /sys/libs/${libname}_ixlibrary.a; $show "cd /sys/libs && $LN_S $lib ${libname}_ixlibrary.a"; cd /sys/libs && $LN_S $lib ${libname}_ixlibrary.a || exit 1; done' ;; esac ;; beos*) library_names_spec='$libname$shared_ext' dynamic_linker="$host_os ld.so" shlibpath_var=LIBRARY_PATH ;; bsdi[45]*) version_type=linux # correct to gnu/linux during the next big refactor need_version=no library_names_spec='$libname$release$shared_ext$versuffix $libname$release$shared_ext$major $libname$shared_ext' soname_spec='$libname$release$shared_ext$major' finish_cmds='PATH="\$PATH:/sbin" ldconfig $libdir' shlibpath_var=LD_LIBRARY_PATH sys_lib_search_path_spec="/shlib /usr/lib /usr/X11/lib /usr/contrib/lib /lib /usr/local/lib" sys_lib_dlsearch_path_spec="/shlib /usr/lib /usr/local/lib" # the default ld.so.conf also contains /usr/contrib/lib and # /usr/X11R6/lib (/usr/X11 is a link to /usr/X11R6), but let us allow # libtool to hard-code these into programs ;; cygwin* | mingw* | pw32* | cegcc*) version_type=windows shrext_cmds=.dll need_version=no need_lib_prefix=no case $GCC,$cc_basename in yes,*) # gcc library_names_spec='$libname.dll.a' # DLL is installed to $(libdir)/../bin by postinstall_cmds postinstall_cmds='base_file=`basename \$file`~ dlpath=`$SHELL 2>&1 -c '\''. $dir/'\''\$base_file'\''i; echo \$dlname'\''`~ dldir=$destdir/`dirname \$dlpath`~ test -d \$dldir || mkdir -p \$dldir~ $install_prog $dir/$dlname \$dldir/$dlname~ chmod a+x \$dldir/$dlname~ if test -n '\''$stripme'\'' && test -n '\''$striplib'\''; then eval '\''$striplib \$dldir/$dlname'\'' || exit \$?; fi' postuninstall_cmds='dldll=`$SHELL 2>&1 -c '\''. $file; echo \$dlname'\''`~ dlpath=$dir/\$dldll~ $RM \$dlpath' shlibpath_overrides_runpath=yes case $host_os in cygwin*) # Cygwin DLLs use 'cyg' prefix rather than 'lib' soname_spec='`echo $libname | sed -e 's/^lib/cyg/'``echo $release | $SED -e 's/[.]/-/g'`$versuffix$shared_ext' sys_lib_search_path_spec="$sys_lib_search_path_spec /usr/lib/w32api" ;; mingw* | cegcc*) # MinGW DLLs use traditional 'lib' prefix soname_spec='$libname`echo $release | $SED -e 's/[.]/-/g'`$versuffix$shared_ext' ;; pw32*) # pw32 DLLs use 'pw' prefix rather than 'lib' library_names_spec='`echo $libname | sed -e 's/^lib/pw/'``echo $release | $SED -e 's/[.]/-/g'`$versuffix$shared_ext' ;; esac dynamic_linker='Win32 ld.exe' ;; *,cl*) # Native MSVC libname_spec='$name' soname_spec='$libname`echo $release | $SED -e 's/[.]/-/g'`$versuffix$shared_ext' library_names_spec='$libname.dll.lib' case $build_os in mingw*) sys_lib_search_path_spec= lt_save_ifs=$IFS IFS=';' for lt_path in $LIB do IFS=$lt_save_ifs # Let DOS variable expansion print the short 8.3 style file name. lt_path=`cd "$lt_path" 2>/dev/null && cmd //C "for %i in (".") do @echo %~si"` sys_lib_search_path_spec="$sys_lib_search_path_spec $lt_path" done IFS=$lt_save_ifs # Convert to MSYS style. sys_lib_search_path_spec=`$ECHO "$sys_lib_search_path_spec" | sed -e 's|\\\\|/|g' -e 's| \\([a-zA-Z]\\):| /\\1|g' -e 's|^ ||'` ;; cygwin*) # Convert to unix form, then to dos form, then back to unix form # but this time dos style (no spaces!) so that the unix form looks # like /cygdrive/c/PROGRA~1:/cygdr... sys_lib_search_path_spec=`cygpath --path --unix "$LIB"` sys_lib_search_path_spec=`cygpath --path --dos "$sys_lib_search_path_spec" 2>/dev/null` sys_lib_search_path_spec=`cygpath --path --unix "$sys_lib_search_path_spec" | $SED -e "s/$PATH_SEPARATOR/ /g"` ;; *) sys_lib_search_path_spec=$LIB if $ECHO "$sys_lib_search_path_spec" | $GREP ';[c-zC-Z]:/' >/dev/null; then # It is most probably a Windows format PATH. sys_lib_search_path_spec=`$ECHO "$sys_lib_search_path_spec" | $SED -e 's/;/ /g'` else sys_lib_search_path_spec=`$ECHO "$sys_lib_search_path_spec" | $SED -e "s/$PATH_SEPARATOR/ /g"` fi # FIXME: find the short name or the path components, as spaces are # common. (e.g. "Program Files" -> "PROGRA~1") ;; esac # DLL is installed to $(libdir)/../bin by postinstall_cmds postinstall_cmds='base_file=`basename \$file`~ dlpath=`$SHELL 2>&1 -c '\''. $dir/'\''\$base_file'\''i; echo \$dlname'\''`~ dldir=$destdir/`dirname \$dlpath`~ test -d \$dldir || mkdir -p \$dldir~ $install_prog $dir/$dlname \$dldir/$dlname' postuninstall_cmds='dldll=`$SHELL 2>&1 -c '\''. $file; echo \$dlname'\''`~ dlpath=$dir/\$dldll~ $RM \$dlpath' shlibpath_overrides_runpath=yes dynamic_linker='Win32 link.exe' ;; *) # Assume MSVC wrapper library_names_spec='$libname`echo $release | $SED -e 's/[.]/-/g'`$versuffix$shared_ext $libname.lib' dynamic_linker='Win32 ld.exe' ;; esac # FIXME: first we should search . and the directory the executable is in shlibpath_var=PATH ;; darwin* | rhapsody*) dynamic_linker="$host_os dyld" version_type=darwin need_lib_prefix=no need_version=no library_names_spec='$libname$release$major$shared_ext $libname$shared_ext' soname_spec='$libname$release$major$shared_ext' shlibpath_overrides_runpath=yes shlibpath_var=DYLD_LIBRARY_PATH shrext_cmds='`test .$module = .yes && echo .so || echo .dylib`' sys_lib_search_path_spec="$sys_lib_search_path_spec /usr/local/lib" sys_lib_dlsearch_path_spec='/usr/local/lib /lib /usr/lib' ;; dgux*) version_type=linux # correct to gnu/linux during the next big refactor need_lib_prefix=no need_version=no library_names_spec='$libname$release$shared_ext$versuffix $libname$release$shared_ext$major $libname$shared_ext' soname_spec='$libname$release$shared_ext$major' shlibpath_var=LD_LIBRARY_PATH ;; freebsd* | dragonfly*) # DragonFly does not have aout. When/if they implement a new # versioning mechanism, adjust this. if test -x /usr/bin/objformat; then objformat=`/usr/bin/objformat` else case $host_os in freebsd[23].*) objformat=aout ;; *) objformat=elf ;; esac fi version_type=freebsd-$objformat case $version_type in freebsd-elf*) library_names_spec='$libname$release$shared_ext$versuffix $libname$release$shared_ext$major $libname$shared_ext' soname_spec='$libname$release$shared_ext$major' need_version=no need_lib_prefix=no ;; freebsd-*) library_names_spec='$libname$release$shared_ext$versuffix $libname$shared_ext$versuffix' need_version=yes ;; esac shlibpath_var=LD_LIBRARY_PATH case $host_os in freebsd2.*) shlibpath_overrides_runpath=yes ;; freebsd3.[01]* | freebsdelf3.[01]*) shlibpath_overrides_runpath=yes hardcode_into_libs=yes ;; freebsd3.[2-9]* | freebsdelf3.[2-9]* | \ freebsd4.[0-5] | freebsdelf4.[0-5] | freebsd4.1.1 | freebsdelf4.1.1) shlibpath_overrides_runpath=no hardcode_into_libs=yes ;; *) # from 4.6 on, and DragonFly shlibpath_overrides_runpath=yes hardcode_into_libs=yes ;; esac ;; haiku*) version_type=linux # correct to gnu/linux during the next big refactor need_lib_prefix=no need_version=no dynamic_linker="$host_os runtime_loader" library_names_spec='$libname$release$shared_ext$versuffix $libname$release$shared_ext$major $libname$shared_ext' soname_spec='$libname$release$shared_ext$major' shlibpath_var=LIBRARY_PATH shlibpath_overrides_runpath=no sys_lib_dlsearch_path_spec='/boot/home/config/lib /boot/common/lib /boot/system/lib' hardcode_into_libs=yes ;; hpux9* | hpux10* | hpux11*) # Give a soname corresponding to the major version so that dld.sl refuses to # link against other versions. version_type=sunos need_lib_prefix=no need_version=no case $host_cpu in ia64*) shrext_cmds='.so' hardcode_into_libs=yes dynamic_linker="$host_os dld.so" shlibpath_var=LD_LIBRARY_PATH shlibpath_overrides_runpath=yes # Unless +noenvvar is specified. library_names_spec='$libname$release$shared_ext$versuffix $libname$release$shared_ext$major $libname$shared_ext' soname_spec='$libname$release$shared_ext$major' if test 32 = "$HPUX_IA64_MODE"; then sys_lib_search_path_spec="/usr/lib/hpux32 /usr/local/lib/hpux32 /usr/local/lib" sys_lib_dlsearch_path_spec=/usr/lib/hpux32 else sys_lib_search_path_spec="/usr/lib/hpux64 /usr/local/lib/hpux64" sys_lib_dlsearch_path_spec=/usr/lib/hpux64 fi ;; hppa*64*) shrext_cmds='.sl' hardcode_into_libs=yes dynamic_linker="$host_os dld.sl" shlibpath_var=LD_LIBRARY_PATH # How should we handle SHLIB_PATH shlibpath_overrides_runpath=yes # Unless +noenvvar is specified. library_names_spec='$libname$release$shared_ext$versuffix $libname$release$shared_ext$major $libname$shared_ext' soname_spec='$libname$release$shared_ext$major' sys_lib_search_path_spec="/usr/lib/pa20_64 /usr/ccs/lib/pa20_64" sys_lib_dlsearch_path_spec=$sys_lib_search_path_spec ;; *) shrext_cmds='.sl' dynamic_linker="$host_os dld.sl" shlibpath_var=SHLIB_PATH shlibpath_overrides_runpath=no # +s is required to enable SHLIB_PATH library_names_spec='$libname$release$shared_ext$versuffix $libname$release$shared_ext$major $libname$shared_ext' soname_spec='$libname$release$shared_ext$major' ;; esac # HP-UX runs *really* slowly unless shared libraries are mode 555, ... postinstall_cmds='chmod 555 $lib' # or fails outright, so override atomically: install_override_mode=555 ;; interix[3-9]*) version_type=linux # correct to gnu/linux during the next big refactor need_lib_prefix=no need_version=no library_names_spec='$libname$release$shared_ext$versuffix $libname$release$shared_ext$major $libname$shared_ext' soname_spec='$libname$release$shared_ext$major' dynamic_linker='Interix 3.x ld.so.1 (PE, like ELF)' shlibpath_var=LD_LIBRARY_PATH shlibpath_overrides_runpath=no hardcode_into_libs=yes ;; irix5* | irix6* | nonstopux*) case $host_os in nonstopux*) version_type=nonstopux ;; *) if test yes = "$lt_cv_prog_gnu_ld"; then version_type=linux # correct to gnu/linux during the next big refactor else version_type=irix fi ;; esac need_lib_prefix=no need_version=no soname_spec='$libname$release$shared_ext$major' library_names_spec='$libname$release$shared_ext$versuffix $libname$release$shared_ext$major $libname$release$shared_ext $libname$shared_ext' case $host_os in irix5* | nonstopux*) libsuff= shlibsuff= ;; *) case $LD in # libtool.m4 will add one of these switches to LD *-32|*"-32 "|*-melf32bsmip|*"-melf32bsmip ") libsuff= shlibsuff= libmagic=32-bit;; *-n32|*"-n32 "|*-melf32bmipn32|*"-melf32bmipn32 ") libsuff=32 shlibsuff=N32 libmagic=N32;; *-64|*"-64 "|*-melf64bmip|*"-melf64bmip ") libsuff=64 shlibsuff=64 libmagic=64-bit;; *) libsuff= shlibsuff= libmagic=never-match;; esac ;; esac shlibpath_var=LD_LIBRARY${shlibsuff}_PATH shlibpath_overrides_runpath=no sys_lib_search_path_spec="/usr/lib$libsuff /lib$libsuff /usr/local/lib$libsuff" sys_lib_dlsearch_path_spec="/usr/lib$libsuff /lib$libsuff" hardcode_into_libs=yes ;; # No shared lib support for Linux oldld, aout, or coff. linux*oldld* | linux*aout* | linux*coff*) dynamic_linker=no ;; linux*android*) version_type=none # Android doesn't support versioned libraries. need_lib_prefix=no need_version=no library_names_spec='$libname$release$shared_ext' soname_spec='$libname$release$shared_ext' finish_cmds= shlibpath_var=LD_LIBRARY_PATH shlibpath_overrides_runpath=yes # This implies no fast_install, which is unacceptable. # Some rework will be needed to allow for fast_install # before this can be enabled. hardcode_into_libs=yes dynamic_linker='Android linker' # Don't embed -rpath directories since the linker doesn't support them. hardcode_libdir_flag_spec='-L$libdir' ;; # This must be glibc/ELF. linux* | k*bsd*-gnu | kopensolaris*-gnu | gnu*) version_type=linux # correct to gnu/linux during the next big refactor need_lib_prefix=no need_version=no library_names_spec='$libname$release$shared_ext$versuffix $libname$release$shared_ext$major $libname$shared_ext' soname_spec='$libname$release$shared_ext$major' finish_cmds='PATH="\$PATH:/sbin" ldconfig -n $libdir' shlibpath_var=LD_LIBRARY_PATH shlibpath_overrides_runpath=no # Some binutils ld are patched to set DT_RUNPATH if ${lt_cv_shlibpath_overrides_runpath+:} false; then : $as_echo_n "(cached) " >&6 else lt_cv_shlibpath_overrides_runpath=no save_LDFLAGS=$LDFLAGS save_libdir=$libdir eval "libdir=/foo; wl=\"$lt_prog_compiler_wl\"; \ LDFLAGS=\"\$LDFLAGS $hardcode_libdir_flag_spec\"" cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ int main () { ; return 0; } _ACEOF if ac_fn_c_try_link "$LINENO"; then : if ($OBJDUMP -p conftest$ac_exeext) 2>/dev/null | grep "RUNPATH.*$libdir" >/dev/null; then : lt_cv_shlibpath_overrides_runpath=yes fi fi rm -f core conftest.err conftest.$ac_objext \ conftest$ac_exeext conftest.$ac_ext LDFLAGS=$save_LDFLAGS libdir=$save_libdir fi shlibpath_overrides_runpath=$lt_cv_shlibpath_overrides_runpath # This implies no fast_install, which is unacceptable. # Some rework will be needed to allow for fast_install # before this can be enabled. hardcode_into_libs=yes # Ideally, we could use ldconfig to report *all* directores which are # searched for libraries, however this is still not possible. Aside from not # being certain /sbin/ldconfig is available, command # 'ldconfig -N -X -v | grep ^/' on 64bit Fedora does not report /usr/lib64, # even though it is searched at run-time. Try to do the best guess by # appending ld.so.conf contents (and includes) to the search path. if test -f /etc/ld.so.conf; then lt_ld_extra=`awk '/^include / { system(sprintf("cd /etc; cat %s 2>/dev/null", \$2)); skip = 1; } { if (!skip) print \$0; skip = 0; }' < /etc/ld.so.conf | $SED -e 's/#.*//;/^[ ]*hwcap[ ]/d;s/[:, ]/ /g;s/=[^=]*$//;s/=[^= ]* / /g;s/"//g;/^$/d' | tr '\n' ' '` sys_lib_dlsearch_path_spec="/lib /usr/lib $lt_ld_extra" fi # We used to test for /lib/ld.so.1 and disable shared libraries on # powerpc, because MkLinux only supported shared libraries with the # GNU dynamic linker. Since this was broken with cross compilers, # most powerpc-linux boxes support dynamic linking these days and # people can always --disable-shared, the test was removed, and we # assume the GNU/Linux dynamic linker is in use. dynamic_linker='GNU/Linux ld.so' ;; netbsd*) version_type=sunos need_lib_prefix=no need_version=no if echo __ELF__ | $CC -E - | $GREP __ELF__ >/dev/null; then library_names_spec='$libname$release$shared_ext$versuffix $libname$shared_ext$versuffix' finish_cmds='PATH="\$PATH:/sbin" ldconfig -m $libdir' dynamic_linker='NetBSD (a.out) ld.so' else library_names_spec='$libname$release$shared_ext$versuffix $libname$release$shared_ext$major $libname$shared_ext' soname_spec='$libname$release$shared_ext$major' dynamic_linker='NetBSD ld.elf_so' fi shlibpath_var=LD_LIBRARY_PATH shlibpath_overrides_runpath=yes hardcode_into_libs=yes ;; newsos6) version_type=linux # correct to gnu/linux during the next big refactor library_names_spec='$libname$release$shared_ext$versuffix $libname$release$shared_ext$major $libname$shared_ext' shlibpath_var=LD_LIBRARY_PATH shlibpath_overrides_runpath=yes ;; *nto* | *qnx*) version_type=qnx need_lib_prefix=no need_version=no library_names_spec='$libname$release$shared_ext$versuffix $libname$release$shared_ext$major $libname$shared_ext' soname_spec='$libname$release$shared_ext$major' shlibpath_var=LD_LIBRARY_PATH shlibpath_overrides_runpath=no hardcode_into_libs=yes dynamic_linker='ldqnx.so' ;; openbsd* | bitrig*) version_type=sunos sys_lib_dlsearch_path_spec=/usr/lib need_lib_prefix=no if test -z "`echo __ELF__ | $CC -E - | $GREP __ELF__`"; then need_version=no else need_version=yes fi library_names_spec='$libname$release$shared_ext$versuffix $libname$shared_ext$versuffix' finish_cmds='PATH="\$PATH:/sbin" ldconfig -m $libdir' shlibpath_var=LD_LIBRARY_PATH shlibpath_overrides_runpath=yes ;; os2*) libname_spec='$name' version_type=windows shrext_cmds=.dll need_version=no need_lib_prefix=no # OS/2 can only load a DLL with a base name of 8 characters or less. soname_spec='`test -n "$os2dllname" && libname="$os2dllname"; v=$($ECHO $release$versuffix | tr -d .-); n=$($ECHO $libname | cut -b -$((8 - ${#v})) | tr . _); $ECHO $n$v`$shared_ext' library_names_spec='${libname}_dll.$libext' dynamic_linker='OS/2 ld.exe' shlibpath_var=BEGINLIBPATH sys_lib_search_path_spec="/lib /usr/lib /usr/local/lib" sys_lib_dlsearch_path_spec=$sys_lib_search_path_spec postinstall_cmds='base_file=`basename \$file`~ dlpath=`$SHELL 2>&1 -c '\''. $dir/'\''\$base_file'\''i; $ECHO \$dlname'\''`~ dldir=$destdir/`dirname \$dlpath`~ test -d \$dldir || mkdir -p \$dldir~ $install_prog $dir/$dlname \$dldir/$dlname~ chmod a+x \$dldir/$dlname~ if test -n '\''$stripme'\'' && test -n '\''$striplib'\''; then eval '\''$striplib \$dldir/$dlname'\'' || exit \$?; fi' postuninstall_cmds='dldll=`$SHELL 2>&1 -c '\''. $file; $ECHO \$dlname'\''`~ dlpath=$dir/\$dldll~ $RM \$dlpath' ;; osf3* | osf4* | osf5*) version_type=osf need_lib_prefix=no need_version=no soname_spec='$libname$release$shared_ext$major' library_names_spec='$libname$release$shared_ext$versuffix $libname$release$shared_ext$major $libname$shared_ext' shlibpath_var=LD_LIBRARY_PATH sys_lib_search_path_spec="/usr/shlib /usr/ccs/lib /usr/lib/cmplrs/cc /usr/lib /usr/local/lib /var/shlib" sys_lib_dlsearch_path_spec=$sys_lib_search_path_spec ;; rdos*) dynamic_linker=no ;; solaris*) version_type=linux # correct to gnu/linux during the next big refactor need_lib_prefix=no need_version=no library_names_spec='$libname$release$shared_ext$versuffix $libname$release$shared_ext$major $libname$shared_ext' soname_spec='$libname$release$shared_ext$major' shlibpath_var=LD_LIBRARY_PATH shlibpath_overrides_runpath=yes hardcode_into_libs=yes # ldd complains unless libraries are executable postinstall_cmds='chmod +x $lib' ;; sunos4*) version_type=sunos library_names_spec='$libname$release$shared_ext$versuffix $libname$shared_ext$versuffix' finish_cmds='PATH="\$PATH:/usr/etc" ldconfig $libdir' shlibpath_var=LD_LIBRARY_PATH shlibpath_overrides_runpath=yes if test yes = "$with_gnu_ld"; then need_lib_prefix=no fi need_version=yes ;; sysv4 | sysv4.3*) version_type=linux # correct to gnu/linux during the next big refactor library_names_spec='$libname$release$shared_ext$versuffix $libname$release$shared_ext$major $libname$shared_ext' soname_spec='$libname$release$shared_ext$major' shlibpath_var=LD_LIBRARY_PATH case $host_vendor in sni) shlibpath_overrides_runpath=no need_lib_prefix=no runpath_var=LD_RUN_PATH ;; siemens) need_lib_prefix=no ;; motorola) need_lib_prefix=no need_version=no shlibpath_overrides_runpath=no sys_lib_search_path_spec='/lib /usr/lib /usr/ccs/lib' ;; esac ;; sysv4*MP*) if test -d /usr/nec; then version_type=linux # correct to gnu/linux during the next big refactor library_names_spec='$libname$shared_ext.$versuffix $libname$shared_ext.$major $libname$shared_ext' soname_spec='$libname$shared_ext.$major' shlibpath_var=LD_LIBRARY_PATH fi ;; sysv5* | sco3.2v5* | sco5v6* | unixware* | OpenUNIX* | sysv4*uw2*) version_type=sco need_lib_prefix=no need_version=no library_names_spec='$libname$release$shared_ext$versuffix $libname$release$shared_ext $libname$shared_ext' soname_spec='$libname$release$shared_ext$major' shlibpath_var=LD_LIBRARY_PATH shlibpath_overrides_runpath=yes hardcode_into_libs=yes if test yes = "$with_gnu_ld"; then sys_lib_search_path_spec='/usr/local/lib /usr/gnu/lib /usr/ccs/lib /usr/lib /lib' else sys_lib_search_path_spec='/usr/ccs/lib /usr/lib' case $host_os in sco3.2v5*) sys_lib_search_path_spec="$sys_lib_search_path_spec /lib" ;; esac fi sys_lib_dlsearch_path_spec='/usr/lib' ;; tpf*) # TPF is a cross-target only. Preferred cross-host = GNU/Linux. version_type=linux # correct to gnu/linux during the next big refactor need_lib_prefix=no need_version=no library_names_spec='$libname$release$shared_ext$versuffix $libname$release$shared_ext$major $libname$shared_ext' shlibpath_var=LD_LIBRARY_PATH shlibpath_overrides_runpath=no hardcode_into_libs=yes ;; uts4*) version_type=linux # correct to gnu/linux during the next big refactor library_names_spec='$libname$release$shared_ext$versuffix $libname$release$shared_ext$major $libname$shared_ext' soname_spec='$libname$release$shared_ext$major' shlibpath_var=LD_LIBRARY_PATH ;; *) dynamic_linker=no ;; esac { $as_echo "$as_me:${as_lineno-$LINENO}: result: $dynamic_linker" >&5 $as_echo "$dynamic_linker" >&6; } test no = "$dynamic_linker" && can_build_shared=no variables_saved_for_relink="PATH $shlibpath_var $runpath_var" if test yes = "$GCC"; then variables_saved_for_relink="$variables_saved_for_relink GCC_EXEC_PREFIX COMPILER_PATH LIBRARY_PATH" fi if test set = "${lt_cv_sys_lib_search_path_spec+set}"; then sys_lib_search_path_spec=$lt_cv_sys_lib_search_path_spec fi if test set = "${lt_cv_sys_lib_dlsearch_path_spec+set}"; then sys_lib_dlsearch_path_spec=$lt_cv_sys_lib_dlsearch_path_spec fi # remember unaugmented sys_lib_dlsearch_path content for libtool script decls... configure_time_dlsearch_path=$sys_lib_dlsearch_path_spec # ... but it needs LT_SYS_LIBRARY_PATH munging for other configure-time code func_munge_path_list sys_lib_dlsearch_path_spec "$LT_SYS_LIBRARY_PATH" # to be used as default LT_SYS_LIBRARY_PATH value in generated libtool configure_time_lt_sys_library_path=$LT_SYS_LIBRARY_PATH { $as_echo "$as_me:${as_lineno-$LINENO}: checking how to hardcode library paths into programs" >&5 $as_echo_n "checking how to hardcode library paths into programs... " >&6; } hardcode_action= if test -n "$hardcode_libdir_flag_spec" || test -n "$runpath_var" || test yes = "$hardcode_automatic"; then # We can hardcode non-existent directories. if test no != "$hardcode_direct" && # If the only mechanism to avoid hardcoding is shlibpath_var, we # have to relink, otherwise we might link with an installed library # when we should be linking with a yet-to-be-installed one ## test no != "$_LT_TAGVAR(hardcode_shlibpath_var, )" && test no != "$hardcode_minus_L"; then # Linking always hardcodes the temporary library directory. hardcode_action=relink else # We can link without hardcoding, and we can hardcode nonexisting dirs. hardcode_action=immediate fi else # We cannot hardcode anything, or else we can only hardcode existing # directories. hardcode_action=unsupported fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $hardcode_action" >&5 $as_echo "$hardcode_action" >&6; } if test relink = "$hardcode_action" || test yes = "$inherit_rpath"; then # Fast installation is not supported enable_fast_install=no elif test yes = "$shlibpath_overrides_runpath" || test no = "$enable_shared"; then # Fast installation is not necessary enable_fast_install=needless fi if test yes != "$enable_dlopen"; then enable_dlopen=unknown enable_dlopen_self=unknown enable_dlopen_self_static=unknown else lt_cv_dlopen=no lt_cv_dlopen_libs= case $host_os in beos*) lt_cv_dlopen=load_add_on lt_cv_dlopen_libs= lt_cv_dlopen_self=yes ;; mingw* | pw32* | cegcc*) lt_cv_dlopen=LoadLibrary lt_cv_dlopen_libs= ;; cygwin*) lt_cv_dlopen=dlopen lt_cv_dlopen_libs= ;; darwin*) # if libdl is installed we need to link against it { $as_echo "$as_me:${as_lineno-$LINENO}: checking for dlopen in -ldl" >&5 $as_echo_n "checking for dlopen in -ldl... " >&6; } if ${ac_cv_lib_dl_dlopen+:} false; then : $as_echo_n "(cached) " >&6 else ac_check_lib_save_LIBS=$LIBS LIBS="-ldl $LIBS" cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ /* Override any GCC internal prototype to avoid an error. Use char because int might match the return type of a GCC builtin and then its argument prototype would still apply. */ #ifdef __cplusplus extern "C" #endif char dlopen (); int main () { return dlopen (); ; return 0; } _ACEOF if ac_fn_c_try_link "$LINENO"; then : ac_cv_lib_dl_dlopen=yes else ac_cv_lib_dl_dlopen=no fi rm -f core conftest.err conftest.$ac_objext \ conftest$ac_exeext conftest.$ac_ext LIBS=$ac_check_lib_save_LIBS fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_dl_dlopen" >&5 $as_echo "$ac_cv_lib_dl_dlopen" >&6; } if test "x$ac_cv_lib_dl_dlopen" = xyes; then : lt_cv_dlopen=dlopen lt_cv_dlopen_libs=-ldl else lt_cv_dlopen=dyld lt_cv_dlopen_libs= lt_cv_dlopen_self=yes fi ;; tpf*) # Don't try to run any link tests for TPF. We know it's impossible # because TPF is a cross-compiler, and we know how we open DSOs. lt_cv_dlopen=dlopen lt_cv_dlopen_libs= lt_cv_dlopen_self=no ;; *) ac_fn_c_check_func "$LINENO" "shl_load" "ac_cv_func_shl_load" if test "x$ac_cv_func_shl_load" = xyes; then : lt_cv_dlopen=shl_load else { $as_echo "$as_me:${as_lineno-$LINENO}: checking for shl_load in -ldld" >&5 $as_echo_n "checking for shl_load in -ldld... " >&6; } if ${ac_cv_lib_dld_shl_load+:} false; then : $as_echo_n "(cached) " >&6 else ac_check_lib_save_LIBS=$LIBS LIBS="-ldld $LIBS" cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ /* Override any GCC internal prototype to avoid an error. Use char because int might match the return type of a GCC builtin and then its argument prototype would still apply. */ #ifdef __cplusplus extern "C" #endif char shl_load (); int main () { return shl_load (); ; return 0; } _ACEOF if ac_fn_c_try_link "$LINENO"; then : ac_cv_lib_dld_shl_load=yes else ac_cv_lib_dld_shl_load=no fi rm -f core conftest.err conftest.$ac_objext \ conftest$ac_exeext conftest.$ac_ext LIBS=$ac_check_lib_save_LIBS fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_dld_shl_load" >&5 $as_echo "$ac_cv_lib_dld_shl_load" >&6; } if test "x$ac_cv_lib_dld_shl_load" = xyes; then : lt_cv_dlopen=shl_load lt_cv_dlopen_libs=-ldld else ac_fn_c_check_func "$LINENO" "dlopen" "ac_cv_func_dlopen" if test "x$ac_cv_func_dlopen" = xyes; then : lt_cv_dlopen=dlopen else { $as_echo "$as_me:${as_lineno-$LINENO}: checking for dlopen in -ldl" >&5 $as_echo_n "checking for dlopen in -ldl... " >&6; } if ${ac_cv_lib_dl_dlopen+:} false; then : $as_echo_n "(cached) " >&6 else ac_check_lib_save_LIBS=$LIBS LIBS="-ldl $LIBS" cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ /* Override any GCC internal prototype to avoid an error. Use char because int might match the return type of a GCC builtin and then its argument prototype would still apply. */ #ifdef __cplusplus extern "C" #endif char dlopen (); int main () { return dlopen (); ; return 0; } _ACEOF if ac_fn_c_try_link "$LINENO"; then : ac_cv_lib_dl_dlopen=yes else ac_cv_lib_dl_dlopen=no fi rm -f core conftest.err conftest.$ac_objext \ conftest$ac_exeext conftest.$ac_ext LIBS=$ac_check_lib_save_LIBS fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_dl_dlopen" >&5 $as_echo "$ac_cv_lib_dl_dlopen" >&6; } if test "x$ac_cv_lib_dl_dlopen" = xyes; then : lt_cv_dlopen=dlopen lt_cv_dlopen_libs=-ldl else { $as_echo "$as_me:${as_lineno-$LINENO}: checking for dlopen in -lsvld" >&5 $as_echo_n "checking for dlopen in -lsvld... " >&6; } if ${ac_cv_lib_svld_dlopen+:} false; then : $as_echo_n "(cached) " >&6 else ac_check_lib_save_LIBS=$LIBS LIBS="-lsvld $LIBS" cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ /* Override any GCC internal prototype to avoid an error. Use char because int might match the return type of a GCC builtin and then its argument prototype would still apply. */ #ifdef __cplusplus extern "C" #endif char dlopen (); int main () { return dlopen (); ; return 0; } _ACEOF if ac_fn_c_try_link "$LINENO"; then : ac_cv_lib_svld_dlopen=yes else ac_cv_lib_svld_dlopen=no fi rm -f core conftest.err conftest.$ac_objext \ conftest$ac_exeext conftest.$ac_ext LIBS=$ac_check_lib_save_LIBS fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_svld_dlopen" >&5 $as_echo "$ac_cv_lib_svld_dlopen" >&6; } if test "x$ac_cv_lib_svld_dlopen" = xyes; then : lt_cv_dlopen=dlopen lt_cv_dlopen_libs=-lsvld else { $as_echo "$as_me:${as_lineno-$LINENO}: checking for dld_link in -ldld" >&5 $as_echo_n "checking for dld_link in -ldld... " >&6; } if ${ac_cv_lib_dld_dld_link+:} false; then : $as_echo_n "(cached) " >&6 else ac_check_lib_save_LIBS=$LIBS LIBS="-ldld $LIBS" cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ /* Override any GCC internal prototype to avoid an error. Use char because int might match the return type of a GCC builtin and then its argument prototype would still apply. */ #ifdef __cplusplus extern "C" #endif char dld_link (); int main () { return dld_link (); ; return 0; } _ACEOF if ac_fn_c_try_link "$LINENO"; then : ac_cv_lib_dld_dld_link=yes else ac_cv_lib_dld_dld_link=no fi rm -f core conftest.err conftest.$ac_objext \ conftest$ac_exeext conftest.$ac_ext LIBS=$ac_check_lib_save_LIBS fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_dld_dld_link" >&5 $as_echo "$ac_cv_lib_dld_dld_link" >&6; } if test "x$ac_cv_lib_dld_dld_link" = xyes; then : lt_cv_dlopen=dld_link lt_cv_dlopen_libs=-ldld fi fi fi fi fi fi ;; esac if test no = "$lt_cv_dlopen"; then enable_dlopen=no else enable_dlopen=yes fi case $lt_cv_dlopen in dlopen) save_CPPFLAGS=$CPPFLAGS test yes = "$ac_cv_header_dlfcn_h" && CPPFLAGS="$CPPFLAGS -DHAVE_DLFCN_H" save_LDFLAGS=$LDFLAGS wl=$lt_prog_compiler_wl eval LDFLAGS=\"\$LDFLAGS $export_dynamic_flag_spec\" save_LIBS=$LIBS LIBS="$lt_cv_dlopen_libs $LIBS" { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether a program can dlopen itself" >&5 $as_echo_n "checking whether a program can dlopen itself... " >&6; } if ${lt_cv_dlopen_self+:} false; then : $as_echo_n "(cached) " >&6 else if test yes = "$cross_compiling"; then : lt_cv_dlopen_self=cross else lt_dlunknown=0; lt_dlno_uscore=1; lt_dlneed_uscore=2 lt_status=$lt_dlunknown cat > conftest.$ac_ext <<_LT_EOF #line $LINENO "configure" #include "confdefs.h" #if HAVE_DLFCN_H #include #endif #include #ifdef RTLD_GLOBAL # define LT_DLGLOBAL RTLD_GLOBAL #else # ifdef DL_GLOBAL # define LT_DLGLOBAL DL_GLOBAL # else # define LT_DLGLOBAL 0 # endif #endif /* We may have to define LT_DLLAZY_OR_NOW in the command line if we find out it does not work in some platform. */ #ifndef LT_DLLAZY_OR_NOW # ifdef RTLD_LAZY # define LT_DLLAZY_OR_NOW RTLD_LAZY # else # ifdef DL_LAZY # define LT_DLLAZY_OR_NOW DL_LAZY # else # ifdef RTLD_NOW # define LT_DLLAZY_OR_NOW RTLD_NOW # else # ifdef DL_NOW # define LT_DLLAZY_OR_NOW DL_NOW # else # define LT_DLLAZY_OR_NOW 0 # endif # endif # endif # endif #endif /* When -fvisibility=hidden is used, assume the code has been annotated correspondingly for the symbols needed. */ #if defined __GNUC__ && (((__GNUC__ == 3) && (__GNUC_MINOR__ >= 3)) || (__GNUC__ > 3)) int fnord () __attribute__((visibility("default"))); #endif int fnord () { return 42; } int main () { void *self = dlopen (0, LT_DLGLOBAL|LT_DLLAZY_OR_NOW); int status = $lt_dlunknown; if (self) { if (dlsym (self,"fnord")) status = $lt_dlno_uscore; else { if (dlsym( self,"_fnord")) status = $lt_dlneed_uscore; else puts (dlerror ()); } /* dlclose (self); */ } else puts (dlerror ()); return status; } _LT_EOF if { { eval echo "\"\$as_me\":${as_lineno-$LINENO}: \"$ac_link\""; } >&5 (eval $ac_link) 2>&5 ac_status=$? $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 test $ac_status = 0; } && test -s "conftest$ac_exeext" 2>/dev/null; then (./conftest; exit; ) >&5 2>/dev/null lt_status=$? case x$lt_status in x$lt_dlno_uscore) lt_cv_dlopen_self=yes ;; x$lt_dlneed_uscore) lt_cv_dlopen_self=yes ;; x$lt_dlunknown|x*) lt_cv_dlopen_self=no ;; esac else : # compilation failed lt_cv_dlopen_self=no fi fi rm -fr conftest* fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_dlopen_self" >&5 $as_echo "$lt_cv_dlopen_self" >&6; } if test yes = "$lt_cv_dlopen_self"; then wl=$lt_prog_compiler_wl eval LDFLAGS=\"\$LDFLAGS $lt_prog_compiler_static\" { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether a statically linked program can dlopen itself" >&5 $as_echo_n "checking whether a statically linked program can dlopen itself... " >&6; } if ${lt_cv_dlopen_self_static+:} false; then : $as_echo_n "(cached) " >&6 else if test yes = "$cross_compiling"; then : lt_cv_dlopen_self_static=cross else lt_dlunknown=0; lt_dlno_uscore=1; lt_dlneed_uscore=2 lt_status=$lt_dlunknown cat > conftest.$ac_ext <<_LT_EOF #line $LINENO "configure" #include "confdefs.h" #if HAVE_DLFCN_H #include #endif #include #ifdef RTLD_GLOBAL # define LT_DLGLOBAL RTLD_GLOBAL #else # ifdef DL_GLOBAL # define LT_DLGLOBAL DL_GLOBAL # else # define LT_DLGLOBAL 0 # endif #endif /* We may have to define LT_DLLAZY_OR_NOW in the command line if we find out it does not work in some platform. */ #ifndef LT_DLLAZY_OR_NOW # ifdef RTLD_LAZY # define LT_DLLAZY_OR_NOW RTLD_LAZY # else # ifdef DL_LAZY # define LT_DLLAZY_OR_NOW DL_LAZY # else # ifdef RTLD_NOW # define LT_DLLAZY_OR_NOW RTLD_NOW # else # ifdef DL_NOW # define LT_DLLAZY_OR_NOW DL_NOW # else # define LT_DLLAZY_OR_NOW 0 # endif # endif # endif # endif #endif /* When -fvisibility=hidden is used, assume the code has been annotated correspondingly for the symbols needed. */ #if defined __GNUC__ && (((__GNUC__ == 3) && (__GNUC_MINOR__ >= 3)) || (__GNUC__ > 3)) int fnord () __attribute__((visibility("default"))); #endif int fnord () { return 42; } int main () { void *self = dlopen (0, LT_DLGLOBAL|LT_DLLAZY_OR_NOW); int status = $lt_dlunknown; if (self) { if (dlsym (self,"fnord")) status = $lt_dlno_uscore; else { if (dlsym( self,"_fnord")) status = $lt_dlneed_uscore; else puts (dlerror ()); } /* dlclose (self); */ } else puts (dlerror ()); return status; } _LT_EOF if { { eval echo "\"\$as_me\":${as_lineno-$LINENO}: \"$ac_link\""; } >&5 (eval $ac_link) 2>&5 ac_status=$? $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 test $ac_status = 0; } && test -s "conftest$ac_exeext" 2>/dev/null; then (./conftest; exit; ) >&5 2>/dev/null lt_status=$? case x$lt_status in x$lt_dlno_uscore) lt_cv_dlopen_self_static=yes ;; x$lt_dlneed_uscore) lt_cv_dlopen_self_static=yes ;; x$lt_dlunknown|x*) lt_cv_dlopen_self_static=no ;; esac else : # compilation failed lt_cv_dlopen_self_static=no fi fi rm -fr conftest* fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_dlopen_self_static" >&5 $as_echo "$lt_cv_dlopen_self_static" >&6; } fi CPPFLAGS=$save_CPPFLAGS LDFLAGS=$save_LDFLAGS LIBS=$save_LIBS ;; esac case $lt_cv_dlopen_self in yes|no) enable_dlopen_self=$lt_cv_dlopen_self ;; *) enable_dlopen_self=unknown ;; esac case $lt_cv_dlopen_self_static in yes|no) enable_dlopen_self_static=$lt_cv_dlopen_self_static ;; *) enable_dlopen_self_static=unknown ;; esac fi striplib= old_striplib= { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether stripping libraries is possible" >&5 $as_echo_n "checking whether stripping libraries is possible... " >&6; } if test -n "$STRIP" && $STRIP -V 2>&1 | $GREP "GNU strip" >/dev/null; then test -z "$old_striplib" && old_striplib="$STRIP --strip-debug" test -z "$striplib" && striplib="$STRIP --strip-unneeded" { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 $as_echo "yes" >&6; } else # FIXME - insert some real tests, host_os isn't really good enough case $host_os in darwin*) if test -n "$STRIP"; then striplib="$STRIP -x" old_striplib="$STRIP -S" { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 $as_echo "yes" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi ;; *) { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } ;; esac fi # Report what library types will actually be built { $as_echo "$as_me:${as_lineno-$LINENO}: checking if libtool supports shared libraries" >&5 $as_echo_n "checking if libtool supports shared libraries... " >&6; } { $as_echo "$as_me:${as_lineno-$LINENO}: result: $can_build_shared" >&5 $as_echo "$can_build_shared" >&6; } { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether to build shared libraries" >&5 $as_echo_n "checking whether to build shared libraries... " >&6; } test no = "$can_build_shared" && enable_shared=no # On AIX, shared libraries and static libraries use the same namespace, and # are all built from PIC. case $host_os in aix3*) test yes = "$enable_shared" && enable_static=no if test -n "$RANLIB"; then archive_cmds="$archive_cmds~\$RANLIB \$lib" postinstall_cmds='$RANLIB $lib' fi ;; aix[4-9]*) if test ia64 != "$host_cpu"; then case $enable_shared,$with_aix_soname,$aix_use_runtimelinking in yes,aix,yes) ;; # shared object as lib.so file only yes,svr4,*) ;; # shared object as lib.so archive member only yes,*) enable_static=no ;; # shared object in lib.a archive as well esac fi ;; esac { $as_echo "$as_me:${as_lineno-$LINENO}: result: $enable_shared" >&5 $as_echo "$enable_shared" >&6; } { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether to build static libraries" >&5 $as_echo_n "checking whether to build static libraries... " >&6; } # Make sure either enable_shared or enable_static is yes. test yes = "$enable_shared" || enable_static=yes { $as_echo "$as_me:${as_lineno-$LINENO}: result: $enable_static" >&5 $as_echo "$enable_static" >&6; } fi ac_ext=c ac_cpp='$CPP $CPPFLAGS' ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' ac_compiler_gnu=$ac_cv_c_compiler_gnu CC=$lt_save_CC ac_config_commands="$ac_config_commands libtool" # Only expand once: # libtool -version-info LT_VERSION=0:36:0 # Check whether --enable-silent-rules was given. if test "${enable_silent_rules+set}" = set; then : enableval=$enable_silent_rules; fi case $enable_silent_rules in # ((( yes) AM_DEFAULT_VERBOSITY=0;; no) AM_DEFAULT_VERBOSITY=1;; *) AM_DEFAULT_VERBOSITY=0;; esac am_make=${MAKE-make} { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether $am_make supports nested variables" >&5 $as_echo_n "checking whether $am_make supports nested variables... " >&6; } if ${am_cv_make_support_nested_variables+:} false; then : $as_echo_n "(cached) " >&6 else if $as_echo 'TRUE=$(BAR$(V)) BAR0=false BAR1=true V=1 am__doit: @$(TRUE) .PHONY: am__doit' | $am_make -f - >/dev/null 2>&1; then am_cv_make_support_nested_variables=yes else am_cv_make_support_nested_variables=no fi fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $am_cv_make_support_nested_variables" >&5 $as_echo "$am_cv_make_support_nested_variables" >&6; } if test $am_cv_make_support_nested_variables = yes; then AM_V='$(V)' AM_DEFAULT_V='$(AM_DEFAULT_VERBOSITY)' else AM_V=$AM_DEFAULT_VERBOSITY AM_DEFAULT_V=$AM_DEFAULT_VERBOSITY fi AM_BACKSLASH='\' # Checks for programs. { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $CC option to accept ISO C99" >&5 $as_echo_n "checking for $CC option to accept ISO C99... " >&6; } if ${ac_cv_prog_cc_c99+:} false; then : $as_echo_n "(cached) " >&6 else ac_cv_prog_cc_c99=no ac_save_CC=$CC cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #include #include #include #include #include // Check varargs macros. These examples are taken from C99 6.10.3.5. #define debug(...) fprintf (stderr, __VA_ARGS__) #define showlist(...) puts (#__VA_ARGS__) #define report(test,...) ((test) ? puts (#test) : printf (__VA_ARGS__)) static void test_varargs_macros (void) { int x = 1234; int y = 5678; debug ("Flag"); debug ("X = %d\n", x); showlist (The first, second, and third items.); report (x>y, "x is %d but y is %d", x, y); } // Check long long types. #define BIG64 18446744073709551615ull #define BIG32 4294967295ul #define BIG_OK (BIG64 / BIG32 == 4294967297ull && BIG64 % BIG32 == 0) #if !BIG_OK your preprocessor is broken; #endif #if BIG_OK #else your preprocessor is broken; #endif static long long int bignum = -9223372036854775807LL; static unsigned long long int ubignum = BIG64; struct incomplete_array { int datasize; double data[]; }; struct named_init { int number; const wchar_t *name; double average; }; typedef const char *ccp; static inline int test_restrict (ccp restrict text) { // See if C++-style comments work. // Iterate through items via the restricted pointer. // Also check for declarations in for loops. for (unsigned int i = 0; *(text+i) != '\0'; ++i) continue; return 0; } // Check varargs and va_copy. static void test_varargs (const char *format, ...) { va_list args; va_start (args, format); va_list args_copy; va_copy (args_copy, args); const char *str; int number; float fnumber; while (*format) { switch (*format++) { case 's': // string str = va_arg (args_copy, const char *); break; case 'd': // int number = va_arg (args_copy, int); break; case 'f': // float fnumber = va_arg (args_copy, double); break; default: break; } } va_end (args_copy); va_end (args); } int main () { // Check bool. _Bool success = false; // Check restrict. if (test_restrict ("String literal") == 0) success = true; char *restrict newvar = "Another string"; // Check varargs. test_varargs ("s, d' f .", "string", 65, 34.234); test_varargs_macros (); // Check flexible array members. struct incomplete_array *ia = malloc (sizeof (struct incomplete_array) + (sizeof (double) * 10)); ia->datasize = 10; for (int i = 0; i < ia->datasize; ++i) ia->data[i] = i * 1.234; // Check named initializers. struct named_init ni = { .number = 34, .name = L"Test wide string", .average = 543.34343, }; ni.number = 58; int dynamic_array[ni.number]; dynamic_array[ni.number - 1] = 543; // work around unused variable warnings return (!success || bignum == 0LL || ubignum == 0uLL || newvar[0] == 'x' || dynamic_array[ni.number - 1] != 543); ; return 0; } _ACEOF for ac_arg in '' -std=gnu99 -std=c99 -c99 -AC99 -D_STDC_C99= -qlanglvl=extc99 do CC="$ac_save_CC $ac_arg" if ac_fn_c_try_compile "$LINENO"; then : ac_cv_prog_cc_c99=$ac_arg fi rm -f core conftest.err conftest.$ac_objext test "x$ac_cv_prog_cc_c99" != "xno" && break done rm -f conftest.$ac_ext CC=$ac_save_CC fi # AC_CACHE_VAL case "x$ac_cv_prog_cc_c99" in x) { $as_echo "$as_me:${as_lineno-$LINENO}: result: none needed" >&5 $as_echo "none needed" >&6; } ;; xno) { $as_echo "$as_me:${as_lineno-$LINENO}: result: unsupported" >&5 $as_echo "unsupported" >&6; } ;; *) CC="$CC $ac_cv_prog_cc_c99" { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_prog_cc_c99" >&5 $as_echo "$ac_cv_prog_cc_c99" >&6; } ;; esac if test "x$ac_cv_prog_cc_c99" != xno; then : fi #AC_PROG_CC { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether ln -s works" >&5 $as_echo_n "checking whether ln -s works... " >&6; } LN_S=$as_ln_s if test "$LN_S" = "ln -s"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 $as_echo "yes" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no, using $LN_S" >&5 $as_echo "no, using $LN_S" >&6; } fi for ac_prog in gawk mawk nawk awk do # Extract the first word of "$ac_prog", so it can be a program name with args. set dummy $ac_prog; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if ${ac_cv_prog_AWK+:} false; then : $as_echo_n "(cached) " >&6 else if test -n "$AWK"; then ac_cv_prog_AWK="$AWK" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then ac_cv_prog_AWK="$ac_prog" $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi fi AWK=$ac_cv_prog_AWK if test -n "$AWK"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $AWK" >&5 $as_echo "$AWK" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi test -n "$AWK" && break done MANTYPE= TestPath="/usr/bin${PATH_SEPARATOR}/usr/ucb" for ac_prog in nroff awf do # Extract the first word of "$ac_prog", so it can be a program name with args. set dummy $ac_prog; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if ${ac_cv_path_NROFF+:} false; then : $as_echo_n "(cached) " >&6 else case $NROFF in [\\/]* | ?:[\\/]*) ac_cv_path_NROFF="$NROFF" # Let the user override the test with a path. ;; *) as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $TestPath do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then ac_cv_path_NROFF="$as_dir/$ac_word$ac_exec_ext" $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS ;; esac fi NROFF=$ac_cv_path_NROFF if test -n "$NROFF"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $NROFF" >&5 $as_echo "$NROFF" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi test -n "$NROFF" && break done test -n "$NROFF" || NROFF="/bin/false" if ${NROFF} -mdoc ${srcdir}/doc/editrc.5.roff >/dev/null 2>&1; then MANTYPE=mdoc fi { $as_echo "$as_me:${as_lineno-$LINENO}: checking for tgetent in -lcurses" >&5 $as_echo_n "checking for tgetent in -lcurses... " >&6; } if ${ac_cv_lib_curses_tgetent+:} false; then : $as_echo_n "(cached) " >&6 else ac_check_lib_save_LIBS=$LIBS LIBS="-lcurses $LIBS" cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ /* Override any GCC internal prototype to avoid an error. Use char because int might match the return type of a GCC builtin and then its argument prototype would still apply. */ #ifdef __cplusplus extern "C" #endif char tgetent (); int main () { return tgetent (); ; return 0; } _ACEOF if ac_fn_c_try_link "$LINENO"; then : ac_cv_lib_curses_tgetent=yes else ac_cv_lib_curses_tgetent=no fi rm -f core conftest.err conftest.$ac_objext \ conftest$ac_exeext conftest.$ac_ext LIBS=$ac_check_lib_save_LIBS fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_curses_tgetent" >&5 $as_echo "$ac_cv_lib_curses_tgetent" >&6; } if test "x$ac_cv_lib_curses_tgetent" = xyes; then : cat >>confdefs.h <<_ACEOF #define HAVE_LIBCURSES 1 _ACEOF LIBS="-lcurses $LIBS" else { $as_echo "$as_me:${as_lineno-$LINENO}: checking for tgetent in -lncurses" >&5 $as_echo_n "checking for tgetent in -lncurses... " >&6; } if ${ac_cv_lib_ncurses_tgetent+:} false; then : $as_echo_n "(cached) " >&6 else ac_check_lib_save_LIBS=$LIBS LIBS="-lncurses $LIBS" cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ /* Override any GCC internal prototype to avoid an error. Use char because int might match the return type of a GCC builtin and then its argument prototype would still apply. */ #ifdef __cplusplus extern "C" #endif char tgetent (); int main () { return tgetent (); ; return 0; } _ACEOF if ac_fn_c_try_link "$LINENO"; then : ac_cv_lib_ncurses_tgetent=yes else ac_cv_lib_ncurses_tgetent=no fi rm -f core conftest.err conftest.$ac_objext \ conftest$ac_exeext conftest.$ac_ext LIBS=$ac_check_lib_save_LIBS fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_ncurses_tgetent" >&5 $as_echo "$ac_cv_lib_ncurses_tgetent" >&6; } if test "x$ac_cv_lib_ncurses_tgetent" = xyes; then : cat >>confdefs.h <<_ACEOF #define HAVE_LIBNCURSES 1 _ACEOF LIBS="-lncurses $LIBS" else as_fn_error $? "libcurses or libncurses are required!" "$LINENO" 5 fi fi # Checks for header files. ac_header_dirent=no for ac_hdr in dirent.h sys/ndir.h sys/dir.h ndir.h; do as_ac_Header=`$as_echo "ac_cv_header_dirent_$ac_hdr" | $as_tr_sh` { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_hdr that defines DIR" >&5 $as_echo_n "checking for $ac_hdr that defines DIR... " >&6; } if eval \${$as_ac_Header+:} false; then : $as_echo_n "(cached) " >&6 else cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #include #include <$ac_hdr> int main () { if ((DIR *) 0) return 0; ; return 0; } _ACEOF if ac_fn_c_try_compile "$LINENO"; then : eval "$as_ac_Header=yes" else eval "$as_ac_Header=no" fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext fi eval ac_res=\$$as_ac_Header { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_res" >&5 $as_echo "$ac_res" >&6; } if eval test \"x\$"$as_ac_Header"\" = x"yes"; then : cat >>confdefs.h <<_ACEOF #define `$as_echo "HAVE_$ac_hdr" | $as_tr_cpp` 1 _ACEOF ac_header_dirent=$ac_hdr; break fi done # Two versions of opendir et al. are in -ldir and -lx on SCO Xenix. if test $ac_header_dirent = dirent.h; then { $as_echo "$as_me:${as_lineno-$LINENO}: checking for library containing opendir" >&5 $as_echo_n "checking for library containing opendir... " >&6; } if ${ac_cv_search_opendir+:} false; then : $as_echo_n "(cached) " >&6 else ac_func_search_save_LIBS=$LIBS cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ /* Override any GCC internal prototype to avoid an error. Use char because int might match the return type of a GCC builtin and then its argument prototype would still apply. */ #ifdef __cplusplus extern "C" #endif char opendir (); int main () { return opendir (); ; return 0; } _ACEOF for ac_lib in '' dir; do if test -z "$ac_lib"; then ac_res="none required" else ac_res=-l$ac_lib LIBS="-l$ac_lib $ac_func_search_save_LIBS" fi if ac_fn_c_try_link "$LINENO"; then : ac_cv_search_opendir=$ac_res fi rm -f core conftest.err conftest.$ac_objext \ conftest$ac_exeext if ${ac_cv_search_opendir+:} false; then : break fi done if ${ac_cv_search_opendir+:} false; then : else ac_cv_search_opendir=no fi rm conftest.$ac_ext LIBS=$ac_func_search_save_LIBS fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_search_opendir" >&5 $as_echo "$ac_cv_search_opendir" >&6; } ac_res=$ac_cv_search_opendir if test "$ac_res" != no; then : test "$ac_res" = "none required" || LIBS="$ac_res $LIBS" fi else { $as_echo "$as_me:${as_lineno-$LINENO}: checking for library containing opendir" >&5 $as_echo_n "checking for library containing opendir... " >&6; } if ${ac_cv_search_opendir+:} false; then : $as_echo_n "(cached) " >&6 else ac_func_search_save_LIBS=$LIBS cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ /* Override any GCC internal prototype to avoid an error. Use char because int might match the return type of a GCC builtin and then its argument prototype would still apply. */ #ifdef __cplusplus extern "C" #endif char opendir (); int main () { return opendir (); ; return 0; } _ACEOF for ac_lib in '' x; do if test -z "$ac_lib"; then ac_res="none required" else ac_res=-l$ac_lib LIBS="-l$ac_lib $ac_func_search_save_LIBS" fi if ac_fn_c_try_link "$LINENO"; then : ac_cv_search_opendir=$ac_res fi rm -f core conftest.err conftest.$ac_objext \ conftest$ac_exeext if ${ac_cv_search_opendir+:} false; then : break fi done if ${ac_cv_search_opendir+:} false; then : else ac_cv_search_opendir=no fi rm conftest.$ac_ext LIBS=$ac_func_search_save_LIBS fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_search_opendir" >&5 $as_echo "$ac_cv_search_opendir" >&6; } ac_res=$ac_cv_search_opendir if test "$ac_res" != no; then : test "$ac_res" = "none required" || LIBS="$ac_res $LIBS" fi fi { $as_echo "$as_me:${as_lineno-$LINENO}: checking for ANSI C header files" >&5 $as_echo_n "checking for ANSI C header files... " >&6; } if ${ac_cv_header_stdc+:} false; then : $as_echo_n "(cached) " >&6 else cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #include #include #include #include int main () { ; return 0; } _ACEOF if ac_fn_c_try_compile "$LINENO"; then : ac_cv_header_stdc=yes else ac_cv_header_stdc=no fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext if test $ac_cv_header_stdc = yes; then # SunOS 4.x string.h does not declare mem*, contrary to ANSI. cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #include _ACEOF if (eval "$ac_cpp conftest.$ac_ext") 2>&5 | $EGREP "memchr" >/dev/null 2>&1; then : else ac_cv_header_stdc=no fi rm -f conftest* fi if test $ac_cv_header_stdc = yes; then # ISC 2.0.2 stdlib.h does not declare free, contrary to ANSI. cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #include _ACEOF if (eval "$ac_cpp conftest.$ac_ext") 2>&5 | $EGREP "free" >/dev/null 2>&1; then : else ac_cv_header_stdc=no fi rm -f conftest* fi if test $ac_cv_header_stdc = yes; then # /bin/cc in Irix-4.0.5 gets non-ANSI ctype macros unless using -ansi. if test "$cross_compiling" = yes; then : : else cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #include #include #if ((' ' & 0x0FF) == 0x020) # define ISLOWER(c) ('a' <= (c) && (c) <= 'z') # define TOUPPER(c) (ISLOWER(c) ? 'A' + ((c) - 'a') : (c)) #else # define ISLOWER(c) \ (('a' <= (c) && (c) <= 'i') \ || ('j' <= (c) && (c) <= 'r') \ || ('s' <= (c) && (c) <= 'z')) # define TOUPPER(c) (ISLOWER(c) ? ((c) | 0x40) : (c)) #endif #define XOR(e, f) (((e) && !(f)) || (!(e) && (f))) int main () { int i; for (i = 0; i < 256; i++) if (XOR (islower (i), ISLOWER (i)) || toupper (i) != TOUPPER (i)) return 2; return 0; } _ACEOF if ac_fn_c_try_run "$LINENO"; then : else ac_cv_header_stdc=no fi rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \ conftest.$ac_objext conftest.beam conftest.$ac_ext fi fi fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_header_stdc" >&5 $as_echo "$ac_cv_header_stdc" >&6; } if test $ac_cv_header_stdc = yes; then $as_echo "#define STDC_HEADERS 1" >>confdefs.h fi { $as_echo "$as_me:${as_lineno-$LINENO}: checking for sys/wait.h that is POSIX.1 compatible" >&5 $as_echo_n "checking for sys/wait.h that is POSIX.1 compatible... " >&6; } if ${ac_cv_header_sys_wait_h+:} false; then : $as_echo_n "(cached) " >&6 else cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #include #include #ifndef WEXITSTATUS # define WEXITSTATUS(stat_val) ((unsigned int) (stat_val) >> 8) #endif #ifndef WIFEXITED # define WIFEXITED(stat_val) (((stat_val) & 255) == 0) #endif int main () { int s; wait (&s); s = WIFEXITED (s) ? WEXITSTATUS (s) : 1; ; return 0; } _ACEOF if ac_fn_c_try_compile "$LINENO"; then : ac_cv_header_sys_wait_h=yes else ac_cv_header_sys_wait_h=no fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_header_sys_wait_h" >&5 $as_echo "$ac_cv_header_sys_wait_h" >&6; } if test $ac_cv_header_sys_wait_h = yes; then $as_echo "#define HAVE_SYS_WAIT_H 1" >>confdefs.h fi for ac_header in fcntl.h limits.h stdint.h stdlib.h string.h sys/ioctl.h sys/param.h unistd.h curses.h ncurses.h sys/cdefs.h do : as_ac_Header=`$as_echo "ac_cv_header_$ac_header" | $as_tr_sh` ac_fn_c_check_header_mongrel "$LINENO" "$ac_header" "$as_ac_Header" "$ac_includes_default" if eval test \"x\$"$as_ac_Header"\" = x"yes"; then : cat >>confdefs.h <<_ACEOF #define `$as_echo "HAVE_$ac_header" | $as_tr_cpp` 1 _ACEOF fi done ac_fn_c_check_header_mongrel "$LINENO" "termios.h" "ac_cv_header_termios_h" "$ac_includes_default" if test "x$ac_cv_header_termios_h" = xyes; then : else as_fn_error $? "termios.h is required!" "$LINENO" 5 fi ## include curses.h to prevent "Present But Cannot Be Compiled" for ac_header in term.h do : ac_fn_c_check_header_compile "$LINENO" "term.h" "ac_cv_header_term_h" "#if HAVE_CURSES_H # include #elif HAVE_NCURSES_H # include #endif " if test "x$ac_cv_header_term_h" = xyes; then : cat >>confdefs.h <<_ACEOF #define HAVE_TERM_H 1 _ACEOF fi done # Checks for typedefs, structures, and compiler characteristics. { $as_echo "$as_me:${as_lineno-$LINENO}: checking for an ANSI C-conforming const" >&5 $as_echo_n "checking for an ANSI C-conforming const... " >&6; } if ${ac_cv_c_const+:} false; then : $as_echo_n "(cached) " >&6 else cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ int main () { #ifndef __cplusplus /* Ultrix mips cc rejects this sort of thing. */ typedef int charset[2]; const charset cs = { 0, 0 }; /* SunOS 4.1.1 cc rejects this. */ char const *const *pcpcc; char **ppc; /* NEC SVR4.0.2 mips cc rejects this. */ struct point {int x, y;}; static struct point const zero = {0,0}; /* AIX XL C 1.02.0.0 rejects this. It does not let you subtract one const X* pointer from another in an arm of an if-expression whose if-part is not a constant expression */ const char *g = "string"; pcpcc = &g + (g ? g-g : 0); /* HPUX 7.0 cc rejects these. */ ++pcpcc; ppc = (char**) pcpcc; pcpcc = (char const *const *) ppc; { /* SCO 3.2v4 cc rejects this sort of thing. */ char tx; char *t = &tx; char const *s = 0 ? (char *) 0 : (char const *) 0; *t++ = 0; if (s) return 0; } { /* Someone thinks the Sun supposedly-ANSI compiler will reject this. */ int x[] = {25, 17}; const int *foo = &x[0]; ++foo; } { /* Sun SC1.0 ANSI compiler rejects this -- but not the above. */ typedef const int *iptr; iptr p = 0; ++p; } { /* AIX XL C 1.02.0.0 rejects this sort of thing, saying "k.c", line 2.27: 1506-025 (S) Operand must be a modifiable lvalue. */ struct s { int j; const int *ap[3]; } bx; struct s *b = &bx; b->j = 5; } { /* ULTRIX-32 V3.1 (Rev 9) vcc rejects this */ const int foo = 10; if (!foo) return 0; } return !cs[0] && !zero.x; #endif ; return 0; } _ACEOF if ac_fn_c_try_compile "$LINENO"; then : ac_cv_c_const=yes else ac_cv_c_const=no fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_c_const" >&5 $as_echo "$ac_cv_c_const" >&6; } if test $ac_cv_c_const = no; then $as_echo "#define const /**/" >>confdefs.h fi ac_fn_c_check_type "$LINENO" "pid_t" "ac_cv_type_pid_t" "$ac_includes_default" if test "x$ac_cv_type_pid_t" = xyes; then : else cat >>confdefs.h <<_ACEOF #define pid_t int _ACEOF fi ac_fn_c_check_type "$LINENO" "size_t" "ac_cv_type_size_t" "$ac_includes_default" if test "x$ac_cv_type_size_t" = xyes; then : else cat >>confdefs.h <<_ACEOF #define size_t unsigned int _ACEOF fi ac_fn_c_check_type "$LINENO" "u_int32_t" "ac_cv_type_u_int32_t" "$ac_includes_default" if test "x$ac_cv_type_u_int32_t" = xyes; then : cat >>confdefs.h <<_ACEOF #define HAVE_U_INT32_T 1 _ACEOF fi cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #include #include #if HAVE_STDINT_H # include #endif int main () { size_t x = SIZE_MAX; ; return 0; } _ACEOF if ac_fn_c_try_compile "$LINENO"; then : have_size_max=yes else have_size_max=no fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext if test "$have_size_max" = yes; then $as_echo "#define HAVE_SIZE_MAX 1" >>confdefs.h fi # Checks for library functions. for ac_header in vfork.h do : ac_fn_c_check_header_mongrel "$LINENO" "vfork.h" "ac_cv_header_vfork_h" "$ac_includes_default" if test "x$ac_cv_header_vfork_h" = xyes; then : cat >>confdefs.h <<_ACEOF #define HAVE_VFORK_H 1 _ACEOF fi done for ac_func in fork vfork do : as_ac_var=`$as_echo "ac_cv_func_$ac_func" | $as_tr_sh` ac_fn_c_check_func "$LINENO" "$ac_func" "$as_ac_var" if eval test \"x\$"$as_ac_var"\" = x"yes"; then : cat >>confdefs.h <<_ACEOF #define `$as_echo "HAVE_$ac_func" | $as_tr_cpp` 1 _ACEOF fi done if test "x$ac_cv_func_fork" = xyes; then { $as_echo "$as_me:${as_lineno-$LINENO}: checking for working fork" >&5 $as_echo_n "checking for working fork... " >&6; } if ${ac_cv_func_fork_works+:} false; then : $as_echo_n "(cached) " >&6 else if test "$cross_compiling" = yes; then : ac_cv_func_fork_works=cross else cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ $ac_includes_default int main () { /* By Ruediger Kuhlmann. */ return fork () < 0; ; return 0; } _ACEOF if ac_fn_c_try_run "$LINENO"; then : ac_cv_func_fork_works=yes else ac_cv_func_fork_works=no fi rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \ conftest.$ac_objext conftest.beam conftest.$ac_ext fi fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_func_fork_works" >&5 $as_echo "$ac_cv_func_fork_works" >&6; } else ac_cv_func_fork_works=$ac_cv_func_fork fi if test "x$ac_cv_func_fork_works" = xcross; then case $host in *-*-amigaos* | *-*-msdosdjgpp*) # Override, as these systems have only a dummy fork() stub ac_cv_func_fork_works=no ;; *) ac_cv_func_fork_works=yes ;; esac { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: result $ac_cv_func_fork_works guessed because of cross compilation" >&5 $as_echo "$as_me: WARNING: result $ac_cv_func_fork_works guessed because of cross compilation" >&2;} fi ac_cv_func_vfork_works=$ac_cv_func_vfork if test "x$ac_cv_func_vfork" = xyes; then { $as_echo "$as_me:${as_lineno-$LINENO}: checking for working vfork" >&5 $as_echo_n "checking for working vfork... " >&6; } if ${ac_cv_func_vfork_works+:} false; then : $as_echo_n "(cached) " >&6 else if test "$cross_compiling" = yes; then : ac_cv_func_vfork_works=cross else cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ /* Thanks to Paul Eggert for this test. */ $ac_includes_default #include #ifdef HAVE_VFORK_H # include #endif /* On some sparc systems, changes by the child to local and incoming argument registers are propagated back to the parent. The compiler is told about this with #include , but some compilers (e.g. gcc -O) don't grok . Test for this by using a static variable whose address is put into a register that is clobbered by the vfork. */ static void #ifdef __cplusplus sparc_address_test (int arg) # else sparc_address_test (arg) int arg; #endif { static pid_t child; if (!child) { child = vfork (); if (child < 0) { perror ("vfork"); _exit(2); } if (!child) { arg = getpid(); write(-1, "", 0); _exit (arg); } } } int main () { pid_t parent = getpid (); pid_t child; sparc_address_test (0); child = vfork (); if (child == 0) { /* Here is another test for sparc vfork register problems. This test uses lots of local variables, at least as many local variables as main has allocated so far including compiler temporaries. 4 locals are enough for gcc 1.40.3 on a Solaris 4.1.3 sparc, but we use 8 to be safe. A buggy compiler should reuse the register of parent for one of the local variables, since it will think that parent can't possibly be used any more in this routine. Assigning to the local variable will thus munge parent in the parent process. */ pid_t p = getpid(), p1 = getpid(), p2 = getpid(), p3 = getpid(), p4 = getpid(), p5 = getpid(), p6 = getpid(), p7 = getpid(); /* Convince the compiler that p..p7 are live; otherwise, it might use the same hardware register for all 8 local variables. */ if (p != p1 || p != p2 || p != p3 || p != p4 || p != p5 || p != p6 || p != p7) _exit(1); /* On some systems (e.g. IRIX 3.3), vfork doesn't separate parent from child file descriptors. If the child closes a descriptor before it execs or exits, this munges the parent's descriptor as well. Test for this by closing stdout in the child. */ _exit(close(fileno(stdout)) != 0); } else { int status; struct stat st; while (wait(&status) != child) ; return ( /* Was there some problem with vforking? */ child < 0 /* Did the child fail? (This shouldn't happen.) */ || status /* Did the vfork/compiler bug occur? */ || parent != getpid() /* Did the file descriptor bug occur? */ || fstat(fileno(stdout), &st) != 0 ); } } _ACEOF if ac_fn_c_try_run "$LINENO"; then : ac_cv_func_vfork_works=yes else ac_cv_func_vfork_works=no fi rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \ conftest.$ac_objext conftest.beam conftest.$ac_ext fi fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_func_vfork_works" >&5 $as_echo "$ac_cv_func_vfork_works" >&6; } fi; if test "x$ac_cv_func_fork_works" = xcross; then ac_cv_func_vfork_works=$ac_cv_func_vfork { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: result $ac_cv_func_vfork_works guessed because of cross compilation" >&5 $as_echo "$as_me: WARNING: result $ac_cv_func_vfork_works guessed because of cross compilation" >&2;} fi if test "x$ac_cv_func_vfork_works" = xyes; then $as_echo "#define HAVE_WORKING_VFORK 1" >>confdefs.h else $as_echo "#define vfork fork" >>confdefs.h fi if test "x$ac_cv_func_fork_works" = xyes; then $as_echo "#define HAVE_WORKING_FORK 1" >>confdefs.h fi if test $ac_cv_c_compiler_gnu = yes; then { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether $CC needs -traditional" >&5 $as_echo_n "checking whether $CC needs -traditional... " >&6; } if ${ac_cv_prog_gcc_traditional+:} false; then : $as_echo_n "(cached) " >&6 else ac_pattern="Autoconf.*'x'" cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #include Autoconf TIOCGETP _ACEOF if (eval "$ac_cpp conftest.$ac_ext") 2>&5 | $EGREP "$ac_pattern" >/dev/null 2>&1; then : ac_cv_prog_gcc_traditional=yes else ac_cv_prog_gcc_traditional=no fi rm -f conftest* if test $ac_cv_prog_gcc_traditional = no; then cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #include Autoconf TCGETA _ACEOF if (eval "$ac_cpp conftest.$ac_ext") 2>&5 | $EGREP "$ac_pattern" >/dev/null 2>&1; then : ac_cv_prog_gcc_traditional=yes fi rm -f conftest* fi fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_prog_gcc_traditional" >&5 $as_echo "$ac_cv_prog_gcc_traditional" >&6; } if test $ac_cv_prog_gcc_traditional = yes; then CC="$CC -traditional" fi fi ## _AIX is offended by rpl_malloc and rpl_realloc #AC_FUNC_MALLOC #AC_FUNC_REALLOC { $as_echo "$as_me:${as_lineno-$LINENO}: checking return type of signal handlers" >&5 $as_echo_n "checking return type of signal handlers... " >&6; } if ${ac_cv_type_signal+:} false; then : $as_echo_n "(cached) " >&6 else cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #include #include int main () { return *(signal (0, 0)) (0) == 1; ; return 0; } _ACEOF if ac_fn_c_try_compile "$LINENO"; then : ac_cv_type_signal=int else ac_cv_type_signal=void fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_type_signal" >&5 $as_echo "$ac_cv_type_signal" >&6; } cat >>confdefs.h <<_ACEOF #define RETSIGTYPE $ac_cv_type_signal _ACEOF { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether lstat correctly handles trailing slash" >&5 $as_echo_n "checking whether lstat correctly handles trailing slash... " >&6; } if ${ac_cv_func_lstat_dereferences_slashed_symlink+:} false; then : $as_echo_n "(cached) " >&6 else rm -f conftest.sym conftest.file echo >conftest.file if test "$as_ln_s" = "ln -s" && ln -s conftest.file conftest.sym; then if test "$cross_compiling" = yes; then : ac_cv_func_lstat_dereferences_slashed_symlink=no else cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ $ac_includes_default int main () { struct stat sbuf; /* Linux will dereference the symlink and fail, as required by POSIX. That is better in the sense that it means we will not have to compile and use the lstat wrapper. */ return lstat ("conftest.sym/", &sbuf) == 0; ; return 0; } _ACEOF if ac_fn_c_try_run "$LINENO"; then : ac_cv_func_lstat_dereferences_slashed_symlink=yes else ac_cv_func_lstat_dereferences_slashed_symlink=no fi rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \ conftest.$ac_objext conftest.beam conftest.$ac_ext fi else # If the `ln -s' command failed, then we probably don't even # have an lstat function. ac_cv_func_lstat_dereferences_slashed_symlink=no fi rm -f conftest.sym conftest.file fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_func_lstat_dereferences_slashed_symlink" >&5 $as_echo "$ac_cv_func_lstat_dereferences_slashed_symlink" >&6; } test $ac_cv_func_lstat_dereferences_slashed_symlink = yes && cat >>confdefs.h <<_ACEOF #define LSTAT_FOLLOWS_SLASHED_SYMLINK 1 _ACEOF if test "x$ac_cv_func_lstat_dereferences_slashed_symlink" = xno; then case " $LIBOBJS " in *" lstat.$ac_objext "* ) ;; *) LIBOBJS="$LIBOBJS lstat.$ac_objext" ;; esac fi { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether stat accepts an empty string" >&5 $as_echo_n "checking whether stat accepts an empty string... " >&6; } if ${ac_cv_func_stat_empty_string_bug+:} false; then : $as_echo_n "(cached) " >&6 else if test "$cross_compiling" = yes; then : ac_cv_func_stat_empty_string_bug=yes else cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ $ac_includes_default int main () { struct stat sbuf; return stat ("", &sbuf) == 0; ; return 0; } _ACEOF if ac_fn_c_try_run "$LINENO"; then : ac_cv_func_stat_empty_string_bug=no else ac_cv_func_stat_empty_string_bug=yes fi rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \ conftest.$ac_objext conftest.beam conftest.$ac_ext fi fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_func_stat_empty_string_bug" >&5 $as_echo "$ac_cv_func_stat_empty_string_bug" >&6; } if test $ac_cv_func_stat_empty_string_bug = yes; then case " $LIBOBJS " in *" stat.$ac_objext "* ) ;; *) LIBOBJS="$LIBOBJS stat.$ac_objext" ;; esac cat >>confdefs.h <<_ACEOF #define HAVE_STAT_EMPTY_STRING_BUG 1 _ACEOF fi for ac_func in getline isascii issetugid wcsdup do : as_ac_var=`$as_echo "ac_cv_func_$ac_func" | $as_tr_sh` ac_fn_c_check_func "$LINENO" "$ac_func" "$as_ac_var" if eval test \"x\$"$as_ac_var"\" = x"yes"; then : cat >>confdefs.h <<_ACEOF #define `$as_echo "HAVE_$ac_func" | $as_tr_cpp` 1 _ACEOF fi done { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether getpwnam_r and getpwuid_r are posix like" >&5 $as_echo_n "checking whether getpwnam_r and getpwuid_r are posix like... " >&6; } # The prototype for the POSIX version is: # int getpwnam_r(char *, struct passwd *, char *, size_t, struct passwd **) # int getpwuid_r(uid_t, struct passwd *, char *, size_t, struct passwd **); cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #include #include #include int main () { getpwnam_r(NULL, NULL, NULL, (size_t)0, NULL); getpwuid_r((uid_t)0, NULL, NULL, (size_t)0, NULL); ; return 0; } _ACEOF if ac_fn_c_try_link "$LINENO"; then : $as_echo "#define HAVE_GETPW_R_POSIX 1" >>confdefs.h { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 $as_echo "yes" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi rm -f core conftest.err conftest.$ac_objext \ conftest$ac_exeext conftest.$ac_ext { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether getpwnam_r and getpwuid_r are posix _draft_ like" >&5 $as_echo_n "checking whether getpwnam_r and getpwuid_r are posix _draft_ like... " >&6; } # The prototype for the POSIX draft version is: # struct passwd *getpwuid_r(uid_t, struct passwd *, char *, int); # struct passwd *getpwnam_r(char *, struct passwd *, char *, int); cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #include #include #include int main () { getpwnam_r(NULL, NULL, NULL, (size_t)0); getpwuid_r((uid_t)0, NULL, NULL, (size_t)0); ; return 0; } _ACEOF if ac_fn_c_try_link "$LINENO"; then : $as_echo "#define HAVE_GETPW_R_DRAFT 1" >>confdefs.h { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 $as_echo "yes" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi rm -f core conftest.err conftest.$ac_objext \ conftest$ac_exeext conftest.$ac_ext ac_fn_c_check_member "$LINENO" "struct dirent" "d_namlen" "ac_cv_member_struct_dirent_d_namlen" "#if HAVE_DIRENT_H #include #endif " if test "x$ac_cv_member_struct_dirent_d_namlen" = xyes; then : $as_echo "#define HAVE_STRUCT_DIRENT_D_NAMLEN 1" >>confdefs.h fi ac_config_files="$ac_config_files Makefile src/Makefile" cat >confcache <<\_ACEOF # This file is a shell script that caches the results of configure # tests run on this system so they can be shared between configure # scripts and configure runs, see configure's option --config-cache. # It is not useful on other systems. If it contains results you don't # want to keep, you may remove or edit it. # # config.status only pays attention to the cache file if you give it # the --recheck option to rerun configure. # # `ac_cv_env_foo' variables (set or unset) will be overridden when # loading this file, other *unset* `ac_cv_foo' will be assigned the # following values. _ACEOF # The following way of writing the cache mishandles newlines in values, # but we know of no workaround that is simple, portable, and efficient. # So, we kill variables containing newlines. # Ultrix sh set writes to stderr and can't be redirected directly, # and sets the high bit in the cache file unless we assign to the vars. ( for ac_var in `(set) 2>&1 | sed -n 's/^\([a-zA-Z_][a-zA-Z0-9_]*\)=.*/\1/p'`; do eval ac_val=\$$ac_var case $ac_val in #( *${as_nl}*) case $ac_var in #( *_cv_*) { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: cache variable $ac_var contains a newline" >&5 $as_echo "$as_me: WARNING: cache variable $ac_var contains a newline" >&2;} ;; esac case $ac_var in #( _ | IFS | as_nl) ;; #( BASH_ARGV | BASH_SOURCE) eval $ac_var= ;; #( *) { eval $ac_var=; unset $ac_var;} ;; esac ;; esac done (set) 2>&1 | case $as_nl`(ac_space=' '; set) 2>&1` in #( *${as_nl}ac_space=\ *) # `set' does not quote correctly, so add quotes: double-quote # substitution turns \\\\ into \\, and sed turns \\ into \. sed -n \ "s/'/'\\\\''/g; s/^\\([_$as_cr_alnum]*_cv_[_$as_cr_alnum]*\\)=\\(.*\\)/\\1='\\2'/p" ;; #( *) # `set' quotes correctly as required by POSIX, so do not add quotes. sed -n "/^[_$as_cr_alnum]*_cv_[_$as_cr_alnum]*=/p" ;; esac | sort ) | sed ' /^ac_cv_env_/b end t clear :clear s/^\([^=]*\)=\(.*[{}].*\)$/test "${\1+set}" = set || &/ t end s/^\([^=]*\)=\(.*\)$/\1=${\1=\2}/ :end' >>confcache if diff "$cache_file" confcache >/dev/null 2>&1; then :; else if test -w "$cache_file"; then if test "x$cache_file" != "x/dev/null"; then { $as_echo "$as_me:${as_lineno-$LINENO}: updating cache $cache_file" >&5 $as_echo "$as_me: updating cache $cache_file" >&6;} if test ! -f "$cache_file" || test -h "$cache_file"; then cat confcache >"$cache_file" else case $cache_file in #( */* | ?:*) mv -f confcache "$cache_file"$$ && mv -f "$cache_file"$$ "$cache_file" ;; #( *) mv -f confcache "$cache_file" ;; esac fi fi else { $as_echo "$as_me:${as_lineno-$LINENO}: not updating unwritable cache $cache_file" >&5 $as_echo "$as_me: not updating unwritable cache $cache_file" >&6;} fi fi rm -f confcache test "x$prefix" = xNONE && prefix=$ac_default_prefix # Let make expand exec_prefix. test "x$exec_prefix" = xNONE && exec_prefix='${prefix}' DEFS=-DHAVE_CONFIG_H ac_libobjs= ac_ltlibobjs= U= for ac_i in : $LIBOBJS; do test "x$ac_i" = x: && continue # 1. Remove the extension, and $U if already installed. ac_script='s/\$U\././;s/\.o$//;s/\.obj$//' ac_i=`$as_echo "$ac_i" | sed "$ac_script"` # 2. Prepend LIBOBJDIR. When used with automake>=1.10 LIBOBJDIR # will be set to the directory where LIBOBJS objects are built. as_fn_append ac_libobjs " \${LIBOBJDIR}$ac_i\$U.$ac_objext" as_fn_append ac_ltlibobjs " \${LIBOBJDIR}$ac_i"'$U.lo' done LIBOBJS=$ac_libobjs LTLIBOBJS=$ac_ltlibobjs { $as_echo "$as_me:${as_lineno-$LINENO}: checking that generated files are newer than configure" >&5 $as_echo_n "checking that generated files are newer than configure... " >&6; } if test -n "$am_sleep_pid"; then # Hide warnings about reused PIDs. wait $am_sleep_pid 2>/dev/null fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: done" >&5 $as_echo "done" >&6; } if test -z "${AMDEP_TRUE}" && test -z "${AMDEP_FALSE}"; then as_fn_error $? "conditional \"AMDEP\" was never defined. Usually this means the macro was only invoked conditionally." "$LINENO" 5 fi if test -z "${am__fastdepCC_TRUE}" && test -z "${am__fastdepCC_FALSE}"; then as_fn_error $? "conditional \"am__fastdepCC\" was never defined. Usually this means the macro was only invoked conditionally." "$LINENO" 5 fi if test -n "$EXEEXT"; then am__EXEEXT_TRUE= am__EXEEXT_FALSE='#' else am__EXEEXT_TRUE='#' am__EXEEXT_FALSE= fi : "${CONFIG_STATUS=./config.status}" ac_write_fail=0 ac_clean_files_save=$ac_clean_files ac_clean_files="$ac_clean_files $CONFIG_STATUS" { $as_echo "$as_me:${as_lineno-$LINENO}: creating $CONFIG_STATUS" >&5 $as_echo "$as_me: creating $CONFIG_STATUS" >&6;} as_write_fail=0 cat >$CONFIG_STATUS <<_ASEOF || as_write_fail=1 #! $SHELL # Generated by $as_me. # Run this file to recreate the current configuration. # Compiler output produced by configure, useful for debugging # configure, is in config.log if it exists. debug=false ac_cs_recheck=false ac_cs_silent=false SHELL=\${CONFIG_SHELL-$SHELL} export SHELL _ASEOF cat >>$CONFIG_STATUS <<\_ASEOF || as_write_fail=1 ## -------------------- ## ## M4sh Initialization. ## ## -------------------- ## # Be more Bourne compatible DUALCASE=1; export DUALCASE # for MKS sh if test -n "${ZSH_VERSION+set}" && (emulate sh) >/dev/null 2>&1; then : emulate sh NULLCMD=: # Pre-4.2 versions of Zsh do word splitting on ${1+"$@"}, which # is contrary to our usage. Disable this feature. alias -g '${1+"$@"}'='"$@"' setopt NO_GLOB_SUBST else case `(set -o) 2>/dev/null` in #( *posix*) : set -o posix ;; #( *) : ;; esac fi as_nl=' ' export as_nl # Printing a long string crashes Solaris 7 /usr/bin/printf. as_echo='\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\' as_echo=$as_echo$as_echo$as_echo$as_echo$as_echo as_echo=$as_echo$as_echo$as_echo$as_echo$as_echo$as_echo # Prefer a ksh shell builtin over an external printf program on Solaris, # but without wasting forks for bash or zsh. if test -z "$BASH_VERSION$ZSH_VERSION" \ && (test "X`print -r -- $as_echo`" = "X$as_echo") 2>/dev/null; then as_echo='print -r --' as_echo_n='print -rn --' elif (test "X`printf %s $as_echo`" = "X$as_echo") 2>/dev/null; then as_echo='printf %s\n' as_echo_n='printf %s' else if test "X`(/usr/ucb/echo -n -n $as_echo) 2>/dev/null`" = "X-n $as_echo"; then as_echo_body='eval /usr/ucb/echo -n "$1$as_nl"' as_echo_n='/usr/ucb/echo -n' else as_echo_body='eval expr "X$1" : "X\\(.*\\)"' as_echo_n_body='eval arg=$1; case $arg in #( *"$as_nl"*) expr "X$arg" : "X\\(.*\\)$as_nl"; arg=`expr "X$arg" : ".*$as_nl\\(.*\\)"`;; esac; expr "X$arg" : "X\\(.*\\)" | tr -d "$as_nl" ' export as_echo_n_body as_echo_n='sh -c $as_echo_n_body as_echo' fi export as_echo_body as_echo='sh -c $as_echo_body as_echo' fi # The user is always right. if test "${PATH_SEPARATOR+set}" != set; then PATH_SEPARATOR=: (PATH='/bin;/bin'; FPATH=$PATH; sh -c :) >/dev/null 2>&1 && { (PATH='/bin:/bin'; FPATH=$PATH; sh -c :) >/dev/null 2>&1 || PATH_SEPARATOR=';' } fi # IFS # We need space, tab and new line, in precisely that order. Quoting is # there to prevent editors from complaining about space-tab. # (If _AS_PATH_WALK were called with IFS unset, it would disable word # splitting by setting IFS to empty value.) IFS=" "" $as_nl" # Find who we are. Look in the path if we contain no directory separator. as_myself= case $0 in #(( *[\\/]* ) as_myself=$0 ;; *) as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. test -r "$as_dir/$0" && as_myself=$as_dir/$0 && break done IFS=$as_save_IFS ;; esac # We did not find ourselves, most probably we were run as `sh COMMAND' # in which case we are not to be found in the path. if test "x$as_myself" = x; then as_myself=$0 fi if test ! -f "$as_myself"; then $as_echo "$as_myself: error: cannot find myself; rerun with an absolute file name" >&2 exit 1 fi # Unset variables that we do not need and which cause bugs (e.g. in # pre-3.0 UWIN ksh). But do not cause bugs in bash 2.01; the "|| exit 1" # suppresses any "Segmentation fault" message there. '((' could # trigger a bug in pdksh 5.2.14. for as_var in BASH_ENV ENV MAIL MAILPATH do eval test x\${$as_var+set} = xset \ && ( (unset $as_var) || exit 1) >/dev/null 2>&1 && unset $as_var || : done PS1='$ ' PS2='> ' PS4='+ ' # NLS nuisances. LC_ALL=C export LC_ALL LANGUAGE=C export LANGUAGE # CDPATH. (unset CDPATH) >/dev/null 2>&1 && unset CDPATH # as_fn_error STATUS ERROR [LINENO LOG_FD] # ---------------------------------------- # Output "`basename $0`: error: ERROR" to stderr. If LINENO and LOG_FD are # provided, also output the error to LOG_FD, referencing LINENO. Then exit the # script with STATUS, using 1 if that was 0. as_fn_error () { as_status=$1; test $as_status -eq 0 && as_status=1 if test "$4"; then as_lineno=${as_lineno-"$3"} as_lineno_stack=as_lineno_stack=$as_lineno_stack $as_echo "$as_me:${as_lineno-$LINENO}: error: $2" >&$4 fi $as_echo "$as_me: error: $2" >&2 as_fn_exit $as_status } # as_fn_error # as_fn_set_status STATUS # ----------------------- # Set $? to STATUS, without forking. as_fn_set_status () { return $1 } # as_fn_set_status # as_fn_exit STATUS # ----------------- # Exit the shell with STATUS, even in a "trap 0" or "set -e" context. as_fn_exit () { set +e as_fn_set_status $1 exit $1 } # as_fn_exit # as_fn_unset VAR # --------------- # Portably unset VAR. as_fn_unset () { { eval $1=; unset $1;} } as_unset=as_fn_unset # as_fn_append VAR VALUE # ---------------------- # Append the text in VALUE to the end of the definition contained in VAR. Take # advantage of any shell optimizations that allow amortized linear growth over # repeated appends, instead of the typical quadratic growth present in naive # implementations. if (eval "as_var=1; as_var+=2; test x\$as_var = x12") 2>/dev/null; then : eval 'as_fn_append () { eval $1+=\$2 }' else as_fn_append () { eval $1=\$$1\$2 } fi # as_fn_append # as_fn_arith ARG... # ------------------ # Perform arithmetic evaluation on the ARGs, and store the result in the # global $as_val. Take advantage of shells that can avoid forks. The arguments # must be portable across $(()) and expr. if (eval "test \$(( 1 + 1 )) = 2") 2>/dev/null; then : eval 'as_fn_arith () { as_val=$(( $* )) }' else as_fn_arith () { as_val=`expr "$@" || test $? -eq 1` } fi # as_fn_arith if expr a : '\(a\)' >/dev/null 2>&1 && test "X`expr 00001 : '.*\(...\)'`" = X001; then as_expr=expr else as_expr=false fi if (basename -- /) >/dev/null 2>&1 && test "X`basename -- / 2>&1`" = "X/"; then as_basename=basename else as_basename=false fi if (as_dir=`dirname -- /` && test "X$as_dir" = X/) >/dev/null 2>&1; then as_dirname=dirname else as_dirname=false fi as_me=`$as_basename -- "$0" || $as_expr X/"$0" : '.*/\([^/][^/]*\)/*$' \| \ X"$0" : 'X\(//\)$' \| \ X"$0" : 'X\(/\)' \| . 2>/dev/null || $as_echo X/"$0" | sed '/^.*\/\([^/][^/]*\)\/*$/{ s//\1/ q } /^X\/\(\/\/\)$/{ s//\1/ q } /^X\/\(\/\).*/{ s//\1/ q } s/.*/./; q'` # Avoid depending upon Character Ranges. as_cr_letters='abcdefghijklmnopqrstuvwxyz' as_cr_LETTERS='ABCDEFGHIJKLMNOPQRSTUVWXYZ' as_cr_Letters=$as_cr_letters$as_cr_LETTERS as_cr_digits='0123456789' as_cr_alnum=$as_cr_Letters$as_cr_digits ECHO_C= ECHO_N= ECHO_T= case `echo -n x` in #((((( -n*) case `echo 'xy\c'` in *c*) ECHO_T=' ';; # ECHO_T is single tab character. xy) ECHO_C='\c';; *) echo `echo ksh88 bug on AIX 6.1` > /dev/null ECHO_T=' ';; esac;; *) ECHO_N='-n';; esac rm -f conf$$ conf$$.exe conf$$.file if test -d conf$$.dir; then rm -f conf$$.dir/conf$$.file else rm -f conf$$.dir mkdir conf$$.dir 2>/dev/null fi if (echo >conf$$.file) 2>/dev/null; then if ln -s conf$$.file conf$$ 2>/dev/null; then as_ln_s='ln -s' # ... but there are two gotchas: # 1) On MSYS, both `ln -s file dir' and `ln file dir' fail. # 2) DJGPP < 2.04 has no symlinks; `ln -s' creates a wrapper executable. # In both cases, we have to default to `cp -pR'. ln -s conf$$.file conf$$.dir 2>/dev/null && test ! -f conf$$.exe || as_ln_s='cp -pR' elif ln conf$$.file conf$$ 2>/dev/null; then as_ln_s=ln else as_ln_s='cp -pR' fi else as_ln_s='cp -pR' fi rm -f conf$$ conf$$.exe conf$$.dir/conf$$.file conf$$.file rmdir conf$$.dir 2>/dev/null # as_fn_mkdir_p # ------------- # Create "$as_dir" as a directory, including parents if necessary. as_fn_mkdir_p () { case $as_dir in #( -*) as_dir=./$as_dir;; esac test -d "$as_dir" || eval $as_mkdir_p || { as_dirs= while :; do case $as_dir in #( *\'*) as_qdir=`$as_echo "$as_dir" | sed "s/'/'\\\\\\\\''/g"`;; #'( *) as_qdir=$as_dir;; esac as_dirs="'$as_qdir' $as_dirs" as_dir=`$as_dirname -- "$as_dir" || $as_expr X"$as_dir" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \ X"$as_dir" : 'X\(//\)[^/]' \| \ X"$as_dir" : 'X\(//\)$' \| \ X"$as_dir" : 'X\(/\)' \| . 2>/dev/null || $as_echo X"$as_dir" | sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{ s//\1/ q } /^X\(\/\/\)[^/].*/{ s//\1/ q } /^X\(\/\/\)$/{ s//\1/ q } /^X\(\/\).*/{ s//\1/ q } s/.*/./; q'` test -d "$as_dir" && break done test -z "$as_dirs" || eval "mkdir $as_dirs" } || test -d "$as_dir" || as_fn_error $? "cannot create directory $as_dir" } # as_fn_mkdir_p if mkdir -p . 2>/dev/null; then as_mkdir_p='mkdir -p "$as_dir"' else test -d ./-p && rmdir ./-p as_mkdir_p=false fi # as_fn_executable_p FILE # ----------------------- # Test if FILE is an executable regular file. as_fn_executable_p () { test -f "$1" && test -x "$1" } # as_fn_executable_p as_test_x='test -x' as_executable_p=as_fn_executable_p # Sed expression to map a string onto a valid CPP name. as_tr_cpp="eval sed 'y%*$as_cr_letters%P$as_cr_LETTERS%;s%[^_$as_cr_alnum]%_%g'" # Sed expression to map a string onto a valid variable name. as_tr_sh="eval sed 'y%*+%pp%;s%[^_$as_cr_alnum]%_%g'" exec 6>&1 ## ----------------------------------- ## ## Main body of $CONFIG_STATUS script. ## ## ----------------------------------- ## _ASEOF test $as_write_fail = 0 && chmod +x $CONFIG_STATUS || ac_write_fail=1 cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 # Save the log message, to keep $0 and so on meaningful, and to # report actual input values of CONFIG_FILES etc. instead of their # values after options handling. ac_log=" This file was extended by libedit $as_me 3.1, which was generated by GNU Autoconf 2.69. Invocation command line was CONFIG_FILES = $CONFIG_FILES CONFIG_HEADERS = $CONFIG_HEADERS CONFIG_LINKS = $CONFIG_LINKS CONFIG_COMMANDS = $CONFIG_COMMANDS $ $0 $@ on `(hostname || uname -n) 2>/dev/null | sed 1q` " _ACEOF case $ac_config_files in *" "*) set x $ac_config_files; shift; ac_config_files=$*;; esac case $ac_config_headers in *" "*) set x $ac_config_headers; shift; ac_config_headers=$*;; esac cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1 # Files that config.status was made for. config_files="$ac_config_files" config_headers="$ac_config_headers" config_commands="$ac_config_commands" _ACEOF cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 ac_cs_usage="\ \`$as_me' instantiates files and other configuration actions from templates according to the current configuration. Unless the files and actions are specified as TAGs, all are instantiated by default. Usage: $0 [OPTION]... [TAG]... -h, --help print this help, then exit -V, --version print version number and configuration settings, then exit --config print configuration, then exit -q, --quiet, --silent do not print progress messages -d, --debug don't remove temporary files --recheck update $as_me by reconfiguring in the same conditions --file=FILE[:TEMPLATE] instantiate the configuration file FILE --header=FILE[:TEMPLATE] instantiate the configuration header FILE Configuration files: $config_files Configuration headers: $config_headers Configuration commands: $config_commands Report bugs to the package provider." _ACEOF cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1 ac_cs_config="`$as_echo "$ac_configure_args" | sed 's/^ //; s/[\\""\`\$]/\\\\&/g'`" ac_cs_version="\\ libedit config.status 3.1 configured by $0, generated by GNU Autoconf 2.69, with options \\"\$ac_cs_config\\" Copyright (C) 2012 Free Software Foundation, Inc. This config.status script is free software; the Free Software Foundation gives unlimited permission to copy, distribute and modify it." ac_pwd='$ac_pwd' srcdir='$srcdir' INSTALL='$INSTALL' MKDIR_P='$MKDIR_P' AWK='$AWK' test -n "\$AWK" || AWK=awk _ACEOF cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 # The default lists apply if the user does not specify any file. ac_need_defaults=: while test $# != 0 do case $1 in --*=?*) ac_option=`expr "X$1" : 'X\([^=]*\)='` ac_optarg=`expr "X$1" : 'X[^=]*=\(.*\)'` ac_shift=: ;; --*=) ac_option=`expr "X$1" : 'X\([^=]*\)='` ac_optarg= ac_shift=: ;; *) ac_option=$1 ac_optarg=$2 ac_shift=shift ;; esac case $ac_option in # Handling of the options. -recheck | --recheck | --rechec | --reche | --rech | --rec | --re | --r) ac_cs_recheck=: ;; --version | --versio | --versi | --vers | --ver | --ve | --v | -V ) $as_echo "$ac_cs_version"; exit ;; --config | --confi | --conf | --con | --co | --c ) $as_echo "$ac_cs_config"; exit ;; --debug | --debu | --deb | --de | --d | -d ) debug=: ;; --file | --fil | --fi | --f ) $ac_shift case $ac_optarg in *\'*) ac_optarg=`$as_echo "$ac_optarg" | sed "s/'/'\\\\\\\\''/g"` ;; '') as_fn_error $? "missing file argument" ;; esac as_fn_append CONFIG_FILES " '$ac_optarg'" ac_need_defaults=false;; --header | --heade | --head | --hea ) $ac_shift case $ac_optarg in *\'*) ac_optarg=`$as_echo "$ac_optarg" | sed "s/'/'\\\\\\\\''/g"` ;; esac as_fn_append CONFIG_HEADERS " '$ac_optarg'" ac_need_defaults=false;; --he | --h) # Conflict between --help and --header as_fn_error $? "ambiguous option: \`$1' Try \`$0 --help' for more information.";; --help | --hel | -h ) $as_echo "$ac_cs_usage"; exit ;; -q | -quiet | --quiet | --quie | --qui | --qu | --q \ | -silent | --silent | --silen | --sile | --sil | --si | --s) ac_cs_silent=: ;; # This is an error. -*) as_fn_error $? "unrecognized option: \`$1' Try \`$0 --help' for more information." ;; *) as_fn_append ac_config_targets " $1" ac_need_defaults=false ;; esac shift done ac_configure_extra_args= if $ac_cs_silent; then exec 6>/dev/null ac_configure_extra_args="$ac_configure_extra_args --silent" fi _ACEOF cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1 if \$ac_cs_recheck; then set X $SHELL '$0' $ac_configure_args \$ac_configure_extra_args --no-create --no-recursion shift \$as_echo "running CONFIG_SHELL=$SHELL \$*" >&6 CONFIG_SHELL='$SHELL' export CONFIG_SHELL exec "\$@" fi _ACEOF cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 exec 5>>config.log { echo sed 'h;s/./-/g;s/^.../## /;s/...$/ ##/;p;x;p;x' <<_ASBOX ## Running $as_me. ## _ASBOX $as_echo "$ac_log" } >&5 _ACEOF cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1 # # INIT-COMMANDS # AMDEP_TRUE="$AMDEP_TRUE" ac_aux_dir="$ac_aux_dir" # The HP-UX ksh and POSIX shell print the target directory to stdout # if CDPATH is set. (unset CDPATH) >/dev/null 2>&1 && unset CDPATH sed_quote_subst='$sed_quote_subst' double_quote_subst='$double_quote_subst' delay_variable_subst='$delay_variable_subst' macro_version='`$ECHO "$macro_version" | $SED "$delay_single_quote_subst"`' macro_revision='`$ECHO "$macro_revision" | $SED "$delay_single_quote_subst"`' enable_shared='`$ECHO "$enable_shared" | $SED "$delay_single_quote_subst"`' enable_static='`$ECHO "$enable_static" | $SED "$delay_single_quote_subst"`' pic_mode='`$ECHO "$pic_mode" | $SED "$delay_single_quote_subst"`' enable_fast_install='`$ECHO "$enable_fast_install" | $SED "$delay_single_quote_subst"`' shared_archive_member_spec='`$ECHO "$shared_archive_member_spec" | $SED "$delay_single_quote_subst"`' SHELL='`$ECHO "$SHELL" | $SED "$delay_single_quote_subst"`' ECHO='`$ECHO "$ECHO" | $SED "$delay_single_quote_subst"`' PATH_SEPARATOR='`$ECHO "$PATH_SEPARATOR" | $SED "$delay_single_quote_subst"`' host_alias='`$ECHO "$host_alias" | $SED "$delay_single_quote_subst"`' host='`$ECHO "$host" | $SED "$delay_single_quote_subst"`' host_os='`$ECHO "$host_os" | $SED "$delay_single_quote_subst"`' build_alias='`$ECHO "$build_alias" | $SED "$delay_single_quote_subst"`' build='`$ECHO "$build" | $SED "$delay_single_quote_subst"`' build_os='`$ECHO "$build_os" | $SED "$delay_single_quote_subst"`' SED='`$ECHO "$SED" | $SED "$delay_single_quote_subst"`' Xsed='`$ECHO "$Xsed" | $SED "$delay_single_quote_subst"`' GREP='`$ECHO "$GREP" | $SED "$delay_single_quote_subst"`' EGREP='`$ECHO "$EGREP" | $SED "$delay_single_quote_subst"`' FGREP='`$ECHO "$FGREP" | $SED "$delay_single_quote_subst"`' LD='`$ECHO "$LD" | $SED "$delay_single_quote_subst"`' NM='`$ECHO "$NM" | $SED "$delay_single_quote_subst"`' LN_S='`$ECHO "$LN_S" | $SED "$delay_single_quote_subst"`' max_cmd_len='`$ECHO "$max_cmd_len" | $SED "$delay_single_quote_subst"`' ac_objext='`$ECHO "$ac_objext" | $SED "$delay_single_quote_subst"`' exeext='`$ECHO "$exeext" | $SED "$delay_single_quote_subst"`' lt_unset='`$ECHO "$lt_unset" | $SED "$delay_single_quote_subst"`' lt_SP2NL='`$ECHO "$lt_SP2NL" | $SED "$delay_single_quote_subst"`' lt_NL2SP='`$ECHO "$lt_NL2SP" | $SED "$delay_single_quote_subst"`' lt_cv_to_host_file_cmd='`$ECHO "$lt_cv_to_host_file_cmd" | $SED "$delay_single_quote_subst"`' lt_cv_to_tool_file_cmd='`$ECHO "$lt_cv_to_tool_file_cmd" | $SED "$delay_single_quote_subst"`' reload_flag='`$ECHO "$reload_flag" | $SED "$delay_single_quote_subst"`' reload_cmds='`$ECHO "$reload_cmds" | $SED "$delay_single_quote_subst"`' OBJDUMP='`$ECHO "$OBJDUMP" | $SED "$delay_single_quote_subst"`' deplibs_check_method='`$ECHO "$deplibs_check_method" | $SED "$delay_single_quote_subst"`' file_magic_cmd='`$ECHO "$file_magic_cmd" | $SED "$delay_single_quote_subst"`' file_magic_glob='`$ECHO "$file_magic_glob" | $SED "$delay_single_quote_subst"`' want_nocaseglob='`$ECHO "$want_nocaseglob" | $SED "$delay_single_quote_subst"`' DLLTOOL='`$ECHO "$DLLTOOL" | $SED "$delay_single_quote_subst"`' sharedlib_from_linklib_cmd='`$ECHO "$sharedlib_from_linklib_cmd" | $SED "$delay_single_quote_subst"`' AR='`$ECHO "$AR" | $SED "$delay_single_quote_subst"`' AR_FLAGS='`$ECHO "$AR_FLAGS" | $SED "$delay_single_quote_subst"`' archiver_list_spec='`$ECHO "$archiver_list_spec" | $SED "$delay_single_quote_subst"`' STRIP='`$ECHO "$STRIP" | $SED "$delay_single_quote_subst"`' RANLIB='`$ECHO "$RANLIB" | $SED "$delay_single_quote_subst"`' old_postinstall_cmds='`$ECHO "$old_postinstall_cmds" | $SED "$delay_single_quote_subst"`' old_postuninstall_cmds='`$ECHO "$old_postuninstall_cmds" | $SED "$delay_single_quote_subst"`' old_archive_cmds='`$ECHO "$old_archive_cmds" | $SED "$delay_single_quote_subst"`' lock_old_archive_extraction='`$ECHO "$lock_old_archive_extraction" | $SED "$delay_single_quote_subst"`' CC='`$ECHO "$CC" | $SED "$delay_single_quote_subst"`' CFLAGS='`$ECHO "$CFLAGS" | $SED "$delay_single_quote_subst"`' compiler='`$ECHO "$compiler" | $SED "$delay_single_quote_subst"`' GCC='`$ECHO "$GCC" | $SED "$delay_single_quote_subst"`' lt_cv_sys_global_symbol_pipe='`$ECHO "$lt_cv_sys_global_symbol_pipe" | $SED "$delay_single_quote_subst"`' lt_cv_sys_global_symbol_to_cdecl='`$ECHO "$lt_cv_sys_global_symbol_to_cdecl" | $SED "$delay_single_quote_subst"`' lt_cv_sys_global_symbol_to_import='`$ECHO "$lt_cv_sys_global_symbol_to_import" | $SED "$delay_single_quote_subst"`' lt_cv_sys_global_symbol_to_c_name_address='`$ECHO "$lt_cv_sys_global_symbol_to_c_name_address" | $SED "$delay_single_quote_subst"`' lt_cv_sys_global_symbol_to_c_name_address_lib_prefix='`$ECHO "$lt_cv_sys_global_symbol_to_c_name_address_lib_prefix" | $SED "$delay_single_quote_subst"`' lt_cv_nm_interface='`$ECHO "$lt_cv_nm_interface" | $SED "$delay_single_quote_subst"`' nm_file_list_spec='`$ECHO "$nm_file_list_spec" | $SED "$delay_single_quote_subst"`' lt_sysroot='`$ECHO "$lt_sysroot" | $SED "$delay_single_quote_subst"`' lt_cv_truncate_bin='`$ECHO "$lt_cv_truncate_bin" | $SED "$delay_single_quote_subst"`' objdir='`$ECHO "$objdir" | $SED "$delay_single_quote_subst"`' MAGIC_CMD='`$ECHO "$MAGIC_CMD" | $SED "$delay_single_quote_subst"`' lt_prog_compiler_no_builtin_flag='`$ECHO "$lt_prog_compiler_no_builtin_flag" | $SED "$delay_single_quote_subst"`' lt_prog_compiler_pic='`$ECHO "$lt_prog_compiler_pic" | $SED "$delay_single_quote_subst"`' lt_prog_compiler_wl='`$ECHO "$lt_prog_compiler_wl" | $SED "$delay_single_quote_subst"`' lt_prog_compiler_static='`$ECHO "$lt_prog_compiler_static" | $SED "$delay_single_quote_subst"`' lt_cv_prog_compiler_c_o='`$ECHO "$lt_cv_prog_compiler_c_o" | $SED "$delay_single_quote_subst"`' need_locks='`$ECHO "$need_locks" | $SED "$delay_single_quote_subst"`' MANIFEST_TOOL='`$ECHO "$MANIFEST_TOOL" | $SED "$delay_single_quote_subst"`' DSYMUTIL='`$ECHO "$DSYMUTIL" | $SED "$delay_single_quote_subst"`' NMEDIT='`$ECHO "$NMEDIT" | $SED "$delay_single_quote_subst"`' LIPO='`$ECHO "$LIPO" | $SED "$delay_single_quote_subst"`' OTOOL='`$ECHO "$OTOOL" | $SED "$delay_single_quote_subst"`' OTOOL64='`$ECHO "$OTOOL64" | $SED "$delay_single_quote_subst"`' libext='`$ECHO "$libext" | $SED "$delay_single_quote_subst"`' shrext_cmds='`$ECHO "$shrext_cmds" | $SED "$delay_single_quote_subst"`' extract_expsyms_cmds='`$ECHO "$extract_expsyms_cmds" | $SED "$delay_single_quote_subst"`' archive_cmds_need_lc='`$ECHO "$archive_cmds_need_lc" | $SED "$delay_single_quote_subst"`' enable_shared_with_static_runtimes='`$ECHO "$enable_shared_with_static_runtimes" | $SED "$delay_single_quote_subst"`' export_dynamic_flag_spec='`$ECHO "$export_dynamic_flag_spec" | $SED "$delay_single_quote_subst"`' whole_archive_flag_spec='`$ECHO "$whole_archive_flag_spec" | $SED "$delay_single_quote_subst"`' compiler_needs_object='`$ECHO "$compiler_needs_object" | $SED "$delay_single_quote_subst"`' old_archive_from_new_cmds='`$ECHO "$old_archive_from_new_cmds" | $SED "$delay_single_quote_subst"`' old_archive_from_expsyms_cmds='`$ECHO "$old_archive_from_expsyms_cmds" | $SED "$delay_single_quote_subst"`' archive_cmds='`$ECHO "$archive_cmds" | $SED "$delay_single_quote_subst"`' archive_expsym_cmds='`$ECHO "$archive_expsym_cmds" | $SED "$delay_single_quote_subst"`' module_cmds='`$ECHO "$module_cmds" | $SED "$delay_single_quote_subst"`' module_expsym_cmds='`$ECHO "$module_expsym_cmds" | $SED "$delay_single_quote_subst"`' with_gnu_ld='`$ECHO "$with_gnu_ld" | $SED "$delay_single_quote_subst"`' allow_undefined_flag='`$ECHO "$allow_undefined_flag" | $SED "$delay_single_quote_subst"`' no_undefined_flag='`$ECHO "$no_undefined_flag" | $SED "$delay_single_quote_subst"`' hardcode_libdir_flag_spec='`$ECHO "$hardcode_libdir_flag_spec" | $SED "$delay_single_quote_subst"`' hardcode_libdir_separator='`$ECHO "$hardcode_libdir_separator" | $SED "$delay_single_quote_subst"`' hardcode_direct='`$ECHO "$hardcode_direct" | $SED "$delay_single_quote_subst"`' hardcode_direct_absolute='`$ECHO "$hardcode_direct_absolute" | $SED "$delay_single_quote_subst"`' hardcode_minus_L='`$ECHO "$hardcode_minus_L" | $SED "$delay_single_quote_subst"`' hardcode_shlibpath_var='`$ECHO "$hardcode_shlibpath_var" | $SED "$delay_single_quote_subst"`' hardcode_automatic='`$ECHO "$hardcode_automatic" | $SED "$delay_single_quote_subst"`' inherit_rpath='`$ECHO "$inherit_rpath" | $SED "$delay_single_quote_subst"`' link_all_deplibs='`$ECHO "$link_all_deplibs" | $SED "$delay_single_quote_subst"`' always_export_symbols='`$ECHO "$always_export_symbols" | $SED "$delay_single_quote_subst"`' export_symbols_cmds='`$ECHO "$export_symbols_cmds" | $SED "$delay_single_quote_subst"`' exclude_expsyms='`$ECHO "$exclude_expsyms" | $SED "$delay_single_quote_subst"`' include_expsyms='`$ECHO "$include_expsyms" | $SED "$delay_single_quote_subst"`' prelink_cmds='`$ECHO "$prelink_cmds" | $SED "$delay_single_quote_subst"`' postlink_cmds='`$ECHO "$postlink_cmds" | $SED "$delay_single_quote_subst"`' file_list_spec='`$ECHO "$file_list_spec" | $SED "$delay_single_quote_subst"`' variables_saved_for_relink='`$ECHO "$variables_saved_for_relink" | $SED "$delay_single_quote_subst"`' need_lib_prefix='`$ECHO "$need_lib_prefix" | $SED "$delay_single_quote_subst"`' need_version='`$ECHO "$need_version" | $SED "$delay_single_quote_subst"`' version_type='`$ECHO "$version_type" | $SED "$delay_single_quote_subst"`' runpath_var='`$ECHO "$runpath_var" | $SED "$delay_single_quote_subst"`' shlibpath_var='`$ECHO "$shlibpath_var" | $SED "$delay_single_quote_subst"`' shlibpath_overrides_runpath='`$ECHO "$shlibpath_overrides_runpath" | $SED "$delay_single_quote_subst"`' libname_spec='`$ECHO "$libname_spec" | $SED "$delay_single_quote_subst"`' library_names_spec='`$ECHO "$library_names_spec" | $SED "$delay_single_quote_subst"`' soname_spec='`$ECHO "$soname_spec" | $SED "$delay_single_quote_subst"`' install_override_mode='`$ECHO "$install_override_mode" | $SED "$delay_single_quote_subst"`' postinstall_cmds='`$ECHO "$postinstall_cmds" | $SED "$delay_single_quote_subst"`' postuninstall_cmds='`$ECHO "$postuninstall_cmds" | $SED "$delay_single_quote_subst"`' finish_cmds='`$ECHO "$finish_cmds" | $SED "$delay_single_quote_subst"`' finish_eval='`$ECHO "$finish_eval" | $SED "$delay_single_quote_subst"`' hardcode_into_libs='`$ECHO "$hardcode_into_libs" | $SED "$delay_single_quote_subst"`' sys_lib_search_path_spec='`$ECHO "$sys_lib_search_path_spec" | $SED "$delay_single_quote_subst"`' configure_time_dlsearch_path='`$ECHO "$configure_time_dlsearch_path" | $SED "$delay_single_quote_subst"`' configure_time_lt_sys_library_path='`$ECHO "$configure_time_lt_sys_library_path" | $SED "$delay_single_quote_subst"`' hardcode_action='`$ECHO "$hardcode_action" | $SED "$delay_single_quote_subst"`' enable_dlopen='`$ECHO "$enable_dlopen" | $SED "$delay_single_quote_subst"`' enable_dlopen_self='`$ECHO "$enable_dlopen_self" | $SED "$delay_single_quote_subst"`' enable_dlopen_self_static='`$ECHO "$enable_dlopen_self_static" | $SED "$delay_single_quote_subst"`' old_striplib='`$ECHO "$old_striplib" | $SED "$delay_single_quote_subst"`' striplib='`$ECHO "$striplib" | $SED "$delay_single_quote_subst"`' LTCC='$LTCC' LTCFLAGS='$LTCFLAGS' compiler='$compiler_DEFAULT' # A function that is used when there is no print builtin or printf. func_fallback_echo () { eval 'cat <<_LTECHO_EOF \$1 _LTECHO_EOF' } # Quote evaled strings. for var in SHELL \ ECHO \ PATH_SEPARATOR \ SED \ GREP \ EGREP \ FGREP \ LD \ NM \ LN_S \ lt_SP2NL \ lt_NL2SP \ reload_flag \ OBJDUMP \ deplibs_check_method \ file_magic_cmd \ file_magic_glob \ want_nocaseglob \ DLLTOOL \ sharedlib_from_linklib_cmd \ AR \ AR_FLAGS \ archiver_list_spec \ STRIP \ RANLIB \ CC \ CFLAGS \ compiler \ lt_cv_sys_global_symbol_pipe \ lt_cv_sys_global_symbol_to_cdecl \ lt_cv_sys_global_symbol_to_import \ lt_cv_sys_global_symbol_to_c_name_address \ lt_cv_sys_global_symbol_to_c_name_address_lib_prefix \ lt_cv_nm_interface \ nm_file_list_spec \ lt_cv_truncate_bin \ lt_prog_compiler_no_builtin_flag \ lt_prog_compiler_pic \ lt_prog_compiler_wl \ lt_prog_compiler_static \ lt_cv_prog_compiler_c_o \ need_locks \ MANIFEST_TOOL \ DSYMUTIL \ NMEDIT \ LIPO \ OTOOL \ OTOOL64 \ shrext_cmds \ export_dynamic_flag_spec \ whole_archive_flag_spec \ compiler_needs_object \ with_gnu_ld \ allow_undefined_flag \ no_undefined_flag \ hardcode_libdir_flag_spec \ hardcode_libdir_separator \ exclude_expsyms \ include_expsyms \ file_list_spec \ variables_saved_for_relink \ libname_spec \ library_names_spec \ soname_spec \ install_override_mode \ finish_eval \ old_striplib \ striplib; do case \`eval \\\\\$ECHO \\\\""\\\\\$\$var"\\\\"\` in *[\\\\\\\`\\"\\\$]*) eval "lt_\$var=\\\\\\"\\\`\\\$ECHO \\"\\\$\$var\\" | \\\$SED \\"\\\$sed_quote_subst\\"\\\`\\\\\\"" ## exclude from sc_prohibit_nested_quotes ;; *) eval "lt_\$var=\\\\\\"\\\$\$var\\\\\\"" ;; esac done # Double-quote double-evaled strings. for var in reload_cmds \ old_postinstall_cmds \ old_postuninstall_cmds \ old_archive_cmds \ extract_expsyms_cmds \ old_archive_from_new_cmds \ old_archive_from_expsyms_cmds \ archive_cmds \ archive_expsym_cmds \ module_cmds \ module_expsym_cmds \ export_symbols_cmds \ prelink_cmds \ postlink_cmds \ postinstall_cmds \ postuninstall_cmds \ finish_cmds \ sys_lib_search_path_spec \ configure_time_dlsearch_path \ configure_time_lt_sys_library_path; do case \`eval \\\\\$ECHO \\\\""\\\\\$\$var"\\\\"\` in *[\\\\\\\`\\"\\\$]*) eval "lt_\$var=\\\\\\"\\\`\\\$ECHO \\"\\\$\$var\\" | \\\$SED -e \\"\\\$double_quote_subst\\" -e \\"\\\$sed_quote_subst\\" -e \\"\\\$delay_variable_subst\\"\\\`\\\\\\"" ## exclude from sc_prohibit_nested_quotes ;; *) eval "lt_\$var=\\\\\\"\\\$\$var\\\\\\"" ;; esac done ac_aux_dir='$ac_aux_dir' # See if we are running on zsh, and set the options that allow our # commands through without removal of \ escapes INIT. if test -n "\${ZSH_VERSION+set}"; then setopt NO_GLOB_SUBST fi PACKAGE='$PACKAGE' VERSION='$VERSION' RM='$RM' ofile='$ofile' _ACEOF cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 # Handling of arguments. for ac_config_target in $ac_config_targets do case $ac_config_target in "config.h") CONFIG_HEADERS="$CONFIG_HEADERS config.h" ;; "depfiles") CONFIG_COMMANDS="$CONFIG_COMMANDS depfiles" ;; "libtool") CONFIG_COMMANDS="$CONFIG_COMMANDS libtool" ;; "Makefile") CONFIG_FILES="$CONFIG_FILES Makefile" ;; "src/Makefile") CONFIG_FILES="$CONFIG_FILES src/Makefile" ;; *) as_fn_error $? "invalid argument: \`$ac_config_target'" "$LINENO" 5;; esac done # If the user did not use the arguments to specify the items to instantiate, # then the envvar interface is used. Set only those that are not. # We use the long form for the default assignment because of an extremely # bizarre bug on SunOS 4.1.3. if $ac_need_defaults; then test "${CONFIG_FILES+set}" = set || CONFIG_FILES=$config_files test "${CONFIG_HEADERS+set}" = set || CONFIG_HEADERS=$config_headers test "${CONFIG_COMMANDS+set}" = set || CONFIG_COMMANDS=$config_commands fi # Have a temporary directory for convenience. Make it in the build tree # simply because there is no reason against having it here, and in addition, # creating and moving files from /tmp can sometimes cause problems. # Hook for its removal unless debugging. # Note that there is a small window in which the directory will not be cleaned: # after its creation but before its name has been assigned to `$tmp'. $debug || { tmp= ac_tmp= trap 'exit_status=$? : "${ac_tmp:=$tmp}" { test ! -d "$ac_tmp" || rm -fr "$ac_tmp"; } && exit $exit_status ' 0 trap 'as_fn_exit 1' 1 2 13 15 } # Create a (secure) tmp directory for tmp files. { tmp=`(umask 077 && mktemp -d "./confXXXXXX") 2>/dev/null` && test -d "$tmp" } || { tmp=./conf$$-$RANDOM (umask 077 && mkdir "$tmp") } || as_fn_error $? "cannot create a temporary directory in ." "$LINENO" 5 ac_tmp=$tmp # Set up the scripts for CONFIG_FILES section. # No need to generate them if there are no CONFIG_FILES. # This happens for instance with `./config.status config.h'. if test -n "$CONFIG_FILES"; then ac_cr=`echo X | tr X '\015'` # On cygwin, bash can eat \r inside `` if the user requested igncr. # But we know of no other shell where ac_cr would be empty at this # point, so we can use a bashism as a fallback. if test "x$ac_cr" = x; then eval ac_cr=\$\'\\r\' fi ac_cs_awk_cr=`$AWK 'BEGIN { print "a\rb" }' /dev/null` if test "$ac_cs_awk_cr" = "a${ac_cr}b"; then ac_cs_awk_cr='\\r' else ac_cs_awk_cr=$ac_cr fi echo 'BEGIN {' >"$ac_tmp/subs1.awk" && _ACEOF { echo "cat >conf$$subs.awk <<_ACEOF" && echo "$ac_subst_vars" | sed 's/.*/&!$&$ac_delim/' && echo "_ACEOF" } >conf$$subs.sh || as_fn_error $? "could not make $CONFIG_STATUS" "$LINENO" 5 ac_delim_num=`echo "$ac_subst_vars" | grep -c '^'` ac_delim='%!_!# ' for ac_last_try in false false false false false :; do . ./conf$$subs.sh || as_fn_error $? "could not make $CONFIG_STATUS" "$LINENO" 5 ac_delim_n=`sed -n "s/.*$ac_delim\$/X/p" conf$$subs.awk | grep -c X` if test $ac_delim_n = $ac_delim_num; then break elif $ac_last_try; then as_fn_error $? "could not make $CONFIG_STATUS" "$LINENO" 5 else ac_delim="$ac_delim!$ac_delim _$ac_delim!! " fi done rm -f conf$$subs.sh cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1 cat >>"\$ac_tmp/subs1.awk" <<\\_ACAWK && _ACEOF sed -n ' h s/^/S["/; s/!.*/"]=/ p g s/^[^!]*!// :repl t repl s/'"$ac_delim"'$// t delim :nl h s/\(.\{148\}\)..*/\1/ t more1 s/["\\]/\\&/g; s/^/"/; s/$/\\n"\\/ p n b repl :more1 s/["\\]/\\&/g; s/^/"/; s/$/"\\/ p g s/.\{148\}// t nl :delim h s/\(.\{148\}\)..*/\1/ t more2 s/["\\]/\\&/g; s/^/"/; s/$/"/ p b :more2 s/["\\]/\\&/g; s/^/"/; s/$/"\\/ p g s/.\{148\}// t delim ' >$CONFIG_STATUS || ac_write_fail=1 rm -f conf$$subs.awk cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1 _ACAWK cat >>"\$ac_tmp/subs1.awk" <<_ACAWK && for (key in S) S_is_set[key] = 1 FS = "" } { line = $ 0 nfields = split(line, field, "@") substed = 0 len = length(field[1]) for (i = 2; i < nfields; i++) { key = field[i] keylen = length(key) if (S_is_set[key]) { value = S[key] line = substr(line, 1, len) "" value "" substr(line, len + keylen + 3) len += length(value) + length(field[++i]) substed = 1 } else len += 1 + keylen } print line } _ACAWK _ACEOF cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 if sed "s/$ac_cr//" < /dev/null > /dev/null 2>&1; then sed "s/$ac_cr\$//; s/$ac_cr/$ac_cs_awk_cr/g" else cat fi < "$ac_tmp/subs1.awk" > "$ac_tmp/subs.awk" \ || as_fn_error $? "could not setup config files machinery" "$LINENO" 5 _ACEOF # VPATH may cause trouble with some makes, so we remove sole $(srcdir), # ${srcdir} and @srcdir@ entries from VPATH if srcdir is ".", strip leading and # trailing colons and then remove the whole line if VPATH becomes empty # (actually we leave an empty line to preserve line numbers). if test "x$srcdir" = x.; then ac_vpsub='/^[ ]*VPATH[ ]*=[ ]*/{ h s/// s/^/:/ s/[ ]*$/:/ s/:\$(srcdir):/:/g s/:\${srcdir}:/:/g s/:@srcdir@:/:/g s/^:*// s/:*$// x s/\(=[ ]*\).*/\1/ G s/\n// s/^[^=]*=[ ]*$// }' fi cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 fi # test -n "$CONFIG_FILES" # Set up the scripts for CONFIG_HEADERS section. # No need to generate them if there are no CONFIG_HEADERS. # This happens for instance with `./config.status Makefile'. if test -n "$CONFIG_HEADERS"; then cat >"$ac_tmp/defines.awk" <<\_ACAWK || BEGIN { _ACEOF # Transform confdefs.h into an awk script `defines.awk', embedded as # here-document in config.status, that substitutes the proper values into # config.h.in to produce config.h. # Create a delimiter string that does not exist in confdefs.h, to ease # handling of long lines. ac_delim='%!_!# ' for ac_last_try in false false :; do ac_tt=`sed -n "/$ac_delim/p" confdefs.h` if test -z "$ac_tt"; then break elif $ac_last_try; then as_fn_error $? "could not make $CONFIG_HEADERS" "$LINENO" 5 else ac_delim="$ac_delim!$ac_delim _$ac_delim!! " fi done # For the awk script, D is an array of macro values keyed by name, # likewise P contains macro parameters if any. Preserve backslash # newline sequences. ac_word_re=[_$as_cr_Letters][_$as_cr_alnum]* sed -n ' s/.\{148\}/&'"$ac_delim"'/g t rset :rset s/^[ ]*#[ ]*define[ ][ ]*/ / t def d :def s/\\$// t bsnl s/["\\]/\\&/g s/^ \('"$ac_word_re"'\)\(([^()]*)\)[ ]*\(.*\)/P["\1"]="\2"\ D["\1"]=" \3"/p s/^ \('"$ac_word_re"'\)[ ]*\(.*\)/D["\1"]=" \2"/p d :bsnl s/["\\]/\\&/g s/^ \('"$ac_word_re"'\)\(([^()]*)\)[ ]*\(.*\)/P["\1"]="\2"\ D["\1"]=" \3\\\\\\n"\\/p t cont s/^ \('"$ac_word_re"'\)[ ]*\(.*\)/D["\1"]=" \2\\\\\\n"\\/p t cont d :cont n s/.\{148\}/&'"$ac_delim"'/g t clear :clear s/\\$// t bsnlc s/["\\]/\\&/g; s/^/"/; s/$/"/p d :bsnlc s/["\\]/\\&/g; s/^/"/; s/$/\\\\\\n"\\/p b cont ' >$CONFIG_STATUS || ac_write_fail=1 cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1 for (key in D) D_is_set[key] = 1 FS = "" } /^[\t ]*#[\t ]*(define|undef)[\t ]+$ac_word_re([\t (]|\$)/ { line = \$ 0 split(line, arg, " ") if (arg[1] == "#") { defundef = arg[2] mac1 = arg[3] } else { defundef = substr(arg[1], 2) mac1 = arg[2] } split(mac1, mac2, "(") #) macro = mac2[1] prefix = substr(line, 1, index(line, defundef) - 1) if (D_is_set[macro]) { # Preserve the white space surrounding the "#". print prefix "define", macro P[macro] D[macro] next } else { # Replace #undef with comments. This is necessary, for example, # in the case of _POSIX_SOURCE, which is predefined and required # on some systems where configure will not decide to define it. if (defundef == "undef") { print "/*", prefix defundef, macro, "*/" next } } } { print } _ACAWK _ACEOF cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 as_fn_error $? "could not setup config headers machinery" "$LINENO" 5 fi # test -n "$CONFIG_HEADERS" eval set X " :F $CONFIG_FILES :H $CONFIG_HEADERS :C $CONFIG_COMMANDS" shift for ac_tag do case $ac_tag in :[FHLC]) ac_mode=$ac_tag; continue;; esac case $ac_mode$ac_tag in :[FHL]*:*);; :L* | :C*:*) as_fn_error $? "invalid tag \`$ac_tag'" "$LINENO" 5;; :[FH]-) ac_tag=-:-;; :[FH]*) ac_tag=$ac_tag:$ac_tag.in;; esac ac_save_IFS=$IFS IFS=: set x $ac_tag IFS=$ac_save_IFS shift ac_file=$1 shift case $ac_mode in :L) ac_source=$1;; :[FH]) ac_file_inputs= for ac_f do case $ac_f in -) ac_f="$ac_tmp/stdin";; *) # Look for the file first in the build tree, then in the source tree # (if the path is not absolute). The absolute path cannot be DOS-style, # because $ac_f cannot contain `:'. test -f "$ac_f" || case $ac_f in [\\/$]*) false;; *) test -f "$srcdir/$ac_f" && ac_f="$srcdir/$ac_f";; esac || as_fn_error 1 "cannot find input file: \`$ac_f'" "$LINENO" 5;; esac case $ac_f in *\'*) ac_f=`$as_echo "$ac_f" | sed "s/'/'\\\\\\\\''/g"`;; esac as_fn_append ac_file_inputs " '$ac_f'" done # Let's still pretend it is `configure' which instantiates (i.e., don't # use $as_me), people would be surprised to read: # /* config.h. Generated by config.status. */ configure_input='Generated from '` $as_echo "$*" | sed 's|^[^:]*/||;s|:[^:]*/|, |g' `' by configure.' if test x"$ac_file" != x-; then configure_input="$ac_file. $configure_input" { $as_echo "$as_me:${as_lineno-$LINENO}: creating $ac_file" >&5 $as_echo "$as_me: creating $ac_file" >&6;} fi # Neutralize special characters interpreted by sed in replacement strings. case $configure_input in #( *\&* | *\|* | *\\* ) ac_sed_conf_input=`$as_echo "$configure_input" | sed 's/[\\\\&|]/\\\\&/g'`;; #( *) ac_sed_conf_input=$configure_input;; esac case $ac_tag in *:-:* | *:-) cat >"$ac_tmp/stdin" \ || as_fn_error $? "could not create $ac_file" "$LINENO" 5 ;; esac ;; esac ac_dir=`$as_dirname -- "$ac_file" || $as_expr X"$ac_file" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \ X"$ac_file" : 'X\(//\)[^/]' \| \ X"$ac_file" : 'X\(//\)$' \| \ X"$ac_file" : 'X\(/\)' \| . 2>/dev/null || $as_echo X"$ac_file" | sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{ s//\1/ q } /^X\(\/\/\)[^/].*/{ s//\1/ q } /^X\(\/\/\)$/{ s//\1/ q } /^X\(\/\).*/{ s//\1/ q } s/.*/./; q'` as_dir="$ac_dir"; as_fn_mkdir_p ac_builddir=. case "$ac_dir" in .) ac_dir_suffix= ac_top_builddir_sub=. ac_top_build_prefix= ;; *) ac_dir_suffix=/`$as_echo "$ac_dir" | sed 's|^\.[\\/]||'` # A ".." for each directory in $ac_dir_suffix. ac_top_builddir_sub=`$as_echo "$ac_dir_suffix" | sed 's|/[^\\/]*|/..|g;s|/||'` case $ac_top_builddir_sub in "") ac_top_builddir_sub=. ac_top_build_prefix= ;; *) ac_top_build_prefix=$ac_top_builddir_sub/ ;; esac ;; esac ac_abs_top_builddir=$ac_pwd ac_abs_builddir=$ac_pwd$ac_dir_suffix # for backward compatibility: ac_top_builddir=$ac_top_build_prefix case $srcdir in .) # We are building in place. ac_srcdir=. ac_top_srcdir=$ac_top_builddir_sub ac_abs_top_srcdir=$ac_pwd ;; [\\/]* | ?:[\\/]* ) # Absolute name. ac_srcdir=$srcdir$ac_dir_suffix; ac_top_srcdir=$srcdir ac_abs_top_srcdir=$srcdir ;; *) # Relative name. ac_srcdir=$ac_top_build_prefix$srcdir$ac_dir_suffix ac_top_srcdir=$ac_top_build_prefix$srcdir ac_abs_top_srcdir=$ac_pwd/$srcdir ;; esac ac_abs_srcdir=$ac_abs_top_srcdir$ac_dir_suffix case $ac_mode in :F) # # CONFIG_FILE # case $INSTALL in [\\/$]* | ?:[\\/]* ) ac_INSTALL=$INSTALL ;; *) ac_INSTALL=$ac_top_build_prefix$INSTALL ;; esac ac_MKDIR_P=$MKDIR_P case $MKDIR_P in [\\/$]* | ?:[\\/]* ) ;; */*) ac_MKDIR_P=$ac_top_build_prefix$MKDIR_P ;; esac _ACEOF cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 # If the template does not know about datarootdir, expand it. # FIXME: This hack should be removed a few years after 2.60. ac_datarootdir_hack=; ac_datarootdir_seen= ac_sed_dataroot=' /datarootdir/ { p q } /@datadir@/p /@docdir@/p /@infodir@/p /@localedir@/p /@mandir@/p' case `eval "sed -n \"\$ac_sed_dataroot\" $ac_file_inputs"` in *datarootdir*) ac_datarootdir_seen=yes;; *@datadir@*|*@docdir@*|*@infodir@*|*@localedir@*|*@mandir@*) { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $ac_file_inputs seems to ignore the --datarootdir setting" >&5 $as_echo "$as_me: WARNING: $ac_file_inputs seems to ignore the --datarootdir setting" >&2;} _ACEOF cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1 ac_datarootdir_hack=' s&@datadir@&$datadir&g s&@docdir@&$docdir&g s&@infodir@&$infodir&g s&@localedir@&$localedir&g s&@mandir@&$mandir&g s&\\\${datarootdir}&$datarootdir&g' ;; esac _ACEOF # Neutralize VPATH when `$srcdir' = `.'. # Shell code in configure.ac might set extrasub. # FIXME: do we really want to maintain this feature? cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1 ac_sed_extra="$ac_vpsub $extrasub _ACEOF cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 :t /@[a-zA-Z_][a-zA-Z_0-9]*@/!b s|@configure_input@|$ac_sed_conf_input|;t t s&@top_builddir@&$ac_top_builddir_sub&;t t s&@top_build_prefix@&$ac_top_build_prefix&;t t s&@srcdir@&$ac_srcdir&;t t s&@abs_srcdir@&$ac_abs_srcdir&;t t s&@top_srcdir@&$ac_top_srcdir&;t t s&@abs_top_srcdir@&$ac_abs_top_srcdir&;t t s&@builddir@&$ac_builddir&;t t s&@abs_builddir@&$ac_abs_builddir&;t t s&@abs_top_builddir@&$ac_abs_top_builddir&;t t s&@INSTALL@&$ac_INSTALL&;t t s&@MKDIR_P@&$ac_MKDIR_P&;t t $ac_datarootdir_hack " eval sed \"\$ac_sed_extra\" "$ac_file_inputs" | $AWK -f "$ac_tmp/subs.awk" \ >$ac_tmp/out || as_fn_error $? "could not create $ac_file" "$LINENO" 5 test -z "$ac_datarootdir_hack$ac_datarootdir_seen" && { ac_out=`sed -n '/\${datarootdir}/p' "$ac_tmp/out"`; test -n "$ac_out"; } && { ac_out=`sed -n '/^[ ]*datarootdir[ ]*:*=/p' \ "$ac_tmp/out"`; test -z "$ac_out"; } && { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $ac_file contains a reference to the variable \`datarootdir' which seems to be undefined. Please make sure it is defined" >&5 $as_echo "$as_me: WARNING: $ac_file contains a reference to the variable \`datarootdir' which seems to be undefined. Please make sure it is defined" >&2;} rm -f "$ac_tmp/stdin" case $ac_file in -) cat "$ac_tmp/out" && rm -f "$ac_tmp/out";; *) rm -f "$ac_file" && mv "$ac_tmp/out" "$ac_file";; esac \ || as_fn_error $? "could not create $ac_file" "$LINENO" 5 ;; :H) # # CONFIG_HEADER # if test x"$ac_file" != x-; then { $as_echo "/* $configure_input */" \ && eval '$AWK -f "$ac_tmp/defines.awk"' "$ac_file_inputs" } >"$ac_tmp/config.h" \ || as_fn_error $? "could not create $ac_file" "$LINENO" 5 if diff "$ac_file" "$ac_tmp/config.h" >/dev/null 2>&1; then { $as_echo "$as_me:${as_lineno-$LINENO}: $ac_file is unchanged" >&5 $as_echo "$as_me: $ac_file is unchanged" >&6;} else rm -f "$ac_file" mv "$ac_tmp/config.h" "$ac_file" \ || as_fn_error $? "could not create $ac_file" "$LINENO" 5 fi else $as_echo "/* $configure_input */" \ && eval '$AWK -f "$ac_tmp/defines.awk"' "$ac_file_inputs" \ || as_fn_error $? "could not create -" "$LINENO" 5 fi # Compute "$ac_file"'s index in $config_headers. _am_arg="$ac_file" _am_stamp_count=1 for _am_header in $config_headers :; do case $_am_header in $_am_arg | $_am_arg:* ) break ;; * ) _am_stamp_count=`expr $_am_stamp_count + 1` ;; esac done echo "timestamp for $_am_arg" >`$as_dirname -- "$_am_arg" || $as_expr X"$_am_arg" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \ X"$_am_arg" : 'X\(//\)[^/]' \| \ X"$_am_arg" : 'X\(//\)$' \| \ X"$_am_arg" : 'X\(/\)' \| . 2>/dev/null || $as_echo X"$_am_arg" | sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{ s//\1/ q } /^X\(\/\/\)[^/].*/{ s//\1/ q } /^X\(\/\/\)$/{ s//\1/ q } /^X\(\/\).*/{ s//\1/ q } s/.*/./; q'`/stamp-h$_am_stamp_count ;; :C) { $as_echo "$as_me:${as_lineno-$LINENO}: executing $ac_file commands" >&5 $as_echo "$as_me: executing $ac_file commands" >&6;} ;; esac case $ac_file$ac_mode in "depfiles":C) test x"$AMDEP_TRUE" != x"" || { # Older Autoconf quotes --file arguments for eval, but not when files # are listed without --file. Let's play safe and only enable the eval # if we detect the quoting. case $CONFIG_FILES in *\'*) eval set x "$CONFIG_FILES" ;; *) set x $CONFIG_FILES ;; esac shift for mf do # Strip MF so we end up with the name of the file. mf=`echo "$mf" | sed -e 's/:.*$//'` # Check whether this is an Automake generated Makefile or not. # We used to match only the files named 'Makefile.in', but # some people rename them; so instead we look at the file content. # Grep'ing the first line is not enough: some people post-process # each Makefile.in and add a new line on top of each file to say so. # Grep'ing the whole file is not good either: AIX grep has a line # limit of 2048, but all sed's we know have understand at least 4000. if sed -n 's,^#.*generated by automake.*,X,p' "$mf" | grep X >/dev/null 2>&1; then dirpart=`$as_dirname -- "$mf" || $as_expr X"$mf" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \ X"$mf" : 'X\(//\)[^/]' \| \ X"$mf" : 'X\(//\)$' \| \ X"$mf" : 'X\(/\)' \| . 2>/dev/null || $as_echo X"$mf" | sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{ s//\1/ q } /^X\(\/\/\)[^/].*/{ s//\1/ q } /^X\(\/\/\)$/{ s//\1/ q } /^X\(\/\).*/{ s//\1/ q } s/.*/./; q'` else continue fi # Extract the definition of DEPDIR, am__include, and am__quote # from the Makefile without running 'make'. DEPDIR=`sed -n 's/^DEPDIR = //p' < "$mf"` test -z "$DEPDIR" && continue am__include=`sed -n 's/^am__include = //p' < "$mf"` test -z "$am__include" && continue am__quote=`sed -n 's/^am__quote = //p' < "$mf"` # Find all dependency output files, they are included files with # $(DEPDIR) in their names. We invoke sed twice because it is the # simplest approach to changing $(DEPDIR) to its actual value in the # expansion. for file in `sed -n " s/^$am__include $am__quote\(.*(DEPDIR).*\)$am__quote"'$/\1/p' <"$mf" | \ sed -e 's/\$(DEPDIR)/'"$DEPDIR"'/g'`; do # Make sure the directory exists. test -f "$dirpart/$file" && continue fdir=`$as_dirname -- "$file" || $as_expr X"$file" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \ X"$file" : 'X\(//\)[^/]' \| \ X"$file" : 'X\(//\)$' \| \ X"$file" : 'X\(/\)' \| . 2>/dev/null || $as_echo X"$file" | sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{ s//\1/ q } /^X\(\/\/\)[^/].*/{ s//\1/ q } /^X\(\/\/\)$/{ s//\1/ q } /^X\(\/\).*/{ s//\1/ q } s/.*/./; q'` as_dir=$dirpart/$fdir; as_fn_mkdir_p # echo "creating $dirpart/$file" echo '# dummy' > "$dirpart/$file" done done } ;; "libtool":C) # See if we are running on zsh, and set the options that allow our # commands through without removal of \ escapes. if test -n "${ZSH_VERSION+set}"; then setopt NO_GLOB_SUBST fi cfgfile=${ofile}T trap "$RM \"$cfgfile\"; exit 1" 1 2 15 $RM "$cfgfile" cat <<_LT_EOF >> "$cfgfile" #! $SHELL # Generated automatically by $as_me ($PACKAGE) $VERSION # Libtool was configured on host `(hostname || uname -n) 2>/dev/null | sed 1q`: # NOTE: Changes made to this file will be lost: look at ltmain.sh. # Provide generalized library-building support services. # Written by Gordon Matzigkeit, 1996 # Copyright (C) 2014 Free Software Foundation, Inc. # This is free software; see the source for copying conditions. There is NO # warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. # GNU Libtool is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of of the License, or # (at your option) any later version. # # As a special exception to the GNU General Public License, if you # distribute this file as part of a program or library that is built # using GNU Libtool, you may include this file under the same # distribution terms that you use for the rest of that program. # # GNU Libtool is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see . # The names of the tagged configurations supported by this script. available_tags='' # Configured defaults for sys_lib_dlsearch_path munging. : \${LT_SYS_LIBRARY_PATH="$configure_time_lt_sys_library_path"} # ### BEGIN LIBTOOL CONFIG # Which release of libtool.m4 was used? macro_version=$macro_version macro_revision=$macro_revision # Whether or not to build shared libraries. build_libtool_libs=$enable_shared # Whether or not to build static libraries. build_old_libs=$enable_static # What type of objects to build. pic_mode=$pic_mode # Whether or not to optimize for fast installation. fast_install=$enable_fast_install # Shared archive member basename,for filename based shared library versioning on AIX. shared_archive_member_spec=$shared_archive_member_spec # Shell to use when invoking shell scripts. SHELL=$lt_SHELL # An echo program that protects backslashes. ECHO=$lt_ECHO # The PATH separator for the build system. PATH_SEPARATOR=$lt_PATH_SEPARATOR # The host system. host_alias=$host_alias host=$host host_os=$host_os # The build system. build_alias=$build_alias build=$build build_os=$build_os # A sed program that does not truncate output. SED=$lt_SED # Sed that helps us avoid accidentally triggering echo(1) options like -n. Xsed="\$SED -e 1s/^X//" # A grep program that handles long lines. GREP=$lt_GREP # An ERE matcher. EGREP=$lt_EGREP # A literal string matcher. FGREP=$lt_FGREP # A BSD- or MS-compatible name lister. NM=$lt_NM # Whether we need soft or hard links. LN_S=$lt_LN_S # What is the maximum length of a command? max_cmd_len=$max_cmd_len # Object file suffix (normally "o"). objext=$ac_objext # Executable file suffix (normally ""). exeext=$exeext # whether the shell understands "unset". lt_unset=$lt_unset # turn spaces into newlines. SP2NL=$lt_lt_SP2NL # turn newlines into spaces. NL2SP=$lt_lt_NL2SP # convert \$build file names to \$host format. to_host_file_cmd=$lt_cv_to_host_file_cmd # convert \$build files to toolchain format. to_tool_file_cmd=$lt_cv_to_tool_file_cmd # An object symbol dumper. OBJDUMP=$lt_OBJDUMP # Method to check whether dependent libraries are shared objects. deplibs_check_method=$lt_deplibs_check_method # Command to use when deplibs_check_method = "file_magic". file_magic_cmd=$lt_file_magic_cmd # How to find potential files when deplibs_check_method = "file_magic". file_magic_glob=$lt_file_magic_glob # Find potential files using nocaseglob when deplibs_check_method = "file_magic". want_nocaseglob=$lt_want_nocaseglob # DLL creation program. DLLTOOL=$lt_DLLTOOL # Command to associate shared and link libraries. sharedlib_from_linklib_cmd=$lt_sharedlib_from_linklib_cmd # The archiver. AR=$lt_AR # Flags to create an archive. AR_FLAGS=$lt_AR_FLAGS # How to feed a file listing to the archiver. archiver_list_spec=$lt_archiver_list_spec # A symbol stripping program. STRIP=$lt_STRIP # Commands used to install an old-style archive. RANLIB=$lt_RANLIB old_postinstall_cmds=$lt_old_postinstall_cmds old_postuninstall_cmds=$lt_old_postuninstall_cmds # Whether to use a lock for old archive extraction. lock_old_archive_extraction=$lock_old_archive_extraction # A C compiler. LTCC=$lt_CC # LTCC compiler flags. LTCFLAGS=$lt_CFLAGS # Take the output of nm and produce a listing of raw symbols and C names. global_symbol_pipe=$lt_lt_cv_sys_global_symbol_pipe # Transform the output of nm in a proper C declaration. global_symbol_to_cdecl=$lt_lt_cv_sys_global_symbol_to_cdecl # Transform the output of nm into a list of symbols to manually relocate. global_symbol_to_import=$lt_lt_cv_sys_global_symbol_to_import # Transform the output of nm in a C name address pair. global_symbol_to_c_name_address=$lt_lt_cv_sys_global_symbol_to_c_name_address # Transform the output of nm in a C name address pair when lib prefix is needed. global_symbol_to_c_name_address_lib_prefix=$lt_lt_cv_sys_global_symbol_to_c_name_address_lib_prefix # The name lister interface. nm_interface=$lt_lt_cv_nm_interface # Specify filename containing input files for \$NM. nm_file_list_spec=$lt_nm_file_list_spec # The root where to search for dependent libraries,and where our libraries should be installed. lt_sysroot=$lt_sysroot # Command to truncate a binary pipe. lt_truncate_bin=$lt_lt_cv_truncate_bin # The name of the directory that contains temporary libtool files. objdir=$objdir # Used to examine libraries when file_magic_cmd begins with "file". MAGIC_CMD=$MAGIC_CMD # Must we lock files when doing compilation? need_locks=$lt_need_locks # Manifest tool. MANIFEST_TOOL=$lt_MANIFEST_TOOL # Tool to manipulate archived DWARF debug symbol files on Mac OS X. DSYMUTIL=$lt_DSYMUTIL # Tool to change global to local symbols on Mac OS X. NMEDIT=$lt_NMEDIT # Tool to manipulate fat objects and archives on Mac OS X. LIPO=$lt_LIPO # ldd/readelf like tool for Mach-O binaries on Mac OS X. OTOOL=$lt_OTOOL # ldd/readelf like tool for 64 bit Mach-O binaries on Mac OS X 10.4. OTOOL64=$lt_OTOOL64 # Old archive suffix (normally "a"). libext=$libext # Shared library suffix (normally ".so"). shrext_cmds=$lt_shrext_cmds # The commands to extract the exported symbol list from a shared archive. extract_expsyms_cmds=$lt_extract_expsyms_cmds # Variables whose values should be saved in libtool wrapper scripts and # restored at link time. variables_saved_for_relink=$lt_variables_saved_for_relink # Do we need the "lib" prefix for modules? need_lib_prefix=$need_lib_prefix # Do we need a version for libraries? need_version=$need_version # Library versioning type. version_type=$version_type # Shared library runtime path variable. runpath_var=$runpath_var # Shared library path variable. shlibpath_var=$shlibpath_var # Is shlibpath searched before the hard-coded library search path? shlibpath_overrides_runpath=$shlibpath_overrides_runpath # Format of library name prefix. libname_spec=$lt_libname_spec # List of archive names. First name is the real one, the rest are links. # The last name is the one that the linker finds with -lNAME library_names_spec=$lt_library_names_spec # The coded name of the library, if different from the real name. soname_spec=$lt_soname_spec # Permission mode override for installation of shared libraries. install_override_mode=$lt_install_override_mode # Command to use after installation of a shared archive. postinstall_cmds=$lt_postinstall_cmds # Command to use after uninstallation of a shared archive. postuninstall_cmds=$lt_postuninstall_cmds # Commands used to finish a libtool library installation in a directory. finish_cmds=$lt_finish_cmds # As "finish_cmds", except a single script fragment to be evaled but # not shown. finish_eval=$lt_finish_eval # Whether we should hardcode library paths into libraries. hardcode_into_libs=$hardcode_into_libs # Compile-time system search path for libraries. sys_lib_search_path_spec=$lt_sys_lib_search_path_spec # Detected run-time system search path for libraries. sys_lib_dlsearch_path_spec=$lt_configure_time_dlsearch_path # Explicit LT_SYS_LIBRARY_PATH set during ./configure time. configure_time_lt_sys_library_path=$lt_configure_time_lt_sys_library_path # Whether dlopen is supported. dlopen_support=$enable_dlopen # Whether dlopen of programs is supported. dlopen_self=$enable_dlopen_self # Whether dlopen of statically linked programs is supported. dlopen_self_static=$enable_dlopen_self_static # Commands to strip libraries. old_striplib=$lt_old_striplib striplib=$lt_striplib # The linker used to build libraries. LD=$lt_LD # How to create reloadable object files. reload_flag=$lt_reload_flag reload_cmds=$lt_reload_cmds # Commands used to build an old-style archive. old_archive_cmds=$lt_old_archive_cmds # A language specific compiler. CC=$lt_compiler # Is the compiler the GNU compiler? with_gcc=$GCC # Compiler flag to turn off builtin functions. no_builtin_flag=$lt_lt_prog_compiler_no_builtin_flag # Additional compiler flags for building library objects. pic_flag=$lt_lt_prog_compiler_pic # How to pass a linker flag through the compiler. wl=$lt_lt_prog_compiler_wl # Compiler flag to prevent dynamic linking. link_static_flag=$lt_lt_prog_compiler_static # Does compiler simultaneously support -c and -o options? compiler_c_o=$lt_lt_cv_prog_compiler_c_o # Whether or not to add -lc for building shared libraries. build_libtool_need_lc=$archive_cmds_need_lc # Whether or not to disallow shared libs when runtime libs are static. allow_libtool_libs_with_static_runtimes=$enable_shared_with_static_runtimes # Compiler flag to allow reflexive dlopens. export_dynamic_flag_spec=$lt_export_dynamic_flag_spec # Compiler flag to generate shared objects directly from archives. whole_archive_flag_spec=$lt_whole_archive_flag_spec # Whether the compiler copes with passing no objects directly. compiler_needs_object=$lt_compiler_needs_object # Create an old-style archive from a shared archive. old_archive_from_new_cmds=$lt_old_archive_from_new_cmds # Create a temporary old-style archive to link instead of a shared archive. old_archive_from_expsyms_cmds=$lt_old_archive_from_expsyms_cmds # Commands used to build a shared archive. archive_cmds=$lt_archive_cmds archive_expsym_cmds=$lt_archive_expsym_cmds # Commands used to build a loadable module if different from building # a shared archive. module_cmds=$lt_module_cmds module_expsym_cmds=$lt_module_expsym_cmds # Whether we are building with GNU ld or not. with_gnu_ld=$lt_with_gnu_ld # Flag that allows shared libraries with undefined symbols to be built. allow_undefined_flag=$lt_allow_undefined_flag # Flag that enforces no undefined symbols. no_undefined_flag=$lt_no_undefined_flag # Flag to hardcode \$libdir into a binary during linking. # This must work even if \$libdir does not exist hardcode_libdir_flag_spec=$lt_hardcode_libdir_flag_spec # Whether we need a single "-rpath" flag with a separated argument. hardcode_libdir_separator=$lt_hardcode_libdir_separator # Set to "yes" if using DIR/libNAME\$shared_ext during linking hardcodes # DIR into the resulting binary. hardcode_direct=$hardcode_direct # Set to "yes" if using DIR/libNAME\$shared_ext during linking hardcodes # DIR into the resulting binary and the resulting library dependency is # "absolute",i.e impossible to change by setting \$shlibpath_var if the # library is relocated. hardcode_direct_absolute=$hardcode_direct_absolute # Set to "yes" if using the -LDIR flag during linking hardcodes DIR # into the resulting binary. hardcode_minus_L=$hardcode_minus_L # Set to "yes" if using SHLIBPATH_VAR=DIR during linking hardcodes DIR # into the resulting binary. hardcode_shlibpath_var=$hardcode_shlibpath_var # Set to "yes" if building a shared library automatically hardcodes DIR # into the library and all subsequent libraries and executables linked # against it. hardcode_automatic=$hardcode_automatic # Set to yes if linker adds runtime paths of dependent libraries # to runtime path list. inherit_rpath=$inherit_rpath # Whether libtool must link a program against all its dependency libraries. link_all_deplibs=$link_all_deplibs # Set to "yes" if exported symbols are required. always_export_symbols=$always_export_symbols # The commands to list exported symbols. export_symbols_cmds=$lt_export_symbols_cmds # Symbols that should not be listed in the preloaded symbols. exclude_expsyms=$lt_exclude_expsyms # Symbols that must always be exported. include_expsyms=$lt_include_expsyms # Commands necessary for linking programs (against libraries) with templates. prelink_cmds=$lt_prelink_cmds # Commands necessary for finishing linking programs. postlink_cmds=$lt_postlink_cmds # Specify filename containing input files. file_list_spec=$lt_file_list_spec # How to hardcode a shared library path into an executable. hardcode_action=$hardcode_action # ### END LIBTOOL CONFIG _LT_EOF cat <<'_LT_EOF' >> "$cfgfile" # ### BEGIN FUNCTIONS SHARED WITH CONFIGURE # func_munge_path_list VARIABLE PATH # ----------------------------------- # VARIABLE is name of variable containing _space_ separated list of # directories to be munged by the contents of PATH, which is string # having a format: # "DIR[:DIR]:" # string "DIR[ DIR]" will be prepended to VARIABLE # ":DIR[:DIR]" # string "DIR[ DIR]" will be appended to VARIABLE # "DIRP[:DIRP]::[DIRA:]DIRA" # string "DIRP[ DIRP]" will be prepended to VARIABLE and string # "DIRA[ DIRA]" will be appended to VARIABLE # "DIR[:DIR]" # VARIABLE will be replaced by "DIR[ DIR]" func_munge_path_list () { case x$2 in x) ;; *:) eval $1=\"`$ECHO $2 | $SED 's/:/ /g'` \$$1\" ;; x:*) eval $1=\"\$$1 `$ECHO $2 | $SED 's/:/ /g'`\" ;; *::*) eval $1=\"\$$1\ `$ECHO $2 | $SED -e 's/.*:://' -e 's/:/ /g'`\" eval $1=\"`$ECHO $2 | $SED -e 's/::.*//' -e 's/:/ /g'`\ \$$1\" ;; *) eval $1=\"`$ECHO $2 | $SED 's/:/ /g'`\" ;; esac } # Calculate cc_basename. Skip known compiler wrappers and cross-prefix. func_cc_basename () { for cc_temp in $*""; do case $cc_temp in compile | *[\\/]compile | ccache | *[\\/]ccache ) ;; distcc | *[\\/]distcc | purify | *[\\/]purify ) ;; \-*) ;; *) break;; esac done func_cc_basename_result=`$ECHO "$cc_temp" | $SED "s%.*/%%; s%^$host_alias-%%"` } # ### END FUNCTIONS SHARED WITH CONFIGURE _LT_EOF case $host_os in aix3*) cat <<\_LT_EOF >> "$cfgfile" # AIX sometimes has problems with the GCC collect2 program. For some # reason, if we set the COLLECT_NAMES environment variable, the problems # vanish in a puff of smoke. if test set != "${COLLECT_NAMES+set}"; then COLLECT_NAMES= export COLLECT_NAMES fi _LT_EOF ;; esac ltmain=$ac_aux_dir/ltmain.sh # We use sed instead of cat because bash on DJGPP gets confused if # if finds mixed CR/LF and LF-only lines. Since sed operates in # text mode, it properly converts lines to CR/LF. This bash problem # is reportedly fixed, but why not run on old versions too? sed '$q' "$ltmain" >> "$cfgfile" \ || (rm -f "$cfgfile"; exit 1) mv -f "$cfgfile" "$ofile" || (rm -f "$ofile" && cp "$cfgfile" "$ofile" && rm -f "$cfgfile") chmod +x "$ofile" ;; esac done # for ac_tag as_fn_exit 0 _ACEOF ac_clean_files=$ac_clean_files_save test $ac_write_fail = 0 || as_fn_error $? "write failure creating $CONFIG_STATUS" "$LINENO" 5 # configure is writing to config.log, and then calls config.status. # config.status does its own redirection, appending to config.log. # Unfortunately, on DOS this fails, as config.log is still kept open # by configure, so config.status won't be able to write to it; its # output is simply discarded. So we exec the FD to /dev/null, # effectively closing config.log, so it can be properly (re)opened and # appended to by config.status. When coming back to configure, we # need to make the FD available again. if test "$no_create" != yes; then ac_cs_success=: ac_config_status_args= test "$silent" = yes && ac_config_status_args="$ac_config_status_args --quiet" exec 5>/dev/null $SHELL $CONFIG_STATUS $ac_config_status_args || ac_cs_success=false exec 5>>config.log # Use ||, not &&, to avoid exiting from the if with $? = 1, which # would make configure fail if this is the last instruction. $ac_cs_success || as_fn_exit 1 fi if test -n "$ac_unrecognized_opts" && test "$enable_option_checking" != no; then { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: unrecognized options: $ac_unrecognized_opts" >&5 $as_echo "$as_me: WARNING: unrecognized options: $ac_unrecognized_opts" >&2;} fi heimdal-7.5.0/lib/libedit/ltmain.sh0000644000175000017500000117077113212444501015266 0ustar niknik#! /bin/sh ## DO NOT EDIT - This file generated from ./build-aux/ltmain.in ## by inline-source v2014-01-03.01 # libtool (GNU libtool) 2.4.6 # Provide generalized library-building support services. # Written by Gordon Matzigkeit , 1996 # Copyright (C) 1996-2015 Free Software Foundation, Inc. # This is free software; see the source for copying conditions. There is NO # warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. # GNU Libtool is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # As a special exception to the GNU General Public License, # if you distribute this file as part of a program or library that # is built using GNU Libtool, you may include this file under the # same distribution terms that you use for the rest of that program. # # GNU Libtool is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see . PROGRAM=libtool PACKAGE=libtool VERSION=2.4.6 package_revision=2.4.6 ## ------ ## ## Usage. ## ## ------ ## # Run './libtool --help' for help with using this script from the # command line. ## ------------------------------- ## ## User overridable command paths. ## ## ------------------------------- ## # After configure completes, it has a better idea of some of the # shell tools we need than the defaults used by the functions shared # with bootstrap, so set those here where they can still be over- # ridden by the user, but otherwise take precedence. : ${AUTOCONF="autoconf"} : ${AUTOMAKE="automake"} ## -------------------------- ## ## Source external libraries. ## ## -------------------------- ## # Much of our low-level functionality needs to be sourced from external # libraries, which are installed to $pkgauxdir. # Set a version string for this script. scriptversion=2015-01-20.17; # UTC # General shell script boiler plate, and helper functions. # Written by Gary V. Vaughan, 2004 # Copyright (C) 2004-2015 Free Software Foundation, Inc. # This is free software; see the source for copying conditions. There is NO # warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3 of the License, or # (at your option) any later version. # As a special exception to the GNU General Public License, if you distribute # this file as part of a program or library that is built using GNU Libtool, # you may include this file under the same distribution terms that you use # for the rest of that program. # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNES FOR A PARTICULAR PURPOSE. See the GNU # General Public License for more details. # You should have received a copy of the GNU General Public License # along with this program. If not, see . # Please report bugs or propose patches to gary@gnu.org. ## ------ ## ## Usage. ## ## ------ ## # Evaluate this file near the top of your script to gain access to # the functions and variables defined here: # # . `echo "$0" | ${SED-sed} 's|[^/]*$||'`/build-aux/funclib.sh # # If you need to override any of the default environment variable # settings, do that before evaluating this file. ## -------------------- ## ## Shell normalisation. ## ## -------------------- ## # Some shells need a little help to be as Bourne compatible as possible. # Before doing anything else, make sure all that help has been provided! DUALCASE=1; export DUALCASE # for MKS sh if test -n "${ZSH_VERSION+set}" && (emulate sh) >/dev/null 2>&1; then : emulate sh NULLCMD=: # Pre-4.2 versions of Zsh do word splitting on ${1+"$@"}, which # is contrary to our usage. Disable this feature. alias -g '${1+"$@"}'='"$@"' setopt NO_GLOB_SUBST else case `(set -o) 2>/dev/null` in *posix*) set -o posix ;; esac fi # NLS nuisances: We save the old values in case they are required later. _G_user_locale= _G_safe_locale= for _G_var in LANG LANGUAGE LC_ALL LC_CTYPE LC_COLLATE LC_MESSAGES do eval "if test set = \"\${$_G_var+set}\"; then save_$_G_var=\$$_G_var $_G_var=C export $_G_var _G_user_locale=\"$_G_var=\\\$save_\$_G_var; \$_G_user_locale\" _G_safe_locale=\"$_G_var=C; \$_G_safe_locale\" fi" done # CDPATH. (unset CDPATH) >/dev/null 2>&1 && unset CDPATH # Make sure IFS has a sensible default sp=' ' nl=' ' IFS="$sp $nl" # There are apparently some retarded systems that use ';' as a PATH separator! if test "${PATH_SEPARATOR+set}" != set; then PATH_SEPARATOR=: (PATH='/bin;/bin'; FPATH=$PATH; sh -c :) >/dev/null 2>&1 && { (PATH='/bin:/bin'; FPATH=$PATH; sh -c :) >/dev/null 2>&1 || PATH_SEPARATOR=';' } fi ## ------------------------- ## ## Locate command utilities. ## ## ------------------------- ## # func_executable_p FILE # ---------------------- # Check that FILE is an executable regular file. func_executable_p () { test -f "$1" && test -x "$1" } # func_path_progs PROGS_LIST CHECK_FUNC [PATH] # -------------------------------------------- # Search for either a program that responds to --version with output # containing "GNU", or else returned by CHECK_FUNC otherwise, by # trying all the directories in PATH with each of the elements of # PROGS_LIST. # # CHECK_FUNC should accept the path to a candidate program, and # set $func_check_prog_result if it truncates its output less than # $_G_path_prog_max characters. func_path_progs () { _G_progs_list=$1 _G_check_func=$2 _G_PATH=${3-"$PATH"} _G_path_prog_max=0 _G_path_prog_found=false _G_save_IFS=$IFS; IFS=${PATH_SEPARATOR-:} for _G_dir in $_G_PATH; do IFS=$_G_save_IFS test -z "$_G_dir" && _G_dir=. for _G_prog_name in $_G_progs_list; do for _exeext in '' .EXE; do _G_path_prog=$_G_dir/$_G_prog_name$_exeext func_executable_p "$_G_path_prog" || continue case `"$_G_path_prog" --version 2>&1` in *GNU*) func_path_progs_result=$_G_path_prog _G_path_prog_found=: ;; *) $_G_check_func $_G_path_prog func_path_progs_result=$func_check_prog_result ;; esac $_G_path_prog_found && break 3 done done done IFS=$_G_save_IFS test -z "$func_path_progs_result" && { echo "no acceptable sed could be found in \$PATH" >&2 exit 1 } } # We want to be able to use the functions in this file before configure # has figured out where the best binaries are kept, which means we have # to search for them ourselves - except when the results are already set # where we skip the searches. # Unless the user overrides by setting SED, search the path for either GNU # sed, or the sed that truncates its output the least. test -z "$SED" && { _G_sed_script=s/aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb/ for _G_i in 1 2 3 4 5 6 7; do _G_sed_script=$_G_sed_script$nl$_G_sed_script done echo "$_G_sed_script" 2>/dev/null | sed 99q >conftest.sed _G_sed_script= func_check_prog_sed () { _G_path_prog=$1 _G_count=0 printf 0123456789 >conftest.in while : do cat conftest.in conftest.in >conftest.tmp mv conftest.tmp conftest.in cp conftest.in conftest.nl echo '' >> conftest.nl "$_G_path_prog" -f conftest.sed conftest.out 2>/dev/null || break diff conftest.out conftest.nl >/dev/null 2>&1 || break _G_count=`expr $_G_count + 1` if test "$_G_count" -gt "$_G_path_prog_max"; then # Best one so far, save it but keep looking for a better one func_check_prog_result=$_G_path_prog _G_path_prog_max=$_G_count fi # 10*(2^10) chars as input seems more than enough test 10 -lt "$_G_count" && break done rm -f conftest.in conftest.tmp conftest.nl conftest.out } func_path_progs "sed gsed" func_check_prog_sed $PATH:/usr/xpg4/bin rm -f conftest.sed SED=$func_path_progs_result } # Unless the user overrides by setting GREP, search the path for either GNU # grep, or the grep that truncates its output the least. test -z "$GREP" && { func_check_prog_grep () { _G_path_prog=$1 _G_count=0 _G_path_prog_max=0 printf 0123456789 >conftest.in while : do cat conftest.in conftest.in >conftest.tmp mv conftest.tmp conftest.in cp conftest.in conftest.nl echo 'GREP' >> conftest.nl "$_G_path_prog" -e 'GREP$' -e '-(cannot match)-' conftest.out 2>/dev/null || break diff conftest.out conftest.nl >/dev/null 2>&1 || break _G_count=`expr $_G_count + 1` if test "$_G_count" -gt "$_G_path_prog_max"; then # Best one so far, save it but keep looking for a better one func_check_prog_result=$_G_path_prog _G_path_prog_max=$_G_count fi # 10*(2^10) chars as input seems more than enough test 10 -lt "$_G_count" && break done rm -f conftest.in conftest.tmp conftest.nl conftest.out } func_path_progs "grep ggrep" func_check_prog_grep $PATH:/usr/xpg4/bin GREP=$func_path_progs_result } ## ------------------------------- ## ## User overridable command paths. ## ## ------------------------------- ## # All uppercase variable names are used for environment variables. These # variables can be overridden by the user before calling a script that # uses them if a suitable command of that name is not already available # in the command search PATH. : ${CP="cp -f"} : ${ECHO="printf %s\n"} : ${EGREP="$GREP -E"} : ${FGREP="$GREP -F"} : ${LN_S="ln -s"} : ${MAKE="make"} : ${MKDIR="mkdir"} : ${MV="mv -f"} : ${RM="rm -f"} : ${SHELL="${CONFIG_SHELL-/bin/sh}"} ## -------------------- ## ## Useful sed snippets. ## ## -------------------- ## sed_dirname='s|/[^/]*$||' sed_basename='s|^.*/||' # Sed substitution that helps us do robust quoting. It backslashifies # metacharacters that are still active within double-quoted strings. sed_quote_subst='s|\([`"$\\]\)|\\\1|g' # Same as above, but do not quote variable references. sed_double_quote_subst='s/\(["`\\]\)/\\\1/g' # Sed substitution that turns a string into a regex matching for the # string literally. sed_make_literal_regex='s|[].[^$\\*\/]|\\&|g' # Sed substitution that converts a w32 file name or path # that contains forward slashes, into one that contains # (escaped) backslashes. A very naive implementation. sed_naive_backslashify='s|\\\\*|\\|g;s|/|\\|g;s|\\|\\\\|g' # Re-'\' parameter expansions in output of sed_double_quote_subst that # were '\'-ed in input to the same. If an odd number of '\' preceded a # '$' in input to sed_double_quote_subst, that '$' was protected from # expansion. Since each input '\' is now two '\'s, look for any number # of runs of four '\'s followed by two '\'s and then a '$'. '\' that '$'. _G_bs='\\' _G_bs2='\\\\' _G_bs4='\\\\\\\\' _G_dollar='\$' sed_double_backslash="\ s/$_G_bs4/&\\ /g s/^$_G_bs2$_G_dollar/$_G_bs&/ s/\\([^$_G_bs]\\)$_G_bs2$_G_dollar/\\1$_G_bs2$_G_bs$_G_dollar/g s/\n//g" ## ----------------- ## ## Global variables. ## ## ----------------- ## # Except for the global variables explicitly listed below, the following # functions in the '^func_' namespace, and the '^require_' namespace # variables initialised in the 'Resource management' section, sourcing # this file will not pollute your global namespace with anything # else. There's no portable way to scope variables in Bourne shell # though, so actually running these functions will sometimes place # results into a variable named after the function, and often use # temporary variables in the '^_G_' namespace. If you are careful to # avoid using those namespaces casually in your sourcing script, things # should continue to work as you expect. And, of course, you can freely # overwrite any of the functions or variables defined here before # calling anything to customize them. EXIT_SUCCESS=0 EXIT_FAILURE=1 EXIT_MISMATCH=63 # $? = 63 is used to indicate version mismatch to missing. EXIT_SKIP=77 # $? = 77 is used to indicate a skipped test to automake. # Allow overriding, eg assuming that you follow the convention of # putting '$debug_cmd' at the start of all your functions, you can get # bash to show function call trace with: # # debug_cmd='eval echo "${FUNCNAME[0]} $*" >&2' bash your-script-name debug_cmd=${debug_cmd-":"} exit_cmd=: # By convention, finish your script with: # # exit $exit_status # # so that you can set exit_status to non-zero if you want to indicate # something went wrong during execution without actually bailing out at # the point of failure. exit_status=$EXIT_SUCCESS # Work around backward compatibility issue on IRIX 6.5. On IRIX 6.4+, sh # is ksh but when the shell is invoked as "sh" and the current value of # the _XPG environment variable is not equal to 1 (one), the special # positional parameter $0, within a function call, is the name of the # function. progpath=$0 # The name of this program. progname=`$ECHO "$progpath" |$SED "$sed_basename"` # Make sure we have an absolute progpath for reexecution: case $progpath in [\\/]*|[A-Za-z]:\\*) ;; *[\\/]*) progdir=`$ECHO "$progpath" |$SED "$sed_dirname"` progdir=`cd "$progdir" && pwd` progpath=$progdir/$progname ;; *) _G_IFS=$IFS IFS=${PATH_SEPARATOR-:} for progdir in $PATH; do IFS=$_G_IFS test -x "$progdir/$progname" && break done IFS=$_G_IFS test -n "$progdir" || progdir=`pwd` progpath=$progdir/$progname ;; esac ## ----------------- ## ## Standard options. ## ## ----------------- ## # The following options affect the operation of the functions defined # below, and should be set appropriately depending on run-time para- # meters passed on the command line. opt_dry_run=false opt_quiet=false opt_verbose=false # Categories 'all' and 'none' are always available. Append any others # you will pass as the first argument to func_warning from your own # code. warning_categories= # By default, display warnings according to 'opt_warning_types'. Set # 'warning_func' to ':' to elide all warnings, or func_fatal_error to # treat the next displayed warning as a fatal error. warning_func=func_warn_and_continue # Set to 'all' to display all warnings, 'none' to suppress all # warnings, or a space delimited list of some subset of # 'warning_categories' to display only the listed warnings. opt_warning_types=all ## -------------------- ## ## Resource management. ## ## -------------------- ## # This section contains definitions for functions that each ensure a # particular resource (a file, or a non-empty configuration variable for # example) is available, and if appropriate to extract default values # from pertinent package files. Call them using their associated # 'require_*' variable to ensure that they are executed, at most, once. # # It's entirely deliberate that calling these functions can set # variables that don't obey the namespace limitations obeyed by the rest # of this file, in order that that they be as useful as possible to # callers. # require_term_colors # ------------------- # Allow display of bold text on terminals that support it. require_term_colors=func_require_term_colors func_require_term_colors () { $debug_cmd test -t 1 && { # COLORTERM and USE_ANSI_COLORS environment variables take # precedence, because most terminfo databases neglect to describe # whether color sequences are supported. test -n "${COLORTERM+set}" && : ${USE_ANSI_COLORS="1"} if test 1 = "$USE_ANSI_COLORS"; then # Standard ANSI escape sequences tc_reset='' tc_bold=''; tc_standout='' tc_red=''; tc_green='' tc_blue=''; tc_cyan='' else # Otherwise trust the terminfo database after all. test -n "`tput sgr0 2>/dev/null`" && { tc_reset=`tput sgr0` test -n "`tput bold 2>/dev/null`" && tc_bold=`tput bold` tc_standout=$tc_bold test -n "`tput smso 2>/dev/null`" && tc_standout=`tput smso` test -n "`tput setaf 1 2>/dev/null`" && tc_red=`tput setaf 1` test -n "`tput setaf 2 2>/dev/null`" && tc_green=`tput setaf 2` test -n "`tput setaf 4 2>/dev/null`" && tc_blue=`tput setaf 4` test -n "`tput setaf 5 2>/dev/null`" && tc_cyan=`tput setaf 5` } fi } require_term_colors=: } ## ----------------- ## ## Function library. ## ## ----------------- ## # This section contains a variety of useful functions to call in your # scripts. Take note of the portable wrappers for features provided by # some modern shells, which will fall back to slower equivalents on # less featureful shells. # func_append VAR VALUE # --------------------- # Append VALUE onto the existing contents of VAR. # We should try to minimise forks, especially on Windows where they are # unreasonably slow, so skip the feature probes when bash or zsh are # being used: if test set = "${BASH_VERSION+set}${ZSH_VERSION+set}"; then : ${_G_HAVE_ARITH_OP="yes"} : ${_G_HAVE_XSI_OPS="yes"} # The += operator was introduced in bash 3.1 case $BASH_VERSION in [12].* | 3.0 | 3.0*) ;; *) : ${_G_HAVE_PLUSEQ_OP="yes"} ;; esac fi # _G_HAVE_PLUSEQ_OP # Can be empty, in which case the shell is probed, "yes" if += is # useable or anything else if it does not work. test -z "$_G_HAVE_PLUSEQ_OP" \ && (eval 'x=a; x+=" b"; test "a b" = "$x"') 2>/dev/null \ && _G_HAVE_PLUSEQ_OP=yes if test yes = "$_G_HAVE_PLUSEQ_OP" then # This is an XSI compatible shell, allowing a faster implementation... eval 'func_append () { $debug_cmd eval "$1+=\$2" }' else # ...otherwise fall back to using expr, which is often a shell builtin. func_append () { $debug_cmd eval "$1=\$$1\$2" } fi # func_append_quoted VAR VALUE # ---------------------------- # Quote VALUE and append to the end of shell variable VAR, separated # by a space. if test yes = "$_G_HAVE_PLUSEQ_OP"; then eval 'func_append_quoted () { $debug_cmd func_quote_for_eval "$2" eval "$1+=\\ \$func_quote_for_eval_result" }' else func_append_quoted () { $debug_cmd func_quote_for_eval "$2" eval "$1=\$$1\\ \$func_quote_for_eval_result" } fi # func_append_uniq VAR VALUE # -------------------------- # Append unique VALUE onto the existing contents of VAR, assuming # entries are delimited by the first character of VALUE. For example: # # func_append_uniq options " --another-option option-argument" # # will only append to $options if " --another-option option-argument " # is not already present somewhere in $options already (note spaces at # each end implied by leading space in second argument). func_append_uniq () { $debug_cmd eval _G_current_value='`$ECHO $'$1'`' _G_delim=`expr "$2" : '\(.\)'` case $_G_delim$_G_current_value$_G_delim in *"$2$_G_delim"*) ;; *) func_append "$@" ;; esac } # func_arith TERM... # ------------------ # Set func_arith_result to the result of evaluating TERMs. test -z "$_G_HAVE_ARITH_OP" \ && (eval 'test 2 = $(( 1 + 1 ))') 2>/dev/null \ && _G_HAVE_ARITH_OP=yes if test yes = "$_G_HAVE_ARITH_OP"; then eval 'func_arith () { $debug_cmd func_arith_result=$(( $* )) }' else func_arith () { $debug_cmd func_arith_result=`expr "$@"` } fi # func_basename FILE # ------------------ # Set func_basename_result to FILE with everything up to and including # the last / stripped. if test yes = "$_G_HAVE_XSI_OPS"; then # If this shell supports suffix pattern removal, then use it to avoid # forking. Hide the definitions single quotes in case the shell chokes # on unsupported syntax... _b='func_basename_result=${1##*/}' _d='case $1 in */*) func_dirname_result=${1%/*}$2 ;; * ) func_dirname_result=$3 ;; esac' else # ...otherwise fall back to using sed. _b='func_basename_result=`$ECHO "$1" |$SED "$sed_basename"`' _d='func_dirname_result=`$ECHO "$1" |$SED "$sed_dirname"` if test "X$func_dirname_result" = "X$1"; then func_dirname_result=$3 else func_append func_dirname_result "$2" fi' fi eval 'func_basename () { $debug_cmd '"$_b"' }' # func_dirname FILE APPEND NONDIR_REPLACEMENT # ------------------------------------------- # Compute the dirname of FILE. If nonempty, add APPEND to the result, # otherwise set result to NONDIR_REPLACEMENT. eval 'func_dirname () { $debug_cmd '"$_d"' }' # func_dirname_and_basename FILE APPEND NONDIR_REPLACEMENT # -------------------------------------------------------- # Perform func_basename and func_dirname in a single function # call: # dirname: Compute the dirname of FILE. If nonempty, # add APPEND to the result, otherwise set result # to NONDIR_REPLACEMENT. # value returned in "$func_dirname_result" # basename: Compute filename of FILE. # value retuned in "$func_basename_result" # For efficiency, we do not delegate to the functions above but instead # duplicate the functionality here. eval 'func_dirname_and_basename () { $debug_cmd '"$_b"' '"$_d"' }' # func_echo ARG... # ---------------- # Echo program name prefixed message. func_echo () { $debug_cmd _G_message=$* func_echo_IFS=$IFS IFS=$nl for _G_line in $_G_message; do IFS=$func_echo_IFS $ECHO "$progname: $_G_line" done IFS=$func_echo_IFS } # func_echo_all ARG... # -------------------- # Invoke $ECHO with all args, space-separated. func_echo_all () { $ECHO "$*" } # func_echo_infix_1 INFIX ARG... # ------------------------------ # Echo program name, followed by INFIX on the first line, with any # additional lines not showing INFIX. func_echo_infix_1 () { $debug_cmd $require_term_colors _G_infix=$1; shift _G_indent=$_G_infix _G_prefix="$progname: $_G_infix: " _G_message=$* # Strip color escape sequences before counting printable length for _G_tc in "$tc_reset" "$tc_bold" "$tc_standout" "$tc_red" "$tc_green" "$tc_blue" "$tc_cyan" do test -n "$_G_tc" && { _G_esc_tc=`$ECHO "$_G_tc" | $SED "$sed_make_literal_regex"` _G_indent=`$ECHO "$_G_indent" | $SED "s|$_G_esc_tc||g"` } done _G_indent="$progname: "`echo "$_G_indent" | $SED 's|.| |g'`" " ## exclude from sc_prohibit_nested_quotes func_echo_infix_1_IFS=$IFS IFS=$nl for _G_line in $_G_message; do IFS=$func_echo_infix_1_IFS $ECHO "$_G_prefix$tc_bold$_G_line$tc_reset" >&2 _G_prefix=$_G_indent done IFS=$func_echo_infix_1_IFS } # func_error ARG... # ----------------- # Echo program name prefixed message to standard error. func_error () { $debug_cmd $require_term_colors func_echo_infix_1 " $tc_standout${tc_red}error$tc_reset" "$*" >&2 } # func_fatal_error ARG... # ----------------------- # Echo program name prefixed message to standard error, and exit. func_fatal_error () { $debug_cmd func_error "$*" exit $EXIT_FAILURE } # func_grep EXPRESSION FILENAME # ----------------------------- # Check whether EXPRESSION matches any line of FILENAME, without output. func_grep () { $debug_cmd $GREP "$1" "$2" >/dev/null 2>&1 } # func_len STRING # --------------- # Set func_len_result to the length of STRING. STRING may not # start with a hyphen. test -z "$_G_HAVE_XSI_OPS" \ && (eval 'x=a/b/c; test 5aa/bb/cc = "${#x}${x%%/*}${x%/*}${x#*/}${x##*/}"') 2>/dev/null \ && _G_HAVE_XSI_OPS=yes if test yes = "$_G_HAVE_XSI_OPS"; then eval 'func_len () { $debug_cmd func_len_result=${#1} }' else func_len () { $debug_cmd func_len_result=`expr "$1" : ".*" 2>/dev/null || echo $max_cmd_len` } fi # func_mkdir_p DIRECTORY-PATH # --------------------------- # Make sure the entire path to DIRECTORY-PATH is available. func_mkdir_p () { $debug_cmd _G_directory_path=$1 _G_dir_list= if test -n "$_G_directory_path" && test : != "$opt_dry_run"; then # Protect directory names starting with '-' case $_G_directory_path in -*) _G_directory_path=./$_G_directory_path ;; esac # While some portion of DIR does not yet exist... while test ! -d "$_G_directory_path"; do # ...make a list in topmost first order. Use a colon delimited # list incase some portion of path contains whitespace. _G_dir_list=$_G_directory_path:$_G_dir_list # If the last portion added has no slash in it, the list is done case $_G_directory_path in */*) ;; *) break ;; esac # ...otherwise throw away the child directory and loop _G_directory_path=`$ECHO "$_G_directory_path" | $SED -e "$sed_dirname"` done _G_dir_list=`$ECHO "$_G_dir_list" | $SED 's|:*$||'` func_mkdir_p_IFS=$IFS; IFS=: for _G_dir in $_G_dir_list; do IFS=$func_mkdir_p_IFS # mkdir can fail with a 'File exist' error if two processes # try to create one of the directories concurrently. Don't # stop in that case! $MKDIR "$_G_dir" 2>/dev/null || : done IFS=$func_mkdir_p_IFS # Bail out if we (or some other process) failed to create a directory. test -d "$_G_directory_path" || \ func_fatal_error "Failed to create '$1'" fi } # func_mktempdir [BASENAME] # ------------------------- # Make a temporary directory that won't clash with other running # libtool processes, and avoids race conditions if possible. If # given, BASENAME is the basename for that directory. func_mktempdir () { $debug_cmd _G_template=${TMPDIR-/tmp}/${1-$progname} if test : = "$opt_dry_run"; then # Return a directory name, but don't create it in dry-run mode _G_tmpdir=$_G_template-$$ else # If mktemp works, use that first and foremost _G_tmpdir=`mktemp -d "$_G_template-XXXXXXXX" 2>/dev/null` if test ! -d "$_G_tmpdir"; then # Failing that, at least try and use $RANDOM to avoid a race _G_tmpdir=$_G_template-${RANDOM-0}$$ func_mktempdir_umask=`umask` umask 0077 $MKDIR "$_G_tmpdir" umask $func_mktempdir_umask fi # If we're not in dry-run mode, bomb out on failure test -d "$_G_tmpdir" || \ func_fatal_error "cannot create temporary directory '$_G_tmpdir'" fi $ECHO "$_G_tmpdir" } # func_normal_abspath PATH # ------------------------ # Remove doubled-up and trailing slashes, "." path components, # and cancel out any ".." path components in PATH after making # it an absolute path. func_normal_abspath () { $debug_cmd # These SED scripts presuppose an absolute path with a trailing slash. _G_pathcar='s|^/\([^/]*\).*$|\1|' _G_pathcdr='s|^/[^/]*||' _G_removedotparts=':dotsl s|/\./|/|g t dotsl s|/\.$|/|' _G_collapseslashes='s|/\{1,\}|/|g' _G_finalslash='s|/*$|/|' # Start from root dir and reassemble the path. func_normal_abspath_result= func_normal_abspath_tpath=$1 func_normal_abspath_altnamespace= case $func_normal_abspath_tpath in "") # Empty path, that just means $cwd. func_stripname '' '/' "`pwd`" func_normal_abspath_result=$func_stripname_result return ;; # The next three entries are used to spot a run of precisely # two leading slashes without using negated character classes; # we take advantage of case's first-match behaviour. ///*) # Unusual form of absolute path, do nothing. ;; //*) # Not necessarily an ordinary path; POSIX reserves leading '//' # and for example Cygwin uses it to access remote file shares # over CIFS/SMB, so we conserve a leading double slash if found. func_normal_abspath_altnamespace=/ ;; /*) # Absolute path, do nothing. ;; *) # Relative path, prepend $cwd. func_normal_abspath_tpath=`pwd`/$func_normal_abspath_tpath ;; esac # Cancel out all the simple stuff to save iterations. We also want # the path to end with a slash for ease of parsing, so make sure # there is one (and only one) here. func_normal_abspath_tpath=`$ECHO "$func_normal_abspath_tpath" | $SED \ -e "$_G_removedotparts" -e "$_G_collapseslashes" -e "$_G_finalslash"` while :; do # Processed it all yet? if test / = "$func_normal_abspath_tpath"; then # If we ascended to the root using ".." the result may be empty now. if test -z "$func_normal_abspath_result"; then func_normal_abspath_result=/ fi break fi func_normal_abspath_tcomponent=`$ECHO "$func_normal_abspath_tpath" | $SED \ -e "$_G_pathcar"` func_normal_abspath_tpath=`$ECHO "$func_normal_abspath_tpath" | $SED \ -e "$_G_pathcdr"` # Figure out what to do with it case $func_normal_abspath_tcomponent in "") # Trailing empty path component, ignore it. ;; ..) # Parent dir; strip last assembled component from result. func_dirname "$func_normal_abspath_result" func_normal_abspath_result=$func_dirname_result ;; *) # Actual path component, append it. func_append func_normal_abspath_result "/$func_normal_abspath_tcomponent" ;; esac done # Restore leading double-slash if one was found on entry. func_normal_abspath_result=$func_normal_abspath_altnamespace$func_normal_abspath_result } # func_notquiet ARG... # -------------------- # Echo program name prefixed message only when not in quiet mode. func_notquiet () { $debug_cmd $opt_quiet || func_echo ${1+"$@"} # A bug in bash halts the script if the last line of a function # fails when set -e is in force, so we need another command to # work around that: : } # func_relative_path SRCDIR DSTDIR # -------------------------------- # Set func_relative_path_result to the relative path from SRCDIR to DSTDIR. func_relative_path () { $debug_cmd func_relative_path_result= func_normal_abspath "$1" func_relative_path_tlibdir=$func_normal_abspath_result func_normal_abspath "$2" func_relative_path_tbindir=$func_normal_abspath_result # Ascend the tree starting from libdir while :; do # check if we have found a prefix of bindir case $func_relative_path_tbindir in $func_relative_path_tlibdir) # found an exact match func_relative_path_tcancelled= break ;; $func_relative_path_tlibdir*) # found a matching prefix func_stripname "$func_relative_path_tlibdir" '' "$func_relative_path_tbindir" func_relative_path_tcancelled=$func_stripname_result if test -z "$func_relative_path_result"; then func_relative_path_result=. fi break ;; *) func_dirname $func_relative_path_tlibdir func_relative_path_tlibdir=$func_dirname_result if test -z "$func_relative_path_tlibdir"; then # Have to descend all the way to the root! func_relative_path_result=../$func_relative_path_result func_relative_path_tcancelled=$func_relative_path_tbindir break fi func_relative_path_result=../$func_relative_path_result ;; esac done # Now calculate path; take care to avoid doubling-up slashes. func_stripname '' '/' "$func_relative_path_result" func_relative_path_result=$func_stripname_result func_stripname '/' '/' "$func_relative_path_tcancelled" if test -n "$func_stripname_result"; then func_append func_relative_path_result "/$func_stripname_result" fi # Normalisation. If bindir is libdir, return '.' else relative path. if test -n "$func_relative_path_result"; then func_stripname './' '' "$func_relative_path_result" func_relative_path_result=$func_stripname_result fi test -n "$func_relative_path_result" || func_relative_path_result=. : } # func_quote_for_eval ARG... # -------------------------- # Aesthetically quote ARGs to be evaled later. # This function returns two values: # i) func_quote_for_eval_result # double-quoted, suitable for a subsequent eval # ii) func_quote_for_eval_unquoted_result # has all characters that are still active within double # quotes backslashified. func_quote_for_eval () { $debug_cmd func_quote_for_eval_unquoted_result= func_quote_for_eval_result= while test 0 -lt $#; do case $1 in *[\\\`\"\$]*) _G_unquoted_arg=`printf '%s\n' "$1" |$SED "$sed_quote_subst"` ;; *) _G_unquoted_arg=$1 ;; esac if test -n "$func_quote_for_eval_unquoted_result"; then func_append func_quote_for_eval_unquoted_result " $_G_unquoted_arg" else func_append func_quote_for_eval_unquoted_result "$_G_unquoted_arg" fi case $_G_unquoted_arg in # Double-quote args containing shell metacharacters to delay # word splitting, command substitution and variable expansion # for a subsequent eval. # Many Bourne shells cannot handle close brackets correctly # in scan sets, so we specify it separately. *[\[\~\#\^\&\*\(\)\{\}\|\;\<\>\?\'\ \ ]*|*]*|"") _G_quoted_arg=\"$_G_unquoted_arg\" ;; *) _G_quoted_arg=$_G_unquoted_arg ;; esac if test -n "$func_quote_for_eval_result"; then func_append func_quote_for_eval_result " $_G_quoted_arg" else func_append func_quote_for_eval_result "$_G_quoted_arg" fi shift done } # func_quote_for_expand ARG # ------------------------- # Aesthetically quote ARG to be evaled later; same as above, # but do not quote variable references. func_quote_for_expand () { $debug_cmd case $1 in *[\\\`\"]*) _G_arg=`$ECHO "$1" | $SED \ -e "$sed_double_quote_subst" -e "$sed_double_backslash"` ;; *) _G_arg=$1 ;; esac case $_G_arg in # Double-quote args containing shell metacharacters to delay # word splitting and command substitution for a subsequent eval. # Many Bourne shells cannot handle close brackets correctly # in scan sets, so we specify it separately. *[\[\~\#\^\&\*\(\)\{\}\|\;\<\>\?\'\ \ ]*|*]*|"") _G_arg=\"$_G_arg\" ;; esac func_quote_for_expand_result=$_G_arg } # func_stripname PREFIX SUFFIX NAME # --------------------------------- # strip PREFIX and SUFFIX from NAME, and store in func_stripname_result. # PREFIX and SUFFIX must not contain globbing or regex special # characters, hashes, percent signs, but SUFFIX may contain a leading # dot (in which case that matches only a dot). if test yes = "$_G_HAVE_XSI_OPS"; then eval 'func_stripname () { $debug_cmd # pdksh 5.2.14 does not do ${X%$Y} correctly if both X and Y are # positional parameters, so assign one to ordinary variable first. func_stripname_result=$3 func_stripname_result=${func_stripname_result#"$1"} func_stripname_result=${func_stripname_result%"$2"} }' else func_stripname () { $debug_cmd case $2 in .*) func_stripname_result=`$ECHO "$3" | $SED -e "s%^$1%%" -e "s%\\\\$2\$%%"`;; *) func_stripname_result=`$ECHO "$3" | $SED -e "s%^$1%%" -e "s%$2\$%%"`;; esac } fi # func_show_eval CMD [FAIL_EXP] # ----------------------------- # Unless opt_quiet is true, then output CMD. Then, if opt_dryrun is # not true, evaluate CMD. If the evaluation of CMD fails, and FAIL_EXP # is given, then evaluate it. func_show_eval () { $debug_cmd _G_cmd=$1 _G_fail_exp=${2-':'} func_quote_for_expand "$_G_cmd" eval "func_notquiet $func_quote_for_expand_result" $opt_dry_run || { eval "$_G_cmd" _G_status=$? if test 0 -ne "$_G_status"; then eval "(exit $_G_status); $_G_fail_exp" fi } } # func_show_eval_locale CMD [FAIL_EXP] # ------------------------------------ # Unless opt_quiet is true, then output CMD. Then, if opt_dryrun is # not true, evaluate CMD. If the evaluation of CMD fails, and FAIL_EXP # is given, then evaluate it. Use the saved locale for evaluation. func_show_eval_locale () { $debug_cmd _G_cmd=$1 _G_fail_exp=${2-':'} $opt_quiet || { func_quote_for_expand "$_G_cmd" eval "func_echo $func_quote_for_expand_result" } $opt_dry_run || { eval "$_G_user_locale $_G_cmd" _G_status=$? eval "$_G_safe_locale" if test 0 -ne "$_G_status"; then eval "(exit $_G_status); $_G_fail_exp" fi } } # func_tr_sh # ---------- # Turn $1 into a string suitable for a shell variable name. # Result is stored in $func_tr_sh_result. All characters # not in the set a-zA-Z0-9_ are replaced with '_'. Further, # if $1 begins with a digit, a '_' is prepended as well. func_tr_sh () { $debug_cmd case $1 in [0-9]* | *[!a-zA-Z0-9_]*) func_tr_sh_result=`$ECHO "$1" | $SED -e 's/^\([0-9]\)/_\1/' -e 's/[^a-zA-Z0-9_]/_/g'` ;; * ) func_tr_sh_result=$1 ;; esac } # func_verbose ARG... # ------------------- # Echo program name prefixed message in verbose mode only. func_verbose () { $debug_cmd $opt_verbose && func_echo "$*" : } # func_warn_and_continue ARG... # ----------------------------- # Echo program name prefixed warning message to standard error. func_warn_and_continue () { $debug_cmd $require_term_colors func_echo_infix_1 "${tc_red}warning$tc_reset" "$*" >&2 } # func_warning CATEGORY ARG... # ---------------------------- # Echo program name prefixed warning message to standard error. Warning # messages can be filtered according to CATEGORY, where this function # elides messages where CATEGORY is not listed in the global variable # 'opt_warning_types'. func_warning () { $debug_cmd # CATEGORY must be in the warning_categories list! case " $warning_categories " in *" $1 "*) ;; *) func_internal_error "invalid warning category '$1'" ;; esac _G_category=$1 shift case " $opt_warning_types " in *" $_G_category "*) $warning_func ${1+"$@"} ;; esac } # func_sort_ver VER1 VER2 # ----------------------- # 'sort -V' is not generally available. # Note this deviates from the version comparison in automake # in that it treats 1.5 < 1.5.0, and treats 1.4.4a < 1.4-p3a # but this should suffice as we won't be specifying old # version formats or redundant trailing .0 in bootstrap.conf. # If we did want full compatibility then we should probably # use m4_version_compare from autoconf. func_sort_ver () { $debug_cmd printf '%s\n%s\n' "$1" "$2" \ | sort -t. -k 1,1n -k 2,2n -k 3,3n -k 4,4n -k 5,5n -k 6,6n -k 7,7n -k 8,8n -k 9,9n } # func_lt_ver PREV CURR # --------------------- # Return true if PREV and CURR are in the correct order according to # func_sort_ver, otherwise false. Use it like this: # # func_lt_ver "$prev_ver" "$proposed_ver" || func_fatal_error "..." func_lt_ver () { $debug_cmd test "x$1" = x`func_sort_ver "$1" "$2" | $SED 1q` } # Local variables: # mode: shell-script # sh-indentation: 2 # eval: (add-hook 'before-save-hook 'time-stamp) # time-stamp-pattern: "10/scriptversion=%:y-%02m-%02d.%02H; # UTC" # time-stamp-time-zone: "UTC" # End: #! /bin/sh # Set a version string for this script. scriptversion=2014-01-07.03; # UTC # A portable, pluggable option parser for Bourne shell. # Written by Gary V. Vaughan, 2010 # Copyright (C) 2010-2015 Free Software Foundation, Inc. # This is free software; see the source for copying conditions. There is NO # warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # You should have received a copy of the GNU General Public License # along with this program. If not, see . # Please report bugs or propose patches to gary@gnu.org. ## ------ ## ## Usage. ## ## ------ ## # This file is a library for parsing options in your shell scripts along # with assorted other useful supporting features that you can make use # of too. # # For the simplest scripts you might need only: # # #!/bin/sh # . relative/path/to/funclib.sh # . relative/path/to/options-parser # scriptversion=1.0 # func_options ${1+"$@"} # eval set dummy "$func_options_result"; shift # ...rest of your script... # # In order for the '--version' option to work, you will need to have a # suitably formatted comment like the one at the top of this file # starting with '# Written by ' and ending with '# warranty; '. # # For '-h' and '--help' to work, you will also need a one line # description of your script's purpose in a comment directly above the # '# Written by ' line, like the one at the top of this file. # # The default options also support '--debug', which will turn on shell # execution tracing (see the comment above debug_cmd below for another # use), and '--verbose' and the func_verbose function to allow your script # to display verbose messages only when your user has specified # '--verbose'. # # After sourcing this file, you can plug processing for additional # options by amending the variables from the 'Configuration' section # below, and following the instructions in the 'Option parsing' # section further down. ## -------------- ## ## Configuration. ## ## -------------- ## # You should override these variables in your script after sourcing this # file so that they reflect the customisations you have added to the # option parser. # The usage line for option parsing errors and the start of '-h' and # '--help' output messages. You can embed shell variables for delayed # expansion at the time the message is displayed, but you will need to # quote other shell meta-characters carefully to prevent them being # expanded when the contents are evaled. usage='$progpath [OPTION]...' # Short help message in response to '-h' and '--help'. Add to this or # override it after sourcing this library to reflect the full set of # options your script accepts. usage_message="\ --debug enable verbose shell tracing -W, --warnings=CATEGORY report the warnings falling in CATEGORY [all] -v, --verbose verbosely report processing --version print version information and exit -h, --help print short or long help message and exit " # Additional text appended to 'usage_message' in response to '--help'. long_help_message=" Warning categories include: 'all' show all warnings 'none' turn off all the warnings 'error' warnings are treated as fatal errors" # Help message printed before fatal option parsing errors. fatal_help="Try '\$progname --help' for more information." ## ------------------------- ## ## Hook function management. ## ## ------------------------- ## # This section contains functions for adding, removing, and running hooks # to the main code. A hook is just a named list of of function, that can # be run in order later on. # func_hookable FUNC_NAME # ----------------------- # Declare that FUNC_NAME will run hooks added with # 'func_add_hook FUNC_NAME ...'. func_hookable () { $debug_cmd func_append hookable_fns " $1" } # func_add_hook FUNC_NAME HOOK_FUNC # --------------------------------- # Request that FUNC_NAME call HOOK_FUNC before it returns. FUNC_NAME must # first have been declared "hookable" by a call to 'func_hookable'. func_add_hook () { $debug_cmd case " $hookable_fns " in *" $1 "*) ;; *) func_fatal_error "'$1' does not accept hook functions." ;; esac eval func_append ${1}_hooks '" $2"' } # func_remove_hook FUNC_NAME HOOK_FUNC # ------------------------------------ # Remove HOOK_FUNC from the list of functions called by FUNC_NAME. func_remove_hook () { $debug_cmd eval ${1}_hooks='`$ECHO "\$'$1'_hooks" |$SED "s| '$2'||"`' } # func_run_hooks FUNC_NAME [ARG]... # --------------------------------- # Run all hook functions registered to FUNC_NAME. # It is assumed that the list of hook functions contains nothing more # than a whitespace-delimited list of legal shell function names, and # no effort is wasted trying to catch shell meta-characters or preserve # whitespace. func_run_hooks () { $debug_cmd case " $hookable_fns " in *" $1 "*) ;; *) func_fatal_error "'$1' does not support hook funcions.n" ;; esac eval _G_hook_fns=\$$1_hooks; shift for _G_hook in $_G_hook_fns; do eval $_G_hook '"$@"' # store returned options list back into positional # parameters for next 'cmd' execution. eval _G_hook_result=\$${_G_hook}_result eval set dummy "$_G_hook_result"; shift done func_quote_for_eval ${1+"$@"} func_run_hooks_result=$func_quote_for_eval_result } ## --------------- ## ## Option parsing. ## ## --------------- ## # In order to add your own option parsing hooks, you must accept the # full positional parameter list in your hook function, remove any # options that you action, and then pass back the remaining unprocessed # options in '_result', escaped suitably for # 'eval'. Like this: # # my_options_prep () # { # $debug_cmd # # # Extend the existing usage message. # usage_message=$usage_message' # -s, --silent don'\''t print informational messages # ' # # func_quote_for_eval ${1+"$@"} # my_options_prep_result=$func_quote_for_eval_result # } # func_add_hook func_options_prep my_options_prep # # # my_silent_option () # { # $debug_cmd # # # Note that for efficiency, we parse as many options as we can # # recognise in a loop before passing the remainder back to the # # caller on the first unrecognised argument we encounter. # while test $# -gt 0; do # opt=$1; shift # case $opt in # --silent|-s) opt_silent=: ;; # # Separate non-argument short options: # -s*) func_split_short_opt "$_G_opt" # set dummy "$func_split_short_opt_name" \ # "-$func_split_short_opt_arg" ${1+"$@"} # shift # ;; # *) set dummy "$_G_opt" "$*"; shift; break ;; # esac # done # # func_quote_for_eval ${1+"$@"} # my_silent_option_result=$func_quote_for_eval_result # } # func_add_hook func_parse_options my_silent_option # # # my_option_validation () # { # $debug_cmd # # $opt_silent && $opt_verbose && func_fatal_help "\ # '--silent' and '--verbose' options are mutually exclusive." # # func_quote_for_eval ${1+"$@"} # my_option_validation_result=$func_quote_for_eval_result # } # func_add_hook func_validate_options my_option_validation # # You'll alse need to manually amend $usage_message to reflect the extra # options you parse. It's preferable to append if you can, so that # multiple option parsing hooks can be added safely. # func_options [ARG]... # --------------------- # All the functions called inside func_options are hookable. See the # individual implementations for details. func_hookable func_options func_options () { $debug_cmd func_options_prep ${1+"$@"} eval func_parse_options \ ${func_options_prep_result+"$func_options_prep_result"} eval func_validate_options \ ${func_parse_options_result+"$func_parse_options_result"} eval func_run_hooks func_options \ ${func_validate_options_result+"$func_validate_options_result"} # save modified positional parameters for caller func_options_result=$func_run_hooks_result } # func_options_prep [ARG]... # -------------------------- # All initialisations required before starting the option parse loop. # Note that when calling hook functions, we pass through the list of # positional parameters. If a hook function modifies that list, and # needs to propogate that back to rest of this script, then the complete # modified list must be put in 'func_run_hooks_result' before # returning. func_hookable func_options_prep func_options_prep () { $debug_cmd # Option defaults: opt_verbose=false opt_warning_types= func_run_hooks func_options_prep ${1+"$@"} # save modified positional parameters for caller func_options_prep_result=$func_run_hooks_result } # func_parse_options [ARG]... # --------------------------- # The main option parsing loop. func_hookable func_parse_options func_parse_options () { $debug_cmd func_parse_options_result= # this just eases exit handling while test $# -gt 0; do # Defer to hook functions for initial option parsing, so they # get priority in the event of reusing an option name. func_run_hooks func_parse_options ${1+"$@"} # Adjust func_parse_options positional parameters to match eval set dummy "$func_run_hooks_result"; shift # Break out of the loop if we already parsed every option. test $# -gt 0 || break _G_opt=$1 shift case $_G_opt in --debug|-x) debug_cmd='set -x' func_echo "enabling shell trace mode" $debug_cmd ;; --no-warnings|--no-warning|--no-warn) set dummy --warnings none ${1+"$@"} shift ;; --warnings|--warning|-W) test $# = 0 && func_missing_arg $_G_opt && break case " $warning_categories $1" in *" $1 "*) # trailing space prevents matching last $1 above func_append_uniq opt_warning_types " $1" ;; *all) opt_warning_types=$warning_categories ;; *none) opt_warning_types=none warning_func=: ;; *error) opt_warning_types=$warning_categories warning_func=func_fatal_error ;; *) func_fatal_error \ "unsupported warning category: '$1'" ;; esac shift ;; --verbose|-v) opt_verbose=: ;; --version) func_version ;; -\?|-h) func_usage ;; --help) func_help ;; # Separate optargs to long options (plugins may need this): --*=*) func_split_equals "$_G_opt" set dummy "$func_split_equals_lhs" \ "$func_split_equals_rhs" ${1+"$@"} shift ;; # Separate optargs to short options: -W*) func_split_short_opt "$_G_opt" set dummy "$func_split_short_opt_name" \ "$func_split_short_opt_arg" ${1+"$@"} shift ;; # Separate non-argument short options: -\?*|-h*|-v*|-x*) func_split_short_opt "$_G_opt" set dummy "$func_split_short_opt_name" \ "-$func_split_short_opt_arg" ${1+"$@"} shift ;; --) break ;; -*) func_fatal_help "unrecognised option: '$_G_opt'" ;; *) set dummy "$_G_opt" ${1+"$@"}; shift; break ;; esac done # save modified positional parameters for caller func_quote_for_eval ${1+"$@"} func_parse_options_result=$func_quote_for_eval_result } # func_validate_options [ARG]... # ------------------------------ # Perform any sanity checks on option settings and/or unconsumed # arguments. func_hookable func_validate_options func_validate_options () { $debug_cmd # Display all warnings if -W was not given. test -n "$opt_warning_types" || opt_warning_types=" $warning_categories" func_run_hooks func_validate_options ${1+"$@"} # Bail if the options were screwed! $exit_cmd $EXIT_FAILURE # save modified positional parameters for caller func_validate_options_result=$func_run_hooks_result } ## ----------------- ## ## Helper functions. ## ## ----------------- ## # This section contains the helper functions used by the rest of the # hookable option parser framework in ascii-betical order. # func_fatal_help ARG... # ---------------------- # Echo program name prefixed message to standard error, followed by # a help hint, and exit. func_fatal_help () { $debug_cmd eval \$ECHO \""Usage: $usage"\" eval \$ECHO \""$fatal_help"\" func_error ${1+"$@"} exit $EXIT_FAILURE } # func_help # --------- # Echo long help message to standard output and exit. func_help () { $debug_cmd func_usage_message $ECHO "$long_help_message" exit 0 } # func_missing_arg ARGNAME # ------------------------ # Echo program name prefixed message to standard error and set global # exit_cmd. func_missing_arg () { $debug_cmd func_error "Missing argument for '$1'." exit_cmd=exit } # func_split_equals STRING # ------------------------ # Set func_split_equals_lhs and func_split_equals_rhs shell variables after # splitting STRING at the '=' sign. test -z "$_G_HAVE_XSI_OPS" \ && (eval 'x=a/b/c; test 5aa/bb/cc = "${#x}${x%%/*}${x%/*}${x#*/}${x##*/}"') 2>/dev/null \ && _G_HAVE_XSI_OPS=yes if test yes = "$_G_HAVE_XSI_OPS" then # This is an XSI compatible shell, allowing a faster implementation... eval 'func_split_equals () { $debug_cmd func_split_equals_lhs=${1%%=*} func_split_equals_rhs=${1#*=} test "x$func_split_equals_lhs" = "x$1" \ && func_split_equals_rhs= }' else # ...otherwise fall back to using expr, which is often a shell builtin. func_split_equals () { $debug_cmd func_split_equals_lhs=`expr "x$1" : 'x\([^=]*\)'` func_split_equals_rhs= test "x$func_split_equals_lhs" = "x$1" \ || func_split_equals_rhs=`expr "x$1" : 'x[^=]*=\(.*\)$'` } fi #func_split_equals # func_split_short_opt SHORTOPT # ----------------------------- # Set func_split_short_opt_name and func_split_short_opt_arg shell # variables after splitting SHORTOPT after the 2nd character. if test yes = "$_G_HAVE_XSI_OPS" then # This is an XSI compatible shell, allowing a faster implementation... eval 'func_split_short_opt () { $debug_cmd func_split_short_opt_arg=${1#??} func_split_short_opt_name=${1%"$func_split_short_opt_arg"} }' else # ...otherwise fall back to using expr, which is often a shell builtin. func_split_short_opt () { $debug_cmd func_split_short_opt_name=`expr "x$1" : 'x-\(.\)'` func_split_short_opt_arg=`expr "x$1" : 'x-.\(.*\)$'` } fi #func_split_short_opt # func_usage # ---------- # Echo short help message to standard output and exit. func_usage () { $debug_cmd func_usage_message $ECHO "Run '$progname --help |${PAGER-more}' for full usage" exit 0 } # func_usage_message # ------------------ # Echo short help message to standard output. func_usage_message () { $debug_cmd eval \$ECHO \""Usage: $usage"\" echo $SED -n 's|^# || /^Written by/{ x;p;x } h /^Written by/q' < "$progpath" echo eval \$ECHO \""$usage_message"\" } # func_version # ------------ # Echo version message to standard output and exit. func_version () { $debug_cmd printf '%s\n' "$progname $scriptversion" $SED -n ' /(C)/!b go :more /\./!{ N s|\n# | | b more } :go /^# Written by /,/# warranty; / { s|^# || s|^# *$|| s|\((C)\)[ 0-9,-]*[ ,-]\([1-9][0-9]* \)|\1 \2| p } /^# Written by / { s|^# || p } /^warranty; /q' < "$progpath" exit $? } # Local variables: # mode: shell-script # sh-indentation: 2 # eval: (add-hook 'before-save-hook 'time-stamp) # time-stamp-pattern: "10/scriptversion=%:y-%02m-%02d.%02H; # UTC" # time-stamp-time-zone: "UTC" # End: # Set a version string. scriptversion='(GNU libtool) 2.4.6' # func_echo ARG... # ---------------- # Libtool also displays the current mode in messages, so override # funclib.sh func_echo with this custom definition. func_echo () { $debug_cmd _G_message=$* func_echo_IFS=$IFS IFS=$nl for _G_line in $_G_message; do IFS=$func_echo_IFS $ECHO "$progname${opt_mode+: $opt_mode}: $_G_line" done IFS=$func_echo_IFS } # func_warning ARG... # ------------------- # Libtool warnings are not categorized, so override funclib.sh # func_warning with this simpler definition. func_warning () { $debug_cmd $warning_func ${1+"$@"} } ## ---------------- ## ## Options parsing. ## ## ---------------- ## # Hook in the functions to make sure our own options are parsed during # the option parsing loop. usage='$progpath [OPTION]... [MODE-ARG]...' # Short help message in response to '-h'. usage_message="Options: --config show all configuration variables --debug enable verbose shell tracing -n, --dry-run display commands without modifying any files --features display basic configuration information and exit --mode=MODE use operation mode MODE --no-warnings equivalent to '-Wnone' --preserve-dup-deps don't remove duplicate dependency libraries --quiet, --silent don't print informational messages --tag=TAG use configuration variables from tag TAG -v, --verbose print more informational messages than default --version print version information -W, --warnings=CATEGORY report the warnings falling in CATEGORY [all] -h, --help, --help-all print short, long, or detailed help message " # Additional text appended to 'usage_message' in response to '--help'. func_help () { $debug_cmd func_usage_message $ECHO "$long_help_message MODE must be one of the following: clean remove files from the build directory compile compile a source file into a libtool object execute automatically set library path, then run a program finish complete the installation of libtool libraries install install libraries or executables link create a library or an executable uninstall remove libraries from an installed directory MODE-ARGS vary depending on the MODE. When passed as first option, '--mode=MODE' may be abbreviated as 'MODE' or a unique abbreviation of that. Try '$progname --help --mode=MODE' for a more detailed description of MODE. When reporting a bug, please describe a test case to reproduce it and include the following information: host-triplet: $host shell: $SHELL compiler: $LTCC compiler flags: $LTCFLAGS linker: $LD (gnu? $with_gnu_ld) version: $progname (GNU libtool) 2.4.6 automake: `($AUTOMAKE --version) 2>/dev/null |$SED 1q` autoconf: `($AUTOCONF --version) 2>/dev/null |$SED 1q` Report bugs to . GNU libtool home page: . General help using GNU software: ." exit 0 } # func_lo2o OBJECT-NAME # --------------------- # Transform OBJECT-NAME from a '.lo' suffix to the platform specific # object suffix. lo2o=s/\\.lo\$/.$objext/ o2lo=s/\\.$objext\$/.lo/ if test yes = "$_G_HAVE_XSI_OPS"; then eval 'func_lo2o () { case $1 in *.lo) func_lo2o_result=${1%.lo}.$objext ;; * ) func_lo2o_result=$1 ;; esac }' # func_xform LIBOBJ-OR-SOURCE # --------------------------- # Transform LIBOBJ-OR-SOURCE from a '.o' or '.c' (or otherwise) # suffix to a '.lo' libtool-object suffix. eval 'func_xform () { func_xform_result=${1%.*}.lo }' else # ...otherwise fall back to using sed. func_lo2o () { func_lo2o_result=`$ECHO "$1" | $SED "$lo2o"` } func_xform () { func_xform_result=`$ECHO "$1" | $SED 's|\.[^.]*$|.lo|'` } fi # func_fatal_configuration ARG... # ------------------------------- # Echo program name prefixed message to standard error, followed by # a configuration failure hint, and exit. func_fatal_configuration () { func__fatal_error ${1+"$@"} \ "See the $PACKAGE documentation for more information." \ "Fatal configuration error." } # func_config # ----------- # Display the configuration for all the tags in this script. func_config () { re_begincf='^# ### BEGIN LIBTOOL' re_endcf='^# ### END LIBTOOL' # Default configuration. $SED "1,/$re_begincf CONFIG/d;/$re_endcf CONFIG/,\$d" < "$progpath" # Now print the configurations for the tags. for tagname in $taglist; do $SED -n "/$re_begincf TAG CONFIG: $tagname\$/,/$re_endcf TAG CONFIG: $tagname\$/p" < "$progpath" done exit $? } # func_features # ------------- # Display the features supported by this script. func_features () { echo "host: $host" if test yes = "$build_libtool_libs"; then echo "enable shared libraries" else echo "disable shared libraries" fi if test yes = "$build_old_libs"; then echo "enable static libraries" else echo "disable static libraries" fi exit $? } # func_enable_tag TAGNAME # ----------------------- # Verify that TAGNAME is valid, and either flag an error and exit, or # enable the TAGNAME tag. We also add TAGNAME to the global $taglist # variable here. func_enable_tag () { # Global variable: tagname=$1 re_begincf="^# ### BEGIN LIBTOOL TAG CONFIG: $tagname\$" re_endcf="^# ### END LIBTOOL TAG CONFIG: $tagname\$" sed_extractcf=/$re_begincf/,/$re_endcf/p # Validate tagname. case $tagname in *[!-_A-Za-z0-9,/]*) func_fatal_error "invalid tag name: $tagname" ;; esac # Don't test for the "default" C tag, as we know it's # there but not specially marked. case $tagname in CC) ;; *) if $GREP "$re_begincf" "$progpath" >/dev/null 2>&1; then taglist="$taglist $tagname" # Evaluate the configuration. Be careful to quote the path # and the sed script, to avoid splitting on whitespace, but # also don't use non-portable quotes within backquotes within # quotes we have to do it in 2 steps: extractedcf=`$SED -n -e "$sed_extractcf" < "$progpath"` eval "$extractedcf" else func_error "ignoring unknown tag $tagname" fi ;; esac } # func_check_version_match # ------------------------ # Ensure that we are using m4 macros, and libtool script from the same # release of libtool. func_check_version_match () { if test "$package_revision" != "$macro_revision"; then if test "$VERSION" != "$macro_version"; then if test -z "$macro_version"; then cat >&2 <<_LT_EOF $progname: Version mismatch error. This is $PACKAGE $VERSION, but the $progname: definition of this LT_INIT comes from an older release. $progname: You should recreate aclocal.m4 with macros from $PACKAGE $VERSION $progname: and run autoconf again. _LT_EOF else cat >&2 <<_LT_EOF $progname: Version mismatch error. This is $PACKAGE $VERSION, but the $progname: definition of this LT_INIT comes from $PACKAGE $macro_version. $progname: You should recreate aclocal.m4 with macros from $PACKAGE $VERSION $progname: and run autoconf again. _LT_EOF fi else cat >&2 <<_LT_EOF $progname: Version mismatch error. This is $PACKAGE $VERSION, revision $package_revision, $progname: but the definition of this LT_INIT comes from revision $macro_revision. $progname: You should recreate aclocal.m4 with macros from revision $package_revision $progname: of $PACKAGE $VERSION and run autoconf again. _LT_EOF fi exit $EXIT_MISMATCH fi } # libtool_options_prep [ARG]... # ----------------------------- # Preparation for options parsed by libtool. libtool_options_prep () { $debug_mode # Option defaults: opt_config=false opt_dlopen= opt_dry_run=false opt_help=false opt_mode= opt_preserve_dup_deps=false opt_quiet=false nonopt= preserve_args= # Shorthand for --mode=foo, only valid as the first argument case $1 in clean|clea|cle|cl) shift; set dummy --mode clean ${1+"$@"}; shift ;; compile|compil|compi|comp|com|co|c) shift; set dummy --mode compile ${1+"$@"}; shift ;; execute|execut|execu|exec|exe|ex|e) shift; set dummy --mode execute ${1+"$@"}; shift ;; finish|finis|fini|fin|fi|f) shift; set dummy --mode finish ${1+"$@"}; shift ;; install|instal|insta|inst|ins|in|i) shift; set dummy --mode install ${1+"$@"}; shift ;; link|lin|li|l) shift; set dummy --mode link ${1+"$@"}; shift ;; uninstall|uninstal|uninsta|uninst|unins|unin|uni|un|u) shift; set dummy --mode uninstall ${1+"$@"}; shift ;; esac # Pass back the list of options. func_quote_for_eval ${1+"$@"} libtool_options_prep_result=$func_quote_for_eval_result } func_add_hook func_options_prep libtool_options_prep # libtool_parse_options [ARG]... # --------------------------------- # Provide handling for libtool specific options. libtool_parse_options () { $debug_cmd # Perform our own loop to consume as many options as possible in # each iteration. while test $# -gt 0; do _G_opt=$1 shift case $_G_opt in --dry-run|--dryrun|-n) opt_dry_run=: ;; --config) func_config ;; --dlopen|-dlopen) opt_dlopen="${opt_dlopen+$opt_dlopen }$1" shift ;; --preserve-dup-deps) opt_preserve_dup_deps=: ;; --features) func_features ;; --finish) set dummy --mode finish ${1+"$@"}; shift ;; --help) opt_help=: ;; --help-all) opt_help=': help-all' ;; --mode) test $# = 0 && func_missing_arg $_G_opt && break opt_mode=$1 case $1 in # Valid mode arguments: clean|compile|execute|finish|install|link|relink|uninstall) ;; # Catch anything else as an error *) func_error "invalid argument for $_G_opt" exit_cmd=exit break ;; esac shift ;; --no-silent|--no-quiet) opt_quiet=false func_append preserve_args " $_G_opt" ;; --no-warnings|--no-warning|--no-warn) opt_warning=false func_append preserve_args " $_G_opt" ;; --no-verbose) opt_verbose=false func_append preserve_args " $_G_opt" ;; --silent|--quiet) opt_quiet=: opt_verbose=false func_append preserve_args " $_G_opt" ;; --tag) test $# = 0 && func_missing_arg $_G_opt && break opt_tag=$1 func_append preserve_args " $_G_opt $1" func_enable_tag "$1" shift ;; --verbose|-v) opt_quiet=false opt_verbose=: func_append preserve_args " $_G_opt" ;; # An option not handled by this hook function: *) set dummy "$_G_opt" ${1+"$@"}; shift; break ;; esac done # save modified positional parameters for caller func_quote_for_eval ${1+"$@"} libtool_parse_options_result=$func_quote_for_eval_result } func_add_hook func_parse_options libtool_parse_options # libtool_validate_options [ARG]... # --------------------------------- # Perform any sanity checks on option settings and/or unconsumed # arguments. libtool_validate_options () { # save first non-option argument if test 0 -lt $#; then nonopt=$1 shift fi # preserve --debug test : = "$debug_cmd" || func_append preserve_args " --debug" case $host in # Solaris2 added to fix http://debbugs.gnu.org/cgi/bugreport.cgi?bug=16452 # see also: http://gcc.gnu.org/bugzilla/show_bug.cgi?id=59788 *cygwin* | *mingw* | *pw32* | *cegcc* | *solaris2* | *os2*) # don't eliminate duplications in $postdeps and $predeps opt_duplicate_compiler_generated_deps=: ;; *) opt_duplicate_compiler_generated_deps=$opt_preserve_dup_deps ;; esac $opt_help || { # Sanity checks first: func_check_version_match test yes != "$build_libtool_libs" \ && test yes != "$build_old_libs" \ && func_fatal_configuration "not configured to build any kind of library" # Darwin sucks eval std_shrext=\"$shrext_cmds\" # Only execute mode is allowed to have -dlopen flags. if test -n "$opt_dlopen" && test execute != "$opt_mode"; then func_error "unrecognized option '-dlopen'" $ECHO "$help" 1>&2 exit $EXIT_FAILURE fi # Change the help message to a mode-specific one. generic_help=$help help="Try '$progname --help --mode=$opt_mode' for more information." } # Pass back the unparsed argument list func_quote_for_eval ${1+"$@"} libtool_validate_options_result=$func_quote_for_eval_result } func_add_hook func_validate_options libtool_validate_options # Process options as early as possible so that --help and --version # can return quickly. func_options ${1+"$@"} eval set dummy "$func_options_result"; shift ## ----------- ## ## Main. ## ## ----------- ## magic='%%%MAGIC variable%%%' magic_exe='%%%MAGIC EXE variable%%%' # Global variables. extracted_archives= extracted_serial=0 # If this variable is set in any of the actions, the command in it # will be execed at the end. This prevents here-documents from being # left over by shells. exec_cmd= # A function that is used when there is no print builtin or printf. func_fallback_echo () { eval 'cat <<_LTECHO_EOF $1 _LTECHO_EOF' } # func_generated_by_libtool # True iff stdin has been generated by Libtool. This function is only # a basic sanity check; it will hardly flush out determined imposters. func_generated_by_libtool_p () { $GREP "^# Generated by .*$PACKAGE" > /dev/null 2>&1 } # func_lalib_p file # True iff FILE is a libtool '.la' library or '.lo' object file. # This function is only a basic sanity check; it will hardly flush out # determined imposters. func_lalib_p () { test -f "$1" && $SED -e 4q "$1" 2>/dev/null | func_generated_by_libtool_p } # func_lalib_unsafe_p file # True iff FILE is a libtool '.la' library or '.lo' object file. # This function implements the same check as func_lalib_p without # resorting to external programs. To this end, it redirects stdin and # closes it afterwards, without saving the original file descriptor. # As a safety measure, use it only where a negative result would be # fatal anyway. Works if 'file' does not exist. func_lalib_unsafe_p () { lalib_p=no if test -f "$1" && test -r "$1" && exec 5<&0 <"$1"; then for lalib_p_l in 1 2 3 4 do read lalib_p_line case $lalib_p_line in \#\ Generated\ by\ *$PACKAGE* ) lalib_p=yes; break;; esac done exec 0<&5 5<&- fi test yes = "$lalib_p" } # func_ltwrapper_script_p file # True iff FILE is a libtool wrapper script # This function is only a basic sanity check; it will hardly flush out # determined imposters. func_ltwrapper_script_p () { test -f "$1" && $lt_truncate_bin < "$1" 2>/dev/null | func_generated_by_libtool_p } # func_ltwrapper_executable_p file # True iff FILE is a libtool wrapper executable # This function is only a basic sanity check; it will hardly flush out # determined imposters. func_ltwrapper_executable_p () { func_ltwrapper_exec_suffix= case $1 in *.exe) ;; *) func_ltwrapper_exec_suffix=.exe ;; esac $GREP "$magic_exe" "$1$func_ltwrapper_exec_suffix" >/dev/null 2>&1 } # func_ltwrapper_scriptname file # Assumes file is an ltwrapper_executable # uses $file to determine the appropriate filename for a # temporary ltwrapper_script. func_ltwrapper_scriptname () { func_dirname_and_basename "$1" "" "." func_stripname '' '.exe' "$func_basename_result" func_ltwrapper_scriptname_result=$func_dirname_result/$objdir/${func_stripname_result}_ltshwrapper } # func_ltwrapper_p file # True iff FILE is a libtool wrapper script or wrapper executable # This function is only a basic sanity check; it will hardly flush out # determined imposters. func_ltwrapper_p () { func_ltwrapper_script_p "$1" || func_ltwrapper_executable_p "$1" } # func_execute_cmds commands fail_cmd # Execute tilde-delimited COMMANDS. # If FAIL_CMD is given, eval that upon failure. # FAIL_CMD may read-access the current command in variable CMD! func_execute_cmds () { $debug_cmd save_ifs=$IFS; IFS='~' for cmd in $1; do IFS=$sp$nl eval cmd=\"$cmd\" IFS=$save_ifs func_show_eval "$cmd" "${2-:}" done IFS=$save_ifs } # func_source file # Source FILE, adding directory component if necessary. # Note that it is not necessary on cygwin/mingw to append a dot to # FILE even if both FILE and FILE.exe exist: automatic-append-.exe # behavior happens only for exec(3), not for open(2)! Also, sourcing # 'FILE.' does not work on cygwin managed mounts. func_source () { $debug_cmd case $1 in */* | *\\*) . "$1" ;; *) . "./$1" ;; esac } # func_resolve_sysroot PATH # Replace a leading = in PATH with a sysroot. Store the result into # func_resolve_sysroot_result func_resolve_sysroot () { func_resolve_sysroot_result=$1 case $func_resolve_sysroot_result in =*) func_stripname '=' '' "$func_resolve_sysroot_result" func_resolve_sysroot_result=$lt_sysroot$func_stripname_result ;; esac } # func_replace_sysroot PATH # If PATH begins with the sysroot, replace it with = and # store the result into func_replace_sysroot_result. func_replace_sysroot () { case $lt_sysroot:$1 in ?*:"$lt_sysroot"*) func_stripname "$lt_sysroot" '' "$1" func_replace_sysroot_result='='$func_stripname_result ;; *) # Including no sysroot. func_replace_sysroot_result=$1 ;; esac } # func_infer_tag arg # Infer tagged configuration to use if any are available and # if one wasn't chosen via the "--tag" command line option. # Only attempt this if the compiler in the base compile # command doesn't match the default compiler. # arg is usually of the form 'gcc ...' func_infer_tag () { $debug_cmd if test -n "$available_tags" && test -z "$tagname"; then CC_quoted= for arg in $CC; do func_append_quoted CC_quoted "$arg" done CC_expanded=`func_echo_all $CC` CC_quoted_expanded=`func_echo_all $CC_quoted` case $@ in # Blanks in the command may have been stripped by the calling shell, # but not from the CC environment variable when configure was run. " $CC "* | "$CC "* | " $CC_expanded "* | "$CC_expanded "* | \ " $CC_quoted"* | "$CC_quoted "* | " $CC_quoted_expanded "* | "$CC_quoted_expanded "*) ;; # Blanks at the start of $base_compile will cause this to fail # if we don't check for them as well. *) for z in $available_tags; do if $GREP "^# ### BEGIN LIBTOOL TAG CONFIG: $z$" < "$progpath" > /dev/null; then # Evaluate the configuration. eval "`$SED -n -e '/^# ### BEGIN LIBTOOL TAG CONFIG: '$z'$/,/^# ### END LIBTOOL TAG CONFIG: '$z'$/p' < $progpath`" CC_quoted= for arg in $CC; do # Double-quote args containing other shell metacharacters. func_append_quoted CC_quoted "$arg" done CC_expanded=`func_echo_all $CC` CC_quoted_expanded=`func_echo_all $CC_quoted` case "$@ " in " $CC "* | "$CC "* | " $CC_expanded "* | "$CC_expanded "* | \ " $CC_quoted"* | "$CC_quoted "* | " $CC_quoted_expanded "* | "$CC_quoted_expanded "*) # The compiler in the base compile command matches # the one in the tagged configuration. # Assume this is the tagged configuration we want. tagname=$z break ;; esac fi done # If $tagname still isn't set, then no tagged configuration # was found and let the user know that the "--tag" command # line option must be used. if test -z "$tagname"; then func_echo "unable to infer tagged configuration" func_fatal_error "specify a tag with '--tag'" # else # func_verbose "using $tagname tagged configuration" fi ;; esac fi } # func_write_libtool_object output_name pic_name nonpic_name # Create a libtool object file (analogous to a ".la" file), # but don't create it if we're doing a dry run. func_write_libtool_object () { write_libobj=$1 if test yes = "$build_libtool_libs"; then write_lobj=\'$2\' else write_lobj=none fi if test yes = "$build_old_libs"; then write_oldobj=\'$3\' else write_oldobj=none fi $opt_dry_run || { cat >${write_libobj}T </dev/null` if test "$?" -eq 0 && test -n "$func_convert_core_file_wine_to_w32_tmp"; then func_convert_core_file_wine_to_w32_result=`$ECHO "$func_convert_core_file_wine_to_w32_tmp" | $SED -e "$sed_naive_backslashify"` else func_convert_core_file_wine_to_w32_result= fi fi } # end: func_convert_core_file_wine_to_w32 # func_convert_core_path_wine_to_w32 ARG # Helper function used by path conversion functions when $build is *nix, and # $host is mingw, cygwin, or some other w32 environment. Relies on a correctly # configured wine environment available, with the winepath program in $build's # $PATH. Assumes ARG has no leading or trailing path separator characters. # # ARG is path to be converted from $build format to win32. # Result is available in $func_convert_core_path_wine_to_w32_result. # Unconvertible file (directory) names in ARG are skipped; if no directory names # are convertible, then the result may be empty. func_convert_core_path_wine_to_w32 () { $debug_cmd # unfortunately, winepath doesn't convert paths, only file names func_convert_core_path_wine_to_w32_result= if test -n "$1"; then oldIFS=$IFS IFS=: for func_convert_core_path_wine_to_w32_f in $1; do IFS=$oldIFS func_convert_core_file_wine_to_w32 "$func_convert_core_path_wine_to_w32_f" if test -n "$func_convert_core_file_wine_to_w32_result"; then if test -z "$func_convert_core_path_wine_to_w32_result"; then func_convert_core_path_wine_to_w32_result=$func_convert_core_file_wine_to_w32_result else func_append func_convert_core_path_wine_to_w32_result ";$func_convert_core_file_wine_to_w32_result" fi fi done IFS=$oldIFS fi } # end: func_convert_core_path_wine_to_w32 # func_cygpath ARGS... # Wrapper around calling the cygpath program via LT_CYGPATH. This is used when # when (1) $build is *nix and Cygwin is hosted via a wine environment; or (2) # $build is MSYS and $host is Cygwin, or (3) $build is Cygwin. In case (1) or # (2), returns the Cygwin file name or path in func_cygpath_result (input # file name or path is assumed to be in w32 format, as previously converted # from $build's *nix or MSYS format). In case (3), returns the w32 file name # or path in func_cygpath_result (input file name or path is assumed to be in # Cygwin format). Returns an empty string on error. # # ARGS are passed to cygpath, with the last one being the file name or path to # be converted. # # Specify the absolute *nix (or w32) name to cygpath in the LT_CYGPATH # environment variable; do not put it in $PATH. func_cygpath () { $debug_cmd if test -n "$LT_CYGPATH" && test -f "$LT_CYGPATH"; then func_cygpath_result=`$LT_CYGPATH "$@" 2>/dev/null` if test "$?" -ne 0; then # on failure, ensure result is empty func_cygpath_result= fi else func_cygpath_result= func_error "LT_CYGPATH is empty or specifies non-existent file: '$LT_CYGPATH'" fi } #end: func_cygpath # func_convert_core_msys_to_w32 ARG # Convert file name or path ARG from MSYS format to w32 format. Return # result in func_convert_core_msys_to_w32_result. func_convert_core_msys_to_w32 () { $debug_cmd # awkward: cmd appends spaces to result func_convert_core_msys_to_w32_result=`( cmd //c echo "$1" ) 2>/dev/null | $SED -e 's/[ ]*$//' -e "$sed_naive_backslashify"` } #end: func_convert_core_msys_to_w32 # func_convert_file_check ARG1 ARG2 # Verify that ARG1 (a file name in $build format) was converted to $host # format in ARG2. Otherwise, emit an error message, but continue (resetting # func_to_host_file_result to ARG1). func_convert_file_check () { $debug_cmd if test -z "$2" && test -n "$1"; then func_error "Could not determine host file name corresponding to" func_error " '$1'" func_error "Continuing, but uninstalled executables may not work." # Fallback: func_to_host_file_result=$1 fi } # end func_convert_file_check # func_convert_path_check FROM_PATHSEP TO_PATHSEP FROM_PATH TO_PATH # Verify that FROM_PATH (a path in $build format) was converted to $host # format in TO_PATH. Otherwise, emit an error message, but continue, resetting # func_to_host_file_result to a simplistic fallback value (see below). func_convert_path_check () { $debug_cmd if test -z "$4" && test -n "$3"; then func_error "Could not determine the host path corresponding to" func_error " '$3'" func_error "Continuing, but uninstalled executables may not work." # Fallback. This is a deliberately simplistic "conversion" and # should not be "improved". See libtool.info. if test "x$1" != "x$2"; then lt_replace_pathsep_chars="s|$1|$2|g" func_to_host_path_result=`echo "$3" | $SED -e "$lt_replace_pathsep_chars"` else func_to_host_path_result=$3 fi fi } # end func_convert_path_check # func_convert_path_front_back_pathsep FRONTPAT BACKPAT REPL ORIG # Modifies func_to_host_path_result by prepending REPL if ORIG matches FRONTPAT # and appending REPL if ORIG matches BACKPAT. func_convert_path_front_back_pathsep () { $debug_cmd case $4 in $1 ) func_to_host_path_result=$3$func_to_host_path_result ;; esac case $4 in $2 ) func_append func_to_host_path_result "$3" ;; esac } # end func_convert_path_front_back_pathsep ################################################## # $build to $host FILE NAME CONVERSION FUNCTIONS # ################################################## # invoked via '$to_host_file_cmd ARG' # # In each case, ARG is the path to be converted from $build to $host format. # Result will be available in $func_to_host_file_result. # func_to_host_file ARG # Converts the file name ARG from $build format to $host format. Return result # in func_to_host_file_result. func_to_host_file () { $debug_cmd $to_host_file_cmd "$1" } # end func_to_host_file # func_to_tool_file ARG LAZY # converts the file name ARG from $build format to toolchain format. Return # result in func_to_tool_file_result. If the conversion in use is listed # in (the comma separated) LAZY, no conversion takes place. func_to_tool_file () { $debug_cmd case ,$2, in *,"$to_tool_file_cmd",*) func_to_tool_file_result=$1 ;; *) $to_tool_file_cmd "$1" func_to_tool_file_result=$func_to_host_file_result ;; esac } # end func_to_tool_file # func_convert_file_noop ARG # Copy ARG to func_to_host_file_result. func_convert_file_noop () { func_to_host_file_result=$1 } # end func_convert_file_noop # func_convert_file_msys_to_w32 ARG # Convert file name ARG from (mingw) MSYS to (mingw) w32 format; automatic # conversion to w32 is not available inside the cwrapper. Returns result in # func_to_host_file_result. func_convert_file_msys_to_w32 () { $debug_cmd func_to_host_file_result=$1 if test -n "$1"; then func_convert_core_msys_to_w32 "$1" func_to_host_file_result=$func_convert_core_msys_to_w32_result fi func_convert_file_check "$1" "$func_to_host_file_result" } # end func_convert_file_msys_to_w32 # func_convert_file_cygwin_to_w32 ARG # Convert file name ARG from Cygwin to w32 format. Returns result in # func_to_host_file_result. func_convert_file_cygwin_to_w32 () { $debug_cmd func_to_host_file_result=$1 if test -n "$1"; then # because $build is cygwin, we call "the" cygpath in $PATH; no need to use # LT_CYGPATH in this case. func_to_host_file_result=`cygpath -m "$1"` fi func_convert_file_check "$1" "$func_to_host_file_result" } # end func_convert_file_cygwin_to_w32 # func_convert_file_nix_to_w32 ARG # Convert file name ARG from *nix to w32 format. Requires a wine environment # and a working winepath. Returns result in func_to_host_file_result. func_convert_file_nix_to_w32 () { $debug_cmd func_to_host_file_result=$1 if test -n "$1"; then func_convert_core_file_wine_to_w32 "$1" func_to_host_file_result=$func_convert_core_file_wine_to_w32_result fi func_convert_file_check "$1" "$func_to_host_file_result" } # end func_convert_file_nix_to_w32 # func_convert_file_msys_to_cygwin ARG # Convert file name ARG from MSYS to Cygwin format. Requires LT_CYGPATH set. # Returns result in func_to_host_file_result. func_convert_file_msys_to_cygwin () { $debug_cmd func_to_host_file_result=$1 if test -n "$1"; then func_convert_core_msys_to_w32 "$1" func_cygpath -u "$func_convert_core_msys_to_w32_result" func_to_host_file_result=$func_cygpath_result fi func_convert_file_check "$1" "$func_to_host_file_result" } # end func_convert_file_msys_to_cygwin # func_convert_file_nix_to_cygwin ARG # Convert file name ARG from *nix to Cygwin format. Requires Cygwin installed # in a wine environment, working winepath, and LT_CYGPATH set. Returns result # in func_to_host_file_result. func_convert_file_nix_to_cygwin () { $debug_cmd func_to_host_file_result=$1 if test -n "$1"; then # convert from *nix to w32, then use cygpath to convert from w32 to cygwin. func_convert_core_file_wine_to_w32 "$1" func_cygpath -u "$func_convert_core_file_wine_to_w32_result" func_to_host_file_result=$func_cygpath_result fi func_convert_file_check "$1" "$func_to_host_file_result" } # end func_convert_file_nix_to_cygwin ############################################# # $build to $host PATH CONVERSION FUNCTIONS # ############################################# # invoked via '$to_host_path_cmd ARG' # # In each case, ARG is the path to be converted from $build to $host format. # The result will be available in $func_to_host_path_result. # # Path separators are also converted from $build format to $host format. If # ARG begins or ends with a path separator character, it is preserved (but # converted to $host format) on output. # # All path conversion functions are named using the following convention: # file name conversion function : func_convert_file_X_to_Y () # path conversion function : func_convert_path_X_to_Y () # where, for any given $build/$host combination the 'X_to_Y' value is the # same. If conversion functions are added for new $build/$host combinations, # the two new functions must follow this pattern, or func_init_to_host_path_cmd # will break. # func_init_to_host_path_cmd # Ensures that function "pointer" variable $to_host_path_cmd is set to the # appropriate value, based on the value of $to_host_file_cmd. to_host_path_cmd= func_init_to_host_path_cmd () { $debug_cmd if test -z "$to_host_path_cmd"; then func_stripname 'func_convert_file_' '' "$to_host_file_cmd" to_host_path_cmd=func_convert_path_$func_stripname_result fi } # func_to_host_path ARG # Converts the path ARG from $build format to $host format. Return result # in func_to_host_path_result. func_to_host_path () { $debug_cmd func_init_to_host_path_cmd $to_host_path_cmd "$1" } # end func_to_host_path # func_convert_path_noop ARG # Copy ARG to func_to_host_path_result. func_convert_path_noop () { func_to_host_path_result=$1 } # end func_convert_path_noop # func_convert_path_msys_to_w32 ARG # Convert path ARG from (mingw) MSYS to (mingw) w32 format; automatic # conversion to w32 is not available inside the cwrapper. Returns result in # func_to_host_path_result. func_convert_path_msys_to_w32 () { $debug_cmd func_to_host_path_result=$1 if test -n "$1"; then # Remove leading and trailing path separator characters from ARG. MSYS # behavior is inconsistent here; cygpath turns them into '.;' and ';.'; # and winepath ignores them completely. func_stripname : : "$1" func_to_host_path_tmp1=$func_stripname_result func_convert_core_msys_to_w32 "$func_to_host_path_tmp1" func_to_host_path_result=$func_convert_core_msys_to_w32_result func_convert_path_check : ";" \ "$func_to_host_path_tmp1" "$func_to_host_path_result" func_convert_path_front_back_pathsep ":*" "*:" ";" "$1" fi } # end func_convert_path_msys_to_w32 # func_convert_path_cygwin_to_w32 ARG # Convert path ARG from Cygwin to w32 format. Returns result in # func_to_host_file_result. func_convert_path_cygwin_to_w32 () { $debug_cmd func_to_host_path_result=$1 if test -n "$1"; then # See func_convert_path_msys_to_w32: func_stripname : : "$1" func_to_host_path_tmp1=$func_stripname_result func_to_host_path_result=`cygpath -m -p "$func_to_host_path_tmp1"` func_convert_path_check : ";" \ "$func_to_host_path_tmp1" "$func_to_host_path_result" func_convert_path_front_back_pathsep ":*" "*:" ";" "$1" fi } # end func_convert_path_cygwin_to_w32 # func_convert_path_nix_to_w32 ARG # Convert path ARG from *nix to w32 format. Requires a wine environment and # a working winepath. Returns result in func_to_host_file_result. func_convert_path_nix_to_w32 () { $debug_cmd func_to_host_path_result=$1 if test -n "$1"; then # See func_convert_path_msys_to_w32: func_stripname : : "$1" func_to_host_path_tmp1=$func_stripname_result func_convert_core_path_wine_to_w32 "$func_to_host_path_tmp1" func_to_host_path_result=$func_convert_core_path_wine_to_w32_result func_convert_path_check : ";" \ "$func_to_host_path_tmp1" "$func_to_host_path_result" func_convert_path_front_back_pathsep ":*" "*:" ";" "$1" fi } # end func_convert_path_nix_to_w32 # func_convert_path_msys_to_cygwin ARG # Convert path ARG from MSYS to Cygwin format. Requires LT_CYGPATH set. # Returns result in func_to_host_file_result. func_convert_path_msys_to_cygwin () { $debug_cmd func_to_host_path_result=$1 if test -n "$1"; then # See func_convert_path_msys_to_w32: func_stripname : : "$1" func_to_host_path_tmp1=$func_stripname_result func_convert_core_msys_to_w32 "$func_to_host_path_tmp1" func_cygpath -u -p "$func_convert_core_msys_to_w32_result" func_to_host_path_result=$func_cygpath_result func_convert_path_check : : \ "$func_to_host_path_tmp1" "$func_to_host_path_result" func_convert_path_front_back_pathsep ":*" "*:" : "$1" fi } # end func_convert_path_msys_to_cygwin # func_convert_path_nix_to_cygwin ARG # Convert path ARG from *nix to Cygwin format. Requires Cygwin installed in a # a wine environment, working winepath, and LT_CYGPATH set. Returns result in # func_to_host_file_result. func_convert_path_nix_to_cygwin () { $debug_cmd func_to_host_path_result=$1 if test -n "$1"; then # Remove leading and trailing path separator characters from # ARG. msys behavior is inconsistent here, cygpath turns them # into '.;' and ';.', and winepath ignores them completely. func_stripname : : "$1" func_to_host_path_tmp1=$func_stripname_result func_convert_core_path_wine_to_w32 "$func_to_host_path_tmp1" func_cygpath -u -p "$func_convert_core_path_wine_to_w32_result" func_to_host_path_result=$func_cygpath_result func_convert_path_check : : \ "$func_to_host_path_tmp1" "$func_to_host_path_result" func_convert_path_front_back_pathsep ":*" "*:" : "$1" fi } # end func_convert_path_nix_to_cygwin # func_dll_def_p FILE # True iff FILE is a Windows DLL '.def' file. # Keep in sync with _LT_DLL_DEF_P in libtool.m4 func_dll_def_p () { $debug_cmd func_dll_def_p_tmp=`$SED -n \ -e 's/^[ ]*//' \ -e '/^\(;.*\)*$/d' \ -e 's/^\(EXPORTS\|LIBRARY\)\([ ].*\)*$/DEF/p' \ -e q \ "$1"` test DEF = "$func_dll_def_p_tmp" } # func_mode_compile arg... func_mode_compile () { $debug_cmd # Get the compilation command and the source file. base_compile= srcfile=$nonopt # always keep a non-empty value in "srcfile" suppress_opt=yes suppress_output= arg_mode=normal libobj= later= pie_flag= for arg do case $arg_mode in arg ) # do not "continue". Instead, add this to base_compile lastarg=$arg arg_mode=normal ;; target ) libobj=$arg arg_mode=normal continue ;; normal ) # Accept any command-line options. case $arg in -o) test -n "$libobj" && \ func_fatal_error "you cannot specify '-o' more than once" arg_mode=target continue ;; -pie | -fpie | -fPIE) func_append pie_flag " $arg" continue ;; -shared | -static | -prefer-pic | -prefer-non-pic) func_append later " $arg" continue ;; -no-suppress) suppress_opt=no continue ;; -Xcompiler) arg_mode=arg # the next one goes into the "base_compile" arg list continue # The current "srcfile" will either be retained or ;; # replaced later. I would guess that would be a bug. -Wc,*) func_stripname '-Wc,' '' "$arg" args=$func_stripname_result lastarg= save_ifs=$IFS; IFS=, for arg in $args; do IFS=$save_ifs func_append_quoted lastarg "$arg" done IFS=$save_ifs func_stripname ' ' '' "$lastarg" lastarg=$func_stripname_result # Add the arguments to base_compile. func_append base_compile " $lastarg" continue ;; *) # Accept the current argument as the source file. # The previous "srcfile" becomes the current argument. # lastarg=$srcfile srcfile=$arg ;; esac # case $arg ;; esac # case $arg_mode # Aesthetically quote the previous argument. func_append_quoted base_compile "$lastarg" done # for arg case $arg_mode in arg) func_fatal_error "you must specify an argument for -Xcompile" ;; target) func_fatal_error "you must specify a target with '-o'" ;; *) # Get the name of the library object. test -z "$libobj" && { func_basename "$srcfile" libobj=$func_basename_result } ;; esac # Recognize several different file suffixes. # If the user specifies -o file.o, it is replaced with file.lo case $libobj in *.[cCFSifmso] | \ *.ada | *.adb | *.ads | *.asm | \ *.c++ | *.cc | *.ii | *.class | *.cpp | *.cxx | \ *.[fF][09]? | *.for | *.java | *.go | *.obj | *.sx | *.cu | *.cup) func_xform "$libobj" libobj=$func_xform_result ;; esac case $libobj in *.lo) func_lo2o "$libobj"; obj=$func_lo2o_result ;; *) func_fatal_error "cannot determine name of library object from '$libobj'" ;; esac func_infer_tag $base_compile for arg in $later; do case $arg in -shared) test yes = "$build_libtool_libs" \ || func_fatal_configuration "cannot build a shared library" build_old_libs=no continue ;; -static) build_libtool_libs=no build_old_libs=yes continue ;; -prefer-pic) pic_mode=yes continue ;; -prefer-non-pic) pic_mode=no continue ;; esac done func_quote_for_eval "$libobj" test "X$libobj" != "X$func_quote_for_eval_result" \ && $ECHO "X$libobj" | $GREP '[]~#^*{};<>?"'"'"' &()|`$[]' \ && func_warning "libobj name '$libobj' may not contain shell special characters." func_dirname_and_basename "$obj" "/" "" objname=$func_basename_result xdir=$func_dirname_result lobj=$xdir$objdir/$objname test -z "$base_compile" && \ func_fatal_help "you must specify a compilation command" # Delete any leftover library objects. if test yes = "$build_old_libs"; then removelist="$obj $lobj $libobj ${libobj}T" else removelist="$lobj $libobj ${libobj}T" fi # On Cygwin there's no "real" PIC flag so we must build both object types case $host_os in cygwin* | mingw* | pw32* | os2* | cegcc*) pic_mode=default ;; esac if test no = "$pic_mode" && test pass_all != "$deplibs_check_method"; then # non-PIC code in shared libraries is not supported pic_mode=default fi # Calculate the filename of the output object if compiler does # not support -o with -c if test no = "$compiler_c_o"; then output_obj=`$ECHO "$srcfile" | $SED 's%^.*/%%; s%\.[^.]*$%%'`.$objext lockfile=$output_obj.lock else output_obj= need_locks=no lockfile= fi # Lock this critical section if it is needed # We use this script file to make the link, it avoids creating a new file if test yes = "$need_locks"; then until $opt_dry_run || ln "$progpath" "$lockfile" 2>/dev/null; do func_echo "Waiting for $lockfile to be removed" sleep 2 done elif test warn = "$need_locks"; then if test -f "$lockfile"; then $ECHO "\ *** ERROR, $lockfile exists and contains: `cat $lockfile 2>/dev/null` This indicates that another process is trying to use the same temporary object file, and libtool could not work around it because your compiler does not support '-c' and '-o' together. If you repeat this compilation, it may succeed, by chance, but you had better avoid parallel builds (make -j) in this platform, or get a better compiler." $opt_dry_run || $RM $removelist exit $EXIT_FAILURE fi func_append removelist " $output_obj" $ECHO "$srcfile" > "$lockfile" fi $opt_dry_run || $RM $removelist func_append removelist " $lockfile" trap '$opt_dry_run || $RM $removelist; exit $EXIT_FAILURE' 1 2 15 func_to_tool_file "$srcfile" func_convert_file_msys_to_w32 srcfile=$func_to_tool_file_result func_quote_for_eval "$srcfile" qsrcfile=$func_quote_for_eval_result # Only build a PIC object if we are building libtool libraries. if test yes = "$build_libtool_libs"; then # Without this assignment, base_compile gets emptied. fbsd_hideous_sh_bug=$base_compile if test no != "$pic_mode"; then command="$base_compile $qsrcfile $pic_flag" else # Don't build PIC code command="$base_compile $qsrcfile" fi func_mkdir_p "$xdir$objdir" if test -z "$output_obj"; then # Place PIC objects in $objdir func_append command " -o $lobj" fi func_show_eval_locale "$command" \ 'test -n "$output_obj" && $RM $removelist; exit $EXIT_FAILURE' if test warn = "$need_locks" && test "X`cat $lockfile 2>/dev/null`" != "X$srcfile"; then $ECHO "\ *** ERROR, $lockfile contains: `cat $lockfile 2>/dev/null` but it should contain: $srcfile This indicates that another process is trying to use the same temporary object file, and libtool could not work around it because your compiler does not support '-c' and '-o' together. If you repeat this compilation, it may succeed, by chance, but you had better avoid parallel builds (make -j) in this platform, or get a better compiler." $opt_dry_run || $RM $removelist exit $EXIT_FAILURE fi # Just move the object if needed, then go on to compile the next one if test -n "$output_obj" && test "X$output_obj" != "X$lobj"; then func_show_eval '$MV "$output_obj" "$lobj"' \ 'error=$?; $opt_dry_run || $RM $removelist; exit $error' fi # Allow error messages only from the first compilation. if test yes = "$suppress_opt"; then suppress_output=' >/dev/null 2>&1' fi fi # Only build a position-dependent object if we build old libraries. if test yes = "$build_old_libs"; then if test yes != "$pic_mode"; then # Don't build PIC code command="$base_compile $qsrcfile$pie_flag" else command="$base_compile $qsrcfile $pic_flag" fi if test yes = "$compiler_c_o"; then func_append command " -o $obj" fi # Suppress compiler output if we already did a PIC compilation. func_append command "$suppress_output" func_show_eval_locale "$command" \ '$opt_dry_run || $RM $removelist; exit $EXIT_FAILURE' if test warn = "$need_locks" && test "X`cat $lockfile 2>/dev/null`" != "X$srcfile"; then $ECHO "\ *** ERROR, $lockfile contains: `cat $lockfile 2>/dev/null` but it should contain: $srcfile This indicates that another process is trying to use the same temporary object file, and libtool could not work around it because your compiler does not support '-c' and '-o' together. If you repeat this compilation, it may succeed, by chance, but you had better avoid parallel builds (make -j) in this platform, or get a better compiler." $opt_dry_run || $RM $removelist exit $EXIT_FAILURE fi # Just move the object if needed if test -n "$output_obj" && test "X$output_obj" != "X$obj"; then func_show_eval '$MV "$output_obj" "$obj"' \ 'error=$?; $opt_dry_run || $RM $removelist; exit $error' fi fi $opt_dry_run || { func_write_libtool_object "$libobj" "$objdir/$objname" "$objname" # Unlock the critical section if it was locked if test no != "$need_locks"; then removelist=$lockfile $RM "$lockfile" fi } exit $EXIT_SUCCESS } $opt_help || { test compile = "$opt_mode" && func_mode_compile ${1+"$@"} } func_mode_help () { # We need to display help for each of the modes. case $opt_mode in "") # Generic help is extracted from the usage comments # at the start of this file. func_help ;; clean) $ECHO \ "Usage: $progname [OPTION]... --mode=clean RM [RM-OPTION]... FILE... Remove files from the build directory. RM is the name of the program to use to delete files associated with each FILE (typically '/bin/rm'). RM-OPTIONS are options (such as '-f') to be passed to RM. If FILE is a libtool library, object or program, all the files associated with it are deleted. Otherwise, only FILE itself is deleted using RM." ;; compile) $ECHO \ "Usage: $progname [OPTION]... --mode=compile COMPILE-COMMAND... SOURCEFILE Compile a source file into a libtool library object. This mode accepts the following additional options: -o OUTPUT-FILE set the output file name to OUTPUT-FILE -no-suppress do not suppress compiler output for multiple passes -prefer-pic try to build PIC objects only -prefer-non-pic try to build non-PIC objects only -shared do not build a '.o' file suitable for static linking -static only build a '.o' file suitable for static linking -Wc,FLAG pass FLAG directly to the compiler COMPILE-COMMAND is a command to be used in creating a 'standard' object file from the given SOURCEFILE. The output file name is determined by removing the directory component from SOURCEFILE, then substituting the C source code suffix '.c' with the library object suffix, '.lo'." ;; execute) $ECHO \ "Usage: $progname [OPTION]... --mode=execute COMMAND [ARGS]... Automatically set library path, then run a program. This mode accepts the following additional options: -dlopen FILE add the directory containing FILE to the library path This mode sets the library path environment variable according to '-dlopen' flags. If any of the ARGS are libtool executable wrappers, then they are translated into their corresponding uninstalled binary, and any of their required library directories are added to the library path. Then, COMMAND is executed, with ARGS as arguments." ;; finish) $ECHO \ "Usage: $progname [OPTION]... --mode=finish [LIBDIR]... Complete the installation of libtool libraries. Each LIBDIR is a directory that contains libtool libraries. The commands that this mode executes may require superuser privileges. Use the '--dry-run' option if you just want to see what would be executed." ;; install) $ECHO \ "Usage: $progname [OPTION]... --mode=install INSTALL-COMMAND... Install executables or libraries. INSTALL-COMMAND is the installation command. The first component should be either the 'install' or 'cp' program. The following components of INSTALL-COMMAND are treated specially: -inst-prefix-dir PREFIX-DIR Use PREFIX-DIR as a staging area for installation The rest of the components are interpreted as arguments to that command (only BSD-compatible install options are recognized)." ;; link) $ECHO \ "Usage: $progname [OPTION]... --mode=link LINK-COMMAND... Link object files or libraries together to form another library, or to create an executable program. LINK-COMMAND is a command using the C compiler that you would use to create a program from several object files. The following components of LINK-COMMAND are treated specially: -all-static do not do any dynamic linking at all -avoid-version do not add a version suffix if possible -bindir BINDIR specify path to binaries directory (for systems where libraries must be found in the PATH setting at runtime) -dlopen FILE '-dlpreopen' FILE if it cannot be dlopened at runtime -dlpreopen FILE link in FILE and add its symbols to lt_preloaded_symbols -export-dynamic allow symbols from OUTPUT-FILE to be resolved with dlsym(3) -export-symbols SYMFILE try to export only the symbols listed in SYMFILE -export-symbols-regex REGEX try to export only the symbols matching REGEX -LLIBDIR search LIBDIR for required installed libraries -lNAME OUTPUT-FILE requires the installed library libNAME -module build a library that can dlopened -no-fast-install disable the fast-install mode -no-install link a not-installable executable -no-undefined declare that a library does not refer to external symbols -o OUTPUT-FILE create OUTPUT-FILE from the specified objects -objectlist FILE use a list of object files found in FILE to specify objects -os2dllname NAME force a short DLL name on OS/2 (no effect on other OSes) -precious-files-regex REGEX don't remove output files matching REGEX -release RELEASE specify package release information -rpath LIBDIR the created library will eventually be installed in LIBDIR -R[ ]LIBDIR add LIBDIR to the runtime path of programs and libraries -shared only do dynamic linking of libtool libraries -shrext SUFFIX override the standard shared library file extension -static do not do any dynamic linking of uninstalled libtool libraries -static-libtool-libs do not do any dynamic linking of libtool libraries -version-info CURRENT[:REVISION[:AGE]] specify library version info [each variable defaults to 0] -weak LIBNAME declare that the target provides the LIBNAME interface -Wc,FLAG -Xcompiler FLAG pass linker-specific FLAG directly to the compiler -Wl,FLAG -Xlinker FLAG pass linker-specific FLAG directly to the linker -XCClinker FLAG pass link-specific FLAG to the compiler driver (CC) All other options (arguments beginning with '-') are ignored. Every other argument is treated as a filename. Files ending in '.la' are treated as uninstalled libtool libraries, other files are standard or library object files. If the OUTPUT-FILE ends in '.la', then a libtool library is created, only library objects ('.lo' files) may be specified, and '-rpath' is required, except when creating a convenience library. If OUTPUT-FILE ends in '.a' or '.lib', then a standard library is created using 'ar' and 'ranlib', or on Windows using 'lib'. If OUTPUT-FILE ends in '.lo' or '.$objext', then a reloadable object file is created, otherwise an executable program is created." ;; uninstall) $ECHO \ "Usage: $progname [OPTION]... --mode=uninstall RM [RM-OPTION]... FILE... Remove libraries from an installation directory. RM is the name of the program to use to delete files associated with each FILE (typically '/bin/rm'). RM-OPTIONS are options (such as '-f') to be passed to RM. If FILE is a libtool library, all the files associated with it are deleted. Otherwise, only FILE itself is deleted using RM." ;; *) func_fatal_help "invalid operation mode '$opt_mode'" ;; esac echo $ECHO "Try '$progname --help' for more information about other modes." } # Now that we've collected a possible --mode arg, show help if necessary if $opt_help; then if test : = "$opt_help"; then func_mode_help else { func_help noexit for opt_mode in compile link execute install finish uninstall clean; do func_mode_help done } | $SED -n '1p; 2,$s/^Usage:/ or: /p' { func_help noexit for opt_mode in compile link execute install finish uninstall clean; do echo func_mode_help done } | $SED '1d /^When reporting/,/^Report/{ H d } $x /information about other modes/d /more detailed .*MODE/d s/^Usage:.*--mode=\([^ ]*\) .*/Description of \1 mode:/' fi exit $? fi # func_mode_execute arg... func_mode_execute () { $debug_cmd # The first argument is the command name. cmd=$nonopt test -z "$cmd" && \ func_fatal_help "you must specify a COMMAND" # Handle -dlopen flags immediately. for file in $opt_dlopen; do test -f "$file" \ || func_fatal_help "'$file' is not a file" dir= case $file in *.la) func_resolve_sysroot "$file" file=$func_resolve_sysroot_result # Check to see that this really is a libtool archive. func_lalib_unsafe_p "$file" \ || func_fatal_help "'$lib' is not a valid libtool archive" # Read the libtool library. dlname= library_names= func_source "$file" # Skip this library if it cannot be dlopened. if test -z "$dlname"; then # Warn if it was a shared library. test -n "$library_names" && \ func_warning "'$file' was not linked with '-export-dynamic'" continue fi func_dirname "$file" "" "." dir=$func_dirname_result if test -f "$dir/$objdir/$dlname"; then func_append dir "/$objdir" else if test ! -f "$dir/$dlname"; then func_fatal_error "cannot find '$dlname' in '$dir' or '$dir/$objdir'" fi fi ;; *.lo) # Just add the directory containing the .lo file. func_dirname "$file" "" "." dir=$func_dirname_result ;; *) func_warning "'-dlopen' is ignored for non-libtool libraries and objects" continue ;; esac # Get the absolute pathname. absdir=`cd "$dir" && pwd` test -n "$absdir" && dir=$absdir # Now add the directory to shlibpath_var. if eval "test -z \"\$$shlibpath_var\""; then eval "$shlibpath_var=\"\$dir\"" else eval "$shlibpath_var=\"\$dir:\$$shlibpath_var\"" fi done # This variable tells wrapper scripts just to set shlibpath_var # rather than running their programs. libtool_execute_magic=$magic # Check if any of the arguments is a wrapper script. args= for file do case $file in -* | *.la | *.lo ) ;; *) # Do a test to see if this is really a libtool program. if func_ltwrapper_script_p "$file"; then func_source "$file" # Transform arg to wrapped name. file=$progdir/$program elif func_ltwrapper_executable_p "$file"; then func_ltwrapper_scriptname "$file" func_source "$func_ltwrapper_scriptname_result" # Transform arg to wrapped name. file=$progdir/$program fi ;; esac # Quote arguments (to preserve shell metacharacters). func_append_quoted args "$file" done if $opt_dry_run; then # Display what would be done. if test -n "$shlibpath_var"; then eval "\$ECHO \"\$shlibpath_var=\$$shlibpath_var\"" echo "export $shlibpath_var" fi $ECHO "$cmd$args" exit $EXIT_SUCCESS else if test -n "$shlibpath_var"; then # Export the shlibpath_var. eval "export $shlibpath_var" fi # Restore saved environment variables for lt_var in LANG LANGUAGE LC_ALL LC_CTYPE LC_COLLATE LC_MESSAGES do eval "if test \"\${save_$lt_var+set}\" = set; then $lt_var=\$save_$lt_var; export $lt_var else $lt_unset $lt_var fi" done # Now prepare to actually exec the command. exec_cmd=\$cmd$args fi } test execute = "$opt_mode" && func_mode_execute ${1+"$@"} # func_mode_finish arg... func_mode_finish () { $debug_cmd libs= libdirs= admincmds= for opt in "$nonopt" ${1+"$@"} do if test -d "$opt"; then func_append libdirs " $opt" elif test -f "$opt"; then if func_lalib_unsafe_p "$opt"; then func_append libs " $opt" else func_warning "'$opt' is not a valid libtool archive" fi else func_fatal_error "invalid argument '$opt'" fi done if test -n "$libs"; then if test -n "$lt_sysroot"; then sysroot_regex=`$ECHO "$lt_sysroot" | $SED "$sed_make_literal_regex"` sysroot_cmd="s/\([ ']\)$sysroot_regex/\1/g;" else sysroot_cmd= fi # Remove sysroot references if $opt_dry_run; then for lib in $libs; do echo "removing references to $lt_sysroot and '=' prefixes from $lib" done else tmpdir=`func_mktempdir` for lib in $libs; do $SED -e "$sysroot_cmd s/\([ ']-[LR]\)=/\1/g; s/\([ ']\)=/\1/g" $lib \ > $tmpdir/tmp-la mv -f $tmpdir/tmp-la $lib done ${RM}r "$tmpdir" fi fi if test -n "$finish_cmds$finish_eval" && test -n "$libdirs"; then for libdir in $libdirs; do if test -n "$finish_cmds"; then # Do each command in the finish commands. func_execute_cmds "$finish_cmds" 'admincmds="$admincmds '"$cmd"'"' fi if test -n "$finish_eval"; then # Do the single finish_eval. eval cmds=\"$finish_eval\" $opt_dry_run || eval "$cmds" || func_append admincmds " $cmds" fi done fi # Exit here if they wanted silent mode. $opt_quiet && exit $EXIT_SUCCESS if test -n "$finish_cmds$finish_eval" && test -n "$libdirs"; then echo "----------------------------------------------------------------------" echo "Libraries have been installed in:" for libdir in $libdirs; do $ECHO " $libdir" done echo echo "If you ever happen to want to link against installed libraries" echo "in a given directory, LIBDIR, you must either use libtool, and" echo "specify the full pathname of the library, or use the '-LLIBDIR'" echo "flag during linking and do at least one of the following:" if test -n "$shlibpath_var"; then echo " - add LIBDIR to the '$shlibpath_var' environment variable" echo " during execution" fi if test -n "$runpath_var"; then echo " - add LIBDIR to the '$runpath_var' environment variable" echo " during linking" fi if test -n "$hardcode_libdir_flag_spec"; then libdir=LIBDIR eval flag=\"$hardcode_libdir_flag_spec\" $ECHO " - use the '$flag' linker flag" fi if test -n "$admincmds"; then $ECHO " - have your system administrator run these commands:$admincmds" fi if test -f /etc/ld.so.conf; then echo " - have your system administrator add LIBDIR to '/etc/ld.so.conf'" fi echo echo "See any operating system documentation about shared libraries for" case $host in solaris2.[6789]|solaris2.1[0-9]) echo "more information, such as the ld(1), crle(1) and ld.so(8) manual" echo "pages." ;; *) echo "more information, such as the ld(1) and ld.so(8) manual pages." ;; esac echo "----------------------------------------------------------------------" fi exit $EXIT_SUCCESS } test finish = "$opt_mode" && func_mode_finish ${1+"$@"} # func_mode_install arg... func_mode_install () { $debug_cmd # There may be an optional sh(1) argument at the beginning of # install_prog (especially on Windows NT). if test "$SHELL" = "$nonopt" || test /bin/sh = "$nonopt" || # Allow the use of GNU shtool's install command. case $nonopt in *shtool*) :;; *) false;; esac then # Aesthetically quote it. func_quote_for_eval "$nonopt" install_prog="$func_quote_for_eval_result " arg=$1 shift else install_prog= arg=$nonopt fi # The real first argument should be the name of the installation program. # Aesthetically quote it. func_quote_for_eval "$arg" func_append install_prog "$func_quote_for_eval_result" install_shared_prog=$install_prog case " $install_prog " in *[\\\ /]cp\ *) install_cp=: ;; *) install_cp=false ;; esac # We need to accept at least all the BSD install flags. dest= files= opts= prev= install_type= isdir=false stripme= no_mode=: for arg do arg2= if test -n "$dest"; then func_append files " $dest" dest=$arg continue fi case $arg in -d) isdir=: ;; -f) if $install_cp; then :; else prev=$arg fi ;; -g | -m | -o) prev=$arg ;; -s) stripme=" -s" continue ;; -*) ;; *) # If the previous option needed an argument, then skip it. if test -n "$prev"; then if test X-m = "X$prev" && test -n "$install_override_mode"; then arg2=$install_override_mode no_mode=false fi prev= else dest=$arg continue fi ;; esac # Aesthetically quote the argument. func_quote_for_eval "$arg" func_append install_prog " $func_quote_for_eval_result" if test -n "$arg2"; then func_quote_for_eval "$arg2" fi func_append install_shared_prog " $func_quote_for_eval_result" done test -z "$install_prog" && \ func_fatal_help "you must specify an install program" test -n "$prev" && \ func_fatal_help "the '$prev' option requires an argument" if test -n "$install_override_mode" && $no_mode; then if $install_cp; then :; else func_quote_for_eval "$install_override_mode" func_append install_shared_prog " -m $func_quote_for_eval_result" fi fi if test -z "$files"; then if test -z "$dest"; then func_fatal_help "no file or destination specified" else func_fatal_help "you must specify a destination" fi fi # Strip any trailing slash from the destination. func_stripname '' '/' "$dest" dest=$func_stripname_result # Check to see that the destination is a directory. test -d "$dest" && isdir=: if $isdir; then destdir=$dest destname= else func_dirname_and_basename "$dest" "" "." destdir=$func_dirname_result destname=$func_basename_result # Not a directory, so check to see that there is only one file specified. set dummy $files; shift test "$#" -gt 1 && \ func_fatal_help "'$dest' is not a directory" fi case $destdir in [\\/]* | [A-Za-z]:[\\/]*) ;; *) for file in $files; do case $file in *.lo) ;; *) func_fatal_help "'$destdir' must be an absolute directory name" ;; esac done ;; esac # This variable tells wrapper scripts just to set variables rather # than running their programs. libtool_install_magic=$magic staticlibs= future_libdirs= current_libdirs= for file in $files; do # Do each installation. case $file in *.$libext) # Do the static libraries later. func_append staticlibs " $file" ;; *.la) func_resolve_sysroot "$file" file=$func_resolve_sysroot_result # Check to see that this really is a libtool archive. func_lalib_unsafe_p "$file" \ || func_fatal_help "'$file' is not a valid libtool archive" library_names= old_library= relink_command= func_source "$file" # Add the libdir to current_libdirs if it is the destination. if test "X$destdir" = "X$libdir"; then case "$current_libdirs " in *" $libdir "*) ;; *) func_append current_libdirs " $libdir" ;; esac else # Note the libdir as a future libdir. case "$future_libdirs " in *" $libdir "*) ;; *) func_append future_libdirs " $libdir" ;; esac fi func_dirname "$file" "/" "" dir=$func_dirname_result func_append dir "$objdir" if test -n "$relink_command"; then # Determine the prefix the user has applied to our future dir. inst_prefix_dir=`$ECHO "$destdir" | $SED -e "s%$libdir\$%%"` # Don't allow the user to place us outside of our expected # location b/c this prevents finding dependent libraries that # are installed to the same prefix. # At present, this check doesn't affect windows .dll's that # are installed into $libdir/../bin (currently, that works fine) # but it's something to keep an eye on. test "$inst_prefix_dir" = "$destdir" && \ func_fatal_error "error: cannot install '$file' to a directory not ending in $libdir" if test -n "$inst_prefix_dir"; then # Stick the inst_prefix_dir data into the link command. relink_command=`$ECHO "$relink_command" | $SED "s%@inst_prefix_dir@%-inst-prefix-dir $inst_prefix_dir%"` else relink_command=`$ECHO "$relink_command" | $SED "s%@inst_prefix_dir@%%"` fi func_warning "relinking '$file'" func_show_eval "$relink_command" \ 'func_fatal_error "error: relink '\''$file'\'' with the above command before installing it"' fi # See the names of the shared library. set dummy $library_names; shift if test -n "$1"; then realname=$1 shift srcname=$realname test -n "$relink_command" && srcname=${realname}T # Install the shared library and build the symlinks. func_show_eval "$install_shared_prog $dir/$srcname $destdir/$realname" \ 'exit $?' tstripme=$stripme case $host_os in cygwin* | mingw* | pw32* | cegcc*) case $realname in *.dll.a) tstripme= ;; esac ;; os2*) case $realname in *_dll.a) tstripme= ;; esac ;; esac if test -n "$tstripme" && test -n "$striplib"; then func_show_eval "$striplib $destdir/$realname" 'exit $?' fi if test "$#" -gt 0; then # Delete the old symlinks, and create new ones. # Try 'ln -sf' first, because the 'ln' binary might depend on # the symlink we replace! Solaris /bin/ln does not understand -f, # so we also need to try rm && ln -s. for linkname do test "$linkname" != "$realname" \ && func_show_eval "(cd $destdir && { $LN_S -f $realname $linkname || { $RM $linkname && $LN_S $realname $linkname; }; })" done fi # Do each command in the postinstall commands. lib=$destdir/$realname func_execute_cmds "$postinstall_cmds" 'exit $?' fi # Install the pseudo-library for information purposes. func_basename "$file" name=$func_basename_result instname=$dir/${name}i func_show_eval "$install_prog $instname $destdir/$name" 'exit $?' # Maybe install the static library, too. test -n "$old_library" && func_append staticlibs " $dir/$old_library" ;; *.lo) # Install (i.e. copy) a libtool object. # Figure out destination file name, if it wasn't already specified. if test -n "$destname"; then destfile=$destdir/$destname else func_basename "$file" destfile=$func_basename_result destfile=$destdir/$destfile fi # Deduce the name of the destination old-style object file. case $destfile in *.lo) func_lo2o "$destfile" staticdest=$func_lo2o_result ;; *.$objext) staticdest=$destfile destfile= ;; *) func_fatal_help "cannot copy a libtool object to '$destfile'" ;; esac # Install the libtool object if requested. test -n "$destfile" && \ func_show_eval "$install_prog $file $destfile" 'exit $?' # Install the old object if enabled. if test yes = "$build_old_libs"; then # Deduce the name of the old-style object file. func_lo2o "$file" staticobj=$func_lo2o_result func_show_eval "$install_prog \$staticobj \$staticdest" 'exit $?' fi exit $EXIT_SUCCESS ;; *) # Figure out destination file name, if it wasn't already specified. if test -n "$destname"; then destfile=$destdir/$destname else func_basename "$file" destfile=$func_basename_result destfile=$destdir/$destfile fi # If the file is missing, and there is a .exe on the end, strip it # because it is most likely a libtool script we actually want to # install stripped_ext= case $file in *.exe) if test ! -f "$file"; then func_stripname '' '.exe' "$file" file=$func_stripname_result stripped_ext=.exe fi ;; esac # Do a test to see if this is really a libtool program. case $host in *cygwin* | *mingw*) if func_ltwrapper_executable_p "$file"; then func_ltwrapper_scriptname "$file" wrapper=$func_ltwrapper_scriptname_result else func_stripname '' '.exe' "$file" wrapper=$func_stripname_result fi ;; *) wrapper=$file ;; esac if func_ltwrapper_script_p "$wrapper"; then notinst_deplibs= relink_command= func_source "$wrapper" # Check the variables that should have been set. test -z "$generated_by_libtool_version" && \ func_fatal_error "invalid libtool wrapper script '$wrapper'" finalize=: for lib in $notinst_deplibs; do # Check to see that each library is installed. libdir= if test -f "$lib"; then func_source "$lib" fi libfile=$libdir/`$ECHO "$lib" | $SED 's%^.*/%%g'` if test -n "$libdir" && test ! -f "$libfile"; then func_warning "'$lib' has not been installed in '$libdir'" finalize=false fi done relink_command= func_source "$wrapper" outputname= if test no = "$fast_install" && test -n "$relink_command"; then $opt_dry_run || { if $finalize; then tmpdir=`func_mktempdir` func_basename "$file$stripped_ext" file=$func_basename_result outputname=$tmpdir/$file # Replace the output file specification. relink_command=`$ECHO "$relink_command" | $SED 's%@OUTPUT@%'"$outputname"'%g'` $opt_quiet || { func_quote_for_expand "$relink_command" eval "func_echo $func_quote_for_expand_result" } if eval "$relink_command"; then : else func_error "error: relink '$file' with the above command before installing it" $opt_dry_run || ${RM}r "$tmpdir" continue fi file=$outputname else func_warning "cannot relink '$file'" fi } else # Install the binary that we compiled earlier. file=`$ECHO "$file$stripped_ext" | $SED "s%\([^/]*\)$%$objdir/\1%"` fi fi # remove .exe since cygwin /usr/bin/install will append another # one anyway case $install_prog,$host in */usr/bin/install*,*cygwin*) case $file:$destfile in *.exe:*.exe) # this is ok ;; *.exe:*) destfile=$destfile.exe ;; *:*.exe) func_stripname '' '.exe' "$destfile" destfile=$func_stripname_result ;; esac ;; esac func_show_eval "$install_prog\$stripme \$file \$destfile" 'exit $?' $opt_dry_run || if test -n "$outputname"; then ${RM}r "$tmpdir" fi ;; esac done for file in $staticlibs; do func_basename "$file" name=$func_basename_result # Set up the ranlib parameters. oldlib=$destdir/$name func_to_tool_file "$oldlib" func_convert_file_msys_to_w32 tool_oldlib=$func_to_tool_file_result func_show_eval "$install_prog \$file \$oldlib" 'exit $?' if test -n "$stripme" && test -n "$old_striplib"; then func_show_eval "$old_striplib $tool_oldlib" 'exit $?' fi # Do each command in the postinstall commands. func_execute_cmds "$old_postinstall_cmds" 'exit $?' done test -n "$future_libdirs" && \ func_warning "remember to run '$progname --finish$future_libdirs'" if test -n "$current_libdirs"; then # Maybe just do a dry run. $opt_dry_run && current_libdirs=" -n$current_libdirs" exec_cmd='$SHELL "$progpath" $preserve_args --finish$current_libdirs' else exit $EXIT_SUCCESS fi } test install = "$opt_mode" && func_mode_install ${1+"$@"} # func_generate_dlsyms outputname originator pic_p # Extract symbols from dlprefiles and create ${outputname}S.o with # a dlpreopen symbol table. func_generate_dlsyms () { $debug_cmd my_outputname=$1 my_originator=$2 my_pic_p=${3-false} my_prefix=`$ECHO "$my_originator" | $SED 's%[^a-zA-Z0-9]%_%g'` my_dlsyms= if test -n "$dlfiles$dlprefiles" || test no != "$dlself"; then if test -n "$NM" && test -n "$global_symbol_pipe"; then my_dlsyms=${my_outputname}S.c else func_error "not configured to extract global symbols from dlpreopened files" fi fi if test -n "$my_dlsyms"; then case $my_dlsyms in "") ;; *.c) # Discover the nlist of each of the dlfiles. nlist=$output_objdir/$my_outputname.nm func_show_eval "$RM $nlist ${nlist}S ${nlist}T" # Parse the name list into a source file. func_verbose "creating $output_objdir/$my_dlsyms" $opt_dry_run || $ECHO > "$output_objdir/$my_dlsyms" "\ /* $my_dlsyms - symbol resolution table for '$my_outputname' dlsym emulation. */ /* Generated by $PROGRAM (GNU $PACKAGE) $VERSION */ #ifdef __cplusplus extern \"C\" { #endif #if defined __GNUC__ && (((__GNUC__ == 4) && (__GNUC_MINOR__ >= 4)) || (__GNUC__ > 4)) #pragma GCC diagnostic ignored \"-Wstrict-prototypes\" #endif /* Keep this code in sync between libtool.m4, ltmain, lt_system.h, and tests. */ #if defined _WIN32 || defined __CYGWIN__ || defined _WIN32_WCE /* DATA imports from DLLs on WIN32 can't be const, because runtime relocations are performed -- see ld's documentation on pseudo-relocs. */ # define LT_DLSYM_CONST #elif defined __osf__ /* This system does not cope well with relocations in const data. */ # define LT_DLSYM_CONST #else # define LT_DLSYM_CONST const #endif #define STREQ(s1, s2) (strcmp ((s1), (s2)) == 0) /* External symbol declarations for the compiler. */\ " if test yes = "$dlself"; then func_verbose "generating symbol list for '$output'" $opt_dry_run || echo ': @PROGRAM@ ' > "$nlist" # Add our own program objects to the symbol list. progfiles=`$ECHO "$objs$old_deplibs" | $SP2NL | $SED "$lo2o" | $NL2SP` for progfile in $progfiles; do func_to_tool_file "$progfile" func_convert_file_msys_to_w32 func_verbose "extracting global C symbols from '$func_to_tool_file_result'" $opt_dry_run || eval "$NM $func_to_tool_file_result | $global_symbol_pipe >> '$nlist'" done if test -n "$exclude_expsyms"; then $opt_dry_run || { eval '$EGREP -v " ($exclude_expsyms)$" "$nlist" > "$nlist"T' eval '$MV "$nlist"T "$nlist"' } fi if test -n "$export_symbols_regex"; then $opt_dry_run || { eval '$EGREP -e "$export_symbols_regex" "$nlist" > "$nlist"T' eval '$MV "$nlist"T "$nlist"' } fi # Prepare the list of exported symbols if test -z "$export_symbols"; then export_symbols=$output_objdir/$outputname.exp $opt_dry_run || { $RM $export_symbols eval "$SED -n -e '/^: @PROGRAM@ $/d' -e 's/^.* \(.*\)$/\1/p' "'< "$nlist" > "$export_symbols"' case $host in *cygwin* | *mingw* | *cegcc* ) eval "echo EXPORTS "'> "$output_objdir/$outputname.def"' eval 'cat "$export_symbols" >> "$output_objdir/$outputname.def"' ;; esac } else $opt_dry_run || { eval "$SED -e 's/\([].[*^$]\)/\\\\\1/g' -e 's/^/ /' -e 's/$/$/'"' < "$export_symbols" > "$output_objdir/$outputname.exp"' eval '$GREP -f "$output_objdir/$outputname.exp" < "$nlist" > "$nlist"T' eval '$MV "$nlist"T "$nlist"' case $host in *cygwin* | *mingw* | *cegcc* ) eval "echo EXPORTS "'> "$output_objdir/$outputname.def"' eval 'cat "$nlist" >> "$output_objdir/$outputname.def"' ;; esac } fi fi for dlprefile in $dlprefiles; do func_verbose "extracting global C symbols from '$dlprefile'" func_basename "$dlprefile" name=$func_basename_result case $host in *cygwin* | *mingw* | *cegcc* ) # if an import library, we need to obtain dlname if func_win32_import_lib_p "$dlprefile"; then func_tr_sh "$dlprefile" eval "curr_lafile=\$libfile_$func_tr_sh_result" dlprefile_dlbasename= if test -n "$curr_lafile" && func_lalib_p "$curr_lafile"; then # Use subshell, to avoid clobbering current variable values dlprefile_dlname=`source "$curr_lafile" && echo "$dlname"` if test -n "$dlprefile_dlname"; then func_basename "$dlprefile_dlname" dlprefile_dlbasename=$func_basename_result else # no lafile. user explicitly requested -dlpreopen . $sharedlib_from_linklib_cmd "$dlprefile" dlprefile_dlbasename=$sharedlib_from_linklib_result fi fi $opt_dry_run || { if test -n "$dlprefile_dlbasename"; then eval '$ECHO ": $dlprefile_dlbasename" >> "$nlist"' else func_warning "Could not compute DLL name from $name" eval '$ECHO ": $name " >> "$nlist"' fi func_to_tool_file "$dlprefile" func_convert_file_msys_to_w32 eval "$NM \"$func_to_tool_file_result\" 2>/dev/null | $global_symbol_pipe | $SED -e '/I __imp/d' -e 's/I __nm_/D /;s/_nm__//' >> '$nlist'" } else # not an import lib $opt_dry_run || { eval '$ECHO ": $name " >> "$nlist"' func_to_tool_file "$dlprefile" func_convert_file_msys_to_w32 eval "$NM \"$func_to_tool_file_result\" 2>/dev/null | $global_symbol_pipe >> '$nlist'" } fi ;; *) $opt_dry_run || { eval '$ECHO ": $name " >> "$nlist"' func_to_tool_file "$dlprefile" func_convert_file_msys_to_w32 eval "$NM \"$func_to_tool_file_result\" 2>/dev/null | $global_symbol_pipe >> '$nlist'" } ;; esac done $opt_dry_run || { # Make sure we have at least an empty file. test -f "$nlist" || : > "$nlist" if test -n "$exclude_expsyms"; then $EGREP -v " ($exclude_expsyms)$" "$nlist" > "$nlist"T $MV "$nlist"T "$nlist" fi # Try sorting and uniquifying the output. if $GREP -v "^: " < "$nlist" | if sort -k 3 /dev/null 2>&1; then sort -k 3 else sort +2 fi | uniq > "$nlist"S; then : else $GREP -v "^: " < "$nlist" > "$nlist"S fi if test -f "$nlist"S; then eval "$global_symbol_to_cdecl"' < "$nlist"S >> "$output_objdir/$my_dlsyms"' else echo '/* NONE */' >> "$output_objdir/$my_dlsyms" fi func_show_eval '$RM "${nlist}I"' if test -n "$global_symbol_to_import"; then eval "$global_symbol_to_import"' < "$nlist"S > "$nlist"I' fi echo >> "$output_objdir/$my_dlsyms" "\ /* The mapping between symbol names and symbols. */ typedef struct { const char *name; void *address; } lt_dlsymlist; extern LT_DLSYM_CONST lt_dlsymlist lt_${my_prefix}_LTX_preloaded_symbols[];\ " if test -s "$nlist"I; then echo >> "$output_objdir/$my_dlsyms" "\ static void lt_syminit(void) { LT_DLSYM_CONST lt_dlsymlist *symbol = lt_${my_prefix}_LTX_preloaded_symbols; for (; symbol->name; ++symbol) {" $SED 's/.*/ if (STREQ (symbol->name, \"&\")) symbol->address = (void *) \&&;/' < "$nlist"I >> "$output_objdir/$my_dlsyms" echo >> "$output_objdir/$my_dlsyms" "\ } }" fi echo >> "$output_objdir/$my_dlsyms" "\ LT_DLSYM_CONST lt_dlsymlist lt_${my_prefix}_LTX_preloaded_symbols[] = { {\"$my_originator\", (void *) 0}," if test -s "$nlist"I; then echo >> "$output_objdir/$my_dlsyms" "\ {\"@INIT@\", (void *) <_syminit}," fi case $need_lib_prefix in no) eval "$global_symbol_to_c_name_address" < "$nlist" >> "$output_objdir/$my_dlsyms" ;; *) eval "$global_symbol_to_c_name_address_lib_prefix" < "$nlist" >> "$output_objdir/$my_dlsyms" ;; esac echo >> "$output_objdir/$my_dlsyms" "\ {0, (void *) 0} }; /* This works around a problem in FreeBSD linker */ #ifdef FREEBSD_WORKAROUND static const void *lt_preloaded_setup() { return lt_${my_prefix}_LTX_preloaded_symbols; } #endif #ifdef __cplusplus } #endif\ " } # !$opt_dry_run pic_flag_for_symtable= case "$compile_command " in *" -static "*) ;; *) case $host in # compiling the symbol table file with pic_flag works around # a FreeBSD bug that causes programs to crash when -lm is # linked before any other PIC object. But we must not use # pic_flag when linking with -static. The problem exists in # FreeBSD 2.2.6 and is fixed in FreeBSD 3.1. *-*-freebsd2.*|*-*-freebsd3.0*|*-*-freebsdelf3.0*) pic_flag_for_symtable=" $pic_flag -DFREEBSD_WORKAROUND" ;; *-*-hpux*) pic_flag_for_symtable=" $pic_flag" ;; *) $my_pic_p && pic_flag_for_symtable=" $pic_flag" ;; esac ;; esac symtab_cflags= for arg in $LTCFLAGS; do case $arg in -pie | -fpie | -fPIE) ;; *) func_append symtab_cflags " $arg" ;; esac done # Now compile the dynamic symbol file. func_show_eval '(cd $output_objdir && $LTCC$symtab_cflags -c$no_builtin_flag$pic_flag_for_symtable "$my_dlsyms")' 'exit $?' # Clean up the generated files. func_show_eval '$RM "$output_objdir/$my_dlsyms" "$nlist" "${nlist}S" "${nlist}T" "${nlist}I"' # Transform the symbol file into the correct name. symfileobj=$output_objdir/${my_outputname}S.$objext case $host in *cygwin* | *mingw* | *cegcc* ) if test -f "$output_objdir/$my_outputname.def"; then compile_command=`$ECHO "$compile_command" | $SED "s%@SYMFILE@%$output_objdir/$my_outputname.def $symfileobj%"` finalize_command=`$ECHO "$finalize_command" | $SED "s%@SYMFILE@%$output_objdir/$my_outputname.def $symfileobj%"` else compile_command=`$ECHO "$compile_command" | $SED "s%@SYMFILE@%$symfileobj%"` finalize_command=`$ECHO "$finalize_command" | $SED "s%@SYMFILE@%$symfileobj%"` fi ;; *) compile_command=`$ECHO "$compile_command" | $SED "s%@SYMFILE@%$symfileobj%"` finalize_command=`$ECHO "$finalize_command" | $SED "s%@SYMFILE@%$symfileobj%"` ;; esac ;; *) func_fatal_error "unknown suffix for '$my_dlsyms'" ;; esac else # We keep going just in case the user didn't refer to # lt_preloaded_symbols. The linker will fail if global_symbol_pipe # really was required. # Nullify the symbol file. compile_command=`$ECHO "$compile_command" | $SED "s% @SYMFILE@%%"` finalize_command=`$ECHO "$finalize_command" | $SED "s% @SYMFILE@%%"` fi } # func_cygming_gnu_implib_p ARG # This predicate returns with zero status (TRUE) if # ARG is a GNU/binutils-style import library. Returns # with nonzero status (FALSE) otherwise. func_cygming_gnu_implib_p () { $debug_cmd func_to_tool_file "$1" func_convert_file_msys_to_w32 func_cygming_gnu_implib_tmp=`$NM "$func_to_tool_file_result" | eval "$global_symbol_pipe" | $EGREP ' (_head_[A-Za-z0-9_]+_[ad]l*|[A-Za-z0-9_]+_[ad]l*_iname)$'` test -n "$func_cygming_gnu_implib_tmp" } # func_cygming_ms_implib_p ARG # This predicate returns with zero status (TRUE) if # ARG is an MS-style import library. Returns # with nonzero status (FALSE) otherwise. func_cygming_ms_implib_p () { $debug_cmd func_to_tool_file "$1" func_convert_file_msys_to_w32 func_cygming_ms_implib_tmp=`$NM "$func_to_tool_file_result" | eval "$global_symbol_pipe" | $GREP '_NULL_IMPORT_DESCRIPTOR'` test -n "$func_cygming_ms_implib_tmp" } # func_win32_libid arg # return the library type of file 'arg' # # Need a lot of goo to handle *both* DLLs and import libs # Has to be a shell function in order to 'eat' the argument # that is supplied when $file_magic_command is called. # Despite the name, also deal with 64 bit binaries. func_win32_libid () { $debug_cmd win32_libid_type=unknown win32_fileres=`file -L $1 2>/dev/null` case $win32_fileres in *ar\ archive\ import\ library*) # definitely import win32_libid_type="x86 archive import" ;; *ar\ archive*) # could be an import, or static # Keep the egrep pattern in sync with the one in _LT_CHECK_MAGIC_METHOD. if eval $OBJDUMP -f $1 | $SED -e '10q' 2>/dev/null | $EGREP 'file format (pei*-i386(.*architecture: i386)?|pe-arm-wince|pe-x86-64)' >/dev/null; then case $nm_interface in "MS dumpbin") if func_cygming_ms_implib_p "$1" || func_cygming_gnu_implib_p "$1" then win32_nmres=import else win32_nmres= fi ;; *) func_to_tool_file "$1" func_convert_file_msys_to_w32 win32_nmres=`eval $NM -f posix -A \"$func_to_tool_file_result\" | $SED -n -e ' 1,100{ / I /{ s|.*|import| p q } }'` ;; esac case $win32_nmres in import*) win32_libid_type="x86 archive import";; *) win32_libid_type="x86 archive static";; esac fi ;; *DLL*) win32_libid_type="x86 DLL" ;; *executable*) # but shell scripts are "executable" too... case $win32_fileres in *MS\ Windows\ PE\ Intel*) win32_libid_type="x86 DLL" ;; esac ;; esac $ECHO "$win32_libid_type" } # func_cygming_dll_for_implib ARG # # Platform-specific function to extract the # name of the DLL associated with the specified # import library ARG. # Invoked by eval'ing the libtool variable # $sharedlib_from_linklib_cmd # Result is available in the variable # $sharedlib_from_linklib_result func_cygming_dll_for_implib () { $debug_cmd sharedlib_from_linklib_result=`$DLLTOOL --identify-strict --identify "$1"` } # func_cygming_dll_for_implib_fallback_core SECTION_NAME LIBNAMEs # # The is the core of a fallback implementation of a # platform-specific function to extract the name of the # DLL associated with the specified import library LIBNAME. # # SECTION_NAME is either .idata$6 or .idata$7, depending # on the platform and compiler that created the implib. # # Echos the name of the DLL associated with the # specified import library. func_cygming_dll_for_implib_fallback_core () { $debug_cmd match_literal=`$ECHO "$1" | $SED "$sed_make_literal_regex"` $OBJDUMP -s --section "$1" "$2" 2>/dev/null | $SED '/^Contents of section '"$match_literal"':/{ # Place marker at beginning of archive member dllname section s/.*/====MARK====/ p d } # These lines can sometimes be longer than 43 characters, but # are always uninteresting /:[ ]*file format pe[i]\{,1\}-/d /^In archive [^:]*:/d # Ensure marker is printed /^====MARK====/p # Remove all lines with less than 43 characters /^.\{43\}/!d # From remaining lines, remove first 43 characters s/^.\{43\}//' | $SED -n ' # Join marker and all lines until next marker into a single line /^====MARK====/ b para H $ b para b :para x s/\n//g # Remove the marker s/^====MARK====// # Remove trailing dots and whitespace s/[\. \t]*$// # Print /./p' | # we now have a list, one entry per line, of the stringified # contents of the appropriate section of all members of the # archive that possess that section. Heuristic: eliminate # all those that have a first or second character that is # a '.' (that is, objdump's representation of an unprintable # character.) This should work for all archives with less than # 0x302f exports -- but will fail for DLLs whose name actually # begins with a literal '.' or a single character followed by # a '.'. # # Of those that remain, print the first one. $SED -e '/^\./d;/^.\./d;q' } # func_cygming_dll_for_implib_fallback ARG # Platform-specific function to extract the # name of the DLL associated with the specified # import library ARG. # # This fallback implementation is for use when $DLLTOOL # does not support the --identify-strict option. # Invoked by eval'ing the libtool variable # $sharedlib_from_linklib_cmd # Result is available in the variable # $sharedlib_from_linklib_result func_cygming_dll_for_implib_fallback () { $debug_cmd if func_cygming_gnu_implib_p "$1"; then # binutils import library sharedlib_from_linklib_result=`func_cygming_dll_for_implib_fallback_core '.idata$7' "$1"` elif func_cygming_ms_implib_p "$1"; then # ms-generated import library sharedlib_from_linklib_result=`func_cygming_dll_for_implib_fallback_core '.idata$6' "$1"` else # unknown sharedlib_from_linklib_result= fi } # func_extract_an_archive dir oldlib func_extract_an_archive () { $debug_cmd f_ex_an_ar_dir=$1; shift f_ex_an_ar_oldlib=$1 if test yes = "$lock_old_archive_extraction"; then lockfile=$f_ex_an_ar_oldlib.lock until $opt_dry_run || ln "$progpath" "$lockfile" 2>/dev/null; do func_echo "Waiting for $lockfile to be removed" sleep 2 done fi func_show_eval "(cd \$f_ex_an_ar_dir && $AR x \"\$f_ex_an_ar_oldlib\")" \ 'stat=$?; rm -f "$lockfile"; exit $stat' if test yes = "$lock_old_archive_extraction"; then $opt_dry_run || rm -f "$lockfile" fi if ($AR t "$f_ex_an_ar_oldlib" | sort | sort -uc >/dev/null 2>&1); then : else func_fatal_error "object name conflicts in archive: $f_ex_an_ar_dir/$f_ex_an_ar_oldlib" fi } # func_extract_archives gentop oldlib ... func_extract_archives () { $debug_cmd my_gentop=$1; shift my_oldlibs=${1+"$@"} my_oldobjs= my_xlib= my_xabs= my_xdir= for my_xlib in $my_oldlibs; do # Extract the objects. case $my_xlib in [\\/]* | [A-Za-z]:[\\/]*) my_xabs=$my_xlib ;; *) my_xabs=`pwd`"/$my_xlib" ;; esac func_basename "$my_xlib" my_xlib=$func_basename_result my_xlib_u=$my_xlib while :; do case " $extracted_archives " in *" $my_xlib_u "*) func_arith $extracted_serial + 1 extracted_serial=$func_arith_result my_xlib_u=lt$extracted_serial-$my_xlib ;; *) break ;; esac done extracted_archives="$extracted_archives $my_xlib_u" my_xdir=$my_gentop/$my_xlib_u func_mkdir_p "$my_xdir" case $host in *-darwin*) func_verbose "Extracting $my_xabs" # Do not bother doing anything if just a dry run $opt_dry_run || { darwin_orig_dir=`pwd` cd $my_xdir || exit $? darwin_archive=$my_xabs darwin_curdir=`pwd` func_basename "$darwin_archive" darwin_base_archive=$func_basename_result darwin_arches=`$LIPO -info "$darwin_archive" 2>/dev/null | $GREP Architectures 2>/dev/null || true` if test -n "$darwin_arches"; then darwin_arches=`$ECHO "$darwin_arches" | $SED -e 's/.*are://'` darwin_arch= func_verbose "$darwin_base_archive has multiple architectures $darwin_arches" for darwin_arch in $darwin_arches; do func_mkdir_p "unfat-$$/$darwin_base_archive-$darwin_arch" $LIPO -thin $darwin_arch -output "unfat-$$/$darwin_base_archive-$darwin_arch/$darwin_base_archive" "$darwin_archive" cd "unfat-$$/$darwin_base_archive-$darwin_arch" func_extract_an_archive "`pwd`" "$darwin_base_archive" cd "$darwin_curdir" $RM "unfat-$$/$darwin_base_archive-$darwin_arch/$darwin_base_archive" done # $darwin_arches ## Okay now we've a bunch of thin objects, gotta fatten them up :) darwin_filelist=`find unfat-$$ -type f -name \*.o -print -o -name \*.lo -print | $SED -e "$sed_basename" | sort -u` darwin_file= darwin_files= for darwin_file in $darwin_filelist; do darwin_files=`find unfat-$$ -name $darwin_file -print | sort | $NL2SP` $LIPO -create -output "$darwin_file" $darwin_files done # $darwin_filelist $RM -rf unfat-$$ cd "$darwin_orig_dir" else cd $darwin_orig_dir func_extract_an_archive "$my_xdir" "$my_xabs" fi # $darwin_arches } # !$opt_dry_run ;; *) func_extract_an_archive "$my_xdir" "$my_xabs" ;; esac my_oldobjs="$my_oldobjs "`find $my_xdir -name \*.$objext -print -o -name \*.lo -print | sort | $NL2SP` done func_extract_archives_result=$my_oldobjs } # func_emit_wrapper [arg=no] # # Emit a libtool wrapper script on stdout. # Don't directly open a file because we may want to # incorporate the script contents within a cygwin/mingw # wrapper executable. Must ONLY be called from within # func_mode_link because it depends on a number of variables # set therein. # # ARG is the value that the WRAPPER_SCRIPT_BELONGS_IN_OBJDIR # variable will take. If 'yes', then the emitted script # will assume that the directory where it is stored is # the $objdir directory. This is a cygwin/mingw-specific # behavior. func_emit_wrapper () { func_emit_wrapper_arg1=${1-no} $ECHO "\ #! $SHELL # $output - temporary wrapper script for $objdir/$outputname # Generated by $PROGRAM (GNU $PACKAGE) $VERSION # # The $output program cannot be directly executed until all the libtool # libraries that it depends on are installed. # # This wrapper script should never be moved out of the build directory. # If it is, it will not operate correctly. # Sed substitution that helps us do robust quoting. It backslashifies # metacharacters that are still active within double-quoted strings. sed_quote_subst='$sed_quote_subst' # Be Bourne compatible if test -n \"\${ZSH_VERSION+set}\" && (emulate sh) >/dev/null 2>&1; then emulate sh NULLCMD=: # Zsh 3.x and 4.x performs word splitting on \${1+\"\$@\"}, which # is contrary to our usage. Disable this feature. alias -g '\${1+\"\$@\"}'='\"\$@\"' setopt NO_GLOB_SUBST else case \`(set -o) 2>/dev/null\` in *posix*) set -o posix;; esac fi BIN_SH=xpg4; export BIN_SH # for Tru64 DUALCASE=1; export DUALCASE # for MKS sh # The HP-UX ksh and POSIX shell print the target directory to stdout # if CDPATH is set. (unset CDPATH) >/dev/null 2>&1 && unset CDPATH relink_command=\"$relink_command\" # This environment variable determines our operation mode. if test \"\$libtool_install_magic\" = \"$magic\"; then # install mode needs the following variables: generated_by_libtool_version='$macro_version' notinst_deplibs='$notinst_deplibs' else # When we are sourced in execute mode, \$file and \$ECHO are already set. if test \"\$libtool_execute_magic\" != \"$magic\"; then file=\"\$0\"" qECHO=`$ECHO "$ECHO" | $SED "$sed_quote_subst"` $ECHO "\ # A function that is used when there is no print builtin or printf. func_fallback_echo () { eval 'cat <<_LTECHO_EOF \$1 _LTECHO_EOF' } ECHO=\"$qECHO\" fi # Very basic option parsing. These options are (a) specific to # the libtool wrapper, (b) are identical between the wrapper # /script/ and the wrapper /executable/ that is used only on # windows platforms, and (c) all begin with the string "--lt-" # (application programs are unlikely to have options that match # this pattern). # # There are only two supported options: --lt-debug and # --lt-dump-script. There is, deliberately, no --lt-help. # # The first argument to this parsing function should be the # script's $0 value, followed by "$@". lt_option_debug= func_parse_lt_options () { lt_script_arg0=\$0 shift for lt_opt do case \"\$lt_opt\" in --lt-debug) lt_option_debug=1 ;; --lt-dump-script) lt_dump_D=\`\$ECHO \"X\$lt_script_arg0\" | $SED -e 's/^X//' -e 's%/[^/]*$%%'\` test \"X\$lt_dump_D\" = \"X\$lt_script_arg0\" && lt_dump_D=. lt_dump_F=\`\$ECHO \"X\$lt_script_arg0\" | $SED -e 's/^X//' -e 's%^.*/%%'\` cat \"\$lt_dump_D/\$lt_dump_F\" exit 0 ;; --lt-*) \$ECHO \"Unrecognized --lt- option: '\$lt_opt'\" 1>&2 exit 1 ;; esac done # Print the debug banner immediately: if test -n \"\$lt_option_debug\"; then echo \"$outputname:$output:\$LINENO: libtool wrapper (GNU $PACKAGE) $VERSION\" 1>&2 fi } # Used when --lt-debug. Prints its arguments to stdout # (redirection is the responsibility of the caller) func_lt_dump_args () { lt_dump_args_N=1; for lt_arg do \$ECHO \"$outputname:$output:\$LINENO: newargv[\$lt_dump_args_N]: \$lt_arg\" lt_dump_args_N=\`expr \$lt_dump_args_N + 1\` done } # Core function for launching the target application func_exec_program_core () { " case $host in # Backslashes separate directories on plain windows *-*-mingw | *-*-os2* | *-cegcc*) $ECHO "\ if test -n \"\$lt_option_debug\"; then \$ECHO \"$outputname:$output:\$LINENO: newargv[0]: \$progdir\\\\\$program\" 1>&2 func_lt_dump_args \${1+\"\$@\"} 1>&2 fi exec \"\$progdir\\\\\$program\" \${1+\"\$@\"} " ;; *) $ECHO "\ if test -n \"\$lt_option_debug\"; then \$ECHO \"$outputname:$output:\$LINENO: newargv[0]: \$progdir/\$program\" 1>&2 func_lt_dump_args \${1+\"\$@\"} 1>&2 fi exec \"\$progdir/\$program\" \${1+\"\$@\"} " ;; esac $ECHO "\ \$ECHO \"\$0: cannot exec \$program \$*\" 1>&2 exit 1 } # A function to encapsulate launching the target application # Strips options in the --lt-* namespace from \$@ and # launches target application with the remaining arguments. func_exec_program () { case \" \$* \" in *\\ --lt-*) for lt_wr_arg do case \$lt_wr_arg in --lt-*) ;; *) set x \"\$@\" \"\$lt_wr_arg\"; shift;; esac shift done ;; esac func_exec_program_core \${1+\"\$@\"} } # Parse options func_parse_lt_options \"\$0\" \${1+\"\$@\"} # Find the directory that this script lives in. thisdir=\`\$ECHO \"\$file\" | $SED 's%/[^/]*$%%'\` test \"x\$thisdir\" = \"x\$file\" && thisdir=. # Follow symbolic links until we get to the real thisdir. file=\`ls -ld \"\$file\" | $SED -n 's/.*-> //p'\` while test -n \"\$file\"; do destdir=\`\$ECHO \"\$file\" | $SED 's%/[^/]*\$%%'\` # If there was a directory component, then change thisdir. if test \"x\$destdir\" != \"x\$file\"; then case \"\$destdir\" in [\\\\/]* | [A-Za-z]:[\\\\/]*) thisdir=\"\$destdir\" ;; *) thisdir=\"\$thisdir/\$destdir\" ;; esac fi file=\`\$ECHO \"\$file\" | $SED 's%^.*/%%'\` file=\`ls -ld \"\$thisdir/\$file\" | $SED -n 's/.*-> //p'\` done # Usually 'no', except on cygwin/mingw when embedded into # the cwrapper. WRAPPER_SCRIPT_BELONGS_IN_OBJDIR=$func_emit_wrapper_arg1 if test \"\$WRAPPER_SCRIPT_BELONGS_IN_OBJDIR\" = \"yes\"; then # special case for '.' if test \"\$thisdir\" = \".\"; then thisdir=\`pwd\` fi # remove .libs from thisdir case \"\$thisdir\" in *[\\\\/]$objdir ) thisdir=\`\$ECHO \"\$thisdir\" | $SED 's%[\\\\/][^\\\\/]*$%%'\` ;; $objdir ) thisdir=. ;; esac fi # Try to get the absolute directory name. absdir=\`cd \"\$thisdir\" && pwd\` test -n \"\$absdir\" && thisdir=\"\$absdir\" " if test yes = "$fast_install"; then $ECHO "\ program=lt-'$outputname'$exeext progdir=\"\$thisdir/$objdir\" if test ! -f \"\$progdir/\$program\" || { file=\`ls -1dt \"\$progdir/\$program\" \"\$progdir/../\$program\" 2>/dev/null | $SED 1q\`; \\ test \"X\$file\" != \"X\$progdir/\$program\"; }; then file=\"\$\$-\$program\" if test ! -d \"\$progdir\"; then $MKDIR \"\$progdir\" else $RM \"\$progdir/\$file\" fi" $ECHO "\ # relink executable if necessary if test -n \"\$relink_command\"; then if relink_command_output=\`eval \$relink_command 2>&1\`; then : else \$ECHO \"\$relink_command_output\" >&2 $RM \"\$progdir/\$file\" exit 1 fi fi $MV \"\$progdir/\$file\" \"\$progdir/\$program\" 2>/dev/null || { $RM \"\$progdir/\$program\"; $MV \"\$progdir/\$file\" \"\$progdir/\$program\"; } $RM \"\$progdir/\$file\" fi" else $ECHO "\ program='$outputname' progdir=\"\$thisdir/$objdir\" " fi $ECHO "\ if test -f \"\$progdir/\$program\"; then" # fixup the dll searchpath if we need to. # # Fix the DLL searchpath if we need to. Do this before prepending # to shlibpath, because on Windows, both are PATH and uninstalled # libraries must come first. if test -n "$dllsearchpath"; then $ECHO "\ # Add the dll search path components to the executable PATH PATH=$dllsearchpath:\$PATH " fi # Export our shlibpath_var if we have one. if test yes = "$shlibpath_overrides_runpath" && test -n "$shlibpath_var" && test -n "$temp_rpath"; then $ECHO "\ # Add our own library path to $shlibpath_var $shlibpath_var=\"$temp_rpath\$$shlibpath_var\" # Some systems cannot cope with colon-terminated $shlibpath_var # The second colon is a workaround for a bug in BeOS R4 sed $shlibpath_var=\`\$ECHO \"\$$shlibpath_var\" | $SED 's/::*\$//'\` export $shlibpath_var " fi $ECHO "\ if test \"\$libtool_execute_magic\" != \"$magic\"; then # Run the actual program with our arguments. func_exec_program \${1+\"\$@\"} fi else # The program doesn't exist. \$ECHO \"\$0: error: '\$progdir/\$program' does not exist\" 1>&2 \$ECHO \"This script is just a wrapper for \$program.\" 1>&2 \$ECHO \"See the $PACKAGE documentation for more information.\" 1>&2 exit 1 fi fi\ " } # func_emit_cwrapperexe_src # emit the source code for a wrapper executable on stdout # Must ONLY be called from within func_mode_link because # it depends on a number of variable set therein. func_emit_cwrapperexe_src () { cat < #include #ifdef _MSC_VER # include # include # include #else # include # include # ifdef __CYGWIN__ # include # endif #endif #include #include #include #include #include #include #include #include #define STREQ(s1, s2) (strcmp ((s1), (s2)) == 0) /* declarations of non-ANSI functions */ #if defined __MINGW32__ # ifdef __STRICT_ANSI__ int _putenv (const char *); # endif #elif defined __CYGWIN__ # ifdef __STRICT_ANSI__ char *realpath (const char *, char *); int putenv (char *); int setenv (const char *, const char *, int); # endif /* #elif defined other_platform || defined ... */ #endif /* portability defines, excluding path handling macros */ #if defined _MSC_VER # define setmode _setmode # define stat _stat # define chmod _chmod # define getcwd _getcwd # define putenv _putenv # define S_IXUSR _S_IEXEC #elif defined __MINGW32__ # define setmode _setmode # define stat _stat # define chmod _chmod # define getcwd _getcwd # define putenv _putenv #elif defined __CYGWIN__ # define HAVE_SETENV # define FOPEN_WB "wb" /* #elif defined other platforms ... */ #endif #if defined PATH_MAX # define LT_PATHMAX PATH_MAX #elif defined MAXPATHLEN # define LT_PATHMAX MAXPATHLEN #else # define LT_PATHMAX 1024 #endif #ifndef S_IXOTH # define S_IXOTH 0 #endif #ifndef S_IXGRP # define S_IXGRP 0 #endif /* path handling portability macros */ #ifndef DIR_SEPARATOR # define DIR_SEPARATOR '/' # define PATH_SEPARATOR ':' #endif #if defined _WIN32 || defined __MSDOS__ || defined __DJGPP__ || \ defined __OS2__ # define HAVE_DOS_BASED_FILE_SYSTEM # define FOPEN_WB "wb" # ifndef DIR_SEPARATOR_2 # define DIR_SEPARATOR_2 '\\' # endif # ifndef PATH_SEPARATOR_2 # define PATH_SEPARATOR_2 ';' # endif #endif #ifndef DIR_SEPARATOR_2 # define IS_DIR_SEPARATOR(ch) ((ch) == DIR_SEPARATOR) #else /* DIR_SEPARATOR_2 */ # define IS_DIR_SEPARATOR(ch) \ (((ch) == DIR_SEPARATOR) || ((ch) == DIR_SEPARATOR_2)) #endif /* DIR_SEPARATOR_2 */ #ifndef PATH_SEPARATOR_2 # define IS_PATH_SEPARATOR(ch) ((ch) == PATH_SEPARATOR) #else /* PATH_SEPARATOR_2 */ # define IS_PATH_SEPARATOR(ch) ((ch) == PATH_SEPARATOR_2) #endif /* PATH_SEPARATOR_2 */ #ifndef FOPEN_WB # define FOPEN_WB "w" #endif #ifndef _O_BINARY # define _O_BINARY 0 #endif #define XMALLOC(type, num) ((type *) xmalloc ((num) * sizeof(type))) #define XFREE(stale) do { \ if (stale) { free (stale); stale = 0; } \ } while (0) #if defined LT_DEBUGWRAPPER static int lt_debug = 1; #else static int lt_debug = 0; #endif const char *program_name = "libtool-wrapper"; /* in case xstrdup fails */ void *xmalloc (size_t num); char *xstrdup (const char *string); const char *base_name (const char *name); char *find_executable (const char *wrapper); char *chase_symlinks (const char *pathspec); int make_executable (const char *path); int check_executable (const char *path); char *strendzap (char *str, const char *pat); void lt_debugprintf (const char *file, int line, const char *fmt, ...); void lt_fatal (const char *file, int line, const char *message, ...); static const char *nonnull (const char *s); static const char *nonempty (const char *s); void lt_setenv (const char *name, const char *value); char *lt_extend_str (const char *orig_value, const char *add, int to_end); void lt_update_exe_path (const char *name, const char *value); void lt_update_lib_path (const char *name, const char *value); char **prepare_spawn (char **argv); void lt_dump_script (FILE *f); EOF cat <= 0) && (st.st_mode & (S_IXUSR | S_IXGRP | S_IXOTH))) return 1; else return 0; } int make_executable (const char *path) { int rval = 0; struct stat st; lt_debugprintf (__FILE__, __LINE__, "(make_executable): %s\n", nonempty (path)); if ((!path) || (!*path)) return 0; if (stat (path, &st) >= 0) { rval = chmod (path, st.st_mode | S_IXOTH | S_IXGRP | S_IXUSR); } return rval; } /* Searches for the full path of the wrapper. Returns newly allocated full path name if found, NULL otherwise Does not chase symlinks, even on platforms that support them. */ char * find_executable (const char *wrapper) { int has_slash = 0; const char *p; const char *p_next; /* static buffer for getcwd */ char tmp[LT_PATHMAX + 1]; size_t tmp_len; char *concat_name; lt_debugprintf (__FILE__, __LINE__, "(find_executable): %s\n", nonempty (wrapper)); if ((wrapper == NULL) || (*wrapper == '\0')) return NULL; /* Absolute path? */ #if defined HAVE_DOS_BASED_FILE_SYSTEM if (isalpha ((unsigned char) wrapper[0]) && wrapper[1] == ':') { concat_name = xstrdup (wrapper); if (check_executable (concat_name)) return concat_name; XFREE (concat_name); } else { #endif if (IS_DIR_SEPARATOR (wrapper[0])) { concat_name = xstrdup (wrapper); if (check_executable (concat_name)) return concat_name; XFREE (concat_name); } #if defined HAVE_DOS_BASED_FILE_SYSTEM } #endif for (p = wrapper; *p; p++) if (*p == '/') { has_slash = 1; break; } if (!has_slash) { /* no slashes; search PATH */ const char *path = getenv ("PATH"); if (path != NULL) { for (p = path; *p; p = p_next) { const char *q; size_t p_len; for (q = p; *q; q++) if (IS_PATH_SEPARATOR (*q)) break; p_len = (size_t) (q - p); p_next = (*q == '\0' ? q : q + 1); if (p_len == 0) { /* empty path: current directory */ if (getcwd (tmp, LT_PATHMAX) == NULL) lt_fatal (__FILE__, __LINE__, "getcwd failed: %s", nonnull (strerror (errno))); tmp_len = strlen (tmp); concat_name = XMALLOC (char, tmp_len + 1 + strlen (wrapper) + 1); memcpy (concat_name, tmp, tmp_len); concat_name[tmp_len] = '/'; strcpy (concat_name + tmp_len + 1, wrapper); } else { concat_name = XMALLOC (char, p_len + 1 + strlen (wrapper) + 1); memcpy (concat_name, p, p_len); concat_name[p_len] = '/'; strcpy (concat_name + p_len + 1, wrapper); } if (check_executable (concat_name)) return concat_name; XFREE (concat_name); } } /* not found in PATH; assume curdir */ } /* Relative path | not found in path: prepend cwd */ if (getcwd (tmp, LT_PATHMAX) == NULL) lt_fatal (__FILE__, __LINE__, "getcwd failed: %s", nonnull (strerror (errno))); tmp_len = strlen (tmp); concat_name = XMALLOC (char, tmp_len + 1 + strlen (wrapper) + 1); memcpy (concat_name, tmp, tmp_len); concat_name[tmp_len] = '/'; strcpy (concat_name + tmp_len + 1, wrapper); if (check_executable (concat_name)) return concat_name; XFREE (concat_name); return NULL; } char * chase_symlinks (const char *pathspec) { #ifndef S_ISLNK return xstrdup (pathspec); #else char buf[LT_PATHMAX]; struct stat s; char *tmp_pathspec = xstrdup (pathspec); char *p; int has_symlinks = 0; while (strlen (tmp_pathspec) && !has_symlinks) { lt_debugprintf (__FILE__, __LINE__, "checking path component for symlinks: %s\n", tmp_pathspec); if (lstat (tmp_pathspec, &s) == 0) { if (S_ISLNK (s.st_mode) != 0) { has_symlinks = 1; break; } /* search backwards for last DIR_SEPARATOR */ p = tmp_pathspec + strlen (tmp_pathspec) - 1; while ((p > tmp_pathspec) && (!IS_DIR_SEPARATOR (*p))) p--; if ((p == tmp_pathspec) && (!IS_DIR_SEPARATOR (*p))) { /* no more DIR_SEPARATORS left */ break; } *p = '\0'; } else { lt_fatal (__FILE__, __LINE__, "error accessing file \"%s\": %s", tmp_pathspec, nonnull (strerror (errno))); } } XFREE (tmp_pathspec); if (!has_symlinks) { return xstrdup (pathspec); } tmp_pathspec = realpath (pathspec, buf); if (tmp_pathspec == 0) { lt_fatal (__FILE__, __LINE__, "could not follow symlinks for %s", pathspec); } return xstrdup (tmp_pathspec); #endif } char * strendzap (char *str, const char *pat) { size_t len, patlen; assert (str != NULL); assert (pat != NULL); len = strlen (str); patlen = strlen (pat); if (patlen <= len) { str += len - patlen; if (STREQ (str, pat)) *str = '\0'; } return str; } void lt_debugprintf (const char *file, int line, const char *fmt, ...) { va_list args; if (lt_debug) { (void) fprintf (stderr, "%s:%s:%d: ", program_name, file, line); va_start (args, fmt); (void) vfprintf (stderr, fmt, args); va_end (args); } } static void lt_error_core (int exit_status, const char *file, int line, const char *mode, const char *message, va_list ap) { fprintf (stderr, "%s:%s:%d: %s: ", program_name, file, line, mode); vfprintf (stderr, message, ap); fprintf (stderr, ".\n"); if (exit_status >= 0) exit (exit_status); } void lt_fatal (const char *file, int line, const char *message, ...) { va_list ap; va_start (ap, message); lt_error_core (EXIT_FAILURE, file, line, "FATAL", message, ap); va_end (ap); } static const char * nonnull (const char *s) { return s ? s : "(null)"; } static const char * nonempty (const char *s) { return (s && !*s) ? "(empty)" : nonnull (s); } void lt_setenv (const char *name, const char *value) { lt_debugprintf (__FILE__, __LINE__, "(lt_setenv) setting '%s' to '%s'\n", nonnull (name), nonnull (value)); { #ifdef HAVE_SETENV /* always make a copy, for consistency with !HAVE_SETENV */ char *str = xstrdup (value); setenv (name, str, 1); #else size_t len = strlen (name) + 1 + strlen (value) + 1; char *str = XMALLOC (char, len); sprintf (str, "%s=%s", name, value); if (putenv (str) != EXIT_SUCCESS) { XFREE (str); } #endif } } char * lt_extend_str (const char *orig_value, const char *add, int to_end) { char *new_value; if (orig_value && *orig_value) { size_t orig_value_len = strlen (orig_value); size_t add_len = strlen (add); new_value = XMALLOC (char, add_len + orig_value_len + 1); if (to_end) { strcpy (new_value, orig_value); strcpy (new_value + orig_value_len, add); } else { strcpy (new_value, add); strcpy (new_value + add_len, orig_value); } } else { new_value = xstrdup (add); } return new_value; } void lt_update_exe_path (const char *name, const char *value) { lt_debugprintf (__FILE__, __LINE__, "(lt_update_exe_path) modifying '%s' by prepending '%s'\n", nonnull (name), nonnull (value)); if (name && *name && value && *value) { char *new_value = lt_extend_str (getenv (name), value, 0); /* some systems can't cope with a ':'-terminated path #' */ size_t len = strlen (new_value); while ((len > 0) && IS_PATH_SEPARATOR (new_value[len-1])) { new_value[--len] = '\0'; } lt_setenv (name, new_value); XFREE (new_value); } } void lt_update_lib_path (const char *name, const char *value) { lt_debugprintf (__FILE__, __LINE__, "(lt_update_lib_path) modifying '%s' by prepending '%s'\n", nonnull (name), nonnull (value)); if (name && *name && value && *value) { char *new_value = lt_extend_str (getenv (name), value, 0); lt_setenv (name, new_value); XFREE (new_value); } } EOF case $host_os in mingw*) cat <<"EOF" /* Prepares an argument vector before calling spawn(). Note that spawn() does not by itself call the command interpreter (getenv ("COMSPEC") != NULL ? getenv ("COMSPEC") : ({ OSVERSIONINFO v; v.dwOSVersionInfoSize = sizeof(OSVERSIONINFO); GetVersionEx(&v); v.dwPlatformId == VER_PLATFORM_WIN32_NT; }) ? "cmd.exe" : "command.com"). Instead it simply concatenates the arguments, separated by ' ', and calls CreateProcess(). We must quote the arguments since Win32 CreateProcess() interprets characters like ' ', '\t', '\\', '"' (but not '<' and '>') in a special way: - Space and tab are interpreted as delimiters. They are not treated as delimiters if they are surrounded by double quotes: "...". - Unescaped double quotes are removed from the input. Their only effect is that within double quotes, space and tab are treated like normal characters. - Backslashes not followed by double quotes are not special. - But 2*n+1 backslashes followed by a double quote become n backslashes followed by a double quote (n >= 0): \" -> " \\\" -> \" \\\\\" -> \\" */ #define SHELL_SPECIAL_CHARS "\"\\ \001\002\003\004\005\006\007\010\011\012\013\014\015\016\017\020\021\022\023\024\025\026\027\030\031\032\033\034\035\036\037" #define SHELL_SPACE_CHARS " \001\002\003\004\005\006\007\010\011\012\013\014\015\016\017\020\021\022\023\024\025\026\027\030\031\032\033\034\035\036\037" char ** prepare_spawn (char **argv) { size_t argc; char **new_argv; size_t i; /* Count number of arguments. */ for (argc = 0; argv[argc] != NULL; argc++) ; /* Allocate new argument vector. */ new_argv = XMALLOC (char *, argc + 1); /* Put quoted arguments into the new argument vector. */ for (i = 0; i < argc; i++) { const char *string = argv[i]; if (string[0] == '\0') new_argv[i] = xstrdup ("\"\""); else if (strpbrk (string, SHELL_SPECIAL_CHARS) != NULL) { int quote_around = (strpbrk (string, SHELL_SPACE_CHARS) != NULL); size_t length; unsigned int backslashes; const char *s; char *quoted_string; char *p; length = 0; backslashes = 0; if (quote_around) length++; for (s = string; *s != '\0'; s++) { char c = *s; if (c == '"') length += backslashes + 1; length++; if (c == '\\') backslashes++; else backslashes = 0; } if (quote_around) length += backslashes + 1; quoted_string = XMALLOC (char, length + 1); p = quoted_string; backslashes = 0; if (quote_around) *p++ = '"'; for (s = string; *s != '\0'; s++) { char c = *s; if (c == '"') { unsigned int j; for (j = backslashes + 1; j > 0; j--) *p++ = '\\'; } *p++ = c; if (c == '\\') backslashes++; else backslashes = 0; } if (quote_around) { unsigned int j; for (j = backslashes; j > 0; j--) *p++ = '\\'; *p++ = '"'; } *p = '\0'; new_argv[i] = quoted_string; } else new_argv[i] = (char *) string; } new_argv[argc] = NULL; return new_argv; } EOF ;; esac cat <<"EOF" void lt_dump_script (FILE* f) { EOF func_emit_wrapper yes | $SED -n -e ' s/^\(.\{79\}\)\(..*\)/\1\ \2/ h s/\([\\"]\)/\\\1/g s/$/\\n/ s/\([^\n]*\).*/ fputs ("\1", f);/p g D' cat <<"EOF" } EOF } # end: func_emit_cwrapperexe_src # func_win32_import_lib_p ARG # True if ARG is an import lib, as indicated by $file_magic_cmd func_win32_import_lib_p () { $debug_cmd case `eval $file_magic_cmd \"\$1\" 2>/dev/null | $SED -e 10q` in *import*) : ;; *) false ;; esac } # func_suncc_cstd_abi # !!ONLY CALL THIS FOR SUN CC AFTER $compile_command IS FULLY EXPANDED!! # Several compiler flags select an ABI that is incompatible with the # Cstd library. Avoid specifying it if any are in CXXFLAGS. func_suncc_cstd_abi () { $debug_cmd case " $compile_command " in *" -compat=g "*|*\ -std=c++[0-9][0-9]\ *|*" -library=stdcxx4 "*|*" -library=stlport4 "*) suncc_use_cstd_abi=no ;; *) suncc_use_cstd_abi=yes ;; esac } # func_mode_link arg... func_mode_link () { $debug_cmd case $host in *-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-os2* | *-cegcc*) # It is impossible to link a dll without this setting, and # we shouldn't force the makefile maintainer to figure out # what system we are compiling for in order to pass an extra # flag for every libtool invocation. # allow_undefined=no # FIXME: Unfortunately, there are problems with the above when trying # to make a dll that has undefined symbols, in which case not # even a static library is built. For now, we need to specify # -no-undefined on the libtool link line when we can be certain # that all symbols are satisfied, otherwise we get a static library. allow_undefined=yes ;; *) allow_undefined=yes ;; esac libtool_args=$nonopt base_compile="$nonopt $@" compile_command=$nonopt finalize_command=$nonopt compile_rpath= finalize_rpath= compile_shlibpath= finalize_shlibpath= convenience= old_convenience= deplibs= old_deplibs= compiler_flags= linker_flags= dllsearchpath= lib_search_path=`pwd` inst_prefix_dir= new_inherited_linker_flags= avoid_version=no bindir= dlfiles= dlprefiles= dlself=no export_dynamic=no export_symbols= export_symbols_regex= generated= libobjs= ltlibs= module=no no_install=no objs= os2dllname= non_pic_objects= precious_files_regex= prefer_static_libs=no preload=false prev= prevarg= release= rpath= xrpath= perm_rpath= temp_rpath= thread_safe=no vinfo= vinfo_number=no weak_libs= single_module=$wl-single_module func_infer_tag $base_compile # We need to know -static, to get the right output filenames. for arg do case $arg in -shared) test yes != "$build_libtool_libs" \ && func_fatal_configuration "cannot build a shared library" build_old_libs=no break ;; -all-static | -static | -static-libtool-libs) case $arg in -all-static) if test yes = "$build_libtool_libs" && test -z "$link_static_flag"; then func_warning "complete static linking is impossible in this configuration" fi if test -n "$link_static_flag"; then dlopen_self=$dlopen_self_static fi prefer_static_libs=yes ;; -static) if test -z "$pic_flag" && test -n "$link_static_flag"; then dlopen_self=$dlopen_self_static fi prefer_static_libs=built ;; -static-libtool-libs) if test -z "$pic_flag" && test -n "$link_static_flag"; then dlopen_self=$dlopen_self_static fi prefer_static_libs=yes ;; esac build_libtool_libs=no build_old_libs=yes break ;; esac done # See if our shared archives depend on static archives. test -n "$old_archive_from_new_cmds" && build_old_libs=yes # Go through the arguments, transforming them on the way. while test "$#" -gt 0; do arg=$1 shift func_quote_for_eval "$arg" qarg=$func_quote_for_eval_unquoted_result func_append libtool_args " $func_quote_for_eval_result" # If the previous option needs an argument, assign it. if test -n "$prev"; then case $prev in output) func_append compile_command " @OUTPUT@" func_append finalize_command " @OUTPUT@" ;; esac case $prev in bindir) bindir=$arg prev= continue ;; dlfiles|dlprefiles) $preload || { # Add the symbol object into the linking commands. func_append compile_command " @SYMFILE@" func_append finalize_command " @SYMFILE@" preload=: } case $arg in *.la | *.lo) ;; # We handle these cases below. force) if test no = "$dlself"; then dlself=needless export_dynamic=yes fi prev= continue ;; self) if test dlprefiles = "$prev"; then dlself=yes elif test dlfiles = "$prev" && test yes != "$dlopen_self"; then dlself=yes else dlself=needless export_dynamic=yes fi prev= continue ;; *) if test dlfiles = "$prev"; then func_append dlfiles " $arg" else func_append dlprefiles " $arg" fi prev= continue ;; esac ;; expsyms) export_symbols=$arg test -f "$arg" \ || func_fatal_error "symbol file '$arg' does not exist" prev= continue ;; expsyms_regex) export_symbols_regex=$arg prev= continue ;; framework) case $host in *-*-darwin*) case "$deplibs " in *" $qarg.ltframework "*) ;; *) func_append deplibs " $qarg.ltframework" # this is fixed later ;; esac ;; esac prev= continue ;; inst_prefix) inst_prefix_dir=$arg prev= continue ;; mllvm) # Clang does not use LLVM to link, so we can simply discard any # '-mllvm $arg' options when doing the link step. prev= continue ;; objectlist) if test -f "$arg"; then save_arg=$arg moreargs= for fil in `cat "$save_arg"` do # func_append moreargs " $fil" arg=$fil # A libtool-controlled object. # Check to see that this really is a libtool object. if func_lalib_unsafe_p "$arg"; then pic_object= non_pic_object= # Read the .lo file func_source "$arg" if test -z "$pic_object" || test -z "$non_pic_object" || test none = "$pic_object" && test none = "$non_pic_object"; then func_fatal_error "cannot find name of object for '$arg'" fi # Extract subdirectory from the argument. func_dirname "$arg" "/" "" xdir=$func_dirname_result if test none != "$pic_object"; then # Prepend the subdirectory the object is found in. pic_object=$xdir$pic_object if test dlfiles = "$prev"; then if test yes = "$build_libtool_libs" && test yes = "$dlopen_support"; then func_append dlfiles " $pic_object" prev= continue else # If libtool objects are unsupported, then we need to preload. prev=dlprefiles fi fi # CHECK ME: I think I busted this. -Ossama if test dlprefiles = "$prev"; then # Preload the old-style object. func_append dlprefiles " $pic_object" prev= fi # A PIC object. func_append libobjs " $pic_object" arg=$pic_object fi # Non-PIC object. if test none != "$non_pic_object"; then # Prepend the subdirectory the object is found in. non_pic_object=$xdir$non_pic_object # A standard non-PIC object func_append non_pic_objects " $non_pic_object" if test -z "$pic_object" || test none = "$pic_object"; then arg=$non_pic_object fi else # If the PIC object exists, use it instead. # $xdir was prepended to $pic_object above. non_pic_object=$pic_object func_append non_pic_objects " $non_pic_object" fi else # Only an error if not doing a dry-run. if $opt_dry_run; then # Extract subdirectory from the argument. func_dirname "$arg" "/" "" xdir=$func_dirname_result func_lo2o "$arg" pic_object=$xdir$objdir/$func_lo2o_result non_pic_object=$xdir$func_lo2o_result func_append libobjs " $pic_object" func_append non_pic_objects " $non_pic_object" else func_fatal_error "'$arg' is not a valid libtool object" fi fi done else func_fatal_error "link input file '$arg' does not exist" fi arg=$save_arg prev= continue ;; os2dllname) os2dllname=$arg prev= continue ;; precious_regex) precious_files_regex=$arg prev= continue ;; release) release=-$arg prev= continue ;; rpath | xrpath) # We need an absolute path. case $arg in [\\/]* | [A-Za-z]:[\\/]*) ;; *) func_fatal_error "only absolute run-paths are allowed" ;; esac if test rpath = "$prev"; then case "$rpath " in *" $arg "*) ;; *) func_append rpath " $arg" ;; esac else case "$xrpath " in *" $arg "*) ;; *) func_append xrpath " $arg" ;; esac fi prev= continue ;; shrext) shrext_cmds=$arg prev= continue ;; weak) func_append weak_libs " $arg" prev= continue ;; xcclinker) func_append linker_flags " $qarg" func_append compiler_flags " $qarg" prev= func_append compile_command " $qarg" func_append finalize_command " $qarg" continue ;; xcompiler) func_append compiler_flags " $qarg" prev= func_append compile_command " $qarg" func_append finalize_command " $qarg" continue ;; xlinker) func_append linker_flags " $qarg" func_append compiler_flags " $wl$qarg" prev= func_append compile_command " $wl$qarg" func_append finalize_command " $wl$qarg" continue ;; *) eval "$prev=\"\$arg\"" prev= continue ;; esac fi # test -n "$prev" prevarg=$arg case $arg in -all-static) if test -n "$link_static_flag"; then # See comment for -static flag below, for more details. func_append compile_command " $link_static_flag" func_append finalize_command " $link_static_flag" fi continue ;; -allow-undefined) # FIXME: remove this flag sometime in the future. func_fatal_error "'-allow-undefined' must not be used because it is the default" ;; -avoid-version) avoid_version=yes continue ;; -bindir) prev=bindir continue ;; -dlopen) prev=dlfiles continue ;; -dlpreopen) prev=dlprefiles continue ;; -export-dynamic) export_dynamic=yes continue ;; -export-symbols | -export-symbols-regex) if test -n "$export_symbols" || test -n "$export_symbols_regex"; then func_fatal_error "more than one -exported-symbols argument is not allowed" fi if test X-export-symbols = "X$arg"; then prev=expsyms else prev=expsyms_regex fi continue ;; -framework) prev=framework continue ;; -inst-prefix-dir) prev=inst_prefix continue ;; # The native IRIX linker understands -LANG:*, -LIST:* and -LNO:* # so, if we see these flags be careful not to treat them like -L -L[A-Z][A-Z]*:*) case $with_gcc/$host in no/*-*-irix* | /*-*-irix*) func_append compile_command " $arg" func_append finalize_command " $arg" ;; esac continue ;; -L*) func_stripname "-L" '' "$arg" if test -z "$func_stripname_result"; then if test "$#" -gt 0; then func_fatal_error "require no space between '-L' and '$1'" else func_fatal_error "need path for '-L' option" fi fi func_resolve_sysroot "$func_stripname_result" dir=$func_resolve_sysroot_result # We need an absolute path. case $dir in [\\/]* | [A-Za-z]:[\\/]*) ;; *) absdir=`cd "$dir" && pwd` test -z "$absdir" && \ func_fatal_error "cannot determine absolute directory name of '$dir'" dir=$absdir ;; esac case "$deplibs " in *" -L$dir "* | *" $arg "*) # Will only happen for absolute or sysroot arguments ;; *) # Preserve sysroot, but never include relative directories case $dir in [\\/]* | [A-Za-z]:[\\/]* | =*) func_append deplibs " $arg" ;; *) func_append deplibs " -L$dir" ;; esac func_append lib_search_path " $dir" ;; esac case $host in *-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-os2* | *-cegcc*) testbindir=`$ECHO "$dir" | $SED 's*/lib$*/bin*'` case :$dllsearchpath: in *":$dir:"*) ;; ::) dllsearchpath=$dir;; *) func_append dllsearchpath ":$dir";; esac case :$dllsearchpath: in *":$testbindir:"*) ;; ::) dllsearchpath=$testbindir;; *) func_append dllsearchpath ":$testbindir";; esac ;; esac continue ;; -l*) if test X-lc = "X$arg" || test X-lm = "X$arg"; then case $host in *-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-beos* | *-cegcc* | *-*-haiku*) # These systems don't actually have a C or math library (as such) continue ;; *-*-os2*) # These systems don't actually have a C library (as such) test X-lc = "X$arg" && continue ;; *-*-openbsd* | *-*-freebsd* | *-*-dragonfly* | *-*-bitrig*) # Do not include libc due to us having libc/libc_r. test X-lc = "X$arg" && continue ;; *-*-rhapsody* | *-*-darwin1.[012]) # Rhapsody C and math libraries are in the System framework func_append deplibs " System.ltframework" continue ;; *-*-sco3.2v5* | *-*-sco5v6*) # Causes problems with __ctype test X-lc = "X$arg" && continue ;; *-*-sysv4.2uw2* | *-*-sysv5* | *-*-unixware* | *-*-OpenUNIX*) # Compiler inserts libc in the correct place for threads to work test X-lc = "X$arg" && continue ;; esac elif test X-lc_r = "X$arg"; then case $host in *-*-openbsd* | *-*-freebsd* | *-*-dragonfly* | *-*-bitrig*) # Do not include libc_r directly, use -pthread flag. continue ;; esac fi func_append deplibs " $arg" continue ;; -mllvm) prev=mllvm continue ;; -module) module=yes continue ;; # Tru64 UNIX uses -model [arg] to determine the layout of C++ # classes, name mangling, and exception handling. # Darwin uses the -arch flag to determine output architecture. -model|-arch|-isysroot|--sysroot) func_append compiler_flags " $arg" func_append compile_command " $arg" func_append finalize_command " $arg" prev=xcompiler continue ;; -mt|-mthreads|-kthread|-Kthread|-pthread|-pthreads|--thread-safe \ |-threads|-fopenmp|-openmp|-mp|-xopenmp|-omp|-qsmp=*) func_append compiler_flags " $arg" func_append compile_command " $arg" func_append finalize_command " $arg" case "$new_inherited_linker_flags " in *" $arg "*) ;; * ) func_append new_inherited_linker_flags " $arg" ;; esac continue ;; -multi_module) single_module=$wl-multi_module continue ;; -no-fast-install) fast_install=no continue ;; -no-install) case $host in *-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-os2* | *-*-darwin* | *-cegcc*) # The PATH hackery in wrapper scripts is required on Windows # and Darwin in order for the loader to find any dlls it needs. func_warning "'-no-install' is ignored for $host" func_warning "assuming '-no-fast-install' instead" fast_install=no ;; *) no_install=yes ;; esac continue ;; -no-undefined) allow_undefined=no continue ;; -objectlist) prev=objectlist continue ;; -os2dllname) prev=os2dllname continue ;; -o) prev=output ;; -precious-files-regex) prev=precious_regex continue ;; -release) prev=release continue ;; -rpath) prev=rpath continue ;; -R) prev=xrpath continue ;; -R*) func_stripname '-R' '' "$arg" dir=$func_stripname_result # We need an absolute path. case $dir in [\\/]* | [A-Za-z]:[\\/]*) ;; =*) func_stripname '=' '' "$dir" dir=$lt_sysroot$func_stripname_result ;; *) func_fatal_error "only absolute run-paths are allowed" ;; esac case "$xrpath " in *" $dir "*) ;; *) func_append xrpath " $dir" ;; esac continue ;; -shared) # The effects of -shared are defined in a previous loop. continue ;; -shrext) prev=shrext continue ;; -static | -static-libtool-libs) # The effects of -static are defined in a previous loop. # We used to do the same as -all-static on platforms that # didn't have a PIC flag, but the assumption that the effects # would be equivalent was wrong. It would break on at least # Digital Unix and AIX. continue ;; -thread-safe) thread_safe=yes continue ;; -version-info) prev=vinfo continue ;; -version-number) prev=vinfo vinfo_number=yes continue ;; -weak) prev=weak continue ;; -Wc,*) func_stripname '-Wc,' '' "$arg" args=$func_stripname_result arg= save_ifs=$IFS; IFS=, for flag in $args; do IFS=$save_ifs func_quote_for_eval "$flag" func_append arg " $func_quote_for_eval_result" func_append compiler_flags " $func_quote_for_eval_result" done IFS=$save_ifs func_stripname ' ' '' "$arg" arg=$func_stripname_result ;; -Wl,*) func_stripname '-Wl,' '' "$arg" args=$func_stripname_result arg= save_ifs=$IFS; IFS=, for flag in $args; do IFS=$save_ifs func_quote_for_eval "$flag" func_append arg " $wl$func_quote_for_eval_result" func_append compiler_flags " $wl$func_quote_for_eval_result" func_append linker_flags " $func_quote_for_eval_result" done IFS=$save_ifs func_stripname ' ' '' "$arg" arg=$func_stripname_result ;; -Xcompiler) prev=xcompiler continue ;; -Xlinker) prev=xlinker continue ;; -XCClinker) prev=xcclinker continue ;; # -msg_* for osf cc -msg_*) func_quote_for_eval "$arg" arg=$func_quote_for_eval_result ;; # Flags to be passed through unchanged, with rationale: # -64, -mips[0-9] enable 64-bit mode for the SGI compiler # -r[0-9][0-9]* specify processor for the SGI compiler # -xarch=*, -xtarget=* enable 64-bit mode for the Sun compiler # +DA*, +DD* enable 64-bit mode for the HP compiler # -q* compiler args for the IBM compiler # -m*, -t[45]*, -txscale* architecture-specific flags for GCC # -F/path path to uninstalled frameworks, gcc on darwin # -p, -pg, --coverage, -fprofile-* profiling flags for GCC # -fstack-protector* stack protector flags for GCC # @file GCC response files # -tp=* Portland pgcc target processor selection # --sysroot=* for sysroot support # -O*, -g*, -flto*, -fwhopr*, -fuse-linker-plugin GCC link-time optimization # -stdlib=* select c++ std lib with clang -64|-mips[0-9]|-r[0-9][0-9]*|-xarch=*|-xtarget=*|+DA*|+DD*|-q*|-m*| \ -t[45]*|-txscale*|-p|-pg|--coverage|-fprofile-*|-F*|@*|-tp=*|--sysroot=*| \ -O*|-g*|-flto*|-fwhopr*|-fuse-linker-plugin|-fstack-protector*|-stdlib=*) func_quote_for_eval "$arg" arg=$func_quote_for_eval_result func_append compile_command " $arg" func_append finalize_command " $arg" func_append compiler_flags " $arg" continue ;; -Z*) if test os2 = "`expr $host : '.*\(os2\)'`"; then # OS/2 uses -Zxxx to specify OS/2-specific options compiler_flags="$compiler_flags $arg" func_append compile_command " $arg" func_append finalize_command " $arg" case $arg in -Zlinker | -Zstack) prev=xcompiler ;; esac continue else # Otherwise treat like 'Some other compiler flag' below func_quote_for_eval "$arg" arg=$func_quote_for_eval_result fi ;; # Some other compiler flag. -* | +*) func_quote_for_eval "$arg" arg=$func_quote_for_eval_result ;; *.$objext) # A standard object. func_append objs " $arg" ;; *.lo) # A libtool-controlled object. # Check to see that this really is a libtool object. if func_lalib_unsafe_p "$arg"; then pic_object= non_pic_object= # Read the .lo file func_source "$arg" if test -z "$pic_object" || test -z "$non_pic_object" || test none = "$pic_object" && test none = "$non_pic_object"; then func_fatal_error "cannot find name of object for '$arg'" fi # Extract subdirectory from the argument. func_dirname "$arg" "/" "" xdir=$func_dirname_result test none = "$pic_object" || { # Prepend the subdirectory the object is found in. pic_object=$xdir$pic_object if test dlfiles = "$prev"; then if test yes = "$build_libtool_libs" && test yes = "$dlopen_support"; then func_append dlfiles " $pic_object" prev= continue else # If libtool objects are unsupported, then we need to preload. prev=dlprefiles fi fi # CHECK ME: I think I busted this. -Ossama if test dlprefiles = "$prev"; then # Preload the old-style object. func_append dlprefiles " $pic_object" prev= fi # A PIC object. func_append libobjs " $pic_object" arg=$pic_object } # Non-PIC object. if test none != "$non_pic_object"; then # Prepend the subdirectory the object is found in. non_pic_object=$xdir$non_pic_object # A standard non-PIC object func_append non_pic_objects " $non_pic_object" if test -z "$pic_object" || test none = "$pic_object"; then arg=$non_pic_object fi else # If the PIC object exists, use it instead. # $xdir was prepended to $pic_object above. non_pic_object=$pic_object func_append non_pic_objects " $non_pic_object" fi else # Only an error if not doing a dry-run. if $opt_dry_run; then # Extract subdirectory from the argument. func_dirname "$arg" "/" "" xdir=$func_dirname_result func_lo2o "$arg" pic_object=$xdir$objdir/$func_lo2o_result non_pic_object=$xdir$func_lo2o_result func_append libobjs " $pic_object" func_append non_pic_objects " $non_pic_object" else func_fatal_error "'$arg' is not a valid libtool object" fi fi ;; *.$libext) # An archive. func_append deplibs " $arg" func_append old_deplibs " $arg" continue ;; *.la) # A libtool-controlled library. func_resolve_sysroot "$arg" if test dlfiles = "$prev"; then # This library was specified with -dlopen. func_append dlfiles " $func_resolve_sysroot_result" prev= elif test dlprefiles = "$prev"; then # The library was specified with -dlpreopen. func_append dlprefiles " $func_resolve_sysroot_result" prev= else func_append deplibs " $func_resolve_sysroot_result" fi continue ;; # Some other compiler argument. *) # Unknown arguments in both finalize_command and compile_command need # to be aesthetically quoted because they are evaled later. func_quote_for_eval "$arg" arg=$func_quote_for_eval_result ;; esac # arg # Now actually substitute the argument into the commands. if test -n "$arg"; then func_append compile_command " $arg" func_append finalize_command " $arg" fi done # argument parsing loop test -n "$prev" && \ func_fatal_help "the '$prevarg' option requires an argument" if test yes = "$export_dynamic" && test -n "$export_dynamic_flag_spec"; then eval arg=\"$export_dynamic_flag_spec\" func_append compile_command " $arg" func_append finalize_command " $arg" fi oldlibs= # calculate the name of the file, without its directory func_basename "$output" outputname=$func_basename_result libobjs_save=$libobjs if test -n "$shlibpath_var"; then # get the directories listed in $shlibpath_var eval shlib_search_path=\`\$ECHO \"\$$shlibpath_var\" \| \$SED \'s/:/ /g\'\` else shlib_search_path= fi eval sys_lib_search_path=\"$sys_lib_search_path_spec\" eval sys_lib_dlsearch_path=\"$sys_lib_dlsearch_path_spec\" # Definition is injected by LT_CONFIG during libtool generation. func_munge_path_list sys_lib_dlsearch_path "$LT_SYS_LIBRARY_PATH" func_dirname "$output" "/" "" output_objdir=$func_dirname_result$objdir func_to_tool_file "$output_objdir/" tool_output_objdir=$func_to_tool_file_result # Create the object directory. func_mkdir_p "$output_objdir" # Determine the type of output case $output in "") func_fatal_help "you must specify an output file" ;; *.$libext) linkmode=oldlib ;; *.lo | *.$objext) linkmode=obj ;; *.la) linkmode=lib ;; *) linkmode=prog ;; # Anything else should be a program. esac specialdeplibs= libs= # Find all interdependent deplibs by searching for libraries # that are linked more than once (e.g. -la -lb -la) for deplib in $deplibs; do if $opt_preserve_dup_deps; then case "$libs " in *" $deplib "*) func_append specialdeplibs " $deplib" ;; esac fi func_append libs " $deplib" done if test lib = "$linkmode"; then libs="$predeps $libs $compiler_lib_search_path $postdeps" # Compute libraries that are listed more than once in $predeps # $postdeps and mark them as special (i.e., whose duplicates are # not to be eliminated). pre_post_deps= if $opt_duplicate_compiler_generated_deps; then for pre_post_dep in $predeps $postdeps; do case "$pre_post_deps " in *" $pre_post_dep "*) func_append specialdeplibs " $pre_post_deps" ;; esac func_append pre_post_deps " $pre_post_dep" done fi pre_post_deps= fi deplibs= newdependency_libs= newlib_search_path= need_relink=no # whether we're linking any uninstalled libtool libraries notinst_deplibs= # not-installed libtool libraries notinst_path= # paths that contain not-installed libtool libraries case $linkmode in lib) passes="conv dlpreopen link" for file in $dlfiles $dlprefiles; do case $file in *.la) ;; *) func_fatal_help "libraries can '-dlopen' only libtool libraries: $file" ;; esac done ;; prog) compile_deplibs= finalize_deplibs= alldeplibs=false newdlfiles= newdlprefiles= passes="conv scan dlopen dlpreopen link" ;; *) passes="conv" ;; esac for pass in $passes; do # The preopen pass in lib mode reverses $deplibs; put it back here # so that -L comes before libs that need it for instance... if test lib,link = "$linkmode,$pass"; then ## FIXME: Find the place where the list is rebuilt in the wrong ## order, and fix it there properly tmp_deplibs= for deplib in $deplibs; do tmp_deplibs="$deplib $tmp_deplibs" done deplibs=$tmp_deplibs fi if test lib,link = "$linkmode,$pass" || test prog,scan = "$linkmode,$pass"; then libs=$deplibs deplibs= fi if test prog = "$linkmode"; then case $pass in dlopen) libs=$dlfiles ;; dlpreopen) libs=$dlprefiles ;; link) libs="$deplibs %DEPLIBS% $dependency_libs" ;; esac fi if test lib,dlpreopen = "$linkmode,$pass"; then # Collect and forward deplibs of preopened libtool libs for lib in $dlprefiles; do # Ignore non-libtool-libs dependency_libs= func_resolve_sysroot "$lib" case $lib in *.la) func_source "$func_resolve_sysroot_result" ;; esac # Collect preopened libtool deplibs, except any this library # has declared as weak libs for deplib in $dependency_libs; do func_basename "$deplib" deplib_base=$func_basename_result case " $weak_libs " in *" $deplib_base "*) ;; *) func_append deplibs " $deplib" ;; esac done done libs=$dlprefiles fi if test dlopen = "$pass"; then # Collect dlpreopened libraries save_deplibs=$deplibs deplibs= fi for deplib in $libs; do lib= found=false case $deplib in -mt|-mthreads|-kthread|-Kthread|-pthread|-pthreads|--thread-safe \ |-threads|-fopenmp|-openmp|-mp|-xopenmp|-omp|-qsmp=*) if test prog,link = "$linkmode,$pass"; then compile_deplibs="$deplib $compile_deplibs" finalize_deplibs="$deplib $finalize_deplibs" else func_append compiler_flags " $deplib" if test lib = "$linkmode"; then case "$new_inherited_linker_flags " in *" $deplib "*) ;; * ) func_append new_inherited_linker_flags " $deplib" ;; esac fi fi continue ;; -l*) if test lib != "$linkmode" && test prog != "$linkmode"; then func_warning "'-l' is ignored for archives/objects" continue fi func_stripname '-l' '' "$deplib" name=$func_stripname_result if test lib = "$linkmode"; then searchdirs="$newlib_search_path $lib_search_path $compiler_lib_search_dirs $sys_lib_search_path $shlib_search_path" else searchdirs="$newlib_search_path $lib_search_path $sys_lib_search_path $shlib_search_path" fi for searchdir in $searchdirs; do for search_ext in .la $std_shrext .so .a; do # Search the libtool library lib=$searchdir/lib$name$search_ext if test -f "$lib"; then if test .la = "$search_ext"; then found=: else found=false fi break 2 fi done done if $found; then # deplib is a libtool library # If $allow_libtool_libs_with_static_runtimes && $deplib is a stdlib, # We need to do some special things here, and not later. if test yes = "$allow_libtool_libs_with_static_runtimes"; then case " $predeps $postdeps " in *" $deplib "*) if func_lalib_p "$lib"; then library_names= old_library= func_source "$lib" for l in $old_library $library_names; do ll=$l done if test "X$ll" = "X$old_library"; then # only static version available found=false func_dirname "$lib" "" "." ladir=$func_dirname_result lib=$ladir/$old_library if test prog,link = "$linkmode,$pass"; then compile_deplibs="$deplib $compile_deplibs" finalize_deplibs="$deplib $finalize_deplibs" else deplibs="$deplib $deplibs" test lib = "$linkmode" && newdependency_libs="$deplib $newdependency_libs" fi continue fi fi ;; *) ;; esac fi else # deplib doesn't seem to be a libtool library if test prog,link = "$linkmode,$pass"; then compile_deplibs="$deplib $compile_deplibs" finalize_deplibs="$deplib $finalize_deplibs" else deplibs="$deplib $deplibs" test lib = "$linkmode" && newdependency_libs="$deplib $newdependency_libs" fi continue fi ;; # -l *.ltframework) if test prog,link = "$linkmode,$pass"; then compile_deplibs="$deplib $compile_deplibs" finalize_deplibs="$deplib $finalize_deplibs" else deplibs="$deplib $deplibs" if test lib = "$linkmode"; then case "$new_inherited_linker_flags " in *" $deplib "*) ;; * ) func_append new_inherited_linker_flags " $deplib" ;; esac fi fi continue ;; -L*) case $linkmode in lib) deplibs="$deplib $deplibs" test conv = "$pass" && continue newdependency_libs="$deplib $newdependency_libs" func_stripname '-L' '' "$deplib" func_resolve_sysroot "$func_stripname_result" func_append newlib_search_path " $func_resolve_sysroot_result" ;; prog) if test conv = "$pass"; then deplibs="$deplib $deplibs" continue fi if test scan = "$pass"; then deplibs="$deplib $deplibs" else compile_deplibs="$deplib $compile_deplibs" finalize_deplibs="$deplib $finalize_deplibs" fi func_stripname '-L' '' "$deplib" func_resolve_sysroot "$func_stripname_result" func_append newlib_search_path " $func_resolve_sysroot_result" ;; *) func_warning "'-L' is ignored for archives/objects" ;; esac # linkmode continue ;; # -L -R*) if test link = "$pass"; then func_stripname '-R' '' "$deplib" func_resolve_sysroot "$func_stripname_result" dir=$func_resolve_sysroot_result # Make sure the xrpath contains only unique directories. case "$xrpath " in *" $dir "*) ;; *) func_append xrpath " $dir" ;; esac fi deplibs="$deplib $deplibs" continue ;; *.la) func_resolve_sysroot "$deplib" lib=$func_resolve_sysroot_result ;; *.$libext) if test conv = "$pass"; then deplibs="$deplib $deplibs" continue fi case $linkmode in lib) # Linking convenience modules into shared libraries is allowed, # but linking other static libraries is non-portable. case " $dlpreconveniencelibs " in *" $deplib "*) ;; *) valid_a_lib=false case $deplibs_check_method in match_pattern*) set dummy $deplibs_check_method; shift match_pattern_regex=`expr "$deplibs_check_method" : "$1 \(.*\)"` if eval "\$ECHO \"$deplib\"" 2>/dev/null | $SED 10q \ | $EGREP "$match_pattern_regex" > /dev/null; then valid_a_lib=: fi ;; pass_all) valid_a_lib=: ;; esac if $valid_a_lib; then echo $ECHO "*** Warning: Linking the shared library $output against the" $ECHO "*** static library $deplib is not portable!" deplibs="$deplib $deplibs" else echo $ECHO "*** Warning: Trying to link with static lib archive $deplib." echo "*** I have the capability to make that library automatically link in when" echo "*** you link to this library. But I can only do this if you have a" echo "*** shared version of the library, which you do not appear to have" echo "*** because the file extensions .$libext of this argument makes me believe" echo "*** that it is just a static archive that I should not use here." fi ;; esac continue ;; prog) if test link != "$pass"; then deplibs="$deplib $deplibs" else compile_deplibs="$deplib $compile_deplibs" finalize_deplibs="$deplib $finalize_deplibs" fi continue ;; esac # linkmode ;; # *.$libext *.lo | *.$objext) if test conv = "$pass"; then deplibs="$deplib $deplibs" elif test prog = "$linkmode"; then if test dlpreopen = "$pass" || test yes != "$dlopen_support" || test no = "$build_libtool_libs"; then # If there is no dlopen support or we're linking statically, # we need to preload. func_append newdlprefiles " $deplib" compile_deplibs="$deplib $compile_deplibs" finalize_deplibs="$deplib $finalize_deplibs" else func_append newdlfiles " $deplib" fi fi continue ;; %DEPLIBS%) alldeplibs=: continue ;; esac # case $deplib $found || test -f "$lib" \ || func_fatal_error "cannot find the library '$lib' or unhandled argument '$deplib'" # Check to see that this really is a libtool archive. func_lalib_unsafe_p "$lib" \ || func_fatal_error "'$lib' is not a valid libtool archive" func_dirname "$lib" "" "." ladir=$func_dirname_result dlname= dlopen= dlpreopen= libdir= library_names= old_library= inherited_linker_flags= # If the library was installed with an old release of libtool, # it will not redefine variables installed, or shouldnotlink installed=yes shouldnotlink=no avoidtemprpath= # Read the .la file func_source "$lib" # Convert "-framework foo" to "foo.ltframework" if test -n "$inherited_linker_flags"; then tmp_inherited_linker_flags=`$ECHO "$inherited_linker_flags" | $SED 's/-framework \([^ $]*\)/\1.ltframework/g'` for tmp_inherited_linker_flag in $tmp_inherited_linker_flags; do case " $new_inherited_linker_flags " in *" $tmp_inherited_linker_flag "*) ;; *) func_append new_inherited_linker_flags " $tmp_inherited_linker_flag";; esac done fi dependency_libs=`$ECHO " $dependency_libs" | $SED 's% \([^ $]*\).ltframework% -framework \1%g'` if test lib,link = "$linkmode,$pass" || test prog,scan = "$linkmode,$pass" || { test prog != "$linkmode" && test lib != "$linkmode"; }; then test -n "$dlopen" && func_append dlfiles " $dlopen" test -n "$dlpreopen" && func_append dlprefiles " $dlpreopen" fi if test conv = "$pass"; then # Only check for convenience libraries deplibs="$lib $deplibs" if test -z "$libdir"; then if test -z "$old_library"; then func_fatal_error "cannot find name of link library for '$lib'" fi # It is a libtool convenience library, so add in its objects. func_append convenience " $ladir/$objdir/$old_library" func_append old_convenience " $ladir/$objdir/$old_library" elif test prog != "$linkmode" && test lib != "$linkmode"; then func_fatal_error "'$lib' is not a convenience library" fi tmp_libs= for deplib in $dependency_libs; do deplibs="$deplib $deplibs" if $opt_preserve_dup_deps; then case "$tmp_libs " in *" $deplib "*) func_append specialdeplibs " $deplib" ;; esac fi func_append tmp_libs " $deplib" done continue fi # $pass = conv # Get the name of the library we link against. linklib= if test -n "$old_library" && { test yes = "$prefer_static_libs" || test built,no = "$prefer_static_libs,$installed"; }; then linklib=$old_library else for l in $old_library $library_names; do linklib=$l done fi if test -z "$linklib"; then func_fatal_error "cannot find name of link library for '$lib'" fi # This library was specified with -dlopen. if test dlopen = "$pass"; then test -z "$libdir" \ && func_fatal_error "cannot -dlopen a convenience library: '$lib'" if test -z "$dlname" || test yes != "$dlopen_support" || test no = "$build_libtool_libs" then # If there is no dlname, no dlopen support or we're linking # statically, we need to preload. We also need to preload any # dependent libraries so libltdl's deplib preloader doesn't # bomb out in the load deplibs phase. func_append dlprefiles " $lib $dependency_libs" else func_append newdlfiles " $lib" fi continue fi # $pass = dlopen # We need an absolute path. case $ladir in [\\/]* | [A-Za-z]:[\\/]*) abs_ladir=$ladir ;; *) abs_ladir=`cd "$ladir" && pwd` if test -z "$abs_ladir"; then func_warning "cannot determine absolute directory name of '$ladir'" func_warning "passing it literally to the linker, although it might fail" abs_ladir=$ladir fi ;; esac func_basename "$lib" laname=$func_basename_result # Find the relevant object directory and library name. if test yes = "$installed"; then if test ! -f "$lt_sysroot$libdir/$linklib" && test -f "$abs_ladir/$linklib"; then func_warning "library '$lib' was moved." dir=$ladir absdir=$abs_ladir libdir=$abs_ladir else dir=$lt_sysroot$libdir absdir=$lt_sysroot$libdir fi test yes = "$hardcode_automatic" && avoidtemprpath=yes else if test ! -f "$ladir/$objdir/$linklib" && test -f "$abs_ladir/$linklib"; then dir=$ladir absdir=$abs_ladir # Remove this search path later func_append notinst_path " $abs_ladir" else dir=$ladir/$objdir absdir=$abs_ladir/$objdir # Remove this search path later func_append notinst_path " $abs_ladir" fi fi # $installed = yes func_stripname 'lib' '.la' "$laname" name=$func_stripname_result # This library was specified with -dlpreopen. if test dlpreopen = "$pass"; then if test -z "$libdir" && test prog = "$linkmode"; then func_fatal_error "only libraries may -dlpreopen a convenience library: '$lib'" fi case $host in # special handling for platforms with PE-DLLs. *cygwin* | *mingw* | *cegcc* ) # Linker will automatically link against shared library if both # static and shared are present. Therefore, ensure we extract # symbols from the import library if a shared library is present # (otherwise, the dlopen module name will be incorrect). We do # this by putting the import library name into $newdlprefiles. # We recover the dlopen module name by 'saving' the la file # name in a special purpose variable, and (later) extracting the # dlname from the la file. if test -n "$dlname"; then func_tr_sh "$dir/$linklib" eval "libfile_$func_tr_sh_result=\$abs_ladir/\$laname" func_append newdlprefiles " $dir/$linklib" else func_append newdlprefiles " $dir/$old_library" # Keep a list of preopened convenience libraries to check # that they are being used correctly in the link pass. test -z "$libdir" && \ func_append dlpreconveniencelibs " $dir/$old_library" fi ;; * ) # Prefer using a static library (so that no silly _DYNAMIC symbols # are required to link). if test -n "$old_library"; then func_append newdlprefiles " $dir/$old_library" # Keep a list of preopened convenience libraries to check # that they are being used correctly in the link pass. test -z "$libdir" && \ func_append dlpreconveniencelibs " $dir/$old_library" # Otherwise, use the dlname, so that lt_dlopen finds it. elif test -n "$dlname"; then func_append newdlprefiles " $dir/$dlname" else func_append newdlprefiles " $dir/$linklib" fi ;; esac fi # $pass = dlpreopen if test -z "$libdir"; then # Link the convenience library if test lib = "$linkmode"; then deplibs="$dir/$old_library $deplibs" elif test prog,link = "$linkmode,$pass"; then compile_deplibs="$dir/$old_library $compile_deplibs" finalize_deplibs="$dir/$old_library $finalize_deplibs" else deplibs="$lib $deplibs" # used for prog,scan pass fi continue fi if test prog = "$linkmode" && test link != "$pass"; then func_append newlib_search_path " $ladir" deplibs="$lib $deplibs" linkalldeplibs=false if test no != "$link_all_deplibs" || test -z "$library_names" || test no = "$build_libtool_libs"; then linkalldeplibs=: fi tmp_libs= for deplib in $dependency_libs; do case $deplib in -L*) func_stripname '-L' '' "$deplib" func_resolve_sysroot "$func_stripname_result" func_append newlib_search_path " $func_resolve_sysroot_result" ;; esac # Need to link against all dependency_libs? if $linkalldeplibs; then deplibs="$deplib $deplibs" else # Need to hardcode shared library paths # or/and link against static libraries newdependency_libs="$deplib $newdependency_libs" fi if $opt_preserve_dup_deps; then case "$tmp_libs " in *" $deplib "*) func_append specialdeplibs " $deplib" ;; esac fi func_append tmp_libs " $deplib" done # for deplib continue fi # $linkmode = prog... if test prog,link = "$linkmode,$pass"; then if test -n "$library_names" && { { test no = "$prefer_static_libs" || test built,yes = "$prefer_static_libs,$installed"; } || test -z "$old_library"; }; then # We need to hardcode the library path if test -n "$shlibpath_var" && test -z "$avoidtemprpath"; then # Make sure the rpath contains only unique directories. case $temp_rpath: in *"$absdir:"*) ;; *) func_append temp_rpath "$absdir:" ;; esac fi # Hardcode the library path. # Skip directories that are in the system default run-time # search path. case " $sys_lib_dlsearch_path " in *" $absdir "*) ;; *) case "$compile_rpath " in *" $absdir "*) ;; *) func_append compile_rpath " $absdir" ;; esac ;; esac case " $sys_lib_dlsearch_path " in *" $libdir "*) ;; *) case "$finalize_rpath " in *" $libdir "*) ;; *) func_append finalize_rpath " $libdir" ;; esac ;; esac fi # $linkmode,$pass = prog,link... if $alldeplibs && { test pass_all = "$deplibs_check_method" || { test yes = "$build_libtool_libs" && test -n "$library_names"; }; }; then # We only need to search for static libraries continue fi fi link_static=no # Whether the deplib will be linked statically use_static_libs=$prefer_static_libs if test built = "$use_static_libs" && test yes = "$installed"; then use_static_libs=no fi if test -n "$library_names" && { test no = "$use_static_libs" || test -z "$old_library"; }; then case $host in *cygwin* | *mingw* | *cegcc* | *os2*) # No point in relinking DLLs because paths are not encoded func_append notinst_deplibs " $lib" need_relink=no ;; *) if test no = "$installed"; then func_append notinst_deplibs " $lib" need_relink=yes fi ;; esac # This is a shared library # Warn about portability, can't link against -module's on some # systems (darwin). Don't bleat about dlopened modules though! dlopenmodule= for dlpremoduletest in $dlprefiles; do if test "X$dlpremoduletest" = "X$lib"; then dlopenmodule=$dlpremoduletest break fi done if test -z "$dlopenmodule" && test yes = "$shouldnotlink" && test link = "$pass"; then echo if test prog = "$linkmode"; then $ECHO "*** Warning: Linking the executable $output against the loadable module" else $ECHO "*** Warning: Linking the shared library $output against the loadable module" fi $ECHO "*** $linklib is not portable!" fi if test lib = "$linkmode" && test yes = "$hardcode_into_libs"; then # Hardcode the library path. # Skip directories that are in the system default run-time # search path. case " $sys_lib_dlsearch_path " in *" $absdir "*) ;; *) case "$compile_rpath " in *" $absdir "*) ;; *) func_append compile_rpath " $absdir" ;; esac ;; esac case " $sys_lib_dlsearch_path " in *" $libdir "*) ;; *) case "$finalize_rpath " in *" $libdir "*) ;; *) func_append finalize_rpath " $libdir" ;; esac ;; esac fi if test -n "$old_archive_from_expsyms_cmds"; then # figure out the soname set dummy $library_names shift realname=$1 shift libname=`eval "\\$ECHO \"$libname_spec\""` # use dlname if we got it. it's perfectly good, no? if test -n "$dlname"; then soname=$dlname elif test -n "$soname_spec"; then # bleh windows case $host in *cygwin* | mingw* | *cegcc* | *os2*) func_arith $current - $age major=$func_arith_result versuffix=-$major ;; esac eval soname=\"$soname_spec\" else soname=$realname fi # Make a new name for the extract_expsyms_cmds to use soroot=$soname func_basename "$soroot" soname=$func_basename_result func_stripname 'lib' '.dll' "$soname" newlib=libimp-$func_stripname_result.a # If the library has no export list, then create one now if test -f "$output_objdir/$soname-def"; then : else func_verbose "extracting exported symbol list from '$soname'" func_execute_cmds "$extract_expsyms_cmds" 'exit $?' fi # Create $newlib if test -f "$output_objdir/$newlib"; then :; else func_verbose "generating import library for '$soname'" func_execute_cmds "$old_archive_from_expsyms_cmds" 'exit $?' fi # make sure the library variables are pointing to the new library dir=$output_objdir linklib=$newlib fi # test -n "$old_archive_from_expsyms_cmds" if test prog = "$linkmode" || test relink != "$opt_mode"; then add_shlibpath= add_dir= add= lib_linked=yes case $hardcode_action in immediate | unsupported) if test no = "$hardcode_direct"; then add=$dir/$linklib case $host in *-*-sco3.2v5.0.[024]*) add_dir=-L$dir ;; *-*-sysv4*uw2*) add_dir=-L$dir ;; *-*-sysv5OpenUNIX* | *-*-sysv5UnixWare7.[01].[10]* | \ *-*-unixware7*) add_dir=-L$dir ;; *-*-darwin* ) # if the lib is a (non-dlopened) module then we cannot # link against it, someone is ignoring the earlier warnings if /usr/bin/file -L $add 2> /dev/null | $GREP ": [^:]* bundle" >/dev/null; then if test "X$dlopenmodule" != "X$lib"; then $ECHO "*** Warning: lib $linklib is a module, not a shared library" if test -z "$old_library"; then echo echo "*** And there doesn't seem to be a static archive available" echo "*** The link will probably fail, sorry" else add=$dir/$old_library fi elif test -n "$old_library"; then add=$dir/$old_library fi fi esac elif test no = "$hardcode_minus_L"; then case $host in *-*-sunos*) add_shlibpath=$dir ;; esac add_dir=-L$dir add=-l$name elif test no = "$hardcode_shlibpath_var"; then add_shlibpath=$dir add=-l$name else lib_linked=no fi ;; relink) if test yes = "$hardcode_direct" && test no = "$hardcode_direct_absolute"; then add=$dir/$linklib elif test yes = "$hardcode_minus_L"; then add_dir=-L$absdir # Try looking first in the location we're being installed to. if test -n "$inst_prefix_dir"; then case $libdir in [\\/]*) func_append add_dir " -L$inst_prefix_dir$libdir" ;; esac fi add=-l$name elif test yes = "$hardcode_shlibpath_var"; then add_shlibpath=$dir add=-l$name else lib_linked=no fi ;; *) lib_linked=no ;; esac if test yes != "$lib_linked"; then func_fatal_configuration "unsupported hardcode properties" fi if test -n "$add_shlibpath"; then case :$compile_shlibpath: in *":$add_shlibpath:"*) ;; *) func_append compile_shlibpath "$add_shlibpath:" ;; esac fi if test prog = "$linkmode"; then test -n "$add_dir" && compile_deplibs="$add_dir $compile_deplibs" test -n "$add" && compile_deplibs="$add $compile_deplibs" else test -n "$add_dir" && deplibs="$add_dir $deplibs" test -n "$add" && deplibs="$add $deplibs" if test yes != "$hardcode_direct" && test yes != "$hardcode_minus_L" && test yes = "$hardcode_shlibpath_var"; then case :$finalize_shlibpath: in *":$libdir:"*) ;; *) func_append finalize_shlibpath "$libdir:" ;; esac fi fi fi if test prog = "$linkmode" || test relink = "$opt_mode"; then add_shlibpath= add_dir= add= # Finalize command for both is simple: just hardcode it. if test yes = "$hardcode_direct" && test no = "$hardcode_direct_absolute"; then add=$libdir/$linklib elif test yes = "$hardcode_minus_L"; then add_dir=-L$libdir add=-l$name elif test yes = "$hardcode_shlibpath_var"; then case :$finalize_shlibpath: in *":$libdir:"*) ;; *) func_append finalize_shlibpath "$libdir:" ;; esac add=-l$name elif test yes = "$hardcode_automatic"; then if test -n "$inst_prefix_dir" && test -f "$inst_prefix_dir$libdir/$linklib"; then add=$inst_prefix_dir$libdir/$linklib else add=$libdir/$linklib fi else # We cannot seem to hardcode it, guess we'll fake it. add_dir=-L$libdir # Try looking first in the location we're being installed to. if test -n "$inst_prefix_dir"; then case $libdir in [\\/]*) func_append add_dir " -L$inst_prefix_dir$libdir" ;; esac fi add=-l$name fi if test prog = "$linkmode"; then test -n "$add_dir" && finalize_deplibs="$add_dir $finalize_deplibs" test -n "$add" && finalize_deplibs="$add $finalize_deplibs" else test -n "$add_dir" && deplibs="$add_dir $deplibs" test -n "$add" && deplibs="$add $deplibs" fi fi elif test prog = "$linkmode"; then # Here we assume that one of hardcode_direct or hardcode_minus_L # is not unsupported. This is valid on all known static and # shared platforms. if test unsupported != "$hardcode_direct"; then test -n "$old_library" && linklib=$old_library compile_deplibs="$dir/$linklib $compile_deplibs" finalize_deplibs="$dir/$linklib $finalize_deplibs" else compile_deplibs="-l$name -L$dir $compile_deplibs" finalize_deplibs="-l$name -L$dir $finalize_deplibs" fi elif test yes = "$build_libtool_libs"; then # Not a shared library if test pass_all != "$deplibs_check_method"; then # We're trying link a shared library against a static one # but the system doesn't support it. # Just print a warning and add the library to dependency_libs so # that the program can be linked against the static library. echo $ECHO "*** Warning: This system cannot link to static lib archive $lib." echo "*** I have the capability to make that library automatically link in when" echo "*** you link to this library. But I can only do this if you have a" echo "*** shared version of the library, which you do not appear to have." if test yes = "$module"; then echo "*** But as you try to build a module library, libtool will still create " echo "*** a static module, that should work as long as the dlopening application" echo "*** is linked with the -dlopen flag to resolve symbols at runtime." if test -z "$global_symbol_pipe"; then echo echo "*** However, this would only work if libtool was able to extract symbol" echo "*** lists from a program, using 'nm' or equivalent, but libtool could" echo "*** not find such a program. So, this module is probably useless." echo "*** 'nm' from GNU binutils and a full rebuild may help." fi if test no = "$build_old_libs"; then build_libtool_libs=module build_old_libs=yes else build_libtool_libs=no fi fi else deplibs="$dir/$old_library $deplibs" link_static=yes fi fi # link shared/static library? if test lib = "$linkmode"; then if test -n "$dependency_libs" && { test yes != "$hardcode_into_libs" || test yes = "$build_old_libs" || test yes = "$link_static"; }; then # Extract -R from dependency_libs temp_deplibs= for libdir in $dependency_libs; do case $libdir in -R*) func_stripname '-R' '' "$libdir" temp_xrpath=$func_stripname_result case " $xrpath " in *" $temp_xrpath "*) ;; *) func_append xrpath " $temp_xrpath";; esac;; *) func_append temp_deplibs " $libdir";; esac done dependency_libs=$temp_deplibs fi func_append newlib_search_path " $absdir" # Link against this library test no = "$link_static" && newdependency_libs="$abs_ladir/$laname $newdependency_libs" # ... and its dependency_libs tmp_libs= for deplib in $dependency_libs; do newdependency_libs="$deplib $newdependency_libs" case $deplib in -L*) func_stripname '-L' '' "$deplib" func_resolve_sysroot "$func_stripname_result";; *) func_resolve_sysroot "$deplib" ;; esac if $opt_preserve_dup_deps; then case "$tmp_libs " in *" $func_resolve_sysroot_result "*) func_append specialdeplibs " $func_resolve_sysroot_result" ;; esac fi func_append tmp_libs " $func_resolve_sysroot_result" done if test no != "$link_all_deplibs"; then # Add the search paths of all dependency libraries for deplib in $dependency_libs; do path= case $deplib in -L*) path=$deplib ;; *.la) func_resolve_sysroot "$deplib" deplib=$func_resolve_sysroot_result func_dirname "$deplib" "" "." dir=$func_dirname_result # We need an absolute path. case $dir in [\\/]* | [A-Za-z]:[\\/]*) absdir=$dir ;; *) absdir=`cd "$dir" && pwd` if test -z "$absdir"; then func_warning "cannot determine absolute directory name of '$dir'" absdir=$dir fi ;; esac if $GREP "^installed=no" $deplib > /dev/null; then case $host in *-*-darwin*) depdepl= eval deplibrary_names=`$SED -n -e 's/^library_names=\(.*\)$/\1/p' $deplib` if test -n "$deplibrary_names"; then for tmp in $deplibrary_names; do depdepl=$tmp done if test -f "$absdir/$objdir/$depdepl"; then depdepl=$absdir/$objdir/$depdepl darwin_install_name=`$OTOOL -L $depdepl | awk '{if (NR == 2) {print $1;exit}}'` if test -z "$darwin_install_name"; then darwin_install_name=`$OTOOL64 -L $depdepl | awk '{if (NR == 2) {print $1;exit}}'` fi func_append compiler_flags " $wl-dylib_file $wl$darwin_install_name:$depdepl" func_append linker_flags " -dylib_file $darwin_install_name:$depdepl" path= fi fi ;; *) path=-L$absdir/$objdir ;; esac else eval libdir=`$SED -n -e 's/^libdir=\(.*\)$/\1/p' $deplib` test -z "$libdir" && \ func_fatal_error "'$deplib' is not a valid libtool archive" test "$absdir" != "$libdir" && \ func_warning "'$deplib' seems to be moved" path=-L$absdir fi ;; esac case " $deplibs " in *" $path "*) ;; *) deplibs="$path $deplibs" ;; esac done fi # link_all_deplibs != no fi # linkmode = lib done # for deplib in $libs if test link = "$pass"; then if test prog = "$linkmode"; then compile_deplibs="$new_inherited_linker_flags $compile_deplibs" finalize_deplibs="$new_inherited_linker_flags $finalize_deplibs" else compiler_flags="$compiler_flags "`$ECHO " $new_inherited_linker_flags" | $SED 's% \([^ $]*\).ltframework% -framework \1%g'` fi fi dependency_libs=$newdependency_libs if test dlpreopen = "$pass"; then # Link the dlpreopened libraries before other libraries for deplib in $save_deplibs; do deplibs="$deplib $deplibs" done fi if test dlopen != "$pass"; then test conv = "$pass" || { # Make sure lib_search_path contains only unique directories. lib_search_path= for dir in $newlib_search_path; do case "$lib_search_path " in *" $dir "*) ;; *) func_append lib_search_path " $dir" ;; esac done newlib_search_path= } if test prog,link = "$linkmode,$pass"; then vars="compile_deplibs finalize_deplibs" else vars=deplibs fi for var in $vars dependency_libs; do # Add libraries to $var in reverse order eval tmp_libs=\"\$$var\" new_libs= for deplib in $tmp_libs; do # FIXME: Pedantically, this is the right thing to do, so # that some nasty dependency loop isn't accidentally # broken: #new_libs="$deplib $new_libs" # Pragmatically, this seems to cause very few problems in # practice: case $deplib in -L*) new_libs="$deplib $new_libs" ;; -R*) ;; *) # And here is the reason: when a library appears more # than once as an explicit dependence of a library, or # is implicitly linked in more than once by the # compiler, it is considered special, and multiple # occurrences thereof are not removed. Compare this # with having the same library being listed as a # dependency of multiple other libraries: in this case, # we know (pedantically, we assume) the library does not # need to be listed more than once, so we keep only the # last copy. This is not always right, but it is rare # enough that we require users that really mean to play # such unportable linking tricks to link the library # using -Wl,-lname, so that libtool does not consider it # for duplicate removal. case " $specialdeplibs " in *" $deplib "*) new_libs="$deplib $new_libs" ;; *) case " $new_libs " in *" $deplib "*) ;; *) new_libs="$deplib $new_libs" ;; esac ;; esac ;; esac done tmp_libs= for deplib in $new_libs; do case $deplib in -L*) case " $tmp_libs " in *" $deplib "*) ;; *) func_append tmp_libs " $deplib" ;; esac ;; *) func_append tmp_libs " $deplib" ;; esac done eval $var=\"$tmp_libs\" done # for var fi # Add Sun CC postdeps if required: test CXX = "$tagname" && { case $host_os in linux*) case `$CC -V 2>&1 | sed 5q` in *Sun\ C*) # Sun C++ 5.9 func_suncc_cstd_abi if test no != "$suncc_use_cstd_abi"; then func_append postdeps ' -library=Cstd -library=Crun' fi ;; esac ;; solaris*) func_cc_basename "$CC" case $func_cc_basename_result in CC* | sunCC*) func_suncc_cstd_abi if test no != "$suncc_use_cstd_abi"; then func_append postdeps ' -library=Cstd -library=Crun' fi ;; esac ;; esac } # Last step: remove runtime libs from dependency_libs # (they stay in deplibs) tmp_libs= for i in $dependency_libs; do case " $predeps $postdeps $compiler_lib_search_path " in *" $i "*) i= ;; esac if test -n "$i"; then func_append tmp_libs " $i" fi done dependency_libs=$tmp_libs done # for pass if test prog = "$linkmode"; then dlfiles=$newdlfiles fi if test prog = "$linkmode" || test lib = "$linkmode"; then dlprefiles=$newdlprefiles fi case $linkmode in oldlib) if test -n "$dlfiles$dlprefiles" || test no != "$dlself"; then func_warning "'-dlopen' is ignored for archives" fi case " $deplibs" in *\ -l* | *\ -L*) func_warning "'-l' and '-L' are ignored for archives" ;; esac test -n "$rpath" && \ func_warning "'-rpath' is ignored for archives" test -n "$xrpath" && \ func_warning "'-R' is ignored for archives" test -n "$vinfo" && \ func_warning "'-version-info/-version-number' is ignored for archives" test -n "$release" && \ func_warning "'-release' is ignored for archives" test -n "$export_symbols$export_symbols_regex" && \ func_warning "'-export-symbols' is ignored for archives" # Now set the variables for building old libraries. build_libtool_libs=no oldlibs=$output func_append objs "$old_deplibs" ;; lib) # Make sure we only generate libraries of the form 'libNAME.la'. case $outputname in lib*) func_stripname 'lib' '.la' "$outputname" name=$func_stripname_result eval shared_ext=\"$shrext_cmds\" eval libname=\"$libname_spec\" ;; *) test no = "$module" \ && func_fatal_help "libtool library '$output' must begin with 'lib'" if test no != "$need_lib_prefix"; then # Add the "lib" prefix for modules if required func_stripname '' '.la' "$outputname" name=$func_stripname_result eval shared_ext=\"$shrext_cmds\" eval libname=\"$libname_spec\" else func_stripname '' '.la' "$outputname" libname=$func_stripname_result fi ;; esac if test -n "$objs"; then if test pass_all != "$deplibs_check_method"; then func_fatal_error "cannot build libtool library '$output' from non-libtool objects on this host:$objs" else echo $ECHO "*** Warning: Linking the shared library $output against the non-libtool" $ECHO "*** objects $objs is not portable!" func_append libobjs " $objs" fi fi test no = "$dlself" \ || func_warning "'-dlopen self' is ignored for libtool libraries" set dummy $rpath shift test 1 -lt "$#" \ && func_warning "ignoring multiple '-rpath's for a libtool library" install_libdir=$1 oldlibs= if test -z "$rpath"; then if test yes = "$build_libtool_libs"; then # Building a libtool convenience library. # Some compilers have problems with a '.al' extension so # convenience libraries should have the same extension an # archive normally would. oldlibs="$output_objdir/$libname.$libext $oldlibs" build_libtool_libs=convenience build_old_libs=yes fi test -n "$vinfo" && \ func_warning "'-version-info/-version-number' is ignored for convenience libraries" test -n "$release" && \ func_warning "'-release' is ignored for convenience libraries" else # Parse the version information argument. save_ifs=$IFS; IFS=: set dummy $vinfo 0 0 0 shift IFS=$save_ifs test -n "$7" && \ func_fatal_help "too many parameters to '-version-info'" # convert absolute version numbers to libtool ages # this retains compatibility with .la files and attempts # to make the code below a bit more comprehensible case $vinfo_number in yes) number_major=$1 number_minor=$2 number_revision=$3 # # There are really only two kinds -- those that # use the current revision as the major version # and those that subtract age and use age as # a minor version. But, then there is irix # that has an extra 1 added just for fun # case $version_type in # correct linux to gnu/linux during the next big refactor darwin|freebsd-elf|linux|osf|windows|none) func_arith $number_major + $number_minor current=$func_arith_result age=$number_minor revision=$number_revision ;; freebsd-aout|qnx|sunos) current=$number_major revision=$number_minor age=0 ;; irix|nonstopux) func_arith $number_major + $number_minor current=$func_arith_result age=$number_minor revision=$number_minor lt_irix_increment=no ;; esac ;; no) current=$1 revision=$2 age=$3 ;; esac # Check that each of the things are valid numbers. case $current in 0|[1-9]|[1-9][0-9]|[1-9][0-9][0-9]|[1-9][0-9][0-9][0-9]|[1-9][0-9][0-9][0-9][0-9]) ;; *) func_error "CURRENT '$current' must be a nonnegative integer" func_fatal_error "'$vinfo' is not valid version information" ;; esac case $revision in 0|[1-9]|[1-9][0-9]|[1-9][0-9][0-9]|[1-9][0-9][0-9][0-9]|[1-9][0-9][0-9][0-9][0-9]) ;; *) func_error "REVISION '$revision' must be a nonnegative integer" func_fatal_error "'$vinfo' is not valid version information" ;; esac case $age in 0|[1-9]|[1-9][0-9]|[1-9][0-9][0-9]|[1-9][0-9][0-9][0-9]|[1-9][0-9][0-9][0-9][0-9]) ;; *) func_error "AGE '$age' must be a nonnegative integer" func_fatal_error "'$vinfo' is not valid version information" ;; esac if test "$age" -gt "$current"; then func_error "AGE '$age' is greater than the current interface number '$current'" func_fatal_error "'$vinfo' is not valid version information" fi # Calculate the version variables. major= versuffix= verstring= case $version_type in none) ;; darwin) # Like Linux, but with the current version available in # verstring for coding it into the library header func_arith $current - $age major=.$func_arith_result versuffix=$major.$age.$revision # Darwin ld doesn't like 0 for these options... func_arith $current + 1 minor_current=$func_arith_result xlcverstring="$wl-compatibility_version $wl$minor_current $wl-current_version $wl$minor_current.$revision" verstring="-compatibility_version $minor_current -current_version $minor_current.$revision" # On Darwin other compilers case $CC in nagfor*) verstring="$wl-compatibility_version $wl$minor_current $wl-current_version $wl$minor_current.$revision" ;; *) verstring="-compatibility_version $minor_current -current_version $minor_current.$revision" ;; esac ;; freebsd-aout) major=.$current versuffix=.$current.$revision ;; freebsd-elf) func_arith $current - $age major=.$func_arith_result versuffix=$major.$age.$revision ;; irix | nonstopux) if test no = "$lt_irix_increment"; then func_arith $current - $age else func_arith $current - $age + 1 fi major=$func_arith_result case $version_type in nonstopux) verstring_prefix=nonstopux ;; *) verstring_prefix=sgi ;; esac verstring=$verstring_prefix$major.$revision # Add in all the interfaces that we are compatible with. loop=$revision while test 0 -ne "$loop"; do func_arith $revision - $loop iface=$func_arith_result func_arith $loop - 1 loop=$func_arith_result verstring=$verstring_prefix$major.$iface:$verstring done # Before this point, $major must not contain '.'. major=.$major versuffix=$major.$revision ;; linux) # correct to gnu/linux during the next big refactor func_arith $current - $age major=.$func_arith_result versuffix=$major.$age.$revision ;; osf) func_arith $current - $age major=.$func_arith_result versuffix=.$current.$age.$revision verstring=$current.$age.$revision # Add in all the interfaces that we are compatible with. loop=$age while test 0 -ne "$loop"; do func_arith $current - $loop iface=$func_arith_result func_arith $loop - 1 loop=$func_arith_result verstring=$verstring:$iface.0 done # Make executables depend on our current version. func_append verstring ":$current.0" ;; qnx) major=.$current versuffix=.$current ;; sco) major=.$current versuffix=.$current ;; sunos) major=.$current versuffix=.$current.$revision ;; windows) # Use '-' rather than '.', since we only want one # extension on DOS 8.3 file systems. func_arith $current - $age major=$func_arith_result versuffix=-$major ;; *) func_fatal_configuration "unknown library version type '$version_type'" ;; esac # Clear the version info if we defaulted, and they specified a release. if test -z "$vinfo" && test -n "$release"; then major= case $version_type in darwin) # we can't check for "0.0" in archive_cmds due to quoting # problems, so we reset it completely verstring= ;; *) verstring=0.0 ;; esac if test no = "$need_version"; then versuffix= else versuffix=.0.0 fi fi # Remove version info from name if versioning should be avoided if test yes,no = "$avoid_version,$need_version"; then major= versuffix= verstring= fi # Check to see if the archive will have undefined symbols. if test yes = "$allow_undefined"; then if test unsupported = "$allow_undefined_flag"; then if test yes = "$build_old_libs"; then func_warning "undefined symbols not allowed in $host shared libraries; building static only" build_libtool_libs=no else func_fatal_error "can't build $host shared library unless -no-undefined is specified" fi fi else # Don't allow undefined symbols. allow_undefined_flag=$no_undefined_flag fi fi func_generate_dlsyms "$libname" "$libname" : func_append libobjs " $symfileobj" test " " = "$libobjs" && libobjs= if test relink != "$opt_mode"; then # Remove our outputs, but don't remove object files since they # may have been created when compiling PIC objects. removelist= tempremovelist=`$ECHO "$output_objdir/*"` for p in $tempremovelist; do case $p in *.$objext | *.gcno) ;; $output_objdir/$outputname | $output_objdir/$libname.* | $output_objdir/$libname$release.*) if test -n "$precious_files_regex"; then if $ECHO "$p" | $EGREP -e "$precious_files_regex" >/dev/null 2>&1 then continue fi fi func_append removelist " $p" ;; *) ;; esac done test -n "$removelist" && \ func_show_eval "${RM}r \$removelist" fi # Now set the variables for building old libraries. if test yes = "$build_old_libs" && test convenience != "$build_libtool_libs"; then func_append oldlibs " $output_objdir/$libname.$libext" # Transform .lo files to .o files. oldobjs="$objs "`$ECHO "$libobjs" | $SP2NL | $SED "/\.$libext$/d; $lo2o" | $NL2SP` fi # Eliminate all temporary directories. #for path in $notinst_path; do # lib_search_path=`$ECHO "$lib_search_path " | $SED "s% $path % %g"` # deplibs=`$ECHO "$deplibs " | $SED "s% -L$path % %g"` # dependency_libs=`$ECHO "$dependency_libs " | $SED "s% -L$path % %g"` #done if test -n "$xrpath"; then # If the user specified any rpath flags, then add them. temp_xrpath= for libdir in $xrpath; do func_replace_sysroot "$libdir" func_append temp_xrpath " -R$func_replace_sysroot_result" case "$finalize_rpath " in *" $libdir "*) ;; *) func_append finalize_rpath " $libdir" ;; esac done if test yes != "$hardcode_into_libs" || test yes = "$build_old_libs"; then dependency_libs="$temp_xrpath $dependency_libs" fi fi # Make sure dlfiles contains only unique files that won't be dlpreopened old_dlfiles=$dlfiles dlfiles= for lib in $old_dlfiles; do case " $dlprefiles $dlfiles " in *" $lib "*) ;; *) func_append dlfiles " $lib" ;; esac done # Make sure dlprefiles contains only unique files old_dlprefiles=$dlprefiles dlprefiles= for lib in $old_dlprefiles; do case "$dlprefiles " in *" $lib "*) ;; *) func_append dlprefiles " $lib" ;; esac done if test yes = "$build_libtool_libs"; then if test -n "$rpath"; then case $host in *-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-os2* | *-*-beos* | *-cegcc* | *-*-haiku*) # these systems don't actually have a c library (as such)! ;; *-*-rhapsody* | *-*-darwin1.[012]) # Rhapsody C library is in the System framework func_append deplibs " System.ltframework" ;; *-*-netbsd*) # Don't link with libc until the a.out ld.so is fixed. ;; *-*-openbsd* | *-*-freebsd* | *-*-dragonfly*) # Do not include libc due to us having libc/libc_r. ;; *-*-sco3.2v5* | *-*-sco5v6*) # Causes problems with __ctype ;; *-*-sysv4.2uw2* | *-*-sysv5* | *-*-unixware* | *-*-OpenUNIX*) # Compiler inserts libc in the correct place for threads to work ;; *) # Add libc to deplibs on all other systems if necessary. if test yes = "$build_libtool_need_lc"; then func_append deplibs " -lc" fi ;; esac fi # Transform deplibs into only deplibs that can be linked in shared. name_save=$name libname_save=$libname release_save=$release versuffix_save=$versuffix major_save=$major # I'm not sure if I'm treating the release correctly. I think # release should show up in the -l (ie -lgmp5) so we don't want to # add it in twice. Is that correct? release= versuffix= major= newdeplibs= droppeddeps=no case $deplibs_check_method in pass_all) # Don't check for shared/static. Everything works. # This might be a little naive. We might want to check # whether the library exists or not. But this is on # osf3 & osf4 and I'm not really sure... Just # implementing what was already the behavior. newdeplibs=$deplibs ;; test_compile) # This code stresses the "libraries are programs" paradigm to its # limits. Maybe even breaks it. We compile a program, linking it # against the deplibs as a proxy for the library. Then we can check # whether they linked in statically or dynamically with ldd. $opt_dry_run || $RM conftest.c cat > conftest.c </dev/null` $nocaseglob else potential_libs=`ls $i/$libnameglob[.-]* 2>/dev/null` fi for potent_lib in $potential_libs; do # Follow soft links. if ls -lLd "$potent_lib" 2>/dev/null | $GREP " -> " >/dev/null; then continue fi # The statement above tries to avoid entering an # endless loop below, in case of cyclic links. # We might still enter an endless loop, since a link # loop can be closed while we follow links, # but so what? potlib=$potent_lib while test -h "$potlib" 2>/dev/null; do potliblink=`ls -ld $potlib | $SED 's/.* -> //'` case $potliblink in [\\/]* | [A-Za-z]:[\\/]*) potlib=$potliblink;; *) potlib=`$ECHO "$potlib" | $SED 's|[^/]*$||'`"$potliblink";; esac done if eval $file_magic_cmd \"\$potlib\" 2>/dev/null | $SED -e 10q | $EGREP "$file_magic_regex" > /dev/null; then func_append newdeplibs " $a_deplib" a_deplib= break 2 fi done done fi if test -n "$a_deplib"; then droppeddeps=yes echo $ECHO "*** Warning: linker path does not have real file for library $a_deplib." echo "*** I have the capability to make that library automatically link in when" echo "*** you link to this library. But I can only do this if you have a" echo "*** shared version of the library, which you do not appear to have" echo "*** because I did check the linker path looking for a file starting" if test -z "$potlib"; then $ECHO "*** with $libname but no candidates were found. (...for file magic test)" else $ECHO "*** with $libname and none of the candidates passed a file format test" $ECHO "*** using a file magic. Last file checked: $potlib" fi fi ;; *) # Add a -L argument. func_append newdeplibs " $a_deplib" ;; esac done # Gone through all deplibs. ;; match_pattern*) set dummy $deplibs_check_method; shift match_pattern_regex=`expr "$deplibs_check_method" : "$1 \(.*\)"` for a_deplib in $deplibs; do case $a_deplib in -l*) func_stripname -l '' "$a_deplib" name=$func_stripname_result if test yes = "$allow_libtool_libs_with_static_runtimes"; then case " $predeps $postdeps " in *" $a_deplib "*) func_append newdeplibs " $a_deplib" a_deplib= ;; esac fi if test -n "$a_deplib"; then libname=`eval "\\$ECHO \"$libname_spec\""` for i in $lib_search_path $sys_lib_search_path $shlib_search_path; do potential_libs=`ls $i/$libname[.-]* 2>/dev/null` for potent_lib in $potential_libs; do potlib=$potent_lib # see symlink-check above in file_magic test if eval "\$ECHO \"$potent_lib\"" 2>/dev/null | $SED 10q | \ $EGREP "$match_pattern_regex" > /dev/null; then func_append newdeplibs " $a_deplib" a_deplib= break 2 fi done done fi if test -n "$a_deplib"; then droppeddeps=yes echo $ECHO "*** Warning: linker path does not have real file for library $a_deplib." echo "*** I have the capability to make that library automatically link in when" echo "*** you link to this library. But I can only do this if you have a" echo "*** shared version of the library, which you do not appear to have" echo "*** because I did check the linker path looking for a file starting" if test -z "$potlib"; then $ECHO "*** with $libname but no candidates were found. (...for regex pattern test)" else $ECHO "*** with $libname and none of the candidates passed a file format test" $ECHO "*** using a regex pattern. Last file checked: $potlib" fi fi ;; *) # Add a -L argument. func_append newdeplibs " $a_deplib" ;; esac done # Gone through all deplibs. ;; none | unknown | *) newdeplibs= tmp_deplibs=`$ECHO " $deplibs" | $SED 's/ -lc$//; s/ -[LR][^ ]*//g'` if test yes = "$allow_libtool_libs_with_static_runtimes"; then for i in $predeps $postdeps; do # can't use Xsed below, because $i might contain '/' tmp_deplibs=`$ECHO " $tmp_deplibs" | $SED "s|$i||"` done fi case $tmp_deplibs in *[!\ \ ]*) echo if test none = "$deplibs_check_method"; then echo "*** Warning: inter-library dependencies are not supported in this platform." else echo "*** Warning: inter-library dependencies are not known to be supported." fi echo "*** All declared inter-library dependencies are being dropped." droppeddeps=yes ;; esac ;; esac versuffix=$versuffix_save major=$major_save release=$release_save libname=$libname_save name=$name_save case $host in *-*-rhapsody* | *-*-darwin1.[012]) # On Rhapsody replace the C library with the System framework newdeplibs=`$ECHO " $newdeplibs" | $SED 's/ -lc / System.ltframework /'` ;; esac if test yes = "$droppeddeps"; then if test yes = "$module"; then echo echo "*** Warning: libtool could not satisfy all declared inter-library" $ECHO "*** dependencies of module $libname. Therefore, libtool will create" echo "*** a static module, that should work as long as the dlopening" echo "*** application is linked with the -dlopen flag." if test -z "$global_symbol_pipe"; then echo echo "*** However, this would only work if libtool was able to extract symbol" echo "*** lists from a program, using 'nm' or equivalent, but libtool could" echo "*** not find such a program. So, this module is probably useless." echo "*** 'nm' from GNU binutils and a full rebuild may help." fi if test no = "$build_old_libs"; then oldlibs=$output_objdir/$libname.$libext build_libtool_libs=module build_old_libs=yes else build_libtool_libs=no fi else echo "*** The inter-library dependencies that have been dropped here will be" echo "*** automatically added whenever a program is linked with this library" echo "*** or is declared to -dlopen it." if test no = "$allow_undefined"; then echo echo "*** Since this library must not contain undefined symbols," echo "*** because either the platform does not support them or" echo "*** it was explicitly requested with -no-undefined," echo "*** libtool will only create a static version of it." if test no = "$build_old_libs"; then oldlibs=$output_objdir/$libname.$libext build_libtool_libs=module build_old_libs=yes else build_libtool_libs=no fi fi fi fi # Done checking deplibs! deplibs=$newdeplibs fi # Time to change all our "foo.ltframework" stuff back to "-framework foo" case $host in *-*-darwin*) newdeplibs=`$ECHO " $newdeplibs" | $SED 's% \([^ $]*\).ltframework% -framework \1%g'` new_inherited_linker_flags=`$ECHO " $new_inherited_linker_flags" | $SED 's% \([^ $]*\).ltframework% -framework \1%g'` deplibs=`$ECHO " $deplibs" | $SED 's% \([^ $]*\).ltframework% -framework \1%g'` ;; esac # move library search paths that coincide with paths to not yet # installed libraries to the beginning of the library search list new_libs= for path in $notinst_path; do case " $new_libs " in *" -L$path/$objdir "*) ;; *) case " $deplibs " in *" -L$path/$objdir "*) func_append new_libs " -L$path/$objdir" ;; esac ;; esac done for deplib in $deplibs; do case $deplib in -L*) case " $new_libs " in *" $deplib "*) ;; *) func_append new_libs " $deplib" ;; esac ;; *) func_append new_libs " $deplib" ;; esac done deplibs=$new_libs # All the library-specific variables (install_libdir is set above). library_names= old_library= dlname= # Test again, we may have decided not to build it any more if test yes = "$build_libtool_libs"; then # Remove $wl instances when linking with ld. # FIXME: should test the right _cmds variable. case $archive_cmds in *\$LD\ *) wl= ;; esac if test yes = "$hardcode_into_libs"; then # Hardcode the library paths hardcode_libdirs= dep_rpath= rpath=$finalize_rpath test relink = "$opt_mode" || rpath=$compile_rpath$rpath for libdir in $rpath; do if test -n "$hardcode_libdir_flag_spec"; then if test -n "$hardcode_libdir_separator"; then func_replace_sysroot "$libdir" libdir=$func_replace_sysroot_result if test -z "$hardcode_libdirs"; then hardcode_libdirs=$libdir else # Just accumulate the unique libdirs. case $hardcode_libdir_separator$hardcode_libdirs$hardcode_libdir_separator in *"$hardcode_libdir_separator$libdir$hardcode_libdir_separator"*) ;; *) func_append hardcode_libdirs "$hardcode_libdir_separator$libdir" ;; esac fi else eval flag=\"$hardcode_libdir_flag_spec\" func_append dep_rpath " $flag" fi elif test -n "$runpath_var"; then case "$perm_rpath " in *" $libdir "*) ;; *) func_append perm_rpath " $libdir" ;; esac fi done # Substitute the hardcoded libdirs into the rpath. if test -n "$hardcode_libdir_separator" && test -n "$hardcode_libdirs"; then libdir=$hardcode_libdirs eval "dep_rpath=\"$hardcode_libdir_flag_spec\"" fi if test -n "$runpath_var" && test -n "$perm_rpath"; then # We should set the runpath_var. rpath= for dir in $perm_rpath; do func_append rpath "$dir:" done eval "$runpath_var='$rpath\$$runpath_var'; export $runpath_var" fi test -n "$dep_rpath" && deplibs="$dep_rpath $deplibs" fi shlibpath=$finalize_shlibpath test relink = "$opt_mode" || shlibpath=$compile_shlibpath$shlibpath if test -n "$shlibpath"; then eval "$shlibpath_var='$shlibpath\$$shlibpath_var'; export $shlibpath_var" fi # Get the real and link names of the library. eval shared_ext=\"$shrext_cmds\" eval library_names=\"$library_names_spec\" set dummy $library_names shift realname=$1 shift if test -n "$soname_spec"; then eval soname=\"$soname_spec\" else soname=$realname fi if test -z "$dlname"; then dlname=$soname fi lib=$output_objdir/$realname linknames= for link do func_append linknames " $link" done # Use standard objects if they are pic test -z "$pic_flag" && libobjs=`$ECHO "$libobjs" | $SP2NL | $SED "$lo2o" | $NL2SP` test "X$libobjs" = "X " && libobjs= delfiles= if test -n "$export_symbols" && test -n "$include_expsyms"; then $opt_dry_run || cp "$export_symbols" "$output_objdir/$libname.uexp" export_symbols=$output_objdir/$libname.uexp func_append delfiles " $export_symbols" fi orig_export_symbols= case $host_os in cygwin* | mingw* | cegcc*) if test -n "$export_symbols" && test -z "$export_symbols_regex"; then # exporting using user supplied symfile func_dll_def_p "$export_symbols" || { # and it's NOT already a .def file. Must figure out # which of the given symbols are data symbols and tag # them as such. So, trigger use of export_symbols_cmds. # export_symbols gets reassigned inside the "prepare # the list of exported symbols" if statement, so the # include_expsyms logic still works. orig_export_symbols=$export_symbols export_symbols= always_export_symbols=yes } fi ;; esac # Prepare the list of exported symbols if test -z "$export_symbols"; then if test yes = "$always_export_symbols" || test -n "$export_symbols_regex"; then func_verbose "generating symbol list for '$libname.la'" export_symbols=$output_objdir/$libname.exp $opt_dry_run || $RM $export_symbols cmds=$export_symbols_cmds save_ifs=$IFS; IFS='~' for cmd1 in $cmds; do IFS=$save_ifs # Take the normal branch if the nm_file_list_spec branch # doesn't work or if tool conversion is not needed. case $nm_file_list_spec~$to_tool_file_cmd in *~func_convert_file_noop | *~func_convert_file_msys_to_w32 | ~*) try_normal_branch=yes eval cmd=\"$cmd1\" func_len " $cmd" len=$func_len_result ;; *) try_normal_branch=no ;; esac if test yes = "$try_normal_branch" \ && { test "$len" -lt "$max_cmd_len" \ || test "$max_cmd_len" -le -1; } then func_show_eval "$cmd" 'exit $?' skipped_export=false elif test -n "$nm_file_list_spec"; then func_basename "$output" output_la=$func_basename_result save_libobjs=$libobjs save_output=$output output=$output_objdir/$output_la.nm func_to_tool_file "$output" libobjs=$nm_file_list_spec$func_to_tool_file_result func_append delfiles " $output" func_verbose "creating $NM input file list: $output" for obj in $save_libobjs; do func_to_tool_file "$obj" $ECHO "$func_to_tool_file_result" done > "$output" eval cmd=\"$cmd1\" func_show_eval "$cmd" 'exit $?' output=$save_output libobjs=$save_libobjs skipped_export=false else # The command line is too long to execute in one step. func_verbose "using reloadable object file for export list..." skipped_export=: # Break out early, otherwise skipped_export may be # set to false by a later but shorter cmd. break fi done IFS=$save_ifs if test -n "$export_symbols_regex" && test : != "$skipped_export"; then func_show_eval '$EGREP -e "$export_symbols_regex" "$export_symbols" > "${export_symbols}T"' func_show_eval '$MV "${export_symbols}T" "$export_symbols"' fi fi fi if test -n "$export_symbols" && test -n "$include_expsyms"; then tmp_export_symbols=$export_symbols test -n "$orig_export_symbols" && tmp_export_symbols=$orig_export_symbols $opt_dry_run || eval '$ECHO "$include_expsyms" | $SP2NL >> "$tmp_export_symbols"' fi if test : != "$skipped_export" && test -n "$orig_export_symbols"; then # The given exports_symbols file has to be filtered, so filter it. func_verbose "filter symbol list for '$libname.la' to tag DATA exports" # FIXME: $output_objdir/$libname.filter potentially contains lots of # 's' commands, which not all seds can handle. GNU sed should be fine # though. Also, the filter scales superlinearly with the number of # global variables. join(1) would be nice here, but unfortunately # isn't a blessed tool. $opt_dry_run || $SED -e '/[ ,]DATA/!d;s,\(.*\)\([ \,].*\),s|^\1$|\1\2|,' < $export_symbols > $output_objdir/$libname.filter func_append delfiles " $export_symbols $output_objdir/$libname.filter" export_symbols=$output_objdir/$libname.def $opt_dry_run || $SED -f $output_objdir/$libname.filter < $orig_export_symbols > $export_symbols fi tmp_deplibs= for test_deplib in $deplibs; do case " $convenience " in *" $test_deplib "*) ;; *) func_append tmp_deplibs " $test_deplib" ;; esac done deplibs=$tmp_deplibs if test -n "$convenience"; then if test -n "$whole_archive_flag_spec" && test yes = "$compiler_needs_object" && test -z "$libobjs"; then # extract the archives, so we have objects to list. # TODO: could optimize this to just extract one archive. whole_archive_flag_spec= fi if test -n "$whole_archive_flag_spec"; then save_libobjs=$libobjs eval libobjs=\"\$libobjs $whole_archive_flag_spec\" test "X$libobjs" = "X " && libobjs= else gentop=$output_objdir/${outputname}x func_append generated " $gentop" func_extract_archives $gentop $convenience func_append libobjs " $func_extract_archives_result" test "X$libobjs" = "X " && libobjs= fi fi if test yes = "$thread_safe" && test -n "$thread_safe_flag_spec"; then eval flag=\"$thread_safe_flag_spec\" func_append linker_flags " $flag" fi # Make a backup of the uninstalled library when relinking if test relink = "$opt_mode"; then $opt_dry_run || eval '(cd $output_objdir && $RM ${realname}U && $MV $realname ${realname}U)' || exit $? fi # Do each of the archive commands. if test yes = "$module" && test -n "$module_cmds"; then if test -n "$export_symbols" && test -n "$module_expsym_cmds"; then eval test_cmds=\"$module_expsym_cmds\" cmds=$module_expsym_cmds else eval test_cmds=\"$module_cmds\" cmds=$module_cmds fi else if test -n "$export_symbols" && test -n "$archive_expsym_cmds"; then eval test_cmds=\"$archive_expsym_cmds\" cmds=$archive_expsym_cmds else eval test_cmds=\"$archive_cmds\" cmds=$archive_cmds fi fi if test : != "$skipped_export" && func_len " $test_cmds" && len=$func_len_result && test "$len" -lt "$max_cmd_len" || test "$max_cmd_len" -le -1; then : else # The command line is too long to link in one step, link piecewise # or, if using GNU ld and skipped_export is not :, use a linker # script. # Save the value of $output and $libobjs because we want to # use them later. If we have whole_archive_flag_spec, we # want to use save_libobjs as it was before # whole_archive_flag_spec was expanded, because we can't # assume the linker understands whole_archive_flag_spec. # This may have to be revisited, in case too many # convenience libraries get linked in and end up exceeding # the spec. if test -z "$convenience" || test -z "$whole_archive_flag_spec"; then save_libobjs=$libobjs fi save_output=$output func_basename "$output" output_la=$func_basename_result # Clear the reloadable object creation command queue and # initialize k to one. test_cmds= concat_cmds= objlist= last_robj= k=1 if test -n "$save_libobjs" && test : != "$skipped_export" && test yes = "$with_gnu_ld"; then output=$output_objdir/$output_la.lnkscript func_verbose "creating GNU ld script: $output" echo 'INPUT (' > $output for obj in $save_libobjs do func_to_tool_file "$obj" $ECHO "$func_to_tool_file_result" >> $output done echo ')' >> $output func_append delfiles " $output" func_to_tool_file "$output" output=$func_to_tool_file_result elif test -n "$save_libobjs" && test : != "$skipped_export" && test -n "$file_list_spec"; then output=$output_objdir/$output_la.lnk func_verbose "creating linker input file list: $output" : > $output set x $save_libobjs shift firstobj= if test yes = "$compiler_needs_object"; then firstobj="$1 " shift fi for obj do func_to_tool_file "$obj" $ECHO "$func_to_tool_file_result" >> $output done func_append delfiles " $output" func_to_tool_file "$output" output=$firstobj\"$file_list_spec$func_to_tool_file_result\" else if test -n "$save_libobjs"; then func_verbose "creating reloadable object files..." output=$output_objdir/$output_la-$k.$objext eval test_cmds=\"$reload_cmds\" func_len " $test_cmds" len0=$func_len_result len=$len0 # Loop over the list of objects to be linked. for obj in $save_libobjs do func_len " $obj" func_arith $len + $func_len_result len=$func_arith_result if test -z "$objlist" || test "$len" -lt "$max_cmd_len"; then func_append objlist " $obj" else # The command $test_cmds is almost too long, add a # command to the queue. if test 1 -eq "$k"; then # The first file doesn't have a previous command to add. reload_objs=$objlist eval concat_cmds=\"$reload_cmds\" else # All subsequent reloadable object files will link in # the last one created. reload_objs="$objlist $last_robj" eval concat_cmds=\"\$concat_cmds~$reload_cmds~\$RM $last_robj\" fi last_robj=$output_objdir/$output_la-$k.$objext func_arith $k + 1 k=$func_arith_result output=$output_objdir/$output_la-$k.$objext objlist=" $obj" func_len " $last_robj" func_arith $len0 + $func_len_result len=$func_arith_result fi done # Handle the remaining objects by creating one last # reloadable object file. All subsequent reloadable object # files will link in the last one created. test -z "$concat_cmds" || concat_cmds=$concat_cmds~ reload_objs="$objlist $last_robj" eval concat_cmds=\"\$concat_cmds$reload_cmds\" if test -n "$last_robj"; then eval concat_cmds=\"\$concat_cmds~\$RM $last_robj\" fi func_append delfiles " $output" else output= fi ${skipped_export-false} && { func_verbose "generating symbol list for '$libname.la'" export_symbols=$output_objdir/$libname.exp $opt_dry_run || $RM $export_symbols libobjs=$output # Append the command to create the export file. test -z "$concat_cmds" || concat_cmds=$concat_cmds~ eval concat_cmds=\"\$concat_cmds$export_symbols_cmds\" if test -n "$last_robj"; then eval concat_cmds=\"\$concat_cmds~\$RM $last_robj\" fi } test -n "$save_libobjs" && func_verbose "creating a temporary reloadable object file: $output" # Loop through the commands generated above and execute them. save_ifs=$IFS; IFS='~' for cmd in $concat_cmds; do IFS=$save_ifs $opt_quiet || { func_quote_for_expand "$cmd" eval "func_echo $func_quote_for_expand_result" } $opt_dry_run || eval "$cmd" || { lt_exit=$? # Restore the uninstalled library and exit if test relink = "$opt_mode"; then ( cd "$output_objdir" && \ $RM "${realname}T" && \ $MV "${realname}U" "$realname" ) fi exit $lt_exit } done IFS=$save_ifs if test -n "$export_symbols_regex" && ${skipped_export-false}; then func_show_eval '$EGREP -e "$export_symbols_regex" "$export_symbols" > "${export_symbols}T"' func_show_eval '$MV "${export_symbols}T" "$export_symbols"' fi fi ${skipped_export-false} && { if test -n "$export_symbols" && test -n "$include_expsyms"; then tmp_export_symbols=$export_symbols test -n "$orig_export_symbols" && tmp_export_symbols=$orig_export_symbols $opt_dry_run || eval '$ECHO "$include_expsyms" | $SP2NL >> "$tmp_export_symbols"' fi if test -n "$orig_export_symbols"; then # The given exports_symbols file has to be filtered, so filter it. func_verbose "filter symbol list for '$libname.la' to tag DATA exports" # FIXME: $output_objdir/$libname.filter potentially contains lots of # 's' commands, which not all seds can handle. GNU sed should be fine # though. Also, the filter scales superlinearly with the number of # global variables. join(1) would be nice here, but unfortunately # isn't a blessed tool. $opt_dry_run || $SED -e '/[ ,]DATA/!d;s,\(.*\)\([ \,].*\),s|^\1$|\1\2|,' < $export_symbols > $output_objdir/$libname.filter func_append delfiles " $export_symbols $output_objdir/$libname.filter" export_symbols=$output_objdir/$libname.def $opt_dry_run || $SED -f $output_objdir/$libname.filter < $orig_export_symbols > $export_symbols fi } libobjs=$output # Restore the value of output. output=$save_output if test -n "$convenience" && test -n "$whole_archive_flag_spec"; then eval libobjs=\"\$libobjs $whole_archive_flag_spec\" test "X$libobjs" = "X " && libobjs= fi # Expand the library linking commands again to reset the # value of $libobjs for piecewise linking. # Do each of the archive commands. if test yes = "$module" && test -n "$module_cmds"; then if test -n "$export_symbols" && test -n "$module_expsym_cmds"; then cmds=$module_expsym_cmds else cmds=$module_cmds fi else if test -n "$export_symbols" && test -n "$archive_expsym_cmds"; then cmds=$archive_expsym_cmds else cmds=$archive_cmds fi fi fi if test -n "$delfiles"; then # Append the command to remove temporary files to $cmds. eval cmds=\"\$cmds~\$RM $delfiles\" fi # Add any objects from preloaded convenience libraries if test -n "$dlprefiles"; then gentop=$output_objdir/${outputname}x func_append generated " $gentop" func_extract_archives $gentop $dlprefiles func_append libobjs " $func_extract_archives_result" test "X$libobjs" = "X " && libobjs= fi save_ifs=$IFS; IFS='~' for cmd in $cmds; do IFS=$sp$nl eval cmd=\"$cmd\" IFS=$save_ifs $opt_quiet || { func_quote_for_expand "$cmd" eval "func_echo $func_quote_for_expand_result" } $opt_dry_run || eval "$cmd" || { lt_exit=$? # Restore the uninstalled library and exit if test relink = "$opt_mode"; then ( cd "$output_objdir" && \ $RM "${realname}T" && \ $MV "${realname}U" "$realname" ) fi exit $lt_exit } done IFS=$save_ifs # Restore the uninstalled library and exit if test relink = "$opt_mode"; then $opt_dry_run || eval '(cd $output_objdir && $RM ${realname}T && $MV $realname ${realname}T && $MV ${realname}U $realname)' || exit $? if test -n "$convenience"; then if test -z "$whole_archive_flag_spec"; then func_show_eval '${RM}r "$gentop"' fi fi exit $EXIT_SUCCESS fi # Create links to the real library. for linkname in $linknames; do if test "$realname" != "$linkname"; then func_show_eval '(cd "$output_objdir" && $RM "$linkname" && $LN_S "$realname" "$linkname")' 'exit $?' fi done # If -module or -export-dynamic was specified, set the dlname. if test yes = "$module" || test yes = "$export_dynamic"; then # On all known operating systems, these are identical. dlname=$soname fi fi ;; obj) if test -n "$dlfiles$dlprefiles" || test no != "$dlself"; then func_warning "'-dlopen' is ignored for objects" fi case " $deplibs" in *\ -l* | *\ -L*) func_warning "'-l' and '-L' are ignored for objects" ;; esac test -n "$rpath" && \ func_warning "'-rpath' is ignored for objects" test -n "$xrpath" && \ func_warning "'-R' is ignored for objects" test -n "$vinfo" && \ func_warning "'-version-info' is ignored for objects" test -n "$release" && \ func_warning "'-release' is ignored for objects" case $output in *.lo) test -n "$objs$old_deplibs" && \ func_fatal_error "cannot build library object '$output' from non-libtool objects" libobj=$output func_lo2o "$libobj" obj=$func_lo2o_result ;; *) libobj= obj=$output ;; esac # Delete the old objects. $opt_dry_run || $RM $obj $libobj # Objects from convenience libraries. This assumes # single-version convenience libraries. Whenever we create # different ones for PIC/non-PIC, this we'll have to duplicate # the extraction. reload_conv_objs= gentop= # if reload_cmds runs $LD directly, get rid of -Wl from # whole_archive_flag_spec and hope we can get by with turning comma # into space. case $reload_cmds in *\$LD[\ \$]*) wl= ;; esac if test -n "$convenience"; then if test -n "$whole_archive_flag_spec"; then eval tmp_whole_archive_flags=\"$whole_archive_flag_spec\" test -n "$wl" || tmp_whole_archive_flags=`$ECHO "$tmp_whole_archive_flags" | $SED 's|,| |g'` reload_conv_objs=$reload_objs\ $tmp_whole_archive_flags else gentop=$output_objdir/${obj}x func_append generated " $gentop" func_extract_archives $gentop $convenience reload_conv_objs="$reload_objs $func_extract_archives_result" fi fi # If we're not building shared, we need to use non_pic_objs test yes = "$build_libtool_libs" || libobjs=$non_pic_objects # Create the old-style object. reload_objs=$objs$old_deplibs' '`$ECHO "$libobjs" | $SP2NL | $SED "/\.$libext$/d; /\.lib$/d; $lo2o" | $NL2SP`' '$reload_conv_objs output=$obj func_execute_cmds "$reload_cmds" 'exit $?' # Exit if we aren't doing a library object file. if test -z "$libobj"; then if test -n "$gentop"; then func_show_eval '${RM}r "$gentop"' fi exit $EXIT_SUCCESS fi test yes = "$build_libtool_libs" || { if test -n "$gentop"; then func_show_eval '${RM}r "$gentop"' fi # Create an invalid libtool object if no PIC, so that we don't # accidentally link it into a program. # $show "echo timestamp > $libobj" # $opt_dry_run || eval "echo timestamp > $libobj" || exit $? exit $EXIT_SUCCESS } if test -n "$pic_flag" || test default != "$pic_mode"; then # Only do commands if we really have different PIC objects. reload_objs="$libobjs $reload_conv_objs" output=$libobj func_execute_cmds "$reload_cmds" 'exit $?' fi if test -n "$gentop"; then func_show_eval '${RM}r "$gentop"' fi exit $EXIT_SUCCESS ;; prog) case $host in *cygwin*) func_stripname '' '.exe' "$output" output=$func_stripname_result.exe;; esac test -n "$vinfo" && \ func_warning "'-version-info' is ignored for programs" test -n "$release" && \ func_warning "'-release' is ignored for programs" $preload \ && test unknown,unknown,unknown = "$dlopen_support,$dlopen_self,$dlopen_self_static" \ && func_warning "'LT_INIT([dlopen])' not used. Assuming no dlopen support." case $host in *-*-rhapsody* | *-*-darwin1.[012]) # On Rhapsody replace the C library is the System framework compile_deplibs=`$ECHO " $compile_deplibs" | $SED 's/ -lc / System.ltframework /'` finalize_deplibs=`$ECHO " $finalize_deplibs" | $SED 's/ -lc / System.ltframework /'` ;; esac case $host in *-*-darwin*) # Don't allow lazy linking, it breaks C++ global constructors # But is supposedly fixed on 10.4 or later (yay!). if test CXX = "$tagname"; then case ${MACOSX_DEPLOYMENT_TARGET-10.0} in 10.[0123]) func_append compile_command " $wl-bind_at_load" func_append finalize_command " $wl-bind_at_load" ;; esac fi # Time to change all our "foo.ltframework" stuff back to "-framework foo" compile_deplibs=`$ECHO " $compile_deplibs" | $SED 's% \([^ $]*\).ltframework% -framework \1%g'` finalize_deplibs=`$ECHO " $finalize_deplibs" | $SED 's% \([^ $]*\).ltframework% -framework \1%g'` ;; esac # move library search paths that coincide with paths to not yet # installed libraries to the beginning of the library search list new_libs= for path in $notinst_path; do case " $new_libs " in *" -L$path/$objdir "*) ;; *) case " $compile_deplibs " in *" -L$path/$objdir "*) func_append new_libs " -L$path/$objdir" ;; esac ;; esac done for deplib in $compile_deplibs; do case $deplib in -L*) case " $new_libs " in *" $deplib "*) ;; *) func_append new_libs " $deplib" ;; esac ;; *) func_append new_libs " $deplib" ;; esac done compile_deplibs=$new_libs func_append compile_command " $compile_deplibs" func_append finalize_command " $finalize_deplibs" if test -n "$rpath$xrpath"; then # If the user specified any rpath flags, then add them. for libdir in $rpath $xrpath; do # This is the magic to use -rpath. case "$finalize_rpath " in *" $libdir "*) ;; *) func_append finalize_rpath " $libdir" ;; esac done fi # Now hardcode the library paths rpath= hardcode_libdirs= for libdir in $compile_rpath $finalize_rpath; do if test -n "$hardcode_libdir_flag_spec"; then if test -n "$hardcode_libdir_separator"; then if test -z "$hardcode_libdirs"; then hardcode_libdirs=$libdir else # Just accumulate the unique libdirs. case $hardcode_libdir_separator$hardcode_libdirs$hardcode_libdir_separator in *"$hardcode_libdir_separator$libdir$hardcode_libdir_separator"*) ;; *) func_append hardcode_libdirs "$hardcode_libdir_separator$libdir" ;; esac fi else eval flag=\"$hardcode_libdir_flag_spec\" func_append rpath " $flag" fi elif test -n "$runpath_var"; then case "$perm_rpath " in *" $libdir "*) ;; *) func_append perm_rpath " $libdir" ;; esac fi case $host in *-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-os2* | *-cegcc*) testbindir=`$ECHO "$libdir" | $SED -e 's*/lib$*/bin*'` case :$dllsearchpath: in *":$libdir:"*) ;; ::) dllsearchpath=$libdir;; *) func_append dllsearchpath ":$libdir";; esac case :$dllsearchpath: in *":$testbindir:"*) ;; ::) dllsearchpath=$testbindir;; *) func_append dllsearchpath ":$testbindir";; esac ;; esac done # Substitute the hardcoded libdirs into the rpath. if test -n "$hardcode_libdir_separator" && test -n "$hardcode_libdirs"; then libdir=$hardcode_libdirs eval rpath=\" $hardcode_libdir_flag_spec\" fi compile_rpath=$rpath rpath= hardcode_libdirs= for libdir in $finalize_rpath; do if test -n "$hardcode_libdir_flag_spec"; then if test -n "$hardcode_libdir_separator"; then if test -z "$hardcode_libdirs"; then hardcode_libdirs=$libdir else # Just accumulate the unique libdirs. case $hardcode_libdir_separator$hardcode_libdirs$hardcode_libdir_separator in *"$hardcode_libdir_separator$libdir$hardcode_libdir_separator"*) ;; *) func_append hardcode_libdirs "$hardcode_libdir_separator$libdir" ;; esac fi else eval flag=\"$hardcode_libdir_flag_spec\" func_append rpath " $flag" fi elif test -n "$runpath_var"; then case "$finalize_perm_rpath " in *" $libdir "*) ;; *) func_append finalize_perm_rpath " $libdir" ;; esac fi done # Substitute the hardcoded libdirs into the rpath. if test -n "$hardcode_libdir_separator" && test -n "$hardcode_libdirs"; then libdir=$hardcode_libdirs eval rpath=\" $hardcode_libdir_flag_spec\" fi finalize_rpath=$rpath if test -n "$libobjs" && test yes = "$build_old_libs"; then # Transform all the library objects into standard objects. compile_command=`$ECHO "$compile_command" | $SP2NL | $SED "$lo2o" | $NL2SP` finalize_command=`$ECHO "$finalize_command" | $SP2NL | $SED "$lo2o" | $NL2SP` fi func_generate_dlsyms "$outputname" "@PROGRAM@" false # template prelinking step if test -n "$prelink_cmds"; then func_execute_cmds "$prelink_cmds" 'exit $?' fi wrappers_required=: case $host in *cegcc* | *mingw32ce*) # Disable wrappers for cegcc and mingw32ce hosts, we are cross compiling anyway. wrappers_required=false ;; *cygwin* | *mingw* ) test yes = "$build_libtool_libs" || wrappers_required=false ;; *) if test no = "$need_relink" || test yes != "$build_libtool_libs"; then wrappers_required=false fi ;; esac $wrappers_required || { # Replace the output file specification. compile_command=`$ECHO "$compile_command" | $SED 's%@OUTPUT@%'"$output"'%g'` link_command=$compile_command$compile_rpath # We have no uninstalled library dependencies, so finalize right now. exit_status=0 func_show_eval "$link_command" 'exit_status=$?' if test -n "$postlink_cmds"; then func_to_tool_file "$output" postlink_cmds=`func_echo_all "$postlink_cmds" | $SED -e 's%@OUTPUT@%'"$output"'%g' -e 's%@TOOL_OUTPUT@%'"$func_to_tool_file_result"'%g'` func_execute_cmds "$postlink_cmds" 'exit $?' fi # Delete the generated files. if test -f "$output_objdir/${outputname}S.$objext"; then func_show_eval '$RM "$output_objdir/${outputname}S.$objext"' fi exit $exit_status } if test -n "$compile_shlibpath$finalize_shlibpath"; then compile_command="$shlibpath_var=\"$compile_shlibpath$finalize_shlibpath\$$shlibpath_var\" $compile_command" fi if test -n "$finalize_shlibpath"; then finalize_command="$shlibpath_var=\"$finalize_shlibpath\$$shlibpath_var\" $finalize_command" fi compile_var= finalize_var= if test -n "$runpath_var"; then if test -n "$perm_rpath"; then # We should set the runpath_var. rpath= for dir in $perm_rpath; do func_append rpath "$dir:" done compile_var="$runpath_var=\"$rpath\$$runpath_var\" " fi if test -n "$finalize_perm_rpath"; then # We should set the runpath_var. rpath= for dir in $finalize_perm_rpath; do func_append rpath "$dir:" done finalize_var="$runpath_var=\"$rpath\$$runpath_var\" " fi fi if test yes = "$no_install"; then # We don't need to create a wrapper script. link_command=$compile_var$compile_command$compile_rpath # Replace the output file specification. link_command=`$ECHO "$link_command" | $SED 's%@OUTPUT@%'"$output"'%g'` # Delete the old output file. $opt_dry_run || $RM $output # Link the executable and exit func_show_eval "$link_command" 'exit $?' if test -n "$postlink_cmds"; then func_to_tool_file "$output" postlink_cmds=`func_echo_all "$postlink_cmds" | $SED -e 's%@OUTPUT@%'"$output"'%g' -e 's%@TOOL_OUTPUT@%'"$func_to_tool_file_result"'%g'` func_execute_cmds "$postlink_cmds" 'exit $?' fi exit $EXIT_SUCCESS fi case $hardcode_action,$fast_install in relink,*) # Fast installation is not supported link_command=$compile_var$compile_command$compile_rpath relink_command=$finalize_var$finalize_command$finalize_rpath func_warning "this platform does not like uninstalled shared libraries" func_warning "'$output' will be relinked during installation" ;; *,yes) link_command=$finalize_var$compile_command$finalize_rpath relink_command=`$ECHO "$compile_var$compile_command$compile_rpath" | $SED 's%@OUTPUT@%\$progdir/\$file%g'` ;; *,no) link_command=$compile_var$compile_command$compile_rpath relink_command=$finalize_var$finalize_command$finalize_rpath ;; *,needless) link_command=$finalize_var$compile_command$finalize_rpath relink_command= ;; esac # Replace the output file specification. link_command=`$ECHO "$link_command" | $SED 's%@OUTPUT@%'"$output_objdir/$outputname"'%g'` # Delete the old output files. $opt_dry_run || $RM $output $output_objdir/$outputname $output_objdir/lt-$outputname func_show_eval "$link_command" 'exit $?' if test -n "$postlink_cmds"; then func_to_tool_file "$output_objdir/$outputname" postlink_cmds=`func_echo_all "$postlink_cmds" | $SED -e 's%@OUTPUT@%'"$output_objdir/$outputname"'%g' -e 's%@TOOL_OUTPUT@%'"$func_to_tool_file_result"'%g'` func_execute_cmds "$postlink_cmds" 'exit $?' fi # Now create the wrapper script. func_verbose "creating $output" # Quote the relink command for shipping. if test -n "$relink_command"; then # Preserve any variables that may affect compiler behavior for var in $variables_saved_for_relink; do if eval test -z \"\${$var+set}\"; then relink_command="{ test -z \"\${$var+set}\" || $lt_unset $var || { $var=; export $var; }; }; $relink_command" elif eval var_value=\$$var; test -z "$var_value"; then relink_command="$var=; export $var; $relink_command" else func_quote_for_eval "$var_value" relink_command="$var=$func_quote_for_eval_result; export $var; $relink_command" fi done relink_command="(cd `pwd`; $relink_command)" relink_command=`$ECHO "$relink_command" | $SED "$sed_quote_subst"` fi # Only actually do things if not in dry run mode. $opt_dry_run || { # win32 will think the script is a binary if it has # a .exe suffix, so we strip it off here. case $output in *.exe) func_stripname '' '.exe' "$output" output=$func_stripname_result ;; esac # test for cygwin because mv fails w/o .exe extensions case $host in *cygwin*) exeext=.exe func_stripname '' '.exe' "$outputname" outputname=$func_stripname_result ;; *) exeext= ;; esac case $host in *cygwin* | *mingw* ) func_dirname_and_basename "$output" "" "." output_name=$func_basename_result output_path=$func_dirname_result cwrappersource=$output_path/$objdir/lt-$output_name.c cwrapper=$output_path/$output_name.exe $RM $cwrappersource $cwrapper trap "$RM $cwrappersource $cwrapper; exit $EXIT_FAILURE" 1 2 15 func_emit_cwrapperexe_src > $cwrappersource # The wrapper executable is built using the $host compiler, # because it contains $host paths and files. If cross- # compiling, it, like the target executable, must be # executed on the $host or under an emulation environment. $opt_dry_run || { $LTCC $LTCFLAGS -o $cwrapper $cwrappersource $STRIP $cwrapper } # Now, create the wrapper script for func_source use: func_ltwrapper_scriptname $cwrapper $RM $func_ltwrapper_scriptname_result trap "$RM $func_ltwrapper_scriptname_result; exit $EXIT_FAILURE" 1 2 15 $opt_dry_run || { # note: this script will not be executed, so do not chmod. if test "x$build" = "x$host"; then $cwrapper --lt-dump-script > $func_ltwrapper_scriptname_result else func_emit_wrapper no > $func_ltwrapper_scriptname_result fi } ;; * ) $RM $output trap "$RM $output; exit $EXIT_FAILURE" 1 2 15 func_emit_wrapper no > $output chmod +x $output ;; esac } exit $EXIT_SUCCESS ;; esac # See if we need to build an old-fashioned archive. for oldlib in $oldlibs; do case $build_libtool_libs in convenience) oldobjs="$libobjs_save $symfileobj" addlibs=$convenience build_libtool_libs=no ;; module) oldobjs=$libobjs_save addlibs=$old_convenience build_libtool_libs=no ;; *) oldobjs="$old_deplibs $non_pic_objects" $preload && test -f "$symfileobj" \ && func_append oldobjs " $symfileobj" addlibs=$old_convenience ;; esac if test -n "$addlibs"; then gentop=$output_objdir/${outputname}x func_append generated " $gentop" func_extract_archives $gentop $addlibs func_append oldobjs " $func_extract_archives_result" fi # Do each command in the archive commands. if test -n "$old_archive_from_new_cmds" && test yes = "$build_libtool_libs"; then cmds=$old_archive_from_new_cmds else # Add any objects from preloaded convenience libraries if test -n "$dlprefiles"; then gentop=$output_objdir/${outputname}x func_append generated " $gentop" func_extract_archives $gentop $dlprefiles func_append oldobjs " $func_extract_archives_result" fi # POSIX demands no paths to be encoded in archives. We have # to avoid creating archives with duplicate basenames if we # might have to extract them afterwards, e.g., when creating a # static archive out of a convenience library, or when linking # the entirety of a libtool archive into another (currently # not supported by libtool). if (for obj in $oldobjs do func_basename "$obj" $ECHO "$func_basename_result" done | sort | sort -uc >/dev/null 2>&1); then : else echo "copying selected object files to avoid basename conflicts..." gentop=$output_objdir/${outputname}x func_append generated " $gentop" func_mkdir_p "$gentop" save_oldobjs=$oldobjs oldobjs= counter=1 for obj in $save_oldobjs do func_basename "$obj" objbase=$func_basename_result case " $oldobjs " in " ") oldobjs=$obj ;; *[\ /]"$objbase "*) while :; do # Make sure we don't pick an alternate name that also # overlaps. newobj=lt$counter-$objbase func_arith $counter + 1 counter=$func_arith_result case " $oldobjs " in *[\ /]"$newobj "*) ;; *) if test ! -f "$gentop/$newobj"; then break; fi ;; esac done func_show_eval "ln $obj $gentop/$newobj || cp $obj $gentop/$newobj" func_append oldobjs " $gentop/$newobj" ;; *) func_append oldobjs " $obj" ;; esac done fi func_to_tool_file "$oldlib" func_convert_file_msys_to_w32 tool_oldlib=$func_to_tool_file_result eval cmds=\"$old_archive_cmds\" func_len " $cmds" len=$func_len_result if test "$len" -lt "$max_cmd_len" || test "$max_cmd_len" -le -1; then cmds=$old_archive_cmds elif test -n "$archiver_list_spec"; then func_verbose "using command file archive linking..." for obj in $oldobjs do func_to_tool_file "$obj" $ECHO "$func_to_tool_file_result" done > $output_objdir/$libname.libcmd func_to_tool_file "$output_objdir/$libname.libcmd" oldobjs=" $archiver_list_spec$func_to_tool_file_result" cmds=$old_archive_cmds else # the command line is too long to link in one step, link in parts func_verbose "using piecewise archive linking..." save_RANLIB=$RANLIB RANLIB=: objlist= concat_cmds= save_oldobjs=$oldobjs oldobjs= # Is there a better way of finding the last object in the list? for obj in $save_oldobjs do last_oldobj=$obj done eval test_cmds=\"$old_archive_cmds\" func_len " $test_cmds" len0=$func_len_result len=$len0 for obj in $save_oldobjs do func_len " $obj" func_arith $len + $func_len_result len=$func_arith_result func_append objlist " $obj" if test "$len" -lt "$max_cmd_len"; then : else # the above command should be used before it gets too long oldobjs=$objlist if test "$obj" = "$last_oldobj"; then RANLIB=$save_RANLIB fi test -z "$concat_cmds" || concat_cmds=$concat_cmds~ eval concat_cmds=\"\$concat_cmds$old_archive_cmds\" objlist= len=$len0 fi done RANLIB=$save_RANLIB oldobjs=$objlist if test -z "$oldobjs"; then eval cmds=\"\$concat_cmds\" else eval cmds=\"\$concat_cmds~\$old_archive_cmds\" fi fi fi func_execute_cmds "$cmds" 'exit $?' done test -n "$generated" && \ func_show_eval "${RM}r$generated" # Now create the libtool archive. case $output in *.la) old_library= test yes = "$build_old_libs" && old_library=$libname.$libext func_verbose "creating $output" # Preserve any variables that may affect compiler behavior for var in $variables_saved_for_relink; do if eval test -z \"\${$var+set}\"; then relink_command="{ test -z \"\${$var+set}\" || $lt_unset $var || { $var=; export $var; }; }; $relink_command" elif eval var_value=\$$var; test -z "$var_value"; then relink_command="$var=; export $var; $relink_command" else func_quote_for_eval "$var_value" relink_command="$var=$func_quote_for_eval_result; export $var; $relink_command" fi done # Quote the link command for shipping. relink_command="(cd `pwd`; $SHELL \"$progpath\" $preserve_args --mode=relink $libtool_args @inst_prefix_dir@)" relink_command=`$ECHO "$relink_command" | $SED "$sed_quote_subst"` if test yes = "$hardcode_automatic"; then relink_command= fi # Only create the output if not a dry run. $opt_dry_run || { for installed in no yes; do if test yes = "$installed"; then if test -z "$install_libdir"; then break fi output=$output_objdir/${outputname}i # Replace all uninstalled libtool libraries with the installed ones newdependency_libs= for deplib in $dependency_libs; do case $deplib in *.la) func_basename "$deplib" name=$func_basename_result func_resolve_sysroot "$deplib" eval libdir=`$SED -n -e 's/^libdir=\(.*\)$/\1/p' $func_resolve_sysroot_result` test -z "$libdir" && \ func_fatal_error "'$deplib' is not a valid libtool archive" func_append newdependency_libs " ${lt_sysroot:+=}$libdir/$name" ;; -L*) func_stripname -L '' "$deplib" func_replace_sysroot "$func_stripname_result" func_append newdependency_libs " -L$func_replace_sysroot_result" ;; -R*) func_stripname -R '' "$deplib" func_replace_sysroot "$func_stripname_result" func_append newdependency_libs " -R$func_replace_sysroot_result" ;; *) func_append newdependency_libs " $deplib" ;; esac done dependency_libs=$newdependency_libs newdlfiles= for lib in $dlfiles; do case $lib in *.la) func_basename "$lib" name=$func_basename_result eval libdir=`$SED -n -e 's/^libdir=\(.*\)$/\1/p' $lib` test -z "$libdir" && \ func_fatal_error "'$lib' is not a valid libtool archive" func_append newdlfiles " ${lt_sysroot:+=}$libdir/$name" ;; *) func_append newdlfiles " $lib" ;; esac done dlfiles=$newdlfiles newdlprefiles= for lib in $dlprefiles; do case $lib in *.la) # Only pass preopened files to the pseudo-archive (for # eventual linking with the app. that links it) if we # didn't already link the preopened objects directly into # the library: func_basename "$lib" name=$func_basename_result eval libdir=`$SED -n -e 's/^libdir=\(.*\)$/\1/p' $lib` test -z "$libdir" && \ func_fatal_error "'$lib' is not a valid libtool archive" func_append newdlprefiles " ${lt_sysroot:+=}$libdir/$name" ;; esac done dlprefiles=$newdlprefiles else newdlfiles= for lib in $dlfiles; do case $lib in [\\/]* | [A-Za-z]:[\\/]*) abs=$lib ;; *) abs=`pwd`"/$lib" ;; esac func_append newdlfiles " $abs" done dlfiles=$newdlfiles newdlprefiles= for lib in $dlprefiles; do case $lib in [\\/]* | [A-Za-z]:[\\/]*) abs=$lib ;; *) abs=`pwd`"/$lib" ;; esac func_append newdlprefiles " $abs" done dlprefiles=$newdlprefiles fi $RM $output # place dlname in correct position for cygwin # In fact, it would be nice if we could use this code for all target # systems that can't hard-code library paths into their executables # and that have no shared library path variable independent of PATH, # but it turns out we can't easily determine that from inspecting # libtool variables, so we have to hard-code the OSs to which it # applies here; at the moment, that means platforms that use the PE # object format with DLL files. See the long comment at the top of # tests/bindir.at for full details. tdlname=$dlname case $host,$output,$installed,$module,$dlname in *cygwin*,*lai,yes,no,*.dll | *mingw*,*lai,yes,no,*.dll | *cegcc*,*lai,yes,no,*.dll) # If a -bindir argument was supplied, place the dll there. if test -n "$bindir"; then func_relative_path "$install_libdir" "$bindir" tdlname=$func_relative_path_result/$dlname else # Otherwise fall back on heuristic. tdlname=../bin/$dlname fi ;; esac $ECHO > $output "\ # $outputname - a libtool library file # Generated by $PROGRAM (GNU $PACKAGE) $VERSION # # Please DO NOT delete this file! # It is necessary for linking the library. # The name that we can dlopen(3). dlname='$tdlname' # Names of this library. library_names='$library_names' # The name of the static archive. old_library='$old_library' # Linker flags that cannot go in dependency_libs. inherited_linker_flags='$new_inherited_linker_flags' # Libraries that this one depends upon. dependency_libs='$dependency_libs' # Names of additional weak libraries provided by this library weak_library_names='$weak_libs' # Version information for $libname. current=$current age=$age revision=$revision # Is this an already installed library? installed=$installed # Should we warn about portability when linking against -modules? shouldnotlink=$module # Files to dlopen/dlpreopen dlopen='$dlfiles' dlpreopen='$dlprefiles' # Directory that this library needs to be installed in: libdir='$install_libdir'" if test no,yes = "$installed,$need_relink"; then $ECHO >> $output "\ relink_command=\"$relink_command\"" fi done } # Do a symbolic link so that the libtool archive can be found in # LD_LIBRARY_PATH before the program is installed. func_show_eval '( cd "$output_objdir" && $RM "$outputname" && $LN_S "../$outputname" "$outputname" )' 'exit $?' ;; esac exit $EXIT_SUCCESS } if test link = "$opt_mode" || test relink = "$opt_mode"; then func_mode_link ${1+"$@"} fi # func_mode_uninstall arg... func_mode_uninstall () { $debug_cmd RM=$nonopt files= rmforce=false exit_status=0 # This variable tells wrapper scripts just to set variables rather # than running their programs. libtool_install_magic=$magic for arg do case $arg in -f) func_append RM " $arg"; rmforce=: ;; -*) func_append RM " $arg" ;; *) func_append files " $arg" ;; esac done test -z "$RM" && \ func_fatal_help "you must specify an RM program" rmdirs= for file in $files; do func_dirname "$file" "" "." dir=$func_dirname_result if test . = "$dir"; then odir=$objdir else odir=$dir/$objdir fi func_basename "$file" name=$func_basename_result test uninstall = "$opt_mode" && odir=$dir # Remember odir for removal later, being careful to avoid duplicates if test clean = "$opt_mode"; then case " $rmdirs " in *" $odir "*) ;; *) func_append rmdirs " $odir" ;; esac fi # Don't error if the file doesn't exist and rm -f was used. if { test -L "$file"; } >/dev/null 2>&1 || { test -h "$file"; } >/dev/null 2>&1 || test -f "$file"; then : elif test -d "$file"; then exit_status=1 continue elif $rmforce; then continue fi rmfiles=$file case $name in *.la) # Possibly a libtool archive, so verify it. if func_lalib_p "$file"; then func_source $dir/$name # Delete the libtool libraries and symlinks. for n in $library_names; do func_append rmfiles " $odir/$n" done test -n "$old_library" && func_append rmfiles " $odir/$old_library" case $opt_mode in clean) case " $library_names " in *" $dlname "*) ;; *) test -n "$dlname" && func_append rmfiles " $odir/$dlname" ;; esac test -n "$libdir" && func_append rmfiles " $odir/$name $odir/${name}i" ;; uninstall) if test -n "$library_names"; then # Do each command in the postuninstall commands. func_execute_cmds "$postuninstall_cmds" '$rmforce || exit_status=1' fi if test -n "$old_library"; then # Do each command in the old_postuninstall commands. func_execute_cmds "$old_postuninstall_cmds" '$rmforce || exit_status=1' fi # FIXME: should reinstall the best remaining shared library. ;; esac fi ;; *.lo) # Possibly a libtool object, so verify it. if func_lalib_p "$file"; then # Read the .lo file func_source $dir/$name # Add PIC object to the list of files to remove. if test -n "$pic_object" && test none != "$pic_object"; then func_append rmfiles " $dir/$pic_object" fi # Add non-PIC object to the list of files to remove. if test -n "$non_pic_object" && test none != "$non_pic_object"; then func_append rmfiles " $dir/$non_pic_object" fi fi ;; *) if test clean = "$opt_mode"; then noexename=$name case $file in *.exe) func_stripname '' '.exe' "$file" file=$func_stripname_result func_stripname '' '.exe' "$name" noexename=$func_stripname_result # $file with .exe has already been added to rmfiles, # add $file without .exe func_append rmfiles " $file" ;; esac # Do a test to see if this is a libtool program. if func_ltwrapper_p "$file"; then if func_ltwrapper_executable_p "$file"; then func_ltwrapper_scriptname "$file" relink_command= func_source $func_ltwrapper_scriptname_result func_append rmfiles " $func_ltwrapper_scriptname_result" else relink_command= func_source $dir/$noexename fi # note $name still contains .exe if it was in $file originally # as does the version of $file that was added into $rmfiles func_append rmfiles " $odir/$name $odir/${name}S.$objext" if test yes = "$fast_install" && test -n "$relink_command"; then func_append rmfiles " $odir/lt-$name" fi if test "X$noexename" != "X$name"; then func_append rmfiles " $odir/lt-$noexename.c" fi fi fi ;; esac func_show_eval "$RM $rmfiles" 'exit_status=1' done # Try to remove the $objdir's in the directories where we deleted files for dir in $rmdirs; do if test -d "$dir"; then func_show_eval "rmdir $dir >/dev/null 2>&1" fi done exit $exit_status } if test uninstall = "$opt_mode" || test clean = "$opt_mode"; then func_mode_uninstall ${1+"$@"} fi test -z "$opt_mode" && { help=$generic_help func_fatal_help "you must specify a MODE" } test -z "$exec_cmd" && \ func_fatal_help "invalid operation mode '$opt_mode'" if test -n "$exec_cmd"; then eval exec "$exec_cmd" exit $EXIT_FAILURE fi exit $exit_status # The TAGs below are defined such that we never get into a situation # where we disable both kinds of libraries. Given conflicting # choices, we go for a static library, that is the most portable, # since we can't tell whether shared libraries were disabled because # the user asked for that or because the platform doesn't support # them. This is particularly important on AIX, because we don't # support having both static and shared libraries enabled at the same # time on that platform, so we default to a shared-only configuration. # If a disable-shared tag is given, we'll fallback to a static-only # configuration. But we'll never go from static-only to shared-only. # ### BEGIN LIBTOOL TAG CONFIG: disable-shared build_libtool_libs=no build_old_libs=yes # ### END LIBTOOL TAG CONFIG: disable-shared # ### BEGIN LIBTOOL TAG CONFIG: disable-static build_old_libs=`case $build_libtool_libs in yes) echo no;; *) echo yes;; esac` # ### END LIBTOOL TAG CONFIG: disable-static # Local Variables: # mode:shell-script # sh-indentation:2 # End: heimdal-7.5.0/lib/libedit/configure.ac0000644000175000017500000000465513026237312015733 0ustar niknik# -*- Autoconf -*- # Process this file with autoconf to produce a configure script. # # Compile with debug symbols: # CFLAGS="-ggdb -pedandic -O0" ./configure # CFLAGS="-ggdb -Wall -Wextra -pedantic -O0" ./configure # # Verbose output can be enabled with # "./configure --disable-silent-rules" or "make V=1" # AC_PREREQ(2.61) AC_INIT(libedit, [EL_RELEASE],, libedit-[EL_TIMESTAMP]) AC_CONFIG_SRCDIR([src/el.c]) AC_CONFIG_HEADER([config.h]) # features of Posix that are extensions to C (define _GNU_SOURCE) AC_USE_SYSTEM_EXTENSIONS AM_INIT_AUTOMAKE AC_PROG_LIBTOOL # libtool -version-info AC_SUBST(LT_VERSION, [0:36:0]) m4_ifdef([AM_SILENT_RULES], [AM_SILENT_RULES([yes])]) # Checks for programs. AC_PROG_CC_C99 #AC_PROG_CC AC_PROG_LN_S AC_PROG_AWK EL_MANTYPE AC_CHECK_LIB(curses, tgetent,, [AC_CHECK_LIB(ncurses, tgetent,, [AC_MSG_ERROR([libcurses or libncurses are required!])] )] ) # Checks for header files. AC_HEADER_DIRENT AC_HEADER_STDC AC_HEADER_SYS_WAIT AC_CHECK_HEADERS([fcntl.h limits.h stdint.h stdlib.h string.h sys/ioctl.h sys/param.h unistd.h curses.h ncurses.h sys/cdefs.h]) AC_CHECK_HEADER([termios.h], [], [AC_MSG_ERROR([termios.h is required!])],[]) ## include curses.h to prevent "Present But Cannot Be Compiled" AC_CHECK_HEADERS([term.h],,, [[#if HAVE_CURSES_H # include #elif HAVE_NCURSES_H # include #endif ]]) # Checks for typedefs, structures, and compiler characteristics. AC_C_CONST AC_TYPE_PID_T AC_TYPE_SIZE_T AC_CHECK_TYPES([u_int32_t]) AC_TRY_COMPILE([ #include #include #if HAVE_STDINT_H # include #endif ], [size_t x = SIZE_MAX;], [have_size_max=yes], [have_size_max=no]) if test "$have_size_max" = yes; then AC_DEFINE([HAVE_SIZE_MAX], [1], [Define to 1 if if your system has SIZE_MAX]) fi # Checks for library functions. AC_FUNC_FORK AC_PROG_GCC_TRADITIONAL ## _AIX is offended by rpl_malloc and rpl_realloc #AC_FUNC_MALLOC #AC_FUNC_REALLOC AC_TYPE_SIGNAL AC_FUNC_STAT AC_CHECK_FUNCS([getline isascii issetugid wcsdup]) EL_GETPW_R_POSIX EL_GETPW_R_DRAFT AC_CHECK_MEMBER(struct dirent.d_namlen, AC_DEFINE([HAVE_STRUCT_DIRENT_D_NAMLEN],[1], [Define to 1 if struct dirent has member d_namlen]),, [#if HAVE_DIRENT_H #include #endif ]) AH_BOTTOM([ #include "sys.h" #define SCCSID #undef LIBC_SCCS #define lint ]) AC_CONFIG_FILES([Makefile src/Makefile ]) AC_OUTPUT heimdal-7.5.0/lib/libedit/install-sh0000755000175000017500000003452413212444505015450 0ustar niknik#!/bin/sh # install - install a program, script, or datafile scriptversion=2016-01-11.22; # UTC # This originates from X11R5 (mit/util/scripts/install.sh), which was # later released in X11R6 (xc/config/util/install.sh) with the # following copyright and license. # # Copyright (C) 1994 X Consortium # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to # deal in the Software without restriction, including without limitation the # rights to use, copy, modify, merge, publish, distribute, sublicense, and/or # sell copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # X CONSORTIUM BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN # AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNEC- # TION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # # Except as contained in this notice, the name of the X Consortium shall not # be used in advertising or otherwise to promote the sale, use or other deal- # ings in this Software without prior written authorization from the X Consor- # tium. # # # FSF changes to this file are in the public domain. # # Calling this script install-sh is preferred over install.sh, to prevent # 'make' implicit rules from creating a file called install from it # when there is no Makefile. # # This script is compatible with the BSD install script, but was written # from scratch. tab=' ' nl=' ' IFS=" $tab$nl" # Set DOITPROG to "echo" to test this script. doit=${DOITPROG-} doit_exec=${doit:-exec} # Put in absolute file names if you don't have them in your path; # or use environment vars. chgrpprog=${CHGRPPROG-chgrp} chmodprog=${CHMODPROG-chmod} chownprog=${CHOWNPROG-chown} cmpprog=${CMPPROG-cmp} cpprog=${CPPROG-cp} mkdirprog=${MKDIRPROG-mkdir} mvprog=${MVPROG-mv} rmprog=${RMPROG-rm} stripprog=${STRIPPROG-strip} posix_mkdir= # Desired mode of installed file. mode=0755 chgrpcmd= chmodcmd=$chmodprog chowncmd= mvcmd=$mvprog rmcmd="$rmprog -f" stripcmd= src= dst= dir_arg= dst_arg= copy_on_change=false is_target_a_directory=possibly usage="\ Usage: $0 [OPTION]... [-T] SRCFILE DSTFILE or: $0 [OPTION]... SRCFILES... DIRECTORY or: $0 [OPTION]... -t DIRECTORY SRCFILES... or: $0 [OPTION]... -d DIRECTORIES... In the 1st form, copy SRCFILE to DSTFILE. In the 2nd and 3rd, copy all SRCFILES to DIRECTORY. In the 4th, create DIRECTORIES. Options: --help display this help and exit. --version display version info and exit. -c (ignored) -C install only if different (preserve the last data modification time) -d create directories instead of installing files. -g GROUP $chgrpprog installed files to GROUP. -m MODE $chmodprog installed files to MODE. -o USER $chownprog installed files to USER. -s $stripprog installed files. -t DIRECTORY install into DIRECTORY. -T report an error if DSTFILE is a directory. Environment variables override the default commands: CHGRPPROG CHMODPROG CHOWNPROG CMPPROG CPPROG MKDIRPROG MVPROG RMPROG STRIPPROG " while test $# -ne 0; do case $1 in -c) ;; -C) copy_on_change=true;; -d) dir_arg=true;; -g) chgrpcmd="$chgrpprog $2" shift;; --help) echo "$usage"; exit $?;; -m) mode=$2 case $mode in *' '* | *"$tab"* | *"$nl"* | *'*'* | *'?'* | *'['*) echo "$0: invalid mode: $mode" >&2 exit 1;; esac shift;; -o) chowncmd="$chownprog $2" shift;; -s) stripcmd=$stripprog;; -t) is_target_a_directory=always dst_arg=$2 # Protect names problematic for 'test' and other utilities. case $dst_arg in -* | [=\(\)!]) dst_arg=./$dst_arg;; esac shift;; -T) is_target_a_directory=never;; --version) echo "$0 $scriptversion"; exit $?;; --) shift break;; -*) echo "$0: invalid option: $1" >&2 exit 1;; *) break;; esac shift done # We allow the use of options -d and -T together, by making -d # take the precedence; this is for compatibility with GNU install. if test -n "$dir_arg"; then if test -n "$dst_arg"; then echo "$0: target directory not allowed when installing a directory." >&2 exit 1 fi fi if test $# -ne 0 && test -z "$dir_arg$dst_arg"; then # When -d is used, all remaining arguments are directories to create. # When -t is used, the destination is already specified. # Otherwise, the last argument is the destination. Remove it from $@. for arg do if test -n "$dst_arg"; then # $@ is not empty: it contains at least $arg. set fnord "$@" "$dst_arg" shift # fnord fi shift # arg dst_arg=$arg # Protect names problematic for 'test' and other utilities. case $dst_arg in -* | [=\(\)!]) dst_arg=./$dst_arg;; esac done fi if test $# -eq 0; then if test -z "$dir_arg"; then echo "$0: no input file specified." >&2 exit 1 fi # It's OK to call 'install-sh -d' without argument. # This can happen when creating conditional directories. exit 0 fi if test -z "$dir_arg"; then if test $# -gt 1 || test "$is_target_a_directory" = always; then if test ! -d "$dst_arg"; then echo "$0: $dst_arg: Is not a directory." >&2 exit 1 fi fi fi if test -z "$dir_arg"; then do_exit='(exit $ret); exit $ret' trap "ret=129; $do_exit" 1 trap "ret=130; $do_exit" 2 trap "ret=141; $do_exit" 13 trap "ret=143; $do_exit" 15 # Set umask so as not to create temps with too-generous modes. # However, 'strip' requires both read and write access to temps. case $mode in # Optimize common cases. *644) cp_umask=133;; *755) cp_umask=22;; *[0-7]) if test -z "$stripcmd"; then u_plus_rw= else u_plus_rw='% 200' fi cp_umask=`expr '(' 777 - $mode % 1000 ')' $u_plus_rw`;; *) if test -z "$stripcmd"; then u_plus_rw= else u_plus_rw=,u+rw fi cp_umask=$mode$u_plus_rw;; esac fi for src do # Protect names problematic for 'test' and other utilities. case $src in -* | [=\(\)!]) src=./$src;; esac if test -n "$dir_arg"; then dst=$src dstdir=$dst test -d "$dstdir" dstdir_status=$? else # Waiting for this to be detected by the "$cpprog $src $dsttmp" command # might cause directories to be created, which would be especially bad # if $src (and thus $dsttmp) contains '*'. if test ! -f "$src" && test ! -d "$src"; then echo "$0: $src does not exist." >&2 exit 1 fi if test -z "$dst_arg"; then echo "$0: no destination specified." >&2 exit 1 fi dst=$dst_arg # If destination is a directory, append the input filename; won't work # if double slashes aren't ignored. if test -d "$dst"; then if test "$is_target_a_directory" = never; then echo "$0: $dst_arg: Is a directory" >&2 exit 1 fi dstdir=$dst dst=$dstdir/`basename "$src"` dstdir_status=0 else dstdir=`dirname "$dst"` test -d "$dstdir" dstdir_status=$? fi fi obsolete_mkdir_used=false if test $dstdir_status != 0; then case $posix_mkdir in '') # Create intermediate dirs using mode 755 as modified by the umask. # This is like FreeBSD 'install' as of 1997-10-28. umask=`umask` case $stripcmd.$umask in # Optimize common cases. *[2367][2367]) mkdir_umask=$umask;; .*0[02][02] | .[02][02] | .[02]) mkdir_umask=22;; *[0-7]) mkdir_umask=`expr $umask + 22 \ - $umask % 100 % 40 + $umask % 20 \ - $umask % 10 % 4 + $umask % 2 `;; *) mkdir_umask=$umask,go-w;; esac # With -d, create the new directory with the user-specified mode. # Otherwise, rely on $mkdir_umask. if test -n "$dir_arg"; then mkdir_mode=-m$mode else mkdir_mode= fi posix_mkdir=false case $umask in *[123567][0-7][0-7]) # POSIX mkdir -p sets u+wx bits regardless of umask, which # is incompatible with FreeBSD 'install' when (umask & 300) != 0. ;; *) tmpdir=${TMPDIR-/tmp}/ins$RANDOM-$$ trap 'ret=$?; rmdir "$tmpdir/d" "$tmpdir" 2>/dev/null; exit $ret' 0 if (umask $mkdir_umask && exec $mkdirprog $mkdir_mode -p -- "$tmpdir/d") >/dev/null 2>&1 then if test -z "$dir_arg" || { # Check for POSIX incompatibilities with -m. # HP-UX 11.23 and IRIX 6.5 mkdir -m -p sets group- or # other-writable bit of parent directory when it shouldn't. # FreeBSD 6.1 mkdir -m -p sets mode of existing directory. ls_ld_tmpdir=`ls -ld "$tmpdir"` case $ls_ld_tmpdir in d????-?r-*) different_mode=700;; d????-?--*) different_mode=755;; *) false;; esac && $mkdirprog -m$different_mode -p -- "$tmpdir" && { ls_ld_tmpdir_1=`ls -ld "$tmpdir"` test "$ls_ld_tmpdir" = "$ls_ld_tmpdir_1" } } then posix_mkdir=: fi rmdir "$tmpdir/d" "$tmpdir" else # Remove any dirs left behind by ancient mkdir implementations. rmdir ./$mkdir_mode ./-p ./-- 2>/dev/null fi trap '' 0;; esac;; esac if $posix_mkdir && ( umask $mkdir_umask && $doit_exec $mkdirprog $mkdir_mode -p -- "$dstdir" ) then : else # The umask is ridiculous, or mkdir does not conform to POSIX, # or it failed possibly due to a race condition. Create the # directory the slow way, step by step, checking for races as we go. case $dstdir in /*) prefix='/';; [-=\(\)!]*) prefix='./';; *) prefix='';; esac oIFS=$IFS IFS=/ set -f set fnord $dstdir shift set +f IFS=$oIFS prefixes= for d do test X"$d" = X && continue prefix=$prefix$d if test -d "$prefix"; then prefixes= else if $posix_mkdir; then (umask=$mkdir_umask && $doit_exec $mkdirprog $mkdir_mode -p -- "$dstdir") && break # Don't fail if two instances are running concurrently. test -d "$prefix" || exit 1 else case $prefix in *\'*) qprefix=`echo "$prefix" | sed "s/'/'\\\\\\\\''/g"`;; *) qprefix=$prefix;; esac prefixes="$prefixes '$qprefix'" fi fi prefix=$prefix/ done if test -n "$prefixes"; then # Don't fail if two instances are running concurrently. (umask $mkdir_umask && eval "\$doit_exec \$mkdirprog $prefixes") || test -d "$dstdir" || exit 1 obsolete_mkdir_used=true fi fi fi if test -n "$dir_arg"; then { test -z "$chowncmd" || $doit $chowncmd "$dst"; } && { test -z "$chgrpcmd" || $doit $chgrpcmd "$dst"; } && { test "$obsolete_mkdir_used$chowncmd$chgrpcmd" = false || test -z "$chmodcmd" || $doit $chmodcmd $mode "$dst"; } || exit 1 else # Make a couple of temp file names in the proper directory. dsttmp=$dstdir/_inst.$$_ rmtmp=$dstdir/_rm.$$_ # Trap to clean up those temp files at exit. trap 'ret=$?; rm -f "$dsttmp" "$rmtmp" && exit $ret' 0 # Copy the file name to the temp name. (umask $cp_umask && $doit_exec $cpprog "$src" "$dsttmp") && # and set any options; do chmod last to preserve setuid bits. # # If any of these fail, we abort the whole thing. If we want to # ignore errors from any of these, just make sure not to ignore # errors from the above "$doit $cpprog $src $dsttmp" command. # { test -z "$chowncmd" || $doit $chowncmd "$dsttmp"; } && { test -z "$chgrpcmd" || $doit $chgrpcmd "$dsttmp"; } && { test -z "$stripcmd" || $doit $stripcmd "$dsttmp"; } && { test -z "$chmodcmd" || $doit $chmodcmd $mode "$dsttmp"; } && # If -C, don't bother to copy if it wouldn't change the file. if $copy_on_change && old=`LC_ALL=C ls -dlL "$dst" 2>/dev/null` && new=`LC_ALL=C ls -dlL "$dsttmp" 2>/dev/null` && set -f && set X $old && old=:$2:$4:$5:$6 && set X $new && new=:$2:$4:$5:$6 && set +f && test "$old" = "$new" && $cmpprog "$dst" "$dsttmp" >/dev/null 2>&1 then rm -f "$dsttmp" else # Rename the file to the real destination. $doit $mvcmd -f "$dsttmp" "$dst" 2>/dev/null || # The rename failed, perhaps because mv can't rename something else # to itself, or perhaps because mv is so ancient that it does not # support -f. { # Now remove or move aside any old file at destination location. # We try this two ways since rm can't unlink itself on some # systems and the destination file might be busy for other # reasons. In this case, the final cleanup might fail but the new # file should still install successfully. { test ! -f "$dst" || $doit $rmcmd -f "$dst" 2>/dev/null || { $doit $mvcmd -f "$dst" "$rmtmp" 2>/dev/null && { $doit $rmcmd -f "$rmtmp" 2>/dev/null; :; } } || { echo "$0: cannot unlink or rename $dst" >&2 (exit 1); exit 1 } } && # Now rename the file to the real destination. $doit $mvcmd "$dsttmp" "$dst" } fi || exit 1 trap '' 0 fi done # Local variables: # eval: (add-hook 'write-file-hooks 'time-stamp) # time-stamp-start: "scriptversion=" # time-stamp-format: "%:y-%02m-%02d.%02H" # time-stamp-time-zone: "UTC0" # time-stamp-end: "; # UTC" # End: heimdal-7.5.0/lib/libedit/acinclude.m40000644000175000017500000000446313026237312015633 0ustar niknik dnl dnl read lib version from file (and trim trailing newline) dnl define([EL_RELEASE], [patsubst(esyscmd([. src/shlib_version; echo $major.$minor]), [ ])]) dnl dnl read cvsexport timestamp from file (and trim trailing newline) dnl define([EL_TIMESTAMP], [patsubst(esyscmd([date +"%Y%m%d"]), [ ])]) dnl dnl NetBSD use the -mdoc macro package for manpages, but e.g. dnl AIX and Solaris only support the -man package. dnl AC_DEFUN([EL_MANTYPE], [ MANTYPE= TestPath="/usr/bin${PATH_SEPARATOR}/usr/ucb" AC_PATH_PROGS(NROFF, nroff awf, /bin/false, $TestPath) if ${NROFF} -mdoc ${srcdir}/doc/editrc.5.roff >/dev/null 2>&1; then MANTYPE=mdoc fi AC_SUBST(MANTYPE) ]) dnl dnl Check if getpwnam_r and getpwuid_r are POSIX.1 compatible dnl POSIX draft version returns 'struct passwd *' (used on Solaris) dnl NOTE: getpwent_r is not POSIX so we always use getpwent dnl AC_DEFUN([EL_GETPW_R_POSIX], [ AC_MSG_CHECKING([whether getpwnam_r and getpwuid_r are posix like]) # The prototype for the POSIX version is: # int getpwnam_r(char *, struct passwd *, char *, size_t, struct passwd **) # int getpwuid_r(uid_t, struct passwd *, char *, size_t, struct passwd **); AC_TRY_LINK([#include #include #include ], [getpwnam_r(NULL, NULL, NULL, (size_t)0, NULL); getpwuid_r((uid_t)0, NULL, NULL, (size_t)0, NULL);], [AC_DEFINE([HAVE_GETPW_R_POSIX], 1, [Define to 1 if you have getpwnam_r and getpwuid_r that are POSIX.1 compatible.]) AC_MSG_RESULT(yes)], [AC_MSG_RESULT(no)]) ]) AC_DEFUN([EL_GETPW_R_DRAFT], [ AC_MSG_CHECKING([whether getpwnam_r and getpwuid_r are posix _draft_ like]) # The prototype for the POSIX draft version is: # struct passwd *getpwuid_r(uid_t, struct passwd *, char *, int); # struct passwd *getpwnam_r(char *, struct passwd *, char *, int); AC_TRY_LINK([#include #include #include ], [getpwnam_r(NULL, NULL, NULL, (size_t)0); getpwuid_r((uid_t)0, NULL, NULL, (size_t)0);], [AC_DEFINE([HAVE_GETPW_R_DRAFT], 1, [Define to 1 if you have getpwnam_r and getpwuid_r that are draft POSIX.1 versions.]) AC_MSG_RESULT(yes)], [AC_MSG_RESULT(no)]) ]) heimdal-7.5.0/lib/sqlite/0000755000175000017500000000000013214604041013314 5ustar niknikheimdal-7.5.0/lib/sqlite/sqlite3ext.h0000644000175000017500000007246413050357006015613 0ustar niknik/* ** 2006 June 7 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ************************************************************************* ** This header file defines the SQLite interface for use by ** shared libraries that want to be imported as extensions into ** an SQLite instance. Shared libraries that intend to be loaded ** as extensions by SQLite should #include this file instead of ** sqlite3.h. */ #ifndef SQLITE3EXT_H #define SQLITE3EXT_H #include "sqlite3.h" /* ** The following structure holds pointers to all of the SQLite API ** routines. ** ** WARNING: In order to maintain backwards compatibility, add new ** interfaces to the end of this structure only. If you insert new ** interfaces in the middle of this structure, then older different ** versions of SQLite will not be able to load each other's shared ** libraries! */ struct sqlite3_api_routines { void * (*aggregate_context)(sqlite3_context*,int nBytes); int (*aggregate_count)(sqlite3_context*); int (*bind_blob)(sqlite3_stmt*,int,const void*,int n,void(*)(void*)); int (*bind_double)(sqlite3_stmt*,int,double); int (*bind_int)(sqlite3_stmt*,int,int); int (*bind_int64)(sqlite3_stmt*,int,sqlite_int64); int (*bind_null)(sqlite3_stmt*,int); int (*bind_parameter_count)(sqlite3_stmt*); int (*bind_parameter_index)(sqlite3_stmt*,const char*zName); const char * (*bind_parameter_name)(sqlite3_stmt*,int); int (*bind_text)(sqlite3_stmt*,int,const char*,int n,void(*)(void*)); int (*bind_text16)(sqlite3_stmt*,int,const void*,int,void(*)(void*)); int (*bind_value)(sqlite3_stmt*,int,const sqlite3_value*); int (*busy_handler)(sqlite3*,int(*)(void*,int),void*); int (*busy_timeout)(sqlite3*,int ms); int (*changes)(sqlite3*); int (*close)(sqlite3*); int (*collation_needed)(sqlite3*,void*,void(*)(void*,sqlite3*, int eTextRep,const char*)); int (*collation_needed16)(sqlite3*,void*,void(*)(void*,sqlite3*, int eTextRep,const void*)); const void * (*column_blob)(sqlite3_stmt*,int iCol); int (*column_bytes)(sqlite3_stmt*,int iCol); int (*column_bytes16)(sqlite3_stmt*,int iCol); int (*column_count)(sqlite3_stmt*pStmt); const char * (*column_database_name)(sqlite3_stmt*,int); const void * (*column_database_name16)(sqlite3_stmt*,int); const char * (*column_decltype)(sqlite3_stmt*,int i); const void * (*column_decltype16)(sqlite3_stmt*,int); double (*column_double)(sqlite3_stmt*,int iCol); int (*column_int)(sqlite3_stmt*,int iCol); sqlite_int64 (*column_int64)(sqlite3_stmt*,int iCol); const char * (*column_name)(sqlite3_stmt*,int); const void * (*column_name16)(sqlite3_stmt*,int); const char * (*column_origin_name)(sqlite3_stmt*,int); const void * (*column_origin_name16)(sqlite3_stmt*,int); const char * (*column_table_name)(sqlite3_stmt*,int); const void * (*column_table_name16)(sqlite3_stmt*,int); const unsigned char * (*column_text)(sqlite3_stmt*,int iCol); const void * (*column_text16)(sqlite3_stmt*,int iCol); int (*column_type)(sqlite3_stmt*,int iCol); sqlite3_value* (*column_value)(sqlite3_stmt*,int iCol); void * (*commit_hook)(sqlite3*,int(*)(void*),void*); int (*complete)(const char*sql); int (*complete16)(const void*sql); int (*create_collation)(sqlite3*,const char*,int,void*, int(*)(void*,int,const void*,int,const void*)); int (*create_collation16)(sqlite3*,const void*,int,void*, int(*)(void*,int,const void*,int,const void*)); int (*create_function)(sqlite3*,const char*,int,int,void*, void (*xFunc)(sqlite3_context*,int,sqlite3_value**), void (*xStep)(sqlite3_context*,int,sqlite3_value**), void (*xFinal)(sqlite3_context*)); int (*create_function16)(sqlite3*,const void*,int,int,void*, void (*xFunc)(sqlite3_context*,int,sqlite3_value**), void (*xStep)(sqlite3_context*,int,sqlite3_value**), void (*xFinal)(sqlite3_context*)); int (*create_module)(sqlite3*,const char*,const sqlite3_module*,void*); int (*data_count)(sqlite3_stmt*pStmt); sqlite3 * (*db_handle)(sqlite3_stmt*); int (*declare_vtab)(sqlite3*,const char*); int (*enable_shared_cache)(int); int (*errcode)(sqlite3*db); const char * (*errmsg)(sqlite3*); const void * (*errmsg16)(sqlite3*); int (*exec)(sqlite3*,const char*,sqlite3_callback,void*,char**); int (*expired)(sqlite3_stmt*); int (*finalize)(sqlite3_stmt*pStmt); void (*free)(void*); void (*free_table)(char**result); int (*get_autocommit)(sqlite3*); void * (*get_auxdata)(sqlite3_context*,int); int (*get_table)(sqlite3*,const char*,char***,int*,int*,char**); int (*global_recover)(void); void (*interruptx)(sqlite3*); sqlite_int64 (*last_insert_rowid)(sqlite3*); const char * (*libversion)(void); int (*libversion_number)(void); void *(*malloc)(int); char * (*mprintf)(const char*,...); int (*open)(const char*,sqlite3**); int (*open16)(const void*,sqlite3**); int (*prepare)(sqlite3*,const char*,int,sqlite3_stmt**,const char**); int (*prepare16)(sqlite3*,const void*,int,sqlite3_stmt**,const void**); void * (*profile)(sqlite3*,void(*)(void*,const char*,sqlite_uint64),void*); void (*progress_handler)(sqlite3*,int,int(*)(void*),void*); void *(*realloc)(void*,int); int (*reset)(sqlite3_stmt*pStmt); void (*result_blob)(sqlite3_context*,const void*,int,void(*)(void*)); void (*result_double)(sqlite3_context*,double); void (*result_error)(sqlite3_context*,const char*,int); void (*result_error16)(sqlite3_context*,const void*,int); void (*result_int)(sqlite3_context*,int); void (*result_int64)(sqlite3_context*,sqlite_int64); void (*result_null)(sqlite3_context*); void (*result_text)(sqlite3_context*,const char*,int,void(*)(void*)); void (*result_text16)(sqlite3_context*,const void*,int,void(*)(void*)); void (*result_text16be)(sqlite3_context*,const void*,int,void(*)(void*)); void (*result_text16le)(sqlite3_context*,const void*,int,void(*)(void*)); void (*result_value)(sqlite3_context*,sqlite3_value*); void * (*rollback_hook)(sqlite3*,void(*)(void*),void*); int (*set_authorizer)(sqlite3*,int(*)(void*,int,const char*,const char*, const char*,const char*),void*); void (*set_auxdata)(sqlite3_context*,int,void*,void (*)(void*)); char * (*snprintf)(int,char*,const char*,...); int (*step)(sqlite3_stmt*); int (*table_column_metadata)(sqlite3*,const char*,const char*,const char*, char const**,char const**,int*,int*,int*); void (*thread_cleanup)(void); int (*total_changes)(sqlite3*); void * (*trace)(sqlite3*,void(*xTrace)(void*,const char*),void*); int (*transfer_bindings)(sqlite3_stmt*,sqlite3_stmt*); void * (*update_hook)(sqlite3*,void(*)(void*,int ,char const*,char const*, sqlite_int64),void*); void * (*user_data)(sqlite3_context*); const void * (*value_blob)(sqlite3_value*); int (*value_bytes)(sqlite3_value*); int (*value_bytes16)(sqlite3_value*); double (*value_double)(sqlite3_value*); int (*value_int)(sqlite3_value*); sqlite_int64 (*value_int64)(sqlite3_value*); int (*value_numeric_type)(sqlite3_value*); const unsigned char * (*value_text)(sqlite3_value*); const void * (*value_text16)(sqlite3_value*); const void * (*value_text16be)(sqlite3_value*); const void * (*value_text16le)(sqlite3_value*); int (*value_type)(sqlite3_value*); char *(*vmprintf)(const char*,va_list); /* Added ??? */ int (*overload_function)(sqlite3*, const char *zFuncName, int nArg); /* Added by 3.3.13 */ int (*prepare_v2)(sqlite3*,const char*,int,sqlite3_stmt**,const char**); int (*prepare16_v2)(sqlite3*,const void*,int,sqlite3_stmt**,const void**); int (*clear_bindings)(sqlite3_stmt*); /* Added by 3.4.1 */ int (*create_module_v2)(sqlite3*,const char*,const sqlite3_module*,void*, void (*xDestroy)(void *)); /* Added by 3.5.0 */ int (*bind_zeroblob)(sqlite3_stmt*,int,int); int (*blob_bytes)(sqlite3_blob*); int (*blob_close)(sqlite3_blob*); int (*blob_open)(sqlite3*,const char*,const char*,const char*,sqlite3_int64, int,sqlite3_blob**); int (*blob_read)(sqlite3_blob*,void*,int,int); int (*blob_write)(sqlite3_blob*,const void*,int,int); int (*create_collation_v2)(sqlite3*,const char*,int,void*, int(*)(void*,int,const void*,int,const void*), void(*)(void*)); int (*file_control)(sqlite3*,const char*,int,void*); sqlite3_int64 (*memory_highwater)(int); sqlite3_int64 (*memory_used)(void); sqlite3_mutex *(*mutex_alloc)(int); void (*mutex_enter)(sqlite3_mutex*); void (*mutex_free)(sqlite3_mutex*); void (*mutex_leave)(sqlite3_mutex*); int (*mutex_try)(sqlite3_mutex*); int (*open_v2)(const char*,sqlite3**,int,const char*); int (*release_memory)(int); void (*result_error_nomem)(sqlite3_context*); void (*result_error_toobig)(sqlite3_context*); int (*sleep)(int); void (*soft_heap_limit)(int); sqlite3_vfs *(*vfs_find)(const char*); int (*vfs_register)(sqlite3_vfs*,int); int (*vfs_unregister)(sqlite3_vfs*); int (*xthreadsafe)(void); void (*result_zeroblob)(sqlite3_context*,int); void (*result_error_code)(sqlite3_context*,int); int (*test_control)(int, ...); void (*randomness)(int,void*); sqlite3 *(*context_db_handle)(sqlite3_context*); int (*extended_result_codes)(sqlite3*,int); int (*limit)(sqlite3*,int,int); sqlite3_stmt *(*next_stmt)(sqlite3*,sqlite3_stmt*); const char *(*sql)(sqlite3_stmt*); int (*status)(int,int*,int*,int); int (*backup_finish)(sqlite3_backup*); sqlite3_backup *(*backup_init)(sqlite3*,const char*,sqlite3*,const char*); int (*backup_pagecount)(sqlite3_backup*); int (*backup_remaining)(sqlite3_backup*); int (*backup_step)(sqlite3_backup*,int); const char *(*compileoption_get)(int); int (*compileoption_used)(const char*); int (*create_function_v2)(sqlite3*,const char*,int,int,void*, void (*xFunc)(sqlite3_context*,int,sqlite3_value**), void (*xStep)(sqlite3_context*,int,sqlite3_value**), void (*xFinal)(sqlite3_context*), void(*xDestroy)(void*)); int (*db_config)(sqlite3*,int,...); sqlite3_mutex *(*db_mutex)(sqlite3*); int (*db_status)(sqlite3*,int,int*,int*,int); int (*extended_errcode)(sqlite3*); void (*log)(int,const char*,...); sqlite3_int64 (*soft_heap_limit64)(sqlite3_int64); const char *(*sourceid)(void); int (*stmt_status)(sqlite3_stmt*,int,int); int (*strnicmp)(const char*,const char*,int); int (*unlock_notify)(sqlite3*,void(*)(void**,int),void*); int (*wal_autocheckpoint)(sqlite3*,int); int (*wal_checkpoint)(sqlite3*,const char*); void *(*wal_hook)(sqlite3*,int(*)(void*,sqlite3*,const char*,int),void*); int (*blob_reopen)(sqlite3_blob*,sqlite3_int64); int (*vtab_config)(sqlite3*,int op,...); int (*vtab_on_conflict)(sqlite3*); /* Version 3.7.16 and later */ int (*close_v2)(sqlite3*); const char *(*db_filename)(sqlite3*,const char*); int (*db_readonly)(sqlite3*,const char*); int (*db_release_memory)(sqlite3*); const char *(*errstr)(int); int (*stmt_busy)(sqlite3_stmt*); int (*stmt_readonly)(sqlite3_stmt*); int (*stricmp)(const char*,const char*); int (*uri_boolean)(const char*,const char*,int); sqlite3_int64 (*uri_int64)(const char*,const char*,sqlite3_int64); const char *(*uri_parameter)(const char*,const char*); char *(*vsnprintf)(int,char*,const char*,va_list); int (*wal_checkpoint_v2)(sqlite3*,const char*,int,int*,int*); /* Version 3.8.7 and later */ int (*auto_extension)(void(*)(void)); int (*bind_blob64)(sqlite3_stmt*,int,const void*,sqlite3_uint64, void(*)(void*)); int (*bind_text64)(sqlite3_stmt*,int,const char*,sqlite3_uint64, void(*)(void*),unsigned char); int (*cancel_auto_extension)(void(*)(void)); int (*load_extension)(sqlite3*,const char*,const char*,char**); void *(*malloc64)(sqlite3_uint64); sqlite3_uint64 (*msize)(void*); void *(*realloc64)(void*,sqlite3_uint64); void (*reset_auto_extension)(void); void (*result_blob64)(sqlite3_context*,const void*,sqlite3_uint64, void(*)(void*)); void (*result_text64)(sqlite3_context*,const char*,sqlite3_uint64, void(*)(void*), unsigned char); int (*strglob)(const char*,const char*); /* Version 3.8.11 and later */ sqlite3_value *(*value_dup)(const sqlite3_value*); void (*value_free)(sqlite3_value*); int (*result_zeroblob64)(sqlite3_context*,sqlite3_uint64); int (*bind_zeroblob64)(sqlite3_stmt*, int, sqlite3_uint64); /* Version 3.9.0 and later */ unsigned int (*value_subtype)(sqlite3_value*); void (*result_subtype)(sqlite3_context*,unsigned int); /* Version 3.10.0 and later */ int (*status64)(int,sqlite3_int64*,sqlite3_int64*,int); int (*strlike)(const char*,const char*,unsigned int); int (*db_cacheflush)(sqlite3*); /* Version 3.12.0 and later */ int (*system_errno)(sqlite3*); /* Version 3.14.0 and later */ int (*trace_v2)(sqlite3*,unsigned,int(*)(unsigned,void*,void*,void*),void*); char *(*expanded_sql)(sqlite3_stmt*); }; /* ** This is the function signature used for all extension entry points. It ** is also defined in the file "loadext.c". */ typedef int (*sqlite3_loadext_entry)( sqlite3 *db, /* Handle to the database. */ char **pzErrMsg, /* Used to set error string on failure. */ const sqlite3_api_routines *pThunk /* Extension API function pointers. */ ); /* ** The following macros redefine the API routines so that they are ** redirected through the global sqlite3_api structure. ** ** This header file is also used by the loadext.c source file ** (part of the main SQLite library - not an extension) so that ** it can get access to the sqlite3_api_routines structure ** definition. But the main library does not want to redefine ** the API. So the redefinition macros are only valid if the ** SQLITE_CORE macros is undefined. */ #if !defined(SQLITE_CORE) && !defined(SQLITE_OMIT_LOAD_EXTENSION) #define sqlite3_aggregate_context sqlite3_api->aggregate_context #ifndef SQLITE_OMIT_DEPRECATED #define sqlite3_aggregate_count sqlite3_api->aggregate_count #endif #define sqlite3_bind_blob sqlite3_api->bind_blob #define sqlite3_bind_double sqlite3_api->bind_double #define sqlite3_bind_int sqlite3_api->bind_int #define sqlite3_bind_int64 sqlite3_api->bind_int64 #define sqlite3_bind_null sqlite3_api->bind_null #define sqlite3_bind_parameter_count sqlite3_api->bind_parameter_count #define sqlite3_bind_parameter_index sqlite3_api->bind_parameter_index #define sqlite3_bind_parameter_name sqlite3_api->bind_parameter_name #define sqlite3_bind_text sqlite3_api->bind_text #define sqlite3_bind_text16 sqlite3_api->bind_text16 #define sqlite3_bind_value sqlite3_api->bind_value #define sqlite3_busy_handler sqlite3_api->busy_handler #define sqlite3_busy_timeout sqlite3_api->busy_timeout #define sqlite3_changes sqlite3_api->changes #define sqlite3_close sqlite3_api->close #define sqlite3_collation_needed sqlite3_api->collation_needed #define sqlite3_collation_needed16 sqlite3_api->collation_needed16 #define sqlite3_column_blob sqlite3_api->column_blob #define sqlite3_column_bytes sqlite3_api->column_bytes #define sqlite3_column_bytes16 sqlite3_api->column_bytes16 #define sqlite3_column_count sqlite3_api->column_count #define sqlite3_column_database_name sqlite3_api->column_database_name #define sqlite3_column_database_name16 sqlite3_api->column_database_name16 #define sqlite3_column_decltype sqlite3_api->column_decltype #define sqlite3_column_decltype16 sqlite3_api->column_decltype16 #define sqlite3_column_double sqlite3_api->column_double #define sqlite3_column_int sqlite3_api->column_int #define sqlite3_column_int64 sqlite3_api->column_int64 #define sqlite3_column_name sqlite3_api->column_name #define sqlite3_column_name16 sqlite3_api->column_name16 #define sqlite3_column_origin_name sqlite3_api->column_origin_name #define sqlite3_column_origin_name16 sqlite3_api->column_origin_name16 #define sqlite3_column_table_name sqlite3_api->column_table_name #define sqlite3_column_table_name16 sqlite3_api->column_table_name16 #define sqlite3_column_text sqlite3_api->column_text #define sqlite3_column_text16 sqlite3_api->column_text16 #define sqlite3_column_type sqlite3_api->column_type #define sqlite3_column_value sqlite3_api->column_value #define sqlite3_commit_hook sqlite3_api->commit_hook #define sqlite3_complete sqlite3_api->complete #define sqlite3_complete16 sqlite3_api->complete16 #define sqlite3_create_collation sqlite3_api->create_collation #define sqlite3_create_collation16 sqlite3_api->create_collation16 #define sqlite3_create_function sqlite3_api->create_function #define sqlite3_create_function16 sqlite3_api->create_function16 #define sqlite3_create_module sqlite3_api->create_module #define sqlite3_create_module_v2 sqlite3_api->create_module_v2 #define sqlite3_data_count sqlite3_api->data_count #define sqlite3_db_handle sqlite3_api->db_handle #define sqlite3_declare_vtab sqlite3_api->declare_vtab #define sqlite3_enable_shared_cache sqlite3_api->enable_shared_cache #define sqlite3_errcode sqlite3_api->errcode #define sqlite3_errmsg sqlite3_api->errmsg #define sqlite3_errmsg16 sqlite3_api->errmsg16 #define sqlite3_exec sqlite3_api->exec #ifndef SQLITE_OMIT_DEPRECATED #define sqlite3_expired sqlite3_api->expired #endif #define sqlite3_finalize sqlite3_api->finalize #define sqlite3_free sqlite3_api->free #define sqlite3_free_table sqlite3_api->free_table #define sqlite3_get_autocommit sqlite3_api->get_autocommit #define sqlite3_get_auxdata sqlite3_api->get_auxdata #define sqlite3_get_table sqlite3_api->get_table #ifndef SQLITE_OMIT_DEPRECATED #define sqlite3_global_recover sqlite3_api->global_recover #endif #define sqlite3_interrupt sqlite3_api->interruptx #define sqlite3_last_insert_rowid sqlite3_api->last_insert_rowid #define sqlite3_libversion sqlite3_api->libversion #define sqlite3_libversion_number sqlite3_api->libversion_number #define sqlite3_malloc sqlite3_api->malloc #define sqlite3_mprintf sqlite3_api->mprintf #define sqlite3_open sqlite3_api->open #define sqlite3_open16 sqlite3_api->open16 #define sqlite3_prepare sqlite3_api->prepare #define sqlite3_prepare16 sqlite3_api->prepare16 #define sqlite3_prepare_v2 sqlite3_api->prepare_v2 #define sqlite3_prepare16_v2 sqlite3_api->prepare16_v2 #define sqlite3_profile sqlite3_api->profile #define sqlite3_progress_handler sqlite3_api->progress_handler #define sqlite3_realloc sqlite3_api->realloc #define sqlite3_reset sqlite3_api->reset #define sqlite3_result_blob sqlite3_api->result_blob #define sqlite3_result_double sqlite3_api->result_double #define sqlite3_result_error sqlite3_api->result_error #define sqlite3_result_error16 sqlite3_api->result_error16 #define sqlite3_result_int sqlite3_api->result_int #define sqlite3_result_int64 sqlite3_api->result_int64 #define sqlite3_result_null sqlite3_api->result_null #define sqlite3_result_text sqlite3_api->result_text #define sqlite3_result_text16 sqlite3_api->result_text16 #define sqlite3_result_text16be sqlite3_api->result_text16be #define sqlite3_result_text16le sqlite3_api->result_text16le #define sqlite3_result_value sqlite3_api->result_value #define sqlite3_rollback_hook sqlite3_api->rollback_hook #define sqlite3_set_authorizer sqlite3_api->set_authorizer #define sqlite3_set_auxdata sqlite3_api->set_auxdata #define sqlite3_snprintf sqlite3_api->snprintf #define sqlite3_step sqlite3_api->step #define sqlite3_table_column_metadata sqlite3_api->table_column_metadata #define sqlite3_thread_cleanup sqlite3_api->thread_cleanup #define sqlite3_total_changes sqlite3_api->total_changes #define sqlite3_trace sqlite3_api->trace #ifndef SQLITE_OMIT_DEPRECATED #define sqlite3_transfer_bindings sqlite3_api->transfer_bindings #endif #define sqlite3_update_hook sqlite3_api->update_hook #define sqlite3_user_data sqlite3_api->user_data #define sqlite3_value_blob sqlite3_api->value_blob #define sqlite3_value_bytes sqlite3_api->value_bytes #define sqlite3_value_bytes16 sqlite3_api->value_bytes16 #define sqlite3_value_double sqlite3_api->value_double #define sqlite3_value_int sqlite3_api->value_int #define sqlite3_value_int64 sqlite3_api->value_int64 #define sqlite3_value_numeric_type sqlite3_api->value_numeric_type #define sqlite3_value_text sqlite3_api->value_text #define sqlite3_value_text16 sqlite3_api->value_text16 #define sqlite3_value_text16be sqlite3_api->value_text16be #define sqlite3_value_text16le sqlite3_api->value_text16le #define sqlite3_value_type sqlite3_api->value_type #define sqlite3_vmprintf sqlite3_api->vmprintf #define sqlite3_vsnprintf sqlite3_api->vsnprintf #define sqlite3_overload_function sqlite3_api->overload_function #define sqlite3_prepare_v2 sqlite3_api->prepare_v2 #define sqlite3_prepare16_v2 sqlite3_api->prepare16_v2 #define sqlite3_clear_bindings sqlite3_api->clear_bindings #define sqlite3_bind_zeroblob sqlite3_api->bind_zeroblob #define sqlite3_blob_bytes sqlite3_api->blob_bytes #define sqlite3_blob_close sqlite3_api->blob_close #define sqlite3_blob_open sqlite3_api->blob_open #define sqlite3_blob_read sqlite3_api->blob_read #define sqlite3_blob_write sqlite3_api->blob_write #define sqlite3_create_collation_v2 sqlite3_api->create_collation_v2 #define sqlite3_file_control sqlite3_api->file_control #define sqlite3_memory_highwater sqlite3_api->memory_highwater #define sqlite3_memory_used sqlite3_api->memory_used #define sqlite3_mutex_alloc sqlite3_api->mutex_alloc #define sqlite3_mutex_enter sqlite3_api->mutex_enter #define sqlite3_mutex_free sqlite3_api->mutex_free #define sqlite3_mutex_leave sqlite3_api->mutex_leave #define sqlite3_mutex_try sqlite3_api->mutex_try #define sqlite3_open_v2 sqlite3_api->open_v2 #define sqlite3_release_memory sqlite3_api->release_memory #define sqlite3_result_error_nomem sqlite3_api->result_error_nomem #define sqlite3_result_error_toobig sqlite3_api->result_error_toobig #define sqlite3_sleep sqlite3_api->sleep #define sqlite3_soft_heap_limit sqlite3_api->soft_heap_limit #define sqlite3_vfs_find sqlite3_api->vfs_find #define sqlite3_vfs_register sqlite3_api->vfs_register #define sqlite3_vfs_unregister sqlite3_api->vfs_unregister #define sqlite3_threadsafe sqlite3_api->xthreadsafe #define sqlite3_result_zeroblob sqlite3_api->result_zeroblob #define sqlite3_result_error_code sqlite3_api->result_error_code #define sqlite3_test_control sqlite3_api->test_control #define sqlite3_randomness sqlite3_api->randomness #define sqlite3_context_db_handle sqlite3_api->context_db_handle #define sqlite3_extended_result_codes sqlite3_api->extended_result_codes #define sqlite3_limit sqlite3_api->limit #define sqlite3_next_stmt sqlite3_api->next_stmt #define sqlite3_sql sqlite3_api->sql #define sqlite3_status sqlite3_api->status #define sqlite3_backup_finish sqlite3_api->backup_finish #define sqlite3_backup_init sqlite3_api->backup_init #define sqlite3_backup_pagecount sqlite3_api->backup_pagecount #define sqlite3_backup_remaining sqlite3_api->backup_remaining #define sqlite3_backup_step sqlite3_api->backup_step #define sqlite3_compileoption_get sqlite3_api->compileoption_get #define sqlite3_compileoption_used sqlite3_api->compileoption_used #define sqlite3_create_function_v2 sqlite3_api->create_function_v2 #define sqlite3_db_config sqlite3_api->db_config #define sqlite3_db_mutex sqlite3_api->db_mutex #define sqlite3_db_status sqlite3_api->db_status #define sqlite3_extended_errcode sqlite3_api->extended_errcode #define sqlite3_log sqlite3_api->log #define sqlite3_soft_heap_limit64 sqlite3_api->soft_heap_limit64 #define sqlite3_sourceid sqlite3_api->sourceid #define sqlite3_stmt_status sqlite3_api->stmt_status #define sqlite3_strnicmp sqlite3_api->strnicmp #define sqlite3_unlock_notify sqlite3_api->unlock_notify #define sqlite3_wal_autocheckpoint sqlite3_api->wal_autocheckpoint #define sqlite3_wal_checkpoint sqlite3_api->wal_checkpoint #define sqlite3_wal_hook sqlite3_api->wal_hook #define sqlite3_blob_reopen sqlite3_api->blob_reopen #define sqlite3_vtab_config sqlite3_api->vtab_config #define sqlite3_vtab_on_conflict sqlite3_api->vtab_on_conflict /* Version 3.7.16 and later */ #define sqlite3_close_v2 sqlite3_api->close_v2 #define sqlite3_db_filename sqlite3_api->db_filename #define sqlite3_db_readonly sqlite3_api->db_readonly #define sqlite3_db_release_memory sqlite3_api->db_release_memory #define sqlite3_errstr sqlite3_api->errstr #define sqlite3_stmt_busy sqlite3_api->stmt_busy #define sqlite3_stmt_readonly sqlite3_api->stmt_readonly #define sqlite3_stricmp sqlite3_api->stricmp #define sqlite3_uri_boolean sqlite3_api->uri_boolean #define sqlite3_uri_int64 sqlite3_api->uri_int64 #define sqlite3_uri_parameter sqlite3_api->uri_parameter #define sqlite3_uri_vsnprintf sqlite3_api->vsnprintf #define sqlite3_wal_checkpoint_v2 sqlite3_api->wal_checkpoint_v2 /* Version 3.8.7 and later */ #define sqlite3_auto_extension sqlite3_api->auto_extension #define sqlite3_bind_blob64 sqlite3_api->bind_blob64 #define sqlite3_bind_text64 sqlite3_api->bind_text64 #define sqlite3_cancel_auto_extension sqlite3_api->cancel_auto_extension #define sqlite3_load_extension sqlite3_api->load_extension #define sqlite3_malloc64 sqlite3_api->malloc64 #define sqlite3_msize sqlite3_api->msize #define sqlite3_realloc64 sqlite3_api->realloc64 #define sqlite3_reset_auto_extension sqlite3_api->reset_auto_extension #define sqlite3_result_blob64 sqlite3_api->result_blob64 #define sqlite3_result_text64 sqlite3_api->result_text64 #define sqlite3_strglob sqlite3_api->strglob /* Version 3.8.11 and later */ #define sqlite3_value_dup sqlite3_api->value_dup #define sqlite3_value_free sqlite3_api->value_free #define sqlite3_result_zeroblob64 sqlite3_api->result_zeroblob64 #define sqlite3_bind_zeroblob64 sqlite3_api->bind_zeroblob64 /* Version 3.9.0 and later */ #define sqlite3_value_subtype sqlite3_api->value_subtype #define sqlite3_result_subtype sqlite3_api->result_subtype /* Version 3.10.0 and later */ #define sqlite3_status64 sqlite3_api->status64 #define sqlite3_strlike sqlite3_api->strlike #define sqlite3_db_cacheflush sqlite3_api->db_cacheflush /* Version 3.12.0 and later */ #define sqlite3_system_errno sqlite3_api->system_errno /* Version 3.14.0 and later */ #define sqlite3_trace_v2 sqlite3_api->trace_v2 #define sqlite3_expanded_sql sqlite3_api->expanded_sql #endif /* !defined(SQLITE_CORE) && !defined(SQLITE_OMIT_LOAD_EXTENSION) */ #if !defined(SQLITE_CORE) && !defined(SQLITE_OMIT_LOAD_EXTENSION) /* This case when the file really is being compiled as a loadable ** extension */ # define SQLITE_EXTENSION_INIT1 const sqlite3_api_routines *sqlite3_api=0; # define SQLITE_EXTENSION_INIT2(v) sqlite3_api=v; # define SQLITE_EXTENSION_INIT3 \ extern const sqlite3_api_routines *sqlite3_api; #else /* This case when the file is being statically linked into the ** application */ # define SQLITE_EXTENSION_INIT1 /*no-op*/ # define SQLITE_EXTENSION_INIT2(v) (void)v; /* unused parameter */ # define SQLITE_EXTENSION_INIT3 /*no-op*/ #endif #endif /* SQLITE3EXT_H */ heimdal-7.5.0/lib/sqlite/sqlite3.h0000644000175000017500000167736313212137553015107 0ustar niknik/* ** 2001 September 15 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ************************************************************************* ** This header file defines the interface that the SQLite library ** presents to client programs. If a C-function, structure, datatype, ** or constant definition does not appear in this file, then it is ** not a published API of SQLite, is subject to change without ** notice, and should not be referenced by programs that use SQLite. ** ** Some of the definitions that are in this file are marked as ** "experimental". Experimental interfaces are normally new ** features recently added to SQLite. We do not anticipate changes ** to experimental interfaces but reserve the right to make minor changes ** if experience from use "in the wild" suggest such changes are prudent. ** ** The official C-language API documentation for SQLite is derived ** from comments in this file. This file is the authoritative source ** on how SQLite interfaces are supposed to operate. ** ** The name of this file under configuration management is "sqlite.h.in". ** The makefile makes some minor changes to this file (such as inserting ** the version number) and changes its name to "sqlite3.h" as ** part of the build process. */ #ifndef SQLITE3_H #define SQLITE3_H #include /* Needed for the definition of va_list */ /* ** Make sure we can call this stuff from C++. */ #ifdef __cplusplus extern "C" { #endif /* ** Provide the ability to override linkage features of the interface. */ #ifndef SQLITE_EXTERN # define SQLITE_EXTERN extern #endif #ifndef SQLITE_API # define SQLITE_API #endif #ifndef SQLITE_CDECL # define SQLITE_CDECL #endif #ifndef SQLITE_APICALL # define SQLITE_APICALL #endif #ifndef SQLITE_STDCALL # define SQLITE_STDCALL SQLITE_APICALL #endif #ifndef SQLITE_CALLBACK # define SQLITE_CALLBACK #endif #ifndef SQLITE_SYSAPI # define SQLITE_SYSAPI #endif /* ** These no-op macros are used in front of interfaces to mark those ** interfaces as either deprecated or experimental. New applications ** should not use deprecated interfaces - they are supported for backwards ** compatibility only. Application writers should be aware that ** experimental interfaces are subject to change in point releases. ** ** These macros used to resolve to various kinds of compiler magic that ** would generate warning messages when they were used. But that ** compiler magic ended up generating such a flurry of bug reports ** that we have taken it all out and gone back to using simple ** noop macros. */ #define SQLITE_DEPRECATED #define SQLITE_EXPERIMENTAL /* ** Ensure these symbols were not defined by some previous header file. */ #ifdef SQLITE_VERSION # undef SQLITE_VERSION #endif #ifdef SQLITE_VERSION_NUMBER # undef SQLITE_VERSION_NUMBER #endif /* ** CAPI3REF: Compile-Time Library Version Numbers ** ** ^(The [SQLITE_VERSION] C preprocessor macro in the sqlite3.h header ** evaluates to a string literal that is the SQLite version in the ** format "X.Y.Z" where X is the major version number (always 3 for ** SQLite3) and Y is the minor version number and Z is the release number.)^ ** ^(The [SQLITE_VERSION_NUMBER] C preprocessor macro resolves to an integer ** with the value (X*1000000 + Y*1000 + Z) where X, Y, and Z are the same ** numbers used in [SQLITE_VERSION].)^ ** The SQLITE_VERSION_NUMBER for any given release of SQLite will also ** be larger than the release from which it is derived. Either Y will ** be held constant and Z will be incremented or else Y will be incremented ** and Z will be reset to zero. ** ** Since [version 3.6.18] ([dateof:3.6.18]), ** SQLite source code has been stored in the ** Fossil configuration management ** system. ^The SQLITE_SOURCE_ID macro evaluates to ** a string which identifies a particular check-in of SQLite ** within its configuration management system. ^The SQLITE_SOURCE_ID ** string contains the date and time of the check-in (UTC) and an SHA1 ** hash of the entire source tree. ** ** See also: [sqlite3_libversion()], ** [sqlite3_libversion_number()], [sqlite3_sourceid()], ** [sqlite_version()] and [sqlite_source_id()]. */ #define SQLITE_VERSION "3.15.1" #define SQLITE_VERSION_NUMBER 3015001 #define SQLITE_SOURCE_ID "2016-11-04 12:08:49 1136863c76576110e710dd5d69ab6bf347c65e36" /* ** CAPI3REF: Run-Time Library Version Numbers ** KEYWORDS: sqlite3_version, sqlite3_sourceid ** ** These interfaces provide the same information as the [SQLITE_VERSION], ** [SQLITE_VERSION_NUMBER], and [SQLITE_SOURCE_ID] C preprocessor macros ** but are associated with the library instead of the header file. ^(Cautious ** programmers might include assert() statements in their application to ** verify that values returned by these interfaces match the macros in ** the header, and thus ensure that the application is ** compiled with matching library and header files. ** **
** assert( sqlite3_libversion_number()==SQLITE_VERSION_NUMBER );
** assert( strcmp(sqlite3_sourceid(),SQLITE_SOURCE_ID)==0 );
** assert( strcmp(sqlite3_libversion(),SQLITE_VERSION)==0 );
** 
)^ ** ** ^The sqlite3_version[] string constant contains the text of [SQLITE_VERSION] ** macro. ^The sqlite3_libversion() function returns a pointer to the ** to the sqlite3_version[] string constant. The sqlite3_libversion() ** function is provided for use in DLLs since DLL users usually do not have ** direct access to string constants within the DLL. ^The ** sqlite3_libversion_number() function returns an integer equal to ** [SQLITE_VERSION_NUMBER]. ^The sqlite3_sourceid() function returns ** a pointer to a string constant whose value is the same as the ** [SQLITE_SOURCE_ID] C preprocessor macro. ** ** See also: [sqlite_version()] and [sqlite_source_id()]. */ SQLITE_API SQLITE_EXTERN const char sqlite3_version[]; SQLITE_API const char *sqlite3_libversion(void); SQLITE_API const char *sqlite3_sourceid(void); SQLITE_API int sqlite3_libversion_number(void); /* ** CAPI3REF: Run-Time Library Compilation Options Diagnostics ** ** ^The sqlite3_compileoption_used() function returns 0 or 1 ** indicating whether the specified option was defined at ** compile time. ^The SQLITE_ prefix may be omitted from the ** option name passed to sqlite3_compileoption_used(). ** ** ^The sqlite3_compileoption_get() function allows iterating ** over the list of options that were defined at compile time by ** returning the N-th compile time option string. ^If N is out of range, ** sqlite3_compileoption_get() returns a NULL pointer. ^The SQLITE_ ** prefix is omitted from any strings returned by ** sqlite3_compileoption_get(). ** ** ^Support for the diagnostic functions sqlite3_compileoption_used() ** and sqlite3_compileoption_get() may be omitted by specifying the ** [SQLITE_OMIT_COMPILEOPTION_DIAGS] option at compile time. ** ** See also: SQL functions [sqlite_compileoption_used()] and ** [sqlite_compileoption_get()] and the [compile_options pragma]. */ #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS SQLITE_API int sqlite3_compileoption_used(const char *zOptName); SQLITE_API const char *sqlite3_compileoption_get(int N); #endif /* ** CAPI3REF: Test To See If The Library Is Threadsafe ** ** ^The sqlite3_threadsafe() function returns zero if and only if ** SQLite was compiled with mutexing code omitted due to the ** [SQLITE_THREADSAFE] compile-time option being set to 0. ** ** SQLite can be compiled with or without mutexes. When ** the [SQLITE_THREADSAFE] C preprocessor macro is 1 or 2, mutexes ** are enabled and SQLite is threadsafe. When the ** [SQLITE_THREADSAFE] macro is 0, ** the mutexes are omitted. Without the mutexes, it is not safe ** to use SQLite concurrently from more than one thread. ** ** Enabling mutexes incurs a measurable performance penalty. ** So if speed is of utmost importance, it makes sense to disable ** the mutexes. But for maximum safety, mutexes should be enabled. ** ^The default behavior is for mutexes to be enabled. ** ** This interface can be used by an application to make sure that the ** version of SQLite that it is linking against was compiled with ** the desired setting of the [SQLITE_THREADSAFE] macro. ** ** This interface only reports on the compile-time mutex setting ** of the [SQLITE_THREADSAFE] flag. If SQLite is compiled with ** SQLITE_THREADSAFE=1 or =2 then mutexes are enabled by default but ** can be fully or partially disabled using a call to [sqlite3_config()] ** with the verbs [SQLITE_CONFIG_SINGLETHREAD], [SQLITE_CONFIG_MULTITHREAD], ** or [SQLITE_CONFIG_SERIALIZED]. ^(The return value of the ** sqlite3_threadsafe() function shows only the compile-time setting of ** thread safety, not any run-time changes to that setting made by ** sqlite3_config(). In other words, the return value from sqlite3_threadsafe() ** is unchanged by calls to sqlite3_config().)^ ** ** See the [threading mode] documentation for additional information. */ SQLITE_API int sqlite3_threadsafe(void); /* ** CAPI3REF: Database Connection Handle ** KEYWORDS: {database connection} {database connections} ** ** Each open SQLite database is represented by a pointer to an instance of ** the opaque structure named "sqlite3". It is useful to think of an sqlite3 ** pointer as an object. The [sqlite3_open()], [sqlite3_open16()], and ** [sqlite3_open_v2()] interfaces are its constructors, and [sqlite3_close()] ** and [sqlite3_close_v2()] are its destructors. There are many other ** interfaces (such as ** [sqlite3_prepare_v2()], [sqlite3_create_function()], and ** [sqlite3_busy_timeout()] to name but three) that are methods on an ** sqlite3 object. */ typedef struct sqlite3 sqlite3; /* ** CAPI3REF: 64-Bit Integer Types ** KEYWORDS: sqlite_int64 sqlite_uint64 ** ** Because there is no cross-platform way to specify 64-bit integer types ** SQLite includes typedefs for 64-bit signed and unsigned integers. ** ** The sqlite3_int64 and sqlite3_uint64 are the preferred type definitions. ** The sqlite_int64 and sqlite_uint64 types are supported for backwards ** compatibility only. ** ** ^The sqlite3_int64 and sqlite_int64 types can store integer values ** between -9223372036854775808 and +9223372036854775807 inclusive. ^The ** sqlite3_uint64 and sqlite_uint64 types can store integer values ** between 0 and +18446744073709551615 inclusive. */ #ifdef SQLITE_INT64_TYPE typedef SQLITE_INT64_TYPE sqlite_int64; typedef unsigned SQLITE_INT64_TYPE sqlite_uint64; #elif defined(_MSC_VER) || defined(__BORLANDC__) typedef __int64 sqlite_int64; typedef unsigned __int64 sqlite_uint64; #else typedef long long int sqlite_int64; typedef unsigned long long int sqlite_uint64; #endif typedef sqlite_int64 sqlite3_int64; typedef sqlite_uint64 sqlite3_uint64; /* ** If compiling for a processor that lacks floating point support, ** substitute integer for floating-point. */ #ifdef SQLITE_OMIT_FLOATING_POINT # define double sqlite3_int64 #endif /* ** CAPI3REF: Closing A Database Connection ** DESTRUCTOR: sqlite3 ** ** ^The sqlite3_close() and sqlite3_close_v2() routines are destructors ** for the [sqlite3] object. ** ^Calls to sqlite3_close() and sqlite3_close_v2() return [SQLITE_OK] if ** the [sqlite3] object is successfully destroyed and all associated ** resources are deallocated. ** ** ^If the database connection is associated with unfinalized prepared ** statements or unfinished sqlite3_backup objects then sqlite3_close() ** will leave the database connection open and return [SQLITE_BUSY]. ** ^If sqlite3_close_v2() is called with unfinalized prepared statements ** and/or unfinished sqlite3_backups, then the database connection becomes ** an unusable "zombie" which will automatically be deallocated when the ** last prepared statement is finalized or the last sqlite3_backup is ** finished. The sqlite3_close_v2() interface is intended for use with ** host languages that are garbage collected, and where the order in which ** destructors are called is arbitrary. ** ** Applications should [sqlite3_finalize | finalize] all [prepared statements], ** [sqlite3_blob_close | close] all [BLOB handles], and ** [sqlite3_backup_finish | finish] all [sqlite3_backup] objects associated ** with the [sqlite3] object prior to attempting to close the object. ^If ** sqlite3_close_v2() is called on a [database connection] that still has ** outstanding [prepared statements], [BLOB handles], and/or ** [sqlite3_backup] objects then it returns [SQLITE_OK] and the deallocation ** of resources is deferred until all [prepared statements], [BLOB handles], ** and [sqlite3_backup] objects are also destroyed. ** ** ^If an [sqlite3] object is destroyed while a transaction is open, ** the transaction is automatically rolled back. ** ** The C parameter to [sqlite3_close(C)] and [sqlite3_close_v2(C)] ** must be either a NULL ** pointer or an [sqlite3] object pointer obtained ** from [sqlite3_open()], [sqlite3_open16()], or ** [sqlite3_open_v2()], and not previously closed. ** ^Calling sqlite3_close() or sqlite3_close_v2() with a NULL pointer ** argument is a harmless no-op. */ SQLITE_API int sqlite3_close(sqlite3*); SQLITE_API int sqlite3_close_v2(sqlite3*); /* ** The type for a callback function. ** This is legacy and deprecated. It is included for historical ** compatibility and is not documented. */ typedef int (*sqlite3_callback)(void*,int,char**, char**); /* ** CAPI3REF: One-Step Query Execution Interface ** METHOD: sqlite3 ** ** The sqlite3_exec() interface is a convenience wrapper around ** [sqlite3_prepare_v2()], [sqlite3_step()], and [sqlite3_finalize()], ** that allows an application to run multiple statements of SQL ** without having to use a lot of C code. ** ** ^The sqlite3_exec() interface runs zero or more UTF-8 encoded, ** semicolon-separate SQL statements passed into its 2nd argument, ** in the context of the [database connection] passed in as its 1st ** argument. ^If the callback function of the 3rd argument to ** sqlite3_exec() is not NULL, then it is invoked for each result row ** coming out of the evaluated SQL statements. ^The 4th argument to ** sqlite3_exec() is relayed through to the 1st argument of each ** callback invocation. ^If the callback pointer to sqlite3_exec() ** is NULL, then no callback is ever invoked and result rows are ** ignored. ** ** ^If an error occurs while evaluating the SQL statements passed into ** sqlite3_exec(), then execution of the current statement stops and ** subsequent statements are skipped. ^If the 5th parameter to sqlite3_exec() ** is not NULL then any error message is written into memory obtained ** from [sqlite3_malloc()] and passed back through the 5th parameter. ** To avoid memory leaks, the application should invoke [sqlite3_free()] ** on error message strings returned through the 5th parameter of ** sqlite3_exec() after the error message string is no longer needed. ** ^If the 5th parameter to sqlite3_exec() is not NULL and no errors ** occur, then sqlite3_exec() sets the pointer in its 5th parameter to ** NULL before returning. ** ** ^If an sqlite3_exec() callback returns non-zero, the sqlite3_exec() ** routine returns SQLITE_ABORT without invoking the callback again and ** without running any subsequent SQL statements. ** ** ^The 2nd argument to the sqlite3_exec() callback function is the ** number of columns in the result. ^The 3rd argument to the sqlite3_exec() ** callback is an array of pointers to strings obtained as if from ** [sqlite3_column_text()], one for each column. ^If an element of a ** result row is NULL then the corresponding string pointer for the ** sqlite3_exec() callback is a NULL pointer. ^The 4th argument to the ** sqlite3_exec() callback is an array of pointers to strings where each ** entry represents the name of corresponding result column as obtained ** from [sqlite3_column_name()]. ** ** ^If the 2nd parameter to sqlite3_exec() is a NULL pointer, a pointer ** to an empty string, or a pointer that contains only whitespace and/or ** SQL comments, then no SQL statements are evaluated and the database ** is not changed. ** ** Restrictions: ** **
    **
  • The application must ensure that the 1st parameter to sqlite3_exec() ** is a valid and open [database connection]. **
  • The application must not close the [database connection] specified by ** the 1st parameter to sqlite3_exec() while sqlite3_exec() is running. **
  • The application must not modify the SQL statement text passed into ** the 2nd parameter of sqlite3_exec() while sqlite3_exec() is running. **
*/ SQLITE_API int sqlite3_exec( sqlite3*, /* An open database */ const char *sql, /* SQL to be evaluated */ int (*callback)(void*,int,char**,char**), /* Callback function */ void *, /* 1st argument to callback */ char **errmsg /* Error msg written here */ ); /* ** CAPI3REF: Result Codes ** KEYWORDS: {result code definitions} ** ** Many SQLite functions return an integer result code from the set shown ** here in order to indicate success or failure. ** ** New error codes may be added in future versions of SQLite. ** ** See also: [extended result code definitions] */ #define SQLITE_OK 0 /* Successful result */ /* beginning-of-error-codes */ #define SQLITE_ERROR 1 /* SQL error or missing database */ #define SQLITE_INTERNAL 2 /* Internal logic error in SQLite */ #define SQLITE_PERM 3 /* Access permission denied */ #define SQLITE_ABORT 4 /* Callback routine requested an abort */ #define SQLITE_BUSY 5 /* The database file is locked */ #define SQLITE_LOCKED 6 /* A table in the database is locked */ #define SQLITE_NOMEM 7 /* A malloc() failed */ #define SQLITE_READONLY 8 /* Attempt to write a readonly database */ #define SQLITE_INTERRUPT 9 /* Operation terminated by sqlite3_interrupt()*/ #define SQLITE_IOERR 10 /* Some kind of disk I/O error occurred */ #define SQLITE_CORRUPT 11 /* The database disk image is malformed */ #define SQLITE_NOTFOUND 12 /* Unknown opcode in sqlite3_file_control() */ #define SQLITE_FULL 13 /* Insertion failed because database is full */ #define SQLITE_CANTOPEN 14 /* Unable to open the database file */ #define SQLITE_PROTOCOL 15 /* Database lock protocol error */ #define SQLITE_EMPTY 16 /* Database is empty */ #define SQLITE_SCHEMA 17 /* The database schema changed */ #define SQLITE_TOOBIG 18 /* String or BLOB exceeds size limit */ #define SQLITE_CONSTRAINT 19 /* Abort due to constraint violation */ #define SQLITE_MISMATCH 20 /* Data type mismatch */ #define SQLITE_MISUSE 21 /* Library used incorrectly */ #define SQLITE_NOLFS 22 /* Uses OS features not supported on host */ #define SQLITE_AUTH 23 /* Authorization denied */ #define SQLITE_FORMAT 24 /* Auxiliary database format error */ #define SQLITE_RANGE 25 /* 2nd parameter to sqlite3_bind out of range */ #define SQLITE_NOTADB 26 /* File opened that is not a database file */ #define SQLITE_NOTICE 27 /* Notifications from sqlite3_log() */ #define SQLITE_WARNING 28 /* Warnings from sqlite3_log() */ #define SQLITE_ROW 100 /* sqlite3_step() has another row ready */ #define SQLITE_DONE 101 /* sqlite3_step() has finished executing */ /* end-of-error-codes */ /* ** CAPI3REF: Extended Result Codes ** KEYWORDS: {extended result code definitions} ** ** In its default configuration, SQLite API routines return one of 30 integer ** [result codes]. However, experience has shown that many of ** these result codes are too coarse-grained. They do not provide as ** much information about problems as programmers might like. In an effort to ** address this, newer versions of SQLite (version 3.3.8 [dateof:3.3.8] ** and later) include ** support for additional result codes that provide more detailed information ** about errors. These [extended result codes] are enabled or disabled ** on a per database connection basis using the ** [sqlite3_extended_result_codes()] API. Or, the extended code for ** the most recent error can be obtained using ** [sqlite3_extended_errcode()]. */ #define SQLITE_IOERR_READ (SQLITE_IOERR | (1<<8)) #define SQLITE_IOERR_SHORT_READ (SQLITE_IOERR | (2<<8)) #define SQLITE_IOERR_WRITE (SQLITE_IOERR | (3<<8)) #define SQLITE_IOERR_FSYNC (SQLITE_IOERR | (4<<8)) #define SQLITE_IOERR_DIR_FSYNC (SQLITE_IOERR | (5<<8)) #define SQLITE_IOERR_TRUNCATE (SQLITE_IOERR | (6<<8)) #define SQLITE_IOERR_FSTAT (SQLITE_IOERR | (7<<8)) #define SQLITE_IOERR_UNLOCK (SQLITE_IOERR | (8<<8)) #define SQLITE_IOERR_RDLOCK (SQLITE_IOERR | (9<<8)) #define SQLITE_IOERR_DELETE (SQLITE_IOERR | (10<<8)) #define SQLITE_IOERR_BLOCKED (SQLITE_IOERR | (11<<8)) #define SQLITE_IOERR_NOMEM (SQLITE_IOERR | (12<<8)) #define SQLITE_IOERR_ACCESS (SQLITE_IOERR | (13<<8)) #define SQLITE_IOERR_CHECKRESERVEDLOCK (SQLITE_IOERR | (14<<8)) #define SQLITE_IOERR_LOCK (SQLITE_IOERR | (15<<8)) #define SQLITE_IOERR_CLOSE (SQLITE_IOERR | (16<<8)) #define SQLITE_IOERR_DIR_CLOSE (SQLITE_IOERR | (17<<8)) #define SQLITE_IOERR_SHMOPEN (SQLITE_IOERR | (18<<8)) #define SQLITE_IOERR_SHMSIZE (SQLITE_IOERR | (19<<8)) #define SQLITE_IOERR_SHMLOCK (SQLITE_IOERR | (20<<8)) #define SQLITE_IOERR_SHMMAP (SQLITE_IOERR | (21<<8)) #define SQLITE_IOERR_SEEK (SQLITE_IOERR | (22<<8)) #define SQLITE_IOERR_DELETE_NOENT (SQLITE_IOERR | (23<<8)) #define SQLITE_IOERR_MMAP (SQLITE_IOERR | (24<<8)) #define SQLITE_IOERR_GETTEMPPATH (SQLITE_IOERR | (25<<8)) #define SQLITE_IOERR_CONVPATH (SQLITE_IOERR | (26<<8)) #define SQLITE_IOERR_VNODE (SQLITE_IOERR | (27<<8)) #define SQLITE_IOERR_AUTH (SQLITE_IOERR | (28<<8)) #define SQLITE_LOCKED_SHAREDCACHE (SQLITE_LOCKED | (1<<8)) #define SQLITE_BUSY_RECOVERY (SQLITE_BUSY | (1<<8)) #define SQLITE_BUSY_SNAPSHOT (SQLITE_BUSY | (2<<8)) #define SQLITE_CANTOPEN_NOTEMPDIR (SQLITE_CANTOPEN | (1<<8)) #define SQLITE_CANTOPEN_ISDIR (SQLITE_CANTOPEN | (2<<8)) #define SQLITE_CANTOPEN_FULLPATH (SQLITE_CANTOPEN | (3<<8)) #define SQLITE_CANTOPEN_CONVPATH (SQLITE_CANTOPEN | (4<<8)) #define SQLITE_CORRUPT_VTAB (SQLITE_CORRUPT | (1<<8)) #define SQLITE_READONLY_RECOVERY (SQLITE_READONLY | (1<<8)) #define SQLITE_READONLY_CANTLOCK (SQLITE_READONLY | (2<<8)) #define SQLITE_READONLY_ROLLBACK (SQLITE_READONLY | (3<<8)) #define SQLITE_READONLY_DBMOVED (SQLITE_READONLY | (4<<8)) #define SQLITE_ABORT_ROLLBACK (SQLITE_ABORT | (2<<8)) #define SQLITE_CONSTRAINT_CHECK (SQLITE_CONSTRAINT | (1<<8)) #define SQLITE_CONSTRAINT_COMMITHOOK (SQLITE_CONSTRAINT | (2<<8)) #define SQLITE_CONSTRAINT_FOREIGNKEY (SQLITE_CONSTRAINT | (3<<8)) #define SQLITE_CONSTRAINT_FUNCTION (SQLITE_CONSTRAINT | (4<<8)) #define SQLITE_CONSTRAINT_NOTNULL (SQLITE_CONSTRAINT | (5<<8)) #define SQLITE_CONSTRAINT_PRIMARYKEY (SQLITE_CONSTRAINT | (6<<8)) #define SQLITE_CONSTRAINT_TRIGGER (SQLITE_CONSTRAINT | (7<<8)) #define SQLITE_CONSTRAINT_UNIQUE (SQLITE_CONSTRAINT | (8<<8)) #define SQLITE_CONSTRAINT_VTAB (SQLITE_CONSTRAINT | (9<<8)) #define SQLITE_CONSTRAINT_ROWID (SQLITE_CONSTRAINT |(10<<8)) #define SQLITE_NOTICE_RECOVER_WAL (SQLITE_NOTICE | (1<<8)) #define SQLITE_NOTICE_RECOVER_ROLLBACK (SQLITE_NOTICE | (2<<8)) #define SQLITE_WARNING_AUTOINDEX (SQLITE_WARNING | (1<<8)) #define SQLITE_AUTH_USER (SQLITE_AUTH | (1<<8)) #define SQLITE_OK_LOAD_PERMANENTLY (SQLITE_OK | (1<<8)) /* ** CAPI3REF: Flags For File Open Operations ** ** These bit values are intended for use in the ** 3rd parameter to the [sqlite3_open_v2()] interface and ** in the 4th parameter to the [sqlite3_vfs.xOpen] method. */ #define SQLITE_OPEN_READONLY 0x00000001 /* Ok for sqlite3_open_v2() */ #define SQLITE_OPEN_READWRITE 0x00000002 /* Ok for sqlite3_open_v2() */ #define SQLITE_OPEN_CREATE 0x00000004 /* Ok for sqlite3_open_v2() */ #define SQLITE_OPEN_DELETEONCLOSE 0x00000008 /* VFS only */ #define SQLITE_OPEN_EXCLUSIVE 0x00000010 /* VFS only */ #define SQLITE_OPEN_AUTOPROXY 0x00000020 /* VFS only */ #define SQLITE_OPEN_URI 0x00000040 /* Ok for sqlite3_open_v2() */ #define SQLITE_OPEN_MEMORY 0x00000080 /* Ok for sqlite3_open_v2() */ #define SQLITE_OPEN_MAIN_DB 0x00000100 /* VFS only */ #define SQLITE_OPEN_TEMP_DB 0x00000200 /* VFS only */ #define SQLITE_OPEN_TRANSIENT_DB 0x00000400 /* VFS only */ #define SQLITE_OPEN_MAIN_JOURNAL 0x00000800 /* VFS only */ #define SQLITE_OPEN_TEMP_JOURNAL 0x00001000 /* VFS only */ #define SQLITE_OPEN_SUBJOURNAL 0x00002000 /* VFS only */ #define SQLITE_OPEN_MASTER_JOURNAL 0x00004000 /* VFS only */ #define SQLITE_OPEN_NOMUTEX 0x00008000 /* Ok for sqlite3_open_v2() */ #define SQLITE_OPEN_FULLMUTEX 0x00010000 /* Ok for sqlite3_open_v2() */ #define SQLITE_OPEN_SHAREDCACHE 0x00020000 /* Ok for sqlite3_open_v2() */ #define SQLITE_OPEN_PRIVATECACHE 0x00040000 /* Ok for sqlite3_open_v2() */ #define SQLITE_OPEN_WAL 0x00080000 /* VFS only */ /* Reserved: 0x00F00000 */ /* ** CAPI3REF: Device Characteristics ** ** The xDeviceCharacteristics method of the [sqlite3_io_methods] ** object returns an integer which is a vector of these ** bit values expressing I/O characteristics of the mass storage ** device that holds the file that the [sqlite3_io_methods] ** refers to. ** ** The SQLITE_IOCAP_ATOMIC property means that all writes of ** any size are atomic. The SQLITE_IOCAP_ATOMICnnn values ** mean that writes of blocks that are nnn bytes in size and ** are aligned to an address which is an integer multiple of ** nnn are atomic. The SQLITE_IOCAP_SAFE_APPEND value means ** that when data is appended to a file, the data is appended ** first then the size of the file is extended, never the other ** way around. The SQLITE_IOCAP_SEQUENTIAL property means that ** information is written to disk in the same order as calls ** to xWrite(). The SQLITE_IOCAP_POWERSAFE_OVERWRITE property means that ** after reboot following a crash or power loss, the only bytes in a ** file that were written at the application level might have changed ** and that adjacent bytes, even bytes within the same sector are ** guaranteed to be unchanged. The SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN ** flag indicate that a file cannot be deleted when open. The ** SQLITE_IOCAP_IMMUTABLE flag indicates that the file is on ** read-only media and cannot be changed even by processes with ** elevated privileges. */ #define SQLITE_IOCAP_ATOMIC 0x00000001 #define SQLITE_IOCAP_ATOMIC512 0x00000002 #define SQLITE_IOCAP_ATOMIC1K 0x00000004 #define SQLITE_IOCAP_ATOMIC2K 0x00000008 #define SQLITE_IOCAP_ATOMIC4K 0x00000010 #define SQLITE_IOCAP_ATOMIC8K 0x00000020 #define SQLITE_IOCAP_ATOMIC16K 0x00000040 #define SQLITE_IOCAP_ATOMIC32K 0x00000080 #define SQLITE_IOCAP_ATOMIC64K 0x00000100 #define SQLITE_IOCAP_SAFE_APPEND 0x00000200 #define SQLITE_IOCAP_SEQUENTIAL 0x00000400 #define SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN 0x00000800 #define SQLITE_IOCAP_POWERSAFE_OVERWRITE 0x00001000 #define SQLITE_IOCAP_IMMUTABLE 0x00002000 /* ** CAPI3REF: File Locking Levels ** ** SQLite uses one of these integer values as the second ** argument to calls it makes to the xLock() and xUnlock() methods ** of an [sqlite3_io_methods] object. */ #define SQLITE_LOCK_NONE 0 #define SQLITE_LOCK_SHARED 1 #define SQLITE_LOCK_RESERVED 2 #define SQLITE_LOCK_PENDING 3 #define SQLITE_LOCK_EXCLUSIVE 4 /* ** CAPI3REF: Synchronization Type Flags ** ** When SQLite invokes the xSync() method of an ** [sqlite3_io_methods] object it uses a combination of ** these integer values as the second argument. ** ** When the SQLITE_SYNC_DATAONLY flag is used, it means that the ** sync operation only needs to flush data to mass storage. Inode ** information need not be flushed. If the lower four bits of the flag ** equal SQLITE_SYNC_NORMAL, that means to use normal fsync() semantics. ** If the lower four bits equal SQLITE_SYNC_FULL, that means ** to use Mac OS X style fullsync instead of fsync(). ** ** Do not confuse the SQLITE_SYNC_NORMAL and SQLITE_SYNC_FULL flags ** with the [PRAGMA synchronous]=NORMAL and [PRAGMA synchronous]=FULL ** settings. The [synchronous pragma] determines when calls to the ** xSync VFS method occur and applies uniformly across all platforms. ** The SQLITE_SYNC_NORMAL and SQLITE_SYNC_FULL flags determine how ** energetic or rigorous or forceful the sync operations are and ** only make a difference on Mac OSX for the default SQLite code. ** (Third-party VFS implementations might also make the distinction ** between SQLITE_SYNC_NORMAL and SQLITE_SYNC_FULL, but among the ** operating systems natively supported by SQLite, only Mac OSX ** cares about the difference.) */ #define SQLITE_SYNC_NORMAL 0x00002 #define SQLITE_SYNC_FULL 0x00003 #define SQLITE_SYNC_DATAONLY 0x00010 /* ** CAPI3REF: OS Interface Open File Handle ** ** An [sqlite3_file] object represents an open file in the ** [sqlite3_vfs | OS interface layer]. Individual OS interface ** implementations will ** want to subclass this object by appending additional fields ** for their own use. The pMethods entry is a pointer to an ** [sqlite3_io_methods] object that defines methods for performing ** I/O operations on the open file. */ typedef struct sqlite3_file sqlite3_file; struct sqlite3_file { const struct sqlite3_io_methods *pMethods; /* Methods for an open file */ }; /* ** CAPI3REF: OS Interface File Virtual Methods Object ** ** Every file opened by the [sqlite3_vfs.xOpen] method populates an ** [sqlite3_file] object (or, more commonly, a subclass of the ** [sqlite3_file] object) with a pointer to an instance of this object. ** This object defines the methods used to perform various operations ** against the open file represented by the [sqlite3_file] object. ** ** If the [sqlite3_vfs.xOpen] method sets the sqlite3_file.pMethods element ** to a non-NULL pointer, then the sqlite3_io_methods.xClose method ** may be invoked even if the [sqlite3_vfs.xOpen] reported that it failed. The ** only way to prevent a call to xClose following a failed [sqlite3_vfs.xOpen] ** is for the [sqlite3_vfs.xOpen] to set the sqlite3_file.pMethods element ** to NULL. ** ** The flags argument to xSync may be one of [SQLITE_SYNC_NORMAL] or ** [SQLITE_SYNC_FULL]. The first choice is the normal fsync(). ** The second choice is a Mac OS X style fullsync. The [SQLITE_SYNC_DATAONLY] ** flag may be ORed in to indicate that only the data of the file ** and not its inode needs to be synced. ** ** The integer values to xLock() and xUnlock() are one of **
    **
  • [SQLITE_LOCK_NONE], **
  • [SQLITE_LOCK_SHARED], **
  • [SQLITE_LOCK_RESERVED], **
  • [SQLITE_LOCK_PENDING], or **
  • [SQLITE_LOCK_EXCLUSIVE]. **
** xLock() increases the lock. xUnlock() decreases the lock. ** The xCheckReservedLock() method checks whether any database connection, ** either in this process or in some other process, is holding a RESERVED, ** PENDING, or EXCLUSIVE lock on the file. It returns true ** if such a lock exists and false otherwise. ** ** The xFileControl() method is a generic interface that allows custom ** VFS implementations to directly control an open file using the ** [sqlite3_file_control()] interface. The second "op" argument is an ** integer opcode. The third argument is a generic pointer intended to ** point to a structure that may contain arguments or space in which to ** write return values. Potential uses for xFileControl() might be ** functions to enable blocking locks with timeouts, to change the ** locking strategy (for example to use dot-file locks), to inquire ** about the status of a lock, or to break stale locks. The SQLite ** core reserves all opcodes less than 100 for its own use. ** A [file control opcodes | list of opcodes] less than 100 is available. ** Applications that define a custom xFileControl method should use opcodes ** greater than 100 to avoid conflicts. VFS implementations should ** return [SQLITE_NOTFOUND] for file control opcodes that they do not ** recognize. ** ** The xSectorSize() method returns the sector size of the ** device that underlies the file. The sector size is the ** minimum write that can be performed without disturbing ** other bytes in the file. The xDeviceCharacteristics() ** method returns a bit vector describing behaviors of the ** underlying device: ** **
    **
  • [SQLITE_IOCAP_ATOMIC] **
  • [SQLITE_IOCAP_ATOMIC512] **
  • [SQLITE_IOCAP_ATOMIC1K] **
  • [SQLITE_IOCAP_ATOMIC2K] **
  • [SQLITE_IOCAP_ATOMIC4K] **
  • [SQLITE_IOCAP_ATOMIC8K] **
  • [SQLITE_IOCAP_ATOMIC16K] **
  • [SQLITE_IOCAP_ATOMIC32K] **
  • [SQLITE_IOCAP_ATOMIC64K] **
  • [SQLITE_IOCAP_SAFE_APPEND] **
  • [SQLITE_IOCAP_SEQUENTIAL] **
** ** The SQLITE_IOCAP_ATOMIC property means that all writes of ** any size are atomic. The SQLITE_IOCAP_ATOMICnnn values ** mean that writes of blocks that are nnn bytes in size and ** are aligned to an address which is an integer multiple of ** nnn are atomic. The SQLITE_IOCAP_SAFE_APPEND value means ** that when data is appended to a file, the data is appended ** first then the size of the file is extended, never the other ** way around. The SQLITE_IOCAP_SEQUENTIAL property means that ** information is written to disk in the same order as calls ** to xWrite(). ** ** If xRead() returns SQLITE_IOERR_SHORT_READ it must also fill ** in the unread portions of the buffer with zeros. A VFS that ** fails to zero-fill short reads might seem to work. However, ** failure to zero-fill short reads will eventually lead to ** database corruption. */ typedef struct sqlite3_io_methods sqlite3_io_methods; struct sqlite3_io_methods { int iVersion; int (*xClose)(sqlite3_file*); int (*xRead)(sqlite3_file*, void*, int iAmt, sqlite3_int64 iOfst); int (*xWrite)(sqlite3_file*, const void*, int iAmt, sqlite3_int64 iOfst); int (*xTruncate)(sqlite3_file*, sqlite3_int64 size); int (*xSync)(sqlite3_file*, int flags); int (*xFileSize)(sqlite3_file*, sqlite3_int64 *pSize); int (*xLock)(sqlite3_file*, int); int (*xUnlock)(sqlite3_file*, int); int (*xCheckReservedLock)(sqlite3_file*, int *pResOut); int (*xFileControl)(sqlite3_file*, int op, void *pArg); int (*xSectorSize)(sqlite3_file*); int (*xDeviceCharacteristics)(sqlite3_file*); /* Methods above are valid for version 1 */ int (*xShmMap)(sqlite3_file*, int iPg, int pgsz, int, void volatile**); int (*xShmLock)(sqlite3_file*, int offset, int n, int flags); void (*xShmBarrier)(sqlite3_file*); int (*xShmUnmap)(sqlite3_file*, int deleteFlag); /* Methods above are valid for version 2 */ int (*xFetch)(sqlite3_file*, sqlite3_int64 iOfst, int iAmt, void **pp); int (*xUnfetch)(sqlite3_file*, sqlite3_int64 iOfst, void *p); /* Methods above are valid for version 3 */ /* Additional methods may be added in future releases */ }; /* ** CAPI3REF: Standard File Control Opcodes ** KEYWORDS: {file control opcodes} {file control opcode} ** ** These integer constants are opcodes for the xFileControl method ** of the [sqlite3_io_methods] object and for the [sqlite3_file_control()] ** interface. ** **
    **
  • [[SQLITE_FCNTL_LOCKSTATE]] ** The [SQLITE_FCNTL_LOCKSTATE] opcode is used for debugging. This ** opcode causes the xFileControl method to write the current state of ** the lock (one of [SQLITE_LOCK_NONE], [SQLITE_LOCK_SHARED], ** [SQLITE_LOCK_RESERVED], [SQLITE_LOCK_PENDING], or [SQLITE_LOCK_EXCLUSIVE]) ** into an integer that the pArg argument points to. This capability ** is used during testing and is only available when the SQLITE_TEST ** compile-time option is used. ** **
  • [[SQLITE_FCNTL_SIZE_HINT]] ** The [SQLITE_FCNTL_SIZE_HINT] opcode is used by SQLite to give the VFS ** layer a hint of how large the database file will grow to be during the ** current transaction. This hint is not guaranteed to be accurate but it ** is often close. The underlying VFS might choose to preallocate database ** file space based on this hint in order to help writes to the database ** file run faster. ** **
  • [[SQLITE_FCNTL_CHUNK_SIZE]] ** The [SQLITE_FCNTL_CHUNK_SIZE] opcode is used to request that the VFS ** extends and truncates the database file in chunks of a size specified ** by the user. The fourth argument to [sqlite3_file_control()] should ** point to an integer (type int) containing the new chunk-size to use ** for the nominated database. Allocating database file space in large ** chunks (say 1MB at a time), may reduce file-system fragmentation and ** improve performance on some systems. ** **
  • [[SQLITE_FCNTL_FILE_POINTER]] ** The [SQLITE_FCNTL_FILE_POINTER] opcode is used to obtain a pointer ** to the [sqlite3_file] object associated with a particular database ** connection. See also [SQLITE_FCNTL_JOURNAL_POINTER]. ** **
  • [[SQLITE_FCNTL_JOURNAL_POINTER]] ** The [SQLITE_FCNTL_JOURNAL_POINTER] opcode is used to obtain a pointer ** to the [sqlite3_file] object associated with the journal file (either ** the [rollback journal] or the [write-ahead log]) for a particular database ** connection. See also [SQLITE_FCNTL_FILE_POINTER]. ** **
  • [[SQLITE_FCNTL_SYNC_OMITTED]] ** No longer in use. ** **
  • [[SQLITE_FCNTL_SYNC]] ** The [SQLITE_FCNTL_SYNC] opcode is generated internally by SQLite and ** sent to the VFS immediately before the xSync method is invoked on a ** database file descriptor. Or, if the xSync method is not invoked ** because the user has configured SQLite with ** [PRAGMA synchronous | PRAGMA synchronous=OFF] it is invoked in place ** of the xSync method. In most cases, the pointer argument passed with ** this file-control is NULL. However, if the database file is being synced ** as part of a multi-database commit, the argument points to a nul-terminated ** string containing the transactions master-journal file name. VFSes that ** do not need this signal should silently ignore this opcode. Applications ** should not call [sqlite3_file_control()] with this opcode as doing so may ** disrupt the operation of the specialized VFSes that do require it. ** **
  • [[SQLITE_FCNTL_COMMIT_PHASETWO]] ** The [SQLITE_FCNTL_COMMIT_PHASETWO] opcode is generated internally by SQLite ** and sent to the VFS after a transaction has been committed immediately ** but before the database is unlocked. VFSes that do not need this signal ** should silently ignore this opcode. Applications should not call ** [sqlite3_file_control()] with this opcode as doing so may disrupt the ** operation of the specialized VFSes that do require it. ** **
  • [[SQLITE_FCNTL_WIN32_AV_RETRY]] ** ^The [SQLITE_FCNTL_WIN32_AV_RETRY] opcode is used to configure automatic ** retry counts and intervals for certain disk I/O operations for the ** windows [VFS] in order to provide robustness in the presence of ** anti-virus programs. By default, the windows VFS will retry file read, ** file write, and file delete operations up to 10 times, with a delay ** of 25 milliseconds before the first retry and with the delay increasing ** by an additional 25 milliseconds with each subsequent retry. This ** opcode allows these two values (10 retries and 25 milliseconds of delay) ** to be adjusted. The values are changed for all database connections ** within the same process. The argument is a pointer to an array of two ** integers where the first integer i the new retry count and the second ** integer is the delay. If either integer is negative, then the setting ** is not changed but instead the prior value of that setting is written ** into the array entry, allowing the current retry settings to be ** interrogated. The zDbName parameter is ignored. ** **
  • [[SQLITE_FCNTL_PERSIST_WAL]] ** ^The [SQLITE_FCNTL_PERSIST_WAL] opcode is used to set or query the ** persistent [WAL | Write Ahead Log] setting. By default, the auxiliary ** write ahead log and shared memory files used for transaction control ** are automatically deleted when the latest connection to the database ** closes. Setting persistent WAL mode causes those files to persist after ** close. Persisting the files is useful when other processes that do not ** have write permission on the directory containing the database file want ** to read the database file, as the WAL and shared memory files must exist ** in order for the database to be readable. The fourth parameter to ** [sqlite3_file_control()] for this opcode should be a pointer to an integer. ** That integer is 0 to disable persistent WAL mode or 1 to enable persistent ** WAL mode. If the integer is -1, then it is overwritten with the current ** WAL persistence setting. ** **
  • [[SQLITE_FCNTL_POWERSAFE_OVERWRITE]] ** ^The [SQLITE_FCNTL_POWERSAFE_OVERWRITE] opcode is used to set or query the ** persistent "powersafe-overwrite" or "PSOW" setting. The PSOW setting ** determines the [SQLITE_IOCAP_POWERSAFE_OVERWRITE] bit of the ** xDeviceCharacteristics methods. The fourth parameter to ** [sqlite3_file_control()] for this opcode should be a pointer to an integer. ** That integer is 0 to disable zero-damage mode or 1 to enable zero-damage ** mode. If the integer is -1, then it is overwritten with the current ** zero-damage mode setting. ** **
  • [[SQLITE_FCNTL_OVERWRITE]] ** ^The [SQLITE_FCNTL_OVERWRITE] opcode is invoked by SQLite after opening ** a write transaction to indicate that, unless it is rolled back for some ** reason, the entire database file will be overwritten by the current ** transaction. This is used by VACUUM operations. ** **
  • [[SQLITE_FCNTL_VFSNAME]] ** ^The [SQLITE_FCNTL_VFSNAME] opcode can be used to obtain the names of ** all [VFSes] in the VFS stack. The names are of all VFS shims and the ** final bottom-level VFS are written into memory obtained from ** [sqlite3_malloc()] and the result is stored in the char* variable ** that the fourth parameter of [sqlite3_file_control()] points to. ** The caller is responsible for freeing the memory when done. As with ** all file-control actions, there is no guarantee that this will actually ** do anything. Callers should initialize the char* variable to a NULL ** pointer in case this file-control is not implemented. This file-control ** is intended for diagnostic use only. ** **
  • [[SQLITE_FCNTL_VFS_POINTER]] ** ^The [SQLITE_FCNTL_VFS_POINTER] opcode finds a pointer to the top-level ** [VFSes] currently in use. ^(The argument X in ** sqlite3_file_control(db,SQLITE_FCNTL_VFS_POINTER,X) must be ** of type "[sqlite3_vfs] **". This opcodes will set *X ** to a pointer to the top-level VFS.)^ ** ^When there are multiple VFS shims in the stack, this opcode finds the ** upper-most shim only. ** **
  • [[SQLITE_FCNTL_PRAGMA]] ** ^Whenever a [PRAGMA] statement is parsed, an [SQLITE_FCNTL_PRAGMA] ** file control is sent to the open [sqlite3_file] object corresponding ** to the database file to which the pragma statement refers. ^The argument ** to the [SQLITE_FCNTL_PRAGMA] file control is an array of ** pointers to strings (char**) in which the second element of the array ** is the name of the pragma and the third element is the argument to the ** pragma or NULL if the pragma has no argument. ^The handler for an ** [SQLITE_FCNTL_PRAGMA] file control can optionally make the first element ** of the char** argument point to a string obtained from [sqlite3_mprintf()] ** or the equivalent and that string will become the result of the pragma or ** the error message if the pragma fails. ^If the ** [SQLITE_FCNTL_PRAGMA] file control returns [SQLITE_NOTFOUND], then normal ** [PRAGMA] processing continues. ^If the [SQLITE_FCNTL_PRAGMA] ** file control returns [SQLITE_OK], then the parser assumes that the ** VFS has handled the PRAGMA itself and the parser generates a no-op ** prepared statement if result string is NULL, or that returns a copy ** of the result string if the string is non-NULL. ** ^If the [SQLITE_FCNTL_PRAGMA] file control returns ** any result code other than [SQLITE_OK] or [SQLITE_NOTFOUND], that means ** that the VFS encountered an error while handling the [PRAGMA] and the ** compilation of the PRAGMA fails with an error. ^The [SQLITE_FCNTL_PRAGMA] ** file control occurs at the beginning of pragma statement analysis and so ** it is able to override built-in [PRAGMA] statements. ** **
  • [[SQLITE_FCNTL_BUSYHANDLER]] ** ^The [SQLITE_FCNTL_BUSYHANDLER] ** file-control may be invoked by SQLite on the database file handle ** shortly after it is opened in order to provide a custom VFS with access ** to the connections busy-handler callback. The argument is of type (void **) ** - an array of two (void *) values. The first (void *) actually points ** to a function of type (int (*)(void *)). In order to invoke the connections ** busy-handler, this function should be invoked with the second (void *) in ** the array as the only argument. If it returns non-zero, then the operation ** should be retried. If it returns zero, the custom VFS should abandon the ** current operation. ** **
  • [[SQLITE_FCNTL_TEMPFILENAME]] ** ^Application can invoke the [SQLITE_FCNTL_TEMPFILENAME] file-control ** to have SQLite generate a ** temporary filename using the same algorithm that is followed to generate ** temporary filenames for TEMP tables and other internal uses. The ** argument should be a char** which will be filled with the filename ** written into memory obtained from [sqlite3_malloc()]. The caller should ** invoke [sqlite3_free()] on the result to avoid a memory leak. ** **
  • [[SQLITE_FCNTL_MMAP_SIZE]] ** The [SQLITE_FCNTL_MMAP_SIZE] file control is used to query or set the ** maximum number of bytes that will be used for memory-mapped I/O. ** The argument is a pointer to a value of type sqlite3_int64 that ** is an advisory maximum number of bytes in the file to memory map. The ** pointer is overwritten with the old value. The limit is not changed if ** the value originally pointed to is negative, and so the current limit ** can be queried by passing in a pointer to a negative number. This ** file-control is used internally to implement [PRAGMA mmap_size]. ** **
  • [[SQLITE_FCNTL_TRACE]] ** The [SQLITE_FCNTL_TRACE] file control provides advisory information ** to the VFS about what the higher layers of the SQLite stack are doing. ** This file control is used by some VFS activity tracing [shims]. ** The argument is a zero-terminated string. Higher layers in the ** SQLite stack may generate instances of this file control if ** the [SQLITE_USE_FCNTL_TRACE] compile-time option is enabled. ** **
  • [[SQLITE_FCNTL_HAS_MOVED]] ** The [SQLITE_FCNTL_HAS_MOVED] file control interprets its argument as a ** pointer to an integer and it writes a boolean into that integer depending ** on whether or not the file has been renamed, moved, or deleted since it ** was first opened. ** **
  • [[SQLITE_FCNTL_WIN32_GET_HANDLE]] ** The [SQLITE_FCNTL_WIN32_GET_HANDLE] opcode can be used to obtain the ** underlying native file handle associated with a file handle. This file ** control interprets its argument as a pointer to a native file handle and ** writes the resulting value there. ** **
  • [[SQLITE_FCNTL_WIN32_SET_HANDLE]] ** The [SQLITE_FCNTL_WIN32_SET_HANDLE] opcode is used for debugging. This ** opcode causes the xFileControl method to swap the file handle with the one ** pointed to by the pArg argument. This capability is used during testing ** and only needs to be supported when SQLITE_TEST is defined. ** **
  • [[SQLITE_FCNTL_WAL_BLOCK]] ** The [SQLITE_FCNTL_WAL_BLOCK] is a signal to the VFS layer that it might ** be advantageous to block on the next WAL lock if the lock is not immediately ** available. The WAL subsystem issues this signal during rare ** circumstances in order to fix a problem with priority inversion. ** Applications should not use this file-control. ** **
  • [[SQLITE_FCNTL_ZIPVFS]] ** The [SQLITE_FCNTL_ZIPVFS] opcode is implemented by zipvfs only. All other ** VFS should return SQLITE_NOTFOUND for this opcode. ** **
  • [[SQLITE_FCNTL_RBU]] ** The [SQLITE_FCNTL_RBU] opcode is implemented by the special VFS used by ** the RBU extension only. All other VFS should return SQLITE_NOTFOUND for ** this opcode. **
*/ #define SQLITE_FCNTL_LOCKSTATE 1 #define SQLITE_FCNTL_GET_LOCKPROXYFILE 2 #define SQLITE_FCNTL_SET_LOCKPROXYFILE 3 #define SQLITE_FCNTL_LAST_ERRNO 4 #define SQLITE_FCNTL_SIZE_HINT 5 #define SQLITE_FCNTL_CHUNK_SIZE 6 #define SQLITE_FCNTL_FILE_POINTER 7 #define SQLITE_FCNTL_SYNC_OMITTED 8 #define SQLITE_FCNTL_WIN32_AV_RETRY 9 #define SQLITE_FCNTL_PERSIST_WAL 10 #define SQLITE_FCNTL_OVERWRITE 11 #define SQLITE_FCNTL_VFSNAME 12 #define SQLITE_FCNTL_POWERSAFE_OVERWRITE 13 #define SQLITE_FCNTL_PRAGMA 14 #define SQLITE_FCNTL_BUSYHANDLER 15 #define SQLITE_FCNTL_TEMPFILENAME 16 #define SQLITE_FCNTL_MMAP_SIZE 18 #define SQLITE_FCNTL_TRACE 19 #define SQLITE_FCNTL_HAS_MOVED 20 #define SQLITE_FCNTL_SYNC 21 #define SQLITE_FCNTL_COMMIT_PHASETWO 22 #define SQLITE_FCNTL_WIN32_SET_HANDLE 23 #define SQLITE_FCNTL_WAL_BLOCK 24 #define SQLITE_FCNTL_ZIPVFS 25 #define SQLITE_FCNTL_RBU 26 #define SQLITE_FCNTL_VFS_POINTER 27 #define SQLITE_FCNTL_JOURNAL_POINTER 28 #define SQLITE_FCNTL_WIN32_GET_HANDLE 29 /* deprecated names */ #define SQLITE_GET_LOCKPROXYFILE SQLITE_FCNTL_GET_LOCKPROXYFILE #define SQLITE_SET_LOCKPROXYFILE SQLITE_FCNTL_SET_LOCKPROXYFILE #define SQLITE_LAST_ERRNO SQLITE_FCNTL_LAST_ERRNO /* ** CAPI3REF: Mutex Handle ** ** The mutex module within SQLite defines [sqlite3_mutex] to be an ** abstract type for a mutex object. The SQLite core never looks ** at the internal representation of an [sqlite3_mutex]. It only ** deals with pointers to the [sqlite3_mutex] object. ** ** Mutexes are created using [sqlite3_mutex_alloc()]. */ typedef struct sqlite3_mutex sqlite3_mutex; /* ** CAPI3REF: Loadable Extension Thunk ** ** A pointer to the opaque sqlite3_api_routines structure is passed as ** the third parameter to entry points of [loadable extensions]. This ** structure must be typedefed in order to work around compiler warnings ** on some platforms. */ typedef struct sqlite3_api_routines sqlite3_api_routines; /* ** CAPI3REF: OS Interface Object ** ** An instance of the sqlite3_vfs object defines the interface between ** the SQLite core and the underlying operating system. The "vfs" ** in the name of the object stands for "virtual file system". See ** the [VFS | VFS documentation] for further information. ** ** The value of the iVersion field is initially 1 but may be larger in ** future versions of SQLite. Additional fields may be appended to this ** object when the iVersion value is increased. Note that the structure ** of the sqlite3_vfs object changes in the transaction between ** SQLite version 3.5.9 and 3.6.0 and yet the iVersion field was not ** modified. ** ** The szOsFile field is the size of the subclassed [sqlite3_file] ** structure used by this VFS. mxPathname is the maximum length of ** a pathname in this VFS. ** ** Registered sqlite3_vfs objects are kept on a linked list formed by ** the pNext pointer. The [sqlite3_vfs_register()] ** and [sqlite3_vfs_unregister()] interfaces manage this list ** in a thread-safe way. The [sqlite3_vfs_find()] interface ** searches the list. Neither the application code nor the VFS ** implementation should use the pNext pointer. ** ** The pNext field is the only field in the sqlite3_vfs ** structure that SQLite will ever modify. SQLite will only access ** or modify this field while holding a particular static mutex. ** The application should never modify anything within the sqlite3_vfs ** object once the object has been registered. ** ** The zName field holds the name of the VFS module. The name must ** be unique across all VFS modules. ** ** [[sqlite3_vfs.xOpen]] ** ^SQLite guarantees that the zFilename parameter to xOpen ** is either a NULL pointer or string obtained ** from xFullPathname() with an optional suffix added. ** ^If a suffix is added to the zFilename parameter, it will ** consist of a single "-" character followed by no more than ** 11 alphanumeric and/or "-" characters. ** ^SQLite further guarantees that ** the string will be valid and unchanged until xClose() is ** called. Because of the previous sentence, ** the [sqlite3_file] can safely store a pointer to the ** filename if it needs to remember the filename for some reason. ** If the zFilename parameter to xOpen is a NULL pointer then xOpen ** must invent its own temporary name for the file. ^Whenever the ** xFilename parameter is NULL it will also be the case that the ** flags parameter will include [SQLITE_OPEN_DELETEONCLOSE]. ** ** The flags argument to xOpen() includes all bits set in ** the flags argument to [sqlite3_open_v2()]. Or if [sqlite3_open()] ** or [sqlite3_open16()] is used, then flags includes at least ** [SQLITE_OPEN_READWRITE] | [SQLITE_OPEN_CREATE]. ** If xOpen() opens a file read-only then it sets *pOutFlags to ** include [SQLITE_OPEN_READONLY]. Other bits in *pOutFlags may be set. ** ** ^(SQLite will also add one of the following flags to the xOpen() ** call, depending on the object being opened: ** **
    **
  • [SQLITE_OPEN_MAIN_DB] **
  • [SQLITE_OPEN_MAIN_JOURNAL] **
  • [SQLITE_OPEN_TEMP_DB] **
  • [SQLITE_OPEN_TEMP_JOURNAL] **
  • [SQLITE_OPEN_TRANSIENT_DB] **
  • [SQLITE_OPEN_SUBJOURNAL] **
  • [SQLITE_OPEN_MASTER_JOURNAL] **
  • [SQLITE_OPEN_WAL] **
)^ ** ** The file I/O implementation can use the object type flags to ** change the way it deals with files. For example, an application ** that does not care about crash recovery or rollback might make ** the open of a journal file a no-op. Writes to this journal would ** also be no-ops, and any attempt to read the journal would return ** SQLITE_IOERR. Or the implementation might recognize that a database ** file will be doing page-aligned sector reads and writes in a random ** order and set up its I/O subsystem accordingly. ** ** SQLite might also add one of the following flags to the xOpen method: ** **
    **
  • [SQLITE_OPEN_DELETEONCLOSE] **
  • [SQLITE_OPEN_EXCLUSIVE] **
** ** The [SQLITE_OPEN_DELETEONCLOSE] flag means the file should be ** deleted when it is closed. ^The [SQLITE_OPEN_DELETEONCLOSE] ** will be set for TEMP databases and their journals, transient ** databases, and subjournals. ** ** ^The [SQLITE_OPEN_EXCLUSIVE] flag is always used in conjunction ** with the [SQLITE_OPEN_CREATE] flag, which are both directly ** analogous to the O_EXCL and O_CREAT flags of the POSIX open() ** API. The SQLITE_OPEN_EXCLUSIVE flag, when paired with the ** SQLITE_OPEN_CREATE, is used to indicate that file should always ** be created, and that it is an error if it already exists. ** It is not used to indicate the file should be opened ** for exclusive access. ** ** ^At least szOsFile bytes of memory are allocated by SQLite ** to hold the [sqlite3_file] structure passed as the third ** argument to xOpen. The xOpen method does not have to ** allocate the structure; it should just fill it in. Note that ** the xOpen method must set the sqlite3_file.pMethods to either ** a valid [sqlite3_io_methods] object or to NULL. xOpen must do ** this even if the open fails. SQLite expects that the sqlite3_file.pMethods ** element will be valid after xOpen returns regardless of the success ** or failure of the xOpen call. ** ** [[sqlite3_vfs.xAccess]] ** ^The flags argument to xAccess() may be [SQLITE_ACCESS_EXISTS] ** to test for the existence of a file, or [SQLITE_ACCESS_READWRITE] to ** test whether a file is readable and writable, or [SQLITE_ACCESS_READ] ** to test whether a file is at least readable. The file can be a ** directory. ** ** ^SQLite will always allocate at least mxPathname+1 bytes for the ** output buffer xFullPathname. The exact size of the output buffer ** is also passed as a parameter to both methods. If the output buffer ** is not large enough, [SQLITE_CANTOPEN] should be returned. Since this is ** handled as a fatal error by SQLite, vfs implementations should endeavor ** to prevent this by setting mxPathname to a sufficiently large value. ** ** The xRandomness(), xSleep(), xCurrentTime(), and xCurrentTimeInt64() ** interfaces are not strictly a part of the filesystem, but they are ** included in the VFS structure for completeness. ** The xRandomness() function attempts to return nBytes bytes ** of good-quality randomness into zOut. The return value is ** the actual number of bytes of randomness obtained. ** The xSleep() method causes the calling thread to sleep for at ** least the number of microseconds given. ^The xCurrentTime() ** method returns a Julian Day Number for the current date and time as ** a floating point value. ** ^The xCurrentTimeInt64() method returns, as an integer, the Julian ** Day Number multiplied by 86400000 (the number of milliseconds in ** a 24-hour day). ** ^SQLite will use the xCurrentTimeInt64() method to get the current ** date and time if that method is available (if iVersion is 2 or ** greater and the function pointer is not NULL) and will fall back ** to xCurrentTime() if xCurrentTimeInt64() is unavailable. ** ** ^The xSetSystemCall(), xGetSystemCall(), and xNestSystemCall() interfaces ** are not used by the SQLite core. These optional interfaces are provided ** by some VFSes to facilitate testing of the VFS code. By overriding ** system calls with functions under its control, a test program can ** simulate faults and error conditions that would otherwise be difficult ** or impossible to induce. The set of system calls that can be overridden ** varies from one VFS to another, and from one version of the same VFS to the ** next. Applications that use these interfaces must be prepared for any ** or all of these interfaces to be NULL or for their behavior to change ** from one release to the next. Applications must not attempt to access ** any of these methods if the iVersion of the VFS is less than 3. */ typedef struct sqlite3_vfs sqlite3_vfs; typedef void (*sqlite3_syscall_ptr)(void); struct sqlite3_vfs { int iVersion; /* Structure version number (currently 3) */ int szOsFile; /* Size of subclassed sqlite3_file */ int mxPathname; /* Maximum file pathname length */ sqlite3_vfs *pNext; /* Next registered VFS */ const char *zName; /* Name of this virtual file system */ void *pAppData; /* Pointer to application-specific data */ int (*xOpen)(sqlite3_vfs*, const char *zName, sqlite3_file*, int flags, int *pOutFlags); int (*xDelete)(sqlite3_vfs*, const char *zName, int syncDir); int (*xAccess)(sqlite3_vfs*, const char *zName, int flags, int *pResOut); int (*xFullPathname)(sqlite3_vfs*, const char *zName, int nOut, char *zOut); void *(*xDlOpen)(sqlite3_vfs*, const char *zFilename); void (*xDlError)(sqlite3_vfs*, int nByte, char *zErrMsg); void (*(*xDlSym)(sqlite3_vfs*,void*, const char *zSymbol))(void); void (*xDlClose)(sqlite3_vfs*, void*); int (*xRandomness)(sqlite3_vfs*, int nByte, char *zOut); int (*xSleep)(sqlite3_vfs*, int microseconds); int (*xCurrentTime)(sqlite3_vfs*, double*); int (*xGetLastError)(sqlite3_vfs*, int, char *); /* ** The methods above are in version 1 of the sqlite_vfs object ** definition. Those that follow are added in version 2 or later */ int (*xCurrentTimeInt64)(sqlite3_vfs*, sqlite3_int64*); /* ** The methods above are in versions 1 and 2 of the sqlite_vfs object. ** Those below are for version 3 and greater. */ int (*xSetSystemCall)(sqlite3_vfs*, const char *zName, sqlite3_syscall_ptr); sqlite3_syscall_ptr (*xGetSystemCall)(sqlite3_vfs*, const char *zName); const char *(*xNextSystemCall)(sqlite3_vfs*, const char *zName); /* ** The methods above are in versions 1 through 3 of the sqlite_vfs object. ** New fields may be appended in future versions. The iVersion ** value will increment whenever this happens. */ }; /* ** CAPI3REF: Flags for the xAccess VFS method ** ** These integer constants can be used as the third parameter to ** the xAccess method of an [sqlite3_vfs] object. They determine ** what kind of permissions the xAccess method is looking for. ** With SQLITE_ACCESS_EXISTS, the xAccess method ** simply checks whether the file exists. ** With SQLITE_ACCESS_READWRITE, the xAccess method ** checks whether the named directory is both readable and writable ** (in other words, if files can be added, removed, and renamed within ** the directory). ** The SQLITE_ACCESS_READWRITE constant is currently used only by the ** [temp_store_directory pragma], though this could change in a future ** release of SQLite. ** With SQLITE_ACCESS_READ, the xAccess method ** checks whether the file is readable. The SQLITE_ACCESS_READ constant is ** currently unused, though it might be used in a future release of ** SQLite. */ #define SQLITE_ACCESS_EXISTS 0 #define SQLITE_ACCESS_READWRITE 1 /* Used by PRAGMA temp_store_directory */ #define SQLITE_ACCESS_READ 2 /* Unused */ /* ** CAPI3REF: Flags for the xShmLock VFS method ** ** These integer constants define the various locking operations ** allowed by the xShmLock method of [sqlite3_io_methods]. The ** following are the only legal combinations of flags to the ** xShmLock method: ** **
    **
  • SQLITE_SHM_LOCK | SQLITE_SHM_SHARED **
  • SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE **
  • SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED **
  • SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE **
** ** When unlocking, the same SHARED or EXCLUSIVE flag must be supplied as ** was given on the corresponding lock. ** ** The xShmLock method can transition between unlocked and SHARED or ** between unlocked and EXCLUSIVE. It cannot transition between SHARED ** and EXCLUSIVE. */ #define SQLITE_SHM_UNLOCK 1 #define SQLITE_SHM_LOCK 2 #define SQLITE_SHM_SHARED 4 #define SQLITE_SHM_EXCLUSIVE 8 /* ** CAPI3REF: Maximum xShmLock index ** ** The xShmLock method on [sqlite3_io_methods] may use values ** between 0 and this upper bound as its "offset" argument. ** The SQLite core will never attempt to acquire or release a ** lock outside of this range */ #define SQLITE_SHM_NLOCK 8 /* ** CAPI3REF: Initialize The SQLite Library ** ** ^The sqlite3_initialize() routine initializes the ** SQLite library. ^The sqlite3_shutdown() routine ** deallocates any resources that were allocated by sqlite3_initialize(). ** These routines are designed to aid in process initialization and ** shutdown on embedded systems. Workstation applications using ** SQLite normally do not need to invoke either of these routines. ** ** A call to sqlite3_initialize() is an "effective" call if it is ** the first time sqlite3_initialize() is invoked during the lifetime of ** the process, or if it is the first time sqlite3_initialize() is invoked ** following a call to sqlite3_shutdown(). ^(Only an effective call ** of sqlite3_initialize() does any initialization. All other calls ** are harmless no-ops.)^ ** ** A call to sqlite3_shutdown() is an "effective" call if it is the first ** call to sqlite3_shutdown() since the last sqlite3_initialize(). ^(Only ** an effective call to sqlite3_shutdown() does any deinitialization. ** All other valid calls to sqlite3_shutdown() are harmless no-ops.)^ ** ** The sqlite3_initialize() interface is threadsafe, but sqlite3_shutdown() ** is not. The sqlite3_shutdown() interface must only be called from a ** single thread. All open [database connections] must be closed and all ** other SQLite resources must be deallocated prior to invoking ** sqlite3_shutdown(). ** ** Among other things, ^sqlite3_initialize() will invoke ** sqlite3_os_init(). Similarly, ^sqlite3_shutdown() ** will invoke sqlite3_os_end(). ** ** ^The sqlite3_initialize() routine returns [SQLITE_OK] on success. ** ^If for some reason, sqlite3_initialize() is unable to initialize ** the library (perhaps it is unable to allocate a needed resource such ** as a mutex) it returns an [error code] other than [SQLITE_OK]. ** ** ^The sqlite3_initialize() routine is called internally by many other ** SQLite interfaces so that an application usually does not need to ** invoke sqlite3_initialize() directly. For example, [sqlite3_open()] ** calls sqlite3_initialize() so the SQLite library will be automatically ** initialized when [sqlite3_open()] is called if it has not be initialized ** already. ^However, if SQLite is compiled with the [SQLITE_OMIT_AUTOINIT] ** compile-time option, then the automatic calls to sqlite3_initialize() ** are omitted and the application must call sqlite3_initialize() directly ** prior to using any other SQLite interface. For maximum portability, ** it is recommended that applications always invoke sqlite3_initialize() ** directly prior to using any other SQLite interface. Future releases ** of SQLite may require this. In other words, the behavior exhibited ** when SQLite is compiled with [SQLITE_OMIT_AUTOINIT] might become the ** default behavior in some future release of SQLite. ** ** The sqlite3_os_init() routine does operating-system specific ** initialization of the SQLite library. The sqlite3_os_end() ** routine undoes the effect of sqlite3_os_init(). Typical tasks ** performed by these routines include allocation or deallocation ** of static resources, initialization of global variables, ** setting up a default [sqlite3_vfs] module, or setting up ** a default configuration using [sqlite3_config()]. ** ** The application should never invoke either sqlite3_os_init() ** or sqlite3_os_end() directly. The application should only invoke ** sqlite3_initialize() and sqlite3_shutdown(). The sqlite3_os_init() ** interface is called automatically by sqlite3_initialize() and ** sqlite3_os_end() is called by sqlite3_shutdown(). Appropriate ** implementations for sqlite3_os_init() and sqlite3_os_end() ** are built into SQLite when it is compiled for Unix, Windows, or OS/2. ** When [custom builds | built for other platforms] ** (using the [SQLITE_OS_OTHER=1] compile-time ** option) the application must supply a suitable implementation for ** sqlite3_os_init() and sqlite3_os_end(). An application-supplied ** implementation of sqlite3_os_init() or sqlite3_os_end() ** must return [SQLITE_OK] on success and some other [error code] upon ** failure. */ SQLITE_API int sqlite3_initialize(void); SQLITE_API int sqlite3_shutdown(void); SQLITE_API int sqlite3_os_init(void); SQLITE_API int sqlite3_os_end(void); /* ** CAPI3REF: Configuring The SQLite Library ** ** The sqlite3_config() interface is used to make global configuration ** changes to SQLite in order to tune SQLite to the specific needs of ** the application. The default configuration is recommended for most ** applications and so this routine is usually not necessary. It is ** provided to support rare applications with unusual needs. ** ** The sqlite3_config() interface is not threadsafe. The application ** must ensure that no other SQLite interfaces are invoked by other ** threads while sqlite3_config() is running. ** ** The sqlite3_config() interface ** may only be invoked prior to library initialization using ** [sqlite3_initialize()] or after shutdown by [sqlite3_shutdown()]. ** ^If sqlite3_config() is called after [sqlite3_initialize()] and before ** [sqlite3_shutdown()] then it will return SQLITE_MISUSE. ** Note, however, that ^sqlite3_config() can be called as part of the ** implementation of an application-defined [sqlite3_os_init()]. ** ** The first argument to sqlite3_config() is an integer ** [configuration option] that determines ** what property of SQLite is to be configured. Subsequent arguments ** vary depending on the [configuration option] ** in the first argument. ** ** ^When a configuration option is set, sqlite3_config() returns [SQLITE_OK]. ** ^If the option is unknown or SQLite is unable to set the option ** then this routine returns a non-zero [error code]. */ SQLITE_API int sqlite3_config(int, ...); /* ** CAPI3REF: Configure database connections ** METHOD: sqlite3 ** ** The sqlite3_db_config() interface is used to make configuration ** changes to a [database connection]. The interface is similar to ** [sqlite3_config()] except that the changes apply to a single ** [database connection] (specified in the first argument). ** ** The second argument to sqlite3_db_config(D,V,...) is the ** [SQLITE_DBCONFIG_LOOKASIDE | configuration verb] - an integer code ** that indicates what aspect of the [database connection] is being configured. ** Subsequent arguments vary depending on the configuration verb. ** ** ^Calls to sqlite3_db_config() return SQLITE_OK if and only if ** the call is considered successful. */ SQLITE_API int sqlite3_db_config(sqlite3*, int op, ...); /* ** CAPI3REF: Memory Allocation Routines ** ** An instance of this object defines the interface between SQLite ** and low-level memory allocation routines. ** ** This object is used in only one place in the SQLite interface. ** A pointer to an instance of this object is the argument to ** [sqlite3_config()] when the configuration option is ** [SQLITE_CONFIG_MALLOC] or [SQLITE_CONFIG_GETMALLOC]. ** By creating an instance of this object ** and passing it to [sqlite3_config]([SQLITE_CONFIG_MALLOC]) ** during configuration, an application can specify an alternative ** memory allocation subsystem for SQLite to use for all of its ** dynamic memory needs. ** ** Note that SQLite comes with several [built-in memory allocators] ** that are perfectly adequate for the overwhelming majority of applications ** and that this object is only useful to a tiny minority of applications ** with specialized memory allocation requirements. This object is ** also used during testing of SQLite in order to specify an alternative ** memory allocator that simulates memory out-of-memory conditions in ** order to verify that SQLite recovers gracefully from such ** conditions. ** ** The xMalloc, xRealloc, and xFree methods must work like the ** malloc(), realloc() and free() functions from the standard C library. ** ^SQLite guarantees that the second argument to ** xRealloc is always a value returned by a prior call to xRoundup. ** ** xSize should return the allocated size of a memory allocation ** previously obtained from xMalloc or xRealloc. The allocated size ** is always at least as big as the requested size but may be larger. ** ** The xRoundup method returns what would be the allocated size of ** a memory allocation given a particular requested size. Most memory ** allocators round up memory allocations at least to the next multiple ** of 8. Some allocators round up to a larger multiple or to a power of 2. ** Every memory allocation request coming in through [sqlite3_malloc()] ** or [sqlite3_realloc()] first calls xRoundup. If xRoundup returns 0, ** that causes the corresponding memory allocation to fail. ** ** The xInit method initializes the memory allocator. For example, ** it might allocate any require mutexes or initialize internal data ** structures. The xShutdown method is invoked (indirectly) by ** [sqlite3_shutdown()] and should deallocate any resources acquired ** by xInit. The pAppData pointer is used as the only parameter to ** xInit and xShutdown. ** ** SQLite holds the [SQLITE_MUTEX_STATIC_MASTER] mutex when it invokes ** the xInit method, so the xInit method need not be threadsafe. The ** xShutdown method is only called from [sqlite3_shutdown()] so it does ** not need to be threadsafe either. For all other methods, SQLite ** holds the [SQLITE_MUTEX_STATIC_MEM] mutex as long as the ** [SQLITE_CONFIG_MEMSTATUS] configuration option is turned on (which ** it is by default) and so the methods are automatically serialized. ** However, if [SQLITE_CONFIG_MEMSTATUS] is disabled, then the other ** methods must be threadsafe or else make their own arrangements for ** serialization. ** ** SQLite will never invoke xInit() more than once without an intervening ** call to xShutdown(). */ typedef struct sqlite3_mem_methods sqlite3_mem_methods; struct sqlite3_mem_methods { void *(*xMalloc)(int); /* Memory allocation function */ void (*xFree)(void*); /* Free a prior allocation */ void *(*xRealloc)(void*,int); /* Resize an allocation */ int (*xSize)(void*); /* Return the size of an allocation */ int (*xRoundup)(int); /* Round up request size to allocation size */ int (*xInit)(void*); /* Initialize the memory allocator */ void (*xShutdown)(void*); /* Deinitialize the memory allocator */ void *pAppData; /* Argument to xInit() and xShutdown() */ }; /* ** CAPI3REF: Configuration Options ** KEYWORDS: {configuration option} ** ** These constants are the available integer configuration options that ** can be passed as the first argument to the [sqlite3_config()] interface. ** ** New configuration options may be added in future releases of SQLite. ** Existing configuration options might be discontinued. Applications ** should check the return code from [sqlite3_config()] to make sure that ** the call worked. The [sqlite3_config()] interface will return a ** non-zero [error code] if a discontinued or unsupported configuration option ** is invoked. ** **
** [[SQLITE_CONFIG_SINGLETHREAD]]
SQLITE_CONFIG_SINGLETHREAD
**
There are no arguments to this option. ^This option sets the ** [threading mode] to Single-thread. In other words, it disables ** all mutexing and puts SQLite into a mode where it can only be used ** by a single thread. ^If SQLite is compiled with ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then ** it is not possible to change the [threading mode] from its default ** value of Single-thread and so [sqlite3_config()] will return ** [SQLITE_ERROR] if called with the SQLITE_CONFIG_SINGLETHREAD ** configuration option.
** ** [[SQLITE_CONFIG_MULTITHREAD]]
SQLITE_CONFIG_MULTITHREAD
**
There are no arguments to this option. ^This option sets the ** [threading mode] to Multi-thread. In other words, it disables ** mutexing on [database connection] and [prepared statement] objects. ** The application is responsible for serializing access to ** [database connections] and [prepared statements]. But other mutexes ** are enabled so that SQLite will be safe to use in a multi-threaded ** environment as long as no two threads attempt to use the same ** [database connection] at the same time. ^If SQLite is compiled with ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then ** it is not possible to set the Multi-thread [threading mode] and ** [sqlite3_config()] will return [SQLITE_ERROR] if called with the ** SQLITE_CONFIG_MULTITHREAD configuration option.
** ** [[SQLITE_CONFIG_SERIALIZED]]
SQLITE_CONFIG_SERIALIZED
**
There are no arguments to this option. ^This option sets the ** [threading mode] to Serialized. In other words, this option enables ** all mutexes including the recursive ** mutexes on [database connection] and [prepared statement] objects. ** In this mode (which is the default when SQLite is compiled with ** [SQLITE_THREADSAFE=1]) the SQLite library will itself serialize access ** to [database connections] and [prepared statements] so that the ** application is free to use the same [database connection] or the ** same [prepared statement] in different threads at the same time. ** ^If SQLite is compiled with ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then ** it is not possible to set the Serialized [threading mode] and ** [sqlite3_config()] will return [SQLITE_ERROR] if called with the ** SQLITE_CONFIG_SERIALIZED configuration option.
** ** [[SQLITE_CONFIG_MALLOC]]
SQLITE_CONFIG_MALLOC
**
^(The SQLITE_CONFIG_MALLOC option takes a single argument which is ** a pointer to an instance of the [sqlite3_mem_methods] structure. ** The argument specifies ** alternative low-level memory allocation routines to be used in place of ** the memory allocation routines built into SQLite.)^ ^SQLite makes ** its own private copy of the content of the [sqlite3_mem_methods] structure ** before the [sqlite3_config()] call returns.
** ** [[SQLITE_CONFIG_GETMALLOC]]
SQLITE_CONFIG_GETMALLOC
**
^(The SQLITE_CONFIG_GETMALLOC option takes a single argument which ** is a pointer to an instance of the [sqlite3_mem_methods] structure. ** The [sqlite3_mem_methods] ** structure is filled with the currently defined memory allocation routines.)^ ** This option can be used to overload the default memory allocation ** routines with a wrapper that simulations memory allocation failure or ** tracks memory usage, for example.
** ** [[SQLITE_CONFIG_MEMSTATUS]]
SQLITE_CONFIG_MEMSTATUS
**
^The SQLITE_CONFIG_MEMSTATUS option takes single argument of type int, ** interpreted as a boolean, which enables or disables the collection of ** memory allocation statistics. ^(When memory allocation statistics are ** disabled, the following SQLite interfaces become non-operational: **
    **
  • [sqlite3_memory_used()] **
  • [sqlite3_memory_highwater()] **
  • [sqlite3_soft_heap_limit64()] **
  • [sqlite3_status64()] **
)^ ** ^Memory allocation statistics are enabled by default unless SQLite is ** compiled with [SQLITE_DEFAULT_MEMSTATUS]=0 in which case memory ** allocation statistics are disabled by default. **
** ** [[SQLITE_CONFIG_SCRATCH]]
SQLITE_CONFIG_SCRATCH
**
^The SQLITE_CONFIG_SCRATCH option specifies a static memory buffer ** that SQLite can use for scratch memory. ^(There are three arguments ** to SQLITE_CONFIG_SCRATCH: A pointer an 8-byte ** aligned memory buffer from which the scratch allocations will be ** drawn, the size of each scratch allocation (sz), ** and the maximum number of scratch allocations (N).)^ ** The first argument must be a pointer to an 8-byte aligned buffer ** of at least sz*N bytes of memory. ** ^SQLite will not use more than one scratch buffers per thread. ** ^SQLite will never request a scratch buffer that is more than 6 ** times the database page size. ** ^If SQLite needs needs additional ** scratch memory beyond what is provided by this configuration option, then ** [sqlite3_malloc()] will be used to obtain the memory needed.

** ^When the application provides any amount of scratch memory using ** SQLITE_CONFIG_SCRATCH, SQLite avoids unnecessary large ** [sqlite3_malloc|heap allocations]. ** This can help [Robson proof|prevent memory allocation failures] due to heap ** fragmentation in low-memory embedded systems. **

** ** [[SQLITE_CONFIG_PAGECACHE]]
SQLITE_CONFIG_PAGECACHE
**
^The SQLITE_CONFIG_PAGECACHE option specifies a memory pool ** that SQLite can use for the database page cache with the default page ** cache implementation. ** This configuration option is a no-op if an application-define page ** cache implementation is loaded using the [SQLITE_CONFIG_PCACHE2]. ** ^There are three arguments to SQLITE_CONFIG_PAGECACHE: A pointer to ** 8-byte aligned memory (pMem), the size of each page cache line (sz), ** and the number of cache lines (N). ** The sz argument should be the size of the largest database page ** (a power of two between 512 and 65536) plus some extra bytes for each ** page header. ^The number of extra bytes needed by the page header ** can be determined using [SQLITE_CONFIG_PCACHE_HDRSZ]. ** ^It is harmless, apart from the wasted memory, ** for the sz parameter to be larger than necessary. The pMem ** argument must be either a NULL pointer or a pointer to an 8-byte ** aligned block of memory of at least sz*N bytes, otherwise ** subsequent behavior is undefined. ** ^When pMem is not NULL, SQLite will strive to use the memory provided ** to satisfy page cache needs, falling back to [sqlite3_malloc()] if ** a page cache line is larger than sz bytes or if all of the pMem buffer ** is exhausted. ** ^If pMem is NULL and N is non-zero, then each database connection ** does an initial bulk allocation for page cache memory ** from [sqlite3_malloc()] sufficient for N cache lines if N is positive or ** of -1024*N bytes if N is negative, . ^If additional ** page cache memory is needed beyond what is provided by the initial ** allocation, then SQLite goes to [sqlite3_malloc()] separately for each ** additional cache line.
** ** [[SQLITE_CONFIG_HEAP]]
SQLITE_CONFIG_HEAP
**
^The SQLITE_CONFIG_HEAP option specifies a static memory buffer ** that SQLite will use for all of its dynamic memory allocation needs ** beyond those provided for by [SQLITE_CONFIG_SCRATCH] and ** [SQLITE_CONFIG_PAGECACHE]. ** ^The SQLITE_CONFIG_HEAP option is only available if SQLite is compiled ** with either [SQLITE_ENABLE_MEMSYS3] or [SQLITE_ENABLE_MEMSYS5] and returns ** [SQLITE_ERROR] if invoked otherwise. ** ^There are three arguments to SQLITE_CONFIG_HEAP: ** An 8-byte aligned pointer to the memory, ** the number of bytes in the memory buffer, and the minimum allocation size. ** ^If the first pointer (the memory pointer) is NULL, then SQLite reverts ** to using its default memory allocator (the system malloc() implementation), ** undoing any prior invocation of [SQLITE_CONFIG_MALLOC]. ^If the ** memory pointer is not NULL then the alternative memory ** allocator is engaged to handle all of SQLites memory allocation needs. ** The first pointer (the memory pointer) must be aligned to an 8-byte ** boundary or subsequent behavior of SQLite will be undefined. ** The minimum allocation size is capped at 2**12. Reasonable values ** for the minimum allocation size are 2**5 through 2**8.
** ** [[SQLITE_CONFIG_MUTEX]]
SQLITE_CONFIG_MUTEX
**
^(The SQLITE_CONFIG_MUTEX option takes a single argument which is a ** pointer to an instance of the [sqlite3_mutex_methods] structure. ** The argument specifies alternative low-level mutex routines to be used ** in place the mutex routines built into SQLite.)^ ^SQLite makes a copy of ** the content of the [sqlite3_mutex_methods] structure before the call to ** [sqlite3_config()] returns. ^If SQLite is compiled with ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then ** the entire mutexing subsystem is omitted from the build and hence calls to ** [sqlite3_config()] with the SQLITE_CONFIG_MUTEX configuration option will ** return [SQLITE_ERROR].
** ** [[SQLITE_CONFIG_GETMUTEX]]
SQLITE_CONFIG_GETMUTEX
**
^(The SQLITE_CONFIG_GETMUTEX option takes a single argument which ** is a pointer to an instance of the [sqlite3_mutex_methods] structure. The ** [sqlite3_mutex_methods] ** structure is filled with the currently defined mutex routines.)^ ** This option can be used to overload the default mutex allocation ** routines with a wrapper used to track mutex usage for performance ** profiling or testing, for example. ^If SQLite is compiled with ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then ** the entire mutexing subsystem is omitted from the build and hence calls to ** [sqlite3_config()] with the SQLITE_CONFIG_GETMUTEX configuration option will ** return [SQLITE_ERROR].
** ** [[SQLITE_CONFIG_LOOKASIDE]]
SQLITE_CONFIG_LOOKASIDE
**
^(The SQLITE_CONFIG_LOOKASIDE option takes two arguments that determine ** the default size of lookaside memory on each [database connection]. ** The first argument is the ** size of each lookaside buffer slot and the second is the number of ** slots allocated to each database connection.)^ ^(SQLITE_CONFIG_LOOKASIDE ** sets the default lookaside size. The [SQLITE_DBCONFIG_LOOKASIDE] ** option to [sqlite3_db_config()] can be used to change the lookaside ** configuration on individual connections.)^
** ** [[SQLITE_CONFIG_PCACHE2]]
SQLITE_CONFIG_PCACHE2
**
^(The SQLITE_CONFIG_PCACHE2 option takes a single argument which is ** a pointer to an [sqlite3_pcache_methods2] object. This object specifies ** the interface to a custom page cache implementation.)^ ** ^SQLite makes a copy of the [sqlite3_pcache_methods2] object.
** ** [[SQLITE_CONFIG_GETPCACHE2]]
SQLITE_CONFIG_GETPCACHE2
**
^(The SQLITE_CONFIG_GETPCACHE2 option takes a single argument which ** is a pointer to an [sqlite3_pcache_methods2] object. SQLite copies of ** the current page cache implementation into that object.)^
** ** [[SQLITE_CONFIG_LOG]]
SQLITE_CONFIG_LOG
**
The SQLITE_CONFIG_LOG option is used to configure the SQLite ** global [error log]. ** (^The SQLITE_CONFIG_LOG option takes two arguments: a pointer to a ** function with a call signature of void(*)(void*,int,const char*), ** and a pointer to void. ^If the function pointer is not NULL, it is ** invoked by [sqlite3_log()] to process each logging event. ^If the ** function pointer is NULL, the [sqlite3_log()] interface becomes a no-op. ** ^The void pointer that is the second argument to SQLITE_CONFIG_LOG is ** passed through as the first parameter to the application-defined logger ** function whenever that function is invoked. ^The second parameter to ** the logger function is a copy of the first parameter to the corresponding ** [sqlite3_log()] call and is intended to be a [result code] or an ** [extended result code]. ^The third parameter passed to the logger is ** log message after formatting via [sqlite3_snprintf()]. ** The SQLite logging interface is not reentrant; the logger function ** supplied by the application must not invoke any SQLite interface. ** In a multi-threaded application, the application-defined logger ** function must be threadsafe.
** ** [[SQLITE_CONFIG_URI]]
SQLITE_CONFIG_URI **
^(The SQLITE_CONFIG_URI option takes a single argument of type int. ** If non-zero, then URI handling is globally enabled. If the parameter is zero, ** then URI handling is globally disabled.)^ ^If URI handling is globally ** enabled, all filenames passed to [sqlite3_open()], [sqlite3_open_v2()], ** [sqlite3_open16()] or ** specified as part of [ATTACH] commands are interpreted as URIs, regardless ** of whether or not the [SQLITE_OPEN_URI] flag is set when the database ** connection is opened. ^If it is globally disabled, filenames are ** only interpreted as URIs if the SQLITE_OPEN_URI flag is set when the ** database connection is opened. ^(By default, URI handling is globally ** disabled. The default value may be changed by compiling with the ** [SQLITE_USE_URI] symbol defined.)^ ** ** [[SQLITE_CONFIG_COVERING_INDEX_SCAN]]
SQLITE_CONFIG_COVERING_INDEX_SCAN **
^The SQLITE_CONFIG_COVERING_INDEX_SCAN option takes a single integer ** argument which is interpreted as a boolean in order to enable or disable ** the use of covering indices for full table scans in the query optimizer. ** ^The default setting is determined ** by the [SQLITE_ALLOW_COVERING_INDEX_SCAN] compile-time option, or is "on" ** if that compile-time option is omitted. ** The ability to disable the use of covering indices for full table scans ** is because some incorrectly coded legacy applications might malfunction ** when the optimization is enabled. Providing the ability to ** disable the optimization allows the older, buggy application code to work ** without change even with newer versions of SQLite. ** ** [[SQLITE_CONFIG_PCACHE]] [[SQLITE_CONFIG_GETPCACHE]] **
SQLITE_CONFIG_PCACHE and SQLITE_CONFIG_GETPCACHE **
These options are obsolete and should not be used by new code. ** They are retained for backwards compatibility but are now no-ops. **
** ** [[SQLITE_CONFIG_SQLLOG]] **
SQLITE_CONFIG_SQLLOG **
This option is only available if sqlite is compiled with the ** [SQLITE_ENABLE_SQLLOG] pre-processor macro defined. The first argument should ** be a pointer to a function of type void(*)(void*,sqlite3*,const char*, int). ** The second should be of type (void*). The callback is invoked by the library ** in three separate circumstances, identified by the value passed as the ** fourth parameter. If the fourth parameter is 0, then the database connection ** passed as the second argument has just been opened. The third argument ** points to a buffer containing the name of the main database file. If the ** fourth parameter is 1, then the SQL statement that the third parameter ** points to has just been executed. Or, if the fourth parameter is 2, then ** the connection being passed as the second parameter is being closed. The ** third parameter is passed NULL In this case. An example of using this ** configuration option can be seen in the "test_sqllog.c" source file in ** the canonical SQLite source tree.
** ** [[SQLITE_CONFIG_MMAP_SIZE]] **
SQLITE_CONFIG_MMAP_SIZE **
^SQLITE_CONFIG_MMAP_SIZE takes two 64-bit integer (sqlite3_int64) values ** that are the default mmap size limit (the default setting for ** [PRAGMA mmap_size]) and the maximum allowed mmap size limit. ** ^The default setting can be overridden by each database connection using ** either the [PRAGMA mmap_size] command, or by using the ** [SQLITE_FCNTL_MMAP_SIZE] file control. ^(The maximum allowed mmap size ** will be silently truncated if necessary so that it does not exceed the ** compile-time maximum mmap size set by the ** [SQLITE_MAX_MMAP_SIZE] compile-time option.)^ ** ^If either argument to this option is negative, then that argument is ** changed to its compile-time default. ** ** [[SQLITE_CONFIG_WIN32_HEAPSIZE]] **
SQLITE_CONFIG_WIN32_HEAPSIZE **
^The SQLITE_CONFIG_WIN32_HEAPSIZE option is only available if SQLite is ** compiled for Windows with the [SQLITE_WIN32_MALLOC] pre-processor macro ** defined. ^SQLITE_CONFIG_WIN32_HEAPSIZE takes a 32-bit unsigned integer value ** that specifies the maximum size of the created heap. ** ** [[SQLITE_CONFIG_PCACHE_HDRSZ]] **
SQLITE_CONFIG_PCACHE_HDRSZ **
^The SQLITE_CONFIG_PCACHE_HDRSZ option takes a single parameter which ** is a pointer to an integer and writes into that integer the number of extra ** bytes per page required for each page in [SQLITE_CONFIG_PAGECACHE]. ** The amount of extra space required can change depending on the compiler, ** target platform, and SQLite version. ** ** [[SQLITE_CONFIG_PMASZ]] **
SQLITE_CONFIG_PMASZ **
^The SQLITE_CONFIG_PMASZ option takes a single parameter which ** is an unsigned integer and sets the "Minimum PMA Size" for the multithreaded ** sorter to that integer. The default minimum PMA Size is set by the ** [SQLITE_SORTER_PMASZ] compile-time option. New threads are launched ** to help with sort operations when multithreaded sorting ** is enabled (using the [PRAGMA threads] command) and the amount of content ** to be sorted exceeds the page size times the minimum of the ** [PRAGMA cache_size] setting and this value. ** ** [[SQLITE_CONFIG_STMTJRNL_SPILL]] **
SQLITE_CONFIG_STMTJRNL_SPILL **
^The SQLITE_CONFIG_STMTJRNL_SPILL option takes a single parameter which ** becomes the [statement journal] spill-to-disk threshold. ** [Statement journals] are held in memory until their size (in bytes) ** exceeds this threshold, at which point they are written to disk. ** Or if the threshold is -1, statement journals are always held ** exclusively in memory. ** Since many statement journals never become large, setting the spill ** threshold to a value such as 64KiB can greatly reduce the amount of ** I/O required to support statement rollback. ** The default value for this setting is controlled by the ** [SQLITE_STMTJRNL_SPILL] compile-time option. **
*/ #define SQLITE_CONFIG_SINGLETHREAD 1 /* nil */ #define SQLITE_CONFIG_MULTITHREAD 2 /* nil */ #define SQLITE_CONFIG_SERIALIZED 3 /* nil */ #define SQLITE_CONFIG_MALLOC 4 /* sqlite3_mem_methods* */ #define SQLITE_CONFIG_GETMALLOC 5 /* sqlite3_mem_methods* */ #define SQLITE_CONFIG_SCRATCH 6 /* void*, int sz, int N */ #define SQLITE_CONFIG_PAGECACHE 7 /* void*, int sz, int N */ #define SQLITE_CONFIG_HEAP 8 /* void*, int nByte, int min */ #define SQLITE_CONFIG_MEMSTATUS 9 /* boolean */ #define SQLITE_CONFIG_MUTEX 10 /* sqlite3_mutex_methods* */ #define SQLITE_CONFIG_GETMUTEX 11 /* sqlite3_mutex_methods* */ /* previously SQLITE_CONFIG_CHUNKALLOC 12 which is now unused. */ #define SQLITE_CONFIG_LOOKASIDE 13 /* int int */ #define SQLITE_CONFIG_PCACHE 14 /* no-op */ #define SQLITE_CONFIG_GETPCACHE 15 /* no-op */ #define SQLITE_CONFIG_LOG 16 /* xFunc, void* */ #define SQLITE_CONFIG_URI 17 /* int */ #define SQLITE_CONFIG_PCACHE2 18 /* sqlite3_pcache_methods2* */ #define SQLITE_CONFIG_GETPCACHE2 19 /* sqlite3_pcache_methods2* */ #define SQLITE_CONFIG_COVERING_INDEX_SCAN 20 /* int */ #define SQLITE_CONFIG_SQLLOG 21 /* xSqllog, void* */ #define SQLITE_CONFIG_MMAP_SIZE 22 /* sqlite3_int64, sqlite3_int64 */ #define SQLITE_CONFIG_WIN32_HEAPSIZE 23 /* int nByte */ #define SQLITE_CONFIG_PCACHE_HDRSZ 24 /* int *psz */ #define SQLITE_CONFIG_PMASZ 25 /* unsigned int szPma */ #define SQLITE_CONFIG_STMTJRNL_SPILL 26 /* int nByte */ /* ** CAPI3REF: Database Connection Configuration Options ** ** These constants are the available integer configuration options that ** can be passed as the second argument to the [sqlite3_db_config()] interface. ** ** New configuration options may be added in future releases of SQLite. ** Existing configuration options might be discontinued. Applications ** should check the return code from [sqlite3_db_config()] to make sure that ** the call worked. ^The [sqlite3_db_config()] interface will return a ** non-zero [error code] if a discontinued or unsupported configuration option ** is invoked. ** **
**
SQLITE_DBCONFIG_LOOKASIDE
**
^This option takes three additional arguments that determine the ** [lookaside memory allocator] configuration for the [database connection]. ** ^The first argument (the third parameter to [sqlite3_db_config()] is a ** pointer to a memory buffer to use for lookaside memory. ** ^The first argument after the SQLITE_DBCONFIG_LOOKASIDE verb ** may be NULL in which case SQLite will allocate the ** lookaside buffer itself using [sqlite3_malloc()]. ^The second argument is the ** size of each lookaside buffer slot. ^The third argument is the number of ** slots. The size of the buffer in the first argument must be greater than ** or equal to the product of the second and third arguments. The buffer ** must be aligned to an 8-byte boundary. ^If the second argument to ** SQLITE_DBCONFIG_LOOKASIDE is not a multiple of 8, it is internally ** rounded down to the next smaller multiple of 8. ^(The lookaside memory ** configuration for a database connection can only be changed when that ** connection is not currently using lookaside memory, or in other words ** when the "current value" returned by ** [sqlite3_db_status](D,[SQLITE_CONFIG_LOOKASIDE],...) is zero. ** Any attempt to change the lookaside memory configuration when lookaside ** memory is in use leaves the configuration unchanged and returns ** [SQLITE_BUSY].)^
** **
SQLITE_DBCONFIG_ENABLE_FKEY
**
^This option is used to enable or disable the enforcement of ** [foreign key constraints]. There should be two additional arguments. ** The first argument is an integer which is 0 to disable FK enforcement, ** positive to enable FK enforcement or negative to leave FK enforcement ** unchanged. The second parameter is a pointer to an integer into which ** is written 0 or 1 to indicate whether FK enforcement is off or on ** following this call. The second parameter may be a NULL pointer, in ** which case the FK enforcement setting is not reported back.
** **
SQLITE_DBCONFIG_ENABLE_TRIGGER
**
^This option is used to enable or disable [CREATE TRIGGER | triggers]. ** There should be two additional arguments. ** The first argument is an integer which is 0 to disable triggers, ** positive to enable triggers or negative to leave the setting unchanged. ** The second parameter is a pointer to an integer into which ** is written 0 or 1 to indicate whether triggers are disabled or enabled ** following this call. The second parameter may be a NULL pointer, in ** which case the trigger setting is not reported back.
** **
SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER
**
^This option is used to enable or disable the two-argument ** version of the [fts3_tokenizer()] function which is part of the ** [FTS3] full-text search engine extension. ** There should be two additional arguments. ** The first argument is an integer which is 0 to disable fts3_tokenizer() or ** positive to enable fts3_tokenizer() or negative to leave the setting ** unchanged. ** The second parameter is a pointer to an integer into which ** is written 0 or 1 to indicate whether fts3_tokenizer is disabled or enabled ** following this call. The second parameter may be a NULL pointer, in ** which case the new setting is not reported back.
** **
SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION
**
^This option is used to enable or disable the [sqlite3_load_extension()] ** interface independently of the [load_extension()] SQL function. ** The [sqlite3_enable_load_extension()] API enables or disables both the ** C-API [sqlite3_load_extension()] and the SQL function [load_extension()]. ** There should be two additional arguments. ** When the first argument to this interface is 1, then only the C-API is ** enabled and the SQL function remains disabled. If the first argument to ** this interface is 0, then both the C-API and the SQL function are disabled. ** If the first argument is -1, then no changes are made to state of either the ** C-API or the SQL function. ** The second parameter is a pointer to an integer into which ** is written 0 or 1 to indicate whether [sqlite3_load_extension()] interface ** is disabled or enabled following this call. The second parameter may ** be a NULL pointer, in which case the new setting is not reported back. **
** **
SQLITE_DBCONFIG_MAINDBNAME
**
^This option is used to change the name of the "main" database ** schema. ^The sole argument is a pointer to a constant UTF8 string ** which will become the new schema name in place of "main". ^SQLite ** does not make a copy of the new main schema name string, so the application ** must ensure that the argument passed into this DBCONFIG option is unchanged ** until after the database connection closes. **
** **
*/ #define SQLITE_DBCONFIG_MAINDBNAME 1000 /* const char* */ #define SQLITE_DBCONFIG_LOOKASIDE 1001 /* void* int int */ #define SQLITE_DBCONFIG_ENABLE_FKEY 1002 /* int int* */ #define SQLITE_DBCONFIG_ENABLE_TRIGGER 1003 /* int int* */ #define SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER 1004 /* int int* */ #define SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION 1005 /* int int* */ /* ** CAPI3REF: Enable Or Disable Extended Result Codes ** METHOD: sqlite3 ** ** ^The sqlite3_extended_result_codes() routine enables or disables the ** [extended result codes] feature of SQLite. ^The extended result ** codes are disabled by default for historical compatibility. */ SQLITE_API int sqlite3_extended_result_codes(sqlite3*, int onoff); /* ** CAPI3REF: Last Insert Rowid ** METHOD: sqlite3 ** ** ^Each entry in most SQLite tables (except for [WITHOUT ROWID] tables) ** has a unique 64-bit signed ** integer key called the [ROWID | "rowid"]. ^The rowid is always available ** as an undeclared column named ROWID, OID, or _ROWID_ as long as those ** names are not also used by explicitly declared columns. ^If ** the table has a column of type [INTEGER PRIMARY KEY] then that column ** is another alias for the rowid. ** ** ^The sqlite3_last_insert_rowid(D) interface returns the [rowid] of the ** most recent successful [INSERT] into a rowid table or [virtual table] ** on database connection D. ** ^Inserts into [WITHOUT ROWID] tables are not recorded. ** ^If no successful [INSERT]s into rowid tables ** have ever occurred on the database connection D, ** then sqlite3_last_insert_rowid(D) returns zero. ** ** ^(If an [INSERT] occurs within a trigger or within a [virtual table] ** method, then this routine will return the [rowid] of the inserted ** row as long as the trigger or virtual table method is running. ** But once the trigger or virtual table method ends, the value returned ** by this routine reverts to what it was before the trigger or virtual ** table method began.)^ ** ** ^An [INSERT] that fails due to a constraint violation is not a ** successful [INSERT] and does not change the value returned by this ** routine. ^Thus INSERT OR FAIL, INSERT OR IGNORE, INSERT OR ROLLBACK, ** and INSERT OR ABORT make no changes to the return value of this ** routine when their insertion fails. ^(When INSERT OR REPLACE ** encounters a constraint violation, it does not fail. The ** INSERT continues to completion after deleting rows that caused ** the constraint problem so INSERT OR REPLACE will always change ** the return value of this interface.)^ ** ** ^For the purposes of this routine, an [INSERT] is considered to ** be successful even if it is subsequently rolled back. ** ** This function is accessible to SQL statements via the ** [last_insert_rowid() SQL function]. ** ** If a separate thread performs a new [INSERT] on the same ** database connection while the [sqlite3_last_insert_rowid()] ** function is running and thus changes the last insert [rowid], ** then the value returned by [sqlite3_last_insert_rowid()] is ** unpredictable and might not equal either the old or the new ** last insert [rowid]. */ SQLITE_API sqlite3_int64 sqlite3_last_insert_rowid(sqlite3*); /* ** CAPI3REF: Count The Number Of Rows Modified ** METHOD: sqlite3 ** ** ^This function returns the number of rows modified, inserted or ** deleted by the most recently completed INSERT, UPDATE or DELETE ** statement on the database connection specified by the only parameter. ** ^Executing any other type of SQL statement does not modify the value ** returned by this function. ** ** ^Only changes made directly by the INSERT, UPDATE or DELETE statement are ** considered - auxiliary changes caused by [CREATE TRIGGER | triggers], ** [foreign key actions] or [REPLACE] constraint resolution are not counted. ** ** Changes to a view that are intercepted by ** [INSTEAD OF trigger | INSTEAD OF triggers] are not counted. ^The value ** returned by sqlite3_changes() immediately after an INSERT, UPDATE or ** DELETE statement run on a view is always zero. Only changes made to real ** tables are counted. ** ** Things are more complicated if the sqlite3_changes() function is ** executed while a trigger program is running. This may happen if the ** program uses the [changes() SQL function], or if some other callback ** function invokes sqlite3_changes() directly. Essentially: ** **
    **
  • ^(Before entering a trigger program the value returned by ** sqlite3_changes() function is saved. After the trigger program ** has finished, the original value is restored.)^ ** **
  • ^(Within a trigger program each INSERT, UPDATE and DELETE ** statement sets the value returned by sqlite3_changes() ** upon completion as normal. Of course, this value will not include ** any changes performed by sub-triggers, as the sqlite3_changes() ** value will be saved and restored after each sub-trigger has run.)^ **
** ** ^This means that if the changes() SQL function (or similar) is used ** by the first INSERT, UPDATE or DELETE statement within a trigger, it ** returns the value as set when the calling statement began executing. ** ^If it is used by the second or subsequent such statement within a trigger ** program, the value returned reflects the number of rows modified by the ** previous INSERT, UPDATE or DELETE statement within the same trigger. ** ** See also the [sqlite3_total_changes()] interface, the ** [count_changes pragma], and the [changes() SQL function]. ** ** If a separate thread makes changes on the same database connection ** while [sqlite3_changes()] is running then the value returned ** is unpredictable and not meaningful. */ SQLITE_API int sqlite3_changes(sqlite3*); /* ** CAPI3REF: Total Number Of Rows Modified ** METHOD: sqlite3 ** ** ^This function returns the total number of rows inserted, modified or ** deleted by all [INSERT], [UPDATE] or [DELETE] statements completed ** since the database connection was opened, including those executed as ** part of trigger programs. ^Executing any other type of SQL statement ** does not affect the value returned by sqlite3_total_changes(). ** ** ^Changes made as part of [foreign key actions] are included in the ** count, but those made as part of REPLACE constraint resolution are ** not. ^Changes to a view that are intercepted by INSTEAD OF triggers ** are not counted. ** ** See also the [sqlite3_changes()] interface, the ** [count_changes pragma], and the [total_changes() SQL function]. ** ** If a separate thread makes changes on the same database connection ** while [sqlite3_total_changes()] is running then the value ** returned is unpredictable and not meaningful. */ SQLITE_API int sqlite3_total_changes(sqlite3*); /* ** CAPI3REF: Interrupt A Long-Running Query ** METHOD: sqlite3 ** ** ^This function causes any pending database operation to abort and ** return at its earliest opportunity. This routine is typically ** called in response to a user action such as pressing "Cancel" ** or Ctrl-C where the user wants a long query operation to halt ** immediately. ** ** ^It is safe to call this routine from a thread different from the ** thread that is currently running the database operation. But it ** is not safe to call this routine with a [database connection] that ** is closed or might close before sqlite3_interrupt() returns. ** ** ^If an SQL operation is very nearly finished at the time when ** sqlite3_interrupt() is called, then it might not have an opportunity ** to be interrupted and might continue to completion. ** ** ^An SQL operation that is interrupted will return [SQLITE_INTERRUPT]. ** ^If the interrupted SQL operation is an INSERT, UPDATE, or DELETE ** that is inside an explicit transaction, then the entire transaction ** will be rolled back automatically. ** ** ^The sqlite3_interrupt(D) call is in effect until all currently running ** SQL statements on [database connection] D complete. ^Any new SQL statements ** that are started after the sqlite3_interrupt() call and before the ** running statements reaches zero are interrupted as if they had been ** running prior to the sqlite3_interrupt() call. ^New SQL statements ** that are started after the running statement count reaches zero are ** not effected by the sqlite3_interrupt(). ** ^A call to sqlite3_interrupt(D) that occurs when there are no running ** SQL statements is a no-op and has no effect on SQL statements ** that are started after the sqlite3_interrupt() call returns. ** ** If the database connection closes while [sqlite3_interrupt()] ** is running then bad things will likely happen. */ SQLITE_API void sqlite3_interrupt(sqlite3*); /* ** CAPI3REF: Determine If An SQL Statement Is Complete ** ** These routines are useful during command-line input to determine if the ** currently entered text seems to form a complete SQL statement or ** if additional input is needed before sending the text into ** SQLite for parsing. ^These routines return 1 if the input string ** appears to be a complete SQL statement. ^A statement is judged to be ** complete if it ends with a semicolon token and is not a prefix of a ** well-formed CREATE TRIGGER statement. ^Semicolons that are embedded within ** string literals or quoted identifier names or comments are not ** independent tokens (they are part of the token in which they are ** embedded) and thus do not count as a statement terminator. ^Whitespace ** and comments that follow the final semicolon are ignored. ** ** ^These routines return 0 if the statement is incomplete. ^If a ** memory allocation fails, then SQLITE_NOMEM is returned. ** ** ^These routines do not parse the SQL statements thus ** will not detect syntactically incorrect SQL. ** ** ^(If SQLite has not been initialized using [sqlite3_initialize()] prior ** to invoking sqlite3_complete16() then sqlite3_initialize() is invoked ** automatically by sqlite3_complete16(). If that initialization fails, ** then the return value from sqlite3_complete16() will be non-zero ** regardless of whether or not the input SQL is complete.)^ ** ** The input to [sqlite3_complete()] must be a zero-terminated ** UTF-8 string. ** ** The input to [sqlite3_complete16()] must be a zero-terminated ** UTF-16 string in native byte order. */ SQLITE_API int sqlite3_complete(const char *sql); SQLITE_API int sqlite3_complete16(const void *sql); /* ** CAPI3REF: Register A Callback To Handle SQLITE_BUSY Errors ** KEYWORDS: {busy-handler callback} {busy handler} ** METHOD: sqlite3 ** ** ^The sqlite3_busy_handler(D,X,P) routine sets a callback function X ** that might be invoked with argument P whenever ** an attempt is made to access a database table associated with ** [database connection] D when another thread ** or process has the table locked. ** The sqlite3_busy_handler() interface is used to implement ** [sqlite3_busy_timeout()] and [PRAGMA busy_timeout]. ** ** ^If the busy callback is NULL, then [SQLITE_BUSY] ** is returned immediately upon encountering the lock. ^If the busy callback ** is not NULL, then the callback might be invoked with two arguments. ** ** ^The first argument to the busy handler is a copy of the void* pointer which ** is the third argument to sqlite3_busy_handler(). ^The second argument to ** the busy handler callback is the number of times that the busy handler has ** been invoked previously for the same locking event. ^If the ** busy callback returns 0, then no additional attempts are made to ** access the database and [SQLITE_BUSY] is returned ** to the application. ** ^If the callback returns non-zero, then another attempt ** is made to access the database and the cycle repeats. ** ** The presence of a busy handler does not guarantee that it will be invoked ** when there is lock contention. ^If SQLite determines that invoking the busy ** handler could result in a deadlock, it will go ahead and return [SQLITE_BUSY] ** to the application instead of invoking the ** busy handler. ** Consider a scenario where one process is holding a read lock that ** it is trying to promote to a reserved lock and ** a second process is holding a reserved lock that it is trying ** to promote to an exclusive lock. The first process cannot proceed ** because it is blocked by the second and the second process cannot ** proceed because it is blocked by the first. If both processes ** invoke the busy handlers, neither will make any progress. Therefore, ** SQLite returns [SQLITE_BUSY] for the first process, hoping that this ** will induce the first process to release its read lock and allow ** the second process to proceed. ** ** ^The default busy callback is NULL. ** ** ^(There can only be a single busy handler defined for each ** [database connection]. Setting a new busy handler clears any ** previously set handler.)^ ^Note that calling [sqlite3_busy_timeout()] ** or evaluating [PRAGMA busy_timeout=N] will change the ** busy handler and thus clear any previously set busy handler. ** ** The busy callback should not take any actions which modify the ** database connection that invoked the busy handler. In other words, ** the busy handler is not reentrant. Any such actions ** result in undefined behavior. ** ** A busy handler must not close the database connection ** or [prepared statement] that invoked the busy handler. */ SQLITE_API int sqlite3_busy_handler(sqlite3*,int(*)(void*,int),void*); /* ** CAPI3REF: Set A Busy Timeout ** METHOD: sqlite3 ** ** ^This routine sets a [sqlite3_busy_handler | busy handler] that sleeps ** for a specified amount of time when a table is locked. ^The handler ** will sleep multiple times until at least "ms" milliseconds of sleeping ** have accumulated. ^After at least "ms" milliseconds of sleeping, ** the handler returns 0 which causes [sqlite3_step()] to return ** [SQLITE_BUSY]. ** ** ^Calling this routine with an argument less than or equal to zero ** turns off all busy handlers. ** ** ^(There can only be a single busy handler for a particular ** [database connection] at any given moment. If another busy handler ** was defined (using [sqlite3_busy_handler()]) prior to calling ** this routine, that other busy handler is cleared.)^ ** ** See also: [PRAGMA busy_timeout] */ SQLITE_API int sqlite3_busy_timeout(sqlite3*, int ms); /* ** CAPI3REF: Convenience Routines For Running Queries ** METHOD: sqlite3 ** ** This is a legacy interface that is preserved for backwards compatibility. ** Use of this interface is not recommended. ** ** Definition: A result table is memory data structure created by the ** [sqlite3_get_table()] interface. A result table records the ** complete query results from one or more queries. ** ** The table conceptually has a number of rows and columns. But ** these numbers are not part of the result table itself. These ** numbers are obtained separately. Let N be the number of rows ** and M be the number of columns. ** ** A result table is an array of pointers to zero-terminated UTF-8 strings. ** There are (N+1)*M elements in the array. The first M pointers point ** to zero-terminated strings that contain the names of the columns. ** The remaining entries all point to query results. NULL values result ** in NULL pointers. All other values are in their UTF-8 zero-terminated ** string representation as returned by [sqlite3_column_text()]. ** ** A result table might consist of one or more memory allocations. ** It is not safe to pass a result table directly to [sqlite3_free()]. ** A result table should be deallocated using [sqlite3_free_table()]. ** ** ^(As an example of the result table format, suppose a query result ** is as follows: ** **
**        Name        | Age
**        -----------------------
**        Alice       | 43
**        Bob         | 28
**        Cindy       | 21
** 
** ** There are two column (M==2) and three rows (N==3). Thus the ** result table has 8 entries. Suppose the result table is stored ** in an array names azResult. Then azResult holds this content: ** **
**        azResult[0] = "Name";
**        azResult[1] = "Age";
**        azResult[2] = "Alice";
**        azResult[3] = "43";
**        azResult[4] = "Bob";
**        azResult[5] = "28";
**        azResult[6] = "Cindy";
**        azResult[7] = "21";
** 
)^ ** ** ^The sqlite3_get_table() function evaluates one or more ** semicolon-separated SQL statements in the zero-terminated UTF-8 ** string of its 2nd parameter and returns a result table to the ** pointer given in its 3rd parameter. ** ** After the application has finished with the result from sqlite3_get_table(), ** it must pass the result table pointer to sqlite3_free_table() in order to ** release the memory that was malloced. Because of the way the ** [sqlite3_malloc()] happens within sqlite3_get_table(), the calling ** function must not try to call [sqlite3_free()] directly. Only ** [sqlite3_free_table()] is able to release the memory properly and safely. ** ** The sqlite3_get_table() interface is implemented as a wrapper around ** [sqlite3_exec()]. The sqlite3_get_table() routine does not have access ** to any internal data structures of SQLite. It uses only the public ** interface defined here. As a consequence, errors that occur in the ** wrapper layer outside of the internal [sqlite3_exec()] call are not ** reflected in subsequent calls to [sqlite3_errcode()] or ** [sqlite3_errmsg()]. */ SQLITE_API int sqlite3_get_table( sqlite3 *db, /* An open database */ const char *zSql, /* SQL to be evaluated */ char ***pazResult, /* Results of the query */ int *pnRow, /* Number of result rows written here */ int *pnColumn, /* Number of result columns written here */ char **pzErrmsg /* Error msg written here */ ); SQLITE_API void sqlite3_free_table(char **result); /* ** CAPI3REF: Formatted String Printing Functions ** ** These routines are work-alikes of the "printf()" family of functions ** from the standard C library. ** These routines understand most of the common K&R formatting options, ** plus some additional non-standard formats, detailed below. ** Note that some of the more obscure formatting options from recent ** C-library standards are omitted from this implementation. ** ** ^The sqlite3_mprintf() and sqlite3_vmprintf() routines write their ** results into memory obtained from [sqlite3_malloc()]. ** The strings returned by these two routines should be ** released by [sqlite3_free()]. ^Both routines return a ** NULL pointer if [sqlite3_malloc()] is unable to allocate enough ** memory to hold the resulting string. ** ** ^(The sqlite3_snprintf() routine is similar to "snprintf()" from ** the standard C library. The result is written into the ** buffer supplied as the second parameter whose size is given by ** the first parameter. Note that the order of the ** first two parameters is reversed from snprintf().)^ This is an ** historical accident that cannot be fixed without breaking ** backwards compatibility. ^(Note also that sqlite3_snprintf() ** returns a pointer to its buffer instead of the number of ** characters actually written into the buffer.)^ We admit that ** the number of characters written would be a more useful return ** value but we cannot change the implementation of sqlite3_snprintf() ** now without breaking compatibility. ** ** ^As long as the buffer size is greater than zero, sqlite3_snprintf() ** guarantees that the buffer is always zero-terminated. ^The first ** parameter "n" is the total size of the buffer, including space for ** the zero terminator. So the longest string that can be completely ** written will be n-1 characters. ** ** ^The sqlite3_vsnprintf() routine is a varargs version of sqlite3_snprintf(). ** ** These routines all implement some additional formatting ** options that are useful for constructing SQL statements. ** All of the usual printf() formatting options apply. In addition, there ** is are "%q", "%Q", "%w" and "%z" options. ** ** ^(The %q option works like %s in that it substitutes a nul-terminated ** string from the argument list. But %q also doubles every '\'' character. ** %q is designed for use inside a string literal.)^ By doubling each '\'' ** character it escapes that character and allows it to be inserted into ** the string. ** ** For example, assume the string variable zText contains text as follows: ** **
**  char *zText = "It's a happy day!";
** 
** ** One can use this text in an SQL statement as follows: ** **
**  char *zSQL = sqlite3_mprintf("INSERT INTO table VALUES('%q')", zText);
**  sqlite3_exec(db, zSQL, 0, 0, 0);
**  sqlite3_free(zSQL);
** 
** ** Because the %q format string is used, the '\'' character in zText ** is escaped and the SQL generated is as follows: ** **
**  INSERT INTO table1 VALUES('It''s a happy day!')
** 
** ** This is correct. Had we used %s instead of %q, the generated SQL ** would have looked like this: ** **
**  INSERT INTO table1 VALUES('It's a happy day!');
** 
** ** This second example is an SQL syntax error. As a general rule you should ** always use %q instead of %s when inserting text into a string literal. ** ** ^(The %Q option works like %q except it also adds single quotes around ** the outside of the total string. Additionally, if the parameter in the ** argument list is a NULL pointer, %Q substitutes the text "NULL" (without ** single quotes).)^ So, for example, one could say: ** **
**  char *zSQL = sqlite3_mprintf("INSERT INTO table VALUES(%Q)", zText);
**  sqlite3_exec(db, zSQL, 0, 0, 0);
**  sqlite3_free(zSQL);
** 
** ** The code above will render a correct SQL statement in the zSQL ** variable even if the zText variable is a NULL pointer. ** ** ^(The "%w" formatting option is like "%q" except that it expects to ** be contained within double-quotes instead of single quotes, and it ** escapes the double-quote character instead of the single-quote ** character.)^ The "%w" formatting option is intended for safely inserting ** table and column names into a constructed SQL statement. ** ** ^(The "%z" formatting option works like "%s" but with the ** addition that after the string has been read and copied into ** the result, [sqlite3_free()] is called on the input string.)^ */ SQLITE_API char *sqlite3_mprintf(const char*,...); SQLITE_API char *sqlite3_vmprintf(const char*, va_list); SQLITE_API char *sqlite3_snprintf(int,char*,const char*, ...); SQLITE_API char *sqlite3_vsnprintf(int,char*,const char*, va_list); /* ** CAPI3REF: Memory Allocation Subsystem ** ** The SQLite core uses these three routines for all of its own ** internal memory allocation needs. "Core" in the previous sentence ** does not include operating-system specific VFS implementation. The ** Windows VFS uses native malloc() and free() for some operations. ** ** ^The sqlite3_malloc() routine returns a pointer to a block ** of memory at least N bytes in length, where N is the parameter. ** ^If sqlite3_malloc() is unable to obtain sufficient free ** memory, it returns a NULL pointer. ^If the parameter N to ** sqlite3_malloc() is zero or negative then sqlite3_malloc() returns ** a NULL pointer. ** ** ^The sqlite3_malloc64(N) routine works just like ** sqlite3_malloc(N) except that N is an unsigned 64-bit integer instead ** of a signed 32-bit integer. ** ** ^Calling sqlite3_free() with a pointer previously returned ** by sqlite3_malloc() or sqlite3_realloc() releases that memory so ** that it might be reused. ^The sqlite3_free() routine is ** a no-op if is called with a NULL pointer. Passing a NULL pointer ** to sqlite3_free() is harmless. After being freed, memory ** should neither be read nor written. Even reading previously freed ** memory might result in a segmentation fault or other severe error. ** Memory corruption, a segmentation fault, or other severe error ** might result if sqlite3_free() is called with a non-NULL pointer that ** was not obtained from sqlite3_malloc() or sqlite3_realloc(). ** ** ^The sqlite3_realloc(X,N) interface attempts to resize a ** prior memory allocation X to be at least N bytes. ** ^If the X parameter to sqlite3_realloc(X,N) ** is a NULL pointer then its behavior is identical to calling ** sqlite3_malloc(N). ** ^If the N parameter to sqlite3_realloc(X,N) is zero or ** negative then the behavior is exactly the same as calling ** sqlite3_free(X). ** ^sqlite3_realloc(X,N) returns a pointer to a memory allocation ** of at least N bytes in size or NULL if insufficient memory is available. ** ^If M is the size of the prior allocation, then min(N,M) bytes ** of the prior allocation are copied into the beginning of buffer returned ** by sqlite3_realloc(X,N) and the prior allocation is freed. ** ^If sqlite3_realloc(X,N) returns NULL and N is positive, then the ** prior allocation is not freed. ** ** ^The sqlite3_realloc64(X,N) interfaces works the same as ** sqlite3_realloc(X,N) except that N is a 64-bit unsigned integer instead ** of a 32-bit signed integer. ** ** ^If X is a memory allocation previously obtained from sqlite3_malloc(), ** sqlite3_malloc64(), sqlite3_realloc(), or sqlite3_realloc64(), then ** sqlite3_msize(X) returns the size of that memory allocation in bytes. ** ^The value returned by sqlite3_msize(X) might be larger than the number ** of bytes requested when X was allocated. ^If X is a NULL pointer then ** sqlite3_msize(X) returns zero. If X points to something that is not ** the beginning of memory allocation, or if it points to a formerly ** valid memory allocation that has now been freed, then the behavior ** of sqlite3_msize(X) is undefined and possibly harmful. ** ** ^The memory returned by sqlite3_malloc(), sqlite3_realloc(), ** sqlite3_malloc64(), and sqlite3_realloc64() ** is always aligned to at least an 8 byte boundary, or to a ** 4 byte boundary if the [SQLITE_4_BYTE_ALIGNED_MALLOC] compile-time ** option is used. ** ** In SQLite version 3.5.0 and 3.5.1, it was possible to define ** the SQLITE_OMIT_MEMORY_ALLOCATION which would cause the built-in ** implementation of these routines to be omitted. That capability ** is no longer provided. Only built-in memory allocators can be used. ** ** Prior to SQLite version 3.7.10, the Windows OS interface layer called ** the system malloc() and free() directly when converting ** filenames between the UTF-8 encoding used by SQLite ** and whatever filename encoding is used by the particular Windows ** installation. Memory allocation errors were detected, but ** they were reported back as [SQLITE_CANTOPEN] or ** [SQLITE_IOERR] rather than [SQLITE_NOMEM]. ** ** The pointer arguments to [sqlite3_free()] and [sqlite3_realloc()] ** must be either NULL or else pointers obtained from a prior ** invocation of [sqlite3_malloc()] or [sqlite3_realloc()] that have ** not yet been released. ** ** The application must not read or write any part of ** a block of memory after it has been released using ** [sqlite3_free()] or [sqlite3_realloc()]. */ SQLITE_API void *sqlite3_malloc(int); SQLITE_API void *sqlite3_malloc64(sqlite3_uint64); SQLITE_API void *sqlite3_realloc(void*, int); SQLITE_API void *sqlite3_realloc64(void*, sqlite3_uint64); SQLITE_API void sqlite3_free(void*); SQLITE_API sqlite3_uint64 sqlite3_msize(void*); /* ** CAPI3REF: Memory Allocator Statistics ** ** SQLite provides these two interfaces for reporting on the status ** of the [sqlite3_malloc()], [sqlite3_free()], and [sqlite3_realloc()] ** routines, which form the built-in memory allocation subsystem. ** ** ^The [sqlite3_memory_used()] routine returns the number of bytes ** of memory currently outstanding (malloced but not freed). ** ^The [sqlite3_memory_highwater()] routine returns the maximum ** value of [sqlite3_memory_used()] since the high-water mark ** was last reset. ^The values returned by [sqlite3_memory_used()] and ** [sqlite3_memory_highwater()] include any overhead ** added by SQLite in its implementation of [sqlite3_malloc()], ** but not overhead added by the any underlying system library ** routines that [sqlite3_malloc()] may call. ** ** ^The memory high-water mark is reset to the current value of ** [sqlite3_memory_used()] if and only if the parameter to ** [sqlite3_memory_highwater()] is true. ^The value returned ** by [sqlite3_memory_highwater(1)] is the high-water mark ** prior to the reset. */ SQLITE_API sqlite3_int64 sqlite3_memory_used(void); SQLITE_API sqlite3_int64 sqlite3_memory_highwater(int resetFlag); /* ** CAPI3REF: Pseudo-Random Number Generator ** ** SQLite contains a high-quality pseudo-random number generator (PRNG) used to ** select random [ROWID | ROWIDs] when inserting new records into a table that ** already uses the largest possible [ROWID]. The PRNG is also used for ** the build-in random() and randomblob() SQL functions. This interface allows ** applications to access the same PRNG for other purposes. ** ** ^A call to this routine stores N bytes of randomness into buffer P. ** ^The P parameter can be a NULL pointer. ** ** ^If this routine has not been previously called or if the previous ** call had N less than one or a NULL pointer for P, then the PRNG is ** seeded using randomness obtained from the xRandomness method of ** the default [sqlite3_vfs] object. ** ^If the previous call to this routine had an N of 1 or more and a ** non-NULL P then the pseudo-randomness is generated ** internally and without recourse to the [sqlite3_vfs] xRandomness ** method. */ SQLITE_API void sqlite3_randomness(int N, void *P); /* ** CAPI3REF: Compile-Time Authorization Callbacks ** METHOD: sqlite3 ** ** ^This routine registers an authorizer callback with a particular ** [database connection], supplied in the first argument. ** ^The authorizer callback is invoked as SQL statements are being compiled ** by [sqlite3_prepare()] or its variants [sqlite3_prepare_v2()], ** [sqlite3_prepare16()] and [sqlite3_prepare16_v2()]. ^At various ** points during the compilation process, as logic is being created ** to perform various actions, the authorizer callback is invoked to ** see if those actions are allowed. ^The authorizer callback should ** return [SQLITE_OK] to allow the action, [SQLITE_IGNORE] to disallow the ** specific action but allow the SQL statement to continue to be ** compiled, or [SQLITE_DENY] to cause the entire SQL statement to be ** rejected with an error. ^If the authorizer callback returns ** any value other than [SQLITE_IGNORE], [SQLITE_OK], or [SQLITE_DENY] ** then the [sqlite3_prepare_v2()] or equivalent call that triggered ** the authorizer will fail with an error message. ** ** When the callback returns [SQLITE_OK], that means the operation ** requested is ok. ^When the callback returns [SQLITE_DENY], the ** [sqlite3_prepare_v2()] or equivalent call that triggered the ** authorizer will fail with an error message explaining that ** access is denied. ** ** ^The first parameter to the authorizer callback is a copy of the third ** parameter to the sqlite3_set_authorizer() interface. ^The second parameter ** to the callback is an integer [SQLITE_COPY | action code] that specifies ** the particular action to be authorized. ^The third through sixth parameters ** to the callback are zero-terminated strings that contain additional ** details about the action to be authorized. ** ** ^If the action code is [SQLITE_READ] ** and the callback returns [SQLITE_IGNORE] then the ** [prepared statement] statement is constructed to substitute ** a NULL value in place of the table column that would have ** been read if [SQLITE_OK] had been returned. The [SQLITE_IGNORE] ** return can be used to deny an untrusted user access to individual ** columns of a table. ** ^If the action code is [SQLITE_DELETE] and the callback returns ** [SQLITE_IGNORE] then the [DELETE] operation proceeds but the ** [truncate optimization] is disabled and all rows are deleted individually. ** ** An authorizer is used when [sqlite3_prepare | preparing] ** SQL statements from an untrusted source, to ensure that the SQL statements ** do not try to access data they are not allowed to see, or that they do not ** try to execute malicious statements that damage the database. For ** example, an application may allow a user to enter arbitrary ** SQL queries for evaluation by a database. But the application does ** not want the user to be able to make arbitrary changes to the ** database. An authorizer could then be put in place while the ** user-entered SQL is being [sqlite3_prepare | prepared] that ** disallows everything except [SELECT] statements. ** ** Applications that need to process SQL from untrusted sources ** might also consider lowering resource limits using [sqlite3_limit()] ** and limiting database size using the [max_page_count] [PRAGMA] ** in addition to using an authorizer. ** ** ^(Only a single authorizer can be in place on a database connection ** at a time. Each call to sqlite3_set_authorizer overrides the ** previous call.)^ ^Disable the authorizer by installing a NULL callback. ** The authorizer is disabled by default. ** ** The authorizer callback must not do anything that will modify ** the database connection that invoked the authorizer callback. ** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their ** database connections for the meaning of "modify" in this paragraph. ** ** ^When [sqlite3_prepare_v2()] is used to prepare a statement, the ** statement might be re-prepared during [sqlite3_step()] due to a ** schema change. Hence, the application should ensure that the ** correct authorizer callback remains in place during the [sqlite3_step()]. ** ** ^Note that the authorizer callback is invoked only during ** [sqlite3_prepare()] or its variants. Authorization is not ** performed during statement evaluation in [sqlite3_step()], unless ** as stated in the previous paragraph, sqlite3_step() invokes ** sqlite3_prepare_v2() to reprepare a statement after a schema change. */ SQLITE_API int sqlite3_set_authorizer( sqlite3*, int (*xAuth)(void*,int,const char*,const char*,const char*,const char*), void *pUserData ); /* ** CAPI3REF: Authorizer Return Codes ** ** The [sqlite3_set_authorizer | authorizer callback function] must ** return either [SQLITE_OK] or one of these two constants in order ** to signal SQLite whether or not the action is permitted. See the ** [sqlite3_set_authorizer | authorizer documentation] for additional ** information. ** ** Note that SQLITE_IGNORE is also used as a [conflict resolution mode] ** returned from the [sqlite3_vtab_on_conflict()] interface. */ #define SQLITE_DENY 1 /* Abort the SQL statement with an error */ #define SQLITE_IGNORE 2 /* Don't allow access, but don't generate an error */ /* ** CAPI3REF: Authorizer Action Codes ** ** The [sqlite3_set_authorizer()] interface registers a callback function ** that is invoked to authorize certain SQL statement actions. The ** second parameter to the callback is an integer code that specifies ** what action is being authorized. These are the integer action codes that ** the authorizer callback may be passed. ** ** These action code values signify what kind of operation is to be ** authorized. The 3rd and 4th parameters to the authorization ** callback function will be parameters or NULL depending on which of these ** codes is used as the second parameter. ^(The 5th parameter to the ** authorizer callback is the name of the database ("main", "temp", ** etc.) if applicable.)^ ^The 6th parameter to the authorizer callback ** is the name of the inner-most trigger or view that is responsible for ** the access attempt or NULL if this access attempt is directly from ** top-level SQL code. */ /******************************************* 3rd ************ 4th ***********/ #define SQLITE_CREATE_INDEX 1 /* Index Name Table Name */ #define SQLITE_CREATE_TABLE 2 /* Table Name NULL */ #define SQLITE_CREATE_TEMP_INDEX 3 /* Index Name Table Name */ #define SQLITE_CREATE_TEMP_TABLE 4 /* Table Name NULL */ #define SQLITE_CREATE_TEMP_TRIGGER 5 /* Trigger Name Table Name */ #define SQLITE_CREATE_TEMP_VIEW 6 /* View Name NULL */ #define SQLITE_CREATE_TRIGGER 7 /* Trigger Name Table Name */ #define SQLITE_CREATE_VIEW 8 /* View Name NULL */ #define SQLITE_DELETE 9 /* Table Name NULL */ #define SQLITE_DROP_INDEX 10 /* Index Name Table Name */ #define SQLITE_DROP_TABLE 11 /* Table Name NULL */ #define SQLITE_DROP_TEMP_INDEX 12 /* Index Name Table Name */ #define SQLITE_DROP_TEMP_TABLE 13 /* Table Name NULL */ #define SQLITE_DROP_TEMP_TRIGGER 14 /* Trigger Name Table Name */ #define SQLITE_DROP_TEMP_VIEW 15 /* View Name NULL */ #define SQLITE_DROP_TRIGGER 16 /* Trigger Name Table Name */ #define SQLITE_DROP_VIEW 17 /* View Name NULL */ #define SQLITE_INSERT 18 /* Table Name NULL */ #define SQLITE_PRAGMA 19 /* Pragma Name 1st arg or NULL */ #define SQLITE_READ 20 /* Table Name Column Name */ #define SQLITE_SELECT 21 /* NULL NULL */ #define SQLITE_TRANSACTION 22 /* Operation NULL */ #define SQLITE_UPDATE 23 /* Table Name Column Name */ #define SQLITE_ATTACH 24 /* Filename NULL */ #define SQLITE_DETACH 25 /* Database Name NULL */ #define SQLITE_ALTER_TABLE 26 /* Database Name Table Name */ #define SQLITE_REINDEX 27 /* Index Name NULL */ #define SQLITE_ANALYZE 28 /* Table Name NULL */ #define SQLITE_CREATE_VTABLE 29 /* Table Name Module Name */ #define SQLITE_DROP_VTABLE 30 /* Table Name Module Name */ #define SQLITE_FUNCTION 31 /* NULL Function Name */ #define SQLITE_SAVEPOINT 32 /* Operation Savepoint Name */ #define SQLITE_COPY 0 /* No longer used */ #define SQLITE_RECURSIVE 33 /* NULL NULL */ /* ** CAPI3REF: Tracing And Profiling Functions ** METHOD: sqlite3 ** ** These routines are deprecated. Use the [sqlite3_trace_v2()] interface ** instead of the routines described here. ** ** These routines register callback functions that can be used for ** tracing and profiling the execution of SQL statements. ** ** ^The callback function registered by sqlite3_trace() is invoked at ** various times when an SQL statement is being run by [sqlite3_step()]. ** ^The sqlite3_trace() callback is invoked with a UTF-8 rendering of the ** SQL statement text as the statement first begins executing. ** ^(Additional sqlite3_trace() callbacks might occur ** as each triggered subprogram is entered. The callbacks for triggers ** contain a UTF-8 SQL comment that identifies the trigger.)^ ** ** The [SQLITE_TRACE_SIZE_LIMIT] compile-time option can be used to limit ** the length of [bound parameter] expansion in the output of sqlite3_trace(). ** ** ^The callback function registered by sqlite3_profile() is invoked ** as each SQL statement finishes. ^The profile callback contains ** the original statement text and an estimate of wall-clock time ** of how long that statement took to run. ^The profile callback ** time is in units of nanoseconds, however the current implementation ** is only capable of millisecond resolution so the six least significant ** digits in the time are meaningless. Future versions of SQLite ** might provide greater resolution on the profiler callback. The ** sqlite3_profile() function is considered experimental and is ** subject to change in future versions of SQLite. */ SQLITE_API SQLITE_DEPRECATED void *sqlite3_trace(sqlite3*, void(*xTrace)(void*,const char*), void*); SQLITE_API SQLITE_DEPRECATED void *sqlite3_profile(sqlite3*, void(*xProfile)(void*,const char*,sqlite3_uint64), void*); /* ** CAPI3REF: SQL Trace Event Codes ** KEYWORDS: SQLITE_TRACE ** ** These constants identify classes of events that can be monitored ** using the [sqlite3_trace_v2()] tracing logic. The third argument ** to [sqlite3_trace_v2()] is an OR-ed combination of one or more of ** the following constants. ^The first argument to the trace callback ** is one of the following constants. ** ** New tracing constants may be added in future releases. ** ** ^A trace callback has four arguments: xCallback(T,C,P,X). ** ^The T argument is one of the integer type codes above. ** ^The C argument is a copy of the context pointer passed in as the ** fourth argument to [sqlite3_trace_v2()]. ** The P and X arguments are pointers whose meanings depend on T. ** **
** [[SQLITE_TRACE_STMT]]
SQLITE_TRACE_STMT
**
^An SQLITE_TRACE_STMT callback is invoked when a prepared statement ** first begins running and possibly at other times during the ** execution of the prepared statement, such as at the start of each ** trigger subprogram. ^The P argument is a pointer to the ** [prepared statement]. ^The X argument is a pointer to a string which ** is the unexpanded SQL text of the prepared statement or an SQL comment ** that indicates the invocation of a trigger. ^The callback can compute ** the same text that would have been returned by the legacy [sqlite3_trace()] ** interface by using the X argument when X begins with "--" and invoking ** [sqlite3_expanded_sql(P)] otherwise. ** ** [[SQLITE_TRACE_PROFILE]]
SQLITE_TRACE_PROFILE
**
^An SQLITE_TRACE_PROFILE callback provides approximately the same ** information as is provided by the [sqlite3_profile()] callback. ** ^The P argument is a pointer to the [prepared statement] and the ** X argument points to a 64-bit integer which is the estimated of ** the number of nanosecond that the prepared statement took to run. ** ^The SQLITE_TRACE_PROFILE callback is invoked when the statement finishes. ** ** [[SQLITE_TRACE_ROW]]
SQLITE_TRACE_ROW
**
^An SQLITE_TRACE_ROW callback is invoked whenever a prepared ** statement generates a single row of result. ** ^The P argument is a pointer to the [prepared statement] and the ** X argument is unused. ** ** [[SQLITE_TRACE_CLOSE]]
SQLITE_TRACE_CLOSE
**
^An SQLITE_TRACE_CLOSE callback is invoked when a database ** connection closes. ** ^The P argument is a pointer to the [database connection] object ** and the X argument is unused. **
*/ #define SQLITE_TRACE_STMT 0x01 #define SQLITE_TRACE_PROFILE 0x02 #define SQLITE_TRACE_ROW 0x04 #define SQLITE_TRACE_CLOSE 0x08 /* ** CAPI3REF: SQL Trace Hook ** METHOD: sqlite3 ** ** ^The sqlite3_trace_v2(D,M,X,P) interface registers a trace callback ** function X against [database connection] D, using property mask M ** and context pointer P. ^If the X callback is ** NULL or if the M mask is zero, then tracing is disabled. The ** M argument should be the bitwise OR-ed combination of ** zero or more [SQLITE_TRACE] constants. ** ** ^Each call to either sqlite3_trace() or sqlite3_trace_v2() overrides ** (cancels) any prior calls to sqlite3_trace() or sqlite3_trace_v2(). ** ** ^The X callback is invoked whenever any of the events identified by ** mask M occur. ^The integer return value from the callback is currently ** ignored, though this may change in future releases. Callback ** implementations should return zero to ensure future compatibility. ** ** ^A trace callback is invoked with four arguments: callback(T,C,P,X). ** ^The T argument is one of the [SQLITE_TRACE] ** constants to indicate why the callback was invoked. ** ^The C argument is a copy of the context pointer. ** The P and X arguments are pointers whose meanings depend on T. ** ** The sqlite3_trace_v2() interface is intended to replace the legacy ** interfaces [sqlite3_trace()] and [sqlite3_profile()], both of which ** are deprecated. */ SQLITE_API int sqlite3_trace_v2( sqlite3*, unsigned uMask, int(*xCallback)(unsigned,void*,void*,void*), void *pCtx ); /* ** CAPI3REF: Query Progress Callbacks ** METHOD: sqlite3 ** ** ^The sqlite3_progress_handler(D,N,X,P) interface causes the callback ** function X to be invoked periodically during long running calls to ** [sqlite3_exec()], [sqlite3_step()] and [sqlite3_get_table()] for ** database connection D. An example use for this ** interface is to keep a GUI updated during a large query. ** ** ^The parameter P is passed through as the only parameter to the ** callback function X. ^The parameter N is the approximate number of ** [virtual machine instructions] that are evaluated between successive ** invocations of the callback X. ^If N is less than one then the progress ** handler is disabled. ** ** ^Only a single progress handler may be defined at one time per ** [database connection]; setting a new progress handler cancels the ** old one. ^Setting parameter X to NULL disables the progress handler. ** ^The progress handler is also disabled by setting N to a value less ** than 1. ** ** ^If the progress callback returns non-zero, the operation is ** interrupted. This feature can be used to implement a ** "Cancel" button on a GUI progress dialog box. ** ** The progress handler callback must not do anything that will modify ** the database connection that invoked the progress handler. ** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their ** database connections for the meaning of "modify" in this paragraph. ** */ SQLITE_API void sqlite3_progress_handler(sqlite3*, int, int(*)(void*), void*); /* ** CAPI3REF: Opening A New Database Connection ** CONSTRUCTOR: sqlite3 ** ** ^These routines open an SQLite database file as specified by the ** filename argument. ^The filename argument is interpreted as UTF-8 for ** sqlite3_open() and sqlite3_open_v2() and as UTF-16 in the native byte ** order for sqlite3_open16(). ^(A [database connection] handle is usually ** returned in *ppDb, even if an error occurs. The only exception is that ** if SQLite is unable to allocate memory to hold the [sqlite3] object, ** a NULL will be written into *ppDb instead of a pointer to the [sqlite3] ** object.)^ ^(If the database is opened (and/or created) successfully, then ** [SQLITE_OK] is returned. Otherwise an [error code] is returned.)^ ^The ** [sqlite3_errmsg()] or [sqlite3_errmsg16()] routines can be used to obtain ** an English language description of the error following a failure of any ** of the sqlite3_open() routines. ** ** ^The default encoding will be UTF-8 for databases created using ** sqlite3_open() or sqlite3_open_v2(). ^The default encoding for databases ** created using sqlite3_open16() will be UTF-16 in the native byte order. ** ** Whether or not an error occurs when it is opened, resources ** associated with the [database connection] handle should be released by ** passing it to [sqlite3_close()] when it is no longer required. ** ** The sqlite3_open_v2() interface works like sqlite3_open() ** except that it accepts two additional parameters for additional control ** over the new database connection. ^(The flags parameter to ** sqlite3_open_v2() can take one of ** the following three values, optionally combined with the ** [SQLITE_OPEN_NOMUTEX], [SQLITE_OPEN_FULLMUTEX], [SQLITE_OPEN_SHAREDCACHE], ** [SQLITE_OPEN_PRIVATECACHE], and/or [SQLITE_OPEN_URI] flags:)^ ** **
** ^(
[SQLITE_OPEN_READONLY]
**
The database is opened in read-only mode. If the database does not ** already exist, an error is returned.
)^ ** ** ^(
[SQLITE_OPEN_READWRITE]
**
The database is opened for reading and writing if possible, or reading ** only if the file is write protected by the operating system. In either ** case the database must already exist, otherwise an error is returned.
)^ ** ** ^(
[SQLITE_OPEN_READWRITE] | [SQLITE_OPEN_CREATE]
**
The database is opened for reading and writing, and is created if ** it does not already exist. This is the behavior that is always used for ** sqlite3_open() and sqlite3_open16().
)^ **
** ** If the 3rd parameter to sqlite3_open_v2() is not one of the ** combinations shown above optionally combined with other ** [SQLITE_OPEN_READONLY | SQLITE_OPEN_* bits] ** then the behavior is undefined. ** ** ^If the [SQLITE_OPEN_NOMUTEX] flag is set, then the database connection ** opens in the multi-thread [threading mode] as long as the single-thread ** mode has not been set at compile-time or start-time. ^If the ** [SQLITE_OPEN_FULLMUTEX] flag is set then the database connection opens ** in the serialized [threading mode] unless single-thread was ** previously selected at compile-time or start-time. ** ^The [SQLITE_OPEN_SHAREDCACHE] flag causes the database connection to be ** eligible to use [shared cache mode], regardless of whether or not shared ** cache is enabled using [sqlite3_enable_shared_cache()]. ^The ** [SQLITE_OPEN_PRIVATECACHE] flag causes the database connection to not ** participate in [shared cache mode] even if it is enabled. ** ** ^The fourth parameter to sqlite3_open_v2() is the name of the ** [sqlite3_vfs] object that defines the operating system interface that ** the new database connection should use. ^If the fourth parameter is ** a NULL pointer then the default [sqlite3_vfs] object is used. ** ** ^If the filename is ":memory:", then a private, temporary in-memory database ** is created for the connection. ^This in-memory database will vanish when ** the database connection is closed. Future versions of SQLite might ** make use of additional special filenames that begin with the ":" character. ** It is recommended that when a database filename actually does begin with ** a ":" character you should prefix the filename with a pathname such as ** "./" to avoid ambiguity. ** ** ^If the filename is an empty string, then a private, temporary ** on-disk database will be created. ^This private database will be ** automatically deleted as soon as the database connection is closed. ** ** [[URI filenames in sqlite3_open()]]

URI Filenames

** ** ^If [URI filename] interpretation is enabled, and the filename argument ** begins with "file:", then the filename is interpreted as a URI. ^URI ** filename interpretation is enabled if the [SQLITE_OPEN_URI] flag is ** set in the fourth argument to sqlite3_open_v2(), or if it has ** been enabled globally using the [SQLITE_CONFIG_URI] option with the ** [sqlite3_config()] method or by the [SQLITE_USE_URI] compile-time option. ** As of SQLite version 3.7.7, URI filename interpretation is turned off ** by default, but future releases of SQLite might enable URI filename ** interpretation by default. See "[URI filenames]" for additional ** information. ** ** URI filenames are parsed according to RFC 3986. ^If the URI contains an ** authority, then it must be either an empty string or the string ** "localhost". ^If the authority is not an empty string or "localhost", an ** error is returned to the caller. ^The fragment component of a URI, if ** present, is ignored. ** ** ^SQLite uses the path component of the URI as the name of the disk file ** which contains the database. ^If the path begins with a '/' character, ** then it is interpreted as an absolute path. ^If the path does not begin ** with a '/' (meaning that the authority section is omitted from the URI) ** then the path is interpreted as a relative path. ** ^(On windows, the first component of an absolute path ** is a drive specification (e.g. "C:").)^ ** ** [[core URI query parameters]] ** The query component of a URI may contain parameters that are interpreted ** either by SQLite itself, or by a [VFS | custom VFS implementation]. ** SQLite and its built-in [VFSes] interpret the ** following query parameters: ** **
    **
  • vfs: ^The "vfs" parameter may be used to specify the name of ** a VFS object that provides the operating system interface that should ** be used to access the database file on disk. ^If this option is set to ** an empty string the default VFS object is used. ^Specifying an unknown ** VFS is an error. ^If sqlite3_open_v2() is used and the vfs option is ** present, then the VFS specified by the option takes precedence over ** the value passed as the fourth parameter to sqlite3_open_v2(). ** **
  • mode: ^(The mode parameter may be set to either "ro", "rw", ** "rwc", or "memory". Attempting to set it to any other value is ** an error)^. ** ^If "ro" is specified, then the database is opened for read-only ** access, just as if the [SQLITE_OPEN_READONLY] flag had been set in the ** third argument to sqlite3_open_v2(). ^If the mode option is set to ** "rw", then the database is opened for read-write (but not create) ** access, as if SQLITE_OPEN_READWRITE (but not SQLITE_OPEN_CREATE) had ** been set. ^Value "rwc" is equivalent to setting both ** SQLITE_OPEN_READWRITE and SQLITE_OPEN_CREATE. ^If the mode option is ** set to "memory" then a pure [in-memory database] that never reads ** or writes from disk is used. ^It is an error to specify a value for ** the mode parameter that is less restrictive than that specified by ** the flags passed in the third parameter to sqlite3_open_v2(). ** **
  • cache: ^The cache parameter may be set to either "shared" or ** "private". ^Setting it to "shared" is equivalent to setting the ** SQLITE_OPEN_SHAREDCACHE bit in the flags argument passed to ** sqlite3_open_v2(). ^Setting the cache parameter to "private" is ** equivalent to setting the SQLITE_OPEN_PRIVATECACHE bit. ** ^If sqlite3_open_v2() is used and the "cache" parameter is present in ** a URI filename, its value overrides any behavior requested by setting ** SQLITE_OPEN_PRIVATECACHE or SQLITE_OPEN_SHAREDCACHE flag. ** **
  • psow: ^The psow parameter indicates whether or not the ** [powersafe overwrite] property does or does not apply to the ** storage media on which the database file resides. ** **
  • nolock: ^The nolock parameter is a boolean query parameter ** which if set disables file locking in rollback journal modes. This ** is useful for accessing a database on a filesystem that does not ** support locking. Caution: Database corruption might result if two ** or more processes write to the same database and any one of those ** processes uses nolock=1. ** **
  • immutable: ^The immutable parameter is a boolean query ** parameter that indicates that the database file is stored on ** read-only media. ^When immutable is set, SQLite assumes that the ** database file cannot be changed, even by a process with higher ** privilege, and so the database is opened read-only and all locking ** and change detection is disabled. Caution: Setting the immutable ** property on a database file that does in fact change can result ** in incorrect query results and/or [SQLITE_CORRUPT] errors. ** See also: [SQLITE_IOCAP_IMMUTABLE]. ** **
** ** ^Specifying an unknown parameter in the query component of a URI is not an ** error. Future versions of SQLite might understand additional query ** parameters. See "[query parameters with special meaning to SQLite]" for ** additional information. ** ** [[URI filename examples]]

URI filename examples

** ** **
URI filenames Results **
file:data.db ** Open the file "data.db" in the current directory. **
file:/home/fred/data.db
** file:///home/fred/data.db
** file://localhost/home/fred/data.db
** Open the database file "/home/fred/data.db". **
file://darkstar/home/fred/data.db ** An error. "darkstar" is not a recognized authority. **
** file:///C:/Documents%20and%20Settings/fred/Desktop/data.db ** Windows only: Open the file "data.db" on fred's desktop on drive ** C:. Note that the %20 escaping in this example is not strictly ** necessary - space characters can be used literally ** in URI filenames. **
file:data.db?mode=ro&cache=private ** Open file "data.db" in the current directory for read-only access. ** Regardless of whether or not shared-cache mode is enabled by ** default, use a private cache. **
file:/home/fred/data.db?vfs=unix-dotfile ** Open file "/home/fred/data.db". Use the special VFS "unix-dotfile" ** that uses dot-files in place of posix advisory locking. **
file:data.db?mode=readonly ** An error. "readonly" is not a valid option for the "mode" parameter. **
** ** ^URI hexadecimal escape sequences (%HH) are supported within the path and ** query components of a URI. A hexadecimal escape sequence consists of a ** percent sign - "%" - followed by exactly two hexadecimal digits ** specifying an octet value. ^Before the path or query components of a ** URI filename are interpreted, they are encoded using UTF-8 and all ** hexadecimal escape sequences replaced by a single byte containing the ** corresponding octet. If this process generates an invalid UTF-8 encoding, ** the results are undefined. ** ** Note to Windows users: The encoding used for the filename argument ** of sqlite3_open() and sqlite3_open_v2() must be UTF-8, not whatever ** codepage is currently defined. Filenames containing international ** characters must be converted to UTF-8 prior to passing them into ** sqlite3_open() or sqlite3_open_v2(). ** ** Note to Windows Runtime users: The temporary directory must be set ** prior to calling sqlite3_open() or sqlite3_open_v2(). Otherwise, various ** features that require the use of temporary files may fail. ** ** See also: [sqlite3_temp_directory] */ SQLITE_API int sqlite3_open( const char *filename, /* Database filename (UTF-8) */ sqlite3 **ppDb /* OUT: SQLite db handle */ ); SQLITE_API int sqlite3_open16( const void *filename, /* Database filename (UTF-16) */ sqlite3 **ppDb /* OUT: SQLite db handle */ ); SQLITE_API int sqlite3_open_v2( const char *filename, /* Database filename (UTF-8) */ sqlite3 **ppDb, /* OUT: SQLite db handle */ int flags, /* Flags */ const char *zVfs /* Name of VFS module to use */ ); /* ** CAPI3REF: Obtain Values For URI Parameters ** ** These are utility routines, useful to VFS implementations, that check ** to see if a database file was a URI that contained a specific query ** parameter, and if so obtains the value of that query parameter. ** ** If F is the database filename pointer passed into the xOpen() method of ** a VFS implementation when the flags parameter to xOpen() has one or ** more of the [SQLITE_OPEN_URI] or [SQLITE_OPEN_MAIN_DB] bits set and ** P is the name of the query parameter, then ** sqlite3_uri_parameter(F,P) returns the value of the P ** parameter if it exists or a NULL pointer if P does not appear as a ** query parameter on F. If P is a query parameter of F ** has no explicit value, then sqlite3_uri_parameter(F,P) returns ** a pointer to an empty string. ** ** The sqlite3_uri_boolean(F,P,B) routine assumes that P is a boolean ** parameter and returns true (1) or false (0) according to the value ** of P. The sqlite3_uri_boolean(F,P,B) routine returns true (1) if the ** value of query parameter P is one of "yes", "true", or "on" in any ** case or if the value begins with a non-zero number. The ** sqlite3_uri_boolean(F,P,B) routines returns false (0) if the value of ** query parameter P is one of "no", "false", or "off" in any case or ** if the value begins with a numeric zero. If P is not a query ** parameter on F or if the value of P is does not match any of the ** above, then sqlite3_uri_boolean(F,P,B) returns (B!=0). ** ** The sqlite3_uri_int64(F,P,D) routine converts the value of P into a ** 64-bit signed integer and returns that integer, or D if P does not ** exist. If the value of P is something other than an integer, then ** zero is returned. ** ** If F is a NULL pointer, then sqlite3_uri_parameter(F,P) returns NULL and ** sqlite3_uri_boolean(F,P,B) returns B. If F is not a NULL pointer and ** is not a database file pathname pointer that SQLite passed into the xOpen ** VFS method, then the behavior of this routine is undefined and probably ** undesirable. */ SQLITE_API const char *sqlite3_uri_parameter(const char *zFilename, const char *zParam); SQLITE_API int sqlite3_uri_boolean(const char *zFile, const char *zParam, int bDefault); SQLITE_API sqlite3_int64 sqlite3_uri_int64(const char*, const char*, sqlite3_int64); /* ** CAPI3REF: Error Codes And Messages ** METHOD: sqlite3 ** ** ^If the most recent sqlite3_* API call associated with ** [database connection] D failed, then the sqlite3_errcode(D) interface ** returns the numeric [result code] or [extended result code] for that ** API call. ** If the most recent API call was successful, ** then the return value from sqlite3_errcode() is undefined. ** ^The sqlite3_extended_errcode() ** interface is the same except that it always returns the ** [extended result code] even when extended result codes are ** disabled. ** ** ^The sqlite3_errmsg() and sqlite3_errmsg16() return English-language ** text that describes the error, as either UTF-8 or UTF-16 respectively. ** ^(Memory to hold the error message string is managed internally. ** The application does not need to worry about freeing the result. ** However, the error string might be overwritten or deallocated by ** subsequent calls to other SQLite interface functions.)^ ** ** ^The sqlite3_errstr() interface returns the English-language text ** that describes the [result code], as UTF-8. ** ^(Memory to hold the error message string is managed internally ** and must not be freed by the application)^. ** ** When the serialized [threading mode] is in use, it might be the ** case that a second error occurs on a separate thread in between ** the time of the first error and the call to these interfaces. ** When that happens, the second error will be reported since these ** interfaces always report the most recent result. To avoid ** this, each thread can obtain exclusive use of the [database connection] D ** by invoking [sqlite3_mutex_enter]([sqlite3_db_mutex](D)) before beginning ** to use D and invoking [sqlite3_mutex_leave]([sqlite3_db_mutex](D)) after ** all calls to the interfaces listed here are completed. ** ** If an interface fails with SQLITE_MISUSE, that means the interface ** was invoked incorrectly by the application. In that case, the ** error code and message may or may not be set. */ SQLITE_API int sqlite3_errcode(sqlite3 *db); SQLITE_API int sqlite3_extended_errcode(sqlite3 *db); SQLITE_API const char *sqlite3_errmsg(sqlite3*); SQLITE_API const void *sqlite3_errmsg16(sqlite3*); SQLITE_API const char *sqlite3_errstr(int); /* ** CAPI3REF: Prepared Statement Object ** KEYWORDS: {prepared statement} {prepared statements} ** ** An instance of this object represents a single SQL statement that ** has been compiled into binary form and is ready to be evaluated. ** ** Think of each SQL statement as a separate computer program. The ** original SQL text is source code. A prepared statement object ** is the compiled object code. All SQL must be converted into a ** prepared statement before it can be run. ** ** The life-cycle of a prepared statement object usually goes like this: ** **
    **
  1. Create the prepared statement object using [sqlite3_prepare_v2()]. **
  2. Bind values to [parameters] using the sqlite3_bind_*() ** interfaces. **
  3. Run the SQL by calling [sqlite3_step()] one or more times. **
  4. Reset the prepared statement using [sqlite3_reset()] then go back ** to step 2. Do this zero or more times. **
  5. Destroy the object using [sqlite3_finalize()]. **
*/ typedef struct sqlite3_stmt sqlite3_stmt; /* ** CAPI3REF: Run-time Limits ** METHOD: sqlite3 ** ** ^(This interface allows the size of various constructs to be limited ** on a connection by connection basis. The first parameter is the ** [database connection] whose limit is to be set or queried. The ** second parameter is one of the [limit categories] that define a ** class of constructs to be size limited. The third parameter is the ** new limit for that construct.)^ ** ** ^If the new limit is a negative number, the limit is unchanged. ** ^(For each limit category SQLITE_LIMIT_NAME there is a ** [limits | hard upper bound] ** set at compile-time by a C preprocessor macro called ** [limits | SQLITE_MAX_NAME]. ** (The "_LIMIT_" in the name is changed to "_MAX_".))^ ** ^Attempts to increase a limit above its hard upper bound are ** silently truncated to the hard upper bound. ** ** ^Regardless of whether or not the limit was changed, the ** [sqlite3_limit()] interface returns the prior value of the limit. ** ^Hence, to find the current value of a limit without changing it, ** simply invoke this interface with the third parameter set to -1. ** ** Run-time limits are intended for use in applications that manage ** both their own internal database and also databases that are controlled ** by untrusted external sources. An example application might be a ** web browser that has its own databases for storing history and ** separate databases controlled by JavaScript applications downloaded ** off the Internet. The internal databases can be given the ** large, default limits. Databases managed by external sources can ** be given much smaller limits designed to prevent a denial of service ** attack. Developers might also want to use the [sqlite3_set_authorizer()] ** interface to further control untrusted SQL. The size of the database ** created by an untrusted script can be contained using the ** [max_page_count] [PRAGMA]. ** ** New run-time limit categories may be added in future releases. */ SQLITE_API int sqlite3_limit(sqlite3*, int id, int newVal); /* ** CAPI3REF: Run-Time Limit Categories ** KEYWORDS: {limit category} {*limit categories} ** ** These constants define various performance limits ** that can be lowered at run-time using [sqlite3_limit()]. ** The synopsis of the meanings of the various limits is shown below. ** Additional information is available at [limits | Limits in SQLite]. ** **
** [[SQLITE_LIMIT_LENGTH]] ^(
SQLITE_LIMIT_LENGTH
**
The maximum size of any string or BLOB or table row, in bytes.
)^ ** ** [[SQLITE_LIMIT_SQL_LENGTH]] ^(
SQLITE_LIMIT_SQL_LENGTH
**
The maximum length of an SQL statement, in bytes.
)^ ** ** [[SQLITE_LIMIT_COLUMN]] ^(
SQLITE_LIMIT_COLUMN
**
The maximum number of columns in a table definition or in the ** result set of a [SELECT] or the maximum number of columns in an index ** or in an ORDER BY or GROUP BY clause.
)^ ** ** [[SQLITE_LIMIT_EXPR_DEPTH]] ^(
SQLITE_LIMIT_EXPR_DEPTH
**
The maximum depth of the parse tree on any expression.
)^ ** ** [[SQLITE_LIMIT_COMPOUND_SELECT]] ^(
SQLITE_LIMIT_COMPOUND_SELECT
**
The maximum number of terms in a compound SELECT statement.
)^ ** ** [[SQLITE_LIMIT_VDBE_OP]] ^(
SQLITE_LIMIT_VDBE_OP
**
The maximum number of instructions in a virtual machine program ** used to implement an SQL statement. This limit is not currently ** enforced, though that might be added in some future release of ** SQLite.
)^ ** ** [[SQLITE_LIMIT_FUNCTION_ARG]] ^(
SQLITE_LIMIT_FUNCTION_ARG
**
The maximum number of arguments on a function.
)^ ** ** [[SQLITE_LIMIT_ATTACHED]] ^(
SQLITE_LIMIT_ATTACHED
**
The maximum number of [ATTACH | attached databases].)^
** ** [[SQLITE_LIMIT_LIKE_PATTERN_LENGTH]] ** ^(
SQLITE_LIMIT_LIKE_PATTERN_LENGTH
**
The maximum length of the pattern argument to the [LIKE] or ** [GLOB] operators.
)^ ** ** [[SQLITE_LIMIT_VARIABLE_NUMBER]] ** ^(
SQLITE_LIMIT_VARIABLE_NUMBER
**
The maximum index number of any [parameter] in an SQL statement.)^ ** ** [[SQLITE_LIMIT_TRIGGER_DEPTH]] ^(
SQLITE_LIMIT_TRIGGER_DEPTH
**
The maximum depth of recursion for triggers.
)^ ** ** [[SQLITE_LIMIT_WORKER_THREADS]] ^(
SQLITE_LIMIT_WORKER_THREADS
**
The maximum number of auxiliary worker threads that a single ** [prepared statement] may start.
)^ **
*/ #define SQLITE_LIMIT_LENGTH 0 #define SQLITE_LIMIT_SQL_LENGTH 1 #define SQLITE_LIMIT_COLUMN 2 #define SQLITE_LIMIT_EXPR_DEPTH 3 #define SQLITE_LIMIT_COMPOUND_SELECT 4 #define SQLITE_LIMIT_VDBE_OP 5 #define SQLITE_LIMIT_FUNCTION_ARG 6 #define SQLITE_LIMIT_ATTACHED 7 #define SQLITE_LIMIT_LIKE_PATTERN_LENGTH 8 #define SQLITE_LIMIT_VARIABLE_NUMBER 9 #define SQLITE_LIMIT_TRIGGER_DEPTH 10 #define SQLITE_LIMIT_WORKER_THREADS 11 /* ** CAPI3REF: Compiling An SQL Statement ** KEYWORDS: {SQL statement compiler} ** METHOD: sqlite3 ** CONSTRUCTOR: sqlite3_stmt ** ** To execute an SQL query, it must first be compiled into a byte-code ** program using one of these routines. ** ** The first argument, "db", is a [database connection] obtained from a ** prior successful call to [sqlite3_open()], [sqlite3_open_v2()] or ** [sqlite3_open16()]. The database connection must not have been closed. ** ** The second argument, "zSql", is the statement to be compiled, encoded ** as either UTF-8 or UTF-16. The sqlite3_prepare() and sqlite3_prepare_v2() ** interfaces use UTF-8, and sqlite3_prepare16() and sqlite3_prepare16_v2() ** use UTF-16. ** ** ^If the nByte argument is negative, then zSql is read up to the ** first zero terminator. ^If nByte is positive, then it is the ** number of bytes read from zSql. ^If nByte is zero, then no prepared ** statement is generated. ** If the caller knows that the supplied string is nul-terminated, then ** there is a small performance advantage to passing an nByte parameter that ** is the number of bytes in the input string including ** the nul-terminator. ** ** ^If pzTail is not NULL then *pzTail is made to point to the first byte ** past the end of the first SQL statement in zSql. These routines only ** compile the first statement in zSql, so *pzTail is left pointing to ** what remains uncompiled. ** ** ^*ppStmt is left pointing to a compiled [prepared statement] that can be ** executed using [sqlite3_step()]. ^If there is an error, *ppStmt is set ** to NULL. ^If the input text contains no SQL (if the input is an empty ** string or a comment) then *ppStmt is set to NULL. ** The calling procedure is responsible for deleting the compiled ** SQL statement using [sqlite3_finalize()] after it has finished with it. ** ppStmt may not be NULL. ** ** ^On success, the sqlite3_prepare() family of routines return [SQLITE_OK]; ** otherwise an [error code] is returned. ** ** The sqlite3_prepare_v2() and sqlite3_prepare16_v2() interfaces are ** recommended for all new programs. The two older interfaces are retained ** for backwards compatibility, but their use is discouraged. ** ^In the "v2" interfaces, the prepared statement ** that is returned (the [sqlite3_stmt] object) contains a copy of the ** original SQL text. This causes the [sqlite3_step()] interface to ** behave differently in three ways: ** **
    **
  1. ** ^If the database schema changes, instead of returning [SQLITE_SCHEMA] as it ** always used to do, [sqlite3_step()] will automatically recompile the SQL ** statement and try to run it again. As many as [SQLITE_MAX_SCHEMA_RETRY] ** retries will occur before sqlite3_step() gives up and returns an error. **
  2. ** **
  3. ** ^When an error occurs, [sqlite3_step()] will return one of the detailed ** [error codes] or [extended error codes]. ^The legacy behavior was that ** [sqlite3_step()] would only return a generic [SQLITE_ERROR] result code ** and the application would have to make a second call to [sqlite3_reset()] ** in order to find the underlying cause of the problem. With the "v2" prepare ** interfaces, the underlying reason for the error is returned immediately. **
  4. ** **
  5. ** ^If the specific value bound to [parameter | host parameter] in the ** WHERE clause might influence the choice of query plan for a statement, ** then the statement will be automatically recompiled, as if there had been ** a schema change, on the first [sqlite3_step()] call following any change ** to the [sqlite3_bind_text | bindings] of that [parameter]. ** ^The specific value of WHERE-clause [parameter] might influence the ** choice of query plan if the parameter is the left-hand side of a [LIKE] ** or [GLOB] operator or if the parameter is compared to an indexed column ** and the [SQLITE_ENABLE_STAT3] compile-time option is enabled. **
  6. **
*/ SQLITE_API int sqlite3_prepare( sqlite3 *db, /* Database handle */ const char *zSql, /* SQL statement, UTF-8 encoded */ int nByte, /* Maximum length of zSql in bytes. */ sqlite3_stmt **ppStmt, /* OUT: Statement handle */ const char **pzTail /* OUT: Pointer to unused portion of zSql */ ); SQLITE_API int sqlite3_prepare_v2( sqlite3 *db, /* Database handle */ const char *zSql, /* SQL statement, UTF-8 encoded */ int nByte, /* Maximum length of zSql in bytes. */ sqlite3_stmt **ppStmt, /* OUT: Statement handle */ const char **pzTail /* OUT: Pointer to unused portion of zSql */ ); SQLITE_API int sqlite3_prepare16( sqlite3 *db, /* Database handle */ const void *zSql, /* SQL statement, UTF-16 encoded */ int nByte, /* Maximum length of zSql in bytes. */ sqlite3_stmt **ppStmt, /* OUT: Statement handle */ const void **pzTail /* OUT: Pointer to unused portion of zSql */ ); SQLITE_API int sqlite3_prepare16_v2( sqlite3 *db, /* Database handle */ const void *zSql, /* SQL statement, UTF-16 encoded */ int nByte, /* Maximum length of zSql in bytes. */ sqlite3_stmt **ppStmt, /* OUT: Statement handle */ const void **pzTail /* OUT: Pointer to unused portion of zSql */ ); /* ** CAPI3REF: Retrieving Statement SQL ** METHOD: sqlite3_stmt ** ** ^The sqlite3_sql(P) interface returns a pointer to a copy of the UTF-8 ** SQL text used to create [prepared statement] P if P was ** created by either [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()]. ** ^The sqlite3_expanded_sql(P) interface returns a pointer to a UTF-8 ** string containing the SQL text of prepared statement P with ** [bound parameters] expanded. ** ** ^(For example, if a prepared statement is created using the SQL ** text "SELECT $abc,:xyz" and if parameter $abc is bound to integer 2345 ** and parameter :xyz is unbound, then sqlite3_sql() will return ** the original string, "SELECT $abc,:xyz" but sqlite3_expanded_sql() ** will return "SELECT 2345,NULL".)^ ** ** ^The sqlite3_expanded_sql() interface returns NULL if insufficient memory ** is available to hold the result, or if the result would exceed the ** the maximum string length determined by the [SQLITE_LIMIT_LENGTH]. ** ** ^The [SQLITE_TRACE_SIZE_LIMIT] compile-time option limits the size of ** bound parameter expansions. ^The [SQLITE_OMIT_TRACE] compile-time ** option causes sqlite3_expanded_sql() to always return NULL. ** ** ^The string returned by sqlite3_sql(P) is managed by SQLite and is ** automatically freed when the prepared statement is finalized. ** ^The string returned by sqlite3_expanded_sql(P), on the other hand, ** is obtained from [sqlite3_malloc()] and must be free by the application ** by passing it to [sqlite3_free()]. */ SQLITE_API const char *sqlite3_sql(sqlite3_stmt *pStmt); SQLITE_API char *sqlite3_expanded_sql(sqlite3_stmt *pStmt); /* ** CAPI3REF: Determine If An SQL Statement Writes The Database ** METHOD: sqlite3_stmt ** ** ^The sqlite3_stmt_readonly(X) interface returns true (non-zero) if ** and only if the [prepared statement] X makes no direct changes to ** the content of the database file. ** ** Note that [application-defined SQL functions] or ** [virtual tables] might change the database indirectly as a side effect. ** ^(For example, if an application defines a function "eval()" that ** calls [sqlite3_exec()], then the following SQL statement would ** change the database file through side-effects: ** **
**    SELECT eval('DELETE FROM t1') FROM t2;
** 
** ** But because the [SELECT] statement does not change the database file ** directly, sqlite3_stmt_readonly() would still return true.)^ ** ** ^Transaction control statements such as [BEGIN], [COMMIT], [ROLLBACK], ** [SAVEPOINT], and [RELEASE] cause sqlite3_stmt_readonly() to return true, ** since the statements themselves do not actually modify the database but ** rather they control the timing of when other statements modify the ** database. ^The [ATTACH] and [DETACH] statements also cause ** sqlite3_stmt_readonly() to return true since, while those statements ** change the configuration of a database connection, they do not make ** changes to the content of the database files on disk. */ SQLITE_API int sqlite3_stmt_readonly(sqlite3_stmt *pStmt); /* ** CAPI3REF: Determine If A Prepared Statement Has Been Reset ** METHOD: sqlite3_stmt ** ** ^The sqlite3_stmt_busy(S) interface returns true (non-zero) if the ** [prepared statement] S has been stepped at least once using ** [sqlite3_step(S)] but has neither run to completion (returned ** [SQLITE_DONE] from [sqlite3_step(S)]) nor ** been reset using [sqlite3_reset(S)]. ^The sqlite3_stmt_busy(S) ** interface returns false if S is a NULL pointer. If S is not a ** NULL pointer and is not a pointer to a valid [prepared statement] ** object, then the behavior is undefined and probably undesirable. ** ** This interface can be used in combination [sqlite3_next_stmt()] ** to locate all prepared statements associated with a database ** connection that are in need of being reset. This can be used, ** for example, in diagnostic routines to search for prepared ** statements that are holding a transaction open. */ SQLITE_API int sqlite3_stmt_busy(sqlite3_stmt*); /* ** CAPI3REF: Dynamically Typed Value Object ** KEYWORDS: {protected sqlite3_value} {unprotected sqlite3_value} ** ** SQLite uses the sqlite3_value object to represent all values ** that can be stored in a database table. SQLite uses dynamic typing ** for the values it stores. ^Values stored in sqlite3_value objects ** can be integers, floating point values, strings, BLOBs, or NULL. ** ** An sqlite3_value object may be either "protected" or "unprotected". ** Some interfaces require a protected sqlite3_value. Other interfaces ** will accept either a protected or an unprotected sqlite3_value. ** Every interface that accepts sqlite3_value arguments specifies ** whether or not it requires a protected sqlite3_value. The ** [sqlite3_value_dup()] interface can be used to construct a new ** protected sqlite3_value from an unprotected sqlite3_value. ** ** The terms "protected" and "unprotected" refer to whether or not ** a mutex is held. An internal mutex is held for a protected ** sqlite3_value object but no mutex is held for an unprotected ** sqlite3_value object. If SQLite is compiled to be single-threaded ** (with [SQLITE_THREADSAFE=0] and with [sqlite3_threadsafe()] returning 0) ** or if SQLite is run in one of reduced mutex modes ** [SQLITE_CONFIG_SINGLETHREAD] or [SQLITE_CONFIG_MULTITHREAD] ** then there is no distinction between protected and unprotected ** sqlite3_value objects and they can be used interchangeably. However, ** for maximum code portability it is recommended that applications ** still make the distinction between protected and unprotected ** sqlite3_value objects even when not strictly required. ** ** ^The sqlite3_value objects that are passed as parameters into the ** implementation of [application-defined SQL functions] are protected. ** ^The sqlite3_value object returned by ** [sqlite3_column_value()] is unprotected. ** Unprotected sqlite3_value objects may only be used with ** [sqlite3_result_value()] and [sqlite3_bind_value()]. ** The [sqlite3_value_blob | sqlite3_value_type()] family of ** interfaces require protected sqlite3_value objects. */ typedef struct Mem sqlite3_value; /* ** CAPI3REF: SQL Function Context Object ** ** The context in which an SQL function executes is stored in an ** sqlite3_context object. ^A pointer to an sqlite3_context object ** is always first parameter to [application-defined SQL functions]. ** The application-defined SQL function implementation will pass this ** pointer through into calls to [sqlite3_result_int | sqlite3_result()], ** [sqlite3_aggregate_context()], [sqlite3_user_data()], ** [sqlite3_context_db_handle()], [sqlite3_get_auxdata()], ** and/or [sqlite3_set_auxdata()]. */ typedef struct sqlite3_context sqlite3_context; /* ** CAPI3REF: Binding Values To Prepared Statements ** KEYWORDS: {host parameter} {host parameters} {host parameter name} ** KEYWORDS: {SQL parameter} {SQL parameters} {parameter binding} ** METHOD: sqlite3_stmt ** ** ^(In the SQL statement text input to [sqlite3_prepare_v2()] and its variants, ** literals may be replaced by a [parameter] that matches one of following ** templates: ** **
    **
  • ? **
  • ?NNN **
  • :VVV **
  • @VVV **
  • $VVV **
** ** In the templates above, NNN represents an integer literal, ** and VVV represents an alphanumeric identifier.)^ ^The values of these ** parameters (also called "host parameter names" or "SQL parameters") ** can be set using the sqlite3_bind_*() routines defined here. ** ** ^The first argument to the sqlite3_bind_*() routines is always ** a pointer to the [sqlite3_stmt] object returned from ** [sqlite3_prepare_v2()] or its variants. ** ** ^The second argument is the index of the SQL parameter to be set. ** ^The leftmost SQL parameter has an index of 1. ^When the same named ** SQL parameter is used more than once, second and subsequent ** occurrences have the same index as the first occurrence. ** ^The index for named parameters can be looked up using the ** [sqlite3_bind_parameter_index()] API if desired. ^The index ** for "?NNN" parameters is the value of NNN. ** ^The NNN value must be between 1 and the [sqlite3_limit()] ** parameter [SQLITE_LIMIT_VARIABLE_NUMBER] (default value: 999). ** ** ^The third argument is the value to bind to the parameter. ** ^If the third parameter to sqlite3_bind_text() or sqlite3_bind_text16() ** or sqlite3_bind_blob() is a NULL pointer then the fourth parameter ** is ignored and the end result is the same as sqlite3_bind_null(). ** ** ^(In those routines that have a fourth argument, its value is the ** number of bytes in the parameter. To be clear: the value is the ** number of bytes in the value, not the number of characters.)^ ** ^If the fourth parameter to sqlite3_bind_text() or sqlite3_bind_text16() ** is negative, then the length of the string is ** the number of bytes up to the first zero terminator. ** If the fourth parameter to sqlite3_bind_blob() is negative, then ** the behavior is undefined. ** If a non-negative fourth parameter is provided to sqlite3_bind_text() ** or sqlite3_bind_text16() or sqlite3_bind_text64() then ** that parameter must be the byte offset ** where the NUL terminator would occur assuming the string were NUL ** terminated. If any NUL characters occur at byte offsets less than ** the value of the fourth parameter then the resulting string value will ** contain embedded NULs. The result of expressions involving strings ** with embedded NULs is undefined. ** ** ^The fifth argument to the BLOB and string binding interfaces ** is a destructor used to dispose of the BLOB or ** string after SQLite has finished with it. ^The destructor is called ** to dispose of the BLOB or string even if the call to bind API fails. ** ^If the fifth argument is ** the special value [SQLITE_STATIC], then SQLite assumes that the ** information is in static, unmanaged space and does not need to be freed. ** ^If the fifth argument has the value [SQLITE_TRANSIENT], then ** SQLite makes its own private copy of the data immediately, before ** the sqlite3_bind_*() routine returns. ** ** ^The sixth argument to sqlite3_bind_text64() must be one of ** [SQLITE_UTF8], [SQLITE_UTF16], [SQLITE_UTF16BE], or [SQLITE_UTF16LE] ** to specify the encoding of the text in the third parameter. If ** the sixth argument to sqlite3_bind_text64() is not one of the ** allowed values shown above, or if the text encoding is different ** from the encoding specified by the sixth parameter, then the behavior ** is undefined. ** ** ^The sqlite3_bind_zeroblob() routine binds a BLOB of length N that ** is filled with zeroes. ^A zeroblob uses a fixed amount of memory ** (just an integer to hold its size) while it is being processed. ** Zeroblobs are intended to serve as placeholders for BLOBs whose ** content is later written using ** [sqlite3_blob_open | incremental BLOB I/O] routines. ** ^A negative value for the zeroblob results in a zero-length BLOB. ** ** ^If any of the sqlite3_bind_*() routines are called with a NULL pointer ** for the [prepared statement] or with a prepared statement for which ** [sqlite3_step()] has been called more recently than [sqlite3_reset()], ** then the call will return [SQLITE_MISUSE]. If any sqlite3_bind_() ** routine is passed a [prepared statement] that has been finalized, the ** result is undefined and probably harmful. ** ** ^Bindings are not cleared by the [sqlite3_reset()] routine. ** ^Unbound parameters are interpreted as NULL. ** ** ^The sqlite3_bind_* routines return [SQLITE_OK] on success or an ** [error code] if anything goes wrong. ** ^[SQLITE_TOOBIG] might be returned if the size of a string or BLOB ** exceeds limits imposed by [sqlite3_limit]([SQLITE_LIMIT_LENGTH]) or ** [SQLITE_MAX_LENGTH]. ** ^[SQLITE_RANGE] is returned if the parameter ** index is out of range. ^[SQLITE_NOMEM] is returned if malloc() fails. ** ** See also: [sqlite3_bind_parameter_count()], ** [sqlite3_bind_parameter_name()], and [sqlite3_bind_parameter_index()]. */ SQLITE_API int sqlite3_bind_blob(sqlite3_stmt*, int, const void*, int n, void(*)(void*)); SQLITE_API int sqlite3_bind_blob64(sqlite3_stmt*, int, const void*, sqlite3_uint64, void(*)(void*)); SQLITE_API int sqlite3_bind_double(sqlite3_stmt*, int, double); SQLITE_API int sqlite3_bind_int(sqlite3_stmt*, int, int); SQLITE_API int sqlite3_bind_int64(sqlite3_stmt*, int, sqlite3_int64); SQLITE_API int sqlite3_bind_null(sqlite3_stmt*, int); SQLITE_API int sqlite3_bind_text(sqlite3_stmt*,int,const char*,int,void(*)(void*)); SQLITE_API int sqlite3_bind_text16(sqlite3_stmt*, int, const void*, int, void(*)(void*)); SQLITE_API int sqlite3_bind_text64(sqlite3_stmt*, int, const char*, sqlite3_uint64, void(*)(void*), unsigned char encoding); SQLITE_API int sqlite3_bind_value(sqlite3_stmt*, int, const sqlite3_value*); SQLITE_API int sqlite3_bind_zeroblob(sqlite3_stmt*, int, int n); SQLITE_API int sqlite3_bind_zeroblob64(sqlite3_stmt*, int, sqlite3_uint64); /* ** CAPI3REF: Number Of SQL Parameters ** METHOD: sqlite3_stmt ** ** ^This routine can be used to find the number of [SQL parameters] ** in a [prepared statement]. SQL parameters are tokens of the ** form "?", "?NNN", ":AAA", "$AAA", or "@AAA" that serve as ** placeholders for values that are [sqlite3_bind_blob | bound] ** to the parameters at a later time. ** ** ^(This routine actually returns the index of the largest (rightmost) ** parameter. For all forms except ?NNN, this will correspond to the ** number of unique parameters. If parameters of the ?NNN form are used, ** there may be gaps in the list.)^ ** ** See also: [sqlite3_bind_blob|sqlite3_bind()], ** [sqlite3_bind_parameter_name()], and ** [sqlite3_bind_parameter_index()]. */ SQLITE_API int sqlite3_bind_parameter_count(sqlite3_stmt*); /* ** CAPI3REF: Name Of A Host Parameter ** METHOD: sqlite3_stmt ** ** ^The sqlite3_bind_parameter_name(P,N) interface returns ** the name of the N-th [SQL parameter] in the [prepared statement] P. ** ^(SQL parameters of the form "?NNN" or ":AAA" or "@AAA" or "$AAA" ** have a name which is the string "?NNN" or ":AAA" or "@AAA" or "$AAA" ** respectively. ** In other words, the initial ":" or "$" or "@" or "?" ** is included as part of the name.)^ ** ^Parameters of the form "?" without a following integer have no name ** and are referred to as "nameless" or "anonymous parameters". ** ** ^The first host parameter has an index of 1, not 0. ** ** ^If the value N is out of range or if the N-th parameter is ** nameless, then NULL is returned. ^The returned string is ** always in UTF-8 encoding even if the named parameter was ** originally specified as UTF-16 in [sqlite3_prepare16()] or ** [sqlite3_prepare16_v2()]. ** ** See also: [sqlite3_bind_blob|sqlite3_bind()], ** [sqlite3_bind_parameter_count()], and ** [sqlite3_bind_parameter_index()]. */ SQLITE_API const char *sqlite3_bind_parameter_name(sqlite3_stmt*, int); /* ** CAPI3REF: Index Of A Parameter With A Given Name ** METHOD: sqlite3_stmt ** ** ^Return the index of an SQL parameter given its name. ^The ** index value returned is suitable for use as the second ** parameter to [sqlite3_bind_blob|sqlite3_bind()]. ^A zero ** is returned if no matching parameter is found. ^The parameter ** name must be given in UTF-8 even if the original statement ** was prepared from UTF-16 text using [sqlite3_prepare16_v2()]. ** ** See also: [sqlite3_bind_blob|sqlite3_bind()], ** [sqlite3_bind_parameter_count()], and ** [sqlite3_bind_parameter_name()]. */ SQLITE_API int sqlite3_bind_parameter_index(sqlite3_stmt*, const char *zName); /* ** CAPI3REF: Reset All Bindings On A Prepared Statement ** METHOD: sqlite3_stmt ** ** ^Contrary to the intuition of many, [sqlite3_reset()] does not reset ** the [sqlite3_bind_blob | bindings] on a [prepared statement]. ** ^Use this routine to reset all host parameters to NULL. */ SQLITE_API int sqlite3_clear_bindings(sqlite3_stmt*); /* ** CAPI3REF: Number Of Columns In A Result Set ** METHOD: sqlite3_stmt ** ** ^Return the number of columns in the result set returned by the ** [prepared statement]. ^This routine returns 0 if pStmt is an SQL ** statement that does not return data (for example an [UPDATE]). ** ** See also: [sqlite3_data_count()] */ SQLITE_API int sqlite3_column_count(sqlite3_stmt *pStmt); /* ** CAPI3REF: Column Names In A Result Set ** METHOD: sqlite3_stmt ** ** ^These routines return the name assigned to a particular column ** in the result set of a [SELECT] statement. ^The sqlite3_column_name() ** interface returns a pointer to a zero-terminated UTF-8 string ** and sqlite3_column_name16() returns a pointer to a zero-terminated ** UTF-16 string. ^The first parameter is the [prepared statement] ** that implements the [SELECT] statement. ^The second parameter is the ** column number. ^The leftmost column is number 0. ** ** ^The returned string pointer is valid until either the [prepared statement] ** is destroyed by [sqlite3_finalize()] or until the statement is automatically ** reprepared by the first call to [sqlite3_step()] for a particular run ** or until the next call to ** sqlite3_column_name() or sqlite3_column_name16() on the same column. ** ** ^If sqlite3_malloc() fails during the processing of either routine ** (for example during a conversion from UTF-8 to UTF-16) then a ** NULL pointer is returned. ** ** ^The name of a result column is the value of the "AS" clause for ** that column, if there is an AS clause. If there is no AS clause ** then the name of the column is unspecified and may change from ** one release of SQLite to the next. */ SQLITE_API const char *sqlite3_column_name(sqlite3_stmt*, int N); SQLITE_API const void *sqlite3_column_name16(sqlite3_stmt*, int N); /* ** CAPI3REF: Source Of Data In A Query Result ** METHOD: sqlite3_stmt ** ** ^These routines provide a means to determine the database, table, and ** table column that is the origin of a particular result column in ** [SELECT] statement. ** ^The name of the database or table or column can be returned as ** either a UTF-8 or UTF-16 string. ^The _database_ routines return ** the database name, the _table_ routines return the table name, and ** the origin_ routines return the column name. ** ^The returned string is valid until the [prepared statement] is destroyed ** using [sqlite3_finalize()] or until the statement is automatically ** reprepared by the first call to [sqlite3_step()] for a particular run ** or until the same information is requested ** again in a different encoding. ** ** ^The names returned are the original un-aliased names of the ** database, table, and column. ** ** ^The first argument to these interfaces is a [prepared statement]. ** ^These functions return information about the Nth result column returned by ** the statement, where N is the second function argument. ** ^The left-most column is column 0 for these routines. ** ** ^If the Nth column returned by the statement is an expression or ** subquery and is not a column value, then all of these functions return ** NULL. ^These routine might also return NULL if a memory allocation error ** occurs. ^Otherwise, they return the name of the attached database, table, ** or column that query result column was extracted from. ** ** ^As with all other SQLite APIs, those whose names end with "16" return ** UTF-16 encoded strings and the other functions return UTF-8. ** ** ^These APIs are only available if the library was compiled with the ** [SQLITE_ENABLE_COLUMN_METADATA] C-preprocessor symbol. ** ** If two or more threads call one or more of these routines against the same ** prepared statement and column at the same time then the results are ** undefined. ** ** If two or more threads call one or more ** [sqlite3_column_database_name | column metadata interfaces] ** for the same [prepared statement] and result column ** at the same time then the results are undefined. */ SQLITE_API const char *sqlite3_column_database_name(sqlite3_stmt*,int); SQLITE_API const void *sqlite3_column_database_name16(sqlite3_stmt*,int); SQLITE_API const char *sqlite3_column_table_name(sqlite3_stmt*,int); SQLITE_API const void *sqlite3_column_table_name16(sqlite3_stmt*,int); SQLITE_API const char *sqlite3_column_origin_name(sqlite3_stmt*,int); SQLITE_API const void *sqlite3_column_origin_name16(sqlite3_stmt*,int); /* ** CAPI3REF: Declared Datatype Of A Query Result ** METHOD: sqlite3_stmt ** ** ^(The first parameter is a [prepared statement]. ** If this statement is a [SELECT] statement and the Nth column of the ** returned result set of that [SELECT] is a table column (not an ** expression or subquery) then the declared type of the table ** column is returned.)^ ^If the Nth column of the result set is an ** expression or subquery, then a NULL pointer is returned. ** ^The returned string is always UTF-8 encoded. ** ** ^(For example, given the database schema: ** ** CREATE TABLE t1(c1 VARIANT); ** ** and the following statement to be compiled: ** ** SELECT c1 + 1, c1 FROM t1; ** ** this routine would return the string "VARIANT" for the second result ** column (i==1), and a NULL pointer for the first result column (i==0).)^ ** ** ^SQLite uses dynamic run-time typing. ^So just because a column ** is declared to contain a particular type does not mean that the ** data stored in that column is of the declared type. SQLite is ** strongly typed, but the typing is dynamic not static. ^Type ** is associated with individual values, not with the containers ** used to hold those values. */ SQLITE_API const char *sqlite3_column_decltype(sqlite3_stmt*,int); SQLITE_API const void *sqlite3_column_decltype16(sqlite3_stmt*,int); /* ** CAPI3REF: Evaluate An SQL Statement ** METHOD: sqlite3_stmt ** ** After a [prepared statement] has been prepared using either ** [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()] or one of the legacy ** interfaces [sqlite3_prepare()] or [sqlite3_prepare16()], this function ** must be called one or more times to evaluate the statement. ** ** The details of the behavior of the sqlite3_step() interface depend ** on whether the statement was prepared using the newer "v2" interface ** [sqlite3_prepare_v2()] and [sqlite3_prepare16_v2()] or the older legacy ** interface [sqlite3_prepare()] and [sqlite3_prepare16()]. The use of the ** new "v2" interface is recommended for new applications but the legacy ** interface will continue to be supported. ** ** ^In the legacy interface, the return value will be either [SQLITE_BUSY], ** [SQLITE_DONE], [SQLITE_ROW], [SQLITE_ERROR], or [SQLITE_MISUSE]. ** ^With the "v2" interface, any of the other [result codes] or ** [extended result codes] might be returned as well. ** ** ^[SQLITE_BUSY] means that the database engine was unable to acquire the ** database locks it needs to do its job. ^If the statement is a [COMMIT] ** or occurs outside of an explicit transaction, then you can retry the ** statement. If the statement is not a [COMMIT] and occurs within an ** explicit transaction then you should rollback the transaction before ** continuing. ** ** ^[SQLITE_DONE] means that the statement has finished executing ** successfully. sqlite3_step() should not be called again on this virtual ** machine without first calling [sqlite3_reset()] to reset the virtual ** machine back to its initial state. ** ** ^If the SQL statement being executed returns any data, then [SQLITE_ROW] ** is returned each time a new row of data is ready for processing by the ** caller. The values may be accessed using the [column access functions]. ** sqlite3_step() is called again to retrieve the next row of data. ** ** ^[SQLITE_ERROR] means that a run-time error (such as a constraint ** violation) has occurred. sqlite3_step() should not be called again on ** the VM. More information may be found by calling [sqlite3_errmsg()]. ** ^With the legacy interface, a more specific error code (for example, ** [SQLITE_INTERRUPT], [SQLITE_SCHEMA], [SQLITE_CORRUPT], and so forth) ** can be obtained by calling [sqlite3_reset()] on the ** [prepared statement]. ^In the "v2" interface, ** the more specific error code is returned directly by sqlite3_step(). ** ** [SQLITE_MISUSE] means that the this routine was called inappropriately. ** Perhaps it was called on a [prepared statement] that has ** already been [sqlite3_finalize | finalized] or on one that had ** previously returned [SQLITE_ERROR] or [SQLITE_DONE]. Or it could ** be the case that the same database connection is being used by two or ** more threads at the same moment in time. ** ** For all versions of SQLite up to and including 3.6.23.1, a call to ** [sqlite3_reset()] was required after sqlite3_step() returned anything ** other than [SQLITE_ROW] before any subsequent invocation of ** sqlite3_step(). Failure to reset the prepared statement using ** [sqlite3_reset()] would result in an [SQLITE_MISUSE] return from ** sqlite3_step(). But after [version 3.6.23.1] ([dateof:3.6.23.1], ** sqlite3_step() began ** calling [sqlite3_reset()] automatically in this circumstance rather ** than returning [SQLITE_MISUSE]. This is not considered a compatibility ** break because any application that ever receives an SQLITE_MISUSE error ** is broken by definition. The [SQLITE_OMIT_AUTORESET] compile-time option ** can be used to restore the legacy behavior. ** ** Goofy Interface Alert: In the legacy interface, the sqlite3_step() ** API always returns a generic error code, [SQLITE_ERROR], following any ** error other than [SQLITE_BUSY] and [SQLITE_MISUSE]. You must call ** [sqlite3_reset()] or [sqlite3_finalize()] in order to find one of the ** specific [error codes] that better describes the error. ** We admit that this is a goofy design. The problem has been fixed ** with the "v2" interface. If you prepare all of your SQL statements ** using either [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()] instead ** of the legacy [sqlite3_prepare()] and [sqlite3_prepare16()] interfaces, ** then the more specific [error codes] are returned directly ** by sqlite3_step(). The use of the "v2" interface is recommended. */ SQLITE_API int sqlite3_step(sqlite3_stmt*); /* ** CAPI3REF: Number of columns in a result set ** METHOD: sqlite3_stmt ** ** ^The sqlite3_data_count(P) interface returns the number of columns in the ** current row of the result set of [prepared statement] P. ** ^If prepared statement P does not have results ready to return ** (via calls to the [sqlite3_column_int | sqlite3_column_*()] of ** interfaces) then sqlite3_data_count(P) returns 0. ** ^The sqlite3_data_count(P) routine also returns 0 if P is a NULL pointer. ** ^The sqlite3_data_count(P) routine returns 0 if the previous call to ** [sqlite3_step](P) returned [SQLITE_DONE]. ^The sqlite3_data_count(P) ** will return non-zero if previous call to [sqlite3_step](P) returned ** [SQLITE_ROW], except in the case of the [PRAGMA incremental_vacuum] ** where it always returns zero since each step of that multi-step ** pragma returns 0 columns of data. ** ** See also: [sqlite3_column_count()] */ SQLITE_API int sqlite3_data_count(sqlite3_stmt *pStmt); /* ** CAPI3REF: Fundamental Datatypes ** KEYWORDS: SQLITE_TEXT ** ** ^(Every value in SQLite has one of five fundamental datatypes: ** **
    **
  • 64-bit signed integer **
  • 64-bit IEEE floating point number **
  • string **
  • BLOB **
  • NULL **
)^ ** ** These constants are codes for each of those types. ** ** Note that the SQLITE_TEXT constant was also used in SQLite version 2 ** for a completely different meaning. Software that links against both ** SQLite version 2 and SQLite version 3 should use SQLITE3_TEXT, not ** SQLITE_TEXT. */ #define SQLITE_INTEGER 1 #define SQLITE_FLOAT 2 #define SQLITE_BLOB 4 #define SQLITE_NULL 5 #ifdef SQLITE_TEXT # undef SQLITE_TEXT #else # define SQLITE_TEXT 3 #endif #define SQLITE3_TEXT 3 /* ** CAPI3REF: Result Values From A Query ** KEYWORDS: {column access functions} ** METHOD: sqlite3_stmt ** ** ^These routines return information about a single column of the current ** result row of a query. ^In every case the first argument is a pointer ** to the [prepared statement] that is being evaluated (the [sqlite3_stmt*] ** that was returned from [sqlite3_prepare_v2()] or one of its variants) ** and the second argument is the index of the column for which information ** should be returned. ^The leftmost column of the result set has the index 0. ** ^The number of columns in the result can be determined using ** [sqlite3_column_count()]. ** ** If the SQL statement does not currently point to a valid row, or if the ** column index is out of range, the result is undefined. ** These routines may only be called when the most recent call to ** [sqlite3_step()] has returned [SQLITE_ROW] and neither ** [sqlite3_reset()] nor [sqlite3_finalize()] have been called subsequently. ** If any of these routines are called after [sqlite3_reset()] or ** [sqlite3_finalize()] or after [sqlite3_step()] has returned ** something other than [SQLITE_ROW], the results are undefined. ** If [sqlite3_step()] or [sqlite3_reset()] or [sqlite3_finalize()] ** are called from a different thread while any of these routines ** are pending, then the results are undefined. ** ** ^The sqlite3_column_type() routine returns the ** [SQLITE_INTEGER | datatype code] for the initial data type ** of the result column. ^The returned value is one of [SQLITE_INTEGER], ** [SQLITE_FLOAT], [SQLITE_TEXT], [SQLITE_BLOB], or [SQLITE_NULL]. The value ** returned by sqlite3_column_type() is only meaningful if no type ** conversions have occurred as described below. After a type conversion, ** the value returned by sqlite3_column_type() is undefined. Future ** versions of SQLite may change the behavior of sqlite3_column_type() ** following a type conversion. ** ** ^If the result is a BLOB or UTF-8 string then the sqlite3_column_bytes() ** routine returns the number of bytes in that BLOB or string. ** ^If the result is a UTF-16 string, then sqlite3_column_bytes() converts ** the string to UTF-8 and then returns the number of bytes. ** ^If the result is a numeric value then sqlite3_column_bytes() uses ** [sqlite3_snprintf()] to convert that value to a UTF-8 string and returns ** the number of bytes in that string. ** ^If the result is NULL, then sqlite3_column_bytes() returns zero. ** ** ^If the result is a BLOB or UTF-16 string then the sqlite3_column_bytes16() ** routine returns the number of bytes in that BLOB or string. ** ^If the result is a UTF-8 string, then sqlite3_column_bytes16() converts ** the string to UTF-16 and then returns the number of bytes. ** ^If the result is a numeric value then sqlite3_column_bytes16() uses ** [sqlite3_snprintf()] to convert that value to a UTF-16 string and returns ** the number of bytes in that string. ** ^If the result is NULL, then sqlite3_column_bytes16() returns zero. ** ** ^The values returned by [sqlite3_column_bytes()] and ** [sqlite3_column_bytes16()] do not include the zero terminators at the end ** of the string. ^For clarity: the values returned by ** [sqlite3_column_bytes()] and [sqlite3_column_bytes16()] are the number of ** bytes in the string, not the number of characters. ** ** ^Strings returned by sqlite3_column_text() and sqlite3_column_text16(), ** even empty strings, are always zero-terminated. ^The return ** value from sqlite3_column_blob() for a zero-length BLOB is a NULL pointer. ** ** Warning: ^The object returned by [sqlite3_column_value()] is an ** [unprotected sqlite3_value] object. In a multithreaded environment, ** an unprotected sqlite3_value object may only be used safely with ** [sqlite3_bind_value()] and [sqlite3_result_value()]. ** If the [unprotected sqlite3_value] object returned by ** [sqlite3_column_value()] is used in any other way, including calls ** to routines like [sqlite3_value_int()], [sqlite3_value_text()], ** or [sqlite3_value_bytes()], the behavior is not threadsafe. ** ** These routines attempt to convert the value where appropriate. ^For ** example, if the internal representation is FLOAT and a text result ** is requested, [sqlite3_snprintf()] is used internally to perform the ** conversion automatically. ^(The following table details the conversions ** that are applied: ** **
** **
Internal
Type
Requested
Type
Conversion ** **
NULL INTEGER Result is 0 **
NULL FLOAT Result is 0.0 **
NULL TEXT Result is a NULL pointer **
NULL BLOB Result is a NULL pointer **
INTEGER FLOAT Convert from integer to float **
INTEGER TEXT ASCII rendering of the integer **
INTEGER BLOB Same as INTEGER->TEXT **
FLOAT INTEGER [CAST] to INTEGER **
FLOAT TEXT ASCII rendering of the float **
FLOAT BLOB [CAST] to BLOB **
TEXT INTEGER [CAST] to INTEGER **
TEXT FLOAT [CAST] to REAL **
TEXT BLOB No change **
BLOB INTEGER [CAST] to INTEGER **
BLOB FLOAT [CAST] to REAL **
BLOB TEXT Add a zero terminator if needed **
**
)^ ** ** Note that when type conversions occur, pointers returned by prior ** calls to sqlite3_column_blob(), sqlite3_column_text(), and/or ** sqlite3_column_text16() may be invalidated. ** Type conversions and pointer invalidations might occur ** in the following cases: ** **
    **
  • The initial content is a BLOB and sqlite3_column_text() or ** sqlite3_column_text16() is called. A zero-terminator might ** need to be added to the string.
  • **
  • The initial content is UTF-8 text and sqlite3_column_bytes16() or ** sqlite3_column_text16() is called. The content must be converted ** to UTF-16.
  • **
  • The initial content is UTF-16 text and sqlite3_column_bytes() or ** sqlite3_column_text() is called. The content must be converted ** to UTF-8.
  • **
** ** ^Conversions between UTF-16be and UTF-16le are always done in place and do ** not invalidate a prior pointer, though of course the content of the buffer ** that the prior pointer references will have been modified. Other kinds ** of conversion are done in place when it is possible, but sometimes they ** are not possible and in those cases prior pointers are invalidated. ** ** The safest policy is to invoke these routines ** in one of the following ways: ** **
    **
  • sqlite3_column_text() followed by sqlite3_column_bytes()
  • **
  • sqlite3_column_blob() followed by sqlite3_column_bytes()
  • **
  • sqlite3_column_text16() followed by sqlite3_column_bytes16()
  • **
** ** In other words, you should call sqlite3_column_text(), ** sqlite3_column_blob(), or sqlite3_column_text16() first to force the result ** into the desired format, then invoke sqlite3_column_bytes() or ** sqlite3_column_bytes16() to find the size of the result. Do not mix calls ** to sqlite3_column_text() or sqlite3_column_blob() with calls to ** sqlite3_column_bytes16(), and do not mix calls to sqlite3_column_text16() ** with calls to sqlite3_column_bytes(). ** ** ^The pointers returned are valid until a type conversion occurs as ** described above, or until [sqlite3_step()] or [sqlite3_reset()] or ** [sqlite3_finalize()] is called. ^The memory space used to hold strings ** and BLOBs is freed automatically. Do not pass the pointers returned ** from [sqlite3_column_blob()], [sqlite3_column_text()], etc. into ** [sqlite3_free()]. ** ** ^(If a memory allocation error occurs during the evaluation of any ** of these routines, a default value is returned. The default value ** is either the integer 0, the floating point number 0.0, or a NULL ** pointer. Subsequent calls to [sqlite3_errcode()] will return ** [SQLITE_NOMEM].)^ */ SQLITE_API const void *sqlite3_column_blob(sqlite3_stmt*, int iCol); SQLITE_API int sqlite3_column_bytes(sqlite3_stmt*, int iCol); SQLITE_API int sqlite3_column_bytes16(sqlite3_stmt*, int iCol); SQLITE_API double sqlite3_column_double(sqlite3_stmt*, int iCol); SQLITE_API int sqlite3_column_int(sqlite3_stmt*, int iCol); SQLITE_API sqlite3_int64 sqlite3_column_int64(sqlite3_stmt*, int iCol); SQLITE_API const unsigned char *sqlite3_column_text(sqlite3_stmt*, int iCol); SQLITE_API const void *sqlite3_column_text16(sqlite3_stmt*, int iCol); SQLITE_API int sqlite3_column_type(sqlite3_stmt*, int iCol); SQLITE_API sqlite3_value *sqlite3_column_value(sqlite3_stmt*, int iCol); /* ** CAPI3REF: Destroy A Prepared Statement Object ** DESTRUCTOR: sqlite3_stmt ** ** ^The sqlite3_finalize() function is called to delete a [prepared statement]. ** ^If the most recent evaluation of the statement encountered no errors ** or if the statement is never been evaluated, then sqlite3_finalize() returns ** SQLITE_OK. ^If the most recent evaluation of statement S failed, then ** sqlite3_finalize(S) returns the appropriate [error code] or ** [extended error code]. ** ** ^The sqlite3_finalize(S) routine can be called at any point during ** the life cycle of [prepared statement] S: ** before statement S is ever evaluated, after ** one or more calls to [sqlite3_reset()], or after any call ** to [sqlite3_step()] regardless of whether or not the statement has ** completed execution. ** ** ^Invoking sqlite3_finalize() on a NULL pointer is a harmless no-op. ** ** The application must finalize every [prepared statement] in order to avoid ** resource leaks. It is a grievous error for the application to try to use ** a prepared statement after it has been finalized. Any use of a prepared ** statement after it has been finalized can result in undefined and ** undesirable behavior such as segfaults and heap corruption. */ SQLITE_API int sqlite3_finalize(sqlite3_stmt *pStmt); /* ** CAPI3REF: Reset A Prepared Statement Object ** METHOD: sqlite3_stmt ** ** The sqlite3_reset() function is called to reset a [prepared statement] ** object back to its initial state, ready to be re-executed. ** ^Any SQL statement variables that had values bound to them using ** the [sqlite3_bind_blob | sqlite3_bind_*() API] retain their values. ** Use [sqlite3_clear_bindings()] to reset the bindings. ** ** ^The [sqlite3_reset(S)] interface resets the [prepared statement] S ** back to the beginning of its program. ** ** ^If the most recent call to [sqlite3_step(S)] for the ** [prepared statement] S returned [SQLITE_ROW] or [SQLITE_DONE], ** or if [sqlite3_step(S)] has never before been called on S, ** then [sqlite3_reset(S)] returns [SQLITE_OK]. ** ** ^If the most recent call to [sqlite3_step(S)] for the ** [prepared statement] S indicated an error, then ** [sqlite3_reset(S)] returns an appropriate [error code]. ** ** ^The [sqlite3_reset(S)] interface does not change the values ** of any [sqlite3_bind_blob|bindings] on the [prepared statement] S. */ SQLITE_API int sqlite3_reset(sqlite3_stmt *pStmt); /* ** CAPI3REF: Create Or Redefine SQL Functions ** KEYWORDS: {function creation routines} ** KEYWORDS: {application-defined SQL function} ** KEYWORDS: {application-defined SQL functions} ** METHOD: sqlite3 ** ** ^These functions (collectively known as "function creation routines") ** are used to add SQL functions or aggregates or to redefine the behavior ** of existing SQL functions or aggregates. The only differences between ** these routines are the text encoding expected for ** the second parameter (the name of the function being created) ** and the presence or absence of a destructor callback for ** the application data pointer. ** ** ^The first parameter is the [database connection] to which the SQL ** function is to be added. ^If an application uses more than one database ** connection then application-defined SQL functions must be added ** to each database connection separately. ** ** ^The second parameter is the name of the SQL function to be created or ** redefined. ^The length of the name is limited to 255 bytes in a UTF-8 ** representation, exclusive of the zero-terminator. ^Note that the name ** length limit is in UTF-8 bytes, not characters nor UTF-16 bytes. ** ^Any attempt to create a function with a longer name ** will result in [SQLITE_MISUSE] being returned. ** ** ^The third parameter (nArg) ** is the number of arguments that the SQL function or ** aggregate takes. ^If this parameter is -1, then the SQL function or ** aggregate may take any number of arguments between 0 and the limit ** set by [sqlite3_limit]([SQLITE_LIMIT_FUNCTION_ARG]). If the third ** parameter is less than -1 or greater than 127 then the behavior is ** undefined. ** ** ^The fourth parameter, eTextRep, specifies what ** [SQLITE_UTF8 | text encoding] this SQL function prefers for ** its parameters. The application should set this parameter to ** [SQLITE_UTF16LE] if the function implementation invokes ** [sqlite3_value_text16le()] on an input, or [SQLITE_UTF16BE] if the ** implementation invokes [sqlite3_value_text16be()] on an input, or ** [SQLITE_UTF16] if [sqlite3_value_text16()] is used, or [SQLITE_UTF8] ** otherwise. ^The same SQL function may be registered multiple times using ** different preferred text encodings, with different implementations for ** each encoding. ** ^When multiple implementations of the same function are available, SQLite ** will pick the one that involves the least amount of data conversion. ** ** ^The fourth parameter may optionally be ORed with [SQLITE_DETERMINISTIC] ** to signal that the function will always return the same result given ** the same inputs within a single SQL statement. Most SQL functions are ** deterministic. The built-in [random()] SQL function is an example of a ** function that is not deterministic. The SQLite query planner is able to ** perform additional optimizations on deterministic functions, so use ** of the [SQLITE_DETERMINISTIC] flag is recommended where possible. ** ** ^(The fifth parameter is an arbitrary pointer. The implementation of the ** function can gain access to this pointer using [sqlite3_user_data()].)^ ** ** ^The sixth, seventh and eighth parameters, xFunc, xStep and xFinal, are ** pointers to C-language functions that implement the SQL function or ** aggregate. ^A scalar SQL function requires an implementation of the xFunc ** callback only; NULL pointers must be passed as the xStep and xFinal ** parameters. ^An aggregate SQL function requires an implementation of xStep ** and xFinal and NULL pointer must be passed for xFunc. ^To delete an existing ** SQL function or aggregate, pass NULL pointers for all three function ** callbacks. ** ** ^(If the ninth parameter to sqlite3_create_function_v2() is not NULL, ** then it is destructor for the application data pointer. ** The destructor is invoked when the function is deleted, either by being ** overloaded or when the database connection closes.)^ ** ^The destructor is also invoked if the call to ** sqlite3_create_function_v2() fails. ** ^When the destructor callback of the tenth parameter is invoked, it ** is passed a single argument which is a copy of the application data ** pointer which was the fifth parameter to sqlite3_create_function_v2(). ** ** ^It is permitted to register multiple implementations of the same ** functions with the same name but with either differing numbers of ** arguments or differing preferred text encodings. ^SQLite will use ** the implementation that most closely matches the way in which the ** SQL function is used. ^A function implementation with a non-negative ** nArg parameter is a better match than a function implementation with ** a negative nArg. ^A function where the preferred text encoding ** matches the database encoding is a better ** match than a function where the encoding is different. ** ^A function where the encoding difference is between UTF16le and UTF16be ** is a closer match than a function where the encoding difference is ** between UTF8 and UTF16. ** ** ^Built-in functions may be overloaded by new application-defined functions. ** ** ^An application-defined function is permitted to call other ** SQLite interfaces. However, such calls must not ** close the database connection nor finalize or reset the prepared ** statement in which the function is running. */ SQLITE_API int sqlite3_create_function( sqlite3 *db, const char *zFunctionName, int nArg, int eTextRep, void *pApp, void (*xFunc)(sqlite3_context*,int,sqlite3_value**), void (*xStep)(sqlite3_context*,int,sqlite3_value**), void (*xFinal)(sqlite3_context*) ); SQLITE_API int sqlite3_create_function16( sqlite3 *db, const void *zFunctionName, int nArg, int eTextRep, void *pApp, void (*xFunc)(sqlite3_context*,int,sqlite3_value**), void (*xStep)(sqlite3_context*,int,sqlite3_value**), void (*xFinal)(sqlite3_context*) ); SQLITE_API int sqlite3_create_function_v2( sqlite3 *db, const char *zFunctionName, int nArg, int eTextRep, void *pApp, void (*xFunc)(sqlite3_context*,int,sqlite3_value**), void (*xStep)(sqlite3_context*,int,sqlite3_value**), void (*xFinal)(sqlite3_context*), void(*xDestroy)(void*) ); /* ** CAPI3REF: Text Encodings ** ** These constant define integer codes that represent the various ** text encodings supported by SQLite. */ #define SQLITE_UTF8 1 /* IMP: R-37514-35566 */ #define SQLITE_UTF16LE 2 /* IMP: R-03371-37637 */ #define SQLITE_UTF16BE 3 /* IMP: R-51971-34154 */ #define SQLITE_UTF16 4 /* Use native byte order */ #define SQLITE_ANY 5 /* Deprecated */ #define SQLITE_UTF16_ALIGNED 8 /* sqlite3_create_collation only */ /* ** CAPI3REF: Function Flags ** ** These constants may be ORed together with the ** [SQLITE_UTF8 | preferred text encoding] as the fourth argument ** to [sqlite3_create_function()], [sqlite3_create_function16()], or ** [sqlite3_create_function_v2()]. */ #define SQLITE_DETERMINISTIC 0x800 /* ** CAPI3REF: Deprecated Functions ** DEPRECATED ** ** These functions are [deprecated]. In order to maintain ** backwards compatibility with older code, these functions continue ** to be supported. However, new applications should avoid ** the use of these functions. To encourage programmers to avoid ** these functions, we will not explain what they do. */ #ifndef SQLITE_OMIT_DEPRECATED SQLITE_API SQLITE_DEPRECATED int sqlite3_aggregate_count(sqlite3_context*); SQLITE_API SQLITE_DEPRECATED int sqlite3_expired(sqlite3_stmt*); SQLITE_API SQLITE_DEPRECATED int sqlite3_transfer_bindings(sqlite3_stmt*, sqlite3_stmt*); SQLITE_API SQLITE_DEPRECATED int sqlite3_global_recover(void); SQLITE_API SQLITE_DEPRECATED void sqlite3_thread_cleanup(void); SQLITE_API SQLITE_DEPRECATED int sqlite3_memory_alarm(void(*)(void*,sqlite3_int64,int), void*,sqlite3_int64); #endif /* ** CAPI3REF: Obtaining SQL Values ** METHOD: sqlite3_value ** ** The C-language implementation of SQL functions and aggregates uses ** this set of interface routines to access the parameter values on ** the function or aggregate. ** ** The xFunc (for scalar functions) or xStep (for aggregates) parameters ** to [sqlite3_create_function()] and [sqlite3_create_function16()] ** define callbacks that implement the SQL functions and aggregates. ** The 3rd parameter to these callbacks is an array of pointers to ** [protected sqlite3_value] objects. There is one [sqlite3_value] object for ** each parameter to the SQL function. These routines are used to ** extract values from the [sqlite3_value] objects. ** ** These routines work only with [protected sqlite3_value] objects. ** Any attempt to use these routines on an [unprotected sqlite3_value] ** object results in undefined behavior. ** ** ^These routines work just like the corresponding [column access functions] ** except that these routines take a single [protected sqlite3_value] object ** pointer instead of a [sqlite3_stmt*] pointer and an integer column number. ** ** ^The sqlite3_value_text16() interface extracts a UTF-16 string ** in the native byte-order of the host machine. ^The ** sqlite3_value_text16be() and sqlite3_value_text16le() interfaces ** extract UTF-16 strings as big-endian and little-endian respectively. ** ** ^(The sqlite3_value_numeric_type() interface attempts to apply ** numeric affinity to the value. This means that an attempt is ** made to convert the value to an integer or floating point. If ** such a conversion is possible without loss of information (in other ** words, if the value is a string that looks like a number) ** then the conversion is performed. Otherwise no conversion occurs. ** The [SQLITE_INTEGER | datatype] after conversion is returned.)^ ** ** Please pay particular attention to the fact that the pointer returned ** from [sqlite3_value_blob()], [sqlite3_value_text()], or ** [sqlite3_value_text16()] can be invalidated by a subsequent call to ** [sqlite3_value_bytes()], [sqlite3_value_bytes16()], [sqlite3_value_text()], ** or [sqlite3_value_text16()]. ** ** These routines must be called from the same thread as ** the SQL function that supplied the [sqlite3_value*] parameters. */ SQLITE_API const void *sqlite3_value_blob(sqlite3_value*); SQLITE_API int sqlite3_value_bytes(sqlite3_value*); SQLITE_API int sqlite3_value_bytes16(sqlite3_value*); SQLITE_API double sqlite3_value_double(sqlite3_value*); SQLITE_API int sqlite3_value_int(sqlite3_value*); SQLITE_API sqlite3_int64 sqlite3_value_int64(sqlite3_value*); SQLITE_API const unsigned char *sqlite3_value_text(sqlite3_value*); SQLITE_API const void *sqlite3_value_text16(sqlite3_value*); SQLITE_API const void *sqlite3_value_text16le(sqlite3_value*); SQLITE_API const void *sqlite3_value_text16be(sqlite3_value*); SQLITE_API int sqlite3_value_type(sqlite3_value*); SQLITE_API int sqlite3_value_numeric_type(sqlite3_value*); /* ** CAPI3REF: Finding The Subtype Of SQL Values ** METHOD: sqlite3_value ** ** The sqlite3_value_subtype(V) function returns the subtype for ** an [application-defined SQL function] argument V. The subtype ** information can be used to pass a limited amount of context from ** one SQL function to another. Use the [sqlite3_result_subtype()] ** routine to set the subtype for the return value of an SQL function. ** ** SQLite makes no use of subtype itself. It merely passes the subtype ** from the result of one [application-defined SQL function] into the ** input of another. */ SQLITE_API unsigned int sqlite3_value_subtype(sqlite3_value*); /* ** CAPI3REF: Copy And Free SQL Values ** METHOD: sqlite3_value ** ** ^The sqlite3_value_dup(V) interface makes a copy of the [sqlite3_value] ** object D and returns a pointer to that copy. ^The [sqlite3_value] returned ** is a [protected sqlite3_value] object even if the input is not. ** ^The sqlite3_value_dup(V) interface returns NULL if V is NULL or if a ** memory allocation fails. ** ** ^The sqlite3_value_free(V) interface frees an [sqlite3_value] object ** previously obtained from [sqlite3_value_dup()]. ^If V is a NULL pointer ** then sqlite3_value_free(V) is a harmless no-op. */ SQLITE_API sqlite3_value *sqlite3_value_dup(const sqlite3_value*); SQLITE_API void sqlite3_value_free(sqlite3_value*); /* ** CAPI3REF: Obtain Aggregate Function Context ** METHOD: sqlite3_context ** ** Implementations of aggregate SQL functions use this ** routine to allocate memory for storing their state. ** ** ^The first time the sqlite3_aggregate_context(C,N) routine is called ** for a particular aggregate function, SQLite ** allocates N of memory, zeroes out that memory, and returns a pointer ** to the new memory. ^On second and subsequent calls to ** sqlite3_aggregate_context() for the same aggregate function instance, ** the same buffer is returned. Sqlite3_aggregate_context() is normally ** called once for each invocation of the xStep callback and then one ** last time when the xFinal callback is invoked. ^(When no rows match ** an aggregate query, the xStep() callback of the aggregate function ** implementation is never called and xFinal() is called exactly once. ** In those cases, sqlite3_aggregate_context() might be called for the ** first time from within xFinal().)^ ** ** ^The sqlite3_aggregate_context(C,N) routine returns a NULL pointer ** when first called if N is less than or equal to zero or if a memory ** allocate error occurs. ** ** ^(The amount of space allocated by sqlite3_aggregate_context(C,N) is ** determined by the N parameter on first successful call. Changing the ** value of N in subsequent call to sqlite3_aggregate_context() within ** the same aggregate function instance will not resize the memory ** allocation.)^ Within the xFinal callback, it is customary to set ** N=0 in calls to sqlite3_aggregate_context(C,N) so that no ** pointless memory allocations occur. ** ** ^SQLite automatically frees the memory allocated by ** sqlite3_aggregate_context() when the aggregate query concludes. ** ** The first parameter must be a copy of the ** [sqlite3_context | SQL function context] that is the first parameter ** to the xStep or xFinal callback routine that implements the aggregate ** function. ** ** This routine must be called from the same thread in which ** the aggregate SQL function is running. */ SQLITE_API void *sqlite3_aggregate_context(sqlite3_context*, int nBytes); /* ** CAPI3REF: User Data For Functions ** METHOD: sqlite3_context ** ** ^The sqlite3_user_data() interface returns a copy of ** the pointer that was the pUserData parameter (the 5th parameter) ** of the [sqlite3_create_function()] ** and [sqlite3_create_function16()] routines that originally ** registered the application defined function. ** ** This routine must be called from the same thread in which ** the application-defined function is running. */ SQLITE_API void *sqlite3_user_data(sqlite3_context*); /* ** CAPI3REF: Database Connection For Functions ** METHOD: sqlite3_context ** ** ^The sqlite3_context_db_handle() interface returns a copy of ** the pointer to the [database connection] (the 1st parameter) ** of the [sqlite3_create_function()] ** and [sqlite3_create_function16()] routines that originally ** registered the application defined function. */ SQLITE_API sqlite3 *sqlite3_context_db_handle(sqlite3_context*); /* ** CAPI3REF: Function Auxiliary Data ** METHOD: sqlite3_context ** ** These functions may be used by (non-aggregate) SQL functions to ** associate metadata with argument values. If the same value is passed to ** multiple invocations of the same SQL function during query execution, under ** some circumstances the associated metadata may be preserved. An example ** of where this might be useful is in a regular-expression matching ** function. The compiled version of the regular expression can be stored as ** metadata associated with the pattern string. ** Then as long as the pattern string remains the same, ** the compiled regular expression can be reused on multiple ** invocations of the same function. ** ** ^The sqlite3_get_auxdata() interface returns a pointer to the metadata ** associated by the sqlite3_set_auxdata() function with the Nth argument ** value to the application-defined function. ^If there is no metadata ** associated with the function argument, this sqlite3_get_auxdata() interface ** returns a NULL pointer. ** ** ^The sqlite3_set_auxdata(C,N,P,X) interface saves P as metadata for the N-th ** argument of the application-defined function. ^Subsequent ** calls to sqlite3_get_auxdata(C,N) return P from the most recent ** sqlite3_set_auxdata(C,N,P,X) call if the metadata is still valid or ** NULL if the metadata has been discarded. ** ^After each call to sqlite3_set_auxdata(C,N,P,X) where X is not NULL, ** SQLite will invoke the destructor function X with parameter P exactly ** once, when the metadata is discarded. ** SQLite is free to discard the metadata at any time, including:
    **
  • ^(when the corresponding function parameter changes)^, or **
  • ^(when [sqlite3_reset()] or [sqlite3_finalize()] is called for the ** SQL statement)^, or **
  • ^(when sqlite3_set_auxdata() is invoked again on the same ** parameter)^, or **
  • ^(during the original sqlite3_set_auxdata() call when a memory ** allocation error occurs.)^
** ** Note the last bullet in particular. The destructor X in ** sqlite3_set_auxdata(C,N,P,X) might be called immediately, before the ** sqlite3_set_auxdata() interface even returns. Hence sqlite3_set_auxdata() ** should be called near the end of the function implementation and the ** function implementation should not make any use of P after ** sqlite3_set_auxdata() has been called. ** ** ^(In practice, metadata is preserved between function calls for ** function parameters that are compile-time constants, including literal ** values and [parameters] and expressions composed from the same.)^ ** ** These routines must be called from the same thread in which ** the SQL function is running. */ SQLITE_API void *sqlite3_get_auxdata(sqlite3_context*, int N); SQLITE_API void sqlite3_set_auxdata(sqlite3_context*, int N, void*, void (*)(void*)); /* ** CAPI3REF: Constants Defining Special Destructor Behavior ** ** These are special values for the destructor that is passed in as the ** final argument to routines like [sqlite3_result_blob()]. ^If the destructor ** argument is SQLITE_STATIC, it means that the content pointer is constant ** and will never change. It does not need to be destroyed. ^The ** SQLITE_TRANSIENT value means that the content will likely change in ** the near future and that SQLite should make its own private copy of ** the content before returning. ** ** The typedef is necessary to work around problems in certain ** C++ compilers. */ typedef void (*sqlite3_destructor_type)(void*); #define SQLITE_STATIC ((sqlite3_destructor_type)0) #define SQLITE_TRANSIENT ((sqlite3_destructor_type)-1) /* ** CAPI3REF: Setting The Result Of An SQL Function ** METHOD: sqlite3_context ** ** These routines are used by the xFunc or xFinal callbacks that ** implement SQL functions and aggregates. See ** [sqlite3_create_function()] and [sqlite3_create_function16()] ** for additional information. ** ** These functions work very much like the [parameter binding] family of ** functions used to bind values to host parameters in prepared statements. ** Refer to the [SQL parameter] documentation for additional information. ** ** ^The sqlite3_result_blob() interface sets the result from ** an application-defined function to be the BLOB whose content is pointed ** to by the second parameter and which is N bytes long where N is the ** third parameter. ** ** ^The sqlite3_result_zeroblob(C,N) and sqlite3_result_zeroblob64(C,N) ** interfaces set the result of the application-defined function to be ** a BLOB containing all zero bytes and N bytes in size. ** ** ^The sqlite3_result_double() interface sets the result from ** an application-defined function to be a floating point value specified ** by its 2nd argument. ** ** ^The sqlite3_result_error() and sqlite3_result_error16() functions ** cause the implemented SQL function to throw an exception. ** ^SQLite uses the string pointed to by the ** 2nd parameter of sqlite3_result_error() or sqlite3_result_error16() ** as the text of an error message. ^SQLite interprets the error ** message string from sqlite3_result_error() as UTF-8. ^SQLite ** interprets the string from sqlite3_result_error16() as UTF-16 in native ** byte order. ^If the third parameter to sqlite3_result_error() ** or sqlite3_result_error16() is negative then SQLite takes as the error ** message all text up through the first zero character. ** ^If the third parameter to sqlite3_result_error() or ** sqlite3_result_error16() is non-negative then SQLite takes that many ** bytes (not characters) from the 2nd parameter as the error message. ** ^The sqlite3_result_error() and sqlite3_result_error16() ** routines make a private copy of the error message text before ** they return. Hence, the calling function can deallocate or ** modify the text after they return without harm. ** ^The sqlite3_result_error_code() function changes the error code ** returned by SQLite as a result of an error in a function. ^By default, ** the error code is SQLITE_ERROR. ^A subsequent call to sqlite3_result_error() ** or sqlite3_result_error16() resets the error code to SQLITE_ERROR. ** ** ^The sqlite3_result_error_toobig() interface causes SQLite to throw an ** error indicating that a string or BLOB is too long to represent. ** ** ^The sqlite3_result_error_nomem() interface causes SQLite to throw an ** error indicating that a memory allocation failed. ** ** ^The sqlite3_result_int() interface sets the return value ** of the application-defined function to be the 32-bit signed integer ** value given in the 2nd argument. ** ^The sqlite3_result_int64() interface sets the return value ** of the application-defined function to be the 64-bit signed integer ** value given in the 2nd argument. ** ** ^The sqlite3_result_null() interface sets the return value ** of the application-defined function to be NULL. ** ** ^The sqlite3_result_text(), sqlite3_result_text16(), ** sqlite3_result_text16le(), and sqlite3_result_text16be() interfaces ** set the return value of the application-defined function to be ** a text string which is represented as UTF-8, UTF-16 native byte order, ** UTF-16 little endian, or UTF-16 big endian, respectively. ** ^The sqlite3_result_text64() interface sets the return value of an ** application-defined function to be a text string in an encoding ** specified by the fifth (and last) parameter, which must be one ** of [SQLITE_UTF8], [SQLITE_UTF16], [SQLITE_UTF16BE], or [SQLITE_UTF16LE]. ** ^SQLite takes the text result from the application from ** the 2nd parameter of the sqlite3_result_text* interfaces. ** ^If the 3rd parameter to the sqlite3_result_text* interfaces ** is negative, then SQLite takes result text from the 2nd parameter ** through the first zero character. ** ^If the 3rd parameter to the sqlite3_result_text* interfaces ** is non-negative, then as many bytes (not characters) of the text ** pointed to by the 2nd parameter are taken as the application-defined ** function result. If the 3rd parameter is non-negative, then it ** must be the byte offset into the string where the NUL terminator would ** appear if the string where NUL terminated. If any NUL characters occur ** in the string at a byte offset that is less than the value of the 3rd ** parameter, then the resulting string will contain embedded NULs and the ** result of expressions operating on strings with embedded NULs is undefined. ** ^If the 4th parameter to the sqlite3_result_text* interfaces ** or sqlite3_result_blob is a non-NULL pointer, then SQLite calls that ** function as the destructor on the text or BLOB result when it has ** finished using that result. ** ^If the 4th parameter to the sqlite3_result_text* interfaces or to ** sqlite3_result_blob is the special constant SQLITE_STATIC, then SQLite ** assumes that the text or BLOB result is in constant space and does not ** copy the content of the parameter nor call a destructor on the content ** when it has finished using that result. ** ^If the 4th parameter to the sqlite3_result_text* interfaces ** or sqlite3_result_blob is the special constant SQLITE_TRANSIENT ** then SQLite makes a copy of the result into space obtained from ** from [sqlite3_malloc()] before it returns. ** ** ^The sqlite3_result_value() interface sets the result of ** the application-defined function to be a copy of the ** [unprotected sqlite3_value] object specified by the 2nd parameter. ^The ** sqlite3_result_value() interface makes a copy of the [sqlite3_value] ** so that the [sqlite3_value] specified in the parameter may change or ** be deallocated after sqlite3_result_value() returns without harm. ** ^A [protected sqlite3_value] object may always be used where an ** [unprotected sqlite3_value] object is required, so either ** kind of [sqlite3_value] object can be used with this interface. ** ** If these routines are called from within the different thread ** than the one containing the application-defined function that received ** the [sqlite3_context] pointer, the results are undefined. */ SQLITE_API void sqlite3_result_blob(sqlite3_context*, const void*, int, void(*)(void*)); SQLITE_API void sqlite3_result_blob64(sqlite3_context*,const void*, sqlite3_uint64,void(*)(void*)); SQLITE_API void sqlite3_result_double(sqlite3_context*, double); SQLITE_API void sqlite3_result_error(sqlite3_context*, const char*, int); SQLITE_API void sqlite3_result_error16(sqlite3_context*, const void*, int); SQLITE_API void sqlite3_result_error_toobig(sqlite3_context*); SQLITE_API void sqlite3_result_error_nomem(sqlite3_context*); SQLITE_API void sqlite3_result_error_code(sqlite3_context*, int); SQLITE_API void sqlite3_result_int(sqlite3_context*, int); SQLITE_API void sqlite3_result_int64(sqlite3_context*, sqlite3_int64); SQLITE_API void sqlite3_result_null(sqlite3_context*); SQLITE_API void sqlite3_result_text(sqlite3_context*, const char*, int, void(*)(void*)); SQLITE_API void sqlite3_result_text64(sqlite3_context*, const char*,sqlite3_uint64, void(*)(void*), unsigned char encoding); SQLITE_API void sqlite3_result_text16(sqlite3_context*, const void*, int, void(*)(void*)); SQLITE_API void sqlite3_result_text16le(sqlite3_context*, const void*, int,void(*)(void*)); SQLITE_API void sqlite3_result_text16be(sqlite3_context*, const void*, int,void(*)(void*)); SQLITE_API void sqlite3_result_value(sqlite3_context*, sqlite3_value*); SQLITE_API void sqlite3_result_zeroblob(sqlite3_context*, int n); SQLITE_API int sqlite3_result_zeroblob64(sqlite3_context*, sqlite3_uint64 n); /* ** CAPI3REF: Setting The Subtype Of An SQL Function ** METHOD: sqlite3_context ** ** The sqlite3_result_subtype(C,T) function causes the subtype of ** the result from the [application-defined SQL function] with ** [sqlite3_context] C to be the value T. Only the lower 8 bits ** of the subtype T are preserved in current versions of SQLite; ** higher order bits are discarded. ** The number of subtype bytes preserved by SQLite might increase ** in future releases of SQLite. */ SQLITE_API void sqlite3_result_subtype(sqlite3_context*,unsigned int); /* ** CAPI3REF: Define New Collating Sequences ** METHOD: sqlite3 ** ** ^These functions add, remove, or modify a [collation] associated ** with the [database connection] specified as the first argument. ** ** ^The name of the collation is a UTF-8 string ** for sqlite3_create_collation() and sqlite3_create_collation_v2() ** and a UTF-16 string in native byte order for sqlite3_create_collation16(). ** ^Collation names that compare equal according to [sqlite3_strnicmp()] are ** considered to be the same name. ** ** ^(The third argument (eTextRep) must be one of the constants: **
    **
  • [SQLITE_UTF8], **
  • [SQLITE_UTF16LE], **
  • [SQLITE_UTF16BE], **
  • [SQLITE_UTF16], or **
  • [SQLITE_UTF16_ALIGNED]. **
)^ ** ^The eTextRep argument determines the encoding of strings passed ** to the collating function callback, xCallback. ** ^The [SQLITE_UTF16] and [SQLITE_UTF16_ALIGNED] values for eTextRep ** force strings to be UTF16 with native byte order. ** ^The [SQLITE_UTF16_ALIGNED] value for eTextRep forces strings to begin ** on an even byte address. ** ** ^The fourth argument, pArg, is an application data pointer that is passed ** through as the first argument to the collating function callback. ** ** ^The fifth argument, xCallback, is a pointer to the collating function. ** ^Multiple collating functions can be registered using the same name but ** with different eTextRep parameters and SQLite will use whichever ** function requires the least amount of data transformation. ** ^If the xCallback argument is NULL then the collating function is ** deleted. ^When all collating functions having the same name are deleted, ** that collation is no longer usable. ** ** ^The collating function callback is invoked with a copy of the pArg ** application data pointer and with two strings in the encoding specified ** by the eTextRep argument. The collating function must return an ** integer that is negative, zero, or positive ** if the first string is less than, equal to, or greater than the second, ** respectively. A collating function must always return the same answer ** given the same inputs. If two or more collating functions are registered ** to the same collation name (using different eTextRep values) then all ** must give an equivalent answer when invoked with equivalent strings. ** The collating function must obey the following properties for all ** strings A, B, and C: ** **
    **
  1. If A==B then B==A. **
  2. If A==B and B==C then A==C. **
  3. If A<B THEN B>A. **
  4. If A<B and B<C then A<C. **
** ** If a collating function fails any of the above constraints and that ** collating function is registered and used, then the behavior of SQLite ** is undefined. ** ** ^The sqlite3_create_collation_v2() works like sqlite3_create_collation() ** with the addition that the xDestroy callback is invoked on pArg when ** the collating function is deleted. ** ^Collating functions are deleted when they are overridden by later ** calls to the collation creation functions or when the ** [database connection] is closed using [sqlite3_close()]. ** ** ^The xDestroy callback is not called if the ** sqlite3_create_collation_v2() function fails. Applications that invoke ** sqlite3_create_collation_v2() with a non-NULL xDestroy argument should ** check the return code and dispose of the application data pointer ** themselves rather than expecting SQLite to deal with it for them. ** This is different from every other SQLite interface. The inconsistency ** is unfortunate but cannot be changed without breaking backwards ** compatibility. ** ** See also: [sqlite3_collation_needed()] and [sqlite3_collation_needed16()]. */ SQLITE_API int sqlite3_create_collation( sqlite3*, const char *zName, int eTextRep, void *pArg, int(*xCompare)(void*,int,const void*,int,const void*) ); SQLITE_API int sqlite3_create_collation_v2( sqlite3*, const char *zName, int eTextRep, void *pArg, int(*xCompare)(void*,int,const void*,int,const void*), void(*xDestroy)(void*) ); SQLITE_API int sqlite3_create_collation16( sqlite3*, const void *zName, int eTextRep, void *pArg, int(*xCompare)(void*,int,const void*,int,const void*) ); /* ** CAPI3REF: Collation Needed Callbacks ** METHOD: sqlite3 ** ** ^To avoid having to register all collation sequences before a database ** can be used, a single callback function may be registered with the ** [database connection] to be invoked whenever an undefined collation ** sequence is required. ** ** ^If the function is registered using the sqlite3_collation_needed() API, ** then it is passed the names of undefined collation sequences as strings ** encoded in UTF-8. ^If sqlite3_collation_needed16() is used, ** the names are passed as UTF-16 in machine native byte order. ** ^A call to either function replaces the existing collation-needed callback. ** ** ^(When the callback is invoked, the first argument passed is a copy ** of the second argument to sqlite3_collation_needed() or ** sqlite3_collation_needed16(). The second argument is the database ** connection. The third argument is one of [SQLITE_UTF8], [SQLITE_UTF16BE], ** or [SQLITE_UTF16LE], indicating the most desirable form of the collation ** sequence function required. The fourth parameter is the name of the ** required collation sequence.)^ ** ** The callback function should register the desired collation using ** [sqlite3_create_collation()], [sqlite3_create_collation16()], or ** [sqlite3_create_collation_v2()]. */ SQLITE_API int sqlite3_collation_needed( sqlite3*, void*, void(*)(void*,sqlite3*,int eTextRep,const char*) ); SQLITE_API int sqlite3_collation_needed16( sqlite3*, void*, void(*)(void*,sqlite3*,int eTextRep,const void*) ); #ifdef SQLITE_HAS_CODEC /* ** Specify the key for an encrypted database. This routine should be ** called right after sqlite3_open(). ** ** The code to implement this API is not available in the public release ** of SQLite. */ SQLITE_API int sqlite3_key( sqlite3 *db, /* Database to be rekeyed */ const void *pKey, int nKey /* The key */ ); SQLITE_API int sqlite3_key_v2( sqlite3 *db, /* Database to be rekeyed */ const char *zDbName, /* Name of the database */ const void *pKey, int nKey /* The key */ ); /* ** Change the key on an open database. If the current database is not ** encrypted, this routine will encrypt it. If pNew==0 or nNew==0, the ** database is decrypted. ** ** The code to implement this API is not available in the public release ** of SQLite. */ SQLITE_API int sqlite3_rekey( sqlite3 *db, /* Database to be rekeyed */ const void *pKey, int nKey /* The new key */ ); SQLITE_API int sqlite3_rekey_v2( sqlite3 *db, /* Database to be rekeyed */ const char *zDbName, /* Name of the database */ const void *pKey, int nKey /* The new key */ ); /* ** Specify the activation key for a SEE database. Unless ** activated, none of the SEE routines will work. */ SQLITE_API void sqlite3_activate_see( const char *zPassPhrase /* Activation phrase */ ); #endif #ifdef SQLITE_ENABLE_CEROD /* ** Specify the activation key for a CEROD database. Unless ** activated, none of the CEROD routines will work. */ SQLITE_API void sqlite3_activate_cerod( const char *zPassPhrase /* Activation phrase */ ); #endif /* ** CAPI3REF: Suspend Execution For A Short Time ** ** The sqlite3_sleep() function causes the current thread to suspend execution ** for at least a number of milliseconds specified in its parameter. ** ** If the operating system does not support sleep requests with ** millisecond time resolution, then the time will be rounded up to ** the nearest second. The number of milliseconds of sleep actually ** requested from the operating system is returned. ** ** ^SQLite implements this interface by calling the xSleep() ** method of the default [sqlite3_vfs] object. If the xSleep() method ** of the default VFS is not implemented correctly, or not implemented at ** all, then the behavior of sqlite3_sleep() may deviate from the description ** in the previous paragraphs. */ SQLITE_API int sqlite3_sleep(int); /* ** CAPI3REF: Name Of The Folder Holding Temporary Files ** ** ^(If this global variable is made to point to a string which is ** the name of a folder (a.k.a. directory), then all temporary files ** created by SQLite when using a built-in [sqlite3_vfs | VFS] ** will be placed in that directory.)^ ^If this variable ** is a NULL pointer, then SQLite performs a search for an appropriate ** temporary file directory. ** ** Applications are strongly discouraged from using this global variable. ** It is required to set a temporary folder on Windows Runtime (WinRT). ** But for all other platforms, it is highly recommended that applications ** neither read nor write this variable. This global variable is a relic ** that exists for backwards compatibility of legacy applications and should ** be avoided in new projects. ** ** It is not safe to read or modify this variable in more than one ** thread at a time. It is not safe to read or modify this variable ** if a [database connection] is being used at the same time in a separate ** thread. ** It is intended that this variable be set once ** as part of process initialization and before any SQLite interface ** routines have been called and that this variable remain unchanged ** thereafter. ** ** ^The [temp_store_directory pragma] may modify this variable and cause ** it to point to memory obtained from [sqlite3_malloc]. ^Furthermore, ** the [temp_store_directory pragma] always assumes that any string ** that this variable points to is held in memory obtained from ** [sqlite3_malloc] and the pragma may attempt to free that memory ** using [sqlite3_free]. ** Hence, if this variable is modified directly, either it should be ** made NULL or made to point to memory obtained from [sqlite3_malloc] ** or else the use of the [temp_store_directory pragma] should be avoided. ** Except when requested by the [temp_store_directory pragma], SQLite ** does not free the memory that sqlite3_temp_directory points to. If ** the application wants that memory to be freed, it must do ** so itself, taking care to only do so after all [database connection] ** objects have been destroyed. ** ** Note to Windows Runtime users: The temporary directory must be set ** prior to calling [sqlite3_open] or [sqlite3_open_v2]. Otherwise, various ** features that require the use of temporary files may fail. Here is an ** example of how to do this using C++ with the Windows Runtime: ** **
** LPCWSTR zPath = Windows::Storage::ApplicationData::Current->
**       TemporaryFolder->Path->Data();
** char zPathBuf[MAX_PATH + 1];
** memset(zPathBuf, 0, sizeof(zPathBuf));
** WideCharToMultiByte(CP_UTF8, 0, zPath, -1, zPathBuf, sizeof(zPathBuf),
**       NULL, NULL);
** sqlite3_temp_directory = sqlite3_mprintf("%s", zPathBuf);
** 
*/ SQLITE_API SQLITE_EXTERN char *sqlite3_temp_directory; /* ** CAPI3REF: Name Of The Folder Holding Database Files ** ** ^(If this global variable is made to point to a string which is ** the name of a folder (a.k.a. directory), then all database files ** specified with a relative pathname and created or accessed by ** SQLite when using a built-in windows [sqlite3_vfs | VFS] will be assumed ** to be relative to that directory.)^ ^If this variable is a NULL ** pointer, then SQLite assumes that all database files specified ** with a relative pathname are relative to the current directory ** for the process. Only the windows VFS makes use of this global ** variable; it is ignored by the unix VFS. ** ** Changing the value of this variable while a database connection is ** open can result in a corrupt database. ** ** It is not safe to read or modify this variable in more than one ** thread at a time. It is not safe to read or modify this variable ** if a [database connection] is being used at the same time in a separate ** thread. ** It is intended that this variable be set once ** as part of process initialization and before any SQLite interface ** routines have been called and that this variable remain unchanged ** thereafter. ** ** ^The [data_store_directory pragma] may modify this variable and cause ** it to point to memory obtained from [sqlite3_malloc]. ^Furthermore, ** the [data_store_directory pragma] always assumes that any string ** that this variable points to is held in memory obtained from ** [sqlite3_malloc] and the pragma may attempt to free that memory ** using [sqlite3_free]. ** Hence, if this variable is modified directly, either it should be ** made NULL or made to point to memory obtained from [sqlite3_malloc] ** or else the use of the [data_store_directory pragma] should be avoided. */ SQLITE_API SQLITE_EXTERN char *sqlite3_data_directory; /* ** CAPI3REF: Test For Auto-Commit Mode ** KEYWORDS: {autocommit mode} ** METHOD: sqlite3 ** ** ^The sqlite3_get_autocommit() interface returns non-zero or ** zero if the given database connection is or is not in autocommit mode, ** respectively. ^Autocommit mode is on by default. ** ^Autocommit mode is disabled by a [BEGIN] statement. ** ^Autocommit mode is re-enabled by a [COMMIT] or [ROLLBACK]. ** ** If certain kinds of errors occur on a statement within a multi-statement ** transaction (errors including [SQLITE_FULL], [SQLITE_IOERR], ** [SQLITE_NOMEM], [SQLITE_BUSY], and [SQLITE_INTERRUPT]) then the ** transaction might be rolled back automatically. The only way to ** find out whether SQLite automatically rolled back the transaction after ** an error is to use this function. ** ** If another thread changes the autocommit status of the database ** connection while this routine is running, then the return value ** is undefined. */ SQLITE_API int sqlite3_get_autocommit(sqlite3*); /* ** CAPI3REF: Find The Database Handle Of A Prepared Statement ** METHOD: sqlite3_stmt ** ** ^The sqlite3_db_handle interface returns the [database connection] handle ** to which a [prepared statement] belongs. ^The [database connection] ** returned by sqlite3_db_handle is the same [database connection] ** that was the first argument ** to the [sqlite3_prepare_v2()] call (or its variants) that was used to ** create the statement in the first place. */ SQLITE_API sqlite3 *sqlite3_db_handle(sqlite3_stmt*); /* ** CAPI3REF: Return The Filename For A Database Connection ** METHOD: sqlite3 ** ** ^The sqlite3_db_filename(D,N) interface returns a pointer to a filename ** associated with database N of connection D. ^The main database file ** has the name "main". If there is no attached database N on the database ** connection D, or if database N is a temporary or in-memory database, then ** a NULL pointer is returned. ** ** ^The filename returned by this function is the output of the ** xFullPathname method of the [VFS]. ^In other words, the filename ** will be an absolute pathname, even if the filename used ** to open the database originally was a URI or relative pathname. */ SQLITE_API const char *sqlite3_db_filename(sqlite3 *db, const char *zDbName); /* ** CAPI3REF: Determine if a database is read-only ** METHOD: sqlite3 ** ** ^The sqlite3_db_readonly(D,N) interface returns 1 if the database N ** of connection D is read-only, 0 if it is read/write, or -1 if N is not ** the name of a database on connection D. */ SQLITE_API int sqlite3_db_readonly(sqlite3 *db, const char *zDbName); /* ** CAPI3REF: Find the next prepared statement ** METHOD: sqlite3 ** ** ^This interface returns a pointer to the next [prepared statement] after ** pStmt associated with the [database connection] pDb. ^If pStmt is NULL ** then this interface returns a pointer to the first prepared statement ** associated with the database connection pDb. ^If no prepared statement ** satisfies the conditions of this routine, it returns NULL. ** ** The [database connection] pointer D in a call to ** [sqlite3_next_stmt(D,S)] must refer to an open database ** connection and in particular must not be a NULL pointer. */ SQLITE_API sqlite3_stmt *sqlite3_next_stmt(sqlite3 *pDb, sqlite3_stmt *pStmt); /* ** CAPI3REF: Commit And Rollback Notification Callbacks ** METHOD: sqlite3 ** ** ^The sqlite3_commit_hook() interface registers a callback ** function to be invoked whenever a transaction is [COMMIT | committed]. ** ^Any callback set by a previous call to sqlite3_commit_hook() ** for the same database connection is overridden. ** ^The sqlite3_rollback_hook() interface registers a callback ** function to be invoked whenever a transaction is [ROLLBACK | rolled back]. ** ^Any callback set by a previous call to sqlite3_rollback_hook() ** for the same database connection is overridden. ** ^The pArg argument is passed through to the callback. ** ^If the callback on a commit hook function returns non-zero, ** then the commit is converted into a rollback. ** ** ^The sqlite3_commit_hook(D,C,P) and sqlite3_rollback_hook(D,C,P) functions ** return the P argument from the previous call of the same function ** on the same [database connection] D, or NULL for ** the first call for each function on D. ** ** The commit and rollback hook callbacks are not reentrant. ** The callback implementation must not do anything that will modify ** the database connection that invoked the callback. Any actions ** to modify the database connection must be deferred until after the ** completion of the [sqlite3_step()] call that triggered the commit ** or rollback hook in the first place. ** Note that running any other SQL statements, including SELECT statements, ** or merely calling [sqlite3_prepare_v2()] and [sqlite3_step()] will modify ** the database connections for the meaning of "modify" in this paragraph. ** ** ^Registering a NULL function disables the callback. ** ** ^When the commit hook callback routine returns zero, the [COMMIT] ** operation is allowed to continue normally. ^If the commit hook ** returns non-zero, then the [COMMIT] is converted into a [ROLLBACK]. ** ^The rollback hook is invoked on a rollback that results from a commit ** hook returning non-zero, just as it would be with any other rollback. ** ** ^For the purposes of this API, a transaction is said to have been ** rolled back if an explicit "ROLLBACK" statement is executed, or ** an error or constraint causes an implicit rollback to occur. ** ^The rollback callback is not invoked if a transaction is ** automatically rolled back because the database connection is closed. ** ** See also the [sqlite3_update_hook()] interface. */ SQLITE_API void *sqlite3_commit_hook(sqlite3*, int(*)(void*), void*); SQLITE_API void *sqlite3_rollback_hook(sqlite3*, void(*)(void *), void*); /* ** CAPI3REF: Data Change Notification Callbacks ** METHOD: sqlite3 ** ** ^The sqlite3_update_hook() interface registers a callback function ** with the [database connection] identified by the first argument ** to be invoked whenever a row is updated, inserted or deleted in ** a [rowid table]. ** ^Any callback set by a previous call to this function ** for the same database connection is overridden. ** ** ^The second argument is a pointer to the function to invoke when a ** row is updated, inserted or deleted in a rowid table. ** ^The first argument to the callback is a copy of the third argument ** to sqlite3_update_hook(). ** ^The second callback argument is one of [SQLITE_INSERT], [SQLITE_DELETE], ** or [SQLITE_UPDATE], depending on the operation that caused the callback ** to be invoked. ** ^The third and fourth arguments to the callback contain pointers to the ** database and table name containing the affected row. ** ^The final callback parameter is the [rowid] of the row. ** ^In the case of an update, this is the [rowid] after the update takes place. ** ** ^(The update hook is not invoked when internal system tables are ** modified (i.e. sqlite_master and sqlite_sequence).)^ ** ^The update hook is not invoked when [WITHOUT ROWID] tables are modified. ** ** ^In the current implementation, the update hook ** is not invoked when duplication rows are deleted because of an ** [ON CONFLICT | ON CONFLICT REPLACE] clause. ^Nor is the update hook ** invoked when rows are deleted using the [truncate optimization]. ** The exceptions defined in this paragraph might change in a future ** release of SQLite. ** ** The update hook implementation must not do anything that will modify ** the database connection that invoked the update hook. Any actions ** to modify the database connection must be deferred until after the ** completion of the [sqlite3_step()] call that triggered the update hook. ** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their ** database connections for the meaning of "modify" in this paragraph. ** ** ^The sqlite3_update_hook(D,C,P) function ** returns the P argument from the previous call ** on the same [database connection] D, or NULL for ** the first call on D. ** ** See also the [sqlite3_commit_hook()], [sqlite3_rollback_hook()], ** and [sqlite3_preupdate_hook()] interfaces. */ SQLITE_API void *sqlite3_update_hook( sqlite3*, void(*)(void *,int ,char const *,char const *,sqlite3_int64), void* ); /* ** CAPI3REF: Enable Or Disable Shared Pager Cache ** ** ^(This routine enables or disables the sharing of the database cache ** and schema data structures between [database connection | connections] ** to the same database. Sharing is enabled if the argument is true ** and disabled if the argument is false.)^ ** ** ^Cache sharing is enabled and disabled for an entire process. ** This is a change as of SQLite [version 3.5.0] ([dateof:3.5.0]). ** In prior versions of SQLite, ** sharing was enabled or disabled for each thread separately. ** ** ^(The cache sharing mode set by this interface effects all subsequent ** calls to [sqlite3_open()], [sqlite3_open_v2()], and [sqlite3_open16()]. ** Existing database connections continue use the sharing mode ** that was in effect at the time they were opened.)^ ** ** ^(This routine returns [SQLITE_OK] if shared cache was enabled or disabled ** successfully. An [error code] is returned otherwise.)^ ** ** ^Shared cache is disabled by default. But this might change in ** future releases of SQLite. Applications that care about shared ** cache setting should set it explicitly. ** ** Note: This method is disabled on MacOS X 10.7 and iOS version 5.0 ** and will always return SQLITE_MISUSE. On those systems, ** shared cache mode should be enabled per-database connection via ** [sqlite3_open_v2()] with [SQLITE_OPEN_SHAREDCACHE]. ** ** This interface is threadsafe on processors where writing a ** 32-bit integer is atomic. ** ** See Also: [SQLite Shared-Cache Mode] */ SQLITE_API int sqlite3_enable_shared_cache(int); /* ** CAPI3REF: Attempt To Free Heap Memory ** ** ^The sqlite3_release_memory() interface attempts to free N bytes ** of heap memory by deallocating non-essential memory allocations ** held by the database library. Memory used to cache database ** pages to improve performance is an example of non-essential memory. ** ^sqlite3_release_memory() returns the number of bytes actually freed, ** which might be more or less than the amount requested. ** ^The sqlite3_release_memory() routine is a no-op returning zero ** if SQLite is not compiled with [SQLITE_ENABLE_MEMORY_MANAGEMENT]. ** ** See also: [sqlite3_db_release_memory()] */ SQLITE_API int sqlite3_release_memory(int); /* ** CAPI3REF: Free Memory Used By A Database Connection ** METHOD: sqlite3 ** ** ^The sqlite3_db_release_memory(D) interface attempts to free as much heap ** memory as possible from database connection D. Unlike the ** [sqlite3_release_memory()] interface, this interface is in effect even ** when the [SQLITE_ENABLE_MEMORY_MANAGEMENT] compile-time option is ** omitted. ** ** See also: [sqlite3_release_memory()] */ SQLITE_API int sqlite3_db_release_memory(sqlite3*); /* ** CAPI3REF: Impose A Limit On Heap Size ** ** ^The sqlite3_soft_heap_limit64() interface sets and/or queries the ** soft limit on the amount of heap memory that may be allocated by SQLite. ** ^SQLite strives to keep heap memory utilization below the soft heap ** limit by reducing the number of pages held in the page cache ** as heap memory usages approaches the limit. ** ^The soft heap limit is "soft" because even though SQLite strives to stay ** below the limit, it will exceed the limit rather than generate ** an [SQLITE_NOMEM] error. In other words, the soft heap limit ** is advisory only. ** ** ^The return value from sqlite3_soft_heap_limit64() is the size of ** the soft heap limit prior to the call, or negative in the case of an ** error. ^If the argument N is negative ** then no change is made to the soft heap limit. Hence, the current ** size of the soft heap limit can be determined by invoking ** sqlite3_soft_heap_limit64() with a negative argument. ** ** ^If the argument N is zero then the soft heap limit is disabled. ** ** ^(The soft heap limit is not enforced in the current implementation ** if one or more of following conditions are true: ** **
    **
  • The soft heap limit is set to zero. **
  • Memory accounting is disabled using a combination of the ** [sqlite3_config]([SQLITE_CONFIG_MEMSTATUS],...) start-time option and ** the [SQLITE_DEFAULT_MEMSTATUS] compile-time option. **
  • An alternative page cache implementation is specified using ** [sqlite3_config]([SQLITE_CONFIG_PCACHE2],...). **
  • The page cache allocates from its own memory pool supplied ** by [sqlite3_config]([SQLITE_CONFIG_PAGECACHE],...) rather than ** from the heap. **
)^ ** ** Beginning with SQLite [version 3.7.3] ([dateof:3.7.3]), ** the soft heap limit is enforced ** regardless of whether or not the [SQLITE_ENABLE_MEMORY_MANAGEMENT] ** compile-time option is invoked. With [SQLITE_ENABLE_MEMORY_MANAGEMENT], ** the soft heap limit is enforced on every memory allocation. Without ** [SQLITE_ENABLE_MEMORY_MANAGEMENT], the soft heap limit is only enforced ** when memory is allocated by the page cache. Testing suggests that because ** the page cache is the predominate memory user in SQLite, most ** applications will achieve adequate soft heap limit enforcement without ** the use of [SQLITE_ENABLE_MEMORY_MANAGEMENT]. ** ** The circumstances under which SQLite will enforce the soft heap limit may ** changes in future releases of SQLite. */ SQLITE_API sqlite3_int64 sqlite3_soft_heap_limit64(sqlite3_int64 N); /* ** CAPI3REF: Deprecated Soft Heap Limit Interface ** DEPRECATED ** ** This is a deprecated version of the [sqlite3_soft_heap_limit64()] ** interface. This routine is provided for historical compatibility ** only. All new applications should use the ** [sqlite3_soft_heap_limit64()] interface rather than this one. */ SQLITE_API SQLITE_DEPRECATED void sqlite3_soft_heap_limit(int N); /* ** CAPI3REF: Extract Metadata About A Column Of A Table ** METHOD: sqlite3 ** ** ^(The sqlite3_table_column_metadata(X,D,T,C,....) routine returns ** information about column C of table T in database D ** on [database connection] X.)^ ^The sqlite3_table_column_metadata() ** interface returns SQLITE_OK and fills in the non-NULL pointers in ** the final five arguments with appropriate values if the specified ** column exists. ^The sqlite3_table_column_metadata() interface returns ** SQLITE_ERROR and if the specified column does not exist. ** ^If the column-name parameter to sqlite3_table_column_metadata() is a ** NULL pointer, then this routine simply checks for the existence of the ** table and returns SQLITE_OK if the table exists and SQLITE_ERROR if it ** does not. ** ** ^The column is identified by the second, third and fourth parameters to ** this function. ^(The second parameter is either the name of the database ** (i.e. "main", "temp", or an attached database) containing the specified ** table or NULL.)^ ^If it is NULL, then all attached databases are searched ** for the table using the same algorithm used by the database engine to ** resolve unqualified table references. ** ** ^The third and fourth parameters to this function are the table and column ** name of the desired column, respectively. ** ** ^Metadata is returned by writing to the memory locations passed as the 5th ** and subsequent parameters to this function. ^Any of these arguments may be ** NULL, in which case the corresponding element of metadata is omitted. ** ** ^(
** **
Parameter Output
Type
Description ** **
5th const char* Data type **
6th const char* Name of default collation sequence **
7th int True if column has a NOT NULL constraint **
8th int True if column is part of the PRIMARY KEY **
9th int True if column is [AUTOINCREMENT] **
**
)^ ** ** ^The memory pointed to by the character pointers returned for the ** declaration type and collation sequence is valid until the next ** call to any SQLite API function. ** ** ^If the specified table is actually a view, an [error code] is returned. ** ** ^If the specified column is "rowid", "oid" or "_rowid_" and the table ** is not a [WITHOUT ROWID] table and an ** [INTEGER PRIMARY KEY] column has been explicitly declared, then the output ** parameters are set for the explicitly declared column. ^(If there is no ** [INTEGER PRIMARY KEY] column, then the outputs ** for the [rowid] are set as follows: ** **
**     data type: "INTEGER"
**     collation sequence: "BINARY"
**     not null: 0
**     primary key: 1
**     auto increment: 0
** 
)^ ** ** ^This function causes all database schemas to be read from disk and ** parsed, if that has not already been done, and returns an error if ** any errors are encountered while loading the schema. */ SQLITE_API int sqlite3_table_column_metadata( sqlite3 *db, /* Connection handle */ const char *zDbName, /* Database name or NULL */ const char *zTableName, /* Table name */ const char *zColumnName, /* Column name */ char const **pzDataType, /* OUTPUT: Declared data type */ char const **pzCollSeq, /* OUTPUT: Collation sequence name */ int *pNotNull, /* OUTPUT: True if NOT NULL constraint exists */ int *pPrimaryKey, /* OUTPUT: True if column part of PK */ int *pAutoinc /* OUTPUT: True if column is auto-increment */ ); /* ** CAPI3REF: Load An Extension ** METHOD: sqlite3 ** ** ^This interface loads an SQLite extension library from the named file. ** ** ^The sqlite3_load_extension() interface attempts to load an ** [SQLite extension] library contained in the file zFile. If ** the file cannot be loaded directly, attempts are made to load ** with various operating-system specific extensions added. ** So for example, if "samplelib" cannot be loaded, then names like ** "samplelib.so" or "samplelib.dylib" or "samplelib.dll" might ** be tried also. ** ** ^The entry point is zProc. ** ^(zProc may be 0, in which case SQLite will try to come up with an ** entry point name on its own. It first tries "sqlite3_extension_init". ** If that does not work, it constructs a name "sqlite3_X_init" where the ** X is consists of the lower-case equivalent of all ASCII alphabetic ** characters in the filename from the last "/" to the first following ** "." and omitting any initial "lib".)^ ** ^The sqlite3_load_extension() interface returns ** [SQLITE_OK] on success and [SQLITE_ERROR] if something goes wrong. ** ^If an error occurs and pzErrMsg is not 0, then the ** [sqlite3_load_extension()] interface shall attempt to ** fill *pzErrMsg with error message text stored in memory ** obtained from [sqlite3_malloc()]. The calling function ** should free this memory by calling [sqlite3_free()]. ** ** ^Extension loading must be enabled using ** [sqlite3_enable_load_extension()] or ** [sqlite3_db_config](db,[SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION],1,NULL) ** prior to calling this API, ** otherwise an error will be returned. ** ** Security warning: It is recommended that the ** [SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION] method be used to enable only this ** interface. The use of the [sqlite3_enable_load_extension()] interface ** should be avoided. This will keep the SQL function [load_extension()] ** disabled and prevent SQL injections from giving attackers ** access to extension loading capabilities. ** ** See also the [load_extension() SQL function]. */ SQLITE_API int sqlite3_load_extension( sqlite3 *db, /* Load the extension into this database connection */ const char *zFile, /* Name of the shared library containing extension */ const char *zProc, /* Entry point. Derived from zFile if 0 */ char **pzErrMsg /* Put error message here if not 0 */ ); /* ** CAPI3REF: Enable Or Disable Extension Loading ** METHOD: sqlite3 ** ** ^So as not to open security holes in older applications that are ** unprepared to deal with [extension loading], and as a means of disabling ** [extension loading] while evaluating user-entered SQL, the following API ** is provided to turn the [sqlite3_load_extension()] mechanism on and off. ** ** ^Extension loading is off by default. ** ^Call the sqlite3_enable_load_extension() routine with onoff==1 ** to turn extension loading on and call it with onoff==0 to turn ** it back off again. ** ** ^This interface enables or disables both the C-API ** [sqlite3_load_extension()] and the SQL function [load_extension()]. ** ^(Use [sqlite3_db_config](db,[SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION],..) ** to enable or disable only the C-API.)^ ** ** Security warning: It is recommended that extension loading ** be disabled using the [SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION] method ** rather than this interface, so the [load_extension()] SQL function ** remains disabled. This will prevent SQL injections from giving attackers ** access to extension loading capabilities. */ SQLITE_API int sqlite3_enable_load_extension(sqlite3 *db, int onoff); /* ** CAPI3REF: Automatically Load Statically Linked Extensions ** ** ^This interface causes the xEntryPoint() function to be invoked for ** each new [database connection] that is created. The idea here is that ** xEntryPoint() is the entry point for a statically linked [SQLite extension] ** that is to be automatically loaded into all new database connections. ** ** ^(Even though the function prototype shows that xEntryPoint() takes ** no arguments and returns void, SQLite invokes xEntryPoint() with three ** arguments and expects an integer result as if the signature of the ** entry point where as follows: ** **
**    int xEntryPoint(
**      sqlite3 *db,
**      const char **pzErrMsg,
**      const struct sqlite3_api_routines *pThunk
**    );
** 
)^ ** ** If the xEntryPoint routine encounters an error, it should make *pzErrMsg ** point to an appropriate error message (obtained from [sqlite3_mprintf()]) ** and return an appropriate [error code]. ^SQLite ensures that *pzErrMsg ** is NULL before calling the xEntryPoint(). ^SQLite will invoke ** [sqlite3_free()] on *pzErrMsg after xEntryPoint() returns. ^If any ** xEntryPoint() returns an error, the [sqlite3_open()], [sqlite3_open16()], ** or [sqlite3_open_v2()] call that provoked the xEntryPoint() will fail. ** ** ^Calling sqlite3_auto_extension(X) with an entry point X that is already ** on the list of automatic extensions is a harmless no-op. ^No entry point ** will be called more than once for each database connection that is opened. ** ** See also: [sqlite3_reset_auto_extension()] ** and [sqlite3_cancel_auto_extension()] */ SQLITE_API int sqlite3_auto_extension(void(*xEntryPoint)(void)); /* ** CAPI3REF: Cancel Automatic Extension Loading ** ** ^The [sqlite3_cancel_auto_extension(X)] interface unregisters the ** initialization routine X that was registered using a prior call to ** [sqlite3_auto_extension(X)]. ^The [sqlite3_cancel_auto_extension(X)] ** routine returns 1 if initialization routine X was successfully ** unregistered and it returns 0 if X was not on the list of initialization ** routines. */ SQLITE_API int sqlite3_cancel_auto_extension(void(*xEntryPoint)(void)); /* ** CAPI3REF: Reset Automatic Extension Loading ** ** ^This interface disables all automatic extensions previously ** registered using [sqlite3_auto_extension()]. */ SQLITE_API void sqlite3_reset_auto_extension(void); /* ** The interface to the virtual-table mechanism is currently considered ** to be experimental. The interface might change in incompatible ways. ** If this is a problem for you, do not use the interface at this time. ** ** When the virtual-table mechanism stabilizes, we will declare the ** interface fixed, support it indefinitely, and remove this comment. */ /* ** Structures used by the virtual table interface */ typedef struct sqlite3_vtab sqlite3_vtab; typedef struct sqlite3_index_info sqlite3_index_info; typedef struct sqlite3_vtab_cursor sqlite3_vtab_cursor; typedef struct sqlite3_module sqlite3_module; /* ** CAPI3REF: Virtual Table Object ** KEYWORDS: sqlite3_module {virtual table module} ** ** This structure, sometimes called a "virtual table module", ** defines the implementation of a [virtual tables]. ** This structure consists mostly of methods for the module. ** ** ^A virtual table module is created by filling in a persistent ** instance of this structure and passing a pointer to that instance ** to [sqlite3_create_module()] or [sqlite3_create_module_v2()]. ** ^The registration remains valid until it is replaced by a different ** module or until the [database connection] closes. The content ** of this structure must not change while it is registered with ** any database connection. */ struct sqlite3_module { int iVersion; int (*xCreate)(sqlite3*, void *pAux, int argc, const char *const*argv, sqlite3_vtab **ppVTab, char**); int (*xConnect)(sqlite3*, void *pAux, int argc, const char *const*argv, sqlite3_vtab **ppVTab, char**); int (*xBestIndex)(sqlite3_vtab *pVTab, sqlite3_index_info*); int (*xDisconnect)(sqlite3_vtab *pVTab); int (*xDestroy)(sqlite3_vtab *pVTab); int (*xOpen)(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor); int (*xClose)(sqlite3_vtab_cursor*); int (*xFilter)(sqlite3_vtab_cursor*, int idxNum, const char *idxStr, int argc, sqlite3_value **argv); int (*xNext)(sqlite3_vtab_cursor*); int (*xEof)(sqlite3_vtab_cursor*); int (*xColumn)(sqlite3_vtab_cursor*, sqlite3_context*, int); int (*xRowid)(sqlite3_vtab_cursor*, sqlite3_int64 *pRowid); int (*xUpdate)(sqlite3_vtab *, int, sqlite3_value **, sqlite3_int64 *); int (*xBegin)(sqlite3_vtab *pVTab); int (*xSync)(sqlite3_vtab *pVTab); int (*xCommit)(sqlite3_vtab *pVTab); int (*xRollback)(sqlite3_vtab *pVTab); int (*xFindFunction)(sqlite3_vtab *pVtab, int nArg, const char *zName, void (**pxFunc)(sqlite3_context*,int,sqlite3_value**), void **ppArg); int (*xRename)(sqlite3_vtab *pVtab, const char *zNew); /* The methods above are in version 1 of the sqlite_module object. Those ** below are for version 2 and greater. */ int (*xSavepoint)(sqlite3_vtab *pVTab, int); int (*xRelease)(sqlite3_vtab *pVTab, int); int (*xRollbackTo)(sqlite3_vtab *pVTab, int); }; /* ** CAPI3REF: Virtual Table Indexing Information ** KEYWORDS: sqlite3_index_info ** ** The sqlite3_index_info structure and its substructures is used as part ** of the [virtual table] interface to ** pass information into and receive the reply from the [xBestIndex] ** method of a [virtual table module]. The fields under **Inputs** are the ** inputs to xBestIndex and are read-only. xBestIndex inserts its ** results into the **Outputs** fields. ** ** ^(The aConstraint[] array records WHERE clause constraints of the form: ** **
column OP expr
** ** where OP is =, <, <=, >, or >=.)^ ^(The particular operator is ** stored in aConstraint[].op using one of the ** [SQLITE_INDEX_CONSTRAINT_EQ | SQLITE_INDEX_CONSTRAINT_ values].)^ ** ^(The index of the column is stored in ** aConstraint[].iColumn.)^ ^(aConstraint[].usable is TRUE if the ** expr on the right-hand side can be evaluated (and thus the constraint ** is usable) and false if it cannot.)^ ** ** ^The optimizer automatically inverts terms of the form "expr OP column" ** and makes other simplifications to the WHERE clause in an attempt to ** get as many WHERE clause terms into the form shown above as possible. ** ^The aConstraint[] array only reports WHERE clause terms that are ** relevant to the particular virtual table being queried. ** ** ^Information about the ORDER BY clause is stored in aOrderBy[]. ** ^Each term of aOrderBy records a column of the ORDER BY clause. ** ** The colUsed field indicates which columns of the virtual table may be ** required by the current scan. Virtual table columns are numbered from ** zero in the order in which they appear within the CREATE TABLE statement ** passed to sqlite3_declare_vtab(). For the first 63 columns (columns 0-62), ** the corresponding bit is set within the colUsed mask if the column may be ** required by SQLite. If the table has at least 64 columns and any column ** to the right of the first 63 is required, then bit 63 of colUsed is also ** set. In other words, column iCol may be required if the expression ** (colUsed & ((sqlite3_uint64)1 << (iCol>=63 ? 63 : iCol))) evaluates to ** non-zero. ** ** The [xBestIndex] method must fill aConstraintUsage[] with information ** about what parameters to pass to xFilter. ^If argvIndex>0 then ** the right-hand side of the corresponding aConstraint[] is evaluated ** and becomes the argvIndex-th entry in argv. ^(If aConstraintUsage[].omit ** is true, then the constraint is assumed to be fully handled by the ** virtual table and is not checked again by SQLite.)^ ** ** ^The idxNum and idxPtr values are recorded and passed into the ** [xFilter] method. ** ^[sqlite3_free()] is used to free idxPtr if and only if ** needToFreeIdxPtr is true. ** ** ^The orderByConsumed means that output from [xFilter]/[xNext] will occur in ** the correct order to satisfy the ORDER BY clause so that no separate ** sorting step is required. ** ** ^The estimatedCost value is an estimate of the cost of a particular ** strategy. A cost of N indicates that the cost of the strategy is similar ** to a linear scan of an SQLite table with N rows. A cost of log(N) ** indicates that the expense of the operation is similar to that of a ** binary search on a unique indexed field of an SQLite table with N rows. ** ** ^The estimatedRows value is an estimate of the number of rows that ** will be returned by the strategy. ** ** The xBestIndex method may optionally populate the idxFlags field with a ** mask of SQLITE_INDEX_SCAN_* flags. Currently there is only one such flag - ** SQLITE_INDEX_SCAN_UNIQUE. If the xBestIndex method sets this flag, SQLite ** assumes that the strategy may visit at most one row. ** ** Additionally, if xBestIndex sets the SQLITE_INDEX_SCAN_UNIQUE flag, then ** SQLite also assumes that if a call to the xUpdate() method is made as ** part of the same statement to delete or update a virtual table row and the ** implementation returns SQLITE_CONSTRAINT, then there is no need to rollback ** any database changes. In other words, if the xUpdate() returns ** SQLITE_CONSTRAINT, the database contents must be exactly as they were ** before xUpdate was called. By contrast, if SQLITE_INDEX_SCAN_UNIQUE is not ** set and xUpdate returns SQLITE_CONSTRAINT, any database changes made by ** the xUpdate method are automatically rolled back by SQLite. ** ** IMPORTANT: The estimatedRows field was added to the sqlite3_index_info ** structure for SQLite [version 3.8.2] ([dateof:3.8.2]). ** If a virtual table extension is ** used with an SQLite version earlier than 3.8.2, the results of attempting ** to read or write the estimatedRows field are undefined (but are likely ** to included crashing the application). The estimatedRows field should ** therefore only be used if [sqlite3_libversion_number()] returns a ** value greater than or equal to 3008002. Similarly, the idxFlags field ** was added for [version 3.9.0] ([dateof:3.9.0]). ** It may therefore only be used if ** sqlite3_libversion_number() returns a value greater than or equal to ** 3009000. */ struct sqlite3_index_info { /* Inputs */ int nConstraint; /* Number of entries in aConstraint */ struct sqlite3_index_constraint { int iColumn; /* Column constrained. -1 for ROWID */ unsigned char op; /* Constraint operator */ unsigned char usable; /* True if this constraint is usable */ int iTermOffset; /* Used internally - xBestIndex should ignore */ } *aConstraint; /* Table of WHERE clause constraints */ int nOrderBy; /* Number of terms in the ORDER BY clause */ struct sqlite3_index_orderby { int iColumn; /* Column number */ unsigned char desc; /* True for DESC. False for ASC. */ } *aOrderBy; /* The ORDER BY clause */ /* Outputs */ struct sqlite3_index_constraint_usage { int argvIndex; /* if >0, constraint is part of argv to xFilter */ unsigned char omit; /* Do not code a test for this constraint */ } *aConstraintUsage; int idxNum; /* Number used to identify the index */ char *idxStr; /* String, possibly obtained from sqlite3_malloc */ int needToFreeIdxStr; /* Free idxStr using sqlite3_free() if true */ int orderByConsumed; /* True if output is already ordered */ double estimatedCost; /* Estimated cost of using this index */ /* Fields below are only available in SQLite 3.8.2 and later */ sqlite3_int64 estimatedRows; /* Estimated number of rows returned */ /* Fields below are only available in SQLite 3.9.0 and later */ int idxFlags; /* Mask of SQLITE_INDEX_SCAN_* flags */ /* Fields below are only available in SQLite 3.10.0 and later */ sqlite3_uint64 colUsed; /* Input: Mask of columns used by statement */ }; /* ** CAPI3REF: Virtual Table Scan Flags */ #define SQLITE_INDEX_SCAN_UNIQUE 1 /* Scan visits at most 1 row */ /* ** CAPI3REF: Virtual Table Constraint Operator Codes ** ** These macros defined the allowed values for the ** [sqlite3_index_info].aConstraint[].op field. Each value represents ** an operator that is part of a constraint term in the wHERE clause of ** a query that uses a [virtual table]. */ #define SQLITE_INDEX_CONSTRAINT_EQ 2 #define SQLITE_INDEX_CONSTRAINT_GT 4 #define SQLITE_INDEX_CONSTRAINT_LE 8 #define SQLITE_INDEX_CONSTRAINT_LT 16 #define SQLITE_INDEX_CONSTRAINT_GE 32 #define SQLITE_INDEX_CONSTRAINT_MATCH 64 #define SQLITE_INDEX_CONSTRAINT_LIKE 65 #define SQLITE_INDEX_CONSTRAINT_GLOB 66 #define SQLITE_INDEX_CONSTRAINT_REGEXP 67 /* ** CAPI3REF: Register A Virtual Table Implementation ** METHOD: sqlite3 ** ** ^These routines are used to register a new [virtual table module] name. ** ^Module names must be registered before ** creating a new [virtual table] using the module and before using a ** preexisting [virtual table] for the module. ** ** ^The module name is registered on the [database connection] specified ** by the first parameter. ^The name of the module is given by the ** second parameter. ^The third parameter is a pointer to ** the implementation of the [virtual table module]. ^The fourth ** parameter is an arbitrary client data pointer that is passed through ** into the [xCreate] and [xConnect] methods of the virtual table module ** when a new virtual table is be being created or reinitialized. ** ** ^The sqlite3_create_module_v2() interface has a fifth parameter which ** is a pointer to a destructor for the pClientData. ^SQLite will ** invoke the destructor function (if it is not NULL) when SQLite ** no longer needs the pClientData pointer. ^The destructor will also ** be invoked if the call to sqlite3_create_module_v2() fails. ** ^The sqlite3_create_module() ** interface is equivalent to sqlite3_create_module_v2() with a NULL ** destructor. */ SQLITE_API int sqlite3_create_module( sqlite3 *db, /* SQLite connection to register module with */ const char *zName, /* Name of the module */ const sqlite3_module *p, /* Methods for the module */ void *pClientData /* Client data for xCreate/xConnect */ ); SQLITE_API int sqlite3_create_module_v2( sqlite3 *db, /* SQLite connection to register module with */ const char *zName, /* Name of the module */ const sqlite3_module *p, /* Methods for the module */ void *pClientData, /* Client data for xCreate/xConnect */ void(*xDestroy)(void*) /* Module destructor function */ ); /* ** CAPI3REF: Virtual Table Instance Object ** KEYWORDS: sqlite3_vtab ** ** Every [virtual table module] implementation uses a subclass ** of this object to describe a particular instance ** of the [virtual table]. Each subclass will ** be tailored to the specific needs of the module implementation. ** The purpose of this superclass is to define certain fields that are ** common to all module implementations. ** ** ^Virtual tables methods can set an error message by assigning a ** string obtained from [sqlite3_mprintf()] to zErrMsg. The method should ** take care that any prior string is freed by a call to [sqlite3_free()] ** prior to assigning a new string to zErrMsg. ^After the error message ** is delivered up to the client application, the string will be automatically ** freed by sqlite3_free() and the zErrMsg field will be zeroed. */ struct sqlite3_vtab { const sqlite3_module *pModule; /* The module for this virtual table */ int nRef; /* Number of open cursors */ char *zErrMsg; /* Error message from sqlite3_mprintf() */ /* Virtual table implementations will typically add additional fields */ }; /* ** CAPI3REF: Virtual Table Cursor Object ** KEYWORDS: sqlite3_vtab_cursor {virtual table cursor} ** ** Every [virtual table module] implementation uses a subclass of the ** following structure to describe cursors that point into the ** [virtual table] and are used ** to loop through the virtual table. Cursors are created using the ** [sqlite3_module.xOpen | xOpen] method of the module and are destroyed ** by the [sqlite3_module.xClose | xClose] method. Cursors are used ** by the [xFilter], [xNext], [xEof], [xColumn], and [xRowid] methods ** of the module. Each module implementation will define ** the content of a cursor structure to suit its own needs. ** ** This superclass exists in order to define fields of the cursor that ** are common to all implementations. */ struct sqlite3_vtab_cursor { sqlite3_vtab *pVtab; /* Virtual table of this cursor */ /* Virtual table implementations will typically add additional fields */ }; /* ** CAPI3REF: Declare The Schema Of A Virtual Table ** ** ^The [xCreate] and [xConnect] methods of a ** [virtual table module] call this interface ** to declare the format (the names and datatypes of the columns) of ** the virtual tables they implement. */ SQLITE_API int sqlite3_declare_vtab(sqlite3*, const char *zSQL); /* ** CAPI3REF: Overload A Function For A Virtual Table ** METHOD: sqlite3 ** ** ^(Virtual tables can provide alternative implementations of functions ** using the [xFindFunction] method of the [virtual table module]. ** But global versions of those functions ** must exist in order to be overloaded.)^ ** ** ^(This API makes sure a global version of a function with a particular ** name and number of parameters exists. If no such function exists ** before this API is called, a new function is created.)^ ^The implementation ** of the new function always causes an exception to be thrown. So ** the new function is not good for anything by itself. Its only ** purpose is to be a placeholder function that can be overloaded ** by a [virtual table]. */ SQLITE_API int sqlite3_overload_function(sqlite3*, const char *zFuncName, int nArg); /* ** The interface to the virtual-table mechanism defined above (back up ** to a comment remarkably similar to this one) is currently considered ** to be experimental. The interface might change in incompatible ways. ** If this is a problem for you, do not use the interface at this time. ** ** When the virtual-table mechanism stabilizes, we will declare the ** interface fixed, support it indefinitely, and remove this comment. */ /* ** CAPI3REF: A Handle To An Open BLOB ** KEYWORDS: {BLOB handle} {BLOB handles} ** ** An instance of this object represents an open BLOB on which ** [sqlite3_blob_open | incremental BLOB I/O] can be performed. ** ^Objects of this type are created by [sqlite3_blob_open()] ** and destroyed by [sqlite3_blob_close()]. ** ^The [sqlite3_blob_read()] and [sqlite3_blob_write()] interfaces ** can be used to read or write small subsections of the BLOB. ** ^The [sqlite3_blob_bytes()] interface returns the size of the BLOB in bytes. */ typedef struct sqlite3_blob sqlite3_blob; /* ** CAPI3REF: Open A BLOB For Incremental I/O ** METHOD: sqlite3 ** CONSTRUCTOR: sqlite3_blob ** ** ^(This interfaces opens a [BLOB handle | handle] to the BLOB located ** in row iRow, column zColumn, table zTable in database zDb; ** in other words, the same BLOB that would be selected by: ** **
**     SELECT zColumn FROM zDb.zTable WHERE [rowid] = iRow;
** 
)^ ** ** ^(Parameter zDb is not the filename that contains the database, but ** rather the symbolic name of the database. For attached databases, this is ** the name that appears after the AS keyword in the [ATTACH] statement. ** For the main database file, the database name is "main". For TEMP ** tables, the database name is "temp".)^ ** ** ^If the flags parameter is non-zero, then the BLOB is opened for read ** and write access. ^If the flags parameter is zero, the BLOB is opened for ** read-only access. ** ** ^(On success, [SQLITE_OK] is returned and the new [BLOB handle] is stored ** in *ppBlob. Otherwise an [error code] is returned and, unless the error ** code is SQLITE_MISUSE, *ppBlob is set to NULL.)^ ^This means that, provided ** the API is not misused, it is always safe to call [sqlite3_blob_close()] ** on *ppBlob after this function it returns. ** ** This function fails with SQLITE_ERROR if any of the following are true: **
    **
  • ^(Database zDb does not exist)^, **
  • ^(Table zTable does not exist within database zDb)^, **
  • ^(Table zTable is a WITHOUT ROWID table)^, **
  • ^(Column zColumn does not exist)^, **
  • ^(Row iRow is not present in the table)^, **
  • ^(The specified column of row iRow contains a value that is not ** a TEXT or BLOB value)^, **
  • ^(Column zColumn is part of an index, PRIMARY KEY or UNIQUE ** constraint and the blob is being opened for read/write access)^, **
  • ^([foreign key constraints | Foreign key constraints] are enabled, ** column zColumn is part of a [child key] definition and the blob is ** being opened for read/write access)^. **
** ** ^Unless it returns SQLITE_MISUSE, this function sets the ** [database connection] error code and message accessible via ** [sqlite3_errcode()] and [sqlite3_errmsg()] and related functions. ** ** ** ^(If the row that a BLOB handle points to is modified by an ** [UPDATE], [DELETE], or by [ON CONFLICT] side-effects ** then the BLOB handle is marked as "expired". ** This is true if any column of the row is changed, even a column ** other than the one the BLOB handle is open on.)^ ** ^Calls to [sqlite3_blob_read()] and [sqlite3_blob_write()] for ** an expired BLOB handle fail with a return code of [SQLITE_ABORT]. ** ^(Changes written into a BLOB prior to the BLOB expiring are not ** rolled back by the expiration of the BLOB. Such changes will eventually ** commit if the transaction continues to completion.)^ ** ** ^Use the [sqlite3_blob_bytes()] interface to determine the size of ** the opened blob. ^The size of a blob may not be changed by this ** interface. Use the [UPDATE] SQL command to change the size of a ** blob. ** ** ^The [sqlite3_bind_zeroblob()] and [sqlite3_result_zeroblob()] interfaces ** and the built-in [zeroblob] SQL function may be used to create a ** zero-filled blob to read or write using the incremental-blob interface. ** ** To avoid a resource leak, every open [BLOB handle] should eventually ** be released by a call to [sqlite3_blob_close()]. */ SQLITE_API int sqlite3_blob_open( sqlite3*, const char *zDb, const char *zTable, const char *zColumn, sqlite3_int64 iRow, int flags, sqlite3_blob **ppBlob ); /* ** CAPI3REF: Move a BLOB Handle to a New Row ** METHOD: sqlite3_blob ** ** ^This function is used to move an existing blob handle so that it points ** to a different row of the same database table. ^The new row is identified ** by the rowid value passed as the second argument. Only the row can be ** changed. ^The database, table and column on which the blob handle is open ** remain the same. Moving an existing blob handle to a new row can be ** faster than closing the existing handle and opening a new one. ** ** ^(The new row must meet the same criteria as for [sqlite3_blob_open()] - ** it must exist and there must be either a blob or text value stored in ** the nominated column.)^ ^If the new row is not present in the table, or if ** it does not contain a blob or text value, or if another error occurs, an ** SQLite error code is returned and the blob handle is considered aborted. ** ^All subsequent calls to [sqlite3_blob_read()], [sqlite3_blob_write()] or ** [sqlite3_blob_reopen()] on an aborted blob handle immediately return ** SQLITE_ABORT. ^Calling [sqlite3_blob_bytes()] on an aborted blob handle ** always returns zero. ** ** ^This function sets the database handle error code and message. */ SQLITE_API int sqlite3_blob_reopen(sqlite3_blob *, sqlite3_int64); /* ** CAPI3REF: Close A BLOB Handle ** DESTRUCTOR: sqlite3_blob ** ** ^This function closes an open [BLOB handle]. ^(The BLOB handle is closed ** unconditionally. Even if this routine returns an error code, the ** handle is still closed.)^ ** ** ^If the blob handle being closed was opened for read-write access, and if ** the database is in auto-commit mode and there are no other open read-write ** blob handles or active write statements, the current transaction is ** committed. ^If an error occurs while committing the transaction, an error ** code is returned and the transaction rolled back. ** ** Calling this function with an argument that is not a NULL pointer or an ** open blob handle results in undefined behaviour. ^Calling this routine ** with a null pointer (such as would be returned by a failed call to ** [sqlite3_blob_open()]) is a harmless no-op. ^Otherwise, if this function ** is passed a valid open blob handle, the values returned by the ** sqlite3_errcode() and sqlite3_errmsg() functions are set before returning. */ SQLITE_API int sqlite3_blob_close(sqlite3_blob *); /* ** CAPI3REF: Return The Size Of An Open BLOB ** METHOD: sqlite3_blob ** ** ^Returns the size in bytes of the BLOB accessible via the ** successfully opened [BLOB handle] in its only argument. ^The ** incremental blob I/O routines can only read or overwriting existing ** blob content; they cannot change the size of a blob. ** ** This routine only works on a [BLOB handle] which has been created ** by a prior successful call to [sqlite3_blob_open()] and which has not ** been closed by [sqlite3_blob_close()]. Passing any other pointer in ** to this routine results in undefined and probably undesirable behavior. */ SQLITE_API int sqlite3_blob_bytes(sqlite3_blob *); /* ** CAPI3REF: Read Data From A BLOB Incrementally ** METHOD: sqlite3_blob ** ** ^(This function is used to read data from an open [BLOB handle] into a ** caller-supplied buffer. N bytes of data are copied into buffer Z ** from the open BLOB, starting at offset iOffset.)^ ** ** ^If offset iOffset is less than N bytes from the end of the BLOB, ** [SQLITE_ERROR] is returned and no data is read. ^If N or iOffset is ** less than zero, [SQLITE_ERROR] is returned and no data is read. ** ^The size of the blob (and hence the maximum value of N+iOffset) ** can be determined using the [sqlite3_blob_bytes()] interface. ** ** ^An attempt to read from an expired [BLOB handle] fails with an ** error code of [SQLITE_ABORT]. ** ** ^(On success, sqlite3_blob_read() returns SQLITE_OK. ** Otherwise, an [error code] or an [extended error code] is returned.)^ ** ** This routine only works on a [BLOB handle] which has been created ** by a prior successful call to [sqlite3_blob_open()] and which has not ** been closed by [sqlite3_blob_close()]. Passing any other pointer in ** to this routine results in undefined and probably undesirable behavior. ** ** See also: [sqlite3_blob_write()]. */ SQLITE_API int sqlite3_blob_read(sqlite3_blob *, void *Z, int N, int iOffset); /* ** CAPI3REF: Write Data Into A BLOB Incrementally ** METHOD: sqlite3_blob ** ** ^(This function is used to write data into an open [BLOB handle] from a ** caller-supplied buffer. N bytes of data are copied from the buffer Z ** into the open BLOB, starting at offset iOffset.)^ ** ** ^(On success, sqlite3_blob_write() returns SQLITE_OK. ** Otherwise, an [error code] or an [extended error code] is returned.)^ ** ^Unless SQLITE_MISUSE is returned, this function sets the ** [database connection] error code and message accessible via ** [sqlite3_errcode()] and [sqlite3_errmsg()] and related functions. ** ** ^If the [BLOB handle] passed as the first argument was not opened for ** writing (the flags parameter to [sqlite3_blob_open()] was zero), ** this function returns [SQLITE_READONLY]. ** ** This function may only modify the contents of the BLOB; it is ** not possible to increase the size of a BLOB using this API. ** ^If offset iOffset is less than N bytes from the end of the BLOB, ** [SQLITE_ERROR] is returned and no data is written. The size of the ** BLOB (and hence the maximum value of N+iOffset) can be determined ** using the [sqlite3_blob_bytes()] interface. ^If N or iOffset are less ** than zero [SQLITE_ERROR] is returned and no data is written. ** ** ^An attempt to write to an expired [BLOB handle] fails with an ** error code of [SQLITE_ABORT]. ^Writes to the BLOB that occurred ** before the [BLOB handle] expired are not rolled back by the ** expiration of the handle, though of course those changes might ** have been overwritten by the statement that expired the BLOB handle ** or by other independent statements. ** ** This routine only works on a [BLOB handle] which has been created ** by a prior successful call to [sqlite3_blob_open()] and which has not ** been closed by [sqlite3_blob_close()]. Passing any other pointer in ** to this routine results in undefined and probably undesirable behavior. ** ** See also: [sqlite3_blob_read()]. */ SQLITE_API int sqlite3_blob_write(sqlite3_blob *, const void *z, int n, int iOffset); /* ** CAPI3REF: Virtual File System Objects ** ** A virtual filesystem (VFS) is an [sqlite3_vfs] object ** that SQLite uses to interact ** with the underlying operating system. Most SQLite builds come with a ** single default VFS that is appropriate for the host computer. ** New VFSes can be registered and existing VFSes can be unregistered. ** The following interfaces are provided. ** ** ^The sqlite3_vfs_find() interface returns a pointer to a VFS given its name. ** ^Names are case sensitive. ** ^Names are zero-terminated UTF-8 strings. ** ^If there is no match, a NULL pointer is returned. ** ^If zVfsName is NULL then the default VFS is returned. ** ** ^New VFSes are registered with sqlite3_vfs_register(). ** ^Each new VFS becomes the default VFS if the makeDflt flag is set. ** ^The same VFS can be registered multiple times without injury. ** ^To make an existing VFS into the default VFS, register it again ** with the makeDflt flag set. If two different VFSes with the ** same name are registered, the behavior is undefined. If a ** VFS is registered with a name that is NULL or an empty string, ** then the behavior is undefined. ** ** ^Unregister a VFS with the sqlite3_vfs_unregister() interface. ** ^(If the default VFS is unregistered, another VFS is chosen as ** the default. The choice for the new VFS is arbitrary.)^ */ SQLITE_API sqlite3_vfs *sqlite3_vfs_find(const char *zVfsName); SQLITE_API int sqlite3_vfs_register(sqlite3_vfs*, int makeDflt); SQLITE_API int sqlite3_vfs_unregister(sqlite3_vfs*); /* ** CAPI3REF: Mutexes ** ** The SQLite core uses these routines for thread ** synchronization. Though they are intended for internal ** use by SQLite, code that links against SQLite is ** permitted to use any of these routines. ** ** The SQLite source code contains multiple implementations ** of these mutex routines. An appropriate implementation ** is selected automatically at compile-time. The following ** implementations are available in the SQLite core: ** **
    **
  • SQLITE_MUTEX_PTHREADS **
  • SQLITE_MUTEX_W32 **
  • SQLITE_MUTEX_NOOP **
** ** The SQLITE_MUTEX_NOOP implementation is a set of routines ** that does no real locking and is appropriate for use in ** a single-threaded application. The SQLITE_MUTEX_PTHREADS and ** SQLITE_MUTEX_W32 implementations are appropriate for use on Unix ** and Windows. ** ** If SQLite is compiled with the SQLITE_MUTEX_APPDEF preprocessor ** macro defined (with "-DSQLITE_MUTEX_APPDEF=1"), then no mutex ** implementation is included with the library. In this case the ** application must supply a custom mutex implementation using the ** [SQLITE_CONFIG_MUTEX] option of the sqlite3_config() function ** before calling sqlite3_initialize() or any other public sqlite3_ ** function that calls sqlite3_initialize(). ** ** ^The sqlite3_mutex_alloc() routine allocates a new ** mutex and returns a pointer to it. ^The sqlite3_mutex_alloc() ** routine returns NULL if it is unable to allocate the requested ** mutex. The argument to sqlite3_mutex_alloc() must one of these ** integer constants: ** **
    **
  • SQLITE_MUTEX_FAST **
  • SQLITE_MUTEX_RECURSIVE **
  • SQLITE_MUTEX_STATIC_MASTER **
  • SQLITE_MUTEX_STATIC_MEM **
  • SQLITE_MUTEX_STATIC_OPEN **
  • SQLITE_MUTEX_STATIC_PRNG **
  • SQLITE_MUTEX_STATIC_LRU **
  • SQLITE_MUTEX_STATIC_PMEM **
  • SQLITE_MUTEX_STATIC_APP1 **
  • SQLITE_MUTEX_STATIC_APP2 **
  • SQLITE_MUTEX_STATIC_APP3 **
  • SQLITE_MUTEX_STATIC_VFS1 **
  • SQLITE_MUTEX_STATIC_VFS2 **
  • SQLITE_MUTEX_STATIC_VFS3 **
** ** ^The first two constants (SQLITE_MUTEX_FAST and SQLITE_MUTEX_RECURSIVE) ** cause sqlite3_mutex_alloc() to create ** a new mutex. ^The new mutex is recursive when SQLITE_MUTEX_RECURSIVE ** is used but not necessarily so when SQLITE_MUTEX_FAST is used. ** The mutex implementation does not need to make a distinction ** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does ** not want to. SQLite will only request a recursive mutex in ** cases where it really needs one. If a faster non-recursive mutex ** implementation is available on the host platform, the mutex subsystem ** might return such a mutex in response to SQLITE_MUTEX_FAST. ** ** ^The other allowed parameters to sqlite3_mutex_alloc() (anything other ** than SQLITE_MUTEX_FAST and SQLITE_MUTEX_RECURSIVE) each return ** a pointer to a static preexisting mutex. ^Nine static mutexes are ** used by the current version of SQLite. Future versions of SQLite ** may add additional static mutexes. Static mutexes are for internal ** use by SQLite only. Applications that use SQLite mutexes should ** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or ** SQLITE_MUTEX_RECURSIVE. ** ** ^Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST ** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc() ** returns a different mutex on every call. ^For the static ** mutex types, the same mutex is returned on every call that has ** the same type number. ** ** ^The sqlite3_mutex_free() routine deallocates a previously ** allocated dynamic mutex. Attempting to deallocate a static ** mutex results in undefined behavior. ** ** ^The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt ** to enter a mutex. ^If another thread is already within the mutex, ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return ** SQLITE_BUSY. ^The sqlite3_mutex_try() interface returns [SQLITE_OK] ** upon successful entry. ^(Mutexes created using ** SQLITE_MUTEX_RECURSIVE can be entered multiple times by the same thread. ** In such cases, the ** mutex must be exited an equal number of times before another thread ** can enter.)^ If the same thread tries to enter any mutex other ** than an SQLITE_MUTEX_RECURSIVE more than once, the behavior is undefined. ** ** ^(Some systems (for example, Windows 95) do not support the operation ** implemented by sqlite3_mutex_try(). On those systems, sqlite3_mutex_try() ** will always return SQLITE_BUSY. The SQLite core only ever uses ** sqlite3_mutex_try() as an optimization so this is acceptable ** behavior.)^ ** ** ^The sqlite3_mutex_leave() routine exits a mutex that was ** previously entered by the same thread. The behavior ** is undefined if the mutex is not currently entered by the ** calling thread or is not currently allocated. ** ** ^If the argument to sqlite3_mutex_enter(), sqlite3_mutex_try(), or ** sqlite3_mutex_leave() is a NULL pointer, then all three routines ** behave as no-ops. ** ** See also: [sqlite3_mutex_held()] and [sqlite3_mutex_notheld()]. */ SQLITE_API sqlite3_mutex *sqlite3_mutex_alloc(int); SQLITE_API void sqlite3_mutex_free(sqlite3_mutex*); SQLITE_API void sqlite3_mutex_enter(sqlite3_mutex*); SQLITE_API int sqlite3_mutex_try(sqlite3_mutex*); SQLITE_API void sqlite3_mutex_leave(sqlite3_mutex*); /* ** CAPI3REF: Mutex Methods Object ** ** An instance of this structure defines the low-level routines ** used to allocate and use mutexes. ** ** Usually, the default mutex implementations provided by SQLite are ** sufficient, however the application has the option of substituting a custom ** implementation for specialized deployments or systems for which SQLite ** does not provide a suitable implementation. In this case, the application ** creates and populates an instance of this structure to pass ** to sqlite3_config() along with the [SQLITE_CONFIG_MUTEX] option. ** Additionally, an instance of this structure can be used as an ** output variable when querying the system for the current mutex ** implementation, using the [SQLITE_CONFIG_GETMUTEX] option. ** ** ^The xMutexInit method defined by this structure is invoked as ** part of system initialization by the sqlite3_initialize() function. ** ^The xMutexInit routine is called by SQLite exactly once for each ** effective call to [sqlite3_initialize()]. ** ** ^The xMutexEnd method defined by this structure is invoked as ** part of system shutdown by the sqlite3_shutdown() function. The ** implementation of this method is expected to release all outstanding ** resources obtained by the mutex methods implementation, especially ** those obtained by the xMutexInit method. ^The xMutexEnd() ** interface is invoked exactly once for each call to [sqlite3_shutdown()]. ** ** ^(The remaining seven methods defined by this structure (xMutexAlloc, ** xMutexFree, xMutexEnter, xMutexTry, xMutexLeave, xMutexHeld and ** xMutexNotheld) implement the following interfaces (respectively): ** **
    **
  • [sqlite3_mutex_alloc()]
  • **
  • [sqlite3_mutex_free()]
  • **
  • [sqlite3_mutex_enter()]
  • **
  • [sqlite3_mutex_try()]
  • **
  • [sqlite3_mutex_leave()]
  • **
  • [sqlite3_mutex_held()]
  • **
  • [sqlite3_mutex_notheld()]
  • **
)^ ** ** The only difference is that the public sqlite3_XXX functions enumerated ** above silently ignore any invocations that pass a NULL pointer instead ** of a valid mutex handle. The implementations of the methods defined ** by this structure are not required to handle this case, the results ** of passing a NULL pointer instead of a valid mutex handle are undefined ** (i.e. it is acceptable to provide an implementation that segfaults if ** it is passed a NULL pointer). ** ** The xMutexInit() method must be threadsafe. It must be harmless to ** invoke xMutexInit() multiple times within the same process and without ** intervening calls to xMutexEnd(). Second and subsequent calls to ** xMutexInit() must be no-ops. ** ** xMutexInit() must not use SQLite memory allocation ([sqlite3_malloc()] ** and its associates). Similarly, xMutexAlloc() must not use SQLite memory ** allocation for a static mutex. ^However xMutexAlloc() may use SQLite ** memory allocation for a fast or recursive mutex. ** ** ^SQLite will invoke the xMutexEnd() method when [sqlite3_shutdown()] is ** called, but only if the prior call to xMutexInit returned SQLITE_OK. ** If xMutexInit fails in any way, it is expected to clean up after itself ** prior to returning. */ typedef struct sqlite3_mutex_methods sqlite3_mutex_methods; struct sqlite3_mutex_methods { int (*xMutexInit)(void); int (*xMutexEnd)(void); sqlite3_mutex *(*xMutexAlloc)(int); void (*xMutexFree)(sqlite3_mutex *); void (*xMutexEnter)(sqlite3_mutex *); int (*xMutexTry)(sqlite3_mutex *); void (*xMutexLeave)(sqlite3_mutex *); int (*xMutexHeld)(sqlite3_mutex *); int (*xMutexNotheld)(sqlite3_mutex *); }; /* ** CAPI3REF: Mutex Verification Routines ** ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routines ** are intended for use inside assert() statements. The SQLite core ** never uses these routines except inside an assert() and applications ** are advised to follow the lead of the core. The SQLite core only ** provides implementations for these routines when it is compiled ** with the SQLITE_DEBUG flag. External mutex implementations ** are only required to provide these routines if SQLITE_DEBUG is ** defined and if NDEBUG is not defined. ** ** These routines should return true if the mutex in their argument ** is held or not held, respectively, by the calling thread. ** ** The implementation is not required to provide versions of these ** routines that actually work. If the implementation does not provide working ** versions of these routines, it should at least provide stubs that always ** return true so that one does not get spurious assertion failures. ** ** If the argument to sqlite3_mutex_held() is a NULL pointer then ** the routine should return 1. This seems counter-intuitive since ** clearly the mutex cannot be held if it does not exist. But ** the reason the mutex does not exist is because the build is not ** using mutexes. And we do not want the assert() containing the ** call to sqlite3_mutex_held() to fail, so a non-zero return is ** the appropriate thing to do. The sqlite3_mutex_notheld() ** interface should also return 1 when given a NULL pointer. */ #ifndef NDEBUG SQLITE_API int sqlite3_mutex_held(sqlite3_mutex*); SQLITE_API int sqlite3_mutex_notheld(sqlite3_mutex*); #endif /* ** CAPI3REF: Mutex Types ** ** The [sqlite3_mutex_alloc()] interface takes a single argument ** which is one of these integer constants. ** ** The set of static mutexes may change from one SQLite release to the ** next. Applications that override the built-in mutex logic must be ** prepared to accommodate additional static mutexes. */ #define SQLITE_MUTEX_FAST 0 #define SQLITE_MUTEX_RECURSIVE 1 #define SQLITE_MUTEX_STATIC_MASTER 2 #define SQLITE_MUTEX_STATIC_MEM 3 /* sqlite3_malloc() */ #define SQLITE_MUTEX_STATIC_MEM2 4 /* NOT USED */ #define SQLITE_MUTEX_STATIC_OPEN 4 /* sqlite3BtreeOpen() */ #define SQLITE_MUTEX_STATIC_PRNG 5 /* sqlite3_randomness() */ #define SQLITE_MUTEX_STATIC_LRU 6 /* lru page list */ #define SQLITE_MUTEX_STATIC_LRU2 7 /* NOT USED */ #define SQLITE_MUTEX_STATIC_PMEM 7 /* sqlite3PageMalloc() */ #define SQLITE_MUTEX_STATIC_APP1 8 /* For use by application */ #define SQLITE_MUTEX_STATIC_APP2 9 /* For use by application */ #define SQLITE_MUTEX_STATIC_APP3 10 /* For use by application */ #define SQLITE_MUTEX_STATIC_VFS1 11 /* For use by built-in VFS */ #define SQLITE_MUTEX_STATIC_VFS2 12 /* For use by extension VFS */ #define SQLITE_MUTEX_STATIC_VFS3 13 /* For use by application VFS */ /* ** CAPI3REF: Retrieve the mutex for a database connection ** METHOD: sqlite3 ** ** ^This interface returns a pointer the [sqlite3_mutex] object that ** serializes access to the [database connection] given in the argument ** when the [threading mode] is Serialized. ** ^If the [threading mode] is Single-thread or Multi-thread then this ** routine returns a NULL pointer. */ SQLITE_API sqlite3_mutex *sqlite3_db_mutex(sqlite3*); /* ** CAPI3REF: Low-Level Control Of Database Files ** METHOD: sqlite3 ** ** ^The [sqlite3_file_control()] interface makes a direct call to the ** xFileControl method for the [sqlite3_io_methods] object associated ** with a particular database identified by the second argument. ^The ** name of the database is "main" for the main database or "temp" for the ** TEMP database, or the name that appears after the AS keyword for ** databases that are added using the [ATTACH] SQL command. ** ^A NULL pointer can be used in place of "main" to refer to the ** main database file. ** ^The third and fourth parameters to this routine ** are passed directly through to the second and third parameters of ** the xFileControl method. ^The return value of the xFileControl ** method becomes the return value of this routine. ** ** ^The SQLITE_FCNTL_FILE_POINTER value for the op parameter causes ** a pointer to the underlying [sqlite3_file] object to be written into ** the space pointed to by the 4th parameter. ^The SQLITE_FCNTL_FILE_POINTER ** case is a short-circuit path which does not actually invoke the ** underlying sqlite3_io_methods.xFileControl method. ** ** ^If the second parameter (zDbName) does not match the name of any ** open database file, then SQLITE_ERROR is returned. ^This error ** code is not remembered and will not be recalled by [sqlite3_errcode()] ** or [sqlite3_errmsg()]. The underlying xFileControl method might ** also return SQLITE_ERROR. There is no way to distinguish between ** an incorrect zDbName and an SQLITE_ERROR return from the underlying ** xFileControl method. ** ** See also: [SQLITE_FCNTL_LOCKSTATE] */ SQLITE_API int sqlite3_file_control(sqlite3*, const char *zDbName, int op, void*); /* ** CAPI3REF: Testing Interface ** ** ^The sqlite3_test_control() interface is used to read out internal ** state of SQLite and to inject faults into SQLite for testing ** purposes. ^The first parameter is an operation code that determines ** the number, meaning, and operation of all subsequent parameters. ** ** This interface is not for use by applications. It exists solely ** for verifying the correct operation of the SQLite library. Depending ** on how the SQLite library is compiled, this interface might not exist. ** ** The details of the operation codes, their meanings, the parameters ** they take, and what they do are all subject to change without notice. ** Unlike most of the SQLite API, this function is not guaranteed to ** operate consistently from one release to the next. */ SQLITE_API int sqlite3_test_control(int op, ...); /* ** CAPI3REF: Testing Interface Operation Codes ** ** These constants are the valid operation code parameters used ** as the first argument to [sqlite3_test_control()]. ** ** These parameters and their meanings are subject to change ** without notice. These values are for testing purposes only. ** Applications should not use any of these parameters or the ** [sqlite3_test_control()] interface. */ #define SQLITE_TESTCTRL_FIRST 5 #define SQLITE_TESTCTRL_PRNG_SAVE 5 #define SQLITE_TESTCTRL_PRNG_RESTORE 6 #define SQLITE_TESTCTRL_PRNG_RESET 7 #define SQLITE_TESTCTRL_BITVEC_TEST 8 #define SQLITE_TESTCTRL_FAULT_INSTALL 9 #define SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS 10 #define SQLITE_TESTCTRL_PENDING_BYTE 11 #define SQLITE_TESTCTRL_ASSERT 12 #define SQLITE_TESTCTRL_ALWAYS 13 #define SQLITE_TESTCTRL_RESERVE 14 #define SQLITE_TESTCTRL_OPTIMIZATIONS 15 #define SQLITE_TESTCTRL_ISKEYWORD 16 #define SQLITE_TESTCTRL_SCRATCHMALLOC 17 #define SQLITE_TESTCTRL_LOCALTIME_FAULT 18 #define SQLITE_TESTCTRL_EXPLAIN_STMT 19 /* NOT USED */ #define SQLITE_TESTCTRL_ONCE_RESET_THRESHOLD 19 #define SQLITE_TESTCTRL_NEVER_CORRUPT 20 #define SQLITE_TESTCTRL_VDBE_COVERAGE 21 #define SQLITE_TESTCTRL_BYTEORDER 22 #define SQLITE_TESTCTRL_ISINIT 23 #define SQLITE_TESTCTRL_SORTER_MMAP 24 #define SQLITE_TESTCTRL_IMPOSTER 25 #define SQLITE_TESTCTRL_LAST 25 /* ** CAPI3REF: SQLite Runtime Status ** ** ^These interfaces are used to retrieve runtime status information ** about the performance of SQLite, and optionally to reset various ** highwater marks. ^The first argument is an integer code for ** the specific parameter to measure. ^(Recognized integer codes ** are of the form [status parameters | SQLITE_STATUS_...].)^ ** ^The current value of the parameter is returned into *pCurrent. ** ^The highest recorded value is returned in *pHighwater. ^If the ** resetFlag is true, then the highest record value is reset after ** *pHighwater is written. ^(Some parameters do not record the highest ** value. For those parameters ** nothing is written into *pHighwater and the resetFlag is ignored.)^ ** ^(Other parameters record only the highwater mark and not the current ** value. For these latter parameters nothing is written into *pCurrent.)^ ** ** ^The sqlite3_status() and sqlite3_status64() routines return ** SQLITE_OK on success and a non-zero [error code] on failure. ** ** If either the current value or the highwater mark is too large to ** be represented by a 32-bit integer, then the values returned by ** sqlite3_status() are undefined. ** ** See also: [sqlite3_db_status()] */ SQLITE_API int sqlite3_status(int op, int *pCurrent, int *pHighwater, int resetFlag); SQLITE_API int sqlite3_status64( int op, sqlite3_int64 *pCurrent, sqlite3_int64 *pHighwater, int resetFlag ); /* ** CAPI3REF: Status Parameters ** KEYWORDS: {status parameters} ** ** These integer constants designate various run-time status parameters ** that can be returned by [sqlite3_status()]. ** **
** [[SQLITE_STATUS_MEMORY_USED]] ^(
SQLITE_STATUS_MEMORY_USED
**
This parameter is the current amount of memory checked out ** using [sqlite3_malloc()], either directly or indirectly. The ** figure includes calls made to [sqlite3_malloc()] by the application ** and internal memory usage by the SQLite library. Scratch memory ** controlled by [SQLITE_CONFIG_SCRATCH] and auxiliary page-cache ** memory controlled by [SQLITE_CONFIG_PAGECACHE] is not included in ** this parameter. The amount returned is the sum of the allocation ** sizes as reported by the xSize method in [sqlite3_mem_methods].
)^ ** ** [[SQLITE_STATUS_MALLOC_SIZE]] ^(
SQLITE_STATUS_MALLOC_SIZE
**
This parameter records the largest memory allocation request ** handed to [sqlite3_malloc()] or [sqlite3_realloc()] (or their ** internal equivalents). Only the value returned in the ** *pHighwater parameter to [sqlite3_status()] is of interest. ** The value written into the *pCurrent parameter is undefined.
)^ ** ** [[SQLITE_STATUS_MALLOC_COUNT]] ^(
SQLITE_STATUS_MALLOC_COUNT
**
This parameter records the number of separate memory allocations ** currently checked out.
)^ ** ** [[SQLITE_STATUS_PAGECACHE_USED]] ^(
SQLITE_STATUS_PAGECACHE_USED
**
This parameter returns the number of pages used out of the ** [pagecache memory allocator] that was configured using ** [SQLITE_CONFIG_PAGECACHE]. The ** value returned is in pages, not in bytes.
)^ ** ** [[SQLITE_STATUS_PAGECACHE_OVERFLOW]] ** ^(
SQLITE_STATUS_PAGECACHE_OVERFLOW
**
This parameter returns the number of bytes of page cache ** allocation which could not be satisfied by the [SQLITE_CONFIG_PAGECACHE] ** buffer and where forced to overflow to [sqlite3_malloc()]. The ** returned value includes allocations that overflowed because they ** where too large (they were larger than the "sz" parameter to ** [SQLITE_CONFIG_PAGECACHE]) and allocations that overflowed because ** no space was left in the page cache.
)^ ** ** [[SQLITE_STATUS_PAGECACHE_SIZE]] ^(
SQLITE_STATUS_PAGECACHE_SIZE
**
This parameter records the largest memory allocation request ** handed to [pagecache memory allocator]. Only the value returned in the ** *pHighwater parameter to [sqlite3_status()] is of interest. ** The value written into the *pCurrent parameter is undefined.
)^ ** ** [[SQLITE_STATUS_SCRATCH_USED]] ^(
SQLITE_STATUS_SCRATCH_USED
**
This parameter returns the number of allocations used out of the ** [scratch memory allocator] configured using ** [SQLITE_CONFIG_SCRATCH]. The value returned is in allocations, not ** in bytes. Since a single thread may only have one scratch allocation ** outstanding at time, this parameter also reports the number of threads ** using scratch memory at the same time.
)^ ** ** [[SQLITE_STATUS_SCRATCH_OVERFLOW]] ^(
SQLITE_STATUS_SCRATCH_OVERFLOW
**
This parameter returns the number of bytes of scratch memory ** allocation which could not be satisfied by the [SQLITE_CONFIG_SCRATCH] ** buffer and where forced to overflow to [sqlite3_malloc()]. The values ** returned include overflows because the requested allocation was too ** larger (that is, because the requested allocation was larger than the ** "sz" parameter to [SQLITE_CONFIG_SCRATCH]) and because no scratch buffer ** slots were available. **
)^ ** ** [[SQLITE_STATUS_SCRATCH_SIZE]] ^(
SQLITE_STATUS_SCRATCH_SIZE
**
This parameter records the largest memory allocation request ** handed to [scratch memory allocator]. Only the value returned in the ** *pHighwater parameter to [sqlite3_status()] is of interest. ** The value written into the *pCurrent parameter is undefined.
)^ ** ** [[SQLITE_STATUS_PARSER_STACK]] ^(
SQLITE_STATUS_PARSER_STACK
**
The *pHighwater parameter records the deepest parser stack. ** The *pCurrent value is undefined. The *pHighwater value is only ** meaningful if SQLite is compiled with [YYTRACKMAXSTACKDEPTH].
)^ **
** ** New status parameters may be added from time to time. */ #define SQLITE_STATUS_MEMORY_USED 0 #define SQLITE_STATUS_PAGECACHE_USED 1 #define SQLITE_STATUS_PAGECACHE_OVERFLOW 2 #define SQLITE_STATUS_SCRATCH_USED 3 #define SQLITE_STATUS_SCRATCH_OVERFLOW 4 #define SQLITE_STATUS_MALLOC_SIZE 5 #define SQLITE_STATUS_PARSER_STACK 6 #define SQLITE_STATUS_PAGECACHE_SIZE 7 #define SQLITE_STATUS_SCRATCH_SIZE 8 #define SQLITE_STATUS_MALLOC_COUNT 9 /* ** CAPI3REF: Database Connection Status ** METHOD: sqlite3 ** ** ^This interface is used to retrieve runtime status information ** about a single [database connection]. ^The first argument is the ** database connection object to be interrogated. ^The second argument ** is an integer constant, taken from the set of ** [SQLITE_DBSTATUS options], that ** determines the parameter to interrogate. The set of ** [SQLITE_DBSTATUS options] is likely ** to grow in future releases of SQLite. ** ** ^The current value of the requested parameter is written into *pCur ** and the highest instantaneous value is written into *pHiwtr. ^If ** the resetFlg is true, then the highest instantaneous value is ** reset back down to the current value. ** ** ^The sqlite3_db_status() routine returns SQLITE_OK on success and a ** non-zero [error code] on failure. ** ** See also: [sqlite3_status()] and [sqlite3_stmt_status()]. */ SQLITE_API int sqlite3_db_status(sqlite3*, int op, int *pCur, int *pHiwtr, int resetFlg); /* ** CAPI3REF: Status Parameters for database connections ** KEYWORDS: {SQLITE_DBSTATUS options} ** ** These constants are the available integer "verbs" that can be passed as ** the second argument to the [sqlite3_db_status()] interface. ** ** New verbs may be added in future releases of SQLite. Existing verbs ** might be discontinued. Applications should check the return code from ** [sqlite3_db_status()] to make sure that the call worked. ** The [sqlite3_db_status()] interface will return a non-zero error code ** if a discontinued or unsupported verb is invoked. ** **
** [[SQLITE_DBSTATUS_LOOKASIDE_USED]] ^(
SQLITE_DBSTATUS_LOOKASIDE_USED
**
This parameter returns the number of lookaside memory slots currently ** checked out.
)^ ** ** [[SQLITE_DBSTATUS_LOOKASIDE_HIT]] ^(
SQLITE_DBSTATUS_LOOKASIDE_HIT
**
This parameter returns the number malloc attempts that were ** satisfied using lookaside memory. Only the high-water value is meaningful; ** the current value is always zero.)^ ** ** [[SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE]] ** ^(
SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE
**
This parameter returns the number malloc attempts that might have ** been satisfied using lookaside memory but failed due to the amount of ** memory requested being larger than the lookaside slot size. ** Only the high-water value is meaningful; ** the current value is always zero.)^ ** ** [[SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL]] ** ^(
SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL
**
This parameter returns the number malloc attempts that might have ** been satisfied using lookaside memory but failed due to all lookaside ** memory already being in use. ** Only the high-water value is meaningful; ** the current value is always zero.)^ ** ** [[SQLITE_DBSTATUS_CACHE_USED]] ^(
SQLITE_DBSTATUS_CACHE_USED
**
This parameter returns the approximate number of bytes of heap ** memory used by all pager caches associated with the database connection.)^ ** ^The highwater mark associated with SQLITE_DBSTATUS_CACHE_USED is always 0. ** ** [[SQLITE_DBSTATUS_CACHE_USED_SHARED]] ** ^(
SQLITE_DBSTATUS_CACHE_USED_SHARED
**
This parameter is similar to DBSTATUS_CACHE_USED, except that if a ** pager cache is shared between two or more connections the bytes of heap ** memory used by that pager cache is divided evenly between the attached ** connections.)^ In other words, if none of the pager caches associated ** with the database connection are shared, this request returns the same ** value as DBSTATUS_CACHE_USED. Or, if one or more or the pager caches are ** shared, the value returned by this call will be smaller than that returned ** by DBSTATUS_CACHE_USED. ^The highwater mark associated with ** SQLITE_DBSTATUS_CACHE_USED_SHARED is always 0. ** ** [[SQLITE_DBSTATUS_SCHEMA_USED]] ^(
SQLITE_DBSTATUS_SCHEMA_USED
**
This parameter returns the approximate number of bytes of heap ** memory used to store the schema for all databases associated ** with the connection - main, temp, and any [ATTACH]-ed databases.)^ ** ^The full amount of memory used by the schemas is reported, even if the ** schema memory is shared with other database connections due to ** [shared cache mode] being enabled. ** ^The highwater mark associated with SQLITE_DBSTATUS_SCHEMA_USED is always 0. ** ** [[SQLITE_DBSTATUS_STMT_USED]] ^(
SQLITE_DBSTATUS_STMT_USED
**
This parameter returns the approximate number of bytes of heap ** and lookaside memory used by all prepared statements associated with ** the database connection.)^ ** ^The highwater mark associated with SQLITE_DBSTATUS_STMT_USED is always 0. **
** ** [[SQLITE_DBSTATUS_CACHE_HIT]] ^(
SQLITE_DBSTATUS_CACHE_HIT
**
This parameter returns the number of pager cache hits that have ** occurred.)^ ^The highwater mark associated with SQLITE_DBSTATUS_CACHE_HIT ** is always 0. **
** ** [[SQLITE_DBSTATUS_CACHE_MISS]] ^(
SQLITE_DBSTATUS_CACHE_MISS
**
This parameter returns the number of pager cache misses that have ** occurred.)^ ^The highwater mark associated with SQLITE_DBSTATUS_CACHE_MISS ** is always 0. **
** ** [[SQLITE_DBSTATUS_CACHE_WRITE]] ^(
SQLITE_DBSTATUS_CACHE_WRITE
**
This parameter returns the number of dirty cache entries that have ** been written to disk. Specifically, the number of pages written to the ** wal file in wal mode databases, or the number of pages written to the ** database file in rollback mode databases. Any pages written as part of ** transaction rollback or database recovery operations are not included. ** If an IO or other error occurs while writing a page to disk, the effect ** on subsequent SQLITE_DBSTATUS_CACHE_WRITE requests is undefined.)^ ^The ** highwater mark associated with SQLITE_DBSTATUS_CACHE_WRITE is always 0. **
** ** [[SQLITE_DBSTATUS_DEFERRED_FKS]] ^(
SQLITE_DBSTATUS_DEFERRED_FKS
**
This parameter returns zero for the current value if and only if ** all foreign key constraints (deferred or immediate) have been ** resolved.)^ ^The highwater mark is always 0. **
**
*/ #define SQLITE_DBSTATUS_LOOKASIDE_USED 0 #define SQLITE_DBSTATUS_CACHE_USED 1 #define SQLITE_DBSTATUS_SCHEMA_USED 2 #define SQLITE_DBSTATUS_STMT_USED 3 #define SQLITE_DBSTATUS_LOOKASIDE_HIT 4 #define SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE 5 #define SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL 6 #define SQLITE_DBSTATUS_CACHE_HIT 7 #define SQLITE_DBSTATUS_CACHE_MISS 8 #define SQLITE_DBSTATUS_CACHE_WRITE 9 #define SQLITE_DBSTATUS_DEFERRED_FKS 10 #define SQLITE_DBSTATUS_CACHE_USED_SHARED 11 #define SQLITE_DBSTATUS_MAX 11 /* Largest defined DBSTATUS */ /* ** CAPI3REF: Prepared Statement Status ** METHOD: sqlite3_stmt ** ** ^(Each prepared statement maintains various ** [SQLITE_STMTSTATUS counters] that measure the number ** of times it has performed specific operations.)^ These counters can ** be used to monitor the performance characteristics of the prepared ** statements. For example, if the number of table steps greatly exceeds ** the number of table searches or result rows, that would tend to indicate ** that the prepared statement is using a full table scan rather than ** an index. ** ** ^(This interface is used to retrieve and reset counter values from ** a [prepared statement]. The first argument is the prepared statement ** object to be interrogated. The second argument ** is an integer code for a specific [SQLITE_STMTSTATUS counter] ** to be interrogated.)^ ** ^The current value of the requested counter is returned. ** ^If the resetFlg is true, then the counter is reset to zero after this ** interface call returns. ** ** See also: [sqlite3_status()] and [sqlite3_db_status()]. */ SQLITE_API int sqlite3_stmt_status(sqlite3_stmt*, int op,int resetFlg); /* ** CAPI3REF: Status Parameters for prepared statements ** KEYWORDS: {SQLITE_STMTSTATUS counter} {SQLITE_STMTSTATUS counters} ** ** These preprocessor macros define integer codes that name counter ** values associated with the [sqlite3_stmt_status()] interface. ** The meanings of the various counters are as follows: ** **
** [[SQLITE_STMTSTATUS_FULLSCAN_STEP]]
SQLITE_STMTSTATUS_FULLSCAN_STEP
**
^This is the number of times that SQLite has stepped forward in ** a table as part of a full table scan. Large numbers for this counter ** may indicate opportunities for performance improvement through ** careful use of indices.
** ** [[SQLITE_STMTSTATUS_SORT]]
SQLITE_STMTSTATUS_SORT
**
^This is the number of sort operations that have occurred. ** A non-zero value in this counter may indicate an opportunity to ** improvement performance through careful use of indices.
** ** [[SQLITE_STMTSTATUS_AUTOINDEX]]
SQLITE_STMTSTATUS_AUTOINDEX
**
^This is the number of rows inserted into transient indices that ** were created automatically in order to help joins run faster. ** A non-zero value in this counter may indicate an opportunity to ** improvement performance by adding permanent indices that do not ** need to be reinitialized each time the statement is run.
** ** [[SQLITE_STMTSTATUS_VM_STEP]]
SQLITE_STMTSTATUS_VM_STEP
**
^This is the number of virtual machine operations executed ** by the prepared statement if that number is less than or equal ** to 2147483647. The number of virtual machine operations can be ** used as a proxy for the total work done by the prepared statement. ** If the number of virtual machine operations exceeds 2147483647 ** then the value returned by this statement status code is undefined. **
**
*/ #define SQLITE_STMTSTATUS_FULLSCAN_STEP 1 #define SQLITE_STMTSTATUS_SORT 2 #define SQLITE_STMTSTATUS_AUTOINDEX 3 #define SQLITE_STMTSTATUS_VM_STEP 4 /* ** CAPI3REF: Custom Page Cache Object ** ** The sqlite3_pcache type is opaque. It is implemented by ** the pluggable module. The SQLite core has no knowledge of ** its size or internal structure and never deals with the ** sqlite3_pcache object except by holding and passing pointers ** to the object. ** ** See [sqlite3_pcache_methods2] for additional information. */ typedef struct sqlite3_pcache sqlite3_pcache; /* ** CAPI3REF: Custom Page Cache Object ** ** The sqlite3_pcache_page object represents a single page in the ** page cache. The page cache will allocate instances of this ** object. Various methods of the page cache use pointers to instances ** of this object as parameters or as their return value. ** ** See [sqlite3_pcache_methods2] for additional information. */ typedef struct sqlite3_pcache_page sqlite3_pcache_page; struct sqlite3_pcache_page { void *pBuf; /* The content of the page */ void *pExtra; /* Extra information associated with the page */ }; /* ** CAPI3REF: Application Defined Page Cache. ** KEYWORDS: {page cache} ** ** ^(The [sqlite3_config]([SQLITE_CONFIG_PCACHE2], ...) interface can ** register an alternative page cache implementation by passing in an ** instance of the sqlite3_pcache_methods2 structure.)^ ** In many applications, most of the heap memory allocated by ** SQLite is used for the page cache. ** By implementing a ** custom page cache using this API, an application can better control ** the amount of memory consumed by SQLite, the way in which ** that memory is allocated and released, and the policies used to ** determine exactly which parts of a database file are cached and for ** how long. ** ** The alternative page cache mechanism is an ** extreme measure that is only needed by the most demanding applications. ** The built-in page cache is recommended for most uses. ** ** ^(The contents of the sqlite3_pcache_methods2 structure are copied to an ** internal buffer by SQLite within the call to [sqlite3_config]. Hence ** the application may discard the parameter after the call to ** [sqlite3_config()] returns.)^ ** ** [[the xInit() page cache method]] ** ^(The xInit() method is called once for each effective ** call to [sqlite3_initialize()])^ ** (usually only once during the lifetime of the process). ^(The xInit() ** method is passed a copy of the sqlite3_pcache_methods2.pArg value.)^ ** The intent of the xInit() method is to set up global data structures ** required by the custom page cache implementation. ** ^(If the xInit() method is NULL, then the ** built-in default page cache is used instead of the application defined ** page cache.)^ ** ** [[the xShutdown() page cache method]] ** ^The xShutdown() method is called by [sqlite3_shutdown()]. ** It can be used to clean up ** any outstanding resources before process shutdown, if required. ** ^The xShutdown() method may be NULL. ** ** ^SQLite automatically serializes calls to the xInit method, ** so the xInit method need not be threadsafe. ^The ** xShutdown method is only called from [sqlite3_shutdown()] so it does ** not need to be threadsafe either. All other methods must be threadsafe ** in multithreaded applications. ** ** ^SQLite will never invoke xInit() more than once without an intervening ** call to xShutdown(). ** ** [[the xCreate() page cache methods]] ** ^SQLite invokes the xCreate() method to construct a new cache instance. ** SQLite will typically create one cache instance for each open database file, ** though this is not guaranteed. ^The ** first parameter, szPage, is the size in bytes of the pages that must ** be allocated by the cache. ^szPage will always a power of two. ^The ** second parameter szExtra is a number of bytes of extra storage ** associated with each page cache entry. ^The szExtra parameter will ** a number less than 250. SQLite will use the ** extra szExtra bytes on each page to store metadata about the underlying ** database page on disk. The value passed into szExtra depends ** on the SQLite version, the target platform, and how SQLite was compiled. ** ^The third argument to xCreate(), bPurgeable, is true if the cache being ** created will be used to cache database pages of a file stored on disk, or ** false if it is used for an in-memory database. The cache implementation ** does not have to do anything special based with the value of bPurgeable; ** it is purely advisory. ^On a cache where bPurgeable is false, SQLite will ** never invoke xUnpin() except to deliberately delete a page. ** ^In other words, calls to xUnpin() on a cache with bPurgeable set to ** false will always have the "discard" flag set to true. ** ^Hence, a cache created with bPurgeable false will ** never contain any unpinned pages. ** ** [[the xCachesize() page cache method]] ** ^(The xCachesize() method may be called at any time by SQLite to set the ** suggested maximum cache-size (number of pages stored by) the cache ** instance passed as the first argument. This is the value configured using ** the SQLite "[PRAGMA cache_size]" command.)^ As with the bPurgeable ** parameter, the implementation is not required to do anything with this ** value; it is advisory only. ** ** [[the xPagecount() page cache methods]] ** The xPagecount() method must return the number of pages currently ** stored in the cache, both pinned and unpinned. ** ** [[the xFetch() page cache methods]] ** The xFetch() method locates a page in the cache and returns a pointer to ** an sqlite3_pcache_page object associated with that page, or a NULL pointer. ** The pBuf element of the returned sqlite3_pcache_page object will be a ** pointer to a buffer of szPage bytes used to store the content of a ** single database page. The pExtra element of sqlite3_pcache_page will be ** a pointer to the szExtra bytes of extra storage that SQLite has requested ** for each entry in the page cache. ** ** The page to be fetched is determined by the key. ^The minimum key value ** is 1. After it has been retrieved using xFetch, the page is considered ** to be "pinned". ** ** If the requested page is already in the page cache, then the page cache ** implementation must return a pointer to the page buffer with its content ** intact. If the requested page is not already in the cache, then the ** cache implementation should use the value of the createFlag ** parameter to help it determined what action to take: ** ** **
createFlag Behavior when page is not already in cache **
0 Do not allocate a new page. Return NULL. **
1 Allocate a new page if it easy and convenient to do so. ** Otherwise return NULL. **
2 Make every effort to allocate a new page. Only return ** NULL if allocating a new page is effectively impossible. **
** ** ^(SQLite will normally invoke xFetch() with a createFlag of 0 or 1. SQLite ** will only use a createFlag of 2 after a prior call with a createFlag of 1 ** failed.)^ In between the to xFetch() calls, SQLite may ** attempt to unpin one or more cache pages by spilling the content of ** pinned pages to disk and synching the operating system disk cache. ** ** [[the xUnpin() page cache method]] ** ^xUnpin() is called by SQLite with a pointer to a currently pinned page ** as its second argument. If the third parameter, discard, is non-zero, ** then the page must be evicted from the cache. ** ^If the discard parameter is ** zero, then the page may be discarded or retained at the discretion of ** page cache implementation. ^The page cache implementation ** may choose to evict unpinned pages at any time. ** ** The cache must not perform any reference counting. A single ** call to xUnpin() unpins the page regardless of the number of prior calls ** to xFetch(). ** ** [[the xRekey() page cache methods]] ** The xRekey() method is used to change the key value associated with the ** page passed as the second argument. If the cache ** previously contains an entry associated with newKey, it must be ** discarded. ^Any prior cache entry associated with newKey is guaranteed not ** to be pinned. ** ** When SQLite calls the xTruncate() method, the cache must discard all ** existing cache entries with page numbers (keys) greater than or equal ** to the value of the iLimit parameter passed to xTruncate(). If any ** of these pages are pinned, they are implicitly unpinned, meaning that ** they can be safely discarded. ** ** [[the xDestroy() page cache method]] ** ^The xDestroy() method is used to delete a cache allocated by xCreate(). ** All resources associated with the specified cache should be freed. ^After ** calling the xDestroy() method, SQLite considers the [sqlite3_pcache*] ** handle invalid, and will not use it with any other sqlite3_pcache_methods2 ** functions. ** ** [[the xShrink() page cache method]] ** ^SQLite invokes the xShrink() method when it wants the page cache to ** free up as much of heap memory as possible. The page cache implementation ** is not obligated to free any memory, but well-behaved implementations should ** do their best. */ typedef struct sqlite3_pcache_methods2 sqlite3_pcache_methods2; struct sqlite3_pcache_methods2 { int iVersion; void *pArg; int (*xInit)(void*); void (*xShutdown)(void*); sqlite3_pcache *(*xCreate)(int szPage, int szExtra, int bPurgeable); void (*xCachesize)(sqlite3_pcache*, int nCachesize); int (*xPagecount)(sqlite3_pcache*); sqlite3_pcache_page *(*xFetch)(sqlite3_pcache*, unsigned key, int createFlag); void (*xUnpin)(sqlite3_pcache*, sqlite3_pcache_page*, int discard); void (*xRekey)(sqlite3_pcache*, sqlite3_pcache_page*, unsigned oldKey, unsigned newKey); void (*xTruncate)(sqlite3_pcache*, unsigned iLimit); void (*xDestroy)(sqlite3_pcache*); void (*xShrink)(sqlite3_pcache*); }; /* ** This is the obsolete pcache_methods object that has now been replaced ** by sqlite3_pcache_methods2. This object is not used by SQLite. It is ** retained in the header file for backwards compatibility only. */ typedef struct sqlite3_pcache_methods sqlite3_pcache_methods; struct sqlite3_pcache_methods { void *pArg; int (*xInit)(void*); void (*xShutdown)(void*); sqlite3_pcache *(*xCreate)(int szPage, int bPurgeable); void (*xCachesize)(sqlite3_pcache*, int nCachesize); int (*xPagecount)(sqlite3_pcache*); void *(*xFetch)(sqlite3_pcache*, unsigned key, int createFlag); void (*xUnpin)(sqlite3_pcache*, void*, int discard); void (*xRekey)(sqlite3_pcache*, void*, unsigned oldKey, unsigned newKey); void (*xTruncate)(sqlite3_pcache*, unsigned iLimit); void (*xDestroy)(sqlite3_pcache*); }; /* ** CAPI3REF: Online Backup Object ** ** The sqlite3_backup object records state information about an ongoing ** online backup operation. ^The sqlite3_backup object is created by ** a call to [sqlite3_backup_init()] and is destroyed by a call to ** [sqlite3_backup_finish()]. ** ** See Also: [Using the SQLite Online Backup API] */ typedef struct sqlite3_backup sqlite3_backup; /* ** CAPI3REF: Online Backup API. ** ** The backup API copies the content of one database into another. ** It is useful either for creating backups of databases or ** for copying in-memory databases to or from persistent files. ** ** See Also: [Using the SQLite Online Backup API] ** ** ^SQLite holds a write transaction open on the destination database file ** for the duration of the backup operation. ** ^The source database is read-locked only while it is being read; ** it is not locked continuously for the entire backup operation. ** ^Thus, the backup may be performed on a live source database without ** preventing other database connections from ** reading or writing to the source database while the backup is underway. ** ** ^(To perform a backup operation: **
    **
  1. sqlite3_backup_init() is called once to initialize the ** backup, **
  2. sqlite3_backup_step() is called one or more times to transfer ** the data between the two databases, and finally **
  3. sqlite3_backup_finish() is called to release all resources ** associated with the backup operation. **
)^ ** There should be exactly one call to sqlite3_backup_finish() for each ** successful call to sqlite3_backup_init(). ** ** [[sqlite3_backup_init()]] sqlite3_backup_init() ** ** ^The D and N arguments to sqlite3_backup_init(D,N,S,M) are the ** [database connection] associated with the destination database ** and the database name, respectively. ** ^The database name is "main" for the main database, "temp" for the ** temporary database, or the name specified after the AS keyword in ** an [ATTACH] statement for an attached database. ** ^The S and M arguments passed to ** sqlite3_backup_init(D,N,S,M) identify the [database connection] ** and database name of the source database, respectively. ** ^The source and destination [database connections] (parameters S and D) ** must be different or else sqlite3_backup_init(D,N,S,M) will fail with ** an error. ** ** ^A call to sqlite3_backup_init() will fail, returning NULL, if ** there is already a read or read-write transaction open on the ** destination database. ** ** ^If an error occurs within sqlite3_backup_init(D,N,S,M), then NULL is ** returned and an error code and error message are stored in the ** destination [database connection] D. ** ^The error code and message for the failed call to sqlite3_backup_init() ** can be retrieved using the [sqlite3_errcode()], [sqlite3_errmsg()], and/or ** [sqlite3_errmsg16()] functions. ** ^A successful call to sqlite3_backup_init() returns a pointer to an ** [sqlite3_backup] object. ** ^The [sqlite3_backup] object may be used with the sqlite3_backup_step() and ** sqlite3_backup_finish() functions to perform the specified backup ** operation. ** ** [[sqlite3_backup_step()]] sqlite3_backup_step() ** ** ^Function sqlite3_backup_step(B,N) will copy up to N pages between ** the source and destination databases specified by [sqlite3_backup] object B. ** ^If N is negative, all remaining source pages are copied. ** ^If sqlite3_backup_step(B,N) successfully copies N pages and there ** are still more pages to be copied, then the function returns [SQLITE_OK]. ** ^If sqlite3_backup_step(B,N) successfully finishes copying all pages ** from source to destination, then it returns [SQLITE_DONE]. ** ^If an error occurs while running sqlite3_backup_step(B,N), ** then an [error code] is returned. ^As well as [SQLITE_OK] and ** [SQLITE_DONE], a call to sqlite3_backup_step() may return [SQLITE_READONLY], ** [SQLITE_NOMEM], [SQLITE_BUSY], [SQLITE_LOCKED], or an ** [SQLITE_IOERR_ACCESS | SQLITE_IOERR_XXX] extended error code. ** ** ^(The sqlite3_backup_step() might return [SQLITE_READONLY] if **
    **
  1. the destination database was opened read-only, or **
  2. the destination database is using write-ahead-log journaling ** and the destination and source page sizes differ, or **
  3. the destination database is an in-memory database and the ** destination and source page sizes differ. **
)^ ** ** ^If sqlite3_backup_step() cannot obtain a required file-system lock, then ** the [sqlite3_busy_handler | busy-handler function] ** is invoked (if one is specified). ^If the ** busy-handler returns non-zero before the lock is available, then ** [SQLITE_BUSY] is returned to the caller. ^In this case the call to ** sqlite3_backup_step() can be retried later. ^If the source ** [database connection] ** is being used to write to the source database when sqlite3_backup_step() ** is called, then [SQLITE_LOCKED] is returned immediately. ^Again, in this ** case the call to sqlite3_backup_step() can be retried later on. ^(If ** [SQLITE_IOERR_ACCESS | SQLITE_IOERR_XXX], [SQLITE_NOMEM], or ** [SQLITE_READONLY] is returned, then ** there is no point in retrying the call to sqlite3_backup_step(). These ** errors are considered fatal.)^ The application must accept ** that the backup operation has failed and pass the backup operation handle ** to the sqlite3_backup_finish() to release associated resources. ** ** ^The first call to sqlite3_backup_step() obtains an exclusive lock ** on the destination file. ^The exclusive lock is not released until either ** sqlite3_backup_finish() is called or the backup operation is complete ** and sqlite3_backup_step() returns [SQLITE_DONE]. ^Every call to ** sqlite3_backup_step() obtains a [shared lock] on the source database that ** lasts for the duration of the sqlite3_backup_step() call. ** ^Because the source database is not locked between calls to ** sqlite3_backup_step(), the source database may be modified mid-way ** through the backup process. ^If the source database is modified by an ** external process or via a database connection other than the one being ** used by the backup operation, then the backup will be automatically ** restarted by the next call to sqlite3_backup_step(). ^If the source ** database is modified by the using the same database connection as is used ** by the backup operation, then the backup database is automatically ** updated at the same time. ** ** [[sqlite3_backup_finish()]] sqlite3_backup_finish() ** ** When sqlite3_backup_step() has returned [SQLITE_DONE], or when the ** application wishes to abandon the backup operation, the application ** should destroy the [sqlite3_backup] by passing it to sqlite3_backup_finish(). ** ^The sqlite3_backup_finish() interfaces releases all ** resources associated with the [sqlite3_backup] object. ** ^If sqlite3_backup_step() has not yet returned [SQLITE_DONE], then any ** active write-transaction on the destination database is rolled back. ** The [sqlite3_backup] object is invalid ** and may not be used following a call to sqlite3_backup_finish(). ** ** ^The value returned by sqlite3_backup_finish is [SQLITE_OK] if no ** sqlite3_backup_step() errors occurred, regardless or whether or not ** sqlite3_backup_step() completed. ** ^If an out-of-memory condition or IO error occurred during any prior ** sqlite3_backup_step() call on the same [sqlite3_backup] object, then ** sqlite3_backup_finish() returns the corresponding [error code]. ** ** ^A return of [SQLITE_BUSY] or [SQLITE_LOCKED] from sqlite3_backup_step() ** is not a permanent error and does not affect the return value of ** sqlite3_backup_finish(). ** ** [[sqlite3_backup_remaining()]] [[sqlite3_backup_pagecount()]] ** sqlite3_backup_remaining() and sqlite3_backup_pagecount() ** ** ^The sqlite3_backup_remaining() routine returns the number of pages still ** to be backed up at the conclusion of the most recent sqlite3_backup_step(). ** ^The sqlite3_backup_pagecount() routine returns the total number of pages ** in the source database at the conclusion of the most recent ** sqlite3_backup_step(). ** ^(The values returned by these functions are only updated by ** sqlite3_backup_step(). If the source database is modified in a way that ** changes the size of the source database or the number of pages remaining, ** those changes are not reflected in the output of sqlite3_backup_pagecount() ** and sqlite3_backup_remaining() until after the next ** sqlite3_backup_step().)^ ** ** Concurrent Usage of Database Handles ** ** ^The source [database connection] may be used by the application for other ** purposes while a backup operation is underway or being initialized. ** ^If SQLite is compiled and configured to support threadsafe database ** connections, then the source database connection may be used concurrently ** from within other threads. ** ** However, the application must guarantee that the destination ** [database connection] is not passed to any other API (by any thread) after ** sqlite3_backup_init() is called and before the corresponding call to ** sqlite3_backup_finish(). SQLite does not currently check to see ** if the application incorrectly accesses the destination [database connection] ** and so no error code is reported, but the operations may malfunction ** nevertheless. Use of the destination database connection while a ** backup is in progress might also also cause a mutex deadlock. ** ** If running in [shared cache mode], the application must ** guarantee that the shared cache used by the destination database ** is not accessed while the backup is running. In practice this means ** that the application must guarantee that the disk file being ** backed up to is not accessed by any connection within the process, ** not just the specific connection that was passed to sqlite3_backup_init(). ** ** The [sqlite3_backup] object itself is partially threadsafe. Multiple ** threads may safely make multiple concurrent calls to sqlite3_backup_step(). ** However, the sqlite3_backup_remaining() and sqlite3_backup_pagecount() ** APIs are not strictly speaking threadsafe. If they are invoked at the ** same time as another thread is invoking sqlite3_backup_step() it is ** possible that they return invalid values. */ SQLITE_API sqlite3_backup *sqlite3_backup_init( sqlite3 *pDest, /* Destination database handle */ const char *zDestName, /* Destination database name */ sqlite3 *pSource, /* Source database handle */ const char *zSourceName /* Source database name */ ); SQLITE_API int sqlite3_backup_step(sqlite3_backup *p, int nPage); SQLITE_API int sqlite3_backup_finish(sqlite3_backup *p); SQLITE_API int sqlite3_backup_remaining(sqlite3_backup *p); SQLITE_API int sqlite3_backup_pagecount(sqlite3_backup *p); /* ** CAPI3REF: Unlock Notification ** METHOD: sqlite3 ** ** ^When running in shared-cache mode, a database operation may fail with ** an [SQLITE_LOCKED] error if the required locks on the shared-cache or ** individual tables within the shared-cache cannot be obtained. See ** [SQLite Shared-Cache Mode] for a description of shared-cache locking. ** ^This API may be used to register a callback that SQLite will invoke ** when the connection currently holding the required lock relinquishes it. ** ^This API is only available if the library was compiled with the ** [SQLITE_ENABLE_UNLOCK_NOTIFY] C-preprocessor symbol defined. ** ** See Also: [Using the SQLite Unlock Notification Feature]. ** ** ^Shared-cache locks are released when a database connection concludes ** its current transaction, either by committing it or rolling it back. ** ** ^When a connection (known as the blocked connection) fails to obtain a ** shared-cache lock and SQLITE_LOCKED is returned to the caller, the ** identity of the database connection (the blocking connection) that ** has locked the required resource is stored internally. ^After an ** application receives an SQLITE_LOCKED error, it may call the ** sqlite3_unlock_notify() method with the blocked connection handle as ** the first argument to register for a callback that will be invoked ** when the blocking connections current transaction is concluded. ^The ** callback is invoked from within the [sqlite3_step] or [sqlite3_close] ** call that concludes the blocking connections transaction. ** ** ^(If sqlite3_unlock_notify() is called in a multi-threaded application, ** there is a chance that the blocking connection will have already ** concluded its transaction by the time sqlite3_unlock_notify() is invoked. ** If this happens, then the specified callback is invoked immediately, ** from within the call to sqlite3_unlock_notify().)^ ** ** ^If the blocked connection is attempting to obtain a write-lock on a ** shared-cache table, and more than one other connection currently holds ** a read-lock on the same table, then SQLite arbitrarily selects one of ** the other connections to use as the blocking connection. ** ** ^(There may be at most one unlock-notify callback registered by a ** blocked connection. If sqlite3_unlock_notify() is called when the ** blocked connection already has a registered unlock-notify callback, ** then the new callback replaces the old.)^ ^If sqlite3_unlock_notify() is ** called with a NULL pointer as its second argument, then any existing ** unlock-notify callback is canceled. ^The blocked connections ** unlock-notify callback may also be canceled by closing the blocked ** connection using [sqlite3_close()]. ** ** The unlock-notify callback is not reentrant. If an application invokes ** any sqlite3_xxx API functions from within an unlock-notify callback, a ** crash or deadlock may be the result. ** ** ^Unless deadlock is detected (see below), sqlite3_unlock_notify() always ** returns SQLITE_OK. ** ** Callback Invocation Details ** ** When an unlock-notify callback is registered, the application provides a ** single void* pointer that is passed to the callback when it is invoked. ** However, the signature of the callback function allows SQLite to pass ** it an array of void* context pointers. The first argument passed to ** an unlock-notify callback is a pointer to an array of void* pointers, ** and the second is the number of entries in the array. ** ** When a blocking connections transaction is concluded, there may be ** more than one blocked connection that has registered for an unlock-notify ** callback. ^If two or more such blocked connections have specified the ** same callback function, then instead of invoking the callback function ** multiple times, it is invoked once with the set of void* context pointers ** specified by the blocked connections bundled together into an array. ** This gives the application an opportunity to prioritize any actions ** related to the set of unblocked database connections. ** ** Deadlock Detection ** ** Assuming that after registering for an unlock-notify callback a ** database waits for the callback to be issued before taking any further ** action (a reasonable assumption), then using this API may cause the ** application to deadlock. For example, if connection X is waiting for ** connection Y's transaction to be concluded, and similarly connection ** Y is waiting on connection X's transaction, then neither connection ** will proceed and the system may remain deadlocked indefinitely. ** ** To avoid this scenario, the sqlite3_unlock_notify() performs deadlock ** detection. ^If a given call to sqlite3_unlock_notify() would put the ** system in a deadlocked state, then SQLITE_LOCKED is returned and no ** unlock-notify callback is registered. The system is said to be in ** a deadlocked state if connection A has registered for an unlock-notify ** callback on the conclusion of connection B's transaction, and connection ** B has itself registered for an unlock-notify callback when connection ** A's transaction is concluded. ^Indirect deadlock is also detected, so ** the system is also considered to be deadlocked if connection B has ** registered for an unlock-notify callback on the conclusion of connection ** C's transaction, where connection C is waiting on connection A. ^Any ** number of levels of indirection are allowed. ** ** The "DROP TABLE" Exception ** ** When a call to [sqlite3_step()] returns SQLITE_LOCKED, it is almost ** always appropriate to call sqlite3_unlock_notify(). There is however, ** one exception. When executing a "DROP TABLE" or "DROP INDEX" statement, ** SQLite checks if there are any currently executing SELECT statements ** that belong to the same connection. If there are, SQLITE_LOCKED is ** returned. In this case there is no "blocking connection", so invoking ** sqlite3_unlock_notify() results in the unlock-notify callback being ** invoked immediately. If the application then re-attempts the "DROP TABLE" ** or "DROP INDEX" query, an infinite loop might be the result. ** ** One way around this problem is to check the extended error code returned ** by an sqlite3_step() call. ^(If there is a blocking connection, then the ** extended error code is set to SQLITE_LOCKED_SHAREDCACHE. Otherwise, in ** the special "DROP TABLE/INDEX" case, the extended error code is just ** SQLITE_LOCKED.)^ */ SQLITE_API int sqlite3_unlock_notify( sqlite3 *pBlocked, /* Waiting connection */ void (*xNotify)(void **apArg, int nArg), /* Callback function to invoke */ void *pNotifyArg /* Argument to pass to xNotify */ ); /* ** CAPI3REF: String Comparison ** ** ^The [sqlite3_stricmp()] and [sqlite3_strnicmp()] APIs allow applications ** and extensions to compare the contents of two buffers containing UTF-8 ** strings in a case-independent fashion, using the same definition of "case ** independence" that SQLite uses internally when comparing identifiers. */ SQLITE_API int sqlite3_stricmp(const char *, const char *); SQLITE_API int sqlite3_strnicmp(const char *, const char *, int); /* ** CAPI3REF: String Globbing * ** ^The [sqlite3_strglob(P,X)] interface returns zero if and only if ** string X matches the [GLOB] pattern P. ** ^The definition of [GLOB] pattern matching used in ** [sqlite3_strglob(P,X)] is the same as for the "X GLOB P" operator in the ** SQL dialect understood by SQLite. ^The [sqlite3_strglob(P,X)] function ** is case sensitive. ** ** Note that this routine returns zero on a match and non-zero if the strings ** do not match, the same as [sqlite3_stricmp()] and [sqlite3_strnicmp()]. ** ** See also: [sqlite3_strlike()]. */ SQLITE_API int sqlite3_strglob(const char *zGlob, const char *zStr); /* ** CAPI3REF: String LIKE Matching * ** ^The [sqlite3_strlike(P,X,E)] interface returns zero if and only if ** string X matches the [LIKE] pattern P with escape character E. ** ^The definition of [LIKE] pattern matching used in ** [sqlite3_strlike(P,X,E)] is the same as for the "X LIKE P ESCAPE E" ** operator in the SQL dialect understood by SQLite. ^For "X LIKE P" without ** the ESCAPE clause, set the E parameter of [sqlite3_strlike(P,X,E)] to 0. ** ^As with the LIKE operator, the [sqlite3_strlike(P,X,E)] function is case ** insensitive - equivalent upper and lower case ASCII characters match ** one another. ** ** ^The [sqlite3_strlike(P,X,E)] function matches Unicode characters, though ** only ASCII characters are case folded. ** ** Note that this routine returns zero on a match and non-zero if the strings ** do not match, the same as [sqlite3_stricmp()] and [sqlite3_strnicmp()]. ** ** See also: [sqlite3_strglob()]. */ SQLITE_API int sqlite3_strlike(const char *zGlob, const char *zStr, unsigned int cEsc); /* ** CAPI3REF: Error Logging Interface ** ** ^The [sqlite3_log()] interface writes a message into the [error log] ** established by the [SQLITE_CONFIG_LOG] option to [sqlite3_config()]. ** ^If logging is enabled, the zFormat string and subsequent arguments are ** used with [sqlite3_snprintf()] to generate the final output string. ** ** The sqlite3_log() interface is intended for use by extensions such as ** virtual tables, collating functions, and SQL functions. While there is ** nothing to prevent an application from calling sqlite3_log(), doing so ** is considered bad form. ** ** The zFormat string must not be NULL. ** ** To avoid deadlocks and other threading problems, the sqlite3_log() routine ** will not use dynamically allocated memory. The log message is stored in ** a fixed-length buffer on the stack. If the log message is longer than ** a few hundred characters, it will be truncated to the length of the ** buffer. */ SQLITE_API void sqlite3_log(int iErrCode, const char *zFormat, ...); /* ** CAPI3REF: Write-Ahead Log Commit Hook ** METHOD: sqlite3 ** ** ^The [sqlite3_wal_hook()] function is used to register a callback that ** is invoked each time data is committed to a database in wal mode. ** ** ^(The callback is invoked by SQLite after the commit has taken place and ** the associated write-lock on the database released)^, so the implementation ** may read, write or [checkpoint] the database as required. ** ** ^The first parameter passed to the callback function when it is invoked ** is a copy of the third parameter passed to sqlite3_wal_hook() when ** registering the callback. ^The second is a copy of the database handle. ** ^The third parameter is the name of the database that was written to - ** either "main" or the name of an [ATTACH]-ed database. ^The fourth parameter ** is the number of pages currently in the write-ahead log file, ** including those that were just committed. ** ** The callback function should normally return [SQLITE_OK]. ^If an error ** code is returned, that error will propagate back up through the ** SQLite code base to cause the statement that provoked the callback ** to report an error, though the commit will have still occurred. If the ** callback returns [SQLITE_ROW] or [SQLITE_DONE], or if it returns a value ** that does not correspond to any valid SQLite error code, the results ** are undefined. ** ** A single database handle may have at most a single write-ahead log callback ** registered at one time. ^Calling [sqlite3_wal_hook()] replaces any ** previously registered write-ahead log callback. ^Note that the ** [sqlite3_wal_autocheckpoint()] interface and the ** [wal_autocheckpoint pragma] both invoke [sqlite3_wal_hook()] and will ** overwrite any prior [sqlite3_wal_hook()] settings. */ SQLITE_API void *sqlite3_wal_hook( sqlite3*, int(*)(void *,sqlite3*,const char*,int), void* ); /* ** CAPI3REF: Configure an auto-checkpoint ** METHOD: sqlite3 ** ** ^The [sqlite3_wal_autocheckpoint(D,N)] is a wrapper around ** [sqlite3_wal_hook()] that causes any database on [database connection] D ** to automatically [checkpoint] ** after committing a transaction if there are N or ** more frames in the [write-ahead log] file. ^Passing zero or ** a negative value as the nFrame parameter disables automatic ** checkpoints entirely. ** ** ^The callback registered by this function replaces any existing callback ** registered using [sqlite3_wal_hook()]. ^Likewise, registering a callback ** using [sqlite3_wal_hook()] disables the automatic checkpoint mechanism ** configured by this function. ** ** ^The [wal_autocheckpoint pragma] can be used to invoke this interface ** from SQL. ** ** ^Checkpoints initiated by this mechanism are ** [sqlite3_wal_checkpoint_v2|PASSIVE]. ** ** ^Every new [database connection] defaults to having the auto-checkpoint ** enabled with a threshold of 1000 or [SQLITE_DEFAULT_WAL_AUTOCHECKPOINT] ** pages. The use of this interface ** is only necessary if the default setting is found to be suboptimal ** for a particular application. */ SQLITE_API int sqlite3_wal_autocheckpoint(sqlite3 *db, int N); /* ** CAPI3REF: Checkpoint a database ** METHOD: sqlite3 ** ** ^(The sqlite3_wal_checkpoint(D,X) is equivalent to ** [sqlite3_wal_checkpoint_v2](D,X,[SQLITE_CHECKPOINT_PASSIVE],0,0).)^ ** ** In brief, sqlite3_wal_checkpoint(D,X) causes the content in the ** [write-ahead log] for database X on [database connection] D to be ** transferred into the database file and for the write-ahead log to ** be reset. See the [checkpointing] documentation for addition ** information. ** ** This interface used to be the only way to cause a checkpoint to ** occur. But then the newer and more powerful [sqlite3_wal_checkpoint_v2()] ** interface was added. This interface is retained for backwards ** compatibility and as a convenience for applications that need to manually ** start a callback but which do not need the full power (and corresponding ** complication) of [sqlite3_wal_checkpoint_v2()]. */ SQLITE_API int sqlite3_wal_checkpoint(sqlite3 *db, const char *zDb); /* ** CAPI3REF: Checkpoint a database ** METHOD: sqlite3 ** ** ^(The sqlite3_wal_checkpoint_v2(D,X,M,L,C) interface runs a checkpoint ** operation on database X of [database connection] D in mode M. Status ** information is written back into integers pointed to by L and C.)^ ** ^(The M parameter must be a valid [checkpoint mode]:)^ ** **
**
SQLITE_CHECKPOINT_PASSIVE
** ^Checkpoint as many frames as possible without waiting for any database ** readers or writers to finish, then sync the database file if all frames ** in the log were checkpointed. ^The [busy-handler callback] ** is never invoked in the SQLITE_CHECKPOINT_PASSIVE mode. ** ^On the other hand, passive mode might leave the checkpoint unfinished ** if there are concurrent readers or writers. ** **
SQLITE_CHECKPOINT_FULL
** ^This mode blocks (it invokes the ** [sqlite3_busy_handler|busy-handler callback]) until there is no ** database writer and all readers are reading from the most recent database ** snapshot. ^It then checkpoints all frames in the log file and syncs the ** database file. ^This mode blocks new database writers while it is pending, ** but new database readers are allowed to continue unimpeded. ** **
SQLITE_CHECKPOINT_RESTART
** ^This mode works the same way as SQLITE_CHECKPOINT_FULL with the addition ** that after checkpointing the log file it blocks (calls the ** [busy-handler callback]) ** until all readers are reading from the database file only. ^This ensures ** that the next writer will restart the log file from the beginning. ** ^Like SQLITE_CHECKPOINT_FULL, this mode blocks new ** database writer attempts while it is pending, but does not impede readers. ** **
SQLITE_CHECKPOINT_TRUNCATE
** ^This mode works the same way as SQLITE_CHECKPOINT_RESTART with the ** addition that it also truncates the log file to zero bytes just prior ** to a successful return. **
** ** ^If pnLog is not NULL, then *pnLog is set to the total number of frames in ** the log file or to -1 if the checkpoint could not run because ** of an error or because the database is not in [WAL mode]. ^If pnCkpt is not ** NULL,then *pnCkpt is set to the total number of checkpointed frames in the ** log file (including any that were already checkpointed before the function ** was called) or to -1 if the checkpoint could not run due to an error or ** because the database is not in WAL mode. ^Note that upon successful ** completion of an SQLITE_CHECKPOINT_TRUNCATE, the log file will have been ** truncated to zero bytes and so both *pnLog and *pnCkpt will be set to zero. ** ** ^All calls obtain an exclusive "checkpoint" lock on the database file. ^If ** any other process is running a checkpoint operation at the same time, the ** lock cannot be obtained and SQLITE_BUSY is returned. ^Even if there is a ** busy-handler configured, it will not be invoked in this case. ** ** ^The SQLITE_CHECKPOINT_FULL, RESTART and TRUNCATE modes also obtain the ** exclusive "writer" lock on the database file. ^If the writer lock cannot be ** obtained immediately, and a busy-handler is configured, it is invoked and ** the writer lock retried until either the busy-handler returns 0 or the lock ** is successfully obtained. ^The busy-handler is also invoked while waiting for ** database readers as described above. ^If the busy-handler returns 0 before ** the writer lock is obtained or while waiting for database readers, the ** checkpoint operation proceeds from that point in the same way as ** SQLITE_CHECKPOINT_PASSIVE - checkpointing as many frames as possible ** without blocking any further. ^SQLITE_BUSY is returned in this case. ** ** ^If parameter zDb is NULL or points to a zero length string, then the ** specified operation is attempted on all WAL databases [attached] to ** [database connection] db. In this case the ** values written to output parameters *pnLog and *pnCkpt are undefined. ^If ** an SQLITE_BUSY error is encountered when processing one or more of the ** attached WAL databases, the operation is still attempted on any remaining ** attached databases and SQLITE_BUSY is returned at the end. ^If any other ** error occurs while processing an attached database, processing is abandoned ** and the error code is returned to the caller immediately. ^If no error ** (SQLITE_BUSY or otherwise) is encountered while processing the attached ** databases, SQLITE_OK is returned. ** ** ^If database zDb is the name of an attached database that is not in WAL ** mode, SQLITE_OK is returned and both *pnLog and *pnCkpt set to -1. ^If ** zDb is not NULL (or a zero length string) and is not the name of any ** attached database, SQLITE_ERROR is returned to the caller. ** ** ^Unless it returns SQLITE_MISUSE, ** the sqlite3_wal_checkpoint_v2() interface ** sets the error information that is queried by ** [sqlite3_errcode()] and [sqlite3_errmsg()]. ** ** ^The [PRAGMA wal_checkpoint] command can be used to invoke this interface ** from SQL. */ SQLITE_API int sqlite3_wal_checkpoint_v2( sqlite3 *db, /* Database handle */ const char *zDb, /* Name of attached database (or NULL) */ int eMode, /* SQLITE_CHECKPOINT_* value */ int *pnLog, /* OUT: Size of WAL log in frames */ int *pnCkpt /* OUT: Total number of frames checkpointed */ ); /* ** CAPI3REF: Checkpoint Mode Values ** KEYWORDS: {checkpoint mode} ** ** These constants define all valid values for the "checkpoint mode" passed ** as the third parameter to the [sqlite3_wal_checkpoint_v2()] interface. ** See the [sqlite3_wal_checkpoint_v2()] documentation for details on the ** meaning of each of these checkpoint modes. */ #define SQLITE_CHECKPOINT_PASSIVE 0 /* Do as much as possible w/o blocking */ #define SQLITE_CHECKPOINT_FULL 1 /* Wait for writers, then checkpoint */ #define SQLITE_CHECKPOINT_RESTART 2 /* Like FULL but wait for for readers */ #define SQLITE_CHECKPOINT_TRUNCATE 3 /* Like RESTART but also truncate WAL */ /* ** CAPI3REF: Virtual Table Interface Configuration ** ** This function may be called by either the [xConnect] or [xCreate] method ** of a [virtual table] implementation to configure ** various facets of the virtual table interface. ** ** If this interface is invoked outside the context of an xConnect or ** xCreate virtual table method then the behavior is undefined. ** ** At present, there is only one option that may be configured using ** this function. (See [SQLITE_VTAB_CONSTRAINT_SUPPORT].) Further options ** may be added in the future. */ SQLITE_API int sqlite3_vtab_config(sqlite3*, int op, ...); /* ** CAPI3REF: Virtual Table Configuration Options ** ** These macros define the various options to the ** [sqlite3_vtab_config()] interface that [virtual table] implementations ** can use to customize and optimize their behavior. ** **
**
SQLITE_VTAB_CONSTRAINT_SUPPORT **
Calls of the form ** [sqlite3_vtab_config](db,SQLITE_VTAB_CONSTRAINT_SUPPORT,X) are supported, ** where X is an integer. If X is zero, then the [virtual table] whose ** [xCreate] or [xConnect] method invoked [sqlite3_vtab_config()] does not ** support constraints. In this configuration (which is the default) if ** a call to the [xUpdate] method returns [SQLITE_CONSTRAINT], then the entire ** statement is rolled back as if [ON CONFLICT | OR ABORT] had been ** specified as part of the users SQL statement, regardless of the actual ** ON CONFLICT mode specified. ** ** If X is non-zero, then the virtual table implementation guarantees ** that if [xUpdate] returns [SQLITE_CONSTRAINT], it will do so before ** any modifications to internal or persistent data structures have been made. ** If the [ON CONFLICT] mode is ABORT, FAIL, IGNORE or ROLLBACK, SQLite ** is able to roll back a statement or database transaction, and abandon ** or continue processing the current SQL statement as appropriate. ** If the ON CONFLICT mode is REPLACE and the [xUpdate] method returns ** [SQLITE_CONSTRAINT], SQLite handles this as if the ON CONFLICT mode ** had been ABORT. ** ** Virtual table implementations that are required to handle OR REPLACE ** must do so within the [xUpdate] method. If a call to the ** [sqlite3_vtab_on_conflict()] function indicates that the current ON ** CONFLICT policy is REPLACE, the virtual table implementation should ** silently replace the appropriate rows within the xUpdate callback and ** return SQLITE_OK. Or, if this is not possible, it may return ** SQLITE_CONSTRAINT, in which case SQLite falls back to OR ABORT ** constraint handling. **
*/ #define SQLITE_VTAB_CONSTRAINT_SUPPORT 1 /* ** CAPI3REF: Determine The Virtual Table Conflict Policy ** ** This function may only be called from within a call to the [xUpdate] method ** of a [virtual table] implementation for an INSERT or UPDATE operation. ^The ** value returned is one of [SQLITE_ROLLBACK], [SQLITE_IGNORE], [SQLITE_FAIL], ** [SQLITE_ABORT], or [SQLITE_REPLACE], according to the [ON CONFLICT] mode ** of the SQL statement that triggered the call to the [xUpdate] method of the ** [virtual table]. */ SQLITE_API int sqlite3_vtab_on_conflict(sqlite3 *); /* ** CAPI3REF: Conflict resolution modes ** KEYWORDS: {conflict resolution mode} ** ** These constants are returned by [sqlite3_vtab_on_conflict()] to ** inform a [virtual table] implementation what the [ON CONFLICT] mode ** is for the SQL statement being evaluated. ** ** Note that the [SQLITE_IGNORE] constant is also used as a potential ** return value from the [sqlite3_set_authorizer()] callback and that ** [SQLITE_ABORT] is also a [result code]. */ #define SQLITE_ROLLBACK 1 /* #define SQLITE_IGNORE 2 // Also used by sqlite3_authorizer() callback */ #define SQLITE_FAIL 3 /* #define SQLITE_ABORT 4 // Also an error code */ #define SQLITE_REPLACE 5 /* ** CAPI3REF: Prepared Statement Scan Status Opcodes ** KEYWORDS: {scanstatus options} ** ** The following constants can be used for the T parameter to the ** [sqlite3_stmt_scanstatus(S,X,T,V)] interface. Each constant designates a ** different metric for sqlite3_stmt_scanstatus() to return. ** ** When the value returned to V is a string, space to hold that string is ** managed by the prepared statement S and will be automatically freed when ** S is finalized. ** **
** [[SQLITE_SCANSTAT_NLOOP]]
SQLITE_SCANSTAT_NLOOP
**
^The [sqlite3_int64] variable pointed to by the T parameter will be ** set to the total number of times that the X-th loop has run.
** ** [[SQLITE_SCANSTAT_NVISIT]]
SQLITE_SCANSTAT_NVISIT
**
^The [sqlite3_int64] variable pointed to by the T parameter will be set ** to the total number of rows examined by all iterations of the X-th loop.
** ** [[SQLITE_SCANSTAT_EST]]
SQLITE_SCANSTAT_EST
**
^The "double" variable pointed to by the T parameter will be set to the ** query planner's estimate for the average number of rows output from each ** iteration of the X-th loop. If the query planner's estimates was accurate, ** then this value will approximate the quotient NVISIT/NLOOP and the ** product of this value for all prior loops with the same SELECTID will ** be the NLOOP value for the current loop. ** ** [[SQLITE_SCANSTAT_NAME]]
SQLITE_SCANSTAT_NAME
**
^The "const char *" variable pointed to by the T parameter will be set ** to a zero-terminated UTF-8 string containing the name of the index or table ** used for the X-th loop. ** ** [[SQLITE_SCANSTAT_EXPLAIN]]
SQLITE_SCANSTAT_EXPLAIN
**
^The "const char *" variable pointed to by the T parameter will be set ** to a zero-terminated UTF-8 string containing the [EXPLAIN QUERY PLAN] ** description for the X-th loop. ** ** [[SQLITE_SCANSTAT_SELECTID]]
SQLITE_SCANSTAT_SELECT
**
^The "int" variable pointed to by the T parameter will be set to the ** "select-id" for the X-th loop. The select-id identifies which query or ** subquery the loop is part of. The main query has a select-id of zero. ** The select-id is the same value as is output in the first column ** of an [EXPLAIN QUERY PLAN] query. **
*/ #define SQLITE_SCANSTAT_NLOOP 0 #define SQLITE_SCANSTAT_NVISIT 1 #define SQLITE_SCANSTAT_EST 2 #define SQLITE_SCANSTAT_NAME 3 #define SQLITE_SCANSTAT_EXPLAIN 4 #define SQLITE_SCANSTAT_SELECTID 5 /* ** CAPI3REF: Prepared Statement Scan Status ** METHOD: sqlite3_stmt ** ** This interface returns information about the predicted and measured ** performance for pStmt. Advanced applications can use this ** interface to compare the predicted and the measured performance and ** issue warnings and/or rerun [ANALYZE] if discrepancies are found. ** ** Since this interface is expected to be rarely used, it is only ** available if SQLite is compiled using the [SQLITE_ENABLE_STMT_SCANSTATUS] ** compile-time option. ** ** The "iScanStatusOp" parameter determines which status information to return. ** The "iScanStatusOp" must be one of the [scanstatus options] or the behavior ** of this interface is undefined. ** ^The requested measurement is written into a variable pointed to by ** the "pOut" parameter. ** Parameter "idx" identifies the specific loop to retrieve statistics for. ** Loops are numbered starting from zero. ^If idx is out of range - less than ** zero or greater than or equal to the total number of loops used to implement ** the statement - a non-zero value is returned and the variable that pOut ** points to is unchanged. ** ** ^Statistics might not be available for all loops in all statements. ^In cases ** where there exist loops with no available statistics, this function behaves ** as if the loop did not exist - it returns non-zero and leave the variable ** that pOut points to unchanged. ** ** See also: [sqlite3_stmt_scanstatus_reset()] */ SQLITE_API int sqlite3_stmt_scanstatus( sqlite3_stmt *pStmt, /* Prepared statement for which info desired */ int idx, /* Index of loop to report on */ int iScanStatusOp, /* Information desired. SQLITE_SCANSTAT_* */ void *pOut /* Result written here */ ); /* ** CAPI3REF: Zero Scan-Status Counters ** METHOD: sqlite3_stmt ** ** ^Zero all [sqlite3_stmt_scanstatus()] related event counters. ** ** This API is only available if the library is built with pre-processor ** symbol [SQLITE_ENABLE_STMT_SCANSTATUS] defined. */ SQLITE_API void sqlite3_stmt_scanstatus_reset(sqlite3_stmt*); /* ** CAPI3REF: Flush caches to disk mid-transaction ** ** ^If a write-transaction is open on [database connection] D when the ** [sqlite3_db_cacheflush(D)] interface invoked, any dirty ** pages in the pager-cache that are not currently in use are written out ** to disk. A dirty page may be in use if a database cursor created by an ** active SQL statement is reading from it, or if it is page 1 of a database ** file (page 1 is always "in use"). ^The [sqlite3_db_cacheflush(D)] ** interface flushes caches for all schemas - "main", "temp", and ** any [attached] databases. ** ** ^If this function needs to obtain extra database locks before dirty pages ** can be flushed to disk, it does so. ^If those locks cannot be obtained ** immediately and there is a busy-handler callback configured, it is invoked ** in the usual manner. ^If the required lock still cannot be obtained, then ** the database is skipped and an attempt made to flush any dirty pages ** belonging to the next (if any) database. ^If any databases are skipped ** because locks cannot be obtained, but no other error occurs, this ** function returns SQLITE_BUSY. ** ** ^If any other error occurs while flushing dirty pages to disk (for ** example an IO error or out-of-memory condition), then processing is ** abandoned and an SQLite [error code] is returned to the caller immediately. ** ** ^Otherwise, if no error occurs, [sqlite3_db_cacheflush()] returns SQLITE_OK. ** ** ^This function does not set the database handle error code or message ** returned by the [sqlite3_errcode()] and [sqlite3_errmsg()] functions. */ SQLITE_API int sqlite3_db_cacheflush(sqlite3*); /* ** CAPI3REF: The pre-update hook. ** ** ^These interfaces are only available if SQLite is compiled using the ** [SQLITE_ENABLE_PREUPDATE_HOOK] compile-time option. ** ** ^The [sqlite3_preupdate_hook()] interface registers a callback function ** that is invoked prior to each [INSERT], [UPDATE], and [DELETE] operation ** on a [rowid table]. ** ^At most one preupdate hook may be registered at a time on a single ** [database connection]; each call to [sqlite3_preupdate_hook()] overrides ** the previous setting. ** ^The preupdate hook is disabled by invoking [sqlite3_preupdate_hook()] ** with a NULL pointer as the second parameter. ** ^The third parameter to [sqlite3_preupdate_hook()] is passed through as ** the first parameter to callbacks. ** ** ^The preupdate hook only fires for changes to [rowid tables]; the preupdate ** hook is not invoked for changes to [virtual tables] or [WITHOUT ROWID] ** tables. ** ** ^The second parameter to the preupdate callback is a pointer to ** the [database connection] that registered the preupdate hook. ** ^The third parameter to the preupdate callback is one of the constants ** [SQLITE_INSERT], [SQLITE_DELETE], or [SQLITE_UPDATE] to identify the ** kind of update operation that is about to occur. ** ^(The fourth parameter to the preupdate callback is the name of the ** database within the database connection that is being modified. This ** will be "main" for the main database or "temp" for TEMP tables or ** the name given after the AS keyword in the [ATTACH] statement for attached ** databases.)^ ** ^The fifth parameter to the preupdate callback is the name of the ** table that is being modified. ** ^The sixth parameter to the preupdate callback is the initial [rowid] of the ** row being changes for SQLITE_UPDATE and SQLITE_DELETE changes and is ** undefined for SQLITE_INSERT changes. ** ^The seventh parameter to the preupdate callback is the final [rowid] of ** the row being changed for SQLITE_UPDATE and SQLITE_INSERT changes and is ** undefined for SQLITE_DELETE changes. ** ** The [sqlite3_preupdate_old()], [sqlite3_preupdate_new()], ** [sqlite3_preupdate_count()], and [sqlite3_preupdate_depth()] interfaces ** provide additional information about a preupdate event. These routines ** may only be called from within a preupdate callback. Invoking any of ** these routines from outside of a preupdate callback or with a ** [database connection] pointer that is different from the one supplied ** to the preupdate callback results in undefined and probably undesirable ** behavior. ** ** ^The [sqlite3_preupdate_count(D)] interface returns the number of columns ** in the row that is being inserted, updated, or deleted. ** ** ^The [sqlite3_preupdate_old(D,N,P)] interface writes into P a pointer to ** a [protected sqlite3_value] that contains the value of the Nth column of ** the table row before it is updated. The N parameter must be between 0 ** and one less than the number of columns or the behavior will be ** undefined. This must only be used within SQLITE_UPDATE and SQLITE_DELETE ** preupdate callbacks; if it is used by an SQLITE_INSERT callback then the ** behavior is undefined. The [sqlite3_value] that P points to ** will be destroyed when the preupdate callback returns. ** ** ^The [sqlite3_preupdate_new(D,N,P)] interface writes into P a pointer to ** a [protected sqlite3_value] that contains the value of the Nth column of ** the table row after it is updated. The N parameter must be between 0 ** and one less than the number of columns or the behavior will be ** undefined. This must only be used within SQLITE_INSERT and SQLITE_UPDATE ** preupdate callbacks; if it is used by an SQLITE_DELETE callback then the ** behavior is undefined. The [sqlite3_value] that P points to ** will be destroyed when the preupdate callback returns. ** ** ^The [sqlite3_preupdate_depth(D)] interface returns 0 if the preupdate ** callback was invoked as a result of a direct insert, update, or delete ** operation; or 1 for inserts, updates, or deletes invoked by top-level ** triggers; or 2 for changes resulting from triggers called by top-level ** triggers; and so forth. ** ** See also: [sqlite3_update_hook()] */ SQLITE_API SQLITE_EXPERIMENTAL void *sqlite3_preupdate_hook( sqlite3 *db, void(*xPreUpdate)( void *pCtx, /* Copy of third arg to preupdate_hook() */ sqlite3 *db, /* Database handle */ int op, /* SQLITE_UPDATE, DELETE or INSERT */ char const *zDb, /* Database name */ char const *zName, /* Table name */ sqlite3_int64 iKey1, /* Rowid of row about to be deleted/updated */ sqlite3_int64 iKey2 /* New rowid value (for a rowid UPDATE) */ ), void* ); SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_preupdate_old(sqlite3 *, int, sqlite3_value **); SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_preupdate_count(sqlite3 *); SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_preupdate_depth(sqlite3 *); SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_preupdate_new(sqlite3 *, int, sqlite3_value **); /* ** CAPI3REF: Low-level system error code ** ** ^Attempt to return the underlying operating system error code or error ** number that caused the most recent I/O error or failure to open a file. ** The return value is OS-dependent. For example, on unix systems, after ** [sqlite3_open_v2()] returns [SQLITE_CANTOPEN], this interface could be ** called to get back the underlying "errno" that caused the problem, such ** as ENOSPC, EAUTH, EISDIR, and so forth. */ SQLITE_API int sqlite3_system_errno(sqlite3*); /* ** CAPI3REF: Database Snapshot ** KEYWORDS: {snapshot} ** EXPERIMENTAL ** ** An instance of the snapshot object records the state of a [WAL mode] ** database for some specific point in history. ** ** In [WAL mode], multiple [database connections] that are open on the ** same database file can each be reading a different historical version ** of the database file. When a [database connection] begins a read ** transaction, that connection sees an unchanging copy of the database ** as it existed for the point in time when the transaction first started. ** Subsequent changes to the database from other connections are not seen ** by the reader until a new read transaction is started. ** ** The sqlite3_snapshot object records state information about an historical ** version of the database file so that it is possible to later open a new read ** transaction that sees that historical version of the database rather than ** the most recent version. ** ** The constructor for this object is [sqlite3_snapshot_get()]. The ** [sqlite3_snapshot_open()] method causes a fresh read transaction to refer ** to an historical snapshot (if possible). The destructor for ** sqlite3_snapshot objects is [sqlite3_snapshot_free()]. */ typedef struct sqlite3_snapshot sqlite3_snapshot; /* ** CAPI3REF: Record A Database Snapshot ** EXPERIMENTAL ** ** ^The [sqlite3_snapshot_get(D,S,P)] interface attempts to make a ** new [sqlite3_snapshot] object that records the current state of ** schema S in database connection D. ^On success, the ** [sqlite3_snapshot_get(D,S,P)] interface writes a pointer to the newly ** created [sqlite3_snapshot] object into *P and returns SQLITE_OK. ** ^If schema S of [database connection] D is not a [WAL mode] database ** that is in a read transaction, then [sqlite3_snapshot_get(D,S,P)] ** leaves the *P value unchanged and returns an appropriate [error code]. ** ** The [sqlite3_snapshot] object returned from a successful call to ** [sqlite3_snapshot_get()] must be freed using [sqlite3_snapshot_free()] ** to avoid a memory leak. ** ** The [sqlite3_snapshot_get()] interface is only available when the ** SQLITE_ENABLE_SNAPSHOT compile-time option is used. */ SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_snapshot_get( sqlite3 *db, const char *zSchema, sqlite3_snapshot **ppSnapshot ); /* ** CAPI3REF: Start a read transaction on an historical snapshot ** EXPERIMENTAL ** ** ^The [sqlite3_snapshot_open(D,S,P)] interface starts a ** read transaction for schema S of ** [database connection] D such that the read transaction ** refers to historical [snapshot] P, rather than the most ** recent change to the database. ** ^The [sqlite3_snapshot_open()] interface returns SQLITE_OK on success ** or an appropriate [error code] if it fails. ** ** ^In order to succeed, a call to [sqlite3_snapshot_open(D,S,P)] must be ** the first operation following the [BEGIN] that takes the schema S ** out of [autocommit mode]. ** ^In other words, schema S must not currently be in ** a transaction for [sqlite3_snapshot_open(D,S,P)] to work, but the ** database connection D must be out of [autocommit mode]. ** ^A [snapshot] will fail to open if it has been overwritten by a ** [checkpoint]. ** ^(A call to [sqlite3_snapshot_open(D,S,P)] will fail if the ** database connection D does not know that the database file for ** schema S is in [WAL mode]. A database connection might not know ** that the database file is in [WAL mode] if there has been no prior ** I/O on that database connection, or if the database entered [WAL mode] ** after the most recent I/O on the database connection.)^ ** (Hint: Run "[PRAGMA application_id]" against a newly opened ** database connection in order to make it ready to use snapshots.) ** ** The [sqlite3_snapshot_open()] interface is only available when the ** SQLITE_ENABLE_SNAPSHOT compile-time option is used. */ SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_snapshot_open( sqlite3 *db, const char *zSchema, sqlite3_snapshot *pSnapshot ); /* ** CAPI3REF: Destroy a snapshot ** EXPERIMENTAL ** ** ^The [sqlite3_snapshot_free(P)] interface destroys [sqlite3_snapshot] P. ** The application must eventually free every [sqlite3_snapshot] object ** using this routine to avoid a memory leak. ** ** The [sqlite3_snapshot_free()] interface is only available when the ** SQLITE_ENABLE_SNAPSHOT compile-time option is used. */ SQLITE_API SQLITE_EXPERIMENTAL void sqlite3_snapshot_free(sqlite3_snapshot*); /* ** CAPI3REF: Compare the ages of two snapshot handles. ** EXPERIMENTAL ** ** The sqlite3_snapshot_cmp(P1, P2) interface is used to compare the ages ** of two valid snapshot handles. ** ** If the two snapshot handles are not associated with the same database ** file, the result of the comparison is undefined. ** ** Additionally, the result of the comparison is only valid if both of the ** snapshot handles were obtained by calling sqlite3_snapshot_get() since the ** last time the wal file was deleted. The wal file is deleted when the ** database is changed back to rollback mode or when the number of database ** clients drops to zero. If either snapshot handle was obtained before the ** wal file was last deleted, the value returned by this function ** is undefined. ** ** Otherwise, this API returns a negative value if P1 refers to an older ** snapshot than P2, zero if the two handles refer to the same database ** snapshot, and a positive value if P1 is a newer snapshot than P2. */ SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_snapshot_cmp( sqlite3_snapshot *p1, sqlite3_snapshot *p2 ); /* ** Undo the hack that converts floating point types to integer for ** builds on processors without floating point support. */ #ifdef SQLITE_OMIT_FLOATING_POINT # undef double #endif #ifdef __cplusplus } /* End of the 'extern "C"' block */ #endif #endif /* SQLITE3_H */ /******** Begin file sqlite3rtree.h *********/ /* ** 2010 August 30 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ************************************************************************* */ #ifndef _SQLITE3RTREE_H_ #define _SQLITE3RTREE_H_ #ifdef __cplusplus extern "C" { #endif typedef struct sqlite3_rtree_geometry sqlite3_rtree_geometry; typedef struct sqlite3_rtree_query_info sqlite3_rtree_query_info; /* The double-precision datatype used by RTree depends on the ** SQLITE_RTREE_INT_ONLY compile-time option. */ #ifdef SQLITE_RTREE_INT_ONLY typedef sqlite3_int64 sqlite3_rtree_dbl; #else typedef double sqlite3_rtree_dbl; #endif /* ** Register a geometry callback named zGeom that can be used as part of an ** R-Tree geometry query as follows: ** ** SELECT ... FROM WHERE MATCH $zGeom(... params ...) */ SQLITE_API int sqlite3_rtree_geometry_callback( sqlite3 *db, const char *zGeom, int (*xGeom)(sqlite3_rtree_geometry*, int, sqlite3_rtree_dbl*,int*), void *pContext ); /* ** A pointer to a structure of the following type is passed as the first ** argument to callbacks registered using rtree_geometry_callback(). */ struct sqlite3_rtree_geometry { void *pContext; /* Copy of pContext passed to s_r_g_c() */ int nParam; /* Size of array aParam[] */ sqlite3_rtree_dbl *aParam; /* Parameters passed to SQL geom function */ void *pUser; /* Callback implementation user data */ void (*xDelUser)(void *); /* Called by SQLite to clean up pUser */ }; /* ** Register a 2nd-generation geometry callback named zScore that can be ** used as part of an R-Tree geometry query as follows: ** ** SELECT ... FROM WHERE MATCH $zQueryFunc(... params ...) */ SQLITE_API int sqlite3_rtree_query_callback( sqlite3 *db, const char *zQueryFunc, int (*xQueryFunc)(sqlite3_rtree_query_info*), void *pContext, void (*xDestructor)(void*) ); /* ** A pointer to a structure of the following type is passed as the ** argument to scored geometry callback registered using ** sqlite3_rtree_query_callback(). ** ** Note that the first 5 fields of this structure are identical to ** sqlite3_rtree_geometry. This structure is a subclass of ** sqlite3_rtree_geometry. */ struct sqlite3_rtree_query_info { void *pContext; /* pContext from when function registered */ int nParam; /* Number of function parameters */ sqlite3_rtree_dbl *aParam; /* value of function parameters */ void *pUser; /* callback can use this, if desired */ void (*xDelUser)(void*); /* function to free pUser */ sqlite3_rtree_dbl *aCoord; /* Coordinates of node or entry to check */ unsigned int *anQueue; /* Number of pending entries in the queue */ int nCoord; /* Number of coordinates */ int iLevel; /* Level of current node or entry */ int mxLevel; /* The largest iLevel value in the tree */ sqlite3_int64 iRowid; /* Rowid for current entry */ sqlite3_rtree_dbl rParentScore; /* Score of parent node */ int eParentWithin; /* Visibility of parent node */ int eWithin; /* OUT: Visiblity */ sqlite3_rtree_dbl rScore; /* OUT: Write the score here */ /* The following fields are only available in 3.8.11 and later */ sqlite3_value **apSqlParam; /* Original SQL values of parameters */ }; /* ** Allowed values for sqlite3_rtree_query.eWithin and .eParentWithin. */ #define NOT_WITHIN 0 /* Object completely outside of query region */ #define PARTLY_WITHIN 1 /* Object partially overlaps query region */ #define FULLY_WITHIN 2 /* Object fully contained within query region */ #ifdef __cplusplus } /* end of the 'extern "C"' block */ #endif #endif /* ifndef _SQLITE3RTREE_H_ */ /******** End of sqlite3rtree.h *********/ /******** Begin file sqlite3session.h *********/ #if !defined(__SQLITESESSION_H_) && defined(SQLITE_ENABLE_SESSION) #define __SQLITESESSION_H_ 1 /* ** Make sure we can call this stuff from C++. */ #ifdef __cplusplus extern "C" { #endif /* ** CAPI3REF: Session Object Handle */ typedef struct sqlite3_session sqlite3_session; /* ** CAPI3REF: Changeset Iterator Handle */ typedef struct sqlite3_changeset_iter sqlite3_changeset_iter; /* ** CAPI3REF: Create A New Session Object ** ** Create a new session object attached to database handle db. If successful, ** a pointer to the new object is written to *ppSession and SQLITE_OK is ** returned. If an error occurs, *ppSession is set to NULL and an SQLite ** error code (e.g. SQLITE_NOMEM) is returned. ** ** It is possible to create multiple session objects attached to a single ** database handle. ** ** Session objects created using this function should be deleted using the ** [sqlite3session_delete()] function before the database handle that they ** are attached to is itself closed. If the database handle is closed before ** the session object is deleted, then the results of calling any session ** module function, including [sqlite3session_delete()] on the session object ** are undefined. ** ** Because the session module uses the [sqlite3_preupdate_hook()] API, it ** is not possible for an application to register a pre-update hook on a ** database handle that has one or more session objects attached. Nor is ** it possible to create a session object attached to a database handle for ** which a pre-update hook is already defined. The results of attempting ** either of these things are undefined. ** ** The session object will be used to create changesets for tables in ** database zDb, where zDb is either "main", or "temp", or the name of an ** attached database. It is not an error if database zDb is not attached ** to the database when the session object is created. */ int sqlite3session_create( sqlite3 *db, /* Database handle */ const char *zDb, /* Name of db (e.g. "main") */ sqlite3_session **ppSession /* OUT: New session object */ ); /* ** CAPI3REF: Delete A Session Object ** ** Delete a session object previously allocated using ** [sqlite3session_create()]. Once a session object has been deleted, the ** results of attempting to use pSession with any other session module ** function are undefined. ** ** Session objects must be deleted before the database handle to which they ** are attached is closed. Refer to the documentation for ** [sqlite3session_create()] for details. */ void sqlite3session_delete(sqlite3_session *pSession); /* ** CAPI3REF: Enable Or Disable A Session Object ** ** Enable or disable the recording of changes by a session object. When ** enabled, a session object records changes made to the database. When ** disabled - it does not. A newly created session object is enabled. ** Refer to the documentation for [sqlite3session_changeset()] for further ** details regarding how enabling and disabling a session object affects ** the eventual changesets. ** ** Passing zero to this function disables the session. Passing a value ** greater than zero enables it. Passing a value less than zero is a ** no-op, and may be used to query the current state of the session. ** ** The return value indicates the final state of the session object: 0 if ** the session is disabled, or 1 if it is enabled. */ int sqlite3session_enable(sqlite3_session *pSession, int bEnable); /* ** CAPI3REF: Set Or Clear the Indirect Change Flag ** ** Each change recorded by a session object is marked as either direct or ** indirect. A change is marked as indirect if either: ** **
    **
  • The session object "indirect" flag is set when the change is ** made, or **
  • The change is made by an SQL trigger or foreign key action ** instead of directly as a result of a users SQL statement. **
** ** If a single row is affected by more than one operation within a session, ** then the change is considered indirect if all operations meet the criteria ** for an indirect change above, or direct otherwise. ** ** This function is used to set, clear or query the session object indirect ** flag. If the second argument passed to this function is zero, then the ** indirect flag is cleared. If it is greater than zero, the indirect flag ** is set. Passing a value less than zero does not modify the current value ** of the indirect flag, and may be used to query the current state of the ** indirect flag for the specified session object. ** ** The return value indicates the final state of the indirect flag: 0 if ** it is clear, or 1 if it is set. */ int sqlite3session_indirect(sqlite3_session *pSession, int bIndirect); /* ** CAPI3REF: Attach A Table To A Session Object ** ** If argument zTab is not NULL, then it is the name of a table to attach ** to the session object passed as the first argument. All subsequent changes ** made to the table while the session object is enabled will be recorded. See ** documentation for [sqlite3session_changeset()] for further details. ** ** Or, if argument zTab is NULL, then changes are recorded for all tables ** in the database. If additional tables are added to the database (by ** executing "CREATE TABLE" statements) after this call is made, changes for ** the new tables are also recorded. ** ** Changes can only be recorded for tables that have a PRIMARY KEY explicitly ** defined as part of their CREATE TABLE statement. It does not matter if the ** PRIMARY KEY is an "INTEGER PRIMARY KEY" (rowid alias) or not. The PRIMARY ** KEY may consist of a single column, or may be a composite key. ** ** It is not an error if the named table does not exist in the database. Nor ** is it an error if the named table does not have a PRIMARY KEY. However, ** no changes will be recorded in either of these scenarios. ** ** Changes are not recorded for individual rows that have NULL values stored ** in one or more of their PRIMARY KEY columns. ** ** SQLITE_OK is returned if the call completes without error. Or, if an error ** occurs, an SQLite error code (e.g. SQLITE_NOMEM) is returned. */ int sqlite3session_attach( sqlite3_session *pSession, /* Session object */ const char *zTab /* Table name */ ); /* ** CAPI3REF: Set a table filter on a Session Object. ** ** The second argument (xFilter) is the "filter callback". For changes to rows ** in tables that are not attached to the Session object, the filter is called ** to determine whether changes to the table's rows should be tracked or not. ** If xFilter returns 0, changes is not tracked. Note that once a table is ** attached, xFilter will not be called again. */ void sqlite3session_table_filter( sqlite3_session *pSession, /* Session object */ int(*xFilter)( void *pCtx, /* Copy of third arg to _filter_table() */ const char *zTab /* Table name */ ), void *pCtx /* First argument passed to xFilter */ ); /* ** CAPI3REF: Generate A Changeset From A Session Object ** ** Obtain a changeset containing changes to the tables attached to the ** session object passed as the first argument. If successful, ** set *ppChangeset to point to a buffer containing the changeset ** and *pnChangeset to the size of the changeset in bytes before returning ** SQLITE_OK. If an error occurs, set both *ppChangeset and *pnChangeset to ** zero and return an SQLite error code. ** ** A changeset consists of zero or more INSERT, UPDATE and/or DELETE changes, ** each representing a change to a single row of an attached table. An INSERT ** change contains the values of each field of a new database row. A DELETE ** contains the original values of each field of a deleted database row. An ** UPDATE change contains the original values of each field of an updated ** database row along with the updated values for each updated non-primary-key ** column. It is not possible for an UPDATE change to represent a change that ** modifies the values of primary key columns. If such a change is made, it ** is represented in a changeset as a DELETE followed by an INSERT. ** ** Changes are not recorded for rows that have NULL values stored in one or ** more of their PRIMARY KEY columns. If such a row is inserted or deleted, ** no corresponding change is present in the changesets returned by this ** function. If an existing row with one or more NULL values stored in ** PRIMARY KEY columns is updated so that all PRIMARY KEY columns are non-NULL, ** only an INSERT is appears in the changeset. Similarly, if an existing row ** with non-NULL PRIMARY KEY values is updated so that one or more of its ** PRIMARY KEY columns are set to NULL, the resulting changeset contains a ** DELETE change only. ** ** The contents of a changeset may be traversed using an iterator created ** using the [sqlite3changeset_start()] API. A changeset may be applied to ** a database with a compatible schema using the [sqlite3changeset_apply()] ** API. ** ** Within a changeset generated by this function, all changes related to a ** single table are grouped together. In other words, when iterating through ** a changeset or when applying a changeset to a database, all changes related ** to a single table are processed before moving on to the next table. Tables ** are sorted in the same order in which they were attached (or auto-attached) ** to the sqlite3_session object. The order in which the changes related to ** a single table are stored is undefined. ** ** Following a successful call to this function, it is the responsibility of ** the caller to eventually free the buffer that *ppChangeset points to using ** [sqlite3_free()]. ** **

Changeset Generation

** ** Once a table has been attached to a session object, the session object ** records the primary key values of all new rows inserted into the table. ** It also records the original primary key and other column values of any ** deleted or updated rows. For each unique primary key value, data is only ** recorded once - the first time a row with said primary key is inserted, ** updated or deleted in the lifetime of the session. ** ** There is one exception to the previous paragraph: when a row is inserted, ** updated or deleted, if one or more of its primary key columns contain a ** NULL value, no record of the change is made. ** ** The session object therefore accumulates two types of records - those ** that consist of primary key values only (created when the user inserts ** a new record) and those that consist of the primary key values and the ** original values of other table columns (created when the users deletes ** or updates a record). ** ** When this function is called, the requested changeset is created using ** both the accumulated records and the current contents of the database ** file. Specifically: ** **
    **
  • For each record generated by an insert, the database is queried ** for a row with a matching primary key. If one is found, an INSERT ** change is added to the changeset. If no such row is found, no change ** is added to the changeset. ** **
  • For each record generated by an update or delete, the database is ** queried for a row with a matching primary key. If such a row is ** found and one or more of the non-primary key fields have been ** modified from their original values, an UPDATE change is added to ** the changeset. Or, if no such row is found in the table, a DELETE ** change is added to the changeset. If there is a row with a matching ** primary key in the database, but all fields contain their original ** values, no change is added to the changeset. **
** ** This means, amongst other things, that if a row is inserted and then later ** deleted while a session object is active, neither the insert nor the delete ** will be present in the changeset. Or if a row is deleted and then later a ** row with the same primary key values inserted while a session object is ** active, the resulting changeset will contain an UPDATE change instead of ** a DELETE and an INSERT. ** ** When a session object is disabled (see the [sqlite3session_enable()] API), ** it does not accumulate records when rows are inserted, updated or deleted. ** This may appear to have some counter-intuitive effects if a single row ** is written to more than once during a session. For example, if a row ** is inserted while a session object is enabled, then later deleted while ** the same session object is disabled, no INSERT record will appear in the ** changeset, even though the delete took place while the session was disabled. ** Or, if one field of a row is updated while a session is disabled, and ** another field of the same row is updated while the session is enabled, the ** resulting changeset will contain an UPDATE change that updates both fields. */ int sqlite3session_changeset( sqlite3_session *pSession, /* Session object */ int *pnChangeset, /* OUT: Size of buffer at *ppChangeset */ void **ppChangeset /* OUT: Buffer containing changeset */ ); /* ** CAPI3REF: Load The Difference Between Tables Into A Session ** ** If it is not already attached to the session object passed as the first ** argument, this function attaches table zTbl in the same manner as the ** [sqlite3session_attach()] function. If zTbl does not exist, or if it ** does not have a primary key, this function is a no-op (but does not return ** an error). ** ** Argument zFromDb must be the name of a database ("main", "temp" etc.) ** attached to the same database handle as the session object that contains ** a table compatible with the table attached to the session by this function. ** A table is considered compatible if it: ** **
    **
  • Has the same name, **
  • Has the same set of columns declared in the same order, and **
  • Has the same PRIMARY KEY definition. **
** ** If the tables are not compatible, SQLITE_SCHEMA is returned. If the tables ** are compatible but do not have any PRIMARY KEY columns, it is not an error ** but no changes are added to the session object. As with other session ** APIs, tables without PRIMARY KEYs are simply ignored. ** ** This function adds a set of changes to the session object that could be ** used to update the table in database zFrom (call this the "from-table") ** so that its content is the same as the table attached to the session ** object (call this the "to-table"). Specifically: ** **
    **
  • For each row (primary key) that exists in the to-table but not in ** the from-table, an INSERT record is added to the session object. ** **
  • For each row (primary key) that exists in the to-table but not in ** the from-table, a DELETE record is added to the session object. ** **
  • For each row (primary key) that exists in both tables, but features ** different in each, an UPDATE record is added to the session. **
** ** To clarify, if this function is called and then a changeset constructed ** using [sqlite3session_changeset()], then after applying that changeset to ** database zFrom the contents of the two compatible tables would be ** identical. ** ** It an error if database zFrom does not exist or does not contain the ** required compatible table. ** ** If the operation successful, SQLITE_OK is returned. Otherwise, an SQLite ** error code. In this case, if argument pzErrMsg is not NULL, *pzErrMsg ** may be set to point to a buffer containing an English language error ** message. It is the responsibility of the caller to free this buffer using ** sqlite3_free(). */ int sqlite3session_diff( sqlite3_session *pSession, const char *zFromDb, const char *zTbl, char **pzErrMsg ); /* ** CAPI3REF: Generate A Patchset From A Session Object ** ** The differences between a patchset and a changeset are that: ** **
    **
  • DELETE records consist of the primary key fields only. The ** original values of other fields are omitted. **
  • The original values of any modified fields are omitted from ** UPDATE records. **
** ** A patchset blob may be used with up to date versions of all ** sqlite3changeset_xxx API functions except for sqlite3changeset_invert(), ** which returns SQLITE_CORRUPT if it is passed a patchset. Similarly, ** attempting to use a patchset blob with old versions of the ** sqlite3changeset_xxx APIs also provokes an SQLITE_CORRUPT error. ** ** Because the non-primary key "old.*" fields are omitted, no ** SQLITE_CHANGESET_DATA conflicts can be detected or reported if a patchset ** is passed to the sqlite3changeset_apply() API. Other conflict types work ** in the same way as for changesets. ** ** Changes within a patchset are ordered in the same way as for changesets ** generated by the sqlite3session_changeset() function (i.e. all changes for ** a single table are grouped together, tables appear in the order in which ** they were attached to the session object). */ int sqlite3session_patchset( sqlite3_session *pSession, /* Session object */ int *pnPatchset, /* OUT: Size of buffer at *ppChangeset */ void **ppPatchset /* OUT: Buffer containing changeset */ ); /* ** CAPI3REF: Test if a changeset has recorded any changes. ** ** Return non-zero if no changes to attached tables have been recorded by ** the session object passed as the first argument. Otherwise, if one or ** more changes have been recorded, return zero. ** ** Even if this function returns zero, it is possible that calling ** [sqlite3session_changeset()] on the session handle may still return a ** changeset that contains no changes. This can happen when a row in ** an attached table is modified and then later on the original values ** are restored. However, if this function returns non-zero, then it is ** guaranteed that a call to sqlite3session_changeset() will return a ** changeset containing zero changes. */ int sqlite3session_isempty(sqlite3_session *pSession); /* ** CAPI3REF: Create An Iterator To Traverse A Changeset ** ** Create an iterator used to iterate through the contents of a changeset. ** If successful, *pp is set to point to the iterator handle and SQLITE_OK ** is returned. Otherwise, if an error occurs, *pp is set to zero and an ** SQLite error code is returned. ** ** The following functions can be used to advance and query a changeset ** iterator created by this function: ** **
    **
  • [sqlite3changeset_next()] **
  • [sqlite3changeset_op()] **
  • [sqlite3changeset_new()] **
  • [sqlite3changeset_old()] **
** ** It is the responsibility of the caller to eventually destroy the iterator ** by passing it to [sqlite3changeset_finalize()]. The buffer containing the ** changeset (pChangeset) must remain valid until after the iterator is ** destroyed. ** ** Assuming the changeset blob was created by one of the ** [sqlite3session_changeset()], [sqlite3changeset_concat()] or ** [sqlite3changeset_invert()] functions, all changes within the changeset ** that apply to a single table are grouped together. This means that when ** an application iterates through a changeset using an iterator created by ** this function, all changes that relate to a single table are visited ** consecutively. There is no chance that the iterator will visit a change ** the applies to table X, then one for table Y, and then later on visit ** another change for table X. */ int sqlite3changeset_start( sqlite3_changeset_iter **pp, /* OUT: New changeset iterator handle */ int nChangeset, /* Size of changeset blob in bytes */ void *pChangeset /* Pointer to blob containing changeset */ ); /* ** CAPI3REF: Advance A Changeset Iterator ** ** This function may only be used with iterators created by function ** [sqlite3changeset_start()]. If it is called on an iterator passed to ** a conflict-handler callback by [sqlite3changeset_apply()], SQLITE_MISUSE ** is returned and the call has no effect. ** ** Immediately after an iterator is created by sqlite3changeset_start(), it ** does not point to any change in the changeset. Assuming the changeset ** is not empty, the first call to this function advances the iterator to ** point to the first change in the changeset. Each subsequent call advances ** the iterator to point to the next change in the changeset (if any). If ** no error occurs and the iterator points to a valid change after a call ** to sqlite3changeset_next() has advanced it, SQLITE_ROW is returned. ** Otherwise, if all changes in the changeset have already been visited, ** SQLITE_DONE is returned. ** ** If an error occurs, an SQLite error code is returned. Possible error ** codes include SQLITE_CORRUPT (if the changeset buffer is corrupt) or ** SQLITE_NOMEM. */ int sqlite3changeset_next(sqlite3_changeset_iter *pIter); /* ** CAPI3REF: Obtain The Current Operation From A Changeset Iterator ** ** The pIter argument passed to this function may either be an iterator ** passed to a conflict-handler by [sqlite3changeset_apply()], or an iterator ** created by [sqlite3changeset_start()]. In the latter case, the most recent ** call to [sqlite3changeset_next()] must have returned [SQLITE_ROW]. If this ** is not the case, this function returns [SQLITE_MISUSE]. ** ** If argument pzTab is not NULL, then *pzTab is set to point to a ** nul-terminated utf-8 encoded string containing the name of the table ** affected by the current change. The buffer remains valid until either ** sqlite3changeset_next() is called on the iterator or until the ** conflict-handler function returns. If pnCol is not NULL, then *pnCol is ** set to the number of columns in the table affected by the change. If ** pbIncorrect is not NULL, then *pbIndirect is set to true (1) if the change ** is an indirect change, or false (0) otherwise. See the documentation for ** [sqlite3session_indirect()] for a description of direct and indirect ** changes. Finally, if pOp is not NULL, then *pOp is set to one of ** [SQLITE_INSERT], [SQLITE_DELETE] or [SQLITE_UPDATE], depending on the ** type of change that the iterator currently points to. ** ** If no error occurs, SQLITE_OK is returned. If an error does occur, an ** SQLite error code is returned. The values of the output variables may not ** be trusted in this case. */ int sqlite3changeset_op( sqlite3_changeset_iter *pIter, /* Iterator object */ const char **pzTab, /* OUT: Pointer to table name */ int *pnCol, /* OUT: Number of columns in table */ int *pOp, /* OUT: SQLITE_INSERT, DELETE or UPDATE */ int *pbIndirect /* OUT: True for an 'indirect' change */ ); /* ** CAPI3REF: Obtain The Primary Key Definition Of A Table ** ** For each modified table, a changeset includes the following: ** **
    **
  • The number of columns in the table, and **
  • Which of those columns make up the tables PRIMARY KEY. **
** ** This function is used to find which columns comprise the PRIMARY KEY of ** the table modified by the change that iterator pIter currently points to. ** If successful, *pabPK is set to point to an array of nCol entries, where ** nCol is the number of columns in the table. Elements of *pabPK are set to ** 0x01 if the corresponding column is part of the tables primary key, or ** 0x00 if it is not. ** ** If argument pnCol is not NULL, then *pnCol is set to the number of columns ** in the table. ** ** If this function is called when the iterator does not point to a valid ** entry, SQLITE_MISUSE is returned and the output variables zeroed. Otherwise, ** SQLITE_OK is returned and the output variables populated as described ** above. */ int sqlite3changeset_pk( sqlite3_changeset_iter *pIter, /* Iterator object */ unsigned char **pabPK, /* OUT: Array of boolean - true for PK cols */ int *pnCol /* OUT: Number of entries in output array */ ); /* ** CAPI3REF: Obtain old.* Values From A Changeset Iterator ** ** The pIter argument passed to this function may either be an iterator ** passed to a conflict-handler by [sqlite3changeset_apply()], or an iterator ** created by [sqlite3changeset_start()]. In the latter case, the most recent ** call to [sqlite3changeset_next()] must have returned SQLITE_ROW. ** Furthermore, it may only be called if the type of change that the iterator ** currently points to is either [SQLITE_DELETE] or [SQLITE_UPDATE]. Otherwise, ** this function returns [SQLITE_MISUSE] and sets *ppValue to NULL. ** ** Argument iVal must be greater than or equal to 0, and less than the number ** of columns in the table affected by the current change. Otherwise, ** [SQLITE_RANGE] is returned and *ppValue is set to NULL. ** ** If successful, this function sets *ppValue to point to a protected ** sqlite3_value object containing the iVal'th value from the vector of ** original row values stored as part of the UPDATE or DELETE change and ** returns SQLITE_OK. The name of the function comes from the fact that this ** is similar to the "old.*" columns available to update or delete triggers. ** ** If some other error occurs (e.g. an OOM condition), an SQLite error code ** is returned and *ppValue is set to NULL. */ int sqlite3changeset_old( sqlite3_changeset_iter *pIter, /* Changeset iterator */ int iVal, /* Column number */ sqlite3_value **ppValue /* OUT: Old value (or NULL pointer) */ ); /* ** CAPI3REF: Obtain new.* Values From A Changeset Iterator ** ** The pIter argument passed to this function may either be an iterator ** passed to a conflict-handler by [sqlite3changeset_apply()], or an iterator ** created by [sqlite3changeset_start()]. In the latter case, the most recent ** call to [sqlite3changeset_next()] must have returned SQLITE_ROW. ** Furthermore, it may only be called if the type of change that the iterator ** currently points to is either [SQLITE_UPDATE] or [SQLITE_INSERT]. Otherwise, ** this function returns [SQLITE_MISUSE] and sets *ppValue to NULL. ** ** Argument iVal must be greater than or equal to 0, and less than the number ** of columns in the table affected by the current change. Otherwise, ** [SQLITE_RANGE] is returned and *ppValue is set to NULL. ** ** If successful, this function sets *ppValue to point to a protected ** sqlite3_value object containing the iVal'th value from the vector of ** new row values stored as part of the UPDATE or INSERT change and ** returns SQLITE_OK. If the change is an UPDATE and does not include ** a new value for the requested column, *ppValue is set to NULL and ** SQLITE_OK returned. The name of the function comes from the fact that ** this is similar to the "new.*" columns available to update or delete ** triggers. ** ** If some other error occurs (e.g. an OOM condition), an SQLite error code ** is returned and *ppValue is set to NULL. */ int sqlite3changeset_new( sqlite3_changeset_iter *pIter, /* Changeset iterator */ int iVal, /* Column number */ sqlite3_value **ppValue /* OUT: New value (or NULL pointer) */ ); /* ** CAPI3REF: Obtain Conflicting Row Values From A Changeset Iterator ** ** This function should only be used with iterator objects passed to a ** conflict-handler callback by [sqlite3changeset_apply()] with either ** [SQLITE_CHANGESET_DATA] or [SQLITE_CHANGESET_CONFLICT]. If this function ** is called on any other iterator, [SQLITE_MISUSE] is returned and *ppValue ** is set to NULL. ** ** Argument iVal must be greater than or equal to 0, and less than the number ** of columns in the table affected by the current change. Otherwise, ** [SQLITE_RANGE] is returned and *ppValue is set to NULL. ** ** If successful, this function sets *ppValue to point to a protected ** sqlite3_value object containing the iVal'th value from the ** "conflicting row" associated with the current conflict-handler callback ** and returns SQLITE_OK. ** ** If some other error occurs (e.g. an OOM condition), an SQLite error code ** is returned and *ppValue is set to NULL. */ int sqlite3changeset_conflict( sqlite3_changeset_iter *pIter, /* Changeset iterator */ int iVal, /* Column number */ sqlite3_value **ppValue /* OUT: Value from conflicting row */ ); /* ** CAPI3REF: Determine The Number Of Foreign Key Constraint Violations ** ** This function may only be called with an iterator passed to an ** SQLITE_CHANGESET_FOREIGN_KEY conflict handler callback. In this case ** it sets the output variable to the total number of known foreign key ** violations in the destination database and returns SQLITE_OK. ** ** In all other cases this function returns SQLITE_MISUSE. */ int sqlite3changeset_fk_conflicts( sqlite3_changeset_iter *pIter, /* Changeset iterator */ int *pnOut /* OUT: Number of FK violations */ ); /* ** CAPI3REF: Finalize A Changeset Iterator ** ** This function is used to finalize an iterator allocated with ** [sqlite3changeset_start()]. ** ** This function should only be called on iterators created using the ** [sqlite3changeset_start()] function. If an application calls this ** function with an iterator passed to a conflict-handler by ** [sqlite3changeset_apply()], [SQLITE_MISUSE] is immediately returned and the ** call has no effect. ** ** If an error was encountered within a call to an sqlite3changeset_xxx() ** function (for example an [SQLITE_CORRUPT] in [sqlite3changeset_next()] or an ** [SQLITE_NOMEM] in [sqlite3changeset_new()]) then an error code corresponding ** to that error is returned by this function. Otherwise, SQLITE_OK is ** returned. This is to allow the following pattern (pseudo-code): ** ** sqlite3changeset_start(); ** while( SQLITE_ROW==sqlite3changeset_next() ){ ** // Do something with change. ** } ** rc = sqlite3changeset_finalize(); ** if( rc!=SQLITE_OK ){ ** // An error has occurred ** } */ int sqlite3changeset_finalize(sqlite3_changeset_iter *pIter); /* ** CAPI3REF: Invert A Changeset ** ** This function is used to "invert" a changeset object. Applying an inverted ** changeset to a database reverses the effects of applying the uninverted ** changeset. Specifically: ** **
    **
  • Each DELETE change is changed to an INSERT, and **
  • Each INSERT change is changed to a DELETE, and **
  • For each UPDATE change, the old.* and new.* values are exchanged. **
** ** This function does not change the order in which changes appear within ** the changeset. It merely reverses the sense of each individual change. ** ** If successful, a pointer to a buffer containing the inverted changeset ** is stored in *ppOut, the size of the same buffer is stored in *pnOut, and ** SQLITE_OK is returned. If an error occurs, both *pnOut and *ppOut are ** zeroed and an SQLite error code returned. ** ** It is the responsibility of the caller to eventually call sqlite3_free() ** on the *ppOut pointer to free the buffer allocation following a successful ** call to this function. ** ** WARNING/TODO: This function currently assumes that the input is a valid ** changeset. If it is not, the results are undefined. */ int sqlite3changeset_invert( int nIn, const void *pIn, /* Input changeset */ int *pnOut, void **ppOut /* OUT: Inverse of input */ ); /* ** CAPI3REF: Concatenate Two Changeset Objects ** ** This function is used to concatenate two changesets, A and B, into a ** single changeset. The result is a changeset equivalent to applying ** changeset A followed by changeset B. ** ** This function combines the two input changesets using an ** sqlite3_changegroup object. Calling it produces similar results as the ** following code fragment: ** ** sqlite3_changegroup *pGrp; ** rc = sqlite3_changegroup_new(&pGrp); ** if( rc==SQLITE_OK ) rc = sqlite3changegroup_add(pGrp, nA, pA); ** if( rc==SQLITE_OK ) rc = sqlite3changegroup_add(pGrp, nB, pB); ** if( rc==SQLITE_OK ){ ** rc = sqlite3changegroup_output(pGrp, pnOut, ppOut); ** }else{ ** *ppOut = 0; ** *pnOut = 0; ** } ** ** Refer to the sqlite3_changegroup documentation below for details. */ int sqlite3changeset_concat( int nA, /* Number of bytes in buffer pA */ void *pA, /* Pointer to buffer containing changeset A */ int nB, /* Number of bytes in buffer pB */ void *pB, /* Pointer to buffer containing changeset B */ int *pnOut, /* OUT: Number of bytes in output changeset */ void **ppOut /* OUT: Buffer containing output changeset */ ); /* ** CAPI3REF: Changegroup Handle */ typedef struct sqlite3_changegroup sqlite3_changegroup; /* ** CAPI3REF: Create A New Changegroup Object ** ** An sqlite3_changegroup object is used to combine two or more changesets ** (or patchsets) into a single changeset (or patchset). A single changegroup ** object may combine changesets or patchsets, but not both. The output is ** always in the same format as the input. ** ** If successful, this function returns SQLITE_OK and populates (*pp) with ** a pointer to a new sqlite3_changegroup object before returning. The caller ** should eventually free the returned object using a call to ** sqlite3changegroup_delete(). If an error occurs, an SQLite error code ** (i.e. SQLITE_NOMEM) is returned and *pp is set to NULL. ** ** The usual usage pattern for an sqlite3_changegroup object is as follows: ** **
    **
  • It is created using a call to sqlite3changegroup_new(). ** **
  • Zero or more changesets (or patchsets) are added to the object ** by calling sqlite3changegroup_add(). ** **
  • The result of combining all input changesets together is obtained ** by the application via a call to sqlite3changegroup_output(). ** **
  • The object is deleted using a call to sqlite3changegroup_delete(). **
** ** Any number of calls to add() and output() may be made between the calls to ** new() and delete(), and in any order. ** ** As well as the regular sqlite3changegroup_add() and ** sqlite3changegroup_output() functions, also available are the streaming ** versions sqlite3changegroup_add_strm() and sqlite3changegroup_output_strm(). */ int sqlite3changegroup_new(sqlite3_changegroup **pp); /* ** CAPI3REF: Add A Changeset To A Changegroup ** ** Add all changes within the changeset (or patchset) in buffer pData (size ** nData bytes) to the changegroup. ** ** If the buffer contains a patchset, then all prior calls to this function ** on the same changegroup object must also have specified patchsets. Or, if ** the buffer contains a changeset, so must have the earlier calls to this ** function. Otherwise, SQLITE_ERROR is returned and no changes are added ** to the changegroup. ** ** Rows within the changeset and changegroup are identified by the values in ** their PRIMARY KEY columns. A change in the changeset is considered to ** apply to the same row as a change already present in the changegroup if ** the two rows have the same primary key. ** ** Changes to rows that do not already appear in the changegroup are ** simply copied into it. Or, if both the new changeset and the changegroup ** contain changes that apply to a single row, the final contents of the ** changegroup depends on the type of each change, as follows: ** ** ** ** **
Existing Change New Change Output Change **
INSERT INSERT ** The new change is ignored. This case does not occur if the new ** changeset was recorded immediately after the changesets already ** added to the changegroup. **
INSERT UPDATE ** The INSERT change remains in the changegroup. The values in the ** INSERT change are modified as if the row was inserted by the ** existing change and then updated according to the new change. **
INSERT DELETE ** The existing INSERT is removed from the changegroup. The DELETE is ** not added. **
UPDATE INSERT ** The new change is ignored. This case does not occur if the new ** changeset was recorded immediately after the changesets already ** added to the changegroup. **
UPDATE UPDATE ** The existing UPDATE remains within the changegroup. It is amended ** so that the accompanying values are as if the row was updated once ** by the existing change and then again by the new change. **
UPDATE DELETE ** The existing UPDATE is replaced by the new DELETE within the ** changegroup. **
DELETE INSERT ** If one or more of the column values in the row inserted by the ** new change differ from those in the row deleted by the existing ** change, the existing DELETE is replaced by an UPDATE within the ** changegroup. Otherwise, if the inserted row is exactly the same ** as the deleted row, the existing DELETE is simply discarded. **
DELETE UPDATE ** The new change is ignored. This case does not occur if the new ** changeset was recorded immediately after the changesets already ** added to the changegroup. **
DELETE DELETE ** The new change is ignored. This case does not occur if the new ** changeset was recorded immediately after the changesets already ** added to the changegroup. **
** ** If the new changeset contains changes to a table that is already present ** in the changegroup, then the number of columns and the position of the ** primary key columns for the table must be consistent. If this is not the ** case, this function fails with SQLITE_SCHEMA. If the input changeset ** appears to be corrupt and the corruption is detected, SQLITE_CORRUPT is ** returned. Or, if an out-of-memory condition occurs during processing, this ** function returns SQLITE_NOMEM. In all cases, if an error occurs the ** final contents of the changegroup is undefined. ** ** If no error occurs, SQLITE_OK is returned. */ int sqlite3changegroup_add(sqlite3_changegroup*, int nData, void *pData); /* ** CAPI3REF: Obtain A Composite Changeset From A Changegroup ** ** Obtain a buffer containing a changeset (or patchset) representing the ** current contents of the changegroup. If the inputs to the changegroup ** were themselves changesets, the output is a changeset. Or, if the ** inputs were patchsets, the output is also a patchset. ** ** As with the output of the sqlite3session_changeset() and ** sqlite3session_patchset() functions, all changes related to a single ** table are grouped together in the output of this function. Tables appear ** in the same order as for the very first changeset added to the changegroup. ** If the second or subsequent changesets added to the changegroup contain ** changes for tables that do not appear in the first changeset, they are ** appended onto the end of the output changeset, again in the order in ** which they are first encountered. ** ** If an error occurs, an SQLite error code is returned and the output ** variables (*pnData) and (*ppData) are set to 0. Otherwise, SQLITE_OK ** is returned and the output variables are set to the size of and a ** pointer to the output buffer, respectively. In this case it is the ** responsibility of the caller to eventually free the buffer using a ** call to sqlite3_free(). */ int sqlite3changegroup_output( sqlite3_changegroup*, int *pnData, /* OUT: Size of output buffer in bytes */ void **ppData /* OUT: Pointer to output buffer */ ); /* ** CAPI3REF: Delete A Changegroup Object */ void sqlite3changegroup_delete(sqlite3_changegroup*); /* ** CAPI3REF: Apply A Changeset To A Database ** ** Apply a changeset to a database. This function attempts to update the ** "main" database attached to handle db with the changes found in the ** changeset passed via the second and third arguments. ** ** The fourth argument (xFilter) passed to this function is the "filter ** callback". If it is not NULL, then for each table affected by at least one ** change in the changeset, the filter callback is invoked with ** the table name as the second argument, and a copy of the context pointer ** passed as the sixth argument to this function as the first. If the "filter ** callback" returns zero, then no attempt is made to apply any changes to ** the table. Otherwise, if the return value is non-zero or the xFilter ** argument to this function is NULL, all changes related to the table are ** attempted. ** ** For each table that is not excluded by the filter callback, this function ** tests that the target database contains a compatible table. A table is ** considered compatible if all of the following are true: ** **
    **
  • The table has the same name as the name recorded in the ** changeset, and **
  • The table has the same number of columns as recorded in the ** changeset, and **
  • The table has primary key columns in the same position as ** recorded in the changeset. **
** ** If there is no compatible table, it is not an error, but none of the ** changes associated with the table are applied. A warning message is issued ** via the sqlite3_log() mechanism with the error code SQLITE_SCHEMA. At most ** one such warning is issued for each table in the changeset. ** ** For each change for which there is a compatible table, an attempt is made ** to modify the table contents according to the UPDATE, INSERT or DELETE ** change. If a change cannot be applied cleanly, the conflict handler ** function passed as the fifth argument to sqlite3changeset_apply() may be ** invoked. A description of exactly when the conflict handler is invoked for ** each type of change is below. ** ** Unlike the xFilter argument, xConflict may not be passed NULL. The results ** of passing anything other than a valid function pointer as the xConflict ** argument are undefined. ** ** Each time the conflict handler function is invoked, it must return one ** of [SQLITE_CHANGESET_OMIT], [SQLITE_CHANGESET_ABORT] or ** [SQLITE_CHANGESET_REPLACE]. SQLITE_CHANGESET_REPLACE may only be returned ** if the second argument passed to the conflict handler is either ** SQLITE_CHANGESET_DATA or SQLITE_CHANGESET_CONFLICT. If the conflict-handler ** returns an illegal value, any changes already made are rolled back and ** the call to sqlite3changeset_apply() returns SQLITE_MISUSE. Different ** actions are taken by sqlite3changeset_apply() depending on the value ** returned by each invocation of the conflict-handler function. Refer to ** the documentation for the three ** [SQLITE_CHANGESET_OMIT|available return values] for details. ** **
**
DELETE Changes
** For each DELETE change, this function checks if the target database ** contains a row with the same primary key value (or values) as the ** original row values stored in the changeset. If it does, and the values ** stored in all non-primary key columns also match the values stored in ** the changeset the row is deleted from the target database. ** ** If a row with matching primary key values is found, but one or more of ** the non-primary key fields contains a value different from the original ** row value stored in the changeset, the conflict-handler function is ** invoked with [SQLITE_CHANGESET_DATA] as the second argument. ** ** If no row with matching primary key values is found in the database, ** the conflict-handler function is invoked with [SQLITE_CHANGESET_NOTFOUND] ** passed as the second argument. ** ** If the DELETE operation is attempted, but SQLite returns SQLITE_CONSTRAINT ** (which can only happen if a foreign key constraint is violated), the ** conflict-handler function is invoked with [SQLITE_CHANGESET_CONSTRAINT] ** passed as the second argument. This includes the case where the DELETE ** operation is attempted because an earlier call to the conflict handler ** function returned [SQLITE_CHANGESET_REPLACE]. ** **
INSERT Changes
** For each INSERT change, an attempt is made to insert the new row into ** the database. ** ** If the attempt to insert the row fails because the database already ** contains a row with the same primary key values, the conflict handler ** function is invoked with the second argument set to ** [SQLITE_CHANGESET_CONFLICT]. ** ** If the attempt to insert the row fails because of some other constraint ** violation (e.g. NOT NULL or UNIQUE), the conflict handler function is ** invoked with the second argument set to [SQLITE_CHANGESET_CONSTRAINT]. ** This includes the case where the INSERT operation is re-attempted because ** an earlier call to the conflict handler function returned ** [SQLITE_CHANGESET_REPLACE]. ** **
UPDATE Changes
** For each UPDATE change, this function checks if the target database ** contains a row with the same primary key value (or values) as the ** original row values stored in the changeset. If it does, and the values ** stored in all non-primary key columns also match the values stored in ** the changeset the row is updated within the target database. ** ** If a row with matching primary key values is found, but one or more of ** the non-primary key fields contains a value different from an original ** row value stored in the changeset, the conflict-handler function is ** invoked with [SQLITE_CHANGESET_DATA] as the second argument. Since ** UPDATE changes only contain values for non-primary key fields that are ** to be modified, only those fields need to match the original values to ** avoid the SQLITE_CHANGESET_DATA conflict-handler callback. ** ** If no row with matching primary key values is found in the database, ** the conflict-handler function is invoked with [SQLITE_CHANGESET_NOTFOUND] ** passed as the second argument. ** ** If the UPDATE operation is attempted, but SQLite returns ** SQLITE_CONSTRAINT, the conflict-handler function is invoked with ** [SQLITE_CHANGESET_CONSTRAINT] passed as the second argument. ** This includes the case where the UPDATE operation is attempted after ** an earlier call to the conflict handler function returned ** [SQLITE_CHANGESET_REPLACE]. **
** ** It is safe to execute SQL statements, including those that write to the ** table that the callback related to, from within the xConflict callback. ** This can be used to further customize the applications conflict ** resolution strategy. ** ** All changes made by this function are enclosed in a savepoint transaction. ** If any other error (aside from a constraint failure when attempting to ** write to the target database) occurs, then the savepoint transaction is ** rolled back, restoring the target database to its original state, and an ** SQLite error code returned. */ int sqlite3changeset_apply( sqlite3 *db, /* Apply change to "main" db of this handle */ int nChangeset, /* Size of changeset in bytes */ void *pChangeset, /* Changeset blob */ int(*xFilter)( void *pCtx, /* Copy of sixth arg to _apply() */ const char *zTab /* Table name */ ), int(*xConflict)( void *pCtx, /* Copy of sixth arg to _apply() */ int eConflict, /* DATA, MISSING, CONFLICT, CONSTRAINT */ sqlite3_changeset_iter *p /* Handle describing change and conflict */ ), void *pCtx /* First argument passed to xConflict */ ); /* ** CAPI3REF: Constants Passed To The Conflict Handler ** ** Values that may be passed as the second argument to a conflict-handler. ** **
**
SQLITE_CHANGESET_DATA
** The conflict handler is invoked with CHANGESET_DATA as the second argument ** when processing a DELETE or UPDATE change if a row with the required ** PRIMARY KEY fields is present in the database, but one or more other ** (non primary-key) fields modified by the update do not contain the ** expected "before" values. ** ** The conflicting row, in this case, is the database row with the matching ** primary key. ** **
SQLITE_CHANGESET_NOTFOUND
** The conflict handler is invoked with CHANGESET_NOTFOUND as the second ** argument when processing a DELETE or UPDATE change if a row with the ** required PRIMARY KEY fields is not present in the database. ** ** There is no conflicting row in this case. The results of invoking the ** sqlite3changeset_conflict() API are undefined. ** **
SQLITE_CHANGESET_CONFLICT
** CHANGESET_CONFLICT is passed as the second argument to the conflict ** handler while processing an INSERT change if the operation would result ** in duplicate primary key values. ** ** The conflicting row in this case is the database row with the matching ** primary key. ** **
SQLITE_CHANGESET_FOREIGN_KEY
** If foreign key handling is enabled, and applying a changeset leaves the ** database in a state containing foreign key violations, the conflict ** handler is invoked with CHANGESET_FOREIGN_KEY as the second argument ** exactly once before the changeset is committed. If the conflict handler ** returns CHANGESET_OMIT, the changes, including those that caused the ** foreign key constraint violation, are committed. Or, if it returns ** CHANGESET_ABORT, the changeset is rolled back. ** ** No current or conflicting row information is provided. The only function ** it is possible to call on the supplied sqlite3_changeset_iter handle ** is sqlite3changeset_fk_conflicts(). ** **
SQLITE_CHANGESET_CONSTRAINT
** If any other constraint violation occurs while applying a change (i.e. ** a UNIQUE, CHECK or NOT NULL constraint), the conflict handler is ** invoked with CHANGESET_CONSTRAINT as the second argument. ** ** There is no conflicting row in this case. The results of invoking the ** sqlite3changeset_conflict() API are undefined. ** **
*/ #define SQLITE_CHANGESET_DATA 1 #define SQLITE_CHANGESET_NOTFOUND 2 #define SQLITE_CHANGESET_CONFLICT 3 #define SQLITE_CHANGESET_CONSTRAINT 4 #define SQLITE_CHANGESET_FOREIGN_KEY 5 /* ** CAPI3REF: Constants Returned By The Conflict Handler ** ** A conflict handler callback must return one of the following three values. ** **
**
SQLITE_CHANGESET_OMIT
** If a conflict handler returns this value no special action is taken. The ** change that caused the conflict is not applied. The session module ** continues to the next change in the changeset. ** **
SQLITE_CHANGESET_REPLACE
** This value may only be returned if the second argument to the conflict ** handler was SQLITE_CHANGESET_DATA or SQLITE_CHANGESET_CONFLICT. If this ** is not the case, any changes applied so far are rolled back and the ** call to sqlite3changeset_apply() returns SQLITE_MISUSE. ** ** If CHANGESET_REPLACE is returned by an SQLITE_CHANGESET_DATA conflict ** handler, then the conflicting row is either updated or deleted, depending ** on the type of change. ** ** If CHANGESET_REPLACE is returned by an SQLITE_CHANGESET_CONFLICT conflict ** handler, then the conflicting row is removed from the database and a ** second attempt to apply the change is made. If this second attempt fails, ** the original row is restored to the database before continuing. ** **
SQLITE_CHANGESET_ABORT
** If this value is returned, any changes applied so far are rolled back ** and the call to sqlite3changeset_apply() returns SQLITE_ABORT. **
*/ #define SQLITE_CHANGESET_OMIT 0 #define SQLITE_CHANGESET_REPLACE 1 #define SQLITE_CHANGESET_ABORT 2 /* ** CAPI3REF: Streaming Versions of API functions. ** ** The six streaming API xxx_strm() functions serve similar purposes to the ** corresponding non-streaming API functions: ** ** ** **
Streaming functionNon-streaming equivalent
sqlite3changeset_apply_str[sqlite3changeset_apply] **
sqlite3changeset_concat_str[sqlite3changeset_concat] **
sqlite3changeset_invert_str[sqlite3changeset_invert] **
sqlite3changeset_start_str[sqlite3changeset_start] **
sqlite3session_changeset_str[sqlite3session_changeset] **
sqlite3session_patchset_str[sqlite3session_patchset] **
** ** Non-streaming functions that accept changesets (or patchsets) as input ** require that the entire changeset be stored in a single buffer in memory. ** Similarly, those that return a changeset or patchset do so by returning ** a pointer to a single large buffer allocated using sqlite3_malloc(). ** Normally this is convenient. However, if an application running in a ** low-memory environment is required to handle very large changesets, the ** large contiguous memory allocations required can become onerous. ** ** In order to avoid this problem, instead of a single large buffer, input ** is passed to a streaming API functions by way of a callback function that ** the sessions module invokes to incrementally request input data as it is ** required. In all cases, a pair of API function parameters such as ** **
**        int nChangeset,
**        void *pChangeset,
**  
** ** Is replaced by: ** **
**        int (*xInput)(void *pIn, void *pData, int *pnData),
**        void *pIn,
**  
** ** Each time the xInput callback is invoked by the sessions module, the first ** argument passed is a copy of the supplied pIn context pointer. The second ** argument, pData, points to a buffer (*pnData) bytes in size. Assuming no ** error occurs the xInput method should copy up to (*pnData) bytes of data ** into the buffer and set (*pnData) to the actual number of bytes copied ** before returning SQLITE_OK. If the input is completely exhausted, (*pnData) ** should be set to zero to indicate this. Or, if an error occurs, an SQLite ** error code should be returned. In all cases, if an xInput callback returns ** an error, all processing is abandoned and the streaming API function ** returns a copy of the error code to the caller. ** ** In the case of sqlite3changeset_start_strm(), the xInput callback may be ** invoked by the sessions module at any point during the lifetime of the ** iterator. If such an xInput callback returns an error, the iterator enters ** an error state, whereby all subsequent calls to iterator functions ** immediately fail with the same error code as returned by xInput. ** ** Similarly, streaming API functions that return changesets (or patchsets) ** return them in chunks by way of a callback function instead of via a ** pointer to a single large buffer. In this case, a pair of parameters such ** as: ** **
**        int *pnChangeset,
**        void **ppChangeset,
**  
** ** Is replaced by: ** **
**        int (*xOutput)(void *pOut, const void *pData, int nData),
**        void *pOut
**  
** ** The xOutput callback is invoked zero or more times to return data to ** the application. The first parameter passed to each call is a copy of the ** pOut pointer supplied by the application. The second parameter, pData, ** points to a buffer nData bytes in size containing the chunk of output ** data being returned. If the xOutput callback successfully processes the ** supplied data, it should return SQLITE_OK to indicate success. Otherwise, ** it should return some other SQLite error code. In this case processing ** is immediately abandoned and the streaming API function returns a copy ** of the xOutput error code to the application. ** ** The sessions module never invokes an xOutput callback with the third ** parameter set to a value less than or equal to zero. Other than this, ** no guarantees are made as to the size of the chunks of data returned. */ int sqlite3changeset_apply_strm( sqlite3 *db, /* Apply change to "main" db of this handle */ int (*xInput)(void *pIn, void *pData, int *pnData), /* Input function */ void *pIn, /* First arg for xInput */ int(*xFilter)( void *pCtx, /* Copy of sixth arg to _apply() */ const char *zTab /* Table name */ ), int(*xConflict)( void *pCtx, /* Copy of sixth arg to _apply() */ int eConflict, /* DATA, MISSING, CONFLICT, CONSTRAINT */ sqlite3_changeset_iter *p /* Handle describing change and conflict */ ), void *pCtx /* First argument passed to xConflict */ ); int sqlite3changeset_concat_strm( int (*xInputA)(void *pIn, void *pData, int *pnData), void *pInA, int (*xInputB)(void *pIn, void *pData, int *pnData), void *pInB, int (*xOutput)(void *pOut, const void *pData, int nData), void *pOut ); int sqlite3changeset_invert_strm( int (*xInput)(void *pIn, void *pData, int *pnData), void *pIn, int (*xOutput)(void *pOut, const void *pData, int nData), void *pOut ); int sqlite3changeset_start_strm( sqlite3_changeset_iter **pp, int (*xInput)(void *pIn, void *pData, int *pnData), void *pIn ); int sqlite3session_changeset_strm( sqlite3_session *pSession, int (*xOutput)(void *pOut, const void *pData, int nData), void *pOut ); int sqlite3session_patchset_strm( sqlite3_session *pSession, int (*xOutput)(void *pOut, const void *pData, int nData), void *pOut ); int sqlite3changegroup_add_strm(sqlite3_changegroup*, int (*xInput)(void *pIn, void *pData, int *pnData), void *pIn ); int sqlite3changegroup_output_strm(sqlite3_changegroup*, int (*xOutput)(void *pOut, const void *pData, int nData), void *pOut ); /* ** Make sure we can call this stuff from C++. */ #ifdef __cplusplus } #endif #endif /* !defined(__SQLITESESSION_H_) && defined(SQLITE_ENABLE_SESSION) */ /******** End of sqlite3session.h *********/ /******** Begin file fts5.h *********/ /* ** 2014 May 31 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ****************************************************************************** ** ** Interfaces to extend FTS5. Using the interfaces defined in this file, ** FTS5 may be extended with: ** ** * custom tokenizers, and ** * custom auxiliary functions. */ #ifndef _FTS5_H #define _FTS5_H #ifdef __cplusplus extern "C" { #endif /************************************************************************* ** CUSTOM AUXILIARY FUNCTIONS ** ** Virtual table implementations may overload SQL functions by implementing ** the sqlite3_module.xFindFunction() method. */ typedef struct Fts5ExtensionApi Fts5ExtensionApi; typedef struct Fts5Context Fts5Context; typedef struct Fts5PhraseIter Fts5PhraseIter; typedef void (*fts5_extension_function)( const Fts5ExtensionApi *pApi, /* API offered by current FTS version */ Fts5Context *pFts, /* First arg to pass to pApi functions */ sqlite3_context *pCtx, /* Context for returning result/error */ int nVal, /* Number of values in apVal[] array */ sqlite3_value **apVal /* Array of trailing arguments */ ); struct Fts5PhraseIter { const unsigned char *a; const unsigned char *b; }; /* ** EXTENSION API FUNCTIONS ** ** xUserData(pFts): ** Return a copy of the context pointer the extension function was ** registered with. ** ** xColumnTotalSize(pFts, iCol, pnToken): ** If parameter iCol is less than zero, set output variable *pnToken ** to the total number of tokens in the FTS5 table. Or, if iCol is ** non-negative but less than the number of columns in the table, return ** the total number of tokens in column iCol, considering all rows in ** the FTS5 table. ** ** If parameter iCol is greater than or equal to the number of columns ** in the table, SQLITE_RANGE is returned. Or, if an error occurs (e.g. ** an OOM condition or IO error), an appropriate SQLite error code is ** returned. ** ** xColumnCount(pFts): ** Return the number of columns in the table. ** ** xColumnSize(pFts, iCol, pnToken): ** If parameter iCol is less than zero, set output variable *pnToken ** to the total number of tokens in the current row. Or, if iCol is ** non-negative but less than the number of columns in the table, set ** *pnToken to the number of tokens in column iCol of the current row. ** ** If parameter iCol is greater than or equal to the number of columns ** in the table, SQLITE_RANGE is returned. Or, if an error occurs (e.g. ** an OOM condition or IO error), an appropriate SQLite error code is ** returned. ** ** This function may be quite inefficient if used with an FTS5 table ** created with the "columnsize=0" option. ** ** xColumnText: ** This function attempts to retrieve the text of column iCol of the ** current document. If successful, (*pz) is set to point to a buffer ** containing the text in utf-8 encoding, (*pn) is set to the size in bytes ** (not characters) of the buffer and SQLITE_OK is returned. Otherwise, ** if an error occurs, an SQLite error code is returned and the final values ** of (*pz) and (*pn) are undefined. ** ** xPhraseCount: ** Returns the number of phrases in the current query expression. ** ** xPhraseSize: ** Returns the number of tokens in phrase iPhrase of the query. Phrases ** are numbered starting from zero. ** ** xInstCount: ** Set *pnInst to the total number of occurrences of all phrases within ** the query within the current row. Return SQLITE_OK if successful, or ** an error code (i.e. SQLITE_NOMEM) if an error occurs. ** ** This API can be quite slow if used with an FTS5 table created with the ** "detail=none" or "detail=column" option. If the FTS5 table is created ** with either "detail=none" or "detail=column" and "content=" option ** (i.e. if it is a contentless table), then this API always returns 0. ** ** xInst: ** Query for the details of phrase match iIdx within the current row. ** Phrase matches are numbered starting from zero, so the iIdx argument ** should be greater than or equal to zero and smaller than the value ** output by xInstCount(). ** ** Usually, output parameter *piPhrase is set to the phrase number, *piCol ** to the column in which it occurs and *piOff the token offset of the ** first token of the phrase. The exception is if the table was created ** with the offsets=0 option specified. In this case *piOff is always ** set to -1. ** ** Returns SQLITE_OK if successful, or an error code (i.e. SQLITE_NOMEM) ** if an error occurs. ** ** This API can be quite slow if used with an FTS5 table created with the ** "detail=none" or "detail=column" option. ** ** xRowid: ** Returns the rowid of the current row. ** ** xTokenize: ** Tokenize text using the tokenizer belonging to the FTS5 table. ** ** xQueryPhrase(pFts5, iPhrase, pUserData, xCallback): ** This API function is used to query the FTS table for phrase iPhrase ** of the current query. Specifically, a query equivalent to: ** ** ... FROM ftstable WHERE ftstable MATCH $p ORDER BY rowid ** ** with $p set to a phrase equivalent to the phrase iPhrase of the ** current query is executed. Any column filter that applies to ** phrase iPhrase of the current query is included in $p. For each ** row visited, the callback function passed as the fourth argument ** is invoked. The context and API objects passed to the callback ** function may be used to access the properties of each matched row. ** Invoking Api.xUserData() returns a copy of the pointer passed as ** the third argument to pUserData. ** ** If the callback function returns any value other than SQLITE_OK, the ** query is abandoned and the xQueryPhrase function returns immediately. ** If the returned value is SQLITE_DONE, xQueryPhrase returns SQLITE_OK. ** Otherwise, the error code is propagated upwards. ** ** If the query runs to completion without incident, SQLITE_OK is returned. ** Or, if some error occurs before the query completes or is aborted by ** the callback, an SQLite error code is returned. ** ** ** xSetAuxdata(pFts5, pAux, xDelete) ** ** Save the pointer passed as the second argument as the extension functions ** "auxiliary data". The pointer may then be retrieved by the current or any ** future invocation of the same fts5 extension function made as part of ** of the same MATCH query using the xGetAuxdata() API. ** ** Each extension function is allocated a single auxiliary data slot for ** each FTS query (MATCH expression). If the extension function is invoked ** more than once for a single FTS query, then all invocations share a ** single auxiliary data context. ** ** If there is already an auxiliary data pointer when this function is ** invoked, then it is replaced by the new pointer. If an xDelete callback ** was specified along with the original pointer, it is invoked at this ** point. ** ** The xDelete callback, if one is specified, is also invoked on the ** auxiliary data pointer after the FTS5 query has finished. ** ** If an error (e.g. an OOM condition) occurs within this function, an ** the auxiliary data is set to NULL and an error code returned. If the ** xDelete parameter was not NULL, it is invoked on the auxiliary data ** pointer before returning. ** ** ** xGetAuxdata(pFts5, bClear) ** ** Returns the current auxiliary data pointer for the fts5 extension ** function. See the xSetAuxdata() method for details. ** ** If the bClear argument is non-zero, then the auxiliary data is cleared ** (set to NULL) before this function returns. In this case the xDelete, ** if any, is not invoked. ** ** ** xRowCount(pFts5, pnRow) ** ** This function is used to retrieve the total number of rows in the table. ** In other words, the same value that would be returned by: ** ** SELECT count(*) FROM ftstable; ** ** xPhraseFirst() ** This function is used, along with type Fts5PhraseIter and the xPhraseNext ** method, to iterate through all instances of a single query phrase within ** the current row. This is the same information as is accessible via the ** xInstCount/xInst APIs. While the xInstCount/xInst APIs are more convenient ** to use, this API may be faster under some circumstances. To iterate ** through instances of phrase iPhrase, use the following code: ** ** Fts5PhraseIter iter; ** int iCol, iOff; ** for(pApi->xPhraseFirst(pFts, iPhrase, &iter, &iCol, &iOff); ** iCol>=0; ** pApi->xPhraseNext(pFts, &iter, &iCol, &iOff) ** ){ ** // An instance of phrase iPhrase at offset iOff of column iCol ** } ** ** The Fts5PhraseIter structure is defined above. Applications should not ** modify this structure directly - it should only be used as shown above ** with the xPhraseFirst() and xPhraseNext() API methods (and by ** xPhraseFirstColumn() and xPhraseNextColumn() as illustrated below). ** ** This API can be quite slow if used with an FTS5 table created with the ** "detail=none" or "detail=column" option. If the FTS5 table is created ** with either "detail=none" or "detail=column" and "content=" option ** (i.e. if it is a contentless table), then this API always iterates ** through an empty set (all calls to xPhraseFirst() set iCol to -1). ** ** xPhraseNext() ** See xPhraseFirst above. ** ** xPhraseFirstColumn() ** This function and xPhraseNextColumn() are similar to the xPhraseFirst() ** and xPhraseNext() APIs described above. The difference is that instead ** of iterating through all instances of a phrase in the current row, these ** APIs are used to iterate through the set of columns in the current row ** that contain one or more instances of a specified phrase. For example: ** ** Fts5PhraseIter iter; ** int iCol; ** for(pApi->xPhraseFirstColumn(pFts, iPhrase, &iter, &iCol); ** iCol>=0; ** pApi->xPhraseNextColumn(pFts, &iter, &iCol) ** ){ ** // Column iCol contains at least one instance of phrase iPhrase ** } ** ** This API can be quite slow if used with an FTS5 table created with the ** "detail=none" option. If the FTS5 table is created with either ** "detail=none" "content=" option (i.e. if it is a contentless table), ** then this API always iterates through an empty set (all calls to ** xPhraseFirstColumn() set iCol to -1). ** ** The information accessed using this API and its companion ** xPhraseFirstColumn() may also be obtained using xPhraseFirst/xPhraseNext ** (or xInst/xInstCount). The chief advantage of this API is that it is ** significantly more efficient than those alternatives when used with ** "detail=column" tables. ** ** xPhraseNextColumn() ** See xPhraseFirstColumn above. */ struct Fts5ExtensionApi { int iVersion; /* Currently always set to 3 */ void *(*xUserData)(Fts5Context*); int (*xColumnCount)(Fts5Context*); int (*xRowCount)(Fts5Context*, sqlite3_int64 *pnRow); int (*xColumnTotalSize)(Fts5Context*, int iCol, sqlite3_int64 *pnToken); int (*xTokenize)(Fts5Context*, const char *pText, int nText, /* Text to tokenize */ void *pCtx, /* Context passed to xToken() */ int (*xToken)(void*, int, const char*, int, int, int) /* Callback */ ); int (*xPhraseCount)(Fts5Context*); int (*xPhraseSize)(Fts5Context*, int iPhrase); int (*xInstCount)(Fts5Context*, int *pnInst); int (*xInst)(Fts5Context*, int iIdx, int *piPhrase, int *piCol, int *piOff); sqlite3_int64 (*xRowid)(Fts5Context*); int (*xColumnText)(Fts5Context*, int iCol, const char **pz, int *pn); int (*xColumnSize)(Fts5Context*, int iCol, int *pnToken); int (*xQueryPhrase)(Fts5Context*, int iPhrase, void *pUserData, int(*)(const Fts5ExtensionApi*,Fts5Context*,void*) ); int (*xSetAuxdata)(Fts5Context*, void *pAux, void(*xDelete)(void*)); void *(*xGetAuxdata)(Fts5Context*, int bClear); int (*xPhraseFirst)(Fts5Context*, int iPhrase, Fts5PhraseIter*, int*, int*); void (*xPhraseNext)(Fts5Context*, Fts5PhraseIter*, int *piCol, int *piOff); int (*xPhraseFirstColumn)(Fts5Context*, int iPhrase, Fts5PhraseIter*, int*); void (*xPhraseNextColumn)(Fts5Context*, Fts5PhraseIter*, int *piCol); }; /* ** CUSTOM AUXILIARY FUNCTIONS *************************************************************************/ /************************************************************************* ** CUSTOM TOKENIZERS ** ** Applications may also register custom tokenizer types. A tokenizer ** is registered by providing fts5 with a populated instance of the ** following structure. All structure methods must be defined, setting ** any member of the fts5_tokenizer struct to NULL leads to undefined ** behaviour. The structure methods are expected to function as follows: ** ** xCreate: ** This function is used to allocate and initialize a tokenizer instance. ** A tokenizer instance is required to actually tokenize text. ** ** The first argument passed to this function is a copy of the (void*) ** pointer provided by the application when the fts5_tokenizer object ** was registered with FTS5 (the third argument to xCreateTokenizer()). ** The second and third arguments are an array of nul-terminated strings ** containing the tokenizer arguments, if any, specified following the ** tokenizer name as part of the CREATE VIRTUAL TABLE statement used ** to create the FTS5 table. ** ** The final argument is an output variable. If successful, (*ppOut) ** should be set to point to the new tokenizer handle and SQLITE_OK ** returned. If an error occurs, some value other than SQLITE_OK should ** be returned. In this case, fts5 assumes that the final value of *ppOut ** is undefined. ** ** xDelete: ** This function is invoked to delete a tokenizer handle previously ** allocated using xCreate(). Fts5 guarantees that this function will ** be invoked exactly once for each successful call to xCreate(). ** ** xTokenize: ** This function is expected to tokenize the nText byte string indicated ** by argument pText. pText may or may not be nul-terminated. The first ** argument passed to this function is a pointer to an Fts5Tokenizer object ** returned by an earlier call to xCreate(). ** ** The second argument indicates the reason that FTS5 is requesting ** tokenization of the supplied text. This is always one of the following ** four values: ** **
  • FTS5_TOKENIZE_DOCUMENT - A document is being inserted into ** or removed from the FTS table. The tokenizer is being invoked to ** determine the set of tokens to add to (or delete from) the ** FTS index. ** **
  • FTS5_TOKENIZE_QUERY - A MATCH query is being executed ** against the FTS index. The tokenizer is being called to tokenize ** a bareword or quoted string specified as part of the query. ** **
  • (FTS5_TOKENIZE_QUERY | FTS5_TOKENIZE_PREFIX) - Same as ** FTS5_TOKENIZE_QUERY, except that the bareword or quoted string is ** followed by a "*" character, indicating that the last token ** returned by the tokenizer will be treated as a token prefix. ** **
  • FTS5_TOKENIZE_AUX - The tokenizer is being invoked to ** satisfy an fts5_api.xTokenize() request made by an auxiliary ** function. Or an fts5_api.xColumnSize() request made by the same ** on a columnsize=0 database. **
** ** For each token in the input string, the supplied callback xToken() must ** be invoked. The first argument to it should be a copy of the pointer ** passed as the second argument to xTokenize(). The third and fourth ** arguments are a pointer to a buffer containing the token text, and the ** size of the token in bytes. The 4th and 5th arguments are the byte offsets ** of the first byte of and first byte immediately following the text from ** which the token is derived within the input. ** ** The second argument passed to the xToken() callback ("tflags") should ** normally be set to 0. The exception is if the tokenizer supports ** synonyms. In this case see the discussion below for details. ** ** FTS5 assumes the xToken() callback is invoked for each token in the ** order that they occur within the input text. ** ** If an xToken() callback returns any value other than SQLITE_OK, then ** the tokenization should be abandoned and the xTokenize() method should ** immediately return a copy of the xToken() return value. Or, if the ** input buffer is exhausted, xTokenize() should return SQLITE_OK. Finally, ** if an error occurs with the xTokenize() implementation itself, it ** may abandon the tokenization and return any error code other than ** SQLITE_OK or SQLITE_DONE. ** ** SYNONYM SUPPORT ** ** Custom tokenizers may also support synonyms. Consider a case in which a ** user wishes to query for a phrase such as "first place". Using the ** built-in tokenizers, the FTS5 query 'first + place' will match instances ** of "first place" within the document set, but not alternative forms ** such as "1st place". In some applications, it would be better to match ** all instances of "first place" or "1st place" regardless of which form ** the user specified in the MATCH query text. ** ** There are several ways to approach this in FTS5: ** **
  1. By mapping all synonyms to a single token. In this case, the ** In the above example, this means that the tokenizer returns the ** same token for inputs "first" and "1st". Say that token is in ** fact "first", so that when the user inserts the document "I won ** 1st place" entries are added to the index for tokens "i", "won", ** "first" and "place". If the user then queries for '1st + place', ** the tokenizer substitutes "first" for "1st" and the query works ** as expected. ** **
  2. By adding multiple synonyms for a single term to the FTS index. ** In this case, when tokenizing query text, the tokenizer may ** provide multiple synonyms for a single term within the document. ** FTS5 then queries the index for each synonym individually. For ** example, faced with the query: ** ** ** ... MATCH 'first place' ** ** the tokenizer offers both "1st" and "first" as synonyms for the ** first token in the MATCH query and FTS5 effectively runs a query ** similar to: ** ** ** ... MATCH '(first OR 1st) place' ** ** except that, for the purposes of auxiliary functions, the query ** still appears to contain just two phrases - "(first OR 1st)" ** being treated as a single phrase. ** **
  3. By adding multiple synonyms for a single term to the FTS index. ** Using this method, when tokenizing document text, the tokenizer ** provides multiple synonyms for each token. So that when a ** document such as "I won first place" is tokenized, entries are ** added to the FTS index for "i", "won", "first", "1st" and ** "place". ** ** This way, even if the tokenizer does not provide synonyms ** when tokenizing query text (it should not - to do would be ** inefficient), it doesn't matter if the user queries for ** 'first + place' or '1st + place', as there are entires in the ** FTS index corresponding to both forms of the first token. **
** ** Whether it is parsing document or query text, any call to xToken that ** specifies a tflags argument with the FTS5_TOKEN_COLOCATED bit ** is considered to supply a synonym for the previous token. For example, ** when parsing the document "I won first place", a tokenizer that supports ** synonyms would call xToken() 5 times, as follows: ** ** ** xToken(pCtx, 0, "i", 1, 0, 1); ** xToken(pCtx, 0, "won", 3, 2, 5); ** xToken(pCtx, 0, "first", 5, 6, 11); ** xToken(pCtx, FTS5_TOKEN_COLOCATED, "1st", 3, 6, 11); ** xToken(pCtx, 0, "place", 5, 12, 17); ** ** ** It is an error to specify the FTS5_TOKEN_COLOCATED flag the first time ** xToken() is called. Multiple synonyms may be specified for a single token ** by making multiple calls to xToken(FTS5_TOKEN_COLOCATED) in sequence. ** There is no limit to the number of synonyms that may be provided for a ** single token. ** ** In many cases, method (1) above is the best approach. It does not add ** extra data to the FTS index or require FTS5 to query for multiple terms, ** so it is efficient in terms of disk space and query speed. However, it ** does not support prefix queries very well. If, as suggested above, the ** token "first" is subsituted for "1st" by the tokenizer, then the query: ** ** ** ... MATCH '1s*' ** ** will not match documents that contain the token "1st" (as the tokenizer ** will probably not map "1s" to any prefix of "first"). ** ** For full prefix support, method (3) may be preferred. In this case, ** because the index contains entries for both "first" and "1st", prefix ** queries such as 'fi*' or '1s*' will match correctly. However, because ** extra entries are added to the FTS index, this method uses more space ** within the database. ** ** Method (2) offers a midpoint between (1) and (3). Using this method, ** a query such as '1s*' will match documents that contain the literal ** token "1st", but not "first" (assuming the tokenizer is not able to ** provide synonyms for prefixes). However, a non-prefix query like '1st' ** will match against "1st" and "first". This method does not require ** extra disk space, as no extra entries are added to the FTS index. ** On the other hand, it may require more CPU cycles to run MATCH queries, ** as separate queries of the FTS index are required for each synonym. ** ** When using methods (2) or (3), it is important that the tokenizer only ** provide synonyms when tokenizing document text (method (2)) or query ** text (method (3)), not both. Doing so will not cause any errors, but is ** inefficient. */ typedef struct Fts5Tokenizer Fts5Tokenizer; typedef struct fts5_tokenizer fts5_tokenizer; struct fts5_tokenizer { int (*xCreate)(void*, const char **azArg, int nArg, Fts5Tokenizer **ppOut); void (*xDelete)(Fts5Tokenizer*); int (*xTokenize)(Fts5Tokenizer*, void *pCtx, int flags, /* Mask of FTS5_TOKENIZE_* flags */ const char *pText, int nText, int (*xToken)( void *pCtx, /* Copy of 2nd argument to xTokenize() */ int tflags, /* Mask of FTS5_TOKEN_* flags */ const char *pToken, /* Pointer to buffer containing token */ int nToken, /* Size of token in bytes */ int iStart, /* Byte offset of token within input text */ int iEnd /* Byte offset of end of token within input text */ ) ); }; /* Flags that may be passed as the third argument to xTokenize() */ #define FTS5_TOKENIZE_QUERY 0x0001 #define FTS5_TOKENIZE_PREFIX 0x0002 #define FTS5_TOKENIZE_DOCUMENT 0x0004 #define FTS5_TOKENIZE_AUX 0x0008 /* Flags that may be passed by the tokenizer implementation back to FTS5 ** as the third argument to the supplied xToken callback. */ #define FTS5_TOKEN_COLOCATED 0x0001 /* Same position as prev. token */ /* ** END OF CUSTOM TOKENIZERS *************************************************************************/ /************************************************************************* ** FTS5 EXTENSION REGISTRATION API */ typedef struct fts5_api fts5_api; struct fts5_api { int iVersion; /* Currently always set to 2 */ /* Create a new tokenizer */ int (*xCreateTokenizer)( fts5_api *pApi, const char *zName, void *pContext, fts5_tokenizer *pTokenizer, void (*xDestroy)(void*) ); /* Find an existing tokenizer */ int (*xFindTokenizer)( fts5_api *pApi, const char *zName, void **ppContext, fts5_tokenizer *pTokenizer ); /* Create a new auxiliary function */ int (*xCreateFunction)( fts5_api *pApi, const char *zName, void *pContext, fts5_extension_function xFunction, void (*xDestroy)(void*) ); }; /* ** END OF REGISTRATION API *************************************************************************/ #ifdef __cplusplus } /* end of the 'extern "C"' block */ #endif #endif /* _FTS5_H */ /******** End of fts5.h *********/ heimdal-7.5.0/lib/sqlite/Makefile.am0000644000175000017500000000046013026237312015354 0ustar niknik# $Id$ include $(top_srcdir)/Makefile.am.common if ENABLE_PTHREAD_SUPPORT AM_CPPFLAGS += -DSQLITE_THREADSAFE=1 endif lib_LTLIBRARIES = libheimsqlite.la noinst_HEADERS = sqlite3.h sqlite3ext.h libheimsqlite_la_SOURCES = sqlite3.c libheimsqlite_la_LIBADD = $(PTHREAD_LIBADD) EXTRA_DIST = NTMakefile heimdal-7.5.0/lib/sqlite/Makefile.in0000644000175000017500000007755213212444523015406 0ustar niknik# Makefile.in generated by automake 1.15.1 from Makefile.am. # @configure_input@ # Copyright (C) 1994-2017 Free Software Foundation, Inc. # This Makefile.in is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, # with or without modifications, as long as this notice is preserved. # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY, to the extent permitted by law; without # even the implied warranty of MERCHANTABILITY or FITNESS FOR A # PARTICULAR PURPOSE. @SET_MAKE@ # $Id$ # $Id$ # $Id$ VPATH = @srcdir@ am__is_gnu_make = { \ if test -z '$(MAKELEVEL)'; then \ false; \ elif test -n '$(MAKE_HOST)'; then \ true; \ elif test -n '$(MAKE_VERSION)' && test -n '$(CURDIR)'; then \ true; \ else \ false; \ fi; \ } am__make_running_with_option = \ case $${target_option-} in \ ?) ;; \ *) echo "am__make_running_with_option: internal error: invalid" \ "target option '$${target_option-}' specified" >&2; \ exit 1;; \ esac; \ has_opt=no; \ sane_makeflags=$$MAKEFLAGS; \ if $(am__is_gnu_make); then \ sane_makeflags=$$MFLAGS; \ else \ case $$MAKEFLAGS in \ *\\[\ \ ]*) \ bs=\\; \ sane_makeflags=`printf '%s\n' "$$MAKEFLAGS" \ | sed "s/$$bs$$bs[$$bs $$bs ]*//g"`;; \ esac; \ fi; \ skip_next=no; \ strip_trailopt () \ { \ flg=`printf '%s\n' "$$flg" | sed "s/$$1.*$$//"`; \ }; \ for flg in $$sane_makeflags; do \ test $$skip_next = yes && { skip_next=no; continue; }; \ case $$flg in \ *=*|--*) continue;; \ -*I) strip_trailopt 'I'; skip_next=yes;; \ -*I?*) strip_trailopt 'I';; \ -*O) strip_trailopt 'O'; skip_next=yes;; \ -*O?*) strip_trailopt 'O';; \ -*l) strip_trailopt 'l'; skip_next=yes;; \ -*l?*) strip_trailopt 'l';; \ -[dEDm]) skip_next=yes;; \ -[JT]) skip_next=yes;; \ esac; \ case $$flg in \ *$$target_option*) has_opt=yes; break;; \ esac; \ done; \ test $$has_opt = yes am__make_dryrun = (target_option=n; $(am__make_running_with_option)) am__make_keepgoing = (target_option=k; $(am__make_running_with_option)) pkgdatadir = $(datadir)/@PACKAGE@ pkgincludedir = $(includedir)/@PACKAGE@ pkglibdir = $(libdir)/@PACKAGE@ pkglibexecdir = $(libexecdir)/@PACKAGE@ am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd install_sh_DATA = $(install_sh) -c -m 644 install_sh_PROGRAM = $(install_sh) -c install_sh_SCRIPT = $(install_sh) -c INSTALL_HEADER = $(INSTALL_DATA) transform = $(program_transform_name) NORMAL_INSTALL = : PRE_INSTALL = : POST_INSTALL = : NORMAL_UNINSTALL = : PRE_UNINSTALL = : POST_UNINSTALL = : build_triplet = @build@ host_triplet = @host@ @ENABLE_PTHREAD_SUPPORT_TRUE@am__append_1 = -DSQLITE_THREADSAFE=1 subdir = lib/sqlite ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 am__aclocal_m4_deps = $(top_srcdir)/cf/aix.m4 \ $(top_srcdir)/cf/auth-modules.m4 \ $(top_srcdir)/cf/broken-getaddrinfo.m4 \ $(top_srcdir)/cf/broken-glob.m4 \ $(top_srcdir)/cf/broken-realloc.m4 \ $(top_srcdir)/cf/broken-snprintf.m4 $(top_srcdir)/cf/broken.m4 \ $(top_srcdir)/cf/broken2.m4 $(top_srcdir)/cf/c-attribute.m4 \ $(top_srcdir)/cf/capabilities.m4 \ $(top_srcdir)/cf/check-compile-et.m4 \ $(top_srcdir)/cf/check-getpwnam_r-posix.m4 \ $(top_srcdir)/cf/check-man.m4 \ $(top_srcdir)/cf/check-netinet-ip-and-tcp.m4 \ $(top_srcdir)/cf/check-type-extra.m4 \ $(top_srcdir)/cf/check-var.m4 $(top_srcdir)/cf/crypto.m4 \ $(top_srcdir)/cf/db.m4 $(top_srcdir)/cf/destdirs.m4 \ $(top_srcdir)/cf/dispatch.m4 $(top_srcdir)/cf/dlopen.m4 \ $(top_srcdir)/cf/find-func-no-libs.m4 \ $(top_srcdir)/cf/find-func-no-libs2.m4 \ $(top_srcdir)/cf/find-func.m4 \ $(top_srcdir)/cf/find-if-not-broken.m4 \ $(top_srcdir)/cf/framework-security.m4 \ $(top_srcdir)/cf/have-struct-field.m4 \ $(top_srcdir)/cf/have-type.m4 $(top_srcdir)/cf/irix.m4 \ $(top_srcdir)/cf/krb-bigendian.m4 \ $(top_srcdir)/cf/krb-func-getlogin.m4 \ $(top_srcdir)/cf/krb-ipv6.m4 $(top_srcdir)/cf/krb-prog-ln-s.m4 \ $(top_srcdir)/cf/krb-prog-perl.m4 \ $(top_srcdir)/cf/krb-readline.m4 \ $(top_srcdir)/cf/krb-struct-spwd.m4 \ $(top_srcdir)/cf/krb-struct-winsize.m4 \ $(top_srcdir)/cf/largefile.m4 $(top_srcdir)/cf/libtool.m4 \ $(top_srcdir)/cf/ltoptions.m4 $(top_srcdir)/cf/ltsugar.m4 \ $(top_srcdir)/cf/ltversion.m4 $(top_srcdir)/cf/lt~obsolete.m4 \ $(top_srcdir)/cf/mips-abi.m4 $(top_srcdir)/cf/misc.m4 \ $(top_srcdir)/cf/need-proto.m4 $(top_srcdir)/cf/osfc2.m4 \ $(top_srcdir)/cf/otp.m4 $(top_srcdir)/cf/pkg.m4 \ $(top_srcdir)/cf/proto-compat.m4 $(top_srcdir)/cf/pthreads.m4 \ $(top_srcdir)/cf/resolv.m4 $(top_srcdir)/cf/retsigtype.m4 \ $(top_srcdir)/cf/roken-frag.m4 \ $(top_srcdir)/cf/socket-wrapper.m4 $(top_srcdir)/cf/sunos.m4 \ $(top_srcdir)/cf/telnet.m4 $(top_srcdir)/cf/test-package.m4 \ $(top_srcdir)/cf/version-script.m4 $(top_srcdir)/cf/wflags.m4 \ $(top_srcdir)/cf/win32.m4 $(top_srcdir)/cf/with-all.m4 \ $(top_srcdir)/acinclude.m4 $(top_srcdir)/configure.ac am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \ $(ACLOCAL_M4) DIST_COMMON = $(srcdir)/Makefile.am $(noinst_HEADERS) \ $(am__DIST_COMMON) mkinstalldirs = $(install_sh) -d CONFIG_HEADER = $(top_builddir)/include/config.h CONFIG_CLEAN_FILES = CONFIG_CLEAN_VPATH_FILES = am__vpath_adj_setup = srcdirstrip=`echo "$(srcdir)" | sed 's|.|.|g'`; am__vpath_adj = case $$p in \ $(srcdir)/*) f=`echo "$$p" | sed "s|^$$srcdirstrip/||"`;; \ *) f=$$p;; \ esac; am__strip_dir = f=`echo $$p | sed -e 's|^.*/||'`; am__install_max = 40 am__nobase_strip_setup = \ srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*|]/\\\\&/g'` am__nobase_strip = \ for p in $$list; do echo "$$p"; done | sed -e "s|$$srcdirstrip/||" am__nobase_list = $(am__nobase_strip_setup); \ for p in $$list; do echo "$$p $$p"; done | \ sed "s| $$srcdirstrip/| |;"' / .*\//!s/ .*/ ./; s,\( .*\)/[^/]*$$,\1,' | \ $(AWK) 'BEGIN { files["."] = "" } { files[$$2] = files[$$2] " " $$1; \ if (++n[$$2] == $(am__install_max)) \ { print $$2, files[$$2]; n[$$2] = 0; files[$$2] = "" } } \ END { for (dir in files) print dir, files[dir] }' am__base_list = \ sed '$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;s/\n/ /g' | \ sed '$$!N;$$!N;$$!N;$$!N;s/\n/ /g' am__uninstall_files_from_dir = { \ test -z "$$files" \ || { test ! -d "$$dir" && test ! -f "$$dir" && test ! -r "$$dir"; } \ || { echo " ( cd '$$dir' && rm -f" $$files ")"; \ $(am__cd) "$$dir" && rm -f $$files; }; \ } am__installdirs = "$(DESTDIR)$(libdir)" LTLIBRARIES = $(lib_LTLIBRARIES) am__DEPENDENCIES_1 = libheimsqlite_la_DEPENDENCIES = $(am__DEPENDENCIES_1) am_libheimsqlite_la_OBJECTS = sqlite3.lo libheimsqlite_la_OBJECTS = $(am_libheimsqlite_la_OBJECTS) AM_V_lt = $(am__v_lt_@AM_V@) am__v_lt_ = $(am__v_lt_@AM_DEFAULT_V@) am__v_lt_0 = --silent am__v_lt_1 = AM_V_P = $(am__v_P_@AM_V@) am__v_P_ = $(am__v_P_@AM_DEFAULT_V@) am__v_P_0 = false am__v_P_1 = : AM_V_GEN = $(am__v_GEN_@AM_V@) am__v_GEN_ = $(am__v_GEN_@AM_DEFAULT_V@) am__v_GEN_0 = @echo " GEN " $@; am__v_GEN_1 = AM_V_at = $(am__v_at_@AM_V@) am__v_at_ = $(am__v_at_@AM_DEFAULT_V@) am__v_at_0 = @ am__v_at_1 = depcomp = $(SHELL) $(top_srcdir)/depcomp am__depfiles_maybe = depfiles am__mv = mv -f COMPILE = $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) \ $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) LTCOMPILE = $(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) \ $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) \ $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) \ $(AM_CFLAGS) $(CFLAGS) AM_V_CC = $(am__v_CC_@AM_V@) am__v_CC_ = $(am__v_CC_@AM_DEFAULT_V@) am__v_CC_0 = @echo " CC " $@; am__v_CC_1 = CCLD = $(CC) LINK = $(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) \ $(LIBTOOLFLAGS) --mode=link $(CCLD) $(AM_CFLAGS) $(CFLAGS) \ $(AM_LDFLAGS) $(LDFLAGS) -o $@ AM_V_CCLD = $(am__v_CCLD_@AM_V@) am__v_CCLD_ = $(am__v_CCLD_@AM_DEFAULT_V@) am__v_CCLD_0 = @echo " CCLD " $@; am__v_CCLD_1 = SOURCES = $(libheimsqlite_la_SOURCES) DIST_SOURCES = $(libheimsqlite_la_SOURCES) am__can_run_installinfo = \ case $$AM_UPDATE_INFO_DIR in \ n|no|NO) false;; \ *) (install-info --version) >/dev/null 2>&1;; \ esac HEADERS = $(noinst_HEADERS) am__tagged_files = $(HEADERS) $(SOURCES) $(TAGS_FILES) $(LISP) # Read a list of newline-separated strings from the standard input, # and print each of them once, without duplicates. Input order is # *not* preserved. am__uniquify_input = $(AWK) '\ BEGIN { nonempty = 0; } \ { items[$$0] = 1; nonempty = 1; } \ END { if (nonempty) { for (i in items) print i; }; } \ ' # Make sure the list of sources is unique. This is necessary because, # e.g., the same source file might be shared among _SOURCES variables # for different programs/libraries. am__define_uniq_tagged_files = \ list='$(am__tagged_files)'; \ unique=`for i in $$list; do \ if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ done | $(am__uniquify_input)` ETAGS = etags CTAGS = ctags am__DIST_COMMON = $(srcdir)/Makefile.in \ $(top_srcdir)/Makefile.am.common \ $(top_srcdir)/cf/Makefile.am.common $(top_srcdir)/depcomp \ README DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST) ACLOCAL = @ACLOCAL@ AIX_EXTRA_KAFS = @AIX_EXTRA_KAFS@ AMTAR = @AMTAR@ AM_DEFAULT_VERBOSITY = @AM_DEFAULT_VERBOSITY@ AR = @AR@ AS = @AS@ ASN1_COMPILE = @ASN1_COMPILE@ ASN1_COMPILE_DEP = @ASN1_COMPILE_DEP@ AUTOCONF = @AUTOCONF@ AUTOHEADER = @AUTOHEADER@ AUTOMAKE = @AUTOMAKE@ AWK = @AWK@ CANONICAL_HOST = @CANONICAL_HOST@ CAPNG_CFLAGS = @CAPNG_CFLAGS@ CAPNG_LIBS = @CAPNG_LIBS@ CATMAN = @CATMAN@ CATMANEXT = @CATMANEXT@ CC = @CC@ CCDEPMODE = @CCDEPMODE@ CFLAGS = @CFLAGS@ COMPILE_ET = @COMPILE_ET@ CPP = @CPP@ CPPFLAGS = @CPPFLAGS@ CYGPATH_W = @CYGPATH_W@ DB1LIB = @DB1LIB@ DB3LIB = @DB3LIB@ DBHEADER = @DBHEADER@ DEFS = @DEFS@ DEPDIR = @DEPDIR@ DIR_com_err = @DIR_com_err@ DIR_hdbdir = @DIR_hdbdir@ DIR_roken = @DIR_roken@ DLLTOOL = @DLLTOOL@ DSYMUTIL = @DSYMUTIL@ DUMPBIN = @DUMPBIN@ ECHO_C = @ECHO_C@ ECHO_N = @ECHO_N@ ECHO_T = @ECHO_T@ EGREP = @EGREP@ ENABLE_AFS_STRING_TO_KEY = @ENABLE_AFS_STRING_TO_KEY@ EXEEXT = @EXEEXT@ FGREP = @FGREP@ GCD_MIG = @GCD_MIG@ GREP = @GREP@ GROFF = @GROFF@ INCLUDES_roken = @INCLUDES_roken@ INCLUDE_libedit = @INCLUDE_libedit@ INCLUDE_libintl = @INCLUDE_libintl@ INCLUDE_openldap = @INCLUDE_openldap@ INCLUDE_openssl_crypto = @INCLUDE_openssl_crypto@ INCLUDE_readline = @INCLUDE_readline@ INCLUDE_sqlite3 = @INCLUDE_sqlite3@ INSTALL = @INSTALL@ INSTALL_DATA = @INSTALL_DATA@ INSTALL_PROGRAM = @INSTALL_PROGRAM@ INSTALL_SCRIPT = @INSTALL_SCRIPT@ INSTALL_STRIP_PROGRAM = @INSTALL_STRIP_PROGRAM@ LD = @LD@ LDFLAGS = @LDFLAGS@ LDFLAGS_VERSION_SCRIPT = @LDFLAGS_VERSION_SCRIPT@ LEX = @LEX@ LEXLIB = @LEXLIB@ LEX_OUTPUT_ROOT = @LEX_OUTPUT_ROOT@ LIBADD_roken = @LIBADD_roken@ LIBOBJS = @LIBOBJS@ LIBS = @LIBS@ LIBTOOL = @LIBTOOL@ LIB_AUTH_SUBDIRS = @LIB_AUTH_SUBDIRS@ LIB_bswap16 = @LIB_bswap16@ LIB_bswap32 = @LIB_bswap32@ LIB_bswap64 = @LIB_bswap64@ LIB_com_err = @LIB_com_err@ LIB_com_err_a = @LIB_com_err_a@ LIB_com_err_so = @LIB_com_err_so@ LIB_crypt = @LIB_crypt@ LIB_db_create = @LIB_db_create@ LIB_dbm_firstkey = @LIB_dbm_firstkey@ LIB_dbopen = @LIB_dbopen@ LIB_dispatch_async_f = @LIB_dispatch_async_f@ LIB_dladdr = @LIB_dladdr@ LIB_dlopen = @LIB_dlopen@ LIB_dn_expand = @LIB_dn_expand@ LIB_dns_search = @LIB_dns_search@ LIB_door_create = @LIB_door_create@ LIB_freeaddrinfo = @LIB_freeaddrinfo@ LIB_gai_strerror = @LIB_gai_strerror@ LIB_getaddrinfo = @LIB_getaddrinfo@ LIB_gethostbyname = @LIB_gethostbyname@ LIB_gethostbyname2 = @LIB_gethostbyname2@ LIB_getnameinfo = @LIB_getnameinfo@ LIB_getpwnam_r = @LIB_getpwnam_r@ LIB_getsockopt = @LIB_getsockopt@ LIB_hcrypto = @LIB_hcrypto@ LIB_hcrypto_a = @LIB_hcrypto_a@ LIB_hcrypto_appl = @LIB_hcrypto_appl@ LIB_hcrypto_so = @LIB_hcrypto_so@ LIB_hstrerror = @LIB_hstrerror@ LIB_kdb = @LIB_kdb@ LIB_libedit = @LIB_libedit@ LIB_libintl = @LIB_libintl@ LIB_loadquery = @LIB_loadquery@ LIB_logout = @LIB_logout@ LIB_logwtmp = @LIB_logwtmp@ LIB_openldap = @LIB_openldap@ LIB_openpty = @LIB_openpty@ LIB_openssl_crypto = @LIB_openssl_crypto@ LIB_otp = @LIB_otp@ LIB_pidfile = @LIB_pidfile@ LIB_readline = @LIB_readline@ LIB_res_ndestroy = @LIB_res_ndestroy@ LIB_res_nsearch = @LIB_res_nsearch@ LIB_res_search = @LIB_res_search@ LIB_roken = @LIB_roken@ LIB_security = @LIB_security@ LIB_setsockopt = @LIB_setsockopt@ LIB_socket = @LIB_socket@ LIB_sqlite3 = @LIB_sqlite3@ LIB_syslog = @LIB_syslog@ LIB_tgetent = @LIB_tgetent@ LIPO = @LIPO@ LMDBLIB = @LMDBLIB@ LN_S = @LN_S@ LTLIBOBJS = @LTLIBOBJS@ LT_SYS_LIBRARY_PATH = @LT_SYS_LIBRARY_PATH@ MAINT = @MAINT@ MAKEINFO = @MAKEINFO@ MANIFEST_TOOL = @MANIFEST_TOOL@ MKDIR_P = @MKDIR_P@ NDBMLIB = @NDBMLIB@ NM = @NM@ NMEDIT = @NMEDIT@ NO_AFS = @NO_AFS@ NROFF = @NROFF@ OBJDUMP = @OBJDUMP@ OBJEXT = @OBJEXT@ OTOOL = @OTOOL@ OTOOL64 = @OTOOL64@ PACKAGE = @PACKAGE@ PACKAGE_BUGREPORT = @PACKAGE_BUGREPORT@ PACKAGE_NAME = @PACKAGE_NAME@ PACKAGE_STRING = @PACKAGE_STRING@ PACKAGE_TARNAME = @PACKAGE_TARNAME@ PACKAGE_URL = @PACKAGE_URL@ PACKAGE_VERSION = @PACKAGE_VERSION@ PATH_SEPARATOR = @PATH_SEPARATOR@ PERL = @PERL@ PKG_CONFIG = @PKG_CONFIG@ PTHREAD_CFLAGS = @PTHREAD_CFLAGS@ PTHREAD_LDADD = @PTHREAD_LDADD@ PTHREAD_LIBADD = @PTHREAD_LIBADD@ RANLIB = @RANLIB@ SED = @SED@ SET_MAKE = @SET_MAKE@ SHELL = @SHELL@ SLC = @SLC@ SLC_DEP = @SLC_DEP@ STRIP = @STRIP@ VERSION = @VERSION@ VERSIONING = @VERSIONING@ WFLAGS = @WFLAGS@ WFLAGS_LITE = @WFLAGS_LITE@ YACC = @YACC@ YFLAGS = @YFLAGS@ abs_builddir = @abs_builddir@ abs_srcdir = @abs_srcdir@ abs_top_builddir = @abs_top_builddir@ abs_top_srcdir = @abs_top_srcdir@ ac_ct_AR = @ac_ct_AR@ ac_ct_CC = @ac_ct_CC@ ac_ct_DUMPBIN = @ac_ct_DUMPBIN@ am__include = @am__include@ am__leading_dot = @am__leading_dot@ am__quote = @am__quote@ am__tar = @am__tar@ am__untar = @am__untar@ bindir = @bindir@ build = @build@ build_alias = @build_alias@ build_cpu = @build_cpu@ build_os = @build_os@ build_vendor = @build_vendor@ builddir = @builddir@ datadir = @datadir@ datarootdir = @datarootdir@ db_type = @db_type@ db_type_preference = @db_type_preference@ docdir = @docdir@ dpagaix_cflags = @dpagaix_cflags@ dpagaix_ldadd = @dpagaix_ldadd@ dpagaix_ldflags = @dpagaix_ldflags@ dvidir = @dvidir@ exec_prefix = @exec_prefix@ host = @host@ host_alias = @host_alias@ host_cpu = @host_cpu@ host_os = @host_os@ host_vendor = @host_vendor@ htmldir = @htmldir@ includedir = @includedir@ infodir = @infodir@ install_sh = @install_sh@ libdir = @libdir@ libexecdir = @libexecdir@ localedir = @localedir@ localstatedir = @localstatedir@ mandir = @mandir@ mkdir_p = @mkdir_p@ oldincludedir = @oldincludedir@ pdfdir = @pdfdir@ prefix = @prefix@ program_transform_name = @program_transform_name@ psdir = @psdir@ sbindir = @sbindir@ sharedstatedir = @sharedstatedir@ srcdir = @srcdir@ subdirs = @subdirs@ sysconfdir = @sysconfdir@ target_alias = @target_alias@ top_build_prefix = @top_build_prefix@ top_builddir = @top_builddir@ top_srcdir = @top_srcdir@ SUFFIXES = .et .h .pc.in .pc .x .z .hx .1 .3 .5 .7 .8 .cat1 .cat3 \ .cat5 .cat7 .cat8 DEFAULT_INCLUDES = -I. -I$(srcdir) -I$(top_builddir)/include -I$(top_srcdir)/include AM_CPPFLAGS = $(INCLUDES_roken) $(am__append_1) @do_roken_rename_TRUE@ROKEN_RENAME = -DROKEN_RENAME AM_CFLAGS = $(WFLAGS) CP = cp buildinclude = $(top_builddir)/include LIB_XauReadAuth = @LIB_XauReadAuth@ LIB_el_init = @LIB_el_init@ LIB_getattr = @LIB_getattr@ LIB_getpwent_r = @LIB_getpwent_r@ LIB_odm_initialize = @LIB_odm_initialize@ LIB_setpcred = @LIB_setpcred@ INCLUDE_krb4 = @INCLUDE_krb4@ LIB_krb4 = @LIB_krb4@ libexec_heimdaldir = $(libexecdir)/heimdal NROFF_MAN = groff -mandoc -Tascii @NO_AFS_FALSE@LIB_kafs = $(top_builddir)/lib/kafs/libkafs.la $(AIX_EXTRA_KAFS) @NO_AFS_TRUE@LIB_kafs = @KRB5_TRUE@LIB_krb5 = $(top_builddir)/lib/krb5/libkrb5.la \ @KRB5_TRUE@ $(top_builddir)/lib/asn1/libasn1.la @KRB5_TRUE@LIB_gssapi = $(top_builddir)/lib/gssapi/libgssapi.la LIB_heimbase = $(top_builddir)/lib/base/libheimbase.la @DCE_TRUE@LIB_kdfs = $(top_builddir)/lib/kdfs/libkdfs.la #silent-rules heim_verbose = $(heim_verbose_$(V)) heim_verbose_ = $(heim_verbose_$(AM_DEFAULT_VERBOSITY)) heim_verbose_0 = @echo " GEN "$@; lib_LTLIBRARIES = libheimsqlite.la noinst_HEADERS = sqlite3.h sqlite3ext.h libheimsqlite_la_SOURCES = sqlite3.c libheimsqlite_la_LIBADD = $(PTHREAD_LIBADD) EXTRA_DIST = NTMakefile all: all-am .SUFFIXES: .SUFFIXES: .et .h .pc.in .pc .x .z .hx .1 .3 .5 .7 .8 .cat1 .cat3 .cat5 .cat7 .cat8 .c .lo .o .obj $(srcdir)/Makefile.in: @MAINTAINER_MODE_TRUE@ $(srcdir)/Makefile.am $(top_srcdir)/Makefile.am.common $(top_srcdir)/cf/Makefile.am.common $(am__configure_deps) @for dep in $?; do \ case '$(am__configure_deps)' in \ *$$dep*) \ ( cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh ) \ && { if test -f $@; then exit 0; else break; fi; }; \ exit 1;; \ esac; \ done; \ echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign lib/sqlite/Makefile'; \ $(am__cd) $(top_srcdir) && \ $(AUTOMAKE) --foreign lib/sqlite/Makefile Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status @case '$?' in \ *config.status*) \ cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh;; \ *) \ echo ' cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe)'; \ cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe);; \ esac; $(top_srcdir)/Makefile.am.common $(top_srcdir)/cf/Makefile.am.common $(am__empty): $(top_builddir)/config.status: $(top_srcdir)/configure $(CONFIG_STATUS_DEPENDENCIES) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(top_srcdir)/configure: @MAINTAINER_MODE_TRUE@ $(am__configure_deps) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(ACLOCAL_M4): @MAINTAINER_MODE_TRUE@ $(am__aclocal_m4_deps) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(am__aclocal_m4_deps): install-libLTLIBRARIES: $(lib_LTLIBRARIES) @$(NORMAL_INSTALL) @list='$(lib_LTLIBRARIES)'; test -n "$(libdir)" || list=; \ list2=; for p in $$list; do \ if test -f $$p; then \ list2="$$list2 $$p"; \ else :; fi; \ done; \ test -z "$$list2" || { \ echo " $(MKDIR_P) '$(DESTDIR)$(libdir)'"; \ $(MKDIR_P) "$(DESTDIR)$(libdir)" || exit 1; \ echo " $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=install $(INSTALL) $(INSTALL_STRIP_FLAG) $$list2 '$(DESTDIR)$(libdir)'"; \ $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=install $(INSTALL) $(INSTALL_STRIP_FLAG) $$list2 "$(DESTDIR)$(libdir)"; \ } uninstall-libLTLIBRARIES: @$(NORMAL_UNINSTALL) @list='$(lib_LTLIBRARIES)'; test -n "$(libdir)" || list=; \ for p in $$list; do \ $(am__strip_dir) \ echo " $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=uninstall rm -f '$(DESTDIR)$(libdir)/$$f'"; \ $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=uninstall rm -f "$(DESTDIR)$(libdir)/$$f"; \ done clean-libLTLIBRARIES: -test -z "$(lib_LTLIBRARIES)" || rm -f $(lib_LTLIBRARIES) @list='$(lib_LTLIBRARIES)'; \ locs=`for p in $$list; do echo $$p; done | \ sed 's|^[^/]*$$|.|; s|/[^/]*$$||; s|$$|/so_locations|' | \ sort -u`; \ test -z "$$locs" || { \ echo rm -f $${locs}; \ rm -f $${locs}; \ } libheimsqlite.la: $(libheimsqlite_la_OBJECTS) $(libheimsqlite_la_DEPENDENCIES) $(EXTRA_libheimsqlite_la_DEPENDENCIES) $(AM_V_CCLD)$(LINK) -rpath $(libdir) $(libheimsqlite_la_OBJECTS) $(libheimsqlite_la_LIBADD) $(LIBS) mostlyclean-compile: -rm -f *.$(OBJEXT) distclean-compile: -rm -f *.tab.c @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/sqlite3.Plo@am__quote@ .c.o: @am__fastdepCC_TRUE@ $(AM_V_CC)$(COMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o $@ $< @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='$<' object='$@' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(COMPILE) -c -o $@ $< .c.obj: @am__fastdepCC_TRUE@ $(AM_V_CC)$(COMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o $@ `$(CYGPATH_W) '$<'` @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='$<' object='$@' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(COMPILE) -c -o $@ `$(CYGPATH_W) '$<'` .c.lo: @am__fastdepCC_TRUE@ $(AM_V_CC)$(LTCOMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o $@ $< @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='$<' object='$@' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LTCOMPILE) -c -o $@ $< mostlyclean-libtool: -rm -f *.lo clean-libtool: -rm -rf .libs _libs ID: $(am__tagged_files) $(am__define_uniq_tagged_files); mkid -fID $$unique tags: tags-am TAGS: tags tags-am: $(TAGS_DEPENDENCIES) $(am__tagged_files) set x; \ here=`pwd`; \ $(am__define_uniq_tagged_files); \ shift; \ if test -z "$(ETAGS_ARGS)$$*$$unique"; then :; else \ test -n "$$unique" || unique=$$empty_fix; \ if test $$# -gt 0; then \ $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ "$$@" $$unique; \ else \ $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ $$unique; \ fi; \ fi ctags: ctags-am CTAGS: ctags ctags-am: $(TAGS_DEPENDENCIES) $(am__tagged_files) $(am__define_uniq_tagged_files); \ test -z "$(CTAGS_ARGS)$$unique" \ || $(CTAGS) $(CTAGSFLAGS) $(AM_CTAGSFLAGS) $(CTAGS_ARGS) \ $$unique GTAGS: here=`$(am__cd) $(top_builddir) && pwd` \ && $(am__cd) $(top_srcdir) \ && gtags -i $(GTAGS_ARGS) "$$here" cscopelist: cscopelist-am cscopelist-am: $(am__tagged_files) list='$(am__tagged_files)'; \ case "$(srcdir)" in \ [\\/]* | ?:[\\/]*) sdir="$(srcdir)" ;; \ *) sdir=$(subdir)/$(srcdir) ;; \ esac; \ for i in $$list; do \ if test -f "$$i"; then \ echo "$(subdir)/$$i"; \ else \ echo "$$sdir/$$i"; \ fi; \ done >> $(top_builddir)/cscope.files distclean-tags: -rm -f TAGS ID GTAGS GRTAGS GSYMS GPATH tags distdir: $(DISTFILES) @srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ topsrcdirstrip=`echo "$(top_srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ list='$(DISTFILES)'; \ dist_files=`for file in $$list; do echo $$file; done | \ sed -e "s|^$$srcdirstrip/||;t" \ -e "s|^$$topsrcdirstrip/|$(top_builddir)/|;t"`; \ case $$dist_files in \ */*) $(MKDIR_P) `echo "$$dist_files" | \ sed '/\//!d;s|^|$(distdir)/|;s,/[^/]*$$,,' | \ sort -u` ;; \ esac; \ for file in $$dist_files; do \ if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \ if test -d $$d/$$file; then \ dir=`echo "/$$file" | sed -e 's,/[^/]*$$,,'`; \ if test -d "$(distdir)/$$file"; then \ find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ fi; \ if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \ cp -fpR $(srcdir)/$$file "$(distdir)$$dir" || exit 1; \ find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ fi; \ cp -fpR $$d/$$file "$(distdir)$$dir" || exit 1; \ else \ test -f "$(distdir)/$$file" \ || cp -p $$d/$$file "$(distdir)/$$file" \ || exit 1; \ fi; \ done $(MAKE) $(AM_MAKEFLAGS) \ top_distdir="$(top_distdir)" distdir="$(distdir)" \ dist-hook check-am: all-am $(MAKE) $(AM_MAKEFLAGS) check-local check: check-am all-am: Makefile $(LTLIBRARIES) $(HEADERS) all-local installdirs: for dir in "$(DESTDIR)$(libdir)"; do \ test -z "$$dir" || $(MKDIR_P) "$$dir"; \ done install: install-am install-exec: install-exec-am install-data: install-data-am uninstall: uninstall-am install-am: all-am @$(MAKE) $(AM_MAKEFLAGS) install-exec-am install-data-am installcheck: installcheck-am install-strip: if test -z '$(STRIP)'; then \ $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ install; \ else \ $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'" install; \ fi mostlyclean-generic: clean-generic: distclean-generic: -test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES) -test . = "$(srcdir)" || test -z "$(CONFIG_CLEAN_VPATH_FILES)" || rm -f $(CONFIG_CLEAN_VPATH_FILES) maintainer-clean-generic: @echo "This command is intended for maintainers to use" @echo "it deletes files that may require special tools to rebuild." clean: clean-am clean-am: clean-generic clean-libLTLIBRARIES clean-libtool \ mostlyclean-am distclean: distclean-am -rm -rf ./$(DEPDIR) -rm -f Makefile distclean-am: clean-am distclean-compile distclean-generic \ distclean-tags dvi: dvi-am dvi-am: html: html-am html-am: info: info-am info-am: install-data-am: @$(NORMAL_INSTALL) $(MAKE) $(AM_MAKEFLAGS) install-data-hook install-dvi: install-dvi-am install-dvi-am: install-exec-am: install-exec-local install-libLTLIBRARIES install-html: install-html-am install-html-am: install-info: install-info-am install-info-am: install-man: install-pdf: install-pdf-am install-pdf-am: install-ps: install-ps-am install-ps-am: installcheck-am: maintainer-clean: maintainer-clean-am -rm -rf ./$(DEPDIR) -rm -f Makefile maintainer-clean-am: distclean-am maintainer-clean-generic mostlyclean: mostlyclean-am mostlyclean-am: mostlyclean-compile mostlyclean-generic \ mostlyclean-libtool pdf: pdf-am pdf-am: ps: ps-am ps-am: uninstall-am: uninstall-libLTLIBRARIES @$(NORMAL_INSTALL) $(MAKE) $(AM_MAKEFLAGS) uninstall-hook .MAKE: check-am install-am install-data-am install-strip uninstall-am .PHONY: CTAGS GTAGS TAGS all all-am all-local check check-am \ check-local clean clean-generic clean-libLTLIBRARIES \ clean-libtool cscopelist-am ctags ctags-am dist-hook distclean \ distclean-compile distclean-generic distclean-libtool \ distclean-tags distdir dvi dvi-am html html-am info info-am \ install install-am install-data install-data-am \ install-data-hook install-dvi install-dvi-am install-exec \ install-exec-am install-exec-local install-html \ install-html-am install-info install-info-am \ install-libLTLIBRARIES install-man install-pdf install-pdf-am \ install-ps install-ps-am install-strip installcheck \ installcheck-am installdirs maintainer-clean \ maintainer-clean-generic mostlyclean mostlyclean-compile \ mostlyclean-generic mostlyclean-libtool pdf pdf-am ps ps-am \ tags tags-am uninstall uninstall-am uninstall-hook \ uninstall-libLTLIBRARIES .PRECIOUS: Makefile install-suid-programs: @foo='$(bin_SUIDS)'; \ for file in $$foo; do \ x=$(DESTDIR)$(bindir)/$$file; \ if chown 0:0 $$x && chmod u+s $$x; then :; else \ echo "*"; \ echo "* Failed to install $$x setuid root"; \ echo "*"; \ fi; \ done install-exec-local: install-suid-programs codesign-all: @if [ X"$$CODE_SIGN_IDENTITY" != X ] ; then \ foo='$(bin_PROGRAMS) $(sbin_PROGRAMS) $(libexec_PROGRAMS)' ; \ for file in $$foo ; do \ echo "CODESIGN $$file" ; \ codesign -f -s "$$CODE_SIGN_IDENTITY" $$file || exit 1 ; \ done ; \ fi all-local: codesign-all install-build-headers:: $(include_HEADERS) $(dist_include_HEADERS) $(nodist_include_HEADERS) $(build_HEADERZ) $(nobase_include_HEADERS) $(noinst_HEADERS) @foo='$(include_HEADERS) $(dist_include_HEADERS) $(nodist_include_HEADERS) $(build_HEADERZ) $(noinst_HEADERS)'; \ for f in $$foo; do \ f=`basename $$f`; \ if test -f "$(srcdir)/$$f"; then file="$(srcdir)/$$f"; \ else file="$$f"; fi; \ if cmp -s $$file $(buildinclude)/$$f 2> /dev/null ; then \ : ; else \ echo " $(CP) $$file $(buildinclude)/$$f"; \ $(CP) $$file $(buildinclude)/$$f || true; \ fi ; \ done ; \ foo='$(nobase_include_HEADERS)'; \ for f in $$foo; do \ if test -f "$(srcdir)/$$f"; then file="$(srcdir)/$$f"; \ else file="$$f"; fi; \ $(mkdir_p) $(buildinclude)/`dirname $$f` ; \ if cmp -s $$file $(buildinclude)/$$f 2> /dev/null ; then \ : ; else \ echo " $(CP) $$file $(buildinclude)/$$f"; \ $(CP) $$file $(buildinclude)/$$f; \ fi ; \ done all-local: install-build-headers check-local:: @if test '$(CHECK_LOCAL)' = "no-check-local"; then \ foo=''; elif test '$(CHECK_LOCAL)'; then \ foo='$(CHECK_LOCAL)'; else \ foo='$(PROGRAMS)'; fi; \ if test "$$foo"; then \ failed=0; all=0; \ for i in $$foo; do \ all=`expr $$all + 1`; \ if (./$$i --version && ./$$i --help) > /dev/null 2>&1; then \ echo "PASS: $$i"; \ else \ echo "FAIL: $$i"; \ failed=`expr $$failed + 1`; \ fi; \ done; \ if test "$$failed" -eq 0; then \ banner="All $$all tests passed"; \ else \ banner="$$failed of $$all tests failed"; \ fi; \ dashes=`echo "$$banner" | sed s/./=/g`; \ echo "$$dashes"; \ echo "$$banner"; \ echo "$$dashes"; \ test "$$failed" -eq 0 || exit 1; \ fi .x.c: @cmp -s $< $@ 2> /dev/null || cp $< $@ .hx.h: @cmp -s $< $@ 2> /dev/null || cp $< $@ #NROFF_MAN = nroff -man .1.cat1: $(NROFF_MAN) $< > $@ .3.cat3: $(NROFF_MAN) $< > $@ .5.cat5: $(NROFF_MAN) $< > $@ .7.cat7: $(NROFF_MAN) $< > $@ .8.cat8: $(NROFF_MAN) $< > $@ dist-cat1-mans: @foo='$(man1_MANS)'; \ bar='$(man_MANS)'; \ for i in $$bar; do \ case $$i in \ *.1) foo="$$foo $$i";; \ esac; done ;\ for i in $$foo; do \ x=`echo $$i | sed 's/\.[^.]*$$/.cat1/'`; \ echo "$(NROFF_MAN) $(srcdir)/$$i > $(distdir)/$$x"; \ $(NROFF_MAN) $(srcdir)/$$i > $(distdir)/$$x; \ done dist-cat3-mans: @foo='$(man3_MANS)'; \ bar='$(man_MANS)'; \ for i in $$bar; do \ case $$i in \ *.3) foo="$$foo $$i";; \ esac; done ;\ for i in $$foo; do \ x=`echo $$i | sed 's/\.[^.]*$$/.cat3/'`; \ echo "$(NROFF_MAN) $(srcdir)/$$i > $(distdir)/$$x"; \ $(NROFF_MAN) $(srcdir)/$$i > $(distdir)/$$x; \ done dist-cat5-mans: @foo='$(man5_MANS)'; \ bar='$(man_MANS)'; \ for i in $$bar; do \ case $$i in \ *.5) foo="$$foo $$i";; \ esac; done ;\ for i in $$foo; do \ x=`echo $$i | sed 's/\.[^.]*$$/.cat5/'`; \ echo "$(NROFF_MAN) $(srcdir)/$$i > $(distdir)/$$x"; \ $(NROFF_MAN) $(srcdir)/$$i > $(distdir)/$$x; \ done dist-cat7-mans: @foo='$(man7_MANS)'; \ bar='$(man_MANS)'; \ for i in $$bar; do \ case $$i in \ *.7) foo="$$foo $$i";; \ esac; done ;\ for i in $$foo; do \ x=`echo $$i | sed 's/\.[^.]*$$/.cat7/'`; \ echo "$(NROFF_MAN) $(srcdir)/$$i > $(distdir)/$$x"; \ $(NROFF_MAN) $(srcdir)/$$i > $(distdir)/$$x; \ done dist-cat8-mans: @foo='$(man8_MANS)'; \ bar='$(man_MANS)'; \ for i in $$bar; do \ case $$i in \ *.8) foo="$$foo $$i";; \ esac; done ;\ for i in $$foo; do \ x=`echo $$i | sed 's/\.[^.]*$$/.cat8/'`; \ echo "$(NROFF_MAN) $(srcdir)/$$i > $(distdir)/$$x"; \ $(NROFF_MAN) $(srcdir)/$$i > $(distdir)/$$x; \ done dist-hook: dist-cat1-mans dist-cat3-mans dist-cat5-mans dist-cat7-mans dist-cat8-mans install-cat-mans: $(SHELL) $(top_srcdir)/cf/install-catman.sh install "$(INSTALL_DATA)" "$(mkinstalldirs)" "$(srcdir)" "$(DESTDIR)$(mandir)" '$(CATMANEXT)' $(man_MANS) $(man1_MANS) $(man3_MANS) $(man5_MANS) $(man7_MANS) $(man8_MANS) uninstall-cat-mans: $(SHELL) $(top_srcdir)/cf/install-catman.sh uninstall "$(INSTALL_DATA)" "$(mkinstalldirs)" "$(srcdir)" "$(DESTDIR)$(mandir)" '$(CATMANEXT)' $(man_MANS) $(man1_MANS) $(man3_MANS) $(man5_MANS) $(man7_MANS) $(man8_MANS) install-data-hook: install-cat-mans uninstall-hook: uninstall-cat-mans .et.h: $(COMPILE_ET) $< .et.c: $(COMPILE_ET) $< # # Useful target for debugging # check-valgrind: tobjdir=`cd $(top_builddir) && pwd` ; \ tsrcdir=`cd $(top_srcdir) && pwd` ; \ env TESTS_ENVIRONMENT="$${tsrcdir}/cf/maybe-valgrind.sh -s $${tsrcdir} -o $${tobjdir}" make check # # Target to please samba build farm, builds distfiles in-tree. # Will break when automake changes... # distdir-in-tree: $(DISTFILES) $(INFO_DEPS) list='$(DIST_SUBDIRS)'; for subdir in $$list; do \ if test "$$subdir" != .; then \ (cd $$subdir && $(MAKE) $(AM_MAKEFLAGS) distdir-in-tree) ; \ fi ; \ done # Tell versions [3.59,3.63) of GNU make to not export all variables. # Otherwise a system limit (for SysV at least) may be exceeded. .NOEXPORT: heimdal-7.5.0/lib/sqlite/sqlite3.c0000644000175000017500003256607513212137553015103 0ustar niknik/****************************************************************************** ** This file is an amalgamation of many separate C source files from SQLite ** version 3.15.1. By combining all the individual C code files into this ** single large file, the entire code can be compiled as a single translation ** unit. This allows many compilers to do optimizations that would not be ** possible if the files were compiled separately. Performance improvements ** of 5% or more are commonly seen when SQLite is compiled as a single ** translation unit. ** ** This file is all you need to compile SQLite. To use SQLite in other ** programs, you need this file and the "sqlite3.h" header file that defines ** the programming interface to the SQLite library. (If you do not have ** the "sqlite3.h" header file at hand, you will find a copy embedded within ** the text of this file. Search for "Begin file sqlite3.h" to find the start ** of the embedded sqlite3.h header file.) Additional code files may be needed ** if you want a wrapper to interface SQLite with your choice of programming ** language. The code for the "sqlite3" command-line shell is also in a ** separate file. This file contains only code for the core SQLite library. */ #define SQLITE_CORE 1 #define SQLITE_AMALGAMATION 1 #ifndef SQLITE_PRIVATE # define SQLITE_PRIVATE static #endif /************** Begin file sqliteInt.h ***************************************/ /* ** 2001 September 15 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ************************************************************************* ** Internal interface definitions for SQLite. ** */ #ifndef SQLITEINT_H #define SQLITEINT_H /* Special Comments: ** ** Some comments have special meaning to the tools that measure test ** coverage: ** ** NO_TEST - The branches on this line are not ** measured by branch coverage. This is ** used on lines of code that actually ** implement parts of coverage testing. ** ** OPTIMIZATION-IF-TRUE - This branch is allowed to alway be false ** and the correct answer is still obtained, ** though perhaps more slowly. ** ** OPTIMIZATION-IF-FALSE - This branch is allowed to alway be true ** and the correct answer is still obtained, ** though perhaps more slowly. ** ** PREVENTS-HARMLESS-OVERREAD - This branch prevents a buffer overread ** that would be harmless and undetectable ** if it did occur. ** ** In all cases, the special comment must be enclosed in the usual ** slash-asterisk...asterisk-slash comment marks, with no spaces between the ** asterisks and the comment text. */ /* ** Make sure the Tcl calling convention macro is defined. This macro is ** only used by test code and Tcl integration code. */ #ifndef SQLITE_TCLAPI # define SQLITE_TCLAPI #endif /* ** Make sure that rand_s() is available on Windows systems with MSVC 2005 ** or higher. */ #if defined(_MSC_VER) && _MSC_VER>=1400 # define _CRT_RAND_S #endif /* ** Include the header file used to customize the compiler options for MSVC. ** This should be done first so that it can successfully prevent spurious ** compiler warnings due to subsequent content in this file and other files ** that are included by this file. */ /************** Include msvc.h in the middle of sqliteInt.h ******************/ /************** Begin file msvc.h ********************************************/ /* ** 2015 January 12 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ****************************************************************************** ** ** This file contains code that is specific to MSVC. */ #ifndef SQLITE_MSVC_H #define SQLITE_MSVC_H #if defined(_MSC_VER) #pragma warning(disable : 4054) #pragma warning(disable : 4055) #pragma warning(disable : 4100) #pragma warning(disable : 4127) #pragma warning(disable : 4130) #pragma warning(disable : 4152) #pragma warning(disable : 4189) #pragma warning(disable : 4206) #pragma warning(disable : 4210) #pragma warning(disable : 4232) #pragma warning(disable : 4244) #pragma warning(disable : 4305) #pragma warning(disable : 4306) #pragma warning(disable : 4702) #pragma warning(disable : 4706) #endif /* defined(_MSC_VER) */ #endif /* SQLITE_MSVC_H */ /************** End of msvc.h ************************************************/ /************** Continuing where we left off in sqliteInt.h ******************/ /* ** Special setup for VxWorks */ /************** Include vxworks.h in the middle of sqliteInt.h ***************/ /************** Begin file vxworks.h *****************************************/ /* ** 2015-03-02 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ****************************************************************************** ** ** This file contains code that is specific to Wind River's VxWorks */ #if defined(__RTP__) || defined(_WRS_KERNEL) /* This is VxWorks. Set up things specially for that OS */ #include #include /* amalgamator: dontcache */ #define OS_VXWORKS 1 #define SQLITE_OS_OTHER 0 #define SQLITE_HOMEGROWN_RECURSIVE_MUTEX 1 #define SQLITE_OMIT_LOAD_EXTENSION 1 #define SQLITE_ENABLE_LOCKING_STYLE 0 #define HAVE_UTIME 1 #else /* This is not VxWorks. */ #define OS_VXWORKS 0 #define HAVE_FCHOWN 1 #define HAVE_READLINK 1 #define HAVE_LSTAT 1 #endif /* defined(_WRS_KERNEL) */ /************** End of vxworks.h *********************************************/ /************** Continuing where we left off in sqliteInt.h ******************/ /* ** These #defines should enable >2GB file support on POSIX if the ** underlying operating system supports it. If the OS lacks ** large file support, or if the OS is windows, these should be no-ops. ** ** Ticket #2739: The _LARGEFILE_SOURCE macro must appear before any ** system #includes. Hence, this block of code must be the very first ** code in all source files. ** ** Large file support can be disabled using the -DSQLITE_DISABLE_LFS switch ** on the compiler command line. This is necessary if you are compiling ** on a recent machine (ex: Red Hat 7.2) but you want your code to work ** on an older machine (ex: Red Hat 6.0). If you compile on Red Hat 7.2 ** without this option, LFS is enable. But LFS does not exist in the kernel ** in Red Hat 6.0, so the code won't work. Hence, for maximum binary ** portability you should omit LFS. ** ** The previous paragraph was written in 2005. (This paragraph is written ** on 2008-11-28.) These days, all Linux kernels support large files, so ** you should probably leave LFS enabled. But some embedded platforms might ** lack LFS in which case the SQLITE_DISABLE_LFS macro might still be useful. ** ** Similar is true for Mac OS X. LFS is only supported on Mac OS X 9 and later. */ #ifndef SQLITE_DISABLE_LFS # define _LARGE_FILE 1 # ifndef _FILE_OFFSET_BITS # define _FILE_OFFSET_BITS 64 # endif # define _LARGEFILE_SOURCE 1 #endif /* What version of GCC is being used. 0 means GCC is not being used */ #ifdef __GNUC__ # define GCC_VERSION (__GNUC__*1000000+__GNUC_MINOR__*1000+__GNUC_PATCHLEVEL__) #else # define GCC_VERSION 0 #endif /* Needed for various definitions... */ #if defined(__GNUC__) && !defined(_GNU_SOURCE) # define _GNU_SOURCE #endif #if defined(__OpenBSD__) && !defined(_BSD_SOURCE) # define _BSD_SOURCE #endif /* ** For MinGW, check to see if we can include the header file containing its ** version information, among other things. Normally, this internal MinGW ** header file would [only] be included automatically by other MinGW header ** files; however, the contained version information is now required by this ** header file to work around binary compatibility issues (see below) and ** this is the only known way to reliably obtain it. This entire #if block ** would be completely unnecessary if there was any other way of detecting ** MinGW via their preprocessor (e.g. if they customized their GCC to define ** some MinGW-specific macros). When compiling for MinGW, either the ** _HAVE_MINGW_H or _HAVE__MINGW_H (note the extra underscore) macro must be ** defined; otherwise, detection of conditions specific to MinGW will be ** disabled. */ #if defined(_HAVE_MINGW_H) # include "mingw.h" #elif defined(_HAVE__MINGW_H) # include "_mingw.h" #endif /* ** For MinGW version 4.x (and higher), check to see if the _USE_32BIT_TIME_T ** define is required to maintain binary compatibility with the MSVC runtime ** library in use (e.g. for Windows XP). */ #if !defined(_USE_32BIT_TIME_T) && !defined(_USE_64BIT_TIME_T) && \ defined(_WIN32) && !defined(_WIN64) && \ defined(__MINGW_MAJOR_VERSION) && __MINGW_MAJOR_VERSION >= 4 && \ defined(__MSVCRT__) # define _USE_32BIT_TIME_T #endif /* The public SQLite interface. The _FILE_OFFSET_BITS macro must appear ** first in QNX. Also, the _USE_32BIT_TIME_T macro must appear first for ** MinGW. */ /************** Include sqlite3.h in the middle of sqliteInt.h ***************/ /************** Begin file sqlite3.h *****************************************/ /* ** 2001 September 15 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ************************************************************************* ** This header file defines the interface that the SQLite library ** presents to client programs. If a C-function, structure, datatype, ** or constant definition does not appear in this file, then it is ** not a published API of SQLite, is subject to change without ** notice, and should not be referenced by programs that use SQLite. ** ** Some of the definitions that are in this file are marked as ** "experimental". Experimental interfaces are normally new ** features recently added to SQLite. We do not anticipate changes ** to experimental interfaces but reserve the right to make minor changes ** if experience from use "in the wild" suggest such changes are prudent. ** ** The official C-language API documentation for SQLite is derived ** from comments in this file. This file is the authoritative source ** on how SQLite interfaces are supposed to operate. ** ** The name of this file under configuration management is "sqlite.h.in". ** The makefile makes some minor changes to this file (such as inserting ** the version number) and changes its name to "sqlite3.h" as ** part of the build process. */ #ifndef SQLITE3_H #define SQLITE3_H #include /* Needed for the definition of va_list */ /* ** Make sure we can call this stuff from C++. */ #if 0 extern "C" { #endif /* ** Provide the ability to override linkage features of the interface. */ #ifndef SQLITE_EXTERN # define SQLITE_EXTERN extern #endif #ifndef SQLITE_API # define SQLITE_API #endif #ifndef SQLITE_CDECL # define SQLITE_CDECL #endif #ifndef SQLITE_APICALL # define SQLITE_APICALL #endif #ifndef SQLITE_STDCALL # define SQLITE_STDCALL SQLITE_APICALL #endif #ifndef SQLITE_CALLBACK # define SQLITE_CALLBACK #endif #ifndef SQLITE_SYSAPI # define SQLITE_SYSAPI #endif /* ** These no-op macros are used in front of interfaces to mark those ** interfaces as either deprecated or experimental. New applications ** should not use deprecated interfaces - they are supported for backwards ** compatibility only. Application writers should be aware that ** experimental interfaces are subject to change in point releases. ** ** These macros used to resolve to various kinds of compiler magic that ** would generate warning messages when they were used. But that ** compiler magic ended up generating such a flurry of bug reports ** that we have taken it all out and gone back to using simple ** noop macros. */ #define SQLITE_DEPRECATED #define SQLITE_EXPERIMENTAL /* ** Ensure these symbols were not defined by some previous header file. */ #ifdef SQLITE_VERSION # undef SQLITE_VERSION #endif #ifdef SQLITE_VERSION_NUMBER # undef SQLITE_VERSION_NUMBER #endif /* ** CAPI3REF: Compile-Time Library Version Numbers ** ** ^(The [SQLITE_VERSION] C preprocessor macro in the sqlite3.h header ** evaluates to a string literal that is the SQLite version in the ** format "X.Y.Z" where X is the major version number (always 3 for ** SQLite3) and Y is the minor version number and Z is the release number.)^ ** ^(The [SQLITE_VERSION_NUMBER] C preprocessor macro resolves to an integer ** with the value (X*1000000 + Y*1000 + Z) where X, Y, and Z are the same ** numbers used in [SQLITE_VERSION].)^ ** The SQLITE_VERSION_NUMBER for any given release of SQLite will also ** be larger than the release from which it is derived. Either Y will ** be held constant and Z will be incremented or else Y will be incremented ** and Z will be reset to zero. ** ** Since [version 3.6.18] ([dateof:3.6.18]), ** SQLite source code has been stored in the ** Fossil configuration management ** system. ^The SQLITE_SOURCE_ID macro evaluates to ** a string which identifies a particular check-in of SQLite ** within its configuration management system. ^The SQLITE_SOURCE_ID ** string contains the date and time of the check-in (UTC) and an SHA1 ** hash of the entire source tree. ** ** See also: [sqlite3_libversion()], ** [sqlite3_libversion_number()], [sqlite3_sourceid()], ** [sqlite_version()] and [sqlite_source_id()]. */ #define SQLITE_VERSION "3.15.1" #define SQLITE_VERSION_NUMBER 3015001 #define SQLITE_SOURCE_ID "2016-11-04 12:08:49 1136863c76576110e710dd5d69ab6bf347c65e36" /* ** CAPI3REF: Run-Time Library Version Numbers ** KEYWORDS: sqlite3_version, sqlite3_sourceid ** ** These interfaces provide the same information as the [SQLITE_VERSION], ** [SQLITE_VERSION_NUMBER], and [SQLITE_SOURCE_ID] C preprocessor macros ** but are associated with the library instead of the header file. ^(Cautious ** programmers might include assert() statements in their application to ** verify that values returned by these interfaces match the macros in ** the header, and thus ensure that the application is ** compiled with matching library and header files. ** **
** assert( sqlite3_libversion_number()==SQLITE_VERSION_NUMBER );
** assert( strcmp(sqlite3_sourceid(),SQLITE_SOURCE_ID)==0 );
** assert( strcmp(sqlite3_libversion(),SQLITE_VERSION)==0 );
** 
)^ ** ** ^The sqlite3_version[] string constant contains the text of [SQLITE_VERSION] ** macro. ^The sqlite3_libversion() function returns a pointer to the ** to the sqlite3_version[] string constant. The sqlite3_libversion() ** function is provided for use in DLLs since DLL users usually do not have ** direct access to string constants within the DLL. ^The ** sqlite3_libversion_number() function returns an integer equal to ** [SQLITE_VERSION_NUMBER]. ^The sqlite3_sourceid() function returns ** a pointer to a string constant whose value is the same as the ** [SQLITE_SOURCE_ID] C preprocessor macro. ** ** See also: [sqlite_version()] and [sqlite_source_id()]. */ SQLITE_API const char sqlite3_version[] = SQLITE_VERSION; SQLITE_API const char *sqlite3_libversion(void); SQLITE_API const char *sqlite3_sourceid(void); SQLITE_API int sqlite3_libversion_number(void); /* ** CAPI3REF: Run-Time Library Compilation Options Diagnostics ** ** ^The sqlite3_compileoption_used() function returns 0 or 1 ** indicating whether the specified option was defined at ** compile time. ^The SQLITE_ prefix may be omitted from the ** option name passed to sqlite3_compileoption_used(). ** ** ^The sqlite3_compileoption_get() function allows iterating ** over the list of options that were defined at compile time by ** returning the N-th compile time option string. ^If N is out of range, ** sqlite3_compileoption_get() returns a NULL pointer. ^The SQLITE_ ** prefix is omitted from any strings returned by ** sqlite3_compileoption_get(). ** ** ^Support for the diagnostic functions sqlite3_compileoption_used() ** and sqlite3_compileoption_get() may be omitted by specifying the ** [SQLITE_OMIT_COMPILEOPTION_DIAGS] option at compile time. ** ** See also: SQL functions [sqlite_compileoption_used()] and ** [sqlite_compileoption_get()] and the [compile_options pragma]. */ #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS SQLITE_API int sqlite3_compileoption_used(const char *zOptName); SQLITE_API const char *sqlite3_compileoption_get(int N); #endif /* ** CAPI3REF: Test To See If The Library Is Threadsafe ** ** ^The sqlite3_threadsafe() function returns zero if and only if ** SQLite was compiled with mutexing code omitted due to the ** [SQLITE_THREADSAFE] compile-time option being set to 0. ** ** SQLite can be compiled with or without mutexes. When ** the [SQLITE_THREADSAFE] C preprocessor macro is 1 or 2, mutexes ** are enabled and SQLite is threadsafe. When the ** [SQLITE_THREADSAFE] macro is 0, ** the mutexes are omitted. Without the mutexes, it is not safe ** to use SQLite concurrently from more than one thread. ** ** Enabling mutexes incurs a measurable performance penalty. ** So if speed is of utmost importance, it makes sense to disable ** the mutexes. But for maximum safety, mutexes should be enabled. ** ^The default behavior is for mutexes to be enabled. ** ** This interface can be used by an application to make sure that the ** version of SQLite that it is linking against was compiled with ** the desired setting of the [SQLITE_THREADSAFE] macro. ** ** This interface only reports on the compile-time mutex setting ** of the [SQLITE_THREADSAFE] flag. If SQLite is compiled with ** SQLITE_THREADSAFE=1 or =2 then mutexes are enabled by default but ** can be fully or partially disabled using a call to [sqlite3_config()] ** with the verbs [SQLITE_CONFIG_SINGLETHREAD], [SQLITE_CONFIG_MULTITHREAD], ** or [SQLITE_CONFIG_SERIALIZED]. ^(The return value of the ** sqlite3_threadsafe() function shows only the compile-time setting of ** thread safety, not any run-time changes to that setting made by ** sqlite3_config(). In other words, the return value from sqlite3_threadsafe() ** is unchanged by calls to sqlite3_config().)^ ** ** See the [threading mode] documentation for additional information. */ SQLITE_API int sqlite3_threadsafe(void); /* ** CAPI3REF: Database Connection Handle ** KEYWORDS: {database connection} {database connections} ** ** Each open SQLite database is represented by a pointer to an instance of ** the opaque structure named "sqlite3". It is useful to think of an sqlite3 ** pointer as an object. The [sqlite3_open()], [sqlite3_open16()], and ** [sqlite3_open_v2()] interfaces are its constructors, and [sqlite3_close()] ** and [sqlite3_close_v2()] are its destructors. There are many other ** interfaces (such as ** [sqlite3_prepare_v2()], [sqlite3_create_function()], and ** [sqlite3_busy_timeout()] to name but three) that are methods on an ** sqlite3 object. */ typedef struct sqlite3 sqlite3; /* ** CAPI3REF: 64-Bit Integer Types ** KEYWORDS: sqlite_int64 sqlite_uint64 ** ** Because there is no cross-platform way to specify 64-bit integer types ** SQLite includes typedefs for 64-bit signed and unsigned integers. ** ** The sqlite3_int64 and sqlite3_uint64 are the preferred type definitions. ** The sqlite_int64 and sqlite_uint64 types are supported for backwards ** compatibility only. ** ** ^The sqlite3_int64 and sqlite_int64 types can store integer values ** between -9223372036854775808 and +9223372036854775807 inclusive. ^The ** sqlite3_uint64 and sqlite_uint64 types can store integer values ** between 0 and +18446744073709551615 inclusive. */ #ifdef SQLITE_INT64_TYPE typedef SQLITE_INT64_TYPE sqlite_int64; typedef unsigned SQLITE_INT64_TYPE sqlite_uint64; #elif defined(_MSC_VER) || defined(__BORLANDC__) typedef __int64 sqlite_int64; typedef unsigned __int64 sqlite_uint64; #else typedef long long int sqlite_int64; typedef unsigned long long int sqlite_uint64; #endif typedef sqlite_int64 sqlite3_int64; typedef sqlite_uint64 sqlite3_uint64; /* ** If compiling for a processor that lacks floating point support, ** substitute integer for floating-point. */ #ifdef SQLITE_OMIT_FLOATING_POINT # define double sqlite3_int64 #endif /* ** CAPI3REF: Closing A Database Connection ** DESTRUCTOR: sqlite3 ** ** ^The sqlite3_close() and sqlite3_close_v2() routines are destructors ** for the [sqlite3] object. ** ^Calls to sqlite3_close() and sqlite3_close_v2() return [SQLITE_OK] if ** the [sqlite3] object is successfully destroyed and all associated ** resources are deallocated. ** ** ^If the database connection is associated with unfinalized prepared ** statements or unfinished sqlite3_backup objects then sqlite3_close() ** will leave the database connection open and return [SQLITE_BUSY]. ** ^If sqlite3_close_v2() is called with unfinalized prepared statements ** and/or unfinished sqlite3_backups, then the database connection becomes ** an unusable "zombie" which will automatically be deallocated when the ** last prepared statement is finalized or the last sqlite3_backup is ** finished. The sqlite3_close_v2() interface is intended for use with ** host languages that are garbage collected, and where the order in which ** destructors are called is arbitrary. ** ** Applications should [sqlite3_finalize | finalize] all [prepared statements], ** [sqlite3_blob_close | close] all [BLOB handles], and ** [sqlite3_backup_finish | finish] all [sqlite3_backup] objects associated ** with the [sqlite3] object prior to attempting to close the object. ^If ** sqlite3_close_v2() is called on a [database connection] that still has ** outstanding [prepared statements], [BLOB handles], and/or ** [sqlite3_backup] objects then it returns [SQLITE_OK] and the deallocation ** of resources is deferred until all [prepared statements], [BLOB handles], ** and [sqlite3_backup] objects are also destroyed. ** ** ^If an [sqlite3] object is destroyed while a transaction is open, ** the transaction is automatically rolled back. ** ** The C parameter to [sqlite3_close(C)] and [sqlite3_close_v2(C)] ** must be either a NULL ** pointer or an [sqlite3] object pointer obtained ** from [sqlite3_open()], [sqlite3_open16()], or ** [sqlite3_open_v2()], and not previously closed. ** ^Calling sqlite3_close() or sqlite3_close_v2() with a NULL pointer ** argument is a harmless no-op. */ SQLITE_API int sqlite3_close(sqlite3*); SQLITE_API int sqlite3_close_v2(sqlite3*); /* ** The type for a callback function. ** This is legacy and deprecated. It is included for historical ** compatibility and is not documented. */ typedef int (*sqlite3_callback)(void*,int,char**, char**); /* ** CAPI3REF: One-Step Query Execution Interface ** METHOD: sqlite3 ** ** The sqlite3_exec() interface is a convenience wrapper around ** [sqlite3_prepare_v2()], [sqlite3_step()], and [sqlite3_finalize()], ** that allows an application to run multiple statements of SQL ** without having to use a lot of C code. ** ** ^The sqlite3_exec() interface runs zero or more UTF-8 encoded, ** semicolon-separate SQL statements passed into its 2nd argument, ** in the context of the [database connection] passed in as its 1st ** argument. ^If the callback function of the 3rd argument to ** sqlite3_exec() is not NULL, then it is invoked for each result row ** coming out of the evaluated SQL statements. ^The 4th argument to ** sqlite3_exec() is relayed through to the 1st argument of each ** callback invocation. ^If the callback pointer to sqlite3_exec() ** is NULL, then no callback is ever invoked and result rows are ** ignored. ** ** ^If an error occurs while evaluating the SQL statements passed into ** sqlite3_exec(), then execution of the current statement stops and ** subsequent statements are skipped. ^If the 5th parameter to sqlite3_exec() ** is not NULL then any error message is written into memory obtained ** from [sqlite3_malloc()] and passed back through the 5th parameter. ** To avoid memory leaks, the application should invoke [sqlite3_free()] ** on error message strings returned through the 5th parameter of ** sqlite3_exec() after the error message string is no longer needed. ** ^If the 5th parameter to sqlite3_exec() is not NULL and no errors ** occur, then sqlite3_exec() sets the pointer in its 5th parameter to ** NULL before returning. ** ** ^If an sqlite3_exec() callback returns non-zero, the sqlite3_exec() ** routine returns SQLITE_ABORT without invoking the callback again and ** without running any subsequent SQL statements. ** ** ^The 2nd argument to the sqlite3_exec() callback function is the ** number of columns in the result. ^The 3rd argument to the sqlite3_exec() ** callback is an array of pointers to strings obtained as if from ** [sqlite3_column_text()], one for each column. ^If an element of a ** result row is NULL then the corresponding string pointer for the ** sqlite3_exec() callback is a NULL pointer. ^The 4th argument to the ** sqlite3_exec() callback is an array of pointers to strings where each ** entry represents the name of corresponding result column as obtained ** from [sqlite3_column_name()]. ** ** ^If the 2nd parameter to sqlite3_exec() is a NULL pointer, a pointer ** to an empty string, or a pointer that contains only whitespace and/or ** SQL comments, then no SQL statements are evaluated and the database ** is not changed. ** ** Restrictions: ** **
    **
  • The application must ensure that the 1st parameter to sqlite3_exec() ** is a valid and open [database connection]. **
  • The application must not close the [database connection] specified by ** the 1st parameter to sqlite3_exec() while sqlite3_exec() is running. **
  • The application must not modify the SQL statement text passed into ** the 2nd parameter of sqlite3_exec() while sqlite3_exec() is running. **
*/ SQLITE_API int sqlite3_exec( sqlite3*, /* An open database */ const char *sql, /* SQL to be evaluated */ int (*callback)(void*,int,char**,char**), /* Callback function */ void *, /* 1st argument to callback */ char **errmsg /* Error msg written here */ ); /* ** CAPI3REF: Result Codes ** KEYWORDS: {result code definitions} ** ** Many SQLite functions return an integer result code from the set shown ** here in order to indicate success or failure. ** ** New error codes may be added in future versions of SQLite. ** ** See also: [extended result code definitions] */ #define SQLITE_OK 0 /* Successful result */ /* beginning-of-error-codes */ #define SQLITE_ERROR 1 /* SQL error or missing database */ #define SQLITE_INTERNAL 2 /* Internal logic error in SQLite */ #define SQLITE_PERM 3 /* Access permission denied */ #define SQLITE_ABORT 4 /* Callback routine requested an abort */ #define SQLITE_BUSY 5 /* The database file is locked */ #define SQLITE_LOCKED 6 /* A table in the database is locked */ #define SQLITE_NOMEM 7 /* A malloc() failed */ #define SQLITE_READONLY 8 /* Attempt to write a readonly database */ #define SQLITE_INTERRUPT 9 /* Operation terminated by sqlite3_interrupt()*/ #define SQLITE_IOERR 10 /* Some kind of disk I/O error occurred */ #define SQLITE_CORRUPT 11 /* The database disk image is malformed */ #define SQLITE_NOTFOUND 12 /* Unknown opcode in sqlite3_file_control() */ #define SQLITE_FULL 13 /* Insertion failed because database is full */ #define SQLITE_CANTOPEN 14 /* Unable to open the database file */ #define SQLITE_PROTOCOL 15 /* Database lock protocol error */ #define SQLITE_EMPTY 16 /* Database is empty */ #define SQLITE_SCHEMA 17 /* The database schema changed */ #define SQLITE_TOOBIG 18 /* String or BLOB exceeds size limit */ #define SQLITE_CONSTRAINT 19 /* Abort due to constraint violation */ #define SQLITE_MISMATCH 20 /* Data type mismatch */ #define SQLITE_MISUSE 21 /* Library used incorrectly */ #define SQLITE_NOLFS 22 /* Uses OS features not supported on host */ #define SQLITE_AUTH 23 /* Authorization denied */ #define SQLITE_FORMAT 24 /* Auxiliary database format error */ #define SQLITE_RANGE 25 /* 2nd parameter to sqlite3_bind out of range */ #define SQLITE_NOTADB 26 /* File opened that is not a database file */ #define SQLITE_NOTICE 27 /* Notifications from sqlite3_log() */ #define SQLITE_WARNING 28 /* Warnings from sqlite3_log() */ #define SQLITE_ROW 100 /* sqlite3_step() has another row ready */ #define SQLITE_DONE 101 /* sqlite3_step() has finished executing */ /* end-of-error-codes */ /* ** CAPI3REF: Extended Result Codes ** KEYWORDS: {extended result code definitions} ** ** In its default configuration, SQLite API routines return one of 30 integer ** [result codes]. However, experience has shown that many of ** these result codes are too coarse-grained. They do not provide as ** much information about problems as programmers might like. In an effort to ** address this, newer versions of SQLite (version 3.3.8 [dateof:3.3.8] ** and later) include ** support for additional result codes that provide more detailed information ** about errors. These [extended result codes] are enabled or disabled ** on a per database connection basis using the ** [sqlite3_extended_result_codes()] API. Or, the extended code for ** the most recent error can be obtained using ** [sqlite3_extended_errcode()]. */ #define SQLITE_IOERR_READ (SQLITE_IOERR | (1<<8)) #define SQLITE_IOERR_SHORT_READ (SQLITE_IOERR | (2<<8)) #define SQLITE_IOERR_WRITE (SQLITE_IOERR | (3<<8)) #define SQLITE_IOERR_FSYNC (SQLITE_IOERR | (4<<8)) #define SQLITE_IOERR_DIR_FSYNC (SQLITE_IOERR | (5<<8)) #define SQLITE_IOERR_TRUNCATE (SQLITE_IOERR | (6<<8)) #define SQLITE_IOERR_FSTAT (SQLITE_IOERR | (7<<8)) #define SQLITE_IOERR_UNLOCK (SQLITE_IOERR | (8<<8)) #define SQLITE_IOERR_RDLOCK (SQLITE_IOERR | (9<<8)) #define SQLITE_IOERR_DELETE (SQLITE_IOERR | (10<<8)) #define SQLITE_IOERR_BLOCKED (SQLITE_IOERR | (11<<8)) #define SQLITE_IOERR_NOMEM (SQLITE_IOERR | (12<<8)) #define SQLITE_IOERR_ACCESS (SQLITE_IOERR | (13<<8)) #define SQLITE_IOERR_CHECKRESERVEDLOCK (SQLITE_IOERR | (14<<8)) #define SQLITE_IOERR_LOCK (SQLITE_IOERR | (15<<8)) #define SQLITE_IOERR_CLOSE (SQLITE_IOERR | (16<<8)) #define SQLITE_IOERR_DIR_CLOSE (SQLITE_IOERR | (17<<8)) #define SQLITE_IOERR_SHMOPEN (SQLITE_IOERR | (18<<8)) #define SQLITE_IOERR_SHMSIZE (SQLITE_IOERR | (19<<8)) #define SQLITE_IOERR_SHMLOCK (SQLITE_IOERR | (20<<8)) #define SQLITE_IOERR_SHMMAP (SQLITE_IOERR | (21<<8)) #define SQLITE_IOERR_SEEK (SQLITE_IOERR | (22<<8)) #define SQLITE_IOERR_DELETE_NOENT (SQLITE_IOERR | (23<<8)) #define SQLITE_IOERR_MMAP (SQLITE_IOERR | (24<<8)) #define SQLITE_IOERR_GETTEMPPATH (SQLITE_IOERR | (25<<8)) #define SQLITE_IOERR_CONVPATH (SQLITE_IOERR | (26<<8)) #define SQLITE_IOERR_VNODE (SQLITE_IOERR | (27<<8)) #define SQLITE_IOERR_AUTH (SQLITE_IOERR | (28<<8)) #define SQLITE_LOCKED_SHAREDCACHE (SQLITE_LOCKED | (1<<8)) #define SQLITE_BUSY_RECOVERY (SQLITE_BUSY | (1<<8)) #define SQLITE_BUSY_SNAPSHOT (SQLITE_BUSY | (2<<8)) #define SQLITE_CANTOPEN_NOTEMPDIR (SQLITE_CANTOPEN | (1<<8)) #define SQLITE_CANTOPEN_ISDIR (SQLITE_CANTOPEN | (2<<8)) #define SQLITE_CANTOPEN_FULLPATH (SQLITE_CANTOPEN | (3<<8)) #define SQLITE_CANTOPEN_CONVPATH (SQLITE_CANTOPEN | (4<<8)) #define SQLITE_CORRUPT_VTAB (SQLITE_CORRUPT | (1<<8)) #define SQLITE_READONLY_RECOVERY (SQLITE_READONLY | (1<<8)) #define SQLITE_READONLY_CANTLOCK (SQLITE_READONLY | (2<<8)) #define SQLITE_READONLY_ROLLBACK (SQLITE_READONLY | (3<<8)) #define SQLITE_READONLY_DBMOVED (SQLITE_READONLY | (4<<8)) #define SQLITE_ABORT_ROLLBACK (SQLITE_ABORT | (2<<8)) #define SQLITE_CONSTRAINT_CHECK (SQLITE_CONSTRAINT | (1<<8)) #define SQLITE_CONSTRAINT_COMMITHOOK (SQLITE_CONSTRAINT | (2<<8)) #define SQLITE_CONSTRAINT_FOREIGNKEY (SQLITE_CONSTRAINT | (3<<8)) #define SQLITE_CONSTRAINT_FUNCTION (SQLITE_CONSTRAINT | (4<<8)) #define SQLITE_CONSTRAINT_NOTNULL (SQLITE_CONSTRAINT | (5<<8)) #define SQLITE_CONSTRAINT_PRIMARYKEY (SQLITE_CONSTRAINT | (6<<8)) #define SQLITE_CONSTRAINT_TRIGGER (SQLITE_CONSTRAINT | (7<<8)) #define SQLITE_CONSTRAINT_UNIQUE (SQLITE_CONSTRAINT | (8<<8)) #define SQLITE_CONSTRAINT_VTAB (SQLITE_CONSTRAINT | (9<<8)) #define SQLITE_CONSTRAINT_ROWID (SQLITE_CONSTRAINT |(10<<8)) #define SQLITE_NOTICE_RECOVER_WAL (SQLITE_NOTICE | (1<<8)) #define SQLITE_NOTICE_RECOVER_ROLLBACK (SQLITE_NOTICE | (2<<8)) #define SQLITE_WARNING_AUTOINDEX (SQLITE_WARNING | (1<<8)) #define SQLITE_AUTH_USER (SQLITE_AUTH | (1<<8)) #define SQLITE_OK_LOAD_PERMANENTLY (SQLITE_OK | (1<<8)) /* ** CAPI3REF: Flags For File Open Operations ** ** These bit values are intended for use in the ** 3rd parameter to the [sqlite3_open_v2()] interface and ** in the 4th parameter to the [sqlite3_vfs.xOpen] method. */ #define SQLITE_OPEN_READONLY 0x00000001 /* Ok for sqlite3_open_v2() */ #define SQLITE_OPEN_READWRITE 0x00000002 /* Ok for sqlite3_open_v2() */ #define SQLITE_OPEN_CREATE 0x00000004 /* Ok for sqlite3_open_v2() */ #define SQLITE_OPEN_DELETEONCLOSE 0x00000008 /* VFS only */ #define SQLITE_OPEN_EXCLUSIVE 0x00000010 /* VFS only */ #define SQLITE_OPEN_AUTOPROXY 0x00000020 /* VFS only */ #define SQLITE_OPEN_URI 0x00000040 /* Ok for sqlite3_open_v2() */ #define SQLITE_OPEN_MEMORY 0x00000080 /* Ok for sqlite3_open_v2() */ #define SQLITE_OPEN_MAIN_DB 0x00000100 /* VFS only */ #define SQLITE_OPEN_TEMP_DB 0x00000200 /* VFS only */ #define SQLITE_OPEN_TRANSIENT_DB 0x00000400 /* VFS only */ #define SQLITE_OPEN_MAIN_JOURNAL 0x00000800 /* VFS only */ #define SQLITE_OPEN_TEMP_JOURNAL 0x00001000 /* VFS only */ #define SQLITE_OPEN_SUBJOURNAL 0x00002000 /* VFS only */ #define SQLITE_OPEN_MASTER_JOURNAL 0x00004000 /* VFS only */ #define SQLITE_OPEN_NOMUTEX 0x00008000 /* Ok for sqlite3_open_v2() */ #define SQLITE_OPEN_FULLMUTEX 0x00010000 /* Ok for sqlite3_open_v2() */ #define SQLITE_OPEN_SHAREDCACHE 0x00020000 /* Ok for sqlite3_open_v2() */ #define SQLITE_OPEN_PRIVATECACHE 0x00040000 /* Ok for sqlite3_open_v2() */ #define SQLITE_OPEN_WAL 0x00080000 /* VFS only */ /* Reserved: 0x00F00000 */ /* ** CAPI3REF: Device Characteristics ** ** The xDeviceCharacteristics method of the [sqlite3_io_methods] ** object returns an integer which is a vector of these ** bit values expressing I/O characteristics of the mass storage ** device that holds the file that the [sqlite3_io_methods] ** refers to. ** ** The SQLITE_IOCAP_ATOMIC property means that all writes of ** any size are atomic. The SQLITE_IOCAP_ATOMICnnn values ** mean that writes of blocks that are nnn bytes in size and ** are aligned to an address which is an integer multiple of ** nnn are atomic. The SQLITE_IOCAP_SAFE_APPEND value means ** that when data is appended to a file, the data is appended ** first then the size of the file is extended, never the other ** way around. The SQLITE_IOCAP_SEQUENTIAL property means that ** information is written to disk in the same order as calls ** to xWrite(). The SQLITE_IOCAP_POWERSAFE_OVERWRITE property means that ** after reboot following a crash or power loss, the only bytes in a ** file that were written at the application level might have changed ** and that adjacent bytes, even bytes within the same sector are ** guaranteed to be unchanged. The SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN ** flag indicate that a file cannot be deleted when open. The ** SQLITE_IOCAP_IMMUTABLE flag indicates that the file is on ** read-only media and cannot be changed even by processes with ** elevated privileges. */ #define SQLITE_IOCAP_ATOMIC 0x00000001 #define SQLITE_IOCAP_ATOMIC512 0x00000002 #define SQLITE_IOCAP_ATOMIC1K 0x00000004 #define SQLITE_IOCAP_ATOMIC2K 0x00000008 #define SQLITE_IOCAP_ATOMIC4K 0x00000010 #define SQLITE_IOCAP_ATOMIC8K 0x00000020 #define SQLITE_IOCAP_ATOMIC16K 0x00000040 #define SQLITE_IOCAP_ATOMIC32K 0x00000080 #define SQLITE_IOCAP_ATOMIC64K 0x00000100 #define SQLITE_IOCAP_SAFE_APPEND 0x00000200 #define SQLITE_IOCAP_SEQUENTIAL 0x00000400 #define SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN 0x00000800 #define SQLITE_IOCAP_POWERSAFE_OVERWRITE 0x00001000 #define SQLITE_IOCAP_IMMUTABLE 0x00002000 /* ** CAPI3REF: File Locking Levels ** ** SQLite uses one of these integer values as the second ** argument to calls it makes to the xLock() and xUnlock() methods ** of an [sqlite3_io_methods] object. */ #define SQLITE_LOCK_NONE 0 #define SQLITE_LOCK_SHARED 1 #define SQLITE_LOCK_RESERVED 2 #define SQLITE_LOCK_PENDING 3 #define SQLITE_LOCK_EXCLUSIVE 4 /* ** CAPI3REF: Synchronization Type Flags ** ** When SQLite invokes the xSync() method of an ** [sqlite3_io_methods] object it uses a combination of ** these integer values as the second argument. ** ** When the SQLITE_SYNC_DATAONLY flag is used, it means that the ** sync operation only needs to flush data to mass storage. Inode ** information need not be flushed. If the lower four bits of the flag ** equal SQLITE_SYNC_NORMAL, that means to use normal fsync() semantics. ** If the lower four bits equal SQLITE_SYNC_FULL, that means ** to use Mac OS X style fullsync instead of fsync(). ** ** Do not confuse the SQLITE_SYNC_NORMAL and SQLITE_SYNC_FULL flags ** with the [PRAGMA synchronous]=NORMAL and [PRAGMA synchronous]=FULL ** settings. The [synchronous pragma] determines when calls to the ** xSync VFS method occur and applies uniformly across all platforms. ** The SQLITE_SYNC_NORMAL and SQLITE_SYNC_FULL flags determine how ** energetic or rigorous or forceful the sync operations are and ** only make a difference on Mac OSX for the default SQLite code. ** (Third-party VFS implementations might also make the distinction ** between SQLITE_SYNC_NORMAL and SQLITE_SYNC_FULL, but among the ** operating systems natively supported by SQLite, only Mac OSX ** cares about the difference.) */ #define SQLITE_SYNC_NORMAL 0x00002 #define SQLITE_SYNC_FULL 0x00003 #define SQLITE_SYNC_DATAONLY 0x00010 /* ** CAPI3REF: OS Interface Open File Handle ** ** An [sqlite3_file] object represents an open file in the ** [sqlite3_vfs | OS interface layer]. Individual OS interface ** implementations will ** want to subclass this object by appending additional fields ** for their own use. The pMethods entry is a pointer to an ** [sqlite3_io_methods] object that defines methods for performing ** I/O operations on the open file. */ typedef struct sqlite3_file sqlite3_file; struct sqlite3_file { const struct sqlite3_io_methods *pMethods; /* Methods for an open file */ }; /* ** CAPI3REF: OS Interface File Virtual Methods Object ** ** Every file opened by the [sqlite3_vfs.xOpen] method populates an ** [sqlite3_file] object (or, more commonly, a subclass of the ** [sqlite3_file] object) with a pointer to an instance of this object. ** This object defines the methods used to perform various operations ** against the open file represented by the [sqlite3_file] object. ** ** If the [sqlite3_vfs.xOpen] method sets the sqlite3_file.pMethods element ** to a non-NULL pointer, then the sqlite3_io_methods.xClose method ** may be invoked even if the [sqlite3_vfs.xOpen] reported that it failed. The ** only way to prevent a call to xClose following a failed [sqlite3_vfs.xOpen] ** is for the [sqlite3_vfs.xOpen] to set the sqlite3_file.pMethods element ** to NULL. ** ** The flags argument to xSync may be one of [SQLITE_SYNC_NORMAL] or ** [SQLITE_SYNC_FULL]. The first choice is the normal fsync(). ** The second choice is a Mac OS X style fullsync. The [SQLITE_SYNC_DATAONLY] ** flag may be ORed in to indicate that only the data of the file ** and not its inode needs to be synced. ** ** The integer values to xLock() and xUnlock() are one of **
    **
  • [SQLITE_LOCK_NONE], **
  • [SQLITE_LOCK_SHARED], **
  • [SQLITE_LOCK_RESERVED], **
  • [SQLITE_LOCK_PENDING], or **
  • [SQLITE_LOCK_EXCLUSIVE]. **
** xLock() increases the lock. xUnlock() decreases the lock. ** The xCheckReservedLock() method checks whether any database connection, ** either in this process or in some other process, is holding a RESERVED, ** PENDING, or EXCLUSIVE lock on the file. It returns true ** if such a lock exists and false otherwise. ** ** The xFileControl() method is a generic interface that allows custom ** VFS implementations to directly control an open file using the ** [sqlite3_file_control()] interface. The second "op" argument is an ** integer opcode. The third argument is a generic pointer intended to ** point to a structure that may contain arguments or space in which to ** write return values. Potential uses for xFileControl() might be ** functions to enable blocking locks with timeouts, to change the ** locking strategy (for example to use dot-file locks), to inquire ** about the status of a lock, or to break stale locks. The SQLite ** core reserves all opcodes less than 100 for its own use. ** A [file control opcodes | list of opcodes] less than 100 is available. ** Applications that define a custom xFileControl method should use opcodes ** greater than 100 to avoid conflicts. VFS implementations should ** return [SQLITE_NOTFOUND] for file control opcodes that they do not ** recognize. ** ** The xSectorSize() method returns the sector size of the ** device that underlies the file. The sector size is the ** minimum write that can be performed without disturbing ** other bytes in the file. The xDeviceCharacteristics() ** method returns a bit vector describing behaviors of the ** underlying device: ** **
    **
  • [SQLITE_IOCAP_ATOMIC] **
  • [SQLITE_IOCAP_ATOMIC512] **
  • [SQLITE_IOCAP_ATOMIC1K] **
  • [SQLITE_IOCAP_ATOMIC2K] **
  • [SQLITE_IOCAP_ATOMIC4K] **
  • [SQLITE_IOCAP_ATOMIC8K] **
  • [SQLITE_IOCAP_ATOMIC16K] **
  • [SQLITE_IOCAP_ATOMIC32K] **
  • [SQLITE_IOCAP_ATOMIC64K] **
  • [SQLITE_IOCAP_SAFE_APPEND] **
  • [SQLITE_IOCAP_SEQUENTIAL] **
** ** The SQLITE_IOCAP_ATOMIC property means that all writes of ** any size are atomic. The SQLITE_IOCAP_ATOMICnnn values ** mean that writes of blocks that are nnn bytes in size and ** are aligned to an address which is an integer multiple of ** nnn are atomic. The SQLITE_IOCAP_SAFE_APPEND value means ** that when data is appended to a file, the data is appended ** first then the size of the file is extended, never the other ** way around. The SQLITE_IOCAP_SEQUENTIAL property means that ** information is written to disk in the same order as calls ** to xWrite(). ** ** If xRead() returns SQLITE_IOERR_SHORT_READ it must also fill ** in the unread portions of the buffer with zeros. A VFS that ** fails to zero-fill short reads might seem to work. However, ** failure to zero-fill short reads will eventually lead to ** database corruption. */ typedef struct sqlite3_io_methods sqlite3_io_methods; struct sqlite3_io_methods { int iVersion; int (*xClose)(sqlite3_file*); int (*xRead)(sqlite3_file*, void*, int iAmt, sqlite3_int64 iOfst); int (*xWrite)(sqlite3_file*, const void*, int iAmt, sqlite3_int64 iOfst); int (*xTruncate)(sqlite3_file*, sqlite3_int64 size); int (*xSync)(sqlite3_file*, int flags); int (*xFileSize)(sqlite3_file*, sqlite3_int64 *pSize); int (*xLock)(sqlite3_file*, int); int (*xUnlock)(sqlite3_file*, int); int (*xCheckReservedLock)(sqlite3_file*, int *pResOut); int (*xFileControl)(sqlite3_file*, int op, void *pArg); int (*xSectorSize)(sqlite3_file*); int (*xDeviceCharacteristics)(sqlite3_file*); /* Methods above are valid for version 1 */ int (*xShmMap)(sqlite3_file*, int iPg, int pgsz, int, void volatile**); int (*xShmLock)(sqlite3_file*, int offset, int n, int flags); void (*xShmBarrier)(sqlite3_file*); int (*xShmUnmap)(sqlite3_file*, int deleteFlag); /* Methods above are valid for version 2 */ int (*xFetch)(sqlite3_file*, sqlite3_int64 iOfst, int iAmt, void **pp); int (*xUnfetch)(sqlite3_file*, sqlite3_int64 iOfst, void *p); /* Methods above are valid for version 3 */ /* Additional methods may be added in future releases */ }; /* ** CAPI3REF: Standard File Control Opcodes ** KEYWORDS: {file control opcodes} {file control opcode} ** ** These integer constants are opcodes for the xFileControl method ** of the [sqlite3_io_methods] object and for the [sqlite3_file_control()] ** interface. ** **
    **
  • [[SQLITE_FCNTL_LOCKSTATE]] ** The [SQLITE_FCNTL_LOCKSTATE] opcode is used for debugging. This ** opcode causes the xFileControl method to write the current state of ** the lock (one of [SQLITE_LOCK_NONE], [SQLITE_LOCK_SHARED], ** [SQLITE_LOCK_RESERVED], [SQLITE_LOCK_PENDING], or [SQLITE_LOCK_EXCLUSIVE]) ** into an integer that the pArg argument points to. This capability ** is used during testing and is only available when the SQLITE_TEST ** compile-time option is used. ** **
  • [[SQLITE_FCNTL_SIZE_HINT]] ** The [SQLITE_FCNTL_SIZE_HINT] opcode is used by SQLite to give the VFS ** layer a hint of how large the database file will grow to be during the ** current transaction. This hint is not guaranteed to be accurate but it ** is often close. The underlying VFS might choose to preallocate database ** file space based on this hint in order to help writes to the database ** file run faster. ** **
  • [[SQLITE_FCNTL_CHUNK_SIZE]] ** The [SQLITE_FCNTL_CHUNK_SIZE] opcode is used to request that the VFS ** extends and truncates the database file in chunks of a size specified ** by the user. The fourth argument to [sqlite3_file_control()] should ** point to an integer (type int) containing the new chunk-size to use ** for the nominated database. Allocating database file space in large ** chunks (say 1MB at a time), may reduce file-system fragmentation and ** improve performance on some systems. ** **
  • [[SQLITE_FCNTL_FILE_POINTER]] ** The [SQLITE_FCNTL_FILE_POINTER] opcode is used to obtain a pointer ** to the [sqlite3_file] object associated with a particular database ** connection. See also [SQLITE_FCNTL_JOURNAL_POINTER]. ** **
  • [[SQLITE_FCNTL_JOURNAL_POINTER]] ** The [SQLITE_FCNTL_JOURNAL_POINTER] opcode is used to obtain a pointer ** to the [sqlite3_file] object associated with the journal file (either ** the [rollback journal] or the [write-ahead log]) for a particular database ** connection. See also [SQLITE_FCNTL_FILE_POINTER]. ** **
  • [[SQLITE_FCNTL_SYNC_OMITTED]] ** No longer in use. ** **
  • [[SQLITE_FCNTL_SYNC]] ** The [SQLITE_FCNTL_SYNC] opcode is generated internally by SQLite and ** sent to the VFS immediately before the xSync method is invoked on a ** database file descriptor. Or, if the xSync method is not invoked ** because the user has configured SQLite with ** [PRAGMA synchronous | PRAGMA synchronous=OFF] it is invoked in place ** of the xSync method. In most cases, the pointer argument passed with ** this file-control is NULL. However, if the database file is being synced ** as part of a multi-database commit, the argument points to a nul-terminated ** string containing the transactions master-journal file name. VFSes that ** do not need this signal should silently ignore this opcode. Applications ** should not call [sqlite3_file_control()] with this opcode as doing so may ** disrupt the operation of the specialized VFSes that do require it. ** **
  • [[SQLITE_FCNTL_COMMIT_PHASETWO]] ** The [SQLITE_FCNTL_COMMIT_PHASETWO] opcode is generated internally by SQLite ** and sent to the VFS after a transaction has been committed immediately ** but before the database is unlocked. VFSes that do not need this signal ** should silently ignore this opcode. Applications should not call ** [sqlite3_file_control()] with this opcode as doing so may disrupt the ** operation of the specialized VFSes that do require it. ** **
  • [[SQLITE_FCNTL_WIN32_AV_RETRY]] ** ^The [SQLITE_FCNTL_WIN32_AV_RETRY] opcode is used to configure automatic ** retry counts and intervals for certain disk I/O operations for the ** windows [VFS] in order to provide robustness in the presence of ** anti-virus programs. By default, the windows VFS will retry file read, ** file write, and file delete operations up to 10 times, with a delay ** of 25 milliseconds before the first retry and with the delay increasing ** by an additional 25 milliseconds with each subsequent retry. This ** opcode allows these two values (10 retries and 25 milliseconds of delay) ** to be adjusted. The values are changed for all database connections ** within the same process. The argument is a pointer to an array of two ** integers where the first integer i the new retry count and the second ** integer is the delay. If either integer is negative, then the setting ** is not changed but instead the prior value of that setting is written ** into the array entry, allowing the current retry settings to be ** interrogated. The zDbName parameter is ignored. ** **
  • [[SQLITE_FCNTL_PERSIST_WAL]] ** ^The [SQLITE_FCNTL_PERSIST_WAL] opcode is used to set or query the ** persistent [WAL | Write Ahead Log] setting. By default, the auxiliary ** write ahead log and shared memory files used for transaction control ** are automatically deleted when the latest connection to the database ** closes. Setting persistent WAL mode causes those files to persist after ** close. Persisting the files is useful when other processes that do not ** have write permission on the directory containing the database file want ** to read the database file, as the WAL and shared memory files must exist ** in order for the database to be readable. The fourth parameter to ** [sqlite3_file_control()] for this opcode should be a pointer to an integer. ** That integer is 0 to disable persistent WAL mode or 1 to enable persistent ** WAL mode. If the integer is -1, then it is overwritten with the current ** WAL persistence setting. ** **
  • [[SQLITE_FCNTL_POWERSAFE_OVERWRITE]] ** ^The [SQLITE_FCNTL_POWERSAFE_OVERWRITE] opcode is used to set or query the ** persistent "powersafe-overwrite" or "PSOW" setting. The PSOW setting ** determines the [SQLITE_IOCAP_POWERSAFE_OVERWRITE] bit of the ** xDeviceCharacteristics methods. The fourth parameter to ** [sqlite3_file_control()] for this opcode should be a pointer to an integer. ** That integer is 0 to disable zero-damage mode or 1 to enable zero-damage ** mode. If the integer is -1, then it is overwritten with the current ** zero-damage mode setting. ** **
  • [[SQLITE_FCNTL_OVERWRITE]] ** ^The [SQLITE_FCNTL_OVERWRITE] opcode is invoked by SQLite after opening ** a write transaction to indicate that, unless it is rolled back for some ** reason, the entire database file will be overwritten by the current ** transaction. This is used by VACUUM operations. ** **
  • [[SQLITE_FCNTL_VFSNAME]] ** ^The [SQLITE_FCNTL_VFSNAME] opcode can be used to obtain the names of ** all [VFSes] in the VFS stack. The names are of all VFS shims and the ** final bottom-level VFS are written into memory obtained from ** [sqlite3_malloc()] and the result is stored in the char* variable ** that the fourth parameter of [sqlite3_file_control()] points to. ** The caller is responsible for freeing the memory when done. As with ** all file-control actions, there is no guarantee that this will actually ** do anything. Callers should initialize the char* variable to a NULL ** pointer in case this file-control is not implemented. This file-control ** is intended for diagnostic use only. ** **
  • [[SQLITE_FCNTL_VFS_POINTER]] ** ^The [SQLITE_FCNTL_VFS_POINTER] opcode finds a pointer to the top-level ** [VFSes] currently in use. ^(The argument X in ** sqlite3_file_control(db,SQLITE_FCNTL_VFS_POINTER,X) must be ** of type "[sqlite3_vfs] **". This opcodes will set *X ** to a pointer to the top-level VFS.)^ ** ^When there are multiple VFS shims in the stack, this opcode finds the ** upper-most shim only. ** **
  • [[SQLITE_FCNTL_PRAGMA]] ** ^Whenever a [PRAGMA] statement is parsed, an [SQLITE_FCNTL_PRAGMA] ** file control is sent to the open [sqlite3_file] object corresponding ** to the database file to which the pragma statement refers. ^The argument ** to the [SQLITE_FCNTL_PRAGMA] file control is an array of ** pointers to strings (char**) in which the second element of the array ** is the name of the pragma and the third element is the argument to the ** pragma or NULL if the pragma has no argument. ^The handler for an ** [SQLITE_FCNTL_PRAGMA] file control can optionally make the first element ** of the char** argument point to a string obtained from [sqlite3_mprintf()] ** or the equivalent and that string will become the result of the pragma or ** the error message if the pragma fails. ^If the ** [SQLITE_FCNTL_PRAGMA] file control returns [SQLITE_NOTFOUND], then normal ** [PRAGMA] processing continues. ^If the [SQLITE_FCNTL_PRAGMA] ** file control returns [SQLITE_OK], then the parser assumes that the ** VFS has handled the PRAGMA itself and the parser generates a no-op ** prepared statement if result string is NULL, or that returns a copy ** of the result string if the string is non-NULL. ** ^If the [SQLITE_FCNTL_PRAGMA] file control returns ** any result code other than [SQLITE_OK] or [SQLITE_NOTFOUND], that means ** that the VFS encountered an error while handling the [PRAGMA] and the ** compilation of the PRAGMA fails with an error. ^The [SQLITE_FCNTL_PRAGMA] ** file control occurs at the beginning of pragma statement analysis and so ** it is able to override built-in [PRAGMA] statements. ** **
  • [[SQLITE_FCNTL_BUSYHANDLER]] ** ^The [SQLITE_FCNTL_BUSYHANDLER] ** file-control may be invoked by SQLite on the database file handle ** shortly after it is opened in order to provide a custom VFS with access ** to the connections busy-handler callback. The argument is of type (void **) ** - an array of two (void *) values. The first (void *) actually points ** to a function of type (int (*)(void *)). In order to invoke the connections ** busy-handler, this function should be invoked with the second (void *) in ** the array as the only argument. If it returns non-zero, then the operation ** should be retried. If it returns zero, the custom VFS should abandon the ** current operation. ** **
  • [[SQLITE_FCNTL_TEMPFILENAME]] ** ^Application can invoke the [SQLITE_FCNTL_TEMPFILENAME] file-control ** to have SQLite generate a ** temporary filename using the same algorithm that is followed to generate ** temporary filenames for TEMP tables and other internal uses. The ** argument should be a char** which will be filled with the filename ** written into memory obtained from [sqlite3_malloc()]. The caller should ** invoke [sqlite3_free()] on the result to avoid a memory leak. ** **
  • [[SQLITE_FCNTL_MMAP_SIZE]] ** The [SQLITE_FCNTL_MMAP_SIZE] file control is used to query or set the ** maximum number of bytes that will be used for memory-mapped I/O. ** The argument is a pointer to a value of type sqlite3_int64 that ** is an advisory maximum number of bytes in the file to memory map. The ** pointer is overwritten with the old value. The limit is not changed if ** the value originally pointed to is negative, and so the current limit ** can be queried by passing in a pointer to a negative number. This ** file-control is used internally to implement [PRAGMA mmap_size]. ** **
  • [[SQLITE_FCNTL_TRACE]] ** The [SQLITE_FCNTL_TRACE] file control provides advisory information ** to the VFS about what the higher layers of the SQLite stack are doing. ** This file control is used by some VFS activity tracing [shims]. ** The argument is a zero-terminated string. Higher layers in the ** SQLite stack may generate instances of this file control if ** the [SQLITE_USE_FCNTL_TRACE] compile-time option is enabled. ** **
  • [[SQLITE_FCNTL_HAS_MOVED]] ** The [SQLITE_FCNTL_HAS_MOVED] file control interprets its argument as a ** pointer to an integer and it writes a boolean into that integer depending ** on whether or not the file has been renamed, moved, or deleted since it ** was first opened. ** **
  • [[SQLITE_FCNTL_WIN32_GET_HANDLE]] ** The [SQLITE_FCNTL_WIN32_GET_HANDLE] opcode can be used to obtain the ** underlying native file handle associated with a file handle. This file ** control interprets its argument as a pointer to a native file handle and ** writes the resulting value there. ** **
  • [[SQLITE_FCNTL_WIN32_SET_HANDLE]] ** The [SQLITE_FCNTL_WIN32_SET_HANDLE] opcode is used for debugging. This ** opcode causes the xFileControl method to swap the file handle with the one ** pointed to by the pArg argument. This capability is used during testing ** and only needs to be supported when SQLITE_TEST is defined. ** **
  • [[SQLITE_FCNTL_WAL_BLOCK]] ** The [SQLITE_FCNTL_WAL_BLOCK] is a signal to the VFS layer that it might ** be advantageous to block on the next WAL lock if the lock is not immediately ** available. The WAL subsystem issues this signal during rare ** circumstances in order to fix a problem with priority inversion. ** Applications should not use this file-control. ** **
  • [[SQLITE_FCNTL_ZIPVFS]] ** The [SQLITE_FCNTL_ZIPVFS] opcode is implemented by zipvfs only. All other ** VFS should return SQLITE_NOTFOUND for this opcode. ** **
  • [[SQLITE_FCNTL_RBU]] ** The [SQLITE_FCNTL_RBU] opcode is implemented by the special VFS used by ** the RBU extension only. All other VFS should return SQLITE_NOTFOUND for ** this opcode. **
*/ #define SQLITE_FCNTL_LOCKSTATE 1 #define SQLITE_FCNTL_GET_LOCKPROXYFILE 2 #define SQLITE_FCNTL_SET_LOCKPROXYFILE 3 #define SQLITE_FCNTL_LAST_ERRNO 4 #define SQLITE_FCNTL_SIZE_HINT 5 #define SQLITE_FCNTL_CHUNK_SIZE 6 #define SQLITE_FCNTL_FILE_POINTER 7 #define SQLITE_FCNTL_SYNC_OMITTED 8 #define SQLITE_FCNTL_WIN32_AV_RETRY 9 #define SQLITE_FCNTL_PERSIST_WAL 10 #define SQLITE_FCNTL_OVERWRITE 11 #define SQLITE_FCNTL_VFSNAME 12 #define SQLITE_FCNTL_POWERSAFE_OVERWRITE 13 #define SQLITE_FCNTL_PRAGMA 14 #define SQLITE_FCNTL_BUSYHANDLER 15 #define SQLITE_FCNTL_TEMPFILENAME 16 #define SQLITE_FCNTL_MMAP_SIZE 18 #define SQLITE_FCNTL_TRACE 19 #define SQLITE_FCNTL_HAS_MOVED 20 #define SQLITE_FCNTL_SYNC 21 #define SQLITE_FCNTL_COMMIT_PHASETWO 22 #define SQLITE_FCNTL_WIN32_SET_HANDLE 23 #define SQLITE_FCNTL_WAL_BLOCK 24 #define SQLITE_FCNTL_ZIPVFS 25 #define SQLITE_FCNTL_RBU 26 #define SQLITE_FCNTL_VFS_POINTER 27 #define SQLITE_FCNTL_JOURNAL_POINTER 28 #define SQLITE_FCNTL_WIN32_GET_HANDLE 29 /* deprecated names */ #define SQLITE_GET_LOCKPROXYFILE SQLITE_FCNTL_GET_LOCKPROXYFILE #define SQLITE_SET_LOCKPROXYFILE SQLITE_FCNTL_SET_LOCKPROXYFILE #define SQLITE_LAST_ERRNO SQLITE_FCNTL_LAST_ERRNO /* ** CAPI3REF: Mutex Handle ** ** The mutex module within SQLite defines [sqlite3_mutex] to be an ** abstract type for a mutex object. The SQLite core never looks ** at the internal representation of an [sqlite3_mutex]. It only ** deals with pointers to the [sqlite3_mutex] object. ** ** Mutexes are created using [sqlite3_mutex_alloc()]. */ typedef struct sqlite3_mutex sqlite3_mutex; /* ** CAPI3REF: Loadable Extension Thunk ** ** A pointer to the opaque sqlite3_api_routines structure is passed as ** the third parameter to entry points of [loadable extensions]. This ** structure must be typedefed in order to work around compiler warnings ** on some platforms. */ typedef struct sqlite3_api_routines sqlite3_api_routines; /* ** CAPI3REF: OS Interface Object ** ** An instance of the sqlite3_vfs object defines the interface between ** the SQLite core and the underlying operating system. The "vfs" ** in the name of the object stands for "virtual file system". See ** the [VFS | VFS documentation] for further information. ** ** The value of the iVersion field is initially 1 but may be larger in ** future versions of SQLite. Additional fields may be appended to this ** object when the iVersion value is increased. Note that the structure ** of the sqlite3_vfs object changes in the transaction between ** SQLite version 3.5.9 and 3.6.0 and yet the iVersion field was not ** modified. ** ** The szOsFile field is the size of the subclassed [sqlite3_file] ** structure used by this VFS. mxPathname is the maximum length of ** a pathname in this VFS. ** ** Registered sqlite3_vfs objects are kept on a linked list formed by ** the pNext pointer. The [sqlite3_vfs_register()] ** and [sqlite3_vfs_unregister()] interfaces manage this list ** in a thread-safe way. The [sqlite3_vfs_find()] interface ** searches the list. Neither the application code nor the VFS ** implementation should use the pNext pointer. ** ** The pNext field is the only field in the sqlite3_vfs ** structure that SQLite will ever modify. SQLite will only access ** or modify this field while holding a particular static mutex. ** The application should never modify anything within the sqlite3_vfs ** object once the object has been registered. ** ** The zName field holds the name of the VFS module. The name must ** be unique across all VFS modules. ** ** [[sqlite3_vfs.xOpen]] ** ^SQLite guarantees that the zFilename parameter to xOpen ** is either a NULL pointer or string obtained ** from xFullPathname() with an optional suffix added. ** ^If a suffix is added to the zFilename parameter, it will ** consist of a single "-" character followed by no more than ** 11 alphanumeric and/or "-" characters. ** ^SQLite further guarantees that ** the string will be valid and unchanged until xClose() is ** called. Because of the previous sentence, ** the [sqlite3_file] can safely store a pointer to the ** filename if it needs to remember the filename for some reason. ** If the zFilename parameter to xOpen is a NULL pointer then xOpen ** must invent its own temporary name for the file. ^Whenever the ** xFilename parameter is NULL it will also be the case that the ** flags parameter will include [SQLITE_OPEN_DELETEONCLOSE]. ** ** The flags argument to xOpen() includes all bits set in ** the flags argument to [sqlite3_open_v2()]. Or if [sqlite3_open()] ** or [sqlite3_open16()] is used, then flags includes at least ** [SQLITE_OPEN_READWRITE] | [SQLITE_OPEN_CREATE]. ** If xOpen() opens a file read-only then it sets *pOutFlags to ** include [SQLITE_OPEN_READONLY]. Other bits in *pOutFlags may be set. ** ** ^(SQLite will also add one of the following flags to the xOpen() ** call, depending on the object being opened: ** **
    **
  • [SQLITE_OPEN_MAIN_DB] **
  • [SQLITE_OPEN_MAIN_JOURNAL] **
  • [SQLITE_OPEN_TEMP_DB] **
  • [SQLITE_OPEN_TEMP_JOURNAL] **
  • [SQLITE_OPEN_TRANSIENT_DB] **
  • [SQLITE_OPEN_SUBJOURNAL] **
  • [SQLITE_OPEN_MASTER_JOURNAL] **
  • [SQLITE_OPEN_WAL] **
)^ ** ** The file I/O implementation can use the object type flags to ** change the way it deals with files. For example, an application ** that does not care about crash recovery or rollback might make ** the open of a journal file a no-op. Writes to this journal would ** also be no-ops, and any attempt to read the journal would return ** SQLITE_IOERR. Or the implementation might recognize that a database ** file will be doing page-aligned sector reads and writes in a random ** order and set up its I/O subsystem accordingly. ** ** SQLite might also add one of the following flags to the xOpen method: ** **
    **
  • [SQLITE_OPEN_DELETEONCLOSE] **
  • [SQLITE_OPEN_EXCLUSIVE] **
** ** The [SQLITE_OPEN_DELETEONCLOSE] flag means the file should be ** deleted when it is closed. ^The [SQLITE_OPEN_DELETEONCLOSE] ** will be set for TEMP databases and their journals, transient ** databases, and subjournals. ** ** ^The [SQLITE_OPEN_EXCLUSIVE] flag is always used in conjunction ** with the [SQLITE_OPEN_CREATE] flag, which are both directly ** analogous to the O_EXCL and O_CREAT flags of the POSIX open() ** API. The SQLITE_OPEN_EXCLUSIVE flag, when paired with the ** SQLITE_OPEN_CREATE, is used to indicate that file should always ** be created, and that it is an error if it already exists. ** It is not used to indicate the file should be opened ** for exclusive access. ** ** ^At least szOsFile bytes of memory are allocated by SQLite ** to hold the [sqlite3_file] structure passed as the third ** argument to xOpen. The xOpen method does not have to ** allocate the structure; it should just fill it in. Note that ** the xOpen method must set the sqlite3_file.pMethods to either ** a valid [sqlite3_io_methods] object or to NULL. xOpen must do ** this even if the open fails. SQLite expects that the sqlite3_file.pMethods ** element will be valid after xOpen returns regardless of the success ** or failure of the xOpen call. ** ** [[sqlite3_vfs.xAccess]] ** ^The flags argument to xAccess() may be [SQLITE_ACCESS_EXISTS] ** to test for the existence of a file, or [SQLITE_ACCESS_READWRITE] to ** test whether a file is readable and writable, or [SQLITE_ACCESS_READ] ** to test whether a file is at least readable. The file can be a ** directory. ** ** ^SQLite will always allocate at least mxPathname+1 bytes for the ** output buffer xFullPathname. The exact size of the output buffer ** is also passed as a parameter to both methods. If the output buffer ** is not large enough, [SQLITE_CANTOPEN] should be returned. Since this is ** handled as a fatal error by SQLite, vfs implementations should endeavor ** to prevent this by setting mxPathname to a sufficiently large value. ** ** The xRandomness(), xSleep(), xCurrentTime(), and xCurrentTimeInt64() ** interfaces are not strictly a part of the filesystem, but they are ** included in the VFS structure for completeness. ** The xRandomness() function attempts to return nBytes bytes ** of good-quality randomness into zOut. The return value is ** the actual number of bytes of randomness obtained. ** The xSleep() method causes the calling thread to sleep for at ** least the number of microseconds given. ^The xCurrentTime() ** method returns a Julian Day Number for the current date and time as ** a floating point value. ** ^The xCurrentTimeInt64() method returns, as an integer, the Julian ** Day Number multiplied by 86400000 (the number of milliseconds in ** a 24-hour day). ** ^SQLite will use the xCurrentTimeInt64() method to get the current ** date and time if that method is available (if iVersion is 2 or ** greater and the function pointer is not NULL) and will fall back ** to xCurrentTime() if xCurrentTimeInt64() is unavailable. ** ** ^The xSetSystemCall(), xGetSystemCall(), and xNestSystemCall() interfaces ** are not used by the SQLite core. These optional interfaces are provided ** by some VFSes to facilitate testing of the VFS code. By overriding ** system calls with functions under its control, a test program can ** simulate faults and error conditions that would otherwise be difficult ** or impossible to induce. The set of system calls that can be overridden ** varies from one VFS to another, and from one version of the same VFS to the ** next. Applications that use these interfaces must be prepared for any ** or all of these interfaces to be NULL or for their behavior to change ** from one release to the next. Applications must not attempt to access ** any of these methods if the iVersion of the VFS is less than 3. */ typedef struct sqlite3_vfs sqlite3_vfs; typedef void (*sqlite3_syscall_ptr)(void); struct sqlite3_vfs { int iVersion; /* Structure version number (currently 3) */ int szOsFile; /* Size of subclassed sqlite3_file */ int mxPathname; /* Maximum file pathname length */ sqlite3_vfs *pNext; /* Next registered VFS */ const char *zName; /* Name of this virtual file system */ void *pAppData; /* Pointer to application-specific data */ int (*xOpen)(sqlite3_vfs*, const char *zName, sqlite3_file*, int flags, int *pOutFlags); int (*xDelete)(sqlite3_vfs*, const char *zName, int syncDir); int (*xAccess)(sqlite3_vfs*, const char *zName, int flags, int *pResOut); int (*xFullPathname)(sqlite3_vfs*, const char *zName, int nOut, char *zOut); void *(*xDlOpen)(sqlite3_vfs*, const char *zFilename); void (*xDlError)(sqlite3_vfs*, int nByte, char *zErrMsg); void (*(*xDlSym)(sqlite3_vfs*,void*, const char *zSymbol))(void); void (*xDlClose)(sqlite3_vfs*, void*); int (*xRandomness)(sqlite3_vfs*, int nByte, char *zOut); int (*xSleep)(sqlite3_vfs*, int microseconds); int (*xCurrentTime)(sqlite3_vfs*, double*); int (*xGetLastError)(sqlite3_vfs*, int, char *); /* ** The methods above are in version 1 of the sqlite_vfs object ** definition. Those that follow are added in version 2 or later */ int (*xCurrentTimeInt64)(sqlite3_vfs*, sqlite3_int64*); /* ** The methods above are in versions 1 and 2 of the sqlite_vfs object. ** Those below are for version 3 and greater. */ int (*xSetSystemCall)(sqlite3_vfs*, const char *zName, sqlite3_syscall_ptr); sqlite3_syscall_ptr (*xGetSystemCall)(sqlite3_vfs*, const char *zName); const char *(*xNextSystemCall)(sqlite3_vfs*, const char *zName); /* ** The methods above are in versions 1 through 3 of the sqlite_vfs object. ** New fields may be appended in future versions. The iVersion ** value will increment whenever this happens. */ }; /* ** CAPI3REF: Flags for the xAccess VFS method ** ** These integer constants can be used as the third parameter to ** the xAccess method of an [sqlite3_vfs] object. They determine ** what kind of permissions the xAccess method is looking for. ** With SQLITE_ACCESS_EXISTS, the xAccess method ** simply checks whether the file exists. ** With SQLITE_ACCESS_READWRITE, the xAccess method ** checks whether the named directory is both readable and writable ** (in other words, if files can be added, removed, and renamed within ** the directory). ** The SQLITE_ACCESS_READWRITE constant is currently used only by the ** [temp_store_directory pragma], though this could change in a future ** release of SQLite. ** With SQLITE_ACCESS_READ, the xAccess method ** checks whether the file is readable. The SQLITE_ACCESS_READ constant is ** currently unused, though it might be used in a future release of ** SQLite. */ #define SQLITE_ACCESS_EXISTS 0 #define SQLITE_ACCESS_READWRITE 1 /* Used by PRAGMA temp_store_directory */ #define SQLITE_ACCESS_READ 2 /* Unused */ /* ** CAPI3REF: Flags for the xShmLock VFS method ** ** These integer constants define the various locking operations ** allowed by the xShmLock method of [sqlite3_io_methods]. The ** following are the only legal combinations of flags to the ** xShmLock method: ** **
    **
  • SQLITE_SHM_LOCK | SQLITE_SHM_SHARED **
  • SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE **
  • SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED **
  • SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE **
** ** When unlocking, the same SHARED or EXCLUSIVE flag must be supplied as ** was given on the corresponding lock. ** ** The xShmLock method can transition between unlocked and SHARED or ** between unlocked and EXCLUSIVE. It cannot transition between SHARED ** and EXCLUSIVE. */ #define SQLITE_SHM_UNLOCK 1 #define SQLITE_SHM_LOCK 2 #define SQLITE_SHM_SHARED 4 #define SQLITE_SHM_EXCLUSIVE 8 /* ** CAPI3REF: Maximum xShmLock index ** ** The xShmLock method on [sqlite3_io_methods] may use values ** between 0 and this upper bound as its "offset" argument. ** The SQLite core will never attempt to acquire or release a ** lock outside of this range */ #define SQLITE_SHM_NLOCK 8 /* ** CAPI3REF: Initialize The SQLite Library ** ** ^The sqlite3_initialize() routine initializes the ** SQLite library. ^The sqlite3_shutdown() routine ** deallocates any resources that were allocated by sqlite3_initialize(). ** These routines are designed to aid in process initialization and ** shutdown on embedded systems. Workstation applications using ** SQLite normally do not need to invoke either of these routines. ** ** A call to sqlite3_initialize() is an "effective" call if it is ** the first time sqlite3_initialize() is invoked during the lifetime of ** the process, or if it is the first time sqlite3_initialize() is invoked ** following a call to sqlite3_shutdown(). ^(Only an effective call ** of sqlite3_initialize() does any initialization. All other calls ** are harmless no-ops.)^ ** ** A call to sqlite3_shutdown() is an "effective" call if it is the first ** call to sqlite3_shutdown() since the last sqlite3_initialize(). ^(Only ** an effective call to sqlite3_shutdown() does any deinitialization. ** All other valid calls to sqlite3_shutdown() are harmless no-ops.)^ ** ** The sqlite3_initialize() interface is threadsafe, but sqlite3_shutdown() ** is not. The sqlite3_shutdown() interface must only be called from a ** single thread. All open [database connections] must be closed and all ** other SQLite resources must be deallocated prior to invoking ** sqlite3_shutdown(). ** ** Among other things, ^sqlite3_initialize() will invoke ** sqlite3_os_init(). Similarly, ^sqlite3_shutdown() ** will invoke sqlite3_os_end(). ** ** ^The sqlite3_initialize() routine returns [SQLITE_OK] on success. ** ^If for some reason, sqlite3_initialize() is unable to initialize ** the library (perhaps it is unable to allocate a needed resource such ** as a mutex) it returns an [error code] other than [SQLITE_OK]. ** ** ^The sqlite3_initialize() routine is called internally by many other ** SQLite interfaces so that an application usually does not need to ** invoke sqlite3_initialize() directly. For example, [sqlite3_open()] ** calls sqlite3_initialize() so the SQLite library will be automatically ** initialized when [sqlite3_open()] is called if it has not be initialized ** already. ^However, if SQLite is compiled with the [SQLITE_OMIT_AUTOINIT] ** compile-time option, then the automatic calls to sqlite3_initialize() ** are omitted and the application must call sqlite3_initialize() directly ** prior to using any other SQLite interface. For maximum portability, ** it is recommended that applications always invoke sqlite3_initialize() ** directly prior to using any other SQLite interface. Future releases ** of SQLite may require this. In other words, the behavior exhibited ** when SQLite is compiled with [SQLITE_OMIT_AUTOINIT] might become the ** default behavior in some future release of SQLite. ** ** The sqlite3_os_init() routine does operating-system specific ** initialization of the SQLite library. The sqlite3_os_end() ** routine undoes the effect of sqlite3_os_init(). Typical tasks ** performed by these routines include allocation or deallocation ** of static resources, initialization of global variables, ** setting up a default [sqlite3_vfs] module, or setting up ** a default configuration using [sqlite3_config()]. ** ** The application should never invoke either sqlite3_os_init() ** or sqlite3_os_end() directly. The application should only invoke ** sqlite3_initialize() and sqlite3_shutdown(). The sqlite3_os_init() ** interface is called automatically by sqlite3_initialize() and ** sqlite3_os_end() is called by sqlite3_shutdown(). Appropriate ** implementations for sqlite3_os_init() and sqlite3_os_end() ** are built into SQLite when it is compiled for Unix, Windows, or OS/2. ** When [custom builds | built for other platforms] ** (using the [SQLITE_OS_OTHER=1] compile-time ** option) the application must supply a suitable implementation for ** sqlite3_os_init() and sqlite3_os_end(). An application-supplied ** implementation of sqlite3_os_init() or sqlite3_os_end() ** must return [SQLITE_OK] on success and some other [error code] upon ** failure. */ SQLITE_API int sqlite3_initialize(void); SQLITE_API int sqlite3_shutdown(void); SQLITE_API int sqlite3_os_init(void); SQLITE_API int sqlite3_os_end(void); /* ** CAPI3REF: Configuring The SQLite Library ** ** The sqlite3_config() interface is used to make global configuration ** changes to SQLite in order to tune SQLite to the specific needs of ** the application. The default configuration is recommended for most ** applications and so this routine is usually not necessary. It is ** provided to support rare applications with unusual needs. ** ** The sqlite3_config() interface is not threadsafe. The application ** must ensure that no other SQLite interfaces are invoked by other ** threads while sqlite3_config() is running. ** ** The sqlite3_config() interface ** may only be invoked prior to library initialization using ** [sqlite3_initialize()] or after shutdown by [sqlite3_shutdown()]. ** ^If sqlite3_config() is called after [sqlite3_initialize()] and before ** [sqlite3_shutdown()] then it will return SQLITE_MISUSE. ** Note, however, that ^sqlite3_config() can be called as part of the ** implementation of an application-defined [sqlite3_os_init()]. ** ** The first argument to sqlite3_config() is an integer ** [configuration option] that determines ** what property of SQLite is to be configured. Subsequent arguments ** vary depending on the [configuration option] ** in the first argument. ** ** ^When a configuration option is set, sqlite3_config() returns [SQLITE_OK]. ** ^If the option is unknown or SQLite is unable to set the option ** then this routine returns a non-zero [error code]. */ SQLITE_API int sqlite3_config(int, ...); /* ** CAPI3REF: Configure database connections ** METHOD: sqlite3 ** ** The sqlite3_db_config() interface is used to make configuration ** changes to a [database connection]. The interface is similar to ** [sqlite3_config()] except that the changes apply to a single ** [database connection] (specified in the first argument). ** ** The second argument to sqlite3_db_config(D,V,...) is the ** [SQLITE_DBCONFIG_LOOKASIDE | configuration verb] - an integer code ** that indicates what aspect of the [database connection] is being configured. ** Subsequent arguments vary depending on the configuration verb. ** ** ^Calls to sqlite3_db_config() return SQLITE_OK if and only if ** the call is considered successful. */ SQLITE_API int sqlite3_db_config(sqlite3*, int op, ...); /* ** CAPI3REF: Memory Allocation Routines ** ** An instance of this object defines the interface between SQLite ** and low-level memory allocation routines. ** ** This object is used in only one place in the SQLite interface. ** A pointer to an instance of this object is the argument to ** [sqlite3_config()] when the configuration option is ** [SQLITE_CONFIG_MALLOC] or [SQLITE_CONFIG_GETMALLOC]. ** By creating an instance of this object ** and passing it to [sqlite3_config]([SQLITE_CONFIG_MALLOC]) ** during configuration, an application can specify an alternative ** memory allocation subsystem for SQLite to use for all of its ** dynamic memory needs. ** ** Note that SQLite comes with several [built-in memory allocators] ** that are perfectly adequate for the overwhelming majority of applications ** and that this object is only useful to a tiny minority of applications ** with specialized memory allocation requirements. This object is ** also used during testing of SQLite in order to specify an alternative ** memory allocator that simulates memory out-of-memory conditions in ** order to verify that SQLite recovers gracefully from such ** conditions. ** ** The xMalloc, xRealloc, and xFree methods must work like the ** malloc(), realloc() and free() functions from the standard C library. ** ^SQLite guarantees that the second argument to ** xRealloc is always a value returned by a prior call to xRoundup. ** ** xSize should return the allocated size of a memory allocation ** previously obtained from xMalloc or xRealloc. The allocated size ** is always at least as big as the requested size but may be larger. ** ** The xRoundup method returns what would be the allocated size of ** a memory allocation given a particular requested size. Most memory ** allocators round up memory allocations at least to the next multiple ** of 8. Some allocators round up to a larger multiple or to a power of 2. ** Every memory allocation request coming in through [sqlite3_malloc()] ** or [sqlite3_realloc()] first calls xRoundup. If xRoundup returns 0, ** that causes the corresponding memory allocation to fail. ** ** The xInit method initializes the memory allocator. For example, ** it might allocate any require mutexes or initialize internal data ** structures. The xShutdown method is invoked (indirectly) by ** [sqlite3_shutdown()] and should deallocate any resources acquired ** by xInit. The pAppData pointer is used as the only parameter to ** xInit and xShutdown. ** ** SQLite holds the [SQLITE_MUTEX_STATIC_MASTER] mutex when it invokes ** the xInit method, so the xInit method need not be threadsafe. The ** xShutdown method is only called from [sqlite3_shutdown()] so it does ** not need to be threadsafe either. For all other methods, SQLite ** holds the [SQLITE_MUTEX_STATIC_MEM] mutex as long as the ** [SQLITE_CONFIG_MEMSTATUS] configuration option is turned on (which ** it is by default) and so the methods are automatically serialized. ** However, if [SQLITE_CONFIG_MEMSTATUS] is disabled, then the other ** methods must be threadsafe or else make their own arrangements for ** serialization. ** ** SQLite will never invoke xInit() more than once without an intervening ** call to xShutdown(). */ typedef struct sqlite3_mem_methods sqlite3_mem_methods; struct sqlite3_mem_methods { void *(*xMalloc)(int); /* Memory allocation function */ void (*xFree)(void*); /* Free a prior allocation */ void *(*xRealloc)(void*,int); /* Resize an allocation */ int (*xSize)(void*); /* Return the size of an allocation */ int (*xRoundup)(int); /* Round up request size to allocation size */ int (*xInit)(void*); /* Initialize the memory allocator */ void (*xShutdown)(void*); /* Deinitialize the memory allocator */ void *pAppData; /* Argument to xInit() and xShutdown() */ }; /* ** CAPI3REF: Configuration Options ** KEYWORDS: {configuration option} ** ** These constants are the available integer configuration options that ** can be passed as the first argument to the [sqlite3_config()] interface. ** ** New configuration options may be added in future releases of SQLite. ** Existing configuration options might be discontinued. Applications ** should check the return code from [sqlite3_config()] to make sure that ** the call worked. The [sqlite3_config()] interface will return a ** non-zero [error code] if a discontinued or unsupported configuration option ** is invoked. ** **
** [[SQLITE_CONFIG_SINGLETHREAD]]
SQLITE_CONFIG_SINGLETHREAD
**
There are no arguments to this option. ^This option sets the ** [threading mode] to Single-thread. In other words, it disables ** all mutexing and puts SQLite into a mode where it can only be used ** by a single thread. ^If SQLite is compiled with ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then ** it is not possible to change the [threading mode] from its default ** value of Single-thread and so [sqlite3_config()] will return ** [SQLITE_ERROR] if called with the SQLITE_CONFIG_SINGLETHREAD ** configuration option.
** ** [[SQLITE_CONFIG_MULTITHREAD]]
SQLITE_CONFIG_MULTITHREAD
**
There are no arguments to this option. ^This option sets the ** [threading mode] to Multi-thread. In other words, it disables ** mutexing on [database connection] and [prepared statement] objects. ** The application is responsible for serializing access to ** [database connections] and [prepared statements]. But other mutexes ** are enabled so that SQLite will be safe to use in a multi-threaded ** environment as long as no two threads attempt to use the same ** [database connection] at the same time. ^If SQLite is compiled with ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then ** it is not possible to set the Multi-thread [threading mode] and ** [sqlite3_config()] will return [SQLITE_ERROR] if called with the ** SQLITE_CONFIG_MULTITHREAD configuration option.
** ** [[SQLITE_CONFIG_SERIALIZED]]
SQLITE_CONFIG_SERIALIZED
**
There are no arguments to this option. ^This option sets the ** [threading mode] to Serialized. In other words, this option enables ** all mutexes including the recursive ** mutexes on [database connection] and [prepared statement] objects. ** In this mode (which is the default when SQLite is compiled with ** [SQLITE_THREADSAFE=1]) the SQLite library will itself serialize access ** to [database connections] and [prepared statements] so that the ** application is free to use the same [database connection] or the ** same [prepared statement] in different threads at the same time. ** ^If SQLite is compiled with ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then ** it is not possible to set the Serialized [threading mode] and ** [sqlite3_config()] will return [SQLITE_ERROR] if called with the ** SQLITE_CONFIG_SERIALIZED configuration option.
** ** [[SQLITE_CONFIG_MALLOC]]
SQLITE_CONFIG_MALLOC
**
^(The SQLITE_CONFIG_MALLOC option takes a single argument which is ** a pointer to an instance of the [sqlite3_mem_methods] structure. ** The argument specifies ** alternative low-level memory allocation routines to be used in place of ** the memory allocation routines built into SQLite.)^ ^SQLite makes ** its own private copy of the content of the [sqlite3_mem_methods] structure ** before the [sqlite3_config()] call returns.
** ** [[SQLITE_CONFIG_GETMALLOC]]
SQLITE_CONFIG_GETMALLOC
**
^(The SQLITE_CONFIG_GETMALLOC option takes a single argument which ** is a pointer to an instance of the [sqlite3_mem_methods] structure. ** The [sqlite3_mem_methods] ** structure is filled with the currently defined memory allocation routines.)^ ** This option can be used to overload the default memory allocation ** routines with a wrapper that simulations memory allocation failure or ** tracks memory usage, for example.
** ** [[SQLITE_CONFIG_MEMSTATUS]]
SQLITE_CONFIG_MEMSTATUS
**
^The SQLITE_CONFIG_MEMSTATUS option takes single argument of type int, ** interpreted as a boolean, which enables or disables the collection of ** memory allocation statistics. ^(When memory allocation statistics are ** disabled, the following SQLite interfaces become non-operational: **
    **
  • [sqlite3_memory_used()] **
  • [sqlite3_memory_highwater()] **
  • [sqlite3_soft_heap_limit64()] **
  • [sqlite3_status64()] **
)^ ** ^Memory allocation statistics are enabled by default unless SQLite is ** compiled with [SQLITE_DEFAULT_MEMSTATUS]=0 in which case memory ** allocation statistics are disabled by default. **
** ** [[SQLITE_CONFIG_SCRATCH]]
SQLITE_CONFIG_SCRATCH
**
^The SQLITE_CONFIG_SCRATCH option specifies a static memory buffer ** that SQLite can use for scratch memory. ^(There are three arguments ** to SQLITE_CONFIG_SCRATCH: A pointer an 8-byte ** aligned memory buffer from which the scratch allocations will be ** drawn, the size of each scratch allocation (sz), ** and the maximum number of scratch allocations (N).)^ ** The first argument must be a pointer to an 8-byte aligned buffer ** of at least sz*N bytes of memory. ** ^SQLite will not use more than one scratch buffers per thread. ** ^SQLite will never request a scratch buffer that is more than 6 ** times the database page size. ** ^If SQLite needs needs additional ** scratch memory beyond what is provided by this configuration option, then ** [sqlite3_malloc()] will be used to obtain the memory needed.

** ^When the application provides any amount of scratch memory using ** SQLITE_CONFIG_SCRATCH, SQLite avoids unnecessary large ** [sqlite3_malloc|heap allocations]. ** This can help [Robson proof|prevent memory allocation failures] due to heap ** fragmentation in low-memory embedded systems. **

** ** [[SQLITE_CONFIG_PAGECACHE]]
SQLITE_CONFIG_PAGECACHE
**
^The SQLITE_CONFIG_PAGECACHE option specifies a memory pool ** that SQLite can use for the database page cache with the default page ** cache implementation. ** This configuration option is a no-op if an application-define page ** cache implementation is loaded using the [SQLITE_CONFIG_PCACHE2]. ** ^There are three arguments to SQLITE_CONFIG_PAGECACHE: A pointer to ** 8-byte aligned memory (pMem), the size of each page cache line (sz), ** and the number of cache lines (N). ** The sz argument should be the size of the largest database page ** (a power of two between 512 and 65536) plus some extra bytes for each ** page header. ^The number of extra bytes needed by the page header ** can be determined using [SQLITE_CONFIG_PCACHE_HDRSZ]. ** ^It is harmless, apart from the wasted memory, ** for the sz parameter to be larger than necessary. The pMem ** argument must be either a NULL pointer or a pointer to an 8-byte ** aligned block of memory of at least sz*N bytes, otherwise ** subsequent behavior is undefined. ** ^When pMem is not NULL, SQLite will strive to use the memory provided ** to satisfy page cache needs, falling back to [sqlite3_malloc()] if ** a page cache line is larger than sz bytes or if all of the pMem buffer ** is exhausted. ** ^If pMem is NULL and N is non-zero, then each database connection ** does an initial bulk allocation for page cache memory ** from [sqlite3_malloc()] sufficient for N cache lines if N is positive or ** of -1024*N bytes if N is negative, . ^If additional ** page cache memory is needed beyond what is provided by the initial ** allocation, then SQLite goes to [sqlite3_malloc()] separately for each ** additional cache line.
** ** [[SQLITE_CONFIG_HEAP]]
SQLITE_CONFIG_HEAP
**
^The SQLITE_CONFIG_HEAP option specifies a static memory buffer ** that SQLite will use for all of its dynamic memory allocation needs ** beyond those provided for by [SQLITE_CONFIG_SCRATCH] and ** [SQLITE_CONFIG_PAGECACHE]. ** ^The SQLITE_CONFIG_HEAP option is only available if SQLite is compiled ** with either [SQLITE_ENABLE_MEMSYS3] or [SQLITE_ENABLE_MEMSYS5] and returns ** [SQLITE_ERROR] if invoked otherwise. ** ^There are three arguments to SQLITE_CONFIG_HEAP: ** An 8-byte aligned pointer to the memory, ** the number of bytes in the memory buffer, and the minimum allocation size. ** ^If the first pointer (the memory pointer) is NULL, then SQLite reverts ** to using its default memory allocator (the system malloc() implementation), ** undoing any prior invocation of [SQLITE_CONFIG_MALLOC]. ^If the ** memory pointer is not NULL then the alternative memory ** allocator is engaged to handle all of SQLites memory allocation needs. ** The first pointer (the memory pointer) must be aligned to an 8-byte ** boundary or subsequent behavior of SQLite will be undefined. ** The minimum allocation size is capped at 2**12. Reasonable values ** for the minimum allocation size are 2**5 through 2**8.
** ** [[SQLITE_CONFIG_MUTEX]]
SQLITE_CONFIG_MUTEX
**
^(The SQLITE_CONFIG_MUTEX option takes a single argument which is a ** pointer to an instance of the [sqlite3_mutex_methods] structure. ** The argument specifies alternative low-level mutex routines to be used ** in place the mutex routines built into SQLite.)^ ^SQLite makes a copy of ** the content of the [sqlite3_mutex_methods] structure before the call to ** [sqlite3_config()] returns. ^If SQLite is compiled with ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then ** the entire mutexing subsystem is omitted from the build and hence calls to ** [sqlite3_config()] with the SQLITE_CONFIG_MUTEX configuration option will ** return [SQLITE_ERROR].
** ** [[SQLITE_CONFIG_GETMUTEX]]
SQLITE_CONFIG_GETMUTEX
**
^(The SQLITE_CONFIG_GETMUTEX option takes a single argument which ** is a pointer to an instance of the [sqlite3_mutex_methods] structure. The ** [sqlite3_mutex_methods] ** structure is filled with the currently defined mutex routines.)^ ** This option can be used to overload the default mutex allocation ** routines with a wrapper used to track mutex usage for performance ** profiling or testing, for example. ^If SQLite is compiled with ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then ** the entire mutexing subsystem is omitted from the build and hence calls to ** [sqlite3_config()] with the SQLITE_CONFIG_GETMUTEX configuration option will ** return [SQLITE_ERROR].
** ** [[SQLITE_CONFIG_LOOKASIDE]]
SQLITE_CONFIG_LOOKASIDE
**
^(The SQLITE_CONFIG_LOOKASIDE option takes two arguments that determine ** the default size of lookaside memory on each [database connection]. ** The first argument is the ** size of each lookaside buffer slot and the second is the number of ** slots allocated to each database connection.)^ ^(SQLITE_CONFIG_LOOKASIDE ** sets the default lookaside size. The [SQLITE_DBCONFIG_LOOKASIDE] ** option to [sqlite3_db_config()] can be used to change the lookaside ** configuration on individual connections.)^
** ** [[SQLITE_CONFIG_PCACHE2]]
SQLITE_CONFIG_PCACHE2
**
^(The SQLITE_CONFIG_PCACHE2 option takes a single argument which is ** a pointer to an [sqlite3_pcache_methods2] object. This object specifies ** the interface to a custom page cache implementation.)^ ** ^SQLite makes a copy of the [sqlite3_pcache_methods2] object.
** ** [[SQLITE_CONFIG_GETPCACHE2]]
SQLITE_CONFIG_GETPCACHE2
**
^(The SQLITE_CONFIG_GETPCACHE2 option takes a single argument which ** is a pointer to an [sqlite3_pcache_methods2] object. SQLite copies of ** the current page cache implementation into that object.)^
** ** [[SQLITE_CONFIG_LOG]]
SQLITE_CONFIG_LOG
**
The SQLITE_CONFIG_LOG option is used to configure the SQLite ** global [error log]. ** (^The SQLITE_CONFIG_LOG option takes two arguments: a pointer to a ** function with a call signature of void(*)(void*,int,const char*), ** and a pointer to void. ^If the function pointer is not NULL, it is ** invoked by [sqlite3_log()] to process each logging event. ^If the ** function pointer is NULL, the [sqlite3_log()] interface becomes a no-op. ** ^The void pointer that is the second argument to SQLITE_CONFIG_LOG is ** passed through as the first parameter to the application-defined logger ** function whenever that function is invoked. ^The second parameter to ** the logger function is a copy of the first parameter to the corresponding ** [sqlite3_log()] call and is intended to be a [result code] or an ** [extended result code]. ^The third parameter passed to the logger is ** log message after formatting via [sqlite3_snprintf()]. ** The SQLite logging interface is not reentrant; the logger function ** supplied by the application must not invoke any SQLite interface. ** In a multi-threaded application, the application-defined logger ** function must be threadsafe.
** ** [[SQLITE_CONFIG_URI]]
SQLITE_CONFIG_URI **
^(The SQLITE_CONFIG_URI option takes a single argument of type int. ** If non-zero, then URI handling is globally enabled. If the parameter is zero, ** then URI handling is globally disabled.)^ ^If URI handling is globally ** enabled, all filenames passed to [sqlite3_open()], [sqlite3_open_v2()], ** [sqlite3_open16()] or ** specified as part of [ATTACH] commands are interpreted as URIs, regardless ** of whether or not the [SQLITE_OPEN_URI] flag is set when the database ** connection is opened. ^If it is globally disabled, filenames are ** only interpreted as URIs if the SQLITE_OPEN_URI flag is set when the ** database connection is opened. ^(By default, URI handling is globally ** disabled. The default value may be changed by compiling with the ** [SQLITE_USE_URI] symbol defined.)^ ** ** [[SQLITE_CONFIG_COVERING_INDEX_SCAN]]
SQLITE_CONFIG_COVERING_INDEX_SCAN **
^The SQLITE_CONFIG_COVERING_INDEX_SCAN option takes a single integer ** argument which is interpreted as a boolean in order to enable or disable ** the use of covering indices for full table scans in the query optimizer. ** ^The default setting is determined ** by the [SQLITE_ALLOW_COVERING_INDEX_SCAN] compile-time option, or is "on" ** if that compile-time option is omitted. ** The ability to disable the use of covering indices for full table scans ** is because some incorrectly coded legacy applications might malfunction ** when the optimization is enabled. Providing the ability to ** disable the optimization allows the older, buggy application code to work ** without change even with newer versions of SQLite. ** ** [[SQLITE_CONFIG_PCACHE]] [[SQLITE_CONFIG_GETPCACHE]] **
SQLITE_CONFIG_PCACHE and SQLITE_CONFIG_GETPCACHE **
These options are obsolete and should not be used by new code. ** They are retained for backwards compatibility but are now no-ops. **
** ** [[SQLITE_CONFIG_SQLLOG]] **
SQLITE_CONFIG_SQLLOG **
This option is only available if sqlite is compiled with the ** [SQLITE_ENABLE_SQLLOG] pre-processor macro defined. The first argument should ** be a pointer to a function of type void(*)(void*,sqlite3*,const char*, int). ** The second should be of type (void*). The callback is invoked by the library ** in three separate circumstances, identified by the value passed as the ** fourth parameter. If the fourth parameter is 0, then the database connection ** passed as the second argument has just been opened. The third argument ** points to a buffer containing the name of the main database file. If the ** fourth parameter is 1, then the SQL statement that the third parameter ** points to has just been executed. Or, if the fourth parameter is 2, then ** the connection being passed as the second parameter is being closed. The ** third parameter is passed NULL In this case. An example of using this ** configuration option can be seen in the "test_sqllog.c" source file in ** the canonical SQLite source tree.
** ** [[SQLITE_CONFIG_MMAP_SIZE]] **
SQLITE_CONFIG_MMAP_SIZE **
^SQLITE_CONFIG_MMAP_SIZE takes two 64-bit integer (sqlite3_int64) values ** that are the default mmap size limit (the default setting for ** [PRAGMA mmap_size]) and the maximum allowed mmap size limit. ** ^The default setting can be overridden by each database connection using ** either the [PRAGMA mmap_size] command, or by using the ** [SQLITE_FCNTL_MMAP_SIZE] file control. ^(The maximum allowed mmap size ** will be silently truncated if necessary so that it does not exceed the ** compile-time maximum mmap size set by the ** [SQLITE_MAX_MMAP_SIZE] compile-time option.)^ ** ^If either argument to this option is negative, then that argument is ** changed to its compile-time default. ** ** [[SQLITE_CONFIG_WIN32_HEAPSIZE]] **
SQLITE_CONFIG_WIN32_HEAPSIZE **
^The SQLITE_CONFIG_WIN32_HEAPSIZE option is only available if SQLite is ** compiled for Windows with the [SQLITE_WIN32_MALLOC] pre-processor macro ** defined. ^SQLITE_CONFIG_WIN32_HEAPSIZE takes a 32-bit unsigned integer value ** that specifies the maximum size of the created heap. ** ** [[SQLITE_CONFIG_PCACHE_HDRSZ]] **
SQLITE_CONFIG_PCACHE_HDRSZ **
^The SQLITE_CONFIG_PCACHE_HDRSZ option takes a single parameter which ** is a pointer to an integer and writes into that integer the number of extra ** bytes per page required for each page in [SQLITE_CONFIG_PAGECACHE]. ** The amount of extra space required can change depending on the compiler, ** target platform, and SQLite version. ** ** [[SQLITE_CONFIG_PMASZ]] **
SQLITE_CONFIG_PMASZ **
^The SQLITE_CONFIG_PMASZ option takes a single parameter which ** is an unsigned integer and sets the "Minimum PMA Size" for the multithreaded ** sorter to that integer. The default minimum PMA Size is set by the ** [SQLITE_SORTER_PMASZ] compile-time option. New threads are launched ** to help with sort operations when multithreaded sorting ** is enabled (using the [PRAGMA threads] command) and the amount of content ** to be sorted exceeds the page size times the minimum of the ** [PRAGMA cache_size] setting and this value. ** ** [[SQLITE_CONFIG_STMTJRNL_SPILL]] **
SQLITE_CONFIG_STMTJRNL_SPILL **
^The SQLITE_CONFIG_STMTJRNL_SPILL option takes a single parameter which ** becomes the [statement journal] spill-to-disk threshold. ** [Statement journals] are held in memory until their size (in bytes) ** exceeds this threshold, at which point they are written to disk. ** Or if the threshold is -1, statement journals are always held ** exclusively in memory. ** Since many statement journals never become large, setting the spill ** threshold to a value such as 64KiB can greatly reduce the amount of ** I/O required to support statement rollback. ** The default value for this setting is controlled by the ** [SQLITE_STMTJRNL_SPILL] compile-time option. **
*/ #define SQLITE_CONFIG_SINGLETHREAD 1 /* nil */ #define SQLITE_CONFIG_MULTITHREAD 2 /* nil */ #define SQLITE_CONFIG_SERIALIZED 3 /* nil */ #define SQLITE_CONFIG_MALLOC 4 /* sqlite3_mem_methods* */ #define SQLITE_CONFIG_GETMALLOC 5 /* sqlite3_mem_methods* */ #define SQLITE_CONFIG_SCRATCH 6 /* void*, int sz, int N */ #define SQLITE_CONFIG_PAGECACHE 7 /* void*, int sz, int N */ #define SQLITE_CONFIG_HEAP 8 /* void*, int nByte, int min */ #define SQLITE_CONFIG_MEMSTATUS 9 /* boolean */ #define SQLITE_CONFIG_MUTEX 10 /* sqlite3_mutex_methods* */ #define SQLITE_CONFIG_GETMUTEX 11 /* sqlite3_mutex_methods* */ /* previously SQLITE_CONFIG_CHUNKALLOC 12 which is now unused. */ #define SQLITE_CONFIG_LOOKASIDE 13 /* int int */ #define SQLITE_CONFIG_PCACHE 14 /* no-op */ #define SQLITE_CONFIG_GETPCACHE 15 /* no-op */ #define SQLITE_CONFIG_LOG 16 /* xFunc, void* */ #define SQLITE_CONFIG_URI 17 /* int */ #define SQLITE_CONFIG_PCACHE2 18 /* sqlite3_pcache_methods2* */ #define SQLITE_CONFIG_GETPCACHE2 19 /* sqlite3_pcache_methods2* */ #define SQLITE_CONFIG_COVERING_INDEX_SCAN 20 /* int */ #define SQLITE_CONFIG_SQLLOG 21 /* xSqllog, void* */ #define SQLITE_CONFIG_MMAP_SIZE 22 /* sqlite3_int64, sqlite3_int64 */ #define SQLITE_CONFIG_WIN32_HEAPSIZE 23 /* int nByte */ #define SQLITE_CONFIG_PCACHE_HDRSZ 24 /* int *psz */ #define SQLITE_CONFIG_PMASZ 25 /* unsigned int szPma */ #define SQLITE_CONFIG_STMTJRNL_SPILL 26 /* int nByte */ /* ** CAPI3REF: Database Connection Configuration Options ** ** These constants are the available integer configuration options that ** can be passed as the second argument to the [sqlite3_db_config()] interface. ** ** New configuration options may be added in future releases of SQLite. ** Existing configuration options might be discontinued. Applications ** should check the return code from [sqlite3_db_config()] to make sure that ** the call worked. ^The [sqlite3_db_config()] interface will return a ** non-zero [error code] if a discontinued or unsupported configuration option ** is invoked. ** **
**
SQLITE_DBCONFIG_LOOKASIDE
**
^This option takes three additional arguments that determine the ** [lookaside memory allocator] configuration for the [database connection]. ** ^The first argument (the third parameter to [sqlite3_db_config()] is a ** pointer to a memory buffer to use for lookaside memory. ** ^The first argument after the SQLITE_DBCONFIG_LOOKASIDE verb ** may be NULL in which case SQLite will allocate the ** lookaside buffer itself using [sqlite3_malloc()]. ^The second argument is the ** size of each lookaside buffer slot. ^The third argument is the number of ** slots. The size of the buffer in the first argument must be greater than ** or equal to the product of the second and third arguments. The buffer ** must be aligned to an 8-byte boundary. ^If the second argument to ** SQLITE_DBCONFIG_LOOKASIDE is not a multiple of 8, it is internally ** rounded down to the next smaller multiple of 8. ^(The lookaside memory ** configuration for a database connection can only be changed when that ** connection is not currently using lookaside memory, or in other words ** when the "current value" returned by ** [sqlite3_db_status](D,[SQLITE_CONFIG_LOOKASIDE],...) is zero. ** Any attempt to change the lookaside memory configuration when lookaside ** memory is in use leaves the configuration unchanged and returns ** [SQLITE_BUSY].)^
** **
SQLITE_DBCONFIG_ENABLE_FKEY
**
^This option is used to enable or disable the enforcement of ** [foreign key constraints]. There should be two additional arguments. ** The first argument is an integer which is 0 to disable FK enforcement, ** positive to enable FK enforcement or negative to leave FK enforcement ** unchanged. The second parameter is a pointer to an integer into which ** is written 0 or 1 to indicate whether FK enforcement is off or on ** following this call. The second parameter may be a NULL pointer, in ** which case the FK enforcement setting is not reported back.
** **
SQLITE_DBCONFIG_ENABLE_TRIGGER
**
^This option is used to enable or disable [CREATE TRIGGER | triggers]. ** There should be two additional arguments. ** The first argument is an integer which is 0 to disable triggers, ** positive to enable triggers or negative to leave the setting unchanged. ** The second parameter is a pointer to an integer into which ** is written 0 or 1 to indicate whether triggers are disabled or enabled ** following this call. The second parameter may be a NULL pointer, in ** which case the trigger setting is not reported back.
** **
SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER
**
^This option is used to enable or disable the two-argument ** version of the [fts3_tokenizer()] function which is part of the ** [FTS3] full-text search engine extension. ** There should be two additional arguments. ** The first argument is an integer which is 0 to disable fts3_tokenizer() or ** positive to enable fts3_tokenizer() or negative to leave the setting ** unchanged. ** The second parameter is a pointer to an integer into which ** is written 0 or 1 to indicate whether fts3_tokenizer is disabled or enabled ** following this call. The second parameter may be a NULL pointer, in ** which case the new setting is not reported back.
** **
SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION
**
^This option is used to enable or disable the [sqlite3_load_extension()] ** interface independently of the [load_extension()] SQL function. ** The [sqlite3_enable_load_extension()] API enables or disables both the ** C-API [sqlite3_load_extension()] and the SQL function [load_extension()]. ** There should be two additional arguments. ** When the first argument to this interface is 1, then only the C-API is ** enabled and the SQL function remains disabled. If the first argument to ** this interface is 0, then both the C-API and the SQL function are disabled. ** If the first argument is -1, then no changes are made to state of either the ** C-API or the SQL function. ** The second parameter is a pointer to an integer into which ** is written 0 or 1 to indicate whether [sqlite3_load_extension()] interface ** is disabled or enabled following this call. The second parameter may ** be a NULL pointer, in which case the new setting is not reported back. **
** **
SQLITE_DBCONFIG_MAINDBNAME
**
^This option is used to change the name of the "main" database ** schema. ^The sole argument is a pointer to a constant UTF8 string ** which will become the new schema name in place of "main". ^SQLite ** does not make a copy of the new main schema name string, so the application ** must ensure that the argument passed into this DBCONFIG option is unchanged ** until after the database connection closes. **
** **
*/ #define SQLITE_DBCONFIG_MAINDBNAME 1000 /* const char* */ #define SQLITE_DBCONFIG_LOOKASIDE 1001 /* void* int int */ #define SQLITE_DBCONFIG_ENABLE_FKEY 1002 /* int int* */ #define SQLITE_DBCONFIG_ENABLE_TRIGGER 1003 /* int int* */ #define SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER 1004 /* int int* */ #define SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION 1005 /* int int* */ /* ** CAPI3REF: Enable Or Disable Extended Result Codes ** METHOD: sqlite3 ** ** ^The sqlite3_extended_result_codes() routine enables or disables the ** [extended result codes] feature of SQLite. ^The extended result ** codes are disabled by default for historical compatibility. */ SQLITE_API int sqlite3_extended_result_codes(sqlite3*, int onoff); /* ** CAPI3REF: Last Insert Rowid ** METHOD: sqlite3 ** ** ^Each entry in most SQLite tables (except for [WITHOUT ROWID] tables) ** has a unique 64-bit signed ** integer key called the [ROWID | "rowid"]. ^The rowid is always available ** as an undeclared column named ROWID, OID, or _ROWID_ as long as those ** names are not also used by explicitly declared columns. ^If ** the table has a column of type [INTEGER PRIMARY KEY] then that column ** is another alias for the rowid. ** ** ^The sqlite3_last_insert_rowid(D) interface returns the [rowid] of the ** most recent successful [INSERT] into a rowid table or [virtual table] ** on database connection D. ** ^Inserts into [WITHOUT ROWID] tables are not recorded. ** ^If no successful [INSERT]s into rowid tables ** have ever occurred on the database connection D, ** then sqlite3_last_insert_rowid(D) returns zero. ** ** ^(If an [INSERT] occurs within a trigger or within a [virtual table] ** method, then this routine will return the [rowid] of the inserted ** row as long as the trigger or virtual table method is running. ** But once the trigger or virtual table method ends, the value returned ** by this routine reverts to what it was before the trigger or virtual ** table method began.)^ ** ** ^An [INSERT] that fails due to a constraint violation is not a ** successful [INSERT] and does not change the value returned by this ** routine. ^Thus INSERT OR FAIL, INSERT OR IGNORE, INSERT OR ROLLBACK, ** and INSERT OR ABORT make no changes to the return value of this ** routine when their insertion fails. ^(When INSERT OR REPLACE ** encounters a constraint violation, it does not fail. The ** INSERT continues to completion after deleting rows that caused ** the constraint problem so INSERT OR REPLACE will always change ** the return value of this interface.)^ ** ** ^For the purposes of this routine, an [INSERT] is considered to ** be successful even if it is subsequently rolled back. ** ** This function is accessible to SQL statements via the ** [last_insert_rowid() SQL function]. ** ** If a separate thread performs a new [INSERT] on the same ** database connection while the [sqlite3_last_insert_rowid()] ** function is running and thus changes the last insert [rowid], ** then the value returned by [sqlite3_last_insert_rowid()] is ** unpredictable and might not equal either the old or the new ** last insert [rowid]. */ SQLITE_API sqlite3_int64 sqlite3_last_insert_rowid(sqlite3*); /* ** CAPI3REF: Count The Number Of Rows Modified ** METHOD: sqlite3 ** ** ^This function returns the number of rows modified, inserted or ** deleted by the most recently completed INSERT, UPDATE or DELETE ** statement on the database connection specified by the only parameter. ** ^Executing any other type of SQL statement does not modify the value ** returned by this function. ** ** ^Only changes made directly by the INSERT, UPDATE or DELETE statement are ** considered - auxiliary changes caused by [CREATE TRIGGER | triggers], ** [foreign key actions] or [REPLACE] constraint resolution are not counted. ** ** Changes to a view that are intercepted by ** [INSTEAD OF trigger | INSTEAD OF triggers] are not counted. ^The value ** returned by sqlite3_changes() immediately after an INSERT, UPDATE or ** DELETE statement run on a view is always zero. Only changes made to real ** tables are counted. ** ** Things are more complicated if the sqlite3_changes() function is ** executed while a trigger program is running. This may happen if the ** program uses the [changes() SQL function], or if some other callback ** function invokes sqlite3_changes() directly. Essentially: ** **
    **
  • ^(Before entering a trigger program the value returned by ** sqlite3_changes() function is saved. After the trigger program ** has finished, the original value is restored.)^ ** **
  • ^(Within a trigger program each INSERT, UPDATE and DELETE ** statement sets the value returned by sqlite3_changes() ** upon completion as normal. Of course, this value will not include ** any changes performed by sub-triggers, as the sqlite3_changes() ** value will be saved and restored after each sub-trigger has run.)^ **
** ** ^This means that if the changes() SQL function (or similar) is used ** by the first INSERT, UPDATE or DELETE statement within a trigger, it ** returns the value as set when the calling statement began executing. ** ^If it is used by the second or subsequent such statement within a trigger ** program, the value returned reflects the number of rows modified by the ** previous INSERT, UPDATE or DELETE statement within the same trigger. ** ** See also the [sqlite3_total_changes()] interface, the ** [count_changes pragma], and the [changes() SQL function]. ** ** If a separate thread makes changes on the same database connection ** while [sqlite3_changes()] is running then the value returned ** is unpredictable and not meaningful. */ SQLITE_API int sqlite3_changes(sqlite3*); /* ** CAPI3REF: Total Number Of Rows Modified ** METHOD: sqlite3 ** ** ^This function returns the total number of rows inserted, modified or ** deleted by all [INSERT], [UPDATE] or [DELETE] statements completed ** since the database connection was opened, including those executed as ** part of trigger programs. ^Executing any other type of SQL statement ** does not affect the value returned by sqlite3_total_changes(). ** ** ^Changes made as part of [foreign key actions] are included in the ** count, but those made as part of REPLACE constraint resolution are ** not. ^Changes to a view that are intercepted by INSTEAD OF triggers ** are not counted. ** ** See also the [sqlite3_changes()] interface, the ** [count_changes pragma], and the [total_changes() SQL function]. ** ** If a separate thread makes changes on the same database connection ** while [sqlite3_total_changes()] is running then the value ** returned is unpredictable and not meaningful. */ SQLITE_API int sqlite3_total_changes(sqlite3*); /* ** CAPI3REF: Interrupt A Long-Running Query ** METHOD: sqlite3 ** ** ^This function causes any pending database operation to abort and ** return at its earliest opportunity. This routine is typically ** called in response to a user action such as pressing "Cancel" ** or Ctrl-C where the user wants a long query operation to halt ** immediately. ** ** ^It is safe to call this routine from a thread different from the ** thread that is currently running the database operation. But it ** is not safe to call this routine with a [database connection] that ** is closed or might close before sqlite3_interrupt() returns. ** ** ^If an SQL operation is very nearly finished at the time when ** sqlite3_interrupt() is called, then it might not have an opportunity ** to be interrupted and might continue to completion. ** ** ^An SQL operation that is interrupted will return [SQLITE_INTERRUPT]. ** ^If the interrupted SQL operation is an INSERT, UPDATE, or DELETE ** that is inside an explicit transaction, then the entire transaction ** will be rolled back automatically. ** ** ^The sqlite3_interrupt(D) call is in effect until all currently running ** SQL statements on [database connection] D complete. ^Any new SQL statements ** that are started after the sqlite3_interrupt() call and before the ** running statements reaches zero are interrupted as if they had been ** running prior to the sqlite3_interrupt() call. ^New SQL statements ** that are started after the running statement count reaches zero are ** not effected by the sqlite3_interrupt(). ** ^A call to sqlite3_interrupt(D) that occurs when there are no running ** SQL statements is a no-op and has no effect on SQL statements ** that are started after the sqlite3_interrupt() call returns. ** ** If the database connection closes while [sqlite3_interrupt()] ** is running then bad things will likely happen. */ SQLITE_API void sqlite3_interrupt(sqlite3*); /* ** CAPI3REF: Determine If An SQL Statement Is Complete ** ** These routines are useful during command-line input to determine if the ** currently entered text seems to form a complete SQL statement or ** if additional input is needed before sending the text into ** SQLite for parsing. ^These routines return 1 if the input string ** appears to be a complete SQL statement. ^A statement is judged to be ** complete if it ends with a semicolon token and is not a prefix of a ** well-formed CREATE TRIGGER statement. ^Semicolons that are embedded within ** string literals or quoted identifier names or comments are not ** independent tokens (they are part of the token in which they are ** embedded) and thus do not count as a statement terminator. ^Whitespace ** and comments that follow the final semicolon are ignored. ** ** ^These routines return 0 if the statement is incomplete. ^If a ** memory allocation fails, then SQLITE_NOMEM is returned. ** ** ^These routines do not parse the SQL statements thus ** will not detect syntactically incorrect SQL. ** ** ^(If SQLite has not been initialized using [sqlite3_initialize()] prior ** to invoking sqlite3_complete16() then sqlite3_initialize() is invoked ** automatically by sqlite3_complete16(). If that initialization fails, ** then the return value from sqlite3_complete16() will be non-zero ** regardless of whether or not the input SQL is complete.)^ ** ** The input to [sqlite3_complete()] must be a zero-terminated ** UTF-8 string. ** ** The input to [sqlite3_complete16()] must be a zero-terminated ** UTF-16 string in native byte order. */ SQLITE_API int sqlite3_complete(const char *sql); SQLITE_API int sqlite3_complete16(const void *sql); /* ** CAPI3REF: Register A Callback To Handle SQLITE_BUSY Errors ** KEYWORDS: {busy-handler callback} {busy handler} ** METHOD: sqlite3 ** ** ^The sqlite3_busy_handler(D,X,P) routine sets a callback function X ** that might be invoked with argument P whenever ** an attempt is made to access a database table associated with ** [database connection] D when another thread ** or process has the table locked. ** The sqlite3_busy_handler() interface is used to implement ** [sqlite3_busy_timeout()] and [PRAGMA busy_timeout]. ** ** ^If the busy callback is NULL, then [SQLITE_BUSY] ** is returned immediately upon encountering the lock. ^If the busy callback ** is not NULL, then the callback might be invoked with two arguments. ** ** ^The first argument to the busy handler is a copy of the void* pointer which ** is the third argument to sqlite3_busy_handler(). ^The second argument to ** the busy handler callback is the number of times that the busy handler has ** been invoked previously for the same locking event. ^If the ** busy callback returns 0, then no additional attempts are made to ** access the database and [SQLITE_BUSY] is returned ** to the application. ** ^If the callback returns non-zero, then another attempt ** is made to access the database and the cycle repeats. ** ** The presence of a busy handler does not guarantee that it will be invoked ** when there is lock contention. ^If SQLite determines that invoking the busy ** handler could result in a deadlock, it will go ahead and return [SQLITE_BUSY] ** to the application instead of invoking the ** busy handler. ** Consider a scenario where one process is holding a read lock that ** it is trying to promote to a reserved lock and ** a second process is holding a reserved lock that it is trying ** to promote to an exclusive lock. The first process cannot proceed ** because it is blocked by the second and the second process cannot ** proceed because it is blocked by the first. If both processes ** invoke the busy handlers, neither will make any progress. Therefore, ** SQLite returns [SQLITE_BUSY] for the first process, hoping that this ** will induce the first process to release its read lock and allow ** the second process to proceed. ** ** ^The default busy callback is NULL. ** ** ^(There can only be a single busy handler defined for each ** [database connection]. Setting a new busy handler clears any ** previously set handler.)^ ^Note that calling [sqlite3_busy_timeout()] ** or evaluating [PRAGMA busy_timeout=N] will change the ** busy handler and thus clear any previously set busy handler. ** ** The busy callback should not take any actions which modify the ** database connection that invoked the busy handler. In other words, ** the busy handler is not reentrant. Any such actions ** result in undefined behavior. ** ** A busy handler must not close the database connection ** or [prepared statement] that invoked the busy handler. */ SQLITE_API int sqlite3_busy_handler(sqlite3*,int(*)(void*,int),void*); /* ** CAPI3REF: Set A Busy Timeout ** METHOD: sqlite3 ** ** ^This routine sets a [sqlite3_busy_handler | busy handler] that sleeps ** for a specified amount of time when a table is locked. ^The handler ** will sleep multiple times until at least "ms" milliseconds of sleeping ** have accumulated. ^After at least "ms" milliseconds of sleeping, ** the handler returns 0 which causes [sqlite3_step()] to return ** [SQLITE_BUSY]. ** ** ^Calling this routine with an argument less than or equal to zero ** turns off all busy handlers. ** ** ^(There can only be a single busy handler for a particular ** [database connection] at any given moment. If another busy handler ** was defined (using [sqlite3_busy_handler()]) prior to calling ** this routine, that other busy handler is cleared.)^ ** ** See also: [PRAGMA busy_timeout] */ SQLITE_API int sqlite3_busy_timeout(sqlite3*, int ms); /* ** CAPI3REF: Convenience Routines For Running Queries ** METHOD: sqlite3 ** ** This is a legacy interface that is preserved for backwards compatibility. ** Use of this interface is not recommended. ** ** Definition: A result table is memory data structure created by the ** [sqlite3_get_table()] interface. A result table records the ** complete query results from one or more queries. ** ** The table conceptually has a number of rows and columns. But ** these numbers are not part of the result table itself. These ** numbers are obtained separately. Let N be the number of rows ** and M be the number of columns. ** ** A result table is an array of pointers to zero-terminated UTF-8 strings. ** There are (N+1)*M elements in the array. The first M pointers point ** to zero-terminated strings that contain the names of the columns. ** The remaining entries all point to query results. NULL values result ** in NULL pointers. All other values are in their UTF-8 zero-terminated ** string representation as returned by [sqlite3_column_text()]. ** ** A result table might consist of one or more memory allocations. ** It is not safe to pass a result table directly to [sqlite3_free()]. ** A result table should be deallocated using [sqlite3_free_table()]. ** ** ^(As an example of the result table format, suppose a query result ** is as follows: ** **
**        Name        | Age
**        -----------------------
**        Alice       | 43
**        Bob         | 28
**        Cindy       | 21
** 
** ** There are two column (M==2) and three rows (N==3). Thus the ** result table has 8 entries. Suppose the result table is stored ** in an array names azResult. Then azResult holds this content: ** **
**        azResult[0] = "Name";
**        azResult[1] = "Age";
**        azResult[2] = "Alice";
**        azResult[3] = "43";
**        azResult[4] = "Bob";
**        azResult[5] = "28";
**        azResult[6] = "Cindy";
**        azResult[7] = "21";
** 
)^ ** ** ^The sqlite3_get_table() function evaluates one or more ** semicolon-separated SQL statements in the zero-terminated UTF-8 ** string of its 2nd parameter and returns a result table to the ** pointer given in its 3rd parameter. ** ** After the application has finished with the result from sqlite3_get_table(), ** it must pass the result table pointer to sqlite3_free_table() in order to ** release the memory that was malloced. Because of the way the ** [sqlite3_malloc()] happens within sqlite3_get_table(), the calling ** function must not try to call [sqlite3_free()] directly. Only ** [sqlite3_free_table()] is able to release the memory properly and safely. ** ** The sqlite3_get_table() interface is implemented as a wrapper around ** [sqlite3_exec()]. The sqlite3_get_table() routine does not have access ** to any internal data structures of SQLite. It uses only the public ** interface defined here. As a consequence, errors that occur in the ** wrapper layer outside of the internal [sqlite3_exec()] call are not ** reflected in subsequent calls to [sqlite3_errcode()] or ** [sqlite3_errmsg()]. */ SQLITE_API int sqlite3_get_table( sqlite3 *db, /* An open database */ const char *zSql, /* SQL to be evaluated */ char ***pazResult, /* Results of the query */ int *pnRow, /* Number of result rows written here */ int *pnColumn, /* Number of result columns written here */ char **pzErrmsg /* Error msg written here */ ); SQLITE_API void sqlite3_free_table(char **result); /* ** CAPI3REF: Formatted String Printing Functions ** ** These routines are work-alikes of the "printf()" family of functions ** from the standard C library. ** These routines understand most of the common K&R formatting options, ** plus some additional non-standard formats, detailed below. ** Note that some of the more obscure formatting options from recent ** C-library standards are omitted from this implementation. ** ** ^The sqlite3_mprintf() and sqlite3_vmprintf() routines write their ** results into memory obtained from [sqlite3_malloc()]. ** The strings returned by these two routines should be ** released by [sqlite3_free()]. ^Both routines return a ** NULL pointer if [sqlite3_malloc()] is unable to allocate enough ** memory to hold the resulting string. ** ** ^(The sqlite3_snprintf() routine is similar to "snprintf()" from ** the standard C library. The result is written into the ** buffer supplied as the second parameter whose size is given by ** the first parameter. Note that the order of the ** first two parameters is reversed from snprintf().)^ This is an ** historical accident that cannot be fixed without breaking ** backwards compatibility. ^(Note also that sqlite3_snprintf() ** returns a pointer to its buffer instead of the number of ** characters actually written into the buffer.)^ We admit that ** the number of characters written would be a more useful return ** value but we cannot change the implementation of sqlite3_snprintf() ** now without breaking compatibility. ** ** ^As long as the buffer size is greater than zero, sqlite3_snprintf() ** guarantees that the buffer is always zero-terminated. ^The first ** parameter "n" is the total size of the buffer, including space for ** the zero terminator. So the longest string that can be completely ** written will be n-1 characters. ** ** ^The sqlite3_vsnprintf() routine is a varargs version of sqlite3_snprintf(). ** ** These routines all implement some additional formatting ** options that are useful for constructing SQL statements. ** All of the usual printf() formatting options apply. In addition, there ** is are "%q", "%Q", "%w" and "%z" options. ** ** ^(The %q option works like %s in that it substitutes a nul-terminated ** string from the argument list. But %q also doubles every '\'' character. ** %q is designed for use inside a string literal.)^ By doubling each '\'' ** character it escapes that character and allows it to be inserted into ** the string. ** ** For example, assume the string variable zText contains text as follows: ** **
**  char *zText = "It's a happy day!";
** 
** ** One can use this text in an SQL statement as follows: ** **
**  char *zSQL = sqlite3_mprintf("INSERT INTO table VALUES('%q')", zText);
**  sqlite3_exec(db, zSQL, 0, 0, 0);
**  sqlite3_free(zSQL);
** 
** ** Because the %q format string is used, the '\'' character in zText ** is escaped and the SQL generated is as follows: ** **
**  INSERT INTO table1 VALUES('It''s a happy day!')
** 
** ** This is correct. Had we used %s instead of %q, the generated SQL ** would have looked like this: ** **
**  INSERT INTO table1 VALUES('It's a happy day!');
** 
** ** This second example is an SQL syntax error. As a general rule you should ** always use %q instead of %s when inserting text into a string literal. ** ** ^(The %Q option works like %q except it also adds single quotes around ** the outside of the total string. Additionally, if the parameter in the ** argument list is a NULL pointer, %Q substitutes the text "NULL" (without ** single quotes).)^ So, for example, one could say: ** **
**  char *zSQL = sqlite3_mprintf("INSERT INTO table VALUES(%Q)", zText);
**  sqlite3_exec(db, zSQL, 0, 0, 0);
**  sqlite3_free(zSQL);
** 
** ** The code above will render a correct SQL statement in the zSQL ** variable even if the zText variable is a NULL pointer. ** ** ^(The "%w" formatting option is like "%q" except that it expects to ** be contained within double-quotes instead of single quotes, and it ** escapes the double-quote character instead of the single-quote ** character.)^ The "%w" formatting option is intended for safely inserting ** table and column names into a constructed SQL statement. ** ** ^(The "%z" formatting option works like "%s" but with the ** addition that after the string has been read and copied into ** the result, [sqlite3_free()] is called on the input string.)^ */ SQLITE_API char *sqlite3_mprintf(const char*,...); SQLITE_API char *sqlite3_vmprintf(const char*, va_list); SQLITE_API char *sqlite3_snprintf(int,char*,const char*, ...); SQLITE_API char *sqlite3_vsnprintf(int,char*,const char*, va_list); /* ** CAPI3REF: Memory Allocation Subsystem ** ** The SQLite core uses these three routines for all of its own ** internal memory allocation needs. "Core" in the previous sentence ** does not include operating-system specific VFS implementation. The ** Windows VFS uses native malloc() and free() for some operations. ** ** ^The sqlite3_malloc() routine returns a pointer to a block ** of memory at least N bytes in length, where N is the parameter. ** ^If sqlite3_malloc() is unable to obtain sufficient free ** memory, it returns a NULL pointer. ^If the parameter N to ** sqlite3_malloc() is zero or negative then sqlite3_malloc() returns ** a NULL pointer. ** ** ^The sqlite3_malloc64(N) routine works just like ** sqlite3_malloc(N) except that N is an unsigned 64-bit integer instead ** of a signed 32-bit integer. ** ** ^Calling sqlite3_free() with a pointer previously returned ** by sqlite3_malloc() or sqlite3_realloc() releases that memory so ** that it might be reused. ^The sqlite3_free() routine is ** a no-op if is called with a NULL pointer. Passing a NULL pointer ** to sqlite3_free() is harmless. After being freed, memory ** should neither be read nor written. Even reading previously freed ** memory might result in a segmentation fault or other severe error. ** Memory corruption, a segmentation fault, or other severe error ** might result if sqlite3_free() is called with a non-NULL pointer that ** was not obtained from sqlite3_malloc() or sqlite3_realloc(). ** ** ^The sqlite3_realloc(X,N) interface attempts to resize a ** prior memory allocation X to be at least N bytes. ** ^If the X parameter to sqlite3_realloc(X,N) ** is a NULL pointer then its behavior is identical to calling ** sqlite3_malloc(N). ** ^If the N parameter to sqlite3_realloc(X,N) is zero or ** negative then the behavior is exactly the same as calling ** sqlite3_free(X). ** ^sqlite3_realloc(X,N) returns a pointer to a memory allocation ** of at least N bytes in size or NULL if insufficient memory is available. ** ^If M is the size of the prior allocation, then min(N,M) bytes ** of the prior allocation are copied into the beginning of buffer returned ** by sqlite3_realloc(X,N) and the prior allocation is freed. ** ^If sqlite3_realloc(X,N) returns NULL and N is positive, then the ** prior allocation is not freed. ** ** ^The sqlite3_realloc64(X,N) interfaces works the same as ** sqlite3_realloc(X,N) except that N is a 64-bit unsigned integer instead ** of a 32-bit signed integer. ** ** ^If X is a memory allocation previously obtained from sqlite3_malloc(), ** sqlite3_malloc64(), sqlite3_realloc(), or sqlite3_realloc64(), then ** sqlite3_msize(X) returns the size of that memory allocation in bytes. ** ^The value returned by sqlite3_msize(X) might be larger than the number ** of bytes requested when X was allocated. ^If X is a NULL pointer then ** sqlite3_msize(X) returns zero. If X points to something that is not ** the beginning of memory allocation, or if it points to a formerly ** valid memory allocation that has now been freed, then the behavior ** of sqlite3_msize(X) is undefined and possibly harmful. ** ** ^The memory returned by sqlite3_malloc(), sqlite3_realloc(), ** sqlite3_malloc64(), and sqlite3_realloc64() ** is always aligned to at least an 8 byte boundary, or to a ** 4 byte boundary if the [SQLITE_4_BYTE_ALIGNED_MALLOC] compile-time ** option is used. ** ** In SQLite version 3.5.0 and 3.5.1, it was possible to define ** the SQLITE_OMIT_MEMORY_ALLOCATION which would cause the built-in ** implementation of these routines to be omitted. That capability ** is no longer provided. Only built-in memory allocators can be used. ** ** Prior to SQLite version 3.7.10, the Windows OS interface layer called ** the system malloc() and free() directly when converting ** filenames between the UTF-8 encoding used by SQLite ** and whatever filename encoding is used by the particular Windows ** installation. Memory allocation errors were detected, but ** they were reported back as [SQLITE_CANTOPEN] or ** [SQLITE_IOERR] rather than [SQLITE_NOMEM]. ** ** The pointer arguments to [sqlite3_free()] and [sqlite3_realloc()] ** must be either NULL or else pointers obtained from a prior ** invocation of [sqlite3_malloc()] or [sqlite3_realloc()] that have ** not yet been released. ** ** The application must not read or write any part of ** a block of memory after it has been released using ** [sqlite3_free()] or [sqlite3_realloc()]. */ SQLITE_API void *sqlite3_malloc(int); SQLITE_API void *sqlite3_malloc64(sqlite3_uint64); SQLITE_API void *sqlite3_realloc(void*, int); SQLITE_API void *sqlite3_realloc64(void*, sqlite3_uint64); SQLITE_API void sqlite3_free(void*); SQLITE_API sqlite3_uint64 sqlite3_msize(void*); /* ** CAPI3REF: Memory Allocator Statistics ** ** SQLite provides these two interfaces for reporting on the status ** of the [sqlite3_malloc()], [sqlite3_free()], and [sqlite3_realloc()] ** routines, which form the built-in memory allocation subsystem. ** ** ^The [sqlite3_memory_used()] routine returns the number of bytes ** of memory currently outstanding (malloced but not freed). ** ^The [sqlite3_memory_highwater()] routine returns the maximum ** value of [sqlite3_memory_used()] since the high-water mark ** was last reset. ^The values returned by [sqlite3_memory_used()] and ** [sqlite3_memory_highwater()] include any overhead ** added by SQLite in its implementation of [sqlite3_malloc()], ** but not overhead added by the any underlying system library ** routines that [sqlite3_malloc()] may call. ** ** ^The memory high-water mark is reset to the current value of ** [sqlite3_memory_used()] if and only if the parameter to ** [sqlite3_memory_highwater()] is true. ^The value returned ** by [sqlite3_memory_highwater(1)] is the high-water mark ** prior to the reset. */ SQLITE_API sqlite3_int64 sqlite3_memory_used(void); SQLITE_API sqlite3_int64 sqlite3_memory_highwater(int resetFlag); /* ** CAPI3REF: Pseudo-Random Number Generator ** ** SQLite contains a high-quality pseudo-random number generator (PRNG) used to ** select random [ROWID | ROWIDs] when inserting new records into a table that ** already uses the largest possible [ROWID]. The PRNG is also used for ** the build-in random() and randomblob() SQL functions. This interface allows ** applications to access the same PRNG for other purposes. ** ** ^A call to this routine stores N bytes of randomness into buffer P. ** ^The P parameter can be a NULL pointer. ** ** ^If this routine has not been previously called or if the previous ** call had N less than one or a NULL pointer for P, then the PRNG is ** seeded using randomness obtained from the xRandomness method of ** the default [sqlite3_vfs] object. ** ^If the previous call to this routine had an N of 1 or more and a ** non-NULL P then the pseudo-randomness is generated ** internally and without recourse to the [sqlite3_vfs] xRandomness ** method. */ SQLITE_API void sqlite3_randomness(int N, void *P); /* ** CAPI3REF: Compile-Time Authorization Callbacks ** METHOD: sqlite3 ** ** ^This routine registers an authorizer callback with a particular ** [database connection], supplied in the first argument. ** ^The authorizer callback is invoked as SQL statements are being compiled ** by [sqlite3_prepare()] or its variants [sqlite3_prepare_v2()], ** [sqlite3_prepare16()] and [sqlite3_prepare16_v2()]. ^At various ** points during the compilation process, as logic is being created ** to perform various actions, the authorizer callback is invoked to ** see if those actions are allowed. ^The authorizer callback should ** return [SQLITE_OK] to allow the action, [SQLITE_IGNORE] to disallow the ** specific action but allow the SQL statement to continue to be ** compiled, or [SQLITE_DENY] to cause the entire SQL statement to be ** rejected with an error. ^If the authorizer callback returns ** any value other than [SQLITE_IGNORE], [SQLITE_OK], or [SQLITE_DENY] ** then the [sqlite3_prepare_v2()] or equivalent call that triggered ** the authorizer will fail with an error message. ** ** When the callback returns [SQLITE_OK], that means the operation ** requested is ok. ^When the callback returns [SQLITE_DENY], the ** [sqlite3_prepare_v2()] or equivalent call that triggered the ** authorizer will fail with an error message explaining that ** access is denied. ** ** ^The first parameter to the authorizer callback is a copy of the third ** parameter to the sqlite3_set_authorizer() interface. ^The second parameter ** to the callback is an integer [SQLITE_COPY | action code] that specifies ** the particular action to be authorized. ^The third through sixth parameters ** to the callback are zero-terminated strings that contain additional ** details about the action to be authorized. ** ** ^If the action code is [SQLITE_READ] ** and the callback returns [SQLITE_IGNORE] then the ** [prepared statement] statement is constructed to substitute ** a NULL value in place of the table column that would have ** been read if [SQLITE_OK] had been returned. The [SQLITE_IGNORE] ** return can be used to deny an untrusted user access to individual ** columns of a table. ** ^If the action code is [SQLITE_DELETE] and the callback returns ** [SQLITE_IGNORE] then the [DELETE] operation proceeds but the ** [truncate optimization] is disabled and all rows are deleted individually. ** ** An authorizer is used when [sqlite3_prepare | preparing] ** SQL statements from an untrusted source, to ensure that the SQL statements ** do not try to access data they are not allowed to see, or that they do not ** try to execute malicious statements that damage the database. For ** example, an application may allow a user to enter arbitrary ** SQL queries for evaluation by a database. But the application does ** not want the user to be able to make arbitrary changes to the ** database. An authorizer could then be put in place while the ** user-entered SQL is being [sqlite3_prepare | prepared] that ** disallows everything except [SELECT] statements. ** ** Applications that need to process SQL from untrusted sources ** might also consider lowering resource limits using [sqlite3_limit()] ** and limiting database size using the [max_page_count] [PRAGMA] ** in addition to using an authorizer. ** ** ^(Only a single authorizer can be in place on a database connection ** at a time. Each call to sqlite3_set_authorizer overrides the ** previous call.)^ ^Disable the authorizer by installing a NULL callback. ** The authorizer is disabled by default. ** ** The authorizer callback must not do anything that will modify ** the database connection that invoked the authorizer callback. ** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their ** database connections for the meaning of "modify" in this paragraph. ** ** ^When [sqlite3_prepare_v2()] is used to prepare a statement, the ** statement might be re-prepared during [sqlite3_step()] due to a ** schema change. Hence, the application should ensure that the ** correct authorizer callback remains in place during the [sqlite3_step()]. ** ** ^Note that the authorizer callback is invoked only during ** [sqlite3_prepare()] or its variants. Authorization is not ** performed during statement evaluation in [sqlite3_step()], unless ** as stated in the previous paragraph, sqlite3_step() invokes ** sqlite3_prepare_v2() to reprepare a statement after a schema change. */ SQLITE_API int sqlite3_set_authorizer( sqlite3*, int (*xAuth)(void*,int,const char*,const char*,const char*,const char*), void *pUserData ); /* ** CAPI3REF: Authorizer Return Codes ** ** The [sqlite3_set_authorizer | authorizer callback function] must ** return either [SQLITE_OK] or one of these two constants in order ** to signal SQLite whether or not the action is permitted. See the ** [sqlite3_set_authorizer | authorizer documentation] for additional ** information. ** ** Note that SQLITE_IGNORE is also used as a [conflict resolution mode] ** returned from the [sqlite3_vtab_on_conflict()] interface. */ #define SQLITE_DENY 1 /* Abort the SQL statement with an error */ #define SQLITE_IGNORE 2 /* Don't allow access, but don't generate an error */ /* ** CAPI3REF: Authorizer Action Codes ** ** The [sqlite3_set_authorizer()] interface registers a callback function ** that is invoked to authorize certain SQL statement actions. The ** second parameter to the callback is an integer code that specifies ** what action is being authorized. These are the integer action codes that ** the authorizer callback may be passed. ** ** These action code values signify what kind of operation is to be ** authorized. The 3rd and 4th parameters to the authorization ** callback function will be parameters or NULL depending on which of these ** codes is used as the second parameter. ^(The 5th parameter to the ** authorizer callback is the name of the database ("main", "temp", ** etc.) if applicable.)^ ^The 6th parameter to the authorizer callback ** is the name of the inner-most trigger or view that is responsible for ** the access attempt or NULL if this access attempt is directly from ** top-level SQL code. */ /******************************************* 3rd ************ 4th ***********/ #define SQLITE_CREATE_INDEX 1 /* Index Name Table Name */ #define SQLITE_CREATE_TABLE 2 /* Table Name NULL */ #define SQLITE_CREATE_TEMP_INDEX 3 /* Index Name Table Name */ #define SQLITE_CREATE_TEMP_TABLE 4 /* Table Name NULL */ #define SQLITE_CREATE_TEMP_TRIGGER 5 /* Trigger Name Table Name */ #define SQLITE_CREATE_TEMP_VIEW 6 /* View Name NULL */ #define SQLITE_CREATE_TRIGGER 7 /* Trigger Name Table Name */ #define SQLITE_CREATE_VIEW 8 /* View Name NULL */ #define SQLITE_DELETE 9 /* Table Name NULL */ #define SQLITE_DROP_INDEX 10 /* Index Name Table Name */ #define SQLITE_DROP_TABLE 11 /* Table Name NULL */ #define SQLITE_DROP_TEMP_INDEX 12 /* Index Name Table Name */ #define SQLITE_DROP_TEMP_TABLE 13 /* Table Name NULL */ #define SQLITE_DROP_TEMP_TRIGGER 14 /* Trigger Name Table Name */ #define SQLITE_DROP_TEMP_VIEW 15 /* View Name NULL */ #define SQLITE_DROP_TRIGGER 16 /* Trigger Name Table Name */ #define SQLITE_DROP_VIEW 17 /* View Name NULL */ #define SQLITE_INSERT 18 /* Table Name NULL */ #define SQLITE_PRAGMA 19 /* Pragma Name 1st arg or NULL */ #define SQLITE_READ 20 /* Table Name Column Name */ #define SQLITE_SELECT 21 /* NULL NULL */ #define SQLITE_TRANSACTION 22 /* Operation NULL */ #define SQLITE_UPDATE 23 /* Table Name Column Name */ #define SQLITE_ATTACH 24 /* Filename NULL */ #define SQLITE_DETACH 25 /* Database Name NULL */ #define SQLITE_ALTER_TABLE 26 /* Database Name Table Name */ #define SQLITE_REINDEX 27 /* Index Name NULL */ #define SQLITE_ANALYZE 28 /* Table Name NULL */ #define SQLITE_CREATE_VTABLE 29 /* Table Name Module Name */ #define SQLITE_DROP_VTABLE 30 /* Table Name Module Name */ #define SQLITE_FUNCTION 31 /* NULL Function Name */ #define SQLITE_SAVEPOINT 32 /* Operation Savepoint Name */ #define SQLITE_COPY 0 /* No longer used */ #define SQLITE_RECURSIVE 33 /* NULL NULL */ /* ** CAPI3REF: Tracing And Profiling Functions ** METHOD: sqlite3 ** ** These routines are deprecated. Use the [sqlite3_trace_v2()] interface ** instead of the routines described here. ** ** These routines register callback functions that can be used for ** tracing and profiling the execution of SQL statements. ** ** ^The callback function registered by sqlite3_trace() is invoked at ** various times when an SQL statement is being run by [sqlite3_step()]. ** ^The sqlite3_trace() callback is invoked with a UTF-8 rendering of the ** SQL statement text as the statement first begins executing. ** ^(Additional sqlite3_trace() callbacks might occur ** as each triggered subprogram is entered. The callbacks for triggers ** contain a UTF-8 SQL comment that identifies the trigger.)^ ** ** The [SQLITE_TRACE_SIZE_LIMIT] compile-time option can be used to limit ** the length of [bound parameter] expansion in the output of sqlite3_trace(). ** ** ^The callback function registered by sqlite3_profile() is invoked ** as each SQL statement finishes. ^The profile callback contains ** the original statement text and an estimate of wall-clock time ** of how long that statement took to run. ^The profile callback ** time is in units of nanoseconds, however the current implementation ** is only capable of millisecond resolution so the six least significant ** digits in the time are meaningless. Future versions of SQLite ** might provide greater resolution on the profiler callback. The ** sqlite3_profile() function is considered experimental and is ** subject to change in future versions of SQLite. */ SQLITE_API SQLITE_DEPRECATED void *sqlite3_trace(sqlite3*, void(*xTrace)(void*,const char*), void*); SQLITE_API SQLITE_DEPRECATED void *sqlite3_profile(sqlite3*, void(*xProfile)(void*,const char*,sqlite3_uint64), void*); /* ** CAPI3REF: SQL Trace Event Codes ** KEYWORDS: SQLITE_TRACE ** ** These constants identify classes of events that can be monitored ** using the [sqlite3_trace_v2()] tracing logic. The third argument ** to [sqlite3_trace_v2()] is an OR-ed combination of one or more of ** the following constants. ^The first argument to the trace callback ** is one of the following constants. ** ** New tracing constants may be added in future releases. ** ** ^A trace callback has four arguments: xCallback(T,C,P,X). ** ^The T argument is one of the integer type codes above. ** ^The C argument is a copy of the context pointer passed in as the ** fourth argument to [sqlite3_trace_v2()]. ** The P and X arguments are pointers whose meanings depend on T. ** **
** [[SQLITE_TRACE_STMT]]
SQLITE_TRACE_STMT
**
^An SQLITE_TRACE_STMT callback is invoked when a prepared statement ** first begins running and possibly at other times during the ** execution of the prepared statement, such as at the start of each ** trigger subprogram. ^The P argument is a pointer to the ** [prepared statement]. ^The X argument is a pointer to a string which ** is the unexpanded SQL text of the prepared statement or an SQL comment ** that indicates the invocation of a trigger. ^The callback can compute ** the same text that would have been returned by the legacy [sqlite3_trace()] ** interface by using the X argument when X begins with "--" and invoking ** [sqlite3_expanded_sql(P)] otherwise. ** ** [[SQLITE_TRACE_PROFILE]]
SQLITE_TRACE_PROFILE
**
^An SQLITE_TRACE_PROFILE callback provides approximately the same ** information as is provided by the [sqlite3_profile()] callback. ** ^The P argument is a pointer to the [prepared statement] and the ** X argument points to a 64-bit integer which is the estimated of ** the number of nanosecond that the prepared statement took to run. ** ^The SQLITE_TRACE_PROFILE callback is invoked when the statement finishes. ** ** [[SQLITE_TRACE_ROW]]
SQLITE_TRACE_ROW
**
^An SQLITE_TRACE_ROW callback is invoked whenever a prepared ** statement generates a single row of result. ** ^The P argument is a pointer to the [prepared statement] and the ** X argument is unused. ** ** [[SQLITE_TRACE_CLOSE]]
SQLITE_TRACE_CLOSE
**
^An SQLITE_TRACE_CLOSE callback is invoked when a database ** connection closes. ** ^The P argument is a pointer to the [database connection] object ** and the X argument is unused. **
*/ #define SQLITE_TRACE_STMT 0x01 #define SQLITE_TRACE_PROFILE 0x02 #define SQLITE_TRACE_ROW 0x04 #define SQLITE_TRACE_CLOSE 0x08 /* ** CAPI3REF: SQL Trace Hook ** METHOD: sqlite3 ** ** ^The sqlite3_trace_v2(D,M,X,P) interface registers a trace callback ** function X against [database connection] D, using property mask M ** and context pointer P. ^If the X callback is ** NULL or if the M mask is zero, then tracing is disabled. The ** M argument should be the bitwise OR-ed combination of ** zero or more [SQLITE_TRACE] constants. ** ** ^Each call to either sqlite3_trace() or sqlite3_trace_v2() overrides ** (cancels) any prior calls to sqlite3_trace() or sqlite3_trace_v2(). ** ** ^The X callback is invoked whenever any of the events identified by ** mask M occur. ^The integer return value from the callback is currently ** ignored, though this may change in future releases. Callback ** implementations should return zero to ensure future compatibility. ** ** ^A trace callback is invoked with four arguments: callback(T,C,P,X). ** ^The T argument is one of the [SQLITE_TRACE] ** constants to indicate why the callback was invoked. ** ^The C argument is a copy of the context pointer. ** The P and X arguments are pointers whose meanings depend on T. ** ** The sqlite3_trace_v2() interface is intended to replace the legacy ** interfaces [sqlite3_trace()] and [sqlite3_profile()], both of which ** are deprecated. */ SQLITE_API int sqlite3_trace_v2( sqlite3*, unsigned uMask, int(*xCallback)(unsigned,void*,void*,void*), void *pCtx ); /* ** CAPI3REF: Query Progress Callbacks ** METHOD: sqlite3 ** ** ^The sqlite3_progress_handler(D,N,X,P) interface causes the callback ** function X to be invoked periodically during long running calls to ** [sqlite3_exec()], [sqlite3_step()] and [sqlite3_get_table()] for ** database connection D. An example use for this ** interface is to keep a GUI updated during a large query. ** ** ^The parameter P is passed through as the only parameter to the ** callback function X. ^The parameter N is the approximate number of ** [virtual machine instructions] that are evaluated between successive ** invocations of the callback X. ^If N is less than one then the progress ** handler is disabled. ** ** ^Only a single progress handler may be defined at one time per ** [database connection]; setting a new progress handler cancels the ** old one. ^Setting parameter X to NULL disables the progress handler. ** ^The progress handler is also disabled by setting N to a value less ** than 1. ** ** ^If the progress callback returns non-zero, the operation is ** interrupted. This feature can be used to implement a ** "Cancel" button on a GUI progress dialog box. ** ** The progress handler callback must not do anything that will modify ** the database connection that invoked the progress handler. ** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their ** database connections for the meaning of "modify" in this paragraph. ** */ SQLITE_API void sqlite3_progress_handler(sqlite3*, int, int(*)(void*), void*); /* ** CAPI3REF: Opening A New Database Connection ** CONSTRUCTOR: sqlite3 ** ** ^These routines open an SQLite database file as specified by the ** filename argument. ^The filename argument is interpreted as UTF-8 for ** sqlite3_open() and sqlite3_open_v2() and as UTF-16 in the native byte ** order for sqlite3_open16(). ^(A [database connection] handle is usually ** returned in *ppDb, even if an error occurs. The only exception is that ** if SQLite is unable to allocate memory to hold the [sqlite3] object, ** a NULL will be written into *ppDb instead of a pointer to the [sqlite3] ** object.)^ ^(If the database is opened (and/or created) successfully, then ** [SQLITE_OK] is returned. Otherwise an [error code] is returned.)^ ^The ** [sqlite3_errmsg()] or [sqlite3_errmsg16()] routines can be used to obtain ** an English language description of the error following a failure of any ** of the sqlite3_open() routines. ** ** ^The default encoding will be UTF-8 for databases created using ** sqlite3_open() or sqlite3_open_v2(). ^The default encoding for databases ** created using sqlite3_open16() will be UTF-16 in the native byte order. ** ** Whether or not an error occurs when it is opened, resources ** associated with the [database connection] handle should be released by ** passing it to [sqlite3_close()] when it is no longer required. ** ** The sqlite3_open_v2() interface works like sqlite3_open() ** except that it accepts two additional parameters for additional control ** over the new database connection. ^(The flags parameter to ** sqlite3_open_v2() can take one of ** the following three values, optionally combined with the ** [SQLITE_OPEN_NOMUTEX], [SQLITE_OPEN_FULLMUTEX], [SQLITE_OPEN_SHAREDCACHE], ** [SQLITE_OPEN_PRIVATECACHE], and/or [SQLITE_OPEN_URI] flags:)^ ** **
** ^(
[SQLITE_OPEN_READONLY]
**
The database is opened in read-only mode. If the database does not ** already exist, an error is returned.
)^ ** ** ^(
[SQLITE_OPEN_READWRITE]
**
The database is opened for reading and writing if possible, or reading ** only if the file is write protected by the operating system. In either ** case the database must already exist, otherwise an error is returned.
)^ ** ** ^(
[SQLITE_OPEN_READWRITE] | [SQLITE_OPEN_CREATE]
**
The database is opened for reading and writing, and is created if ** it does not already exist. This is the behavior that is always used for ** sqlite3_open() and sqlite3_open16().
)^ **
** ** If the 3rd parameter to sqlite3_open_v2() is not one of the ** combinations shown above optionally combined with other ** [SQLITE_OPEN_READONLY | SQLITE_OPEN_* bits] ** then the behavior is undefined. ** ** ^If the [SQLITE_OPEN_NOMUTEX] flag is set, then the database connection ** opens in the multi-thread [threading mode] as long as the single-thread ** mode has not been set at compile-time or start-time. ^If the ** [SQLITE_OPEN_FULLMUTEX] flag is set then the database connection opens ** in the serialized [threading mode] unless single-thread was ** previously selected at compile-time or start-time. ** ^The [SQLITE_OPEN_SHAREDCACHE] flag causes the database connection to be ** eligible to use [shared cache mode], regardless of whether or not shared ** cache is enabled using [sqlite3_enable_shared_cache()]. ^The ** [SQLITE_OPEN_PRIVATECACHE] flag causes the database connection to not ** participate in [shared cache mode] even if it is enabled. ** ** ^The fourth parameter to sqlite3_open_v2() is the name of the ** [sqlite3_vfs] object that defines the operating system interface that ** the new database connection should use. ^If the fourth parameter is ** a NULL pointer then the default [sqlite3_vfs] object is used. ** ** ^If the filename is ":memory:", then a private, temporary in-memory database ** is created for the connection. ^This in-memory database will vanish when ** the database connection is closed. Future versions of SQLite might ** make use of additional special filenames that begin with the ":" character. ** It is recommended that when a database filename actually does begin with ** a ":" character you should prefix the filename with a pathname such as ** "./" to avoid ambiguity. ** ** ^If the filename is an empty string, then a private, temporary ** on-disk database will be created. ^This private database will be ** automatically deleted as soon as the database connection is closed. ** ** [[URI filenames in sqlite3_open()]]

URI Filenames

** ** ^If [URI filename] interpretation is enabled, and the filename argument ** begins with "file:", then the filename is interpreted as a URI. ^URI ** filename interpretation is enabled if the [SQLITE_OPEN_URI] flag is ** set in the fourth argument to sqlite3_open_v2(), or if it has ** been enabled globally using the [SQLITE_CONFIG_URI] option with the ** [sqlite3_config()] method or by the [SQLITE_USE_URI] compile-time option. ** As of SQLite version 3.7.7, URI filename interpretation is turned off ** by default, but future releases of SQLite might enable URI filename ** interpretation by default. See "[URI filenames]" for additional ** information. ** ** URI filenames are parsed according to RFC 3986. ^If the URI contains an ** authority, then it must be either an empty string or the string ** "localhost". ^If the authority is not an empty string or "localhost", an ** error is returned to the caller. ^The fragment component of a URI, if ** present, is ignored. ** ** ^SQLite uses the path component of the URI as the name of the disk file ** which contains the database. ^If the path begins with a '/' character, ** then it is interpreted as an absolute path. ^If the path does not begin ** with a '/' (meaning that the authority section is omitted from the URI) ** then the path is interpreted as a relative path. ** ^(On windows, the first component of an absolute path ** is a drive specification (e.g. "C:").)^ ** ** [[core URI query parameters]] ** The query component of a URI may contain parameters that are interpreted ** either by SQLite itself, or by a [VFS | custom VFS implementation]. ** SQLite and its built-in [VFSes] interpret the ** following query parameters: ** **
    **
  • vfs: ^The "vfs" parameter may be used to specify the name of ** a VFS object that provides the operating system interface that should ** be used to access the database file on disk. ^If this option is set to ** an empty string the default VFS object is used. ^Specifying an unknown ** VFS is an error. ^If sqlite3_open_v2() is used and the vfs option is ** present, then the VFS specified by the option takes precedence over ** the value passed as the fourth parameter to sqlite3_open_v2(). ** **
  • mode: ^(The mode parameter may be set to either "ro", "rw", ** "rwc", or "memory". Attempting to set it to any other value is ** an error)^. ** ^If "ro" is specified, then the database is opened for read-only ** access, just as if the [SQLITE_OPEN_READONLY] flag had been set in the ** third argument to sqlite3_open_v2(). ^If the mode option is set to ** "rw", then the database is opened for read-write (but not create) ** access, as if SQLITE_OPEN_READWRITE (but not SQLITE_OPEN_CREATE) had ** been set. ^Value "rwc" is equivalent to setting both ** SQLITE_OPEN_READWRITE and SQLITE_OPEN_CREATE. ^If the mode option is ** set to "memory" then a pure [in-memory database] that never reads ** or writes from disk is used. ^It is an error to specify a value for ** the mode parameter that is less restrictive than that specified by ** the flags passed in the third parameter to sqlite3_open_v2(). ** **
  • cache: ^The cache parameter may be set to either "shared" or ** "private". ^Setting it to "shared" is equivalent to setting the ** SQLITE_OPEN_SHAREDCACHE bit in the flags argument passed to ** sqlite3_open_v2(). ^Setting the cache parameter to "private" is ** equivalent to setting the SQLITE_OPEN_PRIVATECACHE bit. ** ^If sqlite3_open_v2() is used and the "cache" parameter is present in ** a URI filename, its value overrides any behavior requested by setting ** SQLITE_OPEN_PRIVATECACHE or SQLITE_OPEN_SHAREDCACHE flag. ** **
  • psow: ^The psow parameter indicates whether or not the ** [powersafe overwrite] property does or does not apply to the ** storage media on which the database file resides. ** **
  • nolock: ^The nolock parameter is a boolean query parameter ** which if set disables file locking in rollback journal modes. This ** is useful for accessing a database on a filesystem that does not ** support locking. Caution: Database corruption might result if two ** or more processes write to the same database and any one of those ** processes uses nolock=1. ** **
  • immutable: ^The immutable parameter is a boolean query ** parameter that indicates that the database file is stored on ** read-only media. ^When immutable is set, SQLite assumes that the ** database file cannot be changed, even by a process with higher ** privilege, and so the database is opened read-only and all locking ** and change detection is disabled. Caution: Setting the immutable ** property on a database file that does in fact change can result ** in incorrect query results and/or [SQLITE_CORRUPT] errors. ** See also: [SQLITE_IOCAP_IMMUTABLE]. ** **
** ** ^Specifying an unknown parameter in the query component of a URI is not an ** error. Future versions of SQLite might understand additional query ** parameters. See "[query parameters with special meaning to SQLite]" for ** additional information. ** ** [[URI filename examples]]

URI filename examples

** ** **
URI filenames Results **
file:data.db ** Open the file "data.db" in the current directory. **
file:/home/fred/data.db
** file:///home/fred/data.db
** file://localhost/home/fred/data.db
** Open the database file "/home/fred/data.db". **
file://darkstar/home/fred/data.db ** An error. "darkstar" is not a recognized authority. **
** file:///C:/Documents%20and%20Settings/fred/Desktop/data.db ** Windows only: Open the file "data.db" on fred's desktop on drive ** C:. Note that the %20 escaping in this example is not strictly ** necessary - space characters can be used literally ** in URI filenames. **
file:data.db?mode=ro&cache=private ** Open file "data.db" in the current directory for read-only access. ** Regardless of whether or not shared-cache mode is enabled by ** default, use a private cache. **
file:/home/fred/data.db?vfs=unix-dotfile ** Open file "/home/fred/data.db". Use the special VFS "unix-dotfile" ** that uses dot-files in place of posix advisory locking. **
file:data.db?mode=readonly ** An error. "readonly" is not a valid option for the "mode" parameter. **
** ** ^URI hexadecimal escape sequences (%HH) are supported within the path and ** query components of a URI. A hexadecimal escape sequence consists of a ** percent sign - "%" - followed by exactly two hexadecimal digits ** specifying an octet value. ^Before the path or query components of a ** URI filename are interpreted, they are encoded using UTF-8 and all ** hexadecimal escape sequences replaced by a single byte containing the ** corresponding octet. If this process generates an invalid UTF-8 encoding, ** the results are undefined. ** ** Note to Windows users: The encoding used for the filename argument ** of sqlite3_open() and sqlite3_open_v2() must be UTF-8, not whatever ** codepage is currently defined. Filenames containing international ** characters must be converted to UTF-8 prior to passing them into ** sqlite3_open() or sqlite3_open_v2(). ** ** Note to Windows Runtime users: The temporary directory must be set ** prior to calling sqlite3_open() or sqlite3_open_v2(). Otherwise, various ** features that require the use of temporary files may fail. ** ** See also: [sqlite3_temp_directory] */ SQLITE_API int sqlite3_open( const char *filename, /* Database filename (UTF-8) */ sqlite3 **ppDb /* OUT: SQLite db handle */ ); SQLITE_API int sqlite3_open16( const void *filename, /* Database filename (UTF-16) */ sqlite3 **ppDb /* OUT: SQLite db handle */ ); SQLITE_API int sqlite3_open_v2( const char *filename, /* Database filename (UTF-8) */ sqlite3 **ppDb, /* OUT: SQLite db handle */ int flags, /* Flags */ const char *zVfs /* Name of VFS module to use */ ); /* ** CAPI3REF: Obtain Values For URI Parameters ** ** These are utility routines, useful to VFS implementations, that check ** to see if a database file was a URI that contained a specific query ** parameter, and if so obtains the value of that query parameter. ** ** If F is the database filename pointer passed into the xOpen() method of ** a VFS implementation when the flags parameter to xOpen() has one or ** more of the [SQLITE_OPEN_URI] or [SQLITE_OPEN_MAIN_DB] bits set and ** P is the name of the query parameter, then ** sqlite3_uri_parameter(F,P) returns the value of the P ** parameter if it exists or a NULL pointer if P does not appear as a ** query parameter on F. If P is a query parameter of F ** has no explicit value, then sqlite3_uri_parameter(F,P) returns ** a pointer to an empty string. ** ** The sqlite3_uri_boolean(F,P,B) routine assumes that P is a boolean ** parameter and returns true (1) or false (0) according to the value ** of P. The sqlite3_uri_boolean(F,P,B) routine returns true (1) if the ** value of query parameter P is one of "yes", "true", or "on" in any ** case or if the value begins with a non-zero number. The ** sqlite3_uri_boolean(F,P,B) routines returns false (0) if the value of ** query parameter P is one of "no", "false", or "off" in any case or ** if the value begins with a numeric zero. If P is not a query ** parameter on F or if the value of P is does not match any of the ** above, then sqlite3_uri_boolean(F,P,B) returns (B!=0). ** ** The sqlite3_uri_int64(F,P,D) routine converts the value of P into a ** 64-bit signed integer and returns that integer, or D if P does not ** exist. If the value of P is something other than an integer, then ** zero is returned. ** ** If F is a NULL pointer, then sqlite3_uri_parameter(F,P) returns NULL and ** sqlite3_uri_boolean(F,P,B) returns B. If F is not a NULL pointer and ** is not a database file pathname pointer that SQLite passed into the xOpen ** VFS method, then the behavior of this routine is undefined and probably ** undesirable. */ SQLITE_API const char *sqlite3_uri_parameter(const char *zFilename, const char *zParam); SQLITE_API int sqlite3_uri_boolean(const char *zFile, const char *zParam, int bDefault); SQLITE_API sqlite3_int64 sqlite3_uri_int64(const char*, const char*, sqlite3_int64); /* ** CAPI3REF: Error Codes And Messages ** METHOD: sqlite3 ** ** ^If the most recent sqlite3_* API call associated with ** [database connection] D failed, then the sqlite3_errcode(D) interface ** returns the numeric [result code] or [extended result code] for that ** API call. ** If the most recent API call was successful, ** then the return value from sqlite3_errcode() is undefined. ** ^The sqlite3_extended_errcode() ** interface is the same except that it always returns the ** [extended result code] even when extended result codes are ** disabled. ** ** ^The sqlite3_errmsg() and sqlite3_errmsg16() return English-language ** text that describes the error, as either UTF-8 or UTF-16 respectively. ** ^(Memory to hold the error message string is managed internally. ** The application does not need to worry about freeing the result. ** However, the error string might be overwritten or deallocated by ** subsequent calls to other SQLite interface functions.)^ ** ** ^The sqlite3_errstr() interface returns the English-language text ** that describes the [result code], as UTF-8. ** ^(Memory to hold the error message string is managed internally ** and must not be freed by the application)^. ** ** When the serialized [threading mode] is in use, it might be the ** case that a second error occurs on a separate thread in between ** the time of the first error and the call to these interfaces. ** When that happens, the second error will be reported since these ** interfaces always report the most recent result. To avoid ** this, each thread can obtain exclusive use of the [database connection] D ** by invoking [sqlite3_mutex_enter]([sqlite3_db_mutex](D)) before beginning ** to use D and invoking [sqlite3_mutex_leave]([sqlite3_db_mutex](D)) after ** all calls to the interfaces listed here are completed. ** ** If an interface fails with SQLITE_MISUSE, that means the interface ** was invoked incorrectly by the application. In that case, the ** error code and message may or may not be set. */ SQLITE_API int sqlite3_errcode(sqlite3 *db); SQLITE_API int sqlite3_extended_errcode(sqlite3 *db); SQLITE_API const char *sqlite3_errmsg(sqlite3*); SQLITE_API const void *sqlite3_errmsg16(sqlite3*); SQLITE_API const char *sqlite3_errstr(int); /* ** CAPI3REF: Prepared Statement Object ** KEYWORDS: {prepared statement} {prepared statements} ** ** An instance of this object represents a single SQL statement that ** has been compiled into binary form and is ready to be evaluated. ** ** Think of each SQL statement as a separate computer program. The ** original SQL text is source code. A prepared statement object ** is the compiled object code. All SQL must be converted into a ** prepared statement before it can be run. ** ** The life-cycle of a prepared statement object usually goes like this: ** **
    **
  1. Create the prepared statement object using [sqlite3_prepare_v2()]. **
  2. Bind values to [parameters] using the sqlite3_bind_*() ** interfaces. **
  3. Run the SQL by calling [sqlite3_step()] one or more times. **
  4. Reset the prepared statement using [sqlite3_reset()] then go back ** to step 2. Do this zero or more times. **
  5. Destroy the object using [sqlite3_finalize()]. **
*/ typedef struct sqlite3_stmt sqlite3_stmt; /* ** CAPI3REF: Run-time Limits ** METHOD: sqlite3 ** ** ^(This interface allows the size of various constructs to be limited ** on a connection by connection basis. The first parameter is the ** [database connection] whose limit is to be set or queried. The ** second parameter is one of the [limit categories] that define a ** class of constructs to be size limited. The third parameter is the ** new limit for that construct.)^ ** ** ^If the new limit is a negative number, the limit is unchanged. ** ^(For each limit category SQLITE_LIMIT_NAME there is a ** [limits | hard upper bound] ** set at compile-time by a C preprocessor macro called ** [limits | SQLITE_MAX_NAME]. ** (The "_LIMIT_" in the name is changed to "_MAX_".))^ ** ^Attempts to increase a limit above its hard upper bound are ** silently truncated to the hard upper bound. ** ** ^Regardless of whether or not the limit was changed, the ** [sqlite3_limit()] interface returns the prior value of the limit. ** ^Hence, to find the current value of a limit without changing it, ** simply invoke this interface with the third parameter set to -1. ** ** Run-time limits are intended for use in applications that manage ** both their own internal database and also databases that are controlled ** by untrusted external sources. An example application might be a ** web browser that has its own databases for storing history and ** separate databases controlled by JavaScript applications downloaded ** off the Internet. The internal databases can be given the ** large, default limits. Databases managed by external sources can ** be given much smaller limits designed to prevent a denial of service ** attack. Developers might also want to use the [sqlite3_set_authorizer()] ** interface to further control untrusted SQL. The size of the database ** created by an untrusted script can be contained using the ** [max_page_count] [PRAGMA]. ** ** New run-time limit categories may be added in future releases. */ SQLITE_API int sqlite3_limit(sqlite3*, int id, int newVal); /* ** CAPI3REF: Run-Time Limit Categories ** KEYWORDS: {limit category} {*limit categories} ** ** These constants define various performance limits ** that can be lowered at run-time using [sqlite3_limit()]. ** The synopsis of the meanings of the various limits is shown below. ** Additional information is available at [limits | Limits in SQLite]. ** **
** [[SQLITE_LIMIT_LENGTH]] ^(
SQLITE_LIMIT_LENGTH
**
The maximum size of any string or BLOB or table row, in bytes.
)^ ** ** [[SQLITE_LIMIT_SQL_LENGTH]] ^(
SQLITE_LIMIT_SQL_LENGTH
**
The maximum length of an SQL statement, in bytes.
)^ ** ** [[SQLITE_LIMIT_COLUMN]] ^(
SQLITE_LIMIT_COLUMN
**
The maximum number of columns in a table definition or in the ** result set of a [SELECT] or the maximum number of columns in an index ** or in an ORDER BY or GROUP BY clause.
)^ ** ** [[SQLITE_LIMIT_EXPR_DEPTH]] ^(
SQLITE_LIMIT_EXPR_DEPTH
**
The maximum depth of the parse tree on any expression.
)^ ** ** [[SQLITE_LIMIT_COMPOUND_SELECT]] ^(
SQLITE_LIMIT_COMPOUND_SELECT
**
The maximum number of terms in a compound SELECT statement.
)^ ** ** [[SQLITE_LIMIT_VDBE_OP]] ^(
SQLITE_LIMIT_VDBE_OP
**
The maximum number of instructions in a virtual machine program ** used to implement an SQL statement. This limit is not currently ** enforced, though that might be added in some future release of ** SQLite.
)^ ** ** [[SQLITE_LIMIT_FUNCTION_ARG]] ^(
SQLITE_LIMIT_FUNCTION_ARG
**
The maximum number of arguments on a function.
)^ ** ** [[SQLITE_LIMIT_ATTACHED]] ^(
SQLITE_LIMIT_ATTACHED
**
The maximum number of [ATTACH | attached databases].)^
** ** [[SQLITE_LIMIT_LIKE_PATTERN_LENGTH]] ** ^(
SQLITE_LIMIT_LIKE_PATTERN_LENGTH
**
The maximum length of the pattern argument to the [LIKE] or ** [GLOB] operators.
)^ ** ** [[SQLITE_LIMIT_VARIABLE_NUMBER]] ** ^(
SQLITE_LIMIT_VARIABLE_NUMBER
**
The maximum index number of any [parameter] in an SQL statement.)^ ** ** [[SQLITE_LIMIT_TRIGGER_DEPTH]] ^(
SQLITE_LIMIT_TRIGGER_DEPTH
**
The maximum depth of recursion for triggers.
)^ ** ** [[SQLITE_LIMIT_WORKER_THREADS]] ^(
SQLITE_LIMIT_WORKER_THREADS
**
The maximum number of auxiliary worker threads that a single ** [prepared statement] may start.
)^ **
*/ #define SQLITE_LIMIT_LENGTH 0 #define SQLITE_LIMIT_SQL_LENGTH 1 #define SQLITE_LIMIT_COLUMN 2 #define SQLITE_LIMIT_EXPR_DEPTH 3 #define SQLITE_LIMIT_COMPOUND_SELECT 4 #define SQLITE_LIMIT_VDBE_OP 5 #define SQLITE_LIMIT_FUNCTION_ARG 6 #define SQLITE_LIMIT_ATTACHED 7 #define SQLITE_LIMIT_LIKE_PATTERN_LENGTH 8 #define SQLITE_LIMIT_VARIABLE_NUMBER 9 #define SQLITE_LIMIT_TRIGGER_DEPTH 10 #define SQLITE_LIMIT_WORKER_THREADS 11 /* ** CAPI3REF: Compiling An SQL Statement ** KEYWORDS: {SQL statement compiler} ** METHOD: sqlite3 ** CONSTRUCTOR: sqlite3_stmt ** ** To execute an SQL query, it must first be compiled into a byte-code ** program using one of these routines. ** ** The first argument, "db", is a [database connection] obtained from a ** prior successful call to [sqlite3_open()], [sqlite3_open_v2()] or ** [sqlite3_open16()]. The database connection must not have been closed. ** ** The second argument, "zSql", is the statement to be compiled, encoded ** as either UTF-8 or UTF-16. The sqlite3_prepare() and sqlite3_prepare_v2() ** interfaces use UTF-8, and sqlite3_prepare16() and sqlite3_prepare16_v2() ** use UTF-16. ** ** ^If the nByte argument is negative, then zSql is read up to the ** first zero terminator. ^If nByte is positive, then it is the ** number of bytes read from zSql. ^If nByte is zero, then no prepared ** statement is generated. ** If the caller knows that the supplied string is nul-terminated, then ** there is a small performance advantage to passing an nByte parameter that ** is the number of bytes in the input string including ** the nul-terminator. ** ** ^If pzTail is not NULL then *pzTail is made to point to the first byte ** past the end of the first SQL statement in zSql. These routines only ** compile the first statement in zSql, so *pzTail is left pointing to ** what remains uncompiled. ** ** ^*ppStmt is left pointing to a compiled [prepared statement] that can be ** executed using [sqlite3_step()]. ^If there is an error, *ppStmt is set ** to NULL. ^If the input text contains no SQL (if the input is an empty ** string or a comment) then *ppStmt is set to NULL. ** The calling procedure is responsible for deleting the compiled ** SQL statement using [sqlite3_finalize()] after it has finished with it. ** ppStmt may not be NULL. ** ** ^On success, the sqlite3_prepare() family of routines return [SQLITE_OK]; ** otherwise an [error code] is returned. ** ** The sqlite3_prepare_v2() and sqlite3_prepare16_v2() interfaces are ** recommended for all new programs. The two older interfaces are retained ** for backwards compatibility, but their use is discouraged. ** ^In the "v2" interfaces, the prepared statement ** that is returned (the [sqlite3_stmt] object) contains a copy of the ** original SQL text. This causes the [sqlite3_step()] interface to ** behave differently in three ways: ** **
    **
  1. ** ^If the database schema changes, instead of returning [SQLITE_SCHEMA] as it ** always used to do, [sqlite3_step()] will automatically recompile the SQL ** statement and try to run it again. As many as [SQLITE_MAX_SCHEMA_RETRY] ** retries will occur before sqlite3_step() gives up and returns an error. **
  2. ** **
  3. ** ^When an error occurs, [sqlite3_step()] will return one of the detailed ** [error codes] or [extended error codes]. ^The legacy behavior was that ** [sqlite3_step()] would only return a generic [SQLITE_ERROR] result code ** and the application would have to make a second call to [sqlite3_reset()] ** in order to find the underlying cause of the problem. With the "v2" prepare ** interfaces, the underlying reason for the error is returned immediately. **
  4. ** **
  5. ** ^If the specific value bound to [parameter | host parameter] in the ** WHERE clause might influence the choice of query plan for a statement, ** then the statement will be automatically recompiled, as if there had been ** a schema change, on the first [sqlite3_step()] call following any change ** to the [sqlite3_bind_text | bindings] of that [parameter]. ** ^The specific value of WHERE-clause [parameter] might influence the ** choice of query plan if the parameter is the left-hand side of a [LIKE] ** or [GLOB] operator or if the parameter is compared to an indexed column ** and the [SQLITE_ENABLE_STAT3] compile-time option is enabled. **
  6. **
*/ SQLITE_API int sqlite3_prepare( sqlite3 *db, /* Database handle */ const char *zSql, /* SQL statement, UTF-8 encoded */ int nByte, /* Maximum length of zSql in bytes. */ sqlite3_stmt **ppStmt, /* OUT: Statement handle */ const char **pzTail /* OUT: Pointer to unused portion of zSql */ ); SQLITE_API int sqlite3_prepare_v2( sqlite3 *db, /* Database handle */ const char *zSql, /* SQL statement, UTF-8 encoded */ int nByte, /* Maximum length of zSql in bytes. */ sqlite3_stmt **ppStmt, /* OUT: Statement handle */ const char **pzTail /* OUT: Pointer to unused portion of zSql */ ); SQLITE_API int sqlite3_prepare16( sqlite3 *db, /* Database handle */ const void *zSql, /* SQL statement, UTF-16 encoded */ int nByte, /* Maximum length of zSql in bytes. */ sqlite3_stmt **ppStmt, /* OUT: Statement handle */ const void **pzTail /* OUT: Pointer to unused portion of zSql */ ); SQLITE_API int sqlite3_prepare16_v2( sqlite3 *db, /* Database handle */ const void *zSql, /* SQL statement, UTF-16 encoded */ int nByte, /* Maximum length of zSql in bytes. */ sqlite3_stmt **ppStmt, /* OUT: Statement handle */ const void **pzTail /* OUT: Pointer to unused portion of zSql */ ); /* ** CAPI3REF: Retrieving Statement SQL ** METHOD: sqlite3_stmt ** ** ^The sqlite3_sql(P) interface returns a pointer to a copy of the UTF-8 ** SQL text used to create [prepared statement] P if P was ** created by either [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()]. ** ^The sqlite3_expanded_sql(P) interface returns a pointer to a UTF-8 ** string containing the SQL text of prepared statement P with ** [bound parameters] expanded. ** ** ^(For example, if a prepared statement is created using the SQL ** text "SELECT $abc,:xyz" and if parameter $abc is bound to integer 2345 ** and parameter :xyz is unbound, then sqlite3_sql() will return ** the original string, "SELECT $abc,:xyz" but sqlite3_expanded_sql() ** will return "SELECT 2345,NULL".)^ ** ** ^The sqlite3_expanded_sql() interface returns NULL if insufficient memory ** is available to hold the result, or if the result would exceed the ** the maximum string length determined by the [SQLITE_LIMIT_LENGTH]. ** ** ^The [SQLITE_TRACE_SIZE_LIMIT] compile-time option limits the size of ** bound parameter expansions. ^The [SQLITE_OMIT_TRACE] compile-time ** option causes sqlite3_expanded_sql() to always return NULL. ** ** ^The string returned by sqlite3_sql(P) is managed by SQLite and is ** automatically freed when the prepared statement is finalized. ** ^The string returned by sqlite3_expanded_sql(P), on the other hand, ** is obtained from [sqlite3_malloc()] and must be free by the application ** by passing it to [sqlite3_free()]. */ SQLITE_API const char *sqlite3_sql(sqlite3_stmt *pStmt); SQLITE_API char *sqlite3_expanded_sql(sqlite3_stmt *pStmt); /* ** CAPI3REF: Determine If An SQL Statement Writes The Database ** METHOD: sqlite3_stmt ** ** ^The sqlite3_stmt_readonly(X) interface returns true (non-zero) if ** and only if the [prepared statement] X makes no direct changes to ** the content of the database file. ** ** Note that [application-defined SQL functions] or ** [virtual tables] might change the database indirectly as a side effect. ** ^(For example, if an application defines a function "eval()" that ** calls [sqlite3_exec()], then the following SQL statement would ** change the database file through side-effects: ** **
**    SELECT eval('DELETE FROM t1') FROM t2;
** 
** ** But because the [SELECT] statement does not change the database file ** directly, sqlite3_stmt_readonly() would still return true.)^ ** ** ^Transaction control statements such as [BEGIN], [COMMIT], [ROLLBACK], ** [SAVEPOINT], and [RELEASE] cause sqlite3_stmt_readonly() to return true, ** since the statements themselves do not actually modify the database but ** rather they control the timing of when other statements modify the ** database. ^The [ATTACH] and [DETACH] statements also cause ** sqlite3_stmt_readonly() to return true since, while those statements ** change the configuration of a database connection, they do not make ** changes to the content of the database files on disk. */ SQLITE_API int sqlite3_stmt_readonly(sqlite3_stmt *pStmt); /* ** CAPI3REF: Determine If A Prepared Statement Has Been Reset ** METHOD: sqlite3_stmt ** ** ^The sqlite3_stmt_busy(S) interface returns true (non-zero) if the ** [prepared statement] S has been stepped at least once using ** [sqlite3_step(S)] but has neither run to completion (returned ** [SQLITE_DONE] from [sqlite3_step(S)]) nor ** been reset using [sqlite3_reset(S)]. ^The sqlite3_stmt_busy(S) ** interface returns false if S is a NULL pointer. If S is not a ** NULL pointer and is not a pointer to a valid [prepared statement] ** object, then the behavior is undefined and probably undesirable. ** ** This interface can be used in combination [sqlite3_next_stmt()] ** to locate all prepared statements associated with a database ** connection that are in need of being reset. This can be used, ** for example, in diagnostic routines to search for prepared ** statements that are holding a transaction open. */ SQLITE_API int sqlite3_stmt_busy(sqlite3_stmt*); /* ** CAPI3REF: Dynamically Typed Value Object ** KEYWORDS: {protected sqlite3_value} {unprotected sqlite3_value} ** ** SQLite uses the sqlite3_value object to represent all values ** that can be stored in a database table. SQLite uses dynamic typing ** for the values it stores. ^Values stored in sqlite3_value objects ** can be integers, floating point values, strings, BLOBs, or NULL. ** ** An sqlite3_value object may be either "protected" or "unprotected". ** Some interfaces require a protected sqlite3_value. Other interfaces ** will accept either a protected or an unprotected sqlite3_value. ** Every interface that accepts sqlite3_value arguments specifies ** whether or not it requires a protected sqlite3_value. The ** [sqlite3_value_dup()] interface can be used to construct a new ** protected sqlite3_value from an unprotected sqlite3_value. ** ** The terms "protected" and "unprotected" refer to whether or not ** a mutex is held. An internal mutex is held for a protected ** sqlite3_value object but no mutex is held for an unprotected ** sqlite3_value object. If SQLite is compiled to be single-threaded ** (with [SQLITE_THREADSAFE=0] and with [sqlite3_threadsafe()] returning 0) ** or if SQLite is run in one of reduced mutex modes ** [SQLITE_CONFIG_SINGLETHREAD] or [SQLITE_CONFIG_MULTITHREAD] ** then there is no distinction between protected and unprotected ** sqlite3_value objects and they can be used interchangeably. However, ** for maximum code portability it is recommended that applications ** still make the distinction between protected and unprotected ** sqlite3_value objects even when not strictly required. ** ** ^The sqlite3_value objects that are passed as parameters into the ** implementation of [application-defined SQL functions] are protected. ** ^The sqlite3_value object returned by ** [sqlite3_column_value()] is unprotected. ** Unprotected sqlite3_value objects may only be used with ** [sqlite3_result_value()] and [sqlite3_bind_value()]. ** The [sqlite3_value_blob | sqlite3_value_type()] family of ** interfaces require protected sqlite3_value objects. */ typedef struct Mem sqlite3_value; /* ** CAPI3REF: SQL Function Context Object ** ** The context in which an SQL function executes is stored in an ** sqlite3_context object. ^A pointer to an sqlite3_context object ** is always first parameter to [application-defined SQL functions]. ** The application-defined SQL function implementation will pass this ** pointer through into calls to [sqlite3_result_int | sqlite3_result()], ** [sqlite3_aggregate_context()], [sqlite3_user_data()], ** [sqlite3_context_db_handle()], [sqlite3_get_auxdata()], ** and/or [sqlite3_set_auxdata()]. */ typedef struct sqlite3_context sqlite3_context; /* ** CAPI3REF: Binding Values To Prepared Statements ** KEYWORDS: {host parameter} {host parameters} {host parameter name} ** KEYWORDS: {SQL parameter} {SQL parameters} {parameter binding} ** METHOD: sqlite3_stmt ** ** ^(In the SQL statement text input to [sqlite3_prepare_v2()] and its variants, ** literals may be replaced by a [parameter] that matches one of following ** templates: ** **
    **
  • ? **
  • ?NNN **
  • :VVV **
  • @VVV **
  • $VVV **
** ** In the templates above, NNN represents an integer literal, ** and VVV represents an alphanumeric identifier.)^ ^The values of these ** parameters (also called "host parameter names" or "SQL parameters") ** can be set using the sqlite3_bind_*() routines defined here. ** ** ^The first argument to the sqlite3_bind_*() routines is always ** a pointer to the [sqlite3_stmt] object returned from ** [sqlite3_prepare_v2()] or its variants. ** ** ^The second argument is the index of the SQL parameter to be set. ** ^The leftmost SQL parameter has an index of 1. ^When the same named ** SQL parameter is used more than once, second and subsequent ** occurrences have the same index as the first occurrence. ** ^The index for named parameters can be looked up using the ** [sqlite3_bind_parameter_index()] API if desired. ^The index ** for "?NNN" parameters is the value of NNN. ** ^The NNN value must be between 1 and the [sqlite3_limit()] ** parameter [SQLITE_LIMIT_VARIABLE_NUMBER] (default value: 999). ** ** ^The third argument is the value to bind to the parameter. ** ^If the third parameter to sqlite3_bind_text() or sqlite3_bind_text16() ** or sqlite3_bind_blob() is a NULL pointer then the fourth parameter ** is ignored and the end result is the same as sqlite3_bind_null(). ** ** ^(In those routines that have a fourth argument, its value is the ** number of bytes in the parameter. To be clear: the value is the ** number of bytes in the value, not the number of characters.)^ ** ^If the fourth parameter to sqlite3_bind_text() or sqlite3_bind_text16() ** is negative, then the length of the string is ** the number of bytes up to the first zero terminator. ** If the fourth parameter to sqlite3_bind_blob() is negative, then ** the behavior is undefined. ** If a non-negative fourth parameter is provided to sqlite3_bind_text() ** or sqlite3_bind_text16() or sqlite3_bind_text64() then ** that parameter must be the byte offset ** where the NUL terminator would occur assuming the string were NUL ** terminated. If any NUL characters occur at byte offsets less than ** the value of the fourth parameter then the resulting string value will ** contain embedded NULs. The result of expressions involving strings ** with embedded NULs is undefined. ** ** ^The fifth argument to the BLOB and string binding interfaces ** is a destructor used to dispose of the BLOB or ** string after SQLite has finished with it. ^The destructor is called ** to dispose of the BLOB or string even if the call to bind API fails. ** ^If the fifth argument is ** the special value [SQLITE_STATIC], then SQLite assumes that the ** information is in static, unmanaged space and does not need to be freed. ** ^If the fifth argument has the value [SQLITE_TRANSIENT], then ** SQLite makes its own private copy of the data immediately, before ** the sqlite3_bind_*() routine returns. ** ** ^The sixth argument to sqlite3_bind_text64() must be one of ** [SQLITE_UTF8], [SQLITE_UTF16], [SQLITE_UTF16BE], or [SQLITE_UTF16LE] ** to specify the encoding of the text in the third parameter. If ** the sixth argument to sqlite3_bind_text64() is not one of the ** allowed values shown above, or if the text encoding is different ** from the encoding specified by the sixth parameter, then the behavior ** is undefined. ** ** ^The sqlite3_bind_zeroblob() routine binds a BLOB of length N that ** is filled with zeroes. ^A zeroblob uses a fixed amount of memory ** (just an integer to hold its size) while it is being processed. ** Zeroblobs are intended to serve as placeholders for BLOBs whose ** content is later written using ** [sqlite3_blob_open | incremental BLOB I/O] routines. ** ^A negative value for the zeroblob results in a zero-length BLOB. ** ** ^If any of the sqlite3_bind_*() routines are called with a NULL pointer ** for the [prepared statement] or with a prepared statement for which ** [sqlite3_step()] has been called more recently than [sqlite3_reset()], ** then the call will return [SQLITE_MISUSE]. If any sqlite3_bind_() ** routine is passed a [prepared statement] that has been finalized, the ** result is undefined and probably harmful. ** ** ^Bindings are not cleared by the [sqlite3_reset()] routine. ** ^Unbound parameters are interpreted as NULL. ** ** ^The sqlite3_bind_* routines return [SQLITE_OK] on success or an ** [error code] if anything goes wrong. ** ^[SQLITE_TOOBIG] might be returned if the size of a string or BLOB ** exceeds limits imposed by [sqlite3_limit]([SQLITE_LIMIT_LENGTH]) or ** [SQLITE_MAX_LENGTH]. ** ^[SQLITE_RANGE] is returned if the parameter ** index is out of range. ^[SQLITE_NOMEM] is returned if malloc() fails. ** ** See also: [sqlite3_bind_parameter_count()], ** [sqlite3_bind_parameter_name()], and [sqlite3_bind_parameter_index()]. */ SQLITE_API int sqlite3_bind_blob(sqlite3_stmt*, int, const void*, int n, void(*)(void*)); SQLITE_API int sqlite3_bind_blob64(sqlite3_stmt*, int, const void*, sqlite3_uint64, void(*)(void*)); SQLITE_API int sqlite3_bind_double(sqlite3_stmt*, int, double); SQLITE_API int sqlite3_bind_int(sqlite3_stmt*, int, int); SQLITE_API int sqlite3_bind_int64(sqlite3_stmt*, int, sqlite3_int64); SQLITE_API int sqlite3_bind_null(sqlite3_stmt*, int); SQLITE_API int sqlite3_bind_text(sqlite3_stmt*,int,const char*,int,void(*)(void*)); SQLITE_API int sqlite3_bind_text16(sqlite3_stmt*, int, const void*, int, void(*)(void*)); SQLITE_API int sqlite3_bind_text64(sqlite3_stmt*, int, const char*, sqlite3_uint64, void(*)(void*), unsigned char encoding); SQLITE_API int sqlite3_bind_value(sqlite3_stmt*, int, const sqlite3_value*); SQLITE_API int sqlite3_bind_zeroblob(sqlite3_stmt*, int, int n); SQLITE_API int sqlite3_bind_zeroblob64(sqlite3_stmt*, int, sqlite3_uint64); /* ** CAPI3REF: Number Of SQL Parameters ** METHOD: sqlite3_stmt ** ** ^This routine can be used to find the number of [SQL parameters] ** in a [prepared statement]. SQL parameters are tokens of the ** form "?", "?NNN", ":AAA", "$AAA", or "@AAA" that serve as ** placeholders for values that are [sqlite3_bind_blob | bound] ** to the parameters at a later time. ** ** ^(This routine actually returns the index of the largest (rightmost) ** parameter. For all forms except ?NNN, this will correspond to the ** number of unique parameters. If parameters of the ?NNN form are used, ** there may be gaps in the list.)^ ** ** See also: [sqlite3_bind_blob|sqlite3_bind()], ** [sqlite3_bind_parameter_name()], and ** [sqlite3_bind_parameter_index()]. */ SQLITE_API int sqlite3_bind_parameter_count(sqlite3_stmt*); /* ** CAPI3REF: Name Of A Host Parameter ** METHOD: sqlite3_stmt ** ** ^The sqlite3_bind_parameter_name(P,N) interface returns ** the name of the N-th [SQL parameter] in the [prepared statement] P. ** ^(SQL parameters of the form "?NNN" or ":AAA" or "@AAA" or "$AAA" ** have a name which is the string "?NNN" or ":AAA" or "@AAA" or "$AAA" ** respectively. ** In other words, the initial ":" or "$" or "@" or "?" ** is included as part of the name.)^ ** ^Parameters of the form "?" without a following integer have no name ** and are referred to as "nameless" or "anonymous parameters". ** ** ^The first host parameter has an index of 1, not 0. ** ** ^If the value N is out of range or if the N-th parameter is ** nameless, then NULL is returned. ^The returned string is ** always in UTF-8 encoding even if the named parameter was ** originally specified as UTF-16 in [sqlite3_prepare16()] or ** [sqlite3_prepare16_v2()]. ** ** See also: [sqlite3_bind_blob|sqlite3_bind()], ** [sqlite3_bind_parameter_count()], and ** [sqlite3_bind_parameter_index()]. */ SQLITE_API const char *sqlite3_bind_parameter_name(sqlite3_stmt*, int); /* ** CAPI3REF: Index Of A Parameter With A Given Name ** METHOD: sqlite3_stmt ** ** ^Return the index of an SQL parameter given its name. ^The ** index value returned is suitable for use as the second ** parameter to [sqlite3_bind_blob|sqlite3_bind()]. ^A zero ** is returned if no matching parameter is found. ^The parameter ** name must be given in UTF-8 even if the original statement ** was prepared from UTF-16 text using [sqlite3_prepare16_v2()]. ** ** See also: [sqlite3_bind_blob|sqlite3_bind()], ** [sqlite3_bind_parameter_count()], and ** [sqlite3_bind_parameter_name()]. */ SQLITE_API int sqlite3_bind_parameter_index(sqlite3_stmt*, const char *zName); /* ** CAPI3REF: Reset All Bindings On A Prepared Statement ** METHOD: sqlite3_stmt ** ** ^Contrary to the intuition of many, [sqlite3_reset()] does not reset ** the [sqlite3_bind_blob | bindings] on a [prepared statement]. ** ^Use this routine to reset all host parameters to NULL. */ SQLITE_API int sqlite3_clear_bindings(sqlite3_stmt*); /* ** CAPI3REF: Number Of Columns In A Result Set ** METHOD: sqlite3_stmt ** ** ^Return the number of columns in the result set returned by the ** [prepared statement]. ^This routine returns 0 if pStmt is an SQL ** statement that does not return data (for example an [UPDATE]). ** ** See also: [sqlite3_data_count()] */ SQLITE_API int sqlite3_column_count(sqlite3_stmt *pStmt); /* ** CAPI3REF: Column Names In A Result Set ** METHOD: sqlite3_stmt ** ** ^These routines return the name assigned to a particular column ** in the result set of a [SELECT] statement. ^The sqlite3_column_name() ** interface returns a pointer to a zero-terminated UTF-8 string ** and sqlite3_column_name16() returns a pointer to a zero-terminated ** UTF-16 string. ^The first parameter is the [prepared statement] ** that implements the [SELECT] statement. ^The second parameter is the ** column number. ^The leftmost column is number 0. ** ** ^The returned string pointer is valid until either the [prepared statement] ** is destroyed by [sqlite3_finalize()] or until the statement is automatically ** reprepared by the first call to [sqlite3_step()] for a particular run ** or until the next call to ** sqlite3_column_name() or sqlite3_column_name16() on the same column. ** ** ^If sqlite3_malloc() fails during the processing of either routine ** (for example during a conversion from UTF-8 to UTF-16) then a ** NULL pointer is returned. ** ** ^The name of a result column is the value of the "AS" clause for ** that column, if there is an AS clause. If there is no AS clause ** then the name of the column is unspecified and may change from ** one release of SQLite to the next. */ SQLITE_API const char *sqlite3_column_name(sqlite3_stmt*, int N); SQLITE_API const void *sqlite3_column_name16(sqlite3_stmt*, int N); /* ** CAPI3REF: Source Of Data In A Query Result ** METHOD: sqlite3_stmt ** ** ^These routines provide a means to determine the database, table, and ** table column that is the origin of a particular result column in ** [SELECT] statement. ** ^The name of the database or table or column can be returned as ** either a UTF-8 or UTF-16 string. ^The _database_ routines return ** the database name, the _table_ routines return the table name, and ** the origin_ routines return the column name. ** ^The returned string is valid until the [prepared statement] is destroyed ** using [sqlite3_finalize()] or until the statement is automatically ** reprepared by the first call to [sqlite3_step()] for a particular run ** or until the same information is requested ** again in a different encoding. ** ** ^The names returned are the original un-aliased names of the ** database, table, and column. ** ** ^The first argument to these interfaces is a [prepared statement]. ** ^These functions return information about the Nth result column returned by ** the statement, where N is the second function argument. ** ^The left-most column is column 0 for these routines. ** ** ^If the Nth column returned by the statement is an expression or ** subquery and is not a column value, then all of these functions return ** NULL. ^These routine might also return NULL if a memory allocation error ** occurs. ^Otherwise, they return the name of the attached database, table, ** or column that query result column was extracted from. ** ** ^As with all other SQLite APIs, those whose names end with "16" return ** UTF-16 encoded strings and the other functions return UTF-8. ** ** ^These APIs are only available if the library was compiled with the ** [SQLITE_ENABLE_COLUMN_METADATA] C-preprocessor symbol. ** ** If two or more threads call one or more of these routines against the same ** prepared statement and column at the same time then the results are ** undefined. ** ** If two or more threads call one or more ** [sqlite3_column_database_name | column metadata interfaces] ** for the same [prepared statement] and result column ** at the same time then the results are undefined. */ SQLITE_API const char *sqlite3_column_database_name(sqlite3_stmt*,int); SQLITE_API const void *sqlite3_column_database_name16(sqlite3_stmt*,int); SQLITE_API const char *sqlite3_column_table_name(sqlite3_stmt*,int); SQLITE_API const void *sqlite3_column_table_name16(sqlite3_stmt*,int); SQLITE_API const char *sqlite3_column_origin_name(sqlite3_stmt*,int); SQLITE_API const void *sqlite3_column_origin_name16(sqlite3_stmt*,int); /* ** CAPI3REF: Declared Datatype Of A Query Result ** METHOD: sqlite3_stmt ** ** ^(The first parameter is a [prepared statement]. ** If this statement is a [SELECT] statement and the Nth column of the ** returned result set of that [SELECT] is a table column (not an ** expression or subquery) then the declared type of the table ** column is returned.)^ ^If the Nth column of the result set is an ** expression or subquery, then a NULL pointer is returned. ** ^The returned string is always UTF-8 encoded. ** ** ^(For example, given the database schema: ** ** CREATE TABLE t1(c1 VARIANT); ** ** and the following statement to be compiled: ** ** SELECT c1 + 1, c1 FROM t1; ** ** this routine would return the string "VARIANT" for the second result ** column (i==1), and a NULL pointer for the first result column (i==0).)^ ** ** ^SQLite uses dynamic run-time typing. ^So just because a column ** is declared to contain a particular type does not mean that the ** data stored in that column is of the declared type. SQLite is ** strongly typed, but the typing is dynamic not static. ^Type ** is associated with individual values, not with the containers ** used to hold those values. */ SQLITE_API const char *sqlite3_column_decltype(sqlite3_stmt*,int); SQLITE_API const void *sqlite3_column_decltype16(sqlite3_stmt*,int); /* ** CAPI3REF: Evaluate An SQL Statement ** METHOD: sqlite3_stmt ** ** After a [prepared statement] has been prepared using either ** [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()] or one of the legacy ** interfaces [sqlite3_prepare()] or [sqlite3_prepare16()], this function ** must be called one or more times to evaluate the statement. ** ** The details of the behavior of the sqlite3_step() interface depend ** on whether the statement was prepared using the newer "v2" interface ** [sqlite3_prepare_v2()] and [sqlite3_prepare16_v2()] or the older legacy ** interface [sqlite3_prepare()] and [sqlite3_prepare16()]. The use of the ** new "v2" interface is recommended for new applications but the legacy ** interface will continue to be supported. ** ** ^In the legacy interface, the return value will be either [SQLITE_BUSY], ** [SQLITE_DONE], [SQLITE_ROW], [SQLITE_ERROR], or [SQLITE_MISUSE]. ** ^With the "v2" interface, any of the other [result codes] or ** [extended result codes] might be returned as well. ** ** ^[SQLITE_BUSY] means that the database engine was unable to acquire the ** database locks it needs to do its job. ^If the statement is a [COMMIT] ** or occurs outside of an explicit transaction, then you can retry the ** statement. If the statement is not a [COMMIT] and occurs within an ** explicit transaction then you should rollback the transaction before ** continuing. ** ** ^[SQLITE_DONE] means that the statement has finished executing ** successfully. sqlite3_step() should not be called again on this virtual ** machine without first calling [sqlite3_reset()] to reset the virtual ** machine back to its initial state. ** ** ^If the SQL statement being executed returns any data, then [SQLITE_ROW] ** is returned each time a new row of data is ready for processing by the ** caller. The values may be accessed using the [column access functions]. ** sqlite3_step() is called again to retrieve the next row of data. ** ** ^[SQLITE_ERROR] means that a run-time error (such as a constraint ** violation) has occurred. sqlite3_step() should not be called again on ** the VM. More information may be found by calling [sqlite3_errmsg()]. ** ^With the legacy interface, a more specific error code (for example, ** [SQLITE_INTERRUPT], [SQLITE_SCHEMA], [SQLITE_CORRUPT], and so forth) ** can be obtained by calling [sqlite3_reset()] on the ** [prepared statement]. ^In the "v2" interface, ** the more specific error code is returned directly by sqlite3_step(). ** ** [SQLITE_MISUSE] means that the this routine was called inappropriately. ** Perhaps it was called on a [prepared statement] that has ** already been [sqlite3_finalize | finalized] or on one that had ** previously returned [SQLITE_ERROR] or [SQLITE_DONE]. Or it could ** be the case that the same database connection is being used by two or ** more threads at the same moment in time. ** ** For all versions of SQLite up to and including 3.6.23.1, a call to ** [sqlite3_reset()] was required after sqlite3_step() returned anything ** other than [SQLITE_ROW] before any subsequent invocation of ** sqlite3_step(). Failure to reset the prepared statement using ** [sqlite3_reset()] would result in an [SQLITE_MISUSE] return from ** sqlite3_step(). But after [version 3.6.23.1] ([dateof:3.6.23.1], ** sqlite3_step() began ** calling [sqlite3_reset()] automatically in this circumstance rather ** than returning [SQLITE_MISUSE]. This is not considered a compatibility ** break because any application that ever receives an SQLITE_MISUSE error ** is broken by definition. The [SQLITE_OMIT_AUTORESET] compile-time option ** can be used to restore the legacy behavior. ** ** Goofy Interface Alert: In the legacy interface, the sqlite3_step() ** API always returns a generic error code, [SQLITE_ERROR], following any ** error other than [SQLITE_BUSY] and [SQLITE_MISUSE]. You must call ** [sqlite3_reset()] or [sqlite3_finalize()] in order to find one of the ** specific [error codes] that better describes the error. ** We admit that this is a goofy design. The problem has been fixed ** with the "v2" interface. If you prepare all of your SQL statements ** using either [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()] instead ** of the legacy [sqlite3_prepare()] and [sqlite3_prepare16()] interfaces, ** then the more specific [error codes] are returned directly ** by sqlite3_step(). The use of the "v2" interface is recommended. */ SQLITE_API int sqlite3_step(sqlite3_stmt*); /* ** CAPI3REF: Number of columns in a result set ** METHOD: sqlite3_stmt ** ** ^The sqlite3_data_count(P) interface returns the number of columns in the ** current row of the result set of [prepared statement] P. ** ^If prepared statement P does not have results ready to return ** (via calls to the [sqlite3_column_int | sqlite3_column_*()] of ** interfaces) then sqlite3_data_count(P) returns 0. ** ^The sqlite3_data_count(P) routine also returns 0 if P is a NULL pointer. ** ^The sqlite3_data_count(P) routine returns 0 if the previous call to ** [sqlite3_step](P) returned [SQLITE_DONE]. ^The sqlite3_data_count(P) ** will return non-zero if previous call to [sqlite3_step](P) returned ** [SQLITE_ROW], except in the case of the [PRAGMA incremental_vacuum] ** where it always returns zero since each step of that multi-step ** pragma returns 0 columns of data. ** ** See also: [sqlite3_column_count()] */ SQLITE_API int sqlite3_data_count(sqlite3_stmt *pStmt); /* ** CAPI3REF: Fundamental Datatypes ** KEYWORDS: SQLITE_TEXT ** ** ^(Every value in SQLite has one of five fundamental datatypes: ** **
    **
  • 64-bit signed integer **
  • 64-bit IEEE floating point number **
  • string **
  • BLOB **
  • NULL **
)^ ** ** These constants are codes for each of those types. ** ** Note that the SQLITE_TEXT constant was also used in SQLite version 2 ** for a completely different meaning. Software that links against both ** SQLite version 2 and SQLite version 3 should use SQLITE3_TEXT, not ** SQLITE_TEXT. */ #define SQLITE_INTEGER 1 #define SQLITE_FLOAT 2 #define SQLITE_BLOB 4 #define SQLITE_NULL 5 #ifdef SQLITE_TEXT # undef SQLITE_TEXT #else # define SQLITE_TEXT 3 #endif #define SQLITE3_TEXT 3 /* ** CAPI3REF: Result Values From A Query ** KEYWORDS: {column access functions} ** METHOD: sqlite3_stmt ** ** ^These routines return information about a single column of the current ** result row of a query. ^In every case the first argument is a pointer ** to the [prepared statement] that is being evaluated (the [sqlite3_stmt*] ** that was returned from [sqlite3_prepare_v2()] or one of its variants) ** and the second argument is the index of the column for which information ** should be returned. ^The leftmost column of the result set has the index 0. ** ^The number of columns in the result can be determined using ** [sqlite3_column_count()]. ** ** If the SQL statement does not currently point to a valid row, or if the ** column index is out of range, the result is undefined. ** These routines may only be called when the most recent call to ** [sqlite3_step()] has returned [SQLITE_ROW] and neither ** [sqlite3_reset()] nor [sqlite3_finalize()] have been called subsequently. ** If any of these routines are called after [sqlite3_reset()] or ** [sqlite3_finalize()] or after [sqlite3_step()] has returned ** something other than [SQLITE_ROW], the results are undefined. ** If [sqlite3_step()] or [sqlite3_reset()] or [sqlite3_finalize()] ** are called from a different thread while any of these routines ** are pending, then the results are undefined. ** ** ^The sqlite3_column_type() routine returns the ** [SQLITE_INTEGER | datatype code] for the initial data type ** of the result column. ^The returned value is one of [SQLITE_INTEGER], ** [SQLITE_FLOAT], [SQLITE_TEXT], [SQLITE_BLOB], or [SQLITE_NULL]. The value ** returned by sqlite3_column_type() is only meaningful if no type ** conversions have occurred as described below. After a type conversion, ** the value returned by sqlite3_column_type() is undefined. Future ** versions of SQLite may change the behavior of sqlite3_column_type() ** following a type conversion. ** ** ^If the result is a BLOB or UTF-8 string then the sqlite3_column_bytes() ** routine returns the number of bytes in that BLOB or string. ** ^If the result is a UTF-16 string, then sqlite3_column_bytes() converts ** the string to UTF-8 and then returns the number of bytes. ** ^If the result is a numeric value then sqlite3_column_bytes() uses ** [sqlite3_snprintf()] to convert that value to a UTF-8 string and returns ** the number of bytes in that string. ** ^If the result is NULL, then sqlite3_column_bytes() returns zero. ** ** ^If the result is a BLOB or UTF-16 string then the sqlite3_column_bytes16() ** routine returns the number of bytes in that BLOB or string. ** ^If the result is a UTF-8 string, then sqlite3_column_bytes16() converts ** the string to UTF-16 and then returns the number of bytes. ** ^If the result is a numeric value then sqlite3_column_bytes16() uses ** [sqlite3_snprintf()] to convert that value to a UTF-16 string and returns ** the number of bytes in that string. ** ^If the result is NULL, then sqlite3_column_bytes16() returns zero. ** ** ^The values returned by [sqlite3_column_bytes()] and ** [sqlite3_column_bytes16()] do not include the zero terminators at the end ** of the string. ^For clarity: the values returned by ** [sqlite3_column_bytes()] and [sqlite3_column_bytes16()] are the number of ** bytes in the string, not the number of characters. ** ** ^Strings returned by sqlite3_column_text() and sqlite3_column_text16(), ** even empty strings, are always zero-terminated. ^The return ** value from sqlite3_column_blob() for a zero-length BLOB is a NULL pointer. ** ** Warning: ^The object returned by [sqlite3_column_value()] is an ** [unprotected sqlite3_value] object. In a multithreaded environment, ** an unprotected sqlite3_value object may only be used safely with ** [sqlite3_bind_value()] and [sqlite3_result_value()]. ** If the [unprotected sqlite3_value] object returned by ** [sqlite3_column_value()] is used in any other way, including calls ** to routines like [sqlite3_value_int()], [sqlite3_value_text()], ** or [sqlite3_value_bytes()], the behavior is not threadsafe. ** ** These routines attempt to convert the value where appropriate. ^For ** example, if the internal representation is FLOAT and a text result ** is requested, [sqlite3_snprintf()] is used internally to perform the ** conversion automatically. ^(The following table details the conversions ** that are applied: ** **
** **
Internal
Type
Requested
Type
Conversion ** **
NULL INTEGER Result is 0 **
NULL FLOAT Result is 0.0 **
NULL TEXT Result is a NULL pointer **
NULL BLOB Result is a NULL pointer **
INTEGER FLOAT Convert from integer to float **
INTEGER TEXT ASCII rendering of the integer **
INTEGER BLOB Same as INTEGER->TEXT **
FLOAT INTEGER [CAST] to INTEGER **
FLOAT TEXT ASCII rendering of the float **
FLOAT BLOB [CAST] to BLOB **
TEXT INTEGER [CAST] to INTEGER **
TEXT FLOAT [CAST] to REAL **
TEXT BLOB No change **
BLOB INTEGER [CAST] to INTEGER **
BLOB FLOAT [CAST] to REAL **
BLOB TEXT Add a zero terminator if needed **
**
)^ ** ** Note that when type conversions occur, pointers returned by prior ** calls to sqlite3_column_blob(), sqlite3_column_text(), and/or ** sqlite3_column_text16() may be invalidated. ** Type conversions and pointer invalidations might occur ** in the following cases: ** **
    **
  • The initial content is a BLOB and sqlite3_column_text() or ** sqlite3_column_text16() is called. A zero-terminator might ** need to be added to the string.
  • **
  • The initial content is UTF-8 text and sqlite3_column_bytes16() or ** sqlite3_column_text16() is called. The content must be converted ** to UTF-16.
  • **
  • The initial content is UTF-16 text and sqlite3_column_bytes() or ** sqlite3_column_text() is called. The content must be converted ** to UTF-8.
  • **
** ** ^Conversions between UTF-16be and UTF-16le are always done in place and do ** not invalidate a prior pointer, though of course the content of the buffer ** that the prior pointer references will have been modified. Other kinds ** of conversion are done in place when it is possible, but sometimes they ** are not possible and in those cases prior pointers are invalidated. ** ** The safest policy is to invoke these routines ** in one of the following ways: ** **
    **
  • sqlite3_column_text() followed by sqlite3_column_bytes()
  • **
  • sqlite3_column_blob() followed by sqlite3_column_bytes()
  • **
  • sqlite3_column_text16() followed by sqlite3_column_bytes16()
  • **
** ** In other words, you should call sqlite3_column_text(), ** sqlite3_column_blob(), or sqlite3_column_text16() first to force the result ** into the desired format, then invoke sqlite3_column_bytes() or ** sqlite3_column_bytes16() to find the size of the result. Do not mix calls ** to sqlite3_column_text() or sqlite3_column_blob() with calls to ** sqlite3_column_bytes16(), and do not mix calls to sqlite3_column_text16() ** with calls to sqlite3_column_bytes(). ** ** ^The pointers returned are valid until a type conversion occurs as ** described above, or until [sqlite3_step()] or [sqlite3_reset()] or ** [sqlite3_finalize()] is called. ^The memory space used to hold strings ** and BLOBs is freed automatically. Do not pass the pointers returned ** from [sqlite3_column_blob()], [sqlite3_column_text()], etc. into ** [sqlite3_free()]. ** ** ^(If a memory allocation error occurs during the evaluation of any ** of these routines, a default value is returned. The default value ** is either the integer 0, the floating point number 0.0, or a NULL ** pointer. Subsequent calls to [sqlite3_errcode()] will return ** [SQLITE_NOMEM].)^ */ SQLITE_API const void *sqlite3_column_blob(sqlite3_stmt*, int iCol); SQLITE_API int sqlite3_column_bytes(sqlite3_stmt*, int iCol); SQLITE_API int sqlite3_column_bytes16(sqlite3_stmt*, int iCol); SQLITE_API double sqlite3_column_double(sqlite3_stmt*, int iCol); SQLITE_API int sqlite3_column_int(sqlite3_stmt*, int iCol); SQLITE_API sqlite3_int64 sqlite3_column_int64(sqlite3_stmt*, int iCol); SQLITE_API const unsigned char *sqlite3_column_text(sqlite3_stmt*, int iCol); SQLITE_API const void *sqlite3_column_text16(sqlite3_stmt*, int iCol); SQLITE_API int sqlite3_column_type(sqlite3_stmt*, int iCol); SQLITE_API sqlite3_value *sqlite3_column_value(sqlite3_stmt*, int iCol); /* ** CAPI3REF: Destroy A Prepared Statement Object ** DESTRUCTOR: sqlite3_stmt ** ** ^The sqlite3_finalize() function is called to delete a [prepared statement]. ** ^If the most recent evaluation of the statement encountered no errors ** or if the statement is never been evaluated, then sqlite3_finalize() returns ** SQLITE_OK. ^If the most recent evaluation of statement S failed, then ** sqlite3_finalize(S) returns the appropriate [error code] or ** [extended error code]. ** ** ^The sqlite3_finalize(S) routine can be called at any point during ** the life cycle of [prepared statement] S: ** before statement S is ever evaluated, after ** one or more calls to [sqlite3_reset()], or after any call ** to [sqlite3_step()] regardless of whether or not the statement has ** completed execution. ** ** ^Invoking sqlite3_finalize() on a NULL pointer is a harmless no-op. ** ** The application must finalize every [prepared statement] in order to avoid ** resource leaks. It is a grievous error for the application to try to use ** a prepared statement after it has been finalized. Any use of a prepared ** statement after it has been finalized can result in undefined and ** undesirable behavior such as segfaults and heap corruption. */ SQLITE_API int sqlite3_finalize(sqlite3_stmt *pStmt); /* ** CAPI3REF: Reset A Prepared Statement Object ** METHOD: sqlite3_stmt ** ** The sqlite3_reset() function is called to reset a [prepared statement] ** object back to its initial state, ready to be re-executed. ** ^Any SQL statement variables that had values bound to them using ** the [sqlite3_bind_blob | sqlite3_bind_*() API] retain their values. ** Use [sqlite3_clear_bindings()] to reset the bindings. ** ** ^The [sqlite3_reset(S)] interface resets the [prepared statement] S ** back to the beginning of its program. ** ** ^If the most recent call to [sqlite3_step(S)] for the ** [prepared statement] S returned [SQLITE_ROW] or [SQLITE_DONE], ** or if [sqlite3_step(S)] has never before been called on S, ** then [sqlite3_reset(S)] returns [SQLITE_OK]. ** ** ^If the most recent call to [sqlite3_step(S)] for the ** [prepared statement] S indicated an error, then ** [sqlite3_reset(S)] returns an appropriate [error code]. ** ** ^The [sqlite3_reset(S)] interface does not change the values ** of any [sqlite3_bind_blob|bindings] on the [prepared statement] S. */ SQLITE_API int sqlite3_reset(sqlite3_stmt *pStmt); /* ** CAPI3REF: Create Or Redefine SQL Functions ** KEYWORDS: {function creation routines} ** KEYWORDS: {application-defined SQL function} ** KEYWORDS: {application-defined SQL functions} ** METHOD: sqlite3 ** ** ^These functions (collectively known as "function creation routines") ** are used to add SQL functions or aggregates or to redefine the behavior ** of existing SQL functions or aggregates. The only differences between ** these routines are the text encoding expected for ** the second parameter (the name of the function being created) ** and the presence or absence of a destructor callback for ** the application data pointer. ** ** ^The first parameter is the [database connection] to which the SQL ** function is to be added. ^If an application uses more than one database ** connection then application-defined SQL functions must be added ** to each database connection separately. ** ** ^The second parameter is the name of the SQL function to be created or ** redefined. ^The length of the name is limited to 255 bytes in a UTF-8 ** representation, exclusive of the zero-terminator. ^Note that the name ** length limit is in UTF-8 bytes, not characters nor UTF-16 bytes. ** ^Any attempt to create a function with a longer name ** will result in [SQLITE_MISUSE] being returned. ** ** ^The third parameter (nArg) ** is the number of arguments that the SQL function or ** aggregate takes. ^If this parameter is -1, then the SQL function or ** aggregate may take any number of arguments between 0 and the limit ** set by [sqlite3_limit]([SQLITE_LIMIT_FUNCTION_ARG]). If the third ** parameter is less than -1 or greater than 127 then the behavior is ** undefined. ** ** ^The fourth parameter, eTextRep, specifies what ** [SQLITE_UTF8 | text encoding] this SQL function prefers for ** its parameters. The application should set this parameter to ** [SQLITE_UTF16LE] if the function implementation invokes ** [sqlite3_value_text16le()] on an input, or [SQLITE_UTF16BE] if the ** implementation invokes [sqlite3_value_text16be()] on an input, or ** [SQLITE_UTF16] if [sqlite3_value_text16()] is used, or [SQLITE_UTF8] ** otherwise. ^The same SQL function may be registered multiple times using ** different preferred text encodings, with different implementations for ** each encoding. ** ^When multiple implementations of the same function are available, SQLite ** will pick the one that involves the least amount of data conversion. ** ** ^The fourth parameter may optionally be ORed with [SQLITE_DETERMINISTIC] ** to signal that the function will always return the same result given ** the same inputs within a single SQL statement. Most SQL functions are ** deterministic. The built-in [random()] SQL function is an example of a ** function that is not deterministic. The SQLite query planner is able to ** perform additional optimizations on deterministic functions, so use ** of the [SQLITE_DETERMINISTIC] flag is recommended where possible. ** ** ^(The fifth parameter is an arbitrary pointer. The implementation of the ** function can gain access to this pointer using [sqlite3_user_data()].)^ ** ** ^The sixth, seventh and eighth parameters, xFunc, xStep and xFinal, are ** pointers to C-language functions that implement the SQL function or ** aggregate. ^A scalar SQL function requires an implementation of the xFunc ** callback only; NULL pointers must be passed as the xStep and xFinal ** parameters. ^An aggregate SQL function requires an implementation of xStep ** and xFinal and NULL pointer must be passed for xFunc. ^To delete an existing ** SQL function or aggregate, pass NULL pointers for all three function ** callbacks. ** ** ^(If the ninth parameter to sqlite3_create_function_v2() is not NULL, ** then it is destructor for the application data pointer. ** The destructor is invoked when the function is deleted, either by being ** overloaded or when the database connection closes.)^ ** ^The destructor is also invoked if the call to ** sqlite3_create_function_v2() fails. ** ^When the destructor callback of the tenth parameter is invoked, it ** is passed a single argument which is a copy of the application data ** pointer which was the fifth parameter to sqlite3_create_function_v2(). ** ** ^It is permitted to register multiple implementations of the same ** functions with the same name but with either differing numbers of ** arguments or differing preferred text encodings. ^SQLite will use ** the implementation that most closely matches the way in which the ** SQL function is used. ^A function implementation with a non-negative ** nArg parameter is a better match than a function implementation with ** a negative nArg. ^A function where the preferred text encoding ** matches the database encoding is a better ** match than a function where the encoding is different. ** ^A function where the encoding difference is between UTF16le and UTF16be ** is a closer match than a function where the encoding difference is ** between UTF8 and UTF16. ** ** ^Built-in functions may be overloaded by new application-defined functions. ** ** ^An application-defined function is permitted to call other ** SQLite interfaces. However, such calls must not ** close the database connection nor finalize or reset the prepared ** statement in which the function is running. */ SQLITE_API int sqlite3_create_function( sqlite3 *db, const char *zFunctionName, int nArg, int eTextRep, void *pApp, void (*xFunc)(sqlite3_context*,int,sqlite3_value**), void (*xStep)(sqlite3_context*,int,sqlite3_value**), void (*xFinal)(sqlite3_context*) ); SQLITE_API int sqlite3_create_function16( sqlite3 *db, const void *zFunctionName, int nArg, int eTextRep, void *pApp, void (*xFunc)(sqlite3_context*,int,sqlite3_value**), void (*xStep)(sqlite3_context*,int,sqlite3_value**), void (*xFinal)(sqlite3_context*) ); SQLITE_API int sqlite3_create_function_v2( sqlite3 *db, const char *zFunctionName, int nArg, int eTextRep, void *pApp, void (*xFunc)(sqlite3_context*,int,sqlite3_value**), void (*xStep)(sqlite3_context*,int,sqlite3_value**), void (*xFinal)(sqlite3_context*), void(*xDestroy)(void*) ); /* ** CAPI3REF: Text Encodings ** ** These constant define integer codes that represent the various ** text encodings supported by SQLite. */ #define SQLITE_UTF8 1 /* IMP: R-37514-35566 */ #define SQLITE_UTF16LE 2 /* IMP: R-03371-37637 */ #define SQLITE_UTF16BE 3 /* IMP: R-51971-34154 */ #define SQLITE_UTF16 4 /* Use native byte order */ #define SQLITE_ANY 5 /* Deprecated */ #define SQLITE_UTF16_ALIGNED 8 /* sqlite3_create_collation only */ /* ** CAPI3REF: Function Flags ** ** These constants may be ORed together with the ** [SQLITE_UTF8 | preferred text encoding] as the fourth argument ** to [sqlite3_create_function()], [sqlite3_create_function16()], or ** [sqlite3_create_function_v2()]. */ #define SQLITE_DETERMINISTIC 0x800 /* ** CAPI3REF: Deprecated Functions ** DEPRECATED ** ** These functions are [deprecated]. In order to maintain ** backwards compatibility with older code, these functions continue ** to be supported. However, new applications should avoid ** the use of these functions. To encourage programmers to avoid ** these functions, we will not explain what they do. */ #ifndef SQLITE_OMIT_DEPRECATED SQLITE_API SQLITE_DEPRECATED int sqlite3_aggregate_count(sqlite3_context*); SQLITE_API SQLITE_DEPRECATED int sqlite3_expired(sqlite3_stmt*); SQLITE_API SQLITE_DEPRECATED int sqlite3_transfer_bindings(sqlite3_stmt*, sqlite3_stmt*); SQLITE_API SQLITE_DEPRECATED int sqlite3_global_recover(void); SQLITE_API SQLITE_DEPRECATED void sqlite3_thread_cleanup(void); SQLITE_API SQLITE_DEPRECATED int sqlite3_memory_alarm(void(*)(void*,sqlite3_int64,int), void*,sqlite3_int64); #endif /* ** CAPI3REF: Obtaining SQL Values ** METHOD: sqlite3_value ** ** The C-language implementation of SQL functions and aggregates uses ** this set of interface routines to access the parameter values on ** the function or aggregate. ** ** The xFunc (for scalar functions) or xStep (for aggregates) parameters ** to [sqlite3_create_function()] and [sqlite3_create_function16()] ** define callbacks that implement the SQL functions and aggregates. ** The 3rd parameter to these callbacks is an array of pointers to ** [protected sqlite3_value] objects. There is one [sqlite3_value] object for ** each parameter to the SQL function. These routines are used to ** extract values from the [sqlite3_value] objects. ** ** These routines work only with [protected sqlite3_value] objects. ** Any attempt to use these routines on an [unprotected sqlite3_value] ** object results in undefined behavior. ** ** ^These routines work just like the corresponding [column access functions] ** except that these routines take a single [protected sqlite3_value] object ** pointer instead of a [sqlite3_stmt*] pointer and an integer column number. ** ** ^The sqlite3_value_text16() interface extracts a UTF-16 string ** in the native byte-order of the host machine. ^The ** sqlite3_value_text16be() and sqlite3_value_text16le() interfaces ** extract UTF-16 strings as big-endian and little-endian respectively. ** ** ^(The sqlite3_value_numeric_type() interface attempts to apply ** numeric affinity to the value. This means that an attempt is ** made to convert the value to an integer or floating point. If ** such a conversion is possible without loss of information (in other ** words, if the value is a string that looks like a number) ** then the conversion is performed. Otherwise no conversion occurs. ** The [SQLITE_INTEGER | datatype] after conversion is returned.)^ ** ** Please pay particular attention to the fact that the pointer returned ** from [sqlite3_value_blob()], [sqlite3_value_text()], or ** [sqlite3_value_text16()] can be invalidated by a subsequent call to ** [sqlite3_value_bytes()], [sqlite3_value_bytes16()], [sqlite3_value_text()], ** or [sqlite3_value_text16()]. ** ** These routines must be called from the same thread as ** the SQL function that supplied the [sqlite3_value*] parameters. */ SQLITE_API const void *sqlite3_value_blob(sqlite3_value*); SQLITE_API int sqlite3_value_bytes(sqlite3_value*); SQLITE_API int sqlite3_value_bytes16(sqlite3_value*); SQLITE_API double sqlite3_value_double(sqlite3_value*); SQLITE_API int sqlite3_value_int(sqlite3_value*); SQLITE_API sqlite3_int64 sqlite3_value_int64(sqlite3_value*); SQLITE_API const unsigned char *sqlite3_value_text(sqlite3_value*); SQLITE_API const void *sqlite3_value_text16(sqlite3_value*); SQLITE_API const void *sqlite3_value_text16le(sqlite3_value*); SQLITE_API const void *sqlite3_value_text16be(sqlite3_value*); SQLITE_API int sqlite3_value_type(sqlite3_value*); SQLITE_API int sqlite3_value_numeric_type(sqlite3_value*); /* ** CAPI3REF: Finding The Subtype Of SQL Values ** METHOD: sqlite3_value ** ** The sqlite3_value_subtype(V) function returns the subtype for ** an [application-defined SQL function] argument V. The subtype ** information can be used to pass a limited amount of context from ** one SQL function to another. Use the [sqlite3_result_subtype()] ** routine to set the subtype for the return value of an SQL function. ** ** SQLite makes no use of subtype itself. It merely passes the subtype ** from the result of one [application-defined SQL function] into the ** input of another. */ SQLITE_API unsigned int sqlite3_value_subtype(sqlite3_value*); /* ** CAPI3REF: Copy And Free SQL Values ** METHOD: sqlite3_value ** ** ^The sqlite3_value_dup(V) interface makes a copy of the [sqlite3_value] ** object D and returns a pointer to that copy. ^The [sqlite3_value] returned ** is a [protected sqlite3_value] object even if the input is not. ** ^The sqlite3_value_dup(V) interface returns NULL if V is NULL or if a ** memory allocation fails. ** ** ^The sqlite3_value_free(V) interface frees an [sqlite3_value] object ** previously obtained from [sqlite3_value_dup()]. ^If V is a NULL pointer ** then sqlite3_value_free(V) is a harmless no-op. */ SQLITE_API sqlite3_value *sqlite3_value_dup(const sqlite3_value*); SQLITE_API void sqlite3_value_free(sqlite3_value*); /* ** CAPI3REF: Obtain Aggregate Function Context ** METHOD: sqlite3_context ** ** Implementations of aggregate SQL functions use this ** routine to allocate memory for storing their state. ** ** ^The first time the sqlite3_aggregate_context(C,N) routine is called ** for a particular aggregate function, SQLite ** allocates N of memory, zeroes out that memory, and returns a pointer ** to the new memory. ^On second and subsequent calls to ** sqlite3_aggregate_context() for the same aggregate function instance, ** the same buffer is returned. Sqlite3_aggregate_context() is normally ** called once for each invocation of the xStep callback and then one ** last time when the xFinal callback is invoked. ^(When no rows match ** an aggregate query, the xStep() callback of the aggregate function ** implementation is never called and xFinal() is called exactly once. ** In those cases, sqlite3_aggregate_context() might be called for the ** first time from within xFinal().)^ ** ** ^The sqlite3_aggregate_context(C,N) routine returns a NULL pointer ** when first called if N is less than or equal to zero or if a memory ** allocate error occurs. ** ** ^(The amount of space allocated by sqlite3_aggregate_context(C,N) is ** determined by the N parameter on first successful call. Changing the ** value of N in subsequent call to sqlite3_aggregate_context() within ** the same aggregate function instance will not resize the memory ** allocation.)^ Within the xFinal callback, it is customary to set ** N=0 in calls to sqlite3_aggregate_context(C,N) so that no ** pointless memory allocations occur. ** ** ^SQLite automatically frees the memory allocated by ** sqlite3_aggregate_context() when the aggregate query concludes. ** ** The first parameter must be a copy of the ** [sqlite3_context | SQL function context] that is the first parameter ** to the xStep or xFinal callback routine that implements the aggregate ** function. ** ** This routine must be called from the same thread in which ** the aggregate SQL function is running. */ SQLITE_API void *sqlite3_aggregate_context(sqlite3_context*, int nBytes); /* ** CAPI3REF: User Data For Functions ** METHOD: sqlite3_context ** ** ^The sqlite3_user_data() interface returns a copy of ** the pointer that was the pUserData parameter (the 5th parameter) ** of the [sqlite3_create_function()] ** and [sqlite3_create_function16()] routines that originally ** registered the application defined function. ** ** This routine must be called from the same thread in which ** the application-defined function is running. */ SQLITE_API void *sqlite3_user_data(sqlite3_context*); /* ** CAPI3REF: Database Connection For Functions ** METHOD: sqlite3_context ** ** ^The sqlite3_context_db_handle() interface returns a copy of ** the pointer to the [database connection] (the 1st parameter) ** of the [sqlite3_create_function()] ** and [sqlite3_create_function16()] routines that originally ** registered the application defined function. */ SQLITE_API sqlite3 *sqlite3_context_db_handle(sqlite3_context*); /* ** CAPI3REF: Function Auxiliary Data ** METHOD: sqlite3_context ** ** These functions may be used by (non-aggregate) SQL functions to ** associate metadata with argument values. If the same value is passed to ** multiple invocations of the same SQL function during query execution, under ** some circumstances the associated metadata may be preserved. An example ** of where this might be useful is in a regular-expression matching ** function. The compiled version of the regular expression can be stored as ** metadata associated with the pattern string. ** Then as long as the pattern string remains the same, ** the compiled regular expression can be reused on multiple ** invocations of the same function. ** ** ^The sqlite3_get_auxdata() interface returns a pointer to the metadata ** associated by the sqlite3_set_auxdata() function with the Nth argument ** value to the application-defined function. ^If there is no metadata ** associated with the function argument, this sqlite3_get_auxdata() interface ** returns a NULL pointer. ** ** ^The sqlite3_set_auxdata(C,N,P,X) interface saves P as metadata for the N-th ** argument of the application-defined function. ^Subsequent ** calls to sqlite3_get_auxdata(C,N) return P from the most recent ** sqlite3_set_auxdata(C,N,P,X) call if the metadata is still valid or ** NULL if the metadata has been discarded. ** ^After each call to sqlite3_set_auxdata(C,N,P,X) where X is not NULL, ** SQLite will invoke the destructor function X with parameter P exactly ** once, when the metadata is discarded. ** SQLite is free to discard the metadata at any time, including:
    **
  • ^(when the corresponding function parameter changes)^, or **
  • ^(when [sqlite3_reset()] or [sqlite3_finalize()] is called for the ** SQL statement)^, or **
  • ^(when sqlite3_set_auxdata() is invoked again on the same ** parameter)^, or **
  • ^(during the original sqlite3_set_auxdata() call when a memory ** allocation error occurs.)^
** ** Note the last bullet in particular. The destructor X in ** sqlite3_set_auxdata(C,N,P,X) might be called immediately, before the ** sqlite3_set_auxdata() interface even returns. Hence sqlite3_set_auxdata() ** should be called near the end of the function implementation and the ** function implementation should not make any use of P after ** sqlite3_set_auxdata() has been called. ** ** ^(In practice, metadata is preserved between function calls for ** function parameters that are compile-time constants, including literal ** values and [parameters] and expressions composed from the same.)^ ** ** These routines must be called from the same thread in which ** the SQL function is running. */ SQLITE_API void *sqlite3_get_auxdata(sqlite3_context*, int N); SQLITE_API void sqlite3_set_auxdata(sqlite3_context*, int N, void*, void (*)(void*)); /* ** CAPI3REF: Constants Defining Special Destructor Behavior ** ** These are special values for the destructor that is passed in as the ** final argument to routines like [sqlite3_result_blob()]. ^If the destructor ** argument is SQLITE_STATIC, it means that the content pointer is constant ** and will never change. It does not need to be destroyed. ^The ** SQLITE_TRANSIENT value means that the content will likely change in ** the near future and that SQLite should make its own private copy of ** the content before returning. ** ** The typedef is necessary to work around problems in certain ** C++ compilers. */ typedef void (*sqlite3_destructor_type)(void*); #define SQLITE_STATIC ((sqlite3_destructor_type)0) #define SQLITE_TRANSIENT ((sqlite3_destructor_type)-1) /* ** CAPI3REF: Setting The Result Of An SQL Function ** METHOD: sqlite3_context ** ** These routines are used by the xFunc or xFinal callbacks that ** implement SQL functions and aggregates. See ** [sqlite3_create_function()] and [sqlite3_create_function16()] ** for additional information. ** ** These functions work very much like the [parameter binding] family of ** functions used to bind values to host parameters in prepared statements. ** Refer to the [SQL parameter] documentation for additional information. ** ** ^The sqlite3_result_blob() interface sets the result from ** an application-defined function to be the BLOB whose content is pointed ** to by the second parameter and which is N bytes long where N is the ** third parameter. ** ** ^The sqlite3_result_zeroblob(C,N) and sqlite3_result_zeroblob64(C,N) ** interfaces set the result of the application-defined function to be ** a BLOB containing all zero bytes and N bytes in size. ** ** ^The sqlite3_result_double() interface sets the result from ** an application-defined function to be a floating point value specified ** by its 2nd argument. ** ** ^The sqlite3_result_error() and sqlite3_result_error16() functions ** cause the implemented SQL function to throw an exception. ** ^SQLite uses the string pointed to by the ** 2nd parameter of sqlite3_result_error() or sqlite3_result_error16() ** as the text of an error message. ^SQLite interprets the error ** message string from sqlite3_result_error() as UTF-8. ^SQLite ** interprets the string from sqlite3_result_error16() as UTF-16 in native ** byte order. ^If the third parameter to sqlite3_result_error() ** or sqlite3_result_error16() is negative then SQLite takes as the error ** message all text up through the first zero character. ** ^If the third parameter to sqlite3_result_error() or ** sqlite3_result_error16() is non-negative then SQLite takes that many ** bytes (not characters) from the 2nd parameter as the error message. ** ^The sqlite3_result_error() and sqlite3_result_error16() ** routines make a private copy of the error message text before ** they return. Hence, the calling function can deallocate or ** modify the text after they return without harm. ** ^The sqlite3_result_error_code() function changes the error code ** returned by SQLite as a result of an error in a function. ^By default, ** the error code is SQLITE_ERROR. ^A subsequent call to sqlite3_result_error() ** or sqlite3_result_error16() resets the error code to SQLITE_ERROR. ** ** ^The sqlite3_result_error_toobig() interface causes SQLite to throw an ** error indicating that a string or BLOB is too long to represent. ** ** ^The sqlite3_result_error_nomem() interface causes SQLite to throw an ** error indicating that a memory allocation failed. ** ** ^The sqlite3_result_int() interface sets the return value ** of the application-defined function to be the 32-bit signed integer ** value given in the 2nd argument. ** ^The sqlite3_result_int64() interface sets the return value ** of the application-defined function to be the 64-bit signed integer ** value given in the 2nd argument. ** ** ^The sqlite3_result_null() interface sets the return value ** of the application-defined function to be NULL. ** ** ^The sqlite3_result_text(), sqlite3_result_text16(), ** sqlite3_result_text16le(), and sqlite3_result_text16be() interfaces ** set the return value of the application-defined function to be ** a text string which is represented as UTF-8, UTF-16 native byte order, ** UTF-16 little endian, or UTF-16 big endian, respectively. ** ^The sqlite3_result_text64() interface sets the return value of an ** application-defined function to be a text string in an encoding ** specified by the fifth (and last) parameter, which must be one ** of [SQLITE_UTF8], [SQLITE_UTF16], [SQLITE_UTF16BE], or [SQLITE_UTF16LE]. ** ^SQLite takes the text result from the application from ** the 2nd parameter of the sqlite3_result_text* interfaces. ** ^If the 3rd parameter to the sqlite3_result_text* interfaces ** is negative, then SQLite takes result text from the 2nd parameter ** through the first zero character. ** ^If the 3rd parameter to the sqlite3_result_text* interfaces ** is non-negative, then as many bytes (not characters) of the text ** pointed to by the 2nd parameter are taken as the application-defined ** function result. If the 3rd parameter is non-negative, then it ** must be the byte offset into the string where the NUL terminator would ** appear if the string where NUL terminated. If any NUL characters occur ** in the string at a byte offset that is less than the value of the 3rd ** parameter, then the resulting string will contain embedded NULs and the ** result of expressions operating on strings with embedded NULs is undefined. ** ^If the 4th parameter to the sqlite3_result_text* interfaces ** or sqlite3_result_blob is a non-NULL pointer, then SQLite calls that ** function as the destructor on the text or BLOB result when it has ** finished using that result. ** ^If the 4th parameter to the sqlite3_result_text* interfaces or to ** sqlite3_result_blob is the special constant SQLITE_STATIC, then SQLite ** assumes that the text or BLOB result is in constant space and does not ** copy the content of the parameter nor call a destructor on the content ** when it has finished using that result. ** ^If the 4th parameter to the sqlite3_result_text* interfaces ** or sqlite3_result_blob is the special constant SQLITE_TRANSIENT ** then SQLite makes a copy of the result into space obtained from ** from [sqlite3_malloc()] before it returns. ** ** ^The sqlite3_result_value() interface sets the result of ** the application-defined function to be a copy of the ** [unprotected sqlite3_value] object specified by the 2nd parameter. ^The ** sqlite3_result_value() interface makes a copy of the [sqlite3_value] ** so that the [sqlite3_value] specified in the parameter may change or ** be deallocated after sqlite3_result_value() returns without harm. ** ^A [protected sqlite3_value] object may always be used where an ** [unprotected sqlite3_value] object is required, so either ** kind of [sqlite3_value] object can be used with this interface. ** ** If these routines are called from within the different thread ** than the one containing the application-defined function that received ** the [sqlite3_context] pointer, the results are undefined. */ SQLITE_API void sqlite3_result_blob(sqlite3_context*, const void*, int, void(*)(void*)); SQLITE_API void sqlite3_result_blob64(sqlite3_context*,const void*, sqlite3_uint64,void(*)(void*)); SQLITE_API void sqlite3_result_double(sqlite3_context*, double); SQLITE_API void sqlite3_result_error(sqlite3_context*, const char*, int); SQLITE_API void sqlite3_result_error16(sqlite3_context*, const void*, int); SQLITE_API void sqlite3_result_error_toobig(sqlite3_context*); SQLITE_API void sqlite3_result_error_nomem(sqlite3_context*); SQLITE_API void sqlite3_result_error_code(sqlite3_context*, int); SQLITE_API void sqlite3_result_int(sqlite3_context*, int); SQLITE_API void sqlite3_result_int64(sqlite3_context*, sqlite3_int64); SQLITE_API void sqlite3_result_null(sqlite3_context*); SQLITE_API void sqlite3_result_text(sqlite3_context*, const char*, int, void(*)(void*)); SQLITE_API void sqlite3_result_text64(sqlite3_context*, const char*,sqlite3_uint64, void(*)(void*), unsigned char encoding); SQLITE_API void sqlite3_result_text16(sqlite3_context*, const void*, int, void(*)(void*)); SQLITE_API void sqlite3_result_text16le(sqlite3_context*, const void*, int,void(*)(void*)); SQLITE_API void sqlite3_result_text16be(sqlite3_context*, const void*, int,void(*)(void*)); SQLITE_API void sqlite3_result_value(sqlite3_context*, sqlite3_value*); SQLITE_API void sqlite3_result_zeroblob(sqlite3_context*, int n); SQLITE_API int sqlite3_result_zeroblob64(sqlite3_context*, sqlite3_uint64 n); /* ** CAPI3REF: Setting The Subtype Of An SQL Function ** METHOD: sqlite3_context ** ** The sqlite3_result_subtype(C,T) function causes the subtype of ** the result from the [application-defined SQL function] with ** [sqlite3_context] C to be the value T. Only the lower 8 bits ** of the subtype T are preserved in current versions of SQLite; ** higher order bits are discarded. ** The number of subtype bytes preserved by SQLite might increase ** in future releases of SQLite. */ SQLITE_API void sqlite3_result_subtype(sqlite3_context*,unsigned int); /* ** CAPI3REF: Define New Collating Sequences ** METHOD: sqlite3 ** ** ^These functions add, remove, or modify a [collation] associated ** with the [database connection] specified as the first argument. ** ** ^The name of the collation is a UTF-8 string ** for sqlite3_create_collation() and sqlite3_create_collation_v2() ** and a UTF-16 string in native byte order for sqlite3_create_collation16(). ** ^Collation names that compare equal according to [sqlite3_strnicmp()] are ** considered to be the same name. ** ** ^(The third argument (eTextRep) must be one of the constants: **
    **
  • [SQLITE_UTF8], **
  • [SQLITE_UTF16LE], **
  • [SQLITE_UTF16BE], **
  • [SQLITE_UTF16], or **
  • [SQLITE_UTF16_ALIGNED]. **
)^ ** ^The eTextRep argument determines the encoding of strings passed ** to the collating function callback, xCallback. ** ^The [SQLITE_UTF16] and [SQLITE_UTF16_ALIGNED] values for eTextRep ** force strings to be UTF16 with native byte order. ** ^The [SQLITE_UTF16_ALIGNED] value for eTextRep forces strings to begin ** on an even byte address. ** ** ^The fourth argument, pArg, is an application data pointer that is passed ** through as the first argument to the collating function callback. ** ** ^The fifth argument, xCallback, is a pointer to the collating function. ** ^Multiple collating functions can be registered using the same name but ** with different eTextRep parameters and SQLite will use whichever ** function requires the least amount of data transformation. ** ^If the xCallback argument is NULL then the collating function is ** deleted. ^When all collating functions having the same name are deleted, ** that collation is no longer usable. ** ** ^The collating function callback is invoked with a copy of the pArg ** application data pointer and with two strings in the encoding specified ** by the eTextRep argument. The collating function must return an ** integer that is negative, zero, or positive ** if the first string is less than, equal to, or greater than the second, ** respectively. A collating function must always return the same answer ** given the same inputs. If two or more collating functions are registered ** to the same collation name (using different eTextRep values) then all ** must give an equivalent answer when invoked with equivalent strings. ** The collating function must obey the following properties for all ** strings A, B, and C: ** **
    **
  1. If A==B then B==A. **
  2. If A==B and B==C then A==C. **
  3. If A<B THEN B>A. **
  4. If A<B and B<C then A<C. **
** ** If a collating function fails any of the above constraints and that ** collating function is registered and used, then the behavior of SQLite ** is undefined. ** ** ^The sqlite3_create_collation_v2() works like sqlite3_create_collation() ** with the addition that the xDestroy callback is invoked on pArg when ** the collating function is deleted. ** ^Collating functions are deleted when they are overridden by later ** calls to the collation creation functions or when the ** [database connection] is closed using [sqlite3_close()]. ** ** ^The xDestroy callback is not called if the ** sqlite3_create_collation_v2() function fails. Applications that invoke ** sqlite3_create_collation_v2() with a non-NULL xDestroy argument should ** check the return code and dispose of the application data pointer ** themselves rather than expecting SQLite to deal with it for them. ** This is different from every other SQLite interface. The inconsistency ** is unfortunate but cannot be changed without breaking backwards ** compatibility. ** ** See also: [sqlite3_collation_needed()] and [sqlite3_collation_needed16()]. */ SQLITE_API int sqlite3_create_collation( sqlite3*, const char *zName, int eTextRep, void *pArg, int(*xCompare)(void*,int,const void*,int,const void*) ); SQLITE_API int sqlite3_create_collation_v2( sqlite3*, const char *zName, int eTextRep, void *pArg, int(*xCompare)(void*,int,const void*,int,const void*), void(*xDestroy)(void*) ); SQLITE_API int sqlite3_create_collation16( sqlite3*, const void *zName, int eTextRep, void *pArg, int(*xCompare)(void*,int,const void*,int,const void*) ); /* ** CAPI3REF: Collation Needed Callbacks ** METHOD: sqlite3 ** ** ^To avoid having to register all collation sequences before a database ** can be used, a single callback function may be registered with the ** [database connection] to be invoked whenever an undefined collation ** sequence is required. ** ** ^If the function is registered using the sqlite3_collation_needed() API, ** then it is passed the names of undefined collation sequences as strings ** encoded in UTF-8. ^If sqlite3_collation_needed16() is used, ** the names are passed as UTF-16 in machine native byte order. ** ^A call to either function replaces the existing collation-needed callback. ** ** ^(When the callback is invoked, the first argument passed is a copy ** of the second argument to sqlite3_collation_needed() or ** sqlite3_collation_needed16(). The second argument is the database ** connection. The third argument is one of [SQLITE_UTF8], [SQLITE_UTF16BE], ** or [SQLITE_UTF16LE], indicating the most desirable form of the collation ** sequence function required. The fourth parameter is the name of the ** required collation sequence.)^ ** ** The callback function should register the desired collation using ** [sqlite3_create_collation()], [sqlite3_create_collation16()], or ** [sqlite3_create_collation_v2()]. */ SQLITE_API int sqlite3_collation_needed( sqlite3*, void*, void(*)(void*,sqlite3*,int eTextRep,const char*) ); SQLITE_API int sqlite3_collation_needed16( sqlite3*, void*, void(*)(void*,sqlite3*,int eTextRep,const void*) ); #ifdef SQLITE_HAS_CODEC /* ** Specify the key for an encrypted database. This routine should be ** called right after sqlite3_open(). ** ** The code to implement this API is not available in the public release ** of SQLite. */ SQLITE_API int sqlite3_key( sqlite3 *db, /* Database to be rekeyed */ const void *pKey, int nKey /* The key */ ); SQLITE_API int sqlite3_key_v2( sqlite3 *db, /* Database to be rekeyed */ const char *zDbName, /* Name of the database */ const void *pKey, int nKey /* The key */ ); /* ** Change the key on an open database. If the current database is not ** encrypted, this routine will encrypt it. If pNew==0 or nNew==0, the ** database is decrypted. ** ** The code to implement this API is not available in the public release ** of SQLite. */ SQLITE_API int sqlite3_rekey( sqlite3 *db, /* Database to be rekeyed */ const void *pKey, int nKey /* The new key */ ); SQLITE_API int sqlite3_rekey_v2( sqlite3 *db, /* Database to be rekeyed */ const char *zDbName, /* Name of the database */ const void *pKey, int nKey /* The new key */ ); /* ** Specify the activation key for a SEE database. Unless ** activated, none of the SEE routines will work. */ SQLITE_API void sqlite3_activate_see( const char *zPassPhrase /* Activation phrase */ ); #endif #ifdef SQLITE_ENABLE_CEROD /* ** Specify the activation key for a CEROD database. Unless ** activated, none of the CEROD routines will work. */ SQLITE_API void sqlite3_activate_cerod( const char *zPassPhrase /* Activation phrase */ ); #endif /* ** CAPI3REF: Suspend Execution For A Short Time ** ** The sqlite3_sleep() function causes the current thread to suspend execution ** for at least a number of milliseconds specified in its parameter. ** ** If the operating system does not support sleep requests with ** millisecond time resolution, then the time will be rounded up to ** the nearest second. The number of milliseconds of sleep actually ** requested from the operating system is returned. ** ** ^SQLite implements this interface by calling the xSleep() ** method of the default [sqlite3_vfs] object. If the xSleep() method ** of the default VFS is not implemented correctly, or not implemented at ** all, then the behavior of sqlite3_sleep() may deviate from the description ** in the previous paragraphs. */ SQLITE_API int sqlite3_sleep(int); /* ** CAPI3REF: Name Of The Folder Holding Temporary Files ** ** ^(If this global variable is made to point to a string which is ** the name of a folder (a.k.a. directory), then all temporary files ** created by SQLite when using a built-in [sqlite3_vfs | VFS] ** will be placed in that directory.)^ ^If this variable ** is a NULL pointer, then SQLite performs a search for an appropriate ** temporary file directory. ** ** Applications are strongly discouraged from using this global variable. ** It is required to set a temporary folder on Windows Runtime (WinRT). ** But for all other platforms, it is highly recommended that applications ** neither read nor write this variable. This global variable is a relic ** that exists for backwards compatibility of legacy applications and should ** be avoided in new projects. ** ** It is not safe to read or modify this variable in more than one ** thread at a time. It is not safe to read or modify this variable ** if a [database connection] is being used at the same time in a separate ** thread. ** It is intended that this variable be set once ** as part of process initialization and before any SQLite interface ** routines have been called and that this variable remain unchanged ** thereafter. ** ** ^The [temp_store_directory pragma] may modify this variable and cause ** it to point to memory obtained from [sqlite3_malloc]. ^Furthermore, ** the [temp_store_directory pragma] always assumes that any string ** that this variable points to is held in memory obtained from ** [sqlite3_malloc] and the pragma may attempt to free that memory ** using [sqlite3_free]. ** Hence, if this variable is modified directly, either it should be ** made NULL or made to point to memory obtained from [sqlite3_malloc] ** or else the use of the [temp_store_directory pragma] should be avoided. ** Except when requested by the [temp_store_directory pragma], SQLite ** does not free the memory that sqlite3_temp_directory points to. If ** the application wants that memory to be freed, it must do ** so itself, taking care to only do so after all [database connection] ** objects have been destroyed. ** ** Note to Windows Runtime users: The temporary directory must be set ** prior to calling [sqlite3_open] or [sqlite3_open_v2]. Otherwise, various ** features that require the use of temporary files may fail. Here is an ** example of how to do this using C++ with the Windows Runtime: ** **
** LPCWSTR zPath = Windows::Storage::ApplicationData::Current->
**       TemporaryFolder->Path->Data();
** char zPathBuf[MAX_PATH + 1];
** memset(zPathBuf, 0, sizeof(zPathBuf));
** WideCharToMultiByte(CP_UTF8, 0, zPath, -1, zPathBuf, sizeof(zPathBuf),
**       NULL, NULL);
** sqlite3_temp_directory = sqlite3_mprintf("%s", zPathBuf);
** 
*/ SQLITE_API char *sqlite3_temp_directory; /* ** CAPI3REF: Name Of The Folder Holding Database Files ** ** ^(If this global variable is made to point to a string which is ** the name of a folder (a.k.a. directory), then all database files ** specified with a relative pathname and created or accessed by ** SQLite when using a built-in windows [sqlite3_vfs | VFS] will be assumed ** to be relative to that directory.)^ ^If this variable is a NULL ** pointer, then SQLite assumes that all database files specified ** with a relative pathname are relative to the current directory ** for the process. Only the windows VFS makes use of this global ** variable; it is ignored by the unix VFS. ** ** Changing the value of this variable while a database connection is ** open can result in a corrupt database. ** ** It is not safe to read or modify this variable in more than one ** thread at a time. It is not safe to read or modify this variable ** if a [database connection] is being used at the same time in a separate ** thread. ** It is intended that this variable be set once ** as part of process initialization and before any SQLite interface ** routines have been called and that this variable remain unchanged ** thereafter. ** ** ^The [data_store_directory pragma] may modify this variable and cause ** it to point to memory obtained from [sqlite3_malloc]. ^Furthermore, ** the [data_store_directory pragma] always assumes that any string ** that this variable points to is held in memory obtained from ** [sqlite3_malloc] and the pragma may attempt to free that memory ** using [sqlite3_free]. ** Hence, if this variable is modified directly, either it should be ** made NULL or made to point to memory obtained from [sqlite3_malloc] ** or else the use of the [data_store_directory pragma] should be avoided. */ SQLITE_API char *sqlite3_data_directory; /* ** CAPI3REF: Test For Auto-Commit Mode ** KEYWORDS: {autocommit mode} ** METHOD: sqlite3 ** ** ^The sqlite3_get_autocommit() interface returns non-zero or ** zero if the given database connection is or is not in autocommit mode, ** respectively. ^Autocommit mode is on by default. ** ^Autocommit mode is disabled by a [BEGIN] statement. ** ^Autocommit mode is re-enabled by a [COMMIT] or [ROLLBACK]. ** ** If certain kinds of errors occur on a statement within a multi-statement ** transaction (errors including [SQLITE_FULL], [SQLITE_IOERR], ** [SQLITE_NOMEM], [SQLITE_BUSY], and [SQLITE_INTERRUPT]) then the ** transaction might be rolled back automatically. The only way to ** find out whether SQLite automatically rolled back the transaction after ** an error is to use this function. ** ** If another thread changes the autocommit status of the database ** connection while this routine is running, then the return value ** is undefined. */ SQLITE_API int sqlite3_get_autocommit(sqlite3*); /* ** CAPI3REF: Find The Database Handle Of A Prepared Statement ** METHOD: sqlite3_stmt ** ** ^The sqlite3_db_handle interface returns the [database connection] handle ** to which a [prepared statement] belongs. ^The [database connection] ** returned by sqlite3_db_handle is the same [database connection] ** that was the first argument ** to the [sqlite3_prepare_v2()] call (or its variants) that was used to ** create the statement in the first place. */ SQLITE_API sqlite3 *sqlite3_db_handle(sqlite3_stmt*); /* ** CAPI3REF: Return The Filename For A Database Connection ** METHOD: sqlite3 ** ** ^The sqlite3_db_filename(D,N) interface returns a pointer to a filename ** associated with database N of connection D. ^The main database file ** has the name "main". If there is no attached database N on the database ** connection D, or if database N is a temporary or in-memory database, then ** a NULL pointer is returned. ** ** ^The filename returned by this function is the output of the ** xFullPathname method of the [VFS]. ^In other words, the filename ** will be an absolute pathname, even if the filename used ** to open the database originally was a URI or relative pathname. */ SQLITE_API const char *sqlite3_db_filename(sqlite3 *db, const char *zDbName); /* ** CAPI3REF: Determine if a database is read-only ** METHOD: sqlite3 ** ** ^The sqlite3_db_readonly(D,N) interface returns 1 if the database N ** of connection D is read-only, 0 if it is read/write, or -1 if N is not ** the name of a database on connection D. */ SQLITE_API int sqlite3_db_readonly(sqlite3 *db, const char *zDbName); /* ** CAPI3REF: Find the next prepared statement ** METHOD: sqlite3 ** ** ^This interface returns a pointer to the next [prepared statement] after ** pStmt associated with the [database connection] pDb. ^If pStmt is NULL ** then this interface returns a pointer to the first prepared statement ** associated with the database connection pDb. ^If no prepared statement ** satisfies the conditions of this routine, it returns NULL. ** ** The [database connection] pointer D in a call to ** [sqlite3_next_stmt(D,S)] must refer to an open database ** connection and in particular must not be a NULL pointer. */ SQLITE_API sqlite3_stmt *sqlite3_next_stmt(sqlite3 *pDb, sqlite3_stmt *pStmt); /* ** CAPI3REF: Commit And Rollback Notification Callbacks ** METHOD: sqlite3 ** ** ^The sqlite3_commit_hook() interface registers a callback ** function to be invoked whenever a transaction is [COMMIT | committed]. ** ^Any callback set by a previous call to sqlite3_commit_hook() ** for the same database connection is overridden. ** ^The sqlite3_rollback_hook() interface registers a callback ** function to be invoked whenever a transaction is [ROLLBACK | rolled back]. ** ^Any callback set by a previous call to sqlite3_rollback_hook() ** for the same database connection is overridden. ** ^The pArg argument is passed through to the callback. ** ^If the callback on a commit hook function returns non-zero, ** then the commit is converted into a rollback. ** ** ^The sqlite3_commit_hook(D,C,P) and sqlite3_rollback_hook(D,C,P) functions ** return the P argument from the previous call of the same function ** on the same [database connection] D, or NULL for ** the first call for each function on D. ** ** The commit and rollback hook callbacks are not reentrant. ** The callback implementation must not do anything that will modify ** the database connection that invoked the callback. Any actions ** to modify the database connection must be deferred until after the ** completion of the [sqlite3_step()] call that triggered the commit ** or rollback hook in the first place. ** Note that running any other SQL statements, including SELECT statements, ** or merely calling [sqlite3_prepare_v2()] and [sqlite3_step()] will modify ** the database connections for the meaning of "modify" in this paragraph. ** ** ^Registering a NULL function disables the callback. ** ** ^When the commit hook callback routine returns zero, the [COMMIT] ** operation is allowed to continue normally. ^If the commit hook ** returns non-zero, then the [COMMIT] is converted into a [ROLLBACK]. ** ^The rollback hook is invoked on a rollback that results from a commit ** hook returning non-zero, just as it would be with any other rollback. ** ** ^For the purposes of this API, a transaction is said to have been ** rolled back if an explicit "ROLLBACK" statement is executed, or ** an error or constraint causes an implicit rollback to occur. ** ^The rollback callback is not invoked if a transaction is ** automatically rolled back because the database connection is closed. ** ** See also the [sqlite3_update_hook()] interface. */ SQLITE_API void *sqlite3_commit_hook(sqlite3*, int(*)(void*), void*); SQLITE_API void *sqlite3_rollback_hook(sqlite3*, void(*)(void *), void*); /* ** CAPI3REF: Data Change Notification Callbacks ** METHOD: sqlite3 ** ** ^The sqlite3_update_hook() interface registers a callback function ** with the [database connection] identified by the first argument ** to be invoked whenever a row is updated, inserted or deleted in ** a [rowid table]. ** ^Any callback set by a previous call to this function ** for the same database connection is overridden. ** ** ^The second argument is a pointer to the function to invoke when a ** row is updated, inserted or deleted in a rowid table. ** ^The first argument to the callback is a copy of the third argument ** to sqlite3_update_hook(). ** ^The second callback argument is one of [SQLITE_INSERT], [SQLITE_DELETE], ** or [SQLITE_UPDATE], depending on the operation that caused the callback ** to be invoked. ** ^The third and fourth arguments to the callback contain pointers to the ** database and table name containing the affected row. ** ^The final callback parameter is the [rowid] of the row. ** ^In the case of an update, this is the [rowid] after the update takes place. ** ** ^(The update hook is not invoked when internal system tables are ** modified (i.e. sqlite_master and sqlite_sequence).)^ ** ^The update hook is not invoked when [WITHOUT ROWID] tables are modified. ** ** ^In the current implementation, the update hook ** is not invoked when duplication rows are deleted because of an ** [ON CONFLICT | ON CONFLICT REPLACE] clause. ^Nor is the update hook ** invoked when rows are deleted using the [truncate optimization]. ** The exceptions defined in this paragraph might change in a future ** release of SQLite. ** ** The update hook implementation must not do anything that will modify ** the database connection that invoked the update hook. Any actions ** to modify the database connection must be deferred until after the ** completion of the [sqlite3_step()] call that triggered the update hook. ** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their ** database connections for the meaning of "modify" in this paragraph. ** ** ^The sqlite3_update_hook(D,C,P) function ** returns the P argument from the previous call ** on the same [database connection] D, or NULL for ** the first call on D. ** ** See also the [sqlite3_commit_hook()], [sqlite3_rollback_hook()], ** and [sqlite3_preupdate_hook()] interfaces. */ SQLITE_API void *sqlite3_update_hook( sqlite3*, void(*)(void *,int ,char const *,char const *,sqlite3_int64), void* ); /* ** CAPI3REF: Enable Or Disable Shared Pager Cache ** ** ^(This routine enables or disables the sharing of the database cache ** and schema data structures between [database connection | connections] ** to the same database. Sharing is enabled if the argument is true ** and disabled if the argument is false.)^ ** ** ^Cache sharing is enabled and disabled for an entire process. ** This is a change as of SQLite [version 3.5.0] ([dateof:3.5.0]). ** In prior versions of SQLite, ** sharing was enabled or disabled for each thread separately. ** ** ^(The cache sharing mode set by this interface effects all subsequent ** calls to [sqlite3_open()], [sqlite3_open_v2()], and [sqlite3_open16()]. ** Existing database connections continue use the sharing mode ** that was in effect at the time they were opened.)^ ** ** ^(This routine returns [SQLITE_OK] if shared cache was enabled or disabled ** successfully. An [error code] is returned otherwise.)^ ** ** ^Shared cache is disabled by default. But this might change in ** future releases of SQLite. Applications that care about shared ** cache setting should set it explicitly. ** ** Note: This method is disabled on MacOS X 10.7 and iOS version 5.0 ** and will always return SQLITE_MISUSE. On those systems, ** shared cache mode should be enabled per-database connection via ** [sqlite3_open_v2()] with [SQLITE_OPEN_SHAREDCACHE]. ** ** This interface is threadsafe on processors where writing a ** 32-bit integer is atomic. ** ** See Also: [SQLite Shared-Cache Mode] */ SQLITE_API int sqlite3_enable_shared_cache(int); /* ** CAPI3REF: Attempt To Free Heap Memory ** ** ^The sqlite3_release_memory() interface attempts to free N bytes ** of heap memory by deallocating non-essential memory allocations ** held by the database library. Memory used to cache database ** pages to improve performance is an example of non-essential memory. ** ^sqlite3_release_memory() returns the number of bytes actually freed, ** which might be more or less than the amount requested. ** ^The sqlite3_release_memory() routine is a no-op returning zero ** if SQLite is not compiled with [SQLITE_ENABLE_MEMORY_MANAGEMENT]. ** ** See also: [sqlite3_db_release_memory()] */ SQLITE_API int sqlite3_release_memory(int); /* ** CAPI3REF: Free Memory Used By A Database Connection ** METHOD: sqlite3 ** ** ^The sqlite3_db_release_memory(D) interface attempts to free as much heap ** memory as possible from database connection D. Unlike the ** [sqlite3_release_memory()] interface, this interface is in effect even ** when the [SQLITE_ENABLE_MEMORY_MANAGEMENT] compile-time option is ** omitted. ** ** See also: [sqlite3_release_memory()] */ SQLITE_API int sqlite3_db_release_memory(sqlite3*); /* ** CAPI3REF: Impose A Limit On Heap Size ** ** ^The sqlite3_soft_heap_limit64() interface sets and/or queries the ** soft limit on the amount of heap memory that may be allocated by SQLite. ** ^SQLite strives to keep heap memory utilization below the soft heap ** limit by reducing the number of pages held in the page cache ** as heap memory usages approaches the limit. ** ^The soft heap limit is "soft" because even though SQLite strives to stay ** below the limit, it will exceed the limit rather than generate ** an [SQLITE_NOMEM] error. In other words, the soft heap limit ** is advisory only. ** ** ^The return value from sqlite3_soft_heap_limit64() is the size of ** the soft heap limit prior to the call, or negative in the case of an ** error. ^If the argument N is negative ** then no change is made to the soft heap limit. Hence, the current ** size of the soft heap limit can be determined by invoking ** sqlite3_soft_heap_limit64() with a negative argument. ** ** ^If the argument N is zero then the soft heap limit is disabled. ** ** ^(The soft heap limit is not enforced in the current implementation ** if one or more of following conditions are true: ** **
    **
  • The soft heap limit is set to zero. **
  • Memory accounting is disabled using a combination of the ** [sqlite3_config]([SQLITE_CONFIG_MEMSTATUS],...) start-time option and ** the [SQLITE_DEFAULT_MEMSTATUS] compile-time option. **
  • An alternative page cache implementation is specified using ** [sqlite3_config]([SQLITE_CONFIG_PCACHE2],...). **
  • The page cache allocates from its own memory pool supplied ** by [sqlite3_config]([SQLITE_CONFIG_PAGECACHE],...) rather than ** from the heap. **
)^ ** ** Beginning with SQLite [version 3.7.3] ([dateof:3.7.3]), ** the soft heap limit is enforced ** regardless of whether or not the [SQLITE_ENABLE_MEMORY_MANAGEMENT] ** compile-time option is invoked. With [SQLITE_ENABLE_MEMORY_MANAGEMENT], ** the soft heap limit is enforced on every memory allocation. Without ** [SQLITE_ENABLE_MEMORY_MANAGEMENT], the soft heap limit is only enforced ** when memory is allocated by the page cache. Testing suggests that because ** the page cache is the predominate memory user in SQLite, most ** applications will achieve adequate soft heap limit enforcement without ** the use of [SQLITE_ENABLE_MEMORY_MANAGEMENT]. ** ** The circumstances under which SQLite will enforce the soft heap limit may ** changes in future releases of SQLite. */ SQLITE_API sqlite3_int64 sqlite3_soft_heap_limit64(sqlite3_int64 N); /* ** CAPI3REF: Deprecated Soft Heap Limit Interface ** DEPRECATED ** ** This is a deprecated version of the [sqlite3_soft_heap_limit64()] ** interface. This routine is provided for historical compatibility ** only. All new applications should use the ** [sqlite3_soft_heap_limit64()] interface rather than this one. */ SQLITE_API SQLITE_DEPRECATED void sqlite3_soft_heap_limit(int N); /* ** CAPI3REF: Extract Metadata About A Column Of A Table ** METHOD: sqlite3 ** ** ^(The sqlite3_table_column_metadata(X,D,T,C,....) routine returns ** information about column C of table T in database D ** on [database connection] X.)^ ^The sqlite3_table_column_metadata() ** interface returns SQLITE_OK and fills in the non-NULL pointers in ** the final five arguments with appropriate values if the specified ** column exists. ^The sqlite3_table_column_metadata() interface returns ** SQLITE_ERROR and if the specified column does not exist. ** ^If the column-name parameter to sqlite3_table_column_metadata() is a ** NULL pointer, then this routine simply checks for the existence of the ** table and returns SQLITE_OK if the table exists and SQLITE_ERROR if it ** does not. ** ** ^The column is identified by the second, third and fourth parameters to ** this function. ^(The second parameter is either the name of the database ** (i.e. "main", "temp", or an attached database) containing the specified ** table or NULL.)^ ^If it is NULL, then all attached databases are searched ** for the table using the same algorithm used by the database engine to ** resolve unqualified table references. ** ** ^The third and fourth parameters to this function are the table and column ** name of the desired column, respectively. ** ** ^Metadata is returned by writing to the memory locations passed as the 5th ** and subsequent parameters to this function. ^Any of these arguments may be ** NULL, in which case the corresponding element of metadata is omitted. ** ** ^(
** **
Parameter Output
Type
Description ** **
5th const char* Data type **
6th const char* Name of default collation sequence **
7th int True if column has a NOT NULL constraint **
8th int True if column is part of the PRIMARY KEY **
9th int True if column is [AUTOINCREMENT] **
**
)^ ** ** ^The memory pointed to by the character pointers returned for the ** declaration type and collation sequence is valid until the next ** call to any SQLite API function. ** ** ^If the specified table is actually a view, an [error code] is returned. ** ** ^If the specified column is "rowid", "oid" or "_rowid_" and the table ** is not a [WITHOUT ROWID] table and an ** [INTEGER PRIMARY KEY] column has been explicitly declared, then the output ** parameters are set for the explicitly declared column. ^(If there is no ** [INTEGER PRIMARY KEY] column, then the outputs ** for the [rowid] are set as follows: ** **
**     data type: "INTEGER"
**     collation sequence: "BINARY"
**     not null: 0
**     primary key: 1
**     auto increment: 0
** 
)^ ** ** ^This function causes all database schemas to be read from disk and ** parsed, if that has not already been done, and returns an error if ** any errors are encountered while loading the schema. */ SQLITE_API int sqlite3_table_column_metadata( sqlite3 *db, /* Connection handle */ const char *zDbName, /* Database name or NULL */ const char *zTableName, /* Table name */ const char *zColumnName, /* Column name */ char const **pzDataType, /* OUTPUT: Declared data type */ char const **pzCollSeq, /* OUTPUT: Collation sequence name */ int *pNotNull, /* OUTPUT: True if NOT NULL constraint exists */ int *pPrimaryKey, /* OUTPUT: True if column part of PK */ int *pAutoinc /* OUTPUT: True if column is auto-increment */ ); /* ** CAPI3REF: Load An Extension ** METHOD: sqlite3 ** ** ^This interface loads an SQLite extension library from the named file. ** ** ^The sqlite3_load_extension() interface attempts to load an ** [SQLite extension] library contained in the file zFile. If ** the file cannot be loaded directly, attempts are made to load ** with various operating-system specific extensions added. ** So for example, if "samplelib" cannot be loaded, then names like ** "samplelib.so" or "samplelib.dylib" or "samplelib.dll" might ** be tried also. ** ** ^The entry point is zProc. ** ^(zProc may be 0, in which case SQLite will try to come up with an ** entry point name on its own. It first tries "sqlite3_extension_init". ** If that does not work, it constructs a name "sqlite3_X_init" where the ** X is consists of the lower-case equivalent of all ASCII alphabetic ** characters in the filename from the last "/" to the first following ** "." and omitting any initial "lib".)^ ** ^The sqlite3_load_extension() interface returns ** [SQLITE_OK] on success and [SQLITE_ERROR] if something goes wrong. ** ^If an error occurs and pzErrMsg is not 0, then the ** [sqlite3_load_extension()] interface shall attempt to ** fill *pzErrMsg with error message text stored in memory ** obtained from [sqlite3_malloc()]. The calling function ** should free this memory by calling [sqlite3_free()]. ** ** ^Extension loading must be enabled using ** [sqlite3_enable_load_extension()] or ** [sqlite3_db_config](db,[SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION],1,NULL) ** prior to calling this API, ** otherwise an error will be returned. ** ** Security warning: It is recommended that the ** [SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION] method be used to enable only this ** interface. The use of the [sqlite3_enable_load_extension()] interface ** should be avoided. This will keep the SQL function [load_extension()] ** disabled and prevent SQL injections from giving attackers ** access to extension loading capabilities. ** ** See also the [load_extension() SQL function]. */ SQLITE_API int sqlite3_load_extension( sqlite3 *db, /* Load the extension into this database connection */ const char *zFile, /* Name of the shared library containing extension */ const char *zProc, /* Entry point. Derived from zFile if 0 */ char **pzErrMsg /* Put error message here if not 0 */ ); /* ** CAPI3REF: Enable Or Disable Extension Loading ** METHOD: sqlite3 ** ** ^So as not to open security holes in older applications that are ** unprepared to deal with [extension loading], and as a means of disabling ** [extension loading] while evaluating user-entered SQL, the following API ** is provided to turn the [sqlite3_load_extension()] mechanism on and off. ** ** ^Extension loading is off by default. ** ^Call the sqlite3_enable_load_extension() routine with onoff==1 ** to turn extension loading on and call it with onoff==0 to turn ** it back off again. ** ** ^This interface enables or disables both the C-API ** [sqlite3_load_extension()] and the SQL function [load_extension()]. ** ^(Use [sqlite3_db_config](db,[SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION],..) ** to enable or disable only the C-API.)^ ** ** Security warning: It is recommended that extension loading ** be disabled using the [SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION] method ** rather than this interface, so the [load_extension()] SQL function ** remains disabled. This will prevent SQL injections from giving attackers ** access to extension loading capabilities. */ SQLITE_API int sqlite3_enable_load_extension(sqlite3 *db, int onoff); /* ** CAPI3REF: Automatically Load Statically Linked Extensions ** ** ^This interface causes the xEntryPoint() function to be invoked for ** each new [database connection] that is created. The idea here is that ** xEntryPoint() is the entry point for a statically linked [SQLite extension] ** that is to be automatically loaded into all new database connections. ** ** ^(Even though the function prototype shows that xEntryPoint() takes ** no arguments and returns void, SQLite invokes xEntryPoint() with three ** arguments and expects an integer result as if the signature of the ** entry point where as follows: ** **
**    int xEntryPoint(
**      sqlite3 *db,
**      const char **pzErrMsg,
**      const struct sqlite3_api_routines *pThunk
**    );
** 
)^ ** ** If the xEntryPoint routine encounters an error, it should make *pzErrMsg ** point to an appropriate error message (obtained from [sqlite3_mprintf()]) ** and return an appropriate [error code]. ^SQLite ensures that *pzErrMsg ** is NULL before calling the xEntryPoint(). ^SQLite will invoke ** [sqlite3_free()] on *pzErrMsg after xEntryPoint() returns. ^If any ** xEntryPoint() returns an error, the [sqlite3_open()], [sqlite3_open16()], ** or [sqlite3_open_v2()] call that provoked the xEntryPoint() will fail. ** ** ^Calling sqlite3_auto_extension(X) with an entry point X that is already ** on the list of automatic extensions is a harmless no-op. ^No entry point ** will be called more than once for each database connection that is opened. ** ** See also: [sqlite3_reset_auto_extension()] ** and [sqlite3_cancel_auto_extension()] */ SQLITE_API int sqlite3_auto_extension(void(*xEntryPoint)(void)); /* ** CAPI3REF: Cancel Automatic Extension Loading ** ** ^The [sqlite3_cancel_auto_extension(X)] interface unregisters the ** initialization routine X that was registered using a prior call to ** [sqlite3_auto_extension(X)]. ^The [sqlite3_cancel_auto_extension(X)] ** routine returns 1 if initialization routine X was successfully ** unregistered and it returns 0 if X was not on the list of initialization ** routines. */ SQLITE_API int sqlite3_cancel_auto_extension(void(*xEntryPoint)(void)); /* ** CAPI3REF: Reset Automatic Extension Loading ** ** ^This interface disables all automatic extensions previously ** registered using [sqlite3_auto_extension()]. */ SQLITE_API void sqlite3_reset_auto_extension(void); /* ** The interface to the virtual-table mechanism is currently considered ** to be experimental. The interface might change in incompatible ways. ** If this is a problem for you, do not use the interface at this time. ** ** When the virtual-table mechanism stabilizes, we will declare the ** interface fixed, support it indefinitely, and remove this comment. */ /* ** Structures used by the virtual table interface */ typedef struct sqlite3_vtab sqlite3_vtab; typedef struct sqlite3_index_info sqlite3_index_info; typedef struct sqlite3_vtab_cursor sqlite3_vtab_cursor; typedef struct sqlite3_module sqlite3_module; /* ** CAPI3REF: Virtual Table Object ** KEYWORDS: sqlite3_module {virtual table module} ** ** This structure, sometimes called a "virtual table module", ** defines the implementation of a [virtual tables]. ** This structure consists mostly of methods for the module. ** ** ^A virtual table module is created by filling in a persistent ** instance of this structure and passing a pointer to that instance ** to [sqlite3_create_module()] or [sqlite3_create_module_v2()]. ** ^The registration remains valid until it is replaced by a different ** module or until the [database connection] closes. The content ** of this structure must not change while it is registered with ** any database connection. */ struct sqlite3_module { int iVersion; int (*xCreate)(sqlite3*, void *pAux, int argc, const char *const*argv, sqlite3_vtab **ppVTab, char**); int (*xConnect)(sqlite3*, void *pAux, int argc, const char *const*argv, sqlite3_vtab **ppVTab, char**); int (*xBestIndex)(sqlite3_vtab *pVTab, sqlite3_index_info*); int (*xDisconnect)(sqlite3_vtab *pVTab); int (*xDestroy)(sqlite3_vtab *pVTab); int (*xOpen)(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor); int (*xClose)(sqlite3_vtab_cursor*); int (*xFilter)(sqlite3_vtab_cursor*, int idxNum, const char *idxStr, int argc, sqlite3_value **argv); int (*xNext)(sqlite3_vtab_cursor*); int (*xEof)(sqlite3_vtab_cursor*); int (*xColumn)(sqlite3_vtab_cursor*, sqlite3_context*, int); int (*xRowid)(sqlite3_vtab_cursor*, sqlite3_int64 *pRowid); int (*xUpdate)(sqlite3_vtab *, int, sqlite3_value **, sqlite3_int64 *); int (*xBegin)(sqlite3_vtab *pVTab); int (*xSync)(sqlite3_vtab *pVTab); int (*xCommit)(sqlite3_vtab *pVTab); int (*xRollback)(sqlite3_vtab *pVTab); int (*xFindFunction)(sqlite3_vtab *pVtab, int nArg, const char *zName, void (**pxFunc)(sqlite3_context*,int,sqlite3_value**), void **ppArg); int (*xRename)(sqlite3_vtab *pVtab, const char *zNew); /* The methods above are in version 1 of the sqlite_module object. Those ** below are for version 2 and greater. */ int (*xSavepoint)(sqlite3_vtab *pVTab, int); int (*xRelease)(sqlite3_vtab *pVTab, int); int (*xRollbackTo)(sqlite3_vtab *pVTab, int); }; /* ** CAPI3REF: Virtual Table Indexing Information ** KEYWORDS: sqlite3_index_info ** ** The sqlite3_index_info structure and its substructures is used as part ** of the [virtual table] interface to ** pass information into and receive the reply from the [xBestIndex] ** method of a [virtual table module]. The fields under **Inputs** are the ** inputs to xBestIndex and are read-only. xBestIndex inserts its ** results into the **Outputs** fields. ** ** ^(The aConstraint[] array records WHERE clause constraints of the form: ** **
column OP expr
** ** where OP is =, <, <=, >, or >=.)^ ^(The particular operator is ** stored in aConstraint[].op using one of the ** [SQLITE_INDEX_CONSTRAINT_EQ | SQLITE_INDEX_CONSTRAINT_ values].)^ ** ^(The index of the column is stored in ** aConstraint[].iColumn.)^ ^(aConstraint[].usable is TRUE if the ** expr on the right-hand side can be evaluated (and thus the constraint ** is usable) and false if it cannot.)^ ** ** ^The optimizer automatically inverts terms of the form "expr OP column" ** and makes other simplifications to the WHERE clause in an attempt to ** get as many WHERE clause terms into the form shown above as possible. ** ^The aConstraint[] array only reports WHERE clause terms that are ** relevant to the particular virtual table being queried. ** ** ^Information about the ORDER BY clause is stored in aOrderBy[]. ** ^Each term of aOrderBy records a column of the ORDER BY clause. ** ** The colUsed field indicates which columns of the virtual table may be ** required by the current scan. Virtual table columns are numbered from ** zero in the order in which they appear within the CREATE TABLE statement ** passed to sqlite3_declare_vtab(). For the first 63 columns (columns 0-62), ** the corresponding bit is set within the colUsed mask if the column may be ** required by SQLite. If the table has at least 64 columns and any column ** to the right of the first 63 is required, then bit 63 of colUsed is also ** set. In other words, column iCol may be required if the expression ** (colUsed & ((sqlite3_uint64)1 << (iCol>=63 ? 63 : iCol))) evaluates to ** non-zero. ** ** The [xBestIndex] method must fill aConstraintUsage[] with information ** about what parameters to pass to xFilter. ^If argvIndex>0 then ** the right-hand side of the corresponding aConstraint[] is evaluated ** and becomes the argvIndex-th entry in argv. ^(If aConstraintUsage[].omit ** is true, then the constraint is assumed to be fully handled by the ** virtual table and is not checked again by SQLite.)^ ** ** ^The idxNum and idxPtr values are recorded and passed into the ** [xFilter] method. ** ^[sqlite3_free()] is used to free idxPtr if and only if ** needToFreeIdxPtr is true. ** ** ^The orderByConsumed means that output from [xFilter]/[xNext] will occur in ** the correct order to satisfy the ORDER BY clause so that no separate ** sorting step is required. ** ** ^The estimatedCost value is an estimate of the cost of a particular ** strategy. A cost of N indicates that the cost of the strategy is similar ** to a linear scan of an SQLite table with N rows. A cost of log(N) ** indicates that the expense of the operation is similar to that of a ** binary search on a unique indexed field of an SQLite table with N rows. ** ** ^The estimatedRows value is an estimate of the number of rows that ** will be returned by the strategy. ** ** The xBestIndex method may optionally populate the idxFlags field with a ** mask of SQLITE_INDEX_SCAN_* flags. Currently there is only one such flag - ** SQLITE_INDEX_SCAN_UNIQUE. If the xBestIndex method sets this flag, SQLite ** assumes that the strategy may visit at most one row. ** ** Additionally, if xBestIndex sets the SQLITE_INDEX_SCAN_UNIQUE flag, then ** SQLite also assumes that if a call to the xUpdate() method is made as ** part of the same statement to delete or update a virtual table row and the ** implementation returns SQLITE_CONSTRAINT, then there is no need to rollback ** any database changes. In other words, if the xUpdate() returns ** SQLITE_CONSTRAINT, the database contents must be exactly as they were ** before xUpdate was called. By contrast, if SQLITE_INDEX_SCAN_UNIQUE is not ** set and xUpdate returns SQLITE_CONSTRAINT, any database changes made by ** the xUpdate method are automatically rolled back by SQLite. ** ** IMPORTANT: The estimatedRows field was added to the sqlite3_index_info ** structure for SQLite [version 3.8.2] ([dateof:3.8.2]). ** If a virtual table extension is ** used with an SQLite version earlier than 3.8.2, the results of attempting ** to read or write the estimatedRows field are undefined (but are likely ** to included crashing the application). The estimatedRows field should ** therefore only be used if [sqlite3_libversion_number()] returns a ** value greater than or equal to 3008002. Similarly, the idxFlags field ** was added for [version 3.9.0] ([dateof:3.9.0]). ** It may therefore only be used if ** sqlite3_libversion_number() returns a value greater than or equal to ** 3009000. */ struct sqlite3_index_info { /* Inputs */ int nConstraint; /* Number of entries in aConstraint */ struct sqlite3_index_constraint { int iColumn; /* Column constrained. -1 for ROWID */ unsigned char op; /* Constraint operator */ unsigned char usable; /* True if this constraint is usable */ int iTermOffset; /* Used internally - xBestIndex should ignore */ } *aConstraint; /* Table of WHERE clause constraints */ int nOrderBy; /* Number of terms in the ORDER BY clause */ struct sqlite3_index_orderby { int iColumn; /* Column number */ unsigned char desc; /* True for DESC. False for ASC. */ } *aOrderBy; /* The ORDER BY clause */ /* Outputs */ struct sqlite3_index_constraint_usage { int argvIndex; /* if >0, constraint is part of argv to xFilter */ unsigned char omit; /* Do not code a test for this constraint */ } *aConstraintUsage; int idxNum; /* Number used to identify the index */ char *idxStr; /* String, possibly obtained from sqlite3_malloc */ int needToFreeIdxStr; /* Free idxStr using sqlite3_free() if true */ int orderByConsumed; /* True if output is already ordered */ double estimatedCost; /* Estimated cost of using this index */ /* Fields below are only available in SQLite 3.8.2 and later */ sqlite3_int64 estimatedRows; /* Estimated number of rows returned */ /* Fields below are only available in SQLite 3.9.0 and later */ int idxFlags; /* Mask of SQLITE_INDEX_SCAN_* flags */ /* Fields below are only available in SQLite 3.10.0 and later */ sqlite3_uint64 colUsed; /* Input: Mask of columns used by statement */ }; /* ** CAPI3REF: Virtual Table Scan Flags */ #define SQLITE_INDEX_SCAN_UNIQUE 1 /* Scan visits at most 1 row */ /* ** CAPI3REF: Virtual Table Constraint Operator Codes ** ** These macros defined the allowed values for the ** [sqlite3_index_info].aConstraint[].op field. Each value represents ** an operator that is part of a constraint term in the wHERE clause of ** a query that uses a [virtual table]. */ #define SQLITE_INDEX_CONSTRAINT_EQ 2 #define SQLITE_INDEX_CONSTRAINT_GT 4 #define SQLITE_INDEX_CONSTRAINT_LE 8 #define SQLITE_INDEX_CONSTRAINT_LT 16 #define SQLITE_INDEX_CONSTRAINT_GE 32 #define SQLITE_INDEX_CONSTRAINT_MATCH 64 #define SQLITE_INDEX_CONSTRAINT_LIKE 65 #define SQLITE_INDEX_CONSTRAINT_GLOB 66 #define SQLITE_INDEX_CONSTRAINT_REGEXP 67 /* ** CAPI3REF: Register A Virtual Table Implementation ** METHOD: sqlite3 ** ** ^These routines are used to register a new [virtual table module] name. ** ^Module names must be registered before ** creating a new [virtual table] using the module and before using a ** preexisting [virtual table] for the module. ** ** ^The module name is registered on the [database connection] specified ** by the first parameter. ^The name of the module is given by the ** second parameter. ^The third parameter is a pointer to ** the implementation of the [virtual table module]. ^The fourth ** parameter is an arbitrary client data pointer that is passed through ** into the [xCreate] and [xConnect] methods of the virtual table module ** when a new virtual table is be being created or reinitialized. ** ** ^The sqlite3_create_module_v2() interface has a fifth parameter which ** is a pointer to a destructor for the pClientData. ^SQLite will ** invoke the destructor function (if it is not NULL) when SQLite ** no longer needs the pClientData pointer. ^The destructor will also ** be invoked if the call to sqlite3_create_module_v2() fails. ** ^The sqlite3_create_module() ** interface is equivalent to sqlite3_create_module_v2() with a NULL ** destructor. */ SQLITE_API int sqlite3_create_module( sqlite3 *db, /* SQLite connection to register module with */ const char *zName, /* Name of the module */ const sqlite3_module *p, /* Methods for the module */ void *pClientData /* Client data for xCreate/xConnect */ ); SQLITE_API int sqlite3_create_module_v2( sqlite3 *db, /* SQLite connection to register module with */ const char *zName, /* Name of the module */ const sqlite3_module *p, /* Methods for the module */ void *pClientData, /* Client data for xCreate/xConnect */ void(*xDestroy)(void*) /* Module destructor function */ ); /* ** CAPI3REF: Virtual Table Instance Object ** KEYWORDS: sqlite3_vtab ** ** Every [virtual table module] implementation uses a subclass ** of this object to describe a particular instance ** of the [virtual table]. Each subclass will ** be tailored to the specific needs of the module implementation. ** The purpose of this superclass is to define certain fields that are ** common to all module implementations. ** ** ^Virtual tables methods can set an error message by assigning a ** string obtained from [sqlite3_mprintf()] to zErrMsg. The method should ** take care that any prior string is freed by a call to [sqlite3_free()] ** prior to assigning a new string to zErrMsg. ^After the error message ** is delivered up to the client application, the string will be automatically ** freed by sqlite3_free() and the zErrMsg field will be zeroed. */ struct sqlite3_vtab { const sqlite3_module *pModule; /* The module for this virtual table */ int nRef; /* Number of open cursors */ char *zErrMsg; /* Error message from sqlite3_mprintf() */ /* Virtual table implementations will typically add additional fields */ }; /* ** CAPI3REF: Virtual Table Cursor Object ** KEYWORDS: sqlite3_vtab_cursor {virtual table cursor} ** ** Every [virtual table module] implementation uses a subclass of the ** following structure to describe cursors that point into the ** [virtual table] and are used ** to loop through the virtual table. Cursors are created using the ** [sqlite3_module.xOpen | xOpen] method of the module and are destroyed ** by the [sqlite3_module.xClose | xClose] method. Cursors are used ** by the [xFilter], [xNext], [xEof], [xColumn], and [xRowid] methods ** of the module. Each module implementation will define ** the content of a cursor structure to suit its own needs. ** ** This superclass exists in order to define fields of the cursor that ** are common to all implementations. */ struct sqlite3_vtab_cursor { sqlite3_vtab *pVtab; /* Virtual table of this cursor */ /* Virtual table implementations will typically add additional fields */ }; /* ** CAPI3REF: Declare The Schema Of A Virtual Table ** ** ^The [xCreate] and [xConnect] methods of a ** [virtual table module] call this interface ** to declare the format (the names and datatypes of the columns) of ** the virtual tables they implement. */ SQLITE_API int sqlite3_declare_vtab(sqlite3*, const char *zSQL); /* ** CAPI3REF: Overload A Function For A Virtual Table ** METHOD: sqlite3 ** ** ^(Virtual tables can provide alternative implementations of functions ** using the [xFindFunction] method of the [virtual table module]. ** But global versions of those functions ** must exist in order to be overloaded.)^ ** ** ^(This API makes sure a global version of a function with a particular ** name and number of parameters exists. If no such function exists ** before this API is called, a new function is created.)^ ^The implementation ** of the new function always causes an exception to be thrown. So ** the new function is not good for anything by itself. Its only ** purpose is to be a placeholder function that can be overloaded ** by a [virtual table]. */ SQLITE_API int sqlite3_overload_function(sqlite3*, const char *zFuncName, int nArg); /* ** The interface to the virtual-table mechanism defined above (back up ** to a comment remarkably similar to this one) is currently considered ** to be experimental. The interface might change in incompatible ways. ** If this is a problem for you, do not use the interface at this time. ** ** When the virtual-table mechanism stabilizes, we will declare the ** interface fixed, support it indefinitely, and remove this comment. */ /* ** CAPI3REF: A Handle To An Open BLOB ** KEYWORDS: {BLOB handle} {BLOB handles} ** ** An instance of this object represents an open BLOB on which ** [sqlite3_blob_open | incremental BLOB I/O] can be performed. ** ^Objects of this type are created by [sqlite3_blob_open()] ** and destroyed by [sqlite3_blob_close()]. ** ^The [sqlite3_blob_read()] and [sqlite3_blob_write()] interfaces ** can be used to read or write small subsections of the BLOB. ** ^The [sqlite3_blob_bytes()] interface returns the size of the BLOB in bytes. */ typedef struct sqlite3_blob sqlite3_blob; /* ** CAPI3REF: Open A BLOB For Incremental I/O ** METHOD: sqlite3 ** CONSTRUCTOR: sqlite3_blob ** ** ^(This interfaces opens a [BLOB handle | handle] to the BLOB located ** in row iRow, column zColumn, table zTable in database zDb; ** in other words, the same BLOB that would be selected by: ** **
**     SELECT zColumn FROM zDb.zTable WHERE [rowid] = iRow;
** 
)^ ** ** ^(Parameter zDb is not the filename that contains the database, but ** rather the symbolic name of the database. For attached databases, this is ** the name that appears after the AS keyword in the [ATTACH] statement. ** For the main database file, the database name is "main". For TEMP ** tables, the database name is "temp".)^ ** ** ^If the flags parameter is non-zero, then the BLOB is opened for read ** and write access. ^If the flags parameter is zero, the BLOB is opened for ** read-only access. ** ** ^(On success, [SQLITE_OK] is returned and the new [BLOB handle] is stored ** in *ppBlob. Otherwise an [error code] is returned and, unless the error ** code is SQLITE_MISUSE, *ppBlob is set to NULL.)^ ^This means that, provided ** the API is not misused, it is always safe to call [sqlite3_blob_close()] ** on *ppBlob after this function it returns. ** ** This function fails with SQLITE_ERROR if any of the following are true: **
    **
  • ^(Database zDb does not exist)^, **
  • ^(Table zTable does not exist within database zDb)^, **
  • ^(Table zTable is a WITHOUT ROWID table)^, **
  • ^(Column zColumn does not exist)^, **
  • ^(Row iRow is not present in the table)^, **
  • ^(The specified column of row iRow contains a value that is not ** a TEXT or BLOB value)^, **
  • ^(Column zColumn is part of an index, PRIMARY KEY or UNIQUE ** constraint and the blob is being opened for read/write access)^, **
  • ^([foreign key constraints | Foreign key constraints] are enabled, ** column zColumn is part of a [child key] definition and the blob is ** being opened for read/write access)^. **
** ** ^Unless it returns SQLITE_MISUSE, this function sets the ** [database connection] error code and message accessible via ** [sqlite3_errcode()] and [sqlite3_errmsg()] and related functions. ** ** ** ^(If the row that a BLOB handle points to is modified by an ** [UPDATE], [DELETE], or by [ON CONFLICT] side-effects ** then the BLOB handle is marked as "expired". ** This is true if any column of the row is changed, even a column ** other than the one the BLOB handle is open on.)^ ** ^Calls to [sqlite3_blob_read()] and [sqlite3_blob_write()] for ** an expired BLOB handle fail with a return code of [SQLITE_ABORT]. ** ^(Changes written into a BLOB prior to the BLOB expiring are not ** rolled back by the expiration of the BLOB. Such changes will eventually ** commit if the transaction continues to completion.)^ ** ** ^Use the [sqlite3_blob_bytes()] interface to determine the size of ** the opened blob. ^The size of a blob may not be changed by this ** interface. Use the [UPDATE] SQL command to change the size of a ** blob. ** ** ^The [sqlite3_bind_zeroblob()] and [sqlite3_result_zeroblob()] interfaces ** and the built-in [zeroblob] SQL function may be used to create a ** zero-filled blob to read or write using the incremental-blob interface. ** ** To avoid a resource leak, every open [BLOB handle] should eventually ** be released by a call to [sqlite3_blob_close()]. */ SQLITE_API int sqlite3_blob_open( sqlite3*, const char *zDb, const char *zTable, const char *zColumn, sqlite3_int64 iRow, int flags, sqlite3_blob **ppBlob ); /* ** CAPI3REF: Move a BLOB Handle to a New Row ** METHOD: sqlite3_blob ** ** ^This function is used to move an existing blob handle so that it points ** to a different row of the same database table. ^The new row is identified ** by the rowid value passed as the second argument. Only the row can be ** changed. ^The database, table and column on which the blob handle is open ** remain the same. Moving an existing blob handle to a new row can be ** faster than closing the existing handle and opening a new one. ** ** ^(The new row must meet the same criteria as for [sqlite3_blob_open()] - ** it must exist and there must be either a blob or text value stored in ** the nominated column.)^ ^If the new row is not present in the table, or if ** it does not contain a blob or text value, or if another error occurs, an ** SQLite error code is returned and the blob handle is considered aborted. ** ^All subsequent calls to [sqlite3_blob_read()], [sqlite3_blob_write()] or ** [sqlite3_blob_reopen()] on an aborted blob handle immediately return ** SQLITE_ABORT. ^Calling [sqlite3_blob_bytes()] on an aborted blob handle ** always returns zero. ** ** ^This function sets the database handle error code and message. */ SQLITE_API int sqlite3_blob_reopen(sqlite3_blob *, sqlite3_int64); /* ** CAPI3REF: Close A BLOB Handle ** DESTRUCTOR: sqlite3_blob ** ** ^This function closes an open [BLOB handle]. ^(The BLOB handle is closed ** unconditionally. Even if this routine returns an error code, the ** handle is still closed.)^ ** ** ^If the blob handle being closed was opened for read-write access, and if ** the database is in auto-commit mode and there are no other open read-write ** blob handles or active write statements, the current transaction is ** committed. ^If an error occurs while committing the transaction, an error ** code is returned and the transaction rolled back. ** ** Calling this function with an argument that is not a NULL pointer or an ** open blob handle results in undefined behaviour. ^Calling this routine ** with a null pointer (such as would be returned by a failed call to ** [sqlite3_blob_open()]) is a harmless no-op. ^Otherwise, if this function ** is passed a valid open blob handle, the values returned by the ** sqlite3_errcode() and sqlite3_errmsg() functions are set before returning. */ SQLITE_API int sqlite3_blob_close(sqlite3_blob *); /* ** CAPI3REF: Return The Size Of An Open BLOB ** METHOD: sqlite3_blob ** ** ^Returns the size in bytes of the BLOB accessible via the ** successfully opened [BLOB handle] in its only argument. ^The ** incremental blob I/O routines can only read or overwriting existing ** blob content; they cannot change the size of a blob. ** ** This routine only works on a [BLOB handle] which has been created ** by a prior successful call to [sqlite3_blob_open()] and which has not ** been closed by [sqlite3_blob_close()]. Passing any other pointer in ** to this routine results in undefined and probably undesirable behavior. */ SQLITE_API int sqlite3_blob_bytes(sqlite3_blob *); /* ** CAPI3REF: Read Data From A BLOB Incrementally ** METHOD: sqlite3_blob ** ** ^(This function is used to read data from an open [BLOB handle] into a ** caller-supplied buffer. N bytes of data are copied into buffer Z ** from the open BLOB, starting at offset iOffset.)^ ** ** ^If offset iOffset is less than N bytes from the end of the BLOB, ** [SQLITE_ERROR] is returned and no data is read. ^If N or iOffset is ** less than zero, [SQLITE_ERROR] is returned and no data is read. ** ^The size of the blob (and hence the maximum value of N+iOffset) ** can be determined using the [sqlite3_blob_bytes()] interface. ** ** ^An attempt to read from an expired [BLOB handle] fails with an ** error code of [SQLITE_ABORT]. ** ** ^(On success, sqlite3_blob_read() returns SQLITE_OK. ** Otherwise, an [error code] or an [extended error code] is returned.)^ ** ** This routine only works on a [BLOB handle] which has been created ** by a prior successful call to [sqlite3_blob_open()] and which has not ** been closed by [sqlite3_blob_close()]. Passing any other pointer in ** to this routine results in undefined and probably undesirable behavior. ** ** See also: [sqlite3_blob_write()]. */ SQLITE_API int sqlite3_blob_read(sqlite3_blob *, void *Z, int N, int iOffset); /* ** CAPI3REF: Write Data Into A BLOB Incrementally ** METHOD: sqlite3_blob ** ** ^(This function is used to write data into an open [BLOB handle] from a ** caller-supplied buffer. N bytes of data are copied from the buffer Z ** into the open BLOB, starting at offset iOffset.)^ ** ** ^(On success, sqlite3_blob_write() returns SQLITE_OK. ** Otherwise, an [error code] or an [extended error code] is returned.)^ ** ^Unless SQLITE_MISUSE is returned, this function sets the ** [database connection] error code and message accessible via ** [sqlite3_errcode()] and [sqlite3_errmsg()] and related functions. ** ** ^If the [BLOB handle] passed as the first argument was not opened for ** writing (the flags parameter to [sqlite3_blob_open()] was zero), ** this function returns [SQLITE_READONLY]. ** ** This function may only modify the contents of the BLOB; it is ** not possible to increase the size of a BLOB using this API. ** ^If offset iOffset is less than N bytes from the end of the BLOB, ** [SQLITE_ERROR] is returned and no data is written. The size of the ** BLOB (and hence the maximum value of N+iOffset) can be determined ** using the [sqlite3_blob_bytes()] interface. ^If N or iOffset are less ** than zero [SQLITE_ERROR] is returned and no data is written. ** ** ^An attempt to write to an expired [BLOB handle] fails with an ** error code of [SQLITE_ABORT]. ^Writes to the BLOB that occurred ** before the [BLOB handle] expired are not rolled back by the ** expiration of the handle, though of course those changes might ** have been overwritten by the statement that expired the BLOB handle ** or by other independent statements. ** ** This routine only works on a [BLOB handle] which has been created ** by a prior successful call to [sqlite3_blob_open()] and which has not ** been closed by [sqlite3_blob_close()]. Passing any other pointer in ** to this routine results in undefined and probably undesirable behavior. ** ** See also: [sqlite3_blob_read()]. */ SQLITE_API int sqlite3_blob_write(sqlite3_blob *, const void *z, int n, int iOffset); /* ** CAPI3REF: Virtual File System Objects ** ** A virtual filesystem (VFS) is an [sqlite3_vfs] object ** that SQLite uses to interact ** with the underlying operating system. Most SQLite builds come with a ** single default VFS that is appropriate for the host computer. ** New VFSes can be registered and existing VFSes can be unregistered. ** The following interfaces are provided. ** ** ^The sqlite3_vfs_find() interface returns a pointer to a VFS given its name. ** ^Names are case sensitive. ** ^Names are zero-terminated UTF-8 strings. ** ^If there is no match, a NULL pointer is returned. ** ^If zVfsName is NULL then the default VFS is returned. ** ** ^New VFSes are registered with sqlite3_vfs_register(). ** ^Each new VFS becomes the default VFS if the makeDflt flag is set. ** ^The same VFS can be registered multiple times without injury. ** ^To make an existing VFS into the default VFS, register it again ** with the makeDflt flag set. If two different VFSes with the ** same name are registered, the behavior is undefined. If a ** VFS is registered with a name that is NULL or an empty string, ** then the behavior is undefined. ** ** ^Unregister a VFS with the sqlite3_vfs_unregister() interface. ** ^(If the default VFS is unregistered, another VFS is chosen as ** the default. The choice for the new VFS is arbitrary.)^ */ SQLITE_API sqlite3_vfs *sqlite3_vfs_find(const char *zVfsName); SQLITE_API int sqlite3_vfs_register(sqlite3_vfs*, int makeDflt); SQLITE_API int sqlite3_vfs_unregister(sqlite3_vfs*); /* ** CAPI3REF: Mutexes ** ** The SQLite core uses these routines for thread ** synchronization. Though they are intended for internal ** use by SQLite, code that links against SQLite is ** permitted to use any of these routines. ** ** The SQLite source code contains multiple implementations ** of these mutex routines. An appropriate implementation ** is selected automatically at compile-time. The following ** implementations are available in the SQLite core: ** **
    **
  • SQLITE_MUTEX_PTHREADS **
  • SQLITE_MUTEX_W32 **
  • SQLITE_MUTEX_NOOP **
** ** The SQLITE_MUTEX_NOOP implementation is a set of routines ** that does no real locking and is appropriate for use in ** a single-threaded application. The SQLITE_MUTEX_PTHREADS and ** SQLITE_MUTEX_W32 implementations are appropriate for use on Unix ** and Windows. ** ** If SQLite is compiled with the SQLITE_MUTEX_APPDEF preprocessor ** macro defined (with "-DSQLITE_MUTEX_APPDEF=1"), then no mutex ** implementation is included with the library. In this case the ** application must supply a custom mutex implementation using the ** [SQLITE_CONFIG_MUTEX] option of the sqlite3_config() function ** before calling sqlite3_initialize() or any other public sqlite3_ ** function that calls sqlite3_initialize(). ** ** ^The sqlite3_mutex_alloc() routine allocates a new ** mutex and returns a pointer to it. ^The sqlite3_mutex_alloc() ** routine returns NULL if it is unable to allocate the requested ** mutex. The argument to sqlite3_mutex_alloc() must one of these ** integer constants: ** **
    **
  • SQLITE_MUTEX_FAST **
  • SQLITE_MUTEX_RECURSIVE **
  • SQLITE_MUTEX_STATIC_MASTER **
  • SQLITE_MUTEX_STATIC_MEM **
  • SQLITE_MUTEX_STATIC_OPEN **
  • SQLITE_MUTEX_STATIC_PRNG **
  • SQLITE_MUTEX_STATIC_LRU **
  • SQLITE_MUTEX_STATIC_PMEM **
  • SQLITE_MUTEX_STATIC_APP1 **
  • SQLITE_MUTEX_STATIC_APP2 **
  • SQLITE_MUTEX_STATIC_APP3 **
  • SQLITE_MUTEX_STATIC_VFS1 **
  • SQLITE_MUTEX_STATIC_VFS2 **
  • SQLITE_MUTEX_STATIC_VFS3 **
** ** ^The first two constants (SQLITE_MUTEX_FAST and SQLITE_MUTEX_RECURSIVE) ** cause sqlite3_mutex_alloc() to create ** a new mutex. ^The new mutex is recursive when SQLITE_MUTEX_RECURSIVE ** is used but not necessarily so when SQLITE_MUTEX_FAST is used. ** The mutex implementation does not need to make a distinction ** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does ** not want to. SQLite will only request a recursive mutex in ** cases where it really needs one. If a faster non-recursive mutex ** implementation is available on the host platform, the mutex subsystem ** might return such a mutex in response to SQLITE_MUTEX_FAST. ** ** ^The other allowed parameters to sqlite3_mutex_alloc() (anything other ** than SQLITE_MUTEX_FAST and SQLITE_MUTEX_RECURSIVE) each return ** a pointer to a static preexisting mutex. ^Nine static mutexes are ** used by the current version of SQLite. Future versions of SQLite ** may add additional static mutexes. Static mutexes are for internal ** use by SQLite only. Applications that use SQLite mutexes should ** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or ** SQLITE_MUTEX_RECURSIVE. ** ** ^Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST ** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc() ** returns a different mutex on every call. ^For the static ** mutex types, the same mutex is returned on every call that has ** the same type number. ** ** ^The sqlite3_mutex_free() routine deallocates a previously ** allocated dynamic mutex. Attempting to deallocate a static ** mutex results in undefined behavior. ** ** ^The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt ** to enter a mutex. ^If another thread is already within the mutex, ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return ** SQLITE_BUSY. ^The sqlite3_mutex_try() interface returns [SQLITE_OK] ** upon successful entry. ^(Mutexes created using ** SQLITE_MUTEX_RECURSIVE can be entered multiple times by the same thread. ** In such cases, the ** mutex must be exited an equal number of times before another thread ** can enter.)^ If the same thread tries to enter any mutex other ** than an SQLITE_MUTEX_RECURSIVE more than once, the behavior is undefined. ** ** ^(Some systems (for example, Windows 95) do not support the operation ** implemented by sqlite3_mutex_try(). On those systems, sqlite3_mutex_try() ** will always return SQLITE_BUSY. The SQLite core only ever uses ** sqlite3_mutex_try() as an optimization so this is acceptable ** behavior.)^ ** ** ^The sqlite3_mutex_leave() routine exits a mutex that was ** previously entered by the same thread. The behavior ** is undefined if the mutex is not currently entered by the ** calling thread or is not currently allocated. ** ** ^If the argument to sqlite3_mutex_enter(), sqlite3_mutex_try(), or ** sqlite3_mutex_leave() is a NULL pointer, then all three routines ** behave as no-ops. ** ** See also: [sqlite3_mutex_held()] and [sqlite3_mutex_notheld()]. */ SQLITE_API sqlite3_mutex *sqlite3_mutex_alloc(int); SQLITE_API void sqlite3_mutex_free(sqlite3_mutex*); SQLITE_API void sqlite3_mutex_enter(sqlite3_mutex*); SQLITE_API int sqlite3_mutex_try(sqlite3_mutex*); SQLITE_API void sqlite3_mutex_leave(sqlite3_mutex*); /* ** CAPI3REF: Mutex Methods Object ** ** An instance of this structure defines the low-level routines ** used to allocate and use mutexes. ** ** Usually, the default mutex implementations provided by SQLite are ** sufficient, however the application has the option of substituting a custom ** implementation for specialized deployments or systems for which SQLite ** does not provide a suitable implementation. In this case, the application ** creates and populates an instance of this structure to pass ** to sqlite3_config() along with the [SQLITE_CONFIG_MUTEX] option. ** Additionally, an instance of this structure can be used as an ** output variable when querying the system for the current mutex ** implementation, using the [SQLITE_CONFIG_GETMUTEX] option. ** ** ^The xMutexInit method defined by this structure is invoked as ** part of system initialization by the sqlite3_initialize() function. ** ^The xMutexInit routine is called by SQLite exactly once for each ** effective call to [sqlite3_initialize()]. ** ** ^The xMutexEnd method defined by this structure is invoked as ** part of system shutdown by the sqlite3_shutdown() function. The ** implementation of this method is expected to release all outstanding ** resources obtained by the mutex methods implementation, especially ** those obtained by the xMutexInit method. ^The xMutexEnd() ** interface is invoked exactly once for each call to [sqlite3_shutdown()]. ** ** ^(The remaining seven methods defined by this structure (xMutexAlloc, ** xMutexFree, xMutexEnter, xMutexTry, xMutexLeave, xMutexHeld and ** xMutexNotheld) implement the following interfaces (respectively): ** **
    **
  • [sqlite3_mutex_alloc()]
  • **
  • [sqlite3_mutex_free()]
  • **
  • [sqlite3_mutex_enter()]
  • **
  • [sqlite3_mutex_try()]
  • **
  • [sqlite3_mutex_leave()]
  • **
  • [sqlite3_mutex_held()]
  • **
  • [sqlite3_mutex_notheld()]
  • **
)^ ** ** The only difference is that the public sqlite3_XXX functions enumerated ** above silently ignore any invocations that pass a NULL pointer instead ** of a valid mutex handle. The implementations of the methods defined ** by this structure are not required to handle this case, the results ** of passing a NULL pointer instead of a valid mutex handle are undefined ** (i.e. it is acceptable to provide an implementation that segfaults if ** it is passed a NULL pointer). ** ** The xMutexInit() method must be threadsafe. It must be harmless to ** invoke xMutexInit() multiple times within the same process and without ** intervening calls to xMutexEnd(). Second and subsequent calls to ** xMutexInit() must be no-ops. ** ** xMutexInit() must not use SQLite memory allocation ([sqlite3_malloc()] ** and its associates). Similarly, xMutexAlloc() must not use SQLite memory ** allocation for a static mutex. ^However xMutexAlloc() may use SQLite ** memory allocation for a fast or recursive mutex. ** ** ^SQLite will invoke the xMutexEnd() method when [sqlite3_shutdown()] is ** called, but only if the prior call to xMutexInit returned SQLITE_OK. ** If xMutexInit fails in any way, it is expected to clean up after itself ** prior to returning. */ typedef struct sqlite3_mutex_methods sqlite3_mutex_methods; struct sqlite3_mutex_methods { int (*xMutexInit)(void); int (*xMutexEnd)(void); sqlite3_mutex *(*xMutexAlloc)(int); void (*xMutexFree)(sqlite3_mutex *); void (*xMutexEnter)(sqlite3_mutex *); int (*xMutexTry)(sqlite3_mutex *); void (*xMutexLeave)(sqlite3_mutex *); int (*xMutexHeld)(sqlite3_mutex *); int (*xMutexNotheld)(sqlite3_mutex *); }; /* ** CAPI3REF: Mutex Verification Routines ** ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routines ** are intended for use inside assert() statements. The SQLite core ** never uses these routines except inside an assert() and applications ** are advised to follow the lead of the core. The SQLite core only ** provides implementations for these routines when it is compiled ** with the SQLITE_DEBUG flag. External mutex implementations ** are only required to provide these routines if SQLITE_DEBUG is ** defined and if NDEBUG is not defined. ** ** These routines should return true if the mutex in their argument ** is held or not held, respectively, by the calling thread. ** ** The implementation is not required to provide versions of these ** routines that actually work. If the implementation does not provide working ** versions of these routines, it should at least provide stubs that always ** return true so that one does not get spurious assertion failures. ** ** If the argument to sqlite3_mutex_held() is a NULL pointer then ** the routine should return 1. This seems counter-intuitive since ** clearly the mutex cannot be held if it does not exist. But ** the reason the mutex does not exist is because the build is not ** using mutexes. And we do not want the assert() containing the ** call to sqlite3_mutex_held() to fail, so a non-zero return is ** the appropriate thing to do. The sqlite3_mutex_notheld() ** interface should also return 1 when given a NULL pointer. */ #ifndef NDEBUG SQLITE_API int sqlite3_mutex_held(sqlite3_mutex*); SQLITE_API int sqlite3_mutex_notheld(sqlite3_mutex*); #endif /* ** CAPI3REF: Mutex Types ** ** The [sqlite3_mutex_alloc()] interface takes a single argument ** which is one of these integer constants. ** ** The set of static mutexes may change from one SQLite release to the ** next. Applications that override the built-in mutex logic must be ** prepared to accommodate additional static mutexes. */ #define SQLITE_MUTEX_FAST 0 #define SQLITE_MUTEX_RECURSIVE 1 #define SQLITE_MUTEX_STATIC_MASTER 2 #define SQLITE_MUTEX_STATIC_MEM 3 /* sqlite3_malloc() */ #define SQLITE_MUTEX_STATIC_MEM2 4 /* NOT USED */ #define SQLITE_MUTEX_STATIC_OPEN 4 /* sqlite3BtreeOpen() */ #define SQLITE_MUTEX_STATIC_PRNG 5 /* sqlite3_randomness() */ #define SQLITE_MUTEX_STATIC_LRU 6 /* lru page list */ #define SQLITE_MUTEX_STATIC_LRU2 7 /* NOT USED */ #define SQLITE_MUTEX_STATIC_PMEM 7 /* sqlite3PageMalloc() */ #define SQLITE_MUTEX_STATIC_APP1 8 /* For use by application */ #define SQLITE_MUTEX_STATIC_APP2 9 /* For use by application */ #define SQLITE_MUTEX_STATIC_APP3 10 /* For use by application */ #define SQLITE_MUTEX_STATIC_VFS1 11 /* For use by built-in VFS */ #define SQLITE_MUTEX_STATIC_VFS2 12 /* For use by extension VFS */ #define SQLITE_MUTEX_STATIC_VFS3 13 /* For use by application VFS */ /* ** CAPI3REF: Retrieve the mutex for a database connection ** METHOD: sqlite3 ** ** ^This interface returns a pointer the [sqlite3_mutex] object that ** serializes access to the [database connection] given in the argument ** when the [threading mode] is Serialized. ** ^If the [threading mode] is Single-thread or Multi-thread then this ** routine returns a NULL pointer. */ SQLITE_API sqlite3_mutex *sqlite3_db_mutex(sqlite3*); /* ** CAPI3REF: Low-Level Control Of Database Files ** METHOD: sqlite3 ** ** ^The [sqlite3_file_control()] interface makes a direct call to the ** xFileControl method for the [sqlite3_io_methods] object associated ** with a particular database identified by the second argument. ^The ** name of the database is "main" for the main database or "temp" for the ** TEMP database, or the name that appears after the AS keyword for ** databases that are added using the [ATTACH] SQL command. ** ^A NULL pointer can be used in place of "main" to refer to the ** main database file. ** ^The third and fourth parameters to this routine ** are passed directly through to the second and third parameters of ** the xFileControl method. ^The return value of the xFileControl ** method becomes the return value of this routine. ** ** ^The SQLITE_FCNTL_FILE_POINTER value for the op parameter causes ** a pointer to the underlying [sqlite3_file] object to be written into ** the space pointed to by the 4th parameter. ^The SQLITE_FCNTL_FILE_POINTER ** case is a short-circuit path which does not actually invoke the ** underlying sqlite3_io_methods.xFileControl method. ** ** ^If the second parameter (zDbName) does not match the name of any ** open database file, then SQLITE_ERROR is returned. ^This error ** code is not remembered and will not be recalled by [sqlite3_errcode()] ** or [sqlite3_errmsg()]. The underlying xFileControl method might ** also return SQLITE_ERROR. There is no way to distinguish between ** an incorrect zDbName and an SQLITE_ERROR return from the underlying ** xFileControl method. ** ** See also: [SQLITE_FCNTL_LOCKSTATE] */ SQLITE_API int sqlite3_file_control(sqlite3*, const char *zDbName, int op, void*); /* ** CAPI3REF: Testing Interface ** ** ^The sqlite3_test_control() interface is used to read out internal ** state of SQLite and to inject faults into SQLite for testing ** purposes. ^The first parameter is an operation code that determines ** the number, meaning, and operation of all subsequent parameters. ** ** This interface is not for use by applications. It exists solely ** for verifying the correct operation of the SQLite library. Depending ** on how the SQLite library is compiled, this interface might not exist. ** ** The details of the operation codes, their meanings, the parameters ** they take, and what they do are all subject to change without notice. ** Unlike most of the SQLite API, this function is not guaranteed to ** operate consistently from one release to the next. */ SQLITE_API int sqlite3_test_control(int op, ...); /* ** CAPI3REF: Testing Interface Operation Codes ** ** These constants are the valid operation code parameters used ** as the first argument to [sqlite3_test_control()]. ** ** These parameters and their meanings are subject to change ** without notice. These values are for testing purposes only. ** Applications should not use any of these parameters or the ** [sqlite3_test_control()] interface. */ #define SQLITE_TESTCTRL_FIRST 5 #define SQLITE_TESTCTRL_PRNG_SAVE 5 #define SQLITE_TESTCTRL_PRNG_RESTORE 6 #define SQLITE_TESTCTRL_PRNG_RESET 7 #define SQLITE_TESTCTRL_BITVEC_TEST 8 #define SQLITE_TESTCTRL_FAULT_INSTALL 9 #define SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS 10 #define SQLITE_TESTCTRL_PENDING_BYTE 11 #define SQLITE_TESTCTRL_ASSERT 12 #define SQLITE_TESTCTRL_ALWAYS 13 #define SQLITE_TESTCTRL_RESERVE 14 #define SQLITE_TESTCTRL_OPTIMIZATIONS 15 #define SQLITE_TESTCTRL_ISKEYWORD 16 #define SQLITE_TESTCTRL_SCRATCHMALLOC 17 #define SQLITE_TESTCTRL_LOCALTIME_FAULT 18 #define SQLITE_TESTCTRL_EXPLAIN_STMT 19 /* NOT USED */ #define SQLITE_TESTCTRL_ONCE_RESET_THRESHOLD 19 #define SQLITE_TESTCTRL_NEVER_CORRUPT 20 #define SQLITE_TESTCTRL_VDBE_COVERAGE 21 #define SQLITE_TESTCTRL_BYTEORDER 22 #define SQLITE_TESTCTRL_ISINIT 23 #define SQLITE_TESTCTRL_SORTER_MMAP 24 #define SQLITE_TESTCTRL_IMPOSTER 25 #define SQLITE_TESTCTRL_LAST 25 /* ** CAPI3REF: SQLite Runtime Status ** ** ^These interfaces are used to retrieve runtime status information ** about the performance of SQLite, and optionally to reset various ** highwater marks. ^The first argument is an integer code for ** the specific parameter to measure. ^(Recognized integer codes ** are of the form [status parameters | SQLITE_STATUS_...].)^ ** ^The current value of the parameter is returned into *pCurrent. ** ^The highest recorded value is returned in *pHighwater. ^If the ** resetFlag is true, then the highest record value is reset after ** *pHighwater is written. ^(Some parameters do not record the highest ** value. For those parameters ** nothing is written into *pHighwater and the resetFlag is ignored.)^ ** ^(Other parameters record only the highwater mark and not the current ** value. For these latter parameters nothing is written into *pCurrent.)^ ** ** ^The sqlite3_status() and sqlite3_status64() routines return ** SQLITE_OK on success and a non-zero [error code] on failure. ** ** If either the current value or the highwater mark is too large to ** be represented by a 32-bit integer, then the values returned by ** sqlite3_status() are undefined. ** ** See also: [sqlite3_db_status()] */ SQLITE_API int sqlite3_status(int op, int *pCurrent, int *pHighwater, int resetFlag); SQLITE_API int sqlite3_status64( int op, sqlite3_int64 *pCurrent, sqlite3_int64 *pHighwater, int resetFlag ); /* ** CAPI3REF: Status Parameters ** KEYWORDS: {status parameters} ** ** These integer constants designate various run-time status parameters ** that can be returned by [sqlite3_status()]. ** **
** [[SQLITE_STATUS_MEMORY_USED]] ^(
SQLITE_STATUS_MEMORY_USED
**
This parameter is the current amount of memory checked out ** using [sqlite3_malloc()], either directly or indirectly. The ** figure includes calls made to [sqlite3_malloc()] by the application ** and internal memory usage by the SQLite library. Scratch memory ** controlled by [SQLITE_CONFIG_SCRATCH] and auxiliary page-cache ** memory controlled by [SQLITE_CONFIG_PAGECACHE] is not included in ** this parameter. The amount returned is the sum of the allocation ** sizes as reported by the xSize method in [sqlite3_mem_methods].
)^ ** ** [[SQLITE_STATUS_MALLOC_SIZE]] ^(
SQLITE_STATUS_MALLOC_SIZE
**
This parameter records the largest memory allocation request ** handed to [sqlite3_malloc()] or [sqlite3_realloc()] (or their ** internal equivalents). Only the value returned in the ** *pHighwater parameter to [sqlite3_status()] is of interest. ** The value written into the *pCurrent parameter is undefined.
)^ ** ** [[SQLITE_STATUS_MALLOC_COUNT]] ^(
SQLITE_STATUS_MALLOC_COUNT
**
This parameter records the number of separate memory allocations ** currently checked out.
)^ ** ** [[SQLITE_STATUS_PAGECACHE_USED]] ^(
SQLITE_STATUS_PAGECACHE_USED
**
This parameter returns the number of pages used out of the ** [pagecache memory allocator] that was configured using ** [SQLITE_CONFIG_PAGECACHE]. The ** value returned is in pages, not in bytes.
)^ ** ** [[SQLITE_STATUS_PAGECACHE_OVERFLOW]] ** ^(
SQLITE_STATUS_PAGECACHE_OVERFLOW
**
This parameter returns the number of bytes of page cache ** allocation which could not be satisfied by the [SQLITE_CONFIG_PAGECACHE] ** buffer and where forced to overflow to [sqlite3_malloc()]. The ** returned value includes allocations that overflowed because they ** where too large (they were larger than the "sz" parameter to ** [SQLITE_CONFIG_PAGECACHE]) and allocations that overflowed because ** no space was left in the page cache.
)^ ** ** [[SQLITE_STATUS_PAGECACHE_SIZE]] ^(
SQLITE_STATUS_PAGECACHE_SIZE
**
This parameter records the largest memory allocation request ** handed to [pagecache memory allocator]. Only the value returned in the ** *pHighwater parameter to [sqlite3_status()] is of interest. ** The value written into the *pCurrent parameter is undefined.
)^ ** ** [[SQLITE_STATUS_SCRATCH_USED]] ^(
SQLITE_STATUS_SCRATCH_USED
**
This parameter returns the number of allocations used out of the ** [scratch memory allocator] configured using ** [SQLITE_CONFIG_SCRATCH]. The value returned is in allocations, not ** in bytes. Since a single thread may only have one scratch allocation ** outstanding at time, this parameter also reports the number of threads ** using scratch memory at the same time.
)^ ** ** [[SQLITE_STATUS_SCRATCH_OVERFLOW]] ^(
SQLITE_STATUS_SCRATCH_OVERFLOW
**
This parameter returns the number of bytes of scratch memory ** allocation which could not be satisfied by the [SQLITE_CONFIG_SCRATCH] ** buffer and where forced to overflow to [sqlite3_malloc()]. The values ** returned include overflows because the requested allocation was too ** larger (that is, because the requested allocation was larger than the ** "sz" parameter to [SQLITE_CONFIG_SCRATCH]) and because no scratch buffer ** slots were available. **
)^ ** ** [[SQLITE_STATUS_SCRATCH_SIZE]] ^(
SQLITE_STATUS_SCRATCH_SIZE
**
This parameter records the largest memory allocation request ** handed to [scratch memory allocator]. Only the value returned in the ** *pHighwater parameter to [sqlite3_status()] is of interest. ** The value written into the *pCurrent parameter is undefined.
)^ ** ** [[SQLITE_STATUS_PARSER_STACK]] ^(
SQLITE_STATUS_PARSER_STACK
**
The *pHighwater parameter records the deepest parser stack. ** The *pCurrent value is undefined. The *pHighwater value is only ** meaningful if SQLite is compiled with [YYTRACKMAXSTACKDEPTH].
)^ **
** ** New status parameters may be added from time to time. */ #define SQLITE_STATUS_MEMORY_USED 0 #define SQLITE_STATUS_PAGECACHE_USED 1 #define SQLITE_STATUS_PAGECACHE_OVERFLOW 2 #define SQLITE_STATUS_SCRATCH_USED 3 #define SQLITE_STATUS_SCRATCH_OVERFLOW 4 #define SQLITE_STATUS_MALLOC_SIZE 5 #define SQLITE_STATUS_PARSER_STACK 6 #define SQLITE_STATUS_PAGECACHE_SIZE 7 #define SQLITE_STATUS_SCRATCH_SIZE 8 #define SQLITE_STATUS_MALLOC_COUNT 9 /* ** CAPI3REF: Database Connection Status ** METHOD: sqlite3 ** ** ^This interface is used to retrieve runtime status information ** about a single [database connection]. ^The first argument is the ** database connection object to be interrogated. ^The second argument ** is an integer constant, taken from the set of ** [SQLITE_DBSTATUS options], that ** determines the parameter to interrogate. The set of ** [SQLITE_DBSTATUS options] is likely ** to grow in future releases of SQLite. ** ** ^The current value of the requested parameter is written into *pCur ** and the highest instantaneous value is written into *pHiwtr. ^If ** the resetFlg is true, then the highest instantaneous value is ** reset back down to the current value. ** ** ^The sqlite3_db_status() routine returns SQLITE_OK on success and a ** non-zero [error code] on failure. ** ** See also: [sqlite3_status()] and [sqlite3_stmt_status()]. */ SQLITE_API int sqlite3_db_status(sqlite3*, int op, int *pCur, int *pHiwtr, int resetFlg); /* ** CAPI3REF: Status Parameters for database connections ** KEYWORDS: {SQLITE_DBSTATUS options} ** ** These constants are the available integer "verbs" that can be passed as ** the second argument to the [sqlite3_db_status()] interface. ** ** New verbs may be added in future releases of SQLite. Existing verbs ** might be discontinued. Applications should check the return code from ** [sqlite3_db_status()] to make sure that the call worked. ** The [sqlite3_db_status()] interface will return a non-zero error code ** if a discontinued or unsupported verb is invoked. ** **
** [[SQLITE_DBSTATUS_LOOKASIDE_USED]] ^(
SQLITE_DBSTATUS_LOOKASIDE_USED
**
This parameter returns the number of lookaside memory slots currently ** checked out.
)^ ** ** [[SQLITE_DBSTATUS_LOOKASIDE_HIT]] ^(
SQLITE_DBSTATUS_LOOKASIDE_HIT
**
This parameter returns the number malloc attempts that were ** satisfied using lookaside memory. Only the high-water value is meaningful; ** the current value is always zero.)^ ** ** [[SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE]] ** ^(
SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE
**
This parameter returns the number malloc attempts that might have ** been satisfied using lookaside memory but failed due to the amount of ** memory requested being larger than the lookaside slot size. ** Only the high-water value is meaningful; ** the current value is always zero.)^ ** ** [[SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL]] ** ^(
SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL
**
This parameter returns the number malloc attempts that might have ** been satisfied using lookaside memory but failed due to all lookaside ** memory already being in use. ** Only the high-water value is meaningful; ** the current value is always zero.)^ ** ** [[SQLITE_DBSTATUS_CACHE_USED]] ^(
SQLITE_DBSTATUS_CACHE_USED
**
This parameter returns the approximate number of bytes of heap ** memory used by all pager caches associated with the database connection.)^ ** ^The highwater mark associated with SQLITE_DBSTATUS_CACHE_USED is always 0. ** ** [[SQLITE_DBSTATUS_CACHE_USED_SHARED]] ** ^(
SQLITE_DBSTATUS_CACHE_USED_SHARED
**
This parameter is similar to DBSTATUS_CACHE_USED, except that if a ** pager cache is shared between two or more connections the bytes of heap ** memory used by that pager cache is divided evenly between the attached ** connections.)^ In other words, if none of the pager caches associated ** with the database connection are shared, this request returns the same ** value as DBSTATUS_CACHE_USED. Or, if one or more or the pager caches are ** shared, the value returned by this call will be smaller than that returned ** by DBSTATUS_CACHE_USED. ^The highwater mark associated with ** SQLITE_DBSTATUS_CACHE_USED_SHARED is always 0. ** ** [[SQLITE_DBSTATUS_SCHEMA_USED]] ^(
SQLITE_DBSTATUS_SCHEMA_USED
**
This parameter returns the approximate number of bytes of heap ** memory used to store the schema for all databases associated ** with the connection - main, temp, and any [ATTACH]-ed databases.)^ ** ^The full amount of memory used by the schemas is reported, even if the ** schema memory is shared with other database connections due to ** [shared cache mode] being enabled. ** ^The highwater mark associated with SQLITE_DBSTATUS_SCHEMA_USED is always 0. ** ** [[SQLITE_DBSTATUS_STMT_USED]] ^(
SQLITE_DBSTATUS_STMT_USED
**
This parameter returns the approximate number of bytes of heap ** and lookaside memory used by all prepared statements associated with ** the database connection.)^ ** ^The highwater mark associated with SQLITE_DBSTATUS_STMT_USED is always 0. **
** ** [[SQLITE_DBSTATUS_CACHE_HIT]] ^(
SQLITE_DBSTATUS_CACHE_HIT
**
This parameter returns the number of pager cache hits that have ** occurred.)^ ^The highwater mark associated with SQLITE_DBSTATUS_CACHE_HIT ** is always 0. **
** ** [[SQLITE_DBSTATUS_CACHE_MISS]] ^(
SQLITE_DBSTATUS_CACHE_MISS
**
This parameter returns the number of pager cache misses that have ** occurred.)^ ^The highwater mark associated with SQLITE_DBSTATUS_CACHE_MISS ** is always 0. **
** ** [[SQLITE_DBSTATUS_CACHE_WRITE]] ^(
SQLITE_DBSTATUS_CACHE_WRITE
**
This parameter returns the number of dirty cache entries that have ** been written to disk. Specifically, the number of pages written to the ** wal file in wal mode databases, or the number of pages written to the ** database file in rollback mode databases. Any pages written as part of ** transaction rollback or database recovery operations are not included. ** If an IO or other error occurs while writing a page to disk, the effect ** on subsequent SQLITE_DBSTATUS_CACHE_WRITE requests is undefined.)^ ^The ** highwater mark associated with SQLITE_DBSTATUS_CACHE_WRITE is always 0. **
** ** [[SQLITE_DBSTATUS_DEFERRED_FKS]] ^(
SQLITE_DBSTATUS_DEFERRED_FKS
**
This parameter returns zero for the current value if and only if ** all foreign key constraints (deferred or immediate) have been ** resolved.)^ ^The highwater mark is always 0. **
**
*/ #define SQLITE_DBSTATUS_LOOKASIDE_USED 0 #define SQLITE_DBSTATUS_CACHE_USED 1 #define SQLITE_DBSTATUS_SCHEMA_USED 2 #define SQLITE_DBSTATUS_STMT_USED 3 #define SQLITE_DBSTATUS_LOOKASIDE_HIT 4 #define SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE 5 #define SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL 6 #define SQLITE_DBSTATUS_CACHE_HIT 7 #define SQLITE_DBSTATUS_CACHE_MISS 8 #define SQLITE_DBSTATUS_CACHE_WRITE 9 #define SQLITE_DBSTATUS_DEFERRED_FKS 10 #define SQLITE_DBSTATUS_CACHE_USED_SHARED 11 #define SQLITE_DBSTATUS_MAX 11 /* Largest defined DBSTATUS */ /* ** CAPI3REF: Prepared Statement Status ** METHOD: sqlite3_stmt ** ** ^(Each prepared statement maintains various ** [SQLITE_STMTSTATUS counters] that measure the number ** of times it has performed specific operations.)^ These counters can ** be used to monitor the performance characteristics of the prepared ** statements. For example, if the number of table steps greatly exceeds ** the number of table searches or result rows, that would tend to indicate ** that the prepared statement is using a full table scan rather than ** an index. ** ** ^(This interface is used to retrieve and reset counter values from ** a [prepared statement]. The first argument is the prepared statement ** object to be interrogated. The second argument ** is an integer code for a specific [SQLITE_STMTSTATUS counter] ** to be interrogated.)^ ** ^The current value of the requested counter is returned. ** ^If the resetFlg is true, then the counter is reset to zero after this ** interface call returns. ** ** See also: [sqlite3_status()] and [sqlite3_db_status()]. */ SQLITE_API int sqlite3_stmt_status(sqlite3_stmt*, int op,int resetFlg); /* ** CAPI3REF: Status Parameters for prepared statements ** KEYWORDS: {SQLITE_STMTSTATUS counter} {SQLITE_STMTSTATUS counters} ** ** These preprocessor macros define integer codes that name counter ** values associated with the [sqlite3_stmt_status()] interface. ** The meanings of the various counters are as follows: ** **
** [[SQLITE_STMTSTATUS_FULLSCAN_STEP]]
SQLITE_STMTSTATUS_FULLSCAN_STEP
**
^This is the number of times that SQLite has stepped forward in ** a table as part of a full table scan. Large numbers for this counter ** may indicate opportunities for performance improvement through ** careful use of indices.
** ** [[SQLITE_STMTSTATUS_SORT]]
SQLITE_STMTSTATUS_SORT
**
^This is the number of sort operations that have occurred. ** A non-zero value in this counter may indicate an opportunity to ** improvement performance through careful use of indices.
** ** [[SQLITE_STMTSTATUS_AUTOINDEX]]
SQLITE_STMTSTATUS_AUTOINDEX
**
^This is the number of rows inserted into transient indices that ** were created automatically in order to help joins run faster. ** A non-zero value in this counter may indicate an opportunity to ** improvement performance by adding permanent indices that do not ** need to be reinitialized each time the statement is run.
** ** [[SQLITE_STMTSTATUS_VM_STEP]]
SQLITE_STMTSTATUS_VM_STEP
**
^This is the number of virtual machine operations executed ** by the prepared statement if that number is less than or equal ** to 2147483647. The number of virtual machine operations can be ** used as a proxy for the total work done by the prepared statement. ** If the number of virtual machine operations exceeds 2147483647 ** then the value returned by this statement status code is undefined. **
**
*/ #define SQLITE_STMTSTATUS_FULLSCAN_STEP 1 #define SQLITE_STMTSTATUS_SORT 2 #define SQLITE_STMTSTATUS_AUTOINDEX 3 #define SQLITE_STMTSTATUS_VM_STEP 4 /* ** CAPI3REF: Custom Page Cache Object ** ** The sqlite3_pcache type is opaque. It is implemented by ** the pluggable module. The SQLite core has no knowledge of ** its size or internal structure and never deals with the ** sqlite3_pcache object except by holding and passing pointers ** to the object. ** ** See [sqlite3_pcache_methods2] for additional information. */ typedef struct sqlite3_pcache sqlite3_pcache; /* ** CAPI3REF: Custom Page Cache Object ** ** The sqlite3_pcache_page object represents a single page in the ** page cache. The page cache will allocate instances of this ** object. Various methods of the page cache use pointers to instances ** of this object as parameters or as their return value. ** ** See [sqlite3_pcache_methods2] for additional information. */ typedef struct sqlite3_pcache_page sqlite3_pcache_page; struct sqlite3_pcache_page { void *pBuf; /* The content of the page */ void *pExtra; /* Extra information associated with the page */ }; /* ** CAPI3REF: Application Defined Page Cache. ** KEYWORDS: {page cache} ** ** ^(The [sqlite3_config]([SQLITE_CONFIG_PCACHE2], ...) interface can ** register an alternative page cache implementation by passing in an ** instance of the sqlite3_pcache_methods2 structure.)^ ** In many applications, most of the heap memory allocated by ** SQLite is used for the page cache. ** By implementing a ** custom page cache using this API, an application can better control ** the amount of memory consumed by SQLite, the way in which ** that memory is allocated and released, and the policies used to ** determine exactly which parts of a database file are cached and for ** how long. ** ** The alternative page cache mechanism is an ** extreme measure that is only needed by the most demanding applications. ** The built-in page cache is recommended for most uses. ** ** ^(The contents of the sqlite3_pcache_methods2 structure are copied to an ** internal buffer by SQLite within the call to [sqlite3_config]. Hence ** the application may discard the parameter after the call to ** [sqlite3_config()] returns.)^ ** ** [[the xInit() page cache method]] ** ^(The xInit() method is called once for each effective ** call to [sqlite3_initialize()])^ ** (usually only once during the lifetime of the process). ^(The xInit() ** method is passed a copy of the sqlite3_pcache_methods2.pArg value.)^ ** The intent of the xInit() method is to set up global data structures ** required by the custom page cache implementation. ** ^(If the xInit() method is NULL, then the ** built-in default page cache is used instead of the application defined ** page cache.)^ ** ** [[the xShutdown() page cache method]] ** ^The xShutdown() method is called by [sqlite3_shutdown()]. ** It can be used to clean up ** any outstanding resources before process shutdown, if required. ** ^The xShutdown() method may be NULL. ** ** ^SQLite automatically serializes calls to the xInit method, ** so the xInit method need not be threadsafe. ^The ** xShutdown method is only called from [sqlite3_shutdown()] so it does ** not need to be threadsafe either. All other methods must be threadsafe ** in multithreaded applications. ** ** ^SQLite will never invoke xInit() more than once without an intervening ** call to xShutdown(). ** ** [[the xCreate() page cache methods]] ** ^SQLite invokes the xCreate() method to construct a new cache instance. ** SQLite will typically create one cache instance for each open database file, ** though this is not guaranteed. ^The ** first parameter, szPage, is the size in bytes of the pages that must ** be allocated by the cache. ^szPage will always a power of two. ^The ** second parameter szExtra is a number of bytes of extra storage ** associated with each page cache entry. ^The szExtra parameter will ** a number less than 250. SQLite will use the ** extra szExtra bytes on each page to store metadata about the underlying ** database page on disk. The value passed into szExtra depends ** on the SQLite version, the target platform, and how SQLite was compiled. ** ^The third argument to xCreate(), bPurgeable, is true if the cache being ** created will be used to cache database pages of a file stored on disk, or ** false if it is used for an in-memory database. The cache implementation ** does not have to do anything special based with the value of bPurgeable; ** it is purely advisory. ^On a cache where bPurgeable is false, SQLite will ** never invoke xUnpin() except to deliberately delete a page. ** ^In other words, calls to xUnpin() on a cache with bPurgeable set to ** false will always have the "discard" flag set to true. ** ^Hence, a cache created with bPurgeable false will ** never contain any unpinned pages. ** ** [[the xCachesize() page cache method]] ** ^(The xCachesize() method may be called at any time by SQLite to set the ** suggested maximum cache-size (number of pages stored by) the cache ** instance passed as the first argument. This is the value configured using ** the SQLite "[PRAGMA cache_size]" command.)^ As with the bPurgeable ** parameter, the implementation is not required to do anything with this ** value; it is advisory only. ** ** [[the xPagecount() page cache methods]] ** The xPagecount() method must return the number of pages currently ** stored in the cache, both pinned and unpinned. ** ** [[the xFetch() page cache methods]] ** The xFetch() method locates a page in the cache and returns a pointer to ** an sqlite3_pcache_page object associated with that page, or a NULL pointer. ** The pBuf element of the returned sqlite3_pcache_page object will be a ** pointer to a buffer of szPage bytes used to store the content of a ** single database page. The pExtra element of sqlite3_pcache_page will be ** a pointer to the szExtra bytes of extra storage that SQLite has requested ** for each entry in the page cache. ** ** The page to be fetched is determined by the key. ^The minimum key value ** is 1. After it has been retrieved using xFetch, the page is considered ** to be "pinned". ** ** If the requested page is already in the page cache, then the page cache ** implementation must return a pointer to the page buffer with its content ** intact. If the requested page is not already in the cache, then the ** cache implementation should use the value of the createFlag ** parameter to help it determined what action to take: ** ** **
createFlag Behavior when page is not already in cache **
0 Do not allocate a new page. Return NULL. **
1 Allocate a new page if it easy and convenient to do so. ** Otherwise return NULL. **
2 Make every effort to allocate a new page. Only return ** NULL if allocating a new page is effectively impossible. **
** ** ^(SQLite will normally invoke xFetch() with a createFlag of 0 or 1. SQLite ** will only use a createFlag of 2 after a prior call with a createFlag of 1 ** failed.)^ In between the to xFetch() calls, SQLite may ** attempt to unpin one or more cache pages by spilling the content of ** pinned pages to disk and synching the operating system disk cache. ** ** [[the xUnpin() page cache method]] ** ^xUnpin() is called by SQLite with a pointer to a currently pinned page ** as its second argument. If the third parameter, discard, is non-zero, ** then the page must be evicted from the cache. ** ^If the discard parameter is ** zero, then the page may be discarded or retained at the discretion of ** page cache implementation. ^The page cache implementation ** may choose to evict unpinned pages at any time. ** ** The cache must not perform any reference counting. A single ** call to xUnpin() unpins the page regardless of the number of prior calls ** to xFetch(). ** ** [[the xRekey() page cache methods]] ** The xRekey() method is used to change the key value associated with the ** page passed as the second argument. If the cache ** previously contains an entry associated with newKey, it must be ** discarded. ^Any prior cache entry associated with newKey is guaranteed not ** to be pinned. ** ** When SQLite calls the xTruncate() method, the cache must discard all ** existing cache entries with page numbers (keys) greater than or equal ** to the value of the iLimit parameter passed to xTruncate(). If any ** of these pages are pinned, they are implicitly unpinned, meaning that ** they can be safely discarded. ** ** [[the xDestroy() page cache method]] ** ^The xDestroy() method is used to delete a cache allocated by xCreate(). ** All resources associated with the specified cache should be freed. ^After ** calling the xDestroy() method, SQLite considers the [sqlite3_pcache*] ** handle invalid, and will not use it with any other sqlite3_pcache_methods2 ** functions. ** ** [[the xShrink() page cache method]] ** ^SQLite invokes the xShrink() method when it wants the page cache to ** free up as much of heap memory as possible. The page cache implementation ** is not obligated to free any memory, but well-behaved implementations should ** do their best. */ typedef struct sqlite3_pcache_methods2 sqlite3_pcache_methods2; struct sqlite3_pcache_methods2 { int iVersion; void *pArg; int (*xInit)(void*); void (*xShutdown)(void*); sqlite3_pcache *(*xCreate)(int szPage, int szExtra, int bPurgeable); void (*xCachesize)(sqlite3_pcache*, int nCachesize); int (*xPagecount)(sqlite3_pcache*); sqlite3_pcache_page *(*xFetch)(sqlite3_pcache*, unsigned key, int createFlag); void (*xUnpin)(sqlite3_pcache*, sqlite3_pcache_page*, int discard); void (*xRekey)(sqlite3_pcache*, sqlite3_pcache_page*, unsigned oldKey, unsigned newKey); void (*xTruncate)(sqlite3_pcache*, unsigned iLimit); void (*xDestroy)(sqlite3_pcache*); void (*xShrink)(sqlite3_pcache*); }; /* ** This is the obsolete pcache_methods object that has now been replaced ** by sqlite3_pcache_methods2. This object is not used by SQLite. It is ** retained in the header file for backwards compatibility only. */ typedef struct sqlite3_pcache_methods sqlite3_pcache_methods; struct sqlite3_pcache_methods { void *pArg; int (*xInit)(void*); void (*xShutdown)(void*); sqlite3_pcache *(*xCreate)(int szPage, int bPurgeable); void (*xCachesize)(sqlite3_pcache*, int nCachesize); int (*xPagecount)(sqlite3_pcache*); void *(*xFetch)(sqlite3_pcache*, unsigned key, int createFlag); void (*xUnpin)(sqlite3_pcache*, void*, int discard); void (*xRekey)(sqlite3_pcache*, void*, unsigned oldKey, unsigned newKey); void (*xTruncate)(sqlite3_pcache*, unsigned iLimit); void (*xDestroy)(sqlite3_pcache*); }; /* ** CAPI3REF: Online Backup Object ** ** The sqlite3_backup object records state information about an ongoing ** online backup operation. ^The sqlite3_backup object is created by ** a call to [sqlite3_backup_init()] and is destroyed by a call to ** [sqlite3_backup_finish()]. ** ** See Also: [Using the SQLite Online Backup API] */ typedef struct sqlite3_backup sqlite3_backup; /* ** CAPI3REF: Online Backup API. ** ** The backup API copies the content of one database into another. ** It is useful either for creating backups of databases or ** for copying in-memory databases to or from persistent files. ** ** See Also: [Using the SQLite Online Backup API] ** ** ^SQLite holds a write transaction open on the destination database file ** for the duration of the backup operation. ** ^The source database is read-locked only while it is being read; ** it is not locked continuously for the entire backup operation. ** ^Thus, the backup may be performed on a live source database without ** preventing other database connections from ** reading or writing to the source database while the backup is underway. ** ** ^(To perform a backup operation: **
    **
  1. sqlite3_backup_init() is called once to initialize the ** backup, **
  2. sqlite3_backup_step() is called one or more times to transfer ** the data between the two databases, and finally **
  3. sqlite3_backup_finish() is called to release all resources ** associated with the backup operation. **
)^ ** There should be exactly one call to sqlite3_backup_finish() for each ** successful call to sqlite3_backup_init(). ** ** [[sqlite3_backup_init()]] sqlite3_backup_init() ** ** ^The D and N arguments to sqlite3_backup_init(D,N,S,M) are the ** [database connection] associated with the destination database ** and the database name, respectively. ** ^The database name is "main" for the main database, "temp" for the ** temporary database, or the name specified after the AS keyword in ** an [ATTACH] statement for an attached database. ** ^The S and M arguments passed to ** sqlite3_backup_init(D,N,S,M) identify the [database connection] ** and database name of the source database, respectively. ** ^The source and destination [database connections] (parameters S and D) ** must be different or else sqlite3_backup_init(D,N,S,M) will fail with ** an error. ** ** ^A call to sqlite3_backup_init() will fail, returning NULL, if ** there is already a read or read-write transaction open on the ** destination database. ** ** ^If an error occurs within sqlite3_backup_init(D,N,S,M), then NULL is ** returned and an error code and error message are stored in the ** destination [database connection] D. ** ^The error code and message for the failed call to sqlite3_backup_init() ** can be retrieved using the [sqlite3_errcode()], [sqlite3_errmsg()], and/or ** [sqlite3_errmsg16()] functions. ** ^A successful call to sqlite3_backup_init() returns a pointer to an ** [sqlite3_backup] object. ** ^The [sqlite3_backup] object may be used with the sqlite3_backup_step() and ** sqlite3_backup_finish() functions to perform the specified backup ** operation. ** ** [[sqlite3_backup_step()]] sqlite3_backup_step() ** ** ^Function sqlite3_backup_step(B,N) will copy up to N pages between ** the source and destination databases specified by [sqlite3_backup] object B. ** ^If N is negative, all remaining source pages are copied. ** ^If sqlite3_backup_step(B,N) successfully copies N pages and there ** are still more pages to be copied, then the function returns [SQLITE_OK]. ** ^If sqlite3_backup_step(B,N) successfully finishes copying all pages ** from source to destination, then it returns [SQLITE_DONE]. ** ^If an error occurs while running sqlite3_backup_step(B,N), ** then an [error code] is returned. ^As well as [SQLITE_OK] and ** [SQLITE_DONE], a call to sqlite3_backup_step() may return [SQLITE_READONLY], ** [SQLITE_NOMEM], [SQLITE_BUSY], [SQLITE_LOCKED], or an ** [SQLITE_IOERR_ACCESS | SQLITE_IOERR_XXX] extended error code. ** ** ^(The sqlite3_backup_step() might return [SQLITE_READONLY] if **
    **
  1. the destination database was opened read-only, or **
  2. the destination database is using write-ahead-log journaling ** and the destination and source page sizes differ, or **
  3. the destination database is an in-memory database and the ** destination and source page sizes differ. **
)^ ** ** ^If sqlite3_backup_step() cannot obtain a required file-system lock, then ** the [sqlite3_busy_handler | busy-handler function] ** is invoked (if one is specified). ^If the ** busy-handler returns non-zero before the lock is available, then ** [SQLITE_BUSY] is returned to the caller. ^In this case the call to ** sqlite3_backup_step() can be retried later. ^If the source ** [database connection] ** is being used to write to the source database when sqlite3_backup_step() ** is called, then [SQLITE_LOCKED] is returned immediately. ^Again, in this ** case the call to sqlite3_backup_step() can be retried later on. ^(If ** [SQLITE_IOERR_ACCESS | SQLITE_IOERR_XXX], [SQLITE_NOMEM], or ** [SQLITE_READONLY] is returned, then ** there is no point in retrying the call to sqlite3_backup_step(). These ** errors are considered fatal.)^ The application must accept ** that the backup operation has failed and pass the backup operation handle ** to the sqlite3_backup_finish() to release associated resources. ** ** ^The first call to sqlite3_backup_step() obtains an exclusive lock ** on the destination file. ^The exclusive lock is not released until either ** sqlite3_backup_finish() is called or the backup operation is complete ** and sqlite3_backup_step() returns [SQLITE_DONE]. ^Every call to ** sqlite3_backup_step() obtains a [shared lock] on the source database that ** lasts for the duration of the sqlite3_backup_step() call. ** ^Because the source database is not locked between calls to ** sqlite3_backup_step(), the source database may be modified mid-way ** through the backup process. ^If the source database is modified by an ** external process or via a database connection other than the one being ** used by the backup operation, then the backup will be automatically ** restarted by the next call to sqlite3_backup_step(). ^If the source ** database is modified by the using the same database connection as is used ** by the backup operation, then the backup database is automatically ** updated at the same time. ** ** [[sqlite3_backup_finish()]] sqlite3_backup_finish() ** ** When sqlite3_backup_step() has returned [SQLITE_DONE], or when the ** application wishes to abandon the backup operation, the application ** should destroy the [sqlite3_backup] by passing it to sqlite3_backup_finish(). ** ^The sqlite3_backup_finish() interfaces releases all ** resources associated with the [sqlite3_backup] object. ** ^If sqlite3_backup_step() has not yet returned [SQLITE_DONE], then any ** active write-transaction on the destination database is rolled back. ** The [sqlite3_backup] object is invalid ** and may not be used following a call to sqlite3_backup_finish(). ** ** ^The value returned by sqlite3_backup_finish is [SQLITE_OK] if no ** sqlite3_backup_step() errors occurred, regardless or whether or not ** sqlite3_backup_step() completed. ** ^If an out-of-memory condition or IO error occurred during any prior ** sqlite3_backup_step() call on the same [sqlite3_backup] object, then ** sqlite3_backup_finish() returns the corresponding [error code]. ** ** ^A return of [SQLITE_BUSY] or [SQLITE_LOCKED] from sqlite3_backup_step() ** is not a permanent error and does not affect the return value of ** sqlite3_backup_finish(). ** ** [[sqlite3_backup_remaining()]] [[sqlite3_backup_pagecount()]] ** sqlite3_backup_remaining() and sqlite3_backup_pagecount() ** ** ^The sqlite3_backup_remaining() routine returns the number of pages still ** to be backed up at the conclusion of the most recent sqlite3_backup_step(). ** ^The sqlite3_backup_pagecount() routine returns the total number of pages ** in the source database at the conclusion of the most recent ** sqlite3_backup_step(). ** ^(The values returned by these functions are only updated by ** sqlite3_backup_step(). If the source database is modified in a way that ** changes the size of the source database or the number of pages remaining, ** those changes are not reflected in the output of sqlite3_backup_pagecount() ** and sqlite3_backup_remaining() until after the next ** sqlite3_backup_step().)^ ** ** Concurrent Usage of Database Handles ** ** ^The source [database connection] may be used by the application for other ** purposes while a backup operation is underway or being initialized. ** ^If SQLite is compiled and configured to support threadsafe database ** connections, then the source database connection may be used concurrently ** from within other threads. ** ** However, the application must guarantee that the destination ** [database connection] is not passed to any other API (by any thread) after ** sqlite3_backup_init() is called and before the corresponding call to ** sqlite3_backup_finish(). SQLite does not currently check to see ** if the application incorrectly accesses the destination [database connection] ** and so no error code is reported, but the operations may malfunction ** nevertheless. Use of the destination database connection while a ** backup is in progress might also also cause a mutex deadlock. ** ** If running in [shared cache mode], the application must ** guarantee that the shared cache used by the destination database ** is not accessed while the backup is running. In practice this means ** that the application must guarantee that the disk file being ** backed up to is not accessed by any connection within the process, ** not just the specific connection that was passed to sqlite3_backup_init(). ** ** The [sqlite3_backup] object itself is partially threadsafe. Multiple ** threads may safely make multiple concurrent calls to sqlite3_backup_step(). ** However, the sqlite3_backup_remaining() and sqlite3_backup_pagecount() ** APIs are not strictly speaking threadsafe. If they are invoked at the ** same time as another thread is invoking sqlite3_backup_step() it is ** possible that they return invalid values. */ SQLITE_API sqlite3_backup *sqlite3_backup_init( sqlite3 *pDest, /* Destination database handle */ const char *zDestName, /* Destination database name */ sqlite3 *pSource, /* Source database handle */ const char *zSourceName /* Source database name */ ); SQLITE_API int sqlite3_backup_step(sqlite3_backup *p, int nPage); SQLITE_API int sqlite3_backup_finish(sqlite3_backup *p); SQLITE_API int sqlite3_backup_remaining(sqlite3_backup *p); SQLITE_API int sqlite3_backup_pagecount(sqlite3_backup *p); /* ** CAPI3REF: Unlock Notification ** METHOD: sqlite3 ** ** ^When running in shared-cache mode, a database operation may fail with ** an [SQLITE_LOCKED] error if the required locks on the shared-cache or ** individual tables within the shared-cache cannot be obtained. See ** [SQLite Shared-Cache Mode] for a description of shared-cache locking. ** ^This API may be used to register a callback that SQLite will invoke ** when the connection currently holding the required lock relinquishes it. ** ^This API is only available if the library was compiled with the ** [SQLITE_ENABLE_UNLOCK_NOTIFY] C-preprocessor symbol defined. ** ** See Also: [Using the SQLite Unlock Notification Feature]. ** ** ^Shared-cache locks are released when a database connection concludes ** its current transaction, either by committing it or rolling it back. ** ** ^When a connection (known as the blocked connection) fails to obtain a ** shared-cache lock and SQLITE_LOCKED is returned to the caller, the ** identity of the database connection (the blocking connection) that ** has locked the required resource is stored internally. ^After an ** application receives an SQLITE_LOCKED error, it may call the ** sqlite3_unlock_notify() method with the blocked connection handle as ** the first argument to register for a callback that will be invoked ** when the blocking connections current transaction is concluded. ^The ** callback is invoked from within the [sqlite3_step] or [sqlite3_close] ** call that concludes the blocking connections transaction. ** ** ^(If sqlite3_unlock_notify() is called in a multi-threaded application, ** there is a chance that the blocking connection will have already ** concluded its transaction by the time sqlite3_unlock_notify() is invoked. ** If this happens, then the specified callback is invoked immediately, ** from within the call to sqlite3_unlock_notify().)^ ** ** ^If the blocked connection is attempting to obtain a write-lock on a ** shared-cache table, and more than one other connection currently holds ** a read-lock on the same table, then SQLite arbitrarily selects one of ** the other connections to use as the blocking connection. ** ** ^(There may be at most one unlock-notify callback registered by a ** blocked connection. If sqlite3_unlock_notify() is called when the ** blocked connection already has a registered unlock-notify callback, ** then the new callback replaces the old.)^ ^If sqlite3_unlock_notify() is ** called with a NULL pointer as its second argument, then any existing ** unlock-notify callback is canceled. ^The blocked connections ** unlock-notify callback may also be canceled by closing the blocked ** connection using [sqlite3_close()]. ** ** The unlock-notify callback is not reentrant. If an application invokes ** any sqlite3_xxx API functions from within an unlock-notify callback, a ** crash or deadlock may be the result. ** ** ^Unless deadlock is detected (see below), sqlite3_unlock_notify() always ** returns SQLITE_OK. ** ** Callback Invocation Details ** ** When an unlock-notify callback is registered, the application provides a ** single void* pointer that is passed to the callback when it is invoked. ** However, the signature of the callback function allows SQLite to pass ** it an array of void* context pointers. The first argument passed to ** an unlock-notify callback is a pointer to an array of void* pointers, ** and the second is the number of entries in the array. ** ** When a blocking connections transaction is concluded, there may be ** more than one blocked connection that has registered for an unlock-notify ** callback. ^If two or more such blocked connections have specified the ** same callback function, then instead of invoking the callback function ** multiple times, it is invoked once with the set of void* context pointers ** specified by the blocked connections bundled together into an array. ** This gives the application an opportunity to prioritize any actions ** related to the set of unblocked database connections. ** ** Deadlock Detection ** ** Assuming that after registering for an unlock-notify callback a ** database waits for the callback to be issued before taking any further ** action (a reasonable assumption), then using this API may cause the ** application to deadlock. For example, if connection X is waiting for ** connection Y's transaction to be concluded, and similarly connection ** Y is waiting on connection X's transaction, then neither connection ** will proceed and the system may remain deadlocked indefinitely. ** ** To avoid this scenario, the sqlite3_unlock_notify() performs deadlock ** detection. ^If a given call to sqlite3_unlock_notify() would put the ** system in a deadlocked state, then SQLITE_LOCKED is returned and no ** unlock-notify callback is registered. The system is said to be in ** a deadlocked state if connection A has registered for an unlock-notify ** callback on the conclusion of connection B's transaction, and connection ** B has itself registered for an unlock-notify callback when connection ** A's transaction is concluded. ^Indirect deadlock is also detected, so ** the system is also considered to be deadlocked if connection B has ** registered for an unlock-notify callback on the conclusion of connection ** C's transaction, where connection C is waiting on connection A. ^Any ** number of levels of indirection are allowed. ** ** The "DROP TABLE" Exception ** ** When a call to [sqlite3_step()] returns SQLITE_LOCKED, it is almost ** always appropriate to call sqlite3_unlock_notify(). There is however, ** one exception. When executing a "DROP TABLE" or "DROP INDEX" statement, ** SQLite checks if there are any currently executing SELECT statements ** that belong to the same connection. If there are, SQLITE_LOCKED is ** returned. In this case there is no "blocking connection", so invoking ** sqlite3_unlock_notify() results in the unlock-notify callback being ** invoked immediately. If the application then re-attempts the "DROP TABLE" ** or "DROP INDEX" query, an infinite loop might be the result. ** ** One way around this problem is to check the extended error code returned ** by an sqlite3_step() call. ^(If there is a blocking connection, then the ** extended error code is set to SQLITE_LOCKED_SHAREDCACHE. Otherwise, in ** the special "DROP TABLE/INDEX" case, the extended error code is just ** SQLITE_LOCKED.)^ */ SQLITE_API int sqlite3_unlock_notify( sqlite3 *pBlocked, /* Waiting connection */ void (*xNotify)(void **apArg, int nArg), /* Callback function to invoke */ void *pNotifyArg /* Argument to pass to xNotify */ ); /* ** CAPI3REF: String Comparison ** ** ^The [sqlite3_stricmp()] and [sqlite3_strnicmp()] APIs allow applications ** and extensions to compare the contents of two buffers containing UTF-8 ** strings in a case-independent fashion, using the same definition of "case ** independence" that SQLite uses internally when comparing identifiers. */ SQLITE_API int sqlite3_stricmp(const char *, const char *); SQLITE_API int sqlite3_strnicmp(const char *, const char *, int); /* ** CAPI3REF: String Globbing * ** ^The [sqlite3_strglob(P,X)] interface returns zero if and only if ** string X matches the [GLOB] pattern P. ** ^The definition of [GLOB] pattern matching used in ** [sqlite3_strglob(P,X)] is the same as for the "X GLOB P" operator in the ** SQL dialect understood by SQLite. ^The [sqlite3_strglob(P,X)] function ** is case sensitive. ** ** Note that this routine returns zero on a match and non-zero if the strings ** do not match, the same as [sqlite3_stricmp()] and [sqlite3_strnicmp()]. ** ** See also: [sqlite3_strlike()]. */ SQLITE_API int sqlite3_strglob(const char *zGlob, const char *zStr); /* ** CAPI3REF: String LIKE Matching * ** ^The [sqlite3_strlike(P,X,E)] interface returns zero if and only if ** string X matches the [LIKE] pattern P with escape character E. ** ^The definition of [LIKE] pattern matching used in ** [sqlite3_strlike(P,X,E)] is the same as for the "X LIKE P ESCAPE E" ** operator in the SQL dialect understood by SQLite. ^For "X LIKE P" without ** the ESCAPE clause, set the E parameter of [sqlite3_strlike(P,X,E)] to 0. ** ^As with the LIKE operator, the [sqlite3_strlike(P,X,E)] function is case ** insensitive - equivalent upper and lower case ASCII characters match ** one another. ** ** ^The [sqlite3_strlike(P,X,E)] function matches Unicode characters, though ** only ASCII characters are case folded. ** ** Note that this routine returns zero on a match and non-zero if the strings ** do not match, the same as [sqlite3_stricmp()] and [sqlite3_strnicmp()]. ** ** See also: [sqlite3_strglob()]. */ SQLITE_API int sqlite3_strlike(const char *zGlob, const char *zStr, unsigned int cEsc); /* ** CAPI3REF: Error Logging Interface ** ** ^The [sqlite3_log()] interface writes a message into the [error log] ** established by the [SQLITE_CONFIG_LOG] option to [sqlite3_config()]. ** ^If logging is enabled, the zFormat string and subsequent arguments are ** used with [sqlite3_snprintf()] to generate the final output string. ** ** The sqlite3_log() interface is intended for use by extensions such as ** virtual tables, collating functions, and SQL functions. While there is ** nothing to prevent an application from calling sqlite3_log(), doing so ** is considered bad form. ** ** The zFormat string must not be NULL. ** ** To avoid deadlocks and other threading problems, the sqlite3_log() routine ** will not use dynamically allocated memory. The log message is stored in ** a fixed-length buffer on the stack. If the log message is longer than ** a few hundred characters, it will be truncated to the length of the ** buffer. */ SQLITE_API void sqlite3_log(int iErrCode, const char *zFormat, ...); /* ** CAPI3REF: Write-Ahead Log Commit Hook ** METHOD: sqlite3 ** ** ^The [sqlite3_wal_hook()] function is used to register a callback that ** is invoked each time data is committed to a database in wal mode. ** ** ^(The callback is invoked by SQLite after the commit has taken place and ** the associated write-lock on the database released)^, so the implementation ** may read, write or [checkpoint] the database as required. ** ** ^The first parameter passed to the callback function when it is invoked ** is a copy of the third parameter passed to sqlite3_wal_hook() when ** registering the callback. ^The second is a copy of the database handle. ** ^The third parameter is the name of the database that was written to - ** either "main" or the name of an [ATTACH]-ed database. ^The fourth parameter ** is the number of pages currently in the write-ahead log file, ** including those that were just committed. ** ** The callback function should normally return [SQLITE_OK]. ^If an error ** code is returned, that error will propagate back up through the ** SQLite code base to cause the statement that provoked the callback ** to report an error, though the commit will have still occurred. If the ** callback returns [SQLITE_ROW] or [SQLITE_DONE], or if it returns a value ** that does not correspond to any valid SQLite error code, the results ** are undefined. ** ** A single database handle may have at most a single write-ahead log callback ** registered at one time. ^Calling [sqlite3_wal_hook()] replaces any ** previously registered write-ahead log callback. ^Note that the ** [sqlite3_wal_autocheckpoint()] interface and the ** [wal_autocheckpoint pragma] both invoke [sqlite3_wal_hook()] and will ** overwrite any prior [sqlite3_wal_hook()] settings. */ SQLITE_API void *sqlite3_wal_hook( sqlite3*, int(*)(void *,sqlite3*,const char*,int), void* ); /* ** CAPI3REF: Configure an auto-checkpoint ** METHOD: sqlite3 ** ** ^The [sqlite3_wal_autocheckpoint(D,N)] is a wrapper around ** [sqlite3_wal_hook()] that causes any database on [database connection] D ** to automatically [checkpoint] ** after committing a transaction if there are N or ** more frames in the [write-ahead log] file. ^Passing zero or ** a negative value as the nFrame parameter disables automatic ** checkpoints entirely. ** ** ^The callback registered by this function replaces any existing callback ** registered using [sqlite3_wal_hook()]. ^Likewise, registering a callback ** using [sqlite3_wal_hook()] disables the automatic checkpoint mechanism ** configured by this function. ** ** ^The [wal_autocheckpoint pragma] can be used to invoke this interface ** from SQL. ** ** ^Checkpoints initiated by this mechanism are ** [sqlite3_wal_checkpoint_v2|PASSIVE]. ** ** ^Every new [database connection] defaults to having the auto-checkpoint ** enabled with a threshold of 1000 or [SQLITE_DEFAULT_WAL_AUTOCHECKPOINT] ** pages. The use of this interface ** is only necessary if the default setting is found to be suboptimal ** for a particular application. */ SQLITE_API int sqlite3_wal_autocheckpoint(sqlite3 *db, int N); /* ** CAPI3REF: Checkpoint a database ** METHOD: sqlite3 ** ** ^(The sqlite3_wal_checkpoint(D,X) is equivalent to ** [sqlite3_wal_checkpoint_v2](D,X,[SQLITE_CHECKPOINT_PASSIVE],0,0).)^ ** ** In brief, sqlite3_wal_checkpoint(D,X) causes the content in the ** [write-ahead log] for database X on [database connection] D to be ** transferred into the database file and for the write-ahead log to ** be reset. See the [checkpointing] documentation for addition ** information. ** ** This interface used to be the only way to cause a checkpoint to ** occur. But then the newer and more powerful [sqlite3_wal_checkpoint_v2()] ** interface was added. This interface is retained for backwards ** compatibility and as a convenience for applications that need to manually ** start a callback but which do not need the full power (and corresponding ** complication) of [sqlite3_wal_checkpoint_v2()]. */ SQLITE_API int sqlite3_wal_checkpoint(sqlite3 *db, const char *zDb); /* ** CAPI3REF: Checkpoint a database ** METHOD: sqlite3 ** ** ^(The sqlite3_wal_checkpoint_v2(D,X,M,L,C) interface runs a checkpoint ** operation on database X of [database connection] D in mode M. Status ** information is written back into integers pointed to by L and C.)^ ** ^(The M parameter must be a valid [checkpoint mode]:)^ ** **
**
SQLITE_CHECKPOINT_PASSIVE
** ^Checkpoint as many frames as possible without waiting for any database ** readers or writers to finish, then sync the database file if all frames ** in the log were checkpointed. ^The [busy-handler callback] ** is never invoked in the SQLITE_CHECKPOINT_PASSIVE mode. ** ^On the other hand, passive mode might leave the checkpoint unfinished ** if there are concurrent readers or writers. ** **
SQLITE_CHECKPOINT_FULL
** ^This mode blocks (it invokes the ** [sqlite3_busy_handler|busy-handler callback]) until there is no ** database writer and all readers are reading from the most recent database ** snapshot. ^It then checkpoints all frames in the log file and syncs the ** database file. ^This mode blocks new database writers while it is pending, ** but new database readers are allowed to continue unimpeded. ** **
SQLITE_CHECKPOINT_RESTART
** ^This mode works the same way as SQLITE_CHECKPOINT_FULL with the addition ** that after checkpointing the log file it blocks (calls the ** [busy-handler callback]) ** until all readers are reading from the database file only. ^This ensures ** that the next writer will restart the log file from the beginning. ** ^Like SQLITE_CHECKPOINT_FULL, this mode blocks new ** database writer attempts while it is pending, but does not impede readers. ** **
SQLITE_CHECKPOINT_TRUNCATE
** ^This mode works the same way as SQLITE_CHECKPOINT_RESTART with the ** addition that it also truncates the log file to zero bytes just prior ** to a successful return. **
** ** ^If pnLog is not NULL, then *pnLog is set to the total number of frames in ** the log file or to -1 if the checkpoint could not run because ** of an error or because the database is not in [WAL mode]. ^If pnCkpt is not ** NULL,then *pnCkpt is set to the total number of checkpointed frames in the ** log file (including any that were already checkpointed before the function ** was called) or to -1 if the checkpoint could not run due to an error or ** because the database is not in WAL mode. ^Note that upon successful ** completion of an SQLITE_CHECKPOINT_TRUNCATE, the log file will have been ** truncated to zero bytes and so both *pnLog and *pnCkpt will be set to zero. ** ** ^All calls obtain an exclusive "checkpoint" lock on the database file. ^If ** any other process is running a checkpoint operation at the same time, the ** lock cannot be obtained and SQLITE_BUSY is returned. ^Even if there is a ** busy-handler configured, it will not be invoked in this case. ** ** ^The SQLITE_CHECKPOINT_FULL, RESTART and TRUNCATE modes also obtain the ** exclusive "writer" lock on the database file. ^If the writer lock cannot be ** obtained immediately, and a busy-handler is configured, it is invoked and ** the writer lock retried until either the busy-handler returns 0 or the lock ** is successfully obtained. ^The busy-handler is also invoked while waiting for ** database readers as described above. ^If the busy-handler returns 0 before ** the writer lock is obtained or while waiting for database readers, the ** checkpoint operation proceeds from that point in the same way as ** SQLITE_CHECKPOINT_PASSIVE - checkpointing as many frames as possible ** without blocking any further. ^SQLITE_BUSY is returned in this case. ** ** ^If parameter zDb is NULL or points to a zero length string, then the ** specified operation is attempted on all WAL databases [attached] to ** [database connection] db. In this case the ** values written to output parameters *pnLog and *pnCkpt are undefined. ^If ** an SQLITE_BUSY error is encountered when processing one or more of the ** attached WAL databases, the operation is still attempted on any remaining ** attached databases and SQLITE_BUSY is returned at the end. ^If any other ** error occurs while processing an attached database, processing is abandoned ** and the error code is returned to the caller immediately. ^If no error ** (SQLITE_BUSY or otherwise) is encountered while processing the attached ** databases, SQLITE_OK is returned. ** ** ^If database zDb is the name of an attached database that is not in WAL ** mode, SQLITE_OK is returned and both *pnLog and *pnCkpt set to -1. ^If ** zDb is not NULL (or a zero length string) and is not the name of any ** attached database, SQLITE_ERROR is returned to the caller. ** ** ^Unless it returns SQLITE_MISUSE, ** the sqlite3_wal_checkpoint_v2() interface ** sets the error information that is queried by ** [sqlite3_errcode()] and [sqlite3_errmsg()]. ** ** ^The [PRAGMA wal_checkpoint] command can be used to invoke this interface ** from SQL. */ SQLITE_API int sqlite3_wal_checkpoint_v2( sqlite3 *db, /* Database handle */ const char *zDb, /* Name of attached database (or NULL) */ int eMode, /* SQLITE_CHECKPOINT_* value */ int *pnLog, /* OUT: Size of WAL log in frames */ int *pnCkpt /* OUT: Total number of frames checkpointed */ ); /* ** CAPI3REF: Checkpoint Mode Values ** KEYWORDS: {checkpoint mode} ** ** These constants define all valid values for the "checkpoint mode" passed ** as the third parameter to the [sqlite3_wal_checkpoint_v2()] interface. ** See the [sqlite3_wal_checkpoint_v2()] documentation for details on the ** meaning of each of these checkpoint modes. */ #define SQLITE_CHECKPOINT_PASSIVE 0 /* Do as much as possible w/o blocking */ #define SQLITE_CHECKPOINT_FULL 1 /* Wait for writers, then checkpoint */ #define SQLITE_CHECKPOINT_RESTART 2 /* Like FULL but wait for for readers */ #define SQLITE_CHECKPOINT_TRUNCATE 3 /* Like RESTART but also truncate WAL */ /* ** CAPI3REF: Virtual Table Interface Configuration ** ** This function may be called by either the [xConnect] or [xCreate] method ** of a [virtual table] implementation to configure ** various facets of the virtual table interface. ** ** If this interface is invoked outside the context of an xConnect or ** xCreate virtual table method then the behavior is undefined. ** ** At present, there is only one option that may be configured using ** this function. (See [SQLITE_VTAB_CONSTRAINT_SUPPORT].) Further options ** may be added in the future. */ SQLITE_API int sqlite3_vtab_config(sqlite3*, int op, ...); /* ** CAPI3REF: Virtual Table Configuration Options ** ** These macros define the various options to the ** [sqlite3_vtab_config()] interface that [virtual table] implementations ** can use to customize and optimize their behavior. ** **
**
SQLITE_VTAB_CONSTRAINT_SUPPORT **
Calls of the form ** [sqlite3_vtab_config](db,SQLITE_VTAB_CONSTRAINT_SUPPORT,X) are supported, ** where X is an integer. If X is zero, then the [virtual table] whose ** [xCreate] or [xConnect] method invoked [sqlite3_vtab_config()] does not ** support constraints. In this configuration (which is the default) if ** a call to the [xUpdate] method returns [SQLITE_CONSTRAINT], then the entire ** statement is rolled back as if [ON CONFLICT | OR ABORT] had been ** specified as part of the users SQL statement, regardless of the actual ** ON CONFLICT mode specified. ** ** If X is non-zero, then the virtual table implementation guarantees ** that if [xUpdate] returns [SQLITE_CONSTRAINT], it will do so before ** any modifications to internal or persistent data structures have been made. ** If the [ON CONFLICT] mode is ABORT, FAIL, IGNORE or ROLLBACK, SQLite ** is able to roll back a statement or database transaction, and abandon ** or continue processing the current SQL statement as appropriate. ** If the ON CONFLICT mode is REPLACE and the [xUpdate] method returns ** [SQLITE_CONSTRAINT], SQLite handles this as if the ON CONFLICT mode ** had been ABORT. ** ** Virtual table implementations that are required to handle OR REPLACE ** must do so within the [xUpdate] method. If a call to the ** [sqlite3_vtab_on_conflict()] function indicates that the current ON ** CONFLICT policy is REPLACE, the virtual table implementation should ** silently replace the appropriate rows within the xUpdate callback and ** return SQLITE_OK. Or, if this is not possible, it may return ** SQLITE_CONSTRAINT, in which case SQLite falls back to OR ABORT ** constraint handling. **
*/ #define SQLITE_VTAB_CONSTRAINT_SUPPORT 1 /* ** CAPI3REF: Determine The Virtual Table Conflict Policy ** ** This function may only be called from within a call to the [xUpdate] method ** of a [virtual table] implementation for an INSERT or UPDATE operation. ^The ** value returned is one of [SQLITE_ROLLBACK], [SQLITE_IGNORE], [SQLITE_FAIL], ** [SQLITE_ABORT], or [SQLITE_REPLACE], according to the [ON CONFLICT] mode ** of the SQL statement that triggered the call to the [xUpdate] method of the ** [virtual table]. */ SQLITE_API int sqlite3_vtab_on_conflict(sqlite3 *); /* ** CAPI3REF: Conflict resolution modes ** KEYWORDS: {conflict resolution mode} ** ** These constants are returned by [sqlite3_vtab_on_conflict()] to ** inform a [virtual table] implementation what the [ON CONFLICT] mode ** is for the SQL statement being evaluated. ** ** Note that the [SQLITE_IGNORE] constant is also used as a potential ** return value from the [sqlite3_set_authorizer()] callback and that ** [SQLITE_ABORT] is also a [result code]. */ #define SQLITE_ROLLBACK 1 /* #define SQLITE_IGNORE 2 // Also used by sqlite3_authorizer() callback */ #define SQLITE_FAIL 3 /* #define SQLITE_ABORT 4 // Also an error code */ #define SQLITE_REPLACE 5 /* ** CAPI3REF: Prepared Statement Scan Status Opcodes ** KEYWORDS: {scanstatus options} ** ** The following constants can be used for the T parameter to the ** [sqlite3_stmt_scanstatus(S,X,T,V)] interface. Each constant designates a ** different metric for sqlite3_stmt_scanstatus() to return. ** ** When the value returned to V is a string, space to hold that string is ** managed by the prepared statement S and will be automatically freed when ** S is finalized. ** **
** [[SQLITE_SCANSTAT_NLOOP]]
SQLITE_SCANSTAT_NLOOP
**
^The [sqlite3_int64] variable pointed to by the T parameter will be ** set to the total number of times that the X-th loop has run.
** ** [[SQLITE_SCANSTAT_NVISIT]]
SQLITE_SCANSTAT_NVISIT
**
^The [sqlite3_int64] variable pointed to by the T parameter will be set ** to the total number of rows examined by all iterations of the X-th loop.
** ** [[SQLITE_SCANSTAT_EST]]
SQLITE_SCANSTAT_EST
**
^The "double" variable pointed to by the T parameter will be set to the ** query planner's estimate for the average number of rows output from each ** iteration of the X-th loop. If the query planner's estimates was accurate, ** then this value will approximate the quotient NVISIT/NLOOP and the ** product of this value for all prior loops with the same SELECTID will ** be the NLOOP value for the current loop. ** ** [[SQLITE_SCANSTAT_NAME]]
SQLITE_SCANSTAT_NAME
**
^The "const char *" variable pointed to by the T parameter will be set ** to a zero-terminated UTF-8 string containing the name of the index or table ** used for the X-th loop. ** ** [[SQLITE_SCANSTAT_EXPLAIN]]
SQLITE_SCANSTAT_EXPLAIN
**
^The "const char *" variable pointed to by the T parameter will be set ** to a zero-terminated UTF-8 string containing the [EXPLAIN QUERY PLAN] ** description for the X-th loop. ** ** [[SQLITE_SCANSTAT_SELECTID]]
SQLITE_SCANSTAT_SELECT
**
^The "int" variable pointed to by the T parameter will be set to the ** "select-id" for the X-th loop. The select-id identifies which query or ** subquery the loop is part of. The main query has a select-id of zero. ** The select-id is the same value as is output in the first column ** of an [EXPLAIN QUERY PLAN] query. **
*/ #define SQLITE_SCANSTAT_NLOOP 0 #define SQLITE_SCANSTAT_NVISIT 1 #define SQLITE_SCANSTAT_EST 2 #define SQLITE_SCANSTAT_NAME 3 #define SQLITE_SCANSTAT_EXPLAIN 4 #define SQLITE_SCANSTAT_SELECTID 5 /* ** CAPI3REF: Prepared Statement Scan Status ** METHOD: sqlite3_stmt ** ** This interface returns information about the predicted and measured ** performance for pStmt. Advanced applications can use this ** interface to compare the predicted and the measured performance and ** issue warnings and/or rerun [ANALYZE] if discrepancies are found. ** ** Since this interface is expected to be rarely used, it is only ** available if SQLite is compiled using the [SQLITE_ENABLE_STMT_SCANSTATUS] ** compile-time option. ** ** The "iScanStatusOp" parameter determines which status information to return. ** The "iScanStatusOp" must be one of the [scanstatus options] or the behavior ** of this interface is undefined. ** ^The requested measurement is written into a variable pointed to by ** the "pOut" parameter. ** Parameter "idx" identifies the specific loop to retrieve statistics for. ** Loops are numbered starting from zero. ^If idx is out of range - less than ** zero or greater than or equal to the total number of loops used to implement ** the statement - a non-zero value is returned and the variable that pOut ** points to is unchanged. ** ** ^Statistics might not be available for all loops in all statements. ^In cases ** where there exist loops with no available statistics, this function behaves ** as if the loop did not exist - it returns non-zero and leave the variable ** that pOut points to unchanged. ** ** See also: [sqlite3_stmt_scanstatus_reset()] */ SQLITE_API int sqlite3_stmt_scanstatus( sqlite3_stmt *pStmt, /* Prepared statement for which info desired */ int idx, /* Index of loop to report on */ int iScanStatusOp, /* Information desired. SQLITE_SCANSTAT_* */ void *pOut /* Result written here */ ); /* ** CAPI3REF: Zero Scan-Status Counters ** METHOD: sqlite3_stmt ** ** ^Zero all [sqlite3_stmt_scanstatus()] related event counters. ** ** This API is only available if the library is built with pre-processor ** symbol [SQLITE_ENABLE_STMT_SCANSTATUS] defined. */ SQLITE_API void sqlite3_stmt_scanstatus_reset(sqlite3_stmt*); /* ** CAPI3REF: Flush caches to disk mid-transaction ** ** ^If a write-transaction is open on [database connection] D when the ** [sqlite3_db_cacheflush(D)] interface invoked, any dirty ** pages in the pager-cache that are not currently in use are written out ** to disk. A dirty page may be in use if a database cursor created by an ** active SQL statement is reading from it, or if it is page 1 of a database ** file (page 1 is always "in use"). ^The [sqlite3_db_cacheflush(D)] ** interface flushes caches for all schemas - "main", "temp", and ** any [attached] databases. ** ** ^If this function needs to obtain extra database locks before dirty pages ** can be flushed to disk, it does so. ^If those locks cannot be obtained ** immediately and there is a busy-handler callback configured, it is invoked ** in the usual manner. ^If the required lock still cannot be obtained, then ** the database is skipped and an attempt made to flush any dirty pages ** belonging to the next (if any) database. ^If any databases are skipped ** because locks cannot be obtained, but no other error occurs, this ** function returns SQLITE_BUSY. ** ** ^If any other error occurs while flushing dirty pages to disk (for ** example an IO error or out-of-memory condition), then processing is ** abandoned and an SQLite [error code] is returned to the caller immediately. ** ** ^Otherwise, if no error occurs, [sqlite3_db_cacheflush()] returns SQLITE_OK. ** ** ^This function does not set the database handle error code or message ** returned by the [sqlite3_errcode()] and [sqlite3_errmsg()] functions. */ SQLITE_API int sqlite3_db_cacheflush(sqlite3*); /* ** CAPI3REF: The pre-update hook. ** ** ^These interfaces are only available if SQLite is compiled using the ** [SQLITE_ENABLE_PREUPDATE_HOOK] compile-time option. ** ** ^The [sqlite3_preupdate_hook()] interface registers a callback function ** that is invoked prior to each [INSERT], [UPDATE], and [DELETE] operation ** on a [rowid table]. ** ^At most one preupdate hook may be registered at a time on a single ** [database connection]; each call to [sqlite3_preupdate_hook()] overrides ** the previous setting. ** ^The preupdate hook is disabled by invoking [sqlite3_preupdate_hook()] ** with a NULL pointer as the second parameter. ** ^The third parameter to [sqlite3_preupdate_hook()] is passed through as ** the first parameter to callbacks. ** ** ^The preupdate hook only fires for changes to [rowid tables]; the preupdate ** hook is not invoked for changes to [virtual tables] or [WITHOUT ROWID] ** tables. ** ** ^The second parameter to the preupdate callback is a pointer to ** the [database connection] that registered the preupdate hook. ** ^The third parameter to the preupdate callback is one of the constants ** [SQLITE_INSERT], [SQLITE_DELETE], or [SQLITE_UPDATE] to identify the ** kind of update operation that is about to occur. ** ^(The fourth parameter to the preupdate callback is the name of the ** database within the database connection that is being modified. This ** will be "main" for the main database or "temp" for TEMP tables or ** the name given after the AS keyword in the [ATTACH] statement for attached ** databases.)^ ** ^The fifth parameter to the preupdate callback is the name of the ** table that is being modified. ** ^The sixth parameter to the preupdate callback is the initial [rowid] of the ** row being changes for SQLITE_UPDATE and SQLITE_DELETE changes and is ** undefined for SQLITE_INSERT changes. ** ^The seventh parameter to the preupdate callback is the final [rowid] of ** the row being changed for SQLITE_UPDATE and SQLITE_INSERT changes and is ** undefined for SQLITE_DELETE changes. ** ** The [sqlite3_preupdate_old()], [sqlite3_preupdate_new()], ** [sqlite3_preupdate_count()], and [sqlite3_preupdate_depth()] interfaces ** provide additional information about a preupdate event. These routines ** may only be called from within a preupdate callback. Invoking any of ** these routines from outside of a preupdate callback or with a ** [database connection] pointer that is different from the one supplied ** to the preupdate callback results in undefined and probably undesirable ** behavior. ** ** ^The [sqlite3_preupdate_count(D)] interface returns the number of columns ** in the row that is being inserted, updated, or deleted. ** ** ^The [sqlite3_preupdate_old(D,N,P)] interface writes into P a pointer to ** a [protected sqlite3_value] that contains the value of the Nth column of ** the table row before it is updated. The N parameter must be between 0 ** and one less than the number of columns or the behavior will be ** undefined. This must only be used within SQLITE_UPDATE and SQLITE_DELETE ** preupdate callbacks; if it is used by an SQLITE_INSERT callback then the ** behavior is undefined. The [sqlite3_value] that P points to ** will be destroyed when the preupdate callback returns. ** ** ^The [sqlite3_preupdate_new(D,N,P)] interface writes into P a pointer to ** a [protected sqlite3_value] that contains the value of the Nth column of ** the table row after it is updated. The N parameter must be between 0 ** and one less than the number of columns or the behavior will be ** undefined. This must only be used within SQLITE_INSERT and SQLITE_UPDATE ** preupdate callbacks; if it is used by an SQLITE_DELETE callback then the ** behavior is undefined. The [sqlite3_value] that P points to ** will be destroyed when the preupdate callback returns. ** ** ^The [sqlite3_preupdate_depth(D)] interface returns 0 if the preupdate ** callback was invoked as a result of a direct insert, update, or delete ** operation; or 1 for inserts, updates, or deletes invoked by top-level ** triggers; or 2 for changes resulting from triggers called by top-level ** triggers; and so forth. ** ** See also: [sqlite3_update_hook()] */ SQLITE_API SQLITE_EXPERIMENTAL void *sqlite3_preupdate_hook( sqlite3 *db, void(*xPreUpdate)( void *pCtx, /* Copy of third arg to preupdate_hook() */ sqlite3 *db, /* Database handle */ int op, /* SQLITE_UPDATE, DELETE or INSERT */ char const *zDb, /* Database name */ char const *zName, /* Table name */ sqlite3_int64 iKey1, /* Rowid of row about to be deleted/updated */ sqlite3_int64 iKey2 /* New rowid value (for a rowid UPDATE) */ ), void* ); SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_preupdate_old(sqlite3 *, int, sqlite3_value **); SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_preupdate_count(sqlite3 *); SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_preupdate_depth(sqlite3 *); SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_preupdate_new(sqlite3 *, int, sqlite3_value **); /* ** CAPI3REF: Low-level system error code ** ** ^Attempt to return the underlying operating system error code or error ** number that caused the most recent I/O error or failure to open a file. ** The return value is OS-dependent. For example, on unix systems, after ** [sqlite3_open_v2()] returns [SQLITE_CANTOPEN], this interface could be ** called to get back the underlying "errno" that caused the problem, such ** as ENOSPC, EAUTH, EISDIR, and so forth. */ SQLITE_API int sqlite3_system_errno(sqlite3*); /* ** CAPI3REF: Database Snapshot ** KEYWORDS: {snapshot} ** EXPERIMENTAL ** ** An instance of the snapshot object records the state of a [WAL mode] ** database for some specific point in history. ** ** In [WAL mode], multiple [database connections] that are open on the ** same database file can each be reading a different historical version ** of the database file. When a [database connection] begins a read ** transaction, that connection sees an unchanging copy of the database ** as it existed for the point in time when the transaction first started. ** Subsequent changes to the database from other connections are not seen ** by the reader until a new read transaction is started. ** ** The sqlite3_snapshot object records state information about an historical ** version of the database file so that it is possible to later open a new read ** transaction that sees that historical version of the database rather than ** the most recent version. ** ** The constructor for this object is [sqlite3_snapshot_get()]. The ** [sqlite3_snapshot_open()] method causes a fresh read transaction to refer ** to an historical snapshot (if possible). The destructor for ** sqlite3_snapshot objects is [sqlite3_snapshot_free()]. */ typedef struct sqlite3_snapshot sqlite3_snapshot; /* ** CAPI3REF: Record A Database Snapshot ** EXPERIMENTAL ** ** ^The [sqlite3_snapshot_get(D,S,P)] interface attempts to make a ** new [sqlite3_snapshot] object that records the current state of ** schema S in database connection D. ^On success, the ** [sqlite3_snapshot_get(D,S,P)] interface writes a pointer to the newly ** created [sqlite3_snapshot] object into *P and returns SQLITE_OK. ** ^If schema S of [database connection] D is not a [WAL mode] database ** that is in a read transaction, then [sqlite3_snapshot_get(D,S,P)] ** leaves the *P value unchanged and returns an appropriate [error code]. ** ** The [sqlite3_snapshot] object returned from a successful call to ** [sqlite3_snapshot_get()] must be freed using [sqlite3_snapshot_free()] ** to avoid a memory leak. ** ** The [sqlite3_snapshot_get()] interface is only available when the ** SQLITE_ENABLE_SNAPSHOT compile-time option is used. */ SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_snapshot_get( sqlite3 *db, const char *zSchema, sqlite3_snapshot **ppSnapshot ); /* ** CAPI3REF: Start a read transaction on an historical snapshot ** EXPERIMENTAL ** ** ^The [sqlite3_snapshot_open(D,S,P)] interface starts a ** read transaction for schema S of ** [database connection] D such that the read transaction ** refers to historical [snapshot] P, rather than the most ** recent change to the database. ** ^The [sqlite3_snapshot_open()] interface returns SQLITE_OK on success ** or an appropriate [error code] if it fails. ** ** ^In order to succeed, a call to [sqlite3_snapshot_open(D,S,P)] must be ** the first operation following the [BEGIN] that takes the schema S ** out of [autocommit mode]. ** ^In other words, schema S must not currently be in ** a transaction for [sqlite3_snapshot_open(D,S,P)] to work, but the ** database connection D must be out of [autocommit mode]. ** ^A [snapshot] will fail to open if it has been overwritten by a ** [checkpoint]. ** ^(A call to [sqlite3_snapshot_open(D,S,P)] will fail if the ** database connection D does not know that the database file for ** schema S is in [WAL mode]. A database connection might not know ** that the database file is in [WAL mode] if there has been no prior ** I/O on that database connection, or if the database entered [WAL mode] ** after the most recent I/O on the database connection.)^ ** (Hint: Run "[PRAGMA application_id]" against a newly opened ** database connection in order to make it ready to use snapshots.) ** ** The [sqlite3_snapshot_open()] interface is only available when the ** SQLITE_ENABLE_SNAPSHOT compile-time option is used. */ SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_snapshot_open( sqlite3 *db, const char *zSchema, sqlite3_snapshot *pSnapshot ); /* ** CAPI3REF: Destroy a snapshot ** EXPERIMENTAL ** ** ^The [sqlite3_snapshot_free(P)] interface destroys [sqlite3_snapshot] P. ** The application must eventually free every [sqlite3_snapshot] object ** using this routine to avoid a memory leak. ** ** The [sqlite3_snapshot_free()] interface is only available when the ** SQLITE_ENABLE_SNAPSHOT compile-time option is used. */ SQLITE_API SQLITE_EXPERIMENTAL void sqlite3_snapshot_free(sqlite3_snapshot*); /* ** CAPI3REF: Compare the ages of two snapshot handles. ** EXPERIMENTAL ** ** The sqlite3_snapshot_cmp(P1, P2) interface is used to compare the ages ** of two valid snapshot handles. ** ** If the two snapshot handles are not associated with the same database ** file, the result of the comparison is undefined. ** ** Additionally, the result of the comparison is only valid if both of the ** snapshot handles were obtained by calling sqlite3_snapshot_get() since the ** last time the wal file was deleted. The wal file is deleted when the ** database is changed back to rollback mode or when the number of database ** clients drops to zero. If either snapshot handle was obtained before the ** wal file was last deleted, the value returned by this function ** is undefined. ** ** Otherwise, this API returns a negative value if P1 refers to an older ** snapshot than P2, zero if the two handles refer to the same database ** snapshot, and a positive value if P1 is a newer snapshot than P2. */ SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_snapshot_cmp( sqlite3_snapshot *p1, sqlite3_snapshot *p2 ); /* ** Undo the hack that converts floating point types to integer for ** builds on processors without floating point support. */ #ifdef SQLITE_OMIT_FLOATING_POINT # undef double #endif #if 0 } /* End of the 'extern "C"' block */ #endif #endif /* SQLITE3_H */ /******** Begin file sqlite3rtree.h *********/ /* ** 2010 August 30 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ************************************************************************* */ #ifndef _SQLITE3RTREE_H_ #define _SQLITE3RTREE_H_ #if 0 extern "C" { #endif typedef struct sqlite3_rtree_geometry sqlite3_rtree_geometry; typedef struct sqlite3_rtree_query_info sqlite3_rtree_query_info; /* The double-precision datatype used by RTree depends on the ** SQLITE_RTREE_INT_ONLY compile-time option. */ #ifdef SQLITE_RTREE_INT_ONLY typedef sqlite3_int64 sqlite3_rtree_dbl; #else typedef double sqlite3_rtree_dbl; #endif /* ** Register a geometry callback named zGeom that can be used as part of an ** R-Tree geometry query as follows: ** ** SELECT ... FROM WHERE MATCH $zGeom(... params ...) */ SQLITE_API int sqlite3_rtree_geometry_callback( sqlite3 *db, const char *zGeom, int (*xGeom)(sqlite3_rtree_geometry*, int, sqlite3_rtree_dbl*,int*), void *pContext ); /* ** A pointer to a structure of the following type is passed as the first ** argument to callbacks registered using rtree_geometry_callback(). */ struct sqlite3_rtree_geometry { void *pContext; /* Copy of pContext passed to s_r_g_c() */ int nParam; /* Size of array aParam[] */ sqlite3_rtree_dbl *aParam; /* Parameters passed to SQL geom function */ void *pUser; /* Callback implementation user data */ void (*xDelUser)(void *); /* Called by SQLite to clean up pUser */ }; /* ** Register a 2nd-generation geometry callback named zScore that can be ** used as part of an R-Tree geometry query as follows: ** ** SELECT ... FROM WHERE MATCH $zQueryFunc(... params ...) */ SQLITE_API int sqlite3_rtree_query_callback( sqlite3 *db, const char *zQueryFunc, int (*xQueryFunc)(sqlite3_rtree_query_info*), void *pContext, void (*xDestructor)(void*) ); /* ** A pointer to a structure of the following type is passed as the ** argument to scored geometry callback registered using ** sqlite3_rtree_query_callback(). ** ** Note that the first 5 fields of this structure are identical to ** sqlite3_rtree_geometry. This structure is a subclass of ** sqlite3_rtree_geometry. */ struct sqlite3_rtree_query_info { void *pContext; /* pContext from when function registered */ int nParam; /* Number of function parameters */ sqlite3_rtree_dbl *aParam; /* value of function parameters */ void *pUser; /* callback can use this, if desired */ void (*xDelUser)(void*); /* function to free pUser */ sqlite3_rtree_dbl *aCoord; /* Coordinates of node or entry to check */ unsigned int *anQueue; /* Number of pending entries in the queue */ int nCoord; /* Number of coordinates */ int iLevel; /* Level of current node or entry */ int mxLevel; /* The largest iLevel value in the tree */ sqlite3_int64 iRowid; /* Rowid for current entry */ sqlite3_rtree_dbl rParentScore; /* Score of parent node */ int eParentWithin; /* Visibility of parent node */ int eWithin; /* OUT: Visiblity */ sqlite3_rtree_dbl rScore; /* OUT: Write the score here */ /* The following fields are only available in 3.8.11 and later */ sqlite3_value **apSqlParam; /* Original SQL values of parameters */ }; /* ** Allowed values for sqlite3_rtree_query.eWithin and .eParentWithin. */ #define NOT_WITHIN 0 /* Object completely outside of query region */ #define PARTLY_WITHIN 1 /* Object partially overlaps query region */ #define FULLY_WITHIN 2 /* Object fully contained within query region */ #if 0 } /* end of the 'extern "C"' block */ #endif #endif /* ifndef _SQLITE3RTREE_H_ */ /******** End of sqlite3rtree.h *********/ /******** Begin file sqlite3session.h *********/ #if !defined(__SQLITESESSION_H_) && defined(SQLITE_ENABLE_SESSION) #define __SQLITESESSION_H_ 1 /* ** Make sure we can call this stuff from C++. */ #if 0 extern "C" { #endif /* ** CAPI3REF: Session Object Handle */ typedef struct sqlite3_session sqlite3_session; /* ** CAPI3REF: Changeset Iterator Handle */ typedef struct sqlite3_changeset_iter sqlite3_changeset_iter; /* ** CAPI3REF: Create A New Session Object ** ** Create a new session object attached to database handle db. If successful, ** a pointer to the new object is written to *ppSession and SQLITE_OK is ** returned. If an error occurs, *ppSession is set to NULL and an SQLite ** error code (e.g. SQLITE_NOMEM) is returned. ** ** It is possible to create multiple session objects attached to a single ** database handle. ** ** Session objects created using this function should be deleted using the ** [sqlite3session_delete()] function before the database handle that they ** are attached to is itself closed. If the database handle is closed before ** the session object is deleted, then the results of calling any session ** module function, including [sqlite3session_delete()] on the session object ** are undefined. ** ** Because the session module uses the [sqlite3_preupdate_hook()] API, it ** is not possible for an application to register a pre-update hook on a ** database handle that has one or more session objects attached. Nor is ** it possible to create a session object attached to a database handle for ** which a pre-update hook is already defined. The results of attempting ** either of these things are undefined. ** ** The session object will be used to create changesets for tables in ** database zDb, where zDb is either "main", or "temp", or the name of an ** attached database. It is not an error if database zDb is not attached ** to the database when the session object is created. */ int sqlite3session_create( sqlite3 *db, /* Database handle */ const char *zDb, /* Name of db (e.g. "main") */ sqlite3_session **ppSession /* OUT: New session object */ ); /* ** CAPI3REF: Delete A Session Object ** ** Delete a session object previously allocated using ** [sqlite3session_create()]. Once a session object has been deleted, the ** results of attempting to use pSession with any other session module ** function are undefined. ** ** Session objects must be deleted before the database handle to which they ** are attached is closed. Refer to the documentation for ** [sqlite3session_create()] for details. */ void sqlite3session_delete(sqlite3_session *pSession); /* ** CAPI3REF: Enable Or Disable A Session Object ** ** Enable or disable the recording of changes by a session object. When ** enabled, a session object records changes made to the database. When ** disabled - it does not. A newly created session object is enabled. ** Refer to the documentation for [sqlite3session_changeset()] for further ** details regarding how enabling and disabling a session object affects ** the eventual changesets. ** ** Passing zero to this function disables the session. Passing a value ** greater than zero enables it. Passing a value less than zero is a ** no-op, and may be used to query the current state of the session. ** ** The return value indicates the final state of the session object: 0 if ** the session is disabled, or 1 if it is enabled. */ int sqlite3session_enable(sqlite3_session *pSession, int bEnable); /* ** CAPI3REF: Set Or Clear the Indirect Change Flag ** ** Each change recorded by a session object is marked as either direct or ** indirect. A change is marked as indirect if either: ** **
    **
  • The session object "indirect" flag is set when the change is ** made, or **
  • The change is made by an SQL trigger or foreign key action ** instead of directly as a result of a users SQL statement. **
** ** If a single row is affected by more than one operation within a session, ** then the change is considered indirect if all operations meet the criteria ** for an indirect change above, or direct otherwise. ** ** This function is used to set, clear or query the session object indirect ** flag. If the second argument passed to this function is zero, then the ** indirect flag is cleared. If it is greater than zero, the indirect flag ** is set. Passing a value less than zero does not modify the current value ** of the indirect flag, and may be used to query the current state of the ** indirect flag for the specified session object. ** ** The return value indicates the final state of the indirect flag: 0 if ** it is clear, or 1 if it is set. */ int sqlite3session_indirect(sqlite3_session *pSession, int bIndirect); /* ** CAPI3REF: Attach A Table To A Session Object ** ** If argument zTab is not NULL, then it is the name of a table to attach ** to the session object passed as the first argument. All subsequent changes ** made to the table while the session object is enabled will be recorded. See ** documentation for [sqlite3session_changeset()] for further details. ** ** Or, if argument zTab is NULL, then changes are recorded for all tables ** in the database. If additional tables are added to the database (by ** executing "CREATE TABLE" statements) after this call is made, changes for ** the new tables are also recorded. ** ** Changes can only be recorded for tables that have a PRIMARY KEY explicitly ** defined as part of their CREATE TABLE statement. It does not matter if the ** PRIMARY KEY is an "INTEGER PRIMARY KEY" (rowid alias) or not. The PRIMARY ** KEY may consist of a single column, or may be a composite key. ** ** It is not an error if the named table does not exist in the database. Nor ** is it an error if the named table does not have a PRIMARY KEY. However, ** no changes will be recorded in either of these scenarios. ** ** Changes are not recorded for individual rows that have NULL values stored ** in one or more of their PRIMARY KEY columns. ** ** SQLITE_OK is returned if the call completes without error. Or, if an error ** occurs, an SQLite error code (e.g. SQLITE_NOMEM) is returned. */ int sqlite3session_attach( sqlite3_session *pSession, /* Session object */ const char *zTab /* Table name */ ); /* ** CAPI3REF: Set a table filter on a Session Object. ** ** The second argument (xFilter) is the "filter callback". For changes to rows ** in tables that are not attached to the Session object, the filter is called ** to determine whether changes to the table's rows should be tracked or not. ** If xFilter returns 0, changes is not tracked. Note that once a table is ** attached, xFilter will not be called again. */ void sqlite3session_table_filter( sqlite3_session *pSession, /* Session object */ int(*xFilter)( void *pCtx, /* Copy of third arg to _filter_table() */ const char *zTab /* Table name */ ), void *pCtx /* First argument passed to xFilter */ ); /* ** CAPI3REF: Generate A Changeset From A Session Object ** ** Obtain a changeset containing changes to the tables attached to the ** session object passed as the first argument. If successful, ** set *ppChangeset to point to a buffer containing the changeset ** and *pnChangeset to the size of the changeset in bytes before returning ** SQLITE_OK. If an error occurs, set both *ppChangeset and *pnChangeset to ** zero and return an SQLite error code. ** ** A changeset consists of zero or more INSERT, UPDATE and/or DELETE changes, ** each representing a change to a single row of an attached table. An INSERT ** change contains the values of each field of a new database row. A DELETE ** contains the original values of each field of a deleted database row. An ** UPDATE change contains the original values of each field of an updated ** database row along with the updated values for each updated non-primary-key ** column. It is not possible for an UPDATE change to represent a change that ** modifies the values of primary key columns. If such a change is made, it ** is represented in a changeset as a DELETE followed by an INSERT. ** ** Changes are not recorded for rows that have NULL values stored in one or ** more of their PRIMARY KEY columns. If such a row is inserted or deleted, ** no corresponding change is present in the changesets returned by this ** function. If an existing row with one or more NULL values stored in ** PRIMARY KEY columns is updated so that all PRIMARY KEY columns are non-NULL, ** only an INSERT is appears in the changeset. Similarly, if an existing row ** with non-NULL PRIMARY KEY values is updated so that one or more of its ** PRIMARY KEY columns are set to NULL, the resulting changeset contains a ** DELETE change only. ** ** The contents of a changeset may be traversed using an iterator created ** using the [sqlite3changeset_start()] API. A changeset may be applied to ** a database with a compatible schema using the [sqlite3changeset_apply()] ** API. ** ** Within a changeset generated by this function, all changes related to a ** single table are grouped together. In other words, when iterating through ** a changeset or when applying a changeset to a database, all changes related ** to a single table are processed before moving on to the next table. Tables ** are sorted in the same order in which they were attached (or auto-attached) ** to the sqlite3_session object. The order in which the changes related to ** a single table are stored is undefined. ** ** Following a successful call to this function, it is the responsibility of ** the caller to eventually free the buffer that *ppChangeset points to using ** [sqlite3_free()]. ** **

Changeset Generation

** ** Once a table has been attached to a session object, the session object ** records the primary key values of all new rows inserted into the table. ** It also records the original primary key and other column values of any ** deleted or updated rows. For each unique primary key value, data is only ** recorded once - the first time a row with said primary key is inserted, ** updated or deleted in the lifetime of the session. ** ** There is one exception to the previous paragraph: when a row is inserted, ** updated or deleted, if one or more of its primary key columns contain a ** NULL value, no record of the change is made. ** ** The session object therefore accumulates two types of records - those ** that consist of primary key values only (created when the user inserts ** a new record) and those that consist of the primary key values and the ** original values of other table columns (created when the users deletes ** or updates a record). ** ** When this function is called, the requested changeset is created using ** both the accumulated records and the current contents of the database ** file. Specifically: ** **
    **
  • For each record generated by an insert, the database is queried ** for a row with a matching primary key. If one is found, an INSERT ** change is added to the changeset. If no such row is found, no change ** is added to the changeset. ** **
  • For each record generated by an update or delete, the database is ** queried for a row with a matching primary key. If such a row is ** found and one or more of the non-primary key fields have been ** modified from their original values, an UPDATE change is added to ** the changeset. Or, if no such row is found in the table, a DELETE ** change is added to the changeset. If there is a row with a matching ** primary key in the database, but all fields contain their original ** values, no change is added to the changeset. **
** ** This means, amongst other things, that if a row is inserted and then later ** deleted while a session object is active, neither the insert nor the delete ** will be present in the changeset. Or if a row is deleted and then later a ** row with the same primary key values inserted while a session object is ** active, the resulting changeset will contain an UPDATE change instead of ** a DELETE and an INSERT. ** ** When a session object is disabled (see the [sqlite3session_enable()] API), ** it does not accumulate records when rows are inserted, updated or deleted. ** This may appear to have some counter-intuitive effects if a single row ** is written to more than once during a session. For example, if a row ** is inserted while a session object is enabled, then later deleted while ** the same session object is disabled, no INSERT record will appear in the ** changeset, even though the delete took place while the session was disabled. ** Or, if one field of a row is updated while a session is disabled, and ** another field of the same row is updated while the session is enabled, the ** resulting changeset will contain an UPDATE change that updates both fields. */ int sqlite3session_changeset( sqlite3_session *pSession, /* Session object */ int *pnChangeset, /* OUT: Size of buffer at *ppChangeset */ void **ppChangeset /* OUT: Buffer containing changeset */ ); /* ** CAPI3REF: Load The Difference Between Tables Into A Session ** ** If it is not already attached to the session object passed as the first ** argument, this function attaches table zTbl in the same manner as the ** [sqlite3session_attach()] function. If zTbl does not exist, or if it ** does not have a primary key, this function is a no-op (but does not return ** an error). ** ** Argument zFromDb must be the name of a database ("main", "temp" etc.) ** attached to the same database handle as the session object that contains ** a table compatible with the table attached to the session by this function. ** A table is considered compatible if it: ** **
    **
  • Has the same name, **
  • Has the same set of columns declared in the same order, and **
  • Has the same PRIMARY KEY definition. **
** ** If the tables are not compatible, SQLITE_SCHEMA is returned. If the tables ** are compatible but do not have any PRIMARY KEY columns, it is not an error ** but no changes are added to the session object. As with other session ** APIs, tables without PRIMARY KEYs are simply ignored. ** ** This function adds a set of changes to the session object that could be ** used to update the table in database zFrom (call this the "from-table") ** so that its content is the same as the table attached to the session ** object (call this the "to-table"). Specifically: ** **
    **
  • For each row (primary key) that exists in the to-table but not in ** the from-table, an INSERT record is added to the session object. ** **
  • For each row (primary key) that exists in the to-table but not in ** the from-table, a DELETE record is added to the session object. ** **
  • For each row (primary key) that exists in both tables, but features ** different in each, an UPDATE record is added to the session. **
** ** To clarify, if this function is called and then a changeset constructed ** using [sqlite3session_changeset()], then after applying that changeset to ** database zFrom the contents of the two compatible tables would be ** identical. ** ** It an error if database zFrom does not exist or does not contain the ** required compatible table. ** ** If the operation successful, SQLITE_OK is returned. Otherwise, an SQLite ** error code. In this case, if argument pzErrMsg is not NULL, *pzErrMsg ** may be set to point to a buffer containing an English language error ** message. It is the responsibility of the caller to free this buffer using ** sqlite3_free(). */ int sqlite3session_diff( sqlite3_session *pSession, const char *zFromDb, const char *zTbl, char **pzErrMsg ); /* ** CAPI3REF: Generate A Patchset From A Session Object ** ** The differences between a patchset and a changeset are that: ** **
    **
  • DELETE records consist of the primary key fields only. The ** original values of other fields are omitted. **
  • The original values of any modified fields are omitted from ** UPDATE records. **
** ** A patchset blob may be used with up to date versions of all ** sqlite3changeset_xxx API functions except for sqlite3changeset_invert(), ** which returns SQLITE_CORRUPT if it is passed a patchset. Similarly, ** attempting to use a patchset blob with old versions of the ** sqlite3changeset_xxx APIs also provokes an SQLITE_CORRUPT error. ** ** Because the non-primary key "old.*" fields are omitted, no ** SQLITE_CHANGESET_DATA conflicts can be detected or reported if a patchset ** is passed to the sqlite3changeset_apply() API. Other conflict types work ** in the same way as for changesets. ** ** Changes within a patchset are ordered in the same way as for changesets ** generated by the sqlite3session_changeset() function (i.e. all changes for ** a single table are grouped together, tables appear in the order in which ** they were attached to the session object). */ int sqlite3session_patchset( sqlite3_session *pSession, /* Session object */ int *pnPatchset, /* OUT: Size of buffer at *ppChangeset */ void **ppPatchset /* OUT: Buffer containing changeset */ ); /* ** CAPI3REF: Test if a changeset has recorded any changes. ** ** Return non-zero if no changes to attached tables have been recorded by ** the session object passed as the first argument. Otherwise, if one or ** more changes have been recorded, return zero. ** ** Even if this function returns zero, it is possible that calling ** [sqlite3session_changeset()] on the session handle may still return a ** changeset that contains no changes. This can happen when a row in ** an attached table is modified and then later on the original values ** are restored. However, if this function returns non-zero, then it is ** guaranteed that a call to sqlite3session_changeset() will return a ** changeset containing zero changes. */ int sqlite3session_isempty(sqlite3_session *pSession); /* ** CAPI3REF: Create An Iterator To Traverse A Changeset ** ** Create an iterator used to iterate through the contents of a changeset. ** If successful, *pp is set to point to the iterator handle and SQLITE_OK ** is returned. Otherwise, if an error occurs, *pp is set to zero and an ** SQLite error code is returned. ** ** The following functions can be used to advance and query a changeset ** iterator created by this function: ** **
    **
  • [sqlite3changeset_next()] **
  • [sqlite3changeset_op()] **
  • [sqlite3changeset_new()] **
  • [sqlite3changeset_old()] **
** ** It is the responsibility of the caller to eventually destroy the iterator ** by passing it to [sqlite3changeset_finalize()]. The buffer containing the ** changeset (pChangeset) must remain valid until after the iterator is ** destroyed. ** ** Assuming the changeset blob was created by one of the ** [sqlite3session_changeset()], [sqlite3changeset_concat()] or ** [sqlite3changeset_invert()] functions, all changes within the changeset ** that apply to a single table are grouped together. This means that when ** an application iterates through a changeset using an iterator created by ** this function, all changes that relate to a single table are visited ** consecutively. There is no chance that the iterator will visit a change ** the applies to table X, then one for table Y, and then later on visit ** another change for table X. */ int sqlite3changeset_start( sqlite3_changeset_iter **pp, /* OUT: New changeset iterator handle */ int nChangeset, /* Size of changeset blob in bytes */ void *pChangeset /* Pointer to blob containing changeset */ ); /* ** CAPI3REF: Advance A Changeset Iterator ** ** This function may only be used with iterators created by function ** [sqlite3changeset_start()]. If it is called on an iterator passed to ** a conflict-handler callback by [sqlite3changeset_apply()], SQLITE_MISUSE ** is returned and the call has no effect. ** ** Immediately after an iterator is created by sqlite3changeset_start(), it ** does not point to any change in the changeset. Assuming the changeset ** is not empty, the first call to this function advances the iterator to ** point to the first change in the changeset. Each subsequent call advances ** the iterator to point to the next change in the changeset (if any). If ** no error occurs and the iterator points to a valid change after a call ** to sqlite3changeset_next() has advanced it, SQLITE_ROW is returned. ** Otherwise, if all changes in the changeset have already been visited, ** SQLITE_DONE is returned. ** ** If an error occurs, an SQLite error code is returned. Possible error ** codes include SQLITE_CORRUPT (if the changeset buffer is corrupt) or ** SQLITE_NOMEM. */ int sqlite3changeset_next(sqlite3_changeset_iter *pIter); /* ** CAPI3REF: Obtain The Current Operation From A Changeset Iterator ** ** The pIter argument passed to this function may either be an iterator ** passed to a conflict-handler by [sqlite3changeset_apply()], or an iterator ** created by [sqlite3changeset_start()]. In the latter case, the most recent ** call to [sqlite3changeset_next()] must have returned [SQLITE_ROW]. If this ** is not the case, this function returns [SQLITE_MISUSE]. ** ** If argument pzTab is not NULL, then *pzTab is set to point to a ** nul-terminated utf-8 encoded string containing the name of the table ** affected by the current change. The buffer remains valid until either ** sqlite3changeset_next() is called on the iterator or until the ** conflict-handler function returns. If pnCol is not NULL, then *pnCol is ** set to the number of columns in the table affected by the change. If ** pbIncorrect is not NULL, then *pbIndirect is set to true (1) if the change ** is an indirect change, or false (0) otherwise. See the documentation for ** [sqlite3session_indirect()] for a description of direct and indirect ** changes. Finally, if pOp is not NULL, then *pOp is set to one of ** [SQLITE_INSERT], [SQLITE_DELETE] or [SQLITE_UPDATE], depending on the ** type of change that the iterator currently points to. ** ** If no error occurs, SQLITE_OK is returned. If an error does occur, an ** SQLite error code is returned. The values of the output variables may not ** be trusted in this case. */ int sqlite3changeset_op( sqlite3_changeset_iter *pIter, /* Iterator object */ const char **pzTab, /* OUT: Pointer to table name */ int *pnCol, /* OUT: Number of columns in table */ int *pOp, /* OUT: SQLITE_INSERT, DELETE or UPDATE */ int *pbIndirect /* OUT: True for an 'indirect' change */ ); /* ** CAPI3REF: Obtain The Primary Key Definition Of A Table ** ** For each modified table, a changeset includes the following: ** **
    **
  • The number of columns in the table, and **
  • Which of those columns make up the tables PRIMARY KEY. **
** ** This function is used to find which columns comprise the PRIMARY KEY of ** the table modified by the change that iterator pIter currently points to. ** If successful, *pabPK is set to point to an array of nCol entries, where ** nCol is the number of columns in the table. Elements of *pabPK are set to ** 0x01 if the corresponding column is part of the tables primary key, or ** 0x00 if it is not. ** ** If argument pnCol is not NULL, then *pnCol is set to the number of columns ** in the table. ** ** If this function is called when the iterator does not point to a valid ** entry, SQLITE_MISUSE is returned and the output variables zeroed. Otherwise, ** SQLITE_OK is returned and the output variables populated as described ** above. */ int sqlite3changeset_pk( sqlite3_changeset_iter *pIter, /* Iterator object */ unsigned char **pabPK, /* OUT: Array of boolean - true for PK cols */ int *pnCol /* OUT: Number of entries in output array */ ); /* ** CAPI3REF: Obtain old.* Values From A Changeset Iterator ** ** The pIter argument passed to this function may either be an iterator ** passed to a conflict-handler by [sqlite3changeset_apply()], or an iterator ** created by [sqlite3changeset_start()]. In the latter case, the most recent ** call to [sqlite3changeset_next()] must have returned SQLITE_ROW. ** Furthermore, it may only be called if the type of change that the iterator ** currently points to is either [SQLITE_DELETE] or [SQLITE_UPDATE]. Otherwise, ** this function returns [SQLITE_MISUSE] and sets *ppValue to NULL. ** ** Argument iVal must be greater than or equal to 0, and less than the number ** of columns in the table affected by the current change. Otherwise, ** [SQLITE_RANGE] is returned and *ppValue is set to NULL. ** ** If successful, this function sets *ppValue to point to a protected ** sqlite3_value object containing the iVal'th value from the vector of ** original row values stored as part of the UPDATE or DELETE change and ** returns SQLITE_OK. The name of the function comes from the fact that this ** is similar to the "old.*" columns available to update or delete triggers. ** ** If some other error occurs (e.g. an OOM condition), an SQLite error code ** is returned and *ppValue is set to NULL. */ int sqlite3changeset_old( sqlite3_changeset_iter *pIter, /* Changeset iterator */ int iVal, /* Column number */ sqlite3_value **ppValue /* OUT: Old value (or NULL pointer) */ ); /* ** CAPI3REF: Obtain new.* Values From A Changeset Iterator ** ** The pIter argument passed to this function may either be an iterator ** passed to a conflict-handler by [sqlite3changeset_apply()], or an iterator ** created by [sqlite3changeset_start()]. In the latter case, the most recent ** call to [sqlite3changeset_next()] must have returned SQLITE_ROW. ** Furthermore, it may only be called if the type of change that the iterator ** currently points to is either [SQLITE_UPDATE] or [SQLITE_INSERT]. Otherwise, ** this function returns [SQLITE_MISUSE] and sets *ppValue to NULL. ** ** Argument iVal must be greater than or equal to 0, and less than the number ** of columns in the table affected by the current change. Otherwise, ** [SQLITE_RANGE] is returned and *ppValue is set to NULL. ** ** If successful, this function sets *ppValue to point to a protected ** sqlite3_value object containing the iVal'th value from the vector of ** new row values stored as part of the UPDATE or INSERT change and ** returns SQLITE_OK. If the change is an UPDATE and does not include ** a new value for the requested column, *ppValue is set to NULL and ** SQLITE_OK returned. The name of the function comes from the fact that ** this is similar to the "new.*" columns available to update or delete ** triggers. ** ** If some other error occurs (e.g. an OOM condition), an SQLite error code ** is returned and *ppValue is set to NULL. */ int sqlite3changeset_new( sqlite3_changeset_iter *pIter, /* Changeset iterator */ int iVal, /* Column number */ sqlite3_value **ppValue /* OUT: New value (or NULL pointer) */ ); /* ** CAPI3REF: Obtain Conflicting Row Values From A Changeset Iterator ** ** This function should only be used with iterator objects passed to a ** conflict-handler callback by [sqlite3changeset_apply()] with either ** [SQLITE_CHANGESET_DATA] or [SQLITE_CHANGESET_CONFLICT]. If this function ** is called on any other iterator, [SQLITE_MISUSE] is returned and *ppValue ** is set to NULL. ** ** Argument iVal must be greater than or equal to 0, and less than the number ** of columns in the table affected by the current change. Otherwise, ** [SQLITE_RANGE] is returned and *ppValue is set to NULL. ** ** If successful, this function sets *ppValue to point to a protected ** sqlite3_value object containing the iVal'th value from the ** "conflicting row" associated with the current conflict-handler callback ** and returns SQLITE_OK. ** ** If some other error occurs (e.g. an OOM condition), an SQLite error code ** is returned and *ppValue is set to NULL. */ int sqlite3changeset_conflict( sqlite3_changeset_iter *pIter, /* Changeset iterator */ int iVal, /* Column number */ sqlite3_value **ppValue /* OUT: Value from conflicting row */ ); /* ** CAPI3REF: Determine The Number Of Foreign Key Constraint Violations ** ** This function may only be called with an iterator passed to an ** SQLITE_CHANGESET_FOREIGN_KEY conflict handler callback. In this case ** it sets the output variable to the total number of known foreign key ** violations in the destination database and returns SQLITE_OK. ** ** In all other cases this function returns SQLITE_MISUSE. */ int sqlite3changeset_fk_conflicts( sqlite3_changeset_iter *pIter, /* Changeset iterator */ int *pnOut /* OUT: Number of FK violations */ ); /* ** CAPI3REF: Finalize A Changeset Iterator ** ** This function is used to finalize an iterator allocated with ** [sqlite3changeset_start()]. ** ** This function should only be called on iterators created using the ** [sqlite3changeset_start()] function. If an application calls this ** function with an iterator passed to a conflict-handler by ** [sqlite3changeset_apply()], [SQLITE_MISUSE] is immediately returned and the ** call has no effect. ** ** If an error was encountered within a call to an sqlite3changeset_xxx() ** function (for example an [SQLITE_CORRUPT] in [sqlite3changeset_next()] or an ** [SQLITE_NOMEM] in [sqlite3changeset_new()]) then an error code corresponding ** to that error is returned by this function. Otherwise, SQLITE_OK is ** returned. This is to allow the following pattern (pseudo-code): ** ** sqlite3changeset_start(); ** while( SQLITE_ROW==sqlite3changeset_next() ){ ** // Do something with change. ** } ** rc = sqlite3changeset_finalize(); ** if( rc!=SQLITE_OK ){ ** // An error has occurred ** } */ int sqlite3changeset_finalize(sqlite3_changeset_iter *pIter); /* ** CAPI3REF: Invert A Changeset ** ** This function is used to "invert" a changeset object. Applying an inverted ** changeset to a database reverses the effects of applying the uninverted ** changeset. Specifically: ** **
    **
  • Each DELETE change is changed to an INSERT, and **
  • Each INSERT change is changed to a DELETE, and **
  • For each UPDATE change, the old.* and new.* values are exchanged. **
** ** This function does not change the order in which changes appear within ** the changeset. It merely reverses the sense of each individual change. ** ** If successful, a pointer to a buffer containing the inverted changeset ** is stored in *ppOut, the size of the same buffer is stored in *pnOut, and ** SQLITE_OK is returned. If an error occurs, both *pnOut and *ppOut are ** zeroed and an SQLite error code returned. ** ** It is the responsibility of the caller to eventually call sqlite3_free() ** on the *ppOut pointer to free the buffer allocation following a successful ** call to this function. ** ** WARNING/TODO: This function currently assumes that the input is a valid ** changeset. If it is not, the results are undefined. */ int sqlite3changeset_invert( int nIn, const void *pIn, /* Input changeset */ int *pnOut, void **ppOut /* OUT: Inverse of input */ ); /* ** CAPI3REF: Concatenate Two Changeset Objects ** ** This function is used to concatenate two changesets, A and B, into a ** single changeset. The result is a changeset equivalent to applying ** changeset A followed by changeset B. ** ** This function combines the two input changesets using an ** sqlite3_changegroup object. Calling it produces similar results as the ** following code fragment: ** ** sqlite3_changegroup *pGrp; ** rc = sqlite3_changegroup_new(&pGrp); ** if( rc==SQLITE_OK ) rc = sqlite3changegroup_add(pGrp, nA, pA); ** if( rc==SQLITE_OK ) rc = sqlite3changegroup_add(pGrp, nB, pB); ** if( rc==SQLITE_OK ){ ** rc = sqlite3changegroup_output(pGrp, pnOut, ppOut); ** }else{ ** *ppOut = 0; ** *pnOut = 0; ** } ** ** Refer to the sqlite3_changegroup documentation below for details. */ int sqlite3changeset_concat( int nA, /* Number of bytes in buffer pA */ void *pA, /* Pointer to buffer containing changeset A */ int nB, /* Number of bytes in buffer pB */ void *pB, /* Pointer to buffer containing changeset B */ int *pnOut, /* OUT: Number of bytes in output changeset */ void **ppOut /* OUT: Buffer containing output changeset */ ); /* ** CAPI3REF: Changegroup Handle */ typedef struct sqlite3_changegroup sqlite3_changegroup; /* ** CAPI3REF: Create A New Changegroup Object ** ** An sqlite3_changegroup object is used to combine two or more changesets ** (or patchsets) into a single changeset (or patchset). A single changegroup ** object may combine changesets or patchsets, but not both. The output is ** always in the same format as the input. ** ** If successful, this function returns SQLITE_OK and populates (*pp) with ** a pointer to a new sqlite3_changegroup object before returning. The caller ** should eventually free the returned object using a call to ** sqlite3changegroup_delete(). If an error occurs, an SQLite error code ** (i.e. SQLITE_NOMEM) is returned and *pp is set to NULL. ** ** The usual usage pattern for an sqlite3_changegroup object is as follows: ** **
    **
  • It is created using a call to sqlite3changegroup_new(). ** **
  • Zero or more changesets (or patchsets) are added to the object ** by calling sqlite3changegroup_add(). ** **
  • The result of combining all input changesets together is obtained ** by the application via a call to sqlite3changegroup_output(). ** **
  • The object is deleted using a call to sqlite3changegroup_delete(). **
** ** Any number of calls to add() and output() may be made between the calls to ** new() and delete(), and in any order. ** ** As well as the regular sqlite3changegroup_add() and ** sqlite3changegroup_output() functions, also available are the streaming ** versions sqlite3changegroup_add_strm() and sqlite3changegroup_output_strm(). */ int sqlite3changegroup_new(sqlite3_changegroup **pp); /* ** CAPI3REF: Add A Changeset To A Changegroup ** ** Add all changes within the changeset (or patchset) in buffer pData (size ** nData bytes) to the changegroup. ** ** If the buffer contains a patchset, then all prior calls to this function ** on the same changegroup object must also have specified patchsets. Or, if ** the buffer contains a changeset, so must have the earlier calls to this ** function. Otherwise, SQLITE_ERROR is returned and no changes are added ** to the changegroup. ** ** Rows within the changeset and changegroup are identified by the values in ** their PRIMARY KEY columns. A change in the changeset is considered to ** apply to the same row as a change already present in the changegroup if ** the two rows have the same primary key. ** ** Changes to rows that do not already appear in the changegroup are ** simply copied into it. Or, if both the new changeset and the changegroup ** contain changes that apply to a single row, the final contents of the ** changegroup depends on the type of each change, as follows: ** ** ** ** **
Existing Change New Change Output Change **
INSERT INSERT ** The new change is ignored. This case does not occur if the new ** changeset was recorded immediately after the changesets already ** added to the changegroup. **
INSERT UPDATE ** The INSERT change remains in the changegroup. The values in the ** INSERT change are modified as if the row was inserted by the ** existing change and then updated according to the new change. **
INSERT DELETE ** The existing INSERT is removed from the changegroup. The DELETE is ** not added. **
UPDATE INSERT ** The new change is ignored. This case does not occur if the new ** changeset was recorded immediately after the changesets already ** added to the changegroup. **
UPDATE UPDATE ** The existing UPDATE remains within the changegroup. It is amended ** so that the accompanying values are as if the row was updated once ** by the existing change and then again by the new change. **
UPDATE DELETE ** The existing UPDATE is replaced by the new DELETE within the ** changegroup. **
DELETE INSERT ** If one or more of the column values in the row inserted by the ** new change differ from those in the row deleted by the existing ** change, the existing DELETE is replaced by an UPDATE within the ** changegroup. Otherwise, if the inserted row is exactly the same ** as the deleted row, the existing DELETE is simply discarded. **
DELETE UPDATE ** The new change is ignored. This case does not occur if the new ** changeset was recorded immediately after the changesets already ** added to the changegroup. **
DELETE DELETE ** The new change is ignored. This case does not occur if the new ** changeset was recorded immediately after the changesets already ** added to the changegroup. **
** ** If the new changeset contains changes to a table that is already present ** in the changegroup, then the number of columns and the position of the ** primary key columns for the table must be consistent. If this is not the ** case, this function fails with SQLITE_SCHEMA. If the input changeset ** appears to be corrupt and the corruption is detected, SQLITE_CORRUPT is ** returned. Or, if an out-of-memory condition occurs during processing, this ** function returns SQLITE_NOMEM. In all cases, if an error occurs the ** final contents of the changegroup is undefined. ** ** If no error occurs, SQLITE_OK is returned. */ int sqlite3changegroup_add(sqlite3_changegroup*, int nData, void *pData); /* ** CAPI3REF: Obtain A Composite Changeset From A Changegroup ** ** Obtain a buffer containing a changeset (or patchset) representing the ** current contents of the changegroup. If the inputs to the changegroup ** were themselves changesets, the output is a changeset. Or, if the ** inputs were patchsets, the output is also a patchset. ** ** As with the output of the sqlite3session_changeset() and ** sqlite3session_patchset() functions, all changes related to a single ** table are grouped together in the output of this function. Tables appear ** in the same order as for the very first changeset added to the changegroup. ** If the second or subsequent changesets added to the changegroup contain ** changes for tables that do not appear in the first changeset, they are ** appended onto the end of the output changeset, again in the order in ** which they are first encountered. ** ** If an error occurs, an SQLite error code is returned and the output ** variables (*pnData) and (*ppData) are set to 0. Otherwise, SQLITE_OK ** is returned and the output variables are set to the size of and a ** pointer to the output buffer, respectively. In this case it is the ** responsibility of the caller to eventually free the buffer using a ** call to sqlite3_free(). */ int sqlite3changegroup_output( sqlite3_changegroup*, int *pnData, /* OUT: Size of output buffer in bytes */ void **ppData /* OUT: Pointer to output buffer */ ); /* ** CAPI3REF: Delete A Changegroup Object */ void sqlite3changegroup_delete(sqlite3_changegroup*); /* ** CAPI3REF: Apply A Changeset To A Database ** ** Apply a changeset to a database. This function attempts to update the ** "main" database attached to handle db with the changes found in the ** changeset passed via the second and third arguments. ** ** The fourth argument (xFilter) passed to this function is the "filter ** callback". If it is not NULL, then for each table affected by at least one ** change in the changeset, the filter callback is invoked with ** the table name as the second argument, and a copy of the context pointer ** passed as the sixth argument to this function as the first. If the "filter ** callback" returns zero, then no attempt is made to apply any changes to ** the table. Otherwise, if the return value is non-zero or the xFilter ** argument to this function is NULL, all changes related to the table are ** attempted. ** ** For each table that is not excluded by the filter callback, this function ** tests that the target database contains a compatible table. A table is ** considered compatible if all of the following are true: ** **
    **
  • The table has the same name as the name recorded in the ** changeset, and **
  • The table has the same number of columns as recorded in the ** changeset, and **
  • The table has primary key columns in the same position as ** recorded in the changeset. **
** ** If there is no compatible table, it is not an error, but none of the ** changes associated with the table are applied. A warning message is issued ** via the sqlite3_log() mechanism with the error code SQLITE_SCHEMA. At most ** one such warning is issued for each table in the changeset. ** ** For each change for which there is a compatible table, an attempt is made ** to modify the table contents according to the UPDATE, INSERT or DELETE ** change. If a change cannot be applied cleanly, the conflict handler ** function passed as the fifth argument to sqlite3changeset_apply() may be ** invoked. A description of exactly when the conflict handler is invoked for ** each type of change is below. ** ** Unlike the xFilter argument, xConflict may not be passed NULL. The results ** of passing anything other than a valid function pointer as the xConflict ** argument are undefined. ** ** Each time the conflict handler function is invoked, it must return one ** of [SQLITE_CHANGESET_OMIT], [SQLITE_CHANGESET_ABORT] or ** [SQLITE_CHANGESET_REPLACE]. SQLITE_CHANGESET_REPLACE may only be returned ** if the second argument passed to the conflict handler is either ** SQLITE_CHANGESET_DATA or SQLITE_CHANGESET_CONFLICT. If the conflict-handler ** returns an illegal value, any changes already made are rolled back and ** the call to sqlite3changeset_apply() returns SQLITE_MISUSE. Different ** actions are taken by sqlite3changeset_apply() depending on the value ** returned by each invocation of the conflict-handler function. Refer to ** the documentation for the three ** [SQLITE_CHANGESET_OMIT|available return values] for details. ** **
**
DELETE Changes
** For each DELETE change, this function checks if the target database ** contains a row with the same primary key value (or values) as the ** original row values stored in the changeset. If it does, and the values ** stored in all non-primary key columns also match the values stored in ** the changeset the row is deleted from the target database. ** ** If a row with matching primary key values is found, but one or more of ** the non-primary key fields contains a value different from the original ** row value stored in the changeset, the conflict-handler function is ** invoked with [SQLITE_CHANGESET_DATA] as the second argument. ** ** If no row with matching primary key values is found in the database, ** the conflict-handler function is invoked with [SQLITE_CHANGESET_NOTFOUND] ** passed as the second argument. ** ** If the DELETE operation is attempted, but SQLite returns SQLITE_CONSTRAINT ** (which can only happen if a foreign key constraint is violated), the ** conflict-handler function is invoked with [SQLITE_CHANGESET_CONSTRAINT] ** passed as the second argument. This includes the case where the DELETE ** operation is attempted because an earlier call to the conflict handler ** function returned [SQLITE_CHANGESET_REPLACE]. ** **
INSERT Changes
** For each INSERT change, an attempt is made to insert the new row into ** the database. ** ** If the attempt to insert the row fails because the database already ** contains a row with the same primary key values, the conflict handler ** function is invoked with the second argument set to ** [SQLITE_CHANGESET_CONFLICT]. ** ** If the attempt to insert the row fails because of some other constraint ** violation (e.g. NOT NULL or UNIQUE), the conflict handler function is ** invoked with the second argument set to [SQLITE_CHANGESET_CONSTRAINT]. ** This includes the case where the INSERT operation is re-attempted because ** an earlier call to the conflict handler function returned ** [SQLITE_CHANGESET_REPLACE]. ** **
UPDATE Changes
** For each UPDATE change, this function checks if the target database ** contains a row with the same primary key value (or values) as the ** original row values stored in the changeset. If it does, and the values ** stored in all non-primary key columns also match the values stored in ** the changeset the row is updated within the target database. ** ** If a row with matching primary key values is found, but one or more of ** the non-primary key fields contains a value different from an original ** row value stored in the changeset, the conflict-handler function is ** invoked with [SQLITE_CHANGESET_DATA] as the second argument. Since ** UPDATE changes only contain values for non-primary key fields that are ** to be modified, only those fields need to match the original values to ** avoid the SQLITE_CHANGESET_DATA conflict-handler callback. ** ** If no row with matching primary key values is found in the database, ** the conflict-handler function is invoked with [SQLITE_CHANGESET_NOTFOUND] ** passed as the second argument. ** ** If the UPDATE operation is attempted, but SQLite returns ** SQLITE_CONSTRAINT, the conflict-handler function is invoked with ** [SQLITE_CHANGESET_CONSTRAINT] passed as the second argument. ** This includes the case where the UPDATE operation is attempted after ** an earlier call to the conflict handler function returned ** [SQLITE_CHANGESET_REPLACE]. **
** ** It is safe to execute SQL statements, including those that write to the ** table that the callback related to, from within the xConflict callback. ** This can be used to further customize the applications conflict ** resolution strategy. ** ** All changes made by this function are enclosed in a savepoint transaction. ** If any other error (aside from a constraint failure when attempting to ** write to the target database) occurs, then the savepoint transaction is ** rolled back, restoring the target database to its original state, and an ** SQLite error code returned. */ int sqlite3changeset_apply( sqlite3 *db, /* Apply change to "main" db of this handle */ int nChangeset, /* Size of changeset in bytes */ void *pChangeset, /* Changeset blob */ int(*xFilter)( void *pCtx, /* Copy of sixth arg to _apply() */ const char *zTab /* Table name */ ), int(*xConflict)( void *pCtx, /* Copy of sixth arg to _apply() */ int eConflict, /* DATA, MISSING, CONFLICT, CONSTRAINT */ sqlite3_changeset_iter *p /* Handle describing change and conflict */ ), void *pCtx /* First argument passed to xConflict */ ); /* ** CAPI3REF: Constants Passed To The Conflict Handler ** ** Values that may be passed as the second argument to a conflict-handler. ** **
**
SQLITE_CHANGESET_DATA
** The conflict handler is invoked with CHANGESET_DATA as the second argument ** when processing a DELETE or UPDATE change if a row with the required ** PRIMARY KEY fields is present in the database, but one or more other ** (non primary-key) fields modified by the update do not contain the ** expected "before" values. ** ** The conflicting row, in this case, is the database row with the matching ** primary key. ** **
SQLITE_CHANGESET_NOTFOUND
** The conflict handler is invoked with CHANGESET_NOTFOUND as the second ** argument when processing a DELETE or UPDATE change if a row with the ** required PRIMARY KEY fields is not present in the database. ** ** There is no conflicting row in this case. The results of invoking the ** sqlite3changeset_conflict() API are undefined. ** **
SQLITE_CHANGESET_CONFLICT
** CHANGESET_CONFLICT is passed as the second argument to the conflict ** handler while processing an INSERT change if the operation would result ** in duplicate primary key values. ** ** The conflicting row in this case is the database row with the matching ** primary key. ** **
SQLITE_CHANGESET_FOREIGN_KEY
** If foreign key handling is enabled, and applying a changeset leaves the ** database in a state containing foreign key violations, the conflict ** handler is invoked with CHANGESET_FOREIGN_KEY as the second argument ** exactly once before the changeset is committed. If the conflict handler ** returns CHANGESET_OMIT, the changes, including those that caused the ** foreign key constraint violation, are committed. Or, if it returns ** CHANGESET_ABORT, the changeset is rolled back. ** ** No current or conflicting row information is provided. The only function ** it is possible to call on the supplied sqlite3_changeset_iter handle ** is sqlite3changeset_fk_conflicts(). ** **
SQLITE_CHANGESET_CONSTRAINT
** If any other constraint violation occurs while applying a change (i.e. ** a UNIQUE, CHECK or NOT NULL constraint), the conflict handler is ** invoked with CHANGESET_CONSTRAINT as the second argument. ** ** There is no conflicting row in this case. The results of invoking the ** sqlite3changeset_conflict() API are undefined. ** **
*/ #define SQLITE_CHANGESET_DATA 1 #define SQLITE_CHANGESET_NOTFOUND 2 #define SQLITE_CHANGESET_CONFLICT 3 #define SQLITE_CHANGESET_CONSTRAINT 4 #define SQLITE_CHANGESET_FOREIGN_KEY 5 /* ** CAPI3REF: Constants Returned By The Conflict Handler ** ** A conflict handler callback must return one of the following three values. ** **
**
SQLITE_CHANGESET_OMIT
** If a conflict handler returns this value no special action is taken. The ** change that caused the conflict is not applied. The session module ** continues to the next change in the changeset. ** **
SQLITE_CHANGESET_REPLACE
** This value may only be returned if the second argument to the conflict ** handler was SQLITE_CHANGESET_DATA or SQLITE_CHANGESET_CONFLICT. If this ** is not the case, any changes applied so far are rolled back and the ** call to sqlite3changeset_apply() returns SQLITE_MISUSE. ** ** If CHANGESET_REPLACE is returned by an SQLITE_CHANGESET_DATA conflict ** handler, then the conflicting row is either updated or deleted, depending ** on the type of change. ** ** If CHANGESET_REPLACE is returned by an SQLITE_CHANGESET_CONFLICT conflict ** handler, then the conflicting row is removed from the database and a ** second attempt to apply the change is made. If this second attempt fails, ** the original row is restored to the database before continuing. ** **
SQLITE_CHANGESET_ABORT
** If this value is returned, any changes applied so far are rolled back ** and the call to sqlite3changeset_apply() returns SQLITE_ABORT. **
*/ #define SQLITE_CHANGESET_OMIT 0 #define SQLITE_CHANGESET_REPLACE 1 #define SQLITE_CHANGESET_ABORT 2 /* ** CAPI3REF: Streaming Versions of API functions. ** ** The six streaming API xxx_strm() functions serve similar purposes to the ** corresponding non-streaming API functions: ** ** ** **
Streaming functionNon-streaming equivalent
sqlite3changeset_apply_str[sqlite3changeset_apply] **
sqlite3changeset_concat_str[sqlite3changeset_concat] **
sqlite3changeset_invert_str[sqlite3changeset_invert] **
sqlite3changeset_start_str[sqlite3changeset_start] **
sqlite3session_changeset_str[sqlite3session_changeset] **
sqlite3session_patchset_str[sqlite3session_patchset] **
** ** Non-streaming functions that accept changesets (or patchsets) as input ** require that the entire changeset be stored in a single buffer in memory. ** Similarly, those that return a changeset or patchset do so by returning ** a pointer to a single large buffer allocated using sqlite3_malloc(). ** Normally this is convenient. However, if an application running in a ** low-memory environment is required to handle very large changesets, the ** large contiguous memory allocations required can become onerous. ** ** In order to avoid this problem, instead of a single large buffer, input ** is passed to a streaming API functions by way of a callback function that ** the sessions module invokes to incrementally request input data as it is ** required. In all cases, a pair of API function parameters such as ** **
**        int nChangeset,
**        void *pChangeset,
**  
** ** Is replaced by: ** **
**        int (*xInput)(void *pIn, void *pData, int *pnData),
**        void *pIn,
**  
** ** Each time the xInput callback is invoked by the sessions module, the first ** argument passed is a copy of the supplied pIn context pointer. The second ** argument, pData, points to a buffer (*pnData) bytes in size. Assuming no ** error occurs the xInput method should copy up to (*pnData) bytes of data ** into the buffer and set (*pnData) to the actual number of bytes copied ** before returning SQLITE_OK. If the input is completely exhausted, (*pnData) ** should be set to zero to indicate this. Or, if an error occurs, an SQLite ** error code should be returned. In all cases, if an xInput callback returns ** an error, all processing is abandoned and the streaming API function ** returns a copy of the error code to the caller. ** ** In the case of sqlite3changeset_start_strm(), the xInput callback may be ** invoked by the sessions module at any point during the lifetime of the ** iterator. If such an xInput callback returns an error, the iterator enters ** an error state, whereby all subsequent calls to iterator functions ** immediately fail with the same error code as returned by xInput. ** ** Similarly, streaming API functions that return changesets (or patchsets) ** return them in chunks by way of a callback function instead of via a ** pointer to a single large buffer. In this case, a pair of parameters such ** as: ** **
**        int *pnChangeset,
**        void **ppChangeset,
**  
** ** Is replaced by: ** **
**        int (*xOutput)(void *pOut, const void *pData, int nData),
**        void *pOut
**  
** ** The xOutput callback is invoked zero or more times to return data to ** the application. The first parameter passed to each call is a copy of the ** pOut pointer supplied by the application. The second parameter, pData, ** points to a buffer nData bytes in size containing the chunk of output ** data being returned. If the xOutput callback successfully processes the ** supplied data, it should return SQLITE_OK to indicate success. Otherwise, ** it should return some other SQLite error code. In this case processing ** is immediately abandoned and the streaming API function returns a copy ** of the xOutput error code to the application. ** ** The sessions module never invokes an xOutput callback with the third ** parameter set to a value less than or equal to zero. Other than this, ** no guarantees are made as to the size of the chunks of data returned. */ int sqlite3changeset_apply_strm( sqlite3 *db, /* Apply change to "main" db of this handle */ int (*xInput)(void *pIn, void *pData, int *pnData), /* Input function */ void *pIn, /* First arg for xInput */ int(*xFilter)( void *pCtx, /* Copy of sixth arg to _apply() */ const char *zTab /* Table name */ ), int(*xConflict)( void *pCtx, /* Copy of sixth arg to _apply() */ int eConflict, /* DATA, MISSING, CONFLICT, CONSTRAINT */ sqlite3_changeset_iter *p /* Handle describing change and conflict */ ), void *pCtx /* First argument passed to xConflict */ ); int sqlite3changeset_concat_strm( int (*xInputA)(void *pIn, void *pData, int *pnData), void *pInA, int (*xInputB)(void *pIn, void *pData, int *pnData), void *pInB, int (*xOutput)(void *pOut, const void *pData, int nData), void *pOut ); int sqlite3changeset_invert_strm( int (*xInput)(void *pIn, void *pData, int *pnData), void *pIn, int (*xOutput)(void *pOut, const void *pData, int nData), void *pOut ); int sqlite3changeset_start_strm( sqlite3_changeset_iter **pp, int (*xInput)(void *pIn, void *pData, int *pnData), void *pIn ); int sqlite3session_changeset_strm( sqlite3_session *pSession, int (*xOutput)(void *pOut, const void *pData, int nData), void *pOut ); int sqlite3session_patchset_strm( sqlite3_session *pSession, int (*xOutput)(void *pOut, const void *pData, int nData), void *pOut ); int sqlite3changegroup_add_strm(sqlite3_changegroup*, int (*xInput)(void *pIn, void *pData, int *pnData), void *pIn ); int sqlite3changegroup_output_strm(sqlite3_changegroup*, int (*xOutput)(void *pOut, const void *pData, int nData), void *pOut ); /* ** Make sure we can call this stuff from C++. */ #if 0 } #endif #endif /* !defined(__SQLITESESSION_H_) && defined(SQLITE_ENABLE_SESSION) */ /******** End of sqlite3session.h *********/ /******** Begin file fts5.h *********/ /* ** 2014 May 31 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ****************************************************************************** ** ** Interfaces to extend FTS5. Using the interfaces defined in this file, ** FTS5 may be extended with: ** ** * custom tokenizers, and ** * custom auxiliary functions. */ #ifndef _FTS5_H #define _FTS5_H #if 0 extern "C" { #endif /************************************************************************* ** CUSTOM AUXILIARY FUNCTIONS ** ** Virtual table implementations may overload SQL functions by implementing ** the sqlite3_module.xFindFunction() method. */ typedef struct Fts5ExtensionApi Fts5ExtensionApi; typedef struct Fts5Context Fts5Context; typedef struct Fts5PhraseIter Fts5PhraseIter; typedef void (*fts5_extension_function)( const Fts5ExtensionApi *pApi, /* API offered by current FTS version */ Fts5Context *pFts, /* First arg to pass to pApi functions */ sqlite3_context *pCtx, /* Context for returning result/error */ int nVal, /* Number of values in apVal[] array */ sqlite3_value **apVal /* Array of trailing arguments */ ); struct Fts5PhraseIter { const unsigned char *a; const unsigned char *b; }; /* ** EXTENSION API FUNCTIONS ** ** xUserData(pFts): ** Return a copy of the context pointer the extension function was ** registered with. ** ** xColumnTotalSize(pFts, iCol, pnToken): ** If parameter iCol is less than zero, set output variable *pnToken ** to the total number of tokens in the FTS5 table. Or, if iCol is ** non-negative but less than the number of columns in the table, return ** the total number of tokens in column iCol, considering all rows in ** the FTS5 table. ** ** If parameter iCol is greater than or equal to the number of columns ** in the table, SQLITE_RANGE is returned. Or, if an error occurs (e.g. ** an OOM condition or IO error), an appropriate SQLite error code is ** returned. ** ** xColumnCount(pFts): ** Return the number of columns in the table. ** ** xColumnSize(pFts, iCol, pnToken): ** If parameter iCol is less than zero, set output variable *pnToken ** to the total number of tokens in the current row. Or, if iCol is ** non-negative but less than the number of columns in the table, set ** *pnToken to the number of tokens in column iCol of the current row. ** ** If parameter iCol is greater than or equal to the number of columns ** in the table, SQLITE_RANGE is returned. Or, if an error occurs (e.g. ** an OOM condition or IO error), an appropriate SQLite error code is ** returned. ** ** This function may be quite inefficient if used with an FTS5 table ** created with the "columnsize=0" option. ** ** xColumnText: ** This function attempts to retrieve the text of column iCol of the ** current document. If successful, (*pz) is set to point to a buffer ** containing the text in utf-8 encoding, (*pn) is set to the size in bytes ** (not characters) of the buffer and SQLITE_OK is returned. Otherwise, ** if an error occurs, an SQLite error code is returned and the final values ** of (*pz) and (*pn) are undefined. ** ** xPhraseCount: ** Returns the number of phrases in the current query expression. ** ** xPhraseSize: ** Returns the number of tokens in phrase iPhrase of the query. Phrases ** are numbered starting from zero. ** ** xInstCount: ** Set *pnInst to the total number of occurrences of all phrases within ** the query within the current row. Return SQLITE_OK if successful, or ** an error code (i.e. SQLITE_NOMEM) if an error occurs. ** ** This API can be quite slow if used with an FTS5 table created with the ** "detail=none" or "detail=column" option. If the FTS5 table is created ** with either "detail=none" or "detail=column" and "content=" option ** (i.e. if it is a contentless table), then this API always returns 0. ** ** xInst: ** Query for the details of phrase match iIdx within the current row. ** Phrase matches are numbered starting from zero, so the iIdx argument ** should be greater than or equal to zero and smaller than the value ** output by xInstCount(). ** ** Usually, output parameter *piPhrase is set to the phrase number, *piCol ** to the column in which it occurs and *piOff the token offset of the ** first token of the phrase. The exception is if the table was created ** with the offsets=0 option specified. In this case *piOff is always ** set to -1. ** ** Returns SQLITE_OK if successful, or an error code (i.e. SQLITE_NOMEM) ** if an error occurs. ** ** This API can be quite slow if used with an FTS5 table created with the ** "detail=none" or "detail=column" option. ** ** xRowid: ** Returns the rowid of the current row. ** ** xTokenize: ** Tokenize text using the tokenizer belonging to the FTS5 table. ** ** xQueryPhrase(pFts5, iPhrase, pUserData, xCallback): ** This API function is used to query the FTS table for phrase iPhrase ** of the current query. Specifically, a query equivalent to: ** ** ... FROM ftstable WHERE ftstable MATCH $p ORDER BY rowid ** ** with $p set to a phrase equivalent to the phrase iPhrase of the ** current query is executed. Any column filter that applies to ** phrase iPhrase of the current query is included in $p. For each ** row visited, the callback function passed as the fourth argument ** is invoked. The context and API objects passed to the callback ** function may be used to access the properties of each matched row. ** Invoking Api.xUserData() returns a copy of the pointer passed as ** the third argument to pUserData. ** ** If the callback function returns any value other than SQLITE_OK, the ** query is abandoned and the xQueryPhrase function returns immediately. ** If the returned value is SQLITE_DONE, xQueryPhrase returns SQLITE_OK. ** Otherwise, the error code is propagated upwards. ** ** If the query runs to completion without incident, SQLITE_OK is returned. ** Or, if some error occurs before the query completes or is aborted by ** the callback, an SQLite error code is returned. ** ** ** xSetAuxdata(pFts5, pAux, xDelete) ** ** Save the pointer passed as the second argument as the extension functions ** "auxiliary data". The pointer may then be retrieved by the current or any ** future invocation of the same fts5 extension function made as part of ** of the same MATCH query using the xGetAuxdata() API. ** ** Each extension function is allocated a single auxiliary data slot for ** each FTS query (MATCH expression). If the extension function is invoked ** more than once for a single FTS query, then all invocations share a ** single auxiliary data context. ** ** If there is already an auxiliary data pointer when this function is ** invoked, then it is replaced by the new pointer. If an xDelete callback ** was specified along with the original pointer, it is invoked at this ** point. ** ** The xDelete callback, if one is specified, is also invoked on the ** auxiliary data pointer after the FTS5 query has finished. ** ** If an error (e.g. an OOM condition) occurs within this function, an ** the auxiliary data is set to NULL and an error code returned. If the ** xDelete parameter was not NULL, it is invoked on the auxiliary data ** pointer before returning. ** ** ** xGetAuxdata(pFts5, bClear) ** ** Returns the current auxiliary data pointer for the fts5 extension ** function. See the xSetAuxdata() method for details. ** ** If the bClear argument is non-zero, then the auxiliary data is cleared ** (set to NULL) before this function returns. In this case the xDelete, ** if any, is not invoked. ** ** ** xRowCount(pFts5, pnRow) ** ** This function is used to retrieve the total number of rows in the table. ** In other words, the same value that would be returned by: ** ** SELECT count(*) FROM ftstable; ** ** xPhraseFirst() ** This function is used, along with type Fts5PhraseIter and the xPhraseNext ** method, to iterate through all instances of a single query phrase within ** the current row. This is the same information as is accessible via the ** xInstCount/xInst APIs. While the xInstCount/xInst APIs are more convenient ** to use, this API may be faster under some circumstances. To iterate ** through instances of phrase iPhrase, use the following code: ** ** Fts5PhraseIter iter; ** int iCol, iOff; ** for(pApi->xPhraseFirst(pFts, iPhrase, &iter, &iCol, &iOff); ** iCol>=0; ** pApi->xPhraseNext(pFts, &iter, &iCol, &iOff) ** ){ ** // An instance of phrase iPhrase at offset iOff of column iCol ** } ** ** The Fts5PhraseIter structure is defined above. Applications should not ** modify this structure directly - it should only be used as shown above ** with the xPhraseFirst() and xPhraseNext() API methods (and by ** xPhraseFirstColumn() and xPhraseNextColumn() as illustrated below). ** ** This API can be quite slow if used with an FTS5 table created with the ** "detail=none" or "detail=column" option. If the FTS5 table is created ** with either "detail=none" or "detail=column" and "content=" option ** (i.e. if it is a contentless table), then this API always iterates ** through an empty set (all calls to xPhraseFirst() set iCol to -1). ** ** xPhraseNext() ** See xPhraseFirst above. ** ** xPhraseFirstColumn() ** This function and xPhraseNextColumn() are similar to the xPhraseFirst() ** and xPhraseNext() APIs described above. The difference is that instead ** of iterating through all instances of a phrase in the current row, these ** APIs are used to iterate through the set of columns in the current row ** that contain one or more instances of a specified phrase. For example: ** ** Fts5PhraseIter iter; ** int iCol; ** for(pApi->xPhraseFirstColumn(pFts, iPhrase, &iter, &iCol); ** iCol>=0; ** pApi->xPhraseNextColumn(pFts, &iter, &iCol) ** ){ ** // Column iCol contains at least one instance of phrase iPhrase ** } ** ** This API can be quite slow if used with an FTS5 table created with the ** "detail=none" option. If the FTS5 table is created with either ** "detail=none" "content=" option (i.e. if it is a contentless table), ** then this API always iterates through an empty set (all calls to ** xPhraseFirstColumn() set iCol to -1). ** ** The information accessed using this API and its companion ** xPhraseFirstColumn() may also be obtained using xPhraseFirst/xPhraseNext ** (or xInst/xInstCount). The chief advantage of this API is that it is ** significantly more efficient than those alternatives when used with ** "detail=column" tables. ** ** xPhraseNextColumn() ** See xPhraseFirstColumn above. */ struct Fts5ExtensionApi { int iVersion; /* Currently always set to 3 */ void *(*xUserData)(Fts5Context*); int (*xColumnCount)(Fts5Context*); int (*xRowCount)(Fts5Context*, sqlite3_int64 *pnRow); int (*xColumnTotalSize)(Fts5Context*, int iCol, sqlite3_int64 *pnToken); int (*xTokenize)(Fts5Context*, const char *pText, int nText, /* Text to tokenize */ void *pCtx, /* Context passed to xToken() */ int (*xToken)(void*, int, const char*, int, int, int) /* Callback */ ); int (*xPhraseCount)(Fts5Context*); int (*xPhraseSize)(Fts5Context*, int iPhrase); int (*xInstCount)(Fts5Context*, int *pnInst); int (*xInst)(Fts5Context*, int iIdx, int *piPhrase, int *piCol, int *piOff); sqlite3_int64 (*xRowid)(Fts5Context*); int (*xColumnText)(Fts5Context*, int iCol, const char **pz, int *pn); int (*xColumnSize)(Fts5Context*, int iCol, int *pnToken); int (*xQueryPhrase)(Fts5Context*, int iPhrase, void *pUserData, int(*)(const Fts5ExtensionApi*,Fts5Context*,void*) ); int (*xSetAuxdata)(Fts5Context*, void *pAux, void(*xDelete)(void*)); void *(*xGetAuxdata)(Fts5Context*, int bClear); int (*xPhraseFirst)(Fts5Context*, int iPhrase, Fts5PhraseIter*, int*, int*); void (*xPhraseNext)(Fts5Context*, Fts5PhraseIter*, int *piCol, int *piOff); int (*xPhraseFirstColumn)(Fts5Context*, int iPhrase, Fts5PhraseIter*, int*); void (*xPhraseNextColumn)(Fts5Context*, Fts5PhraseIter*, int *piCol); }; /* ** CUSTOM AUXILIARY FUNCTIONS *************************************************************************/ /************************************************************************* ** CUSTOM TOKENIZERS ** ** Applications may also register custom tokenizer types. A tokenizer ** is registered by providing fts5 with a populated instance of the ** following structure. All structure methods must be defined, setting ** any member of the fts5_tokenizer struct to NULL leads to undefined ** behaviour. The structure methods are expected to function as follows: ** ** xCreate: ** This function is used to allocate and initialize a tokenizer instance. ** A tokenizer instance is required to actually tokenize text. ** ** The first argument passed to this function is a copy of the (void*) ** pointer provided by the application when the fts5_tokenizer object ** was registered with FTS5 (the third argument to xCreateTokenizer()). ** The second and third arguments are an array of nul-terminated strings ** containing the tokenizer arguments, if any, specified following the ** tokenizer name as part of the CREATE VIRTUAL TABLE statement used ** to create the FTS5 table. ** ** The final argument is an output variable. If successful, (*ppOut) ** should be set to point to the new tokenizer handle and SQLITE_OK ** returned. If an error occurs, some value other than SQLITE_OK should ** be returned. In this case, fts5 assumes that the final value of *ppOut ** is undefined. ** ** xDelete: ** This function is invoked to delete a tokenizer handle previously ** allocated using xCreate(). Fts5 guarantees that this function will ** be invoked exactly once for each successful call to xCreate(). ** ** xTokenize: ** This function is expected to tokenize the nText byte string indicated ** by argument pText. pText may or may not be nul-terminated. The first ** argument passed to this function is a pointer to an Fts5Tokenizer object ** returned by an earlier call to xCreate(). ** ** The second argument indicates the reason that FTS5 is requesting ** tokenization of the supplied text. This is always one of the following ** four values: ** **
  • FTS5_TOKENIZE_DOCUMENT - A document is being inserted into ** or removed from the FTS table. The tokenizer is being invoked to ** determine the set of tokens to add to (or delete from) the ** FTS index. ** **
  • FTS5_TOKENIZE_QUERY - A MATCH query is being executed ** against the FTS index. The tokenizer is being called to tokenize ** a bareword or quoted string specified as part of the query. ** **
  • (FTS5_TOKENIZE_QUERY | FTS5_TOKENIZE_PREFIX) - Same as ** FTS5_TOKENIZE_QUERY, except that the bareword or quoted string is ** followed by a "*" character, indicating that the last token ** returned by the tokenizer will be treated as a token prefix. ** **
  • FTS5_TOKENIZE_AUX - The tokenizer is being invoked to ** satisfy an fts5_api.xTokenize() request made by an auxiliary ** function. Or an fts5_api.xColumnSize() request made by the same ** on a columnsize=0 database. **
** ** For each token in the input string, the supplied callback xToken() must ** be invoked. The first argument to it should be a copy of the pointer ** passed as the second argument to xTokenize(). The third and fourth ** arguments are a pointer to a buffer containing the token text, and the ** size of the token in bytes. The 4th and 5th arguments are the byte offsets ** of the first byte of and first byte immediately following the text from ** which the token is derived within the input. ** ** The second argument passed to the xToken() callback ("tflags") should ** normally be set to 0. The exception is if the tokenizer supports ** synonyms. In this case see the discussion below for details. ** ** FTS5 assumes the xToken() callback is invoked for each token in the ** order that they occur within the input text. ** ** If an xToken() callback returns any value other than SQLITE_OK, then ** the tokenization should be abandoned and the xTokenize() method should ** immediately return a copy of the xToken() return value. Or, if the ** input buffer is exhausted, xTokenize() should return SQLITE_OK. Finally, ** if an error occurs with the xTokenize() implementation itself, it ** may abandon the tokenization and return any error code other than ** SQLITE_OK or SQLITE_DONE. ** ** SYNONYM SUPPORT ** ** Custom tokenizers may also support synonyms. Consider a case in which a ** user wishes to query for a phrase such as "first place". Using the ** built-in tokenizers, the FTS5 query 'first + place' will match instances ** of "first place" within the document set, but not alternative forms ** such as "1st place". In some applications, it would be better to match ** all instances of "first place" or "1st place" regardless of which form ** the user specified in the MATCH query text. ** ** There are several ways to approach this in FTS5: ** **
  1. By mapping all synonyms to a single token. In this case, the ** In the above example, this means that the tokenizer returns the ** same token for inputs "first" and "1st". Say that token is in ** fact "first", so that when the user inserts the document "I won ** 1st place" entries are added to the index for tokens "i", "won", ** "first" and "place". If the user then queries for '1st + place', ** the tokenizer substitutes "first" for "1st" and the query works ** as expected. ** **
  2. By adding multiple synonyms for a single term to the FTS index. ** In this case, when tokenizing query text, the tokenizer may ** provide multiple synonyms for a single term within the document. ** FTS5 then queries the index for each synonym individually. For ** example, faced with the query: ** ** ** ... MATCH 'first place' ** ** the tokenizer offers both "1st" and "first" as synonyms for the ** first token in the MATCH query and FTS5 effectively runs a query ** similar to: ** ** ** ... MATCH '(first OR 1st) place' ** ** except that, for the purposes of auxiliary functions, the query ** still appears to contain just two phrases - "(first OR 1st)" ** being treated as a single phrase. ** **
  3. By adding multiple synonyms for a single term to the FTS index. ** Using this method, when tokenizing document text, the tokenizer ** provides multiple synonyms for each token. So that when a ** document such as "I won first place" is tokenized, entries are ** added to the FTS index for "i", "won", "first", "1st" and ** "place". ** ** This way, even if the tokenizer does not provide synonyms ** when tokenizing query text (it should not - to do would be ** inefficient), it doesn't matter if the user queries for ** 'first + place' or '1st + place', as there are entires in the ** FTS index corresponding to both forms of the first token. **
** ** Whether it is parsing document or query text, any call to xToken that ** specifies a tflags argument with the FTS5_TOKEN_COLOCATED bit ** is considered to supply a synonym for the previous token. For example, ** when parsing the document "I won first place", a tokenizer that supports ** synonyms would call xToken() 5 times, as follows: ** ** ** xToken(pCtx, 0, "i", 1, 0, 1); ** xToken(pCtx, 0, "won", 3, 2, 5); ** xToken(pCtx, 0, "first", 5, 6, 11); ** xToken(pCtx, FTS5_TOKEN_COLOCATED, "1st", 3, 6, 11); ** xToken(pCtx, 0, "place", 5, 12, 17); ** ** ** It is an error to specify the FTS5_TOKEN_COLOCATED flag the first time ** xToken() is called. Multiple synonyms may be specified for a single token ** by making multiple calls to xToken(FTS5_TOKEN_COLOCATED) in sequence. ** There is no limit to the number of synonyms that may be provided for a ** single token. ** ** In many cases, method (1) above is the best approach. It does not add ** extra data to the FTS index or require FTS5 to query for multiple terms, ** so it is efficient in terms of disk space and query speed. However, it ** does not support prefix queries very well. If, as suggested above, the ** token "first" is subsituted for "1st" by the tokenizer, then the query: ** ** ** ... MATCH '1s*' ** ** will not match documents that contain the token "1st" (as the tokenizer ** will probably not map "1s" to any prefix of "first"). ** ** For full prefix support, method (3) may be preferred. In this case, ** because the index contains entries for both "first" and "1st", prefix ** queries such as 'fi*' or '1s*' will match correctly. However, because ** extra entries are added to the FTS index, this method uses more space ** within the database. ** ** Method (2) offers a midpoint between (1) and (3). Using this method, ** a query such as '1s*' will match documents that contain the literal ** token "1st", but not "first" (assuming the tokenizer is not able to ** provide synonyms for prefixes). However, a non-prefix query like '1st' ** will match against "1st" and "first". This method does not require ** extra disk space, as no extra entries are added to the FTS index. ** On the other hand, it may require more CPU cycles to run MATCH queries, ** as separate queries of the FTS index are required for each synonym. ** ** When using methods (2) or (3), it is important that the tokenizer only ** provide synonyms when tokenizing document text (method (2)) or query ** text (method (3)), not both. Doing so will not cause any errors, but is ** inefficient. */ typedef struct Fts5Tokenizer Fts5Tokenizer; typedef struct fts5_tokenizer fts5_tokenizer; struct fts5_tokenizer { int (*xCreate)(void*, const char **azArg, int nArg, Fts5Tokenizer **ppOut); void (*xDelete)(Fts5Tokenizer*); int (*xTokenize)(Fts5Tokenizer*, void *pCtx, int flags, /* Mask of FTS5_TOKENIZE_* flags */ const char *pText, int nText, int (*xToken)( void *pCtx, /* Copy of 2nd argument to xTokenize() */ int tflags, /* Mask of FTS5_TOKEN_* flags */ const char *pToken, /* Pointer to buffer containing token */ int nToken, /* Size of token in bytes */ int iStart, /* Byte offset of token within input text */ int iEnd /* Byte offset of end of token within input text */ ) ); }; /* Flags that may be passed as the third argument to xTokenize() */ #define FTS5_TOKENIZE_QUERY 0x0001 #define FTS5_TOKENIZE_PREFIX 0x0002 #define FTS5_TOKENIZE_DOCUMENT 0x0004 #define FTS5_TOKENIZE_AUX 0x0008 /* Flags that may be passed by the tokenizer implementation back to FTS5 ** as the third argument to the supplied xToken callback. */ #define FTS5_TOKEN_COLOCATED 0x0001 /* Same position as prev. token */ /* ** END OF CUSTOM TOKENIZERS *************************************************************************/ /************************************************************************* ** FTS5 EXTENSION REGISTRATION API */ typedef struct fts5_api fts5_api; struct fts5_api { int iVersion; /* Currently always set to 2 */ /* Create a new tokenizer */ int (*xCreateTokenizer)( fts5_api *pApi, const char *zName, void *pContext, fts5_tokenizer *pTokenizer, void (*xDestroy)(void*) ); /* Find an existing tokenizer */ int (*xFindTokenizer)( fts5_api *pApi, const char *zName, void **ppContext, fts5_tokenizer *pTokenizer ); /* Create a new auxiliary function */ int (*xCreateFunction)( fts5_api *pApi, const char *zName, void *pContext, fts5_extension_function xFunction, void (*xDestroy)(void*) ); }; /* ** END OF REGISTRATION API *************************************************************************/ #if 0 } /* end of the 'extern "C"' block */ #endif #endif /* _FTS5_H */ /******** End of fts5.h *********/ /************** End of sqlite3.h *********************************************/ /************** Continuing where we left off in sqliteInt.h ******************/ /* ** Include the configuration header output by 'configure' if we're using the ** autoconf-based build */ #ifdef _HAVE_SQLITE_CONFIG_H #include "config.h" #endif /************** Include sqliteLimit.h in the middle of sqliteInt.h ***********/ /************** Begin file sqliteLimit.h *************************************/ /* ** 2007 May 7 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ************************************************************************* ** ** This file defines various limits of what SQLite can process. */ /* ** The maximum length of a TEXT or BLOB in bytes. This also ** limits the size of a row in a table or index. ** ** The hard limit is the ability of a 32-bit signed integer ** to count the size: 2^31-1 or 2147483647. */ #ifndef SQLITE_MAX_LENGTH # define SQLITE_MAX_LENGTH 1000000000 #endif /* ** This is the maximum number of ** ** * Columns in a table ** * Columns in an index ** * Columns in a view ** * Terms in the SET clause of an UPDATE statement ** * Terms in the result set of a SELECT statement ** * Terms in the GROUP BY or ORDER BY clauses of a SELECT statement. ** * Terms in the VALUES clause of an INSERT statement ** ** The hard upper limit here is 32676. Most database people will ** tell you that in a well-normalized database, you usually should ** not have more than a dozen or so columns in any table. And if ** that is the case, there is no point in having more than a few ** dozen values in any of the other situations described above. */ #ifndef SQLITE_MAX_COLUMN # define SQLITE_MAX_COLUMN 2000 #endif /* ** The maximum length of a single SQL statement in bytes. ** ** It used to be the case that setting this value to zero would ** turn the limit off. That is no longer true. It is not possible ** to turn this limit off. */ #ifndef SQLITE_MAX_SQL_LENGTH # define SQLITE_MAX_SQL_LENGTH 1000000000 #endif /* ** The maximum depth of an expression tree. This is limited to ** some extent by SQLITE_MAX_SQL_LENGTH. But sometime you might ** want to place more severe limits on the complexity of an ** expression. ** ** A value of 0 used to mean that the limit was not enforced. ** But that is no longer true. The limit is now strictly enforced ** at all times. */ #ifndef SQLITE_MAX_EXPR_DEPTH # define SQLITE_MAX_EXPR_DEPTH 1000 #endif /* ** The maximum number of terms in a compound SELECT statement. ** The code generator for compound SELECT statements does one ** level of recursion for each term. A stack overflow can result ** if the number of terms is too large. In practice, most SQL ** never has more than 3 or 4 terms. Use a value of 0 to disable ** any limit on the number of terms in a compount SELECT. */ #ifndef SQLITE_MAX_COMPOUND_SELECT # define SQLITE_MAX_COMPOUND_SELECT 500 #endif /* ** The maximum number of opcodes in a VDBE program. ** Not currently enforced. */ #ifndef SQLITE_MAX_VDBE_OP # define SQLITE_MAX_VDBE_OP 25000 #endif /* ** The maximum number of arguments to an SQL function. */ #ifndef SQLITE_MAX_FUNCTION_ARG # define SQLITE_MAX_FUNCTION_ARG 127 #endif /* ** The suggested maximum number of in-memory pages to use for ** the main database table and for temporary tables. ** ** IMPLEMENTATION-OF: R-30185-15359 The default suggested cache size is -2000, ** which means the cache size is limited to 2048000 bytes of memory. ** IMPLEMENTATION-OF: R-48205-43578 The default suggested cache size can be ** altered using the SQLITE_DEFAULT_CACHE_SIZE compile-time options. */ #ifndef SQLITE_DEFAULT_CACHE_SIZE # define SQLITE_DEFAULT_CACHE_SIZE -2000 #endif /* ** The default number of frames to accumulate in the log file before ** checkpointing the database in WAL mode. */ #ifndef SQLITE_DEFAULT_WAL_AUTOCHECKPOINT # define SQLITE_DEFAULT_WAL_AUTOCHECKPOINT 1000 #endif /* ** The maximum number of attached databases. This must be between 0 ** and 125. The upper bound of 125 is because the attached databases are ** counted using a signed 8-bit integer which has a maximum value of 127 ** and we have to allow 2 extra counts for the "main" and "temp" databases. */ #ifndef SQLITE_MAX_ATTACHED # define SQLITE_MAX_ATTACHED 10 #endif /* ** The maximum value of a ?nnn wildcard that the parser will accept. */ #ifndef SQLITE_MAX_VARIABLE_NUMBER # define SQLITE_MAX_VARIABLE_NUMBER 999 #endif /* Maximum page size. The upper bound on this value is 65536. This a limit ** imposed by the use of 16-bit offsets within each page. ** ** Earlier versions of SQLite allowed the user to change this value at ** compile time. This is no longer permitted, on the grounds that it creates ** a library that is technically incompatible with an SQLite library ** compiled with a different limit. If a process operating on a database ** with a page-size of 65536 bytes crashes, then an instance of SQLite ** compiled with the default page-size limit will not be able to rollback ** the aborted transaction. This could lead to database corruption. */ #ifdef SQLITE_MAX_PAGE_SIZE # undef SQLITE_MAX_PAGE_SIZE #endif #define SQLITE_MAX_PAGE_SIZE 65536 /* ** The default size of a database page. */ #ifndef SQLITE_DEFAULT_PAGE_SIZE # define SQLITE_DEFAULT_PAGE_SIZE 4096 #endif #if SQLITE_DEFAULT_PAGE_SIZE>SQLITE_MAX_PAGE_SIZE # undef SQLITE_DEFAULT_PAGE_SIZE # define SQLITE_DEFAULT_PAGE_SIZE SQLITE_MAX_PAGE_SIZE #endif /* ** Ordinarily, if no value is explicitly provided, SQLite creates databases ** with page size SQLITE_DEFAULT_PAGE_SIZE. However, based on certain ** device characteristics (sector-size and atomic write() support), ** SQLite may choose a larger value. This constant is the maximum value ** SQLite will choose on its own. */ #ifndef SQLITE_MAX_DEFAULT_PAGE_SIZE # define SQLITE_MAX_DEFAULT_PAGE_SIZE 8192 #endif #if SQLITE_MAX_DEFAULT_PAGE_SIZE>SQLITE_MAX_PAGE_SIZE # undef SQLITE_MAX_DEFAULT_PAGE_SIZE # define SQLITE_MAX_DEFAULT_PAGE_SIZE SQLITE_MAX_PAGE_SIZE #endif /* ** Maximum number of pages in one database file. ** ** This is really just the default value for the max_page_count pragma. ** This value can be lowered (or raised) at run-time using that the ** max_page_count macro. */ #ifndef SQLITE_MAX_PAGE_COUNT # define SQLITE_MAX_PAGE_COUNT 1073741823 #endif /* ** Maximum length (in bytes) of the pattern in a LIKE or GLOB ** operator. */ #ifndef SQLITE_MAX_LIKE_PATTERN_LENGTH # define SQLITE_MAX_LIKE_PATTERN_LENGTH 50000 #endif /* ** Maximum depth of recursion for triggers. ** ** A value of 1 means that a trigger program will not be able to itself ** fire any triggers. A value of 0 means that no trigger programs at all ** may be executed. */ #ifndef SQLITE_MAX_TRIGGER_DEPTH # define SQLITE_MAX_TRIGGER_DEPTH 1000 #endif /************** End of sqliteLimit.h *****************************************/ /************** Continuing where we left off in sqliteInt.h ******************/ /* Disable nuisance warnings on Borland compilers */ #if defined(__BORLANDC__) #pragma warn -rch /* unreachable code */ #pragma warn -ccc /* Condition is always true or false */ #pragma warn -aus /* Assigned value is never used */ #pragma warn -csu /* Comparing signed and unsigned */ #pragma warn -spa /* Suspicious pointer arithmetic */ #endif /* ** Include standard header files as necessary */ #ifdef HAVE_STDINT_H #include #endif #ifdef HAVE_INTTYPES_H #include #endif /* ** The following macros are used to cast pointers to integers and ** integers to pointers. The way you do this varies from one compiler ** to the next, so we have developed the following set of #if statements ** to generate appropriate macros for a wide range of compilers. ** ** The correct "ANSI" way to do this is to use the intptr_t type. ** Unfortunately, that typedef is not available on all compilers, or ** if it is available, it requires an #include of specific headers ** that vary from one machine to the next. ** ** Ticket #3860: The llvm-gcc-4.2 compiler from Apple chokes on ** the ((void*)&((char*)0)[X]) construct. But MSVC chokes on ((void*)(X)). ** So we have to define the macros in different ways depending on the ** compiler. */ #if defined(__PTRDIFF_TYPE__) /* This case should work for GCC */ # define SQLITE_INT_TO_PTR(X) ((void*)(__PTRDIFF_TYPE__)(X)) # define SQLITE_PTR_TO_INT(X) ((int)(__PTRDIFF_TYPE__)(X)) #elif !defined(__GNUC__) /* Works for compilers other than LLVM */ # define SQLITE_INT_TO_PTR(X) ((void*)&((char*)0)[X]) # define SQLITE_PTR_TO_INT(X) ((int)(((char*)X)-(char*)0)) #elif defined(HAVE_STDINT_H) /* Use this case if we have ANSI headers */ # define SQLITE_INT_TO_PTR(X) ((void*)(intptr_t)(X)) # define SQLITE_PTR_TO_INT(X) ((int)(intptr_t)(X)) #else /* Generates a warning - but it always works */ # define SQLITE_INT_TO_PTR(X) ((void*)(X)) # define SQLITE_PTR_TO_INT(X) ((int)(X)) #endif /* ** A macro to hint to the compiler that a function should not be ** inlined. */ #if defined(__GNUC__) # define SQLITE_NOINLINE __attribute__((noinline)) #elif defined(_MSC_VER) && _MSC_VER>=1310 # define SQLITE_NOINLINE __declspec(noinline) #else # define SQLITE_NOINLINE #endif /* ** Make sure that the compiler intrinsics we desire are enabled when ** compiling with an appropriate version of MSVC unless prevented by ** the SQLITE_DISABLE_INTRINSIC define. */ #if !defined(SQLITE_DISABLE_INTRINSIC) # if defined(_MSC_VER) && _MSC_VER>=1400 # if !defined(_WIN32_WCE) # include # pragma intrinsic(_byteswap_ushort) # pragma intrinsic(_byteswap_ulong) # pragma intrinsic(_ReadWriteBarrier) # else # include # endif # endif #endif /* ** The SQLITE_THREADSAFE macro must be defined as 0, 1, or 2. ** 0 means mutexes are permanently disable and the library is never ** threadsafe. 1 means the library is serialized which is the highest ** level of threadsafety. 2 means the library is multithreaded - multiple ** threads can use SQLite as long as no two threads try to use the same ** database connection at the same time. ** ** Older versions of SQLite used an optional THREADSAFE macro. ** We support that for legacy. */ #if !defined(SQLITE_THREADSAFE) # if defined(THREADSAFE) # define SQLITE_THREADSAFE THREADSAFE # else # define SQLITE_THREADSAFE 1 /* IMP: R-07272-22309 */ # endif #endif /* ** Powersafe overwrite is on by default. But can be turned off using ** the -DSQLITE_POWERSAFE_OVERWRITE=0 command-line option. */ #ifndef SQLITE_POWERSAFE_OVERWRITE # define SQLITE_POWERSAFE_OVERWRITE 1 #endif /* ** EVIDENCE-OF: R-25715-37072 Memory allocation statistics are enabled by ** default unless SQLite is compiled with SQLITE_DEFAULT_MEMSTATUS=0 in ** which case memory allocation statistics are disabled by default. */ #if !defined(SQLITE_DEFAULT_MEMSTATUS) # define SQLITE_DEFAULT_MEMSTATUS 1 #endif /* ** Exactly one of the following macros must be defined in order to ** specify which memory allocation subsystem to use. ** ** SQLITE_SYSTEM_MALLOC // Use normal system malloc() ** SQLITE_WIN32_MALLOC // Use Win32 native heap API ** SQLITE_ZERO_MALLOC // Use a stub allocator that always fails ** SQLITE_MEMDEBUG // Debugging version of system malloc() ** ** On Windows, if the SQLITE_WIN32_MALLOC_VALIDATE macro is defined and the ** assert() macro is enabled, each call into the Win32 native heap subsystem ** will cause HeapValidate to be called. If heap validation should fail, an ** assertion will be triggered. ** ** If none of the above are defined, then set SQLITE_SYSTEM_MALLOC as ** the default. */ #if defined(SQLITE_SYSTEM_MALLOC) \ + defined(SQLITE_WIN32_MALLOC) \ + defined(SQLITE_ZERO_MALLOC) \ + defined(SQLITE_MEMDEBUG)>1 # error "Two or more of the following compile-time configuration options\ are defined but at most one is allowed:\ SQLITE_SYSTEM_MALLOC, SQLITE_WIN32_MALLOC, SQLITE_MEMDEBUG,\ SQLITE_ZERO_MALLOC" #endif #if defined(SQLITE_SYSTEM_MALLOC) \ + defined(SQLITE_WIN32_MALLOC) \ + defined(SQLITE_ZERO_MALLOC) \ + defined(SQLITE_MEMDEBUG)==0 # define SQLITE_SYSTEM_MALLOC 1 #endif /* ** If SQLITE_MALLOC_SOFT_LIMIT is not zero, then try to keep the ** sizes of memory allocations below this value where possible. */ #if !defined(SQLITE_MALLOC_SOFT_LIMIT) # define SQLITE_MALLOC_SOFT_LIMIT 1024 #endif /* ** We need to define _XOPEN_SOURCE as follows in order to enable ** recursive mutexes on most Unix systems and fchmod() on OpenBSD. ** But _XOPEN_SOURCE define causes problems for Mac OS X, so omit ** it. */ #if !defined(_XOPEN_SOURCE) && !defined(__DARWIN__) && !defined(__APPLE__) # define _XOPEN_SOURCE 600 #endif /* ** NDEBUG and SQLITE_DEBUG are opposites. It should always be true that ** defined(NDEBUG)==!defined(SQLITE_DEBUG). If this is not currently true, ** make it true by defining or undefining NDEBUG. ** ** Setting NDEBUG makes the code smaller and faster by disabling the ** assert() statements in the code. So we want the default action ** to be for NDEBUG to be set and NDEBUG to be undefined only if SQLITE_DEBUG ** is set. Thus NDEBUG becomes an opt-in rather than an opt-out ** feature. */ #if !defined(NDEBUG) && !defined(SQLITE_DEBUG) # define NDEBUG 1 #endif #if defined(NDEBUG) && defined(SQLITE_DEBUG) # undef NDEBUG #endif /* ** Enable SQLITE_ENABLE_EXPLAIN_COMMENTS if SQLITE_DEBUG is turned on. */ #if !defined(SQLITE_ENABLE_EXPLAIN_COMMENTS) && defined(SQLITE_DEBUG) # define SQLITE_ENABLE_EXPLAIN_COMMENTS 1 #endif /* ** The testcase() macro is used to aid in coverage testing. When ** doing coverage testing, the condition inside the argument to ** testcase() must be evaluated both true and false in order to ** get full branch coverage. The testcase() macro is inserted ** to help ensure adequate test coverage in places where simple ** condition/decision coverage is inadequate. For example, testcase() ** can be used to make sure boundary values are tested. For ** bitmask tests, testcase() can be used to make sure each bit ** is significant and used at least once. On switch statements ** where multiple cases go to the same block of code, testcase() ** can insure that all cases are evaluated. ** */ #ifdef SQLITE_COVERAGE_TEST SQLITE_PRIVATE void sqlite3Coverage(int); # define testcase(X) if( X ){ sqlite3Coverage(__LINE__); } #else # define testcase(X) #endif /* ** The TESTONLY macro is used to enclose variable declarations or ** other bits of code that are needed to support the arguments ** within testcase() and assert() macros. */ #if !defined(NDEBUG) || defined(SQLITE_COVERAGE_TEST) # define TESTONLY(X) X #else # define TESTONLY(X) #endif /* ** Sometimes we need a small amount of code such as a variable initialization ** to setup for a later assert() statement. We do not want this code to ** appear when assert() is disabled. The following macro is therefore ** used to contain that setup code. The "VVA" acronym stands for ** "Verification, Validation, and Accreditation". In other words, the ** code within VVA_ONLY() will only run during verification processes. */ #ifndef NDEBUG # define VVA_ONLY(X) X #else # define VVA_ONLY(X) #endif /* ** The ALWAYS and NEVER macros surround boolean expressions which ** are intended to always be true or false, respectively. Such ** expressions could be omitted from the code completely. But they ** are included in a few cases in order to enhance the resilience ** of SQLite to unexpected behavior - to make the code "self-healing" ** or "ductile" rather than being "brittle" and crashing at the first ** hint of unplanned behavior. ** ** In other words, ALWAYS and NEVER are added for defensive code. ** ** When doing coverage testing ALWAYS and NEVER are hard-coded to ** be true and false so that the unreachable code they specify will ** not be counted as untested code. */ #if defined(SQLITE_COVERAGE_TEST) || defined(SQLITE_MUTATION_TEST) # define ALWAYS(X) (1) # define NEVER(X) (0) #elif !defined(NDEBUG) # define ALWAYS(X) ((X)?1:(assert(0),0)) # define NEVER(X) ((X)?(assert(0),1):0) #else # define ALWAYS(X) (X) # define NEVER(X) (X) #endif /* ** Some malloc failures are only possible if SQLITE_TEST_REALLOC_STRESS is ** defined. We need to defend against those failures when testing with ** SQLITE_TEST_REALLOC_STRESS, but we don't want the unreachable branches ** during a normal build. The following macro can be used to disable tests ** that are always false except when SQLITE_TEST_REALLOC_STRESS is set. */ #if defined(SQLITE_TEST_REALLOC_STRESS) # define ONLY_IF_REALLOC_STRESS(X) (X) #elif !defined(NDEBUG) # define ONLY_IF_REALLOC_STRESS(X) ((X)?(assert(0),1):0) #else # define ONLY_IF_REALLOC_STRESS(X) (0) #endif /* ** Declarations used for tracing the operating system interfaces. */ #if defined(SQLITE_FORCE_OS_TRACE) || defined(SQLITE_TEST) || \ (defined(SQLITE_DEBUG) && SQLITE_OS_WIN) extern int sqlite3OSTrace; # define OSTRACE(X) if( sqlite3OSTrace ) sqlite3DebugPrintf X # define SQLITE_HAVE_OS_TRACE #else # define OSTRACE(X) # undef SQLITE_HAVE_OS_TRACE #endif /* ** Is the sqlite3ErrName() function needed in the build? Currently, ** it is needed by "mutex_w32.c" (when debugging), "os_win.c" (when ** OSTRACE is enabled), and by several "test*.c" files (which are ** compiled using SQLITE_TEST). */ #if defined(SQLITE_HAVE_OS_TRACE) || defined(SQLITE_TEST) || \ (defined(SQLITE_DEBUG) && SQLITE_OS_WIN) # define SQLITE_NEED_ERR_NAME #else # undef SQLITE_NEED_ERR_NAME #endif /* ** SQLITE_ENABLE_EXPLAIN_COMMENTS is incompatible with SQLITE_OMIT_EXPLAIN */ #ifdef SQLITE_OMIT_EXPLAIN # undef SQLITE_ENABLE_EXPLAIN_COMMENTS #endif /* ** Return true (non-zero) if the input is an integer that is too large ** to fit in 32-bits. This macro is used inside of various testcase() ** macros to verify that we have tested SQLite for large-file support. */ #define IS_BIG_INT(X) (((X)&~(i64)0xffffffff)!=0) /* ** The macro unlikely() is a hint that surrounds a boolean ** expression that is usually false. Macro likely() surrounds ** a boolean expression that is usually true. These hints could, ** in theory, be used by the compiler to generate better code, but ** currently they are just comments for human readers. */ #define likely(X) (X) #define unlikely(X) (X) /************** Include hash.h in the middle of sqliteInt.h ******************/ /************** Begin file hash.h ********************************************/ /* ** 2001 September 22 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ************************************************************************* ** This is the header file for the generic hash-table implementation ** used in SQLite. */ #ifndef SQLITE_HASH_H #define SQLITE_HASH_H /* Forward declarations of structures. */ typedef struct Hash Hash; typedef struct HashElem HashElem; /* A complete hash table is an instance of the following structure. ** The internals of this structure are intended to be opaque -- client ** code should not attempt to access or modify the fields of this structure ** directly. Change this structure only by using the routines below. ** However, some of the "procedures" and "functions" for modifying and ** accessing this structure are really macros, so we can't really make ** this structure opaque. ** ** All elements of the hash table are on a single doubly-linked list. ** Hash.first points to the head of this list. ** ** There are Hash.htsize buckets. Each bucket points to a spot in ** the global doubly-linked list. The contents of the bucket are the ** element pointed to plus the next _ht.count-1 elements in the list. ** ** Hash.htsize and Hash.ht may be zero. In that case lookup is done ** by a linear search of the global list. For small tables, the ** Hash.ht table is never allocated because if there are few elements ** in the table, it is faster to do a linear search than to manage ** the hash table. */ struct Hash { unsigned int htsize; /* Number of buckets in the hash table */ unsigned int count; /* Number of entries in this table */ HashElem *first; /* The first element of the array */ struct _ht { /* the hash table */ int count; /* Number of entries with this hash */ HashElem *chain; /* Pointer to first entry with this hash */ } *ht; }; /* Each element in the hash table is an instance of the following ** structure. All elements are stored on a single doubly-linked list. ** ** Again, this structure is intended to be opaque, but it can't really ** be opaque because it is used by macros. */ struct HashElem { HashElem *next, *prev; /* Next and previous elements in the table */ void *data; /* Data associated with this element */ const char *pKey; /* Key associated with this element */ }; /* ** Access routines. To delete, insert a NULL pointer. */ SQLITE_PRIVATE void sqlite3HashInit(Hash*); SQLITE_PRIVATE void *sqlite3HashInsert(Hash*, const char *pKey, void *pData); SQLITE_PRIVATE void *sqlite3HashFind(const Hash*, const char *pKey); SQLITE_PRIVATE void sqlite3HashClear(Hash*); /* ** Macros for looping over all elements of a hash table. The idiom is ** like this: ** ** Hash h; ** HashElem *p; ** ... ** for(p=sqliteHashFirst(&h); p; p=sqliteHashNext(p)){ ** SomeStructure *pData = sqliteHashData(p); ** // do something with pData ** } */ #define sqliteHashFirst(H) ((H)->first) #define sqliteHashNext(E) ((E)->next) #define sqliteHashData(E) ((E)->data) /* #define sqliteHashKey(E) ((E)->pKey) // NOT USED */ /* #define sqliteHashKeysize(E) ((E)->nKey) // NOT USED */ /* ** Number of entries in a hash table */ /* #define sqliteHashCount(H) ((H)->count) // NOT USED */ #endif /* SQLITE_HASH_H */ /************** End of hash.h ************************************************/ /************** Continuing where we left off in sqliteInt.h ******************/ /************** Include parse.h in the middle of sqliteInt.h *****************/ /************** Begin file parse.h *******************************************/ #define TK_SEMI 1 #define TK_EXPLAIN 2 #define TK_QUERY 3 #define TK_PLAN 4 #define TK_BEGIN 5 #define TK_TRANSACTION 6 #define TK_DEFERRED 7 #define TK_IMMEDIATE 8 #define TK_EXCLUSIVE 9 #define TK_COMMIT 10 #define TK_END 11 #define TK_ROLLBACK 12 #define TK_SAVEPOINT 13 #define TK_RELEASE 14 #define TK_TO 15 #define TK_TABLE 16 #define TK_CREATE 17 #define TK_IF 18 #define TK_NOT 19 #define TK_EXISTS 20 #define TK_TEMP 21 #define TK_LP 22 #define TK_RP 23 #define TK_AS 24 #define TK_WITHOUT 25 #define TK_COMMA 26 #define TK_OR 27 #define TK_AND 28 #define TK_IS 29 #define TK_MATCH 30 #define TK_LIKE_KW 31 #define TK_BETWEEN 32 #define TK_IN 33 #define TK_ISNULL 34 #define TK_NOTNULL 35 #define TK_NE 36 #define TK_EQ 37 #define TK_GT 38 #define TK_LE 39 #define TK_LT 40 #define TK_GE 41 #define TK_ESCAPE 42 #define TK_BITAND 43 #define TK_BITOR 44 #define TK_LSHIFT 45 #define TK_RSHIFT 46 #define TK_PLUS 47 #define TK_MINUS 48 #define TK_STAR 49 #define TK_SLASH 50 #define TK_REM 51 #define TK_CONCAT 52 #define TK_COLLATE 53 #define TK_BITNOT 54 #define TK_ID 55 #define TK_INDEXED 56 #define TK_ABORT 57 #define TK_ACTION 58 #define TK_AFTER 59 #define TK_ANALYZE 60 #define TK_ASC 61 #define TK_ATTACH 62 #define TK_BEFORE 63 #define TK_BY 64 #define TK_CASCADE 65 #define TK_CAST 66 #define TK_COLUMNKW 67 #define TK_CONFLICT 68 #define TK_DATABASE 69 #define TK_DESC 70 #define TK_DETACH 71 #define TK_EACH 72 #define TK_FAIL 73 #define TK_FOR 74 #define TK_IGNORE 75 #define TK_INITIALLY 76 #define TK_INSTEAD 77 #define TK_NO 78 #define TK_KEY 79 #define TK_OF 80 #define TK_OFFSET 81 #define TK_PRAGMA 82 #define TK_RAISE 83 #define TK_RECURSIVE 84 #define TK_REPLACE 85 #define TK_RESTRICT 86 #define TK_ROW 87 #define TK_TRIGGER 88 #define TK_VACUUM 89 #define TK_VIEW 90 #define TK_VIRTUAL 91 #define TK_WITH 92 #define TK_REINDEX 93 #define TK_RENAME 94 #define TK_CTIME_KW 95 #define TK_ANY 96 #define TK_STRING 97 #define TK_JOIN_KW 98 #define TK_CONSTRAINT 99 #define TK_DEFAULT 100 #define TK_NULL 101 #define TK_PRIMARY 102 #define TK_UNIQUE 103 #define TK_CHECK 104 #define TK_REFERENCES 105 #define TK_AUTOINCR 106 #define TK_ON 107 #define TK_INSERT 108 #define TK_DELETE 109 #define TK_UPDATE 110 #define TK_SET 111 #define TK_DEFERRABLE 112 #define TK_FOREIGN 113 #define TK_DROP 114 #define TK_UNION 115 #define TK_ALL 116 #define TK_EXCEPT 117 #define TK_INTERSECT 118 #define TK_SELECT 119 #define TK_VALUES 120 #define TK_DISTINCT 121 #define TK_DOT 122 #define TK_FROM 123 #define TK_JOIN 124 #define TK_USING 125 #define TK_ORDER 126 #define TK_GROUP 127 #define TK_HAVING 128 #define TK_LIMIT 129 #define TK_WHERE 130 #define TK_INTO 131 #define TK_FLOAT 132 #define TK_BLOB 133 #define TK_INTEGER 134 #define TK_VARIABLE 135 #define TK_CASE 136 #define TK_WHEN 137 #define TK_THEN 138 #define TK_ELSE 139 #define TK_INDEX 140 #define TK_ALTER 141 #define TK_ADD 142 #define TK_TO_TEXT 143 #define TK_TO_BLOB 144 #define TK_TO_NUMERIC 145 #define TK_TO_INT 146 #define TK_TO_REAL 147 #define TK_ISNOT 148 #define TK_END_OF_FILE 149 #define TK_UNCLOSED_STRING 150 #define TK_FUNCTION 151 #define TK_COLUMN 152 #define TK_AGG_FUNCTION 153 #define TK_AGG_COLUMN 154 #define TK_UMINUS 155 #define TK_UPLUS 156 #define TK_REGISTER 157 #define TK_VECTOR 158 #define TK_SELECT_COLUMN 159 #define TK_ASTERISK 160 #define TK_SPAN 161 #define TK_SPACE 162 #define TK_ILLEGAL 163 /* The token codes above must all fit in 8 bits */ #define TKFLG_MASK 0xff /* Flags that can be added to a token code when it is not ** being stored in a u8: */ #define TKFLG_DONTFOLD 0x100 /* Omit constant folding optimizations */ /************** End of parse.h ***********************************************/ /************** Continuing where we left off in sqliteInt.h ******************/ #include #include #include #include #include /* ** If compiling for a processor that lacks floating point support, ** substitute integer for floating-point */ #ifdef SQLITE_OMIT_FLOATING_POINT # define double sqlite_int64 # define float sqlite_int64 # define LONGDOUBLE_TYPE sqlite_int64 # ifndef SQLITE_BIG_DBL # define SQLITE_BIG_DBL (((sqlite3_int64)1)<<50) # endif # define SQLITE_OMIT_DATETIME_FUNCS 1 # define SQLITE_OMIT_TRACE 1 # undef SQLITE_MIXED_ENDIAN_64BIT_FLOAT # undef SQLITE_HAVE_ISNAN #endif #ifndef SQLITE_BIG_DBL # define SQLITE_BIG_DBL (1e99) #endif /* ** OMIT_TEMPDB is set to 1 if SQLITE_OMIT_TEMPDB is defined, or 0 ** afterward. Having this macro allows us to cause the C compiler ** to omit code used by TEMP tables without messy #ifndef statements. */ #ifdef SQLITE_OMIT_TEMPDB #define OMIT_TEMPDB 1 #else #define OMIT_TEMPDB 0 #endif /* ** The "file format" number is an integer that is incremented whenever ** the VDBE-level file format changes. The following macros define the ** the default file format for new databases and the maximum file format ** that the library can read. */ #define SQLITE_MAX_FILE_FORMAT 4 #ifndef SQLITE_DEFAULT_FILE_FORMAT # define SQLITE_DEFAULT_FILE_FORMAT 4 #endif /* ** Determine whether triggers are recursive by default. This can be ** changed at run-time using a pragma. */ #ifndef SQLITE_DEFAULT_RECURSIVE_TRIGGERS # define SQLITE_DEFAULT_RECURSIVE_TRIGGERS 0 #endif /* ** Provide a default value for SQLITE_TEMP_STORE in case it is not specified ** on the command-line */ #ifndef SQLITE_TEMP_STORE # define SQLITE_TEMP_STORE 1 # define SQLITE_TEMP_STORE_xc 1 /* Exclude from ctime.c */ #endif /* ** If no value has been provided for SQLITE_MAX_WORKER_THREADS, or if ** SQLITE_TEMP_STORE is set to 3 (never use temporary files), set it ** to zero. */ #if SQLITE_TEMP_STORE==3 || SQLITE_THREADSAFE==0 # undef SQLITE_MAX_WORKER_THREADS # define SQLITE_MAX_WORKER_THREADS 0 #endif #ifndef SQLITE_MAX_WORKER_THREADS # define SQLITE_MAX_WORKER_THREADS 8 #endif #ifndef SQLITE_DEFAULT_WORKER_THREADS # define SQLITE_DEFAULT_WORKER_THREADS 0 #endif #if SQLITE_DEFAULT_WORKER_THREADS>SQLITE_MAX_WORKER_THREADS # undef SQLITE_MAX_WORKER_THREADS # define SQLITE_MAX_WORKER_THREADS SQLITE_DEFAULT_WORKER_THREADS #endif /* ** The default initial allocation for the pagecache when using separate ** pagecaches for each database connection. A positive number is the ** number of pages. A negative number N translations means that a buffer ** of -1024*N bytes is allocated and used for as many pages as it will hold. */ #ifndef SQLITE_DEFAULT_PCACHE_INITSZ # define SQLITE_DEFAULT_PCACHE_INITSZ 100 #endif /* ** GCC does not define the offsetof() macro so we'll have to do it ** ourselves. */ #ifndef offsetof #define offsetof(STRUCTURE,FIELD) ((int)((char*)&((STRUCTURE*)0)->FIELD)) #endif /* ** Macros to compute minimum and maximum of two numbers. */ #ifndef MIN # define MIN(A,B) ((A)<(B)?(A):(B)) #endif #ifndef MAX # define MAX(A,B) ((A)>(B)?(A):(B)) #endif /* ** Swap two objects of type TYPE. */ #define SWAP(TYPE,A,B) {TYPE t=A; A=B; B=t;} /* ** Check to see if this machine uses EBCDIC. (Yes, believe it or ** not, there are still machines out there that use EBCDIC.) */ #if 'A' == '\301' # define SQLITE_EBCDIC 1 #else # define SQLITE_ASCII 1 #endif /* ** Integers of known sizes. These typedefs might change for architectures ** where the sizes very. Preprocessor macros are available so that the ** types can be conveniently redefined at compile-type. Like this: ** ** cc '-DUINTPTR_TYPE=long long int' ... */ #ifndef UINT32_TYPE # ifdef HAVE_UINT32_T # define UINT32_TYPE uint32_t # else # define UINT32_TYPE unsigned int # endif #endif #ifndef UINT16_TYPE # ifdef HAVE_UINT16_T # define UINT16_TYPE uint16_t # else # define UINT16_TYPE unsigned short int # endif #endif #ifndef INT16_TYPE # ifdef HAVE_INT16_T # define INT16_TYPE int16_t # else # define INT16_TYPE short int # endif #endif #ifndef UINT8_TYPE # ifdef HAVE_UINT8_T # define UINT8_TYPE uint8_t # else # define UINT8_TYPE unsigned char # endif #endif #ifndef INT8_TYPE # ifdef HAVE_INT8_T # define INT8_TYPE int8_t # else # define INT8_TYPE signed char # endif #endif #ifndef LONGDOUBLE_TYPE # define LONGDOUBLE_TYPE long double #endif typedef sqlite_int64 i64; /* 8-byte signed integer */ typedef sqlite_uint64 u64; /* 8-byte unsigned integer */ typedef UINT32_TYPE u32; /* 4-byte unsigned integer */ typedef UINT16_TYPE u16; /* 2-byte unsigned integer */ typedef INT16_TYPE i16; /* 2-byte signed integer */ typedef UINT8_TYPE u8; /* 1-byte unsigned integer */ typedef INT8_TYPE i8; /* 1-byte signed integer */ /* ** SQLITE_MAX_U32 is a u64 constant that is the maximum u64 value ** that can be stored in a u32 without loss of data. The value ** is 0x00000000ffffffff. But because of quirks of some compilers, we ** have to specify the value in the less intuitive manner shown: */ #define SQLITE_MAX_U32 ((((u64)1)<<32)-1) /* ** The datatype used to store estimates of the number of rows in a ** table or index. This is an unsigned integer type. For 99.9% of ** the world, a 32-bit integer is sufficient. But a 64-bit integer ** can be used at compile-time if desired. */ #ifdef SQLITE_64BIT_STATS typedef u64 tRowcnt; /* 64-bit only if requested at compile-time */ #else typedef u32 tRowcnt; /* 32-bit is the default */ #endif /* ** Estimated quantities used for query planning are stored as 16-bit ** logarithms. For quantity X, the value stored is 10*log2(X). This ** gives a possible range of values of approximately 1.0e986 to 1e-986. ** But the allowed values are "grainy". Not every value is representable. ** For example, quantities 16 and 17 are both represented by a LogEst ** of 40. However, since LogEst quantities are suppose to be estimates, ** not exact values, this imprecision is not a problem. ** ** "LogEst" is short for "Logarithmic Estimate". ** ** Examples: ** 1 -> 0 20 -> 43 10000 -> 132 ** 2 -> 10 25 -> 46 25000 -> 146 ** 3 -> 16 100 -> 66 1000000 -> 199 ** 4 -> 20 1000 -> 99 1048576 -> 200 ** 10 -> 33 1024 -> 100 4294967296 -> 320 ** ** The LogEst can be negative to indicate fractional values. ** Examples: ** ** 0.5 -> -10 0.1 -> -33 0.0625 -> -40 */ typedef INT16_TYPE LogEst; /* ** Set the SQLITE_PTRSIZE macro to the number of bytes in a pointer */ #ifndef SQLITE_PTRSIZE # if defined(__SIZEOF_POINTER__) # define SQLITE_PTRSIZE __SIZEOF_POINTER__ # elif defined(i386) || defined(__i386__) || defined(_M_IX86) || \ defined(_M_ARM) || defined(__arm__) || defined(__x86) # define SQLITE_PTRSIZE 4 # else # define SQLITE_PTRSIZE 8 # endif #endif /* The uptr type is an unsigned integer large enough to hold a pointer */ #if defined(HAVE_STDINT_H) typedef uintptr_t uptr; #elif SQLITE_PTRSIZE==4 typedef u32 uptr; #else typedef u64 uptr; #endif /* ** The SQLITE_WITHIN(P,S,E) macro checks to see if pointer P points to ** something between S (inclusive) and E (exclusive). ** ** In other words, S is a buffer and E is a pointer to the first byte after ** the end of buffer S. This macro returns true if P points to something ** contained within the buffer S. */ #define SQLITE_WITHIN(P,S,E) (((uptr)(P)>=(uptr)(S))&&((uptr)(P)<(uptr)(E))) /* ** Macros to determine whether the machine is big or little endian, ** and whether or not that determination is run-time or compile-time. ** ** For best performance, an attempt is made to guess at the byte-order ** using C-preprocessor macros. If that is unsuccessful, or if ** -DSQLITE_RUNTIME_BYTEORDER=1 is set, then byte-order is determined ** at run-time. */ #if (defined(i386) || defined(__i386__) || defined(_M_IX86) || \ defined(__x86_64) || defined(__x86_64__) || defined(_M_X64) || \ defined(_M_AMD64) || defined(_M_ARM) || defined(__x86) || \ defined(__arm__)) && !defined(SQLITE_RUNTIME_BYTEORDER) # define SQLITE_BYTEORDER 1234 # define SQLITE_BIGENDIAN 0 # define SQLITE_LITTLEENDIAN 1 # define SQLITE_UTF16NATIVE SQLITE_UTF16LE #endif #if (defined(sparc) || defined(__ppc__)) \ && !defined(SQLITE_RUNTIME_BYTEORDER) # define SQLITE_BYTEORDER 4321 # define SQLITE_BIGENDIAN 1 # define SQLITE_LITTLEENDIAN 0 # define SQLITE_UTF16NATIVE SQLITE_UTF16BE #endif #if !defined(SQLITE_BYTEORDER) # ifdef SQLITE_AMALGAMATION const int sqlite3one = 1; # else extern const int sqlite3one; # endif # define SQLITE_BYTEORDER 0 /* 0 means "unknown at compile-time" */ # define SQLITE_BIGENDIAN (*(char *)(&sqlite3one)==0) # define SQLITE_LITTLEENDIAN (*(char *)(&sqlite3one)==1) # define SQLITE_UTF16NATIVE (SQLITE_BIGENDIAN?SQLITE_UTF16BE:SQLITE_UTF16LE) #endif /* ** Constants for the largest and smallest possible 64-bit signed integers. ** These macros are designed to work correctly on both 32-bit and 64-bit ** compilers. */ #define LARGEST_INT64 (0xffffffff|(((i64)0x7fffffff)<<32)) #define SMALLEST_INT64 (((i64)-1) - LARGEST_INT64) /* ** Round up a number to the next larger multiple of 8. This is used ** to force 8-byte alignment on 64-bit architectures. */ #define ROUND8(x) (((x)+7)&~7) /* ** Round down to the nearest multiple of 8 */ #define ROUNDDOWN8(x) ((x)&~7) /* ** Assert that the pointer X is aligned to an 8-byte boundary. This ** macro is used only within assert() to verify that the code gets ** all alignment restrictions correct. ** ** Except, if SQLITE_4_BYTE_ALIGNED_MALLOC is defined, then the ** underlying malloc() implementation might return us 4-byte aligned ** pointers. In that case, only verify 4-byte alignment. */ #ifdef SQLITE_4_BYTE_ALIGNED_MALLOC # define EIGHT_BYTE_ALIGNMENT(X) ((((char*)(X) - (char*)0)&3)==0) #else # define EIGHT_BYTE_ALIGNMENT(X) ((((char*)(X) - (char*)0)&7)==0) #endif /* ** Disable MMAP on platforms where it is known to not work */ #if defined(__OpenBSD__) || defined(__QNXNTO__) # undef SQLITE_MAX_MMAP_SIZE # define SQLITE_MAX_MMAP_SIZE 0 #endif /* ** Default maximum size of memory used by memory-mapped I/O in the VFS */ #ifdef __APPLE__ # include #endif #ifndef SQLITE_MAX_MMAP_SIZE # if defined(__linux__) \ || defined(_WIN32) \ || (defined(__APPLE__) && defined(__MACH__)) \ || defined(__sun) \ || defined(__FreeBSD__) \ || defined(__DragonFly__) # define SQLITE_MAX_MMAP_SIZE 0x7fff0000 /* 2147418112 */ # else # define SQLITE_MAX_MMAP_SIZE 0 # endif # define SQLITE_MAX_MMAP_SIZE_xc 1 /* exclude from ctime.c */ #endif /* ** The default MMAP_SIZE is zero on all platforms. Or, even if a larger ** default MMAP_SIZE is specified at compile-time, make sure that it does ** not exceed the maximum mmap size. */ #ifndef SQLITE_DEFAULT_MMAP_SIZE # define SQLITE_DEFAULT_MMAP_SIZE 0 # define SQLITE_DEFAULT_MMAP_SIZE_xc 1 /* Exclude from ctime.c */ #endif #if SQLITE_DEFAULT_MMAP_SIZE>SQLITE_MAX_MMAP_SIZE # undef SQLITE_DEFAULT_MMAP_SIZE # define SQLITE_DEFAULT_MMAP_SIZE SQLITE_MAX_MMAP_SIZE #endif /* ** Only one of SQLITE_ENABLE_STAT3 or SQLITE_ENABLE_STAT4 can be defined. ** Priority is given to SQLITE_ENABLE_STAT4. If either are defined, also ** define SQLITE_ENABLE_STAT3_OR_STAT4 */ #ifdef SQLITE_ENABLE_STAT4 # undef SQLITE_ENABLE_STAT3 # define SQLITE_ENABLE_STAT3_OR_STAT4 1 #elif SQLITE_ENABLE_STAT3 # define SQLITE_ENABLE_STAT3_OR_STAT4 1 #elif SQLITE_ENABLE_STAT3_OR_STAT4 # undef SQLITE_ENABLE_STAT3_OR_STAT4 #endif /* ** SELECTTRACE_ENABLED will be either 1 or 0 depending on whether or not ** the Select query generator tracing logic is turned on. */ #if defined(SQLITE_DEBUG) || defined(SQLITE_ENABLE_SELECTTRACE) # define SELECTTRACE_ENABLED 1 #else # define SELECTTRACE_ENABLED 0 #endif /* ** An instance of the following structure is used to store the busy-handler ** callback for a given sqlite handle. ** ** The sqlite.busyHandler member of the sqlite struct contains the busy ** callback for the database handle. Each pager opened via the sqlite ** handle is passed a pointer to sqlite.busyHandler. The busy-handler ** callback is currently invoked only from within pager.c. */ typedef struct BusyHandler BusyHandler; struct BusyHandler { int (*xFunc)(void *,int); /* The busy callback */ void *pArg; /* First arg to busy callback */ int nBusy; /* Incremented with each busy call */ }; /* ** Name of the master database table. The master database table ** is a special table that holds the names and attributes of all ** user tables and indices. */ #define MASTER_NAME "sqlite_master" #define TEMP_MASTER_NAME "sqlite_temp_master" /* ** The root-page of the master database table. */ #define MASTER_ROOT 1 /* ** The name of the schema table. */ #define SCHEMA_TABLE(x) ((!OMIT_TEMPDB)&&(x==1)?TEMP_MASTER_NAME:MASTER_NAME) /* ** A convenience macro that returns the number of elements in ** an array. */ #define ArraySize(X) ((int)(sizeof(X)/sizeof(X[0]))) /* ** Determine if the argument is a power of two */ #define IsPowerOfTwo(X) (((X)&((X)-1))==0) /* ** The following value as a destructor means to use sqlite3DbFree(). ** The sqlite3DbFree() routine requires two parameters instead of the ** one parameter that destructors normally want. So we have to introduce ** this magic value that the code knows to handle differently. Any ** pointer will work here as long as it is distinct from SQLITE_STATIC ** and SQLITE_TRANSIENT. */ #define SQLITE_DYNAMIC ((sqlite3_destructor_type)sqlite3MallocSize) /* ** When SQLITE_OMIT_WSD is defined, it means that the target platform does ** not support Writable Static Data (WSD) such as global and static variables. ** All variables must either be on the stack or dynamically allocated from ** the heap. When WSD is unsupported, the variable declarations scattered ** throughout the SQLite code must become constants instead. The SQLITE_WSD ** macro is used for this purpose. And instead of referencing the variable ** directly, we use its constant as a key to lookup the run-time allocated ** buffer that holds real variable. The constant is also the initializer ** for the run-time allocated buffer. ** ** In the usual case where WSD is supported, the SQLITE_WSD and GLOBAL ** macros become no-ops and have zero performance impact. */ #ifdef SQLITE_OMIT_WSD #define SQLITE_WSD const #define GLOBAL(t,v) (*(t*)sqlite3_wsd_find((void*)&(v), sizeof(v))) #define sqlite3GlobalConfig GLOBAL(struct Sqlite3Config, sqlite3Config) SQLITE_API int sqlite3_wsd_init(int N, int J); SQLITE_API void *sqlite3_wsd_find(void *K, int L); #else #define SQLITE_WSD #define GLOBAL(t,v) v #define sqlite3GlobalConfig sqlite3Config #endif /* ** The following macros are used to suppress compiler warnings and to ** make it clear to human readers when a function parameter is deliberately ** left unused within the body of a function. This usually happens when ** a function is called via a function pointer. For example the ** implementation of an SQL aggregate step callback may not use the ** parameter indicating the number of arguments passed to the aggregate, ** if it knows that this is enforced elsewhere. ** ** When a function parameter is not used at all within the body of a function, ** it is generally named "NotUsed" or "NotUsed2" to make things even clearer. ** However, these macros may also be used to suppress warnings related to ** parameters that may or may not be used depending on compilation options. ** For example those parameters only used in assert() statements. In these ** cases the parameters are named as per the usual conventions. */ #define UNUSED_PARAMETER(x) (void)(x) #define UNUSED_PARAMETER2(x,y) UNUSED_PARAMETER(x),UNUSED_PARAMETER(y) /* ** Forward references to structures */ typedef struct AggInfo AggInfo; typedef struct AuthContext AuthContext; typedef struct AutoincInfo AutoincInfo; typedef struct Bitvec Bitvec; typedef struct CollSeq CollSeq; typedef struct Column Column; typedef struct Db Db; typedef struct Schema Schema; typedef struct Expr Expr; typedef struct ExprList ExprList; typedef struct ExprSpan ExprSpan; typedef struct FKey FKey; typedef struct FuncDestructor FuncDestructor; typedef struct FuncDef FuncDef; typedef struct FuncDefHash FuncDefHash; typedef struct IdList IdList; typedef struct Index Index; typedef struct IndexSample IndexSample; typedef struct KeyClass KeyClass; typedef struct KeyInfo KeyInfo; typedef struct Lookaside Lookaside; typedef struct LookasideSlot LookasideSlot; typedef struct Module Module; typedef struct NameContext NameContext; typedef struct Parse Parse; typedef struct PreUpdate PreUpdate; typedef struct PrintfArguments PrintfArguments; typedef struct RowSet RowSet; typedef struct Savepoint Savepoint; typedef struct Select Select; typedef struct SQLiteThread SQLiteThread; typedef struct SelectDest SelectDest; typedef struct SrcList SrcList; typedef struct StrAccum StrAccum; typedef struct Table Table; typedef struct TableLock TableLock; typedef struct Token Token; typedef struct TreeView TreeView; typedef struct Trigger Trigger; typedef struct TriggerPrg TriggerPrg; typedef struct TriggerStep TriggerStep; typedef struct UnpackedRecord UnpackedRecord; typedef struct VTable VTable; typedef struct VtabCtx VtabCtx; typedef struct Walker Walker; typedef struct WhereInfo WhereInfo; typedef struct With With; /* ** Defer sourcing vdbe.h and btree.h until after the "u8" and ** "BusyHandler" typedefs. vdbe.h also requires a few of the opaque ** pointer types (i.e. FuncDef) defined above. */ /************** Include btree.h in the middle of sqliteInt.h *****************/ /************** Begin file btree.h *******************************************/ /* ** 2001 September 15 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ************************************************************************* ** This header file defines the interface that the sqlite B-Tree file ** subsystem. See comments in the source code for a detailed description ** of what each interface routine does. */ #ifndef SQLITE_BTREE_H #define SQLITE_BTREE_H /* TODO: This definition is just included so other modules compile. It ** needs to be revisited. */ #define SQLITE_N_BTREE_META 16 /* ** If defined as non-zero, auto-vacuum is enabled by default. Otherwise ** it must be turned on for each database using "PRAGMA auto_vacuum = 1". */ #ifndef SQLITE_DEFAULT_AUTOVACUUM #define SQLITE_DEFAULT_AUTOVACUUM 0 #endif #define BTREE_AUTOVACUUM_NONE 0 /* Do not do auto-vacuum */ #define BTREE_AUTOVACUUM_FULL 1 /* Do full auto-vacuum */ #define BTREE_AUTOVACUUM_INCR 2 /* Incremental vacuum */ /* ** Forward declarations of structure */ typedef struct Btree Btree; typedef struct BtCursor BtCursor; typedef struct BtShared BtShared; typedef struct BtreePayload BtreePayload; SQLITE_PRIVATE int sqlite3BtreeOpen( sqlite3_vfs *pVfs, /* VFS to use with this b-tree */ const char *zFilename, /* Name of database file to open */ sqlite3 *db, /* Associated database connection */ Btree **ppBtree, /* Return open Btree* here */ int flags, /* Flags */ int vfsFlags /* Flags passed through to VFS open */ ); /* The flags parameter to sqlite3BtreeOpen can be the bitwise or of the ** following values. ** ** NOTE: These values must match the corresponding PAGER_ values in ** pager.h. */ #define BTREE_OMIT_JOURNAL 1 /* Do not create or use a rollback journal */ #define BTREE_MEMORY 2 /* This is an in-memory DB */ #define BTREE_SINGLE 4 /* The file contains at most 1 b-tree */ #define BTREE_UNORDERED 8 /* Use of a hash implementation is OK */ SQLITE_PRIVATE int sqlite3BtreeClose(Btree*); SQLITE_PRIVATE int sqlite3BtreeSetCacheSize(Btree*,int); SQLITE_PRIVATE int sqlite3BtreeSetSpillSize(Btree*,int); #if SQLITE_MAX_MMAP_SIZE>0 SQLITE_PRIVATE int sqlite3BtreeSetMmapLimit(Btree*,sqlite3_int64); #endif SQLITE_PRIVATE int sqlite3BtreeSetPagerFlags(Btree*,unsigned); SQLITE_PRIVATE int sqlite3BtreeSetPageSize(Btree *p, int nPagesize, int nReserve, int eFix); SQLITE_PRIVATE int sqlite3BtreeGetPageSize(Btree*); SQLITE_PRIVATE int sqlite3BtreeMaxPageCount(Btree*,int); SQLITE_PRIVATE u32 sqlite3BtreeLastPage(Btree*); SQLITE_PRIVATE int sqlite3BtreeSecureDelete(Btree*,int); SQLITE_PRIVATE int sqlite3BtreeGetOptimalReserve(Btree*); SQLITE_PRIVATE int sqlite3BtreeGetReserveNoMutex(Btree *p); SQLITE_PRIVATE int sqlite3BtreeSetAutoVacuum(Btree *, int); SQLITE_PRIVATE int sqlite3BtreeGetAutoVacuum(Btree *); SQLITE_PRIVATE int sqlite3BtreeBeginTrans(Btree*,int); SQLITE_PRIVATE int sqlite3BtreeCommitPhaseOne(Btree*, const char *zMaster); SQLITE_PRIVATE int sqlite3BtreeCommitPhaseTwo(Btree*, int); SQLITE_PRIVATE int sqlite3BtreeCommit(Btree*); SQLITE_PRIVATE int sqlite3BtreeRollback(Btree*,int,int); SQLITE_PRIVATE int sqlite3BtreeBeginStmt(Btree*,int); SQLITE_PRIVATE int sqlite3BtreeCreateTable(Btree*, int*, int flags); SQLITE_PRIVATE int sqlite3BtreeIsInTrans(Btree*); SQLITE_PRIVATE int sqlite3BtreeIsInReadTrans(Btree*); SQLITE_PRIVATE int sqlite3BtreeIsInBackup(Btree*); SQLITE_PRIVATE void *sqlite3BtreeSchema(Btree *, int, void(*)(void *)); SQLITE_PRIVATE int sqlite3BtreeSchemaLocked(Btree *pBtree); #ifndef SQLITE_OMIT_SHARED_CACHE SQLITE_PRIVATE int sqlite3BtreeLockTable(Btree *pBtree, int iTab, u8 isWriteLock); #endif SQLITE_PRIVATE int sqlite3BtreeSavepoint(Btree *, int, int); SQLITE_PRIVATE const char *sqlite3BtreeGetFilename(Btree *); SQLITE_PRIVATE const char *sqlite3BtreeGetJournalname(Btree *); SQLITE_PRIVATE int sqlite3BtreeCopyFile(Btree *, Btree *); SQLITE_PRIVATE int sqlite3BtreeIncrVacuum(Btree *); /* The flags parameter to sqlite3BtreeCreateTable can be the bitwise OR ** of the flags shown below. ** ** Every SQLite table must have either BTREE_INTKEY or BTREE_BLOBKEY set. ** With BTREE_INTKEY, the table key is a 64-bit integer and arbitrary data ** is stored in the leaves. (BTREE_INTKEY is used for SQL tables.) With ** BTREE_BLOBKEY, the key is an arbitrary BLOB and no content is stored ** anywhere - the key is the content. (BTREE_BLOBKEY is used for SQL ** indices.) */ #define BTREE_INTKEY 1 /* Table has only 64-bit signed integer keys */ #define BTREE_BLOBKEY 2 /* Table has keys only - no data */ SQLITE_PRIVATE int sqlite3BtreeDropTable(Btree*, int, int*); SQLITE_PRIVATE int sqlite3BtreeClearTable(Btree*, int, int*); SQLITE_PRIVATE int sqlite3BtreeClearTableOfCursor(BtCursor*); SQLITE_PRIVATE int sqlite3BtreeTripAllCursors(Btree*, int, int); SQLITE_PRIVATE void sqlite3BtreeGetMeta(Btree *pBtree, int idx, u32 *pValue); SQLITE_PRIVATE int sqlite3BtreeUpdateMeta(Btree*, int idx, u32 value); SQLITE_PRIVATE int sqlite3BtreeNewDb(Btree *p); /* ** The second parameter to sqlite3BtreeGetMeta or sqlite3BtreeUpdateMeta ** should be one of the following values. The integer values are assigned ** to constants so that the offset of the corresponding field in an ** SQLite database header may be found using the following formula: ** ** offset = 36 + (idx * 4) ** ** For example, the free-page-count field is located at byte offset 36 of ** the database file header. The incr-vacuum-flag field is located at ** byte offset 64 (== 36+4*7). ** ** The BTREE_DATA_VERSION value is not really a value stored in the header. ** It is a read-only number computed by the pager. But we merge it with ** the header value access routines since its access pattern is the same. ** Call it a "virtual meta value". */ #define BTREE_FREE_PAGE_COUNT 0 #define BTREE_SCHEMA_VERSION 1 #define BTREE_FILE_FORMAT 2 #define BTREE_DEFAULT_CACHE_SIZE 3 #define BTREE_LARGEST_ROOT_PAGE 4 #define BTREE_TEXT_ENCODING 5 #define BTREE_USER_VERSION 6 #define BTREE_INCR_VACUUM 7 #define BTREE_APPLICATION_ID 8 #define BTREE_DATA_VERSION 15 /* A virtual meta-value */ /* ** Kinds of hints that can be passed into the sqlite3BtreeCursorHint() ** interface. ** ** BTREE_HINT_RANGE (arguments: Expr*, Mem*) ** ** The first argument is an Expr* (which is guaranteed to be constant for ** the lifetime of the cursor) that defines constraints on which rows ** might be fetched with this cursor. The Expr* tree may contain ** TK_REGISTER nodes that refer to values stored in the array of registers ** passed as the second parameter. In other words, if Expr.op==TK_REGISTER ** then the value of the node is the value in Mem[pExpr.iTable]. Any ** TK_COLUMN node in the expression tree refers to the Expr.iColumn-th ** column of the b-tree of the cursor. The Expr tree will not contain ** any function calls nor subqueries nor references to b-trees other than ** the cursor being hinted. ** ** The design of the _RANGE hint is aid b-tree implementations that try ** to prefetch content from remote machines - to provide those ** implementations with limits on what needs to be prefetched and thereby ** reduce network bandwidth. ** ** Note that BTREE_HINT_FLAGS with BTREE_BULKLOAD is the only hint used by ** standard SQLite. The other hints are provided for extentions that use ** the SQLite parser and code generator but substitute their own storage ** engine. */ #define BTREE_HINT_RANGE 0 /* Range constraints on queries */ /* ** Values that may be OR'd together to form the argument to the ** BTREE_HINT_FLAGS hint for sqlite3BtreeCursorHint(): ** ** The BTREE_BULKLOAD flag is set on index cursors when the index is going ** to be filled with content that is already in sorted order. ** ** The BTREE_SEEK_EQ flag is set on cursors that will get OP_SeekGE or ** OP_SeekLE opcodes for a range search, but where the range of entries ** selected will all have the same key. In other words, the cursor will ** be used only for equality key searches. ** */ #define BTREE_BULKLOAD 0x00000001 /* Used to full index in sorted order */ #define BTREE_SEEK_EQ 0x00000002 /* EQ seeks only - no range seeks */ /* ** Flags passed as the third argument to sqlite3BtreeCursor(). ** ** For read-only cursors the wrFlag argument is always zero. For read-write ** cursors it may be set to either (BTREE_WRCSR|BTREE_FORDELETE) or just ** (BTREE_WRCSR). If the BTREE_FORDELETE bit is set, then the cursor will ** only be used by SQLite for the following: ** ** * to seek to and then delete specific entries, and/or ** ** * to read values that will be used to create keys that other ** BTREE_FORDELETE cursors will seek to and delete. ** ** The BTREE_FORDELETE flag is an optimization hint. It is not used by ** by this, the native b-tree engine of SQLite, but it is available to ** alternative storage engines that might be substituted in place of this ** b-tree system. For alternative storage engines in which a delete of ** the main table row automatically deletes corresponding index rows, ** the FORDELETE flag hint allows those alternative storage engines to ** skip a lot of work. Namely: FORDELETE cursors may treat all SEEK ** and DELETE operations as no-ops, and any READ operation against a ** FORDELETE cursor may return a null row: 0x01 0x00. */ #define BTREE_WRCSR 0x00000004 /* read-write cursor */ #define BTREE_FORDELETE 0x00000008 /* Cursor is for seek/delete only */ SQLITE_PRIVATE int sqlite3BtreeCursor( Btree*, /* BTree containing table to open */ int iTable, /* Index of root page */ int wrFlag, /* 1 for writing. 0 for read-only */ struct KeyInfo*, /* First argument to compare function */ BtCursor *pCursor /* Space to write cursor structure */ ); SQLITE_PRIVATE int sqlite3BtreeCursorSize(void); SQLITE_PRIVATE void sqlite3BtreeCursorZero(BtCursor*); SQLITE_PRIVATE void sqlite3BtreeCursorHintFlags(BtCursor*, unsigned); #ifdef SQLITE_ENABLE_CURSOR_HINTS SQLITE_PRIVATE void sqlite3BtreeCursorHint(BtCursor*, int, ...); #endif SQLITE_PRIVATE int sqlite3BtreeCloseCursor(BtCursor*); SQLITE_PRIVATE int sqlite3BtreeMovetoUnpacked( BtCursor*, UnpackedRecord *pUnKey, i64 intKey, int bias, int *pRes ); SQLITE_PRIVATE int sqlite3BtreeCursorHasMoved(BtCursor*); SQLITE_PRIVATE int sqlite3BtreeCursorRestore(BtCursor*, int*); SQLITE_PRIVATE int sqlite3BtreeDelete(BtCursor*, u8 flags); /* Allowed flags for the 2nd argument to sqlite3BtreeDelete() */ #define BTREE_SAVEPOSITION 0x02 /* Leave cursor pointing at NEXT or PREV */ #define BTREE_AUXDELETE 0x04 /* not the primary delete operation */ /* An instance of the BtreePayload object describes the content of a single ** entry in either an index or table btree. ** ** Index btrees (used for indexes and also WITHOUT ROWID tables) contain ** an arbitrary key and no data. These btrees have pKey,nKey set to their ** key and pData,nData,nZero set to zero. ** ** Table btrees (used for rowid tables) contain an integer rowid used as ** the key and passed in the nKey field. The pKey field is zero. ** pData,nData hold the content of the new entry. nZero extra zero bytes ** are appended to the end of the content when constructing the entry. ** ** This object is used to pass information into sqlite3BtreeInsert(). The ** same information used to be passed as five separate parameters. But placing ** the information into this object helps to keep the interface more ** organized and understandable, and it also helps the resulting code to ** run a little faster by using fewer registers for parameter passing. */ struct BtreePayload { const void *pKey; /* Key content for indexes. NULL for tables */ sqlite3_int64 nKey; /* Size of pKey for indexes. PRIMARY KEY for tabs */ const void *pData; /* Data for tables. NULL for indexes */ int nData; /* Size of pData. 0 if none. */ int nZero; /* Extra zero data appended after pData,nData */ }; SQLITE_PRIVATE int sqlite3BtreeInsert(BtCursor*, const BtreePayload *pPayload, int bias, int seekResult); SQLITE_PRIVATE int sqlite3BtreeFirst(BtCursor*, int *pRes); SQLITE_PRIVATE int sqlite3BtreeLast(BtCursor*, int *pRes); SQLITE_PRIVATE int sqlite3BtreeNext(BtCursor*, int *pRes); SQLITE_PRIVATE int sqlite3BtreeEof(BtCursor*); SQLITE_PRIVATE int sqlite3BtreePrevious(BtCursor*, int *pRes); SQLITE_PRIVATE i64 sqlite3BtreeIntegerKey(BtCursor*); SQLITE_PRIVATE int sqlite3BtreeKey(BtCursor*, u32 offset, u32 amt, void*); SQLITE_PRIVATE const void *sqlite3BtreePayloadFetch(BtCursor*, u32 *pAmt); SQLITE_PRIVATE u32 sqlite3BtreePayloadSize(BtCursor*); SQLITE_PRIVATE int sqlite3BtreeData(BtCursor*, u32 offset, u32 amt, void*); SQLITE_PRIVATE char *sqlite3BtreeIntegrityCheck(Btree*, int *aRoot, int nRoot, int, int*); SQLITE_PRIVATE struct Pager *sqlite3BtreePager(Btree*); #ifndef SQLITE_OMIT_INCRBLOB SQLITE_PRIVATE int sqlite3BtreePutData(BtCursor*, u32 offset, u32 amt, void*); SQLITE_PRIVATE void sqlite3BtreeIncrblobCursor(BtCursor *); #endif SQLITE_PRIVATE void sqlite3BtreeClearCursor(BtCursor *); SQLITE_PRIVATE int sqlite3BtreeSetVersion(Btree *pBt, int iVersion); SQLITE_PRIVATE int sqlite3BtreeCursorHasHint(BtCursor*, unsigned int mask); SQLITE_PRIVATE int sqlite3BtreeIsReadonly(Btree *pBt); SQLITE_PRIVATE int sqlite3HeaderSizeBtree(void); #ifndef NDEBUG SQLITE_PRIVATE int sqlite3BtreeCursorIsValid(BtCursor*); #endif #ifndef SQLITE_OMIT_BTREECOUNT SQLITE_PRIVATE int sqlite3BtreeCount(BtCursor *, i64 *); #endif #ifdef SQLITE_TEST SQLITE_PRIVATE int sqlite3BtreeCursorInfo(BtCursor*, int*, int); SQLITE_PRIVATE void sqlite3BtreeCursorList(Btree*); #endif #ifndef SQLITE_OMIT_WAL SQLITE_PRIVATE int sqlite3BtreeCheckpoint(Btree*, int, int *, int *); #endif /* ** If we are not using shared cache, then there is no need to ** use mutexes to access the BtShared structures. So make the ** Enter and Leave procedures no-ops. */ #ifndef SQLITE_OMIT_SHARED_CACHE SQLITE_PRIVATE void sqlite3BtreeEnter(Btree*); SQLITE_PRIVATE void sqlite3BtreeEnterAll(sqlite3*); SQLITE_PRIVATE int sqlite3BtreeSharable(Btree*); SQLITE_PRIVATE void sqlite3BtreeEnterCursor(BtCursor*); SQLITE_PRIVATE int sqlite3BtreeConnectionCount(Btree*); #else # define sqlite3BtreeEnter(X) # define sqlite3BtreeEnterAll(X) # define sqlite3BtreeSharable(X) 0 # define sqlite3BtreeEnterCursor(X) # define sqlite3BtreeConnectionCount(X) 1 #endif #if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE SQLITE_PRIVATE void sqlite3BtreeLeave(Btree*); SQLITE_PRIVATE void sqlite3BtreeLeaveCursor(BtCursor*); SQLITE_PRIVATE void sqlite3BtreeLeaveAll(sqlite3*); #ifndef NDEBUG /* These routines are used inside assert() statements only. */ SQLITE_PRIVATE int sqlite3BtreeHoldsMutex(Btree*); SQLITE_PRIVATE int sqlite3BtreeHoldsAllMutexes(sqlite3*); SQLITE_PRIVATE int sqlite3SchemaMutexHeld(sqlite3*,int,Schema*); #endif #else # define sqlite3BtreeLeave(X) # define sqlite3BtreeLeaveCursor(X) # define sqlite3BtreeLeaveAll(X) # define sqlite3BtreeHoldsMutex(X) 1 # define sqlite3BtreeHoldsAllMutexes(X) 1 # define sqlite3SchemaMutexHeld(X,Y,Z) 1 #endif #endif /* SQLITE_BTREE_H */ /************** End of btree.h ***********************************************/ /************** Continuing where we left off in sqliteInt.h ******************/ /************** Include vdbe.h in the middle of sqliteInt.h ******************/ /************** Begin file vdbe.h ********************************************/ /* ** 2001 September 15 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ************************************************************************* ** Header file for the Virtual DataBase Engine (VDBE) ** ** This header defines the interface to the virtual database engine ** or VDBE. The VDBE implements an abstract machine that runs a ** simple program to access and modify the underlying database. */ #ifndef SQLITE_VDBE_H #define SQLITE_VDBE_H /* #include */ /* ** A single VDBE is an opaque structure named "Vdbe". Only routines ** in the source file sqliteVdbe.c are allowed to see the insides ** of this structure. */ typedef struct Vdbe Vdbe; /* ** The names of the following types declared in vdbeInt.h are required ** for the VdbeOp definition. */ typedef struct Mem Mem; typedef struct SubProgram SubProgram; /* ** A single instruction of the virtual machine has an opcode ** and as many as three operands. The instruction is recorded ** as an instance of the following structure: */ struct VdbeOp { u8 opcode; /* What operation to perform */ signed char p4type; /* One of the P4_xxx constants for p4 */ u8 notUsed1; u8 p5; /* Fifth parameter is an unsigned character */ int p1; /* First operand */ int p2; /* Second parameter (often the jump destination) */ int p3; /* The third parameter */ union p4union { /* fourth parameter */ int i; /* Integer value if p4type==P4_INT32 */ void *p; /* Generic pointer */ char *z; /* Pointer to data for string (char array) types */ i64 *pI64; /* Used when p4type is P4_INT64 */ double *pReal; /* Used when p4type is P4_REAL */ FuncDef *pFunc; /* Used when p4type is P4_FUNCDEF */ sqlite3_context *pCtx; /* Used when p4type is P4_FUNCCTX */ CollSeq *pColl; /* Used when p4type is P4_COLLSEQ */ Mem *pMem; /* Used when p4type is P4_MEM */ VTable *pVtab; /* Used when p4type is P4_VTAB */ KeyInfo *pKeyInfo; /* Used when p4type is P4_KEYINFO */ int *ai; /* Used when p4type is P4_INTARRAY */ SubProgram *pProgram; /* Used when p4type is P4_SUBPROGRAM */ Table *pTab; /* Used when p4type is P4_TABLE */ #ifdef SQLITE_ENABLE_CURSOR_HINTS Expr *pExpr; /* Used when p4type is P4_EXPR */ #endif int (*xAdvance)(BtCursor *, int *); } p4; #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS char *zComment; /* Comment to improve readability */ #endif #ifdef VDBE_PROFILE u32 cnt; /* Number of times this instruction was executed */ u64 cycles; /* Total time spent executing this instruction */ #endif #ifdef SQLITE_VDBE_COVERAGE int iSrcLine; /* Source-code line that generated this opcode */ #endif }; typedef struct VdbeOp VdbeOp; /* ** A sub-routine used to implement a trigger program. */ struct SubProgram { VdbeOp *aOp; /* Array of opcodes for sub-program */ int nOp; /* Elements in aOp[] */ int nMem; /* Number of memory cells required */ int nCsr; /* Number of cursors required */ void *token; /* id that may be used to recursive triggers */ SubProgram *pNext; /* Next sub-program already visited */ }; /* ** A smaller version of VdbeOp used for the VdbeAddOpList() function because ** it takes up less space. */ struct VdbeOpList { u8 opcode; /* What operation to perform */ signed char p1; /* First operand */ signed char p2; /* Second parameter (often the jump destination) */ signed char p3; /* Third parameter */ }; typedef struct VdbeOpList VdbeOpList; /* ** Allowed values of VdbeOp.p4type */ #define P4_NOTUSED 0 /* The P4 parameter is not used */ #define P4_DYNAMIC (-1) /* Pointer to a string obtained from sqliteMalloc() */ #define P4_STATIC (-2) /* Pointer to a static string */ #define P4_COLLSEQ (-4) /* P4 is a pointer to a CollSeq structure */ #define P4_FUNCDEF (-5) /* P4 is a pointer to a FuncDef structure */ #define P4_KEYINFO (-6) /* P4 is a pointer to a KeyInfo structure */ #define P4_EXPR (-7) /* P4 is a pointer to an Expr tree */ #define P4_MEM (-8) /* P4 is a pointer to a Mem* structure */ #define P4_TRANSIENT 0 /* P4 is a pointer to a transient string */ #define P4_VTAB (-10) /* P4 is a pointer to an sqlite3_vtab structure */ #define P4_MPRINTF (-11) /* P4 is a string obtained from sqlite3_mprintf() */ #define P4_REAL (-12) /* P4 is a 64-bit floating point value */ #define P4_INT64 (-13) /* P4 is a 64-bit signed integer */ #define P4_INT32 (-14) /* P4 is a 32-bit signed integer */ #define P4_INTARRAY (-15) /* P4 is a vector of 32-bit integers */ #define P4_SUBPROGRAM (-18) /* P4 is a pointer to a SubProgram structure */ #define P4_ADVANCE (-19) /* P4 is a pointer to BtreeNext() or BtreePrev() */ #define P4_TABLE (-20) /* P4 is a pointer to a Table structure */ #define P4_FUNCCTX (-21) /* P4 is a pointer to an sqlite3_context object */ /* Error message codes for OP_Halt */ #define P5_ConstraintNotNull 1 #define P5_ConstraintUnique 2 #define P5_ConstraintCheck 3 #define P5_ConstraintFK 4 /* ** The Vdbe.aColName array contains 5n Mem structures, where n is the ** number of columns of data returned by the statement. */ #define COLNAME_NAME 0 #define COLNAME_DECLTYPE 1 #define COLNAME_DATABASE 2 #define COLNAME_TABLE 3 #define COLNAME_COLUMN 4 #ifdef SQLITE_ENABLE_COLUMN_METADATA # define COLNAME_N 5 /* Number of COLNAME_xxx symbols */ #else # ifdef SQLITE_OMIT_DECLTYPE # define COLNAME_N 1 /* Store only the name */ # else # define COLNAME_N 2 /* Store the name and decltype */ # endif #endif /* ** The following macro converts a relative address in the p2 field ** of a VdbeOp structure into a negative number so that ** sqlite3VdbeAddOpList() knows that the address is relative. Calling ** the macro again restores the address. */ #define ADDR(X) (-1-(X)) /* ** The makefile scans the vdbe.c source file and creates the "opcodes.h" ** header file that defines a number for each opcode used by the VDBE. */ /************** Include opcodes.h in the middle of vdbe.h ********************/ /************** Begin file opcodes.h *****************************************/ /* Automatically generated. Do not edit */ /* See the tool/mkopcodeh.tcl script for details */ #define OP_Savepoint 0 #define OP_AutoCommit 1 #define OP_Transaction 2 #define OP_SorterNext 3 #define OP_PrevIfOpen 4 #define OP_NextIfOpen 5 #define OP_Prev 6 #define OP_Next 7 #define OP_Checkpoint 8 #define OP_JournalMode 9 #define OP_Vacuum 10 #define OP_VFilter 11 /* synopsis: iplan=r[P3] zplan='P4' */ #define OP_VUpdate 12 /* synopsis: data=r[P3@P2] */ #define OP_Goto 13 #define OP_Gosub 14 #define OP_InitCoroutine 15 #define OP_Yield 16 #define OP_MustBeInt 17 #define OP_Jump 18 #define OP_Not 19 /* same as TK_NOT, synopsis: r[P2]= !r[P1] */ #define OP_Once 20 #define OP_If 21 #define OP_IfNot 22 #define OP_SeekLT 23 /* synopsis: key=r[P3@P4] */ #define OP_SeekLE 24 /* synopsis: key=r[P3@P4] */ #define OP_SeekGE 25 /* synopsis: key=r[P3@P4] */ #define OP_SeekGT 26 /* synopsis: key=r[P3@P4] */ #define OP_Or 27 /* same as TK_OR, synopsis: r[P3]=(r[P1] || r[P2]) */ #define OP_And 28 /* same as TK_AND, synopsis: r[P3]=(r[P1] && r[P2]) */ #define OP_NoConflict 29 /* synopsis: key=r[P3@P4] */ #define OP_NotFound 30 /* synopsis: key=r[P3@P4] */ #define OP_Found 31 /* synopsis: key=r[P3@P4] */ #define OP_SeekRowid 32 /* synopsis: intkey=r[P3] */ #define OP_NotExists 33 /* synopsis: intkey=r[P3] */ #define OP_IsNull 34 /* same as TK_ISNULL, synopsis: if r[P1]==NULL goto P2 */ #define OP_NotNull 35 /* same as TK_NOTNULL, synopsis: if r[P1]!=NULL goto P2 */ #define OP_Ne 36 /* same as TK_NE, synopsis: IF r[P3]!=r[P1] */ #define OP_Eq 37 /* same as TK_EQ, synopsis: IF r[P3]==r[P1] */ #define OP_Gt 38 /* same as TK_GT, synopsis: IF r[P3]>r[P1] */ #define OP_Le 39 /* same as TK_LE, synopsis: IF r[P3]<=r[P1] */ #define OP_Lt 40 /* same as TK_LT, synopsis: IF r[P3]=r[P1] */ #define OP_ElseNotEq 42 /* same as TK_ESCAPE */ #define OP_BitAnd 43 /* same as TK_BITAND, synopsis: r[P3]=r[P1]&r[P2] */ #define OP_BitOr 44 /* same as TK_BITOR, synopsis: r[P3]=r[P1]|r[P2] */ #define OP_ShiftLeft 45 /* same as TK_LSHIFT, synopsis: r[P3]=r[P2]<>r[P1] */ #define OP_Add 47 /* same as TK_PLUS, synopsis: r[P3]=r[P1]+r[P2] */ #define OP_Subtract 48 /* same as TK_MINUS, synopsis: r[P3]=r[P2]-r[P1] */ #define OP_Multiply 49 /* same as TK_STAR, synopsis: r[P3]=r[P1]*r[P2] */ #define OP_Divide 50 /* same as TK_SLASH, synopsis: r[P3]=r[P2]/r[P1] */ #define OP_Remainder 51 /* same as TK_REM, synopsis: r[P3]=r[P2]%r[P1] */ #define OP_Concat 52 /* same as TK_CONCAT, synopsis: r[P3]=r[P2]+r[P1] */ #define OP_Last 53 #define OP_BitNot 54 /* same as TK_BITNOT, synopsis: r[P1]= ~r[P1] */ #define OP_SorterSort 55 #define OP_Sort 56 #define OP_Rewind 57 #define OP_IdxLE 58 /* synopsis: key=r[P3@P4] */ #define OP_IdxGT 59 /* synopsis: key=r[P3@P4] */ #define OP_IdxLT 60 /* synopsis: key=r[P3@P4] */ #define OP_IdxGE 61 /* synopsis: key=r[P3@P4] */ #define OP_RowSetRead 62 /* synopsis: r[P3]=rowset(P1) */ #define OP_RowSetTest 63 /* synopsis: if r[P3] in rowset(P1) goto P2 */ #define OP_Program 64 #define OP_FkIfZero 65 /* synopsis: if fkctr[P1]==0 goto P2 */ #define OP_IfPos 66 /* synopsis: if r[P1]>0 then r[P1]-=P3, goto P2 */ #define OP_IfNotZero 67 /* synopsis: if r[P1]!=0 then r[P1]-=P3, goto P2 */ #define OP_DecrJumpZero 68 /* synopsis: if (--r[P1])==0 goto P2 */ #define OP_IncrVacuum 69 #define OP_VNext 70 #define OP_Init 71 /* synopsis: Start at P2 */ #define OP_Return 72 #define OP_EndCoroutine 73 #define OP_HaltIfNull 74 /* synopsis: if r[P3]=null halt */ #define OP_Halt 75 #define OP_Integer 76 /* synopsis: r[P2]=P1 */ #define OP_Int64 77 /* synopsis: r[P2]=P4 */ #define OP_String 78 /* synopsis: r[P2]='P4' (len=P1) */ #define OP_Null 79 /* synopsis: r[P2..P3]=NULL */ #define OP_SoftNull 80 /* synopsis: r[P1]=NULL */ #define OP_Blob 81 /* synopsis: r[P2]=P4 (len=P1) */ #define OP_Variable 82 /* synopsis: r[P2]=parameter(P1,P4) */ #define OP_Move 83 /* synopsis: r[P2@P3]=r[P1@P3] */ #define OP_Copy 84 /* synopsis: r[P2@P3+1]=r[P1@P3+1] */ #define OP_SCopy 85 /* synopsis: r[P2]=r[P1] */ #define OP_IntCopy 86 /* synopsis: r[P2]=r[P1] */ #define OP_ResultRow 87 /* synopsis: output=r[P1@P2] */ #define OP_CollSeq 88 #define OP_Function0 89 /* synopsis: r[P3]=func(r[P2@P5]) */ #define OP_Function 90 /* synopsis: r[P3]=func(r[P2@P5]) */ #define OP_AddImm 91 /* synopsis: r[P1]=r[P1]+P2 */ #define OP_RealAffinity 92 #define OP_Cast 93 /* synopsis: affinity(r[P1]) */ #define OP_Permutation 94 #define OP_Compare 95 /* synopsis: r[P1@P3] <-> r[P2@P3] */ #define OP_Column 96 /* synopsis: r[P3]=PX */ #define OP_String8 97 /* same as TK_STRING, synopsis: r[P2]='P4' */ #define OP_Affinity 98 /* synopsis: affinity(r[P1@P2]) */ #define OP_MakeRecord 99 /* synopsis: r[P3]=mkrec(r[P1@P2]) */ #define OP_Count 100 /* synopsis: r[P2]=count() */ #define OP_ReadCookie 101 #define OP_SetCookie 102 #define OP_ReopenIdx 103 /* synopsis: root=P2 iDb=P3 */ #define OP_OpenRead 104 /* synopsis: root=P2 iDb=P3 */ #define OP_OpenWrite 105 /* synopsis: root=P2 iDb=P3 */ #define OP_OpenAutoindex 106 /* synopsis: nColumn=P2 */ #define OP_OpenEphemeral 107 /* synopsis: nColumn=P2 */ #define OP_SorterOpen 108 #define OP_SequenceTest 109 /* synopsis: if( cursor[P1].ctr++ ) pc = P2 */ #define OP_OpenPseudo 110 /* synopsis: P3 columns in r[P2] */ #define OP_Close 111 #define OP_ColumnsUsed 112 #define OP_Sequence 113 /* synopsis: r[P2]=cursor[P1].ctr++ */ #define OP_NewRowid 114 /* synopsis: r[P2]=rowid */ #define OP_Insert 115 /* synopsis: intkey=r[P3] data=r[P2] */ #define OP_InsertInt 116 /* synopsis: intkey=P3 data=r[P2] */ #define OP_Delete 117 #define OP_ResetCount 118 #define OP_SorterCompare 119 /* synopsis: if key(P1)!=trim(r[P3],P4) goto P2 */ #define OP_SorterData 120 /* synopsis: r[P2]=data */ #define OP_RowKey 121 /* synopsis: r[P2]=key */ #define OP_RowData 122 /* synopsis: r[P2]=data */ #define OP_Rowid 123 /* synopsis: r[P2]=rowid */ #define OP_NullRow 124 #define OP_SorterInsert 125 #define OP_IdxInsert 126 /* synopsis: key=r[P2] */ #define OP_IdxDelete 127 /* synopsis: key=r[P2@P3] */ #define OP_Seek 128 /* synopsis: Move P3 to P1.rowid */ #define OP_IdxRowid 129 /* synopsis: r[P2]=rowid */ #define OP_Destroy 130 #define OP_Clear 131 #define OP_Real 132 /* same as TK_FLOAT, synopsis: r[P2]=P4 */ #define OP_ResetSorter 133 #define OP_CreateIndex 134 /* synopsis: r[P2]=root iDb=P1 */ #define OP_CreateTable 135 /* synopsis: r[P2]=root iDb=P1 */ #define OP_ParseSchema 136 #define OP_LoadAnalysis 137 #define OP_DropTable 138 #define OP_DropIndex 139 #define OP_DropTrigger 140 #define OP_IntegrityCk 141 #define OP_RowSetAdd 142 /* synopsis: rowset(P1)=r[P2] */ #define OP_Param 143 #define OP_FkCounter 144 /* synopsis: fkctr[P1]+=P2 */ #define OP_MemMax 145 /* synopsis: r[P1]=max(r[P1],r[P2]) */ #define OP_OffsetLimit 146 /* synopsis: if r[P1]>0 then r[P2]=r[P1]+max(0,r[P3]) else r[P2]=(-1) */ #define OP_AggStep0 147 /* synopsis: accum=r[P3] step(r[P2@P5]) */ #define OP_AggStep 148 /* synopsis: accum=r[P3] step(r[P2@P5]) */ #define OP_AggFinal 149 /* synopsis: accum=r[P1] N=P2 */ #define OP_Expire 150 #define OP_TableLock 151 /* synopsis: iDb=P1 root=P2 write=P3 */ #define OP_VBegin 152 #define OP_VCreate 153 #define OP_VDestroy 154 #define OP_VOpen 155 #define OP_VColumn 156 /* synopsis: r[P3]=vcolumn(P2) */ #define OP_VRename 157 #define OP_Pagecount 158 #define OP_MaxPgcnt 159 #define OP_CursorHint 160 #define OP_Noop 161 #define OP_Explain 162 /* Properties such as "out2" or "jump" that are specified in ** comments following the "case" for each opcode in the vdbe.c ** are encoded into bitvectors as follows: */ #define OPFLG_JUMP 0x01 /* jump: P2 holds jmp target */ #define OPFLG_IN1 0x02 /* in1: P1 is an input */ #define OPFLG_IN2 0x04 /* in2: P2 is an input */ #define OPFLG_IN3 0x08 /* in3: P3 is an input */ #define OPFLG_OUT2 0x10 /* out2: P2 is an output */ #define OPFLG_OUT3 0x20 /* out3: P3 is an output */ #define OPFLG_INITIALIZER {\ /* 0 */ 0x00, 0x00, 0x00, 0x01, 0x01, 0x01, 0x01, 0x01,\ /* 8 */ 0x00, 0x10, 0x00, 0x01, 0x00, 0x01, 0x01, 0x01,\ /* 16 */ 0x03, 0x03, 0x01, 0x12, 0x01, 0x03, 0x03, 0x09,\ /* 24 */ 0x09, 0x09, 0x09, 0x26, 0x26, 0x09, 0x09, 0x09,\ /* 32 */ 0x09, 0x09, 0x03, 0x03, 0x0b, 0x0b, 0x0b, 0x0b,\ /* 40 */ 0x0b, 0x0b, 0x01, 0x26, 0x26, 0x26, 0x26, 0x26,\ /* 48 */ 0x26, 0x26, 0x26, 0x26, 0x26, 0x01, 0x12, 0x01,\ /* 56 */ 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x23, 0x0b,\ /* 64 */ 0x01, 0x01, 0x03, 0x03, 0x03, 0x01, 0x01, 0x01,\ /* 72 */ 0x02, 0x02, 0x08, 0x00, 0x10, 0x10, 0x10, 0x10,\ /* 80 */ 0x00, 0x10, 0x10, 0x00, 0x00, 0x10, 0x10, 0x00,\ /* 88 */ 0x00, 0x00, 0x00, 0x02, 0x02, 0x02, 0x00, 0x00,\ /* 96 */ 0x00, 0x10, 0x00, 0x00, 0x10, 0x10, 0x00, 0x00,\ /* 104 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\ /* 112 */ 0x00, 0x10, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00,\ /* 120 */ 0x00, 0x00, 0x00, 0x10, 0x00, 0x04, 0x04, 0x00,\ /* 128 */ 0x00, 0x10, 0x10, 0x00, 0x10, 0x00, 0x10, 0x10,\ /* 136 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x06, 0x10,\ /* 144 */ 0x00, 0x04, 0x1a, 0x00, 0x00, 0x00, 0x00, 0x00,\ /* 152 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0x10,\ /* 160 */ 0x00, 0x00, 0x00,} /* The sqlite3P2Values() routine is able to run faster if it knows ** the value of the largest JUMP opcode. The smaller the maximum ** JUMP opcode the better, so the mkopcodeh.tcl script that ** generated this include file strives to group all JUMP opcodes ** together near the beginning of the list. */ #define SQLITE_MX_JUMP_OPCODE 71 /* Maximum JUMP opcode */ /************** End of opcodes.h *********************************************/ /************** Continuing where we left off in vdbe.h ***********************/ /* ** Prototypes for the VDBE interface. See comments on the implementation ** for a description of what each of these routines does. */ SQLITE_PRIVATE Vdbe *sqlite3VdbeCreate(Parse*); SQLITE_PRIVATE int sqlite3VdbeAddOp0(Vdbe*,int); SQLITE_PRIVATE int sqlite3VdbeAddOp1(Vdbe*,int,int); SQLITE_PRIVATE int sqlite3VdbeAddOp2(Vdbe*,int,int,int); SQLITE_PRIVATE int sqlite3VdbeGoto(Vdbe*,int); SQLITE_PRIVATE int sqlite3VdbeLoadString(Vdbe*,int,const char*); SQLITE_PRIVATE void sqlite3VdbeMultiLoad(Vdbe*,int,const char*,...); SQLITE_PRIVATE int sqlite3VdbeAddOp3(Vdbe*,int,int,int,int); SQLITE_PRIVATE int sqlite3VdbeAddOp4(Vdbe*,int,int,int,int,const char *zP4,int); SQLITE_PRIVATE int sqlite3VdbeAddOp4Dup8(Vdbe*,int,int,int,int,const u8*,int); SQLITE_PRIVATE int sqlite3VdbeAddOp4Int(Vdbe*,int,int,int,int,int); SQLITE_PRIVATE void sqlite3VdbeEndCoroutine(Vdbe*,int); #if defined(SQLITE_DEBUG) && !defined(SQLITE_TEST_REALLOC_STRESS) SQLITE_PRIVATE void sqlite3VdbeVerifyNoMallocRequired(Vdbe *p, int N); #else # define sqlite3VdbeVerifyNoMallocRequired(A,B) #endif SQLITE_PRIVATE VdbeOp *sqlite3VdbeAddOpList(Vdbe*, int nOp, VdbeOpList const *aOp, int iLineno); SQLITE_PRIVATE void sqlite3VdbeAddParseSchemaOp(Vdbe*,int,char*); SQLITE_PRIVATE void sqlite3VdbeChangeOpcode(Vdbe*, u32 addr, u8); SQLITE_PRIVATE void sqlite3VdbeChangeP1(Vdbe*, u32 addr, int P1); SQLITE_PRIVATE void sqlite3VdbeChangeP2(Vdbe*, u32 addr, int P2); SQLITE_PRIVATE void sqlite3VdbeChangeP3(Vdbe*, u32 addr, int P3); SQLITE_PRIVATE void sqlite3VdbeChangeP5(Vdbe*, u8 P5); SQLITE_PRIVATE void sqlite3VdbeJumpHere(Vdbe*, int addr); SQLITE_PRIVATE int sqlite3VdbeChangeToNoop(Vdbe*, int addr); SQLITE_PRIVATE int sqlite3VdbeDeletePriorOpcode(Vdbe*, u8 op); SQLITE_PRIVATE void sqlite3VdbeChangeP4(Vdbe*, int addr, const char *zP4, int N); SQLITE_PRIVATE void sqlite3VdbeSetP4KeyInfo(Parse*, Index*); SQLITE_PRIVATE void sqlite3VdbeUsesBtree(Vdbe*, int); SQLITE_PRIVATE VdbeOp *sqlite3VdbeGetOp(Vdbe*, int); SQLITE_PRIVATE int sqlite3VdbeMakeLabel(Vdbe*); SQLITE_PRIVATE void sqlite3VdbeRunOnlyOnce(Vdbe*); SQLITE_PRIVATE void sqlite3VdbeReusable(Vdbe*); SQLITE_PRIVATE void sqlite3VdbeDelete(Vdbe*); SQLITE_PRIVATE void sqlite3VdbeClearObject(sqlite3*,Vdbe*); SQLITE_PRIVATE void sqlite3VdbeMakeReady(Vdbe*,Parse*); SQLITE_PRIVATE int sqlite3VdbeFinalize(Vdbe*); SQLITE_PRIVATE void sqlite3VdbeResolveLabel(Vdbe*, int); SQLITE_PRIVATE int sqlite3VdbeCurrentAddr(Vdbe*); #ifdef SQLITE_DEBUG SQLITE_PRIVATE int sqlite3VdbeAssertMayAbort(Vdbe *, int); #endif SQLITE_PRIVATE void sqlite3VdbeResetStepResult(Vdbe*); SQLITE_PRIVATE void sqlite3VdbeRewind(Vdbe*); SQLITE_PRIVATE int sqlite3VdbeReset(Vdbe*); SQLITE_PRIVATE void sqlite3VdbeSetNumCols(Vdbe*,int); SQLITE_PRIVATE int sqlite3VdbeSetColName(Vdbe*, int, int, const char *, void(*)(void*)); SQLITE_PRIVATE void sqlite3VdbeCountChanges(Vdbe*); SQLITE_PRIVATE sqlite3 *sqlite3VdbeDb(Vdbe*); SQLITE_PRIVATE void sqlite3VdbeSetSql(Vdbe*, const char *z, int n, int); SQLITE_PRIVATE void sqlite3VdbeSwap(Vdbe*,Vdbe*); SQLITE_PRIVATE VdbeOp *sqlite3VdbeTakeOpArray(Vdbe*, int*, int*); SQLITE_PRIVATE sqlite3_value *sqlite3VdbeGetBoundValue(Vdbe*, int, u8); SQLITE_PRIVATE void sqlite3VdbeSetVarmask(Vdbe*, int); #ifndef SQLITE_OMIT_TRACE SQLITE_PRIVATE char *sqlite3VdbeExpandSql(Vdbe*, const char*); #endif SQLITE_PRIVATE int sqlite3MemCompare(const Mem*, const Mem*, const CollSeq*); SQLITE_PRIVATE void sqlite3VdbeRecordUnpack(KeyInfo*,int,const void*,UnpackedRecord*); SQLITE_PRIVATE int sqlite3VdbeRecordCompare(int,const void*,UnpackedRecord*); SQLITE_PRIVATE int sqlite3VdbeRecordCompareWithSkip(int, const void *, UnpackedRecord *, int); SQLITE_PRIVATE UnpackedRecord *sqlite3VdbeAllocUnpackedRecord(KeyInfo *, char *, int, char **); typedef int (*RecordCompare)(int,const void*,UnpackedRecord*); SQLITE_PRIVATE RecordCompare sqlite3VdbeFindCompare(UnpackedRecord*); #ifndef SQLITE_OMIT_TRIGGER SQLITE_PRIVATE void sqlite3VdbeLinkSubProgram(Vdbe *, SubProgram *); #endif /* Use SQLITE_ENABLE_COMMENTS to enable generation of extra comments on ** each VDBE opcode. ** ** Use the SQLITE_ENABLE_MODULE_COMMENTS macro to see some extra no-op ** comments in VDBE programs that show key decision points in the code ** generator. */ #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS SQLITE_PRIVATE void sqlite3VdbeComment(Vdbe*, const char*, ...); # define VdbeComment(X) sqlite3VdbeComment X SQLITE_PRIVATE void sqlite3VdbeNoopComment(Vdbe*, const char*, ...); # define VdbeNoopComment(X) sqlite3VdbeNoopComment X # ifdef SQLITE_ENABLE_MODULE_COMMENTS # define VdbeModuleComment(X) sqlite3VdbeNoopComment X # else # define VdbeModuleComment(X) # endif #else # define VdbeComment(X) # define VdbeNoopComment(X) # define VdbeModuleComment(X) #endif /* ** The VdbeCoverage macros are used to set a coverage testing point ** for VDBE branch instructions. The coverage testing points are line ** numbers in the sqlite3.c source file. VDBE branch coverage testing ** only works with an amalagmation build. That's ok since a VDBE branch ** coverage build designed for testing the test suite only. No application ** should ever ship with VDBE branch coverage measuring turned on. ** ** VdbeCoverage(v) // Mark the previously coded instruction ** // as a branch ** ** VdbeCoverageIf(v, conditional) // Mark previous if conditional true ** ** VdbeCoverageAlwaysTaken(v) // Previous branch is always taken ** ** VdbeCoverageNeverTaken(v) // Previous branch is never taken ** ** Every VDBE branch operation must be tagged with one of the macros above. ** If not, then when "make test" is run with -DSQLITE_VDBE_COVERAGE and ** -DSQLITE_DEBUG then an ALWAYS() will fail in the vdbeTakeBranch() ** routine in vdbe.c, alerting the developer to the missed tag. */ #ifdef SQLITE_VDBE_COVERAGE SQLITE_PRIVATE void sqlite3VdbeSetLineNumber(Vdbe*,int); # define VdbeCoverage(v) sqlite3VdbeSetLineNumber(v,__LINE__) # define VdbeCoverageIf(v,x) if(x)sqlite3VdbeSetLineNumber(v,__LINE__) # define VdbeCoverageAlwaysTaken(v) sqlite3VdbeSetLineNumber(v,2); # define VdbeCoverageNeverTaken(v) sqlite3VdbeSetLineNumber(v,1); # define VDBE_OFFSET_LINENO(x) (__LINE__+x) #else # define VdbeCoverage(v) # define VdbeCoverageIf(v,x) # define VdbeCoverageAlwaysTaken(v) # define VdbeCoverageNeverTaken(v) # define VDBE_OFFSET_LINENO(x) 0 #endif #ifdef SQLITE_ENABLE_STMT_SCANSTATUS SQLITE_PRIVATE void sqlite3VdbeScanStatus(Vdbe*, int, int, int, LogEst, const char*); #else # define sqlite3VdbeScanStatus(a,b,c,d,e) #endif #endif /* SQLITE_VDBE_H */ /************** End of vdbe.h ************************************************/ /************** Continuing where we left off in sqliteInt.h ******************/ /************** Include pager.h in the middle of sqliteInt.h *****************/ /************** Begin file pager.h *******************************************/ /* ** 2001 September 15 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ************************************************************************* ** This header file defines the interface that the sqlite page cache ** subsystem. The page cache subsystem reads and writes a file a page ** at a time and provides a journal for rollback. */ #ifndef SQLITE_PAGER_H #define SQLITE_PAGER_H /* ** Default maximum size for persistent journal files. A negative ** value means no limit. This value may be overridden using the ** sqlite3PagerJournalSizeLimit() API. See also "PRAGMA journal_size_limit". */ #ifndef SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT #define SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT -1 #endif /* ** The type used to represent a page number. The first page in a file ** is called page 1. 0 is used to represent "not a page". */ typedef u32 Pgno; /* ** Each open file is managed by a separate instance of the "Pager" structure. */ typedef struct Pager Pager; /* ** Handle type for pages. */ typedef struct PgHdr DbPage; /* ** Page number PAGER_MJ_PGNO is never used in an SQLite database (it is ** reserved for working around a windows/posix incompatibility). It is ** used in the journal to signify that the remainder of the journal file ** is devoted to storing a master journal name - there are no more pages to ** roll back. See comments for function writeMasterJournal() in pager.c ** for details. */ #define PAGER_MJ_PGNO(x) ((Pgno)((PENDING_BYTE/((x)->pageSize))+1)) /* ** Allowed values for the flags parameter to sqlite3PagerOpen(). ** ** NOTE: These values must match the corresponding BTREE_ values in btree.h. */ #define PAGER_OMIT_JOURNAL 0x0001 /* Do not use a rollback journal */ #define PAGER_MEMORY 0x0002 /* In-memory database */ /* ** Valid values for the second argument to sqlite3PagerLockingMode(). */ #define PAGER_LOCKINGMODE_QUERY -1 #define PAGER_LOCKINGMODE_NORMAL 0 #define PAGER_LOCKINGMODE_EXCLUSIVE 1 /* ** Numeric constants that encode the journalmode. ** ** The numeric values encoded here (other than PAGER_JOURNALMODE_QUERY) ** are exposed in the API via the "PRAGMA journal_mode" command and ** therefore cannot be changed without a compatibility break. */ #define PAGER_JOURNALMODE_QUERY (-1) /* Query the value of journalmode */ #define PAGER_JOURNALMODE_DELETE 0 /* Commit by deleting journal file */ #define PAGER_JOURNALMODE_PERSIST 1 /* Commit by zeroing journal header */ #define PAGER_JOURNALMODE_OFF 2 /* Journal omitted. */ #define PAGER_JOURNALMODE_TRUNCATE 3 /* Commit by truncating journal */ #define PAGER_JOURNALMODE_MEMORY 4 /* In-memory journal file */ #define PAGER_JOURNALMODE_WAL 5 /* Use write-ahead logging */ /* ** Flags that make up the mask passed to sqlite3PagerGet(). */ #define PAGER_GET_NOCONTENT 0x01 /* Do not load data from disk */ #define PAGER_GET_READONLY 0x02 /* Read-only page is acceptable */ /* ** Flags for sqlite3PagerSetFlags() ** ** Value constraints (enforced via assert()): ** PAGER_FULLFSYNC == SQLITE_FullFSync ** PAGER_CKPT_FULLFSYNC == SQLITE_CkptFullFSync ** PAGER_CACHE_SPILL == SQLITE_CacheSpill */ #define PAGER_SYNCHRONOUS_OFF 0x01 /* PRAGMA synchronous=OFF */ #define PAGER_SYNCHRONOUS_NORMAL 0x02 /* PRAGMA synchronous=NORMAL */ #define PAGER_SYNCHRONOUS_FULL 0x03 /* PRAGMA synchronous=FULL */ #define PAGER_SYNCHRONOUS_EXTRA 0x04 /* PRAGMA synchronous=EXTRA */ #define PAGER_SYNCHRONOUS_MASK 0x07 /* Mask for four values above */ #define PAGER_FULLFSYNC 0x08 /* PRAGMA fullfsync=ON */ #define PAGER_CKPT_FULLFSYNC 0x10 /* PRAGMA checkpoint_fullfsync=ON */ #define PAGER_CACHESPILL 0x20 /* PRAGMA cache_spill=ON */ #define PAGER_FLAGS_MASK 0x38 /* All above except SYNCHRONOUS */ /* ** The remainder of this file contains the declarations of the functions ** that make up the Pager sub-system API. See source code comments for ** a detailed description of each routine. */ /* Open and close a Pager connection. */ SQLITE_PRIVATE int sqlite3PagerOpen( sqlite3_vfs*, Pager **ppPager, const char*, int, int, int, void(*)(DbPage*) ); SQLITE_PRIVATE int sqlite3PagerClose(Pager *pPager); SQLITE_PRIVATE int sqlite3PagerReadFileheader(Pager*, int, unsigned char*); /* Functions used to configure a Pager object. */ SQLITE_PRIVATE void sqlite3PagerSetBusyhandler(Pager*, int(*)(void *), void *); SQLITE_PRIVATE int sqlite3PagerSetPagesize(Pager*, u32*, int); #ifdef SQLITE_HAS_CODEC SQLITE_PRIVATE void sqlite3PagerAlignReserve(Pager*,Pager*); #endif SQLITE_PRIVATE int sqlite3PagerMaxPageCount(Pager*, int); SQLITE_PRIVATE void sqlite3PagerSetCachesize(Pager*, int); SQLITE_PRIVATE int sqlite3PagerSetSpillsize(Pager*, int); SQLITE_PRIVATE void sqlite3PagerSetMmapLimit(Pager *, sqlite3_int64); SQLITE_PRIVATE void sqlite3PagerShrink(Pager*); SQLITE_PRIVATE void sqlite3PagerSetFlags(Pager*,unsigned); SQLITE_PRIVATE int sqlite3PagerLockingMode(Pager *, int); SQLITE_PRIVATE int sqlite3PagerSetJournalMode(Pager *, int); SQLITE_PRIVATE int sqlite3PagerGetJournalMode(Pager*); SQLITE_PRIVATE int sqlite3PagerOkToChangeJournalMode(Pager*); SQLITE_PRIVATE i64 sqlite3PagerJournalSizeLimit(Pager *, i64); SQLITE_PRIVATE sqlite3_backup **sqlite3PagerBackupPtr(Pager*); SQLITE_PRIVATE int sqlite3PagerFlush(Pager*); /* Functions used to obtain and release page references. */ SQLITE_PRIVATE int sqlite3PagerGet(Pager *pPager, Pgno pgno, DbPage **ppPage, int clrFlag); SQLITE_PRIVATE DbPage *sqlite3PagerLookup(Pager *pPager, Pgno pgno); SQLITE_PRIVATE void sqlite3PagerRef(DbPage*); SQLITE_PRIVATE void sqlite3PagerUnref(DbPage*); SQLITE_PRIVATE void sqlite3PagerUnrefNotNull(DbPage*); /* Operations on page references. */ SQLITE_PRIVATE int sqlite3PagerWrite(DbPage*); SQLITE_PRIVATE void sqlite3PagerDontWrite(DbPage*); SQLITE_PRIVATE int sqlite3PagerMovepage(Pager*,DbPage*,Pgno,int); SQLITE_PRIVATE int sqlite3PagerPageRefcount(DbPage*); SQLITE_PRIVATE void *sqlite3PagerGetData(DbPage *); SQLITE_PRIVATE void *sqlite3PagerGetExtra(DbPage *); /* Functions used to manage pager transactions and savepoints. */ SQLITE_PRIVATE void sqlite3PagerPagecount(Pager*, int*); SQLITE_PRIVATE int sqlite3PagerBegin(Pager*, int exFlag, int); SQLITE_PRIVATE int sqlite3PagerCommitPhaseOne(Pager*,const char *zMaster, int); SQLITE_PRIVATE int sqlite3PagerExclusiveLock(Pager*); SQLITE_PRIVATE int sqlite3PagerSync(Pager *pPager, const char *zMaster); SQLITE_PRIVATE int sqlite3PagerCommitPhaseTwo(Pager*); SQLITE_PRIVATE int sqlite3PagerRollback(Pager*); SQLITE_PRIVATE int sqlite3PagerOpenSavepoint(Pager *pPager, int n); SQLITE_PRIVATE int sqlite3PagerSavepoint(Pager *pPager, int op, int iSavepoint); SQLITE_PRIVATE int sqlite3PagerSharedLock(Pager *pPager); #ifndef SQLITE_OMIT_WAL SQLITE_PRIVATE int sqlite3PagerCheckpoint(Pager *pPager, int, int*, int*); SQLITE_PRIVATE int sqlite3PagerWalSupported(Pager *pPager); SQLITE_PRIVATE int sqlite3PagerWalCallback(Pager *pPager); SQLITE_PRIVATE int sqlite3PagerOpenWal(Pager *pPager, int *pisOpen); SQLITE_PRIVATE int sqlite3PagerCloseWal(Pager *pPager); SQLITE_PRIVATE int sqlite3PagerUseWal(Pager *pPager); # ifdef SQLITE_ENABLE_SNAPSHOT SQLITE_PRIVATE int sqlite3PagerSnapshotGet(Pager *pPager, sqlite3_snapshot **ppSnapshot); SQLITE_PRIVATE int sqlite3PagerSnapshotOpen(Pager *pPager, sqlite3_snapshot *pSnapshot); # endif #else # define sqlite3PagerUseWal(x) 0 #endif #ifdef SQLITE_ENABLE_ZIPVFS SQLITE_PRIVATE int sqlite3PagerWalFramesize(Pager *pPager); #endif /* Functions used to query pager state and configuration. */ SQLITE_PRIVATE u8 sqlite3PagerIsreadonly(Pager*); SQLITE_PRIVATE u32 sqlite3PagerDataVersion(Pager*); #ifdef SQLITE_DEBUG SQLITE_PRIVATE int sqlite3PagerRefcount(Pager*); #endif SQLITE_PRIVATE int sqlite3PagerMemUsed(Pager*); SQLITE_PRIVATE const char *sqlite3PagerFilename(Pager*, int); SQLITE_PRIVATE sqlite3_vfs *sqlite3PagerVfs(Pager*); SQLITE_PRIVATE sqlite3_file *sqlite3PagerFile(Pager*); SQLITE_PRIVATE sqlite3_file *sqlite3PagerJrnlFile(Pager*); SQLITE_PRIVATE const char *sqlite3PagerJournalname(Pager*); SQLITE_PRIVATE void *sqlite3PagerTempSpace(Pager*); SQLITE_PRIVATE int sqlite3PagerIsMemdb(Pager*); SQLITE_PRIVATE void sqlite3PagerCacheStat(Pager *, int, int, int *); SQLITE_PRIVATE void sqlite3PagerClearCache(Pager*); SQLITE_PRIVATE int sqlite3SectorSize(sqlite3_file *); /* Functions used to truncate the database file. */ SQLITE_PRIVATE void sqlite3PagerTruncateImage(Pager*,Pgno); SQLITE_PRIVATE void sqlite3PagerRekey(DbPage*, Pgno, u16); #if defined(SQLITE_HAS_CODEC) && !defined(SQLITE_OMIT_WAL) SQLITE_PRIVATE void *sqlite3PagerCodec(DbPage *); #endif /* Functions to support testing and debugging. */ #if !defined(NDEBUG) || defined(SQLITE_TEST) SQLITE_PRIVATE Pgno sqlite3PagerPagenumber(DbPage*); SQLITE_PRIVATE int sqlite3PagerIswriteable(DbPage*); #endif #ifdef SQLITE_TEST SQLITE_PRIVATE int *sqlite3PagerStats(Pager*); SQLITE_PRIVATE void sqlite3PagerRefdump(Pager*); void disable_simulated_io_errors(void); void enable_simulated_io_errors(void); #else # define disable_simulated_io_errors() # define enable_simulated_io_errors() #endif #endif /* SQLITE_PAGER_H */ /************** End of pager.h ***********************************************/ /************** Continuing where we left off in sqliteInt.h ******************/ /************** Include pcache.h in the middle of sqliteInt.h ****************/ /************** Begin file pcache.h ******************************************/ /* ** 2008 August 05 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ************************************************************************* ** This header file defines the interface that the sqlite page cache ** subsystem. */ #ifndef _PCACHE_H_ typedef struct PgHdr PgHdr; typedef struct PCache PCache; /* ** Every page in the cache is controlled by an instance of the following ** structure. */ struct PgHdr { sqlite3_pcache_page *pPage; /* Pcache object page handle */ void *pData; /* Page data */ void *pExtra; /* Extra content */ PgHdr *pDirty; /* Transient list of dirty sorted by pgno */ Pager *pPager; /* The pager this page is part of */ Pgno pgno; /* Page number for this page */ #ifdef SQLITE_CHECK_PAGES u32 pageHash; /* Hash of page content */ #endif u16 flags; /* PGHDR flags defined below */ /********************************************************************** ** Elements above are public. All that follows is private to pcache.c ** and should not be accessed by other modules. */ i16 nRef; /* Number of users of this page */ PCache *pCache; /* Cache that owns this page */ PgHdr *pDirtyNext; /* Next element in list of dirty pages */ PgHdr *pDirtyPrev; /* Previous element in list of dirty pages */ }; /* Bit values for PgHdr.flags */ #define PGHDR_CLEAN 0x001 /* Page not on the PCache.pDirty list */ #define PGHDR_DIRTY 0x002 /* Page is on the PCache.pDirty list */ #define PGHDR_WRITEABLE 0x004 /* Journaled and ready to modify */ #define PGHDR_NEED_SYNC 0x008 /* Fsync the rollback journal before ** writing this page to the database */ #define PGHDR_DONT_WRITE 0x010 /* Do not write content to disk */ #define PGHDR_MMAP 0x020 /* This is an mmap page object */ #define PGHDR_WAL_APPEND 0x040 /* Appended to wal file */ /* Initialize and shutdown the page cache subsystem */ SQLITE_PRIVATE int sqlite3PcacheInitialize(void); SQLITE_PRIVATE void sqlite3PcacheShutdown(void); /* Page cache buffer management: ** These routines implement SQLITE_CONFIG_PAGECACHE. */ SQLITE_PRIVATE void sqlite3PCacheBufferSetup(void *, int sz, int n); /* Create a new pager cache. ** Under memory stress, invoke xStress to try to make pages clean. ** Only clean and unpinned pages can be reclaimed. */ SQLITE_PRIVATE int sqlite3PcacheOpen( int szPage, /* Size of every page */ int szExtra, /* Extra space associated with each page */ int bPurgeable, /* True if pages are on backing store */ int (*xStress)(void*, PgHdr*), /* Call to try to make pages clean */ void *pStress, /* Argument to xStress */ PCache *pToInit /* Preallocated space for the PCache */ ); /* Modify the page-size after the cache has been created. */ SQLITE_PRIVATE int sqlite3PcacheSetPageSize(PCache *, int); /* Return the size in bytes of a PCache object. Used to preallocate ** storage space. */ SQLITE_PRIVATE int sqlite3PcacheSize(void); /* One release per successful fetch. Page is pinned until released. ** Reference counted. */ SQLITE_PRIVATE sqlite3_pcache_page *sqlite3PcacheFetch(PCache*, Pgno, int createFlag); SQLITE_PRIVATE int sqlite3PcacheFetchStress(PCache*, Pgno, sqlite3_pcache_page**); SQLITE_PRIVATE PgHdr *sqlite3PcacheFetchFinish(PCache*, Pgno, sqlite3_pcache_page *pPage); SQLITE_PRIVATE void sqlite3PcacheRelease(PgHdr*); SQLITE_PRIVATE void sqlite3PcacheDrop(PgHdr*); /* Remove page from cache */ SQLITE_PRIVATE void sqlite3PcacheMakeDirty(PgHdr*); /* Make sure page is marked dirty */ SQLITE_PRIVATE void sqlite3PcacheMakeClean(PgHdr*); /* Mark a single page as clean */ SQLITE_PRIVATE void sqlite3PcacheCleanAll(PCache*); /* Mark all dirty list pages as clean */ SQLITE_PRIVATE void sqlite3PcacheClearWritable(PCache*); /* Change a page number. Used by incr-vacuum. */ SQLITE_PRIVATE void sqlite3PcacheMove(PgHdr*, Pgno); /* Remove all pages with pgno>x. Reset the cache if x==0 */ SQLITE_PRIVATE void sqlite3PcacheTruncate(PCache*, Pgno x); /* Get a list of all dirty pages in the cache, sorted by page number */ SQLITE_PRIVATE PgHdr *sqlite3PcacheDirtyList(PCache*); /* Reset and close the cache object */ SQLITE_PRIVATE void sqlite3PcacheClose(PCache*); /* Clear flags from pages of the page cache */ SQLITE_PRIVATE void sqlite3PcacheClearSyncFlags(PCache *); /* Discard the contents of the cache */ SQLITE_PRIVATE void sqlite3PcacheClear(PCache*); /* Return the total number of outstanding page references */ SQLITE_PRIVATE int sqlite3PcacheRefCount(PCache*); /* Increment the reference count of an existing page */ SQLITE_PRIVATE void sqlite3PcacheRef(PgHdr*); SQLITE_PRIVATE int sqlite3PcachePageRefcount(PgHdr*); /* Return the total number of pages stored in the cache */ SQLITE_PRIVATE int sqlite3PcachePagecount(PCache*); #if defined(SQLITE_CHECK_PAGES) || defined(SQLITE_DEBUG) /* Iterate through all dirty pages currently stored in the cache. This ** interface is only available if SQLITE_CHECK_PAGES is defined when the ** library is built. */ SQLITE_PRIVATE void sqlite3PcacheIterateDirty(PCache *pCache, void (*xIter)(PgHdr *)); #endif #if defined(SQLITE_DEBUG) /* Check invariants on a PgHdr object */ SQLITE_PRIVATE int sqlite3PcachePageSanity(PgHdr*); #endif /* Set and get the suggested cache-size for the specified pager-cache. ** ** If no global maximum is configured, then the system attempts to limit ** the total number of pages cached by purgeable pager-caches to the sum ** of the suggested cache-sizes. */ SQLITE_PRIVATE void sqlite3PcacheSetCachesize(PCache *, int); #ifdef SQLITE_TEST SQLITE_PRIVATE int sqlite3PcacheGetCachesize(PCache *); #endif /* Set or get the suggested spill-size for the specified pager-cache. ** ** The spill-size is the minimum number of pages in cache before the cache ** will attempt to spill dirty pages by calling xStress. */ SQLITE_PRIVATE int sqlite3PcacheSetSpillsize(PCache *, int); /* Free up as much memory as possible from the page cache */ SQLITE_PRIVATE void sqlite3PcacheShrink(PCache*); #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT /* Try to return memory used by the pcache module to the main memory heap */ SQLITE_PRIVATE int sqlite3PcacheReleaseMemory(int); #endif #ifdef SQLITE_TEST SQLITE_PRIVATE void sqlite3PcacheStats(int*,int*,int*,int*); #endif SQLITE_PRIVATE void sqlite3PCacheSetDefault(void); /* Return the header size */ SQLITE_PRIVATE int sqlite3HeaderSizePcache(void); SQLITE_PRIVATE int sqlite3HeaderSizePcache1(void); /* Number of dirty pages as a percentage of the configured cache size */ SQLITE_PRIVATE int sqlite3PCachePercentDirty(PCache*); #endif /* _PCACHE_H_ */ /************** End of pcache.h **********************************************/ /************** Continuing where we left off in sqliteInt.h ******************/ /************** Include os.h in the middle of sqliteInt.h ********************/ /************** Begin file os.h **********************************************/ /* ** 2001 September 16 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ****************************************************************************** ** ** This header file (together with is companion C source-code file ** "os.c") attempt to abstract the underlying operating system so that ** the SQLite library will work on both POSIX and windows systems. ** ** This header file is #include-ed by sqliteInt.h and thus ends up ** being included by every source file. */ #ifndef _SQLITE_OS_H_ #define _SQLITE_OS_H_ /* ** Attempt to automatically detect the operating system and setup the ** necessary pre-processor macros for it. */ /************** Include os_setup.h in the middle of os.h *********************/ /************** Begin file os_setup.h ****************************************/ /* ** 2013 November 25 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ****************************************************************************** ** ** This file contains pre-processor directives related to operating system ** detection and/or setup. */ #ifndef SQLITE_OS_SETUP_H #define SQLITE_OS_SETUP_H /* ** Figure out if we are dealing with Unix, Windows, or some other operating ** system. ** ** After the following block of preprocess macros, all of SQLITE_OS_UNIX, ** SQLITE_OS_WIN, and SQLITE_OS_OTHER will defined to either 1 or 0. One of ** the three will be 1. The other two will be 0. */ #if defined(SQLITE_OS_OTHER) # if SQLITE_OS_OTHER==1 # undef SQLITE_OS_UNIX # define SQLITE_OS_UNIX 0 # undef SQLITE_OS_WIN # define SQLITE_OS_WIN 0 # else # undef SQLITE_OS_OTHER # endif #endif #if !defined(SQLITE_OS_UNIX) && !defined(SQLITE_OS_OTHER) # define SQLITE_OS_OTHER 0 # ifndef SQLITE_OS_WIN # if defined(_WIN32) || defined(WIN32) || defined(__CYGWIN__) || \ defined(__MINGW32__) || defined(__BORLANDC__) # define SQLITE_OS_WIN 1 # define SQLITE_OS_UNIX 0 # else # define SQLITE_OS_WIN 0 # define SQLITE_OS_UNIX 1 # endif # else # define SQLITE_OS_UNIX 0 # endif #else # ifndef SQLITE_OS_WIN # define SQLITE_OS_WIN 0 # endif #endif #endif /* SQLITE_OS_SETUP_H */ /************** End of os_setup.h ********************************************/ /************** Continuing where we left off in os.h *************************/ /* If the SET_FULLSYNC macro is not defined above, then make it ** a no-op */ #ifndef SET_FULLSYNC # define SET_FULLSYNC(x,y) #endif /* ** The default size of a disk sector */ #ifndef SQLITE_DEFAULT_SECTOR_SIZE # define SQLITE_DEFAULT_SECTOR_SIZE 4096 #endif /* ** Temporary files are named starting with this prefix followed by 16 random ** alphanumeric characters, and no file extension. They are stored in the ** OS's standard temporary file directory, and are deleted prior to exit. ** If sqlite is being embedded in another program, you may wish to change the ** prefix to reflect your program's name, so that if your program exits ** prematurely, old temporary files can be easily identified. This can be done ** using -DSQLITE_TEMP_FILE_PREFIX=myprefix_ on the compiler command line. ** ** 2006-10-31: The default prefix used to be "sqlite_". But then ** Mcafee started using SQLite in their anti-virus product and it ** started putting files with the "sqlite" name in the c:/temp folder. ** This annoyed many windows users. Those users would then do a ** Google search for "sqlite", find the telephone numbers of the ** developers and call to wake them up at night and complain. ** For this reason, the default name prefix is changed to be "sqlite" ** spelled backwards. So the temp files are still identified, but ** anybody smart enough to figure out the code is also likely smart ** enough to know that calling the developer will not help get rid ** of the file. */ #ifndef SQLITE_TEMP_FILE_PREFIX # define SQLITE_TEMP_FILE_PREFIX "etilqs_" #endif /* ** The following values may be passed as the second argument to ** sqlite3OsLock(). The various locks exhibit the following semantics: ** ** SHARED: Any number of processes may hold a SHARED lock simultaneously. ** RESERVED: A single process may hold a RESERVED lock on a file at ** any time. Other processes may hold and obtain new SHARED locks. ** PENDING: A single process may hold a PENDING lock on a file at ** any one time. Existing SHARED locks may persist, but no new ** SHARED locks may be obtained by other processes. ** EXCLUSIVE: An EXCLUSIVE lock precludes all other locks. ** ** PENDING_LOCK may not be passed directly to sqlite3OsLock(). Instead, a ** process that requests an EXCLUSIVE lock may actually obtain a PENDING ** lock. This can be upgraded to an EXCLUSIVE lock by a subsequent call to ** sqlite3OsLock(). */ #define NO_LOCK 0 #define SHARED_LOCK 1 #define RESERVED_LOCK 2 #define PENDING_LOCK 3 #define EXCLUSIVE_LOCK 4 /* ** File Locking Notes: (Mostly about windows but also some info for Unix) ** ** We cannot use LockFileEx() or UnlockFileEx() on Win95/98/ME because ** those functions are not available. So we use only LockFile() and ** UnlockFile(). ** ** LockFile() prevents not just writing but also reading by other processes. ** A SHARED_LOCK is obtained by locking a single randomly-chosen ** byte out of a specific range of bytes. The lock byte is obtained at ** random so two separate readers can probably access the file at the ** same time, unless they are unlucky and choose the same lock byte. ** An EXCLUSIVE_LOCK is obtained by locking all bytes in the range. ** There can only be one writer. A RESERVED_LOCK is obtained by locking ** a single byte of the file that is designated as the reserved lock byte. ** A PENDING_LOCK is obtained by locking a designated byte different from ** the RESERVED_LOCK byte. ** ** On WinNT/2K/XP systems, LockFileEx() and UnlockFileEx() are available, ** which means we can use reader/writer locks. When reader/writer locks ** are used, the lock is placed on the same range of bytes that is used ** for probabilistic locking in Win95/98/ME. Hence, the locking scheme ** will support two or more Win95 readers or two or more WinNT readers. ** But a single Win95 reader will lock out all WinNT readers and a single ** WinNT reader will lock out all other Win95 readers. ** ** The following #defines specify the range of bytes used for locking. ** SHARED_SIZE is the number of bytes available in the pool from which ** a random byte is selected for a shared lock. The pool of bytes for ** shared locks begins at SHARED_FIRST. ** ** The same locking strategy and ** byte ranges are used for Unix. This leaves open the possibility of having ** clients on win95, winNT, and unix all talking to the same shared file ** and all locking correctly. To do so would require that samba (or whatever ** tool is being used for file sharing) implements locks correctly between ** windows and unix. I'm guessing that isn't likely to happen, but by ** using the same locking range we are at least open to the possibility. ** ** Locking in windows is manditory. For this reason, we cannot store ** actual data in the bytes used for locking. The pager never allocates ** the pages involved in locking therefore. SHARED_SIZE is selected so ** that all locks will fit on a single page even at the minimum page size. ** PENDING_BYTE defines the beginning of the locks. By default PENDING_BYTE ** is set high so that we don't have to allocate an unused page except ** for very large databases. But one should test the page skipping logic ** by setting PENDING_BYTE low and running the entire regression suite. ** ** Changing the value of PENDING_BYTE results in a subtly incompatible ** file format. Depending on how it is changed, you might not notice ** the incompatibility right away, even running a full regression test. ** The default location of PENDING_BYTE is the first byte past the ** 1GB boundary. ** */ #ifdef SQLITE_OMIT_WSD # define PENDING_BYTE (0x40000000) #else # define PENDING_BYTE sqlite3PendingByte #endif #define RESERVED_BYTE (PENDING_BYTE+1) #define SHARED_FIRST (PENDING_BYTE+2) #define SHARED_SIZE 510 /* ** Wrapper around OS specific sqlite3_os_init() function. */ SQLITE_PRIVATE int sqlite3OsInit(void); /* ** Functions for accessing sqlite3_file methods */ SQLITE_PRIVATE void sqlite3OsClose(sqlite3_file*); SQLITE_PRIVATE int sqlite3OsRead(sqlite3_file*, void*, int amt, i64 offset); SQLITE_PRIVATE int sqlite3OsWrite(sqlite3_file*, const void*, int amt, i64 offset); SQLITE_PRIVATE int sqlite3OsTruncate(sqlite3_file*, i64 size); SQLITE_PRIVATE int sqlite3OsSync(sqlite3_file*, int); SQLITE_PRIVATE int sqlite3OsFileSize(sqlite3_file*, i64 *pSize); SQLITE_PRIVATE int sqlite3OsLock(sqlite3_file*, int); SQLITE_PRIVATE int sqlite3OsUnlock(sqlite3_file*, int); SQLITE_PRIVATE int sqlite3OsCheckReservedLock(sqlite3_file *id, int *pResOut); SQLITE_PRIVATE int sqlite3OsFileControl(sqlite3_file*,int,void*); SQLITE_PRIVATE void sqlite3OsFileControlHint(sqlite3_file*,int,void*); #define SQLITE_FCNTL_DB_UNCHANGED 0xca093fa0 SQLITE_PRIVATE int sqlite3OsSectorSize(sqlite3_file *id); SQLITE_PRIVATE int sqlite3OsDeviceCharacteristics(sqlite3_file *id); SQLITE_PRIVATE int sqlite3OsShmMap(sqlite3_file *,int,int,int,void volatile **); SQLITE_PRIVATE int sqlite3OsShmLock(sqlite3_file *id, int, int, int); SQLITE_PRIVATE void sqlite3OsShmBarrier(sqlite3_file *id); SQLITE_PRIVATE int sqlite3OsShmUnmap(sqlite3_file *id, int); SQLITE_PRIVATE int sqlite3OsFetch(sqlite3_file *id, i64, int, void **); SQLITE_PRIVATE int sqlite3OsUnfetch(sqlite3_file *, i64, void *); /* ** Functions for accessing sqlite3_vfs methods */ SQLITE_PRIVATE int sqlite3OsOpen(sqlite3_vfs *, const char *, sqlite3_file*, int, int *); SQLITE_PRIVATE int sqlite3OsDelete(sqlite3_vfs *, const char *, int); SQLITE_PRIVATE int sqlite3OsAccess(sqlite3_vfs *, const char *, int, int *pResOut); SQLITE_PRIVATE int sqlite3OsFullPathname(sqlite3_vfs *, const char *, int, char *); #ifndef SQLITE_OMIT_LOAD_EXTENSION SQLITE_PRIVATE void *sqlite3OsDlOpen(sqlite3_vfs *, const char *); SQLITE_PRIVATE void sqlite3OsDlError(sqlite3_vfs *, int, char *); SQLITE_PRIVATE void (*sqlite3OsDlSym(sqlite3_vfs *, void *, const char *))(void); SQLITE_PRIVATE void sqlite3OsDlClose(sqlite3_vfs *, void *); #endif /* SQLITE_OMIT_LOAD_EXTENSION */ SQLITE_PRIVATE int sqlite3OsRandomness(sqlite3_vfs *, int, char *); SQLITE_PRIVATE int sqlite3OsSleep(sqlite3_vfs *, int); SQLITE_PRIVATE int sqlite3OsGetLastError(sqlite3_vfs*); SQLITE_PRIVATE int sqlite3OsCurrentTimeInt64(sqlite3_vfs *, sqlite3_int64*); /* ** Convenience functions for opening and closing files using ** sqlite3_malloc() to obtain space for the file-handle structure. */ SQLITE_PRIVATE int sqlite3OsOpenMalloc(sqlite3_vfs *, const char *, sqlite3_file **, int,int*); SQLITE_PRIVATE void sqlite3OsCloseFree(sqlite3_file *); #endif /* _SQLITE_OS_H_ */ /************** End of os.h **************************************************/ /************** Continuing where we left off in sqliteInt.h ******************/ /************** Include mutex.h in the middle of sqliteInt.h *****************/ /************** Begin file mutex.h *******************************************/ /* ** 2007 August 28 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ************************************************************************* ** ** This file contains the common header for all mutex implementations. ** The sqliteInt.h header #includes this file so that it is available ** to all source files. We break it out in an effort to keep the code ** better organized. ** ** NOTE: source files should *not* #include this header file directly. ** Source files should #include the sqliteInt.h file and let that file ** include this one indirectly. */ /* ** Figure out what version of the code to use. The choices are ** ** SQLITE_MUTEX_OMIT No mutex logic. Not even stubs. The ** mutexes implementation cannot be overridden ** at start-time. ** ** SQLITE_MUTEX_NOOP For single-threaded applications. No ** mutual exclusion is provided. But this ** implementation can be overridden at ** start-time. ** ** SQLITE_MUTEX_PTHREADS For multi-threaded applications on Unix. ** ** SQLITE_MUTEX_W32 For multi-threaded applications on Win32. */ #if !SQLITE_THREADSAFE # define SQLITE_MUTEX_OMIT #endif #if SQLITE_THREADSAFE && !defined(SQLITE_MUTEX_NOOP) # if SQLITE_OS_UNIX # define SQLITE_MUTEX_PTHREADS # elif SQLITE_OS_WIN # define SQLITE_MUTEX_W32 # else # define SQLITE_MUTEX_NOOP # endif #endif #ifdef SQLITE_MUTEX_OMIT /* ** If this is a no-op implementation, implement everything as macros. */ #define sqlite3_mutex_alloc(X) ((sqlite3_mutex*)8) #define sqlite3_mutex_free(X) #define sqlite3_mutex_enter(X) #define sqlite3_mutex_try(X) SQLITE_OK #define sqlite3_mutex_leave(X) #define sqlite3_mutex_held(X) ((void)(X),1) #define sqlite3_mutex_notheld(X) ((void)(X),1) #define sqlite3MutexAlloc(X) ((sqlite3_mutex*)8) #define sqlite3MutexInit() SQLITE_OK #define sqlite3MutexEnd() #define MUTEX_LOGIC(X) #else #define MUTEX_LOGIC(X) X #endif /* defined(SQLITE_MUTEX_OMIT) */ /************** End of mutex.h ***********************************************/ /************** Continuing where we left off in sqliteInt.h ******************/ /* The SQLITE_EXTRA_DURABLE compile-time option used to set the default ** synchronous setting to EXTRA. It is no longer supported. */ #ifdef SQLITE_EXTRA_DURABLE # warning Use SQLITE_DEFAULT_SYNCHRONOUS=3 instead of SQLITE_EXTRA_DURABLE # define SQLITE_DEFAULT_SYNCHRONOUS 3 #endif /* ** Default synchronous levels. ** ** Note that (for historcal reasons) the PAGER_SYNCHRONOUS_* macros differ ** from the SQLITE_DEFAULT_SYNCHRONOUS value by 1. ** ** PAGER_SYNCHRONOUS DEFAULT_SYNCHRONOUS ** OFF 1 0 ** NORMAL 2 1 ** FULL 3 2 ** EXTRA 4 3 ** ** The "PRAGMA synchronous" statement also uses the zero-based numbers. ** In other words, the zero-based numbers are used for all external interfaces ** and the one-based values are used internally. */ #ifndef SQLITE_DEFAULT_SYNCHRONOUS # define SQLITE_DEFAULT_SYNCHRONOUS (PAGER_SYNCHRONOUS_FULL-1) #endif #ifndef SQLITE_DEFAULT_WAL_SYNCHRONOUS # define SQLITE_DEFAULT_WAL_SYNCHRONOUS SQLITE_DEFAULT_SYNCHRONOUS #endif /* ** Each database file to be accessed by the system is an instance ** of the following structure. There are normally two of these structures ** in the sqlite.aDb[] array. aDb[0] is the main database file and ** aDb[1] is the database file used to hold temporary tables. Additional ** databases may be attached. */ struct Db { char *zDbSName; /* Name of this database. (schema name, not filename) */ Btree *pBt; /* The B*Tree structure for this database file */ u8 safety_level; /* How aggressive at syncing data to disk */ u8 bSyncSet; /* True if "PRAGMA synchronous=N" has been run */ Schema *pSchema; /* Pointer to database schema (possibly shared) */ }; /* ** An instance of the following structure stores a database schema. ** ** Most Schema objects are associated with a Btree. The exception is ** the Schema for the TEMP databaes (sqlite3.aDb[1]) which is free-standing. ** In shared cache mode, a single Schema object can be shared by multiple ** Btrees that refer to the same underlying BtShared object. ** ** Schema objects are automatically deallocated when the last Btree that ** references them is destroyed. The TEMP Schema is manually freed by ** sqlite3_close(). * ** A thread must be holding a mutex on the corresponding Btree in order ** to access Schema content. This implies that the thread must also be ** holding a mutex on the sqlite3 connection pointer that owns the Btree. ** For a TEMP Schema, only the connection mutex is required. */ struct Schema { int schema_cookie; /* Database schema version number for this file */ int iGeneration; /* Generation counter. Incremented with each change */ Hash tblHash; /* All tables indexed by name */ Hash idxHash; /* All (named) indices indexed by name */ Hash trigHash; /* All triggers indexed by name */ Hash fkeyHash; /* All foreign keys by referenced table name */ Table *pSeqTab; /* The sqlite_sequence table used by AUTOINCREMENT */ u8 file_format; /* Schema format version for this file */ u8 enc; /* Text encoding used by this database */ u16 schemaFlags; /* Flags associated with this schema */ int cache_size; /* Number of pages to use in the cache */ }; /* ** These macros can be used to test, set, or clear bits in the ** Db.pSchema->flags field. */ #define DbHasProperty(D,I,P) (((D)->aDb[I].pSchema->schemaFlags&(P))==(P)) #define DbHasAnyProperty(D,I,P) (((D)->aDb[I].pSchema->schemaFlags&(P))!=0) #define DbSetProperty(D,I,P) (D)->aDb[I].pSchema->schemaFlags|=(P) #define DbClearProperty(D,I,P) (D)->aDb[I].pSchema->schemaFlags&=~(P) /* ** Allowed values for the DB.pSchema->flags field. ** ** The DB_SchemaLoaded flag is set after the database schema has been ** read into internal hash tables. ** ** DB_UnresetViews means that one or more views have column names that ** have been filled out. If the schema changes, these column names might ** changes and so the view will need to be reset. */ #define DB_SchemaLoaded 0x0001 /* The schema has been loaded */ #define DB_UnresetViews 0x0002 /* Some views have defined column names */ #define DB_Empty 0x0004 /* The file is empty (length 0 bytes) */ /* ** The number of different kinds of things that can be limited ** using the sqlite3_limit() interface. */ #define SQLITE_N_LIMIT (SQLITE_LIMIT_WORKER_THREADS+1) /* ** Lookaside malloc is a set of fixed-size buffers that can be used ** to satisfy small transient memory allocation requests for objects ** associated with a particular database connection. The use of ** lookaside malloc provides a significant performance enhancement ** (approx 10%) by avoiding numerous malloc/free requests while parsing ** SQL statements. ** ** The Lookaside structure holds configuration information about the ** lookaside malloc subsystem. Each available memory allocation in ** the lookaside subsystem is stored on a linked list of LookasideSlot ** objects. ** ** Lookaside allocations are only allowed for objects that are associated ** with a particular database connection. Hence, schema information cannot ** be stored in lookaside because in shared cache mode the schema information ** is shared by multiple database connections. Therefore, while parsing ** schema information, the Lookaside.bEnabled flag is cleared so that ** lookaside allocations are not used to construct the schema objects. */ struct Lookaside { u32 bDisable; /* Only operate the lookaside when zero */ u16 sz; /* Size of each buffer in bytes */ u8 bMalloced; /* True if pStart obtained from sqlite3_malloc() */ int nOut; /* Number of buffers currently checked out */ int mxOut; /* Highwater mark for nOut */ int anStat[3]; /* 0: hits. 1: size misses. 2: full misses */ LookasideSlot *pFree; /* List of available buffers */ void *pStart; /* First byte of available memory space */ void *pEnd; /* First byte past end of available space */ }; struct LookasideSlot { LookasideSlot *pNext; /* Next buffer in the list of free buffers */ }; /* ** A hash table for built-in function definitions. (Application-defined ** functions use a regular table table from hash.h.) ** ** Hash each FuncDef structure into one of the FuncDefHash.a[] slots. ** Collisions are on the FuncDef.u.pHash chain. */ #define SQLITE_FUNC_HASH_SZ 23 struct FuncDefHash { FuncDef *a[SQLITE_FUNC_HASH_SZ]; /* Hash table for functions */ }; #ifdef SQLITE_USER_AUTHENTICATION /* ** Information held in the "sqlite3" database connection object and used ** to manage user authentication. */ typedef struct sqlite3_userauth sqlite3_userauth; struct sqlite3_userauth { u8 authLevel; /* Current authentication level */ int nAuthPW; /* Size of the zAuthPW in bytes */ char *zAuthPW; /* Password used to authenticate */ char *zAuthUser; /* User name used to authenticate */ }; /* Allowed values for sqlite3_userauth.authLevel */ #define UAUTH_Unknown 0 /* Authentication not yet checked */ #define UAUTH_Fail 1 /* User authentication failed */ #define UAUTH_User 2 /* Authenticated as a normal user */ #define UAUTH_Admin 3 /* Authenticated as an administrator */ /* Functions used only by user authorization logic */ SQLITE_PRIVATE int sqlite3UserAuthTable(const char*); SQLITE_PRIVATE int sqlite3UserAuthCheckLogin(sqlite3*,const char*,u8*); SQLITE_PRIVATE void sqlite3UserAuthInit(sqlite3*); SQLITE_PRIVATE void sqlite3CryptFunc(sqlite3_context*,int,sqlite3_value**); #endif /* SQLITE_USER_AUTHENTICATION */ /* ** typedef for the authorization callback function. */ #ifdef SQLITE_USER_AUTHENTICATION typedef int (*sqlite3_xauth)(void*,int,const char*,const char*,const char*, const char*, const char*); #else typedef int (*sqlite3_xauth)(void*,int,const char*,const char*,const char*, const char*); #endif #ifndef SQLITE_OMIT_DEPRECATED /* This is an extra SQLITE_TRACE macro that indicates "legacy" tracing ** in the style of sqlite3_trace() */ #define SQLITE_TRACE_LEGACY 0x80 #else #define SQLITE_TRACE_LEGACY 0 #endif /* SQLITE_OMIT_DEPRECATED */ /* ** Each database connection is an instance of the following structure. */ struct sqlite3 { sqlite3_vfs *pVfs; /* OS Interface */ struct Vdbe *pVdbe; /* List of active virtual machines */ CollSeq *pDfltColl; /* The default collating sequence (BINARY) */ sqlite3_mutex *mutex; /* Connection mutex */ Db *aDb; /* All backends */ int nDb; /* Number of backends currently in use */ int flags; /* Miscellaneous flags. See below */ i64 lastRowid; /* ROWID of most recent insert (see above) */ i64 szMmap; /* Default mmap_size setting */ unsigned int openFlags; /* Flags passed to sqlite3_vfs.xOpen() */ int errCode; /* Most recent error code (SQLITE_*) */ int errMask; /* & result codes with this before returning */ int iSysErrno; /* Errno value from last system error */ u16 dbOptFlags; /* Flags to enable/disable optimizations */ u8 enc; /* Text encoding */ u8 autoCommit; /* The auto-commit flag. */ u8 temp_store; /* 1: file 2: memory 0: default */ u8 mallocFailed; /* True if we have seen a malloc failure */ u8 bBenignMalloc; /* Do not require OOMs if true */ u8 dfltLockMode; /* Default locking-mode for attached dbs */ signed char nextAutovac; /* Autovac setting after VACUUM if >=0 */ u8 suppressErr; /* Do not issue error messages if true */ u8 vtabOnConflict; /* Value to return for s3_vtab_on_conflict() */ u8 isTransactionSavepoint; /* True if the outermost savepoint is a TS */ u8 mTrace; /* zero or more SQLITE_TRACE flags */ int nextPagesize; /* Pagesize after VACUUM if >0 */ u32 magic; /* Magic number for detect library misuse */ int nChange; /* Value returned by sqlite3_changes() */ int nTotalChange; /* Value returned by sqlite3_total_changes() */ int aLimit[SQLITE_N_LIMIT]; /* Limits */ int nMaxSorterMmap; /* Maximum size of regions mapped by sorter */ struct sqlite3InitInfo { /* Information used during initialization */ int newTnum; /* Rootpage of table being initialized */ u8 iDb; /* Which db file is being initialized */ u8 busy; /* TRUE if currently initializing */ u8 orphanTrigger; /* Last statement is orphaned TEMP trigger */ u8 imposterTable; /* Building an imposter table */ } init; int nVdbeActive; /* Number of VDBEs currently running */ int nVdbeRead; /* Number of active VDBEs that read or write */ int nVdbeWrite; /* Number of active VDBEs that read and write */ int nVdbeExec; /* Number of nested calls to VdbeExec() */ int nVDestroy; /* Number of active OP_VDestroy operations */ int nExtension; /* Number of loaded extensions */ void **aExtension; /* Array of shared library handles */ int (*xTrace)(u32,void*,void*,void*); /* Trace function */ void *pTraceArg; /* Argument to the trace function */ void (*xProfile)(void*,const char*,u64); /* Profiling function */ void *pProfileArg; /* Argument to profile function */ void *pCommitArg; /* Argument to xCommitCallback() */ int (*xCommitCallback)(void*); /* Invoked at every commit. */ void *pRollbackArg; /* Argument to xRollbackCallback() */ void (*xRollbackCallback)(void*); /* Invoked at every commit. */ void *pUpdateArg; void (*xUpdateCallback)(void*,int, const char*,const char*,sqlite_int64); #ifdef SQLITE_ENABLE_PREUPDATE_HOOK void *pPreUpdateArg; /* First argument to xPreUpdateCallback */ void (*xPreUpdateCallback)( /* Registered using sqlite3_preupdate_hook() */ void*,sqlite3*,int,char const*,char const*,sqlite3_int64,sqlite3_int64 ); PreUpdate *pPreUpdate; /* Context for active pre-update callback */ #endif /* SQLITE_ENABLE_PREUPDATE_HOOK */ #ifndef SQLITE_OMIT_WAL int (*xWalCallback)(void *, sqlite3 *, const char *, int); void *pWalArg; #endif void(*xCollNeeded)(void*,sqlite3*,int eTextRep,const char*); void(*xCollNeeded16)(void*,sqlite3*,int eTextRep,const void*); void *pCollNeededArg; sqlite3_value *pErr; /* Most recent error message */ union { volatile int isInterrupted; /* True if sqlite3_interrupt has been called */ double notUsed1; /* Spacer */ } u1; Lookaside lookaside; /* Lookaside malloc configuration */ #ifndef SQLITE_OMIT_AUTHORIZATION sqlite3_xauth xAuth; /* Access authorization function */ void *pAuthArg; /* 1st argument to the access auth function */ #endif #ifndef SQLITE_OMIT_PROGRESS_CALLBACK int (*xProgress)(void *); /* The progress callback */ void *pProgressArg; /* Argument to the progress callback */ unsigned nProgressOps; /* Number of opcodes for progress callback */ #endif #ifndef SQLITE_OMIT_VIRTUALTABLE int nVTrans; /* Allocated size of aVTrans */ Hash aModule; /* populated by sqlite3_create_module() */ VtabCtx *pVtabCtx; /* Context for active vtab connect/create */ VTable **aVTrans; /* Virtual tables with open transactions */ VTable *pDisconnect; /* Disconnect these in next sqlite3_prepare() */ #endif Hash aFunc; /* Hash table of connection functions */ Hash aCollSeq; /* All collating sequences */ BusyHandler busyHandler; /* Busy callback */ Db aDbStatic[2]; /* Static space for the 2 default backends */ Savepoint *pSavepoint; /* List of active savepoints */ int busyTimeout; /* Busy handler timeout, in msec */ int nSavepoint; /* Number of non-transaction savepoints */ int nStatement; /* Number of nested statement-transactions */ i64 nDeferredCons; /* Net deferred constraints this transaction. */ i64 nDeferredImmCons; /* Net deferred immediate constraints */ int *pnBytesFreed; /* If not NULL, increment this in DbFree() */ #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY /* The following variables are all protected by the STATIC_MASTER ** mutex, not by sqlite3.mutex. They are used by code in notify.c. ** ** When X.pUnlockConnection==Y, that means that X is waiting for Y to ** unlock so that it can proceed. ** ** When X.pBlockingConnection==Y, that means that something that X tried ** tried to do recently failed with an SQLITE_LOCKED error due to locks ** held by Y. */ sqlite3 *pBlockingConnection; /* Connection that caused SQLITE_LOCKED */ sqlite3 *pUnlockConnection; /* Connection to watch for unlock */ void *pUnlockArg; /* Argument to xUnlockNotify */ void (*xUnlockNotify)(void **, int); /* Unlock notify callback */ sqlite3 *pNextBlocked; /* Next in list of all blocked connections */ #endif #ifdef SQLITE_USER_AUTHENTICATION sqlite3_userauth auth; /* User authentication information */ #endif }; /* ** A macro to discover the encoding of a database. */ #define SCHEMA_ENC(db) ((db)->aDb[0].pSchema->enc) #define ENC(db) ((db)->enc) /* ** Possible values for the sqlite3.flags. ** ** Value constraints (enforced via assert()): ** SQLITE_FullFSync == PAGER_FULLFSYNC ** SQLITE_CkptFullFSync == PAGER_CKPT_FULLFSYNC ** SQLITE_CacheSpill == PAGER_CACHE_SPILL */ #define SQLITE_VdbeTrace 0x00000001 /* True to trace VDBE execution */ #define SQLITE_InternChanges 0x00000002 /* Uncommitted Hash table changes */ #define SQLITE_FullColNames 0x00000004 /* Show full column names on SELECT */ #define SQLITE_FullFSync 0x00000008 /* Use full fsync on the backend */ #define SQLITE_CkptFullFSync 0x00000010 /* Use full fsync for checkpoint */ #define SQLITE_CacheSpill 0x00000020 /* OK to spill pager cache */ #define SQLITE_ShortColNames 0x00000040 /* Show short columns names */ #define SQLITE_CountRows 0x00000080 /* Count rows changed by INSERT, */ /* DELETE, or UPDATE and return */ /* the count using a callback. */ #define SQLITE_NullCallback 0x00000100 /* Invoke the callback once if the */ /* result set is empty */ #define SQLITE_SqlTrace 0x00000200 /* Debug print SQL as it executes */ #define SQLITE_VdbeListing 0x00000400 /* Debug listings of VDBE programs */ #define SQLITE_WriteSchema 0x00000800 /* OK to update SQLITE_MASTER */ #define SQLITE_VdbeAddopTrace 0x00001000 /* Trace sqlite3VdbeAddOp() calls */ #define SQLITE_IgnoreChecks 0x00002000 /* Do not enforce check constraints */ #define SQLITE_ReadUncommitted 0x0004000 /* For shared-cache mode */ #define SQLITE_LegacyFileFmt 0x00008000 /* Create new databases in format 1 */ #define SQLITE_RecoveryMode 0x00010000 /* Ignore schema errors */ #define SQLITE_ReverseOrder 0x00020000 /* Reverse unordered SELECTs */ #define SQLITE_RecTriggers 0x00040000 /* Enable recursive triggers */ #define SQLITE_ForeignKeys 0x00080000 /* Enforce foreign key constraints */ #define SQLITE_AutoIndex 0x00100000 /* Enable automatic indexes */ #define SQLITE_PreferBuiltin 0x00200000 /* Preference to built-in funcs */ #define SQLITE_LoadExtension 0x00400000 /* Enable load_extension */ #define SQLITE_LoadExtFunc 0x00800000 /* Enable load_extension() SQL func */ #define SQLITE_EnableTrigger 0x01000000 /* True to enable triggers */ #define SQLITE_DeferFKs 0x02000000 /* Defer all FK constraints */ #define SQLITE_QueryOnly 0x04000000 /* Disable database changes */ #define SQLITE_VdbeEQP 0x08000000 /* Debug EXPLAIN QUERY PLAN */ #define SQLITE_Vacuum 0x10000000 /* Currently in a VACUUM */ #define SQLITE_CellSizeCk 0x20000000 /* Check btree cell sizes on load */ #define SQLITE_Fts3Tokenizer 0x40000000 /* Enable fts3_tokenizer(2) */ /* ** Bits of the sqlite3.dbOptFlags field that are used by the ** sqlite3_test_control(SQLITE_TESTCTRL_OPTIMIZATIONS,...) interface to ** selectively disable various optimizations. */ #define SQLITE_QueryFlattener 0x0001 /* Query flattening */ #define SQLITE_ColumnCache 0x0002 /* Column cache */ #define SQLITE_GroupByOrder 0x0004 /* GROUPBY cover of ORDERBY */ #define SQLITE_FactorOutConst 0x0008 /* Constant factoring */ /* not used 0x0010 // Was: SQLITE_IdxRealAsInt */ #define SQLITE_DistinctOpt 0x0020 /* DISTINCT using indexes */ #define SQLITE_CoverIdxScan 0x0040 /* Covering index scans */ #define SQLITE_OrderByIdxJoin 0x0080 /* ORDER BY of joins via index */ #define SQLITE_SubqCoroutine 0x0100 /* Evaluate subqueries as coroutines */ #define SQLITE_Transitive 0x0200 /* Transitive constraints */ #define SQLITE_OmitNoopJoin 0x0400 /* Omit unused tables in joins */ #define SQLITE_Stat34 0x0800 /* Use STAT3 or STAT4 data */ #define SQLITE_CursorHints 0x2000 /* Add OP_CursorHint opcodes */ #define SQLITE_AllOpts 0xffff /* All optimizations */ /* ** Macros for testing whether or not optimizations are enabled or disabled. */ #ifndef SQLITE_OMIT_BUILTIN_TEST #define OptimizationDisabled(db, mask) (((db)->dbOptFlags&(mask))!=0) #define OptimizationEnabled(db, mask) (((db)->dbOptFlags&(mask))==0) #else #define OptimizationDisabled(db, mask) 0 #define OptimizationEnabled(db, mask) 1 #endif /* ** Return true if it OK to factor constant expressions into the initialization ** code. The argument is a Parse object for the code generator. */ #define ConstFactorOk(P) ((P)->okConstFactor) /* ** Possible values for the sqlite.magic field. ** The numbers are obtained at random and have no special meaning, other ** than being distinct from one another. */ #define SQLITE_MAGIC_OPEN 0xa029a697 /* Database is open */ #define SQLITE_MAGIC_CLOSED 0x9f3c2d33 /* Database is closed */ #define SQLITE_MAGIC_SICK 0x4b771290 /* Error and awaiting close */ #define SQLITE_MAGIC_BUSY 0xf03b7906 /* Database currently in use */ #define SQLITE_MAGIC_ERROR 0xb5357930 /* An SQLITE_MISUSE error occurred */ #define SQLITE_MAGIC_ZOMBIE 0x64cffc7f /* Close with last statement close */ /* ** Each SQL function is defined by an instance of the following ** structure. For global built-in functions (ex: substr(), max(), count()) ** a pointer to this structure is held in the sqlite3BuiltinFunctions object. ** For per-connection application-defined functions, a pointer to this ** structure is held in the db->aHash hash table. ** ** The u.pHash field is used by the global built-ins. The u.pDestructor ** field is used by per-connection app-def functions. */ struct FuncDef { i8 nArg; /* Number of arguments. -1 means unlimited */ u16 funcFlags; /* Some combination of SQLITE_FUNC_* */ void *pUserData; /* User data parameter */ FuncDef *pNext; /* Next function with same name */ void (*xSFunc)(sqlite3_context*,int,sqlite3_value**); /* func or agg-step */ void (*xFinalize)(sqlite3_context*); /* Agg finalizer */ const char *zName; /* SQL name of the function. */ union { FuncDef *pHash; /* Next with a different name but the same hash */ FuncDestructor *pDestructor; /* Reference counted destructor function */ } u; }; /* ** This structure encapsulates a user-function destructor callback (as ** configured using create_function_v2()) and a reference counter. When ** create_function_v2() is called to create a function with a destructor, ** a single object of this type is allocated. FuncDestructor.nRef is set to ** the number of FuncDef objects created (either 1 or 3, depending on whether ** or not the specified encoding is SQLITE_ANY). The FuncDef.pDestructor ** member of each of the new FuncDef objects is set to point to the allocated ** FuncDestructor. ** ** Thereafter, when one of the FuncDef objects is deleted, the reference ** count on this object is decremented. When it reaches 0, the destructor ** is invoked and the FuncDestructor structure freed. */ struct FuncDestructor { int nRef; void (*xDestroy)(void *); void *pUserData; }; /* ** Possible values for FuncDef.flags. Note that the _LENGTH and _TYPEOF ** values must correspond to OPFLAG_LENGTHARG and OPFLAG_TYPEOFARG. And ** SQLITE_FUNC_CONSTANT must be the same as SQLITE_DETERMINISTIC. There ** are assert() statements in the code to verify this. ** ** Value constraints (enforced via assert()): ** SQLITE_FUNC_MINMAX == NC_MinMaxAgg == SF_MinMaxAgg ** SQLITE_FUNC_LENGTH == OPFLAG_LENGTHARG ** SQLITE_FUNC_TYPEOF == OPFLAG_TYPEOFARG ** SQLITE_FUNC_CONSTANT == SQLITE_DETERMINISTIC from the API ** SQLITE_FUNC_ENCMASK depends on SQLITE_UTF* macros in the API */ #define SQLITE_FUNC_ENCMASK 0x0003 /* SQLITE_UTF8, SQLITE_UTF16BE or UTF16LE */ #define SQLITE_FUNC_LIKE 0x0004 /* Candidate for the LIKE optimization */ #define SQLITE_FUNC_CASE 0x0008 /* Case-sensitive LIKE-type function */ #define SQLITE_FUNC_EPHEM 0x0010 /* Ephemeral. Delete with VDBE */ #define SQLITE_FUNC_NEEDCOLL 0x0020 /* sqlite3GetFuncCollSeq() might be called*/ #define SQLITE_FUNC_LENGTH 0x0040 /* Built-in length() function */ #define SQLITE_FUNC_TYPEOF 0x0080 /* Built-in typeof() function */ #define SQLITE_FUNC_COUNT 0x0100 /* Built-in count(*) aggregate */ #define SQLITE_FUNC_COALESCE 0x0200 /* Built-in coalesce() or ifnull() */ #define SQLITE_FUNC_UNLIKELY 0x0400 /* Built-in unlikely() function */ #define SQLITE_FUNC_CONSTANT 0x0800 /* Constant inputs give a constant output */ #define SQLITE_FUNC_MINMAX 0x1000 /* True for min() and max() aggregates */ #define SQLITE_FUNC_SLOCHNG 0x2000 /* "Slow Change". Value constant during a ** single query - might change over time */ /* ** The following three macros, FUNCTION(), LIKEFUNC() and AGGREGATE() are ** used to create the initializers for the FuncDef structures. ** ** FUNCTION(zName, nArg, iArg, bNC, xFunc) ** Used to create a scalar function definition of a function zName ** implemented by C function xFunc that accepts nArg arguments. The ** value passed as iArg is cast to a (void*) and made available ** as the user-data (sqlite3_user_data()) for the function. If ** argument bNC is true, then the SQLITE_FUNC_NEEDCOLL flag is set. ** ** VFUNCTION(zName, nArg, iArg, bNC, xFunc) ** Like FUNCTION except it omits the SQLITE_FUNC_CONSTANT flag. ** ** DFUNCTION(zName, nArg, iArg, bNC, xFunc) ** Like FUNCTION except it omits the SQLITE_FUNC_CONSTANT flag and ** adds the SQLITE_FUNC_SLOCHNG flag. Used for date & time functions ** and functions like sqlite_version() that can change, but not during ** a single query. ** ** AGGREGATE(zName, nArg, iArg, bNC, xStep, xFinal) ** Used to create an aggregate function definition implemented by ** the C functions xStep and xFinal. The first four parameters ** are interpreted in the same way as the first 4 parameters to ** FUNCTION(). ** ** LIKEFUNC(zName, nArg, pArg, flags) ** Used to create a scalar function definition of a function zName ** that accepts nArg arguments and is implemented by a call to C ** function likeFunc. Argument pArg is cast to a (void *) and made ** available as the function user-data (sqlite3_user_data()). The ** FuncDef.flags variable is set to the value passed as the flags ** parameter. */ #define FUNCTION(zName, nArg, iArg, bNC, xFunc) \ {nArg, SQLITE_FUNC_CONSTANT|SQLITE_UTF8|(bNC*SQLITE_FUNC_NEEDCOLL), \ SQLITE_INT_TO_PTR(iArg), 0, xFunc, 0, #zName, {0} } #define VFUNCTION(zName, nArg, iArg, bNC, xFunc) \ {nArg, SQLITE_UTF8|(bNC*SQLITE_FUNC_NEEDCOLL), \ SQLITE_INT_TO_PTR(iArg), 0, xFunc, 0, #zName, {0} } #define DFUNCTION(zName, nArg, iArg, bNC, xFunc) \ {nArg, SQLITE_FUNC_SLOCHNG|SQLITE_UTF8|(bNC*SQLITE_FUNC_NEEDCOLL), \ SQLITE_INT_TO_PTR(iArg), 0, xFunc, 0, #zName, {0} } #define FUNCTION2(zName, nArg, iArg, bNC, xFunc, extraFlags) \ {nArg,SQLITE_FUNC_CONSTANT|SQLITE_UTF8|(bNC*SQLITE_FUNC_NEEDCOLL)|extraFlags,\ SQLITE_INT_TO_PTR(iArg), 0, xFunc, 0, #zName, {0} } #define STR_FUNCTION(zName, nArg, pArg, bNC, xFunc) \ {nArg, SQLITE_FUNC_SLOCHNG|SQLITE_UTF8|(bNC*SQLITE_FUNC_NEEDCOLL), \ pArg, 0, xFunc, 0, #zName, } #define LIKEFUNC(zName, nArg, arg, flags) \ {nArg, SQLITE_FUNC_CONSTANT|SQLITE_UTF8|flags, \ (void *)arg, 0, likeFunc, 0, #zName, {0} } #define AGGREGATE(zName, nArg, arg, nc, xStep, xFinal) \ {nArg, SQLITE_UTF8|(nc*SQLITE_FUNC_NEEDCOLL), \ SQLITE_INT_TO_PTR(arg), 0, xStep,xFinal,#zName, {0}} #define AGGREGATE2(zName, nArg, arg, nc, xStep, xFinal, extraFlags) \ {nArg, SQLITE_UTF8|(nc*SQLITE_FUNC_NEEDCOLL)|extraFlags, \ SQLITE_INT_TO_PTR(arg), 0, xStep,xFinal,#zName, {0}} /* ** All current savepoints are stored in a linked list starting at ** sqlite3.pSavepoint. The first element in the list is the most recently ** opened savepoint. Savepoints are added to the list by the vdbe ** OP_Savepoint instruction. */ struct Savepoint { char *zName; /* Savepoint name (nul-terminated) */ i64 nDeferredCons; /* Number of deferred fk violations */ i64 nDeferredImmCons; /* Number of deferred imm fk. */ Savepoint *pNext; /* Parent savepoint (if any) */ }; /* ** The following are used as the second parameter to sqlite3Savepoint(), ** and as the P1 argument to the OP_Savepoint instruction. */ #define SAVEPOINT_BEGIN 0 #define SAVEPOINT_RELEASE 1 #define SAVEPOINT_ROLLBACK 2 /* ** Each SQLite module (virtual table definition) is defined by an ** instance of the following structure, stored in the sqlite3.aModule ** hash table. */ struct Module { const sqlite3_module *pModule; /* Callback pointers */ const char *zName; /* Name passed to create_module() */ void *pAux; /* pAux passed to create_module() */ void (*xDestroy)(void *); /* Module destructor function */ Table *pEpoTab; /* Eponymous table for this module */ }; /* ** information about each column of an SQL table is held in an instance ** of this structure. */ struct Column { char *zName; /* Name of this column, \000, then the type */ Expr *pDflt; /* Default value of this column */ char *zColl; /* Collating sequence. If NULL, use the default */ u8 notNull; /* An OE_ code for handling a NOT NULL constraint */ char affinity; /* One of the SQLITE_AFF_... values */ u8 szEst; /* Estimated size of value in this column. sizeof(INT)==1 */ u8 colFlags; /* Boolean properties. See COLFLAG_ defines below */ }; /* Allowed values for Column.colFlags: */ #define COLFLAG_PRIMKEY 0x0001 /* Column is part of the primary key */ #define COLFLAG_HIDDEN 0x0002 /* A hidden column in a virtual table */ #define COLFLAG_HASTYPE 0x0004 /* Type name follows column name */ /* ** A "Collating Sequence" is defined by an instance of the following ** structure. Conceptually, a collating sequence consists of a name and ** a comparison routine that defines the order of that sequence. ** ** If CollSeq.xCmp is NULL, it means that the ** collating sequence is undefined. Indices built on an undefined ** collating sequence may not be read or written. */ struct CollSeq { char *zName; /* Name of the collating sequence, UTF-8 encoded */ u8 enc; /* Text encoding handled by xCmp() */ void *pUser; /* First argument to xCmp() */ int (*xCmp)(void*,int, const void*, int, const void*); void (*xDel)(void*); /* Destructor for pUser */ }; /* ** A sort order can be either ASC or DESC. */ #define SQLITE_SO_ASC 0 /* Sort in ascending order */ #define SQLITE_SO_DESC 1 /* Sort in ascending order */ #define SQLITE_SO_UNDEFINED -1 /* No sort order specified */ /* ** Column affinity types. ** ** These used to have mnemonic name like 'i' for SQLITE_AFF_INTEGER and ** 't' for SQLITE_AFF_TEXT. But we can save a little space and improve ** the speed a little by numbering the values consecutively. ** ** But rather than start with 0 or 1, we begin with 'A'. That way, ** when multiple affinity types are concatenated into a string and ** used as the P4 operand, they will be more readable. ** ** Note also that the numeric types are grouped together so that testing ** for a numeric type is a single comparison. And the BLOB type is first. */ #define SQLITE_AFF_BLOB 'A' #define SQLITE_AFF_TEXT 'B' #define SQLITE_AFF_NUMERIC 'C' #define SQLITE_AFF_INTEGER 'D' #define SQLITE_AFF_REAL 'E' #define sqlite3IsNumericAffinity(X) ((X)>=SQLITE_AFF_NUMERIC) /* ** The SQLITE_AFF_MASK values masks off the significant bits of an ** affinity value. */ #define SQLITE_AFF_MASK 0x47 /* ** Additional bit values that can be ORed with an affinity without ** changing the affinity. ** ** The SQLITE_NOTNULL flag is a combination of NULLEQ and JUMPIFNULL. ** It causes an assert() to fire if either operand to a comparison ** operator is NULL. It is added to certain comparison operators to ** prove that the operands are always NOT NULL. */ #define SQLITE_KEEPNULL 0x08 /* Used by vector == or <> */ #define SQLITE_JUMPIFNULL 0x10 /* jumps if either operand is NULL */ #define SQLITE_STOREP2 0x20 /* Store result in reg[P2] rather than jump */ #define SQLITE_NULLEQ 0x80 /* NULL=NULL */ #define SQLITE_NOTNULL 0x90 /* Assert that operands are never NULL */ /* ** An object of this type is created for each virtual table present in ** the database schema. ** ** If the database schema is shared, then there is one instance of this ** structure for each database connection (sqlite3*) that uses the shared ** schema. This is because each database connection requires its own unique ** instance of the sqlite3_vtab* handle used to access the virtual table ** implementation. sqlite3_vtab* handles can not be shared between ** database connections, even when the rest of the in-memory database ** schema is shared, as the implementation often stores the database ** connection handle passed to it via the xConnect() or xCreate() method ** during initialization internally. This database connection handle may ** then be used by the virtual table implementation to access real tables ** within the database. So that they appear as part of the callers ** transaction, these accesses need to be made via the same database ** connection as that used to execute SQL operations on the virtual table. ** ** All VTable objects that correspond to a single table in a shared ** database schema are initially stored in a linked-list pointed to by ** the Table.pVTable member variable of the corresponding Table object. ** When an sqlite3_prepare() operation is required to access the virtual ** table, it searches the list for the VTable that corresponds to the ** database connection doing the preparing so as to use the correct ** sqlite3_vtab* handle in the compiled query. ** ** When an in-memory Table object is deleted (for example when the ** schema is being reloaded for some reason), the VTable objects are not ** deleted and the sqlite3_vtab* handles are not xDisconnect()ed ** immediately. Instead, they are moved from the Table.pVTable list to ** another linked list headed by the sqlite3.pDisconnect member of the ** corresponding sqlite3 structure. They are then deleted/xDisconnected ** next time a statement is prepared using said sqlite3*. This is done ** to avoid deadlock issues involving multiple sqlite3.mutex mutexes. ** Refer to comments above function sqlite3VtabUnlockList() for an ** explanation as to why it is safe to add an entry to an sqlite3.pDisconnect ** list without holding the corresponding sqlite3.mutex mutex. ** ** The memory for objects of this type is always allocated by ** sqlite3DbMalloc(), using the connection handle stored in VTable.db as ** the first argument. */ struct VTable { sqlite3 *db; /* Database connection associated with this table */ Module *pMod; /* Pointer to module implementation */ sqlite3_vtab *pVtab; /* Pointer to vtab instance */ int nRef; /* Number of pointers to this structure */ u8 bConstraint; /* True if constraints are supported */ int iSavepoint; /* Depth of the SAVEPOINT stack */ VTable *pNext; /* Next in linked list (see above) */ }; /* ** The schema for each SQL table and view is represented in memory ** by an instance of the following structure. */ struct Table { char *zName; /* Name of the table or view */ Column *aCol; /* Information about each column */ Index *pIndex; /* List of SQL indexes on this table. */ Select *pSelect; /* NULL for tables. Points to definition if a view. */ FKey *pFKey; /* Linked list of all foreign keys in this table */ char *zColAff; /* String defining the affinity of each column */ ExprList *pCheck; /* All CHECK constraints */ /* ... also used as column name list in a VIEW */ int tnum; /* Root BTree page for this table */ i16 iPKey; /* If not negative, use aCol[iPKey] as the rowid */ i16 nCol; /* Number of columns in this table */ u16 nRef; /* Number of pointers to this Table */ LogEst nRowLogEst; /* Estimated rows in table - from sqlite_stat1 table */ LogEst szTabRow; /* Estimated size of each table row in bytes */ #ifdef SQLITE_ENABLE_COSTMULT LogEst costMult; /* Cost multiplier for using this table */ #endif u8 tabFlags; /* Mask of TF_* values */ u8 keyConf; /* What to do in case of uniqueness conflict on iPKey */ #ifndef SQLITE_OMIT_ALTERTABLE int addColOffset; /* Offset in CREATE TABLE stmt to add a new column */ #endif #ifndef SQLITE_OMIT_VIRTUALTABLE int nModuleArg; /* Number of arguments to the module */ char **azModuleArg; /* 0: module 1: schema 2: vtab name 3...: args */ VTable *pVTable; /* List of VTable objects. */ #endif Trigger *pTrigger; /* List of triggers stored in pSchema */ Schema *pSchema; /* Schema that contains this table */ Table *pNextZombie; /* Next on the Parse.pZombieTab list */ }; /* ** Allowed values for Table.tabFlags. ** ** TF_OOOHidden applies to tables or view that have hidden columns that are ** followed by non-hidden columns. Example: "CREATE VIRTUAL TABLE x USING ** vtab1(a HIDDEN, b);". Since "b" is a non-hidden column but "a" is hidden, ** the TF_OOOHidden attribute would apply in this case. Such tables require ** special handling during INSERT processing. */ #define TF_Readonly 0x01 /* Read-only system table */ #define TF_Ephemeral 0x02 /* An ephemeral table */ #define TF_HasPrimaryKey 0x04 /* Table has a primary key */ #define TF_Autoincrement 0x08 /* Integer primary key is autoincrement */ #define TF_Virtual 0x10 /* Is a virtual table */ #define TF_WithoutRowid 0x20 /* No rowid. PRIMARY KEY is the key */ #define TF_NoVisibleRowid 0x40 /* No user-visible "rowid" column */ #define TF_OOOHidden 0x80 /* Out-of-Order hidden columns */ /* ** Test to see whether or not a table is a virtual table. This is ** done as a macro so that it will be optimized out when virtual ** table support is omitted from the build. */ #ifndef SQLITE_OMIT_VIRTUALTABLE # define IsVirtual(X) (((X)->tabFlags & TF_Virtual)!=0) #else # define IsVirtual(X) 0 #endif /* ** Macros to determine if a column is hidden. IsOrdinaryHiddenColumn() ** only works for non-virtual tables (ordinary tables and views) and is ** always false unless SQLITE_ENABLE_HIDDEN_COLUMNS is defined. The ** IsHiddenColumn() macro is general purpose. */ #if defined(SQLITE_ENABLE_HIDDEN_COLUMNS) # define IsHiddenColumn(X) (((X)->colFlags & COLFLAG_HIDDEN)!=0) # define IsOrdinaryHiddenColumn(X) (((X)->colFlags & COLFLAG_HIDDEN)!=0) #elif !defined(SQLITE_OMIT_VIRTUALTABLE) # define IsHiddenColumn(X) (((X)->colFlags & COLFLAG_HIDDEN)!=0) # define IsOrdinaryHiddenColumn(X) 0 #else # define IsHiddenColumn(X) 0 # define IsOrdinaryHiddenColumn(X) 0 #endif /* Does the table have a rowid */ #define HasRowid(X) (((X)->tabFlags & TF_WithoutRowid)==0) #define VisibleRowid(X) (((X)->tabFlags & TF_NoVisibleRowid)==0) /* ** Each foreign key constraint is an instance of the following structure. ** ** A foreign key is associated with two tables. The "from" table is ** the table that contains the REFERENCES clause that creates the foreign ** key. The "to" table is the table that is named in the REFERENCES clause. ** Consider this example: ** ** CREATE TABLE ex1( ** a INTEGER PRIMARY KEY, ** b INTEGER CONSTRAINT fk1 REFERENCES ex2(x) ** ); ** ** For foreign key "fk1", the from-table is "ex1" and the to-table is "ex2". ** Equivalent names: ** ** from-table == child-table ** to-table == parent-table ** ** Each REFERENCES clause generates an instance of the following structure ** which is attached to the from-table. The to-table need not exist when ** the from-table is created. The existence of the to-table is not checked. ** ** The list of all parents for child Table X is held at X.pFKey. ** ** A list of all children for a table named Z (which might not even exist) ** is held in Schema.fkeyHash with a hash key of Z. */ struct FKey { Table *pFrom; /* Table containing the REFERENCES clause (aka: Child) */ FKey *pNextFrom; /* Next FKey with the same in pFrom. Next parent of pFrom */ char *zTo; /* Name of table that the key points to (aka: Parent) */ FKey *pNextTo; /* Next with the same zTo. Next child of zTo. */ FKey *pPrevTo; /* Previous with the same zTo */ int nCol; /* Number of columns in this key */ /* EV: R-30323-21917 */ u8 isDeferred; /* True if constraint checking is deferred till COMMIT */ u8 aAction[2]; /* ON DELETE and ON UPDATE actions, respectively */ Trigger *apTrigger[2];/* Triggers for aAction[] actions */ struct sColMap { /* Mapping of columns in pFrom to columns in zTo */ int iFrom; /* Index of column in pFrom */ char *zCol; /* Name of column in zTo. If NULL use PRIMARY KEY */ } aCol[1]; /* One entry for each of nCol columns */ }; /* ** SQLite supports many different ways to resolve a constraint ** error. ROLLBACK processing means that a constraint violation ** causes the operation in process to fail and for the current transaction ** to be rolled back. ABORT processing means the operation in process ** fails and any prior changes from that one operation are backed out, ** but the transaction is not rolled back. FAIL processing means that ** the operation in progress stops and returns an error code. But prior ** changes due to the same operation are not backed out and no rollback ** occurs. IGNORE means that the particular row that caused the constraint ** error is not inserted or updated. Processing continues and no error ** is returned. REPLACE means that preexisting database rows that caused ** a UNIQUE constraint violation are removed so that the new insert or ** update can proceed. Processing continues and no error is reported. ** ** RESTRICT, SETNULL, and CASCADE actions apply only to foreign keys. ** RESTRICT is the same as ABORT for IMMEDIATE foreign keys and the ** same as ROLLBACK for DEFERRED keys. SETNULL means that the foreign ** key is set to NULL. CASCADE means that a DELETE or UPDATE of the ** referenced table row is propagated into the row that holds the ** foreign key. ** ** The following symbolic values are used to record which type ** of action to take. */ #define OE_None 0 /* There is no constraint to check */ #define OE_Rollback 1 /* Fail the operation and rollback the transaction */ #define OE_Abort 2 /* Back out changes but do no rollback transaction */ #define OE_Fail 3 /* Stop the operation but leave all prior changes */ #define OE_Ignore 4 /* Ignore the error. Do not do the INSERT or UPDATE */ #define OE_Replace 5 /* Delete existing record, then do INSERT or UPDATE */ #define OE_Restrict 6 /* OE_Abort for IMMEDIATE, OE_Rollback for DEFERRED */ #define OE_SetNull 7 /* Set the foreign key value to NULL */ #define OE_SetDflt 8 /* Set the foreign key value to its default */ #define OE_Cascade 9 /* Cascade the changes */ #define OE_Default 10 /* Do whatever the default action is */ /* ** An instance of the following structure is passed as the first ** argument to sqlite3VdbeKeyCompare and is used to control the ** comparison of the two index keys. ** ** Note that aSortOrder[] and aColl[] have nField+1 slots. There ** are nField slots for the columns of an index then one extra slot ** for the rowid at the end. */ struct KeyInfo { u32 nRef; /* Number of references to this KeyInfo object */ u8 enc; /* Text encoding - one of the SQLITE_UTF* values */ u16 nField; /* Number of key columns in the index */ u16 nXField; /* Number of columns beyond the key columns */ sqlite3 *db; /* The database connection */ u8 *aSortOrder; /* Sort order for each column. */ CollSeq *aColl[1]; /* Collating sequence for each term of the key */ }; /* ** This object holds a record which has been parsed out into individual ** fields, for the purposes of doing a comparison. ** ** A record is an object that contains one or more fields of data. ** Records are used to store the content of a table row and to store ** the key of an index. A blob encoding of a record is created by ** the OP_MakeRecord opcode of the VDBE and is disassembled by the ** OP_Column opcode. ** ** An instance of this object serves as a "key" for doing a search on ** an index b+tree. The goal of the search is to find the entry that ** is closed to the key described by this object. This object might hold ** just a prefix of the key. The number of fields is given by ** pKeyInfo->nField. ** ** The r1 and r2 fields are the values to return if this key is less than ** or greater than a key in the btree, respectively. These are normally ** -1 and +1 respectively, but might be inverted to +1 and -1 if the b-tree ** is in DESC order. ** ** The key comparison functions actually return default_rc when they find ** an equals comparison. default_rc can be -1, 0, or +1. If there are ** multiple entries in the b-tree with the same key (when only looking ** at the first pKeyInfo->nFields,) then default_rc can be set to -1 to ** cause the search to find the last match, or +1 to cause the search to ** find the first match. ** ** The key comparison functions will set eqSeen to true if they ever ** get and equal results when comparing this structure to a b-tree record. ** When default_rc!=0, the search might end up on the record immediately ** before the first match or immediately after the last match. The ** eqSeen field will indicate whether or not an exact match exists in the ** b-tree. */ struct UnpackedRecord { KeyInfo *pKeyInfo; /* Collation and sort-order information */ Mem *aMem; /* Values */ u16 nField; /* Number of entries in apMem[] */ i8 default_rc; /* Comparison result if keys are equal */ u8 errCode; /* Error detected by xRecordCompare (CORRUPT or NOMEM) */ i8 r1; /* Value to return if (lhs > rhs) */ i8 r2; /* Value to return if (rhs < lhs) */ u8 eqSeen; /* True if an equality comparison has been seen */ }; /* ** Each SQL index is represented in memory by an ** instance of the following structure. ** ** The columns of the table that are to be indexed are described ** by the aiColumn[] field of this structure. For example, suppose ** we have the following table and index: ** ** CREATE TABLE Ex1(c1 int, c2 int, c3 text); ** CREATE INDEX Ex2 ON Ex1(c3,c1); ** ** In the Table structure describing Ex1, nCol==3 because there are ** three columns in the table. In the Index structure describing ** Ex2, nColumn==2 since 2 of the 3 columns of Ex1 are indexed. ** The value of aiColumn is {2, 0}. aiColumn[0]==2 because the ** first column to be indexed (c3) has an index of 2 in Ex1.aCol[]. ** The second column to be indexed (c1) has an index of 0 in ** Ex1.aCol[], hence Ex2.aiColumn[1]==0. ** ** The Index.onError field determines whether or not the indexed columns ** must be unique and what to do if they are not. When Index.onError=OE_None, ** it means this is not a unique index. Otherwise it is a unique index ** and the value of Index.onError indicate the which conflict resolution ** algorithm to employ whenever an attempt is made to insert a non-unique ** element. ** ** While parsing a CREATE TABLE or CREATE INDEX statement in order to ** generate VDBE code (as opposed to parsing one read from an sqlite_master ** table as part of parsing an existing database schema), transient instances ** of this structure may be created. In this case the Index.tnum variable is ** used to store the address of a VDBE instruction, not a database page ** number (it cannot - the database page is not allocated until the VDBE ** program is executed). See convertToWithoutRowidTable() for details. */ struct Index { char *zName; /* Name of this index */ i16 *aiColumn; /* Which columns are used by this index. 1st is 0 */ LogEst *aiRowLogEst; /* From ANALYZE: Est. rows selected by each column */ Table *pTable; /* The SQL table being indexed */ char *zColAff; /* String defining the affinity of each column */ Index *pNext; /* The next index associated with the same table */ Schema *pSchema; /* Schema containing this index */ u8 *aSortOrder; /* for each column: True==DESC, False==ASC */ const char **azColl; /* Array of collation sequence names for index */ Expr *pPartIdxWhere; /* WHERE clause for partial indices */ ExprList *aColExpr; /* Column expressions */ int tnum; /* DB Page containing root of this index */ LogEst szIdxRow; /* Estimated average row size in bytes */ u16 nKeyCol; /* Number of columns forming the key */ u16 nColumn; /* Number of columns stored in the index */ u8 onError; /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */ unsigned idxType:2; /* 1==UNIQUE, 2==PRIMARY KEY, 0==CREATE INDEX */ unsigned bUnordered:1; /* Use this index for == or IN queries only */ unsigned uniqNotNull:1; /* True if UNIQUE and NOT NULL for all columns */ unsigned isResized:1; /* True if resizeIndexObject() has been called */ unsigned isCovering:1; /* True if this is a covering index */ unsigned noSkipScan:1; /* Do not try to use skip-scan if true */ #ifdef SQLITE_ENABLE_STAT3_OR_STAT4 int nSample; /* Number of elements in aSample[] */ int nSampleCol; /* Size of IndexSample.anEq[] and so on */ tRowcnt *aAvgEq; /* Average nEq values for keys not in aSample */ IndexSample *aSample; /* Samples of the left-most key */ tRowcnt *aiRowEst; /* Non-logarithmic stat1 data for this index */ tRowcnt nRowEst0; /* Non-logarithmic number of rows in the index */ #endif }; /* ** Allowed values for Index.idxType */ #define SQLITE_IDXTYPE_APPDEF 0 /* Created using CREATE INDEX */ #define SQLITE_IDXTYPE_UNIQUE 1 /* Implements a UNIQUE constraint */ #define SQLITE_IDXTYPE_PRIMARYKEY 2 /* Is the PRIMARY KEY for the table */ /* Return true if index X is a PRIMARY KEY index */ #define IsPrimaryKeyIndex(X) ((X)->idxType==SQLITE_IDXTYPE_PRIMARYKEY) /* Return true if index X is a UNIQUE index */ #define IsUniqueIndex(X) ((X)->onError!=OE_None) /* The Index.aiColumn[] values are normally positive integer. But ** there are some negative values that have special meaning: */ #define XN_ROWID (-1) /* Indexed column is the rowid */ #define XN_EXPR (-2) /* Indexed column is an expression */ /* ** Each sample stored in the sqlite_stat3 table is represented in memory ** using a structure of this type. See documentation at the top of the ** analyze.c source file for additional information. */ struct IndexSample { void *p; /* Pointer to sampled record */ int n; /* Size of record in bytes */ tRowcnt *anEq; /* Est. number of rows where the key equals this sample */ tRowcnt *anLt; /* Est. number of rows where key is less than this sample */ tRowcnt *anDLt; /* Est. number of distinct keys less than this sample */ }; /* ** Each token coming out of the lexer is an instance of ** this structure. Tokens are also used as part of an expression. ** ** Note if Token.z==0 then Token.dyn and Token.n are undefined and ** may contain random values. Do not make any assumptions about Token.dyn ** and Token.n when Token.z==0. */ struct Token { const char *z; /* Text of the token. Not NULL-terminated! */ unsigned int n; /* Number of characters in this token */ }; /* ** An instance of this structure contains information needed to generate ** code for a SELECT that contains aggregate functions. ** ** If Expr.op==TK_AGG_COLUMN or TK_AGG_FUNCTION then Expr.pAggInfo is a ** pointer to this structure. The Expr.iColumn field is the index in ** AggInfo.aCol[] or AggInfo.aFunc[] of information needed to generate ** code for that node. ** ** AggInfo.pGroupBy and AggInfo.aFunc.pExpr point to fields within the ** original Select structure that describes the SELECT statement. These ** fields do not need to be freed when deallocating the AggInfo structure. */ struct AggInfo { u8 directMode; /* Direct rendering mode means take data directly ** from source tables rather than from accumulators */ u8 useSortingIdx; /* In direct mode, reference the sorting index rather ** than the source table */ int sortingIdx; /* Cursor number of the sorting index */ int sortingIdxPTab; /* Cursor number of pseudo-table */ int nSortingColumn; /* Number of columns in the sorting index */ int mnReg, mxReg; /* Range of registers allocated for aCol and aFunc */ ExprList *pGroupBy; /* The group by clause */ struct AggInfo_col { /* For each column used in source tables */ Table *pTab; /* Source table */ int iTable; /* Cursor number of the source table */ int iColumn; /* Column number within the source table */ int iSorterColumn; /* Column number in the sorting index */ int iMem; /* Memory location that acts as accumulator */ Expr *pExpr; /* The original expression */ } *aCol; int nColumn; /* Number of used entries in aCol[] */ int nAccumulator; /* Number of columns that show through to the output. ** Additional columns are used only as parameters to ** aggregate functions */ struct AggInfo_func { /* For each aggregate function */ Expr *pExpr; /* Expression encoding the function */ FuncDef *pFunc; /* The aggregate function implementation */ int iMem; /* Memory location that acts as accumulator */ int iDistinct; /* Ephemeral table used to enforce DISTINCT */ } *aFunc; int nFunc; /* Number of entries in aFunc[] */ }; /* ** The datatype ynVar is a signed integer, either 16-bit or 32-bit. ** Usually it is 16-bits. But if SQLITE_MAX_VARIABLE_NUMBER is greater ** than 32767 we have to make it 32-bit. 16-bit is preferred because ** it uses less memory in the Expr object, which is a big memory user ** in systems with lots of prepared statements. And few applications ** need more than about 10 or 20 variables. But some extreme users want ** to have prepared statements with over 32767 variables, and for them ** the option is available (at compile-time). */ #if SQLITE_MAX_VARIABLE_NUMBER<=32767 typedef i16 ynVar; #else typedef int ynVar; #endif /* ** Each node of an expression in the parse tree is an instance ** of this structure. ** ** Expr.op is the opcode. The integer parser token codes are reused ** as opcodes here. For example, the parser defines TK_GE to be an integer ** code representing the ">=" operator. This same integer code is reused ** to represent the greater-than-or-equal-to operator in the expression ** tree. ** ** If the expression is an SQL literal (TK_INTEGER, TK_FLOAT, TK_BLOB, ** or TK_STRING), then Expr.token contains the text of the SQL literal. If ** the expression is a variable (TK_VARIABLE), then Expr.token contains the ** variable name. Finally, if the expression is an SQL function (TK_FUNCTION), ** then Expr.token contains the name of the function. ** ** Expr.pRight and Expr.pLeft are the left and right subexpressions of a ** binary operator. Either or both may be NULL. ** ** Expr.x.pList is a list of arguments if the expression is an SQL function, ** a CASE expression or an IN expression of the form " IN (, ...)". ** Expr.x.pSelect is used if the expression is a sub-select or an expression of ** the form " IN (SELECT ...)". If the EP_xIsSelect bit is set in the ** Expr.flags mask, then Expr.x.pSelect is valid. Otherwise, Expr.x.pList is ** valid. ** ** An expression of the form ID or ID.ID refers to a column in a table. ** For such expressions, Expr.op is set to TK_COLUMN and Expr.iTable is ** the integer cursor number of a VDBE cursor pointing to that table and ** Expr.iColumn is the column number for the specific column. If the ** expression is used as a result in an aggregate SELECT, then the ** value is also stored in the Expr.iAgg column in the aggregate so that ** it can be accessed after all aggregates are computed. ** ** If the expression is an unbound variable marker (a question mark ** character '?' in the original SQL) then the Expr.iTable holds the index ** number for that variable. ** ** If the expression is a subquery then Expr.iColumn holds an integer ** register number containing the result of the subquery. If the ** subquery gives a constant result, then iTable is -1. If the subquery ** gives a different answer at different times during statement processing ** then iTable is the address of a subroutine that computes the subquery. ** ** If the Expr is of type OP_Column, and the table it is selecting from ** is a disk table or the "old.*" pseudo-table, then pTab points to the ** corresponding table definition. ** ** ALLOCATION NOTES: ** ** Expr objects can use a lot of memory space in database schema. To ** help reduce memory requirements, sometimes an Expr object will be ** truncated. And to reduce the number of memory allocations, sometimes ** two or more Expr objects will be stored in a single memory allocation, ** together with Expr.zToken strings. ** ** If the EP_Reduced and EP_TokenOnly flags are set when ** an Expr object is truncated. When EP_Reduced is set, then all ** the child Expr objects in the Expr.pLeft and Expr.pRight subtrees ** are contained within the same memory allocation. Note, however, that ** the subtrees in Expr.x.pList or Expr.x.pSelect are always separately ** allocated, regardless of whether or not EP_Reduced is set. */ struct Expr { u8 op; /* Operation performed by this node */ char affinity; /* The affinity of the column or 0 if not a column */ u32 flags; /* Various flags. EP_* See below */ union { char *zToken; /* Token value. Zero terminated and dequoted */ int iValue; /* Non-negative integer value if EP_IntValue */ } u; /* If the EP_TokenOnly flag is set in the Expr.flags mask, then no ** space is allocated for the fields below this point. An attempt to ** access them will result in a segfault or malfunction. *********************************************************************/ Expr *pLeft; /* Left subnode */ Expr *pRight; /* Right subnode */ union { ExprList *pList; /* op = IN, EXISTS, SELECT, CASE, FUNCTION, BETWEEN */ Select *pSelect; /* EP_xIsSelect and op = IN, EXISTS, SELECT */ } x; /* If the EP_Reduced flag is set in the Expr.flags mask, then no ** space is allocated for the fields below this point. An attempt to ** access them will result in a segfault or malfunction. *********************************************************************/ #if SQLITE_MAX_EXPR_DEPTH>0 int nHeight; /* Height of the tree headed by this node */ #endif int iTable; /* TK_COLUMN: cursor number of table holding column ** TK_REGISTER: register number ** TK_TRIGGER: 1 -> new, 0 -> old ** EP_Unlikely: 134217728 times likelihood ** TK_SELECT: 1st register of result vector */ ynVar iColumn; /* TK_COLUMN: column index. -1 for rowid. ** TK_VARIABLE: variable number (always >= 1). ** TK_SELECT_COLUMN: column of the result vector */ i16 iAgg; /* Which entry in pAggInfo->aCol[] or ->aFunc[] */ i16 iRightJoinTable; /* If EP_FromJoin, the right table of the join */ u8 op2; /* TK_REGISTER: original value of Expr.op ** TK_COLUMN: the value of p5 for OP_Column ** TK_AGG_FUNCTION: nesting depth */ AggInfo *pAggInfo; /* Used by TK_AGG_COLUMN and TK_AGG_FUNCTION */ Table *pTab; /* Table for TK_COLUMN expressions. */ }; /* ** The following are the meanings of bits in the Expr.flags field. */ #define EP_FromJoin 0x000001 /* Originates in ON/USING clause of outer join */ #define EP_Agg 0x000002 /* Contains one or more aggregate functions */ #define EP_Resolved 0x000004 /* IDs have been resolved to COLUMNs */ #define EP_Error 0x000008 /* Expression contains one or more errors */ #define EP_Distinct 0x000010 /* Aggregate function with DISTINCT keyword */ #define EP_VarSelect 0x000020 /* pSelect is correlated, not constant */ #define EP_DblQuoted 0x000040 /* token.z was originally in "..." */ #define EP_InfixFunc 0x000080 /* True for an infix function: LIKE, GLOB, etc */ #define EP_Collate 0x000100 /* Tree contains a TK_COLLATE operator */ #define EP_Generic 0x000200 /* Ignore COLLATE or affinity on this tree */ #define EP_IntValue 0x000400 /* Integer value contained in u.iValue */ #define EP_xIsSelect 0x000800 /* x.pSelect is valid (otherwise x.pList is) */ #define EP_Skip 0x001000 /* COLLATE, AS, or UNLIKELY */ #define EP_Reduced 0x002000 /* Expr struct EXPR_REDUCEDSIZE bytes only */ #define EP_TokenOnly 0x004000 /* Expr struct EXPR_TOKENONLYSIZE bytes only */ #define EP_Static 0x008000 /* Held in memory not obtained from malloc() */ #define EP_MemToken 0x010000 /* Need to sqlite3DbFree() Expr.zToken */ #define EP_NoReduce 0x020000 /* Cannot EXPRDUP_REDUCE this Expr */ #define EP_Unlikely 0x040000 /* unlikely() or likelihood() function */ #define EP_ConstFunc 0x080000 /* A SQLITE_FUNC_CONSTANT or _SLOCHNG function */ #define EP_CanBeNull 0x100000 /* Can be null despite NOT NULL constraint */ #define EP_Subquery 0x200000 /* Tree contains a TK_SELECT operator */ #define EP_Alias 0x400000 /* Is an alias for a result set column */ #define EP_Leaf 0x800000 /* Expr.pLeft, .pRight, .u.pSelect all NULL */ /* ** Combinations of two or more EP_* flags */ #define EP_Propagate (EP_Collate|EP_Subquery) /* Propagate these bits up tree */ /* ** These macros can be used to test, set, or clear bits in the ** Expr.flags field. */ #define ExprHasProperty(E,P) (((E)->flags&(P))!=0) #define ExprHasAllProperty(E,P) (((E)->flags&(P))==(P)) #define ExprSetProperty(E,P) (E)->flags|=(P) #define ExprClearProperty(E,P) (E)->flags&=~(P) /* The ExprSetVVAProperty() macro is used for Verification, Validation, ** and Accreditation only. It works like ExprSetProperty() during VVA ** processes but is a no-op for delivery. */ #ifdef SQLITE_DEBUG # define ExprSetVVAProperty(E,P) (E)->flags|=(P) #else # define ExprSetVVAProperty(E,P) #endif /* ** Macros to determine the number of bytes required by a normal Expr ** struct, an Expr struct with the EP_Reduced flag set in Expr.flags ** and an Expr struct with the EP_TokenOnly flag set. */ #define EXPR_FULLSIZE sizeof(Expr) /* Full size */ #define EXPR_REDUCEDSIZE offsetof(Expr,iTable) /* Common features */ #define EXPR_TOKENONLYSIZE offsetof(Expr,pLeft) /* Fewer features */ /* ** Flags passed to the sqlite3ExprDup() function. See the header comment ** above sqlite3ExprDup() for details. */ #define EXPRDUP_REDUCE 0x0001 /* Used reduced-size Expr nodes */ /* ** A list of expressions. Each expression may optionally have a ** name. An expr/name combination can be used in several ways, such ** as the list of "expr AS ID" fields following a "SELECT" or in the ** list of "ID = expr" items in an UPDATE. A list of expressions can ** also be used as the argument to a function, in which case the a.zName ** field is not used. ** ** By default the Expr.zSpan field holds a human-readable description of ** the expression that is used in the generation of error messages and ** column labels. In this case, Expr.zSpan is typically the text of a ** column expression as it exists in a SELECT statement. However, if ** the bSpanIsTab flag is set, then zSpan is overloaded to mean the name ** of the result column in the form: DATABASE.TABLE.COLUMN. This later ** form is used for name resolution with nested FROM clauses. */ struct ExprList { int nExpr; /* Number of expressions on the list */ struct ExprList_item { /* For each expression in the list */ Expr *pExpr; /* The list of expressions */ char *zName; /* Token associated with this expression */ char *zSpan; /* Original text of the expression */ u8 sortOrder; /* 1 for DESC or 0 for ASC */ unsigned done :1; /* A flag to indicate when processing is finished */ unsigned bSpanIsTab :1; /* zSpan holds DB.TABLE.COLUMN */ unsigned reusable :1; /* Constant expression is reusable */ union { struct { u16 iOrderByCol; /* For ORDER BY, column number in result set */ u16 iAlias; /* Index into Parse.aAlias[] for zName */ } x; int iConstExprReg; /* Register in which Expr value is cached */ } u; } *a; /* Alloc a power of two greater or equal to nExpr */ }; /* ** An instance of this structure is used by the parser to record both ** the parse tree for an expression and the span of input text for an ** expression. */ struct ExprSpan { Expr *pExpr; /* The expression parse tree */ const char *zStart; /* First character of input text */ const char *zEnd; /* One character past the end of input text */ }; /* ** An instance of this structure can hold a simple list of identifiers, ** such as the list "a,b,c" in the following statements: ** ** INSERT INTO t(a,b,c) VALUES ...; ** CREATE INDEX idx ON t(a,b,c); ** CREATE TRIGGER trig BEFORE UPDATE ON t(a,b,c) ...; ** ** The IdList.a.idx field is used when the IdList represents the list of ** column names after a table name in an INSERT statement. In the statement ** ** INSERT INTO t(a,b,c) ... ** ** If "a" is the k-th column of table "t", then IdList.a[0].idx==k. */ struct IdList { struct IdList_item { char *zName; /* Name of the identifier */ int idx; /* Index in some Table.aCol[] of a column named zName */ } *a; int nId; /* Number of identifiers on the list */ }; /* ** The bitmask datatype defined below is used for various optimizations. ** ** Changing this from a 64-bit to a 32-bit type limits the number of ** tables in a join to 32 instead of 64. But it also reduces the size ** of the library by 738 bytes on ix86. */ #ifdef SQLITE_BITMASK_TYPE typedef SQLITE_BITMASK_TYPE Bitmask; #else typedef u64 Bitmask; #endif /* ** The number of bits in a Bitmask. "BMS" means "BitMask Size". */ #define BMS ((int)(sizeof(Bitmask)*8)) /* ** A bit in a Bitmask */ #define MASKBIT(n) (((Bitmask)1)<<(n)) #define MASKBIT32(n) (((unsigned int)1)<<(n)) #define ALLBITS ((Bitmask)-1) /* ** The following structure describes the FROM clause of a SELECT statement. ** Each table or subquery in the FROM clause is a separate element of ** the SrcList.a[] array. ** ** With the addition of multiple database support, the following structure ** can also be used to describe a particular table such as the table that ** is modified by an INSERT, DELETE, or UPDATE statement. In standard SQL, ** such a table must be a simple name: ID. But in SQLite, the table can ** now be identified by a database name, a dot, then the table name: ID.ID. ** ** The jointype starts out showing the join type between the current table ** and the next table on the list. The parser builds the list this way. ** But sqlite3SrcListShiftJoinType() later shifts the jointypes so that each ** jointype expresses the join between the table and the previous table. ** ** In the colUsed field, the high-order bit (bit 63) is set if the table ** contains more than 63 columns and the 64-th or later column is used. */ struct SrcList { int nSrc; /* Number of tables or subqueries in the FROM clause */ u32 nAlloc; /* Number of entries allocated in a[] below */ struct SrcList_item { Schema *pSchema; /* Schema to which this item is fixed */ char *zDatabase; /* Name of database holding this table */ char *zName; /* Name of the table */ char *zAlias; /* The "B" part of a "A AS B" phrase. zName is the "A" */ Table *pTab; /* An SQL table corresponding to zName */ Select *pSelect; /* A SELECT statement used in place of a table name */ int addrFillSub; /* Address of subroutine to manifest a subquery */ int regReturn; /* Register holding return address of addrFillSub */ int regResult; /* Registers holding results of a co-routine */ struct { u8 jointype; /* Type of join between this table and the previous */ unsigned notIndexed :1; /* True if there is a NOT INDEXED clause */ unsigned isIndexedBy :1; /* True if there is an INDEXED BY clause */ unsigned isTabFunc :1; /* True if table-valued-function syntax */ unsigned isCorrelated :1; /* True if sub-query is correlated */ unsigned viaCoroutine :1; /* Implemented as a co-routine */ unsigned isRecursive :1; /* True for recursive reference in WITH */ } fg; #ifndef SQLITE_OMIT_EXPLAIN u8 iSelectId; /* If pSelect!=0, the id of the sub-select in EQP */ #endif int iCursor; /* The VDBE cursor number used to access this table */ Expr *pOn; /* The ON clause of a join */ IdList *pUsing; /* The USING clause of a join */ Bitmask colUsed; /* Bit N (1<" clause */ ExprList *pFuncArg; /* Arguments to table-valued-function */ } u1; Index *pIBIndex; /* Index structure corresponding to u1.zIndexedBy */ } a[1]; /* One entry for each identifier on the list */ }; /* ** Permitted values of the SrcList.a.jointype field */ #define JT_INNER 0x0001 /* Any kind of inner or cross join */ #define JT_CROSS 0x0002 /* Explicit use of the CROSS keyword */ #define JT_NATURAL 0x0004 /* True for a "natural" join */ #define JT_LEFT 0x0008 /* Left outer join */ #define JT_RIGHT 0x0010 /* Right outer join */ #define JT_OUTER 0x0020 /* The "OUTER" keyword is present */ #define JT_ERROR 0x0040 /* unknown or unsupported join type */ /* ** Flags appropriate for the wctrlFlags parameter of sqlite3WhereBegin() ** and the WhereInfo.wctrlFlags member. ** ** Value constraints (enforced via assert()): ** WHERE_USE_LIMIT == SF_FixedLimit */ #define WHERE_ORDERBY_NORMAL 0x0000 /* No-op */ #define WHERE_ORDERBY_MIN 0x0001 /* ORDER BY processing for min() func */ #define WHERE_ORDERBY_MAX 0x0002 /* ORDER BY processing for max() func */ #define WHERE_ONEPASS_DESIRED 0x0004 /* Want to do one-pass UPDATE/DELETE */ #define WHERE_ONEPASS_MULTIROW 0x0008 /* ONEPASS is ok with multiple rows */ #define WHERE_DUPLICATES_OK 0x0010 /* Ok to return a row more than once */ #define WHERE_OR_SUBCLAUSE 0x0020 /* Processing a sub-WHERE as part of ** the OR optimization */ #define WHERE_GROUPBY 0x0040 /* pOrderBy is really a GROUP BY */ #define WHERE_DISTINCTBY 0x0080 /* pOrderby is really a DISTINCT clause */ #define WHERE_WANT_DISTINCT 0x0100 /* All output needs to be distinct */ #define WHERE_SORTBYGROUP 0x0200 /* Support sqlite3WhereIsSorted() */ #define WHERE_SEEK_TABLE 0x0400 /* Do not defer seeks on main table */ #define WHERE_ORDERBY_LIMIT 0x0800 /* ORDERBY+LIMIT on the inner loop */ /* 0x1000 not currently used */ /* 0x2000 not currently used */ #define WHERE_USE_LIMIT 0x4000 /* Use the LIMIT in cost estimates */ /* 0x8000 not currently used */ /* Allowed return values from sqlite3WhereIsDistinct() */ #define WHERE_DISTINCT_NOOP 0 /* DISTINCT keyword not used */ #define WHERE_DISTINCT_UNIQUE 1 /* No duplicates */ #define WHERE_DISTINCT_ORDERED 2 /* All duplicates are adjacent */ #define WHERE_DISTINCT_UNORDERED 3 /* Duplicates are scattered */ /* ** A NameContext defines a context in which to resolve table and column ** names. The context consists of a list of tables (the pSrcList) field and ** a list of named expression (pEList). The named expression list may ** be NULL. The pSrc corresponds to the FROM clause of a SELECT or ** to the table being operated on by INSERT, UPDATE, or DELETE. The ** pEList corresponds to the result set of a SELECT and is NULL for ** other statements. ** ** NameContexts can be nested. When resolving names, the inner-most ** context is searched first. If no match is found, the next outer ** context is checked. If there is still no match, the next context ** is checked. This process continues until either a match is found ** or all contexts are check. When a match is found, the nRef member of ** the context containing the match is incremented. ** ** Each subquery gets a new NameContext. The pNext field points to the ** NameContext in the parent query. Thus the process of scanning the ** NameContext list corresponds to searching through successively outer ** subqueries looking for a match. */ struct NameContext { Parse *pParse; /* The parser */ SrcList *pSrcList; /* One or more tables used to resolve names */ ExprList *pEList; /* Optional list of result-set columns */ AggInfo *pAggInfo; /* Information about aggregates at this level */ NameContext *pNext; /* Next outer name context. NULL for outermost */ int nRef; /* Number of names resolved by this context */ int nErr; /* Number of errors encountered while resolving names */ u16 ncFlags; /* Zero or more NC_* flags defined below */ }; /* ** Allowed values for the NameContext, ncFlags field. ** ** Value constraints (all checked via assert()): ** NC_HasAgg == SF_HasAgg ** NC_MinMaxAgg == SF_MinMaxAgg == SQLITE_FUNC_MINMAX ** */ #define NC_AllowAgg 0x0001 /* Aggregate functions are allowed here */ #define NC_PartIdx 0x0002 /* True if resolving a partial index WHERE */ #define NC_IsCheck 0x0004 /* True if resolving names in a CHECK constraint */ #define NC_InAggFunc 0x0008 /* True if analyzing arguments to an agg func */ #define NC_HasAgg 0x0010 /* One or more aggregate functions seen */ #define NC_IdxExpr 0x0020 /* True if resolving columns of CREATE INDEX */ #define NC_VarSelect 0x0040 /* A correlated subquery has been seen */ #define NC_MinMaxAgg 0x1000 /* min/max aggregates seen. See note above */ /* ** An instance of the following structure contains all information ** needed to generate code for a single SELECT statement. ** ** nLimit is set to -1 if there is no LIMIT clause. nOffset is set to 0. ** If there is a LIMIT clause, the parser sets nLimit to the value of the ** limit and nOffset to the value of the offset (or 0 if there is not ** offset). But later on, nLimit and nOffset become the memory locations ** in the VDBE that record the limit and offset counters. ** ** addrOpenEphm[] entries contain the address of OP_OpenEphemeral opcodes. ** These addresses must be stored so that we can go back and fill in ** the P4_KEYINFO and P2 parameters later. Neither the KeyInfo nor ** the number of columns in P2 can be computed at the same time ** as the OP_OpenEphm instruction is coded because not ** enough information about the compound query is known at that point. ** The KeyInfo for addrOpenTran[0] and [1] contains collating sequences ** for the result set. The KeyInfo for addrOpenEphm[2] contains collating ** sequences for the ORDER BY clause. */ struct Select { ExprList *pEList; /* The fields of the result */ u8 op; /* One of: TK_UNION TK_ALL TK_INTERSECT TK_EXCEPT */ LogEst nSelectRow; /* Estimated number of result rows */ u32 selFlags; /* Various SF_* values */ int iLimit, iOffset; /* Memory registers holding LIMIT & OFFSET counters */ #if SELECTTRACE_ENABLED char zSelName[12]; /* Symbolic name of this SELECT use for debugging */ #endif int addrOpenEphm[2]; /* OP_OpenEphem opcodes related to this select */ SrcList *pSrc; /* The FROM clause */ Expr *pWhere; /* The WHERE clause */ ExprList *pGroupBy; /* The GROUP BY clause */ Expr *pHaving; /* The HAVING clause */ ExprList *pOrderBy; /* The ORDER BY clause */ Select *pPrior; /* Prior select in a compound select statement */ Select *pNext; /* Next select to the left in a compound */ Expr *pLimit; /* LIMIT expression. NULL means not used. */ Expr *pOffset; /* OFFSET expression. NULL means not used. */ With *pWith; /* WITH clause attached to this select. Or NULL. */ }; /* ** Allowed values for Select.selFlags. The "SF" prefix stands for ** "Select Flag". ** ** Value constraints (all checked via assert()) ** SF_HasAgg == NC_HasAgg ** SF_MinMaxAgg == NC_MinMaxAgg == SQLITE_FUNC_MINMAX ** SF_FixedLimit == WHERE_USE_LIMIT */ #define SF_Distinct 0x00001 /* Output should be DISTINCT */ #define SF_All 0x00002 /* Includes the ALL keyword */ #define SF_Resolved 0x00004 /* Identifiers have been resolved */ #define SF_Aggregate 0x00008 /* Contains agg functions or a GROUP BY */ #define SF_HasAgg 0x00010 /* Contains aggregate functions */ #define SF_UsesEphemeral 0x00020 /* Uses the OpenEphemeral opcode */ #define SF_Expanded 0x00040 /* sqlite3SelectExpand() called on this */ #define SF_HasTypeInfo 0x00080 /* FROM subqueries have Table metadata */ #define SF_Compound 0x00100 /* Part of a compound query */ #define SF_Values 0x00200 /* Synthesized from VALUES clause */ #define SF_MultiValue 0x00400 /* Single VALUES term with multiple rows */ #define SF_NestedFrom 0x00800 /* Part of a parenthesized FROM clause */ #define SF_MinMaxAgg 0x01000 /* Aggregate containing min() or max() */ #define SF_Recursive 0x02000 /* The recursive part of a recursive CTE */ #define SF_FixedLimit 0x04000 /* nSelectRow set by a constant LIMIT */ #define SF_MaybeConvert 0x08000 /* Need convertCompoundSelectToSubquery() */ #define SF_Converted 0x10000 /* By convertCompoundSelectToSubquery() */ #define SF_IncludeHidden 0x20000 /* Include hidden columns in output */ /* ** The results of a SELECT can be distributed in several ways, as defined ** by one of the following macros. The "SRT" prefix means "SELECT Result ** Type". ** ** SRT_Union Store results as a key in a temporary index ** identified by pDest->iSDParm. ** ** SRT_Except Remove results from the temporary index pDest->iSDParm. ** ** SRT_Exists Store a 1 in memory cell pDest->iSDParm if the result ** set is not empty. ** ** SRT_Discard Throw the results away. This is used by SELECT ** statements within triggers whose only purpose is ** the side-effects of functions. ** ** All of the above are free to ignore their ORDER BY clause. Those that ** follow must honor the ORDER BY clause. ** ** SRT_Output Generate a row of output (using the OP_ResultRow ** opcode) for each row in the result set. ** ** SRT_Mem Only valid if the result is a single column. ** Store the first column of the first result row ** in register pDest->iSDParm then abandon the rest ** of the query. This destination implies "LIMIT 1". ** ** SRT_Set The result must be a single column. Store each ** row of result as the key in table pDest->iSDParm. ** Apply the affinity pDest->affSdst before storing ** results. Used to implement "IN (SELECT ...)". ** ** SRT_EphemTab Create an temporary table pDest->iSDParm and store ** the result there. The cursor is left open after ** returning. This is like SRT_Table except that ** this destination uses OP_OpenEphemeral to create ** the table first. ** ** SRT_Coroutine Generate a co-routine that returns a new row of ** results each time it is invoked. The entry point ** of the co-routine is stored in register pDest->iSDParm ** and the result row is stored in pDest->nDest registers ** starting with pDest->iSdst. ** ** SRT_Table Store results in temporary table pDest->iSDParm. ** SRT_Fifo This is like SRT_EphemTab except that the table ** is assumed to already be open. SRT_Fifo has ** the additional property of being able to ignore ** the ORDER BY clause. ** ** SRT_DistFifo Store results in a temporary table pDest->iSDParm. ** But also use temporary table pDest->iSDParm+1 as ** a record of all prior results and ignore any duplicate ** rows. Name means: "Distinct Fifo". ** ** SRT_Queue Store results in priority queue pDest->iSDParm (really ** an index). Append a sequence number so that all entries ** are distinct. ** ** SRT_DistQueue Store results in priority queue pDest->iSDParm only if ** the same record has never been stored before. The ** index at pDest->iSDParm+1 hold all prior stores. */ #define SRT_Union 1 /* Store result as keys in an index */ #define SRT_Except 2 /* Remove result from a UNION index */ #define SRT_Exists 3 /* Store 1 if the result is not empty */ #define SRT_Discard 4 /* Do not save the results anywhere */ #define SRT_Fifo 5 /* Store result as data with an automatic rowid */ #define SRT_DistFifo 6 /* Like SRT_Fifo, but unique results only */ #define SRT_Queue 7 /* Store result in an queue */ #define SRT_DistQueue 8 /* Like SRT_Queue, but unique results only */ /* The ORDER BY clause is ignored for all of the above */ #define IgnorableOrderby(X) ((X->eDest)<=SRT_DistQueue) #define SRT_Output 9 /* Output each row of result */ #define SRT_Mem 10 /* Store result in a memory cell */ #define SRT_Set 11 /* Store results as keys in an index */ #define SRT_EphemTab 12 /* Create transient tab and store like SRT_Table */ #define SRT_Coroutine 13 /* Generate a single row of result */ #define SRT_Table 14 /* Store result as data with an automatic rowid */ /* ** An instance of this object describes where to put of the results of ** a SELECT statement. */ struct SelectDest { u8 eDest; /* How to dispose of the results. On of SRT_* above. */ char *zAffSdst; /* Affinity used when eDest==SRT_Set */ int iSDParm; /* A parameter used by the eDest disposal method */ int iSdst; /* Base register where results are written */ int nSdst; /* Number of registers allocated */ ExprList *pOrderBy; /* Key columns for SRT_Queue and SRT_DistQueue */ }; /* ** During code generation of statements that do inserts into AUTOINCREMENT ** tables, the following information is attached to the Table.u.autoInc.p ** pointer of each autoincrement table to record some side information that ** the code generator needs. We have to keep per-table autoincrement ** information in case inserts are done within triggers. Triggers do not ** normally coordinate their activities, but we do need to coordinate the ** loading and saving of autoincrement information. */ struct AutoincInfo { AutoincInfo *pNext; /* Next info block in a list of them all */ Table *pTab; /* Table this info block refers to */ int iDb; /* Index in sqlite3.aDb[] of database holding pTab */ int regCtr; /* Memory register holding the rowid counter */ }; /* ** Size of the column cache */ #ifndef SQLITE_N_COLCACHE # define SQLITE_N_COLCACHE 10 #endif /* ** At least one instance of the following structure is created for each ** trigger that may be fired while parsing an INSERT, UPDATE or DELETE ** statement. All such objects are stored in the linked list headed at ** Parse.pTriggerPrg and deleted once statement compilation has been ** completed. ** ** A Vdbe sub-program that implements the body and WHEN clause of trigger ** TriggerPrg.pTrigger, assuming a default ON CONFLICT clause of ** TriggerPrg.orconf, is stored in the TriggerPrg.pProgram variable. ** The Parse.pTriggerPrg list never contains two entries with the same ** values for both pTrigger and orconf. ** ** The TriggerPrg.aColmask[0] variable is set to a mask of old.* columns ** accessed (or set to 0 for triggers fired as a result of INSERT ** statements). Similarly, the TriggerPrg.aColmask[1] variable is set to ** a mask of new.* columns used by the program. */ struct TriggerPrg { Trigger *pTrigger; /* Trigger this program was coded from */ TriggerPrg *pNext; /* Next entry in Parse.pTriggerPrg list */ SubProgram *pProgram; /* Program implementing pTrigger/orconf */ int orconf; /* Default ON CONFLICT policy */ u32 aColmask[2]; /* Masks of old.*, new.* columns accessed */ }; /* ** The yDbMask datatype for the bitmask of all attached databases. */ #if SQLITE_MAX_ATTACHED>30 typedef unsigned char yDbMask[(SQLITE_MAX_ATTACHED+9)/8]; # define DbMaskTest(M,I) (((M)[(I)/8]&(1<<((I)&7)))!=0) # define DbMaskZero(M) memset((M),0,sizeof(M)) # define DbMaskSet(M,I) (M)[(I)/8]|=(1<<((I)&7)) # define DbMaskAllZero(M) sqlite3DbMaskAllZero(M) # define DbMaskNonZero(M) (sqlite3DbMaskAllZero(M)==0) #else typedef unsigned int yDbMask; # define DbMaskTest(M,I) (((M)&(((yDbMask)1)<<(I)))!=0) # define DbMaskZero(M) (M)=0 # define DbMaskSet(M,I) (M)|=(((yDbMask)1)<<(I)) # define DbMaskAllZero(M) (M)==0 # define DbMaskNonZero(M) (M)!=0 #endif /* ** An SQL parser context. A copy of this structure is passed through ** the parser and down into all the parser action routine in order to ** carry around information that is global to the entire parse. ** ** The structure is divided into two parts. When the parser and code ** generate call themselves recursively, the first part of the structure ** is constant but the second part is reset at the beginning and end of ** each recursion. ** ** The nTableLock and aTableLock variables are only used if the shared-cache ** feature is enabled (if sqlite3Tsd()->useSharedData is true). They are ** used to store the set of table-locks required by the statement being ** compiled. Function sqlite3TableLock() is used to add entries to the ** list. */ struct Parse { sqlite3 *db; /* The main database structure */ char *zErrMsg; /* An error message */ Vdbe *pVdbe; /* An engine for executing database bytecode */ int rc; /* Return code from execution */ u8 colNamesSet; /* TRUE after OP_ColumnName has been issued to pVdbe */ u8 checkSchema; /* Causes schema cookie check after an error */ u8 nested; /* Number of nested calls to the parser/code generator */ u8 nTempReg; /* Number of temporary registers in aTempReg[] */ u8 isMultiWrite; /* True if statement may modify/insert multiple rows */ u8 mayAbort; /* True if statement may throw an ABORT exception */ u8 hasCompound; /* Need to invoke convertCompoundSelectToSubquery() */ u8 okConstFactor; /* OK to factor out constants */ u8 disableLookaside; /* Number of times lookaside has been disabled */ u8 nColCache; /* Number of entries in aColCache[] */ int nRangeReg; /* Size of the temporary register block */ int iRangeReg; /* First register in temporary register block */ int nErr; /* Number of errors seen */ int nTab; /* Number of previously allocated VDBE cursors */ int nMem; /* Number of memory cells used so far */ int nOpAlloc; /* Number of slots allocated for Vdbe.aOp[] */ int szOpAlloc; /* Bytes of memory space allocated for Vdbe.aOp[] */ int ckBase; /* Base register of data during check constraints */ int iSelfTab; /* Table of an index whose exprs are being coded */ int iCacheLevel; /* ColCache valid when aColCache[].iLevel<=iCacheLevel */ int iCacheCnt; /* Counter used to generate aColCache[].lru values */ int nLabel; /* Number of labels used */ int *aLabel; /* Space to hold the labels */ ExprList *pConstExpr;/* Constant expressions */ Token constraintName;/* Name of the constraint currently being parsed */ yDbMask writeMask; /* Start a write transaction on these databases */ yDbMask cookieMask; /* Bitmask of schema verified databases */ int regRowid; /* Register holding rowid of CREATE TABLE entry */ int regRoot; /* Register holding root page number for new objects */ int nMaxArg; /* Max args passed to user function by sub-program */ #if SELECTTRACE_ENABLED int nSelect; /* Number of SELECT statements seen */ int nSelectIndent; /* How far to indent SELECTTRACE() output */ #endif #ifndef SQLITE_OMIT_SHARED_CACHE int nTableLock; /* Number of locks in aTableLock */ TableLock *aTableLock; /* Required table locks for shared-cache mode */ #endif AutoincInfo *pAinc; /* Information about AUTOINCREMENT counters */ Parse *pToplevel; /* Parse structure for main program (or NULL) */ Table *pTriggerTab; /* Table triggers are being coded for */ int addrCrTab; /* Address of OP_CreateTable opcode on CREATE TABLE */ u32 nQueryLoop; /* Est number of iterations of a query (10*log2(N)) */ u32 oldmask; /* Mask of old.* columns referenced */ u32 newmask; /* Mask of new.* columns referenced */ u8 eTriggerOp; /* TK_UPDATE, TK_INSERT or TK_DELETE */ u8 eOrconf; /* Default ON CONFLICT policy for trigger steps */ u8 disableTriggers; /* True to disable triggers */ /************************************************************************** ** Fields above must be initialized to zero. The fields that follow, ** down to the beginning of the recursive section, do not need to be ** initialized as they will be set before being used. The boundary is ** determined by offsetof(Parse,aColCache). **************************************************************************/ struct yColCache { int iTable; /* Table cursor number */ i16 iColumn; /* Table column number */ u8 tempReg; /* iReg is a temp register that needs to be freed */ int iLevel; /* Nesting level */ int iReg; /* Reg with value of this column. 0 means none. */ int lru; /* Least recently used entry has the smallest value */ } aColCache[SQLITE_N_COLCACHE]; /* One for each column cache entry */ int aTempReg[8]; /* Holding area for temporary registers */ Token sNameToken; /* Token with unqualified schema object name */ Token sLastToken; /* The last token parsed */ /************************************************************************ ** Above is constant between recursions. Below is reset before and after ** each recursion. The boundary between these two regions is determined ** using offsetof(Parse,nVar) so the nVar field must be the first field ** in the recursive region. ************************************************************************/ ynVar nVar; /* Number of '?' variables seen in the SQL so far */ int nzVar; /* Number of available slots in azVar[] */ u8 iPkSortOrder; /* ASC or DESC for INTEGER PRIMARY KEY */ u8 explain; /* True if the EXPLAIN flag is found on the query */ #ifndef SQLITE_OMIT_VIRTUALTABLE u8 declareVtab; /* True if inside sqlite3_declare_vtab() */ int nVtabLock; /* Number of virtual tables to lock */ #endif int nHeight; /* Expression tree height of current sub-select */ #ifndef SQLITE_OMIT_EXPLAIN int iSelectId; /* ID of current select for EXPLAIN output */ int iNextSelectId; /* Next available select ID for EXPLAIN output */ #endif char **azVar; /* Pointers to names of parameters */ Vdbe *pReprepare; /* VM being reprepared (sqlite3Reprepare()) */ const char *zTail; /* All SQL text past the last semicolon parsed */ Table *pNewTable; /* A table being constructed by CREATE TABLE */ Trigger *pNewTrigger; /* Trigger under construct by a CREATE TRIGGER */ const char *zAuthContext; /* The 6th parameter to db->xAuth callbacks */ #ifndef SQLITE_OMIT_VIRTUALTABLE Token sArg; /* Complete text of a module argument */ Table **apVtabLock; /* Pointer to virtual tables needing locking */ #endif Table *pZombieTab; /* List of Table objects to delete after code gen */ TriggerPrg *pTriggerPrg; /* Linked list of coded triggers */ With *pWith; /* Current WITH clause, or NULL */ With *pWithToFree; /* Free this WITH object at the end of the parse */ }; /* ** Sizes and pointers of various parts of the Parse object. */ #define PARSE_HDR_SZ offsetof(Parse,aColCache) /* Recursive part w/o aColCache*/ #define PARSE_RECURSE_SZ offsetof(Parse,nVar) /* Recursive part */ #define PARSE_TAIL_SZ (sizeof(Parse)-PARSE_RECURSE_SZ) /* Non-recursive part */ #define PARSE_TAIL(X) (((char*)(X))+PARSE_RECURSE_SZ) /* Pointer to tail */ /* ** Return true if currently inside an sqlite3_declare_vtab() call. */ #ifdef SQLITE_OMIT_VIRTUALTABLE #define IN_DECLARE_VTAB 0 #else #define IN_DECLARE_VTAB (pParse->declareVtab) #endif /* ** An instance of the following structure can be declared on a stack and used ** to save the Parse.zAuthContext value so that it can be restored later. */ struct AuthContext { const char *zAuthContext; /* Put saved Parse.zAuthContext here */ Parse *pParse; /* The Parse structure */ }; /* ** Bitfield flags for P5 value in various opcodes. ** ** Value constraints (enforced via assert()): ** OPFLAG_LENGTHARG == SQLITE_FUNC_LENGTH ** OPFLAG_TYPEOFARG == SQLITE_FUNC_TYPEOF ** OPFLAG_BULKCSR == BTREE_BULKLOAD ** OPFLAG_SEEKEQ == BTREE_SEEK_EQ ** OPFLAG_FORDELETE == BTREE_FORDELETE ** OPFLAG_SAVEPOSITION == BTREE_SAVEPOSITION ** OPFLAG_AUXDELETE == BTREE_AUXDELETE */ #define OPFLAG_NCHANGE 0x01 /* OP_Insert: Set to update db->nChange */ /* Also used in P2 (not P5) of OP_Delete */ #define OPFLAG_EPHEM 0x01 /* OP_Column: Ephemeral output is ok */ #define OPFLAG_LASTROWID 0x02 /* Set to update db->lastRowid */ #define OPFLAG_ISUPDATE 0x04 /* This OP_Insert is an sql UPDATE */ #define OPFLAG_APPEND 0x08 /* This is likely to be an append */ #define OPFLAG_USESEEKRESULT 0x10 /* Try to avoid a seek in BtreeInsert() */ #ifdef SQLITE_ENABLE_PREUPDATE_HOOK #define OPFLAG_ISNOOP 0x40 /* OP_Delete does pre-update-hook only */ #endif #define OPFLAG_LENGTHARG 0x40 /* OP_Column only used for length() */ #define OPFLAG_TYPEOFARG 0x80 /* OP_Column only used for typeof() */ #define OPFLAG_BULKCSR 0x01 /* OP_Open** used to open bulk cursor */ #define OPFLAG_SEEKEQ 0x02 /* OP_Open** cursor uses EQ seek only */ #define OPFLAG_FORDELETE 0x08 /* OP_Open should use BTREE_FORDELETE */ #define OPFLAG_P2ISREG 0x10 /* P2 to OP_Open** is a register number */ #define OPFLAG_PERMUTE 0x01 /* OP_Compare: use the permutation */ #define OPFLAG_SAVEPOSITION 0x02 /* OP_Delete: keep cursor position */ #define OPFLAG_AUXDELETE 0x04 /* OP_Delete: index in a DELETE op */ /* * Each trigger present in the database schema is stored as an instance of * struct Trigger. * * Pointers to instances of struct Trigger are stored in two ways. * 1. In the "trigHash" hash table (part of the sqlite3* that represents the * database). This allows Trigger structures to be retrieved by name. * 2. All triggers associated with a single table form a linked list, using the * pNext member of struct Trigger. A pointer to the first element of the * linked list is stored as the "pTrigger" member of the associated * struct Table. * * The "step_list" member points to the first element of a linked list * containing the SQL statements specified as the trigger program. */ struct Trigger { char *zName; /* The name of the trigger */ char *table; /* The table or view to which the trigger applies */ u8 op; /* One of TK_DELETE, TK_UPDATE, TK_INSERT */ u8 tr_tm; /* One of TRIGGER_BEFORE, TRIGGER_AFTER */ Expr *pWhen; /* The WHEN clause of the expression (may be NULL) */ IdList *pColumns; /* If this is an UPDATE OF trigger, the is stored here */ Schema *pSchema; /* Schema containing the trigger */ Schema *pTabSchema; /* Schema containing the table */ TriggerStep *step_list; /* Link list of trigger program steps */ Trigger *pNext; /* Next trigger associated with the table */ }; /* ** A trigger is either a BEFORE or an AFTER trigger. The following constants ** determine which. ** ** If there are multiple triggers, you might of some BEFORE and some AFTER. ** In that cases, the constants below can be ORed together. */ #define TRIGGER_BEFORE 1 #define TRIGGER_AFTER 2 /* * An instance of struct TriggerStep is used to store a single SQL statement * that is a part of a trigger-program. * * Instances of struct TriggerStep are stored in a singly linked list (linked * using the "pNext" member) referenced by the "step_list" member of the * associated struct Trigger instance. The first element of the linked list is * the first step of the trigger-program. * * The "op" member indicates whether this is a "DELETE", "INSERT", "UPDATE" or * "SELECT" statement. The meanings of the other members is determined by the * value of "op" as follows: * * (op == TK_INSERT) * orconf -> stores the ON CONFLICT algorithm * pSelect -> If this is an INSERT INTO ... SELECT ... statement, then * this stores a pointer to the SELECT statement. Otherwise NULL. * zTarget -> Dequoted name of the table to insert into. * pExprList -> If this is an INSERT INTO ... VALUES ... statement, then * this stores values to be inserted. Otherwise NULL. * pIdList -> If this is an INSERT INTO ... () VALUES ... * statement, then this stores the column-names to be * inserted into. * * (op == TK_DELETE) * zTarget -> Dequoted name of the table to delete from. * pWhere -> The WHERE clause of the DELETE statement if one is specified. * Otherwise NULL. * * (op == TK_UPDATE) * zTarget -> Dequoted name of the table to update. * pWhere -> The WHERE clause of the UPDATE statement if one is specified. * Otherwise NULL. * pExprList -> A list of the columns to update and the expressions to update * them to. See sqlite3Update() documentation of "pChanges" * argument. * */ struct TriggerStep { u8 op; /* One of TK_DELETE, TK_UPDATE, TK_INSERT, TK_SELECT */ u8 orconf; /* OE_Rollback etc. */ Trigger *pTrig; /* The trigger that this step is a part of */ Select *pSelect; /* SELECT statement or RHS of INSERT INTO SELECT ... */ char *zTarget; /* Target table for DELETE, UPDATE, INSERT */ Expr *pWhere; /* The WHERE clause for DELETE or UPDATE steps */ ExprList *pExprList; /* SET clause for UPDATE. */ IdList *pIdList; /* Column names for INSERT */ TriggerStep *pNext; /* Next in the link-list */ TriggerStep *pLast; /* Last element in link-list. Valid for 1st elem only */ }; /* ** The following structure contains information used by the sqliteFix... ** routines as they walk the parse tree to make database references ** explicit. */ typedef struct DbFixer DbFixer; struct DbFixer { Parse *pParse; /* The parsing context. Error messages written here */ Schema *pSchema; /* Fix items to this schema */ int bVarOnly; /* Check for variable references only */ const char *zDb; /* Make sure all objects are contained in this database */ const char *zType; /* Type of the container - used for error messages */ const Token *pName; /* Name of the container - used for error messages */ }; /* ** An objected used to accumulate the text of a string where we ** do not necessarily know how big the string will be in the end. */ struct StrAccum { sqlite3 *db; /* Optional database for lookaside. Can be NULL */ char *zBase; /* A base allocation. Not from malloc. */ char *zText; /* The string collected so far */ u32 nChar; /* Length of the string so far */ u32 nAlloc; /* Amount of space allocated in zText */ u32 mxAlloc; /* Maximum allowed allocation. 0 for no malloc usage */ u8 accError; /* STRACCUM_NOMEM or STRACCUM_TOOBIG */ u8 printfFlags; /* SQLITE_PRINTF flags below */ }; #define STRACCUM_NOMEM 1 #define STRACCUM_TOOBIG 2 #define SQLITE_PRINTF_INTERNAL 0x01 /* Internal-use-only converters allowed */ #define SQLITE_PRINTF_SQLFUNC 0x02 /* SQL function arguments to VXPrintf */ #define SQLITE_PRINTF_MALLOCED 0x04 /* True if xText is allocated space */ #define isMalloced(X) (((X)->printfFlags & SQLITE_PRINTF_MALLOCED)!=0) /* ** A pointer to this structure is used to communicate information ** from sqlite3Init and OP_ParseSchema into the sqlite3InitCallback. */ typedef struct { sqlite3 *db; /* The database being initialized */ char **pzErrMsg; /* Error message stored here */ int iDb; /* 0 for main database. 1 for TEMP, 2.. for ATTACHed */ int rc; /* Result code stored here */ } InitData; /* ** Structure containing global configuration data for the SQLite library. ** ** This structure also contains some state information. */ struct Sqlite3Config { int bMemstat; /* True to enable memory status */ int bCoreMutex; /* True to enable core mutexing */ int bFullMutex; /* True to enable full mutexing */ int bOpenUri; /* True to interpret filenames as URIs */ int bUseCis; /* Use covering indices for full-scans */ int mxStrlen; /* Maximum string length */ int neverCorrupt; /* Database is always well-formed */ int szLookaside; /* Default lookaside buffer size */ int nLookaside; /* Default lookaside buffer count */ int nStmtSpill; /* Stmt-journal spill-to-disk threshold */ sqlite3_mem_methods m; /* Low-level memory allocation interface */ sqlite3_mutex_methods mutex; /* Low-level mutex interface */ sqlite3_pcache_methods2 pcache2; /* Low-level page-cache interface */ void *pHeap; /* Heap storage space */ int nHeap; /* Size of pHeap[] */ int mnReq, mxReq; /* Min and max heap requests sizes */ sqlite3_int64 szMmap; /* mmap() space per open file */ sqlite3_int64 mxMmap; /* Maximum value for szMmap */ void *pScratch; /* Scratch memory */ int szScratch; /* Size of each scratch buffer */ int nScratch; /* Number of scratch buffers */ void *pPage; /* Page cache memory */ int szPage; /* Size of each page in pPage[] */ int nPage; /* Number of pages in pPage[] */ int mxParserStack; /* maximum depth of the parser stack */ int sharedCacheEnabled; /* true if shared-cache mode enabled */ u32 szPma; /* Maximum Sorter PMA size */ /* The above might be initialized to non-zero. The following need to always ** initially be zero, however. */ int isInit; /* True after initialization has finished */ int inProgress; /* True while initialization in progress */ int isMutexInit; /* True after mutexes are initialized */ int isMallocInit; /* True after malloc is initialized */ int isPCacheInit; /* True after malloc is initialized */ int nRefInitMutex; /* Number of users of pInitMutex */ sqlite3_mutex *pInitMutex; /* Mutex used by sqlite3_initialize() */ void (*xLog)(void*,int,const char*); /* Function for logging */ void *pLogArg; /* First argument to xLog() */ #ifdef SQLITE_ENABLE_SQLLOG void(*xSqllog)(void*,sqlite3*,const char*, int); void *pSqllogArg; #endif #ifdef SQLITE_VDBE_COVERAGE /* The following callback (if not NULL) is invoked on every VDBE branch ** operation. Set the callback using SQLITE_TESTCTRL_VDBE_COVERAGE. */ void (*xVdbeBranch)(void*,int iSrcLine,u8 eThis,u8 eMx); /* Callback */ void *pVdbeBranchArg; /* 1st argument */ #endif #ifndef SQLITE_OMIT_BUILTIN_TEST int (*xTestCallback)(int); /* Invoked by sqlite3FaultSim() */ #endif int bLocaltimeFault; /* True to fail localtime() calls */ int iOnceResetThreshold; /* When to reset OP_Once counters */ }; /* ** This macro is used inside of assert() statements to indicate that ** the assert is only valid on a well-formed database. Instead of: ** ** assert( X ); ** ** One writes: ** ** assert( X || CORRUPT_DB ); ** ** CORRUPT_DB is true during normal operation. CORRUPT_DB does not indicate ** that the database is definitely corrupt, only that it might be corrupt. ** For most test cases, CORRUPT_DB is set to false using a special ** sqlite3_test_control(). This enables assert() statements to prove ** things that are always true for well-formed databases. */ #define CORRUPT_DB (sqlite3Config.neverCorrupt==0) /* ** Context pointer passed down through the tree-walk. */ struct Walker { Parse *pParse; /* Parser context. */ int (*xExprCallback)(Walker*, Expr*); /* Callback for expressions */ int (*xSelectCallback)(Walker*,Select*); /* Callback for SELECTs */ void (*xSelectCallback2)(Walker*,Select*);/* Second callback for SELECTs */ int walkerDepth; /* Number of subqueries */ u8 eCode; /* A small processing code */ union { /* Extra data for callback */ NameContext *pNC; /* Naming context */ int n; /* A counter */ int iCur; /* A cursor number */ SrcList *pSrcList; /* FROM clause */ struct SrcCount *pSrcCount; /* Counting column references */ struct CCurHint *pCCurHint; /* Used by codeCursorHint() */ int *aiCol; /* array of column indexes */ struct IdxCover *pIdxCover; /* Check for index coverage */ } u; }; /* Forward declarations */ SQLITE_PRIVATE int sqlite3WalkExpr(Walker*, Expr*); SQLITE_PRIVATE int sqlite3WalkExprList(Walker*, ExprList*); SQLITE_PRIVATE int sqlite3WalkSelect(Walker*, Select*); SQLITE_PRIVATE int sqlite3WalkSelectExpr(Walker*, Select*); SQLITE_PRIVATE int sqlite3WalkSelectFrom(Walker*, Select*); SQLITE_PRIVATE int sqlite3ExprWalkNoop(Walker*, Expr*); /* ** Return code from the parse-tree walking primitives and their ** callbacks. */ #define WRC_Continue 0 /* Continue down into children */ #define WRC_Prune 1 /* Omit children but continue walking siblings */ #define WRC_Abort 2 /* Abandon the tree walk */ /* ** An instance of this structure represents a set of one or more CTEs ** (common table expressions) created by a single WITH clause. */ struct With { int nCte; /* Number of CTEs in the WITH clause */ With *pOuter; /* Containing WITH clause, or NULL */ struct Cte { /* For each CTE in the WITH clause.... */ char *zName; /* Name of this CTE */ ExprList *pCols; /* List of explicit column names, or NULL */ Select *pSelect; /* The definition of this CTE */ const char *zCteErr; /* Error message for circular references */ } a[1]; }; #ifdef SQLITE_DEBUG /* ** An instance of the TreeView object is used for printing the content of ** data structures on sqlite3DebugPrintf() using a tree-like view. */ struct TreeView { int iLevel; /* Which level of the tree we are on */ u8 bLine[100]; /* Draw vertical in column i if bLine[i] is true */ }; #endif /* SQLITE_DEBUG */ /* ** Assuming zIn points to the first byte of a UTF-8 character, ** advance zIn to point to the first byte of the next UTF-8 character. */ #define SQLITE_SKIP_UTF8(zIn) { \ if( (*(zIn++))>=0xc0 ){ \ while( (*zIn & 0xc0)==0x80 ){ zIn++; } \ } \ } /* ** The SQLITE_*_BKPT macros are substitutes for the error codes with ** the same name but without the _BKPT suffix. These macros invoke ** routines that report the line-number on which the error originated ** using sqlite3_log(). The routines also provide a convenient place ** to set a debugger breakpoint. */ SQLITE_PRIVATE int sqlite3CorruptError(int); SQLITE_PRIVATE int sqlite3MisuseError(int); SQLITE_PRIVATE int sqlite3CantopenError(int); #define SQLITE_CORRUPT_BKPT sqlite3CorruptError(__LINE__) #define SQLITE_MISUSE_BKPT sqlite3MisuseError(__LINE__) #define SQLITE_CANTOPEN_BKPT sqlite3CantopenError(__LINE__) #ifdef SQLITE_DEBUG SQLITE_PRIVATE int sqlite3NomemError(int); SQLITE_PRIVATE int sqlite3IoerrnomemError(int); # define SQLITE_NOMEM_BKPT sqlite3NomemError(__LINE__) # define SQLITE_IOERR_NOMEM_BKPT sqlite3IoerrnomemError(__LINE__) #else # define SQLITE_NOMEM_BKPT SQLITE_NOMEM # define SQLITE_IOERR_NOMEM_BKPT SQLITE_IOERR_NOMEM #endif /* ** FTS3 and FTS4 both require virtual table support */ #if defined(SQLITE_OMIT_VIRTUALTABLE) # undef SQLITE_ENABLE_FTS3 # undef SQLITE_ENABLE_FTS4 #endif /* ** FTS4 is really an extension for FTS3. It is enabled using the ** SQLITE_ENABLE_FTS3 macro. But to avoid confusion we also call ** the SQLITE_ENABLE_FTS4 macro to serve as an alias for SQLITE_ENABLE_FTS3. */ #if defined(SQLITE_ENABLE_FTS4) && !defined(SQLITE_ENABLE_FTS3) # define SQLITE_ENABLE_FTS3 1 #endif /* ** The ctype.h header is needed for non-ASCII systems. It is also ** needed by FTS3 when FTS3 is included in the amalgamation. */ #if !defined(SQLITE_ASCII) || \ (defined(SQLITE_ENABLE_FTS3) && defined(SQLITE_AMALGAMATION)) # include #endif /* ** The following macros mimic the standard library functions toupper(), ** isspace(), isalnum(), isdigit() and isxdigit(), respectively. The ** sqlite versions only work for ASCII characters, regardless of locale. */ #ifdef SQLITE_ASCII # define sqlite3Toupper(x) ((x)&~(sqlite3CtypeMap[(unsigned char)(x)]&0x20)) # define sqlite3Isspace(x) (sqlite3CtypeMap[(unsigned char)(x)]&0x01) # define sqlite3Isalnum(x) (sqlite3CtypeMap[(unsigned char)(x)]&0x06) # define sqlite3Isalpha(x) (sqlite3CtypeMap[(unsigned char)(x)]&0x02) # define sqlite3Isdigit(x) (sqlite3CtypeMap[(unsigned char)(x)]&0x04) # define sqlite3Isxdigit(x) (sqlite3CtypeMap[(unsigned char)(x)]&0x08) # define sqlite3Tolower(x) (sqlite3UpperToLower[(unsigned char)(x)]) # define sqlite3Isquote(x) (sqlite3CtypeMap[(unsigned char)(x)]&0x80) #else # define sqlite3Toupper(x) toupper((unsigned char)(x)) # define sqlite3Isspace(x) isspace((unsigned char)(x)) # define sqlite3Isalnum(x) isalnum((unsigned char)(x)) # define sqlite3Isalpha(x) isalpha((unsigned char)(x)) # define sqlite3Isdigit(x) isdigit((unsigned char)(x)) # define sqlite3Isxdigit(x) isxdigit((unsigned char)(x)) # define sqlite3Tolower(x) tolower((unsigned char)(x)) # define sqlite3Isquote(x) ((x)=='"'||(x)=='\''||(x)=='['||(x)=='`') #endif #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS SQLITE_PRIVATE int sqlite3IsIdChar(u8); #endif /* ** Internal function prototypes */ SQLITE_PRIVATE int sqlite3StrICmp(const char*,const char*); SQLITE_PRIVATE int sqlite3Strlen30(const char*); SQLITE_PRIVATE char *sqlite3ColumnType(Column*,char*); #define sqlite3StrNICmp sqlite3_strnicmp SQLITE_PRIVATE int sqlite3MallocInit(void); SQLITE_PRIVATE void sqlite3MallocEnd(void); SQLITE_PRIVATE void *sqlite3Malloc(u64); SQLITE_PRIVATE void *sqlite3MallocZero(u64); SQLITE_PRIVATE void *sqlite3DbMallocZero(sqlite3*, u64); SQLITE_PRIVATE void *sqlite3DbMallocRaw(sqlite3*, u64); SQLITE_PRIVATE void *sqlite3DbMallocRawNN(sqlite3*, u64); SQLITE_PRIVATE char *sqlite3DbStrDup(sqlite3*,const char*); SQLITE_PRIVATE char *sqlite3DbStrNDup(sqlite3*,const char*, u64); SQLITE_PRIVATE void *sqlite3Realloc(void*, u64); SQLITE_PRIVATE void *sqlite3DbReallocOrFree(sqlite3 *, void *, u64); SQLITE_PRIVATE void *sqlite3DbRealloc(sqlite3 *, void *, u64); SQLITE_PRIVATE void sqlite3DbFree(sqlite3*, void*); SQLITE_PRIVATE int sqlite3MallocSize(void*); SQLITE_PRIVATE int sqlite3DbMallocSize(sqlite3*, void*); SQLITE_PRIVATE void *sqlite3ScratchMalloc(int); SQLITE_PRIVATE void sqlite3ScratchFree(void*); SQLITE_PRIVATE void *sqlite3PageMalloc(int); SQLITE_PRIVATE void sqlite3PageFree(void*); SQLITE_PRIVATE void sqlite3MemSetDefault(void); #ifndef SQLITE_OMIT_BUILTIN_TEST SQLITE_PRIVATE void sqlite3BenignMallocHooks(void (*)(void), void (*)(void)); #endif SQLITE_PRIVATE int sqlite3HeapNearlyFull(void); /* ** On systems with ample stack space and that support alloca(), make ** use of alloca() to obtain space for large automatic objects. By default, ** obtain space from malloc(). ** ** The alloca() routine never returns NULL. This will cause code paths ** that deal with sqlite3StackAlloc() failures to be unreachable. */ #ifdef SQLITE_USE_ALLOCA # define sqlite3StackAllocRaw(D,N) alloca(N) # define sqlite3StackAllocZero(D,N) memset(alloca(N), 0, N) # define sqlite3StackFree(D,P) #else # define sqlite3StackAllocRaw(D,N) sqlite3DbMallocRaw(D,N) # define sqlite3StackAllocZero(D,N) sqlite3DbMallocZero(D,N) # define sqlite3StackFree(D,P) sqlite3DbFree(D,P) #endif /* Do not allow both MEMSYS5 and MEMSYS3 to be defined together. If they ** are, disable MEMSYS3 */ #ifdef SQLITE_ENABLE_MEMSYS5 SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys5(void); #undef SQLITE_ENABLE_MEMSYS3 #endif #ifdef SQLITE_ENABLE_MEMSYS3 SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys3(void); #endif #ifndef SQLITE_MUTEX_OMIT SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void); SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3NoopMutex(void); SQLITE_PRIVATE sqlite3_mutex *sqlite3MutexAlloc(int); SQLITE_PRIVATE int sqlite3MutexInit(void); SQLITE_PRIVATE int sqlite3MutexEnd(void); #endif #if !defined(SQLITE_MUTEX_OMIT) && !defined(SQLITE_MUTEX_NOOP) SQLITE_PRIVATE void sqlite3MemoryBarrier(void); #else # define sqlite3MemoryBarrier() #endif SQLITE_PRIVATE sqlite3_int64 sqlite3StatusValue(int); SQLITE_PRIVATE void sqlite3StatusUp(int, int); SQLITE_PRIVATE void sqlite3StatusDown(int, int); SQLITE_PRIVATE void sqlite3StatusHighwater(int, int); /* Access to mutexes used by sqlite3_status() */ SQLITE_PRIVATE sqlite3_mutex *sqlite3Pcache1Mutex(void); SQLITE_PRIVATE sqlite3_mutex *sqlite3MallocMutex(void); #ifndef SQLITE_OMIT_FLOATING_POINT SQLITE_PRIVATE int sqlite3IsNaN(double); #else # define sqlite3IsNaN(X) 0 #endif /* ** An instance of the following structure holds information about SQL ** functions arguments that are the parameters to the printf() function. */ struct PrintfArguments { int nArg; /* Total number of arguments */ int nUsed; /* Number of arguments used so far */ sqlite3_value **apArg; /* The argument values */ }; SQLITE_PRIVATE void sqlite3VXPrintf(StrAccum*, const char*, va_list); SQLITE_PRIVATE void sqlite3XPrintf(StrAccum*, const char*, ...); SQLITE_PRIVATE char *sqlite3MPrintf(sqlite3*,const char*, ...); SQLITE_PRIVATE char *sqlite3VMPrintf(sqlite3*,const char*, va_list); #if defined(SQLITE_DEBUG) || defined(SQLITE_HAVE_OS_TRACE) SQLITE_PRIVATE void sqlite3DebugPrintf(const char*, ...); #endif #if defined(SQLITE_TEST) SQLITE_PRIVATE void *sqlite3TestTextToPtr(const char*); #endif #if defined(SQLITE_DEBUG) SQLITE_PRIVATE void sqlite3TreeViewExpr(TreeView*, const Expr*, u8); SQLITE_PRIVATE void sqlite3TreeViewBareExprList(TreeView*, const ExprList*, const char*); SQLITE_PRIVATE void sqlite3TreeViewExprList(TreeView*, const ExprList*, u8, const char*); SQLITE_PRIVATE void sqlite3TreeViewSelect(TreeView*, const Select*, u8); SQLITE_PRIVATE void sqlite3TreeViewWith(TreeView*, const With*, u8); #endif SQLITE_PRIVATE void sqlite3SetString(char **, sqlite3*, const char*); SQLITE_PRIVATE void sqlite3ErrorMsg(Parse*, const char*, ...); SQLITE_PRIVATE void sqlite3Dequote(char*); SQLITE_PRIVATE void sqlite3TokenInit(Token*,char*); SQLITE_PRIVATE int sqlite3KeywordCode(const unsigned char*, int); SQLITE_PRIVATE int sqlite3RunParser(Parse*, const char*, char **); SQLITE_PRIVATE void sqlite3FinishCoding(Parse*); SQLITE_PRIVATE int sqlite3GetTempReg(Parse*); SQLITE_PRIVATE void sqlite3ReleaseTempReg(Parse*,int); SQLITE_PRIVATE int sqlite3GetTempRange(Parse*,int); SQLITE_PRIVATE void sqlite3ReleaseTempRange(Parse*,int,int); SQLITE_PRIVATE void sqlite3ClearTempRegCache(Parse*); #ifdef SQLITE_DEBUG SQLITE_PRIVATE int sqlite3NoTempsInRange(Parse*,int,int); #endif SQLITE_PRIVATE Expr *sqlite3ExprAlloc(sqlite3*,int,const Token*,int); SQLITE_PRIVATE Expr *sqlite3Expr(sqlite3*,int,const char*); SQLITE_PRIVATE void sqlite3ExprAttachSubtrees(sqlite3*,Expr*,Expr*,Expr*); SQLITE_PRIVATE Expr *sqlite3PExpr(Parse*, int, Expr*, Expr*, const Token*); SQLITE_PRIVATE void sqlite3PExprAddSelect(Parse*, Expr*, Select*); SQLITE_PRIVATE Expr *sqlite3ExprAnd(sqlite3*,Expr*, Expr*); SQLITE_PRIVATE Expr *sqlite3ExprFunction(Parse*,ExprList*, Token*); SQLITE_PRIVATE void sqlite3ExprAssignVarNumber(Parse*, Expr*, u32); SQLITE_PRIVATE void sqlite3ExprDelete(sqlite3*, Expr*); SQLITE_PRIVATE ExprList *sqlite3ExprListAppend(Parse*,ExprList*,Expr*); SQLITE_PRIVATE ExprList *sqlite3ExprListAppendVector(Parse*,ExprList*,IdList*,Expr*); SQLITE_PRIVATE void sqlite3ExprListSetSortOrder(ExprList*,int); SQLITE_PRIVATE void sqlite3ExprListSetName(Parse*,ExprList*,Token*,int); SQLITE_PRIVATE void sqlite3ExprListSetSpan(Parse*,ExprList*,ExprSpan*); SQLITE_PRIVATE void sqlite3ExprListDelete(sqlite3*, ExprList*); SQLITE_PRIVATE u32 sqlite3ExprListFlags(const ExprList*); SQLITE_PRIVATE int sqlite3Init(sqlite3*, char**); SQLITE_PRIVATE int sqlite3InitCallback(void*, int, char**, char**); SQLITE_PRIVATE void sqlite3Pragma(Parse*,Token*,Token*,Token*,int); SQLITE_PRIVATE void sqlite3ResetAllSchemasOfConnection(sqlite3*); SQLITE_PRIVATE void sqlite3ResetOneSchema(sqlite3*,int); SQLITE_PRIVATE void sqlite3CollapseDatabaseArray(sqlite3*); SQLITE_PRIVATE void sqlite3CommitInternalChanges(sqlite3*); SQLITE_PRIVATE void sqlite3DeleteColumnNames(sqlite3*,Table*); SQLITE_PRIVATE int sqlite3ColumnsFromExprList(Parse*,ExprList*,i16*,Column**); SQLITE_PRIVATE void sqlite3SelectAddColumnTypeAndCollation(Parse*,Table*,Select*); SQLITE_PRIVATE Table *sqlite3ResultSetOfSelect(Parse*,Select*); SQLITE_PRIVATE void sqlite3OpenMasterTable(Parse *, int); SQLITE_PRIVATE Index *sqlite3PrimaryKeyIndex(Table*); SQLITE_PRIVATE i16 sqlite3ColumnOfIndex(Index*, i16); SQLITE_PRIVATE void sqlite3StartTable(Parse*,Token*,Token*,int,int,int,int); #if SQLITE_ENABLE_HIDDEN_COLUMNS SQLITE_PRIVATE void sqlite3ColumnPropertiesFromName(Table*, Column*); #else # define sqlite3ColumnPropertiesFromName(T,C) /* no-op */ #endif SQLITE_PRIVATE void sqlite3AddColumn(Parse*,Token*,Token*); SQLITE_PRIVATE void sqlite3AddNotNull(Parse*, int); SQLITE_PRIVATE void sqlite3AddPrimaryKey(Parse*, ExprList*, int, int, int); SQLITE_PRIVATE void sqlite3AddCheckConstraint(Parse*, Expr*); SQLITE_PRIVATE void sqlite3AddDefaultValue(Parse*,ExprSpan*); SQLITE_PRIVATE void sqlite3AddCollateType(Parse*, Token*); SQLITE_PRIVATE void sqlite3EndTable(Parse*,Token*,Token*,u8,Select*); SQLITE_PRIVATE int sqlite3ParseUri(const char*,const char*,unsigned int*, sqlite3_vfs**,char**,char **); SQLITE_PRIVATE Btree *sqlite3DbNameToBtree(sqlite3*,const char*); #ifdef SQLITE_OMIT_BUILTIN_TEST # define sqlite3FaultSim(X) SQLITE_OK #else SQLITE_PRIVATE int sqlite3FaultSim(int); #endif SQLITE_PRIVATE Bitvec *sqlite3BitvecCreate(u32); SQLITE_PRIVATE int sqlite3BitvecTest(Bitvec*, u32); SQLITE_PRIVATE int sqlite3BitvecTestNotNull(Bitvec*, u32); SQLITE_PRIVATE int sqlite3BitvecSet(Bitvec*, u32); SQLITE_PRIVATE void sqlite3BitvecClear(Bitvec*, u32, void*); SQLITE_PRIVATE void sqlite3BitvecDestroy(Bitvec*); SQLITE_PRIVATE u32 sqlite3BitvecSize(Bitvec*); #ifndef SQLITE_OMIT_BUILTIN_TEST SQLITE_PRIVATE int sqlite3BitvecBuiltinTest(int,int*); #endif SQLITE_PRIVATE RowSet *sqlite3RowSetInit(sqlite3*, void*, unsigned int); SQLITE_PRIVATE void sqlite3RowSetClear(RowSet*); SQLITE_PRIVATE void sqlite3RowSetInsert(RowSet*, i64); SQLITE_PRIVATE int sqlite3RowSetTest(RowSet*, int iBatch, i64); SQLITE_PRIVATE int sqlite3RowSetNext(RowSet*, i64*); SQLITE_PRIVATE void sqlite3CreateView(Parse*,Token*,Token*,Token*,ExprList*,Select*,int,int); #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE) SQLITE_PRIVATE int sqlite3ViewGetColumnNames(Parse*,Table*); #else # define sqlite3ViewGetColumnNames(A,B) 0 #endif #if SQLITE_MAX_ATTACHED>30 SQLITE_PRIVATE int sqlite3DbMaskAllZero(yDbMask); #endif SQLITE_PRIVATE void sqlite3DropTable(Parse*, SrcList*, int, int); SQLITE_PRIVATE void sqlite3CodeDropTable(Parse*, Table*, int, int); SQLITE_PRIVATE void sqlite3DeleteTable(sqlite3*, Table*); #ifndef SQLITE_OMIT_AUTOINCREMENT SQLITE_PRIVATE void sqlite3AutoincrementBegin(Parse *pParse); SQLITE_PRIVATE void sqlite3AutoincrementEnd(Parse *pParse); #else # define sqlite3AutoincrementBegin(X) # define sqlite3AutoincrementEnd(X) #endif SQLITE_PRIVATE void sqlite3Insert(Parse*, SrcList*, Select*, IdList*, int); SQLITE_PRIVATE void *sqlite3ArrayAllocate(sqlite3*,void*,int,int*,int*); SQLITE_PRIVATE IdList *sqlite3IdListAppend(sqlite3*, IdList*, Token*); SQLITE_PRIVATE int sqlite3IdListIndex(IdList*,const char*); SQLITE_PRIVATE SrcList *sqlite3SrcListEnlarge(sqlite3*, SrcList*, int, int); SQLITE_PRIVATE SrcList *sqlite3SrcListAppend(sqlite3*, SrcList*, Token*, Token*); SQLITE_PRIVATE SrcList *sqlite3SrcListAppendFromTerm(Parse*, SrcList*, Token*, Token*, Token*, Select*, Expr*, IdList*); SQLITE_PRIVATE void sqlite3SrcListIndexedBy(Parse *, SrcList *, Token *); SQLITE_PRIVATE void sqlite3SrcListFuncArgs(Parse*, SrcList*, ExprList*); SQLITE_PRIVATE int sqlite3IndexedByLookup(Parse *, struct SrcList_item *); SQLITE_PRIVATE void sqlite3SrcListShiftJoinType(SrcList*); SQLITE_PRIVATE void sqlite3SrcListAssignCursors(Parse*, SrcList*); SQLITE_PRIVATE void sqlite3IdListDelete(sqlite3*, IdList*); SQLITE_PRIVATE void sqlite3SrcListDelete(sqlite3*, SrcList*); SQLITE_PRIVATE Index *sqlite3AllocateIndexObject(sqlite3*,i16,int,char**); SQLITE_PRIVATE void sqlite3CreateIndex(Parse*,Token*,Token*,SrcList*,ExprList*,int,Token*, Expr*, int, int, u8); SQLITE_PRIVATE void sqlite3DropIndex(Parse*, SrcList*, int); SQLITE_PRIVATE int sqlite3Select(Parse*, Select*, SelectDest*); SQLITE_PRIVATE Select *sqlite3SelectNew(Parse*,ExprList*,SrcList*,Expr*,ExprList*, Expr*,ExprList*,u32,Expr*,Expr*); SQLITE_PRIVATE void sqlite3SelectDelete(sqlite3*, Select*); SQLITE_PRIVATE Table *sqlite3SrcListLookup(Parse*, SrcList*); SQLITE_PRIVATE int sqlite3IsReadOnly(Parse*, Table*, int); SQLITE_PRIVATE void sqlite3OpenTable(Parse*, int iCur, int iDb, Table*, int); #if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY) SQLITE_PRIVATE Expr *sqlite3LimitWhere(Parse*,SrcList*,Expr*,ExprList*,Expr*,Expr*,char*); #endif SQLITE_PRIVATE void sqlite3DeleteFrom(Parse*, SrcList*, Expr*); SQLITE_PRIVATE void sqlite3Update(Parse*, SrcList*, ExprList*, Expr*, int); SQLITE_PRIVATE WhereInfo *sqlite3WhereBegin(Parse*,SrcList*,Expr*,ExprList*,ExprList*,u16,int); SQLITE_PRIVATE void sqlite3WhereEnd(WhereInfo*); SQLITE_PRIVATE LogEst sqlite3WhereOutputRowCount(WhereInfo*); SQLITE_PRIVATE int sqlite3WhereIsDistinct(WhereInfo*); SQLITE_PRIVATE int sqlite3WhereIsOrdered(WhereInfo*); SQLITE_PRIVATE int sqlite3WhereOrderedInnerLoop(WhereInfo*); SQLITE_PRIVATE int sqlite3WhereIsSorted(WhereInfo*); SQLITE_PRIVATE int sqlite3WhereContinueLabel(WhereInfo*); SQLITE_PRIVATE int sqlite3WhereBreakLabel(WhereInfo*); SQLITE_PRIVATE int sqlite3WhereOkOnePass(WhereInfo*, int*); #define ONEPASS_OFF 0 /* Use of ONEPASS not allowed */ #define ONEPASS_SINGLE 1 /* ONEPASS valid for a single row update */ #define ONEPASS_MULTI 2 /* ONEPASS is valid for multiple rows */ SQLITE_PRIVATE void sqlite3ExprCodeLoadIndexColumn(Parse*, Index*, int, int, int); SQLITE_PRIVATE int sqlite3ExprCodeGetColumn(Parse*, Table*, int, int, int, u8); SQLITE_PRIVATE void sqlite3ExprCodeGetColumnToReg(Parse*, Table*, int, int, int); SQLITE_PRIVATE void sqlite3ExprCodeGetColumnOfTable(Vdbe*, Table*, int, int, int); SQLITE_PRIVATE void sqlite3ExprCodeMove(Parse*, int, int, int); SQLITE_PRIVATE void sqlite3ExprCacheStore(Parse*, int, int, int); SQLITE_PRIVATE void sqlite3ExprCachePush(Parse*); SQLITE_PRIVATE void sqlite3ExprCachePop(Parse*); SQLITE_PRIVATE void sqlite3ExprCacheRemove(Parse*, int, int); SQLITE_PRIVATE void sqlite3ExprCacheClear(Parse*); SQLITE_PRIVATE void sqlite3ExprCacheAffinityChange(Parse*, int, int); SQLITE_PRIVATE void sqlite3ExprCode(Parse*, Expr*, int); SQLITE_PRIVATE void sqlite3ExprCodeCopy(Parse*, Expr*, int); SQLITE_PRIVATE void sqlite3ExprCodeFactorable(Parse*, Expr*, int); SQLITE_PRIVATE void sqlite3ExprCodeAtInit(Parse*, Expr*, int, u8); SQLITE_PRIVATE int sqlite3ExprCodeTemp(Parse*, Expr*, int*); SQLITE_PRIVATE int sqlite3ExprCodeTarget(Parse*, Expr*, int); SQLITE_PRIVATE void sqlite3ExprCodeAndCache(Parse*, Expr*, int); SQLITE_PRIVATE int sqlite3ExprCodeExprList(Parse*, ExprList*, int, int, u8); #define SQLITE_ECEL_DUP 0x01 /* Deep, not shallow copies */ #define SQLITE_ECEL_FACTOR 0x02 /* Factor out constant terms */ #define SQLITE_ECEL_REF 0x04 /* Use ExprList.u.x.iOrderByCol */ SQLITE_PRIVATE void sqlite3ExprIfTrue(Parse*, Expr*, int, int); SQLITE_PRIVATE void sqlite3ExprIfFalse(Parse*, Expr*, int, int); SQLITE_PRIVATE void sqlite3ExprIfFalseDup(Parse*, Expr*, int, int); SQLITE_PRIVATE Table *sqlite3FindTable(sqlite3*,const char*, const char*); #define LOCATE_VIEW 0x01 #define LOCATE_NOERR 0x02 SQLITE_PRIVATE Table *sqlite3LocateTable(Parse*,u32 flags,const char*, const char*); SQLITE_PRIVATE Table *sqlite3LocateTableItem(Parse*,u32 flags,struct SrcList_item *); SQLITE_PRIVATE Index *sqlite3FindIndex(sqlite3*,const char*, const char*); SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTable(sqlite3*,int,const char*); SQLITE_PRIVATE void sqlite3UnlinkAndDeleteIndex(sqlite3*,int,const char*); SQLITE_PRIVATE void sqlite3Vacuum(Parse*,Token*); SQLITE_PRIVATE int sqlite3RunVacuum(char**, sqlite3*, int); SQLITE_PRIVATE char *sqlite3NameFromToken(sqlite3*, Token*); SQLITE_PRIVATE int sqlite3ExprCompare(Expr*, Expr*, int); SQLITE_PRIVATE int sqlite3ExprListCompare(ExprList*, ExprList*, int); SQLITE_PRIVATE int sqlite3ExprImpliesExpr(Expr*, Expr*, int); SQLITE_PRIVATE void sqlite3ExprAnalyzeAggregates(NameContext*, Expr*); SQLITE_PRIVATE void sqlite3ExprAnalyzeAggList(NameContext*,ExprList*); SQLITE_PRIVATE int sqlite3ExprCoveredByIndex(Expr*, int iCur, Index *pIdx); SQLITE_PRIVATE int sqlite3FunctionUsesThisSrc(Expr*, SrcList*); SQLITE_PRIVATE Vdbe *sqlite3GetVdbe(Parse*); #ifndef SQLITE_OMIT_BUILTIN_TEST SQLITE_PRIVATE void sqlite3PrngSaveState(void); SQLITE_PRIVATE void sqlite3PrngRestoreState(void); #endif SQLITE_PRIVATE void sqlite3RollbackAll(sqlite3*,int); SQLITE_PRIVATE void sqlite3CodeVerifySchema(Parse*, int); SQLITE_PRIVATE void sqlite3CodeVerifyNamedSchema(Parse*, const char *zDb); SQLITE_PRIVATE void sqlite3BeginTransaction(Parse*, int); SQLITE_PRIVATE void sqlite3CommitTransaction(Parse*); SQLITE_PRIVATE void sqlite3RollbackTransaction(Parse*); SQLITE_PRIVATE void sqlite3Savepoint(Parse*, int, Token*); SQLITE_PRIVATE void sqlite3CloseSavepoints(sqlite3 *); SQLITE_PRIVATE void sqlite3LeaveMutexAndCloseZombie(sqlite3*); SQLITE_PRIVATE int sqlite3ExprIsConstant(Expr*); SQLITE_PRIVATE int sqlite3ExprIsConstantNotJoin(Expr*); SQLITE_PRIVATE int sqlite3ExprIsConstantOrFunction(Expr*, u8); SQLITE_PRIVATE int sqlite3ExprIsTableConstant(Expr*,int); #ifdef SQLITE_ENABLE_CURSOR_HINTS SQLITE_PRIVATE int sqlite3ExprContainsSubquery(Expr*); #endif SQLITE_PRIVATE int sqlite3ExprIsInteger(Expr*, int*); SQLITE_PRIVATE int sqlite3ExprCanBeNull(const Expr*); SQLITE_PRIVATE int sqlite3ExprNeedsNoAffinityChange(const Expr*, char); SQLITE_PRIVATE int sqlite3IsRowid(const char*); SQLITE_PRIVATE void sqlite3GenerateRowDelete( Parse*,Table*,Trigger*,int,int,int,i16,u8,u8,u8,int); SQLITE_PRIVATE void sqlite3GenerateRowIndexDelete(Parse*, Table*, int, int, int*, int); SQLITE_PRIVATE int sqlite3GenerateIndexKey(Parse*, Index*, int, int, int, int*,Index*,int); SQLITE_PRIVATE void sqlite3ResolvePartIdxLabel(Parse*,int); SQLITE_PRIVATE void sqlite3GenerateConstraintChecks(Parse*,Table*,int*,int,int,int,int, u8,u8,int,int*,int*); SQLITE_PRIVATE void sqlite3CompleteInsertion(Parse*,Table*,int,int,int,int*,int,int,int); SQLITE_PRIVATE int sqlite3OpenTableAndIndices(Parse*, Table*, int, u8, int, u8*, int*, int*); SQLITE_PRIVATE void sqlite3BeginWriteOperation(Parse*, int, int); SQLITE_PRIVATE void sqlite3MultiWrite(Parse*); SQLITE_PRIVATE void sqlite3MayAbort(Parse*); SQLITE_PRIVATE void sqlite3HaltConstraint(Parse*, int, int, char*, i8, u8); SQLITE_PRIVATE void sqlite3UniqueConstraint(Parse*, int, Index*); SQLITE_PRIVATE void sqlite3RowidConstraint(Parse*, int, Table*); SQLITE_PRIVATE Expr *sqlite3ExprDup(sqlite3*,Expr*,int); SQLITE_PRIVATE ExprList *sqlite3ExprListDup(sqlite3*,ExprList*,int); SQLITE_PRIVATE SrcList *sqlite3SrcListDup(sqlite3*,SrcList*,int); SQLITE_PRIVATE IdList *sqlite3IdListDup(sqlite3*,IdList*); SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3*,Select*,int); #if SELECTTRACE_ENABLED SQLITE_PRIVATE void sqlite3SelectSetName(Select*,const char*); #else # define sqlite3SelectSetName(A,B) #endif SQLITE_PRIVATE void sqlite3InsertBuiltinFuncs(FuncDef*,int); SQLITE_PRIVATE FuncDef *sqlite3FindFunction(sqlite3*,const char*,int,u8,u8); SQLITE_PRIVATE void sqlite3RegisterBuiltinFunctions(void); SQLITE_PRIVATE void sqlite3RegisterDateTimeFunctions(void); SQLITE_PRIVATE void sqlite3RegisterPerConnectionBuiltinFunctions(sqlite3*); SQLITE_PRIVATE int sqlite3SafetyCheckOk(sqlite3*); SQLITE_PRIVATE int sqlite3SafetyCheckSickOrOk(sqlite3*); SQLITE_PRIVATE void sqlite3ChangeCookie(Parse*, int); #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER) SQLITE_PRIVATE void sqlite3MaterializeView(Parse*, Table*, Expr*, int); #endif #ifndef SQLITE_OMIT_TRIGGER SQLITE_PRIVATE void sqlite3BeginTrigger(Parse*, Token*,Token*,int,int,IdList*,SrcList*, Expr*,int, int); SQLITE_PRIVATE void sqlite3FinishTrigger(Parse*, TriggerStep*, Token*); SQLITE_PRIVATE void sqlite3DropTrigger(Parse*, SrcList*, int); SQLITE_PRIVATE void sqlite3DropTriggerPtr(Parse*, Trigger*); SQLITE_PRIVATE Trigger *sqlite3TriggersExist(Parse *, Table*, int, ExprList*, int *pMask); SQLITE_PRIVATE Trigger *sqlite3TriggerList(Parse *, Table *); SQLITE_PRIVATE void sqlite3CodeRowTrigger(Parse*, Trigger *, int, ExprList*, int, Table *, int, int, int); SQLITE_PRIVATE void sqlite3CodeRowTriggerDirect(Parse *, Trigger *, Table *, int, int, int); void sqliteViewTriggers(Parse*, Table*, Expr*, int, ExprList*); SQLITE_PRIVATE void sqlite3DeleteTriggerStep(sqlite3*, TriggerStep*); SQLITE_PRIVATE TriggerStep *sqlite3TriggerSelectStep(sqlite3*,Select*); SQLITE_PRIVATE TriggerStep *sqlite3TriggerInsertStep(sqlite3*,Token*, IdList*, Select*,u8); SQLITE_PRIVATE TriggerStep *sqlite3TriggerUpdateStep(sqlite3*,Token*,ExprList*, Expr*, u8); SQLITE_PRIVATE TriggerStep *sqlite3TriggerDeleteStep(sqlite3*,Token*, Expr*); SQLITE_PRIVATE void sqlite3DeleteTrigger(sqlite3*, Trigger*); SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTrigger(sqlite3*,int,const char*); SQLITE_PRIVATE u32 sqlite3TriggerColmask(Parse*,Trigger*,ExprList*,int,int,Table*,int); # define sqlite3ParseToplevel(p) ((p)->pToplevel ? (p)->pToplevel : (p)) # define sqlite3IsToplevel(p) ((p)->pToplevel==0) #else # define sqlite3TriggersExist(B,C,D,E,F) 0 # define sqlite3DeleteTrigger(A,B) # define sqlite3DropTriggerPtr(A,B) # define sqlite3UnlinkAndDeleteTrigger(A,B,C) # define sqlite3CodeRowTrigger(A,B,C,D,E,F,G,H,I) # define sqlite3CodeRowTriggerDirect(A,B,C,D,E,F) # define sqlite3TriggerList(X, Y) 0 # define sqlite3ParseToplevel(p) p # define sqlite3IsToplevel(p) 1 # define sqlite3TriggerColmask(A,B,C,D,E,F,G) 0 #endif SQLITE_PRIVATE int sqlite3JoinType(Parse*, Token*, Token*, Token*); SQLITE_PRIVATE void sqlite3CreateForeignKey(Parse*, ExprList*, Token*, ExprList*, int); SQLITE_PRIVATE void sqlite3DeferForeignKey(Parse*, int); #ifndef SQLITE_OMIT_AUTHORIZATION SQLITE_PRIVATE void sqlite3AuthRead(Parse*,Expr*,Schema*,SrcList*); SQLITE_PRIVATE int sqlite3AuthCheck(Parse*,int, const char*, const char*, const char*); SQLITE_PRIVATE void sqlite3AuthContextPush(Parse*, AuthContext*, const char*); SQLITE_PRIVATE void sqlite3AuthContextPop(AuthContext*); SQLITE_PRIVATE int sqlite3AuthReadCol(Parse*, const char *, const char *, int); #else # define sqlite3AuthRead(a,b,c,d) # define sqlite3AuthCheck(a,b,c,d,e) SQLITE_OK # define sqlite3AuthContextPush(a,b,c) # define sqlite3AuthContextPop(a) ((void)(a)) #endif SQLITE_PRIVATE void sqlite3Attach(Parse*, Expr*, Expr*, Expr*); SQLITE_PRIVATE void sqlite3Detach(Parse*, Expr*); SQLITE_PRIVATE void sqlite3FixInit(DbFixer*, Parse*, int, const char*, const Token*); SQLITE_PRIVATE int sqlite3FixSrcList(DbFixer*, SrcList*); SQLITE_PRIVATE int sqlite3FixSelect(DbFixer*, Select*); SQLITE_PRIVATE int sqlite3FixExpr(DbFixer*, Expr*); SQLITE_PRIVATE int sqlite3FixExprList(DbFixer*, ExprList*); SQLITE_PRIVATE int sqlite3FixTriggerStep(DbFixer*, TriggerStep*); SQLITE_PRIVATE int sqlite3AtoF(const char *z, double*, int, u8); SQLITE_PRIVATE int sqlite3GetInt32(const char *, int*); SQLITE_PRIVATE int sqlite3Atoi(const char*); SQLITE_PRIVATE int sqlite3Utf16ByteLen(const void *pData, int nChar); SQLITE_PRIVATE int sqlite3Utf8CharLen(const char *pData, int nByte); SQLITE_PRIVATE u32 sqlite3Utf8Read(const u8**); SQLITE_PRIVATE LogEst sqlite3LogEst(u64); SQLITE_PRIVATE LogEst sqlite3LogEstAdd(LogEst,LogEst); #ifndef SQLITE_OMIT_VIRTUALTABLE SQLITE_PRIVATE LogEst sqlite3LogEstFromDouble(double); #endif #if defined(SQLITE_ENABLE_STMT_SCANSTATUS) || \ defined(SQLITE_ENABLE_STAT3_OR_STAT4) || \ defined(SQLITE_EXPLAIN_ESTIMATED_ROWS) SQLITE_PRIVATE u64 sqlite3LogEstToInt(LogEst); #endif /* ** Routines to read and write variable-length integers. These used to ** be defined locally, but now we use the varint routines in the util.c ** file. */ SQLITE_PRIVATE int sqlite3PutVarint(unsigned char*, u64); SQLITE_PRIVATE u8 sqlite3GetVarint(const unsigned char *, u64 *); SQLITE_PRIVATE u8 sqlite3GetVarint32(const unsigned char *, u32 *); SQLITE_PRIVATE int sqlite3VarintLen(u64 v); /* ** The common case is for a varint to be a single byte. They following ** macros handle the common case without a procedure call, but then call ** the procedure for larger varints. */ #define getVarint32(A,B) \ (u8)((*(A)<(u8)0x80)?((B)=(u32)*(A)),1:sqlite3GetVarint32((A),(u32 *)&(B))) #define putVarint32(A,B) \ (u8)(((u32)(B)<(u32)0x80)?(*(A)=(unsigned char)(B)),1:\ sqlite3PutVarint((A),(B))) #define getVarint sqlite3GetVarint #define putVarint sqlite3PutVarint SQLITE_PRIVATE const char *sqlite3IndexAffinityStr(sqlite3*, Index*); SQLITE_PRIVATE void sqlite3TableAffinity(Vdbe*, Table*, int); SQLITE_PRIVATE char sqlite3CompareAffinity(Expr *pExpr, char aff2); SQLITE_PRIVATE int sqlite3IndexAffinityOk(Expr *pExpr, char idx_affinity); SQLITE_PRIVATE char sqlite3TableColumnAffinity(Table*,int); SQLITE_PRIVATE char sqlite3ExprAffinity(Expr *pExpr); SQLITE_PRIVATE int sqlite3Atoi64(const char*, i64*, int, u8); SQLITE_PRIVATE int sqlite3DecOrHexToI64(const char*, i64*); SQLITE_PRIVATE void sqlite3ErrorWithMsg(sqlite3*, int, const char*,...); SQLITE_PRIVATE void sqlite3Error(sqlite3*,int); SQLITE_PRIVATE void sqlite3SystemError(sqlite3*,int); SQLITE_PRIVATE void *sqlite3HexToBlob(sqlite3*, const char *z, int n); SQLITE_PRIVATE u8 sqlite3HexToInt(int h); SQLITE_PRIVATE int sqlite3TwoPartName(Parse *, Token *, Token *, Token **); #if defined(SQLITE_NEED_ERR_NAME) SQLITE_PRIVATE const char *sqlite3ErrName(int); #endif SQLITE_PRIVATE const char *sqlite3ErrStr(int); SQLITE_PRIVATE int sqlite3ReadSchema(Parse *pParse); SQLITE_PRIVATE CollSeq *sqlite3FindCollSeq(sqlite3*,u8 enc, const char*,int); SQLITE_PRIVATE CollSeq *sqlite3LocateCollSeq(Parse *pParse, const char*zName); SQLITE_PRIVATE CollSeq *sqlite3ExprCollSeq(Parse *pParse, Expr *pExpr); SQLITE_PRIVATE Expr *sqlite3ExprAddCollateToken(Parse *pParse, Expr*, const Token*, int); SQLITE_PRIVATE Expr *sqlite3ExprAddCollateString(Parse*,Expr*,const char*); SQLITE_PRIVATE Expr *sqlite3ExprSkipCollate(Expr*); SQLITE_PRIVATE int sqlite3CheckCollSeq(Parse *, CollSeq *); SQLITE_PRIVATE int sqlite3CheckObjectName(Parse *, const char *); SQLITE_PRIVATE void sqlite3VdbeSetChanges(sqlite3 *, int); SQLITE_PRIVATE int sqlite3AddInt64(i64*,i64); SQLITE_PRIVATE int sqlite3SubInt64(i64*,i64); SQLITE_PRIVATE int sqlite3MulInt64(i64*,i64); SQLITE_PRIVATE int sqlite3AbsInt32(int); #ifdef SQLITE_ENABLE_8_3_NAMES SQLITE_PRIVATE void sqlite3FileSuffix3(const char*, char*); #else # define sqlite3FileSuffix3(X,Y) #endif SQLITE_PRIVATE u8 sqlite3GetBoolean(const char *z,u8); SQLITE_PRIVATE const void *sqlite3ValueText(sqlite3_value*, u8); SQLITE_PRIVATE int sqlite3ValueBytes(sqlite3_value*, u8); SQLITE_PRIVATE void sqlite3ValueSetStr(sqlite3_value*, int, const void *,u8, void(*)(void*)); SQLITE_PRIVATE void sqlite3ValueSetNull(sqlite3_value*); SQLITE_PRIVATE void sqlite3ValueFree(sqlite3_value*); SQLITE_PRIVATE sqlite3_value *sqlite3ValueNew(sqlite3 *); SQLITE_PRIVATE char *sqlite3Utf16to8(sqlite3 *, const void*, int, u8); SQLITE_PRIVATE int sqlite3ValueFromExpr(sqlite3 *, Expr *, u8, u8, sqlite3_value **); SQLITE_PRIVATE void sqlite3ValueApplyAffinity(sqlite3_value *, u8, u8); #ifndef SQLITE_AMALGAMATION SQLITE_PRIVATE const unsigned char sqlite3OpcodeProperty[]; SQLITE_PRIVATE const char sqlite3StrBINARY[]; SQLITE_PRIVATE const unsigned char sqlite3UpperToLower[]; SQLITE_PRIVATE const unsigned char sqlite3CtypeMap[]; SQLITE_PRIVATE const Token sqlite3IntTokens[]; SQLITE_PRIVATE SQLITE_WSD struct Sqlite3Config sqlite3Config; SQLITE_PRIVATE FuncDefHash sqlite3BuiltinFunctions; #ifndef SQLITE_OMIT_WSD SQLITE_PRIVATE int sqlite3PendingByte; #endif #endif SQLITE_PRIVATE void sqlite3RootPageMoved(sqlite3*, int, int, int); SQLITE_PRIVATE void sqlite3Reindex(Parse*, Token*, Token*); SQLITE_PRIVATE void sqlite3AlterFunctions(void); SQLITE_PRIVATE void sqlite3AlterRenameTable(Parse*, SrcList*, Token*); SQLITE_PRIVATE int sqlite3GetToken(const unsigned char *, int *); SQLITE_PRIVATE void sqlite3NestedParse(Parse*, const char*, ...); SQLITE_PRIVATE void sqlite3ExpirePreparedStatements(sqlite3*); SQLITE_PRIVATE int sqlite3CodeSubselect(Parse*, Expr *, int, int); SQLITE_PRIVATE void sqlite3SelectPrep(Parse*, Select*, NameContext*); SQLITE_PRIVATE void sqlite3SelectWrongNumTermsError(Parse *pParse, Select *p); SQLITE_PRIVATE int sqlite3MatchSpanName(const char*, const char*, const char*, const char*); SQLITE_PRIVATE int sqlite3ResolveExprNames(NameContext*, Expr*); SQLITE_PRIVATE int sqlite3ResolveExprListNames(NameContext*, ExprList*); SQLITE_PRIVATE void sqlite3ResolveSelectNames(Parse*, Select*, NameContext*); SQLITE_PRIVATE void sqlite3ResolveSelfReference(Parse*,Table*,int,Expr*,ExprList*); SQLITE_PRIVATE int sqlite3ResolveOrderGroupBy(Parse*, Select*, ExprList*, const char*); SQLITE_PRIVATE void sqlite3ColumnDefault(Vdbe *, Table *, int, int); SQLITE_PRIVATE void sqlite3AlterFinishAddColumn(Parse *, Token *); SQLITE_PRIVATE void sqlite3AlterBeginAddColumn(Parse *, SrcList *); SQLITE_PRIVATE CollSeq *sqlite3GetCollSeq(Parse*, u8, CollSeq *, const char*); SQLITE_PRIVATE char sqlite3AffinityType(const char*, u8*); SQLITE_PRIVATE void sqlite3Analyze(Parse*, Token*, Token*); SQLITE_PRIVATE int sqlite3InvokeBusyHandler(BusyHandler*); SQLITE_PRIVATE int sqlite3FindDb(sqlite3*, Token*); SQLITE_PRIVATE int sqlite3FindDbName(sqlite3 *, const char *); SQLITE_PRIVATE int sqlite3AnalysisLoad(sqlite3*,int iDB); SQLITE_PRIVATE void sqlite3DeleteIndexSamples(sqlite3*,Index*); SQLITE_PRIVATE void sqlite3DefaultRowEst(Index*); SQLITE_PRIVATE void sqlite3RegisterLikeFunctions(sqlite3*, int); SQLITE_PRIVATE int sqlite3IsLikeFunction(sqlite3*,Expr*,int*,char*); SQLITE_PRIVATE void sqlite3SchemaClear(void *); SQLITE_PRIVATE Schema *sqlite3SchemaGet(sqlite3 *, Btree *); SQLITE_PRIVATE int sqlite3SchemaToIndex(sqlite3 *db, Schema *); SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoAlloc(sqlite3*,int,int); SQLITE_PRIVATE void sqlite3KeyInfoUnref(KeyInfo*); SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoRef(KeyInfo*); SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoOfIndex(Parse*, Index*); #ifdef SQLITE_DEBUG SQLITE_PRIVATE int sqlite3KeyInfoIsWriteable(KeyInfo*); #endif SQLITE_PRIVATE int sqlite3CreateFunc(sqlite3 *, const char *, int, int, void *, void (*)(sqlite3_context*,int,sqlite3_value **), void (*)(sqlite3_context*,int,sqlite3_value **), void (*)(sqlite3_context*), FuncDestructor *pDestructor ); SQLITE_PRIVATE void sqlite3OomFault(sqlite3*); SQLITE_PRIVATE void sqlite3OomClear(sqlite3*); SQLITE_PRIVATE int sqlite3ApiExit(sqlite3 *db, int); SQLITE_PRIVATE int sqlite3OpenTempDatabase(Parse *); SQLITE_PRIVATE void sqlite3StrAccumInit(StrAccum*, sqlite3*, char*, int, int); SQLITE_PRIVATE void sqlite3StrAccumAppend(StrAccum*,const char*,int); SQLITE_PRIVATE void sqlite3StrAccumAppendAll(StrAccum*,const char*); SQLITE_PRIVATE void sqlite3AppendChar(StrAccum*,int,char); SQLITE_PRIVATE char *sqlite3StrAccumFinish(StrAccum*); SQLITE_PRIVATE void sqlite3StrAccumReset(StrAccum*); SQLITE_PRIVATE void sqlite3SelectDestInit(SelectDest*,int,int); SQLITE_PRIVATE Expr *sqlite3CreateColumnExpr(sqlite3 *, SrcList *, int, int); SQLITE_PRIVATE void sqlite3BackupRestart(sqlite3_backup *); SQLITE_PRIVATE void sqlite3BackupUpdate(sqlite3_backup *, Pgno, const u8 *); #ifndef SQLITE_OMIT_SUBQUERY SQLITE_PRIVATE int sqlite3ExprCheckIN(Parse*, Expr*); #else # define sqlite3ExprCheckIN(x,y) SQLITE_OK #endif #ifdef SQLITE_ENABLE_STAT3_OR_STAT4 SQLITE_PRIVATE void sqlite3AnalyzeFunctions(void); SQLITE_PRIVATE int sqlite3Stat4ProbeSetValue( Parse*,Index*,UnpackedRecord**,Expr*,int,int,int*); SQLITE_PRIVATE int sqlite3Stat4ValueFromExpr(Parse*, Expr*, u8, sqlite3_value**); SQLITE_PRIVATE void sqlite3Stat4ProbeFree(UnpackedRecord*); SQLITE_PRIVATE int sqlite3Stat4Column(sqlite3*, const void*, int, int, sqlite3_value**); SQLITE_PRIVATE char sqlite3IndexColumnAffinity(sqlite3*, Index*, int); #endif /* ** The interface to the LEMON-generated parser */ SQLITE_PRIVATE void *sqlite3ParserAlloc(void*(*)(u64)); SQLITE_PRIVATE void sqlite3ParserFree(void*, void(*)(void*)); SQLITE_PRIVATE void sqlite3Parser(void*, int, Token, Parse*); #ifdef YYTRACKMAXSTACKDEPTH SQLITE_PRIVATE int sqlite3ParserStackPeak(void*); #endif SQLITE_PRIVATE void sqlite3AutoLoadExtensions(sqlite3*); #ifndef SQLITE_OMIT_LOAD_EXTENSION SQLITE_PRIVATE void sqlite3CloseExtensions(sqlite3*); #else # define sqlite3CloseExtensions(X) #endif #ifndef SQLITE_OMIT_SHARED_CACHE SQLITE_PRIVATE void sqlite3TableLock(Parse *, int, int, u8, const char *); #else #define sqlite3TableLock(v,w,x,y,z) #endif #ifdef SQLITE_TEST SQLITE_PRIVATE int sqlite3Utf8To8(unsigned char*); #endif #ifdef SQLITE_OMIT_VIRTUALTABLE # define sqlite3VtabClear(Y) # define sqlite3VtabSync(X,Y) SQLITE_OK # define sqlite3VtabRollback(X) # define sqlite3VtabCommit(X) # define sqlite3VtabInSync(db) 0 # define sqlite3VtabLock(X) # define sqlite3VtabUnlock(X) # define sqlite3VtabUnlockList(X) # define sqlite3VtabSavepoint(X, Y, Z) SQLITE_OK # define sqlite3GetVTable(X,Y) ((VTable*)0) #else SQLITE_PRIVATE void sqlite3VtabClear(sqlite3 *db, Table*); SQLITE_PRIVATE void sqlite3VtabDisconnect(sqlite3 *db, Table *p); SQLITE_PRIVATE int sqlite3VtabSync(sqlite3 *db, Vdbe*); SQLITE_PRIVATE int sqlite3VtabRollback(sqlite3 *db); SQLITE_PRIVATE int sqlite3VtabCommit(sqlite3 *db); SQLITE_PRIVATE void sqlite3VtabLock(VTable *); SQLITE_PRIVATE void sqlite3VtabUnlock(VTable *); SQLITE_PRIVATE void sqlite3VtabUnlockList(sqlite3*); SQLITE_PRIVATE int sqlite3VtabSavepoint(sqlite3 *, int, int); SQLITE_PRIVATE void sqlite3VtabImportErrmsg(Vdbe*, sqlite3_vtab*); SQLITE_PRIVATE VTable *sqlite3GetVTable(sqlite3*, Table*); # define sqlite3VtabInSync(db) ((db)->nVTrans>0 && (db)->aVTrans==0) #endif SQLITE_PRIVATE int sqlite3VtabEponymousTableInit(Parse*,Module*); SQLITE_PRIVATE void sqlite3VtabEponymousTableClear(sqlite3*,Module*); SQLITE_PRIVATE void sqlite3VtabMakeWritable(Parse*,Table*); SQLITE_PRIVATE void sqlite3VtabBeginParse(Parse*, Token*, Token*, Token*, int); SQLITE_PRIVATE void sqlite3VtabFinishParse(Parse*, Token*); SQLITE_PRIVATE void sqlite3VtabArgInit(Parse*); SQLITE_PRIVATE void sqlite3VtabArgExtend(Parse*, Token*); SQLITE_PRIVATE int sqlite3VtabCallCreate(sqlite3*, int, const char *, char **); SQLITE_PRIVATE int sqlite3VtabCallConnect(Parse*, Table*); SQLITE_PRIVATE int sqlite3VtabCallDestroy(sqlite3*, int, const char *); SQLITE_PRIVATE int sqlite3VtabBegin(sqlite3 *, VTable *); SQLITE_PRIVATE FuncDef *sqlite3VtabOverloadFunction(sqlite3 *,FuncDef*, int nArg, Expr*); SQLITE_PRIVATE void sqlite3InvalidFunction(sqlite3_context*,int,sqlite3_value**); SQLITE_PRIVATE sqlite3_int64 sqlite3StmtCurrentTime(sqlite3_context*); SQLITE_PRIVATE int sqlite3VdbeParameterIndex(Vdbe*, const char*, int); SQLITE_PRIVATE int sqlite3TransferBindings(sqlite3_stmt *, sqlite3_stmt *); SQLITE_PRIVATE void sqlite3ParserReset(Parse*); SQLITE_PRIVATE int sqlite3Reprepare(Vdbe*); SQLITE_PRIVATE void sqlite3ExprListCheckLength(Parse*, ExprList*, const char*); SQLITE_PRIVATE CollSeq *sqlite3BinaryCompareCollSeq(Parse *, Expr *, Expr *); SQLITE_PRIVATE int sqlite3TempInMemory(const sqlite3*); SQLITE_PRIVATE const char *sqlite3JournalModename(int); #ifndef SQLITE_OMIT_WAL SQLITE_PRIVATE int sqlite3Checkpoint(sqlite3*, int, int, int*, int*); SQLITE_PRIVATE int sqlite3WalDefaultHook(void*,sqlite3*,const char*,int); #endif #ifndef SQLITE_OMIT_CTE SQLITE_PRIVATE With *sqlite3WithAdd(Parse*,With*,Token*,ExprList*,Select*); SQLITE_PRIVATE void sqlite3WithDelete(sqlite3*,With*); SQLITE_PRIVATE void sqlite3WithPush(Parse*, With*, u8); #else #define sqlite3WithPush(x,y,z) #define sqlite3WithDelete(x,y) #endif /* Declarations for functions in fkey.c. All of these are replaced by ** no-op macros if OMIT_FOREIGN_KEY is defined. In this case no foreign ** key functionality is available. If OMIT_TRIGGER is defined but ** OMIT_FOREIGN_KEY is not, only some of the functions are no-oped. In ** this case foreign keys are parsed, but no other functionality is ** provided (enforcement of FK constraints requires the triggers sub-system). */ #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER) SQLITE_PRIVATE void sqlite3FkCheck(Parse*, Table*, int, int, int*, int); SQLITE_PRIVATE void sqlite3FkDropTable(Parse*, SrcList *, Table*); SQLITE_PRIVATE void sqlite3FkActions(Parse*, Table*, ExprList*, int, int*, int); SQLITE_PRIVATE int sqlite3FkRequired(Parse*, Table*, int*, int); SQLITE_PRIVATE u32 sqlite3FkOldmask(Parse*, Table*); SQLITE_PRIVATE FKey *sqlite3FkReferences(Table *); #else #define sqlite3FkActions(a,b,c,d,e,f) #define sqlite3FkCheck(a,b,c,d,e,f) #define sqlite3FkDropTable(a,b,c) #define sqlite3FkOldmask(a,b) 0 #define sqlite3FkRequired(a,b,c,d) 0 #endif #ifndef SQLITE_OMIT_FOREIGN_KEY SQLITE_PRIVATE void sqlite3FkDelete(sqlite3 *, Table*); SQLITE_PRIVATE int sqlite3FkLocateIndex(Parse*,Table*,FKey*,Index**,int**); #else #define sqlite3FkDelete(a,b) #define sqlite3FkLocateIndex(a,b,c,d,e) #endif /* ** Available fault injectors. Should be numbered beginning with 0. */ #define SQLITE_FAULTINJECTOR_MALLOC 0 #define SQLITE_FAULTINJECTOR_COUNT 1 /* ** The interface to the code in fault.c used for identifying "benign" ** malloc failures. This is only present if SQLITE_OMIT_BUILTIN_TEST ** is not defined. */ #ifndef SQLITE_OMIT_BUILTIN_TEST SQLITE_PRIVATE void sqlite3BeginBenignMalloc(void); SQLITE_PRIVATE void sqlite3EndBenignMalloc(void); #else #define sqlite3BeginBenignMalloc() #define sqlite3EndBenignMalloc() #endif /* ** Allowed return values from sqlite3FindInIndex() */ #define IN_INDEX_ROWID 1 /* Search the rowid of the table */ #define IN_INDEX_EPH 2 /* Search an ephemeral b-tree */ #define IN_INDEX_INDEX_ASC 3 /* Existing index ASCENDING */ #define IN_INDEX_INDEX_DESC 4 /* Existing index DESCENDING */ #define IN_INDEX_NOOP 5 /* No table available. Use comparisons */ /* ** Allowed flags for the 3rd parameter to sqlite3FindInIndex(). */ #define IN_INDEX_NOOP_OK 0x0001 /* OK to return IN_INDEX_NOOP */ #define IN_INDEX_MEMBERSHIP 0x0002 /* IN operator used for membership test */ #define IN_INDEX_LOOP 0x0004 /* IN operator used as a loop */ SQLITE_PRIVATE int sqlite3FindInIndex(Parse *, Expr *, u32, int*, int*); SQLITE_PRIVATE int sqlite3JournalOpen(sqlite3_vfs *, const char *, sqlite3_file *, int, int); SQLITE_PRIVATE int sqlite3JournalSize(sqlite3_vfs *); #ifdef SQLITE_ENABLE_ATOMIC_WRITE SQLITE_PRIVATE int sqlite3JournalCreate(sqlite3_file *); #endif SQLITE_PRIVATE int sqlite3JournalIsInMemory(sqlite3_file *p); SQLITE_PRIVATE void sqlite3MemJournalOpen(sqlite3_file *); SQLITE_PRIVATE void sqlite3ExprSetHeightAndFlags(Parse *pParse, Expr *p); #if SQLITE_MAX_EXPR_DEPTH>0 SQLITE_PRIVATE int sqlite3SelectExprHeight(Select *); SQLITE_PRIVATE int sqlite3ExprCheckHeight(Parse*, int); #else #define sqlite3SelectExprHeight(x) 0 #define sqlite3ExprCheckHeight(x,y) #endif SQLITE_PRIVATE u32 sqlite3Get4byte(const u8*); SQLITE_PRIVATE void sqlite3Put4byte(u8*, u32); #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY SQLITE_PRIVATE void sqlite3ConnectionBlocked(sqlite3 *, sqlite3 *); SQLITE_PRIVATE void sqlite3ConnectionUnlocked(sqlite3 *db); SQLITE_PRIVATE void sqlite3ConnectionClosed(sqlite3 *db); #else #define sqlite3ConnectionBlocked(x,y) #define sqlite3ConnectionUnlocked(x) #define sqlite3ConnectionClosed(x) #endif #ifdef SQLITE_DEBUG SQLITE_PRIVATE void sqlite3ParserTrace(FILE*, char *); #endif /* ** If the SQLITE_ENABLE IOTRACE exists then the global variable ** sqlite3IoTrace is a pointer to a printf-like routine used to ** print I/O tracing messages. */ #ifdef SQLITE_ENABLE_IOTRACE # define IOTRACE(A) if( sqlite3IoTrace ){ sqlite3IoTrace A; } SQLITE_PRIVATE void sqlite3VdbeIOTraceSql(Vdbe*); SQLITE_API SQLITE_EXTERN void (SQLITE_CDECL *sqlite3IoTrace)(const char*,...); #else # define IOTRACE(A) # define sqlite3VdbeIOTraceSql(X) #endif /* ** These routines are available for the mem2.c debugging memory allocator ** only. They are used to verify that different "types" of memory ** allocations are properly tracked by the system. ** ** sqlite3MemdebugSetType() sets the "type" of an allocation to one of ** the MEMTYPE_* macros defined below. The type must be a bitmask with ** a single bit set. ** ** sqlite3MemdebugHasType() returns true if any of the bits in its second ** argument match the type set by the previous sqlite3MemdebugSetType(). ** sqlite3MemdebugHasType() is intended for use inside assert() statements. ** ** sqlite3MemdebugNoType() returns true if none of the bits in its second ** argument match the type set by the previous sqlite3MemdebugSetType(). ** ** Perhaps the most important point is the difference between MEMTYPE_HEAP ** and MEMTYPE_LOOKASIDE. If an allocation is MEMTYPE_LOOKASIDE, that means ** it might have been allocated by lookaside, except the allocation was ** too large or lookaside was already full. It is important to verify ** that allocations that might have been satisfied by lookaside are not ** passed back to non-lookaside free() routines. Asserts such as the ** example above are placed on the non-lookaside free() routines to verify ** this constraint. ** ** All of this is no-op for a production build. It only comes into ** play when the SQLITE_MEMDEBUG compile-time option is used. */ #ifdef SQLITE_MEMDEBUG SQLITE_PRIVATE void sqlite3MemdebugSetType(void*,u8); SQLITE_PRIVATE int sqlite3MemdebugHasType(void*,u8); SQLITE_PRIVATE int sqlite3MemdebugNoType(void*,u8); #else # define sqlite3MemdebugSetType(X,Y) /* no-op */ # define sqlite3MemdebugHasType(X,Y) 1 # define sqlite3MemdebugNoType(X,Y) 1 #endif #define MEMTYPE_HEAP 0x01 /* General heap allocations */ #define MEMTYPE_LOOKASIDE 0x02 /* Heap that might have been lookaside */ #define MEMTYPE_SCRATCH 0x04 /* Scratch allocations */ #define MEMTYPE_PCACHE 0x08 /* Page cache allocations */ /* ** Threading interface */ #if SQLITE_MAX_WORKER_THREADS>0 SQLITE_PRIVATE int sqlite3ThreadCreate(SQLiteThread**,void*(*)(void*),void*); SQLITE_PRIVATE int sqlite3ThreadJoin(SQLiteThread*, void**); #endif #if defined(SQLITE_ENABLE_DBSTAT_VTAB) || defined(SQLITE_TEST) SQLITE_PRIVATE int sqlite3DbstatRegister(sqlite3*); #endif SQLITE_PRIVATE int sqlite3ExprVectorSize(Expr *pExpr); SQLITE_PRIVATE int sqlite3ExprIsVector(Expr *pExpr); SQLITE_PRIVATE Expr *sqlite3VectorFieldSubexpr(Expr*, int); SQLITE_PRIVATE Expr *sqlite3ExprForVectorField(Parse*,Expr*,int); #endif /* SQLITEINT_H */ /************** End of sqliteInt.h *******************************************/ /************** Begin file global.c ******************************************/ /* ** 2008 June 13 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ************************************************************************* ** ** This file contains definitions of global variables and constants. */ /* #include "sqliteInt.h" */ /* An array to map all upper-case characters into their corresponding ** lower-case character. ** ** SQLite only considers US-ASCII (or EBCDIC) characters. We do not ** handle case conversions for the UTF character set since the tables ** involved are nearly as big or bigger than SQLite itself. */ SQLITE_PRIVATE const unsigned char sqlite3UpperToLower[] = { #ifdef SQLITE_ASCII 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 97, 98, 99,100,101,102,103, 104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120,121, 122, 91, 92, 93, 94, 95, 96, 97, 98, 99,100,101,102,103,104,105,106,107, 108,109,110,111,112,113,114,115,116,117,118,119,120,121,122,123,124,125, 126,127,128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143, 144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,160,161, 162,163,164,165,166,167,168,169,170,171,172,173,174,175,176,177,178,179, 180,181,182,183,184,185,186,187,188,189,190,191,192,193,194,195,196,197, 198,199,200,201,202,203,204,205,206,207,208,209,210,211,212,213,214,215, 216,217,218,219,220,221,222,223,224,225,226,227,228,229,230,231,232,233, 234,235,236,237,238,239,240,241,242,243,244,245,246,247,248,249,250,251, 252,253,254,255 #endif #ifdef SQLITE_EBCDIC 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, /* 0x */ 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, /* 1x */ 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, /* 2x */ 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, /* 3x */ 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, /* 4x */ 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, /* 5x */ 96, 97, 98, 99,100,101,102,103,104,105,106,107,108,109,110,111, /* 6x */ 112,113,114,115,116,117,118,119,120,121,122,123,124,125,126,127, /* 7x */ 128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143, /* 8x */ 144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159, /* 9x */ 160,161,162,163,164,165,166,167,168,169,170,171,140,141,142,175, /* Ax */ 176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191, /* Bx */ 192,129,130,131,132,133,134,135,136,137,202,203,204,205,206,207, /* Cx */ 208,145,146,147,148,149,150,151,152,153,218,219,220,221,222,223, /* Dx */ 224,225,162,163,164,165,166,167,168,169,234,235,236,237,238,239, /* Ex */ 240,241,242,243,244,245,246,247,248,249,250,251,252,253,254,255, /* Fx */ #endif }; /* ** The following 256 byte lookup table is used to support SQLites built-in ** equivalents to the following standard library functions: ** ** isspace() 0x01 ** isalpha() 0x02 ** isdigit() 0x04 ** isalnum() 0x06 ** isxdigit() 0x08 ** toupper() 0x20 ** SQLite identifier character 0x40 ** Quote character 0x80 ** ** Bit 0x20 is set if the mapped character requires translation to upper ** case. i.e. if the character is a lower-case ASCII character. ** If x is a lower-case ASCII character, then its upper-case equivalent ** is (x - 0x20). Therefore toupper() can be implemented as: ** ** (x & ~(map[x]&0x20)) ** ** The equivalent of tolower() is implemented using the sqlite3UpperToLower[] ** array. tolower() is used more often than toupper() by SQLite. ** ** Bit 0x40 is set if the character is non-alphanumeric and can be used in an ** SQLite identifier. Identifiers are alphanumerics, "_", "$", and any ** non-ASCII UTF character. Hence the test for whether or not a character is ** part of an identifier is 0x46. */ #ifdef SQLITE_ASCII SQLITE_PRIVATE const unsigned char sqlite3CtypeMap[256] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 00..07 ........ */ 0x00, 0x01, 0x01, 0x01, 0x01, 0x01, 0x00, 0x00, /* 08..0f ........ */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 10..17 ........ */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 18..1f ........ */ 0x01, 0x00, 0x80, 0x00, 0x40, 0x00, 0x00, 0x80, /* 20..27 !"#$%&' */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 28..2f ()*+,-./ */ 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, /* 30..37 01234567 */ 0x0c, 0x0c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 38..3f 89:;<=>? */ 0x00, 0x0a, 0x0a, 0x0a, 0x0a, 0x0a, 0x0a, 0x02, /* 40..47 @ABCDEFG */ 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, /* 48..4f HIJKLMNO */ 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, /* 50..57 PQRSTUVW */ 0x02, 0x02, 0x02, 0x80, 0x00, 0x00, 0x00, 0x40, /* 58..5f XYZ[\]^_ */ 0x80, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x22, /* 60..67 `abcdefg */ 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, /* 68..6f hijklmno */ 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, /* 70..77 pqrstuvw */ 0x22, 0x22, 0x22, 0x00, 0x00, 0x00, 0x00, 0x00, /* 78..7f xyz{|}~. */ 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* 80..87 ........ */ 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* 88..8f ........ */ 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* 90..97 ........ */ 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* 98..9f ........ */ 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* a0..a7 ........ */ 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* a8..af ........ */ 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* b0..b7 ........ */ 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* b8..bf ........ */ 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* c0..c7 ........ */ 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* c8..cf ........ */ 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* d0..d7 ........ */ 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* d8..df ........ */ 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* e0..e7 ........ */ 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* e8..ef ........ */ 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* f0..f7 ........ */ 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40 /* f8..ff ........ */ }; #endif /* EVIDENCE-OF: R-02982-34736 In order to maintain full backwards ** compatibility for legacy applications, the URI filename capability is ** disabled by default. ** ** EVIDENCE-OF: R-38799-08373 URI filenames can be enabled or disabled ** using the SQLITE_USE_URI=1 or SQLITE_USE_URI=0 compile-time options. ** ** EVIDENCE-OF: R-43642-56306 By default, URI handling is globally ** disabled. The default value may be changed by compiling with the ** SQLITE_USE_URI symbol defined. */ #ifndef SQLITE_USE_URI # define SQLITE_USE_URI 0 #endif /* EVIDENCE-OF: R-38720-18127 The default setting is determined by the ** SQLITE_ALLOW_COVERING_INDEX_SCAN compile-time option, or is "on" if ** that compile-time option is omitted. */ #ifndef SQLITE_ALLOW_COVERING_INDEX_SCAN # define SQLITE_ALLOW_COVERING_INDEX_SCAN 1 #endif /* The minimum PMA size is set to this value multiplied by the database ** page size in bytes. */ #ifndef SQLITE_SORTER_PMASZ # define SQLITE_SORTER_PMASZ 250 #endif /* Statement journals spill to disk when their size exceeds the following ** threshold (in bytes). 0 means that statement journals are created and ** written to disk immediately (the default behavior for SQLite versions ** before 3.12.0). -1 means always keep the entire statement journal in ** memory. (The statement journal is also always held entirely in memory ** if journal_mode=MEMORY or if temp_store=MEMORY, regardless of this ** setting.) */ #ifndef SQLITE_STMTJRNL_SPILL # define SQLITE_STMTJRNL_SPILL (64*1024) #endif /* ** The following singleton contains the global configuration for ** the SQLite library. */ SQLITE_PRIVATE SQLITE_WSD struct Sqlite3Config sqlite3Config = { SQLITE_DEFAULT_MEMSTATUS, /* bMemstat */ 1, /* bCoreMutex */ SQLITE_THREADSAFE==1, /* bFullMutex */ SQLITE_USE_URI, /* bOpenUri */ SQLITE_ALLOW_COVERING_INDEX_SCAN, /* bUseCis */ 0x7ffffffe, /* mxStrlen */ 0, /* neverCorrupt */ 128, /* szLookaside */ 500, /* nLookaside */ SQLITE_STMTJRNL_SPILL, /* nStmtSpill */ {0,0,0,0,0,0,0,0}, /* m */ {0,0,0,0,0,0,0,0,0}, /* mutex */ {0,0,0,0,0,0,0,0,0,0,0,0,0},/* pcache2 */ (void*)0, /* pHeap */ 0, /* nHeap */ 0, 0, /* mnHeap, mxHeap */ SQLITE_DEFAULT_MMAP_SIZE, /* szMmap */ SQLITE_MAX_MMAP_SIZE, /* mxMmap */ (void*)0, /* pScratch */ 0, /* szScratch */ 0, /* nScratch */ (void*)0, /* pPage */ 0, /* szPage */ SQLITE_DEFAULT_PCACHE_INITSZ, /* nPage */ 0, /* mxParserStack */ 0, /* sharedCacheEnabled */ SQLITE_SORTER_PMASZ, /* szPma */ /* All the rest should always be initialized to zero */ 0, /* isInit */ 0, /* inProgress */ 0, /* isMutexInit */ 0, /* isMallocInit */ 0, /* isPCacheInit */ 0, /* nRefInitMutex */ 0, /* pInitMutex */ 0, /* xLog */ 0, /* pLogArg */ #ifdef SQLITE_ENABLE_SQLLOG 0, /* xSqllog */ 0, /* pSqllogArg */ #endif #ifdef SQLITE_VDBE_COVERAGE 0, /* xVdbeBranch */ 0, /* pVbeBranchArg */ #endif #ifndef SQLITE_OMIT_BUILTIN_TEST 0, /* xTestCallback */ #endif 0, /* bLocaltimeFault */ 0x7ffffffe /* iOnceResetThreshold */ }; /* ** Hash table for global functions - functions common to all ** database connections. After initialization, this table is ** read-only. */ SQLITE_PRIVATE FuncDefHash sqlite3BuiltinFunctions; /* ** Constant tokens for values 0 and 1. */ SQLITE_PRIVATE const Token sqlite3IntTokens[] = { { "0", 1 }, { "1", 1 } }; /* ** The value of the "pending" byte must be 0x40000000 (1 byte past the ** 1-gibabyte boundary) in a compatible database. SQLite never uses ** the database page that contains the pending byte. It never attempts ** to read or write that page. The pending byte page is set aside ** for use by the VFS layers as space for managing file locks. ** ** During testing, it is often desirable to move the pending byte to ** a different position in the file. This allows code that has to ** deal with the pending byte to run on files that are much smaller ** than 1 GiB. The sqlite3_test_control() interface can be used to ** move the pending byte. ** ** IMPORTANT: Changing the pending byte to any value other than ** 0x40000000 results in an incompatible database file format! ** Changing the pending byte during operation will result in undefined ** and incorrect behavior. */ #ifndef SQLITE_OMIT_WSD SQLITE_PRIVATE int sqlite3PendingByte = 0x40000000; #endif /* #include "opcodes.h" */ /* ** Properties of opcodes. The OPFLG_INITIALIZER macro is ** created by mkopcodeh.awk during compilation. Data is obtained ** from the comments following the "case OP_xxxx:" statements in ** the vdbe.c file. */ SQLITE_PRIVATE const unsigned char sqlite3OpcodeProperty[] = OPFLG_INITIALIZER; /* ** Name of the default collating sequence */ SQLITE_PRIVATE const char sqlite3StrBINARY[] = "BINARY"; /************** End of global.c **********************************************/ /************** Begin file ctime.c *******************************************/ /* ** 2010 February 23 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ************************************************************************* ** ** This file implements routines used to report what compile-time options ** SQLite was built with. */ #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS /* #include "sqliteInt.h" */ /* ** An array of names of all compile-time options. This array should ** be sorted A-Z. ** ** This array looks large, but in a typical installation actually uses ** only a handful of compile-time options, so most times this array is usually ** rather short and uses little memory space. */ static const char * const azCompileOpt[] = { /* These macros are provided to "stringify" the value of the define ** for those options in which the value is meaningful. */ #define CTIMEOPT_VAL_(opt) #opt #define CTIMEOPT_VAL(opt) CTIMEOPT_VAL_(opt) #if SQLITE_32BIT_ROWID "32BIT_ROWID", #endif #if SQLITE_4_BYTE_ALIGNED_MALLOC "4_BYTE_ALIGNED_MALLOC", #endif #if SQLITE_CASE_SENSITIVE_LIKE "CASE_SENSITIVE_LIKE", #endif #if SQLITE_CHECK_PAGES "CHECK_PAGES", #endif #if defined(__clang__) && defined(__clang_major__) "COMPILER=clang-" CTIMEOPT_VAL(__clang_major__) "." CTIMEOPT_VAL(__clang_minor__) "." CTIMEOPT_VAL(__clang_patchlevel__), #elif defined(_MSC_VER) "COMPILER=msvc-" CTIMEOPT_VAL(_MSC_VER), #elif defined(__GNUC__) && defined(__VERSION__) "COMPILER=gcc-" __VERSION__, #endif #if SQLITE_COVERAGE_TEST "COVERAGE_TEST", #endif #if SQLITE_DEBUG "DEBUG", #endif #if SQLITE_DEFAULT_LOCKING_MODE "DEFAULT_LOCKING_MODE=" CTIMEOPT_VAL(SQLITE_DEFAULT_LOCKING_MODE), #endif #if defined(SQLITE_DEFAULT_MMAP_SIZE) && !defined(SQLITE_DEFAULT_MMAP_SIZE_xc) "DEFAULT_MMAP_SIZE=" CTIMEOPT_VAL(SQLITE_DEFAULT_MMAP_SIZE), #endif #if SQLITE_DISABLE_DIRSYNC "DISABLE_DIRSYNC", #endif #if SQLITE_DISABLE_LFS "DISABLE_LFS", #endif #if SQLITE_ENABLE_8_3_NAMES "ENABLE_8_3_NAMES=" CTIMEOPT_VAL(SQLITE_ENABLE_8_3_NAMES), #endif #if SQLITE_ENABLE_API_ARMOR "ENABLE_API_ARMOR", #endif #if SQLITE_ENABLE_ATOMIC_WRITE "ENABLE_ATOMIC_WRITE", #endif #if SQLITE_ENABLE_CEROD "ENABLE_CEROD", #endif #if SQLITE_ENABLE_COLUMN_METADATA "ENABLE_COLUMN_METADATA", #endif #if SQLITE_ENABLE_DBSTAT_VTAB "ENABLE_DBSTAT_VTAB", #endif #if SQLITE_ENABLE_EXPENSIVE_ASSERT "ENABLE_EXPENSIVE_ASSERT", #endif #if SQLITE_ENABLE_FTS1 "ENABLE_FTS1", #endif #if SQLITE_ENABLE_FTS2 "ENABLE_FTS2", #endif #if SQLITE_ENABLE_FTS3 "ENABLE_FTS3", #endif #if SQLITE_ENABLE_FTS3_PARENTHESIS "ENABLE_FTS3_PARENTHESIS", #endif #if SQLITE_ENABLE_FTS4 "ENABLE_FTS4", #endif #if SQLITE_ENABLE_FTS5 "ENABLE_FTS5", #endif #if SQLITE_ENABLE_ICU "ENABLE_ICU", #endif #if SQLITE_ENABLE_IOTRACE "ENABLE_IOTRACE", #endif #if SQLITE_ENABLE_JSON1 "ENABLE_JSON1", #endif #if SQLITE_ENABLE_LOAD_EXTENSION "ENABLE_LOAD_EXTENSION", #endif #if SQLITE_ENABLE_LOCKING_STYLE "ENABLE_LOCKING_STYLE=" CTIMEOPT_VAL(SQLITE_ENABLE_LOCKING_STYLE), #endif #if SQLITE_ENABLE_MEMORY_MANAGEMENT "ENABLE_MEMORY_MANAGEMENT", #endif #if SQLITE_ENABLE_MEMSYS3 "ENABLE_MEMSYS3", #endif #if SQLITE_ENABLE_MEMSYS5 "ENABLE_MEMSYS5", #endif #if SQLITE_ENABLE_OVERSIZE_CELL_CHECK "ENABLE_OVERSIZE_CELL_CHECK", #endif #if SQLITE_ENABLE_RTREE "ENABLE_RTREE", #endif #if defined(SQLITE_ENABLE_STAT4) "ENABLE_STAT4", #elif defined(SQLITE_ENABLE_STAT3) "ENABLE_STAT3", #endif #if SQLITE_ENABLE_UNLOCK_NOTIFY "ENABLE_UNLOCK_NOTIFY", #endif #if SQLITE_ENABLE_UPDATE_DELETE_LIMIT "ENABLE_UPDATE_DELETE_LIMIT", #endif #if SQLITE_HAS_CODEC "HAS_CODEC", #endif #if HAVE_ISNAN || SQLITE_HAVE_ISNAN "HAVE_ISNAN", #endif #if SQLITE_HOMEGROWN_RECURSIVE_MUTEX "HOMEGROWN_RECURSIVE_MUTEX", #endif #if SQLITE_IGNORE_AFP_LOCK_ERRORS "IGNORE_AFP_LOCK_ERRORS", #endif #if SQLITE_IGNORE_FLOCK_LOCK_ERRORS "IGNORE_FLOCK_LOCK_ERRORS", #endif #ifdef SQLITE_INT64_TYPE "INT64_TYPE", #endif #ifdef SQLITE_LIKE_DOESNT_MATCH_BLOBS "LIKE_DOESNT_MATCH_BLOBS", #endif #if SQLITE_LOCK_TRACE "LOCK_TRACE", #endif #if defined(SQLITE_MAX_MMAP_SIZE) && !defined(SQLITE_MAX_MMAP_SIZE_xc) "MAX_MMAP_SIZE=" CTIMEOPT_VAL(SQLITE_MAX_MMAP_SIZE), #endif #ifdef SQLITE_MAX_SCHEMA_RETRY "MAX_SCHEMA_RETRY=" CTIMEOPT_VAL(SQLITE_MAX_SCHEMA_RETRY), #endif #if SQLITE_MEMDEBUG "MEMDEBUG", #endif #if SQLITE_MIXED_ENDIAN_64BIT_FLOAT "MIXED_ENDIAN_64BIT_FLOAT", #endif #if SQLITE_NO_SYNC "NO_SYNC", #endif #if SQLITE_OMIT_ALTERTABLE "OMIT_ALTERTABLE", #endif #if SQLITE_OMIT_ANALYZE "OMIT_ANALYZE", #endif #if SQLITE_OMIT_ATTACH "OMIT_ATTACH", #endif #if SQLITE_OMIT_AUTHORIZATION "OMIT_AUTHORIZATION", #endif #if SQLITE_OMIT_AUTOINCREMENT "OMIT_AUTOINCREMENT", #endif #if SQLITE_OMIT_AUTOINIT "OMIT_AUTOINIT", #endif #if SQLITE_OMIT_AUTOMATIC_INDEX "OMIT_AUTOMATIC_INDEX", #endif #if SQLITE_OMIT_AUTORESET "OMIT_AUTORESET", #endif #if SQLITE_OMIT_AUTOVACUUM "OMIT_AUTOVACUUM", #endif #if SQLITE_OMIT_BETWEEN_OPTIMIZATION "OMIT_BETWEEN_OPTIMIZATION", #endif #if SQLITE_OMIT_BLOB_LITERAL "OMIT_BLOB_LITERAL", #endif #if SQLITE_OMIT_BTREECOUNT "OMIT_BTREECOUNT", #endif #if SQLITE_OMIT_BUILTIN_TEST "OMIT_BUILTIN_TEST", #endif #if SQLITE_OMIT_CAST "OMIT_CAST", #endif #if SQLITE_OMIT_CHECK "OMIT_CHECK", #endif #if SQLITE_OMIT_COMPLETE "OMIT_COMPLETE", #endif #if SQLITE_OMIT_COMPOUND_SELECT "OMIT_COMPOUND_SELECT", #endif #if SQLITE_OMIT_CTE "OMIT_CTE", #endif #if SQLITE_OMIT_DATETIME_FUNCS "OMIT_DATETIME_FUNCS", #endif #if SQLITE_OMIT_DECLTYPE "OMIT_DECLTYPE", #endif #if SQLITE_OMIT_DEPRECATED "OMIT_DEPRECATED", #endif #if SQLITE_OMIT_DISKIO "OMIT_DISKIO", #endif #if SQLITE_OMIT_EXPLAIN "OMIT_EXPLAIN", #endif #if SQLITE_OMIT_FLAG_PRAGMAS "OMIT_FLAG_PRAGMAS", #endif #if SQLITE_OMIT_FLOATING_POINT "OMIT_FLOATING_POINT", #endif #if SQLITE_OMIT_FOREIGN_KEY "OMIT_FOREIGN_KEY", #endif #if SQLITE_OMIT_GET_TABLE "OMIT_GET_TABLE", #endif #if SQLITE_OMIT_INCRBLOB "OMIT_INCRBLOB", #endif #if SQLITE_OMIT_INTEGRITY_CHECK "OMIT_INTEGRITY_CHECK", #endif #if SQLITE_OMIT_LIKE_OPTIMIZATION "OMIT_LIKE_OPTIMIZATION", #endif #if SQLITE_OMIT_LOAD_EXTENSION "OMIT_LOAD_EXTENSION", #endif #if SQLITE_OMIT_LOCALTIME "OMIT_LOCALTIME", #endif #if SQLITE_OMIT_LOOKASIDE "OMIT_LOOKASIDE", #endif #if SQLITE_OMIT_MEMORYDB "OMIT_MEMORYDB", #endif #if SQLITE_OMIT_OR_OPTIMIZATION "OMIT_OR_OPTIMIZATION", #endif #if SQLITE_OMIT_PAGER_PRAGMAS "OMIT_PAGER_PRAGMAS", #endif #if SQLITE_OMIT_PRAGMA "OMIT_PRAGMA", #endif #if SQLITE_OMIT_PROGRESS_CALLBACK "OMIT_PROGRESS_CALLBACK", #endif #if SQLITE_OMIT_QUICKBALANCE "OMIT_QUICKBALANCE", #endif #if SQLITE_OMIT_REINDEX "OMIT_REINDEX", #endif #if SQLITE_OMIT_SCHEMA_PRAGMAS "OMIT_SCHEMA_PRAGMAS", #endif #if SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS "OMIT_SCHEMA_VERSION_PRAGMAS", #endif #if SQLITE_OMIT_SHARED_CACHE "OMIT_SHARED_CACHE", #endif #if SQLITE_OMIT_SUBQUERY "OMIT_SUBQUERY", #endif #if SQLITE_OMIT_TCL_VARIABLE "OMIT_TCL_VARIABLE", #endif #if SQLITE_OMIT_TEMPDB "OMIT_TEMPDB", #endif #if SQLITE_OMIT_TRACE "OMIT_TRACE", #endif #if SQLITE_OMIT_TRIGGER "OMIT_TRIGGER", #endif #if SQLITE_OMIT_TRUNCATE_OPTIMIZATION "OMIT_TRUNCATE_OPTIMIZATION", #endif #if SQLITE_OMIT_UTF16 "OMIT_UTF16", #endif #if SQLITE_OMIT_VACUUM "OMIT_VACUUM", #endif #if SQLITE_OMIT_VIEW "OMIT_VIEW", #endif #if SQLITE_OMIT_VIRTUALTABLE "OMIT_VIRTUALTABLE", #endif #if SQLITE_OMIT_WAL "OMIT_WAL", #endif #if SQLITE_OMIT_WSD "OMIT_WSD", #endif #if SQLITE_OMIT_XFER_OPT "OMIT_XFER_OPT", #endif #if SQLITE_PERFORMANCE_TRACE "PERFORMANCE_TRACE", #endif #if SQLITE_PROXY_DEBUG "PROXY_DEBUG", #endif #if SQLITE_RTREE_INT_ONLY "RTREE_INT_ONLY", #endif #if SQLITE_SECURE_DELETE "SECURE_DELETE", #endif #if SQLITE_SMALL_STACK "SMALL_STACK", #endif #if SQLITE_SOUNDEX "SOUNDEX", #endif #if SQLITE_SYSTEM_MALLOC "SYSTEM_MALLOC", #endif #if SQLITE_TCL "TCL", #endif #if defined(SQLITE_TEMP_STORE) && !defined(SQLITE_TEMP_STORE_xc) "TEMP_STORE=" CTIMEOPT_VAL(SQLITE_TEMP_STORE), #endif #if SQLITE_TEST "TEST", #endif #if defined(SQLITE_THREADSAFE) "THREADSAFE=" CTIMEOPT_VAL(SQLITE_THREADSAFE), #endif #if SQLITE_USE_ALLOCA "USE_ALLOCA", #endif #if SQLITE_USER_AUTHENTICATION "USER_AUTHENTICATION", #endif #if SQLITE_WIN32_MALLOC "WIN32_MALLOC", #endif #if SQLITE_ZERO_MALLOC "ZERO_MALLOC" #endif }; /* ** Given the name of a compile-time option, return true if that option ** was used and false if not. ** ** The name can optionally begin with "SQLITE_" but the "SQLITE_" prefix ** is not required for a match. */ SQLITE_API int sqlite3_compileoption_used(const char *zOptName){ int i, n; #if SQLITE_ENABLE_API_ARMOR if( zOptName==0 ){ (void)SQLITE_MISUSE_BKPT; return 0; } #endif if( sqlite3StrNICmp(zOptName, "SQLITE_", 7)==0 ) zOptName += 7; n = sqlite3Strlen30(zOptName); /* Since ArraySize(azCompileOpt) is normally in single digits, a ** linear search is adequate. No need for a binary search. */ for(i=0; i=0 && NaDb[] (or -1) */ u8 nullRow; /* True if pointing to a row with no data */ u8 deferredMoveto; /* A call to sqlite3BtreeMoveto() is needed */ u8 isTable; /* True for rowid tables. False for indexes */ #ifdef SQLITE_DEBUG u8 seekOp; /* Most recent seek operation on this cursor */ u8 wrFlag; /* The wrFlag argument to sqlite3BtreeCursor() */ #endif Bool isEphemeral:1; /* True for an ephemeral table */ Bool useRandomRowid:1;/* Generate new record numbers semi-randomly */ Bool isOrdered:1; /* True if the table is not BTREE_UNORDERED */ Pgno pgnoRoot; /* Root page of the open btree cursor */ i16 nField; /* Number of fields in the header */ u16 nHdrParsed; /* Number of header fields parsed so far */ union { BtCursor *pCursor; /* CURTYPE_BTREE. Btree cursor */ sqlite3_vtab_cursor *pVCur; /* CURTYPE_VTAB. Vtab cursor */ int pseudoTableReg; /* CURTYPE_PSEUDO. Reg holding content. */ VdbeSorter *pSorter; /* CURTYPE_SORTER. Sorter object */ } uc; Btree *pBt; /* Separate file holding temporary table */ KeyInfo *pKeyInfo; /* Info about index keys needed by index cursors */ int seekResult; /* Result of previous sqlite3BtreeMoveto() */ i64 seqCount; /* Sequence counter */ i64 movetoTarget; /* Argument to the deferred sqlite3BtreeMoveto() */ VdbeCursor *pAltCursor; /* Associated index cursor from which to read */ int *aAltMap; /* Mapping from table to index column numbers */ #ifdef SQLITE_ENABLE_COLUMN_USED_MASK u64 maskUsed; /* Mask of columns used by this cursor */ #endif /* Cached information about the header for the data record that the ** cursor is currently pointing to. Only valid if cacheStatus matches ** Vdbe.cacheCtr. Vdbe.cacheCtr will never take on the value of ** CACHE_STALE and so setting cacheStatus=CACHE_STALE guarantees that ** the cache is out of date. ** ** aRow might point to (ephemeral) data for the current row, or it might ** be NULL. */ u32 cacheStatus; /* Cache is valid if this matches Vdbe.cacheCtr */ u32 payloadSize; /* Total number of bytes in the record */ u32 szRow; /* Byte available in aRow */ u32 iHdrOffset; /* Offset to next unparsed byte of the header */ const u8 *aRow; /* Data for the current row, if all on one page */ u32 *aOffset; /* Pointer to aType[nField] */ u32 aType[1]; /* Type values for all entries in the record */ /* 2*nField extra array elements allocated for aType[], beyond the one ** static element declared in the structure. nField total array slots for ** aType[] and nField+1 array slots for aOffset[] */ }; /* ** A value for VdbeCursor.cacheStatus that means the cache is always invalid. */ #define CACHE_STALE 0 /* ** When a sub-program is executed (OP_Program), a structure of this type ** is allocated to store the current value of the program counter, as ** well as the current memory cell array and various other frame specific ** values stored in the Vdbe struct. When the sub-program is finished, ** these values are copied back to the Vdbe from the VdbeFrame structure, ** restoring the state of the VM to as it was before the sub-program ** began executing. ** ** The memory for a VdbeFrame object is allocated and managed by a memory ** cell in the parent (calling) frame. When the memory cell is deleted or ** overwritten, the VdbeFrame object is not freed immediately. Instead, it ** is linked into the Vdbe.pDelFrame list. The contents of the Vdbe.pDelFrame ** list is deleted when the VM is reset in VdbeHalt(). The reason for doing ** this instead of deleting the VdbeFrame immediately is to avoid recursive ** calls to sqlite3VdbeMemRelease() when the memory cells belonging to the ** child frame are released. ** ** The currently executing frame is stored in Vdbe.pFrame. Vdbe.pFrame is ** set to NULL if the currently executing frame is the main program. */ typedef struct VdbeFrame VdbeFrame; struct VdbeFrame { Vdbe *v; /* VM this frame belongs to */ VdbeFrame *pParent; /* Parent of this frame, or NULL if parent is main */ Op *aOp; /* Program instructions for parent frame */ i64 *anExec; /* Event counters from parent frame */ Mem *aMem; /* Array of memory cells for parent frame */ VdbeCursor **apCsr; /* Array of Vdbe cursors for parent frame */ void *token; /* Copy of SubProgram.token */ i64 lastRowid; /* Last insert rowid (sqlite3.lastRowid) */ AuxData *pAuxData; /* Linked list of auxdata allocations */ int nCursor; /* Number of entries in apCsr */ int pc; /* Program Counter in parent (calling) frame */ int nOp; /* Size of aOp array */ int nMem; /* Number of entries in aMem */ int nChildMem; /* Number of memory cells for child frame */ int nChildCsr; /* Number of cursors for child frame */ int nChange; /* Statement changes (Vdbe.nChange) */ int nDbChange; /* Value of db->nChange */ }; #define VdbeFrameMem(p) ((Mem *)&((u8 *)p)[ROUND8(sizeof(VdbeFrame))]) /* ** Internally, the vdbe manipulates nearly all SQL values as Mem ** structures. Each Mem struct may cache multiple representations (string, ** integer etc.) of the same value. */ struct Mem { union MemValue { double r; /* Real value used when MEM_Real is set in flags */ i64 i; /* Integer value used when MEM_Int is set in flags */ int nZero; /* Used when bit MEM_Zero is set in flags */ FuncDef *pDef; /* Used only when flags==MEM_Agg */ RowSet *pRowSet; /* Used only when flags==MEM_RowSet */ VdbeFrame *pFrame; /* Used when flags==MEM_Frame */ } u; u16 flags; /* Some combination of MEM_Null, MEM_Str, MEM_Dyn, etc. */ u8 enc; /* SQLITE_UTF8, SQLITE_UTF16BE, SQLITE_UTF16LE */ u8 eSubtype; /* Subtype for this value */ int n; /* Number of characters in string value, excluding '\0' */ char *z; /* String or BLOB value */ /* ShallowCopy only needs to copy the information above */ char *zMalloc; /* Space to hold MEM_Str or MEM_Blob if szMalloc>0 */ int szMalloc; /* Size of the zMalloc allocation */ u32 uTemp; /* Transient storage for serial_type in OP_MakeRecord */ sqlite3 *db; /* The associated database connection */ void (*xDel)(void*);/* Destructor for Mem.z - only valid if MEM_Dyn */ #ifdef SQLITE_DEBUG Mem *pScopyFrom; /* This Mem is a shallow copy of pScopyFrom */ void *pFiller; /* So that sizeof(Mem) is a multiple of 8 */ #endif }; /* ** Size of struct Mem not including the Mem.zMalloc member or anything that ** follows. */ #define MEMCELLSIZE offsetof(Mem,zMalloc) /* One or more of the following flags are set to indicate the validOK ** representations of the value stored in the Mem struct. ** ** If the MEM_Null flag is set, then the value is an SQL NULL value. ** No other flags may be set in this case. ** ** If the MEM_Str flag is set then Mem.z points at a string representation. ** Usually this is encoded in the same unicode encoding as the main ** database (see below for exceptions). If the MEM_Term flag is also ** set, then the string is nul terminated. The MEM_Int and MEM_Real ** flags may coexist with the MEM_Str flag. */ #define MEM_Null 0x0001 /* Value is NULL */ #define MEM_Str 0x0002 /* Value is a string */ #define MEM_Int 0x0004 /* Value is an integer */ #define MEM_Real 0x0008 /* Value is a real number */ #define MEM_Blob 0x0010 /* Value is a BLOB */ #define MEM_AffMask 0x001f /* Mask of affinity bits */ #define MEM_RowSet 0x0020 /* Value is a RowSet object */ #define MEM_Frame 0x0040 /* Value is a VdbeFrame object */ #define MEM_Undefined 0x0080 /* Value is undefined */ #define MEM_Cleared 0x0100 /* NULL set by OP_Null, not from data */ #define MEM_TypeMask 0x81ff /* Mask of type bits */ /* Whenever Mem contains a valid string or blob representation, one of ** the following flags must be set to determine the memory management ** policy for Mem.z. The MEM_Term flag tells us whether or not the ** string is \000 or \u0000 terminated */ #define MEM_Term 0x0200 /* String rep is nul terminated */ #define MEM_Dyn 0x0400 /* Need to call Mem.xDel() on Mem.z */ #define MEM_Static 0x0800 /* Mem.z points to a static string */ #define MEM_Ephem 0x1000 /* Mem.z points to an ephemeral string */ #define MEM_Agg 0x2000 /* Mem.z points to an agg function context */ #define MEM_Zero 0x4000 /* Mem.i contains count of 0s appended to blob */ #define MEM_Subtype 0x8000 /* Mem.eSubtype is valid */ #ifdef SQLITE_OMIT_INCRBLOB #undef MEM_Zero #define MEM_Zero 0x0000 #endif /* Return TRUE if Mem X contains dynamically allocated content - anything ** that needs to be deallocated to avoid a leak. */ #define VdbeMemDynamic(X) \ (((X)->flags&(MEM_Agg|MEM_Dyn|MEM_RowSet|MEM_Frame))!=0) /* ** Clear any existing type flags from a Mem and replace them with f */ #define MemSetTypeFlag(p, f) \ ((p)->flags = ((p)->flags&~(MEM_TypeMask|MEM_Zero))|f) /* ** Return true if a memory cell is not marked as invalid. This macro ** is for use inside assert() statements only. */ #ifdef SQLITE_DEBUG #define memIsValid(M) ((M)->flags & MEM_Undefined)==0 #endif /* ** Each auxiliary data pointer stored by a user defined function ** implementation calling sqlite3_set_auxdata() is stored in an instance ** of this structure. All such structures associated with a single VM ** are stored in a linked list headed at Vdbe.pAuxData. All are destroyed ** when the VM is halted (if not before). */ struct AuxData { int iOp; /* Instruction number of OP_Function opcode */ int iArg; /* Index of function argument. */ void *pAux; /* Aux data pointer */ void (*xDelete)(void *); /* Destructor for the aux data */ AuxData *pNext; /* Next element in list */ }; /* ** The "context" argument for an installable function. A pointer to an ** instance of this structure is the first argument to the routines used ** implement the SQL functions. ** ** There is a typedef for this structure in sqlite.h. So all routines, ** even the public interface to SQLite, can use a pointer to this structure. ** But this file is the only place where the internal details of this ** structure are known. ** ** This structure is defined inside of vdbeInt.h because it uses substructures ** (Mem) which are only defined there. */ struct sqlite3_context { Mem *pOut; /* The return value is stored here */ FuncDef *pFunc; /* Pointer to function information */ Mem *pMem; /* Memory cell used to store aggregate context */ Vdbe *pVdbe; /* The VM that owns this context */ int iOp; /* Instruction number of OP_Function */ int isError; /* Error code returned by the function. */ u8 skipFlag; /* Skip accumulator loading if true */ u8 fErrorOrAux; /* isError!=0 or pVdbe->pAuxData modified */ u8 argc; /* Number of arguments */ sqlite3_value *argv[1]; /* Argument set */ }; /* A bitfield type for use inside of structures. Always follow with :N where ** N is the number of bits. */ typedef unsigned bft; /* Bit Field Type */ typedef struct ScanStatus ScanStatus; struct ScanStatus { int addrExplain; /* OP_Explain for loop */ int addrLoop; /* Address of "loops" counter */ int addrVisit; /* Address of "rows visited" counter */ int iSelectID; /* The "Select-ID" for this loop */ LogEst nEst; /* Estimated output rows per loop */ char *zName; /* Name of table or index */ }; /* ** An instance of the virtual machine. This structure contains the complete ** state of the virtual machine. ** ** The "sqlite3_stmt" structure pointer that is returned by sqlite3_prepare() ** is really a pointer to an instance of this structure. */ struct Vdbe { sqlite3 *db; /* The database connection that owns this statement */ Vdbe *pPrev,*pNext; /* Linked list of VDBEs with the same Vdbe.db */ Parse *pParse; /* Parsing context used to create this Vdbe */ ynVar nVar; /* Number of entries in aVar[] */ ynVar nzVar; /* Number of entries in azVar[] */ u32 magic; /* Magic number for sanity checking */ int nMem; /* Number of memory locations currently allocated */ int nCursor; /* Number of slots in apCsr[] */ u32 cacheCtr; /* VdbeCursor row cache generation counter */ int pc; /* The program counter */ int rc; /* Value to return */ int nChange; /* Number of db changes made since last reset */ int iStatement; /* Statement number (or 0 if has not opened stmt) */ i64 iCurrentTime; /* Value of julianday('now') for this statement */ i64 nFkConstraint; /* Number of imm. FK constraints this VM */ i64 nStmtDefCons; /* Number of def. constraints when stmt started */ i64 nStmtDefImmCons; /* Number of def. imm constraints when stmt started */ /* When allocating a new Vdbe object, all of the fields below should be ** initialized to zero or NULL */ Op *aOp; /* Space to hold the virtual machine's program */ Mem *aMem; /* The memory locations */ Mem **apArg; /* Arguments to currently executing user function */ Mem *aColName; /* Column names to return */ Mem *pResultSet; /* Pointer to an array of results */ char *zErrMsg; /* Error message written here */ VdbeCursor **apCsr; /* One element of this array for each open cursor */ Mem *aVar; /* Values for the OP_Variable opcode. */ char **azVar; /* Name of variables */ #ifndef SQLITE_OMIT_TRACE i64 startTime; /* Time when query started - used for profiling */ #endif int nOp; /* Number of instructions in the program */ #ifdef SQLITE_DEBUG int rcApp; /* errcode set by sqlite3_result_error_code() */ #endif u16 nResColumn; /* Number of columns in one row of the result set */ u8 errorAction; /* Recovery action to do in case of an error */ u8 minWriteFileFormat; /* Minimum file format for writable database files */ bft expired:1; /* True if the VM needs to be recompiled */ bft doingRerun:1; /* True if rerunning after an auto-reprepare */ bft explain:2; /* True if EXPLAIN present on SQL command */ bft changeCntOn:1; /* True to update the change-counter */ bft runOnlyOnce:1; /* Automatically expire on reset */ bft usesStmtJournal:1; /* True if uses a statement journal */ bft readOnly:1; /* True for statements that do not write */ bft bIsReader:1; /* True for statements that read */ bft isPrepareV2:1; /* True if prepared with prepare_v2() */ yDbMask btreeMask; /* Bitmask of db->aDb[] entries referenced */ yDbMask lockMask; /* Subset of btreeMask that requires a lock */ u32 aCounter[5]; /* Counters used by sqlite3_stmt_status() */ char *zSql; /* Text of the SQL statement that generated this */ void *pFree; /* Free this when deleting the vdbe */ VdbeFrame *pFrame; /* Parent frame */ VdbeFrame *pDelFrame; /* List of frame objects to free on VM reset */ int nFrame; /* Number of frames in pFrame list */ u32 expmask; /* Binding to these vars invalidates VM */ SubProgram *pProgram; /* Linked list of all sub-programs used by VM */ AuxData *pAuxData; /* Linked list of auxdata allocations */ #ifdef SQLITE_ENABLE_STMT_SCANSTATUS i64 *anExec; /* Number of times each op has been executed */ int nScan; /* Entries in aScan[] */ ScanStatus *aScan; /* Scan definitions for sqlite3_stmt_scanstatus() */ #endif }; /* ** The following are allowed values for Vdbe.magic */ #define VDBE_MAGIC_INIT 0x16bceaa5 /* Building a VDBE program */ #define VDBE_MAGIC_RUN 0x2df20da3 /* VDBE is ready to execute */ #define VDBE_MAGIC_HALT 0x319c2973 /* VDBE has completed execution */ #define VDBE_MAGIC_RESET 0x48fa9f76 /* Reset and ready to run again */ #define VDBE_MAGIC_DEAD 0x5606c3c8 /* The VDBE has been deallocated */ /* ** Structure used to store the context required by the ** sqlite3_preupdate_*() API functions. */ struct PreUpdate { Vdbe *v; VdbeCursor *pCsr; /* Cursor to read old values from */ int op; /* One of SQLITE_INSERT, UPDATE, DELETE */ u8 *aRecord; /* old.* database record */ KeyInfo keyinfo; UnpackedRecord *pUnpacked; /* Unpacked version of aRecord[] */ UnpackedRecord *pNewUnpacked; /* Unpacked version of new.* record */ int iNewReg; /* Register for new.* values */ i64 iKey1; /* First key value passed to hook */ i64 iKey2; /* Second key value passed to hook */ Mem *aNew; /* Array of new.* values */ Table *pTab; /* Schema object being upated */ }; /* ** Function prototypes */ SQLITE_PRIVATE void sqlite3VdbeError(Vdbe*, const char *, ...); SQLITE_PRIVATE void sqlite3VdbeFreeCursor(Vdbe *, VdbeCursor*); void sqliteVdbePopStack(Vdbe*,int); SQLITE_PRIVATE int sqlite3VdbeCursorMoveto(VdbeCursor**, int*); SQLITE_PRIVATE int sqlite3VdbeCursorRestore(VdbeCursor*); #if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE) SQLITE_PRIVATE void sqlite3VdbePrintOp(FILE*, int, Op*); #endif SQLITE_PRIVATE u32 sqlite3VdbeSerialTypeLen(u32); SQLITE_PRIVATE u8 sqlite3VdbeOneByteSerialTypeLen(u8); SQLITE_PRIVATE u32 sqlite3VdbeSerialType(Mem*, int, u32*); SQLITE_PRIVATE u32 sqlite3VdbeSerialPut(unsigned char*, Mem*, u32); SQLITE_PRIVATE u32 sqlite3VdbeSerialGet(const unsigned char*, u32, Mem*); SQLITE_PRIVATE void sqlite3VdbeDeleteAuxData(sqlite3*, AuxData**, int, int); int sqlite2BtreeKeyCompare(BtCursor *, const void *, int, int, int *); SQLITE_PRIVATE int sqlite3VdbeIdxKeyCompare(sqlite3*,VdbeCursor*,UnpackedRecord*,int*); SQLITE_PRIVATE int sqlite3VdbeIdxRowid(sqlite3*, BtCursor*, i64*); SQLITE_PRIVATE int sqlite3VdbeExec(Vdbe*); SQLITE_PRIVATE int sqlite3VdbeList(Vdbe*); SQLITE_PRIVATE int sqlite3VdbeHalt(Vdbe*); SQLITE_PRIVATE int sqlite3VdbeChangeEncoding(Mem *, int); SQLITE_PRIVATE int sqlite3VdbeMemTooBig(Mem*); SQLITE_PRIVATE int sqlite3VdbeMemCopy(Mem*, const Mem*); SQLITE_PRIVATE void sqlite3VdbeMemShallowCopy(Mem*, const Mem*, int); SQLITE_PRIVATE void sqlite3VdbeMemMove(Mem*, Mem*); SQLITE_PRIVATE int sqlite3VdbeMemNulTerminate(Mem*); SQLITE_PRIVATE int sqlite3VdbeMemSetStr(Mem*, const char*, int, u8, void(*)(void*)); SQLITE_PRIVATE void sqlite3VdbeMemSetInt64(Mem*, i64); #ifdef SQLITE_OMIT_FLOATING_POINT # define sqlite3VdbeMemSetDouble sqlite3VdbeMemSetInt64 #else SQLITE_PRIVATE void sqlite3VdbeMemSetDouble(Mem*, double); #endif SQLITE_PRIVATE void sqlite3VdbeMemInit(Mem*,sqlite3*,u16); SQLITE_PRIVATE void sqlite3VdbeMemSetNull(Mem*); SQLITE_PRIVATE void sqlite3VdbeMemSetZeroBlob(Mem*,int); SQLITE_PRIVATE void sqlite3VdbeMemSetRowSet(Mem*); SQLITE_PRIVATE int sqlite3VdbeMemMakeWriteable(Mem*); SQLITE_PRIVATE int sqlite3VdbeMemStringify(Mem*, u8, u8); SQLITE_PRIVATE i64 sqlite3VdbeIntValue(Mem*); SQLITE_PRIVATE int sqlite3VdbeMemIntegerify(Mem*); SQLITE_PRIVATE double sqlite3VdbeRealValue(Mem*); SQLITE_PRIVATE void sqlite3VdbeIntegerAffinity(Mem*); SQLITE_PRIVATE int sqlite3VdbeMemRealify(Mem*); SQLITE_PRIVATE int sqlite3VdbeMemNumerify(Mem*); SQLITE_PRIVATE void sqlite3VdbeMemCast(Mem*,u8,u8); SQLITE_PRIVATE int sqlite3VdbeMemFromBtree(BtCursor*,u32,u32,int,Mem*); SQLITE_PRIVATE void sqlite3VdbeMemRelease(Mem *p); SQLITE_PRIVATE int sqlite3VdbeMemFinalize(Mem*, FuncDef*); SQLITE_PRIVATE const char *sqlite3OpcodeName(int); SQLITE_PRIVATE int sqlite3VdbeMemGrow(Mem *pMem, int n, int preserve); SQLITE_PRIVATE int sqlite3VdbeMemClearAndResize(Mem *pMem, int n); SQLITE_PRIVATE int sqlite3VdbeCloseStatement(Vdbe *, int); SQLITE_PRIVATE void sqlite3VdbeFrameDelete(VdbeFrame*); SQLITE_PRIVATE int sqlite3VdbeFrameRestore(VdbeFrame *); #ifdef SQLITE_ENABLE_PREUPDATE_HOOK SQLITE_PRIVATE void sqlite3VdbePreUpdateHook(Vdbe*,VdbeCursor*,int,const char*,Table*,i64,int); #endif SQLITE_PRIVATE int sqlite3VdbeTransferError(Vdbe *p); SQLITE_PRIVATE int sqlite3VdbeSorterInit(sqlite3 *, int, VdbeCursor *); SQLITE_PRIVATE void sqlite3VdbeSorterReset(sqlite3 *, VdbeSorter *); SQLITE_PRIVATE void sqlite3VdbeSorterClose(sqlite3 *, VdbeCursor *); SQLITE_PRIVATE int sqlite3VdbeSorterRowkey(const VdbeCursor *, Mem *); SQLITE_PRIVATE int sqlite3VdbeSorterNext(sqlite3 *, const VdbeCursor *, int *); SQLITE_PRIVATE int sqlite3VdbeSorterRewind(const VdbeCursor *, int *); SQLITE_PRIVATE int sqlite3VdbeSorterWrite(const VdbeCursor *, Mem *); SQLITE_PRIVATE int sqlite3VdbeSorterCompare(const VdbeCursor *, Mem *, int, int *); #if !defined(SQLITE_OMIT_SHARED_CACHE) SQLITE_PRIVATE void sqlite3VdbeEnter(Vdbe*); #else # define sqlite3VdbeEnter(X) #endif #if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE>0 SQLITE_PRIVATE void sqlite3VdbeLeave(Vdbe*); #else # define sqlite3VdbeLeave(X) #endif #ifdef SQLITE_DEBUG SQLITE_PRIVATE void sqlite3VdbeMemAboutToChange(Vdbe*,Mem*); SQLITE_PRIVATE int sqlite3VdbeCheckMemInvariants(Mem*); #endif #ifndef SQLITE_OMIT_FOREIGN_KEY SQLITE_PRIVATE int sqlite3VdbeCheckFk(Vdbe *, int); #else # define sqlite3VdbeCheckFk(p,i) 0 #endif SQLITE_PRIVATE int sqlite3VdbeMemTranslate(Mem*, u8); #ifdef SQLITE_DEBUG SQLITE_PRIVATE void sqlite3VdbePrintSql(Vdbe*); SQLITE_PRIVATE void sqlite3VdbeMemPrettyPrint(Mem *pMem, char *zBuf); #endif SQLITE_PRIVATE int sqlite3VdbeMemHandleBom(Mem *pMem); #ifndef SQLITE_OMIT_INCRBLOB SQLITE_PRIVATE int sqlite3VdbeMemExpandBlob(Mem *); #define ExpandBlob(P) (((P)->flags&MEM_Zero)?sqlite3VdbeMemExpandBlob(P):0) #else #define sqlite3VdbeMemExpandBlob(x) SQLITE_OK #define ExpandBlob(P) SQLITE_OK #endif #endif /* !defined(SQLITE_VDBEINT_H) */ /************** End of vdbeInt.h *********************************************/ /************** Continuing where we left off in status.c *********************/ /* ** Variables in which to record status information. */ #if SQLITE_PTRSIZE>4 typedef sqlite3_int64 sqlite3StatValueType; #else typedef u32 sqlite3StatValueType; #endif typedef struct sqlite3StatType sqlite3StatType; static SQLITE_WSD struct sqlite3StatType { sqlite3StatValueType nowValue[10]; /* Current value */ sqlite3StatValueType mxValue[10]; /* Maximum value */ } sqlite3Stat = { {0,}, {0,} }; /* ** Elements of sqlite3Stat[] are protected by either the memory allocator ** mutex, or by the pcache1 mutex. The following array determines which. */ static const char statMutex[] = { 0, /* SQLITE_STATUS_MEMORY_USED */ 1, /* SQLITE_STATUS_PAGECACHE_USED */ 1, /* SQLITE_STATUS_PAGECACHE_OVERFLOW */ 0, /* SQLITE_STATUS_SCRATCH_USED */ 0, /* SQLITE_STATUS_SCRATCH_OVERFLOW */ 0, /* SQLITE_STATUS_MALLOC_SIZE */ 0, /* SQLITE_STATUS_PARSER_STACK */ 1, /* SQLITE_STATUS_PAGECACHE_SIZE */ 0, /* SQLITE_STATUS_SCRATCH_SIZE */ 0, /* SQLITE_STATUS_MALLOC_COUNT */ }; /* The "wsdStat" macro will resolve to the status information ** state vector. If writable static data is unsupported on the target, ** we have to locate the state vector at run-time. In the more common ** case where writable static data is supported, wsdStat can refer directly ** to the "sqlite3Stat" state vector declared above. */ #ifdef SQLITE_OMIT_WSD # define wsdStatInit sqlite3StatType *x = &GLOBAL(sqlite3StatType,sqlite3Stat) # define wsdStat x[0] #else # define wsdStatInit # define wsdStat sqlite3Stat #endif /* ** Return the current value of a status parameter. The caller must ** be holding the appropriate mutex. */ SQLITE_PRIVATE sqlite3_int64 sqlite3StatusValue(int op){ wsdStatInit; assert( op>=0 && op=0 && op=0 && op=0 && opwsdStat.mxValue[op] ){ wsdStat.mxValue[op] = wsdStat.nowValue[op]; } } SQLITE_PRIVATE void sqlite3StatusDown(int op, int N){ wsdStatInit; assert( N>=0 ); assert( op>=0 && op=0 && op=0 ); newValue = (sqlite3StatValueType)X; assert( op>=0 && op=0 && opwsdStat.mxValue[op] ){ wsdStat.mxValue[op] = newValue; } } /* ** Query status information. */ SQLITE_API int sqlite3_status64( int op, sqlite3_int64 *pCurrent, sqlite3_int64 *pHighwater, int resetFlag ){ sqlite3_mutex *pMutex; wsdStatInit; if( op<0 || op>=ArraySize(wsdStat.nowValue) ){ return SQLITE_MISUSE_BKPT; } #ifdef SQLITE_ENABLE_API_ARMOR if( pCurrent==0 || pHighwater==0 ) return SQLITE_MISUSE_BKPT; #endif pMutex = statMutex[op] ? sqlite3Pcache1Mutex() : sqlite3MallocMutex(); sqlite3_mutex_enter(pMutex); *pCurrent = wsdStat.nowValue[op]; *pHighwater = wsdStat.mxValue[op]; if( resetFlag ){ wsdStat.mxValue[op] = wsdStat.nowValue[op]; } sqlite3_mutex_leave(pMutex); (void)pMutex; /* Prevent warning when SQLITE_THREADSAFE=0 */ return SQLITE_OK; } SQLITE_API int sqlite3_status(int op, int *pCurrent, int *pHighwater, int resetFlag){ sqlite3_int64 iCur = 0, iHwtr = 0; int rc; #ifdef SQLITE_ENABLE_API_ARMOR if( pCurrent==0 || pHighwater==0 ) return SQLITE_MISUSE_BKPT; #endif rc = sqlite3_status64(op, &iCur, &iHwtr, resetFlag); if( rc==0 ){ *pCurrent = (int)iCur; *pHighwater = (int)iHwtr; } return rc; } /* ** Query status information for a single database connection */ SQLITE_API int sqlite3_db_status( sqlite3 *db, /* The database connection whose status is desired */ int op, /* Status verb */ int *pCurrent, /* Write current value here */ int *pHighwater, /* Write high-water mark here */ int resetFlag /* Reset high-water mark if true */ ){ int rc = SQLITE_OK; /* Return code */ #ifdef SQLITE_ENABLE_API_ARMOR if( !sqlite3SafetyCheckOk(db) || pCurrent==0|| pHighwater==0 ){ return SQLITE_MISUSE_BKPT; } #endif sqlite3_mutex_enter(db->mutex); switch( op ){ case SQLITE_DBSTATUS_LOOKASIDE_USED: { *pCurrent = db->lookaside.nOut; *pHighwater = db->lookaside.mxOut; if( resetFlag ){ db->lookaside.mxOut = db->lookaside.nOut; } break; } case SQLITE_DBSTATUS_LOOKASIDE_HIT: case SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE: case SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL: { testcase( op==SQLITE_DBSTATUS_LOOKASIDE_HIT ); testcase( op==SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE ); testcase( op==SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL ); assert( (op-SQLITE_DBSTATUS_LOOKASIDE_HIT)>=0 ); assert( (op-SQLITE_DBSTATUS_LOOKASIDE_HIT)<3 ); *pCurrent = 0; *pHighwater = db->lookaside.anStat[op - SQLITE_DBSTATUS_LOOKASIDE_HIT]; if( resetFlag ){ db->lookaside.anStat[op - SQLITE_DBSTATUS_LOOKASIDE_HIT] = 0; } break; } /* ** Return an approximation for the amount of memory currently used ** by all pagers associated with the given database connection. The ** highwater mark is meaningless and is returned as zero. */ case SQLITE_DBSTATUS_CACHE_USED_SHARED: case SQLITE_DBSTATUS_CACHE_USED: { int totalUsed = 0; int i; sqlite3BtreeEnterAll(db); for(i=0; inDb; i++){ Btree *pBt = db->aDb[i].pBt; if( pBt ){ Pager *pPager = sqlite3BtreePager(pBt); int nByte = sqlite3PagerMemUsed(pPager); if( op==SQLITE_DBSTATUS_CACHE_USED_SHARED ){ nByte = nByte / sqlite3BtreeConnectionCount(pBt); } totalUsed += nByte; } } sqlite3BtreeLeaveAll(db); *pCurrent = totalUsed; *pHighwater = 0; break; } /* ** *pCurrent gets an accurate estimate of the amount of memory used ** to store the schema for all databases (main, temp, and any ATTACHed ** databases. *pHighwater is set to zero. */ case SQLITE_DBSTATUS_SCHEMA_USED: { int i; /* Used to iterate through schemas */ int nByte = 0; /* Used to accumulate return value */ sqlite3BtreeEnterAll(db); db->pnBytesFreed = &nByte; for(i=0; inDb; i++){ Schema *pSchema = db->aDb[i].pSchema; if( ALWAYS(pSchema!=0) ){ HashElem *p; nByte += sqlite3GlobalConfig.m.xRoundup(sizeof(HashElem)) * ( pSchema->tblHash.count + pSchema->trigHash.count + pSchema->idxHash.count + pSchema->fkeyHash.count ); nByte += sqlite3_msize(pSchema->tblHash.ht); nByte += sqlite3_msize(pSchema->trigHash.ht); nByte += sqlite3_msize(pSchema->idxHash.ht); nByte += sqlite3_msize(pSchema->fkeyHash.ht); for(p=sqliteHashFirst(&pSchema->trigHash); p; p=sqliteHashNext(p)){ sqlite3DeleteTrigger(db, (Trigger*)sqliteHashData(p)); } for(p=sqliteHashFirst(&pSchema->tblHash); p; p=sqliteHashNext(p)){ sqlite3DeleteTable(db, (Table *)sqliteHashData(p)); } } } db->pnBytesFreed = 0; sqlite3BtreeLeaveAll(db); *pHighwater = 0; *pCurrent = nByte; break; } /* ** *pCurrent gets an accurate estimate of the amount of memory used ** to store all prepared statements. ** *pHighwater is set to zero. */ case SQLITE_DBSTATUS_STMT_USED: { struct Vdbe *pVdbe; /* Used to iterate through VMs */ int nByte = 0; /* Used to accumulate return value */ db->pnBytesFreed = &nByte; for(pVdbe=db->pVdbe; pVdbe; pVdbe=pVdbe->pNext){ sqlite3VdbeClearObject(db, pVdbe); sqlite3DbFree(db, pVdbe); } db->pnBytesFreed = 0; *pHighwater = 0; /* IMP: R-64479-57858 */ *pCurrent = nByte; break; } /* ** Set *pCurrent to the total cache hits or misses encountered by all ** pagers the database handle is connected to. *pHighwater is always set ** to zero. */ case SQLITE_DBSTATUS_CACHE_HIT: case SQLITE_DBSTATUS_CACHE_MISS: case SQLITE_DBSTATUS_CACHE_WRITE:{ int i; int nRet = 0; assert( SQLITE_DBSTATUS_CACHE_MISS==SQLITE_DBSTATUS_CACHE_HIT+1 ); assert( SQLITE_DBSTATUS_CACHE_WRITE==SQLITE_DBSTATUS_CACHE_HIT+2 ); for(i=0; inDb; i++){ if( db->aDb[i].pBt ){ Pager *pPager = sqlite3BtreePager(db->aDb[i].pBt); sqlite3PagerCacheStat(pPager, op, resetFlag, &nRet); } } *pHighwater = 0; /* IMP: R-42420-56072 */ /* IMP: R-54100-20147 */ /* IMP: R-29431-39229 */ *pCurrent = nRet; break; } /* Set *pCurrent to non-zero if there are unresolved deferred foreign ** key constraints. Set *pCurrent to zero if all foreign key constraints ** have been satisfied. The *pHighwater is always set to zero. */ case SQLITE_DBSTATUS_DEFERRED_FKS: { *pHighwater = 0; /* IMP: R-11967-56545 */ *pCurrent = db->nDeferredImmCons>0 || db->nDeferredCons>0; break; } default: { rc = SQLITE_ERROR; } } sqlite3_mutex_leave(db->mutex); return rc; } /************** End of status.c **********************************************/ /************** Begin file date.c ********************************************/ /* ** 2003 October 31 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ************************************************************************* ** This file contains the C functions that implement date and time ** functions for SQLite. ** ** There is only one exported symbol in this file - the function ** sqlite3RegisterDateTimeFunctions() found at the bottom of the file. ** All other code has file scope. ** ** SQLite processes all times and dates as julian day numbers. The ** dates and times are stored as the number of days since noon ** in Greenwich on November 24, 4714 B.C. according to the Gregorian ** calendar system. ** ** 1970-01-01 00:00:00 is JD 2440587.5 ** 2000-01-01 00:00:00 is JD 2451544.5 ** ** This implementation requires years to be expressed as a 4-digit number ** which means that only dates between 0000-01-01 and 9999-12-31 can ** be represented, even though julian day numbers allow a much wider ** range of dates. ** ** The Gregorian calendar system is used for all dates and times, ** even those that predate the Gregorian calendar. Historians usually ** use the julian calendar for dates prior to 1582-10-15 and for some ** dates afterwards, depending on locale. Beware of this difference. ** ** The conversion algorithms are implemented based on descriptions ** in the following text: ** ** Jean Meeus ** Astronomical Algorithms, 2nd Edition, 1998 ** ISBM 0-943396-61-1 ** Willmann-Bell, Inc ** Richmond, Virginia (USA) */ /* #include "sqliteInt.h" */ /* #include */ /* #include */ #include #ifndef SQLITE_OMIT_DATETIME_FUNCS /* ** The MSVC CRT on Windows CE may not have a localtime() function. ** So declare a substitute. The substitute function itself is ** defined in "os_win.c". */ #if !defined(SQLITE_OMIT_LOCALTIME) && defined(_WIN32_WCE) && \ (!defined(SQLITE_MSVC_LOCALTIME_API) || !SQLITE_MSVC_LOCALTIME_API) struct tm *__cdecl localtime(const time_t *); #endif /* ** A structure for holding a single date and time. */ typedef struct DateTime DateTime; struct DateTime { sqlite3_int64 iJD; /* The julian day number times 86400000 */ int Y, M, D; /* Year, month, and day */ int h, m; /* Hour and minutes */ int tz; /* Timezone offset in minutes */ double s; /* Seconds */ char validYMD; /* True (1) if Y,M,D are valid */ char validHMS; /* True (1) if h,m,s are valid */ char validJD; /* True (1) if iJD is valid */ char validTZ; /* True (1) if tz is valid */ char tzSet; /* Timezone was set explicitly */ }; /* ** Convert zDate into one or more integers according to the conversion ** specifier zFormat. ** ** zFormat[] contains 4 characters for each integer converted, except for ** the last integer which is specified by three characters. The meaning ** of a four-character format specifiers ABCD is: ** ** A: number of digits to convert. Always "2" or "4". ** B: minimum value. Always "0" or "1". ** C: maximum value, decoded as: ** a: 12 ** b: 14 ** c: 24 ** d: 31 ** e: 59 ** f: 9999 ** D: the separator character, or \000 to indicate this is the ** last number to convert. ** ** Example: To translate an ISO-8601 date YYYY-MM-DD, the format would ** be "40f-21a-20c". The "40f-" indicates the 4-digit year followed by "-". ** The "21a-" indicates the 2-digit month followed by "-". The "20c" indicates ** the 2-digit day which is the last integer in the set. ** ** The function returns the number of successful conversions. */ static int getDigits(const char *zDate, const char *zFormat, ...){ /* The aMx[] array translates the 3rd character of each format ** spec into a max size: a b c d e f */ static const u16 aMx[] = { 12, 14, 24, 31, 59, 9999 }; va_list ap; int cnt = 0; char nextC; va_start(ap, zFormat); do{ char N = zFormat[0] - '0'; char min = zFormat[1] - '0'; int val = 0; u16 max; assert( zFormat[2]>='a' && zFormat[2]<='f' ); max = aMx[zFormat[2] - 'a']; nextC = zFormat[3]; val = 0; while( N-- ){ if( !sqlite3Isdigit(*zDate) ){ goto end_getDigits; } val = val*10 + *zDate - '0'; zDate++; } if( val<(int)min || val>(int)max || (nextC!=0 && nextC!=*zDate) ){ goto end_getDigits; } *va_arg(ap,int*) = val; zDate++; cnt++; zFormat += 4; }while( nextC ); end_getDigits: va_end(ap); return cnt; } /* ** Parse a timezone extension on the end of a date-time. ** The extension is of the form: ** ** (+/-)HH:MM ** ** Or the "zulu" notation: ** ** Z ** ** If the parse is successful, write the number of minutes ** of change in p->tz and return 0. If a parser error occurs, ** return non-zero. ** ** A missing specifier is not considered an error. */ static int parseTimezone(const char *zDate, DateTime *p){ int sgn = 0; int nHr, nMn; int c; while( sqlite3Isspace(*zDate) ){ zDate++; } p->tz = 0; c = *zDate; if( c=='-' ){ sgn = -1; }else if( c=='+' ){ sgn = +1; }else if( c=='Z' || c=='z' ){ zDate++; goto zulu_time; }else{ return c!=0; } zDate++; if( getDigits(zDate, "20b:20e", &nHr, &nMn)!=2 ){ return 1; } zDate += 5; p->tz = sgn*(nMn + nHr*60); zulu_time: while( sqlite3Isspace(*zDate) ){ zDate++; } p->tzSet = 1; return *zDate!=0; } /* ** Parse times of the form HH:MM or HH:MM:SS or HH:MM:SS.FFFF. ** The HH, MM, and SS must each be exactly 2 digits. The ** fractional seconds FFFF can be one or more digits. ** ** Return 1 if there is a parsing error and 0 on success. */ static int parseHhMmSs(const char *zDate, DateTime *p){ int h, m, s; double ms = 0.0; if( getDigits(zDate, "20c:20e", &h, &m)!=2 ){ return 1; } zDate += 5; if( *zDate==':' ){ zDate++; if( getDigits(zDate, "20e", &s)!=1 ){ return 1; } zDate += 2; if( *zDate=='.' && sqlite3Isdigit(zDate[1]) ){ double rScale = 1.0; zDate++; while( sqlite3Isdigit(*zDate) ){ ms = ms*10.0 + *zDate - '0'; rScale *= 10.0; zDate++; } ms /= rScale; } }else{ s = 0; } p->validJD = 0; p->validHMS = 1; p->h = h; p->m = m; p->s = s + ms; if( parseTimezone(zDate, p) ) return 1; p->validTZ = (p->tz!=0)?1:0; return 0; } /* ** Convert from YYYY-MM-DD HH:MM:SS to julian day. We always assume ** that the YYYY-MM-DD is according to the Gregorian calendar. ** ** Reference: Meeus page 61 */ static void computeJD(DateTime *p){ int Y, M, D, A, B, X1, X2; if( p->validJD ) return; if( p->validYMD ){ Y = p->Y; M = p->M; D = p->D; }else{ Y = 2000; /* If no YMD specified, assume 2000-Jan-01 */ M = 1; D = 1; } if( M<=2 ){ Y--; M += 12; } A = Y/100; B = 2 - A + (A/4); X1 = 36525*(Y+4716)/100; X2 = 306001*(M+1)/10000; p->iJD = (sqlite3_int64)((X1 + X2 + D + B - 1524.5 ) * 86400000); p->validJD = 1; if( p->validHMS ){ p->iJD += p->h*3600000 + p->m*60000 + (sqlite3_int64)(p->s*1000); if( p->validTZ ){ p->iJD -= p->tz*60000; p->validYMD = 0; p->validHMS = 0; p->validTZ = 0; } } } /* ** Parse dates of the form ** ** YYYY-MM-DD HH:MM:SS.FFF ** YYYY-MM-DD HH:MM:SS ** YYYY-MM-DD HH:MM ** YYYY-MM-DD ** ** Write the result into the DateTime structure and return 0 ** on success and 1 if the input string is not a well-formed ** date. */ static int parseYyyyMmDd(const char *zDate, DateTime *p){ int Y, M, D, neg; if( zDate[0]=='-' ){ zDate++; neg = 1; }else{ neg = 0; } if( getDigits(zDate, "40f-21a-21d", &Y, &M, &D)!=3 ){ return 1; } zDate += 10; while( sqlite3Isspace(*zDate) || 'T'==*(u8*)zDate ){ zDate++; } if( parseHhMmSs(zDate, p)==0 ){ /* We got the time */ }else if( *zDate==0 ){ p->validHMS = 0; }else{ return 1; } p->validJD = 0; p->validYMD = 1; p->Y = neg ? -Y : Y; p->M = M; p->D = D; if( p->validTZ ){ computeJD(p); } return 0; } /* ** Set the time to the current time reported by the VFS. ** ** Return the number of errors. */ static int setDateTimeToCurrent(sqlite3_context *context, DateTime *p){ p->iJD = sqlite3StmtCurrentTime(context); if( p->iJD>0 ){ p->validJD = 1; return 0; }else{ return 1; } } /* ** Attempt to parse the given string into a julian day number. Return ** the number of errors. ** ** The following are acceptable forms for the input string: ** ** YYYY-MM-DD HH:MM:SS.FFF +/-HH:MM ** DDDD.DD ** now ** ** In the first form, the +/-HH:MM is always optional. The fractional ** seconds extension (the ".FFF") is optional. The seconds portion ** (":SS.FFF") is option. The year and date can be omitted as long ** as there is a time string. The time string can be omitted as long ** as there is a year and date. */ static int parseDateOrTime( sqlite3_context *context, const char *zDate, DateTime *p ){ double r; if( parseYyyyMmDd(zDate,p)==0 ){ return 0; }else if( parseHhMmSs(zDate, p)==0 ){ return 0; }else if( sqlite3StrICmp(zDate,"now")==0){ return setDateTimeToCurrent(context, p); }else if( sqlite3AtoF(zDate, &r, sqlite3Strlen30(zDate), SQLITE_UTF8) ){ p->iJD = (sqlite3_int64)(r*86400000.0 + 0.5); p->validJD = 1; return 0; } return 1; } /* ** Compute the Year, Month, and Day from the julian day number. */ static void computeYMD(DateTime *p){ int Z, A, B, C, D, E, X1; if( p->validYMD ) return; if( !p->validJD ){ p->Y = 2000; p->M = 1; p->D = 1; }else{ Z = (int)((p->iJD + 43200000)/86400000); A = (int)((Z - 1867216.25)/36524.25); A = Z + 1 + A - (A/4); B = A + 1524; C = (int)((B - 122.1)/365.25); D = (36525*(C&32767))/100; E = (int)((B-D)/30.6001); X1 = (int)(30.6001*E); p->D = B - D - X1; p->M = E<14 ? E-1 : E-13; p->Y = p->M>2 ? C - 4716 : C - 4715; } p->validYMD = 1; } /* ** Compute the Hour, Minute, and Seconds from the julian day number. */ static void computeHMS(DateTime *p){ int s; if( p->validHMS ) return; computeJD(p); s = (int)((p->iJD + 43200000) % 86400000); p->s = s/1000.0; s = (int)p->s; p->s -= s; p->h = s/3600; s -= p->h*3600; p->m = s/60; p->s += s - p->m*60; p->validHMS = 1; } /* ** Compute both YMD and HMS */ static void computeYMD_HMS(DateTime *p){ computeYMD(p); computeHMS(p); } /* ** Clear the YMD and HMS and the TZ */ static void clearYMD_HMS_TZ(DateTime *p){ p->validYMD = 0; p->validHMS = 0; p->validTZ = 0; } #ifndef SQLITE_OMIT_LOCALTIME /* ** On recent Windows platforms, the localtime_s() function is available ** as part of the "Secure CRT". It is essentially equivalent to ** localtime_r() available under most POSIX platforms, except that the ** order of the parameters is reversed. ** ** See http://msdn.microsoft.com/en-us/library/a442x3ye(VS.80).aspx. ** ** If the user has not indicated to use localtime_r() or localtime_s() ** already, check for an MSVC build environment that provides ** localtime_s(). */ #if !HAVE_LOCALTIME_R && !HAVE_LOCALTIME_S \ && defined(_MSC_VER) && defined(_CRT_INSECURE_DEPRECATE) #undef HAVE_LOCALTIME_S #define HAVE_LOCALTIME_S 1 #endif /* ** The following routine implements the rough equivalent of localtime_r() ** using whatever operating-system specific localtime facility that ** is available. This routine returns 0 on success and ** non-zero on any kind of error. ** ** If the sqlite3GlobalConfig.bLocaltimeFault variable is true then this ** routine will always fail. ** ** EVIDENCE-OF: R-62172-00036 In this implementation, the standard C ** library function localtime_r() is used to assist in the calculation of ** local time. */ static int osLocaltime(time_t *t, struct tm *pTm){ int rc; #if !HAVE_LOCALTIME_R && !HAVE_LOCALTIME_S struct tm *pX; #if SQLITE_THREADSAFE>0 sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); #endif sqlite3_mutex_enter(mutex); pX = localtime(t); #ifndef SQLITE_OMIT_BUILTIN_TEST if( sqlite3GlobalConfig.bLocaltimeFault ) pX = 0; #endif if( pX ) *pTm = *pX; sqlite3_mutex_leave(mutex); rc = pX==0; #else #ifndef SQLITE_OMIT_BUILTIN_TEST if( sqlite3GlobalConfig.bLocaltimeFault ) return 1; #endif #if HAVE_LOCALTIME_R rc = localtime_r(t, pTm)==0; #else rc = localtime_s(pTm, t); #endif /* HAVE_LOCALTIME_R */ #endif /* HAVE_LOCALTIME_R || HAVE_LOCALTIME_S */ return rc; } #endif /* SQLITE_OMIT_LOCALTIME */ #ifndef SQLITE_OMIT_LOCALTIME /* ** Compute the difference (in milliseconds) between localtime and UTC ** (a.k.a. GMT) for the time value p where p is in UTC. If no error occurs, ** return this value and set *pRc to SQLITE_OK. ** ** Or, if an error does occur, set *pRc to SQLITE_ERROR. The returned value ** is undefined in this case. */ static sqlite3_int64 localtimeOffset( DateTime *p, /* Date at which to calculate offset */ sqlite3_context *pCtx, /* Write error here if one occurs */ int *pRc /* OUT: Error code. SQLITE_OK or ERROR */ ){ DateTime x, y; time_t t; struct tm sLocal; /* Initialize the contents of sLocal to avoid a compiler warning. */ memset(&sLocal, 0, sizeof(sLocal)); x = *p; computeYMD_HMS(&x); if( x.Y<1971 || x.Y>=2038 ){ /* EVIDENCE-OF: R-55269-29598 The localtime_r() C function normally only ** works for years between 1970 and 2037. For dates outside this range, ** SQLite attempts to map the year into an equivalent year within this ** range, do the calculation, then map the year back. */ x.Y = 2000; x.M = 1; x.D = 1; x.h = 0; x.m = 0; x.s = 0.0; } else { int s = (int)(x.s + 0.5); x.s = s; } x.tz = 0; x.validJD = 0; computeJD(&x); t = (time_t)(x.iJD/1000 - 21086676*(i64)10000); if( osLocaltime(&t, &sLocal) ){ sqlite3_result_error(pCtx, "local time unavailable", -1); *pRc = SQLITE_ERROR; return 0; } y.Y = sLocal.tm_year + 1900; y.M = sLocal.tm_mon + 1; y.D = sLocal.tm_mday; y.h = sLocal.tm_hour; y.m = sLocal.tm_min; y.s = sLocal.tm_sec; y.validYMD = 1; y.validHMS = 1; y.validJD = 0; y.validTZ = 0; computeJD(&y); *pRc = SQLITE_OK; return y.iJD - x.iJD; } #endif /* SQLITE_OMIT_LOCALTIME */ /* ** Process a modifier to a date-time stamp. The modifiers are ** as follows: ** ** NNN days ** NNN hours ** NNN minutes ** NNN.NNNN seconds ** NNN months ** NNN years ** start of month ** start of year ** start of week ** start of day ** weekday N ** unixepoch ** localtime ** utc ** ** Return 0 on success and 1 if there is any kind of error. If the error ** is in a system call (i.e. localtime()), then an error message is written ** to context pCtx. If the error is an unrecognized modifier, no error is ** written to pCtx. */ static int parseModifier(sqlite3_context *pCtx, const char *zMod, DateTime *p){ int rc = 1; int n; double r; char *z, zBuf[30]; z = zBuf; for(n=0; niJD += localtimeOffset(p, pCtx, &rc); clearYMD_HMS_TZ(p); } break; } #endif case 'u': { /* ** unixepoch ** ** Treat the current value of p->iJD as the number of ** seconds since 1970. Convert to a real julian day number. */ if( strcmp(z, "unixepoch")==0 && p->validJD ){ p->iJD = (p->iJD + 43200)/86400 + 21086676*(i64)10000000; clearYMD_HMS_TZ(p); rc = 0; } #ifndef SQLITE_OMIT_LOCALTIME else if( strcmp(z, "utc")==0 ){ if( p->tzSet==0 ){ sqlite3_int64 c1; computeJD(p); c1 = localtimeOffset(p, pCtx, &rc); if( rc==SQLITE_OK ){ p->iJD -= c1; clearYMD_HMS_TZ(p); p->iJD += c1 - localtimeOffset(p, pCtx, &rc); } p->tzSet = 1; }else{ rc = SQLITE_OK; } } #endif break; } case 'w': { /* ** weekday N ** ** Move the date to the same time on the next occurrence of ** weekday N where 0==Sunday, 1==Monday, and so forth. If the ** date is already on the appropriate weekday, this is a no-op. */ if( strncmp(z, "weekday ", 8)==0 && sqlite3AtoF(&z[8], &r, sqlite3Strlen30(&z[8]), SQLITE_UTF8) && (n=(int)r)==r && n>=0 && r<7 ){ sqlite3_int64 Z; computeYMD_HMS(p); p->validTZ = 0; p->validJD = 0; computeJD(p); Z = ((p->iJD + 129600000)/86400000) % 7; if( Z>n ) Z -= 7; p->iJD += (n - Z)*86400000; clearYMD_HMS_TZ(p); rc = 0; } break; } case 's': { /* ** start of TTTTT ** ** Move the date backwards to the beginning of the current day, ** or month or year. */ if( strncmp(z, "start of ", 9)!=0 ) break; z += 9; computeYMD(p); p->validHMS = 1; p->h = p->m = 0; p->s = 0.0; p->validTZ = 0; p->validJD = 0; if( strcmp(z,"month")==0 ){ p->D = 1; rc = 0; }else if( strcmp(z,"year")==0 ){ computeYMD(p); p->M = 1; p->D = 1; rc = 0; }else if( strcmp(z,"day")==0 ){ rc = 0; } break; } case '+': case '-': case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': { double rRounder; for(n=1; z[n] && z[n]!=':' && !sqlite3Isspace(z[n]); n++){} if( !sqlite3AtoF(z, &r, n, SQLITE_UTF8) ){ rc = 1; break; } if( z[n]==':' ){ /* A modifier of the form (+|-)HH:MM:SS.FFF adds (or subtracts) the ** specified number of hours, minutes, seconds, and fractional seconds ** to the time. The ".FFF" may be omitted. The ":SS.FFF" may be ** omitted. */ const char *z2 = z; DateTime tx; sqlite3_int64 day; if( !sqlite3Isdigit(*z2) ) z2++; memset(&tx, 0, sizeof(tx)); if( parseHhMmSs(z2, &tx) ) break; computeJD(&tx); tx.iJD -= 43200000; day = tx.iJD/86400000; tx.iJD -= day*86400000; if( z[0]=='-' ) tx.iJD = -tx.iJD; computeJD(p); clearYMD_HMS_TZ(p); p->iJD += tx.iJD; rc = 0; break; } z += n; while( sqlite3Isspace(*z) ) z++; n = sqlite3Strlen30(z); if( n>10 || n<3 ) break; if( z[n-1]=='s' ){ z[n-1] = 0; n--; } computeJD(p); rc = 0; rRounder = r<0 ? -0.5 : +0.5; if( n==3 && strcmp(z,"day")==0 ){ p->iJD += (sqlite3_int64)(r*86400000.0 + rRounder); }else if( n==4 && strcmp(z,"hour")==0 ){ p->iJD += (sqlite3_int64)(r*(86400000.0/24.0) + rRounder); }else if( n==6 && strcmp(z,"minute")==0 ){ p->iJD += (sqlite3_int64)(r*(86400000.0/(24.0*60.0)) + rRounder); }else if( n==6 && strcmp(z,"second")==0 ){ p->iJD += (sqlite3_int64)(r*(86400000.0/(24.0*60.0*60.0)) + rRounder); }else if( n==5 && strcmp(z,"month")==0 ){ int x, y; computeYMD_HMS(p); p->M += (int)r; x = p->M>0 ? (p->M-1)/12 : (p->M-12)/12; p->Y += x; p->M -= x*12; p->validJD = 0; computeJD(p); y = (int)r; if( y!=r ){ p->iJD += (sqlite3_int64)((r - y)*30.0*86400000.0 + rRounder); } }else if( n==4 && strcmp(z,"year")==0 ){ int y = (int)r; computeYMD_HMS(p); p->Y += y; p->validJD = 0; computeJD(p); if( y!=r ){ p->iJD += (sqlite3_int64)((r - y)*365.0*86400000.0 + rRounder); } }else{ rc = 1; } clearYMD_HMS_TZ(p); break; } default: { break; } } return rc; } /* ** Process time function arguments. argv[0] is a date-time stamp. ** argv[1] and following are modifiers. Parse them all and write ** the resulting time into the DateTime structure p. Return 0 ** on success and 1 if there are any errors. ** ** If there are zero parameters (if even argv[0] is undefined) ** then assume a default value of "now" for argv[0]. */ static int isDate( sqlite3_context *context, int argc, sqlite3_value **argv, DateTime *p ){ int i; const unsigned char *z; int eType; memset(p, 0, sizeof(*p)); if( argc==0 ){ return setDateTimeToCurrent(context, p); } if( (eType = sqlite3_value_type(argv[0]))==SQLITE_FLOAT || eType==SQLITE_INTEGER ){ p->iJD = (sqlite3_int64)(sqlite3_value_double(argv[0])*86400000.0 + 0.5); p->validJD = 1; }else{ z = sqlite3_value_text(argv[0]); if( !z || parseDateOrTime(context, (char*)z, p) ){ return 1; } } for(i=1; iaLimit[SQLITE_LIMIT_LENGTH]+1 ); testcase( n==(u64)db->aLimit[SQLITE_LIMIT_LENGTH] ); if( n(u64)db->aLimit[SQLITE_LIMIT_LENGTH] ){ sqlite3_result_error_toobig(context); return; }else{ z = sqlite3DbMallocRawNN(db, (int)n); if( z==0 ){ sqlite3_result_error_nomem(context); return; } } computeJD(&x); computeYMD_HMS(&x); for(i=j=0; zFmt[i]; i++){ if( zFmt[i]!='%' ){ z[j++] = zFmt[i]; }else{ i++; switch( zFmt[i] ){ case 'd': sqlite3_snprintf(3, &z[j],"%02d",x.D); j+=2; break; case 'f': { double s = x.s; if( s>59.999 ) s = 59.999; sqlite3_snprintf(7, &z[j],"%06.3f", s); j += sqlite3Strlen30(&z[j]); break; } case 'H': sqlite3_snprintf(3, &z[j],"%02d",x.h); j+=2; break; case 'W': /* Fall thru */ case 'j': { int nDay; /* Number of days since 1st day of year */ DateTime y = x; y.validJD = 0; y.M = 1; y.D = 1; computeJD(&y); nDay = (int)((x.iJD-y.iJD+43200000)/86400000); if( zFmt[i]=='W' ){ int wd; /* 0=Monday, 1=Tuesday, ... 6=Sunday */ wd = (int)(((x.iJD+43200000)/86400000)%7); sqlite3_snprintf(3, &z[j],"%02d",(nDay+7-wd)/7); j += 2; }else{ sqlite3_snprintf(4, &z[j],"%03d",nDay+1); j += 3; } break; } case 'J': { sqlite3_snprintf(20, &z[j],"%.16g",x.iJD/86400000.0); j+=sqlite3Strlen30(&z[j]); break; } case 'm': sqlite3_snprintf(3, &z[j],"%02d",x.M); j+=2; break; case 'M': sqlite3_snprintf(3, &z[j],"%02d",x.m); j+=2; break; case 's': { sqlite3_snprintf(30,&z[j],"%lld", (i64)(x.iJD/1000 - 21086676*(i64)10000)); j += sqlite3Strlen30(&z[j]); break; } case 'S': sqlite3_snprintf(3,&z[j],"%02d",(int)x.s); j+=2; break; case 'w': { z[j++] = (char)(((x.iJD+129600000)/86400000) % 7) + '0'; break; } case 'Y': { sqlite3_snprintf(5,&z[j],"%04d",x.Y); j+=sqlite3Strlen30(&z[j]); break; } default: z[j++] = '%'; break; } } } z[j] = 0; sqlite3_result_text(context, z, -1, z==zBuf ? SQLITE_TRANSIENT : SQLITE_DYNAMIC); } /* ** current_time() ** ** This function returns the same value as time('now'). */ static void ctimeFunc( sqlite3_context *context, int NotUsed, sqlite3_value **NotUsed2 ){ UNUSED_PARAMETER2(NotUsed, NotUsed2); timeFunc(context, 0, 0); } /* ** current_date() ** ** This function returns the same value as date('now'). */ static void cdateFunc( sqlite3_context *context, int NotUsed, sqlite3_value **NotUsed2 ){ UNUSED_PARAMETER2(NotUsed, NotUsed2); dateFunc(context, 0, 0); } /* ** current_timestamp() ** ** This function returns the same value as datetime('now'). */ static void ctimestampFunc( sqlite3_context *context, int NotUsed, sqlite3_value **NotUsed2 ){ UNUSED_PARAMETER2(NotUsed, NotUsed2); datetimeFunc(context, 0, 0); } #endif /* !defined(SQLITE_OMIT_DATETIME_FUNCS) */ #ifdef SQLITE_OMIT_DATETIME_FUNCS /* ** If the library is compiled to omit the full-scale date and time ** handling (to get a smaller binary), the following minimal version ** of the functions current_time(), current_date() and current_timestamp() ** are included instead. This is to support column declarations that ** include "DEFAULT CURRENT_TIME" etc. ** ** This function uses the C-library functions time(), gmtime() ** and strftime(). The format string to pass to strftime() is supplied ** as the user-data for the function. */ static void currentTimeFunc( sqlite3_context *context, int argc, sqlite3_value **argv ){ time_t t; char *zFormat = (char *)sqlite3_user_data(context); sqlite3_int64 iT; struct tm *pTm; struct tm sNow; char zBuf[20]; UNUSED_PARAMETER(argc); UNUSED_PARAMETER(argv); iT = sqlite3StmtCurrentTime(context); if( iT<=0 ) return; t = iT/1000 - 10000*(sqlite3_int64)21086676; #if HAVE_GMTIME_R pTm = gmtime_r(&t, &sNow); #else sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER)); pTm = gmtime(&t); if( pTm ) memcpy(&sNow, pTm, sizeof(sNow)); sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER)); #endif if( pTm ){ strftime(zBuf, 20, zFormat, &sNow); sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT); } } #endif /* ** This function registered all of the above C functions as SQL ** functions. This should be the only routine in this file with ** external linkage. */ SQLITE_PRIVATE void sqlite3RegisterDateTimeFunctions(void){ static FuncDef aDateTimeFuncs[] = { #ifndef SQLITE_OMIT_DATETIME_FUNCS DFUNCTION(julianday, -1, 0, 0, juliandayFunc ), DFUNCTION(date, -1, 0, 0, dateFunc ), DFUNCTION(time, -1, 0, 0, timeFunc ), DFUNCTION(datetime, -1, 0, 0, datetimeFunc ), DFUNCTION(strftime, -1, 0, 0, strftimeFunc ), DFUNCTION(current_time, 0, 0, 0, ctimeFunc ), DFUNCTION(current_timestamp, 0, 0, 0, ctimestampFunc), DFUNCTION(current_date, 0, 0, 0, cdateFunc ), #else STR_FUNCTION(current_time, 0, "%H:%M:%S", 0, currentTimeFunc), STR_FUNCTION(current_date, 0, "%Y-%m-%d", 0, currentTimeFunc), STR_FUNCTION(current_timestamp, 0, "%Y-%m-%d %H:%M:%S", 0, currentTimeFunc), #endif }; sqlite3InsertBuiltinFuncs(aDateTimeFuncs, ArraySize(aDateTimeFuncs)); } /************** End of date.c ************************************************/ /************** Begin file os.c **********************************************/ /* ** 2005 November 29 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ****************************************************************************** ** ** This file contains OS interface code that is common to all ** architectures. */ /* #include "sqliteInt.h" */ /* ** If we compile with the SQLITE_TEST macro set, then the following block ** of code will give us the ability to simulate a disk I/O error. This ** is used for testing the I/O recovery logic. */ #if defined(SQLITE_TEST) SQLITE_API int sqlite3_io_error_hit = 0; /* Total number of I/O Errors */ SQLITE_API int sqlite3_io_error_hardhit = 0; /* Number of non-benign errors */ SQLITE_API int sqlite3_io_error_pending = 0; /* Count down to first I/O error */ SQLITE_API int sqlite3_io_error_persist = 0; /* True if I/O errors persist */ SQLITE_API int sqlite3_io_error_benign = 0; /* True if errors are benign */ SQLITE_API int sqlite3_diskfull_pending = 0; SQLITE_API int sqlite3_diskfull = 0; #endif /* defined(SQLITE_TEST) */ /* ** When testing, also keep a count of the number of open files. */ #if defined(SQLITE_TEST) SQLITE_API int sqlite3_open_file_count = 0; #endif /* defined(SQLITE_TEST) */ /* ** The default SQLite sqlite3_vfs implementations do not allocate ** memory (actually, os_unix.c allocates a small amount of memory ** from within OsOpen()), but some third-party implementations may. ** So we test the effects of a malloc() failing and the sqlite3OsXXX() ** function returning SQLITE_IOERR_NOMEM using the DO_OS_MALLOC_TEST macro. ** ** The following functions are instrumented for malloc() failure ** testing: ** ** sqlite3OsRead() ** sqlite3OsWrite() ** sqlite3OsSync() ** sqlite3OsFileSize() ** sqlite3OsLock() ** sqlite3OsCheckReservedLock() ** sqlite3OsFileControl() ** sqlite3OsShmMap() ** sqlite3OsOpen() ** sqlite3OsDelete() ** sqlite3OsAccess() ** sqlite3OsFullPathname() ** */ #if defined(SQLITE_TEST) SQLITE_API int sqlite3_memdebug_vfs_oom_test = 1; #define DO_OS_MALLOC_TEST(x) \ if (sqlite3_memdebug_vfs_oom_test && (!x || !sqlite3JournalIsInMemory(x))) { \ void *pTstAlloc = sqlite3Malloc(10); \ if (!pTstAlloc) return SQLITE_IOERR_NOMEM_BKPT; \ sqlite3_free(pTstAlloc); \ } #else #define DO_OS_MALLOC_TEST(x) #endif /* ** The following routines are convenience wrappers around methods ** of the sqlite3_file object. This is mostly just syntactic sugar. All ** of this would be completely automatic if SQLite were coded using ** C++ instead of plain old C. */ SQLITE_PRIVATE void sqlite3OsClose(sqlite3_file *pId){ if( pId->pMethods ){ pId->pMethods->xClose(pId); pId->pMethods = 0; } } SQLITE_PRIVATE int sqlite3OsRead(sqlite3_file *id, void *pBuf, int amt, i64 offset){ DO_OS_MALLOC_TEST(id); return id->pMethods->xRead(id, pBuf, amt, offset); } SQLITE_PRIVATE int sqlite3OsWrite(sqlite3_file *id, const void *pBuf, int amt, i64 offset){ DO_OS_MALLOC_TEST(id); return id->pMethods->xWrite(id, pBuf, amt, offset); } SQLITE_PRIVATE int sqlite3OsTruncate(sqlite3_file *id, i64 size){ return id->pMethods->xTruncate(id, size); } SQLITE_PRIVATE int sqlite3OsSync(sqlite3_file *id, int flags){ DO_OS_MALLOC_TEST(id); return id->pMethods->xSync(id, flags); } SQLITE_PRIVATE int sqlite3OsFileSize(sqlite3_file *id, i64 *pSize){ DO_OS_MALLOC_TEST(id); return id->pMethods->xFileSize(id, pSize); } SQLITE_PRIVATE int sqlite3OsLock(sqlite3_file *id, int lockType){ DO_OS_MALLOC_TEST(id); return id->pMethods->xLock(id, lockType); } SQLITE_PRIVATE int sqlite3OsUnlock(sqlite3_file *id, int lockType){ return id->pMethods->xUnlock(id, lockType); } SQLITE_PRIVATE int sqlite3OsCheckReservedLock(sqlite3_file *id, int *pResOut){ DO_OS_MALLOC_TEST(id); return id->pMethods->xCheckReservedLock(id, pResOut); } /* ** Use sqlite3OsFileControl() when we are doing something that might fail ** and we need to know about the failures. Use sqlite3OsFileControlHint() ** when simply tossing information over the wall to the VFS and we do not ** really care if the VFS receives and understands the information since it ** is only a hint and can be safely ignored. The sqlite3OsFileControlHint() ** routine has no return value since the return value would be meaningless. */ SQLITE_PRIVATE int sqlite3OsFileControl(sqlite3_file *id, int op, void *pArg){ #ifdef SQLITE_TEST if( op!=SQLITE_FCNTL_COMMIT_PHASETWO ){ /* Faults are not injected into COMMIT_PHASETWO because, assuming SQLite ** is using a regular VFS, it is called after the corresponding ** transaction has been committed. Injecting a fault at this point ** confuses the test scripts - the COMMIT comand returns SQLITE_NOMEM ** but the transaction is committed anyway. ** ** The core must call OsFileControl() though, not OsFileControlHint(), ** as if a custom VFS (e.g. zipvfs) returns an error here, it probably ** means the commit really has failed and an error should be returned ** to the user. */ DO_OS_MALLOC_TEST(id); } #endif return id->pMethods->xFileControl(id, op, pArg); } SQLITE_PRIVATE void sqlite3OsFileControlHint(sqlite3_file *id, int op, void *pArg){ (void)id->pMethods->xFileControl(id, op, pArg); } SQLITE_PRIVATE int sqlite3OsSectorSize(sqlite3_file *id){ int (*xSectorSize)(sqlite3_file*) = id->pMethods->xSectorSize; return (xSectorSize ? xSectorSize(id) : SQLITE_DEFAULT_SECTOR_SIZE); } SQLITE_PRIVATE int sqlite3OsDeviceCharacteristics(sqlite3_file *id){ return id->pMethods->xDeviceCharacteristics(id); } SQLITE_PRIVATE int sqlite3OsShmLock(sqlite3_file *id, int offset, int n, int flags){ return id->pMethods->xShmLock(id, offset, n, flags); } SQLITE_PRIVATE void sqlite3OsShmBarrier(sqlite3_file *id){ id->pMethods->xShmBarrier(id); } SQLITE_PRIVATE int sqlite3OsShmUnmap(sqlite3_file *id, int deleteFlag){ return id->pMethods->xShmUnmap(id, deleteFlag); } SQLITE_PRIVATE int sqlite3OsShmMap( sqlite3_file *id, /* Database file handle */ int iPage, int pgsz, int bExtend, /* True to extend file if necessary */ void volatile **pp /* OUT: Pointer to mapping */ ){ DO_OS_MALLOC_TEST(id); return id->pMethods->xShmMap(id, iPage, pgsz, bExtend, pp); } #if SQLITE_MAX_MMAP_SIZE>0 /* The real implementation of xFetch and xUnfetch */ SQLITE_PRIVATE int sqlite3OsFetch(sqlite3_file *id, i64 iOff, int iAmt, void **pp){ DO_OS_MALLOC_TEST(id); return id->pMethods->xFetch(id, iOff, iAmt, pp); } SQLITE_PRIVATE int sqlite3OsUnfetch(sqlite3_file *id, i64 iOff, void *p){ return id->pMethods->xUnfetch(id, iOff, p); } #else /* No-op stubs to use when memory-mapped I/O is disabled */ SQLITE_PRIVATE int sqlite3OsFetch(sqlite3_file *id, i64 iOff, int iAmt, void **pp){ *pp = 0; return SQLITE_OK; } SQLITE_PRIVATE int sqlite3OsUnfetch(sqlite3_file *id, i64 iOff, void *p){ return SQLITE_OK; } #endif /* ** The next group of routines are convenience wrappers around the ** VFS methods. */ SQLITE_PRIVATE int sqlite3OsOpen( sqlite3_vfs *pVfs, const char *zPath, sqlite3_file *pFile, int flags, int *pFlagsOut ){ int rc; DO_OS_MALLOC_TEST(0); /* 0x87f7f is a mask of SQLITE_OPEN_ flags that are valid to be passed ** down into the VFS layer. Some SQLITE_OPEN_ flags (for example, ** SQLITE_OPEN_FULLMUTEX or SQLITE_OPEN_SHAREDCACHE) are blocked before ** reaching the VFS. */ rc = pVfs->xOpen(pVfs, zPath, pFile, flags & 0x87f7f, pFlagsOut); assert( rc==SQLITE_OK || pFile->pMethods==0 ); return rc; } SQLITE_PRIVATE int sqlite3OsDelete(sqlite3_vfs *pVfs, const char *zPath, int dirSync){ DO_OS_MALLOC_TEST(0); assert( dirSync==0 || dirSync==1 ); return pVfs->xDelete(pVfs, zPath, dirSync); } SQLITE_PRIVATE int sqlite3OsAccess( sqlite3_vfs *pVfs, const char *zPath, int flags, int *pResOut ){ DO_OS_MALLOC_TEST(0); return pVfs->xAccess(pVfs, zPath, flags, pResOut); } SQLITE_PRIVATE int sqlite3OsFullPathname( sqlite3_vfs *pVfs, const char *zPath, int nPathOut, char *zPathOut ){ DO_OS_MALLOC_TEST(0); zPathOut[0] = 0; return pVfs->xFullPathname(pVfs, zPath, nPathOut, zPathOut); } #ifndef SQLITE_OMIT_LOAD_EXTENSION SQLITE_PRIVATE void *sqlite3OsDlOpen(sqlite3_vfs *pVfs, const char *zPath){ return pVfs->xDlOpen(pVfs, zPath); } SQLITE_PRIVATE void sqlite3OsDlError(sqlite3_vfs *pVfs, int nByte, char *zBufOut){ pVfs->xDlError(pVfs, nByte, zBufOut); } SQLITE_PRIVATE void (*sqlite3OsDlSym(sqlite3_vfs *pVfs, void *pHdle, const char *zSym))(void){ return pVfs->xDlSym(pVfs, pHdle, zSym); } SQLITE_PRIVATE void sqlite3OsDlClose(sqlite3_vfs *pVfs, void *pHandle){ pVfs->xDlClose(pVfs, pHandle); } #endif /* SQLITE_OMIT_LOAD_EXTENSION */ SQLITE_PRIVATE int sqlite3OsRandomness(sqlite3_vfs *pVfs, int nByte, char *zBufOut){ return pVfs->xRandomness(pVfs, nByte, zBufOut); } SQLITE_PRIVATE int sqlite3OsSleep(sqlite3_vfs *pVfs, int nMicro){ return pVfs->xSleep(pVfs, nMicro); } SQLITE_PRIVATE int sqlite3OsGetLastError(sqlite3_vfs *pVfs){ return pVfs->xGetLastError ? pVfs->xGetLastError(pVfs, 0, 0) : 0; } SQLITE_PRIVATE int sqlite3OsCurrentTimeInt64(sqlite3_vfs *pVfs, sqlite3_int64 *pTimeOut){ int rc; /* IMPLEMENTATION-OF: R-49045-42493 SQLite will use the xCurrentTimeInt64() ** method to get the current date and time if that method is available ** (if iVersion is 2 or greater and the function pointer is not NULL) and ** will fall back to xCurrentTime() if xCurrentTimeInt64() is ** unavailable. */ if( pVfs->iVersion>=2 && pVfs->xCurrentTimeInt64 ){ rc = pVfs->xCurrentTimeInt64(pVfs, pTimeOut); }else{ double r; rc = pVfs->xCurrentTime(pVfs, &r); *pTimeOut = (sqlite3_int64)(r*86400000.0); } return rc; } SQLITE_PRIVATE int sqlite3OsOpenMalloc( sqlite3_vfs *pVfs, const char *zFile, sqlite3_file **ppFile, int flags, int *pOutFlags ){ int rc; sqlite3_file *pFile; pFile = (sqlite3_file *)sqlite3MallocZero(pVfs->szOsFile); if( pFile ){ rc = sqlite3OsOpen(pVfs, zFile, pFile, flags, pOutFlags); if( rc!=SQLITE_OK ){ sqlite3_free(pFile); }else{ *ppFile = pFile; } }else{ rc = SQLITE_NOMEM_BKPT; } return rc; } SQLITE_PRIVATE void sqlite3OsCloseFree(sqlite3_file *pFile){ assert( pFile ); sqlite3OsClose(pFile); sqlite3_free(pFile); } /* ** This function is a wrapper around the OS specific implementation of ** sqlite3_os_init(). The purpose of the wrapper is to provide the ** ability to simulate a malloc failure, so that the handling of an ** error in sqlite3_os_init() by the upper layers can be tested. */ SQLITE_PRIVATE int sqlite3OsInit(void){ void *p = sqlite3_malloc(10); if( p==0 ) return SQLITE_NOMEM_BKPT; sqlite3_free(p); return sqlite3_os_init(); } /* ** The list of all registered VFS implementations. */ static sqlite3_vfs * SQLITE_WSD vfsList = 0; #define vfsList GLOBAL(sqlite3_vfs *, vfsList) /* ** Locate a VFS by name. If no name is given, simply return the ** first VFS on the list. */ SQLITE_API sqlite3_vfs *sqlite3_vfs_find(const char *zVfs){ sqlite3_vfs *pVfs = 0; #if SQLITE_THREADSAFE sqlite3_mutex *mutex; #endif #ifndef SQLITE_OMIT_AUTOINIT int rc = sqlite3_initialize(); if( rc ) return 0; #endif #if SQLITE_THREADSAFE mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); #endif sqlite3_mutex_enter(mutex); for(pVfs = vfsList; pVfs; pVfs=pVfs->pNext){ if( zVfs==0 ) break; if( strcmp(zVfs, pVfs->zName)==0 ) break; } sqlite3_mutex_leave(mutex); return pVfs; } /* ** Unlink a VFS from the linked list */ static void vfsUnlink(sqlite3_vfs *pVfs){ assert( sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER)) ); if( pVfs==0 ){ /* No-op */ }else if( vfsList==pVfs ){ vfsList = pVfs->pNext; }else if( vfsList ){ sqlite3_vfs *p = vfsList; while( p->pNext && p->pNext!=pVfs ){ p = p->pNext; } if( p->pNext==pVfs ){ p->pNext = pVfs->pNext; } } } /* ** Register a VFS with the system. It is harmless to register the same ** VFS multiple times. The new VFS becomes the default if makeDflt is ** true. */ SQLITE_API int sqlite3_vfs_register(sqlite3_vfs *pVfs, int makeDflt){ MUTEX_LOGIC(sqlite3_mutex *mutex;) #ifndef SQLITE_OMIT_AUTOINIT int rc = sqlite3_initialize(); if( rc ) return rc; #endif #ifdef SQLITE_ENABLE_API_ARMOR if( pVfs==0 ) return SQLITE_MISUSE_BKPT; #endif MUTEX_LOGIC( mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); ) sqlite3_mutex_enter(mutex); vfsUnlink(pVfs); if( makeDflt || vfsList==0 ){ pVfs->pNext = vfsList; vfsList = pVfs; }else{ pVfs->pNext = vfsList->pNext; vfsList->pNext = pVfs; } assert(vfsList); sqlite3_mutex_leave(mutex); return SQLITE_OK; } /* ** Unregister a VFS so that it is no longer accessible. */ SQLITE_API int sqlite3_vfs_unregister(sqlite3_vfs *pVfs){ #if SQLITE_THREADSAFE sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); #endif sqlite3_mutex_enter(mutex); vfsUnlink(pVfs); sqlite3_mutex_leave(mutex); return SQLITE_OK; } /************** End of os.c **************************************************/ /************** Begin file fault.c *******************************************/ /* ** 2008 Jan 22 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ************************************************************************* ** ** This file contains code to support the concept of "benign" ** malloc failures (when the xMalloc() or xRealloc() method of the ** sqlite3_mem_methods structure fails to allocate a block of memory ** and returns 0). ** ** Most malloc failures are non-benign. After they occur, SQLite ** abandons the current operation and returns an error code (usually ** SQLITE_NOMEM) to the user. However, sometimes a fault is not necessarily ** fatal. For example, if a malloc fails while resizing a hash table, this ** is completely recoverable simply by not carrying out the resize. The ** hash table will continue to function normally. So a malloc failure ** during a hash table resize is a benign fault. */ /* #include "sqliteInt.h" */ #ifndef SQLITE_OMIT_BUILTIN_TEST /* ** Global variables. */ typedef struct BenignMallocHooks BenignMallocHooks; static SQLITE_WSD struct BenignMallocHooks { void (*xBenignBegin)(void); void (*xBenignEnd)(void); } sqlite3Hooks = { 0, 0 }; /* The "wsdHooks" macro will resolve to the appropriate BenignMallocHooks ** structure. If writable static data is unsupported on the target, ** we have to locate the state vector at run-time. In the more common ** case where writable static data is supported, wsdHooks can refer directly ** to the "sqlite3Hooks" state vector declared above. */ #ifdef SQLITE_OMIT_WSD # define wsdHooksInit \ BenignMallocHooks *x = &GLOBAL(BenignMallocHooks,sqlite3Hooks) # define wsdHooks x[0] #else # define wsdHooksInit # define wsdHooks sqlite3Hooks #endif /* ** Register hooks to call when sqlite3BeginBenignMalloc() and ** sqlite3EndBenignMalloc() are called, respectively. */ SQLITE_PRIVATE void sqlite3BenignMallocHooks( void (*xBenignBegin)(void), void (*xBenignEnd)(void) ){ wsdHooksInit; wsdHooks.xBenignBegin = xBenignBegin; wsdHooks.xBenignEnd = xBenignEnd; } /* ** This (sqlite3EndBenignMalloc()) is called by SQLite code to indicate that ** subsequent malloc failures are benign. A call to sqlite3EndBenignMalloc() ** indicates that subsequent malloc failures are non-benign. */ SQLITE_PRIVATE void sqlite3BeginBenignMalloc(void){ wsdHooksInit; if( wsdHooks.xBenignBegin ){ wsdHooks.xBenignBegin(); } } SQLITE_PRIVATE void sqlite3EndBenignMalloc(void){ wsdHooksInit; if( wsdHooks.xBenignEnd ){ wsdHooks.xBenignEnd(); } } #endif /* #ifndef SQLITE_OMIT_BUILTIN_TEST */ /************** End of fault.c ***********************************************/ /************** Begin file mem0.c ********************************************/ /* ** 2008 October 28 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ************************************************************************* ** ** This file contains a no-op memory allocation drivers for use when ** SQLITE_ZERO_MALLOC is defined. The allocation drivers implemented ** here always fail. SQLite will not operate with these drivers. These ** are merely placeholders. Real drivers must be substituted using ** sqlite3_config() before SQLite will operate. */ /* #include "sqliteInt.h" */ /* ** This version of the memory allocator is the default. It is ** used when no other memory allocator is specified using compile-time ** macros. */ #ifdef SQLITE_ZERO_MALLOC /* ** No-op versions of all memory allocation routines */ static void *sqlite3MemMalloc(int nByte){ return 0; } static void sqlite3MemFree(void *pPrior){ return; } static void *sqlite3MemRealloc(void *pPrior, int nByte){ return 0; } static int sqlite3MemSize(void *pPrior){ return 0; } static int sqlite3MemRoundup(int n){ return n; } static int sqlite3MemInit(void *NotUsed){ return SQLITE_OK; } static void sqlite3MemShutdown(void *NotUsed){ return; } /* ** This routine is the only routine in this file with external linkage. ** ** Populate the low-level memory allocation function pointers in ** sqlite3GlobalConfig.m with pointers to the routines in this file. */ SQLITE_PRIVATE void sqlite3MemSetDefault(void){ static const sqlite3_mem_methods defaultMethods = { sqlite3MemMalloc, sqlite3MemFree, sqlite3MemRealloc, sqlite3MemSize, sqlite3MemRoundup, sqlite3MemInit, sqlite3MemShutdown, 0 }; sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods); } #endif /* SQLITE_ZERO_MALLOC */ /************** End of mem0.c ************************************************/ /************** Begin file mem1.c ********************************************/ /* ** 2007 August 14 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ************************************************************************* ** ** This file contains low-level memory allocation drivers for when ** SQLite will use the standard C-library malloc/realloc/free interface ** to obtain the memory it needs. ** ** This file contains implementations of the low-level memory allocation ** routines specified in the sqlite3_mem_methods object. The content of ** this file is only used if SQLITE_SYSTEM_MALLOC is defined. The ** SQLITE_SYSTEM_MALLOC macro is defined automatically if neither the ** SQLITE_MEMDEBUG nor the SQLITE_WIN32_MALLOC macros are defined. The ** default configuration is to use memory allocation routines in this ** file. ** ** C-preprocessor macro summary: ** ** HAVE_MALLOC_USABLE_SIZE The configure script sets this symbol if ** the malloc_usable_size() interface exists ** on the target platform. Or, this symbol ** can be set manually, if desired. ** If an equivalent interface exists by ** a different name, using a separate -D ** option to rename it. ** ** SQLITE_WITHOUT_ZONEMALLOC Some older macs lack support for the zone ** memory allocator. Set this symbol to enable ** building on older macs. ** ** SQLITE_WITHOUT_MSIZE Set this symbol to disable the use of ** _msize() on windows systems. This might ** be necessary when compiling for Delphi, ** for example. */ /* #include "sqliteInt.h" */ /* ** This version of the memory allocator is the default. It is ** used when no other memory allocator is specified using compile-time ** macros. */ #ifdef SQLITE_SYSTEM_MALLOC #if defined(__APPLE__) && !defined(SQLITE_WITHOUT_ZONEMALLOC) /* ** Use the zone allocator available on apple products unless the ** SQLITE_WITHOUT_ZONEMALLOC symbol is defined. */ #include #include #include static malloc_zone_t* _sqliteZone_; #define SQLITE_MALLOC(x) malloc_zone_malloc(_sqliteZone_, (x)) #define SQLITE_FREE(x) malloc_zone_free(_sqliteZone_, (x)); #define SQLITE_REALLOC(x,y) malloc_zone_realloc(_sqliteZone_, (x), (y)) #define SQLITE_MALLOCSIZE(x) \ (_sqliteZone_ ? _sqliteZone_->size(_sqliteZone_,x) : malloc_size(x)) #else /* if not __APPLE__ */ /* ** Use standard C library malloc and free on non-Apple systems. ** Also used by Apple systems if SQLITE_WITHOUT_ZONEMALLOC is defined. */ #define SQLITE_MALLOC(x) malloc(x) #define SQLITE_FREE(x) free(x) #define SQLITE_REALLOC(x,y) realloc((x),(y)) /* ** The malloc.h header file is needed for malloc_usable_size() function ** on some systems (e.g. Linux). */ #if HAVE_MALLOC_H && HAVE_MALLOC_USABLE_SIZE # define SQLITE_USE_MALLOC_H 1 # define SQLITE_USE_MALLOC_USABLE_SIZE 1 /* ** The MSVCRT has malloc_usable_size(), but it is called _msize(). The ** use of _msize() is automatic, but can be disabled by compiling with ** -DSQLITE_WITHOUT_MSIZE. Using the _msize() function also requires ** the malloc.h header file. */ #elif defined(_MSC_VER) && !defined(SQLITE_WITHOUT_MSIZE) # define SQLITE_USE_MALLOC_H # define SQLITE_USE_MSIZE #endif /* ** Include the malloc.h header file, if necessary. Also set define macro ** SQLITE_MALLOCSIZE to the appropriate function name, which is _msize() ** for MSVC and malloc_usable_size() for most other systems (e.g. Linux). ** The memory size function can always be overridden manually by defining ** the macro SQLITE_MALLOCSIZE to the desired function name. */ #if defined(SQLITE_USE_MALLOC_H) # include # if defined(SQLITE_USE_MALLOC_USABLE_SIZE) # if !defined(SQLITE_MALLOCSIZE) # define SQLITE_MALLOCSIZE(x) malloc_usable_size(x) # endif # elif defined(SQLITE_USE_MSIZE) # if !defined(SQLITE_MALLOCSIZE) # define SQLITE_MALLOCSIZE _msize # endif # endif #endif /* defined(SQLITE_USE_MALLOC_H) */ #endif /* __APPLE__ or not __APPLE__ */ /* ** Like malloc(), but remember the size of the allocation ** so that we can find it later using sqlite3MemSize(). ** ** For this low-level routine, we are guaranteed that nByte>0 because ** cases of nByte<=0 will be intercepted and dealt with by higher level ** routines. */ static void *sqlite3MemMalloc(int nByte){ #ifdef SQLITE_MALLOCSIZE void *p = SQLITE_MALLOC( nByte ); if( p==0 ){ testcase( sqlite3GlobalConfig.xLog!=0 ); sqlite3_log(SQLITE_NOMEM, "failed to allocate %u bytes of memory", nByte); } return p; #else sqlite3_int64 *p; assert( nByte>0 ); nByte = ROUND8(nByte); p = SQLITE_MALLOC( nByte+8 ); if( p ){ p[0] = nByte; p++; }else{ testcase( sqlite3GlobalConfig.xLog!=0 ); sqlite3_log(SQLITE_NOMEM, "failed to allocate %u bytes of memory", nByte); } return (void *)p; #endif } /* ** Like free() but works for allocations obtained from sqlite3MemMalloc() ** or sqlite3MemRealloc(). ** ** For this low-level routine, we already know that pPrior!=0 since ** cases where pPrior==0 will have been intecepted and dealt with ** by higher-level routines. */ static void sqlite3MemFree(void *pPrior){ #ifdef SQLITE_MALLOCSIZE SQLITE_FREE(pPrior); #else sqlite3_int64 *p = (sqlite3_int64*)pPrior; assert( pPrior!=0 ); p--; SQLITE_FREE(p); #endif } /* ** Report the allocated size of a prior return from xMalloc() ** or xRealloc(). */ static int sqlite3MemSize(void *pPrior){ #ifdef SQLITE_MALLOCSIZE assert( pPrior!=0 ); return (int)SQLITE_MALLOCSIZE(pPrior); #else sqlite3_int64 *p; assert( pPrior!=0 ); p = (sqlite3_int64*)pPrior; p--; return (int)p[0]; #endif } /* ** Like realloc(). Resize an allocation previously obtained from ** sqlite3MemMalloc(). ** ** For this low-level interface, we know that pPrior!=0. Cases where ** pPrior==0 while have been intercepted by higher-level routine and ** redirected to xMalloc. Similarly, we know that nByte>0 because ** cases where nByte<=0 will have been intercepted by higher-level ** routines and redirected to xFree. */ static void *sqlite3MemRealloc(void *pPrior, int nByte){ #ifdef SQLITE_MALLOCSIZE void *p = SQLITE_REALLOC(pPrior, nByte); if( p==0 ){ testcase( sqlite3GlobalConfig.xLog!=0 ); sqlite3_log(SQLITE_NOMEM, "failed memory resize %u to %u bytes", SQLITE_MALLOCSIZE(pPrior), nByte); } return p; #else sqlite3_int64 *p = (sqlite3_int64*)pPrior; assert( pPrior!=0 && nByte>0 ); assert( nByte==ROUND8(nByte) ); /* EV: R-46199-30249 */ p--; p = SQLITE_REALLOC(p, nByte+8 ); if( p ){ p[0] = nByte; p++; }else{ testcase( sqlite3GlobalConfig.xLog!=0 ); sqlite3_log(SQLITE_NOMEM, "failed memory resize %u to %u bytes", sqlite3MemSize(pPrior), nByte); } return (void*)p; #endif } /* ** Round up a request size to the next valid allocation size. */ static int sqlite3MemRoundup(int n){ return ROUND8(n); } /* ** Initialize this module. */ static int sqlite3MemInit(void *NotUsed){ #if defined(__APPLE__) && !defined(SQLITE_WITHOUT_ZONEMALLOC) int cpuCount; size_t len; if( _sqliteZone_ ){ return SQLITE_OK; } len = sizeof(cpuCount); /* One usually wants to use hw.acctivecpu for MT decisions, but not here */ sysctlbyname("hw.ncpu", &cpuCount, &len, NULL, 0); if( cpuCount>1 ){ /* defer MT decisions to system malloc */ _sqliteZone_ = malloc_default_zone(); }else{ /* only 1 core, use our own zone to contention over global locks, ** e.g. we have our own dedicated locks */ bool success; malloc_zone_t* newzone = malloc_create_zone(4096, 0); malloc_set_zone_name(newzone, "Sqlite_Heap"); do{ success = OSAtomicCompareAndSwapPtrBarrier(NULL, newzone, (void * volatile *)&_sqliteZone_); }while(!_sqliteZone_); if( !success ){ /* somebody registered a zone first */ malloc_destroy_zone(newzone); } } #endif UNUSED_PARAMETER(NotUsed); return SQLITE_OK; } /* ** Deinitialize this module. */ static void sqlite3MemShutdown(void *NotUsed){ UNUSED_PARAMETER(NotUsed); return; } /* ** This routine is the only routine in this file with external linkage. ** ** Populate the low-level memory allocation function pointers in ** sqlite3GlobalConfig.m with pointers to the routines in this file. */ SQLITE_PRIVATE void sqlite3MemSetDefault(void){ static const sqlite3_mem_methods defaultMethods = { sqlite3MemMalloc, sqlite3MemFree, sqlite3MemRealloc, sqlite3MemSize, sqlite3MemRoundup, sqlite3MemInit, sqlite3MemShutdown, 0 }; sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods); } #endif /* SQLITE_SYSTEM_MALLOC */ /************** End of mem1.c ************************************************/ /************** Begin file mem2.c ********************************************/ /* ** 2007 August 15 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ************************************************************************* ** ** This file contains low-level memory allocation drivers for when ** SQLite will use the standard C-library malloc/realloc/free interface ** to obtain the memory it needs while adding lots of additional debugging ** information to each allocation in order to help detect and fix memory ** leaks and memory usage errors. ** ** This file contains implementations of the low-level memory allocation ** routines specified in the sqlite3_mem_methods object. */ /* #include "sqliteInt.h" */ /* ** This version of the memory allocator is used only if the ** SQLITE_MEMDEBUG macro is defined */ #ifdef SQLITE_MEMDEBUG /* ** The backtrace functionality is only available with GLIBC */ #ifdef __GLIBC__ extern int backtrace(void**,int); extern void backtrace_symbols_fd(void*const*,int,int); #else # define backtrace(A,B) 1 # define backtrace_symbols_fd(A,B,C) #endif /* #include */ /* ** Each memory allocation looks like this: ** ** ------------------------------------------------------------------------ ** | Title | backtrace pointers | MemBlockHdr | allocation | EndGuard | ** ------------------------------------------------------------------------ ** ** The application code sees only a pointer to the allocation. We have ** to back up from the allocation pointer to find the MemBlockHdr. The ** MemBlockHdr tells us the size of the allocation and the number of ** backtrace pointers. There is also a guard word at the end of the ** MemBlockHdr. */ struct MemBlockHdr { i64 iSize; /* Size of this allocation */ struct MemBlockHdr *pNext, *pPrev; /* Linked list of all unfreed memory */ char nBacktrace; /* Number of backtraces on this alloc */ char nBacktraceSlots; /* Available backtrace slots */ u8 nTitle; /* Bytes of title; includes '\0' */ u8 eType; /* Allocation type code */ int iForeGuard; /* Guard word for sanity */ }; /* ** Guard words */ #define FOREGUARD 0x80F5E153 #define REARGUARD 0xE4676B53 /* ** Number of malloc size increments to track. */ #define NCSIZE 1000 /* ** All of the static variables used by this module are collected ** into a single structure named "mem". This is to keep the ** static variables organized and to reduce namespace pollution ** when this module is combined with other in the amalgamation. */ static struct { /* ** Mutex to control access to the memory allocation subsystem. */ sqlite3_mutex *mutex; /* ** Head and tail of a linked list of all outstanding allocations */ struct MemBlockHdr *pFirst; struct MemBlockHdr *pLast; /* ** The number of levels of backtrace to save in new allocations. */ int nBacktrace; void (*xBacktrace)(int, int, void **); /* ** Title text to insert in front of each block */ int nTitle; /* Bytes of zTitle to save. Includes '\0' and padding */ char zTitle[100]; /* The title text */ /* ** sqlite3MallocDisallow() increments the following counter. ** sqlite3MallocAllow() decrements it. */ int disallow; /* Do not allow memory allocation */ /* ** Gather statistics on the sizes of memory allocations. ** nAlloc[i] is the number of allocation attempts of i*8 ** bytes. i==NCSIZE is the number of allocation attempts for ** sizes more than NCSIZE*8 bytes. */ int nAlloc[NCSIZE]; /* Total number of allocations */ int nCurrent[NCSIZE]; /* Current number of allocations */ int mxCurrent[NCSIZE]; /* Highwater mark for nCurrent */ } mem; /* ** Adjust memory usage statistics */ static void adjustStats(int iSize, int increment){ int i = ROUND8(iSize)/8; if( i>NCSIZE-1 ){ i = NCSIZE - 1; } if( increment>0 ){ mem.nAlloc[i]++; mem.nCurrent[i]++; if( mem.nCurrent[i]>mem.mxCurrent[i] ){ mem.mxCurrent[i] = mem.nCurrent[i]; } }else{ mem.nCurrent[i]--; assert( mem.nCurrent[i]>=0 ); } } /* ** Given an allocation, find the MemBlockHdr for that allocation. ** ** This routine checks the guards at either end of the allocation and ** if they are incorrect it asserts. */ static struct MemBlockHdr *sqlite3MemsysGetHeader(void *pAllocation){ struct MemBlockHdr *p; int *pInt; u8 *pU8; int nReserve; p = (struct MemBlockHdr*)pAllocation; p--; assert( p->iForeGuard==(int)FOREGUARD ); nReserve = ROUND8(p->iSize); pInt = (int*)pAllocation; pU8 = (u8*)pAllocation; assert( pInt[nReserve/sizeof(int)]==(int)REARGUARD ); /* This checks any of the "extra" bytes allocated due ** to rounding up to an 8 byte boundary to ensure ** they haven't been overwritten. */ while( nReserve-- > p->iSize ) assert( pU8[nReserve]==0x65 ); return p; } /* ** Return the number of bytes currently allocated at address p. */ static int sqlite3MemSize(void *p){ struct MemBlockHdr *pHdr; if( !p ){ return 0; } pHdr = sqlite3MemsysGetHeader(p); return (int)pHdr->iSize; } /* ** Initialize the memory allocation subsystem. */ static int sqlite3MemInit(void *NotUsed){ UNUSED_PARAMETER(NotUsed); assert( (sizeof(struct MemBlockHdr)&7) == 0 ); if( !sqlite3GlobalConfig.bMemstat ){ /* If memory status is enabled, then the malloc.c wrapper will already ** hold the STATIC_MEM mutex when the routines here are invoked. */ mem.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM); } return SQLITE_OK; } /* ** Deinitialize the memory allocation subsystem. */ static void sqlite3MemShutdown(void *NotUsed){ UNUSED_PARAMETER(NotUsed); mem.mutex = 0; } /* ** Round up a request size to the next valid allocation size. */ static int sqlite3MemRoundup(int n){ return ROUND8(n); } /* ** Fill a buffer with pseudo-random bytes. This is used to preset ** the content of a new memory allocation to unpredictable values and ** to clear the content of a freed allocation to unpredictable values. */ static void randomFill(char *pBuf, int nByte){ unsigned int x, y, r; x = SQLITE_PTR_TO_INT(pBuf); y = nByte | 1; while( nByte >= 4 ){ x = (x>>1) ^ (-(int)(x&1) & 0xd0000001); y = y*1103515245 + 12345; r = x ^ y; *(int*)pBuf = r; pBuf += 4; nByte -= 4; } while( nByte-- > 0 ){ x = (x>>1) ^ (-(int)(x&1) & 0xd0000001); y = y*1103515245 + 12345; r = x ^ y; *(pBuf++) = r & 0xff; } } /* ** Allocate nByte bytes of memory. */ static void *sqlite3MemMalloc(int nByte){ struct MemBlockHdr *pHdr; void **pBt; char *z; int *pInt; void *p = 0; int totalSize; int nReserve; sqlite3_mutex_enter(mem.mutex); assert( mem.disallow==0 ); nReserve = ROUND8(nByte); totalSize = nReserve + sizeof(*pHdr) + sizeof(int) + mem.nBacktrace*sizeof(void*) + mem.nTitle; p = malloc(totalSize); if( p ){ z = p; pBt = (void**)&z[mem.nTitle]; pHdr = (struct MemBlockHdr*)&pBt[mem.nBacktrace]; pHdr->pNext = 0; pHdr->pPrev = mem.pLast; if( mem.pLast ){ mem.pLast->pNext = pHdr; }else{ mem.pFirst = pHdr; } mem.pLast = pHdr; pHdr->iForeGuard = FOREGUARD; pHdr->eType = MEMTYPE_HEAP; pHdr->nBacktraceSlots = mem.nBacktrace; pHdr->nTitle = mem.nTitle; if( mem.nBacktrace ){ void *aAddr[40]; pHdr->nBacktrace = backtrace(aAddr, mem.nBacktrace+1)-1; memcpy(pBt, &aAddr[1], pHdr->nBacktrace*sizeof(void*)); assert(pBt[0]); if( mem.xBacktrace ){ mem.xBacktrace(nByte, pHdr->nBacktrace-1, &aAddr[1]); } }else{ pHdr->nBacktrace = 0; } if( mem.nTitle ){ memcpy(z, mem.zTitle, mem.nTitle); } pHdr->iSize = nByte; adjustStats(nByte, +1); pInt = (int*)&pHdr[1]; pInt[nReserve/sizeof(int)] = REARGUARD; randomFill((char*)pInt, nByte); memset(((char*)pInt)+nByte, 0x65, nReserve-nByte); p = (void*)pInt; } sqlite3_mutex_leave(mem.mutex); return p; } /* ** Free memory. */ static void sqlite3MemFree(void *pPrior){ struct MemBlockHdr *pHdr; void **pBt; char *z; assert( sqlite3GlobalConfig.bMemstat || sqlite3GlobalConfig.bCoreMutex==0 || mem.mutex!=0 ); pHdr = sqlite3MemsysGetHeader(pPrior); pBt = (void**)pHdr; pBt -= pHdr->nBacktraceSlots; sqlite3_mutex_enter(mem.mutex); if( pHdr->pPrev ){ assert( pHdr->pPrev->pNext==pHdr ); pHdr->pPrev->pNext = pHdr->pNext; }else{ assert( mem.pFirst==pHdr ); mem.pFirst = pHdr->pNext; } if( pHdr->pNext ){ assert( pHdr->pNext->pPrev==pHdr ); pHdr->pNext->pPrev = pHdr->pPrev; }else{ assert( mem.pLast==pHdr ); mem.pLast = pHdr->pPrev; } z = (char*)pBt; z -= pHdr->nTitle; adjustStats((int)pHdr->iSize, -1); randomFill(z, sizeof(void*)*pHdr->nBacktraceSlots + sizeof(*pHdr) + (int)pHdr->iSize + sizeof(int) + pHdr->nTitle); free(z); sqlite3_mutex_leave(mem.mutex); } /* ** Change the size of an existing memory allocation. ** ** For this debugging implementation, we *always* make a copy of the ** allocation into a new place in memory. In this way, if the ** higher level code is using pointer to the old allocation, it is ** much more likely to break and we are much more liking to find ** the error. */ static void *sqlite3MemRealloc(void *pPrior, int nByte){ struct MemBlockHdr *pOldHdr; void *pNew; assert( mem.disallow==0 ); assert( (nByte & 7)==0 ); /* EV: R-46199-30249 */ pOldHdr = sqlite3MemsysGetHeader(pPrior); pNew = sqlite3MemMalloc(nByte); if( pNew ){ memcpy(pNew, pPrior, (int)(nByteiSize ? nByte : pOldHdr->iSize)); if( nByte>pOldHdr->iSize ){ randomFill(&((char*)pNew)[pOldHdr->iSize], nByte - (int)pOldHdr->iSize); } sqlite3MemFree(pPrior); } return pNew; } /* ** Populate the low-level memory allocation function pointers in ** sqlite3GlobalConfig.m with pointers to the routines in this file. */ SQLITE_PRIVATE void sqlite3MemSetDefault(void){ static const sqlite3_mem_methods defaultMethods = { sqlite3MemMalloc, sqlite3MemFree, sqlite3MemRealloc, sqlite3MemSize, sqlite3MemRoundup, sqlite3MemInit, sqlite3MemShutdown, 0 }; sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods); } /* ** Set the "type" of an allocation. */ SQLITE_PRIVATE void sqlite3MemdebugSetType(void *p, u8 eType){ if( p && sqlite3GlobalConfig.m.xMalloc==sqlite3MemMalloc ){ struct MemBlockHdr *pHdr; pHdr = sqlite3MemsysGetHeader(p); assert( pHdr->iForeGuard==FOREGUARD ); pHdr->eType = eType; } } /* ** Return TRUE if the mask of type in eType matches the type of the ** allocation p. Also return true if p==NULL. ** ** This routine is designed for use within an assert() statement, to ** verify the type of an allocation. For example: ** ** assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) ); */ SQLITE_PRIVATE int sqlite3MemdebugHasType(void *p, u8 eType){ int rc = 1; if( p && sqlite3GlobalConfig.m.xMalloc==sqlite3MemMalloc ){ struct MemBlockHdr *pHdr; pHdr = sqlite3MemsysGetHeader(p); assert( pHdr->iForeGuard==FOREGUARD ); /* Allocation is valid */ if( (pHdr->eType&eType)==0 ){ rc = 0; } } return rc; } /* ** Return TRUE if the mask of type in eType matches no bits of the type of the ** allocation p. Also return true if p==NULL. ** ** This routine is designed for use within an assert() statement, to ** verify the type of an allocation. For example: ** ** assert( sqlite3MemdebugNoType(p, MEMTYPE_LOOKASIDE) ); */ SQLITE_PRIVATE int sqlite3MemdebugNoType(void *p, u8 eType){ int rc = 1; if( p && sqlite3GlobalConfig.m.xMalloc==sqlite3MemMalloc ){ struct MemBlockHdr *pHdr; pHdr = sqlite3MemsysGetHeader(p); assert( pHdr->iForeGuard==FOREGUARD ); /* Allocation is valid */ if( (pHdr->eType&eType)!=0 ){ rc = 0; } } return rc; } /* ** Set the number of backtrace levels kept for each allocation. ** A value of zero turns off backtracing. The number is always rounded ** up to a multiple of 2. */ SQLITE_PRIVATE void sqlite3MemdebugBacktrace(int depth){ if( depth<0 ){ depth = 0; } if( depth>20 ){ depth = 20; } depth = (depth+1)&0xfe; mem.nBacktrace = depth; } SQLITE_PRIVATE void sqlite3MemdebugBacktraceCallback(void (*xBacktrace)(int, int, void **)){ mem.xBacktrace = xBacktrace; } /* ** Set the title string for subsequent allocations. */ SQLITE_PRIVATE void sqlite3MemdebugSettitle(const char *zTitle){ unsigned int n = sqlite3Strlen30(zTitle) + 1; sqlite3_mutex_enter(mem.mutex); if( n>=sizeof(mem.zTitle) ) n = sizeof(mem.zTitle)-1; memcpy(mem.zTitle, zTitle, n); mem.zTitle[n] = 0; mem.nTitle = ROUND8(n); sqlite3_mutex_leave(mem.mutex); } SQLITE_PRIVATE void sqlite3MemdebugSync(){ struct MemBlockHdr *pHdr; for(pHdr=mem.pFirst; pHdr; pHdr=pHdr->pNext){ void **pBt = (void**)pHdr; pBt -= pHdr->nBacktraceSlots; mem.xBacktrace((int)pHdr->iSize, pHdr->nBacktrace-1, &pBt[1]); } } /* ** Open the file indicated and write a log of all unfreed memory ** allocations into that log. */ SQLITE_PRIVATE void sqlite3MemdebugDump(const char *zFilename){ FILE *out; struct MemBlockHdr *pHdr; void **pBt; int i; out = fopen(zFilename, "w"); if( out==0 ){ fprintf(stderr, "** Unable to output memory debug output log: %s **\n", zFilename); return; } for(pHdr=mem.pFirst; pHdr; pHdr=pHdr->pNext){ char *z = (char*)pHdr; z -= pHdr->nBacktraceSlots*sizeof(void*) + pHdr->nTitle; fprintf(out, "**** %lld bytes at %p from %s ****\n", pHdr->iSize, &pHdr[1], pHdr->nTitle ? z : "???"); if( pHdr->nBacktrace ){ fflush(out); pBt = (void**)pHdr; pBt -= pHdr->nBacktraceSlots; backtrace_symbols_fd(pBt, pHdr->nBacktrace, fileno(out)); fprintf(out, "\n"); } } fprintf(out, "COUNTS:\n"); for(i=0; i=1 ); size = mem3.aPool[i-1].u.hdr.size4x/4; assert( size==mem3.aPool[i+size-1].u.hdr.prevSize ); assert( size>=2 ); if( size <= MX_SMALL ){ memsys3UnlinkFromList(i, &mem3.aiSmall[size-2]); }else{ hash = size % N_HASH; memsys3UnlinkFromList(i, &mem3.aiHash[hash]); } } /* ** Link the chunk at mem3.aPool[i] so that is on the list rooted ** at *pRoot. */ static void memsys3LinkIntoList(u32 i, u32 *pRoot){ assert( sqlite3_mutex_held(mem3.mutex) ); mem3.aPool[i].u.list.next = *pRoot; mem3.aPool[i].u.list.prev = 0; if( *pRoot ){ mem3.aPool[*pRoot].u.list.prev = i; } *pRoot = i; } /* ** Link the chunk at index i into either the appropriate ** small chunk list, or into the large chunk hash table. */ static void memsys3Link(u32 i){ u32 size, hash; assert( sqlite3_mutex_held(mem3.mutex) ); assert( i>=1 ); assert( (mem3.aPool[i-1].u.hdr.size4x & 1)==0 ); size = mem3.aPool[i-1].u.hdr.size4x/4; assert( size==mem3.aPool[i+size-1].u.hdr.prevSize ); assert( size>=2 ); if( size <= MX_SMALL ){ memsys3LinkIntoList(i, &mem3.aiSmall[size-2]); }else{ hash = size % N_HASH; memsys3LinkIntoList(i, &mem3.aiHash[hash]); } } /* ** If the STATIC_MEM mutex is not already held, obtain it now. The mutex ** will already be held (obtained by code in malloc.c) if ** sqlite3GlobalConfig.bMemStat is true. */ static void memsys3Enter(void){ if( sqlite3GlobalConfig.bMemstat==0 && mem3.mutex==0 ){ mem3.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM); } sqlite3_mutex_enter(mem3.mutex); } static void memsys3Leave(void){ sqlite3_mutex_leave(mem3.mutex); } /* ** Called when we are unable to satisfy an allocation of nBytes. */ static void memsys3OutOfMemory(int nByte){ if( !mem3.alarmBusy ){ mem3.alarmBusy = 1; assert( sqlite3_mutex_held(mem3.mutex) ); sqlite3_mutex_leave(mem3.mutex); sqlite3_release_memory(nByte); sqlite3_mutex_enter(mem3.mutex); mem3.alarmBusy = 0; } } /* ** Chunk i is a free chunk that has been unlinked. Adjust its ** size parameters for check-out and return a pointer to the ** user portion of the chunk. */ static void *memsys3Checkout(u32 i, u32 nBlock){ u32 x; assert( sqlite3_mutex_held(mem3.mutex) ); assert( i>=1 ); assert( mem3.aPool[i-1].u.hdr.size4x/4==nBlock ); assert( mem3.aPool[i+nBlock-1].u.hdr.prevSize==nBlock ); x = mem3.aPool[i-1].u.hdr.size4x; mem3.aPool[i-1].u.hdr.size4x = nBlock*4 | 1 | (x&2); mem3.aPool[i+nBlock-1].u.hdr.prevSize = nBlock; mem3.aPool[i+nBlock-1].u.hdr.size4x |= 2; return &mem3.aPool[i]; } /* ** Carve a piece off of the end of the mem3.iMaster free chunk. ** Return a pointer to the new allocation. Or, if the master chunk ** is not large enough, return 0. */ static void *memsys3FromMaster(u32 nBlock){ assert( sqlite3_mutex_held(mem3.mutex) ); assert( mem3.szMaster>=nBlock ); if( nBlock>=mem3.szMaster-1 ){ /* Use the entire master */ void *p = memsys3Checkout(mem3.iMaster, mem3.szMaster); mem3.iMaster = 0; mem3.szMaster = 0; mem3.mnMaster = 0; return p; }else{ /* Split the master block. Return the tail. */ u32 newi, x; newi = mem3.iMaster + mem3.szMaster - nBlock; assert( newi > mem3.iMaster+1 ); mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = nBlock; mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x |= 2; mem3.aPool[newi-1].u.hdr.size4x = nBlock*4 + 1; mem3.szMaster -= nBlock; mem3.aPool[newi-1].u.hdr.prevSize = mem3.szMaster; x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2; mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x; if( mem3.szMaster < mem3.mnMaster ){ mem3.mnMaster = mem3.szMaster; } return (void*)&mem3.aPool[newi]; } } /* ** *pRoot is the head of a list of free chunks of the same size ** or same size hash. In other words, *pRoot is an entry in either ** mem3.aiSmall[] or mem3.aiHash[]. ** ** This routine examines all entries on the given list and tries ** to coalesce each entries with adjacent free chunks. ** ** If it sees a chunk that is larger than mem3.iMaster, it replaces ** the current mem3.iMaster with the new larger chunk. In order for ** this mem3.iMaster replacement to work, the master chunk must be ** linked into the hash tables. That is not the normal state of ** affairs, of course. The calling routine must link the master ** chunk before invoking this routine, then must unlink the (possibly ** changed) master chunk once this routine has finished. */ static void memsys3Merge(u32 *pRoot){ u32 iNext, prev, size, i, x; assert( sqlite3_mutex_held(mem3.mutex) ); for(i=*pRoot; i>0; i=iNext){ iNext = mem3.aPool[i].u.list.next; size = mem3.aPool[i-1].u.hdr.size4x; assert( (size&1)==0 ); if( (size&2)==0 ){ memsys3UnlinkFromList(i, pRoot); assert( i > mem3.aPool[i-1].u.hdr.prevSize ); prev = i - mem3.aPool[i-1].u.hdr.prevSize; if( prev==iNext ){ iNext = mem3.aPool[prev].u.list.next; } memsys3Unlink(prev); size = i + size/4 - prev; x = mem3.aPool[prev-1].u.hdr.size4x & 2; mem3.aPool[prev-1].u.hdr.size4x = size*4 | x; mem3.aPool[prev+size-1].u.hdr.prevSize = size; memsys3Link(prev); i = prev; }else{ size /= 4; } if( size>mem3.szMaster ){ mem3.iMaster = i; mem3.szMaster = size; } } } /* ** Return a block of memory of at least nBytes in size. ** Return NULL if unable. ** ** This function assumes that the necessary mutexes, if any, are ** already held by the caller. Hence "Unsafe". */ static void *memsys3MallocUnsafe(int nByte){ u32 i; u32 nBlock; u32 toFree; assert( sqlite3_mutex_held(mem3.mutex) ); assert( sizeof(Mem3Block)==8 ); if( nByte<=12 ){ nBlock = 2; }else{ nBlock = (nByte + 11)/8; } assert( nBlock>=2 ); /* STEP 1: ** Look for an entry of the correct size in either the small ** chunk table or in the large chunk hash table. This is ** successful most of the time (about 9 times out of 10). */ if( nBlock <= MX_SMALL ){ i = mem3.aiSmall[nBlock-2]; if( i>0 ){ memsys3UnlinkFromList(i, &mem3.aiSmall[nBlock-2]); return memsys3Checkout(i, nBlock); } }else{ int hash = nBlock % N_HASH; for(i=mem3.aiHash[hash]; i>0; i=mem3.aPool[i].u.list.next){ if( mem3.aPool[i-1].u.hdr.size4x/4==nBlock ){ memsys3UnlinkFromList(i, &mem3.aiHash[hash]); return memsys3Checkout(i, nBlock); } } } /* STEP 2: ** Try to satisfy the allocation by carving a piece off of the end ** of the master chunk. This step usually works if step 1 fails. */ if( mem3.szMaster>=nBlock ){ return memsys3FromMaster(nBlock); } /* STEP 3: ** Loop through the entire memory pool. Coalesce adjacent free ** chunks. Recompute the master chunk as the largest free chunk. ** Then try again to satisfy the allocation by carving a piece off ** of the end of the master chunk. This step happens very ** rarely (we hope!) */ for(toFree=nBlock*16; toFree<(mem3.nPool*16); toFree *= 2){ memsys3OutOfMemory(toFree); if( mem3.iMaster ){ memsys3Link(mem3.iMaster); mem3.iMaster = 0; mem3.szMaster = 0; } for(i=0; i=nBlock ){ return memsys3FromMaster(nBlock); } } } /* If none of the above worked, then we fail. */ return 0; } /* ** Free an outstanding memory allocation. ** ** This function assumes that the necessary mutexes, if any, are ** already held by the caller. Hence "Unsafe". */ static void memsys3FreeUnsafe(void *pOld){ Mem3Block *p = (Mem3Block*)pOld; int i; u32 size, x; assert( sqlite3_mutex_held(mem3.mutex) ); assert( p>mem3.aPool && p<&mem3.aPool[mem3.nPool] ); i = p - mem3.aPool; assert( (mem3.aPool[i-1].u.hdr.size4x&1)==1 ); size = mem3.aPool[i-1].u.hdr.size4x/4; assert( i+size<=mem3.nPool+1 ); mem3.aPool[i-1].u.hdr.size4x &= ~1; mem3.aPool[i+size-1].u.hdr.prevSize = size; mem3.aPool[i+size-1].u.hdr.size4x &= ~2; memsys3Link(i); /* Try to expand the master using the newly freed chunk */ if( mem3.iMaster ){ while( (mem3.aPool[mem3.iMaster-1].u.hdr.size4x&2)==0 ){ size = mem3.aPool[mem3.iMaster-1].u.hdr.prevSize; mem3.iMaster -= size; mem3.szMaster += size; memsys3Unlink(mem3.iMaster); x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2; mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x; mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = mem3.szMaster; } x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2; while( (mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x&1)==0 ){ memsys3Unlink(mem3.iMaster+mem3.szMaster); mem3.szMaster += mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x/4; mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x; mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = mem3.szMaster; } } } /* ** Return the size of an outstanding allocation, in bytes. The ** size returned omits the 8-byte header overhead. This only ** works for chunks that are currently checked out. */ static int memsys3Size(void *p){ Mem3Block *pBlock; assert( p!=0 ); pBlock = (Mem3Block*)p; assert( (pBlock[-1].u.hdr.size4x&1)!=0 ); return (pBlock[-1].u.hdr.size4x&~3)*2 - 4; } /* ** Round up a request size to the next valid allocation size. */ static int memsys3Roundup(int n){ if( n<=12 ){ return 12; }else{ return ((n+11)&~7) - 4; } } /* ** Allocate nBytes of memory. */ static void *memsys3Malloc(int nBytes){ sqlite3_int64 *p; assert( nBytes>0 ); /* malloc.c filters out 0 byte requests */ memsys3Enter(); p = memsys3MallocUnsafe(nBytes); memsys3Leave(); return (void*)p; } /* ** Free memory. */ static void memsys3Free(void *pPrior){ assert( pPrior ); memsys3Enter(); memsys3FreeUnsafe(pPrior); memsys3Leave(); } /* ** Change the size of an existing memory allocation */ static void *memsys3Realloc(void *pPrior, int nBytes){ int nOld; void *p; if( pPrior==0 ){ return sqlite3_malloc(nBytes); } if( nBytes<=0 ){ sqlite3_free(pPrior); return 0; } nOld = memsys3Size(pPrior); if( nBytes<=nOld && nBytes>=nOld-128 ){ return pPrior; } memsys3Enter(); p = memsys3MallocUnsafe(nBytes); if( p ){ if( nOld>1)!=(size&1) ){ fprintf(out, "%p tail checkout bit is incorrect\n", &mem3.aPool[i]); assert( 0 ); break; } if( size&1 ){ fprintf(out, "%p %6d bytes checked out\n", &mem3.aPool[i], (size/4)*8-8); }else{ fprintf(out, "%p %6d bytes free%s\n", &mem3.aPool[i], (size/4)*8-8, i==mem3.iMaster ? " **master**" : ""); } } for(i=0; i0; j=mem3.aPool[j].u.list.next){ fprintf(out, " %p(%d)", &mem3.aPool[j], (mem3.aPool[j-1].u.hdr.size4x/4)*8-8); } fprintf(out, "\n"); } for(i=0; i0; j=mem3.aPool[j].u.list.next){ fprintf(out, " %p(%d)", &mem3.aPool[j], (mem3.aPool[j-1].u.hdr.size4x/4)*8-8); } fprintf(out, "\n"); } fprintf(out, "master=%d\n", mem3.iMaster); fprintf(out, "nowUsed=%d\n", mem3.nPool*8 - mem3.szMaster*8); fprintf(out, "mxUsed=%d\n", mem3.nPool*8 - mem3.mnMaster*8); sqlite3_mutex_leave(mem3.mutex); if( out==stdout ){ fflush(stdout); }else{ fclose(out); } #else UNUSED_PARAMETER(zFilename); #endif } /* ** This routine is the only routine in this file with external ** linkage. ** ** Populate the low-level memory allocation function pointers in ** sqlite3GlobalConfig.m with pointers to the routines in this file. The ** arguments specify the block of memory to manage. ** ** This routine is only called by sqlite3_config(), and therefore ** is not required to be threadsafe (it is not). */ SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys3(void){ static const sqlite3_mem_methods mempoolMethods = { memsys3Malloc, memsys3Free, memsys3Realloc, memsys3Size, memsys3Roundup, memsys3Init, memsys3Shutdown, 0 }; return &mempoolMethods; } #endif /* SQLITE_ENABLE_MEMSYS3 */ /************** End of mem3.c ************************************************/ /************** Begin file mem5.c ********************************************/ /* ** 2007 October 14 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ************************************************************************* ** This file contains the C functions that implement a memory ** allocation subsystem for use by SQLite. ** ** This version of the memory allocation subsystem omits all ** use of malloc(). The application gives SQLite a block of memory ** before calling sqlite3_initialize() from which allocations ** are made and returned by the xMalloc() and xRealloc() ** implementations. Once sqlite3_initialize() has been called, ** the amount of memory available to SQLite is fixed and cannot ** be changed. ** ** This version of the memory allocation subsystem is included ** in the build only if SQLITE_ENABLE_MEMSYS5 is defined. ** ** This memory allocator uses the following algorithm: ** ** 1. All memory allocation sizes are rounded up to a power of 2. ** ** 2. If two adjacent free blocks are the halves of a larger block, ** then the two blocks are coalesced into the single larger block. ** ** 3. New memory is allocated from the first available free block. ** ** This algorithm is described in: J. M. Robson. "Bounds for Some Functions ** Concerning Dynamic Storage Allocation". Journal of the Association for ** Computing Machinery, Volume 21, Number 8, July 1974, pages 491-499. ** ** Let n be the size of the largest allocation divided by the minimum ** allocation size (after rounding all sizes up to a power of 2.) Let M ** be the maximum amount of memory ever outstanding at one time. Let ** N be the total amount of memory available for allocation. Robson ** proved that this memory allocator will never breakdown due to ** fragmentation as long as the following constraint holds: ** ** N >= M*(1 + log2(n)/2) - n + 1 ** ** The sqlite3_status() logic tracks the maximum values of n and M so ** that an application can, at any time, verify this constraint. */ /* #include "sqliteInt.h" */ /* ** This version of the memory allocator is used only when ** SQLITE_ENABLE_MEMSYS5 is defined. */ #ifdef SQLITE_ENABLE_MEMSYS5 /* ** A minimum allocation is an instance of the following structure. ** Larger allocations are an array of these structures where the ** size of the array is a power of 2. ** ** The size of this object must be a power of two. That fact is ** verified in memsys5Init(). */ typedef struct Mem5Link Mem5Link; struct Mem5Link { int next; /* Index of next free chunk */ int prev; /* Index of previous free chunk */ }; /* ** Maximum size of any allocation is ((1<=0 && i=0 && iLogsize<=LOGMAX ); assert( (mem5.aCtrl[i] & CTRL_LOGSIZE)==iLogsize ); next = MEM5LINK(i)->next; prev = MEM5LINK(i)->prev; if( prev<0 ){ mem5.aiFreelist[iLogsize] = next; }else{ MEM5LINK(prev)->next = next; } if( next>=0 ){ MEM5LINK(next)->prev = prev; } } /* ** Link the chunk at mem5.aPool[i] so that is on the iLogsize ** free list. */ static void memsys5Link(int i, int iLogsize){ int x; assert( sqlite3_mutex_held(mem5.mutex) ); assert( i>=0 && i=0 && iLogsize<=LOGMAX ); assert( (mem5.aCtrl[i] & CTRL_LOGSIZE)==iLogsize ); x = MEM5LINK(i)->next = mem5.aiFreelist[iLogsize]; MEM5LINK(i)->prev = -1; if( x>=0 ){ assert( xprev = i; } mem5.aiFreelist[iLogsize] = i; } /* ** Obtain or release the mutex needed to access global data structures. */ static void memsys5Enter(void){ sqlite3_mutex_enter(mem5.mutex); } static void memsys5Leave(void){ sqlite3_mutex_leave(mem5.mutex); } /* ** Return the size of an outstanding allocation, in bytes. ** This only works for chunks that are currently checked out. */ static int memsys5Size(void *p){ int iSize, i; assert( p!=0 ); i = (int)(((u8 *)p-mem5.zPool)/mem5.szAtom); assert( i>=0 && i0 ); /* No more than 1GiB per allocation */ if( nByte > 0x40000000 ) return 0; #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST) /* Keep track of the maximum allocation request. Even unfulfilled ** requests are counted */ if( (u32)nByte>mem5.maxRequest ){ mem5.maxRequest = nByte; } #endif /* Round nByte up to the next valid power of two */ for(iFullSz=mem5.szAtom,iLogsize=0; iFullSzLOGMAX ){ testcase( sqlite3GlobalConfig.xLog!=0 ); sqlite3_log(SQLITE_NOMEM, "failed to allocate %u bytes", nByte); return 0; } i = mem5.aiFreelist[iBin]; memsys5Unlink(i, iBin); while( iBin>iLogsize ){ int newSize; iBin--; newSize = 1 << iBin; mem5.aCtrl[i+newSize] = CTRL_FREE | iBin; memsys5Link(i+newSize, iBin); } mem5.aCtrl[i] = iLogsize; #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST) /* Update allocator performance statistics. */ mem5.nAlloc++; mem5.totalAlloc += iFullSz; mem5.totalExcess += iFullSz - nByte; mem5.currentCount++; mem5.currentOut += iFullSz; if( mem5.maxCount=0 && iBlock0 ); assert( mem5.currentOut>=(size*mem5.szAtom) ); mem5.currentCount--; mem5.currentOut -= size*mem5.szAtom; assert( mem5.currentOut>0 || mem5.currentCount==0 ); assert( mem5.currentCount>0 || mem5.currentOut==0 ); #endif mem5.aCtrl[iBlock] = CTRL_FREE | iLogsize; while( ALWAYS(iLogsize>iLogsize) & 1 ){ iBuddy = iBlock - size; assert( iBuddy>=0 ); }else{ iBuddy = iBlock + size; if( iBuddy>=mem5.nBlock ) break; } if( mem5.aCtrl[iBuddy]!=(CTRL_FREE | iLogsize) ) break; memsys5Unlink(iBuddy, iLogsize); iLogsize++; if( iBuddy0 ){ memsys5Enter(); p = memsys5MallocUnsafe(nBytes); memsys5Leave(); } return (void*)p; } /* ** Free memory. ** ** The outer layer memory allocator prevents this routine from ** being called with pPrior==0. */ static void memsys5Free(void *pPrior){ assert( pPrior!=0 ); memsys5Enter(); memsys5FreeUnsafe(pPrior); memsys5Leave(); } /* ** Change the size of an existing memory allocation. ** ** The outer layer memory allocator prevents this routine from ** being called with pPrior==0. ** ** nBytes is always a value obtained from a prior call to ** memsys5Round(). Hence nBytes is always a non-negative power ** of two. If nBytes==0 that means that an oversize allocation ** (an allocation larger than 0x40000000) was requested and this ** routine should return 0 without freeing pPrior. */ static void *memsys5Realloc(void *pPrior, int nBytes){ int nOld; void *p; assert( pPrior!=0 ); assert( (nBytes&(nBytes-1))==0 ); /* EV: R-46199-30249 */ assert( nBytes>=0 ); if( nBytes==0 ){ return 0; } nOld = memsys5Size(pPrior); if( nBytes<=nOld ){ return pPrior; } p = memsys5Malloc(nBytes); if( p ){ memcpy(p, pPrior, nOld); memsys5Free(pPrior); } return p; } /* ** Round up a request size to the next valid allocation size. If ** the allocation is too large to be handled by this allocation system, ** return 0. ** ** All allocations must be a power of two and must be expressed by a ** 32-bit signed integer. Hence the largest allocation is 0x40000000 ** or 1073741824 bytes. */ static int memsys5Roundup(int n){ int iFullSz; if( n > 0x40000000 ) return 0; for(iFullSz=mem5.szAtom; iFullSz 0 ** memsys5Log(2) -> 1 ** memsys5Log(4) -> 2 ** memsys5Log(5) -> 3 ** memsys5Log(8) -> 3 ** memsys5Log(9) -> 4 */ static int memsys5Log(int iValue){ int iLog; for(iLog=0; (iLog<(int)((sizeof(int)*8)-1)) && (1<mem5.szAtom ){ mem5.szAtom = mem5.szAtom << 1; } mem5.nBlock = (nByte / (mem5.szAtom+sizeof(u8))); mem5.zPool = zByte; mem5.aCtrl = (u8 *)&mem5.zPool[mem5.nBlock*mem5.szAtom]; for(ii=0; ii<=LOGMAX; ii++){ mem5.aiFreelist[ii] = -1; } iOffset = 0; for(ii=LOGMAX; ii>=0; ii--){ int nAlloc = (1<mem5.nBlock); } /* If a mutex is required for normal operation, allocate one */ if( sqlite3GlobalConfig.bMemstat==0 ){ mem5.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM); } return SQLITE_OK; } /* ** Deinitialize this module. */ static void memsys5Shutdown(void *NotUsed){ UNUSED_PARAMETER(NotUsed); mem5.mutex = 0; return; } #ifdef SQLITE_TEST /* ** Open the file indicated and write a log of all unfreed memory ** allocations into that log. */ SQLITE_PRIVATE void sqlite3Memsys5Dump(const char *zFilename){ FILE *out; int i, j, n; int nMinLog; if( zFilename==0 || zFilename[0]==0 ){ out = stdout; }else{ out = fopen(zFilename, "w"); if( out==0 ){ fprintf(stderr, "** Unable to output memory debug output log: %s **\n", zFilename); return; } } memsys5Enter(); nMinLog = memsys5Log(mem5.szAtom); for(i=0; i<=LOGMAX && i+nMinLog<32; i++){ for(n=0, j=mem5.aiFreelist[i]; j>=0; j = MEM5LINK(j)->next, n++){} fprintf(out, "freelist items of size %d: %d\n", mem5.szAtom << i, n); } fprintf(out, "mem5.nAlloc = %llu\n", mem5.nAlloc); fprintf(out, "mem5.totalAlloc = %llu\n", mem5.totalAlloc); fprintf(out, "mem5.totalExcess = %llu\n", mem5.totalExcess); fprintf(out, "mem5.currentOut = %u\n", mem5.currentOut); fprintf(out, "mem5.currentCount = %u\n", mem5.currentCount); fprintf(out, "mem5.maxOut = %u\n", mem5.maxOut); fprintf(out, "mem5.maxCount = %u\n", mem5.maxCount); fprintf(out, "mem5.maxRequest = %u\n", mem5.maxRequest); memsys5Leave(); if( out==stdout ){ fflush(stdout); }else{ fclose(out); } } #endif /* ** This routine is the only routine in this file with external ** linkage. It returns a pointer to a static sqlite3_mem_methods ** struct populated with the memsys5 methods. */ SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys5(void){ static const sqlite3_mem_methods memsys5Methods = { memsys5Malloc, memsys5Free, memsys5Realloc, memsys5Size, memsys5Roundup, memsys5Init, memsys5Shutdown, 0 }; return &memsys5Methods; } #endif /* SQLITE_ENABLE_MEMSYS5 */ /************** End of mem5.c ************************************************/ /************** Begin file mutex.c *******************************************/ /* ** 2007 August 14 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ************************************************************************* ** This file contains the C functions that implement mutexes. ** ** This file contains code that is common across all mutex implementations. */ /* #include "sqliteInt.h" */ #if defined(SQLITE_DEBUG) && !defined(SQLITE_MUTEX_OMIT) /* ** For debugging purposes, record when the mutex subsystem is initialized ** and uninitialized so that we can assert() if there is an attempt to ** allocate a mutex while the system is uninitialized. */ static SQLITE_WSD int mutexIsInit = 0; #endif /* SQLITE_DEBUG && !defined(SQLITE_MUTEX_OMIT) */ #ifndef SQLITE_MUTEX_OMIT /* ** Initialize the mutex system. */ SQLITE_PRIVATE int sqlite3MutexInit(void){ int rc = SQLITE_OK; if( !sqlite3GlobalConfig.mutex.xMutexAlloc ){ /* If the xMutexAlloc method has not been set, then the user did not ** install a mutex implementation via sqlite3_config() prior to ** sqlite3_initialize() being called. This block copies pointers to ** the default implementation into the sqlite3GlobalConfig structure. */ sqlite3_mutex_methods const *pFrom; sqlite3_mutex_methods *pTo = &sqlite3GlobalConfig.mutex; if( sqlite3GlobalConfig.bCoreMutex ){ pFrom = sqlite3DefaultMutex(); }else{ pFrom = sqlite3NoopMutex(); } pTo->xMutexInit = pFrom->xMutexInit; pTo->xMutexEnd = pFrom->xMutexEnd; pTo->xMutexFree = pFrom->xMutexFree; pTo->xMutexEnter = pFrom->xMutexEnter; pTo->xMutexTry = pFrom->xMutexTry; pTo->xMutexLeave = pFrom->xMutexLeave; pTo->xMutexHeld = pFrom->xMutexHeld; pTo->xMutexNotheld = pFrom->xMutexNotheld; sqlite3MemoryBarrier(); pTo->xMutexAlloc = pFrom->xMutexAlloc; } assert( sqlite3GlobalConfig.mutex.xMutexInit ); rc = sqlite3GlobalConfig.mutex.xMutexInit(); #ifdef SQLITE_DEBUG GLOBAL(int, mutexIsInit) = 1; #endif return rc; } /* ** Shutdown the mutex system. This call frees resources allocated by ** sqlite3MutexInit(). */ SQLITE_PRIVATE int sqlite3MutexEnd(void){ int rc = SQLITE_OK; if( sqlite3GlobalConfig.mutex.xMutexEnd ){ rc = sqlite3GlobalConfig.mutex.xMutexEnd(); } #ifdef SQLITE_DEBUG GLOBAL(int, mutexIsInit) = 0; #endif return rc; } /* ** Retrieve a pointer to a static mutex or allocate a new dynamic one. */ SQLITE_API sqlite3_mutex *sqlite3_mutex_alloc(int id){ #ifndef SQLITE_OMIT_AUTOINIT if( id<=SQLITE_MUTEX_RECURSIVE && sqlite3_initialize() ) return 0; if( id>SQLITE_MUTEX_RECURSIVE && sqlite3MutexInit() ) return 0; #endif assert( sqlite3GlobalConfig.mutex.xMutexAlloc ); return sqlite3GlobalConfig.mutex.xMutexAlloc(id); } SQLITE_PRIVATE sqlite3_mutex *sqlite3MutexAlloc(int id){ if( !sqlite3GlobalConfig.bCoreMutex ){ return 0; } assert( GLOBAL(int, mutexIsInit) ); assert( sqlite3GlobalConfig.mutex.xMutexAlloc ); return sqlite3GlobalConfig.mutex.xMutexAlloc(id); } /* ** Free a dynamic mutex. */ SQLITE_API void sqlite3_mutex_free(sqlite3_mutex *p){ if( p ){ assert( sqlite3GlobalConfig.mutex.xMutexFree ); sqlite3GlobalConfig.mutex.xMutexFree(p); } } /* ** Obtain the mutex p. If some other thread already has the mutex, block ** until it can be obtained. */ SQLITE_API void sqlite3_mutex_enter(sqlite3_mutex *p){ if( p ){ assert( sqlite3GlobalConfig.mutex.xMutexEnter ); sqlite3GlobalConfig.mutex.xMutexEnter(p); } } /* ** Obtain the mutex p. If successful, return SQLITE_OK. Otherwise, if another ** thread holds the mutex and it cannot be obtained, return SQLITE_BUSY. */ SQLITE_API int sqlite3_mutex_try(sqlite3_mutex *p){ int rc = SQLITE_OK; if( p ){ assert( sqlite3GlobalConfig.mutex.xMutexTry ); return sqlite3GlobalConfig.mutex.xMutexTry(p); } return rc; } /* ** The sqlite3_mutex_leave() routine exits a mutex that was previously ** entered by the same thread. The behavior is undefined if the mutex ** is not currently entered. If a NULL pointer is passed as an argument ** this function is a no-op. */ SQLITE_API void sqlite3_mutex_leave(sqlite3_mutex *p){ if( p ){ assert( sqlite3GlobalConfig.mutex.xMutexLeave ); sqlite3GlobalConfig.mutex.xMutexLeave(p); } } #ifndef NDEBUG /* ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are ** intended for use inside assert() statements. */ SQLITE_API int sqlite3_mutex_held(sqlite3_mutex *p){ assert( p==0 || sqlite3GlobalConfig.mutex.xMutexHeld ); return p==0 || sqlite3GlobalConfig.mutex.xMutexHeld(p); } SQLITE_API int sqlite3_mutex_notheld(sqlite3_mutex *p){ assert( p==0 || sqlite3GlobalConfig.mutex.xMutexNotheld ); return p==0 || sqlite3GlobalConfig.mutex.xMutexNotheld(p); } #endif #endif /* !defined(SQLITE_MUTEX_OMIT) */ /************** End of mutex.c ***********************************************/ /************** Begin file mutex_noop.c **************************************/ /* ** 2008 October 07 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ************************************************************************* ** This file contains the C functions that implement mutexes. ** ** This implementation in this file does not provide any mutual ** exclusion and is thus suitable for use only in applications ** that use SQLite in a single thread. The routines defined ** here are place-holders. Applications can substitute working ** mutex routines at start-time using the ** ** sqlite3_config(SQLITE_CONFIG_MUTEX,...) ** ** interface. ** ** If compiled with SQLITE_DEBUG, then additional logic is inserted ** that does error checking on mutexes to make sure they are being ** called correctly. */ /* #include "sqliteInt.h" */ #ifndef SQLITE_MUTEX_OMIT #ifndef SQLITE_DEBUG /* ** Stub routines for all mutex methods. ** ** This routines provide no mutual exclusion or error checking. */ static int noopMutexInit(void){ return SQLITE_OK; } static int noopMutexEnd(void){ return SQLITE_OK; } static sqlite3_mutex *noopMutexAlloc(int id){ UNUSED_PARAMETER(id); return (sqlite3_mutex*)8; } static void noopMutexFree(sqlite3_mutex *p){ UNUSED_PARAMETER(p); return; } static void noopMutexEnter(sqlite3_mutex *p){ UNUSED_PARAMETER(p); return; } static int noopMutexTry(sqlite3_mutex *p){ UNUSED_PARAMETER(p); return SQLITE_OK; } static void noopMutexLeave(sqlite3_mutex *p){ UNUSED_PARAMETER(p); return; } SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3NoopMutex(void){ static const sqlite3_mutex_methods sMutex = { noopMutexInit, noopMutexEnd, noopMutexAlloc, noopMutexFree, noopMutexEnter, noopMutexTry, noopMutexLeave, 0, 0, }; return &sMutex; } #endif /* !SQLITE_DEBUG */ #ifdef SQLITE_DEBUG /* ** In this implementation, error checking is provided for testing ** and debugging purposes. The mutexes still do not provide any ** mutual exclusion. */ /* ** The mutex object */ typedef struct sqlite3_debug_mutex { int id; /* The mutex type */ int cnt; /* Number of entries without a matching leave */ } sqlite3_debug_mutex; /* ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are ** intended for use inside assert() statements. */ static int debugMutexHeld(sqlite3_mutex *pX){ sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX; return p==0 || p->cnt>0; } static int debugMutexNotheld(sqlite3_mutex *pX){ sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX; return p==0 || p->cnt==0; } /* ** Initialize and deinitialize the mutex subsystem. */ static int debugMutexInit(void){ return SQLITE_OK; } static int debugMutexEnd(void){ return SQLITE_OK; } /* ** The sqlite3_mutex_alloc() routine allocates a new ** mutex and returns a pointer to it. If it returns NULL ** that means that a mutex could not be allocated. */ static sqlite3_mutex *debugMutexAlloc(int id){ static sqlite3_debug_mutex aStatic[SQLITE_MUTEX_STATIC_VFS3 - 1]; sqlite3_debug_mutex *pNew = 0; switch( id ){ case SQLITE_MUTEX_FAST: case SQLITE_MUTEX_RECURSIVE: { pNew = sqlite3Malloc(sizeof(*pNew)); if( pNew ){ pNew->id = id; pNew->cnt = 0; } break; } default: { #ifdef SQLITE_ENABLE_API_ARMOR if( id-2<0 || id-2>=ArraySize(aStatic) ){ (void)SQLITE_MISUSE_BKPT; return 0; } #endif pNew = &aStatic[id-2]; pNew->id = id; break; } } return (sqlite3_mutex*)pNew; } /* ** This routine deallocates a previously allocated mutex. */ static void debugMutexFree(sqlite3_mutex *pX){ sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX; assert( p->cnt==0 ); if( p->id==SQLITE_MUTEX_RECURSIVE || p->id==SQLITE_MUTEX_FAST ){ sqlite3_free(p); }else{ #ifdef SQLITE_ENABLE_API_ARMOR (void)SQLITE_MISUSE_BKPT; #endif } } /* ** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt ** to enter a mutex. If another thread is already within the mutex, ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return ** SQLITE_BUSY. The sqlite3_mutex_try() interface returns SQLITE_OK ** upon successful entry. Mutexes created using SQLITE_MUTEX_RECURSIVE can ** be entered multiple times by the same thread. In such cases the, ** mutex must be exited an equal number of times before another thread ** can enter. If the same thread tries to enter any other kind of mutex ** more than once, the behavior is undefined. */ static void debugMutexEnter(sqlite3_mutex *pX){ sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX; assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(pX) ); p->cnt++; } static int debugMutexTry(sqlite3_mutex *pX){ sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX; assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(pX) ); p->cnt++; return SQLITE_OK; } /* ** The sqlite3_mutex_leave() routine exits a mutex that was ** previously entered by the same thread. The behavior ** is undefined if the mutex is not currently entered or ** is not currently allocated. SQLite will never do either. */ static void debugMutexLeave(sqlite3_mutex *pX){ sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX; assert( debugMutexHeld(pX) ); p->cnt--; assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(pX) ); } SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3NoopMutex(void){ static const sqlite3_mutex_methods sMutex = { debugMutexInit, debugMutexEnd, debugMutexAlloc, debugMutexFree, debugMutexEnter, debugMutexTry, debugMutexLeave, debugMutexHeld, debugMutexNotheld }; return &sMutex; } #endif /* SQLITE_DEBUG */ /* ** If compiled with SQLITE_MUTEX_NOOP, then the no-op mutex implementation ** is used regardless of the run-time threadsafety setting. */ #ifdef SQLITE_MUTEX_NOOP SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void){ return sqlite3NoopMutex(); } #endif /* defined(SQLITE_MUTEX_NOOP) */ #endif /* !defined(SQLITE_MUTEX_OMIT) */ /************** End of mutex_noop.c ******************************************/ /************** Begin file mutex_unix.c **************************************/ /* ** 2007 August 28 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ************************************************************************* ** This file contains the C functions that implement mutexes for pthreads */ /* #include "sqliteInt.h" */ /* ** The code in this file is only used if we are compiling threadsafe ** under unix with pthreads. ** ** Note that this implementation requires a version of pthreads that ** supports recursive mutexes. */ #ifdef SQLITE_MUTEX_PTHREADS #include /* ** The sqlite3_mutex.id, sqlite3_mutex.nRef, and sqlite3_mutex.owner fields ** are necessary under two condidtions: (1) Debug builds and (2) using ** home-grown mutexes. Encapsulate these conditions into a single #define. */ #if defined(SQLITE_DEBUG) || defined(SQLITE_HOMEGROWN_RECURSIVE_MUTEX) # define SQLITE_MUTEX_NREF 1 #else # define SQLITE_MUTEX_NREF 0 #endif /* ** Each recursive mutex is an instance of the following structure. */ struct sqlite3_mutex { pthread_mutex_t mutex; /* Mutex controlling the lock */ #if SQLITE_MUTEX_NREF || defined(SQLITE_ENABLE_API_ARMOR) int id; /* Mutex type */ #endif #if SQLITE_MUTEX_NREF volatile int nRef; /* Number of entrances */ volatile pthread_t owner; /* Thread that is within this mutex */ int trace; /* True to trace changes */ #endif }; #if SQLITE_MUTEX_NREF #define SQLITE3_MUTEX_INITIALIZER {PTHREAD_MUTEX_INITIALIZER,0,0,(pthread_t)0,0} #elif defined(SQLITE_ENABLE_API_ARMOR) #define SQLITE3_MUTEX_INITIALIZER { PTHREAD_MUTEX_INITIALIZER, 0 } #else #define SQLITE3_MUTEX_INITIALIZER { PTHREAD_MUTEX_INITIALIZER } #endif /* ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are ** intended for use only inside assert() statements. On some platforms, ** there might be race conditions that can cause these routines to ** deliver incorrect results. In particular, if pthread_equal() is ** not an atomic operation, then these routines might delivery ** incorrect results. On most platforms, pthread_equal() is a ** comparison of two integers and is therefore atomic. But we are ** told that HPUX is not such a platform. If so, then these routines ** will not always work correctly on HPUX. ** ** On those platforms where pthread_equal() is not atomic, SQLite ** should be compiled without -DSQLITE_DEBUG and with -DNDEBUG to ** make sure no assert() statements are evaluated and hence these ** routines are never called. */ #if !defined(NDEBUG) || defined(SQLITE_DEBUG) static int pthreadMutexHeld(sqlite3_mutex *p){ return (p->nRef!=0 && pthread_equal(p->owner, pthread_self())); } static int pthreadMutexNotheld(sqlite3_mutex *p){ return p->nRef==0 || pthread_equal(p->owner, pthread_self())==0; } #endif /* ** Try to provide a memory barrier operation, needed for initialization ** and also for the implementation of xShmBarrier in the VFS in cases ** where SQLite is compiled without mutexes. */ SQLITE_PRIVATE void sqlite3MemoryBarrier(void){ #if defined(SQLITE_MEMORY_BARRIER) SQLITE_MEMORY_BARRIER; #elif defined(__GNUC__) && GCC_VERSION>=4001000 __sync_synchronize(); #endif } /* ** Initialize and deinitialize the mutex subsystem. */ static int pthreadMutexInit(void){ return SQLITE_OK; } static int pthreadMutexEnd(void){ return SQLITE_OK; } /* ** The sqlite3_mutex_alloc() routine allocates a new ** mutex and returns a pointer to it. If it returns NULL ** that means that a mutex could not be allocated. SQLite ** will unwind its stack and return an error. The argument ** to sqlite3_mutex_alloc() is one of these integer constants: ** **
    **
  • SQLITE_MUTEX_FAST **
  • SQLITE_MUTEX_RECURSIVE **
  • SQLITE_MUTEX_STATIC_MASTER **
  • SQLITE_MUTEX_STATIC_MEM **
  • SQLITE_MUTEX_STATIC_OPEN **
  • SQLITE_MUTEX_STATIC_PRNG **
  • SQLITE_MUTEX_STATIC_LRU **
  • SQLITE_MUTEX_STATIC_PMEM **
  • SQLITE_MUTEX_STATIC_APP1 **
  • SQLITE_MUTEX_STATIC_APP2 **
  • SQLITE_MUTEX_STATIC_APP3 **
  • SQLITE_MUTEX_STATIC_VFS1 **
  • SQLITE_MUTEX_STATIC_VFS2 **
  • SQLITE_MUTEX_STATIC_VFS3 **
** ** The first two constants cause sqlite3_mutex_alloc() to create ** a new mutex. The new mutex is recursive when SQLITE_MUTEX_RECURSIVE ** is used but not necessarily so when SQLITE_MUTEX_FAST is used. ** The mutex implementation does not need to make a distinction ** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does ** not want to. But SQLite will only request a recursive mutex in ** cases where it really needs one. If a faster non-recursive mutex ** implementation is available on the host platform, the mutex subsystem ** might return such a mutex in response to SQLITE_MUTEX_FAST. ** ** The other allowed parameters to sqlite3_mutex_alloc() each return ** a pointer to a static preexisting mutex. Six static mutexes are ** used by the current version of SQLite. Future versions of SQLite ** may add additional static mutexes. Static mutexes are for internal ** use by SQLite only. Applications that use SQLite mutexes should ** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or ** SQLITE_MUTEX_RECURSIVE. ** ** Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST ** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc() ** returns a different mutex on every call. But for the static ** mutex types, the same mutex is returned on every call that has ** the same type number. */ static sqlite3_mutex *pthreadMutexAlloc(int iType){ static sqlite3_mutex staticMutexes[] = { SQLITE3_MUTEX_INITIALIZER, SQLITE3_MUTEX_INITIALIZER, SQLITE3_MUTEX_INITIALIZER, SQLITE3_MUTEX_INITIALIZER, SQLITE3_MUTEX_INITIALIZER, SQLITE3_MUTEX_INITIALIZER, SQLITE3_MUTEX_INITIALIZER, SQLITE3_MUTEX_INITIALIZER, SQLITE3_MUTEX_INITIALIZER, SQLITE3_MUTEX_INITIALIZER, SQLITE3_MUTEX_INITIALIZER, SQLITE3_MUTEX_INITIALIZER }; sqlite3_mutex *p; switch( iType ){ case SQLITE_MUTEX_RECURSIVE: { p = sqlite3MallocZero( sizeof(*p) ); if( p ){ #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX /* If recursive mutexes are not available, we will have to ** build our own. See below. */ pthread_mutex_init(&p->mutex, 0); #else /* Use a recursive mutex if it is available */ pthread_mutexattr_t recursiveAttr; pthread_mutexattr_init(&recursiveAttr); pthread_mutexattr_settype(&recursiveAttr, PTHREAD_MUTEX_RECURSIVE); pthread_mutex_init(&p->mutex, &recursiveAttr); pthread_mutexattr_destroy(&recursiveAttr); #endif } break; } case SQLITE_MUTEX_FAST: { p = sqlite3MallocZero( sizeof(*p) ); if( p ){ pthread_mutex_init(&p->mutex, 0); } break; } default: { #ifdef SQLITE_ENABLE_API_ARMOR if( iType-2<0 || iType-2>=ArraySize(staticMutexes) ){ (void)SQLITE_MISUSE_BKPT; return 0; } #endif p = &staticMutexes[iType-2]; break; } } #if SQLITE_MUTEX_NREF || defined(SQLITE_ENABLE_API_ARMOR) if( p ) p->id = iType; #endif return p; } /* ** This routine deallocates a previously ** allocated mutex. SQLite is careful to deallocate every ** mutex that it allocates. */ static void pthreadMutexFree(sqlite3_mutex *p){ assert( p->nRef==0 ); #if SQLITE_ENABLE_API_ARMOR if( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE ) #endif { pthread_mutex_destroy(&p->mutex); sqlite3_free(p); } #ifdef SQLITE_ENABLE_API_ARMOR else{ (void)SQLITE_MISUSE_BKPT; } #endif } /* ** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt ** to enter a mutex. If another thread is already within the mutex, ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return ** SQLITE_BUSY. The sqlite3_mutex_try() interface returns SQLITE_OK ** upon successful entry. Mutexes created using SQLITE_MUTEX_RECURSIVE can ** be entered multiple times by the same thread. In such cases the, ** mutex must be exited an equal number of times before another thread ** can enter. If the same thread tries to enter any other kind of mutex ** more than once, the behavior is undefined. */ static void pthreadMutexEnter(sqlite3_mutex *p){ assert( p->id==SQLITE_MUTEX_RECURSIVE || pthreadMutexNotheld(p) ); #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX /* If recursive mutexes are not available, then we have to grow ** our own. This implementation assumes that pthread_equal() ** is atomic - that it cannot be deceived into thinking self ** and p->owner are equal if p->owner changes between two values ** that are not equal to self while the comparison is taking place. ** This implementation also assumes a coherent cache - that ** separate processes cannot read different values from the same ** address at the same time. If either of these two conditions ** are not met, then the mutexes will fail and problems will result. */ { pthread_t self = pthread_self(); if( p->nRef>0 && pthread_equal(p->owner, self) ){ p->nRef++; }else{ pthread_mutex_lock(&p->mutex); assert( p->nRef==0 ); p->owner = self; p->nRef = 1; } } #else /* Use the built-in recursive mutexes if they are available. */ pthread_mutex_lock(&p->mutex); #if SQLITE_MUTEX_NREF assert( p->nRef>0 || p->owner==0 ); p->owner = pthread_self(); p->nRef++; #endif #endif #ifdef SQLITE_DEBUG if( p->trace ){ printf("enter mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef); } #endif } static int pthreadMutexTry(sqlite3_mutex *p){ int rc; assert( p->id==SQLITE_MUTEX_RECURSIVE || pthreadMutexNotheld(p) ); #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX /* If recursive mutexes are not available, then we have to grow ** our own. This implementation assumes that pthread_equal() ** is atomic - that it cannot be deceived into thinking self ** and p->owner are equal if p->owner changes between two values ** that are not equal to self while the comparison is taking place. ** This implementation also assumes a coherent cache - that ** separate processes cannot read different values from the same ** address at the same time. If either of these two conditions ** are not met, then the mutexes will fail and problems will result. */ { pthread_t self = pthread_self(); if( p->nRef>0 && pthread_equal(p->owner, self) ){ p->nRef++; rc = SQLITE_OK; }else if( pthread_mutex_trylock(&p->mutex)==0 ){ assert( p->nRef==0 ); p->owner = self; p->nRef = 1; rc = SQLITE_OK; }else{ rc = SQLITE_BUSY; } } #else /* Use the built-in recursive mutexes if they are available. */ if( pthread_mutex_trylock(&p->mutex)==0 ){ #if SQLITE_MUTEX_NREF p->owner = pthread_self(); p->nRef++; #endif rc = SQLITE_OK; }else{ rc = SQLITE_BUSY; } #endif #ifdef SQLITE_DEBUG if( rc==SQLITE_OK && p->trace ){ printf("enter mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef); } #endif return rc; } /* ** The sqlite3_mutex_leave() routine exits a mutex that was ** previously entered by the same thread. The behavior ** is undefined if the mutex is not currently entered or ** is not currently allocated. SQLite will never do either. */ static void pthreadMutexLeave(sqlite3_mutex *p){ assert( pthreadMutexHeld(p) ); #if SQLITE_MUTEX_NREF p->nRef--; if( p->nRef==0 ) p->owner = 0; #endif assert( p->nRef==0 || p->id==SQLITE_MUTEX_RECURSIVE ); #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX if( p->nRef==0 ){ pthread_mutex_unlock(&p->mutex); } #else pthread_mutex_unlock(&p->mutex); #endif #ifdef SQLITE_DEBUG if( p->trace ){ printf("leave mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef); } #endif } SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void){ static const sqlite3_mutex_methods sMutex = { pthreadMutexInit, pthreadMutexEnd, pthreadMutexAlloc, pthreadMutexFree, pthreadMutexEnter, pthreadMutexTry, pthreadMutexLeave, #ifdef SQLITE_DEBUG pthreadMutexHeld, pthreadMutexNotheld #else 0, 0 #endif }; return &sMutex; } #endif /* SQLITE_MUTEX_PTHREADS */ /************** End of mutex_unix.c ******************************************/ /************** Begin file mutex_w32.c ***************************************/ /* ** 2007 August 14 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ************************************************************************* ** This file contains the C functions that implement mutexes for Win32. */ /* #include "sqliteInt.h" */ #if SQLITE_OS_WIN /* ** Include code that is common to all os_*.c files */ /************** Include os_common.h in the middle of mutex_w32.c *************/ /************** Begin file os_common.h ***************************************/ /* ** 2004 May 22 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ****************************************************************************** ** ** This file contains macros and a little bit of code that is common to ** all of the platform-specific files (os_*.c) and is #included into those ** files. ** ** This file should be #included by the os_*.c files only. It is not a ** general purpose header file. */ #ifndef _OS_COMMON_H_ #define _OS_COMMON_H_ /* ** At least two bugs have slipped in because we changed the MEMORY_DEBUG ** macro to SQLITE_DEBUG and some older makefiles have not yet made the ** switch. The following code should catch this problem at compile-time. */ #ifdef MEMORY_DEBUG # error "The MEMORY_DEBUG macro is obsolete. Use SQLITE_DEBUG instead." #endif /* ** Macros for performance tracing. Normally turned off. Only works ** on i486 hardware. */ #ifdef SQLITE_PERFORMANCE_TRACE /* ** hwtime.h contains inline assembler code for implementing ** high-performance timing routines. */ /************** Include hwtime.h in the middle of os_common.h ****************/ /************** Begin file hwtime.h ******************************************/ /* ** 2008 May 27 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ****************************************************************************** ** ** This file contains inline asm code for retrieving "high-performance" ** counters for x86 class CPUs. */ #ifndef SQLITE_HWTIME_H #define SQLITE_HWTIME_H /* ** The following routine only works on pentium-class (or newer) processors. ** It uses the RDTSC opcode to read the cycle count value out of the ** processor and returns that value. This can be used for high-res ** profiling. */ #if (defined(__GNUC__) || defined(_MSC_VER)) && \ (defined(i386) || defined(__i386__) || defined(_M_IX86)) #if defined(__GNUC__) __inline__ sqlite_uint64 sqlite3Hwtime(void){ unsigned int lo, hi; __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi)); return (sqlite_uint64)hi << 32 | lo; } #elif defined(_MSC_VER) __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){ __asm { rdtsc ret ; return value at EDX:EAX } } #endif #elif (defined(__GNUC__) && defined(__x86_64__)) __inline__ sqlite_uint64 sqlite3Hwtime(void){ unsigned long val; __asm__ __volatile__ ("rdtsc" : "=A" (val)); return val; } #elif (defined(__GNUC__) && defined(__ppc__)) __inline__ sqlite_uint64 sqlite3Hwtime(void){ unsigned long long retval; unsigned long junk; __asm__ __volatile__ ("\n\ 1: mftbu %1\n\ mftb %L0\n\ mftbu %0\n\ cmpw %0,%1\n\ bne 1b" : "=r" (retval), "=r" (junk)); return retval; } #else #error Need implementation of sqlite3Hwtime() for your platform. /* ** To compile without implementing sqlite3Hwtime() for your platform, ** you can remove the above #error and use the following ** stub function. You will lose timing support for many ** of the debugging and testing utilities, but it should at ** least compile and run. */ SQLITE_PRIVATE sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); } #endif #endif /* !defined(SQLITE_HWTIME_H) */ /************** End of hwtime.h **********************************************/ /************** Continuing where we left off in os_common.h ******************/ static sqlite_uint64 g_start; static sqlite_uint64 g_elapsed; #define TIMER_START g_start=sqlite3Hwtime() #define TIMER_END g_elapsed=sqlite3Hwtime()-g_start #define TIMER_ELAPSED g_elapsed #else #define TIMER_START #define TIMER_END #define TIMER_ELAPSED ((sqlite_uint64)0) #endif /* ** If we compile with the SQLITE_TEST macro set, then the following block ** of code will give us the ability to simulate a disk I/O error. This ** is used for testing the I/O recovery logic. */ #if defined(SQLITE_TEST) SQLITE_API extern int sqlite3_io_error_hit; SQLITE_API extern int sqlite3_io_error_hardhit; SQLITE_API extern int sqlite3_io_error_pending; SQLITE_API extern int sqlite3_io_error_persist; SQLITE_API extern int sqlite3_io_error_benign; SQLITE_API extern int sqlite3_diskfull_pending; SQLITE_API extern int sqlite3_diskfull; #define SimulateIOErrorBenign(X) sqlite3_io_error_benign=(X) #define SimulateIOError(CODE) \ if( (sqlite3_io_error_persist && sqlite3_io_error_hit) \ || sqlite3_io_error_pending-- == 1 ) \ { local_ioerr(); CODE; } static void local_ioerr(){ IOTRACE(("IOERR\n")); sqlite3_io_error_hit++; if( !sqlite3_io_error_benign ) sqlite3_io_error_hardhit++; } #define SimulateDiskfullError(CODE) \ if( sqlite3_diskfull_pending ){ \ if( sqlite3_diskfull_pending == 1 ){ \ local_ioerr(); \ sqlite3_diskfull = 1; \ sqlite3_io_error_hit = 1; \ CODE; \ }else{ \ sqlite3_diskfull_pending--; \ } \ } #else #define SimulateIOErrorBenign(X) #define SimulateIOError(A) #define SimulateDiskfullError(A) #endif /* defined(SQLITE_TEST) */ /* ** When testing, keep a count of the number of open files. */ #if defined(SQLITE_TEST) SQLITE_API extern int sqlite3_open_file_count; #define OpenCounter(X) sqlite3_open_file_count+=(X) #else #define OpenCounter(X) #endif /* defined(SQLITE_TEST) */ #endif /* !defined(_OS_COMMON_H_) */ /************** End of os_common.h *******************************************/ /************** Continuing where we left off in mutex_w32.c ******************/ /* ** Include the header file for the Windows VFS. */ /************** Include os_win.h in the middle of mutex_w32.c ****************/ /************** Begin file os_win.h ******************************************/ /* ** 2013 November 25 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ****************************************************************************** ** ** This file contains code that is specific to Windows. */ #ifndef SQLITE_OS_WIN_H #define SQLITE_OS_WIN_H /* ** Include the primary Windows SDK header file. */ #include "windows.h" #ifdef __CYGWIN__ # include # include /* amalgamator: dontcache */ #endif /* ** Determine if we are dealing with Windows NT. ** ** We ought to be able to determine if we are compiling for Windows 9x or ** Windows NT using the _WIN32_WINNT macro as follows: ** ** #if defined(_WIN32_WINNT) ** # define SQLITE_OS_WINNT 1 ** #else ** # define SQLITE_OS_WINNT 0 ** #endif ** ** However, Visual Studio 2005 does not set _WIN32_WINNT by default, as ** it ought to, so the above test does not work. We'll just assume that ** everything is Windows NT unless the programmer explicitly says otherwise ** by setting SQLITE_OS_WINNT to 0. */ #if SQLITE_OS_WIN && !defined(SQLITE_OS_WINNT) # define SQLITE_OS_WINNT 1 #endif /* ** Determine if we are dealing with Windows CE - which has a much reduced ** API. */ #if defined(_WIN32_WCE) # define SQLITE_OS_WINCE 1 #else # define SQLITE_OS_WINCE 0 #endif /* ** Determine if we are dealing with WinRT, which provides only a subset of ** the full Win32 API. */ #if !defined(SQLITE_OS_WINRT) # define SQLITE_OS_WINRT 0 #endif /* ** For WinCE, some API function parameters do not appear to be declared as ** volatile. */ #if SQLITE_OS_WINCE # define SQLITE_WIN32_VOLATILE #else # define SQLITE_WIN32_VOLATILE volatile #endif /* ** For some Windows sub-platforms, the _beginthreadex() / _endthreadex() ** functions are not available (e.g. those not using MSVC, Cygwin, etc). */ #if SQLITE_OS_WIN && !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && \ SQLITE_THREADSAFE>0 && !defined(__CYGWIN__) # define SQLITE_OS_WIN_THREADS 1 #else # define SQLITE_OS_WIN_THREADS 0 #endif #endif /* SQLITE_OS_WIN_H */ /************** End of os_win.h **********************************************/ /************** Continuing where we left off in mutex_w32.c ******************/ #endif /* ** The code in this file is only used if we are compiling multithreaded ** on a Win32 system. */ #ifdef SQLITE_MUTEX_W32 /* ** Each recursive mutex is an instance of the following structure. */ struct sqlite3_mutex { CRITICAL_SECTION mutex; /* Mutex controlling the lock */ int id; /* Mutex type */ #ifdef SQLITE_DEBUG volatile int nRef; /* Number of enterances */ volatile DWORD owner; /* Thread holding this mutex */ volatile int trace; /* True to trace changes */ #endif }; /* ** These are the initializer values used when declaring a "static" mutex ** on Win32. It should be noted that all mutexes require initialization ** on the Win32 platform. */ #define SQLITE_W32_MUTEX_INITIALIZER { 0 } #ifdef SQLITE_DEBUG #define SQLITE3_MUTEX_INITIALIZER { SQLITE_W32_MUTEX_INITIALIZER, 0, \ 0L, (DWORD)0, 0 } #else #define SQLITE3_MUTEX_INITIALIZER { SQLITE_W32_MUTEX_INITIALIZER, 0 } #endif #ifdef SQLITE_DEBUG /* ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are ** intended for use only inside assert() statements. */ static int winMutexHeld(sqlite3_mutex *p){ return p->nRef!=0 && p->owner==GetCurrentThreadId(); } static int winMutexNotheld2(sqlite3_mutex *p, DWORD tid){ return p->nRef==0 || p->owner!=tid; } static int winMutexNotheld(sqlite3_mutex *p){ DWORD tid = GetCurrentThreadId(); return winMutexNotheld2(p, tid); } #endif /* ** Try to provide a memory barrier operation, needed for initialization ** and also for the xShmBarrier method of the VFS in cases when SQLite is ** compiled without mutexes (SQLITE_THREADSAFE=0). */ SQLITE_PRIVATE void sqlite3MemoryBarrier(void){ #if defined(SQLITE_MEMORY_BARRIER) SQLITE_MEMORY_BARRIER; #elif defined(__GNUC__) __sync_synchronize(); #elif !defined(SQLITE_DISABLE_INTRINSIC) && \ defined(_MSC_VER) && _MSC_VER>=1300 _ReadWriteBarrier(); #elif defined(MemoryBarrier) MemoryBarrier(); #endif } /* ** Initialize and deinitialize the mutex subsystem. */ static sqlite3_mutex winMutex_staticMutexes[] = { SQLITE3_MUTEX_INITIALIZER, SQLITE3_MUTEX_INITIALIZER, SQLITE3_MUTEX_INITIALIZER, SQLITE3_MUTEX_INITIALIZER, SQLITE3_MUTEX_INITIALIZER, SQLITE3_MUTEX_INITIALIZER, SQLITE3_MUTEX_INITIALIZER, SQLITE3_MUTEX_INITIALIZER, SQLITE3_MUTEX_INITIALIZER, SQLITE3_MUTEX_INITIALIZER, SQLITE3_MUTEX_INITIALIZER, SQLITE3_MUTEX_INITIALIZER }; static int winMutex_isInit = 0; static int winMutex_isNt = -1; /* <0 means "need to query" */ /* As the winMutexInit() and winMutexEnd() functions are called as part ** of the sqlite3_initialize() and sqlite3_shutdown() processing, the ** "interlocked" magic used here is probably not strictly necessary. */ static LONG SQLITE_WIN32_VOLATILE winMutex_lock = 0; SQLITE_API int sqlite3_win32_is_nt(void); /* os_win.c */ SQLITE_API void sqlite3_win32_sleep(DWORD milliseconds); /* os_win.c */ static int winMutexInit(void){ /* The first to increment to 1 does actual initialization */ if( InterlockedCompareExchange(&winMutex_lock, 1, 0)==0 ){ int i; for(i=0; i **
  • SQLITE_MUTEX_FAST **
  • SQLITE_MUTEX_RECURSIVE **
  • SQLITE_MUTEX_STATIC_MASTER **
  • SQLITE_MUTEX_STATIC_MEM **
  • SQLITE_MUTEX_STATIC_OPEN **
  • SQLITE_MUTEX_STATIC_PRNG **
  • SQLITE_MUTEX_STATIC_LRU **
  • SQLITE_MUTEX_STATIC_PMEM **
  • SQLITE_MUTEX_STATIC_APP1 **
  • SQLITE_MUTEX_STATIC_APP2 **
  • SQLITE_MUTEX_STATIC_APP3 **
  • SQLITE_MUTEX_STATIC_VFS1 **
  • SQLITE_MUTEX_STATIC_VFS2 **
  • SQLITE_MUTEX_STATIC_VFS3 ** ** ** The first two constants cause sqlite3_mutex_alloc() to create ** a new mutex. The new mutex is recursive when SQLITE_MUTEX_RECURSIVE ** is used but not necessarily so when SQLITE_MUTEX_FAST is used. ** The mutex implementation does not need to make a distinction ** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does ** not want to. But SQLite will only request a recursive mutex in ** cases where it really needs one. If a faster non-recursive mutex ** implementation is available on the host platform, the mutex subsystem ** might return such a mutex in response to SQLITE_MUTEX_FAST. ** ** The other allowed parameters to sqlite3_mutex_alloc() each return ** a pointer to a static preexisting mutex. Six static mutexes are ** used by the current version of SQLite. Future versions of SQLite ** may add additional static mutexes. Static mutexes are for internal ** use by SQLite only. Applications that use SQLite mutexes should ** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or ** SQLITE_MUTEX_RECURSIVE. ** ** Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST ** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc() ** returns a different mutex on every call. But for the static ** mutex types, the same mutex is returned on every call that has ** the same type number. */ static sqlite3_mutex *winMutexAlloc(int iType){ sqlite3_mutex *p; switch( iType ){ case SQLITE_MUTEX_FAST: case SQLITE_MUTEX_RECURSIVE: { p = sqlite3MallocZero( sizeof(*p) ); if( p ){ p->id = iType; #ifdef SQLITE_DEBUG #ifdef SQLITE_WIN32_MUTEX_TRACE_DYNAMIC p->trace = 1; #endif #endif #if SQLITE_OS_WINRT InitializeCriticalSectionEx(&p->mutex, 0, 0); #else InitializeCriticalSection(&p->mutex); #endif } break; } default: { #ifdef SQLITE_ENABLE_API_ARMOR if( iType-2<0 || iType-2>=ArraySize(winMutex_staticMutexes) ){ (void)SQLITE_MISUSE_BKPT; return 0; } #endif p = &winMutex_staticMutexes[iType-2]; p->id = iType; #ifdef SQLITE_DEBUG #ifdef SQLITE_WIN32_MUTEX_TRACE_STATIC p->trace = 1; #endif #endif break; } } return p; } /* ** This routine deallocates a previously ** allocated mutex. SQLite is careful to deallocate every ** mutex that it allocates. */ static void winMutexFree(sqlite3_mutex *p){ assert( p ); assert( p->nRef==0 && p->owner==0 ); if( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE ){ DeleteCriticalSection(&p->mutex); sqlite3_free(p); }else{ #ifdef SQLITE_ENABLE_API_ARMOR (void)SQLITE_MISUSE_BKPT; #endif } } /* ** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt ** to enter a mutex. If another thread is already within the mutex, ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return ** SQLITE_BUSY. The sqlite3_mutex_try() interface returns SQLITE_OK ** upon successful entry. Mutexes created using SQLITE_MUTEX_RECURSIVE can ** be entered multiple times by the same thread. In such cases the, ** mutex must be exited an equal number of times before another thread ** can enter. If the same thread tries to enter any other kind of mutex ** more than once, the behavior is undefined. */ static void winMutexEnter(sqlite3_mutex *p){ #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST) DWORD tid = GetCurrentThreadId(); #endif #ifdef SQLITE_DEBUG assert( p ); assert( p->id==SQLITE_MUTEX_RECURSIVE || winMutexNotheld2(p, tid) ); #else assert( p ); #endif assert( winMutex_isInit==1 ); EnterCriticalSection(&p->mutex); #ifdef SQLITE_DEBUG assert( p->nRef>0 || p->owner==0 ); p->owner = tid; p->nRef++; if( p->trace ){ OSTRACE(("ENTER-MUTEX tid=%lu, mutex=%p (%d), nRef=%d\n", tid, p, p->trace, p->nRef)); } #endif } static int winMutexTry(sqlite3_mutex *p){ #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST) DWORD tid = GetCurrentThreadId(); #endif int rc = SQLITE_BUSY; assert( p ); assert( p->id==SQLITE_MUTEX_RECURSIVE || winMutexNotheld2(p, tid) ); /* ** The sqlite3_mutex_try() routine is very rarely used, and when it ** is used it is merely an optimization. So it is OK for it to always ** fail. ** ** The TryEnterCriticalSection() interface is only available on WinNT. ** And some windows compilers complain if you try to use it without ** first doing some #defines that prevent SQLite from building on Win98. ** For that reason, we will omit this optimization for now. See ** ticket #2685. */ #if defined(_WIN32_WINNT) && _WIN32_WINNT >= 0x0400 assert( winMutex_isInit==1 ); assert( winMutex_isNt>=-1 && winMutex_isNt<=1 ); if( winMutex_isNt<0 ){ winMutex_isNt = sqlite3_win32_is_nt(); } assert( winMutex_isNt==0 || winMutex_isNt==1 ); if( winMutex_isNt && TryEnterCriticalSection(&p->mutex) ){ #ifdef SQLITE_DEBUG p->owner = tid; p->nRef++; #endif rc = SQLITE_OK; } #else UNUSED_PARAMETER(p); #endif #ifdef SQLITE_DEBUG if( p->trace ){ OSTRACE(("TRY-MUTEX tid=%lu, mutex=%p (%d), owner=%lu, nRef=%d, rc=%s\n", tid, p, p->trace, p->owner, p->nRef, sqlite3ErrName(rc))); } #endif return rc; } /* ** The sqlite3_mutex_leave() routine exits a mutex that was ** previously entered by the same thread. The behavior ** is undefined if the mutex is not currently entered or ** is not currently allocated. SQLite will never do either. */ static void winMutexLeave(sqlite3_mutex *p){ #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST) DWORD tid = GetCurrentThreadId(); #endif assert( p ); #ifdef SQLITE_DEBUG assert( p->nRef>0 ); assert( p->owner==tid ); p->nRef--; if( p->nRef==0 ) p->owner = 0; assert( p->nRef==0 || p->id==SQLITE_MUTEX_RECURSIVE ); #endif assert( winMutex_isInit==1 ); LeaveCriticalSection(&p->mutex); #ifdef SQLITE_DEBUG if( p->trace ){ OSTRACE(("LEAVE-MUTEX tid=%lu, mutex=%p (%d), nRef=%d\n", tid, p, p->trace, p->nRef)); } #endif } SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void){ static const sqlite3_mutex_methods sMutex = { winMutexInit, winMutexEnd, winMutexAlloc, winMutexFree, winMutexEnter, winMutexTry, winMutexLeave, #ifdef SQLITE_DEBUG winMutexHeld, winMutexNotheld #else 0, 0 #endif }; return &sMutex; } #endif /* SQLITE_MUTEX_W32 */ /************** End of mutex_w32.c *******************************************/ /************** Begin file malloc.c ******************************************/ /* ** 2001 September 15 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ************************************************************************* ** ** Memory allocation functions used throughout sqlite. */ /* #include "sqliteInt.h" */ /* #include */ /* ** Attempt to release up to n bytes of non-essential memory currently ** held by SQLite. An example of non-essential memory is memory used to ** cache database pages that are not currently in use. */ SQLITE_API int sqlite3_release_memory(int n){ #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT return sqlite3PcacheReleaseMemory(n); #else /* IMPLEMENTATION-OF: R-34391-24921 The sqlite3_release_memory() routine ** is a no-op returning zero if SQLite is not compiled with ** SQLITE_ENABLE_MEMORY_MANAGEMENT. */ UNUSED_PARAMETER(n); return 0; #endif } /* ** An instance of the following object records the location of ** each unused scratch buffer. */ typedef struct ScratchFreeslot { struct ScratchFreeslot *pNext; /* Next unused scratch buffer */ } ScratchFreeslot; /* ** State information local to the memory allocation subsystem. */ static SQLITE_WSD struct Mem0Global { sqlite3_mutex *mutex; /* Mutex to serialize access */ sqlite3_int64 alarmThreshold; /* The soft heap limit */ /* ** Pointers to the end of sqlite3GlobalConfig.pScratch memory ** (so that a range test can be used to determine if an allocation ** being freed came from pScratch) and a pointer to the list of ** unused scratch allocations. */ void *pScratchEnd; ScratchFreeslot *pScratchFree; u32 nScratchFree; /* ** True if heap is nearly "full" where "full" is defined by the ** sqlite3_soft_heap_limit() setting. */ int nearlyFull; } mem0 = { 0, 0, 0, 0, 0, 0 }; #define mem0 GLOBAL(struct Mem0Global, mem0) /* ** Return the memory allocator mutex. sqlite3_status() needs it. */ SQLITE_PRIVATE sqlite3_mutex *sqlite3MallocMutex(void){ return mem0.mutex; } #ifndef SQLITE_OMIT_DEPRECATED /* ** Deprecated external interface. It used to set an alarm callback ** that was invoked when memory usage grew too large. Now it is a ** no-op. */ SQLITE_API int sqlite3_memory_alarm( void(*xCallback)(void *pArg, sqlite3_int64 used,int N), void *pArg, sqlite3_int64 iThreshold ){ (void)xCallback; (void)pArg; (void)iThreshold; return SQLITE_OK; } #endif /* ** Set the soft heap-size limit for the library. Passing a zero or ** negative value indicates no limit. */ SQLITE_API sqlite3_int64 sqlite3_soft_heap_limit64(sqlite3_int64 n){ sqlite3_int64 priorLimit; sqlite3_int64 excess; sqlite3_int64 nUsed; #ifndef SQLITE_OMIT_AUTOINIT int rc = sqlite3_initialize(); if( rc ) return -1; #endif sqlite3_mutex_enter(mem0.mutex); priorLimit = mem0.alarmThreshold; if( n<0 ){ sqlite3_mutex_leave(mem0.mutex); return priorLimit; } mem0.alarmThreshold = n; nUsed = sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED); mem0.nearlyFull = (n>0 && n<=nUsed); sqlite3_mutex_leave(mem0.mutex); excess = sqlite3_memory_used() - n; if( excess>0 ) sqlite3_release_memory((int)(excess & 0x7fffffff)); return priorLimit; } SQLITE_API void sqlite3_soft_heap_limit(int n){ if( n<0 ) n = 0; sqlite3_soft_heap_limit64(n); } /* ** Initialize the memory allocation subsystem. */ SQLITE_PRIVATE int sqlite3MallocInit(void){ int rc; if( sqlite3GlobalConfig.m.xMalloc==0 ){ sqlite3MemSetDefault(); } memset(&mem0, 0, sizeof(mem0)); mem0.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM); if( sqlite3GlobalConfig.pScratch && sqlite3GlobalConfig.szScratch>=100 && sqlite3GlobalConfig.nScratch>0 ){ int i, n, sz; ScratchFreeslot *pSlot; sz = ROUNDDOWN8(sqlite3GlobalConfig.szScratch); sqlite3GlobalConfig.szScratch = sz; pSlot = (ScratchFreeslot*)sqlite3GlobalConfig.pScratch; n = sqlite3GlobalConfig.nScratch; mem0.pScratchFree = pSlot; mem0.nScratchFree = n; for(i=0; ipNext = (ScratchFreeslot*)(sz+(char*)pSlot); pSlot = pSlot->pNext; } pSlot->pNext = 0; mem0.pScratchEnd = (void*)&pSlot[1]; }else{ mem0.pScratchEnd = 0; sqlite3GlobalConfig.pScratch = 0; sqlite3GlobalConfig.szScratch = 0; sqlite3GlobalConfig.nScratch = 0; } if( sqlite3GlobalConfig.pPage==0 || sqlite3GlobalConfig.szPage<512 || sqlite3GlobalConfig.nPage<=0 ){ sqlite3GlobalConfig.pPage = 0; sqlite3GlobalConfig.szPage = 0; } rc = sqlite3GlobalConfig.m.xInit(sqlite3GlobalConfig.m.pAppData); if( rc!=SQLITE_OK ) memset(&mem0, 0, sizeof(mem0)); return rc; } /* ** Return true if the heap is currently under memory pressure - in other ** words if the amount of heap used is close to the limit set by ** sqlite3_soft_heap_limit(). */ SQLITE_PRIVATE int sqlite3HeapNearlyFull(void){ return mem0.nearlyFull; } /* ** Deinitialize the memory allocation subsystem. */ SQLITE_PRIVATE void sqlite3MallocEnd(void){ if( sqlite3GlobalConfig.m.xShutdown ){ sqlite3GlobalConfig.m.xShutdown(sqlite3GlobalConfig.m.pAppData); } memset(&mem0, 0, sizeof(mem0)); } /* ** Return the amount of memory currently checked out. */ SQLITE_API sqlite3_int64 sqlite3_memory_used(void){ sqlite3_int64 res, mx; sqlite3_status64(SQLITE_STATUS_MEMORY_USED, &res, &mx, 0); return res; } /* ** Return the maximum amount of memory that has ever been ** checked out since either the beginning of this process ** or since the most recent reset. */ SQLITE_API sqlite3_int64 sqlite3_memory_highwater(int resetFlag){ sqlite3_int64 res, mx; sqlite3_status64(SQLITE_STATUS_MEMORY_USED, &res, &mx, resetFlag); return mx; } /* ** Trigger the alarm */ static void sqlite3MallocAlarm(int nByte){ if( mem0.alarmThreshold<=0 ) return; sqlite3_mutex_leave(mem0.mutex); sqlite3_release_memory(nByte); sqlite3_mutex_enter(mem0.mutex); } /* ** Do a memory allocation with statistics and alarms. Assume the ** lock is already held. */ static int mallocWithAlarm(int n, void **pp){ int nFull; void *p; assert( sqlite3_mutex_held(mem0.mutex) ); nFull = sqlite3GlobalConfig.m.xRoundup(n); sqlite3StatusHighwater(SQLITE_STATUS_MALLOC_SIZE, n); if( mem0.alarmThreshold>0 ){ sqlite3_int64 nUsed = sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED); if( nUsed >= mem0.alarmThreshold - nFull ){ mem0.nearlyFull = 1; sqlite3MallocAlarm(nFull); }else{ mem0.nearlyFull = 0; } } p = sqlite3GlobalConfig.m.xMalloc(nFull); #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT if( p==0 && mem0.alarmThreshold>0 ){ sqlite3MallocAlarm(nFull); p = sqlite3GlobalConfig.m.xMalloc(nFull); } #endif if( p ){ nFull = sqlite3MallocSize(p); sqlite3StatusUp(SQLITE_STATUS_MEMORY_USED, nFull); sqlite3StatusUp(SQLITE_STATUS_MALLOC_COUNT, 1); } *pp = p; return nFull; } /* ** Allocate memory. This routine is like sqlite3_malloc() except that it ** assumes the memory subsystem has already been initialized. */ SQLITE_PRIVATE void *sqlite3Malloc(u64 n){ void *p; if( n==0 || n>=0x7fffff00 ){ /* A memory allocation of a number of bytes which is near the maximum ** signed integer value might cause an integer overflow inside of the ** xMalloc(). Hence we limit the maximum size to 0x7fffff00, giving ** 255 bytes of overhead. SQLite itself will never use anything near ** this amount. The only way to reach the limit is with sqlite3_malloc() */ p = 0; }else if( sqlite3GlobalConfig.bMemstat ){ sqlite3_mutex_enter(mem0.mutex); mallocWithAlarm((int)n, &p); sqlite3_mutex_leave(mem0.mutex); }else{ p = sqlite3GlobalConfig.m.xMalloc((int)n); } assert( EIGHT_BYTE_ALIGNMENT(p) ); /* IMP: R-11148-40995 */ return p; } /* ** This version of the memory allocation is for use by the application. ** First make sure the memory subsystem is initialized, then do the ** allocation. */ SQLITE_API void *sqlite3_malloc(int n){ #ifndef SQLITE_OMIT_AUTOINIT if( sqlite3_initialize() ) return 0; #endif return n<=0 ? 0 : sqlite3Malloc(n); } SQLITE_API void *sqlite3_malloc64(sqlite3_uint64 n){ #ifndef SQLITE_OMIT_AUTOINIT if( sqlite3_initialize() ) return 0; #endif return sqlite3Malloc(n); } /* ** Each thread may only have a single outstanding allocation from ** xScratchMalloc(). We verify this constraint in the single-threaded ** case by setting scratchAllocOut to 1 when an allocation ** is outstanding clearing it when the allocation is freed. */ #if SQLITE_THREADSAFE==0 && !defined(NDEBUG) static int scratchAllocOut = 0; #endif /* ** Allocate memory that is to be used and released right away. ** This routine is similar to alloca() in that it is not intended ** for situations where the memory might be held long-term. This ** routine is intended to get memory to old large transient data ** structures that would not normally fit on the stack of an ** embedded processor. */ SQLITE_PRIVATE void *sqlite3ScratchMalloc(int n){ void *p; assert( n>0 ); sqlite3_mutex_enter(mem0.mutex); sqlite3StatusHighwater(SQLITE_STATUS_SCRATCH_SIZE, n); if( mem0.nScratchFree && sqlite3GlobalConfig.szScratch>=n ){ p = mem0.pScratchFree; mem0.pScratchFree = mem0.pScratchFree->pNext; mem0.nScratchFree--; sqlite3StatusUp(SQLITE_STATUS_SCRATCH_USED, 1); sqlite3_mutex_leave(mem0.mutex); }else{ sqlite3_mutex_leave(mem0.mutex); p = sqlite3Malloc(n); if( sqlite3GlobalConfig.bMemstat && p ){ sqlite3_mutex_enter(mem0.mutex); sqlite3StatusUp(SQLITE_STATUS_SCRATCH_OVERFLOW, sqlite3MallocSize(p)); sqlite3_mutex_leave(mem0.mutex); } sqlite3MemdebugSetType(p, MEMTYPE_SCRATCH); } assert( sqlite3_mutex_notheld(mem0.mutex) ); #if SQLITE_THREADSAFE==0 && !defined(NDEBUG) /* EVIDENCE-OF: R-12970-05880 SQLite will not use more than one scratch ** buffers per thread. ** ** This can only be checked in single-threaded mode. */ assert( scratchAllocOut==0 ); if( p ) scratchAllocOut++; #endif return p; } SQLITE_PRIVATE void sqlite3ScratchFree(void *p){ if( p ){ #if SQLITE_THREADSAFE==0 && !defined(NDEBUG) /* Verify that no more than two scratch allocation per thread ** is outstanding at one time. (This is only checked in the ** single-threaded case since checking in the multi-threaded case ** would be much more complicated.) */ assert( scratchAllocOut>=1 && scratchAllocOut<=2 ); scratchAllocOut--; #endif if( SQLITE_WITHIN(p, sqlite3GlobalConfig.pScratch, mem0.pScratchEnd) ){ /* Release memory from the SQLITE_CONFIG_SCRATCH allocation */ ScratchFreeslot *pSlot; pSlot = (ScratchFreeslot*)p; sqlite3_mutex_enter(mem0.mutex); pSlot->pNext = mem0.pScratchFree; mem0.pScratchFree = pSlot; mem0.nScratchFree++; assert( mem0.nScratchFree <= (u32)sqlite3GlobalConfig.nScratch ); sqlite3StatusDown(SQLITE_STATUS_SCRATCH_USED, 1); sqlite3_mutex_leave(mem0.mutex); }else{ /* Release memory back to the heap */ assert( sqlite3MemdebugHasType(p, MEMTYPE_SCRATCH) ); assert( sqlite3MemdebugNoType(p, (u8)~MEMTYPE_SCRATCH) ); sqlite3MemdebugSetType(p, MEMTYPE_HEAP); if( sqlite3GlobalConfig.bMemstat ){ int iSize = sqlite3MallocSize(p); sqlite3_mutex_enter(mem0.mutex); sqlite3StatusDown(SQLITE_STATUS_SCRATCH_OVERFLOW, iSize); sqlite3StatusDown(SQLITE_STATUS_MEMORY_USED, iSize); sqlite3StatusDown(SQLITE_STATUS_MALLOC_COUNT, 1); sqlite3GlobalConfig.m.xFree(p); sqlite3_mutex_leave(mem0.mutex); }else{ sqlite3GlobalConfig.m.xFree(p); } } } } /* ** TRUE if p is a lookaside memory allocation from db */ #ifndef SQLITE_OMIT_LOOKASIDE static int isLookaside(sqlite3 *db, void *p){ return SQLITE_WITHIN(p, db->lookaside.pStart, db->lookaside.pEnd); } #else #define isLookaside(A,B) 0 #endif /* ** Return the size of a memory allocation previously obtained from ** sqlite3Malloc() or sqlite3_malloc(). */ SQLITE_PRIVATE int sqlite3MallocSize(void *p){ assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) ); return sqlite3GlobalConfig.m.xSize(p); } SQLITE_PRIVATE int sqlite3DbMallocSize(sqlite3 *db, void *p){ assert( p!=0 ); if( db==0 || !isLookaside(db,p) ){ #if SQLITE_DEBUG if( db==0 ){ assert( sqlite3MemdebugNoType(p, (u8)~MEMTYPE_HEAP) ); assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) ); }else{ assert( sqlite3MemdebugHasType(p, (MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) ); assert( sqlite3MemdebugNoType(p, (u8)~(MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) ); } #endif return sqlite3GlobalConfig.m.xSize(p); }else{ assert( sqlite3_mutex_held(db->mutex) ); return db->lookaside.sz; } } SQLITE_API sqlite3_uint64 sqlite3_msize(void *p){ assert( sqlite3MemdebugNoType(p, (u8)~MEMTYPE_HEAP) ); assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) ); return p ? sqlite3GlobalConfig.m.xSize(p) : 0; } /* ** Free memory previously obtained from sqlite3Malloc(). */ SQLITE_API void sqlite3_free(void *p){ if( p==0 ) return; /* IMP: R-49053-54554 */ assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) ); assert( sqlite3MemdebugNoType(p, (u8)~MEMTYPE_HEAP) ); if( sqlite3GlobalConfig.bMemstat ){ sqlite3_mutex_enter(mem0.mutex); sqlite3StatusDown(SQLITE_STATUS_MEMORY_USED, sqlite3MallocSize(p)); sqlite3StatusDown(SQLITE_STATUS_MALLOC_COUNT, 1); sqlite3GlobalConfig.m.xFree(p); sqlite3_mutex_leave(mem0.mutex); }else{ sqlite3GlobalConfig.m.xFree(p); } } /* ** Add the size of memory allocation "p" to the count in ** *db->pnBytesFreed. */ static SQLITE_NOINLINE void measureAllocationSize(sqlite3 *db, void *p){ *db->pnBytesFreed += sqlite3DbMallocSize(db,p); } /* ** Free memory that might be associated with a particular database ** connection. */ SQLITE_PRIVATE void sqlite3DbFree(sqlite3 *db, void *p){ assert( db==0 || sqlite3_mutex_held(db->mutex) ); if( p==0 ) return; if( db ){ if( db->pnBytesFreed ){ measureAllocationSize(db, p); return; } if( isLookaside(db, p) ){ LookasideSlot *pBuf = (LookasideSlot*)p; #if SQLITE_DEBUG /* Trash all content in the buffer being freed */ memset(p, 0xaa, db->lookaside.sz); #endif pBuf->pNext = db->lookaside.pFree; db->lookaside.pFree = pBuf; db->lookaside.nOut--; return; } } assert( sqlite3MemdebugHasType(p, (MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) ); assert( sqlite3MemdebugNoType(p, (u8)~(MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) ); assert( db!=0 || sqlite3MemdebugNoType(p, MEMTYPE_LOOKASIDE) ); sqlite3MemdebugSetType(p, MEMTYPE_HEAP); sqlite3_free(p); } /* ** Change the size of an existing memory allocation */ SQLITE_PRIVATE void *sqlite3Realloc(void *pOld, u64 nBytes){ int nOld, nNew, nDiff; void *pNew; assert( sqlite3MemdebugHasType(pOld, MEMTYPE_HEAP) ); assert( sqlite3MemdebugNoType(pOld, (u8)~MEMTYPE_HEAP) ); if( pOld==0 ){ return sqlite3Malloc(nBytes); /* IMP: R-04300-56712 */ } if( nBytes==0 ){ sqlite3_free(pOld); /* IMP: R-26507-47431 */ return 0; } if( nBytes>=0x7fffff00 ){ /* The 0x7ffff00 limit term is explained in comments on sqlite3Malloc() */ return 0; } nOld = sqlite3MallocSize(pOld); /* IMPLEMENTATION-OF: R-46199-30249 SQLite guarantees that the second ** argument to xRealloc is always a value returned by a prior call to ** xRoundup. */ nNew = sqlite3GlobalConfig.m.xRoundup((int)nBytes); if( nOld==nNew ){ pNew = pOld; }else if( sqlite3GlobalConfig.bMemstat ){ sqlite3_mutex_enter(mem0.mutex); sqlite3StatusHighwater(SQLITE_STATUS_MALLOC_SIZE, (int)nBytes); nDiff = nNew - nOld; if( sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED) >= mem0.alarmThreshold-nDiff ){ sqlite3MallocAlarm(nDiff); } pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew); if( pNew==0 && mem0.alarmThreshold>0 ){ sqlite3MallocAlarm((int)nBytes); pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew); } if( pNew ){ nNew = sqlite3MallocSize(pNew); sqlite3StatusUp(SQLITE_STATUS_MEMORY_USED, nNew-nOld); } sqlite3_mutex_leave(mem0.mutex); }else{ pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew); } assert( EIGHT_BYTE_ALIGNMENT(pNew) ); /* IMP: R-11148-40995 */ return pNew; } /* ** The public interface to sqlite3Realloc. Make sure that the memory ** subsystem is initialized prior to invoking sqliteRealloc. */ SQLITE_API void *sqlite3_realloc(void *pOld, int n){ #ifndef SQLITE_OMIT_AUTOINIT if( sqlite3_initialize() ) return 0; #endif if( n<0 ) n = 0; /* IMP: R-26507-47431 */ return sqlite3Realloc(pOld, n); } SQLITE_API void *sqlite3_realloc64(void *pOld, sqlite3_uint64 n){ #ifndef SQLITE_OMIT_AUTOINIT if( sqlite3_initialize() ) return 0; #endif return sqlite3Realloc(pOld, n); } /* ** Allocate and zero memory. */ SQLITE_PRIVATE void *sqlite3MallocZero(u64 n){ void *p = sqlite3Malloc(n); if( p ){ memset(p, 0, (size_t)n); } return p; } /* ** Allocate and zero memory. If the allocation fails, make ** the mallocFailed flag in the connection pointer. */ SQLITE_PRIVATE void *sqlite3DbMallocZero(sqlite3 *db, u64 n){ void *p; testcase( db==0 ); p = sqlite3DbMallocRaw(db, n); if( p ) memset(p, 0, (size_t)n); return p; } /* Finish the work of sqlite3DbMallocRawNN for the unusual and ** slower case when the allocation cannot be fulfilled using lookaside. */ static SQLITE_NOINLINE void *dbMallocRawFinish(sqlite3 *db, u64 n){ void *p; assert( db!=0 ); p = sqlite3Malloc(n); if( !p ) sqlite3OomFault(db); sqlite3MemdebugSetType(p, (db->lookaside.bDisable==0) ? MEMTYPE_LOOKASIDE : MEMTYPE_HEAP); return p; } /* ** Allocate memory, either lookaside (if possible) or heap. ** If the allocation fails, set the mallocFailed flag in ** the connection pointer. ** ** If db!=0 and db->mallocFailed is true (indicating a prior malloc ** failure on the same database connection) then always return 0. ** Hence for a particular database connection, once malloc starts ** failing, it fails consistently until mallocFailed is reset. ** This is an important assumption. There are many places in the ** code that do things like this: ** ** int *a = (int*)sqlite3DbMallocRaw(db, 100); ** int *b = (int*)sqlite3DbMallocRaw(db, 200); ** if( b ) a[10] = 9; ** ** In other words, if a subsequent malloc (ex: "b") worked, it is assumed ** that all prior mallocs (ex: "a") worked too. ** ** The sqlite3MallocRawNN() variant guarantees that the "db" parameter is ** not a NULL pointer. */ SQLITE_PRIVATE void *sqlite3DbMallocRaw(sqlite3 *db, u64 n){ void *p; if( db ) return sqlite3DbMallocRawNN(db, n); p = sqlite3Malloc(n); sqlite3MemdebugSetType(p, MEMTYPE_HEAP); return p; } SQLITE_PRIVATE void *sqlite3DbMallocRawNN(sqlite3 *db, u64 n){ #ifndef SQLITE_OMIT_LOOKASIDE LookasideSlot *pBuf; assert( db!=0 ); assert( sqlite3_mutex_held(db->mutex) ); assert( db->pnBytesFreed==0 ); if( db->lookaside.bDisable==0 ){ assert( db->mallocFailed==0 ); if( n>db->lookaside.sz ){ db->lookaside.anStat[1]++; }else if( (pBuf = db->lookaside.pFree)==0 ){ db->lookaside.anStat[2]++; }else{ db->lookaside.pFree = pBuf->pNext; db->lookaside.nOut++; db->lookaside.anStat[0]++; if( db->lookaside.nOut>db->lookaside.mxOut ){ db->lookaside.mxOut = db->lookaside.nOut; } return (void*)pBuf; } }else if( db->mallocFailed ){ return 0; } #else assert( db!=0 ); assert( sqlite3_mutex_held(db->mutex) ); assert( db->pnBytesFreed==0 ); if( db->mallocFailed ){ return 0; } #endif return dbMallocRawFinish(db, n); } /* Forward declaration */ static SQLITE_NOINLINE void *dbReallocFinish(sqlite3 *db, void *p, u64 n); /* ** Resize the block of memory pointed to by p to n bytes. If the ** resize fails, set the mallocFailed flag in the connection object. */ SQLITE_PRIVATE void *sqlite3DbRealloc(sqlite3 *db, void *p, u64 n){ assert( db!=0 ); if( p==0 ) return sqlite3DbMallocRawNN(db, n); assert( sqlite3_mutex_held(db->mutex) ); if( isLookaside(db,p) && n<=db->lookaside.sz ) return p; return dbReallocFinish(db, p, n); } static SQLITE_NOINLINE void *dbReallocFinish(sqlite3 *db, void *p, u64 n){ void *pNew = 0; assert( db!=0 ); assert( p!=0 ); if( db->mallocFailed==0 ){ if( isLookaside(db, p) ){ pNew = sqlite3DbMallocRawNN(db, n); if( pNew ){ memcpy(pNew, p, db->lookaside.sz); sqlite3DbFree(db, p); } }else{ assert( sqlite3MemdebugHasType(p, (MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) ); assert( sqlite3MemdebugNoType(p, (u8)~(MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) ); sqlite3MemdebugSetType(p, MEMTYPE_HEAP); pNew = sqlite3_realloc64(p, n); if( !pNew ){ sqlite3OomFault(db); } sqlite3MemdebugSetType(pNew, (db->lookaside.bDisable==0 ? MEMTYPE_LOOKASIDE : MEMTYPE_HEAP)); } } return pNew; } /* ** Attempt to reallocate p. If the reallocation fails, then free p ** and set the mallocFailed flag in the database connection. */ SQLITE_PRIVATE void *sqlite3DbReallocOrFree(sqlite3 *db, void *p, u64 n){ void *pNew; pNew = sqlite3DbRealloc(db, p, n); if( !pNew ){ sqlite3DbFree(db, p); } return pNew; } /* ** Make a copy of a string in memory obtained from sqliteMalloc(). These ** functions call sqlite3MallocRaw() directly instead of sqliteMalloc(). This ** is because when memory debugging is turned on, these two functions are ** called via macros that record the current file and line number in the ** ThreadData structure. */ SQLITE_PRIVATE char *sqlite3DbStrDup(sqlite3 *db, const char *z){ char *zNew; size_t n; if( z==0 ){ return 0; } n = sqlite3Strlen30(z) + 1; assert( (n&0x7fffffff)==n ); zNew = sqlite3DbMallocRaw(db, (int)n); if( zNew ){ memcpy(zNew, z, n); } return zNew; } SQLITE_PRIVATE char *sqlite3DbStrNDup(sqlite3 *db, const char *z, u64 n){ char *zNew; assert( db!=0 ); if( z==0 ){ return 0; } assert( (n&0x7fffffff)==n ); zNew = sqlite3DbMallocRawNN(db, n+1); if( zNew ){ memcpy(zNew, z, (size_t)n); zNew[n] = 0; } return zNew; } /* ** Free any prior content in *pz and replace it with a copy of zNew. */ SQLITE_PRIVATE void sqlite3SetString(char **pz, sqlite3 *db, const char *zNew){ sqlite3DbFree(db, *pz); *pz = sqlite3DbStrDup(db, zNew); } /* ** Call this routine to record the fact that an OOM (out-of-memory) error ** has happened. This routine will set db->mallocFailed, and also ** temporarily disable the lookaside memory allocator and interrupt ** any running VDBEs. */ SQLITE_PRIVATE void sqlite3OomFault(sqlite3 *db){ if( db->mallocFailed==0 && db->bBenignMalloc==0 ){ db->mallocFailed = 1; if( db->nVdbeExec>0 ){ db->u1.isInterrupted = 1; } db->lookaside.bDisable++; } } /* ** This routine reactivates the memory allocator and clears the ** db->mallocFailed flag as necessary. ** ** The memory allocator is not restarted if there are running ** VDBEs. */ SQLITE_PRIVATE void sqlite3OomClear(sqlite3 *db){ if( db->mallocFailed && db->nVdbeExec==0 ){ db->mallocFailed = 0; db->u1.isInterrupted = 0; assert( db->lookaside.bDisable>0 ); db->lookaside.bDisable--; } } /* ** Take actions at the end of an API call to indicate an OOM error */ static SQLITE_NOINLINE int apiOomError(sqlite3 *db){ sqlite3OomClear(db); sqlite3Error(db, SQLITE_NOMEM); return SQLITE_NOMEM_BKPT; } /* ** This function must be called before exiting any API function (i.e. ** returning control to the user) that has called sqlite3_malloc or ** sqlite3_realloc. ** ** The returned value is normally a copy of the second argument to this ** function. However, if a malloc() failure has occurred since the previous ** invocation SQLITE_NOMEM is returned instead. ** ** If an OOM as occurred, then the connection error-code (the value ** returned by sqlite3_errcode()) is set to SQLITE_NOMEM. */ SQLITE_PRIVATE int sqlite3ApiExit(sqlite3* db, int rc){ /* If the db handle must hold the connection handle mutex here. ** Otherwise the read (and possible write) of db->mallocFailed ** is unsafe, as is the call to sqlite3Error(). */ assert( db!=0 ); assert( sqlite3_mutex_held(db->mutex) ); if( db->mallocFailed || rc==SQLITE_IOERR_NOMEM ){ return apiOomError(db); } return rc & db->errMask; } /************** End of malloc.c **********************************************/ /************** Begin file printf.c ******************************************/ /* ** The "printf" code that follows dates from the 1980's. It is in ** the public domain. ** ************************************************************************** ** ** This file contains code for a set of "printf"-like routines. These ** routines format strings much like the printf() from the standard C ** library, though the implementation here has enhancements to support ** SQLite. */ /* #include "sqliteInt.h" */ /* ** Conversion types fall into various categories as defined by the ** following enumeration. */ #define etRADIX 0 /* Integer types. %d, %x, %o, and so forth */ #define etFLOAT 1 /* Floating point. %f */ #define etEXP 2 /* Exponentional notation. %e and %E */ #define etGENERIC 3 /* Floating or exponential, depending on exponent. %g */ #define etSIZE 4 /* Return number of characters processed so far. %n */ #define etSTRING 5 /* Strings. %s */ #define etDYNSTRING 6 /* Dynamically allocated strings. %z */ #define etPERCENT 7 /* Percent symbol. %% */ #define etCHARX 8 /* Characters. %c */ /* The rest are extensions, not normally found in printf() */ #define etSQLESCAPE 9 /* Strings with '\'' doubled. %q */ #define etSQLESCAPE2 10 /* Strings with '\'' doubled and enclosed in '', NULL pointers replaced by SQL NULL. %Q */ #define etTOKEN 11 /* a pointer to a Token structure */ #define etSRCLIST 12 /* a pointer to a SrcList */ #define etPOINTER 13 /* The %p conversion */ #define etSQLESCAPE3 14 /* %w -> Strings with '\"' doubled */ #define etORDINAL 15 /* %r -> 1st, 2nd, 3rd, 4th, etc. English only */ #define etINVALID 16 /* Any unrecognized conversion type */ /* ** An "etByte" is an 8-bit unsigned value. */ typedef unsigned char etByte; /* ** Each builtin conversion character (ex: the 'd' in "%d") is described ** by an instance of the following structure */ typedef struct et_info { /* Information about each format field */ char fmttype; /* The format field code letter */ etByte base; /* The base for radix conversion */ etByte flags; /* One or more of FLAG_ constants below */ etByte type; /* Conversion paradigm */ etByte charset; /* Offset into aDigits[] of the digits string */ etByte prefix; /* Offset into aPrefix[] of the prefix string */ } et_info; /* ** Allowed values for et_info.flags */ #define FLAG_SIGNED 1 /* True if the value to convert is signed */ #define FLAG_INTERN 2 /* True if for internal use only */ #define FLAG_STRING 4 /* Allow infinity precision */ /* ** The following table is searched linearly, so it is good to put the ** most frequently used conversion types first. */ static const char aDigits[] = "0123456789ABCDEF0123456789abcdef"; static const char aPrefix[] = "-x0\000X0"; static const et_info fmtinfo[] = { { 'd', 10, 1, etRADIX, 0, 0 }, { 's', 0, 4, etSTRING, 0, 0 }, { 'g', 0, 1, etGENERIC, 30, 0 }, { 'z', 0, 4, etDYNSTRING, 0, 0 }, { 'q', 0, 4, etSQLESCAPE, 0, 0 }, { 'Q', 0, 4, etSQLESCAPE2, 0, 0 }, { 'w', 0, 4, etSQLESCAPE3, 0, 0 }, { 'c', 0, 0, etCHARX, 0, 0 }, { 'o', 8, 0, etRADIX, 0, 2 }, { 'u', 10, 0, etRADIX, 0, 0 }, { 'x', 16, 0, etRADIX, 16, 1 }, { 'X', 16, 0, etRADIX, 0, 4 }, #ifndef SQLITE_OMIT_FLOATING_POINT { 'f', 0, 1, etFLOAT, 0, 0 }, { 'e', 0, 1, etEXP, 30, 0 }, { 'E', 0, 1, etEXP, 14, 0 }, { 'G', 0, 1, etGENERIC, 14, 0 }, #endif { 'i', 10, 1, etRADIX, 0, 0 }, { 'n', 0, 0, etSIZE, 0, 0 }, { '%', 0, 0, etPERCENT, 0, 0 }, { 'p', 16, 0, etPOINTER, 0, 1 }, /* All the rest have the FLAG_INTERN bit set and are thus for internal ** use only */ { 'T', 0, 2, etTOKEN, 0, 0 }, { 'S', 0, 2, etSRCLIST, 0, 0 }, { 'r', 10, 3, etORDINAL, 0, 0 }, }; /* ** If SQLITE_OMIT_FLOATING_POINT is defined, then none of the floating point ** conversions will work. */ #ifndef SQLITE_OMIT_FLOATING_POINT /* ** "*val" is a double such that 0.1 <= *val < 10.0 ** Return the ascii code for the leading digit of *val, then ** multiply "*val" by 10.0 to renormalize. ** ** Example: ** input: *val = 3.14159 ** output: *val = 1.4159 function return = '3' ** ** The counter *cnt is incremented each time. After counter exceeds ** 16 (the number of significant digits in a 64-bit float) '0' is ** always returned. */ static char et_getdigit(LONGDOUBLE_TYPE *val, int *cnt){ int digit; LONGDOUBLE_TYPE d; if( (*cnt)<=0 ) return '0'; (*cnt)--; digit = (int)*val; d = digit; digit += '0'; *val = (*val - d)*10.0; return (char)digit; } #endif /* SQLITE_OMIT_FLOATING_POINT */ /* ** Set the StrAccum object to an error mode. */ static void setStrAccumError(StrAccum *p, u8 eError){ assert( eError==STRACCUM_NOMEM || eError==STRACCUM_TOOBIG ); p->accError = eError; p->nAlloc = 0; } /* ** Extra argument values from a PrintfArguments object */ static sqlite3_int64 getIntArg(PrintfArguments *p){ if( p->nArg<=p->nUsed ) return 0; return sqlite3_value_int64(p->apArg[p->nUsed++]); } static double getDoubleArg(PrintfArguments *p){ if( p->nArg<=p->nUsed ) return 0.0; return sqlite3_value_double(p->apArg[p->nUsed++]); } static char *getTextArg(PrintfArguments *p){ if( p->nArg<=p->nUsed ) return 0; return (char*)sqlite3_value_text(p->apArg[p->nUsed++]); } /* ** On machines with a small stack size, you can redefine the ** SQLITE_PRINT_BUF_SIZE to be something smaller, if desired. */ #ifndef SQLITE_PRINT_BUF_SIZE # define SQLITE_PRINT_BUF_SIZE 70 #endif #define etBUFSIZE SQLITE_PRINT_BUF_SIZE /* Size of the output buffer */ /* ** Render a string given by "fmt" into the StrAccum object. */ SQLITE_PRIVATE void sqlite3VXPrintf( StrAccum *pAccum, /* Accumulate results here */ const char *fmt, /* Format string */ va_list ap /* arguments */ ){ int c; /* Next character in the format string */ char *bufpt; /* Pointer to the conversion buffer */ int precision; /* Precision of the current field */ int length; /* Length of the field */ int idx; /* A general purpose loop counter */ int width; /* Width of the current field */ etByte flag_leftjustify; /* True if "-" flag is present */ etByte flag_plussign; /* True if "+" flag is present */ etByte flag_blanksign; /* True if " " flag is present */ etByte flag_alternateform; /* True if "#" flag is present */ etByte flag_altform2; /* True if "!" flag is present */ etByte flag_zeropad; /* True if field width constant starts with zero */ etByte flag_long; /* True if "l" flag is present */ etByte flag_longlong; /* True if the "ll" flag is present */ etByte done; /* Loop termination flag */ etByte xtype = etINVALID; /* Conversion paradigm */ u8 bArgList; /* True for SQLITE_PRINTF_SQLFUNC */ u8 useIntern; /* Ok to use internal conversions (ex: %T) */ char prefix; /* Prefix character. "+" or "-" or " " or '\0'. */ sqlite_uint64 longvalue; /* Value for integer types */ LONGDOUBLE_TYPE realvalue; /* Value for real types */ const et_info *infop; /* Pointer to the appropriate info structure */ char *zOut; /* Rendering buffer */ int nOut; /* Size of the rendering buffer */ char *zExtra = 0; /* Malloced memory used by some conversion */ #ifndef SQLITE_OMIT_FLOATING_POINT int exp, e2; /* exponent of real numbers */ int nsd; /* Number of significant digits returned */ double rounder; /* Used for rounding floating point values */ etByte flag_dp; /* True if decimal point should be shown */ etByte flag_rtz; /* True if trailing zeros should be removed */ #endif PrintfArguments *pArgList = 0; /* Arguments for SQLITE_PRINTF_SQLFUNC */ char buf[etBUFSIZE]; /* Conversion buffer */ bufpt = 0; if( pAccum->printfFlags ){ if( (bArgList = (pAccum->printfFlags & SQLITE_PRINTF_SQLFUNC))!=0 ){ pArgList = va_arg(ap, PrintfArguments*); } useIntern = pAccum->printfFlags & SQLITE_PRINTF_INTERNAL; }else{ bArgList = useIntern = 0; } for(; (c=(*fmt))!=0; ++fmt){ if( c!='%' ){ bufpt = (char *)fmt; #if HAVE_STRCHRNUL fmt = strchrnul(fmt, '%'); #else do{ fmt++; }while( *fmt && *fmt != '%' ); #endif sqlite3StrAccumAppend(pAccum, bufpt, (int)(fmt - bufpt)); if( *fmt==0 ) break; } if( (c=(*++fmt))==0 ){ sqlite3StrAccumAppend(pAccum, "%", 1); break; } /* Find out what flags are present */ flag_leftjustify = flag_plussign = flag_blanksign = flag_alternateform = flag_altform2 = flag_zeropad = 0; done = 0; do{ switch( c ){ case '-': flag_leftjustify = 1; break; case '+': flag_plussign = 1; break; case ' ': flag_blanksign = 1; break; case '#': flag_alternateform = 1; break; case '!': flag_altform2 = 1; break; case '0': flag_zeropad = 1; break; default: done = 1; break; } }while( !done && (c=(*++fmt))!=0 ); /* Get the field width */ if( c=='*' ){ if( bArgList ){ width = (int)getIntArg(pArgList); }else{ width = va_arg(ap,int); } if( width<0 ){ flag_leftjustify = 1; width = width >= -2147483647 ? -width : 0; } c = *++fmt; }else{ unsigned wx = 0; while( c>='0' && c<='9' ){ wx = wx*10 + c - '0'; c = *++fmt; } testcase( wx>0x7fffffff ); width = wx & 0x7fffffff; } assert( width>=0 ); #ifdef SQLITE_PRINTF_PRECISION_LIMIT if( width>SQLITE_PRINTF_PRECISION_LIMIT ){ width = SQLITE_PRINTF_PRECISION_LIMIT; } #endif /* Get the precision */ if( c=='.' ){ c = *++fmt; if( c=='*' ){ if( bArgList ){ precision = (int)getIntArg(pArgList); }else{ precision = va_arg(ap,int); } c = *++fmt; if( precision<0 ){ precision = precision >= -2147483647 ? -precision : -1; } }else{ unsigned px = 0; while( c>='0' && c<='9' ){ px = px*10 + c - '0'; c = *++fmt; } testcase( px>0x7fffffff ); precision = px & 0x7fffffff; } }else{ precision = -1; } assert( precision>=(-1) ); #ifdef SQLITE_PRINTF_PRECISION_LIMIT if( precision>SQLITE_PRINTF_PRECISION_LIMIT ){ precision = SQLITE_PRINTF_PRECISION_LIMIT; } #endif /* Get the conversion type modifier */ if( c=='l' ){ flag_long = 1; c = *++fmt; if( c=='l' ){ flag_longlong = 1; c = *++fmt; }else{ flag_longlong = 0; } }else{ flag_long = flag_longlong = 0; } /* Fetch the info entry for the field */ infop = &fmtinfo[0]; xtype = etINVALID; for(idx=0; idxflags & FLAG_INTERN)==0 ){ xtype = infop->type; }else{ return; } break; } } /* ** At this point, variables are initialized as follows: ** ** flag_alternateform TRUE if a '#' is present. ** flag_altform2 TRUE if a '!' is present. ** flag_plussign TRUE if a '+' is present. ** flag_leftjustify TRUE if a '-' is present or if the ** field width was negative. ** flag_zeropad TRUE if the width began with 0. ** flag_long TRUE if the letter 'l' (ell) prefixed ** the conversion character. ** flag_longlong TRUE if the letter 'll' (ell ell) prefixed ** the conversion character. ** flag_blanksign TRUE if a ' ' is present. ** width The specified field width. This is ** always non-negative. Zero is the default. ** precision The specified precision. The default ** is -1. ** xtype The class of the conversion. ** infop Pointer to the appropriate info struct. */ switch( xtype ){ case etPOINTER: flag_longlong = sizeof(char*)==sizeof(i64); flag_long = sizeof(char*)==sizeof(long int); /* Fall through into the next case */ case etORDINAL: case etRADIX: if( infop->flags & FLAG_SIGNED ){ i64 v; if( bArgList ){ v = getIntArg(pArgList); }else if( flag_longlong ){ v = va_arg(ap,i64); }else if( flag_long ){ v = va_arg(ap,long int); }else{ v = va_arg(ap,int); } if( v<0 ){ if( v==SMALLEST_INT64 ){ longvalue = ((u64)1)<<63; }else{ longvalue = -v; } prefix = '-'; }else{ longvalue = v; if( flag_plussign ) prefix = '+'; else if( flag_blanksign ) prefix = ' '; else prefix = 0; } }else{ if( bArgList ){ longvalue = (u64)getIntArg(pArgList); }else if( flag_longlong ){ longvalue = va_arg(ap,u64); }else if( flag_long ){ longvalue = va_arg(ap,unsigned long int); }else{ longvalue = va_arg(ap,unsigned int); } prefix = 0; } if( longvalue==0 ) flag_alternateform = 0; if( flag_zeropad && precision=4 || (longvalue/10)%10==1 ){ x = 0; } *(--bufpt) = zOrd[x*2+1]; *(--bufpt) = zOrd[x*2]; } { const char *cset = &aDigits[infop->charset]; u8 base = infop->base; do{ /* Convert to ascii */ *(--bufpt) = cset[longvalue%base]; longvalue = longvalue/base; }while( longvalue>0 ); } length = (int)(&zOut[nOut-1]-bufpt); for(idx=precision-length; idx>0; idx--){ *(--bufpt) = '0'; /* Zero pad */ } if( prefix ) *(--bufpt) = prefix; /* Add sign */ if( flag_alternateform && infop->prefix ){ /* Add "0" or "0x" */ const char *pre; char x; pre = &aPrefix[infop->prefix]; for(; (x=(*pre))!=0; pre++) *(--bufpt) = x; } length = (int)(&zOut[nOut-1]-bufpt); break; case etFLOAT: case etEXP: case etGENERIC: if( bArgList ){ realvalue = getDoubleArg(pArgList); }else{ realvalue = va_arg(ap,double); } #ifdef SQLITE_OMIT_FLOATING_POINT length = 0; #else if( precision<0 ) precision = 6; /* Set default precision */ if( realvalue<0.0 ){ realvalue = -realvalue; prefix = '-'; }else{ if( flag_plussign ) prefix = '+'; else if( flag_blanksign ) prefix = ' '; else prefix = 0; } if( xtype==etGENERIC && precision>0 ) precision--; testcase( precision>0xfff ); for(idx=precision&0xfff, rounder=0.5; idx>0; idx--, rounder*=0.1){} if( xtype==etFLOAT ) realvalue += rounder; /* Normalize realvalue to within 10.0 > realvalue >= 1.0 */ exp = 0; if( sqlite3IsNaN((double)realvalue) ){ bufpt = "NaN"; length = 3; break; } if( realvalue>0.0 ){ LONGDOUBLE_TYPE scale = 1.0; while( realvalue>=1e100*scale && exp<=350 ){ scale *= 1e100;exp+=100;} while( realvalue>=1e10*scale && exp<=350 ){ scale *= 1e10; exp+=10; } while( realvalue>=10.0*scale && exp<=350 ){ scale *= 10.0; exp++; } realvalue /= scale; while( realvalue<1e-8 ){ realvalue *= 1e8; exp-=8; } while( realvalue<1.0 ){ realvalue *= 10.0; exp--; } if( exp>350 ){ bufpt = buf; buf[0] = prefix; memcpy(buf+(prefix!=0),"Inf",4); length = 3+(prefix!=0); break; } } bufpt = buf; /* ** If the field type is etGENERIC, then convert to either etEXP ** or etFLOAT, as appropriate. */ if( xtype!=etFLOAT ){ realvalue += rounder; if( realvalue>=10.0 ){ realvalue *= 0.1; exp++; } } if( xtype==etGENERIC ){ flag_rtz = !flag_alternateform; if( exp<-4 || exp>precision ){ xtype = etEXP; }else{ precision = precision - exp; xtype = etFLOAT; } }else{ flag_rtz = flag_altform2; } if( xtype==etEXP ){ e2 = 0; }else{ e2 = exp; } if( MAX(e2,0)+(i64)precision+(i64)width > etBUFSIZE - 15 ){ bufpt = zExtra = sqlite3Malloc( MAX(e2,0)+(i64)precision+(i64)width+15 ); if( bufpt==0 ){ setStrAccumError(pAccum, STRACCUM_NOMEM); return; } } zOut = bufpt; nsd = 16 + flag_altform2*10; flag_dp = (precision>0 ?1:0) | flag_alternateform | flag_altform2; /* The sign in front of the number */ if( prefix ){ *(bufpt++) = prefix; } /* Digits prior to the decimal point */ if( e2<0 ){ *(bufpt++) = '0'; }else{ for(; e2>=0; e2--){ *(bufpt++) = et_getdigit(&realvalue,&nsd); } } /* The decimal point */ if( flag_dp ){ *(bufpt++) = '.'; } /* "0" digits after the decimal point but before the first ** significant digit of the number */ for(e2++; e2<0; precision--, e2++){ assert( precision>0 ); *(bufpt++) = '0'; } /* Significant digits after the decimal point */ while( (precision--)>0 ){ *(bufpt++) = et_getdigit(&realvalue,&nsd); } /* Remove trailing zeros and the "." if no digits follow the "." */ if( flag_rtz && flag_dp ){ while( bufpt[-1]=='0' ) *(--bufpt) = 0; assert( bufpt>zOut ); if( bufpt[-1]=='.' ){ if( flag_altform2 ){ *(bufpt++) = '0'; }else{ *(--bufpt) = 0; } } } /* Add the "eNNN" suffix */ if( xtype==etEXP ){ *(bufpt++) = aDigits[infop->charset]; if( exp<0 ){ *(bufpt++) = '-'; exp = -exp; }else{ *(bufpt++) = '+'; } if( exp>=100 ){ *(bufpt++) = (char)((exp/100)+'0'); /* 100's digit */ exp %= 100; } *(bufpt++) = (char)(exp/10+'0'); /* 10's digit */ *(bufpt++) = (char)(exp%10+'0'); /* 1's digit */ } *bufpt = 0; /* The converted number is in buf[] and zero terminated. Output it. ** Note that the number is in the usual order, not reversed as with ** integer conversions. */ length = (int)(bufpt-zOut); bufpt = zOut; /* Special case: Add leading zeros if the flag_zeropad flag is ** set and we are not left justified */ if( flag_zeropad && !flag_leftjustify && length < width){ int i; int nPad = width - length; for(i=width; i>=nPad; i--){ bufpt[i] = bufpt[i-nPad]; } i = prefix!=0; while( nPad-- ) bufpt[i++] = '0'; length = width; } #endif /* !defined(SQLITE_OMIT_FLOATING_POINT) */ break; case etSIZE: if( !bArgList ){ *(va_arg(ap,int*)) = pAccum->nChar; } length = width = 0; break; case etPERCENT: buf[0] = '%'; bufpt = buf; length = 1; break; case etCHARX: if( bArgList ){ bufpt = getTextArg(pArgList); c = bufpt ? bufpt[0] : 0; }else{ c = va_arg(ap,int); } if( precision>1 ){ width -= precision-1; if( width>1 && !flag_leftjustify ){ sqlite3AppendChar(pAccum, width-1, ' '); width = 0; } sqlite3AppendChar(pAccum, precision-1, c); } length = 1; buf[0] = c; bufpt = buf; break; case etSTRING: case etDYNSTRING: if( bArgList ){ bufpt = getTextArg(pArgList); xtype = etSTRING; }else{ bufpt = va_arg(ap,char*); } if( bufpt==0 ){ bufpt = ""; }else if( xtype==etDYNSTRING ){ zExtra = bufpt; } if( precision>=0 ){ for(length=0; lengthetBUFSIZE ){ bufpt = zExtra = sqlite3Malloc( n ); if( bufpt==0 ){ setStrAccumError(pAccum, STRACCUM_NOMEM); return; } }else{ bufpt = buf; } j = 0; if( needQuote ) bufpt[j++] = q; k = i; for(i=0; i=0 && precisionn ){ sqlite3StrAccumAppend(pAccum, (const char*)pToken->z, pToken->n); } length = width = 0; break; } case etSRCLIST: { SrcList *pSrc = va_arg(ap, SrcList*); int k = va_arg(ap, int); struct SrcList_item *pItem = &pSrc->a[k]; assert( bArgList==0 ); assert( k>=0 && knSrc ); if( pItem->zDatabase ){ sqlite3StrAccumAppendAll(pAccum, pItem->zDatabase); sqlite3StrAccumAppend(pAccum, ".", 1); } sqlite3StrAccumAppendAll(pAccum, pItem->zName); length = width = 0; break; } default: { assert( xtype==etINVALID ); return; } }/* End switch over the format type */ /* ** The text of the conversion is pointed to by "bufpt" and is ** "length" characters long. The field width is "width". Do ** the output. */ width -= length; if( width>0 && !flag_leftjustify ) sqlite3AppendChar(pAccum, width, ' '); sqlite3StrAccumAppend(pAccum, bufpt, length); if( width>0 && flag_leftjustify ) sqlite3AppendChar(pAccum, width, ' '); if( zExtra ){ sqlite3DbFree(pAccum->db, zExtra); zExtra = 0; } }/* End for loop over the format string */ } /* End of function */ /* ** Enlarge the memory allocation on a StrAccum object so that it is ** able to accept at least N more bytes of text. ** ** Return the number of bytes of text that StrAccum is able to accept ** after the attempted enlargement. The value returned might be zero. */ static int sqlite3StrAccumEnlarge(StrAccum *p, int N){ char *zNew; assert( p->nChar+(i64)N >= p->nAlloc ); /* Only called if really needed */ if( p->accError ){ testcase(p->accError==STRACCUM_TOOBIG); testcase(p->accError==STRACCUM_NOMEM); return 0; } if( p->mxAlloc==0 ){ N = p->nAlloc - p->nChar - 1; setStrAccumError(p, STRACCUM_TOOBIG); return N; }else{ char *zOld = isMalloced(p) ? p->zText : 0; i64 szNew = p->nChar; assert( (p->zText==0 || p->zText==p->zBase)==!isMalloced(p) ); szNew += N + 1; if( szNew+p->nChar<=p->mxAlloc ){ /* Force exponential buffer size growth as long as it does not overflow, ** to avoid having to call this routine too often */ szNew += p->nChar; } if( szNew > p->mxAlloc ){ sqlite3StrAccumReset(p); setStrAccumError(p, STRACCUM_TOOBIG); return 0; }else{ p->nAlloc = (int)szNew; } if( p->db ){ zNew = sqlite3DbRealloc(p->db, zOld, p->nAlloc); }else{ zNew = sqlite3_realloc64(zOld, p->nAlloc); } if( zNew ){ assert( p->zText!=0 || p->nChar==0 ); if( !isMalloced(p) && p->nChar>0 ) memcpy(zNew, p->zText, p->nChar); p->zText = zNew; p->nAlloc = sqlite3DbMallocSize(p->db, zNew); p->printfFlags |= SQLITE_PRINTF_MALLOCED; }else{ sqlite3StrAccumReset(p); setStrAccumError(p, STRACCUM_NOMEM); return 0; } } return N; } /* ** Append N copies of character c to the given string buffer. */ SQLITE_PRIVATE void sqlite3AppendChar(StrAccum *p, int N, char c){ testcase( p->nChar + (i64)N > 0x7fffffff ); if( p->nChar+(i64)N >= p->nAlloc && (N = sqlite3StrAccumEnlarge(p, N))<=0 ){ return; } assert( (p->zText==p->zBase)==!isMalloced(p) ); while( (N--)>0 ) p->zText[p->nChar++] = c; } /* ** The StrAccum "p" is not large enough to accept N new bytes of z[]. ** So enlarge if first, then do the append. ** ** This is a helper routine to sqlite3StrAccumAppend() that does special-case ** work (enlarging the buffer) using tail recursion, so that the ** sqlite3StrAccumAppend() routine can use fast calling semantics. */ static void SQLITE_NOINLINE enlargeAndAppend(StrAccum *p, const char *z, int N){ N = sqlite3StrAccumEnlarge(p, N); if( N>0 ){ memcpy(&p->zText[p->nChar], z, N); p->nChar += N; } assert( (p->zText==0 || p->zText==p->zBase)==!isMalloced(p) ); } /* ** Append N bytes of text from z to the StrAccum object. Increase the ** size of the memory allocation for StrAccum if necessary. */ SQLITE_PRIVATE void sqlite3StrAccumAppend(StrAccum *p, const char *z, int N){ assert( z!=0 || N==0 ); assert( p->zText!=0 || p->nChar==0 || p->accError ); assert( N>=0 ); assert( p->accError==0 || p->nAlloc==0 ); if( p->nChar+N >= p->nAlloc ){ enlargeAndAppend(p,z,N); }else{ assert( p->zText ); p->nChar += N; memcpy(&p->zText[p->nChar-N], z, N); } } /* ** Append the complete text of zero-terminated string z[] to the p string. */ SQLITE_PRIVATE void sqlite3StrAccumAppendAll(StrAccum *p, const char *z){ sqlite3StrAccumAppend(p, z, sqlite3Strlen30(z)); } /* ** Finish off a string by making sure it is zero-terminated. ** Return a pointer to the resulting string. Return a NULL ** pointer if any kind of error was encountered. */ SQLITE_PRIVATE char *sqlite3StrAccumFinish(StrAccum *p){ if( p->zText ){ assert( (p->zText==p->zBase)==!isMalloced(p) ); p->zText[p->nChar] = 0; if( p->mxAlloc>0 && !isMalloced(p) ){ p->zText = sqlite3DbMallocRaw(p->db, p->nChar+1 ); if( p->zText ){ memcpy(p->zText, p->zBase, p->nChar+1); p->printfFlags |= SQLITE_PRINTF_MALLOCED; }else{ setStrAccumError(p, STRACCUM_NOMEM); } } } return p->zText; } /* ** Reset an StrAccum string. Reclaim all malloced memory. */ SQLITE_PRIVATE void sqlite3StrAccumReset(StrAccum *p){ assert( (p->zText==0 || p->zText==p->zBase)==!isMalloced(p) ); if( isMalloced(p) ){ sqlite3DbFree(p->db, p->zText); p->printfFlags &= ~SQLITE_PRINTF_MALLOCED; } p->zText = 0; } /* ** Initialize a string accumulator. ** ** p: The accumulator to be initialized. ** db: Pointer to a database connection. May be NULL. Lookaside ** memory is used if not NULL. db->mallocFailed is set appropriately ** when not NULL. ** zBase: An initial buffer. May be NULL in which case the initial buffer ** is malloced. ** n: Size of zBase in bytes. If total space requirements never exceed ** n then no memory allocations ever occur. ** mx: Maximum number of bytes to accumulate. If mx==0 then no memory ** allocations will ever occur. */ SQLITE_PRIVATE void sqlite3StrAccumInit(StrAccum *p, sqlite3 *db, char *zBase, int n, int mx){ p->zText = p->zBase = zBase; p->db = db; p->nChar = 0; p->nAlloc = n; p->mxAlloc = mx; p->accError = 0; p->printfFlags = 0; } /* ** Print into memory obtained from sqliteMalloc(). Use the internal ** %-conversion extensions. */ SQLITE_PRIVATE char *sqlite3VMPrintf(sqlite3 *db, const char *zFormat, va_list ap){ char *z; char zBase[SQLITE_PRINT_BUF_SIZE]; StrAccum acc; assert( db!=0 ); sqlite3StrAccumInit(&acc, db, zBase, sizeof(zBase), db->aLimit[SQLITE_LIMIT_LENGTH]); acc.printfFlags = SQLITE_PRINTF_INTERNAL; sqlite3VXPrintf(&acc, zFormat, ap); z = sqlite3StrAccumFinish(&acc); if( acc.accError==STRACCUM_NOMEM ){ sqlite3OomFault(db); } return z; } /* ** Print into memory obtained from sqliteMalloc(). Use the internal ** %-conversion extensions. */ SQLITE_PRIVATE char *sqlite3MPrintf(sqlite3 *db, const char *zFormat, ...){ va_list ap; char *z; va_start(ap, zFormat); z = sqlite3VMPrintf(db, zFormat, ap); va_end(ap); return z; } /* ** Print into memory obtained from sqlite3_malloc(). Omit the internal ** %-conversion extensions. */ SQLITE_API char *sqlite3_vmprintf(const char *zFormat, va_list ap){ char *z; char zBase[SQLITE_PRINT_BUF_SIZE]; StrAccum acc; #ifdef SQLITE_ENABLE_API_ARMOR if( zFormat==0 ){ (void)SQLITE_MISUSE_BKPT; return 0; } #endif #ifndef SQLITE_OMIT_AUTOINIT if( sqlite3_initialize() ) return 0; #endif sqlite3StrAccumInit(&acc, 0, zBase, sizeof(zBase), SQLITE_MAX_LENGTH); sqlite3VXPrintf(&acc, zFormat, ap); z = sqlite3StrAccumFinish(&acc); return z; } /* ** Print into memory obtained from sqlite3_malloc()(). Omit the internal ** %-conversion extensions. */ SQLITE_API char *sqlite3_mprintf(const char *zFormat, ...){ va_list ap; char *z; #ifndef SQLITE_OMIT_AUTOINIT if( sqlite3_initialize() ) return 0; #endif va_start(ap, zFormat); z = sqlite3_vmprintf(zFormat, ap); va_end(ap); return z; } /* ** sqlite3_snprintf() works like snprintf() except that it ignores the ** current locale settings. This is important for SQLite because we ** are not able to use a "," as the decimal point in place of "." as ** specified by some locales. ** ** Oops: The first two arguments of sqlite3_snprintf() are backwards ** from the snprintf() standard. Unfortunately, it is too late to change ** this without breaking compatibility, so we just have to live with the ** mistake. ** ** sqlite3_vsnprintf() is the varargs version. */ SQLITE_API char *sqlite3_vsnprintf(int n, char *zBuf, const char *zFormat, va_list ap){ StrAccum acc; if( n<=0 ) return zBuf; #ifdef SQLITE_ENABLE_API_ARMOR if( zBuf==0 || zFormat==0 ) { (void)SQLITE_MISUSE_BKPT; if( zBuf ) zBuf[0] = 0; return zBuf; } #endif sqlite3StrAccumInit(&acc, 0, zBuf, n, 0); sqlite3VXPrintf(&acc, zFormat, ap); return sqlite3StrAccumFinish(&acc); } SQLITE_API char *sqlite3_snprintf(int n, char *zBuf, const char *zFormat, ...){ char *z; va_list ap; va_start(ap,zFormat); z = sqlite3_vsnprintf(n, zBuf, zFormat, ap); va_end(ap); return z; } /* ** This is the routine that actually formats the sqlite3_log() message. ** We house it in a separate routine from sqlite3_log() to avoid using ** stack space on small-stack systems when logging is disabled. ** ** sqlite3_log() must render into a static buffer. It cannot dynamically ** allocate memory because it might be called while the memory allocator ** mutex is held. ** ** sqlite3VXPrintf() might ask for *temporary* memory allocations for ** certain format characters (%q) or for very large precisions or widths. ** Care must be taken that any sqlite3_log() calls that occur while the ** memory mutex is held do not use these mechanisms. */ static void renderLogMsg(int iErrCode, const char *zFormat, va_list ap){ StrAccum acc; /* String accumulator */ char zMsg[SQLITE_PRINT_BUF_SIZE*3]; /* Complete log message */ sqlite3StrAccumInit(&acc, 0, zMsg, sizeof(zMsg), 0); sqlite3VXPrintf(&acc, zFormat, ap); sqlite3GlobalConfig.xLog(sqlite3GlobalConfig.pLogArg, iErrCode, sqlite3StrAccumFinish(&acc)); } /* ** Format and write a message to the log if logging is enabled. */ SQLITE_API void sqlite3_log(int iErrCode, const char *zFormat, ...){ va_list ap; /* Vararg list */ if( sqlite3GlobalConfig.xLog ){ va_start(ap, zFormat); renderLogMsg(iErrCode, zFormat, ap); va_end(ap); } } #if defined(SQLITE_DEBUG) || defined(SQLITE_HAVE_OS_TRACE) /* ** A version of printf() that understands %lld. Used for debugging. ** The printf() built into some versions of windows does not understand %lld ** and segfaults if you give it a long long int. */ SQLITE_PRIVATE void sqlite3DebugPrintf(const char *zFormat, ...){ va_list ap; StrAccum acc; char zBuf[500]; sqlite3StrAccumInit(&acc, 0, zBuf, sizeof(zBuf), 0); va_start(ap,zFormat); sqlite3VXPrintf(&acc, zFormat, ap); va_end(ap); sqlite3StrAccumFinish(&acc); fprintf(stdout,"%s", zBuf); fflush(stdout); } #endif /* ** variable-argument wrapper around sqlite3VXPrintf(). The bFlags argument ** can contain the bit SQLITE_PRINTF_INTERNAL enable internal formats. */ SQLITE_PRIVATE void sqlite3XPrintf(StrAccum *p, const char *zFormat, ...){ va_list ap; va_start(ap,zFormat); sqlite3VXPrintf(p, zFormat, ap); va_end(ap); } /************** End of printf.c **********************************************/ /************** Begin file treeview.c ****************************************/ /* ** 2015-06-08 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ************************************************************************* ** ** This file contains C code to implement the TreeView debugging routines. ** These routines print a parse tree to standard output for debugging and ** analysis. ** ** The interfaces in this file is only available when compiling ** with SQLITE_DEBUG. */ /* #include "sqliteInt.h" */ #ifdef SQLITE_DEBUG /* ** Add a new subitem to the tree. The moreToFollow flag indicates that this ** is not the last item in the tree. */ static TreeView *sqlite3TreeViewPush(TreeView *p, u8 moreToFollow){ if( p==0 ){ p = sqlite3_malloc64( sizeof(*p) ); if( p==0 ) return 0; memset(p, 0, sizeof(*p)); }else{ p->iLevel++; } assert( moreToFollow==0 || moreToFollow==1 ); if( p->iLevelbLine) ) p->bLine[p->iLevel] = moreToFollow; return p; } /* ** Finished with one layer of the tree */ static void sqlite3TreeViewPop(TreeView *p){ if( p==0 ) return; p->iLevel--; if( p->iLevel<0 ) sqlite3_free(p); } /* ** Generate a single line of output for the tree, with a prefix that contains ** all the appropriate tree lines */ static void sqlite3TreeViewLine(TreeView *p, const char *zFormat, ...){ va_list ap; int i; StrAccum acc; char zBuf[500]; sqlite3StrAccumInit(&acc, 0, zBuf, sizeof(zBuf), 0); if( p ){ for(i=0; iiLevel && ibLine)-1; i++){ sqlite3StrAccumAppend(&acc, p->bLine[i] ? "| " : " ", 4); } sqlite3StrAccumAppend(&acc, p->bLine[i] ? "|-- " : "'-- ", 4); } va_start(ap, zFormat); sqlite3VXPrintf(&acc, zFormat, ap); va_end(ap); if( zBuf[acc.nChar-1]!='\n' ) sqlite3StrAccumAppend(&acc, "\n", 1); sqlite3StrAccumFinish(&acc); fprintf(stdout,"%s", zBuf); fflush(stdout); } /* ** Shorthand for starting a new tree item that consists of a single label */ static void sqlite3TreeViewItem(TreeView *p, const char *zLabel,u8 moreFollows){ p = sqlite3TreeViewPush(p, moreFollows); sqlite3TreeViewLine(p, "%s", zLabel); } /* ** Generate a human-readable description of a WITH clause. */ SQLITE_PRIVATE void sqlite3TreeViewWith(TreeView *pView, const With *pWith, u8 moreToFollow){ int i; if( pWith==0 ) return; if( pWith->nCte==0 ) return; if( pWith->pOuter ){ sqlite3TreeViewLine(pView, "WITH (0x%p, pOuter=0x%p)",pWith,pWith->pOuter); }else{ sqlite3TreeViewLine(pView, "WITH (0x%p)", pWith); } if( pWith->nCte>0 ){ pView = sqlite3TreeViewPush(pView, 1); for(i=0; inCte; i++){ StrAccum x; char zLine[1000]; const struct Cte *pCte = &pWith->a[i]; sqlite3StrAccumInit(&x, 0, zLine, sizeof(zLine), 0); sqlite3XPrintf(&x, "%s", pCte->zName); if( pCte->pCols && pCte->pCols->nExpr>0 ){ char cSep = '('; int j; for(j=0; jpCols->nExpr; j++){ sqlite3XPrintf(&x, "%c%s", cSep, pCte->pCols->a[j].zName); cSep = ','; } sqlite3XPrintf(&x, ")"); } sqlite3XPrintf(&x, " AS"); sqlite3StrAccumFinish(&x); sqlite3TreeViewItem(pView, zLine, inCte-1); sqlite3TreeViewSelect(pView, pCte->pSelect, 0); sqlite3TreeViewPop(pView); } sqlite3TreeViewPop(pView); } } /* ** Generate a human-readable description of a Select object. */ SQLITE_PRIVATE void sqlite3TreeViewSelect(TreeView *pView, const Select *p, u8 moreToFollow){ int n = 0; int cnt = 0; pView = sqlite3TreeViewPush(pView, moreToFollow); if( p->pWith ){ sqlite3TreeViewWith(pView, p->pWith, 1); cnt = 1; sqlite3TreeViewPush(pView, 1); } do{ sqlite3TreeViewLine(pView, "SELECT%s%s (0x%p) selFlags=0x%x nSelectRow=%d", ((p->selFlags & SF_Distinct) ? " DISTINCT" : ""), ((p->selFlags & SF_Aggregate) ? " agg_flag" : ""), p, p->selFlags, (int)p->nSelectRow ); if( cnt++ ) sqlite3TreeViewPop(pView); if( p->pPrior ){ n = 1000; }else{ n = 0; if( p->pSrc && p->pSrc->nSrc ) n++; if( p->pWhere ) n++; if( p->pGroupBy ) n++; if( p->pHaving ) n++; if( p->pOrderBy ) n++; if( p->pLimit ) n++; if( p->pOffset ) n++; } sqlite3TreeViewExprList(pView, p->pEList, (n--)>0, "result-set"); if( p->pSrc && p->pSrc->nSrc ){ int i; pView = sqlite3TreeViewPush(pView, (n--)>0); sqlite3TreeViewLine(pView, "FROM"); for(i=0; ipSrc->nSrc; i++){ struct SrcList_item *pItem = &p->pSrc->a[i]; StrAccum x; char zLine[100]; sqlite3StrAccumInit(&x, 0, zLine, sizeof(zLine), 0); sqlite3XPrintf(&x, "{%d,*}", pItem->iCursor); if( pItem->zDatabase ){ sqlite3XPrintf(&x, " %s.%s", pItem->zDatabase, pItem->zName); }else if( pItem->zName ){ sqlite3XPrintf(&x, " %s", pItem->zName); } if( pItem->pTab ){ sqlite3XPrintf(&x, " tabname=%Q", pItem->pTab->zName); } if( pItem->zAlias ){ sqlite3XPrintf(&x, " (AS %s)", pItem->zAlias); } if( pItem->fg.jointype & JT_LEFT ){ sqlite3XPrintf(&x, " LEFT-JOIN"); } sqlite3StrAccumFinish(&x); sqlite3TreeViewItem(pView, zLine, ipSrc->nSrc-1); if( pItem->pSelect ){ sqlite3TreeViewSelect(pView, pItem->pSelect, 0); } if( pItem->fg.isTabFunc ){ sqlite3TreeViewExprList(pView, pItem->u1.pFuncArg, 0, "func-args:"); } sqlite3TreeViewPop(pView); } sqlite3TreeViewPop(pView); } if( p->pWhere ){ sqlite3TreeViewItem(pView, "WHERE", (n--)>0); sqlite3TreeViewExpr(pView, p->pWhere, 0); sqlite3TreeViewPop(pView); } if( p->pGroupBy ){ sqlite3TreeViewExprList(pView, p->pGroupBy, (n--)>0, "GROUPBY"); } if( p->pHaving ){ sqlite3TreeViewItem(pView, "HAVING", (n--)>0); sqlite3TreeViewExpr(pView, p->pHaving, 0); sqlite3TreeViewPop(pView); } if( p->pOrderBy ){ sqlite3TreeViewExprList(pView, p->pOrderBy, (n--)>0, "ORDERBY"); } if( p->pLimit ){ sqlite3TreeViewItem(pView, "LIMIT", (n--)>0); sqlite3TreeViewExpr(pView, p->pLimit, 0); sqlite3TreeViewPop(pView); } if( p->pOffset ){ sqlite3TreeViewItem(pView, "OFFSET", (n--)>0); sqlite3TreeViewExpr(pView, p->pOffset, 0); sqlite3TreeViewPop(pView); } if( p->pPrior ){ const char *zOp = "UNION"; switch( p->op ){ case TK_ALL: zOp = "UNION ALL"; break; case TK_INTERSECT: zOp = "INTERSECT"; break; case TK_EXCEPT: zOp = "EXCEPT"; break; } sqlite3TreeViewItem(pView, zOp, 1); } p = p->pPrior; }while( p!=0 ); sqlite3TreeViewPop(pView); } /* ** Generate a human-readable explanation of an expression tree. */ SQLITE_PRIVATE void sqlite3TreeViewExpr(TreeView *pView, const Expr *pExpr, u8 moreToFollow){ const char *zBinOp = 0; /* Binary operator */ const char *zUniOp = 0; /* Unary operator */ char zFlgs[30]; pView = sqlite3TreeViewPush(pView, moreToFollow); if( pExpr==0 ){ sqlite3TreeViewLine(pView, "nil"); sqlite3TreeViewPop(pView); return; } if( pExpr->flags ){ sqlite3_snprintf(sizeof(zFlgs),zFlgs," flags=0x%x",pExpr->flags); }else{ zFlgs[0] = 0; } switch( pExpr->op ){ case TK_AGG_COLUMN: { sqlite3TreeViewLine(pView, "AGG{%d:%d}%s", pExpr->iTable, pExpr->iColumn, zFlgs); break; } case TK_COLUMN: { if( pExpr->iTable<0 ){ /* This only happens when coding check constraints */ sqlite3TreeViewLine(pView, "COLUMN(%d)%s", pExpr->iColumn, zFlgs); }else{ sqlite3TreeViewLine(pView, "{%d:%d}%s", pExpr->iTable, pExpr->iColumn, zFlgs); } break; } case TK_INTEGER: { if( pExpr->flags & EP_IntValue ){ sqlite3TreeViewLine(pView, "%d", pExpr->u.iValue); }else{ sqlite3TreeViewLine(pView, "%s", pExpr->u.zToken); } break; } #ifndef SQLITE_OMIT_FLOATING_POINT case TK_FLOAT: { sqlite3TreeViewLine(pView,"%s", pExpr->u.zToken); break; } #endif case TK_STRING: { sqlite3TreeViewLine(pView,"%Q", pExpr->u.zToken); break; } case TK_NULL: { sqlite3TreeViewLine(pView,"NULL"); break; } #ifndef SQLITE_OMIT_BLOB_LITERAL case TK_BLOB: { sqlite3TreeViewLine(pView,"%s", pExpr->u.zToken); break; } #endif case TK_VARIABLE: { sqlite3TreeViewLine(pView,"VARIABLE(%s,%d)", pExpr->u.zToken, pExpr->iColumn); break; } case TK_REGISTER: { sqlite3TreeViewLine(pView,"REGISTER(%d)", pExpr->iTable); break; } case TK_ID: { sqlite3TreeViewLine(pView,"ID \"%w\"", pExpr->u.zToken); break; } #ifndef SQLITE_OMIT_CAST case TK_CAST: { /* Expressions of the form: CAST(pLeft AS token) */ sqlite3TreeViewLine(pView,"CAST %Q", pExpr->u.zToken); sqlite3TreeViewExpr(pView, pExpr->pLeft, 0); break; } #endif /* SQLITE_OMIT_CAST */ case TK_LT: zBinOp = "LT"; break; case TK_LE: zBinOp = "LE"; break; case TK_GT: zBinOp = "GT"; break; case TK_GE: zBinOp = "GE"; break; case TK_NE: zBinOp = "NE"; break; case TK_EQ: zBinOp = "EQ"; break; case TK_IS: zBinOp = "IS"; break; case TK_ISNOT: zBinOp = "ISNOT"; break; case TK_AND: zBinOp = "AND"; break; case TK_OR: zBinOp = "OR"; break; case TK_PLUS: zBinOp = "ADD"; break; case TK_STAR: zBinOp = "MUL"; break; case TK_MINUS: zBinOp = "SUB"; break; case TK_REM: zBinOp = "REM"; break; case TK_BITAND: zBinOp = "BITAND"; break; case TK_BITOR: zBinOp = "BITOR"; break; case TK_SLASH: zBinOp = "DIV"; break; case TK_LSHIFT: zBinOp = "LSHIFT"; break; case TK_RSHIFT: zBinOp = "RSHIFT"; break; case TK_CONCAT: zBinOp = "CONCAT"; break; case TK_DOT: zBinOp = "DOT"; break; case TK_UMINUS: zUniOp = "UMINUS"; break; case TK_UPLUS: zUniOp = "UPLUS"; break; case TK_BITNOT: zUniOp = "BITNOT"; break; case TK_NOT: zUniOp = "NOT"; break; case TK_ISNULL: zUniOp = "ISNULL"; break; case TK_NOTNULL: zUniOp = "NOTNULL"; break; case TK_SPAN: { sqlite3TreeViewLine(pView, "SPAN %Q", pExpr->u.zToken); sqlite3TreeViewExpr(pView, pExpr->pLeft, 0); break; } case TK_COLLATE: { sqlite3TreeViewLine(pView, "COLLATE %Q", pExpr->u.zToken); sqlite3TreeViewExpr(pView, pExpr->pLeft, 0); break; } case TK_AGG_FUNCTION: case TK_FUNCTION: { ExprList *pFarg; /* List of function arguments */ if( ExprHasProperty(pExpr, EP_TokenOnly) ){ pFarg = 0; }else{ pFarg = pExpr->x.pList; } if( pExpr->op==TK_AGG_FUNCTION ){ sqlite3TreeViewLine(pView, "AGG_FUNCTION%d %Q", pExpr->op2, pExpr->u.zToken); }else{ sqlite3TreeViewLine(pView, "FUNCTION %Q", pExpr->u.zToken); } if( pFarg ){ sqlite3TreeViewExprList(pView, pFarg, 0, 0); } break; } #ifndef SQLITE_OMIT_SUBQUERY case TK_EXISTS: { sqlite3TreeViewLine(pView, "EXISTS-expr"); sqlite3TreeViewSelect(pView, pExpr->x.pSelect, 0); break; } case TK_SELECT: { sqlite3TreeViewLine(pView, "SELECT-expr"); sqlite3TreeViewSelect(pView, pExpr->x.pSelect, 0); break; } case TK_IN: { sqlite3TreeViewLine(pView, "IN"); sqlite3TreeViewExpr(pView, pExpr->pLeft, 1); if( ExprHasProperty(pExpr, EP_xIsSelect) ){ sqlite3TreeViewSelect(pView, pExpr->x.pSelect, 0); }else{ sqlite3TreeViewExprList(pView, pExpr->x.pList, 0, 0); } break; } #endif /* SQLITE_OMIT_SUBQUERY */ /* ** x BETWEEN y AND z ** ** This is equivalent to ** ** x>=y AND x<=z ** ** X is stored in pExpr->pLeft. ** Y is stored in pExpr->pList->a[0].pExpr. ** Z is stored in pExpr->pList->a[1].pExpr. */ case TK_BETWEEN: { Expr *pX = pExpr->pLeft; Expr *pY = pExpr->x.pList->a[0].pExpr; Expr *pZ = pExpr->x.pList->a[1].pExpr; sqlite3TreeViewLine(pView, "BETWEEN"); sqlite3TreeViewExpr(pView, pX, 1); sqlite3TreeViewExpr(pView, pY, 1); sqlite3TreeViewExpr(pView, pZ, 0); break; } case TK_TRIGGER: { /* If the opcode is TK_TRIGGER, then the expression is a reference ** to a column in the new.* or old.* pseudo-tables available to ** trigger programs. In this case Expr.iTable is set to 1 for the ** new.* pseudo-table, or 0 for the old.* pseudo-table. Expr.iColumn ** is set to the column of the pseudo-table to read, or to -1 to ** read the rowid field. */ sqlite3TreeViewLine(pView, "%s(%d)", pExpr->iTable ? "NEW" : "OLD", pExpr->iColumn); break; } case TK_CASE: { sqlite3TreeViewLine(pView, "CASE"); sqlite3TreeViewExpr(pView, pExpr->pLeft, 1); sqlite3TreeViewExprList(pView, pExpr->x.pList, 0, 0); break; } #ifndef SQLITE_OMIT_TRIGGER case TK_RAISE: { const char *zType = "unk"; switch( pExpr->affinity ){ case OE_Rollback: zType = "rollback"; break; case OE_Abort: zType = "abort"; break; case OE_Fail: zType = "fail"; break; case OE_Ignore: zType = "ignore"; break; } sqlite3TreeViewLine(pView, "RAISE %s(%Q)", zType, pExpr->u.zToken); break; } #endif case TK_MATCH: { sqlite3TreeViewLine(pView, "MATCH {%d:%d}%s", pExpr->iTable, pExpr->iColumn, zFlgs); sqlite3TreeViewExpr(pView, pExpr->pRight, 0); break; } case TK_VECTOR: { sqlite3TreeViewBareExprList(pView, pExpr->x.pList, "VECTOR"); break; } case TK_SELECT_COLUMN: { sqlite3TreeViewLine(pView, "SELECT-COLUMN %d", pExpr->iColumn); sqlite3TreeViewSelect(pView, pExpr->pLeft->x.pSelect, 0); break; } default: { sqlite3TreeViewLine(pView, "op=%d", pExpr->op); break; } } if( zBinOp ){ sqlite3TreeViewLine(pView, "%s%s", zBinOp, zFlgs); sqlite3TreeViewExpr(pView, pExpr->pLeft, 1); sqlite3TreeViewExpr(pView, pExpr->pRight, 0); }else if( zUniOp ){ sqlite3TreeViewLine(pView, "%s%s", zUniOp, zFlgs); sqlite3TreeViewExpr(pView, pExpr->pLeft, 0); } sqlite3TreeViewPop(pView); } /* ** Generate a human-readable explanation of an expression list. */ SQLITE_PRIVATE void sqlite3TreeViewBareExprList( TreeView *pView, const ExprList *pList, const char *zLabel ){ if( zLabel==0 || zLabel[0]==0 ) zLabel = "LIST"; if( pList==0 ){ sqlite3TreeViewLine(pView, "%s (empty)", zLabel); }else{ int i; sqlite3TreeViewLine(pView, "%s", zLabel); for(i=0; inExpr; i++){ int j = pList->a[i].u.x.iOrderByCol; if( j ){ sqlite3TreeViewPush(pView, 0); sqlite3TreeViewLine(pView, "iOrderByCol=%d", j); } sqlite3TreeViewExpr(pView, pList->a[i].pExpr, inExpr-1); if( j ) sqlite3TreeViewPop(pView); } } } SQLITE_PRIVATE void sqlite3TreeViewExprList( TreeView *pView, const ExprList *pList, u8 moreToFollow, const char *zLabel ){ pView = sqlite3TreeViewPush(pView, moreToFollow); sqlite3TreeViewBareExprList(pView, pList, zLabel); sqlite3TreeViewPop(pView); } #endif /* SQLITE_DEBUG */ /************** End of treeview.c ********************************************/ /************** Begin file random.c ******************************************/ /* ** 2001 September 15 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ************************************************************************* ** This file contains code to implement a pseudo-random number ** generator (PRNG) for SQLite. ** ** Random numbers are used by some of the database backends in order ** to generate random integer keys for tables or random filenames. */ /* #include "sqliteInt.h" */ /* All threads share a single random number generator. ** This structure is the current state of the generator. */ static SQLITE_WSD struct sqlite3PrngType { unsigned char isInit; /* True if initialized */ unsigned char i, j; /* State variables */ unsigned char s[256]; /* State variables */ } sqlite3Prng; /* ** Return N random bytes. */ SQLITE_API void sqlite3_randomness(int N, void *pBuf){ unsigned char t; unsigned char *zBuf = pBuf; /* The "wsdPrng" macro will resolve to the pseudo-random number generator ** state vector. If writable static data is unsupported on the target, ** we have to locate the state vector at run-time. In the more common ** case where writable static data is supported, wsdPrng can refer directly ** to the "sqlite3Prng" state vector declared above. */ #ifdef SQLITE_OMIT_WSD struct sqlite3PrngType *p = &GLOBAL(struct sqlite3PrngType, sqlite3Prng); # define wsdPrng p[0] #else # define wsdPrng sqlite3Prng #endif #if SQLITE_THREADSAFE sqlite3_mutex *mutex; #endif #ifndef SQLITE_OMIT_AUTOINIT if( sqlite3_initialize() ) return; #endif #if SQLITE_THREADSAFE mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_PRNG); #endif sqlite3_mutex_enter(mutex); if( N<=0 || pBuf==0 ){ wsdPrng.isInit = 0; sqlite3_mutex_leave(mutex); return; } /* Initialize the state of the random number generator once, ** the first time this routine is called. The seed value does ** not need to contain a lot of randomness since we are not ** trying to do secure encryption or anything like that... ** ** Nothing in this file or anywhere else in SQLite does any kind of ** encryption. The RC4 algorithm is being used as a PRNG (pseudo-random ** number generator) not as an encryption device. */ if( !wsdPrng.isInit ){ int i; char k[256]; wsdPrng.j = 0; wsdPrng.i = 0; sqlite3OsRandomness(sqlite3_vfs_find(0), 256, k); for(i=0; i<256; i++){ wsdPrng.s[i] = (u8)i; } for(i=0; i<256; i++){ wsdPrng.j += wsdPrng.s[i] + k[i]; t = wsdPrng.s[wsdPrng.j]; wsdPrng.s[wsdPrng.j] = wsdPrng.s[i]; wsdPrng.s[i] = t; } wsdPrng.isInit = 1; } assert( N>0 ); do{ wsdPrng.i++; t = wsdPrng.s[wsdPrng.i]; wsdPrng.j += t; wsdPrng.s[wsdPrng.i] = wsdPrng.s[wsdPrng.j]; wsdPrng.s[wsdPrng.j] = t; t += wsdPrng.s[wsdPrng.i]; *(zBuf++) = wsdPrng.s[t]; }while( --N ); sqlite3_mutex_leave(mutex); } #ifndef SQLITE_OMIT_BUILTIN_TEST /* ** For testing purposes, we sometimes want to preserve the state of ** PRNG and restore the PRNG to its saved state at a later time, or ** to reset the PRNG to its initial state. These routines accomplish ** those tasks. ** ** The sqlite3_test_control() interface calls these routines to ** control the PRNG. */ static SQLITE_WSD struct sqlite3PrngType sqlite3SavedPrng; SQLITE_PRIVATE void sqlite3PrngSaveState(void){ memcpy( &GLOBAL(struct sqlite3PrngType, sqlite3SavedPrng), &GLOBAL(struct sqlite3PrngType, sqlite3Prng), sizeof(sqlite3Prng) ); } SQLITE_PRIVATE void sqlite3PrngRestoreState(void){ memcpy( &GLOBAL(struct sqlite3PrngType, sqlite3Prng), &GLOBAL(struct sqlite3PrngType, sqlite3SavedPrng), sizeof(sqlite3Prng) ); } #endif /* SQLITE_OMIT_BUILTIN_TEST */ /************** End of random.c **********************************************/ /************** Begin file threads.c *****************************************/ /* ** 2012 July 21 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ****************************************************************************** ** ** This file presents a simple cross-platform threading interface for ** use internally by SQLite. ** ** A "thread" can be created using sqlite3ThreadCreate(). This thread ** runs independently of its creator until it is joined using ** sqlite3ThreadJoin(), at which point it terminates. ** ** Threads do not have to be real. It could be that the work of the ** "thread" is done by the main thread at either the sqlite3ThreadCreate() ** or sqlite3ThreadJoin() call. This is, in fact, what happens in ** single threaded systems. Nothing in SQLite requires multiple threads. ** This interface exists so that applications that want to take advantage ** of multiple cores can do so, while also allowing applications to stay ** single-threaded if desired. */ /* #include "sqliteInt.h" */ #if SQLITE_OS_WIN /* # include "os_win.h" */ #endif #if SQLITE_MAX_WORKER_THREADS>0 /********************************* Unix Pthreads ****************************/ #if SQLITE_OS_UNIX && defined(SQLITE_MUTEX_PTHREADS) && SQLITE_THREADSAFE>0 #define SQLITE_THREADS_IMPLEMENTED 1 /* Prevent the single-thread code below */ /* #include */ /* A running thread */ struct SQLiteThread { pthread_t tid; /* Thread ID */ int done; /* Set to true when thread finishes */ void *pOut; /* Result returned by the thread */ void *(*xTask)(void*); /* The thread routine */ void *pIn; /* Argument to the thread */ }; /* Create a new thread */ SQLITE_PRIVATE int sqlite3ThreadCreate( SQLiteThread **ppThread, /* OUT: Write the thread object here */ void *(*xTask)(void*), /* Routine to run in a separate thread */ void *pIn /* Argument passed into xTask() */ ){ SQLiteThread *p; int rc; assert( ppThread!=0 ); assert( xTask!=0 ); /* This routine is never used in single-threaded mode */ assert( sqlite3GlobalConfig.bCoreMutex!=0 ); *ppThread = 0; p = sqlite3Malloc(sizeof(*p)); if( p==0 ) return SQLITE_NOMEM_BKPT; memset(p, 0, sizeof(*p)); p->xTask = xTask; p->pIn = pIn; /* If the SQLITE_TESTCTRL_FAULT_INSTALL callback is registered to a ** function that returns SQLITE_ERROR when passed the argument 200, that ** forces worker threads to run sequentially and deterministically ** for testing purposes. */ if( sqlite3FaultSim(200) ){ rc = 1; }else{ rc = pthread_create(&p->tid, 0, xTask, pIn); } if( rc ){ p->done = 1; p->pOut = xTask(pIn); } *ppThread = p; return SQLITE_OK; } /* Get the results of the thread */ SQLITE_PRIVATE int sqlite3ThreadJoin(SQLiteThread *p, void **ppOut){ int rc; assert( ppOut!=0 ); if( NEVER(p==0) ) return SQLITE_NOMEM_BKPT; if( p->done ){ *ppOut = p->pOut; rc = SQLITE_OK; }else{ rc = pthread_join(p->tid, ppOut) ? SQLITE_ERROR : SQLITE_OK; } sqlite3_free(p); return rc; } #endif /* SQLITE_OS_UNIX && defined(SQLITE_MUTEX_PTHREADS) */ /******************************** End Unix Pthreads *************************/ /********************************* Win32 Threads ****************************/ #if SQLITE_OS_WIN_THREADS #define SQLITE_THREADS_IMPLEMENTED 1 /* Prevent the single-thread code below */ #include /* A running thread */ struct SQLiteThread { void *tid; /* The thread handle */ unsigned id; /* The thread identifier */ void *(*xTask)(void*); /* The routine to run as a thread */ void *pIn; /* Argument to xTask */ void *pResult; /* Result of xTask */ }; /* Thread procedure Win32 compatibility shim */ static unsigned __stdcall sqlite3ThreadProc( void *pArg /* IN: Pointer to the SQLiteThread structure */ ){ SQLiteThread *p = (SQLiteThread *)pArg; assert( p!=0 ); #if 0 /* ** This assert appears to trigger spuriously on certain ** versions of Windows, possibly due to _beginthreadex() ** and/or CreateThread() not fully setting their thread ** ID parameter before starting the thread. */ assert( p->id==GetCurrentThreadId() ); #endif assert( p->xTask!=0 ); p->pResult = p->xTask(p->pIn); _endthreadex(0); return 0; /* NOT REACHED */ } /* Create a new thread */ SQLITE_PRIVATE int sqlite3ThreadCreate( SQLiteThread **ppThread, /* OUT: Write the thread object here */ void *(*xTask)(void*), /* Routine to run in a separate thread */ void *pIn /* Argument passed into xTask() */ ){ SQLiteThread *p; assert( ppThread!=0 ); assert( xTask!=0 ); *ppThread = 0; p = sqlite3Malloc(sizeof(*p)); if( p==0 ) return SQLITE_NOMEM_BKPT; /* If the SQLITE_TESTCTRL_FAULT_INSTALL callback is registered to a ** function that returns SQLITE_ERROR when passed the argument 200, that ** forces worker threads to run sequentially and deterministically ** (via the sqlite3FaultSim() term of the conditional) for testing ** purposes. */ if( sqlite3GlobalConfig.bCoreMutex==0 || sqlite3FaultSim(200) ){ memset(p, 0, sizeof(*p)); }else{ p->xTask = xTask; p->pIn = pIn; p->tid = (void*)_beginthreadex(0, 0, sqlite3ThreadProc, p, 0, &p->id); if( p->tid==0 ){ memset(p, 0, sizeof(*p)); } } if( p->xTask==0 ){ p->id = GetCurrentThreadId(); p->pResult = xTask(pIn); } *ppThread = p; return SQLITE_OK; } SQLITE_PRIVATE DWORD sqlite3Win32Wait(HANDLE hObject); /* os_win.c */ /* Get the results of the thread */ SQLITE_PRIVATE int sqlite3ThreadJoin(SQLiteThread *p, void **ppOut){ DWORD rc; BOOL bRc; assert( ppOut!=0 ); if( NEVER(p==0) ) return SQLITE_NOMEM_BKPT; if( p->xTask==0 ){ /* assert( p->id==GetCurrentThreadId() ); */ rc = WAIT_OBJECT_0; assert( p->tid==0 ); }else{ assert( p->id!=0 && p->id!=GetCurrentThreadId() ); rc = sqlite3Win32Wait((HANDLE)p->tid); assert( rc!=WAIT_IO_COMPLETION ); bRc = CloseHandle((HANDLE)p->tid); assert( bRc ); } if( rc==WAIT_OBJECT_0 ) *ppOut = p->pResult; sqlite3_free(p); return (rc==WAIT_OBJECT_0) ? SQLITE_OK : SQLITE_ERROR; } #endif /* SQLITE_OS_WIN_THREADS */ /******************************** End Win32 Threads *************************/ /********************************* Single-Threaded **************************/ #ifndef SQLITE_THREADS_IMPLEMENTED /* ** This implementation does not actually create a new thread. It does the ** work of the thread in the main thread, when either the thread is created ** or when it is joined */ /* A running thread */ struct SQLiteThread { void *(*xTask)(void*); /* The routine to run as a thread */ void *pIn; /* Argument to xTask */ void *pResult; /* Result of xTask */ }; /* Create a new thread */ SQLITE_PRIVATE int sqlite3ThreadCreate( SQLiteThread **ppThread, /* OUT: Write the thread object here */ void *(*xTask)(void*), /* Routine to run in a separate thread */ void *pIn /* Argument passed into xTask() */ ){ SQLiteThread *p; assert( ppThread!=0 ); assert( xTask!=0 ); *ppThread = 0; p = sqlite3Malloc(sizeof(*p)); if( p==0 ) return SQLITE_NOMEM_BKPT; if( (SQLITE_PTR_TO_INT(p)/17)&1 ){ p->xTask = xTask; p->pIn = pIn; }else{ p->xTask = 0; p->pResult = xTask(pIn); } *ppThread = p; return SQLITE_OK; } /* Get the results of the thread */ SQLITE_PRIVATE int sqlite3ThreadJoin(SQLiteThread *p, void **ppOut){ assert( ppOut!=0 ); if( NEVER(p==0) ) return SQLITE_NOMEM_BKPT; if( p->xTask ){ *ppOut = p->xTask(p->pIn); }else{ *ppOut = p->pResult; } sqlite3_free(p); #if defined(SQLITE_TEST) { void *pTstAlloc = sqlite3Malloc(10); if (!pTstAlloc) return SQLITE_NOMEM_BKPT; sqlite3_free(pTstAlloc); } #endif return SQLITE_OK; } #endif /* !defined(SQLITE_THREADS_IMPLEMENTED) */ /****************************** End Single-Threaded *************************/ #endif /* SQLITE_MAX_WORKER_THREADS>0 */ /************** End of threads.c *********************************************/ /************** Begin file utf.c *********************************************/ /* ** 2004 April 13 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ************************************************************************* ** This file contains routines used to translate between UTF-8, ** UTF-16, UTF-16BE, and UTF-16LE. ** ** Notes on UTF-8: ** ** Byte-0 Byte-1 Byte-2 Byte-3 Value ** 0xxxxxxx 00000000 00000000 0xxxxxxx ** 110yyyyy 10xxxxxx 00000000 00000yyy yyxxxxxx ** 1110zzzz 10yyyyyy 10xxxxxx 00000000 zzzzyyyy yyxxxxxx ** 11110uuu 10uuzzzz 10yyyyyy 10xxxxxx 000uuuuu zzzzyyyy yyxxxxxx ** ** ** Notes on UTF-16: (with wwww+1==uuuuu) ** ** Word-0 Word-1 Value ** 110110ww wwzzzzyy 110111yy yyxxxxxx 000uuuuu zzzzyyyy yyxxxxxx ** zzzzyyyy yyxxxxxx 00000000 zzzzyyyy yyxxxxxx ** ** ** BOM or Byte Order Mark: ** 0xff 0xfe little-endian utf-16 follows ** 0xfe 0xff big-endian utf-16 follows ** */ /* #include "sqliteInt.h" */ /* #include */ /* #include "vdbeInt.h" */ #if !defined(SQLITE_AMALGAMATION) && SQLITE_BYTEORDER==0 /* ** The following constant value is used by the SQLITE_BIGENDIAN and ** SQLITE_LITTLEENDIAN macros. */ SQLITE_PRIVATE const int sqlite3one = 1; #endif /* SQLITE_AMALGAMATION && SQLITE_BYTEORDER==0 */ /* ** This lookup table is used to help decode the first byte of ** a multi-byte UTF8 character. */ static const unsigned char sqlite3Utf8Trans1[] = { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x00, 0x01, 0x02, 0x03, 0x00, 0x01, 0x00, 0x00, }; #define WRITE_UTF8(zOut, c) { \ if( c<0x00080 ){ \ *zOut++ = (u8)(c&0xFF); \ } \ else if( c<0x00800 ){ \ *zOut++ = 0xC0 + (u8)((c>>6)&0x1F); \ *zOut++ = 0x80 + (u8)(c & 0x3F); \ } \ else if( c<0x10000 ){ \ *zOut++ = 0xE0 + (u8)((c>>12)&0x0F); \ *zOut++ = 0x80 + (u8)((c>>6) & 0x3F); \ *zOut++ = 0x80 + (u8)(c & 0x3F); \ }else{ \ *zOut++ = 0xF0 + (u8)((c>>18) & 0x07); \ *zOut++ = 0x80 + (u8)((c>>12) & 0x3F); \ *zOut++ = 0x80 + (u8)((c>>6) & 0x3F); \ *zOut++ = 0x80 + (u8)(c & 0x3F); \ } \ } #define WRITE_UTF16LE(zOut, c) { \ if( c<=0xFFFF ){ \ *zOut++ = (u8)(c&0x00FF); \ *zOut++ = (u8)((c>>8)&0x00FF); \ }else{ \ *zOut++ = (u8)(((c>>10)&0x003F) + (((c-0x10000)>>10)&0x00C0)); \ *zOut++ = (u8)(0x00D8 + (((c-0x10000)>>18)&0x03)); \ *zOut++ = (u8)(c&0x00FF); \ *zOut++ = (u8)(0x00DC + ((c>>8)&0x03)); \ } \ } #define WRITE_UTF16BE(zOut, c) { \ if( c<=0xFFFF ){ \ *zOut++ = (u8)((c>>8)&0x00FF); \ *zOut++ = (u8)(c&0x00FF); \ }else{ \ *zOut++ = (u8)(0x00D8 + (((c-0x10000)>>18)&0x03)); \ *zOut++ = (u8)(((c>>10)&0x003F) + (((c-0x10000)>>10)&0x00C0)); \ *zOut++ = (u8)(0x00DC + ((c>>8)&0x03)); \ *zOut++ = (u8)(c&0x00FF); \ } \ } #define READ_UTF16LE(zIn, TERM, c){ \ c = (*zIn++); \ c += ((*zIn++)<<8); \ if( c>=0xD800 && c<0xE000 && TERM ){ \ int c2 = (*zIn++); \ c2 += ((*zIn++)<<8); \ c = (c2&0x03FF) + ((c&0x003F)<<10) + (((c&0x03C0)+0x0040)<<10); \ } \ } #define READ_UTF16BE(zIn, TERM, c){ \ c = ((*zIn++)<<8); \ c += (*zIn++); \ if( c>=0xD800 && c<0xE000 && TERM ){ \ int c2 = ((*zIn++)<<8); \ c2 += (*zIn++); \ c = (c2&0x03FF) + ((c&0x003F)<<10) + (((c&0x03C0)+0x0040)<<10); \ } \ } /* ** Translate a single UTF-8 character. Return the unicode value. ** ** During translation, assume that the byte that zTerm points ** is a 0x00. ** ** Write a pointer to the next unread byte back into *pzNext. ** ** Notes On Invalid UTF-8: ** ** * This routine never allows a 7-bit character (0x00 through 0x7f) to ** be encoded as a multi-byte character. Any multi-byte character that ** attempts to encode a value between 0x00 and 0x7f is rendered as 0xfffd. ** ** * This routine never allows a UTF16 surrogate value to be encoded. ** If a multi-byte character attempts to encode a value between ** 0xd800 and 0xe000 then it is rendered as 0xfffd. ** ** * Bytes in the range of 0x80 through 0xbf which occur as the first ** byte of a character are interpreted as single-byte characters ** and rendered as themselves even though they are technically ** invalid characters. ** ** * This routine accepts over-length UTF8 encodings ** for unicode values 0x80 and greater. It does not change over-length ** encodings to 0xfffd as some systems recommend. */ #define READ_UTF8(zIn, zTerm, c) \ c = *(zIn++); \ if( c>=0xc0 ){ \ c = sqlite3Utf8Trans1[c-0xc0]; \ while( zIn!=zTerm && (*zIn & 0xc0)==0x80 ){ \ c = (c<<6) + (0x3f & *(zIn++)); \ } \ if( c<0x80 \ || (c&0xFFFFF800)==0xD800 \ || (c&0xFFFFFFFE)==0xFFFE ){ c = 0xFFFD; } \ } SQLITE_PRIVATE u32 sqlite3Utf8Read( const unsigned char **pz /* Pointer to string from which to read char */ ){ unsigned int c; /* Same as READ_UTF8() above but without the zTerm parameter. ** For this routine, we assume the UTF8 string is always zero-terminated. */ c = *((*pz)++); if( c>=0xc0 ){ c = sqlite3Utf8Trans1[c-0xc0]; while( (*(*pz) & 0xc0)==0x80 ){ c = (c<<6) + (0x3f & *((*pz)++)); } if( c<0x80 || (c&0xFFFFF800)==0xD800 || (c&0xFFFFFFFE)==0xFFFE ){ c = 0xFFFD; } } return c; } /* ** If the TRANSLATE_TRACE macro is defined, the value of each Mem is ** printed on stderr on the way into and out of sqlite3VdbeMemTranslate(). */ /* #define TRANSLATE_TRACE 1 */ #ifndef SQLITE_OMIT_UTF16 /* ** This routine transforms the internal text encoding used by pMem to ** desiredEnc. It is an error if the string is already of the desired ** encoding, or if *pMem does not contain a string value. */ SQLITE_PRIVATE SQLITE_NOINLINE int sqlite3VdbeMemTranslate(Mem *pMem, u8 desiredEnc){ int len; /* Maximum length of output string in bytes */ unsigned char *zOut; /* Output buffer */ unsigned char *zIn; /* Input iterator */ unsigned char *zTerm; /* End of input */ unsigned char *z; /* Output iterator */ unsigned int c; assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) ); assert( pMem->flags&MEM_Str ); assert( pMem->enc!=desiredEnc ); assert( pMem->enc!=0 ); assert( pMem->n>=0 ); #if defined(TRANSLATE_TRACE) && defined(SQLITE_DEBUG) { char zBuf[100]; sqlite3VdbeMemPrettyPrint(pMem, zBuf); fprintf(stderr, "INPUT: %s\n", zBuf); } #endif /* If the translation is between UTF-16 little and big endian, then ** all that is required is to swap the byte order. This case is handled ** differently from the others. */ if( pMem->enc!=SQLITE_UTF8 && desiredEnc!=SQLITE_UTF8 ){ u8 temp; int rc; rc = sqlite3VdbeMemMakeWriteable(pMem); if( rc!=SQLITE_OK ){ assert( rc==SQLITE_NOMEM ); return SQLITE_NOMEM_BKPT; } zIn = (u8*)pMem->z; zTerm = &zIn[pMem->n&~1]; while( zInenc = desiredEnc; goto translate_out; } /* Set len to the maximum number of bytes required in the output buffer. */ if( desiredEnc==SQLITE_UTF8 ){ /* When converting from UTF-16, the maximum growth results from ** translating a 2-byte character to a 4-byte UTF-8 character. ** A single byte is required for the output string ** nul-terminator. */ pMem->n &= ~1; len = pMem->n * 2 + 1; }else{ /* When converting from UTF-8 to UTF-16 the maximum growth is caused ** when a 1-byte UTF-8 character is translated into a 2-byte UTF-16 ** character. Two bytes are required in the output buffer for the ** nul-terminator. */ len = pMem->n * 2 + 2; } /* Set zIn to point at the start of the input buffer and zTerm to point 1 ** byte past the end. ** ** Variable zOut is set to point at the output buffer, space obtained ** from sqlite3_malloc(). */ zIn = (u8*)pMem->z; zTerm = &zIn[pMem->n]; zOut = sqlite3DbMallocRaw(pMem->db, len); if( !zOut ){ return SQLITE_NOMEM_BKPT; } z = zOut; if( pMem->enc==SQLITE_UTF8 ){ if( desiredEnc==SQLITE_UTF16LE ){ /* UTF-8 -> UTF-16 Little-endian */ while( zIn UTF-16 Big-endian */ while( zInn = (int)(z - zOut); *z++ = 0; }else{ assert( desiredEnc==SQLITE_UTF8 ); if( pMem->enc==SQLITE_UTF16LE ){ /* UTF-16 Little-endian -> UTF-8 */ while( zIn UTF-8 */ while( zInn = (int)(z - zOut); } *z = 0; assert( (pMem->n+(desiredEnc==SQLITE_UTF8?1:2))<=len ); c = pMem->flags; sqlite3VdbeMemRelease(pMem); pMem->flags = MEM_Str|MEM_Term|(c&(MEM_AffMask|MEM_Subtype)); pMem->enc = desiredEnc; pMem->z = (char*)zOut; pMem->zMalloc = pMem->z; pMem->szMalloc = sqlite3DbMallocSize(pMem->db, pMem->z); translate_out: #if defined(TRANSLATE_TRACE) && defined(SQLITE_DEBUG) { char zBuf[100]; sqlite3VdbeMemPrettyPrint(pMem, zBuf); fprintf(stderr, "OUTPUT: %s\n", zBuf); } #endif return SQLITE_OK; } /* ** This routine checks for a byte-order mark at the beginning of the ** UTF-16 string stored in *pMem. If one is present, it is removed and ** the encoding of the Mem adjusted. This routine does not do any ** byte-swapping, it just sets Mem.enc appropriately. ** ** The allocation (static, dynamic etc.) and encoding of the Mem may be ** changed by this function. */ SQLITE_PRIVATE int sqlite3VdbeMemHandleBom(Mem *pMem){ int rc = SQLITE_OK; u8 bom = 0; assert( pMem->n>=0 ); if( pMem->n>1 ){ u8 b1 = *(u8 *)pMem->z; u8 b2 = *(((u8 *)pMem->z) + 1); if( b1==0xFE && b2==0xFF ){ bom = SQLITE_UTF16BE; } if( b1==0xFF && b2==0xFE ){ bom = SQLITE_UTF16LE; } } if( bom ){ rc = sqlite3VdbeMemMakeWriteable(pMem); if( rc==SQLITE_OK ){ pMem->n -= 2; memmove(pMem->z, &pMem->z[2], pMem->n); pMem->z[pMem->n] = '\0'; pMem->z[pMem->n+1] = '\0'; pMem->flags |= MEM_Term; pMem->enc = bom; } } return rc; } #endif /* SQLITE_OMIT_UTF16 */ /* ** pZ is a UTF-8 encoded unicode string. If nByte is less than zero, ** return the number of unicode characters in pZ up to (but not including) ** the first 0x00 byte. If nByte is not less than zero, return the ** number of unicode characters in the first nByte of pZ (or up to ** the first 0x00, whichever comes first). */ SQLITE_PRIVATE int sqlite3Utf8CharLen(const char *zIn, int nByte){ int r = 0; const u8 *z = (const u8*)zIn; const u8 *zTerm; if( nByte>=0 ){ zTerm = &z[nByte]; }else{ zTerm = (const u8*)(-1); } assert( z<=zTerm ); while( *z!=0 && zmallocFailed ){ sqlite3VdbeMemRelease(&m); m.z = 0; } assert( (m.flags & MEM_Term)!=0 || db->mallocFailed ); assert( (m.flags & MEM_Str)!=0 || db->mallocFailed ); assert( m.z || db->mallocFailed ); return m.z; } /* ** zIn is a UTF-16 encoded unicode string at least nChar characters long. ** Return the number of bytes in the first nChar unicode characters ** in pZ. nChar must be non-negative. */ SQLITE_PRIVATE int sqlite3Utf16ByteLen(const void *zIn, int nChar){ int c; unsigned char const *z = zIn; int n = 0; if( SQLITE_UTF16NATIVE==SQLITE_UTF16BE ){ while( n0 && n<=4 ); z[0] = 0; z = zBuf; c = sqlite3Utf8Read((const u8**)&z); t = i; if( i>=0xD800 && i<=0xDFFF ) t = 0xFFFD; if( (i&0xFFFFFFFE)==0xFFFE ) t = 0xFFFD; assert( c==t ); assert( (z-zBuf)==n ); } for(i=0; i<0x00110000; i++){ if( i>=0xD800 && i<0xE000 ) continue; z = zBuf; WRITE_UTF16LE(z, i); n = (int)(z-zBuf); assert( n>0 && n<=4 ); z[0] = 0; z = zBuf; READ_UTF16LE(z, 1, c); assert( c==i ); assert( (z-zBuf)==n ); } for(i=0; i<0x00110000; i++){ if( i>=0xD800 && i<0xE000 ) continue; z = zBuf; WRITE_UTF16BE(z, i); n = (int)(z-zBuf); assert( n>0 && n<=4 ); z[0] = 0; z = zBuf; READ_UTF16BE(z, 1, c); assert( c==i ); assert( (z-zBuf)==n ); } } #endif /* SQLITE_TEST */ #endif /* SQLITE_OMIT_UTF16 */ /************** End of utf.c *************************************************/ /************** Begin file util.c ********************************************/ /* ** 2001 September 15 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ************************************************************************* ** Utility functions used throughout sqlite. ** ** This file contains functions for allocating memory, comparing ** strings, and stuff like that. ** */ /* #include "sqliteInt.h" */ /* #include */ #if HAVE_ISNAN || SQLITE_HAVE_ISNAN # include #endif /* ** Routine needed to support the testcase() macro. */ #ifdef SQLITE_COVERAGE_TEST SQLITE_PRIVATE void sqlite3Coverage(int x){ static unsigned dummy = 0; dummy += (unsigned)x; } #endif /* ** Give a callback to the test harness that can be used to simulate faults ** in places where it is difficult or expensive to do so purely by means ** of inputs. ** ** The intent of the integer argument is to let the fault simulator know ** which of multiple sqlite3FaultSim() calls has been hit. ** ** Return whatever integer value the test callback returns, or return ** SQLITE_OK if no test callback is installed. */ #ifndef SQLITE_OMIT_BUILTIN_TEST SQLITE_PRIVATE int sqlite3FaultSim(int iTest){ int (*xCallback)(int) = sqlite3GlobalConfig.xTestCallback; return xCallback ? xCallback(iTest) : SQLITE_OK; } #endif #ifndef SQLITE_OMIT_FLOATING_POINT /* ** Return true if the floating point value is Not a Number (NaN). ** ** Use the math library isnan() function if compiled with SQLITE_HAVE_ISNAN. ** Otherwise, we have our own implementation that works on most systems. */ SQLITE_PRIVATE int sqlite3IsNaN(double x){ int rc; /* The value return */ #if !SQLITE_HAVE_ISNAN && !HAVE_ISNAN /* ** Systems that support the isnan() library function should probably ** make use of it by compiling with -DSQLITE_HAVE_ISNAN. But we have ** found that many systems do not have a working isnan() function so ** this implementation is provided as an alternative. ** ** This NaN test sometimes fails if compiled on GCC with -ffast-math. ** On the other hand, the use of -ffast-math comes with the following ** warning: ** ** This option [-ffast-math] should never be turned on by any ** -O option since it can result in incorrect output for programs ** which depend on an exact implementation of IEEE or ISO ** rules/specifications for math functions. ** ** Under MSVC, this NaN test may fail if compiled with a floating- ** point precision mode other than /fp:precise. From the MSDN ** documentation: ** ** The compiler [with /fp:precise] will properly handle comparisons ** involving NaN. For example, x != x evaluates to true if x is NaN ** ... */ #ifdef __FAST_MATH__ # error SQLite will not work correctly with the -ffast-math option of GCC. #endif volatile double y = x; volatile double z = y; rc = (y!=z); #else /* if HAVE_ISNAN */ rc = isnan(x); #endif /* HAVE_ISNAN */ testcase( rc ); return rc; } #endif /* SQLITE_OMIT_FLOATING_POINT */ /* ** Compute a string length that is limited to what can be stored in ** lower 30 bits of a 32-bit signed integer. ** ** The value returned will never be negative. Nor will it ever be greater ** than the actual length of the string. For very long strings (greater ** than 1GiB) the value returned might be less than the true string length. */ SQLITE_PRIVATE int sqlite3Strlen30(const char *z){ if( z==0 ) return 0; return 0x3fffffff & (int)strlen(z); } /* ** Return the declared type of a column. Or return zDflt if the column ** has no declared type. ** ** The column type is an extra string stored after the zero-terminator on ** the column name if and only if the COLFLAG_HASTYPE flag is set. */ SQLITE_PRIVATE char *sqlite3ColumnType(Column *pCol, char *zDflt){ if( (pCol->colFlags & COLFLAG_HASTYPE)==0 ) return zDflt; return pCol->zName + strlen(pCol->zName) + 1; } /* ** Helper function for sqlite3Error() - called rarely. Broken out into ** a separate routine to avoid unnecessary register saves on entry to ** sqlite3Error(). */ static SQLITE_NOINLINE void sqlite3ErrorFinish(sqlite3 *db, int err_code){ if( db->pErr ) sqlite3ValueSetNull(db->pErr); sqlite3SystemError(db, err_code); } /* ** Set the current error code to err_code and clear any prior error message. ** Also set iSysErrno (by calling sqlite3System) if the err_code indicates ** that would be appropriate. */ SQLITE_PRIVATE void sqlite3Error(sqlite3 *db, int err_code){ assert( db!=0 ); db->errCode = err_code; if( err_code || db->pErr ) sqlite3ErrorFinish(db, err_code); } /* ** Load the sqlite3.iSysErrno field if that is an appropriate thing ** to do based on the SQLite error code in rc. */ SQLITE_PRIVATE void sqlite3SystemError(sqlite3 *db, int rc){ if( rc==SQLITE_IOERR_NOMEM ) return; rc &= 0xff; if( rc==SQLITE_CANTOPEN || rc==SQLITE_IOERR ){ db->iSysErrno = sqlite3OsGetLastError(db->pVfs); } } /* ** Set the most recent error code and error string for the sqlite ** handle "db". The error code is set to "err_code". ** ** If it is not NULL, string zFormat specifies the format of the ** error string in the style of the printf functions: The following ** format characters are allowed: ** ** %s Insert a string ** %z A string that should be freed after use ** %d Insert an integer ** %T Insert a token ** %S Insert the first element of a SrcList ** ** zFormat and any string tokens that follow it are assumed to be ** encoded in UTF-8. ** ** To clear the most recent error for sqlite handle "db", sqlite3Error ** should be called with err_code set to SQLITE_OK and zFormat set ** to NULL. */ SQLITE_PRIVATE void sqlite3ErrorWithMsg(sqlite3 *db, int err_code, const char *zFormat, ...){ assert( db!=0 ); db->errCode = err_code; sqlite3SystemError(db, err_code); if( zFormat==0 ){ sqlite3Error(db, err_code); }else if( db->pErr || (db->pErr = sqlite3ValueNew(db))!=0 ){ char *z; va_list ap; va_start(ap, zFormat); z = sqlite3VMPrintf(db, zFormat, ap); va_end(ap); sqlite3ValueSetStr(db->pErr, -1, z, SQLITE_UTF8, SQLITE_DYNAMIC); } } /* ** Add an error message to pParse->zErrMsg and increment pParse->nErr. ** The following formatting characters are allowed: ** ** %s Insert a string ** %z A string that should be freed after use ** %d Insert an integer ** %T Insert a token ** %S Insert the first element of a SrcList ** ** This function should be used to report any error that occurs while ** compiling an SQL statement (i.e. within sqlite3_prepare()). The ** last thing the sqlite3_prepare() function does is copy the error ** stored by this function into the database handle using sqlite3Error(). ** Functions sqlite3Error() or sqlite3ErrorWithMsg() should be used ** during statement execution (sqlite3_step() etc.). */ SQLITE_PRIVATE void sqlite3ErrorMsg(Parse *pParse, const char *zFormat, ...){ char *zMsg; va_list ap; sqlite3 *db = pParse->db; va_start(ap, zFormat); zMsg = sqlite3VMPrintf(db, zFormat, ap); va_end(ap); if( db->suppressErr ){ sqlite3DbFree(db, zMsg); }else{ pParse->nErr++; sqlite3DbFree(db, pParse->zErrMsg); pParse->zErrMsg = zMsg; pParse->rc = SQLITE_ERROR; } } /* ** Convert an SQL-style quoted string into a normal string by removing ** the quote characters. The conversion is done in-place. If the ** input does not begin with a quote character, then this routine ** is a no-op. ** ** The input string must be zero-terminated. A new zero-terminator ** is added to the dequoted string. ** ** The return value is -1 if no dequoting occurs or the length of the ** dequoted string, exclusive of the zero terminator, if dequoting does ** occur. ** ** 2002-Feb-14: This routine is extended to remove MS-Access style ** brackets from around identifiers. For example: "[a-b-c]" becomes ** "a-b-c". */ SQLITE_PRIVATE void sqlite3Dequote(char *z){ char quote; int i, j; if( z==0 ) return; quote = z[0]; if( !sqlite3Isquote(quote) ) return; if( quote=='[' ) quote = ']'; for(i=1, j=0;; i++){ assert( z[i] ); if( z[i]==quote ){ if( z[i+1]==quote ){ z[j++] = quote; i++; }else{ break; } }else{ z[j++] = z[i]; } } z[j] = 0; } /* ** Generate a Token object from a string */ SQLITE_PRIVATE void sqlite3TokenInit(Token *p, char *z){ p->z = z; p->n = sqlite3Strlen30(z); } /* Convenient short-hand */ #define UpperToLower sqlite3UpperToLower /* ** Some systems have stricmp(). Others have strcasecmp(). Because ** there is no consistency, we will define our own. ** ** IMPLEMENTATION-OF: R-30243-02494 The sqlite3_stricmp() and ** sqlite3_strnicmp() APIs allow applications and extensions to compare ** the contents of two buffers containing UTF-8 strings in a ** case-independent fashion, using the same definition of "case ** independence" that SQLite uses internally when comparing identifiers. */ SQLITE_API int sqlite3_stricmp(const char *zLeft, const char *zRight){ if( zLeft==0 ){ return zRight ? -1 : 0; }else if( zRight==0 ){ return 1; } return sqlite3StrICmp(zLeft, zRight); } SQLITE_PRIVATE int sqlite3StrICmp(const char *zLeft, const char *zRight){ unsigned char *a, *b; int c; a = (unsigned char *)zLeft; b = (unsigned char *)zRight; for(;;){ c = (int)UpperToLower[*a] - (int)UpperToLower[*b]; if( c || *a==0 ) break; a++; b++; } return c; } SQLITE_API int sqlite3_strnicmp(const char *zLeft, const char *zRight, int N){ register unsigned char *a, *b; if( zLeft==0 ){ return zRight ? -1 : 0; }else if( zRight==0 ){ return 1; } a = (unsigned char *)zLeft; b = (unsigned char *)zRight; while( N-- > 0 && *a!=0 && UpperToLower[*a]==UpperToLower[*b]){ a++; b++; } return N<0 ? 0 : UpperToLower[*a] - UpperToLower[*b]; } /* ** The string z[] is an text representation of a real number. ** Convert this string to a double and write it into *pResult. ** ** The string z[] is length bytes in length (bytes, not characters) and ** uses the encoding enc. The string is not necessarily zero-terminated. ** ** Return TRUE if the result is a valid real number (or integer) and FALSE ** if the string is empty or contains extraneous text. Valid numbers ** are in one of these formats: ** ** [+-]digits[E[+-]digits] ** [+-]digits.[digits][E[+-]digits] ** [+-].digits[E[+-]digits] ** ** Leading and trailing whitespace is ignored for the purpose of determining ** validity. ** ** If some prefix of the input string is a valid number, this routine ** returns FALSE but it still converts the prefix and writes the result ** into *pResult. */ SQLITE_PRIVATE int sqlite3AtoF(const char *z, double *pResult, int length, u8 enc){ #ifndef SQLITE_OMIT_FLOATING_POINT int incr; const char *zEnd = z + length; /* sign * significand * (10 ^ (esign * exponent)) */ int sign = 1; /* sign of significand */ i64 s = 0; /* significand */ int d = 0; /* adjust exponent for shifting decimal point */ int esign = 1; /* sign of exponent */ int e = 0; /* exponent */ int eValid = 1; /* True exponent is either not used or is well-formed */ double result; int nDigits = 0; int nonNum = 0; /* True if input contains UTF16 with high byte non-zero */ assert( enc==SQLITE_UTF8 || enc==SQLITE_UTF16LE || enc==SQLITE_UTF16BE ); *pResult = 0.0; /* Default return value, in case of an error */ if( enc==SQLITE_UTF8 ){ incr = 1; }else{ int i; incr = 2; assert( SQLITE_UTF16LE==2 && SQLITE_UTF16BE==3 ); for(i=3-enc; i=zEnd ) return 0; /* get sign of significand */ if( *z=='-' ){ sign = -1; z+=incr; }else if( *z=='+' ){ z+=incr; } /* copy max significant digits to significand */ while( z=zEnd ) goto do_atof_calc; /* if decimal point is present */ if( *z=='.' ){ z+=incr; /* copy digits from after decimal to significand ** (decrease exponent by d to shift decimal right) */ while( z=zEnd ) goto do_atof_calc; /* if exponent is present */ if( *z=='e' || *z=='E' ){ z+=incr; eValid = 0; /* This branch is needed to avoid a (harmless) buffer overread. The ** special comment alerts the mutation tester that the correct answer ** is obtained even if the branch is omitted */ if( z>=zEnd ) goto do_atof_calc; /*PREVENTS-HARMLESS-OVERREAD*/ /* get sign of exponent */ if( *z=='-' ){ esign = -1; z+=incr; }else if( *z=='+' ){ z+=incr; } /* copy digits to exponent */ while( z0 ){ /*OPTIMIZATION-IF-TRUE*/ if( esign>0 ){ if( s>=(LARGEST_INT64/10) ) break; /*OPTIMIZATION-IF-FALSE*/ s *= 10; }else{ if( s%10!=0 ) break; /*OPTIMIZATION-IF-FALSE*/ s /= 10; } e--; } /* adjust the sign of significand */ s = sign<0 ? -s : s; if( e==0 ){ /*OPTIMIZATION-IF-TRUE*/ result = (double)s; }else{ LONGDOUBLE_TYPE scale = 1.0; /* attempt to handle extremely small/large numbers better */ if( e>307 ){ /*OPTIMIZATION-IF-TRUE*/ if( e<342 ){ /*OPTIMIZATION-IF-TRUE*/ while( e%308 ) { scale *= 1.0e+1; e -= 1; } if( esign<0 ){ result = s / scale; result /= 1.0e+308; }else{ result = s * scale; result *= 1.0e+308; } }else{ assert( e>=342 ); if( esign<0 ){ result = 0.0*s; }else{ result = 1e308*1e308*s; /* Infinity */ } } }else{ /* 1.0e+22 is the largest power of 10 than can be ** represented exactly. */ while( e%22 ) { scale *= 1.0e+1; e -= 1; } while( e>0 ) { scale *= 1.0e+22; e -= 22; } if( esign<0 ){ result = s / scale; }else{ result = s * scale; } } } } /* store the result */ *pResult = result; /* return true if number and no extra non-whitespace chracters after */ return z==zEnd && nDigits>0 && eValid && nonNum==0; #else return !sqlite3Atoi64(z, pResult, length, enc); #endif /* SQLITE_OMIT_FLOATING_POINT */ } /* ** Compare the 19-character string zNum against the text representation ** value 2^63: 9223372036854775808. Return negative, zero, or positive ** if zNum is less than, equal to, or greater than the string. ** Note that zNum must contain exactly 19 characters. ** ** Unlike memcmp() this routine is guaranteed to return the difference ** in the values of the last digit if the only difference is in the ** last digit. So, for example, ** ** compare2pow63("9223372036854775800", 1) ** ** will return -8. */ static int compare2pow63(const char *zNum, int incr){ int c = 0; int i; /* 012345678901234567 */ const char *pow63 = "922337203685477580"; for(i=0; c==0 && i<18; i++){ c = (zNum[i*incr]-pow63[i])*10; } if( c==0 ){ c = zNum[18*incr] - '8'; testcase( c==(-1) ); testcase( c==0 ); testcase( c==(+1) ); } return c; } /* ** Convert zNum to a 64-bit signed integer. zNum must be decimal. This ** routine does *not* accept hexadecimal notation. ** ** If the zNum value is representable as a 64-bit twos-complement ** integer, then write that value into *pNum and return 0. ** ** If zNum is exactly 9223372036854775808, return 2. This special ** case is broken out because while 9223372036854775808 cannot be a ** signed 64-bit integer, its negative -9223372036854775808 can be. ** ** If zNum is too big for a 64-bit integer and is not ** 9223372036854775808 or if zNum contains any non-numeric text, ** then return 1. ** ** length is the number of bytes in the string (bytes, not characters). ** The string is not necessarily zero-terminated. The encoding is ** given by enc. */ SQLITE_PRIVATE int sqlite3Atoi64(const char *zNum, i64 *pNum, int length, u8 enc){ int incr; u64 u = 0; int neg = 0; /* assume positive */ int i; int c = 0; int nonNum = 0; /* True if input contains UTF16 with high byte non-zero */ const char *zStart; const char *zEnd = zNum + length; assert( enc==SQLITE_UTF8 || enc==SQLITE_UTF16LE || enc==SQLITE_UTF16BE ); if( enc==SQLITE_UTF8 ){ incr = 1; }else{ incr = 2; assert( SQLITE_UTF16LE==2 && SQLITE_UTF16BE==3 ); for(i=3-enc; i='0' && c<='9'; i+=incr){ u = u*10 + c - '0'; } if( u>LARGEST_INT64 ){ *pNum = neg ? SMALLEST_INT64 : LARGEST_INT64; }else if( neg ){ *pNum = -(i64)u; }else{ *pNum = (i64)u; } testcase( i==18 ); testcase( i==19 ); testcase( i==20 ); if( &zNum[i]19*incr /* Too many digits */ || nonNum /* UTF16 with high-order bytes non-zero */ ){ /* zNum is empty or contains non-numeric text or is longer ** than 19 digits (thus guaranteeing that it is too large) */ return 1; }else if( i<19*incr ){ /* Less than 19 digits, so we know that it fits in 64 bits */ assert( u<=LARGEST_INT64 ); return 0; }else{ /* zNum is a 19-digit numbers. Compare it against 9223372036854775808. */ c = compare2pow63(zNum, incr); if( c<0 ){ /* zNum is less than 9223372036854775808 so it fits */ assert( u<=LARGEST_INT64 ); return 0; }else if( c>0 ){ /* zNum is greater than 9223372036854775808 so it overflows */ return 1; }else{ /* zNum is exactly 9223372036854775808. Fits if negative. The ** special case 2 overflow if positive */ assert( u-1==LARGEST_INT64 ); return neg ? 0 : 2; } } } /* ** Transform a UTF-8 integer literal, in either decimal or hexadecimal, ** into a 64-bit signed integer. This routine accepts hexadecimal literals, ** whereas sqlite3Atoi64() does not. ** ** Returns: ** ** 0 Successful transformation. Fits in a 64-bit signed integer. ** 1 Integer too large for a 64-bit signed integer or is malformed ** 2 Special case of 9223372036854775808 */ SQLITE_PRIVATE int sqlite3DecOrHexToI64(const char *z, i64 *pOut){ #ifndef SQLITE_OMIT_HEX_INTEGER if( z[0]=='0' && (z[1]=='x' || z[1]=='X') ){ u64 u = 0; int i, k; for(i=2; z[i]=='0'; i++){} for(k=i; sqlite3Isxdigit(z[k]); k++){ u = u*16 + sqlite3HexToInt(z[k]); } memcpy(pOut, &u, 8); return (z[k]==0 && k-i<=16) ? 0 : 1; }else #endif /* SQLITE_OMIT_HEX_INTEGER */ { return sqlite3Atoi64(z, pOut, sqlite3Strlen30(z), SQLITE_UTF8); } } /* ** If zNum represents an integer that will fit in 32-bits, then set ** *pValue to that integer and return true. Otherwise return false. ** ** This routine accepts both decimal and hexadecimal notation for integers. ** ** Any non-numeric characters that following zNum are ignored. ** This is different from sqlite3Atoi64() which requires the ** input number to be zero-terminated. */ SQLITE_PRIVATE int sqlite3GetInt32(const char *zNum, int *pValue){ sqlite_int64 v = 0; int i, c; int neg = 0; if( zNum[0]=='-' ){ neg = 1; zNum++; }else if( zNum[0]=='+' ){ zNum++; } #ifndef SQLITE_OMIT_HEX_INTEGER else if( zNum[0]=='0' && (zNum[1]=='x' || zNum[1]=='X') && sqlite3Isxdigit(zNum[2]) ){ u32 u = 0; zNum += 2; while( zNum[0]=='0' ) zNum++; for(i=0; sqlite3Isxdigit(zNum[i]) && i<8; i++){ u = u*16 + sqlite3HexToInt(zNum[i]); } if( (u&0x80000000)==0 && sqlite3Isxdigit(zNum[i])==0 ){ memcpy(pValue, &u, 4); return 1; }else{ return 0; } } #endif while( zNum[0]=='0' ) zNum++; for(i=0; i<11 && (c = zNum[i] - '0')>=0 && c<=9; i++){ v = v*10 + c; } /* The longest decimal representation of a 32 bit integer is 10 digits: ** ** 1234567890 ** 2^31 -> 2147483648 */ testcase( i==10 ); if( i>10 ){ return 0; } testcase( v-neg==2147483647 ); if( v-neg>2147483647 ){ return 0; } if( neg ){ v = -v; } *pValue = (int)v; return 1; } /* ** Return a 32-bit integer value extracted from a string. If the ** string is not an integer, just return 0. */ SQLITE_PRIVATE int sqlite3Atoi(const char *z){ int x = 0; if( z ) sqlite3GetInt32(z, &x); return x; } /* ** The variable-length integer encoding is as follows: ** ** KEY: ** A = 0xxxxxxx 7 bits of data and one flag bit ** B = 1xxxxxxx 7 bits of data and one flag bit ** C = xxxxxxxx 8 bits of data ** ** 7 bits - A ** 14 bits - BA ** 21 bits - BBA ** 28 bits - BBBA ** 35 bits - BBBBA ** 42 bits - BBBBBA ** 49 bits - BBBBBBA ** 56 bits - BBBBBBBA ** 64 bits - BBBBBBBBC */ /* ** Write a 64-bit variable-length integer to memory starting at p[0]. ** The length of data write will be between 1 and 9 bytes. The number ** of bytes written is returned. ** ** A variable-length integer consists of the lower 7 bits of each byte ** for all bytes that have the 8th bit set and one byte with the 8th ** bit clear. Except, if we get to the 9th byte, it stores the full ** 8 bits and is the last byte. */ static int SQLITE_NOINLINE putVarint64(unsigned char *p, u64 v){ int i, j, n; u8 buf[10]; if( v & (((u64)0xff000000)<<32) ){ p[8] = (u8)v; v >>= 8; for(i=7; i>=0; i--){ p[i] = (u8)((v & 0x7f) | 0x80); v >>= 7; } return 9; } n = 0; do{ buf[n++] = (u8)((v & 0x7f) | 0x80); v >>= 7; }while( v!=0 ); buf[0] &= 0x7f; assert( n<=9 ); for(i=0, j=n-1; j>=0; j--, i++){ p[i] = buf[j]; } return n; } SQLITE_PRIVATE int sqlite3PutVarint(unsigned char *p, u64 v){ if( v<=0x7f ){ p[0] = v&0x7f; return 1; } if( v<=0x3fff ){ p[0] = ((v>>7)&0x7f)|0x80; p[1] = v&0x7f; return 2; } return putVarint64(p,v); } /* ** Bitmasks used by sqlite3GetVarint(). These precomputed constants ** are defined here rather than simply putting the constant expressions ** inline in order to work around bugs in the RVT compiler. ** ** SLOT_2_0 A mask for (0x7f<<14) | 0x7f ** ** SLOT_4_2_0 A mask for (0x7f<<28) | SLOT_2_0 */ #define SLOT_2_0 0x001fc07f #define SLOT_4_2_0 0xf01fc07f /* ** Read a 64-bit variable-length integer from memory starting at p[0]. ** Return the number of bytes read. The value is stored in *v. */ SQLITE_PRIVATE u8 sqlite3GetVarint(const unsigned char *p, u64 *v){ u32 a,b,s; a = *p; /* a: p0 (unmasked) */ if (!(a&0x80)) { *v = a; return 1; } p++; b = *p; /* b: p1 (unmasked) */ if (!(b&0x80)) { a &= 0x7f; a = a<<7; a |= b; *v = a; return 2; } /* Verify that constants are precomputed correctly */ assert( SLOT_2_0 == ((0x7f<<14) | (0x7f)) ); assert( SLOT_4_2_0 == ((0xfU<<28) | (0x7f<<14) | (0x7f)) ); p++; a = a<<14; a |= *p; /* a: p0<<14 | p2 (unmasked) */ if (!(a&0x80)) { a &= SLOT_2_0; b &= 0x7f; b = b<<7; a |= b; *v = a; return 3; } /* CSE1 from below */ a &= SLOT_2_0; p++; b = b<<14; b |= *p; /* b: p1<<14 | p3 (unmasked) */ if (!(b&0x80)) { b &= SLOT_2_0; /* moved CSE1 up */ /* a &= (0x7f<<14)|(0x7f); */ a = a<<7; a |= b; *v = a; return 4; } /* a: p0<<14 | p2 (masked) */ /* b: p1<<14 | p3 (unmasked) */ /* 1:save off p0<<21 | p1<<14 | p2<<7 | p3 (masked) */ /* moved CSE1 up */ /* a &= (0x7f<<14)|(0x7f); */ b &= SLOT_2_0; s = a; /* s: p0<<14 | p2 (masked) */ p++; a = a<<14; a |= *p; /* a: p0<<28 | p2<<14 | p4 (unmasked) */ if (!(a&0x80)) { /* we can skip these cause they were (effectively) done above ** while calculating s */ /* a &= (0x7f<<28)|(0x7f<<14)|(0x7f); */ /* b &= (0x7f<<14)|(0x7f); */ b = b<<7; a |= b; s = s>>18; *v = ((u64)s)<<32 | a; return 5; } /* 2:save off p0<<21 | p1<<14 | p2<<7 | p3 (masked) */ s = s<<7; s |= b; /* s: p0<<21 | p1<<14 | p2<<7 | p3 (masked) */ p++; b = b<<14; b |= *p; /* b: p1<<28 | p3<<14 | p5 (unmasked) */ if (!(b&0x80)) { /* we can skip this cause it was (effectively) done above in calc'ing s */ /* b &= (0x7f<<28)|(0x7f<<14)|(0x7f); */ a &= SLOT_2_0; a = a<<7; a |= b; s = s>>18; *v = ((u64)s)<<32 | a; return 6; } p++; a = a<<14; a |= *p; /* a: p2<<28 | p4<<14 | p6 (unmasked) */ if (!(a&0x80)) { a &= SLOT_4_2_0; b &= SLOT_2_0; b = b<<7; a |= b; s = s>>11; *v = ((u64)s)<<32 | a; return 7; } /* CSE2 from below */ a &= SLOT_2_0; p++; b = b<<14; b |= *p; /* b: p3<<28 | p5<<14 | p7 (unmasked) */ if (!(b&0x80)) { b &= SLOT_4_2_0; /* moved CSE2 up */ /* a &= (0x7f<<14)|(0x7f); */ a = a<<7; a |= b; s = s>>4; *v = ((u64)s)<<32 | a; return 8; } p++; a = a<<15; a |= *p; /* a: p4<<29 | p6<<15 | p8 (unmasked) */ /* moved CSE2 up */ /* a &= (0x7f<<29)|(0x7f<<15)|(0xff); */ b &= SLOT_2_0; b = b<<8; a |= b; s = s<<4; b = p[-4]; b &= 0x7f; b = b>>3; s |= b; *v = ((u64)s)<<32 | a; return 9; } /* ** Read a 32-bit variable-length integer from memory starting at p[0]. ** Return the number of bytes read. The value is stored in *v. ** ** If the varint stored in p[0] is larger than can fit in a 32-bit unsigned ** integer, then set *v to 0xffffffff. ** ** A MACRO version, getVarint32, is provided which inlines the ** single-byte case. All code should use the MACRO version as ** this function assumes the single-byte case has already been handled. */ SQLITE_PRIVATE u8 sqlite3GetVarint32(const unsigned char *p, u32 *v){ u32 a,b; /* The 1-byte case. Overwhelmingly the most common. Handled inline ** by the getVarin32() macro */ a = *p; /* a: p0 (unmasked) */ #ifndef getVarint32 if (!(a&0x80)) { /* Values between 0 and 127 */ *v = a; return 1; } #endif /* The 2-byte case */ p++; b = *p; /* b: p1 (unmasked) */ if (!(b&0x80)) { /* Values between 128 and 16383 */ a &= 0x7f; a = a<<7; *v = a | b; return 2; } /* The 3-byte case */ p++; a = a<<14; a |= *p; /* a: p0<<14 | p2 (unmasked) */ if (!(a&0x80)) { /* Values between 16384 and 2097151 */ a &= (0x7f<<14)|(0x7f); b &= 0x7f; b = b<<7; *v = a | b; return 3; } /* A 32-bit varint is used to store size information in btrees. ** Objects are rarely larger than 2MiB limit of a 3-byte varint. ** A 3-byte varint is sufficient, for example, to record the size ** of a 1048569-byte BLOB or string. ** ** We only unroll the first 1-, 2-, and 3- byte cases. The very ** rare larger cases can be handled by the slower 64-bit varint ** routine. */ #if 1 { u64 v64; u8 n; p -= 2; n = sqlite3GetVarint(p, &v64); assert( n>3 && n<=9 ); if( (v64 & SQLITE_MAX_U32)!=v64 ){ *v = 0xffffffff; }else{ *v = (u32)v64; } return n; } #else /* For following code (kept for historical record only) shows an ** unrolling for the 3- and 4-byte varint cases. This code is ** slightly faster, but it is also larger and much harder to test. */ p++; b = b<<14; b |= *p; /* b: p1<<14 | p3 (unmasked) */ if (!(b&0x80)) { /* Values between 2097152 and 268435455 */ b &= (0x7f<<14)|(0x7f); a &= (0x7f<<14)|(0x7f); a = a<<7; *v = a | b; return 4; } p++; a = a<<14; a |= *p; /* a: p0<<28 | p2<<14 | p4 (unmasked) */ if (!(a&0x80)) { /* Values between 268435456 and 34359738367 */ a &= SLOT_4_2_0; b &= SLOT_4_2_0; b = b<<7; *v = a | b; return 5; } /* We can only reach this point when reading a corrupt database ** file. In that case we are not in any hurry. Use the (relatively ** slow) general-purpose sqlite3GetVarint() routine to extract the ** value. */ { u64 v64; u8 n; p -= 4; n = sqlite3GetVarint(p, &v64); assert( n>5 && n<=9 ); *v = (u32)v64; return n; } #endif } /* ** Return the number of bytes that will be needed to store the given ** 64-bit integer. */ SQLITE_PRIVATE int sqlite3VarintLen(u64 v){ int i; for(i=1; (v >>= 7)!=0; i++){ assert( i<10 ); } return i; } /* ** Read or write a four-byte big-endian integer value. */ SQLITE_PRIVATE u32 sqlite3Get4byte(const u8 *p){ #if SQLITE_BYTEORDER==4321 u32 x; memcpy(&x,p,4); return x; #elif SQLITE_BYTEORDER==1234 && !defined(SQLITE_DISABLE_INTRINSIC) \ && defined(__GNUC__) && GCC_VERSION>=4003000 u32 x; memcpy(&x,p,4); return __builtin_bswap32(x); #elif SQLITE_BYTEORDER==1234 && !defined(SQLITE_DISABLE_INTRINSIC) \ && defined(_MSC_VER) && _MSC_VER>=1300 u32 x; memcpy(&x,p,4); return _byteswap_ulong(x); #else testcase( p[0]&0x80 ); return ((unsigned)p[0]<<24) | (p[1]<<16) | (p[2]<<8) | p[3]; #endif } SQLITE_PRIVATE void sqlite3Put4byte(unsigned char *p, u32 v){ #if SQLITE_BYTEORDER==4321 memcpy(p,&v,4); #elif SQLITE_BYTEORDER==1234 && !defined(SQLITE_DISABLE_INTRINSIC) \ && defined(__GNUC__) && GCC_VERSION>=4003000 u32 x = __builtin_bswap32(v); memcpy(p,&x,4); #elif SQLITE_BYTEORDER==1234 && !defined(SQLITE_DISABLE_INTRINSIC) \ && defined(_MSC_VER) && _MSC_VER>=1300 u32 x = _byteswap_ulong(v); memcpy(p,&x,4); #else p[0] = (u8)(v>>24); p[1] = (u8)(v>>16); p[2] = (u8)(v>>8); p[3] = (u8)v; #endif } /* ** Translate a single byte of Hex into an integer. ** This routine only works if h really is a valid hexadecimal ** character: 0..9a..fA..F */ SQLITE_PRIVATE u8 sqlite3HexToInt(int h){ assert( (h>='0' && h<='9') || (h>='a' && h<='f') || (h>='A' && h<='F') ); #ifdef SQLITE_ASCII h += 9*(1&(h>>6)); #endif #ifdef SQLITE_EBCDIC h += 9*(1&~(h>>4)); #endif return (u8)(h & 0xf); } #if !defined(SQLITE_OMIT_BLOB_LITERAL) || defined(SQLITE_HAS_CODEC) /* ** Convert a BLOB literal of the form "x'hhhhhh'" into its binary ** value. Return a pointer to its binary value. Space to hold the ** binary value has been obtained from malloc and must be freed by ** the calling routine. */ SQLITE_PRIVATE void *sqlite3HexToBlob(sqlite3 *db, const char *z, int n){ char *zBlob; int i; zBlob = (char *)sqlite3DbMallocRawNN(db, n/2 + 1); n--; if( zBlob ){ for(i=0; imagic; if( magic!=SQLITE_MAGIC_OPEN ){ if( sqlite3SafetyCheckSickOrOk(db) ){ testcase( sqlite3GlobalConfig.xLog!=0 ); logBadConnection("unopened"); } return 0; }else{ return 1; } } SQLITE_PRIVATE int sqlite3SafetyCheckSickOrOk(sqlite3 *db){ u32 magic; magic = db->magic; if( magic!=SQLITE_MAGIC_SICK && magic!=SQLITE_MAGIC_OPEN && magic!=SQLITE_MAGIC_BUSY ){ testcase( sqlite3GlobalConfig.xLog!=0 ); logBadConnection("invalid"); return 0; }else{ return 1; } } /* ** Attempt to add, substract, or multiply the 64-bit signed value iB against ** the other 64-bit signed integer at *pA and store the result in *pA. ** Return 0 on success. Or if the operation would have resulted in an ** overflow, leave *pA unchanged and return 1. */ SQLITE_PRIVATE int sqlite3AddInt64(i64 *pA, i64 iB){ i64 iA = *pA; testcase( iA==0 ); testcase( iA==1 ); testcase( iB==-1 ); testcase( iB==0 ); if( iB>=0 ){ testcase( iA>0 && LARGEST_INT64 - iA == iB ); testcase( iA>0 && LARGEST_INT64 - iA == iB - 1 ); if( iA>0 && LARGEST_INT64 - iA < iB ) return 1; }else{ testcase( iA<0 && -(iA + LARGEST_INT64) == iB + 1 ); testcase( iA<0 && -(iA + LARGEST_INT64) == iB + 2 ); if( iA<0 && -(iA + LARGEST_INT64) > iB + 1 ) return 1; } *pA += iB; return 0; } SQLITE_PRIVATE int sqlite3SubInt64(i64 *pA, i64 iB){ testcase( iB==SMALLEST_INT64+1 ); if( iB==SMALLEST_INT64 ){ testcase( (*pA)==(-1) ); testcase( (*pA)==0 ); if( (*pA)>=0 ) return 1; *pA -= iB; return 0; }else{ return sqlite3AddInt64(pA, -iB); } } SQLITE_PRIVATE int sqlite3MulInt64(i64 *pA, i64 iB){ i64 iA = *pA; if( iB>0 ){ if( iA>LARGEST_INT64/iB ) return 1; if( iA0 ){ if( iBLARGEST_INT64/-iB ) return 1; } } *pA = iA*iB; return 0; } /* ** Compute the absolute value of a 32-bit signed integer, of possible. Or ** if the integer has a value of -2147483648, return +2147483647 */ SQLITE_PRIVATE int sqlite3AbsInt32(int x){ if( x>=0 ) return x; if( x==(int)0x80000000 ) return 0x7fffffff; return -x; } #ifdef SQLITE_ENABLE_8_3_NAMES /* ** If SQLITE_ENABLE_8_3_NAMES is set at compile-time and if the database ** filename in zBaseFilename is a URI with the "8_3_names=1" parameter and ** if filename in z[] has a suffix (a.k.a. "extension") that is longer than ** three characters, then shorten the suffix on z[] to be the last three ** characters of the original suffix. ** ** If SQLITE_ENABLE_8_3_NAMES is set to 2 at compile-time, then always ** do the suffix shortening regardless of URI parameter. ** ** Examples: ** ** test.db-journal => test.nal ** test.db-wal => test.wal ** test.db-shm => test.shm ** test.db-mj7f3319fa => test.9fa */ SQLITE_PRIVATE void sqlite3FileSuffix3(const char *zBaseFilename, char *z){ #if SQLITE_ENABLE_8_3_NAMES<2 if( sqlite3_uri_boolean(zBaseFilename, "8_3_names", 0) ) #endif { int i, sz; sz = sqlite3Strlen30(z); for(i=sz-1; i>0 && z[i]!='/' && z[i]!='.'; i--){} if( z[i]=='.' && ALWAYS(sz>i+4) ) memmove(&z[i+1], &z[sz-3], 4); } } #endif /* ** Find (an approximate) sum of two LogEst values. This computation is ** not a simple "+" operator because LogEst is stored as a logarithmic ** value. ** */ SQLITE_PRIVATE LogEst sqlite3LogEstAdd(LogEst a, LogEst b){ static const unsigned char x[] = { 10, 10, /* 0,1 */ 9, 9, /* 2,3 */ 8, 8, /* 4,5 */ 7, 7, 7, /* 6,7,8 */ 6, 6, 6, /* 9,10,11 */ 5, 5, 5, /* 12-14 */ 4, 4, 4, 4, /* 15-18 */ 3, 3, 3, 3, 3, 3, /* 19-24 */ 2, 2, 2, 2, 2, 2, 2, /* 25-31 */ }; if( a>=b ){ if( a>b+49 ) return a; if( a>b+31 ) return a+1; return a+x[a-b]; }else{ if( b>a+49 ) return b; if( b>a+31 ) return b+1; return b+x[b-a]; } } /* ** Convert an integer into a LogEst. In other words, compute an ** approximation for 10*log2(x). */ SQLITE_PRIVATE LogEst sqlite3LogEst(u64 x){ static LogEst a[] = { 0, 2, 3, 5, 6, 7, 8, 9 }; LogEst y = 40; if( x<8 ){ if( x<2 ) return 0; while( x<8 ){ y -= 10; x <<= 1; } }else{ while( x>255 ){ y += 40; x >>= 4; } /*OPTIMIZATION-IF-TRUE*/ while( x>15 ){ y += 10; x >>= 1; } } return a[x&7] + y - 10; } #ifndef SQLITE_OMIT_VIRTUALTABLE /* ** Convert a double into a LogEst ** In other words, compute an approximation for 10*log2(x). */ SQLITE_PRIVATE LogEst sqlite3LogEstFromDouble(double x){ u64 a; LogEst e; assert( sizeof(x)==8 && sizeof(a)==8 ); if( x<=1 ) return 0; if( x<=2000000000 ) return sqlite3LogEst((u64)x); memcpy(&a, &x, 8); e = (a>>52) - 1022; return e*10; } #endif /* SQLITE_OMIT_VIRTUALTABLE */ #if defined(SQLITE_ENABLE_STMT_SCANSTATUS) || \ defined(SQLITE_ENABLE_STAT3_OR_STAT4) || \ defined(SQLITE_EXPLAIN_ESTIMATED_ROWS) /* ** Convert a LogEst into an integer. ** ** Note that this routine is only used when one or more of various ** non-standard compile-time options is enabled. */ SQLITE_PRIVATE u64 sqlite3LogEstToInt(LogEst x){ u64 n; n = x%10; x /= 10; if( n>=5 ) n -= 2; else if( n>=1 ) n -= 1; #if defined(SQLITE_ENABLE_STMT_SCANSTATUS) || \ defined(SQLITE_EXPLAIN_ESTIMATED_ROWS) if( x>60 ) return (u64)LARGEST_INT64; #else /* If only SQLITE_ENABLE_STAT3_OR_STAT4 is on, then the largest input ** possible to this routine is 310, resulting in a maximum x of 31 */ assert( x<=60 ); #endif return x>=3 ? (n+8)<<(x-3) : (n+8)>>(3-x); } #endif /* defined SCANSTAT or STAT4 or ESTIMATED_ROWS */ /************** End of util.c ************************************************/ /************** Begin file hash.c ********************************************/ /* ** 2001 September 22 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ************************************************************************* ** This is the implementation of generic hash-tables ** used in SQLite. */ /* #include "sqliteInt.h" */ /* #include */ /* Turn bulk memory into a hash table object by initializing the ** fields of the Hash structure. ** ** "pNew" is a pointer to the hash table that is to be initialized. */ SQLITE_PRIVATE void sqlite3HashInit(Hash *pNew){ assert( pNew!=0 ); pNew->first = 0; pNew->count = 0; pNew->htsize = 0; pNew->ht = 0; } /* Remove all entries from a hash table. Reclaim all memory. ** Call this routine to delete a hash table or to reset a hash table ** to the empty state. */ SQLITE_PRIVATE void sqlite3HashClear(Hash *pH){ HashElem *elem; /* For looping over all elements of the table */ assert( pH!=0 ); elem = pH->first; pH->first = 0; sqlite3_free(pH->ht); pH->ht = 0; pH->htsize = 0; while( elem ){ HashElem *next_elem = elem->next; sqlite3_free(elem); elem = next_elem; } pH->count = 0; } /* ** The hashing function. */ static unsigned int strHash(const char *z){ unsigned int h = 0; unsigned char c; while( (c = (unsigned char)*z++)!=0 ){ /*OPTIMIZATION-IF-TRUE*/ /* Knuth multiplicative hashing. (Sorting & Searching, p. 510). ** 0x9e3779b1 is 2654435761 which is the closest prime number to ** (2**32)*golden_ratio, where golden_ratio = (sqrt(5) - 1)/2. */ h += sqlite3UpperToLower[c]; h *= 0x9e3779b1; } return h; } /* Link pNew element into the hash table pH. If pEntry!=0 then also ** insert pNew into the pEntry hash bucket. */ static void insertElement( Hash *pH, /* The complete hash table */ struct _ht *pEntry, /* The entry into which pNew is inserted */ HashElem *pNew /* The element to be inserted */ ){ HashElem *pHead; /* First element already in pEntry */ if( pEntry ){ pHead = pEntry->count ? pEntry->chain : 0; pEntry->count++; pEntry->chain = pNew; }else{ pHead = 0; } if( pHead ){ pNew->next = pHead; pNew->prev = pHead->prev; if( pHead->prev ){ pHead->prev->next = pNew; } else { pH->first = pNew; } pHead->prev = pNew; }else{ pNew->next = pH->first; if( pH->first ){ pH->first->prev = pNew; } pNew->prev = 0; pH->first = pNew; } } /* Resize the hash table so that it cantains "new_size" buckets. ** ** The hash table might fail to resize if sqlite3_malloc() fails or ** if the new size is the same as the prior size. ** Return TRUE if the resize occurs and false if not. */ static int rehash(Hash *pH, unsigned int new_size){ struct _ht *new_ht; /* The new hash table */ HashElem *elem, *next_elem; /* For looping over existing elements */ #if SQLITE_MALLOC_SOFT_LIMIT>0 if( new_size*sizeof(struct _ht)>SQLITE_MALLOC_SOFT_LIMIT ){ new_size = SQLITE_MALLOC_SOFT_LIMIT/sizeof(struct _ht); } if( new_size==pH->htsize ) return 0; #endif /* The inability to allocates space for a larger hash table is ** a performance hit but it is not a fatal error. So mark the ** allocation as a benign. Use sqlite3Malloc()/memset(0) instead of ** sqlite3MallocZero() to make the allocation, as sqlite3MallocZero() ** only zeroes the requested number of bytes whereas this module will ** use the actual amount of space allocated for the hash table (which ** may be larger than the requested amount). */ sqlite3BeginBenignMalloc(); new_ht = (struct _ht *)sqlite3Malloc( new_size*sizeof(struct _ht) ); sqlite3EndBenignMalloc(); if( new_ht==0 ) return 0; sqlite3_free(pH->ht); pH->ht = new_ht; pH->htsize = new_size = sqlite3MallocSize(new_ht)/sizeof(struct _ht); memset(new_ht, 0, new_size*sizeof(struct _ht)); for(elem=pH->first, pH->first=0; elem; elem = next_elem){ unsigned int h = strHash(elem->pKey) % new_size; next_elem = elem->next; insertElement(pH, &new_ht[h], elem); } return 1; } /* This function (for internal use only) locates an element in an ** hash table that matches the given key. The hash for this key is ** also computed and returned in the *pH parameter. */ static HashElem *findElementWithHash( const Hash *pH, /* The pH to be searched */ const char *pKey, /* The key we are searching for */ unsigned int *pHash /* Write the hash value here */ ){ HashElem *elem; /* Used to loop thru the element list */ int count; /* Number of elements left to test */ unsigned int h; /* The computed hash */ if( pH->ht ){ /*OPTIMIZATION-IF-TRUE*/ struct _ht *pEntry; h = strHash(pKey) % pH->htsize; pEntry = &pH->ht[h]; elem = pEntry->chain; count = pEntry->count; }else{ h = 0; elem = pH->first; count = pH->count; } *pHash = h; while( count-- ){ assert( elem!=0 ); if( sqlite3StrICmp(elem->pKey,pKey)==0 ){ return elem; } elem = elem->next; } return 0; } /* Remove a single entry from the hash table given a pointer to that ** element and a hash on the element's key. */ static void removeElementGivenHash( Hash *pH, /* The pH containing "elem" */ HashElem* elem, /* The element to be removed from the pH */ unsigned int h /* Hash value for the element */ ){ struct _ht *pEntry; if( elem->prev ){ elem->prev->next = elem->next; }else{ pH->first = elem->next; } if( elem->next ){ elem->next->prev = elem->prev; } if( pH->ht ){ pEntry = &pH->ht[h]; if( pEntry->chain==elem ){ pEntry->chain = elem->next; } pEntry->count--; assert( pEntry->count>=0 ); } sqlite3_free( elem ); pH->count--; if( pH->count==0 ){ assert( pH->first==0 ); assert( pH->count==0 ); sqlite3HashClear(pH); } } /* Attempt to locate an element of the hash table pH with a key ** that matches pKey. Return the data for this element if it is ** found, or NULL if there is no match. */ SQLITE_PRIVATE void *sqlite3HashFind(const Hash *pH, const char *pKey){ HashElem *elem; /* The element that matches key */ unsigned int h; /* A hash on key */ assert( pH!=0 ); assert( pKey!=0 ); elem = findElementWithHash(pH, pKey, &h); return elem ? elem->data : 0; } /* Insert an element into the hash table pH. The key is pKey ** and the data is "data". ** ** If no element exists with a matching key, then a new ** element is created and NULL is returned. ** ** If another element already exists with the same key, then the ** new data replaces the old data and the old data is returned. ** The key is not copied in this instance. If a malloc fails, then ** the new data is returned and the hash table is unchanged. ** ** If the "data" parameter to this function is NULL, then the ** element corresponding to "key" is removed from the hash table. */ SQLITE_PRIVATE void *sqlite3HashInsert(Hash *pH, const char *pKey, void *data){ unsigned int h; /* the hash of the key modulo hash table size */ HashElem *elem; /* Used to loop thru the element list */ HashElem *new_elem; /* New element added to the pH */ assert( pH!=0 ); assert( pKey!=0 ); elem = findElementWithHash(pH,pKey,&h); if( elem ){ void *old_data = elem->data; if( data==0 ){ removeElementGivenHash(pH,elem,h); }else{ elem->data = data; elem->pKey = pKey; } return old_data; } if( data==0 ) return 0; new_elem = (HashElem*)sqlite3Malloc( sizeof(HashElem) ); if( new_elem==0 ) return data; new_elem->pKey = pKey; new_elem->data = data; pH->count++; if( pH->count>=10 && pH->count > 2*pH->htsize ){ if( rehash(pH, pH->count*2) ){ assert( pH->htsize>0 ); h = strHash(pKey) % pH->htsize; } } insertElement(pH, pH->ht ? &pH->ht[h] : 0, new_elem); return 0; } /************** End of hash.c ************************************************/ /************** Begin file opcodes.c *****************************************/ /* Automatically generated. Do not edit */ /* See the tool/mkopcodec.tcl script for details. */ #if !defined(SQLITE_OMIT_EXPLAIN) \ || defined(VDBE_PROFILE) \ || defined(SQLITE_DEBUG) #if defined(SQLITE_ENABLE_EXPLAIN_COMMENTS) || defined(SQLITE_DEBUG) # define OpHelp(X) "\0" X #else # define OpHelp(X) #endif SQLITE_PRIVATE const char *sqlite3OpcodeName(int i){ static const char *const azName[] = { /* 0 */ "Savepoint" OpHelp(""), /* 1 */ "AutoCommit" OpHelp(""), /* 2 */ "Transaction" OpHelp(""), /* 3 */ "SorterNext" OpHelp(""), /* 4 */ "PrevIfOpen" OpHelp(""), /* 5 */ "NextIfOpen" OpHelp(""), /* 6 */ "Prev" OpHelp(""), /* 7 */ "Next" OpHelp(""), /* 8 */ "Checkpoint" OpHelp(""), /* 9 */ "JournalMode" OpHelp(""), /* 10 */ "Vacuum" OpHelp(""), /* 11 */ "VFilter" OpHelp("iplan=r[P3] zplan='P4'"), /* 12 */ "VUpdate" OpHelp("data=r[P3@P2]"), /* 13 */ "Goto" OpHelp(""), /* 14 */ "Gosub" OpHelp(""), /* 15 */ "InitCoroutine" OpHelp(""), /* 16 */ "Yield" OpHelp(""), /* 17 */ "MustBeInt" OpHelp(""), /* 18 */ "Jump" OpHelp(""), /* 19 */ "Not" OpHelp("r[P2]= !r[P1]"), /* 20 */ "Once" OpHelp(""), /* 21 */ "If" OpHelp(""), /* 22 */ "IfNot" OpHelp(""), /* 23 */ "SeekLT" OpHelp("key=r[P3@P4]"), /* 24 */ "SeekLE" OpHelp("key=r[P3@P4]"), /* 25 */ "SeekGE" OpHelp("key=r[P3@P4]"), /* 26 */ "SeekGT" OpHelp("key=r[P3@P4]"), /* 27 */ "Or" OpHelp("r[P3]=(r[P1] || r[P2])"), /* 28 */ "And" OpHelp("r[P3]=(r[P1] && r[P2])"), /* 29 */ "NoConflict" OpHelp("key=r[P3@P4]"), /* 30 */ "NotFound" OpHelp("key=r[P3@P4]"), /* 31 */ "Found" OpHelp("key=r[P3@P4]"), /* 32 */ "SeekRowid" OpHelp("intkey=r[P3]"), /* 33 */ "NotExists" OpHelp("intkey=r[P3]"), /* 34 */ "IsNull" OpHelp("if r[P1]==NULL goto P2"), /* 35 */ "NotNull" OpHelp("if r[P1]!=NULL goto P2"), /* 36 */ "Ne" OpHelp("IF r[P3]!=r[P1]"), /* 37 */ "Eq" OpHelp("IF r[P3]==r[P1]"), /* 38 */ "Gt" OpHelp("IF r[P3]>r[P1]"), /* 39 */ "Le" OpHelp("IF r[P3]<=r[P1]"), /* 40 */ "Lt" OpHelp("IF r[P3]=r[P1]"), /* 42 */ "ElseNotEq" OpHelp(""), /* 43 */ "BitAnd" OpHelp("r[P3]=r[P1]&r[P2]"), /* 44 */ "BitOr" OpHelp("r[P3]=r[P1]|r[P2]"), /* 45 */ "ShiftLeft" OpHelp("r[P3]=r[P2]<>r[P1]"), /* 47 */ "Add" OpHelp("r[P3]=r[P1]+r[P2]"), /* 48 */ "Subtract" OpHelp("r[P3]=r[P2]-r[P1]"), /* 49 */ "Multiply" OpHelp("r[P3]=r[P1]*r[P2]"), /* 50 */ "Divide" OpHelp("r[P3]=r[P2]/r[P1]"), /* 51 */ "Remainder" OpHelp("r[P3]=r[P2]%r[P1]"), /* 52 */ "Concat" OpHelp("r[P3]=r[P2]+r[P1]"), /* 53 */ "Last" OpHelp(""), /* 54 */ "BitNot" OpHelp("r[P1]= ~r[P1]"), /* 55 */ "SorterSort" OpHelp(""), /* 56 */ "Sort" OpHelp(""), /* 57 */ "Rewind" OpHelp(""), /* 58 */ "IdxLE" OpHelp("key=r[P3@P4]"), /* 59 */ "IdxGT" OpHelp("key=r[P3@P4]"), /* 60 */ "IdxLT" OpHelp("key=r[P3@P4]"), /* 61 */ "IdxGE" OpHelp("key=r[P3@P4]"), /* 62 */ "RowSetRead" OpHelp("r[P3]=rowset(P1)"), /* 63 */ "RowSetTest" OpHelp("if r[P3] in rowset(P1) goto P2"), /* 64 */ "Program" OpHelp(""), /* 65 */ "FkIfZero" OpHelp("if fkctr[P1]==0 goto P2"), /* 66 */ "IfPos" OpHelp("if r[P1]>0 then r[P1]-=P3, goto P2"), /* 67 */ "IfNotZero" OpHelp("if r[P1]!=0 then r[P1]-=P3, goto P2"), /* 68 */ "DecrJumpZero" OpHelp("if (--r[P1])==0 goto P2"), /* 69 */ "IncrVacuum" OpHelp(""), /* 70 */ "VNext" OpHelp(""), /* 71 */ "Init" OpHelp("Start at P2"), /* 72 */ "Return" OpHelp(""), /* 73 */ "EndCoroutine" OpHelp(""), /* 74 */ "HaltIfNull" OpHelp("if r[P3]=null halt"), /* 75 */ "Halt" OpHelp(""), /* 76 */ "Integer" OpHelp("r[P2]=P1"), /* 77 */ "Int64" OpHelp("r[P2]=P4"), /* 78 */ "String" OpHelp("r[P2]='P4' (len=P1)"), /* 79 */ "Null" OpHelp("r[P2..P3]=NULL"), /* 80 */ "SoftNull" OpHelp("r[P1]=NULL"), /* 81 */ "Blob" OpHelp("r[P2]=P4 (len=P1)"), /* 82 */ "Variable" OpHelp("r[P2]=parameter(P1,P4)"), /* 83 */ "Move" OpHelp("r[P2@P3]=r[P1@P3]"), /* 84 */ "Copy" OpHelp("r[P2@P3+1]=r[P1@P3+1]"), /* 85 */ "SCopy" OpHelp("r[P2]=r[P1]"), /* 86 */ "IntCopy" OpHelp("r[P2]=r[P1]"), /* 87 */ "ResultRow" OpHelp("output=r[P1@P2]"), /* 88 */ "CollSeq" OpHelp(""), /* 89 */ "Function0" OpHelp("r[P3]=func(r[P2@P5])"), /* 90 */ "Function" OpHelp("r[P3]=func(r[P2@P5])"), /* 91 */ "AddImm" OpHelp("r[P1]=r[P1]+P2"), /* 92 */ "RealAffinity" OpHelp(""), /* 93 */ "Cast" OpHelp("affinity(r[P1])"), /* 94 */ "Permutation" OpHelp(""), /* 95 */ "Compare" OpHelp("r[P1@P3] <-> r[P2@P3]"), /* 96 */ "Column" OpHelp("r[P3]=PX"), /* 97 */ "String8" OpHelp("r[P2]='P4'"), /* 98 */ "Affinity" OpHelp("affinity(r[P1@P2])"), /* 99 */ "MakeRecord" OpHelp("r[P3]=mkrec(r[P1@P2])"), /* 100 */ "Count" OpHelp("r[P2]=count()"), /* 101 */ "ReadCookie" OpHelp(""), /* 102 */ "SetCookie" OpHelp(""), /* 103 */ "ReopenIdx" OpHelp("root=P2 iDb=P3"), /* 104 */ "OpenRead" OpHelp("root=P2 iDb=P3"), /* 105 */ "OpenWrite" OpHelp("root=P2 iDb=P3"), /* 106 */ "OpenAutoindex" OpHelp("nColumn=P2"), /* 107 */ "OpenEphemeral" OpHelp("nColumn=P2"), /* 108 */ "SorterOpen" OpHelp(""), /* 109 */ "SequenceTest" OpHelp("if( cursor[P1].ctr++ ) pc = P2"), /* 110 */ "OpenPseudo" OpHelp("P3 columns in r[P2]"), /* 111 */ "Close" OpHelp(""), /* 112 */ "ColumnsUsed" OpHelp(""), /* 113 */ "Sequence" OpHelp("r[P2]=cursor[P1].ctr++"), /* 114 */ "NewRowid" OpHelp("r[P2]=rowid"), /* 115 */ "Insert" OpHelp("intkey=r[P3] data=r[P2]"), /* 116 */ "InsertInt" OpHelp("intkey=P3 data=r[P2]"), /* 117 */ "Delete" OpHelp(""), /* 118 */ "ResetCount" OpHelp(""), /* 119 */ "SorterCompare" OpHelp("if key(P1)!=trim(r[P3],P4) goto P2"), /* 120 */ "SorterData" OpHelp("r[P2]=data"), /* 121 */ "RowKey" OpHelp("r[P2]=key"), /* 122 */ "RowData" OpHelp("r[P2]=data"), /* 123 */ "Rowid" OpHelp("r[P2]=rowid"), /* 124 */ "NullRow" OpHelp(""), /* 125 */ "SorterInsert" OpHelp(""), /* 126 */ "IdxInsert" OpHelp("key=r[P2]"), /* 127 */ "IdxDelete" OpHelp("key=r[P2@P3]"), /* 128 */ "Seek" OpHelp("Move P3 to P1.rowid"), /* 129 */ "IdxRowid" OpHelp("r[P2]=rowid"), /* 130 */ "Destroy" OpHelp(""), /* 131 */ "Clear" OpHelp(""), /* 132 */ "Real" OpHelp("r[P2]=P4"), /* 133 */ "ResetSorter" OpHelp(""), /* 134 */ "CreateIndex" OpHelp("r[P2]=root iDb=P1"), /* 135 */ "CreateTable" OpHelp("r[P2]=root iDb=P1"), /* 136 */ "ParseSchema" OpHelp(""), /* 137 */ "LoadAnalysis" OpHelp(""), /* 138 */ "DropTable" OpHelp(""), /* 139 */ "DropIndex" OpHelp(""), /* 140 */ "DropTrigger" OpHelp(""), /* 141 */ "IntegrityCk" OpHelp(""), /* 142 */ "RowSetAdd" OpHelp("rowset(P1)=r[P2]"), /* 143 */ "Param" OpHelp(""), /* 144 */ "FkCounter" OpHelp("fkctr[P1]+=P2"), /* 145 */ "MemMax" OpHelp("r[P1]=max(r[P1],r[P2])"), /* 146 */ "OffsetLimit" OpHelp("if r[P1]>0 then r[P2]=r[P1]+max(0,r[P3]) else r[P2]=(-1)"), /* 147 */ "AggStep0" OpHelp("accum=r[P3] step(r[P2@P5])"), /* 148 */ "AggStep" OpHelp("accum=r[P3] step(r[P2@P5])"), /* 149 */ "AggFinal" OpHelp("accum=r[P1] N=P2"), /* 150 */ "Expire" OpHelp(""), /* 151 */ "TableLock" OpHelp("iDb=P1 root=P2 write=P3"), /* 152 */ "VBegin" OpHelp(""), /* 153 */ "VCreate" OpHelp(""), /* 154 */ "VDestroy" OpHelp(""), /* 155 */ "VOpen" OpHelp(""), /* 156 */ "VColumn" OpHelp("r[P3]=vcolumn(P2)"), /* 157 */ "VRename" OpHelp(""), /* 158 */ "Pagecount" OpHelp(""), /* 159 */ "MaxPgcnt" OpHelp(""), /* 160 */ "CursorHint" OpHelp(""), /* 161 */ "Noop" OpHelp(""), /* 162 */ "Explain" OpHelp(""), }; return azName[i]; } #endif /************** End of opcodes.c *********************************************/ /************** Begin file os_unix.c *****************************************/ /* ** 2004 May 22 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ****************************************************************************** ** ** This file contains the VFS implementation for unix-like operating systems ** include Linux, MacOSX, *BSD, QNX, VxWorks, AIX, HPUX, and others. ** ** There are actually several different VFS implementations in this file. ** The differences are in the way that file locking is done. The default ** implementation uses Posix Advisory Locks. Alternative implementations ** use flock(), dot-files, various proprietary locking schemas, or simply ** skip locking all together. ** ** This source file is organized into divisions where the logic for various ** subfunctions is contained within the appropriate division. PLEASE ** KEEP THE STRUCTURE OF THIS FILE INTACT. New code should be placed ** in the correct division and should be clearly labeled. ** ** The layout of divisions is as follows: ** ** * General-purpose declarations and utility functions. ** * Unique file ID logic used by VxWorks. ** * Various locking primitive implementations (all except proxy locking): ** + for Posix Advisory Locks ** + for no-op locks ** + for dot-file locks ** + for flock() locking ** + for named semaphore locks (VxWorks only) ** + for AFP filesystem locks (MacOSX only) ** * sqlite3_file methods not associated with locking. ** * Definitions of sqlite3_io_methods objects for all locking ** methods plus "finder" functions for each locking method. ** * sqlite3_vfs method implementations. ** * Locking primitives for the proxy uber-locking-method. (MacOSX only) ** * Definitions of sqlite3_vfs objects for all locking methods ** plus implementations of sqlite3_os_init() and sqlite3_os_end(). */ /* #include "sqliteInt.h" */ #if SQLITE_OS_UNIX /* This file is used on unix only */ /* ** There are various methods for file locking used for concurrency ** control: ** ** 1. POSIX locking (the default), ** 2. No locking, ** 3. Dot-file locking, ** 4. flock() locking, ** 5. AFP locking (OSX only), ** 6. Named POSIX semaphores (VXWorks only), ** 7. proxy locking. (OSX only) ** ** Styles 4, 5, and 7 are only available of SQLITE_ENABLE_LOCKING_STYLE ** is defined to 1. The SQLITE_ENABLE_LOCKING_STYLE also enables automatic ** selection of the appropriate locking style based on the filesystem ** where the database is located. */ #if !defined(SQLITE_ENABLE_LOCKING_STYLE) # if defined(__APPLE__) # define SQLITE_ENABLE_LOCKING_STYLE 1 # else # define SQLITE_ENABLE_LOCKING_STYLE 0 # endif #endif /* Use pread() and pwrite() if they are available */ #if defined(__APPLE__) # define HAVE_PREAD 1 # define HAVE_PWRITE 1 #endif #if defined(HAVE_PREAD64) && defined(HAVE_PWRITE64) # undef USE_PREAD # define USE_PREAD64 1 #elif defined(HAVE_PREAD) && defined(HAVE_PWRITE) # undef USE_PREAD64 # define USE_PREAD 1 #endif /* ** standard include files. */ #include #include #include #include /* #include */ #include #include #if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0 # include #endif #if SQLITE_ENABLE_LOCKING_STYLE # include # include # include #endif /* SQLITE_ENABLE_LOCKING_STYLE */ #if defined(__APPLE__) && ((__MAC_OS_X_VERSION_MIN_REQUIRED > 1050) || \ (__IPHONE_OS_VERSION_MIN_REQUIRED > 2000)) # if (!defined(TARGET_OS_EMBEDDED) || (TARGET_OS_EMBEDDED==0)) \ && (!defined(TARGET_IPHONE_SIMULATOR) || (TARGET_IPHONE_SIMULATOR==0)) # define HAVE_GETHOSTUUID 1 # else # warning "gethostuuid() is disabled." # endif #endif #if OS_VXWORKS /* # include */ # include # include #endif /* OS_VXWORKS */ #if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE # include #endif #ifdef HAVE_UTIME # include #endif /* ** Allowed values of unixFile.fsFlags */ #define SQLITE_FSFLAGS_IS_MSDOS 0x1 /* ** If we are to be thread-safe, include the pthreads header and define ** the SQLITE_UNIX_THREADS macro. */ #if SQLITE_THREADSAFE /* # include */ # define SQLITE_UNIX_THREADS 1 #endif /* ** Default permissions when creating a new file */ #ifndef SQLITE_DEFAULT_FILE_PERMISSIONS # define SQLITE_DEFAULT_FILE_PERMISSIONS 0644 #endif /* ** Default permissions when creating auto proxy dir */ #ifndef SQLITE_DEFAULT_PROXYDIR_PERMISSIONS # define SQLITE_DEFAULT_PROXYDIR_PERMISSIONS 0755 #endif /* ** Maximum supported path-length. */ #define MAX_PATHNAME 512 /* ** Maximum supported symbolic links */ #define SQLITE_MAX_SYMLINKS 100 /* Always cast the getpid() return type for compatibility with ** kernel modules in VxWorks. */ #define osGetpid(X) (pid_t)getpid() /* ** Only set the lastErrno if the error code is a real error and not ** a normal expected return code of SQLITE_BUSY or SQLITE_OK */ #define IS_LOCK_ERROR(x) ((x != SQLITE_OK) && (x != SQLITE_BUSY)) /* Forward references */ typedef struct unixShm unixShm; /* Connection shared memory */ typedef struct unixShmNode unixShmNode; /* Shared memory instance */ typedef struct unixInodeInfo unixInodeInfo; /* An i-node */ typedef struct UnixUnusedFd UnixUnusedFd; /* An unused file descriptor */ /* ** Sometimes, after a file handle is closed by SQLite, the file descriptor ** cannot be closed immediately. In these cases, instances of the following ** structure are used to store the file descriptor while waiting for an ** opportunity to either close or reuse it. */ struct UnixUnusedFd { int fd; /* File descriptor to close */ int flags; /* Flags this file descriptor was opened with */ UnixUnusedFd *pNext; /* Next unused file descriptor on same file */ }; /* ** The unixFile structure is subclass of sqlite3_file specific to the unix ** VFS implementations. */ typedef struct unixFile unixFile; struct unixFile { sqlite3_io_methods const *pMethod; /* Always the first entry */ sqlite3_vfs *pVfs; /* The VFS that created this unixFile */ unixInodeInfo *pInode; /* Info about locks on this inode */ int h; /* The file descriptor */ unsigned char eFileLock; /* The type of lock held on this fd */ unsigned short int ctrlFlags; /* Behavioral bits. UNIXFILE_* flags */ int lastErrno; /* The unix errno from last I/O error */ void *lockingContext; /* Locking style specific state */ UnixUnusedFd *pUnused; /* Pre-allocated UnixUnusedFd */ const char *zPath; /* Name of the file */ unixShm *pShm; /* Shared memory segment information */ int szChunk; /* Configured by FCNTL_CHUNK_SIZE */ #if SQLITE_MAX_MMAP_SIZE>0 int nFetchOut; /* Number of outstanding xFetch refs */ sqlite3_int64 mmapSize; /* Usable size of mapping at pMapRegion */ sqlite3_int64 mmapSizeActual; /* Actual size of mapping at pMapRegion */ sqlite3_int64 mmapSizeMax; /* Configured FCNTL_MMAP_SIZE value */ void *pMapRegion; /* Memory mapped region */ #endif #ifdef __QNXNTO__ int sectorSize; /* Device sector size */ int deviceCharacteristics; /* Precomputed device characteristics */ #endif #if SQLITE_ENABLE_LOCKING_STYLE int openFlags; /* The flags specified at open() */ #endif #if SQLITE_ENABLE_LOCKING_STYLE || defined(__APPLE__) unsigned fsFlags; /* cached details from statfs() */ #endif #if OS_VXWORKS struct vxworksFileId *pId; /* Unique file ID */ #endif #ifdef SQLITE_DEBUG /* The next group of variables are used to track whether or not the ** transaction counter in bytes 24-27 of database files are updated ** whenever any part of the database changes. An assertion fault will ** occur if a file is updated without also updating the transaction ** counter. This test is made to avoid new problems similar to the ** one described by ticket #3584. */ unsigned char transCntrChng; /* True if the transaction counter changed */ unsigned char dbUpdate; /* True if any part of database file changed */ unsigned char inNormalWrite; /* True if in a normal write operation */ #endif #ifdef SQLITE_TEST /* In test mode, increase the size of this structure a bit so that ** it is larger than the struct CrashFile defined in test6.c. */ char aPadding[32]; #endif }; /* This variable holds the process id (pid) from when the xRandomness() ** method was called. If xOpen() is called from a different process id, ** indicating that a fork() has occurred, the PRNG will be reset. */ static pid_t randomnessPid = 0; /* ** Allowed values for the unixFile.ctrlFlags bitmask: */ #define UNIXFILE_EXCL 0x01 /* Connections from one process only */ #define UNIXFILE_RDONLY 0x02 /* Connection is read only */ #define UNIXFILE_PERSIST_WAL 0x04 /* Persistent WAL mode */ #ifndef SQLITE_DISABLE_DIRSYNC # define UNIXFILE_DIRSYNC 0x08 /* Directory sync needed */ #else # define UNIXFILE_DIRSYNC 0x00 #endif #define UNIXFILE_PSOW 0x10 /* SQLITE_IOCAP_POWERSAFE_OVERWRITE */ #define UNIXFILE_DELETE 0x20 /* Delete on close */ #define UNIXFILE_URI 0x40 /* Filename might have query parameters */ #define UNIXFILE_NOLOCK 0x80 /* Do no file locking */ /* ** Include code that is common to all os_*.c files */ /************** Include os_common.h in the middle of os_unix.c ***************/ /************** Begin file os_common.h ***************************************/ /* ** 2004 May 22 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ****************************************************************************** ** ** This file contains macros and a little bit of code that is common to ** all of the platform-specific files (os_*.c) and is #included into those ** files. ** ** This file should be #included by the os_*.c files only. It is not a ** general purpose header file. */ #ifndef _OS_COMMON_H_ #define _OS_COMMON_H_ /* ** At least two bugs have slipped in because we changed the MEMORY_DEBUG ** macro to SQLITE_DEBUG and some older makefiles have not yet made the ** switch. The following code should catch this problem at compile-time. */ #ifdef MEMORY_DEBUG # error "The MEMORY_DEBUG macro is obsolete. Use SQLITE_DEBUG instead." #endif /* ** Macros for performance tracing. Normally turned off. Only works ** on i486 hardware. */ #ifdef SQLITE_PERFORMANCE_TRACE /* ** hwtime.h contains inline assembler code for implementing ** high-performance timing routines. */ /************** Include hwtime.h in the middle of os_common.h ****************/ /************** Begin file hwtime.h ******************************************/ /* ** 2008 May 27 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ****************************************************************************** ** ** This file contains inline asm code for retrieving "high-performance" ** counters for x86 class CPUs. */ #ifndef SQLITE_HWTIME_H #define SQLITE_HWTIME_H /* ** The following routine only works on pentium-class (or newer) processors. ** It uses the RDTSC opcode to read the cycle count value out of the ** processor and returns that value. This can be used for high-res ** profiling. */ #if (defined(__GNUC__) || defined(_MSC_VER)) && \ (defined(i386) || defined(__i386__) || defined(_M_IX86)) #if defined(__GNUC__) __inline__ sqlite_uint64 sqlite3Hwtime(void){ unsigned int lo, hi; __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi)); return (sqlite_uint64)hi << 32 | lo; } #elif defined(_MSC_VER) __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){ __asm { rdtsc ret ; return value at EDX:EAX } } #endif #elif (defined(__GNUC__) && defined(__x86_64__)) __inline__ sqlite_uint64 sqlite3Hwtime(void){ unsigned long val; __asm__ __volatile__ ("rdtsc" : "=A" (val)); return val; } #elif (defined(__GNUC__) && defined(__ppc__)) __inline__ sqlite_uint64 sqlite3Hwtime(void){ unsigned long long retval; unsigned long junk; __asm__ __volatile__ ("\n\ 1: mftbu %1\n\ mftb %L0\n\ mftbu %0\n\ cmpw %0,%1\n\ bne 1b" : "=r" (retval), "=r" (junk)); return retval; } #else #error Need implementation of sqlite3Hwtime() for your platform. /* ** To compile without implementing sqlite3Hwtime() for your platform, ** you can remove the above #error and use the following ** stub function. You will lose timing support for many ** of the debugging and testing utilities, but it should at ** least compile and run. */ SQLITE_PRIVATE sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); } #endif #endif /* !defined(SQLITE_HWTIME_H) */ /************** End of hwtime.h **********************************************/ /************** Continuing where we left off in os_common.h ******************/ static sqlite_uint64 g_start; static sqlite_uint64 g_elapsed; #define TIMER_START g_start=sqlite3Hwtime() #define TIMER_END g_elapsed=sqlite3Hwtime()-g_start #define TIMER_ELAPSED g_elapsed #else #define TIMER_START #define TIMER_END #define TIMER_ELAPSED ((sqlite_uint64)0) #endif /* ** If we compile with the SQLITE_TEST macro set, then the following block ** of code will give us the ability to simulate a disk I/O error. This ** is used for testing the I/O recovery logic. */ #if defined(SQLITE_TEST) SQLITE_API extern int sqlite3_io_error_hit; SQLITE_API extern int sqlite3_io_error_hardhit; SQLITE_API extern int sqlite3_io_error_pending; SQLITE_API extern int sqlite3_io_error_persist; SQLITE_API extern int sqlite3_io_error_benign; SQLITE_API extern int sqlite3_diskfull_pending; SQLITE_API extern int sqlite3_diskfull; #define SimulateIOErrorBenign(X) sqlite3_io_error_benign=(X) #define SimulateIOError(CODE) \ if( (sqlite3_io_error_persist && sqlite3_io_error_hit) \ || sqlite3_io_error_pending-- == 1 ) \ { local_ioerr(); CODE; } static void local_ioerr(){ IOTRACE(("IOERR\n")); sqlite3_io_error_hit++; if( !sqlite3_io_error_benign ) sqlite3_io_error_hardhit++; } #define SimulateDiskfullError(CODE) \ if( sqlite3_diskfull_pending ){ \ if( sqlite3_diskfull_pending == 1 ){ \ local_ioerr(); \ sqlite3_diskfull = 1; \ sqlite3_io_error_hit = 1; \ CODE; \ }else{ \ sqlite3_diskfull_pending--; \ } \ } #else #define SimulateIOErrorBenign(X) #define SimulateIOError(A) #define SimulateDiskfullError(A) #endif /* defined(SQLITE_TEST) */ /* ** When testing, keep a count of the number of open files. */ #if defined(SQLITE_TEST) SQLITE_API extern int sqlite3_open_file_count; #define OpenCounter(X) sqlite3_open_file_count+=(X) #else #define OpenCounter(X) #endif /* defined(SQLITE_TEST) */ #endif /* !defined(_OS_COMMON_H_) */ /************** End of os_common.h *******************************************/ /************** Continuing where we left off in os_unix.c ********************/ /* ** Define various macros that are missing from some systems. */ #ifndef O_LARGEFILE # define O_LARGEFILE 0 #endif #ifdef SQLITE_DISABLE_LFS # undef O_LARGEFILE # define O_LARGEFILE 0 #endif #ifndef O_NOFOLLOW # define O_NOFOLLOW 0 #endif #ifndef O_BINARY # define O_BINARY 0 #endif /* ** The threadid macro resolves to the thread-id or to 0. Used for ** testing and debugging only. */ #if SQLITE_THREADSAFE #define threadid pthread_self() #else #define threadid 0 #endif /* ** HAVE_MREMAP defaults to true on Linux and false everywhere else. */ #if !defined(HAVE_MREMAP) # if defined(__linux__) && defined(_GNU_SOURCE) # define HAVE_MREMAP 1 # else # define HAVE_MREMAP 0 # endif #endif /* ** Explicitly call the 64-bit version of lseek() on Android. Otherwise, lseek() ** is the 32-bit version, even if _FILE_OFFSET_BITS=64 is defined. */ #ifdef __ANDROID__ # define lseek lseek64 #endif /* ** Different Unix systems declare open() in different ways. Same use ** open(const char*,int,mode_t). Others use open(const char*,int,...). ** The difference is important when using a pointer to the function. ** ** The safest way to deal with the problem is to always use this wrapper ** which always has the same well-defined interface. */ static int posixOpen(const char *zFile, int flags, int mode){ return open(zFile, flags, mode); } /* Forward reference */ static int openDirectory(const char*, int*); static int unixGetpagesize(void); /* ** Many system calls are accessed through pointer-to-functions so that ** they may be overridden at runtime to facilitate fault injection during ** testing and sandboxing. The following array holds the names and pointers ** to all overrideable system calls. */ static struct unix_syscall { const char *zName; /* Name of the system call */ sqlite3_syscall_ptr pCurrent; /* Current value of the system call */ sqlite3_syscall_ptr pDefault; /* Default value */ } aSyscall[] = { { "open", (sqlite3_syscall_ptr)posixOpen, 0 }, #define osOpen ((int(*)(const char*,int,int))aSyscall[0].pCurrent) { "close", (sqlite3_syscall_ptr)close, 0 }, #define osClose ((int(*)(int))aSyscall[1].pCurrent) { "access", (sqlite3_syscall_ptr)access, 0 }, #define osAccess ((int(*)(const char*,int))aSyscall[2].pCurrent) { "getcwd", (sqlite3_syscall_ptr)getcwd, 0 }, #define osGetcwd ((char*(*)(char*,size_t))aSyscall[3].pCurrent) { "stat", (sqlite3_syscall_ptr)stat, 0 }, #define osStat ((int(*)(const char*,struct stat*))aSyscall[4].pCurrent) /* ** The DJGPP compiler environment looks mostly like Unix, but it ** lacks the fcntl() system call. So redefine fcntl() to be something ** that always succeeds. This means that locking does not occur under ** DJGPP. But it is DOS - what did you expect? */ #ifdef __DJGPP__ { "fstat", 0, 0 }, #define osFstat(a,b,c) 0 #else { "fstat", (sqlite3_syscall_ptr)fstat, 0 }, #define osFstat ((int(*)(int,struct stat*))aSyscall[5].pCurrent) #endif { "ftruncate", (sqlite3_syscall_ptr)ftruncate, 0 }, #define osFtruncate ((int(*)(int,off_t))aSyscall[6].pCurrent) { "fcntl", (sqlite3_syscall_ptr)fcntl, 0 }, #define osFcntl ((int(*)(int,int,...))aSyscall[7].pCurrent) { "read", (sqlite3_syscall_ptr)read, 0 }, #define osRead ((ssize_t(*)(int,void*,size_t))aSyscall[8].pCurrent) #if defined(USE_PREAD) || SQLITE_ENABLE_LOCKING_STYLE { "pread", (sqlite3_syscall_ptr)pread, 0 }, #else { "pread", (sqlite3_syscall_ptr)0, 0 }, #endif #define osPread ((ssize_t(*)(int,void*,size_t,off_t))aSyscall[9].pCurrent) #if defined(USE_PREAD64) { "pread64", (sqlite3_syscall_ptr)pread64, 0 }, #else { "pread64", (sqlite3_syscall_ptr)0, 0 }, #endif #define osPread64 ((ssize_t(*)(int,void*,size_t,off64_t))aSyscall[10].pCurrent) { "write", (sqlite3_syscall_ptr)write, 0 }, #define osWrite ((ssize_t(*)(int,const void*,size_t))aSyscall[11].pCurrent) #if defined(USE_PREAD) || SQLITE_ENABLE_LOCKING_STYLE { "pwrite", (sqlite3_syscall_ptr)pwrite, 0 }, #else { "pwrite", (sqlite3_syscall_ptr)0, 0 }, #endif #define osPwrite ((ssize_t(*)(int,const void*,size_t,off_t))\ aSyscall[12].pCurrent) #if defined(USE_PREAD64) { "pwrite64", (sqlite3_syscall_ptr)pwrite64, 0 }, #else { "pwrite64", (sqlite3_syscall_ptr)0, 0 }, #endif #define osPwrite64 ((ssize_t(*)(int,const void*,size_t,off64_t))\ aSyscall[13].pCurrent) { "fchmod", (sqlite3_syscall_ptr)fchmod, 0 }, #define osFchmod ((int(*)(int,mode_t))aSyscall[14].pCurrent) #if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE { "fallocate", (sqlite3_syscall_ptr)posix_fallocate, 0 }, #else { "fallocate", (sqlite3_syscall_ptr)0, 0 }, #endif #define osFallocate ((int(*)(int,off_t,off_t))aSyscall[15].pCurrent) { "unlink", (sqlite3_syscall_ptr)unlink, 0 }, #define osUnlink ((int(*)(const char*))aSyscall[16].pCurrent) { "openDirectory", (sqlite3_syscall_ptr)openDirectory, 0 }, #define osOpenDirectory ((int(*)(const char*,int*))aSyscall[17].pCurrent) { "mkdir", (sqlite3_syscall_ptr)mkdir, 0 }, #define osMkdir ((int(*)(const char*,mode_t))aSyscall[18].pCurrent) { "rmdir", (sqlite3_syscall_ptr)rmdir, 0 }, #define osRmdir ((int(*)(const char*))aSyscall[19].pCurrent) #if defined(HAVE_FCHOWN) { "fchown", (sqlite3_syscall_ptr)fchown, 0 }, #else { "fchown", (sqlite3_syscall_ptr)0, 0 }, #endif #define osFchown ((int(*)(int,uid_t,gid_t))aSyscall[20].pCurrent) { "geteuid", (sqlite3_syscall_ptr)geteuid, 0 }, #define osGeteuid ((uid_t(*)(void))aSyscall[21].pCurrent) #if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0 { "mmap", (sqlite3_syscall_ptr)mmap, 0 }, #else { "mmap", (sqlite3_syscall_ptr)0, 0 }, #endif #define osMmap ((void*(*)(void*,size_t,int,int,int,off_t))aSyscall[22].pCurrent) #if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0 { "munmap", (sqlite3_syscall_ptr)munmap, 0 }, #else { "munmap", (sqlite3_syscall_ptr)0, 0 }, #endif #define osMunmap ((void*(*)(void*,size_t))aSyscall[23].pCurrent) #if HAVE_MREMAP && (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0) { "mremap", (sqlite3_syscall_ptr)mremap, 0 }, #else { "mremap", (sqlite3_syscall_ptr)0, 0 }, #endif #define osMremap ((void*(*)(void*,size_t,size_t,int,...))aSyscall[24].pCurrent) #if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0 { "getpagesize", (sqlite3_syscall_ptr)unixGetpagesize, 0 }, #else { "getpagesize", (sqlite3_syscall_ptr)0, 0 }, #endif #define osGetpagesize ((int(*)(void))aSyscall[25].pCurrent) #if defined(HAVE_READLINK) { "readlink", (sqlite3_syscall_ptr)readlink, 0 }, #else { "readlink", (sqlite3_syscall_ptr)0, 0 }, #endif #define osReadlink ((ssize_t(*)(const char*,char*,size_t))aSyscall[26].pCurrent) #if defined(HAVE_LSTAT) { "lstat", (sqlite3_syscall_ptr)lstat, 0 }, #else { "lstat", (sqlite3_syscall_ptr)0, 0 }, #endif #define osLstat ((int(*)(const char*,struct stat*))aSyscall[27].pCurrent) }; /* End of the overrideable system calls */ /* ** On some systems, calls to fchown() will trigger a message in a security ** log if they come from non-root processes. So avoid calling fchown() if ** we are not running as root. */ static int robustFchown(int fd, uid_t uid, gid_t gid){ #if defined(HAVE_FCHOWN) return osGeteuid() ? 0 : osFchown(fd,uid,gid); #else return 0; #endif } /* ** This is the xSetSystemCall() method of sqlite3_vfs for all of the ** "unix" VFSes. Return SQLITE_OK opon successfully updating the ** system call pointer, or SQLITE_NOTFOUND if there is no configurable ** system call named zName. */ static int unixSetSystemCall( sqlite3_vfs *pNotUsed, /* The VFS pointer. Not used */ const char *zName, /* Name of system call to override */ sqlite3_syscall_ptr pNewFunc /* Pointer to new system call value */ ){ unsigned int i; int rc = SQLITE_NOTFOUND; UNUSED_PARAMETER(pNotUsed); if( zName==0 ){ /* If no zName is given, restore all system calls to their default ** settings and return NULL */ rc = SQLITE_OK; for(i=0; i=SQLITE_MINIMUM_FILE_DESCRIPTOR ) break; osClose(fd); sqlite3_log(SQLITE_WARNING, "attempt to open \"%s\" as file descriptor %d", z, fd); fd = -1; if( osOpen("/dev/null", f, m)<0 ) break; } if( fd>=0 ){ if( m!=0 ){ struct stat statbuf; if( osFstat(fd, &statbuf)==0 && statbuf.st_size==0 && (statbuf.st_mode&0777)!=m ){ osFchmod(fd, m); } } #if defined(FD_CLOEXEC) && (!defined(O_CLOEXEC) || O_CLOEXEC==0) osFcntl(fd, F_SETFD, osFcntl(fd, F_GETFD, 0) | FD_CLOEXEC); #endif } return fd; } /* ** Helper functions to obtain and relinquish the global mutex. The ** global mutex is used to protect the unixInodeInfo and ** vxworksFileId objects used by this file, all of which may be ** shared by multiple threads. ** ** Function unixMutexHeld() is used to assert() that the global mutex ** is held when required. This function is only used as part of assert() ** statements. e.g. ** ** unixEnterMutex() ** assert( unixMutexHeld() ); ** unixEnterLeave() */ static void unixEnterMutex(void){ sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_VFS1)); } static void unixLeaveMutex(void){ sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_VFS1)); } #ifdef SQLITE_DEBUG static int unixMutexHeld(void) { return sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_VFS1)); } #endif #ifdef SQLITE_HAVE_OS_TRACE /* ** Helper function for printing out trace information from debugging ** binaries. This returns the string representation of the supplied ** integer lock-type. */ static const char *azFileLock(int eFileLock){ switch( eFileLock ){ case NO_LOCK: return "NONE"; case SHARED_LOCK: return "SHARED"; case RESERVED_LOCK: return "RESERVED"; case PENDING_LOCK: return "PENDING"; case EXCLUSIVE_LOCK: return "EXCLUSIVE"; } return "ERROR"; } #endif #ifdef SQLITE_LOCK_TRACE /* ** Print out information about all locking operations. ** ** This routine is used for troubleshooting locks on multithreaded ** platforms. Enable by compiling with the -DSQLITE_LOCK_TRACE ** command-line option on the compiler. This code is normally ** turned off. */ static int lockTrace(int fd, int op, struct flock *p){ char *zOpName, *zType; int s; int savedErrno; if( op==F_GETLK ){ zOpName = "GETLK"; }else if( op==F_SETLK ){ zOpName = "SETLK"; }else{ s = osFcntl(fd, op, p); sqlite3DebugPrintf("fcntl unknown %d %d %d\n", fd, op, s); return s; } if( p->l_type==F_RDLCK ){ zType = "RDLCK"; }else if( p->l_type==F_WRLCK ){ zType = "WRLCK"; }else if( p->l_type==F_UNLCK ){ zType = "UNLCK"; }else{ assert( 0 ); } assert( p->l_whence==SEEK_SET ); s = osFcntl(fd, op, p); savedErrno = errno; sqlite3DebugPrintf("fcntl %d %d %s %s %d %d %d %d\n", threadid, fd, zOpName, zType, (int)p->l_start, (int)p->l_len, (int)p->l_pid, s); if( s==(-1) && op==F_SETLK && (p->l_type==F_RDLCK || p->l_type==F_WRLCK) ){ struct flock l2; l2 = *p; osFcntl(fd, F_GETLK, &l2); if( l2.l_type==F_RDLCK ){ zType = "RDLCK"; }else if( l2.l_type==F_WRLCK ){ zType = "WRLCK"; }else if( l2.l_type==F_UNLCK ){ zType = "UNLCK"; }else{ assert( 0 ); } sqlite3DebugPrintf("fcntl-failure-reason: %s %d %d %d\n", zType, (int)l2.l_start, (int)l2.l_len, (int)l2.l_pid); } errno = savedErrno; return s; } #undef osFcntl #define osFcntl lockTrace #endif /* SQLITE_LOCK_TRACE */ /* ** Retry ftruncate() calls that fail due to EINTR ** ** All calls to ftruncate() within this file should be made through ** this wrapper. On the Android platform, bypassing the logic below ** could lead to a corrupt database. */ static int robust_ftruncate(int h, sqlite3_int64 sz){ int rc; #ifdef __ANDROID__ /* On Android, ftruncate() always uses 32-bit offsets, even if ** _FILE_OFFSET_BITS=64 is defined. This means it is unsafe to attempt to ** truncate a file to any size larger than 2GiB. Silently ignore any ** such attempts. */ if( sz>(sqlite3_int64)0x7FFFFFFF ){ rc = SQLITE_OK; }else #endif do{ rc = osFtruncate(h,sz); }while( rc<0 && errno==EINTR ); return rc; } /* ** This routine translates a standard POSIX errno code into something ** useful to the clients of the sqlite3 functions. Specifically, it is ** intended to translate a variety of "try again" errors into SQLITE_BUSY ** and a variety of "please close the file descriptor NOW" errors into ** SQLITE_IOERR ** ** Errors during initialization of locks, or file system support for locks, ** should handle ENOLCK, ENOTSUP, EOPNOTSUPP separately. */ static int sqliteErrorFromPosixError(int posixError, int sqliteIOErr) { assert( (sqliteIOErr == SQLITE_IOERR_LOCK) || (sqliteIOErr == SQLITE_IOERR_UNLOCK) || (sqliteIOErr == SQLITE_IOERR_RDLOCK) || (sqliteIOErr == SQLITE_IOERR_CHECKRESERVEDLOCK) ); switch (posixError) { case EACCES: case EAGAIN: case ETIMEDOUT: case EBUSY: case EINTR: case ENOLCK: /* random NFS retry error, unless during file system support * introspection, in which it actually means what it says */ return SQLITE_BUSY; case EPERM: return SQLITE_PERM; default: return sqliteIOErr; } } /****************************************************************************** ****************** Begin Unique File ID Utility Used By VxWorks *************** ** ** On most versions of unix, we can get a unique ID for a file by concatenating ** the device number and the inode number. But this does not work on VxWorks. ** On VxWorks, a unique file id must be based on the canonical filename. ** ** A pointer to an instance of the following structure can be used as a ** unique file ID in VxWorks. Each instance of this structure contains ** a copy of the canonical filename. There is also a reference count. ** The structure is reclaimed when the number of pointers to it drops to ** zero. ** ** There are never very many files open at one time and lookups are not ** a performance-critical path, so it is sufficient to put these ** structures on a linked list. */ struct vxworksFileId { struct vxworksFileId *pNext; /* Next in a list of them all */ int nRef; /* Number of references to this one */ int nName; /* Length of the zCanonicalName[] string */ char *zCanonicalName; /* Canonical filename */ }; #if OS_VXWORKS /* ** All unique filenames are held on a linked list headed by this ** variable: */ static struct vxworksFileId *vxworksFileList = 0; /* ** Simplify a filename into its canonical form ** by making the following changes: ** ** * removing any trailing and duplicate / ** * convert /./ into just / ** * convert /A/../ where A is any simple name into just / ** ** Changes are made in-place. Return the new name length. ** ** The original filename is in z[0..n-1]. Return the number of ** characters in the simplified name. */ static int vxworksSimplifyName(char *z, int n){ int i, j; while( n>1 && z[n-1]=='/' ){ n--; } for(i=j=0; i0 && z[j-1]!='/' ){ j--; } if( j>0 ){ j--; } i += 2; continue; } } z[j++] = z[i]; } z[j] = 0; return j; } /* ** Find a unique file ID for the given absolute pathname. Return ** a pointer to the vxworksFileId object. This pointer is the unique ** file ID. ** ** The nRef field of the vxworksFileId object is incremented before ** the object is returned. A new vxworksFileId object is created ** and added to the global list if necessary. ** ** If a memory allocation error occurs, return NULL. */ static struct vxworksFileId *vxworksFindFileId(const char *zAbsoluteName){ struct vxworksFileId *pNew; /* search key and new file ID */ struct vxworksFileId *pCandidate; /* For looping over existing file IDs */ int n; /* Length of zAbsoluteName string */ assert( zAbsoluteName[0]=='/' ); n = (int)strlen(zAbsoluteName); pNew = sqlite3_malloc64( sizeof(*pNew) + (n+1) ); if( pNew==0 ) return 0; pNew->zCanonicalName = (char*)&pNew[1]; memcpy(pNew->zCanonicalName, zAbsoluteName, n+1); n = vxworksSimplifyName(pNew->zCanonicalName, n); /* Search for an existing entry that matching the canonical name. ** If found, increment the reference count and return a pointer to ** the existing file ID. */ unixEnterMutex(); for(pCandidate=vxworksFileList; pCandidate; pCandidate=pCandidate->pNext){ if( pCandidate->nName==n && memcmp(pCandidate->zCanonicalName, pNew->zCanonicalName, n)==0 ){ sqlite3_free(pNew); pCandidate->nRef++; unixLeaveMutex(); return pCandidate; } } /* No match was found. We will make a new file ID */ pNew->nRef = 1; pNew->nName = n; pNew->pNext = vxworksFileList; vxworksFileList = pNew; unixLeaveMutex(); return pNew; } /* ** Decrement the reference count on a vxworksFileId object. Free ** the object when the reference count reaches zero. */ static void vxworksReleaseFileId(struct vxworksFileId *pId){ unixEnterMutex(); assert( pId->nRef>0 ); pId->nRef--; if( pId->nRef==0 ){ struct vxworksFileId **pp; for(pp=&vxworksFileList; *pp && *pp!=pId; pp = &((*pp)->pNext)){} assert( *pp==pId ); *pp = pId->pNext; sqlite3_free(pId); } unixLeaveMutex(); } #endif /* OS_VXWORKS */ /*************** End of Unique File ID Utility Used By VxWorks **************** ******************************************************************************/ /****************************************************************************** *************************** Posix Advisory Locking **************************** ** ** POSIX advisory locks are broken by design. ANSI STD 1003.1 (1996) ** section 6.5.2.2 lines 483 through 490 specify that when a process ** sets or clears a lock, that operation overrides any prior locks set ** by the same process. It does not explicitly say so, but this implies ** that it overrides locks set by the same process using a different ** file descriptor. Consider this test case: ** ** int fd1 = open("./file1", O_RDWR|O_CREAT, 0644); ** int fd2 = open("./file2", O_RDWR|O_CREAT, 0644); ** ** Suppose ./file1 and ./file2 are really the same file (because ** one is a hard or symbolic link to the other) then if you set ** an exclusive lock on fd1, then try to get an exclusive lock ** on fd2, it works. I would have expected the second lock to ** fail since there was already a lock on the file due to fd1. ** But not so. Since both locks came from the same process, the ** second overrides the first, even though they were on different ** file descriptors opened on different file names. ** ** This means that we cannot use POSIX locks to synchronize file access ** among competing threads of the same process. POSIX locks will work fine ** to synchronize access for threads in separate processes, but not ** threads within the same process. ** ** To work around the problem, SQLite has to manage file locks internally ** on its own. Whenever a new database is opened, we have to find the ** specific inode of the database file (the inode is determined by the ** st_dev and st_ino fields of the stat structure that fstat() fills in) ** and check for locks already existing on that inode. When locks are ** created or removed, we have to look at our own internal record of the ** locks to see if another thread has previously set a lock on that same ** inode. ** ** (Aside: The use of inode numbers as unique IDs does not work on VxWorks. ** For VxWorks, we have to use the alternative unique ID system based on ** canonical filename and implemented in the previous division.) ** ** The sqlite3_file structure for POSIX is no longer just an integer file ** descriptor. It is now a structure that holds the integer file ** descriptor and a pointer to a structure that describes the internal ** locks on the corresponding inode. There is one locking structure ** per inode, so if the same inode is opened twice, both unixFile structures ** point to the same locking structure. The locking structure keeps ** a reference count (so we will know when to delete it) and a "cnt" ** field that tells us its internal lock status. cnt==0 means the ** file is unlocked. cnt==-1 means the file has an exclusive lock. ** cnt>0 means there are cnt shared locks on the file. ** ** Any attempt to lock or unlock a file first checks the locking ** structure. The fcntl() system call is only invoked to set a ** POSIX lock if the internal lock structure transitions between ** a locked and an unlocked state. ** ** But wait: there are yet more problems with POSIX advisory locks. ** ** If you close a file descriptor that points to a file that has locks, ** all locks on that file that are owned by the current process are ** released. To work around this problem, each unixInodeInfo object ** maintains a count of the number of pending locks on tha inode. ** When an attempt is made to close an unixFile, if there are ** other unixFile open on the same inode that are holding locks, the call ** to close() the file descriptor is deferred until all of the locks clear. ** The unixInodeInfo structure keeps a list of file descriptors that need to ** be closed and that list is walked (and cleared) when the last lock ** clears. ** ** Yet another problem: LinuxThreads do not play well with posix locks. ** ** Many older versions of linux use the LinuxThreads library which is ** not posix compliant. Under LinuxThreads, a lock created by thread ** A cannot be modified or overridden by a different thread B. ** Only thread A can modify the lock. Locking behavior is correct ** if the appliation uses the newer Native Posix Thread Library (NPTL) ** on linux - with NPTL a lock created by thread A can override locks ** in thread B. But there is no way to know at compile-time which ** threading library is being used. So there is no way to know at ** compile-time whether or not thread A can override locks on thread B. ** One has to do a run-time check to discover the behavior of the ** current process. ** ** SQLite used to support LinuxThreads. But support for LinuxThreads ** was dropped beginning with version 3.7.0. SQLite will still work with ** LinuxThreads provided that (1) there is no more than one connection ** per database file in the same process and (2) database connections ** do not move across threads. */ /* ** An instance of the following structure serves as the key used ** to locate a particular unixInodeInfo object. */ struct unixFileId { dev_t dev; /* Device number */ #if OS_VXWORKS struct vxworksFileId *pId; /* Unique file ID for vxworks. */ #else ino_t ino; /* Inode number */ #endif }; /* ** An instance of the following structure is allocated for each open ** inode. Or, on LinuxThreads, there is one of these structures for ** each inode opened by each thread. ** ** A single inode can have multiple file descriptors, so each unixFile ** structure contains a pointer to an instance of this object and this ** object keeps a count of the number of unixFile pointing to it. */ struct unixInodeInfo { struct unixFileId fileId; /* The lookup key */ int nShared; /* Number of SHARED locks held */ unsigned char eFileLock; /* One of SHARED_LOCK, RESERVED_LOCK etc. */ unsigned char bProcessLock; /* An exclusive process lock is held */ int nRef; /* Number of pointers to this structure */ unixShmNode *pShmNode; /* Shared memory associated with this inode */ int nLock; /* Number of outstanding file locks */ UnixUnusedFd *pUnused; /* Unused file descriptors to close */ unixInodeInfo *pNext; /* List of all unixInodeInfo objects */ unixInodeInfo *pPrev; /* .... doubly linked */ #if SQLITE_ENABLE_LOCKING_STYLE unsigned long long sharedByte; /* for AFP simulated shared lock */ #endif #if OS_VXWORKS sem_t *pSem; /* Named POSIX semaphore */ char aSemName[MAX_PATHNAME+2]; /* Name of that semaphore */ #endif }; /* ** A lists of all unixInodeInfo objects. */ static unixInodeInfo *inodeList = 0; /* ** ** This function - unixLogErrorAtLine(), is only ever called via the macro ** unixLogError(). ** ** It is invoked after an error occurs in an OS function and errno has been ** set. It logs a message using sqlite3_log() containing the current value of ** errno and, if possible, the human-readable equivalent from strerror() or ** strerror_r(). ** ** The first argument passed to the macro should be the error code that ** will be returned to SQLite (e.g. SQLITE_IOERR_DELETE, SQLITE_CANTOPEN). ** The two subsequent arguments should be the name of the OS function that ** failed (e.g. "unlink", "open") and the associated file-system path, ** if any. */ #define unixLogError(a,b,c) unixLogErrorAtLine(a,b,c,__LINE__) static int unixLogErrorAtLine( int errcode, /* SQLite error code */ const char *zFunc, /* Name of OS function that failed */ const char *zPath, /* File path associated with error */ int iLine /* Source line number where error occurred */ ){ char *zErr; /* Message from strerror() or equivalent */ int iErrno = errno; /* Saved syscall error number */ /* If this is not a threadsafe build (SQLITE_THREADSAFE==0), then use ** the strerror() function to obtain the human-readable error message ** equivalent to errno. Otherwise, use strerror_r(). */ #if SQLITE_THREADSAFE && defined(HAVE_STRERROR_R) char aErr[80]; memset(aErr, 0, sizeof(aErr)); zErr = aErr; /* If STRERROR_R_CHAR_P (set by autoconf scripts) or __USE_GNU is defined, ** assume that the system provides the GNU version of strerror_r() that ** returns a pointer to a buffer containing the error message. That pointer ** may point to aErr[], or it may point to some static storage somewhere. ** Otherwise, assume that the system provides the POSIX version of ** strerror_r(), which always writes an error message into aErr[]. ** ** If the code incorrectly assumes that it is the POSIX version that is ** available, the error message will often be an empty string. Not a ** huge problem. Incorrectly concluding that the GNU version is available ** could lead to a segfault though. */ #if defined(STRERROR_R_CHAR_P) || defined(__USE_GNU) zErr = # endif strerror_r(iErrno, aErr, sizeof(aErr)-1); #elif SQLITE_THREADSAFE /* This is a threadsafe build, but strerror_r() is not available. */ zErr = ""; #else /* Non-threadsafe build, use strerror(). */ zErr = strerror(iErrno); #endif if( zPath==0 ) zPath = ""; sqlite3_log(errcode, "os_unix.c:%d: (%d) %s(%s) - %s", iLine, iErrno, zFunc, zPath, zErr ); return errcode; } /* ** Close a file descriptor. ** ** We assume that close() almost always works, since it is only in a ** very sick application or on a very sick platform that it might fail. ** If it does fail, simply leak the file descriptor, but do log the ** error. ** ** Note that it is not safe to retry close() after EINTR since the ** file descriptor might have already been reused by another thread. ** So we don't even try to recover from an EINTR. Just log the error ** and move on. */ static void robust_close(unixFile *pFile, int h, int lineno){ if( osClose(h) ){ unixLogErrorAtLine(SQLITE_IOERR_CLOSE, "close", pFile ? pFile->zPath : 0, lineno); } } /* ** Set the pFile->lastErrno. Do this in a subroutine as that provides ** a convenient place to set a breakpoint. */ static void storeLastErrno(unixFile *pFile, int error){ pFile->lastErrno = error; } /* ** Close all file descriptors accumuated in the unixInodeInfo->pUnused list. */ static void closePendingFds(unixFile *pFile){ unixInodeInfo *pInode = pFile->pInode; UnixUnusedFd *p; UnixUnusedFd *pNext; for(p=pInode->pUnused; p; p=pNext){ pNext = p->pNext; robust_close(pFile, p->fd, __LINE__); sqlite3_free(p); } pInode->pUnused = 0; } /* ** Release a unixInodeInfo structure previously allocated by findInodeInfo(). ** ** The mutex entered using the unixEnterMutex() function must be held ** when this function is called. */ static void releaseInodeInfo(unixFile *pFile){ unixInodeInfo *pInode = pFile->pInode; assert( unixMutexHeld() ); if( ALWAYS(pInode) ){ pInode->nRef--; if( pInode->nRef==0 ){ assert( pInode->pShmNode==0 ); closePendingFds(pFile); if( pInode->pPrev ){ assert( pInode->pPrev->pNext==pInode ); pInode->pPrev->pNext = pInode->pNext; }else{ assert( inodeList==pInode ); inodeList = pInode->pNext; } if( pInode->pNext ){ assert( pInode->pNext->pPrev==pInode ); pInode->pNext->pPrev = pInode->pPrev; } sqlite3_free(pInode); } } } /* ** Given a file descriptor, locate the unixInodeInfo object that ** describes that file descriptor. Create a new one if necessary. The ** return value might be uninitialized if an error occurs. ** ** The mutex entered using the unixEnterMutex() function must be held ** when this function is called. ** ** Return an appropriate error code. */ static int findInodeInfo( unixFile *pFile, /* Unix file with file desc used in the key */ unixInodeInfo **ppInode /* Return the unixInodeInfo object here */ ){ int rc; /* System call return code */ int fd; /* The file descriptor for pFile */ struct unixFileId fileId; /* Lookup key for the unixInodeInfo */ struct stat statbuf; /* Low-level file information */ unixInodeInfo *pInode = 0; /* Candidate unixInodeInfo object */ assert( unixMutexHeld() ); /* Get low-level information about the file that we can used to ** create a unique name for the file. */ fd = pFile->h; rc = osFstat(fd, &statbuf); if( rc!=0 ){ storeLastErrno(pFile, errno); #if defined(EOVERFLOW) && defined(SQLITE_DISABLE_LFS) if( pFile->lastErrno==EOVERFLOW ) return SQLITE_NOLFS; #endif return SQLITE_IOERR; } #ifdef __APPLE__ /* On OS X on an msdos filesystem, the inode number is reported ** incorrectly for zero-size files. See ticket #3260. To work ** around this problem (we consider it a bug in OS X, not SQLite) ** we always increase the file size to 1 by writing a single byte ** prior to accessing the inode number. The one byte written is ** an ASCII 'S' character which also happens to be the first byte ** in the header of every SQLite database. In this way, if there ** is a race condition such that another thread has already populated ** the first page of the database, no damage is done. */ if( statbuf.st_size==0 && (pFile->fsFlags & SQLITE_FSFLAGS_IS_MSDOS)!=0 ){ do{ rc = osWrite(fd, "S", 1); }while( rc<0 && errno==EINTR ); if( rc!=1 ){ storeLastErrno(pFile, errno); return SQLITE_IOERR; } rc = osFstat(fd, &statbuf); if( rc!=0 ){ storeLastErrno(pFile, errno); return SQLITE_IOERR; } } #endif memset(&fileId, 0, sizeof(fileId)); fileId.dev = statbuf.st_dev; #if OS_VXWORKS fileId.pId = pFile->pId; #else fileId.ino = statbuf.st_ino; #endif pInode = inodeList; while( pInode && memcmp(&fileId, &pInode->fileId, sizeof(fileId)) ){ pInode = pInode->pNext; } if( pInode==0 ){ pInode = sqlite3_malloc64( sizeof(*pInode) ); if( pInode==0 ){ return SQLITE_NOMEM_BKPT; } memset(pInode, 0, sizeof(*pInode)); memcpy(&pInode->fileId, &fileId, sizeof(fileId)); pInode->nRef = 1; pInode->pNext = inodeList; pInode->pPrev = 0; if( inodeList ) inodeList->pPrev = pInode; inodeList = pInode; }else{ pInode->nRef++; } *ppInode = pInode; return SQLITE_OK; } /* ** Return TRUE if pFile has been renamed or unlinked since it was first opened. */ static int fileHasMoved(unixFile *pFile){ #if OS_VXWORKS return pFile->pInode!=0 && pFile->pId!=pFile->pInode->fileId.pId; #else struct stat buf; return pFile->pInode!=0 && (osStat(pFile->zPath, &buf)!=0 || buf.st_ino!=pFile->pInode->fileId.ino); #endif } /* ** Check a unixFile that is a database. Verify the following: ** ** (1) There is exactly one hard link on the file ** (2) The file is not a symbolic link ** (3) The file has not been renamed or unlinked ** ** Issue sqlite3_log(SQLITE_WARNING,...) messages if anything is not right. */ static void verifyDbFile(unixFile *pFile){ struct stat buf; int rc; /* These verifications occurs for the main database only */ if( pFile->ctrlFlags & UNIXFILE_NOLOCK ) return; rc = osFstat(pFile->h, &buf); if( rc!=0 ){ sqlite3_log(SQLITE_WARNING, "cannot fstat db file %s", pFile->zPath); return; } if( buf.st_nlink==0 ){ sqlite3_log(SQLITE_WARNING, "file unlinked while open: %s", pFile->zPath); return; } if( buf.st_nlink>1 ){ sqlite3_log(SQLITE_WARNING, "multiple links to file: %s", pFile->zPath); return; } if( fileHasMoved(pFile) ){ sqlite3_log(SQLITE_WARNING, "file renamed while open: %s", pFile->zPath); return; } } /* ** This routine checks if there is a RESERVED lock held on the specified ** file by this or any other process. If such a lock is held, set *pResOut ** to a non-zero value otherwise *pResOut is set to zero. The return value ** is set to SQLITE_OK unless an I/O error occurs during lock checking. */ static int unixCheckReservedLock(sqlite3_file *id, int *pResOut){ int rc = SQLITE_OK; int reserved = 0; unixFile *pFile = (unixFile*)id; SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; ); assert( pFile ); assert( pFile->eFileLock<=SHARED_LOCK ); unixEnterMutex(); /* Because pFile->pInode is shared across threads */ /* Check if a thread in this process holds such a lock */ if( pFile->pInode->eFileLock>SHARED_LOCK ){ reserved = 1; } /* Otherwise see if some other process holds it. */ #ifndef __DJGPP__ if( !reserved && !pFile->pInode->bProcessLock ){ struct flock lock; lock.l_whence = SEEK_SET; lock.l_start = RESERVED_BYTE; lock.l_len = 1; lock.l_type = F_WRLCK; if( osFcntl(pFile->h, F_GETLK, &lock) ){ rc = SQLITE_IOERR_CHECKRESERVEDLOCK; storeLastErrno(pFile, errno); } else if( lock.l_type!=F_UNLCK ){ reserved = 1; } } #endif unixLeaveMutex(); OSTRACE(("TEST WR-LOCK %d %d %d (unix)\n", pFile->h, rc, reserved)); *pResOut = reserved; return rc; } /* ** Attempt to set a system-lock on the file pFile. The lock is ** described by pLock. ** ** If the pFile was opened read/write from unix-excl, then the only lock ** ever obtained is an exclusive lock, and it is obtained exactly once ** the first time any lock is attempted. All subsequent system locking ** operations become no-ops. Locking operations still happen internally, ** in order to coordinate access between separate database connections ** within this process, but all of that is handled in memory and the ** operating system does not participate. ** ** This function is a pass-through to fcntl(F_SETLK) if pFile is using ** any VFS other than "unix-excl" or if pFile is opened on "unix-excl" ** and is read-only. ** ** Zero is returned if the call completes successfully, or -1 if a call ** to fcntl() fails. In this case, errno is set appropriately (by fcntl()). */ static int unixFileLock(unixFile *pFile, struct flock *pLock){ int rc; unixInodeInfo *pInode = pFile->pInode; assert( unixMutexHeld() ); assert( pInode!=0 ); if( (pFile->ctrlFlags & (UNIXFILE_EXCL|UNIXFILE_RDONLY))==UNIXFILE_EXCL ){ if( pInode->bProcessLock==0 ){ struct flock lock; assert( pInode->nLock==0 ); lock.l_whence = SEEK_SET; lock.l_start = SHARED_FIRST; lock.l_len = SHARED_SIZE; lock.l_type = F_WRLCK; rc = osFcntl(pFile->h, F_SETLK, &lock); if( rc<0 ) return rc; pInode->bProcessLock = 1; pInode->nLock++; }else{ rc = 0; } }else{ rc = osFcntl(pFile->h, F_SETLK, pLock); } return rc; } /* ** Lock the file with the lock specified by parameter eFileLock - one ** of the following: ** ** (1) SHARED_LOCK ** (2) RESERVED_LOCK ** (3) PENDING_LOCK ** (4) EXCLUSIVE_LOCK ** ** Sometimes when requesting one lock state, additional lock states ** are inserted in between. The locking might fail on one of the later ** transitions leaving the lock state different from what it started but ** still short of its goal. The following chart shows the allowed ** transitions and the inserted intermediate states: ** ** UNLOCKED -> SHARED ** SHARED -> RESERVED ** SHARED -> (PENDING) -> EXCLUSIVE ** RESERVED -> (PENDING) -> EXCLUSIVE ** PENDING -> EXCLUSIVE ** ** This routine will only increase a lock. Use the sqlite3OsUnlock() ** routine to lower a locking level. */ static int unixLock(sqlite3_file *id, int eFileLock){ /* The following describes the implementation of the various locks and ** lock transitions in terms of the POSIX advisory shared and exclusive ** lock primitives (called read-locks and write-locks below, to avoid ** confusion with SQLite lock names). The algorithms are complicated ** slightly in order to be compatible with Windows95 systems simultaneously ** accessing the same database file, in case that is ever required. ** ** Symbols defined in os.h indentify the 'pending byte' and the 'reserved ** byte', each single bytes at well known offsets, and the 'shared byte ** range', a range of 510 bytes at a well known offset. ** ** To obtain a SHARED lock, a read-lock is obtained on the 'pending ** byte'. If this is successful, 'shared byte range' is read-locked ** and the lock on the 'pending byte' released. (Legacy note: When ** SQLite was first developed, Windows95 systems were still very common, ** and Widnows95 lacks a shared-lock capability. So on Windows95, a ** single randomly selected by from the 'shared byte range' is locked. ** Windows95 is now pretty much extinct, but this work-around for the ** lack of shared-locks on Windows95 lives on, for backwards ** compatibility.) ** ** A process may only obtain a RESERVED lock after it has a SHARED lock. ** A RESERVED lock is implemented by grabbing a write-lock on the ** 'reserved byte'. ** ** A process may only obtain a PENDING lock after it has obtained a ** SHARED lock. A PENDING lock is implemented by obtaining a write-lock ** on the 'pending byte'. This ensures that no new SHARED locks can be ** obtained, but existing SHARED locks are allowed to persist. A process ** does not have to obtain a RESERVED lock on the way to a PENDING lock. ** This property is used by the algorithm for rolling back a journal file ** after a crash. ** ** An EXCLUSIVE lock, obtained after a PENDING lock is held, is ** implemented by obtaining a write-lock on the entire 'shared byte ** range'. Since all other locks require a read-lock on one of the bytes ** within this range, this ensures that no other locks are held on the ** database. */ int rc = SQLITE_OK; unixFile *pFile = (unixFile*)id; unixInodeInfo *pInode; struct flock lock; int tErrno = 0; assert( pFile ); OSTRACE(("LOCK %d %s was %s(%s,%d) pid=%d (unix)\n", pFile->h, azFileLock(eFileLock), azFileLock(pFile->eFileLock), azFileLock(pFile->pInode->eFileLock), pFile->pInode->nShared, osGetpid(0))); /* If there is already a lock of this type or more restrictive on the ** unixFile, do nothing. Don't use the end_lock: exit path, as ** unixEnterMutex() hasn't been called yet. */ if( pFile->eFileLock>=eFileLock ){ OSTRACE(("LOCK %d %s ok (already held) (unix)\n", pFile->h, azFileLock(eFileLock))); return SQLITE_OK; } /* Make sure the locking sequence is correct. ** (1) We never move from unlocked to anything higher than shared lock. ** (2) SQLite never explicitly requests a pendig lock. ** (3) A shared lock is always held when a reserve lock is requested. */ assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK ); assert( eFileLock!=PENDING_LOCK ); assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK ); /* This mutex is needed because pFile->pInode is shared across threads */ unixEnterMutex(); pInode = pFile->pInode; /* If some thread using this PID has a lock via a different unixFile* ** handle that precludes the requested lock, return BUSY. */ if( (pFile->eFileLock!=pInode->eFileLock && (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK)) ){ rc = SQLITE_BUSY; goto end_lock; } /* If a SHARED lock is requested, and some thread using this PID already ** has a SHARED or RESERVED lock, then increment reference counts and ** return SQLITE_OK. */ if( eFileLock==SHARED_LOCK && (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){ assert( eFileLock==SHARED_LOCK ); assert( pFile->eFileLock==0 ); assert( pInode->nShared>0 ); pFile->eFileLock = SHARED_LOCK; pInode->nShared++; pInode->nLock++; goto end_lock; } /* A PENDING lock is needed before acquiring a SHARED lock and before ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will ** be released. */ lock.l_len = 1L; lock.l_whence = SEEK_SET; if( eFileLock==SHARED_LOCK || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLocknShared==0 ); assert( pInode->eFileLock==0 ); assert( rc==SQLITE_OK ); /* Now get the read-lock */ lock.l_start = SHARED_FIRST; lock.l_len = SHARED_SIZE; if( unixFileLock(pFile, &lock) ){ tErrno = errno; rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK); } /* Drop the temporary PENDING lock */ lock.l_start = PENDING_BYTE; lock.l_len = 1L; lock.l_type = F_UNLCK; if( unixFileLock(pFile, &lock) && rc==SQLITE_OK ){ /* This could happen with a network mount */ tErrno = errno; rc = SQLITE_IOERR_UNLOCK; } if( rc ){ if( rc!=SQLITE_BUSY ){ storeLastErrno(pFile, tErrno); } goto end_lock; }else{ pFile->eFileLock = SHARED_LOCK; pInode->nLock++; pInode->nShared = 1; } }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){ /* We are trying for an exclusive lock but another thread in this ** same process is still holding a shared lock. */ rc = SQLITE_BUSY; }else{ /* The request was for a RESERVED or EXCLUSIVE lock. It is ** assumed that there is a SHARED or greater lock on the file ** already. */ assert( 0!=pFile->eFileLock ); lock.l_type = F_WRLCK; assert( eFileLock==RESERVED_LOCK || eFileLock==EXCLUSIVE_LOCK ); if( eFileLock==RESERVED_LOCK ){ lock.l_start = RESERVED_BYTE; lock.l_len = 1L; }else{ lock.l_start = SHARED_FIRST; lock.l_len = SHARED_SIZE; } if( unixFileLock(pFile, &lock) ){ tErrno = errno; rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK); if( rc!=SQLITE_BUSY ){ storeLastErrno(pFile, tErrno); } } } #ifdef SQLITE_DEBUG /* Set up the transaction-counter change checking flags when ** transitioning from a SHARED to a RESERVED lock. The change ** from SHARED to RESERVED marks the beginning of a normal ** write operation (not a hot journal rollback). */ if( rc==SQLITE_OK && pFile->eFileLock<=SHARED_LOCK && eFileLock==RESERVED_LOCK ){ pFile->transCntrChng = 0; pFile->dbUpdate = 0; pFile->inNormalWrite = 1; } #endif if( rc==SQLITE_OK ){ pFile->eFileLock = eFileLock; pInode->eFileLock = eFileLock; }else if( eFileLock==EXCLUSIVE_LOCK ){ pFile->eFileLock = PENDING_LOCK; pInode->eFileLock = PENDING_LOCK; } end_lock: unixLeaveMutex(); OSTRACE(("LOCK %d %s %s (unix)\n", pFile->h, azFileLock(eFileLock), rc==SQLITE_OK ? "ok" : "failed")); return rc; } /* ** Add the file descriptor used by file handle pFile to the corresponding ** pUnused list. */ static void setPendingFd(unixFile *pFile){ unixInodeInfo *pInode = pFile->pInode; UnixUnusedFd *p = pFile->pUnused; p->pNext = pInode->pUnused; pInode->pUnused = p; pFile->h = -1; pFile->pUnused = 0; } /* ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock ** must be either NO_LOCK or SHARED_LOCK. ** ** If the locking level of the file descriptor is already at or below ** the requested locking level, this routine is a no-op. ** ** If handleNFSUnlock is true, then on downgrading an EXCLUSIVE_LOCK to SHARED ** the byte range is divided into 2 parts and the first part is unlocked then ** set to a read lock, then the other part is simply unlocked. This works ** around a bug in BSD NFS lockd (also seen on MacOSX 10.3+) that fails to ** remove the write lock on a region when a read lock is set. */ static int posixUnlock(sqlite3_file *id, int eFileLock, int handleNFSUnlock){ unixFile *pFile = (unixFile*)id; unixInodeInfo *pInode; struct flock lock; int rc = SQLITE_OK; assert( pFile ); OSTRACE(("UNLOCK %d %d was %d(%d,%d) pid=%d (unix)\n", pFile->h, eFileLock, pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared, osGetpid(0))); assert( eFileLock<=SHARED_LOCK ); if( pFile->eFileLock<=eFileLock ){ return SQLITE_OK; } unixEnterMutex(); pInode = pFile->pInode; assert( pInode->nShared!=0 ); if( pFile->eFileLock>SHARED_LOCK ){ assert( pInode->eFileLock==pFile->eFileLock ); #ifdef SQLITE_DEBUG /* When reducing a lock such that other processes can start ** reading the database file again, make sure that the ** transaction counter was updated if any part of the database ** file changed. If the transaction counter is not updated, ** other connections to the same file might not realize that ** the file has changed and hence might not know to flush their ** cache. The use of a stale cache can lead to database corruption. */ pFile->inNormalWrite = 0; #endif /* downgrading to a shared lock on NFS involves clearing the write lock ** before establishing the readlock - to avoid a race condition we downgrade ** the lock in 2 blocks, so that part of the range will be covered by a ** write lock until the rest is covered by a read lock: ** 1: [WWWWW] ** 2: [....W] ** 3: [RRRRW] ** 4: [RRRR.] */ if( eFileLock==SHARED_LOCK ){ #if !defined(__APPLE__) || !SQLITE_ENABLE_LOCKING_STYLE (void)handleNFSUnlock; assert( handleNFSUnlock==0 ); #endif #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE if( handleNFSUnlock ){ int tErrno; /* Error code from system call errors */ off_t divSize = SHARED_SIZE - 1; lock.l_type = F_UNLCK; lock.l_whence = SEEK_SET; lock.l_start = SHARED_FIRST; lock.l_len = divSize; if( unixFileLock(pFile, &lock)==(-1) ){ tErrno = errno; rc = SQLITE_IOERR_UNLOCK; storeLastErrno(pFile, tErrno); goto end_unlock; } lock.l_type = F_RDLCK; lock.l_whence = SEEK_SET; lock.l_start = SHARED_FIRST; lock.l_len = divSize; if( unixFileLock(pFile, &lock)==(-1) ){ tErrno = errno; rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_RDLOCK); if( IS_LOCK_ERROR(rc) ){ storeLastErrno(pFile, tErrno); } goto end_unlock; } lock.l_type = F_UNLCK; lock.l_whence = SEEK_SET; lock.l_start = SHARED_FIRST+divSize; lock.l_len = SHARED_SIZE-divSize; if( unixFileLock(pFile, &lock)==(-1) ){ tErrno = errno; rc = SQLITE_IOERR_UNLOCK; storeLastErrno(pFile, tErrno); goto end_unlock; } }else #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */ { lock.l_type = F_RDLCK; lock.l_whence = SEEK_SET; lock.l_start = SHARED_FIRST; lock.l_len = SHARED_SIZE; if( unixFileLock(pFile, &lock) ){ /* In theory, the call to unixFileLock() cannot fail because another ** process is holding an incompatible lock. If it does, this ** indicates that the other process is not following the locking ** protocol. If this happens, return SQLITE_IOERR_RDLOCK. Returning ** SQLITE_BUSY would confuse the upper layer (in practice it causes ** an assert to fail). */ rc = SQLITE_IOERR_RDLOCK; storeLastErrno(pFile, errno); goto end_unlock; } } } lock.l_type = F_UNLCK; lock.l_whence = SEEK_SET; lock.l_start = PENDING_BYTE; lock.l_len = 2L; assert( PENDING_BYTE+1==RESERVED_BYTE ); if( unixFileLock(pFile, &lock)==0 ){ pInode->eFileLock = SHARED_LOCK; }else{ rc = SQLITE_IOERR_UNLOCK; storeLastErrno(pFile, errno); goto end_unlock; } } if( eFileLock==NO_LOCK ){ /* Decrement the shared lock counter. Release the lock using an ** OS call only when all threads in this same process have released ** the lock. */ pInode->nShared--; if( pInode->nShared==0 ){ lock.l_type = F_UNLCK; lock.l_whence = SEEK_SET; lock.l_start = lock.l_len = 0L; if( unixFileLock(pFile, &lock)==0 ){ pInode->eFileLock = NO_LOCK; }else{ rc = SQLITE_IOERR_UNLOCK; storeLastErrno(pFile, errno); pInode->eFileLock = NO_LOCK; pFile->eFileLock = NO_LOCK; } } /* Decrement the count of locks against this same file. When the ** count reaches zero, close any other file descriptors whose close ** was deferred because of outstanding locks. */ pInode->nLock--; assert( pInode->nLock>=0 ); if( pInode->nLock==0 ){ closePendingFds(pFile); } } end_unlock: unixLeaveMutex(); if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock; return rc; } /* ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock ** must be either NO_LOCK or SHARED_LOCK. ** ** If the locking level of the file descriptor is already at or below ** the requested locking level, this routine is a no-op. */ static int unixUnlock(sqlite3_file *id, int eFileLock){ #if SQLITE_MAX_MMAP_SIZE>0 assert( eFileLock==SHARED_LOCK || ((unixFile *)id)->nFetchOut==0 ); #endif return posixUnlock(id, eFileLock, 0); } #if SQLITE_MAX_MMAP_SIZE>0 static int unixMapfile(unixFile *pFd, i64 nByte); static void unixUnmapfile(unixFile *pFd); #endif /* ** This function performs the parts of the "close file" operation ** common to all locking schemes. It closes the directory and file ** handles, if they are valid, and sets all fields of the unixFile ** structure to 0. ** ** It is *not* necessary to hold the mutex when this routine is called, ** even on VxWorks. A mutex will be acquired on VxWorks by the ** vxworksReleaseFileId() routine. */ static int closeUnixFile(sqlite3_file *id){ unixFile *pFile = (unixFile*)id; #if SQLITE_MAX_MMAP_SIZE>0 unixUnmapfile(pFile); #endif if( pFile->h>=0 ){ robust_close(pFile, pFile->h, __LINE__); pFile->h = -1; } #if OS_VXWORKS if( pFile->pId ){ if( pFile->ctrlFlags & UNIXFILE_DELETE ){ osUnlink(pFile->pId->zCanonicalName); } vxworksReleaseFileId(pFile->pId); pFile->pId = 0; } #endif #ifdef SQLITE_UNLINK_AFTER_CLOSE if( pFile->ctrlFlags & UNIXFILE_DELETE ){ osUnlink(pFile->zPath); sqlite3_free(*(char**)&pFile->zPath); pFile->zPath = 0; } #endif OSTRACE(("CLOSE %-3d\n", pFile->h)); OpenCounter(-1); sqlite3_free(pFile->pUnused); memset(pFile, 0, sizeof(unixFile)); return SQLITE_OK; } /* ** Close a file. */ static int unixClose(sqlite3_file *id){ int rc = SQLITE_OK; unixFile *pFile = (unixFile *)id; verifyDbFile(pFile); unixUnlock(id, NO_LOCK); unixEnterMutex(); /* unixFile.pInode is always valid here. Otherwise, a different close ** routine (e.g. nolockClose()) would be called instead. */ assert( pFile->pInode->nLock>0 || pFile->pInode->bProcessLock==0 ); if( ALWAYS(pFile->pInode) && pFile->pInode->nLock ){ /* If there are outstanding locks, do not actually close the file just ** yet because that would clear those locks. Instead, add the file ** descriptor to pInode->pUnused list. It will be automatically closed ** when the last lock is cleared. */ setPendingFd(pFile); } releaseInodeInfo(pFile); rc = closeUnixFile(id); unixLeaveMutex(); return rc; } /************** End of the posix advisory lock implementation ***************** ******************************************************************************/ /****************************************************************************** ****************************** No-op Locking ********************************** ** ** Of the various locking implementations available, this is by far the ** simplest: locking is ignored. No attempt is made to lock the database ** file for reading or writing. ** ** This locking mode is appropriate for use on read-only databases ** (ex: databases that are burned into CD-ROM, for example.) It can ** also be used if the application employs some external mechanism to ** prevent simultaneous access of the same database by two or more ** database connections. But there is a serious risk of database ** corruption if this locking mode is used in situations where multiple ** database connections are accessing the same database file at the same ** time and one or more of those connections are writing. */ static int nolockCheckReservedLock(sqlite3_file *NotUsed, int *pResOut){ UNUSED_PARAMETER(NotUsed); *pResOut = 0; return SQLITE_OK; } static int nolockLock(sqlite3_file *NotUsed, int NotUsed2){ UNUSED_PARAMETER2(NotUsed, NotUsed2); return SQLITE_OK; } static int nolockUnlock(sqlite3_file *NotUsed, int NotUsed2){ UNUSED_PARAMETER2(NotUsed, NotUsed2); return SQLITE_OK; } /* ** Close the file. */ static int nolockClose(sqlite3_file *id) { return closeUnixFile(id); } /******************* End of the no-op lock implementation ********************* ******************************************************************************/ /****************************************************************************** ************************* Begin dot-file Locking ****************************** ** ** The dotfile locking implementation uses the existence of separate lock ** files (really a directory) to control access to the database. This works ** on just about every filesystem imaginable. But there are serious downsides: ** ** (1) There is zero concurrency. A single reader blocks all other ** connections from reading or writing the database. ** ** (2) An application crash or power loss can leave stale lock files ** sitting around that need to be cleared manually. ** ** Nevertheless, a dotlock is an appropriate locking mode for use if no ** other locking strategy is available. ** ** Dotfile locking works by creating a subdirectory in the same directory as ** the database and with the same name but with a ".lock" extension added. ** The existence of a lock directory implies an EXCLUSIVE lock. All other ** lock types (SHARED, RESERVED, PENDING) are mapped into EXCLUSIVE. */ /* ** The file suffix added to the data base filename in order to create the ** lock directory. */ #define DOTLOCK_SUFFIX ".lock" /* ** This routine checks if there is a RESERVED lock held on the specified ** file by this or any other process. If such a lock is held, set *pResOut ** to a non-zero value otherwise *pResOut is set to zero. The return value ** is set to SQLITE_OK unless an I/O error occurs during lock checking. ** ** In dotfile locking, either a lock exists or it does not. So in this ** variation of CheckReservedLock(), *pResOut is set to true if any lock ** is held on the file and false if the file is unlocked. */ static int dotlockCheckReservedLock(sqlite3_file *id, int *pResOut) { int rc = SQLITE_OK; int reserved = 0; unixFile *pFile = (unixFile*)id; SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; ); assert( pFile ); reserved = osAccess((const char*)pFile->lockingContext, 0)==0; OSTRACE(("TEST WR-LOCK %d %d %d (dotlock)\n", pFile->h, rc, reserved)); *pResOut = reserved; return rc; } /* ** Lock the file with the lock specified by parameter eFileLock - one ** of the following: ** ** (1) SHARED_LOCK ** (2) RESERVED_LOCK ** (3) PENDING_LOCK ** (4) EXCLUSIVE_LOCK ** ** Sometimes when requesting one lock state, additional lock states ** are inserted in between. The locking might fail on one of the later ** transitions leaving the lock state different from what it started but ** still short of its goal. The following chart shows the allowed ** transitions and the inserted intermediate states: ** ** UNLOCKED -> SHARED ** SHARED -> RESERVED ** SHARED -> (PENDING) -> EXCLUSIVE ** RESERVED -> (PENDING) -> EXCLUSIVE ** PENDING -> EXCLUSIVE ** ** This routine will only increase a lock. Use the sqlite3OsUnlock() ** routine to lower a locking level. ** ** With dotfile locking, we really only support state (4): EXCLUSIVE. ** But we track the other locking levels internally. */ static int dotlockLock(sqlite3_file *id, int eFileLock) { unixFile *pFile = (unixFile*)id; char *zLockFile = (char *)pFile->lockingContext; int rc = SQLITE_OK; /* If we have any lock, then the lock file already exists. All we have ** to do is adjust our internal record of the lock level. */ if( pFile->eFileLock > NO_LOCK ){ pFile->eFileLock = eFileLock; /* Always update the timestamp on the old file */ #ifdef HAVE_UTIME utime(zLockFile, NULL); #else utimes(zLockFile, NULL); #endif return SQLITE_OK; } /* grab an exclusive lock */ rc = osMkdir(zLockFile, 0777); if( rc<0 ){ /* failed to open/create the lock directory */ int tErrno = errno; if( EEXIST == tErrno ){ rc = SQLITE_BUSY; } else { rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK); if( rc!=SQLITE_BUSY ){ storeLastErrno(pFile, tErrno); } } return rc; } /* got it, set the type and return ok */ pFile->eFileLock = eFileLock; return rc; } /* ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock ** must be either NO_LOCK or SHARED_LOCK. ** ** If the locking level of the file descriptor is already at or below ** the requested locking level, this routine is a no-op. ** ** When the locking level reaches NO_LOCK, delete the lock file. */ static int dotlockUnlock(sqlite3_file *id, int eFileLock) { unixFile *pFile = (unixFile*)id; char *zLockFile = (char *)pFile->lockingContext; int rc; assert( pFile ); OSTRACE(("UNLOCK %d %d was %d pid=%d (dotlock)\n", pFile->h, eFileLock, pFile->eFileLock, osGetpid(0))); assert( eFileLock<=SHARED_LOCK ); /* no-op if possible */ if( pFile->eFileLock==eFileLock ){ return SQLITE_OK; } /* To downgrade to shared, simply update our internal notion of the ** lock state. No need to mess with the file on disk. */ if( eFileLock==SHARED_LOCK ){ pFile->eFileLock = SHARED_LOCK; return SQLITE_OK; } /* To fully unlock the database, delete the lock file */ assert( eFileLock==NO_LOCK ); rc = osRmdir(zLockFile); if( rc<0 ){ int tErrno = errno; if( tErrno==ENOENT ){ rc = SQLITE_OK; }else{ rc = SQLITE_IOERR_UNLOCK; storeLastErrno(pFile, tErrno); } return rc; } pFile->eFileLock = NO_LOCK; return SQLITE_OK; } /* ** Close a file. Make sure the lock has been released before closing. */ static int dotlockClose(sqlite3_file *id) { unixFile *pFile = (unixFile*)id; assert( id!=0 ); dotlockUnlock(id, NO_LOCK); sqlite3_free(pFile->lockingContext); return closeUnixFile(id); } /****************** End of the dot-file lock implementation ******************* ******************************************************************************/ /****************************************************************************** ************************** Begin flock Locking ******************************** ** ** Use the flock() system call to do file locking. ** ** flock() locking is like dot-file locking in that the various ** fine-grain locking levels supported by SQLite are collapsed into ** a single exclusive lock. In other words, SHARED, RESERVED, and ** PENDING locks are the same thing as an EXCLUSIVE lock. SQLite ** still works when you do this, but concurrency is reduced since ** only a single process can be reading the database at a time. ** ** Omit this section if SQLITE_ENABLE_LOCKING_STYLE is turned off */ #if SQLITE_ENABLE_LOCKING_STYLE /* ** Retry flock() calls that fail with EINTR */ #ifdef EINTR static int robust_flock(int fd, int op){ int rc; do{ rc = flock(fd,op); }while( rc<0 && errno==EINTR ); return rc; } #else # define robust_flock(a,b) flock(a,b) #endif /* ** This routine checks if there is a RESERVED lock held on the specified ** file by this or any other process. If such a lock is held, set *pResOut ** to a non-zero value otherwise *pResOut is set to zero. The return value ** is set to SQLITE_OK unless an I/O error occurs during lock checking. */ static int flockCheckReservedLock(sqlite3_file *id, int *pResOut){ int rc = SQLITE_OK; int reserved = 0; unixFile *pFile = (unixFile*)id; SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; ); assert( pFile ); /* Check if a thread in this process holds such a lock */ if( pFile->eFileLock>SHARED_LOCK ){ reserved = 1; } /* Otherwise see if some other process holds it. */ if( !reserved ){ /* attempt to get the lock */ int lrc = robust_flock(pFile->h, LOCK_EX | LOCK_NB); if( !lrc ){ /* got the lock, unlock it */ lrc = robust_flock(pFile->h, LOCK_UN); if ( lrc ) { int tErrno = errno; /* unlock failed with an error */ lrc = SQLITE_IOERR_UNLOCK; storeLastErrno(pFile, tErrno); rc = lrc; } } else { int tErrno = errno; reserved = 1; /* someone else might have it reserved */ lrc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK); if( IS_LOCK_ERROR(lrc) ){ storeLastErrno(pFile, tErrno); rc = lrc; } } } OSTRACE(("TEST WR-LOCK %d %d %d (flock)\n", pFile->h, rc, reserved)); #ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){ rc = SQLITE_OK; reserved=1; } #endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */ *pResOut = reserved; return rc; } /* ** Lock the file with the lock specified by parameter eFileLock - one ** of the following: ** ** (1) SHARED_LOCK ** (2) RESERVED_LOCK ** (3) PENDING_LOCK ** (4) EXCLUSIVE_LOCK ** ** Sometimes when requesting one lock state, additional lock states ** are inserted in between. The locking might fail on one of the later ** transitions leaving the lock state different from what it started but ** still short of its goal. The following chart shows the allowed ** transitions and the inserted intermediate states: ** ** UNLOCKED -> SHARED ** SHARED -> RESERVED ** SHARED -> (PENDING) -> EXCLUSIVE ** RESERVED -> (PENDING) -> EXCLUSIVE ** PENDING -> EXCLUSIVE ** ** flock() only really support EXCLUSIVE locks. We track intermediate ** lock states in the sqlite3_file structure, but all locks SHARED or ** above are really EXCLUSIVE locks and exclude all other processes from ** access the file. ** ** This routine will only increase a lock. Use the sqlite3OsUnlock() ** routine to lower a locking level. */ static int flockLock(sqlite3_file *id, int eFileLock) { int rc = SQLITE_OK; unixFile *pFile = (unixFile*)id; assert( pFile ); /* if we already have a lock, it is exclusive. ** Just adjust level and punt on outta here. */ if (pFile->eFileLock > NO_LOCK) { pFile->eFileLock = eFileLock; return SQLITE_OK; } /* grab an exclusive lock */ if (robust_flock(pFile->h, LOCK_EX | LOCK_NB)) { int tErrno = errno; /* didn't get, must be busy */ rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK); if( IS_LOCK_ERROR(rc) ){ storeLastErrno(pFile, tErrno); } } else { /* got it, set the type and return ok */ pFile->eFileLock = eFileLock; } OSTRACE(("LOCK %d %s %s (flock)\n", pFile->h, azFileLock(eFileLock), rc==SQLITE_OK ? "ok" : "failed")); #ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){ rc = SQLITE_BUSY; } #endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */ return rc; } /* ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock ** must be either NO_LOCK or SHARED_LOCK. ** ** If the locking level of the file descriptor is already at or below ** the requested locking level, this routine is a no-op. */ static int flockUnlock(sqlite3_file *id, int eFileLock) { unixFile *pFile = (unixFile*)id; assert( pFile ); OSTRACE(("UNLOCK %d %d was %d pid=%d (flock)\n", pFile->h, eFileLock, pFile->eFileLock, osGetpid(0))); assert( eFileLock<=SHARED_LOCK ); /* no-op if possible */ if( pFile->eFileLock==eFileLock ){ return SQLITE_OK; } /* shared can just be set because we always have an exclusive */ if (eFileLock==SHARED_LOCK) { pFile->eFileLock = eFileLock; return SQLITE_OK; } /* no, really, unlock. */ if( robust_flock(pFile->h, LOCK_UN) ){ #ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS return SQLITE_OK; #endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */ return SQLITE_IOERR_UNLOCK; }else{ pFile->eFileLock = NO_LOCK; return SQLITE_OK; } } /* ** Close a file. */ static int flockClose(sqlite3_file *id) { assert( id!=0 ); flockUnlock(id, NO_LOCK); return closeUnixFile(id); } #endif /* SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORK */ /******************* End of the flock lock implementation ********************* ******************************************************************************/ /****************************************************************************** ************************ Begin Named Semaphore Locking ************************ ** ** Named semaphore locking is only supported on VxWorks. ** ** Semaphore locking is like dot-lock and flock in that it really only ** supports EXCLUSIVE locking. Only a single process can read or write ** the database file at a time. This reduces potential concurrency, but ** makes the lock implementation much easier. */ #if OS_VXWORKS /* ** This routine checks if there is a RESERVED lock held on the specified ** file by this or any other process. If such a lock is held, set *pResOut ** to a non-zero value otherwise *pResOut is set to zero. The return value ** is set to SQLITE_OK unless an I/O error occurs during lock checking. */ static int semXCheckReservedLock(sqlite3_file *id, int *pResOut) { int rc = SQLITE_OK; int reserved = 0; unixFile *pFile = (unixFile*)id; SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; ); assert( pFile ); /* Check if a thread in this process holds such a lock */ if( pFile->eFileLock>SHARED_LOCK ){ reserved = 1; } /* Otherwise see if some other process holds it. */ if( !reserved ){ sem_t *pSem = pFile->pInode->pSem; if( sem_trywait(pSem)==-1 ){ int tErrno = errno; if( EAGAIN != tErrno ){ rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_CHECKRESERVEDLOCK); storeLastErrno(pFile, tErrno); } else { /* someone else has the lock when we are in NO_LOCK */ reserved = (pFile->eFileLock < SHARED_LOCK); } }else{ /* we could have it if we want it */ sem_post(pSem); } } OSTRACE(("TEST WR-LOCK %d %d %d (sem)\n", pFile->h, rc, reserved)); *pResOut = reserved; return rc; } /* ** Lock the file with the lock specified by parameter eFileLock - one ** of the following: ** ** (1) SHARED_LOCK ** (2) RESERVED_LOCK ** (3) PENDING_LOCK ** (4) EXCLUSIVE_LOCK ** ** Sometimes when requesting one lock state, additional lock states ** are inserted in between. The locking might fail on one of the later ** transitions leaving the lock state different from what it started but ** still short of its goal. The following chart shows the allowed ** transitions and the inserted intermediate states: ** ** UNLOCKED -> SHARED ** SHARED -> RESERVED ** SHARED -> (PENDING) -> EXCLUSIVE ** RESERVED -> (PENDING) -> EXCLUSIVE ** PENDING -> EXCLUSIVE ** ** Semaphore locks only really support EXCLUSIVE locks. We track intermediate ** lock states in the sqlite3_file structure, but all locks SHARED or ** above are really EXCLUSIVE locks and exclude all other processes from ** access the file. ** ** This routine will only increase a lock. Use the sqlite3OsUnlock() ** routine to lower a locking level. */ static int semXLock(sqlite3_file *id, int eFileLock) { unixFile *pFile = (unixFile*)id; sem_t *pSem = pFile->pInode->pSem; int rc = SQLITE_OK; /* if we already have a lock, it is exclusive. ** Just adjust level and punt on outta here. */ if (pFile->eFileLock > NO_LOCK) { pFile->eFileLock = eFileLock; rc = SQLITE_OK; goto sem_end_lock; } /* lock semaphore now but bail out when already locked. */ if( sem_trywait(pSem)==-1 ){ rc = SQLITE_BUSY; goto sem_end_lock; } /* got it, set the type and return ok */ pFile->eFileLock = eFileLock; sem_end_lock: return rc; } /* ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock ** must be either NO_LOCK or SHARED_LOCK. ** ** If the locking level of the file descriptor is already at or below ** the requested locking level, this routine is a no-op. */ static int semXUnlock(sqlite3_file *id, int eFileLock) { unixFile *pFile = (unixFile*)id; sem_t *pSem = pFile->pInode->pSem; assert( pFile ); assert( pSem ); OSTRACE(("UNLOCK %d %d was %d pid=%d (sem)\n", pFile->h, eFileLock, pFile->eFileLock, osGetpid(0))); assert( eFileLock<=SHARED_LOCK ); /* no-op if possible */ if( pFile->eFileLock==eFileLock ){ return SQLITE_OK; } /* shared can just be set because we always have an exclusive */ if (eFileLock==SHARED_LOCK) { pFile->eFileLock = eFileLock; return SQLITE_OK; } /* no, really unlock. */ if ( sem_post(pSem)==-1 ) { int rc, tErrno = errno; rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK); if( IS_LOCK_ERROR(rc) ){ storeLastErrno(pFile, tErrno); } return rc; } pFile->eFileLock = NO_LOCK; return SQLITE_OK; } /* ** Close a file. */ static int semXClose(sqlite3_file *id) { if( id ){ unixFile *pFile = (unixFile*)id; semXUnlock(id, NO_LOCK); assert( pFile ); unixEnterMutex(); releaseInodeInfo(pFile); unixLeaveMutex(); closeUnixFile(id); } return SQLITE_OK; } #endif /* OS_VXWORKS */ /* ** Named semaphore locking is only available on VxWorks. ** *************** End of the named semaphore lock implementation **************** ******************************************************************************/ /****************************************************************************** *************************** Begin AFP Locking ********************************* ** ** AFP is the Apple Filing Protocol. AFP is a network filesystem found ** on Apple Macintosh computers - both OS9 and OSX. ** ** Third-party implementations of AFP are available. But this code here ** only works on OSX. */ #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE /* ** The afpLockingContext structure contains all afp lock specific state */ typedef struct afpLockingContext afpLockingContext; struct afpLockingContext { int reserved; const char *dbPath; /* Name of the open file */ }; struct ByteRangeLockPB2 { unsigned long long offset; /* offset to first byte to lock */ unsigned long long length; /* nbr of bytes to lock */ unsigned long long retRangeStart; /* nbr of 1st byte locked if successful */ unsigned char unLockFlag; /* 1 = unlock, 0 = lock */ unsigned char startEndFlag; /* 1=rel to end of fork, 0=rel to start */ int fd; /* file desc to assoc this lock with */ }; #define afpfsByteRangeLock2FSCTL _IOWR('z', 23, struct ByteRangeLockPB2) /* ** This is a utility for setting or clearing a bit-range lock on an ** AFP filesystem. ** ** Return SQLITE_OK on success, SQLITE_BUSY on failure. */ static int afpSetLock( const char *path, /* Name of the file to be locked or unlocked */ unixFile *pFile, /* Open file descriptor on path */ unsigned long long offset, /* First byte to be locked */ unsigned long long length, /* Number of bytes to lock */ int setLockFlag /* True to set lock. False to clear lock */ ){ struct ByteRangeLockPB2 pb; int err; pb.unLockFlag = setLockFlag ? 0 : 1; pb.startEndFlag = 0; pb.offset = offset; pb.length = length; pb.fd = pFile->h; OSTRACE(("AFPSETLOCK [%s] for %d%s in range %llx:%llx\n", (setLockFlag?"ON":"OFF"), pFile->h, (pb.fd==-1?"[testval-1]":""), offset, length)); err = fsctl(path, afpfsByteRangeLock2FSCTL, &pb, 0); if ( err==-1 ) { int rc; int tErrno = errno; OSTRACE(("AFPSETLOCK failed to fsctl() '%s' %d %s\n", path, tErrno, strerror(tErrno))); #ifdef SQLITE_IGNORE_AFP_LOCK_ERRORS rc = SQLITE_BUSY; #else rc = sqliteErrorFromPosixError(tErrno, setLockFlag ? SQLITE_IOERR_LOCK : SQLITE_IOERR_UNLOCK); #endif /* SQLITE_IGNORE_AFP_LOCK_ERRORS */ if( IS_LOCK_ERROR(rc) ){ storeLastErrno(pFile, tErrno); } return rc; } else { return SQLITE_OK; } } /* ** This routine checks if there is a RESERVED lock held on the specified ** file by this or any other process. If such a lock is held, set *pResOut ** to a non-zero value otherwise *pResOut is set to zero. The return value ** is set to SQLITE_OK unless an I/O error occurs during lock checking. */ static int afpCheckReservedLock(sqlite3_file *id, int *pResOut){ int rc = SQLITE_OK; int reserved = 0; unixFile *pFile = (unixFile*)id; afpLockingContext *context; SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; ); assert( pFile ); context = (afpLockingContext *) pFile->lockingContext; if( context->reserved ){ *pResOut = 1; return SQLITE_OK; } unixEnterMutex(); /* Because pFile->pInode is shared across threads */ /* Check if a thread in this process holds such a lock */ if( pFile->pInode->eFileLock>SHARED_LOCK ){ reserved = 1; } /* Otherwise see if some other process holds it. */ if( !reserved ){ /* lock the RESERVED byte */ int lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1); if( SQLITE_OK==lrc ){ /* if we succeeded in taking the reserved lock, unlock it to restore ** the original state */ lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0); } else { /* if we failed to get the lock then someone else must have it */ reserved = 1; } if( IS_LOCK_ERROR(lrc) ){ rc=lrc; } } unixLeaveMutex(); OSTRACE(("TEST WR-LOCK %d %d %d (afp)\n", pFile->h, rc, reserved)); *pResOut = reserved; return rc; } /* ** Lock the file with the lock specified by parameter eFileLock - one ** of the following: ** ** (1) SHARED_LOCK ** (2) RESERVED_LOCK ** (3) PENDING_LOCK ** (4) EXCLUSIVE_LOCK ** ** Sometimes when requesting one lock state, additional lock states ** are inserted in between. The locking might fail on one of the later ** transitions leaving the lock state different from what it started but ** still short of its goal. The following chart shows the allowed ** transitions and the inserted intermediate states: ** ** UNLOCKED -> SHARED ** SHARED -> RESERVED ** SHARED -> (PENDING) -> EXCLUSIVE ** RESERVED -> (PENDING) -> EXCLUSIVE ** PENDING -> EXCLUSIVE ** ** This routine will only increase a lock. Use the sqlite3OsUnlock() ** routine to lower a locking level. */ static int afpLock(sqlite3_file *id, int eFileLock){ int rc = SQLITE_OK; unixFile *pFile = (unixFile*)id; unixInodeInfo *pInode = pFile->pInode; afpLockingContext *context = (afpLockingContext *) pFile->lockingContext; assert( pFile ); OSTRACE(("LOCK %d %s was %s(%s,%d) pid=%d (afp)\n", pFile->h, azFileLock(eFileLock), azFileLock(pFile->eFileLock), azFileLock(pInode->eFileLock), pInode->nShared , osGetpid(0))); /* If there is already a lock of this type or more restrictive on the ** unixFile, do nothing. Don't use the afp_end_lock: exit path, as ** unixEnterMutex() hasn't been called yet. */ if( pFile->eFileLock>=eFileLock ){ OSTRACE(("LOCK %d %s ok (already held) (afp)\n", pFile->h, azFileLock(eFileLock))); return SQLITE_OK; } /* Make sure the locking sequence is correct ** (1) We never move from unlocked to anything higher than shared lock. ** (2) SQLite never explicitly requests a pendig lock. ** (3) A shared lock is always held when a reserve lock is requested. */ assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK ); assert( eFileLock!=PENDING_LOCK ); assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK ); /* This mutex is needed because pFile->pInode is shared across threads */ unixEnterMutex(); pInode = pFile->pInode; /* If some thread using this PID has a lock via a different unixFile* ** handle that precludes the requested lock, return BUSY. */ if( (pFile->eFileLock!=pInode->eFileLock && (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK)) ){ rc = SQLITE_BUSY; goto afp_end_lock; } /* If a SHARED lock is requested, and some thread using this PID already ** has a SHARED or RESERVED lock, then increment reference counts and ** return SQLITE_OK. */ if( eFileLock==SHARED_LOCK && (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){ assert( eFileLock==SHARED_LOCK ); assert( pFile->eFileLock==0 ); assert( pInode->nShared>0 ); pFile->eFileLock = SHARED_LOCK; pInode->nShared++; pInode->nLock++; goto afp_end_lock; } /* A PENDING lock is needed before acquiring a SHARED lock and before ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will ** be released. */ if( eFileLock==SHARED_LOCK || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLockdbPath, pFile, PENDING_BYTE, 1, 1); if (failed) { rc = failed; goto afp_end_lock; } } /* If control gets to this point, then actually go ahead and make ** operating system calls for the specified lock. */ if( eFileLock==SHARED_LOCK ){ int lrc1, lrc2, lrc1Errno = 0; long lk, mask; assert( pInode->nShared==0 ); assert( pInode->eFileLock==0 ); mask = (sizeof(long)==8) ? LARGEST_INT64 : 0x7fffffff; /* Now get the read-lock SHARED_LOCK */ /* note that the quality of the randomness doesn't matter that much */ lk = random(); pInode->sharedByte = (lk & mask)%(SHARED_SIZE - 1); lrc1 = afpSetLock(context->dbPath, pFile, SHARED_FIRST+pInode->sharedByte, 1, 1); if( IS_LOCK_ERROR(lrc1) ){ lrc1Errno = pFile->lastErrno; } /* Drop the temporary PENDING lock */ lrc2 = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0); if( IS_LOCK_ERROR(lrc1) ) { storeLastErrno(pFile, lrc1Errno); rc = lrc1; goto afp_end_lock; } else if( IS_LOCK_ERROR(lrc2) ){ rc = lrc2; goto afp_end_lock; } else if( lrc1 != SQLITE_OK ) { rc = lrc1; } else { pFile->eFileLock = SHARED_LOCK; pInode->nLock++; pInode->nShared = 1; } }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){ /* We are trying for an exclusive lock but another thread in this ** same process is still holding a shared lock. */ rc = SQLITE_BUSY; }else{ /* The request was for a RESERVED or EXCLUSIVE lock. It is ** assumed that there is a SHARED or greater lock on the file ** already. */ int failed = 0; assert( 0!=pFile->eFileLock ); if (eFileLock >= RESERVED_LOCK && pFile->eFileLock < RESERVED_LOCK) { /* Acquire a RESERVED lock */ failed = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1); if( !failed ){ context->reserved = 1; } } if (!failed && eFileLock == EXCLUSIVE_LOCK) { /* Acquire an EXCLUSIVE lock */ /* Remove the shared lock before trying the range. we'll need to ** reestablish the shared lock if we can't get the afpUnlock */ if( !(failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST + pInode->sharedByte, 1, 0)) ){ int failed2 = SQLITE_OK; /* now attemmpt to get the exclusive lock range */ failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST, SHARED_SIZE, 1); if( failed && (failed2 = afpSetLock(context->dbPath, pFile, SHARED_FIRST + pInode->sharedByte, 1, 1)) ){ /* Can't reestablish the shared lock. Sqlite can't deal, this is ** a critical I/O error */ rc = ((failed & SQLITE_IOERR) == SQLITE_IOERR) ? failed2 : SQLITE_IOERR_LOCK; goto afp_end_lock; } }else{ rc = failed; } } if( failed ){ rc = failed; } } if( rc==SQLITE_OK ){ pFile->eFileLock = eFileLock; pInode->eFileLock = eFileLock; }else if( eFileLock==EXCLUSIVE_LOCK ){ pFile->eFileLock = PENDING_LOCK; pInode->eFileLock = PENDING_LOCK; } afp_end_lock: unixLeaveMutex(); OSTRACE(("LOCK %d %s %s (afp)\n", pFile->h, azFileLock(eFileLock), rc==SQLITE_OK ? "ok" : "failed")); return rc; } /* ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock ** must be either NO_LOCK or SHARED_LOCK. ** ** If the locking level of the file descriptor is already at or below ** the requested locking level, this routine is a no-op. */ static int afpUnlock(sqlite3_file *id, int eFileLock) { int rc = SQLITE_OK; unixFile *pFile = (unixFile*)id; unixInodeInfo *pInode; afpLockingContext *context = (afpLockingContext *) pFile->lockingContext; int skipShared = 0; #ifdef SQLITE_TEST int h = pFile->h; #endif assert( pFile ); OSTRACE(("UNLOCK %d %d was %d(%d,%d) pid=%d (afp)\n", pFile->h, eFileLock, pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared, osGetpid(0))); assert( eFileLock<=SHARED_LOCK ); if( pFile->eFileLock<=eFileLock ){ return SQLITE_OK; } unixEnterMutex(); pInode = pFile->pInode; assert( pInode->nShared!=0 ); if( pFile->eFileLock>SHARED_LOCK ){ assert( pInode->eFileLock==pFile->eFileLock ); SimulateIOErrorBenign(1); SimulateIOError( h=(-1) ) SimulateIOErrorBenign(0); #ifdef SQLITE_DEBUG /* When reducing a lock such that other processes can start ** reading the database file again, make sure that the ** transaction counter was updated if any part of the database ** file changed. If the transaction counter is not updated, ** other connections to the same file might not realize that ** the file has changed and hence might not know to flush their ** cache. The use of a stale cache can lead to database corruption. */ assert( pFile->inNormalWrite==0 || pFile->dbUpdate==0 || pFile->transCntrChng==1 ); pFile->inNormalWrite = 0; #endif if( pFile->eFileLock==EXCLUSIVE_LOCK ){ rc = afpSetLock(context->dbPath, pFile, SHARED_FIRST, SHARED_SIZE, 0); if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1) ){ /* only re-establish the shared lock if necessary */ int sharedLockByte = SHARED_FIRST+pInode->sharedByte; rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 1); } else { skipShared = 1; } } if( rc==SQLITE_OK && pFile->eFileLock>=PENDING_LOCK ){ rc = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0); } if( rc==SQLITE_OK && pFile->eFileLock>=RESERVED_LOCK && context->reserved ){ rc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0); if( !rc ){ context->reserved = 0; } } if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1)){ pInode->eFileLock = SHARED_LOCK; } } if( rc==SQLITE_OK && eFileLock==NO_LOCK ){ /* Decrement the shared lock counter. Release the lock using an ** OS call only when all threads in this same process have released ** the lock. */ unsigned long long sharedLockByte = SHARED_FIRST+pInode->sharedByte; pInode->nShared--; if( pInode->nShared==0 ){ SimulateIOErrorBenign(1); SimulateIOError( h=(-1) ) SimulateIOErrorBenign(0); if( !skipShared ){ rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 0); } if( !rc ){ pInode->eFileLock = NO_LOCK; pFile->eFileLock = NO_LOCK; } } if( rc==SQLITE_OK ){ pInode->nLock--; assert( pInode->nLock>=0 ); if( pInode->nLock==0 ){ closePendingFds(pFile); } } } unixLeaveMutex(); if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock; return rc; } /* ** Close a file & cleanup AFP specific locking context */ static int afpClose(sqlite3_file *id) { int rc = SQLITE_OK; unixFile *pFile = (unixFile*)id; assert( id!=0 ); afpUnlock(id, NO_LOCK); unixEnterMutex(); if( pFile->pInode && pFile->pInode->nLock ){ /* If there are outstanding locks, do not actually close the file just ** yet because that would clear those locks. Instead, add the file ** descriptor to pInode->aPending. It will be automatically closed when ** the last lock is cleared. */ setPendingFd(pFile); } releaseInodeInfo(pFile); sqlite3_free(pFile->lockingContext); rc = closeUnixFile(id); unixLeaveMutex(); return rc; } #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */ /* ** The code above is the AFP lock implementation. The code is specific ** to MacOSX and does not work on other unix platforms. No alternative ** is available. If you don't compile for a mac, then the "unix-afp" ** VFS is not available. ** ********************* End of the AFP lock implementation ********************** ******************************************************************************/ /****************************************************************************** *************************** Begin NFS Locking ********************************/ #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE /* ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock ** must be either NO_LOCK or SHARED_LOCK. ** ** If the locking level of the file descriptor is already at or below ** the requested locking level, this routine is a no-op. */ static int nfsUnlock(sqlite3_file *id, int eFileLock){ return posixUnlock(id, eFileLock, 1); } #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */ /* ** The code above is the NFS lock implementation. The code is specific ** to MacOSX and does not work on other unix platforms. No alternative ** is available. ** ********************* End of the NFS lock implementation ********************** ******************************************************************************/ /****************************************************************************** **************** Non-locking sqlite3_file methods ***************************** ** ** The next division contains implementations for all methods of the ** sqlite3_file object other than the locking methods. The locking ** methods were defined in divisions above (one locking method per ** division). Those methods that are common to all locking modes ** are gather together into this division. */ /* ** Seek to the offset passed as the second argument, then read cnt ** bytes into pBuf. Return the number of bytes actually read. ** ** NB: If you define USE_PREAD or USE_PREAD64, then it might also ** be necessary to define _XOPEN_SOURCE to be 500. This varies from ** one system to another. Since SQLite does not define USE_PREAD ** in any form by default, we will not attempt to define _XOPEN_SOURCE. ** See tickets #2741 and #2681. ** ** To avoid stomping the errno value on a failed read the lastErrno value ** is set before returning. */ static int seekAndRead(unixFile *id, sqlite3_int64 offset, void *pBuf, int cnt){ int got; int prior = 0; #if (!defined(USE_PREAD) && !defined(USE_PREAD64)) i64 newOffset; #endif TIMER_START; assert( cnt==(cnt&0x1ffff) ); assert( id->h>2 ); do{ #if defined(USE_PREAD) got = osPread(id->h, pBuf, cnt, offset); SimulateIOError( got = -1 ); #elif defined(USE_PREAD64) got = osPread64(id->h, pBuf, cnt, offset); SimulateIOError( got = -1 ); #else newOffset = lseek(id->h, offset, SEEK_SET); SimulateIOError( newOffset = -1 ); if( newOffset<0 ){ storeLastErrno((unixFile*)id, errno); return -1; } got = osRead(id->h, pBuf, cnt); #endif if( got==cnt ) break; if( got<0 ){ if( errno==EINTR ){ got = 1; continue; } prior = 0; storeLastErrno((unixFile*)id, errno); break; }else if( got>0 ){ cnt -= got; offset += got; prior += got; pBuf = (void*)(got + (char*)pBuf); } }while( got>0 ); TIMER_END; OSTRACE(("READ %-3d %5d %7lld %llu\n", id->h, got+prior, offset-prior, TIMER_ELAPSED)); return got+prior; } /* ** Read data from a file into a buffer. Return SQLITE_OK if all ** bytes were read successfully and SQLITE_IOERR if anything goes ** wrong. */ static int unixRead( sqlite3_file *id, void *pBuf, int amt, sqlite3_int64 offset ){ unixFile *pFile = (unixFile *)id; int got; assert( id ); assert( offset>=0 ); assert( amt>0 ); /* If this is a database file (not a journal, master-journal or temp ** file), the bytes in the locking range should never be read or written. */ #if 0 assert( pFile->pUnused==0 || offset>=PENDING_BYTE+512 || offset+amt<=PENDING_BYTE ); #endif #if SQLITE_MAX_MMAP_SIZE>0 /* Deal with as much of this read request as possible by transfering ** data from the memory mapping using memcpy(). */ if( offsetmmapSize ){ if( offset+amt <= pFile->mmapSize ){ memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], amt); return SQLITE_OK; }else{ int nCopy = pFile->mmapSize - offset; memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], nCopy); pBuf = &((u8 *)pBuf)[nCopy]; amt -= nCopy; offset += nCopy; } } #endif got = seekAndRead(pFile, offset, pBuf, amt); if( got==amt ){ return SQLITE_OK; }else if( got<0 ){ /* lastErrno set by seekAndRead */ return SQLITE_IOERR_READ; }else{ storeLastErrno(pFile, 0); /* not a system error */ /* Unread parts of the buffer must be zero-filled */ memset(&((char*)pBuf)[got], 0, amt-got); return SQLITE_IOERR_SHORT_READ; } } /* ** Attempt to seek the file-descriptor passed as the first argument to ** absolute offset iOff, then attempt to write nBuf bytes of data from ** pBuf to it. If an error occurs, return -1 and set *piErrno. Otherwise, ** return the actual number of bytes written (which may be less than ** nBuf). */ static int seekAndWriteFd( int fd, /* File descriptor to write to */ i64 iOff, /* File offset to begin writing at */ const void *pBuf, /* Copy data from this buffer to the file */ int nBuf, /* Size of buffer pBuf in bytes */ int *piErrno /* OUT: Error number if error occurs */ ){ int rc = 0; /* Value returned by system call */ assert( nBuf==(nBuf&0x1ffff) ); assert( fd>2 ); assert( piErrno!=0 ); nBuf &= 0x1ffff; TIMER_START; #if defined(USE_PREAD) do{ rc = (int)osPwrite(fd, pBuf, nBuf, iOff); }while( rc<0 && errno==EINTR ); #elif defined(USE_PREAD64) do{ rc = (int)osPwrite64(fd, pBuf, nBuf, iOff);}while( rc<0 && errno==EINTR); #else do{ i64 iSeek = lseek(fd, iOff, SEEK_SET); SimulateIOError( iSeek = -1 ); if( iSeek<0 ){ rc = -1; break; } rc = osWrite(fd, pBuf, nBuf); }while( rc<0 && errno==EINTR ); #endif TIMER_END; OSTRACE(("WRITE %-3d %5d %7lld %llu\n", fd, rc, iOff, TIMER_ELAPSED)); if( rc<0 ) *piErrno = errno; return rc; } /* ** Seek to the offset in id->offset then read cnt bytes into pBuf. ** Return the number of bytes actually read. Update the offset. ** ** To avoid stomping the errno value on a failed write the lastErrno value ** is set before returning. */ static int seekAndWrite(unixFile *id, i64 offset, const void *pBuf, int cnt){ return seekAndWriteFd(id->h, offset, pBuf, cnt, &id->lastErrno); } /* ** Write data from a buffer into a file. Return SQLITE_OK on success ** or some other error code on failure. */ static int unixWrite( sqlite3_file *id, const void *pBuf, int amt, sqlite3_int64 offset ){ unixFile *pFile = (unixFile*)id; int wrote = 0; assert( id ); assert( amt>0 ); /* If this is a database file (not a journal, master-journal or temp ** file), the bytes in the locking range should never be read or written. */ #if 0 assert( pFile->pUnused==0 || offset>=PENDING_BYTE+512 || offset+amt<=PENDING_BYTE ); #endif #ifdef SQLITE_DEBUG /* If we are doing a normal write to a database file (as opposed to ** doing a hot-journal rollback or a write to some file other than a ** normal database file) then record the fact that the database ** has changed. If the transaction counter is modified, record that ** fact too. */ if( pFile->inNormalWrite ){ pFile->dbUpdate = 1; /* The database has been modified */ if( offset<=24 && offset+amt>=27 ){ int rc; char oldCntr[4]; SimulateIOErrorBenign(1); rc = seekAndRead(pFile, 24, oldCntr, 4); SimulateIOErrorBenign(0); if( rc!=4 || memcmp(oldCntr, &((char*)pBuf)[24-offset], 4)!=0 ){ pFile->transCntrChng = 1; /* The transaction counter has changed */ } } } #endif #if defined(SQLITE_MMAP_READWRITE) && SQLITE_MAX_MMAP_SIZE>0 /* Deal with as much of this write request as possible by transfering ** data from the memory mapping using memcpy(). */ if( offsetmmapSize ){ if( offset+amt <= pFile->mmapSize ){ memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, amt); return SQLITE_OK; }else{ int nCopy = pFile->mmapSize - offset; memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, nCopy); pBuf = &((u8 *)pBuf)[nCopy]; amt -= nCopy; offset += nCopy; } } #endif while( (wrote = seekAndWrite(pFile, offset, pBuf, amt))0 ){ amt -= wrote; offset += wrote; pBuf = &((char*)pBuf)[wrote]; } SimulateIOError(( wrote=(-1), amt=1 )); SimulateDiskfullError(( wrote=0, amt=1 )); if( amt>wrote ){ if( wrote<0 && pFile->lastErrno!=ENOSPC ){ /* lastErrno set by seekAndWrite */ return SQLITE_IOERR_WRITE; }else{ storeLastErrno(pFile, 0); /* not a system error */ return SQLITE_FULL; } } return SQLITE_OK; } #ifdef SQLITE_TEST /* ** Count the number of fullsyncs and normal syncs. This is used to test ** that syncs and fullsyncs are occurring at the right times. */ SQLITE_API int sqlite3_sync_count = 0; SQLITE_API int sqlite3_fullsync_count = 0; #endif /* ** We do not trust systems to provide a working fdatasync(). Some do. ** Others do no. To be safe, we will stick with the (slightly slower) ** fsync(). If you know that your system does support fdatasync() correctly, ** then simply compile with -Dfdatasync=fdatasync or -DHAVE_FDATASYNC */ #if !defined(fdatasync) && !HAVE_FDATASYNC # define fdatasync fsync #endif /* ** Define HAVE_FULLFSYNC to 0 or 1 depending on whether or not ** the F_FULLFSYNC macro is defined. F_FULLFSYNC is currently ** only available on Mac OS X. But that could change. */ #ifdef F_FULLFSYNC # define HAVE_FULLFSYNC 1 #else # define HAVE_FULLFSYNC 0 #endif /* ** The fsync() system call does not work as advertised on many ** unix systems. The following procedure is an attempt to make ** it work better. ** ** The SQLITE_NO_SYNC macro disables all fsync()s. This is useful ** for testing when we want to run through the test suite quickly. ** You are strongly advised *not* to deploy with SQLITE_NO_SYNC ** enabled, however, since with SQLITE_NO_SYNC enabled, an OS crash ** or power failure will likely corrupt the database file. ** ** SQLite sets the dataOnly flag if the size of the file is unchanged. ** The idea behind dataOnly is that it should only write the file content ** to disk, not the inode. We only set dataOnly if the file size is ** unchanged since the file size is part of the inode. However, ** Ted Ts'o tells us that fdatasync() will also write the inode if the ** file size has changed. The only real difference between fdatasync() ** and fsync(), Ted tells us, is that fdatasync() will not flush the ** inode if the mtime or owner or other inode attributes have changed. ** We only care about the file size, not the other file attributes, so ** as far as SQLite is concerned, an fdatasync() is always adequate. ** So, we always use fdatasync() if it is available, regardless of ** the value of the dataOnly flag. */ static int full_fsync(int fd, int fullSync, int dataOnly){ int rc; /* The following "ifdef/elif/else/" block has the same structure as ** the one below. It is replicated here solely to avoid cluttering ** up the real code with the UNUSED_PARAMETER() macros. */ #ifdef SQLITE_NO_SYNC UNUSED_PARAMETER(fd); UNUSED_PARAMETER(fullSync); UNUSED_PARAMETER(dataOnly); #elif HAVE_FULLFSYNC UNUSED_PARAMETER(dataOnly); #else UNUSED_PARAMETER(fullSync); UNUSED_PARAMETER(dataOnly); #endif /* Record the number of times that we do a normal fsync() and ** FULLSYNC. This is used during testing to verify that this procedure ** gets called with the correct arguments. */ #ifdef SQLITE_TEST if( fullSync ) sqlite3_fullsync_count++; sqlite3_sync_count++; #endif /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a ** no-op. But go ahead and call fstat() to validate the file ** descriptor as we need a method to provoke a failure during ** coverate testing. */ #ifdef SQLITE_NO_SYNC { struct stat buf; rc = osFstat(fd, &buf); } #elif HAVE_FULLFSYNC if( fullSync ){ rc = osFcntl(fd, F_FULLFSYNC, 0); }else{ rc = 1; } /* If the FULLFSYNC failed, fall back to attempting an fsync(). ** It shouldn't be possible for fullfsync to fail on the local ** file system (on OSX), so failure indicates that FULLFSYNC ** isn't supported for this file system. So, attempt an fsync ** and (for now) ignore the overhead of a superfluous fcntl call. ** It'd be better to detect fullfsync support once and avoid ** the fcntl call every time sync is called. */ if( rc ) rc = fsync(fd); #elif defined(__APPLE__) /* fdatasync() on HFS+ doesn't yet flush the file size if it changed correctly ** so currently we default to the macro that redefines fdatasync to fsync */ rc = fsync(fd); #else rc = fdatasync(fd); #if OS_VXWORKS if( rc==-1 && errno==ENOTSUP ){ rc = fsync(fd); } #endif /* OS_VXWORKS */ #endif /* ifdef SQLITE_NO_SYNC elif HAVE_FULLFSYNC */ if( OS_VXWORKS && rc!= -1 ){ rc = 0; } return rc; } /* ** Open a file descriptor to the directory containing file zFilename. ** If successful, *pFd is set to the opened file descriptor and ** SQLITE_OK is returned. If an error occurs, either SQLITE_NOMEM ** or SQLITE_CANTOPEN is returned and *pFd is set to an undefined ** value. ** ** The directory file descriptor is used for only one thing - to ** fsync() a directory to make sure file creation and deletion events ** are flushed to disk. Such fsyncs are not needed on newer ** journaling filesystems, but are required on older filesystems. ** ** This routine can be overridden using the xSetSysCall interface. ** The ability to override this routine was added in support of the ** chromium sandbox. Opening a directory is a security risk (we are ** told) so making it overrideable allows the chromium sandbox to ** replace this routine with a harmless no-op. To make this routine ** a no-op, replace it with a stub that returns SQLITE_OK but leaves ** *pFd set to a negative number. ** ** If SQLITE_OK is returned, the caller is responsible for closing ** the file descriptor *pFd using close(). */ static int openDirectory(const char *zFilename, int *pFd){ int ii; int fd = -1; char zDirname[MAX_PATHNAME+1]; sqlite3_snprintf(MAX_PATHNAME, zDirname, "%s", zFilename); for(ii=(int)strlen(zDirname); ii>0 && zDirname[ii]!='/'; ii--); if( ii>0 ){ zDirname[ii] = '\0'; }else{ if( zDirname[0]!='/' ) zDirname[0] = '.'; zDirname[1] = 0; } fd = robust_open(zDirname, O_RDONLY|O_BINARY, 0); if( fd>=0 ){ OSTRACE(("OPENDIR %-3d %s\n", fd, zDirname)); } *pFd = fd; if( fd>=0 ) return SQLITE_OK; return unixLogError(SQLITE_CANTOPEN_BKPT, "openDirectory", zDirname); } /* ** Make sure all writes to a particular file are committed to disk. ** ** If dataOnly==0 then both the file itself and its metadata (file ** size, access time, etc) are synced. If dataOnly!=0 then only the ** file data is synced. ** ** Under Unix, also make sure that the directory entry for the file ** has been created by fsync-ing the directory that contains the file. ** If we do not do this and we encounter a power failure, the directory ** entry for the journal might not exist after we reboot. The next ** SQLite to access the file will not know that the journal exists (because ** the directory entry for the journal was never created) and the transaction ** will not roll back - possibly leading to database corruption. */ static int unixSync(sqlite3_file *id, int flags){ int rc; unixFile *pFile = (unixFile*)id; int isDataOnly = (flags&SQLITE_SYNC_DATAONLY); int isFullsync = (flags&0x0F)==SQLITE_SYNC_FULL; /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */ assert((flags&0x0F)==SQLITE_SYNC_NORMAL || (flags&0x0F)==SQLITE_SYNC_FULL ); /* Unix cannot, but some systems may return SQLITE_FULL from here. This ** line is to test that doing so does not cause any problems. */ SimulateDiskfullError( return SQLITE_FULL ); assert( pFile ); OSTRACE(("SYNC %-3d\n", pFile->h)); rc = full_fsync(pFile->h, isFullsync, isDataOnly); SimulateIOError( rc=1 ); if( rc ){ storeLastErrno(pFile, errno); return unixLogError(SQLITE_IOERR_FSYNC, "full_fsync", pFile->zPath); } /* Also fsync the directory containing the file if the DIRSYNC flag ** is set. This is a one-time occurrence. Many systems (examples: AIX) ** are unable to fsync a directory, so ignore errors on the fsync. */ if( pFile->ctrlFlags & UNIXFILE_DIRSYNC ){ int dirfd; OSTRACE(("DIRSYNC %s (have_fullfsync=%d fullsync=%d)\n", pFile->zPath, HAVE_FULLFSYNC, isFullsync)); rc = osOpenDirectory(pFile->zPath, &dirfd); if( rc==SQLITE_OK ){ full_fsync(dirfd, 0, 0); robust_close(pFile, dirfd, __LINE__); }else{ assert( rc==SQLITE_CANTOPEN ); rc = SQLITE_OK; } pFile->ctrlFlags &= ~UNIXFILE_DIRSYNC; } return rc; } /* ** Truncate an open file to a specified size */ static int unixTruncate(sqlite3_file *id, i64 nByte){ unixFile *pFile = (unixFile *)id; int rc; assert( pFile ); SimulateIOError( return SQLITE_IOERR_TRUNCATE ); /* If the user has configured a chunk-size for this file, truncate the ** file so that it consists of an integer number of chunks (i.e. the ** actual file size after the operation may be larger than the requested ** size). */ if( pFile->szChunk>0 ){ nByte = ((nByte + pFile->szChunk - 1)/pFile->szChunk) * pFile->szChunk; } rc = robust_ftruncate(pFile->h, nByte); if( rc ){ storeLastErrno(pFile, errno); return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath); }else{ #ifdef SQLITE_DEBUG /* If we are doing a normal write to a database file (as opposed to ** doing a hot-journal rollback or a write to some file other than a ** normal database file) and we truncate the file to zero length, ** that effectively updates the change counter. This might happen ** when restoring a database using the backup API from a zero-length ** source. */ if( pFile->inNormalWrite && nByte==0 ){ pFile->transCntrChng = 1; } #endif #if SQLITE_MAX_MMAP_SIZE>0 /* If the file was just truncated to a size smaller than the currently ** mapped region, reduce the effective mapping size as well. SQLite will ** use read() and write() to access data beyond this point from now on. */ if( nBytemmapSize ){ pFile->mmapSize = nByte; } #endif return SQLITE_OK; } } /* ** Determine the current size of a file in bytes */ static int unixFileSize(sqlite3_file *id, i64 *pSize){ int rc; struct stat buf; assert( id ); rc = osFstat(((unixFile*)id)->h, &buf); SimulateIOError( rc=1 ); if( rc!=0 ){ storeLastErrno((unixFile*)id, errno); return SQLITE_IOERR_FSTAT; } *pSize = buf.st_size; /* When opening a zero-size database, the findInodeInfo() procedure ** writes a single byte into that file in order to work around a bug ** in the OS-X msdos filesystem. In order to avoid problems with upper ** layers, we need to report this file size as zero even though it is ** really 1. Ticket #3260. */ if( *pSize==1 ) *pSize = 0; return SQLITE_OK; } #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__) /* ** Handler for proxy-locking file-control verbs. Defined below in the ** proxying locking division. */ static int proxyFileControl(sqlite3_file*,int,void*); #endif /* ** This function is called to handle the SQLITE_FCNTL_SIZE_HINT ** file-control operation. Enlarge the database to nBytes in size ** (rounded up to the next chunk-size). If the database is already ** nBytes or larger, this routine is a no-op. */ static int fcntlSizeHint(unixFile *pFile, i64 nByte){ if( pFile->szChunk>0 ){ i64 nSize; /* Required file size */ struct stat buf; /* Used to hold return values of fstat() */ if( osFstat(pFile->h, &buf) ){ return SQLITE_IOERR_FSTAT; } nSize = ((nByte+pFile->szChunk-1) / pFile->szChunk) * pFile->szChunk; if( nSize>(i64)buf.st_size ){ #if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE /* The code below is handling the return value of osFallocate() ** correctly. posix_fallocate() is defined to "returns zero on success, ** or an error number on failure". See the manpage for details. */ int err; do{ err = osFallocate(pFile->h, buf.st_size, nSize-buf.st_size); }while( err==EINTR ); if( err ) return SQLITE_IOERR_WRITE; #else /* If the OS does not have posix_fallocate(), fake it. Write a ** single byte to the last byte in each block that falls entirely ** within the extended region. Then, if required, a single byte ** at offset (nSize-1), to set the size of the file correctly. ** This is a similar technique to that used by glibc on systems ** that do not have a real fallocate() call. */ int nBlk = buf.st_blksize; /* File-system block size */ int nWrite = 0; /* Number of bytes written by seekAndWrite */ i64 iWrite; /* Next offset to write to */ iWrite = (buf.st_size/nBlk)*nBlk + nBlk - 1; assert( iWrite>=buf.st_size ); assert( ((iWrite+1)%nBlk)==0 ); for(/*no-op*/; iWrite=nSize ) iWrite = nSize - 1; nWrite = seekAndWrite(pFile, iWrite, "", 1); if( nWrite!=1 ) return SQLITE_IOERR_WRITE; } #endif } } #if SQLITE_MAX_MMAP_SIZE>0 if( pFile->mmapSizeMax>0 && nByte>pFile->mmapSize ){ int rc; if( pFile->szChunk<=0 ){ if( robust_ftruncate(pFile->h, nByte) ){ storeLastErrno(pFile, errno); return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath); } } rc = unixMapfile(pFile, nByte); return rc; } #endif return SQLITE_OK; } /* ** If *pArg is initially negative then this is a query. Set *pArg to ** 1 or 0 depending on whether or not bit mask of pFile->ctrlFlags is set. ** ** If *pArg is 0 or 1, then clear or set the mask bit of pFile->ctrlFlags. */ static void unixModeBit(unixFile *pFile, unsigned char mask, int *pArg){ if( *pArg<0 ){ *pArg = (pFile->ctrlFlags & mask)!=0; }else if( (*pArg)==0 ){ pFile->ctrlFlags &= ~mask; }else{ pFile->ctrlFlags |= mask; } } /* Forward declaration */ static int unixGetTempname(int nBuf, char *zBuf); /* ** Information and control of an open file handle. */ static int unixFileControl(sqlite3_file *id, int op, void *pArg){ unixFile *pFile = (unixFile*)id; switch( op ){ case SQLITE_FCNTL_LOCKSTATE: { *(int*)pArg = pFile->eFileLock; return SQLITE_OK; } case SQLITE_FCNTL_LAST_ERRNO: { *(int*)pArg = pFile->lastErrno; return SQLITE_OK; } case SQLITE_FCNTL_CHUNK_SIZE: { pFile->szChunk = *(int *)pArg; return SQLITE_OK; } case SQLITE_FCNTL_SIZE_HINT: { int rc; SimulateIOErrorBenign(1); rc = fcntlSizeHint(pFile, *(i64 *)pArg); SimulateIOErrorBenign(0); return rc; } case SQLITE_FCNTL_PERSIST_WAL: { unixModeBit(pFile, UNIXFILE_PERSIST_WAL, (int*)pArg); return SQLITE_OK; } case SQLITE_FCNTL_POWERSAFE_OVERWRITE: { unixModeBit(pFile, UNIXFILE_PSOW, (int*)pArg); return SQLITE_OK; } case SQLITE_FCNTL_VFSNAME: { *(char**)pArg = sqlite3_mprintf("%s", pFile->pVfs->zName); return SQLITE_OK; } case SQLITE_FCNTL_TEMPFILENAME: { char *zTFile = sqlite3_malloc64( pFile->pVfs->mxPathname ); if( zTFile ){ unixGetTempname(pFile->pVfs->mxPathname, zTFile); *(char**)pArg = zTFile; } return SQLITE_OK; } case SQLITE_FCNTL_HAS_MOVED: { *(int*)pArg = fileHasMoved(pFile); return SQLITE_OK; } #if SQLITE_MAX_MMAP_SIZE>0 case SQLITE_FCNTL_MMAP_SIZE: { i64 newLimit = *(i64*)pArg; int rc = SQLITE_OK; if( newLimit>sqlite3GlobalConfig.mxMmap ){ newLimit = sqlite3GlobalConfig.mxMmap; } *(i64*)pArg = pFile->mmapSizeMax; if( newLimit>=0 && newLimit!=pFile->mmapSizeMax && pFile->nFetchOut==0 ){ pFile->mmapSizeMax = newLimit; if( pFile->mmapSize>0 ){ unixUnmapfile(pFile); rc = unixMapfile(pFile, -1); } } return rc; } #endif #ifdef SQLITE_DEBUG /* The pager calls this method to signal that it has done ** a rollback and that the database is therefore unchanged and ** it hence it is OK for the transaction change counter to be ** unchanged. */ case SQLITE_FCNTL_DB_UNCHANGED: { ((unixFile*)id)->dbUpdate = 0; return SQLITE_OK; } #endif #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__) case SQLITE_FCNTL_SET_LOCKPROXYFILE: case SQLITE_FCNTL_GET_LOCKPROXYFILE: { return proxyFileControl(id,op,pArg); } #endif /* SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__) */ } return SQLITE_NOTFOUND; } /* ** Return the sector size in bytes of the underlying block device for ** the specified file. This is almost always 512 bytes, but may be ** larger for some devices. ** ** SQLite code assumes this function cannot fail. It also assumes that ** if two files are created in the same file-system directory (i.e. ** a database and its journal file) that the sector size will be the ** same for both. */ #ifndef __QNXNTO__ static int unixSectorSize(sqlite3_file *NotUsed){ UNUSED_PARAMETER(NotUsed); return SQLITE_DEFAULT_SECTOR_SIZE; } #endif /* ** The following version of unixSectorSize() is optimized for QNX. */ #ifdef __QNXNTO__ #include #include static int unixSectorSize(sqlite3_file *id){ unixFile *pFile = (unixFile*)id; if( pFile->sectorSize == 0 ){ struct statvfs fsInfo; /* Set defaults for non-supported filesystems */ pFile->sectorSize = SQLITE_DEFAULT_SECTOR_SIZE; pFile->deviceCharacteristics = 0; if( fstatvfs(pFile->h, &fsInfo) == -1 ) { return pFile->sectorSize; } if( !strcmp(fsInfo.f_basetype, "tmp") ) { pFile->sectorSize = fsInfo.f_bsize; pFile->deviceCharacteristics = SQLITE_IOCAP_ATOMIC4K | /* All ram filesystem writes are atomic */ SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until ** the write succeeds */ SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind ** so it is ordered */ 0; }else if( strstr(fsInfo.f_basetype, "etfs") ){ pFile->sectorSize = fsInfo.f_bsize; pFile->deviceCharacteristics = /* etfs cluster size writes are atomic */ (pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) | SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until ** the write succeeds */ SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind ** so it is ordered */ 0; }else if( !strcmp(fsInfo.f_basetype, "qnx6") ){ pFile->sectorSize = fsInfo.f_bsize; pFile->deviceCharacteristics = SQLITE_IOCAP_ATOMIC | /* All filesystem writes are atomic */ SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until ** the write succeeds */ SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind ** so it is ordered */ 0; }else if( !strcmp(fsInfo.f_basetype, "qnx4") ){ pFile->sectorSize = fsInfo.f_bsize; pFile->deviceCharacteristics = /* full bitset of atomics from max sector size and smaller */ ((pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) << 1) - 2 | SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind ** so it is ordered */ 0; }else if( strstr(fsInfo.f_basetype, "dos") ){ pFile->sectorSize = fsInfo.f_bsize; pFile->deviceCharacteristics = /* full bitset of atomics from max sector size and smaller */ ((pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) << 1) - 2 | SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind ** so it is ordered */ 0; }else{ pFile->deviceCharacteristics = SQLITE_IOCAP_ATOMIC512 | /* blocks are atomic */ SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until ** the write succeeds */ 0; } } /* Last chance verification. If the sector size isn't a multiple of 512 ** then it isn't valid.*/ if( pFile->sectorSize % 512 != 0 ){ pFile->deviceCharacteristics = 0; pFile->sectorSize = SQLITE_DEFAULT_SECTOR_SIZE; } return pFile->sectorSize; } #endif /* __QNXNTO__ */ /* ** Return the device characteristics for the file. ** ** This VFS is set up to return SQLITE_IOCAP_POWERSAFE_OVERWRITE by default. ** However, that choice is controversial since technically the underlying ** file system does not always provide powersafe overwrites. (In other ** words, after a power-loss event, parts of the file that were never ** written might end up being altered.) However, non-PSOW behavior is very, ** very rare. And asserting PSOW makes a large reduction in the amount ** of required I/O for journaling, since a lot of padding is eliminated. ** Hence, while POWERSAFE_OVERWRITE is on by default, there is a file-control ** available to turn it off and URI query parameter available to turn it off. */ static int unixDeviceCharacteristics(sqlite3_file *id){ unixFile *p = (unixFile*)id; int rc = 0; #ifdef __QNXNTO__ if( p->sectorSize==0 ) unixSectorSize(id); rc = p->deviceCharacteristics; #endif if( p->ctrlFlags & UNIXFILE_PSOW ){ rc |= SQLITE_IOCAP_POWERSAFE_OVERWRITE; } return rc; } #if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0 /* ** Return the system page size. ** ** This function should not be called directly by other code in this file. ** Instead, it should be called via macro osGetpagesize(). */ static int unixGetpagesize(void){ #if OS_VXWORKS return 1024; #elif defined(_BSD_SOURCE) return getpagesize(); #else return (int)sysconf(_SC_PAGESIZE); #endif } #endif /* !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0 */ #ifndef SQLITE_OMIT_WAL /* ** Object used to represent an shared memory buffer. ** ** When multiple threads all reference the same wal-index, each thread ** has its own unixShm object, but they all point to a single instance ** of this unixShmNode object. In other words, each wal-index is opened ** only once per process. ** ** Each unixShmNode object is connected to a single unixInodeInfo object. ** We could coalesce this object into unixInodeInfo, but that would mean ** every open file that does not use shared memory (in other words, most ** open files) would have to carry around this extra information. So ** the unixInodeInfo object contains a pointer to this unixShmNode object ** and the unixShmNode object is created only when needed. ** ** unixMutexHeld() must be true when creating or destroying ** this object or while reading or writing the following fields: ** ** nRef ** ** The following fields are read-only after the object is created: ** ** fid ** zFilename ** ** Either unixShmNode.mutex must be held or unixShmNode.nRef==0 and ** unixMutexHeld() is true when reading or writing any other field ** in this structure. */ struct unixShmNode { unixInodeInfo *pInode; /* unixInodeInfo that owns this SHM node */ sqlite3_mutex *mutex; /* Mutex to access this object */ char *zFilename; /* Name of the mmapped file */ int h; /* Open file descriptor */ int szRegion; /* Size of shared-memory regions */ u16 nRegion; /* Size of array apRegion */ u8 isReadonly; /* True if read-only */ char **apRegion; /* Array of mapped shared-memory regions */ int nRef; /* Number of unixShm objects pointing to this */ unixShm *pFirst; /* All unixShm objects pointing to this */ #ifdef SQLITE_DEBUG u8 exclMask; /* Mask of exclusive locks held */ u8 sharedMask; /* Mask of shared locks held */ u8 nextShmId; /* Next available unixShm.id value */ #endif }; /* ** Structure used internally by this VFS to record the state of an ** open shared memory connection. ** ** The following fields are initialized when this object is created and ** are read-only thereafter: ** ** unixShm.pFile ** unixShm.id ** ** All other fields are read/write. The unixShm.pFile->mutex must be held ** while accessing any read/write fields. */ struct unixShm { unixShmNode *pShmNode; /* The underlying unixShmNode object */ unixShm *pNext; /* Next unixShm with the same unixShmNode */ u8 hasMutex; /* True if holding the unixShmNode mutex */ u8 id; /* Id of this connection within its unixShmNode */ u16 sharedMask; /* Mask of shared locks held */ u16 exclMask; /* Mask of exclusive locks held */ }; /* ** Constants used for locking */ #define UNIX_SHM_BASE ((22+SQLITE_SHM_NLOCK)*4) /* first lock byte */ #define UNIX_SHM_DMS (UNIX_SHM_BASE+SQLITE_SHM_NLOCK) /* deadman switch */ /* ** Apply posix advisory locks for all bytes from ofst through ofst+n-1. ** ** Locks block if the mask is exactly UNIX_SHM_C and are non-blocking ** otherwise. */ static int unixShmSystemLock( unixFile *pFile, /* Open connection to the WAL file */ int lockType, /* F_UNLCK, F_RDLCK, or F_WRLCK */ int ofst, /* First byte of the locking range */ int n /* Number of bytes to lock */ ){ unixShmNode *pShmNode; /* Apply locks to this open shared-memory segment */ struct flock f; /* The posix advisory locking structure */ int rc = SQLITE_OK; /* Result code form fcntl() */ /* Access to the unixShmNode object is serialized by the caller */ pShmNode = pFile->pInode->pShmNode; assert( sqlite3_mutex_held(pShmNode->mutex) || pShmNode->nRef==0 ); /* Shared locks never span more than one byte */ assert( n==1 || lockType!=F_RDLCK ); /* Locks are within range */ assert( n>=1 && n<=SQLITE_SHM_NLOCK ); if( pShmNode->h>=0 ){ /* Initialize the locking parameters */ memset(&f, 0, sizeof(f)); f.l_type = lockType; f.l_whence = SEEK_SET; f.l_start = ofst; f.l_len = n; rc = osFcntl(pShmNode->h, F_SETLK, &f); rc = (rc!=(-1)) ? SQLITE_OK : SQLITE_BUSY; } /* Update the global lock state and do debug tracing */ #ifdef SQLITE_DEBUG { u16 mask; OSTRACE(("SHM-LOCK ")); mask = ofst>31 ? 0xffff : (1<<(ofst+n)) - (1<exclMask &= ~mask; pShmNode->sharedMask &= ~mask; }else if( lockType==F_RDLCK ){ OSTRACE(("read-lock %d ok", ofst)); pShmNode->exclMask &= ~mask; pShmNode->sharedMask |= mask; }else{ assert( lockType==F_WRLCK ); OSTRACE(("write-lock %d ok", ofst)); pShmNode->exclMask |= mask; pShmNode->sharedMask &= ~mask; } }else{ if( lockType==F_UNLCK ){ OSTRACE(("unlock %d failed", ofst)); }else if( lockType==F_RDLCK ){ OSTRACE(("read-lock failed")); }else{ assert( lockType==F_WRLCK ); OSTRACE(("write-lock %d failed", ofst)); } } OSTRACE((" - afterwards %03x,%03x\n", pShmNode->sharedMask, pShmNode->exclMask)); } #endif return rc; } /* ** Return the minimum number of 32KB shm regions that should be mapped at ** a time, assuming that each mapping must be an integer multiple of the ** current system page-size. ** ** Usually, this is 1. The exception seems to be systems that are configured ** to use 64KB pages - in this case each mapping must cover at least two ** shm regions. */ static int unixShmRegionPerMap(void){ int shmsz = 32*1024; /* SHM region size */ int pgsz = osGetpagesize(); /* System page size */ assert( ((pgsz-1)&pgsz)==0 ); /* Page size must be a power of 2 */ if( pgszpInode->pShmNode; assert( unixMutexHeld() ); if( p && ALWAYS(p->nRef==0) ){ int nShmPerMap = unixShmRegionPerMap(); int i; assert( p->pInode==pFd->pInode ); sqlite3_mutex_free(p->mutex); for(i=0; inRegion; i+=nShmPerMap){ if( p->h>=0 ){ osMunmap(p->apRegion[i], p->szRegion); }else{ sqlite3_free(p->apRegion[i]); } } sqlite3_free(p->apRegion); if( p->h>=0 ){ robust_close(pFd, p->h, __LINE__); p->h = -1; } p->pInode->pShmNode = 0; sqlite3_free(p); } } /* ** Open a shared-memory area associated with open database file pDbFd. ** This particular implementation uses mmapped files. ** ** The file used to implement shared-memory is in the same directory ** as the open database file and has the same name as the open database ** file with the "-shm" suffix added. For example, if the database file ** is "/home/user1/config.db" then the file that is created and mmapped ** for shared memory will be called "/home/user1/config.db-shm". ** ** Another approach to is to use files in /dev/shm or /dev/tmp or an ** some other tmpfs mount. But if a file in a different directory ** from the database file is used, then differing access permissions ** or a chroot() might cause two different processes on the same ** database to end up using different files for shared memory - ** meaning that their memory would not really be shared - resulting ** in database corruption. Nevertheless, this tmpfs file usage ** can be enabled at compile-time using -DSQLITE_SHM_DIRECTORY="/dev/shm" ** or the equivalent. The use of the SQLITE_SHM_DIRECTORY compile-time ** option results in an incompatible build of SQLite; builds of SQLite ** that with differing SQLITE_SHM_DIRECTORY settings attempt to use the ** same database file at the same time, database corruption will likely ** result. The SQLITE_SHM_DIRECTORY compile-time option is considered ** "unsupported" and may go away in a future SQLite release. ** ** When opening a new shared-memory file, if no other instances of that ** file are currently open, in this process or in other processes, then ** the file must be truncated to zero length or have its header cleared. ** ** If the original database file (pDbFd) is using the "unix-excl" VFS ** that means that an exclusive lock is held on the database file and ** that no other processes are able to read or write the database. In ** that case, we do not really need shared memory. No shared memory ** file is created. The shared memory will be simulated with heap memory. */ static int unixOpenSharedMemory(unixFile *pDbFd){ struct unixShm *p = 0; /* The connection to be opened */ struct unixShmNode *pShmNode; /* The underlying mmapped file */ int rc; /* Result code */ unixInodeInfo *pInode; /* The inode of fd */ char *zShmFilename; /* Name of the file used for SHM */ int nShmFilename; /* Size of the SHM filename in bytes */ /* Allocate space for the new unixShm object. */ p = sqlite3_malloc64( sizeof(*p) ); if( p==0 ) return SQLITE_NOMEM_BKPT; memset(p, 0, sizeof(*p)); assert( pDbFd->pShm==0 ); /* Check to see if a unixShmNode object already exists. Reuse an existing ** one if present. Create a new one if necessary. */ unixEnterMutex(); pInode = pDbFd->pInode; pShmNode = pInode->pShmNode; if( pShmNode==0 ){ struct stat sStat; /* fstat() info for database file */ #ifndef SQLITE_SHM_DIRECTORY const char *zBasePath = pDbFd->zPath; #endif /* Call fstat() to figure out the permissions on the database file. If ** a new *-shm file is created, an attempt will be made to create it ** with the same permissions. */ if( osFstat(pDbFd->h, &sStat) ){ rc = SQLITE_IOERR_FSTAT; goto shm_open_err; } #ifdef SQLITE_SHM_DIRECTORY nShmFilename = sizeof(SQLITE_SHM_DIRECTORY) + 31; #else nShmFilename = 6 + (int)strlen(zBasePath); #endif pShmNode = sqlite3_malloc64( sizeof(*pShmNode) + nShmFilename ); if( pShmNode==0 ){ rc = SQLITE_NOMEM_BKPT; goto shm_open_err; } memset(pShmNode, 0, sizeof(*pShmNode)+nShmFilename); zShmFilename = pShmNode->zFilename = (char*)&pShmNode[1]; #ifdef SQLITE_SHM_DIRECTORY sqlite3_snprintf(nShmFilename, zShmFilename, SQLITE_SHM_DIRECTORY "/sqlite-shm-%x-%x", (u32)sStat.st_ino, (u32)sStat.st_dev); #else sqlite3_snprintf(nShmFilename, zShmFilename, "%s-shm", zBasePath); sqlite3FileSuffix3(pDbFd->zPath, zShmFilename); #endif pShmNode->h = -1; pDbFd->pInode->pShmNode = pShmNode; pShmNode->pInode = pDbFd->pInode; if( sqlite3GlobalConfig.bCoreMutex ){ pShmNode->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST); if( pShmNode->mutex==0 ){ rc = SQLITE_NOMEM_BKPT; goto shm_open_err; } } if( pInode->bProcessLock==0 ){ int openFlags = O_RDWR | O_CREAT; if( sqlite3_uri_boolean(pDbFd->zPath, "readonly_shm", 0) ){ openFlags = O_RDONLY; pShmNode->isReadonly = 1; } pShmNode->h = robust_open(zShmFilename, openFlags, (sStat.st_mode&0777)); if( pShmNode->h<0 ){ rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zShmFilename); goto shm_open_err; } /* If this process is running as root, make sure that the SHM file ** is owned by the same user that owns the original database. Otherwise, ** the original owner will not be able to connect. */ robustFchown(pShmNode->h, sStat.st_uid, sStat.st_gid); /* Check to see if another process is holding the dead-man switch. ** If not, truncate the file to zero length. */ rc = SQLITE_OK; if( unixShmSystemLock(pDbFd, F_WRLCK, UNIX_SHM_DMS, 1)==SQLITE_OK ){ if( robust_ftruncate(pShmNode->h, 0) ){ rc = unixLogError(SQLITE_IOERR_SHMOPEN, "ftruncate", zShmFilename); } } if( rc==SQLITE_OK ){ rc = unixShmSystemLock(pDbFd, F_RDLCK, UNIX_SHM_DMS, 1); } if( rc ) goto shm_open_err; } } /* Make the new connection a child of the unixShmNode */ p->pShmNode = pShmNode; #ifdef SQLITE_DEBUG p->id = pShmNode->nextShmId++; #endif pShmNode->nRef++; pDbFd->pShm = p; unixLeaveMutex(); /* The reference count on pShmNode has already been incremented under ** the cover of the unixEnterMutex() mutex and the pointer from the ** new (struct unixShm) object to the pShmNode has been set. All that is ** left to do is to link the new object into the linked list starting ** at pShmNode->pFirst. This must be done while holding the pShmNode->mutex ** mutex. */ sqlite3_mutex_enter(pShmNode->mutex); p->pNext = pShmNode->pFirst; pShmNode->pFirst = p; sqlite3_mutex_leave(pShmNode->mutex); return SQLITE_OK; /* Jump here on any error */ shm_open_err: unixShmPurge(pDbFd); /* This call frees pShmNode if required */ sqlite3_free(p); unixLeaveMutex(); return rc; } /* ** This function is called to obtain a pointer to region iRegion of the ** shared-memory associated with the database file fd. Shared-memory regions ** are numbered starting from zero. Each shared-memory region is szRegion ** bytes in size. ** ** If an error occurs, an error code is returned and *pp is set to NULL. ** ** Otherwise, if the bExtend parameter is 0 and the requested shared-memory ** region has not been allocated (by any client, including one running in a ** separate process), then *pp is set to NULL and SQLITE_OK returned. If ** bExtend is non-zero and the requested shared-memory region has not yet ** been allocated, it is allocated by this function. ** ** If the shared-memory region has already been allocated or is allocated by ** this call as described above, then it is mapped into this processes ** address space (if it is not already), *pp is set to point to the mapped ** memory and SQLITE_OK returned. */ static int unixShmMap( sqlite3_file *fd, /* Handle open on database file */ int iRegion, /* Region to retrieve */ int szRegion, /* Size of regions */ int bExtend, /* True to extend file if necessary */ void volatile **pp /* OUT: Mapped memory */ ){ unixFile *pDbFd = (unixFile*)fd; unixShm *p; unixShmNode *pShmNode; int rc = SQLITE_OK; int nShmPerMap = unixShmRegionPerMap(); int nReqRegion; /* If the shared-memory file has not yet been opened, open it now. */ if( pDbFd->pShm==0 ){ rc = unixOpenSharedMemory(pDbFd); if( rc!=SQLITE_OK ) return rc; } p = pDbFd->pShm; pShmNode = p->pShmNode; sqlite3_mutex_enter(pShmNode->mutex); assert( szRegion==pShmNode->szRegion || pShmNode->nRegion==0 ); assert( pShmNode->pInode==pDbFd->pInode ); assert( pShmNode->h>=0 || pDbFd->pInode->bProcessLock==1 ); assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 ); /* Minimum number of regions required to be mapped. */ nReqRegion = ((iRegion+nShmPerMap) / nShmPerMap) * nShmPerMap; if( pShmNode->nRegionszRegion = szRegion; if( pShmNode->h>=0 ){ /* The requested region is not mapped into this processes address space. ** Check to see if it has been allocated (i.e. if the wal-index file is ** large enough to contain the requested region). */ if( osFstat(pShmNode->h, &sStat) ){ rc = SQLITE_IOERR_SHMSIZE; goto shmpage_out; } if( sStat.st_sizeh, iPg*pgsz + pgsz-1, "", 1, &x)!=1 ){ const char *zFile = pShmNode->zFilename; rc = unixLogError(SQLITE_IOERR_SHMSIZE, "write", zFile); goto shmpage_out; } } } } } /* Map the requested memory region into this processes address space. */ apNew = (char **)sqlite3_realloc( pShmNode->apRegion, nReqRegion*sizeof(char *) ); if( !apNew ){ rc = SQLITE_IOERR_NOMEM_BKPT; goto shmpage_out; } pShmNode->apRegion = apNew; while( pShmNode->nRegionh>=0 ){ pMem = osMmap(0, nMap, pShmNode->isReadonly ? PROT_READ : PROT_READ|PROT_WRITE, MAP_SHARED, pShmNode->h, szRegion*(i64)pShmNode->nRegion ); if( pMem==MAP_FAILED ){ rc = unixLogError(SQLITE_IOERR_SHMMAP, "mmap", pShmNode->zFilename); goto shmpage_out; } }else{ pMem = sqlite3_malloc64(szRegion); if( pMem==0 ){ rc = SQLITE_NOMEM_BKPT; goto shmpage_out; } memset(pMem, 0, szRegion); } for(i=0; iapRegion[pShmNode->nRegion+i] = &((char*)pMem)[szRegion*i]; } pShmNode->nRegion += nShmPerMap; } } shmpage_out: if( pShmNode->nRegion>iRegion ){ *pp = pShmNode->apRegion[iRegion]; }else{ *pp = 0; } if( pShmNode->isReadonly && rc==SQLITE_OK ) rc = SQLITE_READONLY; sqlite3_mutex_leave(pShmNode->mutex); return rc; } /* ** Change the lock state for a shared-memory segment. ** ** Note that the relationship between SHAREd and EXCLUSIVE locks is a little ** different here than in posix. In xShmLock(), one can go from unlocked ** to shared and back or from unlocked to exclusive and back. But one may ** not go from shared to exclusive or from exclusive to shared. */ static int unixShmLock( sqlite3_file *fd, /* Database file holding the shared memory */ int ofst, /* First lock to acquire or release */ int n, /* Number of locks to acquire or release */ int flags /* What to do with the lock */ ){ unixFile *pDbFd = (unixFile*)fd; /* Connection holding shared memory */ unixShm *p = pDbFd->pShm; /* The shared memory being locked */ unixShm *pX; /* For looping over all siblings */ unixShmNode *pShmNode = p->pShmNode; /* The underlying file iNode */ int rc = SQLITE_OK; /* Result code */ u16 mask; /* Mask of locks to take or release */ assert( pShmNode==pDbFd->pInode->pShmNode ); assert( pShmNode->pInode==pDbFd->pInode ); assert( ofst>=0 && ofst+n<=SQLITE_SHM_NLOCK ); assert( n>=1 ); assert( flags==(SQLITE_SHM_LOCK | SQLITE_SHM_SHARED) || flags==(SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE) || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED) || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE) ); assert( n==1 || (flags & SQLITE_SHM_EXCLUSIVE)!=0 ); assert( pShmNode->h>=0 || pDbFd->pInode->bProcessLock==1 ); assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 ); mask = (1<<(ofst+n)) - (1<1 || mask==(1<mutex); if( flags & SQLITE_SHM_UNLOCK ){ u16 allMask = 0; /* Mask of locks held by siblings */ /* See if any siblings hold this same lock */ for(pX=pShmNode->pFirst; pX; pX=pX->pNext){ if( pX==p ) continue; assert( (pX->exclMask & (p->exclMask|p->sharedMask))==0 ); allMask |= pX->sharedMask; } /* Unlock the system-level locks */ if( (mask & allMask)==0 ){ rc = unixShmSystemLock(pDbFd, F_UNLCK, ofst+UNIX_SHM_BASE, n); }else{ rc = SQLITE_OK; } /* Undo the local locks */ if( rc==SQLITE_OK ){ p->exclMask &= ~mask; p->sharedMask &= ~mask; } }else if( flags & SQLITE_SHM_SHARED ){ u16 allShared = 0; /* Union of locks held by connections other than "p" */ /* Find out which shared locks are already held by sibling connections. ** If any sibling already holds an exclusive lock, go ahead and return ** SQLITE_BUSY. */ for(pX=pShmNode->pFirst; pX; pX=pX->pNext){ if( (pX->exclMask & mask)!=0 ){ rc = SQLITE_BUSY; break; } allShared |= pX->sharedMask; } /* Get shared locks at the system level, if necessary */ if( rc==SQLITE_OK ){ if( (allShared & mask)==0 ){ rc = unixShmSystemLock(pDbFd, F_RDLCK, ofst+UNIX_SHM_BASE, n); }else{ rc = SQLITE_OK; } } /* Get the local shared locks */ if( rc==SQLITE_OK ){ p->sharedMask |= mask; } }else{ /* Make sure no sibling connections hold locks that will block this ** lock. If any do, return SQLITE_BUSY right away. */ for(pX=pShmNode->pFirst; pX; pX=pX->pNext){ if( (pX->exclMask & mask)!=0 || (pX->sharedMask & mask)!=0 ){ rc = SQLITE_BUSY; break; } } /* Get the exclusive locks at the system level. Then if successful ** also mark the local connection as being locked. */ if( rc==SQLITE_OK ){ rc = unixShmSystemLock(pDbFd, F_WRLCK, ofst+UNIX_SHM_BASE, n); if( rc==SQLITE_OK ){ assert( (p->sharedMask & mask)==0 ); p->exclMask |= mask; } } } sqlite3_mutex_leave(pShmNode->mutex); OSTRACE(("SHM-LOCK shmid-%d, pid-%d got %03x,%03x\n", p->id, osGetpid(0), p->sharedMask, p->exclMask)); return rc; } /* ** Implement a memory barrier or memory fence on shared memory. ** ** All loads and stores begun before the barrier must complete before ** any load or store begun after the barrier. */ static void unixShmBarrier( sqlite3_file *fd /* Database file holding the shared memory */ ){ UNUSED_PARAMETER(fd); sqlite3MemoryBarrier(); /* compiler-defined memory barrier */ unixEnterMutex(); /* Also mutex, for redundancy */ unixLeaveMutex(); } /* ** Close a connection to shared-memory. Delete the underlying ** storage if deleteFlag is true. ** ** If there is no shared memory associated with the connection then this ** routine is a harmless no-op. */ static int unixShmUnmap( sqlite3_file *fd, /* The underlying database file */ int deleteFlag /* Delete shared-memory if true */ ){ unixShm *p; /* The connection to be closed */ unixShmNode *pShmNode; /* The underlying shared-memory file */ unixShm **pp; /* For looping over sibling connections */ unixFile *pDbFd; /* The underlying database file */ pDbFd = (unixFile*)fd; p = pDbFd->pShm; if( p==0 ) return SQLITE_OK; pShmNode = p->pShmNode; assert( pShmNode==pDbFd->pInode->pShmNode ); assert( pShmNode->pInode==pDbFd->pInode ); /* Remove connection p from the set of connections associated ** with pShmNode */ sqlite3_mutex_enter(pShmNode->mutex); for(pp=&pShmNode->pFirst; (*pp)!=p; pp = &(*pp)->pNext){} *pp = p->pNext; /* Free the connection p */ sqlite3_free(p); pDbFd->pShm = 0; sqlite3_mutex_leave(pShmNode->mutex); /* If pShmNode->nRef has reached 0, then close the underlying ** shared-memory file, too */ unixEnterMutex(); assert( pShmNode->nRef>0 ); pShmNode->nRef--; if( pShmNode->nRef==0 ){ if( deleteFlag && pShmNode->h>=0 ){ osUnlink(pShmNode->zFilename); } unixShmPurge(pDbFd); } unixLeaveMutex(); return SQLITE_OK; } #else # define unixShmMap 0 # define unixShmLock 0 # define unixShmBarrier 0 # define unixShmUnmap 0 #endif /* #ifndef SQLITE_OMIT_WAL */ #if SQLITE_MAX_MMAP_SIZE>0 /* ** If it is currently memory mapped, unmap file pFd. */ static void unixUnmapfile(unixFile *pFd){ assert( pFd->nFetchOut==0 ); if( pFd->pMapRegion ){ osMunmap(pFd->pMapRegion, pFd->mmapSizeActual); pFd->pMapRegion = 0; pFd->mmapSize = 0; pFd->mmapSizeActual = 0; } } /* ** Attempt to set the size of the memory mapping maintained by file ** descriptor pFd to nNew bytes. Any existing mapping is discarded. ** ** If successful, this function sets the following variables: ** ** unixFile.pMapRegion ** unixFile.mmapSize ** unixFile.mmapSizeActual ** ** If unsuccessful, an error message is logged via sqlite3_log() and ** the three variables above are zeroed. In this case SQLite should ** continue accessing the database using the xRead() and xWrite() ** methods. */ static void unixRemapfile( unixFile *pFd, /* File descriptor object */ i64 nNew /* Required mapping size */ ){ const char *zErr = "mmap"; int h = pFd->h; /* File descriptor open on db file */ u8 *pOrig = (u8 *)pFd->pMapRegion; /* Pointer to current file mapping */ i64 nOrig = pFd->mmapSizeActual; /* Size of pOrig region in bytes */ u8 *pNew = 0; /* Location of new mapping */ int flags = PROT_READ; /* Flags to pass to mmap() */ assert( pFd->nFetchOut==0 ); assert( nNew>pFd->mmapSize ); assert( nNew<=pFd->mmapSizeMax ); assert( nNew>0 ); assert( pFd->mmapSizeActual>=pFd->mmapSize ); assert( MAP_FAILED!=0 ); #ifdef SQLITE_MMAP_READWRITE if( (pFd->ctrlFlags & UNIXFILE_RDONLY)==0 ) flags |= PROT_WRITE; #endif if( pOrig ){ #if HAVE_MREMAP i64 nReuse = pFd->mmapSize; #else const int szSyspage = osGetpagesize(); i64 nReuse = (pFd->mmapSize & ~(szSyspage-1)); #endif u8 *pReq = &pOrig[nReuse]; /* Unmap any pages of the existing mapping that cannot be reused. */ if( nReuse!=nOrig ){ osMunmap(pReq, nOrig-nReuse); } #if HAVE_MREMAP pNew = osMremap(pOrig, nReuse, nNew, MREMAP_MAYMOVE); zErr = "mremap"; #else pNew = osMmap(pReq, nNew-nReuse, flags, MAP_SHARED, h, nReuse); if( pNew!=MAP_FAILED ){ if( pNew!=pReq ){ osMunmap(pNew, nNew - nReuse); pNew = 0; }else{ pNew = pOrig; } } #endif /* The attempt to extend the existing mapping failed. Free it. */ if( pNew==MAP_FAILED || pNew==0 ){ osMunmap(pOrig, nReuse); } } /* If pNew is still NULL, try to create an entirely new mapping. */ if( pNew==0 ){ pNew = osMmap(0, nNew, flags, MAP_SHARED, h, 0); } if( pNew==MAP_FAILED ){ pNew = 0; nNew = 0; unixLogError(SQLITE_OK, zErr, pFd->zPath); /* If the mmap() above failed, assume that all subsequent mmap() calls ** will probably fail too. Fall back to using xRead/xWrite exclusively ** in this case. */ pFd->mmapSizeMax = 0; } pFd->pMapRegion = (void *)pNew; pFd->mmapSize = pFd->mmapSizeActual = nNew; } /* ** Memory map or remap the file opened by file-descriptor pFd (if the file ** is already mapped, the existing mapping is replaced by the new). Or, if ** there already exists a mapping for this file, and there are still ** outstanding xFetch() references to it, this function is a no-op. ** ** If parameter nByte is non-negative, then it is the requested size of ** the mapping to create. Otherwise, if nByte is less than zero, then the ** requested size is the size of the file on disk. The actual size of the ** created mapping is either the requested size or the value configured ** using SQLITE_FCNTL_MMAP_LIMIT, whichever is smaller. ** ** SQLITE_OK is returned if no error occurs (even if the mapping is not ** recreated as a result of outstanding references) or an SQLite error ** code otherwise. */ static int unixMapfile(unixFile *pFd, i64 nMap){ assert( nMap>=0 || pFd->nFetchOut==0 ); assert( nMap>0 || (pFd->mmapSize==0 && pFd->pMapRegion==0) ); if( pFd->nFetchOut>0 ) return SQLITE_OK; if( nMap<0 ){ struct stat statbuf; /* Low-level file information */ if( osFstat(pFd->h, &statbuf) ){ return SQLITE_IOERR_FSTAT; } nMap = statbuf.st_size; } if( nMap>pFd->mmapSizeMax ){ nMap = pFd->mmapSizeMax; } assert( nMap>0 || (pFd->mmapSize==0 && pFd->pMapRegion==0) ); if( nMap!=pFd->mmapSize ){ unixRemapfile(pFd, nMap); } return SQLITE_OK; } #endif /* SQLITE_MAX_MMAP_SIZE>0 */ /* ** If possible, return a pointer to a mapping of file fd starting at offset ** iOff. The mapping must be valid for at least nAmt bytes. ** ** If such a pointer can be obtained, store it in *pp and return SQLITE_OK. ** Or, if one cannot but no error occurs, set *pp to 0 and return SQLITE_OK. ** Finally, if an error does occur, return an SQLite error code. The final ** value of *pp is undefined in this case. ** ** If this function does return a pointer, the caller must eventually ** release the reference by calling unixUnfetch(). */ static int unixFetch(sqlite3_file *fd, i64 iOff, int nAmt, void **pp){ #if SQLITE_MAX_MMAP_SIZE>0 unixFile *pFd = (unixFile *)fd; /* The underlying database file */ #endif *pp = 0; #if SQLITE_MAX_MMAP_SIZE>0 if( pFd->mmapSizeMax>0 ){ if( pFd->pMapRegion==0 ){ int rc = unixMapfile(pFd, -1); if( rc!=SQLITE_OK ) return rc; } if( pFd->mmapSize >= iOff+nAmt ){ *pp = &((u8 *)pFd->pMapRegion)[iOff]; pFd->nFetchOut++; } } #endif return SQLITE_OK; } /* ** If the third argument is non-NULL, then this function releases a ** reference obtained by an earlier call to unixFetch(). The second ** argument passed to this function must be the same as the corresponding ** argument that was passed to the unixFetch() invocation. ** ** Or, if the third argument is NULL, then this function is being called ** to inform the VFS layer that, according to POSIX, any existing mapping ** may now be invalid and should be unmapped. */ static int unixUnfetch(sqlite3_file *fd, i64 iOff, void *p){ #if SQLITE_MAX_MMAP_SIZE>0 unixFile *pFd = (unixFile *)fd; /* The underlying database file */ UNUSED_PARAMETER(iOff); /* If p==0 (unmap the entire file) then there must be no outstanding ** xFetch references. Or, if p!=0 (meaning it is an xFetch reference), ** then there must be at least one outstanding. */ assert( (p==0)==(pFd->nFetchOut==0) ); /* If p!=0, it must match the iOff value. */ assert( p==0 || p==&((u8 *)pFd->pMapRegion)[iOff] ); if( p ){ pFd->nFetchOut--; }else{ unixUnmapfile(pFd); } assert( pFd->nFetchOut>=0 ); #else UNUSED_PARAMETER(fd); UNUSED_PARAMETER(p); UNUSED_PARAMETER(iOff); #endif return SQLITE_OK; } /* ** Here ends the implementation of all sqlite3_file methods. ** ********************** End sqlite3_file Methods ******************************* ******************************************************************************/ /* ** This division contains definitions of sqlite3_io_methods objects that ** implement various file locking strategies. It also contains definitions ** of "finder" functions. A finder-function is used to locate the appropriate ** sqlite3_io_methods object for a particular database file. The pAppData ** field of the sqlite3_vfs VFS objects are initialized to be pointers to ** the correct finder-function for that VFS. ** ** Most finder functions return a pointer to a fixed sqlite3_io_methods ** object. The only interesting finder-function is autolockIoFinder, which ** looks at the filesystem type and tries to guess the best locking ** strategy from that. ** ** For finder-function F, two objects are created: ** ** (1) The real finder-function named "FImpt()". ** ** (2) A constant pointer to this function named just "F". ** ** ** A pointer to the F pointer is used as the pAppData value for VFS ** objects. We have to do this instead of letting pAppData point ** directly at the finder-function since C90 rules prevent a void* ** from be cast into a function pointer. ** ** ** Each instance of this macro generates two objects: ** ** * A constant sqlite3_io_methods object call METHOD that has locking ** methods CLOSE, LOCK, UNLOCK, CKRESLOCK. ** ** * An I/O method finder function called FINDER that returns a pointer ** to the METHOD object in the previous bullet. */ #define IOMETHODS(FINDER,METHOD,VERSION,CLOSE,LOCK,UNLOCK,CKLOCK,SHMMAP) \ static const sqlite3_io_methods METHOD = { \ VERSION, /* iVersion */ \ CLOSE, /* xClose */ \ unixRead, /* xRead */ \ unixWrite, /* xWrite */ \ unixTruncate, /* xTruncate */ \ unixSync, /* xSync */ \ unixFileSize, /* xFileSize */ \ LOCK, /* xLock */ \ UNLOCK, /* xUnlock */ \ CKLOCK, /* xCheckReservedLock */ \ unixFileControl, /* xFileControl */ \ unixSectorSize, /* xSectorSize */ \ unixDeviceCharacteristics, /* xDeviceCapabilities */ \ SHMMAP, /* xShmMap */ \ unixShmLock, /* xShmLock */ \ unixShmBarrier, /* xShmBarrier */ \ unixShmUnmap, /* xShmUnmap */ \ unixFetch, /* xFetch */ \ unixUnfetch, /* xUnfetch */ \ }; \ static const sqlite3_io_methods *FINDER##Impl(const char *z, unixFile *p){ \ UNUSED_PARAMETER(z); UNUSED_PARAMETER(p); \ return &METHOD; \ } \ static const sqlite3_io_methods *(*const FINDER)(const char*,unixFile *p) \ = FINDER##Impl; /* ** Here are all of the sqlite3_io_methods objects for each of the ** locking strategies. Functions that return pointers to these methods ** are also created. */ IOMETHODS( posixIoFinder, /* Finder function name */ posixIoMethods, /* sqlite3_io_methods object name */ 3, /* shared memory and mmap are enabled */ unixClose, /* xClose method */ unixLock, /* xLock method */ unixUnlock, /* xUnlock method */ unixCheckReservedLock, /* xCheckReservedLock method */ unixShmMap /* xShmMap method */ ) IOMETHODS( nolockIoFinder, /* Finder function name */ nolockIoMethods, /* sqlite3_io_methods object name */ 3, /* shared memory is disabled */ nolockClose, /* xClose method */ nolockLock, /* xLock method */ nolockUnlock, /* xUnlock method */ nolockCheckReservedLock, /* xCheckReservedLock method */ 0 /* xShmMap method */ ) IOMETHODS( dotlockIoFinder, /* Finder function name */ dotlockIoMethods, /* sqlite3_io_methods object name */ 1, /* shared memory is disabled */ dotlockClose, /* xClose method */ dotlockLock, /* xLock method */ dotlockUnlock, /* xUnlock method */ dotlockCheckReservedLock, /* xCheckReservedLock method */ 0 /* xShmMap method */ ) #if SQLITE_ENABLE_LOCKING_STYLE IOMETHODS( flockIoFinder, /* Finder function name */ flockIoMethods, /* sqlite3_io_methods object name */ 1, /* shared memory is disabled */ flockClose, /* xClose method */ flockLock, /* xLock method */ flockUnlock, /* xUnlock method */ flockCheckReservedLock, /* xCheckReservedLock method */ 0 /* xShmMap method */ ) #endif #if OS_VXWORKS IOMETHODS( semIoFinder, /* Finder function name */ semIoMethods, /* sqlite3_io_methods object name */ 1, /* shared memory is disabled */ semXClose, /* xClose method */ semXLock, /* xLock method */ semXUnlock, /* xUnlock method */ semXCheckReservedLock, /* xCheckReservedLock method */ 0 /* xShmMap method */ ) #endif #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE IOMETHODS( afpIoFinder, /* Finder function name */ afpIoMethods, /* sqlite3_io_methods object name */ 1, /* shared memory is disabled */ afpClose, /* xClose method */ afpLock, /* xLock method */ afpUnlock, /* xUnlock method */ afpCheckReservedLock, /* xCheckReservedLock method */ 0 /* xShmMap method */ ) #endif /* ** The proxy locking method is a "super-method" in the sense that it ** opens secondary file descriptors for the conch and lock files and ** it uses proxy, dot-file, AFP, and flock() locking methods on those ** secondary files. For this reason, the division that implements ** proxy locking is located much further down in the file. But we need ** to go ahead and define the sqlite3_io_methods and finder function ** for proxy locking here. So we forward declare the I/O methods. */ #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE static int proxyClose(sqlite3_file*); static int proxyLock(sqlite3_file*, int); static int proxyUnlock(sqlite3_file*, int); static int proxyCheckReservedLock(sqlite3_file*, int*); IOMETHODS( proxyIoFinder, /* Finder function name */ proxyIoMethods, /* sqlite3_io_methods object name */ 1, /* shared memory is disabled */ proxyClose, /* xClose method */ proxyLock, /* xLock method */ proxyUnlock, /* xUnlock method */ proxyCheckReservedLock, /* xCheckReservedLock method */ 0 /* xShmMap method */ ) #endif /* nfs lockd on OSX 10.3+ doesn't clear write locks when a read lock is set */ #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE IOMETHODS( nfsIoFinder, /* Finder function name */ nfsIoMethods, /* sqlite3_io_methods object name */ 1, /* shared memory is disabled */ unixClose, /* xClose method */ unixLock, /* xLock method */ nfsUnlock, /* xUnlock method */ unixCheckReservedLock, /* xCheckReservedLock method */ 0 /* xShmMap method */ ) #endif #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE /* ** This "finder" function attempts to determine the best locking strategy ** for the database file "filePath". It then returns the sqlite3_io_methods ** object that implements that strategy. ** ** This is for MacOSX only. */ static const sqlite3_io_methods *autolockIoFinderImpl( const char *filePath, /* name of the database file */ unixFile *pNew /* open file object for the database file */ ){ static const struct Mapping { const char *zFilesystem; /* Filesystem type name */ const sqlite3_io_methods *pMethods; /* Appropriate locking method */ } aMap[] = { { "hfs", &posixIoMethods }, { "ufs", &posixIoMethods }, { "afpfs", &afpIoMethods }, { "smbfs", &afpIoMethods }, { "webdav", &nolockIoMethods }, { 0, 0 } }; int i; struct statfs fsInfo; struct flock lockInfo; if( !filePath ){ /* If filePath==NULL that means we are dealing with a transient file ** that does not need to be locked. */ return &nolockIoMethods; } if( statfs(filePath, &fsInfo) != -1 ){ if( fsInfo.f_flags & MNT_RDONLY ){ return &nolockIoMethods; } for(i=0; aMap[i].zFilesystem; i++){ if( strcmp(fsInfo.f_fstypename, aMap[i].zFilesystem)==0 ){ return aMap[i].pMethods; } } } /* Default case. Handles, amongst others, "nfs". ** Test byte-range lock using fcntl(). If the call succeeds, ** assume that the file-system supports POSIX style locks. */ lockInfo.l_len = 1; lockInfo.l_start = 0; lockInfo.l_whence = SEEK_SET; lockInfo.l_type = F_RDLCK; if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) { if( strcmp(fsInfo.f_fstypename, "nfs")==0 ){ return &nfsIoMethods; } else { return &posixIoMethods; } }else{ return &dotlockIoMethods; } } static const sqlite3_io_methods *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl; #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */ #if OS_VXWORKS /* ** This "finder" function for VxWorks checks to see if posix advisory ** locking works. If it does, then that is what is used. If it does not ** work, then fallback to named semaphore locking. */ static const sqlite3_io_methods *vxworksIoFinderImpl( const char *filePath, /* name of the database file */ unixFile *pNew /* the open file object */ ){ struct flock lockInfo; if( !filePath ){ /* If filePath==NULL that means we are dealing with a transient file ** that does not need to be locked. */ return &nolockIoMethods; } /* Test if fcntl() is supported and use POSIX style locks. ** Otherwise fall back to the named semaphore method. */ lockInfo.l_len = 1; lockInfo.l_start = 0; lockInfo.l_whence = SEEK_SET; lockInfo.l_type = F_RDLCK; if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) { return &posixIoMethods; }else{ return &semIoMethods; } } static const sqlite3_io_methods *(*const vxworksIoFinder)(const char*,unixFile*) = vxworksIoFinderImpl; #endif /* OS_VXWORKS */ /* ** An abstract type for a pointer to an IO method finder function: */ typedef const sqlite3_io_methods *(*finder_type)(const char*,unixFile*); /**************************************************************************** **************************** sqlite3_vfs methods **************************** ** ** This division contains the implementation of methods on the ** sqlite3_vfs object. */ /* ** Initialize the contents of the unixFile structure pointed to by pId. */ static int fillInUnixFile( sqlite3_vfs *pVfs, /* Pointer to vfs object */ int h, /* Open file descriptor of file being opened */ sqlite3_file *pId, /* Write to the unixFile structure here */ const char *zFilename, /* Name of the file being opened */ int ctrlFlags /* Zero or more UNIXFILE_* values */ ){ const sqlite3_io_methods *pLockingStyle; unixFile *pNew = (unixFile *)pId; int rc = SQLITE_OK; assert( pNew->pInode==NULL ); /* Usually the path zFilename should not be a relative pathname. The ** exception is when opening the proxy "conch" file in builds that ** include the special Apple locking styles. */ #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE assert( zFilename==0 || zFilename[0]=='/' || pVfs->pAppData==(void*)&autolockIoFinder ); #else assert( zFilename==0 || zFilename[0]=='/' ); #endif /* No locking occurs in temporary files */ assert( zFilename!=0 || (ctrlFlags & UNIXFILE_NOLOCK)!=0 ); OSTRACE(("OPEN %-3d %s\n", h, zFilename)); pNew->h = h; pNew->pVfs = pVfs; pNew->zPath = zFilename; pNew->ctrlFlags = (u8)ctrlFlags; #if SQLITE_MAX_MMAP_SIZE>0 pNew->mmapSizeMax = sqlite3GlobalConfig.szMmap; #endif if( sqlite3_uri_boolean(((ctrlFlags & UNIXFILE_URI) ? zFilename : 0), "psow", SQLITE_POWERSAFE_OVERWRITE) ){ pNew->ctrlFlags |= UNIXFILE_PSOW; } if( strcmp(pVfs->zName,"unix-excl")==0 ){ pNew->ctrlFlags |= UNIXFILE_EXCL; } #if OS_VXWORKS pNew->pId = vxworksFindFileId(zFilename); if( pNew->pId==0 ){ ctrlFlags |= UNIXFILE_NOLOCK; rc = SQLITE_NOMEM_BKPT; } #endif if( ctrlFlags & UNIXFILE_NOLOCK ){ pLockingStyle = &nolockIoMethods; }else{ pLockingStyle = (**(finder_type*)pVfs->pAppData)(zFilename, pNew); #if SQLITE_ENABLE_LOCKING_STYLE /* Cache zFilename in the locking context (AFP and dotlock override) for ** proxyLock activation is possible (remote proxy is based on db name) ** zFilename remains valid until file is closed, to support */ pNew->lockingContext = (void*)zFilename; #endif } if( pLockingStyle == &posixIoMethods #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE || pLockingStyle == &nfsIoMethods #endif ){ unixEnterMutex(); rc = findInodeInfo(pNew, &pNew->pInode); if( rc!=SQLITE_OK ){ /* If an error occurred in findInodeInfo(), close the file descriptor ** immediately, before releasing the mutex. findInodeInfo() may fail ** in two scenarios: ** ** (a) A call to fstat() failed. ** (b) A malloc failed. ** ** Scenario (b) may only occur if the process is holding no other ** file descriptors open on the same file. If there were other file ** descriptors on this file, then no malloc would be required by ** findInodeInfo(). If this is the case, it is quite safe to close ** handle h - as it is guaranteed that no posix locks will be released ** by doing so. ** ** If scenario (a) caused the error then things are not so safe. The ** implicit assumption here is that if fstat() fails, things are in ** such bad shape that dropping a lock or two doesn't matter much. */ robust_close(pNew, h, __LINE__); h = -1; } unixLeaveMutex(); } #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__) else if( pLockingStyle == &afpIoMethods ){ /* AFP locking uses the file path so it needs to be included in ** the afpLockingContext. */ afpLockingContext *pCtx; pNew->lockingContext = pCtx = sqlite3_malloc64( sizeof(*pCtx) ); if( pCtx==0 ){ rc = SQLITE_NOMEM_BKPT; }else{ /* NB: zFilename exists and remains valid until the file is closed ** according to requirement F11141. So we do not need to make a ** copy of the filename. */ pCtx->dbPath = zFilename; pCtx->reserved = 0; srandomdev(); unixEnterMutex(); rc = findInodeInfo(pNew, &pNew->pInode); if( rc!=SQLITE_OK ){ sqlite3_free(pNew->lockingContext); robust_close(pNew, h, __LINE__); h = -1; } unixLeaveMutex(); } } #endif else if( pLockingStyle == &dotlockIoMethods ){ /* Dotfile locking uses the file path so it needs to be included in ** the dotlockLockingContext */ char *zLockFile; int nFilename; assert( zFilename!=0 ); nFilename = (int)strlen(zFilename) + 6; zLockFile = (char *)sqlite3_malloc64(nFilename); if( zLockFile==0 ){ rc = SQLITE_NOMEM_BKPT; }else{ sqlite3_snprintf(nFilename, zLockFile, "%s" DOTLOCK_SUFFIX, zFilename); } pNew->lockingContext = zLockFile; } #if OS_VXWORKS else if( pLockingStyle == &semIoMethods ){ /* Named semaphore locking uses the file path so it needs to be ** included in the semLockingContext */ unixEnterMutex(); rc = findInodeInfo(pNew, &pNew->pInode); if( (rc==SQLITE_OK) && (pNew->pInode->pSem==NULL) ){ char *zSemName = pNew->pInode->aSemName; int n; sqlite3_snprintf(MAX_PATHNAME, zSemName, "/%s.sem", pNew->pId->zCanonicalName); for( n=1; zSemName[n]; n++ ) if( zSemName[n]=='/' ) zSemName[n] = '_'; pNew->pInode->pSem = sem_open(zSemName, O_CREAT, 0666, 1); if( pNew->pInode->pSem == SEM_FAILED ){ rc = SQLITE_NOMEM_BKPT; pNew->pInode->aSemName[0] = '\0'; } } unixLeaveMutex(); } #endif storeLastErrno(pNew, 0); #if OS_VXWORKS if( rc!=SQLITE_OK ){ if( h>=0 ) robust_close(pNew, h, __LINE__); h = -1; osUnlink(zFilename); pNew->ctrlFlags |= UNIXFILE_DELETE; } #endif if( rc!=SQLITE_OK ){ if( h>=0 ) robust_close(pNew, h, __LINE__); }else{ pNew->pMethod = pLockingStyle; OpenCounter(+1); verifyDbFile(pNew); } return rc; } /* ** Return the name of a directory in which to put temporary files. ** If no suitable temporary file directory can be found, return NULL. */ static const char *unixTempFileDir(void){ static const char *azDirs[] = { 0, 0, "/var/tmp", "/usr/tmp", "/tmp", "." }; unsigned int i = 0; struct stat buf; const char *zDir = sqlite3_temp_directory; if( !azDirs[0] ) azDirs[0] = getenv("SQLITE_TMPDIR"); if( !azDirs[1] ) azDirs[1] = getenv("TMPDIR"); while(1){ if( zDir!=0 && osStat(zDir, &buf)==0 && S_ISDIR(buf.st_mode) && osAccess(zDir, 03)==0 ){ return zDir; } if( i>=sizeof(azDirs)/sizeof(azDirs[0]) ) break; zDir = azDirs[i++]; } return 0; } /* ** Create a temporary file name in zBuf. zBuf must be allocated ** by the calling process and must be big enough to hold at least ** pVfs->mxPathname bytes. */ static int unixGetTempname(int nBuf, char *zBuf){ const char *zDir; int iLimit = 0; /* It's odd to simulate an io-error here, but really this is just ** using the io-error infrastructure to test that SQLite handles this ** function failing. */ zBuf[0] = 0; SimulateIOError( return SQLITE_IOERR ); zDir = unixTempFileDir(); if( zDir==0 ) return SQLITE_IOERR_GETTEMPPATH; do{ u64 r; sqlite3_randomness(sizeof(r), &r); assert( nBuf>2 ); zBuf[nBuf-2] = 0; sqlite3_snprintf(nBuf, zBuf, "%s/"SQLITE_TEMP_FILE_PREFIX"%llx%c", zDir, r, 0); if( zBuf[nBuf-2]!=0 || (iLimit++)>10 ) return SQLITE_ERROR; }while( osAccess(zBuf,0)==0 ); return SQLITE_OK; } #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__) /* ** Routine to transform a unixFile into a proxy-locking unixFile. ** Implementation in the proxy-lock division, but used by unixOpen() ** if SQLITE_PREFER_PROXY_LOCKING is defined. */ static int proxyTransformUnixFile(unixFile*, const char*); #endif /* ** Search for an unused file descriptor that was opened on the database ** file (not a journal or master-journal file) identified by pathname ** zPath with SQLITE_OPEN_XXX flags matching those passed as the second ** argument to this function. ** ** Such a file descriptor may exist if a database connection was closed ** but the associated file descriptor could not be closed because some ** other file descriptor open on the same file is holding a file-lock. ** Refer to comments in the unixClose() function and the lengthy comment ** describing "Posix Advisory Locking" at the start of this file for ** further details. Also, ticket #4018. ** ** If a suitable file descriptor is found, then it is returned. If no ** such file descriptor is located, -1 is returned. */ static UnixUnusedFd *findReusableFd(const char *zPath, int flags){ UnixUnusedFd *pUnused = 0; /* Do not search for an unused file descriptor on vxworks. Not because ** vxworks would not benefit from the change (it might, we're not sure), ** but because no way to test it is currently available. It is better ** not to risk breaking vxworks support for the sake of such an obscure ** feature. */ #if !OS_VXWORKS struct stat sStat; /* Results of stat() call */ /* A stat() call may fail for various reasons. If this happens, it is ** almost certain that an open() call on the same path will also fail. ** For this reason, if an error occurs in the stat() call here, it is ** ignored and -1 is returned. The caller will try to open a new file ** descriptor on the same path, fail, and return an error to SQLite. ** ** Even if a subsequent open() call does succeed, the consequences of ** not searching for a reusable file descriptor are not dire. */ if( 0==osStat(zPath, &sStat) ){ unixInodeInfo *pInode; unixEnterMutex(); pInode = inodeList; while( pInode && (pInode->fileId.dev!=sStat.st_dev || pInode->fileId.ino!=sStat.st_ino) ){ pInode = pInode->pNext; } if( pInode ){ UnixUnusedFd **pp; for(pp=&pInode->pUnused; *pp && (*pp)->flags!=flags; pp=&((*pp)->pNext)); pUnused = *pp; if( pUnused ){ *pp = pUnused->pNext; } } unixLeaveMutex(); } #endif /* if !OS_VXWORKS */ return pUnused; } /* ** Find the mode, uid and gid of file zFile. */ static int getFileMode( const char *zFile, /* File name */ mode_t *pMode, /* OUT: Permissions of zFile */ uid_t *pUid, /* OUT: uid of zFile. */ gid_t *pGid /* OUT: gid of zFile. */ ){ struct stat sStat; /* Output of stat() on database file */ int rc = SQLITE_OK; if( 0==osStat(zFile, &sStat) ){ *pMode = sStat.st_mode & 0777; *pUid = sStat.st_uid; *pGid = sStat.st_gid; }else{ rc = SQLITE_IOERR_FSTAT; } return rc; } /* ** This function is called by unixOpen() to determine the unix permissions ** to create new files with. If no error occurs, then SQLITE_OK is returned ** and a value suitable for passing as the third argument to open(2) is ** written to *pMode. If an IO error occurs, an SQLite error code is ** returned and the value of *pMode is not modified. ** ** In most cases, this routine sets *pMode to 0, which will become ** an indication to robust_open() to create the file using ** SQLITE_DEFAULT_FILE_PERMISSIONS adjusted by the umask. ** But if the file being opened is a WAL or regular journal file, then ** this function queries the file-system for the permissions on the ** corresponding database file and sets *pMode to this value. Whenever ** possible, WAL and journal files are created using the same permissions ** as the associated database file. ** ** If the SQLITE_ENABLE_8_3_NAMES option is enabled, then the ** original filename is unavailable. But 8_3_NAMES is only used for ** FAT filesystems and permissions do not matter there, so just use ** the default permissions. */ static int findCreateFileMode( const char *zPath, /* Path of file (possibly) being created */ int flags, /* Flags passed as 4th argument to xOpen() */ mode_t *pMode, /* OUT: Permissions to open file with */ uid_t *pUid, /* OUT: uid to set on the file */ gid_t *pGid /* OUT: gid to set on the file */ ){ int rc = SQLITE_OK; /* Return Code */ *pMode = 0; *pUid = 0; *pGid = 0; if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){ char zDb[MAX_PATHNAME+1]; /* Database file path */ int nDb; /* Number of valid bytes in zDb */ /* zPath is a path to a WAL or journal file. The following block derives ** the path to the associated database file from zPath. This block handles ** the following naming conventions: ** ** "-journal" ** "-wal" ** "-journalNN" ** "-walNN" ** ** where NN is a decimal number. The NN naming schemes are ** used by the test_multiplex.c module. */ nDb = sqlite3Strlen30(zPath) - 1; while( zPath[nDb]!='-' ){ #ifndef SQLITE_ENABLE_8_3_NAMES /* In the normal case (8+3 filenames disabled) the journal filename ** is guaranteed to contain a '-' character. */ assert( nDb>0 ); assert( sqlite3Isalnum(zPath[nDb]) ); #else /* If 8+3 names are possible, then the journal file might not contain ** a '-' character. So check for that case and return early. */ if( nDb==0 || zPath[nDb]=='.' ) return SQLITE_OK; #endif nDb--; } memcpy(zDb, zPath, nDb); zDb[nDb] = '\0'; rc = getFileMode(zDb, pMode, pUid, pGid); }else if( flags & SQLITE_OPEN_DELETEONCLOSE ){ *pMode = 0600; }else if( flags & SQLITE_OPEN_URI ){ /* If this is a main database file and the file was opened using a URI ** filename, check for the "modeof" parameter. If present, interpret ** its value as a filename and try to copy the mode, uid and gid from ** that file. */ const char *z = sqlite3_uri_parameter(zPath, "modeof"); if( z ){ rc = getFileMode(z, pMode, pUid, pGid); } } return rc; } /* ** Open the file zPath. ** ** Previously, the SQLite OS layer used three functions in place of this ** one: ** ** sqlite3OsOpenReadWrite(); ** sqlite3OsOpenReadOnly(); ** sqlite3OsOpenExclusive(); ** ** These calls correspond to the following combinations of flags: ** ** ReadWrite() -> (READWRITE | CREATE) ** ReadOnly() -> (READONLY) ** OpenExclusive() -> (READWRITE | CREATE | EXCLUSIVE) ** ** The old OpenExclusive() accepted a boolean argument - "delFlag". If ** true, the file was configured to be automatically deleted when the ** file handle closed. To achieve the same effect using this new ** interface, add the DELETEONCLOSE flag to those specified above for ** OpenExclusive(). */ static int unixOpen( sqlite3_vfs *pVfs, /* The VFS for which this is the xOpen method */ const char *zPath, /* Pathname of file to be opened */ sqlite3_file *pFile, /* The file descriptor to be filled in */ int flags, /* Input flags to control the opening */ int *pOutFlags /* Output flags returned to SQLite core */ ){ unixFile *p = (unixFile *)pFile; int fd = -1; /* File descriptor returned by open() */ int openFlags = 0; /* Flags to pass to open() */ int eType = flags&0xFFFFFF00; /* Type of file to open */ int noLock; /* True to omit locking primitives */ int rc = SQLITE_OK; /* Function Return Code */ int ctrlFlags = 0; /* UNIXFILE_* flags */ int isExclusive = (flags & SQLITE_OPEN_EXCLUSIVE); int isDelete = (flags & SQLITE_OPEN_DELETEONCLOSE); int isCreate = (flags & SQLITE_OPEN_CREATE); int isReadonly = (flags & SQLITE_OPEN_READONLY); int isReadWrite = (flags & SQLITE_OPEN_READWRITE); #if SQLITE_ENABLE_LOCKING_STYLE int isAutoProxy = (flags & SQLITE_OPEN_AUTOPROXY); #endif #if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE struct statfs fsInfo; #endif /* If creating a master or main-file journal, this function will open ** a file-descriptor on the directory too. The first time unixSync() ** is called the directory file descriptor will be fsync()ed and close()d. */ int syncDir = (isCreate && ( eType==SQLITE_OPEN_MASTER_JOURNAL || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_WAL )); /* If argument zPath is a NULL pointer, this function is required to open ** a temporary file. Use this buffer to store the file name in. */ char zTmpname[MAX_PATHNAME+2]; const char *zName = zPath; /* Check the following statements are true: ** ** (a) Exactly one of the READWRITE and READONLY flags must be set, and ** (b) if CREATE is set, then READWRITE must also be set, and ** (c) if EXCLUSIVE is set, then CREATE must also be set. ** (d) if DELETEONCLOSE is set, then CREATE must also be set. */ assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly)); assert(isCreate==0 || isReadWrite); assert(isExclusive==0 || isCreate); assert(isDelete==0 || isCreate); /* The main DB, main journal, WAL file and master journal are never ** automatically deleted. Nor are they ever temporary files. */ assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB ); assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL ); assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL ); assert( (!isDelete && zName) || eType!=SQLITE_OPEN_WAL ); /* Assert that the upper layer has set one of the "file-type" flags. */ assert( eType==SQLITE_OPEN_MAIN_DB || eType==SQLITE_OPEN_TEMP_DB || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL || eType==SQLITE_OPEN_SUBJOURNAL || eType==SQLITE_OPEN_MASTER_JOURNAL || eType==SQLITE_OPEN_TRANSIENT_DB || eType==SQLITE_OPEN_WAL ); /* Detect a pid change and reset the PRNG. There is a race condition ** here such that two or more threads all trying to open databases at ** the same instant might all reset the PRNG. But multiple resets ** are harmless. */ if( randomnessPid!=osGetpid(0) ){ randomnessPid = osGetpid(0); sqlite3_randomness(0,0); } memset(p, 0, sizeof(unixFile)); if( eType==SQLITE_OPEN_MAIN_DB ){ UnixUnusedFd *pUnused; pUnused = findReusableFd(zName, flags); if( pUnused ){ fd = pUnused->fd; }else{ pUnused = sqlite3_malloc64(sizeof(*pUnused)); if( !pUnused ){ return SQLITE_NOMEM_BKPT; } } p->pUnused = pUnused; /* Database filenames are double-zero terminated if they are not ** URIs with parameters. Hence, they can always be passed into ** sqlite3_uri_parameter(). */ assert( (flags & SQLITE_OPEN_URI) || zName[strlen(zName)+1]==0 ); }else if( !zName ){ /* If zName is NULL, the upper layer is requesting a temp file. */ assert(isDelete && !syncDir); rc = unixGetTempname(pVfs->mxPathname, zTmpname); if( rc!=SQLITE_OK ){ return rc; } zName = zTmpname; /* Generated temporary filenames are always double-zero terminated ** for use by sqlite3_uri_parameter(). */ assert( zName[strlen(zName)+1]==0 ); } /* Determine the value of the flags parameter passed to POSIX function ** open(). These must be calculated even if open() is not called, as ** they may be stored as part of the file handle and used by the ** 'conch file' locking functions later on. */ if( isReadonly ) openFlags |= O_RDONLY; if( isReadWrite ) openFlags |= O_RDWR; if( isCreate ) openFlags |= O_CREAT; if( isExclusive ) openFlags |= (O_EXCL|O_NOFOLLOW); openFlags |= (O_LARGEFILE|O_BINARY); if( fd<0 ){ mode_t openMode; /* Permissions to create file with */ uid_t uid; /* Userid for the file */ gid_t gid; /* Groupid for the file */ rc = findCreateFileMode(zName, flags, &openMode, &uid, &gid); if( rc!=SQLITE_OK ){ assert( !p->pUnused ); assert( eType==SQLITE_OPEN_WAL || eType==SQLITE_OPEN_MAIN_JOURNAL ); return rc; } fd = robust_open(zName, openFlags, openMode); OSTRACE(("OPENX %-3d %s 0%o\n", fd, zName, openFlags)); assert( !isExclusive || (openFlags & O_CREAT)!=0 ); if( fd<0 && errno!=EISDIR && isReadWrite ){ /* Failed to open the file for read/write access. Try read-only. */ flags &= ~(SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE); openFlags &= ~(O_RDWR|O_CREAT); flags |= SQLITE_OPEN_READONLY; openFlags |= O_RDONLY; isReadonly = 1; fd = robust_open(zName, openFlags, openMode); } if( fd<0 ){ rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zName); goto open_finished; } /* If this process is running as root and if creating a new rollback ** journal or WAL file, set the ownership of the journal or WAL to be ** the same as the original database. */ if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){ robustFchown(fd, uid, gid); } } assert( fd>=0 ); if( pOutFlags ){ *pOutFlags = flags; } if( p->pUnused ){ p->pUnused->fd = fd; p->pUnused->flags = flags; } if( isDelete ){ #if OS_VXWORKS zPath = zName; #elif defined(SQLITE_UNLINK_AFTER_CLOSE) zPath = sqlite3_mprintf("%s", zName); if( zPath==0 ){ robust_close(p, fd, __LINE__); return SQLITE_NOMEM_BKPT; } #else osUnlink(zName); #endif } #if SQLITE_ENABLE_LOCKING_STYLE else{ p->openFlags = openFlags; } #endif #if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE if( fstatfs(fd, &fsInfo) == -1 ){ storeLastErrno(p, errno); robust_close(p, fd, __LINE__); return SQLITE_IOERR_ACCESS; } if (0 == strncmp("msdos", fsInfo.f_fstypename, 5)) { ((unixFile*)pFile)->fsFlags |= SQLITE_FSFLAGS_IS_MSDOS; } if (0 == strncmp("exfat", fsInfo.f_fstypename, 5)) { ((unixFile*)pFile)->fsFlags |= SQLITE_FSFLAGS_IS_MSDOS; } #endif /* Set up appropriate ctrlFlags */ if( isDelete ) ctrlFlags |= UNIXFILE_DELETE; if( isReadonly ) ctrlFlags |= UNIXFILE_RDONLY; noLock = eType!=SQLITE_OPEN_MAIN_DB; if( noLock ) ctrlFlags |= UNIXFILE_NOLOCK; if( syncDir ) ctrlFlags |= UNIXFILE_DIRSYNC; if( flags & SQLITE_OPEN_URI ) ctrlFlags |= UNIXFILE_URI; #if SQLITE_ENABLE_LOCKING_STYLE #if SQLITE_PREFER_PROXY_LOCKING isAutoProxy = 1; #endif if( isAutoProxy && (zPath!=NULL) && (!noLock) && pVfs->xOpen ){ char *envforce = getenv("SQLITE_FORCE_PROXY_LOCKING"); int useProxy = 0; /* SQLITE_FORCE_PROXY_LOCKING==1 means force always use proxy, 0 means ** never use proxy, NULL means use proxy for non-local files only. */ if( envforce!=NULL ){ useProxy = atoi(envforce)>0; }else{ useProxy = !(fsInfo.f_flags&MNT_LOCAL); } if( useProxy ){ rc = fillInUnixFile(pVfs, fd, pFile, zPath, ctrlFlags); if( rc==SQLITE_OK ){ rc = proxyTransformUnixFile((unixFile*)pFile, ":auto:"); if( rc!=SQLITE_OK ){ /* Use unixClose to clean up the resources added in fillInUnixFile ** and clear all the structure's references. Specifically, ** pFile->pMethods will be NULL so sqlite3OsClose will be a no-op */ unixClose(pFile); return rc; } } goto open_finished; } } #endif rc = fillInUnixFile(pVfs, fd, pFile, zPath, ctrlFlags); open_finished: if( rc!=SQLITE_OK ){ sqlite3_free(p->pUnused); } return rc; } /* ** Delete the file at zPath. If the dirSync argument is true, fsync() ** the directory after deleting the file. */ static int unixDelete( sqlite3_vfs *NotUsed, /* VFS containing this as the xDelete method */ const char *zPath, /* Name of file to be deleted */ int dirSync /* If true, fsync() directory after deleting file */ ){ int rc = SQLITE_OK; UNUSED_PARAMETER(NotUsed); SimulateIOError(return SQLITE_IOERR_DELETE); if( osUnlink(zPath)==(-1) ){ if( errno==ENOENT #if OS_VXWORKS || osAccess(zPath,0)!=0 #endif ){ rc = SQLITE_IOERR_DELETE_NOENT; }else{ rc = unixLogError(SQLITE_IOERR_DELETE, "unlink", zPath); } return rc; } #ifndef SQLITE_DISABLE_DIRSYNC if( (dirSync & 1)!=0 ){ int fd; rc = osOpenDirectory(zPath, &fd); if( rc==SQLITE_OK ){ if( full_fsync(fd,0,0) ){ rc = unixLogError(SQLITE_IOERR_DIR_FSYNC, "fsync", zPath); } robust_close(0, fd, __LINE__); }else{ assert( rc==SQLITE_CANTOPEN ); rc = SQLITE_OK; } } #endif return rc; } /* ** Test the existence of or access permissions of file zPath. The ** test performed depends on the value of flags: ** ** SQLITE_ACCESS_EXISTS: Return 1 if the file exists ** SQLITE_ACCESS_READWRITE: Return 1 if the file is read and writable. ** SQLITE_ACCESS_READONLY: Return 1 if the file is readable. ** ** Otherwise return 0. */ static int unixAccess( sqlite3_vfs *NotUsed, /* The VFS containing this xAccess method */ const char *zPath, /* Path of the file to examine */ int flags, /* What do we want to learn about the zPath file? */ int *pResOut /* Write result boolean here */ ){ UNUSED_PARAMETER(NotUsed); SimulateIOError( return SQLITE_IOERR_ACCESS; ); assert( pResOut!=0 ); /* The spec says there are three possible values for flags. But only ** two of them are actually used */ assert( flags==SQLITE_ACCESS_EXISTS || flags==SQLITE_ACCESS_READWRITE ); if( flags==SQLITE_ACCESS_EXISTS ){ struct stat buf; *pResOut = (0==osStat(zPath, &buf) && buf.st_size>0); }else{ *pResOut = osAccess(zPath, W_OK|R_OK)==0; } return SQLITE_OK; } /* ** */ static int mkFullPathname( const char *zPath, /* Input path */ char *zOut, /* Output buffer */ int nOut /* Allocated size of buffer zOut */ ){ int nPath = sqlite3Strlen30(zPath); int iOff = 0; if( zPath[0]!='/' ){ if( osGetcwd(zOut, nOut-2)==0 ){ return unixLogError(SQLITE_CANTOPEN_BKPT, "getcwd", zPath); } iOff = sqlite3Strlen30(zOut); zOut[iOff++] = '/'; } if( (iOff+nPath+1)>nOut ){ /* SQLite assumes that xFullPathname() nul-terminates the output buffer ** even if it returns an error. */ zOut[iOff] = '\0'; return SQLITE_CANTOPEN_BKPT; } sqlite3_snprintf(nOut-iOff, &zOut[iOff], "%s", zPath); return SQLITE_OK; } /* ** Turn a relative pathname into a full pathname. The relative path ** is stored as a nul-terminated string in the buffer pointed to by ** zPath. ** ** zOut points to a buffer of at least sqlite3_vfs.mxPathname bytes ** (in this case, MAX_PATHNAME bytes). The full-path is written to ** this buffer before returning. */ static int unixFullPathname( sqlite3_vfs *pVfs, /* Pointer to vfs object */ const char *zPath, /* Possibly relative input path */ int nOut, /* Size of output buffer in bytes */ char *zOut /* Output buffer */ ){ #if !defined(HAVE_READLINK) || !defined(HAVE_LSTAT) return mkFullPathname(zPath, zOut, nOut); #else int rc = SQLITE_OK; int nByte; int nLink = 1; /* Number of symbolic links followed so far */ const char *zIn = zPath; /* Input path for each iteration of loop */ char *zDel = 0; assert( pVfs->mxPathname==MAX_PATHNAME ); UNUSED_PARAMETER(pVfs); /* It's odd to simulate an io-error here, but really this is just ** using the io-error infrastructure to test that SQLite handles this ** function failing. This function could fail if, for example, the ** current working directory has been unlinked. */ SimulateIOError( return SQLITE_ERROR ); do { /* Call stat() on path zIn. Set bLink to true if the path is a symbolic ** link, or false otherwise. */ int bLink = 0; struct stat buf; if( osLstat(zIn, &buf)!=0 ){ if( errno!=ENOENT ){ rc = unixLogError(SQLITE_CANTOPEN_BKPT, "lstat", zIn); } }else{ bLink = S_ISLNK(buf.st_mode); } if( bLink ){ if( zDel==0 ){ zDel = sqlite3_malloc(nOut); if( zDel==0 ) rc = SQLITE_NOMEM_BKPT; }else if( ++nLink>SQLITE_MAX_SYMLINKS ){ rc = SQLITE_CANTOPEN_BKPT; } if( rc==SQLITE_OK ){ nByte = osReadlink(zIn, zDel, nOut-1); if( nByte<0 ){ rc = unixLogError(SQLITE_CANTOPEN_BKPT, "readlink", zIn); }else{ if( zDel[0]!='/' ){ int n; for(n = sqlite3Strlen30(zIn); n>0 && zIn[n-1]!='/'; n--); if( nByte+n+1>nOut ){ rc = SQLITE_CANTOPEN_BKPT; }else{ memmove(&zDel[n], zDel, nByte+1); memcpy(zDel, zIn, n); nByte += n; } } zDel[nByte] = '\0'; } } zIn = zDel; } assert( rc!=SQLITE_OK || zIn!=zOut || zIn[0]=='/' ); if( rc==SQLITE_OK && zIn!=zOut ){ rc = mkFullPathname(zIn, zOut, nOut); } if( bLink==0 ) break; zIn = zOut; }while( rc==SQLITE_OK ); sqlite3_free(zDel); return rc; #endif /* HAVE_READLINK && HAVE_LSTAT */ } #ifndef SQLITE_OMIT_LOAD_EXTENSION /* ** Interfaces for opening a shared library, finding entry points ** within the shared library, and closing the shared library. */ #include static void *unixDlOpen(sqlite3_vfs *NotUsed, const char *zFilename){ UNUSED_PARAMETER(NotUsed); return dlopen(zFilename, RTLD_NOW | RTLD_GLOBAL); } /* ** SQLite calls this function immediately after a call to unixDlSym() or ** unixDlOpen() fails (returns a null pointer). If a more detailed error ** message is available, it is written to zBufOut. If no error message ** is available, zBufOut is left unmodified and SQLite uses a default ** error message. */ static void unixDlError(sqlite3_vfs *NotUsed, int nBuf, char *zBufOut){ const char *zErr; UNUSED_PARAMETER(NotUsed); unixEnterMutex(); zErr = dlerror(); if( zErr ){ sqlite3_snprintf(nBuf, zBufOut, "%s", zErr); } unixLeaveMutex(); } static void (*unixDlSym(sqlite3_vfs *NotUsed, void *p, const char*zSym))(void){ /* ** GCC with -pedantic-errors says that C90 does not allow a void* to be ** cast into a pointer to a function. And yet the library dlsym() routine ** returns a void* which is really a pointer to a function. So how do we ** use dlsym() with -pedantic-errors? ** ** Variable x below is defined to be a pointer to a function taking ** parameters void* and const char* and returning a pointer to a function. ** We initialize x by assigning it a pointer to the dlsym() function. ** (That assignment requires a cast.) Then we call the function that ** x points to. ** ** This work-around is unlikely to work correctly on any system where ** you really cannot cast a function pointer into void*. But then, on the ** other hand, dlsym() will not work on such a system either, so we have ** not really lost anything. */ void (*(*x)(void*,const char*))(void); UNUSED_PARAMETER(NotUsed); x = (void(*(*)(void*,const char*))(void))dlsym; return (*x)(p, zSym); } static void unixDlClose(sqlite3_vfs *NotUsed, void *pHandle){ UNUSED_PARAMETER(NotUsed); dlclose(pHandle); } #else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */ #define unixDlOpen 0 #define unixDlError 0 #define unixDlSym 0 #define unixDlClose 0 #endif /* ** Write nBuf bytes of random data to the supplied buffer zBuf. */ static int unixRandomness(sqlite3_vfs *NotUsed, int nBuf, char *zBuf){ UNUSED_PARAMETER(NotUsed); assert((size_t)nBuf>=(sizeof(time_t)+sizeof(int))); /* We have to initialize zBuf to prevent valgrind from reporting ** errors. The reports issued by valgrind are incorrect - we would ** prefer that the randomness be increased by making use of the ** uninitialized space in zBuf - but valgrind errors tend to worry ** some users. Rather than argue, it seems easier just to initialize ** the whole array and silence valgrind, even if that means less randomness ** in the random seed. ** ** When testing, initializing zBuf[] to zero is all we do. That means ** that we always use the same random number sequence. This makes the ** tests repeatable. */ memset(zBuf, 0, nBuf); randomnessPid = osGetpid(0); #if !defined(SQLITE_TEST) && !defined(SQLITE_OMIT_RANDOMNESS) { int fd, got; fd = robust_open("/dev/urandom", O_RDONLY, 0); if( fd<0 ){ time_t t; time(&t); memcpy(zBuf, &t, sizeof(t)); memcpy(&zBuf[sizeof(t)], &randomnessPid, sizeof(randomnessPid)); assert( sizeof(t)+sizeof(randomnessPid)<=(size_t)nBuf ); nBuf = sizeof(t) + sizeof(randomnessPid); }else{ do{ got = osRead(fd, zBuf, nBuf); }while( got<0 && errno==EINTR ); robust_close(0, fd, __LINE__); } } #endif return nBuf; } /* ** Sleep for a little while. Return the amount of time slept. ** The argument is the number of microseconds we want to sleep. ** The return value is the number of microseconds of sleep actually ** requested from the underlying operating system, a number which ** might be greater than or equal to the argument, but not less ** than the argument. */ static int unixSleep(sqlite3_vfs *NotUsed, int microseconds){ #if OS_VXWORKS struct timespec sp; sp.tv_sec = microseconds / 1000000; sp.tv_nsec = (microseconds % 1000000) * 1000; nanosleep(&sp, NULL); UNUSED_PARAMETER(NotUsed); return microseconds; #elif defined(HAVE_USLEEP) && HAVE_USLEEP usleep(microseconds); UNUSED_PARAMETER(NotUsed); return microseconds; #else int seconds = (microseconds+999999)/1000000; sleep(seconds); UNUSED_PARAMETER(NotUsed); return seconds*1000000; #endif } /* ** The following variable, if set to a non-zero value, is interpreted as ** the number of seconds since 1970 and is used to set the result of ** sqlite3OsCurrentTime() during testing. */ #ifdef SQLITE_TEST SQLITE_API int sqlite3_current_time = 0; /* Fake system time in seconds since 1970. */ #endif /* ** Find the current time (in Universal Coordinated Time). Write into *piNow ** the current time and date as a Julian Day number times 86_400_000. In ** other words, write into *piNow the number of milliseconds since the Julian ** epoch of noon in Greenwich on November 24, 4714 B.C according to the ** proleptic Gregorian calendar. ** ** On success, return SQLITE_OK. Return SQLITE_ERROR if the time and date ** cannot be found. */ static int unixCurrentTimeInt64(sqlite3_vfs *NotUsed, sqlite3_int64 *piNow){ static const sqlite3_int64 unixEpoch = 24405875*(sqlite3_int64)8640000; int rc = SQLITE_OK; #if defined(NO_GETTOD) time_t t; time(&t); *piNow = ((sqlite3_int64)t)*1000 + unixEpoch; #elif OS_VXWORKS struct timespec sNow; clock_gettime(CLOCK_REALTIME, &sNow); *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_nsec/1000000; #else struct timeval sNow; (void)gettimeofday(&sNow, 0); /* Cannot fail given valid arguments */ *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_usec/1000; #endif #ifdef SQLITE_TEST if( sqlite3_current_time ){ *piNow = 1000*(sqlite3_int64)sqlite3_current_time + unixEpoch; } #endif UNUSED_PARAMETER(NotUsed); return rc; } #ifndef SQLITE_OMIT_DEPRECATED /* ** Find the current time (in Universal Coordinated Time). Write the ** current time and date as a Julian Day number into *prNow and ** return 0. Return 1 if the time and date cannot be found. */ static int unixCurrentTime(sqlite3_vfs *NotUsed, double *prNow){ sqlite3_int64 i = 0; int rc; UNUSED_PARAMETER(NotUsed); rc = unixCurrentTimeInt64(0, &i); *prNow = i/86400000.0; return rc; } #else # define unixCurrentTime 0 #endif /* ** The xGetLastError() method is designed to return a better ** low-level error message when operating-system problems come up ** during SQLite operation. Only the integer return code is currently ** used. */ static int unixGetLastError(sqlite3_vfs *NotUsed, int NotUsed2, char *NotUsed3){ UNUSED_PARAMETER(NotUsed); UNUSED_PARAMETER(NotUsed2); UNUSED_PARAMETER(NotUsed3); return errno; } /* ************************ End of sqlite3_vfs methods *************************** ******************************************************************************/ /****************************************************************************** ************************** Begin Proxy Locking ******************************** ** ** Proxy locking is a "uber-locking-method" in this sense: It uses the ** other locking methods on secondary lock files. Proxy locking is a ** meta-layer over top of the primitive locking implemented above. For ** this reason, the division that implements of proxy locking is deferred ** until late in the file (here) after all of the other I/O methods have ** been defined - so that the primitive locking methods are available ** as services to help with the implementation of proxy locking. ** **** ** ** The default locking schemes in SQLite use byte-range locks on the ** database file to coordinate safe, concurrent access by multiple readers ** and writers [http://sqlite.org/lockingv3.html]. The five file locking ** states (UNLOCKED, PENDING, SHARED, RESERVED, EXCLUSIVE) are implemented ** as POSIX read & write locks over fixed set of locations (via fsctl), ** on AFP and SMB only exclusive byte-range locks are available via fsctl ** with _IOWR('z', 23, struct ByteRangeLockPB2) to track the same 5 states. ** To simulate a F_RDLCK on the shared range, on AFP a randomly selected ** address in the shared range is taken for a SHARED lock, the entire ** shared range is taken for an EXCLUSIVE lock): ** ** PENDING_BYTE 0x40000000 ** RESERVED_BYTE 0x40000001 ** SHARED_RANGE 0x40000002 -> 0x40000200 ** ** This works well on the local file system, but shows a nearly 100x ** slowdown in read performance on AFP because the AFP client disables ** the read cache when byte-range locks are present. Enabling the read ** cache exposes a cache coherency problem that is present on all OS X ** supported network file systems. NFS and AFP both observe the ** close-to-open semantics for ensuring cache coherency ** [http://nfs.sourceforge.net/#faq_a8], which does not effectively ** address the requirements for concurrent database access by multiple ** readers and writers ** [http://www.nabble.com/SQLite-on-NFS-cache-coherency-td15655701.html]. ** ** To address the performance and cache coherency issues, proxy file locking ** changes the way database access is controlled by limiting access to a ** single host at a time and moving file locks off of the database file ** and onto a proxy file on the local file system. ** ** ** Using proxy locks ** ----------------- ** ** C APIs ** ** sqlite3_file_control(db, dbname, SQLITE_FCNTL_SET_LOCKPROXYFILE, ** | ":auto:"); ** sqlite3_file_control(db, dbname, SQLITE_FCNTL_GET_LOCKPROXYFILE, ** &); ** ** ** SQL pragmas ** ** PRAGMA [database.]lock_proxy_file= | :auto: ** PRAGMA [database.]lock_proxy_file ** ** Specifying ":auto:" means that if there is a conch file with a matching ** host ID in it, the proxy path in the conch file will be used, otherwise ** a proxy path based on the user's temp dir ** (via confstr(_CS_DARWIN_USER_TEMP_DIR,...)) will be used and the ** actual proxy file name is generated from the name and path of the ** database file. For example: ** ** For database path "/Users/me/foo.db" ** The lock path will be "/sqliteplocks/_Users_me_foo.db:auto:") ** ** Once a lock proxy is configured for a database connection, it can not ** be removed, however it may be switched to a different proxy path via ** the above APIs (assuming the conch file is not being held by another ** connection or process). ** ** ** How proxy locking works ** ----------------------- ** ** Proxy file locking relies primarily on two new supporting files: ** ** * conch file to limit access to the database file to a single host ** at a time ** ** * proxy file to act as a proxy for the advisory locks normally ** taken on the database ** ** The conch file - to use a proxy file, sqlite must first "hold the conch" ** by taking an sqlite-style shared lock on the conch file, reading the ** contents and comparing the host's unique host ID (see below) and lock ** proxy path against the values stored in the conch. The conch file is ** stored in the same directory as the database file and the file name ** is patterned after the database file name as ".-conch". ** If the conch file does not exist, or its contents do not match the ** host ID and/or proxy path, then the lock is escalated to an exclusive ** lock and the conch file contents is updated with the host ID and proxy ** path and the lock is downgraded to a shared lock again. If the conch ** is held by another process (with a shared lock), the exclusive lock ** will fail and SQLITE_BUSY is returned. ** ** The proxy file - a single-byte file used for all advisory file locks ** normally taken on the database file. This allows for safe sharing ** of the database file for multiple readers and writers on the same ** host (the conch ensures that they all use the same local lock file). ** ** Requesting the lock proxy does not immediately take the conch, it is ** only taken when the first request to lock database file is made. ** This matches the semantics of the traditional locking behavior, where ** opening a connection to a database file does not take a lock on it. ** The shared lock and an open file descriptor are maintained until ** the connection to the database is closed. ** ** The proxy file and the lock file are never deleted so they only need ** to be created the first time they are used. ** ** Configuration options ** --------------------- ** ** SQLITE_PREFER_PROXY_LOCKING ** ** Database files accessed on non-local file systems are ** automatically configured for proxy locking, lock files are ** named automatically using the same logic as ** PRAGMA lock_proxy_file=":auto:" ** ** SQLITE_PROXY_DEBUG ** ** Enables the logging of error messages during host id file ** retrieval and creation ** ** LOCKPROXYDIR ** ** Overrides the default directory used for lock proxy files that ** are named automatically via the ":auto:" setting ** ** SQLITE_DEFAULT_PROXYDIR_PERMISSIONS ** ** Permissions to use when creating a directory for storing the ** lock proxy files, only used when LOCKPROXYDIR is not set. ** ** ** As mentioned above, when compiled with SQLITE_PREFER_PROXY_LOCKING, ** setting the environment variable SQLITE_FORCE_PROXY_LOCKING to 1 will ** force proxy locking to be used for every database file opened, and 0 ** will force automatic proxy locking to be disabled for all database ** files (explicitly calling the SQLITE_FCNTL_SET_LOCKPROXYFILE pragma or ** sqlite_file_control API is not affected by SQLITE_FORCE_PROXY_LOCKING). */ /* ** Proxy locking is only available on MacOSX */ #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE /* ** The proxyLockingContext has the path and file structures for the remote ** and local proxy files in it */ typedef struct proxyLockingContext proxyLockingContext; struct proxyLockingContext { unixFile *conchFile; /* Open conch file */ char *conchFilePath; /* Name of the conch file */ unixFile *lockProxy; /* Open proxy lock file */ char *lockProxyPath; /* Name of the proxy lock file */ char *dbPath; /* Name of the open file */ int conchHeld; /* 1 if the conch is held, -1 if lockless */ int nFails; /* Number of conch taking failures */ void *oldLockingContext; /* Original lockingcontext to restore on close */ sqlite3_io_methods const *pOldMethod; /* Original I/O methods for close */ }; /* ** The proxy lock file path for the database at dbPath is written into lPath, ** which must point to valid, writable memory large enough for a maxLen length ** file path. */ static int proxyGetLockPath(const char *dbPath, char *lPath, size_t maxLen){ int len; int dbLen; int i; #ifdef LOCKPROXYDIR len = strlcpy(lPath, LOCKPROXYDIR, maxLen); #else # ifdef _CS_DARWIN_USER_TEMP_DIR { if( !confstr(_CS_DARWIN_USER_TEMP_DIR, lPath, maxLen) ){ OSTRACE(("GETLOCKPATH failed %s errno=%d pid=%d\n", lPath, errno, osGetpid(0))); return SQLITE_IOERR_LOCK; } len = strlcat(lPath, "sqliteplocks", maxLen); } # else len = strlcpy(lPath, "/tmp/", maxLen); # endif #endif if( lPath[len-1]!='/' ){ len = strlcat(lPath, "/", maxLen); } /* transform the db path to a unique cache name */ dbLen = (int)strlen(dbPath); for( i=0; i 0) ){ /* only mkdir if leaf dir != "." or "/" or ".." */ if( i-start>2 || (i-start==1 && buf[start] != '.' && buf[start] != '/') || (i-start==2 && buf[start] != '.' && buf[start+1] != '.') ){ buf[i]='\0'; if( osMkdir(buf, SQLITE_DEFAULT_PROXYDIR_PERMISSIONS) ){ int err=errno; if( err!=EEXIST ) { OSTRACE(("CREATELOCKPATH FAILED creating %s, " "'%s' proxy lock path=%s pid=%d\n", buf, strerror(err), lockPath, osGetpid(0))); return err; } } } start=i+1; } buf[i] = lockPath[i]; } OSTRACE(("CREATELOCKPATH proxy lock path=%s pid=%d\n",lockPath,osGetpid(0))); return 0; } /* ** Create a new VFS file descriptor (stored in memory obtained from ** sqlite3_malloc) and open the file named "path" in the file descriptor. ** ** The caller is responsible not only for closing the file descriptor ** but also for freeing the memory associated with the file descriptor. */ static int proxyCreateUnixFile( const char *path, /* path for the new unixFile */ unixFile **ppFile, /* unixFile created and returned by ref */ int islockfile /* if non zero missing dirs will be created */ ) { int fd = -1; unixFile *pNew; int rc = SQLITE_OK; int openFlags = O_RDWR | O_CREAT; sqlite3_vfs dummyVfs; int terrno = 0; UnixUnusedFd *pUnused = NULL; /* 1. first try to open/create the file ** 2. if that fails, and this is a lock file (not-conch), try creating ** the parent directories and then try again. ** 3. if that fails, try to open the file read-only ** otherwise return BUSY (if lock file) or CANTOPEN for the conch file */ pUnused = findReusableFd(path, openFlags); if( pUnused ){ fd = pUnused->fd; }else{ pUnused = sqlite3_malloc64(sizeof(*pUnused)); if( !pUnused ){ return SQLITE_NOMEM_BKPT; } } if( fd<0 ){ fd = robust_open(path, openFlags, 0); terrno = errno; if( fd<0 && errno==ENOENT && islockfile ){ if( proxyCreateLockPath(path) == SQLITE_OK ){ fd = robust_open(path, openFlags, 0); } } } if( fd<0 ){ openFlags = O_RDONLY; fd = robust_open(path, openFlags, 0); terrno = errno; } if( fd<0 ){ if( islockfile ){ return SQLITE_BUSY; } switch (terrno) { case EACCES: return SQLITE_PERM; case EIO: return SQLITE_IOERR_LOCK; /* even though it is the conch */ default: return SQLITE_CANTOPEN_BKPT; } } pNew = (unixFile *)sqlite3_malloc64(sizeof(*pNew)); if( pNew==NULL ){ rc = SQLITE_NOMEM_BKPT; goto end_create_proxy; } memset(pNew, 0, sizeof(unixFile)); pNew->openFlags = openFlags; memset(&dummyVfs, 0, sizeof(dummyVfs)); dummyVfs.pAppData = (void*)&autolockIoFinder; dummyVfs.zName = "dummy"; pUnused->fd = fd; pUnused->flags = openFlags; pNew->pUnused = pUnused; rc = fillInUnixFile(&dummyVfs, fd, (sqlite3_file*)pNew, path, 0); if( rc==SQLITE_OK ){ *ppFile = pNew; return SQLITE_OK; } end_create_proxy: robust_close(pNew, fd, __LINE__); sqlite3_free(pNew); sqlite3_free(pUnused); return rc; } #ifdef SQLITE_TEST /* simulate multiple hosts by creating unique hostid file paths */ SQLITE_API int sqlite3_hostid_num = 0; #endif #define PROXY_HOSTIDLEN 16 /* conch file host id length */ #ifdef HAVE_GETHOSTUUID /* Not always defined in the headers as it ought to be */ extern int gethostuuid(uuid_t id, const struct timespec *wait); #endif /* get the host ID via gethostuuid(), pHostID must point to PROXY_HOSTIDLEN ** bytes of writable memory. */ static int proxyGetHostID(unsigned char *pHostID, int *pError){ assert(PROXY_HOSTIDLEN == sizeof(uuid_t)); memset(pHostID, 0, PROXY_HOSTIDLEN); #ifdef HAVE_GETHOSTUUID { struct timespec timeout = {1, 0}; /* 1 sec timeout */ if( gethostuuid(pHostID, &timeout) ){ int err = errno; if( pError ){ *pError = err; } return SQLITE_IOERR; } } #else UNUSED_PARAMETER(pError); #endif #ifdef SQLITE_TEST /* simulate multiple hosts by creating unique hostid file paths */ if( sqlite3_hostid_num != 0){ pHostID[0] = (char)(pHostID[0] + (char)(sqlite3_hostid_num & 0xFF)); } #endif return SQLITE_OK; } /* The conch file contains the header, host id and lock file path */ #define PROXY_CONCHVERSION 2 /* 1-byte header, 16-byte host id, path */ #define PROXY_HEADERLEN 1 /* conch file header length */ #define PROXY_PATHINDEX (PROXY_HEADERLEN+PROXY_HOSTIDLEN) #define PROXY_MAXCONCHLEN (PROXY_HEADERLEN+PROXY_HOSTIDLEN+MAXPATHLEN) /* ** Takes an open conch file, copies the contents to a new path and then moves ** it back. The newly created file's file descriptor is assigned to the ** conch file structure and finally the original conch file descriptor is ** closed. Returns zero if successful. */ static int proxyBreakConchLock(unixFile *pFile, uuid_t myHostID){ proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext; unixFile *conchFile = pCtx->conchFile; char tPath[MAXPATHLEN]; char buf[PROXY_MAXCONCHLEN]; char *cPath = pCtx->conchFilePath; size_t readLen = 0; size_t pathLen = 0; char errmsg[64] = ""; int fd = -1; int rc = -1; UNUSED_PARAMETER(myHostID); /* create a new path by replace the trailing '-conch' with '-break' */ pathLen = strlcpy(tPath, cPath, MAXPATHLEN); if( pathLen>MAXPATHLEN || pathLen<6 || (strlcpy(&tPath[pathLen-5], "break", 6) != 5) ){ sqlite3_snprintf(sizeof(errmsg),errmsg,"path error (len %d)",(int)pathLen); goto end_breaklock; } /* read the conch content */ readLen = osPread(conchFile->h, buf, PROXY_MAXCONCHLEN, 0); if( readLenh, __LINE__); conchFile->h = fd; conchFile->openFlags = O_RDWR | O_CREAT; end_breaklock: if( rc ){ if( fd>=0 ){ osUnlink(tPath); robust_close(pFile, fd, __LINE__); } fprintf(stderr, "failed to break stale lock on %s, %s\n", cPath, errmsg); } return rc; } /* Take the requested lock on the conch file and break a stale lock if the ** host id matches. */ static int proxyConchLock(unixFile *pFile, uuid_t myHostID, int lockType){ proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext; unixFile *conchFile = pCtx->conchFile; int rc = SQLITE_OK; int nTries = 0; struct timespec conchModTime; memset(&conchModTime, 0, sizeof(conchModTime)); do { rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType); nTries ++; if( rc==SQLITE_BUSY ){ /* If the lock failed (busy): * 1st try: get the mod time of the conch, wait 0.5s and try again. * 2nd try: fail if the mod time changed or host id is different, wait * 10 sec and try again * 3rd try: break the lock unless the mod time has changed. */ struct stat buf; if( osFstat(conchFile->h, &buf) ){ storeLastErrno(pFile, errno); return SQLITE_IOERR_LOCK; } if( nTries==1 ){ conchModTime = buf.st_mtimespec; usleep(500000); /* wait 0.5 sec and try the lock again*/ continue; } assert( nTries>1 ); if( conchModTime.tv_sec != buf.st_mtimespec.tv_sec || conchModTime.tv_nsec != buf.st_mtimespec.tv_nsec ){ return SQLITE_BUSY; } if( nTries==2 ){ char tBuf[PROXY_MAXCONCHLEN]; int len = osPread(conchFile->h, tBuf, PROXY_MAXCONCHLEN, 0); if( len<0 ){ storeLastErrno(pFile, errno); return SQLITE_IOERR_LOCK; } if( len>PROXY_PATHINDEX && tBuf[0]==(char)PROXY_CONCHVERSION){ /* don't break the lock if the host id doesn't match */ if( 0!=memcmp(&tBuf[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN) ){ return SQLITE_BUSY; } }else{ /* don't break the lock on short read or a version mismatch */ return SQLITE_BUSY; } usleep(10000000); /* wait 10 sec and try the lock again */ continue; } assert( nTries==3 ); if( 0==proxyBreakConchLock(pFile, myHostID) ){ rc = SQLITE_OK; if( lockType==EXCLUSIVE_LOCK ){ rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, SHARED_LOCK); } if( !rc ){ rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType); } } } } while( rc==SQLITE_BUSY && nTries<3 ); return rc; } /* Takes the conch by taking a shared lock and read the contents conch, if ** lockPath is non-NULL, the host ID and lock file path must match. A NULL ** lockPath means that the lockPath in the conch file will be used if the ** host IDs match, or a new lock path will be generated automatically ** and written to the conch file. */ static int proxyTakeConch(unixFile *pFile){ proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext; if( pCtx->conchHeld!=0 ){ return SQLITE_OK; }else{ unixFile *conchFile = pCtx->conchFile; uuid_t myHostID; int pError = 0; char readBuf[PROXY_MAXCONCHLEN]; char lockPath[MAXPATHLEN]; char *tempLockPath = NULL; int rc = SQLITE_OK; int createConch = 0; int hostIdMatch = 0; int readLen = 0; int tryOldLockPath = 0; int forceNewLockPath = 0; OSTRACE(("TAKECONCH %d for %s pid=%d\n", conchFile->h, (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"), osGetpid(0))); rc = proxyGetHostID(myHostID, &pError); if( (rc&0xff)==SQLITE_IOERR ){ storeLastErrno(pFile, pError); goto end_takeconch; } rc = proxyConchLock(pFile, myHostID, SHARED_LOCK); if( rc!=SQLITE_OK ){ goto end_takeconch; } /* read the existing conch file */ readLen = seekAndRead((unixFile*)conchFile, 0, readBuf, PROXY_MAXCONCHLEN); if( readLen<0 ){ /* I/O error: lastErrno set by seekAndRead */ storeLastErrno(pFile, conchFile->lastErrno); rc = SQLITE_IOERR_READ; goto end_takeconch; }else if( readLen<=(PROXY_HEADERLEN+PROXY_HOSTIDLEN) || readBuf[0]!=(char)PROXY_CONCHVERSION ){ /* a short read or version format mismatch means we need to create a new ** conch file. */ createConch = 1; } /* if the host id matches and the lock path already exists in the conch ** we'll try to use the path there, if we can't open that path, we'll ** retry with a new auto-generated path */ do { /* in case we need to try again for an :auto: named lock file */ if( !createConch && !forceNewLockPath ){ hostIdMatch = !memcmp(&readBuf[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN); /* if the conch has data compare the contents */ if( !pCtx->lockProxyPath ){ /* for auto-named local lock file, just check the host ID and we'll ** use the local lock file path that's already in there */ if( hostIdMatch ){ size_t pathLen = (readLen - PROXY_PATHINDEX); if( pathLen>=MAXPATHLEN ){ pathLen=MAXPATHLEN-1; } memcpy(lockPath, &readBuf[PROXY_PATHINDEX], pathLen); lockPath[pathLen] = 0; tempLockPath = lockPath; tryOldLockPath = 1; /* create a copy of the lock path if the conch is taken */ goto end_takeconch; } }else if( hostIdMatch && !strncmp(pCtx->lockProxyPath, &readBuf[PROXY_PATHINDEX], readLen-PROXY_PATHINDEX) ){ /* conch host and lock path match */ goto end_takeconch; } } /* if the conch isn't writable and doesn't match, we can't take it */ if( (conchFile->openFlags&O_RDWR) == 0 ){ rc = SQLITE_BUSY; goto end_takeconch; } /* either the conch didn't match or we need to create a new one */ if( !pCtx->lockProxyPath ){ proxyGetLockPath(pCtx->dbPath, lockPath, MAXPATHLEN); tempLockPath = lockPath; /* create a copy of the lock path _only_ if the conch is taken */ } /* update conch with host and path (this will fail if other process ** has a shared lock already), if the host id matches, use the big ** stick. */ futimes(conchFile->h, NULL); if( hostIdMatch && !createConch ){ if( conchFile->pInode && conchFile->pInode->nShared>1 ){ /* We are trying for an exclusive lock but another thread in this ** same process is still holding a shared lock. */ rc = SQLITE_BUSY; } else { rc = proxyConchLock(pFile, myHostID, EXCLUSIVE_LOCK); } }else{ rc = proxyConchLock(pFile, myHostID, EXCLUSIVE_LOCK); } if( rc==SQLITE_OK ){ char writeBuffer[PROXY_MAXCONCHLEN]; int writeSize = 0; writeBuffer[0] = (char)PROXY_CONCHVERSION; memcpy(&writeBuffer[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN); if( pCtx->lockProxyPath!=NULL ){ strlcpy(&writeBuffer[PROXY_PATHINDEX], pCtx->lockProxyPath, MAXPATHLEN); }else{ strlcpy(&writeBuffer[PROXY_PATHINDEX], tempLockPath, MAXPATHLEN); } writeSize = PROXY_PATHINDEX + strlen(&writeBuffer[PROXY_PATHINDEX]); robust_ftruncate(conchFile->h, writeSize); rc = unixWrite((sqlite3_file *)conchFile, writeBuffer, writeSize, 0); full_fsync(conchFile->h,0,0); /* If we created a new conch file (not just updated the contents of a ** valid conch file), try to match the permissions of the database */ if( rc==SQLITE_OK && createConch ){ struct stat buf; int err = osFstat(pFile->h, &buf); if( err==0 ){ mode_t cmode = buf.st_mode&(S_IRUSR|S_IWUSR | S_IRGRP|S_IWGRP | S_IROTH|S_IWOTH); /* try to match the database file R/W permissions, ignore failure */ #ifndef SQLITE_PROXY_DEBUG osFchmod(conchFile->h, cmode); #else do{ rc = osFchmod(conchFile->h, cmode); }while( rc==(-1) && errno==EINTR ); if( rc!=0 ){ int code = errno; fprintf(stderr, "fchmod %o FAILED with %d %s\n", cmode, code, strerror(code)); } else { fprintf(stderr, "fchmod %o SUCCEDED\n",cmode); } }else{ int code = errno; fprintf(stderr, "STAT FAILED[%d] with %d %s\n", err, code, strerror(code)); #endif } } } conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, SHARED_LOCK); end_takeconch: OSTRACE(("TRANSPROXY: CLOSE %d\n", pFile->h)); if( rc==SQLITE_OK && pFile->openFlags ){ int fd; if( pFile->h>=0 ){ robust_close(pFile, pFile->h, __LINE__); } pFile->h = -1; fd = robust_open(pCtx->dbPath, pFile->openFlags, 0); OSTRACE(("TRANSPROXY: OPEN %d\n", fd)); if( fd>=0 ){ pFile->h = fd; }else{ rc=SQLITE_CANTOPEN_BKPT; /* SQLITE_BUSY? proxyTakeConch called during locking */ } } if( rc==SQLITE_OK && !pCtx->lockProxy ){ char *path = tempLockPath ? tempLockPath : pCtx->lockProxyPath; rc = proxyCreateUnixFile(path, &pCtx->lockProxy, 1); if( rc!=SQLITE_OK && rc!=SQLITE_NOMEM && tryOldLockPath ){ /* we couldn't create the proxy lock file with the old lock file path ** so try again via auto-naming */ forceNewLockPath = 1; tryOldLockPath = 0; continue; /* go back to the do {} while start point, try again */ } } if( rc==SQLITE_OK ){ /* Need to make a copy of path if we extracted the value ** from the conch file or the path was allocated on the stack */ if( tempLockPath ){ pCtx->lockProxyPath = sqlite3DbStrDup(0, tempLockPath); if( !pCtx->lockProxyPath ){ rc = SQLITE_NOMEM_BKPT; } } } if( rc==SQLITE_OK ){ pCtx->conchHeld = 1; if( pCtx->lockProxy->pMethod == &afpIoMethods ){ afpLockingContext *afpCtx; afpCtx = (afpLockingContext *)pCtx->lockProxy->lockingContext; afpCtx->dbPath = pCtx->lockProxyPath; } } else { conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK); } OSTRACE(("TAKECONCH %d %s\n", conchFile->h, rc==SQLITE_OK?"ok":"failed")); return rc; } while (1); /* in case we need to retry the :auto: lock file - ** we should never get here except via the 'continue' call. */ } } /* ** If pFile holds a lock on a conch file, then release that lock. */ static int proxyReleaseConch(unixFile *pFile){ int rc = SQLITE_OK; /* Subroutine return code */ proxyLockingContext *pCtx; /* The locking context for the proxy lock */ unixFile *conchFile; /* Name of the conch file */ pCtx = (proxyLockingContext *)pFile->lockingContext; conchFile = pCtx->conchFile; OSTRACE(("RELEASECONCH %d for %s pid=%d\n", conchFile->h, (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"), osGetpid(0))); if( pCtx->conchHeld>0 ){ rc = conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK); } pCtx->conchHeld = 0; OSTRACE(("RELEASECONCH %d %s\n", conchFile->h, (rc==SQLITE_OK ? "ok" : "failed"))); return rc; } /* ** Given the name of a database file, compute the name of its conch file. ** Store the conch filename in memory obtained from sqlite3_malloc64(). ** Make *pConchPath point to the new name. Return SQLITE_OK on success ** or SQLITE_NOMEM if unable to obtain memory. ** ** The caller is responsible for ensuring that the allocated memory ** space is eventually freed. ** ** *pConchPath is set to NULL if a memory allocation error occurs. */ static int proxyCreateConchPathname(char *dbPath, char **pConchPath){ int i; /* Loop counter */ int len = (int)strlen(dbPath); /* Length of database filename - dbPath */ char *conchPath; /* buffer in which to construct conch name */ /* Allocate space for the conch filename and initialize the name to ** the name of the original database file. */ *pConchPath = conchPath = (char *)sqlite3_malloc64(len + 8); if( conchPath==0 ){ return SQLITE_NOMEM_BKPT; } memcpy(conchPath, dbPath, len+1); /* now insert a "." before the last / character */ for( i=(len-1); i>=0; i-- ){ if( conchPath[i]=='/' ){ i++; break; } } conchPath[i]='.'; while ( ilockingContext; char *oldPath = pCtx->lockProxyPath; int rc = SQLITE_OK; if( pFile->eFileLock!=NO_LOCK ){ return SQLITE_BUSY; } /* nothing to do if the path is NULL, :auto: or matches the existing path */ if( !path || path[0]=='\0' || !strcmp(path, ":auto:") || (oldPath && !strncmp(oldPath, path, MAXPATHLEN)) ){ return SQLITE_OK; }else{ unixFile *lockProxy = pCtx->lockProxy; pCtx->lockProxy=NULL; pCtx->conchHeld = 0; if( lockProxy!=NULL ){ rc=lockProxy->pMethod->xClose((sqlite3_file *)lockProxy); if( rc ) return rc; sqlite3_free(lockProxy); } sqlite3_free(oldPath); pCtx->lockProxyPath = sqlite3DbStrDup(0, path); } return rc; } /* ** pFile is a file that has been opened by a prior xOpen call. dbPath ** is a string buffer at least MAXPATHLEN+1 characters in size. ** ** This routine find the filename associated with pFile and writes it ** int dbPath. */ static int proxyGetDbPathForUnixFile(unixFile *pFile, char *dbPath){ #if defined(__APPLE__) if( pFile->pMethod == &afpIoMethods ){ /* afp style keeps a reference to the db path in the filePath field ** of the struct */ assert( (int)strlen((char*)pFile->lockingContext)<=MAXPATHLEN ); strlcpy(dbPath, ((afpLockingContext *)pFile->lockingContext)->dbPath, MAXPATHLEN); } else #endif if( pFile->pMethod == &dotlockIoMethods ){ /* dot lock style uses the locking context to store the dot lock ** file path */ int len = strlen((char *)pFile->lockingContext) - strlen(DOTLOCK_SUFFIX); memcpy(dbPath, (char *)pFile->lockingContext, len + 1); }else{ /* all other styles use the locking context to store the db file path */ assert( strlen((char*)pFile->lockingContext)<=MAXPATHLEN ); strlcpy(dbPath, (char *)pFile->lockingContext, MAXPATHLEN); } return SQLITE_OK; } /* ** Takes an already filled in unix file and alters it so all file locking ** will be performed on the local proxy lock file. The following fields ** are preserved in the locking context so that they can be restored and ** the unix structure properly cleaned up at close time: ** ->lockingContext ** ->pMethod */ static int proxyTransformUnixFile(unixFile *pFile, const char *path) { proxyLockingContext *pCtx; char dbPath[MAXPATHLEN+1]; /* Name of the database file */ char *lockPath=NULL; int rc = SQLITE_OK; if( pFile->eFileLock!=NO_LOCK ){ return SQLITE_BUSY; } proxyGetDbPathForUnixFile(pFile, dbPath); if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ){ lockPath=NULL; }else{ lockPath=(char *)path; } OSTRACE(("TRANSPROXY %d for %s pid=%d\n", pFile->h, (lockPath ? lockPath : ":auto:"), osGetpid(0))); pCtx = sqlite3_malloc64( sizeof(*pCtx) ); if( pCtx==0 ){ return SQLITE_NOMEM_BKPT; } memset(pCtx, 0, sizeof(*pCtx)); rc = proxyCreateConchPathname(dbPath, &pCtx->conchFilePath); if( rc==SQLITE_OK ){ rc = proxyCreateUnixFile(pCtx->conchFilePath, &pCtx->conchFile, 0); if( rc==SQLITE_CANTOPEN && ((pFile->openFlags&O_RDWR) == 0) ){ /* if (a) the open flags are not O_RDWR, (b) the conch isn't there, and ** (c) the file system is read-only, then enable no-locking access. ** Ugh, since O_RDONLY==0x0000 we test for !O_RDWR since unixOpen asserts ** that openFlags will have only one of O_RDONLY or O_RDWR. */ struct statfs fsInfo; struct stat conchInfo; int goLockless = 0; if( osStat(pCtx->conchFilePath, &conchInfo) == -1 ) { int err = errno; if( (err==ENOENT) && (statfs(dbPath, &fsInfo) != -1) ){ goLockless = (fsInfo.f_flags&MNT_RDONLY) == MNT_RDONLY; } } if( goLockless ){ pCtx->conchHeld = -1; /* read only FS/ lockless */ rc = SQLITE_OK; } } } if( rc==SQLITE_OK && lockPath ){ pCtx->lockProxyPath = sqlite3DbStrDup(0, lockPath); } if( rc==SQLITE_OK ){ pCtx->dbPath = sqlite3DbStrDup(0, dbPath); if( pCtx->dbPath==NULL ){ rc = SQLITE_NOMEM_BKPT; } } if( rc==SQLITE_OK ){ /* all memory is allocated, proxys are created and assigned, ** switch the locking context and pMethod then return. */ pCtx->oldLockingContext = pFile->lockingContext; pFile->lockingContext = pCtx; pCtx->pOldMethod = pFile->pMethod; pFile->pMethod = &proxyIoMethods; }else{ if( pCtx->conchFile ){ pCtx->conchFile->pMethod->xClose((sqlite3_file *)pCtx->conchFile); sqlite3_free(pCtx->conchFile); } sqlite3DbFree(0, pCtx->lockProxyPath); sqlite3_free(pCtx->conchFilePath); sqlite3_free(pCtx); } OSTRACE(("TRANSPROXY %d %s\n", pFile->h, (rc==SQLITE_OK ? "ok" : "failed"))); return rc; } /* ** This routine handles sqlite3_file_control() calls that are specific ** to proxy locking. */ static int proxyFileControl(sqlite3_file *id, int op, void *pArg){ switch( op ){ case SQLITE_FCNTL_GET_LOCKPROXYFILE: { unixFile *pFile = (unixFile*)id; if( pFile->pMethod == &proxyIoMethods ){ proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext; proxyTakeConch(pFile); if( pCtx->lockProxyPath ){ *(const char **)pArg = pCtx->lockProxyPath; }else{ *(const char **)pArg = ":auto: (not held)"; } } else { *(const char **)pArg = NULL; } return SQLITE_OK; } case SQLITE_FCNTL_SET_LOCKPROXYFILE: { unixFile *pFile = (unixFile*)id; int rc = SQLITE_OK; int isProxyStyle = (pFile->pMethod == &proxyIoMethods); if( pArg==NULL || (const char *)pArg==0 ){ if( isProxyStyle ){ /* turn off proxy locking - not supported. If support is added for ** switching proxy locking mode off then it will need to fail if ** the journal mode is WAL mode. */ rc = SQLITE_ERROR /*SQLITE_PROTOCOL? SQLITE_MISUSE?*/; }else{ /* turn off proxy locking - already off - NOOP */ rc = SQLITE_OK; } }else{ const char *proxyPath = (const char *)pArg; if( isProxyStyle ){ proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext; if( !strcmp(pArg, ":auto:") || (pCtx->lockProxyPath && !strncmp(pCtx->lockProxyPath, proxyPath, MAXPATHLEN)) ){ rc = SQLITE_OK; }else{ rc = switchLockProxyPath(pFile, proxyPath); } }else{ /* turn on proxy file locking */ rc = proxyTransformUnixFile(pFile, proxyPath); } } return rc; } default: { assert( 0 ); /* The call assures that only valid opcodes are sent */ } } /*NOTREACHED*/ return SQLITE_ERROR; } /* ** Within this division (the proxying locking implementation) the procedures ** above this point are all utilities. The lock-related methods of the ** proxy-locking sqlite3_io_method object follow. */ /* ** This routine checks if there is a RESERVED lock held on the specified ** file by this or any other process. If such a lock is held, set *pResOut ** to a non-zero value otherwise *pResOut is set to zero. The return value ** is set to SQLITE_OK unless an I/O error occurs during lock checking. */ static int proxyCheckReservedLock(sqlite3_file *id, int *pResOut) { unixFile *pFile = (unixFile*)id; int rc = proxyTakeConch(pFile); if( rc==SQLITE_OK ){ proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext; if( pCtx->conchHeld>0 ){ unixFile *proxy = pCtx->lockProxy; return proxy->pMethod->xCheckReservedLock((sqlite3_file*)proxy, pResOut); }else{ /* conchHeld < 0 is lockless */ pResOut=0; } } return rc; } /* ** Lock the file with the lock specified by parameter eFileLock - one ** of the following: ** ** (1) SHARED_LOCK ** (2) RESERVED_LOCK ** (3) PENDING_LOCK ** (4) EXCLUSIVE_LOCK ** ** Sometimes when requesting one lock state, additional lock states ** are inserted in between. The locking might fail on one of the later ** transitions leaving the lock state different from what it started but ** still short of its goal. The following chart shows the allowed ** transitions and the inserted intermediate states: ** ** UNLOCKED -> SHARED ** SHARED -> RESERVED ** SHARED -> (PENDING) -> EXCLUSIVE ** RESERVED -> (PENDING) -> EXCLUSIVE ** PENDING -> EXCLUSIVE ** ** This routine will only increase a lock. Use the sqlite3OsUnlock() ** routine to lower a locking level. */ static int proxyLock(sqlite3_file *id, int eFileLock) { unixFile *pFile = (unixFile*)id; int rc = proxyTakeConch(pFile); if( rc==SQLITE_OK ){ proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext; if( pCtx->conchHeld>0 ){ unixFile *proxy = pCtx->lockProxy; rc = proxy->pMethod->xLock((sqlite3_file*)proxy, eFileLock); pFile->eFileLock = proxy->eFileLock; }else{ /* conchHeld < 0 is lockless */ } } return rc; } /* ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock ** must be either NO_LOCK or SHARED_LOCK. ** ** If the locking level of the file descriptor is already at or below ** the requested locking level, this routine is a no-op. */ static int proxyUnlock(sqlite3_file *id, int eFileLock) { unixFile *pFile = (unixFile*)id; int rc = proxyTakeConch(pFile); if( rc==SQLITE_OK ){ proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext; if( pCtx->conchHeld>0 ){ unixFile *proxy = pCtx->lockProxy; rc = proxy->pMethod->xUnlock((sqlite3_file*)proxy, eFileLock); pFile->eFileLock = proxy->eFileLock; }else{ /* conchHeld < 0 is lockless */ } } return rc; } /* ** Close a file that uses proxy locks. */ static int proxyClose(sqlite3_file *id) { if( ALWAYS(id) ){ unixFile *pFile = (unixFile*)id; proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext; unixFile *lockProxy = pCtx->lockProxy; unixFile *conchFile = pCtx->conchFile; int rc = SQLITE_OK; if( lockProxy ){ rc = lockProxy->pMethod->xUnlock((sqlite3_file*)lockProxy, NO_LOCK); if( rc ) return rc; rc = lockProxy->pMethod->xClose((sqlite3_file*)lockProxy); if( rc ) return rc; sqlite3_free(lockProxy); pCtx->lockProxy = 0; } if( conchFile ){ if( pCtx->conchHeld ){ rc = proxyReleaseConch(pFile); if( rc ) return rc; } rc = conchFile->pMethod->xClose((sqlite3_file*)conchFile); if( rc ) return rc; sqlite3_free(conchFile); } sqlite3DbFree(0, pCtx->lockProxyPath); sqlite3_free(pCtx->conchFilePath); sqlite3DbFree(0, pCtx->dbPath); /* restore the original locking context and pMethod then close it */ pFile->lockingContext = pCtx->oldLockingContext; pFile->pMethod = pCtx->pOldMethod; sqlite3_free(pCtx); return pFile->pMethod->xClose(id); } return SQLITE_OK; } #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */ /* ** The proxy locking style is intended for use with AFP filesystems. ** And since AFP is only supported on MacOSX, the proxy locking is also ** restricted to MacOSX. ** ** ******************* End of the proxy lock implementation ********************** ******************************************************************************/ /* ** Initialize the operating system interface. ** ** This routine registers all VFS implementations for unix-like operating ** systems. This routine, and the sqlite3_os_end() routine that follows, ** should be the only routines in this file that are visible from other ** files. ** ** This routine is called once during SQLite initialization and by a ** single thread. The memory allocation and mutex subsystems have not ** necessarily been initialized when this routine is called, and so they ** should not be used. */ SQLITE_API int sqlite3_os_init(void){ /* ** The following macro defines an initializer for an sqlite3_vfs object. ** The name of the VFS is NAME. The pAppData is a pointer to a pointer ** to the "finder" function. (pAppData is a pointer to a pointer because ** silly C90 rules prohibit a void* from being cast to a function pointer ** and so we have to go through the intermediate pointer to avoid problems ** when compiling with -pedantic-errors on GCC.) ** ** The FINDER parameter to this macro is the name of the pointer to the ** finder-function. The finder-function returns a pointer to the ** sqlite_io_methods object that implements the desired locking ** behaviors. See the division above that contains the IOMETHODS ** macro for addition information on finder-functions. ** ** Most finders simply return a pointer to a fixed sqlite3_io_methods ** object. But the "autolockIoFinder" available on MacOSX does a little ** more than that; it looks at the filesystem type that hosts the ** database file and tries to choose an locking method appropriate for ** that filesystem time. */ #define UNIXVFS(VFSNAME, FINDER) { \ 3, /* iVersion */ \ sizeof(unixFile), /* szOsFile */ \ MAX_PATHNAME, /* mxPathname */ \ 0, /* pNext */ \ VFSNAME, /* zName */ \ (void*)&FINDER, /* pAppData */ \ unixOpen, /* xOpen */ \ unixDelete, /* xDelete */ \ unixAccess, /* xAccess */ \ unixFullPathname, /* xFullPathname */ \ unixDlOpen, /* xDlOpen */ \ unixDlError, /* xDlError */ \ unixDlSym, /* xDlSym */ \ unixDlClose, /* xDlClose */ \ unixRandomness, /* xRandomness */ \ unixSleep, /* xSleep */ \ unixCurrentTime, /* xCurrentTime */ \ unixGetLastError, /* xGetLastError */ \ unixCurrentTimeInt64, /* xCurrentTimeInt64 */ \ unixSetSystemCall, /* xSetSystemCall */ \ unixGetSystemCall, /* xGetSystemCall */ \ unixNextSystemCall, /* xNextSystemCall */ \ } /* ** All default VFSes for unix are contained in the following array. ** ** Note that the sqlite3_vfs.pNext field of the VFS object is modified ** by the SQLite core when the VFS is registered. So the following ** array cannot be const. */ static sqlite3_vfs aVfs[] = { #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__) UNIXVFS("unix", autolockIoFinder ), #elif OS_VXWORKS UNIXVFS("unix", vxworksIoFinder ), #else UNIXVFS("unix", posixIoFinder ), #endif UNIXVFS("unix-none", nolockIoFinder ), UNIXVFS("unix-dotfile", dotlockIoFinder ), UNIXVFS("unix-excl", posixIoFinder ), #if OS_VXWORKS UNIXVFS("unix-namedsem", semIoFinder ), #endif #if SQLITE_ENABLE_LOCKING_STYLE || OS_VXWORKS UNIXVFS("unix-posix", posixIoFinder ), #endif #if SQLITE_ENABLE_LOCKING_STYLE UNIXVFS("unix-flock", flockIoFinder ), #endif #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__) UNIXVFS("unix-afp", afpIoFinder ), UNIXVFS("unix-nfs", nfsIoFinder ), UNIXVFS("unix-proxy", proxyIoFinder ), #endif }; unsigned int i; /* Loop counter */ /* Double-check that the aSyscall[] array has been constructed ** correctly. See ticket [bb3a86e890c8e96ab] */ assert( ArraySize(aSyscall)==28 ); /* Register all VFSes defined in the aVfs[] array */ for(i=0; i<(sizeof(aVfs)/sizeof(sqlite3_vfs)); i++){ sqlite3_vfs_register(&aVfs[i], i==0); } return SQLITE_OK; } /* ** Shutdown the operating system interface. ** ** Some operating systems might need to do some cleanup in this routine, ** to release dynamically allocated objects. But not on unix. ** This routine is a no-op for unix. */ SQLITE_API int sqlite3_os_end(void){ return SQLITE_OK; } #endif /* SQLITE_OS_UNIX */ /************** End of os_unix.c *********************************************/ /************** Begin file os_win.c ******************************************/ /* ** 2004 May 22 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ****************************************************************************** ** ** This file contains code that is specific to Windows. */ /* #include "sqliteInt.h" */ #if SQLITE_OS_WIN /* This file is used for Windows only */ /* ** Include code that is common to all os_*.c files */ /************** Include os_common.h in the middle of os_win.c ****************/ /************** Begin file os_common.h ***************************************/ /* ** 2004 May 22 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ****************************************************************************** ** ** This file contains macros and a little bit of code that is common to ** all of the platform-specific files (os_*.c) and is #included into those ** files. ** ** This file should be #included by the os_*.c files only. It is not a ** general purpose header file. */ #ifndef _OS_COMMON_H_ #define _OS_COMMON_H_ /* ** At least two bugs have slipped in because we changed the MEMORY_DEBUG ** macro to SQLITE_DEBUG and some older makefiles have not yet made the ** switch. The following code should catch this problem at compile-time. */ #ifdef MEMORY_DEBUG # error "The MEMORY_DEBUG macro is obsolete. Use SQLITE_DEBUG instead." #endif /* ** Macros for performance tracing. Normally turned off. Only works ** on i486 hardware. */ #ifdef SQLITE_PERFORMANCE_TRACE /* ** hwtime.h contains inline assembler code for implementing ** high-performance timing routines. */ /************** Include hwtime.h in the middle of os_common.h ****************/ /************** Begin file hwtime.h ******************************************/ /* ** 2008 May 27 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ****************************************************************************** ** ** This file contains inline asm code for retrieving "high-performance" ** counters for x86 class CPUs. */ #ifndef SQLITE_HWTIME_H #define SQLITE_HWTIME_H /* ** The following routine only works on pentium-class (or newer) processors. ** It uses the RDTSC opcode to read the cycle count value out of the ** processor and returns that value. This can be used for high-res ** profiling. */ #if (defined(__GNUC__) || defined(_MSC_VER)) && \ (defined(i386) || defined(__i386__) || defined(_M_IX86)) #if defined(__GNUC__) __inline__ sqlite_uint64 sqlite3Hwtime(void){ unsigned int lo, hi; __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi)); return (sqlite_uint64)hi << 32 | lo; } #elif defined(_MSC_VER) __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){ __asm { rdtsc ret ; return value at EDX:EAX } } #endif #elif (defined(__GNUC__) && defined(__x86_64__)) __inline__ sqlite_uint64 sqlite3Hwtime(void){ unsigned long val; __asm__ __volatile__ ("rdtsc" : "=A" (val)); return val; } #elif (defined(__GNUC__) && defined(__ppc__)) __inline__ sqlite_uint64 sqlite3Hwtime(void){ unsigned long long retval; unsigned long junk; __asm__ __volatile__ ("\n\ 1: mftbu %1\n\ mftb %L0\n\ mftbu %0\n\ cmpw %0,%1\n\ bne 1b" : "=r" (retval), "=r" (junk)); return retval; } #else #error Need implementation of sqlite3Hwtime() for your platform. /* ** To compile without implementing sqlite3Hwtime() for your platform, ** you can remove the above #error and use the following ** stub function. You will lose timing support for many ** of the debugging and testing utilities, but it should at ** least compile and run. */ SQLITE_PRIVATE sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); } #endif #endif /* !defined(SQLITE_HWTIME_H) */ /************** End of hwtime.h **********************************************/ /************** Continuing where we left off in os_common.h ******************/ static sqlite_uint64 g_start; static sqlite_uint64 g_elapsed; #define TIMER_START g_start=sqlite3Hwtime() #define TIMER_END g_elapsed=sqlite3Hwtime()-g_start #define TIMER_ELAPSED g_elapsed #else #define TIMER_START #define TIMER_END #define TIMER_ELAPSED ((sqlite_uint64)0) #endif /* ** If we compile with the SQLITE_TEST macro set, then the following block ** of code will give us the ability to simulate a disk I/O error. This ** is used for testing the I/O recovery logic. */ #if defined(SQLITE_TEST) SQLITE_API extern int sqlite3_io_error_hit; SQLITE_API extern int sqlite3_io_error_hardhit; SQLITE_API extern int sqlite3_io_error_pending; SQLITE_API extern int sqlite3_io_error_persist; SQLITE_API extern int sqlite3_io_error_benign; SQLITE_API extern int sqlite3_diskfull_pending; SQLITE_API extern int sqlite3_diskfull; #define SimulateIOErrorBenign(X) sqlite3_io_error_benign=(X) #define SimulateIOError(CODE) \ if( (sqlite3_io_error_persist && sqlite3_io_error_hit) \ || sqlite3_io_error_pending-- == 1 ) \ { local_ioerr(); CODE; } static void local_ioerr(){ IOTRACE(("IOERR\n")); sqlite3_io_error_hit++; if( !sqlite3_io_error_benign ) sqlite3_io_error_hardhit++; } #define SimulateDiskfullError(CODE) \ if( sqlite3_diskfull_pending ){ \ if( sqlite3_diskfull_pending == 1 ){ \ local_ioerr(); \ sqlite3_diskfull = 1; \ sqlite3_io_error_hit = 1; \ CODE; \ }else{ \ sqlite3_diskfull_pending--; \ } \ } #else #define SimulateIOErrorBenign(X) #define SimulateIOError(A) #define SimulateDiskfullError(A) #endif /* defined(SQLITE_TEST) */ /* ** When testing, keep a count of the number of open files. */ #if defined(SQLITE_TEST) SQLITE_API extern int sqlite3_open_file_count; #define OpenCounter(X) sqlite3_open_file_count+=(X) #else #define OpenCounter(X) #endif /* defined(SQLITE_TEST) */ #endif /* !defined(_OS_COMMON_H_) */ /************** End of os_common.h *******************************************/ /************** Continuing where we left off in os_win.c *********************/ /* ** Include the header file for the Windows VFS. */ /* #include "os_win.h" */ /* ** Compiling and using WAL mode requires several APIs that are only ** available in Windows platforms based on the NT kernel. */ #if !SQLITE_OS_WINNT && !defined(SQLITE_OMIT_WAL) # error "WAL mode requires support from the Windows NT kernel, compile\ with SQLITE_OMIT_WAL." #endif #if !SQLITE_OS_WINNT && SQLITE_MAX_MMAP_SIZE>0 # error "Memory mapped files require support from the Windows NT kernel,\ compile with SQLITE_MAX_MMAP_SIZE=0." #endif /* ** Are most of the Win32 ANSI APIs available (i.e. with certain exceptions ** based on the sub-platform)? */ #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && !defined(SQLITE_WIN32_NO_ANSI) # define SQLITE_WIN32_HAS_ANSI #endif /* ** Are most of the Win32 Unicode APIs available (i.e. with certain exceptions ** based on the sub-platform)? */ #if (SQLITE_OS_WINCE || SQLITE_OS_WINNT || SQLITE_OS_WINRT) && \ !defined(SQLITE_WIN32_NO_WIDE) # define SQLITE_WIN32_HAS_WIDE #endif /* ** Make sure at least one set of Win32 APIs is available. */ #if !defined(SQLITE_WIN32_HAS_ANSI) && !defined(SQLITE_WIN32_HAS_WIDE) # error "At least one of SQLITE_WIN32_HAS_ANSI and SQLITE_WIN32_HAS_WIDE\ must be defined." #endif /* ** Define the required Windows SDK version constants if they are not ** already available. */ #ifndef NTDDI_WIN8 # define NTDDI_WIN8 0x06020000 #endif #ifndef NTDDI_WINBLUE # define NTDDI_WINBLUE 0x06030000 #endif #ifndef NTDDI_WINTHRESHOLD # define NTDDI_WINTHRESHOLD 0x06040000 #endif /* ** Check to see if the GetVersionEx[AW] functions are deprecated on the ** target system. GetVersionEx was first deprecated in Win8.1. */ #ifndef SQLITE_WIN32_GETVERSIONEX # if defined(NTDDI_VERSION) && NTDDI_VERSION >= NTDDI_WINBLUE # define SQLITE_WIN32_GETVERSIONEX 0 /* GetVersionEx() is deprecated */ # else # define SQLITE_WIN32_GETVERSIONEX 1 /* GetVersionEx() is current */ # endif #endif /* ** Check to see if the CreateFileMappingA function is supported on the ** target system. It is unavailable when using "mincore.lib" on Win10. ** When compiling for Windows 10, always assume "mincore.lib" is in use. */ #ifndef SQLITE_WIN32_CREATEFILEMAPPINGA # if defined(NTDDI_VERSION) && NTDDI_VERSION >= NTDDI_WINTHRESHOLD # define SQLITE_WIN32_CREATEFILEMAPPINGA 0 # else # define SQLITE_WIN32_CREATEFILEMAPPINGA 1 # endif #endif /* ** This constant should already be defined (in the "WinDef.h" SDK file). */ #ifndef MAX_PATH # define MAX_PATH (260) #endif /* ** Maximum pathname length (in chars) for Win32. This should normally be ** MAX_PATH. */ #ifndef SQLITE_WIN32_MAX_PATH_CHARS # define SQLITE_WIN32_MAX_PATH_CHARS (MAX_PATH) #endif /* ** This constant should already be defined (in the "WinNT.h" SDK file). */ #ifndef UNICODE_STRING_MAX_CHARS # define UNICODE_STRING_MAX_CHARS (32767) #endif /* ** Maximum pathname length (in chars) for WinNT. This should normally be ** UNICODE_STRING_MAX_CHARS. */ #ifndef SQLITE_WINNT_MAX_PATH_CHARS # define SQLITE_WINNT_MAX_PATH_CHARS (UNICODE_STRING_MAX_CHARS) #endif /* ** Maximum pathname length (in bytes) for Win32. The MAX_PATH macro is in ** characters, so we allocate 4 bytes per character assuming worst-case of ** 4-bytes-per-character for UTF8. */ #ifndef SQLITE_WIN32_MAX_PATH_BYTES # define SQLITE_WIN32_MAX_PATH_BYTES (SQLITE_WIN32_MAX_PATH_CHARS*4) #endif /* ** Maximum pathname length (in bytes) for WinNT. This should normally be ** UNICODE_STRING_MAX_CHARS * sizeof(WCHAR). */ #ifndef SQLITE_WINNT_MAX_PATH_BYTES # define SQLITE_WINNT_MAX_PATH_BYTES \ (sizeof(WCHAR) * SQLITE_WINNT_MAX_PATH_CHARS) #endif /* ** Maximum error message length (in chars) for WinRT. */ #ifndef SQLITE_WIN32_MAX_ERRMSG_CHARS # define SQLITE_WIN32_MAX_ERRMSG_CHARS (1024) #endif /* ** Returns non-zero if the character should be treated as a directory ** separator. */ #ifndef winIsDirSep # define winIsDirSep(a) (((a) == '/') || ((a) == '\\')) #endif /* ** This macro is used when a local variable is set to a value that is ** [sometimes] not used by the code (e.g. via conditional compilation). */ #ifndef UNUSED_VARIABLE_VALUE # define UNUSED_VARIABLE_VALUE(x) (void)(x) #endif /* ** Returns the character that should be used as the directory separator. */ #ifndef winGetDirSep # define winGetDirSep() '\\' #endif /* ** Do we need to manually define the Win32 file mapping APIs for use with WAL ** mode or memory mapped files (e.g. these APIs are available in the Windows ** CE SDK; however, they are not present in the header file)? */ #if SQLITE_WIN32_FILEMAPPING_API && \ (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0) /* ** Two of the file mapping APIs are different under WinRT. Figure out which ** set we need. */ #if SQLITE_OS_WINRT WINBASEAPI HANDLE WINAPI CreateFileMappingFromApp(HANDLE, \ LPSECURITY_ATTRIBUTES, ULONG, ULONG64, LPCWSTR); WINBASEAPI LPVOID WINAPI MapViewOfFileFromApp(HANDLE, ULONG, ULONG64, SIZE_T); #else #if defined(SQLITE_WIN32_HAS_ANSI) WINBASEAPI HANDLE WINAPI CreateFileMappingA(HANDLE, LPSECURITY_ATTRIBUTES, \ DWORD, DWORD, DWORD, LPCSTR); #endif /* defined(SQLITE_WIN32_HAS_ANSI) */ #if defined(SQLITE_WIN32_HAS_WIDE) WINBASEAPI HANDLE WINAPI CreateFileMappingW(HANDLE, LPSECURITY_ATTRIBUTES, \ DWORD, DWORD, DWORD, LPCWSTR); #endif /* defined(SQLITE_WIN32_HAS_WIDE) */ WINBASEAPI LPVOID WINAPI MapViewOfFile(HANDLE, DWORD, DWORD, DWORD, SIZE_T); #endif /* SQLITE_OS_WINRT */ /* ** These file mapping APIs are common to both Win32 and WinRT. */ WINBASEAPI BOOL WINAPI FlushViewOfFile(LPCVOID, SIZE_T); WINBASEAPI BOOL WINAPI UnmapViewOfFile(LPCVOID); #endif /* SQLITE_WIN32_FILEMAPPING_API */ /* ** Some Microsoft compilers lack this definition. */ #ifndef INVALID_FILE_ATTRIBUTES # define INVALID_FILE_ATTRIBUTES ((DWORD)-1) #endif #ifndef FILE_FLAG_MASK # define FILE_FLAG_MASK (0xFF3C0000) #endif #ifndef FILE_ATTRIBUTE_MASK # define FILE_ATTRIBUTE_MASK (0x0003FFF7) #endif #ifndef SQLITE_OMIT_WAL /* Forward references to structures used for WAL */ typedef struct winShm winShm; /* A connection to shared-memory */ typedef struct winShmNode winShmNode; /* A region of shared-memory */ #endif /* ** WinCE lacks native support for file locking so we have to fake it ** with some code of our own. */ #if SQLITE_OS_WINCE typedef struct winceLock { int nReaders; /* Number of reader locks obtained */ BOOL bPending; /* Indicates a pending lock has been obtained */ BOOL bReserved; /* Indicates a reserved lock has been obtained */ BOOL bExclusive; /* Indicates an exclusive lock has been obtained */ } winceLock; #endif /* ** The winFile structure is a subclass of sqlite3_file* specific to the win32 ** portability layer. */ typedef struct winFile winFile; struct winFile { const sqlite3_io_methods *pMethod; /*** Must be first ***/ sqlite3_vfs *pVfs; /* The VFS used to open this file */ HANDLE h; /* Handle for accessing the file */ u8 locktype; /* Type of lock currently held on this file */ short sharedLockByte; /* Randomly chosen byte used as a shared lock */ u8 ctrlFlags; /* Flags. See WINFILE_* below */ DWORD lastErrno; /* The Windows errno from the last I/O error */ #ifndef SQLITE_OMIT_WAL winShm *pShm; /* Instance of shared memory on this file */ #endif const char *zPath; /* Full pathname of this file */ int szChunk; /* Chunk size configured by FCNTL_CHUNK_SIZE */ #if SQLITE_OS_WINCE LPWSTR zDeleteOnClose; /* Name of file to delete when closing */ HANDLE hMutex; /* Mutex used to control access to shared lock */ HANDLE hShared; /* Shared memory segment used for locking */ winceLock local; /* Locks obtained by this instance of winFile */ winceLock *shared; /* Global shared lock memory for the file */ #endif #if SQLITE_MAX_MMAP_SIZE>0 int nFetchOut; /* Number of outstanding xFetch references */ HANDLE hMap; /* Handle for accessing memory mapping */ void *pMapRegion; /* Area memory mapped */ sqlite3_int64 mmapSize; /* Usable size of mapped region */ sqlite3_int64 mmapSizeActual; /* Actual size of mapped region */ sqlite3_int64 mmapSizeMax; /* Configured FCNTL_MMAP_SIZE value */ #endif }; /* ** The winVfsAppData structure is used for the pAppData member for all of the ** Win32 VFS variants. */ typedef struct winVfsAppData winVfsAppData; struct winVfsAppData { const sqlite3_io_methods *pMethod; /* The file I/O methods to use. */ void *pAppData; /* The extra pAppData, if any. */ BOOL bNoLock; /* Non-zero if locking is disabled. */ }; /* ** Allowed values for winFile.ctrlFlags */ #define WINFILE_RDONLY 0x02 /* Connection is read only */ #define WINFILE_PERSIST_WAL 0x04 /* Persistent WAL mode */ #define WINFILE_PSOW 0x10 /* SQLITE_IOCAP_POWERSAFE_OVERWRITE */ /* * The size of the buffer used by sqlite3_win32_write_debug(). */ #ifndef SQLITE_WIN32_DBG_BUF_SIZE # define SQLITE_WIN32_DBG_BUF_SIZE ((int)(4096-sizeof(DWORD))) #endif /* * The value used with sqlite3_win32_set_directory() to specify that * the data directory should be changed. */ #ifndef SQLITE_WIN32_DATA_DIRECTORY_TYPE # define SQLITE_WIN32_DATA_DIRECTORY_TYPE (1) #endif /* * The value used with sqlite3_win32_set_directory() to specify that * the temporary directory should be changed. */ #ifndef SQLITE_WIN32_TEMP_DIRECTORY_TYPE # define SQLITE_WIN32_TEMP_DIRECTORY_TYPE (2) #endif /* * If compiled with SQLITE_WIN32_MALLOC on Windows, we will use the * various Win32 API heap functions instead of our own. */ #ifdef SQLITE_WIN32_MALLOC /* * If this is non-zero, an isolated heap will be created by the native Win32 * allocator subsystem; otherwise, the default process heap will be used. This * setting has no effect when compiling for WinRT. By default, this is enabled * and an isolated heap will be created to store all allocated data. * ****************************************************************************** * WARNING: It is important to note that when this setting is non-zero and the * winMemShutdown function is called (e.g. by the sqlite3_shutdown * function), all data that was allocated using the isolated heap will * be freed immediately and any attempt to access any of that freed * data will almost certainly result in an immediate access violation. ****************************************************************************** */ #ifndef SQLITE_WIN32_HEAP_CREATE # define SQLITE_WIN32_HEAP_CREATE (TRUE) #endif /* * This is cache size used in the calculation of the initial size of the * Win32-specific heap. It cannot be negative. */ #ifndef SQLITE_WIN32_CACHE_SIZE # if SQLITE_DEFAULT_CACHE_SIZE>=0 # define SQLITE_WIN32_CACHE_SIZE (SQLITE_DEFAULT_CACHE_SIZE) # else # define SQLITE_WIN32_CACHE_SIZE (-(SQLITE_DEFAULT_CACHE_SIZE)) # endif #endif /* * The initial size of the Win32-specific heap. This value may be zero. */ #ifndef SQLITE_WIN32_HEAP_INIT_SIZE # define SQLITE_WIN32_HEAP_INIT_SIZE ((SQLITE_WIN32_CACHE_SIZE) * \ (SQLITE_DEFAULT_PAGE_SIZE) + 4194304) #endif /* * The maximum size of the Win32-specific heap. This value may be zero. */ #ifndef SQLITE_WIN32_HEAP_MAX_SIZE # define SQLITE_WIN32_HEAP_MAX_SIZE (0) #endif /* * The extra flags to use in calls to the Win32 heap APIs. This value may be * zero for the default behavior. */ #ifndef SQLITE_WIN32_HEAP_FLAGS # define SQLITE_WIN32_HEAP_FLAGS (0) #endif /* ** The winMemData structure stores information required by the Win32-specific ** sqlite3_mem_methods implementation. */ typedef struct winMemData winMemData; struct winMemData { #ifndef NDEBUG u32 magic1; /* Magic number to detect structure corruption. */ #endif HANDLE hHeap; /* The handle to our heap. */ BOOL bOwned; /* Do we own the heap (i.e. destroy it on shutdown)? */ #ifndef NDEBUG u32 magic2; /* Magic number to detect structure corruption. */ #endif }; #ifndef NDEBUG #define WINMEM_MAGIC1 0x42b2830b #define WINMEM_MAGIC2 0xbd4d7cf4 #endif static struct winMemData win_mem_data = { #ifndef NDEBUG WINMEM_MAGIC1, #endif NULL, FALSE #ifndef NDEBUG ,WINMEM_MAGIC2 #endif }; #ifndef NDEBUG #define winMemAssertMagic1() assert( win_mem_data.magic1==WINMEM_MAGIC1 ) #define winMemAssertMagic2() assert( win_mem_data.magic2==WINMEM_MAGIC2 ) #define winMemAssertMagic() winMemAssertMagic1(); winMemAssertMagic2(); #else #define winMemAssertMagic() #endif #define winMemGetDataPtr() &win_mem_data #define winMemGetHeap() win_mem_data.hHeap #define winMemGetOwned() win_mem_data.bOwned static void *winMemMalloc(int nBytes); static void winMemFree(void *pPrior); static void *winMemRealloc(void *pPrior, int nBytes); static int winMemSize(void *p); static int winMemRoundup(int n); static int winMemInit(void *pAppData); static void winMemShutdown(void *pAppData); SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetWin32(void); #endif /* SQLITE_WIN32_MALLOC */ /* ** The following variable is (normally) set once and never changes ** thereafter. It records whether the operating system is Win9x ** or WinNT. ** ** 0: Operating system unknown. ** 1: Operating system is Win9x. ** 2: Operating system is WinNT. ** ** In order to facilitate testing on a WinNT system, the test fixture ** can manually set this value to 1 to emulate Win98 behavior. */ #ifdef SQLITE_TEST SQLITE_API LONG SQLITE_WIN32_VOLATILE sqlite3_os_type = 0; #else static LONG SQLITE_WIN32_VOLATILE sqlite3_os_type = 0; #endif #ifndef SYSCALL # define SYSCALL sqlite3_syscall_ptr #endif /* ** This function is not available on Windows CE or WinRT. */ #if SQLITE_OS_WINCE || SQLITE_OS_WINRT # define osAreFileApisANSI() 1 #endif /* ** Many system calls are accessed through pointer-to-functions so that ** they may be overridden at runtime to facilitate fault injection during ** testing and sandboxing. The following array holds the names and pointers ** to all overrideable system calls. */ static struct win_syscall { const char *zName; /* Name of the system call */ sqlite3_syscall_ptr pCurrent; /* Current value of the system call */ sqlite3_syscall_ptr pDefault; /* Default value */ } aSyscall[] = { #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT { "AreFileApisANSI", (SYSCALL)AreFileApisANSI, 0 }, #else { "AreFileApisANSI", (SYSCALL)0, 0 }, #endif #ifndef osAreFileApisANSI #define osAreFileApisANSI ((BOOL(WINAPI*)(VOID))aSyscall[0].pCurrent) #endif #if SQLITE_OS_WINCE && defined(SQLITE_WIN32_HAS_WIDE) { "CharLowerW", (SYSCALL)CharLowerW, 0 }, #else { "CharLowerW", (SYSCALL)0, 0 }, #endif #define osCharLowerW ((LPWSTR(WINAPI*)(LPWSTR))aSyscall[1].pCurrent) #if SQLITE_OS_WINCE && defined(SQLITE_WIN32_HAS_WIDE) { "CharUpperW", (SYSCALL)CharUpperW, 0 }, #else { "CharUpperW", (SYSCALL)0, 0 }, #endif #define osCharUpperW ((LPWSTR(WINAPI*)(LPWSTR))aSyscall[2].pCurrent) { "CloseHandle", (SYSCALL)CloseHandle, 0 }, #define osCloseHandle ((BOOL(WINAPI*)(HANDLE))aSyscall[3].pCurrent) #if defined(SQLITE_WIN32_HAS_ANSI) { "CreateFileA", (SYSCALL)CreateFileA, 0 }, #else { "CreateFileA", (SYSCALL)0, 0 }, #endif #define osCreateFileA ((HANDLE(WINAPI*)(LPCSTR,DWORD,DWORD, \ LPSECURITY_ATTRIBUTES,DWORD,DWORD,HANDLE))aSyscall[4].pCurrent) #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE) { "CreateFileW", (SYSCALL)CreateFileW, 0 }, #else { "CreateFileW", (SYSCALL)0, 0 }, #endif #define osCreateFileW ((HANDLE(WINAPI*)(LPCWSTR,DWORD,DWORD, \ LPSECURITY_ATTRIBUTES,DWORD,DWORD,HANDLE))aSyscall[5].pCurrent) #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_ANSI) && \ (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0) && \ SQLITE_WIN32_CREATEFILEMAPPINGA { "CreateFileMappingA", (SYSCALL)CreateFileMappingA, 0 }, #else { "CreateFileMappingA", (SYSCALL)0, 0 }, #endif #define osCreateFileMappingA ((HANDLE(WINAPI*)(HANDLE,LPSECURITY_ATTRIBUTES, \ DWORD,DWORD,DWORD,LPCSTR))aSyscall[6].pCurrent) #if SQLITE_OS_WINCE || (!SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE) && \ (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0)) { "CreateFileMappingW", (SYSCALL)CreateFileMappingW, 0 }, #else { "CreateFileMappingW", (SYSCALL)0, 0 }, #endif #define osCreateFileMappingW ((HANDLE(WINAPI*)(HANDLE,LPSECURITY_ATTRIBUTES, \ DWORD,DWORD,DWORD,LPCWSTR))aSyscall[7].pCurrent) #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE) { "CreateMutexW", (SYSCALL)CreateMutexW, 0 }, #else { "CreateMutexW", (SYSCALL)0, 0 }, #endif #define osCreateMutexW ((HANDLE(WINAPI*)(LPSECURITY_ATTRIBUTES,BOOL, \ LPCWSTR))aSyscall[8].pCurrent) #if defined(SQLITE_WIN32_HAS_ANSI) { "DeleteFileA", (SYSCALL)DeleteFileA, 0 }, #else { "DeleteFileA", (SYSCALL)0, 0 }, #endif #define osDeleteFileA ((BOOL(WINAPI*)(LPCSTR))aSyscall[9].pCurrent) #if defined(SQLITE_WIN32_HAS_WIDE) { "DeleteFileW", (SYSCALL)DeleteFileW, 0 }, #else { "DeleteFileW", (SYSCALL)0, 0 }, #endif #define osDeleteFileW ((BOOL(WINAPI*)(LPCWSTR))aSyscall[10].pCurrent) #if SQLITE_OS_WINCE { "FileTimeToLocalFileTime", (SYSCALL)FileTimeToLocalFileTime, 0 }, #else { "FileTimeToLocalFileTime", (SYSCALL)0, 0 }, #endif #define osFileTimeToLocalFileTime ((BOOL(WINAPI*)(CONST FILETIME*, \ LPFILETIME))aSyscall[11].pCurrent) #if SQLITE_OS_WINCE { "FileTimeToSystemTime", (SYSCALL)FileTimeToSystemTime, 0 }, #else { "FileTimeToSystemTime", (SYSCALL)0, 0 }, #endif #define osFileTimeToSystemTime ((BOOL(WINAPI*)(CONST FILETIME*, \ LPSYSTEMTIME))aSyscall[12].pCurrent) { "FlushFileBuffers", (SYSCALL)FlushFileBuffers, 0 }, #define osFlushFileBuffers ((BOOL(WINAPI*)(HANDLE))aSyscall[13].pCurrent) #if defined(SQLITE_WIN32_HAS_ANSI) { "FormatMessageA", (SYSCALL)FormatMessageA, 0 }, #else { "FormatMessageA", (SYSCALL)0, 0 }, #endif #define osFormatMessageA ((DWORD(WINAPI*)(DWORD,LPCVOID,DWORD,DWORD,LPSTR, \ DWORD,va_list*))aSyscall[14].pCurrent) #if defined(SQLITE_WIN32_HAS_WIDE) { "FormatMessageW", (SYSCALL)FormatMessageW, 0 }, #else { "FormatMessageW", (SYSCALL)0, 0 }, #endif #define osFormatMessageW ((DWORD(WINAPI*)(DWORD,LPCVOID,DWORD,DWORD,LPWSTR, \ DWORD,va_list*))aSyscall[15].pCurrent) #if !defined(SQLITE_OMIT_LOAD_EXTENSION) { "FreeLibrary", (SYSCALL)FreeLibrary, 0 }, #else { "FreeLibrary", (SYSCALL)0, 0 }, #endif #define osFreeLibrary ((BOOL(WINAPI*)(HMODULE))aSyscall[16].pCurrent) { "GetCurrentProcessId", (SYSCALL)GetCurrentProcessId, 0 }, #define osGetCurrentProcessId ((DWORD(WINAPI*)(VOID))aSyscall[17].pCurrent) #if !SQLITE_OS_WINCE && defined(SQLITE_WIN32_HAS_ANSI) { "GetDiskFreeSpaceA", (SYSCALL)GetDiskFreeSpaceA, 0 }, #else { "GetDiskFreeSpaceA", (SYSCALL)0, 0 }, #endif #define osGetDiskFreeSpaceA ((BOOL(WINAPI*)(LPCSTR,LPDWORD,LPDWORD,LPDWORD, \ LPDWORD))aSyscall[18].pCurrent) #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE) { "GetDiskFreeSpaceW", (SYSCALL)GetDiskFreeSpaceW, 0 }, #else { "GetDiskFreeSpaceW", (SYSCALL)0, 0 }, #endif #define osGetDiskFreeSpaceW ((BOOL(WINAPI*)(LPCWSTR,LPDWORD,LPDWORD,LPDWORD, \ LPDWORD))aSyscall[19].pCurrent) #if defined(SQLITE_WIN32_HAS_ANSI) { "GetFileAttributesA", (SYSCALL)GetFileAttributesA, 0 }, #else { "GetFileAttributesA", (SYSCALL)0, 0 }, #endif #define osGetFileAttributesA ((DWORD(WINAPI*)(LPCSTR))aSyscall[20].pCurrent) #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE) { "GetFileAttributesW", (SYSCALL)GetFileAttributesW, 0 }, #else { "GetFileAttributesW", (SYSCALL)0, 0 }, #endif #define osGetFileAttributesW ((DWORD(WINAPI*)(LPCWSTR))aSyscall[21].pCurrent) #if defined(SQLITE_WIN32_HAS_WIDE) { "GetFileAttributesExW", (SYSCALL)GetFileAttributesExW, 0 }, #else { "GetFileAttributesExW", (SYSCALL)0, 0 }, #endif #define osGetFileAttributesExW ((BOOL(WINAPI*)(LPCWSTR,GET_FILEEX_INFO_LEVELS, \ LPVOID))aSyscall[22].pCurrent) #if !SQLITE_OS_WINRT { "GetFileSize", (SYSCALL)GetFileSize, 0 }, #else { "GetFileSize", (SYSCALL)0, 0 }, #endif #define osGetFileSize ((DWORD(WINAPI*)(HANDLE,LPDWORD))aSyscall[23].pCurrent) #if !SQLITE_OS_WINCE && defined(SQLITE_WIN32_HAS_ANSI) { "GetFullPathNameA", (SYSCALL)GetFullPathNameA, 0 }, #else { "GetFullPathNameA", (SYSCALL)0, 0 }, #endif #define osGetFullPathNameA ((DWORD(WINAPI*)(LPCSTR,DWORD,LPSTR, \ LPSTR*))aSyscall[24].pCurrent) #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE) { "GetFullPathNameW", (SYSCALL)GetFullPathNameW, 0 }, #else { "GetFullPathNameW", (SYSCALL)0, 0 }, #endif #define osGetFullPathNameW ((DWORD(WINAPI*)(LPCWSTR,DWORD,LPWSTR, \ LPWSTR*))aSyscall[25].pCurrent) { "GetLastError", (SYSCALL)GetLastError, 0 }, #define osGetLastError ((DWORD(WINAPI*)(VOID))aSyscall[26].pCurrent) #if !defined(SQLITE_OMIT_LOAD_EXTENSION) #if SQLITE_OS_WINCE /* The GetProcAddressA() routine is only available on Windows CE. */ { "GetProcAddressA", (SYSCALL)GetProcAddressA, 0 }, #else /* All other Windows platforms expect GetProcAddress() to take ** an ANSI string regardless of the _UNICODE setting */ { "GetProcAddressA", (SYSCALL)GetProcAddress, 0 }, #endif #else { "GetProcAddressA", (SYSCALL)0, 0 }, #endif #define osGetProcAddressA ((FARPROC(WINAPI*)(HMODULE, \ LPCSTR))aSyscall[27].pCurrent) #if !SQLITE_OS_WINRT { "GetSystemInfo", (SYSCALL)GetSystemInfo, 0 }, #else { "GetSystemInfo", (SYSCALL)0, 0 }, #endif #define osGetSystemInfo ((VOID(WINAPI*)(LPSYSTEM_INFO))aSyscall[28].pCurrent) { "GetSystemTime", (SYSCALL)GetSystemTime, 0 }, #define osGetSystemTime ((VOID(WINAPI*)(LPSYSTEMTIME))aSyscall[29].pCurrent) #if !SQLITE_OS_WINCE { "GetSystemTimeAsFileTime", (SYSCALL)GetSystemTimeAsFileTime, 0 }, #else { "GetSystemTimeAsFileTime", (SYSCALL)0, 0 }, #endif #define osGetSystemTimeAsFileTime ((VOID(WINAPI*)( \ LPFILETIME))aSyscall[30].pCurrent) #if defined(SQLITE_WIN32_HAS_ANSI) { "GetTempPathA", (SYSCALL)GetTempPathA, 0 }, #else { "GetTempPathA", (SYSCALL)0, 0 }, #endif #define osGetTempPathA ((DWORD(WINAPI*)(DWORD,LPSTR))aSyscall[31].pCurrent) #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE) { "GetTempPathW", (SYSCALL)GetTempPathW, 0 }, #else { "GetTempPathW", (SYSCALL)0, 0 }, #endif #define osGetTempPathW ((DWORD(WINAPI*)(DWORD,LPWSTR))aSyscall[32].pCurrent) #if !SQLITE_OS_WINRT { "GetTickCount", (SYSCALL)GetTickCount, 0 }, #else { "GetTickCount", (SYSCALL)0, 0 }, #endif #define osGetTickCount ((DWORD(WINAPI*)(VOID))aSyscall[33].pCurrent) #if defined(SQLITE_WIN32_HAS_ANSI) && SQLITE_WIN32_GETVERSIONEX { "GetVersionExA", (SYSCALL)GetVersionExA, 0 }, #else { "GetVersionExA", (SYSCALL)0, 0 }, #endif #define osGetVersionExA ((BOOL(WINAPI*)( \ LPOSVERSIONINFOA))aSyscall[34].pCurrent) #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE) && \ SQLITE_WIN32_GETVERSIONEX { "GetVersionExW", (SYSCALL)GetVersionExW, 0 }, #else { "GetVersionExW", (SYSCALL)0, 0 }, #endif #define osGetVersionExW ((BOOL(WINAPI*)( \ LPOSVERSIONINFOW))aSyscall[35].pCurrent) { "HeapAlloc", (SYSCALL)HeapAlloc, 0 }, #define osHeapAlloc ((LPVOID(WINAPI*)(HANDLE,DWORD, \ SIZE_T))aSyscall[36].pCurrent) #if !SQLITE_OS_WINRT { "HeapCreate", (SYSCALL)HeapCreate, 0 }, #else { "HeapCreate", (SYSCALL)0, 0 }, #endif #define osHeapCreate ((HANDLE(WINAPI*)(DWORD,SIZE_T, \ SIZE_T))aSyscall[37].pCurrent) #if !SQLITE_OS_WINRT { "HeapDestroy", (SYSCALL)HeapDestroy, 0 }, #else { "HeapDestroy", (SYSCALL)0, 0 }, #endif #define osHeapDestroy ((BOOL(WINAPI*)(HANDLE))aSyscall[38].pCurrent) { "HeapFree", (SYSCALL)HeapFree, 0 }, #define osHeapFree ((BOOL(WINAPI*)(HANDLE,DWORD,LPVOID))aSyscall[39].pCurrent) { "HeapReAlloc", (SYSCALL)HeapReAlloc, 0 }, #define osHeapReAlloc ((LPVOID(WINAPI*)(HANDLE,DWORD,LPVOID, \ SIZE_T))aSyscall[40].pCurrent) { "HeapSize", (SYSCALL)HeapSize, 0 }, #define osHeapSize ((SIZE_T(WINAPI*)(HANDLE,DWORD, \ LPCVOID))aSyscall[41].pCurrent) #if !SQLITE_OS_WINRT { "HeapValidate", (SYSCALL)HeapValidate, 0 }, #else { "HeapValidate", (SYSCALL)0, 0 }, #endif #define osHeapValidate ((BOOL(WINAPI*)(HANDLE,DWORD, \ LPCVOID))aSyscall[42].pCurrent) #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT { "HeapCompact", (SYSCALL)HeapCompact, 0 }, #else { "HeapCompact", (SYSCALL)0, 0 }, #endif #define osHeapCompact ((UINT(WINAPI*)(HANDLE,DWORD))aSyscall[43].pCurrent) #if defined(SQLITE_WIN32_HAS_ANSI) && !defined(SQLITE_OMIT_LOAD_EXTENSION) { "LoadLibraryA", (SYSCALL)LoadLibraryA, 0 }, #else { "LoadLibraryA", (SYSCALL)0, 0 }, #endif #define osLoadLibraryA ((HMODULE(WINAPI*)(LPCSTR))aSyscall[44].pCurrent) #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE) && \ !defined(SQLITE_OMIT_LOAD_EXTENSION) { "LoadLibraryW", (SYSCALL)LoadLibraryW, 0 }, #else { "LoadLibraryW", (SYSCALL)0, 0 }, #endif #define osLoadLibraryW ((HMODULE(WINAPI*)(LPCWSTR))aSyscall[45].pCurrent) #if !SQLITE_OS_WINRT { "LocalFree", (SYSCALL)LocalFree, 0 }, #else { "LocalFree", (SYSCALL)0, 0 }, #endif #define osLocalFree ((HLOCAL(WINAPI*)(HLOCAL))aSyscall[46].pCurrent) #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT { "LockFile", (SYSCALL)LockFile, 0 }, #else { "LockFile", (SYSCALL)0, 0 }, #endif #ifndef osLockFile #define osLockFile ((BOOL(WINAPI*)(HANDLE,DWORD,DWORD,DWORD, \ DWORD))aSyscall[47].pCurrent) #endif #if !SQLITE_OS_WINCE { "LockFileEx", (SYSCALL)LockFileEx, 0 }, #else { "LockFileEx", (SYSCALL)0, 0 }, #endif #ifndef osLockFileEx #define osLockFileEx ((BOOL(WINAPI*)(HANDLE,DWORD,DWORD,DWORD,DWORD, \ LPOVERLAPPED))aSyscall[48].pCurrent) #endif #if SQLITE_OS_WINCE || (!SQLITE_OS_WINRT && \ (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0)) { "MapViewOfFile", (SYSCALL)MapViewOfFile, 0 }, #else { "MapViewOfFile", (SYSCALL)0, 0 }, #endif #define osMapViewOfFile ((LPVOID(WINAPI*)(HANDLE,DWORD,DWORD,DWORD, \ SIZE_T))aSyscall[49].pCurrent) { "MultiByteToWideChar", (SYSCALL)MultiByteToWideChar, 0 }, #define osMultiByteToWideChar ((int(WINAPI*)(UINT,DWORD,LPCSTR,int,LPWSTR, \ int))aSyscall[50].pCurrent) { "QueryPerformanceCounter", (SYSCALL)QueryPerformanceCounter, 0 }, #define osQueryPerformanceCounter ((BOOL(WINAPI*)( \ LARGE_INTEGER*))aSyscall[51].pCurrent) { "ReadFile", (SYSCALL)ReadFile, 0 }, #define osReadFile ((BOOL(WINAPI*)(HANDLE,LPVOID,DWORD,LPDWORD, \ LPOVERLAPPED))aSyscall[52].pCurrent) { "SetEndOfFile", (SYSCALL)SetEndOfFile, 0 }, #define osSetEndOfFile ((BOOL(WINAPI*)(HANDLE))aSyscall[53].pCurrent) #if !SQLITE_OS_WINRT { "SetFilePointer", (SYSCALL)SetFilePointer, 0 }, #else { "SetFilePointer", (SYSCALL)0, 0 }, #endif #define osSetFilePointer ((DWORD(WINAPI*)(HANDLE,LONG,PLONG, \ DWORD))aSyscall[54].pCurrent) #if !SQLITE_OS_WINRT { "Sleep", (SYSCALL)Sleep, 0 }, #else { "Sleep", (SYSCALL)0, 0 }, #endif #define osSleep ((VOID(WINAPI*)(DWORD))aSyscall[55].pCurrent) { "SystemTimeToFileTime", (SYSCALL)SystemTimeToFileTime, 0 }, #define osSystemTimeToFileTime ((BOOL(WINAPI*)(CONST SYSTEMTIME*, \ LPFILETIME))aSyscall[56].pCurrent) #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT { "UnlockFile", (SYSCALL)UnlockFile, 0 }, #else { "UnlockFile", (SYSCALL)0, 0 }, #endif #ifndef osUnlockFile #define osUnlockFile ((BOOL(WINAPI*)(HANDLE,DWORD,DWORD,DWORD, \ DWORD))aSyscall[57].pCurrent) #endif #if !SQLITE_OS_WINCE { "UnlockFileEx", (SYSCALL)UnlockFileEx, 0 }, #else { "UnlockFileEx", (SYSCALL)0, 0 }, #endif #define osUnlockFileEx ((BOOL(WINAPI*)(HANDLE,DWORD,DWORD,DWORD, \ LPOVERLAPPED))aSyscall[58].pCurrent) #if SQLITE_OS_WINCE || !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0 { "UnmapViewOfFile", (SYSCALL)UnmapViewOfFile, 0 }, #else { "UnmapViewOfFile", (SYSCALL)0, 0 }, #endif #define osUnmapViewOfFile ((BOOL(WINAPI*)(LPCVOID))aSyscall[59].pCurrent) { "WideCharToMultiByte", (SYSCALL)WideCharToMultiByte, 0 }, #define osWideCharToMultiByte ((int(WINAPI*)(UINT,DWORD,LPCWSTR,int,LPSTR,int, \ LPCSTR,LPBOOL))aSyscall[60].pCurrent) { "WriteFile", (SYSCALL)WriteFile, 0 }, #define osWriteFile ((BOOL(WINAPI*)(HANDLE,LPCVOID,DWORD,LPDWORD, \ LPOVERLAPPED))aSyscall[61].pCurrent) #if SQLITE_OS_WINRT { "CreateEventExW", (SYSCALL)CreateEventExW, 0 }, #else { "CreateEventExW", (SYSCALL)0, 0 }, #endif #define osCreateEventExW ((HANDLE(WINAPI*)(LPSECURITY_ATTRIBUTES,LPCWSTR, \ DWORD,DWORD))aSyscall[62].pCurrent) #if !SQLITE_OS_WINRT { "WaitForSingleObject", (SYSCALL)WaitForSingleObject, 0 }, #else { "WaitForSingleObject", (SYSCALL)0, 0 }, #endif #define osWaitForSingleObject ((DWORD(WINAPI*)(HANDLE, \ DWORD))aSyscall[63].pCurrent) #if !SQLITE_OS_WINCE { "WaitForSingleObjectEx", (SYSCALL)WaitForSingleObjectEx, 0 }, #else { "WaitForSingleObjectEx", (SYSCALL)0, 0 }, #endif #define osWaitForSingleObjectEx ((DWORD(WINAPI*)(HANDLE,DWORD, \ BOOL))aSyscall[64].pCurrent) #if SQLITE_OS_WINRT { "SetFilePointerEx", (SYSCALL)SetFilePointerEx, 0 }, #else { "SetFilePointerEx", (SYSCALL)0, 0 }, #endif #define osSetFilePointerEx ((BOOL(WINAPI*)(HANDLE,LARGE_INTEGER, \ PLARGE_INTEGER,DWORD))aSyscall[65].pCurrent) #if SQLITE_OS_WINRT { "GetFileInformationByHandleEx", (SYSCALL)GetFileInformationByHandleEx, 0 }, #else { "GetFileInformationByHandleEx", (SYSCALL)0, 0 }, #endif #define osGetFileInformationByHandleEx ((BOOL(WINAPI*)(HANDLE, \ FILE_INFO_BY_HANDLE_CLASS,LPVOID,DWORD))aSyscall[66].pCurrent) #if SQLITE_OS_WINRT && (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0) { "MapViewOfFileFromApp", (SYSCALL)MapViewOfFileFromApp, 0 }, #else { "MapViewOfFileFromApp", (SYSCALL)0, 0 }, #endif #define osMapViewOfFileFromApp ((LPVOID(WINAPI*)(HANDLE,ULONG,ULONG64, \ SIZE_T))aSyscall[67].pCurrent) #if SQLITE_OS_WINRT { "CreateFile2", (SYSCALL)CreateFile2, 0 }, #else { "CreateFile2", (SYSCALL)0, 0 }, #endif #define osCreateFile2 ((HANDLE(WINAPI*)(LPCWSTR,DWORD,DWORD,DWORD, \ LPCREATEFILE2_EXTENDED_PARAMETERS))aSyscall[68].pCurrent) #if SQLITE_OS_WINRT && !defined(SQLITE_OMIT_LOAD_EXTENSION) { "LoadPackagedLibrary", (SYSCALL)LoadPackagedLibrary, 0 }, #else { "LoadPackagedLibrary", (SYSCALL)0, 0 }, #endif #define osLoadPackagedLibrary ((HMODULE(WINAPI*)(LPCWSTR, \ DWORD))aSyscall[69].pCurrent) #if SQLITE_OS_WINRT { "GetTickCount64", (SYSCALL)GetTickCount64, 0 }, #else { "GetTickCount64", (SYSCALL)0, 0 }, #endif #define osGetTickCount64 ((ULONGLONG(WINAPI*)(VOID))aSyscall[70].pCurrent) #if SQLITE_OS_WINRT { "GetNativeSystemInfo", (SYSCALL)GetNativeSystemInfo, 0 }, #else { "GetNativeSystemInfo", (SYSCALL)0, 0 }, #endif #define osGetNativeSystemInfo ((VOID(WINAPI*)( \ LPSYSTEM_INFO))aSyscall[71].pCurrent) #if defined(SQLITE_WIN32_HAS_ANSI) { "OutputDebugStringA", (SYSCALL)OutputDebugStringA, 0 }, #else { "OutputDebugStringA", (SYSCALL)0, 0 }, #endif #define osOutputDebugStringA ((VOID(WINAPI*)(LPCSTR))aSyscall[72].pCurrent) #if defined(SQLITE_WIN32_HAS_WIDE) { "OutputDebugStringW", (SYSCALL)OutputDebugStringW, 0 }, #else { "OutputDebugStringW", (SYSCALL)0, 0 }, #endif #define osOutputDebugStringW ((VOID(WINAPI*)(LPCWSTR))aSyscall[73].pCurrent) { "GetProcessHeap", (SYSCALL)GetProcessHeap, 0 }, #define osGetProcessHeap ((HANDLE(WINAPI*)(VOID))aSyscall[74].pCurrent) #if SQLITE_OS_WINRT && (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0) { "CreateFileMappingFromApp", (SYSCALL)CreateFileMappingFromApp, 0 }, #else { "CreateFileMappingFromApp", (SYSCALL)0, 0 }, #endif #define osCreateFileMappingFromApp ((HANDLE(WINAPI*)(HANDLE, \ LPSECURITY_ATTRIBUTES,ULONG,ULONG64,LPCWSTR))aSyscall[75].pCurrent) /* ** NOTE: On some sub-platforms, the InterlockedCompareExchange "function" ** is really just a macro that uses a compiler intrinsic (e.g. x64). ** So do not try to make this is into a redefinable interface. */ #if defined(InterlockedCompareExchange) { "InterlockedCompareExchange", (SYSCALL)0, 0 }, #define osInterlockedCompareExchange InterlockedCompareExchange #else { "InterlockedCompareExchange", (SYSCALL)InterlockedCompareExchange, 0 }, #define osInterlockedCompareExchange ((LONG(WINAPI*)(LONG \ SQLITE_WIN32_VOLATILE*, LONG,LONG))aSyscall[76].pCurrent) #endif /* defined(InterlockedCompareExchange) */ #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && SQLITE_WIN32_USE_UUID { "UuidCreate", (SYSCALL)UuidCreate, 0 }, #else { "UuidCreate", (SYSCALL)0, 0 }, #endif #define osUuidCreate ((RPC_STATUS(RPC_ENTRY*)(UUID*))aSyscall[77].pCurrent) #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && SQLITE_WIN32_USE_UUID { "UuidCreateSequential", (SYSCALL)UuidCreateSequential, 0 }, #else { "UuidCreateSequential", (SYSCALL)0, 0 }, #endif #define osUuidCreateSequential \ ((RPC_STATUS(RPC_ENTRY*)(UUID*))aSyscall[78].pCurrent) #if !defined(SQLITE_NO_SYNC) && SQLITE_MAX_MMAP_SIZE>0 { "FlushViewOfFile", (SYSCALL)FlushViewOfFile, 0 }, #else { "FlushViewOfFile", (SYSCALL)0, 0 }, #endif #define osFlushViewOfFile \ ((BOOL(WINAPI*)(LPCVOID,SIZE_T))aSyscall[79].pCurrent) }; /* End of the overrideable system calls */ /* ** This is the xSetSystemCall() method of sqlite3_vfs for all of the ** "win32" VFSes. Return SQLITE_OK opon successfully updating the ** system call pointer, or SQLITE_NOTFOUND if there is no configurable ** system call named zName. */ static int winSetSystemCall( sqlite3_vfs *pNotUsed, /* The VFS pointer. Not used */ const char *zName, /* Name of system call to override */ sqlite3_syscall_ptr pNewFunc /* Pointer to new system call value */ ){ unsigned int i; int rc = SQLITE_NOTFOUND; UNUSED_PARAMETER(pNotUsed); if( zName==0 ){ /* If no zName is given, restore all system calls to their default ** settings and return NULL */ rc = SQLITE_OK; for(i=0; i0 ){ memset(zDbgBuf, 0, SQLITE_WIN32_DBG_BUF_SIZE); memcpy(zDbgBuf, zBuf, nMin); osOutputDebugStringA(zDbgBuf); }else{ osOutputDebugStringA(zBuf); } #elif defined(SQLITE_WIN32_HAS_WIDE) memset(zDbgBuf, 0, SQLITE_WIN32_DBG_BUF_SIZE); if ( osMultiByteToWideChar( osAreFileApisANSI() ? CP_ACP : CP_OEMCP, 0, zBuf, nMin, (LPWSTR)zDbgBuf, SQLITE_WIN32_DBG_BUF_SIZE/sizeof(WCHAR))<=0 ){ return; } osOutputDebugStringW((LPCWSTR)zDbgBuf); #else if( nMin>0 ){ memset(zDbgBuf, 0, SQLITE_WIN32_DBG_BUF_SIZE); memcpy(zDbgBuf, zBuf, nMin); fprintf(stderr, "%s", zDbgBuf); }else{ fprintf(stderr, "%s", zBuf); } #endif } /* ** The following routine suspends the current thread for at least ms ** milliseconds. This is equivalent to the Win32 Sleep() interface. */ #if SQLITE_OS_WINRT static HANDLE sleepObj = NULL; #endif SQLITE_API void sqlite3_win32_sleep(DWORD milliseconds){ #if SQLITE_OS_WINRT if ( sleepObj==NULL ){ sleepObj = osCreateEventExW(NULL, NULL, CREATE_EVENT_MANUAL_RESET, SYNCHRONIZE); } assert( sleepObj!=NULL ); osWaitForSingleObjectEx(sleepObj, milliseconds, FALSE); #else osSleep(milliseconds); #endif } #if SQLITE_MAX_WORKER_THREADS>0 && !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && \ SQLITE_THREADSAFE>0 SQLITE_PRIVATE DWORD sqlite3Win32Wait(HANDLE hObject){ DWORD rc; while( (rc = osWaitForSingleObjectEx(hObject, INFINITE, TRUE))==WAIT_IO_COMPLETION ){} return rc; } #endif /* ** Return true (non-zero) if we are running under WinNT, Win2K, WinXP, ** or WinCE. Return false (zero) for Win95, Win98, or WinME. ** ** Here is an interesting observation: Win95, Win98, and WinME lack ** the LockFileEx() API. But we can still statically link against that ** API as long as we don't call it when running Win95/98/ME. A call to ** this routine is used to determine if the host is Win95/98/ME or ** WinNT/2K/XP so that we will know whether or not we can safely call ** the LockFileEx() API. */ #if !SQLITE_WIN32_GETVERSIONEX # define osIsNT() (1) #elif SQLITE_OS_WINCE || SQLITE_OS_WINRT || !defined(SQLITE_WIN32_HAS_ANSI) # define osIsNT() (1) #elif !defined(SQLITE_WIN32_HAS_WIDE) # define osIsNT() (0) #else # define osIsNT() ((sqlite3_os_type==2) || sqlite3_win32_is_nt()) #endif /* ** This function determines if the machine is running a version of Windows ** based on the NT kernel. */ SQLITE_API int sqlite3_win32_is_nt(void){ #if SQLITE_OS_WINRT /* ** NOTE: The WinRT sub-platform is always assumed to be based on the NT ** kernel. */ return 1; #elif SQLITE_WIN32_GETVERSIONEX if( osInterlockedCompareExchange(&sqlite3_os_type, 0, 0)==0 ){ #if defined(SQLITE_WIN32_HAS_ANSI) OSVERSIONINFOA sInfo; sInfo.dwOSVersionInfoSize = sizeof(sInfo); osGetVersionExA(&sInfo); osInterlockedCompareExchange(&sqlite3_os_type, (sInfo.dwPlatformId == VER_PLATFORM_WIN32_NT) ? 2 : 1, 0); #elif defined(SQLITE_WIN32_HAS_WIDE) OSVERSIONINFOW sInfo; sInfo.dwOSVersionInfoSize = sizeof(sInfo); osGetVersionExW(&sInfo); osInterlockedCompareExchange(&sqlite3_os_type, (sInfo.dwPlatformId == VER_PLATFORM_WIN32_NT) ? 2 : 1, 0); #endif } return osInterlockedCompareExchange(&sqlite3_os_type, 2, 2)==2; #elif SQLITE_TEST return osInterlockedCompareExchange(&sqlite3_os_type, 2, 2)==2; #else /* ** NOTE: All sub-platforms where the GetVersionEx[AW] functions are ** deprecated are always assumed to be based on the NT kernel. */ return 1; #endif } #ifdef SQLITE_WIN32_MALLOC /* ** Allocate nBytes of memory. */ static void *winMemMalloc(int nBytes){ HANDLE hHeap; void *p; winMemAssertMagic(); hHeap = winMemGetHeap(); assert( hHeap!=0 ); assert( hHeap!=INVALID_HANDLE_VALUE ); #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE) assert( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) ); #endif assert( nBytes>=0 ); p = osHeapAlloc(hHeap, SQLITE_WIN32_HEAP_FLAGS, (SIZE_T)nBytes); if( !p ){ sqlite3_log(SQLITE_NOMEM, "failed to HeapAlloc %u bytes (%lu), heap=%p", nBytes, osGetLastError(), (void*)hHeap); } return p; } /* ** Free memory. */ static void winMemFree(void *pPrior){ HANDLE hHeap; winMemAssertMagic(); hHeap = winMemGetHeap(); assert( hHeap!=0 ); assert( hHeap!=INVALID_HANDLE_VALUE ); #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE) assert( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior) ); #endif if( !pPrior ) return; /* Passing NULL to HeapFree is undefined. */ if( !osHeapFree(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior) ){ sqlite3_log(SQLITE_NOMEM, "failed to HeapFree block %p (%lu), heap=%p", pPrior, osGetLastError(), (void*)hHeap); } } /* ** Change the size of an existing memory allocation */ static void *winMemRealloc(void *pPrior, int nBytes){ HANDLE hHeap; void *p; winMemAssertMagic(); hHeap = winMemGetHeap(); assert( hHeap!=0 ); assert( hHeap!=INVALID_HANDLE_VALUE ); #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE) assert( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior) ); #endif assert( nBytes>=0 ); if( !pPrior ){ p = osHeapAlloc(hHeap, SQLITE_WIN32_HEAP_FLAGS, (SIZE_T)nBytes); }else{ p = osHeapReAlloc(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior, (SIZE_T)nBytes); } if( !p ){ sqlite3_log(SQLITE_NOMEM, "failed to %s %u bytes (%lu), heap=%p", pPrior ? "HeapReAlloc" : "HeapAlloc", nBytes, osGetLastError(), (void*)hHeap); } return p; } /* ** Return the size of an outstanding allocation, in bytes. */ static int winMemSize(void *p){ HANDLE hHeap; SIZE_T n; winMemAssertMagic(); hHeap = winMemGetHeap(); assert( hHeap!=0 ); assert( hHeap!=INVALID_HANDLE_VALUE ); #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE) assert( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, p) ); #endif if( !p ) return 0; n = osHeapSize(hHeap, SQLITE_WIN32_HEAP_FLAGS, p); if( n==(SIZE_T)-1 ){ sqlite3_log(SQLITE_NOMEM, "failed to HeapSize block %p (%lu), heap=%p", p, osGetLastError(), (void*)hHeap); return 0; } return (int)n; } /* ** Round up a request size to the next valid allocation size. */ static int winMemRoundup(int n){ return n; } /* ** Initialize this module. */ static int winMemInit(void *pAppData){ winMemData *pWinMemData = (winMemData *)pAppData; if( !pWinMemData ) return SQLITE_ERROR; assert( pWinMemData->magic1==WINMEM_MAGIC1 ); assert( pWinMemData->magic2==WINMEM_MAGIC2 ); #if !SQLITE_OS_WINRT && SQLITE_WIN32_HEAP_CREATE if( !pWinMemData->hHeap ){ DWORD dwInitialSize = SQLITE_WIN32_HEAP_INIT_SIZE; DWORD dwMaximumSize = (DWORD)sqlite3GlobalConfig.nHeap; if( dwMaximumSize==0 ){ dwMaximumSize = SQLITE_WIN32_HEAP_MAX_SIZE; }else if( dwInitialSize>dwMaximumSize ){ dwInitialSize = dwMaximumSize; } pWinMemData->hHeap = osHeapCreate(SQLITE_WIN32_HEAP_FLAGS, dwInitialSize, dwMaximumSize); if( !pWinMemData->hHeap ){ sqlite3_log(SQLITE_NOMEM, "failed to HeapCreate (%lu), flags=%u, initSize=%lu, maxSize=%lu", osGetLastError(), SQLITE_WIN32_HEAP_FLAGS, dwInitialSize, dwMaximumSize); return SQLITE_NOMEM_BKPT; } pWinMemData->bOwned = TRUE; assert( pWinMemData->bOwned ); } #else pWinMemData->hHeap = osGetProcessHeap(); if( !pWinMemData->hHeap ){ sqlite3_log(SQLITE_NOMEM, "failed to GetProcessHeap (%lu)", osGetLastError()); return SQLITE_NOMEM_BKPT; } pWinMemData->bOwned = FALSE; assert( !pWinMemData->bOwned ); #endif assert( pWinMemData->hHeap!=0 ); assert( pWinMemData->hHeap!=INVALID_HANDLE_VALUE ); #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE) assert( osHeapValidate(pWinMemData->hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) ); #endif return SQLITE_OK; } /* ** Deinitialize this module. */ static void winMemShutdown(void *pAppData){ winMemData *pWinMemData = (winMemData *)pAppData; if( !pWinMemData ) return; assert( pWinMemData->magic1==WINMEM_MAGIC1 ); assert( pWinMemData->magic2==WINMEM_MAGIC2 ); if( pWinMemData->hHeap ){ assert( pWinMemData->hHeap!=INVALID_HANDLE_VALUE ); #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE) assert( osHeapValidate(pWinMemData->hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) ); #endif if( pWinMemData->bOwned ){ if( !osHeapDestroy(pWinMemData->hHeap) ){ sqlite3_log(SQLITE_NOMEM, "failed to HeapDestroy (%lu), heap=%p", osGetLastError(), (void*)pWinMemData->hHeap); } pWinMemData->bOwned = FALSE; } pWinMemData->hHeap = NULL; } } /* ** Populate the low-level memory allocation function pointers in ** sqlite3GlobalConfig.m with pointers to the routines in this file. The ** arguments specify the block of memory to manage. ** ** This routine is only called by sqlite3_config(), and therefore ** is not required to be threadsafe (it is not). */ SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetWin32(void){ static const sqlite3_mem_methods winMemMethods = { winMemMalloc, winMemFree, winMemRealloc, winMemSize, winMemRoundup, winMemInit, winMemShutdown, &win_mem_data }; return &winMemMethods; } SQLITE_PRIVATE void sqlite3MemSetDefault(void){ sqlite3_config(SQLITE_CONFIG_MALLOC, sqlite3MemGetWin32()); } #endif /* SQLITE_WIN32_MALLOC */ /* ** Convert a UTF-8 string to Microsoft Unicode. ** ** Space to hold the returned string is obtained from sqlite3_malloc(). */ static LPWSTR winUtf8ToUnicode(const char *zText){ int nChar; LPWSTR zWideText; nChar = osMultiByteToWideChar(CP_UTF8, 0, zText, -1, NULL, 0); if( nChar==0 ){ return 0; } zWideText = sqlite3MallocZero( nChar*sizeof(WCHAR) ); if( zWideText==0 ){ return 0; } nChar = osMultiByteToWideChar(CP_UTF8, 0, zText, -1, zWideText, nChar); if( nChar==0 ){ sqlite3_free(zWideText); zWideText = 0; } return zWideText; } /* ** Convert a Microsoft Unicode string to UTF-8. ** ** Space to hold the returned string is obtained from sqlite3_malloc(). */ static char *winUnicodeToUtf8(LPCWSTR zWideText){ int nByte; char *zText; nByte = osWideCharToMultiByte(CP_UTF8, 0, zWideText, -1, 0, 0, 0, 0); if( nByte == 0 ){ return 0; } zText = sqlite3MallocZero( nByte ); if( zText==0 ){ return 0; } nByte = osWideCharToMultiByte(CP_UTF8, 0, zWideText, -1, zText, nByte, 0, 0); if( nByte == 0 ){ sqlite3_free(zText); zText = 0; } return zText; } /* ** Convert an ANSI string to Microsoft Unicode, using the ANSI or OEM ** code page. ** ** Space to hold the returned string is obtained from sqlite3_malloc(). */ static LPWSTR winMbcsToUnicode(const char *zText, int useAnsi){ int nByte; LPWSTR zMbcsText; int codepage = useAnsi ? CP_ACP : CP_OEMCP; nByte = osMultiByteToWideChar(codepage, 0, zText, -1, NULL, 0)*sizeof(WCHAR); if( nByte==0 ){ return 0; } zMbcsText = sqlite3MallocZero( nByte*sizeof(WCHAR) ); if( zMbcsText==0 ){ return 0; } nByte = osMultiByteToWideChar(codepage, 0, zText, -1, zMbcsText, nByte); if( nByte==0 ){ sqlite3_free(zMbcsText); zMbcsText = 0; } return zMbcsText; } /* ** Convert a Microsoft Unicode string to a multi-byte character string, ** using the ANSI or OEM code page. ** ** Space to hold the returned string is obtained from sqlite3_malloc(). */ static char *winUnicodeToMbcs(LPCWSTR zWideText, int useAnsi){ int nByte; char *zText; int codepage = useAnsi ? CP_ACP : CP_OEMCP; nByte = osWideCharToMultiByte(codepage, 0, zWideText, -1, 0, 0, 0, 0); if( nByte == 0 ){ return 0; } zText = sqlite3MallocZero( nByte ); if( zText==0 ){ return 0; } nByte = osWideCharToMultiByte(codepage, 0, zWideText, -1, zText, nByte, 0, 0); if( nByte == 0 ){ sqlite3_free(zText); zText = 0; } return zText; } /* ** Convert a multi-byte character string to UTF-8. ** ** Space to hold the returned string is obtained from sqlite3_malloc(). */ static char *winMbcsToUtf8(const char *zText, int useAnsi){ char *zTextUtf8; LPWSTR zTmpWide; zTmpWide = winMbcsToUnicode(zText, useAnsi); if( zTmpWide==0 ){ return 0; } zTextUtf8 = winUnicodeToUtf8(zTmpWide); sqlite3_free(zTmpWide); return zTextUtf8; } /* ** Convert a UTF-8 string to a multi-byte character string. ** ** Space to hold the returned string is obtained from sqlite3_malloc(). */ static char *winUtf8ToMbcs(const char *zText, int useAnsi){ char *zTextMbcs; LPWSTR zTmpWide; zTmpWide = winUtf8ToUnicode(zText); if( zTmpWide==0 ){ return 0; } zTextMbcs = winUnicodeToMbcs(zTmpWide, useAnsi); sqlite3_free(zTmpWide); return zTextMbcs; } /* ** This is a public wrapper for the winUtf8ToUnicode() function. */ SQLITE_API LPWSTR sqlite3_win32_utf8_to_unicode(const char *zText){ #ifdef SQLITE_ENABLE_API_ARMOR if( !zText ){ (void)SQLITE_MISUSE_BKPT; return 0; } #endif #ifndef SQLITE_OMIT_AUTOINIT if( sqlite3_initialize() ) return 0; #endif return winUtf8ToUnicode(zText); } /* ** This is a public wrapper for the winUnicodeToUtf8() function. */ SQLITE_API char *sqlite3_win32_unicode_to_utf8(LPCWSTR zWideText){ #ifdef SQLITE_ENABLE_API_ARMOR if( !zWideText ){ (void)SQLITE_MISUSE_BKPT; return 0; } #endif #ifndef SQLITE_OMIT_AUTOINIT if( sqlite3_initialize() ) return 0; #endif return winUnicodeToUtf8(zWideText); } /* ** This is a public wrapper for the winMbcsToUtf8() function. */ SQLITE_API char *sqlite3_win32_mbcs_to_utf8(const char *zText){ #ifdef SQLITE_ENABLE_API_ARMOR if( !zText ){ (void)SQLITE_MISUSE_BKPT; return 0; } #endif #ifndef SQLITE_OMIT_AUTOINIT if( sqlite3_initialize() ) return 0; #endif return winMbcsToUtf8(zText, osAreFileApisANSI()); } /* ** This is a public wrapper for the winMbcsToUtf8() function. */ SQLITE_API char *sqlite3_win32_mbcs_to_utf8_v2(const char *zText, int useAnsi){ #ifdef SQLITE_ENABLE_API_ARMOR if( !zText ){ (void)SQLITE_MISUSE_BKPT; return 0; } #endif #ifndef SQLITE_OMIT_AUTOINIT if( sqlite3_initialize() ) return 0; #endif return winMbcsToUtf8(zText, useAnsi); } /* ** This is a public wrapper for the winUtf8ToMbcs() function. */ SQLITE_API char *sqlite3_win32_utf8_to_mbcs(const char *zText){ #ifdef SQLITE_ENABLE_API_ARMOR if( !zText ){ (void)SQLITE_MISUSE_BKPT; return 0; } #endif #ifndef SQLITE_OMIT_AUTOINIT if( sqlite3_initialize() ) return 0; #endif return winUtf8ToMbcs(zText, osAreFileApisANSI()); } /* ** This is a public wrapper for the winUtf8ToMbcs() function. */ SQLITE_API char *sqlite3_win32_utf8_to_mbcs_v2(const char *zText, int useAnsi){ #ifdef SQLITE_ENABLE_API_ARMOR if( !zText ){ (void)SQLITE_MISUSE_BKPT; return 0; } #endif #ifndef SQLITE_OMIT_AUTOINIT if( sqlite3_initialize() ) return 0; #endif return winUtf8ToMbcs(zText, useAnsi); } /* ** This function sets the data directory or the temporary directory based on ** the provided arguments. The type argument must be 1 in order to set the ** data directory or 2 in order to set the temporary directory. The zValue ** argument is the name of the directory to use. The return value will be ** SQLITE_OK if successful. */ SQLITE_API int sqlite3_win32_set_directory(DWORD type, LPCWSTR zValue){ char **ppDirectory = 0; #ifndef SQLITE_OMIT_AUTOINIT int rc = sqlite3_initialize(); if( rc ) return rc; #endif if( type==SQLITE_WIN32_DATA_DIRECTORY_TYPE ){ ppDirectory = &sqlite3_data_directory; }else if( type==SQLITE_WIN32_TEMP_DIRECTORY_TYPE ){ ppDirectory = &sqlite3_temp_directory; } assert( !ppDirectory || type==SQLITE_WIN32_DATA_DIRECTORY_TYPE || type==SQLITE_WIN32_TEMP_DIRECTORY_TYPE ); assert( !ppDirectory || sqlite3MemdebugHasType(*ppDirectory, MEMTYPE_HEAP) ); if( ppDirectory ){ char *zValueUtf8 = 0; if( zValue && zValue[0] ){ zValueUtf8 = winUnicodeToUtf8(zValue); if ( zValueUtf8==0 ){ return SQLITE_NOMEM_BKPT; } } sqlite3_free(*ppDirectory); *ppDirectory = zValueUtf8; return SQLITE_OK; } return SQLITE_ERROR; } /* ** The return value of winGetLastErrorMsg ** is zero if the error message fits in the buffer, or non-zero ** otherwise (if the message was truncated). */ static int winGetLastErrorMsg(DWORD lastErrno, int nBuf, char *zBuf){ /* FormatMessage returns 0 on failure. Otherwise it ** returns the number of TCHARs written to the output ** buffer, excluding the terminating null char. */ DWORD dwLen = 0; char *zOut = 0; if( osIsNT() ){ #if SQLITE_OS_WINRT WCHAR zTempWide[SQLITE_WIN32_MAX_ERRMSG_CHARS+1]; dwLen = osFormatMessageW(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, lastErrno, 0, zTempWide, SQLITE_WIN32_MAX_ERRMSG_CHARS, 0); #else LPWSTR zTempWide = NULL; dwLen = osFormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, lastErrno, 0, (LPWSTR) &zTempWide, 0, 0); #endif if( dwLen > 0 ){ /* allocate a buffer and convert to UTF8 */ sqlite3BeginBenignMalloc(); zOut = winUnicodeToUtf8(zTempWide); sqlite3EndBenignMalloc(); #if !SQLITE_OS_WINRT /* free the system buffer allocated by FormatMessage */ osLocalFree(zTempWide); #endif } } #ifdef SQLITE_WIN32_HAS_ANSI else{ char *zTemp = NULL; dwLen = osFormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, lastErrno, 0, (LPSTR) &zTemp, 0, 0); if( dwLen > 0 ){ /* allocate a buffer and convert to UTF8 */ sqlite3BeginBenignMalloc(); zOut = winMbcsToUtf8(zTemp, osAreFileApisANSI()); sqlite3EndBenignMalloc(); /* free the system buffer allocated by FormatMessage */ osLocalFree(zTemp); } } #endif if( 0 == dwLen ){ sqlite3_snprintf(nBuf, zBuf, "OsError 0x%lx (%lu)", lastErrno, lastErrno); }else{ /* copy a maximum of nBuf chars to output buffer */ sqlite3_snprintf(nBuf, zBuf, "%s", zOut); /* free the UTF8 buffer */ sqlite3_free(zOut); } return 0; } /* ** ** This function - winLogErrorAtLine() - is only ever called via the macro ** winLogError(). ** ** This routine is invoked after an error occurs in an OS function. ** It logs a message using sqlite3_log() containing the current value of ** error code and, if possible, the human-readable equivalent from ** FormatMessage. ** ** The first argument passed to the macro should be the error code that ** will be returned to SQLite (e.g. SQLITE_IOERR_DELETE, SQLITE_CANTOPEN). ** The two subsequent arguments should be the name of the OS function that ** failed and the associated file-system path, if any. */ #define winLogError(a,b,c,d) winLogErrorAtLine(a,b,c,d,__LINE__) static int winLogErrorAtLine( int errcode, /* SQLite error code */ DWORD lastErrno, /* Win32 last error */ const char *zFunc, /* Name of OS function that failed */ const char *zPath, /* File path associated with error */ int iLine /* Source line number where error occurred */ ){ char zMsg[500]; /* Human readable error text */ int i; /* Loop counter */ zMsg[0] = 0; winGetLastErrorMsg(lastErrno, sizeof(zMsg), zMsg); assert( errcode!=SQLITE_OK ); if( zPath==0 ) zPath = ""; for(i=0; zMsg[i] && zMsg[i]!='\r' && zMsg[i]!='\n'; i++){} zMsg[i] = 0; sqlite3_log(errcode, "os_win.c:%d: (%lu) %s(%s) - %s", iLine, lastErrno, zFunc, zPath, zMsg ); return errcode; } /* ** The number of times that a ReadFile(), WriteFile(), and DeleteFile() ** will be retried following a locking error - probably caused by ** antivirus software. Also the initial delay before the first retry. ** The delay increases linearly with each retry. */ #ifndef SQLITE_WIN32_IOERR_RETRY # define SQLITE_WIN32_IOERR_RETRY 10 #endif #ifndef SQLITE_WIN32_IOERR_RETRY_DELAY # define SQLITE_WIN32_IOERR_RETRY_DELAY 25 #endif static int winIoerrRetry = SQLITE_WIN32_IOERR_RETRY; static int winIoerrRetryDelay = SQLITE_WIN32_IOERR_RETRY_DELAY; /* ** The "winIoerrCanRetry1" macro is used to determine if a particular I/O ** error code obtained via GetLastError() is eligible to be retried. It ** must accept the error code DWORD as its only argument and should return ** non-zero if the error code is transient in nature and the operation ** responsible for generating the original error might succeed upon being ** retried. The argument to this macro should be a variable. ** ** Additionally, a macro named "winIoerrCanRetry2" may be defined. If it ** is defined, it will be consulted only when the macro "winIoerrCanRetry1" ** returns zero. The "winIoerrCanRetry2" macro is completely optional and ** may be used to include additional error codes in the set that should ** result in the failing I/O operation being retried by the caller. If ** defined, the "winIoerrCanRetry2" macro must exhibit external semantics ** identical to those of the "winIoerrCanRetry1" macro. */ #if !defined(winIoerrCanRetry1) #define winIoerrCanRetry1(a) (((a)==ERROR_ACCESS_DENIED) || \ ((a)==ERROR_SHARING_VIOLATION) || \ ((a)==ERROR_LOCK_VIOLATION) || \ ((a)==ERROR_DEV_NOT_EXIST) || \ ((a)==ERROR_NETNAME_DELETED) || \ ((a)==ERROR_SEM_TIMEOUT) || \ ((a)==ERROR_NETWORK_UNREACHABLE)) #endif /* ** If a ReadFile() or WriteFile() error occurs, invoke this routine ** to see if it should be retried. Return TRUE to retry. Return FALSE ** to give up with an error. */ static int winRetryIoerr(int *pnRetry, DWORD *pError){ DWORD e = osGetLastError(); if( *pnRetry>=winIoerrRetry ){ if( pError ){ *pError = e; } return 0; } if( winIoerrCanRetry1(e) ){ sqlite3_win32_sleep(winIoerrRetryDelay*(1+*pnRetry)); ++*pnRetry; return 1; } #if defined(winIoerrCanRetry2) else if( winIoerrCanRetry2(e) ){ sqlite3_win32_sleep(winIoerrRetryDelay*(1+*pnRetry)); ++*pnRetry; return 1; } #endif if( pError ){ *pError = e; } return 0; } /* ** Log a I/O error retry episode. */ static void winLogIoerr(int nRetry, int lineno){ if( nRetry ){ sqlite3_log(SQLITE_NOTICE, "delayed %dms for lock/sharing conflict at line %d", winIoerrRetryDelay*nRetry*(nRetry+1)/2, lineno ); } } /* ** This #if does not rely on the SQLITE_OS_WINCE define because the ** corresponding section in "date.c" cannot use it. */ #if !defined(SQLITE_OMIT_LOCALTIME) && defined(_WIN32_WCE) && \ (!defined(SQLITE_MSVC_LOCALTIME_API) || !SQLITE_MSVC_LOCALTIME_API) /* ** The MSVC CRT on Windows CE may not have a localtime() function. ** So define a substitute. */ /* # include */ struct tm *__cdecl localtime(const time_t *t) { static struct tm y; FILETIME uTm, lTm; SYSTEMTIME pTm; sqlite3_int64 t64; t64 = *t; t64 = (t64 + 11644473600)*10000000; uTm.dwLowDateTime = (DWORD)(t64 & 0xFFFFFFFF); uTm.dwHighDateTime= (DWORD)(t64 >> 32); osFileTimeToLocalFileTime(&uTm,&lTm); osFileTimeToSystemTime(&lTm,&pTm); y.tm_year = pTm.wYear - 1900; y.tm_mon = pTm.wMonth - 1; y.tm_wday = pTm.wDayOfWeek; y.tm_mday = pTm.wDay; y.tm_hour = pTm.wHour; y.tm_min = pTm.wMinute; y.tm_sec = pTm.wSecond; return &y; } #endif #if SQLITE_OS_WINCE /************************************************************************* ** This section contains code for WinCE only. */ #define HANDLE_TO_WINFILE(a) (winFile*)&((char*)a)[-(int)offsetof(winFile,h)] /* ** Acquire a lock on the handle h */ static void winceMutexAcquire(HANDLE h){ DWORD dwErr; do { dwErr = osWaitForSingleObject(h, INFINITE); } while (dwErr != WAIT_OBJECT_0 && dwErr != WAIT_ABANDONED); } /* ** Release a lock acquired by winceMutexAcquire() */ #define winceMutexRelease(h) ReleaseMutex(h) /* ** Create the mutex and shared memory used for locking in the file ** descriptor pFile */ static int winceCreateLock(const char *zFilename, winFile *pFile){ LPWSTR zTok; LPWSTR zName; DWORD lastErrno; BOOL bLogged = FALSE; BOOL bInit = TRUE; zName = winUtf8ToUnicode(zFilename); if( zName==0 ){ /* out of memory */ return SQLITE_IOERR_NOMEM_BKPT; } /* Initialize the local lockdata */ memset(&pFile->local, 0, sizeof(pFile->local)); /* Replace the backslashes from the filename and lowercase it ** to derive a mutex name. */ zTok = osCharLowerW(zName); for (;*zTok;zTok++){ if (*zTok == '\\') *zTok = '_'; } /* Create/open the named mutex */ pFile->hMutex = osCreateMutexW(NULL, FALSE, zName); if (!pFile->hMutex){ pFile->lastErrno = osGetLastError(); sqlite3_free(zName); return winLogError(SQLITE_IOERR, pFile->lastErrno, "winceCreateLock1", zFilename); } /* Acquire the mutex before continuing */ winceMutexAcquire(pFile->hMutex); /* Since the names of named mutexes, semaphores, file mappings etc are ** case-sensitive, take advantage of that by uppercasing the mutex name ** and using that as the shared filemapping name. */ osCharUpperW(zName); pFile->hShared = osCreateFileMappingW(INVALID_HANDLE_VALUE, NULL, PAGE_READWRITE, 0, sizeof(winceLock), zName); /* Set a flag that indicates we're the first to create the memory so it ** must be zero-initialized */ lastErrno = osGetLastError(); if (lastErrno == ERROR_ALREADY_EXISTS){ bInit = FALSE; } sqlite3_free(zName); /* If we succeeded in making the shared memory handle, map it. */ if( pFile->hShared ){ pFile->shared = (winceLock*)osMapViewOfFile(pFile->hShared, FILE_MAP_READ|FILE_MAP_WRITE, 0, 0, sizeof(winceLock)); /* If mapping failed, close the shared memory handle and erase it */ if( !pFile->shared ){ pFile->lastErrno = osGetLastError(); winLogError(SQLITE_IOERR, pFile->lastErrno, "winceCreateLock2", zFilename); bLogged = TRUE; osCloseHandle(pFile->hShared); pFile->hShared = NULL; } } /* If shared memory could not be created, then close the mutex and fail */ if( pFile->hShared==NULL ){ if( !bLogged ){ pFile->lastErrno = lastErrno; winLogError(SQLITE_IOERR, pFile->lastErrno, "winceCreateLock3", zFilename); bLogged = TRUE; } winceMutexRelease(pFile->hMutex); osCloseHandle(pFile->hMutex); pFile->hMutex = NULL; return SQLITE_IOERR; } /* Initialize the shared memory if we're supposed to */ if( bInit ){ memset(pFile->shared, 0, sizeof(winceLock)); } winceMutexRelease(pFile->hMutex); return SQLITE_OK; } /* ** Destroy the part of winFile that deals with wince locks */ static void winceDestroyLock(winFile *pFile){ if (pFile->hMutex){ /* Acquire the mutex */ winceMutexAcquire(pFile->hMutex); /* The following blocks should probably assert in debug mode, but they are to cleanup in case any locks remained open */ if (pFile->local.nReaders){ pFile->shared->nReaders --; } if (pFile->local.bReserved){ pFile->shared->bReserved = FALSE; } if (pFile->local.bPending){ pFile->shared->bPending = FALSE; } if (pFile->local.bExclusive){ pFile->shared->bExclusive = FALSE; } /* De-reference and close our copy of the shared memory handle */ osUnmapViewOfFile(pFile->shared); osCloseHandle(pFile->hShared); /* Done with the mutex */ winceMutexRelease(pFile->hMutex); osCloseHandle(pFile->hMutex); pFile->hMutex = NULL; } } /* ** An implementation of the LockFile() API of Windows for CE */ static BOOL winceLockFile( LPHANDLE phFile, DWORD dwFileOffsetLow, DWORD dwFileOffsetHigh, DWORD nNumberOfBytesToLockLow, DWORD nNumberOfBytesToLockHigh ){ winFile *pFile = HANDLE_TO_WINFILE(phFile); BOOL bReturn = FALSE; UNUSED_PARAMETER(dwFileOffsetHigh); UNUSED_PARAMETER(nNumberOfBytesToLockHigh); if (!pFile->hMutex) return TRUE; winceMutexAcquire(pFile->hMutex); /* Wanting an exclusive lock? */ if (dwFileOffsetLow == (DWORD)SHARED_FIRST && nNumberOfBytesToLockLow == (DWORD)SHARED_SIZE){ if (pFile->shared->nReaders == 0 && pFile->shared->bExclusive == 0){ pFile->shared->bExclusive = TRUE; pFile->local.bExclusive = TRUE; bReturn = TRUE; } } /* Want a read-only lock? */ else if (dwFileOffsetLow == (DWORD)SHARED_FIRST && nNumberOfBytesToLockLow == 1){ if (pFile->shared->bExclusive == 0){ pFile->local.nReaders ++; if (pFile->local.nReaders == 1){ pFile->shared->nReaders ++; } bReturn = TRUE; } } /* Want a pending lock? */ else if (dwFileOffsetLow == (DWORD)PENDING_BYTE && nNumberOfBytesToLockLow == 1){ /* If no pending lock has been acquired, then acquire it */ if (pFile->shared->bPending == 0) { pFile->shared->bPending = TRUE; pFile->local.bPending = TRUE; bReturn = TRUE; } } /* Want a reserved lock? */ else if (dwFileOffsetLow == (DWORD)RESERVED_BYTE && nNumberOfBytesToLockLow == 1){ if (pFile->shared->bReserved == 0) { pFile->shared->bReserved = TRUE; pFile->local.bReserved = TRUE; bReturn = TRUE; } } winceMutexRelease(pFile->hMutex); return bReturn; } /* ** An implementation of the UnlockFile API of Windows for CE */ static BOOL winceUnlockFile( LPHANDLE phFile, DWORD dwFileOffsetLow, DWORD dwFileOffsetHigh, DWORD nNumberOfBytesToUnlockLow, DWORD nNumberOfBytesToUnlockHigh ){ winFile *pFile = HANDLE_TO_WINFILE(phFile); BOOL bReturn = FALSE; UNUSED_PARAMETER(dwFileOffsetHigh); UNUSED_PARAMETER(nNumberOfBytesToUnlockHigh); if (!pFile->hMutex) return TRUE; winceMutexAcquire(pFile->hMutex); /* Releasing a reader lock or an exclusive lock */ if (dwFileOffsetLow == (DWORD)SHARED_FIRST){ /* Did we have an exclusive lock? */ if (pFile->local.bExclusive){ assert(nNumberOfBytesToUnlockLow == (DWORD)SHARED_SIZE); pFile->local.bExclusive = FALSE; pFile->shared->bExclusive = FALSE; bReturn = TRUE; } /* Did we just have a reader lock? */ else if (pFile->local.nReaders){ assert(nNumberOfBytesToUnlockLow == (DWORD)SHARED_SIZE || nNumberOfBytesToUnlockLow == 1); pFile->local.nReaders --; if (pFile->local.nReaders == 0) { pFile->shared->nReaders --; } bReturn = TRUE; } } /* Releasing a pending lock */ else if (dwFileOffsetLow == (DWORD)PENDING_BYTE && nNumberOfBytesToUnlockLow == 1){ if (pFile->local.bPending){ pFile->local.bPending = FALSE; pFile->shared->bPending = FALSE; bReturn = TRUE; } } /* Releasing a reserved lock */ else if (dwFileOffsetLow == (DWORD)RESERVED_BYTE && nNumberOfBytesToUnlockLow == 1){ if (pFile->local.bReserved) { pFile->local.bReserved = FALSE; pFile->shared->bReserved = FALSE; bReturn = TRUE; } } winceMutexRelease(pFile->hMutex); return bReturn; } /* ** End of the special code for wince *****************************************************************************/ #endif /* SQLITE_OS_WINCE */ /* ** Lock a file region. */ static BOOL winLockFile( LPHANDLE phFile, DWORD flags, DWORD offsetLow, DWORD offsetHigh, DWORD numBytesLow, DWORD numBytesHigh ){ #if SQLITE_OS_WINCE /* ** NOTE: Windows CE is handled differently here due its lack of the Win32 ** API LockFile. */ return winceLockFile(phFile, offsetLow, offsetHigh, numBytesLow, numBytesHigh); #else if( osIsNT() ){ OVERLAPPED ovlp; memset(&ovlp, 0, sizeof(OVERLAPPED)); ovlp.Offset = offsetLow; ovlp.OffsetHigh = offsetHigh; return osLockFileEx(*phFile, flags, 0, numBytesLow, numBytesHigh, &ovlp); }else{ return osLockFile(*phFile, offsetLow, offsetHigh, numBytesLow, numBytesHigh); } #endif } /* ** Unlock a file region. */ static BOOL winUnlockFile( LPHANDLE phFile, DWORD offsetLow, DWORD offsetHigh, DWORD numBytesLow, DWORD numBytesHigh ){ #if SQLITE_OS_WINCE /* ** NOTE: Windows CE is handled differently here due its lack of the Win32 ** API UnlockFile. */ return winceUnlockFile(phFile, offsetLow, offsetHigh, numBytesLow, numBytesHigh); #else if( osIsNT() ){ OVERLAPPED ovlp; memset(&ovlp, 0, sizeof(OVERLAPPED)); ovlp.Offset = offsetLow; ovlp.OffsetHigh = offsetHigh; return osUnlockFileEx(*phFile, 0, numBytesLow, numBytesHigh, &ovlp); }else{ return osUnlockFile(*phFile, offsetLow, offsetHigh, numBytesLow, numBytesHigh); } #endif } /***************************************************************************** ** The next group of routines implement the I/O methods specified ** by the sqlite3_io_methods object. ******************************************************************************/ /* ** Some Microsoft compilers lack this definition. */ #ifndef INVALID_SET_FILE_POINTER # define INVALID_SET_FILE_POINTER ((DWORD)-1) #endif /* ** Move the current position of the file handle passed as the first ** argument to offset iOffset within the file. If successful, return 0. ** Otherwise, set pFile->lastErrno and return non-zero. */ static int winSeekFile(winFile *pFile, sqlite3_int64 iOffset){ #if !SQLITE_OS_WINRT LONG upperBits; /* Most sig. 32 bits of new offset */ LONG lowerBits; /* Least sig. 32 bits of new offset */ DWORD dwRet; /* Value returned by SetFilePointer() */ DWORD lastErrno; /* Value returned by GetLastError() */ OSTRACE(("SEEK file=%p, offset=%lld\n", pFile->h, iOffset)); upperBits = (LONG)((iOffset>>32) & 0x7fffffff); lowerBits = (LONG)(iOffset & 0xffffffff); /* API oddity: If successful, SetFilePointer() returns a dword ** containing the lower 32-bits of the new file-offset. Or, if it fails, ** it returns INVALID_SET_FILE_POINTER. However according to MSDN, ** INVALID_SET_FILE_POINTER may also be a valid new offset. So to determine ** whether an error has actually occurred, it is also necessary to call ** GetLastError(). */ dwRet = osSetFilePointer(pFile->h, lowerBits, &upperBits, FILE_BEGIN); if( (dwRet==INVALID_SET_FILE_POINTER && ((lastErrno = osGetLastError())!=NO_ERROR)) ){ pFile->lastErrno = lastErrno; winLogError(SQLITE_IOERR_SEEK, pFile->lastErrno, "winSeekFile", pFile->zPath); OSTRACE(("SEEK file=%p, rc=SQLITE_IOERR_SEEK\n", pFile->h)); return 1; } OSTRACE(("SEEK file=%p, rc=SQLITE_OK\n", pFile->h)); return 0; #else /* ** Same as above, except that this implementation works for WinRT. */ LARGE_INTEGER x; /* The new offset */ BOOL bRet; /* Value returned by SetFilePointerEx() */ x.QuadPart = iOffset; bRet = osSetFilePointerEx(pFile->h, x, 0, FILE_BEGIN); if(!bRet){ pFile->lastErrno = osGetLastError(); winLogError(SQLITE_IOERR_SEEK, pFile->lastErrno, "winSeekFile", pFile->zPath); OSTRACE(("SEEK file=%p, rc=SQLITE_IOERR_SEEK\n", pFile->h)); return 1; } OSTRACE(("SEEK file=%p, rc=SQLITE_OK\n", pFile->h)); return 0; #endif } #if SQLITE_MAX_MMAP_SIZE>0 /* Forward references to VFS helper methods used for memory mapped files */ static int winMapfile(winFile*, sqlite3_int64); static int winUnmapfile(winFile*); #endif /* ** Close a file. ** ** It is reported that an attempt to close a handle might sometimes ** fail. This is a very unreasonable result, but Windows is notorious ** for being unreasonable so I do not doubt that it might happen. If ** the close fails, we pause for 100 milliseconds and try again. As ** many as MX_CLOSE_ATTEMPT attempts to close the handle are made before ** giving up and returning an error. */ #define MX_CLOSE_ATTEMPT 3 static int winClose(sqlite3_file *id){ int rc, cnt = 0; winFile *pFile = (winFile*)id; assert( id!=0 ); #ifndef SQLITE_OMIT_WAL assert( pFile->pShm==0 ); #endif assert( pFile->h!=NULL && pFile->h!=INVALID_HANDLE_VALUE ); OSTRACE(("CLOSE pid=%lu, pFile=%p, file=%p\n", osGetCurrentProcessId(), pFile, pFile->h)); #if SQLITE_MAX_MMAP_SIZE>0 winUnmapfile(pFile); #endif do{ rc = osCloseHandle(pFile->h); /* SimulateIOError( rc=0; cnt=MX_CLOSE_ATTEMPT; ); */ }while( rc==0 && ++cnt < MX_CLOSE_ATTEMPT && (sqlite3_win32_sleep(100), 1) ); #if SQLITE_OS_WINCE #define WINCE_DELETION_ATTEMPTS 3 { winVfsAppData *pAppData = (winVfsAppData*)pFile->pVfs->pAppData; if( pAppData==NULL || !pAppData->bNoLock ){ winceDestroyLock(pFile); } } if( pFile->zDeleteOnClose ){ int cnt = 0; while( osDeleteFileW(pFile->zDeleteOnClose)==0 && osGetFileAttributesW(pFile->zDeleteOnClose)!=0xffffffff && cnt++ < WINCE_DELETION_ATTEMPTS ){ sqlite3_win32_sleep(100); /* Wait a little before trying again */ } sqlite3_free(pFile->zDeleteOnClose); } #endif if( rc ){ pFile->h = NULL; } OpenCounter(-1); OSTRACE(("CLOSE pid=%lu, pFile=%p, file=%p, rc=%s\n", osGetCurrentProcessId(), pFile, pFile->h, rc ? "ok" : "failed")); return rc ? SQLITE_OK : winLogError(SQLITE_IOERR_CLOSE, osGetLastError(), "winClose", pFile->zPath); } /* ** Read data from a file into a buffer. Return SQLITE_OK if all ** bytes were read successfully and SQLITE_IOERR if anything goes ** wrong. */ static int winRead( sqlite3_file *id, /* File to read from */ void *pBuf, /* Write content into this buffer */ int amt, /* Number of bytes to read */ sqlite3_int64 offset /* Begin reading at this offset */ ){ #if !SQLITE_OS_WINCE && !defined(SQLITE_WIN32_NO_OVERLAPPED) OVERLAPPED overlapped; /* The offset for ReadFile. */ #endif winFile *pFile = (winFile*)id; /* file handle */ DWORD nRead; /* Number of bytes actually read from file */ int nRetry = 0; /* Number of retrys */ assert( id!=0 ); assert( amt>0 ); assert( offset>=0 ); SimulateIOError(return SQLITE_IOERR_READ); OSTRACE(("READ pid=%lu, pFile=%p, file=%p, buffer=%p, amount=%d, " "offset=%lld, lock=%d\n", osGetCurrentProcessId(), pFile, pFile->h, pBuf, amt, offset, pFile->locktype)); #if SQLITE_MAX_MMAP_SIZE>0 /* Deal with as much of this read request as possible by transfering ** data from the memory mapping using memcpy(). */ if( offsetmmapSize ){ if( offset+amt <= pFile->mmapSize ){ memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], amt); OSTRACE(("READ-MMAP pid=%lu, pFile=%p, file=%p, rc=SQLITE_OK\n", osGetCurrentProcessId(), pFile, pFile->h)); return SQLITE_OK; }else{ int nCopy = (int)(pFile->mmapSize - offset); memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], nCopy); pBuf = &((u8 *)pBuf)[nCopy]; amt -= nCopy; offset += nCopy; } } #endif #if SQLITE_OS_WINCE || defined(SQLITE_WIN32_NO_OVERLAPPED) if( winSeekFile(pFile, offset) ){ OSTRACE(("READ pid=%lu, pFile=%p, file=%p, rc=SQLITE_FULL\n", osGetCurrentProcessId(), pFile, pFile->h)); return SQLITE_FULL; } while( !osReadFile(pFile->h, pBuf, amt, &nRead, 0) ){ #else memset(&overlapped, 0, sizeof(OVERLAPPED)); overlapped.Offset = (LONG)(offset & 0xffffffff); overlapped.OffsetHigh = (LONG)((offset>>32) & 0x7fffffff); while( !osReadFile(pFile->h, pBuf, amt, &nRead, &overlapped) && osGetLastError()!=ERROR_HANDLE_EOF ){ #endif DWORD lastErrno; if( winRetryIoerr(&nRetry, &lastErrno) ) continue; pFile->lastErrno = lastErrno; OSTRACE(("READ pid=%lu, pFile=%p, file=%p, rc=SQLITE_IOERR_READ\n", osGetCurrentProcessId(), pFile, pFile->h)); return winLogError(SQLITE_IOERR_READ, pFile->lastErrno, "winRead", pFile->zPath); } winLogIoerr(nRetry, __LINE__); if( nRead<(DWORD)amt ){ /* Unread parts of the buffer must be zero-filled */ memset(&((char*)pBuf)[nRead], 0, amt-nRead); OSTRACE(("READ pid=%lu, pFile=%p, file=%p, rc=SQLITE_IOERR_SHORT_READ\n", osGetCurrentProcessId(), pFile, pFile->h)); return SQLITE_IOERR_SHORT_READ; } OSTRACE(("READ pid=%lu, pFile=%p, file=%p, rc=SQLITE_OK\n", osGetCurrentProcessId(), pFile, pFile->h)); return SQLITE_OK; } /* ** Write data from a buffer into a file. Return SQLITE_OK on success ** or some other error code on failure. */ static int winWrite( sqlite3_file *id, /* File to write into */ const void *pBuf, /* The bytes to be written */ int amt, /* Number of bytes to write */ sqlite3_int64 offset /* Offset into the file to begin writing at */ ){ int rc = 0; /* True if error has occurred, else false */ winFile *pFile = (winFile*)id; /* File handle */ int nRetry = 0; /* Number of retries */ assert( amt>0 ); assert( pFile ); SimulateIOError(return SQLITE_IOERR_WRITE); SimulateDiskfullError(return SQLITE_FULL); OSTRACE(("WRITE pid=%lu, pFile=%p, file=%p, buffer=%p, amount=%d, " "offset=%lld, lock=%d\n", osGetCurrentProcessId(), pFile, pFile->h, pBuf, amt, offset, pFile->locktype)); #if defined(SQLITE_MMAP_READWRITE) && SQLITE_MAX_MMAP_SIZE>0 /* Deal with as much of this write request as possible by transfering ** data from the memory mapping using memcpy(). */ if( offsetmmapSize ){ if( offset+amt <= pFile->mmapSize ){ memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, amt); OSTRACE(("WRITE-MMAP pid=%lu, pFile=%p, file=%p, rc=SQLITE_OK\n", osGetCurrentProcessId(), pFile, pFile->h)); return SQLITE_OK; }else{ int nCopy = (int)(pFile->mmapSize - offset); memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, nCopy); pBuf = &((u8 *)pBuf)[nCopy]; amt -= nCopy; offset += nCopy; } } #endif #if SQLITE_OS_WINCE || defined(SQLITE_WIN32_NO_OVERLAPPED) rc = winSeekFile(pFile, offset); if( rc==0 ){ #else { #endif #if !SQLITE_OS_WINCE && !defined(SQLITE_WIN32_NO_OVERLAPPED) OVERLAPPED overlapped; /* The offset for WriteFile. */ #endif u8 *aRem = (u8 *)pBuf; /* Data yet to be written */ int nRem = amt; /* Number of bytes yet to be written */ DWORD nWrite; /* Bytes written by each WriteFile() call */ DWORD lastErrno = NO_ERROR; /* Value returned by GetLastError() */ #if !SQLITE_OS_WINCE && !defined(SQLITE_WIN32_NO_OVERLAPPED) memset(&overlapped, 0, sizeof(OVERLAPPED)); overlapped.Offset = (LONG)(offset & 0xffffffff); overlapped.OffsetHigh = (LONG)((offset>>32) & 0x7fffffff); #endif while( nRem>0 ){ #if SQLITE_OS_WINCE || defined(SQLITE_WIN32_NO_OVERLAPPED) if( !osWriteFile(pFile->h, aRem, nRem, &nWrite, 0) ){ #else if( !osWriteFile(pFile->h, aRem, nRem, &nWrite, &overlapped) ){ #endif if( winRetryIoerr(&nRetry, &lastErrno) ) continue; break; } assert( nWrite==0 || nWrite<=(DWORD)nRem ); if( nWrite==0 || nWrite>(DWORD)nRem ){ lastErrno = osGetLastError(); break; } #if !SQLITE_OS_WINCE && !defined(SQLITE_WIN32_NO_OVERLAPPED) offset += nWrite; overlapped.Offset = (LONG)(offset & 0xffffffff); overlapped.OffsetHigh = (LONG)((offset>>32) & 0x7fffffff); #endif aRem += nWrite; nRem -= nWrite; } if( nRem>0 ){ pFile->lastErrno = lastErrno; rc = 1; } } if( rc ){ if( ( pFile->lastErrno==ERROR_HANDLE_DISK_FULL ) || ( pFile->lastErrno==ERROR_DISK_FULL )){ OSTRACE(("WRITE pid=%lu, pFile=%p, file=%p, rc=SQLITE_FULL\n", osGetCurrentProcessId(), pFile, pFile->h)); return winLogError(SQLITE_FULL, pFile->lastErrno, "winWrite1", pFile->zPath); } OSTRACE(("WRITE pid=%lu, pFile=%p, file=%p, rc=SQLITE_IOERR_WRITE\n", osGetCurrentProcessId(), pFile, pFile->h)); return winLogError(SQLITE_IOERR_WRITE, pFile->lastErrno, "winWrite2", pFile->zPath); }else{ winLogIoerr(nRetry, __LINE__); } OSTRACE(("WRITE pid=%lu, pFile=%p, file=%p, rc=SQLITE_OK\n", osGetCurrentProcessId(), pFile, pFile->h)); return SQLITE_OK; } /* ** Truncate an open file to a specified size */ static int winTruncate(sqlite3_file *id, sqlite3_int64 nByte){ winFile *pFile = (winFile*)id; /* File handle object */ int rc = SQLITE_OK; /* Return code for this function */ DWORD lastErrno; assert( pFile ); SimulateIOError(return SQLITE_IOERR_TRUNCATE); OSTRACE(("TRUNCATE pid=%lu, pFile=%p, file=%p, size=%lld, lock=%d\n", osGetCurrentProcessId(), pFile, pFile->h, nByte, pFile->locktype)); /* If the user has configured a chunk-size for this file, truncate the ** file so that it consists of an integer number of chunks (i.e. the ** actual file size after the operation may be larger than the requested ** size). */ if( pFile->szChunk>0 ){ nByte = ((nByte + pFile->szChunk - 1)/pFile->szChunk) * pFile->szChunk; } /* SetEndOfFile() returns non-zero when successful, or zero when it fails. */ if( winSeekFile(pFile, nByte) ){ rc = winLogError(SQLITE_IOERR_TRUNCATE, pFile->lastErrno, "winTruncate1", pFile->zPath); }else if( 0==osSetEndOfFile(pFile->h) && ((lastErrno = osGetLastError())!=ERROR_USER_MAPPED_FILE) ){ pFile->lastErrno = lastErrno; rc = winLogError(SQLITE_IOERR_TRUNCATE, pFile->lastErrno, "winTruncate2", pFile->zPath); } #if SQLITE_MAX_MMAP_SIZE>0 /* If the file was truncated to a size smaller than the currently ** mapped region, reduce the effective mapping size as well. SQLite will ** use read() and write() to access data beyond this point from now on. */ if( pFile->pMapRegion && nBytemmapSize ){ pFile->mmapSize = nByte; } #endif OSTRACE(("TRUNCATE pid=%lu, pFile=%p, file=%p, rc=%s\n", osGetCurrentProcessId(), pFile, pFile->h, sqlite3ErrName(rc))); return rc; } #ifdef SQLITE_TEST /* ** Count the number of fullsyncs and normal syncs. This is used to test ** that syncs and fullsyncs are occuring at the right times. */ SQLITE_API int sqlite3_sync_count = 0; SQLITE_API int sqlite3_fullsync_count = 0; #endif /* ** Make sure all writes to a particular file are committed to disk. */ static int winSync(sqlite3_file *id, int flags){ #ifndef SQLITE_NO_SYNC /* ** Used only when SQLITE_NO_SYNC is not defined. */ BOOL rc; #endif #if !defined(NDEBUG) || !defined(SQLITE_NO_SYNC) || \ defined(SQLITE_HAVE_OS_TRACE) /* ** Used when SQLITE_NO_SYNC is not defined and by the assert() and/or ** OSTRACE() macros. */ winFile *pFile = (winFile*)id; #else UNUSED_PARAMETER(id); #endif assert( pFile ); /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */ assert((flags&0x0F)==SQLITE_SYNC_NORMAL || (flags&0x0F)==SQLITE_SYNC_FULL ); /* Unix cannot, but some systems may return SQLITE_FULL from here. This ** line is to test that doing so does not cause any problems. */ SimulateDiskfullError( return SQLITE_FULL ); OSTRACE(("SYNC pid=%lu, pFile=%p, file=%p, flags=%x, lock=%d\n", osGetCurrentProcessId(), pFile, pFile->h, flags, pFile->locktype)); #ifndef SQLITE_TEST UNUSED_PARAMETER(flags); #else if( (flags&0x0F)==SQLITE_SYNC_FULL ){ sqlite3_fullsync_count++; } sqlite3_sync_count++; #endif /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a ** no-op */ #ifdef SQLITE_NO_SYNC OSTRACE(("SYNC-NOP pid=%lu, pFile=%p, file=%p, rc=SQLITE_OK\n", osGetCurrentProcessId(), pFile, pFile->h)); return SQLITE_OK; #else #if SQLITE_MAX_MMAP_SIZE>0 if( pFile->pMapRegion ){ if( osFlushViewOfFile(pFile->pMapRegion, 0) ){ OSTRACE(("SYNC-MMAP pid=%lu, pFile=%p, pMapRegion=%p, " "rc=SQLITE_OK\n", osGetCurrentProcessId(), pFile, pFile->pMapRegion)); }else{ pFile->lastErrno = osGetLastError(); OSTRACE(("SYNC-MMAP pid=%lu, pFile=%p, pMapRegion=%p, " "rc=SQLITE_IOERR_MMAP\n", osGetCurrentProcessId(), pFile, pFile->pMapRegion)); return winLogError(SQLITE_IOERR_MMAP, pFile->lastErrno, "winSync1", pFile->zPath); } } #endif rc = osFlushFileBuffers(pFile->h); SimulateIOError( rc=FALSE ); if( rc ){ OSTRACE(("SYNC pid=%lu, pFile=%p, file=%p, rc=SQLITE_OK\n", osGetCurrentProcessId(), pFile, pFile->h)); return SQLITE_OK; }else{ pFile->lastErrno = osGetLastError(); OSTRACE(("SYNC pid=%lu, pFile=%p, file=%p, rc=SQLITE_IOERR_FSYNC\n", osGetCurrentProcessId(), pFile, pFile->h)); return winLogError(SQLITE_IOERR_FSYNC, pFile->lastErrno, "winSync2", pFile->zPath); } #endif } /* ** Determine the current size of a file in bytes */ static int winFileSize(sqlite3_file *id, sqlite3_int64 *pSize){ winFile *pFile = (winFile*)id; int rc = SQLITE_OK; assert( id!=0 ); assert( pSize!=0 ); SimulateIOError(return SQLITE_IOERR_FSTAT); OSTRACE(("SIZE file=%p, pSize=%p\n", pFile->h, pSize)); #if SQLITE_OS_WINRT { FILE_STANDARD_INFO info; if( osGetFileInformationByHandleEx(pFile->h, FileStandardInfo, &info, sizeof(info)) ){ *pSize = info.EndOfFile.QuadPart; }else{ pFile->lastErrno = osGetLastError(); rc = winLogError(SQLITE_IOERR_FSTAT, pFile->lastErrno, "winFileSize", pFile->zPath); } } #else { DWORD upperBits; DWORD lowerBits; DWORD lastErrno; lowerBits = osGetFileSize(pFile->h, &upperBits); *pSize = (((sqlite3_int64)upperBits)<<32) + lowerBits; if( (lowerBits == INVALID_FILE_SIZE) && ((lastErrno = osGetLastError())!=NO_ERROR) ){ pFile->lastErrno = lastErrno; rc = winLogError(SQLITE_IOERR_FSTAT, pFile->lastErrno, "winFileSize", pFile->zPath); } } #endif OSTRACE(("SIZE file=%p, pSize=%p, *pSize=%lld, rc=%s\n", pFile->h, pSize, *pSize, sqlite3ErrName(rc))); return rc; } /* ** LOCKFILE_FAIL_IMMEDIATELY is undefined on some Windows systems. */ #ifndef LOCKFILE_FAIL_IMMEDIATELY # define LOCKFILE_FAIL_IMMEDIATELY 1 #endif #ifndef LOCKFILE_EXCLUSIVE_LOCK # define LOCKFILE_EXCLUSIVE_LOCK 2 #endif /* ** Historically, SQLite has used both the LockFile and LockFileEx functions. ** When the LockFile function was used, it was always expected to fail ** immediately if the lock could not be obtained. Also, it always expected to ** obtain an exclusive lock. These flags are used with the LockFileEx function ** and reflect those expectations; therefore, they should not be changed. */ #ifndef SQLITE_LOCKFILE_FLAGS # define SQLITE_LOCKFILE_FLAGS (LOCKFILE_FAIL_IMMEDIATELY | \ LOCKFILE_EXCLUSIVE_LOCK) #endif /* ** Currently, SQLite never calls the LockFileEx function without wanting the ** call to fail immediately if the lock cannot be obtained. */ #ifndef SQLITE_LOCKFILEEX_FLAGS # define SQLITE_LOCKFILEEX_FLAGS (LOCKFILE_FAIL_IMMEDIATELY) #endif /* ** Acquire a reader lock. ** Different API routines are called depending on whether or not this ** is Win9x or WinNT. */ static int winGetReadLock(winFile *pFile){ int res; OSTRACE(("READ-LOCK file=%p, lock=%d\n", pFile->h, pFile->locktype)); if( osIsNT() ){ #if SQLITE_OS_WINCE /* ** NOTE: Windows CE is handled differently here due its lack of the Win32 ** API LockFileEx. */ res = winceLockFile(&pFile->h, SHARED_FIRST, 0, 1, 0); #else res = winLockFile(&pFile->h, SQLITE_LOCKFILEEX_FLAGS, SHARED_FIRST, 0, SHARED_SIZE, 0); #endif } #ifdef SQLITE_WIN32_HAS_ANSI else{ int lk; sqlite3_randomness(sizeof(lk), &lk); pFile->sharedLockByte = (short)((lk & 0x7fffffff)%(SHARED_SIZE - 1)); res = winLockFile(&pFile->h, SQLITE_LOCKFILE_FLAGS, SHARED_FIRST+pFile->sharedLockByte, 0, 1, 0); } #endif if( res == 0 ){ pFile->lastErrno = osGetLastError(); /* No need to log a failure to lock */ } OSTRACE(("READ-LOCK file=%p, result=%d\n", pFile->h, res)); return res; } /* ** Undo a readlock */ static int winUnlockReadLock(winFile *pFile){ int res; DWORD lastErrno; OSTRACE(("READ-UNLOCK file=%p, lock=%d\n", pFile->h, pFile->locktype)); if( osIsNT() ){ res = winUnlockFile(&pFile->h, SHARED_FIRST, 0, SHARED_SIZE, 0); } #ifdef SQLITE_WIN32_HAS_ANSI else{ res = winUnlockFile(&pFile->h, SHARED_FIRST+pFile->sharedLockByte, 0, 1, 0); } #endif if( res==0 && ((lastErrno = osGetLastError())!=ERROR_NOT_LOCKED) ){ pFile->lastErrno = lastErrno; winLogError(SQLITE_IOERR_UNLOCK, pFile->lastErrno, "winUnlockReadLock", pFile->zPath); } OSTRACE(("READ-UNLOCK file=%p, result=%d\n", pFile->h, res)); return res; } /* ** Lock the file with the lock specified by parameter locktype - one ** of the following: ** ** (1) SHARED_LOCK ** (2) RESERVED_LOCK ** (3) PENDING_LOCK ** (4) EXCLUSIVE_LOCK ** ** Sometimes when requesting one lock state, additional lock states ** are inserted in between. The locking might fail on one of the later ** transitions leaving the lock state different from what it started but ** still short of its goal. The following chart shows the allowed ** transitions and the inserted intermediate states: ** ** UNLOCKED -> SHARED ** SHARED -> RESERVED ** SHARED -> (PENDING) -> EXCLUSIVE ** RESERVED -> (PENDING) -> EXCLUSIVE ** PENDING -> EXCLUSIVE ** ** This routine will only increase a lock. The winUnlock() routine ** erases all locks at once and returns us immediately to locking level 0. ** It is not possible to lower the locking level one step at a time. You ** must go straight to locking level 0. */ static int winLock(sqlite3_file *id, int locktype){ int rc = SQLITE_OK; /* Return code from subroutines */ int res = 1; /* Result of a Windows lock call */ int newLocktype; /* Set pFile->locktype to this value before exiting */ int gotPendingLock = 0;/* True if we acquired a PENDING lock this time */ winFile *pFile = (winFile*)id; DWORD lastErrno = NO_ERROR; assert( id!=0 ); OSTRACE(("LOCK file=%p, oldLock=%d(%d), newLock=%d\n", pFile->h, pFile->locktype, pFile->sharedLockByte, locktype)); /* If there is already a lock of this type or more restrictive on the ** OsFile, do nothing. Don't use the end_lock: exit path, as ** sqlite3OsEnterMutex() hasn't been called yet. */ if( pFile->locktype>=locktype ){ OSTRACE(("LOCK-HELD file=%p, rc=SQLITE_OK\n", pFile->h)); return SQLITE_OK; } /* Do not allow any kind of write-lock on a read-only database */ if( (pFile->ctrlFlags & WINFILE_RDONLY)!=0 && locktype>=RESERVED_LOCK ){ return SQLITE_IOERR_LOCK; } /* Make sure the locking sequence is correct */ assert( pFile->locktype!=NO_LOCK || locktype==SHARED_LOCK ); assert( locktype!=PENDING_LOCK ); assert( locktype!=RESERVED_LOCK || pFile->locktype==SHARED_LOCK ); /* Lock the PENDING_LOCK byte if we need to acquire a PENDING lock or ** a SHARED lock. If we are acquiring a SHARED lock, the acquisition of ** the PENDING_LOCK byte is temporary. */ newLocktype = pFile->locktype; if( pFile->locktype==NO_LOCK || (locktype==EXCLUSIVE_LOCK && pFile->locktype<=RESERVED_LOCK) ){ int cnt = 3; while( cnt-->0 && (res = winLockFile(&pFile->h, SQLITE_LOCKFILE_FLAGS, PENDING_BYTE, 0, 1, 0))==0 ){ /* Try 3 times to get the pending lock. This is needed to work ** around problems caused by indexing and/or anti-virus software on ** Windows systems. ** If you are using this code as a model for alternative VFSes, do not ** copy this retry logic. It is a hack intended for Windows only. */ lastErrno = osGetLastError(); OSTRACE(("LOCK-PENDING-FAIL file=%p, count=%d, result=%d\n", pFile->h, cnt, res)); if( lastErrno==ERROR_INVALID_HANDLE ){ pFile->lastErrno = lastErrno; rc = SQLITE_IOERR_LOCK; OSTRACE(("LOCK-FAIL file=%p, count=%d, rc=%s\n", pFile->h, cnt, sqlite3ErrName(rc))); return rc; } if( cnt ) sqlite3_win32_sleep(1); } gotPendingLock = res; if( !res ){ lastErrno = osGetLastError(); } } /* Acquire a shared lock */ if( locktype==SHARED_LOCK && res ){ assert( pFile->locktype==NO_LOCK ); res = winGetReadLock(pFile); if( res ){ newLocktype = SHARED_LOCK; }else{ lastErrno = osGetLastError(); } } /* Acquire a RESERVED lock */ if( locktype==RESERVED_LOCK && res ){ assert( pFile->locktype==SHARED_LOCK ); res = winLockFile(&pFile->h, SQLITE_LOCKFILE_FLAGS, RESERVED_BYTE, 0, 1, 0); if( res ){ newLocktype = RESERVED_LOCK; }else{ lastErrno = osGetLastError(); } } /* Acquire a PENDING lock */ if( locktype==EXCLUSIVE_LOCK && res ){ newLocktype = PENDING_LOCK; gotPendingLock = 0; } /* Acquire an EXCLUSIVE lock */ if( locktype==EXCLUSIVE_LOCK && res ){ assert( pFile->locktype>=SHARED_LOCK ); res = winUnlockReadLock(pFile); res = winLockFile(&pFile->h, SQLITE_LOCKFILE_FLAGS, SHARED_FIRST, 0, SHARED_SIZE, 0); if( res ){ newLocktype = EXCLUSIVE_LOCK; }else{ lastErrno = osGetLastError(); winGetReadLock(pFile); } } /* If we are holding a PENDING lock that ought to be released, then ** release it now. */ if( gotPendingLock && locktype==SHARED_LOCK ){ winUnlockFile(&pFile->h, PENDING_BYTE, 0, 1, 0); } /* Update the state of the lock has held in the file descriptor then ** return the appropriate result code. */ if( res ){ rc = SQLITE_OK; }else{ pFile->lastErrno = lastErrno; rc = SQLITE_BUSY; OSTRACE(("LOCK-FAIL file=%p, wanted=%d, got=%d\n", pFile->h, locktype, newLocktype)); } pFile->locktype = (u8)newLocktype; OSTRACE(("LOCK file=%p, lock=%d, rc=%s\n", pFile->h, pFile->locktype, sqlite3ErrName(rc))); return rc; } /* ** This routine checks if there is a RESERVED lock held on the specified ** file by this or any other process. If such a lock is held, return ** non-zero, otherwise zero. */ static int winCheckReservedLock(sqlite3_file *id, int *pResOut){ int res; winFile *pFile = (winFile*)id; SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; ); OSTRACE(("TEST-WR-LOCK file=%p, pResOut=%p\n", pFile->h, pResOut)); assert( id!=0 ); if( pFile->locktype>=RESERVED_LOCK ){ res = 1; OSTRACE(("TEST-WR-LOCK file=%p, result=%d (local)\n", pFile->h, res)); }else{ res = winLockFile(&pFile->h, SQLITE_LOCKFILEEX_FLAGS,RESERVED_BYTE,0,1,0); if( res ){ winUnlockFile(&pFile->h, RESERVED_BYTE, 0, 1, 0); } res = !res; OSTRACE(("TEST-WR-LOCK file=%p, result=%d (remote)\n", pFile->h, res)); } *pResOut = res; OSTRACE(("TEST-WR-LOCK file=%p, pResOut=%p, *pResOut=%d, rc=SQLITE_OK\n", pFile->h, pResOut, *pResOut)); return SQLITE_OK; } /* ** Lower the locking level on file descriptor id to locktype. locktype ** must be either NO_LOCK or SHARED_LOCK. ** ** If the locking level of the file descriptor is already at or below ** the requested locking level, this routine is a no-op. ** ** It is not possible for this routine to fail if the second argument ** is NO_LOCK. If the second argument is SHARED_LOCK then this routine ** might return SQLITE_IOERR; */ static int winUnlock(sqlite3_file *id, int locktype){ int type; winFile *pFile = (winFile*)id; int rc = SQLITE_OK; assert( pFile!=0 ); assert( locktype<=SHARED_LOCK ); OSTRACE(("UNLOCK file=%p, oldLock=%d(%d), newLock=%d\n", pFile->h, pFile->locktype, pFile->sharedLockByte, locktype)); type = pFile->locktype; if( type>=EXCLUSIVE_LOCK ){ winUnlockFile(&pFile->h, SHARED_FIRST, 0, SHARED_SIZE, 0); if( locktype==SHARED_LOCK && !winGetReadLock(pFile) ){ /* This should never happen. We should always be able to ** reacquire the read lock */ rc = winLogError(SQLITE_IOERR_UNLOCK, osGetLastError(), "winUnlock", pFile->zPath); } } if( type>=RESERVED_LOCK ){ winUnlockFile(&pFile->h, RESERVED_BYTE, 0, 1, 0); } if( locktype==NO_LOCK && type>=SHARED_LOCK ){ winUnlockReadLock(pFile); } if( type>=PENDING_LOCK ){ winUnlockFile(&pFile->h, PENDING_BYTE, 0, 1, 0); } pFile->locktype = (u8)locktype; OSTRACE(("UNLOCK file=%p, lock=%d, rc=%s\n", pFile->h, pFile->locktype, sqlite3ErrName(rc))); return rc; } /****************************************************************************** ****************************** No-op Locking ********************************** ** ** Of the various locking implementations available, this is by far the ** simplest: locking is ignored. No attempt is made to lock the database ** file for reading or writing. ** ** This locking mode is appropriate for use on read-only databases ** (ex: databases that are burned into CD-ROM, for example.) It can ** also be used if the application employs some external mechanism to ** prevent simultaneous access of the same database by two or more ** database connections. But there is a serious risk of database ** corruption if this locking mode is used in situations where multiple ** database connections are accessing the same database file at the same ** time and one or more of those connections are writing. */ static int winNolockLock(sqlite3_file *id, int locktype){ UNUSED_PARAMETER(id); UNUSED_PARAMETER(locktype); return SQLITE_OK; } static int winNolockCheckReservedLock(sqlite3_file *id, int *pResOut){ UNUSED_PARAMETER(id); UNUSED_PARAMETER(pResOut); return SQLITE_OK; } static int winNolockUnlock(sqlite3_file *id, int locktype){ UNUSED_PARAMETER(id); UNUSED_PARAMETER(locktype); return SQLITE_OK; } /******************* End of the no-op lock implementation ********************* ******************************************************************************/ /* ** If *pArg is initially negative then this is a query. Set *pArg to ** 1 or 0 depending on whether or not bit mask of pFile->ctrlFlags is set. ** ** If *pArg is 0 or 1, then clear or set the mask bit of pFile->ctrlFlags. */ static void winModeBit(winFile *pFile, unsigned char mask, int *pArg){ if( *pArg<0 ){ *pArg = (pFile->ctrlFlags & mask)!=0; }else if( (*pArg)==0 ){ pFile->ctrlFlags &= ~mask; }else{ pFile->ctrlFlags |= mask; } } /* Forward references to VFS helper methods used for temporary files */ static int winGetTempname(sqlite3_vfs *, char **); static int winIsDir(const void *); static BOOL winIsDriveLetterAndColon(const char *); /* ** Control and query of the open file handle. */ static int winFileControl(sqlite3_file *id, int op, void *pArg){ winFile *pFile = (winFile*)id; OSTRACE(("FCNTL file=%p, op=%d, pArg=%p\n", pFile->h, op, pArg)); switch( op ){ case SQLITE_FCNTL_LOCKSTATE: { *(int*)pArg = pFile->locktype; OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h)); return SQLITE_OK; } case SQLITE_FCNTL_LAST_ERRNO: { *(int*)pArg = (int)pFile->lastErrno; OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h)); return SQLITE_OK; } case SQLITE_FCNTL_CHUNK_SIZE: { pFile->szChunk = *(int *)pArg; OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h)); return SQLITE_OK; } case SQLITE_FCNTL_SIZE_HINT: { if( pFile->szChunk>0 ){ sqlite3_int64 oldSz; int rc = winFileSize(id, &oldSz); if( rc==SQLITE_OK ){ sqlite3_int64 newSz = *(sqlite3_int64*)pArg; if( newSz>oldSz ){ SimulateIOErrorBenign(1); rc = winTruncate(id, newSz); SimulateIOErrorBenign(0); } } OSTRACE(("FCNTL file=%p, rc=%s\n", pFile->h, sqlite3ErrName(rc))); return rc; } OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h)); return SQLITE_OK; } case SQLITE_FCNTL_PERSIST_WAL: { winModeBit(pFile, WINFILE_PERSIST_WAL, (int*)pArg); OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h)); return SQLITE_OK; } case SQLITE_FCNTL_POWERSAFE_OVERWRITE: { winModeBit(pFile, WINFILE_PSOW, (int*)pArg); OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h)); return SQLITE_OK; } case SQLITE_FCNTL_VFSNAME: { *(char**)pArg = sqlite3_mprintf("%s", pFile->pVfs->zName); OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h)); return SQLITE_OK; } case SQLITE_FCNTL_WIN32_AV_RETRY: { int *a = (int*)pArg; if( a[0]>0 ){ winIoerrRetry = a[0]; }else{ a[0] = winIoerrRetry; } if( a[1]>0 ){ winIoerrRetryDelay = a[1]; }else{ a[1] = winIoerrRetryDelay; } OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h)); return SQLITE_OK; } case SQLITE_FCNTL_WIN32_GET_HANDLE: { LPHANDLE phFile = (LPHANDLE)pArg; *phFile = pFile->h; OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h)); return SQLITE_OK; } #ifdef SQLITE_TEST case SQLITE_FCNTL_WIN32_SET_HANDLE: { LPHANDLE phFile = (LPHANDLE)pArg; HANDLE hOldFile = pFile->h; pFile->h = *phFile; *phFile = hOldFile; OSTRACE(("FCNTL oldFile=%p, newFile=%p, rc=SQLITE_OK\n", hOldFile, pFile->h)); return SQLITE_OK; } #endif case SQLITE_FCNTL_TEMPFILENAME: { char *zTFile = 0; int rc = winGetTempname(pFile->pVfs, &zTFile); if( rc==SQLITE_OK ){ *(char**)pArg = zTFile; } OSTRACE(("FCNTL file=%p, rc=%s\n", pFile->h, sqlite3ErrName(rc))); return rc; } #if SQLITE_MAX_MMAP_SIZE>0 case SQLITE_FCNTL_MMAP_SIZE: { i64 newLimit = *(i64*)pArg; int rc = SQLITE_OK; if( newLimit>sqlite3GlobalConfig.mxMmap ){ newLimit = sqlite3GlobalConfig.mxMmap; } *(i64*)pArg = pFile->mmapSizeMax; if( newLimit>=0 && newLimit!=pFile->mmapSizeMax && pFile->nFetchOut==0 ){ pFile->mmapSizeMax = newLimit; if( pFile->mmapSize>0 ){ winUnmapfile(pFile); rc = winMapfile(pFile, -1); } } OSTRACE(("FCNTL file=%p, rc=%s\n", pFile->h, sqlite3ErrName(rc))); return rc; } #endif } OSTRACE(("FCNTL file=%p, rc=SQLITE_NOTFOUND\n", pFile->h)); return SQLITE_NOTFOUND; } /* ** Return the sector size in bytes of the underlying block device for ** the specified file. This is almost always 512 bytes, but may be ** larger for some devices. ** ** SQLite code assumes this function cannot fail. It also assumes that ** if two files are created in the same file-system directory (i.e. ** a database and its journal file) that the sector size will be the ** same for both. */ static int winSectorSize(sqlite3_file *id){ (void)id; return SQLITE_DEFAULT_SECTOR_SIZE; } /* ** Return a vector of device characteristics. */ static int winDeviceCharacteristics(sqlite3_file *id){ winFile *p = (winFile*)id; return SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN | ((p->ctrlFlags & WINFILE_PSOW)?SQLITE_IOCAP_POWERSAFE_OVERWRITE:0); } /* ** Windows will only let you create file view mappings ** on allocation size granularity boundaries. ** During sqlite3_os_init() we do a GetSystemInfo() ** to get the granularity size. */ static SYSTEM_INFO winSysInfo; #ifndef SQLITE_OMIT_WAL /* ** Helper functions to obtain and relinquish the global mutex. The ** global mutex is used to protect the winLockInfo objects used by ** this file, all of which may be shared by multiple threads. ** ** Function winShmMutexHeld() is used to assert() that the global mutex ** is held when required. This function is only used as part of assert() ** statements. e.g. ** ** winShmEnterMutex() ** assert( winShmMutexHeld() ); ** winShmLeaveMutex() */ static void winShmEnterMutex(void){ sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_VFS1)); } static void winShmLeaveMutex(void){ sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_VFS1)); } #ifndef NDEBUG static int winShmMutexHeld(void) { return sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_VFS1)); } #endif /* ** Object used to represent a single file opened and mmapped to provide ** shared memory. When multiple threads all reference the same ** log-summary, each thread has its own winFile object, but they all ** point to a single instance of this object. In other words, each ** log-summary is opened only once per process. ** ** winShmMutexHeld() must be true when creating or destroying ** this object or while reading or writing the following fields: ** ** nRef ** pNext ** ** The following fields are read-only after the object is created: ** ** fid ** zFilename ** ** Either winShmNode.mutex must be held or winShmNode.nRef==0 and ** winShmMutexHeld() is true when reading or writing any other field ** in this structure. ** */ struct winShmNode { sqlite3_mutex *mutex; /* Mutex to access this object */ char *zFilename; /* Name of the file */ winFile hFile; /* File handle from winOpen */ int szRegion; /* Size of shared-memory regions */ int nRegion; /* Size of array apRegion */ struct ShmRegion { HANDLE hMap; /* File handle from CreateFileMapping */ void *pMap; } *aRegion; DWORD lastErrno; /* The Windows errno from the last I/O error */ int nRef; /* Number of winShm objects pointing to this */ winShm *pFirst; /* All winShm objects pointing to this */ winShmNode *pNext; /* Next in list of all winShmNode objects */ #if defined(SQLITE_DEBUG) || defined(SQLITE_HAVE_OS_TRACE) u8 nextShmId; /* Next available winShm.id value */ #endif }; /* ** A global array of all winShmNode objects. ** ** The winShmMutexHeld() must be true while reading or writing this list. */ static winShmNode *winShmNodeList = 0; /* ** Structure used internally by this VFS to record the state of an ** open shared memory connection. ** ** The following fields are initialized when this object is created and ** are read-only thereafter: ** ** winShm.pShmNode ** winShm.id ** ** All other fields are read/write. The winShm.pShmNode->mutex must be held ** while accessing any read/write fields. */ struct winShm { winShmNode *pShmNode; /* The underlying winShmNode object */ winShm *pNext; /* Next winShm with the same winShmNode */ u8 hasMutex; /* True if holding the winShmNode mutex */ u16 sharedMask; /* Mask of shared locks held */ u16 exclMask; /* Mask of exclusive locks held */ #if defined(SQLITE_DEBUG) || defined(SQLITE_HAVE_OS_TRACE) u8 id; /* Id of this connection with its winShmNode */ #endif }; /* ** Constants used for locking */ #define WIN_SHM_BASE ((22+SQLITE_SHM_NLOCK)*4) /* first lock byte */ #define WIN_SHM_DMS (WIN_SHM_BASE+SQLITE_SHM_NLOCK) /* deadman switch */ /* ** Apply advisory locks for all n bytes beginning at ofst. */ #define WINSHM_UNLCK 1 #define WINSHM_RDLCK 2 #define WINSHM_WRLCK 3 static int winShmSystemLock( winShmNode *pFile, /* Apply locks to this open shared-memory segment */ int lockType, /* WINSHM_UNLCK, WINSHM_RDLCK, or WINSHM_WRLCK */ int ofst, /* Offset to first byte to be locked/unlocked */ int nByte /* Number of bytes to lock or unlock */ ){ int rc = 0; /* Result code form Lock/UnlockFileEx() */ /* Access to the winShmNode object is serialized by the caller */ assert( sqlite3_mutex_held(pFile->mutex) || pFile->nRef==0 ); OSTRACE(("SHM-LOCK file=%p, lock=%d, offset=%d, size=%d\n", pFile->hFile.h, lockType, ofst, nByte)); /* Release/Acquire the system-level lock */ if( lockType==WINSHM_UNLCK ){ rc = winUnlockFile(&pFile->hFile.h, ofst, 0, nByte, 0); }else{ /* Initialize the locking parameters */ DWORD dwFlags = LOCKFILE_FAIL_IMMEDIATELY; if( lockType == WINSHM_WRLCK ) dwFlags |= LOCKFILE_EXCLUSIVE_LOCK; rc = winLockFile(&pFile->hFile.h, dwFlags, ofst, 0, nByte, 0); } if( rc!= 0 ){ rc = SQLITE_OK; }else{ pFile->lastErrno = osGetLastError(); rc = SQLITE_BUSY; } OSTRACE(("SHM-LOCK file=%p, func=%s, errno=%lu, rc=%s\n", pFile->hFile.h, (lockType == WINSHM_UNLCK) ? "winUnlockFile" : "winLockFile", pFile->lastErrno, sqlite3ErrName(rc))); return rc; } /* Forward references to VFS methods */ static int winOpen(sqlite3_vfs*,const char*,sqlite3_file*,int,int*); static int winDelete(sqlite3_vfs *,const char*,int); /* ** Purge the winShmNodeList list of all entries with winShmNode.nRef==0. ** ** This is not a VFS shared-memory method; it is a utility function called ** by VFS shared-memory methods. */ static void winShmPurge(sqlite3_vfs *pVfs, int deleteFlag){ winShmNode **pp; winShmNode *p; assert( winShmMutexHeld() ); OSTRACE(("SHM-PURGE pid=%lu, deleteFlag=%d\n", osGetCurrentProcessId(), deleteFlag)); pp = &winShmNodeList; while( (p = *pp)!=0 ){ if( p->nRef==0 ){ int i; if( p->mutex ){ sqlite3_mutex_free(p->mutex); } for(i=0; inRegion; i++){ BOOL bRc = osUnmapViewOfFile(p->aRegion[i].pMap); OSTRACE(("SHM-PURGE-UNMAP pid=%lu, region=%d, rc=%s\n", osGetCurrentProcessId(), i, bRc ? "ok" : "failed")); UNUSED_VARIABLE_VALUE(bRc); bRc = osCloseHandle(p->aRegion[i].hMap); OSTRACE(("SHM-PURGE-CLOSE pid=%lu, region=%d, rc=%s\n", osGetCurrentProcessId(), i, bRc ? "ok" : "failed")); UNUSED_VARIABLE_VALUE(bRc); } if( p->hFile.h!=NULL && p->hFile.h!=INVALID_HANDLE_VALUE ){ SimulateIOErrorBenign(1); winClose((sqlite3_file *)&p->hFile); SimulateIOErrorBenign(0); } if( deleteFlag ){ SimulateIOErrorBenign(1); sqlite3BeginBenignMalloc(); winDelete(pVfs, p->zFilename, 0); sqlite3EndBenignMalloc(); SimulateIOErrorBenign(0); } *pp = p->pNext; sqlite3_free(p->aRegion); sqlite3_free(p); }else{ pp = &p->pNext; } } } /* ** Open the shared-memory area associated with database file pDbFd. ** ** When opening a new shared-memory file, if no other instances of that ** file are currently open, in this process or in other processes, then ** the file must be truncated to zero length or have its header cleared. */ static int winOpenSharedMemory(winFile *pDbFd){ struct winShm *p; /* The connection to be opened */ struct winShmNode *pShmNode = 0; /* The underlying mmapped file */ int rc; /* Result code */ struct winShmNode *pNew; /* Newly allocated winShmNode */ int nName; /* Size of zName in bytes */ assert( pDbFd->pShm==0 ); /* Not previously opened */ /* Allocate space for the new sqlite3_shm object. Also speculatively ** allocate space for a new winShmNode and filename. */ p = sqlite3MallocZero( sizeof(*p) ); if( p==0 ) return SQLITE_IOERR_NOMEM_BKPT; nName = sqlite3Strlen30(pDbFd->zPath); pNew = sqlite3MallocZero( sizeof(*pShmNode) + nName + 17 ); if( pNew==0 ){ sqlite3_free(p); return SQLITE_IOERR_NOMEM_BKPT; } pNew->zFilename = (char*)&pNew[1]; sqlite3_snprintf(nName+15, pNew->zFilename, "%s-shm", pDbFd->zPath); sqlite3FileSuffix3(pDbFd->zPath, pNew->zFilename); /* Look to see if there is an existing winShmNode that can be used. ** If no matching winShmNode currently exists, create a new one. */ winShmEnterMutex(); for(pShmNode = winShmNodeList; pShmNode; pShmNode=pShmNode->pNext){ /* TBD need to come up with better match here. Perhaps ** use FILE_ID_BOTH_DIR_INFO Structure. */ if( sqlite3StrICmp(pShmNode->zFilename, pNew->zFilename)==0 ) break; } if( pShmNode ){ sqlite3_free(pNew); }else{ pShmNode = pNew; pNew = 0; ((winFile*)(&pShmNode->hFile))->h = INVALID_HANDLE_VALUE; pShmNode->pNext = winShmNodeList; winShmNodeList = pShmNode; if( sqlite3GlobalConfig.bCoreMutex ){ pShmNode->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST); if( pShmNode->mutex==0 ){ rc = SQLITE_IOERR_NOMEM_BKPT; goto shm_open_err; } } rc = winOpen(pDbFd->pVfs, pShmNode->zFilename, /* Name of the file (UTF-8) */ (sqlite3_file*)&pShmNode->hFile, /* File handle here */ SQLITE_OPEN_WAL | SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, 0); if( SQLITE_OK!=rc ){ goto shm_open_err; } /* Check to see if another process is holding the dead-man switch. ** If not, truncate the file to zero length. */ if( winShmSystemLock(pShmNode, WINSHM_WRLCK, WIN_SHM_DMS, 1)==SQLITE_OK ){ rc = winTruncate((sqlite3_file *)&pShmNode->hFile, 0); if( rc!=SQLITE_OK ){ rc = winLogError(SQLITE_IOERR_SHMOPEN, osGetLastError(), "winOpenShm", pDbFd->zPath); } } if( rc==SQLITE_OK ){ winShmSystemLock(pShmNode, WINSHM_UNLCK, WIN_SHM_DMS, 1); rc = winShmSystemLock(pShmNode, WINSHM_RDLCK, WIN_SHM_DMS, 1); } if( rc ) goto shm_open_err; } /* Make the new connection a child of the winShmNode */ p->pShmNode = pShmNode; #if defined(SQLITE_DEBUG) || defined(SQLITE_HAVE_OS_TRACE) p->id = pShmNode->nextShmId++; #endif pShmNode->nRef++; pDbFd->pShm = p; winShmLeaveMutex(); /* The reference count on pShmNode has already been incremented under ** the cover of the winShmEnterMutex() mutex and the pointer from the ** new (struct winShm) object to the pShmNode has been set. All that is ** left to do is to link the new object into the linked list starting ** at pShmNode->pFirst. This must be done while holding the pShmNode->mutex ** mutex. */ sqlite3_mutex_enter(pShmNode->mutex); p->pNext = pShmNode->pFirst; pShmNode->pFirst = p; sqlite3_mutex_leave(pShmNode->mutex); return SQLITE_OK; /* Jump here on any error */ shm_open_err: winShmSystemLock(pShmNode, WINSHM_UNLCK, WIN_SHM_DMS, 1); winShmPurge(pDbFd->pVfs, 0); /* This call frees pShmNode if required */ sqlite3_free(p); sqlite3_free(pNew); winShmLeaveMutex(); return rc; } /* ** Close a connection to shared-memory. Delete the underlying ** storage if deleteFlag is true. */ static int winShmUnmap( sqlite3_file *fd, /* Database holding shared memory */ int deleteFlag /* Delete after closing if true */ ){ winFile *pDbFd; /* Database holding shared-memory */ winShm *p; /* The connection to be closed */ winShmNode *pShmNode; /* The underlying shared-memory file */ winShm **pp; /* For looping over sibling connections */ pDbFd = (winFile*)fd; p = pDbFd->pShm; if( p==0 ) return SQLITE_OK; pShmNode = p->pShmNode; /* Remove connection p from the set of connections associated ** with pShmNode */ sqlite3_mutex_enter(pShmNode->mutex); for(pp=&pShmNode->pFirst; (*pp)!=p; pp = &(*pp)->pNext){} *pp = p->pNext; /* Free the connection p */ sqlite3_free(p); pDbFd->pShm = 0; sqlite3_mutex_leave(pShmNode->mutex); /* If pShmNode->nRef has reached 0, then close the underlying ** shared-memory file, too */ winShmEnterMutex(); assert( pShmNode->nRef>0 ); pShmNode->nRef--; if( pShmNode->nRef==0 ){ winShmPurge(pDbFd->pVfs, deleteFlag); } winShmLeaveMutex(); return SQLITE_OK; } /* ** Change the lock state for a shared-memory segment. */ static int winShmLock( sqlite3_file *fd, /* Database file holding the shared memory */ int ofst, /* First lock to acquire or release */ int n, /* Number of locks to acquire or release */ int flags /* What to do with the lock */ ){ winFile *pDbFd = (winFile*)fd; /* Connection holding shared memory */ winShm *p = pDbFd->pShm; /* The shared memory being locked */ winShm *pX; /* For looping over all siblings */ winShmNode *pShmNode = p->pShmNode; int rc = SQLITE_OK; /* Result code */ u16 mask; /* Mask of locks to take or release */ assert( ofst>=0 && ofst+n<=SQLITE_SHM_NLOCK ); assert( n>=1 ); assert( flags==(SQLITE_SHM_LOCK | SQLITE_SHM_SHARED) || flags==(SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE) || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED) || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE) ); assert( n==1 || (flags & SQLITE_SHM_EXCLUSIVE)!=0 ); mask = (u16)((1U<<(ofst+n)) - (1U<1 || mask==(1<mutex); if( flags & SQLITE_SHM_UNLOCK ){ u16 allMask = 0; /* Mask of locks held by siblings */ /* See if any siblings hold this same lock */ for(pX=pShmNode->pFirst; pX; pX=pX->pNext){ if( pX==p ) continue; assert( (pX->exclMask & (p->exclMask|p->sharedMask))==0 ); allMask |= pX->sharedMask; } /* Unlock the system-level locks */ if( (mask & allMask)==0 ){ rc = winShmSystemLock(pShmNode, WINSHM_UNLCK, ofst+WIN_SHM_BASE, n); }else{ rc = SQLITE_OK; } /* Undo the local locks */ if( rc==SQLITE_OK ){ p->exclMask &= ~mask; p->sharedMask &= ~mask; } }else if( flags & SQLITE_SHM_SHARED ){ u16 allShared = 0; /* Union of locks held by connections other than "p" */ /* Find out which shared locks are already held by sibling connections. ** If any sibling already holds an exclusive lock, go ahead and return ** SQLITE_BUSY. */ for(pX=pShmNode->pFirst; pX; pX=pX->pNext){ if( (pX->exclMask & mask)!=0 ){ rc = SQLITE_BUSY; break; } allShared |= pX->sharedMask; } /* Get shared locks at the system level, if necessary */ if( rc==SQLITE_OK ){ if( (allShared & mask)==0 ){ rc = winShmSystemLock(pShmNode, WINSHM_RDLCK, ofst+WIN_SHM_BASE, n); }else{ rc = SQLITE_OK; } } /* Get the local shared locks */ if( rc==SQLITE_OK ){ p->sharedMask |= mask; } }else{ /* Make sure no sibling connections hold locks that will block this ** lock. If any do, return SQLITE_BUSY right away. */ for(pX=pShmNode->pFirst; pX; pX=pX->pNext){ if( (pX->exclMask & mask)!=0 || (pX->sharedMask & mask)!=0 ){ rc = SQLITE_BUSY; break; } } /* Get the exclusive locks at the system level. Then if successful ** also mark the local connection as being locked. */ if( rc==SQLITE_OK ){ rc = winShmSystemLock(pShmNode, WINSHM_WRLCK, ofst+WIN_SHM_BASE, n); if( rc==SQLITE_OK ){ assert( (p->sharedMask & mask)==0 ); p->exclMask |= mask; } } } sqlite3_mutex_leave(pShmNode->mutex); OSTRACE(("SHM-LOCK pid=%lu, id=%d, sharedMask=%03x, exclMask=%03x, rc=%s\n", osGetCurrentProcessId(), p->id, p->sharedMask, p->exclMask, sqlite3ErrName(rc))); return rc; } /* ** Implement a memory barrier or memory fence on shared memory. ** ** All loads and stores begun before the barrier must complete before ** any load or store begun after the barrier. */ static void winShmBarrier( sqlite3_file *fd /* Database holding the shared memory */ ){ UNUSED_PARAMETER(fd); sqlite3MemoryBarrier(); /* compiler-defined memory barrier */ winShmEnterMutex(); /* Also mutex, for redundancy */ winShmLeaveMutex(); } /* ** This function is called to obtain a pointer to region iRegion of the ** shared-memory associated with the database file fd. Shared-memory regions ** are numbered starting from zero. Each shared-memory region is szRegion ** bytes in size. ** ** If an error occurs, an error code is returned and *pp is set to NULL. ** ** Otherwise, if the isWrite parameter is 0 and the requested shared-memory ** region has not been allocated (by any client, including one running in a ** separate process), then *pp is set to NULL and SQLITE_OK returned. If ** isWrite is non-zero and the requested shared-memory region has not yet ** been allocated, it is allocated by this function. ** ** If the shared-memory region has already been allocated or is allocated by ** this call as described above, then it is mapped into this processes ** address space (if it is not already), *pp is set to point to the mapped ** memory and SQLITE_OK returned. */ static int winShmMap( sqlite3_file *fd, /* Handle open on database file */ int iRegion, /* Region to retrieve */ int szRegion, /* Size of regions */ int isWrite, /* True to extend file if necessary */ void volatile **pp /* OUT: Mapped memory */ ){ winFile *pDbFd = (winFile*)fd; winShm *pShm = pDbFd->pShm; winShmNode *pShmNode; int rc = SQLITE_OK; if( !pShm ){ rc = winOpenSharedMemory(pDbFd); if( rc!=SQLITE_OK ) return rc; pShm = pDbFd->pShm; } pShmNode = pShm->pShmNode; sqlite3_mutex_enter(pShmNode->mutex); assert( szRegion==pShmNode->szRegion || pShmNode->nRegion==0 ); if( pShmNode->nRegion<=iRegion ){ struct ShmRegion *apNew; /* New aRegion[] array */ int nByte = (iRegion+1)*szRegion; /* Minimum required file size */ sqlite3_int64 sz; /* Current size of wal-index file */ pShmNode->szRegion = szRegion; /* The requested region is not mapped into this processes address space. ** Check to see if it has been allocated (i.e. if the wal-index file is ** large enough to contain the requested region). */ rc = winFileSize((sqlite3_file *)&pShmNode->hFile, &sz); if( rc!=SQLITE_OK ){ rc = winLogError(SQLITE_IOERR_SHMSIZE, osGetLastError(), "winShmMap1", pDbFd->zPath); goto shmpage_out; } if( szhFile, nByte); if( rc!=SQLITE_OK ){ rc = winLogError(SQLITE_IOERR_SHMSIZE, osGetLastError(), "winShmMap2", pDbFd->zPath); goto shmpage_out; } } /* Map the requested memory region into this processes address space. */ apNew = (struct ShmRegion *)sqlite3_realloc64( pShmNode->aRegion, (iRegion+1)*sizeof(apNew[0]) ); if( !apNew ){ rc = SQLITE_IOERR_NOMEM_BKPT; goto shmpage_out; } pShmNode->aRegion = apNew; while( pShmNode->nRegion<=iRegion ){ HANDLE hMap = NULL; /* file-mapping handle */ void *pMap = 0; /* Mapped memory region */ #if SQLITE_OS_WINRT hMap = osCreateFileMappingFromApp(pShmNode->hFile.h, NULL, PAGE_READWRITE, nByte, NULL ); #elif defined(SQLITE_WIN32_HAS_WIDE) hMap = osCreateFileMappingW(pShmNode->hFile.h, NULL, PAGE_READWRITE, 0, nByte, NULL ); #elif defined(SQLITE_WIN32_HAS_ANSI) && SQLITE_WIN32_CREATEFILEMAPPINGA hMap = osCreateFileMappingA(pShmNode->hFile.h, NULL, PAGE_READWRITE, 0, nByte, NULL ); #endif OSTRACE(("SHM-MAP-CREATE pid=%lu, region=%d, size=%d, rc=%s\n", osGetCurrentProcessId(), pShmNode->nRegion, nByte, hMap ? "ok" : "failed")); if( hMap ){ int iOffset = pShmNode->nRegion*szRegion; int iOffsetShift = iOffset % winSysInfo.dwAllocationGranularity; #if SQLITE_OS_WINRT pMap = osMapViewOfFileFromApp(hMap, FILE_MAP_WRITE | FILE_MAP_READ, iOffset - iOffsetShift, szRegion + iOffsetShift ); #else pMap = osMapViewOfFile(hMap, FILE_MAP_WRITE | FILE_MAP_READ, 0, iOffset - iOffsetShift, szRegion + iOffsetShift ); #endif OSTRACE(("SHM-MAP-MAP pid=%lu, region=%d, offset=%d, size=%d, rc=%s\n", osGetCurrentProcessId(), pShmNode->nRegion, iOffset, szRegion, pMap ? "ok" : "failed")); } if( !pMap ){ pShmNode->lastErrno = osGetLastError(); rc = winLogError(SQLITE_IOERR_SHMMAP, pShmNode->lastErrno, "winShmMap3", pDbFd->zPath); if( hMap ) osCloseHandle(hMap); goto shmpage_out; } pShmNode->aRegion[pShmNode->nRegion].pMap = pMap; pShmNode->aRegion[pShmNode->nRegion].hMap = hMap; pShmNode->nRegion++; } } shmpage_out: if( pShmNode->nRegion>iRegion ){ int iOffset = iRegion*szRegion; int iOffsetShift = iOffset % winSysInfo.dwAllocationGranularity; char *p = (char *)pShmNode->aRegion[iRegion].pMap; *pp = (void *)&p[iOffsetShift]; }else{ *pp = 0; } sqlite3_mutex_leave(pShmNode->mutex); return rc; } #else # define winShmMap 0 # define winShmLock 0 # define winShmBarrier 0 # define winShmUnmap 0 #endif /* #ifndef SQLITE_OMIT_WAL */ /* ** Cleans up the mapped region of the specified file, if any. */ #if SQLITE_MAX_MMAP_SIZE>0 static int winUnmapfile(winFile *pFile){ assert( pFile!=0 ); OSTRACE(("UNMAP-FILE pid=%lu, pFile=%p, hMap=%p, pMapRegion=%p, " "mmapSize=%lld, mmapSizeActual=%lld, mmapSizeMax=%lld\n", osGetCurrentProcessId(), pFile, pFile->hMap, pFile->pMapRegion, pFile->mmapSize, pFile->mmapSizeActual, pFile->mmapSizeMax)); if( pFile->pMapRegion ){ if( !osUnmapViewOfFile(pFile->pMapRegion) ){ pFile->lastErrno = osGetLastError(); OSTRACE(("UNMAP-FILE pid=%lu, pFile=%p, pMapRegion=%p, " "rc=SQLITE_IOERR_MMAP\n", osGetCurrentProcessId(), pFile, pFile->pMapRegion)); return winLogError(SQLITE_IOERR_MMAP, pFile->lastErrno, "winUnmapfile1", pFile->zPath); } pFile->pMapRegion = 0; pFile->mmapSize = 0; pFile->mmapSizeActual = 0; } if( pFile->hMap!=NULL ){ if( !osCloseHandle(pFile->hMap) ){ pFile->lastErrno = osGetLastError(); OSTRACE(("UNMAP-FILE pid=%lu, pFile=%p, hMap=%p, rc=SQLITE_IOERR_MMAP\n", osGetCurrentProcessId(), pFile, pFile->hMap)); return winLogError(SQLITE_IOERR_MMAP, pFile->lastErrno, "winUnmapfile2", pFile->zPath); } pFile->hMap = NULL; } OSTRACE(("UNMAP-FILE pid=%lu, pFile=%p, rc=SQLITE_OK\n", osGetCurrentProcessId(), pFile)); return SQLITE_OK; } /* ** Memory map or remap the file opened by file-descriptor pFd (if the file ** is already mapped, the existing mapping is replaced by the new). Or, if ** there already exists a mapping for this file, and there are still ** outstanding xFetch() references to it, this function is a no-op. ** ** If parameter nByte is non-negative, then it is the requested size of ** the mapping to create. Otherwise, if nByte is less than zero, then the ** requested size is the size of the file on disk. The actual size of the ** created mapping is either the requested size or the value configured ** using SQLITE_FCNTL_MMAP_SIZE, whichever is smaller. ** ** SQLITE_OK is returned if no error occurs (even if the mapping is not ** recreated as a result of outstanding references) or an SQLite error ** code otherwise. */ static int winMapfile(winFile *pFd, sqlite3_int64 nByte){ sqlite3_int64 nMap = nByte; int rc; assert( nMap>=0 || pFd->nFetchOut==0 ); OSTRACE(("MAP-FILE pid=%lu, pFile=%p, size=%lld\n", osGetCurrentProcessId(), pFd, nByte)); if( pFd->nFetchOut>0 ) return SQLITE_OK; if( nMap<0 ){ rc = winFileSize((sqlite3_file*)pFd, &nMap); if( rc ){ OSTRACE(("MAP-FILE pid=%lu, pFile=%p, rc=SQLITE_IOERR_FSTAT\n", osGetCurrentProcessId(), pFd)); return SQLITE_IOERR_FSTAT; } } if( nMap>pFd->mmapSizeMax ){ nMap = pFd->mmapSizeMax; } nMap &= ~(sqlite3_int64)(winSysInfo.dwPageSize - 1); if( nMap==0 && pFd->mmapSize>0 ){ winUnmapfile(pFd); } if( nMap!=pFd->mmapSize ){ void *pNew = 0; DWORD protect = PAGE_READONLY; DWORD flags = FILE_MAP_READ; winUnmapfile(pFd); #ifdef SQLITE_MMAP_READWRITE if( (pFd->ctrlFlags & WINFILE_RDONLY)==0 ){ protect = PAGE_READWRITE; flags |= FILE_MAP_WRITE; } #endif #if SQLITE_OS_WINRT pFd->hMap = osCreateFileMappingFromApp(pFd->h, NULL, protect, nMap, NULL); #elif defined(SQLITE_WIN32_HAS_WIDE) pFd->hMap = osCreateFileMappingW(pFd->h, NULL, protect, (DWORD)((nMap>>32) & 0xffffffff), (DWORD)(nMap & 0xffffffff), NULL); #elif defined(SQLITE_WIN32_HAS_ANSI) && SQLITE_WIN32_CREATEFILEMAPPINGA pFd->hMap = osCreateFileMappingA(pFd->h, NULL, protect, (DWORD)((nMap>>32) & 0xffffffff), (DWORD)(nMap & 0xffffffff), NULL); #endif if( pFd->hMap==NULL ){ pFd->lastErrno = osGetLastError(); rc = winLogError(SQLITE_IOERR_MMAP, pFd->lastErrno, "winMapfile1", pFd->zPath); /* Log the error, but continue normal operation using xRead/xWrite */ OSTRACE(("MAP-FILE-CREATE pid=%lu, pFile=%p, rc=%s\n", osGetCurrentProcessId(), pFd, sqlite3ErrName(rc))); return SQLITE_OK; } assert( (nMap % winSysInfo.dwPageSize)==0 ); assert( sizeof(SIZE_T)==sizeof(sqlite3_int64) || nMap<=0xffffffff ); #if SQLITE_OS_WINRT pNew = osMapViewOfFileFromApp(pFd->hMap, flags, 0, (SIZE_T)nMap); #else pNew = osMapViewOfFile(pFd->hMap, flags, 0, 0, (SIZE_T)nMap); #endif if( pNew==NULL ){ osCloseHandle(pFd->hMap); pFd->hMap = NULL; pFd->lastErrno = osGetLastError(); rc = winLogError(SQLITE_IOERR_MMAP, pFd->lastErrno, "winMapfile2", pFd->zPath); /* Log the error, but continue normal operation using xRead/xWrite */ OSTRACE(("MAP-FILE-MAP pid=%lu, pFile=%p, rc=%s\n", osGetCurrentProcessId(), pFd, sqlite3ErrName(rc))); return SQLITE_OK; } pFd->pMapRegion = pNew; pFd->mmapSize = nMap; pFd->mmapSizeActual = nMap; } OSTRACE(("MAP-FILE pid=%lu, pFile=%p, rc=SQLITE_OK\n", osGetCurrentProcessId(), pFd)); return SQLITE_OK; } #endif /* SQLITE_MAX_MMAP_SIZE>0 */ /* ** If possible, return a pointer to a mapping of file fd starting at offset ** iOff. The mapping must be valid for at least nAmt bytes. ** ** If such a pointer can be obtained, store it in *pp and return SQLITE_OK. ** Or, if one cannot but no error occurs, set *pp to 0 and return SQLITE_OK. ** Finally, if an error does occur, return an SQLite error code. The final ** value of *pp is undefined in this case. ** ** If this function does return a pointer, the caller must eventually ** release the reference by calling winUnfetch(). */ static int winFetch(sqlite3_file *fd, i64 iOff, int nAmt, void **pp){ #if SQLITE_MAX_MMAP_SIZE>0 winFile *pFd = (winFile*)fd; /* The underlying database file */ #endif *pp = 0; OSTRACE(("FETCH pid=%lu, pFile=%p, offset=%lld, amount=%d, pp=%p\n", osGetCurrentProcessId(), fd, iOff, nAmt, pp)); #if SQLITE_MAX_MMAP_SIZE>0 if( pFd->mmapSizeMax>0 ){ if( pFd->pMapRegion==0 ){ int rc = winMapfile(pFd, -1); if( rc!=SQLITE_OK ){ OSTRACE(("FETCH pid=%lu, pFile=%p, rc=%s\n", osGetCurrentProcessId(), pFd, sqlite3ErrName(rc))); return rc; } } if( pFd->mmapSize >= iOff+nAmt ){ *pp = &((u8 *)pFd->pMapRegion)[iOff]; pFd->nFetchOut++; } } #endif OSTRACE(("FETCH pid=%lu, pFile=%p, pp=%p, *pp=%p, rc=SQLITE_OK\n", osGetCurrentProcessId(), fd, pp, *pp)); return SQLITE_OK; } /* ** If the third argument is non-NULL, then this function releases a ** reference obtained by an earlier call to winFetch(). The second ** argument passed to this function must be the same as the corresponding ** argument that was passed to the winFetch() invocation. ** ** Or, if the third argument is NULL, then this function is being called ** to inform the VFS layer that, according to POSIX, any existing mapping ** may now be invalid and should be unmapped. */ static int winUnfetch(sqlite3_file *fd, i64 iOff, void *p){ #if SQLITE_MAX_MMAP_SIZE>0 winFile *pFd = (winFile*)fd; /* The underlying database file */ /* If p==0 (unmap the entire file) then there must be no outstanding ** xFetch references. Or, if p!=0 (meaning it is an xFetch reference), ** then there must be at least one outstanding. */ assert( (p==0)==(pFd->nFetchOut==0) ); /* If p!=0, it must match the iOff value. */ assert( p==0 || p==&((u8 *)pFd->pMapRegion)[iOff] ); OSTRACE(("UNFETCH pid=%lu, pFile=%p, offset=%lld, p=%p\n", osGetCurrentProcessId(), pFd, iOff, p)); if( p ){ pFd->nFetchOut--; }else{ /* FIXME: If Windows truly always prevents truncating or deleting a ** file while a mapping is held, then the following winUnmapfile() call ** is unnecessary can be omitted - potentially improving ** performance. */ winUnmapfile(pFd); } assert( pFd->nFetchOut>=0 ); #endif OSTRACE(("UNFETCH pid=%lu, pFile=%p, rc=SQLITE_OK\n", osGetCurrentProcessId(), fd)); return SQLITE_OK; } /* ** Here ends the implementation of all sqlite3_file methods. ** ********************** End sqlite3_file Methods ******************************* ******************************************************************************/ /* ** This vector defines all the methods that can operate on an ** sqlite3_file for win32. */ static const sqlite3_io_methods winIoMethod = { 3, /* iVersion */ winClose, /* xClose */ winRead, /* xRead */ winWrite, /* xWrite */ winTruncate, /* xTruncate */ winSync, /* xSync */ winFileSize, /* xFileSize */ winLock, /* xLock */ winUnlock, /* xUnlock */ winCheckReservedLock, /* xCheckReservedLock */ winFileControl, /* xFileControl */ winSectorSize, /* xSectorSize */ winDeviceCharacteristics, /* xDeviceCharacteristics */ winShmMap, /* xShmMap */ winShmLock, /* xShmLock */ winShmBarrier, /* xShmBarrier */ winShmUnmap, /* xShmUnmap */ winFetch, /* xFetch */ winUnfetch /* xUnfetch */ }; /* ** This vector defines all the methods that can operate on an ** sqlite3_file for win32 without performing any locking. */ static const sqlite3_io_methods winIoNolockMethod = { 3, /* iVersion */ winClose, /* xClose */ winRead, /* xRead */ winWrite, /* xWrite */ winTruncate, /* xTruncate */ winSync, /* xSync */ winFileSize, /* xFileSize */ winNolockLock, /* xLock */ winNolockUnlock, /* xUnlock */ winNolockCheckReservedLock, /* xCheckReservedLock */ winFileControl, /* xFileControl */ winSectorSize, /* xSectorSize */ winDeviceCharacteristics, /* xDeviceCharacteristics */ winShmMap, /* xShmMap */ winShmLock, /* xShmLock */ winShmBarrier, /* xShmBarrier */ winShmUnmap, /* xShmUnmap */ winFetch, /* xFetch */ winUnfetch /* xUnfetch */ }; static winVfsAppData winAppData = { &winIoMethod, /* pMethod */ 0, /* pAppData */ 0 /* bNoLock */ }; static winVfsAppData winNolockAppData = { &winIoNolockMethod, /* pMethod */ 0, /* pAppData */ 1 /* bNoLock */ }; /**************************************************************************** **************************** sqlite3_vfs methods **************************** ** ** This division contains the implementation of methods on the ** sqlite3_vfs object. */ #if defined(__CYGWIN__) /* ** Convert a filename from whatever the underlying operating system ** supports for filenames into UTF-8. Space to hold the result is ** obtained from malloc and must be freed by the calling function. */ static char *winConvertToUtf8Filename(const void *zFilename){ char *zConverted = 0; if( osIsNT() ){ zConverted = winUnicodeToUtf8(zFilename); } #ifdef SQLITE_WIN32_HAS_ANSI else{ zConverted = winMbcsToUtf8(zFilename, osAreFileApisANSI()); } #endif /* caller will handle out of memory */ return zConverted; } #endif /* ** Convert a UTF-8 filename into whatever form the underlying ** operating system wants filenames in. Space to hold the result ** is obtained from malloc and must be freed by the calling ** function. */ static void *winConvertFromUtf8Filename(const char *zFilename){ void *zConverted = 0; if( osIsNT() ){ zConverted = winUtf8ToUnicode(zFilename); } #ifdef SQLITE_WIN32_HAS_ANSI else{ zConverted = winUtf8ToMbcs(zFilename, osAreFileApisANSI()); } #endif /* caller will handle out of memory */ return zConverted; } /* ** This function returns non-zero if the specified UTF-8 string buffer ** ends with a directory separator character or one was successfully ** added to it. */ static int winMakeEndInDirSep(int nBuf, char *zBuf){ if( zBuf ){ int nLen = sqlite3Strlen30(zBuf); if( nLen>0 ){ if( winIsDirSep(zBuf[nLen-1]) ){ return 1; }else if( nLen+1mxPathname; nBuf = nMax + 2; zBuf = sqlite3MallocZero( nBuf ); if( !zBuf ){ OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n")); return SQLITE_IOERR_NOMEM_BKPT; } /* Figure out the effective temporary directory. First, check if one ** has been explicitly set by the application; otherwise, use the one ** configured by the operating system. */ nDir = nMax - (nPre + 15); assert( nDir>0 ); if( sqlite3_temp_directory ){ int nDirLen = sqlite3Strlen30(sqlite3_temp_directory); if( nDirLen>0 ){ if( !winIsDirSep(sqlite3_temp_directory[nDirLen-1]) ){ nDirLen++; } if( nDirLen>nDir ){ sqlite3_free(zBuf); OSTRACE(("TEMP-FILENAME rc=SQLITE_ERROR\n")); return winLogError(SQLITE_ERROR, 0, "winGetTempname1", 0); } sqlite3_snprintf(nMax, zBuf, "%s", sqlite3_temp_directory); } } #if defined(__CYGWIN__) else{ static const char *azDirs[] = { 0, /* getenv("SQLITE_TMPDIR") */ 0, /* getenv("TMPDIR") */ 0, /* getenv("TMP") */ 0, /* getenv("TEMP") */ 0, /* getenv("USERPROFILE") */ "/var/tmp", "/usr/tmp", "/tmp", ".", 0 /* List terminator */ }; unsigned int i; const char *zDir = 0; if( !azDirs[0] ) azDirs[0] = getenv("SQLITE_TMPDIR"); if( !azDirs[1] ) azDirs[1] = getenv("TMPDIR"); if( !azDirs[2] ) azDirs[2] = getenv("TMP"); if( !azDirs[3] ) azDirs[3] = getenv("TEMP"); if( !azDirs[4] ) azDirs[4] = getenv("USERPROFILE"); for(i=0; i/etilqs_XXXXXXXXXXXXXXX\0\0" ** ** If not, return SQLITE_ERROR. The number 17 is used here in order to ** account for the space used by the 15 character random suffix and the ** two trailing NUL characters. The final directory separator character ** has already added if it was not already present. */ nLen = sqlite3Strlen30(zBuf); if( (nLen + nPre + 17) > nBuf ){ sqlite3_free(zBuf); OSTRACE(("TEMP-FILENAME rc=SQLITE_ERROR\n")); return winLogError(SQLITE_ERROR, 0, "winGetTempname5", 0); } sqlite3_snprintf(nBuf-16-nLen, zBuf+nLen, SQLITE_TEMP_FILE_PREFIX); j = sqlite3Strlen30(zBuf); sqlite3_randomness(15, &zBuf[j]); for(i=0; i<15; i++, j++){ zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ]; } zBuf[j] = 0; zBuf[j+1] = 0; *pzBuf = zBuf; OSTRACE(("TEMP-FILENAME name=%s, rc=SQLITE_OK\n", zBuf)); return SQLITE_OK; } /* ** Return TRUE if the named file is really a directory. Return false if ** it is something other than a directory, or if there is any kind of memory ** allocation failure. */ static int winIsDir(const void *zConverted){ DWORD attr; int rc = 0; DWORD lastErrno; if( osIsNT() ){ int cnt = 0; WIN32_FILE_ATTRIBUTE_DATA sAttrData; memset(&sAttrData, 0, sizeof(sAttrData)); while( !(rc = osGetFileAttributesExW((LPCWSTR)zConverted, GetFileExInfoStandard, &sAttrData)) && winRetryIoerr(&cnt, &lastErrno) ){} if( !rc ){ return 0; /* Invalid name? */ } attr = sAttrData.dwFileAttributes; #if SQLITE_OS_WINCE==0 }else{ attr = osGetFileAttributesA((char*)zConverted); #endif } return (attr!=INVALID_FILE_ATTRIBUTES) && (attr&FILE_ATTRIBUTE_DIRECTORY); } /* ** Open a file. */ static int winOpen( sqlite3_vfs *pVfs, /* Used to get maximum path length and AppData */ const char *zName, /* Name of the file (UTF-8) */ sqlite3_file *id, /* Write the SQLite file handle here */ int flags, /* Open mode flags */ int *pOutFlags /* Status return flags */ ){ HANDLE h; DWORD lastErrno = 0; DWORD dwDesiredAccess; DWORD dwShareMode; DWORD dwCreationDisposition; DWORD dwFlagsAndAttributes = 0; #if SQLITE_OS_WINCE int isTemp = 0; #endif winVfsAppData *pAppData; winFile *pFile = (winFile*)id; void *zConverted; /* Filename in OS encoding */ const char *zUtf8Name = zName; /* Filename in UTF-8 encoding */ int cnt = 0; /* If argument zPath is a NULL pointer, this function is required to open ** a temporary file. Use this buffer to store the file name in. */ char *zTmpname = 0; /* For temporary filename, if necessary. */ int rc = SQLITE_OK; /* Function Return Code */ #if !defined(NDEBUG) || SQLITE_OS_WINCE int eType = flags&0xFFFFFF00; /* Type of file to open */ #endif int isExclusive = (flags & SQLITE_OPEN_EXCLUSIVE); int isDelete = (flags & SQLITE_OPEN_DELETEONCLOSE); int isCreate = (flags & SQLITE_OPEN_CREATE); int isReadonly = (flags & SQLITE_OPEN_READONLY); int isReadWrite = (flags & SQLITE_OPEN_READWRITE); #ifndef NDEBUG int isOpenJournal = (isCreate && ( eType==SQLITE_OPEN_MASTER_JOURNAL || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_WAL )); #endif OSTRACE(("OPEN name=%s, pFile=%p, flags=%x, pOutFlags=%p\n", zUtf8Name, id, flags, pOutFlags)); /* Check the following statements are true: ** ** (a) Exactly one of the READWRITE and READONLY flags must be set, and ** (b) if CREATE is set, then READWRITE must also be set, and ** (c) if EXCLUSIVE is set, then CREATE must also be set. ** (d) if DELETEONCLOSE is set, then CREATE must also be set. */ assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly)); assert(isCreate==0 || isReadWrite); assert(isExclusive==0 || isCreate); assert(isDelete==0 || isCreate); /* The main DB, main journal, WAL file and master journal are never ** automatically deleted. Nor are they ever temporary files. */ assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB ); assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL ); assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL ); assert( (!isDelete && zName) || eType!=SQLITE_OPEN_WAL ); /* Assert that the upper layer has set one of the "file-type" flags. */ assert( eType==SQLITE_OPEN_MAIN_DB || eType==SQLITE_OPEN_TEMP_DB || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL || eType==SQLITE_OPEN_SUBJOURNAL || eType==SQLITE_OPEN_MASTER_JOURNAL || eType==SQLITE_OPEN_TRANSIENT_DB || eType==SQLITE_OPEN_WAL ); assert( pFile!=0 ); memset(pFile, 0, sizeof(winFile)); pFile->h = INVALID_HANDLE_VALUE; #if SQLITE_OS_WINRT if( !zUtf8Name && !sqlite3_temp_directory ){ sqlite3_log(SQLITE_ERROR, "sqlite3_temp_directory variable should be set for WinRT"); } #endif /* If the second argument to this function is NULL, generate a ** temporary file name to use */ if( !zUtf8Name ){ assert( isDelete && !isOpenJournal ); rc = winGetTempname(pVfs, &zTmpname); if( rc!=SQLITE_OK ){ OSTRACE(("OPEN name=%s, rc=%s", zUtf8Name, sqlite3ErrName(rc))); return rc; } zUtf8Name = zTmpname; } /* Database filenames are double-zero terminated if they are not ** URIs with parameters. Hence, they can always be passed into ** sqlite3_uri_parameter(). */ assert( (eType!=SQLITE_OPEN_MAIN_DB) || (flags & SQLITE_OPEN_URI) || zUtf8Name[sqlite3Strlen30(zUtf8Name)+1]==0 ); /* Convert the filename to the system encoding. */ zConverted = winConvertFromUtf8Filename(zUtf8Name); if( zConverted==0 ){ sqlite3_free(zTmpname); OSTRACE(("OPEN name=%s, rc=SQLITE_IOERR_NOMEM", zUtf8Name)); return SQLITE_IOERR_NOMEM_BKPT; } if( winIsDir(zConverted) ){ sqlite3_free(zConverted); sqlite3_free(zTmpname); OSTRACE(("OPEN name=%s, rc=SQLITE_CANTOPEN_ISDIR", zUtf8Name)); return SQLITE_CANTOPEN_ISDIR; } if( isReadWrite ){ dwDesiredAccess = GENERIC_READ | GENERIC_WRITE; }else{ dwDesiredAccess = GENERIC_READ; } /* SQLITE_OPEN_EXCLUSIVE is used to make sure that a new file is ** created. SQLite doesn't use it to indicate "exclusive access" ** as it is usually understood. */ if( isExclusive ){ /* Creates a new file, only if it does not already exist. */ /* If the file exists, it fails. */ dwCreationDisposition = CREATE_NEW; }else if( isCreate ){ /* Open existing file, or create if it doesn't exist */ dwCreationDisposition = OPEN_ALWAYS; }else{ /* Opens a file, only if it exists. */ dwCreationDisposition = OPEN_EXISTING; } dwShareMode = FILE_SHARE_READ | FILE_SHARE_WRITE; if( isDelete ){ #if SQLITE_OS_WINCE dwFlagsAndAttributes = FILE_ATTRIBUTE_HIDDEN; isTemp = 1; #else dwFlagsAndAttributes = FILE_ATTRIBUTE_TEMPORARY | FILE_ATTRIBUTE_HIDDEN | FILE_FLAG_DELETE_ON_CLOSE; #endif }else{ dwFlagsAndAttributes = FILE_ATTRIBUTE_NORMAL; } /* Reports from the internet are that performance is always ** better if FILE_FLAG_RANDOM_ACCESS is used. Ticket #2699. */ #if SQLITE_OS_WINCE dwFlagsAndAttributes |= FILE_FLAG_RANDOM_ACCESS; #endif if( osIsNT() ){ #if SQLITE_OS_WINRT CREATEFILE2_EXTENDED_PARAMETERS extendedParameters; extendedParameters.dwSize = sizeof(CREATEFILE2_EXTENDED_PARAMETERS); extendedParameters.dwFileAttributes = dwFlagsAndAttributes & FILE_ATTRIBUTE_MASK; extendedParameters.dwFileFlags = dwFlagsAndAttributes & FILE_FLAG_MASK; extendedParameters.dwSecurityQosFlags = SECURITY_ANONYMOUS; extendedParameters.lpSecurityAttributes = NULL; extendedParameters.hTemplateFile = NULL; while( (h = osCreateFile2((LPCWSTR)zConverted, dwDesiredAccess, dwShareMode, dwCreationDisposition, &extendedParameters))==INVALID_HANDLE_VALUE && winRetryIoerr(&cnt, &lastErrno) ){ /* Noop */ } #else while( (h = osCreateFileW((LPCWSTR)zConverted, dwDesiredAccess, dwShareMode, NULL, dwCreationDisposition, dwFlagsAndAttributes, NULL))==INVALID_HANDLE_VALUE && winRetryIoerr(&cnt, &lastErrno) ){ /* Noop */ } #endif } #ifdef SQLITE_WIN32_HAS_ANSI else{ while( (h = osCreateFileA((LPCSTR)zConverted, dwDesiredAccess, dwShareMode, NULL, dwCreationDisposition, dwFlagsAndAttributes, NULL))==INVALID_HANDLE_VALUE && winRetryIoerr(&cnt, &lastErrno) ){ /* Noop */ } } #endif winLogIoerr(cnt, __LINE__); OSTRACE(("OPEN file=%p, name=%s, access=%lx, rc=%s\n", h, zUtf8Name, dwDesiredAccess, (h==INVALID_HANDLE_VALUE) ? "failed" : "ok")); if( h==INVALID_HANDLE_VALUE ){ pFile->lastErrno = lastErrno; winLogError(SQLITE_CANTOPEN, pFile->lastErrno, "winOpen", zUtf8Name); sqlite3_free(zConverted); sqlite3_free(zTmpname); if( isReadWrite && !isExclusive ){ return winOpen(pVfs, zName, id, ((flags|SQLITE_OPEN_READONLY) & ~(SQLITE_OPEN_CREATE|SQLITE_OPEN_READWRITE)), pOutFlags); }else{ return SQLITE_CANTOPEN_BKPT; } } if( pOutFlags ){ if( isReadWrite ){ *pOutFlags = SQLITE_OPEN_READWRITE; }else{ *pOutFlags = SQLITE_OPEN_READONLY; } } OSTRACE(("OPEN file=%p, name=%s, access=%lx, pOutFlags=%p, *pOutFlags=%d, " "rc=%s\n", h, zUtf8Name, dwDesiredAccess, pOutFlags, pOutFlags ? *pOutFlags : 0, (h==INVALID_HANDLE_VALUE) ? "failed" : "ok")); pAppData = (winVfsAppData*)pVfs->pAppData; #if SQLITE_OS_WINCE { if( isReadWrite && eType==SQLITE_OPEN_MAIN_DB && ((pAppData==NULL) || !pAppData->bNoLock) && (rc = winceCreateLock(zName, pFile))!=SQLITE_OK ){ osCloseHandle(h); sqlite3_free(zConverted); sqlite3_free(zTmpname); OSTRACE(("OPEN-CE-LOCK name=%s, rc=%s\n", zName, sqlite3ErrName(rc))); return rc; } } if( isTemp ){ pFile->zDeleteOnClose = zConverted; }else #endif { sqlite3_free(zConverted); } sqlite3_free(zTmpname); pFile->pMethod = pAppData ? pAppData->pMethod : &winIoMethod; pFile->pVfs = pVfs; pFile->h = h; if( isReadonly ){ pFile->ctrlFlags |= WINFILE_RDONLY; } if( sqlite3_uri_boolean(zName, "psow", SQLITE_POWERSAFE_OVERWRITE) ){ pFile->ctrlFlags |= WINFILE_PSOW; } pFile->lastErrno = NO_ERROR; pFile->zPath = zName; #if SQLITE_MAX_MMAP_SIZE>0 pFile->hMap = NULL; pFile->pMapRegion = 0; pFile->mmapSize = 0; pFile->mmapSizeActual = 0; pFile->mmapSizeMax = sqlite3GlobalConfig.szMmap; #endif OpenCounter(+1); return rc; } /* ** Delete the named file. ** ** Note that Windows does not allow a file to be deleted if some other ** process has it open. Sometimes a virus scanner or indexing program ** will open a journal file shortly after it is created in order to do ** whatever it does. While this other process is holding the ** file open, we will be unable to delete it. To work around this ** problem, we delay 100 milliseconds and try to delete again. Up ** to MX_DELETION_ATTEMPTs deletion attempts are run before giving ** up and returning an error. */ static int winDelete( sqlite3_vfs *pVfs, /* Not used on win32 */ const char *zFilename, /* Name of file to delete */ int syncDir /* Not used on win32 */ ){ int cnt = 0; int rc; DWORD attr; DWORD lastErrno = 0; void *zConverted; UNUSED_PARAMETER(pVfs); UNUSED_PARAMETER(syncDir); SimulateIOError(return SQLITE_IOERR_DELETE); OSTRACE(("DELETE name=%s, syncDir=%d\n", zFilename, syncDir)); zConverted = winConvertFromUtf8Filename(zFilename); if( zConverted==0 ){ OSTRACE(("DELETE name=%s, rc=SQLITE_IOERR_NOMEM\n", zFilename)); return SQLITE_IOERR_NOMEM_BKPT; } if( osIsNT() ){ do { #if SQLITE_OS_WINRT WIN32_FILE_ATTRIBUTE_DATA sAttrData; memset(&sAttrData, 0, sizeof(sAttrData)); if ( osGetFileAttributesExW(zConverted, GetFileExInfoStandard, &sAttrData) ){ attr = sAttrData.dwFileAttributes; }else{ lastErrno = osGetLastError(); if( lastErrno==ERROR_FILE_NOT_FOUND || lastErrno==ERROR_PATH_NOT_FOUND ){ rc = SQLITE_IOERR_DELETE_NOENT; /* Already gone? */ }else{ rc = SQLITE_ERROR; } break; } #else attr = osGetFileAttributesW(zConverted); #endif if ( attr==INVALID_FILE_ATTRIBUTES ){ lastErrno = osGetLastError(); if( lastErrno==ERROR_FILE_NOT_FOUND || lastErrno==ERROR_PATH_NOT_FOUND ){ rc = SQLITE_IOERR_DELETE_NOENT; /* Already gone? */ }else{ rc = SQLITE_ERROR; } break; } if ( attr&FILE_ATTRIBUTE_DIRECTORY ){ rc = SQLITE_ERROR; /* Files only. */ break; } if ( osDeleteFileW(zConverted) ){ rc = SQLITE_OK; /* Deleted OK. */ break; } if ( !winRetryIoerr(&cnt, &lastErrno) ){ rc = SQLITE_ERROR; /* No more retries. */ break; } } while(1); } #ifdef SQLITE_WIN32_HAS_ANSI else{ do { attr = osGetFileAttributesA(zConverted); if ( attr==INVALID_FILE_ATTRIBUTES ){ lastErrno = osGetLastError(); if( lastErrno==ERROR_FILE_NOT_FOUND || lastErrno==ERROR_PATH_NOT_FOUND ){ rc = SQLITE_IOERR_DELETE_NOENT; /* Already gone? */ }else{ rc = SQLITE_ERROR; } break; } if ( attr&FILE_ATTRIBUTE_DIRECTORY ){ rc = SQLITE_ERROR; /* Files only. */ break; } if ( osDeleteFileA(zConverted) ){ rc = SQLITE_OK; /* Deleted OK. */ break; } if ( !winRetryIoerr(&cnt, &lastErrno) ){ rc = SQLITE_ERROR; /* No more retries. */ break; } } while(1); } #endif if( rc && rc!=SQLITE_IOERR_DELETE_NOENT ){ rc = winLogError(SQLITE_IOERR_DELETE, lastErrno, "winDelete", zFilename); }else{ winLogIoerr(cnt, __LINE__); } sqlite3_free(zConverted); OSTRACE(("DELETE name=%s, rc=%s\n", zFilename, sqlite3ErrName(rc))); return rc; } /* ** Check the existence and status of a file. */ static int winAccess( sqlite3_vfs *pVfs, /* Not used on win32 */ const char *zFilename, /* Name of file to check */ int flags, /* Type of test to make on this file */ int *pResOut /* OUT: Result */ ){ DWORD attr; int rc = 0; DWORD lastErrno = 0; void *zConverted; UNUSED_PARAMETER(pVfs); SimulateIOError( return SQLITE_IOERR_ACCESS; ); OSTRACE(("ACCESS name=%s, flags=%x, pResOut=%p\n", zFilename, flags, pResOut)); zConverted = winConvertFromUtf8Filename(zFilename); if( zConverted==0 ){ OSTRACE(("ACCESS name=%s, rc=SQLITE_IOERR_NOMEM\n", zFilename)); return SQLITE_IOERR_NOMEM_BKPT; } if( osIsNT() ){ int cnt = 0; WIN32_FILE_ATTRIBUTE_DATA sAttrData; memset(&sAttrData, 0, sizeof(sAttrData)); while( !(rc = osGetFileAttributesExW((LPCWSTR)zConverted, GetFileExInfoStandard, &sAttrData)) && winRetryIoerr(&cnt, &lastErrno) ){} if( rc ){ /* For an SQLITE_ACCESS_EXISTS query, treat a zero-length file ** as if it does not exist. */ if( flags==SQLITE_ACCESS_EXISTS && sAttrData.nFileSizeHigh==0 && sAttrData.nFileSizeLow==0 ){ attr = INVALID_FILE_ATTRIBUTES; }else{ attr = sAttrData.dwFileAttributes; } }else{ winLogIoerr(cnt, __LINE__); if( lastErrno!=ERROR_FILE_NOT_FOUND && lastErrno!=ERROR_PATH_NOT_FOUND ){ sqlite3_free(zConverted); return winLogError(SQLITE_IOERR_ACCESS, lastErrno, "winAccess", zFilename); }else{ attr = INVALID_FILE_ATTRIBUTES; } } } #ifdef SQLITE_WIN32_HAS_ANSI else{ attr = osGetFileAttributesA((char*)zConverted); } #endif sqlite3_free(zConverted); switch( flags ){ case SQLITE_ACCESS_READ: case SQLITE_ACCESS_EXISTS: rc = attr!=INVALID_FILE_ATTRIBUTES; break; case SQLITE_ACCESS_READWRITE: rc = attr!=INVALID_FILE_ATTRIBUTES && (attr & FILE_ATTRIBUTE_READONLY)==0; break; default: assert(!"Invalid flags argument"); } *pResOut = rc; OSTRACE(("ACCESS name=%s, pResOut=%p, *pResOut=%d, rc=SQLITE_OK\n", zFilename, pResOut, *pResOut)); return SQLITE_OK; } /* ** Returns non-zero if the specified path name starts with a drive letter ** followed by a colon character. */ static BOOL winIsDriveLetterAndColon( const char *zPathname ){ return ( sqlite3Isalpha(zPathname[0]) && zPathname[1]==':' ); } /* ** Returns non-zero if the specified path name should be used verbatim. If ** non-zero is returned from this function, the calling function must simply ** use the provided path name verbatim -OR- resolve it into a full path name ** using the GetFullPathName Win32 API function (if available). */ static BOOL winIsVerbatimPathname( const char *zPathname ){ /* ** If the path name starts with a forward slash or a backslash, it is either ** a legal UNC name, a volume relative path, or an absolute path name in the ** "Unix" format on Windows. There is no easy way to differentiate between ** the final two cases; therefore, we return the safer return value of TRUE ** so that callers of this function will simply use it verbatim. */ if ( winIsDirSep(zPathname[0]) ){ return TRUE; } /* ** If the path name starts with a letter and a colon it is either a volume ** relative path or an absolute path. Callers of this function must not ** attempt to treat it as a relative path name (i.e. they should simply use ** it verbatim). */ if ( winIsDriveLetterAndColon(zPathname) ){ return TRUE; } /* ** If we get to this point, the path name should almost certainly be a purely ** relative one (i.e. not a UNC name, not absolute, and not volume relative). */ return FALSE; } /* ** Turn a relative pathname into a full pathname. Write the full ** pathname into zOut[]. zOut[] will be at least pVfs->mxPathname ** bytes in size. */ static int winFullPathname( sqlite3_vfs *pVfs, /* Pointer to vfs object */ const char *zRelative, /* Possibly relative input path */ int nFull, /* Size of output buffer in bytes */ char *zFull /* Output buffer */ ){ #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && !defined(__CYGWIN__) DWORD nByte; void *zConverted; char *zOut; #endif /* If this path name begins with "/X:", where "X" is any alphabetic ** character, discard the initial "/" from the pathname. */ if( zRelative[0]=='/' && winIsDriveLetterAndColon(zRelative+1) ){ zRelative++; } #if defined(__CYGWIN__) SimulateIOError( return SQLITE_ERROR ); UNUSED_PARAMETER(nFull); assert( nFull>=pVfs->mxPathname ); if ( sqlite3_data_directory && !winIsVerbatimPathname(zRelative) ){ /* ** NOTE: We are dealing with a relative path name and the data ** directory has been set. Therefore, use it as the basis ** for converting the relative path name to an absolute ** one by prepending the data directory and a slash. */ char *zOut = sqlite3MallocZero( pVfs->mxPathname+1 ); if( !zOut ){ return SQLITE_IOERR_NOMEM_BKPT; } if( cygwin_conv_path( (osIsNT() ? CCP_POSIX_TO_WIN_W : CCP_POSIX_TO_WIN_A) | CCP_RELATIVE, zRelative, zOut, pVfs->mxPathname+1)<0 ){ sqlite3_free(zOut); return winLogError(SQLITE_CANTOPEN_CONVPATH, (DWORD)errno, "winFullPathname1", zRelative); }else{ char *zUtf8 = winConvertToUtf8Filename(zOut); if( !zUtf8 ){ sqlite3_free(zOut); return SQLITE_IOERR_NOMEM_BKPT; } sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s%c%s", sqlite3_data_directory, winGetDirSep(), zUtf8); sqlite3_free(zUtf8); sqlite3_free(zOut); } }else{ char *zOut = sqlite3MallocZero( pVfs->mxPathname+1 ); if( !zOut ){ return SQLITE_IOERR_NOMEM_BKPT; } if( cygwin_conv_path( (osIsNT() ? CCP_POSIX_TO_WIN_W : CCP_POSIX_TO_WIN_A), zRelative, zOut, pVfs->mxPathname+1)<0 ){ sqlite3_free(zOut); return winLogError(SQLITE_CANTOPEN_CONVPATH, (DWORD)errno, "winFullPathname2", zRelative); }else{ char *zUtf8 = winConvertToUtf8Filename(zOut); if( !zUtf8 ){ sqlite3_free(zOut); return SQLITE_IOERR_NOMEM_BKPT; } sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s", zUtf8); sqlite3_free(zUtf8); sqlite3_free(zOut); } } return SQLITE_OK; #endif #if (SQLITE_OS_WINCE || SQLITE_OS_WINRT) && !defined(__CYGWIN__) SimulateIOError( return SQLITE_ERROR ); /* WinCE has no concept of a relative pathname, or so I am told. */ /* WinRT has no way to convert a relative path to an absolute one. */ if ( sqlite3_data_directory && !winIsVerbatimPathname(zRelative) ){ /* ** NOTE: We are dealing with a relative path name and the data ** directory has been set. Therefore, use it as the basis ** for converting the relative path name to an absolute ** one by prepending the data directory and a backslash. */ sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s%c%s", sqlite3_data_directory, winGetDirSep(), zRelative); }else{ sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s", zRelative); } return SQLITE_OK; #endif #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && !defined(__CYGWIN__) /* It's odd to simulate an io-error here, but really this is just ** using the io-error infrastructure to test that SQLite handles this ** function failing. This function could fail if, for example, the ** current working directory has been unlinked. */ SimulateIOError( return SQLITE_ERROR ); if ( sqlite3_data_directory && !winIsVerbatimPathname(zRelative) ){ /* ** NOTE: We are dealing with a relative path name and the data ** directory has been set. Therefore, use it as the basis ** for converting the relative path name to an absolute ** one by prepending the data directory and a backslash. */ sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s%c%s", sqlite3_data_directory, winGetDirSep(), zRelative); return SQLITE_OK; } zConverted = winConvertFromUtf8Filename(zRelative); if( zConverted==0 ){ return SQLITE_IOERR_NOMEM_BKPT; } if( osIsNT() ){ LPWSTR zTemp; nByte = osGetFullPathNameW((LPCWSTR)zConverted, 0, 0, 0); if( nByte==0 ){ sqlite3_free(zConverted); return winLogError(SQLITE_CANTOPEN_FULLPATH, osGetLastError(), "winFullPathname1", zRelative); } nByte += 3; zTemp = sqlite3MallocZero( nByte*sizeof(zTemp[0]) ); if( zTemp==0 ){ sqlite3_free(zConverted); return SQLITE_IOERR_NOMEM_BKPT; } nByte = osGetFullPathNameW((LPCWSTR)zConverted, nByte, zTemp, 0); if( nByte==0 ){ sqlite3_free(zConverted); sqlite3_free(zTemp); return winLogError(SQLITE_CANTOPEN_FULLPATH, osGetLastError(), "winFullPathname2", zRelative); } sqlite3_free(zConverted); zOut = winUnicodeToUtf8(zTemp); sqlite3_free(zTemp); } #ifdef SQLITE_WIN32_HAS_ANSI else{ char *zTemp; nByte = osGetFullPathNameA((char*)zConverted, 0, 0, 0); if( nByte==0 ){ sqlite3_free(zConverted); return winLogError(SQLITE_CANTOPEN_FULLPATH, osGetLastError(), "winFullPathname3", zRelative); } nByte += 3; zTemp = sqlite3MallocZero( nByte*sizeof(zTemp[0]) ); if( zTemp==0 ){ sqlite3_free(zConverted); return SQLITE_IOERR_NOMEM_BKPT; } nByte = osGetFullPathNameA((char*)zConverted, nByte, zTemp, 0); if( nByte==0 ){ sqlite3_free(zConverted); sqlite3_free(zTemp); return winLogError(SQLITE_CANTOPEN_FULLPATH, osGetLastError(), "winFullPathname4", zRelative); } sqlite3_free(zConverted); zOut = winMbcsToUtf8(zTemp, osAreFileApisANSI()); sqlite3_free(zTemp); } #endif if( zOut ){ sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s", zOut); sqlite3_free(zOut); return SQLITE_OK; }else{ return SQLITE_IOERR_NOMEM_BKPT; } #endif } #ifndef SQLITE_OMIT_LOAD_EXTENSION /* ** Interfaces for opening a shared library, finding entry points ** within the shared library, and closing the shared library. */ static void *winDlOpen(sqlite3_vfs *pVfs, const char *zFilename){ HANDLE h; #if defined(__CYGWIN__) int nFull = pVfs->mxPathname+1; char *zFull = sqlite3MallocZero( nFull ); void *zConverted = 0; if( zFull==0 ){ OSTRACE(("DLOPEN name=%s, handle=%p\n", zFilename, (void*)0)); return 0; } if( winFullPathname(pVfs, zFilename, nFull, zFull)!=SQLITE_OK ){ sqlite3_free(zFull); OSTRACE(("DLOPEN name=%s, handle=%p\n", zFilename, (void*)0)); return 0; } zConverted = winConvertFromUtf8Filename(zFull); sqlite3_free(zFull); #else void *zConverted = winConvertFromUtf8Filename(zFilename); UNUSED_PARAMETER(pVfs); #endif if( zConverted==0 ){ OSTRACE(("DLOPEN name=%s, handle=%p\n", zFilename, (void*)0)); return 0; } if( osIsNT() ){ #if SQLITE_OS_WINRT h = osLoadPackagedLibrary((LPCWSTR)zConverted, 0); #else h = osLoadLibraryW((LPCWSTR)zConverted); #endif } #ifdef SQLITE_WIN32_HAS_ANSI else{ h = osLoadLibraryA((char*)zConverted); } #endif OSTRACE(("DLOPEN name=%s, handle=%p\n", zFilename, (void*)h)); sqlite3_free(zConverted); return (void*)h; } static void winDlError(sqlite3_vfs *pVfs, int nBuf, char *zBufOut){ UNUSED_PARAMETER(pVfs); winGetLastErrorMsg(osGetLastError(), nBuf, zBufOut); } static void (*winDlSym(sqlite3_vfs *pVfs,void *pH,const char *zSym))(void){ FARPROC proc; UNUSED_PARAMETER(pVfs); proc = osGetProcAddressA((HANDLE)pH, zSym); OSTRACE(("DLSYM handle=%p, symbol=%s, address=%p\n", (void*)pH, zSym, (void*)proc)); return (void(*)(void))proc; } static void winDlClose(sqlite3_vfs *pVfs, void *pHandle){ UNUSED_PARAMETER(pVfs); osFreeLibrary((HANDLE)pHandle); OSTRACE(("DLCLOSE handle=%p\n", (void*)pHandle)); } #else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */ #define winDlOpen 0 #define winDlError 0 #define winDlSym 0 #define winDlClose 0 #endif /* State information for the randomness gatherer. */ typedef struct EntropyGatherer EntropyGatherer; struct EntropyGatherer { unsigned char *a; /* Gather entropy into this buffer */ int na; /* Size of a[] in bytes */ int i; /* XOR next input into a[i] */ int nXor; /* Number of XOR operations done */ }; #if !defined(SQLITE_TEST) && !defined(SQLITE_OMIT_RANDOMNESS) /* Mix sz bytes of entropy into p. */ static void xorMemory(EntropyGatherer *p, unsigned char *x, int sz){ int j, k; for(j=0, k=p->i; ja[k++] ^= x[j]; if( k>=p->na ) k = 0; } p->i = k; p->nXor += sz; } #endif /* !defined(SQLITE_TEST) && !defined(SQLITE_OMIT_RANDOMNESS) */ /* ** Write up to nBuf bytes of randomness into zBuf. */ static int winRandomness(sqlite3_vfs *pVfs, int nBuf, char *zBuf){ #if defined(SQLITE_TEST) || defined(SQLITE_OMIT_RANDOMNESS) UNUSED_PARAMETER(pVfs); memset(zBuf, 0, nBuf); return nBuf; #else EntropyGatherer e; UNUSED_PARAMETER(pVfs); memset(zBuf, 0, nBuf); #if defined(_MSC_VER) && _MSC_VER>=1400 && !SQLITE_OS_WINCE rand_s((unsigned int*)zBuf); /* rand_s() is not available with MinGW */ #endif /* defined(_MSC_VER) && _MSC_VER>=1400 */ e.a = (unsigned char*)zBuf; e.na = nBuf; e.nXor = 0; e.i = 0; { SYSTEMTIME x; osGetSystemTime(&x); xorMemory(&e, (unsigned char*)&x, sizeof(SYSTEMTIME)); } { DWORD pid = osGetCurrentProcessId(); xorMemory(&e, (unsigned char*)&pid, sizeof(DWORD)); } #if SQLITE_OS_WINRT { ULONGLONG cnt = osGetTickCount64(); xorMemory(&e, (unsigned char*)&cnt, sizeof(ULONGLONG)); } #else { DWORD cnt = osGetTickCount(); xorMemory(&e, (unsigned char*)&cnt, sizeof(DWORD)); } #endif /* SQLITE_OS_WINRT */ { LARGE_INTEGER i; osQueryPerformanceCounter(&i); xorMemory(&e, (unsigned char*)&i, sizeof(LARGE_INTEGER)); } #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && SQLITE_WIN32_USE_UUID { UUID id; memset(&id, 0, sizeof(UUID)); osUuidCreate(&id); xorMemory(&e, (unsigned char*)&id, sizeof(UUID)); memset(&id, 0, sizeof(UUID)); osUuidCreateSequential(&id); xorMemory(&e, (unsigned char*)&id, sizeof(UUID)); } #endif /* !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && SQLITE_WIN32_USE_UUID */ return e.nXor>nBuf ? nBuf : e.nXor; #endif /* defined(SQLITE_TEST) || defined(SQLITE_OMIT_RANDOMNESS) */ } /* ** Sleep for a little while. Return the amount of time slept. */ static int winSleep(sqlite3_vfs *pVfs, int microsec){ sqlite3_win32_sleep((microsec+999)/1000); UNUSED_PARAMETER(pVfs); return ((microsec+999)/1000)*1000; } /* ** The following variable, if set to a non-zero value, is interpreted as ** the number of seconds since 1970 and is used to set the result of ** sqlite3OsCurrentTime() during testing. */ #ifdef SQLITE_TEST SQLITE_API int sqlite3_current_time = 0; /* Fake system time in seconds since 1970. */ #endif /* ** Find the current time (in Universal Coordinated Time). Write into *piNow ** the current time and date as a Julian Day number times 86_400_000. In ** other words, write into *piNow the number of milliseconds since the Julian ** epoch of noon in Greenwich on November 24, 4714 B.C according to the ** proleptic Gregorian calendar. ** ** On success, return SQLITE_OK. Return SQLITE_ERROR if the time and date ** cannot be found. */ static int winCurrentTimeInt64(sqlite3_vfs *pVfs, sqlite3_int64 *piNow){ /* FILETIME structure is a 64-bit value representing the number of 100-nanosecond intervals since January 1, 1601 (= JD 2305813.5). */ FILETIME ft; static const sqlite3_int64 winFiletimeEpoch = 23058135*(sqlite3_int64)8640000; #ifdef SQLITE_TEST static const sqlite3_int64 unixEpoch = 24405875*(sqlite3_int64)8640000; #endif /* 2^32 - to avoid use of LL and warnings in gcc */ static const sqlite3_int64 max32BitValue = (sqlite3_int64)2000000000 + (sqlite3_int64)2000000000 + (sqlite3_int64)294967296; #if SQLITE_OS_WINCE SYSTEMTIME time; osGetSystemTime(&time); /* if SystemTimeToFileTime() fails, it returns zero. */ if (!osSystemTimeToFileTime(&time,&ft)){ return SQLITE_ERROR; } #else osGetSystemTimeAsFileTime( &ft ); #endif *piNow = winFiletimeEpoch + ((((sqlite3_int64)ft.dwHighDateTime)*max32BitValue) + (sqlite3_int64)ft.dwLowDateTime)/(sqlite3_int64)10000; #ifdef SQLITE_TEST if( sqlite3_current_time ){ *piNow = 1000*(sqlite3_int64)sqlite3_current_time + unixEpoch; } #endif UNUSED_PARAMETER(pVfs); return SQLITE_OK; } /* ** Find the current time (in Universal Coordinated Time). Write the ** current time and date as a Julian Day number into *prNow and ** return 0. Return 1 if the time and date cannot be found. */ static int winCurrentTime(sqlite3_vfs *pVfs, double *prNow){ int rc; sqlite3_int64 i; rc = winCurrentTimeInt64(pVfs, &i); if( !rc ){ *prNow = i/86400000.0; } return rc; } /* ** The idea is that this function works like a combination of ** GetLastError() and FormatMessage() on Windows (or errno and ** strerror_r() on Unix). After an error is returned by an OS ** function, SQLite calls this function with zBuf pointing to ** a buffer of nBuf bytes. The OS layer should populate the ** buffer with a nul-terminated UTF-8 encoded error message ** describing the last IO error to have occurred within the calling ** thread. ** ** If the error message is too large for the supplied buffer, ** it should be truncated. The return value of xGetLastError ** is zero if the error message fits in the buffer, or non-zero ** otherwise (if the message was truncated). If non-zero is returned, ** then it is not necessary to include the nul-terminator character ** in the output buffer. ** ** Not supplying an error message will have no adverse effect ** on SQLite. It is fine to have an implementation that never ** returns an error message: ** ** int xGetLastError(sqlite3_vfs *pVfs, int nBuf, char *zBuf){ ** assert(zBuf[0]=='\0'); ** return 0; ** } ** ** However if an error message is supplied, it will be incorporated ** by sqlite into the error message available to the user using ** sqlite3_errmsg(), possibly making IO errors easier to debug. */ static int winGetLastError(sqlite3_vfs *pVfs, int nBuf, char *zBuf){ DWORD e = osGetLastError(); UNUSED_PARAMETER(pVfs); if( nBuf>0 ) winGetLastErrorMsg(e, nBuf, zBuf); return e; } /* ** Initialize and deinitialize the operating system interface. */ SQLITE_API int sqlite3_os_init(void){ static sqlite3_vfs winVfs = { 3, /* iVersion */ sizeof(winFile), /* szOsFile */ SQLITE_WIN32_MAX_PATH_BYTES, /* mxPathname */ 0, /* pNext */ "win32", /* zName */ &winAppData, /* pAppData */ winOpen, /* xOpen */ winDelete, /* xDelete */ winAccess, /* xAccess */ winFullPathname, /* xFullPathname */ winDlOpen, /* xDlOpen */ winDlError, /* xDlError */ winDlSym, /* xDlSym */ winDlClose, /* xDlClose */ winRandomness, /* xRandomness */ winSleep, /* xSleep */ winCurrentTime, /* xCurrentTime */ winGetLastError, /* xGetLastError */ winCurrentTimeInt64, /* xCurrentTimeInt64 */ winSetSystemCall, /* xSetSystemCall */ winGetSystemCall, /* xGetSystemCall */ winNextSystemCall, /* xNextSystemCall */ }; #if defined(SQLITE_WIN32_HAS_WIDE) static sqlite3_vfs winLongPathVfs = { 3, /* iVersion */ sizeof(winFile), /* szOsFile */ SQLITE_WINNT_MAX_PATH_BYTES, /* mxPathname */ 0, /* pNext */ "win32-longpath", /* zName */ &winAppData, /* pAppData */ winOpen, /* xOpen */ winDelete, /* xDelete */ winAccess, /* xAccess */ winFullPathname, /* xFullPathname */ winDlOpen, /* xDlOpen */ winDlError, /* xDlError */ winDlSym, /* xDlSym */ winDlClose, /* xDlClose */ winRandomness, /* xRandomness */ winSleep, /* xSleep */ winCurrentTime, /* xCurrentTime */ winGetLastError, /* xGetLastError */ winCurrentTimeInt64, /* xCurrentTimeInt64 */ winSetSystemCall, /* xSetSystemCall */ winGetSystemCall, /* xGetSystemCall */ winNextSystemCall, /* xNextSystemCall */ }; #endif static sqlite3_vfs winNolockVfs = { 3, /* iVersion */ sizeof(winFile), /* szOsFile */ SQLITE_WIN32_MAX_PATH_BYTES, /* mxPathname */ 0, /* pNext */ "win32-none", /* zName */ &winNolockAppData, /* pAppData */ winOpen, /* xOpen */ winDelete, /* xDelete */ winAccess, /* xAccess */ winFullPathname, /* xFullPathname */ winDlOpen, /* xDlOpen */ winDlError, /* xDlError */ winDlSym, /* xDlSym */ winDlClose, /* xDlClose */ winRandomness, /* xRandomness */ winSleep, /* xSleep */ winCurrentTime, /* xCurrentTime */ winGetLastError, /* xGetLastError */ winCurrentTimeInt64, /* xCurrentTimeInt64 */ winSetSystemCall, /* xSetSystemCall */ winGetSystemCall, /* xGetSystemCall */ winNextSystemCall, /* xNextSystemCall */ }; #if defined(SQLITE_WIN32_HAS_WIDE) static sqlite3_vfs winLongPathNolockVfs = { 3, /* iVersion */ sizeof(winFile), /* szOsFile */ SQLITE_WINNT_MAX_PATH_BYTES, /* mxPathname */ 0, /* pNext */ "win32-longpath-none", /* zName */ &winNolockAppData, /* pAppData */ winOpen, /* xOpen */ winDelete, /* xDelete */ winAccess, /* xAccess */ winFullPathname, /* xFullPathname */ winDlOpen, /* xDlOpen */ winDlError, /* xDlError */ winDlSym, /* xDlSym */ winDlClose, /* xDlClose */ winRandomness, /* xRandomness */ winSleep, /* xSleep */ winCurrentTime, /* xCurrentTime */ winGetLastError, /* xGetLastError */ winCurrentTimeInt64, /* xCurrentTimeInt64 */ winSetSystemCall, /* xSetSystemCall */ winGetSystemCall, /* xGetSystemCall */ winNextSystemCall, /* xNextSystemCall */ }; #endif /* Double-check that the aSyscall[] array has been constructed ** correctly. See ticket [bb3a86e890c8e96ab] */ assert( ArraySize(aSyscall)==80 ); /* get memory map allocation granularity */ memset(&winSysInfo, 0, sizeof(SYSTEM_INFO)); #if SQLITE_OS_WINRT osGetNativeSystemInfo(&winSysInfo); #else osGetSystemInfo(&winSysInfo); #endif assert( winSysInfo.dwAllocationGranularity>0 ); assert( winSysInfo.dwPageSize>0 ); sqlite3_vfs_register(&winVfs, 1); #if defined(SQLITE_WIN32_HAS_WIDE) sqlite3_vfs_register(&winLongPathVfs, 0); #endif sqlite3_vfs_register(&winNolockVfs, 0); #if defined(SQLITE_WIN32_HAS_WIDE) sqlite3_vfs_register(&winLongPathNolockVfs, 0); #endif return SQLITE_OK; } SQLITE_API int sqlite3_os_end(void){ #if SQLITE_OS_WINRT if( sleepObj!=NULL ){ osCloseHandle(sleepObj); sleepObj = NULL; } #endif return SQLITE_OK; } #endif /* SQLITE_OS_WIN */ /************** End of os_win.c **********************************************/ /************** Begin file bitvec.c ******************************************/ /* ** 2008 February 16 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ************************************************************************* ** This file implements an object that represents a fixed-length ** bitmap. Bits are numbered starting with 1. ** ** A bitmap is used to record which pages of a database file have been ** journalled during a transaction, or which pages have the "dont-write" ** property. Usually only a few pages are meet either condition. ** So the bitmap is usually sparse and has low cardinality. ** But sometimes (for example when during a DROP of a large table) most ** or all of the pages in a database can get journalled. In those cases, ** the bitmap becomes dense with high cardinality. The algorithm needs ** to handle both cases well. ** ** The size of the bitmap is fixed when the object is created. ** ** All bits are clear when the bitmap is created. Individual bits ** may be set or cleared one at a time. ** ** Test operations are about 100 times more common that set operations. ** Clear operations are exceedingly rare. There are usually between ** 5 and 500 set operations per Bitvec object, though the number of sets can ** sometimes grow into tens of thousands or larger. The size of the ** Bitvec object is the number of pages in the database file at the ** start of a transaction, and is thus usually less than a few thousand, ** but can be as large as 2 billion for a really big database. */ /* #include "sqliteInt.h" */ /* Size of the Bitvec structure in bytes. */ #define BITVEC_SZ 512 /* Round the union size down to the nearest pointer boundary, since that's how ** it will be aligned within the Bitvec struct. */ #define BITVEC_USIZE \ (((BITVEC_SZ-(3*sizeof(u32)))/sizeof(Bitvec*))*sizeof(Bitvec*)) /* Type of the array "element" for the bitmap representation. ** Should be a power of 2, and ideally, evenly divide into BITVEC_USIZE. ** Setting this to the "natural word" size of your CPU may improve ** performance. */ #define BITVEC_TELEM u8 /* Size, in bits, of the bitmap element. */ #define BITVEC_SZELEM 8 /* Number of elements in a bitmap array. */ #define BITVEC_NELEM (BITVEC_USIZE/sizeof(BITVEC_TELEM)) /* Number of bits in the bitmap array. */ #define BITVEC_NBIT (BITVEC_NELEM*BITVEC_SZELEM) /* Number of u32 values in hash table. */ #define BITVEC_NINT (BITVEC_USIZE/sizeof(u32)) /* Maximum number of entries in hash table before ** sub-dividing and re-hashing. */ #define BITVEC_MXHASH (BITVEC_NINT/2) /* Hashing function for the aHash representation. ** Empirical testing showed that the *37 multiplier ** (an arbitrary prime)in the hash function provided ** no fewer collisions than the no-op *1. */ #define BITVEC_HASH(X) (((X)*1)%BITVEC_NINT) #define BITVEC_NPTR (BITVEC_USIZE/sizeof(Bitvec *)) /* ** A bitmap is an instance of the following structure. ** ** This bitmap records the existence of zero or more bits ** with values between 1 and iSize, inclusive. ** ** There are three possible representations of the bitmap. ** If iSize<=BITVEC_NBIT, then Bitvec.u.aBitmap[] is a straight ** bitmap. The least significant bit is bit 1. ** ** If iSize>BITVEC_NBIT and iDivisor==0 then Bitvec.u.aHash[] is ** a hash table that will hold up to BITVEC_MXHASH distinct values. ** ** Otherwise, the value i is redirected into one of BITVEC_NPTR ** sub-bitmaps pointed to by Bitvec.u.apSub[]. Each subbitmap ** handles up to iDivisor separate values of i. apSub[0] holds ** values between 1 and iDivisor. apSub[1] holds values between ** iDivisor+1 and 2*iDivisor. apSub[N] holds values between ** N*iDivisor+1 and (N+1)*iDivisor. Each subbitmap is normalized ** to hold deal with values between 1 and iDivisor. */ struct Bitvec { u32 iSize; /* Maximum bit index. Max iSize is 4,294,967,296. */ u32 nSet; /* Number of bits that are set - only valid for aHash ** element. Max is BITVEC_NINT. For BITVEC_SZ of 512, ** this would be 125. */ u32 iDivisor; /* Number of bits handled by each apSub[] entry. */ /* Should >=0 for apSub element. */ /* Max iDivisor is max(u32) / BITVEC_NPTR + 1. */ /* For a BITVEC_SZ of 512, this would be 34,359,739. */ union { BITVEC_TELEM aBitmap[BITVEC_NELEM]; /* Bitmap representation */ u32 aHash[BITVEC_NINT]; /* Hash table representation */ Bitvec *apSub[BITVEC_NPTR]; /* Recursive representation */ } u; }; /* ** Create a new bitmap object able to handle bits between 0 and iSize, ** inclusive. Return a pointer to the new object. Return NULL if ** malloc fails. */ SQLITE_PRIVATE Bitvec *sqlite3BitvecCreate(u32 iSize){ Bitvec *p; assert( sizeof(*p)==BITVEC_SZ ); p = sqlite3MallocZero( sizeof(*p) ); if( p ){ p->iSize = iSize; } return p; } /* ** Check to see if the i-th bit is set. Return true or false. ** If p is NULL (if the bitmap has not been created) or if ** i is out of range, then return false. */ SQLITE_PRIVATE int sqlite3BitvecTestNotNull(Bitvec *p, u32 i){ assert( p!=0 ); i--; if( i>=p->iSize ) return 0; while( p->iDivisor ){ u32 bin = i/p->iDivisor; i = i%p->iDivisor; p = p->u.apSub[bin]; if (!p) { return 0; } } if( p->iSize<=BITVEC_NBIT ){ return (p->u.aBitmap[i/BITVEC_SZELEM] & (1<<(i&(BITVEC_SZELEM-1))))!=0; } else{ u32 h = BITVEC_HASH(i++); while( p->u.aHash[h] ){ if( p->u.aHash[h]==i ) return 1; h = (h+1) % BITVEC_NINT; } return 0; } } SQLITE_PRIVATE int sqlite3BitvecTest(Bitvec *p, u32 i){ return p!=0 && sqlite3BitvecTestNotNull(p,i); } /* ** Set the i-th bit. Return 0 on success and an error code if ** anything goes wrong. ** ** This routine might cause sub-bitmaps to be allocated. Failing ** to get the memory needed to hold the sub-bitmap is the only ** that can go wrong with an insert, assuming p and i are valid. ** ** The calling function must ensure that p is a valid Bitvec object ** and that the value for "i" is within range of the Bitvec object. ** Otherwise the behavior is undefined. */ SQLITE_PRIVATE int sqlite3BitvecSet(Bitvec *p, u32 i){ u32 h; if( p==0 ) return SQLITE_OK; assert( i>0 ); assert( i<=p->iSize ); i--; while((p->iSize > BITVEC_NBIT) && p->iDivisor) { u32 bin = i/p->iDivisor; i = i%p->iDivisor; if( p->u.apSub[bin]==0 ){ p->u.apSub[bin] = sqlite3BitvecCreate( p->iDivisor ); if( p->u.apSub[bin]==0 ) return SQLITE_NOMEM_BKPT; } p = p->u.apSub[bin]; } if( p->iSize<=BITVEC_NBIT ){ p->u.aBitmap[i/BITVEC_SZELEM] |= 1 << (i&(BITVEC_SZELEM-1)); return SQLITE_OK; } h = BITVEC_HASH(i++); /* if there wasn't a hash collision, and this doesn't */ /* completely fill the hash, then just add it without */ /* worring about sub-dividing and re-hashing. */ if( !p->u.aHash[h] ){ if (p->nSet<(BITVEC_NINT-1)) { goto bitvec_set_end; } else { goto bitvec_set_rehash; } } /* there was a collision, check to see if it's already */ /* in hash, if not, try to find a spot for it */ do { if( p->u.aHash[h]==i ) return SQLITE_OK; h++; if( h>=BITVEC_NINT ) h = 0; } while( p->u.aHash[h] ); /* we didn't find it in the hash. h points to the first */ /* available free spot. check to see if this is going to */ /* make our hash too "full". */ bitvec_set_rehash: if( p->nSet>=BITVEC_MXHASH ){ unsigned int j; int rc; u32 *aiValues = sqlite3StackAllocRaw(0, sizeof(p->u.aHash)); if( aiValues==0 ){ return SQLITE_NOMEM_BKPT; }else{ memcpy(aiValues, p->u.aHash, sizeof(p->u.aHash)); memset(p->u.apSub, 0, sizeof(p->u.apSub)); p->iDivisor = (p->iSize + BITVEC_NPTR - 1)/BITVEC_NPTR; rc = sqlite3BitvecSet(p, i); for(j=0; jnSet++; p->u.aHash[h] = i; return SQLITE_OK; } /* ** Clear the i-th bit. ** ** pBuf must be a pointer to at least BITVEC_SZ bytes of temporary storage ** that BitvecClear can use to rebuilt its hash table. */ SQLITE_PRIVATE void sqlite3BitvecClear(Bitvec *p, u32 i, void *pBuf){ if( p==0 ) return; assert( i>0 ); i--; while( p->iDivisor ){ u32 bin = i/p->iDivisor; i = i%p->iDivisor; p = p->u.apSub[bin]; if (!p) { return; } } if( p->iSize<=BITVEC_NBIT ){ p->u.aBitmap[i/BITVEC_SZELEM] &= ~(1 << (i&(BITVEC_SZELEM-1))); }else{ unsigned int j; u32 *aiValues = pBuf; memcpy(aiValues, p->u.aHash, sizeof(p->u.aHash)); memset(p->u.aHash, 0, sizeof(p->u.aHash)); p->nSet = 0; for(j=0; jnSet++; while( p->u.aHash[h] ){ h++; if( h>=BITVEC_NINT ) h = 0; } p->u.aHash[h] = aiValues[j]; } } } } /* ** Destroy a bitmap object. Reclaim all memory used. */ SQLITE_PRIVATE void sqlite3BitvecDestroy(Bitvec *p){ if( p==0 ) return; if( p->iDivisor ){ unsigned int i; for(i=0; iu.apSub[i]); } } sqlite3_free(p); } /* ** Return the value of the iSize parameter specified when Bitvec *p ** was created. */ SQLITE_PRIVATE u32 sqlite3BitvecSize(Bitvec *p){ return p->iSize; } #ifndef SQLITE_OMIT_BUILTIN_TEST /* ** Let V[] be an array of unsigned characters sufficient to hold ** up to N bits. Let I be an integer between 0 and N. 0<=I>3] |= (1<<(I&7)) #define CLEARBIT(V,I) V[I>>3] &= ~(1<<(I&7)) #define TESTBIT(V,I) (V[I>>3]&(1<<(I&7)))!=0 /* ** This routine runs an extensive test of the Bitvec code. ** ** The input is an array of integers that acts as a program ** to test the Bitvec. The integers are opcodes followed ** by 0, 1, or 3 operands, depending on the opcode. Another ** opcode follows immediately after the last operand. ** ** There are 6 opcodes numbered from 0 through 5. 0 is the ** "halt" opcode and causes the test to end. ** ** 0 Halt and return the number of errors ** 1 N S X Set N bits beginning with S and incrementing by X ** 2 N S X Clear N bits beginning with S and incrementing by X ** 3 N Set N randomly chosen bits ** 4 N Clear N randomly chosen bits ** 5 N S X Set N bits from S increment X in array only, not in bitvec ** ** The opcodes 1 through 4 perform set and clear operations are performed ** on both a Bitvec object and on a linear array of bits obtained from malloc. ** Opcode 5 works on the linear array only, not on the Bitvec. ** Opcode 5 is used to deliberately induce a fault in order to ** confirm that error detection works. ** ** At the conclusion of the test the linear array is compared ** against the Bitvec object. If there are any differences, ** an error is returned. If they are the same, zero is returned. ** ** If a memory allocation error occurs, return -1. */ SQLITE_PRIVATE int sqlite3BitvecBuiltinTest(int sz, int *aOp){ Bitvec *pBitvec = 0; unsigned char *pV = 0; int rc = -1; int i, nx, pc, op; void *pTmpSpace; /* Allocate the Bitvec to be tested and a linear array of ** bits to act as the reference */ pBitvec = sqlite3BitvecCreate( sz ); pV = sqlite3MallocZero( (sz+7)/8 + 1 ); pTmpSpace = sqlite3_malloc64(BITVEC_SZ); if( pBitvec==0 || pV==0 || pTmpSpace==0 ) goto bitvec_end; /* NULL pBitvec tests */ sqlite3BitvecSet(0, 1); sqlite3BitvecClear(0, 1, pTmpSpace); /* Run the program */ pc = 0; while( (op = aOp[pc])!=0 ){ switch( op ){ case 1: case 2: case 5: { nx = 4; i = aOp[pc+2] - 1; aOp[pc+2] += aOp[pc+3]; break; } case 3: case 4: default: { nx = 2; sqlite3_randomness(sizeof(i), &i); break; } } if( (--aOp[pc+1]) > 0 ) nx = 0; pc += nx; i = (i & 0x7fffffff)%sz; if( (op & 1)!=0 ){ SETBIT(pV, (i+1)); if( op!=5 ){ if( sqlite3BitvecSet(pBitvec, i+1) ) goto bitvec_end; } }else{ CLEARBIT(pV, (i+1)); sqlite3BitvecClear(pBitvec, i+1, pTmpSpace); } } /* Test to make sure the linear array exactly matches the ** Bitvec object. Start with the assumption that they do ** match (rc==0). Change rc to non-zero if a discrepancy ** is found. */ rc = sqlite3BitvecTest(0,0) + sqlite3BitvecTest(pBitvec, sz+1) + sqlite3BitvecTest(pBitvec, 0) + (sqlite3BitvecSize(pBitvec) - sz); for(i=1; i<=sz; i++){ if( (TESTBIT(pV,i))!=sqlite3BitvecTest(pBitvec,i) ){ rc = i; break; } } /* Free allocated structure */ bitvec_end: sqlite3_free(pTmpSpace); sqlite3_free(pV); sqlite3BitvecDestroy(pBitvec); return rc; } #endif /* SQLITE_OMIT_BUILTIN_TEST */ /************** End of bitvec.c **********************************************/ /************** Begin file pcache.c ******************************************/ /* ** 2008 August 05 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ************************************************************************* ** This file implements that page cache. */ /* #include "sqliteInt.h" */ /* ** A complete page cache is an instance of this structure. Every ** entry in the cache holds a single page of the database file. The ** btree layer only operates on the cached copy of the database pages. ** ** A page cache entry is "clean" if it exactly matches what is currently ** on disk. A page is "dirty" if it has been modified and needs to be ** persisted to disk. ** ** pDirty, pDirtyTail, pSynced: ** All dirty pages are linked into the doubly linked list using ** PgHdr.pDirtyNext and pDirtyPrev. The list is maintained in LRU order ** such that p was added to the list more recently than p->pDirtyNext. ** PCache.pDirty points to the first (newest) element in the list and ** pDirtyTail to the last (oldest). ** ** The PCache.pSynced variable is used to optimize searching for a dirty ** page to eject from the cache mid-transaction. It is better to eject ** a page that does not require a journal sync than one that does. ** Therefore, pSynced is maintained to that it *almost* always points ** to either the oldest page in the pDirty/pDirtyTail list that has a ** clear PGHDR_NEED_SYNC flag or to a page that is older than this one ** (so that the right page to eject can be found by following pDirtyPrev ** pointers). */ struct PCache { PgHdr *pDirty, *pDirtyTail; /* List of dirty pages in LRU order */ PgHdr *pSynced; /* Last synced page in dirty page list */ int nRefSum; /* Sum of ref counts over all pages */ int szCache; /* Configured cache size */ int szSpill; /* Size before spilling occurs */ int szPage; /* Size of every page in this cache */ int szExtra; /* Size of extra space for each page */ u8 bPurgeable; /* True if pages are on backing store */ u8 eCreate; /* eCreate value for for xFetch() */ int (*xStress)(void*,PgHdr*); /* Call to try make a page clean */ void *pStress; /* Argument to xStress */ sqlite3_pcache *pCache; /* Pluggable cache module */ }; /********************************** Test and Debug Logic **********************/ /* ** Debug tracing macros. Enable by by changing the "0" to "1" and ** recompiling. ** ** When sqlite3PcacheTrace is 1, single line trace messages are issued. ** When sqlite3PcacheTrace is 2, a dump of the pcache showing all cache entries ** is displayed for many operations, resulting in a lot of output. */ #if defined(SQLITE_DEBUG) && 0 int sqlite3PcacheTrace = 2; /* 0: off 1: simple 2: cache dumps */ int sqlite3PcacheMxDump = 9999; /* Max cache entries for pcacheDump() */ # define pcacheTrace(X) if(sqlite3PcacheTrace){sqlite3DebugPrintf X;} void pcacheDump(PCache *pCache){ int N; int i, j; sqlite3_pcache_page *pLower; PgHdr *pPg; unsigned char *a; if( sqlite3PcacheTrace<2 ) return; if( pCache->pCache==0 ) return; N = sqlite3PcachePagecount(pCache); if( N>sqlite3PcacheMxDump ) N = sqlite3PcacheMxDump; for(i=1; i<=N; i++){ pLower = sqlite3GlobalConfig.pcache2.xFetch(pCache->pCache, i, 0); if( pLower==0 ) continue; pPg = (PgHdr*)pLower->pExtra; printf("%3d: nRef %2d flgs %02x data ", i, pPg->nRef, pPg->flags); a = (unsigned char *)pLower->pBuf; for(j=0; j<12; j++) printf("%02x", a[j]); printf("\n"); if( pPg->pPage==0 ){ sqlite3GlobalConfig.pcache2.xUnpin(pCache->pCache, pLower, 0); } } } #else # define pcacheTrace(X) # define pcacheDump(X) #endif /* ** Check invariants on a PgHdr entry. Return true if everything is OK. ** Return false if any invariant is violated. ** ** This routine is for use inside of assert() statements only. For ** example: ** ** assert( sqlite3PcachePageSanity(pPg) ); */ #if SQLITE_DEBUG SQLITE_PRIVATE int sqlite3PcachePageSanity(PgHdr *pPg){ PCache *pCache; assert( pPg!=0 ); assert( pPg->pgno>0 ); /* Page number is 1 or more */ pCache = pPg->pCache; assert( pCache!=0 ); /* Every page has an associated PCache */ if( pPg->flags & PGHDR_CLEAN ){ assert( (pPg->flags & PGHDR_DIRTY)==0 );/* Cannot be both CLEAN and DIRTY */ assert( pCache->pDirty!=pPg ); /* CLEAN pages not on dirty list */ assert( pCache->pDirtyTail!=pPg ); } /* WRITEABLE pages must also be DIRTY */ if( pPg->flags & PGHDR_WRITEABLE ){ assert( pPg->flags & PGHDR_DIRTY ); /* WRITEABLE implies DIRTY */ } /* NEED_SYNC can be set independently of WRITEABLE. This can happen, ** for example, when using the sqlite3PagerDontWrite() optimization: ** (1) Page X is journalled, and gets WRITEABLE and NEED_SEEK. ** (2) Page X moved to freelist, WRITEABLE is cleared ** (3) Page X reused, WRITEABLE is set again ** If NEED_SYNC had been cleared in step 2, then it would not be reset ** in step 3, and page might be written into the database without first ** syncing the rollback journal, which might cause corruption on a power ** loss. ** ** Another example is when the database page size is smaller than the ** disk sector size. When any page of a sector is journalled, all pages ** in that sector are marked NEED_SYNC even if they are still CLEAN, just ** in case they are later modified, since all pages in the same sector ** must be journalled and synced before any of those pages can be safely ** written. */ return 1; } #endif /* SQLITE_DEBUG */ /********************************** Linked List Management ********************/ /* Allowed values for second argument to pcacheManageDirtyList() */ #define PCACHE_DIRTYLIST_REMOVE 1 /* Remove pPage from dirty list */ #define PCACHE_DIRTYLIST_ADD 2 /* Add pPage to the dirty list */ #define PCACHE_DIRTYLIST_FRONT 3 /* Move pPage to the front of the list */ /* ** Manage pPage's participation on the dirty list. Bits of the addRemove ** argument determines what operation to do. The 0x01 bit means first ** remove pPage from the dirty list. The 0x02 means add pPage back to ** the dirty list. Doing both moves pPage to the front of the dirty list. */ static void pcacheManageDirtyList(PgHdr *pPage, u8 addRemove){ PCache *p = pPage->pCache; pcacheTrace(("%p.DIRTYLIST.%s %d\n", p, addRemove==1 ? "REMOVE" : addRemove==2 ? "ADD" : "FRONT", pPage->pgno)); if( addRemove & PCACHE_DIRTYLIST_REMOVE ){ assert( pPage->pDirtyNext || pPage==p->pDirtyTail ); assert( pPage->pDirtyPrev || pPage==p->pDirty ); /* Update the PCache1.pSynced variable if necessary. */ if( p->pSynced==pPage ){ p->pSynced = pPage->pDirtyPrev; } if( pPage->pDirtyNext ){ pPage->pDirtyNext->pDirtyPrev = pPage->pDirtyPrev; }else{ assert( pPage==p->pDirtyTail ); p->pDirtyTail = pPage->pDirtyPrev; } if( pPage->pDirtyPrev ){ pPage->pDirtyPrev->pDirtyNext = pPage->pDirtyNext; }else{ /* If there are now no dirty pages in the cache, set eCreate to 2. ** This is an optimization that allows sqlite3PcacheFetch() to skip ** searching for a dirty page to eject from the cache when it might ** otherwise have to. */ assert( pPage==p->pDirty ); p->pDirty = pPage->pDirtyNext; assert( p->bPurgeable || p->eCreate==2 ); if( p->pDirty==0 ){ /*OPTIMIZATION-IF-TRUE*/ assert( p->bPurgeable==0 || p->eCreate==1 ); p->eCreate = 2; } } pPage->pDirtyNext = 0; pPage->pDirtyPrev = 0; } if( addRemove & PCACHE_DIRTYLIST_ADD ){ assert( pPage->pDirtyNext==0 && pPage->pDirtyPrev==0 && p->pDirty!=pPage ); pPage->pDirtyNext = p->pDirty; if( pPage->pDirtyNext ){ assert( pPage->pDirtyNext->pDirtyPrev==0 ); pPage->pDirtyNext->pDirtyPrev = pPage; }else{ p->pDirtyTail = pPage; if( p->bPurgeable ){ assert( p->eCreate==2 ); p->eCreate = 1; } } p->pDirty = pPage; /* If pSynced is NULL and this page has a clear NEED_SYNC flag, set ** pSynced to point to it. Checking the NEED_SYNC flag is an ** optimization, as if pSynced points to a page with the NEED_SYNC ** flag set sqlite3PcacheFetchStress() searches through all newer ** entries of the dirty-list for a page with NEED_SYNC clear anyway. */ if( !p->pSynced && 0==(pPage->flags&PGHDR_NEED_SYNC) /*OPTIMIZATION-IF-FALSE*/ ){ p->pSynced = pPage; } } pcacheDump(p); } /* ** Wrapper around the pluggable caches xUnpin method. If the cache is ** being used for an in-memory database, this function is a no-op. */ static void pcacheUnpin(PgHdr *p){ if( p->pCache->bPurgeable ){ pcacheTrace(("%p.UNPIN %d\n", p->pCache, p->pgno)); sqlite3GlobalConfig.pcache2.xUnpin(p->pCache->pCache, p->pPage, 0); pcacheDump(p->pCache); } } /* ** Compute the number of pages of cache requested. p->szCache is the ** cache size requested by the "PRAGMA cache_size" statement. */ static int numberOfCachePages(PCache *p){ if( p->szCache>=0 ){ /* IMPLEMENTATION-OF: R-42059-47211 If the argument N is positive then the ** suggested cache size is set to N. */ return p->szCache; }else{ /* IMPLEMENTATION-OF: R-61436-13639 If the argument N is negative, then ** the number of cache pages is adjusted to use approximately abs(N*1024) ** bytes of memory. */ return (int)((-1024*(i64)p->szCache)/(p->szPage+p->szExtra)); } } /*************************************************** General Interfaces ****** ** ** Initialize and shutdown the page cache subsystem. Neither of these ** functions are threadsafe. */ SQLITE_PRIVATE int sqlite3PcacheInitialize(void){ if( sqlite3GlobalConfig.pcache2.xInit==0 ){ /* IMPLEMENTATION-OF: R-26801-64137 If the xInit() method is NULL, then the ** built-in default page cache is used instead of the application defined ** page cache. */ sqlite3PCacheSetDefault(); } return sqlite3GlobalConfig.pcache2.xInit(sqlite3GlobalConfig.pcache2.pArg); } SQLITE_PRIVATE void sqlite3PcacheShutdown(void){ if( sqlite3GlobalConfig.pcache2.xShutdown ){ /* IMPLEMENTATION-OF: R-26000-56589 The xShutdown() method may be NULL. */ sqlite3GlobalConfig.pcache2.xShutdown(sqlite3GlobalConfig.pcache2.pArg); } } /* ** Return the size in bytes of a PCache object. */ SQLITE_PRIVATE int sqlite3PcacheSize(void){ return sizeof(PCache); } /* ** Create a new PCache object. Storage space to hold the object ** has already been allocated and is passed in as the p pointer. ** The caller discovers how much space needs to be allocated by ** calling sqlite3PcacheSize(). */ SQLITE_PRIVATE int sqlite3PcacheOpen( int szPage, /* Size of every page */ int szExtra, /* Extra space associated with each page */ int bPurgeable, /* True if pages are on backing store */ int (*xStress)(void*,PgHdr*),/* Call to try to make pages clean */ void *pStress, /* Argument to xStress */ PCache *p /* Preallocated space for the PCache */ ){ memset(p, 0, sizeof(PCache)); p->szPage = 1; p->szExtra = szExtra; p->bPurgeable = bPurgeable; p->eCreate = 2; p->xStress = xStress; p->pStress = pStress; p->szCache = 100; p->szSpill = 1; pcacheTrace(("%p.OPEN szPage %d bPurgeable %d\n",p,szPage,bPurgeable)); return sqlite3PcacheSetPageSize(p, szPage); } /* ** Change the page size for PCache object. The caller must ensure that there ** are no outstanding page references when this function is called. */ SQLITE_PRIVATE int sqlite3PcacheSetPageSize(PCache *pCache, int szPage){ assert( pCache->nRefSum==0 && pCache->pDirty==0 ); if( pCache->szPage ){ sqlite3_pcache *pNew; pNew = sqlite3GlobalConfig.pcache2.xCreate( szPage, pCache->szExtra + ROUND8(sizeof(PgHdr)), pCache->bPurgeable ); if( pNew==0 ) return SQLITE_NOMEM_BKPT; sqlite3GlobalConfig.pcache2.xCachesize(pNew, numberOfCachePages(pCache)); if( pCache->pCache ){ sqlite3GlobalConfig.pcache2.xDestroy(pCache->pCache); } pCache->pCache = pNew; pCache->szPage = szPage; pcacheTrace(("%p.PAGESIZE %d\n",pCache,szPage)); } return SQLITE_OK; } /* ** Try to obtain a page from the cache. ** ** This routine returns a pointer to an sqlite3_pcache_page object if ** such an object is already in cache, or if a new one is created. ** This routine returns a NULL pointer if the object was not in cache ** and could not be created. ** ** The createFlags should be 0 to check for existing pages and should ** be 3 (not 1, but 3) to try to create a new page. ** ** If the createFlag is 0, then NULL is always returned if the page ** is not already in the cache. If createFlag is 1, then a new page ** is created only if that can be done without spilling dirty pages ** and without exceeding the cache size limit. ** ** The caller needs to invoke sqlite3PcacheFetchFinish() to properly ** initialize the sqlite3_pcache_page object and convert it into a ** PgHdr object. The sqlite3PcacheFetch() and sqlite3PcacheFetchFinish() ** routines are split this way for performance reasons. When separated ** they can both (usually) operate without having to push values to ** the stack on entry and pop them back off on exit, which saves a ** lot of pushing and popping. */ SQLITE_PRIVATE sqlite3_pcache_page *sqlite3PcacheFetch( PCache *pCache, /* Obtain the page from this cache */ Pgno pgno, /* Page number to obtain */ int createFlag /* If true, create page if it does not exist already */ ){ int eCreate; sqlite3_pcache_page *pRes; assert( pCache!=0 ); assert( pCache->pCache!=0 ); assert( createFlag==3 || createFlag==0 ); assert( pgno>0 ); assert( pCache->eCreate==((pCache->bPurgeable && pCache->pDirty) ? 1 : 2) ); /* eCreate defines what to do if the page does not exist. ** 0 Do not allocate a new page. (createFlag==0) ** 1 Allocate a new page if doing so is inexpensive. ** (createFlag==1 AND bPurgeable AND pDirty) ** 2 Allocate a new page even it doing so is difficult. ** (createFlag==1 AND !(bPurgeable AND pDirty) */ eCreate = createFlag & pCache->eCreate; assert( eCreate==0 || eCreate==1 || eCreate==2 ); assert( createFlag==0 || pCache->eCreate==eCreate ); assert( createFlag==0 || eCreate==1+(!pCache->bPurgeable||!pCache->pDirty) ); pRes = sqlite3GlobalConfig.pcache2.xFetch(pCache->pCache, pgno, eCreate); pcacheTrace(("%p.FETCH %d%s (result: %p)\n",pCache,pgno, createFlag?" create":"",pRes)); return pRes; } /* ** If the sqlite3PcacheFetch() routine is unable to allocate a new ** page because no clean pages are available for reuse and the cache ** size limit has been reached, then this routine can be invoked to ** try harder to allocate a page. This routine might invoke the stress ** callback to spill dirty pages to the journal. It will then try to ** allocate the new page and will only fail to allocate a new page on ** an OOM error. ** ** This routine should be invoked only after sqlite3PcacheFetch() fails. */ SQLITE_PRIVATE int sqlite3PcacheFetchStress( PCache *pCache, /* Obtain the page from this cache */ Pgno pgno, /* Page number to obtain */ sqlite3_pcache_page **ppPage /* Write result here */ ){ PgHdr *pPg; if( pCache->eCreate==2 ) return 0; if( sqlite3PcachePagecount(pCache)>pCache->szSpill ){ /* Find a dirty page to write-out and recycle. First try to find a ** page that does not require a journal-sync (one with PGHDR_NEED_SYNC ** cleared), but if that is not possible settle for any other ** unreferenced dirty page. ** ** If the LRU page in the dirty list that has a clear PGHDR_NEED_SYNC ** flag is currently referenced, then the following may leave pSynced ** set incorrectly (pointing to other than the LRU page with NEED_SYNC ** cleared). This is Ok, as pSynced is just an optimization. */ for(pPg=pCache->pSynced; pPg && (pPg->nRef || (pPg->flags&PGHDR_NEED_SYNC)); pPg=pPg->pDirtyPrev ); pCache->pSynced = pPg; if( !pPg ){ for(pPg=pCache->pDirtyTail; pPg && pPg->nRef; pPg=pPg->pDirtyPrev); } if( pPg ){ int rc; #ifdef SQLITE_LOG_CACHE_SPILL sqlite3_log(SQLITE_FULL, "spill page %d making room for %d - cache used: %d/%d", pPg->pgno, pgno, sqlite3GlobalConfig.pcache.xPagecount(pCache->pCache), numberOfCachePages(pCache)); #endif pcacheTrace(("%p.SPILL %d\n",pCache,pPg->pgno)); rc = pCache->xStress(pCache->pStress, pPg); pcacheDump(pCache); if( rc!=SQLITE_OK && rc!=SQLITE_BUSY ){ return rc; } } } *ppPage = sqlite3GlobalConfig.pcache2.xFetch(pCache->pCache, pgno, 2); return *ppPage==0 ? SQLITE_NOMEM_BKPT : SQLITE_OK; } /* ** This is a helper routine for sqlite3PcacheFetchFinish() ** ** In the uncommon case where the page being fetched has not been ** initialized, this routine is invoked to do the initialization. ** This routine is broken out into a separate function since it ** requires extra stack manipulation that can be avoided in the common ** case. */ static SQLITE_NOINLINE PgHdr *pcacheFetchFinishWithInit( PCache *pCache, /* Obtain the page from this cache */ Pgno pgno, /* Page number obtained */ sqlite3_pcache_page *pPage /* Page obtained by prior PcacheFetch() call */ ){ PgHdr *pPgHdr; assert( pPage!=0 ); pPgHdr = (PgHdr*)pPage->pExtra; assert( pPgHdr->pPage==0 ); memset(&pPgHdr->pDirty, 0, sizeof(PgHdr) - offsetof(PgHdr,pDirty)); pPgHdr->pPage = pPage; pPgHdr->pData = pPage->pBuf; pPgHdr->pExtra = (void *)&pPgHdr[1]; memset(pPgHdr->pExtra, 0, pCache->szExtra); pPgHdr->pCache = pCache; pPgHdr->pgno = pgno; pPgHdr->flags = PGHDR_CLEAN; return sqlite3PcacheFetchFinish(pCache,pgno,pPage); } /* ** This routine converts the sqlite3_pcache_page object returned by ** sqlite3PcacheFetch() into an initialized PgHdr object. This routine ** must be called after sqlite3PcacheFetch() in order to get a usable ** result. */ SQLITE_PRIVATE PgHdr *sqlite3PcacheFetchFinish( PCache *pCache, /* Obtain the page from this cache */ Pgno pgno, /* Page number obtained */ sqlite3_pcache_page *pPage /* Page obtained by prior PcacheFetch() call */ ){ PgHdr *pPgHdr; assert( pPage!=0 ); pPgHdr = (PgHdr *)pPage->pExtra; if( !pPgHdr->pPage ){ return pcacheFetchFinishWithInit(pCache, pgno, pPage); } pCache->nRefSum++; pPgHdr->nRef++; assert( sqlite3PcachePageSanity(pPgHdr) ); return pPgHdr; } /* ** Decrement the reference count on a page. If the page is clean and the ** reference count drops to 0, then it is made eligible for recycling. */ SQLITE_PRIVATE void SQLITE_NOINLINE sqlite3PcacheRelease(PgHdr *p){ assert( p->nRef>0 ); p->pCache->nRefSum--; if( (--p->nRef)==0 ){ if( p->flags&PGHDR_CLEAN ){ pcacheUnpin(p); }else if( p->pDirtyPrev!=0 ){ /*OPTIMIZATION-IF-FALSE*/ /* Move the page to the head of the dirty list. If p->pDirtyPrev==0, ** then page p is already at the head of the dirty list and the ** following call would be a no-op. Hence the OPTIMIZATION-IF-FALSE ** tag above. */ pcacheManageDirtyList(p, PCACHE_DIRTYLIST_FRONT); } } } /* ** Increase the reference count of a supplied page by 1. */ SQLITE_PRIVATE void sqlite3PcacheRef(PgHdr *p){ assert(p->nRef>0); assert( sqlite3PcachePageSanity(p) ); p->nRef++; p->pCache->nRefSum++; } /* ** Drop a page from the cache. There must be exactly one reference to the ** page. This function deletes that reference, so after it returns the ** page pointed to by p is invalid. */ SQLITE_PRIVATE void sqlite3PcacheDrop(PgHdr *p){ assert( p->nRef==1 ); assert( sqlite3PcachePageSanity(p) ); if( p->flags&PGHDR_DIRTY ){ pcacheManageDirtyList(p, PCACHE_DIRTYLIST_REMOVE); } p->pCache->nRefSum--; sqlite3GlobalConfig.pcache2.xUnpin(p->pCache->pCache, p->pPage, 1); } /* ** Make sure the page is marked as dirty. If it isn't dirty already, ** make it so. */ SQLITE_PRIVATE void sqlite3PcacheMakeDirty(PgHdr *p){ assert( p->nRef>0 ); assert( sqlite3PcachePageSanity(p) ); if( p->flags & (PGHDR_CLEAN|PGHDR_DONT_WRITE) ){ /*OPTIMIZATION-IF-FALSE*/ p->flags &= ~PGHDR_DONT_WRITE; if( p->flags & PGHDR_CLEAN ){ p->flags ^= (PGHDR_DIRTY|PGHDR_CLEAN); pcacheTrace(("%p.DIRTY %d\n",p->pCache,p->pgno)); assert( (p->flags & (PGHDR_DIRTY|PGHDR_CLEAN))==PGHDR_DIRTY ); pcacheManageDirtyList(p, PCACHE_DIRTYLIST_ADD); } assert( sqlite3PcachePageSanity(p) ); } } /* ** Make sure the page is marked as clean. If it isn't clean already, ** make it so. */ SQLITE_PRIVATE void sqlite3PcacheMakeClean(PgHdr *p){ assert( sqlite3PcachePageSanity(p) ); if( ALWAYS((p->flags & PGHDR_DIRTY)!=0) ){ assert( (p->flags & PGHDR_CLEAN)==0 ); pcacheManageDirtyList(p, PCACHE_DIRTYLIST_REMOVE); p->flags &= ~(PGHDR_DIRTY|PGHDR_NEED_SYNC|PGHDR_WRITEABLE); p->flags |= PGHDR_CLEAN; pcacheTrace(("%p.CLEAN %d\n",p->pCache,p->pgno)); assert( sqlite3PcachePageSanity(p) ); if( p->nRef==0 ){ pcacheUnpin(p); } } } /* ** Make every page in the cache clean. */ SQLITE_PRIVATE void sqlite3PcacheCleanAll(PCache *pCache){ PgHdr *p; pcacheTrace(("%p.CLEAN-ALL\n",pCache)); while( (p = pCache->pDirty)!=0 ){ sqlite3PcacheMakeClean(p); } } /* ** Clear the PGHDR_NEED_SYNC and PGHDR_WRITEABLE flag from all dirty pages. */ SQLITE_PRIVATE void sqlite3PcacheClearWritable(PCache *pCache){ PgHdr *p; pcacheTrace(("%p.CLEAR-WRITEABLE\n",pCache)); for(p=pCache->pDirty; p; p=p->pDirtyNext){ p->flags &= ~(PGHDR_NEED_SYNC|PGHDR_WRITEABLE); } pCache->pSynced = pCache->pDirtyTail; } /* ** Clear the PGHDR_NEED_SYNC flag from all dirty pages. */ SQLITE_PRIVATE void sqlite3PcacheClearSyncFlags(PCache *pCache){ PgHdr *p; for(p=pCache->pDirty; p; p=p->pDirtyNext){ p->flags &= ~PGHDR_NEED_SYNC; } pCache->pSynced = pCache->pDirtyTail; } /* ** Change the page number of page p to newPgno. */ SQLITE_PRIVATE void sqlite3PcacheMove(PgHdr *p, Pgno newPgno){ PCache *pCache = p->pCache; assert( p->nRef>0 ); assert( newPgno>0 ); assert( sqlite3PcachePageSanity(p) ); pcacheTrace(("%p.MOVE %d -> %d\n",pCache,p->pgno,newPgno)); sqlite3GlobalConfig.pcache2.xRekey(pCache->pCache, p->pPage, p->pgno,newPgno); p->pgno = newPgno; if( (p->flags&PGHDR_DIRTY) && (p->flags&PGHDR_NEED_SYNC) ){ pcacheManageDirtyList(p, PCACHE_DIRTYLIST_FRONT); } } /* ** Drop every cache entry whose page number is greater than "pgno". The ** caller must ensure that there are no outstanding references to any pages ** other than page 1 with a page number greater than pgno. ** ** If there is a reference to page 1 and the pgno parameter passed to this ** function is 0, then the data area associated with page 1 is zeroed, but ** the page object is not dropped. */ SQLITE_PRIVATE void sqlite3PcacheTruncate(PCache *pCache, Pgno pgno){ if( pCache->pCache ){ PgHdr *p; PgHdr *pNext; pcacheTrace(("%p.TRUNCATE %d\n",pCache,pgno)); for(p=pCache->pDirty; p; p=pNext){ pNext = p->pDirtyNext; /* This routine never gets call with a positive pgno except right ** after sqlite3PcacheCleanAll(). So if there are dirty pages, ** it must be that pgno==0. */ assert( p->pgno>0 ); if( p->pgno>pgno ){ assert( p->flags&PGHDR_DIRTY ); sqlite3PcacheMakeClean(p); } } if( pgno==0 && pCache->nRefSum ){ sqlite3_pcache_page *pPage1; pPage1 = sqlite3GlobalConfig.pcache2.xFetch(pCache->pCache,1,0); if( ALWAYS(pPage1) ){ /* Page 1 is always available in cache, because ** pCache->nRefSum>0 */ memset(pPage1->pBuf, 0, pCache->szPage); pgno = 1; } } sqlite3GlobalConfig.pcache2.xTruncate(pCache->pCache, pgno+1); } } /* ** Close a cache. */ SQLITE_PRIVATE void sqlite3PcacheClose(PCache *pCache){ assert( pCache->pCache!=0 ); pcacheTrace(("%p.CLOSE\n",pCache)); sqlite3GlobalConfig.pcache2.xDestroy(pCache->pCache); } /* ** Discard the contents of the cache. */ SQLITE_PRIVATE void sqlite3PcacheClear(PCache *pCache){ sqlite3PcacheTruncate(pCache, 0); } /* ** Merge two lists of pages connected by pDirty and in pgno order. ** Do not bother fixing the pDirtyPrev pointers. */ static PgHdr *pcacheMergeDirtyList(PgHdr *pA, PgHdr *pB){ PgHdr result, *pTail; pTail = &result; assert( pA!=0 && pB!=0 ); for(;;){ if( pA->pgnopgno ){ pTail->pDirty = pA; pTail = pA; pA = pA->pDirty; if( pA==0 ){ pTail->pDirty = pB; break; } }else{ pTail->pDirty = pB; pTail = pB; pB = pB->pDirty; if( pB==0 ){ pTail->pDirty = pA; break; } } } return result.pDirty; } /* ** Sort the list of pages in accending order by pgno. Pages are ** connected by pDirty pointers. The pDirtyPrev pointers are ** corrupted by this sort. ** ** Since there cannot be more than 2^31 distinct pages in a database, ** there cannot be more than 31 buckets required by the merge sorter. ** One extra bucket is added to catch overflow in case something ** ever changes to make the previous sentence incorrect. */ #define N_SORT_BUCKET 32 static PgHdr *pcacheSortDirtyList(PgHdr *pIn){ PgHdr *a[N_SORT_BUCKET], *p; int i; memset(a, 0, sizeof(a)); while( pIn ){ p = pIn; pIn = p->pDirty; p->pDirty = 0; for(i=0; ALWAYS(ipDirty; p; p=p->pDirtyNext){ p->pDirty = p->pDirtyNext; } return pcacheSortDirtyList(pCache->pDirty); } /* ** Return the total number of references to all pages held by the cache. ** ** This is not the total number of pages referenced, but the sum of the ** reference count for all pages. */ SQLITE_PRIVATE int sqlite3PcacheRefCount(PCache *pCache){ return pCache->nRefSum; } /* ** Return the number of references to the page supplied as an argument. */ SQLITE_PRIVATE int sqlite3PcachePageRefcount(PgHdr *p){ return p->nRef; } /* ** Return the total number of pages in the cache. */ SQLITE_PRIVATE int sqlite3PcachePagecount(PCache *pCache){ assert( pCache->pCache!=0 ); return sqlite3GlobalConfig.pcache2.xPagecount(pCache->pCache); } #ifdef SQLITE_TEST /* ** Get the suggested cache-size value. */ SQLITE_PRIVATE int sqlite3PcacheGetCachesize(PCache *pCache){ return numberOfCachePages(pCache); } #endif /* ** Set the suggested cache-size value. */ SQLITE_PRIVATE void sqlite3PcacheSetCachesize(PCache *pCache, int mxPage){ assert( pCache->pCache!=0 ); pCache->szCache = mxPage; sqlite3GlobalConfig.pcache2.xCachesize(pCache->pCache, numberOfCachePages(pCache)); } /* ** Set the suggested cache-spill value. Make no changes if if the ** argument is zero. Return the effective cache-spill size, which will ** be the larger of the szSpill and szCache. */ SQLITE_PRIVATE int sqlite3PcacheSetSpillsize(PCache *p, int mxPage){ int res; assert( p->pCache!=0 ); if( mxPage ){ if( mxPage<0 ){ mxPage = (int)((-1024*(i64)mxPage)/(p->szPage+p->szExtra)); } p->szSpill = mxPage; } res = numberOfCachePages(p); if( resszSpill ) res = p->szSpill; return res; } /* ** Free up as much memory as possible from the page cache. */ SQLITE_PRIVATE void sqlite3PcacheShrink(PCache *pCache){ assert( pCache->pCache!=0 ); sqlite3GlobalConfig.pcache2.xShrink(pCache->pCache); } /* ** Return the size of the header added by this middleware layer ** in the page-cache hierarchy. */ SQLITE_PRIVATE int sqlite3HeaderSizePcache(void){ return ROUND8(sizeof(PgHdr)); } /* ** Return the number of dirty pages currently in the cache, as a percentage ** of the configured cache size. */ SQLITE_PRIVATE int sqlite3PCachePercentDirty(PCache *pCache){ PgHdr *pDirty; int nDirty = 0; int nCache = numberOfCachePages(pCache); for(pDirty=pCache->pDirty; pDirty; pDirty=pDirty->pDirtyNext) nDirty++; return nCache ? (int)(((i64)nDirty * 100) / nCache) : 0; } #if defined(SQLITE_CHECK_PAGES) || defined(SQLITE_DEBUG) /* ** For all dirty pages currently in the cache, invoke the specified ** callback. This is only used if the SQLITE_CHECK_PAGES macro is ** defined. */ SQLITE_PRIVATE void sqlite3PcacheIterateDirty(PCache *pCache, void (*xIter)(PgHdr *)){ PgHdr *pDirty; for(pDirty=pCache->pDirty; pDirty; pDirty=pDirty->pDirtyNext){ xIter(pDirty); } } #endif /************** End of pcache.c **********************************************/ /************** Begin file pcache1.c *****************************************/ /* ** 2008 November 05 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ************************************************************************* ** ** This file implements the default page cache implementation (the ** sqlite3_pcache interface). It also contains part of the implementation ** of the SQLITE_CONFIG_PAGECACHE and sqlite3_release_memory() features. ** If the default page cache implementation is overridden, then neither of ** these two features are available. ** ** A Page cache line looks like this: ** ** ------------------------------------------------------------- ** | database page content | PgHdr1 | MemPage | PgHdr | ** ------------------------------------------------------------- ** ** The database page content is up front (so that buffer overreads tend to ** flow harmlessly into the PgHdr1, MemPage, and PgHdr extensions). MemPage ** is the extension added by the btree.c module containing information such ** as the database page number and how that database page is used. PgHdr ** is added by the pcache.c layer and contains information used to keep track ** of which pages are "dirty". PgHdr1 is an extension added by this ** module (pcache1.c). The PgHdr1 header is a subclass of sqlite3_pcache_page. ** PgHdr1 contains information needed to look up a page by its page number. ** The superclass sqlite3_pcache_page.pBuf points to the start of the ** database page content and sqlite3_pcache_page.pExtra points to PgHdr. ** ** The size of the extension (MemPage+PgHdr+PgHdr1) can be determined at ** runtime using sqlite3_config(SQLITE_CONFIG_PCACHE_HDRSZ, &size). The ** sizes of the extensions sum to 272 bytes on x64 for 3.8.10, but this ** size can vary according to architecture, compile-time options, and ** SQLite library version number. ** ** If SQLITE_PCACHE_SEPARATE_HEADER is defined, then the extension is obtained ** using a separate memory allocation from the database page content. This ** seeks to overcome the "clownshoe" problem (also called "internal ** fragmentation" in academic literature) of allocating a few bytes more ** than a power of two with the memory allocator rounding up to the next ** power of two, and leaving the rounded-up space unused. ** ** This module tracks pointers to PgHdr1 objects. Only pcache.c communicates ** with this module. Information is passed back and forth as PgHdr1 pointers. ** ** The pcache.c and pager.c modules deal pointers to PgHdr objects. ** The btree.c module deals with pointers to MemPage objects. ** ** SOURCE OF PAGE CACHE MEMORY: ** ** Memory for a page might come from any of three sources: ** ** (1) The general-purpose memory allocator - sqlite3Malloc() ** (2) Global page-cache memory provided using sqlite3_config() with ** SQLITE_CONFIG_PAGECACHE. ** (3) PCache-local bulk allocation. ** ** The third case is a chunk of heap memory (defaulting to 100 pages worth) ** that is allocated when the page cache is created. The size of the local ** bulk allocation can be adjusted using ** ** sqlite3_config(SQLITE_CONFIG_PAGECACHE, (void*)0, 0, N). ** ** If N is positive, then N pages worth of memory are allocated using a single ** sqlite3Malloc() call and that memory is used for the first N pages allocated. ** Or if N is negative, then -1024*N bytes of memory are allocated and used ** for as many pages as can be accomodated. ** ** Only one of (2) or (3) can be used. Once the memory available to (2) or ** (3) is exhausted, subsequent allocations fail over to the general-purpose ** memory allocator (1). ** ** Earlier versions of SQLite used only methods (1) and (2). But experiments ** show that method (3) with N==100 provides about a 5% performance boost for ** common workloads. */ /* #include "sqliteInt.h" */ typedef struct PCache1 PCache1; typedef struct PgHdr1 PgHdr1; typedef struct PgFreeslot PgFreeslot; typedef struct PGroup PGroup; /* ** Each cache entry is represented by an instance of the following ** structure. Unless SQLITE_PCACHE_SEPARATE_HEADER is defined, a buffer of ** PgHdr1.pCache->szPage bytes is allocated directly before this structure ** in memory. */ struct PgHdr1 { sqlite3_pcache_page page; /* Base class. Must be first. pBuf & pExtra */ unsigned int iKey; /* Key value (page number) */ u8 isPinned; /* Page in use, not on the LRU list */ u8 isBulkLocal; /* This page from bulk local storage */ u8 isAnchor; /* This is the PGroup.lru element */ PgHdr1 *pNext; /* Next in hash table chain */ PCache1 *pCache; /* Cache that currently owns this page */ PgHdr1 *pLruNext; /* Next in LRU list of unpinned pages */ PgHdr1 *pLruPrev; /* Previous in LRU list of unpinned pages */ }; /* Each page cache (or PCache) belongs to a PGroup. A PGroup is a set ** of one or more PCaches that are able to recycle each other's unpinned ** pages when they are under memory pressure. A PGroup is an instance of ** the following object. ** ** This page cache implementation works in one of two modes: ** ** (1) Every PCache is the sole member of its own PGroup. There is ** one PGroup per PCache. ** ** (2) There is a single global PGroup that all PCaches are a member ** of. ** ** Mode 1 uses more memory (since PCache instances are not able to rob ** unused pages from other PCaches) but it also operates without a mutex, ** and is therefore often faster. Mode 2 requires a mutex in order to be ** threadsafe, but recycles pages more efficiently. ** ** For mode (1), PGroup.mutex is NULL. For mode (2) there is only a single ** PGroup which is the pcache1.grp global variable and its mutex is ** SQLITE_MUTEX_STATIC_LRU. */ struct PGroup { sqlite3_mutex *mutex; /* MUTEX_STATIC_LRU or NULL */ unsigned int nMaxPage; /* Sum of nMax for purgeable caches */ unsigned int nMinPage; /* Sum of nMin for purgeable caches */ unsigned int mxPinned; /* nMaxpage + 10 - nMinPage */ unsigned int nCurrentPage; /* Number of purgeable pages allocated */ PgHdr1 lru; /* The beginning and end of the LRU list */ }; /* Each page cache is an instance of the following object. Every ** open database file (including each in-memory database and each ** temporary or transient database) has a single page cache which ** is an instance of this object. ** ** Pointers to structures of this type are cast and returned as ** opaque sqlite3_pcache* handles. */ struct PCache1 { /* Cache configuration parameters. Page size (szPage) and the purgeable ** flag (bPurgeable) are set when the cache is created. nMax may be ** modified at any time by a call to the pcache1Cachesize() method. ** The PGroup mutex must be held when accessing nMax. */ PGroup *pGroup; /* PGroup this cache belongs to */ int szPage; /* Size of database content section */ int szExtra; /* sizeof(MemPage)+sizeof(PgHdr) */ int szAlloc; /* Total size of one pcache line */ int bPurgeable; /* True if cache is purgeable */ unsigned int nMin; /* Minimum number of pages reserved */ unsigned int nMax; /* Configured "cache_size" value */ unsigned int n90pct; /* nMax*9/10 */ unsigned int iMaxKey; /* Largest key seen since xTruncate() */ /* Hash table of all pages. The following variables may only be accessed ** when the accessor is holding the PGroup mutex. */ unsigned int nRecyclable; /* Number of pages in the LRU list */ unsigned int nPage; /* Total number of pages in apHash */ unsigned int nHash; /* Number of slots in apHash[] */ PgHdr1 **apHash; /* Hash table for fast lookup by key */ PgHdr1 *pFree; /* List of unused pcache-local pages */ void *pBulk; /* Bulk memory used by pcache-local */ }; /* ** Free slots in the allocator used to divide up the global page cache ** buffer provided using the SQLITE_CONFIG_PAGECACHE mechanism. */ struct PgFreeslot { PgFreeslot *pNext; /* Next free slot */ }; /* ** Global data used by this cache. */ static SQLITE_WSD struct PCacheGlobal { PGroup grp; /* The global PGroup for mode (2) */ /* Variables related to SQLITE_CONFIG_PAGECACHE settings. The ** szSlot, nSlot, pStart, pEnd, nReserve, and isInit values are all ** fixed at sqlite3_initialize() time and do not require mutex protection. ** The nFreeSlot and pFree values do require mutex protection. */ int isInit; /* True if initialized */ int separateCache; /* Use a new PGroup for each PCache */ int nInitPage; /* Initial bulk allocation size */ int szSlot; /* Size of each free slot */ int nSlot; /* The number of pcache slots */ int nReserve; /* Try to keep nFreeSlot above this */ void *pStart, *pEnd; /* Bounds of global page cache memory */ /* Above requires no mutex. Use mutex below for variable that follow. */ sqlite3_mutex *mutex; /* Mutex for accessing the following: */ PgFreeslot *pFree; /* Free page blocks */ int nFreeSlot; /* Number of unused pcache slots */ /* The following value requires a mutex to change. We skip the mutex on ** reading because (1) most platforms read a 32-bit integer atomically and ** (2) even if an incorrect value is read, no great harm is done since this ** is really just an optimization. */ int bUnderPressure; /* True if low on PAGECACHE memory */ } pcache1_g; /* ** All code in this file should access the global structure above via the ** alias "pcache1". This ensures that the WSD emulation is used when ** compiling for systems that do not support real WSD. */ #define pcache1 (GLOBAL(struct PCacheGlobal, pcache1_g)) /* ** Macros to enter and leave the PCache LRU mutex. */ #if !defined(SQLITE_ENABLE_MEMORY_MANAGEMENT) || SQLITE_THREADSAFE==0 # define pcache1EnterMutex(X) assert((X)->mutex==0) # define pcache1LeaveMutex(X) assert((X)->mutex==0) # define PCACHE1_MIGHT_USE_GROUP_MUTEX 0 #else # define pcache1EnterMutex(X) sqlite3_mutex_enter((X)->mutex) # define pcache1LeaveMutex(X) sqlite3_mutex_leave((X)->mutex) # define PCACHE1_MIGHT_USE_GROUP_MUTEX 1 #endif /******************************************************************************/ /******** Page Allocation/SQLITE_CONFIG_PCACHE Related Functions **************/ /* ** This function is called during initialization if a static buffer is ** supplied to use for the page-cache by passing the SQLITE_CONFIG_PAGECACHE ** verb to sqlite3_config(). Parameter pBuf points to an allocation large ** enough to contain 'n' buffers of 'sz' bytes each. ** ** This routine is called from sqlite3_initialize() and so it is guaranteed ** to be serialized already. There is no need for further mutexing. */ SQLITE_PRIVATE void sqlite3PCacheBufferSetup(void *pBuf, int sz, int n){ if( pcache1.isInit ){ PgFreeslot *p; if( pBuf==0 ) sz = n = 0; sz = ROUNDDOWN8(sz); pcache1.szSlot = sz; pcache1.nSlot = pcache1.nFreeSlot = n; pcache1.nReserve = n>90 ? 10 : (n/10 + 1); pcache1.pStart = pBuf; pcache1.pFree = 0; pcache1.bUnderPressure = 0; while( n-- ){ p = (PgFreeslot*)pBuf; p->pNext = pcache1.pFree; pcache1.pFree = p; pBuf = (void*)&((char*)pBuf)[sz]; } pcache1.pEnd = pBuf; } } /* ** Try to initialize the pCache->pFree and pCache->pBulk fields. Return ** true if pCache->pFree ends up containing one or more free pages. */ static int pcache1InitBulk(PCache1 *pCache){ i64 szBulk; char *zBulk; if( pcache1.nInitPage==0 ) return 0; /* Do not bother with a bulk allocation if the cache size very small */ if( pCache->nMax<3 ) return 0; sqlite3BeginBenignMalloc(); if( pcache1.nInitPage>0 ){ szBulk = pCache->szAlloc * (i64)pcache1.nInitPage; }else{ szBulk = -1024 * (i64)pcache1.nInitPage; } if( szBulk > pCache->szAlloc*(i64)pCache->nMax ){ szBulk = pCache->szAlloc*(i64)pCache->nMax; } zBulk = pCache->pBulk = sqlite3Malloc( szBulk ); sqlite3EndBenignMalloc(); if( zBulk ){ int nBulk = sqlite3MallocSize(zBulk)/pCache->szAlloc; int i; for(i=0; iszPage]; pX->page.pBuf = zBulk; pX->page.pExtra = &pX[1]; pX->isBulkLocal = 1; pX->isAnchor = 0; pX->pNext = pCache->pFree; pCache->pFree = pX; zBulk += pCache->szAlloc; } } return pCache->pFree!=0; } /* ** Malloc function used within this file to allocate space from the buffer ** configured using sqlite3_config(SQLITE_CONFIG_PAGECACHE) option. If no ** such buffer exists or there is no space left in it, this function falls ** back to sqlite3Malloc(). ** ** Multiple threads can run this routine at the same time. Global variables ** in pcache1 need to be protected via mutex. */ static void *pcache1Alloc(int nByte){ void *p = 0; assert( sqlite3_mutex_notheld(pcache1.grp.mutex) ); if( nByte<=pcache1.szSlot ){ sqlite3_mutex_enter(pcache1.mutex); p = (PgHdr1 *)pcache1.pFree; if( p ){ pcache1.pFree = pcache1.pFree->pNext; pcache1.nFreeSlot--; pcache1.bUnderPressure = pcache1.nFreeSlot=0 ); sqlite3StatusHighwater(SQLITE_STATUS_PAGECACHE_SIZE, nByte); sqlite3StatusUp(SQLITE_STATUS_PAGECACHE_USED, 1); } sqlite3_mutex_leave(pcache1.mutex); } if( p==0 ){ /* Memory is not available in the SQLITE_CONFIG_PAGECACHE pool. Get ** it from sqlite3Malloc instead. */ p = sqlite3Malloc(nByte); #ifndef SQLITE_DISABLE_PAGECACHE_OVERFLOW_STATS if( p ){ int sz = sqlite3MallocSize(p); sqlite3_mutex_enter(pcache1.mutex); sqlite3StatusHighwater(SQLITE_STATUS_PAGECACHE_SIZE, nByte); sqlite3StatusUp(SQLITE_STATUS_PAGECACHE_OVERFLOW, sz); sqlite3_mutex_leave(pcache1.mutex); } #endif sqlite3MemdebugSetType(p, MEMTYPE_PCACHE); } return p; } /* ** Free an allocated buffer obtained from pcache1Alloc(). */ static void pcache1Free(void *p){ if( p==0 ) return; if( SQLITE_WITHIN(p, pcache1.pStart, pcache1.pEnd) ){ PgFreeslot *pSlot; sqlite3_mutex_enter(pcache1.mutex); sqlite3StatusDown(SQLITE_STATUS_PAGECACHE_USED, 1); pSlot = (PgFreeslot*)p; pSlot->pNext = pcache1.pFree; pcache1.pFree = pSlot; pcache1.nFreeSlot++; pcache1.bUnderPressure = pcache1.nFreeSlot=pcache1.pStart && ppGroup->mutex) ); if( pCache->pFree || (pCache->nPage==0 && pcache1InitBulk(pCache)) ){ p = pCache->pFree; pCache->pFree = p->pNext; p->pNext = 0; }else{ #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT /* The group mutex must be released before pcache1Alloc() is called. This ** is because it might call sqlite3_release_memory(), which assumes that ** this mutex is not held. */ assert( pcache1.separateCache==0 ); assert( pCache->pGroup==&pcache1.grp ); pcache1LeaveMutex(pCache->pGroup); #endif if( benignMalloc ){ sqlite3BeginBenignMalloc(); } #ifdef SQLITE_PCACHE_SEPARATE_HEADER pPg = pcache1Alloc(pCache->szPage); p = sqlite3Malloc(sizeof(PgHdr1) + pCache->szExtra); if( !pPg || !p ){ pcache1Free(pPg); sqlite3_free(p); pPg = 0; } #else pPg = pcache1Alloc(pCache->szAlloc); p = (PgHdr1 *)&((u8 *)pPg)[pCache->szPage]; #endif if( benignMalloc ){ sqlite3EndBenignMalloc(); } #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT pcache1EnterMutex(pCache->pGroup); #endif if( pPg==0 ) return 0; p->page.pBuf = pPg; p->page.pExtra = &p[1]; p->isBulkLocal = 0; p->isAnchor = 0; } if( pCache->bPurgeable ){ pCache->pGroup->nCurrentPage++; } return p; } /* ** Free a page object allocated by pcache1AllocPage(). */ static void pcache1FreePage(PgHdr1 *p){ PCache1 *pCache; assert( p!=0 ); pCache = p->pCache; assert( sqlite3_mutex_held(p->pCache->pGroup->mutex) ); if( p->isBulkLocal ){ p->pNext = pCache->pFree; pCache->pFree = p; }else{ pcache1Free(p->page.pBuf); #ifdef SQLITE_PCACHE_SEPARATE_HEADER sqlite3_free(p); #endif } if( pCache->bPurgeable ){ pCache->pGroup->nCurrentPage--; } } /* ** Malloc function used by SQLite to obtain space from the buffer configured ** using sqlite3_config(SQLITE_CONFIG_PAGECACHE) option. If no such buffer ** exists, this function falls back to sqlite3Malloc(). */ SQLITE_PRIVATE void *sqlite3PageMalloc(int sz){ return pcache1Alloc(sz); } /* ** Free an allocated buffer obtained from sqlite3PageMalloc(). */ SQLITE_PRIVATE void sqlite3PageFree(void *p){ pcache1Free(p); } /* ** Return true if it desirable to avoid allocating a new page cache ** entry. ** ** If memory was allocated specifically to the page cache using ** SQLITE_CONFIG_PAGECACHE but that memory has all been used, then ** it is desirable to avoid allocating a new page cache entry because ** presumably SQLITE_CONFIG_PAGECACHE was suppose to be sufficient ** for all page cache needs and we should not need to spill the ** allocation onto the heap. ** ** Or, the heap is used for all page cache memory but the heap is ** under memory pressure, then again it is desirable to avoid ** allocating a new page cache entry in order to avoid stressing ** the heap even further. */ static int pcache1UnderMemoryPressure(PCache1 *pCache){ if( pcache1.nSlot && (pCache->szPage+pCache->szExtra)<=pcache1.szSlot ){ return pcache1.bUnderPressure; }else{ return sqlite3HeapNearlyFull(); } } /******************************************************************************/ /******** General Implementation Functions ************************************/ /* ** This function is used to resize the hash table used by the cache passed ** as the first argument. ** ** The PCache mutex must be held when this function is called. */ static void pcache1ResizeHash(PCache1 *p){ PgHdr1 **apNew; unsigned int nNew; unsigned int i; assert( sqlite3_mutex_held(p->pGroup->mutex) ); nNew = p->nHash*2; if( nNew<256 ){ nNew = 256; } pcache1LeaveMutex(p->pGroup); if( p->nHash ){ sqlite3BeginBenignMalloc(); } apNew = (PgHdr1 **)sqlite3MallocZero(sizeof(PgHdr1 *)*nNew); if( p->nHash ){ sqlite3EndBenignMalloc(); } pcache1EnterMutex(p->pGroup); if( apNew ){ for(i=0; inHash; i++){ PgHdr1 *pPage; PgHdr1 *pNext = p->apHash[i]; while( (pPage = pNext)!=0 ){ unsigned int h = pPage->iKey % nNew; pNext = pPage->pNext; pPage->pNext = apNew[h]; apNew[h] = pPage; } } sqlite3_free(p->apHash); p->apHash = apNew; p->nHash = nNew; } } /* ** This function is used internally to remove the page pPage from the ** PGroup LRU list, if is part of it. If pPage is not part of the PGroup ** LRU list, then this function is a no-op. ** ** The PGroup mutex must be held when this function is called. */ static PgHdr1 *pcache1PinPage(PgHdr1 *pPage){ PCache1 *pCache; assert( pPage!=0 ); assert( pPage->isPinned==0 ); pCache = pPage->pCache; assert( pPage->pLruNext ); assert( pPage->pLruPrev ); assert( sqlite3_mutex_held(pCache->pGroup->mutex) ); pPage->pLruPrev->pLruNext = pPage->pLruNext; pPage->pLruNext->pLruPrev = pPage->pLruPrev; pPage->pLruNext = 0; pPage->pLruPrev = 0; pPage->isPinned = 1; assert( pPage->isAnchor==0 ); assert( pCache->pGroup->lru.isAnchor==1 ); pCache->nRecyclable--; return pPage; } /* ** Remove the page supplied as an argument from the hash table ** (PCache1.apHash structure) that it is currently stored in. ** Also free the page if freePage is true. ** ** The PGroup mutex must be held when this function is called. */ static void pcache1RemoveFromHash(PgHdr1 *pPage, int freeFlag){ unsigned int h; PCache1 *pCache = pPage->pCache; PgHdr1 **pp; assert( sqlite3_mutex_held(pCache->pGroup->mutex) ); h = pPage->iKey % pCache->nHash; for(pp=&pCache->apHash[h]; (*pp)!=pPage; pp=&(*pp)->pNext); *pp = (*pp)->pNext; pCache->nPage--; if( freeFlag ) pcache1FreePage(pPage); } /* ** If there are currently more than nMaxPage pages allocated, try ** to recycle pages to reduce the number allocated to nMaxPage. */ static void pcache1EnforceMaxPage(PCache1 *pCache){ PGroup *pGroup = pCache->pGroup; PgHdr1 *p; assert( sqlite3_mutex_held(pGroup->mutex) ); while( pGroup->nCurrentPage>pGroup->nMaxPage && (p=pGroup->lru.pLruPrev)->isAnchor==0 ){ assert( p->pCache->pGroup==pGroup ); assert( p->isPinned==0 ); pcache1PinPage(p); pcache1RemoveFromHash(p, 1); } if( pCache->nPage==0 && pCache->pBulk ){ sqlite3_free(pCache->pBulk); pCache->pBulk = pCache->pFree = 0; } } /* ** Discard all pages from cache pCache with a page number (key value) ** greater than or equal to iLimit. Any pinned pages that meet this ** criteria are unpinned before they are discarded. ** ** The PCache mutex must be held when this function is called. */ static void pcache1TruncateUnsafe( PCache1 *pCache, /* The cache to truncate */ unsigned int iLimit /* Drop pages with this pgno or larger */ ){ TESTONLY( int nPage = 0; ) /* To assert pCache->nPage is correct */ unsigned int h, iStop; assert( sqlite3_mutex_held(pCache->pGroup->mutex) ); assert( pCache->iMaxKey >= iLimit ); assert( pCache->nHash > 0 ); if( pCache->iMaxKey - iLimit < pCache->nHash ){ /* If we are just shaving the last few pages off the end of the ** cache, then there is no point in scanning the entire hash table. ** Only scan those hash slots that might contain pages that need to ** be removed. */ h = iLimit % pCache->nHash; iStop = pCache->iMaxKey % pCache->nHash; TESTONLY( nPage = -10; ) /* Disable the pCache->nPage validity check */ }else{ /* This is the general case where many pages are being removed. ** It is necessary to scan the entire hash table */ h = pCache->nHash/2; iStop = h - 1; } for(;;){ PgHdr1 **pp; PgHdr1 *pPage; assert( hnHash ); pp = &pCache->apHash[h]; while( (pPage = *pp)!=0 ){ if( pPage->iKey>=iLimit ){ pCache->nPage--; *pp = pPage->pNext; if( !pPage->isPinned ) pcache1PinPage(pPage); pcache1FreePage(pPage); }else{ pp = &pPage->pNext; TESTONLY( if( nPage>=0 ) nPage++; ) } } if( h==iStop ) break; h = (h+1) % pCache->nHash; } assert( nPage<0 || pCache->nPage==(unsigned)nPage ); } /******************************************************************************/ /******** sqlite3_pcache Methods **********************************************/ /* ** Implementation of the sqlite3_pcache.xInit method. */ static int pcache1Init(void *NotUsed){ UNUSED_PARAMETER(NotUsed); assert( pcache1.isInit==0 ); memset(&pcache1, 0, sizeof(pcache1)); /* ** The pcache1.separateCache variable is true if each PCache has its own ** private PGroup (mode-1). pcache1.separateCache is false if the single ** PGroup in pcache1.grp is used for all page caches (mode-2). ** ** * Always use a unified cache (mode-2) if ENABLE_MEMORY_MANAGEMENT ** ** * Use a unified cache in single-threaded applications that have ** configured a start-time buffer for use as page-cache memory using ** sqlite3_config(SQLITE_CONFIG_PAGECACHE, pBuf, sz, N) with non-NULL ** pBuf argument. ** ** * Otherwise use separate caches (mode-1) */ #if defined(SQLITE_ENABLE_MEMORY_MANAGEMENT) pcache1.separateCache = 0; #elif SQLITE_THREADSAFE pcache1.separateCache = sqlite3GlobalConfig.pPage==0 || sqlite3GlobalConfig.bCoreMutex>0; #else pcache1.separateCache = sqlite3GlobalConfig.pPage==0; #endif #if SQLITE_THREADSAFE if( sqlite3GlobalConfig.bCoreMutex ){ pcache1.grp.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_LRU); pcache1.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_PMEM); } #endif if( pcache1.separateCache && sqlite3GlobalConfig.nPage!=0 && sqlite3GlobalConfig.pPage==0 ){ pcache1.nInitPage = sqlite3GlobalConfig.nPage; }else{ pcache1.nInitPage = 0; } pcache1.grp.mxPinned = 10; pcache1.isInit = 1; return SQLITE_OK; } /* ** Implementation of the sqlite3_pcache.xShutdown method. ** Note that the static mutex allocated in xInit does ** not need to be freed. */ static void pcache1Shutdown(void *NotUsed){ UNUSED_PARAMETER(NotUsed); assert( pcache1.isInit!=0 ); memset(&pcache1, 0, sizeof(pcache1)); } /* forward declaration */ static void pcache1Destroy(sqlite3_pcache *p); /* ** Implementation of the sqlite3_pcache.xCreate method. ** ** Allocate a new cache. */ static sqlite3_pcache *pcache1Create(int szPage, int szExtra, int bPurgeable){ PCache1 *pCache; /* The newly created page cache */ PGroup *pGroup; /* The group the new page cache will belong to */ int sz; /* Bytes of memory required to allocate the new cache */ assert( (szPage & (szPage-1))==0 && szPage>=512 && szPage<=65536 ); assert( szExtra < 300 ); sz = sizeof(PCache1) + sizeof(PGroup)*pcache1.separateCache; pCache = (PCache1 *)sqlite3MallocZero(sz); if( pCache ){ if( pcache1.separateCache ){ pGroup = (PGroup*)&pCache[1]; pGroup->mxPinned = 10; }else{ pGroup = &pcache1.grp; } if( pGroup->lru.isAnchor==0 ){ pGroup->lru.isAnchor = 1; pGroup->lru.pLruPrev = pGroup->lru.pLruNext = &pGroup->lru; } pCache->pGroup = pGroup; pCache->szPage = szPage; pCache->szExtra = szExtra; pCache->szAlloc = szPage + szExtra + ROUND8(sizeof(PgHdr1)); pCache->bPurgeable = (bPurgeable ? 1 : 0); pcache1EnterMutex(pGroup); pcache1ResizeHash(pCache); if( bPurgeable ){ pCache->nMin = 10; pGroup->nMinPage += pCache->nMin; pGroup->mxPinned = pGroup->nMaxPage + 10 - pGroup->nMinPage; } pcache1LeaveMutex(pGroup); if( pCache->nHash==0 ){ pcache1Destroy((sqlite3_pcache*)pCache); pCache = 0; } } return (sqlite3_pcache *)pCache; } /* ** Implementation of the sqlite3_pcache.xCachesize method. ** ** Configure the cache_size limit for a cache. */ static void pcache1Cachesize(sqlite3_pcache *p, int nMax){ PCache1 *pCache = (PCache1 *)p; if( pCache->bPurgeable ){ PGroup *pGroup = pCache->pGroup; pcache1EnterMutex(pGroup); pGroup->nMaxPage += (nMax - pCache->nMax); pGroup->mxPinned = pGroup->nMaxPage + 10 - pGroup->nMinPage; pCache->nMax = nMax; pCache->n90pct = pCache->nMax*9/10; pcache1EnforceMaxPage(pCache); pcache1LeaveMutex(pGroup); } } /* ** Implementation of the sqlite3_pcache.xShrink method. ** ** Free up as much memory as possible. */ static void pcache1Shrink(sqlite3_pcache *p){ PCache1 *pCache = (PCache1*)p; if( pCache->bPurgeable ){ PGroup *pGroup = pCache->pGroup; int savedMaxPage; pcache1EnterMutex(pGroup); savedMaxPage = pGroup->nMaxPage; pGroup->nMaxPage = 0; pcache1EnforceMaxPage(pCache); pGroup->nMaxPage = savedMaxPage; pcache1LeaveMutex(pGroup); } } /* ** Implementation of the sqlite3_pcache.xPagecount method. */ static int pcache1Pagecount(sqlite3_pcache *p){ int n; PCache1 *pCache = (PCache1*)p; pcache1EnterMutex(pCache->pGroup); n = pCache->nPage; pcache1LeaveMutex(pCache->pGroup); return n; } /* ** Implement steps 3, 4, and 5 of the pcache1Fetch() algorithm described ** in the header of the pcache1Fetch() procedure. ** ** This steps are broken out into a separate procedure because they are ** usually not needed, and by avoiding the stack initialization required ** for these steps, the main pcache1Fetch() procedure can run faster. */ static SQLITE_NOINLINE PgHdr1 *pcache1FetchStage2( PCache1 *pCache, unsigned int iKey, int createFlag ){ unsigned int nPinned; PGroup *pGroup = pCache->pGroup; PgHdr1 *pPage = 0; /* Step 3: Abort if createFlag is 1 but the cache is nearly full */ assert( pCache->nPage >= pCache->nRecyclable ); nPinned = pCache->nPage - pCache->nRecyclable; assert( pGroup->mxPinned == pGroup->nMaxPage + 10 - pGroup->nMinPage ); assert( pCache->n90pct == pCache->nMax*9/10 ); if( createFlag==1 && ( nPinned>=pGroup->mxPinned || nPinned>=pCache->n90pct || (pcache1UnderMemoryPressure(pCache) && pCache->nRecyclablenPage>=pCache->nHash ) pcache1ResizeHash(pCache); assert( pCache->nHash>0 && pCache->apHash ); /* Step 4. Try to recycle a page. */ if( pCache->bPurgeable && !pGroup->lru.pLruPrev->isAnchor && ((pCache->nPage+1>=pCache->nMax) || pcache1UnderMemoryPressure(pCache)) ){ PCache1 *pOther; pPage = pGroup->lru.pLruPrev; assert( pPage->isPinned==0 ); pcache1RemoveFromHash(pPage, 0); pcache1PinPage(pPage); pOther = pPage->pCache; if( pOther->szAlloc != pCache->szAlloc ){ pcache1FreePage(pPage); pPage = 0; }else{ pGroup->nCurrentPage -= (pOther->bPurgeable - pCache->bPurgeable); } } /* Step 5. If a usable page buffer has still not been found, ** attempt to allocate a new one. */ if( !pPage ){ pPage = pcache1AllocPage(pCache, createFlag==1); } if( pPage ){ unsigned int h = iKey % pCache->nHash; pCache->nPage++; pPage->iKey = iKey; pPage->pNext = pCache->apHash[h]; pPage->pCache = pCache; pPage->pLruPrev = 0; pPage->pLruNext = 0; pPage->isPinned = 1; *(void **)pPage->page.pExtra = 0; pCache->apHash[h] = pPage; if( iKey>pCache->iMaxKey ){ pCache->iMaxKey = iKey; } } return pPage; } /* ** Implementation of the sqlite3_pcache.xFetch method. ** ** Fetch a page by key value. ** ** Whether or not a new page may be allocated by this function depends on ** the value of the createFlag argument. 0 means do not allocate a new ** page. 1 means allocate a new page if space is easily available. 2 ** means to try really hard to allocate a new page. ** ** For a non-purgeable cache (a cache used as the storage for an in-memory ** database) there is really no difference between createFlag 1 and 2. So ** the calling function (pcache.c) will never have a createFlag of 1 on ** a non-purgeable cache. ** ** There are three different approaches to obtaining space for a page, ** depending on the value of parameter createFlag (which may be 0, 1 or 2). ** ** 1. Regardless of the value of createFlag, the cache is searched for a ** copy of the requested page. If one is found, it is returned. ** ** 2. If createFlag==0 and the page is not already in the cache, NULL is ** returned. ** ** 3. If createFlag is 1, and the page is not already in the cache, then ** return NULL (do not allocate a new page) if any of the following ** conditions are true: ** ** (a) the number of pages pinned by the cache is greater than ** PCache1.nMax, or ** ** (b) the number of pages pinned by the cache is greater than ** the sum of nMax for all purgeable caches, less the sum of ** nMin for all other purgeable caches, or ** ** 4. If none of the first three conditions apply and the cache is marked ** as purgeable, and if one of the following is true: ** ** (a) The number of pages allocated for the cache is already ** PCache1.nMax, or ** ** (b) The number of pages allocated for all purgeable caches is ** already equal to or greater than the sum of nMax for all ** purgeable caches, ** ** (c) The system is under memory pressure and wants to avoid ** unnecessary pages cache entry allocations ** ** then attempt to recycle a page from the LRU list. If it is the right ** size, return the recycled buffer. Otherwise, free the buffer and ** proceed to step 5. ** ** 5. Otherwise, allocate and return a new page buffer. ** ** There are two versions of this routine. pcache1FetchWithMutex() is ** the general case. pcache1FetchNoMutex() is a faster implementation for ** the common case where pGroup->mutex is NULL. The pcache1Fetch() wrapper ** invokes the appropriate routine. */ static PgHdr1 *pcache1FetchNoMutex( sqlite3_pcache *p, unsigned int iKey, int createFlag ){ PCache1 *pCache = (PCache1 *)p; PgHdr1 *pPage = 0; /* Step 1: Search the hash table for an existing entry. */ pPage = pCache->apHash[iKey % pCache->nHash]; while( pPage && pPage->iKey!=iKey ){ pPage = pPage->pNext; } /* Step 2: If the page was found in the hash table, then return it. ** If the page was not in the hash table and createFlag is 0, abort. ** Otherwise (page not in hash and createFlag!=0) continue with ** subsequent steps to try to create the page. */ if( pPage ){ if( !pPage->isPinned ){ return pcache1PinPage(pPage); }else{ return pPage; } }else if( createFlag ){ /* Steps 3, 4, and 5 implemented by this subroutine */ return pcache1FetchStage2(pCache, iKey, createFlag); }else{ return 0; } } #if PCACHE1_MIGHT_USE_GROUP_MUTEX static PgHdr1 *pcache1FetchWithMutex( sqlite3_pcache *p, unsigned int iKey, int createFlag ){ PCache1 *pCache = (PCache1 *)p; PgHdr1 *pPage; pcache1EnterMutex(pCache->pGroup); pPage = pcache1FetchNoMutex(p, iKey, createFlag); assert( pPage==0 || pCache->iMaxKey>=iKey ); pcache1LeaveMutex(pCache->pGroup); return pPage; } #endif static sqlite3_pcache_page *pcache1Fetch( sqlite3_pcache *p, unsigned int iKey, int createFlag ){ #if PCACHE1_MIGHT_USE_GROUP_MUTEX || defined(SQLITE_DEBUG) PCache1 *pCache = (PCache1 *)p; #endif assert( offsetof(PgHdr1,page)==0 ); assert( pCache->bPurgeable || createFlag!=1 ); assert( pCache->bPurgeable || pCache->nMin==0 ); assert( pCache->bPurgeable==0 || pCache->nMin==10 ); assert( pCache->nMin==0 || pCache->bPurgeable ); assert( pCache->nHash>0 ); #if PCACHE1_MIGHT_USE_GROUP_MUTEX if( pCache->pGroup->mutex ){ return (sqlite3_pcache_page*)pcache1FetchWithMutex(p, iKey, createFlag); }else #endif { return (sqlite3_pcache_page*)pcache1FetchNoMutex(p, iKey, createFlag); } } /* ** Implementation of the sqlite3_pcache.xUnpin method. ** ** Mark a page as unpinned (eligible for asynchronous recycling). */ static void pcache1Unpin( sqlite3_pcache *p, sqlite3_pcache_page *pPg, int reuseUnlikely ){ PCache1 *pCache = (PCache1 *)p; PgHdr1 *pPage = (PgHdr1 *)pPg; PGroup *pGroup = pCache->pGroup; assert( pPage->pCache==pCache ); pcache1EnterMutex(pGroup); /* It is an error to call this function if the page is already ** part of the PGroup LRU list. */ assert( pPage->pLruPrev==0 && pPage->pLruNext==0 ); assert( pPage->isPinned==1 ); if( reuseUnlikely || pGroup->nCurrentPage>pGroup->nMaxPage ){ pcache1RemoveFromHash(pPage, 1); }else{ /* Add the page to the PGroup LRU list. */ PgHdr1 **ppFirst = &pGroup->lru.pLruNext; pPage->pLruPrev = &pGroup->lru; (pPage->pLruNext = *ppFirst)->pLruPrev = pPage; *ppFirst = pPage; pCache->nRecyclable++; pPage->isPinned = 0; } pcache1LeaveMutex(pCache->pGroup); } /* ** Implementation of the sqlite3_pcache.xRekey method. */ static void pcache1Rekey( sqlite3_pcache *p, sqlite3_pcache_page *pPg, unsigned int iOld, unsigned int iNew ){ PCache1 *pCache = (PCache1 *)p; PgHdr1 *pPage = (PgHdr1 *)pPg; PgHdr1 **pp; unsigned int h; assert( pPage->iKey==iOld ); assert( pPage->pCache==pCache ); pcache1EnterMutex(pCache->pGroup); h = iOld%pCache->nHash; pp = &pCache->apHash[h]; while( (*pp)!=pPage ){ pp = &(*pp)->pNext; } *pp = pPage->pNext; h = iNew%pCache->nHash; pPage->iKey = iNew; pPage->pNext = pCache->apHash[h]; pCache->apHash[h] = pPage; if( iNew>pCache->iMaxKey ){ pCache->iMaxKey = iNew; } pcache1LeaveMutex(pCache->pGroup); } /* ** Implementation of the sqlite3_pcache.xTruncate method. ** ** Discard all unpinned pages in the cache with a page number equal to ** or greater than parameter iLimit. Any pinned pages with a page number ** equal to or greater than iLimit are implicitly unpinned. */ static void pcache1Truncate(sqlite3_pcache *p, unsigned int iLimit){ PCache1 *pCache = (PCache1 *)p; pcache1EnterMutex(pCache->pGroup); if( iLimit<=pCache->iMaxKey ){ pcache1TruncateUnsafe(pCache, iLimit); pCache->iMaxKey = iLimit-1; } pcache1LeaveMutex(pCache->pGroup); } /* ** Implementation of the sqlite3_pcache.xDestroy method. ** ** Destroy a cache allocated using pcache1Create(). */ static void pcache1Destroy(sqlite3_pcache *p){ PCache1 *pCache = (PCache1 *)p; PGroup *pGroup = pCache->pGroup; assert( pCache->bPurgeable || (pCache->nMax==0 && pCache->nMin==0) ); pcache1EnterMutex(pGroup); if( pCache->nPage ) pcache1TruncateUnsafe(pCache, 0); assert( pGroup->nMaxPage >= pCache->nMax ); pGroup->nMaxPage -= pCache->nMax; assert( pGroup->nMinPage >= pCache->nMin ); pGroup->nMinPage -= pCache->nMin; pGroup->mxPinned = pGroup->nMaxPage + 10 - pGroup->nMinPage; pcache1EnforceMaxPage(pCache); pcache1LeaveMutex(pGroup); sqlite3_free(pCache->pBulk); sqlite3_free(pCache->apHash); sqlite3_free(pCache); } /* ** This function is called during initialization (sqlite3_initialize()) to ** install the default pluggable cache module, assuming the user has not ** already provided an alternative. */ SQLITE_PRIVATE void sqlite3PCacheSetDefault(void){ static const sqlite3_pcache_methods2 defaultMethods = { 1, /* iVersion */ 0, /* pArg */ pcache1Init, /* xInit */ pcache1Shutdown, /* xShutdown */ pcache1Create, /* xCreate */ pcache1Cachesize, /* xCachesize */ pcache1Pagecount, /* xPagecount */ pcache1Fetch, /* xFetch */ pcache1Unpin, /* xUnpin */ pcache1Rekey, /* xRekey */ pcache1Truncate, /* xTruncate */ pcache1Destroy, /* xDestroy */ pcache1Shrink /* xShrink */ }; sqlite3_config(SQLITE_CONFIG_PCACHE2, &defaultMethods); } /* ** Return the size of the header on each page of this PCACHE implementation. */ SQLITE_PRIVATE int sqlite3HeaderSizePcache1(void){ return ROUND8(sizeof(PgHdr1)); } /* ** Return the global mutex used by this PCACHE implementation. The ** sqlite3_status() routine needs access to this mutex. */ SQLITE_PRIVATE sqlite3_mutex *sqlite3Pcache1Mutex(void){ return pcache1.mutex; } #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT /* ** This function is called to free superfluous dynamically allocated memory ** held by the pager system. Memory in use by any SQLite pager allocated ** by the current thread may be sqlite3_free()ed. ** ** nReq is the number of bytes of memory required. Once this much has ** been released, the function returns. The return value is the total number ** of bytes of memory released. */ SQLITE_PRIVATE int sqlite3PcacheReleaseMemory(int nReq){ int nFree = 0; assert( sqlite3_mutex_notheld(pcache1.grp.mutex) ); assert( sqlite3_mutex_notheld(pcache1.mutex) ); if( sqlite3GlobalConfig.nPage==0 ){ PgHdr1 *p; pcache1EnterMutex(&pcache1.grp); while( (nReq<0 || nFreeisAnchor==0 ){ nFree += pcache1MemSize(p->page.pBuf); #ifdef SQLITE_PCACHE_SEPARATE_HEADER nFree += sqlite3MemSize(p); #endif assert( p->isPinned==0 ); pcache1PinPage(p); pcache1RemoveFromHash(p, 1); } pcache1LeaveMutex(&pcache1.grp); } return nFree; } #endif /* SQLITE_ENABLE_MEMORY_MANAGEMENT */ #ifdef SQLITE_TEST /* ** This function is used by test procedures to inspect the internal state ** of the global cache. */ SQLITE_PRIVATE void sqlite3PcacheStats( int *pnCurrent, /* OUT: Total number of pages cached */ int *pnMax, /* OUT: Global maximum cache size */ int *pnMin, /* OUT: Sum of PCache1.nMin for purgeable caches */ int *pnRecyclable /* OUT: Total number of pages available for recycling */ ){ PgHdr1 *p; int nRecyclable = 0; for(p=pcache1.grp.lru.pLruNext; p && !p->isAnchor; p=p->pLruNext){ assert( p->isPinned==0 ); nRecyclable++; } *pnCurrent = pcache1.grp.nCurrentPage; *pnMax = (int)pcache1.grp.nMaxPage; *pnMin = (int)pcache1.grp.nMinPage; *pnRecyclable = nRecyclable; } #endif /************** End of pcache1.c *********************************************/ /************** Begin file rowset.c ******************************************/ /* ** 2008 December 3 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ************************************************************************* ** ** This module implements an object we call a "RowSet". ** ** The RowSet object is a collection of rowids. Rowids ** are inserted into the RowSet in an arbitrary order. Inserts ** can be intermixed with tests to see if a given rowid has been ** previously inserted into the RowSet. ** ** After all inserts are finished, it is possible to extract the ** elements of the RowSet in sorted order. Once this extraction ** process has started, no new elements may be inserted. ** ** Hence, the primitive operations for a RowSet are: ** ** CREATE ** INSERT ** TEST ** SMALLEST ** DESTROY ** ** The CREATE and DESTROY primitives are the constructor and destructor, ** obviously. The INSERT primitive adds a new element to the RowSet. ** TEST checks to see if an element is already in the RowSet. SMALLEST ** extracts the least value from the RowSet. ** ** The INSERT primitive might allocate additional memory. Memory is ** allocated in chunks so most INSERTs do no allocation. There is an ** upper bound on the size of allocated memory. No memory is freed ** until DESTROY. ** ** The TEST primitive includes a "batch" number. The TEST primitive ** will only see elements that were inserted before the last change ** in the batch number. In other words, if an INSERT occurs between ** two TESTs where the TESTs have the same batch nubmer, then the ** value added by the INSERT will not be visible to the second TEST. ** The initial batch number is zero, so if the very first TEST contains ** a non-zero batch number, it will see all prior INSERTs. ** ** No INSERTs may occurs after a SMALLEST. An assertion will fail if ** that is attempted. ** ** The cost of an INSERT is roughly constant. (Sometimes new memory ** has to be allocated on an INSERT.) The cost of a TEST with a new ** batch number is O(NlogN) where N is the number of elements in the RowSet. ** The cost of a TEST using the same batch number is O(logN). The cost ** of the first SMALLEST is O(NlogN). Second and subsequent SMALLEST ** primitives are constant time. The cost of DESTROY is O(N). ** ** TEST and SMALLEST may not be used by the same RowSet. This used to ** be possible, but the feature was not used, so it was removed in order ** to simplify the code. */ /* #include "sqliteInt.h" */ /* ** Target size for allocation chunks. */ #define ROWSET_ALLOCATION_SIZE 1024 /* ** The number of rowset entries per allocation chunk. */ #define ROWSET_ENTRY_PER_CHUNK \ ((ROWSET_ALLOCATION_SIZE-8)/sizeof(struct RowSetEntry)) /* ** Each entry in a RowSet is an instance of the following object. ** ** This same object is reused to store a linked list of trees of RowSetEntry ** objects. In that alternative use, pRight points to the next entry ** in the list, pLeft points to the tree, and v is unused. The ** RowSet.pForest value points to the head of this forest list. */ struct RowSetEntry { i64 v; /* ROWID value for this entry */ struct RowSetEntry *pRight; /* Right subtree (larger entries) or list */ struct RowSetEntry *pLeft; /* Left subtree (smaller entries) */ }; /* ** RowSetEntry objects are allocated in large chunks (instances of the ** following structure) to reduce memory allocation overhead. The ** chunks are kept on a linked list so that they can be deallocated ** when the RowSet is destroyed. */ struct RowSetChunk { struct RowSetChunk *pNextChunk; /* Next chunk on list of them all */ struct RowSetEntry aEntry[ROWSET_ENTRY_PER_CHUNK]; /* Allocated entries */ }; /* ** A RowSet in an instance of the following structure. ** ** A typedef of this structure if found in sqliteInt.h. */ struct RowSet { struct RowSetChunk *pChunk; /* List of all chunk allocations */ sqlite3 *db; /* The database connection */ struct RowSetEntry *pEntry; /* List of entries using pRight */ struct RowSetEntry *pLast; /* Last entry on the pEntry list */ struct RowSetEntry *pFresh; /* Source of new entry objects */ struct RowSetEntry *pForest; /* List of binary trees of entries */ u16 nFresh; /* Number of objects on pFresh */ u16 rsFlags; /* Various flags */ int iBatch; /* Current insert batch */ }; /* ** Allowed values for RowSet.rsFlags */ #define ROWSET_SORTED 0x01 /* True if RowSet.pEntry is sorted */ #define ROWSET_NEXT 0x02 /* True if sqlite3RowSetNext() has been called */ /* ** Turn bulk memory into a RowSet object. N bytes of memory ** are available at pSpace. The db pointer is used as a memory context ** for any subsequent allocations that need to occur. ** Return a pointer to the new RowSet object. ** ** It must be the case that N is sufficient to make a Rowset. If not ** an assertion fault occurs. ** ** If N is larger than the minimum, use the surplus as an initial ** allocation of entries available to be filled. */ SQLITE_PRIVATE RowSet *sqlite3RowSetInit(sqlite3 *db, void *pSpace, unsigned int N){ RowSet *p; assert( N >= ROUND8(sizeof(*p)) ); p = pSpace; p->pChunk = 0; p->db = db; p->pEntry = 0; p->pLast = 0; p->pForest = 0; p->pFresh = (struct RowSetEntry*)(ROUND8(sizeof(*p)) + (char*)p); p->nFresh = (u16)((N - ROUND8(sizeof(*p)))/sizeof(struct RowSetEntry)); p->rsFlags = ROWSET_SORTED; p->iBatch = 0; return p; } /* ** Deallocate all chunks from a RowSet. This frees all memory that ** the RowSet has allocated over its lifetime. This routine is ** the destructor for the RowSet. */ SQLITE_PRIVATE void sqlite3RowSetClear(RowSet *p){ struct RowSetChunk *pChunk, *pNextChunk; for(pChunk=p->pChunk; pChunk; pChunk = pNextChunk){ pNextChunk = pChunk->pNextChunk; sqlite3DbFree(p->db, pChunk); } p->pChunk = 0; p->nFresh = 0; p->pEntry = 0; p->pLast = 0; p->pForest = 0; p->rsFlags = ROWSET_SORTED; } /* ** Allocate a new RowSetEntry object that is associated with the ** given RowSet. Return a pointer to the new and completely uninitialized ** objected. ** ** In an OOM situation, the RowSet.db->mallocFailed flag is set and this ** routine returns NULL. */ static struct RowSetEntry *rowSetEntryAlloc(RowSet *p){ assert( p!=0 ); if( p->nFresh==0 ){ /*OPTIMIZATION-IF-FALSE*/ /* We could allocate a fresh RowSetEntry each time one is needed, but it ** is more efficient to pull a preallocated entry from the pool */ struct RowSetChunk *pNew; pNew = sqlite3DbMallocRawNN(p->db, sizeof(*pNew)); if( pNew==0 ){ return 0; } pNew->pNextChunk = p->pChunk; p->pChunk = pNew; p->pFresh = pNew->aEntry; p->nFresh = ROWSET_ENTRY_PER_CHUNK; } p->nFresh--; return p->pFresh++; } /* ** Insert a new value into a RowSet. ** ** The mallocFailed flag of the database connection is set if a ** memory allocation fails. */ SQLITE_PRIVATE void sqlite3RowSetInsert(RowSet *p, i64 rowid){ struct RowSetEntry *pEntry; /* The new entry */ struct RowSetEntry *pLast; /* The last prior entry */ /* This routine is never called after sqlite3RowSetNext() */ assert( p!=0 && (p->rsFlags & ROWSET_NEXT)==0 ); pEntry = rowSetEntryAlloc(p); if( pEntry==0 ) return; pEntry->v = rowid; pEntry->pRight = 0; pLast = p->pLast; if( pLast ){ if( rowid<=pLast->v ){ /*OPTIMIZATION-IF-FALSE*/ /* Avoid unnecessary sorts by preserving the ROWSET_SORTED flags ** where possible */ p->rsFlags &= ~ROWSET_SORTED; } pLast->pRight = pEntry; }else{ p->pEntry = pEntry; } p->pLast = pEntry; } /* ** Merge two lists of RowSetEntry objects. Remove duplicates. ** ** The input lists are connected via pRight pointers and are ** assumed to each already be in sorted order. */ static struct RowSetEntry *rowSetEntryMerge( struct RowSetEntry *pA, /* First sorted list to be merged */ struct RowSetEntry *pB /* Second sorted list to be merged */ ){ struct RowSetEntry head; struct RowSetEntry *pTail; pTail = &head; assert( pA!=0 && pB!=0 ); for(;;){ assert( pA->pRight==0 || pA->v<=pA->pRight->v ); assert( pB->pRight==0 || pB->v<=pB->pRight->v ); if( pA->v<=pB->v ){ if( pA->vv ) pTail = pTail->pRight = pA; pA = pA->pRight; if( pA==0 ){ pTail->pRight = pB; break; } }else{ pTail = pTail->pRight = pB; pB = pB->pRight; if( pB==0 ){ pTail->pRight = pA; break; } } } return head.pRight; } /* ** Sort all elements on the list of RowSetEntry objects into order of ** increasing v. */ static struct RowSetEntry *rowSetEntrySort(struct RowSetEntry *pIn){ unsigned int i; struct RowSetEntry *pNext, *aBucket[40]; memset(aBucket, 0, sizeof(aBucket)); while( pIn ){ pNext = pIn->pRight; pIn->pRight = 0; for(i=0; aBucket[i]; i++){ pIn = rowSetEntryMerge(aBucket[i], pIn); aBucket[i] = 0; } aBucket[i] = pIn; pIn = pNext; } pIn = aBucket[0]; for(i=1; ipLeft ){ struct RowSetEntry *p; rowSetTreeToList(pIn->pLeft, ppFirst, &p); p->pRight = pIn; }else{ *ppFirst = pIn; } if( pIn->pRight ){ rowSetTreeToList(pIn->pRight, &pIn->pRight, ppLast); }else{ *ppLast = pIn; } assert( (*ppLast)->pRight==0 ); } /* ** Convert a sorted list of elements (connected by pRight) into a binary ** tree with depth of iDepth. A depth of 1 means the tree contains a single ** node taken from the head of *ppList. A depth of 2 means a tree with ** three nodes. And so forth. ** ** Use as many entries from the input list as required and update the ** *ppList to point to the unused elements of the list. If the input ** list contains too few elements, then construct an incomplete tree ** and leave *ppList set to NULL. ** ** Return a pointer to the root of the constructed binary tree. */ static struct RowSetEntry *rowSetNDeepTree( struct RowSetEntry **ppList, int iDepth ){ struct RowSetEntry *p; /* Root of the new tree */ struct RowSetEntry *pLeft; /* Left subtree */ if( *ppList==0 ){ /*OPTIMIZATION-IF-TRUE*/ /* Prevent unnecessary deep recursion when we run out of entries */ return 0; } if( iDepth>1 ){ /*OPTIMIZATION-IF-TRUE*/ /* This branch causes a *balanced* tree to be generated. A valid tree ** is still generated without this branch, but the tree is wildly ** unbalanced and inefficient. */ pLeft = rowSetNDeepTree(ppList, iDepth-1); p = *ppList; if( p==0 ){ /*OPTIMIZATION-IF-FALSE*/ /* It is safe to always return here, but the resulting tree ** would be unbalanced */ return pLeft; } p->pLeft = pLeft; *ppList = p->pRight; p->pRight = rowSetNDeepTree(ppList, iDepth-1); }else{ p = *ppList; *ppList = p->pRight; p->pLeft = p->pRight = 0; } return p; } /* ** Convert a sorted list of elements into a binary tree. Make the tree ** as deep as it needs to be in order to contain the entire list. */ static struct RowSetEntry *rowSetListToTree(struct RowSetEntry *pList){ int iDepth; /* Depth of the tree so far */ struct RowSetEntry *p; /* Current tree root */ struct RowSetEntry *pLeft; /* Left subtree */ assert( pList!=0 ); p = pList; pList = p->pRight; p->pLeft = p->pRight = 0; for(iDepth=1; pList; iDepth++){ pLeft = p; p = pList; pList = p->pRight; p->pLeft = pLeft; p->pRight = rowSetNDeepTree(&pList, iDepth); } return p; } /* ** Extract the smallest element from the RowSet. ** Write the element into *pRowid. Return 1 on success. Return ** 0 if the RowSet is already empty. ** ** After this routine has been called, the sqlite3RowSetInsert() ** routine may not be called again. ** ** This routine may not be called after sqlite3RowSetTest() has ** been used. Older versions of RowSet allowed that, but as the ** capability was not used by the code generator, it was removed ** for code economy. */ SQLITE_PRIVATE int sqlite3RowSetNext(RowSet *p, i64 *pRowid){ assert( p!=0 ); assert( p->pForest==0 ); /* Cannot be used with sqlite3RowSetText() */ /* Merge the forest into a single sorted list on first call */ if( (p->rsFlags & ROWSET_NEXT)==0 ){ /*OPTIMIZATION-IF-FALSE*/ if( (p->rsFlags & ROWSET_SORTED)==0 ){ /*OPTIMIZATION-IF-FALSE*/ p->pEntry = rowSetEntrySort(p->pEntry); } p->rsFlags |= ROWSET_SORTED|ROWSET_NEXT; } /* Return the next entry on the list */ if( p->pEntry ){ *pRowid = p->pEntry->v; p->pEntry = p->pEntry->pRight; if( p->pEntry==0 ){ /*OPTIMIZATION-IF-TRUE*/ /* Free memory immediately, rather than waiting on sqlite3_finalize() */ sqlite3RowSetClear(p); } return 1; }else{ return 0; } } /* ** Check to see if element iRowid was inserted into the rowset as ** part of any insert batch prior to iBatch. Return 1 or 0. ** ** If this is the first test of a new batch and if there exist entries ** on pRowSet->pEntry, then sort those entries into the forest at ** pRowSet->pForest so that they can be tested. */ SQLITE_PRIVATE int sqlite3RowSetTest(RowSet *pRowSet, int iBatch, sqlite3_int64 iRowid){ struct RowSetEntry *p, *pTree; /* This routine is never called after sqlite3RowSetNext() */ assert( pRowSet!=0 && (pRowSet->rsFlags & ROWSET_NEXT)==0 ); /* Sort entries into the forest on the first test of a new batch. ** To save unnecessary work, only do this when the batch number changes. */ if( iBatch!=pRowSet->iBatch ){ /*OPTIMIZATION-IF-FALSE*/ p = pRowSet->pEntry; if( p ){ struct RowSetEntry **ppPrevTree = &pRowSet->pForest; if( (pRowSet->rsFlags & ROWSET_SORTED)==0 ){ /*OPTIMIZATION-IF-FALSE*/ /* Only sort the current set of entiries if they need it */ p = rowSetEntrySort(p); } for(pTree = pRowSet->pForest; pTree; pTree=pTree->pRight){ ppPrevTree = &pTree->pRight; if( pTree->pLeft==0 ){ pTree->pLeft = rowSetListToTree(p); break; }else{ struct RowSetEntry *pAux, *pTail; rowSetTreeToList(pTree->pLeft, &pAux, &pTail); pTree->pLeft = 0; p = rowSetEntryMerge(pAux, p); } } if( pTree==0 ){ *ppPrevTree = pTree = rowSetEntryAlloc(pRowSet); if( pTree ){ pTree->v = 0; pTree->pRight = 0; pTree->pLeft = rowSetListToTree(p); } } pRowSet->pEntry = 0; pRowSet->pLast = 0; pRowSet->rsFlags |= ROWSET_SORTED; } pRowSet->iBatch = iBatch; } /* Test to see if the iRowid value appears anywhere in the forest. ** Return 1 if it does and 0 if not. */ for(pTree = pRowSet->pForest; pTree; pTree=pTree->pRight){ p = pTree->pLeft; while( p ){ if( p->vpRight; }else if( p->v>iRowid ){ p = p->pLeft; }else{ return 1; } } } return 0; } /************** End of rowset.c **********************************************/ /************** Begin file pager.c *******************************************/ /* ** 2001 September 15 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ************************************************************************* ** This is the implementation of the page cache subsystem or "pager". ** ** The pager is used to access a database disk file. It implements ** atomic commit and rollback through the use of a journal file that ** is separate from the database file. The pager also implements file ** locking to prevent two processes from writing the same database ** file simultaneously, or one process from reading the database while ** another is writing. */ #ifndef SQLITE_OMIT_DISKIO /* #include "sqliteInt.h" */ /************** Include wal.h in the middle of pager.c ***********************/ /************** Begin file wal.h *********************************************/ /* ** 2010 February 1 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ************************************************************************* ** This header file defines the interface to the write-ahead logging ** system. Refer to the comments below and the header comment attached to ** the implementation of each function in log.c for further details. */ #ifndef SQLITE_WAL_H #define SQLITE_WAL_H /* #include "sqliteInt.h" */ /* Additional values that can be added to the sync_flags argument of ** sqlite3WalFrames(): */ #define WAL_SYNC_TRANSACTIONS 0x20 /* Sync at the end of each transaction */ #define SQLITE_SYNC_MASK 0x13 /* Mask off the SQLITE_SYNC_* values */ #ifdef SQLITE_OMIT_WAL # define sqlite3WalOpen(x,y,z) 0 # define sqlite3WalLimit(x,y) # define sqlite3WalClose(w,x,y,z) 0 # define sqlite3WalBeginReadTransaction(y,z) 0 # define sqlite3WalEndReadTransaction(z) # define sqlite3WalDbsize(y) 0 # define sqlite3WalBeginWriteTransaction(y) 0 # define sqlite3WalEndWriteTransaction(x) 0 # define sqlite3WalUndo(x,y,z) 0 # define sqlite3WalSavepoint(y,z) # define sqlite3WalSavepointUndo(y,z) 0 # define sqlite3WalFrames(u,v,w,x,y,z) 0 # define sqlite3WalCheckpoint(r,s,t,u,v,w,x,y,z) 0 # define sqlite3WalCallback(z) 0 # define sqlite3WalExclusiveMode(y,z) 0 # define sqlite3WalHeapMemory(z) 0 # define sqlite3WalFramesize(z) 0 # define sqlite3WalFindFrame(x,y,z) 0 # define sqlite3WalFile(x) 0 #else #define WAL_SAVEPOINT_NDATA 4 /* Connection to a write-ahead log (WAL) file. ** There is one object of this type for each pager. */ typedef struct Wal Wal; /* Open and close a connection to a write-ahead log. */ SQLITE_PRIVATE int sqlite3WalOpen(sqlite3_vfs*, sqlite3_file*, const char *, int, i64, Wal**); SQLITE_PRIVATE int sqlite3WalClose(Wal *pWal, int sync_flags, int, u8 *); /* Set the limiting size of a WAL file. */ SQLITE_PRIVATE void sqlite3WalLimit(Wal*, i64); /* Used by readers to open (lock) and close (unlock) a snapshot. A ** snapshot is like a read-transaction. It is the state of the database ** at an instant in time. sqlite3WalOpenSnapshot gets a read lock and ** preserves the current state even if the other threads or processes ** write to or checkpoint the WAL. sqlite3WalCloseSnapshot() closes the ** transaction and releases the lock. */ SQLITE_PRIVATE int sqlite3WalBeginReadTransaction(Wal *pWal, int *); SQLITE_PRIVATE void sqlite3WalEndReadTransaction(Wal *pWal); /* Read a page from the write-ahead log, if it is present. */ SQLITE_PRIVATE int sqlite3WalFindFrame(Wal *, Pgno, u32 *); SQLITE_PRIVATE int sqlite3WalReadFrame(Wal *, u32, int, u8 *); /* If the WAL is not empty, return the size of the database. */ SQLITE_PRIVATE Pgno sqlite3WalDbsize(Wal *pWal); /* Obtain or release the WRITER lock. */ SQLITE_PRIVATE int sqlite3WalBeginWriteTransaction(Wal *pWal); SQLITE_PRIVATE int sqlite3WalEndWriteTransaction(Wal *pWal); /* Undo any frames written (but not committed) to the log */ SQLITE_PRIVATE int sqlite3WalUndo(Wal *pWal, int (*xUndo)(void *, Pgno), void *pUndoCtx); /* Return an integer that records the current (uncommitted) write ** position in the WAL */ SQLITE_PRIVATE void sqlite3WalSavepoint(Wal *pWal, u32 *aWalData); /* Move the write position of the WAL back to iFrame. Called in ** response to a ROLLBACK TO command. */ SQLITE_PRIVATE int sqlite3WalSavepointUndo(Wal *pWal, u32 *aWalData); /* Write a frame or frames to the log. */ SQLITE_PRIVATE int sqlite3WalFrames(Wal *pWal, int, PgHdr *, Pgno, int, int); /* Copy pages from the log to the database file */ SQLITE_PRIVATE int sqlite3WalCheckpoint( Wal *pWal, /* Write-ahead log connection */ int eMode, /* One of PASSIVE, FULL and RESTART */ int (*xBusy)(void*), /* Function to call when busy */ void *pBusyArg, /* Context argument for xBusyHandler */ int sync_flags, /* Flags to sync db file with (or 0) */ int nBuf, /* Size of buffer nBuf */ u8 *zBuf, /* Temporary buffer to use */ int *pnLog, /* OUT: Number of frames in WAL */ int *pnCkpt /* OUT: Number of backfilled frames in WAL */ ); /* Return the value to pass to a sqlite3_wal_hook callback, the ** number of frames in the WAL at the point of the last commit since ** sqlite3WalCallback() was called. If no commits have occurred since ** the last call, then return 0. */ SQLITE_PRIVATE int sqlite3WalCallback(Wal *pWal); /* Tell the wal layer that an EXCLUSIVE lock has been obtained (or released) ** by the pager layer on the database file. */ SQLITE_PRIVATE int sqlite3WalExclusiveMode(Wal *pWal, int op); /* Return true if the argument is non-NULL and the WAL module is using ** heap-memory for the wal-index. Otherwise, if the argument is NULL or the ** WAL module is using shared-memory, return false. */ SQLITE_PRIVATE int sqlite3WalHeapMemory(Wal *pWal); #ifdef SQLITE_ENABLE_SNAPSHOT SQLITE_PRIVATE int sqlite3WalSnapshotGet(Wal *pWal, sqlite3_snapshot **ppSnapshot); SQLITE_PRIVATE void sqlite3WalSnapshotOpen(Wal *pWal, sqlite3_snapshot *pSnapshot); #endif #ifdef SQLITE_ENABLE_ZIPVFS /* If the WAL file is not empty, return the number of bytes of content ** stored in each frame (i.e. the db page-size when the WAL was created). */ SQLITE_PRIVATE int sqlite3WalFramesize(Wal *pWal); #endif /* Return the sqlite3_file object for the WAL file */ SQLITE_PRIVATE sqlite3_file *sqlite3WalFile(Wal *pWal); #endif /* ifndef SQLITE_OMIT_WAL */ #endif /* SQLITE_WAL_H */ /************** End of wal.h *************************************************/ /************** Continuing where we left off in pager.c **********************/ /******************* NOTES ON THE DESIGN OF THE PAGER ************************ ** ** This comment block describes invariants that hold when using a rollback ** journal. These invariants do not apply for journal_mode=WAL, ** journal_mode=MEMORY, or journal_mode=OFF. ** ** Within this comment block, a page is deemed to have been synced ** automatically as soon as it is written when PRAGMA synchronous=OFF. ** Otherwise, the page is not synced until the xSync method of the VFS ** is called successfully on the file containing the page. ** ** Definition: A page of the database file is said to be "overwriteable" if ** one or more of the following are true about the page: ** ** (a) The original content of the page as it was at the beginning of ** the transaction has been written into the rollback journal and ** synced. ** ** (b) The page was a freelist leaf page at the start of the transaction. ** ** (c) The page number is greater than the largest page that existed in ** the database file at the start of the transaction. ** ** (1) A page of the database file is never overwritten unless one of the ** following are true: ** ** (a) The page and all other pages on the same sector are overwriteable. ** ** (b) The atomic page write optimization is enabled, and the entire ** transaction other than the update of the transaction sequence ** number consists of a single page change. ** ** (2) The content of a page written into the rollback journal exactly matches ** both the content in the database when the rollback journal was written ** and the content in the database at the beginning of the current ** transaction. ** ** (3) Writes to the database file are an integer multiple of the page size ** in length and are aligned on a page boundary. ** ** (4) Reads from the database file are either aligned on a page boundary and ** an integer multiple of the page size in length or are taken from the ** first 100 bytes of the database file. ** ** (5) All writes to the database file are synced prior to the rollback journal ** being deleted, truncated, or zeroed. ** ** (6) If a master journal file is used, then all writes to the database file ** are synced prior to the master journal being deleted. ** ** Definition: Two databases (or the same database at two points it time) ** are said to be "logically equivalent" if they give the same answer to ** all queries. Note in particular the content of freelist leaf ** pages can be changed arbitrarily without affecting the logical equivalence ** of the database. ** ** (7) At any time, if any subset, including the empty set and the total set, ** of the unsynced changes to a rollback journal are removed and the ** journal is rolled back, the resulting database file will be logically ** equivalent to the database file at the beginning of the transaction. ** ** (8) When a transaction is rolled back, the xTruncate method of the VFS ** is called to restore the database file to the same size it was at ** the beginning of the transaction. (In some VFSes, the xTruncate ** method is a no-op, but that does not change the fact the SQLite will ** invoke it.) ** ** (9) Whenever the database file is modified, at least one bit in the range ** of bytes from 24 through 39 inclusive will be changed prior to releasing ** the EXCLUSIVE lock, thus signaling other connections on the same ** database to flush their caches. ** ** (10) The pattern of bits in bytes 24 through 39 shall not repeat in less ** than one billion transactions. ** ** (11) A database file is well-formed at the beginning and at the conclusion ** of every transaction. ** ** (12) An EXCLUSIVE lock is held on the database file when writing to ** the database file. ** ** (13) A SHARED lock is held on the database file while reading any ** content out of the database file. ** ******************************************************************************/ /* ** Macros for troubleshooting. Normally turned off */ #if 0 int sqlite3PagerTrace=1; /* True to enable tracing */ #define sqlite3DebugPrintf printf #define PAGERTRACE(X) if( sqlite3PagerTrace ){ sqlite3DebugPrintf X; } #else #define PAGERTRACE(X) #endif /* ** The following two macros are used within the PAGERTRACE() macros above ** to print out file-descriptors. ** ** PAGERID() takes a pointer to a Pager struct as its argument. The ** associated file-descriptor is returned. FILEHANDLEID() takes an sqlite3_file ** struct as its argument. */ #define PAGERID(p) ((int)(p->fd)) #define FILEHANDLEID(fd) ((int)fd) /* ** The Pager.eState variable stores the current 'state' of a pager. A ** pager may be in any one of the seven states shown in the following ** state diagram. ** ** OPEN <------+------+ ** | | | ** V | | ** +---------> READER-------+ | ** | | | ** | V | ** |<-------WRITER_LOCKED------> ERROR ** | | ^ ** | V | ** |<------WRITER_CACHEMOD-------->| ** | | | ** | V | ** |<-------WRITER_DBMOD---------->| ** | | | ** | V | ** +<------WRITER_FINISHED-------->+ ** ** ** List of state transitions and the C [function] that performs each: ** ** OPEN -> READER [sqlite3PagerSharedLock] ** READER -> OPEN [pager_unlock] ** ** READER -> WRITER_LOCKED [sqlite3PagerBegin] ** WRITER_LOCKED -> WRITER_CACHEMOD [pager_open_journal] ** WRITER_CACHEMOD -> WRITER_DBMOD [syncJournal] ** WRITER_DBMOD -> WRITER_FINISHED [sqlite3PagerCommitPhaseOne] ** WRITER_*** -> READER [pager_end_transaction] ** ** WRITER_*** -> ERROR [pager_error] ** ERROR -> OPEN [pager_unlock] ** ** ** OPEN: ** ** The pager starts up in this state. Nothing is guaranteed in this ** state - the file may or may not be locked and the database size is ** unknown. The database may not be read or written. ** ** * No read or write transaction is active. ** * Any lock, or no lock at all, may be held on the database file. ** * The dbSize, dbOrigSize and dbFileSize variables may not be trusted. ** ** READER: ** ** In this state all the requirements for reading the database in ** rollback (non-WAL) mode are met. Unless the pager is (or recently ** was) in exclusive-locking mode, a user-level read transaction is ** open. The database size is known in this state. ** ** A connection running with locking_mode=normal enters this state when ** it opens a read-transaction on the database and returns to state ** OPEN after the read-transaction is completed. However a connection ** running in locking_mode=exclusive (including temp databases) remains in ** this state even after the read-transaction is closed. The only way ** a locking_mode=exclusive connection can transition from READER to OPEN ** is via the ERROR state (see below). ** ** * A read transaction may be active (but a write-transaction cannot). ** * A SHARED or greater lock is held on the database file. ** * The dbSize variable may be trusted (even if a user-level read ** transaction is not active). The dbOrigSize and dbFileSize variables ** may not be trusted at this point. ** * If the database is a WAL database, then the WAL connection is open. ** * Even if a read-transaction is not open, it is guaranteed that ** there is no hot-journal in the file-system. ** ** WRITER_LOCKED: ** ** The pager moves to this state from READER when a write-transaction ** is first opened on the database. In WRITER_LOCKED state, all locks ** required to start a write-transaction are held, but no actual ** modifications to the cache or database have taken place. ** ** In rollback mode, a RESERVED or (if the transaction was opened with ** BEGIN EXCLUSIVE) EXCLUSIVE lock is obtained on the database file when ** moving to this state, but the journal file is not written to or opened ** to in this state. If the transaction is committed or rolled back while ** in WRITER_LOCKED state, all that is required is to unlock the database ** file. ** ** IN WAL mode, WalBeginWriteTransaction() is called to lock the log file. ** If the connection is running with locking_mode=exclusive, an attempt ** is made to obtain an EXCLUSIVE lock on the database file. ** ** * A write transaction is active. ** * If the connection is open in rollback-mode, a RESERVED or greater ** lock is held on the database file. ** * If the connection is open in WAL-mode, a WAL write transaction ** is open (i.e. sqlite3WalBeginWriteTransaction() has been successfully ** called). ** * The dbSize, dbOrigSize and dbFileSize variables are all valid. ** * The contents of the pager cache have not been modified. ** * The journal file may or may not be open. ** * Nothing (not even the first header) has been written to the journal. ** ** WRITER_CACHEMOD: ** ** A pager moves from WRITER_LOCKED state to this state when a page is ** first modified by the upper layer. In rollback mode the journal file ** is opened (if it is not already open) and a header written to the ** start of it. The database file on disk has not been modified. ** ** * A write transaction is active. ** * A RESERVED or greater lock is held on the database file. ** * The journal file is open and the first header has been written ** to it, but the header has not been synced to disk. ** * The contents of the page cache have been modified. ** ** WRITER_DBMOD: ** ** The pager transitions from WRITER_CACHEMOD into WRITER_DBMOD state ** when it modifies the contents of the database file. WAL connections ** never enter this state (since they do not modify the database file, ** just the log file). ** ** * A write transaction is active. ** * An EXCLUSIVE or greater lock is held on the database file. ** * The journal file is open and the first header has been written ** and synced to disk. ** * The contents of the page cache have been modified (and possibly ** written to disk). ** ** WRITER_FINISHED: ** ** It is not possible for a WAL connection to enter this state. ** ** A rollback-mode pager changes to WRITER_FINISHED state from WRITER_DBMOD ** state after the entire transaction has been successfully written into the ** database file. In this state the transaction may be committed simply ** by finalizing the journal file. Once in WRITER_FINISHED state, it is ** not possible to modify the database further. At this point, the upper ** layer must either commit or rollback the transaction. ** ** * A write transaction is active. ** * An EXCLUSIVE or greater lock is held on the database file. ** * All writing and syncing of journal and database data has finished. ** If no error occurred, all that remains is to finalize the journal to ** commit the transaction. If an error did occur, the caller will need ** to rollback the transaction. ** ** ERROR: ** ** The ERROR state is entered when an IO or disk-full error (including ** SQLITE_IOERR_NOMEM) occurs at a point in the code that makes it ** difficult to be sure that the in-memory pager state (cache contents, ** db size etc.) are consistent with the contents of the file-system. ** ** Temporary pager files may enter the ERROR state, but in-memory pagers ** cannot. ** ** For example, if an IO error occurs while performing a rollback, ** the contents of the page-cache may be left in an inconsistent state. ** At this point it would be dangerous to change back to READER state ** (as usually happens after a rollback). Any subsequent readers might ** report database corruption (due to the inconsistent cache), and if ** they upgrade to writers, they may inadvertently corrupt the database ** file. To avoid this hazard, the pager switches into the ERROR state ** instead of READER following such an error. ** ** Once it has entered the ERROR state, any attempt to use the pager ** to read or write data returns an error. Eventually, once all ** outstanding transactions have been abandoned, the pager is able to ** transition back to OPEN state, discarding the contents of the ** page-cache and any other in-memory state at the same time. Everything ** is reloaded from disk (and, if necessary, hot-journal rollback peformed) ** when a read-transaction is next opened on the pager (transitioning ** the pager into READER state). At that point the system has recovered ** from the error. ** ** Specifically, the pager jumps into the ERROR state if: ** ** 1. An error occurs while attempting a rollback. This happens in ** function sqlite3PagerRollback(). ** ** 2. An error occurs while attempting to finalize a journal file ** following a commit in function sqlite3PagerCommitPhaseTwo(). ** ** 3. An error occurs while attempting to write to the journal or ** database file in function pagerStress() in order to free up ** memory. ** ** In other cases, the error is returned to the b-tree layer. The b-tree ** layer then attempts a rollback operation. If the error condition ** persists, the pager enters the ERROR state via condition (1) above. ** ** Condition (3) is necessary because it can be triggered by a read-only ** statement executed within a transaction. In this case, if the error ** code were simply returned to the user, the b-tree layer would not ** automatically attempt a rollback, as it assumes that an error in a ** read-only statement cannot leave the pager in an internally inconsistent ** state. ** ** * The Pager.errCode variable is set to something other than SQLITE_OK. ** * There are one or more outstanding references to pages (after the ** last reference is dropped the pager should move back to OPEN state). ** * The pager is not an in-memory pager. ** ** ** Notes: ** ** * A pager is never in WRITER_DBMOD or WRITER_FINISHED state if the ** connection is open in WAL mode. A WAL connection is always in one ** of the first four states. ** ** * Normally, a connection open in exclusive mode is never in PAGER_OPEN ** state. There are two exceptions: immediately after exclusive-mode has ** been turned on (and before any read or write transactions are ** executed), and when the pager is leaving the "error state". ** ** * See also: assert_pager_state(). */ #define PAGER_OPEN 0 #define PAGER_READER 1 #define PAGER_WRITER_LOCKED 2 #define PAGER_WRITER_CACHEMOD 3 #define PAGER_WRITER_DBMOD 4 #define PAGER_WRITER_FINISHED 5 #define PAGER_ERROR 6 /* ** The Pager.eLock variable is almost always set to one of the ** following locking-states, according to the lock currently held on ** the database file: NO_LOCK, SHARED_LOCK, RESERVED_LOCK or EXCLUSIVE_LOCK. ** This variable is kept up to date as locks are taken and released by ** the pagerLockDb() and pagerUnlockDb() wrappers. ** ** If the VFS xLock() or xUnlock() returns an error other than SQLITE_BUSY ** (i.e. one of the SQLITE_IOERR subtypes), it is not clear whether or not ** the operation was successful. In these circumstances pagerLockDb() and ** pagerUnlockDb() take a conservative approach - eLock is always updated ** when unlocking the file, and only updated when locking the file if the ** VFS call is successful. This way, the Pager.eLock variable may be set ** to a less exclusive (lower) value than the lock that is actually held ** at the system level, but it is never set to a more exclusive value. ** ** This is usually safe. If an xUnlock fails or appears to fail, there may ** be a few redundant xLock() calls or a lock may be held for longer than ** required, but nothing really goes wrong. ** ** The exception is when the database file is unlocked as the pager moves ** from ERROR to OPEN state. At this point there may be a hot-journal file ** in the file-system that needs to be rolled back (as part of an OPEN->SHARED ** transition, by the same pager or any other). If the call to xUnlock() ** fails at this point and the pager is left holding an EXCLUSIVE lock, this ** can confuse the call to xCheckReservedLock() call made later as part ** of hot-journal detection. ** ** xCheckReservedLock() is defined as returning true "if there is a RESERVED ** lock held by this process or any others". So xCheckReservedLock may ** return true because the caller itself is holding an EXCLUSIVE lock (but ** doesn't know it because of a previous error in xUnlock). If this happens ** a hot-journal may be mistaken for a journal being created by an active ** transaction in another process, causing SQLite to read from the database ** without rolling it back. ** ** To work around this, if a call to xUnlock() fails when unlocking the ** database in the ERROR state, Pager.eLock is set to UNKNOWN_LOCK. It ** is only changed back to a real locking state after a successful call ** to xLock(EXCLUSIVE). Also, the code to do the OPEN->SHARED state transition ** omits the check for a hot-journal if Pager.eLock is set to UNKNOWN_LOCK ** lock. Instead, it assumes a hot-journal exists and obtains an EXCLUSIVE ** lock on the database file before attempting to roll it back. See function ** PagerSharedLock() for more detail. ** ** Pager.eLock may only be set to UNKNOWN_LOCK when the pager is in ** PAGER_OPEN state. */ #define UNKNOWN_LOCK (EXCLUSIVE_LOCK+1) /* ** A macro used for invoking the codec if there is one */ #ifdef SQLITE_HAS_CODEC # define CODEC1(P,D,N,X,E) \ if( P->xCodec && P->xCodec(P->pCodec,D,N,X)==0 ){ E; } # define CODEC2(P,D,N,X,E,O) \ if( P->xCodec==0 ){ O=(char*)D; }else \ if( (O=(char*)(P->xCodec(P->pCodec,D,N,X)))==0 ){ E; } #else # define CODEC1(P,D,N,X,E) /* NO-OP */ # define CODEC2(P,D,N,X,E,O) O=(char*)D #endif /* ** The maximum allowed sector size. 64KiB. If the xSectorsize() method ** returns a value larger than this, then MAX_SECTOR_SIZE is used instead. ** This could conceivably cause corruption following a power failure on ** such a system. This is currently an undocumented limit. */ #define MAX_SECTOR_SIZE 0x10000 /* ** An instance of the following structure is allocated for each active ** savepoint and statement transaction in the system. All such structures ** are stored in the Pager.aSavepoint[] array, which is allocated and ** resized using sqlite3Realloc(). ** ** When a savepoint is created, the PagerSavepoint.iHdrOffset field is ** set to 0. If a journal-header is written into the main journal while ** the savepoint is active, then iHdrOffset is set to the byte offset ** immediately following the last journal record written into the main ** journal before the journal-header. This is required during savepoint ** rollback (see pagerPlaybackSavepoint()). */ typedef struct PagerSavepoint PagerSavepoint; struct PagerSavepoint { i64 iOffset; /* Starting offset in main journal */ i64 iHdrOffset; /* See above */ Bitvec *pInSavepoint; /* Set of pages in this savepoint */ Pgno nOrig; /* Original number of pages in file */ Pgno iSubRec; /* Index of first record in sub-journal */ #ifndef SQLITE_OMIT_WAL u32 aWalData[WAL_SAVEPOINT_NDATA]; /* WAL savepoint context */ #endif }; /* ** Bits of the Pager.doNotSpill flag. See further description below. */ #define SPILLFLAG_OFF 0x01 /* Never spill cache. Set via pragma */ #define SPILLFLAG_ROLLBACK 0x02 /* Current rolling back, so do not spill */ #define SPILLFLAG_NOSYNC 0x04 /* Spill is ok, but do not sync */ /* ** An open page cache is an instance of struct Pager. A description of ** some of the more important member variables follows: ** ** eState ** ** The current 'state' of the pager object. See the comment and state ** diagram above for a description of the pager state. ** ** eLock ** ** For a real on-disk database, the current lock held on the database file - ** NO_LOCK, SHARED_LOCK, RESERVED_LOCK or EXCLUSIVE_LOCK. ** ** For a temporary or in-memory database (neither of which require any ** locks), this variable is always set to EXCLUSIVE_LOCK. Since such ** databases always have Pager.exclusiveMode==1, this tricks the pager ** logic into thinking that it already has all the locks it will ever ** need (and no reason to release them). ** ** In some (obscure) circumstances, this variable may also be set to ** UNKNOWN_LOCK. See the comment above the #define of UNKNOWN_LOCK for ** details. ** ** changeCountDone ** ** This boolean variable is used to make sure that the change-counter ** (the 4-byte header field at byte offset 24 of the database file) is ** not updated more often than necessary. ** ** It is set to true when the change-counter field is updated, which ** can only happen if an exclusive lock is held on the database file. ** It is cleared (set to false) whenever an exclusive lock is ** relinquished on the database file. Each time a transaction is committed, ** The changeCountDone flag is inspected. If it is true, the work of ** updating the change-counter is omitted for the current transaction. ** ** This mechanism means that when running in exclusive mode, a connection ** need only update the change-counter once, for the first transaction ** committed. ** ** setMaster ** ** When PagerCommitPhaseOne() is called to commit a transaction, it may ** (or may not) specify a master-journal name to be written into the ** journal file before it is synced to disk. ** ** Whether or not a journal file contains a master-journal pointer affects ** the way in which the journal file is finalized after the transaction is ** committed or rolled back when running in "journal_mode=PERSIST" mode. ** If a journal file does not contain a master-journal pointer, it is ** finalized by overwriting the first journal header with zeroes. If ** it does contain a master-journal pointer the journal file is finalized ** by truncating it to zero bytes, just as if the connection were ** running in "journal_mode=truncate" mode. ** ** Journal files that contain master journal pointers cannot be finalized ** simply by overwriting the first journal-header with zeroes, as the ** master journal pointer could interfere with hot-journal rollback of any ** subsequently interrupted transaction that reuses the journal file. ** ** The flag is cleared as soon as the journal file is finalized (either ** by PagerCommitPhaseTwo or PagerRollback). If an IO error prevents the ** journal file from being successfully finalized, the setMaster flag ** is cleared anyway (and the pager will move to ERROR state). ** ** doNotSpill ** ** This variables control the behavior of cache-spills (calls made by ** the pcache module to the pagerStress() routine to write cached data ** to the file-system in order to free up memory). ** ** When bits SPILLFLAG_OFF or SPILLFLAG_ROLLBACK of doNotSpill are set, ** writing to the database from pagerStress() is disabled altogether. ** The SPILLFLAG_ROLLBACK case is done in a very obscure case that ** comes up during savepoint rollback that requires the pcache module ** to allocate a new page to prevent the journal file from being written ** while it is being traversed by code in pager_playback(). The SPILLFLAG_OFF ** case is a user preference. ** ** If the SPILLFLAG_NOSYNC bit is set, writing to the database from ** pagerStress() is permitted, but syncing the journal file is not. ** This flag is set by sqlite3PagerWrite() when the file-system sector-size ** is larger than the database page-size in order to prevent a journal sync ** from happening in between the journalling of two pages on the same sector. ** ** subjInMemory ** ** This is a boolean variable. If true, then any required sub-journal ** is opened as an in-memory journal file. If false, then in-memory ** sub-journals are only used for in-memory pager files. ** ** This variable is updated by the upper layer each time a new ** write-transaction is opened. ** ** dbSize, dbOrigSize, dbFileSize ** ** Variable dbSize is set to the number of pages in the database file. ** It is valid in PAGER_READER and higher states (all states except for ** OPEN and ERROR). ** ** dbSize is set based on the size of the database file, which may be ** larger than the size of the database (the value stored at offset ** 28 of the database header by the btree). If the size of the file ** is not an integer multiple of the page-size, the value stored in ** dbSize is rounded down (i.e. a 5KB file with 2K page-size has dbSize==2). ** Except, any file that is greater than 0 bytes in size is considered ** to have at least one page. (i.e. a 1KB file with 2K page-size leads ** to dbSize==1). ** ** During a write-transaction, if pages with page-numbers greater than ** dbSize are modified in the cache, dbSize is updated accordingly. ** Similarly, if the database is truncated using PagerTruncateImage(), ** dbSize is updated. ** ** Variables dbOrigSize and dbFileSize are valid in states ** PAGER_WRITER_LOCKED and higher. dbOrigSize is a copy of the dbSize ** variable at the start of the transaction. It is used during rollback, ** and to determine whether or not pages need to be journalled before ** being modified. ** ** Throughout a write-transaction, dbFileSize contains the size of ** the file on disk in pages. It is set to a copy of dbSize when the ** write-transaction is first opened, and updated when VFS calls are made ** to write or truncate the database file on disk. ** ** The only reason the dbFileSize variable is required is to suppress ** unnecessary calls to xTruncate() after committing a transaction. If, ** when a transaction is committed, the dbFileSize variable indicates ** that the database file is larger than the database image (Pager.dbSize), ** pager_truncate() is called. The pager_truncate() call uses xFilesize() ** to measure the database file on disk, and then truncates it if required. ** dbFileSize is not used when rolling back a transaction. In this case ** pager_truncate() is called unconditionally (which means there may be ** a call to xFilesize() that is not strictly required). In either case, ** pager_truncate() may cause the file to become smaller or larger. ** ** dbHintSize ** ** The dbHintSize variable is used to limit the number of calls made to ** the VFS xFileControl(FCNTL_SIZE_HINT) method. ** ** dbHintSize is set to a copy of the dbSize variable when a ** write-transaction is opened (at the same time as dbFileSize and ** dbOrigSize). If the xFileControl(FCNTL_SIZE_HINT) method is called, ** dbHintSize is increased to the number of pages that correspond to the ** size-hint passed to the method call. See pager_write_pagelist() for ** details. ** ** errCode ** ** The Pager.errCode variable is only ever used in PAGER_ERROR state. It ** is set to zero in all other states. In PAGER_ERROR state, Pager.errCode ** is always set to SQLITE_FULL, SQLITE_IOERR or one of the SQLITE_IOERR_XXX ** sub-codes. */ struct Pager { sqlite3_vfs *pVfs; /* OS functions to use for IO */ u8 exclusiveMode; /* Boolean. True if locking_mode==EXCLUSIVE */ u8 journalMode; /* One of the PAGER_JOURNALMODE_* values */ u8 useJournal; /* Use a rollback journal on this file */ u8 noSync; /* Do not sync the journal if true */ u8 fullSync; /* Do extra syncs of the journal for robustness */ u8 extraSync; /* sync directory after journal delete */ u8 ckptSyncFlags; /* SYNC_NORMAL or SYNC_FULL for checkpoint */ u8 walSyncFlags; /* SYNC_NORMAL or SYNC_FULL for wal writes */ u8 syncFlags; /* SYNC_NORMAL or SYNC_FULL otherwise */ u8 tempFile; /* zFilename is a temporary or immutable file */ u8 noLock; /* Do not lock (except in WAL mode) */ u8 readOnly; /* True for a read-only database */ u8 memDb; /* True to inhibit all file I/O */ /************************************************************************** ** The following block contains those class members that change during ** routine operation. Class members not in this block are either fixed ** when the pager is first created or else only change when there is a ** significant mode change (such as changing the page_size, locking_mode, ** or the journal_mode). From another view, these class members describe ** the "state" of the pager, while other class members describe the ** "configuration" of the pager. */ u8 eState; /* Pager state (OPEN, READER, WRITER_LOCKED..) */ u8 eLock; /* Current lock held on database file */ u8 changeCountDone; /* Set after incrementing the change-counter */ u8 setMaster; /* True if a m-j name has been written to jrnl */ u8 doNotSpill; /* Do not spill the cache when non-zero */ u8 subjInMemory; /* True to use in-memory sub-journals */ u8 bUseFetch; /* True to use xFetch() */ u8 hasHeldSharedLock; /* True if a shared lock has ever been held */ Pgno dbSize; /* Number of pages in the database */ Pgno dbOrigSize; /* dbSize before the current transaction */ Pgno dbFileSize; /* Number of pages in the database file */ Pgno dbHintSize; /* Value passed to FCNTL_SIZE_HINT call */ int errCode; /* One of several kinds of errors */ int nRec; /* Pages journalled since last j-header written */ u32 cksumInit; /* Quasi-random value added to every checksum */ u32 nSubRec; /* Number of records written to sub-journal */ Bitvec *pInJournal; /* One bit for each page in the database file */ sqlite3_file *fd; /* File descriptor for database */ sqlite3_file *jfd; /* File descriptor for main journal */ sqlite3_file *sjfd; /* File descriptor for sub-journal */ i64 journalOff; /* Current write offset in the journal file */ i64 journalHdr; /* Byte offset to previous journal header */ sqlite3_backup *pBackup; /* Pointer to list of ongoing backup processes */ PagerSavepoint *aSavepoint; /* Array of active savepoints */ int nSavepoint; /* Number of elements in aSavepoint[] */ u32 iDataVersion; /* Changes whenever database content changes */ char dbFileVers[16]; /* Changes whenever database file changes */ int nMmapOut; /* Number of mmap pages currently outstanding */ sqlite3_int64 szMmap; /* Desired maximum mmap size */ PgHdr *pMmapFreelist; /* List of free mmap page headers (pDirty) */ /* ** End of the routinely-changing class members ***************************************************************************/ u16 nExtra; /* Add this many bytes to each in-memory page */ i16 nReserve; /* Number of unused bytes at end of each page */ u32 vfsFlags; /* Flags for sqlite3_vfs.xOpen() */ u32 sectorSize; /* Assumed sector size during rollback */ int pageSize; /* Number of bytes in a page */ Pgno mxPgno; /* Maximum allowed size of the database */ i64 journalSizeLimit; /* Size limit for persistent journal files */ char *zFilename; /* Name of the database file */ char *zJournal; /* Name of the journal file */ int (*xBusyHandler)(void*); /* Function to call when busy */ void *pBusyHandlerArg; /* Context argument for xBusyHandler */ int aStat[3]; /* Total cache hits, misses and writes */ #ifdef SQLITE_TEST int nRead; /* Database pages read */ #endif void (*xReiniter)(DbPage*); /* Call this routine when reloading pages */ #ifdef SQLITE_HAS_CODEC void *(*xCodec)(void*,void*,Pgno,int); /* Routine for en/decoding data */ void (*xCodecSizeChng)(void*,int,int); /* Notify of page size changes */ void (*xCodecFree)(void*); /* Destructor for the codec */ void *pCodec; /* First argument to xCodec... methods */ #endif char *pTmpSpace; /* Pager.pageSize bytes of space for tmp use */ PCache *pPCache; /* Pointer to page cache object */ #ifndef SQLITE_OMIT_WAL Wal *pWal; /* Write-ahead log used by "journal_mode=wal" */ char *zWal; /* File name for write-ahead log */ #endif }; /* ** Indexes for use with Pager.aStat[]. The Pager.aStat[] array contains ** the values accessed by passing SQLITE_DBSTATUS_CACHE_HIT, CACHE_MISS ** or CACHE_WRITE to sqlite3_db_status(). */ #define PAGER_STAT_HIT 0 #define PAGER_STAT_MISS 1 #define PAGER_STAT_WRITE 2 /* ** The following global variables hold counters used for ** testing purposes only. These variables do not exist in ** a non-testing build. These variables are not thread-safe. */ #ifdef SQLITE_TEST SQLITE_API int sqlite3_pager_readdb_count = 0; /* Number of full pages read from DB */ SQLITE_API int sqlite3_pager_writedb_count = 0; /* Number of full pages written to DB */ SQLITE_API int sqlite3_pager_writej_count = 0; /* Number of pages written to journal */ # define PAGER_INCR(v) v++ #else # define PAGER_INCR(v) #endif /* ** Journal files begin with the following magic string. The data ** was obtained from /dev/random. It is used only as a sanity check. ** ** Since version 2.8.0, the journal format contains additional sanity ** checking information. If the power fails while the journal is being ** written, semi-random garbage data might appear in the journal ** file after power is restored. If an attempt is then made ** to roll the journal back, the database could be corrupted. The additional ** sanity checking data is an attempt to discover the garbage in the ** journal and ignore it. ** ** The sanity checking information for the new journal format consists ** of a 32-bit checksum on each page of data. The checksum covers both ** the page number and the pPager->pageSize bytes of data for the page. ** This cksum is initialized to a 32-bit random value that appears in the ** journal file right after the header. The random initializer is important, ** because garbage data that appears at the end of a journal is likely ** data that was once in other files that have now been deleted. If the ** garbage data came from an obsolete journal file, the checksums might ** be correct. But by initializing the checksum to random value which ** is different for every journal, we minimize that risk. */ static const unsigned char aJournalMagic[] = { 0xd9, 0xd5, 0x05, 0xf9, 0x20, 0xa1, 0x63, 0xd7, }; /* ** The size of the of each page record in the journal is given by ** the following macro. */ #define JOURNAL_PG_SZ(pPager) ((pPager->pageSize) + 8) /* ** The journal header size for this pager. This is usually the same ** size as a single disk sector. See also setSectorSize(). */ #define JOURNAL_HDR_SZ(pPager) (pPager->sectorSize) /* ** The macro MEMDB is true if we are dealing with an in-memory database. ** We do this as a macro so that if the SQLITE_OMIT_MEMORYDB macro is set, ** the value of MEMDB will be a constant and the compiler will optimize ** out code that would never execute. */ #ifdef SQLITE_OMIT_MEMORYDB # define MEMDB 0 #else # define MEMDB pPager->memDb #endif /* ** The macro USEFETCH is true if we are allowed to use the xFetch and xUnfetch ** interfaces to access the database using memory-mapped I/O. */ #if SQLITE_MAX_MMAP_SIZE>0 # define USEFETCH(x) ((x)->bUseFetch) #else # define USEFETCH(x) 0 #endif /* ** The maximum legal page number is (2^31 - 1). */ #define PAGER_MAX_PGNO 2147483647 /* ** The argument to this macro is a file descriptor (type sqlite3_file*). ** Return 0 if it is not open, or non-zero (but not 1) if it is. ** ** This is so that expressions can be written as: ** ** if( isOpen(pPager->jfd) ){ ... ** ** instead of ** ** if( pPager->jfd->pMethods ){ ... */ #define isOpen(pFd) ((pFd)->pMethods!=0) /* ** Return true if this pager uses a write-ahead log instead of the usual ** rollback journal. Otherwise false. */ #ifndef SQLITE_OMIT_WAL SQLITE_PRIVATE int sqlite3PagerUseWal(Pager *pPager){ return (pPager->pWal!=0); } # define pagerUseWal(x) sqlite3PagerUseWal(x) #else # define pagerUseWal(x) 0 # define pagerRollbackWal(x) 0 # define pagerWalFrames(v,w,x,y) 0 # define pagerOpenWalIfPresent(z) SQLITE_OK # define pagerBeginReadTransaction(z) SQLITE_OK #endif #ifndef NDEBUG /* ** Usage: ** ** assert( assert_pager_state(pPager) ); ** ** This function runs many asserts to try to find inconsistencies in ** the internal state of the Pager object. */ static int assert_pager_state(Pager *p){ Pager *pPager = p; /* State must be valid. */ assert( p->eState==PAGER_OPEN || p->eState==PAGER_READER || p->eState==PAGER_WRITER_LOCKED || p->eState==PAGER_WRITER_CACHEMOD || p->eState==PAGER_WRITER_DBMOD || p->eState==PAGER_WRITER_FINISHED || p->eState==PAGER_ERROR ); /* Regardless of the current state, a temp-file connection always behaves ** as if it has an exclusive lock on the database file. It never updates ** the change-counter field, so the changeCountDone flag is always set. */ assert( p->tempFile==0 || p->eLock==EXCLUSIVE_LOCK ); assert( p->tempFile==0 || pPager->changeCountDone ); /* If the useJournal flag is clear, the journal-mode must be "OFF". ** And if the journal-mode is "OFF", the journal file must not be open. */ assert( p->journalMode==PAGER_JOURNALMODE_OFF || p->useJournal ); assert( p->journalMode!=PAGER_JOURNALMODE_OFF || !isOpen(p->jfd) ); /* Check that MEMDB implies noSync. And an in-memory journal. Since ** this means an in-memory pager performs no IO at all, it cannot encounter ** either SQLITE_IOERR or SQLITE_FULL during rollback or while finalizing ** a journal file. (although the in-memory journal implementation may ** return SQLITE_IOERR_NOMEM while the journal file is being written). It ** is therefore not possible for an in-memory pager to enter the ERROR ** state. */ if( MEMDB ){ assert( !isOpen(p->fd) ); assert( p->noSync ); assert( p->journalMode==PAGER_JOURNALMODE_OFF || p->journalMode==PAGER_JOURNALMODE_MEMORY ); assert( p->eState!=PAGER_ERROR && p->eState!=PAGER_OPEN ); assert( pagerUseWal(p)==0 ); } /* If changeCountDone is set, a RESERVED lock or greater must be held ** on the file. */ assert( pPager->changeCountDone==0 || pPager->eLock>=RESERVED_LOCK ); assert( p->eLock!=PENDING_LOCK ); switch( p->eState ){ case PAGER_OPEN: assert( !MEMDB ); assert( pPager->errCode==SQLITE_OK ); assert( sqlite3PcacheRefCount(pPager->pPCache)==0 || pPager->tempFile ); break; case PAGER_READER: assert( pPager->errCode==SQLITE_OK ); assert( p->eLock!=UNKNOWN_LOCK ); assert( p->eLock>=SHARED_LOCK ); break; case PAGER_WRITER_LOCKED: assert( p->eLock!=UNKNOWN_LOCK ); assert( pPager->errCode==SQLITE_OK ); if( !pagerUseWal(pPager) ){ assert( p->eLock>=RESERVED_LOCK ); } assert( pPager->dbSize==pPager->dbOrigSize ); assert( pPager->dbOrigSize==pPager->dbFileSize ); assert( pPager->dbOrigSize==pPager->dbHintSize ); assert( pPager->setMaster==0 ); break; case PAGER_WRITER_CACHEMOD: assert( p->eLock!=UNKNOWN_LOCK ); assert( pPager->errCode==SQLITE_OK ); if( !pagerUseWal(pPager) ){ /* It is possible that if journal_mode=wal here that neither the ** journal file nor the WAL file are open. This happens during ** a rollback transaction that switches from journal_mode=off ** to journal_mode=wal. */ assert( p->eLock>=RESERVED_LOCK ); assert( isOpen(p->jfd) || p->journalMode==PAGER_JOURNALMODE_OFF || p->journalMode==PAGER_JOURNALMODE_WAL ); } assert( pPager->dbOrigSize==pPager->dbFileSize ); assert( pPager->dbOrigSize==pPager->dbHintSize ); break; case PAGER_WRITER_DBMOD: assert( p->eLock==EXCLUSIVE_LOCK ); assert( pPager->errCode==SQLITE_OK ); assert( !pagerUseWal(pPager) ); assert( p->eLock>=EXCLUSIVE_LOCK ); assert( isOpen(p->jfd) || p->journalMode==PAGER_JOURNALMODE_OFF || p->journalMode==PAGER_JOURNALMODE_WAL ); assert( pPager->dbOrigSize<=pPager->dbHintSize ); break; case PAGER_WRITER_FINISHED: assert( p->eLock==EXCLUSIVE_LOCK ); assert( pPager->errCode==SQLITE_OK ); assert( !pagerUseWal(pPager) ); assert( isOpen(p->jfd) || p->journalMode==PAGER_JOURNALMODE_OFF || p->journalMode==PAGER_JOURNALMODE_WAL ); break; case PAGER_ERROR: /* There must be at least one outstanding reference to the pager if ** in ERROR state. Otherwise the pager should have already dropped ** back to OPEN state. */ assert( pPager->errCode!=SQLITE_OK ); assert( sqlite3PcacheRefCount(pPager->pPCache)>0 || pPager->tempFile ); break; } return 1; } #endif /* ifndef NDEBUG */ #ifdef SQLITE_DEBUG /* ** Return a pointer to a human readable string in a static buffer ** containing the state of the Pager object passed as an argument. This ** is intended to be used within debuggers. For example, as an alternative ** to "print *pPager" in gdb: ** ** (gdb) printf "%s", print_pager_state(pPager) */ static char *print_pager_state(Pager *p){ static char zRet[1024]; sqlite3_snprintf(1024, zRet, "Filename: %s\n" "State: %s errCode=%d\n" "Lock: %s\n" "Locking mode: locking_mode=%s\n" "Journal mode: journal_mode=%s\n" "Backing store: tempFile=%d memDb=%d useJournal=%d\n" "Journal: journalOff=%lld journalHdr=%lld\n" "Size: dbsize=%d dbOrigSize=%d dbFileSize=%d\n" , p->zFilename , p->eState==PAGER_OPEN ? "OPEN" : p->eState==PAGER_READER ? "READER" : p->eState==PAGER_WRITER_LOCKED ? "WRITER_LOCKED" : p->eState==PAGER_WRITER_CACHEMOD ? "WRITER_CACHEMOD" : p->eState==PAGER_WRITER_DBMOD ? "WRITER_DBMOD" : p->eState==PAGER_WRITER_FINISHED ? "WRITER_FINISHED" : p->eState==PAGER_ERROR ? "ERROR" : "?error?" , (int)p->errCode , p->eLock==NO_LOCK ? "NO_LOCK" : p->eLock==RESERVED_LOCK ? "RESERVED" : p->eLock==EXCLUSIVE_LOCK ? "EXCLUSIVE" : p->eLock==SHARED_LOCK ? "SHARED" : p->eLock==UNKNOWN_LOCK ? "UNKNOWN" : "?error?" , p->exclusiveMode ? "exclusive" : "normal" , p->journalMode==PAGER_JOURNALMODE_MEMORY ? "memory" : p->journalMode==PAGER_JOURNALMODE_OFF ? "off" : p->journalMode==PAGER_JOURNALMODE_DELETE ? "delete" : p->journalMode==PAGER_JOURNALMODE_PERSIST ? "persist" : p->journalMode==PAGER_JOURNALMODE_TRUNCATE ? "truncate" : p->journalMode==PAGER_JOURNALMODE_WAL ? "wal" : "?error?" , (int)p->tempFile, (int)p->memDb, (int)p->useJournal , p->journalOff, p->journalHdr , (int)p->dbSize, (int)p->dbOrigSize, (int)p->dbFileSize ); return zRet; } #endif /* ** Return true if it is necessary to write page *pPg into the sub-journal. ** A page needs to be written into the sub-journal if there exists one ** or more open savepoints for which: ** ** * The page-number is less than or equal to PagerSavepoint.nOrig, and ** * The bit corresponding to the page-number is not set in ** PagerSavepoint.pInSavepoint. */ static int subjRequiresPage(PgHdr *pPg){ Pager *pPager = pPg->pPager; PagerSavepoint *p; Pgno pgno = pPg->pgno; int i; for(i=0; inSavepoint; i++){ p = &pPager->aSavepoint[i]; if( p->nOrig>=pgno && 0==sqlite3BitvecTestNotNull(p->pInSavepoint, pgno) ){ return 1; } } return 0; } #ifdef SQLITE_DEBUG /* ** Return true if the page is already in the journal file. */ static int pageInJournal(Pager *pPager, PgHdr *pPg){ return sqlite3BitvecTest(pPager->pInJournal, pPg->pgno); } #endif /* ** Read a 32-bit integer from the given file descriptor. Store the integer ** that is read in *pRes. Return SQLITE_OK if everything worked, or an ** error code is something goes wrong. ** ** All values are stored on disk as big-endian. */ static int read32bits(sqlite3_file *fd, i64 offset, u32 *pRes){ unsigned char ac[4]; int rc = sqlite3OsRead(fd, ac, sizeof(ac), offset); if( rc==SQLITE_OK ){ *pRes = sqlite3Get4byte(ac); } return rc; } /* ** Write a 32-bit integer into a string buffer in big-endian byte order. */ #define put32bits(A,B) sqlite3Put4byte((u8*)A,B) /* ** Write a 32-bit integer into the given file descriptor. Return SQLITE_OK ** on success or an error code is something goes wrong. */ static int write32bits(sqlite3_file *fd, i64 offset, u32 val){ char ac[4]; put32bits(ac, val); return sqlite3OsWrite(fd, ac, 4, offset); } /* ** Unlock the database file to level eLock, which must be either NO_LOCK ** or SHARED_LOCK. Regardless of whether or not the call to xUnlock() ** succeeds, set the Pager.eLock variable to match the (attempted) new lock. ** ** Except, if Pager.eLock is set to UNKNOWN_LOCK when this function is ** called, do not modify it. See the comment above the #define of ** UNKNOWN_LOCK for an explanation of this. */ static int pagerUnlockDb(Pager *pPager, int eLock){ int rc = SQLITE_OK; assert( !pPager->exclusiveMode || pPager->eLock==eLock ); assert( eLock==NO_LOCK || eLock==SHARED_LOCK ); assert( eLock!=NO_LOCK || pagerUseWal(pPager)==0 ); if( isOpen(pPager->fd) ){ assert( pPager->eLock>=eLock ); rc = pPager->noLock ? SQLITE_OK : sqlite3OsUnlock(pPager->fd, eLock); if( pPager->eLock!=UNKNOWN_LOCK ){ pPager->eLock = (u8)eLock; } IOTRACE(("UNLOCK %p %d\n", pPager, eLock)) } return rc; } /* ** Lock the database file to level eLock, which must be either SHARED_LOCK, ** RESERVED_LOCK or EXCLUSIVE_LOCK. If the caller is successful, set the ** Pager.eLock variable to the new locking state. ** ** Except, if Pager.eLock is set to UNKNOWN_LOCK when this function is ** called, do not modify it unless the new locking state is EXCLUSIVE_LOCK. ** See the comment above the #define of UNKNOWN_LOCK for an explanation ** of this. */ static int pagerLockDb(Pager *pPager, int eLock){ int rc = SQLITE_OK; assert( eLock==SHARED_LOCK || eLock==RESERVED_LOCK || eLock==EXCLUSIVE_LOCK ); if( pPager->eLockeLock==UNKNOWN_LOCK ){ rc = pPager->noLock ? SQLITE_OK : sqlite3OsLock(pPager->fd, eLock); if( rc==SQLITE_OK && (pPager->eLock!=UNKNOWN_LOCK||eLock==EXCLUSIVE_LOCK) ){ pPager->eLock = (u8)eLock; IOTRACE(("LOCK %p %d\n", pPager, eLock)) } } return rc; } /* ** This function determines whether or not the atomic-write optimization ** can be used with this pager. The optimization can be used if: ** ** (a) the value returned by OsDeviceCharacteristics() indicates that ** a database page may be written atomically, and ** (b) the value returned by OsSectorSize() is less than or equal ** to the page size. ** ** The optimization is also always enabled for temporary files. It is ** an error to call this function if pPager is opened on an in-memory ** database. ** ** If the optimization cannot be used, 0 is returned. If it can be used, ** then the value returned is the size of the journal file when it ** contains rollback data for exactly one page. */ #ifdef SQLITE_ENABLE_ATOMIC_WRITE static int jrnlBufferSize(Pager *pPager){ assert( !MEMDB ); if( !pPager->tempFile ){ int dc; /* Device characteristics */ int nSector; /* Sector size */ int szPage; /* Page size */ assert( isOpen(pPager->fd) ); dc = sqlite3OsDeviceCharacteristics(pPager->fd); nSector = pPager->sectorSize; szPage = pPager->pageSize; assert(SQLITE_IOCAP_ATOMIC512==(512>>8)); assert(SQLITE_IOCAP_ATOMIC64K==(65536>>8)); if( 0==(dc&(SQLITE_IOCAP_ATOMIC|(szPage>>8)) || nSector>szPage) ){ return 0; } } return JOURNAL_HDR_SZ(pPager) + JOURNAL_PG_SZ(pPager); } #else # define jrnlBufferSize(x) 0 #endif /* ** If SQLITE_CHECK_PAGES is defined then we do some sanity checking ** on the cache using a hash function. This is used for testing ** and debugging only. */ #ifdef SQLITE_CHECK_PAGES /* ** Return a 32-bit hash of the page data for pPage. */ static u32 pager_datahash(int nByte, unsigned char *pData){ u32 hash = 0; int i; for(i=0; ipPager->pageSize, (unsigned char *)pPage->pData); } static void pager_set_pagehash(PgHdr *pPage){ pPage->pageHash = pager_pagehash(pPage); } /* ** The CHECK_PAGE macro takes a PgHdr* as an argument. If SQLITE_CHECK_PAGES ** is defined, and NDEBUG is not defined, an assert() statement checks ** that the page is either dirty or still matches the calculated page-hash. */ #define CHECK_PAGE(x) checkPage(x) static void checkPage(PgHdr *pPg){ Pager *pPager = pPg->pPager; assert( pPager->eState!=PAGER_ERROR ); assert( (pPg->flags&PGHDR_DIRTY) || pPg->pageHash==pager_pagehash(pPg) ); } #else #define pager_datahash(X,Y) 0 #define pager_pagehash(X) 0 #define pager_set_pagehash(X) #define CHECK_PAGE(x) #endif /* SQLITE_CHECK_PAGES */ /* ** When this is called the journal file for pager pPager must be open. ** This function attempts to read a master journal file name from the ** end of the file and, if successful, copies it into memory supplied ** by the caller. See comments above writeMasterJournal() for the format ** used to store a master journal file name at the end of a journal file. ** ** zMaster must point to a buffer of at least nMaster bytes allocated by ** the caller. This should be sqlite3_vfs.mxPathname+1 (to ensure there is ** enough space to write the master journal name). If the master journal ** name in the journal is longer than nMaster bytes (including a ** nul-terminator), then this is handled as if no master journal name ** were present in the journal. ** ** If a master journal file name is present at the end of the journal ** file, then it is copied into the buffer pointed to by zMaster. A ** nul-terminator byte is appended to the buffer following the master ** journal file name. ** ** If it is determined that no master journal file name is present ** zMaster[0] is set to 0 and SQLITE_OK returned. ** ** If an error occurs while reading from the journal file, an SQLite ** error code is returned. */ static int readMasterJournal(sqlite3_file *pJrnl, char *zMaster, u32 nMaster){ int rc; /* Return code */ u32 len; /* Length in bytes of master journal name */ i64 szJ; /* Total size in bytes of journal file pJrnl */ u32 cksum; /* MJ checksum value read from journal */ u32 u; /* Unsigned loop counter */ unsigned char aMagic[8]; /* A buffer to hold the magic header */ zMaster[0] = '\0'; if( SQLITE_OK!=(rc = sqlite3OsFileSize(pJrnl, &szJ)) || szJ<16 || SQLITE_OK!=(rc = read32bits(pJrnl, szJ-16, &len)) || len>=nMaster || len==0 || SQLITE_OK!=(rc = read32bits(pJrnl, szJ-12, &cksum)) || SQLITE_OK!=(rc = sqlite3OsRead(pJrnl, aMagic, 8, szJ-8)) || memcmp(aMagic, aJournalMagic, 8) || SQLITE_OK!=(rc = sqlite3OsRead(pJrnl, zMaster, len, szJ-16-len)) ){ return rc; } /* See if the checksum matches the master journal name */ for(u=0; ujournalOff, assuming a sector ** size of pPager->sectorSize bytes. ** ** i.e for a sector size of 512: ** ** Pager.journalOff Return value ** --------------------------------------- ** 0 0 ** 512 512 ** 100 512 ** 2000 2048 ** */ static i64 journalHdrOffset(Pager *pPager){ i64 offset = 0; i64 c = pPager->journalOff; if( c ){ offset = ((c-1)/JOURNAL_HDR_SZ(pPager) + 1) * JOURNAL_HDR_SZ(pPager); } assert( offset%JOURNAL_HDR_SZ(pPager)==0 ); assert( offset>=c ); assert( (offset-c)jfd) ); assert( !sqlite3JournalIsInMemory(pPager->jfd) ); if( pPager->journalOff ){ const i64 iLimit = pPager->journalSizeLimit; /* Local cache of jsl */ IOTRACE(("JZEROHDR %p\n", pPager)) if( doTruncate || iLimit==0 ){ rc = sqlite3OsTruncate(pPager->jfd, 0); }else{ static const char zeroHdr[28] = {0}; rc = sqlite3OsWrite(pPager->jfd, zeroHdr, sizeof(zeroHdr), 0); } if( rc==SQLITE_OK && !pPager->noSync ){ rc = sqlite3OsSync(pPager->jfd, SQLITE_SYNC_DATAONLY|pPager->syncFlags); } /* At this point the transaction is committed but the write lock ** is still held on the file. If there is a size limit configured for ** the persistent journal and the journal file currently consumes more ** space than that limit allows for, truncate it now. There is no need ** to sync the file following this operation. */ if( rc==SQLITE_OK && iLimit>0 ){ i64 sz; rc = sqlite3OsFileSize(pPager->jfd, &sz); if( rc==SQLITE_OK && sz>iLimit ){ rc = sqlite3OsTruncate(pPager->jfd, iLimit); } } } return rc; } /* ** The journal file must be open when this routine is called. A journal ** header (JOURNAL_HDR_SZ bytes) is written into the journal file at the ** current location. ** ** The format for the journal header is as follows: ** - 8 bytes: Magic identifying journal format. ** - 4 bytes: Number of records in journal, or -1 no-sync mode is on. ** - 4 bytes: Random number used for page hash. ** - 4 bytes: Initial database page count. ** - 4 bytes: Sector size used by the process that wrote this journal. ** - 4 bytes: Database page size. ** ** Followed by (JOURNAL_HDR_SZ - 28) bytes of unused space. */ static int writeJournalHdr(Pager *pPager){ int rc = SQLITE_OK; /* Return code */ char *zHeader = pPager->pTmpSpace; /* Temporary space used to build header */ u32 nHeader = (u32)pPager->pageSize;/* Size of buffer pointed to by zHeader */ u32 nWrite; /* Bytes of header sector written */ int ii; /* Loop counter */ assert( isOpen(pPager->jfd) ); /* Journal file must be open. */ if( nHeader>JOURNAL_HDR_SZ(pPager) ){ nHeader = JOURNAL_HDR_SZ(pPager); } /* If there are active savepoints and any of them were created ** since the most recent journal header was written, update the ** PagerSavepoint.iHdrOffset fields now. */ for(ii=0; iinSavepoint; ii++){ if( pPager->aSavepoint[ii].iHdrOffset==0 ){ pPager->aSavepoint[ii].iHdrOffset = pPager->journalOff; } } pPager->journalHdr = pPager->journalOff = journalHdrOffset(pPager); /* ** Write the nRec Field - the number of page records that follow this ** journal header. Normally, zero is written to this value at this time. ** After the records are added to the journal (and the journal synced, ** if in full-sync mode), the zero is overwritten with the true number ** of records (see syncJournal()). ** ** A faster alternative is to write 0xFFFFFFFF to the nRec field. When ** reading the journal this value tells SQLite to assume that the ** rest of the journal file contains valid page records. This assumption ** is dangerous, as if a failure occurred whilst writing to the journal ** file it may contain some garbage data. There are two scenarios ** where this risk can be ignored: ** ** * When the pager is in no-sync mode. Corruption can follow a ** power failure in this case anyway. ** ** * When the SQLITE_IOCAP_SAFE_APPEND flag is set. This guarantees ** that garbage data is never appended to the journal file. */ assert( isOpen(pPager->fd) || pPager->noSync ); if( pPager->noSync || (pPager->journalMode==PAGER_JOURNALMODE_MEMORY) || (sqlite3OsDeviceCharacteristics(pPager->fd)&SQLITE_IOCAP_SAFE_APPEND) ){ memcpy(zHeader, aJournalMagic, sizeof(aJournalMagic)); put32bits(&zHeader[sizeof(aJournalMagic)], 0xffffffff); }else{ memset(zHeader, 0, sizeof(aJournalMagic)+4); } /* The random check-hash initializer */ sqlite3_randomness(sizeof(pPager->cksumInit), &pPager->cksumInit); put32bits(&zHeader[sizeof(aJournalMagic)+4], pPager->cksumInit); /* The initial database size */ put32bits(&zHeader[sizeof(aJournalMagic)+8], pPager->dbOrigSize); /* The assumed sector size for this process */ put32bits(&zHeader[sizeof(aJournalMagic)+12], pPager->sectorSize); /* The page size */ put32bits(&zHeader[sizeof(aJournalMagic)+16], pPager->pageSize); /* Initializing the tail of the buffer is not necessary. Everything ** works find if the following memset() is omitted. But initializing ** the memory prevents valgrind from complaining, so we are willing to ** take the performance hit. */ memset(&zHeader[sizeof(aJournalMagic)+20], 0, nHeader-(sizeof(aJournalMagic)+20)); /* In theory, it is only necessary to write the 28 bytes that the ** journal header consumes to the journal file here. Then increment the ** Pager.journalOff variable by JOURNAL_HDR_SZ so that the next ** record is written to the following sector (leaving a gap in the file ** that will be implicitly filled in by the OS). ** ** However it has been discovered that on some systems this pattern can ** be significantly slower than contiguously writing data to the file, ** even if that means explicitly writing data to the block of ** (JOURNAL_HDR_SZ - 28) bytes that will not be used. So that is what ** is done. ** ** The loop is required here in case the sector-size is larger than the ** database page size. Since the zHeader buffer is only Pager.pageSize ** bytes in size, more than one call to sqlite3OsWrite() may be required ** to populate the entire journal header sector. */ for(nWrite=0; rc==SQLITE_OK&&nWritejournalHdr, nHeader)) rc = sqlite3OsWrite(pPager->jfd, zHeader, nHeader, pPager->journalOff); assert( pPager->journalHdr <= pPager->journalOff ); pPager->journalOff += nHeader; } return rc; } /* ** The journal file must be open when this is called. A journal header file ** (JOURNAL_HDR_SZ bytes) is read from the current location in the journal ** file. The current location in the journal file is given by ** pPager->journalOff. See comments above function writeJournalHdr() for ** a description of the journal header format. ** ** If the header is read successfully, *pNRec is set to the number of ** page records following this header and *pDbSize is set to the size of the ** database before the transaction began, in pages. Also, pPager->cksumInit ** is set to the value read from the journal header. SQLITE_OK is returned ** in this case. ** ** If the journal header file appears to be corrupted, SQLITE_DONE is ** returned and *pNRec and *PDbSize are undefined. If JOURNAL_HDR_SZ bytes ** cannot be read from the journal file an error code is returned. */ static int readJournalHdr( Pager *pPager, /* Pager object */ int isHot, i64 journalSize, /* Size of the open journal file in bytes */ u32 *pNRec, /* OUT: Value read from the nRec field */ u32 *pDbSize /* OUT: Value of original database size field */ ){ int rc; /* Return code */ unsigned char aMagic[8]; /* A buffer to hold the magic header */ i64 iHdrOff; /* Offset of journal header being read */ assert( isOpen(pPager->jfd) ); /* Journal file must be open. */ /* Advance Pager.journalOff to the start of the next sector. If the ** journal file is too small for there to be a header stored at this ** point, return SQLITE_DONE. */ pPager->journalOff = journalHdrOffset(pPager); if( pPager->journalOff+JOURNAL_HDR_SZ(pPager) > journalSize ){ return SQLITE_DONE; } iHdrOff = pPager->journalOff; /* Read in the first 8 bytes of the journal header. If they do not match ** the magic string found at the start of each journal header, return ** SQLITE_DONE. If an IO error occurs, return an error code. Otherwise, ** proceed. */ if( isHot || iHdrOff!=pPager->journalHdr ){ rc = sqlite3OsRead(pPager->jfd, aMagic, sizeof(aMagic), iHdrOff); if( rc ){ return rc; } if( memcmp(aMagic, aJournalMagic, sizeof(aMagic))!=0 ){ return SQLITE_DONE; } } /* Read the first three 32-bit fields of the journal header: The nRec ** field, the checksum-initializer and the database size at the start ** of the transaction. Return an error code if anything goes wrong. */ if( SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+8, pNRec)) || SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+12, &pPager->cksumInit)) || SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+16, pDbSize)) ){ return rc; } if( pPager->journalOff==0 ){ u32 iPageSize; /* Page-size field of journal header */ u32 iSectorSize; /* Sector-size field of journal header */ /* Read the page-size and sector-size journal header fields. */ if( SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+20, &iSectorSize)) || SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+24, &iPageSize)) ){ return rc; } /* Versions of SQLite prior to 3.5.8 set the page-size field of the ** journal header to zero. In this case, assume that the Pager.pageSize ** variable is already set to the correct page size. */ if( iPageSize==0 ){ iPageSize = pPager->pageSize; } /* Check that the values read from the page-size and sector-size fields ** are within range. To be 'in range', both values need to be a power ** of two greater than or equal to 512 or 32, and not greater than their ** respective compile time maximum limits. */ if( iPageSize<512 || iSectorSize<32 || iPageSize>SQLITE_MAX_PAGE_SIZE || iSectorSize>MAX_SECTOR_SIZE || ((iPageSize-1)&iPageSize)!=0 || ((iSectorSize-1)&iSectorSize)!=0 ){ /* If the either the page-size or sector-size in the journal-header is ** invalid, then the process that wrote the journal-header must have ** crashed before the header was synced. In this case stop reading ** the journal file here. */ return SQLITE_DONE; } /* Update the page-size to match the value read from the journal. ** Use a testcase() macro to make sure that malloc failure within ** PagerSetPagesize() is tested. */ rc = sqlite3PagerSetPagesize(pPager, &iPageSize, -1); testcase( rc!=SQLITE_OK ); /* Update the assumed sector-size to match the value used by ** the process that created this journal. If this journal was ** created by a process other than this one, then this routine ** is being called from within pager_playback(). The local value ** of Pager.sectorSize is restored at the end of that routine. */ pPager->sectorSize = iSectorSize; } pPager->journalOff += JOURNAL_HDR_SZ(pPager); return rc; } /* ** Write the supplied master journal name into the journal file for pager ** pPager at the current location. The master journal name must be the last ** thing written to a journal file. If the pager is in full-sync mode, the ** journal file descriptor is advanced to the next sector boundary before ** anything is written. The format is: ** ** + 4 bytes: PAGER_MJ_PGNO. ** + N bytes: Master journal filename in utf-8. ** + 4 bytes: N (length of master journal name in bytes, no nul-terminator). ** + 4 bytes: Master journal name checksum. ** + 8 bytes: aJournalMagic[]. ** ** The master journal page checksum is the sum of the bytes in the master ** journal name, where each byte is interpreted as a signed 8-bit integer. ** ** If zMaster is a NULL pointer (occurs for a single database transaction), ** this call is a no-op. */ static int writeMasterJournal(Pager *pPager, const char *zMaster){ int rc; /* Return code */ int nMaster; /* Length of string zMaster */ i64 iHdrOff; /* Offset of header in journal file */ i64 jrnlSize; /* Size of journal file on disk */ u32 cksum = 0; /* Checksum of string zMaster */ assert( pPager->setMaster==0 ); assert( !pagerUseWal(pPager) ); if( !zMaster || pPager->journalMode==PAGER_JOURNALMODE_MEMORY || !isOpen(pPager->jfd) ){ return SQLITE_OK; } pPager->setMaster = 1; assert( pPager->journalHdr <= pPager->journalOff ); /* Calculate the length in bytes and the checksum of zMaster */ for(nMaster=0; zMaster[nMaster]; nMaster++){ cksum += zMaster[nMaster]; } /* If in full-sync mode, advance to the next disk sector before writing ** the master journal name. This is in case the previous page written to ** the journal has already been synced. */ if( pPager->fullSync ){ pPager->journalOff = journalHdrOffset(pPager); } iHdrOff = pPager->journalOff; /* Write the master journal data to the end of the journal file. If ** an error occurs, return the error code to the caller. */ if( (0 != (rc = write32bits(pPager->jfd, iHdrOff, PAGER_MJ_PGNO(pPager)))) || (0 != (rc = sqlite3OsWrite(pPager->jfd, zMaster, nMaster, iHdrOff+4))) || (0 != (rc = write32bits(pPager->jfd, iHdrOff+4+nMaster, nMaster))) || (0 != (rc = write32bits(pPager->jfd, iHdrOff+4+nMaster+4, cksum))) || (0 != (rc = sqlite3OsWrite(pPager->jfd, aJournalMagic, 8, iHdrOff+4+nMaster+8))) ){ return rc; } pPager->journalOff += (nMaster+20); /* If the pager is in peristent-journal mode, then the physical ** journal-file may extend past the end of the master-journal name ** and 8 bytes of magic data just written to the file. This is ** dangerous because the code to rollback a hot-journal file ** will not be able to find the master-journal name to determine ** whether or not the journal is hot. ** ** Easiest thing to do in this scenario is to truncate the journal ** file to the required size. */ if( SQLITE_OK==(rc = sqlite3OsFileSize(pPager->jfd, &jrnlSize)) && jrnlSize>pPager->journalOff ){ rc = sqlite3OsTruncate(pPager->jfd, pPager->journalOff); } return rc; } /* ** Discard the entire contents of the in-memory page-cache. */ static void pager_reset(Pager *pPager){ pPager->iDataVersion++; sqlite3BackupRestart(pPager->pBackup); sqlite3PcacheClear(pPager->pPCache); } /* ** Return the pPager->iDataVersion value */ SQLITE_PRIVATE u32 sqlite3PagerDataVersion(Pager *pPager){ assert( pPager->eState>PAGER_OPEN ); return pPager->iDataVersion; } /* ** Free all structures in the Pager.aSavepoint[] array and set both ** Pager.aSavepoint and Pager.nSavepoint to zero. Close the sub-journal ** if it is open and the pager is not in exclusive mode. */ static void releaseAllSavepoints(Pager *pPager){ int ii; /* Iterator for looping through Pager.aSavepoint */ for(ii=0; iinSavepoint; ii++){ sqlite3BitvecDestroy(pPager->aSavepoint[ii].pInSavepoint); } if( !pPager->exclusiveMode || sqlite3JournalIsInMemory(pPager->sjfd) ){ sqlite3OsClose(pPager->sjfd); } sqlite3_free(pPager->aSavepoint); pPager->aSavepoint = 0; pPager->nSavepoint = 0; pPager->nSubRec = 0; } /* ** Set the bit number pgno in the PagerSavepoint.pInSavepoint ** bitvecs of all open savepoints. Return SQLITE_OK if successful ** or SQLITE_NOMEM if a malloc failure occurs. */ static int addToSavepointBitvecs(Pager *pPager, Pgno pgno){ int ii; /* Loop counter */ int rc = SQLITE_OK; /* Result code */ for(ii=0; iinSavepoint; ii++){ PagerSavepoint *p = &pPager->aSavepoint[ii]; if( pgno<=p->nOrig ){ rc |= sqlite3BitvecSet(p->pInSavepoint, pgno); testcase( rc==SQLITE_NOMEM ); assert( rc==SQLITE_OK || rc==SQLITE_NOMEM ); } } return rc; } /* ** This function is a no-op if the pager is in exclusive mode and not ** in the ERROR state. Otherwise, it switches the pager to PAGER_OPEN ** state. ** ** If the pager is not in exclusive-access mode, the database file is ** completely unlocked. If the file is unlocked and the file-system does ** not exhibit the UNDELETABLE_WHEN_OPEN property, the journal file is ** closed (if it is open). ** ** If the pager is in ERROR state when this function is called, the ** contents of the pager cache are discarded before switching back to ** the OPEN state. Regardless of whether the pager is in exclusive-mode ** or not, any journal file left in the file-system will be treated ** as a hot-journal and rolled back the next time a read-transaction ** is opened (by this or by any other connection). */ static void pager_unlock(Pager *pPager){ assert( pPager->eState==PAGER_READER || pPager->eState==PAGER_OPEN || pPager->eState==PAGER_ERROR ); sqlite3BitvecDestroy(pPager->pInJournal); pPager->pInJournal = 0; releaseAllSavepoints(pPager); if( pagerUseWal(pPager) ){ assert( !isOpen(pPager->jfd) ); sqlite3WalEndReadTransaction(pPager->pWal); pPager->eState = PAGER_OPEN; }else if( !pPager->exclusiveMode ){ int rc; /* Error code returned by pagerUnlockDb() */ int iDc = isOpen(pPager->fd)?sqlite3OsDeviceCharacteristics(pPager->fd):0; /* If the operating system support deletion of open files, then ** close the journal file when dropping the database lock. Otherwise ** another connection with journal_mode=delete might delete the file ** out from under us. */ assert( (PAGER_JOURNALMODE_MEMORY & 5)!=1 ); assert( (PAGER_JOURNALMODE_OFF & 5)!=1 ); assert( (PAGER_JOURNALMODE_WAL & 5)!=1 ); assert( (PAGER_JOURNALMODE_DELETE & 5)!=1 ); assert( (PAGER_JOURNALMODE_TRUNCATE & 5)==1 ); assert( (PAGER_JOURNALMODE_PERSIST & 5)==1 ); if( 0==(iDc & SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN) || 1!=(pPager->journalMode & 5) ){ sqlite3OsClose(pPager->jfd); } /* If the pager is in the ERROR state and the call to unlock the database ** file fails, set the current lock to UNKNOWN_LOCK. See the comment ** above the #define for UNKNOWN_LOCK for an explanation of why this ** is necessary. */ rc = pagerUnlockDb(pPager, NO_LOCK); if( rc!=SQLITE_OK && pPager->eState==PAGER_ERROR ){ pPager->eLock = UNKNOWN_LOCK; } /* The pager state may be changed from PAGER_ERROR to PAGER_OPEN here ** without clearing the error code. This is intentional - the error ** code is cleared and the cache reset in the block below. */ assert( pPager->errCode || pPager->eState!=PAGER_ERROR ); pPager->changeCountDone = 0; pPager->eState = PAGER_OPEN; } /* If Pager.errCode is set, the contents of the pager cache cannot be ** trusted. Now that there are no outstanding references to the pager, ** it can safely move back to PAGER_OPEN state. This happens in both ** normal and exclusive-locking mode. */ assert( pPager->errCode==SQLITE_OK || !MEMDB ); if( pPager->errCode ){ if( pPager->tempFile==0 ){ pager_reset(pPager); pPager->changeCountDone = 0; pPager->eState = PAGER_OPEN; }else{ pPager->eState = (isOpen(pPager->jfd) ? PAGER_OPEN : PAGER_READER); } if( USEFETCH(pPager) ) sqlite3OsUnfetch(pPager->fd, 0, 0); pPager->errCode = SQLITE_OK; } pPager->journalOff = 0; pPager->journalHdr = 0; pPager->setMaster = 0; } /* ** This function is called whenever an IOERR or FULL error that requires ** the pager to transition into the ERROR state may ahve occurred. ** The first argument is a pointer to the pager structure, the second ** the error-code about to be returned by a pager API function. The ** value returned is a copy of the second argument to this function. ** ** If the second argument is SQLITE_FULL, SQLITE_IOERR or one of the ** IOERR sub-codes, the pager enters the ERROR state and the error code ** is stored in Pager.errCode. While the pager remains in the ERROR state, ** all major API calls on the Pager will immediately return Pager.errCode. ** ** The ERROR state indicates that the contents of the pager-cache ** cannot be trusted. This state can be cleared by completely discarding ** the contents of the pager-cache. If a transaction was active when ** the persistent error occurred, then the rollback journal may need ** to be replayed to restore the contents of the database file (as if ** it were a hot-journal). */ static int pager_error(Pager *pPager, int rc){ int rc2 = rc & 0xff; assert( rc==SQLITE_OK || !MEMDB ); assert( pPager->errCode==SQLITE_FULL || pPager->errCode==SQLITE_OK || (pPager->errCode & 0xff)==SQLITE_IOERR ); if( rc2==SQLITE_FULL || rc2==SQLITE_IOERR ){ pPager->errCode = rc; pPager->eState = PAGER_ERROR; } return rc; } static int pager_truncate(Pager *pPager, Pgno nPage); /* ** The write transaction open on pPager is being committed (bCommit==1) ** or rolled back (bCommit==0). ** ** Return TRUE if and only if all dirty pages should be flushed to disk. ** ** Rules: ** ** * For non-TEMP databases, always sync to disk. This is necessary ** for transactions to be durable. ** ** * Sync TEMP database only on a COMMIT (not a ROLLBACK) when the backing ** file has been created already (via a spill on pagerStress()) and ** when the number of dirty pages in memory exceeds 25% of the total ** cache size. */ static int pagerFlushOnCommit(Pager *pPager, int bCommit){ if( pPager->tempFile==0 ) return 1; if( !bCommit ) return 0; if( !isOpen(pPager->fd) ) return 0; return (sqlite3PCachePercentDirty(pPager->pPCache)>=25); } /* ** This routine ends a transaction. A transaction is usually ended by ** either a COMMIT or a ROLLBACK operation. This routine may be called ** after rollback of a hot-journal, or if an error occurs while opening ** the journal file or writing the very first journal-header of a ** database transaction. ** ** This routine is never called in PAGER_ERROR state. If it is called ** in PAGER_NONE or PAGER_SHARED state and the lock held is less ** exclusive than a RESERVED lock, it is a no-op. ** ** Otherwise, any active savepoints are released. ** ** If the journal file is open, then it is "finalized". Once a journal ** file has been finalized it is not possible to use it to roll back a ** transaction. Nor will it be considered to be a hot-journal by this ** or any other database connection. Exactly how a journal is finalized ** depends on whether or not the pager is running in exclusive mode and ** the current journal-mode (Pager.journalMode value), as follows: ** ** journalMode==MEMORY ** Journal file descriptor is simply closed. This destroys an ** in-memory journal. ** ** journalMode==TRUNCATE ** Journal file is truncated to zero bytes in size. ** ** journalMode==PERSIST ** The first 28 bytes of the journal file are zeroed. This invalidates ** the first journal header in the file, and hence the entire journal ** file. An invalid journal file cannot be rolled back. ** ** journalMode==DELETE ** The journal file is closed and deleted using sqlite3OsDelete(). ** ** If the pager is running in exclusive mode, this method of finalizing ** the journal file is never used. Instead, if the journalMode is ** DELETE and the pager is in exclusive mode, the method described under ** journalMode==PERSIST is used instead. ** ** After the journal is finalized, the pager moves to PAGER_READER state. ** If running in non-exclusive rollback mode, the lock on the file is ** downgraded to a SHARED_LOCK. ** ** SQLITE_OK is returned if no error occurs. If an error occurs during ** any of the IO operations to finalize the journal file or unlock the ** database then the IO error code is returned to the user. If the ** operation to finalize the journal file fails, then the code still ** tries to unlock the database file if not in exclusive mode. If the ** unlock operation fails as well, then the first error code related ** to the first error encountered (the journal finalization one) is ** returned. */ static int pager_end_transaction(Pager *pPager, int hasMaster, int bCommit){ int rc = SQLITE_OK; /* Error code from journal finalization operation */ int rc2 = SQLITE_OK; /* Error code from db file unlock operation */ /* Do nothing if the pager does not have an open write transaction ** or at least a RESERVED lock. This function may be called when there ** is no write-transaction active but a RESERVED or greater lock is ** held under two circumstances: ** ** 1. After a successful hot-journal rollback, it is called with ** eState==PAGER_NONE and eLock==EXCLUSIVE_LOCK. ** ** 2. If a connection with locking_mode=exclusive holding an EXCLUSIVE ** lock switches back to locking_mode=normal and then executes a ** read-transaction, this function is called with eState==PAGER_READER ** and eLock==EXCLUSIVE_LOCK when the read-transaction is closed. */ assert( assert_pager_state(pPager) ); assert( pPager->eState!=PAGER_ERROR ); if( pPager->eStateeLockjfd) || pPager->pInJournal==0 ); if( isOpen(pPager->jfd) ){ assert( !pagerUseWal(pPager) ); /* Finalize the journal file. */ if( sqlite3JournalIsInMemory(pPager->jfd) ){ /* assert( pPager->journalMode==PAGER_JOURNALMODE_MEMORY ); */ sqlite3OsClose(pPager->jfd); }else if( pPager->journalMode==PAGER_JOURNALMODE_TRUNCATE ){ if( pPager->journalOff==0 ){ rc = SQLITE_OK; }else{ rc = sqlite3OsTruncate(pPager->jfd, 0); if( rc==SQLITE_OK && pPager->fullSync ){ /* Make sure the new file size is written into the inode right away. ** Otherwise the journal might resurrect following a power loss and ** cause the last transaction to roll back. See ** https://bugzilla.mozilla.org/show_bug.cgi?id=1072773 */ rc = sqlite3OsSync(pPager->jfd, pPager->syncFlags); } } pPager->journalOff = 0; }else if( pPager->journalMode==PAGER_JOURNALMODE_PERSIST || (pPager->exclusiveMode && pPager->journalMode!=PAGER_JOURNALMODE_WAL) ){ rc = zeroJournalHdr(pPager, hasMaster||pPager->tempFile); pPager->journalOff = 0; }else{ /* This branch may be executed with Pager.journalMode==MEMORY if ** a hot-journal was just rolled back. In this case the journal ** file should be closed and deleted. If this connection writes to ** the database file, it will do so using an in-memory journal. */ int bDelete = !pPager->tempFile; assert( sqlite3JournalIsInMemory(pPager->jfd)==0 ); assert( pPager->journalMode==PAGER_JOURNALMODE_DELETE || pPager->journalMode==PAGER_JOURNALMODE_MEMORY || pPager->journalMode==PAGER_JOURNALMODE_WAL ); sqlite3OsClose(pPager->jfd); if( bDelete ){ rc = sqlite3OsDelete(pPager->pVfs, pPager->zJournal, pPager->extraSync); } } } #ifdef SQLITE_CHECK_PAGES sqlite3PcacheIterateDirty(pPager->pPCache, pager_set_pagehash); if( pPager->dbSize==0 && sqlite3PcacheRefCount(pPager->pPCache)>0 ){ PgHdr *p = sqlite3PagerLookup(pPager, 1); if( p ){ p->pageHash = 0; sqlite3PagerUnrefNotNull(p); } } #endif sqlite3BitvecDestroy(pPager->pInJournal); pPager->pInJournal = 0; pPager->nRec = 0; if( rc==SQLITE_OK ){ if( pagerFlushOnCommit(pPager, bCommit) ){ sqlite3PcacheCleanAll(pPager->pPCache); }else{ sqlite3PcacheClearWritable(pPager->pPCache); } sqlite3PcacheTruncate(pPager->pPCache, pPager->dbSize); } if( pagerUseWal(pPager) ){ /* Drop the WAL write-lock, if any. Also, if the connection was in ** locking_mode=exclusive mode but is no longer, drop the EXCLUSIVE ** lock held on the database file. */ rc2 = sqlite3WalEndWriteTransaction(pPager->pWal); assert( rc2==SQLITE_OK ); }else if( rc==SQLITE_OK && bCommit && pPager->dbFileSize>pPager->dbSize ){ /* This branch is taken when committing a transaction in rollback-journal ** mode if the database file on disk is larger than the database image. ** At this point the journal has been finalized and the transaction ** successfully committed, but the EXCLUSIVE lock is still held on the ** file. So it is safe to truncate the database file to its minimum ** required size. */ assert( pPager->eLock==EXCLUSIVE_LOCK ); rc = pager_truncate(pPager, pPager->dbSize); } if( rc==SQLITE_OK && bCommit && isOpen(pPager->fd) ){ rc = sqlite3OsFileControl(pPager->fd, SQLITE_FCNTL_COMMIT_PHASETWO, 0); if( rc==SQLITE_NOTFOUND ) rc = SQLITE_OK; } if( !pPager->exclusiveMode && (!pagerUseWal(pPager) || sqlite3WalExclusiveMode(pPager->pWal, 0)) ){ rc2 = pagerUnlockDb(pPager, SHARED_LOCK); pPager->changeCountDone = 0; } pPager->eState = PAGER_READER; pPager->setMaster = 0; return (rc==SQLITE_OK?rc2:rc); } /* ** Execute a rollback if a transaction is active and unlock the ** database file. ** ** If the pager has already entered the ERROR state, do not attempt ** the rollback at this time. Instead, pager_unlock() is called. The ** call to pager_unlock() will discard all in-memory pages, unlock ** the database file and move the pager back to OPEN state. If this ** means that there is a hot-journal left in the file-system, the next ** connection to obtain a shared lock on the pager (which may be this one) ** will roll it back. ** ** If the pager has not already entered the ERROR state, but an IO or ** malloc error occurs during a rollback, then this will itself cause ** the pager to enter the ERROR state. Which will be cleared by the ** call to pager_unlock(), as described above. */ static void pagerUnlockAndRollback(Pager *pPager){ if( pPager->eState!=PAGER_ERROR && pPager->eState!=PAGER_OPEN ){ assert( assert_pager_state(pPager) ); if( pPager->eState>=PAGER_WRITER_LOCKED ){ sqlite3BeginBenignMalloc(); sqlite3PagerRollback(pPager); sqlite3EndBenignMalloc(); }else if( !pPager->exclusiveMode ){ assert( pPager->eState==PAGER_READER ); pager_end_transaction(pPager, 0, 0); } } pager_unlock(pPager); } /* ** Parameter aData must point to a buffer of pPager->pageSize bytes ** of data. Compute and return a checksum based ont the contents of the ** page of data and the current value of pPager->cksumInit. ** ** This is not a real checksum. It is really just the sum of the ** random initial value (pPager->cksumInit) and every 200th byte ** of the page data, starting with byte offset (pPager->pageSize%200). ** Each byte is interpreted as an 8-bit unsigned integer. ** ** Changing the formula used to compute this checksum results in an ** incompatible journal file format. ** ** If journal corruption occurs due to a power failure, the most likely ** scenario is that one end or the other of the record will be changed. ** It is much less likely that the two ends of the journal record will be ** correct and the middle be corrupt. Thus, this "checksum" scheme, ** though fast and simple, catches the mostly likely kind of corruption. */ static u32 pager_cksum(Pager *pPager, const u8 *aData){ u32 cksum = pPager->cksumInit; /* Checksum value to return */ int i = pPager->pageSize-200; /* Loop counter */ while( i>0 ){ cksum += aData[i]; i -= 200; } return cksum; } /* ** Report the current page size and number of reserved bytes back ** to the codec. */ #ifdef SQLITE_HAS_CODEC static void pagerReportSize(Pager *pPager){ if( pPager->xCodecSizeChng ){ pPager->xCodecSizeChng(pPager->pCodec, pPager->pageSize, (int)pPager->nReserve); } } #else # define pagerReportSize(X) /* No-op if we do not support a codec */ #endif #ifdef SQLITE_HAS_CODEC /* ** Make sure the number of reserved bits is the same in the destination ** pager as it is in the source. This comes up when a VACUUM changes the ** number of reserved bits to the "optimal" amount. */ SQLITE_PRIVATE void sqlite3PagerAlignReserve(Pager *pDest, Pager *pSrc){ if( pDest->nReserve!=pSrc->nReserve ){ pDest->nReserve = pSrc->nReserve; pagerReportSize(pDest); } } #endif /* ** Read a single page from either the journal file (if isMainJrnl==1) or ** from the sub-journal (if isMainJrnl==0) and playback that page. ** The page begins at offset *pOffset into the file. The *pOffset ** value is increased to the start of the next page in the journal. ** ** The main rollback journal uses checksums - the statement journal does ** not. ** ** If the page number of the page record read from the (sub-)journal file ** is greater than the current value of Pager.dbSize, then playback is ** skipped and SQLITE_OK is returned. ** ** If pDone is not NULL, then it is a record of pages that have already ** been played back. If the page at *pOffset has already been played back ** (if the corresponding pDone bit is set) then skip the playback. ** Make sure the pDone bit corresponding to the *pOffset page is set ** prior to returning. ** ** If the page record is successfully read from the (sub-)journal file ** and played back, then SQLITE_OK is returned. If an IO error occurs ** while reading the record from the (sub-)journal file or while writing ** to the database file, then the IO error code is returned. If data ** is successfully read from the (sub-)journal file but appears to be ** corrupted, SQLITE_DONE is returned. Data is considered corrupted in ** two circumstances: ** ** * If the record page-number is illegal (0 or PAGER_MJ_PGNO), or ** * If the record is being rolled back from the main journal file ** and the checksum field does not match the record content. ** ** Neither of these two scenarios are possible during a savepoint rollback. ** ** If this is a savepoint rollback, then memory may have to be dynamically ** allocated by this function. If this is the case and an allocation fails, ** SQLITE_NOMEM is returned. */ static int pager_playback_one_page( Pager *pPager, /* The pager being played back */ i64 *pOffset, /* Offset of record to playback */ Bitvec *pDone, /* Bitvec of pages already played back */ int isMainJrnl, /* 1 -> main journal. 0 -> sub-journal. */ int isSavepnt /* True for a savepoint rollback */ ){ int rc; PgHdr *pPg; /* An existing page in the cache */ Pgno pgno; /* The page number of a page in journal */ u32 cksum; /* Checksum used for sanity checking */ char *aData; /* Temporary storage for the page */ sqlite3_file *jfd; /* The file descriptor for the journal file */ int isSynced; /* True if journal page is synced */ assert( (isMainJrnl&~1)==0 ); /* isMainJrnl is 0 or 1 */ assert( (isSavepnt&~1)==0 ); /* isSavepnt is 0 or 1 */ assert( isMainJrnl || pDone ); /* pDone always used on sub-journals */ assert( isSavepnt || pDone==0 ); /* pDone never used on non-savepoint */ aData = pPager->pTmpSpace; assert( aData ); /* Temp storage must have already been allocated */ assert( pagerUseWal(pPager)==0 || (!isMainJrnl && isSavepnt) ); /* Either the state is greater than PAGER_WRITER_CACHEMOD (a transaction ** or savepoint rollback done at the request of the caller) or this is ** a hot-journal rollback. If it is a hot-journal rollback, the pager ** is in state OPEN and holds an EXCLUSIVE lock. Hot-journal rollback ** only reads from the main journal, not the sub-journal. */ assert( pPager->eState>=PAGER_WRITER_CACHEMOD || (pPager->eState==PAGER_OPEN && pPager->eLock==EXCLUSIVE_LOCK) ); assert( pPager->eState>=PAGER_WRITER_CACHEMOD || isMainJrnl ); /* Read the page number and page data from the journal or sub-journal ** file. Return an error code to the caller if an IO error occurs. */ jfd = isMainJrnl ? pPager->jfd : pPager->sjfd; rc = read32bits(jfd, *pOffset, &pgno); if( rc!=SQLITE_OK ) return rc; rc = sqlite3OsRead(jfd, (u8*)aData, pPager->pageSize, (*pOffset)+4); if( rc!=SQLITE_OK ) return rc; *pOffset += pPager->pageSize + 4 + isMainJrnl*4; /* Sanity checking on the page. This is more important that I originally ** thought. If a power failure occurs while the journal is being written, ** it could cause invalid data to be written into the journal. We need to ** detect this invalid data (with high probability) and ignore it. */ if( pgno==0 || pgno==PAGER_MJ_PGNO(pPager) ){ assert( !isSavepnt ); return SQLITE_DONE; } if( pgno>(Pgno)pPager->dbSize || sqlite3BitvecTest(pDone, pgno) ){ return SQLITE_OK; } if( isMainJrnl ){ rc = read32bits(jfd, (*pOffset)-4, &cksum); if( rc ) return rc; if( !isSavepnt && pager_cksum(pPager, (u8*)aData)!=cksum ){ return SQLITE_DONE; } } /* If this page has already been played back before during the current ** rollback, then don't bother to play it back again. */ if( pDone && (rc = sqlite3BitvecSet(pDone, pgno))!=SQLITE_OK ){ return rc; } /* When playing back page 1, restore the nReserve setting */ if( pgno==1 && pPager->nReserve!=((u8*)aData)[20] ){ pPager->nReserve = ((u8*)aData)[20]; pagerReportSize(pPager); } /* If the pager is in CACHEMOD state, then there must be a copy of this ** page in the pager cache. In this case just update the pager cache, ** not the database file. The page is left marked dirty in this case. ** ** An exception to the above rule: If the database is in no-sync mode ** and a page is moved during an incremental vacuum then the page may ** not be in the pager cache. Later: if a malloc() or IO error occurs ** during a Movepage() call, then the page may not be in the cache ** either. So the condition described in the above paragraph is not ** assert()able. ** ** If in WRITER_DBMOD, WRITER_FINISHED or OPEN state, then we update the ** pager cache if it exists and the main file. The page is then marked ** not dirty. Since this code is only executed in PAGER_OPEN state for ** a hot-journal rollback, it is guaranteed that the page-cache is empty ** if the pager is in OPEN state. ** ** Ticket #1171: The statement journal might contain page content that is ** different from the page content at the start of the transaction. ** This occurs when a page is changed prior to the start of a statement ** then changed again within the statement. When rolling back such a ** statement we must not write to the original database unless we know ** for certain that original page contents are synced into the main rollback ** journal. Otherwise, a power loss might leave modified data in the ** database file without an entry in the rollback journal that can ** restore the database to its original form. Two conditions must be ** met before writing to the database files. (1) the database must be ** locked. (2) we know that the original page content is fully synced ** in the main journal either because the page is not in cache or else ** the page is marked as needSync==0. ** ** 2008-04-14: When attempting to vacuum a corrupt database file, it ** is possible to fail a statement on a database that does not yet exist. ** Do not attempt to write if database file has never been opened. */ if( pagerUseWal(pPager) ){ pPg = 0; }else{ pPg = sqlite3PagerLookup(pPager, pgno); } assert( pPg || !MEMDB ); assert( pPager->eState!=PAGER_OPEN || pPg==0 || pPager->tempFile ); PAGERTRACE(("PLAYBACK %d page %d hash(%08x) %s\n", PAGERID(pPager), pgno, pager_datahash(pPager->pageSize, (u8*)aData), (isMainJrnl?"main-journal":"sub-journal") )); if( isMainJrnl ){ isSynced = pPager->noSync || (*pOffset <= pPager->journalHdr); }else{ isSynced = (pPg==0 || 0==(pPg->flags & PGHDR_NEED_SYNC)); } if( isOpen(pPager->fd) && (pPager->eState>=PAGER_WRITER_DBMOD || pPager->eState==PAGER_OPEN) && isSynced ){ i64 ofst = (pgno-1)*(i64)pPager->pageSize; testcase( !isSavepnt && pPg!=0 && (pPg->flags&PGHDR_NEED_SYNC)!=0 ); assert( !pagerUseWal(pPager) ); rc = sqlite3OsWrite(pPager->fd, (u8 *)aData, pPager->pageSize, ofst); if( pgno>pPager->dbFileSize ){ pPager->dbFileSize = pgno; } if( pPager->pBackup ){ CODEC1(pPager, aData, pgno, 3, rc=SQLITE_NOMEM_BKPT); sqlite3BackupUpdate(pPager->pBackup, pgno, (u8*)aData); CODEC2(pPager, aData, pgno, 7, rc=SQLITE_NOMEM_BKPT, aData); } }else if( !isMainJrnl && pPg==0 ){ /* If this is a rollback of a savepoint and data was not written to ** the database and the page is not in-memory, there is a potential ** problem. When the page is next fetched by the b-tree layer, it ** will be read from the database file, which may or may not be ** current. ** ** There are a couple of different ways this can happen. All are quite ** obscure. When running in synchronous mode, this can only happen ** if the page is on the free-list at the start of the transaction, then ** populated, then moved using sqlite3PagerMovepage(). ** ** The solution is to add an in-memory page to the cache containing ** the data just read from the sub-journal. Mark the page as dirty ** and if the pager requires a journal-sync, then mark the page as ** requiring a journal-sync before it is written. */ assert( isSavepnt ); assert( (pPager->doNotSpill & SPILLFLAG_ROLLBACK)==0 ); pPager->doNotSpill |= SPILLFLAG_ROLLBACK; rc = sqlite3PagerGet(pPager, pgno, &pPg, 1); assert( (pPager->doNotSpill & SPILLFLAG_ROLLBACK)!=0 ); pPager->doNotSpill &= ~SPILLFLAG_ROLLBACK; if( rc!=SQLITE_OK ) return rc; sqlite3PcacheMakeDirty(pPg); } if( pPg ){ /* No page should ever be explicitly rolled back that is in use, except ** for page 1 which is held in use in order to keep the lock on the ** database active. However such a page may be rolled back as a result ** of an internal error resulting in an automatic call to ** sqlite3PagerRollback(). */ void *pData; pData = pPg->pData; memcpy(pData, (u8*)aData, pPager->pageSize); pPager->xReiniter(pPg); /* It used to be that sqlite3PcacheMakeClean(pPg) was called here. But ** that call was dangerous and had no detectable benefit since the cache ** is normally cleaned by sqlite3PcacheCleanAll() after rollback and so ** has been removed. */ pager_set_pagehash(pPg); /* If this was page 1, then restore the value of Pager.dbFileVers. ** Do this before any decoding. */ if( pgno==1 ){ memcpy(&pPager->dbFileVers, &((u8*)pData)[24],sizeof(pPager->dbFileVers)); } /* Decode the page just read from disk */ CODEC1(pPager, pData, pPg->pgno, 3, rc=SQLITE_NOMEM_BKPT); sqlite3PcacheRelease(pPg); } return rc; } /* ** Parameter zMaster is the name of a master journal file. A single journal ** file that referred to the master journal file has just been rolled back. ** This routine checks if it is possible to delete the master journal file, ** and does so if it is. ** ** Argument zMaster may point to Pager.pTmpSpace. So that buffer is not ** available for use within this function. ** ** When a master journal file is created, it is populated with the names ** of all of its child journals, one after another, formatted as utf-8 ** encoded text. The end of each child journal file is marked with a ** nul-terminator byte (0x00). i.e. the entire contents of a master journal ** file for a transaction involving two databases might be: ** ** "/home/bill/a.db-journal\x00/home/bill/b.db-journal\x00" ** ** A master journal file may only be deleted once all of its child ** journals have been rolled back. ** ** This function reads the contents of the master-journal file into ** memory and loops through each of the child journal names. For ** each child journal, it checks if: ** ** * if the child journal exists, and if so ** * if the child journal contains a reference to master journal ** file zMaster ** ** If a child journal can be found that matches both of the criteria ** above, this function returns without doing anything. Otherwise, if ** no such child journal can be found, file zMaster is deleted from ** the file-system using sqlite3OsDelete(). ** ** If an IO error within this function, an error code is returned. This ** function allocates memory by calling sqlite3Malloc(). If an allocation ** fails, SQLITE_NOMEM is returned. Otherwise, if no IO or malloc errors ** occur, SQLITE_OK is returned. ** ** TODO: This function allocates a single block of memory to load ** the entire contents of the master journal file. This could be ** a couple of kilobytes or so - potentially larger than the page ** size. */ static int pager_delmaster(Pager *pPager, const char *zMaster){ sqlite3_vfs *pVfs = pPager->pVfs; int rc; /* Return code */ sqlite3_file *pMaster; /* Malloc'd master-journal file descriptor */ sqlite3_file *pJournal; /* Malloc'd child-journal file descriptor */ char *zMasterJournal = 0; /* Contents of master journal file */ i64 nMasterJournal; /* Size of master journal file */ char *zJournal; /* Pointer to one journal within MJ file */ char *zMasterPtr; /* Space to hold MJ filename from a journal file */ int nMasterPtr; /* Amount of space allocated to zMasterPtr[] */ /* Allocate space for both the pJournal and pMaster file descriptors. ** If successful, open the master journal file for reading. */ pMaster = (sqlite3_file *)sqlite3MallocZero(pVfs->szOsFile * 2); pJournal = (sqlite3_file *)(((u8 *)pMaster) + pVfs->szOsFile); if( !pMaster ){ rc = SQLITE_NOMEM_BKPT; }else{ const int flags = (SQLITE_OPEN_READONLY|SQLITE_OPEN_MASTER_JOURNAL); rc = sqlite3OsOpen(pVfs, zMaster, pMaster, flags, 0); } if( rc!=SQLITE_OK ) goto delmaster_out; /* Load the entire master journal file into space obtained from ** sqlite3_malloc() and pointed to by zMasterJournal. Also obtain ** sufficient space (in zMasterPtr) to hold the names of master ** journal files extracted from regular rollback-journals. */ rc = sqlite3OsFileSize(pMaster, &nMasterJournal); if( rc!=SQLITE_OK ) goto delmaster_out; nMasterPtr = pVfs->mxPathname+1; zMasterJournal = sqlite3Malloc(nMasterJournal + nMasterPtr + 1); if( !zMasterJournal ){ rc = SQLITE_NOMEM_BKPT; goto delmaster_out; } zMasterPtr = &zMasterJournal[nMasterJournal+1]; rc = sqlite3OsRead(pMaster, zMasterJournal, (int)nMasterJournal, 0); if( rc!=SQLITE_OK ) goto delmaster_out; zMasterJournal[nMasterJournal] = 0; zJournal = zMasterJournal; while( (zJournal-zMasterJournal)pageSize bytes). ** If the file on disk is currently larger than nPage pages, then use the VFS ** xTruncate() method to truncate it. ** ** Or, it might be the case that the file on disk is smaller than ** nPage pages. Some operating system implementations can get confused if ** you try to truncate a file to some size that is larger than it ** currently is, so detect this case and write a single zero byte to ** the end of the new file instead. ** ** If successful, return SQLITE_OK. If an IO error occurs while modifying ** the database file, return the error code to the caller. */ static int pager_truncate(Pager *pPager, Pgno nPage){ int rc = SQLITE_OK; assert( pPager->eState!=PAGER_ERROR ); assert( pPager->eState!=PAGER_READER ); if( isOpen(pPager->fd) && (pPager->eState>=PAGER_WRITER_DBMOD || pPager->eState==PAGER_OPEN) ){ i64 currentSize, newSize; int szPage = pPager->pageSize; assert( pPager->eLock==EXCLUSIVE_LOCK ); /* TODO: Is it safe to use Pager.dbFileSize here? */ rc = sqlite3OsFileSize(pPager->fd, ¤tSize); newSize = szPage*(i64)nPage; if( rc==SQLITE_OK && currentSize!=newSize ){ if( currentSize>newSize ){ rc = sqlite3OsTruncate(pPager->fd, newSize); }else if( (currentSize+szPage)<=newSize ){ char *pTmp = pPager->pTmpSpace; memset(pTmp, 0, szPage); testcase( (newSize-szPage) == currentSize ); testcase( (newSize-szPage) > currentSize ); rc = sqlite3OsWrite(pPager->fd, pTmp, szPage, newSize-szPage); } if( rc==SQLITE_OK ){ pPager->dbFileSize = nPage; } } } return rc; } /* ** Return a sanitized version of the sector-size of OS file pFile. The ** return value is guaranteed to lie between 32 and MAX_SECTOR_SIZE. */ SQLITE_PRIVATE int sqlite3SectorSize(sqlite3_file *pFile){ int iRet = sqlite3OsSectorSize(pFile); if( iRet<32 ){ iRet = 512; }else if( iRet>MAX_SECTOR_SIZE ){ assert( MAX_SECTOR_SIZE>=512 ); iRet = MAX_SECTOR_SIZE; } return iRet; } /* ** Set the value of the Pager.sectorSize variable for the given ** pager based on the value returned by the xSectorSize method ** of the open database file. The sector size will be used ** to determine the size and alignment of journal header and ** master journal pointers within created journal files. ** ** For temporary files the effective sector size is always 512 bytes. ** ** Otherwise, for non-temporary files, the effective sector size is ** the value returned by the xSectorSize() method rounded up to 32 if ** it is less than 32, or rounded down to MAX_SECTOR_SIZE if it ** is greater than MAX_SECTOR_SIZE. ** ** If the file has the SQLITE_IOCAP_POWERSAFE_OVERWRITE property, then set ** the effective sector size to its minimum value (512). The purpose of ** pPager->sectorSize is to define the "blast radius" of bytes that ** might change if a crash occurs while writing to a single byte in ** that range. But with POWERSAFE_OVERWRITE, the blast radius is zero ** (that is what POWERSAFE_OVERWRITE means), so we minimize the sector ** size. For backwards compatibility of the rollback journal file format, ** we cannot reduce the effective sector size below 512. */ static void setSectorSize(Pager *pPager){ assert( isOpen(pPager->fd) || pPager->tempFile ); if( pPager->tempFile || (sqlite3OsDeviceCharacteristics(pPager->fd) & SQLITE_IOCAP_POWERSAFE_OVERWRITE)!=0 ){ /* Sector size doesn't matter for temporary files. Also, the file ** may not have been opened yet, in which case the OsSectorSize() ** call will segfault. */ pPager->sectorSize = 512; }else{ pPager->sectorSize = sqlite3SectorSize(pPager->fd); } } /* ** Playback the journal and thus restore the database file to ** the state it was in before we started making changes. ** ** The journal file format is as follows: ** ** (1) 8 byte prefix. A copy of aJournalMagic[]. ** (2) 4 byte big-endian integer which is the number of valid page records ** in the journal. If this value is 0xffffffff, then compute the ** number of page records from the journal size. ** (3) 4 byte big-endian integer which is the initial value for the ** sanity checksum. ** (4) 4 byte integer which is the number of pages to truncate the ** database to during a rollback. ** (5) 4 byte big-endian integer which is the sector size. The header ** is this many bytes in size. ** (6) 4 byte big-endian integer which is the page size. ** (7) zero padding out to the next sector size. ** (8) Zero or more pages instances, each as follows: ** + 4 byte page number. ** + pPager->pageSize bytes of data. ** + 4 byte checksum ** ** When we speak of the journal header, we mean the first 7 items above. ** Each entry in the journal is an instance of the 8th item. ** ** Call the value from the second bullet "nRec". nRec is the number of ** valid page entries in the journal. In most cases, you can compute the ** value of nRec from the size of the journal file. But if a power ** failure occurred while the journal was being written, it could be the ** case that the size of the journal file had already been increased but ** the extra entries had not yet made it safely to disk. In such a case, ** the value of nRec computed from the file size would be too large. For ** that reason, we always use the nRec value in the header. ** ** If the nRec value is 0xffffffff it means that nRec should be computed ** from the file size. This value is used when the user selects the ** no-sync option for the journal. A power failure could lead to corruption ** in this case. But for things like temporary table (which will be ** deleted when the power is restored) we don't care. ** ** If the file opened as the journal file is not a well-formed ** journal file then all pages up to the first corrupted page are rolled ** back (or no pages if the journal header is corrupted). The journal file ** is then deleted and SQLITE_OK returned, just as if no corruption had ** been encountered. ** ** If an I/O or malloc() error occurs, the journal-file is not deleted ** and an error code is returned. ** ** The isHot parameter indicates that we are trying to rollback a journal ** that might be a hot journal. Or, it could be that the journal is ** preserved because of JOURNALMODE_PERSIST or JOURNALMODE_TRUNCATE. ** If the journal really is hot, reset the pager cache prior rolling ** back any content. If the journal is merely persistent, no reset is ** needed. */ static int pager_playback(Pager *pPager, int isHot){ sqlite3_vfs *pVfs = pPager->pVfs; i64 szJ; /* Size of the journal file in bytes */ u32 nRec; /* Number of Records in the journal */ u32 u; /* Unsigned loop counter */ Pgno mxPg = 0; /* Size of the original file in pages */ int rc; /* Result code of a subroutine */ int res = 1; /* Value returned by sqlite3OsAccess() */ char *zMaster = 0; /* Name of master journal file if any */ int needPagerReset; /* True to reset page prior to first page rollback */ int nPlayback = 0; /* Total number of pages restored from journal */ /* Figure out how many records are in the journal. Abort early if ** the journal is empty. */ assert( isOpen(pPager->jfd) ); rc = sqlite3OsFileSize(pPager->jfd, &szJ); if( rc!=SQLITE_OK ){ goto end_playback; } /* Read the master journal name from the journal, if it is present. ** If a master journal file name is specified, but the file is not ** present on disk, then the journal is not hot and does not need to be ** played back. ** ** TODO: Technically the following is an error because it assumes that ** buffer Pager.pTmpSpace is (mxPathname+1) bytes or larger. i.e. that ** (pPager->pageSize >= pPager->pVfs->mxPathname+1). Using os_unix.c, ** mxPathname is 512, which is the same as the minimum allowable value ** for pageSize. */ zMaster = pPager->pTmpSpace; rc = readMasterJournal(pPager->jfd, zMaster, pPager->pVfs->mxPathname+1); if( rc==SQLITE_OK && zMaster[0] ){ rc = sqlite3OsAccess(pVfs, zMaster, SQLITE_ACCESS_EXISTS, &res); } zMaster = 0; if( rc!=SQLITE_OK || !res ){ goto end_playback; } pPager->journalOff = 0; needPagerReset = isHot; /* This loop terminates either when a readJournalHdr() or ** pager_playback_one_page() call returns SQLITE_DONE or an IO error ** occurs. */ while( 1 ){ /* Read the next journal header from the journal file. If there are ** not enough bytes left in the journal file for a complete header, or ** it is corrupted, then a process must have failed while writing it. ** This indicates nothing more needs to be rolled back. */ rc = readJournalHdr(pPager, isHot, szJ, &nRec, &mxPg); if( rc!=SQLITE_OK ){ if( rc==SQLITE_DONE ){ rc = SQLITE_OK; } goto end_playback; } /* If nRec is 0xffffffff, then this journal was created by a process ** working in no-sync mode. This means that the rest of the journal ** file consists of pages, there are no more journal headers. Compute ** the value of nRec based on this assumption. */ if( nRec==0xffffffff ){ assert( pPager->journalOff==JOURNAL_HDR_SZ(pPager) ); nRec = (int)((szJ - JOURNAL_HDR_SZ(pPager))/JOURNAL_PG_SZ(pPager)); } /* If nRec is 0 and this rollback is of a transaction created by this ** process and if this is the final header in the journal, then it means ** that this part of the journal was being filled but has not yet been ** synced to disk. Compute the number of pages based on the remaining ** size of the file. ** ** The third term of the test was added to fix ticket #2565. ** When rolling back a hot journal, nRec==0 always means that the next ** chunk of the journal contains zero pages to be rolled back. But ** when doing a ROLLBACK and the nRec==0 chunk is the last chunk in ** the journal, it means that the journal might contain additional ** pages that need to be rolled back and that the number of pages ** should be computed based on the journal file size. */ if( nRec==0 && !isHot && pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff ){ nRec = (int)((szJ - pPager->journalOff) / JOURNAL_PG_SZ(pPager)); } /* If this is the first header read from the journal, truncate the ** database file back to its original size. */ if( pPager->journalOff==JOURNAL_HDR_SZ(pPager) ){ rc = pager_truncate(pPager, mxPg); if( rc!=SQLITE_OK ){ goto end_playback; } pPager->dbSize = mxPg; } /* Copy original pages out of the journal and back into the ** database file and/or page cache. */ for(u=0; ujournalOff,0,1,0); if( rc==SQLITE_OK ){ nPlayback++; }else{ if( rc==SQLITE_DONE ){ pPager->journalOff = szJ; break; }else if( rc==SQLITE_IOERR_SHORT_READ ){ /* If the journal has been truncated, simply stop reading and ** processing the journal. This might happen if the journal was ** not completely written and synced prior to a crash. In that ** case, the database should have never been written in the ** first place so it is OK to simply abandon the rollback. */ rc = SQLITE_OK; goto end_playback; }else{ /* If we are unable to rollback, quit and return the error ** code. This will cause the pager to enter the error state ** so that no further harm will be done. Perhaps the next ** process to come along will be able to rollback the database. */ goto end_playback; } } } } /*NOTREACHED*/ assert( 0 ); end_playback: /* Following a rollback, the database file should be back in its original ** state prior to the start of the transaction, so invoke the ** SQLITE_FCNTL_DB_UNCHANGED file-control method to disable the ** assertion that the transaction counter was modified. */ #ifdef SQLITE_DEBUG if( pPager->fd->pMethods ){ sqlite3OsFileControlHint(pPager->fd,SQLITE_FCNTL_DB_UNCHANGED,0); } #endif /* If this playback is happening automatically as a result of an IO or ** malloc error that occurred after the change-counter was updated but ** before the transaction was committed, then the change-counter ** modification may just have been reverted. If this happens in exclusive ** mode, then subsequent transactions performed by the connection will not ** update the change-counter at all. This may lead to cache inconsistency ** problems for other processes at some point in the future. So, just ** in case this has happened, clear the changeCountDone flag now. */ pPager->changeCountDone = pPager->tempFile; if( rc==SQLITE_OK ){ zMaster = pPager->pTmpSpace; rc = readMasterJournal(pPager->jfd, zMaster, pPager->pVfs->mxPathname+1); testcase( rc!=SQLITE_OK ); } if( rc==SQLITE_OK && (pPager->eState>=PAGER_WRITER_DBMOD || pPager->eState==PAGER_OPEN) ){ rc = sqlite3PagerSync(pPager, 0); } if( rc==SQLITE_OK ){ rc = pager_end_transaction(pPager, zMaster[0]!='\0', 0); testcase( rc!=SQLITE_OK ); } if( rc==SQLITE_OK && zMaster[0] && res ){ /* If there was a master journal and this routine will return success, ** see if it is possible to delete the master journal. */ rc = pager_delmaster(pPager, zMaster); testcase( rc!=SQLITE_OK ); } if( isHot && nPlayback ){ sqlite3_log(SQLITE_NOTICE_RECOVER_ROLLBACK, "recovered %d pages from %s", nPlayback, pPager->zJournal); } /* The Pager.sectorSize variable may have been updated while rolling ** back a journal created by a process with a different sector size ** value. Reset it to the correct value for this process. */ setSectorSize(pPager); return rc; } /* ** Read the content for page pPg out of the database file and into ** pPg->pData. A shared lock or greater must be held on the database ** file before this function is called. ** ** If page 1 is read, then the value of Pager.dbFileVers[] is set to ** the value read from the database file. ** ** If an IO error occurs, then the IO error is returned to the caller. ** Otherwise, SQLITE_OK is returned. */ static int readDbPage(PgHdr *pPg, u32 iFrame){ Pager *pPager = pPg->pPager; /* Pager object associated with page pPg */ Pgno pgno = pPg->pgno; /* Page number to read */ int rc = SQLITE_OK; /* Return code */ int pgsz = pPager->pageSize; /* Number of bytes to read */ assert( pPager->eState>=PAGER_READER && !MEMDB ); assert( isOpen(pPager->fd) ); #ifndef SQLITE_OMIT_WAL if( iFrame ){ /* Try to pull the page from the write-ahead log. */ rc = sqlite3WalReadFrame(pPager->pWal, iFrame, pgsz, pPg->pData); }else #endif { i64 iOffset = (pgno-1)*(i64)pPager->pageSize; rc = sqlite3OsRead(pPager->fd, pPg->pData, pgsz, iOffset); if( rc==SQLITE_IOERR_SHORT_READ ){ rc = SQLITE_OK; } } if( pgno==1 ){ if( rc ){ /* If the read is unsuccessful, set the dbFileVers[] to something ** that will never be a valid file version. dbFileVers[] is a copy ** of bytes 24..39 of the database. Bytes 28..31 should always be ** zero or the size of the database in page. Bytes 32..35 and 35..39 ** should be page numbers which are never 0xffffffff. So filling ** pPager->dbFileVers[] with all 0xff bytes should suffice. ** ** For an encrypted database, the situation is more complex: bytes ** 24..39 of the database are white noise. But the probability of ** white noise equaling 16 bytes of 0xff is vanishingly small so ** we should still be ok. */ memset(pPager->dbFileVers, 0xff, sizeof(pPager->dbFileVers)); }else{ u8 *dbFileVers = &((u8*)pPg->pData)[24]; memcpy(&pPager->dbFileVers, dbFileVers, sizeof(pPager->dbFileVers)); } } CODEC1(pPager, pPg->pData, pgno, 3, rc = SQLITE_NOMEM_BKPT); PAGER_INCR(sqlite3_pager_readdb_count); PAGER_INCR(pPager->nRead); IOTRACE(("PGIN %p %d\n", pPager, pgno)); PAGERTRACE(("FETCH %d page %d hash(%08x)\n", PAGERID(pPager), pgno, pager_pagehash(pPg))); return rc; } /* ** Update the value of the change-counter at offsets 24 and 92 in ** the header and the sqlite version number at offset 96. ** ** This is an unconditional update. See also the pager_incr_changecounter() ** routine which only updates the change-counter if the update is actually ** needed, as determined by the pPager->changeCountDone state variable. */ static void pager_write_changecounter(PgHdr *pPg){ u32 change_counter; /* Increment the value just read and write it back to byte 24. */ change_counter = sqlite3Get4byte((u8*)pPg->pPager->dbFileVers)+1; put32bits(((char*)pPg->pData)+24, change_counter); /* Also store the SQLite version number in bytes 96..99 and in ** bytes 92..95 store the change counter for which the version number ** is valid. */ put32bits(((char*)pPg->pData)+92, change_counter); put32bits(((char*)pPg->pData)+96, SQLITE_VERSION_NUMBER); } #ifndef SQLITE_OMIT_WAL /* ** This function is invoked once for each page that has already been ** written into the log file when a WAL transaction is rolled back. ** Parameter iPg is the page number of said page. The pCtx argument ** is actually a pointer to the Pager structure. ** ** If page iPg is present in the cache, and has no outstanding references, ** it is discarded. Otherwise, if there are one or more outstanding ** references, the page content is reloaded from the database. If the ** attempt to reload content from the database is required and fails, ** return an SQLite error code. Otherwise, SQLITE_OK. */ static int pagerUndoCallback(void *pCtx, Pgno iPg){ int rc = SQLITE_OK; Pager *pPager = (Pager *)pCtx; PgHdr *pPg; assert( pagerUseWal(pPager) ); pPg = sqlite3PagerLookup(pPager, iPg); if( pPg ){ if( sqlite3PcachePageRefcount(pPg)==1 ){ sqlite3PcacheDrop(pPg); }else{ u32 iFrame = 0; rc = sqlite3WalFindFrame(pPager->pWal, pPg->pgno, &iFrame); if( rc==SQLITE_OK ){ rc = readDbPage(pPg, iFrame); } if( rc==SQLITE_OK ){ pPager->xReiniter(pPg); } sqlite3PagerUnrefNotNull(pPg); } } /* Normally, if a transaction is rolled back, any backup processes are ** updated as data is copied out of the rollback journal and into the ** database. This is not generally possible with a WAL database, as ** rollback involves simply truncating the log file. Therefore, if one ** or more frames have already been written to the log (and therefore ** also copied into the backup databases) as part of this transaction, ** the backups must be restarted. */ sqlite3BackupRestart(pPager->pBackup); return rc; } /* ** This function is called to rollback a transaction on a WAL database. */ static int pagerRollbackWal(Pager *pPager){ int rc; /* Return Code */ PgHdr *pList; /* List of dirty pages to revert */ /* For all pages in the cache that are currently dirty or have already ** been written (but not committed) to the log file, do one of the ** following: ** ** + Discard the cached page (if refcount==0), or ** + Reload page content from the database (if refcount>0). */ pPager->dbSize = pPager->dbOrigSize; rc = sqlite3WalUndo(pPager->pWal, pagerUndoCallback, (void *)pPager); pList = sqlite3PcacheDirtyList(pPager->pPCache); while( pList && rc==SQLITE_OK ){ PgHdr *pNext = pList->pDirty; rc = pagerUndoCallback((void *)pPager, pList->pgno); pList = pNext; } return rc; } /* ** This function is a wrapper around sqlite3WalFrames(). As well as logging ** the contents of the list of pages headed by pList (connected by pDirty), ** this function notifies any active backup processes that the pages have ** changed. ** ** The list of pages passed into this routine is always sorted by page number. ** Hence, if page 1 appears anywhere on the list, it will be the first page. */ static int pagerWalFrames( Pager *pPager, /* Pager object */ PgHdr *pList, /* List of frames to log */ Pgno nTruncate, /* Database size after this commit */ int isCommit /* True if this is a commit */ ){ int rc; /* Return code */ int nList; /* Number of pages in pList */ PgHdr *p; /* For looping over pages */ assert( pPager->pWal ); assert( pList ); #ifdef SQLITE_DEBUG /* Verify that the page list is in accending order */ for(p=pList; p && p->pDirty; p=p->pDirty){ assert( p->pgno < p->pDirty->pgno ); } #endif assert( pList->pDirty==0 || isCommit ); if( isCommit ){ /* If a WAL transaction is being committed, there is no point in writing ** any pages with page numbers greater than nTruncate into the WAL file. ** They will never be read by any client. So remove them from the pDirty ** list here. */ PgHdr **ppNext = &pList; nList = 0; for(p=pList; (*ppNext = p)!=0; p=p->pDirty){ if( p->pgno<=nTruncate ){ ppNext = &p->pDirty; nList++; } } assert( pList ); }else{ nList = 1; } pPager->aStat[PAGER_STAT_WRITE] += nList; if( pList->pgno==1 ) pager_write_changecounter(pList); rc = sqlite3WalFrames(pPager->pWal, pPager->pageSize, pList, nTruncate, isCommit, pPager->walSyncFlags ); if( rc==SQLITE_OK && pPager->pBackup ){ for(p=pList; p; p=p->pDirty){ sqlite3BackupUpdate(pPager->pBackup, p->pgno, (u8 *)p->pData); } } #ifdef SQLITE_CHECK_PAGES pList = sqlite3PcacheDirtyList(pPager->pPCache); for(p=pList; p; p=p->pDirty){ pager_set_pagehash(p); } #endif return rc; } /* ** Begin a read transaction on the WAL. ** ** This routine used to be called "pagerOpenSnapshot()" because it essentially ** makes a snapshot of the database at the current point in time and preserves ** that snapshot for use by the reader in spite of concurrently changes by ** other writers or checkpointers. */ static int pagerBeginReadTransaction(Pager *pPager){ int rc; /* Return code */ int changed = 0; /* True if cache must be reset */ assert( pagerUseWal(pPager) ); assert( pPager->eState==PAGER_OPEN || pPager->eState==PAGER_READER ); /* sqlite3WalEndReadTransaction() was not called for the previous ** transaction in locking_mode=EXCLUSIVE. So call it now. If we ** are in locking_mode=NORMAL and EndRead() was previously called, ** the duplicate call is harmless. */ sqlite3WalEndReadTransaction(pPager->pWal); rc = sqlite3WalBeginReadTransaction(pPager->pWal, &changed); if( rc!=SQLITE_OK || changed ){ pager_reset(pPager); if( USEFETCH(pPager) ) sqlite3OsUnfetch(pPager->fd, 0, 0); } return rc; } #endif /* ** This function is called as part of the transition from PAGER_OPEN ** to PAGER_READER state to determine the size of the database file ** in pages (assuming the page size currently stored in Pager.pageSize). ** ** If no error occurs, SQLITE_OK is returned and the size of the database ** in pages is stored in *pnPage. Otherwise, an error code (perhaps ** SQLITE_IOERR_FSTAT) is returned and *pnPage is left unmodified. */ static int pagerPagecount(Pager *pPager, Pgno *pnPage){ Pgno nPage; /* Value to return via *pnPage */ /* Query the WAL sub-system for the database size. The WalDbsize() ** function returns zero if the WAL is not open (i.e. Pager.pWal==0), or ** if the database size is not available. The database size is not ** available from the WAL sub-system if the log file is empty or ** contains no valid committed transactions. */ assert( pPager->eState==PAGER_OPEN ); assert( pPager->eLock>=SHARED_LOCK ); assert( isOpen(pPager->fd) ); assert( pPager->tempFile==0 ); nPage = sqlite3WalDbsize(pPager->pWal); /* If the number of pages in the database is not available from the ** WAL sub-system, determine the page counte based on the size of ** the database file. If the size of the database file is not an ** integer multiple of the page-size, round up the result. */ if( nPage==0 && ALWAYS(isOpen(pPager->fd)) ){ i64 n = 0; /* Size of db file in bytes */ int rc = sqlite3OsFileSize(pPager->fd, &n); if( rc!=SQLITE_OK ){ return rc; } nPage = (Pgno)((n+pPager->pageSize-1) / pPager->pageSize); } /* If the current number of pages in the file is greater than the ** configured maximum pager number, increase the allowed limit so ** that the file can be read. */ if( nPage>pPager->mxPgno ){ pPager->mxPgno = (Pgno)nPage; } *pnPage = nPage; return SQLITE_OK; } #ifndef SQLITE_OMIT_WAL /* ** Check if the *-wal file that corresponds to the database opened by pPager ** exists if the database is not empy, or verify that the *-wal file does ** not exist (by deleting it) if the database file is empty. ** ** If the database is not empty and the *-wal file exists, open the pager ** in WAL mode. If the database is empty or if no *-wal file exists and ** if no error occurs, make sure Pager.journalMode is not set to ** PAGER_JOURNALMODE_WAL. ** ** Return SQLITE_OK or an error code. ** ** The caller must hold a SHARED lock on the database file to call this ** function. Because an EXCLUSIVE lock on the db file is required to delete ** a WAL on a none-empty database, this ensures there is no race condition ** between the xAccess() below and an xDelete() being executed by some ** other connection. */ static int pagerOpenWalIfPresent(Pager *pPager){ int rc = SQLITE_OK; assert( pPager->eState==PAGER_OPEN ); assert( pPager->eLock>=SHARED_LOCK ); if( !pPager->tempFile ){ int isWal; /* True if WAL file exists */ Pgno nPage; /* Size of the database file */ rc = pagerPagecount(pPager, &nPage); if( rc ) return rc; if( nPage==0 ){ rc = sqlite3OsDelete(pPager->pVfs, pPager->zWal, 0); if( rc==SQLITE_IOERR_DELETE_NOENT ) rc = SQLITE_OK; isWal = 0; }else{ rc = sqlite3OsAccess( pPager->pVfs, pPager->zWal, SQLITE_ACCESS_EXISTS, &isWal ); } if( rc==SQLITE_OK ){ if( isWal ){ testcase( sqlite3PcachePagecount(pPager->pPCache)==0 ); rc = sqlite3PagerOpenWal(pPager, 0); }else if( pPager->journalMode==PAGER_JOURNALMODE_WAL ){ pPager->journalMode = PAGER_JOURNALMODE_DELETE; } } } return rc; } #endif /* ** Playback savepoint pSavepoint. Or, if pSavepoint==NULL, then playback ** the entire master journal file. The case pSavepoint==NULL occurs when ** a ROLLBACK TO command is invoked on a SAVEPOINT that is a transaction ** savepoint. ** ** When pSavepoint is not NULL (meaning a non-transaction savepoint is ** being rolled back), then the rollback consists of up to three stages, ** performed in the order specified: ** ** * Pages are played back from the main journal starting at byte ** offset PagerSavepoint.iOffset and continuing to ** PagerSavepoint.iHdrOffset, or to the end of the main journal ** file if PagerSavepoint.iHdrOffset is zero. ** ** * If PagerSavepoint.iHdrOffset is not zero, then pages are played ** back starting from the journal header immediately following ** PagerSavepoint.iHdrOffset to the end of the main journal file. ** ** * Pages are then played back from the sub-journal file, starting ** with the PagerSavepoint.iSubRec and continuing to the end of ** the journal file. ** ** Throughout the rollback process, each time a page is rolled back, the ** corresponding bit is set in a bitvec structure (variable pDone in the ** implementation below). This is used to ensure that a page is only ** rolled back the first time it is encountered in either journal. ** ** If pSavepoint is NULL, then pages are only played back from the main ** journal file. There is no need for a bitvec in this case. ** ** In either case, before playback commences the Pager.dbSize variable ** is reset to the value that it held at the start of the savepoint ** (or transaction). No page with a page-number greater than this value ** is played back. If one is encountered it is simply skipped. */ static int pagerPlaybackSavepoint(Pager *pPager, PagerSavepoint *pSavepoint){ i64 szJ; /* Effective size of the main journal */ i64 iHdrOff; /* End of first segment of main-journal records */ int rc = SQLITE_OK; /* Return code */ Bitvec *pDone = 0; /* Bitvec to ensure pages played back only once */ assert( pPager->eState!=PAGER_ERROR ); assert( pPager->eState>=PAGER_WRITER_LOCKED ); /* Allocate a bitvec to use to store the set of pages rolled back */ if( pSavepoint ){ pDone = sqlite3BitvecCreate(pSavepoint->nOrig); if( !pDone ){ return SQLITE_NOMEM_BKPT; } } /* Set the database size back to the value it was before the savepoint ** being reverted was opened. */ pPager->dbSize = pSavepoint ? pSavepoint->nOrig : pPager->dbOrigSize; pPager->changeCountDone = pPager->tempFile; if( !pSavepoint && pagerUseWal(pPager) ){ return pagerRollbackWal(pPager); } /* Use pPager->journalOff as the effective size of the main rollback ** journal. The actual file might be larger than this in ** PAGER_JOURNALMODE_TRUNCATE or PAGER_JOURNALMODE_PERSIST. But anything ** past pPager->journalOff is off-limits to us. */ szJ = pPager->journalOff; assert( pagerUseWal(pPager)==0 || szJ==0 ); /* Begin by rolling back records from the main journal starting at ** PagerSavepoint.iOffset and continuing to the next journal header. ** There might be records in the main journal that have a page number ** greater than the current database size (pPager->dbSize) but those ** will be skipped automatically. Pages are added to pDone as they ** are played back. */ if( pSavepoint && !pagerUseWal(pPager) ){ iHdrOff = pSavepoint->iHdrOffset ? pSavepoint->iHdrOffset : szJ; pPager->journalOff = pSavepoint->iOffset; while( rc==SQLITE_OK && pPager->journalOffjournalOff, pDone, 1, 1); } assert( rc!=SQLITE_DONE ); }else{ pPager->journalOff = 0; } /* Continue rolling back records out of the main journal starting at ** the first journal header seen and continuing until the effective end ** of the main journal file. Continue to skip out-of-range pages and ** continue adding pages rolled back to pDone. */ while( rc==SQLITE_OK && pPager->journalOffjournalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff" ** test is related to ticket #2565. See the discussion in the ** pager_playback() function for additional information. */ if( nJRec==0 && pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff ){ nJRec = (u32)((szJ - pPager->journalOff)/JOURNAL_PG_SZ(pPager)); } for(ii=0; rc==SQLITE_OK && iijournalOffjournalOff, pDone, 1, 1); } assert( rc!=SQLITE_DONE ); } assert( rc!=SQLITE_OK || pPager->journalOff>=szJ ); /* Finally, rollback pages from the sub-journal. Page that were ** previously rolled back out of the main journal (and are hence in pDone) ** will be skipped. Out-of-range pages are also skipped. */ if( pSavepoint ){ u32 ii; /* Loop counter */ i64 offset = (i64)pSavepoint->iSubRec*(4+pPager->pageSize); if( pagerUseWal(pPager) ){ rc = sqlite3WalSavepointUndo(pPager->pWal, pSavepoint->aWalData); } for(ii=pSavepoint->iSubRec; rc==SQLITE_OK && iinSubRec; ii++){ assert( offset==(i64)ii*(4+pPager->pageSize) ); rc = pager_playback_one_page(pPager, &offset, pDone, 0, 1); } assert( rc!=SQLITE_DONE ); } sqlite3BitvecDestroy(pDone); if( rc==SQLITE_OK ){ pPager->journalOff = szJ; } return rc; } /* ** Change the maximum number of in-memory pages that are allowed ** before attempting to recycle clean and unused pages. */ SQLITE_PRIVATE void sqlite3PagerSetCachesize(Pager *pPager, int mxPage){ sqlite3PcacheSetCachesize(pPager->pPCache, mxPage); } /* ** Change the maximum number of in-memory pages that are allowed ** before attempting to spill pages to journal. */ SQLITE_PRIVATE int sqlite3PagerSetSpillsize(Pager *pPager, int mxPage){ return sqlite3PcacheSetSpillsize(pPager->pPCache, mxPage); } /* ** Invoke SQLITE_FCNTL_MMAP_SIZE based on the current value of szMmap. */ static void pagerFixMaplimit(Pager *pPager){ #if SQLITE_MAX_MMAP_SIZE>0 sqlite3_file *fd = pPager->fd; if( isOpen(fd) && fd->pMethods->iVersion>=3 ){ sqlite3_int64 sz; sz = pPager->szMmap; pPager->bUseFetch = (sz>0); sqlite3OsFileControlHint(pPager->fd, SQLITE_FCNTL_MMAP_SIZE, &sz); } #endif } /* ** Change the maximum size of any memory mapping made of the database file. */ SQLITE_PRIVATE void sqlite3PagerSetMmapLimit(Pager *pPager, sqlite3_int64 szMmap){ pPager->szMmap = szMmap; pagerFixMaplimit(pPager); } /* ** Free as much memory as possible from the pager. */ SQLITE_PRIVATE void sqlite3PagerShrink(Pager *pPager){ sqlite3PcacheShrink(pPager->pPCache); } /* ** Adjust settings of the pager to those specified in the pgFlags parameter. ** ** The "level" in pgFlags & PAGER_SYNCHRONOUS_MASK sets the robustness ** of the database to damage due to OS crashes or power failures by ** changing the number of syncs()s when writing the journals. ** There are four levels: ** ** OFF sqlite3OsSync() is never called. This is the default ** for temporary and transient files. ** ** NORMAL The journal is synced once before writes begin on the ** database. This is normally adequate protection, but ** it is theoretically possible, though very unlikely, ** that an inopertune power failure could leave the journal ** in a state which would cause damage to the database ** when it is rolled back. ** ** FULL The journal is synced twice before writes begin on the ** database (with some additional information - the nRec field ** of the journal header - being written in between the two ** syncs). If we assume that writing a ** single disk sector is atomic, then this mode provides ** assurance that the journal will not be corrupted to the ** point of causing damage to the database during rollback. ** ** EXTRA This is like FULL except that is also syncs the directory ** that contains the rollback journal after the rollback ** journal is unlinked. ** ** The above is for a rollback-journal mode. For WAL mode, OFF continues ** to mean that no syncs ever occur. NORMAL means that the WAL is synced ** prior to the start of checkpoint and that the database file is synced ** at the conclusion of the checkpoint if the entire content of the WAL ** was written back into the database. But no sync operations occur for ** an ordinary commit in NORMAL mode with WAL. FULL means that the WAL ** file is synced following each commit operation, in addition to the ** syncs associated with NORMAL. There is no difference between FULL ** and EXTRA for WAL mode. ** ** Do not confuse synchronous=FULL with SQLITE_SYNC_FULL. The ** SQLITE_SYNC_FULL macro means to use the MacOSX-style full-fsync ** using fcntl(F_FULLFSYNC). SQLITE_SYNC_NORMAL means to do an ** ordinary fsync() call. There is no difference between SQLITE_SYNC_FULL ** and SQLITE_SYNC_NORMAL on platforms other than MacOSX. But the ** synchronous=FULL versus synchronous=NORMAL setting determines when ** the xSync primitive is called and is relevant to all platforms. ** ** Numeric values associated with these states are OFF==1, NORMAL=2, ** and FULL=3. */ #ifndef SQLITE_OMIT_PAGER_PRAGMAS SQLITE_PRIVATE void sqlite3PagerSetFlags( Pager *pPager, /* The pager to set safety level for */ unsigned pgFlags /* Various flags */ ){ unsigned level = pgFlags & PAGER_SYNCHRONOUS_MASK; if( pPager->tempFile ){ pPager->noSync = 1; pPager->fullSync = 0; pPager->extraSync = 0; }else{ pPager->noSync = level==PAGER_SYNCHRONOUS_OFF ?1:0; pPager->fullSync = level>=PAGER_SYNCHRONOUS_FULL ?1:0; pPager->extraSync = level==PAGER_SYNCHRONOUS_EXTRA ?1:0; } if( pPager->noSync ){ pPager->syncFlags = 0; pPager->ckptSyncFlags = 0; }else if( pgFlags & PAGER_FULLFSYNC ){ pPager->syncFlags = SQLITE_SYNC_FULL; pPager->ckptSyncFlags = SQLITE_SYNC_FULL; }else if( pgFlags & PAGER_CKPT_FULLFSYNC ){ pPager->syncFlags = SQLITE_SYNC_NORMAL; pPager->ckptSyncFlags = SQLITE_SYNC_FULL; }else{ pPager->syncFlags = SQLITE_SYNC_NORMAL; pPager->ckptSyncFlags = SQLITE_SYNC_NORMAL; } pPager->walSyncFlags = pPager->syncFlags; if( pPager->fullSync ){ pPager->walSyncFlags |= WAL_SYNC_TRANSACTIONS; } if( pgFlags & PAGER_CACHESPILL ){ pPager->doNotSpill &= ~SPILLFLAG_OFF; }else{ pPager->doNotSpill |= SPILLFLAG_OFF; } } #endif /* ** The following global variable is incremented whenever the library ** attempts to open a temporary file. This information is used for ** testing and analysis only. */ #ifdef SQLITE_TEST SQLITE_API int sqlite3_opentemp_count = 0; #endif /* ** Open a temporary file. ** ** Write the file descriptor into *pFile. Return SQLITE_OK on success ** or some other error code if we fail. The OS will automatically ** delete the temporary file when it is closed. ** ** The flags passed to the VFS layer xOpen() call are those specified ** by parameter vfsFlags ORed with the following: ** ** SQLITE_OPEN_READWRITE ** SQLITE_OPEN_CREATE ** SQLITE_OPEN_EXCLUSIVE ** SQLITE_OPEN_DELETEONCLOSE */ static int pagerOpentemp( Pager *pPager, /* The pager object */ sqlite3_file *pFile, /* Write the file descriptor here */ int vfsFlags /* Flags passed through to the VFS */ ){ int rc; /* Return code */ #ifdef SQLITE_TEST sqlite3_opentemp_count++; /* Used for testing and analysis only */ #endif vfsFlags |= SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE | SQLITE_OPEN_EXCLUSIVE | SQLITE_OPEN_DELETEONCLOSE; rc = sqlite3OsOpen(pPager->pVfs, 0, pFile, vfsFlags, 0); assert( rc!=SQLITE_OK || isOpen(pFile) ); return rc; } /* ** Set the busy handler function. ** ** The pager invokes the busy-handler if sqlite3OsLock() returns ** SQLITE_BUSY when trying to upgrade from no-lock to a SHARED lock, ** or when trying to upgrade from a RESERVED lock to an EXCLUSIVE ** lock. It does *not* invoke the busy handler when upgrading from ** SHARED to RESERVED, or when upgrading from SHARED to EXCLUSIVE ** (which occurs during hot-journal rollback). Summary: ** ** Transition | Invokes xBusyHandler ** -------------------------------------------------------- ** NO_LOCK -> SHARED_LOCK | Yes ** SHARED_LOCK -> RESERVED_LOCK | No ** SHARED_LOCK -> EXCLUSIVE_LOCK | No ** RESERVED_LOCK -> EXCLUSIVE_LOCK | Yes ** ** If the busy-handler callback returns non-zero, the lock is ** retried. If it returns zero, then the SQLITE_BUSY error is ** returned to the caller of the pager API function. */ SQLITE_PRIVATE void sqlite3PagerSetBusyhandler( Pager *pPager, /* Pager object */ int (*xBusyHandler)(void *), /* Pointer to busy-handler function */ void *pBusyHandlerArg /* Argument to pass to xBusyHandler */ ){ pPager->xBusyHandler = xBusyHandler; pPager->pBusyHandlerArg = pBusyHandlerArg; if( isOpen(pPager->fd) ){ void **ap = (void **)&pPager->xBusyHandler; assert( ((int(*)(void *))(ap[0]))==xBusyHandler ); assert( ap[1]==pBusyHandlerArg ); sqlite3OsFileControlHint(pPager->fd, SQLITE_FCNTL_BUSYHANDLER, (void *)ap); } } /* ** Change the page size used by the Pager object. The new page size ** is passed in *pPageSize. ** ** If the pager is in the error state when this function is called, it ** is a no-op. The value returned is the error state error code (i.e. ** one of SQLITE_IOERR, an SQLITE_IOERR_xxx sub-code or SQLITE_FULL). ** ** Otherwise, if all of the following are true: ** ** * the new page size (value of *pPageSize) is valid (a power ** of two between 512 and SQLITE_MAX_PAGE_SIZE, inclusive), and ** ** * there are no outstanding page references, and ** ** * the database is either not an in-memory database or it is ** an in-memory database that currently consists of zero pages. ** ** then the pager object page size is set to *pPageSize. ** ** If the page size is changed, then this function uses sqlite3PagerMalloc() ** to obtain a new Pager.pTmpSpace buffer. If this allocation attempt ** fails, SQLITE_NOMEM is returned and the page size remains unchanged. ** In all other cases, SQLITE_OK is returned. ** ** If the page size is not changed, either because one of the enumerated ** conditions above is not true, the pager was in error state when this ** function was called, or because the memory allocation attempt failed, ** then *pPageSize is set to the old, retained page size before returning. */ SQLITE_PRIVATE int sqlite3PagerSetPagesize(Pager *pPager, u32 *pPageSize, int nReserve){ int rc = SQLITE_OK; /* It is not possible to do a full assert_pager_state() here, as this ** function may be called from within PagerOpen(), before the state ** of the Pager object is internally consistent. ** ** At one point this function returned an error if the pager was in ** PAGER_ERROR state. But since PAGER_ERROR state guarantees that ** there is at least one outstanding page reference, this function ** is a no-op for that case anyhow. */ u32 pageSize = *pPageSize; assert( pageSize==0 || (pageSize>=512 && pageSize<=SQLITE_MAX_PAGE_SIZE) ); if( (pPager->memDb==0 || pPager->dbSize==0) && sqlite3PcacheRefCount(pPager->pPCache)==0 && pageSize && pageSize!=(u32)pPager->pageSize ){ char *pNew = NULL; /* New temp space */ i64 nByte = 0; if( pPager->eState>PAGER_OPEN && isOpen(pPager->fd) ){ rc = sqlite3OsFileSize(pPager->fd, &nByte); } if( rc==SQLITE_OK ){ pNew = (char *)sqlite3PageMalloc(pageSize); if( !pNew ) rc = SQLITE_NOMEM_BKPT; } if( rc==SQLITE_OK ){ pager_reset(pPager); rc = sqlite3PcacheSetPageSize(pPager->pPCache, pageSize); } if( rc==SQLITE_OK ){ sqlite3PageFree(pPager->pTmpSpace); pPager->pTmpSpace = pNew; pPager->dbSize = (Pgno)((nByte+pageSize-1)/pageSize); pPager->pageSize = pageSize; }else{ sqlite3PageFree(pNew); } } *pPageSize = pPager->pageSize; if( rc==SQLITE_OK ){ if( nReserve<0 ) nReserve = pPager->nReserve; assert( nReserve>=0 && nReserve<1000 ); pPager->nReserve = (i16)nReserve; pagerReportSize(pPager); pagerFixMaplimit(pPager); } return rc; } /* ** Return a pointer to the "temporary page" buffer held internally ** by the pager. This is a buffer that is big enough to hold the ** entire content of a database page. This buffer is used internally ** during rollback and will be overwritten whenever a rollback ** occurs. But other modules are free to use it too, as long as ** no rollbacks are happening. */ SQLITE_PRIVATE void *sqlite3PagerTempSpace(Pager *pPager){ return pPager->pTmpSpace; } /* ** Attempt to set the maximum database page count if mxPage is positive. ** Make no changes if mxPage is zero or negative. And never reduce the ** maximum page count below the current size of the database. ** ** Regardless of mxPage, return the current maximum page count. */ SQLITE_PRIVATE int sqlite3PagerMaxPageCount(Pager *pPager, int mxPage){ if( mxPage>0 ){ pPager->mxPgno = mxPage; } assert( pPager->eState!=PAGER_OPEN ); /* Called only by OP_MaxPgcnt */ assert( pPager->mxPgno>=pPager->dbSize ); /* OP_MaxPgcnt enforces this */ return pPager->mxPgno; } /* ** The following set of routines are used to disable the simulated ** I/O error mechanism. These routines are used to avoid simulated ** errors in places where we do not care about errors. ** ** Unless -DSQLITE_TEST=1 is used, these routines are all no-ops ** and generate no code. */ #ifdef SQLITE_TEST SQLITE_API extern int sqlite3_io_error_pending; SQLITE_API extern int sqlite3_io_error_hit; static int saved_cnt; void disable_simulated_io_errors(void){ saved_cnt = sqlite3_io_error_pending; sqlite3_io_error_pending = -1; } void enable_simulated_io_errors(void){ sqlite3_io_error_pending = saved_cnt; } #else # define disable_simulated_io_errors() # define enable_simulated_io_errors() #endif /* ** Read the first N bytes from the beginning of the file into memory ** that pDest points to. ** ** If the pager was opened on a transient file (zFilename==""), or ** opened on a file less than N bytes in size, the output buffer is ** zeroed and SQLITE_OK returned. The rationale for this is that this ** function is used to read database headers, and a new transient or ** zero sized database has a header than consists entirely of zeroes. ** ** If any IO error apart from SQLITE_IOERR_SHORT_READ is encountered, ** the error code is returned to the caller and the contents of the ** output buffer undefined. */ SQLITE_PRIVATE int sqlite3PagerReadFileheader(Pager *pPager, int N, unsigned char *pDest){ int rc = SQLITE_OK; memset(pDest, 0, N); assert( isOpen(pPager->fd) || pPager->tempFile ); /* This routine is only called by btree immediately after creating ** the Pager object. There has not been an opportunity to transition ** to WAL mode yet. */ assert( !pagerUseWal(pPager) ); if( isOpen(pPager->fd) ){ IOTRACE(("DBHDR %p 0 %d\n", pPager, N)) rc = sqlite3OsRead(pPager->fd, pDest, N, 0); if( rc==SQLITE_IOERR_SHORT_READ ){ rc = SQLITE_OK; } } return rc; } /* ** This function may only be called when a read-transaction is open on ** the pager. It returns the total number of pages in the database. ** ** However, if the file is between 1 and bytes in size, then ** this is considered a 1 page file. */ SQLITE_PRIVATE void sqlite3PagerPagecount(Pager *pPager, int *pnPage){ assert( pPager->eState>=PAGER_READER ); assert( pPager->eState!=PAGER_WRITER_FINISHED ); *pnPage = (int)pPager->dbSize; } /* ** Try to obtain a lock of type locktype on the database file. If ** a similar or greater lock is already held, this function is a no-op ** (returning SQLITE_OK immediately). ** ** Otherwise, attempt to obtain the lock using sqlite3OsLock(). Invoke ** the busy callback if the lock is currently not available. Repeat ** until the busy callback returns false or until the attempt to ** obtain the lock succeeds. ** ** Return SQLITE_OK on success and an error code if we cannot obtain ** the lock. If the lock is obtained successfully, set the Pager.state ** variable to locktype before returning. */ static int pager_wait_on_lock(Pager *pPager, int locktype){ int rc; /* Return code */ /* Check that this is either a no-op (because the requested lock is ** already held), or one of the transitions that the busy-handler ** may be invoked during, according to the comment above ** sqlite3PagerSetBusyhandler(). */ assert( (pPager->eLock>=locktype) || (pPager->eLock==NO_LOCK && locktype==SHARED_LOCK) || (pPager->eLock==RESERVED_LOCK && locktype==EXCLUSIVE_LOCK) ); do { rc = pagerLockDb(pPager, locktype); }while( rc==SQLITE_BUSY && pPager->xBusyHandler(pPager->pBusyHandlerArg) ); return rc; } /* ** Function assertTruncateConstraint(pPager) checks that one of the ** following is true for all dirty pages currently in the page-cache: ** ** a) The page number is less than or equal to the size of the ** current database image, in pages, OR ** ** b) if the page content were written at this time, it would not ** be necessary to write the current content out to the sub-journal ** (as determined by function subjRequiresPage()). ** ** If the condition asserted by this function were not true, and the ** dirty page were to be discarded from the cache via the pagerStress() ** routine, pagerStress() would not write the current page content to ** the database file. If a savepoint transaction were rolled back after ** this happened, the correct behavior would be to restore the current ** content of the page. However, since this content is not present in either ** the database file or the portion of the rollback journal and ** sub-journal rolled back the content could not be restored and the ** database image would become corrupt. It is therefore fortunate that ** this circumstance cannot arise. */ #if defined(SQLITE_DEBUG) static void assertTruncateConstraintCb(PgHdr *pPg){ assert( pPg->flags&PGHDR_DIRTY ); assert( !subjRequiresPage(pPg) || pPg->pgno<=pPg->pPager->dbSize ); } static void assertTruncateConstraint(Pager *pPager){ sqlite3PcacheIterateDirty(pPager->pPCache, assertTruncateConstraintCb); } #else # define assertTruncateConstraint(pPager) #endif /* ** Truncate the in-memory database file image to nPage pages. This ** function does not actually modify the database file on disk. It ** just sets the internal state of the pager object so that the ** truncation will be done when the current transaction is committed. ** ** This function is only called right before committing a transaction. ** Once this function has been called, the transaction must either be ** rolled back or committed. It is not safe to call this function and ** then continue writing to the database. */ SQLITE_PRIVATE void sqlite3PagerTruncateImage(Pager *pPager, Pgno nPage){ assert( pPager->dbSize>=nPage ); assert( pPager->eState>=PAGER_WRITER_CACHEMOD ); pPager->dbSize = nPage; /* At one point the code here called assertTruncateConstraint() to ** ensure that all pages being truncated away by this operation are, ** if one or more savepoints are open, present in the savepoint ** journal so that they can be restored if the savepoint is rolled ** back. This is no longer necessary as this function is now only ** called right before committing a transaction. So although the ** Pager object may still have open savepoints (Pager.nSavepoint!=0), ** they cannot be rolled back. So the assertTruncateConstraint() call ** is no longer correct. */ } /* ** This function is called before attempting a hot-journal rollback. It ** syncs the journal file to disk, then sets pPager->journalHdr to the ** size of the journal file so that the pager_playback() routine knows ** that the entire journal file has been synced. ** ** Syncing a hot-journal to disk before attempting to roll it back ensures ** that if a power-failure occurs during the rollback, the process that ** attempts rollback following system recovery sees the same journal ** content as this process. ** ** If everything goes as planned, SQLITE_OK is returned. Otherwise, ** an SQLite error code. */ static int pagerSyncHotJournal(Pager *pPager){ int rc = SQLITE_OK; if( !pPager->noSync ){ rc = sqlite3OsSync(pPager->jfd, SQLITE_SYNC_NORMAL); } if( rc==SQLITE_OK ){ rc = sqlite3OsFileSize(pPager->jfd, &pPager->journalHdr); } return rc; } /* ** Obtain a reference to a memory mapped page object for page number pgno. ** The new object will use the pointer pData, obtained from xFetch(). ** If successful, set *ppPage to point to the new page reference ** and return SQLITE_OK. Otherwise, return an SQLite error code and set ** *ppPage to zero. ** ** Page references obtained by calling this function should be released ** by calling pagerReleaseMapPage(). */ static int pagerAcquireMapPage( Pager *pPager, /* Pager object */ Pgno pgno, /* Page number */ void *pData, /* xFetch()'d data for this page */ PgHdr **ppPage /* OUT: Acquired page object */ ){ PgHdr *p; /* Memory mapped page to return */ if( pPager->pMmapFreelist ){ *ppPage = p = pPager->pMmapFreelist; pPager->pMmapFreelist = p->pDirty; p->pDirty = 0; memset(p->pExtra, 0, pPager->nExtra); }else{ *ppPage = p = (PgHdr *)sqlite3MallocZero(sizeof(PgHdr) + pPager->nExtra); if( p==0 ){ sqlite3OsUnfetch(pPager->fd, (i64)(pgno-1) * pPager->pageSize, pData); return SQLITE_NOMEM_BKPT; } p->pExtra = (void *)&p[1]; p->flags = PGHDR_MMAP; p->nRef = 1; p->pPager = pPager; } assert( p->pExtra==(void *)&p[1] ); assert( p->pPage==0 ); assert( p->flags==PGHDR_MMAP ); assert( p->pPager==pPager ); assert( p->nRef==1 ); p->pgno = pgno; p->pData = pData; pPager->nMmapOut++; return SQLITE_OK; } /* ** Release a reference to page pPg. pPg must have been returned by an ** earlier call to pagerAcquireMapPage(). */ static void pagerReleaseMapPage(PgHdr *pPg){ Pager *pPager = pPg->pPager; pPager->nMmapOut--; pPg->pDirty = pPager->pMmapFreelist; pPager->pMmapFreelist = pPg; assert( pPager->fd->pMethods->iVersion>=3 ); sqlite3OsUnfetch(pPager->fd, (i64)(pPg->pgno-1)*pPager->pageSize, pPg->pData); } /* ** Free all PgHdr objects stored in the Pager.pMmapFreelist list. */ static void pagerFreeMapHdrs(Pager *pPager){ PgHdr *p; PgHdr *pNext; for(p=pPager->pMmapFreelist; p; p=pNext){ pNext = p->pDirty; sqlite3_free(p); } } /* ** Shutdown the page cache. Free all memory and close all files. ** ** If a transaction was in progress when this routine is called, that ** transaction is rolled back. All outstanding pages are invalidated ** and their memory is freed. Any attempt to use a page associated ** with this page cache after this function returns will likely ** result in a coredump. ** ** This function always succeeds. If a transaction is active an attempt ** is made to roll it back. If an error occurs during the rollback ** a hot journal may be left in the filesystem but no error is returned ** to the caller. */ SQLITE_PRIVATE int sqlite3PagerClose(Pager *pPager){ u8 *pTmp = (u8 *)pPager->pTmpSpace; assert( assert_pager_state(pPager) ); disable_simulated_io_errors(); sqlite3BeginBenignMalloc(); pagerFreeMapHdrs(pPager); /* pPager->errCode = 0; */ pPager->exclusiveMode = 0; #ifndef SQLITE_OMIT_WAL sqlite3WalClose(pPager->pWal, pPager->ckptSyncFlags, pPager->pageSize, pTmp); pPager->pWal = 0; #endif pager_reset(pPager); if( MEMDB ){ pager_unlock(pPager); }else{ /* If it is open, sync the journal file before calling UnlockAndRollback. ** If this is not done, then an unsynced portion of the open journal ** file may be played back into the database. If a power failure occurs ** while this is happening, the database could become corrupt. ** ** If an error occurs while trying to sync the journal, shift the pager ** into the ERROR state. This causes UnlockAndRollback to unlock the ** database and close the journal file without attempting to roll it ** back or finalize it. The next database user will have to do hot-journal ** rollback before accessing the database file. */ if( isOpen(pPager->jfd) ){ pager_error(pPager, pagerSyncHotJournal(pPager)); } pagerUnlockAndRollback(pPager); } sqlite3EndBenignMalloc(); enable_simulated_io_errors(); PAGERTRACE(("CLOSE %d\n", PAGERID(pPager))); IOTRACE(("CLOSE %p\n", pPager)) sqlite3OsClose(pPager->jfd); sqlite3OsClose(pPager->fd); sqlite3PageFree(pTmp); sqlite3PcacheClose(pPager->pPCache); #ifdef SQLITE_HAS_CODEC if( pPager->xCodecFree ) pPager->xCodecFree(pPager->pCodec); #endif assert( !pPager->aSavepoint && !pPager->pInJournal ); assert( !isOpen(pPager->jfd) && !isOpen(pPager->sjfd) ); sqlite3_free(pPager); return SQLITE_OK; } #if !defined(NDEBUG) || defined(SQLITE_TEST) /* ** Return the page number for page pPg. */ SQLITE_PRIVATE Pgno sqlite3PagerPagenumber(DbPage *pPg){ return pPg->pgno; } #endif /* ** Increment the reference count for page pPg. */ SQLITE_PRIVATE void sqlite3PagerRef(DbPage *pPg){ sqlite3PcacheRef(pPg); } /* ** Sync the journal. In other words, make sure all the pages that have ** been written to the journal have actually reached the surface of the ** disk and can be restored in the event of a hot-journal rollback. ** ** If the Pager.noSync flag is set, then this function is a no-op. ** Otherwise, the actions required depend on the journal-mode and the ** device characteristics of the file-system, as follows: ** ** * If the journal file is an in-memory journal file, no action need ** be taken. ** ** * Otherwise, if the device does not support the SAFE_APPEND property, ** then the nRec field of the most recently written journal header ** is updated to contain the number of journal records that have ** been written following it. If the pager is operating in full-sync ** mode, then the journal file is synced before this field is updated. ** ** * If the device does not support the SEQUENTIAL property, then ** journal file is synced. ** ** Or, in pseudo-code: ** ** if( NOT ){ ** if( NOT SAFE_APPEND ){ ** if( ) xSync(); ** ** } ** if( NOT SEQUENTIAL ) xSync(); ** } ** ** If successful, this routine clears the PGHDR_NEED_SYNC flag of every ** page currently held in memory before returning SQLITE_OK. If an IO ** error is encountered, then the IO error code is returned to the caller. */ static int syncJournal(Pager *pPager, int newHdr){ int rc; /* Return code */ assert( pPager->eState==PAGER_WRITER_CACHEMOD || pPager->eState==PAGER_WRITER_DBMOD ); assert( assert_pager_state(pPager) ); assert( !pagerUseWal(pPager) ); rc = sqlite3PagerExclusiveLock(pPager); if( rc!=SQLITE_OK ) return rc; if( !pPager->noSync ){ assert( !pPager->tempFile ); if( isOpen(pPager->jfd) && pPager->journalMode!=PAGER_JOURNALMODE_MEMORY ){ const int iDc = sqlite3OsDeviceCharacteristics(pPager->fd); assert( isOpen(pPager->jfd) ); if( 0==(iDc&SQLITE_IOCAP_SAFE_APPEND) ){ /* This block deals with an obscure problem. If the last connection ** that wrote to this database was operating in persistent-journal ** mode, then the journal file may at this point actually be larger ** than Pager.journalOff bytes. If the next thing in the journal ** file happens to be a journal-header (written as part of the ** previous connection's transaction), and a crash or power-failure ** occurs after nRec is updated but before this connection writes ** anything else to the journal file (or commits/rolls back its ** transaction), then SQLite may become confused when doing the ** hot-journal rollback following recovery. It may roll back all ** of this connections data, then proceed to rolling back the old, ** out-of-date data that follows it. Database corruption. ** ** To work around this, if the journal file does appear to contain ** a valid header following Pager.journalOff, then write a 0x00 ** byte to the start of it to prevent it from being recognized. ** ** Variable iNextHdrOffset is set to the offset at which this ** problematic header will occur, if it exists. aMagic is used ** as a temporary buffer to inspect the first couple of bytes of ** the potential journal header. */ i64 iNextHdrOffset; u8 aMagic[8]; u8 zHeader[sizeof(aJournalMagic)+4]; memcpy(zHeader, aJournalMagic, sizeof(aJournalMagic)); put32bits(&zHeader[sizeof(aJournalMagic)], pPager->nRec); iNextHdrOffset = journalHdrOffset(pPager); rc = sqlite3OsRead(pPager->jfd, aMagic, 8, iNextHdrOffset); if( rc==SQLITE_OK && 0==memcmp(aMagic, aJournalMagic, 8) ){ static const u8 zerobyte = 0; rc = sqlite3OsWrite(pPager->jfd, &zerobyte, 1, iNextHdrOffset); } if( rc!=SQLITE_OK && rc!=SQLITE_IOERR_SHORT_READ ){ return rc; } /* Write the nRec value into the journal file header. If in ** full-synchronous mode, sync the journal first. This ensures that ** all data has really hit the disk before nRec is updated to mark ** it as a candidate for rollback. ** ** This is not required if the persistent media supports the ** SAFE_APPEND property. Because in this case it is not possible ** for garbage data to be appended to the file, the nRec field ** is populated with 0xFFFFFFFF when the journal header is written ** and never needs to be updated. */ if( pPager->fullSync && 0==(iDc&SQLITE_IOCAP_SEQUENTIAL) ){ PAGERTRACE(("SYNC journal of %d\n", PAGERID(pPager))); IOTRACE(("JSYNC %p\n", pPager)) rc = sqlite3OsSync(pPager->jfd, pPager->syncFlags); if( rc!=SQLITE_OK ) return rc; } IOTRACE(("JHDR %p %lld\n", pPager, pPager->journalHdr)); rc = sqlite3OsWrite( pPager->jfd, zHeader, sizeof(zHeader), pPager->journalHdr ); if( rc!=SQLITE_OK ) return rc; } if( 0==(iDc&SQLITE_IOCAP_SEQUENTIAL) ){ PAGERTRACE(("SYNC journal of %d\n", PAGERID(pPager))); IOTRACE(("JSYNC %p\n", pPager)) rc = sqlite3OsSync(pPager->jfd, pPager->syncFlags| (pPager->syncFlags==SQLITE_SYNC_FULL?SQLITE_SYNC_DATAONLY:0) ); if( rc!=SQLITE_OK ) return rc; } pPager->journalHdr = pPager->journalOff; if( newHdr && 0==(iDc&SQLITE_IOCAP_SAFE_APPEND) ){ pPager->nRec = 0; rc = writeJournalHdr(pPager); if( rc!=SQLITE_OK ) return rc; } }else{ pPager->journalHdr = pPager->journalOff; } } /* Unless the pager is in noSync mode, the journal file was just ** successfully synced. Either way, clear the PGHDR_NEED_SYNC flag on ** all pages. */ sqlite3PcacheClearSyncFlags(pPager->pPCache); pPager->eState = PAGER_WRITER_DBMOD; assert( assert_pager_state(pPager) ); return SQLITE_OK; } /* ** The argument is the first in a linked list of dirty pages connected ** by the PgHdr.pDirty pointer. This function writes each one of the ** in-memory pages in the list to the database file. The argument may ** be NULL, representing an empty list. In this case this function is ** a no-op. ** ** The pager must hold at least a RESERVED lock when this function ** is called. Before writing anything to the database file, this lock ** is upgraded to an EXCLUSIVE lock. If the lock cannot be obtained, ** SQLITE_BUSY is returned and no data is written to the database file. ** ** If the pager is a temp-file pager and the actual file-system file ** is not yet open, it is created and opened before any data is ** written out. ** ** Once the lock has been upgraded and, if necessary, the file opened, ** the pages are written out to the database file in list order. Writing ** a page is skipped if it meets either of the following criteria: ** ** * The page number is greater than Pager.dbSize, or ** * The PGHDR_DONT_WRITE flag is set on the page. ** ** If writing out a page causes the database file to grow, Pager.dbFileSize ** is updated accordingly. If page 1 is written out, then the value cached ** in Pager.dbFileVers[] is updated to match the new value stored in ** the database file. ** ** If everything is successful, SQLITE_OK is returned. If an IO error ** occurs, an IO error code is returned. Or, if the EXCLUSIVE lock cannot ** be obtained, SQLITE_BUSY is returned. */ static int pager_write_pagelist(Pager *pPager, PgHdr *pList){ int rc = SQLITE_OK; /* Return code */ /* This function is only called for rollback pagers in WRITER_DBMOD state. */ assert( !pagerUseWal(pPager) ); assert( pPager->tempFile || pPager->eState==PAGER_WRITER_DBMOD ); assert( pPager->eLock==EXCLUSIVE_LOCK ); assert( isOpen(pPager->fd) || pList->pDirty==0 ); /* If the file is a temp-file has not yet been opened, open it now. It ** is not possible for rc to be other than SQLITE_OK if this branch ** is taken, as pager_wait_on_lock() is a no-op for temp-files. */ if( !isOpen(pPager->fd) ){ assert( pPager->tempFile && rc==SQLITE_OK ); rc = pagerOpentemp(pPager, pPager->fd, pPager->vfsFlags); } /* Before the first write, give the VFS a hint of what the final ** file size will be. */ assert( rc!=SQLITE_OK || isOpen(pPager->fd) ); if( rc==SQLITE_OK && pPager->dbHintSizedbSize && (pList->pDirty || pList->pgno>pPager->dbHintSize) ){ sqlite3_int64 szFile = pPager->pageSize * (sqlite3_int64)pPager->dbSize; sqlite3OsFileControlHint(pPager->fd, SQLITE_FCNTL_SIZE_HINT, &szFile); pPager->dbHintSize = pPager->dbSize; } while( rc==SQLITE_OK && pList ){ Pgno pgno = pList->pgno; /* If there are dirty pages in the page cache with page numbers greater ** than Pager.dbSize, this means sqlite3PagerTruncateImage() was called to ** make the file smaller (presumably by auto-vacuum code). Do not write ** any such pages to the file. ** ** Also, do not write out any page that has the PGHDR_DONT_WRITE flag ** set (set by sqlite3PagerDontWrite()). */ if( pgno<=pPager->dbSize && 0==(pList->flags&PGHDR_DONT_WRITE) ){ i64 offset = (pgno-1)*(i64)pPager->pageSize; /* Offset to write */ char *pData; /* Data to write */ assert( (pList->flags&PGHDR_NEED_SYNC)==0 ); if( pList->pgno==1 ) pager_write_changecounter(pList); /* Encode the database */ CODEC2(pPager, pList->pData, pgno, 6, return SQLITE_NOMEM_BKPT, pData); /* Write out the page data. */ rc = sqlite3OsWrite(pPager->fd, pData, pPager->pageSize, offset); /* If page 1 was just written, update Pager.dbFileVers to match ** the value now stored in the database file. If writing this ** page caused the database file to grow, update dbFileSize. */ if( pgno==1 ){ memcpy(&pPager->dbFileVers, &pData[24], sizeof(pPager->dbFileVers)); } if( pgno>pPager->dbFileSize ){ pPager->dbFileSize = pgno; } pPager->aStat[PAGER_STAT_WRITE]++; /* Update any backup objects copying the contents of this pager. */ sqlite3BackupUpdate(pPager->pBackup, pgno, (u8*)pList->pData); PAGERTRACE(("STORE %d page %d hash(%08x)\n", PAGERID(pPager), pgno, pager_pagehash(pList))); IOTRACE(("PGOUT %p %d\n", pPager, pgno)); PAGER_INCR(sqlite3_pager_writedb_count); }else{ PAGERTRACE(("NOSTORE %d page %d\n", PAGERID(pPager), pgno)); } pager_set_pagehash(pList); pList = pList->pDirty; } return rc; } /* ** Ensure that the sub-journal file is open. If it is already open, this ** function is a no-op. ** ** SQLITE_OK is returned if everything goes according to plan. An ** SQLITE_IOERR_XXX error code is returned if a call to sqlite3OsOpen() ** fails. */ static int openSubJournal(Pager *pPager){ int rc = SQLITE_OK; if( !isOpen(pPager->sjfd) ){ const int flags = SQLITE_OPEN_SUBJOURNAL | SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE | SQLITE_OPEN_EXCLUSIVE | SQLITE_OPEN_DELETEONCLOSE; int nStmtSpill = sqlite3Config.nStmtSpill; if( pPager->journalMode==PAGER_JOURNALMODE_MEMORY || pPager->subjInMemory ){ nStmtSpill = -1; } rc = sqlite3JournalOpen(pPager->pVfs, 0, pPager->sjfd, flags, nStmtSpill); } return rc; } /* ** Append a record of the current state of page pPg to the sub-journal. ** ** If successful, set the bit corresponding to pPg->pgno in the bitvecs ** for all open savepoints before returning. ** ** This function returns SQLITE_OK if everything is successful, an IO ** error code if the attempt to write to the sub-journal fails, or ** SQLITE_NOMEM if a malloc fails while setting a bit in a savepoint ** bitvec. */ static int subjournalPage(PgHdr *pPg){ int rc = SQLITE_OK; Pager *pPager = pPg->pPager; if( pPager->journalMode!=PAGER_JOURNALMODE_OFF ){ /* Open the sub-journal, if it has not already been opened */ assert( pPager->useJournal ); assert( isOpen(pPager->jfd) || pagerUseWal(pPager) ); assert( isOpen(pPager->sjfd) || pPager->nSubRec==0 ); assert( pagerUseWal(pPager) || pageInJournal(pPager, pPg) || pPg->pgno>pPager->dbOrigSize ); rc = openSubJournal(pPager); /* If the sub-journal was opened successfully (or was already open), ** write the journal record into the file. */ if( rc==SQLITE_OK ){ void *pData = pPg->pData; i64 offset = (i64)pPager->nSubRec*(4+pPager->pageSize); char *pData2; CODEC2(pPager, pData, pPg->pgno, 7, return SQLITE_NOMEM_BKPT, pData2); PAGERTRACE(("STMT-JOURNAL %d page %d\n", PAGERID(pPager), pPg->pgno)); rc = write32bits(pPager->sjfd, offset, pPg->pgno); if( rc==SQLITE_OK ){ rc = sqlite3OsWrite(pPager->sjfd, pData2, pPager->pageSize, offset+4); } } } if( rc==SQLITE_OK ){ pPager->nSubRec++; assert( pPager->nSavepoint>0 ); rc = addToSavepointBitvecs(pPager, pPg->pgno); } return rc; } static int subjournalPageIfRequired(PgHdr *pPg){ if( subjRequiresPage(pPg) ){ return subjournalPage(pPg); }else{ return SQLITE_OK; } } /* ** This function is called by the pcache layer when it has reached some ** soft memory limit. The first argument is a pointer to a Pager object ** (cast as a void*). The pager is always 'purgeable' (not an in-memory ** database). The second argument is a reference to a page that is ** currently dirty but has no outstanding references. The page ** is always associated with the Pager object passed as the first ** argument. ** ** The job of this function is to make pPg clean by writing its contents ** out to the database file, if possible. This may involve syncing the ** journal file. ** ** If successful, sqlite3PcacheMakeClean() is called on the page and ** SQLITE_OK returned. If an IO error occurs while trying to make the ** page clean, the IO error code is returned. If the page cannot be ** made clean for some other reason, but no error occurs, then SQLITE_OK ** is returned by sqlite3PcacheMakeClean() is not called. */ static int pagerStress(void *p, PgHdr *pPg){ Pager *pPager = (Pager *)p; int rc = SQLITE_OK; assert( pPg->pPager==pPager ); assert( pPg->flags&PGHDR_DIRTY ); /* The doNotSpill NOSYNC bit is set during times when doing a sync of ** journal (and adding a new header) is not allowed. This occurs ** during calls to sqlite3PagerWrite() while trying to journal multiple ** pages belonging to the same sector. ** ** The doNotSpill ROLLBACK and OFF bits inhibits all cache spilling ** regardless of whether or not a sync is required. This is set during ** a rollback or by user request, respectively. ** ** Spilling is also prohibited when in an error state since that could ** lead to database corruption. In the current implementation it ** is impossible for sqlite3PcacheFetch() to be called with createFlag==3 ** while in the error state, hence it is impossible for this routine to ** be called in the error state. Nevertheless, we include a NEVER() ** test for the error state as a safeguard against future changes. */ if( NEVER(pPager->errCode) ) return SQLITE_OK; testcase( pPager->doNotSpill & SPILLFLAG_ROLLBACK ); testcase( pPager->doNotSpill & SPILLFLAG_OFF ); testcase( pPager->doNotSpill & SPILLFLAG_NOSYNC ); if( pPager->doNotSpill && ((pPager->doNotSpill & (SPILLFLAG_ROLLBACK|SPILLFLAG_OFF))!=0 || (pPg->flags & PGHDR_NEED_SYNC)!=0) ){ return SQLITE_OK; } pPg->pDirty = 0; if( pagerUseWal(pPager) ){ /* Write a single frame for this page to the log. */ rc = subjournalPageIfRequired(pPg); if( rc==SQLITE_OK ){ rc = pagerWalFrames(pPager, pPg, 0, 0); } }else{ /* Sync the journal file if required. */ if( pPg->flags&PGHDR_NEED_SYNC || pPager->eState==PAGER_WRITER_CACHEMOD ){ rc = syncJournal(pPager, 1); } /* Write the contents of the page out to the database file. */ if( rc==SQLITE_OK ){ assert( (pPg->flags&PGHDR_NEED_SYNC)==0 ); rc = pager_write_pagelist(pPager, pPg); } } /* Mark the page as clean. */ if( rc==SQLITE_OK ){ PAGERTRACE(("STRESS %d page %d\n", PAGERID(pPager), pPg->pgno)); sqlite3PcacheMakeClean(pPg); } return pager_error(pPager, rc); } /* ** Flush all unreferenced dirty pages to disk. */ SQLITE_PRIVATE int sqlite3PagerFlush(Pager *pPager){ int rc = pPager->errCode; if( !MEMDB ){ PgHdr *pList = sqlite3PcacheDirtyList(pPager->pPCache); assert( assert_pager_state(pPager) ); while( rc==SQLITE_OK && pList ){ PgHdr *pNext = pList->pDirty; if( pList->nRef==0 ){ rc = pagerStress((void*)pPager, pList); } pList = pNext; } } return rc; } /* ** Allocate and initialize a new Pager object and put a pointer to it ** in *ppPager. The pager should eventually be freed by passing it ** to sqlite3PagerClose(). ** ** The zFilename argument is the path to the database file to open. ** If zFilename is NULL then a randomly-named temporary file is created ** and used as the file to be cached. Temporary files are be deleted ** automatically when they are closed. If zFilename is ":memory:" then ** all information is held in cache. It is never written to disk. ** This can be used to implement an in-memory database. ** ** The nExtra parameter specifies the number of bytes of space allocated ** along with each page reference. This space is available to the user ** via the sqlite3PagerGetExtra() API. ** ** The flags argument is used to specify properties that affect the ** operation of the pager. It should be passed some bitwise combination ** of the PAGER_* flags. ** ** The vfsFlags parameter is a bitmask to pass to the flags parameter ** of the xOpen() method of the supplied VFS when opening files. ** ** If the pager object is allocated and the specified file opened ** successfully, SQLITE_OK is returned and *ppPager set to point to ** the new pager object. If an error occurs, *ppPager is set to NULL ** and error code returned. This function may return SQLITE_NOMEM ** (sqlite3Malloc() is used to allocate memory), SQLITE_CANTOPEN or ** various SQLITE_IO_XXX errors. */ SQLITE_PRIVATE int sqlite3PagerOpen( sqlite3_vfs *pVfs, /* The virtual file system to use */ Pager **ppPager, /* OUT: Return the Pager structure here */ const char *zFilename, /* Name of the database file to open */ int nExtra, /* Extra bytes append to each in-memory page */ int flags, /* flags controlling this file */ int vfsFlags, /* flags passed through to sqlite3_vfs.xOpen() */ void (*xReinit)(DbPage*) /* Function to reinitialize pages */ ){ u8 *pPtr; Pager *pPager = 0; /* Pager object to allocate and return */ int rc = SQLITE_OK; /* Return code */ int tempFile = 0; /* True for temp files (incl. in-memory files) */ int memDb = 0; /* True if this is an in-memory file */ int readOnly = 0; /* True if this is a read-only file */ int journalFileSize; /* Bytes to allocate for each journal fd */ char *zPathname = 0; /* Full path to database file */ int nPathname = 0; /* Number of bytes in zPathname */ int useJournal = (flags & PAGER_OMIT_JOURNAL)==0; /* False to omit journal */ int pcacheSize = sqlite3PcacheSize(); /* Bytes to allocate for PCache */ u32 szPageDflt = SQLITE_DEFAULT_PAGE_SIZE; /* Default page size */ const char *zUri = 0; /* URI args to copy */ int nUri = 0; /* Number of bytes of URI args at *zUri */ /* Figure out how much space is required for each journal file-handle ** (there are two of them, the main journal and the sub-journal). */ journalFileSize = ROUND8(sqlite3JournalSize(pVfs)); /* Set the output variable to NULL in case an error occurs. */ *ppPager = 0; #ifndef SQLITE_OMIT_MEMORYDB if( flags & PAGER_MEMORY ){ memDb = 1; if( zFilename && zFilename[0] ){ zPathname = sqlite3DbStrDup(0, zFilename); if( zPathname==0 ) return SQLITE_NOMEM_BKPT; nPathname = sqlite3Strlen30(zPathname); zFilename = 0; } } #endif /* Compute and store the full pathname in an allocated buffer pointed ** to by zPathname, length nPathname. Or, if this is a temporary file, ** leave both nPathname and zPathname set to 0. */ if( zFilename && zFilename[0] ){ const char *z; nPathname = pVfs->mxPathname+1; zPathname = sqlite3DbMallocRaw(0, nPathname*2); if( zPathname==0 ){ return SQLITE_NOMEM_BKPT; } zPathname[0] = 0; /* Make sure initialized even if FullPathname() fails */ rc = sqlite3OsFullPathname(pVfs, zFilename, nPathname, zPathname); nPathname = sqlite3Strlen30(zPathname); z = zUri = &zFilename[sqlite3Strlen30(zFilename)+1]; while( *z ){ z += sqlite3Strlen30(z)+1; z += sqlite3Strlen30(z)+1; } nUri = (int)(&z[1] - zUri); assert( nUri>=0 ); if( rc==SQLITE_OK && nPathname+8>pVfs->mxPathname ){ /* This branch is taken when the journal path required by ** the database being opened will be more than pVfs->mxPathname ** bytes in length. This means the database cannot be opened, ** as it will not be possible to open the journal file or even ** check for a hot-journal before reading. */ rc = SQLITE_CANTOPEN_BKPT; } if( rc!=SQLITE_OK ){ sqlite3DbFree(0, zPathname); return rc; } } /* Allocate memory for the Pager structure, PCache object, the ** three file descriptors, the database file name and the journal ** file name. The layout in memory is as follows: ** ** Pager object (sizeof(Pager) bytes) ** PCache object (sqlite3PcacheSize() bytes) ** Database file handle (pVfs->szOsFile bytes) ** Sub-journal file handle (journalFileSize bytes) ** Main journal file handle (journalFileSize bytes) ** Database file name (nPathname+1 bytes) ** Journal file name (nPathname+8+1 bytes) */ pPtr = (u8 *)sqlite3MallocZero( ROUND8(sizeof(*pPager)) + /* Pager structure */ ROUND8(pcacheSize) + /* PCache object */ ROUND8(pVfs->szOsFile) + /* The main db file */ journalFileSize * 2 + /* The two journal files */ nPathname + 1 + nUri + /* zFilename */ nPathname + 8 + 2 /* zJournal */ #ifndef SQLITE_OMIT_WAL + nPathname + 4 + 2 /* zWal */ #endif ); assert( EIGHT_BYTE_ALIGNMENT(SQLITE_INT_TO_PTR(journalFileSize)) ); if( !pPtr ){ sqlite3DbFree(0, zPathname); return SQLITE_NOMEM_BKPT; } pPager = (Pager*)(pPtr); pPager->pPCache = (PCache*)(pPtr += ROUND8(sizeof(*pPager))); pPager->fd = (sqlite3_file*)(pPtr += ROUND8(pcacheSize)); pPager->sjfd = (sqlite3_file*)(pPtr += ROUND8(pVfs->szOsFile)); pPager->jfd = (sqlite3_file*)(pPtr += journalFileSize); pPager->zFilename = (char*)(pPtr += journalFileSize); assert( EIGHT_BYTE_ALIGNMENT(pPager->jfd) ); /* Fill in the Pager.zFilename and Pager.zJournal buffers, if required. */ if( zPathname ){ assert( nPathname>0 ); pPager->zJournal = (char*)(pPtr += nPathname + 1 + nUri); memcpy(pPager->zFilename, zPathname, nPathname); if( nUri ) memcpy(&pPager->zFilename[nPathname+1], zUri, nUri); memcpy(pPager->zJournal, zPathname, nPathname); memcpy(&pPager->zJournal[nPathname], "-journal\000", 8+2); sqlite3FileSuffix3(pPager->zFilename, pPager->zJournal); #ifndef SQLITE_OMIT_WAL pPager->zWal = &pPager->zJournal[nPathname+8+1]; memcpy(pPager->zWal, zPathname, nPathname); memcpy(&pPager->zWal[nPathname], "-wal\000", 4+1); sqlite3FileSuffix3(pPager->zFilename, pPager->zWal); #endif sqlite3DbFree(0, zPathname); } pPager->pVfs = pVfs; pPager->vfsFlags = vfsFlags; /* Open the pager file. */ if( zFilename && zFilename[0] ){ int fout = 0; /* VFS flags returned by xOpen() */ rc = sqlite3OsOpen(pVfs, pPager->zFilename, pPager->fd, vfsFlags, &fout); assert( !memDb ); readOnly = (fout&SQLITE_OPEN_READONLY); /* If the file was successfully opened for read/write access, ** choose a default page size in case we have to create the ** database file. The default page size is the maximum of: ** ** + SQLITE_DEFAULT_PAGE_SIZE, ** + The value returned by sqlite3OsSectorSize() ** + The largest page size that can be written atomically. */ if( rc==SQLITE_OK ){ int iDc = sqlite3OsDeviceCharacteristics(pPager->fd); if( !readOnly ){ setSectorSize(pPager); assert(SQLITE_DEFAULT_PAGE_SIZE<=SQLITE_MAX_DEFAULT_PAGE_SIZE); if( szPageDfltsectorSize ){ if( pPager->sectorSize>SQLITE_MAX_DEFAULT_PAGE_SIZE ){ szPageDflt = SQLITE_MAX_DEFAULT_PAGE_SIZE; }else{ szPageDflt = (u32)pPager->sectorSize; } } #ifdef SQLITE_ENABLE_ATOMIC_WRITE { int ii; assert(SQLITE_IOCAP_ATOMIC512==(512>>8)); assert(SQLITE_IOCAP_ATOMIC64K==(65536>>8)); assert(SQLITE_MAX_DEFAULT_PAGE_SIZE<=65536); for(ii=szPageDflt; ii<=SQLITE_MAX_DEFAULT_PAGE_SIZE; ii=ii*2){ if( iDc&(SQLITE_IOCAP_ATOMIC|(ii>>8)) ){ szPageDflt = ii; } } } #endif } pPager->noLock = sqlite3_uri_boolean(zFilename, "nolock", 0); if( (iDc & SQLITE_IOCAP_IMMUTABLE)!=0 || sqlite3_uri_boolean(zFilename, "immutable", 0) ){ vfsFlags |= SQLITE_OPEN_READONLY; goto act_like_temp_file; } } }else{ /* If a temporary file is requested, it is not opened immediately. ** In this case we accept the default page size and delay actually ** opening the file until the first call to OsWrite(). ** ** This branch is also run for an in-memory database. An in-memory ** database is the same as a temp-file that is never written out to ** disk and uses an in-memory rollback journal. ** ** This branch also runs for files marked as immutable. */ act_like_temp_file: tempFile = 1; pPager->eState = PAGER_READER; /* Pretend we already have a lock */ pPager->eLock = EXCLUSIVE_LOCK; /* Pretend we are in EXCLUSIVE mode */ pPager->noLock = 1; /* Do no locking */ readOnly = (vfsFlags&SQLITE_OPEN_READONLY); } /* The following call to PagerSetPagesize() serves to set the value of ** Pager.pageSize and to allocate the Pager.pTmpSpace buffer. */ if( rc==SQLITE_OK ){ assert( pPager->memDb==0 ); rc = sqlite3PagerSetPagesize(pPager, &szPageDflt, -1); testcase( rc!=SQLITE_OK ); } /* Initialize the PCache object. */ if( rc==SQLITE_OK ){ assert( nExtra<1000 ); nExtra = ROUND8(nExtra); rc = sqlite3PcacheOpen(szPageDflt, nExtra, !memDb, !memDb?pagerStress:0, (void *)pPager, pPager->pPCache); } /* If an error occurred above, free the Pager structure and close the file. */ if( rc!=SQLITE_OK ){ sqlite3OsClose(pPager->fd); sqlite3PageFree(pPager->pTmpSpace); sqlite3_free(pPager); return rc; } PAGERTRACE(("OPEN %d %s\n", FILEHANDLEID(pPager->fd), pPager->zFilename)); IOTRACE(("OPEN %p %s\n", pPager, pPager->zFilename)) pPager->useJournal = (u8)useJournal; /* pPager->stmtOpen = 0; */ /* pPager->stmtInUse = 0; */ /* pPager->nRef = 0; */ /* pPager->stmtSize = 0; */ /* pPager->stmtJSize = 0; */ /* pPager->nPage = 0; */ pPager->mxPgno = SQLITE_MAX_PAGE_COUNT; /* pPager->state = PAGER_UNLOCK; */ /* pPager->errMask = 0; */ pPager->tempFile = (u8)tempFile; assert( tempFile==PAGER_LOCKINGMODE_NORMAL || tempFile==PAGER_LOCKINGMODE_EXCLUSIVE ); assert( PAGER_LOCKINGMODE_EXCLUSIVE==1 ); pPager->exclusiveMode = (u8)tempFile; pPager->changeCountDone = pPager->tempFile; pPager->memDb = (u8)memDb; pPager->readOnly = (u8)readOnly; assert( useJournal || pPager->tempFile ); pPager->noSync = pPager->tempFile; if( pPager->noSync ){ assert( pPager->fullSync==0 ); assert( pPager->extraSync==0 ); assert( pPager->syncFlags==0 ); assert( pPager->walSyncFlags==0 ); assert( pPager->ckptSyncFlags==0 ); }else{ pPager->fullSync = 1; pPager->extraSync = 0; pPager->syncFlags = SQLITE_SYNC_NORMAL; pPager->walSyncFlags = SQLITE_SYNC_NORMAL | WAL_SYNC_TRANSACTIONS; pPager->ckptSyncFlags = SQLITE_SYNC_NORMAL; } /* pPager->pFirst = 0; */ /* pPager->pFirstSynced = 0; */ /* pPager->pLast = 0; */ pPager->nExtra = (u16)nExtra; pPager->journalSizeLimit = SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT; assert( isOpen(pPager->fd) || tempFile ); setSectorSize(pPager); if( !useJournal ){ pPager->journalMode = PAGER_JOURNALMODE_OFF; }else if( memDb ){ pPager->journalMode = PAGER_JOURNALMODE_MEMORY; } /* pPager->xBusyHandler = 0; */ /* pPager->pBusyHandlerArg = 0; */ pPager->xReiniter = xReinit; /* memset(pPager->aHash, 0, sizeof(pPager->aHash)); */ /* pPager->szMmap = SQLITE_DEFAULT_MMAP_SIZE // will be set by btree.c */ *ppPager = pPager; return SQLITE_OK; } /* Verify that the database file has not be deleted or renamed out from ** under the pager. Return SQLITE_OK if the database is still were it ought ** to be on disk. Return non-zero (SQLITE_READONLY_DBMOVED or some other error ** code from sqlite3OsAccess()) if the database has gone missing. */ static int databaseIsUnmoved(Pager *pPager){ int bHasMoved = 0; int rc; if( pPager->tempFile ) return SQLITE_OK; if( pPager->dbSize==0 ) return SQLITE_OK; assert( pPager->zFilename && pPager->zFilename[0] ); rc = sqlite3OsFileControl(pPager->fd, SQLITE_FCNTL_HAS_MOVED, &bHasMoved); if( rc==SQLITE_NOTFOUND ){ /* If the HAS_MOVED file-control is unimplemented, assume that the file ** has not been moved. That is the historical behavior of SQLite: prior to ** version 3.8.3, it never checked */ rc = SQLITE_OK; }else if( rc==SQLITE_OK && bHasMoved ){ rc = SQLITE_READONLY_DBMOVED; } return rc; } /* ** This function is called after transitioning from PAGER_UNLOCK to ** PAGER_SHARED state. It tests if there is a hot journal present in ** the file-system for the given pager. A hot journal is one that ** needs to be played back. According to this function, a hot-journal ** file exists if the following criteria are met: ** ** * The journal file exists in the file system, and ** * No process holds a RESERVED or greater lock on the database file, and ** * The database file itself is greater than 0 bytes in size, and ** * The first byte of the journal file exists and is not 0x00. ** ** If the current size of the database file is 0 but a journal file ** exists, that is probably an old journal left over from a prior ** database with the same name. In this case the journal file is ** just deleted using OsDelete, *pExists is set to 0 and SQLITE_OK ** is returned. ** ** This routine does not check if there is a master journal filename ** at the end of the file. If there is, and that master journal file ** does not exist, then the journal file is not really hot. In this ** case this routine will return a false-positive. The pager_playback() ** routine will discover that the journal file is not really hot and ** will not roll it back. ** ** If a hot-journal file is found to exist, *pExists is set to 1 and ** SQLITE_OK returned. If no hot-journal file is present, *pExists is ** set to 0 and SQLITE_OK returned. If an IO error occurs while trying ** to determine whether or not a hot-journal file exists, the IO error ** code is returned and the value of *pExists is undefined. */ static int hasHotJournal(Pager *pPager, int *pExists){ sqlite3_vfs * const pVfs = pPager->pVfs; int rc = SQLITE_OK; /* Return code */ int exists = 1; /* True if a journal file is present */ int jrnlOpen = !!isOpen(pPager->jfd); assert( pPager->useJournal ); assert( isOpen(pPager->fd) ); assert( pPager->eState==PAGER_OPEN ); assert( jrnlOpen==0 || ( sqlite3OsDeviceCharacteristics(pPager->jfd) & SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN )); *pExists = 0; if( !jrnlOpen ){ rc = sqlite3OsAccess(pVfs, pPager->zJournal, SQLITE_ACCESS_EXISTS, &exists); } if( rc==SQLITE_OK && exists ){ int locked = 0; /* True if some process holds a RESERVED lock */ /* Race condition here: Another process might have been holding the ** the RESERVED lock and have a journal open at the sqlite3OsAccess() ** call above, but then delete the journal and drop the lock before ** we get to the following sqlite3OsCheckReservedLock() call. If that ** is the case, this routine might think there is a hot journal when ** in fact there is none. This results in a false-positive which will ** be dealt with by the playback routine. Ticket #3883. */ rc = sqlite3OsCheckReservedLock(pPager->fd, &locked); if( rc==SQLITE_OK && !locked ){ Pgno nPage; /* Number of pages in database file */ assert( pPager->tempFile==0 ); rc = pagerPagecount(pPager, &nPage); if( rc==SQLITE_OK ){ /* If the database is zero pages in size, that means that either (1) the ** journal is a remnant from a prior database with the same name where ** the database file but not the journal was deleted, or (2) the initial ** transaction that populates a new database is being rolled back. ** In either case, the journal file can be deleted. However, take care ** not to delete the journal file if it is already open due to ** journal_mode=PERSIST. */ if( nPage==0 && !jrnlOpen ){ sqlite3BeginBenignMalloc(); if( pagerLockDb(pPager, RESERVED_LOCK)==SQLITE_OK ){ sqlite3OsDelete(pVfs, pPager->zJournal, 0); if( !pPager->exclusiveMode ) pagerUnlockDb(pPager, SHARED_LOCK); } sqlite3EndBenignMalloc(); }else{ /* The journal file exists and no other connection has a reserved ** or greater lock on the database file. Now check that there is ** at least one non-zero bytes at the start of the journal file. ** If there is, then we consider this journal to be hot. If not, ** it can be ignored. */ if( !jrnlOpen ){ int f = SQLITE_OPEN_READONLY|SQLITE_OPEN_MAIN_JOURNAL; rc = sqlite3OsOpen(pVfs, pPager->zJournal, pPager->jfd, f, &f); } if( rc==SQLITE_OK ){ u8 first = 0; rc = sqlite3OsRead(pPager->jfd, (void *)&first, 1, 0); if( rc==SQLITE_IOERR_SHORT_READ ){ rc = SQLITE_OK; } if( !jrnlOpen ){ sqlite3OsClose(pPager->jfd); } *pExists = (first!=0); }else if( rc==SQLITE_CANTOPEN ){ /* If we cannot open the rollback journal file in order to see if ** it has a zero header, that might be due to an I/O error, or ** it might be due to the race condition described above and in ** ticket #3883. Either way, assume that the journal is hot. ** This might be a false positive. But if it is, then the ** automatic journal playback and recovery mechanism will deal ** with it under an EXCLUSIVE lock where we do not need to ** worry so much with race conditions. */ *pExists = 1; rc = SQLITE_OK; } } } } } return rc; } /* ** This function is called to obtain a shared lock on the database file. ** It is illegal to call sqlite3PagerGet() until after this function ** has been successfully called. If a shared-lock is already held when ** this function is called, it is a no-op. ** ** The following operations are also performed by this function. ** ** 1) If the pager is currently in PAGER_OPEN state (no lock held ** on the database file), then an attempt is made to obtain a ** SHARED lock on the database file. Immediately after obtaining ** the SHARED lock, the file-system is checked for a hot-journal, ** which is played back if present. Following any hot-journal ** rollback, the contents of the cache are validated by checking ** the 'change-counter' field of the database file header and ** discarded if they are found to be invalid. ** ** 2) If the pager is running in exclusive-mode, and there are currently ** no outstanding references to any pages, and is in the error state, ** then an attempt is made to clear the error state by discarding ** the contents of the page cache and rolling back any open journal ** file. ** ** If everything is successful, SQLITE_OK is returned. If an IO error ** occurs while locking the database, checking for a hot-journal file or ** rolling back a journal file, the IO error code is returned. */ SQLITE_PRIVATE int sqlite3PagerSharedLock(Pager *pPager){ int rc = SQLITE_OK; /* Return code */ /* This routine is only called from b-tree and only when there are no ** outstanding pages. This implies that the pager state should either ** be OPEN or READER. READER is only possible if the pager is or was in ** exclusive access mode. */ assert( sqlite3PcacheRefCount(pPager->pPCache)==0 ); assert( assert_pager_state(pPager) ); assert( pPager->eState==PAGER_OPEN || pPager->eState==PAGER_READER ); assert( pPager->errCode==SQLITE_OK ); if( !pagerUseWal(pPager) && pPager->eState==PAGER_OPEN ){ int bHotJournal = 1; /* True if there exists a hot journal-file */ assert( !MEMDB ); assert( pPager->tempFile==0 || pPager->eLock==EXCLUSIVE_LOCK ); rc = pager_wait_on_lock(pPager, SHARED_LOCK); if( rc!=SQLITE_OK ){ assert( pPager->eLock==NO_LOCK || pPager->eLock==UNKNOWN_LOCK ); goto failed; } /* If a journal file exists, and there is no RESERVED lock on the ** database file, then it either needs to be played back or deleted. */ if( pPager->eLock<=SHARED_LOCK ){ rc = hasHotJournal(pPager, &bHotJournal); } if( rc!=SQLITE_OK ){ goto failed; } if( bHotJournal ){ if( pPager->readOnly ){ rc = SQLITE_READONLY_ROLLBACK; goto failed; } /* Get an EXCLUSIVE lock on the database file. At this point it is ** important that a RESERVED lock is not obtained on the way to the ** EXCLUSIVE lock. If it were, another process might open the ** database file, detect the RESERVED lock, and conclude that the ** database is safe to read while this process is still rolling the ** hot-journal back. ** ** Because the intermediate RESERVED lock is not requested, any ** other process attempting to access the database file will get to ** this point in the code and fail to obtain its own EXCLUSIVE lock ** on the database file. ** ** Unless the pager is in locking_mode=exclusive mode, the lock is ** downgraded to SHARED_LOCK before this function returns. */ rc = pagerLockDb(pPager, EXCLUSIVE_LOCK); if( rc!=SQLITE_OK ){ goto failed; } /* If it is not already open and the file exists on disk, open the ** journal for read/write access. Write access is required because ** in exclusive-access mode the file descriptor will be kept open ** and possibly used for a transaction later on. Also, write-access ** is usually required to finalize the journal in journal_mode=persist ** mode (and also for journal_mode=truncate on some systems). ** ** If the journal does not exist, it usually means that some ** other connection managed to get in and roll it back before ** this connection obtained the exclusive lock above. Or, it ** may mean that the pager was in the error-state when this ** function was called and the journal file does not exist. */ if( !isOpen(pPager->jfd) ){ sqlite3_vfs * const pVfs = pPager->pVfs; int bExists; /* True if journal file exists */ rc = sqlite3OsAccess( pVfs, pPager->zJournal, SQLITE_ACCESS_EXISTS, &bExists); if( rc==SQLITE_OK && bExists ){ int fout = 0; int f = SQLITE_OPEN_READWRITE|SQLITE_OPEN_MAIN_JOURNAL; assert( !pPager->tempFile ); rc = sqlite3OsOpen(pVfs, pPager->zJournal, pPager->jfd, f, &fout); assert( rc!=SQLITE_OK || isOpen(pPager->jfd) ); if( rc==SQLITE_OK && fout&SQLITE_OPEN_READONLY ){ rc = SQLITE_CANTOPEN_BKPT; sqlite3OsClose(pPager->jfd); } } } /* Playback and delete the journal. Drop the database write ** lock and reacquire the read lock. Purge the cache before ** playing back the hot-journal so that we don't end up with ** an inconsistent cache. Sync the hot journal before playing ** it back since the process that crashed and left the hot journal ** probably did not sync it and we are required to always sync ** the journal before playing it back. */ if( isOpen(pPager->jfd) ){ assert( rc==SQLITE_OK ); rc = pagerSyncHotJournal(pPager); if( rc==SQLITE_OK ){ rc = pager_playback(pPager, !pPager->tempFile); pPager->eState = PAGER_OPEN; } }else if( !pPager->exclusiveMode ){ pagerUnlockDb(pPager, SHARED_LOCK); } if( rc!=SQLITE_OK ){ /* This branch is taken if an error occurs while trying to open ** or roll back a hot-journal while holding an EXCLUSIVE lock. The ** pager_unlock() routine will be called before returning to unlock ** the file. If the unlock attempt fails, then Pager.eLock must be ** set to UNKNOWN_LOCK (see the comment above the #define for ** UNKNOWN_LOCK above for an explanation). ** ** In order to get pager_unlock() to do this, set Pager.eState to ** PAGER_ERROR now. This is not actually counted as a transition ** to ERROR state in the state diagram at the top of this file, ** since we know that the same call to pager_unlock() will very ** shortly transition the pager object to the OPEN state. Calling ** assert_pager_state() would fail now, as it should not be possible ** to be in ERROR state when there are zero outstanding page ** references. */ pager_error(pPager, rc); goto failed; } assert( pPager->eState==PAGER_OPEN ); assert( (pPager->eLock==SHARED_LOCK) || (pPager->exclusiveMode && pPager->eLock>SHARED_LOCK) ); } if( !pPager->tempFile && pPager->hasHeldSharedLock ){ /* The shared-lock has just been acquired then check to ** see if the database has been modified. If the database has changed, ** flush the cache. The hasHeldSharedLock flag prevents this from ** occurring on the very first access to a file, in order to save a ** single unnecessary sqlite3OsRead() call at the start-up. ** ** Database changes are detected by looking at 15 bytes beginning ** at offset 24 into the file. The first 4 of these 16 bytes are ** a 32-bit counter that is incremented with each change. The ** other bytes change randomly with each file change when ** a codec is in use. ** ** There is a vanishingly small chance that a change will not be ** detected. The chance of an undetected change is so small that ** it can be neglected. */ Pgno nPage = 0; char dbFileVers[sizeof(pPager->dbFileVers)]; rc = pagerPagecount(pPager, &nPage); if( rc ) goto failed; if( nPage>0 ){ IOTRACE(("CKVERS %p %d\n", pPager, sizeof(dbFileVers))); rc = sqlite3OsRead(pPager->fd, &dbFileVers, sizeof(dbFileVers), 24); if( rc!=SQLITE_OK && rc!=SQLITE_IOERR_SHORT_READ ){ goto failed; } }else{ memset(dbFileVers, 0, sizeof(dbFileVers)); } if( memcmp(pPager->dbFileVers, dbFileVers, sizeof(dbFileVers))!=0 ){ pager_reset(pPager); /* Unmap the database file. It is possible that external processes ** may have truncated the database file and then extended it back ** to its original size while this process was not holding a lock. ** In this case there may exist a Pager.pMap mapping that appears ** to be the right size but is not actually valid. Avoid this ** possibility by unmapping the db here. */ if( USEFETCH(pPager) ){ sqlite3OsUnfetch(pPager->fd, 0, 0); } } } /* If there is a WAL file in the file-system, open this database in WAL ** mode. Otherwise, the following function call is a no-op. */ rc = pagerOpenWalIfPresent(pPager); #ifndef SQLITE_OMIT_WAL assert( pPager->pWal==0 || rc==SQLITE_OK ); #endif } if( pagerUseWal(pPager) ){ assert( rc==SQLITE_OK ); rc = pagerBeginReadTransaction(pPager); } if( pPager->tempFile==0 && pPager->eState==PAGER_OPEN && rc==SQLITE_OK ){ rc = pagerPagecount(pPager, &pPager->dbSize); } failed: if( rc!=SQLITE_OK ){ assert( !MEMDB ); pager_unlock(pPager); assert( pPager->eState==PAGER_OPEN ); }else{ pPager->eState = PAGER_READER; pPager->hasHeldSharedLock = 1; } return rc; } /* ** If the reference count has reached zero, rollback any active ** transaction and unlock the pager. ** ** Except, in locking_mode=EXCLUSIVE when there is nothing to in ** the rollback journal, the unlock is not performed and there is ** nothing to rollback, so this routine is a no-op. */ static void pagerUnlockIfUnused(Pager *pPager){ if( pPager->nMmapOut==0 && (sqlite3PcacheRefCount(pPager->pPCache)==0) ){ pagerUnlockAndRollback(pPager); } } /* ** Acquire a reference to page number pgno in pager pPager (a page ** reference has type DbPage*). If the requested reference is ** successfully obtained, it is copied to *ppPage and SQLITE_OK returned. ** ** If the requested page is already in the cache, it is returned. ** Otherwise, a new page object is allocated and populated with data ** read from the database file. In some cases, the pcache module may ** choose not to allocate a new page object and may reuse an existing ** object with no outstanding references. ** ** The extra data appended to a page is always initialized to zeros the ** first time a page is loaded into memory. If the page requested is ** already in the cache when this function is called, then the extra ** data is left as it was when the page object was last used. ** ** If the database image is smaller than the requested page or if a ** non-zero value is passed as the noContent parameter and the ** requested page is not already stored in the cache, then no ** actual disk read occurs. In this case the memory image of the ** page is initialized to all zeros. ** ** If noContent is true, it means that we do not care about the contents ** of the page. This occurs in two scenarios: ** ** a) When reading a free-list leaf page from the database, and ** ** b) When a savepoint is being rolled back and we need to load ** a new page into the cache to be filled with the data read ** from the savepoint journal. ** ** If noContent is true, then the data returned is zeroed instead of ** being read from the database. Additionally, the bits corresponding ** to pgno in Pager.pInJournal (bitvec of pages already written to the ** journal file) and the PagerSavepoint.pInSavepoint bitvecs of any open ** savepoints are set. This means if the page is made writable at any ** point in the future, using a call to sqlite3PagerWrite(), its contents ** will not be journaled. This saves IO. ** ** The acquisition might fail for several reasons. In all cases, ** an appropriate error code is returned and *ppPage is set to NULL. ** ** See also sqlite3PagerLookup(). Both this routine and Lookup() attempt ** to find a page in the in-memory cache first. If the page is not already ** in memory, this routine goes to disk to read it in whereas Lookup() ** just returns 0. This routine acquires a read-lock the first time it ** has to go to disk, and could also playback an old journal if necessary. ** Since Lookup() never goes to disk, it never has to deal with locks ** or journal files. */ SQLITE_PRIVATE int sqlite3PagerGet( Pager *pPager, /* The pager open on the database file */ Pgno pgno, /* Page number to fetch */ DbPage **ppPage, /* Write a pointer to the page here */ int flags /* PAGER_GET_XXX flags */ ){ int rc = SQLITE_OK; PgHdr *pPg = 0; u32 iFrame = 0; /* Frame to read from WAL file */ const int noContent = (flags & PAGER_GET_NOCONTENT); /* It is acceptable to use a read-only (mmap) page for any page except ** page 1 if there is no write-transaction open or the ACQUIRE_READONLY ** flag was specified by the caller. And so long as the db is not a ** temporary or in-memory database. */ const int bMmapOk = (pgno>1 && USEFETCH(pPager) && (pPager->eState==PAGER_READER || (flags & PAGER_GET_READONLY)) #ifdef SQLITE_HAS_CODEC && pPager->xCodec==0 #endif ); /* Optimization note: Adding the "pgno<=1" term before "pgno==0" here ** allows the compiler optimizer to reuse the results of the "pgno>1" ** test in the previous statement, and avoid testing pgno==0 in the ** common case where pgno is large. */ if( pgno<=1 && pgno==0 ){ return SQLITE_CORRUPT_BKPT; } assert( pPager->eState>=PAGER_READER ); assert( assert_pager_state(pPager) ); assert( noContent==0 || bMmapOk==0 ); assert( pPager->hasHeldSharedLock==1 ); /* If the pager is in the error state, return an error immediately. ** Otherwise, request the page from the PCache layer. */ if( pPager->errCode!=SQLITE_OK ){ rc = pPager->errCode; }else{ if( bMmapOk && pagerUseWal(pPager) ){ rc = sqlite3WalFindFrame(pPager->pWal, pgno, &iFrame); if( rc!=SQLITE_OK ) goto pager_acquire_err; } if( bMmapOk && iFrame==0 ){ void *pData = 0; rc = sqlite3OsFetch(pPager->fd, (i64)(pgno-1) * pPager->pageSize, pPager->pageSize, &pData ); if( rc==SQLITE_OK && pData ){ if( pPager->eState>PAGER_READER || pPager->tempFile ){ pPg = sqlite3PagerLookup(pPager, pgno); } if( pPg==0 ){ rc = pagerAcquireMapPage(pPager, pgno, pData, &pPg); }else{ sqlite3OsUnfetch(pPager->fd, (i64)(pgno-1)*pPager->pageSize, pData); } if( pPg ){ assert( rc==SQLITE_OK ); *ppPage = pPg; return SQLITE_OK; } } if( rc!=SQLITE_OK ){ goto pager_acquire_err; } } { sqlite3_pcache_page *pBase; pBase = sqlite3PcacheFetch(pPager->pPCache, pgno, 3); if( pBase==0 ){ rc = sqlite3PcacheFetchStress(pPager->pPCache, pgno, &pBase); if( rc!=SQLITE_OK ) goto pager_acquire_err; if( pBase==0 ){ pPg = *ppPage = 0; rc = SQLITE_NOMEM_BKPT; goto pager_acquire_err; } } pPg = *ppPage = sqlite3PcacheFetchFinish(pPager->pPCache, pgno, pBase); assert( pPg!=0 ); } } if( rc!=SQLITE_OK ){ /* Either the call to sqlite3PcacheFetch() returned an error or the ** pager was already in the error-state when this function was called. ** Set pPg to 0 and jump to the exception handler. */ pPg = 0; goto pager_acquire_err; } assert( pPg==(*ppPage) ); assert( pPg->pgno==pgno ); assert( pPg->pPager==pPager || pPg->pPager==0 ); if( pPg->pPager && !noContent ){ /* In this case the pcache already contains an initialized copy of ** the page. Return without further ado. */ assert( pgno<=PAGER_MAX_PGNO && pgno!=PAGER_MJ_PGNO(pPager) ); pPager->aStat[PAGER_STAT_HIT]++; return SQLITE_OK; }else{ /* The pager cache has created a new page. Its content needs to ** be initialized. */ pPg->pPager = pPager; /* The maximum page number is 2^31. Return SQLITE_CORRUPT if a page ** number greater than this, or the unused locking-page, is requested. */ if( pgno>PAGER_MAX_PGNO || pgno==PAGER_MJ_PGNO(pPager) ){ rc = SQLITE_CORRUPT_BKPT; goto pager_acquire_err; } assert( !isOpen(pPager->fd) || !MEMDB ); if( !isOpen(pPager->fd) || pPager->dbSizepPager->mxPgno ){ rc = SQLITE_FULL; goto pager_acquire_err; } if( noContent ){ /* Failure to set the bits in the InJournal bit-vectors is benign. ** It merely means that we might do some extra work to journal a ** page that does not need to be journaled. Nevertheless, be sure ** to test the case where a malloc error occurs while trying to set ** a bit in a bit vector. */ sqlite3BeginBenignMalloc(); if( pgno<=pPager->dbOrigSize ){ TESTONLY( rc = ) sqlite3BitvecSet(pPager->pInJournal, pgno); testcase( rc==SQLITE_NOMEM ); } TESTONLY( rc = ) addToSavepointBitvecs(pPager, pgno); testcase( rc==SQLITE_NOMEM ); sqlite3EndBenignMalloc(); } memset(pPg->pData, 0, pPager->pageSize); IOTRACE(("ZERO %p %d\n", pPager, pgno)); }else{ if( pagerUseWal(pPager) && bMmapOk==0 ){ rc = sqlite3WalFindFrame(pPager->pWal, pgno, &iFrame); if( rc!=SQLITE_OK ) goto pager_acquire_err; } assert( pPg->pPager==pPager ); pPager->aStat[PAGER_STAT_MISS]++; rc = readDbPage(pPg, iFrame); if( rc!=SQLITE_OK ){ goto pager_acquire_err; } } pager_set_pagehash(pPg); } return SQLITE_OK; pager_acquire_err: assert( rc!=SQLITE_OK ); if( pPg ){ sqlite3PcacheDrop(pPg); } pagerUnlockIfUnused(pPager); *ppPage = 0; return rc; } /* ** Acquire a page if it is already in the in-memory cache. Do ** not read the page from disk. Return a pointer to the page, ** or 0 if the page is not in cache. ** ** See also sqlite3PagerGet(). The difference between this routine ** and sqlite3PagerGet() is that _get() will go to the disk and read ** in the page if the page is not already in cache. This routine ** returns NULL if the page is not in cache or if a disk I/O error ** has ever happened. */ SQLITE_PRIVATE DbPage *sqlite3PagerLookup(Pager *pPager, Pgno pgno){ sqlite3_pcache_page *pPage; assert( pPager!=0 ); assert( pgno!=0 ); assert( pPager->pPCache!=0 ); pPage = sqlite3PcacheFetch(pPager->pPCache, pgno, 0); assert( pPage==0 || pPager->hasHeldSharedLock ); if( pPage==0 ) return 0; return sqlite3PcacheFetchFinish(pPager->pPCache, pgno, pPage); } /* ** Release a page reference. ** ** If the number of references to the page drop to zero, then the ** page is added to the LRU list. When all references to all pages ** are released, a rollback occurs and the lock on the database is ** removed. */ SQLITE_PRIVATE void sqlite3PagerUnrefNotNull(DbPage *pPg){ Pager *pPager; assert( pPg!=0 ); pPager = pPg->pPager; if( pPg->flags & PGHDR_MMAP ){ pagerReleaseMapPage(pPg); }else{ sqlite3PcacheRelease(pPg); } pagerUnlockIfUnused(pPager); } SQLITE_PRIVATE void sqlite3PagerUnref(DbPage *pPg){ if( pPg ) sqlite3PagerUnrefNotNull(pPg); } /* ** This function is called at the start of every write transaction. ** There must already be a RESERVED or EXCLUSIVE lock on the database ** file when this routine is called. ** ** Open the journal file for pager pPager and write a journal header ** to the start of it. If there are active savepoints, open the sub-journal ** as well. This function is only used when the journal file is being ** opened to write a rollback log for a transaction. It is not used ** when opening a hot journal file to roll it back. ** ** If the journal file is already open (as it may be in exclusive mode), ** then this function just writes a journal header to the start of the ** already open file. ** ** Whether or not the journal file is opened by this function, the ** Pager.pInJournal bitvec structure is allocated. ** ** Return SQLITE_OK if everything is successful. Otherwise, return ** SQLITE_NOMEM if the attempt to allocate Pager.pInJournal fails, or ** an IO error code if opening or writing the journal file fails. */ static int pager_open_journal(Pager *pPager){ int rc = SQLITE_OK; /* Return code */ sqlite3_vfs * const pVfs = pPager->pVfs; /* Local cache of vfs pointer */ assert( pPager->eState==PAGER_WRITER_LOCKED ); assert( assert_pager_state(pPager) ); assert( pPager->pInJournal==0 ); /* If already in the error state, this function is a no-op. But on ** the other hand, this routine is never called if we are already in ** an error state. */ if( NEVER(pPager->errCode) ) return pPager->errCode; if( !pagerUseWal(pPager) && pPager->journalMode!=PAGER_JOURNALMODE_OFF ){ pPager->pInJournal = sqlite3BitvecCreate(pPager->dbSize); if( pPager->pInJournal==0 ){ return SQLITE_NOMEM_BKPT; } /* Open the journal file if it is not already open. */ if( !isOpen(pPager->jfd) ){ if( pPager->journalMode==PAGER_JOURNALMODE_MEMORY ){ sqlite3MemJournalOpen(pPager->jfd); }else{ int flags = SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE; int nSpill; if( pPager->tempFile ){ flags |= (SQLITE_OPEN_DELETEONCLOSE|SQLITE_OPEN_TEMP_JOURNAL); nSpill = sqlite3Config.nStmtSpill; }else{ flags |= SQLITE_OPEN_MAIN_JOURNAL; nSpill = jrnlBufferSize(pPager); } /* Verify that the database still has the same name as it did when ** it was originally opened. */ rc = databaseIsUnmoved(pPager); if( rc==SQLITE_OK ){ rc = sqlite3JournalOpen ( pVfs, pPager->zJournal, pPager->jfd, flags, nSpill ); } } assert( rc!=SQLITE_OK || isOpen(pPager->jfd) ); } /* Write the first journal header to the journal file and open ** the sub-journal if necessary. */ if( rc==SQLITE_OK ){ /* TODO: Check if all of these are really required. */ pPager->nRec = 0; pPager->journalOff = 0; pPager->setMaster = 0; pPager->journalHdr = 0; rc = writeJournalHdr(pPager); } } if( rc!=SQLITE_OK ){ sqlite3BitvecDestroy(pPager->pInJournal); pPager->pInJournal = 0; }else{ assert( pPager->eState==PAGER_WRITER_LOCKED ); pPager->eState = PAGER_WRITER_CACHEMOD; } return rc; } /* ** Begin a write-transaction on the specified pager object. If a ** write-transaction has already been opened, this function is a no-op. ** ** If the exFlag argument is false, then acquire at least a RESERVED ** lock on the database file. If exFlag is true, then acquire at least ** an EXCLUSIVE lock. If such a lock is already held, no locking ** functions need be called. ** ** If the subjInMemory argument is non-zero, then any sub-journal opened ** within this transaction will be opened as an in-memory file. This ** has no effect if the sub-journal is already opened (as it may be when ** running in exclusive mode) or if the transaction does not require a ** sub-journal. If the subjInMemory argument is zero, then any required ** sub-journal is implemented in-memory if pPager is an in-memory database, ** or using a temporary file otherwise. */ SQLITE_PRIVATE int sqlite3PagerBegin(Pager *pPager, int exFlag, int subjInMemory){ int rc = SQLITE_OK; if( pPager->errCode ) return pPager->errCode; assert( pPager->eState>=PAGER_READER && pPager->eStatesubjInMemory = (u8)subjInMemory; if( ALWAYS(pPager->eState==PAGER_READER) ){ assert( pPager->pInJournal==0 ); if( pagerUseWal(pPager) ){ /* If the pager is configured to use locking_mode=exclusive, and an ** exclusive lock on the database is not already held, obtain it now. */ if( pPager->exclusiveMode && sqlite3WalExclusiveMode(pPager->pWal, -1) ){ rc = pagerLockDb(pPager, EXCLUSIVE_LOCK); if( rc!=SQLITE_OK ){ return rc; } (void)sqlite3WalExclusiveMode(pPager->pWal, 1); } /* Grab the write lock on the log file. If successful, upgrade to ** PAGER_RESERVED state. Otherwise, return an error code to the caller. ** The busy-handler is not invoked if another connection already ** holds the write-lock. If possible, the upper layer will call it. */ rc = sqlite3WalBeginWriteTransaction(pPager->pWal); }else{ /* Obtain a RESERVED lock on the database file. If the exFlag parameter ** is true, then immediately upgrade this to an EXCLUSIVE lock. The ** busy-handler callback can be used when upgrading to the EXCLUSIVE ** lock, but not when obtaining the RESERVED lock. */ rc = pagerLockDb(pPager, RESERVED_LOCK); if( rc==SQLITE_OK && exFlag ){ rc = pager_wait_on_lock(pPager, EXCLUSIVE_LOCK); } } if( rc==SQLITE_OK ){ /* Change to WRITER_LOCKED state. ** ** WAL mode sets Pager.eState to PAGER_WRITER_LOCKED or CACHEMOD ** when it has an open transaction, but never to DBMOD or FINISHED. ** This is because in those states the code to roll back savepoint ** transactions may copy data from the sub-journal into the database ** file as well as into the page cache. Which would be incorrect in ** WAL mode. */ pPager->eState = PAGER_WRITER_LOCKED; pPager->dbHintSize = pPager->dbSize; pPager->dbFileSize = pPager->dbSize; pPager->dbOrigSize = pPager->dbSize; pPager->journalOff = 0; } assert( rc==SQLITE_OK || pPager->eState==PAGER_READER ); assert( rc!=SQLITE_OK || pPager->eState==PAGER_WRITER_LOCKED ); assert( assert_pager_state(pPager) ); } PAGERTRACE(("TRANSACTION %d\n", PAGERID(pPager))); return rc; } /* ** Write page pPg onto the end of the rollback journal. */ static SQLITE_NOINLINE int pagerAddPageToRollbackJournal(PgHdr *pPg){ Pager *pPager = pPg->pPager; int rc; u32 cksum; char *pData2; i64 iOff = pPager->journalOff; /* We should never write to the journal file the page that ** contains the database locks. The following assert verifies ** that we do not. */ assert( pPg->pgno!=PAGER_MJ_PGNO(pPager) ); assert( pPager->journalHdr<=pPager->journalOff ); CODEC2(pPager, pPg->pData, pPg->pgno, 7, return SQLITE_NOMEM_BKPT, pData2); cksum = pager_cksum(pPager, (u8*)pData2); /* Even if an IO or diskfull error occurs while journalling the ** page in the block above, set the need-sync flag for the page. ** Otherwise, when the transaction is rolled back, the logic in ** playback_one_page() will think that the page needs to be restored ** in the database file. And if an IO error occurs while doing so, ** then corruption may follow. */ pPg->flags |= PGHDR_NEED_SYNC; rc = write32bits(pPager->jfd, iOff, pPg->pgno); if( rc!=SQLITE_OK ) return rc; rc = sqlite3OsWrite(pPager->jfd, pData2, pPager->pageSize, iOff+4); if( rc!=SQLITE_OK ) return rc; rc = write32bits(pPager->jfd, iOff+pPager->pageSize+4, cksum); if( rc!=SQLITE_OK ) return rc; IOTRACE(("JOUT %p %d %lld %d\n", pPager, pPg->pgno, pPager->journalOff, pPager->pageSize)); PAGER_INCR(sqlite3_pager_writej_count); PAGERTRACE(("JOURNAL %d page %d needSync=%d hash(%08x)\n", PAGERID(pPager), pPg->pgno, ((pPg->flags&PGHDR_NEED_SYNC)?1:0), pager_pagehash(pPg))); pPager->journalOff += 8 + pPager->pageSize; pPager->nRec++; assert( pPager->pInJournal!=0 ); rc = sqlite3BitvecSet(pPager->pInJournal, pPg->pgno); testcase( rc==SQLITE_NOMEM ); assert( rc==SQLITE_OK || rc==SQLITE_NOMEM ); rc |= addToSavepointBitvecs(pPager, pPg->pgno); assert( rc==SQLITE_OK || rc==SQLITE_NOMEM ); return rc; } /* ** Mark a single data page as writeable. The page is written into the ** main journal or sub-journal as required. If the page is written into ** one of the journals, the corresponding bit is set in the ** Pager.pInJournal bitvec and the PagerSavepoint.pInSavepoint bitvecs ** of any open savepoints as appropriate. */ static int pager_write(PgHdr *pPg){ Pager *pPager = pPg->pPager; int rc = SQLITE_OK; /* This routine is not called unless a write-transaction has already ** been started. The journal file may or may not be open at this point. ** It is never called in the ERROR state. */ assert( pPager->eState==PAGER_WRITER_LOCKED || pPager->eState==PAGER_WRITER_CACHEMOD || pPager->eState==PAGER_WRITER_DBMOD ); assert( assert_pager_state(pPager) ); assert( pPager->errCode==0 ); assert( pPager->readOnly==0 ); CHECK_PAGE(pPg); /* The journal file needs to be opened. Higher level routines have already ** obtained the necessary locks to begin the write-transaction, but the ** rollback journal might not yet be open. Open it now if this is the case. ** ** This is done before calling sqlite3PcacheMakeDirty() on the page. ** Otherwise, if it were done after calling sqlite3PcacheMakeDirty(), then ** an error might occur and the pager would end up in WRITER_LOCKED state ** with pages marked as dirty in the cache. */ if( pPager->eState==PAGER_WRITER_LOCKED ){ rc = pager_open_journal(pPager); if( rc!=SQLITE_OK ) return rc; } assert( pPager->eState>=PAGER_WRITER_CACHEMOD ); assert( assert_pager_state(pPager) ); /* Mark the page that is about to be modified as dirty. */ sqlite3PcacheMakeDirty(pPg); /* If a rollback journal is in use, them make sure the page that is about ** to change is in the rollback journal, or if the page is a new page off ** then end of the file, make sure it is marked as PGHDR_NEED_SYNC. */ assert( (pPager->pInJournal!=0) == isOpen(pPager->jfd) ); if( pPager->pInJournal!=0 && sqlite3BitvecTestNotNull(pPager->pInJournal, pPg->pgno)==0 ){ assert( pagerUseWal(pPager)==0 ); if( pPg->pgno<=pPager->dbOrigSize ){ rc = pagerAddPageToRollbackJournal(pPg); if( rc!=SQLITE_OK ){ return rc; } }else{ if( pPager->eState!=PAGER_WRITER_DBMOD ){ pPg->flags |= PGHDR_NEED_SYNC; } PAGERTRACE(("APPEND %d page %d needSync=%d\n", PAGERID(pPager), pPg->pgno, ((pPg->flags&PGHDR_NEED_SYNC)?1:0))); } } /* The PGHDR_DIRTY bit is set above when the page was added to the dirty-list ** and before writing the page into the rollback journal. Wait until now, ** after the page has been successfully journalled, before setting the ** PGHDR_WRITEABLE bit that indicates that the page can be safely modified. */ pPg->flags |= PGHDR_WRITEABLE; /* If the statement journal is open and the page is not in it, ** then write the page into the statement journal. */ if( pPager->nSavepoint>0 ){ rc = subjournalPageIfRequired(pPg); } /* Update the database size and return. */ if( pPager->dbSizepgno ){ pPager->dbSize = pPg->pgno; } return rc; } /* ** This is a variant of sqlite3PagerWrite() that runs when the sector size ** is larger than the page size. SQLite makes the (reasonable) assumption that ** all bytes of a sector are written together by hardware. Hence, all bytes of ** a sector need to be journalled in case of a power loss in the middle of ** a write. ** ** Usually, the sector size is less than or equal to the page size, in which ** case pages can be individually written. This routine only runs in the ** exceptional case where the page size is smaller than the sector size. */ static SQLITE_NOINLINE int pagerWriteLargeSector(PgHdr *pPg){ int rc = SQLITE_OK; /* Return code */ Pgno nPageCount; /* Total number of pages in database file */ Pgno pg1; /* First page of the sector pPg is located on. */ int nPage = 0; /* Number of pages starting at pg1 to journal */ int ii; /* Loop counter */ int needSync = 0; /* True if any page has PGHDR_NEED_SYNC */ Pager *pPager = pPg->pPager; /* The pager that owns pPg */ Pgno nPagePerSector = (pPager->sectorSize/pPager->pageSize); /* Set the doNotSpill NOSYNC bit to 1. This is because we cannot allow ** a journal header to be written between the pages journaled by ** this function. */ assert( !MEMDB ); assert( (pPager->doNotSpill & SPILLFLAG_NOSYNC)==0 ); pPager->doNotSpill |= SPILLFLAG_NOSYNC; /* This trick assumes that both the page-size and sector-size are ** an integer power of 2. It sets variable pg1 to the identifier ** of the first page of the sector pPg is located on. */ pg1 = ((pPg->pgno-1) & ~(nPagePerSector-1)) + 1; nPageCount = pPager->dbSize; if( pPg->pgno>nPageCount ){ nPage = (pPg->pgno - pg1)+1; }else if( (pg1+nPagePerSector-1)>nPageCount ){ nPage = nPageCount+1-pg1; }else{ nPage = nPagePerSector; } assert(nPage>0); assert(pg1<=pPg->pgno); assert((pg1+nPage)>pPg->pgno); for(ii=0; iipgno || !sqlite3BitvecTest(pPager->pInJournal, pg) ){ if( pg!=PAGER_MJ_PGNO(pPager) ){ rc = sqlite3PagerGet(pPager, pg, &pPage, 0); if( rc==SQLITE_OK ){ rc = pager_write(pPage); if( pPage->flags&PGHDR_NEED_SYNC ){ needSync = 1; } sqlite3PagerUnrefNotNull(pPage); } } }else if( (pPage = sqlite3PagerLookup(pPager, pg))!=0 ){ if( pPage->flags&PGHDR_NEED_SYNC ){ needSync = 1; } sqlite3PagerUnrefNotNull(pPage); } } /* If the PGHDR_NEED_SYNC flag is set for any of the nPage pages ** starting at pg1, then it needs to be set for all of them. Because ** writing to any of these nPage pages may damage the others, the ** journal file must contain sync()ed copies of all of them ** before any of them can be written out to the database file. */ if( rc==SQLITE_OK && needSync ){ assert( !MEMDB ); for(ii=0; iiflags |= PGHDR_NEED_SYNC; sqlite3PagerUnrefNotNull(pPage); } } } assert( (pPager->doNotSpill & SPILLFLAG_NOSYNC)!=0 ); pPager->doNotSpill &= ~SPILLFLAG_NOSYNC; return rc; } /* ** Mark a data page as writeable. This routine must be called before ** making changes to a page. The caller must check the return value ** of this function and be careful not to change any page data unless ** this routine returns SQLITE_OK. ** ** The difference between this function and pager_write() is that this ** function also deals with the special case where 2 or more pages ** fit on a single disk sector. In this case all co-resident pages ** must have been written to the journal file before returning. ** ** If an error occurs, SQLITE_NOMEM or an IO error code is returned ** as appropriate. Otherwise, SQLITE_OK. */ SQLITE_PRIVATE int sqlite3PagerWrite(PgHdr *pPg){ Pager *pPager = pPg->pPager; assert( (pPg->flags & PGHDR_MMAP)==0 ); assert( pPager->eState>=PAGER_WRITER_LOCKED ); assert( assert_pager_state(pPager) ); if( pPager->errCode ){ return pPager->errCode; }else if( (pPg->flags & PGHDR_WRITEABLE)!=0 && pPager->dbSize>=pPg->pgno ){ if( pPager->nSavepoint ) return subjournalPageIfRequired(pPg); return SQLITE_OK; }else if( pPager->sectorSize > (u32)pPager->pageSize ){ assert( pPager->tempFile==0 ); return pagerWriteLargeSector(pPg); }else{ return pager_write(pPg); } } /* ** Return TRUE if the page given in the argument was previously passed ** to sqlite3PagerWrite(). In other words, return TRUE if it is ok ** to change the content of the page. */ #ifndef NDEBUG SQLITE_PRIVATE int sqlite3PagerIswriteable(DbPage *pPg){ return pPg->flags & PGHDR_WRITEABLE; } #endif /* ** A call to this routine tells the pager that it is not necessary to ** write the information on page pPg back to the disk, even though ** that page might be marked as dirty. This happens, for example, when ** the page has been added as a leaf of the freelist and so its ** content no longer matters. ** ** The overlying software layer calls this routine when all of the data ** on the given page is unused. The pager marks the page as clean so ** that it does not get written to disk. ** ** Tests show that this optimization can quadruple the speed of large ** DELETE operations. ** ** This optimization cannot be used with a temp-file, as the page may ** have been dirty at the start of the transaction. In that case, if ** memory pressure forces page pPg out of the cache, the data does need ** to be written out to disk so that it may be read back in if the ** current transaction is rolled back. */ SQLITE_PRIVATE void sqlite3PagerDontWrite(PgHdr *pPg){ Pager *pPager = pPg->pPager; if( !pPager->tempFile && (pPg->flags&PGHDR_DIRTY) && pPager->nSavepoint==0 ){ PAGERTRACE(("DONT_WRITE page %d of %d\n", pPg->pgno, PAGERID(pPager))); IOTRACE(("CLEAN %p %d\n", pPager, pPg->pgno)) pPg->flags |= PGHDR_DONT_WRITE; pPg->flags &= ~PGHDR_WRITEABLE; testcase( pPg->flags & PGHDR_NEED_SYNC ); pager_set_pagehash(pPg); } } /* ** This routine is called to increment the value of the database file ** change-counter, stored as a 4-byte big-endian integer starting at ** byte offset 24 of the pager file. The secondary change counter at ** 92 is also updated, as is the SQLite version number at offset 96. ** ** But this only happens if the pPager->changeCountDone flag is false. ** To avoid excess churning of page 1, the update only happens once. ** See also the pager_write_changecounter() routine that does an ** unconditional update of the change counters. ** ** If the isDirectMode flag is zero, then this is done by calling ** sqlite3PagerWrite() on page 1, then modifying the contents of the ** page data. In this case the file will be updated when the current ** transaction is committed. ** ** The isDirectMode flag may only be non-zero if the library was compiled ** with the SQLITE_ENABLE_ATOMIC_WRITE macro defined. In this case, ** if isDirect is non-zero, then the database file is updated directly ** by writing an updated version of page 1 using a call to the ** sqlite3OsWrite() function. */ static int pager_incr_changecounter(Pager *pPager, int isDirectMode){ int rc = SQLITE_OK; assert( pPager->eState==PAGER_WRITER_CACHEMOD || pPager->eState==PAGER_WRITER_DBMOD ); assert( assert_pager_state(pPager) ); /* Declare and initialize constant integer 'isDirect'. If the ** atomic-write optimization is enabled in this build, then isDirect ** is initialized to the value passed as the isDirectMode parameter ** to this function. Otherwise, it is always set to zero. ** ** The idea is that if the atomic-write optimization is not ** enabled at compile time, the compiler can omit the tests of ** 'isDirect' below, as well as the block enclosed in the ** "if( isDirect )" condition. */ #ifndef SQLITE_ENABLE_ATOMIC_WRITE # define DIRECT_MODE 0 assert( isDirectMode==0 ); UNUSED_PARAMETER(isDirectMode); #else # define DIRECT_MODE isDirectMode #endif if( !pPager->changeCountDone && ALWAYS(pPager->dbSize>0) ){ PgHdr *pPgHdr; /* Reference to page 1 */ assert( !pPager->tempFile && isOpen(pPager->fd) ); /* Open page 1 of the file for writing. */ rc = sqlite3PagerGet(pPager, 1, &pPgHdr, 0); assert( pPgHdr==0 || rc==SQLITE_OK ); /* If page one was fetched successfully, and this function is not ** operating in direct-mode, make page 1 writable. When not in ** direct mode, page 1 is always held in cache and hence the PagerGet() ** above is always successful - hence the ALWAYS on rc==SQLITE_OK. */ if( !DIRECT_MODE && ALWAYS(rc==SQLITE_OK) ){ rc = sqlite3PagerWrite(pPgHdr); } if( rc==SQLITE_OK ){ /* Actually do the update of the change counter */ pager_write_changecounter(pPgHdr); /* If running in direct mode, write the contents of page 1 to the file. */ if( DIRECT_MODE ){ const void *zBuf; assert( pPager->dbFileSize>0 ); CODEC2(pPager, pPgHdr->pData, 1, 6, rc=SQLITE_NOMEM_BKPT, zBuf); if( rc==SQLITE_OK ){ rc = sqlite3OsWrite(pPager->fd, zBuf, pPager->pageSize, 0); pPager->aStat[PAGER_STAT_WRITE]++; } if( rc==SQLITE_OK ){ /* Update the pager's copy of the change-counter. Otherwise, the ** next time a read transaction is opened the cache will be ** flushed (as the change-counter values will not match). */ const void *pCopy = (const void *)&((const char *)zBuf)[24]; memcpy(&pPager->dbFileVers, pCopy, sizeof(pPager->dbFileVers)); pPager->changeCountDone = 1; } }else{ pPager->changeCountDone = 1; } } /* Release the page reference. */ sqlite3PagerUnref(pPgHdr); } return rc; } /* ** Sync the database file to disk. This is a no-op for in-memory databases ** or pages with the Pager.noSync flag set. ** ** If successful, or if called on a pager for which it is a no-op, this ** function returns SQLITE_OK. Otherwise, an IO error code is returned. */ SQLITE_PRIVATE int sqlite3PagerSync(Pager *pPager, const char *zMaster){ int rc = SQLITE_OK; if( isOpen(pPager->fd) ){ void *pArg = (void*)zMaster; rc = sqlite3OsFileControl(pPager->fd, SQLITE_FCNTL_SYNC, pArg); if( rc==SQLITE_NOTFOUND ) rc = SQLITE_OK; } if( rc==SQLITE_OK && !pPager->noSync ){ assert( !MEMDB ); rc = sqlite3OsSync(pPager->fd, pPager->syncFlags); } return rc; } /* ** This function may only be called while a write-transaction is active in ** rollback. If the connection is in WAL mode, this call is a no-op. ** Otherwise, if the connection does not already have an EXCLUSIVE lock on ** the database file, an attempt is made to obtain one. ** ** If the EXCLUSIVE lock is already held or the attempt to obtain it is ** successful, or the connection is in WAL mode, SQLITE_OK is returned. ** Otherwise, either SQLITE_BUSY or an SQLITE_IOERR_XXX error code is ** returned. */ SQLITE_PRIVATE int sqlite3PagerExclusiveLock(Pager *pPager){ int rc = pPager->errCode; assert( assert_pager_state(pPager) ); if( rc==SQLITE_OK ){ assert( pPager->eState==PAGER_WRITER_CACHEMOD || pPager->eState==PAGER_WRITER_DBMOD || pPager->eState==PAGER_WRITER_LOCKED ); assert( assert_pager_state(pPager) ); if( 0==pagerUseWal(pPager) ){ rc = pager_wait_on_lock(pPager, EXCLUSIVE_LOCK); } } return rc; } /* ** Sync the database file for the pager pPager. zMaster points to the name ** of a master journal file that should be written into the individual ** journal file. zMaster may be NULL, which is interpreted as no master ** journal (a single database transaction). ** ** This routine ensures that: ** ** * The database file change-counter is updated, ** * the journal is synced (unless the atomic-write optimization is used), ** * all dirty pages are written to the database file, ** * the database file is truncated (if required), and ** * the database file synced. ** ** The only thing that remains to commit the transaction is to finalize ** (delete, truncate or zero the first part of) the journal file (or ** delete the master journal file if specified). ** ** Note that if zMaster==NULL, this does not overwrite a previous value ** passed to an sqlite3PagerCommitPhaseOne() call. ** ** If the final parameter - noSync - is true, then the database file itself ** is not synced. The caller must call sqlite3PagerSync() directly to ** sync the database file before calling CommitPhaseTwo() to delete the ** journal file in this case. */ SQLITE_PRIVATE int sqlite3PagerCommitPhaseOne( Pager *pPager, /* Pager object */ const char *zMaster, /* If not NULL, the master journal name */ int noSync /* True to omit the xSync on the db file */ ){ int rc = SQLITE_OK; /* Return code */ assert( pPager->eState==PAGER_WRITER_LOCKED || pPager->eState==PAGER_WRITER_CACHEMOD || pPager->eState==PAGER_WRITER_DBMOD || pPager->eState==PAGER_ERROR ); assert( assert_pager_state(pPager) ); /* If a prior error occurred, report that error again. */ if( NEVER(pPager->errCode) ) return pPager->errCode; /* Provide the ability to easily simulate an I/O error during testing */ if( sqlite3FaultSim(400) ) return SQLITE_IOERR; PAGERTRACE(("DATABASE SYNC: File=%s zMaster=%s nSize=%d\n", pPager->zFilename, zMaster, pPager->dbSize)); /* If no database changes have been made, return early. */ if( pPager->eStatetempFile ); assert( isOpen(pPager->fd) || pPager->tempFile ); if( 0==pagerFlushOnCommit(pPager, 1) ){ /* If this is an in-memory db, or no pages have been written to, or this ** function has already been called, it is mostly a no-op. However, any ** backup in progress needs to be restarted. */ sqlite3BackupRestart(pPager->pBackup); }else{ if( pagerUseWal(pPager) ){ PgHdr *pList = sqlite3PcacheDirtyList(pPager->pPCache); PgHdr *pPageOne = 0; if( pList==0 ){ /* Must have at least one page for the WAL commit flag. ** Ticket [2d1a5c67dfc2363e44f29d9bbd57f] 2011-05-18 */ rc = sqlite3PagerGet(pPager, 1, &pPageOne, 0); pList = pPageOne; pList->pDirty = 0; } assert( rc==SQLITE_OK ); if( ALWAYS(pList) ){ rc = pagerWalFrames(pPager, pList, pPager->dbSize, 1); } sqlite3PagerUnref(pPageOne); if( rc==SQLITE_OK ){ sqlite3PcacheCleanAll(pPager->pPCache); } }else{ /* The following block updates the change-counter. Exactly how it ** does this depends on whether or not the atomic-update optimization ** was enabled at compile time, and if this transaction meets the ** runtime criteria to use the operation: ** ** * The file-system supports the atomic-write property for ** blocks of size page-size, and ** * This commit is not part of a multi-file transaction, and ** * Exactly one page has been modified and store in the journal file. ** ** If the optimization was not enabled at compile time, then the ** pager_incr_changecounter() function is called to update the change ** counter in 'indirect-mode'. If the optimization is compiled in but ** is not applicable to this transaction, call sqlite3JournalCreate() ** to make sure the journal file has actually been created, then call ** pager_incr_changecounter() to update the change-counter in indirect ** mode. ** ** Otherwise, if the optimization is both enabled and applicable, ** then call pager_incr_changecounter() to update the change-counter ** in 'direct' mode. In this case the journal file will never be ** created for this transaction. */ #ifdef SQLITE_ENABLE_ATOMIC_WRITE PgHdr *pPg; assert( isOpen(pPager->jfd) || pPager->journalMode==PAGER_JOURNALMODE_OFF || pPager->journalMode==PAGER_JOURNALMODE_WAL ); if( !zMaster && isOpen(pPager->jfd) && pPager->journalOff==jrnlBufferSize(pPager) && pPager->dbSize>=pPager->dbOrigSize && (0==(pPg = sqlite3PcacheDirtyList(pPager->pPCache)) || 0==pPg->pDirty) ){ /* Update the db file change counter via the direct-write method. The ** following call will modify the in-memory representation of page 1 ** to include the updated change counter and then write page 1 ** directly to the database file. Because of the atomic-write ** property of the host file-system, this is safe. */ rc = pager_incr_changecounter(pPager, 1); }else{ rc = sqlite3JournalCreate(pPager->jfd); if( rc==SQLITE_OK ){ rc = pager_incr_changecounter(pPager, 0); } } #else rc = pager_incr_changecounter(pPager, 0); #endif if( rc!=SQLITE_OK ) goto commit_phase_one_exit; /* Write the master journal name into the journal file. If a master ** journal file name has already been written to the journal file, ** or if zMaster is NULL (no master journal), then this call is a no-op. */ rc = writeMasterJournal(pPager, zMaster); if( rc!=SQLITE_OK ) goto commit_phase_one_exit; /* Sync the journal file and write all dirty pages to the database. ** If the atomic-update optimization is being used, this sync will not ** create the journal file or perform any real IO. ** ** Because the change-counter page was just modified, unless the ** atomic-update optimization is used it is almost certain that the ** journal requires a sync here. However, in locking_mode=exclusive ** on a system under memory pressure it is just possible that this is ** not the case. In this case it is likely enough that the redundant ** xSync() call will be changed to a no-op by the OS anyhow. */ rc = syncJournal(pPager, 0); if( rc!=SQLITE_OK ) goto commit_phase_one_exit; rc = pager_write_pagelist(pPager,sqlite3PcacheDirtyList(pPager->pPCache)); if( rc!=SQLITE_OK ){ assert( rc!=SQLITE_IOERR_BLOCKED ); goto commit_phase_one_exit; } sqlite3PcacheCleanAll(pPager->pPCache); /* If the file on disk is smaller than the database image, use ** pager_truncate to grow the file here. This can happen if the database ** image was extended as part of the current transaction and then the ** last page in the db image moved to the free-list. In this case the ** last page is never written out to disk, leaving the database file ** undersized. Fix this now if it is the case. */ if( pPager->dbSize>pPager->dbFileSize ){ Pgno nNew = pPager->dbSize - (pPager->dbSize==PAGER_MJ_PGNO(pPager)); assert( pPager->eState==PAGER_WRITER_DBMOD ); rc = pager_truncate(pPager, nNew); if( rc!=SQLITE_OK ) goto commit_phase_one_exit; } /* Finally, sync the database file. */ if( !noSync ){ rc = sqlite3PagerSync(pPager, zMaster); } IOTRACE(("DBSYNC %p\n", pPager)) } } commit_phase_one_exit: if( rc==SQLITE_OK && !pagerUseWal(pPager) ){ pPager->eState = PAGER_WRITER_FINISHED; } return rc; } /* ** When this function is called, the database file has been completely ** updated to reflect the changes made by the current transaction and ** synced to disk. The journal file still exists in the file-system ** though, and if a failure occurs at this point it will eventually ** be used as a hot-journal and the current transaction rolled back. ** ** This function finalizes the journal file, either by deleting, ** truncating or partially zeroing it, so that it cannot be used ** for hot-journal rollback. Once this is done the transaction is ** irrevocably committed. ** ** If an error occurs, an IO error code is returned and the pager ** moves into the error state. Otherwise, SQLITE_OK is returned. */ SQLITE_PRIVATE int sqlite3PagerCommitPhaseTwo(Pager *pPager){ int rc = SQLITE_OK; /* Return code */ /* This routine should not be called if a prior error has occurred. ** But if (due to a coding error elsewhere in the system) it does get ** called, just return the same error code without doing anything. */ if( NEVER(pPager->errCode) ) return pPager->errCode; assert( pPager->eState==PAGER_WRITER_LOCKED || pPager->eState==PAGER_WRITER_FINISHED || (pagerUseWal(pPager) && pPager->eState==PAGER_WRITER_CACHEMOD) ); assert( assert_pager_state(pPager) ); /* An optimization. If the database was not actually modified during ** this transaction, the pager is running in exclusive-mode and is ** using persistent journals, then this function is a no-op. ** ** The start of the journal file currently contains a single journal ** header with the nRec field set to 0. If such a journal is used as ** a hot-journal during hot-journal rollback, 0 changes will be made ** to the database file. So there is no need to zero the journal ** header. Since the pager is in exclusive mode, there is no need ** to drop any locks either. */ if( pPager->eState==PAGER_WRITER_LOCKED && pPager->exclusiveMode && pPager->journalMode==PAGER_JOURNALMODE_PERSIST ){ assert( pPager->journalOff==JOURNAL_HDR_SZ(pPager) || !pPager->journalOff ); pPager->eState = PAGER_READER; return SQLITE_OK; } PAGERTRACE(("COMMIT %d\n", PAGERID(pPager))); pPager->iDataVersion++; rc = pager_end_transaction(pPager, pPager->setMaster, 1); return pager_error(pPager, rc); } /* ** If a write transaction is open, then all changes made within the ** transaction are reverted and the current write-transaction is closed. ** The pager falls back to PAGER_READER state if successful, or PAGER_ERROR ** state if an error occurs. ** ** If the pager is already in PAGER_ERROR state when this function is called, ** it returns Pager.errCode immediately. No work is performed in this case. ** ** Otherwise, in rollback mode, this function performs two functions: ** ** 1) It rolls back the journal file, restoring all database file and ** in-memory cache pages to the state they were in when the transaction ** was opened, and ** ** 2) It finalizes the journal file, so that it is not used for hot ** rollback at any point in the future. ** ** Finalization of the journal file (task 2) is only performed if the ** rollback is successful. ** ** In WAL mode, all cache-entries containing data modified within the ** current transaction are either expelled from the cache or reverted to ** their pre-transaction state by re-reading data from the database or ** WAL files. The WAL transaction is then closed. */ SQLITE_PRIVATE int sqlite3PagerRollback(Pager *pPager){ int rc = SQLITE_OK; /* Return code */ PAGERTRACE(("ROLLBACK %d\n", PAGERID(pPager))); /* PagerRollback() is a no-op if called in READER or OPEN state. If ** the pager is already in the ERROR state, the rollback is not ** attempted here. Instead, the error code is returned to the caller. */ assert( assert_pager_state(pPager) ); if( pPager->eState==PAGER_ERROR ) return pPager->errCode; if( pPager->eState<=PAGER_READER ) return SQLITE_OK; if( pagerUseWal(pPager) ){ int rc2; rc = sqlite3PagerSavepoint(pPager, SAVEPOINT_ROLLBACK, -1); rc2 = pager_end_transaction(pPager, pPager->setMaster, 0); if( rc==SQLITE_OK ) rc = rc2; }else if( !isOpen(pPager->jfd) || pPager->eState==PAGER_WRITER_LOCKED ){ int eState = pPager->eState; rc = pager_end_transaction(pPager, 0, 0); if( !MEMDB && eState>PAGER_WRITER_LOCKED ){ /* This can happen using journal_mode=off. Move the pager to the error ** state to indicate that the contents of the cache may not be trusted. ** Any active readers will get SQLITE_ABORT. */ pPager->errCode = SQLITE_ABORT; pPager->eState = PAGER_ERROR; return rc; } }else{ rc = pager_playback(pPager, 0); } assert( pPager->eState==PAGER_READER || rc!=SQLITE_OK ); assert( rc==SQLITE_OK || rc==SQLITE_FULL || rc==SQLITE_CORRUPT || rc==SQLITE_NOMEM || (rc&0xFF)==SQLITE_IOERR || rc==SQLITE_CANTOPEN ); /* If an error occurs during a ROLLBACK, we can no longer trust the pager ** cache. So call pager_error() on the way out to make any error persistent. */ return pager_error(pPager, rc); } /* ** Return TRUE if the database file is opened read-only. Return FALSE ** if the database is (in theory) writable. */ SQLITE_PRIVATE u8 sqlite3PagerIsreadonly(Pager *pPager){ return pPager->readOnly; } #ifdef SQLITE_DEBUG /* ** Return the sum of the reference counts for all pages held by pPager. */ SQLITE_PRIVATE int sqlite3PagerRefcount(Pager *pPager){ return sqlite3PcacheRefCount(pPager->pPCache); } #endif /* ** Return the approximate number of bytes of memory currently ** used by the pager and its associated cache. */ SQLITE_PRIVATE int sqlite3PagerMemUsed(Pager *pPager){ int perPageSize = pPager->pageSize + pPager->nExtra + sizeof(PgHdr) + 5*sizeof(void*); return perPageSize*sqlite3PcachePagecount(pPager->pPCache) + sqlite3MallocSize(pPager) + pPager->pageSize; } /* ** Return the number of references to the specified page. */ SQLITE_PRIVATE int sqlite3PagerPageRefcount(DbPage *pPage){ return sqlite3PcachePageRefcount(pPage); } #ifdef SQLITE_TEST /* ** This routine is used for testing and analysis only. */ SQLITE_PRIVATE int *sqlite3PagerStats(Pager *pPager){ static int a[11]; a[0] = sqlite3PcacheRefCount(pPager->pPCache); a[1] = sqlite3PcachePagecount(pPager->pPCache); a[2] = sqlite3PcacheGetCachesize(pPager->pPCache); a[3] = pPager->eState==PAGER_OPEN ? -1 : (int) pPager->dbSize; a[4] = pPager->eState; a[5] = pPager->errCode; a[6] = pPager->aStat[PAGER_STAT_HIT]; a[7] = pPager->aStat[PAGER_STAT_MISS]; a[8] = 0; /* Used to be pPager->nOvfl */ a[9] = pPager->nRead; a[10] = pPager->aStat[PAGER_STAT_WRITE]; return a; } #endif /* ** Parameter eStat must be either SQLITE_DBSTATUS_CACHE_HIT or ** SQLITE_DBSTATUS_CACHE_MISS. Before returning, *pnVal is incremented by the ** current cache hit or miss count, according to the value of eStat. If the ** reset parameter is non-zero, the cache hit or miss count is zeroed before ** returning. */ SQLITE_PRIVATE void sqlite3PagerCacheStat(Pager *pPager, int eStat, int reset, int *pnVal){ assert( eStat==SQLITE_DBSTATUS_CACHE_HIT || eStat==SQLITE_DBSTATUS_CACHE_MISS || eStat==SQLITE_DBSTATUS_CACHE_WRITE ); assert( SQLITE_DBSTATUS_CACHE_HIT+1==SQLITE_DBSTATUS_CACHE_MISS ); assert( SQLITE_DBSTATUS_CACHE_HIT+2==SQLITE_DBSTATUS_CACHE_WRITE ); assert( PAGER_STAT_HIT==0 && PAGER_STAT_MISS==1 && PAGER_STAT_WRITE==2 ); *pnVal += pPager->aStat[eStat - SQLITE_DBSTATUS_CACHE_HIT]; if( reset ){ pPager->aStat[eStat - SQLITE_DBSTATUS_CACHE_HIT] = 0; } } /* ** Return true if this is an in-memory or temp-file backed pager. */ SQLITE_PRIVATE int sqlite3PagerIsMemdb(Pager *pPager){ return pPager->tempFile; } /* ** Check that there are at least nSavepoint savepoints open. If there are ** currently less than nSavepoints open, then open one or more savepoints ** to make up the difference. If the number of savepoints is already ** equal to nSavepoint, then this function is a no-op. ** ** If a memory allocation fails, SQLITE_NOMEM is returned. If an error ** occurs while opening the sub-journal file, then an IO error code is ** returned. Otherwise, SQLITE_OK. */ static SQLITE_NOINLINE int pagerOpenSavepoint(Pager *pPager, int nSavepoint){ int rc = SQLITE_OK; /* Return code */ int nCurrent = pPager->nSavepoint; /* Current number of savepoints */ int ii; /* Iterator variable */ PagerSavepoint *aNew; /* New Pager.aSavepoint array */ assert( pPager->eState>=PAGER_WRITER_LOCKED ); assert( assert_pager_state(pPager) ); assert( nSavepoint>nCurrent && pPager->useJournal ); /* Grow the Pager.aSavepoint array using realloc(). Return SQLITE_NOMEM ** if the allocation fails. Otherwise, zero the new portion in case a ** malloc failure occurs while populating it in the for(...) loop below. */ aNew = (PagerSavepoint *)sqlite3Realloc( pPager->aSavepoint, sizeof(PagerSavepoint)*nSavepoint ); if( !aNew ){ return SQLITE_NOMEM_BKPT; } memset(&aNew[nCurrent], 0, (nSavepoint-nCurrent) * sizeof(PagerSavepoint)); pPager->aSavepoint = aNew; /* Populate the PagerSavepoint structures just allocated. */ for(ii=nCurrent; iidbSize; if( isOpen(pPager->jfd) && pPager->journalOff>0 ){ aNew[ii].iOffset = pPager->journalOff; }else{ aNew[ii].iOffset = JOURNAL_HDR_SZ(pPager); } aNew[ii].iSubRec = pPager->nSubRec; aNew[ii].pInSavepoint = sqlite3BitvecCreate(pPager->dbSize); if( !aNew[ii].pInSavepoint ){ return SQLITE_NOMEM_BKPT; } if( pagerUseWal(pPager) ){ sqlite3WalSavepoint(pPager->pWal, aNew[ii].aWalData); } pPager->nSavepoint = ii+1; } assert( pPager->nSavepoint==nSavepoint ); assertTruncateConstraint(pPager); return rc; } SQLITE_PRIVATE int sqlite3PagerOpenSavepoint(Pager *pPager, int nSavepoint){ assert( pPager->eState>=PAGER_WRITER_LOCKED ); assert( assert_pager_state(pPager) ); if( nSavepoint>pPager->nSavepoint && pPager->useJournal ){ return pagerOpenSavepoint(pPager, nSavepoint); }else{ return SQLITE_OK; } } /* ** This function is called to rollback or release (commit) a savepoint. ** The savepoint to release or rollback need not be the most recently ** created savepoint. ** ** Parameter op is always either SAVEPOINT_ROLLBACK or SAVEPOINT_RELEASE. ** If it is SAVEPOINT_RELEASE, then release and destroy the savepoint with ** index iSavepoint. If it is SAVEPOINT_ROLLBACK, then rollback all changes ** that have occurred since the specified savepoint was created. ** ** The savepoint to rollback or release is identified by parameter ** iSavepoint. A value of 0 means to operate on the outermost savepoint ** (the first created). A value of (Pager.nSavepoint-1) means operate ** on the most recently created savepoint. If iSavepoint is greater than ** (Pager.nSavepoint-1), then this function is a no-op. ** ** If a negative value is passed to this function, then the current ** transaction is rolled back. This is different to calling ** sqlite3PagerRollback() because this function does not terminate ** the transaction or unlock the database, it just restores the ** contents of the database to its original state. ** ** In any case, all savepoints with an index greater than iSavepoint ** are destroyed. If this is a release operation (op==SAVEPOINT_RELEASE), ** then savepoint iSavepoint is also destroyed. ** ** This function may return SQLITE_NOMEM if a memory allocation fails, ** or an IO error code if an IO error occurs while rolling back a ** savepoint. If no errors occur, SQLITE_OK is returned. */ SQLITE_PRIVATE int sqlite3PagerSavepoint(Pager *pPager, int op, int iSavepoint){ int rc = pPager->errCode; #ifdef SQLITE_ENABLE_ZIPVFS if( op==SAVEPOINT_RELEASE ) rc = SQLITE_OK; #endif assert( op==SAVEPOINT_RELEASE || op==SAVEPOINT_ROLLBACK ); assert( iSavepoint>=0 || op==SAVEPOINT_ROLLBACK ); if( rc==SQLITE_OK && iSavepointnSavepoint ){ int ii; /* Iterator variable */ int nNew; /* Number of remaining savepoints after this op. */ /* Figure out how many savepoints will still be active after this ** operation. Store this value in nNew. Then free resources associated ** with any savepoints that are destroyed by this operation. */ nNew = iSavepoint + (( op==SAVEPOINT_RELEASE ) ? 0 : 1); for(ii=nNew; iinSavepoint; ii++){ sqlite3BitvecDestroy(pPager->aSavepoint[ii].pInSavepoint); } pPager->nSavepoint = nNew; /* If this is a release of the outermost savepoint, truncate ** the sub-journal to zero bytes in size. */ if( op==SAVEPOINT_RELEASE ){ if( nNew==0 && isOpen(pPager->sjfd) ){ /* Only truncate if it is an in-memory sub-journal. */ if( sqlite3JournalIsInMemory(pPager->sjfd) ){ rc = sqlite3OsTruncate(pPager->sjfd, 0); assert( rc==SQLITE_OK ); } pPager->nSubRec = 0; } } /* Else this is a rollback operation, playback the specified savepoint. ** If this is a temp-file, it is possible that the journal file has ** not yet been opened. In this case there have been no changes to ** the database file, so the playback operation can be skipped. */ else if( pagerUseWal(pPager) || isOpen(pPager->jfd) ){ PagerSavepoint *pSavepoint = (nNew==0)?0:&pPager->aSavepoint[nNew-1]; rc = pagerPlaybackSavepoint(pPager, pSavepoint); assert(rc!=SQLITE_DONE); } #ifdef SQLITE_ENABLE_ZIPVFS /* If the cache has been modified but the savepoint cannot be rolled ** back journal_mode=off, put the pager in the error state. This way, ** if the VFS used by this pager includes ZipVFS, the entire transaction ** can be rolled back at the ZipVFS level. */ else if( pPager->journalMode==PAGER_JOURNALMODE_OFF && pPager->eState>=PAGER_WRITER_CACHEMOD ){ pPager->errCode = SQLITE_ABORT; pPager->eState = PAGER_ERROR; } #endif } return rc; } /* ** Return the full pathname of the database file. ** ** Except, if the pager is in-memory only, then return an empty string if ** nullIfMemDb is true. This routine is called with nullIfMemDb==1 when ** used to report the filename to the user, for compatibility with legacy ** behavior. But when the Btree needs to know the filename for matching to ** shared cache, it uses nullIfMemDb==0 so that in-memory databases can ** participate in shared-cache. */ SQLITE_PRIVATE const char *sqlite3PagerFilename(Pager *pPager, int nullIfMemDb){ return (nullIfMemDb && pPager->memDb) ? "" : pPager->zFilename; } /* ** Return the VFS structure for the pager. */ SQLITE_PRIVATE sqlite3_vfs *sqlite3PagerVfs(Pager *pPager){ return pPager->pVfs; } /* ** Return the file handle for the database file associated ** with the pager. This might return NULL if the file has ** not yet been opened. */ SQLITE_PRIVATE sqlite3_file *sqlite3PagerFile(Pager *pPager){ return pPager->fd; } /* ** Return the file handle for the journal file (if it exists). ** This will be either the rollback journal or the WAL file. */ SQLITE_PRIVATE sqlite3_file *sqlite3PagerJrnlFile(Pager *pPager){ #if SQLITE_OMIT_WAL return pPager->jfd; #else return pPager->pWal ? sqlite3WalFile(pPager->pWal) : pPager->jfd; #endif } /* ** Return the full pathname of the journal file. */ SQLITE_PRIVATE const char *sqlite3PagerJournalname(Pager *pPager){ return pPager->zJournal; } #ifdef SQLITE_HAS_CODEC /* ** Set or retrieve the codec for this pager */ SQLITE_PRIVATE void sqlite3PagerSetCodec( Pager *pPager, void *(*xCodec)(void*,void*,Pgno,int), void (*xCodecSizeChng)(void*,int,int), void (*xCodecFree)(void*), void *pCodec ){ if( pPager->xCodecFree ) pPager->xCodecFree(pPager->pCodec); pPager->xCodec = pPager->memDb ? 0 : xCodec; pPager->xCodecSizeChng = xCodecSizeChng; pPager->xCodecFree = xCodecFree; pPager->pCodec = pCodec; pagerReportSize(pPager); } SQLITE_PRIVATE void *sqlite3PagerGetCodec(Pager *pPager){ return pPager->pCodec; } /* ** This function is called by the wal module when writing page content ** into the log file. ** ** This function returns a pointer to a buffer containing the encrypted ** page content. If a malloc fails, this function may return NULL. */ SQLITE_PRIVATE void *sqlite3PagerCodec(PgHdr *pPg){ void *aData = 0; CODEC2(pPg->pPager, pPg->pData, pPg->pgno, 6, return 0, aData); return aData; } /* ** Return the current pager state */ SQLITE_PRIVATE int sqlite3PagerState(Pager *pPager){ return pPager->eState; } #endif /* SQLITE_HAS_CODEC */ #ifndef SQLITE_OMIT_AUTOVACUUM /* ** Move the page pPg to location pgno in the file. ** ** There must be no references to the page previously located at ** pgno (which we call pPgOld) though that page is allowed to be ** in cache. If the page previously located at pgno is not already ** in the rollback journal, it is not put there by by this routine. ** ** References to the page pPg remain valid. Updating any ** meta-data associated with pPg (i.e. data stored in the nExtra bytes ** allocated along with the page) is the responsibility of the caller. ** ** A transaction must be active when this routine is called. It used to be ** required that a statement transaction was not active, but this restriction ** has been removed (CREATE INDEX needs to move a page when a statement ** transaction is active). ** ** If the fourth argument, isCommit, is non-zero, then this page is being ** moved as part of a database reorganization just before the transaction ** is being committed. In this case, it is guaranteed that the database page ** pPg refers to will not be written to again within this transaction. ** ** This function may return SQLITE_NOMEM or an IO error code if an error ** occurs. Otherwise, it returns SQLITE_OK. */ SQLITE_PRIVATE int sqlite3PagerMovepage(Pager *pPager, DbPage *pPg, Pgno pgno, int isCommit){ PgHdr *pPgOld; /* The page being overwritten. */ Pgno needSyncPgno = 0; /* Old value of pPg->pgno, if sync is required */ int rc; /* Return code */ Pgno origPgno; /* The original page number */ assert( pPg->nRef>0 ); assert( pPager->eState==PAGER_WRITER_CACHEMOD || pPager->eState==PAGER_WRITER_DBMOD ); assert( assert_pager_state(pPager) ); /* In order to be able to rollback, an in-memory database must journal ** the page we are moving from. */ assert( pPager->tempFile || !MEMDB ); if( pPager->tempFile ){ rc = sqlite3PagerWrite(pPg); if( rc ) return rc; } /* If the page being moved is dirty and has not been saved by the latest ** savepoint, then save the current contents of the page into the ** sub-journal now. This is required to handle the following scenario: ** ** BEGIN; ** ** SAVEPOINT one; ** ** ROLLBACK TO one; ** ** If page X were not written to the sub-journal here, it would not ** be possible to restore its contents when the "ROLLBACK TO one" ** statement were is processed. ** ** subjournalPage() may need to allocate space to store pPg->pgno into ** one or more savepoint bitvecs. This is the reason this function ** may return SQLITE_NOMEM. */ if( (pPg->flags & PGHDR_DIRTY)!=0 && SQLITE_OK!=(rc = subjournalPageIfRequired(pPg)) ){ return rc; } PAGERTRACE(("MOVE %d page %d (needSync=%d) moves to %d\n", PAGERID(pPager), pPg->pgno, (pPg->flags&PGHDR_NEED_SYNC)?1:0, pgno)); IOTRACE(("MOVE %p %d %d\n", pPager, pPg->pgno, pgno)) /* If the journal needs to be sync()ed before page pPg->pgno can ** be written to, store pPg->pgno in local variable needSyncPgno. ** ** If the isCommit flag is set, there is no need to remember that ** the journal needs to be sync()ed before database page pPg->pgno ** can be written to. The caller has already promised not to write to it. */ if( (pPg->flags&PGHDR_NEED_SYNC) && !isCommit ){ needSyncPgno = pPg->pgno; assert( pPager->journalMode==PAGER_JOURNALMODE_OFF || pageInJournal(pPager, pPg) || pPg->pgno>pPager->dbOrigSize ); assert( pPg->flags&PGHDR_DIRTY ); } /* If the cache contains a page with page-number pgno, remove it ** from its hash chain. Also, if the PGHDR_NEED_SYNC flag was set for ** page pgno before the 'move' operation, it needs to be retained ** for the page moved there. */ pPg->flags &= ~PGHDR_NEED_SYNC; pPgOld = sqlite3PagerLookup(pPager, pgno); assert( !pPgOld || pPgOld->nRef==1 ); if( pPgOld ){ pPg->flags |= (pPgOld->flags&PGHDR_NEED_SYNC); if( pPager->tempFile ){ /* Do not discard pages from an in-memory database since we might ** need to rollback later. Just move the page out of the way. */ sqlite3PcacheMove(pPgOld, pPager->dbSize+1); }else{ sqlite3PcacheDrop(pPgOld); } } origPgno = pPg->pgno; sqlite3PcacheMove(pPg, pgno); sqlite3PcacheMakeDirty(pPg); /* For an in-memory database, make sure the original page continues ** to exist, in case the transaction needs to roll back. Use pPgOld ** as the original page since it has already been allocated. */ if( pPager->tempFile && pPgOld ){ sqlite3PcacheMove(pPgOld, origPgno); sqlite3PagerUnrefNotNull(pPgOld); } if( needSyncPgno ){ /* If needSyncPgno is non-zero, then the journal file needs to be ** sync()ed before any data is written to database file page needSyncPgno. ** Currently, no such page exists in the page-cache and the ** "is journaled" bitvec flag has been set. This needs to be remedied by ** loading the page into the pager-cache and setting the PGHDR_NEED_SYNC ** flag. ** ** If the attempt to load the page into the page-cache fails, (due ** to a malloc() or IO failure), clear the bit in the pInJournal[] ** array. Otherwise, if the page is loaded and written again in ** this transaction, it may be written to the database file before ** it is synced into the journal file. This way, it may end up in ** the journal file twice, but that is not a problem. */ PgHdr *pPgHdr; rc = sqlite3PagerGet(pPager, needSyncPgno, &pPgHdr, 0); if( rc!=SQLITE_OK ){ if( needSyncPgno<=pPager->dbOrigSize ){ assert( pPager->pTmpSpace!=0 ); sqlite3BitvecClear(pPager->pInJournal, needSyncPgno, pPager->pTmpSpace); } return rc; } pPgHdr->flags |= PGHDR_NEED_SYNC; sqlite3PcacheMakeDirty(pPgHdr); sqlite3PagerUnrefNotNull(pPgHdr); } return SQLITE_OK; } #endif /* ** The page handle passed as the first argument refers to a dirty page ** with a page number other than iNew. This function changes the page's ** page number to iNew and sets the value of the PgHdr.flags field to ** the value passed as the third parameter. */ SQLITE_PRIVATE void sqlite3PagerRekey(DbPage *pPg, Pgno iNew, u16 flags){ assert( pPg->pgno!=iNew ); pPg->flags = flags; sqlite3PcacheMove(pPg, iNew); } /* ** Return a pointer to the data for the specified page. */ SQLITE_PRIVATE void *sqlite3PagerGetData(DbPage *pPg){ assert( pPg->nRef>0 || pPg->pPager->memDb ); return pPg->pData; } /* ** Return a pointer to the Pager.nExtra bytes of "extra" space ** allocated along with the specified page. */ SQLITE_PRIVATE void *sqlite3PagerGetExtra(DbPage *pPg){ return pPg->pExtra; } /* ** Get/set the locking-mode for this pager. Parameter eMode must be one ** of PAGER_LOCKINGMODE_QUERY, PAGER_LOCKINGMODE_NORMAL or ** PAGER_LOCKINGMODE_EXCLUSIVE. If the parameter is not _QUERY, then ** the locking-mode is set to the value specified. ** ** The returned value is either PAGER_LOCKINGMODE_NORMAL or ** PAGER_LOCKINGMODE_EXCLUSIVE, indicating the current (possibly updated) ** locking-mode. */ SQLITE_PRIVATE int sqlite3PagerLockingMode(Pager *pPager, int eMode){ assert( eMode==PAGER_LOCKINGMODE_QUERY || eMode==PAGER_LOCKINGMODE_NORMAL || eMode==PAGER_LOCKINGMODE_EXCLUSIVE ); assert( PAGER_LOCKINGMODE_QUERY<0 ); assert( PAGER_LOCKINGMODE_NORMAL>=0 && PAGER_LOCKINGMODE_EXCLUSIVE>=0 ); assert( pPager->exclusiveMode || 0==sqlite3WalHeapMemory(pPager->pWal) ); if( eMode>=0 && !pPager->tempFile && !sqlite3WalHeapMemory(pPager->pWal) ){ pPager->exclusiveMode = (u8)eMode; } return (int)pPager->exclusiveMode; } /* ** Set the journal-mode for this pager. Parameter eMode must be one of: ** ** PAGER_JOURNALMODE_DELETE ** PAGER_JOURNALMODE_TRUNCATE ** PAGER_JOURNALMODE_PERSIST ** PAGER_JOURNALMODE_OFF ** PAGER_JOURNALMODE_MEMORY ** PAGER_JOURNALMODE_WAL ** ** The journalmode is set to the value specified if the change is allowed. ** The change may be disallowed for the following reasons: ** ** * An in-memory database can only have its journal_mode set to _OFF ** or _MEMORY. ** ** * Temporary databases cannot have _WAL journalmode. ** ** The returned indicate the current (possibly updated) journal-mode. */ SQLITE_PRIVATE int sqlite3PagerSetJournalMode(Pager *pPager, int eMode){ u8 eOld = pPager->journalMode; /* Prior journalmode */ #ifdef SQLITE_DEBUG /* The print_pager_state() routine is intended to be used by the debugger ** only. We invoke it once here to suppress a compiler warning. */ print_pager_state(pPager); #endif /* The eMode parameter is always valid */ assert( eMode==PAGER_JOURNALMODE_DELETE || eMode==PAGER_JOURNALMODE_TRUNCATE || eMode==PAGER_JOURNALMODE_PERSIST || eMode==PAGER_JOURNALMODE_OFF || eMode==PAGER_JOURNALMODE_WAL || eMode==PAGER_JOURNALMODE_MEMORY ); /* This routine is only called from the OP_JournalMode opcode, and ** the logic there will never allow a temporary file to be changed ** to WAL mode. */ assert( pPager->tempFile==0 || eMode!=PAGER_JOURNALMODE_WAL ); /* Do allow the journalmode of an in-memory database to be set to ** anything other than MEMORY or OFF */ if( MEMDB ){ assert( eOld==PAGER_JOURNALMODE_MEMORY || eOld==PAGER_JOURNALMODE_OFF ); if( eMode!=PAGER_JOURNALMODE_MEMORY && eMode!=PAGER_JOURNALMODE_OFF ){ eMode = eOld; } } if( eMode!=eOld ){ /* Change the journal mode. */ assert( pPager->eState!=PAGER_ERROR ); pPager->journalMode = (u8)eMode; /* When transistioning from TRUNCATE or PERSIST to any other journal ** mode except WAL, unless the pager is in locking_mode=exclusive mode, ** delete the journal file. */ assert( (PAGER_JOURNALMODE_TRUNCATE & 5)==1 ); assert( (PAGER_JOURNALMODE_PERSIST & 5)==1 ); assert( (PAGER_JOURNALMODE_DELETE & 5)==0 ); assert( (PAGER_JOURNALMODE_MEMORY & 5)==4 ); assert( (PAGER_JOURNALMODE_OFF & 5)==0 ); assert( (PAGER_JOURNALMODE_WAL & 5)==5 ); assert( isOpen(pPager->fd) || pPager->exclusiveMode ); if( !pPager->exclusiveMode && (eOld & 5)==1 && (eMode & 1)==0 ){ /* In this case we would like to delete the journal file. If it is ** not possible, then that is not a problem. Deleting the journal file ** here is an optimization only. ** ** Before deleting the journal file, obtain a RESERVED lock on the ** database file. This ensures that the journal file is not deleted ** while it is in use by some other client. */ sqlite3OsClose(pPager->jfd); if( pPager->eLock>=RESERVED_LOCK ){ sqlite3OsDelete(pPager->pVfs, pPager->zJournal, 0); }else{ int rc = SQLITE_OK; int state = pPager->eState; assert( state==PAGER_OPEN || state==PAGER_READER ); if( state==PAGER_OPEN ){ rc = sqlite3PagerSharedLock(pPager); } if( pPager->eState==PAGER_READER ){ assert( rc==SQLITE_OK ); rc = pagerLockDb(pPager, RESERVED_LOCK); } if( rc==SQLITE_OK ){ sqlite3OsDelete(pPager->pVfs, pPager->zJournal, 0); } if( rc==SQLITE_OK && state==PAGER_READER ){ pagerUnlockDb(pPager, SHARED_LOCK); }else if( state==PAGER_OPEN ){ pager_unlock(pPager); } assert( state==pPager->eState ); } }else if( eMode==PAGER_JOURNALMODE_OFF ){ sqlite3OsClose(pPager->jfd); } } /* Return the new journal mode */ return (int)pPager->journalMode; } /* ** Return the current journal mode. */ SQLITE_PRIVATE int sqlite3PagerGetJournalMode(Pager *pPager){ return (int)pPager->journalMode; } /* ** Return TRUE if the pager is in a state where it is OK to change the ** journalmode. Journalmode changes can only happen when the database ** is unmodified. */ SQLITE_PRIVATE int sqlite3PagerOkToChangeJournalMode(Pager *pPager){ assert( assert_pager_state(pPager) ); if( pPager->eState>=PAGER_WRITER_CACHEMOD ) return 0; if( NEVER(isOpen(pPager->jfd) && pPager->journalOff>0) ) return 0; return 1; } /* ** Get/set the size-limit used for persistent journal files. ** ** Setting the size limit to -1 means no limit is enforced. ** An attempt to set a limit smaller than -1 is a no-op. */ SQLITE_PRIVATE i64 sqlite3PagerJournalSizeLimit(Pager *pPager, i64 iLimit){ if( iLimit>=-1 ){ pPager->journalSizeLimit = iLimit; sqlite3WalLimit(pPager->pWal, iLimit); } return pPager->journalSizeLimit; } /* ** Return a pointer to the pPager->pBackup variable. The backup module ** in backup.c maintains the content of this variable. This module ** uses it opaquely as an argument to sqlite3BackupRestart() and ** sqlite3BackupUpdate() only. */ SQLITE_PRIVATE sqlite3_backup **sqlite3PagerBackupPtr(Pager *pPager){ return &pPager->pBackup; } #ifndef SQLITE_OMIT_VACUUM /* ** Unless this is an in-memory or temporary database, clear the pager cache. */ SQLITE_PRIVATE void sqlite3PagerClearCache(Pager *pPager){ assert( MEMDB==0 || pPager->tempFile ); if( pPager->tempFile==0 ) pager_reset(pPager); } #endif #ifndef SQLITE_OMIT_WAL /* ** This function is called when the user invokes "PRAGMA wal_checkpoint", ** "PRAGMA wal_blocking_checkpoint" or calls the sqlite3_wal_checkpoint() ** or wal_blocking_checkpoint() API functions. ** ** Parameter eMode is one of SQLITE_CHECKPOINT_PASSIVE, FULL or RESTART. */ SQLITE_PRIVATE int sqlite3PagerCheckpoint(Pager *pPager, int eMode, int *pnLog, int *pnCkpt){ int rc = SQLITE_OK; if( pPager->pWal ){ rc = sqlite3WalCheckpoint(pPager->pWal, eMode, (eMode==SQLITE_CHECKPOINT_PASSIVE ? 0 : pPager->xBusyHandler), pPager->pBusyHandlerArg, pPager->ckptSyncFlags, pPager->pageSize, (u8 *)pPager->pTmpSpace, pnLog, pnCkpt ); } return rc; } SQLITE_PRIVATE int sqlite3PagerWalCallback(Pager *pPager){ return sqlite3WalCallback(pPager->pWal); } /* ** Return true if the underlying VFS for the given pager supports the ** primitives necessary for write-ahead logging. */ SQLITE_PRIVATE int sqlite3PagerWalSupported(Pager *pPager){ const sqlite3_io_methods *pMethods = pPager->fd->pMethods; if( pPager->noLock ) return 0; return pPager->exclusiveMode || (pMethods->iVersion>=2 && pMethods->xShmMap); } /* ** Attempt to take an exclusive lock on the database file. If a PENDING lock ** is obtained instead, immediately release it. */ static int pagerExclusiveLock(Pager *pPager){ int rc; /* Return code */ assert( pPager->eLock==SHARED_LOCK || pPager->eLock==EXCLUSIVE_LOCK ); rc = pagerLockDb(pPager, EXCLUSIVE_LOCK); if( rc!=SQLITE_OK ){ /* If the attempt to grab the exclusive lock failed, release the ** pending lock that may have been obtained instead. */ pagerUnlockDb(pPager, SHARED_LOCK); } return rc; } /* ** Call sqlite3WalOpen() to open the WAL handle. If the pager is in ** exclusive-locking mode when this function is called, take an EXCLUSIVE ** lock on the database file and use heap-memory to store the wal-index ** in. Otherwise, use the normal shared-memory. */ static int pagerOpenWal(Pager *pPager){ int rc = SQLITE_OK; assert( pPager->pWal==0 && pPager->tempFile==0 ); assert( pPager->eLock==SHARED_LOCK || pPager->eLock==EXCLUSIVE_LOCK ); /* If the pager is already in exclusive-mode, the WAL module will use ** heap-memory for the wal-index instead of the VFS shared-memory ** implementation. Take the exclusive lock now, before opening the WAL ** file, to make sure this is safe. */ if( pPager->exclusiveMode ){ rc = pagerExclusiveLock(pPager); } /* Open the connection to the log file. If this operation fails, ** (e.g. due to malloc() failure), return an error code. */ if( rc==SQLITE_OK ){ rc = sqlite3WalOpen(pPager->pVfs, pPager->fd, pPager->zWal, pPager->exclusiveMode, pPager->journalSizeLimit, &pPager->pWal ); } pagerFixMaplimit(pPager); return rc; } /* ** The caller must be holding a SHARED lock on the database file to call ** this function. ** ** If the pager passed as the first argument is open on a real database ** file (not a temp file or an in-memory database), and the WAL file ** is not already open, make an attempt to open it now. If successful, ** return SQLITE_OK. If an error occurs or the VFS used by the pager does ** not support the xShmXXX() methods, return an error code. *pbOpen is ** not modified in either case. ** ** If the pager is open on a temp-file (or in-memory database), or if ** the WAL file is already open, set *pbOpen to 1 and return SQLITE_OK ** without doing anything. */ SQLITE_PRIVATE int sqlite3PagerOpenWal( Pager *pPager, /* Pager object */ int *pbOpen /* OUT: Set to true if call is a no-op */ ){ int rc = SQLITE_OK; /* Return code */ assert( assert_pager_state(pPager) ); assert( pPager->eState==PAGER_OPEN || pbOpen ); assert( pPager->eState==PAGER_READER || !pbOpen ); assert( pbOpen==0 || *pbOpen==0 ); assert( pbOpen!=0 || (!pPager->tempFile && !pPager->pWal) ); if( !pPager->tempFile && !pPager->pWal ){ if( !sqlite3PagerWalSupported(pPager) ) return SQLITE_CANTOPEN; /* Close any rollback journal previously open */ sqlite3OsClose(pPager->jfd); rc = pagerOpenWal(pPager); if( rc==SQLITE_OK ){ pPager->journalMode = PAGER_JOURNALMODE_WAL; pPager->eState = PAGER_OPEN; } }else{ *pbOpen = 1; } return rc; } /* ** This function is called to close the connection to the log file prior ** to switching from WAL to rollback mode. ** ** Before closing the log file, this function attempts to take an ** EXCLUSIVE lock on the database file. If this cannot be obtained, an ** error (SQLITE_BUSY) is returned and the log connection is not closed. ** If successful, the EXCLUSIVE lock is not released before returning. */ SQLITE_PRIVATE int sqlite3PagerCloseWal(Pager *pPager){ int rc = SQLITE_OK; assert( pPager->journalMode==PAGER_JOURNALMODE_WAL ); /* If the log file is not already open, but does exist in the file-system, ** it may need to be checkpointed before the connection can switch to ** rollback mode. Open it now so this can happen. */ if( !pPager->pWal ){ int logexists = 0; rc = pagerLockDb(pPager, SHARED_LOCK); if( rc==SQLITE_OK ){ rc = sqlite3OsAccess( pPager->pVfs, pPager->zWal, SQLITE_ACCESS_EXISTS, &logexists ); } if( rc==SQLITE_OK && logexists ){ rc = pagerOpenWal(pPager); } } /* Checkpoint and close the log. Because an EXCLUSIVE lock is held on ** the database file, the log and log-summary files will be deleted. */ if( rc==SQLITE_OK && pPager->pWal ){ rc = pagerExclusiveLock(pPager); if( rc==SQLITE_OK ){ rc = sqlite3WalClose(pPager->pWal, pPager->ckptSyncFlags, pPager->pageSize, (u8*)pPager->pTmpSpace); pPager->pWal = 0; pagerFixMaplimit(pPager); if( rc && !pPager->exclusiveMode ) pagerUnlockDb(pPager, SHARED_LOCK); } } return rc; } #ifdef SQLITE_ENABLE_SNAPSHOT /* ** If this is a WAL database, obtain a snapshot handle for the snapshot ** currently open. Otherwise, return an error. */ SQLITE_PRIVATE int sqlite3PagerSnapshotGet(Pager *pPager, sqlite3_snapshot **ppSnapshot){ int rc = SQLITE_ERROR; if( pPager->pWal ){ rc = sqlite3WalSnapshotGet(pPager->pWal, ppSnapshot); } return rc; } /* ** If this is a WAL database, store a pointer to pSnapshot. Next time a ** read transaction is opened, attempt to read from the snapshot it ** identifies. If this is not a WAL database, return an error. */ SQLITE_PRIVATE int sqlite3PagerSnapshotOpen(Pager *pPager, sqlite3_snapshot *pSnapshot){ int rc = SQLITE_OK; if( pPager->pWal ){ sqlite3WalSnapshotOpen(pPager->pWal, pSnapshot); }else{ rc = SQLITE_ERROR; } return rc; } #endif /* SQLITE_ENABLE_SNAPSHOT */ #endif /* !SQLITE_OMIT_WAL */ #ifdef SQLITE_ENABLE_ZIPVFS /* ** A read-lock must be held on the pager when this function is called. If ** the pager is in WAL mode and the WAL file currently contains one or more ** frames, return the size in bytes of the page images stored within the ** WAL frames. Otherwise, if this is not a WAL database or the WAL file ** is empty, return 0. */ SQLITE_PRIVATE int sqlite3PagerWalFramesize(Pager *pPager){ assert( pPager->eState>=PAGER_READER ); return sqlite3WalFramesize(pPager->pWal); } #endif #endif /* SQLITE_OMIT_DISKIO */ /************** End of pager.c ***********************************************/ /************** Begin file wal.c *********************************************/ /* ** 2010 February 1 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ************************************************************************* ** ** This file contains the implementation of a write-ahead log (WAL) used in ** "journal_mode=WAL" mode. ** ** WRITE-AHEAD LOG (WAL) FILE FORMAT ** ** A WAL file consists of a header followed by zero or more "frames". ** Each frame records the revised content of a single page from the ** database file. All changes to the database are recorded by writing ** frames into the WAL. Transactions commit when a frame is written that ** contains a commit marker. A single WAL can and usually does record ** multiple transactions. Periodically, the content of the WAL is ** transferred back into the database file in an operation called a ** "checkpoint". ** ** A single WAL file can be used multiple times. In other words, the ** WAL can fill up with frames and then be checkpointed and then new ** frames can overwrite the old ones. A WAL always grows from beginning ** toward the end. Checksums and counters attached to each frame are ** used to determine which frames within the WAL are valid and which ** are leftovers from prior checkpoints. ** ** The WAL header is 32 bytes in size and consists of the following eight ** big-endian 32-bit unsigned integer values: ** ** 0: Magic number. 0x377f0682 or 0x377f0683 ** 4: File format version. Currently 3007000 ** 8: Database page size. Example: 1024 ** 12: Checkpoint sequence number ** 16: Salt-1, random integer incremented with each checkpoint ** 20: Salt-2, a different random integer changing with each ckpt ** 24: Checksum-1 (first part of checksum for first 24 bytes of header). ** 28: Checksum-2 (second part of checksum for first 24 bytes of header). ** ** Immediately following the wal-header are zero or more frames. Each ** frame consists of a 24-byte frame-header followed by a bytes ** of page data. The frame-header is six big-endian 32-bit unsigned ** integer values, as follows: ** ** 0: Page number. ** 4: For commit records, the size of the database image in pages ** after the commit. For all other records, zero. ** 8: Salt-1 (copied from the header) ** 12: Salt-2 (copied from the header) ** 16: Checksum-1. ** 20: Checksum-2. ** ** A frame is considered valid if and only if the following conditions are ** true: ** ** (1) The salt-1 and salt-2 values in the frame-header match ** salt values in the wal-header ** ** (2) The checksum values in the final 8 bytes of the frame-header ** exactly match the checksum computed consecutively on the ** WAL header and the first 8 bytes and the content of all frames ** up to and including the current frame. ** ** The checksum is computed using 32-bit big-endian integers if the ** magic number in the first 4 bytes of the WAL is 0x377f0683 and it ** is computed using little-endian if the magic number is 0x377f0682. ** The checksum values are always stored in the frame header in a ** big-endian format regardless of which byte order is used to compute ** the checksum. The checksum is computed by interpreting the input as ** an even number of unsigned 32-bit integers: x[0] through x[N]. The ** algorithm used for the checksum is as follows: ** ** for i from 0 to n-1 step 2: ** s0 += x[i] + s1; ** s1 += x[i+1] + s0; ** endfor ** ** Note that s0 and s1 are both weighted checksums using fibonacci weights ** in reverse order (the largest fibonacci weight occurs on the first element ** of the sequence being summed.) The s1 value spans all 32-bit ** terms of the sequence whereas s0 omits the final term. ** ** On a checkpoint, the WAL is first VFS.xSync-ed, then valid content of the ** WAL is transferred into the database, then the database is VFS.xSync-ed. ** The VFS.xSync operations serve as write barriers - all writes launched ** before the xSync must complete before any write that launches after the ** xSync begins. ** ** After each checkpoint, the salt-1 value is incremented and the salt-2 ** value is randomized. This prevents old and new frames in the WAL from ** being considered valid at the same time and being checkpointing together ** following a crash. ** ** READER ALGORITHM ** ** To read a page from the database (call it page number P), a reader ** first checks the WAL to see if it contains page P. If so, then the ** last valid instance of page P that is a followed by a commit frame ** or is a commit frame itself becomes the value read. If the WAL ** contains no copies of page P that are valid and which are a commit ** frame or are followed by a commit frame, then page P is read from ** the database file. ** ** To start a read transaction, the reader records the index of the last ** valid frame in the WAL. The reader uses this recorded "mxFrame" value ** for all subsequent read operations. New transactions can be appended ** to the WAL, but as long as the reader uses its original mxFrame value ** and ignores the newly appended content, it will see a consistent snapshot ** of the database from a single point in time. This technique allows ** multiple concurrent readers to view different versions of the database ** content simultaneously. ** ** The reader algorithm in the previous paragraphs works correctly, but ** because frames for page P can appear anywhere within the WAL, the ** reader has to scan the entire WAL looking for page P frames. If the ** WAL is large (multiple megabytes is typical) that scan can be slow, ** and read performance suffers. To overcome this problem, a separate ** data structure called the wal-index is maintained to expedite the ** search for frames of a particular page. ** ** WAL-INDEX FORMAT ** ** Conceptually, the wal-index is shared memory, though VFS implementations ** might choose to implement the wal-index using a mmapped file. Because ** the wal-index is shared memory, SQLite does not support journal_mode=WAL ** on a network filesystem. All users of the database must be able to ** share memory. ** ** The wal-index is transient. After a crash, the wal-index can (and should ** be) reconstructed from the original WAL file. In fact, the VFS is required ** to either truncate or zero the header of the wal-index when the last ** connection to it closes. Because the wal-index is transient, it can ** use an architecture-specific format; it does not have to be cross-platform. ** Hence, unlike the database and WAL file formats which store all values ** as big endian, the wal-index can store multi-byte values in the native ** byte order of the host computer. ** ** The purpose of the wal-index is to answer this question quickly: Given ** a page number P and a maximum frame index M, return the index of the ** last frame in the wal before frame M for page P in the WAL, or return ** NULL if there are no frames for page P in the WAL prior to M. ** ** The wal-index consists of a header region, followed by an one or ** more index blocks. ** ** The wal-index header contains the total number of frames within the WAL ** in the mxFrame field. ** ** Each index block except for the first contains information on ** HASHTABLE_NPAGE frames. The first index block contains information on ** HASHTABLE_NPAGE_ONE frames. The values of HASHTABLE_NPAGE_ONE and ** HASHTABLE_NPAGE are selected so that together the wal-index header and ** first index block are the same size as all other index blocks in the ** wal-index. ** ** Each index block contains two sections, a page-mapping that contains the ** database page number associated with each wal frame, and a hash-table ** that allows readers to query an index block for a specific page number. ** The page-mapping is an array of HASHTABLE_NPAGE (or HASHTABLE_NPAGE_ONE ** for the first index block) 32-bit page numbers. The first entry in the ** first index-block contains the database page number corresponding to the ** first frame in the WAL file. The first entry in the second index block ** in the WAL file corresponds to the (HASHTABLE_NPAGE_ONE+1)th frame in ** the log, and so on. ** ** The last index block in a wal-index usually contains less than the full ** complement of HASHTABLE_NPAGE (or HASHTABLE_NPAGE_ONE) page-numbers, ** depending on the contents of the WAL file. This does not change the ** allocated size of the page-mapping array - the page-mapping array merely ** contains unused entries. ** ** Even without using the hash table, the last frame for page P ** can be found by scanning the page-mapping sections of each index block ** starting with the last index block and moving toward the first, and ** within each index block, starting at the end and moving toward the ** beginning. The first entry that equals P corresponds to the frame ** holding the content for that page. ** ** The hash table consists of HASHTABLE_NSLOT 16-bit unsigned integers. ** HASHTABLE_NSLOT = 2*HASHTABLE_NPAGE, and there is one entry in the ** hash table for each page number in the mapping section, so the hash ** table is never more than half full. The expected number of collisions ** prior to finding a match is 1. Each entry of the hash table is an ** 1-based index of an entry in the mapping section of the same ** index block. Let K be the 1-based index of the largest entry in ** the mapping section. (For index blocks other than the last, K will ** always be exactly HASHTABLE_NPAGE (4096) and for the last index block ** K will be (mxFrame%HASHTABLE_NPAGE).) Unused slots of the hash table ** contain a value of 0. ** ** To look for page P in the hash table, first compute a hash iKey on ** P as follows: ** ** iKey = (P * 383) % HASHTABLE_NSLOT ** ** Then start scanning entries of the hash table, starting with iKey ** (wrapping around to the beginning when the end of the hash table is ** reached) until an unused hash slot is found. Let the first unused slot ** be at index iUnused. (iUnused might be less than iKey if there was ** wrap-around.) Because the hash table is never more than half full, ** the search is guaranteed to eventually hit an unused entry. Let ** iMax be the value between iKey and iUnused, closest to iUnused, ** where aHash[iMax]==P. If there is no iMax entry (if there exists ** no hash slot such that aHash[i]==p) then page P is not in the ** current index block. Otherwise the iMax-th mapping entry of the ** current index block corresponds to the last entry that references ** page P. ** ** A hash search begins with the last index block and moves toward the ** first index block, looking for entries corresponding to page P. On ** average, only two or three slots in each index block need to be ** examined in order to either find the last entry for page P, or to ** establish that no such entry exists in the block. Each index block ** holds over 4000 entries. So two or three index blocks are sufficient ** to cover a typical 10 megabyte WAL file, assuming 1K pages. 8 or 10 ** comparisons (on average) suffice to either locate a frame in the ** WAL or to establish that the frame does not exist in the WAL. This ** is much faster than scanning the entire 10MB WAL. ** ** Note that entries are added in order of increasing K. Hence, one ** reader might be using some value K0 and a second reader that started ** at a later time (after additional transactions were added to the WAL ** and to the wal-index) might be using a different value K1, where K1>K0. ** Both readers can use the same hash table and mapping section to get ** the correct result. There may be entries in the hash table with ** K>K0 but to the first reader, those entries will appear to be unused ** slots in the hash table and so the first reader will get an answer as ** if no values greater than K0 had ever been inserted into the hash table ** in the first place - which is what reader one wants. Meanwhile, the ** second reader using K1 will see additional values that were inserted ** later, which is exactly what reader two wants. ** ** When a rollback occurs, the value of K is decreased. Hash table entries ** that correspond to frames greater than the new K value are removed ** from the hash table at this point. */ #ifndef SQLITE_OMIT_WAL /* #include "wal.h" */ /* ** Trace output macros */ #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG) SQLITE_PRIVATE int sqlite3WalTrace = 0; # define WALTRACE(X) if(sqlite3WalTrace) sqlite3DebugPrintf X #else # define WALTRACE(X) #endif /* ** The maximum (and only) versions of the wal and wal-index formats ** that may be interpreted by this version of SQLite. ** ** If a client begins recovering a WAL file and finds that (a) the checksum ** values in the wal-header are correct and (b) the version field is not ** WAL_MAX_VERSION, recovery fails and SQLite returns SQLITE_CANTOPEN. ** ** Similarly, if a client successfully reads a wal-index header (i.e. the ** checksum test is successful) and finds that the version field is not ** WALINDEX_MAX_VERSION, then no read-transaction is opened and SQLite ** returns SQLITE_CANTOPEN. */ #define WAL_MAX_VERSION 3007000 #define WALINDEX_MAX_VERSION 3007000 /* ** Indices of various locking bytes. WAL_NREADER is the number ** of available reader locks and should be at least 3. The default ** is SQLITE_SHM_NLOCK==8 and WAL_NREADER==5. */ #define WAL_WRITE_LOCK 0 #define WAL_ALL_BUT_WRITE 1 #define WAL_CKPT_LOCK 1 #define WAL_RECOVER_LOCK 2 #define WAL_READ_LOCK(I) (3+(I)) #define WAL_NREADER (SQLITE_SHM_NLOCK-3) /* Object declarations */ typedef struct WalIndexHdr WalIndexHdr; typedef struct WalIterator WalIterator; typedef struct WalCkptInfo WalCkptInfo; /* ** The following object holds a copy of the wal-index header content. ** ** The actual header in the wal-index consists of two copies of this ** object followed by one instance of the WalCkptInfo object. ** For all versions of SQLite through 3.10.0 and probably beyond, ** the locking bytes (WalCkptInfo.aLock) start at offset 120 and ** the total header size is 136 bytes. ** ** The szPage value can be any power of 2 between 512 and 32768, inclusive. ** Or it can be 1 to represent a 65536-byte page. The latter case was ** added in 3.7.1 when support for 64K pages was added. */ struct WalIndexHdr { u32 iVersion; /* Wal-index version */ u32 unused; /* Unused (padding) field */ u32 iChange; /* Counter incremented each transaction */ u8 isInit; /* 1 when initialized */ u8 bigEndCksum; /* True if checksums in WAL are big-endian */ u16 szPage; /* Database page size in bytes. 1==64K */ u32 mxFrame; /* Index of last valid frame in the WAL */ u32 nPage; /* Size of database in pages */ u32 aFrameCksum[2]; /* Checksum of last frame in log */ u32 aSalt[2]; /* Two salt values copied from WAL header */ u32 aCksum[2]; /* Checksum over all prior fields */ }; /* ** A copy of the following object occurs in the wal-index immediately ** following the second copy of the WalIndexHdr. This object stores ** information used by checkpoint. ** ** nBackfill is the number of frames in the WAL that have been written ** back into the database. (We call the act of moving content from WAL to ** database "backfilling".) The nBackfill number is never greater than ** WalIndexHdr.mxFrame. nBackfill can only be increased by threads ** holding the WAL_CKPT_LOCK lock (which includes a recovery thread). ** However, a WAL_WRITE_LOCK thread can move the value of nBackfill from ** mxFrame back to zero when the WAL is reset. ** ** nBackfillAttempted is the largest value of nBackfill that a checkpoint ** has attempted to achieve. Normally nBackfill==nBackfillAtempted, however ** the nBackfillAttempted is set before any backfilling is done and the ** nBackfill is only set after all backfilling completes. So if a checkpoint ** crashes, nBackfillAttempted might be larger than nBackfill. The ** WalIndexHdr.mxFrame must never be less than nBackfillAttempted. ** ** The aLock[] field is a set of bytes used for locking. These bytes should ** never be read or written. ** ** There is one entry in aReadMark[] for each reader lock. If a reader ** holds read-lock K, then the value in aReadMark[K] is no greater than ** the mxFrame for that reader. The value READMARK_NOT_USED (0xffffffff) ** for any aReadMark[] means that entry is unused. aReadMark[0] is ** a special case; its value is never used and it exists as a place-holder ** to avoid having to offset aReadMark[] indexs by one. Readers holding ** WAL_READ_LOCK(0) always ignore the entire WAL and read all content ** directly from the database. ** ** The value of aReadMark[K] may only be changed by a thread that ** is holding an exclusive lock on WAL_READ_LOCK(K). Thus, the value of ** aReadMark[K] cannot changed while there is a reader is using that mark ** since the reader will be holding a shared lock on WAL_READ_LOCK(K). ** ** The checkpointer may only transfer frames from WAL to database where ** the frame numbers are less than or equal to every aReadMark[] that is ** in use (that is, every aReadMark[j] for which there is a corresponding ** WAL_READ_LOCK(j)). New readers (usually) pick the aReadMark[] with the ** largest value and will increase an unused aReadMark[] to mxFrame if there ** is not already an aReadMark[] equal to mxFrame. The exception to the ** previous sentence is when nBackfill equals mxFrame (meaning that everything ** in the WAL has been backfilled into the database) then new readers ** will choose aReadMark[0] which has value 0 and hence such reader will ** get all their all content directly from the database file and ignore ** the WAL. ** ** Writers normally append new frames to the end of the WAL. However, ** if nBackfill equals mxFrame (meaning that all WAL content has been ** written back into the database) and if no readers are using the WAL ** (in other words, if there are no WAL_READ_LOCK(i) where i>0) then ** the writer will first "reset" the WAL back to the beginning and start ** writing new content beginning at frame 1. ** ** We assume that 32-bit loads are atomic and so no locks are needed in ** order to read from any aReadMark[] entries. */ struct WalCkptInfo { u32 nBackfill; /* Number of WAL frames backfilled into DB */ u32 aReadMark[WAL_NREADER]; /* Reader marks */ u8 aLock[SQLITE_SHM_NLOCK]; /* Reserved space for locks */ u32 nBackfillAttempted; /* WAL frames perhaps written, or maybe not */ u32 notUsed0; /* Available for future enhancements */ }; #define READMARK_NOT_USED 0xffffffff /* A block of WALINDEX_LOCK_RESERVED bytes beginning at ** WALINDEX_LOCK_OFFSET is reserved for locks. Since some systems ** only support mandatory file-locks, we do not read or write data ** from the region of the file on which locks are applied. */ #define WALINDEX_LOCK_OFFSET (sizeof(WalIndexHdr)*2+offsetof(WalCkptInfo,aLock)) #define WALINDEX_HDR_SIZE (sizeof(WalIndexHdr)*2+sizeof(WalCkptInfo)) /* Size of header before each frame in wal */ #define WAL_FRAME_HDRSIZE 24 /* Size of write ahead log header, including checksum. */ /* #define WAL_HDRSIZE 24 */ #define WAL_HDRSIZE 32 /* WAL magic value. Either this value, or the same value with the least ** significant bit also set (WAL_MAGIC | 0x00000001) is stored in 32-bit ** big-endian format in the first 4 bytes of a WAL file. ** ** If the LSB is set, then the checksums for each frame within the WAL ** file are calculated by treating all data as an array of 32-bit ** big-endian words. Otherwise, they are calculated by interpreting ** all data as 32-bit little-endian words. */ #define WAL_MAGIC 0x377f0682 /* ** Return the offset of frame iFrame in the write-ahead log file, ** assuming a database page size of szPage bytes. The offset returned ** is to the start of the write-ahead log frame-header. */ #define walFrameOffset(iFrame, szPage) ( \ WAL_HDRSIZE + ((iFrame)-1)*(i64)((szPage)+WAL_FRAME_HDRSIZE) \ ) /* ** An open write-ahead log file is represented by an instance of the ** following object. */ struct Wal { sqlite3_vfs *pVfs; /* The VFS used to create pDbFd */ sqlite3_file *pDbFd; /* File handle for the database file */ sqlite3_file *pWalFd; /* File handle for WAL file */ u32 iCallback; /* Value to pass to log callback (or 0) */ i64 mxWalSize; /* Truncate WAL to this size upon reset */ int nWiData; /* Size of array apWiData */ int szFirstBlock; /* Size of first block written to WAL file */ volatile u32 **apWiData; /* Pointer to wal-index content in memory */ u32 szPage; /* Database page size */ i16 readLock; /* Which read lock is being held. -1 for none */ u8 syncFlags; /* Flags to use to sync header writes */ u8 exclusiveMode; /* Non-zero if connection is in exclusive mode */ u8 writeLock; /* True if in a write transaction */ u8 ckptLock; /* True if holding a checkpoint lock */ u8 readOnly; /* WAL_RDWR, WAL_RDONLY, or WAL_SHM_RDONLY */ u8 truncateOnCommit; /* True to truncate WAL file on commit */ u8 syncHeader; /* Fsync the WAL header if true */ u8 padToSectorBoundary; /* Pad transactions out to the next sector */ WalIndexHdr hdr; /* Wal-index header for current transaction */ u32 minFrame; /* Ignore wal frames before this one */ u32 iReCksum; /* On commit, recalculate checksums from here */ const char *zWalName; /* Name of WAL file */ u32 nCkpt; /* Checkpoint sequence counter in the wal-header */ #ifdef SQLITE_DEBUG u8 lockError; /* True if a locking error has occurred */ #endif #ifdef SQLITE_ENABLE_SNAPSHOT WalIndexHdr *pSnapshot; /* Start transaction here if not NULL */ #endif }; /* ** Candidate values for Wal.exclusiveMode. */ #define WAL_NORMAL_MODE 0 #define WAL_EXCLUSIVE_MODE 1 #define WAL_HEAPMEMORY_MODE 2 /* ** Possible values for WAL.readOnly */ #define WAL_RDWR 0 /* Normal read/write connection */ #define WAL_RDONLY 1 /* The WAL file is readonly */ #define WAL_SHM_RDONLY 2 /* The SHM file is readonly */ /* ** Each page of the wal-index mapping contains a hash-table made up of ** an array of HASHTABLE_NSLOT elements of the following type. */ typedef u16 ht_slot; /* ** This structure is used to implement an iterator that loops through ** all frames in the WAL in database page order. Where two or more frames ** correspond to the same database page, the iterator visits only the ** frame most recently written to the WAL (in other words, the frame with ** the largest index). ** ** The internals of this structure are only accessed by: ** ** walIteratorInit() - Create a new iterator, ** walIteratorNext() - Step an iterator, ** walIteratorFree() - Free an iterator. ** ** This functionality is used by the checkpoint code (see walCheckpoint()). */ struct WalIterator { int iPrior; /* Last result returned from the iterator */ int nSegment; /* Number of entries in aSegment[] */ struct WalSegment { int iNext; /* Next slot in aIndex[] not yet returned */ ht_slot *aIndex; /* i0, i1, i2... such that aPgno[iN] ascend */ u32 *aPgno; /* Array of page numbers. */ int nEntry; /* Nr. of entries in aPgno[] and aIndex[] */ int iZero; /* Frame number associated with aPgno[0] */ } aSegment[1]; /* One for every 32KB page in the wal-index */ }; /* ** Define the parameters of the hash tables in the wal-index file. There ** is a hash-table following every HASHTABLE_NPAGE page numbers in the ** wal-index. ** ** Changing any of these constants will alter the wal-index format and ** create incompatibilities. */ #define HASHTABLE_NPAGE 4096 /* Must be power of 2 */ #define HASHTABLE_HASH_1 383 /* Should be prime */ #define HASHTABLE_NSLOT (HASHTABLE_NPAGE*2) /* Must be a power of 2 */ /* ** The block of page numbers associated with the first hash-table in a ** wal-index is smaller than usual. This is so that there is a complete ** hash-table on each aligned 32KB page of the wal-index. */ #define HASHTABLE_NPAGE_ONE (HASHTABLE_NPAGE - (WALINDEX_HDR_SIZE/sizeof(u32))) /* The wal-index is divided into pages of WALINDEX_PGSZ bytes each. */ #define WALINDEX_PGSZ ( \ sizeof(ht_slot)*HASHTABLE_NSLOT + HASHTABLE_NPAGE*sizeof(u32) \ ) /* ** Obtain a pointer to the iPage'th page of the wal-index. The wal-index ** is broken into pages of WALINDEX_PGSZ bytes. Wal-index pages are ** numbered from zero. ** ** If this call is successful, *ppPage is set to point to the wal-index ** page and SQLITE_OK is returned. If an error (an OOM or VFS error) occurs, ** then an SQLite error code is returned and *ppPage is set to 0. */ static int walIndexPage(Wal *pWal, int iPage, volatile u32 **ppPage){ int rc = SQLITE_OK; /* Enlarge the pWal->apWiData[] array if required */ if( pWal->nWiData<=iPage ){ int nByte = sizeof(u32*)*(iPage+1); volatile u32 **apNew; apNew = (volatile u32 **)sqlite3_realloc64((void *)pWal->apWiData, nByte); if( !apNew ){ *ppPage = 0; return SQLITE_NOMEM_BKPT; } memset((void*)&apNew[pWal->nWiData], 0, sizeof(u32*)*(iPage+1-pWal->nWiData)); pWal->apWiData = apNew; pWal->nWiData = iPage+1; } /* Request a pointer to the required page from the VFS */ if( pWal->apWiData[iPage]==0 ){ if( pWal->exclusiveMode==WAL_HEAPMEMORY_MODE ){ pWal->apWiData[iPage] = (u32 volatile *)sqlite3MallocZero(WALINDEX_PGSZ); if( !pWal->apWiData[iPage] ) rc = SQLITE_NOMEM_BKPT; }else{ rc = sqlite3OsShmMap(pWal->pDbFd, iPage, WALINDEX_PGSZ, pWal->writeLock, (void volatile **)&pWal->apWiData[iPage] ); if( rc==SQLITE_READONLY ){ pWal->readOnly |= WAL_SHM_RDONLY; rc = SQLITE_OK; } } } *ppPage = pWal->apWiData[iPage]; assert( iPage==0 || *ppPage || rc!=SQLITE_OK ); return rc; } /* ** Return a pointer to the WalCkptInfo structure in the wal-index. */ static volatile WalCkptInfo *walCkptInfo(Wal *pWal){ assert( pWal->nWiData>0 && pWal->apWiData[0] ); return (volatile WalCkptInfo*)&(pWal->apWiData[0][sizeof(WalIndexHdr)/2]); } /* ** Return a pointer to the WalIndexHdr structure in the wal-index. */ static volatile WalIndexHdr *walIndexHdr(Wal *pWal){ assert( pWal->nWiData>0 && pWal->apWiData[0] ); return (volatile WalIndexHdr*)pWal->apWiData[0]; } /* ** The argument to this macro must be of type u32. On a little-endian ** architecture, it returns the u32 value that results from interpreting ** the 4 bytes as a big-endian value. On a big-endian architecture, it ** returns the value that would be produced by interpreting the 4 bytes ** of the input value as a little-endian integer. */ #define BYTESWAP32(x) ( \ (((x)&0x000000FF)<<24) + (((x)&0x0000FF00)<<8) \ + (((x)&0x00FF0000)>>8) + (((x)&0xFF000000)>>24) \ ) /* ** Generate or extend an 8 byte checksum based on the data in ** array aByte[] and the initial values of aIn[0] and aIn[1] (or ** initial values of 0 and 0 if aIn==NULL). ** ** The checksum is written back into aOut[] before returning. ** ** nByte must be a positive multiple of 8. */ static void walChecksumBytes( int nativeCksum, /* True for native byte-order, false for non-native */ u8 *a, /* Content to be checksummed */ int nByte, /* Bytes of content in a[]. Must be a multiple of 8. */ const u32 *aIn, /* Initial checksum value input */ u32 *aOut /* OUT: Final checksum value output */ ){ u32 s1, s2; u32 *aData = (u32 *)a; u32 *aEnd = (u32 *)&a[nByte]; if( aIn ){ s1 = aIn[0]; s2 = aIn[1]; }else{ s1 = s2 = 0; } assert( nByte>=8 ); assert( (nByte&0x00000007)==0 ); if( nativeCksum ){ do { s1 += *aData++ + s2; s2 += *aData++ + s1; }while( aDataexclusiveMode!=WAL_HEAPMEMORY_MODE ){ sqlite3OsShmBarrier(pWal->pDbFd); } } /* ** Write the header information in pWal->hdr into the wal-index. ** ** The checksum on pWal->hdr is updated before it is written. */ static void walIndexWriteHdr(Wal *pWal){ volatile WalIndexHdr *aHdr = walIndexHdr(pWal); const int nCksum = offsetof(WalIndexHdr, aCksum); assert( pWal->writeLock ); pWal->hdr.isInit = 1; pWal->hdr.iVersion = WALINDEX_MAX_VERSION; walChecksumBytes(1, (u8*)&pWal->hdr, nCksum, 0, pWal->hdr.aCksum); memcpy((void*)&aHdr[1], (const void*)&pWal->hdr, sizeof(WalIndexHdr)); walShmBarrier(pWal); memcpy((void*)&aHdr[0], (const void*)&pWal->hdr, sizeof(WalIndexHdr)); } /* ** This function encodes a single frame header and writes it to a buffer ** supplied by the caller. A frame-header is made up of a series of ** 4-byte big-endian integers, as follows: ** ** 0: Page number. ** 4: For commit records, the size of the database image in pages ** after the commit. For all other records, zero. ** 8: Salt-1 (copied from the wal-header) ** 12: Salt-2 (copied from the wal-header) ** 16: Checksum-1. ** 20: Checksum-2. */ static void walEncodeFrame( Wal *pWal, /* The write-ahead log */ u32 iPage, /* Database page number for frame */ u32 nTruncate, /* New db size (or 0 for non-commit frames) */ u8 *aData, /* Pointer to page data */ u8 *aFrame /* OUT: Write encoded frame here */ ){ int nativeCksum; /* True for native byte-order checksums */ u32 *aCksum = pWal->hdr.aFrameCksum; assert( WAL_FRAME_HDRSIZE==24 ); sqlite3Put4byte(&aFrame[0], iPage); sqlite3Put4byte(&aFrame[4], nTruncate); if( pWal->iReCksum==0 ){ memcpy(&aFrame[8], pWal->hdr.aSalt, 8); nativeCksum = (pWal->hdr.bigEndCksum==SQLITE_BIGENDIAN); walChecksumBytes(nativeCksum, aFrame, 8, aCksum, aCksum); walChecksumBytes(nativeCksum, aData, pWal->szPage, aCksum, aCksum); sqlite3Put4byte(&aFrame[16], aCksum[0]); sqlite3Put4byte(&aFrame[20], aCksum[1]); }else{ memset(&aFrame[8], 0, 16); } } /* ** Check to see if the frame with header in aFrame[] and content ** in aData[] is valid. If it is a valid frame, fill *piPage and ** *pnTruncate and return true. Return if the frame is not valid. */ static int walDecodeFrame( Wal *pWal, /* The write-ahead log */ u32 *piPage, /* OUT: Database page number for frame */ u32 *pnTruncate, /* OUT: New db size (or 0 if not commit) */ u8 *aData, /* Pointer to page data (for checksum) */ u8 *aFrame /* Frame data */ ){ int nativeCksum; /* True for native byte-order checksums */ u32 *aCksum = pWal->hdr.aFrameCksum; u32 pgno; /* Page number of the frame */ assert( WAL_FRAME_HDRSIZE==24 ); /* A frame is only valid if the salt values in the frame-header ** match the salt values in the wal-header. */ if( memcmp(&pWal->hdr.aSalt, &aFrame[8], 8)!=0 ){ return 0; } /* A frame is only valid if the page number is creater than zero. */ pgno = sqlite3Get4byte(&aFrame[0]); if( pgno==0 ){ return 0; } /* A frame is only valid if a checksum of the WAL header, ** all prior frams, the first 16 bytes of this frame-header, ** and the frame-data matches the checksum in the last 8 ** bytes of this frame-header. */ nativeCksum = (pWal->hdr.bigEndCksum==SQLITE_BIGENDIAN); walChecksumBytes(nativeCksum, aFrame, 8, aCksum, aCksum); walChecksumBytes(nativeCksum, aData, pWal->szPage, aCksum, aCksum); if( aCksum[0]!=sqlite3Get4byte(&aFrame[16]) || aCksum[1]!=sqlite3Get4byte(&aFrame[20]) ){ /* Checksum failed. */ return 0; } /* If we reach this point, the frame is valid. Return the page number ** and the new database size. */ *piPage = pgno; *pnTruncate = sqlite3Get4byte(&aFrame[4]); return 1; } #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG) /* ** Names of locks. This routine is used to provide debugging output and is not ** a part of an ordinary build. */ static const char *walLockName(int lockIdx){ if( lockIdx==WAL_WRITE_LOCK ){ return "WRITE-LOCK"; }else if( lockIdx==WAL_CKPT_LOCK ){ return "CKPT-LOCK"; }else if( lockIdx==WAL_RECOVER_LOCK ){ return "RECOVER-LOCK"; }else{ static char zName[15]; sqlite3_snprintf(sizeof(zName), zName, "READ-LOCK[%d]", lockIdx-WAL_READ_LOCK(0)); return zName; } } #endif /*defined(SQLITE_TEST) || defined(SQLITE_DEBUG) */ /* ** Set or release locks on the WAL. Locks are either shared or exclusive. ** A lock cannot be moved directly between shared and exclusive - it must go ** through the unlocked state first. ** ** In locking_mode=EXCLUSIVE, all of these routines become no-ops. */ static int walLockShared(Wal *pWal, int lockIdx){ int rc; if( pWal->exclusiveMode ) return SQLITE_OK; rc = sqlite3OsShmLock(pWal->pDbFd, lockIdx, 1, SQLITE_SHM_LOCK | SQLITE_SHM_SHARED); WALTRACE(("WAL%p: acquire SHARED-%s %s\n", pWal, walLockName(lockIdx), rc ? "failed" : "ok")); VVA_ONLY( pWal->lockError = (u8)(rc!=SQLITE_OK && rc!=SQLITE_BUSY); ) return rc; } static void walUnlockShared(Wal *pWal, int lockIdx){ if( pWal->exclusiveMode ) return; (void)sqlite3OsShmLock(pWal->pDbFd, lockIdx, 1, SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED); WALTRACE(("WAL%p: release SHARED-%s\n", pWal, walLockName(lockIdx))); } static int walLockExclusive(Wal *pWal, int lockIdx, int n){ int rc; if( pWal->exclusiveMode ) return SQLITE_OK; rc = sqlite3OsShmLock(pWal->pDbFd, lockIdx, n, SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE); WALTRACE(("WAL%p: acquire EXCLUSIVE-%s cnt=%d %s\n", pWal, walLockName(lockIdx), n, rc ? "failed" : "ok")); VVA_ONLY( pWal->lockError = (u8)(rc!=SQLITE_OK && rc!=SQLITE_BUSY); ) return rc; } static void walUnlockExclusive(Wal *pWal, int lockIdx, int n){ if( pWal->exclusiveMode ) return; (void)sqlite3OsShmLock(pWal->pDbFd, lockIdx, n, SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE); WALTRACE(("WAL%p: release EXCLUSIVE-%s cnt=%d\n", pWal, walLockName(lockIdx), n)); } /* ** Compute a hash on a page number. The resulting hash value must land ** between 0 and (HASHTABLE_NSLOT-1). The walHashNext() function advances ** the hash to the next value in the event of a collision. */ static int walHash(u32 iPage){ assert( iPage>0 ); assert( (HASHTABLE_NSLOT & (HASHTABLE_NSLOT-1))==0 ); return (iPage*HASHTABLE_HASH_1) & (HASHTABLE_NSLOT-1); } static int walNextHash(int iPriorHash){ return (iPriorHash+1)&(HASHTABLE_NSLOT-1); } /* ** Return pointers to the hash table and page number array stored on ** page iHash of the wal-index. The wal-index is broken into 32KB pages ** numbered starting from 0. ** ** Set output variable *paHash to point to the start of the hash table ** in the wal-index file. Set *piZero to one less than the frame ** number of the first frame indexed by this hash table. If a ** slot in the hash table is set to N, it refers to frame number ** (*piZero+N) in the log. ** ** Finally, set *paPgno so that *paPgno[1] is the page number of the ** first frame indexed by the hash table, frame (*piZero+1). */ static int walHashGet( Wal *pWal, /* WAL handle */ int iHash, /* Find the iHash'th table */ volatile ht_slot **paHash, /* OUT: Pointer to hash index */ volatile u32 **paPgno, /* OUT: Pointer to page number array */ u32 *piZero /* OUT: Frame associated with *paPgno[0] */ ){ int rc; /* Return code */ volatile u32 *aPgno; rc = walIndexPage(pWal, iHash, &aPgno); assert( rc==SQLITE_OK || iHash>0 ); if( rc==SQLITE_OK ){ u32 iZero; volatile ht_slot *aHash; aHash = (volatile ht_slot *)&aPgno[HASHTABLE_NPAGE]; if( iHash==0 ){ aPgno = &aPgno[WALINDEX_HDR_SIZE/sizeof(u32)]; iZero = 0; }else{ iZero = HASHTABLE_NPAGE_ONE + (iHash-1)*HASHTABLE_NPAGE; } *paPgno = &aPgno[-1]; *paHash = aHash; *piZero = iZero; } return rc; } /* ** Return the number of the wal-index page that contains the hash-table ** and page-number array that contain entries corresponding to WAL frame ** iFrame. The wal-index is broken up into 32KB pages. Wal-index pages ** are numbered starting from 0. */ static int walFramePage(u32 iFrame){ int iHash = (iFrame+HASHTABLE_NPAGE-HASHTABLE_NPAGE_ONE-1) / HASHTABLE_NPAGE; assert( (iHash==0 || iFrame>HASHTABLE_NPAGE_ONE) && (iHash>=1 || iFrame<=HASHTABLE_NPAGE_ONE) && (iHash<=1 || iFrame>(HASHTABLE_NPAGE_ONE+HASHTABLE_NPAGE)) && (iHash>=2 || iFrame<=HASHTABLE_NPAGE_ONE+HASHTABLE_NPAGE) && (iHash<=2 || iFrame>(HASHTABLE_NPAGE_ONE+2*HASHTABLE_NPAGE)) ); return iHash; } /* ** Return the page number associated with frame iFrame in this WAL. */ static u32 walFramePgno(Wal *pWal, u32 iFrame){ int iHash = walFramePage(iFrame); if( iHash==0 ){ return pWal->apWiData[0][WALINDEX_HDR_SIZE/sizeof(u32) + iFrame - 1]; } return pWal->apWiData[iHash][(iFrame-1-HASHTABLE_NPAGE_ONE)%HASHTABLE_NPAGE]; } /* ** Remove entries from the hash table that point to WAL slots greater ** than pWal->hdr.mxFrame. ** ** This function is called whenever pWal->hdr.mxFrame is decreased due ** to a rollback or savepoint. ** ** At most only the hash table containing pWal->hdr.mxFrame needs to be ** updated. Any later hash tables will be automatically cleared when ** pWal->hdr.mxFrame advances to the point where those hash tables are ** actually needed. */ static void walCleanupHash(Wal *pWal){ volatile ht_slot *aHash = 0; /* Pointer to hash table to clear */ volatile u32 *aPgno = 0; /* Page number array for hash table */ u32 iZero = 0; /* frame == (aHash[x]+iZero) */ int iLimit = 0; /* Zero values greater than this */ int nByte; /* Number of bytes to zero in aPgno[] */ int i; /* Used to iterate through aHash[] */ assert( pWal->writeLock ); testcase( pWal->hdr.mxFrame==HASHTABLE_NPAGE_ONE-1 ); testcase( pWal->hdr.mxFrame==HASHTABLE_NPAGE_ONE ); testcase( pWal->hdr.mxFrame==HASHTABLE_NPAGE_ONE+1 ); if( pWal->hdr.mxFrame==0 ) return; /* Obtain pointers to the hash-table and page-number array containing ** the entry that corresponds to frame pWal->hdr.mxFrame. It is guaranteed ** that the page said hash-table and array reside on is already mapped. */ assert( pWal->nWiData>walFramePage(pWal->hdr.mxFrame) ); assert( pWal->apWiData[walFramePage(pWal->hdr.mxFrame)] ); walHashGet(pWal, walFramePage(pWal->hdr.mxFrame), &aHash, &aPgno, &iZero); /* Zero all hash-table entries that correspond to frame numbers greater ** than pWal->hdr.mxFrame. */ iLimit = pWal->hdr.mxFrame - iZero; assert( iLimit>0 ); for(i=0; iiLimit ){ aHash[i] = 0; } } /* Zero the entries in the aPgno array that correspond to frames with ** frame numbers greater than pWal->hdr.mxFrame. */ nByte = (int)((char *)aHash - (char *)&aPgno[iLimit+1]); memset((void *)&aPgno[iLimit+1], 0, nByte); #ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT /* Verify that the every entry in the mapping region is still reachable ** via the hash table even after the cleanup. */ if( iLimit ){ int j; /* Loop counter */ int iKey; /* Hash key */ for(j=1; j<=iLimit; j++){ for(iKey=walHash(aPgno[j]); aHash[iKey]; iKey=walNextHash(iKey)){ if( aHash[iKey]==j ) break; } assert( aHash[iKey]==j ); } } #endif /* SQLITE_ENABLE_EXPENSIVE_ASSERT */ } /* ** Set an entry in the wal-index that will map database page number ** pPage into WAL frame iFrame. */ static int walIndexAppend(Wal *pWal, u32 iFrame, u32 iPage){ int rc; /* Return code */ u32 iZero = 0; /* One less than frame number of aPgno[1] */ volatile u32 *aPgno = 0; /* Page number array */ volatile ht_slot *aHash = 0; /* Hash table */ rc = walHashGet(pWal, walFramePage(iFrame), &aHash, &aPgno, &iZero); /* Assuming the wal-index file was successfully mapped, populate the ** page number array and hash table entry. */ if( rc==SQLITE_OK ){ int iKey; /* Hash table key */ int idx; /* Value to write to hash-table slot */ int nCollide; /* Number of hash collisions */ idx = iFrame - iZero; assert( idx <= HASHTABLE_NSLOT/2 + 1 ); /* If this is the first entry to be added to this hash-table, zero the ** entire hash table and aPgno[] array before proceeding. */ if( idx==1 ){ int nByte = (int)((u8 *)&aHash[HASHTABLE_NSLOT] - (u8 *)&aPgno[1]); memset((void*)&aPgno[1], 0, nByte); } /* If the entry in aPgno[] is already set, then the previous writer ** must have exited unexpectedly in the middle of a transaction (after ** writing one or more dirty pages to the WAL to free up memory). ** Remove the remnants of that writers uncommitted transaction from ** the hash-table before writing any new entries. */ if( aPgno[idx] ){ walCleanupHash(pWal); assert( !aPgno[idx] ); } /* Write the aPgno[] array entry and the hash-table slot. */ nCollide = idx; for(iKey=walHash(iPage); aHash[iKey]; iKey=walNextHash(iKey)){ if( (nCollide--)==0 ) return SQLITE_CORRUPT_BKPT; } aPgno[idx] = iPage; aHash[iKey] = (ht_slot)idx; #ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT /* Verify that the number of entries in the hash table exactly equals ** the number of entries in the mapping region. */ { int i; /* Loop counter */ int nEntry = 0; /* Number of entries in the hash table */ for(i=0; ickptLock==1 || pWal->ckptLock==0 ); assert( WAL_ALL_BUT_WRITE==WAL_WRITE_LOCK+1 ); assert( WAL_CKPT_LOCK==WAL_ALL_BUT_WRITE ); assert( pWal->writeLock ); iLock = WAL_ALL_BUT_WRITE + pWal->ckptLock; nLock = SQLITE_SHM_NLOCK - iLock; rc = walLockExclusive(pWal, iLock, nLock); if( rc ){ return rc; } WALTRACE(("WAL%p: recovery begin...\n", pWal)); memset(&pWal->hdr, 0, sizeof(WalIndexHdr)); rc = sqlite3OsFileSize(pWal->pWalFd, &nSize); if( rc!=SQLITE_OK ){ goto recovery_error; } if( nSize>WAL_HDRSIZE ){ u8 aBuf[WAL_HDRSIZE]; /* Buffer to load WAL header into */ u8 *aFrame = 0; /* Malloc'd buffer to load entire frame */ int szFrame; /* Number of bytes in buffer aFrame[] */ u8 *aData; /* Pointer to data part of aFrame buffer */ int iFrame; /* Index of last frame read */ i64 iOffset; /* Next offset to read from log file */ int szPage; /* Page size according to the log */ u32 magic; /* Magic value read from WAL header */ u32 version; /* Magic value read from WAL header */ int isValid; /* True if this frame is valid */ /* Read in the WAL header. */ rc = sqlite3OsRead(pWal->pWalFd, aBuf, WAL_HDRSIZE, 0); if( rc!=SQLITE_OK ){ goto recovery_error; } /* If the database page size is not a power of two, or is greater than ** SQLITE_MAX_PAGE_SIZE, conclude that the WAL file contains no valid ** data. Similarly, if the 'magic' value is invalid, ignore the whole ** WAL file. */ magic = sqlite3Get4byte(&aBuf[0]); szPage = sqlite3Get4byte(&aBuf[8]); if( (magic&0xFFFFFFFE)!=WAL_MAGIC || szPage&(szPage-1) || szPage>SQLITE_MAX_PAGE_SIZE || szPage<512 ){ goto finished; } pWal->hdr.bigEndCksum = (u8)(magic&0x00000001); pWal->szPage = szPage; pWal->nCkpt = sqlite3Get4byte(&aBuf[12]); memcpy(&pWal->hdr.aSalt, &aBuf[16], 8); /* Verify that the WAL header checksum is correct */ walChecksumBytes(pWal->hdr.bigEndCksum==SQLITE_BIGENDIAN, aBuf, WAL_HDRSIZE-2*4, 0, pWal->hdr.aFrameCksum ); if( pWal->hdr.aFrameCksum[0]!=sqlite3Get4byte(&aBuf[24]) || pWal->hdr.aFrameCksum[1]!=sqlite3Get4byte(&aBuf[28]) ){ goto finished; } /* Verify that the version number on the WAL format is one that ** are able to understand */ version = sqlite3Get4byte(&aBuf[4]); if( version!=WAL_MAX_VERSION ){ rc = SQLITE_CANTOPEN_BKPT; goto finished; } /* Malloc a buffer to read frames into. */ szFrame = szPage + WAL_FRAME_HDRSIZE; aFrame = (u8 *)sqlite3_malloc64(szFrame); if( !aFrame ){ rc = SQLITE_NOMEM_BKPT; goto recovery_error; } aData = &aFrame[WAL_FRAME_HDRSIZE]; /* Read all frames from the log file. */ iFrame = 0; for(iOffset=WAL_HDRSIZE; (iOffset+szFrame)<=nSize; iOffset+=szFrame){ u32 pgno; /* Database page number for frame */ u32 nTruncate; /* dbsize field from frame header */ /* Read and decode the next log frame. */ iFrame++; rc = sqlite3OsRead(pWal->pWalFd, aFrame, szFrame, iOffset); if( rc!=SQLITE_OK ) break; isValid = walDecodeFrame(pWal, &pgno, &nTruncate, aData, aFrame); if( !isValid ) break; rc = walIndexAppend(pWal, iFrame, pgno); if( rc!=SQLITE_OK ) break; /* If nTruncate is non-zero, this is a commit record. */ if( nTruncate ){ pWal->hdr.mxFrame = iFrame; pWal->hdr.nPage = nTruncate; pWal->hdr.szPage = (u16)((szPage&0xff00) | (szPage>>16)); testcase( szPage<=32768 ); testcase( szPage>=65536 ); aFrameCksum[0] = pWal->hdr.aFrameCksum[0]; aFrameCksum[1] = pWal->hdr.aFrameCksum[1]; } } sqlite3_free(aFrame); } finished: if( rc==SQLITE_OK ){ volatile WalCkptInfo *pInfo; int i; pWal->hdr.aFrameCksum[0] = aFrameCksum[0]; pWal->hdr.aFrameCksum[1] = aFrameCksum[1]; walIndexWriteHdr(pWal); /* Reset the checkpoint-header. This is safe because this thread is ** currently holding locks that exclude all other readers, writers and ** checkpointers. */ pInfo = walCkptInfo(pWal); pInfo->nBackfill = 0; pInfo->nBackfillAttempted = pWal->hdr.mxFrame; pInfo->aReadMark[0] = 0; for(i=1; iaReadMark[i] = READMARK_NOT_USED; if( pWal->hdr.mxFrame ) pInfo->aReadMark[1] = pWal->hdr.mxFrame; /* If more than one frame was recovered from the log file, report an ** event via sqlite3_log(). This is to help with identifying performance ** problems caused by applications routinely shutting down without ** checkpointing the log file. */ if( pWal->hdr.nPage ){ sqlite3_log(SQLITE_NOTICE_RECOVER_WAL, "recovered %d frames from WAL file %s", pWal->hdr.mxFrame, pWal->zWalName ); } } recovery_error: WALTRACE(("WAL%p: recovery %s\n", pWal, rc ? "failed" : "ok")); walUnlockExclusive(pWal, iLock, nLock); return rc; } /* ** Close an open wal-index. */ static void walIndexClose(Wal *pWal, int isDelete){ if( pWal->exclusiveMode==WAL_HEAPMEMORY_MODE ){ int i; for(i=0; inWiData; i++){ sqlite3_free((void *)pWal->apWiData[i]); pWal->apWiData[i] = 0; } }else{ sqlite3OsShmUnmap(pWal->pDbFd, isDelete); } } /* ** Open a connection to the WAL file zWalName. The database file must ** already be opened on connection pDbFd. The buffer that zWalName points ** to must remain valid for the lifetime of the returned Wal* handle. ** ** A SHARED lock should be held on the database file when this function ** is called. The purpose of this SHARED lock is to prevent any other ** client from unlinking the WAL or wal-index file. If another process ** were to do this just after this client opened one of these files, the ** system would be badly broken. ** ** If the log file is successfully opened, SQLITE_OK is returned and ** *ppWal is set to point to a new WAL handle. If an error occurs, ** an SQLite error code is returned and *ppWal is left unmodified. */ SQLITE_PRIVATE int sqlite3WalOpen( sqlite3_vfs *pVfs, /* vfs module to open wal and wal-index */ sqlite3_file *pDbFd, /* The open database file */ const char *zWalName, /* Name of the WAL file */ int bNoShm, /* True to run in heap-memory mode */ i64 mxWalSize, /* Truncate WAL to this size on reset */ Wal **ppWal /* OUT: Allocated Wal handle */ ){ int rc; /* Return Code */ Wal *pRet; /* Object to allocate and return */ int flags; /* Flags passed to OsOpen() */ assert( zWalName && zWalName[0] ); assert( pDbFd ); /* In the amalgamation, the os_unix.c and os_win.c source files come before ** this source file. Verify that the #defines of the locking byte offsets ** in os_unix.c and os_win.c agree with the WALINDEX_LOCK_OFFSET value. ** For that matter, if the lock offset ever changes from its initial design ** value of 120, we need to know that so there is an assert() to check it. */ assert( 120==WALINDEX_LOCK_OFFSET ); assert( 136==WALINDEX_HDR_SIZE ); #ifdef WIN_SHM_BASE assert( WIN_SHM_BASE==WALINDEX_LOCK_OFFSET ); #endif #ifdef UNIX_SHM_BASE assert( UNIX_SHM_BASE==WALINDEX_LOCK_OFFSET ); #endif /* Allocate an instance of struct Wal to return. */ *ppWal = 0; pRet = (Wal*)sqlite3MallocZero(sizeof(Wal) + pVfs->szOsFile); if( !pRet ){ return SQLITE_NOMEM_BKPT; } pRet->pVfs = pVfs; pRet->pWalFd = (sqlite3_file *)&pRet[1]; pRet->pDbFd = pDbFd; pRet->readLock = -1; pRet->mxWalSize = mxWalSize; pRet->zWalName = zWalName; pRet->syncHeader = 1; pRet->padToSectorBoundary = 1; pRet->exclusiveMode = (bNoShm ? WAL_HEAPMEMORY_MODE: WAL_NORMAL_MODE); /* Open file handle on the write-ahead log file. */ flags = (SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|SQLITE_OPEN_WAL); rc = sqlite3OsOpen(pVfs, zWalName, pRet->pWalFd, flags, &flags); if( rc==SQLITE_OK && flags&SQLITE_OPEN_READONLY ){ pRet->readOnly = WAL_RDONLY; } if( rc!=SQLITE_OK ){ walIndexClose(pRet, 0); sqlite3OsClose(pRet->pWalFd); sqlite3_free(pRet); }else{ int iDC = sqlite3OsDeviceCharacteristics(pDbFd); if( iDC & SQLITE_IOCAP_SEQUENTIAL ){ pRet->syncHeader = 0; } if( iDC & SQLITE_IOCAP_POWERSAFE_OVERWRITE ){ pRet->padToSectorBoundary = 0; } *ppWal = pRet; WALTRACE(("WAL%d: opened\n", pRet)); } return rc; } /* ** Change the size to which the WAL file is trucated on each reset. */ SQLITE_PRIVATE void sqlite3WalLimit(Wal *pWal, i64 iLimit){ if( pWal ) pWal->mxWalSize = iLimit; } /* ** Find the smallest page number out of all pages held in the WAL that ** has not been returned by any prior invocation of this method on the ** same WalIterator object. Write into *piFrame the frame index where ** that page was last written into the WAL. Write into *piPage the page ** number. ** ** Return 0 on success. If there are no pages in the WAL with a page ** number larger than *piPage, then return 1. */ static int walIteratorNext( WalIterator *p, /* Iterator */ u32 *piPage, /* OUT: The page number of the next page */ u32 *piFrame /* OUT: Wal frame index of next page */ ){ u32 iMin; /* Result pgno must be greater than iMin */ u32 iRet = 0xFFFFFFFF; /* 0xffffffff is never a valid page number */ int i; /* For looping through segments */ iMin = p->iPrior; assert( iMin<0xffffffff ); for(i=p->nSegment-1; i>=0; i--){ struct WalSegment *pSegment = &p->aSegment[i]; while( pSegment->iNextnEntry ){ u32 iPg = pSegment->aPgno[pSegment->aIndex[pSegment->iNext]]; if( iPg>iMin ){ if( iPgiZero + pSegment->aIndex[pSegment->iNext]; } break; } pSegment->iNext++; } } *piPage = p->iPrior = iRet; return (iRet==0xFFFFFFFF); } /* ** This function merges two sorted lists into a single sorted list. ** ** aLeft[] and aRight[] are arrays of indices. The sort key is ** aContent[aLeft[]] and aContent[aRight[]]. Upon entry, the following ** is guaranteed for all J0 && nRight>0 ); while( iRight=nRight || aContent[aLeft[iLeft]]=nLeft || aContent[aLeft[iLeft]]>dbpage ); assert( iRight>=nRight || aContent[aRight[iRight]]>dbpage ); } *paRight = aLeft; *pnRight = iOut; memcpy(aLeft, aTmp, sizeof(aTmp[0])*iOut); } /* ** Sort the elements in list aList using aContent[] as the sort key. ** Remove elements with duplicate keys, preferring to keep the ** larger aList[] values. ** ** The aList[] entries are indices into aContent[]. The values in ** aList[] are to be sorted so that for all J0 ); assert( HASHTABLE_NPAGE==(1<<(ArraySize(aSub)-1)) ); for(iList=0; iListaList && p->nList<=(1<aList==&aList[iList&~((2<aList, p->nList, &aMerge, &nMerge, aBuffer); } aSub[iSub].aList = aMerge; aSub[iSub].nList = nMerge; } for(iSub++; iSubnList<=(1<aList==&aList[nList&~((2<aList, p->nList, &aMerge, &nMerge, aBuffer); } } assert( aMerge==aList ); *pnList = nMerge; #ifdef SQLITE_DEBUG { int i; for(i=1; i<*pnList; i++){ assert( aContent[aList[i]] > aContent[aList[i-1]] ); } } #endif } /* ** Free an iterator allocated by walIteratorInit(). */ static void walIteratorFree(WalIterator *p){ sqlite3_free(p); } /* ** Construct a WalInterator object that can be used to loop over all ** pages in the WAL in ascending order. The caller must hold the checkpoint ** lock. ** ** On success, make *pp point to the newly allocated WalInterator object ** return SQLITE_OK. Otherwise, return an error code. If this routine ** returns an error, the value of *pp is undefined. ** ** The calling routine should invoke walIteratorFree() to destroy the ** WalIterator object when it has finished with it. */ static int walIteratorInit(Wal *pWal, WalIterator **pp){ WalIterator *p; /* Return value */ int nSegment; /* Number of segments to merge */ u32 iLast; /* Last frame in log */ int nByte; /* Number of bytes to allocate */ int i; /* Iterator variable */ ht_slot *aTmp; /* Temp space used by merge-sort */ int rc = SQLITE_OK; /* Return Code */ /* This routine only runs while holding the checkpoint lock. And ** it only runs if there is actually content in the log (mxFrame>0). */ assert( pWal->ckptLock && pWal->hdr.mxFrame>0 ); iLast = pWal->hdr.mxFrame; /* Allocate space for the WalIterator object. */ nSegment = walFramePage(iLast) + 1; nByte = sizeof(WalIterator) + (nSegment-1)*sizeof(struct WalSegment) + iLast*sizeof(ht_slot); p = (WalIterator *)sqlite3_malloc64(nByte); if( !p ){ return SQLITE_NOMEM_BKPT; } memset(p, 0, nByte); p->nSegment = nSegment; /* Allocate temporary space used by the merge-sort routine. This block ** of memory will be freed before this function returns. */ aTmp = (ht_slot *)sqlite3_malloc64( sizeof(ht_slot) * (iLast>HASHTABLE_NPAGE?HASHTABLE_NPAGE:iLast) ); if( !aTmp ){ rc = SQLITE_NOMEM_BKPT; } for(i=0; rc==SQLITE_OK && iaSegment[p->nSegment])[iZero]; iZero++; for(j=0; jaSegment[i].iZero = iZero; p->aSegment[i].nEntry = nEntry; p->aSegment[i].aIndex = aIndex; p->aSegment[i].aPgno = (u32 *)aPgno; } } sqlite3_free(aTmp); if( rc!=SQLITE_OK ){ walIteratorFree(p); } *pp = p; return rc; } /* ** Attempt to obtain the exclusive WAL lock defined by parameters lockIdx and ** n. If the attempt fails and parameter xBusy is not NULL, then it is a ** busy-handler function. Invoke it and retry the lock until either the ** lock is successfully obtained or the busy-handler returns 0. */ static int walBusyLock( Wal *pWal, /* WAL connection */ int (*xBusy)(void*), /* Function to call when busy */ void *pBusyArg, /* Context argument for xBusyHandler */ int lockIdx, /* Offset of first byte to lock */ int n /* Number of bytes to lock */ ){ int rc; do { rc = walLockExclusive(pWal, lockIdx, n); }while( xBusy && rc==SQLITE_BUSY && xBusy(pBusyArg) ); return rc; } /* ** The cache of the wal-index header must be valid to call this function. ** Return the page-size in bytes used by the database. */ static int walPagesize(Wal *pWal){ return (pWal->hdr.szPage&0xfe00) + ((pWal->hdr.szPage&0x0001)<<16); } /* ** The following is guaranteed when this function is called: ** ** a) the WRITER lock is held, ** b) the entire log file has been checkpointed, and ** c) any existing readers are reading exclusively from the database ** file - there are no readers that may attempt to read a frame from ** the log file. ** ** This function updates the shared-memory structures so that the next ** client to write to the database (which may be this one) does so by ** writing frames into the start of the log file. ** ** The value of parameter salt1 is used as the aSalt[1] value in the ** new wal-index header. It should be passed a pseudo-random value (i.e. ** one obtained from sqlite3_randomness()). */ static void walRestartHdr(Wal *pWal, u32 salt1){ volatile WalCkptInfo *pInfo = walCkptInfo(pWal); int i; /* Loop counter */ u32 *aSalt = pWal->hdr.aSalt; /* Big-endian salt values */ pWal->nCkpt++; pWal->hdr.mxFrame = 0; sqlite3Put4byte((u8*)&aSalt[0], 1 + sqlite3Get4byte((u8*)&aSalt[0])); memcpy(&pWal->hdr.aSalt[1], &salt1, 4); walIndexWriteHdr(pWal); pInfo->nBackfill = 0; pInfo->nBackfillAttempted = 0; pInfo->aReadMark[1] = 0; for(i=2; iaReadMark[i] = READMARK_NOT_USED; assert( pInfo->aReadMark[0]==0 ); } /* ** Copy as much content as we can from the WAL back into the database file ** in response to an sqlite3_wal_checkpoint() request or the equivalent. ** ** The amount of information copies from WAL to database might be limited ** by active readers. This routine will never overwrite a database page ** that a concurrent reader might be using. ** ** All I/O barrier operations (a.k.a fsyncs) occur in this routine when ** SQLite is in WAL-mode in synchronous=NORMAL. That means that if ** checkpoints are always run by a background thread or background ** process, foreground threads will never block on a lengthy fsync call. ** ** Fsync is called on the WAL before writing content out of the WAL and ** into the database. This ensures that if the new content is persistent ** in the WAL and can be recovered following a power-loss or hard reset. ** ** Fsync is also called on the database file if (and only if) the entire ** WAL content is copied into the database file. This second fsync makes ** it safe to delete the WAL since the new content will persist in the ** database file. ** ** This routine uses and updates the nBackfill field of the wal-index header. ** This is the only routine that will increase the value of nBackfill. ** (A WAL reset or recovery will revert nBackfill to zero, but not increase ** its value.) ** ** The caller must be holding sufficient locks to ensure that no other ** checkpoint is running (in any other thread or process) at the same ** time. */ static int walCheckpoint( Wal *pWal, /* Wal connection */ int eMode, /* One of PASSIVE, FULL or RESTART */ int (*xBusy)(void*), /* Function to call when busy */ void *pBusyArg, /* Context argument for xBusyHandler */ int sync_flags, /* Flags for OsSync() (or 0) */ u8 *zBuf /* Temporary buffer to use */ ){ int rc = SQLITE_OK; /* Return code */ int szPage; /* Database page-size */ WalIterator *pIter = 0; /* Wal iterator context */ u32 iDbpage = 0; /* Next database page to write */ u32 iFrame = 0; /* Wal frame containing data for iDbpage */ u32 mxSafeFrame; /* Max frame that can be backfilled */ u32 mxPage; /* Max database page to write */ int i; /* Loop counter */ volatile WalCkptInfo *pInfo; /* The checkpoint status information */ szPage = walPagesize(pWal); testcase( szPage<=32768 ); testcase( szPage>=65536 ); pInfo = walCkptInfo(pWal); if( pInfo->nBackfillhdr.mxFrame ){ /* Allocate the iterator */ rc = walIteratorInit(pWal, &pIter); if( rc!=SQLITE_OK ){ return rc; } assert( pIter ); /* EVIDENCE-OF: R-62920-47450 The busy-handler callback is never invoked ** in the SQLITE_CHECKPOINT_PASSIVE mode. */ assert( eMode!=SQLITE_CHECKPOINT_PASSIVE || xBusy==0 ); /* Compute in mxSafeFrame the index of the last frame of the WAL that is ** safe to write into the database. Frames beyond mxSafeFrame might ** overwrite database pages that are in use by active readers and thus ** cannot be backfilled from the WAL. */ mxSafeFrame = pWal->hdr.mxFrame; mxPage = pWal->hdr.nPage; for(i=1; iaReadMark[i]; if( mxSafeFrame>y ){ assert( y<=pWal->hdr.mxFrame ); rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_READ_LOCK(i), 1); if( rc==SQLITE_OK ){ pInfo->aReadMark[i] = (i==1 ? mxSafeFrame : READMARK_NOT_USED); walUnlockExclusive(pWal, WAL_READ_LOCK(i), 1); }else if( rc==SQLITE_BUSY ){ mxSafeFrame = y; xBusy = 0; }else{ goto walcheckpoint_out; } } } if( pInfo->nBackfillnBackfill; pInfo->nBackfillAttempted = mxSafeFrame; /* Sync the WAL to disk */ if( sync_flags ){ rc = sqlite3OsSync(pWal->pWalFd, sync_flags); } /* If the database may grow as a result of this checkpoint, hint ** about the eventual size of the db file to the VFS layer. */ if( rc==SQLITE_OK ){ i64 nReq = ((i64)mxPage * szPage); rc = sqlite3OsFileSize(pWal->pDbFd, &nSize); if( rc==SQLITE_OK && nSizepDbFd, SQLITE_FCNTL_SIZE_HINT, &nReq); } } /* Iterate through the contents of the WAL, copying data to the db file */ while( rc==SQLITE_OK && 0==walIteratorNext(pIter, &iDbpage, &iFrame) ){ i64 iOffset; assert( walFramePgno(pWal, iFrame)==iDbpage ); if( iFrame<=nBackfill || iFrame>mxSafeFrame || iDbpage>mxPage ){ continue; } iOffset = walFrameOffset(iFrame, szPage) + WAL_FRAME_HDRSIZE; /* testcase( IS_BIG_INT(iOffset) ); // requires a 4GiB WAL file */ rc = sqlite3OsRead(pWal->pWalFd, zBuf, szPage, iOffset); if( rc!=SQLITE_OK ) break; iOffset = (iDbpage-1)*(i64)szPage; testcase( IS_BIG_INT(iOffset) ); rc = sqlite3OsWrite(pWal->pDbFd, zBuf, szPage, iOffset); if( rc!=SQLITE_OK ) break; } /* If work was actually accomplished... */ if( rc==SQLITE_OK ){ if( mxSafeFrame==walIndexHdr(pWal)->mxFrame ){ i64 szDb = pWal->hdr.nPage*(i64)szPage; testcase( IS_BIG_INT(szDb) ); rc = sqlite3OsTruncate(pWal->pDbFd, szDb); if( rc==SQLITE_OK && sync_flags ){ rc = sqlite3OsSync(pWal->pDbFd, sync_flags); } } if( rc==SQLITE_OK ){ pInfo->nBackfill = mxSafeFrame; } } /* Release the reader lock held while backfilling */ walUnlockExclusive(pWal, WAL_READ_LOCK(0), 1); } if( rc==SQLITE_BUSY ){ /* Reset the return code so as not to report a checkpoint failure ** just because there are active readers. */ rc = SQLITE_OK; } } /* If this is an SQLITE_CHECKPOINT_RESTART or TRUNCATE operation, and the ** entire wal file has been copied into the database file, then block ** until all readers have finished using the wal file. This ensures that ** the next process to write to the database restarts the wal file. */ if( rc==SQLITE_OK && eMode!=SQLITE_CHECKPOINT_PASSIVE ){ assert( pWal->writeLock ); if( pInfo->nBackfillhdr.mxFrame ){ rc = SQLITE_BUSY; }else if( eMode>=SQLITE_CHECKPOINT_RESTART ){ u32 salt1; sqlite3_randomness(4, &salt1); assert( pInfo->nBackfill==pWal->hdr.mxFrame ); rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_READ_LOCK(1), WAL_NREADER-1); if( rc==SQLITE_OK ){ if( eMode==SQLITE_CHECKPOINT_TRUNCATE ){ /* IMPLEMENTATION-OF: R-44699-57140 This mode works the same way as ** SQLITE_CHECKPOINT_RESTART with the addition that it also ** truncates the log file to zero bytes just prior to a ** successful return. ** ** In theory, it might be safe to do this without updating the ** wal-index header in shared memory, as all subsequent reader or ** writer clients should see that the entire log file has been ** checkpointed and behave accordingly. This seems unsafe though, ** as it would leave the system in a state where the contents of ** the wal-index header do not match the contents of the ** file-system. To avoid this, update the wal-index header to ** indicate that the log file contains zero valid frames. */ walRestartHdr(pWal, salt1); rc = sqlite3OsTruncate(pWal->pWalFd, 0); } walUnlockExclusive(pWal, WAL_READ_LOCK(1), WAL_NREADER-1); } } } walcheckpoint_out: walIteratorFree(pIter); return rc; } /* ** If the WAL file is currently larger than nMax bytes in size, truncate ** it to exactly nMax bytes. If an error occurs while doing so, ignore it. */ static void walLimitSize(Wal *pWal, i64 nMax){ i64 sz; int rx; sqlite3BeginBenignMalloc(); rx = sqlite3OsFileSize(pWal->pWalFd, &sz); if( rx==SQLITE_OK && (sz > nMax ) ){ rx = sqlite3OsTruncate(pWal->pWalFd, nMax); } sqlite3EndBenignMalloc(); if( rx ){ sqlite3_log(rx, "cannot limit WAL size: %s", pWal->zWalName); } } /* ** Close a connection to a log file. */ SQLITE_PRIVATE int sqlite3WalClose( Wal *pWal, /* Wal to close */ int sync_flags, /* Flags to pass to OsSync() (or 0) */ int nBuf, u8 *zBuf /* Buffer of at least nBuf bytes */ ){ int rc = SQLITE_OK; if( pWal ){ int isDelete = 0; /* True to unlink wal and wal-index files */ /* If an EXCLUSIVE lock can be obtained on the database file (using the ** ordinary, rollback-mode locking methods, this guarantees that the ** connection associated with this log file is the only connection to ** the database. In this case checkpoint the database and unlink both ** the wal and wal-index files. ** ** The EXCLUSIVE lock is not released before returning. */ rc = sqlite3OsLock(pWal->pDbFd, SQLITE_LOCK_EXCLUSIVE); if( rc==SQLITE_OK ){ if( pWal->exclusiveMode==WAL_NORMAL_MODE ){ pWal->exclusiveMode = WAL_EXCLUSIVE_MODE; } rc = sqlite3WalCheckpoint( pWal, SQLITE_CHECKPOINT_PASSIVE, 0, 0, sync_flags, nBuf, zBuf, 0, 0 ); if( rc==SQLITE_OK ){ int bPersist = -1; sqlite3OsFileControlHint( pWal->pDbFd, SQLITE_FCNTL_PERSIST_WAL, &bPersist ); if( bPersist!=1 ){ /* Try to delete the WAL file if the checkpoint completed and ** fsyned (rc==SQLITE_OK) and if we are not in persistent-wal ** mode (!bPersist) */ isDelete = 1; }else if( pWal->mxWalSize>=0 ){ /* Try to truncate the WAL file to zero bytes if the checkpoint ** completed and fsynced (rc==SQLITE_OK) and we are in persistent ** WAL mode (bPersist) and if the PRAGMA journal_size_limit is a ** non-negative value (pWal->mxWalSize>=0). Note that we truncate ** to zero bytes as truncating to the journal_size_limit might ** leave a corrupt WAL file on disk. */ walLimitSize(pWal, 0); } } } walIndexClose(pWal, isDelete); sqlite3OsClose(pWal->pWalFd); if( isDelete ){ sqlite3BeginBenignMalloc(); sqlite3OsDelete(pWal->pVfs, pWal->zWalName, 0); sqlite3EndBenignMalloc(); } WALTRACE(("WAL%p: closed\n", pWal)); sqlite3_free((void *)pWal->apWiData); sqlite3_free(pWal); } return rc; } /* ** Try to read the wal-index header. Return 0 on success and 1 if ** there is a problem. ** ** The wal-index is in shared memory. Another thread or process might ** be writing the header at the same time this procedure is trying to ** read it, which might result in inconsistency. A dirty read is detected ** by verifying that both copies of the header are the same and also by ** a checksum on the header. ** ** If and only if the read is consistent and the header is different from ** pWal->hdr, then pWal->hdr is updated to the content of the new header ** and *pChanged is set to 1. ** ** If the checksum cannot be verified return non-zero. If the header ** is read successfully and the checksum verified, return zero. */ static int walIndexTryHdr(Wal *pWal, int *pChanged){ u32 aCksum[2]; /* Checksum on the header content */ WalIndexHdr h1, h2; /* Two copies of the header content */ WalIndexHdr volatile *aHdr; /* Header in shared memory */ /* The first page of the wal-index must be mapped at this point. */ assert( pWal->nWiData>0 && pWal->apWiData[0] ); /* Read the header. This might happen concurrently with a write to the ** same area of shared memory on a different CPU in a SMP, ** meaning it is possible that an inconsistent snapshot is read ** from the file. If this happens, return non-zero. ** ** There are two copies of the header at the beginning of the wal-index. ** When reading, read [0] first then [1]. Writes are in the reverse order. ** Memory barriers are used to prevent the compiler or the hardware from ** reordering the reads and writes. */ aHdr = walIndexHdr(pWal); memcpy(&h1, (void *)&aHdr[0], sizeof(h1)); walShmBarrier(pWal); memcpy(&h2, (void *)&aHdr[1], sizeof(h2)); if( memcmp(&h1, &h2, sizeof(h1))!=0 ){ return 1; /* Dirty read */ } if( h1.isInit==0 ){ return 1; /* Malformed header - probably all zeros */ } walChecksumBytes(1, (u8*)&h1, sizeof(h1)-sizeof(h1.aCksum), 0, aCksum); if( aCksum[0]!=h1.aCksum[0] || aCksum[1]!=h1.aCksum[1] ){ return 1; /* Checksum does not match */ } if( memcmp(&pWal->hdr, &h1, sizeof(WalIndexHdr)) ){ *pChanged = 1; memcpy(&pWal->hdr, &h1, sizeof(WalIndexHdr)); pWal->szPage = (pWal->hdr.szPage&0xfe00) + ((pWal->hdr.szPage&0x0001)<<16); testcase( pWal->szPage<=32768 ); testcase( pWal->szPage>=65536 ); } /* The header was successfully read. Return zero. */ return 0; } /* ** Read the wal-index header from the wal-index and into pWal->hdr. ** If the wal-header appears to be corrupt, try to reconstruct the ** wal-index from the WAL before returning. ** ** Set *pChanged to 1 if the wal-index header value in pWal->hdr is ** changed by this operation. If pWal->hdr is unchanged, set *pChanged ** to 0. ** ** If the wal-index header is successfully read, return SQLITE_OK. ** Otherwise an SQLite error code. */ static int walIndexReadHdr(Wal *pWal, int *pChanged){ int rc; /* Return code */ int badHdr; /* True if a header read failed */ volatile u32 *page0; /* Chunk of wal-index containing header */ /* Ensure that page 0 of the wal-index (the page that contains the ** wal-index header) is mapped. Return early if an error occurs here. */ assert( pChanged ); rc = walIndexPage(pWal, 0, &page0); if( rc!=SQLITE_OK ){ return rc; }; assert( page0 || pWal->writeLock==0 ); /* If the first page of the wal-index has been mapped, try to read the ** wal-index header immediately, without holding any lock. This usually ** works, but may fail if the wal-index header is corrupt or currently ** being modified by another thread or process. */ badHdr = (page0 ? walIndexTryHdr(pWal, pChanged) : 1); /* If the first attempt failed, it might have been due to a race ** with a writer. So get a WRITE lock and try again. */ assert( badHdr==0 || pWal->writeLock==0 ); if( badHdr ){ if( pWal->readOnly & WAL_SHM_RDONLY ){ if( SQLITE_OK==(rc = walLockShared(pWal, WAL_WRITE_LOCK)) ){ walUnlockShared(pWal, WAL_WRITE_LOCK); rc = SQLITE_READONLY_RECOVERY; } }else if( SQLITE_OK==(rc = walLockExclusive(pWal, WAL_WRITE_LOCK, 1)) ){ pWal->writeLock = 1; if( SQLITE_OK==(rc = walIndexPage(pWal, 0, &page0)) ){ badHdr = walIndexTryHdr(pWal, pChanged); if( badHdr ){ /* If the wal-index header is still malformed even while holding ** a WRITE lock, it can only mean that the header is corrupted and ** needs to be reconstructed. So run recovery to do exactly that. */ rc = walIndexRecover(pWal); *pChanged = 1; } } pWal->writeLock = 0; walUnlockExclusive(pWal, WAL_WRITE_LOCK, 1); } } /* If the header is read successfully, check the version number to make ** sure the wal-index was not constructed with some future format that ** this version of SQLite cannot understand. */ if( badHdr==0 && pWal->hdr.iVersion!=WALINDEX_MAX_VERSION ){ rc = SQLITE_CANTOPEN_BKPT; } return rc; } /* ** This is the value that walTryBeginRead returns when it needs to ** be retried. */ #define WAL_RETRY (-1) /* ** Attempt to start a read transaction. This might fail due to a race or ** other transient condition. When that happens, it returns WAL_RETRY to ** indicate to the caller that it is safe to retry immediately. ** ** On success return SQLITE_OK. On a permanent failure (such an ** I/O error or an SQLITE_BUSY because another process is running ** recovery) return a positive error code. ** ** The useWal parameter is true to force the use of the WAL and disable ** the case where the WAL is bypassed because it has been completely ** checkpointed. If useWal==0 then this routine calls walIndexReadHdr() ** to make a copy of the wal-index header into pWal->hdr. If the ** wal-index header has changed, *pChanged is set to 1 (as an indication ** to the caller that the local paget cache is obsolete and needs to be ** flushed.) When useWal==1, the wal-index header is assumed to already ** be loaded and the pChanged parameter is unused. ** ** The caller must set the cnt parameter to the number of prior calls to ** this routine during the current read attempt that returned WAL_RETRY. ** This routine will start taking more aggressive measures to clear the ** race conditions after multiple WAL_RETRY returns, and after an excessive ** number of errors will ultimately return SQLITE_PROTOCOL. The ** SQLITE_PROTOCOL return indicates that some other process has gone rogue ** and is not honoring the locking protocol. There is a vanishingly small ** chance that SQLITE_PROTOCOL could be returned because of a run of really ** bad luck when there is lots of contention for the wal-index, but that ** possibility is so small that it can be safely neglected, we believe. ** ** On success, this routine obtains a read lock on ** WAL_READ_LOCK(pWal->readLock). The pWal->readLock integer is ** in the range 0 <= pWal->readLock < WAL_NREADER. If pWal->readLock==(-1) ** that means the Wal does not hold any read lock. The reader must not ** access any database page that is modified by a WAL frame up to and ** including frame number aReadMark[pWal->readLock]. The reader will ** use WAL frames up to and including pWal->hdr.mxFrame if pWal->readLock>0 ** Or if pWal->readLock==0, then the reader will ignore the WAL ** completely and get all content directly from the database file. ** If the useWal parameter is 1 then the WAL will never be ignored and ** this routine will always set pWal->readLock>0 on success. ** When the read transaction is completed, the caller must release the ** lock on WAL_READ_LOCK(pWal->readLock) and set pWal->readLock to -1. ** ** This routine uses the nBackfill and aReadMark[] fields of the header ** to select a particular WAL_READ_LOCK() that strives to let the ** checkpoint process do as much work as possible. This routine might ** update values of the aReadMark[] array in the header, but if it does ** so it takes care to hold an exclusive lock on the corresponding ** WAL_READ_LOCK() while changing values. */ static int walTryBeginRead(Wal *pWal, int *pChanged, int useWal, int cnt){ volatile WalCkptInfo *pInfo; /* Checkpoint information in wal-index */ u32 mxReadMark; /* Largest aReadMark[] value */ int mxI; /* Index of largest aReadMark[] value */ int i; /* Loop counter */ int rc = SQLITE_OK; /* Return code */ u32 mxFrame; /* Wal frame to lock to */ assert( pWal->readLock<0 ); /* Not currently locked */ /* Take steps to avoid spinning forever if there is a protocol error. ** ** Circumstances that cause a RETRY should only last for the briefest ** instances of time. No I/O or other system calls are done while the ** locks are held, so the locks should not be held for very long. But ** if we are unlucky, another process that is holding a lock might get ** paged out or take a page-fault that is time-consuming to resolve, ** during the few nanoseconds that it is holding the lock. In that case, ** it might take longer than normal for the lock to free. ** ** After 5 RETRYs, we begin calling sqlite3OsSleep(). The first few ** calls to sqlite3OsSleep() have a delay of 1 microsecond. Really this ** is more of a scheduler yield than an actual delay. But on the 10th ** an subsequent retries, the delays start becoming longer and longer, ** so that on the 100th (and last) RETRY we delay for 323 milliseconds. ** The total delay time before giving up is less than 10 seconds. */ if( cnt>5 ){ int nDelay = 1; /* Pause time in microseconds */ if( cnt>100 ){ VVA_ONLY( pWal->lockError = 1; ) return SQLITE_PROTOCOL; } if( cnt>=10 ) nDelay = (cnt-9)*(cnt-9)*39; sqlite3OsSleep(pWal->pVfs, nDelay); } if( !useWal ){ rc = walIndexReadHdr(pWal, pChanged); if( rc==SQLITE_BUSY ){ /* If there is not a recovery running in another thread or process ** then convert BUSY errors to WAL_RETRY. If recovery is known to ** be running, convert BUSY to BUSY_RECOVERY. There is a race here ** which might cause WAL_RETRY to be returned even if BUSY_RECOVERY ** would be technically correct. But the race is benign since with ** WAL_RETRY this routine will be called again and will probably be ** right on the second iteration. */ if( pWal->apWiData[0]==0 ){ /* This branch is taken when the xShmMap() method returns SQLITE_BUSY. ** We assume this is a transient condition, so return WAL_RETRY. The ** xShmMap() implementation used by the default unix and win32 VFS ** modules may return SQLITE_BUSY due to a race condition in the ** code that determines whether or not the shared-memory region ** must be zeroed before the requested page is returned. */ rc = WAL_RETRY; }else if( SQLITE_OK==(rc = walLockShared(pWal, WAL_RECOVER_LOCK)) ){ walUnlockShared(pWal, WAL_RECOVER_LOCK); rc = WAL_RETRY; }else if( rc==SQLITE_BUSY ){ rc = SQLITE_BUSY_RECOVERY; } } if( rc!=SQLITE_OK ){ return rc; } } pInfo = walCkptInfo(pWal); if( !useWal && pInfo->nBackfill==pWal->hdr.mxFrame #ifdef SQLITE_ENABLE_SNAPSHOT && (pWal->pSnapshot==0 || pWal->hdr.mxFrame==0 || 0==memcmp(&pWal->hdr, pWal->pSnapshot, sizeof(WalIndexHdr))) #endif ){ /* The WAL has been completely backfilled (or it is empty). ** and can be safely ignored. */ rc = walLockShared(pWal, WAL_READ_LOCK(0)); walShmBarrier(pWal); if( rc==SQLITE_OK ){ if( memcmp((void *)walIndexHdr(pWal), &pWal->hdr, sizeof(WalIndexHdr)) ){ /* It is not safe to allow the reader to continue here if frames ** may have been appended to the log before READ_LOCK(0) was obtained. ** When holding READ_LOCK(0), the reader ignores the entire log file, ** which implies that the database file contains a trustworthy ** snapshot. Since holding READ_LOCK(0) prevents a checkpoint from ** happening, this is usually correct. ** ** However, if frames have been appended to the log (or if the log ** is wrapped and written for that matter) before the READ_LOCK(0) ** is obtained, that is not necessarily true. A checkpointer may ** have started to backfill the appended frames but crashed before ** it finished. Leaving a corrupt image in the database file. */ walUnlockShared(pWal, WAL_READ_LOCK(0)); return WAL_RETRY; } pWal->readLock = 0; return SQLITE_OK; }else if( rc!=SQLITE_BUSY ){ return rc; } } /* If we get this far, it means that the reader will want to use ** the WAL to get at content from recent commits. The job now is ** to select one of the aReadMark[] entries that is closest to ** but not exceeding pWal->hdr.mxFrame and lock that entry. */ mxReadMark = 0; mxI = 0; mxFrame = pWal->hdr.mxFrame; #ifdef SQLITE_ENABLE_SNAPSHOT if( pWal->pSnapshot && pWal->pSnapshot->mxFramepSnapshot->mxFrame; } #endif for(i=1; iaReadMark[i]; if( mxReadMark<=thisMark && thisMark<=mxFrame ){ assert( thisMark!=READMARK_NOT_USED ); mxReadMark = thisMark; mxI = i; } } if( (pWal->readOnly & WAL_SHM_RDONLY)==0 && (mxReadMarkaReadMark[i] = mxFrame; mxI = i; walUnlockExclusive(pWal, WAL_READ_LOCK(i), 1); break; }else if( rc!=SQLITE_BUSY ){ return rc; } } } if( mxI==0 ){ assert( rc==SQLITE_BUSY || (pWal->readOnly & WAL_SHM_RDONLY)!=0 ); return rc==SQLITE_BUSY ? WAL_RETRY : SQLITE_READONLY_CANTLOCK; } rc = walLockShared(pWal, WAL_READ_LOCK(mxI)); if( rc ){ return rc==SQLITE_BUSY ? WAL_RETRY : rc; } /* Now that the read-lock has been obtained, check that neither the ** value in the aReadMark[] array or the contents of the wal-index ** header have changed. ** ** It is necessary to check that the wal-index header did not change ** between the time it was read and when the shared-lock was obtained ** on WAL_READ_LOCK(mxI) was obtained to account for the possibility ** that the log file may have been wrapped by a writer, or that frames ** that occur later in the log than pWal->hdr.mxFrame may have been ** copied into the database by a checkpointer. If either of these things ** happened, then reading the database with the current value of ** pWal->hdr.mxFrame risks reading a corrupted snapshot. So, retry ** instead. ** ** Before checking that the live wal-index header has not changed ** since it was read, set Wal.minFrame to the first frame in the wal ** file that has not yet been checkpointed. This client will not need ** to read any frames earlier than minFrame from the wal file - they ** can be safely read directly from the database file. ** ** Because a ShmBarrier() call is made between taking the copy of ** nBackfill and checking that the wal-header in shared-memory still ** matches the one cached in pWal->hdr, it is guaranteed that the ** checkpointer that set nBackfill was not working with a wal-index ** header newer than that cached in pWal->hdr. If it were, that could ** cause a problem. The checkpointer could omit to checkpoint ** a version of page X that lies before pWal->minFrame (call that version ** A) on the basis that there is a newer version (version B) of the same ** page later in the wal file. But if version B happens to like past ** frame pWal->hdr.mxFrame - then the client would incorrectly assume ** that it can read version A from the database file. However, since ** we can guarantee that the checkpointer that set nBackfill could not ** see any pages past pWal->hdr.mxFrame, this problem does not come up. */ pWal->minFrame = pInfo->nBackfill+1; walShmBarrier(pWal); if( pInfo->aReadMark[mxI]!=mxReadMark || memcmp((void *)walIndexHdr(pWal), &pWal->hdr, sizeof(WalIndexHdr)) ){ walUnlockShared(pWal, WAL_READ_LOCK(mxI)); return WAL_RETRY; }else{ assert( mxReadMark<=pWal->hdr.mxFrame ); pWal->readLock = (i16)mxI; } return rc; } /* ** Begin a read transaction on the database. ** ** This routine used to be called sqlite3OpenSnapshot() and with good reason: ** it takes a snapshot of the state of the WAL and wal-index for the current ** instant in time. The current thread will continue to use this snapshot. ** Other threads might append new content to the WAL and wal-index but ** that extra content is ignored by the current thread. ** ** If the database contents have changes since the previous read ** transaction, then *pChanged is set to 1 before returning. The ** Pager layer will use this to know that is cache is stale and ** needs to be flushed. */ SQLITE_PRIVATE int sqlite3WalBeginReadTransaction(Wal *pWal, int *pChanged){ int rc; /* Return code */ int cnt = 0; /* Number of TryBeginRead attempts */ #ifdef SQLITE_ENABLE_SNAPSHOT int bChanged = 0; WalIndexHdr *pSnapshot = pWal->pSnapshot; if( pSnapshot && memcmp(pSnapshot, &pWal->hdr, sizeof(WalIndexHdr))!=0 ){ bChanged = 1; } #endif do{ rc = walTryBeginRead(pWal, pChanged, 0, ++cnt); }while( rc==WAL_RETRY ); testcase( (rc&0xff)==SQLITE_BUSY ); testcase( (rc&0xff)==SQLITE_IOERR ); testcase( rc==SQLITE_PROTOCOL ); testcase( rc==SQLITE_OK ); #ifdef SQLITE_ENABLE_SNAPSHOT if( rc==SQLITE_OK ){ if( pSnapshot && memcmp(pSnapshot, &pWal->hdr, sizeof(WalIndexHdr))!=0 ){ /* At this point the client has a lock on an aReadMark[] slot holding ** a value equal to or smaller than pSnapshot->mxFrame, but pWal->hdr ** is populated with the wal-index header corresponding to the head ** of the wal file. Verify that pSnapshot is still valid before ** continuing. Reasons why pSnapshot might no longer be valid: ** ** (1) The WAL file has been reset since the snapshot was taken. ** In this case, the salt will have changed. ** ** (2) A checkpoint as been attempted that wrote frames past ** pSnapshot->mxFrame into the database file. Note that the ** checkpoint need not have completed for this to cause problems. */ volatile WalCkptInfo *pInfo = walCkptInfo(pWal); assert( pWal->readLock>0 || pWal->hdr.mxFrame==0 ); assert( pInfo->aReadMark[pWal->readLock]<=pSnapshot->mxFrame ); /* It is possible that there is a checkpointer thread running ** concurrent with this code. If this is the case, it may be that the ** checkpointer has already determined that it will checkpoint ** snapshot X, where X is later in the wal file than pSnapshot, but ** has not yet set the pInfo->nBackfillAttempted variable to indicate ** its intent. To avoid the race condition this leads to, ensure that ** there is no checkpointer process by taking a shared CKPT lock ** before checking pInfo->nBackfillAttempted. */ rc = walLockShared(pWal, WAL_CKPT_LOCK); if( rc==SQLITE_OK ){ /* Check that the wal file has not been wrapped. Assuming that it has ** not, also check that no checkpointer has attempted to checkpoint any ** frames beyond pSnapshot->mxFrame. If either of these conditions are ** true, return SQLITE_BUSY_SNAPSHOT. Otherwise, overwrite pWal->hdr ** with *pSnapshot and set *pChanged as appropriate for opening the ** snapshot. */ if( !memcmp(pSnapshot->aSalt, pWal->hdr.aSalt, sizeof(pWal->hdr.aSalt)) && pSnapshot->mxFrame>=pInfo->nBackfillAttempted ){ assert( pWal->readLock>0 ); memcpy(&pWal->hdr, pSnapshot, sizeof(WalIndexHdr)); *pChanged = bChanged; }else{ rc = SQLITE_BUSY_SNAPSHOT; } /* Release the shared CKPT lock obtained above. */ walUnlockShared(pWal, WAL_CKPT_LOCK); } if( rc!=SQLITE_OK ){ sqlite3WalEndReadTransaction(pWal); } } } #endif return rc; } /* ** Finish with a read transaction. All this does is release the ** read-lock. */ SQLITE_PRIVATE void sqlite3WalEndReadTransaction(Wal *pWal){ sqlite3WalEndWriteTransaction(pWal); if( pWal->readLock>=0 ){ walUnlockShared(pWal, WAL_READ_LOCK(pWal->readLock)); pWal->readLock = -1; } } /* ** Search the wal file for page pgno. If found, set *piRead to the frame that ** contains the page. Otherwise, if pgno is not in the wal file, set *piRead ** to zero. ** ** Return SQLITE_OK if successful, or an error code if an error occurs. If an ** error does occur, the final value of *piRead is undefined. */ SQLITE_PRIVATE int sqlite3WalFindFrame( Wal *pWal, /* WAL handle */ Pgno pgno, /* Database page number to read data for */ u32 *piRead /* OUT: Frame number (or zero) */ ){ u32 iRead = 0; /* If !=0, WAL frame to return data from */ u32 iLast = pWal->hdr.mxFrame; /* Last page in WAL for this reader */ int iHash; /* Used to loop through N hash tables */ int iMinHash; /* This routine is only be called from within a read transaction. */ assert( pWal->readLock>=0 || pWal->lockError ); /* If the "last page" field of the wal-index header snapshot is 0, then ** no data will be read from the wal under any circumstances. Return early ** in this case as an optimization. Likewise, if pWal->readLock==0, ** then the WAL is ignored by the reader so return early, as if the ** WAL were empty. */ if( iLast==0 || pWal->readLock==0 ){ *piRead = 0; return SQLITE_OK; } /* Search the hash table or tables for an entry matching page number ** pgno. Each iteration of the following for() loop searches one ** hash table (each hash table indexes up to HASHTABLE_NPAGE frames). ** ** This code might run concurrently to the code in walIndexAppend() ** that adds entries to the wal-index (and possibly to this hash ** table). This means the value just read from the hash ** slot (aHash[iKey]) may have been added before or after the ** current read transaction was opened. Values added after the ** read transaction was opened may have been written incorrectly - ** i.e. these slots may contain garbage data. However, we assume ** that any slots written before the current read transaction was ** opened remain unmodified. ** ** For the reasons above, the if(...) condition featured in the inner ** loop of the following block is more stringent that would be required ** if we had exclusive access to the hash-table: ** ** (aPgno[iFrame]==pgno): ** This condition filters out normal hash-table collisions. ** ** (iFrame<=iLast): ** This condition filters out entries that were added to the hash ** table after the current read-transaction had started. */ iMinHash = walFramePage(pWal->minFrame); for(iHash=walFramePage(iLast); iHash>=iMinHash && iRead==0; iHash--){ volatile ht_slot *aHash; /* Pointer to hash table */ volatile u32 *aPgno; /* Pointer to array of page numbers */ u32 iZero; /* Frame number corresponding to aPgno[0] */ int iKey; /* Hash slot index */ int nCollide; /* Number of hash collisions remaining */ int rc; /* Error code */ rc = walHashGet(pWal, iHash, &aHash, &aPgno, &iZero); if( rc!=SQLITE_OK ){ return rc; } nCollide = HASHTABLE_NSLOT; for(iKey=walHash(pgno); aHash[iKey]; iKey=walNextHash(iKey)){ u32 iFrame = aHash[iKey] + iZero; if( iFrame<=iLast && iFrame>=pWal->minFrame && aPgno[aHash[iKey]]==pgno ){ assert( iFrame>iRead || CORRUPT_DB ); iRead = iFrame; } if( (nCollide--)==0 ){ return SQLITE_CORRUPT_BKPT; } } } #ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT /* If expensive assert() statements are available, do a linear search ** of the wal-index file content. Make sure the results agree with the ** result obtained using the hash indexes above. */ { u32 iRead2 = 0; u32 iTest; assert( pWal->minFrame>0 ); for(iTest=iLast; iTest>=pWal->minFrame; iTest--){ if( walFramePgno(pWal, iTest)==pgno ){ iRead2 = iTest; break; } } assert( iRead==iRead2 ); } #endif *piRead = iRead; return SQLITE_OK; } /* ** Read the contents of frame iRead from the wal file into buffer pOut ** (which is nOut bytes in size). Return SQLITE_OK if successful, or an ** error code otherwise. */ SQLITE_PRIVATE int sqlite3WalReadFrame( Wal *pWal, /* WAL handle */ u32 iRead, /* Frame to read */ int nOut, /* Size of buffer pOut in bytes */ u8 *pOut /* Buffer to write page data to */ ){ int sz; i64 iOffset; sz = pWal->hdr.szPage; sz = (sz&0xfe00) + ((sz&0x0001)<<16); testcase( sz<=32768 ); testcase( sz>=65536 ); iOffset = walFrameOffset(iRead, sz) + WAL_FRAME_HDRSIZE; /* testcase( IS_BIG_INT(iOffset) ); // requires a 4GiB WAL */ return sqlite3OsRead(pWal->pWalFd, pOut, (nOut>sz ? sz : nOut), iOffset); } /* ** Return the size of the database in pages (or zero, if unknown). */ SQLITE_PRIVATE Pgno sqlite3WalDbsize(Wal *pWal){ if( pWal && ALWAYS(pWal->readLock>=0) ){ return pWal->hdr.nPage; } return 0; } /* ** This function starts a write transaction on the WAL. ** ** A read transaction must have already been started by a prior call ** to sqlite3WalBeginReadTransaction(). ** ** If another thread or process has written into the database since ** the read transaction was started, then it is not possible for this ** thread to write as doing so would cause a fork. So this routine ** returns SQLITE_BUSY in that case and no write transaction is started. ** ** There can only be a single writer active at a time. */ SQLITE_PRIVATE int sqlite3WalBeginWriteTransaction(Wal *pWal){ int rc; /* Cannot start a write transaction without first holding a read ** transaction. */ assert( pWal->readLock>=0 ); assert( pWal->writeLock==0 && pWal->iReCksum==0 ); if( pWal->readOnly ){ return SQLITE_READONLY; } /* Only one writer allowed at a time. Get the write lock. Return ** SQLITE_BUSY if unable. */ rc = walLockExclusive(pWal, WAL_WRITE_LOCK, 1); if( rc ){ return rc; } pWal->writeLock = 1; /* If another connection has written to the database file since the ** time the read transaction on this connection was started, then ** the write is disallowed. */ if( memcmp(&pWal->hdr, (void *)walIndexHdr(pWal), sizeof(WalIndexHdr))!=0 ){ walUnlockExclusive(pWal, WAL_WRITE_LOCK, 1); pWal->writeLock = 0; rc = SQLITE_BUSY_SNAPSHOT; } return rc; } /* ** End a write transaction. The commit has already been done. This ** routine merely releases the lock. */ SQLITE_PRIVATE int sqlite3WalEndWriteTransaction(Wal *pWal){ if( pWal->writeLock ){ walUnlockExclusive(pWal, WAL_WRITE_LOCK, 1); pWal->writeLock = 0; pWal->iReCksum = 0; pWal->truncateOnCommit = 0; } return SQLITE_OK; } /* ** If any data has been written (but not committed) to the log file, this ** function moves the write-pointer back to the start of the transaction. ** ** Additionally, the callback function is invoked for each frame written ** to the WAL since the start of the transaction. If the callback returns ** other than SQLITE_OK, it is not invoked again and the error code is ** returned to the caller. ** ** Otherwise, if the callback function does not return an error, this ** function returns SQLITE_OK. */ SQLITE_PRIVATE int sqlite3WalUndo(Wal *pWal, int (*xUndo)(void *, Pgno), void *pUndoCtx){ int rc = SQLITE_OK; if( ALWAYS(pWal->writeLock) ){ Pgno iMax = pWal->hdr.mxFrame; Pgno iFrame; /* Restore the clients cache of the wal-index header to the state it ** was in before the client began writing to the database. */ memcpy(&pWal->hdr, (void *)walIndexHdr(pWal), sizeof(WalIndexHdr)); for(iFrame=pWal->hdr.mxFrame+1; ALWAYS(rc==SQLITE_OK) && iFrame<=iMax; iFrame++ ){ /* This call cannot fail. Unless the page for which the page number ** is passed as the second argument is (a) in the cache and ** (b) has an outstanding reference, then xUndo is either a no-op ** (if (a) is false) or simply expels the page from the cache (if (b) ** is false). ** ** If the upper layer is doing a rollback, it is guaranteed that there ** are no outstanding references to any page other than page 1. And ** page 1 is never written to the log until the transaction is ** committed. As a result, the call to xUndo may not fail. */ assert( walFramePgno(pWal, iFrame)!=1 ); rc = xUndo(pUndoCtx, walFramePgno(pWal, iFrame)); } if( iMax!=pWal->hdr.mxFrame ) walCleanupHash(pWal); } return rc; } /* ** Argument aWalData must point to an array of WAL_SAVEPOINT_NDATA u32 ** values. This function populates the array with values required to ** "rollback" the write position of the WAL handle back to the current ** point in the event of a savepoint rollback (via WalSavepointUndo()). */ SQLITE_PRIVATE void sqlite3WalSavepoint(Wal *pWal, u32 *aWalData){ assert( pWal->writeLock ); aWalData[0] = pWal->hdr.mxFrame; aWalData[1] = pWal->hdr.aFrameCksum[0]; aWalData[2] = pWal->hdr.aFrameCksum[1]; aWalData[3] = pWal->nCkpt; } /* ** Move the write position of the WAL back to the point identified by ** the values in the aWalData[] array. aWalData must point to an array ** of WAL_SAVEPOINT_NDATA u32 values that has been previously populated ** by a call to WalSavepoint(). */ SQLITE_PRIVATE int sqlite3WalSavepointUndo(Wal *pWal, u32 *aWalData){ int rc = SQLITE_OK; assert( pWal->writeLock ); assert( aWalData[3]!=pWal->nCkpt || aWalData[0]<=pWal->hdr.mxFrame ); if( aWalData[3]!=pWal->nCkpt ){ /* This savepoint was opened immediately after the write-transaction ** was started. Right after that, the writer decided to wrap around ** to the start of the log. Update the savepoint values to match. */ aWalData[0] = 0; aWalData[3] = pWal->nCkpt; } if( aWalData[0]hdr.mxFrame ){ pWal->hdr.mxFrame = aWalData[0]; pWal->hdr.aFrameCksum[0] = aWalData[1]; pWal->hdr.aFrameCksum[1] = aWalData[2]; walCleanupHash(pWal); } return rc; } /* ** This function is called just before writing a set of frames to the log ** file (see sqlite3WalFrames()). It checks to see if, instead of appending ** to the current log file, it is possible to overwrite the start of the ** existing log file with the new frames (i.e. "reset" the log). If so, ** it sets pWal->hdr.mxFrame to 0. Otherwise, pWal->hdr.mxFrame is left ** unchanged. ** ** SQLITE_OK is returned if no error is encountered (regardless of whether ** or not pWal->hdr.mxFrame is modified). An SQLite error code is returned ** if an error occurs. */ static int walRestartLog(Wal *pWal){ int rc = SQLITE_OK; int cnt; if( pWal->readLock==0 ){ volatile WalCkptInfo *pInfo = walCkptInfo(pWal); assert( pInfo->nBackfill==pWal->hdr.mxFrame ); if( pInfo->nBackfill>0 ){ u32 salt1; sqlite3_randomness(4, &salt1); rc = walLockExclusive(pWal, WAL_READ_LOCK(1), WAL_NREADER-1); if( rc==SQLITE_OK ){ /* If all readers are using WAL_READ_LOCK(0) (in other words if no ** readers are currently using the WAL), then the transactions ** frames will overwrite the start of the existing log. Update the ** wal-index header to reflect this. ** ** In theory it would be Ok to update the cache of the header only ** at this point. But updating the actual wal-index header is also ** safe and means there is no special case for sqlite3WalUndo() ** to handle if this transaction is rolled back. */ walRestartHdr(pWal, salt1); walUnlockExclusive(pWal, WAL_READ_LOCK(1), WAL_NREADER-1); }else if( rc!=SQLITE_BUSY ){ return rc; } } walUnlockShared(pWal, WAL_READ_LOCK(0)); pWal->readLock = -1; cnt = 0; do{ int notUsed; rc = walTryBeginRead(pWal, ¬Used, 1, ++cnt); }while( rc==WAL_RETRY ); assert( (rc&0xff)!=SQLITE_BUSY ); /* BUSY not possible when useWal==1 */ testcase( (rc&0xff)==SQLITE_IOERR ); testcase( rc==SQLITE_PROTOCOL ); testcase( rc==SQLITE_OK ); } return rc; } /* ** Information about the current state of the WAL file and where ** the next fsync should occur - passed from sqlite3WalFrames() into ** walWriteToLog(). */ typedef struct WalWriter { Wal *pWal; /* The complete WAL information */ sqlite3_file *pFd; /* The WAL file to which we write */ sqlite3_int64 iSyncPoint; /* Fsync at this offset */ int syncFlags; /* Flags for the fsync */ int szPage; /* Size of one page */ } WalWriter; /* ** Write iAmt bytes of content into the WAL file beginning at iOffset. ** Do a sync when crossing the p->iSyncPoint boundary. ** ** In other words, if iSyncPoint is in between iOffset and iOffset+iAmt, ** first write the part before iSyncPoint, then sync, then write the ** rest. */ static int walWriteToLog( WalWriter *p, /* WAL to write to */ void *pContent, /* Content to be written */ int iAmt, /* Number of bytes to write */ sqlite3_int64 iOffset /* Start writing at this offset */ ){ int rc; if( iOffsetiSyncPoint && iOffset+iAmt>=p->iSyncPoint ){ int iFirstAmt = (int)(p->iSyncPoint - iOffset); rc = sqlite3OsWrite(p->pFd, pContent, iFirstAmt, iOffset); if( rc ) return rc; iOffset += iFirstAmt; iAmt -= iFirstAmt; pContent = (void*)(iFirstAmt + (char*)pContent); assert( p->syncFlags & (SQLITE_SYNC_NORMAL|SQLITE_SYNC_FULL) ); rc = sqlite3OsSync(p->pFd, p->syncFlags & SQLITE_SYNC_MASK); if( iAmt==0 || rc ) return rc; } rc = sqlite3OsWrite(p->pFd, pContent, iAmt, iOffset); return rc; } /* ** Write out a single frame of the WAL */ static int walWriteOneFrame( WalWriter *p, /* Where to write the frame */ PgHdr *pPage, /* The page of the frame to be written */ int nTruncate, /* The commit flag. Usually 0. >0 for commit */ sqlite3_int64 iOffset /* Byte offset at which to write */ ){ int rc; /* Result code from subfunctions */ void *pData; /* Data actually written */ u8 aFrame[WAL_FRAME_HDRSIZE]; /* Buffer to assemble frame-header in */ #if defined(SQLITE_HAS_CODEC) if( (pData = sqlite3PagerCodec(pPage))==0 ) return SQLITE_NOMEM_BKPT; #else pData = pPage->pData; #endif walEncodeFrame(p->pWal, pPage->pgno, nTruncate, pData, aFrame); rc = walWriteToLog(p, aFrame, sizeof(aFrame), iOffset); if( rc ) return rc; /* Write the page data */ rc = walWriteToLog(p, pData, p->szPage, iOffset+sizeof(aFrame)); return rc; } /* ** This function is called as part of committing a transaction within which ** one or more frames have been overwritten. It updates the checksums for ** all frames written to the wal file by the current transaction starting ** with the earliest to have been overwritten. ** ** SQLITE_OK is returned if successful, or an SQLite error code otherwise. */ static int walRewriteChecksums(Wal *pWal, u32 iLast){ const int szPage = pWal->szPage;/* Database page size */ int rc = SQLITE_OK; /* Return code */ u8 *aBuf; /* Buffer to load data from wal file into */ u8 aFrame[WAL_FRAME_HDRSIZE]; /* Buffer to assemble frame-headers in */ u32 iRead; /* Next frame to read from wal file */ i64 iCksumOff; aBuf = sqlite3_malloc(szPage + WAL_FRAME_HDRSIZE); if( aBuf==0 ) return SQLITE_NOMEM_BKPT; /* Find the checksum values to use as input for the recalculating the ** first checksum. If the first frame is frame 1 (implying that the current ** transaction restarted the wal file), these values must be read from the ** wal-file header. Otherwise, read them from the frame header of the ** previous frame. */ assert( pWal->iReCksum>0 ); if( pWal->iReCksum==1 ){ iCksumOff = 24; }else{ iCksumOff = walFrameOffset(pWal->iReCksum-1, szPage) + 16; } rc = sqlite3OsRead(pWal->pWalFd, aBuf, sizeof(u32)*2, iCksumOff); pWal->hdr.aFrameCksum[0] = sqlite3Get4byte(aBuf); pWal->hdr.aFrameCksum[1] = sqlite3Get4byte(&aBuf[sizeof(u32)]); iRead = pWal->iReCksum; pWal->iReCksum = 0; for(; rc==SQLITE_OK && iRead<=iLast; iRead++){ i64 iOff = walFrameOffset(iRead, szPage); rc = sqlite3OsRead(pWal->pWalFd, aBuf, szPage+WAL_FRAME_HDRSIZE, iOff); if( rc==SQLITE_OK ){ u32 iPgno, nDbSize; iPgno = sqlite3Get4byte(aBuf); nDbSize = sqlite3Get4byte(&aBuf[4]); walEncodeFrame(pWal, iPgno, nDbSize, &aBuf[WAL_FRAME_HDRSIZE], aFrame); rc = sqlite3OsWrite(pWal->pWalFd, aFrame, sizeof(aFrame), iOff); } } sqlite3_free(aBuf); return rc; } /* ** Write a set of frames to the log. The caller must hold the write-lock ** on the log file (obtained using sqlite3WalBeginWriteTransaction()). */ SQLITE_PRIVATE int sqlite3WalFrames( Wal *pWal, /* Wal handle to write to */ int szPage, /* Database page-size in bytes */ PgHdr *pList, /* List of dirty pages to write */ Pgno nTruncate, /* Database size after this commit */ int isCommit, /* True if this is a commit */ int sync_flags /* Flags to pass to OsSync() (or 0) */ ){ int rc; /* Used to catch return codes */ u32 iFrame; /* Next frame address */ PgHdr *p; /* Iterator to run through pList with. */ PgHdr *pLast = 0; /* Last frame in list */ int nExtra = 0; /* Number of extra copies of last page */ int szFrame; /* The size of a single frame */ i64 iOffset; /* Next byte to write in WAL file */ WalWriter w; /* The writer */ u32 iFirst = 0; /* First frame that may be overwritten */ WalIndexHdr *pLive; /* Pointer to shared header */ assert( pList ); assert( pWal->writeLock ); /* If this frame set completes a transaction, then nTruncate>0. If ** nTruncate==0 then this frame set does not complete the transaction. */ assert( (isCommit!=0)==(nTruncate!=0) ); #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG) { int cnt; for(cnt=0, p=pList; p; p=p->pDirty, cnt++){} WALTRACE(("WAL%p: frame write begin. %d frames. mxFrame=%d. %s\n", pWal, cnt, pWal->hdr.mxFrame, isCommit ? "Commit" : "Spill")); } #endif pLive = (WalIndexHdr*)walIndexHdr(pWal); if( memcmp(&pWal->hdr, (void *)pLive, sizeof(WalIndexHdr))!=0 ){ iFirst = pLive->mxFrame+1; } /* See if it is possible to write these frames into the start of the ** log file, instead of appending to it at pWal->hdr.mxFrame. */ if( SQLITE_OK!=(rc = walRestartLog(pWal)) ){ return rc; } /* If this is the first frame written into the log, write the WAL ** header to the start of the WAL file. See comments at the top of ** this source file for a description of the WAL header format. */ iFrame = pWal->hdr.mxFrame; if( iFrame==0 ){ u8 aWalHdr[WAL_HDRSIZE]; /* Buffer to assemble wal-header in */ u32 aCksum[2]; /* Checksum for wal-header */ sqlite3Put4byte(&aWalHdr[0], (WAL_MAGIC | SQLITE_BIGENDIAN)); sqlite3Put4byte(&aWalHdr[4], WAL_MAX_VERSION); sqlite3Put4byte(&aWalHdr[8], szPage); sqlite3Put4byte(&aWalHdr[12], pWal->nCkpt); if( pWal->nCkpt==0 ) sqlite3_randomness(8, pWal->hdr.aSalt); memcpy(&aWalHdr[16], pWal->hdr.aSalt, 8); walChecksumBytes(1, aWalHdr, WAL_HDRSIZE-2*4, 0, aCksum); sqlite3Put4byte(&aWalHdr[24], aCksum[0]); sqlite3Put4byte(&aWalHdr[28], aCksum[1]); pWal->szPage = szPage; pWal->hdr.bigEndCksum = SQLITE_BIGENDIAN; pWal->hdr.aFrameCksum[0] = aCksum[0]; pWal->hdr.aFrameCksum[1] = aCksum[1]; pWal->truncateOnCommit = 1; rc = sqlite3OsWrite(pWal->pWalFd, aWalHdr, sizeof(aWalHdr), 0); WALTRACE(("WAL%p: wal-header write %s\n", pWal, rc ? "failed" : "ok")); if( rc!=SQLITE_OK ){ return rc; } /* Sync the header (unless SQLITE_IOCAP_SEQUENTIAL is true or unless ** all syncing is turned off by PRAGMA synchronous=OFF). Otherwise ** an out-of-order write following a WAL restart could result in ** database corruption. See the ticket: ** ** http://localhost:591/sqlite/info/ff5be73dee */ if( pWal->syncHeader && sync_flags ){ rc = sqlite3OsSync(pWal->pWalFd, sync_flags & SQLITE_SYNC_MASK); if( rc ) return rc; } } assert( (int)pWal->szPage==szPage ); /* Setup information needed to write frames into the WAL */ w.pWal = pWal; w.pFd = pWal->pWalFd; w.iSyncPoint = 0; w.syncFlags = sync_flags; w.szPage = szPage; iOffset = walFrameOffset(iFrame+1, szPage); szFrame = szPage + WAL_FRAME_HDRSIZE; /* Write all frames into the log file exactly once */ for(p=pList; p; p=p->pDirty){ int nDbSize; /* 0 normally. Positive == commit flag */ /* Check if this page has already been written into the wal file by ** the current transaction. If so, overwrite the existing frame and ** set Wal.writeLock to WAL_WRITELOCK_RECKSUM - indicating that ** checksums must be recomputed when the transaction is committed. */ if( iFirst && (p->pDirty || isCommit==0) ){ u32 iWrite = 0; VVA_ONLY(rc =) sqlite3WalFindFrame(pWal, p->pgno, &iWrite); assert( rc==SQLITE_OK || iWrite==0 ); if( iWrite>=iFirst ){ i64 iOff = walFrameOffset(iWrite, szPage) + WAL_FRAME_HDRSIZE; void *pData; if( pWal->iReCksum==0 || iWriteiReCksum ){ pWal->iReCksum = iWrite; } #if defined(SQLITE_HAS_CODEC) if( (pData = sqlite3PagerCodec(p))==0 ) return SQLITE_NOMEM; #else pData = p->pData; #endif rc = sqlite3OsWrite(pWal->pWalFd, pData, szPage, iOff); if( rc ) return rc; p->flags &= ~PGHDR_WAL_APPEND; continue; } } iFrame++; assert( iOffset==walFrameOffset(iFrame, szPage) ); nDbSize = (isCommit && p->pDirty==0) ? nTruncate : 0; rc = walWriteOneFrame(&w, p, nDbSize, iOffset); if( rc ) return rc; pLast = p; iOffset += szFrame; p->flags |= PGHDR_WAL_APPEND; } /* Recalculate checksums within the wal file if required. */ if( isCommit && pWal->iReCksum ){ rc = walRewriteChecksums(pWal, iFrame); if( rc ) return rc; } /* If this is the end of a transaction, then we might need to pad ** the transaction and/or sync the WAL file. ** ** Padding and syncing only occur if this set of frames complete a ** transaction and if PRAGMA synchronous=FULL. If synchronous==NORMAL ** or synchronous==OFF, then no padding or syncing are needed. ** ** If SQLITE_IOCAP_POWERSAFE_OVERWRITE is defined, then padding is not ** needed and only the sync is done. If padding is needed, then the ** final frame is repeated (with its commit mark) until the next sector ** boundary is crossed. Only the part of the WAL prior to the last ** sector boundary is synced; the part of the last frame that extends ** past the sector boundary is written after the sync. */ if( isCommit && (sync_flags & WAL_SYNC_TRANSACTIONS)!=0 ){ int bSync = 1; if( pWal->padToSectorBoundary ){ int sectorSize = sqlite3SectorSize(pWal->pWalFd); w.iSyncPoint = ((iOffset+sectorSize-1)/sectorSize)*sectorSize; bSync = (w.iSyncPoint==iOffset); testcase( bSync ); while( iOffsettruncateOnCommit && pWal->mxWalSize>=0 ){ i64 sz = pWal->mxWalSize; if( walFrameOffset(iFrame+nExtra+1, szPage)>pWal->mxWalSize ){ sz = walFrameOffset(iFrame+nExtra+1, szPage); } walLimitSize(pWal, sz); pWal->truncateOnCommit = 0; } /* Append data to the wal-index. It is not necessary to lock the ** wal-index to do this as the SQLITE_SHM_WRITE lock held on the wal-index ** guarantees that there are no other writers, and no data that may ** be in use by existing readers is being overwritten. */ iFrame = pWal->hdr.mxFrame; for(p=pList; p && rc==SQLITE_OK; p=p->pDirty){ if( (p->flags & PGHDR_WAL_APPEND)==0 ) continue; iFrame++; rc = walIndexAppend(pWal, iFrame, p->pgno); } while( rc==SQLITE_OK && nExtra>0 ){ iFrame++; nExtra--; rc = walIndexAppend(pWal, iFrame, pLast->pgno); } if( rc==SQLITE_OK ){ /* Update the private copy of the header. */ pWal->hdr.szPage = (u16)((szPage&0xff00) | (szPage>>16)); testcase( szPage<=32768 ); testcase( szPage>=65536 ); pWal->hdr.mxFrame = iFrame; if( isCommit ){ pWal->hdr.iChange++; pWal->hdr.nPage = nTruncate; } /* If this is a commit, update the wal-index header too. */ if( isCommit ){ walIndexWriteHdr(pWal); pWal->iCallback = iFrame; } } WALTRACE(("WAL%p: frame write %s\n", pWal, rc ? "failed" : "ok")); return rc; } /* ** This routine is called to implement sqlite3_wal_checkpoint() and ** related interfaces. ** ** Obtain a CHECKPOINT lock and then backfill as much information as ** we can from WAL into the database. ** ** If parameter xBusy is not NULL, it is a pointer to a busy-handler ** callback. In this case this function runs a blocking checkpoint. */ SQLITE_PRIVATE int sqlite3WalCheckpoint( Wal *pWal, /* Wal connection */ int eMode, /* PASSIVE, FULL, RESTART, or TRUNCATE */ int (*xBusy)(void*), /* Function to call when busy */ void *pBusyArg, /* Context argument for xBusyHandler */ int sync_flags, /* Flags to sync db file with (or 0) */ int nBuf, /* Size of temporary buffer */ u8 *zBuf, /* Temporary buffer to use */ int *pnLog, /* OUT: Number of frames in WAL */ int *pnCkpt /* OUT: Number of backfilled frames in WAL */ ){ int rc; /* Return code */ int isChanged = 0; /* True if a new wal-index header is loaded */ int eMode2 = eMode; /* Mode to pass to walCheckpoint() */ int (*xBusy2)(void*) = xBusy; /* Busy handler for eMode2 */ assert( pWal->ckptLock==0 ); assert( pWal->writeLock==0 ); /* EVIDENCE-OF: R-62920-47450 The busy-handler callback is never invoked ** in the SQLITE_CHECKPOINT_PASSIVE mode. */ assert( eMode!=SQLITE_CHECKPOINT_PASSIVE || xBusy==0 ); if( pWal->readOnly ) return SQLITE_READONLY; WALTRACE(("WAL%p: checkpoint begins\n", pWal)); /* IMPLEMENTATION-OF: R-62028-47212 All calls obtain an exclusive ** "checkpoint" lock on the database file. */ rc = walLockExclusive(pWal, WAL_CKPT_LOCK, 1); if( rc ){ /* EVIDENCE-OF: R-10421-19736 If any other process is running a ** checkpoint operation at the same time, the lock cannot be obtained and ** SQLITE_BUSY is returned. ** EVIDENCE-OF: R-53820-33897 Even if there is a busy-handler configured, ** it will not be invoked in this case. */ testcase( rc==SQLITE_BUSY ); testcase( xBusy!=0 ); return rc; } pWal->ckptLock = 1; /* IMPLEMENTATION-OF: R-59782-36818 The SQLITE_CHECKPOINT_FULL, RESTART and ** TRUNCATE modes also obtain the exclusive "writer" lock on the database ** file. ** ** EVIDENCE-OF: R-60642-04082 If the writer lock cannot be obtained ** immediately, and a busy-handler is configured, it is invoked and the ** writer lock retried until either the busy-handler returns 0 or the ** lock is successfully obtained. */ if( eMode!=SQLITE_CHECKPOINT_PASSIVE ){ rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_WRITE_LOCK, 1); if( rc==SQLITE_OK ){ pWal->writeLock = 1; }else if( rc==SQLITE_BUSY ){ eMode2 = SQLITE_CHECKPOINT_PASSIVE; xBusy2 = 0; rc = SQLITE_OK; } } /* Read the wal-index header. */ if( rc==SQLITE_OK ){ rc = walIndexReadHdr(pWal, &isChanged); if( isChanged && pWal->pDbFd->pMethods->iVersion>=3 ){ sqlite3OsUnfetch(pWal->pDbFd, 0, 0); } } /* Copy data from the log to the database file. */ if( rc==SQLITE_OK ){ if( pWal->hdr.mxFrame && walPagesize(pWal)!=nBuf ){ rc = SQLITE_CORRUPT_BKPT; }else{ rc = walCheckpoint(pWal, eMode2, xBusy2, pBusyArg, sync_flags, zBuf); } /* If no error occurred, set the output variables. */ if( rc==SQLITE_OK || rc==SQLITE_BUSY ){ if( pnLog ) *pnLog = (int)pWal->hdr.mxFrame; if( pnCkpt ) *pnCkpt = (int)(walCkptInfo(pWal)->nBackfill); } } if( isChanged ){ /* If a new wal-index header was loaded before the checkpoint was ** performed, then the pager-cache associated with pWal is now ** out of date. So zero the cached wal-index header to ensure that ** next time the pager opens a snapshot on this database it knows that ** the cache needs to be reset. */ memset(&pWal->hdr, 0, sizeof(WalIndexHdr)); } /* Release the locks. */ sqlite3WalEndWriteTransaction(pWal); walUnlockExclusive(pWal, WAL_CKPT_LOCK, 1); pWal->ckptLock = 0; WALTRACE(("WAL%p: checkpoint %s\n", pWal, rc ? "failed" : "ok")); return (rc==SQLITE_OK && eMode!=eMode2 ? SQLITE_BUSY : rc); } /* Return the value to pass to a sqlite3_wal_hook callback, the ** number of frames in the WAL at the point of the last commit since ** sqlite3WalCallback() was called. If no commits have occurred since ** the last call, then return 0. */ SQLITE_PRIVATE int sqlite3WalCallback(Wal *pWal){ u32 ret = 0; if( pWal ){ ret = pWal->iCallback; pWal->iCallback = 0; } return (int)ret; } /* ** This function is called to change the WAL subsystem into or out ** of locking_mode=EXCLUSIVE. ** ** If op is zero, then attempt to change from locking_mode=EXCLUSIVE ** into locking_mode=NORMAL. This means that we must acquire a lock ** on the pWal->readLock byte. If the WAL is already in locking_mode=NORMAL ** or if the acquisition of the lock fails, then return 0. If the ** transition out of exclusive-mode is successful, return 1. This ** operation must occur while the pager is still holding the exclusive ** lock on the main database file. ** ** If op is one, then change from locking_mode=NORMAL into ** locking_mode=EXCLUSIVE. This means that the pWal->readLock must ** be released. Return 1 if the transition is made and 0 if the ** WAL is already in exclusive-locking mode - meaning that this ** routine is a no-op. The pager must already hold the exclusive lock ** on the main database file before invoking this operation. ** ** If op is negative, then do a dry-run of the op==1 case but do ** not actually change anything. The pager uses this to see if it ** should acquire the database exclusive lock prior to invoking ** the op==1 case. */ SQLITE_PRIVATE int sqlite3WalExclusiveMode(Wal *pWal, int op){ int rc; assert( pWal->writeLock==0 ); assert( pWal->exclusiveMode!=WAL_HEAPMEMORY_MODE || op==-1 ); /* pWal->readLock is usually set, but might be -1 if there was a ** prior error while attempting to acquire are read-lock. This cannot ** happen if the connection is actually in exclusive mode (as no xShmLock ** locks are taken in this case). Nor should the pager attempt to ** upgrade to exclusive-mode following such an error. */ assert( pWal->readLock>=0 || pWal->lockError ); assert( pWal->readLock>=0 || (op<=0 && pWal->exclusiveMode==0) ); if( op==0 ){ if( pWal->exclusiveMode ){ pWal->exclusiveMode = 0; if( walLockShared(pWal, WAL_READ_LOCK(pWal->readLock))!=SQLITE_OK ){ pWal->exclusiveMode = 1; } rc = pWal->exclusiveMode==0; }else{ /* Already in locking_mode=NORMAL */ rc = 0; } }else if( op>0 ){ assert( pWal->exclusiveMode==0 ); assert( pWal->readLock>=0 ); walUnlockShared(pWal, WAL_READ_LOCK(pWal->readLock)); pWal->exclusiveMode = 1; rc = 1; }else{ rc = pWal->exclusiveMode==0; } return rc; } /* ** Return true if the argument is non-NULL and the WAL module is using ** heap-memory for the wal-index. Otherwise, if the argument is NULL or the ** WAL module is using shared-memory, return false. */ SQLITE_PRIVATE int sqlite3WalHeapMemory(Wal *pWal){ return (pWal && pWal->exclusiveMode==WAL_HEAPMEMORY_MODE ); } #ifdef SQLITE_ENABLE_SNAPSHOT /* Create a snapshot object. The content of a snapshot is opaque to ** every other subsystem, so the WAL module can put whatever it needs ** in the object. */ SQLITE_PRIVATE int sqlite3WalSnapshotGet(Wal *pWal, sqlite3_snapshot **ppSnapshot){ int rc = SQLITE_OK; WalIndexHdr *pRet; assert( pWal->readLock>=0 && pWal->writeLock==0 ); pRet = (WalIndexHdr*)sqlite3_malloc(sizeof(WalIndexHdr)); if( pRet==0 ){ rc = SQLITE_NOMEM_BKPT; }else{ memcpy(pRet, &pWal->hdr, sizeof(WalIndexHdr)); *ppSnapshot = (sqlite3_snapshot*)pRet; } return rc; } /* Try to open on pSnapshot when the next read-transaction starts */ SQLITE_PRIVATE void sqlite3WalSnapshotOpen(Wal *pWal, sqlite3_snapshot *pSnapshot){ pWal->pSnapshot = (WalIndexHdr*)pSnapshot; } /* ** Return a +ve value if snapshot p1 is newer than p2. A -ve value if ** p1 is older than p2 and zero if p1 and p2 are the same snapshot. */ SQLITE_API int sqlite3_snapshot_cmp(sqlite3_snapshot *p1, sqlite3_snapshot *p2){ WalIndexHdr *pHdr1 = (WalIndexHdr*)p1; WalIndexHdr *pHdr2 = (WalIndexHdr*)p2; /* aSalt[0] is a copy of the value stored in the wal file header. It ** is incremented each time the wal file is restarted. */ if( pHdr1->aSalt[0]aSalt[0] ) return -1; if( pHdr1->aSalt[0]>pHdr2->aSalt[0] ) return +1; if( pHdr1->mxFramemxFrame ) return -1; if( pHdr1->mxFrame>pHdr2->mxFrame ) return +1; return 0; } #endif /* SQLITE_ENABLE_SNAPSHOT */ #ifdef SQLITE_ENABLE_ZIPVFS /* ** If the argument is not NULL, it points to a Wal object that holds a ** read-lock. This function returns the database page-size if it is known, ** or zero if it is not (or if pWal is NULL). */ SQLITE_PRIVATE int sqlite3WalFramesize(Wal *pWal){ assert( pWal==0 || pWal->readLock>=0 ); return (pWal ? pWal->szPage : 0); } #endif /* Return the sqlite3_file object for the WAL file */ SQLITE_PRIVATE sqlite3_file *sqlite3WalFile(Wal *pWal){ return pWal->pWalFd; } #endif /* #ifndef SQLITE_OMIT_WAL */ /************** End of wal.c *************************************************/ /************** Begin file btmutex.c *****************************************/ /* ** 2007 August 27 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ************************************************************************* ** ** This file contains code used to implement mutexes on Btree objects. ** This code really belongs in btree.c. But btree.c is getting too ** big and we want to break it down some. This packaged seemed like ** a good breakout. */ /************** Include btreeInt.h in the middle of btmutex.c ****************/ /************** Begin file btreeInt.h ****************************************/ /* ** 2004 April 6 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ************************************************************************* ** This file implements an external (disk-based) database using BTrees. ** For a detailed discussion of BTrees, refer to ** ** Donald E. Knuth, THE ART OF COMPUTER PROGRAMMING, Volume 3: ** "Sorting And Searching", pages 473-480. Addison-Wesley ** Publishing Company, Reading, Massachusetts. ** ** The basic idea is that each page of the file contains N database ** entries and N+1 pointers to subpages. ** ** ---------------------------------------------------------------- ** | Ptr(0) | Key(0) | Ptr(1) | Key(1) | ... | Key(N-1) | Ptr(N) | ** ---------------------------------------------------------------- ** ** All of the keys on the page that Ptr(0) points to have values less ** than Key(0). All of the keys on page Ptr(1) and its subpages have ** values greater than Key(0) and less than Key(1). All of the keys ** on Ptr(N) and its subpages have values greater than Key(N-1). And ** so forth. ** ** Finding a particular key requires reading O(log(M)) pages from the ** disk where M is the number of entries in the tree. ** ** In this implementation, a single file can hold one or more separate ** BTrees. Each BTree is identified by the index of its root page. The ** key and data for any entry are combined to form the "payload". A ** fixed amount of payload can be carried directly on the database ** page. If the payload is larger than the preset amount then surplus ** bytes are stored on overflow pages. The payload for an entry ** and the preceding pointer are combined to form a "Cell". Each ** page has a small header which contains the Ptr(N) pointer and other ** information such as the size of key and data. ** ** FORMAT DETAILS ** ** The file is divided into pages. The first page is called page 1, ** the second is page 2, and so forth. A page number of zero indicates ** "no such page". The page size can be any power of 2 between 512 and 65536. ** Each page can be either a btree page, a freelist page, an overflow ** page, or a pointer-map page. ** ** The first page is always a btree page. The first 100 bytes of the first ** page contain a special header (the "file header") that describes the file. ** The format of the file header is as follows: ** ** OFFSET SIZE DESCRIPTION ** 0 16 Header string: "SQLite format 3\000" ** 16 2 Page size in bytes. (1 means 65536) ** 18 1 File format write version ** 19 1 File format read version ** 20 1 Bytes of unused space at the end of each page ** 21 1 Max embedded payload fraction (must be 64) ** 22 1 Min embedded payload fraction (must be 32) ** 23 1 Min leaf payload fraction (must be 32) ** 24 4 File change counter ** 28 4 Reserved for future use ** 32 4 First freelist page ** 36 4 Number of freelist pages in the file ** 40 60 15 4-byte meta values passed to higher layers ** ** 40 4 Schema cookie ** 44 4 File format of schema layer ** 48 4 Size of page cache ** 52 4 Largest root-page (auto/incr_vacuum) ** 56 4 1=UTF-8 2=UTF16le 3=UTF16be ** 60 4 User version ** 64 4 Incremental vacuum mode ** 68 4 Application-ID ** 72 20 unused ** 92 4 The version-valid-for number ** 96 4 SQLITE_VERSION_NUMBER ** ** All of the integer values are big-endian (most significant byte first). ** ** The file change counter is incremented when the database is changed ** This counter allows other processes to know when the file has changed ** and thus when they need to flush their cache. ** ** The max embedded payload fraction is the amount of the total usable ** space in a page that can be consumed by a single cell for standard ** B-tree (non-LEAFDATA) tables. A value of 255 means 100%. The default ** is to limit the maximum cell size so that at least 4 cells will fit ** on one page. Thus the default max embedded payload fraction is 64. ** ** If the payload for a cell is larger than the max payload, then extra ** payload is spilled to overflow pages. Once an overflow page is allocated, ** as many bytes as possible are moved into the overflow pages without letting ** the cell size drop below the min embedded payload fraction. ** ** The min leaf payload fraction is like the min embedded payload fraction ** except that it applies to leaf nodes in a LEAFDATA tree. The maximum ** payload fraction for a LEAFDATA tree is always 100% (or 255) and it ** not specified in the header. ** ** Each btree pages is divided into three sections: The header, the ** cell pointer array, and the cell content area. Page 1 also has a 100-byte ** file header that occurs before the page header. ** ** |----------------| ** | file header | 100 bytes. Page 1 only. ** |----------------| ** | page header | 8 bytes for leaves. 12 bytes for interior nodes ** |----------------| ** | cell pointer | | 2 bytes per cell. Sorted order. ** | array | | Grows downward ** | | v ** |----------------| ** | unallocated | ** | space | ** |----------------| ^ Grows upwards ** | cell content | | Arbitrary order interspersed with freeblocks. ** | area | | and free space fragments. ** |----------------| ** ** The page headers looks like this: ** ** OFFSET SIZE DESCRIPTION ** 0 1 Flags. 1: intkey, 2: zerodata, 4: leafdata, 8: leaf ** 1 2 byte offset to the first freeblock ** 3 2 number of cells on this page ** 5 2 first byte of the cell content area ** 7 1 number of fragmented free bytes ** 8 4 Right child (the Ptr(N) value). Omitted on leaves. ** ** The flags define the format of this btree page. The leaf flag means that ** this page has no children. The zerodata flag means that this page carries ** only keys and no data. The intkey flag means that the key is an integer ** which is stored in the key size entry of the cell header rather than in ** the payload area. ** ** The cell pointer array begins on the first byte after the page header. ** The cell pointer array contains zero or more 2-byte numbers which are ** offsets from the beginning of the page to the cell content in the cell ** content area. The cell pointers occur in sorted order. The system strives ** to keep free space after the last cell pointer so that new cells can ** be easily added without having to defragment the page. ** ** Cell content is stored at the very end of the page and grows toward the ** beginning of the page. ** ** Unused space within the cell content area is collected into a linked list of ** freeblocks. Each freeblock is at least 4 bytes in size. The byte offset ** to the first freeblock is given in the header. Freeblocks occur in ** increasing order. Because a freeblock must be at least 4 bytes in size, ** any group of 3 or fewer unused bytes in the cell content area cannot ** exist on the freeblock chain. A group of 3 or fewer free bytes is called ** a fragment. The total number of bytes in all fragments is recorded. ** in the page header at offset 7. ** ** SIZE DESCRIPTION ** 2 Byte offset of the next freeblock ** 2 Bytes in this freeblock ** ** Cells are of variable length. Cells are stored in the cell content area at ** the end of the page. Pointers to the cells are in the cell pointer array ** that immediately follows the page header. Cells is not necessarily ** contiguous or in order, but cell pointers are contiguous and in order. ** ** Cell content makes use of variable length integers. A variable ** length integer is 1 to 9 bytes where the lower 7 bits of each ** byte are used. The integer consists of all bytes that have bit 8 set and ** the first byte with bit 8 clear. The most significant byte of the integer ** appears first. A variable-length integer may not be more than 9 bytes long. ** As a special case, all 8 bytes of the 9th byte are used as data. This ** allows a 64-bit integer to be encoded in 9 bytes. ** ** 0x00 becomes 0x00000000 ** 0x7f becomes 0x0000007f ** 0x81 0x00 becomes 0x00000080 ** 0x82 0x00 becomes 0x00000100 ** 0x80 0x7f becomes 0x0000007f ** 0x8a 0x91 0xd1 0xac 0x78 becomes 0x12345678 ** 0x81 0x81 0x81 0x81 0x01 becomes 0x10204081 ** ** Variable length integers are used for rowids and to hold the number of ** bytes of key and data in a btree cell. ** ** The content of a cell looks like this: ** ** SIZE DESCRIPTION ** 4 Page number of the left child. Omitted if leaf flag is set. ** var Number of bytes of data. Omitted if the zerodata flag is set. ** var Number of bytes of key. Or the key itself if intkey flag is set. ** * Payload ** 4 First page of the overflow chain. Omitted if no overflow ** ** Overflow pages form a linked list. Each page except the last is completely ** filled with data (pagesize - 4 bytes). The last page can have as little ** as 1 byte of data. ** ** SIZE DESCRIPTION ** 4 Page number of next overflow page ** * Data ** ** Freelist pages come in two subtypes: trunk pages and leaf pages. The ** file header points to the first in a linked list of trunk page. Each trunk ** page points to multiple leaf pages. The content of a leaf page is ** unspecified. A trunk page looks like this: ** ** SIZE DESCRIPTION ** 4 Page number of next trunk page ** 4 Number of leaf pointers on this page ** * zero or more pages numbers of leaves */ /* #include "sqliteInt.h" */ /* The following value is the maximum cell size assuming a maximum page ** size give above. */ #define MX_CELL_SIZE(pBt) ((int)(pBt->pageSize-8)) /* The maximum number of cells on a single page of the database. This ** assumes a minimum cell size of 6 bytes (4 bytes for the cell itself ** plus 2 bytes for the index to the cell in the page header). Such ** small cells will be rare, but they are possible. */ #define MX_CELL(pBt) ((pBt->pageSize-8)/6) /* Forward declarations */ typedef struct MemPage MemPage; typedef struct BtLock BtLock; typedef struct CellInfo CellInfo; /* ** This is a magic string that appears at the beginning of every ** SQLite database in order to identify the file as a real database. ** ** You can change this value at compile-time by specifying a ** -DSQLITE_FILE_HEADER="..." on the compiler command-line. The ** header must be exactly 16 bytes including the zero-terminator so ** the string itself should be 15 characters long. If you change ** the header, then your custom library will not be able to read ** databases generated by the standard tools and the standard tools ** will not be able to read databases created by your custom library. */ #ifndef SQLITE_FILE_HEADER /* 123456789 123456 */ # define SQLITE_FILE_HEADER "SQLite format 3" #endif /* ** Page type flags. An ORed combination of these flags appear as the ** first byte of on-disk image of every BTree page. */ #define PTF_INTKEY 0x01 #define PTF_ZERODATA 0x02 #define PTF_LEAFDATA 0x04 #define PTF_LEAF 0x08 /* ** As each page of the file is loaded into memory, an instance of the following ** structure is appended and initialized to zero. This structure stores ** information about the page that is decoded from the raw file page. ** ** The pParent field points back to the parent page. This allows us to ** walk up the BTree from any leaf to the root. Care must be taken to ** unref() the parent page pointer when this page is no longer referenced. ** The pageDestructor() routine handles that chore. ** ** Access to all fields of this structure is controlled by the mutex ** stored in MemPage.pBt->mutex. */ struct MemPage { u8 isInit; /* True if previously initialized. MUST BE FIRST! */ u8 nOverflow; /* Number of overflow cell bodies in aCell[] */ u8 intKey; /* True if table b-trees. False for index b-trees */ u8 intKeyLeaf; /* True if the leaf of an intKey table */ u8 leaf; /* True if a leaf page */ u8 hdrOffset; /* 100 for page 1. 0 otherwise */ u8 childPtrSize; /* 0 if leaf==1. 4 if leaf==0 */ u8 max1bytePayload; /* min(maxLocal,127) */ u8 bBusy; /* Prevent endless loops on corrupt database files */ u16 maxLocal; /* Copy of BtShared.maxLocal or BtShared.maxLeaf */ u16 minLocal; /* Copy of BtShared.minLocal or BtShared.minLeaf */ u16 cellOffset; /* Index in aData of first cell pointer */ u16 nFree; /* Number of free bytes on the page */ u16 nCell; /* Number of cells on this page, local and ovfl */ u16 maskPage; /* Mask for page offset */ u16 aiOvfl[5]; /* Insert the i-th overflow cell before the aiOvfl-th ** non-overflow cell */ u8 *apOvfl[5]; /* Pointers to the body of overflow cells */ BtShared *pBt; /* Pointer to BtShared that this page is part of */ u8 *aData; /* Pointer to disk image of the page data */ u8 *aDataEnd; /* One byte past the end of usable data */ u8 *aCellIdx; /* The cell index area */ u8 *aDataOfst; /* Same as aData for leaves. aData+4 for interior */ DbPage *pDbPage; /* Pager page handle */ u16 (*xCellSize)(MemPage*,u8*); /* cellSizePtr method */ void (*xParseCell)(MemPage*,u8*,CellInfo*); /* btreeParseCell method */ Pgno pgno; /* Page number for this page */ }; /* ** The in-memory image of a disk page has the auxiliary information appended ** to the end. EXTRA_SIZE is the number of bytes of space needed to hold ** that extra information. */ #define EXTRA_SIZE sizeof(MemPage) /* ** A linked list of the following structures is stored at BtShared.pLock. ** Locks are added (or upgraded from READ_LOCK to WRITE_LOCK) when a cursor ** is opened on the table with root page BtShared.iTable. Locks are removed ** from this list when a transaction is committed or rolled back, or when ** a btree handle is closed. */ struct BtLock { Btree *pBtree; /* Btree handle holding this lock */ Pgno iTable; /* Root page of table */ u8 eLock; /* READ_LOCK or WRITE_LOCK */ BtLock *pNext; /* Next in BtShared.pLock list */ }; /* Candidate values for BtLock.eLock */ #define READ_LOCK 1 #define WRITE_LOCK 2 /* A Btree handle ** ** A database connection contains a pointer to an instance of ** this object for every database file that it has open. This structure ** is opaque to the database connection. The database connection cannot ** see the internals of this structure and only deals with pointers to ** this structure. ** ** For some database files, the same underlying database cache might be ** shared between multiple connections. In that case, each connection ** has it own instance of this object. But each instance of this object ** points to the same BtShared object. The database cache and the ** schema associated with the database file are all contained within ** the BtShared object. ** ** All fields in this structure are accessed under sqlite3.mutex. ** The pBt pointer itself may not be changed while there exists cursors ** in the referenced BtShared that point back to this Btree since those ** cursors have to go through this Btree to find their BtShared and ** they often do so without holding sqlite3.mutex. */ struct Btree { sqlite3 *db; /* The database connection holding this btree */ BtShared *pBt; /* Sharable content of this btree */ u8 inTrans; /* TRANS_NONE, TRANS_READ or TRANS_WRITE */ u8 sharable; /* True if we can share pBt with another db */ u8 locked; /* True if db currently has pBt locked */ u8 hasIncrblobCur; /* True if there are one or more Incrblob cursors */ int wantToLock; /* Number of nested calls to sqlite3BtreeEnter() */ int nBackup; /* Number of backup operations reading this btree */ u32 iDataVersion; /* Combines with pBt->pPager->iDataVersion */ Btree *pNext; /* List of other sharable Btrees from the same db */ Btree *pPrev; /* Back pointer of the same list */ #ifndef SQLITE_OMIT_SHARED_CACHE BtLock lock; /* Object used to lock page 1 */ #endif }; /* ** Btree.inTrans may take one of the following values. ** ** If the shared-data extension is enabled, there may be multiple users ** of the Btree structure. At most one of these may open a write transaction, ** but any number may have active read transactions. */ #define TRANS_NONE 0 #define TRANS_READ 1 #define TRANS_WRITE 2 /* ** An instance of this object represents a single database file. ** ** A single database file can be in use at the same time by two ** or more database connections. When two or more connections are ** sharing the same database file, each connection has it own ** private Btree object for the file and each of those Btrees points ** to this one BtShared object. BtShared.nRef is the number of ** connections currently sharing this database file. ** ** Fields in this structure are accessed under the BtShared.mutex ** mutex, except for nRef and pNext which are accessed under the ** global SQLITE_MUTEX_STATIC_MASTER mutex. The pPager field ** may not be modified once it is initially set as long as nRef>0. ** The pSchema field may be set once under BtShared.mutex and ** thereafter is unchanged as long as nRef>0. ** ** isPending: ** ** If a BtShared client fails to obtain a write-lock on a database ** table (because there exists one or more read-locks on the table), ** the shared-cache enters 'pending-lock' state and isPending is ** set to true. ** ** The shared-cache leaves the 'pending lock' state when either of ** the following occur: ** ** 1) The current writer (BtShared.pWriter) concludes its transaction, OR ** 2) The number of locks held by other connections drops to zero. ** ** while in the 'pending-lock' state, no connection may start a new ** transaction. ** ** This feature is included to help prevent writer-starvation. */ struct BtShared { Pager *pPager; /* The page cache */ sqlite3 *db; /* Database connection currently using this Btree */ BtCursor *pCursor; /* A list of all open cursors */ MemPage *pPage1; /* First page of the database */ u8 openFlags; /* Flags to sqlite3BtreeOpen() */ #ifndef SQLITE_OMIT_AUTOVACUUM u8 autoVacuum; /* True if auto-vacuum is enabled */ u8 incrVacuum; /* True if incr-vacuum is enabled */ u8 bDoTruncate; /* True to truncate db on commit */ #endif u8 inTransaction; /* Transaction state */ u8 max1bytePayload; /* Maximum first byte of cell for a 1-byte payload */ #ifdef SQLITE_HAS_CODEC u8 optimalReserve; /* Desired amount of reserved space per page */ #endif u16 btsFlags; /* Boolean parameters. See BTS_* macros below */ u16 maxLocal; /* Maximum local payload in non-LEAFDATA tables */ u16 minLocal; /* Minimum local payload in non-LEAFDATA tables */ u16 maxLeaf; /* Maximum local payload in a LEAFDATA table */ u16 minLeaf; /* Minimum local payload in a LEAFDATA table */ u32 pageSize; /* Total number of bytes on a page */ u32 usableSize; /* Number of usable bytes on each page */ int nTransaction; /* Number of open transactions (read + write) */ u32 nPage; /* Number of pages in the database */ void *pSchema; /* Pointer to space allocated by sqlite3BtreeSchema() */ void (*xFreeSchema)(void*); /* Destructor for BtShared.pSchema */ sqlite3_mutex *mutex; /* Non-recursive mutex required to access this object */ Bitvec *pHasContent; /* Set of pages moved to free-list this transaction */ #ifndef SQLITE_OMIT_SHARED_CACHE int nRef; /* Number of references to this structure */ BtShared *pNext; /* Next on a list of sharable BtShared structs */ BtLock *pLock; /* List of locks held on this shared-btree struct */ Btree *pWriter; /* Btree with currently open write transaction */ #endif u8 *pTmpSpace; /* Temp space sufficient to hold a single cell */ }; /* ** Allowed values for BtShared.btsFlags */ #define BTS_READ_ONLY 0x0001 /* Underlying file is readonly */ #define BTS_PAGESIZE_FIXED 0x0002 /* Page size can no longer be changed */ #define BTS_SECURE_DELETE 0x0004 /* PRAGMA secure_delete is enabled */ #define BTS_INITIALLY_EMPTY 0x0008 /* Database was empty at trans start */ #define BTS_NO_WAL 0x0010 /* Do not open write-ahead-log files */ #define BTS_EXCLUSIVE 0x0020 /* pWriter has an exclusive lock */ #define BTS_PENDING 0x0040 /* Waiting for read-locks to clear */ /* ** An instance of the following structure is used to hold information ** about a cell. The parseCellPtr() function fills in this structure ** based on information extract from the raw disk page. */ struct CellInfo { i64 nKey; /* The key for INTKEY tables, or nPayload otherwise */ u8 *pPayload; /* Pointer to the start of payload */ u32 nPayload; /* Bytes of payload */ u16 nLocal; /* Amount of payload held locally, not on overflow */ u16 nSize; /* Size of the cell content on the main b-tree page */ }; /* ** Maximum depth of an SQLite B-Tree structure. Any B-Tree deeper than ** this will be declared corrupt. This value is calculated based on a ** maximum database size of 2^31 pages a minimum fanout of 2 for a ** root-node and 3 for all other internal nodes. ** ** If a tree that appears to be taller than this is encountered, it is ** assumed that the database is corrupt. */ #define BTCURSOR_MAX_DEPTH 20 /* ** A cursor is a pointer to a particular entry within a particular ** b-tree within a database file. ** ** The entry is identified by its MemPage and the index in ** MemPage.aCell[] of the entry. ** ** A single database file can be shared by two more database connections, ** but cursors cannot be shared. Each cursor is associated with a ** particular database connection identified BtCursor.pBtree.db. ** ** Fields in this structure are accessed under the BtShared.mutex ** found at self->pBt->mutex. ** ** skipNext meaning: ** eState==SKIPNEXT && skipNext>0: Next sqlite3BtreeNext() is no-op. ** eState==SKIPNEXT && skipNext<0: Next sqlite3BtreePrevious() is no-op. ** eState==FAULT: Cursor fault with skipNext as error code. */ struct BtCursor { Btree *pBtree; /* The Btree to which this cursor belongs */ BtShared *pBt; /* The BtShared this cursor points to */ BtCursor *pNext; /* Forms a linked list of all cursors */ Pgno *aOverflow; /* Cache of overflow page locations */ CellInfo info; /* A parse of the cell we are pointing at */ i64 nKey; /* Size of pKey, or last integer key */ void *pKey; /* Saved key that was cursor last known position */ Pgno pgnoRoot; /* The root page of this tree */ int nOvflAlloc; /* Allocated size of aOverflow[] array */ int skipNext; /* Prev() is noop if negative. Next() is noop if positive. ** Error code if eState==CURSOR_FAULT */ u8 curFlags; /* zero or more BTCF_* flags defined below */ u8 curPagerFlags; /* Flags to send to sqlite3PagerGet() */ u8 eState; /* One of the CURSOR_XXX constants (see below) */ u8 hints; /* As configured by CursorSetHints() */ /* All fields above are zeroed when the cursor is allocated. See ** sqlite3BtreeCursorZero(). Fields that follow must be manually ** initialized. */ i8 iPage; /* Index of current page in apPage */ u8 curIntKey; /* Value of apPage[0]->intKey */ struct KeyInfo *pKeyInfo; /* Argument passed to comparison function */ void *padding1; /* Make object size a multiple of 16 */ u16 aiIdx[BTCURSOR_MAX_DEPTH]; /* Current index in apPage[i] */ MemPage *apPage[BTCURSOR_MAX_DEPTH]; /* Pages from root to current page */ }; /* ** Legal values for BtCursor.curFlags */ #define BTCF_WriteFlag 0x01 /* True if a write cursor */ #define BTCF_ValidNKey 0x02 /* True if info.nKey is valid */ #define BTCF_ValidOvfl 0x04 /* True if aOverflow is valid */ #define BTCF_AtLast 0x08 /* Cursor is pointing ot the last entry */ #define BTCF_Incrblob 0x10 /* True if an incremental I/O handle */ #define BTCF_Multiple 0x20 /* Maybe another cursor on the same btree */ /* ** Potential values for BtCursor.eState. ** ** CURSOR_INVALID: ** Cursor does not point to a valid entry. This can happen (for example) ** because the table is empty or because BtreeCursorFirst() has not been ** called. ** ** CURSOR_VALID: ** Cursor points to a valid entry. getPayload() etc. may be called. ** ** CURSOR_SKIPNEXT: ** Cursor is valid except that the Cursor.skipNext field is non-zero ** indicating that the next sqlite3BtreeNext() or sqlite3BtreePrevious() ** operation should be a no-op. ** ** CURSOR_REQUIRESEEK: ** The table that this cursor was opened on still exists, but has been ** modified since the cursor was last used. The cursor position is saved ** in variables BtCursor.pKey and BtCursor.nKey. When a cursor is in ** this state, restoreCursorPosition() can be called to attempt to ** seek the cursor to the saved position. ** ** CURSOR_FAULT: ** An unrecoverable error (an I/O error or a malloc failure) has occurred ** on a different connection that shares the BtShared cache with this ** cursor. The error has left the cache in an inconsistent state. ** Do nothing else with this cursor. Any attempt to use the cursor ** should return the error code stored in BtCursor.skipNext */ #define CURSOR_INVALID 0 #define CURSOR_VALID 1 #define CURSOR_SKIPNEXT 2 #define CURSOR_REQUIRESEEK 3 #define CURSOR_FAULT 4 /* ** The database page the PENDING_BYTE occupies. This page is never used. */ # define PENDING_BYTE_PAGE(pBt) PAGER_MJ_PGNO(pBt) /* ** These macros define the location of the pointer-map entry for a ** database page. The first argument to each is the number of usable ** bytes on each page of the database (often 1024). The second is the ** page number to look up in the pointer map. ** ** PTRMAP_PAGENO returns the database page number of the pointer-map ** page that stores the required pointer. PTRMAP_PTROFFSET returns ** the offset of the requested map entry. ** ** If the pgno argument passed to PTRMAP_PAGENO is a pointer-map page, ** then pgno is returned. So (pgno==PTRMAP_PAGENO(pgsz, pgno)) can be ** used to test if pgno is a pointer-map page. PTRMAP_ISPAGE implements ** this test. */ #define PTRMAP_PAGENO(pBt, pgno) ptrmapPageno(pBt, pgno) #define PTRMAP_PTROFFSET(pgptrmap, pgno) (5*(pgno-pgptrmap-1)) #define PTRMAP_ISPAGE(pBt, pgno) (PTRMAP_PAGENO((pBt),(pgno))==(pgno)) /* ** The pointer map is a lookup table that identifies the parent page for ** each child page in the database file. The parent page is the page that ** contains a pointer to the child. Every page in the database contains ** 0 or 1 parent pages. (In this context 'database page' refers ** to any page that is not part of the pointer map itself.) Each pointer map ** entry consists of a single byte 'type' and a 4 byte parent page number. ** The PTRMAP_XXX identifiers below are the valid types. ** ** The purpose of the pointer map is to facility moving pages from one ** position in the file to another as part of autovacuum. When a page ** is moved, the pointer in its parent must be updated to point to the ** new location. The pointer map is used to locate the parent page quickly. ** ** PTRMAP_ROOTPAGE: The database page is a root-page. The page-number is not ** used in this case. ** ** PTRMAP_FREEPAGE: The database page is an unused (free) page. The page-number ** is not used in this case. ** ** PTRMAP_OVERFLOW1: The database page is the first page in a list of ** overflow pages. The page number identifies the page that ** contains the cell with a pointer to this overflow page. ** ** PTRMAP_OVERFLOW2: The database page is the second or later page in a list of ** overflow pages. The page-number identifies the previous ** page in the overflow page list. ** ** PTRMAP_BTREE: The database page is a non-root btree page. The page number ** identifies the parent page in the btree. */ #define PTRMAP_ROOTPAGE 1 #define PTRMAP_FREEPAGE 2 #define PTRMAP_OVERFLOW1 3 #define PTRMAP_OVERFLOW2 4 #define PTRMAP_BTREE 5 /* A bunch of assert() statements to check the transaction state variables ** of handle p (type Btree*) are internally consistent. */ #define btreeIntegrity(p) \ assert( p->pBt->inTransaction!=TRANS_NONE || p->pBt->nTransaction==0 ); \ assert( p->pBt->inTransaction>=p->inTrans ); /* ** The ISAUTOVACUUM macro is used within balance_nonroot() to determine ** if the database supports auto-vacuum or not. Because it is used ** within an expression that is an argument to another macro ** (sqliteMallocRaw), it is not possible to use conditional compilation. ** So, this macro is defined instead. */ #ifndef SQLITE_OMIT_AUTOVACUUM #define ISAUTOVACUUM (pBt->autoVacuum) #else #define ISAUTOVACUUM 0 #endif /* ** This structure is passed around through all the sanity checking routines ** in order to keep track of some global state information. ** ** The aRef[] array is allocated so that there is 1 bit for each page in ** the database. As the integrity-check proceeds, for each page used in ** the database the corresponding bit is set. This allows integrity-check to ** detect pages that are used twice and orphaned pages (both of which ** indicate corruption). */ typedef struct IntegrityCk IntegrityCk; struct IntegrityCk { BtShared *pBt; /* The tree being checked out */ Pager *pPager; /* The associated pager. Also accessible by pBt->pPager */ u8 *aPgRef; /* 1 bit per page in the db (see above) */ Pgno nPage; /* Number of pages in the database */ int mxErr; /* Stop accumulating errors when this reaches zero */ int nErr; /* Number of messages written to zErrMsg so far */ int mallocFailed; /* A memory allocation error has occurred */ const char *zPfx; /* Error message prefix */ int v1, v2; /* Values for up to two %d fields in zPfx */ StrAccum errMsg; /* Accumulate the error message text here */ u32 *heap; /* Min-heap used for analyzing cell coverage */ }; /* ** Routines to read or write a two- and four-byte big-endian integer values. */ #define get2byte(x) ((x)[0]<<8 | (x)[1]) #define put2byte(p,v) ((p)[0] = (u8)((v)>>8), (p)[1] = (u8)(v)) #define get4byte sqlite3Get4byte #define put4byte sqlite3Put4byte /* ** get2byteAligned(), unlike get2byte(), requires that its argument point to a ** two-byte aligned address. get2bytea() is only used for accessing the ** cell addresses in a btree header. */ #if SQLITE_BYTEORDER==4321 # define get2byteAligned(x) (*(u16*)(x)) #elif SQLITE_BYTEORDER==1234 && !defined(SQLITE_DISABLE_INTRINSIC) \ && GCC_VERSION>=4008000 # define get2byteAligned(x) __builtin_bswap16(*(u16*)(x)) #elif SQLITE_BYTEORDER==1234 && !defined(SQLITE_DISABLE_INTRINSIC) \ && defined(_MSC_VER) && _MSC_VER>=1300 # define get2byteAligned(x) _byteswap_ushort(*(u16*)(x)) #else # define get2byteAligned(x) ((x)[0]<<8 | (x)[1]) #endif /************** End of btreeInt.h ********************************************/ /************** Continuing where we left off in btmutex.c ********************/ #ifndef SQLITE_OMIT_SHARED_CACHE #if SQLITE_THREADSAFE /* ** Obtain the BtShared mutex associated with B-Tree handle p. Also, ** set BtShared.db to the database handle associated with p and the ** p->locked boolean to true. */ static void lockBtreeMutex(Btree *p){ assert( p->locked==0 ); assert( sqlite3_mutex_notheld(p->pBt->mutex) ); assert( sqlite3_mutex_held(p->db->mutex) ); sqlite3_mutex_enter(p->pBt->mutex); p->pBt->db = p->db; p->locked = 1; } /* ** Release the BtShared mutex associated with B-Tree handle p and ** clear the p->locked boolean. */ static void SQLITE_NOINLINE unlockBtreeMutex(Btree *p){ BtShared *pBt = p->pBt; assert( p->locked==1 ); assert( sqlite3_mutex_held(pBt->mutex) ); assert( sqlite3_mutex_held(p->db->mutex) ); assert( p->db==pBt->db ); sqlite3_mutex_leave(pBt->mutex); p->locked = 0; } /* Forward reference */ static void SQLITE_NOINLINE btreeLockCarefully(Btree *p); /* ** Enter a mutex on the given BTree object. ** ** If the object is not sharable, then no mutex is ever required ** and this routine is a no-op. The underlying mutex is non-recursive. ** But we keep a reference count in Btree.wantToLock so the behavior ** of this interface is recursive. ** ** To avoid deadlocks, multiple Btrees are locked in the same order ** by all database connections. The p->pNext is a list of other ** Btrees belonging to the same database connection as the p Btree ** which need to be locked after p. If we cannot get a lock on ** p, then first unlock all of the others on p->pNext, then wait ** for the lock to become available on p, then relock all of the ** subsequent Btrees that desire a lock. */ SQLITE_PRIVATE void sqlite3BtreeEnter(Btree *p){ /* Some basic sanity checking on the Btree. The list of Btrees ** connected by pNext and pPrev should be in sorted order by ** Btree.pBt value. All elements of the list should belong to ** the same connection. Only shared Btrees are on the list. */ assert( p->pNext==0 || p->pNext->pBt>p->pBt ); assert( p->pPrev==0 || p->pPrev->pBtpBt ); assert( p->pNext==0 || p->pNext->db==p->db ); assert( p->pPrev==0 || p->pPrev->db==p->db ); assert( p->sharable || (p->pNext==0 && p->pPrev==0) ); /* Check for locking consistency */ assert( !p->locked || p->wantToLock>0 ); assert( p->sharable || p->wantToLock==0 ); /* We should already hold a lock on the database connection */ assert( sqlite3_mutex_held(p->db->mutex) ); /* Unless the database is sharable and unlocked, then BtShared.db ** should already be set correctly. */ assert( (p->locked==0 && p->sharable) || p->pBt->db==p->db ); if( !p->sharable ) return; p->wantToLock++; if( p->locked ) return; btreeLockCarefully(p); } /* This is a helper function for sqlite3BtreeLock(). By moving ** complex, but seldom used logic, out of sqlite3BtreeLock() and ** into this routine, we avoid unnecessary stack pointer changes ** and thus help the sqlite3BtreeLock() routine to run much faster ** in the common case. */ static void SQLITE_NOINLINE btreeLockCarefully(Btree *p){ Btree *pLater; /* In most cases, we should be able to acquire the lock we ** want without having to go through the ascending lock ** procedure that follows. Just be sure not to block. */ if( sqlite3_mutex_try(p->pBt->mutex)==SQLITE_OK ){ p->pBt->db = p->db; p->locked = 1; return; } /* To avoid deadlock, first release all locks with a larger ** BtShared address. Then acquire our lock. Then reacquire ** the other BtShared locks that we used to hold in ascending ** order. */ for(pLater=p->pNext; pLater; pLater=pLater->pNext){ assert( pLater->sharable ); assert( pLater->pNext==0 || pLater->pNext->pBt>pLater->pBt ); assert( !pLater->locked || pLater->wantToLock>0 ); if( pLater->locked ){ unlockBtreeMutex(pLater); } } lockBtreeMutex(p); for(pLater=p->pNext; pLater; pLater=pLater->pNext){ if( pLater->wantToLock ){ lockBtreeMutex(pLater); } } } /* ** Exit the recursive mutex on a Btree. */ SQLITE_PRIVATE void sqlite3BtreeLeave(Btree *p){ assert( sqlite3_mutex_held(p->db->mutex) ); if( p->sharable ){ assert( p->wantToLock>0 ); p->wantToLock--; if( p->wantToLock==0 ){ unlockBtreeMutex(p); } } } #ifndef NDEBUG /* ** Return true if the BtShared mutex is held on the btree, or if the ** B-Tree is not marked as sharable. ** ** This routine is used only from within assert() statements. */ SQLITE_PRIVATE int sqlite3BtreeHoldsMutex(Btree *p){ assert( p->sharable==0 || p->locked==0 || p->wantToLock>0 ); assert( p->sharable==0 || p->locked==0 || p->db==p->pBt->db ); assert( p->sharable==0 || p->locked==0 || sqlite3_mutex_held(p->pBt->mutex) ); assert( p->sharable==0 || p->locked==0 || sqlite3_mutex_held(p->db->mutex) ); return (p->sharable==0 || p->locked); } #endif /* ** Enter the mutex on every Btree associated with a database ** connection. This is needed (for example) prior to parsing ** a statement since we will be comparing table and column names ** against all schemas and we do not want those schemas being ** reset out from under us. ** ** There is a corresponding leave-all procedures. ** ** Enter the mutexes in accending order by BtShared pointer address ** to avoid the possibility of deadlock when two threads with ** two or more btrees in common both try to lock all their btrees ** at the same instant. */ SQLITE_PRIVATE void sqlite3BtreeEnterAll(sqlite3 *db){ int i; Btree *p; assert( sqlite3_mutex_held(db->mutex) ); for(i=0; inDb; i++){ p = db->aDb[i].pBt; if( p ) sqlite3BtreeEnter(p); } } SQLITE_PRIVATE void sqlite3BtreeLeaveAll(sqlite3 *db){ int i; Btree *p; assert( sqlite3_mutex_held(db->mutex) ); for(i=0; inDb; i++){ p = db->aDb[i].pBt; if( p ) sqlite3BtreeLeave(p); } } #ifndef NDEBUG /* ** Return true if the current thread holds the database connection ** mutex and all required BtShared mutexes. ** ** This routine is used inside assert() statements only. */ SQLITE_PRIVATE int sqlite3BtreeHoldsAllMutexes(sqlite3 *db){ int i; if( !sqlite3_mutex_held(db->mutex) ){ return 0; } for(i=0; inDb; i++){ Btree *p; p = db->aDb[i].pBt; if( p && p->sharable && (p->wantToLock==0 || !sqlite3_mutex_held(p->pBt->mutex)) ){ return 0; } } return 1; } #endif /* NDEBUG */ #ifndef NDEBUG /* ** Return true if the correct mutexes are held for accessing the ** db->aDb[iDb].pSchema structure. The mutexes required for schema ** access are: ** ** (1) The mutex on db ** (2) if iDb!=1, then the mutex on db->aDb[iDb].pBt. ** ** If pSchema is not NULL, then iDb is computed from pSchema and ** db using sqlite3SchemaToIndex(). */ SQLITE_PRIVATE int sqlite3SchemaMutexHeld(sqlite3 *db, int iDb, Schema *pSchema){ Btree *p; assert( db!=0 ); if( pSchema ) iDb = sqlite3SchemaToIndex(db, pSchema); assert( iDb>=0 && iDbnDb ); if( !sqlite3_mutex_held(db->mutex) ) return 0; if( iDb==1 ) return 1; p = db->aDb[iDb].pBt; assert( p!=0 ); return p->sharable==0 || p->locked==1; } #endif /* NDEBUG */ #else /* SQLITE_THREADSAFE>0 above. SQLITE_THREADSAFE==0 below */ /* ** The following are special cases for mutex enter routines for use ** in single threaded applications that use shared cache. Except for ** these two routines, all mutex operations are no-ops in that case and ** are null #defines in btree.h. ** ** If shared cache is disabled, then all btree mutex routines, including ** the ones below, are no-ops and are null #defines in btree.h. */ SQLITE_PRIVATE void sqlite3BtreeEnter(Btree *p){ p->pBt->db = p->db; } SQLITE_PRIVATE void sqlite3BtreeEnterAll(sqlite3 *db){ int i; for(i=0; inDb; i++){ Btree *p = db->aDb[i].pBt; if( p ){ p->pBt->db = p->db; } } } #endif /* if SQLITE_THREADSAFE */ #ifndef SQLITE_OMIT_INCRBLOB /* ** Enter a mutex on a Btree given a cursor owned by that Btree. ** ** These entry points are used by incremental I/O only. Enter() is required ** any time OMIT_SHARED_CACHE is not defined, regardless of whether or not ** the build is threadsafe. Leave() is only required by threadsafe builds. */ SQLITE_PRIVATE void sqlite3BtreeEnterCursor(BtCursor *pCur){ sqlite3BtreeEnter(pCur->pBtree); } # if SQLITE_THREADSAFE SQLITE_PRIVATE void sqlite3BtreeLeaveCursor(BtCursor *pCur){ sqlite3BtreeLeave(pCur->pBtree); } # endif #endif /* ifndef SQLITE_OMIT_INCRBLOB */ #endif /* ifndef SQLITE_OMIT_SHARED_CACHE */ /************** End of btmutex.c *********************************************/ /************** Begin file btree.c *******************************************/ /* ** 2004 April 6 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ************************************************************************* ** This file implements an external (disk-based) database using BTrees. ** See the header comment on "btreeInt.h" for additional information. ** Including a description of file format and an overview of operation. */ /* #include "btreeInt.h" */ /* ** The header string that appears at the beginning of every ** SQLite database. */ static const char zMagicHeader[] = SQLITE_FILE_HEADER; /* ** Set this global variable to 1 to enable tracing using the TRACE ** macro. */ #if 0 int sqlite3BtreeTrace=1; /* True to enable tracing */ # define TRACE(X) if(sqlite3BtreeTrace){printf X;fflush(stdout);} #else # define TRACE(X) #endif /* ** Extract a 2-byte big-endian integer from an array of unsigned bytes. ** But if the value is zero, make it 65536. ** ** This routine is used to extract the "offset to cell content area" value ** from the header of a btree page. If the page size is 65536 and the page ** is empty, the offset should be 65536, but the 2-byte value stores zero. ** This routine makes the necessary adjustment to 65536. */ #define get2byteNotZero(X) (((((int)get2byte(X))-1)&0xffff)+1) /* ** Values passed as the 5th argument to allocateBtreePage() */ #define BTALLOC_ANY 0 /* Allocate any page */ #define BTALLOC_EXACT 1 /* Allocate exact page if possible */ #define BTALLOC_LE 2 /* Allocate any page <= the parameter */ /* ** Macro IfNotOmitAV(x) returns (x) if SQLITE_OMIT_AUTOVACUUM is not ** defined, or 0 if it is. For example: ** ** bIncrVacuum = IfNotOmitAV(pBtShared->incrVacuum); */ #ifndef SQLITE_OMIT_AUTOVACUUM #define IfNotOmitAV(expr) (expr) #else #define IfNotOmitAV(expr) 0 #endif #ifndef SQLITE_OMIT_SHARED_CACHE /* ** A list of BtShared objects that are eligible for participation ** in shared cache. This variable has file scope during normal builds, ** but the test harness needs to access it so we make it global for ** test builds. ** ** Access to this variable is protected by SQLITE_MUTEX_STATIC_MASTER. */ #ifdef SQLITE_TEST SQLITE_PRIVATE BtShared *SQLITE_WSD sqlite3SharedCacheList = 0; #else static BtShared *SQLITE_WSD sqlite3SharedCacheList = 0; #endif #endif /* SQLITE_OMIT_SHARED_CACHE */ #ifndef SQLITE_OMIT_SHARED_CACHE /* ** Enable or disable the shared pager and schema features. ** ** This routine has no effect on existing database connections. ** The shared cache setting effects only future calls to ** sqlite3_open(), sqlite3_open16(), or sqlite3_open_v2(). */ SQLITE_API int sqlite3_enable_shared_cache(int enable){ sqlite3GlobalConfig.sharedCacheEnabled = enable; return SQLITE_OK; } #endif #ifdef SQLITE_OMIT_SHARED_CACHE /* ** The functions querySharedCacheTableLock(), setSharedCacheTableLock(), ** and clearAllSharedCacheTableLocks() ** manipulate entries in the BtShared.pLock linked list used to store ** shared-cache table level locks. If the library is compiled with the ** shared-cache feature disabled, then there is only ever one user ** of each BtShared structure and so this locking is not necessary. ** So define the lock related functions as no-ops. */ #define querySharedCacheTableLock(a,b,c) SQLITE_OK #define setSharedCacheTableLock(a,b,c) SQLITE_OK #define clearAllSharedCacheTableLocks(a) #define downgradeAllSharedCacheTableLocks(a) #define hasSharedCacheTableLock(a,b,c,d) 1 #define hasReadConflicts(a, b) 0 #endif #ifndef SQLITE_OMIT_SHARED_CACHE #ifdef SQLITE_DEBUG /* **** This function is only used as part of an assert() statement. *** ** ** Check to see if pBtree holds the required locks to read or write to the ** table with root page iRoot. Return 1 if it does and 0 if not. ** ** For example, when writing to a table with root-page iRoot via ** Btree connection pBtree: ** ** assert( hasSharedCacheTableLock(pBtree, iRoot, 0, WRITE_LOCK) ); ** ** When writing to an index that resides in a sharable database, the ** caller should have first obtained a lock specifying the root page of ** the corresponding table. This makes things a bit more complicated, ** as this module treats each table as a separate structure. To determine ** the table corresponding to the index being written, this ** function has to search through the database schema. ** ** Instead of a lock on the table/index rooted at page iRoot, the caller may ** hold a write-lock on the schema table (root page 1). This is also ** acceptable. */ static int hasSharedCacheTableLock( Btree *pBtree, /* Handle that must hold lock */ Pgno iRoot, /* Root page of b-tree */ int isIndex, /* True if iRoot is the root of an index b-tree */ int eLockType /* Required lock type (READ_LOCK or WRITE_LOCK) */ ){ Schema *pSchema = (Schema *)pBtree->pBt->pSchema; Pgno iTab = 0; BtLock *pLock; /* If this database is not shareable, or if the client is reading ** and has the read-uncommitted flag set, then no lock is required. ** Return true immediately. */ if( (pBtree->sharable==0) || (eLockType==READ_LOCK && (pBtree->db->flags & SQLITE_ReadUncommitted)) ){ return 1; } /* If the client is reading or writing an index and the schema is ** not loaded, then it is too difficult to actually check to see if ** the correct locks are held. So do not bother - just return true. ** This case does not come up very often anyhow. */ if( isIndex && (!pSchema || (pSchema->schemaFlags&DB_SchemaLoaded)==0) ){ return 1; } /* Figure out the root-page that the lock should be held on. For table ** b-trees, this is just the root page of the b-tree being read or ** written. For index b-trees, it is the root page of the associated ** table. */ if( isIndex ){ HashElem *p; for(p=sqliteHashFirst(&pSchema->idxHash); p; p=sqliteHashNext(p)){ Index *pIdx = (Index *)sqliteHashData(p); if( pIdx->tnum==(int)iRoot ){ if( iTab ){ /* Two or more indexes share the same root page. There must ** be imposter tables. So just return true. The assert is not ** useful in that case. */ return 1; } iTab = pIdx->pTable->tnum; } } }else{ iTab = iRoot; } /* Search for the required lock. Either a write-lock on root-page iTab, a ** write-lock on the schema table, or (if the client is reading) a ** read-lock on iTab will suffice. Return 1 if any of these are found. */ for(pLock=pBtree->pBt->pLock; pLock; pLock=pLock->pNext){ if( pLock->pBtree==pBtree && (pLock->iTable==iTab || (pLock->eLock==WRITE_LOCK && pLock->iTable==1)) && pLock->eLock>=eLockType ){ return 1; } } /* Failed to find the required lock. */ return 0; } #endif /* SQLITE_DEBUG */ #ifdef SQLITE_DEBUG /* **** This function may be used as part of assert() statements only. **** ** ** Return true if it would be illegal for pBtree to write into the ** table or index rooted at iRoot because other shared connections are ** simultaneously reading that same table or index. ** ** It is illegal for pBtree to write if some other Btree object that ** shares the same BtShared object is currently reading or writing ** the iRoot table. Except, if the other Btree object has the ** read-uncommitted flag set, then it is OK for the other object to ** have a read cursor. ** ** For example, before writing to any part of the table or index ** rooted at page iRoot, one should call: ** ** assert( !hasReadConflicts(pBtree, iRoot) ); */ static int hasReadConflicts(Btree *pBtree, Pgno iRoot){ BtCursor *p; for(p=pBtree->pBt->pCursor; p; p=p->pNext){ if( p->pgnoRoot==iRoot && p->pBtree!=pBtree && 0==(p->pBtree->db->flags & SQLITE_ReadUncommitted) ){ return 1; } } return 0; } #endif /* #ifdef SQLITE_DEBUG */ /* ** Query to see if Btree handle p may obtain a lock of type eLock ** (READ_LOCK or WRITE_LOCK) on the table with root-page iTab. Return ** SQLITE_OK if the lock may be obtained (by calling ** setSharedCacheTableLock()), or SQLITE_LOCKED if not. */ static int querySharedCacheTableLock(Btree *p, Pgno iTab, u8 eLock){ BtShared *pBt = p->pBt; BtLock *pIter; assert( sqlite3BtreeHoldsMutex(p) ); assert( eLock==READ_LOCK || eLock==WRITE_LOCK ); assert( p->db!=0 ); assert( !(p->db->flags&SQLITE_ReadUncommitted)||eLock==WRITE_LOCK||iTab==1 ); /* If requesting a write-lock, then the Btree must have an open write ** transaction on this file. And, obviously, for this to be so there ** must be an open write transaction on the file itself. */ assert( eLock==READ_LOCK || (p==pBt->pWriter && p->inTrans==TRANS_WRITE) ); assert( eLock==READ_LOCK || pBt->inTransaction==TRANS_WRITE ); /* This routine is a no-op if the shared-cache is not enabled */ if( !p->sharable ){ return SQLITE_OK; } /* If some other connection is holding an exclusive lock, the ** requested lock may not be obtained. */ if( pBt->pWriter!=p && (pBt->btsFlags & BTS_EXCLUSIVE)!=0 ){ sqlite3ConnectionBlocked(p->db, pBt->pWriter->db); return SQLITE_LOCKED_SHAREDCACHE; } for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){ /* The condition (pIter->eLock!=eLock) in the following if(...) ** statement is a simplification of: ** ** (eLock==WRITE_LOCK || pIter->eLock==WRITE_LOCK) ** ** since we know that if eLock==WRITE_LOCK, then no other connection ** may hold a WRITE_LOCK on any table in this file (since there can ** only be a single writer). */ assert( pIter->eLock==READ_LOCK || pIter->eLock==WRITE_LOCK ); assert( eLock==READ_LOCK || pIter->pBtree==p || pIter->eLock==READ_LOCK); if( pIter->pBtree!=p && pIter->iTable==iTab && pIter->eLock!=eLock ){ sqlite3ConnectionBlocked(p->db, pIter->pBtree->db); if( eLock==WRITE_LOCK ){ assert( p==pBt->pWriter ); pBt->btsFlags |= BTS_PENDING; } return SQLITE_LOCKED_SHAREDCACHE; } } return SQLITE_OK; } #endif /* !SQLITE_OMIT_SHARED_CACHE */ #ifndef SQLITE_OMIT_SHARED_CACHE /* ** Add a lock on the table with root-page iTable to the shared-btree used ** by Btree handle p. Parameter eLock must be either READ_LOCK or ** WRITE_LOCK. ** ** This function assumes the following: ** ** (a) The specified Btree object p is connected to a sharable ** database (one with the BtShared.sharable flag set), and ** ** (b) No other Btree objects hold a lock that conflicts ** with the requested lock (i.e. querySharedCacheTableLock() has ** already been called and returned SQLITE_OK). ** ** SQLITE_OK is returned if the lock is added successfully. SQLITE_NOMEM ** is returned if a malloc attempt fails. */ static int setSharedCacheTableLock(Btree *p, Pgno iTable, u8 eLock){ BtShared *pBt = p->pBt; BtLock *pLock = 0; BtLock *pIter; assert( sqlite3BtreeHoldsMutex(p) ); assert( eLock==READ_LOCK || eLock==WRITE_LOCK ); assert( p->db!=0 ); /* A connection with the read-uncommitted flag set will never try to ** obtain a read-lock using this function. The only read-lock obtained ** by a connection in read-uncommitted mode is on the sqlite_master ** table, and that lock is obtained in BtreeBeginTrans(). */ assert( 0==(p->db->flags&SQLITE_ReadUncommitted) || eLock==WRITE_LOCK ); /* This function should only be called on a sharable b-tree after it ** has been determined that no other b-tree holds a conflicting lock. */ assert( p->sharable ); assert( SQLITE_OK==querySharedCacheTableLock(p, iTable, eLock) ); /* First search the list for an existing lock on this table. */ for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){ if( pIter->iTable==iTable && pIter->pBtree==p ){ pLock = pIter; break; } } /* If the above search did not find a BtLock struct associating Btree p ** with table iTable, allocate one and link it into the list. */ if( !pLock ){ pLock = (BtLock *)sqlite3MallocZero(sizeof(BtLock)); if( !pLock ){ return SQLITE_NOMEM_BKPT; } pLock->iTable = iTable; pLock->pBtree = p; pLock->pNext = pBt->pLock; pBt->pLock = pLock; } /* Set the BtLock.eLock variable to the maximum of the current lock ** and the requested lock. This means if a write-lock was already held ** and a read-lock requested, we don't incorrectly downgrade the lock. */ assert( WRITE_LOCK>READ_LOCK ); if( eLock>pLock->eLock ){ pLock->eLock = eLock; } return SQLITE_OK; } #endif /* !SQLITE_OMIT_SHARED_CACHE */ #ifndef SQLITE_OMIT_SHARED_CACHE /* ** Release all the table locks (locks obtained via calls to ** the setSharedCacheTableLock() procedure) held by Btree object p. ** ** This function assumes that Btree p has an open read or write ** transaction. If it does not, then the BTS_PENDING flag ** may be incorrectly cleared. */ static void clearAllSharedCacheTableLocks(Btree *p){ BtShared *pBt = p->pBt; BtLock **ppIter = &pBt->pLock; assert( sqlite3BtreeHoldsMutex(p) ); assert( p->sharable || 0==*ppIter ); assert( p->inTrans>0 ); while( *ppIter ){ BtLock *pLock = *ppIter; assert( (pBt->btsFlags & BTS_EXCLUSIVE)==0 || pBt->pWriter==pLock->pBtree ); assert( pLock->pBtree->inTrans>=pLock->eLock ); if( pLock->pBtree==p ){ *ppIter = pLock->pNext; assert( pLock->iTable!=1 || pLock==&p->lock ); if( pLock->iTable!=1 ){ sqlite3_free(pLock); } }else{ ppIter = &pLock->pNext; } } assert( (pBt->btsFlags & BTS_PENDING)==0 || pBt->pWriter ); if( pBt->pWriter==p ){ pBt->pWriter = 0; pBt->btsFlags &= ~(BTS_EXCLUSIVE|BTS_PENDING); }else if( pBt->nTransaction==2 ){ /* This function is called when Btree p is concluding its ** transaction. If there currently exists a writer, and p is not ** that writer, then the number of locks held by connections other ** than the writer must be about to drop to zero. In this case ** set the BTS_PENDING flag to 0. ** ** If there is not currently a writer, then BTS_PENDING must ** be zero already. So this next line is harmless in that case. */ pBt->btsFlags &= ~BTS_PENDING; } } /* ** This function changes all write-locks held by Btree p into read-locks. */ static void downgradeAllSharedCacheTableLocks(Btree *p){ BtShared *pBt = p->pBt; if( pBt->pWriter==p ){ BtLock *pLock; pBt->pWriter = 0; pBt->btsFlags &= ~(BTS_EXCLUSIVE|BTS_PENDING); for(pLock=pBt->pLock; pLock; pLock=pLock->pNext){ assert( pLock->eLock==READ_LOCK || pLock->pBtree==p ); pLock->eLock = READ_LOCK; } } } #endif /* SQLITE_OMIT_SHARED_CACHE */ static void releasePage(MemPage *pPage); /* Forward reference */ /* ***** This routine is used inside of assert() only **** ** ** Verify that the cursor holds the mutex on its BtShared */ #ifdef SQLITE_DEBUG static int cursorHoldsMutex(BtCursor *p){ return sqlite3_mutex_held(p->pBt->mutex); } /* Verify that the cursor and the BtShared agree about what is the current ** database connetion. This is important in shared-cache mode. If the database ** connection pointers get out-of-sync, it is possible for routines like ** btreeInitPage() to reference an stale connection pointer that references a ** a connection that has already closed. This routine is used inside assert() ** statements only and for the purpose of double-checking that the btree code ** does keep the database connection pointers up-to-date. */ static int cursorOwnsBtShared(BtCursor *p){ assert( cursorHoldsMutex(p) ); return (p->pBtree->db==p->pBt->db); } #endif /* ** Invalidate the overflow cache of the cursor passed as the first argument. ** on the shared btree structure pBt. */ #define invalidateOverflowCache(pCur) (pCur->curFlags &= ~BTCF_ValidOvfl) /* ** Invalidate the overflow page-list cache for all cursors opened ** on the shared btree structure pBt. */ static void invalidateAllOverflowCache(BtShared *pBt){ BtCursor *p; assert( sqlite3_mutex_held(pBt->mutex) ); for(p=pBt->pCursor; p; p=p->pNext){ invalidateOverflowCache(p); } } #ifndef SQLITE_OMIT_INCRBLOB /* ** This function is called before modifying the contents of a table ** to invalidate any incrblob cursors that are open on the ** row or one of the rows being modified. ** ** If argument isClearTable is true, then the entire contents of the ** table is about to be deleted. In this case invalidate all incrblob ** cursors open on any row within the table with root-page pgnoRoot. ** ** Otherwise, if argument isClearTable is false, then the row with ** rowid iRow is being replaced or deleted. In this case invalidate ** only those incrblob cursors open on that specific row. */ static void invalidateIncrblobCursors( Btree *pBtree, /* The database file to check */ i64 iRow, /* The rowid that might be changing */ int isClearTable /* True if all rows are being deleted */ ){ BtCursor *p; if( pBtree->hasIncrblobCur==0 ) return; assert( sqlite3BtreeHoldsMutex(pBtree) ); pBtree->hasIncrblobCur = 0; for(p=pBtree->pBt->pCursor; p; p=p->pNext){ if( (p->curFlags & BTCF_Incrblob)!=0 ){ pBtree->hasIncrblobCur = 1; if( isClearTable || p->info.nKey==iRow ){ p->eState = CURSOR_INVALID; } } } } #else /* Stub function when INCRBLOB is omitted */ #define invalidateIncrblobCursors(x,y,z) #endif /* SQLITE_OMIT_INCRBLOB */ /* ** Set bit pgno of the BtShared.pHasContent bitvec. This is called ** when a page that previously contained data becomes a free-list leaf ** page. ** ** The BtShared.pHasContent bitvec exists to work around an obscure ** bug caused by the interaction of two useful IO optimizations surrounding ** free-list leaf pages: ** ** 1) When all data is deleted from a page and the page becomes ** a free-list leaf page, the page is not written to the database ** (as free-list leaf pages contain no meaningful data). Sometimes ** such a page is not even journalled (as it will not be modified, ** why bother journalling it?). ** ** 2) When a free-list leaf page is reused, its content is not read ** from the database or written to the journal file (why should it ** be, if it is not at all meaningful?). ** ** By themselves, these optimizations work fine and provide a handy ** performance boost to bulk delete or insert operations. However, if ** a page is moved to the free-list and then reused within the same ** transaction, a problem comes up. If the page is not journalled when ** it is moved to the free-list and it is also not journalled when it ** is extracted from the free-list and reused, then the original data ** may be lost. In the event of a rollback, it may not be possible ** to restore the database to its original configuration. ** ** The solution is the BtShared.pHasContent bitvec. Whenever a page is ** moved to become a free-list leaf page, the corresponding bit is ** set in the bitvec. Whenever a leaf page is extracted from the free-list, ** optimization 2 above is omitted if the corresponding bit is already ** set in BtShared.pHasContent. The contents of the bitvec are cleared ** at the end of every transaction. */ static int btreeSetHasContent(BtShared *pBt, Pgno pgno){ int rc = SQLITE_OK; if( !pBt->pHasContent ){ assert( pgno<=pBt->nPage ); pBt->pHasContent = sqlite3BitvecCreate(pBt->nPage); if( !pBt->pHasContent ){ rc = SQLITE_NOMEM_BKPT; } } if( rc==SQLITE_OK && pgno<=sqlite3BitvecSize(pBt->pHasContent) ){ rc = sqlite3BitvecSet(pBt->pHasContent, pgno); } return rc; } /* ** Query the BtShared.pHasContent vector. ** ** This function is called when a free-list leaf page is removed from the ** free-list for reuse. It returns false if it is safe to retrieve the ** page from the pager layer with the 'no-content' flag set. True otherwise. */ static int btreeGetHasContent(BtShared *pBt, Pgno pgno){ Bitvec *p = pBt->pHasContent; return (p && (pgno>sqlite3BitvecSize(p) || sqlite3BitvecTest(p, pgno))); } /* ** Clear (destroy) the BtShared.pHasContent bitvec. This should be ** invoked at the conclusion of each write-transaction. */ static void btreeClearHasContent(BtShared *pBt){ sqlite3BitvecDestroy(pBt->pHasContent); pBt->pHasContent = 0; } /* ** Release all of the apPage[] pages for a cursor. */ static void btreeReleaseAllCursorPages(BtCursor *pCur){ int i; for(i=0; i<=pCur->iPage; i++){ releasePage(pCur->apPage[i]); pCur->apPage[i] = 0; } pCur->iPage = -1; } /* ** The cursor passed as the only argument must point to a valid entry ** when this function is called (i.e. have eState==CURSOR_VALID). This ** function saves the current cursor key in variables pCur->nKey and ** pCur->pKey. SQLITE_OK is returned if successful or an SQLite error ** code otherwise. ** ** If the cursor is open on an intkey table, then the integer key ** (the rowid) is stored in pCur->nKey and pCur->pKey is left set to ** NULL. If the cursor is open on a non-intkey table, then pCur->pKey is ** set to point to a malloced buffer pCur->nKey bytes in size containing ** the key. */ static int saveCursorKey(BtCursor *pCur){ int rc = SQLITE_OK; assert( CURSOR_VALID==pCur->eState ); assert( 0==pCur->pKey ); assert( cursorHoldsMutex(pCur) ); if( pCur->curIntKey ){ /* Only the rowid is required for a table btree */ pCur->nKey = sqlite3BtreeIntegerKey(pCur); }else{ /* For an index btree, save the complete key content */ void *pKey; pCur->nKey = sqlite3BtreePayloadSize(pCur); pKey = sqlite3Malloc( pCur->nKey ); if( pKey ){ rc = sqlite3BtreeKey(pCur, 0, (int)pCur->nKey, pKey); if( rc==SQLITE_OK ){ pCur->pKey = pKey; }else{ sqlite3_free(pKey); } }else{ rc = SQLITE_NOMEM_BKPT; } } assert( !pCur->curIntKey || !pCur->pKey ); return rc; } /* ** Save the current cursor position in the variables BtCursor.nKey ** and BtCursor.pKey. The cursor's state is set to CURSOR_REQUIRESEEK. ** ** The caller must ensure that the cursor is valid (has eState==CURSOR_VALID) ** prior to calling this routine. */ static int saveCursorPosition(BtCursor *pCur){ int rc; assert( CURSOR_VALID==pCur->eState || CURSOR_SKIPNEXT==pCur->eState ); assert( 0==pCur->pKey ); assert( cursorHoldsMutex(pCur) ); if( pCur->eState==CURSOR_SKIPNEXT ){ pCur->eState = CURSOR_VALID; }else{ pCur->skipNext = 0; } rc = saveCursorKey(pCur); if( rc==SQLITE_OK ){ btreeReleaseAllCursorPages(pCur); pCur->eState = CURSOR_REQUIRESEEK; } pCur->curFlags &= ~(BTCF_ValidNKey|BTCF_ValidOvfl|BTCF_AtLast); return rc; } /* Forward reference */ static int SQLITE_NOINLINE saveCursorsOnList(BtCursor*,Pgno,BtCursor*); /* ** Save the positions of all cursors (except pExcept) that are open on ** the table with root-page iRoot. "Saving the cursor position" means that ** the location in the btree is remembered in such a way that it can be ** moved back to the same spot after the btree has been modified. This ** routine is called just before cursor pExcept is used to modify the ** table, for example in BtreeDelete() or BtreeInsert(). ** ** If there are two or more cursors on the same btree, then all such ** cursors should have their BTCF_Multiple flag set. The btreeCursor() ** routine enforces that rule. This routine only needs to be called in ** the uncommon case when pExpect has the BTCF_Multiple flag set. ** ** If pExpect!=NULL and if no other cursors are found on the same root-page, ** then the BTCF_Multiple flag on pExpect is cleared, to avoid another ** pointless call to this routine. ** ** Implementation note: This routine merely checks to see if any cursors ** need to be saved. It calls out to saveCursorsOnList() in the (unusual) ** event that cursors are in need to being saved. */ static int saveAllCursors(BtShared *pBt, Pgno iRoot, BtCursor *pExcept){ BtCursor *p; assert( sqlite3_mutex_held(pBt->mutex) ); assert( pExcept==0 || pExcept->pBt==pBt ); for(p=pBt->pCursor; p; p=p->pNext){ if( p!=pExcept && (0==iRoot || p->pgnoRoot==iRoot) ) break; } if( p ) return saveCursorsOnList(p, iRoot, pExcept); if( pExcept ) pExcept->curFlags &= ~BTCF_Multiple; return SQLITE_OK; } /* This helper routine to saveAllCursors does the actual work of saving ** the cursors if and when a cursor is found that actually requires saving. ** The common case is that no cursors need to be saved, so this routine is ** broken out from its caller to avoid unnecessary stack pointer movement. */ static int SQLITE_NOINLINE saveCursorsOnList( BtCursor *p, /* The first cursor that needs saving */ Pgno iRoot, /* Only save cursor with this iRoot. Save all if zero */ BtCursor *pExcept /* Do not save this cursor */ ){ do{ if( p!=pExcept && (0==iRoot || p->pgnoRoot==iRoot) ){ if( p->eState==CURSOR_VALID || p->eState==CURSOR_SKIPNEXT ){ int rc = saveCursorPosition(p); if( SQLITE_OK!=rc ){ return rc; } }else{ testcase( p->iPage>0 ); btreeReleaseAllCursorPages(p); } } p = p->pNext; }while( p ); return SQLITE_OK; } /* ** Clear the current cursor position. */ SQLITE_PRIVATE void sqlite3BtreeClearCursor(BtCursor *pCur){ assert( cursorHoldsMutex(pCur) ); sqlite3_free(pCur->pKey); pCur->pKey = 0; pCur->eState = CURSOR_INVALID; } /* ** In this version of BtreeMoveto, pKey is a packed index record ** such as is generated by the OP_MakeRecord opcode. Unpack the ** record and then call BtreeMovetoUnpacked() to do the work. */ static int btreeMoveto( BtCursor *pCur, /* Cursor open on the btree to be searched */ const void *pKey, /* Packed key if the btree is an index */ i64 nKey, /* Integer key for tables. Size of pKey for indices */ int bias, /* Bias search to the high end */ int *pRes /* Write search results here */ ){ int rc; /* Status code */ UnpackedRecord *pIdxKey; /* Unpacked index key */ char aSpace[384]; /* Temp space for pIdxKey - to avoid a malloc */ char *pFree = 0; if( pKey ){ assert( nKey==(i64)(int)nKey ); pIdxKey = sqlite3VdbeAllocUnpackedRecord( pCur->pKeyInfo, aSpace, sizeof(aSpace), &pFree ); if( pIdxKey==0 ) return SQLITE_NOMEM_BKPT; sqlite3VdbeRecordUnpack(pCur->pKeyInfo, (int)nKey, pKey, pIdxKey); if( pIdxKey->nField==0 ){ sqlite3DbFree(pCur->pKeyInfo->db, pFree); return SQLITE_CORRUPT_BKPT; } }else{ pIdxKey = 0; } rc = sqlite3BtreeMovetoUnpacked(pCur, pIdxKey, nKey, bias, pRes); if( pFree ){ sqlite3DbFree(pCur->pKeyInfo->db, pFree); } return rc; } /* ** Restore the cursor to the position it was in (or as close to as possible) ** when saveCursorPosition() was called. Note that this call deletes the ** saved position info stored by saveCursorPosition(), so there can be ** at most one effective restoreCursorPosition() call after each ** saveCursorPosition(). */ static int btreeRestoreCursorPosition(BtCursor *pCur){ int rc; int skipNext; assert( cursorOwnsBtShared(pCur) ); assert( pCur->eState>=CURSOR_REQUIRESEEK ); if( pCur->eState==CURSOR_FAULT ){ return pCur->skipNext; } pCur->eState = CURSOR_INVALID; rc = btreeMoveto(pCur, pCur->pKey, pCur->nKey, 0, &skipNext); if( rc==SQLITE_OK ){ sqlite3_free(pCur->pKey); pCur->pKey = 0; assert( pCur->eState==CURSOR_VALID || pCur->eState==CURSOR_INVALID ); pCur->skipNext |= skipNext; if( pCur->skipNext && pCur->eState==CURSOR_VALID ){ pCur->eState = CURSOR_SKIPNEXT; } } return rc; } #define restoreCursorPosition(p) \ (p->eState>=CURSOR_REQUIRESEEK ? \ btreeRestoreCursorPosition(p) : \ SQLITE_OK) /* ** Determine whether or not a cursor has moved from the position where ** it was last placed, or has been invalidated for any other reason. ** Cursors can move when the row they are pointing at is deleted out ** from under them, for example. Cursor might also move if a btree ** is rebalanced. ** ** Calling this routine with a NULL cursor pointer returns false. ** ** Use the separate sqlite3BtreeCursorRestore() routine to restore a cursor ** back to where it ought to be if this routine returns true. */ SQLITE_PRIVATE int sqlite3BtreeCursorHasMoved(BtCursor *pCur){ return pCur->eState!=CURSOR_VALID; } /* ** This routine restores a cursor back to its original position after it ** has been moved by some outside activity (such as a btree rebalance or ** a row having been deleted out from under the cursor). ** ** On success, the *pDifferentRow parameter is false if the cursor is left ** pointing at exactly the same row. *pDifferntRow is the row the cursor ** was pointing to has been deleted, forcing the cursor to point to some ** nearby row. ** ** This routine should only be called for a cursor that just returned ** TRUE from sqlite3BtreeCursorHasMoved(). */ SQLITE_PRIVATE int sqlite3BtreeCursorRestore(BtCursor *pCur, int *pDifferentRow){ int rc; assert( pCur!=0 ); assert( pCur->eState!=CURSOR_VALID ); rc = restoreCursorPosition(pCur); if( rc ){ *pDifferentRow = 1; return rc; } if( pCur->eState!=CURSOR_VALID ){ *pDifferentRow = 1; }else{ assert( pCur->skipNext==0 ); *pDifferentRow = 0; } return SQLITE_OK; } #ifdef SQLITE_ENABLE_CURSOR_HINTS /* ** Provide hints to the cursor. The particular hint given (and the type ** and number of the varargs parameters) is determined by the eHintType ** parameter. See the definitions of the BTREE_HINT_* macros for details. */ SQLITE_PRIVATE void sqlite3BtreeCursorHint(BtCursor *pCur, int eHintType, ...){ /* Used only by system that substitute their own storage engine */ } #endif /* ** Provide flag hints to the cursor. */ SQLITE_PRIVATE void sqlite3BtreeCursorHintFlags(BtCursor *pCur, unsigned x){ assert( x==BTREE_SEEK_EQ || x==BTREE_BULKLOAD || x==0 ); pCur->hints = x; } #ifndef SQLITE_OMIT_AUTOVACUUM /* ** Given a page number of a regular database page, return the page ** number for the pointer-map page that contains the entry for the ** input page number. ** ** Return 0 (not a valid page) for pgno==1 since there is ** no pointer map associated with page 1. The integrity_check logic ** requires that ptrmapPageno(*,1)!=1. */ static Pgno ptrmapPageno(BtShared *pBt, Pgno pgno){ int nPagesPerMapPage; Pgno iPtrMap, ret; assert( sqlite3_mutex_held(pBt->mutex) ); if( pgno<2 ) return 0; nPagesPerMapPage = (pBt->usableSize/5)+1; iPtrMap = (pgno-2)/nPagesPerMapPage; ret = (iPtrMap*nPagesPerMapPage) + 2; if( ret==PENDING_BYTE_PAGE(pBt) ){ ret++; } return ret; } /* ** Write an entry into the pointer map. ** ** This routine updates the pointer map entry for page number 'key' ** so that it maps to type 'eType' and parent page number 'pgno'. ** ** If *pRC is initially non-zero (non-SQLITE_OK) then this routine is ** a no-op. If an error occurs, the appropriate error code is written ** into *pRC. */ static void ptrmapPut(BtShared *pBt, Pgno key, u8 eType, Pgno parent, int *pRC){ DbPage *pDbPage; /* The pointer map page */ u8 *pPtrmap; /* The pointer map data */ Pgno iPtrmap; /* The pointer map page number */ int offset; /* Offset in pointer map page */ int rc; /* Return code from subfunctions */ if( *pRC ) return; assert( sqlite3_mutex_held(pBt->mutex) ); /* The master-journal page number must never be used as a pointer map page */ assert( 0==PTRMAP_ISPAGE(pBt, PENDING_BYTE_PAGE(pBt)) ); assert( pBt->autoVacuum ); if( key==0 ){ *pRC = SQLITE_CORRUPT_BKPT; return; } iPtrmap = PTRMAP_PAGENO(pBt, key); rc = sqlite3PagerGet(pBt->pPager, iPtrmap, &pDbPage, 0); if( rc!=SQLITE_OK ){ *pRC = rc; return; } offset = PTRMAP_PTROFFSET(iPtrmap, key); if( offset<0 ){ *pRC = SQLITE_CORRUPT_BKPT; goto ptrmap_exit; } assert( offset <= (int)pBt->usableSize-5 ); pPtrmap = (u8 *)sqlite3PagerGetData(pDbPage); if( eType!=pPtrmap[offset] || get4byte(&pPtrmap[offset+1])!=parent ){ TRACE(("PTRMAP_UPDATE: %d->(%d,%d)\n", key, eType, parent)); *pRC= rc = sqlite3PagerWrite(pDbPage); if( rc==SQLITE_OK ){ pPtrmap[offset] = eType; put4byte(&pPtrmap[offset+1], parent); } } ptrmap_exit: sqlite3PagerUnref(pDbPage); } /* ** Read an entry from the pointer map. ** ** This routine retrieves the pointer map entry for page 'key', writing ** the type and parent page number to *pEType and *pPgno respectively. ** An error code is returned if something goes wrong, otherwise SQLITE_OK. */ static int ptrmapGet(BtShared *pBt, Pgno key, u8 *pEType, Pgno *pPgno){ DbPage *pDbPage; /* The pointer map page */ int iPtrmap; /* Pointer map page index */ u8 *pPtrmap; /* Pointer map page data */ int offset; /* Offset of entry in pointer map */ int rc; assert( sqlite3_mutex_held(pBt->mutex) ); iPtrmap = PTRMAP_PAGENO(pBt, key); rc = sqlite3PagerGet(pBt->pPager, iPtrmap, &pDbPage, 0); if( rc!=0 ){ return rc; } pPtrmap = (u8 *)sqlite3PagerGetData(pDbPage); offset = PTRMAP_PTROFFSET(iPtrmap, key); if( offset<0 ){ sqlite3PagerUnref(pDbPage); return SQLITE_CORRUPT_BKPT; } assert( offset <= (int)pBt->usableSize-5 ); assert( pEType!=0 ); *pEType = pPtrmap[offset]; if( pPgno ) *pPgno = get4byte(&pPtrmap[offset+1]); sqlite3PagerUnref(pDbPage); if( *pEType<1 || *pEType>5 ) return SQLITE_CORRUPT_BKPT; return SQLITE_OK; } #else /* if defined SQLITE_OMIT_AUTOVACUUM */ #define ptrmapPut(w,x,y,z,rc) #define ptrmapGet(w,x,y,z) SQLITE_OK #define ptrmapPutOvflPtr(x, y, rc) #endif /* ** Given a btree page and a cell index (0 means the first cell on ** the page, 1 means the second cell, and so forth) return a pointer ** to the cell content. ** ** findCellPastPtr() does the same except it skips past the initial ** 4-byte child pointer found on interior pages, if there is one. ** ** This routine works only for pages that do not contain overflow cells. */ #define findCell(P,I) \ ((P)->aData + ((P)->maskPage & get2byteAligned(&(P)->aCellIdx[2*(I)]))) #define findCellPastPtr(P,I) \ ((P)->aDataOfst + ((P)->maskPage & get2byteAligned(&(P)->aCellIdx[2*(I)]))) /* ** This is common tail processing for btreeParseCellPtr() and ** btreeParseCellPtrIndex() for the case when the cell does not fit entirely ** on a single B-tree page. Make necessary adjustments to the CellInfo ** structure. */ static SQLITE_NOINLINE void btreeParseCellAdjustSizeForOverflow( MemPage *pPage, /* Page containing the cell */ u8 *pCell, /* Pointer to the cell text. */ CellInfo *pInfo /* Fill in this structure */ ){ /* If the payload will not fit completely on the local page, we have ** to decide how much to store locally and how much to spill onto ** overflow pages. The strategy is to minimize the amount of unused ** space on overflow pages while keeping the amount of local storage ** in between minLocal and maxLocal. ** ** Warning: changing the way overflow payload is distributed in any ** way will result in an incompatible file format. */ int minLocal; /* Minimum amount of payload held locally */ int maxLocal; /* Maximum amount of payload held locally */ int surplus; /* Overflow payload available for local storage */ minLocal = pPage->minLocal; maxLocal = pPage->maxLocal; surplus = minLocal + (pInfo->nPayload - minLocal)%(pPage->pBt->usableSize-4); testcase( surplus==maxLocal ); testcase( surplus==maxLocal+1 ); if( surplus <= maxLocal ){ pInfo->nLocal = (u16)surplus; }else{ pInfo->nLocal = (u16)minLocal; } pInfo->nSize = (u16)(&pInfo->pPayload[pInfo->nLocal] - pCell) + 4; } /* ** The following routines are implementations of the MemPage.xParseCell() ** method. ** ** Parse a cell content block and fill in the CellInfo structure. ** ** btreeParseCellPtr() => table btree leaf nodes ** btreeParseCellNoPayload() => table btree internal nodes ** btreeParseCellPtrIndex() => index btree nodes ** ** There is also a wrapper function btreeParseCell() that works for ** all MemPage types and that references the cell by index rather than ** by pointer. */ static void btreeParseCellPtrNoPayload( MemPage *pPage, /* Page containing the cell */ u8 *pCell, /* Pointer to the cell text. */ CellInfo *pInfo /* Fill in this structure */ ){ assert( sqlite3_mutex_held(pPage->pBt->mutex) ); assert( pPage->leaf==0 ); assert( pPage->childPtrSize==4 ); #ifndef SQLITE_DEBUG UNUSED_PARAMETER(pPage); #endif pInfo->nSize = 4 + getVarint(&pCell[4], (u64*)&pInfo->nKey); pInfo->nPayload = 0; pInfo->nLocal = 0; pInfo->pPayload = 0; return; } static void btreeParseCellPtr( MemPage *pPage, /* Page containing the cell */ u8 *pCell, /* Pointer to the cell text. */ CellInfo *pInfo /* Fill in this structure */ ){ u8 *pIter; /* For scanning through pCell */ u32 nPayload; /* Number of bytes of cell payload */ u64 iKey; /* Extracted Key value */ assert( sqlite3_mutex_held(pPage->pBt->mutex) ); assert( pPage->leaf==0 || pPage->leaf==1 ); assert( pPage->intKeyLeaf ); assert( pPage->childPtrSize==0 ); pIter = pCell; /* The next block of code is equivalent to: ** ** pIter += getVarint32(pIter, nPayload); ** ** The code is inlined to avoid a function call. */ nPayload = *pIter; if( nPayload>=0x80 ){ u8 *pEnd = &pIter[8]; nPayload &= 0x7f; do{ nPayload = (nPayload<<7) | (*++pIter & 0x7f); }while( (*pIter)>=0x80 && pIternKey); ** ** The code is inlined to avoid a function call. */ iKey = *pIter; if( iKey>=0x80 ){ u8 *pEnd = &pIter[7]; iKey &= 0x7f; while(1){ iKey = (iKey<<7) | (*++pIter & 0x7f); if( (*pIter)<0x80 ) break; if( pIter>=pEnd ){ iKey = (iKey<<8) | *++pIter; break; } } } pIter++; pInfo->nKey = *(i64*)&iKey; pInfo->nPayload = nPayload; pInfo->pPayload = pIter; testcase( nPayload==pPage->maxLocal ); testcase( nPayload==pPage->maxLocal+1 ); if( nPayload<=pPage->maxLocal ){ /* This is the (easy) common case where the entire payload fits ** on the local page. No overflow is required. */ pInfo->nSize = nPayload + (u16)(pIter - pCell); if( pInfo->nSize<4 ) pInfo->nSize = 4; pInfo->nLocal = (u16)nPayload; }else{ btreeParseCellAdjustSizeForOverflow(pPage, pCell, pInfo); } } static void btreeParseCellPtrIndex( MemPage *pPage, /* Page containing the cell */ u8 *pCell, /* Pointer to the cell text. */ CellInfo *pInfo /* Fill in this structure */ ){ u8 *pIter; /* For scanning through pCell */ u32 nPayload; /* Number of bytes of cell payload */ assert( sqlite3_mutex_held(pPage->pBt->mutex) ); assert( pPage->leaf==0 || pPage->leaf==1 ); assert( pPage->intKeyLeaf==0 ); pIter = pCell + pPage->childPtrSize; nPayload = *pIter; if( nPayload>=0x80 ){ u8 *pEnd = &pIter[8]; nPayload &= 0x7f; do{ nPayload = (nPayload<<7) | (*++pIter & 0x7f); }while( *(pIter)>=0x80 && pIternKey = nPayload; pInfo->nPayload = nPayload; pInfo->pPayload = pIter; testcase( nPayload==pPage->maxLocal ); testcase( nPayload==pPage->maxLocal+1 ); if( nPayload<=pPage->maxLocal ){ /* This is the (easy) common case where the entire payload fits ** on the local page. No overflow is required. */ pInfo->nSize = nPayload + (u16)(pIter - pCell); if( pInfo->nSize<4 ) pInfo->nSize = 4; pInfo->nLocal = (u16)nPayload; }else{ btreeParseCellAdjustSizeForOverflow(pPage, pCell, pInfo); } } static void btreeParseCell( MemPage *pPage, /* Page containing the cell */ int iCell, /* The cell index. First cell is 0 */ CellInfo *pInfo /* Fill in this structure */ ){ pPage->xParseCell(pPage, findCell(pPage, iCell), pInfo); } /* ** The following routines are implementations of the MemPage.xCellSize ** method. ** ** Compute the total number of bytes that a Cell needs in the cell ** data area of the btree-page. The return number includes the cell ** data header and the local payload, but not any overflow page or ** the space used by the cell pointer. ** ** cellSizePtrNoPayload() => table internal nodes ** cellSizePtr() => all index nodes & table leaf nodes */ static u16 cellSizePtr(MemPage *pPage, u8 *pCell){ u8 *pIter = pCell + pPage->childPtrSize; /* For looping over bytes of pCell */ u8 *pEnd; /* End mark for a varint */ u32 nSize; /* Size value to return */ #ifdef SQLITE_DEBUG /* The value returned by this function should always be the same as ** the (CellInfo.nSize) value found by doing a full parse of the ** cell. If SQLITE_DEBUG is defined, an assert() at the bottom of ** this function verifies that this invariant is not violated. */ CellInfo debuginfo; pPage->xParseCell(pPage, pCell, &debuginfo); #endif nSize = *pIter; if( nSize>=0x80 ){ pEnd = &pIter[8]; nSize &= 0x7f; do{ nSize = (nSize<<7) | (*++pIter & 0x7f); }while( *(pIter)>=0x80 && pIterintKey ){ /* pIter now points at the 64-bit integer key value, a variable length ** integer. The following block moves pIter to point at the first byte ** past the end of the key value. */ pEnd = &pIter[9]; while( (*pIter++)&0x80 && pItermaxLocal ); testcase( nSize==pPage->maxLocal+1 ); if( nSize<=pPage->maxLocal ){ nSize += (u32)(pIter - pCell); if( nSize<4 ) nSize = 4; }else{ int minLocal = pPage->minLocal; nSize = minLocal + (nSize - minLocal) % (pPage->pBt->usableSize - 4); testcase( nSize==pPage->maxLocal ); testcase( nSize==pPage->maxLocal+1 ); if( nSize>pPage->maxLocal ){ nSize = minLocal; } nSize += 4 + (u16)(pIter - pCell); } assert( nSize==debuginfo.nSize || CORRUPT_DB ); return (u16)nSize; } static u16 cellSizePtrNoPayload(MemPage *pPage, u8 *pCell){ u8 *pIter = pCell + 4; /* For looping over bytes of pCell */ u8 *pEnd; /* End mark for a varint */ #ifdef SQLITE_DEBUG /* The value returned by this function should always be the same as ** the (CellInfo.nSize) value found by doing a full parse of the ** cell. If SQLITE_DEBUG is defined, an assert() at the bottom of ** this function verifies that this invariant is not violated. */ CellInfo debuginfo; pPage->xParseCell(pPage, pCell, &debuginfo); #else UNUSED_PARAMETER(pPage); #endif assert( pPage->childPtrSize==4 ); pEnd = pIter + 9; while( (*pIter++)&0x80 && pIterxCellSize(pPage, findCell(pPage, iCell)); } #endif #ifndef SQLITE_OMIT_AUTOVACUUM /* ** If the cell pCell, part of page pPage contains a pointer ** to an overflow page, insert an entry into the pointer-map ** for the overflow page. */ static void ptrmapPutOvflPtr(MemPage *pPage, u8 *pCell, int *pRC){ CellInfo info; if( *pRC ) return; assert( pCell!=0 ); pPage->xParseCell(pPage, pCell, &info); if( info.nLocalpBt, ovfl, PTRMAP_OVERFLOW1, pPage->pgno, pRC); } } #endif /* ** Defragment the page given. All Cells are moved to the ** end of the page and all free space is collected into one ** big FreeBlk that occurs in between the header and cell ** pointer array and the cell content area. ** ** EVIDENCE-OF: R-44582-60138 SQLite may from time to time reorganize a ** b-tree page so that there are no freeblocks or fragment bytes, all ** unused bytes are contained in the unallocated space region, and all ** cells are packed tightly at the end of the page. */ static int defragmentPage(MemPage *pPage){ int i; /* Loop counter */ int pc; /* Address of the i-th cell */ int hdr; /* Offset to the page header */ int size; /* Size of a cell */ int usableSize; /* Number of usable bytes on a page */ int cellOffset; /* Offset to the cell pointer array */ int cbrk; /* Offset to the cell content area */ int nCell; /* Number of cells on the page */ unsigned char *data; /* The page data */ unsigned char *temp; /* Temp area for cell content */ unsigned char *src; /* Source of content */ int iCellFirst; /* First allowable cell index */ int iCellLast; /* Last possible cell index */ assert( sqlite3PagerIswriteable(pPage->pDbPage) ); assert( pPage->pBt!=0 ); assert( pPage->pBt->usableSize <= SQLITE_MAX_PAGE_SIZE ); assert( pPage->nOverflow==0 ); assert( sqlite3_mutex_held(pPage->pBt->mutex) ); temp = 0; src = data = pPage->aData; hdr = pPage->hdrOffset; cellOffset = pPage->cellOffset; nCell = pPage->nCell; assert( nCell==get2byte(&data[hdr+3]) ); usableSize = pPage->pBt->usableSize; cbrk = usableSize; iCellFirst = cellOffset + 2*nCell; iCellLast = usableSize - 4; for(i=0; iiCellLast ){ return SQLITE_CORRUPT_BKPT; } assert( pc>=iCellFirst && pc<=iCellLast ); size = pPage->xCellSize(pPage, &src[pc]); cbrk -= size; if( cbrkusableSize ){ return SQLITE_CORRUPT_BKPT; } assert( cbrk+size<=usableSize && cbrk>=iCellFirst ); testcase( cbrk+size==usableSize ); testcase( pc+size==usableSize ); put2byte(pAddr, cbrk); if( temp==0 ){ int x; if( cbrk==pc ) continue; temp = sqlite3PagerTempSpace(pPage->pBt->pPager); x = get2byte(&data[hdr+5]); memcpy(&temp[x], &data[x], (cbrk+size) - x); src = temp; } memcpy(&data[cbrk], &src[pc], size); } assert( cbrk>=iCellFirst ); put2byte(&data[hdr+5], cbrk); data[hdr+1] = 0; data[hdr+2] = 0; data[hdr+7] = 0; memset(&data[iCellFirst], 0, cbrk-iCellFirst); assert( sqlite3PagerIswriteable(pPage->pDbPage) ); if( cbrk-iCellFirst!=pPage->nFree ){ return SQLITE_CORRUPT_BKPT; } return SQLITE_OK; } /* ** Search the free-list on page pPg for space to store a cell nByte bytes in ** size. If one can be found, return a pointer to the space and remove it ** from the free-list. ** ** If no suitable space can be found on the free-list, return NULL. ** ** This function may detect corruption within pPg. If corruption is ** detected then *pRc is set to SQLITE_CORRUPT and NULL is returned. ** ** Slots on the free list that are between 1 and 3 bytes larger than nByte ** will be ignored if adding the extra space to the fragmentation count ** causes the fragmentation count to exceed 60. */ static u8 *pageFindSlot(MemPage *pPg, int nByte, int *pRc){ const int hdr = pPg->hdrOffset; u8 * const aData = pPg->aData; int iAddr = hdr + 1; int pc = get2byte(&aData[iAddr]); int x; int usableSize = pPg->pBt->usableSize; assert( pc>0 ); do{ int size; /* Size of the free slot */ /* EVIDENCE-OF: R-06866-39125 Freeblocks are always connected in order of ** increasing offset. */ if( pc>usableSize-4 || pc=0 ){ testcase( x==4 ); testcase( x==3 ); if( pc < pPg->cellOffset+2*pPg->nCell || size+pc > usableSize ){ *pRc = SQLITE_CORRUPT_BKPT; return 0; }else if( x<4 ){ /* EVIDENCE-OF: R-11498-58022 In a well-formed b-tree page, the total ** number of bytes in fragments may not exceed 60. */ if( aData[hdr+7]>57 ) return 0; /* Remove the slot from the free-list. Update the number of ** fragmented bytes within the page. */ memcpy(&aData[iAddr], &aData[pc], 2); aData[hdr+7] += (u8)x; }else{ /* The slot remains on the free-list. Reduce its size to account ** for the portion used by the new allocation. */ put2byte(&aData[pc+2], x); } return &aData[pc + x]; } iAddr = pc; pc = get2byte(&aData[pc]); }while( pc ); return 0; } /* ** Allocate nByte bytes of space from within the B-Tree page passed ** as the first argument. Write into *pIdx the index into pPage->aData[] ** of the first byte of allocated space. Return either SQLITE_OK or ** an error code (usually SQLITE_CORRUPT). ** ** The caller guarantees that there is sufficient space to make the ** allocation. This routine might need to defragment in order to bring ** all the space together, however. This routine will avoid using ** the first two bytes past the cell pointer area since presumably this ** allocation is being made in order to insert a new cell, so we will ** also end up needing a new cell pointer. */ static int allocateSpace(MemPage *pPage, int nByte, int *pIdx){ const int hdr = pPage->hdrOffset; /* Local cache of pPage->hdrOffset */ u8 * const data = pPage->aData; /* Local cache of pPage->aData */ int top; /* First byte of cell content area */ int rc = SQLITE_OK; /* Integer return code */ int gap; /* First byte of gap between cell pointers and cell content */ assert( sqlite3PagerIswriteable(pPage->pDbPage) ); assert( pPage->pBt ); assert( sqlite3_mutex_held(pPage->pBt->mutex) ); assert( nByte>=0 ); /* Minimum cell size is 4 */ assert( pPage->nFree>=nByte ); assert( pPage->nOverflow==0 ); assert( nByte < (int)(pPage->pBt->usableSize-8) ); assert( pPage->cellOffset == hdr + 12 - 4*pPage->leaf ); gap = pPage->cellOffset + 2*pPage->nCell; assert( gap<=65536 ); /* EVIDENCE-OF: R-29356-02391 If the database uses a 65536-byte page size ** and the reserved space is zero (the usual value for reserved space) ** then the cell content offset of an empty page wants to be 65536. ** However, that integer is too large to be stored in a 2-byte unsigned ** integer, so a value of 0 is used in its place. */ top = get2byte(&data[hdr+5]); assert( top<=(int)pPage->pBt->usableSize ); /* Prevent by getAndInitPage() */ if( gap>top ){ if( top==0 && pPage->pBt->usableSize==65536 ){ top = 65536; }else{ return SQLITE_CORRUPT_BKPT; } } /* If there is enough space between gap and top for one more cell pointer ** array entry offset, and if the freelist is not empty, then search the ** freelist looking for a free slot big enough to satisfy the request. */ testcase( gap+2==top ); testcase( gap+1==top ); testcase( gap==top ); if( (data[hdr+2] || data[hdr+1]) && gap+2<=top ){ u8 *pSpace = pageFindSlot(pPage, nByte, &rc); if( pSpace ){ assert( pSpace>=data && (pSpace - data)<65536 ); *pIdx = (int)(pSpace - data); return SQLITE_OK; }else if( rc ){ return rc; } } /* The request could not be fulfilled using a freelist slot. Check ** to see if defragmentation is necessary. */ testcase( gap+2+nByte==top ); if( gap+2+nByte>top ){ assert( pPage->nCell>0 || CORRUPT_DB ); rc = defragmentPage(pPage); if( rc ) return rc; top = get2byteNotZero(&data[hdr+5]); assert( gap+nByte<=top ); } /* Allocate memory from the gap in between the cell pointer array ** and the cell content area. The btreeInitPage() call has already ** validated the freelist. Given that the freelist is valid, there ** is no way that the allocation can extend off the end of the page. ** The assert() below verifies the previous sentence. */ top -= nByte; put2byte(&data[hdr+5], top); assert( top+nByte <= (int)pPage->pBt->usableSize ); *pIdx = top; return SQLITE_OK; } /* ** Return a section of the pPage->aData to the freelist. ** The first byte of the new free block is pPage->aData[iStart] ** and the size of the block is iSize bytes. ** ** Adjacent freeblocks are coalesced. ** ** Note that even though the freeblock list was checked by btreeInitPage(), ** that routine will not detect overlap between cells or freeblocks. Nor ** does it detect cells or freeblocks that encrouch into the reserved bytes ** at the end of the page. So do additional corruption checks inside this ** routine and return SQLITE_CORRUPT if any problems are found. */ static int freeSpace(MemPage *pPage, u16 iStart, u16 iSize){ u16 iPtr; /* Address of ptr to next freeblock */ u16 iFreeBlk; /* Address of the next freeblock */ u8 hdr; /* Page header size. 0 or 100 */ u8 nFrag = 0; /* Reduction in fragmentation */ u16 iOrigSize = iSize; /* Original value of iSize */ u32 iLast = pPage->pBt->usableSize-4; /* Largest possible freeblock offset */ u32 iEnd = iStart + iSize; /* First byte past the iStart buffer */ unsigned char *data = pPage->aData; /* Page content */ assert( pPage->pBt!=0 ); assert( sqlite3PagerIswriteable(pPage->pDbPage) ); assert( CORRUPT_DB || iStart>=pPage->hdrOffset+6+pPage->childPtrSize ); assert( CORRUPT_DB || iEnd <= pPage->pBt->usableSize ); assert( sqlite3_mutex_held(pPage->pBt->mutex) ); assert( iSize>=4 ); /* Minimum cell size is 4 */ assert( iStart<=iLast ); /* Overwrite deleted information with zeros when the secure_delete ** option is enabled */ if( pPage->pBt->btsFlags & BTS_SECURE_DELETE ){ memset(&data[iStart], 0, iSize); } /* The list of freeblocks must be in ascending order. Find the ** spot on the list where iStart should be inserted. */ hdr = pPage->hdrOffset; iPtr = hdr + 1; if( data[iPtr+1]==0 && data[iPtr]==0 ){ iFreeBlk = 0; /* Shortcut for the case when the freelist is empty */ }else{ while( (iFreeBlk = get2byte(&data[iPtr]))iLast ) return SQLITE_CORRUPT_BKPT; assert( iFreeBlk>iPtr || iFreeBlk==0 ); /* At this point: ** iFreeBlk: First freeblock after iStart, or zero if none ** iPtr: The address of a pointer to iFreeBlk ** ** Check to see if iFreeBlk should be coalesced onto the end of iStart. */ if( iFreeBlk && iEnd+3>=iFreeBlk ){ nFrag = iFreeBlk - iEnd; if( iEnd>iFreeBlk ) return SQLITE_CORRUPT_BKPT; iEnd = iFreeBlk + get2byte(&data[iFreeBlk+2]); if( iEnd > pPage->pBt->usableSize ) return SQLITE_CORRUPT_BKPT; iSize = iEnd - iStart; iFreeBlk = get2byte(&data[iFreeBlk]); } /* If iPtr is another freeblock (that is, if iPtr is not the freelist ** pointer in the page header) then check to see if iStart should be ** coalesced onto the end of iPtr. */ if( iPtr>hdr+1 ){ int iPtrEnd = iPtr + get2byte(&data[iPtr+2]); if( iPtrEnd+3>=iStart ){ if( iPtrEnd>iStart ) return SQLITE_CORRUPT_BKPT; nFrag += iStart - iPtrEnd; iSize = iEnd - iPtr; iStart = iPtr; } } if( nFrag>data[hdr+7] ) return SQLITE_CORRUPT_BKPT; data[hdr+7] -= nFrag; } if( iStart==get2byte(&data[hdr+5]) ){ /* The new freeblock is at the beginning of the cell content area, ** so just extend the cell content area rather than create another ** freelist entry */ if( iPtr!=hdr+1 ) return SQLITE_CORRUPT_BKPT; put2byte(&data[hdr+1], iFreeBlk); put2byte(&data[hdr+5], iEnd); }else{ /* Insert the new freeblock into the freelist */ put2byte(&data[iPtr], iStart); put2byte(&data[iStart], iFreeBlk); put2byte(&data[iStart+2], iSize); } pPage->nFree += iOrigSize; return SQLITE_OK; } /* ** Decode the flags byte (the first byte of the header) for a page ** and initialize fields of the MemPage structure accordingly. ** ** Only the following combinations are supported. Anything different ** indicates a corrupt database files: ** ** PTF_ZERODATA ** PTF_ZERODATA | PTF_LEAF ** PTF_LEAFDATA | PTF_INTKEY ** PTF_LEAFDATA | PTF_INTKEY | PTF_LEAF */ static int decodeFlags(MemPage *pPage, int flagByte){ BtShared *pBt; /* A copy of pPage->pBt */ assert( pPage->hdrOffset==(pPage->pgno==1 ? 100 : 0) ); assert( sqlite3_mutex_held(pPage->pBt->mutex) ); pPage->leaf = (u8)(flagByte>>3); assert( PTF_LEAF == 1<<3 ); flagByte &= ~PTF_LEAF; pPage->childPtrSize = 4-4*pPage->leaf; pPage->xCellSize = cellSizePtr; pBt = pPage->pBt; if( flagByte==(PTF_LEAFDATA | PTF_INTKEY) ){ /* EVIDENCE-OF: R-07291-35328 A value of 5 (0x05) means the page is an ** interior table b-tree page. */ assert( (PTF_LEAFDATA|PTF_INTKEY)==5 ); /* EVIDENCE-OF: R-26900-09176 A value of 13 (0x0d) means the page is a ** leaf table b-tree page. */ assert( (PTF_LEAFDATA|PTF_INTKEY|PTF_LEAF)==13 ); pPage->intKey = 1; if( pPage->leaf ){ pPage->intKeyLeaf = 1; pPage->xParseCell = btreeParseCellPtr; }else{ pPage->intKeyLeaf = 0; pPage->xCellSize = cellSizePtrNoPayload; pPage->xParseCell = btreeParseCellPtrNoPayload; } pPage->maxLocal = pBt->maxLeaf; pPage->minLocal = pBt->minLeaf; }else if( flagByte==PTF_ZERODATA ){ /* EVIDENCE-OF: R-43316-37308 A value of 2 (0x02) means the page is an ** interior index b-tree page. */ assert( (PTF_ZERODATA)==2 ); /* EVIDENCE-OF: R-59615-42828 A value of 10 (0x0a) means the page is a ** leaf index b-tree page. */ assert( (PTF_ZERODATA|PTF_LEAF)==10 ); pPage->intKey = 0; pPage->intKeyLeaf = 0; pPage->xParseCell = btreeParseCellPtrIndex; pPage->maxLocal = pBt->maxLocal; pPage->minLocal = pBt->minLocal; }else{ /* EVIDENCE-OF: R-47608-56469 Any other value for the b-tree page type is ** an error. */ return SQLITE_CORRUPT_BKPT; } pPage->max1bytePayload = pBt->max1bytePayload; return SQLITE_OK; } /* ** Initialize the auxiliary information for a disk block. ** ** Return SQLITE_OK on success. If we see that the page does ** not contain a well-formed database page, then return ** SQLITE_CORRUPT. Note that a return of SQLITE_OK does not ** guarantee that the page is well-formed. It only shows that ** we failed to detect any corruption. */ static int btreeInitPage(MemPage *pPage){ assert( pPage->pBt!=0 ); assert( pPage->pBt->db!=0 ); assert( sqlite3_mutex_held(pPage->pBt->mutex) ); assert( pPage->pgno==sqlite3PagerPagenumber(pPage->pDbPage) ); assert( pPage == sqlite3PagerGetExtra(pPage->pDbPage) ); assert( pPage->aData == sqlite3PagerGetData(pPage->pDbPage) ); if( !pPage->isInit ){ u16 pc; /* Address of a freeblock within pPage->aData[] */ u8 hdr; /* Offset to beginning of page header */ u8 *data; /* Equal to pPage->aData */ BtShared *pBt; /* The main btree structure */ int usableSize; /* Amount of usable space on each page */ u16 cellOffset; /* Offset from start of page to first cell pointer */ int nFree; /* Number of unused bytes on the page */ int top; /* First byte of the cell content area */ int iCellFirst; /* First allowable cell or freeblock offset */ int iCellLast; /* Last possible cell or freeblock offset */ pBt = pPage->pBt; hdr = pPage->hdrOffset; data = pPage->aData; /* EVIDENCE-OF: R-28594-02890 The one-byte flag at offset 0 indicating ** the b-tree page type. */ if( decodeFlags(pPage, data[hdr]) ) return SQLITE_CORRUPT_BKPT; assert( pBt->pageSize>=512 && pBt->pageSize<=65536 ); pPage->maskPage = (u16)(pBt->pageSize - 1); pPage->nOverflow = 0; usableSize = pBt->usableSize; pPage->cellOffset = cellOffset = hdr + 8 + pPage->childPtrSize; pPage->aDataEnd = &data[usableSize]; pPage->aCellIdx = &data[cellOffset]; pPage->aDataOfst = &data[pPage->childPtrSize]; /* EVIDENCE-OF: R-58015-48175 The two-byte integer at offset 5 designates ** the start of the cell content area. A zero value for this integer is ** interpreted as 65536. */ top = get2byteNotZero(&data[hdr+5]); /* EVIDENCE-OF: R-37002-32774 The two-byte integer at offset 3 gives the ** number of cells on the page. */ pPage->nCell = get2byte(&data[hdr+3]); if( pPage->nCell>MX_CELL(pBt) ){ /* To many cells for a single page. The page must be corrupt */ return SQLITE_CORRUPT_BKPT; } testcase( pPage->nCell==MX_CELL(pBt) ); /* EVIDENCE-OF: R-24089-57979 If a page contains no cells (which is only ** possible for a root page of a table that contains no rows) then the ** offset to the cell content area will equal the page size minus the ** bytes of reserved space. */ assert( pPage->nCell>0 || top==usableSize || CORRUPT_DB ); /* A malformed database page might cause us to read past the end ** of page when parsing a cell. ** ** The following block of code checks early to see if a cell extends ** past the end of a page boundary and causes SQLITE_CORRUPT to be ** returned if it does. */ iCellFirst = cellOffset + 2*pPage->nCell; iCellLast = usableSize - 4; if( pBt->db->flags & SQLITE_CellSizeCk ){ int i; /* Index into the cell pointer array */ int sz; /* Size of a cell */ if( !pPage->leaf ) iCellLast--; for(i=0; inCell; i++){ pc = get2byteAligned(&data[cellOffset+i*2]); testcase( pc==iCellFirst ); testcase( pc==iCellLast ); if( pciCellLast ){ return SQLITE_CORRUPT_BKPT; } sz = pPage->xCellSize(pPage, &data[pc]); testcase( pc+sz==usableSize ); if( pc+sz>usableSize ){ return SQLITE_CORRUPT_BKPT; } } if( !pPage->leaf ) iCellLast++; } /* Compute the total free space on the page ** EVIDENCE-OF: R-23588-34450 The two-byte integer at offset 1 gives the ** start of the first freeblock on the page, or is zero if there are no ** freeblocks. */ pc = get2byte(&data[hdr+1]); nFree = data[hdr+7] + top; /* Init nFree to non-freeblock free space */ while( pc>0 ){ u16 next, size; if( pciCellLast ){ /* EVIDENCE-OF: R-55530-52930 In a well-formed b-tree page, there will ** always be at least one cell before the first freeblock. ** ** Or, the freeblock is off the end of the page */ return SQLITE_CORRUPT_BKPT; } next = get2byte(&data[pc]); size = get2byte(&data[pc+2]); if( (next>0 && next<=pc+size+3) || pc+size>usableSize ){ /* Free blocks must be in ascending order. And the last byte of ** the free-block must lie on the database page. */ return SQLITE_CORRUPT_BKPT; } nFree = nFree + size; pc = next; } /* At this point, nFree contains the sum of the offset to the start ** of the cell-content area plus the number of free bytes within ** the cell-content area. If this is greater than the usable-size ** of the page, then the page must be corrupted. This check also ** serves to verify that the offset to the start of the cell-content ** area, according to the page header, lies within the page. */ if( nFree>usableSize ){ return SQLITE_CORRUPT_BKPT; } pPage->nFree = (u16)(nFree - iCellFirst); pPage->isInit = 1; } return SQLITE_OK; } /* ** Set up a raw page so that it looks like a database page holding ** no entries. */ static void zeroPage(MemPage *pPage, int flags){ unsigned char *data = pPage->aData; BtShared *pBt = pPage->pBt; u8 hdr = pPage->hdrOffset; u16 first; assert( sqlite3PagerPagenumber(pPage->pDbPage)==pPage->pgno ); assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage ); assert( sqlite3PagerGetData(pPage->pDbPage) == data ); assert( sqlite3PagerIswriteable(pPage->pDbPage) ); assert( sqlite3_mutex_held(pBt->mutex) ); if( pBt->btsFlags & BTS_SECURE_DELETE ){ memset(&data[hdr], 0, pBt->usableSize - hdr); } data[hdr] = (char)flags; first = hdr + ((flags&PTF_LEAF)==0 ? 12 : 8); memset(&data[hdr+1], 0, 4); data[hdr+7] = 0; put2byte(&data[hdr+5], pBt->usableSize); pPage->nFree = (u16)(pBt->usableSize - first); decodeFlags(pPage, flags); pPage->cellOffset = first; pPage->aDataEnd = &data[pBt->usableSize]; pPage->aCellIdx = &data[first]; pPage->aDataOfst = &data[pPage->childPtrSize]; pPage->nOverflow = 0; assert( pBt->pageSize>=512 && pBt->pageSize<=65536 ); pPage->maskPage = (u16)(pBt->pageSize - 1); pPage->nCell = 0; pPage->isInit = 1; } /* ** Convert a DbPage obtained from the pager into a MemPage used by ** the btree layer. */ static MemPage *btreePageFromDbPage(DbPage *pDbPage, Pgno pgno, BtShared *pBt){ MemPage *pPage = (MemPage*)sqlite3PagerGetExtra(pDbPage); if( pgno!=pPage->pgno ){ pPage->aData = sqlite3PagerGetData(pDbPage); pPage->pDbPage = pDbPage; pPage->pBt = pBt; pPage->pgno = pgno; pPage->hdrOffset = pgno==1 ? 100 : 0; } assert( pPage->aData==sqlite3PagerGetData(pDbPage) ); return pPage; } /* ** Get a page from the pager. Initialize the MemPage.pBt and ** MemPage.aData elements if needed. See also: btreeGetUnusedPage(). ** ** If the PAGER_GET_NOCONTENT flag is set, it means that we do not care ** about the content of the page at this time. So do not go to the disk ** to fetch the content. Just fill in the content with zeros for now. ** If in the future we call sqlite3PagerWrite() on this page, that ** means we have started to be concerned about content and the disk ** read should occur at that point. */ static int btreeGetPage( BtShared *pBt, /* The btree */ Pgno pgno, /* Number of the page to fetch */ MemPage **ppPage, /* Return the page in this parameter */ int flags /* PAGER_GET_NOCONTENT or PAGER_GET_READONLY */ ){ int rc; DbPage *pDbPage; assert( flags==0 || flags==PAGER_GET_NOCONTENT || flags==PAGER_GET_READONLY ); assert( sqlite3_mutex_held(pBt->mutex) ); rc = sqlite3PagerGet(pBt->pPager, pgno, (DbPage**)&pDbPage, flags); if( rc ) return rc; *ppPage = btreePageFromDbPage(pDbPage, pgno, pBt); return SQLITE_OK; } /* ** Retrieve a page from the pager cache. If the requested page is not ** already in the pager cache return NULL. Initialize the MemPage.pBt and ** MemPage.aData elements if needed. */ static MemPage *btreePageLookup(BtShared *pBt, Pgno pgno){ DbPage *pDbPage; assert( sqlite3_mutex_held(pBt->mutex) ); pDbPage = sqlite3PagerLookup(pBt->pPager, pgno); if( pDbPage ){ return btreePageFromDbPage(pDbPage, pgno, pBt); } return 0; } /* ** Return the size of the database file in pages. If there is any kind of ** error, return ((unsigned int)-1). */ static Pgno btreePagecount(BtShared *pBt){ return pBt->nPage; } SQLITE_PRIVATE u32 sqlite3BtreeLastPage(Btree *p){ assert( sqlite3BtreeHoldsMutex(p) ); assert( ((p->pBt->nPage)&0x8000000)==0 ); return btreePagecount(p->pBt); } /* ** Get a page from the pager and initialize it. ** ** If pCur!=0 then the page is being fetched as part of a moveToChild() ** call. Do additional sanity checking on the page in this case. ** And if the fetch fails, this routine must decrement pCur->iPage. ** ** The page is fetched as read-write unless pCur is not NULL and is ** a read-only cursor. ** ** If an error occurs, then *ppPage is undefined. It ** may remain unchanged, or it may be set to an invalid value. */ static int getAndInitPage( BtShared *pBt, /* The database file */ Pgno pgno, /* Number of the page to get */ MemPage **ppPage, /* Write the page pointer here */ BtCursor *pCur, /* Cursor to receive the page, or NULL */ int bReadOnly /* True for a read-only page */ ){ int rc; DbPage *pDbPage; assert( sqlite3_mutex_held(pBt->mutex) ); assert( pCur==0 || ppPage==&pCur->apPage[pCur->iPage] ); assert( pCur==0 || bReadOnly==pCur->curPagerFlags ); assert( pCur==0 || pCur->iPage>0 ); if( pgno>btreePagecount(pBt) ){ rc = SQLITE_CORRUPT_BKPT; goto getAndInitPage_error; } rc = sqlite3PagerGet(pBt->pPager, pgno, (DbPage**)&pDbPage, bReadOnly); if( rc ){ goto getAndInitPage_error; } *ppPage = (MemPage*)sqlite3PagerGetExtra(pDbPage); if( (*ppPage)->isInit==0 ){ btreePageFromDbPage(pDbPage, pgno, pBt); rc = btreeInitPage(*ppPage); if( rc!=SQLITE_OK ){ releasePage(*ppPage); goto getAndInitPage_error; } } assert( (*ppPage)->pgno==pgno ); assert( (*ppPage)->aData==sqlite3PagerGetData(pDbPage) ); /* If obtaining a child page for a cursor, we must verify that the page is ** compatible with the root page. */ if( pCur && ((*ppPage)->nCell<1 || (*ppPage)->intKey!=pCur->curIntKey) ){ rc = SQLITE_CORRUPT_BKPT; releasePage(*ppPage); goto getAndInitPage_error; } return SQLITE_OK; getAndInitPage_error: if( pCur ) pCur->iPage--; testcase( pgno==0 ); assert( pgno!=0 || rc==SQLITE_CORRUPT ); return rc; } /* ** Release a MemPage. This should be called once for each prior ** call to btreeGetPage. */ static void releasePageNotNull(MemPage *pPage){ assert( pPage->aData ); assert( pPage->pBt ); assert( pPage->pDbPage!=0 ); assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage ); assert( sqlite3PagerGetData(pPage->pDbPage)==pPage->aData ); assert( sqlite3_mutex_held(pPage->pBt->mutex) ); sqlite3PagerUnrefNotNull(pPage->pDbPage); } static void releasePage(MemPage *pPage){ if( pPage ) releasePageNotNull(pPage); } /* ** Get an unused page. ** ** This works just like btreeGetPage() with the addition: ** ** * If the page is already in use for some other purpose, immediately ** release it and return an SQLITE_CURRUPT error. ** * Make sure the isInit flag is clear */ static int btreeGetUnusedPage( BtShared *pBt, /* The btree */ Pgno pgno, /* Number of the page to fetch */ MemPage **ppPage, /* Return the page in this parameter */ int flags /* PAGER_GET_NOCONTENT or PAGER_GET_READONLY */ ){ int rc = btreeGetPage(pBt, pgno, ppPage, flags); if( rc==SQLITE_OK ){ if( sqlite3PagerPageRefcount((*ppPage)->pDbPage)>1 ){ releasePage(*ppPage); *ppPage = 0; return SQLITE_CORRUPT_BKPT; } (*ppPage)->isInit = 0; }else{ *ppPage = 0; } return rc; } /* ** During a rollback, when the pager reloads information into the cache ** so that the cache is restored to its original state at the start of ** the transaction, for each page restored this routine is called. ** ** This routine needs to reset the extra data section at the end of the ** page to agree with the restored data. */ static void pageReinit(DbPage *pData){ MemPage *pPage; pPage = (MemPage *)sqlite3PagerGetExtra(pData); assert( sqlite3PagerPageRefcount(pData)>0 ); if( pPage->isInit ){ assert( sqlite3_mutex_held(pPage->pBt->mutex) ); pPage->isInit = 0; if( sqlite3PagerPageRefcount(pData)>1 ){ /* pPage might not be a btree page; it might be an overflow page ** or ptrmap page or a free page. In those cases, the following ** call to btreeInitPage() will likely return SQLITE_CORRUPT. ** But no harm is done by this. And it is very important that ** btreeInitPage() be called on every btree page so we make ** the call for every page that comes in for re-initing. */ btreeInitPage(pPage); } } } /* ** Invoke the busy handler for a btree. */ static int btreeInvokeBusyHandler(void *pArg){ BtShared *pBt = (BtShared*)pArg; assert( pBt->db ); assert( sqlite3_mutex_held(pBt->db->mutex) ); return sqlite3InvokeBusyHandler(&pBt->db->busyHandler); } /* ** Open a database file. ** ** zFilename is the name of the database file. If zFilename is NULL ** then an ephemeral database is created. The ephemeral database might ** be exclusively in memory, or it might use a disk-based memory cache. ** Either way, the ephemeral database will be automatically deleted ** when sqlite3BtreeClose() is called. ** ** If zFilename is ":memory:" then an in-memory database is created ** that is automatically destroyed when it is closed. ** ** The "flags" parameter is a bitmask that might contain bits like ** BTREE_OMIT_JOURNAL and/or BTREE_MEMORY. ** ** If the database is already opened in the same database connection ** and we are in shared cache mode, then the open will fail with an ** SQLITE_CONSTRAINT error. We cannot allow two or more BtShared ** objects in the same database connection since doing so will lead ** to problems with locking. */ SQLITE_PRIVATE int sqlite3BtreeOpen( sqlite3_vfs *pVfs, /* VFS to use for this b-tree */ const char *zFilename, /* Name of the file containing the BTree database */ sqlite3 *db, /* Associated database handle */ Btree **ppBtree, /* Pointer to new Btree object written here */ int flags, /* Options */ int vfsFlags /* Flags passed through to sqlite3_vfs.xOpen() */ ){ BtShared *pBt = 0; /* Shared part of btree structure */ Btree *p; /* Handle to return */ sqlite3_mutex *mutexOpen = 0; /* Prevents a race condition. Ticket #3537 */ int rc = SQLITE_OK; /* Result code from this function */ u8 nReserve; /* Byte of unused space on each page */ unsigned char zDbHeader[100]; /* Database header content */ /* True if opening an ephemeral, temporary database */ const int isTempDb = zFilename==0 || zFilename[0]==0; /* Set the variable isMemdb to true for an in-memory database, or ** false for a file-based database. */ #ifdef SQLITE_OMIT_MEMORYDB const int isMemdb = 0; #else const int isMemdb = (zFilename && strcmp(zFilename, ":memory:")==0) || (isTempDb && sqlite3TempInMemory(db)) || (vfsFlags & SQLITE_OPEN_MEMORY)!=0; #endif assert( db!=0 ); assert( pVfs!=0 ); assert( sqlite3_mutex_held(db->mutex) ); assert( (flags&0xff)==flags ); /* flags fit in 8 bits */ /* Only a BTREE_SINGLE database can be BTREE_UNORDERED */ assert( (flags & BTREE_UNORDERED)==0 || (flags & BTREE_SINGLE)!=0 ); /* A BTREE_SINGLE database is always a temporary and/or ephemeral */ assert( (flags & BTREE_SINGLE)==0 || isTempDb ); if( isMemdb ){ flags |= BTREE_MEMORY; } if( (vfsFlags & SQLITE_OPEN_MAIN_DB)!=0 && (isMemdb || isTempDb) ){ vfsFlags = (vfsFlags & ~SQLITE_OPEN_MAIN_DB) | SQLITE_OPEN_TEMP_DB; } p = sqlite3MallocZero(sizeof(Btree)); if( !p ){ return SQLITE_NOMEM_BKPT; } p->inTrans = TRANS_NONE; p->db = db; #ifndef SQLITE_OMIT_SHARED_CACHE p->lock.pBtree = p; p->lock.iTable = 1; #endif #if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO) /* ** If this Btree is a candidate for shared cache, try to find an ** existing BtShared object that we can share with */ if( isTempDb==0 && (isMemdb==0 || (vfsFlags&SQLITE_OPEN_URI)!=0) ){ if( vfsFlags & SQLITE_OPEN_SHAREDCACHE ){ int nFilename = sqlite3Strlen30(zFilename)+1; int nFullPathname = pVfs->mxPathname+1; char *zFullPathname = sqlite3Malloc(MAX(nFullPathname,nFilename)); MUTEX_LOGIC( sqlite3_mutex *mutexShared; ) p->sharable = 1; if( !zFullPathname ){ sqlite3_free(p); return SQLITE_NOMEM_BKPT; } if( isMemdb ){ memcpy(zFullPathname, zFilename, nFilename); }else{ rc = sqlite3OsFullPathname(pVfs, zFilename, nFullPathname, zFullPathname); if( rc ){ sqlite3_free(zFullPathname); sqlite3_free(p); return rc; } } #if SQLITE_THREADSAFE mutexOpen = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_OPEN); sqlite3_mutex_enter(mutexOpen); mutexShared = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); sqlite3_mutex_enter(mutexShared); #endif for(pBt=GLOBAL(BtShared*,sqlite3SharedCacheList); pBt; pBt=pBt->pNext){ assert( pBt->nRef>0 ); if( 0==strcmp(zFullPathname, sqlite3PagerFilename(pBt->pPager, 0)) && sqlite3PagerVfs(pBt->pPager)==pVfs ){ int iDb; for(iDb=db->nDb-1; iDb>=0; iDb--){ Btree *pExisting = db->aDb[iDb].pBt; if( pExisting && pExisting->pBt==pBt ){ sqlite3_mutex_leave(mutexShared); sqlite3_mutex_leave(mutexOpen); sqlite3_free(zFullPathname); sqlite3_free(p); return SQLITE_CONSTRAINT; } } p->pBt = pBt; pBt->nRef++; break; } } sqlite3_mutex_leave(mutexShared); sqlite3_free(zFullPathname); } #ifdef SQLITE_DEBUG else{ /* In debug mode, we mark all persistent databases as sharable ** even when they are not. This exercises the locking code and ** gives more opportunity for asserts(sqlite3_mutex_held()) ** statements to find locking problems. */ p->sharable = 1; } #endif } #endif if( pBt==0 ){ /* ** The following asserts make sure that structures used by the btree are ** the right size. This is to guard against size changes that result ** when compiling on a different architecture. */ assert( sizeof(i64)==8 ); assert( sizeof(u64)==8 ); assert( sizeof(u32)==4 ); assert( sizeof(u16)==2 ); assert( sizeof(Pgno)==4 ); pBt = sqlite3MallocZero( sizeof(*pBt) ); if( pBt==0 ){ rc = SQLITE_NOMEM_BKPT; goto btree_open_out; } rc = sqlite3PagerOpen(pVfs, &pBt->pPager, zFilename, EXTRA_SIZE, flags, vfsFlags, pageReinit); if( rc==SQLITE_OK ){ sqlite3PagerSetMmapLimit(pBt->pPager, db->szMmap); rc = sqlite3PagerReadFileheader(pBt->pPager,sizeof(zDbHeader),zDbHeader); } if( rc!=SQLITE_OK ){ goto btree_open_out; } pBt->openFlags = (u8)flags; pBt->db = db; sqlite3PagerSetBusyhandler(pBt->pPager, btreeInvokeBusyHandler, pBt); p->pBt = pBt; pBt->pCursor = 0; pBt->pPage1 = 0; if( sqlite3PagerIsreadonly(pBt->pPager) ) pBt->btsFlags |= BTS_READ_ONLY; #ifdef SQLITE_SECURE_DELETE pBt->btsFlags |= BTS_SECURE_DELETE; #endif /* EVIDENCE-OF: R-51873-39618 The page size for a database file is ** determined by the 2-byte integer located at an offset of 16 bytes from ** the beginning of the database file. */ pBt->pageSize = (zDbHeader[16]<<8) | (zDbHeader[17]<<16); if( pBt->pageSize<512 || pBt->pageSize>SQLITE_MAX_PAGE_SIZE || ((pBt->pageSize-1)&pBt->pageSize)!=0 ){ pBt->pageSize = 0; #ifndef SQLITE_OMIT_AUTOVACUUM /* If the magic name ":memory:" will create an in-memory database, then ** leave the autoVacuum mode at 0 (do not auto-vacuum), even if ** SQLITE_DEFAULT_AUTOVACUUM is true. On the other hand, if ** SQLITE_OMIT_MEMORYDB has been defined, then ":memory:" is just a ** regular file-name. In this case the auto-vacuum applies as per normal. */ if( zFilename && !isMemdb ){ pBt->autoVacuum = (SQLITE_DEFAULT_AUTOVACUUM ? 1 : 0); pBt->incrVacuum = (SQLITE_DEFAULT_AUTOVACUUM==2 ? 1 : 0); } #endif nReserve = 0; }else{ /* EVIDENCE-OF: R-37497-42412 The size of the reserved region is ** determined by the one-byte unsigned integer found at an offset of 20 ** into the database file header. */ nReserve = zDbHeader[20]; pBt->btsFlags |= BTS_PAGESIZE_FIXED; #ifndef SQLITE_OMIT_AUTOVACUUM pBt->autoVacuum = (get4byte(&zDbHeader[36 + 4*4])?1:0); pBt->incrVacuum = (get4byte(&zDbHeader[36 + 7*4])?1:0); #endif } rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize, nReserve); if( rc ) goto btree_open_out; pBt->usableSize = pBt->pageSize - nReserve; assert( (pBt->pageSize & 7)==0 ); /* 8-byte alignment of pageSize */ #if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO) /* Add the new BtShared object to the linked list sharable BtShareds. */ pBt->nRef = 1; if( p->sharable ){ MUTEX_LOGIC( sqlite3_mutex *mutexShared; ) MUTEX_LOGIC( mutexShared = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);) if( SQLITE_THREADSAFE && sqlite3GlobalConfig.bCoreMutex ){ pBt->mutex = sqlite3MutexAlloc(SQLITE_MUTEX_FAST); if( pBt->mutex==0 ){ rc = SQLITE_NOMEM_BKPT; goto btree_open_out; } } sqlite3_mutex_enter(mutexShared); pBt->pNext = GLOBAL(BtShared*,sqlite3SharedCacheList); GLOBAL(BtShared*,sqlite3SharedCacheList) = pBt; sqlite3_mutex_leave(mutexShared); } #endif } #if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO) /* If the new Btree uses a sharable pBtShared, then link the new ** Btree into the list of all sharable Btrees for the same connection. ** The list is kept in ascending order by pBt address. */ if( p->sharable ){ int i; Btree *pSib; for(i=0; inDb; i++){ if( (pSib = db->aDb[i].pBt)!=0 && pSib->sharable ){ while( pSib->pPrev ){ pSib = pSib->pPrev; } if( (uptr)p->pBt<(uptr)pSib->pBt ){ p->pNext = pSib; p->pPrev = 0; pSib->pPrev = p; }else{ while( pSib->pNext && (uptr)pSib->pNext->pBt<(uptr)p->pBt ){ pSib = pSib->pNext; } p->pNext = pSib->pNext; p->pPrev = pSib; if( p->pNext ){ p->pNext->pPrev = p; } pSib->pNext = p; } break; } } } #endif *ppBtree = p; btree_open_out: if( rc!=SQLITE_OK ){ if( pBt && pBt->pPager ){ sqlite3PagerClose(pBt->pPager); } sqlite3_free(pBt); sqlite3_free(p); *ppBtree = 0; }else{ /* If the B-Tree was successfully opened, set the pager-cache size to the ** default value. Except, when opening on an existing shared pager-cache, ** do not change the pager-cache size. */ if( sqlite3BtreeSchema(p, 0, 0)==0 ){ sqlite3PagerSetCachesize(p->pBt->pPager, SQLITE_DEFAULT_CACHE_SIZE); } } if( mutexOpen ){ assert( sqlite3_mutex_held(mutexOpen) ); sqlite3_mutex_leave(mutexOpen); } assert( rc!=SQLITE_OK || sqlite3BtreeConnectionCount(*ppBtree)>0 ); return rc; } /* ** Decrement the BtShared.nRef counter. When it reaches zero, ** remove the BtShared structure from the sharing list. Return ** true if the BtShared.nRef counter reaches zero and return ** false if it is still positive. */ static int removeFromSharingList(BtShared *pBt){ #ifndef SQLITE_OMIT_SHARED_CACHE MUTEX_LOGIC( sqlite3_mutex *pMaster; ) BtShared *pList; int removed = 0; assert( sqlite3_mutex_notheld(pBt->mutex) ); MUTEX_LOGIC( pMaster = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); ) sqlite3_mutex_enter(pMaster); pBt->nRef--; if( pBt->nRef<=0 ){ if( GLOBAL(BtShared*,sqlite3SharedCacheList)==pBt ){ GLOBAL(BtShared*,sqlite3SharedCacheList) = pBt->pNext; }else{ pList = GLOBAL(BtShared*,sqlite3SharedCacheList); while( ALWAYS(pList) && pList->pNext!=pBt ){ pList=pList->pNext; } if( ALWAYS(pList) ){ pList->pNext = pBt->pNext; } } if( SQLITE_THREADSAFE ){ sqlite3_mutex_free(pBt->mutex); } removed = 1; } sqlite3_mutex_leave(pMaster); return removed; #else return 1; #endif } /* ** Make sure pBt->pTmpSpace points to an allocation of ** MX_CELL_SIZE(pBt) bytes with a 4-byte prefix for a left-child ** pointer. */ static void allocateTempSpace(BtShared *pBt){ if( !pBt->pTmpSpace ){ pBt->pTmpSpace = sqlite3PageMalloc( pBt->pageSize ); /* One of the uses of pBt->pTmpSpace is to format cells before ** inserting them into a leaf page (function fillInCell()). If ** a cell is less than 4 bytes in size, it is rounded up to 4 bytes ** by the various routines that manipulate binary cells. Which ** can mean that fillInCell() only initializes the first 2 or 3 ** bytes of pTmpSpace, but that the first 4 bytes are copied from ** it into a database page. This is not actually a problem, but it ** does cause a valgrind error when the 1 or 2 bytes of unitialized ** data is passed to system call write(). So to avoid this error, ** zero the first 4 bytes of temp space here. ** ** Also: Provide four bytes of initialized space before the ** beginning of pTmpSpace as an area available to prepend the ** left-child pointer to the beginning of a cell. */ if( pBt->pTmpSpace ){ memset(pBt->pTmpSpace, 0, 8); pBt->pTmpSpace += 4; } } } /* ** Free the pBt->pTmpSpace allocation */ static void freeTempSpace(BtShared *pBt){ if( pBt->pTmpSpace ){ pBt->pTmpSpace -= 4; sqlite3PageFree(pBt->pTmpSpace); pBt->pTmpSpace = 0; } } /* ** Close an open database and invalidate all cursors. */ SQLITE_PRIVATE int sqlite3BtreeClose(Btree *p){ BtShared *pBt = p->pBt; BtCursor *pCur; /* Close all cursors opened via this handle. */ assert( sqlite3_mutex_held(p->db->mutex) ); sqlite3BtreeEnter(p); pCur = pBt->pCursor; while( pCur ){ BtCursor *pTmp = pCur; pCur = pCur->pNext; if( pTmp->pBtree==p ){ sqlite3BtreeCloseCursor(pTmp); } } /* Rollback any active transaction and free the handle structure. ** The call to sqlite3BtreeRollback() drops any table-locks held by ** this handle. */ sqlite3BtreeRollback(p, SQLITE_OK, 0); sqlite3BtreeLeave(p); /* If there are still other outstanding references to the shared-btree ** structure, return now. The remainder of this procedure cleans ** up the shared-btree. */ assert( p->wantToLock==0 && p->locked==0 ); if( !p->sharable || removeFromSharingList(pBt) ){ /* The pBt is no longer on the sharing list, so we can access ** it without having to hold the mutex. ** ** Clean out and delete the BtShared object. */ assert( !pBt->pCursor ); sqlite3PagerClose(pBt->pPager); if( pBt->xFreeSchema && pBt->pSchema ){ pBt->xFreeSchema(pBt->pSchema); } sqlite3DbFree(0, pBt->pSchema); freeTempSpace(pBt); sqlite3_free(pBt); } #ifndef SQLITE_OMIT_SHARED_CACHE assert( p->wantToLock==0 ); assert( p->locked==0 ); if( p->pPrev ) p->pPrev->pNext = p->pNext; if( p->pNext ) p->pNext->pPrev = p->pPrev; #endif sqlite3_free(p); return SQLITE_OK; } /* ** Change the "soft" limit on the number of pages in the cache. ** Unused and unmodified pages will be recycled when the number of ** pages in the cache exceeds this soft limit. But the size of the ** cache is allowed to grow larger than this limit if it contains ** dirty pages or pages still in active use. */ SQLITE_PRIVATE int sqlite3BtreeSetCacheSize(Btree *p, int mxPage){ BtShared *pBt = p->pBt; assert( sqlite3_mutex_held(p->db->mutex) ); sqlite3BtreeEnter(p); sqlite3PagerSetCachesize(pBt->pPager, mxPage); sqlite3BtreeLeave(p); return SQLITE_OK; } /* ** Change the "spill" limit on the number of pages in the cache. ** If the number of pages exceeds this limit during a write transaction, ** the pager might attempt to "spill" pages to the journal early in ** order to free up memory. ** ** The value returned is the current spill size. If zero is passed ** as an argument, no changes are made to the spill size setting, so ** using mxPage of 0 is a way to query the current spill size. */ SQLITE_PRIVATE int sqlite3BtreeSetSpillSize(Btree *p, int mxPage){ BtShared *pBt = p->pBt; int res; assert( sqlite3_mutex_held(p->db->mutex) ); sqlite3BtreeEnter(p); res = sqlite3PagerSetSpillsize(pBt->pPager, mxPage); sqlite3BtreeLeave(p); return res; } #if SQLITE_MAX_MMAP_SIZE>0 /* ** Change the limit on the amount of the database file that may be ** memory mapped. */ SQLITE_PRIVATE int sqlite3BtreeSetMmapLimit(Btree *p, sqlite3_int64 szMmap){ BtShared *pBt = p->pBt; assert( sqlite3_mutex_held(p->db->mutex) ); sqlite3BtreeEnter(p); sqlite3PagerSetMmapLimit(pBt->pPager, szMmap); sqlite3BtreeLeave(p); return SQLITE_OK; } #endif /* SQLITE_MAX_MMAP_SIZE>0 */ /* ** Change the way data is synced to disk in order to increase or decrease ** how well the database resists damage due to OS crashes and power ** failures. Level 1 is the same as asynchronous (no syncs() occur and ** there is a high probability of damage) Level 2 is the default. There ** is a very low but non-zero probability of damage. Level 3 reduces the ** probability of damage to near zero but with a write performance reduction. */ #ifndef SQLITE_OMIT_PAGER_PRAGMAS SQLITE_PRIVATE int sqlite3BtreeSetPagerFlags( Btree *p, /* The btree to set the safety level on */ unsigned pgFlags /* Various PAGER_* flags */ ){ BtShared *pBt = p->pBt; assert( sqlite3_mutex_held(p->db->mutex) ); sqlite3BtreeEnter(p); sqlite3PagerSetFlags(pBt->pPager, pgFlags); sqlite3BtreeLeave(p); return SQLITE_OK; } #endif /* ** Change the default pages size and the number of reserved bytes per page. ** Or, if the page size has already been fixed, return SQLITE_READONLY ** without changing anything. ** ** The page size must be a power of 2 between 512 and 65536. If the page ** size supplied does not meet this constraint then the page size is not ** changed. ** ** Page sizes are constrained to be a power of two so that the region ** of the database file used for locking (beginning at PENDING_BYTE, ** the first byte past the 1GB boundary, 0x40000000) needs to occur ** at the beginning of a page. ** ** If parameter nReserve is less than zero, then the number of reserved ** bytes per page is left unchanged. ** ** If the iFix!=0 then the BTS_PAGESIZE_FIXED flag is set so that the page size ** and autovacuum mode can no longer be changed. */ SQLITE_PRIVATE int sqlite3BtreeSetPageSize(Btree *p, int pageSize, int nReserve, int iFix){ int rc = SQLITE_OK; BtShared *pBt = p->pBt; assert( nReserve>=-1 && nReserve<=255 ); sqlite3BtreeEnter(p); #if SQLITE_HAS_CODEC if( nReserve>pBt->optimalReserve ) pBt->optimalReserve = (u8)nReserve; #endif if( pBt->btsFlags & BTS_PAGESIZE_FIXED ){ sqlite3BtreeLeave(p); return SQLITE_READONLY; } if( nReserve<0 ){ nReserve = pBt->pageSize - pBt->usableSize; } assert( nReserve>=0 && nReserve<=255 ); if( pageSize>=512 && pageSize<=SQLITE_MAX_PAGE_SIZE && ((pageSize-1)&pageSize)==0 ){ assert( (pageSize & 7)==0 ); assert( !pBt->pCursor ); pBt->pageSize = (u32)pageSize; freeTempSpace(pBt); } rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize, nReserve); pBt->usableSize = pBt->pageSize - (u16)nReserve; if( iFix ) pBt->btsFlags |= BTS_PAGESIZE_FIXED; sqlite3BtreeLeave(p); return rc; } /* ** Return the currently defined page size */ SQLITE_PRIVATE int sqlite3BtreeGetPageSize(Btree *p){ return p->pBt->pageSize; } /* ** This function is similar to sqlite3BtreeGetReserve(), except that it ** may only be called if it is guaranteed that the b-tree mutex is already ** held. ** ** This is useful in one special case in the backup API code where it is ** known that the shared b-tree mutex is held, but the mutex on the ** database handle that owns *p is not. In this case if sqlite3BtreeEnter() ** were to be called, it might collide with some other operation on the ** database handle that owns *p, causing undefined behavior. */ SQLITE_PRIVATE int sqlite3BtreeGetReserveNoMutex(Btree *p){ int n; assert( sqlite3_mutex_held(p->pBt->mutex) ); n = p->pBt->pageSize - p->pBt->usableSize; return n; } /* ** Return the number of bytes of space at the end of every page that ** are intentually left unused. This is the "reserved" space that is ** sometimes used by extensions. ** ** If SQLITE_HAS_MUTEX is defined then the number returned is the ** greater of the current reserved space and the maximum requested ** reserve space. */ SQLITE_PRIVATE int sqlite3BtreeGetOptimalReserve(Btree *p){ int n; sqlite3BtreeEnter(p); n = sqlite3BtreeGetReserveNoMutex(p); #ifdef SQLITE_HAS_CODEC if( npBt->optimalReserve ) n = p->pBt->optimalReserve; #endif sqlite3BtreeLeave(p); return n; } /* ** Set the maximum page count for a database if mxPage is positive. ** No changes are made if mxPage is 0 or negative. ** Regardless of the value of mxPage, return the maximum page count. */ SQLITE_PRIVATE int sqlite3BtreeMaxPageCount(Btree *p, int mxPage){ int n; sqlite3BtreeEnter(p); n = sqlite3PagerMaxPageCount(p->pBt->pPager, mxPage); sqlite3BtreeLeave(p); return n; } /* ** Set the BTS_SECURE_DELETE flag if newFlag is 0 or 1. If newFlag is -1, ** then make no changes. Always return the value of the BTS_SECURE_DELETE ** setting after the change. */ SQLITE_PRIVATE int sqlite3BtreeSecureDelete(Btree *p, int newFlag){ int b; if( p==0 ) return 0; sqlite3BtreeEnter(p); if( newFlag>=0 ){ p->pBt->btsFlags &= ~BTS_SECURE_DELETE; if( newFlag ) p->pBt->btsFlags |= BTS_SECURE_DELETE; } b = (p->pBt->btsFlags & BTS_SECURE_DELETE)!=0; sqlite3BtreeLeave(p); return b; } /* ** Change the 'auto-vacuum' property of the database. If the 'autoVacuum' ** parameter is non-zero, then auto-vacuum mode is enabled. If zero, it ** is disabled. The default value for the auto-vacuum property is ** determined by the SQLITE_DEFAULT_AUTOVACUUM macro. */ SQLITE_PRIVATE int sqlite3BtreeSetAutoVacuum(Btree *p, int autoVacuum){ #ifdef SQLITE_OMIT_AUTOVACUUM return SQLITE_READONLY; #else BtShared *pBt = p->pBt; int rc = SQLITE_OK; u8 av = (u8)autoVacuum; sqlite3BtreeEnter(p); if( (pBt->btsFlags & BTS_PAGESIZE_FIXED)!=0 && (av ?1:0)!=pBt->autoVacuum ){ rc = SQLITE_READONLY; }else{ pBt->autoVacuum = av ?1:0; pBt->incrVacuum = av==2 ?1:0; } sqlite3BtreeLeave(p); return rc; #endif } /* ** Return the value of the 'auto-vacuum' property. If auto-vacuum is ** enabled 1 is returned. Otherwise 0. */ SQLITE_PRIVATE int sqlite3BtreeGetAutoVacuum(Btree *p){ #ifdef SQLITE_OMIT_AUTOVACUUM return BTREE_AUTOVACUUM_NONE; #else int rc; sqlite3BtreeEnter(p); rc = ( (!p->pBt->autoVacuum)?BTREE_AUTOVACUUM_NONE: (!p->pBt->incrVacuum)?BTREE_AUTOVACUUM_FULL: BTREE_AUTOVACUUM_INCR ); sqlite3BtreeLeave(p); return rc; #endif } /* ** Get a reference to pPage1 of the database file. This will ** also acquire a readlock on that file. ** ** SQLITE_OK is returned on success. If the file is not a ** well-formed database file, then SQLITE_CORRUPT is returned. ** SQLITE_BUSY is returned if the database is locked. SQLITE_NOMEM ** is returned if we run out of memory. */ static int lockBtree(BtShared *pBt){ int rc; /* Result code from subfunctions */ MemPage *pPage1; /* Page 1 of the database file */ int nPage; /* Number of pages in the database */ int nPageFile = 0; /* Number of pages in the database file */ int nPageHeader; /* Number of pages in the database according to hdr */ assert( sqlite3_mutex_held(pBt->mutex) ); assert( pBt->pPage1==0 ); rc = sqlite3PagerSharedLock(pBt->pPager); if( rc!=SQLITE_OK ) return rc; rc = btreeGetPage(pBt, 1, &pPage1, 0); if( rc!=SQLITE_OK ) return rc; /* Do some checking to help insure the file we opened really is ** a valid database file. */ nPage = nPageHeader = get4byte(28+(u8*)pPage1->aData); sqlite3PagerPagecount(pBt->pPager, &nPageFile); if( nPage==0 || memcmp(24+(u8*)pPage1->aData, 92+(u8*)pPage1->aData,4)!=0 ){ nPage = nPageFile; } if( nPage>0 ){ u32 pageSize; u32 usableSize; u8 *page1 = pPage1->aData; rc = SQLITE_NOTADB; /* EVIDENCE-OF: R-43737-39999 Every valid SQLite database file begins ** with the following 16 bytes (in hex): 53 51 4c 69 74 65 20 66 6f 72 6d ** 61 74 20 33 00. */ if( memcmp(page1, zMagicHeader, 16)!=0 ){ goto page1_init_failed; } #ifdef SQLITE_OMIT_WAL if( page1[18]>1 ){ pBt->btsFlags |= BTS_READ_ONLY; } if( page1[19]>1 ){ goto page1_init_failed; } #else if( page1[18]>2 ){ pBt->btsFlags |= BTS_READ_ONLY; } if( page1[19]>2 ){ goto page1_init_failed; } /* If the write version is set to 2, this database should be accessed ** in WAL mode. If the log is not already open, open it now. Then ** return SQLITE_OK and return without populating BtShared.pPage1. ** The caller detects this and calls this function again. This is ** required as the version of page 1 currently in the page1 buffer ** may not be the latest version - there may be a newer one in the log ** file. */ if( page1[19]==2 && (pBt->btsFlags & BTS_NO_WAL)==0 ){ int isOpen = 0; rc = sqlite3PagerOpenWal(pBt->pPager, &isOpen); if( rc!=SQLITE_OK ){ goto page1_init_failed; }else{ #if SQLITE_DEFAULT_SYNCHRONOUS!=SQLITE_DEFAULT_WAL_SYNCHRONOUS sqlite3 *db; Db *pDb; if( (db=pBt->db)!=0 && (pDb=db->aDb)!=0 ){ while( pDb->pBt==0 || pDb->pBt->pBt!=pBt ){ pDb++; } if( pDb->bSyncSet==0 && pDb->safety_level==SQLITE_DEFAULT_SYNCHRONOUS+1 ){ pDb->safety_level = SQLITE_DEFAULT_WAL_SYNCHRONOUS+1; sqlite3PagerSetFlags(pBt->pPager, pDb->safety_level | (db->flags & PAGER_FLAGS_MASK)); } } #endif if( isOpen==0 ){ releasePage(pPage1); return SQLITE_OK; } } rc = SQLITE_NOTADB; } #endif /* EVIDENCE-OF: R-15465-20813 The maximum and minimum embedded payload ** fractions and the leaf payload fraction values must be 64, 32, and 32. ** ** The original design allowed these amounts to vary, but as of ** version 3.6.0, we require them to be fixed. */ if( memcmp(&page1[21], "\100\040\040",3)!=0 ){ goto page1_init_failed; } /* EVIDENCE-OF: R-51873-39618 The page size for a database file is ** determined by the 2-byte integer located at an offset of 16 bytes from ** the beginning of the database file. */ pageSize = (page1[16]<<8) | (page1[17]<<16); /* EVIDENCE-OF: R-25008-21688 The size of a page is a power of two ** between 512 and 65536 inclusive. */ if( ((pageSize-1)&pageSize)!=0 || pageSize>SQLITE_MAX_PAGE_SIZE || pageSize<=256 ){ goto page1_init_failed; } assert( (pageSize & 7)==0 ); /* EVIDENCE-OF: R-59310-51205 The "reserved space" size in the 1-byte ** integer at offset 20 is the number of bytes of space at the end of ** each page to reserve for extensions. ** ** EVIDENCE-OF: R-37497-42412 The size of the reserved region is ** determined by the one-byte unsigned integer found at an offset of 20 ** into the database file header. */ usableSize = pageSize - page1[20]; if( (u32)pageSize!=pBt->pageSize ){ /* After reading the first page of the database assuming a page size ** of BtShared.pageSize, we have discovered that the page-size is ** actually pageSize. Unlock the database, leave pBt->pPage1 at ** zero and return SQLITE_OK. The caller will call this function ** again with the correct page-size. */ releasePage(pPage1); pBt->usableSize = usableSize; pBt->pageSize = pageSize; freeTempSpace(pBt); rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize, pageSize-usableSize); return rc; } if( (pBt->db->flags & SQLITE_RecoveryMode)==0 && nPage>nPageFile ){ rc = SQLITE_CORRUPT_BKPT; goto page1_init_failed; } /* EVIDENCE-OF: R-28312-64704 However, the usable size is not allowed to ** be less than 480. In other words, if the page size is 512, then the ** reserved space size cannot exceed 32. */ if( usableSize<480 ){ goto page1_init_failed; } pBt->pageSize = pageSize; pBt->usableSize = usableSize; #ifndef SQLITE_OMIT_AUTOVACUUM pBt->autoVacuum = (get4byte(&page1[36 + 4*4])?1:0); pBt->incrVacuum = (get4byte(&page1[36 + 7*4])?1:0); #endif } /* maxLocal is the maximum amount of payload to store locally for ** a cell. Make sure it is small enough so that at least minFanout ** cells can will fit on one page. We assume a 10-byte page header. ** Besides the payload, the cell must store: ** 2-byte pointer to the cell ** 4-byte child pointer ** 9-byte nKey value ** 4-byte nData value ** 4-byte overflow page pointer ** So a cell consists of a 2-byte pointer, a header which is as much as ** 17 bytes long, 0 to N bytes of payload, and an optional 4 byte overflow ** page pointer. */ pBt->maxLocal = (u16)((pBt->usableSize-12)*64/255 - 23); pBt->minLocal = (u16)((pBt->usableSize-12)*32/255 - 23); pBt->maxLeaf = (u16)(pBt->usableSize - 35); pBt->minLeaf = (u16)((pBt->usableSize-12)*32/255 - 23); if( pBt->maxLocal>127 ){ pBt->max1bytePayload = 127; }else{ pBt->max1bytePayload = (u8)pBt->maxLocal; } assert( pBt->maxLeaf + 23 <= MX_CELL_SIZE(pBt) ); pBt->pPage1 = pPage1; pBt->nPage = nPage; return SQLITE_OK; page1_init_failed: releasePage(pPage1); pBt->pPage1 = 0; return rc; } #ifndef NDEBUG /* ** Return the number of cursors open on pBt. This is for use ** in assert() expressions, so it is only compiled if NDEBUG is not ** defined. ** ** Only write cursors are counted if wrOnly is true. If wrOnly is ** false then all cursors are counted. ** ** For the purposes of this routine, a cursor is any cursor that ** is capable of reading or writing to the database. Cursors that ** have been tripped into the CURSOR_FAULT state are not counted. */ static int countValidCursors(BtShared *pBt, int wrOnly){ BtCursor *pCur; int r = 0; for(pCur=pBt->pCursor; pCur; pCur=pCur->pNext){ if( (wrOnly==0 || (pCur->curFlags & BTCF_WriteFlag)!=0) && pCur->eState!=CURSOR_FAULT ) r++; } return r; } #endif /* ** If there are no outstanding cursors and we are not in the middle ** of a transaction but there is a read lock on the database, then ** this routine unrefs the first page of the database file which ** has the effect of releasing the read lock. ** ** If there is a transaction in progress, this routine is a no-op. */ static void unlockBtreeIfUnused(BtShared *pBt){ assert( sqlite3_mutex_held(pBt->mutex) ); assert( countValidCursors(pBt,0)==0 || pBt->inTransaction>TRANS_NONE ); if( pBt->inTransaction==TRANS_NONE && pBt->pPage1!=0 ){ MemPage *pPage1 = pBt->pPage1; assert( pPage1->aData ); assert( sqlite3PagerRefcount(pBt->pPager)==1 ); pBt->pPage1 = 0; releasePageNotNull(pPage1); } } /* ** If pBt points to an empty file then convert that empty file ** into a new empty database by initializing the first page of ** the database. */ static int newDatabase(BtShared *pBt){ MemPage *pP1; unsigned char *data; int rc; assert( sqlite3_mutex_held(pBt->mutex) ); if( pBt->nPage>0 ){ return SQLITE_OK; } pP1 = pBt->pPage1; assert( pP1!=0 ); data = pP1->aData; rc = sqlite3PagerWrite(pP1->pDbPage); if( rc ) return rc; memcpy(data, zMagicHeader, sizeof(zMagicHeader)); assert( sizeof(zMagicHeader)==16 ); data[16] = (u8)((pBt->pageSize>>8)&0xff); data[17] = (u8)((pBt->pageSize>>16)&0xff); data[18] = 1; data[19] = 1; assert( pBt->usableSize<=pBt->pageSize && pBt->usableSize+255>=pBt->pageSize); data[20] = (u8)(pBt->pageSize - pBt->usableSize); data[21] = 64; data[22] = 32; data[23] = 32; memset(&data[24], 0, 100-24); zeroPage(pP1, PTF_INTKEY|PTF_LEAF|PTF_LEAFDATA ); pBt->btsFlags |= BTS_PAGESIZE_FIXED; #ifndef SQLITE_OMIT_AUTOVACUUM assert( pBt->autoVacuum==1 || pBt->autoVacuum==0 ); assert( pBt->incrVacuum==1 || pBt->incrVacuum==0 ); put4byte(&data[36 + 4*4], pBt->autoVacuum); put4byte(&data[36 + 7*4], pBt->incrVacuum); #endif pBt->nPage = 1; data[31] = 1; return SQLITE_OK; } /* ** Initialize the first page of the database file (creating a database ** consisting of a single page and no schema objects). Return SQLITE_OK ** if successful, or an SQLite error code otherwise. */ SQLITE_PRIVATE int sqlite3BtreeNewDb(Btree *p){ int rc; sqlite3BtreeEnter(p); p->pBt->nPage = 0; rc = newDatabase(p->pBt); sqlite3BtreeLeave(p); return rc; } /* ** Attempt to start a new transaction. A write-transaction ** is started if the second argument is nonzero, otherwise a read- ** transaction. If the second argument is 2 or more and exclusive ** transaction is started, meaning that no other process is allowed ** to access the database. A preexisting transaction may not be ** upgraded to exclusive by calling this routine a second time - the ** exclusivity flag only works for a new transaction. ** ** A write-transaction must be started before attempting any ** changes to the database. None of the following routines ** will work unless a transaction is started first: ** ** sqlite3BtreeCreateTable() ** sqlite3BtreeCreateIndex() ** sqlite3BtreeClearTable() ** sqlite3BtreeDropTable() ** sqlite3BtreeInsert() ** sqlite3BtreeDelete() ** sqlite3BtreeUpdateMeta() ** ** If an initial attempt to acquire the lock fails because of lock contention ** and the database was previously unlocked, then invoke the busy handler ** if there is one. But if there was previously a read-lock, do not ** invoke the busy handler - just return SQLITE_BUSY. SQLITE_BUSY is ** returned when there is already a read-lock in order to avoid a deadlock. ** ** Suppose there are two processes A and B. A has a read lock and B has ** a reserved lock. B tries to promote to exclusive but is blocked because ** of A's read lock. A tries to promote to reserved but is blocked by B. ** One or the other of the two processes must give way or there can be ** no progress. By returning SQLITE_BUSY and not invoking the busy callback ** when A already has a read lock, we encourage A to give up and let B ** proceed. */ SQLITE_PRIVATE int sqlite3BtreeBeginTrans(Btree *p, int wrflag){ BtShared *pBt = p->pBt; int rc = SQLITE_OK; sqlite3BtreeEnter(p); btreeIntegrity(p); /* If the btree is already in a write-transaction, or it ** is already in a read-transaction and a read-transaction ** is requested, this is a no-op. */ if( p->inTrans==TRANS_WRITE || (p->inTrans==TRANS_READ && !wrflag) ){ goto trans_begun; } assert( pBt->inTransaction==TRANS_WRITE || IfNotOmitAV(pBt->bDoTruncate)==0 ); /* Write transactions are not possible on a read-only database */ if( (pBt->btsFlags & BTS_READ_ONLY)!=0 && wrflag ){ rc = SQLITE_READONLY; goto trans_begun; } #ifndef SQLITE_OMIT_SHARED_CACHE { sqlite3 *pBlock = 0; /* If another database handle has already opened a write transaction ** on this shared-btree structure and a second write transaction is ** requested, return SQLITE_LOCKED. */ if( (wrflag && pBt->inTransaction==TRANS_WRITE) || (pBt->btsFlags & BTS_PENDING)!=0 ){ pBlock = pBt->pWriter->db; }else if( wrflag>1 ){ BtLock *pIter; for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){ if( pIter->pBtree!=p ){ pBlock = pIter->pBtree->db; break; } } } if( pBlock ){ sqlite3ConnectionBlocked(p->db, pBlock); rc = SQLITE_LOCKED_SHAREDCACHE; goto trans_begun; } } #endif /* Any read-only or read-write transaction implies a read-lock on ** page 1. So if some other shared-cache client already has a write-lock ** on page 1, the transaction cannot be opened. */ rc = querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK); if( SQLITE_OK!=rc ) goto trans_begun; pBt->btsFlags &= ~BTS_INITIALLY_EMPTY; if( pBt->nPage==0 ) pBt->btsFlags |= BTS_INITIALLY_EMPTY; do { /* Call lockBtree() until either pBt->pPage1 is populated or ** lockBtree() returns something other than SQLITE_OK. lockBtree() ** may return SQLITE_OK but leave pBt->pPage1 set to 0 if after ** reading page 1 it discovers that the page-size of the database ** file is not pBt->pageSize. In this case lockBtree() will update ** pBt->pageSize to the page-size of the file on disk. */ while( pBt->pPage1==0 && SQLITE_OK==(rc = lockBtree(pBt)) ); if( rc==SQLITE_OK && wrflag ){ if( (pBt->btsFlags & BTS_READ_ONLY)!=0 ){ rc = SQLITE_READONLY; }else{ rc = sqlite3PagerBegin(pBt->pPager,wrflag>1,sqlite3TempInMemory(p->db)); if( rc==SQLITE_OK ){ rc = newDatabase(pBt); } } } if( rc!=SQLITE_OK ){ unlockBtreeIfUnused(pBt); } }while( (rc&0xFF)==SQLITE_BUSY && pBt->inTransaction==TRANS_NONE && btreeInvokeBusyHandler(pBt) ); if( rc==SQLITE_OK ){ if( p->inTrans==TRANS_NONE ){ pBt->nTransaction++; #ifndef SQLITE_OMIT_SHARED_CACHE if( p->sharable ){ assert( p->lock.pBtree==p && p->lock.iTable==1 ); p->lock.eLock = READ_LOCK; p->lock.pNext = pBt->pLock; pBt->pLock = &p->lock; } #endif } p->inTrans = (wrflag?TRANS_WRITE:TRANS_READ); if( p->inTrans>pBt->inTransaction ){ pBt->inTransaction = p->inTrans; } if( wrflag ){ MemPage *pPage1 = pBt->pPage1; #ifndef SQLITE_OMIT_SHARED_CACHE assert( !pBt->pWriter ); pBt->pWriter = p; pBt->btsFlags &= ~BTS_EXCLUSIVE; if( wrflag>1 ) pBt->btsFlags |= BTS_EXCLUSIVE; #endif /* If the db-size header field is incorrect (as it may be if an old ** client has been writing the database file), update it now. Doing ** this sooner rather than later means the database size can safely ** re-read the database size from page 1 if a savepoint or transaction ** rollback occurs within the transaction. */ if( pBt->nPage!=get4byte(&pPage1->aData[28]) ){ rc = sqlite3PagerWrite(pPage1->pDbPage); if( rc==SQLITE_OK ){ put4byte(&pPage1->aData[28], pBt->nPage); } } } } trans_begun: if( rc==SQLITE_OK && wrflag ){ /* This call makes sure that the pager has the correct number of ** open savepoints. If the second parameter is greater than 0 and ** the sub-journal is not already open, then it will be opened here. */ rc = sqlite3PagerOpenSavepoint(pBt->pPager, p->db->nSavepoint); } btreeIntegrity(p); sqlite3BtreeLeave(p); return rc; } #ifndef SQLITE_OMIT_AUTOVACUUM /* ** Set the pointer-map entries for all children of page pPage. Also, if ** pPage contains cells that point to overflow pages, set the pointer ** map entries for the overflow pages as well. */ static int setChildPtrmaps(MemPage *pPage){ int i; /* Counter variable */ int nCell; /* Number of cells in page pPage */ int rc; /* Return code */ BtShared *pBt = pPage->pBt; u8 isInitOrig = pPage->isInit; Pgno pgno = pPage->pgno; assert( sqlite3_mutex_held(pPage->pBt->mutex) ); rc = btreeInitPage(pPage); if( rc!=SQLITE_OK ){ goto set_child_ptrmaps_out; } nCell = pPage->nCell; for(i=0; ileaf ){ Pgno childPgno = get4byte(pCell); ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno, &rc); } } if( !pPage->leaf ){ Pgno childPgno = get4byte(&pPage->aData[pPage->hdrOffset+8]); ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno, &rc); } set_child_ptrmaps_out: pPage->isInit = isInitOrig; return rc; } /* ** Somewhere on pPage is a pointer to page iFrom. Modify this pointer so ** that it points to iTo. Parameter eType describes the type of pointer to ** be modified, as follows: ** ** PTRMAP_BTREE: pPage is a btree-page. The pointer points at a child ** page of pPage. ** ** PTRMAP_OVERFLOW1: pPage is a btree-page. The pointer points at an overflow ** page pointed to by one of the cells on pPage. ** ** PTRMAP_OVERFLOW2: pPage is an overflow-page. The pointer points at the next ** overflow page in the list. */ static int modifyPagePointer(MemPage *pPage, Pgno iFrom, Pgno iTo, u8 eType){ assert( sqlite3_mutex_held(pPage->pBt->mutex) ); assert( sqlite3PagerIswriteable(pPage->pDbPage) ); if( eType==PTRMAP_OVERFLOW2 ){ /* The pointer is always the first 4 bytes of the page in this case. */ if( get4byte(pPage->aData)!=iFrom ){ return SQLITE_CORRUPT_BKPT; } put4byte(pPage->aData, iTo); }else{ u8 isInitOrig = pPage->isInit; int i; int nCell; int rc; rc = btreeInitPage(pPage); if( rc ) return rc; nCell = pPage->nCell; for(i=0; ixParseCell(pPage, pCell, &info); if( info.nLocalaData+pPage->maskPage && iFrom==get4byte(pCell+info.nSize-4) ){ put4byte(pCell+info.nSize-4, iTo); break; } }else{ if( get4byte(pCell)==iFrom ){ put4byte(pCell, iTo); break; } } } if( i==nCell ){ if( eType!=PTRMAP_BTREE || get4byte(&pPage->aData[pPage->hdrOffset+8])!=iFrom ){ return SQLITE_CORRUPT_BKPT; } put4byte(&pPage->aData[pPage->hdrOffset+8], iTo); } pPage->isInit = isInitOrig; } return SQLITE_OK; } /* ** Move the open database page pDbPage to location iFreePage in the ** database. The pDbPage reference remains valid. ** ** The isCommit flag indicates that there is no need to remember that ** the journal needs to be sync()ed before database page pDbPage->pgno ** can be written to. The caller has already promised not to write to that ** page. */ static int relocatePage( BtShared *pBt, /* Btree */ MemPage *pDbPage, /* Open page to move */ u8 eType, /* Pointer map 'type' entry for pDbPage */ Pgno iPtrPage, /* Pointer map 'page-no' entry for pDbPage */ Pgno iFreePage, /* The location to move pDbPage to */ int isCommit /* isCommit flag passed to sqlite3PagerMovepage */ ){ MemPage *pPtrPage; /* The page that contains a pointer to pDbPage */ Pgno iDbPage = pDbPage->pgno; Pager *pPager = pBt->pPager; int rc; assert( eType==PTRMAP_OVERFLOW2 || eType==PTRMAP_OVERFLOW1 || eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE ); assert( sqlite3_mutex_held(pBt->mutex) ); assert( pDbPage->pBt==pBt ); /* Move page iDbPage from its current location to page number iFreePage */ TRACE(("AUTOVACUUM: Moving %d to free page %d (ptr page %d type %d)\n", iDbPage, iFreePage, iPtrPage, eType)); rc = sqlite3PagerMovepage(pPager, pDbPage->pDbPage, iFreePage, isCommit); if( rc!=SQLITE_OK ){ return rc; } pDbPage->pgno = iFreePage; /* If pDbPage was a btree-page, then it may have child pages and/or cells ** that point to overflow pages. The pointer map entries for all these ** pages need to be changed. ** ** If pDbPage is an overflow page, then the first 4 bytes may store a ** pointer to a subsequent overflow page. If this is the case, then ** the pointer map needs to be updated for the subsequent overflow page. */ if( eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE ){ rc = setChildPtrmaps(pDbPage); if( rc!=SQLITE_OK ){ return rc; } }else{ Pgno nextOvfl = get4byte(pDbPage->aData); if( nextOvfl!=0 ){ ptrmapPut(pBt, nextOvfl, PTRMAP_OVERFLOW2, iFreePage, &rc); if( rc!=SQLITE_OK ){ return rc; } } } /* Fix the database pointer on page iPtrPage that pointed at iDbPage so ** that it points at iFreePage. Also fix the pointer map entry for ** iPtrPage. */ if( eType!=PTRMAP_ROOTPAGE ){ rc = btreeGetPage(pBt, iPtrPage, &pPtrPage, 0); if( rc!=SQLITE_OK ){ return rc; } rc = sqlite3PagerWrite(pPtrPage->pDbPage); if( rc!=SQLITE_OK ){ releasePage(pPtrPage); return rc; } rc = modifyPagePointer(pPtrPage, iDbPage, iFreePage, eType); releasePage(pPtrPage); if( rc==SQLITE_OK ){ ptrmapPut(pBt, iFreePage, eType, iPtrPage, &rc); } } return rc; } /* Forward declaration required by incrVacuumStep(). */ static int allocateBtreePage(BtShared *, MemPage **, Pgno *, Pgno, u8); /* ** Perform a single step of an incremental-vacuum. If successful, return ** SQLITE_OK. If there is no work to do (and therefore no point in ** calling this function again), return SQLITE_DONE. Or, if an error ** occurs, return some other error code. ** ** More specifically, this function attempts to re-organize the database so ** that the last page of the file currently in use is no longer in use. ** ** Parameter nFin is the number of pages that this database would contain ** were this function called until it returns SQLITE_DONE. ** ** If the bCommit parameter is non-zero, this function assumes that the ** caller will keep calling incrVacuumStep() until it returns SQLITE_DONE ** or an error. bCommit is passed true for an auto-vacuum-on-commit ** operation, or false for an incremental vacuum. */ static int incrVacuumStep(BtShared *pBt, Pgno nFin, Pgno iLastPg, int bCommit){ Pgno nFreeList; /* Number of pages still on the free-list */ int rc; assert( sqlite3_mutex_held(pBt->mutex) ); assert( iLastPg>nFin ); if( !PTRMAP_ISPAGE(pBt, iLastPg) && iLastPg!=PENDING_BYTE_PAGE(pBt) ){ u8 eType; Pgno iPtrPage; nFreeList = get4byte(&pBt->pPage1->aData[36]); if( nFreeList==0 ){ return SQLITE_DONE; } rc = ptrmapGet(pBt, iLastPg, &eType, &iPtrPage); if( rc!=SQLITE_OK ){ return rc; } if( eType==PTRMAP_ROOTPAGE ){ return SQLITE_CORRUPT_BKPT; } if( eType==PTRMAP_FREEPAGE ){ if( bCommit==0 ){ /* Remove the page from the files free-list. This is not required ** if bCommit is non-zero. In that case, the free-list will be ** truncated to zero after this function returns, so it doesn't ** matter if it still contains some garbage entries. */ Pgno iFreePg; MemPage *pFreePg; rc = allocateBtreePage(pBt, &pFreePg, &iFreePg, iLastPg, BTALLOC_EXACT); if( rc!=SQLITE_OK ){ return rc; } assert( iFreePg==iLastPg ); releasePage(pFreePg); } } else { Pgno iFreePg; /* Index of free page to move pLastPg to */ MemPage *pLastPg; u8 eMode = BTALLOC_ANY; /* Mode parameter for allocateBtreePage() */ Pgno iNear = 0; /* nearby parameter for allocateBtreePage() */ rc = btreeGetPage(pBt, iLastPg, &pLastPg, 0); if( rc!=SQLITE_OK ){ return rc; } /* If bCommit is zero, this loop runs exactly once and page pLastPg ** is swapped with the first free page pulled off the free list. ** ** On the other hand, if bCommit is greater than zero, then keep ** looping until a free-page located within the first nFin pages ** of the file is found. */ if( bCommit==0 ){ eMode = BTALLOC_LE; iNear = nFin; } do { MemPage *pFreePg; rc = allocateBtreePage(pBt, &pFreePg, &iFreePg, iNear, eMode); if( rc!=SQLITE_OK ){ releasePage(pLastPg); return rc; } releasePage(pFreePg); }while( bCommit && iFreePg>nFin ); assert( iFreePgbDoTruncate = 1; pBt->nPage = iLastPg; } return SQLITE_OK; } /* ** The database opened by the first argument is an auto-vacuum database ** nOrig pages in size containing nFree free pages. Return the expected ** size of the database in pages following an auto-vacuum operation. */ static Pgno finalDbSize(BtShared *pBt, Pgno nOrig, Pgno nFree){ int nEntry; /* Number of entries on one ptrmap page */ Pgno nPtrmap; /* Number of PtrMap pages to be freed */ Pgno nFin; /* Return value */ nEntry = pBt->usableSize/5; nPtrmap = (nFree-nOrig+PTRMAP_PAGENO(pBt, nOrig)+nEntry)/nEntry; nFin = nOrig - nFree - nPtrmap; if( nOrig>PENDING_BYTE_PAGE(pBt) && nFinpBt; sqlite3BtreeEnter(p); assert( pBt->inTransaction==TRANS_WRITE && p->inTrans==TRANS_WRITE ); if( !pBt->autoVacuum ){ rc = SQLITE_DONE; }else{ Pgno nOrig = btreePagecount(pBt); Pgno nFree = get4byte(&pBt->pPage1->aData[36]); Pgno nFin = finalDbSize(pBt, nOrig, nFree); if( nOrig0 ){ rc = saveAllCursors(pBt, 0, 0); if( rc==SQLITE_OK ){ invalidateAllOverflowCache(pBt); rc = incrVacuumStep(pBt, nFin, nOrig, 0); } if( rc==SQLITE_OK ){ rc = sqlite3PagerWrite(pBt->pPage1->pDbPage); put4byte(&pBt->pPage1->aData[28], pBt->nPage); } }else{ rc = SQLITE_DONE; } } sqlite3BtreeLeave(p); return rc; } /* ** This routine is called prior to sqlite3PagerCommit when a transaction ** is committed for an auto-vacuum database. ** ** If SQLITE_OK is returned, then *pnTrunc is set to the number of pages ** the database file should be truncated to during the commit process. ** i.e. the database has been reorganized so that only the first *pnTrunc ** pages are in use. */ static int autoVacuumCommit(BtShared *pBt){ int rc = SQLITE_OK; Pager *pPager = pBt->pPager; VVA_ONLY( int nRef = sqlite3PagerRefcount(pPager); ) assert( sqlite3_mutex_held(pBt->mutex) ); invalidateAllOverflowCache(pBt); assert(pBt->autoVacuum); if( !pBt->incrVacuum ){ Pgno nFin; /* Number of pages in database after autovacuuming */ Pgno nFree; /* Number of pages on the freelist initially */ Pgno iFree; /* The next page to be freed */ Pgno nOrig; /* Database size before freeing */ nOrig = btreePagecount(pBt); if( PTRMAP_ISPAGE(pBt, nOrig) || nOrig==PENDING_BYTE_PAGE(pBt) ){ /* It is not possible to create a database for which the final page ** is either a pointer-map page or the pending-byte page. If one ** is encountered, this indicates corruption. */ return SQLITE_CORRUPT_BKPT; } nFree = get4byte(&pBt->pPage1->aData[36]); nFin = finalDbSize(pBt, nOrig, nFree); if( nFin>nOrig ) return SQLITE_CORRUPT_BKPT; if( nFinnFin && rc==SQLITE_OK; iFree--){ rc = incrVacuumStep(pBt, nFin, iFree, 1); } if( (rc==SQLITE_DONE || rc==SQLITE_OK) && nFree>0 ){ rc = sqlite3PagerWrite(pBt->pPage1->pDbPage); put4byte(&pBt->pPage1->aData[32], 0); put4byte(&pBt->pPage1->aData[36], 0); put4byte(&pBt->pPage1->aData[28], nFin); pBt->bDoTruncate = 1; pBt->nPage = nFin; } if( rc!=SQLITE_OK ){ sqlite3PagerRollback(pPager); } } assert( nRef>=sqlite3PagerRefcount(pPager) ); return rc; } #else /* ifndef SQLITE_OMIT_AUTOVACUUM */ # define setChildPtrmaps(x) SQLITE_OK #endif /* ** This routine does the first phase of a two-phase commit. This routine ** causes a rollback journal to be created (if it does not already exist) ** and populated with enough information so that if a power loss occurs ** the database can be restored to its original state by playing back ** the journal. Then the contents of the journal are flushed out to ** the disk. After the journal is safely on oxide, the changes to the ** database are written into the database file and flushed to oxide. ** At the end of this call, the rollback journal still exists on the ** disk and we are still holding all locks, so the transaction has not ** committed. See sqlite3BtreeCommitPhaseTwo() for the second phase of the ** commit process. ** ** This call is a no-op if no write-transaction is currently active on pBt. ** ** Otherwise, sync the database file for the btree pBt. zMaster points to ** the name of a master journal file that should be written into the ** individual journal file, or is NULL, indicating no master journal file ** (single database transaction). ** ** When this is called, the master journal should already have been ** created, populated with this journal pointer and synced to disk. ** ** Once this is routine has returned, the only thing required to commit ** the write-transaction for this database file is to delete the journal. */ SQLITE_PRIVATE int sqlite3BtreeCommitPhaseOne(Btree *p, const char *zMaster){ int rc = SQLITE_OK; if( p->inTrans==TRANS_WRITE ){ BtShared *pBt = p->pBt; sqlite3BtreeEnter(p); #ifndef SQLITE_OMIT_AUTOVACUUM if( pBt->autoVacuum ){ rc = autoVacuumCommit(pBt); if( rc!=SQLITE_OK ){ sqlite3BtreeLeave(p); return rc; } } if( pBt->bDoTruncate ){ sqlite3PagerTruncateImage(pBt->pPager, pBt->nPage); } #endif rc = sqlite3PagerCommitPhaseOne(pBt->pPager, zMaster, 0); sqlite3BtreeLeave(p); } return rc; } /* ** This function is called from both BtreeCommitPhaseTwo() and BtreeRollback() ** at the conclusion of a transaction. */ static void btreeEndTransaction(Btree *p){ BtShared *pBt = p->pBt; sqlite3 *db = p->db; assert( sqlite3BtreeHoldsMutex(p) ); #ifndef SQLITE_OMIT_AUTOVACUUM pBt->bDoTruncate = 0; #endif if( p->inTrans>TRANS_NONE && db->nVdbeRead>1 ){ /* If there are other active statements that belong to this database ** handle, downgrade to a read-only transaction. The other statements ** may still be reading from the database. */ downgradeAllSharedCacheTableLocks(p); p->inTrans = TRANS_READ; }else{ /* If the handle had any kind of transaction open, decrement the ** transaction count of the shared btree. If the transaction count ** reaches 0, set the shared state to TRANS_NONE. The unlockBtreeIfUnused() ** call below will unlock the pager. */ if( p->inTrans!=TRANS_NONE ){ clearAllSharedCacheTableLocks(p); pBt->nTransaction--; if( 0==pBt->nTransaction ){ pBt->inTransaction = TRANS_NONE; } } /* Set the current transaction state to TRANS_NONE and unlock the ** pager if this call closed the only read or write transaction. */ p->inTrans = TRANS_NONE; unlockBtreeIfUnused(pBt); } btreeIntegrity(p); } /* ** Commit the transaction currently in progress. ** ** This routine implements the second phase of a 2-phase commit. The ** sqlite3BtreeCommitPhaseOne() routine does the first phase and should ** be invoked prior to calling this routine. The sqlite3BtreeCommitPhaseOne() ** routine did all the work of writing information out to disk and flushing the ** contents so that they are written onto the disk platter. All this ** routine has to do is delete or truncate or zero the header in the ** the rollback journal (which causes the transaction to commit) and ** drop locks. ** ** Normally, if an error occurs while the pager layer is attempting to ** finalize the underlying journal file, this function returns an error and ** the upper layer will attempt a rollback. However, if the second argument ** is non-zero then this b-tree transaction is part of a multi-file ** transaction. In this case, the transaction has already been committed ** (by deleting a master journal file) and the caller will ignore this ** functions return code. So, even if an error occurs in the pager layer, ** reset the b-tree objects internal state to indicate that the write ** transaction has been closed. This is quite safe, as the pager will have ** transitioned to the error state. ** ** This will release the write lock on the database file. If there ** are no active cursors, it also releases the read lock. */ SQLITE_PRIVATE int sqlite3BtreeCommitPhaseTwo(Btree *p, int bCleanup){ if( p->inTrans==TRANS_NONE ) return SQLITE_OK; sqlite3BtreeEnter(p); btreeIntegrity(p); /* If the handle has a write-transaction open, commit the shared-btrees ** transaction and set the shared state to TRANS_READ. */ if( p->inTrans==TRANS_WRITE ){ int rc; BtShared *pBt = p->pBt; assert( pBt->inTransaction==TRANS_WRITE ); assert( pBt->nTransaction>0 ); rc = sqlite3PagerCommitPhaseTwo(pBt->pPager); if( rc!=SQLITE_OK && bCleanup==0 ){ sqlite3BtreeLeave(p); return rc; } p->iDataVersion--; /* Compensate for pPager->iDataVersion++; */ pBt->inTransaction = TRANS_READ; btreeClearHasContent(pBt); } btreeEndTransaction(p); sqlite3BtreeLeave(p); return SQLITE_OK; } /* ** Do both phases of a commit. */ SQLITE_PRIVATE int sqlite3BtreeCommit(Btree *p){ int rc; sqlite3BtreeEnter(p); rc = sqlite3BtreeCommitPhaseOne(p, 0); if( rc==SQLITE_OK ){ rc = sqlite3BtreeCommitPhaseTwo(p, 0); } sqlite3BtreeLeave(p); return rc; } /* ** This routine sets the state to CURSOR_FAULT and the error ** code to errCode for every cursor on any BtShared that pBtree ** references. Or if the writeOnly flag is set to 1, then only ** trip write cursors and leave read cursors unchanged. ** ** Every cursor is a candidate to be tripped, including cursors ** that belong to other database connections that happen to be ** sharing the cache with pBtree. ** ** This routine gets called when a rollback occurs. If the writeOnly ** flag is true, then only write-cursors need be tripped - read-only ** cursors save their current positions so that they may continue ** following the rollback. Or, if writeOnly is false, all cursors are ** tripped. In general, writeOnly is false if the transaction being ** rolled back modified the database schema. In this case b-tree root ** pages may be moved or deleted from the database altogether, making ** it unsafe for read cursors to continue. ** ** If the writeOnly flag is true and an error is encountered while ** saving the current position of a read-only cursor, all cursors, ** including all read-cursors are tripped. ** ** SQLITE_OK is returned if successful, or if an error occurs while ** saving a cursor position, an SQLite error code. */ SQLITE_PRIVATE int sqlite3BtreeTripAllCursors(Btree *pBtree, int errCode, int writeOnly){ BtCursor *p; int rc = SQLITE_OK; assert( (writeOnly==0 || writeOnly==1) && BTCF_WriteFlag==1 ); if( pBtree ){ sqlite3BtreeEnter(pBtree); for(p=pBtree->pBt->pCursor; p; p=p->pNext){ int i; if( writeOnly && (p->curFlags & BTCF_WriteFlag)==0 ){ if( p->eState==CURSOR_VALID || p->eState==CURSOR_SKIPNEXT ){ rc = saveCursorPosition(p); if( rc!=SQLITE_OK ){ (void)sqlite3BtreeTripAllCursors(pBtree, rc, 0); break; } } }else{ sqlite3BtreeClearCursor(p); p->eState = CURSOR_FAULT; p->skipNext = errCode; } for(i=0; i<=p->iPage; i++){ releasePage(p->apPage[i]); p->apPage[i] = 0; } } sqlite3BtreeLeave(pBtree); } return rc; } /* ** Rollback the transaction in progress. ** ** If tripCode is not SQLITE_OK then cursors will be invalidated (tripped). ** Only write cursors are tripped if writeOnly is true but all cursors are ** tripped if writeOnly is false. Any attempt to use ** a tripped cursor will result in an error. ** ** This will release the write lock on the database file. If there ** are no active cursors, it also releases the read lock. */ SQLITE_PRIVATE int sqlite3BtreeRollback(Btree *p, int tripCode, int writeOnly){ int rc; BtShared *pBt = p->pBt; MemPage *pPage1; assert( writeOnly==1 || writeOnly==0 ); assert( tripCode==SQLITE_ABORT_ROLLBACK || tripCode==SQLITE_OK ); sqlite3BtreeEnter(p); if( tripCode==SQLITE_OK ){ rc = tripCode = saveAllCursors(pBt, 0, 0); if( rc ) writeOnly = 0; }else{ rc = SQLITE_OK; } if( tripCode ){ int rc2 = sqlite3BtreeTripAllCursors(p, tripCode, writeOnly); assert( rc==SQLITE_OK || (writeOnly==0 && rc2==SQLITE_OK) ); if( rc2!=SQLITE_OK ) rc = rc2; } btreeIntegrity(p); if( p->inTrans==TRANS_WRITE ){ int rc2; assert( TRANS_WRITE==pBt->inTransaction ); rc2 = sqlite3PagerRollback(pBt->pPager); if( rc2!=SQLITE_OK ){ rc = rc2; } /* The rollback may have destroyed the pPage1->aData value. So ** call btreeGetPage() on page 1 again to make ** sure pPage1->aData is set correctly. */ if( btreeGetPage(pBt, 1, &pPage1, 0)==SQLITE_OK ){ int nPage = get4byte(28+(u8*)pPage1->aData); testcase( nPage==0 ); if( nPage==0 ) sqlite3PagerPagecount(pBt->pPager, &nPage); testcase( pBt->nPage!=nPage ); pBt->nPage = nPage; releasePage(pPage1); } assert( countValidCursors(pBt, 1)==0 ); pBt->inTransaction = TRANS_READ; btreeClearHasContent(pBt); } btreeEndTransaction(p); sqlite3BtreeLeave(p); return rc; } /* ** Start a statement subtransaction. The subtransaction can be rolled ** back independently of the main transaction. You must start a transaction ** before starting a subtransaction. The subtransaction is ended automatically ** if the main transaction commits or rolls back. ** ** Statement subtransactions are used around individual SQL statements ** that are contained within a BEGIN...COMMIT block. If a constraint ** error occurs within the statement, the effect of that one statement ** can be rolled back without having to rollback the entire transaction. ** ** A statement sub-transaction is implemented as an anonymous savepoint. The ** value passed as the second parameter is the total number of savepoints, ** including the new anonymous savepoint, open on the B-Tree. i.e. if there ** are no active savepoints and no other statement-transactions open, ** iStatement is 1. This anonymous savepoint can be released or rolled back ** using the sqlite3BtreeSavepoint() function. */ SQLITE_PRIVATE int sqlite3BtreeBeginStmt(Btree *p, int iStatement){ int rc; BtShared *pBt = p->pBt; sqlite3BtreeEnter(p); assert( p->inTrans==TRANS_WRITE ); assert( (pBt->btsFlags & BTS_READ_ONLY)==0 ); assert( iStatement>0 ); assert( iStatement>p->db->nSavepoint ); assert( pBt->inTransaction==TRANS_WRITE ); /* At the pager level, a statement transaction is a savepoint with ** an index greater than all savepoints created explicitly using ** SQL statements. It is illegal to open, release or rollback any ** such savepoints while the statement transaction savepoint is active. */ rc = sqlite3PagerOpenSavepoint(pBt->pPager, iStatement); sqlite3BtreeLeave(p); return rc; } /* ** The second argument to this function, op, is always SAVEPOINT_ROLLBACK ** or SAVEPOINT_RELEASE. This function either releases or rolls back the ** savepoint identified by parameter iSavepoint, depending on the value ** of op. ** ** Normally, iSavepoint is greater than or equal to zero. However, if op is ** SAVEPOINT_ROLLBACK, then iSavepoint may also be -1. In this case the ** contents of the entire transaction are rolled back. This is different ** from a normal transaction rollback, as no locks are released and the ** transaction remains open. */ SQLITE_PRIVATE int sqlite3BtreeSavepoint(Btree *p, int op, int iSavepoint){ int rc = SQLITE_OK; if( p && p->inTrans==TRANS_WRITE ){ BtShared *pBt = p->pBt; assert( op==SAVEPOINT_RELEASE || op==SAVEPOINT_ROLLBACK ); assert( iSavepoint>=0 || (iSavepoint==-1 && op==SAVEPOINT_ROLLBACK) ); sqlite3BtreeEnter(p); rc = sqlite3PagerSavepoint(pBt->pPager, op, iSavepoint); if( rc==SQLITE_OK ){ if( iSavepoint<0 && (pBt->btsFlags & BTS_INITIALLY_EMPTY)!=0 ){ pBt->nPage = 0; } rc = newDatabase(pBt); pBt->nPage = get4byte(28 + pBt->pPage1->aData); /* The database size was written into the offset 28 of the header ** when the transaction started, so we know that the value at offset ** 28 is nonzero. */ assert( pBt->nPage>0 ); } sqlite3BtreeLeave(p); } return rc; } /* ** Create a new cursor for the BTree whose root is on the page ** iTable. If a read-only cursor is requested, it is assumed that ** the caller already has at least a read-only transaction open ** on the database already. If a write-cursor is requested, then ** the caller is assumed to have an open write transaction. ** ** If the BTREE_WRCSR bit of wrFlag is clear, then the cursor can only ** be used for reading. If the BTREE_WRCSR bit is set, then the cursor ** can be used for reading or for writing if other conditions for writing ** are also met. These are the conditions that must be met in order ** for writing to be allowed: ** ** 1: The cursor must have been opened with wrFlag containing BTREE_WRCSR ** ** 2: Other database connections that share the same pager cache ** but which are not in the READ_UNCOMMITTED state may not have ** cursors open with wrFlag==0 on the same table. Otherwise ** the changes made by this write cursor would be visible to ** the read cursors in the other database connection. ** ** 3: The database must be writable (not on read-only media) ** ** 4: There must be an active transaction. ** ** The BTREE_FORDELETE bit of wrFlag may optionally be set if BTREE_WRCSR ** is set. If FORDELETE is set, that is a hint to the implementation that ** this cursor will only be used to seek to and delete entries of an index ** as part of a larger DELETE statement. The FORDELETE hint is not used by ** this implementation. But in a hypothetical alternative storage engine ** in which index entries are automatically deleted when corresponding table ** rows are deleted, the FORDELETE flag is a hint that all SEEK and DELETE ** operations on this cursor can be no-ops and all READ operations can ** return a null row (2-bytes: 0x01 0x00). ** ** No checking is done to make sure that page iTable really is the ** root page of a b-tree. If it is not, then the cursor acquired ** will not work correctly. ** ** It is assumed that the sqlite3BtreeCursorZero() has been called ** on pCur to initialize the memory space prior to invoking this routine. */ static int btreeCursor( Btree *p, /* The btree */ int iTable, /* Root page of table to open */ int wrFlag, /* 1 to write. 0 read-only */ struct KeyInfo *pKeyInfo, /* First arg to comparison function */ BtCursor *pCur /* Space for new cursor */ ){ BtShared *pBt = p->pBt; /* Shared b-tree handle */ BtCursor *pX; /* Looping over other all cursors */ assert( sqlite3BtreeHoldsMutex(p) ); assert( wrFlag==0 || wrFlag==BTREE_WRCSR || wrFlag==(BTREE_WRCSR|BTREE_FORDELETE) ); /* The following assert statements verify that if this is a sharable ** b-tree database, the connection is holding the required table locks, ** and that no other connection has any open cursor that conflicts with ** this lock. */ assert( hasSharedCacheTableLock(p, iTable, pKeyInfo!=0, (wrFlag?2:1)) ); assert( wrFlag==0 || !hasReadConflicts(p, iTable) ); /* Assert that the caller has opened the required transaction. */ assert( p->inTrans>TRANS_NONE ); assert( wrFlag==0 || p->inTrans==TRANS_WRITE ); assert( pBt->pPage1 && pBt->pPage1->aData ); assert( wrFlag==0 || (pBt->btsFlags & BTS_READ_ONLY)==0 ); if( wrFlag ){ allocateTempSpace(pBt); if( pBt->pTmpSpace==0 ) return SQLITE_NOMEM_BKPT; } if( iTable==1 && btreePagecount(pBt)==0 ){ assert( wrFlag==0 ); iTable = 0; } /* Now that no other errors can occur, finish filling in the BtCursor ** variables and link the cursor into the BtShared list. */ pCur->pgnoRoot = (Pgno)iTable; pCur->iPage = -1; pCur->pKeyInfo = pKeyInfo; pCur->pBtree = p; pCur->pBt = pBt; pCur->curFlags = wrFlag ? BTCF_WriteFlag : 0; pCur->curPagerFlags = wrFlag ? 0 : PAGER_GET_READONLY; /* If there are two or more cursors on the same btree, then all such ** cursors *must* have the BTCF_Multiple flag set. */ for(pX=pBt->pCursor; pX; pX=pX->pNext){ if( pX->pgnoRoot==(Pgno)iTable ){ pX->curFlags |= BTCF_Multiple; pCur->curFlags |= BTCF_Multiple; } } pCur->pNext = pBt->pCursor; pBt->pCursor = pCur; pCur->eState = CURSOR_INVALID; return SQLITE_OK; } SQLITE_PRIVATE int sqlite3BtreeCursor( Btree *p, /* The btree */ int iTable, /* Root page of table to open */ int wrFlag, /* 1 to write. 0 read-only */ struct KeyInfo *pKeyInfo, /* First arg to xCompare() */ BtCursor *pCur /* Write new cursor here */ ){ int rc; if( iTable<1 ){ rc = SQLITE_CORRUPT_BKPT; }else{ sqlite3BtreeEnter(p); rc = btreeCursor(p, iTable, wrFlag, pKeyInfo, pCur); sqlite3BtreeLeave(p); } return rc; } /* ** Return the size of a BtCursor object in bytes. ** ** This interfaces is needed so that users of cursors can preallocate ** sufficient storage to hold a cursor. The BtCursor object is opaque ** to users so they cannot do the sizeof() themselves - they must call ** this routine. */ SQLITE_PRIVATE int sqlite3BtreeCursorSize(void){ return ROUND8(sizeof(BtCursor)); } /* ** Initialize memory that will be converted into a BtCursor object. ** ** The simple approach here would be to memset() the entire object ** to zero. But it turns out that the apPage[] and aiIdx[] arrays ** do not need to be zeroed and they are large, so we can save a lot ** of run-time by skipping the initialization of those elements. */ SQLITE_PRIVATE void sqlite3BtreeCursorZero(BtCursor *p){ memset(p, 0, offsetof(BtCursor, iPage)); } /* ** Close a cursor. The read lock on the database file is released ** when the last cursor is closed. */ SQLITE_PRIVATE int sqlite3BtreeCloseCursor(BtCursor *pCur){ Btree *pBtree = pCur->pBtree; if( pBtree ){ int i; BtShared *pBt = pCur->pBt; sqlite3BtreeEnter(pBtree); sqlite3BtreeClearCursor(pCur); assert( pBt->pCursor!=0 ); if( pBt->pCursor==pCur ){ pBt->pCursor = pCur->pNext; }else{ BtCursor *pPrev = pBt->pCursor; do{ if( pPrev->pNext==pCur ){ pPrev->pNext = pCur->pNext; break; } pPrev = pPrev->pNext; }while( ALWAYS(pPrev) ); } for(i=0; i<=pCur->iPage; i++){ releasePage(pCur->apPage[i]); } unlockBtreeIfUnused(pBt); sqlite3_free(pCur->aOverflow); /* sqlite3_free(pCur); */ sqlite3BtreeLeave(pBtree); } return SQLITE_OK; } /* ** Make sure the BtCursor* given in the argument has a valid ** BtCursor.info structure. If it is not already valid, call ** btreeParseCell() to fill it in. ** ** BtCursor.info is a cache of the information in the current cell. ** Using this cache reduces the number of calls to btreeParseCell(). */ #ifndef NDEBUG static void assertCellInfo(BtCursor *pCur){ CellInfo info; int iPage = pCur->iPage; memset(&info, 0, sizeof(info)); btreeParseCell(pCur->apPage[iPage], pCur->aiIdx[iPage], &info); assert( CORRUPT_DB || memcmp(&info, &pCur->info, sizeof(info))==0 ); } #else #define assertCellInfo(x) #endif static SQLITE_NOINLINE void getCellInfo(BtCursor *pCur){ if( pCur->info.nSize==0 ){ int iPage = pCur->iPage; pCur->curFlags |= BTCF_ValidNKey; btreeParseCell(pCur->apPage[iPage],pCur->aiIdx[iPage],&pCur->info); }else{ assertCellInfo(pCur); } } #ifndef NDEBUG /* The next routine used only within assert() statements */ /* ** Return true if the given BtCursor is valid. A valid cursor is one ** that is currently pointing to a row in a (non-empty) table. ** This is a verification routine is used only within assert() statements. */ SQLITE_PRIVATE int sqlite3BtreeCursorIsValid(BtCursor *pCur){ return pCur && pCur->eState==CURSOR_VALID; } #endif /* NDEBUG */ /* ** Return the value of the integer key or "rowid" for a table btree. ** This routine is only valid for a cursor that is pointing into a ** ordinary table btree. If the cursor points to an index btree or ** is invalid, the result of this routine is undefined. */ SQLITE_PRIVATE i64 sqlite3BtreeIntegerKey(BtCursor *pCur){ assert( cursorHoldsMutex(pCur) ); assert( pCur->eState==CURSOR_VALID ); assert( pCur->curIntKey ); getCellInfo(pCur); return pCur->info.nKey; } /* ** Return the number of bytes of payload for the entry that pCur is ** currently pointing to. For table btrees, this will be the amount ** of data. For index btrees, this will be the size of the key. ** ** The caller must guarantee that the cursor is pointing to a non-NULL ** valid entry. In other words, the calling procedure must guarantee ** that the cursor has Cursor.eState==CURSOR_VALID. */ SQLITE_PRIVATE u32 sqlite3BtreePayloadSize(BtCursor *pCur){ assert( cursorHoldsMutex(pCur) ); assert( pCur->eState==CURSOR_VALID ); getCellInfo(pCur); return pCur->info.nPayload; } /* ** Given the page number of an overflow page in the database (parameter ** ovfl), this function finds the page number of the next page in the ** linked list of overflow pages. If possible, it uses the auto-vacuum ** pointer-map data instead of reading the content of page ovfl to do so. ** ** If an error occurs an SQLite error code is returned. Otherwise: ** ** The page number of the next overflow page in the linked list is ** written to *pPgnoNext. If page ovfl is the last page in its linked ** list, *pPgnoNext is set to zero. ** ** If ppPage is not NULL, and a reference to the MemPage object corresponding ** to page number pOvfl was obtained, then *ppPage is set to point to that ** reference. It is the responsibility of the caller to call releasePage() ** on *ppPage to free the reference. In no reference was obtained (because ** the pointer-map was used to obtain the value for *pPgnoNext), then ** *ppPage is set to zero. */ static int getOverflowPage( BtShared *pBt, /* The database file */ Pgno ovfl, /* Current overflow page number */ MemPage **ppPage, /* OUT: MemPage handle (may be NULL) */ Pgno *pPgnoNext /* OUT: Next overflow page number */ ){ Pgno next = 0; MemPage *pPage = 0; int rc = SQLITE_OK; assert( sqlite3_mutex_held(pBt->mutex) ); assert(pPgnoNext); #ifndef SQLITE_OMIT_AUTOVACUUM /* Try to find the next page in the overflow list using the ** autovacuum pointer-map pages. Guess that the next page in ** the overflow list is page number (ovfl+1). If that guess turns ** out to be wrong, fall back to loading the data of page ** number ovfl to determine the next page number. */ if( pBt->autoVacuum ){ Pgno pgno; Pgno iGuess = ovfl+1; u8 eType; while( PTRMAP_ISPAGE(pBt, iGuess) || iGuess==PENDING_BYTE_PAGE(pBt) ){ iGuess++; } if( iGuess<=btreePagecount(pBt) ){ rc = ptrmapGet(pBt, iGuess, &eType, &pgno); if( rc==SQLITE_OK && eType==PTRMAP_OVERFLOW2 && pgno==ovfl ){ next = iGuess; rc = SQLITE_DONE; } } } #endif assert( next==0 || rc==SQLITE_DONE ); if( rc==SQLITE_OK ){ rc = btreeGetPage(pBt, ovfl, &pPage, (ppPage==0) ? PAGER_GET_READONLY : 0); assert( rc==SQLITE_OK || pPage==0 ); if( rc==SQLITE_OK ){ next = get4byte(pPage->aData); } } *pPgnoNext = next; if( ppPage ){ *ppPage = pPage; }else{ releasePage(pPage); } return (rc==SQLITE_DONE ? SQLITE_OK : rc); } /* ** Copy data from a buffer to a page, or from a page to a buffer. ** ** pPayload is a pointer to data stored on database page pDbPage. ** If argument eOp is false, then nByte bytes of data are copied ** from pPayload to the buffer pointed at by pBuf. If eOp is true, ** then sqlite3PagerWrite() is called on pDbPage and nByte bytes ** of data are copied from the buffer pBuf to pPayload. ** ** SQLITE_OK is returned on success, otherwise an error code. */ static int copyPayload( void *pPayload, /* Pointer to page data */ void *pBuf, /* Pointer to buffer */ int nByte, /* Number of bytes to copy */ int eOp, /* 0 -> copy from page, 1 -> copy to page */ DbPage *pDbPage /* Page containing pPayload */ ){ if( eOp ){ /* Copy data from buffer to page (a write operation) */ int rc = sqlite3PagerWrite(pDbPage); if( rc!=SQLITE_OK ){ return rc; } memcpy(pPayload, pBuf, nByte); }else{ /* Copy data from page to buffer (a read operation) */ memcpy(pBuf, pPayload, nByte); } return SQLITE_OK; } /* ** This function is used to read or overwrite payload information ** for the entry that the pCur cursor is pointing to. The eOp ** argument is interpreted as follows: ** ** 0: The operation is a read. Populate the overflow cache. ** 1: The operation is a write. Populate the overflow cache. ** 2: The operation is a read. Do not populate the overflow cache. ** ** A total of "amt" bytes are read or written beginning at "offset". ** Data is read to or from the buffer pBuf. ** ** The content being read or written might appear on the main page ** or be scattered out on multiple overflow pages. ** ** If the current cursor entry uses one or more overflow pages and the ** eOp argument is not 2, this function may allocate space for and lazily ** populates the overflow page-list cache array (BtCursor.aOverflow). ** Subsequent calls use this cache to make seeking to the supplied offset ** more efficient. ** ** Once an overflow page-list cache has been allocated, it may be ** invalidated if some other cursor writes to the same table, or if ** the cursor is moved to a different row. Additionally, in auto-vacuum ** mode, the following events may invalidate an overflow page-list cache. ** ** * An incremental vacuum, ** * A commit in auto_vacuum="full" mode, ** * Creating a table (may require moving an overflow page). */ static int accessPayload( BtCursor *pCur, /* Cursor pointing to entry to read from */ u32 offset, /* Begin reading this far into payload */ u32 amt, /* Read this many bytes */ unsigned char *pBuf, /* Write the bytes into this buffer */ int eOp /* zero to read. non-zero to write. */ ){ unsigned char *aPayload; int rc = SQLITE_OK; int iIdx = 0; MemPage *pPage = pCur->apPage[pCur->iPage]; /* Btree page of current entry */ BtShared *pBt = pCur->pBt; /* Btree this cursor belongs to */ #ifdef SQLITE_DIRECT_OVERFLOW_READ unsigned char * const pBufStart = pBuf; int bEnd; /* True if reading to end of data */ #endif assert( pPage ); assert( pCur->eState==CURSOR_VALID ); assert( pCur->aiIdx[pCur->iPage]nCell ); assert( cursorHoldsMutex(pCur) ); assert( eOp!=2 || offset==0 ); /* Always start from beginning for eOp==2 */ getCellInfo(pCur); aPayload = pCur->info.pPayload; #ifdef SQLITE_DIRECT_OVERFLOW_READ bEnd = offset+amt==pCur->info.nPayload; #endif assert( offset+amt <= pCur->info.nPayload ); assert( aPayload > pPage->aData ); if( (uptr)(aPayload - pPage->aData) > (pBt->usableSize - pCur->info.nLocal) ){ /* Trying to read or write past the end of the data is an error. The ** conditional above is really: ** &aPayload[pCur->info.nLocal] > &pPage->aData[pBt->usableSize] ** but is recast into its current form to avoid integer overflow problems */ return SQLITE_CORRUPT_BKPT; } /* Check if data must be read/written to/from the btree page itself. */ if( offsetinfo.nLocal ){ int a = amt; if( a+offset>pCur->info.nLocal ){ a = pCur->info.nLocal - offset; } rc = copyPayload(&aPayload[offset], pBuf, a, (eOp & 0x01), pPage->pDbPage); offset = 0; pBuf += a; amt -= a; }else{ offset -= pCur->info.nLocal; } if( rc==SQLITE_OK && amt>0 ){ const u32 ovflSize = pBt->usableSize - 4; /* Bytes content per ovfl page */ Pgno nextPage; nextPage = get4byte(&aPayload[pCur->info.nLocal]); /* If the BtCursor.aOverflow[] has not been allocated, allocate it now. ** Except, do not allocate aOverflow[] for eOp==2. ** ** The aOverflow[] array is sized at one entry for each overflow page ** in the overflow chain. The page number of the first overflow page is ** stored in aOverflow[0], etc. A value of 0 in the aOverflow[] array ** means "not yet known" (the cache is lazily populated). */ if( eOp!=2 && (pCur->curFlags & BTCF_ValidOvfl)==0 ){ int nOvfl = (pCur->info.nPayload-pCur->info.nLocal+ovflSize-1)/ovflSize; if( nOvfl>pCur->nOvflAlloc ){ Pgno *aNew = (Pgno*)sqlite3Realloc( pCur->aOverflow, nOvfl*2*sizeof(Pgno) ); if( aNew==0 ){ rc = SQLITE_NOMEM_BKPT; }else{ pCur->nOvflAlloc = nOvfl*2; pCur->aOverflow = aNew; } } if( rc==SQLITE_OK ){ memset(pCur->aOverflow, 0, nOvfl*sizeof(Pgno)); pCur->curFlags |= BTCF_ValidOvfl; } } /* If the overflow page-list cache has been allocated and the ** entry for the first required overflow page is valid, skip ** directly to it. */ if( (pCur->curFlags & BTCF_ValidOvfl)!=0 && pCur->aOverflow[offset/ovflSize] ){ iIdx = (offset/ovflSize); nextPage = pCur->aOverflow[iIdx]; offset = (offset%ovflSize); } for( ; rc==SQLITE_OK && amt>0 && nextPage; iIdx++){ /* If required, populate the overflow page-list cache. */ if( (pCur->curFlags & BTCF_ValidOvfl)!=0 ){ assert( pCur->aOverflow[iIdx]==0 || pCur->aOverflow[iIdx]==nextPage || CORRUPT_DB ); pCur->aOverflow[iIdx] = nextPage; } if( offset>=ovflSize ){ /* The only reason to read this page is to obtain the page ** number for the next page in the overflow chain. The page ** data is not required. So first try to lookup the overflow ** page-list cache, if any, then fall back to the getOverflowPage() ** function. ** ** Note that the aOverflow[] array must be allocated because eOp!=2 ** here. If eOp==2, then offset==0 and this branch is never taken. */ assert( eOp!=2 ); assert( pCur->curFlags & BTCF_ValidOvfl ); assert( pCur->pBtree->db==pBt->db ); if( pCur->aOverflow[iIdx+1] ){ nextPage = pCur->aOverflow[iIdx+1]; }else{ rc = getOverflowPage(pBt, nextPage, 0, &nextPage); } offset -= ovflSize; }else{ /* Need to read this page properly. It contains some of the ** range of data that is being read (eOp==0) or written (eOp!=0). */ #ifdef SQLITE_DIRECT_OVERFLOW_READ sqlite3_file *fd; #endif int a = amt; if( a + offset > ovflSize ){ a = ovflSize - offset; } #ifdef SQLITE_DIRECT_OVERFLOW_READ /* If all the following are true: ** ** 1) this is a read operation, and ** 2) data is required from the start of this overflow page, and ** 3) the database is file-backed, and ** 4) there is no open write-transaction, and ** 5) the database is not a WAL database, ** 6) all data from the page is being read. ** 7) at least 4 bytes have already been read into the output buffer ** ** then data can be read directly from the database file into the ** output buffer, bypassing the page-cache altogether. This speeds ** up loading large records that span many overflow pages. */ if( (eOp&0x01)==0 /* (1) */ && offset==0 /* (2) */ && (bEnd || a==ovflSize) /* (6) */ && pBt->inTransaction==TRANS_READ /* (4) */ && (fd = sqlite3PagerFile(pBt->pPager))->pMethods /* (3) */ && 0==sqlite3PagerUseWal(pBt->pPager) /* (5) */ && &pBuf[-4]>=pBufStart /* (7) */ ){ u8 aSave[4]; u8 *aWrite = &pBuf[-4]; assert( aWrite>=pBufStart ); /* hence (7) */ memcpy(aSave, aWrite, 4); rc = sqlite3OsRead(fd, aWrite, a+4, (i64)pBt->pageSize*(nextPage-1)); nextPage = get4byte(aWrite); memcpy(aWrite, aSave, 4); }else #endif { DbPage *pDbPage; rc = sqlite3PagerGet(pBt->pPager, nextPage, &pDbPage, ((eOp&0x01)==0 ? PAGER_GET_READONLY : 0) ); if( rc==SQLITE_OK ){ aPayload = sqlite3PagerGetData(pDbPage); nextPage = get4byte(aPayload); rc = copyPayload(&aPayload[offset+4], pBuf, a, (eOp&0x01), pDbPage); sqlite3PagerUnref(pDbPage); offset = 0; } } amt -= a; pBuf += a; } } } if( rc==SQLITE_OK && amt>0 ){ return SQLITE_CORRUPT_BKPT; } return rc; } /* ** Read part of the key associated with cursor pCur. Exactly ** "amt" bytes will be transferred into pBuf[]. The transfer ** begins at "offset". ** ** The caller must ensure that pCur is pointing to a valid row ** in the table. ** ** Return SQLITE_OK on success or an error code if anything goes ** wrong. An error is returned if "offset+amt" is larger than ** the available payload. */ SQLITE_PRIVATE int sqlite3BtreeKey(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){ assert( cursorHoldsMutex(pCur) ); assert( pCur->eState==CURSOR_VALID ); assert( pCur->iPage>=0 && pCur->apPage[pCur->iPage] ); assert( pCur->aiIdx[pCur->iPage]apPage[pCur->iPage]->nCell ); return accessPayload(pCur, offset, amt, (unsigned char*)pBuf, 0); } /* ** Read part of the data associated with cursor pCur. Exactly ** "amt" bytes will be transfered into pBuf[]. The transfer ** begins at "offset". ** ** Return SQLITE_OK on success or an error code if anything goes ** wrong. An error is returned if "offset+amt" is larger than ** the available payload. */ SQLITE_PRIVATE int sqlite3BtreeData(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){ int rc; #ifndef SQLITE_OMIT_INCRBLOB if ( pCur->eState==CURSOR_INVALID ){ return SQLITE_ABORT; } #endif assert( cursorOwnsBtShared(pCur) ); rc = restoreCursorPosition(pCur); if( rc==SQLITE_OK ){ assert( pCur->eState==CURSOR_VALID ); assert( pCur->iPage>=0 && pCur->apPage[pCur->iPage] ); assert( pCur->aiIdx[pCur->iPage]apPage[pCur->iPage]->nCell ); rc = accessPayload(pCur, offset, amt, pBuf, 0); } return rc; } /* ** Return a pointer to payload information from the entry that the ** pCur cursor is pointing to. The pointer is to the beginning of ** the key if index btrees (pPage->intKey==0) and is the data for ** table btrees (pPage->intKey==1). The number of bytes of available ** key/data is written into *pAmt. If *pAmt==0, then the value ** returned will not be a valid pointer. ** ** This routine is an optimization. It is common for the entire key ** and data to fit on the local page and for there to be no overflow ** pages. When that is so, this routine can be used to access the ** key and data without making a copy. If the key and/or data spills ** onto overflow pages, then accessPayload() must be used to reassemble ** the key/data and copy it into a preallocated buffer. ** ** The pointer returned by this routine looks directly into the cached ** page of the database. The data might change or move the next time ** any btree routine is called. */ static const void *fetchPayload( BtCursor *pCur, /* Cursor pointing to entry to read from */ u32 *pAmt /* Write the number of available bytes here */ ){ u32 amt; assert( pCur!=0 && pCur->iPage>=0 && pCur->apPage[pCur->iPage]); assert( pCur->eState==CURSOR_VALID ); assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) ); assert( cursorOwnsBtShared(pCur) ); assert( pCur->aiIdx[pCur->iPage]apPage[pCur->iPage]->nCell ); assert( pCur->info.nSize>0 ); assert( pCur->info.pPayload>pCur->apPage[pCur->iPage]->aData || CORRUPT_DB ); assert( pCur->info.pPayloadapPage[pCur->iPage]->aDataEnd ||CORRUPT_DB); amt = (int)(pCur->apPage[pCur->iPage]->aDataEnd - pCur->info.pPayload); if( pCur->info.nLocalinfo.nLocal; *pAmt = amt; return (void*)pCur->info.pPayload; } /* ** For the entry that cursor pCur is point to, return as ** many bytes of the key or data as are available on the local ** b-tree page. Write the number of available bytes into *pAmt. ** ** The pointer returned is ephemeral. The key/data may move ** or be destroyed on the next call to any Btree routine, ** including calls from other threads against the same cache. ** Hence, a mutex on the BtShared should be held prior to calling ** this routine. ** ** These routines is used to get quick access to key and data ** in the common case where no overflow pages are used. */ SQLITE_PRIVATE const void *sqlite3BtreePayloadFetch(BtCursor *pCur, u32 *pAmt){ return fetchPayload(pCur, pAmt); } /* ** Move the cursor down to a new child page. The newPgno argument is the ** page number of the child page to move to. ** ** This function returns SQLITE_CORRUPT if the page-header flags field of ** the new child page does not match the flags field of the parent (i.e. ** if an intkey page appears to be the parent of a non-intkey page, or ** vice-versa). */ static int moveToChild(BtCursor *pCur, u32 newPgno){ BtShared *pBt = pCur->pBt; assert( cursorOwnsBtShared(pCur) ); assert( pCur->eState==CURSOR_VALID ); assert( pCur->iPageiPage>=0 ); if( pCur->iPage>=(BTCURSOR_MAX_DEPTH-1) ){ return SQLITE_CORRUPT_BKPT; } pCur->info.nSize = 0; pCur->curFlags &= ~(BTCF_ValidNKey|BTCF_ValidOvfl); pCur->iPage++; pCur->aiIdx[pCur->iPage] = 0; return getAndInitPage(pBt, newPgno, &pCur->apPage[pCur->iPage], pCur, pCur->curPagerFlags); } #if SQLITE_DEBUG /* ** Page pParent is an internal (non-leaf) tree page. This function ** asserts that page number iChild is the left-child if the iIdx'th ** cell in page pParent. Or, if iIdx is equal to the total number of ** cells in pParent, that page number iChild is the right-child of ** the page. */ static void assertParentIndex(MemPage *pParent, int iIdx, Pgno iChild){ if( CORRUPT_DB ) return; /* The conditions tested below might not be true ** in a corrupt database */ assert( iIdx<=pParent->nCell ); if( iIdx==pParent->nCell ){ assert( get4byte(&pParent->aData[pParent->hdrOffset+8])==iChild ); }else{ assert( get4byte(findCell(pParent, iIdx))==iChild ); } } #else # define assertParentIndex(x,y,z) #endif /* ** Move the cursor up to the parent page. ** ** pCur->idx is set to the cell index that contains the pointer ** to the page we are coming from. If we are coming from the ** right-most child page then pCur->idx is set to one more than ** the largest cell index. */ static void moveToParent(BtCursor *pCur){ assert( cursorOwnsBtShared(pCur) ); assert( pCur->eState==CURSOR_VALID ); assert( pCur->iPage>0 ); assert( pCur->apPage[pCur->iPage] ); assertParentIndex( pCur->apPage[pCur->iPage-1], pCur->aiIdx[pCur->iPage-1], pCur->apPage[pCur->iPage]->pgno ); testcase( pCur->aiIdx[pCur->iPage-1] > pCur->apPage[pCur->iPage-1]->nCell ); pCur->info.nSize = 0; pCur->curFlags &= ~(BTCF_ValidNKey|BTCF_ValidOvfl); releasePageNotNull(pCur->apPage[pCur->iPage--]); } /* ** Move the cursor to point to the root page of its b-tree structure. ** ** If the table has a virtual root page, then the cursor is moved to point ** to the virtual root page instead of the actual root page. A table has a ** virtual root page when the actual root page contains no cells and a ** single child page. This can only happen with the table rooted at page 1. ** ** If the b-tree structure is empty, the cursor state is set to ** CURSOR_INVALID. Otherwise, the cursor is set to point to the first ** cell located on the root (or virtual root) page and the cursor state ** is set to CURSOR_VALID. ** ** If this function returns successfully, it may be assumed that the ** page-header flags indicate that the [virtual] root-page is the expected ** kind of b-tree page (i.e. if when opening the cursor the caller did not ** specify a KeyInfo structure the flags byte is set to 0x05 or 0x0D, ** indicating a table b-tree, or if the caller did specify a KeyInfo ** structure the flags byte is set to 0x02 or 0x0A, indicating an index ** b-tree). */ static int moveToRoot(BtCursor *pCur){ MemPage *pRoot; int rc = SQLITE_OK; assert( cursorOwnsBtShared(pCur) ); assert( CURSOR_INVALID < CURSOR_REQUIRESEEK ); assert( CURSOR_VALID < CURSOR_REQUIRESEEK ); assert( CURSOR_FAULT > CURSOR_REQUIRESEEK ); if( pCur->eState>=CURSOR_REQUIRESEEK ){ if( pCur->eState==CURSOR_FAULT ){ assert( pCur->skipNext!=SQLITE_OK ); return pCur->skipNext; } sqlite3BtreeClearCursor(pCur); } if( pCur->iPage>=0 ){ while( pCur->iPage ){ assert( pCur->apPage[pCur->iPage]!=0 ); releasePageNotNull(pCur->apPage[pCur->iPage--]); } }else if( pCur->pgnoRoot==0 ){ pCur->eState = CURSOR_INVALID; return SQLITE_OK; }else{ assert( pCur->iPage==(-1) ); rc = getAndInitPage(pCur->pBtree->pBt, pCur->pgnoRoot, &pCur->apPage[0], 0, pCur->curPagerFlags); if( rc!=SQLITE_OK ){ pCur->eState = CURSOR_INVALID; return rc; } pCur->iPage = 0; pCur->curIntKey = pCur->apPage[0]->intKey; } pRoot = pCur->apPage[0]; assert( pRoot->pgno==pCur->pgnoRoot ); /* If pCur->pKeyInfo is not NULL, then the caller that opened this cursor ** expected to open it on an index b-tree. Otherwise, if pKeyInfo is ** NULL, the caller expects a table b-tree. If this is not the case, ** return an SQLITE_CORRUPT error. ** ** Earlier versions of SQLite assumed that this test could not fail ** if the root page was already loaded when this function was called (i.e. ** if pCur->iPage>=0). But this is not so if the database is corrupted ** in such a way that page pRoot is linked into a second b-tree table ** (or the freelist). */ assert( pRoot->intKey==1 || pRoot->intKey==0 ); if( pRoot->isInit==0 || (pCur->pKeyInfo==0)!=pRoot->intKey ){ return SQLITE_CORRUPT_BKPT; } pCur->aiIdx[0] = 0; pCur->info.nSize = 0; pCur->curFlags &= ~(BTCF_AtLast|BTCF_ValidNKey|BTCF_ValidOvfl); if( pRoot->nCell>0 ){ pCur->eState = CURSOR_VALID; }else if( !pRoot->leaf ){ Pgno subpage; if( pRoot->pgno!=1 ) return SQLITE_CORRUPT_BKPT; subpage = get4byte(&pRoot->aData[pRoot->hdrOffset+8]); pCur->eState = CURSOR_VALID; rc = moveToChild(pCur, subpage); }else{ pCur->eState = CURSOR_INVALID; } return rc; } /* ** Move the cursor down to the left-most leaf entry beneath the ** entry to which it is currently pointing. ** ** The left-most leaf is the one with the smallest key - the first ** in ascending order. */ static int moveToLeftmost(BtCursor *pCur){ Pgno pgno; int rc = SQLITE_OK; MemPage *pPage; assert( cursorOwnsBtShared(pCur) ); assert( pCur->eState==CURSOR_VALID ); while( rc==SQLITE_OK && !(pPage = pCur->apPage[pCur->iPage])->leaf ){ assert( pCur->aiIdx[pCur->iPage]nCell ); pgno = get4byte(findCell(pPage, pCur->aiIdx[pCur->iPage])); rc = moveToChild(pCur, pgno); } return rc; } /* ** Move the cursor down to the right-most leaf entry beneath the ** page to which it is currently pointing. Notice the difference ** between moveToLeftmost() and moveToRightmost(). moveToLeftmost() ** finds the left-most entry beneath the *entry* whereas moveToRightmost() ** finds the right-most entry beneath the *page*. ** ** The right-most entry is the one with the largest key - the last ** key in ascending order. */ static int moveToRightmost(BtCursor *pCur){ Pgno pgno; int rc = SQLITE_OK; MemPage *pPage = 0; assert( cursorOwnsBtShared(pCur) ); assert( pCur->eState==CURSOR_VALID ); while( !(pPage = pCur->apPage[pCur->iPage])->leaf ){ pgno = get4byte(&pPage->aData[pPage->hdrOffset+8]); pCur->aiIdx[pCur->iPage] = pPage->nCell; rc = moveToChild(pCur, pgno); if( rc ) return rc; } pCur->aiIdx[pCur->iPage] = pPage->nCell-1; assert( pCur->info.nSize==0 ); assert( (pCur->curFlags & BTCF_ValidNKey)==0 ); return SQLITE_OK; } /* Move the cursor to the first entry in the table. Return SQLITE_OK ** on success. Set *pRes to 0 if the cursor actually points to something ** or set *pRes to 1 if the table is empty. */ SQLITE_PRIVATE int sqlite3BtreeFirst(BtCursor *pCur, int *pRes){ int rc; assert( cursorOwnsBtShared(pCur) ); assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) ); rc = moveToRoot(pCur); if( rc==SQLITE_OK ){ if( pCur->eState==CURSOR_INVALID ){ assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage]->nCell==0 ); *pRes = 1; }else{ assert( pCur->apPage[pCur->iPage]->nCell>0 ); *pRes = 0; rc = moveToLeftmost(pCur); } } return rc; } /* Move the cursor to the last entry in the table. Return SQLITE_OK ** on success. Set *pRes to 0 if the cursor actually points to something ** or set *pRes to 1 if the table is empty. */ SQLITE_PRIVATE int sqlite3BtreeLast(BtCursor *pCur, int *pRes){ int rc; assert( cursorOwnsBtShared(pCur) ); assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) ); /* If the cursor already points to the last entry, this is a no-op. */ if( CURSOR_VALID==pCur->eState && (pCur->curFlags & BTCF_AtLast)!=0 ){ #ifdef SQLITE_DEBUG /* This block serves to assert() that the cursor really does point ** to the last entry in the b-tree. */ int ii; for(ii=0; iiiPage; ii++){ assert( pCur->aiIdx[ii]==pCur->apPage[ii]->nCell ); } assert( pCur->aiIdx[pCur->iPage]==pCur->apPage[pCur->iPage]->nCell-1 ); assert( pCur->apPage[pCur->iPage]->leaf ); #endif return SQLITE_OK; } rc = moveToRoot(pCur); if( rc==SQLITE_OK ){ if( CURSOR_INVALID==pCur->eState ){ assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage]->nCell==0 ); *pRes = 1; }else{ assert( pCur->eState==CURSOR_VALID ); *pRes = 0; rc = moveToRightmost(pCur); if( rc==SQLITE_OK ){ pCur->curFlags |= BTCF_AtLast; }else{ pCur->curFlags &= ~BTCF_AtLast; } } } return rc; } /* Move the cursor so that it points to an entry near the key ** specified by pIdxKey or intKey. Return a success code. ** ** For INTKEY tables, the intKey parameter is used. pIdxKey ** must be NULL. For index tables, pIdxKey is used and intKey ** is ignored. ** ** If an exact match is not found, then the cursor is always ** left pointing at a leaf page which would hold the entry if it ** were present. The cursor might point to an entry that comes ** before or after the key. ** ** An integer is written into *pRes which is the result of ** comparing the key with the entry to which the cursor is ** pointing. The meaning of the integer written into ** *pRes is as follows: ** ** *pRes<0 The cursor is left pointing at an entry that ** is smaller than intKey/pIdxKey or if the table is empty ** and the cursor is therefore left point to nothing. ** ** *pRes==0 The cursor is left pointing at an entry that ** exactly matches intKey/pIdxKey. ** ** *pRes>0 The cursor is left pointing at an entry that ** is larger than intKey/pIdxKey. ** ** For index tables, the pIdxKey->eqSeen field is set to 1 if there ** exists an entry in the table that exactly matches pIdxKey. */ SQLITE_PRIVATE int sqlite3BtreeMovetoUnpacked( BtCursor *pCur, /* The cursor to be moved */ UnpackedRecord *pIdxKey, /* Unpacked index key */ i64 intKey, /* The table key */ int biasRight, /* If true, bias the search to the high end */ int *pRes /* Write search results here */ ){ int rc; RecordCompare xRecordCompare; assert( cursorOwnsBtShared(pCur) ); assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) ); assert( pRes ); assert( (pIdxKey==0)==(pCur->pKeyInfo==0) ); assert( pCur->eState!=CURSOR_VALID || (pIdxKey==0)==(pCur->curIntKey!=0) ); /* If the cursor is already positioned at the point we are trying ** to move to, then just return without doing any work */ if( pIdxKey==0 && pCur->eState==CURSOR_VALID && (pCur->curFlags & BTCF_ValidNKey)!=0 ){ if( pCur->info.nKey==intKey ){ *pRes = 0; return SQLITE_OK; } if( (pCur->curFlags & BTCF_AtLast)!=0 && pCur->info.nKeyerrCode = 0; assert( pIdxKey->default_rc==1 || pIdxKey->default_rc==0 || pIdxKey->default_rc==-1 ); }else{ xRecordCompare = 0; /* All keys are integers */ } rc = moveToRoot(pCur); if( rc ){ return rc; } assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage] ); assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage]->isInit ); assert( pCur->eState==CURSOR_INVALID || pCur->apPage[pCur->iPage]->nCell>0 ); if( pCur->eState==CURSOR_INVALID ){ *pRes = -1; assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage]->nCell==0 ); return SQLITE_OK; } assert( pCur->apPage[0]->intKey==pCur->curIntKey ); assert( pCur->curIntKey || pIdxKey ); for(;;){ int lwr, upr, idx, c; Pgno chldPg; MemPage *pPage = pCur->apPage[pCur->iPage]; u8 *pCell; /* Pointer to current cell in pPage */ /* pPage->nCell must be greater than zero. If this is the root-page ** the cursor would have been INVALID above and this for(;;) loop ** not run. If this is not the root-page, then the moveToChild() routine ** would have already detected db corruption. Similarly, pPage must ** be the right kind (index or table) of b-tree page. Otherwise ** a moveToChild() or moveToRoot() call would have detected corruption. */ assert( pPage->nCell>0 ); assert( pPage->intKey==(pIdxKey==0) ); lwr = 0; upr = pPage->nCell-1; assert( biasRight==0 || biasRight==1 ); idx = upr>>(1-biasRight); /* idx = biasRight ? upr : (lwr+upr)/2; */ pCur->aiIdx[pCur->iPage] = (u16)idx; if( xRecordCompare==0 ){ for(;;){ i64 nCellKey; pCell = findCellPastPtr(pPage, idx); if( pPage->intKeyLeaf ){ while( 0x80 <= *(pCell++) ){ if( pCell>=pPage->aDataEnd ) return SQLITE_CORRUPT_BKPT; } } getVarint(pCell, (u64*)&nCellKey); if( nCellKeyupr ){ c = -1; break; } }else if( nCellKey>intKey ){ upr = idx-1; if( lwr>upr ){ c = +1; break; } }else{ assert( nCellKey==intKey ); pCur->curFlags |= BTCF_ValidNKey; pCur->info.nKey = nCellKey; pCur->aiIdx[pCur->iPage] = (u16)idx; if( !pPage->leaf ){ lwr = idx; goto moveto_next_layer; }else{ *pRes = 0; rc = SQLITE_OK; goto moveto_finish; } } assert( lwr+upr>=0 ); idx = (lwr+upr)>>1; /* idx = (lwr+upr)/2; */ } }else{ for(;;){ int nCell; /* Size of the pCell cell in bytes */ pCell = findCellPastPtr(pPage, idx); /* The maximum supported page-size is 65536 bytes. This means that ** the maximum number of record bytes stored on an index B-Tree ** page is less than 16384 bytes and may be stored as a 2-byte ** varint. This information is used to attempt to avoid parsing ** the entire cell by checking for the cases where the record is ** stored entirely within the b-tree page by inspecting the first ** 2 bytes of the cell. */ nCell = pCell[0]; if( nCell<=pPage->max1bytePayload ){ /* This branch runs if the record-size field of the cell is a ** single byte varint and the record fits entirely on the main ** b-tree page. */ testcase( pCell+nCell+1==pPage->aDataEnd ); c = xRecordCompare(nCell, (void*)&pCell[1], pIdxKey); }else if( !(pCell[1] & 0x80) && (nCell = ((nCell&0x7f)<<7) + pCell[1])<=pPage->maxLocal ){ /* The record-size field is a 2 byte varint and the record ** fits entirely on the main b-tree page. */ testcase( pCell+nCell+2==pPage->aDataEnd ); c = xRecordCompare(nCell, (void*)&pCell[2], pIdxKey); }else{ /* The record flows over onto one or more overflow pages. In ** this case the whole cell needs to be parsed, a buffer allocated ** and accessPayload() used to retrieve the record into the ** buffer before VdbeRecordCompare() can be called. ** ** If the record is corrupt, the xRecordCompare routine may read ** up to two varints past the end of the buffer. An extra 18 ** bytes of padding is allocated at the end of the buffer in ** case this happens. */ void *pCellKey; u8 * const pCellBody = pCell - pPage->childPtrSize; pPage->xParseCell(pPage, pCellBody, &pCur->info); nCell = (int)pCur->info.nKey; testcase( nCell<0 ); /* True if key size is 2^32 or more */ testcase( nCell==0 ); /* Invalid key size: 0x80 0x80 0x00 */ testcase( nCell==1 ); /* Invalid key size: 0x80 0x80 0x01 */ testcase( nCell==2 ); /* Minimum legal index key size */ if( nCell<2 ){ rc = SQLITE_CORRUPT_BKPT; goto moveto_finish; } pCellKey = sqlite3Malloc( nCell+18 ); if( pCellKey==0 ){ rc = SQLITE_NOMEM_BKPT; goto moveto_finish; } pCur->aiIdx[pCur->iPage] = (u16)idx; rc = accessPayload(pCur, 0, nCell, (unsigned char*)pCellKey, 2); if( rc ){ sqlite3_free(pCellKey); goto moveto_finish; } c = xRecordCompare(nCell, pCellKey, pIdxKey); sqlite3_free(pCellKey); } assert( (pIdxKey->errCode!=SQLITE_CORRUPT || c==0) && (pIdxKey->errCode!=SQLITE_NOMEM || pCur->pBtree->db->mallocFailed) ); if( c<0 ){ lwr = idx+1; }else if( c>0 ){ upr = idx-1; }else{ assert( c==0 ); *pRes = 0; rc = SQLITE_OK; pCur->aiIdx[pCur->iPage] = (u16)idx; if( pIdxKey->errCode ) rc = SQLITE_CORRUPT; goto moveto_finish; } if( lwr>upr ) break; assert( lwr+upr>=0 ); idx = (lwr+upr)>>1; /* idx = (lwr+upr)/2 */ } } assert( lwr==upr+1 || (pPage->intKey && !pPage->leaf) ); assert( pPage->isInit ); if( pPage->leaf ){ assert( pCur->aiIdx[pCur->iPage]apPage[pCur->iPage]->nCell ); pCur->aiIdx[pCur->iPage] = (u16)idx; *pRes = c; rc = SQLITE_OK; goto moveto_finish; } moveto_next_layer: if( lwr>=pPage->nCell ){ chldPg = get4byte(&pPage->aData[pPage->hdrOffset+8]); }else{ chldPg = get4byte(findCell(pPage, lwr)); } pCur->aiIdx[pCur->iPage] = (u16)lwr; rc = moveToChild(pCur, chldPg); if( rc ) break; } moveto_finish: pCur->info.nSize = 0; pCur->curFlags &= ~(BTCF_ValidNKey|BTCF_ValidOvfl); return rc; } /* ** Return TRUE if the cursor is not pointing at an entry of the table. ** ** TRUE will be returned after a call to sqlite3BtreeNext() moves ** past the last entry in the table or sqlite3BtreePrev() moves past ** the first entry. TRUE is also returned if the table is empty. */ SQLITE_PRIVATE int sqlite3BtreeEof(BtCursor *pCur){ /* TODO: What if the cursor is in CURSOR_REQUIRESEEK but all table entries ** have been deleted? This API will need to change to return an error code ** as well as the boolean result value. */ return (CURSOR_VALID!=pCur->eState); } /* ** Advance the cursor to the next entry in the database. If ** successful then set *pRes=0. If the cursor ** was already pointing to the last entry in the database before ** this routine was called, then set *pRes=1. ** ** The main entry point is sqlite3BtreeNext(). That routine is optimized ** for the common case of merely incrementing the cell counter BtCursor.aiIdx ** to the next cell on the current page. The (slower) btreeNext() helper ** routine is called when it is necessary to move to a different page or ** to restore the cursor. ** ** The calling function will set *pRes to 0 or 1. The initial *pRes value ** will be 1 if the cursor being stepped corresponds to an SQL index and ** if this routine could have been skipped if that SQL index had been ** a unique index. Otherwise the caller will have set *pRes to zero. ** Zero is the common case. The btree implementation is free to use the ** initial *pRes value as a hint to improve performance, but the current ** SQLite btree implementation does not. (Note that the comdb2 btree ** implementation does use this hint, however.) */ static SQLITE_NOINLINE int btreeNext(BtCursor *pCur, int *pRes){ int rc; int idx; MemPage *pPage; assert( cursorOwnsBtShared(pCur) ); assert( pCur->skipNext==0 || pCur->eState!=CURSOR_VALID ); assert( *pRes==0 ); if( pCur->eState!=CURSOR_VALID ){ assert( (pCur->curFlags & BTCF_ValidOvfl)==0 ); rc = restoreCursorPosition(pCur); if( rc!=SQLITE_OK ){ return rc; } if( CURSOR_INVALID==pCur->eState ){ *pRes = 1; return SQLITE_OK; } if( pCur->skipNext ){ assert( pCur->eState==CURSOR_VALID || pCur->eState==CURSOR_SKIPNEXT ); pCur->eState = CURSOR_VALID; if( pCur->skipNext>0 ){ pCur->skipNext = 0; return SQLITE_OK; } pCur->skipNext = 0; } } pPage = pCur->apPage[pCur->iPage]; idx = ++pCur->aiIdx[pCur->iPage]; assert( pPage->isInit ); /* If the database file is corrupt, it is possible for the value of idx ** to be invalid here. This can only occur if a second cursor modifies ** the page while cursor pCur is holding a reference to it. Which can ** only happen if the database is corrupt in such a way as to link the ** page into more than one b-tree structure. */ testcase( idx>pPage->nCell ); if( idx>=pPage->nCell ){ if( !pPage->leaf ){ rc = moveToChild(pCur, get4byte(&pPage->aData[pPage->hdrOffset+8])); if( rc ) return rc; return moveToLeftmost(pCur); } do{ if( pCur->iPage==0 ){ *pRes = 1; pCur->eState = CURSOR_INVALID; return SQLITE_OK; } moveToParent(pCur); pPage = pCur->apPage[pCur->iPage]; }while( pCur->aiIdx[pCur->iPage]>=pPage->nCell ); if( pPage->intKey ){ return sqlite3BtreeNext(pCur, pRes); }else{ return SQLITE_OK; } } if( pPage->leaf ){ return SQLITE_OK; }else{ return moveToLeftmost(pCur); } } SQLITE_PRIVATE int sqlite3BtreeNext(BtCursor *pCur, int *pRes){ MemPage *pPage; assert( cursorOwnsBtShared(pCur) ); assert( pRes!=0 ); assert( *pRes==0 || *pRes==1 ); assert( pCur->skipNext==0 || pCur->eState!=CURSOR_VALID ); pCur->info.nSize = 0; pCur->curFlags &= ~(BTCF_ValidNKey|BTCF_ValidOvfl); *pRes = 0; if( pCur->eState!=CURSOR_VALID ) return btreeNext(pCur, pRes); pPage = pCur->apPage[pCur->iPage]; if( (++pCur->aiIdx[pCur->iPage])>=pPage->nCell ){ pCur->aiIdx[pCur->iPage]--; return btreeNext(pCur, pRes); } if( pPage->leaf ){ return SQLITE_OK; }else{ return moveToLeftmost(pCur); } } /* ** Step the cursor to the back to the previous entry in the database. If ** successful then set *pRes=0. If the cursor ** was already pointing to the first entry in the database before ** this routine was called, then set *pRes=1. ** ** The main entry point is sqlite3BtreePrevious(). That routine is optimized ** for the common case of merely decrementing the cell counter BtCursor.aiIdx ** to the previous cell on the current page. The (slower) btreePrevious() ** helper routine is called when it is necessary to move to a different page ** or to restore the cursor. ** ** The calling function will set *pRes to 0 or 1. The initial *pRes value ** will be 1 if the cursor being stepped corresponds to an SQL index and ** if this routine could have been skipped if that SQL index had been ** a unique index. Otherwise the caller will have set *pRes to zero. ** Zero is the common case. The btree implementation is free to use the ** initial *pRes value as a hint to improve performance, but the current ** SQLite btree implementation does not. (Note that the comdb2 btree ** implementation does use this hint, however.) */ static SQLITE_NOINLINE int btreePrevious(BtCursor *pCur, int *pRes){ int rc; MemPage *pPage; assert( cursorOwnsBtShared(pCur) ); assert( pRes!=0 ); assert( *pRes==0 ); assert( pCur->skipNext==0 || pCur->eState!=CURSOR_VALID ); assert( (pCur->curFlags & (BTCF_AtLast|BTCF_ValidOvfl|BTCF_ValidNKey))==0 ); assert( pCur->info.nSize==0 ); if( pCur->eState!=CURSOR_VALID ){ rc = restoreCursorPosition(pCur); if( rc!=SQLITE_OK ){ return rc; } if( CURSOR_INVALID==pCur->eState ){ *pRes = 1; return SQLITE_OK; } if( pCur->skipNext ){ assert( pCur->eState==CURSOR_VALID || pCur->eState==CURSOR_SKIPNEXT ); pCur->eState = CURSOR_VALID; if( pCur->skipNext<0 ){ pCur->skipNext = 0; return SQLITE_OK; } pCur->skipNext = 0; } } pPage = pCur->apPage[pCur->iPage]; assert( pPage->isInit ); if( !pPage->leaf ){ int idx = pCur->aiIdx[pCur->iPage]; rc = moveToChild(pCur, get4byte(findCell(pPage, idx))); if( rc ) return rc; rc = moveToRightmost(pCur); }else{ while( pCur->aiIdx[pCur->iPage]==0 ){ if( pCur->iPage==0 ){ pCur->eState = CURSOR_INVALID; *pRes = 1; return SQLITE_OK; } moveToParent(pCur); } assert( pCur->info.nSize==0 ); assert( (pCur->curFlags & (BTCF_ValidNKey|BTCF_ValidOvfl))==0 ); pCur->aiIdx[pCur->iPage]--; pPage = pCur->apPage[pCur->iPage]; if( pPage->intKey && !pPage->leaf ){ rc = sqlite3BtreePrevious(pCur, pRes); }else{ rc = SQLITE_OK; } } return rc; } SQLITE_PRIVATE int sqlite3BtreePrevious(BtCursor *pCur, int *pRes){ assert( cursorOwnsBtShared(pCur) ); assert( pRes!=0 ); assert( *pRes==0 || *pRes==1 ); assert( pCur->skipNext==0 || pCur->eState!=CURSOR_VALID ); *pRes = 0; pCur->curFlags &= ~(BTCF_AtLast|BTCF_ValidOvfl|BTCF_ValidNKey); pCur->info.nSize = 0; if( pCur->eState!=CURSOR_VALID || pCur->aiIdx[pCur->iPage]==0 || pCur->apPage[pCur->iPage]->leaf==0 ){ return btreePrevious(pCur, pRes); } pCur->aiIdx[pCur->iPage]--; return SQLITE_OK; } /* ** Allocate a new page from the database file. ** ** The new page is marked as dirty. (In other words, sqlite3PagerWrite() ** has already been called on the new page.) The new page has also ** been referenced and the calling routine is responsible for calling ** sqlite3PagerUnref() on the new page when it is done. ** ** SQLITE_OK is returned on success. Any other return value indicates ** an error. *ppPage is set to NULL in the event of an error. ** ** If the "nearby" parameter is not 0, then an effort is made to ** locate a page close to the page number "nearby". This can be used in an ** attempt to keep related pages close to each other in the database file, ** which in turn can make database access faster. ** ** If the eMode parameter is BTALLOC_EXACT and the nearby page exists ** anywhere on the free-list, then it is guaranteed to be returned. If ** eMode is BTALLOC_LT then the page returned will be less than or equal ** to nearby if any such page exists. If eMode is BTALLOC_ANY then there ** are no restrictions on which page is returned. */ static int allocateBtreePage( BtShared *pBt, /* The btree */ MemPage **ppPage, /* Store pointer to the allocated page here */ Pgno *pPgno, /* Store the page number here */ Pgno nearby, /* Search for a page near this one */ u8 eMode /* BTALLOC_EXACT, BTALLOC_LT, or BTALLOC_ANY */ ){ MemPage *pPage1; int rc; u32 n; /* Number of pages on the freelist */ u32 k; /* Number of leaves on the trunk of the freelist */ MemPage *pTrunk = 0; MemPage *pPrevTrunk = 0; Pgno mxPage; /* Total size of the database file */ assert( sqlite3_mutex_held(pBt->mutex) ); assert( eMode==BTALLOC_ANY || (nearby>0 && IfNotOmitAV(pBt->autoVacuum)) ); pPage1 = pBt->pPage1; mxPage = btreePagecount(pBt); /* EVIDENCE-OF: R-05119-02637 The 4-byte big-endian integer at offset 36 ** stores stores the total number of pages on the freelist. */ n = get4byte(&pPage1->aData[36]); testcase( n==mxPage-1 ); if( n>=mxPage ){ return SQLITE_CORRUPT_BKPT; } if( n>0 ){ /* There are pages on the freelist. Reuse one of those pages. */ Pgno iTrunk; u8 searchList = 0; /* If the free-list must be searched for 'nearby' */ u32 nSearch = 0; /* Count of the number of search attempts */ /* If eMode==BTALLOC_EXACT and a query of the pointer-map ** shows that the page 'nearby' is somewhere on the free-list, then ** the entire-list will be searched for that page. */ #ifndef SQLITE_OMIT_AUTOVACUUM if( eMode==BTALLOC_EXACT ){ if( nearby<=mxPage ){ u8 eType; assert( nearby>0 ); assert( pBt->autoVacuum ); rc = ptrmapGet(pBt, nearby, &eType, 0); if( rc ) return rc; if( eType==PTRMAP_FREEPAGE ){ searchList = 1; } } }else if( eMode==BTALLOC_LE ){ searchList = 1; } #endif /* Decrement the free-list count by 1. Set iTrunk to the index of the ** first free-list trunk page. iPrevTrunk is initially 1. */ rc = sqlite3PagerWrite(pPage1->pDbPage); if( rc ) return rc; put4byte(&pPage1->aData[36], n-1); /* The code within this loop is run only once if the 'searchList' variable ** is not true. Otherwise, it runs once for each trunk-page on the ** free-list until the page 'nearby' is located (eMode==BTALLOC_EXACT) ** or until a page less than 'nearby' is located (eMode==BTALLOC_LT) */ do { pPrevTrunk = pTrunk; if( pPrevTrunk ){ /* EVIDENCE-OF: R-01506-11053 The first integer on a freelist trunk page ** is the page number of the next freelist trunk page in the list or ** zero if this is the last freelist trunk page. */ iTrunk = get4byte(&pPrevTrunk->aData[0]); }else{ /* EVIDENCE-OF: R-59841-13798 The 4-byte big-endian integer at offset 32 ** stores the page number of the first page of the freelist, or zero if ** the freelist is empty. */ iTrunk = get4byte(&pPage1->aData[32]); } testcase( iTrunk==mxPage ); if( iTrunk>mxPage || nSearch++ > n ){ rc = SQLITE_CORRUPT_BKPT; }else{ rc = btreeGetUnusedPage(pBt, iTrunk, &pTrunk, 0); } if( rc ){ pTrunk = 0; goto end_allocate_page; } assert( pTrunk!=0 ); assert( pTrunk->aData!=0 ); /* EVIDENCE-OF: R-13523-04394 The second integer on a freelist trunk page ** is the number of leaf page pointers to follow. */ k = get4byte(&pTrunk->aData[4]); if( k==0 && !searchList ){ /* The trunk has no leaves and the list is not being searched. ** So extract the trunk page itself and use it as the newly ** allocated page */ assert( pPrevTrunk==0 ); rc = sqlite3PagerWrite(pTrunk->pDbPage); if( rc ){ goto end_allocate_page; } *pPgno = iTrunk; memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4); *ppPage = pTrunk; pTrunk = 0; TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1)); }else if( k>(u32)(pBt->usableSize/4 - 2) ){ /* Value of k is out of range. Database corruption */ rc = SQLITE_CORRUPT_BKPT; goto end_allocate_page; #ifndef SQLITE_OMIT_AUTOVACUUM }else if( searchList && (nearby==iTrunk || (iTrunkpDbPage); if( rc ){ goto end_allocate_page; } if( k==0 ){ if( !pPrevTrunk ){ memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4); }else{ rc = sqlite3PagerWrite(pPrevTrunk->pDbPage); if( rc!=SQLITE_OK ){ goto end_allocate_page; } memcpy(&pPrevTrunk->aData[0], &pTrunk->aData[0], 4); } }else{ /* The trunk page is required by the caller but it contains ** pointers to free-list leaves. The first leaf becomes a trunk ** page in this case. */ MemPage *pNewTrunk; Pgno iNewTrunk = get4byte(&pTrunk->aData[8]); if( iNewTrunk>mxPage ){ rc = SQLITE_CORRUPT_BKPT; goto end_allocate_page; } testcase( iNewTrunk==mxPage ); rc = btreeGetUnusedPage(pBt, iNewTrunk, &pNewTrunk, 0); if( rc!=SQLITE_OK ){ goto end_allocate_page; } rc = sqlite3PagerWrite(pNewTrunk->pDbPage); if( rc!=SQLITE_OK ){ releasePage(pNewTrunk); goto end_allocate_page; } memcpy(&pNewTrunk->aData[0], &pTrunk->aData[0], 4); put4byte(&pNewTrunk->aData[4], k-1); memcpy(&pNewTrunk->aData[8], &pTrunk->aData[12], (k-1)*4); releasePage(pNewTrunk); if( !pPrevTrunk ){ assert( sqlite3PagerIswriteable(pPage1->pDbPage) ); put4byte(&pPage1->aData[32], iNewTrunk); }else{ rc = sqlite3PagerWrite(pPrevTrunk->pDbPage); if( rc ){ goto end_allocate_page; } put4byte(&pPrevTrunk->aData[0], iNewTrunk); } } pTrunk = 0; TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1)); #endif }else if( k>0 ){ /* Extract a leaf from the trunk */ u32 closest; Pgno iPage; unsigned char *aData = pTrunk->aData; if( nearby>0 ){ u32 i; closest = 0; if( eMode==BTALLOC_LE ){ for(i=0; imxPage ){ rc = SQLITE_CORRUPT_BKPT; goto end_allocate_page; } testcase( iPage==mxPage ); if( !searchList || (iPage==nearby || (iPagepgno, n-1)); rc = sqlite3PagerWrite(pTrunk->pDbPage); if( rc ) goto end_allocate_page; if( closestpDbPage); if( rc!=SQLITE_OK ){ releasePage(*ppPage); *ppPage = 0; } } searchList = 0; } } releasePage(pPrevTrunk); pPrevTrunk = 0; }while( searchList ); }else{ /* There are no pages on the freelist, so append a new page to the ** database image. ** ** Normally, new pages allocated by this block can be requested from the ** pager layer with the 'no-content' flag set. This prevents the pager ** from trying to read the pages content from disk. However, if the ** current transaction has already run one or more incremental-vacuum ** steps, then the page we are about to allocate may contain content ** that is required in the event of a rollback. In this case, do ** not set the no-content flag. This causes the pager to load and journal ** the current page content before overwriting it. ** ** Note that the pager will not actually attempt to load or journal ** content for any page that really does lie past the end of the database ** file on disk. So the effects of disabling the no-content optimization ** here are confined to those pages that lie between the end of the ** database image and the end of the database file. */ int bNoContent = (0==IfNotOmitAV(pBt->bDoTruncate))? PAGER_GET_NOCONTENT:0; rc = sqlite3PagerWrite(pBt->pPage1->pDbPage); if( rc ) return rc; pBt->nPage++; if( pBt->nPage==PENDING_BYTE_PAGE(pBt) ) pBt->nPage++; #ifndef SQLITE_OMIT_AUTOVACUUM if( pBt->autoVacuum && PTRMAP_ISPAGE(pBt, pBt->nPage) ){ /* If *pPgno refers to a pointer-map page, allocate two new pages ** at the end of the file instead of one. The first allocated page ** becomes a new pointer-map page, the second is used by the caller. */ MemPage *pPg = 0; TRACE(("ALLOCATE: %d from end of file (pointer-map page)\n", pBt->nPage)); assert( pBt->nPage!=PENDING_BYTE_PAGE(pBt) ); rc = btreeGetUnusedPage(pBt, pBt->nPage, &pPg, bNoContent); if( rc==SQLITE_OK ){ rc = sqlite3PagerWrite(pPg->pDbPage); releasePage(pPg); } if( rc ) return rc; pBt->nPage++; if( pBt->nPage==PENDING_BYTE_PAGE(pBt) ){ pBt->nPage++; } } #endif put4byte(28 + (u8*)pBt->pPage1->aData, pBt->nPage); *pPgno = pBt->nPage; assert( *pPgno!=PENDING_BYTE_PAGE(pBt) ); rc = btreeGetUnusedPage(pBt, *pPgno, ppPage, bNoContent); if( rc ) return rc; rc = sqlite3PagerWrite((*ppPage)->pDbPage); if( rc!=SQLITE_OK ){ releasePage(*ppPage); *ppPage = 0; } TRACE(("ALLOCATE: %d from end of file\n", *pPgno)); } assert( *pPgno!=PENDING_BYTE_PAGE(pBt) ); end_allocate_page: releasePage(pTrunk); releasePage(pPrevTrunk); assert( rc!=SQLITE_OK || sqlite3PagerPageRefcount((*ppPage)->pDbPage)<=1 ); assert( rc!=SQLITE_OK || (*ppPage)->isInit==0 ); return rc; } /* ** This function is used to add page iPage to the database file free-list. ** It is assumed that the page is not already a part of the free-list. ** ** The value passed as the second argument to this function is optional. ** If the caller happens to have a pointer to the MemPage object ** corresponding to page iPage handy, it may pass it as the second value. ** Otherwise, it may pass NULL. ** ** If a pointer to a MemPage object is passed as the second argument, ** its reference count is not altered by this function. */ static int freePage2(BtShared *pBt, MemPage *pMemPage, Pgno iPage){ MemPage *pTrunk = 0; /* Free-list trunk page */ Pgno iTrunk = 0; /* Page number of free-list trunk page */ MemPage *pPage1 = pBt->pPage1; /* Local reference to page 1 */ MemPage *pPage; /* Page being freed. May be NULL. */ int rc; /* Return Code */ int nFree; /* Initial number of pages on free-list */ assert( sqlite3_mutex_held(pBt->mutex) ); assert( CORRUPT_DB || iPage>1 ); assert( !pMemPage || pMemPage->pgno==iPage ); if( iPage<2 ) return SQLITE_CORRUPT_BKPT; if( pMemPage ){ pPage = pMemPage; sqlite3PagerRef(pPage->pDbPage); }else{ pPage = btreePageLookup(pBt, iPage); } /* Increment the free page count on pPage1 */ rc = sqlite3PagerWrite(pPage1->pDbPage); if( rc ) goto freepage_out; nFree = get4byte(&pPage1->aData[36]); put4byte(&pPage1->aData[36], nFree+1); if( pBt->btsFlags & BTS_SECURE_DELETE ){ /* If the secure_delete option is enabled, then ** always fully overwrite deleted information with zeros. */ if( (!pPage && ((rc = btreeGetPage(pBt, iPage, &pPage, 0))!=0) ) || ((rc = sqlite3PagerWrite(pPage->pDbPage))!=0) ){ goto freepage_out; } memset(pPage->aData, 0, pPage->pBt->pageSize); } /* If the database supports auto-vacuum, write an entry in the pointer-map ** to indicate that the page is free. */ if( ISAUTOVACUUM ){ ptrmapPut(pBt, iPage, PTRMAP_FREEPAGE, 0, &rc); if( rc ) goto freepage_out; } /* Now manipulate the actual database free-list structure. There are two ** possibilities. If the free-list is currently empty, or if the first ** trunk page in the free-list is full, then this page will become a ** new free-list trunk page. Otherwise, it will become a leaf of the ** first trunk page in the current free-list. This block tests if it ** is possible to add the page as a new free-list leaf. */ if( nFree!=0 ){ u32 nLeaf; /* Initial number of leaf cells on trunk page */ iTrunk = get4byte(&pPage1->aData[32]); rc = btreeGetPage(pBt, iTrunk, &pTrunk, 0); if( rc!=SQLITE_OK ){ goto freepage_out; } nLeaf = get4byte(&pTrunk->aData[4]); assert( pBt->usableSize>32 ); if( nLeaf > (u32)pBt->usableSize/4 - 2 ){ rc = SQLITE_CORRUPT_BKPT; goto freepage_out; } if( nLeaf < (u32)pBt->usableSize/4 - 8 ){ /* In this case there is room on the trunk page to insert the page ** being freed as a new leaf. ** ** Note that the trunk page is not really full until it contains ** usableSize/4 - 2 entries, not usableSize/4 - 8 entries as we have ** coded. But due to a coding error in versions of SQLite prior to ** 3.6.0, databases with freelist trunk pages holding more than ** usableSize/4 - 8 entries will be reported as corrupt. In order ** to maintain backwards compatibility with older versions of SQLite, ** we will continue to restrict the number of entries to usableSize/4 - 8 ** for now. At some point in the future (once everyone has upgraded ** to 3.6.0 or later) we should consider fixing the conditional above ** to read "usableSize/4-2" instead of "usableSize/4-8". ** ** EVIDENCE-OF: R-19920-11576 However, newer versions of SQLite still ** avoid using the last six entries in the freelist trunk page array in ** order that database files created by newer versions of SQLite can be ** read by older versions of SQLite. */ rc = sqlite3PagerWrite(pTrunk->pDbPage); if( rc==SQLITE_OK ){ put4byte(&pTrunk->aData[4], nLeaf+1); put4byte(&pTrunk->aData[8+nLeaf*4], iPage); if( pPage && (pBt->btsFlags & BTS_SECURE_DELETE)==0 ){ sqlite3PagerDontWrite(pPage->pDbPage); } rc = btreeSetHasContent(pBt, iPage); } TRACE(("FREE-PAGE: %d leaf on trunk page %d\n",pPage->pgno,pTrunk->pgno)); goto freepage_out; } } /* If control flows to this point, then it was not possible to add the ** the page being freed as a leaf page of the first trunk in the free-list. ** Possibly because the free-list is empty, or possibly because the ** first trunk in the free-list is full. Either way, the page being freed ** will become the new first trunk page in the free-list. */ if( pPage==0 && SQLITE_OK!=(rc = btreeGetPage(pBt, iPage, &pPage, 0)) ){ goto freepage_out; } rc = sqlite3PagerWrite(pPage->pDbPage); if( rc!=SQLITE_OK ){ goto freepage_out; } put4byte(pPage->aData, iTrunk); put4byte(&pPage->aData[4], 0); put4byte(&pPage1->aData[32], iPage); TRACE(("FREE-PAGE: %d new trunk page replacing %d\n", pPage->pgno, iTrunk)); freepage_out: if( pPage ){ pPage->isInit = 0; } releasePage(pPage); releasePage(pTrunk); return rc; } static void freePage(MemPage *pPage, int *pRC){ if( (*pRC)==SQLITE_OK ){ *pRC = freePage2(pPage->pBt, pPage, pPage->pgno); } } /* ** Free any overflow pages associated with the given Cell. Write the ** local Cell size (the number of bytes on the original page, omitting ** overflow) into *pnSize. */ static int clearCell( MemPage *pPage, /* The page that contains the Cell */ unsigned char *pCell, /* First byte of the Cell */ u16 *pnSize /* Write the size of the Cell here */ ){ BtShared *pBt = pPage->pBt; CellInfo info; Pgno ovflPgno; int rc; int nOvfl; u32 ovflPageSize; assert( sqlite3_mutex_held(pPage->pBt->mutex) ); pPage->xParseCell(pPage, pCell, &info); *pnSize = info.nSize; if( info.nLocal==info.nPayload ){ return SQLITE_OK; /* No overflow pages. Return without doing anything */ } if( pCell+info.nSize-1 > pPage->aData+pPage->maskPage ){ return SQLITE_CORRUPT_BKPT; /* Cell extends past end of page */ } ovflPgno = get4byte(pCell + info.nSize - 4); assert( pBt->usableSize > 4 ); ovflPageSize = pBt->usableSize - 4; nOvfl = (info.nPayload - info.nLocal + ovflPageSize - 1)/ovflPageSize; assert( nOvfl>0 || (CORRUPT_DB && (info.nPayload + ovflPageSize)btreePagecount(pBt) ){ /* 0 is not a legal page number and page 1 cannot be an ** overflow page. Therefore if ovflPgno<2 or past the end of the ** file the database must be corrupt. */ return SQLITE_CORRUPT_BKPT; } if( nOvfl ){ rc = getOverflowPage(pBt, ovflPgno, &pOvfl, &iNext); if( rc ) return rc; } if( ( pOvfl || ((pOvfl = btreePageLookup(pBt, ovflPgno))!=0) ) && sqlite3PagerPageRefcount(pOvfl->pDbPage)!=1 ){ /* There is no reason any cursor should have an outstanding reference ** to an overflow page belonging to a cell that is being deleted/updated. ** So if there exists more than one reference to this page, then it ** must not really be an overflow page and the database must be corrupt. ** It is helpful to detect this before calling freePage2(), as ** freePage2() may zero the page contents if secure-delete mode is ** enabled. If this 'overflow' page happens to be a page that the ** caller is iterating through or using in some other way, this ** can be problematic. */ rc = SQLITE_CORRUPT_BKPT; }else{ rc = freePage2(pBt, pOvfl, ovflPgno); } if( pOvfl ){ sqlite3PagerUnref(pOvfl->pDbPage); } if( rc ) return rc; ovflPgno = iNext; } return SQLITE_OK; } /* ** Create the byte sequence used to represent a cell on page pPage ** and write that byte sequence into pCell[]. Overflow pages are ** allocated and filled in as necessary. The calling procedure ** is responsible for making sure sufficient space has been allocated ** for pCell[]. ** ** Note that pCell does not necessary need to point to the pPage->aData ** area. pCell might point to some temporary storage. The cell will ** be constructed in this temporary area then copied into pPage->aData ** later. */ static int fillInCell( MemPage *pPage, /* The page that contains the cell */ unsigned char *pCell, /* Complete text of the cell */ const BtreePayload *pX, /* Payload with which to construct the cell */ int *pnSize /* Write cell size here */ ){ int nPayload; const u8 *pSrc; int nSrc, n, rc; int spaceLeft; MemPage *pOvfl = 0; MemPage *pToRelease = 0; unsigned char *pPrior; unsigned char *pPayload; BtShared *pBt = pPage->pBt; Pgno pgnoOvfl = 0; int nHeader; assert( sqlite3_mutex_held(pPage->pBt->mutex) ); /* pPage is not necessarily writeable since pCell might be auxiliary ** buffer space that is separate from the pPage buffer area */ assert( pCellaData || pCell>=&pPage->aData[pBt->pageSize] || sqlite3PagerIswriteable(pPage->pDbPage) ); /* Fill in the header. */ nHeader = pPage->childPtrSize; if( pPage->intKey ){ nPayload = pX->nData + pX->nZero; pSrc = pX->pData; nSrc = pX->nData; assert( pPage->intKeyLeaf ); /* fillInCell() only called for leaves */ nHeader += putVarint32(&pCell[nHeader], nPayload); nHeader += putVarint(&pCell[nHeader], *(u64*)&pX->nKey); }else{ assert( pX->nKey<=0x7fffffff && pX->pKey!=0 ); nSrc = nPayload = (int)pX->nKey; pSrc = pX->pKey; nHeader += putVarint32(&pCell[nHeader], nPayload); } /* Fill in the payload */ if( nPayload<=pPage->maxLocal ){ n = nHeader + nPayload; testcase( n==3 ); testcase( n==4 ); if( n<4 ) n = 4; *pnSize = n; spaceLeft = nPayload; pPrior = pCell; }else{ int mn = pPage->minLocal; n = mn + (nPayload - mn) % (pPage->pBt->usableSize - 4); testcase( n==pPage->maxLocal ); testcase( n==pPage->maxLocal+1 ); if( n > pPage->maxLocal ) n = mn; spaceLeft = n; *pnSize = n + nHeader + 4; pPrior = &pCell[nHeader+n]; } pPayload = &pCell[nHeader]; /* At this point variables should be set as follows: ** ** nPayload Total payload size in bytes ** pPayload Begin writing payload here ** spaceLeft Space available at pPayload. If nPayload>spaceLeft, ** that means content must spill into overflow pages. ** *pnSize Size of the local cell (not counting overflow pages) ** pPrior Where to write the pgno of the first overflow page ** ** Use a call to btreeParseCellPtr() to verify that the values above ** were computed correctly. */ #if SQLITE_DEBUG { CellInfo info; pPage->xParseCell(pPage, pCell, &info); assert( nHeader==(int)(info.pPayload - pCell) ); assert( info.nKey==pX->nKey ); assert( *pnSize == info.nSize ); assert( spaceLeft == info.nLocal ); } #endif /* Write the payload into the local Cell and any extra into overflow pages */ while( nPayload>0 ){ if( spaceLeft==0 ){ #ifndef SQLITE_OMIT_AUTOVACUUM Pgno pgnoPtrmap = pgnoOvfl; /* Overflow page pointer-map entry page */ if( pBt->autoVacuum ){ do{ pgnoOvfl++; } while( PTRMAP_ISPAGE(pBt, pgnoOvfl) || pgnoOvfl==PENDING_BYTE_PAGE(pBt) ); } #endif rc = allocateBtreePage(pBt, &pOvfl, &pgnoOvfl, pgnoOvfl, 0); #ifndef SQLITE_OMIT_AUTOVACUUM /* If the database supports auto-vacuum, and the second or subsequent ** overflow page is being allocated, add an entry to the pointer-map ** for that page now. ** ** If this is the first overflow page, then write a partial entry ** to the pointer-map. If we write nothing to this pointer-map slot, ** then the optimistic overflow chain processing in clearCell() ** may misinterpret the uninitialized values and delete the ** wrong pages from the database. */ if( pBt->autoVacuum && rc==SQLITE_OK ){ u8 eType = (pgnoPtrmap?PTRMAP_OVERFLOW2:PTRMAP_OVERFLOW1); ptrmapPut(pBt, pgnoOvfl, eType, pgnoPtrmap, &rc); if( rc ){ releasePage(pOvfl); } } #endif if( rc ){ releasePage(pToRelease); return rc; } /* If pToRelease is not zero than pPrior points into the data area ** of pToRelease. Make sure pToRelease is still writeable. */ assert( pToRelease==0 || sqlite3PagerIswriteable(pToRelease->pDbPage) ); /* If pPrior is part of the data area of pPage, then make sure pPage ** is still writeable */ assert( pPrioraData || pPrior>=&pPage->aData[pBt->pageSize] || sqlite3PagerIswriteable(pPage->pDbPage) ); put4byte(pPrior, pgnoOvfl); releasePage(pToRelease); pToRelease = pOvfl; pPrior = pOvfl->aData; put4byte(pPrior, 0); pPayload = &pOvfl->aData[4]; spaceLeft = pBt->usableSize - 4; } n = nPayload; if( n>spaceLeft ) n = spaceLeft; /* If pToRelease is not zero than pPayload points into the data area ** of pToRelease. Make sure pToRelease is still writeable. */ assert( pToRelease==0 || sqlite3PagerIswriteable(pToRelease->pDbPage) ); /* If pPayload is part of the data area of pPage, then make sure pPage ** is still writeable */ assert( pPayloadaData || pPayload>=&pPage->aData[pBt->pageSize] || sqlite3PagerIswriteable(pPage->pDbPage) ); if( nSrc>0 ){ if( n>nSrc ) n = nSrc; assert( pSrc ); memcpy(pPayload, pSrc, n); }else{ memset(pPayload, 0, n); } nPayload -= n; pPayload += n; pSrc += n; nSrc -= n; spaceLeft -= n; } releasePage(pToRelease); return SQLITE_OK; } /* ** Remove the i-th cell from pPage. This routine effects pPage only. ** The cell content is not freed or deallocated. It is assumed that ** the cell content has been copied someplace else. This routine just ** removes the reference to the cell from pPage. ** ** "sz" must be the number of bytes in the cell. */ static void dropCell(MemPage *pPage, int idx, int sz, int *pRC){ u32 pc; /* Offset to cell content of cell being deleted */ u8 *data; /* pPage->aData */ u8 *ptr; /* Used to move bytes around within data[] */ int rc; /* The return code */ int hdr; /* Beginning of the header. 0 most pages. 100 page 1 */ if( *pRC ) return; assert( idx>=0 && idxnCell ); assert( CORRUPT_DB || sz==cellSize(pPage, idx) ); assert( sqlite3PagerIswriteable(pPage->pDbPage) ); assert( sqlite3_mutex_held(pPage->pBt->mutex) ); data = pPage->aData; ptr = &pPage->aCellIdx[2*idx]; pc = get2byte(ptr); hdr = pPage->hdrOffset; testcase( pc==get2byte(&data[hdr+5]) ); testcase( pc+sz==pPage->pBt->usableSize ); if( pc < (u32)get2byte(&data[hdr+5]) || pc+sz > pPage->pBt->usableSize ){ *pRC = SQLITE_CORRUPT_BKPT; return; } rc = freeSpace(pPage, pc, sz); if( rc ){ *pRC = rc; return; } pPage->nCell--; if( pPage->nCell==0 ){ memset(&data[hdr+1], 0, 4); data[hdr+7] = 0; put2byte(&data[hdr+5], pPage->pBt->usableSize); pPage->nFree = pPage->pBt->usableSize - pPage->hdrOffset - pPage->childPtrSize - 8; }else{ memmove(ptr, ptr+2, 2*(pPage->nCell - idx)); put2byte(&data[hdr+3], pPage->nCell); pPage->nFree += 2; } } /* ** Insert a new cell on pPage at cell index "i". pCell points to the ** content of the cell. ** ** If the cell content will fit on the page, then put it there. If it ** will not fit, then make a copy of the cell content into pTemp if ** pTemp is not null. Regardless of pTemp, allocate a new entry ** in pPage->apOvfl[] and make it point to the cell content (either ** in pTemp or the original pCell) and also record its index. ** Allocating a new entry in pPage->aCell[] implies that ** pPage->nOverflow is incremented. ** ** *pRC must be SQLITE_OK when this routine is called. */ static void insertCell( MemPage *pPage, /* Page into which we are copying */ int i, /* New cell becomes the i-th cell of the page */ u8 *pCell, /* Content of the new cell */ int sz, /* Bytes of content in pCell */ u8 *pTemp, /* Temp storage space for pCell, if needed */ Pgno iChild, /* If non-zero, replace first 4 bytes with this value */ int *pRC /* Read and write return code from here */ ){ int idx = 0; /* Where to write new cell content in data[] */ int j; /* Loop counter */ u8 *data; /* The content of the whole page */ u8 *pIns; /* The point in pPage->aCellIdx[] where no cell inserted */ assert( *pRC==SQLITE_OK ); assert( i>=0 && i<=pPage->nCell+pPage->nOverflow ); assert( MX_CELL(pPage->pBt)<=10921 ); assert( pPage->nCell<=MX_CELL(pPage->pBt) || CORRUPT_DB ); assert( pPage->nOverflow<=ArraySize(pPage->apOvfl) ); assert( ArraySize(pPage->apOvfl)==ArraySize(pPage->aiOvfl) ); assert( sqlite3_mutex_held(pPage->pBt->mutex) ); /* The cell should normally be sized correctly. However, when moving a ** malformed cell from a leaf page to an interior page, if the cell size ** wanted to be less than 4 but got rounded up to 4 on the leaf, then size ** might be less than 8 (leaf-size + pointer) on the interior node. Hence ** the term after the || in the following assert(). */ assert( sz==pPage->xCellSize(pPage, pCell) || (sz==8 && iChild>0) ); if( pPage->nOverflow || sz+2>pPage->nFree ){ if( pTemp ){ memcpy(pTemp, pCell, sz); pCell = pTemp; } if( iChild ){ put4byte(pCell, iChild); } j = pPage->nOverflow++; assert( j<(int)(sizeof(pPage->apOvfl)/sizeof(pPage->apOvfl[0])) ); pPage->apOvfl[j] = pCell; pPage->aiOvfl[j] = (u16)i; /* When multiple overflows occur, they are always sequential and in ** sorted order. This invariants arise because multiple overflows can ** only occur when inserting divider cells into the parent page during ** balancing, and the dividers are adjacent and sorted. */ assert( j==0 || pPage->aiOvfl[j-1]<(u16)i ); /* Overflows in sorted order */ assert( j==0 || i==pPage->aiOvfl[j-1]+1 ); /* Overflows are sequential */ }else{ int rc = sqlite3PagerWrite(pPage->pDbPage); if( rc!=SQLITE_OK ){ *pRC = rc; return; } assert( sqlite3PagerIswriteable(pPage->pDbPage) ); data = pPage->aData; assert( &data[pPage->cellOffset]==pPage->aCellIdx ); rc = allocateSpace(pPage, sz, &idx); if( rc ){ *pRC = rc; return; } /* The allocateSpace() routine guarantees the following properties ** if it returns successfully */ assert( idx >= 0 ); assert( idx >= pPage->cellOffset+2*pPage->nCell+2 || CORRUPT_DB ); assert( idx+sz <= (int)pPage->pBt->usableSize ); pPage->nFree -= (u16)(2 + sz); memcpy(&data[idx], pCell, sz); if( iChild ){ put4byte(&data[idx], iChild); } pIns = pPage->aCellIdx + i*2; memmove(pIns+2, pIns, 2*(pPage->nCell - i)); put2byte(pIns, idx); pPage->nCell++; /* increment the cell count */ if( (++data[pPage->hdrOffset+4])==0 ) data[pPage->hdrOffset+3]++; assert( get2byte(&data[pPage->hdrOffset+3])==pPage->nCell ); #ifndef SQLITE_OMIT_AUTOVACUUM if( pPage->pBt->autoVacuum ){ /* The cell may contain a pointer to an overflow page. If so, write ** the entry for the overflow page into the pointer map. */ ptrmapPutOvflPtr(pPage, pCell, pRC); } #endif } } /* ** A CellArray object contains a cache of pointers and sizes for a ** consecutive sequence of cells that might be held on multiple pages. */ typedef struct CellArray CellArray; struct CellArray { int nCell; /* Number of cells in apCell[] */ MemPage *pRef; /* Reference page */ u8 **apCell; /* All cells begin balanced */ u16 *szCell; /* Local size of all cells in apCell[] */ }; /* ** Make sure the cell sizes at idx, idx+1, ..., idx+N-1 have been ** computed. */ static void populateCellCache(CellArray *p, int idx, int N){ assert( idx>=0 && idx+N<=p->nCell ); while( N>0 ){ assert( p->apCell[idx]!=0 ); if( p->szCell[idx]==0 ){ p->szCell[idx] = p->pRef->xCellSize(p->pRef, p->apCell[idx]); }else{ assert( CORRUPT_DB || p->szCell[idx]==p->pRef->xCellSize(p->pRef, p->apCell[idx]) ); } idx++; N--; } } /* ** Return the size of the Nth element of the cell array */ static SQLITE_NOINLINE u16 computeCellSize(CellArray *p, int N){ assert( N>=0 && NnCell ); assert( p->szCell[N]==0 ); p->szCell[N] = p->pRef->xCellSize(p->pRef, p->apCell[N]); return p->szCell[N]; } static u16 cachedCellSize(CellArray *p, int N){ assert( N>=0 && NnCell ); if( p->szCell[N] ) return p->szCell[N]; return computeCellSize(p, N); } /* ** Array apCell[] contains pointers to nCell b-tree page cells. The ** szCell[] array contains the size in bytes of each cell. This function ** replaces the current contents of page pPg with the contents of the cell ** array. ** ** Some of the cells in apCell[] may currently be stored in pPg. This ** function works around problems caused by this by making a copy of any ** such cells before overwriting the page data. ** ** The MemPage.nFree field is invalidated by this function. It is the ** responsibility of the caller to set it correctly. */ static int rebuildPage( MemPage *pPg, /* Edit this page */ int nCell, /* Final number of cells on page */ u8 **apCell, /* Array of cells */ u16 *szCell /* Array of cell sizes */ ){ const int hdr = pPg->hdrOffset; /* Offset of header on pPg */ u8 * const aData = pPg->aData; /* Pointer to data for pPg */ const int usableSize = pPg->pBt->usableSize; u8 * const pEnd = &aData[usableSize]; int i; u8 *pCellptr = pPg->aCellIdx; u8 *pTmp = sqlite3PagerTempSpace(pPg->pBt->pPager); u8 *pData; i = get2byte(&aData[hdr+5]); memcpy(&pTmp[i], &aData[i], usableSize - i); pData = pEnd; for(i=0; ixCellSize(pPg, pCell) || CORRUPT_DB ); testcase( szCell[i]!=pPg->xCellSize(pPg,pCell) ); } /* The pPg->nFree field is now set incorrectly. The caller will fix it. */ pPg->nCell = nCell; pPg->nOverflow = 0; put2byte(&aData[hdr+1], 0); put2byte(&aData[hdr+3], pPg->nCell); put2byte(&aData[hdr+5], pData - aData); aData[hdr+7] = 0x00; return SQLITE_OK; } /* ** Array apCell[] contains nCell pointers to b-tree cells. Array szCell ** contains the size in bytes of each such cell. This function attempts to ** add the cells stored in the array to page pPg. If it cannot (because ** the page needs to be defragmented before the cells will fit), non-zero ** is returned. Otherwise, if the cells are added successfully, zero is ** returned. ** ** Argument pCellptr points to the first entry in the cell-pointer array ** (part of page pPg) to populate. After cell apCell[0] is written to the ** page body, a 16-bit offset is written to pCellptr. And so on, for each ** cell in the array. It is the responsibility of the caller to ensure ** that it is safe to overwrite this part of the cell-pointer array. ** ** When this function is called, *ppData points to the start of the ** content area on page pPg. If the size of the content area is extended, ** *ppData is updated to point to the new start of the content area ** before returning. ** ** Finally, argument pBegin points to the byte immediately following the ** end of the space required by this page for the cell-pointer area (for ** all cells - not just those inserted by the current call). If the content ** area must be extended to before this point in order to accomodate all ** cells in apCell[], then the cells do not fit and non-zero is returned. */ static int pageInsertArray( MemPage *pPg, /* Page to add cells to */ u8 *pBegin, /* End of cell-pointer array */ u8 **ppData, /* IN/OUT: Page content -area pointer */ u8 *pCellptr, /* Pointer to cell-pointer area */ int iFirst, /* Index of first cell to add */ int nCell, /* Number of cells to add to pPg */ CellArray *pCArray /* Array of cells */ ){ int i; u8 *aData = pPg->aData; u8 *pData = *ppData; int iEnd = iFirst + nCell; assert( CORRUPT_DB || pPg->hdrOffset==0 ); /* Never called on page 1 */ for(i=iFirst; iapCell[i] will never overlap on a well-formed ** database. But they might for a corrupt database. Hence use memmove() ** since memcpy() sends SIGABORT with overlapping buffers on OpenBSD */ assert( (pSlot+sz)<=pCArray->apCell[i] || pSlot>=(pCArray->apCell[i]+sz) || CORRUPT_DB ); memmove(pSlot, pCArray->apCell[i], sz); put2byte(pCellptr, (pSlot - aData)); pCellptr += 2; } *ppData = pData; return 0; } /* ** Array apCell[] contains nCell pointers to b-tree cells. Array szCell ** contains the size in bytes of each such cell. This function adds the ** space associated with each cell in the array that is currently stored ** within the body of pPg to the pPg free-list. The cell-pointers and other ** fields of the page are not updated. ** ** This function returns the total number of cells added to the free-list. */ static int pageFreeArray( MemPage *pPg, /* Page to edit */ int iFirst, /* First cell to delete */ int nCell, /* Cells to delete */ CellArray *pCArray /* Array of cells */ ){ u8 * const aData = pPg->aData; u8 * const pEnd = &aData[pPg->pBt->usableSize]; u8 * const pStart = &aData[pPg->hdrOffset + 8 + pPg->childPtrSize]; int nRet = 0; int i; int iEnd = iFirst + nCell; u8 *pFree = 0; int szFree = 0; for(i=iFirst; iapCell[i]; if( SQLITE_WITHIN(pCell, pStart, pEnd) ){ int sz; /* No need to use cachedCellSize() here. The sizes of all cells that ** are to be freed have already been computing while deciding which ** cells need freeing */ sz = pCArray->szCell[i]; assert( sz>0 ); if( pFree!=(pCell + sz) ){ if( pFree ){ assert( pFree>aData && (pFree - aData)<65536 ); freeSpace(pPg, (u16)(pFree - aData), szFree); } pFree = pCell; szFree = sz; if( pFree+sz>pEnd ) return 0; }else{ pFree = pCell; szFree += sz; } nRet++; } } if( pFree ){ assert( pFree>aData && (pFree - aData)<65536 ); freeSpace(pPg, (u16)(pFree - aData), szFree); } return nRet; } /* ** apCell[] and szCell[] contains pointers to and sizes of all cells in the ** pages being balanced. The current page, pPg, has pPg->nCell cells starting ** with apCell[iOld]. After balancing, this page should hold nNew cells ** starting at apCell[iNew]. ** ** This routine makes the necessary adjustments to pPg so that it contains ** the correct cells after being balanced. ** ** The pPg->nFree field is invalid when this function returns. It is the ** responsibility of the caller to set it correctly. */ static int editPage( MemPage *pPg, /* Edit this page */ int iOld, /* Index of first cell currently on page */ int iNew, /* Index of new first cell on page */ int nNew, /* Final number of cells on page */ CellArray *pCArray /* Array of cells and sizes */ ){ u8 * const aData = pPg->aData; const int hdr = pPg->hdrOffset; u8 *pBegin = &pPg->aCellIdx[nNew * 2]; int nCell = pPg->nCell; /* Cells stored on pPg */ u8 *pData; u8 *pCellptr; int i; int iOldEnd = iOld + pPg->nCell + pPg->nOverflow; int iNewEnd = iNew + nNew; #ifdef SQLITE_DEBUG u8 *pTmp = sqlite3PagerTempSpace(pPg->pBt->pPager); memcpy(pTmp, aData, pPg->pBt->usableSize); #endif /* Remove cells from the start and end of the page */ if( iOldaCellIdx, &pPg->aCellIdx[nShift*2], nCell*2); nCell -= nShift; } if( iNewEnd < iOldEnd ){ nCell -= pageFreeArray(pPg, iNewEnd, iOldEnd - iNewEnd, pCArray); } pData = &aData[get2byteNotZero(&aData[hdr+5])]; if( pDataaCellIdx; memmove(&pCellptr[nAdd*2], pCellptr, nCell*2); if( pageInsertArray( pPg, pBegin, &pData, pCellptr, iNew, nAdd, pCArray ) ) goto editpage_fail; nCell += nAdd; } /* Add any overflow cells */ for(i=0; inOverflow; i++){ int iCell = (iOld + pPg->aiOvfl[i]) - iNew; if( iCell>=0 && iCellaCellIdx[iCell * 2]; memmove(&pCellptr[2], pCellptr, (nCell - iCell) * 2); nCell++; if( pageInsertArray( pPg, pBegin, &pData, pCellptr, iCell+iNew, 1, pCArray ) ) goto editpage_fail; } } /* Append cells to the end of the page */ pCellptr = &pPg->aCellIdx[nCell*2]; if( pageInsertArray( pPg, pBegin, &pData, pCellptr, iNew+nCell, nNew-nCell, pCArray ) ) goto editpage_fail; pPg->nCell = nNew; pPg->nOverflow = 0; put2byte(&aData[hdr+3], pPg->nCell); put2byte(&aData[hdr+5], pData - aData); #ifdef SQLITE_DEBUG for(i=0; iapCell[i+iNew]; int iOff = get2byteAligned(&pPg->aCellIdx[i*2]); if( SQLITE_WITHIN(pCell, aData, &aData[pPg->pBt->usableSize]) ){ pCell = &pTmp[pCell - aData]; } assert( 0==memcmp(pCell, &aData[iOff], pCArray->pRef->xCellSize(pCArray->pRef, pCArray->apCell[i+iNew])) ); } #endif return SQLITE_OK; editpage_fail: /* Unable to edit this page. Rebuild it from scratch instead. */ populateCellCache(pCArray, iNew, nNew); return rebuildPage(pPg, nNew, &pCArray->apCell[iNew], &pCArray->szCell[iNew]); } /* ** The following parameters determine how many adjacent pages get involved ** in a balancing operation. NN is the number of neighbors on either side ** of the page that participate in the balancing operation. NB is the ** total number of pages that participate, including the target page and ** NN neighbors on either side. ** ** The minimum value of NN is 1 (of course). Increasing NN above 1 ** (to 2 or 3) gives a modest improvement in SELECT and DELETE performance ** in exchange for a larger degradation in INSERT and UPDATE performance. ** The value of NN appears to give the best results overall. */ #define NN 1 /* Number of neighbors on either side of pPage */ #define NB (NN*2+1) /* Total pages involved in the balance */ #ifndef SQLITE_OMIT_QUICKBALANCE /* ** This version of balance() handles the common special case where ** a new entry is being inserted on the extreme right-end of the ** tree, in other words, when the new entry will become the largest ** entry in the tree. ** ** Instead of trying to balance the 3 right-most leaf pages, just add ** a new page to the right-hand side and put the one new entry in ** that page. This leaves the right side of the tree somewhat ** unbalanced. But odds are that we will be inserting new entries ** at the end soon afterwards so the nearly empty page will quickly ** fill up. On average. ** ** pPage is the leaf page which is the right-most page in the tree. ** pParent is its parent. pPage must have a single overflow entry ** which is also the right-most entry on the page. ** ** The pSpace buffer is used to store a temporary copy of the divider ** cell that will be inserted into pParent. Such a cell consists of a 4 ** byte page number followed by a variable length integer. In other ** words, at most 13 bytes. Hence the pSpace buffer must be at ** least 13 bytes in size. */ static int balance_quick(MemPage *pParent, MemPage *pPage, u8 *pSpace){ BtShared *const pBt = pPage->pBt; /* B-Tree Database */ MemPage *pNew; /* Newly allocated page */ int rc; /* Return Code */ Pgno pgnoNew; /* Page number of pNew */ assert( sqlite3_mutex_held(pPage->pBt->mutex) ); assert( sqlite3PagerIswriteable(pParent->pDbPage) ); assert( pPage->nOverflow==1 ); /* This error condition is now caught prior to reaching this function */ if( NEVER(pPage->nCell==0) ) return SQLITE_CORRUPT_BKPT; /* Allocate a new page. This page will become the right-sibling of ** pPage. Make the parent page writable, so that the new divider cell ** may be inserted. If both these operations are successful, proceed. */ rc = allocateBtreePage(pBt, &pNew, &pgnoNew, 0, 0); if( rc==SQLITE_OK ){ u8 *pOut = &pSpace[4]; u8 *pCell = pPage->apOvfl[0]; u16 szCell = pPage->xCellSize(pPage, pCell); u8 *pStop; assert( sqlite3PagerIswriteable(pNew->pDbPage) ); assert( pPage->aData[0]==(PTF_INTKEY|PTF_LEAFDATA|PTF_LEAF) ); zeroPage(pNew, PTF_INTKEY|PTF_LEAFDATA|PTF_LEAF); rc = rebuildPage(pNew, 1, &pCell, &szCell); if( NEVER(rc) ) return rc; pNew->nFree = pBt->usableSize - pNew->cellOffset - 2 - szCell; /* If this is an auto-vacuum database, update the pointer map ** with entries for the new page, and any pointer from the ** cell on the page to an overflow page. If either of these ** operations fails, the return code is set, but the contents ** of the parent page are still manipulated by thh code below. ** That is Ok, at this point the parent page is guaranteed to ** be marked as dirty. Returning an error code will cause a ** rollback, undoing any changes made to the parent page. */ if( ISAUTOVACUUM ){ ptrmapPut(pBt, pgnoNew, PTRMAP_BTREE, pParent->pgno, &rc); if( szCell>pNew->minLocal ){ ptrmapPutOvflPtr(pNew, pCell, &rc); } } /* Create a divider cell to insert into pParent. The divider cell ** consists of a 4-byte page number (the page number of pPage) and ** a variable length key value (which must be the same value as the ** largest key on pPage). ** ** To find the largest key value on pPage, first find the right-most ** cell on pPage. The first two fields of this cell are the ** record-length (a variable length integer at most 32-bits in size) ** and the key value (a variable length integer, may have any value). ** The first of the while(...) loops below skips over the record-length ** field. The second while(...) loop copies the key value from the ** cell on pPage into the pSpace buffer. */ pCell = findCell(pPage, pPage->nCell-1); pStop = &pCell[9]; while( (*(pCell++)&0x80) && pCellnCell, pSpace, (int)(pOut-pSpace), 0, pPage->pgno, &rc); } /* Set the right-child pointer of pParent to point to the new page. */ put4byte(&pParent->aData[pParent->hdrOffset+8], pgnoNew); /* Release the reference to the new page. */ releasePage(pNew); } return rc; } #endif /* SQLITE_OMIT_QUICKBALANCE */ #if 0 /* ** This function does not contribute anything to the operation of SQLite. ** it is sometimes activated temporarily while debugging code responsible ** for setting pointer-map entries. */ static int ptrmapCheckPages(MemPage **apPage, int nPage){ int i, j; for(i=0; ipBt; assert( pPage->isInit ); for(j=0; jnCell; j++){ CellInfo info; u8 *z; z = findCell(pPage, j); pPage->xParseCell(pPage, z, &info); if( info.nLocalpgno && e==PTRMAP_OVERFLOW1 ); } if( !pPage->leaf ){ Pgno child = get4byte(z); ptrmapGet(pBt, child, &e, &n); assert( n==pPage->pgno && e==PTRMAP_BTREE ); } } if( !pPage->leaf ){ Pgno child = get4byte(&pPage->aData[pPage->hdrOffset+8]); ptrmapGet(pBt, child, &e, &n); assert( n==pPage->pgno && e==PTRMAP_BTREE ); } } return 1; } #endif /* ** This function is used to copy the contents of the b-tree node stored ** on page pFrom to page pTo. If page pFrom was not a leaf page, then ** the pointer-map entries for each child page are updated so that the ** parent page stored in the pointer map is page pTo. If pFrom contained ** any cells with overflow page pointers, then the corresponding pointer ** map entries are also updated so that the parent page is page pTo. ** ** If pFrom is currently carrying any overflow cells (entries in the ** MemPage.apOvfl[] array), they are not copied to pTo. ** ** Before returning, page pTo is reinitialized using btreeInitPage(). ** ** The performance of this function is not critical. It is only used by ** the balance_shallower() and balance_deeper() procedures, neither of ** which are called often under normal circumstances. */ static void copyNodeContent(MemPage *pFrom, MemPage *pTo, int *pRC){ if( (*pRC)==SQLITE_OK ){ BtShared * const pBt = pFrom->pBt; u8 * const aFrom = pFrom->aData; u8 * const aTo = pTo->aData; int const iFromHdr = pFrom->hdrOffset; int const iToHdr = ((pTo->pgno==1) ? 100 : 0); int rc; int iData; assert( pFrom->isInit ); assert( pFrom->nFree>=iToHdr ); assert( get2byte(&aFrom[iFromHdr+5]) <= (int)pBt->usableSize ); /* Copy the b-tree node content from page pFrom to page pTo. */ iData = get2byte(&aFrom[iFromHdr+5]); memcpy(&aTo[iData], &aFrom[iData], pBt->usableSize-iData); memcpy(&aTo[iToHdr], &aFrom[iFromHdr], pFrom->cellOffset + 2*pFrom->nCell); /* Reinitialize page pTo so that the contents of the MemPage structure ** match the new data. The initialization of pTo can actually fail under ** fairly obscure circumstances, even though it is a copy of initialized ** page pFrom. */ pTo->isInit = 0; rc = btreeInitPage(pTo); if( rc!=SQLITE_OK ){ *pRC = rc; return; } /* If this is an auto-vacuum database, update the pointer-map entries ** for any b-tree or overflow pages that pTo now contains the pointers to. */ if( ISAUTOVACUUM ){ *pRC = setChildPtrmaps(pTo); } } } /* ** This routine redistributes cells on the iParentIdx'th child of pParent ** (hereafter "the page") and up to 2 siblings so that all pages have about the ** same amount of free space. Usually a single sibling on either side of the ** page are used in the balancing, though both siblings might come from one ** side if the page is the first or last child of its parent. If the page ** has fewer than 2 siblings (something which can only happen if the page ** is a root page or a child of a root page) then all available siblings ** participate in the balancing. ** ** The number of siblings of the page might be increased or decreased by ** one or two in an effort to keep pages nearly full but not over full. ** ** Note that when this routine is called, some of the cells on the page ** might not actually be stored in MemPage.aData[]. This can happen ** if the page is overfull. This routine ensures that all cells allocated ** to the page and its siblings fit into MemPage.aData[] before returning. ** ** In the course of balancing the page and its siblings, cells may be ** inserted into or removed from the parent page (pParent). Doing so ** may cause the parent page to become overfull or underfull. If this ** happens, it is the responsibility of the caller to invoke the correct ** balancing routine to fix this problem (see the balance() routine). ** ** If this routine fails for any reason, it might leave the database ** in a corrupted state. So if this routine fails, the database should ** be rolled back. ** ** The third argument to this function, aOvflSpace, is a pointer to a ** buffer big enough to hold one page. If while inserting cells into the parent ** page (pParent) the parent page becomes overfull, this buffer is ** used to store the parent's overflow cells. Because this function inserts ** a maximum of four divider cells into the parent page, and the maximum ** size of a cell stored within an internal node is always less than 1/4 ** of the page-size, the aOvflSpace[] buffer is guaranteed to be large ** enough for all overflow cells. ** ** If aOvflSpace is set to a null pointer, this function returns ** SQLITE_NOMEM. */ static int balance_nonroot( MemPage *pParent, /* Parent page of siblings being balanced */ int iParentIdx, /* Index of "the page" in pParent */ u8 *aOvflSpace, /* page-size bytes of space for parent ovfl */ int isRoot, /* True if pParent is a root-page */ int bBulk /* True if this call is part of a bulk load */ ){ BtShared *pBt; /* The whole database */ int nMaxCells = 0; /* Allocated size of apCell, szCell, aFrom. */ int nNew = 0; /* Number of pages in apNew[] */ int nOld; /* Number of pages in apOld[] */ int i, j, k; /* Loop counters */ int nxDiv; /* Next divider slot in pParent->aCell[] */ int rc = SQLITE_OK; /* The return code */ u16 leafCorrection; /* 4 if pPage is a leaf. 0 if not */ int leafData; /* True if pPage is a leaf of a LEAFDATA tree */ int usableSpace; /* Bytes in pPage beyond the header */ int pageFlags; /* Value of pPage->aData[0] */ int iSpace1 = 0; /* First unused byte of aSpace1[] */ int iOvflSpace = 0; /* First unused byte of aOvflSpace[] */ int szScratch; /* Size of scratch memory requested */ MemPage *apOld[NB]; /* pPage and up to two siblings */ MemPage *apNew[NB+2]; /* pPage and up to NB siblings after balancing */ u8 *pRight; /* Location in parent of right-sibling pointer */ u8 *apDiv[NB-1]; /* Divider cells in pParent */ int cntNew[NB+2]; /* Index in b.paCell[] of cell after i-th page */ int cntOld[NB+2]; /* Old index in b.apCell[] */ int szNew[NB+2]; /* Combined size of cells placed on i-th page */ u8 *aSpace1; /* Space for copies of dividers cells */ Pgno pgno; /* Temp var to store a page number in */ u8 abDone[NB+2]; /* True after i'th new page is populated */ Pgno aPgno[NB+2]; /* Page numbers of new pages before shuffling */ Pgno aPgOrder[NB+2]; /* Copy of aPgno[] used for sorting pages */ u16 aPgFlags[NB+2]; /* flags field of new pages before shuffling */ CellArray b; /* Parsed information on cells being balanced */ memset(abDone, 0, sizeof(abDone)); b.nCell = 0; b.apCell = 0; pBt = pParent->pBt; assert( sqlite3_mutex_held(pBt->mutex) ); assert( sqlite3PagerIswriteable(pParent->pDbPage) ); #if 0 TRACE(("BALANCE: begin page %d child of %d\n", pPage->pgno, pParent->pgno)); #endif /* At this point pParent may have at most one overflow cell. And if ** this overflow cell is present, it must be the cell with ** index iParentIdx. This scenario comes about when this function ** is called (indirectly) from sqlite3BtreeDelete(). */ assert( pParent->nOverflow==0 || pParent->nOverflow==1 ); assert( pParent->nOverflow==0 || pParent->aiOvfl[0]==iParentIdx ); if( !aOvflSpace ){ return SQLITE_NOMEM_BKPT; } /* Find the sibling pages to balance. Also locate the cells in pParent ** that divide the siblings. An attempt is made to find NN siblings on ** either side of pPage. More siblings are taken from one side, however, ** if there are fewer than NN siblings on the other side. If pParent ** has NB or fewer children then all children of pParent are taken. ** ** This loop also drops the divider cells from the parent page. This ** way, the remainder of the function does not have to deal with any ** overflow cells in the parent page, since if any existed they will ** have already been removed. */ i = pParent->nOverflow + pParent->nCell; if( i<2 ){ nxDiv = 0; }else{ assert( bBulk==0 || bBulk==1 ); if( iParentIdx==0 ){ nxDiv = 0; }else if( iParentIdx==i ){ nxDiv = i-2+bBulk; }else{ nxDiv = iParentIdx-1; } i = 2-bBulk; } nOld = i+1; if( (i+nxDiv-pParent->nOverflow)==pParent->nCell ){ pRight = &pParent->aData[pParent->hdrOffset+8]; }else{ pRight = findCell(pParent, i+nxDiv-pParent->nOverflow); } pgno = get4byte(pRight); while( 1 ){ rc = getAndInitPage(pBt, pgno, &apOld[i], 0, 0); if( rc ){ memset(apOld, 0, (i+1)*sizeof(MemPage*)); goto balance_cleanup; } nMaxCells += 1+apOld[i]->nCell+apOld[i]->nOverflow; if( (i--)==0 ) break; if( i+nxDiv==pParent->aiOvfl[0] && pParent->nOverflow ){ apDiv[i] = pParent->apOvfl[0]; pgno = get4byte(apDiv[i]); szNew[i] = pParent->xCellSize(pParent, apDiv[i]); pParent->nOverflow = 0; }else{ apDiv[i] = findCell(pParent, i+nxDiv-pParent->nOverflow); pgno = get4byte(apDiv[i]); szNew[i] = pParent->xCellSize(pParent, apDiv[i]); /* Drop the cell from the parent page. apDiv[i] still points to ** the cell within the parent, even though it has been dropped. ** This is safe because dropping a cell only overwrites the first ** four bytes of it, and this function does not need the first ** four bytes of the divider cell. So the pointer is safe to use ** later on. ** ** But not if we are in secure-delete mode. In secure-delete mode, ** the dropCell() routine will overwrite the entire cell with zeroes. ** In this case, temporarily copy the cell into the aOvflSpace[] ** buffer. It will be copied out again as soon as the aSpace[] buffer ** is allocated. */ if( pBt->btsFlags & BTS_SECURE_DELETE ){ int iOff; iOff = SQLITE_PTR_TO_INT(apDiv[i]) - SQLITE_PTR_TO_INT(pParent->aData); if( (iOff+szNew[i])>(int)pBt->usableSize ){ rc = SQLITE_CORRUPT_BKPT; memset(apOld, 0, (i+1)*sizeof(MemPage*)); goto balance_cleanup; }else{ memcpy(&aOvflSpace[iOff], apDiv[i], szNew[i]); apDiv[i] = &aOvflSpace[apDiv[i]-pParent->aData]; } } dropCell(pParent, i+nxDiv-pParent->nOverflow, szNew[i], &rc); } } /* Make nMaxCells a multiple of 4 in order to preserve 8-byte ** alignment */ nMaxCells = (nMaxCells + 3)&~3; /* ** Allocate space for memory structures */ szScratch = nMaxCells*sizeof(u8*) /* b.apCell */ + nMaxCells*sizeof(u16) /* b.szCell */ + pBt->pageSize; /* aSpace1 */ /* EVIDENCE-OF: R-28375-38319 SQLite will never request a scratch buffer ** that is more than 6 times the database page size. */ assert( szScratch<=6*(int)pBt->pageSize ); b.apCell = sqlite3ScratchMalloc( szScratch ); if( b.apCell==0 ){ rc = SQLITE_NOMEM_BKPT; goto balance_cleanup; } b.szCell = (u16*)&b.apCell[nMaxCells]; aSpace1 = (u8*)&b.szCell[nMaxCells]; assert( EIGHT_BYTE_ALIGNMENT(aSpace1) ); /* ** Load pointers to all cells on sibling pages and the divider cells ** into the local b.apCell[] array. Make copies of the divider cells ** into space obtained from aSpace1[]. The divider cells have already ** been removed from pParent. ** ** If the siblings are on leaf pages, then the child pointers of the ** divider cells are stripped from the cells before they are copied ** into aSpace1[]. In this way, all cells in b.apCell[] are without ** child pointers. If siblings are not leaves, then all cell in ** b.apCell[] include child pointers. Either way, all cells in b.apCell[] ** are alike. ** ** leafCorrection: 4 if pPage is a leaf. 0 if pPage is not a leaf. ** leafData: 1 if pPage holds key+data and pParent holds only keys. */ b.pRef = apOld[0]; leafCorrection = b.pRef->leaf*4; leafData = b.pRef->intKeyLeaf; for(i=0; inCell; u8 *aData = pOld->aData; u16 maskPage = pOld->maskPage; u8 *piCell = aData + pOld->cellOffset; u8 *piEnd; /* Verify that all sibling pages are of the same "type" (table-leaf, ** table-interior, index-leaf, or index-interior). */ if( pOld->aData[0]!=apOld[0]->aData[0] ){ rc = SQLITE_CORRUPT_BKPT; goto balance_cleanup; } /* Load b.apCell[] with pointers to all cells in pOld. If pOld ** constains overflow cells, include them in the b.apCell[] array ** in the correct spot. ** ** Note that when there are multiple overflow cells, it is always the ** case that they are sequential and adjacent. This invariant arises ** because multiple overflows can only occurs when inserting divider ** cells into a parent on a prior balance, and divider cells are always ** adjacent and are inserted in order. There is an assert() tagged ** with "NOTE 1" in the overflow cell insertion loop to prove this ** invariant. ** ** This must be done in advance. Once the balance starts, the cell ** offset section of the btree page will be overwritten and we will no ** long be able to find the cells if a pointer to each cell is not saved ** first. */ memset(&b.szCell[b.nCell], 0, sizeof(b.szCell[0])*(limit+pOld->nOverflow)); if( pOld->nOverflow>0 ){ limit = pOld->aiOvfl[0]; for(j=0; jnOverflow; k++){ assert( k==0 || pOld->aiOvfl[k-1]+1==pOld->aiOvfl[k] );/* NOTE 1 */ b.apCell[b.nCell] = pOld->apOvfl[k]; b.nCell++; } } piEnd = aData + pOld->cellOffset + 2*pOld->nCell; while( piCellmaxLocal+23 ); assert( iSpace1 <= (int)pBt->pageSize ); memcpy(pTemp, apDiv[i], sz); b.apCell[b.nCell] = pTemp+leafCorrection; assert( leafCorrection==0 || leafCorrection==4 ); b.szCell[b.nCell] = b.szCell[b.nCell] - leafCorrection; if( !pOld->leaf ){ assert( leafCorrection==0 ); assert( pOld->hdrOffset==0 ); /* The right pointer of the child page pOld becomes the left ** pointer of the divider cell */ memcpy(b.apCell[b.nCell], &pOld->aData[8], 4); }else{ assert( leafCorrection==4 ); while( b.szCell[b.nCell]<4 ){ /* Do not allow any cells smaller than 4 bytes. If a smaller cell ** does exist, pad it with 0x00 bytes. */ assert( b.szCell[b.nCell]==3 || CORRUPT_DB ); assert( b.apCell[b.nCell]==&aSpace1[iSpace1-3] || CORRUPT_DB ); aSpace1[iSpace1++] = 0x00; b.szCell[b.nCell]++; } } b.nCell++; } } /* ** Figure out the number of pages needed to hold all b.nCell cells. ** Store this number in "k". Also compute szNew[] which is the total ** size of all cells on the i-th page and cntNew[] which is the index ** in b.apCell[] of the cell that divides page i from page i+1. ** cntNew[k] should equal b.nCell. ** ** Values computed by this block: ** ** k: The total number of sibling pages ** szNew[i]: Spaced used on the i-th sibling page. ** cntNew[i]: Index in b.apCell[] and b.szCell[] for the first cell to ** the right of the i-th sibling page. ** usableSpace: Number of bytes of space available on each sibling. ** */ usableSpace = pBt->usableSize - 12 + leafCorrection; for(i=0; inFree; if( szNew[i]<0 ){ rc = SQLITE_CORRUPT_BKPT; goto balance_cleanup; } for(j=0; jnOverflow; j++){ szNew[i] += 2 + p->xCellSize(p, p->apOvfl[j]); } cntNew[i] = cntOld[i]; } k = nOld; for(i=0; iusableSpace ){ if( i+1>=k ){ k = i+2; if( k>NB+2 ){ rc = SQLITE_CORRUPT_BKPT; goto balance_cleanup; } szNew[k-1] = 0; cntNew[k-1] = b.nCell; } sz = 2 + cachedCellSize(&b, cntNew[i]-1); szNew[i] -= sz; if( !leafData ){ if( cntNew[i]usableSpace ) break; szNew[i] += sz; cntNew[i]++; if( !leafData ){ if( cntNew[i]=b.nCell ){ k = i+1; }else if( cntNew[i] <= (i>0 ? cntNew[i-1] : 0) ){ rc = SQLITE_CORRUPT_BKPT; goto balance_cleanup; } } /* ** The packing computed by the previous block is biased toward the siblings ** on the left side (siblings with smaller keys). The left siblings are ** always nearly full, while the right-most sibling might be nearly empty. ** The next block of code attempts to adjust the packing of siblings to ** get a better balance. ** ** This adjustment is more than an optimization. The packing above might ** be so out of balance as to be illegal. For example, the right-most ** sibling might be completely empty. This adjustment is not optional. */ for(i=k-1; i>0; i--){ int szRight = szNew[i]; /* Size of sibling on the right */ int szLeft = szNew[i-1]; /* Size of sibling on the left */ int r; /* Index of right-most cell in left sibling */ int d; /* Index of first cell to the left of right sibling */ r = cntNew[i-1] - 1; d = r + 1 - leafData; (void)cachedCellSize(&b, d); do{ assert( d szLeft-(b.szCell[r]+(i==k-1?0:2)))){ break; } szRight += b.szCell[d] + 2; szLeft -= b.szCell[r] + 2; cntNew[i-1] = r; r--; d--; }while( r>=0 ); szNew[i] = szRight; szNew[i-1] = szLeft; if( cntNew[i-1] <= (i>1 ? cntNew[i-2] : 0) ){ rc = SQLITE_CORRUPT_BKPT; goto balance_cleanup; } } /* Sanity check: For a non-corrupt database file one of the follwing ** must be true: ** (1) We found one or more cells (cntNew[0])>0), or ** (2) pPage is a virtual root page. A virtual root page is when ** the real root page is page 1 and we are the only child of ** that page. */ assert( cntNew[0]>0 || (pParent->pgno==1 && pParent->nCell==0) || CORRUPT_DB); TRACE(("BALANCE: old: %d(nc=%d) %d(nc=%d) %d(nc=%d)\n", apOld[0]->pgno, apOld[0]->nCell, nOld>=2 ? apOld[1]->pgno : 0, nOld>=2 ? apOld[1]->nCell : 0, nOld>=3 ? apOld[2]->pgno : 0, nOld>=3 ? apOld[2]->nCell : 0 )); /* ** Allocate k new pages. Reuse old pages where possible. */ pageFlags = apOld[0]->aData[0]; for(i=0; ipDbPage); nNew++; if( rc ) goto balance_cleanup; }else{ assert( i>0 ); rc = allocateBtreePage(pBt, &pNew, &pgno, (bBulk ? 1 : pgno), 0); if( rc ) goto balance_cleanup; zeroPage(pNew, pageFlags); apNew[i] = pNew; nNew++; cntOld[i] = b.nCell; /* Set the pointer-map entry for the new sibling page. */ if( ISAUTOVACUUM ){ ptrmapPut(pBt, pNew->pgno, PTRMAP_BTREE, pParent->pgno, &rc); if( rc!=SQLITE_OK ){ goto balance_cleanup; } } } } /* ** Reassign page numbers so that the new pages are in ascending order. ** This helps to keep entries in the disk file in order so that a scan ** of the table is closer to a linear scan through the file. That in turn ** helps the operating system to deliver pages from the disk more rapidly. ** ** An O(n^2) insertion sort algorithm is used, but since n is never more ** than (NB+2) (a small constant), that should not be a problem. ** ** When NB==3, this one optimization makes the database about 25% faster ** for large insertions and deletions. */ for(i=0; ipgno; aPgFlags[i] = apNew[i]->pDbPage->flags; for(j=0; ji ){ sqlite3PagerRekey(apNew[iBest]->pDbPage, pBt->nPage+iBest+1, 0); } sqlite3PagerRekey(apNew[i]->pDbPage, pgno, aPgFlags[iBest]); apNew[i]->pgno = pgno; } } TRACE(("BALANCE: new: %d(%d nc=%d) %d(%d nc=%d) %d(%d nc=%d) " "%d(%d nc=%d) %d(%d nc=%d)\n", apNew[0]->pgno, szNew[0], cntNew[0], nNew>=2 ? apNew[1]->pgno : 0, nNew>=2 ? szNew[1] : 0, nNew>=2 ? cntNew[1] - cntNew[0] - !leafData : 0, nNew>=3 ? apNew[2]->pgno : 0, nNew>=3 ? szNew[2] : 0, nNew>=3 ? cntNew[2] - cntNew[1] - !leafData : 0, nNew>=4 ? apNew[3]->pgno : 0, nNew>=4 ? szNew[3] : 0, nNew>=4 ? cntNew[3] - cntNew[2] - !leafData : 0, nNew>=5 ? apNew[4]->pgno : 0, nNew>=5 ? szNew[4] : 0, nNew>=5 ? cntNew[4] - cntNew[3] - !leafData : 0 )); assert( sqlite3PagerIswriteable(pParent->pDbPage) ); put4byte(pRight, apNew[nNew-1]->pgno); /* If the sibling pages are not leaves, ensure that the right-child pointer ** of the right-most new sibling page is set to the value that was ** originally in the same field of the right-most old sibling page. */ if( (pageFlags & PTF_LEAF)==0 && nOld!=nNew ){ MemPage *pOld = (nNew>nOld ? apNew : apOld)[nOld-1]; memcpy(&apNew[nNew-1]->aData[8], &pOld->aData[8], 4); } /* Make any required updates to pointer map entries associated with ** cells stored on sibling pages following the balance operation. Pointer ** map entries associated with divider cells are set by the insertCell() ** routine. The associated pointer map entries are: ** ** a) if the cell contains a reference to an overflow chain, the ** entry associated with the first page in the overflow chain, and ** ** b) if the sibling pages are not leaves, the child page associated ** with the cell. ** ** If the sibling pages are not leaves, then the pointer map entry ** associated with the right-child of each sibling may also need to be ** updated. This happens below, after the sibling pages have been ** populated, not here. */ if( ISAUTOVACUUM ){ MemPage *pNew = apNew[0]; u8 *aOld = pNew->aData; int cntOldNext = pNew->nCell + pNew->nOverflow; int usableSize = pBt->usableSize; int iNew = 0; int iOld = 0; for(i=0; inCell + pOld->nOverflow + !leafData; aOld = pOld->aData; } if( i==cntNew[iNew] ){ pNew = apNew[++iNew]; if( !leafData ) continue; } /* Cell pCell is destined for new sibling page pNew. Originally, it ** was either part of sibling page iOld (possibly an overflow cell), ** or else the divider cell to the left of sibling page iOld. So, ** if sibling page iOld had the same page number as pNew, and if ** pCell really was a part of sibling page iOld (not a divider or ** overflow cell), we can skip updating the pointer map entries. */ if( iOld>=nNew || pNew->pgno!=aPgno[iOld] || !SQLITE_WITHIN(pCell,aOld,&aOld[usableSize]) ){ if( !leafCorrection ){ ptrmapPut(pBt, get4byte(pCell), PTRMAP_BTREE, pNew->pgno, &rc); } if( cachedCellSize(&b,i)>pNew->minLocal ){ ptrmapPutOvflPtr(pNew, pCell, &rc); } if( rc ) goto balance_cleanup; } } } /* Insert new divider cells into pParent. */ for(i=0; ileaf ){ memcpy(&pNew->aData[8], pCell, 4); }else if( leafData ){ /* If the tree is a leaf-data tree, and the siblings are leaves, ** then there is no divider cell in b.apCell[]. Instead, the divider ** cell consists of the integer key for the right-most cell of ** the sibling-page assembled above only. */ CellInfo info; j--; pNew->xParseCell(pNew, b.apCell[j], &info); pCell = pTemp; sz = 4 + putVarint(&pCell[4], info.nKey); pTemp = 0; }else{ pCell -= 4; /* Obscure case for non-leaf-data trees: If the cell at pCell was ** previously stored on a leaf node, and its reported size was 4 ** bytes, then it may actually be smaller than this ** (see btreeParseCellPtr(), 4 bytes is the minimum size of ** any cell). But it is important to pass the correct size to ** insertCell(), so reparse the cell now. ** ** This can only happen for b-trees used to evaluate "IN (SELECT ...)" ** and WITHOUT ROWID tables with exactly one column which is the ** primary key. */ if( b.szCell[j]==4 ){ assert(leafCorrection==4); sz = pParent->xCellSize(pParent, pCell); } } iOvflSpace += sz; assert( sz<=pBt->maxLocal+23 ); assert( iOvflSpace <= (int)pBt->pageSize ); insertCell(pParent, nxDiv+i, pCell, sz, pTemp, pNew->pgno, &rc); if( rc!=SQLITE_OK ) goto balance_cleanup; assert( sqlite3PagerIswriteable(pParent->pDbPage) ); } /* Now update the actual sibling pages. The order in which they are updated ** is important, as this code needs to avoid disrupting any page from which ** cells may still to be read. In practice, this means: ** ** (1) If cells are moving left (from apNew[iPg] to apNew[iPg-1]) ** then it is not safe to update page apNew[iPg] until after ** the left-hand sibling apNew[iPg-1] has been updated. ** ** (2) If cells are moving right (from apNew[iPg] to apNew[iPg+1]) ** then it is not safe to update page apNew[iPg] until after ** the right-hand sibling apNew[iPg+1] has been updated. ** ** If neither of the above apply, the page is safe to update. ** ** The iPg value in the following loop starts at nNew-1 goes down ** to 0, then back up to nNew-1 again, thus making two passes over ** the pages. On the initial downward pass, only condition (1) above ** needs to be tested because (2) will always be true from the previous ** step. On the upward pass, both conditions are always true, so the ** upwards pass simply processes pages that were missed on the downward ** pass. */ for(i=1-nNew; i=0 && iPg=0 /* On the upwards pass, or... */ || cntOld[iPg-1]>=cntNew[iPg-1] /* Condition (1) is true */ ){ int iNew; int iOld; int nNewCell; /* Verify condition (1): If cells are moving left, update iPg ** only after iPg-1 has already been updated. */ assert( iPg==0 || cntOld[iPg-1]>=cntNew[iPg-1] || abDone[iPg-1] ); /* Verify condition (2): If cells are moving right, update iPg ** only after iPg+1 has already been updated. */ assert( cntNew[iPg]>=cntOld[iPg] || abDone[iPg+1] ); if( iPg==0 ){ iNew = iOld = 0; nNewCell = cntNew[0]; }else{ iOld = iPgnFree = usableSpace-szNew[iPg]; assert( apNew[iPg]->nOverflow==0 ); assert( apNew[iPg]->nCell==nNewCell ); } } /* All pages have been processed exactly once */ assert( memcmp(abDone, "\01\01\01\01\01", nNew)==0 ); assert( nOld>0 ); assert( nNew>0 ); if( isRoot && pParent->nCell==0 && pParent->hdrOffset<=apNew[0]->nFree ){ /* The root page of the b-tree now contains no cells. The only sibling ** page is the right-child of the parent. Copy the contents of the ** child page into the parent, decreasing the overall height of the ** b-tree structure by one. This is described as the "balance-shallower" ** sub-algorithm in some documentation. ** ** If this is an auto-vacuum database, the call to copyNodeContent() ** sets all pointer-map entries corresponding to database image pages ** for which the pointer is stored within the content being copied. ** ** It is critical that the child page be defragmented before being ** copied into the parent, because if the parent is page 1 then it will ** by smaller than the child due to the database header, and so all the ** free space needs to be up front. */ assert( nNew==1 || CORRUPT_DB ); rc = defragmentPage(apNew[0]); testcase( rc!=SQLITE_OK ); assert( apNew[0]->nFree == (get2byte(&apNew[0]->aData[5])-apNew[0]->cellOffset-apNew[0]->nCell*2) || rc!=SQLITE_OK ); copyNodeContent(apNew[0], pParent, &rc); freePage(apNew[0], &rc); }else if( ISAUTOVACUUM && !leafCorrection ){ /* Fix the pointer map entries associated with the right-child of each ** sibling page. All other pointer map entries have already been taken ** care of. */ for(i=0; iaData[8]); ptrmapPut(pBt, key, PTRMAP_BTREE, apNew[i]->pgno, &rc); } } assert( pParent->isInit ); TRACE(("BALANCE: finished: old=%d new=%d cells=%d\n", nOld, nNew, b.nCell)); /* Free any old pages that were not reused as new pages. */ for(i=nNew; iisInit ){ /* The ptrmapCheckPages() contains assert() statements that verify that ** all pointer map pages are set correctly. This is helpful while ** debugging. This is usually disabled because a corrupt database may ** cause an assert() statement to fail. */ ptrmapCheckPages(apNew, nNew); ptrmapCheckPages(&pParent, 1); } #endif /* ** Cleanup before returning. */ balance_cleanup: sqlite3ScratchFree(b.apCell); for(i=0; ipBt; /* The BTree */ assert( pRoot->nOverflow>0 ); assert( sqlite3_mutex_held(pBt->mutex) ); /* Make pRoot, the root page of the b-tree, writable. Allocate a new ** page that will become the new right-child of pPage. Copy the contents ** of the node stored on pRoot into the new child page. */ rc = sqlite3PagerWrite(pRoot->pDbPage); if( rc==SQLITE_OK ){ rc = allocateBtreePage(pBt,&pChild,&pgnoChild,pRoot->pgno,0); copyNodeContent(pRoot, pChild, &rc); if( ISAUTOVACUUM ){ ptrmapPut(pBt, pgnoChild, PTRMAP_BTREE, pRoot->pgno, &rc); } } if( rc ){ *ppChild = 0; releasePage(pChild); return rc; } assert( sqlite3PagerIswriteable(pChild->pDbPage) ); assert( sqlite3PagerIswriteable(pRoot->pDbPage) ); assert( pChild->nCell==pRoot->nCell ); TRACE(("BALANCE: copy root %d into %d\n", pRoot->pgno, pChild->pgno)); /* Copy the overflow cells from pRoot to pChild */ memcpy(pChild->aiOvfl, pRoot->aiOvfl, pRoot->nOverflow*sizeof(pRoot->aiOvfl[0])); memcpy(pChild->apOvfl, pRoot->apOvfl, pRoot->nOverflow*sizeof(pRoot->apOvfl[0])); pChild->nOverflow = pRoot->nOverflow; /* Zero the contents of pRoot. Then install pChild as the right-child. */ zeroPage(pRoot, pChild->aData[0] & ~PTF_LEAF); put4byte(&pRoot->aData[pRoot->hdrOffset+8], pgnoChild); *ppChild = pChild; return SQLITE_OK; } /* ** The page that pCur currently points to has just been modified in ** some way. This function figures out if this modification means the ** tree needs to be balanced, and if so calls the appropriate balancing ** routine. Balancing routines are: ** ** balance_quick() ** balance_deeper() ** balance_nonroot() */ static int balance(BtCursor *pCur){ int rc = SQLITE_OK; const int nMin = pCur->pBt->usableSize * 2 / 3; u8 aBalanceQuickSpace[13]; u8 *pFree = 0; VVA_ONLY( int balance_quick_called = 0 ); VVA_ONLY( int balance_deeper_called = 0 ); do { int iPage = pCur->iPage; MemPage *pPage = pCur->apPage[iPage]; if( iPage==0 ){ if( pPage->nOverflow ){ /* The root page of the b-tree is overfull. In this case call the ** balance_deeper() function to create a new child for the root-page ** and copy the current contents of the root-page to it. The ** next iteration of the do-loop will balance the child page. */ assert( balance_deeper_called==0 ); VVA_ONLY( balance_deeper_called++ ); rc = balance_deeper(pPage, &pCur->apPage[1]); if( rc==SQLITE_OK ){ pCur->iPage = 1; pCur->aiIdx[0] = 0; pCur->aiIdx[1] = 0; assert( pCur->apPage[1]->nOverflow ); } }else{ break; } }else if( pPage->nOverflow==0 && pPage->nFree<=nMin ){ break; }else{ MemPage * const pParent = pCur->apPage[iPage-1]; int const iIdx = pCur->aiIdx[iPage-1]; rc = sqlite3PagerWrite(pParent->pDbPage); if( rc==SQLITE_OK ){ #ifndef SQLITE_OMIT_QUICKBALANCE if( pPage->intKeyLeaf && pPage->nOverflow==1 && pPage->aiOvfl[0]==pPage->nCell && pParent->pgno!=1 && pParent->nCell==iIdx ){ /* Call balance_quick() to create a new sibling of pPage on which ** to store the overflow cell. balance_quick() inserts a new cell ** into pParent, which may cause pParent overflow. If this ** happens, the next iteration of the do-loop will balance pParent ** use either balance_nonroot() or balance_deeper(). Until this ** happens, the overflow cell is stored in the aBalanceQuickSpace[] ** buffer. ** ** The purpose of the following assert() is to check that only a ** single call to balance_quick() is made for each call to this ** function. If this were not verified, a subtle bug involving reuse ** of the aBalanceQuickSpace[] might sneak in. */ assert( balance_quick_called==0 ); VVA_ONLY( balance_quick_called++ ); rc = balance_quick(pParent, pPage, aBalanceQuickSpace); }else #endif { /* In this case, call balance_nonroot() to redistribute cells ** between pPage and up to 2 of its sibling pages. This involves ** modifying the contents of pParent, which may cause pParent to ** become overfull or underfull. The next iteration of the do-loop ** will balance the parent page to correct this. ** ** If the parent page becomes overfull, the overflow cell or cells ** are stored in the pSpace buffer allocated immediately below. ** A subsequent iteration of the do-loop will deal with this by ** calling balance_nonroot() (balance_deeper() may be called first, ** but it doesn't deal with overflow cells - just moves them to a ** different page). Once this subsequent call to balance_nonroot() ** has completed, it is safe to release the pSpace buffer used by ** the previous call, as the overflow cell data will have been ** copied either into the body of a database page or into the new ** pSpace buffer passed to the latter call to balance_nonroot(). */ u8 *pSpace = sqlite3PageMalloc(pCur->pBt->pageSize); rc = balance_nonroot(pParent, iIdx, pSpace, iPage==1, pCur->hints&BTREE_BULKLOAD); if( pFree ){ /* If pFree is not NULL, it points to the pSpace buffer used ** by a previous call to balance_nonroot(). Its contents are ** now stored either on real database pages or within the ** new pSpace buffer, so it may be safely freed here. */ sqlite3PageFree(pFree); } /* The pSpace buffer will be freed after the next call to ** balance_nonroot(), or just before this function returns, whichever ** comes first. */ pFree = pSpace; } } pPage->nOverflow = 0; /* The next iteration of the do-loop balances the parent page. */ releasePage(pPage); pCur->iPage--; assert( pCur->iPage>=0 ); } }while( rc==SQLITE_OK ); if( pFree ){ sqlite3PageFree(pFree); } return rc; } /* ** Insert a new record into the BTree. The content of the new record ** is described by the pX object. The pCur cursor is used only to ** define what table the record should be inserted into, and is left ** pointing at a random location. ** ** For a table btree (used for rowid tables), only the pX.nKey value of ** the key is used. The pX.pKey value must be NULL. The pX.nKey is the ** rowid or INTEGER PRIMARY KEY of the row. The pX.nData,pData,nZero fields ** hold the content of the row. ** ** For an index btree (used for indexes and WITHOUT ROWID tables), the ** key is an arbitrary byte sequence stored in pX.pKey,nKey. The ** pX.pData,nData,nZero fields must be zero. ** ** If the seekResult parameter is non-zero, then a successful call to ** MovetoUnpacked() to seek cursor pCur to (pKey, nKey) has already ** been performed. seekResult is the search result returned (a negative ** number if pCur points at an entry that is smaller than (pKey, nKey), or ** a positive value if pCur points at an entry that is larger than ** (pKey, nKey)). ** ** If the seekResult parameter is non-zero, then the caller guarantees that ** cursor pCur is pointing at the existing copy of a row that is to be ** overwritten. If the seekResult parameter is 0, then cursor pCur may ** point to any entry or to no entry at all and so this function has to seek ** the cursor before the new key can be inserted. */ SQLITE_PRIVATE int sqlite3BtreeInsert( BtCursor *pCur, /* Insert data into the table of this cursor */ const BtreePayload *pX, /* Content of the row to be inserted */ int appendBias, /* True if this is likely an append */ int seekResult /* Result of prior MovetoUnpacked() call */ ){ int rc; int loc = seekResult; /* -1: before desired location +1: after */ int szNew = 0; int idx; MemPage *pPage; Btree *p = pCur->pBtree; BtShared *pBt = p->pBt; unsigned char *oldCell; unsigned char *newCell = 0; if( pCur->eState==CURSOR_FAULT ){ assert( pCur->skipNext!=SQLITE_OK ); return pCur->skipNext; } assert( cursorOwnsBtShared(pCur) ); assert( (pCur->curFlags & BTCF_WriteFlag)!=0 && pBt->inTransaction==TRANS_WRITE && (pBt->btsFlags & BTS_READ_ONLY)==0 ); assert( hasSharedCacheTableLock(p, pCur->pgnoRoot, pCur->pKeyInfo!=0, 2) ); /* Assert that the caller has been consistent. If this cursor was opened ** expecting an index b-tree, then the caller should be inserting blob ** keys with no associated data. If the cursor was opened expecting an ** intkey table, the caller should be inserting integer keys with a ** blob of associated data. */ assert( (pX->pKey==0)==(pCur->pKeyInfo==0) ); /* Save the positions of any other cursors open on this table. ** ** In some cases, the call to btreeMoveto() below is a no-op. For ** example, when inserting data into a table with auto-generated integer ** keys, the VDBE layer invokes sqlite3BtreeLast() to figure out the ** integer key to use. It then calls this function to actually insert the ** data into the intkey B-Tree. In this case btreeMoveto() recognizes ** that the cursor is already where it needs to be and returns without ** doing any work. To avoid thwarting these optimizations, it is important ** not to clear the cursor here. */ if( pCur->curFlags & BTCF_Multiple ){ rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur); if( rc ) return rc; } if( pCur->pKeyInfo==0 ){ assert( pX->pKey==0 ); /* If this is an insert into a table b-tree, invalidate any incrblob ** cursors open on the row being replaced */ invalidateIncrblobCursors(p, pX->nKey, 0); /* If the cursor is currently on the last row and we are appending a ** new row onto the end, set the "loc" to avoid an unnecessary ** btreeMoveto() call */ if( (pCur->curFlags&BTCF_ValidNKey)!=0 && pX->nKey>0 && pCur->info.nKey==pX->nKey-1 ){ loc = -1; }else if( loc==0 ){ rc = sqlite3BtreeMovetoUnpacked(pCur, 0, pX->nKey, appendBias, &loc); if( rc ) return rc; } }else if( loc==0 ){ rc = btreeMoveto(pCur, pX->pKey, pX->nKey, appendBias, &loc); if( rc ) return rc; } assert( pCur->eState==CURSOR_VALID || (pCur->eState==CURSOR_INVALID && loc) ); pPage = pCur->apPage[pCur->iPage]; assert( pPage->intKey || pX->nKey>=0 ); assert( pPage->leaf || !pPage->intKey ); TRACE(("INSERT: table=%d nkey=%lld ndata=%d page=%d %s\n", pCur->pgnoRoot, pX->nKey, pX->nData, pPage->pgno, loc==0 ? "overwrite" : "new entry")); assert( pPage->isInit ); newCell = pBt->pTmpSpace; assert( newCell!=0 ); rc = fillInCell(pPage, newCell, pX, &szNew); if( rc ) goto end_insert; assert( szNew==pPage->xCellSize(pPage, newCell) ); assert( szNew <= MX_CELL_SIZE(pBt) ); idx = pCur->aiIdx[pCur->iPage]; if( loc==0 ){ u16 szOld; assert( idxnCell ); rc = sqlite3PagerWrite(pPage->pDbPage); if( rc ){ goto end_insert; } oldCell = findCell(pPage, idx); if( !pPage->leaf ){ memcpy(newCell, oldCell, 4); } rc = clearCell(pPage, oldCell, &szOld); dropCell(pPage, idx, szOld, &rc); if( rc ) goto end_insert; }else if( loc<0 && pPage->nCell>0 ){ assert( pPage->leaf ); idx = ++pCur->aiIdx[pCur->iPage]; }else{ assert( pPage->leaf ); } insertCell(pPage, idx, newCell, szNew, 0, 0, &rc); assert( pPage->nOverflow==0 || rc==SQLITE_OK ); assert( rc!=SQLITE_OK || pPage->nCell>0 || pPage->nOverflow>0 ); /* If no error has occurred and pPage has an overflow cell, call balance() ** to redistribute the cells within the tree. Since balance() may move ** the cursor, zero the BtCursor.info.nSize and BTCF_ValidNKey ** variables. ** ** Previous versions of SQLite called moveToRoot() to move the cursor ** back to the root page as balance() used to invalidate the contents ** of BtCursor.apPage[] and BtCursor.aiIdx[]. Instead of doing that, ** set the cursor state to "invalid". This makes common insert operations ** slightly faster. ** ** There is a subtle but important optimization here too. When inserting ** multiple records into an intkey b-tree using a single cursor (as can ** happen while processing an "INSERT INTO ... SELECT" statement), it ** is advantageous to leave the cursor pointing to the last entry in ** the b-tree if possible. If the cursor is left pointing to the last ** entry in the table, and the next row inserted has an integer key ** larger than the largest existing key, it is possible to insert the ** row without seeking the cursor. This can be a big performance boost. */ pCur->info.nSize = 0; if( pPage->nOverflow ){ assert( rc==SQLITE_OK ); pCur->curFlags &= ~(BTCF_ValidNKey); rc = balance(pCur); /* Must make sure nOverflow is reset to zero even if the balance() ** fails. Internal data structure corruption will result otherwise. ** Also, set the cursor state to invalid. This stops saveCursorPosition() ** from trying to save the current position of the cursor. */ pCur->apPage[pCur->iPage]->nOverflow = 0; pCur->eState = CURSOR_INVALID; } assert( pCur->apPage[pCur->iPage]->nOverflow==0 ); end_insert: return rc; } /* ** Delete the entry that the cursor is pointing to. ** ** If the BTREE_SAVEPOSITION bit of the flags parameter is zero, then ** the cursor is left pointing at an arbitrary location after the delete. ** But if that bit is set, then the cursor is left in a state such that ** the next call to BtreeNext() or BtreePrev() moves it to the same row ** as it would have been on if the call to BtreeDelete() had been omitted. ** ** The BTREE_AUXDELETE bit of flags indicates that is one of several deletes ** associated with a single table entry and its indexes. Only one of those ** deletes is considered the "primary" delete. The primary delete occurs ** on a cursor that is not a BTREE_FORDELETE cursor. All but one delete ** operation on non-FORDELETE cursors is tagged with the AUXDELETE flag. ** The BTREE_AUXDELETE bit is a hint that is not used by this implementation, ** but which might be used by alternative storage engines. */ SQLITE_PRIVATE int sqlite3BtreeDelete(BtCursor *pCur, u8 flags){ Btree *p = pCur->pBtree; BtShared *pBt = p->pBt; int rc; /* Return code */ MemPage *pPage; /* Page to delete cell from */ unsigned char *pCell; /* Pointer to cell to delete */ int iCellIdx; /* Index of cell to delete */ int iCellDepth; /* Depth of node containing pCell */ u16 szCell; /* Size of the cell being deleted */ int bSkipnext = 0; /* Leaf cursor in SKIPNEXT state */ u8 bPreserve = flags & BTREE_SAVEPOSITION; /* Keep cursor valid */ assert( cursorOwnsBtShared(pCur) ); assert( pBt->inTransaction==TRANS_WRITE ); assert( (pBt->btsFlags & BTS_READ_ONLY)==0 ); assert( pCur->curFlags & BTCF_WriteFlag ); assert( hasSharedCacheTableLock(p, pCur->pgnoRoot, pCur->pKeyInfo!=0, 2) ); assert( !hasReadConflicts(p, pCur->pgnoRoot) ); assert( pCur->aiIdx[pCur->iPage]apPage[pCur->iPage]->nCell ); assert( pCur->eState==CURSOR_VALID ); assert( (flags & ~(BTREE_SAVEPOSITION | BTREE_AUXDELETE))==0 ); iCellDepth = pCur->iPage; iCellIdx = pCur->aiIdx[iCellDepth]; pPage = pCur->apPage[iCellDepth]; pCell = findCell(pPage, iCellIdx); /* If the bPreserve flag is set to true, then the cursor position must ** be preserved following this delete operation. If the current delete ** will cause a b-tree rebalance, then this is done by saving the cursor ** key and leaving the cursor in CURSOR_REQUIRESEEK state before ** returning. ** ** Or, if the current delete will not cause a rebalance, then the cursor ** will be left in CURSOR_SKIPNEXT state pointing to the entry immediately ** before or after the deleted entry. In this case set bSkipnext to true. */ if( bPreserve ){ if( !pPage->leaf || (pPage->nFree+cellSizePtr(pPage,pCell)+2)>(int)(pBt->usableSize*2/3) ){ /* A b-tree rebalance will be required after deleting this entry. ** Save the cursor key. */ rc = saveCursorKey(pCur); if( rc ) return rc; }else{ bSkipnext = 1; } } /* If the page containing the entry to delete is not a leaf page, move ** the cursor to the largest entry in the tree that is smaller than ** the entry being deleted. This cell will replace the cell being deleted ** from the internal node. The 'previous' entry is used for this instead ** of the 'next' entry, as the previous entry is always a part of the ** sub-tree headed by the child page of the cell being deleted. This makes ** balancing the tree following the delete operation easier. */ if( !pPage->leaf ){ int notUsed = 0; rc = sqlite3BtreePrevious(pCur, ¬Used); if( rc ) return rc; } /* Save the positions of any other cursors open on this table before ** making any modifications. */ if( pCur->curFlags & BTCF_Multiple ){ rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur); if( rc ) return rc; } /* If this is a delete operation to remove a row from a table b-tree, ** invalidate any incrblob cursors open on the row being deleted. */ if( pCur->pKeyInfo==0 ){ invalidateIncrblobCursors(p, pCur->info.nKey, 0); } /* Make the page containing the entry to be deleted writable. Then free any ** overflow pages associated with the entry and finally remove the cell ** itself from within the page. */ rc = sqlite3PagerWrite(pPage->pDbPage); if( rc ) return rc; rc = clearCell(pPage, pCell, &szCell); dropCell(pPage, iCellIdx, szCell, &rc); if( rc ) return rc; /* If the cell deleted was not located on a leaf page, then the cursor ** is currently pointing to the largest entry in the sub-tree headed ** by the child-page of the cell that was just deleted from an internal ** node. The cell from the leaf node needs to be moved to the internal ** node to replace the deleted cell. */ if( !pPage->leaf ){ MemPage *pLeaf = pCur->apPage[pCur->iPage]; int nCell; Pgno n = pCur->apPage[iCellDepth+1]->pgno; unsigned char *pTmp; pCell = findCell(pLeaf, pLeaf->nCell-1); if( pCell<&pLeaf->aData[4] ) return SQLITE_CORRUPT_BKPT; nCell = pLeaf->xCellSize(pLeaf, pCell); assert( MX_CELL_SIZE(pBt) >= nCell ); pTmp = pBt->pTmpSpace; assert( pTmp!=0 ); rc = sqlite3PagerWrite(pLeaf->pDbPage); if( rc==SQLITE_OK ){ insertCell(pPage, iCellIdx, pCell-4, nCell+4, pTmp, n, &rc); } dropCell(pLeaf, pLeaf->nCell-1, nCell, &rc); if( rc ) return rc; } /* Balance the tree. If the entry deleted was located on a leaf page, ** then the cursor still points to that page. In this case the first ** call to balance() repairs the tree, and the if(...) condition is ** never true. ** ** Otherwise, if the entry deleted was on an internal node page, then ** pCur is pointing to the leaf page from which a cell was removed to ** replace the cell deleted from the internal node. This is slightly ** tricky as the leaf node may be underfull, and the internal node may ** be either under or overfull. In this case run the balancing algorithm ** on the leaf node first. If the balance proceeds far enough up the ** tree that we can be sure that any problem in the internal node has ** been corrected, so be it. Otherwise, after balancing the leaf node, ** walk the cursor up the tree to the internal node and balance it as ** well. */ rc = balance(pCur); if( rc==SQLITE_OK && pCur->iPage>iCellDepth ){ while( pCur->iPage>iCellDepth ){ releasePage(pCur->apPage[pCur->iPage--]); } rc = balance(pCur); } if( rc==SQLITE_OK ){ if( bSkipnext ){ assert( bPreserve && (pCur->iPage==iCellDepth || CORRUPT_DB) ); assert( pPage==pCur->apPage[pCur->iPage] || CORRUPT_DB ); assert( (pPage->nCell>0 || CORRUPT_DB) && iCellIdx<=pPage->nCell ); pCur->eState = CURSOR_SKIPNEXT; if( iCellIdx>=pPage->nCell ){ pCur->skipNext = -1; pCur->aiIdx[iCellDepth] = pPage->nCell-1; }else{ pCur->skipNext = 1; } }else{ rc = moveToRoot(pCur); if( bPreserve ){ pCur->eState = CURSOR_REQUIRESEEK; } } } return rc; } /* ** Create a new BTree table. Write into *piTable the page ** number for the root page of the new table. ** ** The type of type is determined by the flags parameter. Only the ** following values of flags are currently in use. Other values for ** flags might not work: ** ** BTREE_INTKEY|BTREE_LEAFDATA Used for SQL tables with rowid keys ** BTREE_ZERODATA Used for SQL indices */ static int btreeCreateTable(Btree *p, int *piTable, int createTabFlags){ BtShared *pBt = p->pBt; MemPage *pRoot; Pgno pgnoRoot; int rc; int ptfFlags; /* Page-type flage for the root page of new table */ assert( sqlite3BtreeHoldsMutex(p) ); assert( pBt->inTransaction==TRANS_WRITE ); assert( (pBt->btsFlags & BTS_READ_ONLY)==0 ); #ifdef SQLITE_OMIT_AUTOVACUUM rc = allocateBtreePage(pBt, &pRoot, &pgnoRoot, 1, 0); if( rc ){ return rc; } #else if( pBt->autoVacuum ){ Pgno pgnoMove; /* Move a page here to make room for the root-page */ MemPage *pPageMove; /* The page to move to. */ /* Creating a new table may probably require moving an existing database ** to make room for the new tables root page. In case this page turns ** out to be an overflow page, delete all overflow page-map caches ** held by open cursors. */ invalidateAllOverflowCache(pBt); /* Read the value of meta[3] from the database to determine where the ** root page of the new table should go. meta[3] is the largest root-page ** created so far, so the new root-page is (meta[3]+1). */ sqlite3BtreeGetMeta(p, BTREE_LARGEST_ROOT_PAGE, &pgnoRoot); pgnoRoot++; /* The new root-page may not be allocated on a pointer-map page, or the ** PENDING_BYTE page. */ while( pgnoRoot==PTRMAP_PAGENO(pBt, pgnoRoot) || pgnoRoot==PENDING_BYTE_PAGE(pBt) ){ pgnoRoot++; } assert( pgnoRoot>=3 || CORRUPT_DB ); testcase( pgnoRoot<3 ); /* Allocate a page. The page that currently resides at pgnoRoot will ** be moved to the allocated page (unless the allocated page happens ** to reside at pgnoRoot). */ rc = allocateBtreePage(pBt, &pPageMove, &pgnoMove, pgnoRoot, BTALLOC_EXACT); if( rc!=SQLITE_OK ){ return rc; } if( pgnoMove!=pgnoRoot ){ /* pgnoRoot is the page that will be used for the root-page of ** the new table (assuming an error did not occur). But we were ** allocated pgnoMove. If required (i.e. if it was not allocated ** by extending the file), the current page at position pgnoMove ** is already journaled. */ u8 eType = 0; Pgno iPtrPage = 0; /* Save the positions of any open cursors. This is required in ** case they are holding a reference to an xFetch reference ** corresponding to page pgnoRoot. */ rc = saveAllCursors(pBt, 0, 0); releasePage(pPageMove); if( rc!=SQLITE_OK ){ return rc; } /* Move the page currently at pgnoRoot to pgnoMove. */ rc = btreeGetPage(pBt, pgnoRoot, &pRoot, 0); if( rc!=SQLITE_OK ){ return rc; } rc = ptrmapGet(pBt, pgnoRoot, &eType, &iPtrPage); if( eType==PTRMAP_ROOTPAGE || eType==PTRMAP_FREEPAGE ){ rc = SQLITE_CORRUPT_BKPT; } if( rc!=SQLITE_OK ){ releasePage(pRoot); return rc; } assert( eType!=PTRMAP_ROOTPAGE ); assert( eType!=PTRMAP_FREEPAGE ); rc = relocatePage(pBt, pRoot, eType, iPtrPage, pgnoMove, 0); releasePage(pRoot); /* Obtain the page at pgnoRoot */ if( rc!=SQLITE_OK ){ return rc; } rc = btreeGetPage(pBt, pgnoRoot, &pRoot, 0); if( rc!=SQLITE_OK ){ return rc; } rc = sqlite3PagerWrite(pRoot->pDbPage); if( rc!=SQLITE_OK ){ releasePage(pRoot); return rc; } }else{ pRoot = pPageMove; } /* Update the pointer-map and meta-data with the new root-page number. */ ptrmapPut(pBt, pgnoRoot, PTRMAP_ROOTPAGE, 0, &rc); if( rc ){ releasePage(pRoot); return rc; } /* When the new root page was allocated, page 1 was made writable in ** order either to increase the database filesize, or to decrement the ** freelist count. Hence, the sqlite3BtreeUpdateMeta() call cannot fail. */ assert( sqlite3PagerIswriteable(pBt->pPage1->pDbPage) ); rc = sqlite3BtreeUpdateMeta(p, 4, pgnoRoot); if( NEVER(rc) ){ releasePage(pRoot); return rc; } }else{ rc = allocateBtreePage(pBt, &pRoot, &pgnoRoot, 1, 0); if( rc ) return rc; } #endif assert( sqlite3PagerIswriteable(pRoot->pDbPage) ); if( createTabFlags & BTREE_INTKEY ){ ptfFlags = PTF_INTKEY | PTF_LEAFDATA | PTF_LEAF; }else{ ptfFlags = PTF_ZERODATA | PTF_LEAF; } zeroPage(pRoot, ptfFlags); sqlite3PagerUnref(pRoot->pDbPage); assert( (pBt->openFlags & BTREE_SINGLE)==0 || pgnoRoot==2 ); *piTable = (int)pgnoRoot; return SQLITE_OK; } SQLITE_PRIVATE int sqlite3BtreeCreateTable(Btree *p, int *piTable, int flags){ int rc; sqlite3BtreeEnter(p); rc = btreeCreateTable(p, piTable, flags); sqlite3BtreeLeave(p); return rc; } /* ** Erase the given database page and all its children. Return ** the page to the freelist. */ static int clearDatabasePage( BtShared *pBt, /* The BTree that contains the table */ Pgno pgno, /* Page number to clear */ int freePageFlag, /* Deallocate page if true */ int *pnChange /* Add number of Cells freed to this counter */ ){ MemPage *pPage; int rc; unsigned char *pCell; int i; int hdr; u16 szCell; assert( sqlite3_mutex_held(pBt->mutex) ); if( pgno>btreePagecount(pBt) ){ return SQLITE_CORRUPT_BKPT; } rc = getAndInitPage(pBt, pgno, &pPage, 0, 0); if( rc ) return rc; if( pPage->bBusy ){ rc = SQLITE_CORRUPT_BKPT; goto cleardatabasepage_out; } pPage->bBusy = 1; hdr = pPage->hdrOffset; for(i=0; inCell; i++){ pCell = findCell(pPage, i); if( !pPage->leaf ){ rc = clearDatabasePage(pBt, get4byte(pCell), 1, pnChange); if( rc ) goto cleardatabasepage_out; } rc = clearCell(pPage, pCell, &szCell); if( rc ) goto cleardatabasepage_out; } if( !pPage->leaf ){ rc = clearDatabasePage(pBt, get4byte(&pPage->aData[hdr+8]), 1, pnChange); if( rc ) goto cleardatabasepage_out; }else if( pnChange ){ assert( pPage->intKey || CORRUPT_DB ); testcase( !pPage->intKey ); *pnChange += pPage->nCell; } if( freePageFlag ){ freePage(pPage, &rc); }else if( (rc = sqlite3PagerWrite(pPage->pDbPage))==0 ){ zeroPage(pPage, pPage->aData[hdr] | PTF_LEAF); } cleardatabasepage_out: pPage->bBusy = 0; releasePage(pPage); return rc; } /* ** Delete all information from a single table in the database. iTable is ** the page number of the root of the table. After this routine returns, ** the root page is empty, but still exists. ** ** This routine will fail with SQLITE_LOCKED if there are any open ** read cursors on the table. Open write cursors are moved to the ** root of the table. ** ** If pnChange is not NULL, then table iTable must be an intkey table. The ** integer value pointed to by pnChange is incremented by the number of ** entries in the table. */ SQLITE_PRIVATE int sqlite3BtreeClearTable(Btree *p, int iTable, int *pnChange){ int rc; BtShared *pBt = p->pBt; sqlite3BtreeEnter(p); assert( p->inTrans==TRANS_WRITE ); rc = saveAllCursors(pBt, (Pgno)iTable, 0); if( SQLITE_OK==rc ){ /* Invalidate all incrblob cursors open on table iTable (assuming iTable ** is the root of a table b-tree - if it is not, the following call is ** a no-op). */ invalidateIncrblobCursors(p, 0, 1); rc = clearDatabasePage(pBt, (Pgno)iTable, 0, pnChange); } sqlite3BtreeLeave(p); return rc; } /* ** Delete all information from the single table that pCur is open on. ** ** This routine only work for pCur on an ephemeral table. */ SQLITE_PRIVATE int sqlite3BtreeClearTableOfCursor(BtCursor *pCur){ return sqlite3BtreeClearTable(pCur->pBtree, pCur->pgnoRoot, 0); } /* ** Erase all information in a table and add the root of the table to ** the freelist. Except, the root of the principle table (the one on ** page 1) is never added to the freelist. ** ** This routine will fail with SQLITE_LOCKED if there are any open ** cursors on the table. ** ** If AUTOVACUUM is enabled and the page at iTable is not the last ** root page in the database file, then the last root page ** in the database file is moved into the slot formerly occupied by ** iTable and that last slot formerly occupied by the last root page ** is added to the freelist instead of iTable. In this say, all ** root pages are kept at the beginning of the database file, which ** is necessary for AUTOVACUUM to work right. *piMoved is set to the ** page number that used to be the last root page in the file before ** the move. If no page gets moved, *piMoved is set to 0. ** The last root page is recorded in meta[3] and the value of ** meta[3] is updated by this procedure. */ static int btreeDropTable(Btree *p, Pgno iTable, int *piMoved){ int rc; MemPage *pPage = 0; BtShared *pBt = p->pBt; assert( sqlite3BtreeHoldsMutex(p) ); assert( p->inTrans==TRANS_WRITE ); /* It is illegal to drop a table if any cursors are open on the ** database. This is because in auto-vacuum mode the backend may ** need to move another root-page to fill a gap left by the deleted ** root page. If an open cursor was using this page a problem would ** occur. ** ** This error is caught long before control reaches this point. */ if( NEVER(pBt->pCursor) ){ sqlite3ConnectionBlocked(p->db, pBt->pCursor->pBtree->db); return SQLITE_LOCKED_SHAREDCACHE; } /* ** It is illegal to drop the sqlite_master table on page 1. But again, ** this error is caught long before reaching this point. */ if( NEVER(iTable<2) ){ return SQLITE_CORRUPT_BKPT; } rc = btreeGetPage(pBt, (Pgno)iTable, &pPage, 0); if( rc ) return rc; rc = sqlite3BtreeClearTable(p, iTable, 0); if( rc ){ releasePage(pPage); return rc; } *piMoved = 0; #ifdef SQLITE_OMIT_AUTOVACUUM freePage(pPage, &rc); releasePage(pPage); #else if( pBt->autoVacuum ){ Pgno maxRootPgno; sqlite3BtreeGetMeta(p, BTREE_LARGEST_ROOT_PAGE, &maxRootPgno); if( iTable==maxRootPgno ){ /* If the table being dropped is the table with the largest root-page ** number in the database, put the root page on the free list. */ freePage(pPage, &rc); releasePage(pPage); if( rc!=SQLITE_OK ){ return rc; } }else{ /* The table being dropped does not have the largest root-page ** number in the database. So move the page that does into the ** gap left by the deleted root-page. */ MemPage *pMove; releasePage(pPage); rc = btreeGetPage(pBt, maxRootPgno, &pMove, 0); if( rc!=SQLITE_OK ){ return rc; } rc = relocatePage(pBt, pMove, PTRMAP_ROOTPAGE, 0, iTable, 0); releasePage(pMove); if( rc!=SQLITE_OK ){ return rc; } pMove = 0; rc = btreeGetPage(pBt, maxRootPgno, &pMove, 0); freePage(pMove, &rc); releasePage(pMove); if( rc!=SQLITE_OK ){ return rc; } *piMoved = maxRootPgno; } /* Set the new 'max-root-page' value in the database header. This ** is the old value less one, less one more if that happens to ** be a root-page number, less one again if that is the ** PENDING_BYTE_PAGE. */ maxRootPgno--; while( maxRootPgno==PENDING_BYTE_PAGE(pBt) || PTRMAP_ISPAGE(pBt, maxRootPgno) ){ maxRootPgno--; } assert( maxRootPgno!=PENDING_BYTE_PAGE(pBt) ); rc = sqlite3BtreeUpdateMeta(p, 4, maxRootPgno); }else{ freePage(pPage, &rc); releasePage(pPage); } #endif return rc; } SQLITE_PRIVATE int sqlite3BtreeDropTable(Btree *p, int iTable, int *piMoved){ int rc; sqlite3BtreeEnter(p); rc = btreeDropTable(p, iTable, piMoved); sqlite3BtreeLeave(p); return rc; } /* ** This function may only be called if the b-tree connection already ** has a read or write transaction open on the database. ** ** Read the meta-information out of a database file. Meta[0] ** is the number of free pages currently in the database. Meta[1] ** through meta[15] are available for use by higher layers. Meta[0] ** is read-only, the others are read/write. ** ** The schema layer numbers meta values differently. At the schema ** layer (and the SetCookie and ReadCookie opcodes) the number of ** free pages is not visible. So Cookie[0] is the same as Meta[1]. ** ** This routine treats Meta[BTREE_DATA_VERSION] as a special case. Instead ** of reading the value out of the header, it instead loads the "DataVersion" ** from the pager. The BTREE_DATA_VERSION value is not actually stored in the ** database file. It is a number computed by the pager. But its access ** pattern is the same as header meta values, and so it is convenient to ** read it from this routine. */ SQLITE_PRIVATE void sqlite3BtreeGetMeta(Btree *p, int idx, u32 *pMeta){ BtShared *pBt = p->pBt; sqlite3BtreeEnter(p); assert( p->inTrans>TRANS_NONE ); assert( SQLITE_OK==querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK) ); assert( pBt->pPage1 ); assert( idx>=0 && idx<=15 ); if( idx==BTREE_DATA_VERSION ){ *pMeta = sqlite3PagerDataVersion(pBt->pPager) + p->iDataVersion; }else{ *pMeta = get4byte(&pBt->pPage1->aData[36 + idx*4]); } /* If auto-vacuum is disabled in this build and this is an auto-vacuum ** database, mark the database as read-only. */ #ifdef SQLITE_OMIT_AUTOVACUUM if( idx==BTREE_LARGEST_ROOT_PAGE && *pMeta>0 ){ pBt->btsFlags |= BTS_READ_ONLY; } #endif sqlite3BtreeLeave(p); } /* ** Write meta-information back into the database. Meta[0] is ** read-only and may not be written. */ SQLITE_PRIVATE int sqlite3BtreeUpdateMeta(Btree *p, int idx, u32 iMeta){ BtShared *pBt = p->pBt; unsigned char *pP1; int rc; assert( idx>=1 && idx<=15 ); sqlite3BtreeEnter(p); assert( p->inTrans==TRANS_WRITE ); assert( pBt->pPage1!=0 ); pP1 = pBt->pPage1->aData; rc = sqlite3PagerWrite(pBt->pPage1->pDbPage); if( rc==SQLITE_OK ){ put4byte(&pP1[36 + idx*4], iMeta); #ifndef SQLITE_OMIT_AUTOVACUUM if( idx==BTREE_INCR_VACUUM ){ assert( pBt->autoVacuum || iMeta==0 ); assert( iMeta==0 || iMeta==1 ); pBt->incrVacuum = (u8)iMeta; } #endif } sqlite3BtreeLeave(p); return rc; } #ifndef SQLITE_OMIT_BTREECOUNT /* ** The first argument, pCur, is a cursor opened on some b-tree. Count the ** number of entries in the b-tree and write the result to *pnEntry. ** ** SQLITE_OK is returned if the operation is successfully executed. ** Otherwise, if an error is encountered (i.e. an IO error or database ** corruption) an SQLite error code is returned. */ SQLITE_PRIVATE int sqlite3BtreeCount(BtCursor *pCur, i64 *pnEntry){ i64 nEntry = 0; /* Value to return in *pnEntry */ int rc; /* Return code */ if( pCur->pgnoRoot==0 ){ *pnEntry = 0; return SQLITE_OK; } rc = moveToRoot(pCur); /* Unless an error occurs, the following loop runs one iteration for each ** page in the B-Tree structure (not including overflow pages). */ while( rc==SQLITE_OK ){ int iIdx; /* Index of child node in parent */ MemPage *pPage; /* Current page of the b-tree */ /* If this is a leaf page or the tree is not an int-key tree, then ** this page contains countable entries. Increment the entry counter ** accordingly. */ pPage = pCur->apPage[pCur->iPage]; if( pPage->leaf || !pPage->intKey ){ nEntry += pPage->nCell; } /* pPage is a leaf node. This loop navigates the cursor so that it ** points to the first interior cell that it points to the parent of ** the next page in the tree that has not yet been visited. The ** pCur->aiIdx[pCur->iPage] value is set to the index of the parent cell ** of the page, or to the number of cells in the page if the next page ** to visit is the right-child of its parent. ** ** If all pages in the tree have been visited, return SQLITE_OK to the ** caller. */ if( pPage->leaf ){ do { if( pCur->iPage==0 ){ /* All pages of the b-tree have been visited. Return successfully. */ *pnEntry = nEntry; return moveToRoot(pCur); } moveToParent(pCur); }while ( pCur->aiIdx[pCur->iPage]>=pCur->apPage[pCur->iPage]->nCell ); pCur->aiIdx[pCur->iPage]++; pPage = pCur->apPage[pCur->iPage]; } /* Descend to the child node of the cell that the cursor currently ** points at. This is the right-child if (iIdx==pPage->nCell). */ iIdx = pCur->aiIdx[pCur->iPage]; if( iIdx==pPage->nCell ){ rc = moveToChild(pCur, get4byte(&pPage->aData[pPage->hdrOffset+8])); }else{ rc = moveToChild(pCur, get4byte(findCell(pPage, iIdx))); } } /* An error has occurred. Return an error code. */ return rc; } #endif /* ** Return the pager associated with a BTree. This routine is used for ** testing and debugging only. */ SQLITE_PRIVATE Pager *sqlite3BtreePager(Btree *p){ return p->pBt->pPager; } #ifndef SQLITE_OMIT_INTEGRITY_CHECK /* ** Append a message to the error message string. */ static void checkAppendMsg( IntegrityCk *pCheck, const char *zFormat, ... ){ va_list ap; if( !pCheck->mxErr ) return; pCheck->mxErr--; pCheck->nErr++; va_start(ap, zFormat); if( pCheck->errMsg.nChar ){ sqlite3StrAccumAppend(&pCheck->errMsg, "\n", 1); } if( pCheck->zPfx ){ sqlite3XPrintf(&pCheck->errMsg, pCheck->zPfx, pCheck->v1, pCheck->v2); } sqlite3VXPrintf(&pCheck->errMsg, zFormat, ap); va_end(ap); if( pCheck->errMsg.accError==STRACCUM_NOMEM ){ pCheck->mallocFailed = 1; } } #endif /* SQLITE_OMIT_INTEGRITY_CHECK */ #ifndef SQLITE_OMIT_INTEGRITY_CHECK /* ** Return non-zero if the bit in the IntegrityCk.aPgRef[] array that ** corresponds to page iPg is already set. */ static int getPageReferenced(IntegrityCk *pCheck, Pgno iPg){ assert( iPg<=pCheck->nPage && sizeof(pCheck->aPgRef[0])==1 ); return (pCheck->aPgRef[iPg/8] & (1 << (iPg & 0x07))); } /* ** Set the bit in the IntegrityCk.aPgRef[] array that corresponds to page iPg. */ static void setPageReferenced(IntegrityCk *pCheck, Pgno iPg){ assert( iPg<=pCheck->nPage && sizeof(pCheck->aPgRef[0])==1 ); pCheck->aPgRef[iPg/8] |= (1 << (iPg & 0x07)); } /* ** Add 1 to the reference count for page iPage. If this is the second ** reference to the page, add an error message to pCheck->zErrMsg. ** Return 1 if there are 2 or more references to the page and 0 if ** if this is the first reference to the page. ** ** Also check that the page number is in bounds. */ static int checkRef(IntegrityCk *pCheck, Pgno iPage){ if( iPage==0 ) return 1; if( iPage>pCheck->nPage ){ checkAppendMsg(pCheck, "invalid page number %d", iPage); return 1; } if( getPageReferenced(pCheck, iPage) ){ checkAppendMsg(pCheck, "2nd reference to page %d", iPage); return 1; } setPageReferenced(pCheck, iPage); return 0; } #ifndef SQLITE_OMIT_AUTOVACUUM /* ** Check that the entry in the pointer-map for page iChild maps to ** page iParent, pointer type ptrType. If not, append an error message ** to pCheck. */ static void checkPtrmap( IntegrityCk *pCheck, /* Integrity check context */ Pgno iChild, /* Child page number */ u8 eType, /* Expected pointer map type */ Pgno iParent /* Expected pointer map parent page number */ ){ int rc; u8 ePtrmapType; Pgno iPtrmapParent; rc = ptrmapGet(pCheck->pBt, iChild, &ePtrmapType, &iPtrmapParent); if( rc!=SQLITE_OK ){ if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ) pCheck->mallocFailed = 1; checkAppendMsg(pCheck, "Failed to read ptrmap key=%d", iChild); return; } if( ePtrmapType!=eType || iPtrmapParent!=iParent ){ checkAppendMsg(pCheck, "Bad ptr map entry key=%d expected=(%d,%d) got=(%d,%d)", iChild, eType, iParent, ePtrmapType, iPtrmapParent); } } #endif /* ** Check the integrity of the freelist or of an overflow page list. ** Verify that the number of pages on the list is N. */ static void checkList( IntegrityCk *pCheck, /* Integrity checking context */ int isFreeList, /* True for a freelist. False for overflow page list */ int iPage, /* Page number for first page in the list */ int N /* Expected number of pages in the list */ ){ int i; int expected = N; int iFirst = iPage; while( N-- > 0 && pCheck->mxErr ){ DbPage *pOvflPage; unsigned char *pOvflData; if( iPage<1 ){ checkAppendMsg(pCheck, "%d of %d pages missing from overflow list starting at %d", N+1, expected, iFirst); break; } if( checkRef(pCheck, iPage) ) break; if( sqlite3PagerGet(pCheck->pPager, (Pgno)iPage, &pOvflPage, 0) ){ checkAppendMsg(pCheck, "failed to get page %d", iPage); break; } pOvflData = (unsigned char *)sqlite3PagerGetData(pOvflPage); if( isFreeList ){ int n = get4byte(&pOvflData[4]); #ifndef SQLITE_OMIT_AUTOVACUUM if( pCheck->pBt->autoVacuum ){ checkPtrmap(pCheck, iPage, PTRMAP_FREEPAGE, 0); } #endif if( n>(int)pCheck->pBt->usableSize/4-2 ){ checkAppendMsg(pCheck, "freelist leaf count too big on page %d", iPage); N--; }else{ for(i=0; ipBt->autoVacuum ){ checkPtrmap(pCheck, iFreePage, PTRMAP_FREEPAGE, 0); } #endif checkRef(pCheck, iFreePage); } N -= n; } } #ifndef SQLITE_OMIT_AUTOVACUUM else{ /* If this database supports auto-vacuum and iPage is not the last ** page in this overflow list, check that the pointer-map entry for ** the following page matches iPage. */ if( pCheck->pBt->autoVacuum && N>0 ){ i = get4byte(pOvflData); checkPtrmap(pCheck, i, PTRMAP_OVERFLOW2, iPage); } } #endif iPage = get4byte(pOvflData); sqlite3PagerUnref(pOvflPage); if( isFreeList && N<(iPage!=0) ){ checkAppendMsg(pCheck, "free-page count in header is too small"); } } } #endif /* SQLITE_OMIT_INTEGRITY_CHECK */ /* ** An implementation of a min-heap. ** ** aHeap[0] is the number of elements on the heap. aHeap[1] is the ** root element. The daughter nodes of aHeap[N] are aHeap[N*2] ** and aHeap[N*2+1]. ** ** The heap property is this: Every node is less than or equal to both ** of its daughter nodes. A consequence of the heap property is that the ** root node aHeap[1] is always the minimum value currently in the heap. ** ** The btreeHeapInsert() routine inserts an unsigned 32-bit number onto ** the heap, preserving the heap property. The btreeHeapPull() routine ** removes the root element from the heap (the minimum value in the heap) ** and then moves other nodes around as necessary to preserve the heap ** property. ** ** This heap is used for cell overlap and coverage testing. Each u32 ** entry represents the span of a cell or freeblock on a btree page. ** The upper 16 bits are the index of the first byte of a range and the ** lower 16 bits are the index of the last byte of that range. */ static void btreeHeapInsert(u32 *aHeap, u32 x){ u32 j, i = ++aHeap[0]; aHeap[i] = x; while( (j = i/2)>0 && aHeap[j]>aHeap[i] ){ x = aHeap[j]; aHeap[j] = aHeap[i]; aHeap[i] = x; i = j; } } static int btreeHeapPull(u32 *aHeap, u32 *pOut){ u32 j, i, x; if( (x = aHeap[0])==0 ) return 0; *pOut = aHeap[1]; aHeap[1] = aHeap[x]; aHeap[x] = 0xffffffff; aHeap[0]--; i = 1; while( (j = i*2)<=aHeap[0] ){ if( aHeap[j]>aHeap[j+1] ) j++; if( aHeap[i]zPfx; int saved_v1 = pCheck->v1; int saved_v2 = pCheck->v2; u8 savedIsInit = 0; /* Check that the page exists */ pBt = pCheck->pBt; usableSize = pBt->usableSize; if( iPage==0 ) return 0; if( checkRef(pCheck, iPage) ) return 0; pCheck->zPfx = "Page %d: "; pCheck->v1 = iPage; if( (rc = btreeGetPage(pBt, (Pgno)iPage, &pPage, 0))!=0 ){ checkAppendMsg(pCheck, "unable to get the page. error code=%d", rc); goto end_of_check; } /* Clear MemPage.isInit to make sure the corruption detection code in ** btreeInitPage() is executed. */ savedIsInit = pPage->isInit; pPage->isInit = 0; if( (rc = btreeInitPage(pPage))!=0 ){ assert( rc==SQLITE_CORRUPT ); /* The only possible error from InitPage */ checkAppendMsg(pCheck, "btreeInitPage() returns error code %d", rc); goto end_of_check; } data = pPage->aData; hdr = pPage->hdrOffset; /* Set up for cell analysis */ pCheck->zPfx = "On tree page %d cell %d: "; contentOffset = get2byteNotZero(&data[hdr+5]); assert( contentOffset<=usableSize ); /* Enforced by btreeInitPage() */ /* EVIDENCE-OF: R-37002-32774 The two-byte integer at offset 3 gives the ** number of cells on the page. */ nCell = get2byte(&data[hdr+3]); assert( pPage->nCell==nCell ); /* EVIDENCE-OF: R-23882-45353 The cell pointer array of a b-tree page ** immediately follows the b-tree page header. */ cellStart = hdr + 12 - 4*pPage->leaf; assert( pPage->aCellIdx==&data[cellStart] ); pCellIdx = &data[cellStart + 2*(nCell-1)]; if( !pPage->leaf ){ /* Analyze the right-child page of internal pages */ pgno = get4byte(&data[hdr+8]); #ifndef SQLITE_OMIT_AUTOVACUUM if( pBt->autoVacuum ){ pCheck->zPfx = "On page %d at right child: "; checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage); } #endif depth = checkTreePage(pCheck, pgno, &maxKey, maxKey); keyCanBeEqual = 0; }else{ /* For leaf pages, the coverage check will occur in the same loop ** as the other cell checks, so initialize the heap. */ heap = pCheck->heap; heap[0] = 0; } /* EVIDENCE-OF: R-02776-14802 The cell pointer array consists of K 2-byte ** integer offsets to the cell contents. */ for(i=nCell-1; i>=0 && pCheck->mxErr; i--){ CellInfo info; /* Check cell size */ pCheck->v2 = i; assert( pCellIdx==&data[cellStart + i*2] ); pc = get2byteAligned(pCellIdx); pCellIdx -= 2; if( pcusableSize-4 ){ checkAppendMsg(pCheck, "Offset %d out of range %d..%d", pc, contentOffset, usableSize-4); doCoverageCheck = 0; continue; } pCell = &data[pc]; pPage->xParseCell(pPage, pCell, &info); if( pc+info.nSize>usableSize ){ checkAppendMsg(pCheck, "Extends off end of page"); doCoverageCheck = 0; continue; } /* Check for integer primary key out of range */ if( pPage->intKey ){ if( keyCanBeEqual ? (info.nKey > maxKey) : (info.nKey >= maxKey) ){ checkAppendMsg(pCheck, "Rowid %lld out of order", info.nKey); } maxKey = info.nKey; } /* Check the content overflow list */ if( info.nPayload>info.nLocal ){ int nPage; /* Number of pages on the overflow chain */ Pgno pgnoOvfl; /* First page of the overflow chain */ assert( pc + info.nSize - 4 <= usableSize ); nPage = (info.nPayload - info.nLocal + usableSize - 5)/(usableSize - 4); pgnoOvfl = get4byte(&pCell[info.nSize - 4]); #ifndef SQLITE_OMIT_AUTOVACUUM if( pBt->autoVacuum ){ checkPtrmap(pCheck, pgnoOvfl, PTRMAP_OVERFLOW1, iPage); } #endif checkList(pCheck, 0, pgnoOvfl, nPage); } if( !pPage->leaf ){ /* Check sanity of left child page for internal pages */ pgno = get4byte(pCell); #ifndef SQLITE_OMIT_AUTOVACUUM if( pBt->autoVacuum ){ checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage); } #endif d2 = checkTreePage(pCheck, pgno, &maxKey, maxKey); keyCanBeEqual = 0; if( d2!=depth ){ checkAppendMsg(pCheck, "Child page depth differs"); depth = d2; } }else{ /* Populate the coverage-checking heap for leaf pages */ btreeHeapInsert(heap, (pc<<16)|(pc+info.nSize-1)); } } *piMinKey = maxKey; /* Check for complete coverage of the page */ pCheck->zPfx = 0; if( doCoverageCheck && pCheck->mxErr>0 ){ /* For leaf pages, the min-heap has already been initialized and the ** cells have already been inserted. But for internal pages, that has ** not yet been done, so do it now */ if( !pPage->leaf ){ heap = pCheck->heap; heap[0] = 0; for(i=nCell-1; i>=0; i--){ u32 size; pc = get2byteAligned(&data[cellStart+i*2]); size = pPage->xCellSize(pPage, &data[pc]); btreeHeapInsert(heap, (pc<<16)|(pc+size-1)); } } /* Add the freeblocks to the min-heap ** ** EVIDENCE-OF: R-20690-50594 The second field of the b-tree page header ** is the offset of the first freeblock, or zero if there are no ** freeblocks on the page. */ i = get2byte(&data[hdr+1]); while( i>0 ){ int size, j; assert( (u32)i<=usableSize-4 ); /* Enforced by btreeInitPage() */ size = get2byte(&data[i+2]); assert( (u32)(i+size)<=usableSize ); /* Enforced by btreeInitPage() */ btreeHeapInsert(heap, (((u32)i)<<16)|(i+size-1)); /* EVIDENCE-OF: R-58208-19414 The first 2 bytes of a freeblock are a ** big-endian integer which is the offset in the b-tree page of the next ** freeblock in the chain, or zero if the freeblock is the last on the ** chain. */ j = get2byte(&data[i]); /* EVIDENCE-OF: R-06866-39125 Freeblocks are always connected in order of ** increasing offset. */ assert( j==0 || j>i+size ); /* Enforced by btreeInitPage() */ assert( (u32)j<=usableSize-4 ); /* Enforced by btreeInitPage() */ i = j; } /* Analyze the min-heap looking for overlap between cells and/or ** freeblocks, and counting the number of untracked bytes in nFrag. ** ** Each min-heap entry is of the form: (start_address<<16)|end_address. ** There is an implied first entry the covers the page header, the cell ** pointer index, and the gap between the cell pointer index and the start ** of cell content. ** ** The loop below pulls entries from the min-heap in order and compares ** the start_address against the previous end_address. If there is an ** overlap, that means bytes are used multiple times. If there is a gap, ** that gap is added to the fragmentation count. */ nFrag = 0; prev = contentOffset - 1; /* Implied first min-heap entry */ while( btreeHeapPull(heap,&x) ){ if( (prev&0xffff)>=(x>>16) ){ checkAppendMsg(pCheck, "Multiple uses for byte %u of page %d", x>>16, iPage); break; }else{ nFrag += (x>>16) - (prev&0xffff) - 1; prev = x; } } nFrag += usableSize - (prev&0xffff) - 1; /* EVIDENCE-OF: R-43263-13491 The total number of bytes in all fragments ** is stored in the fifth field of the b-tree page header. ** EVIDENCE-OF: R-07161-27322 The one-byte integer at offset 7 gives the ** number of fragmented free bytes within the cell content area. */ if( heap[0]==0 && nFrag!=data[hdr+7] ){ checkAppendMsg(pCheck, "Fragmentation of %d bytes reported as %d on page %d", nFrag, data[hdr+7], iPage); } } end_of_check: if( !doCoverageCheck ) pPage->isInit = savedIsInit; releasePage(pPage); pCheck->zPfx = saved_zPfx; pCheck->v1 = saved_v1; pCheck->v2 = saved_v2; return depth+1; } #endif /* SQLITE_OMIT_INTEGRITY_CHECK */ #ifndef SQLITE_OMIT_INTEGRITY_CHECK /* ** This routine does a complete check of the given BTree file. aRoot[] is ** an array of pages numbers were each page number is the root page of ** a table. nRoot is the number of entries in aRoot. ** ** A read-only or read-write transaction must be opened before calling ** this function. ** ** Write the number of error seen in *pnErr. Except for some memory ** allocation errors, an error message held in memory obtained from ** malloc is returned if *pnErr is non-zero. If *pnErr==0 then NULL is ** returned. If a memory allocation error occurs, NULL is returned. */ SQLITE_PRIVATE char *sqlite3BtreeIntegrityCheck( Btree *p, /* The btree to be checked */ int *aRoot, /* An array of root pages numbers for individual trees */ int nRoot, /* Number of entries in aRoot[] */ int mxErr, /* Stop reporting errors after this many */ int *pnErr /* Write number of errors seen to this variable */ ){ Pgno i; IntegrityCk sCheck; BtShared *pBt = p->pBt; int savedDbFlags = pBt->db->flags; char zErr[100]; VVA_ONLY( int nRef ); sqlite3BtreeEnter(p); assert( p->inTrans>TRANS_NONE && pBt->inTransaction>TRANS_NONE ); VVA_ONLY( nRef = sqlite3PagerRefcount(pBt->pPager) ); assert( nRef>=0 ); sCheck.pBt = pBt; sCheck.pPager = pBt->pPager; sCheck.nPage = btreePagecount(sCheck.pBt); sCheck.mxErr = mxErr; sCheck.nErr = 0; sCheck.mallocFailed = 0; sCheck.zPfx = 0; sCheck.v1 = 0; sCheck.v2 = 0; sCheck.aPgRef = 0; sCheck.heap = 0; sqlite3StrAccumInit(&sCheck.errMsg, 0, zErr, sizeof(zErr), SQLITE_MAX_LENGTH); sCheck.errMsg.printfFlags = SQLITE_PRINTF_INTERNAL; if( sCheck.nPage==0 ){ goto integrity_ck_cleanup; } sCheck.aPgRef = sqlite3MallocZero((sCheck.nPage / 8)+ 1); if( !sCheck.aPgRef ){ sCheck.mallocFailed = 1; goto integrity_ck_cleanup; } sCheck.heap = (u32*)sqlite3PageMalloc( pBt->pageSize ); if( sCheck.heap==0 ){ sCheck.mallocFailed = 1; goto integrity_ck_cleanup; } i = PENDING_BYTE_PAGE(pBt); if( i<=sCheck.nPage ) setPageReferenced(&sCheck, i); /* Check the integrity of the freelist */ sCheck.zPfx = "Main freelist: "; checkList(&sCheck, 1, get4byte(&pBt->pPage1->aData[32]), get4byte(&pBt->pPage1->aData[36])); sCheck.zPfx = 0; /* Check all the tables. */ testcase( pBt->db->flags & SQLITE_CellSizeCk ); pBt->db->flags &= ~SQLITE_CellSizeCk; for(i=0; (int)iautoVacuum && aRoot[i]>1 ){ checkPtrmap(&sCheck, aRoot[i], PTRMAP_ROOTPAGE, 0); } #endif checkTreePage(&sCheck, aRoot[i], ¬Used, LARGEST_INT64); } pBt->db->flags = savedDbFlags; /* Make sure every page in the file is referenced */ for(i=1; i<=sCheck.nPage && sCheck.mxErr; i++){ #ifdef SQLITE_OMIT_AUTOVACUUM if( getPageReferenced(&sCheck, i)==0 ){ checkAppendMsg(&sCheck, "Page %d is never used", i); } #else /* If the database supports auto-vacuum, make sure no tables contain ** references to pointer-map pages. */ if( getPageReferenced(&sCheck, i)==0 && (PTRMAP_PAGENO(pBt, i)!=i || !pBt->autoVacuum) ){ checkAppendMsg(&sCheck, "Page %d is never used", i); } if( getPageReferenced(&sCheck, i)!=0 && (PTRMAP_PAGENO(pBt, i)==i && pBt->autoVacuum) ){ checkAppendMsg(&sCheck, "Pointer map page %d is referenced", i); } #endif } /* Clean up and report errors. */ integrity_ck_cleanup: sqlite3PageFree(sCheck.heap); sqlite3_free(sCheck.aPgRef); if( sCheck.mallocFailed ){ sqlite3StrAccumReset(&sCheck.errMsg); sCheck.nErr++; } *pnErr = sCheck.nErr; if( sCheck.nErr==0 ) sqlite3StrAccumReset(&sCheck.errMsg); /* Make sure this analysis did not leave any unref() pages. */ assert( nRef==sqlite3PagerRefcount(pBt->pPager) ); sqlite3BtreeLeave(p); return sqlite3StrAccumFinish(&sCheck.errMsg); } #endif /* SQLITE_OMIT_INTEGRITY_CHECK */ /* ** Return the full pathname of the underlying database file. Return ** an empty string if the database is in-memory or a TEMP database. ** ** The pager filename is invariant as long as the pager is ** open so it is safe to access without the BtShared mutex. */ SQLITE_PRIVATE const char *sqlite3BtreeGetFilename(Btree *p){ assert( p->pBt->pPager!=0 ); return sqlite3PagerFilename(p->pBt->pPager, 1); } /* ** Return the pathname of the journal file for this database. The return ** value of this routine is the same regardless of whether the journal file ** has been created or not. ** ** The pager journal filename is invariant as long as the pager is ** open so it is safe to access without the BtShared mutex. */ SQLITE_PRIVATE const char *sqlite3BtreeGetJournalname(Btree *p){ assert( p->pBt->pPager!=0 ); return sqlite3PagerJournalname(p->pBt->pPager); } /* ** Return non-zero if a transaction is active. */ SQLITE_PRIVATE int sqlite3BtreeIsInTrans(Btree *p){ assert( p==0 || sqlite3_mutex_held(p->db->mutex) ); return (p && (p->inTrans==TRANS_WRITE)); } #ifndef SQLITE_OMIT_WAL /* ** Run a checkpoint on the Btree passed as the first argument. ** ** Return SQLITE_LOCKED if this or any other connection has an open ** transaction on the shared-cache the argument Btree is connected to. ** ** Parameter eMode is one of SQLITE_CHECKPOINT_PASSIVE, FULL or RESTART. */ SQLITE_PRIVATE int sqlite3BtreeCheckpoint(Btree *p, int eMode, int *pnLog, int *pnCkpt){ int rc = SQLITE_OK; if( p ){ BtShared *pBt = p->pBt; sqlite3BtreeEnter(p); if( pBt->inTransaction!=TRANS_NONE ){ rc = SQLITE_LOCKED; }else{ rc = sqlite3PagerCheckpoint(pBt->pPager, eMode, pnLog, pnCkpt); } sqlite3BtreeLeave(p); } return rc; } #endif /* ** Return non-zero if a read (or write) transaction is active. */ SQLITE_PRIVATE int sqlite3BtreeIsInReadTrans(Btree *p){ assert( p ); assert( sqlite3_mutex_held(p->db->mutex) ); return p->inTrans!=TRANS_NONE; } SQLITE_PRIVATE int sqlite3BtreeIsInBackup(Btree *p){ assert( p ); assert( sqlite3_mutex_held(p->db->mutex) ); return p->nBackup!=0; } /* ** This function returns a pointer to a blob of memory associated with ** a single shared-btree. The memory is used by client code for its own ** purposes (for example, to store a high-level schema associated with ** the shared-btree). The btree layer manages reference counting issues. ** ** The first time this is called on a shared-btree, nBytes bytes of memory ** are allocated, zeroed, and returned to the caller. For each subsequent ** call the nBytes parameter is ignored and a pointer to the same blob ** of memory returned. ** ** If the nBytes parameter is 0 and the blob of memory has not yet been ** allocated, a null pointer is returned. If the blob has already been ** allocated, it is returned as normal. ** ** Just before the shared-btree is closed, the function passed as the ** xFree argument when the memory allocation was made is invoked on the ** blob of allocated memory. The xFree function should not call sqlite3_free() ** on the memory, the btree layer does that. */ SQLITE_PRIVATE void *sqlite3BtreeSchema(Btree *p, int nBytes, void(*xFree)(void *)){ BtShared *pBt = p->pBt; sqlite3BtreeEnter(p); if( !pBt->pSchema && nBytes ){ pBt->pSchema = sqlite3DbMallocZero(0, nBytes); pBt->xFreeSchema = xFree; } sqlite3BtreeLeave(p); return pBt->pSchema; } /* ** Return SQLITE_LOCKED_SHAREDCACHE if another user of the same shared ** btree as the argument handle holds an exclusive lock on the ** sqlite_master table. Otherwise SQLITE_OK. */ SQLITE_PRIVATE int sqlite3BtreeSchemaLocked(Btree *p){ int rc; assert( sqlite3_mutex_held(p->db->mutex) ); sqlite3BtreeEnter(p); rc = querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK); assert( rc==SQLITE_OK || rc==SQLITE_LOCKED_SHAREDCACHE ); sqlite3BtreeLeave(p); return rc; } #ifndef SQLITE_OMIT_SHARED_CACHE /* ** Obtain a lock on the table whose root page is iTab. The ** lock is a write lock if isWritelock is true or a read lock ** if it is false. */ SQLITE_PRIVATE int sqlite3BtreeLockTable(Btree *p, int iTab, u8 isWriteLock){ int rc = SQLITE_OK; assert( p->inTrans!=TRANS_NONE ); if( p->sharable ){ u8 lockType = READ_LOCK + isWriteLock; assert( READ_LOCK+1==WRITE_LOCK ); assert( isWriteLock==0 || isWriteLock==1 ); sqlite3BtreeEnter(p); rc = querySharedCacheTableLock(p, iTab, lockType); if( rc==SQLITE_OK ){ rc = setSharedCacheTableLock(p, iTab, lockType); } sqlite3BtreeLeave(p); } return rc; } #endif #ifndef SQLITE_OMIT_INCRBLOB /* ** Argument pCsr must be a cursor opened for writing on an ** INTKEY table currently pointing at a valid table entry. ** This function modifies the data stored as part of that entry. ** ** Only the data content may only be modified, it is not possible to ** change the length of the data stored. If this function is called with ** parameters that attempt to write past the end of the existing data, ** no modifications are made and SQLITE_CORRUPT is returned. */ SQLITE_PRIVATE int sqlite3BtreePutData(BtCursor *pCsr, u32 offset, u32 amt, void *z){ int rc; assert( cursorOwnsBtShared(pCsr) ); assert( sqlite3_mutex_held(pCsr->pBtree->db->mutex) ); assert( pCsr->curFlags & BTCF_Incrblob ); rc = restoreCursorPosition(pCsr); if( rc!=SQLITE_OK ){ return rc; } assert( pCsr->eState!=CURSOR_REQUIRESEEK ); if( pCsr->eState!=CURSOR_VALID ){ return SQLITE_ABORT; } /* Save the positions of all other cursors open on this table. This is ** required in case any of them are holding references to an xFetch ** version of the b-tree page modified by the accessPayload call below. ** ** Note that pCsr must be open on a INTKEY table and saveCursorPosition() ** and hence saveAllCursors() cannot fail on a BTREE_INTKEY table, hence ** saveAllCursors can only return SQLITE_OK. */ VVA_ONLY(rc =) saveAllCursors(pCsr->pBt, pCsr->pgnoRoot, pCsr); assert( rc==SQLITE_OK ); /* Check some assumptions: ** (a) the cursor is open for writing, ** (b) there is a read/write transaction open, ** (c) the connection holds a write-lock on the table (if required), ** (d) there are no conflicting read-locks, and ** (e) the cursor points at a valid row of an intKey table. */ if( (pCsr->curFlags & BTCF_WriteFlag)==0 ){ return SQLITE_READONLY; } assert( (pCsr->pBt->btsFlags & BTS_READ_ONLY)==0 && pCsr->pBt->inTransaction==TRANS_WRITE ); assert( hasSharedCacheTableLock(pCsr->pBtree, pCsr->pgnoRoot, 0, 2) ); assert( !hasReadConflicts(pCsr->pBtree, pCsr->pgnoRoot) ); assert( pCsr->apPage[pCsr->iPage]->intKey ); return accessPayload(pCsr, offset, amt, (unsigned char *)z, 1); } /* ** Mark this cursor as an incremental blob cursor. */ SQLITE_PRIVATE void sqlite3BtreeIncrblobCursor(BtCursor *pCur){ pCur->curFlags |= BTCF_Incrblob; pCur->pBtree->hasIncrblobCur = 1; } #endif /* ** Set both the "read version" (single byte at byte offset 18) and ** "write version" (single byte at byte offset 19) fields in the database ** header to iVersion. */ SQLITE_PRIVATE int sqlite3BtreeSetVersion(Btree *pBtree, int iVersion){ BtShared *pBt = pBtree->pBt; int rc; /* Return code */ assert( iVersion==1 || iVersion==2 ); /* If setting the version fields to 1, do not automatically open the ** WAL connection, even if the version fields are currently set to 2. */ pBt->btsFlags &= ~BTS_NO_WAL; if( iVersion==1 ) pBt->btsFlags |= BTS_NO_WAL; rc = sqlite3BtreeBeginTrans(pBtree, 0); if( rc==SQLITE_OK ){ u8 *aData = pBt->pPage1->aData; if( aData[18]!=(u8)iVersion || aData[19]!=(u8)iVersion ){ rc = sqlite3BtreeBeginTrans(pBtree, 2); if( rc==SQLITE_OK ){ rc = sqlite3PagerWrite(pBt->pPage1->pDbPage); if( rc==SQLITE_OK ){ aData[18] = (u8)iVersion; aData[19] = (u8)iVersion; } } } } pBt->btsFlags &= ~BTS_NO_WAL; return rc; } /* ** Return true if the cursor has a hint specified. This routine is ** only used from within assert() statements */ SQLITE_PRIVATE int sqlite3BtreeCursorHasHint(BtCursor *pCsr, unsigned int mask){ return (pCsr->hints & mask)!=0; } /* ** Return true if the given Btree is read-only. */ SQLITE_PRIVATE int sqlite3BtreeIsReadonly(Btree *p){ return (p->pBt->btsFlags & BTS_READ_ONLY)!=0; } /* ** Return the size of the header added to each page by this module. */ SQLITE_PRIVATE int sqlite3HeaderSizeBtree(void){ return ROUND8(sizeof(MemPage)); } #if !defined(SQLITE_OMIT_SHARED_CACHE) /* ** Return true if the Btree passed as the only argument is sharable. */ SQLITE_PRIVATE int sqlite3BtreeSharable(Btree *p){ return p->sharable; } /* ** Return the number of connections to the BtShared object accessed by ** the Btree handle passed as the only argument. For private caches ** this is always 1. For shared caches it may be 1 or greater. */ SQLITE_PRIVATE int sqlite3BtreeConnectionCount(Btree *p){ testcase( p->sharable ); return p->pBt->nRef; } #endif /************** End of btree.c ***********************************************/ /************** Begin file backup.c ******************************************/ /* ** 2009 January 28 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ************************************************************************* ** This file contains the implementation of the sqlite3_backup_XXX() ** API functions and the related features. */ /* #include "sqliteInt.h" */ /* #include "btreeInt.h" */ /* ** Structure allocated for each backup operation. */ struct sqlite3_backup { sqlite3* pDestDb; /* Destination database handle */ Btree *pDest; /* Destination b-tree file */ u32 iDestSchema; /* Original schema cookie in destination */ int bDestLocked; /* True once a write-transaction is open on pDest */ Pgno iNext; /* Page number of the next source page to copy */ sqlite3* pSrcDb; /* Source database handle */ Btree *pSrc; /* Source b-tree file */ int rc; /* Backup process error code */ /* These two variables are set by every call to backup_step(). They are ** read by calls to backup_remaining() and backup_pagecount(). */ Pgno nRemaining; /* Number of pages left to copy */ Pgno nPagecount; /* Total number of pages to copy */ int isAttached; /* True once backup has been registered with pager */ sqlite3_backup *pNext; /* Next backup associated with source pager */ }; /* ** THREAD SAFETY NOTES: ** ** Once it has been created using backup_init(), a single sqlite3_backup ** structure may be accessed via two groups of thread-safe entry points: ** ** * Via the sqlite3_backup_XXX() API function backup_step() and ** backup_finish(). Both these functions obtain the source database ** handle mutex and the mutex associated with the source BtShared ** structure, in that order. ** ** * Via the BackupUpdate() and BackupRestart() functions, which are ** invoked by the pager layer to report various state changes in ** the page cache associated with the source database. The mutex ** associated with the source database BtShared structure will always ** be held when either of these functions are invoked. ** ** The other sqlite3_backup_XXX() API functions, backup_remaining() and ** backup_pagecount() are not thread-safe functions. If they are called ** while some other thread is calling backup_step() or backup_finish(), ** the values returned may be invalid. There is no way for a call to ** BackupUpdate() or BackupRestart() to interfere with backup_remaining() ** or backup_pagecount(). ** ** Depending on the SQLite configuration, the database handles and/or ** the Btree objects may have their own mutexes that require locking. ** Non-sharable Btrees (in-memory databases for example), do not have ** associated mutexes. */ /* ** Return a pointer corresponding to database zDb (i.e. "main", "temp") ** in connection handle pDb. If such a database cannot be found, return ** a NULL pointer and write an error message to pErrorDb. ** ** If the "temp" database is requested, it may need to be opened by this ** function. If an error occurs while doing so, return 0 and write an ** error message to pErrorDb. */ static Btree *findBtree(sqlite3 *pErrorDb, sqlite3 *pDb, const char *zDb){ int i = sqlite3FindDbName(pDb, zDb); if( i==1 ){ Parse sParse; int rc = 0; memset(&sParse, 0, sizeof(sParse)); sParse.db = pDb; if( sqlite3OpenTempDatabase(&sParse) ){ sqlite3ErrorWithMsg(pErrorDb, sParse.rc, "%s", sParse.zErrMsg); rc = SQLITE_ERROR; } sqlite3DbFree(pErrorDb, sParse.zErrMsg); sqlite3ParserReset(&sParse); if( rc ){ return 0; } } if( i<0 ){ sqlite3ErrorWithMsg(pErrorDb, SQLITE_ERROR, "unknown database %s", zDb); return 0; } return pDb->aDb[i].pBt; } /* ** Attempt to set the page size of the destination to match the page size ** of the source. */ static int setDestPgsz(sqlite3_backup *p){ int rc; rc = sqlite3BtreeSetPageSize(p->pDest,sqlite3BtreeGetPageSize(p->pSrc),-1,0); return rc; } /* ** Check that there is no open read-transaction on the b-tree passed as the ** second argument. If there is not, return SQLITE_OK. Otherwise, if there ** is an open read-transaction, return SQLITE_ERROR and leave an error ** message in database handle db. */ static int checkReadTransaction(sqlite3 *db, Btree *p){ if( sqlite3BtreeIsInReadTrans(p) ){ sqlite3ErrorWithMsg(db, SQLITE_ERROR, "destination database is in use"); return SQLITE_ERROR; } return SQLITE_OK; } /* ** Create an sqlite3_backup process to copy the contents of zSrcDb from ** connection handle pSrcDb to zDestDb in pDestDb. If successful, return ** a pointer to the new sqlite3_backup object. ** ** If an error occurs, NULL is returned and an error code and error message ** stored in database handle pDestDb. */ SQLITE_API sqlite3_backup *sqlite3_backup_init( sqlite3* pDestDb, /* Database to write to */ const char *zDestDb, /* Name of database within pDestDb */ sqlite3* pSrcDb, /* Database connection to read from */ const char *zSrcDb /* Name of database within pSrcDb */ ){ sqlite3_backup *p; /* Value to return */ #ifdef SQLITE_ENABLE_API_ARMOR if( !sqlite3SafetyCheckOk(pSrcDb)||!sqlite3SafetyCheckOk(pDestDb) ){ (void)SQLITE_MISUSE_BKPT; return 0; } #endif /* Lock the source database handle. The destination database ** handle is not locked in this routine, but it is locked in ** sqlite3_backup_step(). The user is required to ensure that no ** other thread accesses the destination handle for the duration ** of the backup operation. Any attempt to use the destination ** database connection while a backup is in progress may cause ** a malfunction or a deadlock. */ sqlite3_mutex_enter(pSrcDb->mutex); sqlite3_mutex_enter(pDestDb->mutex); if( pSrcDb==pDestDb ){ sqlite3ErrorWithMsg( pDestDb, SQLITE_ERROR, "source and destination must be distinct" ); p = 0; }else { /* Allocate space for a new sqlite3_backup object... ** EVIDENCE-OF: R-64852-21591 The sqlite3_backup object is created by a ** call to sqlite3_backup_init() and is destroyed by a call to ** sqlite3_backup_finish(). */ p = (sqlite3_backup *)sqlite3MallocZero(sizeof(sqlite3_backup)); if( !p ){ sqlite3Error(pDestDb, SQLITE_NOMEM_BKPT); } } /* If the allocation succeeded, populate the new object. */ if( p ){ p->pSrc = findBtree(pDestDb, pSrcDb, zSrcDb); p->pDest = findBtree(pDestDb, pDestDb, zDestDb); p->pDestDb = pDestDb; p->pSrcDb = pSrcDb; p->iNext = 1; p->isAttached = 0; if( 0==p->pSrc || 0==p->pDest || checkReadTransaction(pDestDb, p->pDest)!=SQLITE_OK ){ /* One (or both) of the named databases did not exist or an OOM ** error was hit. Or there is a transaction open on the destination ** database. The error has already been written into the pDestDb ** handle. All that is left to do here is free the sqlite3_backup ** structure. */ sqlite3_free(p); p = 0; } } if( p ){ p->pSrc->nBackup++; } sqlite3_mutex_leave(pDestDb->mutex); sqlite3_mutex_leave(pSrcDb->mutex); return p; } /* ** Argument rc is an SQLite error code. Return true if this error is ** considered fatal if encountered during a backup operation. All errors ** are considered fatal except for SQLITE_BUSY and SQLITE_LOCKED. */ static int isFatalError(int rc){ return (rc!=SQLITE_OK && rc!=SQLITE_BUSY && ALWAYS(rc!=SQLITE_LOCKED)); } /* ** Parameter zSrcData points to a buffer containing the data for ** page iSrcPg from the source database. Copy this data into the ** destination database. */ static int backupOnePage( sqlite3_backup *p, /* Backup handle */ Pgno iSrcPg, /* Source database page to backup */ const u8 *zSrcData, /* Source database page data */ int bUpdate /* True for an update, false otherwise */ ){ Pager * const pDestPager = sqlite3BtreePager(p->pDest); const int nSrcPgsz = sqlite3BtreeGetPageSize(p->pSrc); int nDestPgsz = sqlite3BtreeGetPageSize(p->pDest); const int nCopy = MIN(nSrcPgsz, nDestPgsz); const i64 iEnd = (i64)iSrcPg*(i64)nSrcPgsz; #ifdef SQLITE_HAS_CODEC /* Use BtreeGetReserveNoMutex() for the source b-tree, as although it is ** guaranteed that the shared-mutex is held by this thread, handle ** p->pSrc may not actually be the owner. */ int nSrcReserve = sqlite3BtreeGetReserveNoMutex(p->pSrc); int nDestReserve = sqlite3BtreeGetOptimalReserve(p->pDest); #endif int rc = SQLITE_OK; i64 iOff; assert( sqlite3BtreeGetReserveNoMutex(p->pSrc)>=0 ); assert( p->bDestLocked ); assert( !isFatalError(p->rc) ); assert( iSrcPg!=PENDING_BYTE_PAGE(p->pSrc->pBt) ); assert( zSrcData ); /* Catch the case where the destination is an in-memory database and the ** page sizes of the source and destination differ. */ if( nSrcPgsz!=nDestPgsz && sqlite3PagerIsMemdb(pDestPager) ){ rc = SQLITE_READONLY; } #ifdef SQLITE_HAS_CODEC /* Backup is not possible if the page size of the destination is changing ** and a codec is in use. */ if( nSrcPgsz!=nDestPgsz && sqlite3PagerGetCodec(pDestPager)!=0 ){ rc = SQLITE_READONLY; } /* Backup is not possible if the number of bytes of reserve space differ ** between source and destination. If there is a difference, try to ** fix the destination to agree with the source. If that is not possible, ** then the backup cannot proceed. */ if( nSrcReserve!=nDestReserve ){ u32 newPgsz = nSrcPgsz; rc = sqlite3PagerSetPagesize(pDestPager, &newPgsz, nSrcReserve); if( rc==SQLITE_OK && newPgsz!=nSrcPgsz ) rc = SQLITE_READONLY; } #endif /* This loop runs once for each destination page spanned by the source ** page. For each iteration, variable iOff is set to the byte offset ** of the destination page. */ for(iOff=iEnd-(i64)nSrcPgsz; rc==SQLITE_OK && iOffpDest->pBt) ) continue; if( SQLITE_OK==(rc = sqlite3PagerGet(pDestPager, iDest, &pDestPg, 0)) && SQLITE_OK==(rc = sqlite3PagerWrite(pDestPg)) ){ const u8 *zIn = &zSrcData[iOff%nSrcPgsz]; u8 *zDestData = sqlite3PagerGetData(pDestPg); u8 *zOut = &zDestData[iOff%nDestPgsz]; /* Copy the data from the source page into the destination page. ** Then clear the Btree layer MemPage.isInit flag. Both this module ** and the pager code use this trick (clearing the first byte ** of the page 'extra' space to invalidate the Btree layers ** cached parse of the page). MemPage.isInit is marked ** "MUST BE FIRST" for this purpose. */ memcpy(zOut, zIn, nCopy); ((u8 *)sqlite3PagerGetExtra(pDestPg))[0] = 0; if( iOff==0 && bUpdate==0 ){ sqlite3Put4byte(&zOut[28], sqlite3BtreeLastPage(p->pSrc)); } } sqlite3PagerUnref(pDestPg); } return rc; } /* ** If pFile is currently larger than iSize bytes, then truncate it to ** exactly iSize bytes. If pFile is not larger than iSize bytes, then ** this function is a no-op. ** ** Return SQLITE_OK if everything is successful, or an SQLite error ** code if an error occurs. */ static int backupTruncateFile(sqlite3_file *pFile, i64 iSize){ i64 iCurrent; int rc = sqlite3OsFileSize(pFile, &iCurrent); if( rc==SQLITE_OK && iCurrent>iSize ){ rc = sqlite3OsTruncate(pFile, iSize); } return rc; } /* ** Register this backup object with the associated source pager for ** callbacks when pages are changed or the cache invalidated. */ static void attachBackupObject(sqlite3_backup *p){ sqlite3_backup **pp; assert( sqlite3BtreeHoldsMutex(p->pSrc) ); pp = sqlite3PagerBackupPtr(sqlite3BtreePager(p->pSrc)); p->pNext = *pp; *pp = p; p->isAttached = 1; } /* ** Copy nPage pages from the source b-tree to the destination. */ SQLITE_API int sqlite3_backup_step(sqlite3_backup *p, int nPage){ int rc; int destMode; /* Destination journal mode */ int pgszSrc = 0; /* Source page size */ int pgszDest = 0; /* Destination page size */ #ifdef SQLITE_ENABLE_API_ARMOR if( p==0 ) return SQLITE_MISUSE_BKPT; #endif sqlite3_mutex_enter(p->pSrcDb->mutex); sqlite3BtreeEnter(p->pSrc); if( p->pDestDb ){ sqlite3_mutex_enter(p->pDestDb->mutex); } rc = p->rc; if( !isFatalError(rc) ){ Pager * const pSrcPager = sqlite3BtreePager(p->pSrc); /* Source pager */ Pager * const pDestPager = sqlite3BtreePager(p->pDest); /* Dest pager */ int ii; /* Iterator variable */ int nSrcPage = -1; /* Size of source db in pages */ int bCloseTrans = 0; /* True if src db requires unlocking */ /* If the source pager is currently in a write-transaction, return ** SQLITE_BUSY immediately. */ if( p->pDestDb && p->pSrc->pBt->inTransaction==TRANS_WRITE ){ rc = SQLITE_BUSY; }else{ rc = SQLITE_OK; } /* If there is no open read-transaction on the source database, open ** one now. If a transaction is opened here, then it will be closed ** before this function exits. */ if( rc==SQLITE_OK && 0==sqlite3BtreeIsInReadTrans(p->pSrc) ){ rc = sqlite3BtreeBeginTrans(p->pSrc, 0); bCloseTrans = 1; } /* If the destination database has not yet been locked (i.e. if this ** is the first call to backup_step() for the current backup operation), ** try to set its page size to the same as the source database. This ** is especially important on ZipVFS systems, as in that case it is ** not possible to create a database file that uses one page size by ** writing to it with another. */ if( p->bDestLocked==0 && rc==SQLITE_OK && setDestPgsz(p)==SQLITE_NOMEM ){ rc = SQLITE_NOMEM; } /* Lock the destination database, if it is not locked already. */ if( SQLITE_OK==rc && p->bDestLocked==0 && SQLITE_OK==(rc = sqlite3BtreeBeginTrans(p->pDest, 2)) ){ p->bDestLocked = 1; sqlite3BtreeGetMeta(p->pDest, BTREE_SCHEMA_VERSION, &p->iDestSchema); } /* Do not allow backup if the destination database is in WAL mode ** and the page sizes are different between source and destination */ pgszSrc = sqlite3BtreeGetPageSize(p->pSrc); pgszDest = sqlite3BtreeGetPageSize(p->pDest); destMode = sqlite3PagerGetJournalMode(sqlite3BtreePager(p->pDest)); if( SQLITE_OK==rc && destMode==PAGER_JOURNALMODE_WAL && pgszSrc!=pgszDest ){ rc = SQLITE_READONLY; } /* Now that there is a read-lock on the source database, query the ** source pager for the number of pages in the database. */ nSrcPage = (int)sqlite3BtreeLastPage(p->pSrc); assert( nSrcPage>=0 ); for(ii=0; (nPage<0 || iiiNext<=(Pgno)nSrcPage && !rc; ii++){ const Pgno iSrcPg = p->iNext; /* Source page number */ if( iSrcPg!=PENDING_BYTE_PAGE(p->pSrc->pBt) ){ DbPage *pSrcPg; /* Source page object */ rc = sqlite3PagerGet(pSrcPager, iSrcPg, &pSrcPg,PAGER_GET_READONLY); if( rc==SQLITE_OK ){ rc = backupOnePage(p, iSrcPg, sqlite3PagerGetData(pSrcPg), 0); sqlite3PagerUnref(pSrcPg); } } p->iNext++; } if( rc==SQLITE_OK ){ p->nPagecount = nSrcPage; p->nRemaining = nSrcPage+1-p->iNext; if( p->iNext>(Pgno)nSrcPage ){ rc = SQLITE_DONE; }else if( !p->isAttached ){ attachBackupObject(p); } } /* Update the schema version field in the destination database. This ** is to make sure that the schema-version really does change in ** the case where the source and destination databases have the ** same schema version. */ if( rc==SQLITE_DONE ){ if( nSrcPage==0 ){ rc = sqlite3BtreeNewDb(p->pDest); nSrcPage = 1; } if( rc==SQLITE_OK || rc==SQLITE_DONE ){ rc = sqlite3BtreeUpdateMeta(p->pDest,1,p->iDestSchema+1); } if( rc==SQLITE_OK ){ if( p->pDestDb ){ sqlite3ResetAllSchemasOfConnection(p->pDestDb); } if( destMode==PAGER_JOURNALMODE_WAL ){ rc = sqlite3BtreeSetVersion(p->pDest, 2); } } if( rc==SQLITE_OK ){ int nDestTruncate; /* Set nDestTruncate to the final number of pages in the destination ** database. The complication here is that the destination page ** size may be different to the source page size. ** ** If the source page size is smaller than the destination page size, ** round up. In this case the call to sqlite3OsTruncate() below will ** fix the size of the file. However it is important to call ** sqlite3PagerTruncateImage() here so that any pages in the ** destination file that lie beyond the nDestTruncate page mark are ** journalled by PagerCommitPhaseOne() before they are destroyed ** by the file truncation. */ assert( pgszSrc==sqlite3BtreeGetPageSize(p->pSrc) ); assert( pgszDest==sqlite3BtreeGetPageSize(p->pDest) ); if( pgszSrcpDest->pBt) ){ nDestTruncate--; } }else{ nDestTruncate = nSrcPage * (pgszSrc/pgszDest); } assert( nDestTruncate>0 ); if( pgszSrc= iSize || ( nDestTruncate==(int)(PENDING_BYTE_PAGE(p->pDest->pBt)-1) && iSize>=PENDING_BYTE && iSize<=PENDING_BYTE+pgszDest )); /* This block ensures that all data required to recreate the original ** database has been stored in the journal for pDestPager and the ** journal synced to disk. So at this point we may safely modify ** the database file in any way, knowing that if a power failure ** occurs, the original database will be reconstructed from the ** journal file. */ sqlite3PagerPagecount(pDestPager, &nDstPage); for(iPg=nDestTruncate; rc==SQLITE_OK && iPg<=(Pgno)nDstPage; iPg++){ if( iPg!=PENDING_BYTE_PAGE(p->pDest->pBt) ){ DbPage *pPg; rc = sqlite3PagerGet(pDestPager, iPg, &pPg, 0); if( rc==SQLITE_OK ){ rc = sqlite3PagerWrite(pPg); sqlite3PagerUnref(pPg); } } } if( rc==SQLITE_OK ){ rc = sqlite3PagerCommitPhaseOne(pDestPager, 0, 1); } /* Write the extra pages and truncate the database file as required */ iEnd = MIN(PENDING_BYTE + pgszDest, iSize); for( iOff=PENDING_BYTE+pgszSrc; rc==SQLITE_OK && iOffpDest, 0)) ){ rc = SQLITE_DONE; } } } /* If bCloseTrans is true, then this function opened a read transaction ** on the source database. Close the read transaction here. There is ** no need to check the return values of the btree methods here, as ** "committing" a read-only transaction cannot fail. */ if( bCloseTrans ){ TESTONLY( int rc2 ); TESTONLY( rc2 = ) sqlite3BtreeCommitPhaseOne(p->pSrc, 0); TESTONLY( rc2 |= ) sqlite3BtreeCommitPhaseTwo(p->pSrc, 0); assert( rc2==SQLITE_OK ); } if( rc==SQLITE_IOERR_NOMEM ){ rc = SQLITE_NOMEM_BKPT; } p->rc = rc; } if( p->pDestDb ){ sqlite3_mutex_leave(p->pDestDb->mutex); } sqlite3BtreeLeave(p->pSrc); sqlite3_mutex_leave(p->pSrcDb->mutex); return rc; } /* ** Release all resources associated with an sqlite3_backup* handle. */ SQLITE_API int sqlite3_backup_finish(sqlite3_backup *p){ sqlite3_backup **pp; /* Ptr to head of pagers backup list */ sqlite3 *pSrcDb; /* Source database connection */ int rc; /* Value to return */ /* Enter the mutexes */ if( p==0 ) return SQLITE_OK; pSrcDb = p->pSrcDb; sqlite3_mutex_enter(pSrcDb->mutex); sqlite3BtreeEnter(p->pSrc); if( p->pDestDb ){ sqlite3_mutex_enter(p->pDestDb->mutex); } /* Detach this backup from the source pager. */ if( p->pDestDb ){ p->pSrc->nBackup--; } if( p->isAttached ){ pp = sqlite3PagerBackupPtr(sqlite3BtreePager(p->pSrc)); while( *pp!=p ){ pp = &(*pp)->pNext; } *pp = p->pNext; } /* If a transaction is still open on the Btree, roll it back. */ sqlite3BtreeRollback(p->pDest, SQLITE_OK, 0); /* Set the error code of the destination database handle. */ rc = (p->rc==SQLITE_DONE) ? SQLITE_OK : p->rc; if( p->pDestDb ){ sqlite3Error(p->pDestDb, rc); /* Exit the mutexes and free the backup context structure. */ sqlite3LeaveMutexAndCloseZombie(p->pDestDb); } sqlite3BtreeLeave(p->pSrc); if( p->pDestDb ){ /* EVIDENCE-OF: R-64852-21591 The sqlite3_backup object is created by a ** call to sqlite3_backup_init() and is destroyed by a call to ** sqlite3_backup_finish(). */ sqlite3_free(p); } sqlite3LeaveMutexAndCloseZombie(pSrcDb); return rc; } /* ** Return the number of pages still to be backed up as of the most recent ** call to sqlite3_backup_step(). */ SQLITE_API int sqlite3_backup_remaining(sqlite3_backup *p){ #ifdef SQLITE_ENABLE_API_ARMOR if( p==0 ){ (void)SQLITE_MISUSE_BKPT; return 0; } #endif return p->nRemaining; } /* ** Return the total number of pages in the source database as of the most ** recent call to sqlite3_backup_step(). */ SQLITE_API int sqlite3_backup_pagecount(sqlite3_backup *p){ #ifdef SQLITE_ENABLE_API_ARMOR if( p==0 ){ (void)SQLITE_MISUSE_BKPT; return 0; } #endif return p->nPagecount; } /* ** This function is called after the contents of page iPage of the ** source database have been modified. If page iPage has already been ** copied into the destination database, then the data written to the ** destination is now invalidated. The destination copy of iPage needs ** to be updated with the new data before the backup operation is ** complete. ** ** It is assumed that the mutex associated with the BtShared object ** corresponding to the source database is held when this function is ** called. */ static SQLITE_NOINLINE void backupUpdate( sqlite3_backup *p, Pgno iPage, const u8 *aData ){ assert( p!=0 ); do{ assert( sqlite3_mutex_held(p->pSrc->pBt->mutex) ); if( !isFatalError(p->rc) && iPageiNext ){ /* The backup process p has already copied page iPage. But now it ** has been modified by a transaction on the source pager. Copy ** the new data into the backup. */ int rc; assert( p->pDestDb ); sqlite3_mutex_enter(p->pDestDb->mutex); rc = backupOnePage(p, iPage, aData, 1); sqlite3_mutex_leave(p->pDestDb->mutex); assert( rc!=SQLITE_BUSY && rc!=SQLITE_LOCKED ); if( rc!=SQLITE_OK ){ p->rc = rc; } } }while( (p = p->pNext)!=0 ); } SQLITE_PRIVATE void sqlite3BackupUpdate(sqlite3_backup *pBackup, Pgno iPage, const u8 *aData){ if( pBackup ) backupUpdate(pBackup, iPage, aData); } /* ** Restart the backup process. This is called when the pager layer ** detects that the database has been modified by an external database ** connection. In this case there is no way of knowing which of the ** pages that have been copied into the destination database are still ** valid and which are not, so the entire process needs to be restarted. ** ** It is assumed that the mutex associated with the BtShared object ** corresponding to the source database is held when this function is ** called. */ SQLITE_PRIVATE void sqlite3BackupRestart(sqlite3_backup *pBackup){ sqlite3_backup *p; /* Iterator variable */ for(p=pBackup; p; p=p->pNext){ assert( sqlite3_mutex_held(p->pSrc->pBt->mutex) ); p->iNext = 1; } } #ifndef SQLITE_OMIT_VACUUM /* ** Copy the complete content of pBtFrom into pBtTo. A transaction ** must be active for both files. ** ** The size of file pTo may be reduced by this operation. If anything ** goes wrong, the transaction on pTo is rolled back. If successful, the ** transaction is committed before returning. */ SQLITE_PRIVATE int sqlite3BtreeCopyFile(Btree *pTo, Btree *pFrom){ int rc; sqlite3_file *pFd; /* File descriptor for database pTo */ sqlite3_backup b; sqlite3BtreeEnter(pTo); sqlite3BtreeEnter(pFrom); assert( sqlite3BtreeIsInTrans(pTo) ); pFd = sqlite3PagerFile(sqlite3BtreePager(pTo)); if( pFd->pMethods ){ i64 nByte = sqlite3BtreeGetPageSize(pFrom)*(i64)sqlite3BtreeLastPage(pFrom); rc = sqlite3OsFileControl(pFd, SQLITE_FCNTL_OVERWRITE, &nByte); if( rc==SQLITE_NOTFOUND ) rc = SQLITE_OK; if( rc ) goto copy_finished; } /* Set up an sqlite3_backup object. sqlite3_backup.pDestDb must be set ** to 0. This is used by the implementations of sqlite3_backup_step() ** and sqlite3_backup_finish() to detect that they are being called ** from this function, not directly by the user. */ memset(&b, 0, sizeof(b)); b.pSrcDb = pFrom->db; b.pSrc = pFrom; b.pDest = pTo; b.iNext = 1; #ifdef SQLITE_HAS_CODEC sqlite3PagerAlignReserve(sqlite3BtreePager(pTo), sqlite3BtreePager(pFrom)); #endif /* 0x7FFFFFFF is the hard limit for the number of pages in a database ** file. By passing this as the number of pages to copy to ** sqlite3_backup_step(), we can guarantee that the copy finishes ** within a single call (unless an error occurs). The assert() statement ** checks this assumption - (p->rc) should be set to either SQLITE_DONE ** or an error code. */ sqlite3_backup_step(&b, 0x7FFFFFFF); assert( b.rc!=SQLITE_OK ); rc = sqlite3_backup_finish(&b); if( rc==SQLITE_OK ){ pTo->pBt->btsFlags &= ~BTS_PAGESIZE_FIXED; }else{ sqlite3PagerClearCache(sqlite3BtreePager(b.pDest)); } assert( sqlite3BtreeIsInTrans(pTo)==0 ); copy_finished: sqlite3BtreeLeave(pFrom); sqlite3BtreeLeave(pTo); return rc; } #endif /* SQLITE_OMIT_VACUUM */ /************** End of backup.c **********************************************/ /************** Begin file vdbemem.c *****************************************/ /* ** 2004 May 26 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ************************************************************************* ** ** This file contains code use to manipulate "Mem" structure. A "Mem" ** stores a single value in the VDBE. Mem is an opaque structure visible ** only within the VDBE. Interface routines refer to a Mem using the ** name sqlite_value */ /* #include "sqliteInt.h" */ /* #include "vdbeInt.h" */ #ifdef SQLITE_DEBUG /* ** Check invariants on a Mem object. ** ** This routine is intended for use inside of assert() statements, like ** this: assert( sqlite3VdbeCheckMemInvariants(pMem) ); */ SQLITE_PRIVATE int sqlite3VdbeCheckMemInvariants(Mem *p){ /* If MEM_Dyn is set then Mem.xDel!=0. ** Mem.xDel is might not be initialized if MEM_Dyn is clear. */ assert( (p->flags & MEM_Dyn)==0 || p->xDel!=0 ); /* MEM_Dyn may only be set if Mem.szMalloc==0. In this way we ** ensure that if Mem.szMalloc>0 then it is safe to do ** Mem.z = Mem.zMalloc without having to check Mem.flags&MEM_Dyn. ** That saves a few cycles in inner loops. */ assert( (p->flags & MEM_Dyn)==0 || p->szMalloc==0 ); /* Cannot be both MEM_Int and MEM_Real at the same time */ assert( (p->flags & (MEM_Int|MEM_Real))!=(MEM_Int|MEM_Real) ); /* The szMalloc field holds the correct memory allocation size */ assert( p->szMalloc==0 || p->szMalloc==sqlite3DbMallocSize(p->db,p->zMalloc) ); /* If p holds a string or blob, the Mem.z must point to exactly ** one of the following: ** ** (1) Memory in Mem.zMalloc and managed by the Mem object ** (2) Memory to be freed using Mem.xDel ** (3) An ephemeral string or blob ** (4) A static string or blob */ if( (p->flags & (MEM_Str|MEM_Blob)) && p->n>0 ){ assert( ((p->szMalloc>0 && p->z==p->zMalloc)? 1 : 0) + ((p->flags&MEM_Dyn)!=0 ? 1 : 0) + ((p->flags&MEM_Ephem)!=0 ? 1 : 0) + ((p->flags&MEM_Static)!=0 ? 1 : 0) == 1 ); } return 1; } #endif /* ** If pMem is an object with a valid string representation, this routine ** ensures the internal encoding for the string representation is ** 'desiredEnc', one of SQLITE_UTF8, SQLITE_UTF16LE or SQLITE_UTF16BE. ** ** If pMem is not a string object, or the encoding of the string ** representation is already stored using the requested encoding, then this ** routine is a no-op. ** ** SQLITE_OK is returned if the conversion is successful (or not required). ** SQLITE_NOMEM may be returned if a malloc() fails during conversion ** between formats. */ SQLITE_PRIVATE int sqlite3VdbeChangeEncoding(Mem *pMem, int desiredEnc){ #ifndef SQLITE_OMIT_UTF16 int rc; #endif assert( (pMem->flags&MEM_RowSet)==0 ); assert( desiredEnc==SQLITE_UTF8 || desiredEnc==SQLITE_UTF16LE || desiredEnc==SQLITE_UTF16BE ); if( !(pMem->flags&MEM_Str) || pMem->enc==desiredEnc ){ return SQLITE_OK; } assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) ); #ifdef SQLITE_OMIT_UTF16 return SQLITE_ERROR; #else /* MemTranslate() may return SQLITE_OK or SQLITE_NOMEM. If NOMEM is returned, ** then the encoding of the value may not have changed. */ rc = sqlite3VdbeMemTranslate(pMem, (u8)desiredEnc); assert(rc==SQLITE_OK || rc==SQLITE_NOMEM); assert(rc==SQLITE_OK || pMem->enc!=desiredEnc); assert(rc==SQLITE_NOMEM || pMem->enc==desiredEnc); return rc; #endif } /* ** Make sure pMem->z points to a writable allocation of at least ** min(n,32) bytes. ** ** If the bPreserve argument is true, then copy of the content of ** pMem->z into the new allocation. pMem must be either a string or ** blob if bPreserve is true. If bPreserve is false, any prior content ** in pMem->z is discarded. */ SQLITE_PRIVATE SQLITE_NOINLINE int sqlite3VdbeMemGrow(Mem *pMem, int n, int bPreserve){ assert( sqlite3VdbeCheckMemInvariants(pMem) ); assert( (pMem->flags&MEM_RowSet)==0 ); testcase( pMem->db==0 ); /* If the bPreserve flag is set to true, then the memory cell must already ** contain a valid string or blob value. */ assert( bPreserve==0 || pMem->flags&(MEM_Blob|MEM_Str) ); testcase( bPreserve && pMem->z==0 ); assert( pMem->szMalloc==0 || pMem->szMalloc==sqlite3DbMallocSize(pMem->db, pMem->zMalloc) ); if( pMem->szMallocszMalloc>0 && pMem->z==pMem->zMalloc ){ pMem->z = pMem->zMalloc = sqlite3DbReallocOrFree(pMem->db, pMem->z, n); bPreserve = 0; }else{ if( pMem->szMalloc>0 ) sqlite3DbFree(pMem->db, pMem->zMalloc); pMem->zMalloc = sqlite3DbMallocRaw(pMem->db, n); } if( pMem->zMalloc==0 ){ sqlite3VdbeMemSetNull(pMem); pMem->z = 0; pMem->szMalloc = 0; return SQLITE_NOMEM_BKPT; }else{ pMem->szMalloc = sqlite3DbMallocSize(pMem->db, pMem->zMalloc); } } if( bPreserve && pMem->z && pMem->z!=pMem->zMalloc ){ memcpy(pMem->zMalloc, pMem->z, pMem->n); } if( (pMem->flags&MEM_Dyn)!=0 ){ assert( pMem->xDel!=0 && pMem->xDel!=SQLITE_DYNAMIC ); pMem->xDel((void *)(pMem->z)); } pMem->z = pMem->zMalloc; pMem->flags &= ~(MEM_Dyn|MEM_Ephem|MEM_Static); return SQLITE_OK; } /* ** Change the pMem->zMalloc allocation to be at least szNew bytes. ** If pMem->zMalloc already meets or exceeds the requested size, this ** routine is a no-op. ** ** Any prior string or blob content in the pMem object may be discarded. ** The pMem->xDel destructor is called, if it exists. Though MEM_Str ** and MEM_Blob values may be discarded, MEM_Int, MEM_Real, and MEM_Null ** values are preserved. ** ** Return SQLITE_OK on success or an error code (probably SQLITE_NOMEM) ** if unable to complete the resizing. */ SQLITE_PRIVATE int sqlite3VdbeMemClearAndResize(Mem *pMem, int szNew){ assert( szNew>0 ); assert( (pMem->flags & MEM_Dyn)==0 || pMem->szMalloc==0 ); if( pMem->szMallocflags & MEM_Dyn)==0 ); pMem->z = pMem->zMalloc; pMem->flags &= (MEM_Null|MEM_Int|MEM_Real); return SQLITE_OK; } /* ** Change pMem so that its MEM_Str or MEM_Blob value is stored in ** MEM.zMalloc, where it can be safely written. ** ** Return SQLITE_OK on success or SQLITE_NOMEM if malloc fails. */ SQLITE_PRIVATE int sqlite3VdbeMemMakeWriteable(Mem *pMem){ assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) ); assert( (pMem->flags&MEM_RowSet)==0 ); if( (pMem->flags & (MEM_Str|MEM_Blob))!=0 ){ if( ExpandBlob(pMem) ) return SQLITE_NOMEM; if( pMem->szMalloc==0 || pMem->z!=pMem->zMalloc ){ if( sqlite3VdbeMemGrow(pMem, pMem->n + 2, 1) ){ return SQLITE_NOMEM_BKPT; } pMem->z[pMem->n] = 0; pMem->z[pMem->n+1] = 0; pMem->flags |= MEM_Term; } } pMem->flags &= ~MEM_Ephem; #ifdef SQLITE_DEBUG pMem->pScopyFrom = 0; #endif return SQLITE_OK; } /* ** If the given Mem* has a zero-filled tail, turn it into an ordinary ** blob stored in dynamically allocated space. */ #ifndef SQLITE_OMIT_INCRBLOB SQLITE_PRIVATE int sqlite3VdbeMemExpandBlob(Mem *pMem){ int nByte; assert( pMem->flags & MEM_Zero ); assert( pMem->flags&MEM_Blob ); assert( (pMem->flags&MEM_RowSet)==0 ); assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) ); /* Set nByte to the number of bytes required to store the expanded blob. */ nByte = pMem->n + pMem->u.nZero; if( nByte<=0 ){ nByte = 1; } if( sqlite3VdbeMemGrow(pMem, nByte, 1) ){ return SQLITE_NOMEM_BKPT; } memset(&pMem->z[pMem->n], 0, pMem->u.nZero); pMem->n += pMem->u.nZero; pMem->flags &= ~(MEM_Zero|MEM_Term); return SQLITE_OK; } #endif /* ** It is already known that pMem contains an unterminated string. ** Add the zero terminator. */ static SQLITE_NOINLINE int vdbeMemAddTerminator(Mem *pMem){ if( sqlite3VdbeMemGrow(pMem, pMem->n+2, 1) ){ return SQLITE_NOMEM_BKPT; } pMem->z[pMem->n] = 0; pMem->z[pMem->n+1] = 0; pMem->flags |= MEM_Term; return SQLITE_OK; } /* ** Make sure the given Mem is \u0000 terminated. */ SQLITE_PRIVATE int sqlite3VdbeMemNulTerminate(Mem *pMem){ assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) ); testcase( (pMem->flags & (MEM_Term|MEM_Str))==(MEM_Term|MEM_Str) ); testcase( (pMem->flags & (MEM_Term|MEM_Str))==0 ); if( (pMem->flags & (MEM_Term|MEM_Str))!=MEM_Str ){ return SQLITE_OK; /* Nothing to do */ }else{ return vdbeMemAddTerminator(pMem); } } /* ** Add MEM_Str to the set of representations for the given Mem. Numbers ** are converted using sqlite3_snprintf(). Converting a BLOB to a string ** is a no-op. ** ** Existing representations MEM_Int and MEM_Real are invalidated if ** bForce is true but are retained if bForce is false. ** ** A MEM_Null value will never be passed to this function. This function is ** used for converting values to text for returning to the user (i.e. via ** sqlite3_value_text()), or for ensuring that values to be used as btree ** keys are strings. In the former case a NULL pointer is returned the ** user and the latter is an internal programming error. */ SQLITE_PRIVATE int sqlite3VdbeMemStringify(Mem *pMem, u8 enc, u8 bForce){ int fg = pMem->flags; const int nByte = 32; assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) ); assert( !(fg&MEM_Zero) ); assert( !(fg&(MEM_Str|MEM_Blob)) ); assert( fg&(MEM_Int|MEM_Real) ); assert( (pMem->flags&MEM_RowSet)==0 ); assert( EIGHT_BYTE_ALIGNMENT(pMem) ); if( sqlite3VdbeMemClearAndResize(pMem, nByte) ){ pMem->enc = 0; return SQLITE_NOMEM_BKPT; } /* For a Real or Integer, use sqlite3_snprintf() to produce the UTF-8 ** string representation of the value. Then, if the required encoding ** is UTF-16le or UTF-16be do a translation. ** ** FIX ME: It would be better if sqlite3_snprintf() could do UTF-16. */ if( fg & MEM_Int ){ sqlite3_snprintf(nByte, pMem->z, "%lld", pMem->u.i); }else{ assert( fg & MEM_Real ); sqlite3_snprintf(nByte, pMem->z, "%!.15g", pMem->u.r); } pMem->n = sqlite3Strlen30(pMem->z); pMem->enc = SQLITE_UTF8; pMem->flags |= MEM_Str|MEM_Term; if( bForce ) pMem->flags &= ~(MEM_Int|MEM_Real); sqlite3VdbeChangeEncoding(pMem, enc); return SQLITE_OK; } /* ** Memory cell pMem contains the context of an aggregate function. ** This routine calls the finalize method for that function. The ** result of the aggregate is stored back into pMem. ** ** Return SQLITE_ERROR if the finalizer reports an error. SQLITE_OK ** otherwise. */ SQLITE_PRIVATE int sqlite3VdbeMemFinalize(Mem *pMem, FuncDef *pFunc){ int rc = SQLITE_OK; if( ALWAYS(pFunc && pFunc->xFinalize) ){ sqlite3_context ctx; Mem t; assert( (pMem->flags & MEM_Null)!=0 || pFunc==pMem->u.pDef ); assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) ); memset(&ctx, 0, sizeof(ctx)); memset(&t, 0, sizeof(t)); t.flags = MEM_Null; t.db = pMem->db; ctx.pOut = &t; ctx.pMem = pMem; ctx.pFunc = pFunc; pFunc->xFinalize(&ctx); /* IMP: R-24505-23230 */ assert( (pMem->flags & MEM_Dyn)==0 ); if( pMem->szMalloc>0 ) sqlite3DbFree(pMem->db, pMem->zMalloc); memcpy(pMem, &t, sizeof(t)); rc = ctx.isError; } return rc; } /* ** If the memory cell contains a value that must be freed by ** invoking the external callback in Mem.xDel, then this routine ** will free that value. It also sets Mem.flags to MEM_Null. ** ** This is a helper routine for sqlite3VdbeMemSetNull() and ** for sqlite3VdbeMemRelease(). Use those other routines as the ** entry point for releasing Mem resources. */ static SQLITE_NOINLINE void vdbeMemClearExternAndSetNull(Mem *p){ assert( p->db==0 || sqlite3_mutex_held(p->db->mutex) ); assert( VdbeMemDynamic(p) ); if( p->flags&MEM_Agg ){ sqlite3VdbeMemFinalize(p, p->u.pDef); assert( (p->flags & MEM_Agg)==0 ); testcase( p->flags & MEM_Dyn ); } if( p->flags&MEM_Dyn ){ assert( (p->flags&MEM_RowSet)==0 ); assert( p->xDel!=SQLITE_DYNAMIC && p->xDel!=0 ); p->xDel((void *)p->z); }else if( p->flags&MEM_RowSet ){ sqlite3RowSetClear(p->u.pRowSet); }else if( p->flags&MEM_Frame ){ VdbeFrame *pFrame = p->u.pFrame; pFrame->pParent = pFrame->v->pDelFrame; pFrame->v->pDelFrame = pFrame; } p->flags = MEM_Null; } /* ** Release memory held by the Mem p, both external memory cleared ** by p->xDel and memory in p->zMalloc. ** ** This is a helper routine invoked by sqlite3VdbeMemRelease() in ** the unusual case where there really is memory in p that needs ** to be freed. */ static SQLITE_NOINLINE void vdbeMemClear(Mem *p){ if( VdbeMemDynamic(p) ){ vdbeMemClearExternAndSetNull(p); } if( p->szMalloc ){ sqlite3DbFree(p->db, p->zMalloc); p->szMalloc = 0; } p->z = 0; } /* ** Release any memory resources held by the Mem. Both the memory that is ** free by Mem.xDel and the Mem.zMalloc allocation are freed. ** ** Use this routine prior to clean up prior to abandoning a Mem, or to ** reset a Mem back to its minimum memory utilization. ** ** Use sqlite3VdbeMemSetNull() to release just the Mem.xDel space ** prior to inserting new content into the Mem. */ SQLITE_PRIVATE void sqlite3VdbeMemRelease(Mem *p){ assert( sqlite3VdbeCheckMemInvariants(p) ); if( VdbeMemDynamic(p) || p->szMalloc ){ vdbeMemClear(p); } } /* ** Convert a 64-bit IEEE double into a 64-bit signed integer. ** If the double is out of range of a 64-bit signed integer then ** return the closest available 64-bit signed integer. */ static i64 doubleToInt64(double r){ #ifdef SQLITE_OMIT_FLOATING_POINT /* When floating-point is omitted, double and int64 are the same thing */ return r; #else /* ** Many compilers we encounter do not define constants for the ** minimum and maximum 64-bit integers, or they define them ** inconsistently. And many do not understand the "LL" notation. ** So we define our own static constants here using nothing ** larger than a 32-bit integer constant. */ static const i64 maxInt = LARGEST_INT64; static const i64 minInt = SMALLEST_INT64; if( r<=(double)minInt ){ return minInt; }else if( r>=(double)maxInt ){ return maxInt; }else{ return (i64)r; } #endif } /* ** Return some kind of integer value which is the best we can do ** at representing the value that *pMem describes as an integer. ** If pMem is an integer, then the value is exact. If pMem is ** a floating-point then the value returned is the integer part. ** If pMem is a string or blob, then we make an attempt to convert ** it into an integer and return that. If pMem represents an ** an SQL-NULL value, return 0. ** ** If pMem represents a string value, its encoding might be changed. */ SQLITE_PRIVATE i64 sqlite3VdbeIntValue(Mem *pMem){ int flags; assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) ); assert( EIGHT_BYTE_ALIGNMENT(pMem) ); flags = pMem->flags; if( flags & MEM_Int ){ return pMem->u.i; }else if( flags & MEM_Real ){ return doubleToInt64(pMem->u.r); }else if( flags & (MEM_Str|MEM_Blob) ){ i64 value = 0; assert( pMem->z || pMem->n==0 ); sqlite3Atoi64(pMem->z, &value, pMem->n, pMem->enc); return value; }else{ return 0; } } /* ** Return the best representation of pMem that we can get into a ** double. If pMem is already a double or an integer, return its ** value. If it is a string or blob, try to convert it to a double. ** If it is a NULL, return 0.0. */ SQLITE_PRIVATE double sqlite3VdbeRealValue(Mem *pMem){ assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) ); assert( EIGHT_BYTE_ALIGNMENT(pMem) ); if( pMem->flags & MEM_Real ){ return pMem->u.r; }else if( pMem->flags & MEM_Int ){ return (double)pMem->u.i; }else if( pMem->flags & (MEM_Str|MEM_Blob) ){ /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */ double val = (double)0; sqlite3AtoF(pMem->z, &val, pMem->n, pMem->enc); return val; }else{ /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */ return (double)0; } } /* ** The MEM structure is already a MEM_Real. Try to also make it a ** MEM_Int if we can. */ SQLITE_PRIVATE void sqlite3VdbeIntegerAffinity(Mem *pMem){ i64 ix; assert( pMem->flags & MEM_Real ); assert( (pMem->flags & MEM_RowSet)==0 ); assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) ); assert( EIGHT_BYTE_ALIGNMENT(pMem) ); ix = doubleToInt64(pMem->u.r); /* Only mark the value as an integer if ** ** (1) the round-trip conversion real->int->real is a no-op, and ** (2) The integer is neither the largest nor the smallest ** possible integer (ticket #3922) ** ** The second and third terms in the following conditional enforces ** the second condition under the assumption that addition overflow causes ** values to wrap around. */ if( pMem->u.r==ix && ix>SMALLEST_INT64 && ixu.i = ix; MemSetTypeFlag(pMem, MEM_Int); } } /* ** Convert pMem to type integer. Invalidate any prior representations. */ SQLITE_PRIVATE int sqlite3VdbeMemIntegerify(Mem *pMem){ assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) ); assert( (pMem->flags & MEM_RowSet)==0 ); assert( EIGHT_BYTE_ALIGNMENT(pMem) ); pMem->u.i = sqlite3VdbeIntValue(pMem); MemSetTypeFlag(pMem, MEM_Int); return SQLITE_OK; } /* ** Convert pMem so that it is of type MEM_Real. ** Invalidate any prior representations. */ SQLITE_PRIVATE int sqlite3VdbeMemRealify(Mem *pMem){ assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) ); assert( EIGHT_BYTE_ALIGNMENT(pMem) ); pMem->u.r = sqlite3VdbeRealValue(pMem); MemSetTypeFlag(pMem, MEM_Real); return SQLITE_OK; } /* ** Convert pMem so that it has types MEM_Real or MEM_Int or both. ** Invalidate any prior representations. ** ** Every effort is made to force the conversion, even if the input ** is a string that does not look completely like a number. Convert ** as much of the string as we can and ignore the rest. */ SQLITE_PRIVATE int sqlite3VdbeMemNumerify(Mem *pMem){ if( (pMem->flags & (MEM_Int|MEM_Real|MEM_Null))==0 ){ assert( (pMem->flags & (MEM_Blob|MEM_Str))!=0 ); assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) ); if( 0==sqlite3Atoi64(pMem->z, &pMem->u.i, pMem->n, pMem->enc) ){ MemSetTypeFlag(pMem, MEM_Int); }else{ pMem->u.r = sqlite3VdbeRealValue(pMem); MemSetTypeFlag(pMem, MEM_Real); sqlite3VdbeIntegerAffinity(pMem); } } assert( (pMem->flags & (MEM_Int|MEM_Real|MEM_Null))!=0 ); pMem->flags &= ~(MEM_Str|MEM_Blob|MEM_Zero); return SQLITE_OK; } /* ** Cast the datatype of the value in pMem according to the affinity ** "aff". Casting is different from applying affinity in that a cast ** is forced. In other words, the value is converted into the desired ** affinity even if that results in loss of data. This routine is ** used (for example) to implement the SQL "cast()" operator. */ SQLITE_PRIVATE void sqlite3VdbeMemCast(Mem *pMem, u8 aff, u8 encoding){ if( pMem->flags & MEM_Null ) return; switch( aff ){ case SQLITE_AFF_BLOB: { /* Really a cast to BLOB */ if( (pMem->flags & MEM_Blob)==0 ){ sqlite3ValueApplyAffinity(pMem, SQLITE_AFF_TEXT, encoding); assert( pMem->flags & MEM_Str || pMem->db->mallocFailed ); if( pMem->flags & MEM_Str ) MemSetTypeFlag(pMem, MEM_Blob); }else{ pMem->flags &= ~(MEM_TypeMask&~MEM_Blob); } break; } case SQLITE_AFF_NUMERIC: { sqlite3VdbeMemNumerify(pMem); break; } case SQLITE_AFF_INTEGER: { sqlite3VdbeMemIntegerify(pMem); break; } case SQLITE_AFF_REAL: { sqlite3VdbeMemRealify(pMem); break; } default: { assert( aff==SQLITE_AFF_TEXT ); assert( MEM_Str==(MEM_Blob>>3) ); pMem->flags |= (pMem->flags&MEM_Blob)>>3; sqlite3ValueApplyAffinity(pMem, SQLITE_AFF_TEXT, encoding); assert( pMem->flags & MEM_Str || pMem->db->mallocFailed ); pMem->flags &= ~(MEM_Int|MEM_Real|MEM_Blob|MEM_Zero); break; } } } /* ** Initialize bulk memory to be a consistent Mem object. ** ** The minimum amount of initialization feasible is performed. */ SQLITE_PRIVATE void sqlite3VdbeMemInit(Mem *pMem, sqlite3 *db, u16 flags){ assert( (flags & ~MEM_TypeMask)==0 ); pMem->flags = flags; pMem->db = db; pMem->szMalloc = 0; } /* ** Delete any previous value and set the value stored in *pMem to NULL. ** ** This routine calls the Mem.xDel destructor to dispose of values that ** require the destructor. But it preserves the Mem.zMalloc memory allocation. ** To free all resources, use sqlite3VdbeMemRelease(), which both calls this ** routine to invoke the destructor and deallocates Mem.zMalloc. ** ** Use this routine to reset the Mem prior to insert a new value. ** ** Use sqlite3VdbeMemRelease() to complete erase the Mem prior to abandoning it. */ SQLITE_PRIVATE void sqlite3VdbeMemSetNull(Mem *pMem){ if( VdbeMemDynamic(pMem) ){ vdbeMemClearExternAndSetNull(pMem); }else{ pMem->flags = MEM_Null; } } SQLITE_PRIVATE void sqlite3ValueSetNull(sqlite3_value *p){ sqlite3VdbeMemSetNull((Mem*)p); } /* ** Delete any previous value and set the value to be a BLOB of length ** n containing all zeros. */ SQLITE_PRIVATE void sqlite3VdbeMemSetZeroBlob(Mem *pMem, int n){ sqlite3VdbeMemRelease(pMem); pMem->flags = MEM_Blob|MEM_Zero; pMem->n = 0; if( n<0 ) n = 0; pMem->u.nZero = n; pMem->enc = SQLITE_UTF8; pMem->z = 0; } /* ** The pMem is known to contain content that needs to be destroyed prior ** to a value change. So invoke the destructor, then set the value to ** a 64-bit integer. */ static SQLITE_NOINLINE void vdbeReleaseAndSetInt64(Mem *pMem, i64 val){ sqlite3VdbeMemSetNull(pMem); pMem->u.i = val; pMem->flags = MEM_Int; } /* ** Delete any previous value and set the value stored in *pMem to val, ** manifest type INTEGER. */ SQLITE_PRIVATE void sqlite3VdbeMemSetInt64(Mem *pMem, i64 val){ if( VdbeMemDynamic(pMem) ){ vdbeReleaseAndSetInt64(pMem, val); }else{ pMem->u.i = val; pMem->flags = MEM_Int; } } #ifndef SQLITE_OMIT_FLOATING_POINT /* ** Delete any previous value and set the value stored in *pMem to val, ** manifest type REAL. */ SQLITE_PRIVATE void sqlite3VdbeMemSetDouble(Mem *pMem, double val){ sqlite3VdbeMemSetNull(pMem); if( !sqlite3IsNaN(val) ){ pMem->u.r = val; pMem->flags = MEM_Real; } } #endif /* ** Delete any previous value and set the value of pMem to be an ** empty boolean index. */ SQLITE_PRIVATE void sqlite3VdbeMemSetRowSet(Mem *pMem){ sqlite3 *db = pMem->db; assert( db!=0 ); assert( (pMem->flags & MEM_RowSet)==0 ); sqlite3VdbeMemRelease(pMem); pMem->zMalloc = sqlite3DbMallocRawNN(db, 64); if( db->mallocFailed ){ pMem->flags = MEM_Null; pMem->szMalloc = 0; }else{ assert( pMem->zMalloc ); pMem->szMalloc = sqlite3DbMallocSize(db, pMem->zMalloc); pMem->u.pRowSet = sqlite3RowSetInit(db, pMem->zMalloc, pMem->szMalloc); assert( pMem->u.pRowSet!=0 ); pMem->flags = MEM_RowSet; } } /* ** Return true if the Mem object contains a TEXT or BLOB that is ** too large - whose size exceeds SQLITE_MAX_LENGTH. */ SQLITE_PRIVATE int sqlite3VdbeMemTooBig(Mem *p){ assert( p->db!=0 ); if( p->flags & (MEM_Str|MEM_Blob) ){ int n = p->n; if( p->flags & MEM_Zero ){ n += p->u.nZero; } return n>p->db->aLimit[SQLITE_LIMIT_LENGTH]; } return 0; } #ifdef SQLITE_DEBUG /* ** This routine prepares a memory cell for modification by breaking ** its link to a shallow copy and by marking any current shallow ** copies of this cell as invalid. ** ** This is used for testing and debugging only - to make sure shallow ** copies are not misused. */ SQLITE_PRIVATE void sqlite3VdbeMemAboutToChange(Vdbe *pVdbe, Mem *pMem){ int i; Mem *pX; for(i=0, pX=pVdbe->aMem; inMem; i++, pX++){ if( pX->pScopyFrom==pMem ){ pX->flags |= MEM_Undefined; pX->pScopyFrom = 0; } } pMem->pScopyFrom = 0; } #endif /* SQLITE_DEBUG */ /* ** Make an shallow copy of pFrom into pTo. Prior contents of ** pTo are freed. The pFrom->z field is not duplicated. If ** pFrom->z is used, then pTo->z points to the same thing as pFrom->z ** and flags gets srcType (either MEM_Ephem or MEM_Static). */ static SQLITE_NOINLINE void vdbeClrCopy(Mem *pTo, const Mem *pFrom, int eType){ vdbeMemClearExternAndSetNull(pTo); assert( !VdbeMemDynamic(pTo) ); sqlite3VdbeMemShallowCopy(pTo, pFrom, eType); } SQLITE_PRIVATE void sqlite3VdbeMemShallowCopy(Mem *pTo, const Mem *pFrom, int srcType){ assert( (pFrom->flags & MEM_RowSet)==0 ); assert( pTo->db==pFrom->db ); if( VdbeMemDynamic(pTo) ){ vdbeClrCopy(pTo,pFrom,srcType); return; } memcpy(pTo, pFrom, MEMCELLSIZE); if( (pFrom->flags&MEM_Static)==0 ){ pTo->flags &= ~(MEM_Dyn|MEM_Static|MEM_Ephem); assert( srcType==MEM_Ephem || srcType==MEM_Static ); pTo->flags |= srcType; } } /* ** Make a full copy of pFrom into pTo. Prior contents of pTo are ** freed before the copy is made. */ SQLITE_PRIVATE int sqlite3VdbeMemCopy(Mem *pTo, const Mem *pFrom){ int rc = SQLITE_OK; assert( (pFrom->flags & MEM_RowSet)==0 ); if( VdbeMemDynamic(pTo) ) vdbeMemClearExternAndSetNull(pTo); memcpy(pTo, pFrom, MEMCELLSIZE); pTo->flags &= ~MEM_Dyn; if( pTo->flags&(MEM_Str|MEM_Blob) ){ if( 0==(pFrom->flags&MEM_Static) ){ pTo->flags |= MEM_Ephem; rc = sqlite3VdbeMemMakeWriteable(pTo); } } return rc; } /* ** Transfer the contents of pFrom to pTo. Any existing value in pTo is ** freed. If pFrom contains ephemeral data, a copy is made. ** ** pFrom contains an SQL NULL when this routine returns. */ SQLITE_PRIVATE void sqlite3VdbeMemMove(Mem *pTo, Mem *pFrom){ assert( pFrom->db==0 || sqlite3_mutex_held(pFrom->db->mutex) ); assert( pTo->db==0 || sqlite3_mutex_held(pTo->db->mutex) ); assert( pFrom->db==0 || pTo->db==0 || pFrom->db==pTo->db ); sqlite3VdbeMemRelease(pTo); memcpy(pTo, pFrom, sizeof(Mem)); pFrom->flags = MEM_Null; pFrom->szMalloc = 0; } /* ** Change the value of a Mem to be a string or a BLOB. ** ** The memory management strategy depends on the value of the xDel ** parameter. If the value passed is SQLITE_TRANSIENT, then the ** string is copied into a (possibly existing) buffer managed by the ** Mem structure. Otherwise, any existing buffer is freed and the ** pointer copied. ** ** If the string is too large (if it exceeds the SQLITE_LIMIT_LENGTH ** size limit) then no memory allocation occurs. If the string can be ** stored without allocating memory, then it is. If a memory allocation ** is required to store the string, then value of pMem is unchanged. In ** either case, SQLITE_TOOBIG is returned. */ SQLITE_PRIVATE int sqlite3VdbeMemSetStr( Mem *pMem, /* Memory cell to set to string value */ const char *z, /* String pointer */ int n, /* Bytes in string, or negative */ u8 enc, /* Encoding of z. 0 for BLOBs */ void (*xDel)(void*) /* Destructor function */ ){ int nByte = n; /* New value for pMem->n */ int iLimit; /* Maximum allowed string or blob size */ u16 flags = 0; /* New value for pMem->flags */ assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) ); assert( (pMem->flags & MEM_RowSet)==0 ); /* If z is a NULL pointer, set pMem to contain an SQL NULL. */ if( !z ){ sqlite3VdbeMemSetNull(pMem); return SQLITE_OK; } if( pMem->db ){ iLimit = pMem->db->aLimit[SQLITE_LIMIT_LENGTH]; }else{ iLimit = SQLITE_MAX_LENGTH; } flags = (enc==0?MEM_Blob:MEM_Str); if( nByte<0 ){ assert( enc!=0 ); if( enc==SQLITE_UTF8 ){ nByte = sqlite3Strlen30(z); if( nByte>iLimit ) nByte = iLimit+1; }else{ for(nByte=0; nByte<=iLimit && (z[nByte] | z[nByte+1]); nByte+=2){} } flags |= MEM_Term; } /* The following block sets the new values of Mem.z and Mem.xDel. It ** also sets a flag in local variable "flags" to indicate the memory ** management (one of MEM_Dyn or MEM_Static). */ if( xDel==SQLITE_TRANSIENT ){ int nAlloc = nByte; if( flags&MEM_Term ){ nAlloc += (enc==SQLITE_UTF8?1:2); } if( nByte>iLimit ){ return SQLITE_TOOBIG; } testcase( nAlloc==0 ); testcase( nAlloc==31 ); testcase( nAlloc==32 ); if( sqlite3VdbeMemClearAndResize(pMem, MAX(nAlloc,32)) ){ return SQLITE_NOMEM_BKPT; } memcpy(pMem->z, z, nAlloc); }else if( xDel==SQLITE_DYNAMIC ){ sqlite3VdbeMemRelease(pMem); pMem->zMalloc = pMem->z = (char *)z; pMem->szMalloc = sqlite3DbMallocSize(pMem->db, pMem->zMalloc); }else{ sqlite3VdbeMemRelease(pMem); pMem->z = (char *)z; pMem->xDel = xDel; flags |= ((xDel==SQLITE_STATIC)?MEM_Static:MEM_Dyn); } pMem->n = nByte; pMem->flags = flags; pMem->enc = (enc==0 ? SQLITE_UTF8 : enc); #ifndef SQLITE_OMIT_UTF16 if( pMem->enc!=SQLITE_UTF8 && sqlite3VdbeMemHandleBom(pMem) ){ return SQLITE_NOMEM_BKPT; } #endif if( nByte>iLimit ){ return SQLITE_TOOBIG; } return SQLITE_OK; } /* ** Move data out of a btree key or data field and into a Mem structure. ** The data or key is taken from the entry that pCur is currently pointing ** to. offset and amt determine what portion of the data or key to retrieve. ** key is true to get the key or false to get data. The result is written ** into the pMem element. ** ** The pMem object must have been initialized. This routine will use ** pMem->zMalloc to hold the content from the btree, if possible. New ** pMem->zMalloc space will be allocated if necessary. The calling routine ** is responsible for making sure that the pMem object is eventually ** destroyed. ** ** If this routine fails for any reason (malloc returns NULL or unable ** to read from the disk) then the pMem is left in an inconsistent state. */ static SQLITE_NOINLINE int vdbeMemFromBtreeResize( BtCursor *pCur, /* Cursor pointing at record to retrieve. */ u32 offset, /* Offset from the start of data to return bytes from. */ u32 amt, /* Number of bytes to return. */ int key, /* If true, retrieve from the btree key, not data. */ Mem *pMem /* OUT: Return data in this Mem structure. */ ){ int rc; pMem->flags = MEM_Null; if( SQLITE_OK==(rc = sqlite3VdbeMemClearAndResize(pMem, amt+2)) ){ if( key ){ rc = sqlite3BtreeKey(pCur, offset, amt, pMem->z); }else{ rc = sqlite3BtreeData(pCur, offset, amt, pMem->z); } if( rc==SQLITE_OK ){ pMem->z[amt] = 0; pMem->z[amt+1] = 0; pMem->flags = MEM_Blob|MEM_Term; pMem->n = (int)amt; }else{ sqlite3VdbeMemRelease(pMem); } } return rc; } SQLITE_PRIVATE int sqlite3VdbeMemFromBtree( BtCursor *pCur, /* Cursor pointing at record to retrieve. */ u32 offset, /* Offset from the start of data to return bytes from. */ u32 amt, /* Number of bytes to return. */ int key, /* If true, retrieve from the btree key, not data. */ Mem *pMem /* OUT: Return data in this Mem structure. */ ){ char *zData; /* Data from the btree layer */ u32 available = 0; /* Number of bytes available on the local btree page */ int rc = SQLITE_OK; /* Return code */ assert( sqlite3BtreeCursorIsValid(pCur) ); assert( !VdbeMemDynamic(pMem) ); /* Note: the calls to BtreeKeyFetch() and DataFetch() below assert() ** that both the BtShared and database handle mutexes are held. */ assert( (pMem->flags & MEM_RowSet)==0 ); zData = (char *)sqlite3BtreePayloadFetch(pCur, &available); assert( zData!=0 ); if( offset+amt<=available ){ pMem->z = &zData[offset]; pMem->flags = MEM_Blob|MEM_Ephem; pMem->n = (int)amt; }else{ rc = vdbeMemFromBtreeResize(pCur, offset, amt, key, pMem); } return rc; } /* ** The pVal argument is known to be a value other than NULL. ** Convert it into a string with encoding enc and return a pointer ** to a zero-terminated version of that string. */ static SQLITE_NOINLINE const void *valueToText(sqlite3_value* pVal, u8 enc){ assert( pVal!=0 ); assert( pVal->db==0 || sqlite3_mutex_held(pVal->db->mutex) ); assert( (enc&3)==(enc&~SQLITE_UTF16_ALIGNED) ); assert( (pVal->flags & MEM_RowSet)==0 ); assert( (pVal->flags & (MEM_Null))==0 ); if( pVal->flags & (MEM_Blob|MEM_Str) ){ pVal->flags |= MEM_Str; if( pVal->enc != (enc & ~SQLITE_UTF16_ALIGNED) ){ sqlite3VdbeChangeEncoding(pVal, enc & ~SQLITE_UTF16_ALIGNED); } if( (enc & SQLITE_UTF16_ALIGNED)!=0 && 1==(1&SQLITE_PTR_TO_INT(pVal->z)) ){ assert( (pVal->flags & (MEM_Ephem|MEM_Static))!=0 ); if( sqlite3VdbeMemMakeWriteable(pVal)!=SQLITE_OK ){ return 0; } } sqlite3VdbeMemNulTerminate(pVal); /* IMP: R-31275-44060 */ }else{ sqlite3VdbeMemStringify(pVal, enc, 0); assert( 0==(1&SQLITE_PTR_TO_INT(pVal->z)) ); } assert(pVal->enc==(enc & ~SQLITE_UTF16_ALIGNED) || pVal->db==0 || pVal->db->mallocFailed ); if( pVal->enc==(enc & ~SQLITE_UTF16_ALIGNED) ){ return pVal->z; }else{ return 0; } } /* This function is only available internally, it is not part of the ** external API. It works in a similar way to sqlite3_value_text(), ** except the data returned is in the encoding specified by the second ** parameter, which must be one of SQLITE_UTF16BE, SQLITE_UTF16LE or ** SQLITE_UTF8. ** ** (2006-02-16:) The enc value can be or-ed with SQLITE_UTF16_ALIGNED. ** If that is the case, then the result must be aligned on an even byte ** boundary. */ SQLITE_PRIVATE const void *sqlite3ValueText(sqlite3_value* pVal, u8 enc){ if( !pVal ) return 0; assert( pVal->db==0 || sqlite3_mutex_held(pVal->db->mutex) ); assert( (enc&3)==(enc&~SQLITE_UTF16_ALIGNED) ); assert( (pVal->flags & MEM_RowSet)==0 ); if( (pVal->flags&(MEM_Str|MEM_Term))==(MEM_Str|MEM_Term) && pVal->enc==enc ){ return pVal->z; } if( pVal->flags&MEM_Null ){ return 0; } return valueToText(pVal, enc); } /* ** Create a new sqlite3_value object. */ SQLITE_PRIVATE sqlite3_value *sqlite3ValueNew(sqlite3 *db){ Mem *p = sqlite3DbMallocZero(db, sizeof(*p)); if( p ){ p->flags = MEM_Null; p->db = db; } return p; } /* ** Context object passed by sqlite3Stat4ProbeSetValue() through to ** valueNew(). See comments above valueNew() for details. */ struct ValueNewStat4Ctx { Parse *pParse; Index *pIdx; UnpackedRecord **ppRec; int iVal; }; /* ** Allocate and return a pointer to a new sqlite3_value object. If ** the second argument to this function is NULL, the object is allocated ** by calling sqlite3ValueNew(). ** ** Otherwise, if the second argument is non-zero, then this function is ** being called indirectly by sqlite3Stat4ProbeSetValue(). If it has not ** already been allocated, allocate the UnpackedRecord structure that ** that function will return to its caller here. Then return a pointer to ** an sqlite3_value within the UnpackedRecord.a[] array. */ static sqlite3_value *valueNew(sqlite3 *db, struct ValueNewStat4Ctx *p){ #ifdef SQLITE_ENABLE_STAT3_OR_STAT4 if( p ){ UnpackedRecord *pRec = p->ppRec[0]; if( pRec==0 ){ Index *pIdx = p->pIdx; /* Index being probed */ int nByte; /* Bytes of space to allocate */ int i; /* Counter variable */ int nCol = pIdx->nColumn; /* Number of index columns including rowid */ nByte = sizeof(Mem) * nCol + ROUND8(sizeof(UnpackedRecord)); pRec = (UnpackedRecord*)sqlite3DbMallocZero(db, nByte); if( pRec ){ pRec->pKeyInfo = sqlite3KeyInfoOfIndex(p->pParse, pIdx); if( pRec->pKeyInfo ){ assert( pRec->pKeyInfo->nField+pRec->pKeyInfo->nXField==nCol ); assert( pRec->pKeyInfo->enc==ENC(db) ); pRec->aMem = (Mem *)((u8*)pRec + ROUND8(sizeof(UnpackedRecord))); for(i=0; iaMem[i].flags = MEM_Null; pRec->aMem[i].db = db; } }else{ sqlite3DbFree(db, pRec); pRec = 0; } } if( pRec==0 ) return 0; p->ppRec[0] = pRec; } pRec->nField = p->iVal+1; return &pRec->aMem[p->iVal]; } #else UNUSED_PARAMETER(p); #endif /* defined(SQLITE_ENABLE_STAT3_OR_STAT4) */ return sqlite3ValueNew(db); } /* ** The expression object indicated by the second argument is guaranteed ** to be a scalar SQL function. If ** ** * all function arguments are SQL literals, ** * one of the SQLITE_FUNC_CONSTANT or _SLOCHNG function flags is set, and ** * the SQLITE_FUNC_NEEDCOLL function flag is not set, ** ** then this routine attempts to invoke the SQL function. Assuming no ** error occurs, output parameter (*ppVal) is set to point to a value ** object containing the result before returning SQLITE_OK. ** ** Affinity aff is applied to the result of the function before returning. ** If the result is a text value, the sqlite3_value object uses encoding ** enc. ** ** If the conditions above are not met, this function returns SQLITE_OK ** and sets (*ppVal) to NULL. Or, if an error occurs, (*ppVal) is set to ** NULL and an SQLite error code returned. */ #ifdef SQLITE_ENABLE_STAT3_OR_STAT4 static int valueFromFunction( sqlite3 *db, /* The database connection */ Expr *p, /* The expression to evaluate */ u8 enc, /* Encoding to use */ u8 aff, /* Affinity to use */ sqlite3_value **ppVal, /* Write the new value here */ struct ValueNewStat4Ctx *pCtx /* Second argument for valueNew() */ ){ sqlite3_context ctx; /* Context object for function invocation */ sqlite3_value **apVal = 0; /* Function arguments */ int nVal = 0; /* Size of apVal[] array */ FuncDef *pFunc = 0; /* Function definition */ sqlite3_value *pVal = 0; /* New value */ int rc = SQLITE_OK; /* Return code */ ExprList *pList = 0; /* Function arguments */ int i; /* Iterator variable */ assert( pCtx!=0 ); assert( (p->flags & EP_TokenOnly)==0 ); pList = p->x.pList; if( pList ) nVal = pList->nExpr; pFunc = sqlite3FindFunction(db, p->u.zToken, nVal, enc, 0); assert( pFunc ); if( (pFunc->funcFlags & (SQLITE_FUNC_CONSTANT|SQLITE_FUNC_SLOCHNG))==0 || (pFunc->funcFlags & SQLITE_FUNC_NEEDCOLL) ){ return SQLITE_OK; } if( pList ){ apVal = (sqlite3_value**)sqlite3DbMallocZero(db, sizeof(apVal[0]) * nVal); if( apVal==0 ){ rc = SQLITE_NOMEM_BKPT; goto value_from_function_out; } for(i=0; ia[i].pExpr, enc, aff, &apVal[i]); if( apVal[i]==0 || rc!=SQLITE_OK ) goto value_from_function_out; } } pVal = valueNew(db, pCtx); if( pVal==0 ){ rc = SQLITE_NOMEM_BKPT; goto value_from_function_out; } assert( pCtx->pParse->rc==SQLITE_OK ); memset(&ctx, 0, sizeof(ctx)); ctx.pOut = pVal; ctx.pFunc = pFunc; pFunc->xSFunc(&ctx, nVal, apVal); if( ctx.isError ){ rc = ctx.isError; sqlite3ErrorMsg(pCtx->pParse, "%s", sqlite3_value_text(pVal)); }else{ sqlite3ValueApplyAffinity(pVal, aff, SQLITE_UTF8); assert( rc==SQLITE_OK ); rc = sqlite3VdbeChangeEncoding(pVal, enc); if( rc==SQLITE_OK && sqlite3VdbeMemTooBig(pVal) ){ rc = SQLITE_TOOBIG; pCtx->pParse->nErr++; } } pCtx->pParse->rc = rc; value_from_function_out: if( rc!=SQLITE_OK ){ pVal = 0; } if( apVal ){ for(i=0; iop)==TK_UPLUS || op==TK_SPAN ) pExpr = pExpr->pLeft; if( NEVER(op==TK_REGISTER) ) op = pExpr->op2; /* Compressed expressions only appear when parsing the DEFAULT clause ** on a table column definition, and hence only when pCtx==0. This ** check ensures that an EP_TokenOnly expression is never passed down ** into valueFromFunction(). */ assert( (pExpr->flags & EP_TokenOnly)==0 || pCtx==0 ); if( op==TK_CAST ){ u8 aff = sqlite3AffinityType(pExpr->u.zToken,0); rc = valueFromExpr(db, pExpr->pLeft, enc, aff, ppVal, pCtx); testcase( rc!=SQLITE_OK ); if( *ppVal ){ sqlite3VdbeMemCast(*ppVal, aff, SQLITE_UTF8); sqlite3ValueApplyAffinity(*ppVal, affinity, SQLITE_UTF8); } return rc; } /* Handle negative integers in a single step. This is needed in the ** case when the value is -9223372036854775808. */ if( op==TK_UMINUS && (pExpr->pLeft->op==TK_INTEGER || pExpr->pLeft->op==TK_FLOAT) ){ pExpr = pExpr->pLeft; op = pExpr->op; negInt = -1; zNeg = "-"; } if( op==TK_STRING || op==TK_FLOAT || op==TK_INTEGER ){ pVal = valueNew(db, pCtx); if( pVal==0 ) goto no_mem; if( ExprHasProperty(pExpr, EP_IntValue) ){ sqlite3VdbeMemSetInt64(pVal, (i64)pExpr->u.iValue*negInt); }else{ zVal = sqlite3MPrintf(db, "%s%s", zNeg, pExpr->u.zToken); if( zVal==0 ) goto no_mem; sqlite3ValueSetStr(pVal, -1, zVal, SQLITE_UTF8, SQLITE_DYNAMIC); } if( (op==TK_INTEGER || op==TK_FLOAT ) && affinity==SQLITE_AFF_BLOB ){ sqlite3ValueApplyAffinity(pVal, SQLITE_AFF_NUMERIC, SQLITE_UTF8); }else{ sqlite3ValueApplyAffinity(pVal, affinity, SQLITE_UTF8); } if( pVal->flags & (MEM_Int|MEM_Real) ) pVal->flags &= ~MEM_Str; if( enc!=SQLITE_UTF8 ){ rc = sqlite3VdbeChangeEncoding(pVal, enc); } }else if( op==TK_UMINUS ) { /* This branch happens for multiple negative signs. Ex: -(-5) */ if( SQLITE_OK==sqlite3ValueFromExpr(db,pExpr->pLeft,enc,affinity,&pVal) && pVal!=0 ){ sqlite3VdbeMemNumerify(pVal); if( pVal->flags & MEM_Real ){ pVal->u.r = -pVal->u.r; }else if( pVal->u.i==SMALLEST_INT64 ){ pVal->u.r = -(double)SMALLEST_INT64; MemSetTypeFlag(pVal, MEM_Real); }else{ pVal->u.i = -pVal->u.i; } sqlite3ValueApplyAffinity(pVal, affinity, enc); } }else if( op==TK_NULL ){ pVal = valueNew(db, pCtx); if( pVal==0 ) goto no_mem; } #ifndef SQLITE_OMIT_BLOB_LITERAL else if( op==TK_BLOB ){ int nVal; assert( pExpr->u.zToken[0]=='x' || pExpr->u.zToken[0]=='X' ); assert( pExpr->u.zToken[1]=='\'' ); pVal = valueNew(db, pCtx); if( !pVal ) goto no_mem; zVal = &pExpr->u.zToken[2]; nVal = sqlite3Strlen30(zVal)-1; assert( zVal[nVal]=='\'' ); sqlite3VdbeMemSetStr(pVal, sqlite3HexToBlob(db, zVal, nVal), nVal/2, 0, SQLITE_DYNAMIC); } #endif #ifdef SQLITE_ENABLE_STAT3_OR_STAT4 else if( op==TK_FUNCTION && pCtx!=0 ){ rc = valueFromFunction(db, pExpr, enc, affinity, &pVal, pCtx); } #endif *ppVal = pVal; return rc; no_mem: sqlite3OomFault(db); sqlite3DbFree(db, zVal); assert( *ppVal==0 ); #ifdef SQLITE_ENABLE_STAT3_OR_STAT4 if( pCtx==0 ) sqlite3ValueFree(pVal); #else assert( pCtx==0 ); sqlite3ValueFree(pVal); #endif return SQLITE_NOMEM_BKPT; } /* ** Create a new sqlite3_value object, containing the value of pExpr. ** ** This only works for very simple expressions that consist of one constant ** token (i.e. "5", "5.1", "'a string'"). If the expression can ** be converted directly into a value, then the value is allocated and ** a pointer written to *ppVal. The caller is responsible for deallocating ** the value by passing it to sqlite3ValueFree() later on. If the expression ** cannot be converted to a value, then *ppVal is set to NULL. */ SQLITE_PRIVATE int sqlite3ValueFromExpr( sqlite3 *db, /* The database connection */ Expr *pExpr, /* The expression to evaluate */ u8 enc, /* Encoding to use */ u8 affinity, /* Affinity to use */ sqlite3_value **ppVal /* Write the new value here */ ){ return pExpr ? valueFromExpr(db, pExpr, enc, affinity, ppVal, 0) : 0; } #ifdef SQLITE_ENABLE_STAT3_OR_STAT4 /* ** The implementation of the sqlite_record() function. This function accepts ** a single argument of any type. The return value is a formatted database ** record (a blob) containing the argument value. ** ** This is used to convert the value stored in the 'sample' column of the ** sqlite_stat3 table to the record format SQLite uses internally. */ static void recordFunc( sqlite3_context *context, int argc, sqlite3_value **argv ){ const int file_format = 1; u32 iSerial; /* Serial type */ int nSerial; /* Bytes of space for iSerial as varint */ u32 nVal; /* Bytes of space required for argv[0] */ int nRet; sqlite3 *db; u8 *aRet; UNUSED_PARAMETER( argc ); iSerial = sqlite3VdbeSerialType(argv[0], file_format, &nVal); nSerial = sqlite3VarintLen(iSerial); db = sqlite3_context_db_handle(context); nRet = 1 + nSerial + nVal; aRet = sqlite3DbMallocRawNN(db, nRet); if( aRet==0 ){ sqlite3_result_error_nomem(context); }else{ aRet[0] = nSerial+1; putVarint32(&aRet[1], iSerial); sqlite3VdbeSerialPut(&aRet[1+nSerial], argv[0], iSerial); sqlite3_result_blob(context, aRet, nRet, SQLITE_TRANSIENT); sqlite3DbFree(db, aRet); } } /* ** Register built-in functions used to help read ANALYZE data. */ SQLITE_PRIVATE void sqlite3AnalyzeFunctions(void){ static FuncDef aAnalyzeTableFuncs[] = { FUNCTION(sqlite_record, 1, 0, 0, recordFunc), }; sqlite3InsertBuiltinFuncs(aAnalyzeTableFuncs, ArraySize(aAnalyzeTableFuncs)); } /* ** Attempt to extract a value from pExpr and use it to construct *ppVal. ** ** If pAlloc is not NULL, then an UnpackedRecord object is created for ** pAlloc if one does not exist and the new value is added to the ** UnpackedRecord object. ** ** A value is extracted in the following cases: ** ** * (pExpr==0). In this case the value is assumed to be an SQL NULL, ** ** * The expression is a bound variable, and this is a reprepare, or ** ** * The expression is a literal value. ** ** On success, *ppVal is made to point to the extracted value. The caller ** is responsible for ensuring that the value is eventually freed. */ static int stat4ValueFromExpr( Parse *pParse, /* Parse context */ Expr *pExpr, /* The expression to extract a value from */ u8 affinity, /* Affinity to use */ struct ValueNewStat4Ctx *pAlloc,/* How to allocate space. Or NULL */ sqlite3_value **ppVal /* OUT: New value object (or NULL) */ ){ int rc = SQLITE_OK; sqlite3_value *pVal = 0; sqlite3 *db = pParse->db; /* Skip over any TK_COLLATE nodes */ pExpr = sqlite3ExprSkipCollate(pExpr); if( !pExpr ){ pVal = valueNew(db, pAlloc); if( pVal ){ sqlite3VdbeMemSetNull((Mem*)pVal); } }else if( pExpr->op==TK_VARIABLE || NEVER(pExpr->op==TK_REGISTER && pExpr->op2==TK_VARIABLE) ){ Vdbe *v; int iBindVar = pExpr->iColumn; sqlite3VdbeSetVarmask(pParse->pVdbe, iBindVar); if( (v = pParse->pReprepare)!=0 ){ pVal = valueNew(db, pAlloc); if( pVal ){ rc = sqlite3VdbeMemCopy((Mem*)pVal, &v->aVar[iBindVar-1]); if( rc==SQLITE_OK ){ sqlite3ValueApplyAffinity(pVal, affinity, ENC(db)); } pVal->db = pParse->db; } } }else{ rc = valueFromExpr(db, pExpr, ENC(db), affinity, &pVal, pAlloc); } assert( pVal==0 || pVal->db==db ); *ppVal = pVal; return rc; } /* ** This function is used to allocate and populate UnpackedRecord ** structures intended to be compared against sample index keys stored ** in the sqlite_stat4 table. ** ** A single call to this function populates zero or more fields of the ** record starting with field iVal (fields are numbered from left to ** right starting with 0). A single field is populated if: ** ** * (pExpr==0). In this case the value is assumed to be an SQL NULL, ** ** * The expression is a bound variable, and this is a reprepare, or ** ** * The sqlite3ValueFromExpr() function is able to extract a value ** from the expression (i.e. the expression is a literal value). ** ** Or, if pExpr is a TK_VECTOR, one field is populated for each of the ** vector components that match either of the two latter criteria listed ** above. ** ** Before any value is appended to the record, the affinity of the ** corresponding column within index pIdx is applied to it. Before ** this function returns, output parameter *pnExtract is set to the ** number of values appended to the record. ** ** When this function is called, *ppRec must either point to an object ** allocated by an earlier call to this function, or must be NULL. If it ** is NULL and a value can be successfully extracted, a new UnpackedRecord ** is allocated (and *ppRec set to point to it) before returning. ** ** Unless an error is encountered, SQLITE_OK is returned. It is not an ** error if a value cannot be extracted from pExpr. If an error does ** occur, an SQLite error code is returned. */ SQLITE_PRIVATE int sqlite3Stat4ProbeSetValue( Parse *pParse, /* Parse context */ Index *pIdx, /* Index being probed */ UnpackedRecord **ppRec, /* IN/OUT: Probe record */ Expr *pExpr, /* The expression to extract a value from */ int nElem, /* Maximum number of values to append */ int iVal, /* Array element to populate */ int *pnExtract /* OUT: Values appended to the record */ ){ int rc = SQLITE_OK; int nExtract = 0; if( pExpr==0 || pExpr->op!=TK_SELECT ){ int i; struct ValueNewStat4Ctx alloc; alloc.pParse = pParse; alloc.pIdx = pIdx; alloc.ppRec = ppRec; for(i=0; idb, pIdx, iVal+i); alloc.iVal = iVal+i; rc = stat4ValueFromExpr(pParse, pElem, aff, &alloc, &pVal); if( !pVal ) break; nExtract++; } } *pnExtract = nExtract; return rc; } /* ** Attempt to extract a value from expression pExpr using the methods ** as described for sqlite3Stat4ProbeSetValue() above. ** ** If successful, set *ppVal to point to a new value object and return ** SQLITE_OK. If no value can be extracted, but no other error occurs ** (e.g. OOM), return SQLITE_OK and set *ppVal to NULL. Or, if an error ** does occur, return an SQLite error code. The final value of *ppVal ** is undefined in this case. */ SQLITE_PRIVATE int sqlite3Stat4ValueFromExpr( Parse *pParse, /* Parse context */ Expr *pExpr, /* The expression to extract a value from */ u8 affinity, /* Affinity to use */ sqlite3_value **ppVal /* OUT: New value object (or NULL) */ ){ return stat4ValueFromExpr(pParse, pExpr, affinity, 0, ppVal); } /* ** Extract the iCol-th column from the nRec-byte record in pRec. Write ** the column value into *ppVal. If *ppVal is initially NULL then a new ** sqlite3_value object is allocated. ** ** If *ppVal is initially NULL then the caller is responsible for ** ensuring that the value written into *ppVal is eventually freed. */ SQLITE_PRIVATE int sqlite3Stat4Column( sqlite3 *db, /* Database handle */ const void *pRec, /* Pointer to buffer containing record */ int nRec, /* Size of buffer pRec in bytes */ int iCol, /* Column to extract */ sqlite3_value **ppVal /* OUT: Extracted value */ ){ u32 t; /* a column type code */ int nHdr; /* Size of the header in the record */ int iHdr; /* Next unread header byte */ int iField; /* Next unread data byte */ int szField; /* Size of the current data field */ int i; /* Column index */ u8 *a = (u8*)pRec; /* Typecast byte array */ Mem *pMem = *ppVal; /* Write result into this Mem object */ assert( iCol>0 ); iHdr = getVarint32(a, nHdr); if( nHdr>nRec || iHdr>=nHdr ) return SQLITE_CORRUPT_BKPT; iField = nHdr; for(i=0; i<=iCol; i++){ iHdr += getVarint32(&a[iHdr], t); testcase( iHdr==nHdr ); testcase( iHdr==nHdr+1 ); if( iHdr>nHdr ) return SQLITE_CORRUPT_BKPT; szField = sqlite3VdbeSerialTypeLen(t); iField += szField; } testcase( iField==nRec ); testcase( iField==nRec+1 ); if( iField>nRec ) return SQLITE_CORRUPT_BKPT; if( pMem==0 ){ pMem = *ppVal = sqlite3ValueNew(db); if( pMem==0 ) return SQLITE_NOMEM_BKPT; } sqlite3VdbeSerialGet(&a[iField-szField], t, pMem); pMem->enc = ENC(db); return SQLITE_OK; } /* ** Unless it is NULL, the argument must be an UnpackedRecord object returned ** by an earlier call to sqlite3Stat4ProbeSetValue(). This call deletes ** the object. */ SQLITE_PRIVATE void sqlite3Stat4ProbeFree(UnpackedRecord *pRec){ if( pRec ){ int i; int nCol = pRec->pKeyInfo->nField+pRec->pKeyInfo->nXField; Mem *aMem = pRec->aMem; sqlite3 *db = aMem[0].db; for(i=0; ipKeyInfo); sqlite3DbFree(db, pRec); } } #endif /* ifdef SQLITE_ENABLE_STAT4 */ /* ** Change the string value of an sqlite3_value object */ SQLITE_PRIVATE void sqlite3ValueSetStr( sqlite3_value *v, /* Value to be set */ int n, /* Length of string z */ const void *z, /* Text of the new string */ u8 enc, /* Encoding to use */ void (*xDel)(void*) /* Destructor for the string */ ){ if( v ) sqlite3VdbeMemSetStr((Mem *)v, z, n, enc, xDel); } /* ** Free an sqlite3_value object */ SQLITE_PRIVATE void sqlite3ValueFree(sqlite3_value *v){ if( !v ) return; sqlite3VdbeMemRelease((Mem *)v); sqlite3DbFree(((Mem*)v)->db, v); } /* ** The sqlite3ValueBytes() routine returns the number of bytes in the ** sqlite3_value object assuming that it uses the encoding "enc". ** The valueBytes() routine is a helper function. */ static SQLITE_NOINLINE int valueBytes(sqlite3_value *pVal, u8 enc){ return valueToText(pVal, enc)!=0 ? pVal->n : 0; } SQLITE_PRIVATE int sqlite3ValueBytes(sqlite3_value *pVal, u8 enc){ Mem *p = (Mem*)pVal; assert( (p->flags & MEM_Null)==0 || (p->flags & (MEM_Str|MEM_Blob))==0 ); if( (p->flags & MEM_Str)!=0 && pVal->enc==enc ){ return p->n; } if( (p->flags & MEM_Blob)!=0 ){ if( p->flags & MEM_Zero ){ return p->n + p->u.nZero; }else{ return p->n; } } if( p->flags & MEM_Null ) return 0; return valueBytes(pVal, enc); } /************** End of vdbemem.c *********************************************/ /************** Begin file vdbeaux.c *****************************************/ /* ** 2003 September 6 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ************************************************************************* ** This file contains code used for creating, destroying, and populating ** a VDBE (or an "sqlite3_stmt" as it is known to the outside world.) */ /* #include "sqliteInt.h" */ /* #include "vdbeInt.h" */ /* ** Create a new virtual database engine. */ SQLITE_PRIVATE Vdbe *sqlite3VdbeCreate(Parse *pParse){ sqlite3 *db = pParse->db; Vdbe *p; p = sqlite3DbMallocRawNN(db, sizeof(Vdbe) ); if( p==0 ) return 0; memset(&p->aOp, 0, sizeof(Vdbe)-offsetof(Vdbe,aOp)); p->db = db; if( db->pVdbe ){ db->pVdbe->pPrev = p; } p->pNext = db->pVdbe; p->pPrev = 0; db->pVdbe = p; p->magic = VDBE_MAGIC_INIT; p->pParse = pParse; assert( pParse->aLabel==0 ); assert( pParse->nLabel==0 ); assert( pParse->nOpAlloc==0 ); assert( pParse->szOpAlloc==0 ); return p; } /* ** Change the error string stored in Vdbe.zErrMsg */ SQLITE_PRIVATE void sqlite3VdbeError(Vdbe *p, const char *zFormat, ...){ va_list ap; sqlite3DbFree(p->db, p->zErrMsg); va_start(ap, zFormat); p->zErrMsg = sqlite3VMPrintf(p->db, zFormat, ap); va_end(ap); } /* ** Remember the SQL string for a prepared statement. */ SQLITE_PRIVATE void sqlite3VdbeSetSql(Vdbe *p, const char *z, int n, int isPrepareV2){ assert( isPrepareV2==1 || isPrepareV2==0 ); if( p==0 ) return; #if defined(SQLITE_OMIT_TRACE) && !defined(SQLITE_ENABLE_SQLLOG) if( !isPrepareV2 ) return; #endif assert( p->zSql==0 ); p->zSql = sqlite3DbStrNDup(p->db, z, n); p->isPrepareV2 = (u8)isPrepareV2; } /* ** Swap all content between two VDBE structures. */ SQLITE_PRIVATE void sqlite3VdbeSwap(Vdbe *pA, Vdbe *pB){ Vdbe tmp, *pTmp; char *zTmp; assert( pA->db==pB->db ); tmp = *pA; *pA = *pB; *pB = tmp; pTmp = pA->pNext; pA->pNext = pB->pNext; pB->pNext = pTmp; pTmp = pA->pPrev; pA->pPrev = pB->pPrev; pB->pPrev = pTmp; zTmp = pA->zSql; pA->zSql = pB->zSql; pB->zSql = zTmp; pB->isPrepareV2 = pA->isPrepareV2; } /* ** Resize the Vdbe.aOp array so that it is at least nOp elements larger ** than its current size. nOp is guaranteed to be less than or equal ** to 1024/sizeof(Op). ** ** If an out-of-memory error occurs while resizing the array, return ** SQLITE_NOMEM. In this case Vdbe.aOp and Parse.nOpAlloc remain ** unchanged (this is so that any opcodes already allocated can be ** correctly deallocated along with the rest of the Vdbe). */ static int growOpArray(Vdbe *v, int nOp){ VdbeOp *pNew; Parse *p = v->pParse; /* The SQLITE_TEST_REALLOC_STRESS compile-time option is designed to force ** more frequent reallocs and hence provide more opportunities for ** simulated OOM faults. SQLITE_TEST_REALLOC_STRESS is generally used ** during testing only. With SQLITE_TEST_REALLOC_STRESS grow the op array ** by the minimum* amount required until the size reaches 512. Normal ** operation (without SQLITE_TEST_REALLOC_STRESS) is to double the current ** size of the op array or add 1KB of space, whichever is smaller. */ #ifdef SQLITE_TEST_REALLOC_STRESS int nNew = (p->nOpAlloc>=512 ? p->nOpAlloc*2 : p->nOpAlloc+nOp); #else int nNew = (p->nOpAlloc ? p->nOpAlloc*2 : (int)(1024/sizeof(Op))); UNUSED_PARAMETER(nOp); #endif assert( nOp<=(1024/sizeof(Op)) ); assert( nNew>=(p->nOpAlloc+nOp) ); pNew = sqlite3DbRealloc(p->db, v->aOp, nNew*sizeof(Op)); if( pNew ){ p->szOpAlloc = sqlite3DbMallocSize(p->db, pNew); p->nOpAlloc = p->szOpAlloc/sizeof(Op); v->aOp = pNew; } return (pNew ? SQLITE_OK : SQLITE_NOMEM_BKPT); } #ifdef SQLITE_DEBUG /* This routine is just a convenient place to set a breakpoint that will ** fire after each opcode is inserted and displayed using ** "PRAGMA vdbe_addoptrace=on". */ static void test_addop_breakpoint(void){ static int n = 0; n++; } #endif /* ** Add a new instruction to the list of instructions current in the ** VDBE. Return the address of the new instruction. ** ** Parameters: ** ** p Pointer to the VDBE ** ** op The opcode for this instruction ** ** p1, p2, p3 Operands ** ** Use the sqlite3VdbeResolveLabel() function to fix an address and ** the sqlite3VdbeChangeP4() function to change the value of the P4 ** operand. */ static SQLITE_NOINLINE int growOp3(Vdbe *p, int op, int p1, int p2, int p3){ assert( p->pParse->nOpAlloc<=p->nOp ); if( growOpArray(p, 1) ) return 1; assert( p->pParse->nOpAlloc>p->nOp ); return sqlite3VdbeAddOp3(p, op, p1, p2, p3); } SQLITE_PRIVATE int sqlite3VdbeAddOp3(Vdbe *p, int op, int p1, int p2, int p3){ int i; VdbeOp *pOp; i = p->nOp; assert( p->magic==VDBE_MAGIC_INIT ); assert( op>=0 && op<0xff ); if( p->pParse->nOpAlloc<=i ){ return growOp3(p, op, p1, p2, p3); } p->nOp++; pOp = &p->aOp[i]; pOp->opcode = (u8)op; pOp->p5 = 0; pOp->p1 = p1; pOp->p2 = p2; pOp->p3 = p3; pOp->p4.p = 0; pOp->p4type = P4_NOTUSED; #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS pOp->zComment = 0; #endif #ifdef SQLITE_DEBUG if( p->db->flags & SQLITE_VdbeAddopTrace ){ int jj, kk; Parse *pParse = p->pParse; for(jj=kk=0; jjnColCache; jj++){ struct yColCache *x = pParse->aColCache + jj; printf(" r[%d]={%d:%d}", x->iReg, x->iTable, x->iColumn); kk++; } if( kk ) printf("\n"); sqlite3VdbePrintOp(0, i, &p->aOp[i]); test_addop_breakpoint(); } #endif #ifdef VDBE_PROFILE pOp->cycles = 0; pOp->cnt = 0; #endif #ifdef SQLITE_VDBE_COVERAGE pOp->iSrcLine = 0; #endif return i; } SQLITE_PRIVATE int sqlite3VdbeAddOp0(Vdbe *p, int op){ return sqlite3VdbeAddOp3(p, op, 0, 0, 0); } SQLITE_PRIVATE int sqlite3VdbeAddOp1(Vdbe *p, int op, int p1){ return sqlite3VdbeAddOp3(p, op, p1, 0, 0); } SQLITE_PRIVATE int sqlite3VdbeAddOp2(Vdbe *p, int op, int p1, int p2){ return sqlite3VdbeAddOp3(p, op, p1, p2, 0); } /* Generate code for an unconditional jump to instruction iDest */ SQLITE_PRIVATE int sqlite3VdbeGoto(Vdbe *p, int iDest){ return sqlite3VdbeAddOp3(p, OP_Goto, 0, iDest, 0); } /* Generate code to cause the string zStr to be loaded into ** register iDest */ SQLITE_PRIVATE int sqlite3VdbeLoadString(Vdbe *p, int iDest, const char *zStr){ return sqlite3VdbeAddOp4(p, OP_String8, 0, iDest, 0, zStr, 0); } /* ** Generate code that initializes multiple registers to string or integer ** constants. The registers begin with iDest and increase consecutively. ** One register is initialized for each characgter in zTypes[]. For each ** "s" character in zTypes[], the register is a string if the argument is ** not NULL, or OP_Null if the value is a null pointer. For each "i" character ** in zTypes[], the register is initialized to an integer. */ SQLITE_PRIVATE void sqlite3VdbeMultiLoad(Vdbe *p, int iDest, const char *zTypes, ...){ va_list ap; int i; char c; va_start(ap, zTypes); for(i=0; (c = zTypes[i])!=0; i++){ if( c=='s' ){ const char *z = va_arg(ap, const char*); sqlite3VdbeAddOp4(p, z==0 ? OP_Null : OP_String8, 0, iDest++, 0, z, 0); }else{ assert( c=='i' ); sqlite3VdbeAddOp2(p, OP_Integer, va_arg(ap, int), iDest++); } } va_end(ap); } /* ** Add an opcode that includes the p4 value as a pointer. */ SQLITE_PRIVATE int sqlite3VdbeAddOp4( Vdbe *p, /* Add the opcode to this VM */ int op, /* The new opcode */ int p1, /* The P1 operand */ int p2, /* The P2 operand */ int p3, /* The P3 operand */ const char *zP4, /* The P4 operand */ int p4type /* P4 operand type */ ){ int addr = sqlite3VdbeAddOp3(p, op, p1, p2, p3); sqlite3VdbeChangeP4(p, addr, zP4, p4type); return addr; } /* ** Add an opcode that includes the p4 value with a P4_INT64 or ** P4_REAL type. */ SQLITE_PRIVATE int sqlite3VdbeAddOp4Dup8( Vdbe *p, /* Add the opcode to this VM */ int op, /* The new opcode */ int p1, /* The P1 operand */ int p2, /* The P2 operand */ int p3, /* The P3 operand */ const u8 *zP4, /* The P4 operand */ int p4type /* P4 operand type */ ){ char *p4copy = sqlite3DbMallocRawNN(sqlite3VdbeDb(p), 8); if( p4copy ) memcpy(p4copy, zP4, 8); return sqlite3VdbeAddOp4(p, op, p1, p2, p3, p4copy, p4type); } /* ** Add an OP_ParseSchema opcode. This routine is broken out from ** sqlite3VdbeAddOp4() since it needs to also needs to mark all btrees ** as having been used. ** ** The zWhere string must have been obtained from sqlite3_malloc(). ** This routine will take ownership of the allocated memory. */ SQLITE_PRIVATE void sqlite3VdbeAddParseSchemaOp(Vdbe *p, int iDb, char *zWhere){ int j; sqlite3VdbeAddOp4(p, OP_ParseSchema, iDb, 0, 0, zWhere, P4_DYNAMIC); for(j=0; jdb->nDb; j++) sqlite3VdbeUsesBtree(p, j); } /* ** Add an opcode that includes the p4 value as an integer. */ SQLITE_PRIVATE int sqlite3VdbeAddOp4Int( Vdbe *p, /* Add the opcode to this VM */ int op, /* The new opcode */ int p1, /* The P1 operand */ int p2, /* The P2 operand */ int p3, /* The P3 operand */ int p4 /* The P4 operand as an integer */ ){ int addr = sqlite3VdbeAddOp3(p, op, p1, p2, p3); sqlite3VdbeChangeP4(p, addr, SQLITE_INT_TO_PTR(p4), P4_INT32); return addr; } /* Insert the end of a co-routine */ SQLITE_PRIVATE void sqlite3VdbeEndCoroutine(Vdbe *v, int regYield){ sqlite3VdbeAddOp1(v, OP_EndCoroutine, regYield); /* Clear the temporary register cache, thereby ensuring that each ** co-routine has its own independent set of registers, because co-routines ** might expect their registers to be preserved across an OP_Yield, and ** that could cause problems if two or more co-routines are using the same ** temporary register. */ v->pParse->nTempReg = 0; v->pParse->nRangeReg = 0; } /* ** Create a new symbolic label for an instruction that has yet to be ** coded. The symbolic label is really just a negative number. The ** label can be used as the P2 value of an operation. Later, when ** the label is resolved to a specific address, the VDBE will scan ** through its operation list and change all values of P2 which match ** the label into the resolved address. ** ** The VDBE knows that a P2 value is a label because labels are ** always negative and P2 values are suppose to be non-negative. ** Hence, a negative P2 value is a label that has yet to be resolved. ** ** Zero is returned if a malloc() fails. */ SQLITE_PRIVATE int sqlite3VdbeMakeLabel(Vdbe *v){ Parse *p = v->pParse; int i = p->nLabel++; assert( v->magic==VDBE_MAGIC_INIT ); if( (i & (i-1))==0 ){ p->aLabel = sqlite3DbReallocOrFree(p->db, p->aLabel, (i*2+1)*sizeof(p->aLabel[0])); } if( p->aLabel ){ p->aLabel[i] = -1; } return ADDR(i); } /* ** Resolve label "x" to be the address of the next instruction to ** be inserted. The parameter "x" must have been obtained from ** a prior call to sqlite3VdbeMakeLabel(). */ SQLITE_PRIVATE void sqlite3VdbeResolveLabel(Vdbe *v, int x){ Parse *p = v->pParse; int j = ADDR(x); assert( v->magic==VDBE_MAGIC_INIT ); assert( jnLabel ); assert( j>=0 ); if( p->aLabel ){ p->aLabel[j] = v->nOp; } } /* ** Mark the VDBE as one that can only be run one time. */ SQLITE_PRIVATE void sqlite3VdbeRunOnlyOnce(Vdbe *p){ p->runOnlyOnce = 1; } /* ** Mark the VDBE as one that can only be run multiple times. */ SQLITE_PRIVATE void sqlite3VdbeReusable(Vdbe *p){ p->runOnlyOnce = 0; } #ifdef SQLITE_DEBUG /* sqlite3AssertMayAbort() logic */ /* ** The following type and function are used to iterate through all opcodes ** in a Vdbe main program and each of the sub-programs (triggers) it may ** invoke directly or indirectly. It should be used as follows: ** ** Op *pOp; ** VdbeOpIter sIter; ** ** memset(&sIter, 0, sizeof(sIter)); ** sIter.v = v; // v is of type Vdbe* ** while( (pOp = opIterNext(&sIter)) ){ ** // Do something with pOp ** } ** sqlite3DbFree(v->db, sIter.apSub); ** */ typedef struct VdbeOpIter VdbeOpIter; struct VdbeOpIter { Vdbe *v; /* Vdbe to iterate through the opcodes of */ SubProgram **apSub; /* Array of subprograms */ int nSub; /* Number of entries in apSub */ int iAddr; /* Address of next instruction to return */ int iSub; /* 0 = main program, 1 = first sub-program etc. */ }; static Op *opIterNext(VdbeOpIter *p){ Vdbe *v = p->v; Op *pRet = 0; Op *aOp; int nOp; if( p->iSub<=p->nSub ){ if( p->iSub==0 ){ aOp = v->aOp; nOp = v->nOp; }else{ aOp = p->apSub[p->iSub-1]->aOp; nOp = p->apSub[p->iSub-1]->nOp; } assert( p->iAddriAddr]; p->iAddr++; if( p->iAddr==nOp ){ p->iSub++; p->iAddr = 0; } if( pRet->p4type==P4_SUBPROGRAM ){ int nByte = (p->nSub+1)*sizeof(SubProgram*); int j; for(j=0; jnSub; j++){ if( p->apSub[j]==pRet->p4.pProgram ) break; } if( j==p->nSub ){ p->apSub = sqlite3DbReallocOrFree(v->db, p->apSub, nByte); if( !p->apSub ){ pRet = 0; }else{ p->apSub[p->nSub++] = pRet->p4.pProgram; } } } } return pRet; } /* ** Check if the program stored in the VM associated with pParse may ** throw an ABORT exception (causing the statement, but not entire transaction ** to be rolled back). This condition is true if the main program or any ** sub-programs contains any of the following: ** ** * OP_Halt with P1=SQLITE_CONSTRAINT and P2=OE_Abort. ** * OP_HaltIfNull with P1=SQLITE_CONSTRAINT and P2=OE_Abort. ** * OP_Destroy ** * OP_VUpdate ** * OP_VRename ** * OP_FkCounter with P2==0 (immediate foreign key constraint) ** * OP_CreateTable and OP_InitCoroutine (for CREATE TABLE AS SELECT ...) ** ** Then check that the value of Parse.mayAbort is true if an ** ABORT may be thrown, or false otherwise. Return true if it does ** match, or false otherwise. This function is intended to be used as ** part of an assert statement in the compiler. Similar to: ** ** assert( sqlite3VdbeAssertMayAbort(pParse->pVdbe, pParse->mayAbort) ); */ SQLITE_PRIVATE int sqlite3VdbeAssertMayAbort(Vdbe *v, int mayAbort){ int hasAbort = 0; int hasFkCounter = 0; int hasCreateTable = 0; int hasInitCoroutine = 0; Op *pOp; VdbeOpIter sIter; memset(&sIter, 0, sizeof(sIter)); sIter.v = v; while( (pOp = opIterNext(&sIter))!=0 ){ int opcode = pOp->opcode; if( opcode==OP_Destroy || opcode==OP_VUpdate || opcode==OP_VRename || ((opcode==OP_Halt || opcode==OP_HaltIfNull) && ((pOp->p1&0xff)==SQLITE_CONSTRAINT && pOp->p2==OE_Abort)) ){ hasAbort = 1; break; } if( opcode==OP_CreateTable ) hasCreateTable = 1; if( opcode==OP_InitCoroutine ) hasInitCoroutine = 1; #ifndef SQLITE_OMIT_FOREIGN_KEY if( opcode==OP_FkCounter && pOp->p1==0 && pOp->p2==1 ){ hasFkCounter = 1; } #endif } sqlite3DbFree(v->db, sIter.apSub); /* Return true if hasAbort==mayAbort. Or if a malloc failure occurred. ** If malloc failed, then the while() loop above may not have iterated ** through all opcodes and hasAbort may be set incorrectly. Return ** true for this case to prevent the assert() in the callers frame ** from failing. */ return ( v->db->mallocFailed || hasAbort==mayAbort || hasFkCounter || (hasCreateTable && hasInitCoroutine) ); } #endif /* SQLITE_DEBUG - the sqlite3AssertMayAbort() function */ /* ** This routine is called after all opcodes have been inserted. It loops ** through all the opcodes and fixes up some details. ** ** (1) For each jump instruction with a negative P2 value (a label) ** resolve the P2 value to an actual address. ** ** (2) Compute the maximum number of arguments used by any SQL function ** and store that value in *pMaxFuncArgs. ** ** (3) Update the Vdbe.readOnly and Vdbe.bIsReader flags to accurately ** indicate what the prepared statement actually does. ** ** (4) Initialize the p4.xAdvance pointer on opcodes that use it. ** ** (5) Reclaim the memory allocated for storing labels. ** ** This routine will only function correctly if the mkopcodeh.tcl generator ** script numbers the opcodes correctly. Changes to this routine must be ** coordinated with changes to mkopcodeh.tcl. */ static void resolveP2Values(Vdbe *p, int *pMaxFuncArgs){ int nMaxArgs = *pMaxFuncArgs; Op *pOp; Parse *pParse = p->pParse; int *aLabel = pParse->aLabel; p->readOnly = 1; p->bIsReader = 0; pOp = &p->aOp[p->nOp-1]; while(1){ /* Only JUMP opcodes and the short list of special opcodes in the switch ** below need to be considered. The mkopcodeh.tcl generator script groups ** all these opcodes together near the front of the opcode list. Skip ** any opcode that does not need processing by virtual of the fact that ** it is larger than SQLITE_MX_JUMP_OPCODE, as a performance optimization. */ if( pOp->opcode<=SQLITE_MX_JUMP_OPCODE ){ /* NOTE: Be sure to update mkopcodeh.tcl when adding or removing ** cases from this switch! */ switch( pOp->opcode ){ case OP_Transaction: { if( pOp->p2!=0 ) p->readOnly = 0; /* fall thru */ } case OP_AutoCommit: case OP_Savepoint: { p->bIsReader = 1; break; } #ifndef SQLITE_OMIT_WAL case OP_Checkpoint: #endif case OP_Vacuum: case OP_JournalMode: { p->readOnly = 0; p->bIsReader = 1; break; } #ifndef SQLITE_OMIT_VIRTUALTABLE case OP_VUpdate: { if( pOp->p2>nMaxArgs ) nMaxArgs = pOp->p2; break; } case OP_VFilter: { int n; assert( (pOp - p->aOp) >= 3 ); assert( pOp[-1].opcode==OP_Integer ); n = pOp[-1].p1; if( n>nMaxArgs ) nMaxArgs = n; break; } #endif case OP_Next: case OP_NextIfOpen: case OP_SorterNext: { pOp->p4.xAdvance = sqlite3BtreeNext; pOp->p4type = P4_ADVANCE; break; } case OP_Prev: case OP_PrevIfOpen: { pOp->p4.xAdvance = sqlite3BtreePrevious; pOp->p4type = P4_ADVANCE; break; } } if( (sqlite3OpcodeProperty[pOp->opcode] & OPFLG_JUMP)!=0 && pOp->p2<0 ){ assert( ADDR(pOp->p2)nLabel ); pOp->p2 = aLabel[ADDR(pOp->p2)]; } } if( pOp==p->aOp ) break; pOp--; } sqlite3DbFree(p->db, pParse->aLabel); pParse->aLabel = 0; pParse->nLabel = 0; *pMaxFuncArgs = nMaxArgs; assert( p->bIsReader!=0 || DbMaskAllZero(p->btreeMask) ); } /* ** Return the address of the next instruction to be inserted. */ SQLITE_PRIVATE int sqlite3VdbeCurrentAddr(Vdbe *p){ assert( p->magic==VDBE_MAGIC_INIT ); return p->nOp; } /* ** Verify that at least N opcode slots are available in p without ** having to malloc for more space (except when compiled using ** SQLITE_TEST_REALLOC_STRESS). This interface is used during testing ** to verify that certain calls to sqlite3VdbeAddOpList() can never ** fail due to a OOM fault and hence that the return value from ** sqlite3VdbeAddOpList() will always be non-NULL. */ #if defined(SQLITE_DEBUG) && !defined(SQLITE_TEST_REALLOC_STRESS) SQLITE_PRIVATE void sqlite3VdbeVerifyNoMallocRequired(Vdbe *p, int N){ assert( p->nOp + N <= p->pParse->nOpAlloc ); } #endif /* ** This function returns a pointer to the array of opcodes associated with ** the Vdbe passed as the first argument. It is the callers responsibility ** to arrange for the returned array to be eventually freed using the ** vdbeFreeOpArray() function. ** ** Before returning, *pnOp is set to the number of entries in the returned ** array. Also, *pnMaxArg is set to the larger of its current value and ** the number of entries in the Vdbe.apArg[] array required to execute the ** returned program. */ SQLITE_PRIVATE VdbeOp *sqlite3VdbeTakeOpArray(Vdbe *p, int *pnOp, int *pnMaxArg){ VdbeOp *aOp = p->aOp; assert( aOp && !p->db->mallocFailed ); /* Check that sqlite3VdbeUsesBtree() was not called on this VM */ assert( DbMaskAllZero(p->btreeMask) ); resolveP2Values(p, pnMaxArg); *pnOp = p->nOp; p->aOp = 0; return aOp; } /* ** Add a whole list of operations to the operation stack. Return a ** pointer to the first operation inserted. ** ** Non-zero P2 arguments to jump instructions are automatically adjusted ** so that the jump target is relative to the first operation inserted. */ SQLITE_PRIVATE VdbeOp *sqlite3VdbeAddOpList( Vdbe *p, /* Add opcodes to the prepared statement */ int nOp, /* Number of opcodes to add */ VdbeOpList const *aOp, /* The opcodes to be added */ int iLineno /* Source-file line number of first opcode */ ){ int i; VdbeOp *pOut, *pFirst; assert( nOp>0 ); assert( p->magic==VDBE_MAGIC_INIT ); if( p->nOp + nOp > p->pParse->nOpAlloc && growOpArray(p, nOp) ){ return 0; } pFirst = pOut = &p->aOp[p->nOp]; for(i=0; iopcode = aOp->opcode; pOut->p1 = aOp->p1; pOut->p2 = aOp->p2; assert( aOp->p2>=0 ); if( (sqlite3OpcodeProperty[aOp->opcode] & OPFLG_JUMP)!=0 && aOp->p2>0 ){ pOut->p2 += p->nOp; } pOut->p3 = aOp->p3; pOut->p4type = P4_NOTUSED; pOut->p4.p = 0; pOut->p5 = 0; #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS pOut->zComment = 0; #endif #ifdef SQLITE_VDBE_COVERAGE pOut->iSrcLine = iLineno+i; #else (void)iLineno; #endif #ifdef SQLITE_DEBUG if( p->db->flags & SQLITE_VdbeAddopTrace ){ sqlite3VdbePrintOp(0, i+p->nOp, &p->aOp[i+p->nOp]); } #endif } p->nOp += nOp; return pFirst; } #if defined(SQLITE_ENABLE_STMT_SCANSTATUS) /* ** Add an entry to the array of counters managed by sqlite3_stmt_scanstatus(). */ SQLITE_PRIVATE void sqlite3VdbeScanStatus( Vdbe *p, /* VM to add scanstatus() to */ int addrExplain, /* Address of OP_Explain (or 0) */ int addrLoop, /* Address of loop counter */ int addrVisit, /* Address of rows visited counter */ LogEst nEst, /* Estimated number of output rows */ const char *zName /* Name of table or index being scanned */ ){ int nByte = (p->nScan+1) * sizeof(ScanStatus); ScanStatus *aNew; aNew = (ScanStatus*)sqlite3DbRealloc(p->db, p->aScan, nByte); if( aNew ){ ScanStatus *pNew = &aNew[p->nScan++]; pNew->addrExplain = addrExplain; pNew->addrLoop = addrLoop; pNew->addrVisit = addrVisit; pNew->nEst = nEst; pNew->zName = sqlite3DbStrDup(p->db, zName); p->aScan = aNew; } } #endif /* ** Change the value of the opcode, or P1, P2, P3, or P5 operands ** for a specific instruction. */ SQLITE_PRIVATE void sqlite3VdbeChangeOpcode(Vdbe *p, u32 addr, u8 iNewOpcode){ sqlite3VdbeGetOp(p,addr)->opcode = iNewOpcode; } SQLITE_PRIVATE void sqlite3VdbeChangeP1(Vdbe *p, u32 addr, int val){ sqlite3VdbeGetOp(p,addr)->p1 = val; } SQLITE_PRIVATE void sqlite3VdbeChangeP2(Vdbe *p, u32 addr, int val){ sqlite3VdbeGetOp(p,addr)->p2 = val; } SQLITE_PRIVATE void sqlite3VdbeChangeP3(Vdbe *p, u32 addr, int val){ sqlite3VdbeGetOp(p,addr)->p3 = val; } SQLITE_PRIVATE void sqlite3VdbeChangeP5(Vdbe *p, u8 p5){ assert( p->nOp>0 || p->db->mallocFailed ); if( p->nOp>0 ) p->aOp[p->nOp-1].p5 = p5; } /* ** Change the P2 operand of instruction addr so that it points to ** the address of the next instruction to be coded. */ SQLITE_PRIVATE void sqlite3VdbeJumpHere(Vdbe *p, int addr){ sqlite3VdbeChangeP2(p, addr, p->nOp); } /* ** If the input FuncDef structure is ephemeral, then free it. If ** the FuncDef is not ephermal, then do nothing. */ static void freeEphemeralFunction(sqlite3 *db, FuncDef *pDef){ if( (pDef->funcFlags & SQLITE_FUNC_EPHEM)!=0 ){ sqlite3DbFree(db, pDef); } } static void vdbeFreeOpArray(sqlite3 *, Op *, int); /* ** Delete a P4 value if necessary. */ static SQLITE_NOINLINE void freeP4Mem(sqlite3 *db, Mem *p){ if( p->szMalloc ) sqlite3DbFree(db, p->zMalloc); sqlite3DbFree(db, p); } static SQLITE_NOINLINE void freeP4FuncCtx(sqlite3 *db, sqlite3_context *p){ freeEphemeralFunction(db, p->pFunc); sqlite3DbFree(db, p); } static void freeP4(sqlite3 *db, int p4type, void *p4){ assert( db ); switch( p4type ){ case P4_FUNCCTX: { freeP4FuncCtx(db, (sqlite3_context*)p4); break; } case P4_REAL: case P4_INT64: case P4_DYNAMIC: case P4_INTARRAY: { sqlite3DbFree(db, p4); break; } case P4_KEYINFO: { if( db->pnBytesFreed==0 ) sqlite3KeyInfoUnref((KeyInfo*)p4); break; } #ifdef SQLITE_ENABLE_CURSOR_HINTS case P4_EXPR: { sqlite3ExprDelete(db, (Expr*)p4); break; } #endif case P4_MPRINTF: { if( db->pnBytesFreed==0 ) sqlite3_free(p4); break; } case P4_FUNCDEF: { freeEphemeralFunction(db, (FuncDef*)p4); break; } case P4_MEM: { if( db->pnBytesFreed==0 ){ sqlite3ValueFree((sqlite3_value*)p4); }else{ freeP4Mem(db, (Mem*)p4); } break; } case P4_VTAB : { if( db->pnBytesFreed==0 ) sqlite3VtabUnlock((VTable *)p4); break; } } } /* ** Free the space allocated for aOp and any p4 values allocated for the ** opcodes contained within. If aOp is not NULL it is assumed to contain ** nOp entries. */ static void vdbeFreeOpArray(sqlite3 *db, Op *aOp, int nOp){ if( aOp ){ Op *pOp; for(pOp=aOp; pOp<&aOp[nOp]; pOp++){ if( pOp->p4type ) freeP4(db, pOp->p4type, pOp->p4.p); #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS sqlite3DbFree(db, pOp->zComment); #endif } } sqlite3DbFree(db, aOp); } /* ** Link the SubProgram object passed as the second argument into the linked ** list at Vdbe.pSubProgram. This list is used to delete all sub-program ** objects when the VM is no longer required. */ SQLITE_PRIVATE void sqlite3VdbeLinkSubProgram(Vdbe *pVdbe, SubProgram *p){ p->pNext = pVdbe->pProgram; pVdbe->pProgram = p; } /* ** Change the opcode at addr into OP_Noop */ SQLITE_PRIVATE int sqlite3VdbeChangeToNoop(Vdbe *p, int addr){ VdbeOp *pOp; if( p->db->mallocFailed ) return 0; assert( addr>=0 && addrnOp ); pOp = &p->aOp[addr]; freeP4(p->db, pOp->p4type, pOp->p4.p); pOp->p4type = P4_NOTUSED; pOp->p4.z = 0; pOp->opcode = OP_Noop; return 1; } /* ** If the last opcode is "op" and it is not a jump destination, ** then remove it. Return true if and only if an opcode was removed. */ SQLITE_PRIVATE int sqlite3VdbeDeletePriorOpcode(Vdbe *p, u8 op){ if( p->nOp>0 && p->aOp[p->nOp-1].opcode==op ){ return sqlite3VdbeChangeToNoop(p, p->nOp-1); }else{ return 0; } } /* ** Change the value of the P4 operand for a specific instruction. ** This routine is useful when a large program is loaded from a ** static array using sqlite3VdbeAddOpList but we want to make a ** few minor changes to the program. ** ** If n>=0 then the P4 operand is dynamic, meaning that a copy of ** the string is made into memory obtained from sqlite3_malloc(). ** A value of n==0 means copy bytes of zP4 up to and including the ** first null byte. If n>0 then copy n+1 bytes of zP4. ** ** Other values of n (P4_STATIC, P4_COLLSEQ etc.) indicate that zP4 points ** to a string or structure that is guaranteed to exist for the lifetime of ** the Vdbe. In these cases we can just copy the pointer. ** ** If addr<0 then change P4 on the most recently inserted instruction. */ static void SQLITE_NOINLINE vdbeChangeP4Full( Vdbe *p, Op *pOp, const char *zP4, int n ){ if( pOp->p4type ){ freeP4(p->db, pOp->p4type, pOp->p4.p); pOp->p4type = 0; pOp->p4.p = 0; } if( n<0 ){ sqlite3VdbeChangeP4(p, (int)(pOp - p->aOp), zP4, n); }else{ if( n==0 ) n = sqlite3Strlen30(zP4); pOp->p4.z = sqlite3DbStrNDup(p->db, zP4, n); pOp->p4type = P4_DYNAMIC; } } SQLITE_PRIVATE void sqlite3VdbeChangeP4(Vdbe *p, int addr, const char *zP4, int n){ Op *pOp; sqlite3 *db; assert( p!=0 ); db = p->db; assert( p->magic==VDBE_MAGIC_INIT ); assert( p->aOp!=0 || db->mallocFailed ); if( db->mallocFailed ){ if( n!=P4_VTAB ) freeP4(db, n, (void*)*(char**)&zP4); return; } assert( p->nOp>0 ); assert( addrnOp ); if( addr<0 ){ addr = p->nOp - 1; } pOp = &p->aOp[addr]; if( n>=0 || pOp->p4type ){ vdbeChangeP4Full(p, pOp, zP4, n); return; } if( n==P4_INT32 ){ /* Note: this cast is safe, because the origin data point was an int ** that was cast to a (const char *). */ pOp->p4.i = SQLITE_PTR_TO_INT(zP4); pOp->p4type = P4_INT32; }else if( zP4!=0 ){ assert( n<0 ); pOp->p4.p = (void*)zP4; pOp->p4type = (signed char)n; if( n==P4_VTAB ) sqlite3VtabLock((VTable*)zP4); } } /* ** Set the P4 on the most recently added opcode to the KeyInfo for the ** index given. */ SQLITE_PRIVATE void sqlite3VdbeSetP4KeyInfo(Parse *pParse, Index *pIdx){ Vdbe *v = pParse->pVdbe; assert( v!=0 ); assert( pIdx!=0 ); sqlite3VdbeChangeP4(v, -1, (char*)sqlite3KeyInfoOfIndex(pParse, pIdx), P4_KEYINFO); } #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS /* ** Change the comment on the most recently coded instruction. Or ** insert a No-op and add the comment to that new instruction. This ** makes the code easier to read during debugging. None of this happens ** in a production build. */ static void vdbeVComment(Vdbe *p, const char *zFormat, va_list ap){ assert( p->nOp>0 || p->aOp==0 ); assert( p->aOp==0 || p->aOp[p->nOp-1].zComment==0 || p->db->mallocFailed ); if( p->nOp ){ assert( p->aOp ); sqlite3DbFree(p->db, p->aOp[p->nOp-1].zComment); p->aOp[p->nOp-1].zComment = sqlite3VMPrintf(p->db, zFormat, ap); } } SQLITE_PRIVATE void sqlite3VdbeComment(Vdbe *p, const char *zFormat, ...){ va_list ap; if( p ){ va_start(ap, zFormat); vdbeVComment(p, zFormat, ap); va_end(ap); } } SQLITE_PRIVATE void sqlite3VdbeNoopComment(Vdbe *p, const char *zFormat, ...){ va_list ap; if( p ){ sqlite3VdbeAddOp0(p, OP_Noop); va_start(ap, zFormat); vdbeVComment(p, zFormat, ap); va_end(ap); } } #endif /* NDEBUG */ #ifdef SQLITE_VDBE_COVERAGE /* ** Set the value if the iSrcLine field for the previously coded instruction. */ SQLITE_PRIVATE void sqlite3VdbeSetLineNumber(Vdbe *v, int iLine){ sqlite3VdbeGetOp(v,-1)->iSrcLine = iLine; } #endif /* SQLITE_VDBE_COVERAGE */ /* ** Return the opcode for a given address. If the address is -1, then ** return the most recently inserted opcode. ** ** If a memory allocation error has occurred prior to the calling of this ** routine, then a pointer to a dummy VdbeOp will be returned. That opcode ** is readable but not writable, though it is cast to a writable value. ** The return of a dummy opcode allows the call to continue functioning ** after an OOM fault without having to check to see if the return from ** this routine is a valid pointer. But because the dummy.opcode is 0, ** dummy will never be written to. This is verified by code inspection and ** by running with Valgrind. */ SQLITE_PRIVATE VdbeOp *sqlite3VdbeGetOp(Vdbe *p, int addr){ /* C89 specifies that the constant "dummy" will be initialized to all ** zeros, which is correct. MSVC generates a warning, nevertheless. */ static VdbeOp dummy; /* Ignore the MSVC warning about no initializer */ assert( p->magic==VDBE_MAGIC_INIT ); if( addr<0 ){ addr = p->nOp - 1; } assert( (addr>=0 && addrnOp) || p->db->mallocFailed ); if( p->db->mallocFailed ){ return (VdbeOp*)&dummy; }else{ return &p->aOp[addr]; } } #if defined(SQLITE_ENABLE_EXPLAIN_COMMENTS) /* ** Return an integer value for one of the parameters to the opcode pOp ** determined by character c. */ static int translateP(char c, const Op *pOp){ if( c=='1' ) return pOp->p1; if( c=='2' ) return pOp->p2; if( c=='3' ) return pOp->p3; if( c=='4' ) return pOp->p4.i; return pOp->p5; } /* ** Compute a string for the "comment" field of a VDBE opcode listing. ** ** The Synopsis: field in comments in the vdbe.c source file gets converted ** to an extra string that is appended to the sqlite3OpcodeName(). In the ** absence of other comments, this synopsis becomes the comment on the opcode. ** Some translation occurs: ** ** "PX" -> "r[X]" ** "PX@PY" -> "r[X..X+Y-1]" or "r[x]" if y is 0 or 1 ** "PX@PY+1" -> "r[X..X+Y]" or "r[x]" if y is 0 ** "PY..PY" -> "r[X..Y]" or "r[x]" if y<=x */ static int displayComment( const Op *pOp, /* The opcode to be commented */ const char *zP4, /* Previously obtained value for P4 */ char *zTemp, /* Write result here */ int nTemp /* Space available in zTemp[] */ ){ const char *zOpName; const char *zSynopsis; int nOpName; int ii, jj; char zAlt[50]; zOpName = sqlite3OpcodeName(pOp->opcode); nOpName = sqlite3Strlen30(zOpName); if( zOpName[nOpName+1] ){ int seenCom = 0; char c; zSynopsis = zOpName += nOpName + 1; if( strncmp(zSynopsis,"IF ",3)==0 ){ if( pOp->p5 & SQLITE_STOREP2 ){ sqlite3_snprintf(sizeof(zAlt), zAlt, "r[P2] = (%s)", zSynopsis+3); }else{ sqlite3_snprintf(sizeof(zAlt), zAlt, "if %s goto P2", zSynopsis+3); } zSynopsis = zAlt; } for(ii=jj=0; jjzComment); seenCom = 1; }else{ int v1 = translateP(c, pOp); int v2; sqlite3_snprintf(nTemp-jj, zTemp+jj, "%d", v1); if( strncmp(zSynopsis+ii+1, "@P", 2)==0 ){ ii += 3; jj += sqlite3Strlen30(zTemp+jj); v2 = translateP(zSynopsis[ii], pOp); if( strncmp(zSynopsis+ii+1,"+1",2)==0 ){ ii += 2; v2++; } if( v2>1 ){ sqlite3_snprintf(nTemp-jj, zTemp+jj, "..%d", v1+v2-1); } }else if( strncmp(zSynopsis+ii+1, "..P3", 4)==0 && pOp->p3==0 ){ ii += 4; } } jj += sqlite3Strlen30(zTemp+jj); }else{ zTemp[jj++] = c; } } if( !seenCom && jjzComment ){ sqlite3_snprintf(nTemp-jj, zTemp+jj, "; %s", pOp->zComment); jj += sqlite3Strlen30(zTemp+jj); } if( jjzComment ){ sqlite3_snprintf(nTemp, zTemp, "%s", pOp->zComment); jj = sqlite3Strlen30(zTemp); }else{ zTemp[0] = 0; jj = 0; } return jj; } #endif /* SQLITE_DEBUG */ #if VDBE_DISPLAY_P4 && defined(SQLITE_ENABLE_CURSOR_HINTS) /* ** Translate the P4.pExpr value for an OP_CursorHint opcode into text ** that can be displayed in the P4 column of EXPLAIN output. */ static void displayP4Expr(StrAccum *p, Expr *pExpr){ const char *zOp = 0; switch( pExpr->op ){ case TK_STRING: sqlite3XPrintf(p, "%Q", pExpr->u.zToken); break; case TK_INTEGER: sqlite3XPrintf(p, "%d", pExpr->u.iValue); break; case TK_NULL: sqlite3XPrintf(p, "NULL"); break; case TK_REGISTER: { sqlite3XPrintf(p, "r[%d]", pExpr->iTable); break; } case TK_COLUMN: { if( pExpr->iColumn<0 ){ sqlite3XPrintf(p, "rowid"); }else{ sqlite3XPrintf(p, "c%d", (int)pExpr->iColumn); } break; } case TK_LT: zOp = "LT"; break; case TK_LE: zOp = "LE"; break; case TK_GT: zOp = "GT"; break; case TK_GE: zOp = "GE"; break; case TK_NE: zOp = "NE"; break; case TK_EQ: zOp = "EQ"; break; case TK_IS: zOp = "IS"; break; case TK_ISNOT: zOp = "ISNOT"; break; case TK_AND: zOp = "AND"; break; case TK_OR: zOp = "OR"; break; case TK_PLUS: zOp = "ADD"; break; case TK_STAR: zOp = "MUL"; break; case TK_MINUS: zOp = "SUB"; break; case TK_REM: zOp = "REM"; break; case TK_BITAND: zOp = "BITAND"; break; case TK_BITOR: zOp = "BITOR"; break; case TK_SLASH: zOp = "DIV"; break; case TK_LSHIFT: zOp = "LSHIFT"; break; case TK_RSHIFT: zOp = "RSHIFT"; break; case TK_CONCAT: zOp = "CONCAT"; break; case TK_UMINUS: zOp = "MINUS"; break; case TK_UPLUS: zOp = "PLUS"; break; case TK_BITNOT: zOp = "BITNOT"; break; case TK_NOT: zOp = "NOT"; break; case TK_ISNULL: zOp = "ISNULL"; break; case TK_NOTNULL: zOp = "NOTNULL"; break; default: sqlite3XPrintf(p, "%s", "expr"); break; } if( zOp ){ sqlite3XPrintf(p, "%s(", zOp); displayP4Expr(p, pExpr->pLeft); if( pExpr->pRight ){ sqlite3StrAccumAppend(p, ",", 1); displayP4Expr(p, pExpr->pRight); } sqlite3StrAccumAppend(p, ")", 1); } } #endif /* VDBE_DISPLAY_P4 && defined(SQLITE_ENABLE_CURSOR_HINTS) */ #if VDBE_DISPLAY_P4 /* ** Compute a string that describes the P4 parameter for an opcode. ** Use zTemp for any required temporary buffer space. */ static char *displayP4(Op *pOp, char *zTemp, int nTemp){ char *zP4 = zTemp; StrAccum x; assert( nTemp>=20 ); sqlite3StrAccumInit(&x, 0, zTemp, nTemp, 0); switch( pOp->p4type ){ case P4_KEYINFO: { int j; KeyInfo *pKeyInfo = pOp->p4.pKeyInfo; assert( pKeyInfo->aSortOrder!=0 ); sqlite3XPrintf(&x, "k(%d", pKeyInfo->nField); for(j=0; jnField; j++){ CollSeq *pColl = pKeyInfo->aColl[j]; const char *zColl = pColl ? pColl->zName : ""; if( strcmp(zColl, "BINARY")==0 ) zColl = "B"; sqlite3XPrintf(&x, ",%s%s", pKeyInfo->aSortOrder[j] ? "-" : "", zColl); } sqlite3StrAccumAppend(&x, ")", 1); break; } #ifdef SQLITE_ENABLE_CURSOR_HINTS case P4_EXPR: { displayP4Expr(&x, pOp->p4.pExpr); break; } #endif case P4_COLLSEQ: { CollSeq *pColl = pOp->p4.pColl; sqlite3XPrintf(&x, "(%.20s)", pColl->zName); break; } case P4_FUNCDEF: { FuncDef *pDef = pOp->p4.pFunc; sqlite3XPrintf(&x, "%s(%d)", pDef->zName, pDef->nArg); break; } #ifdef SQLITE_DEBUG case P4_FUNCCTX: { FuncDef *pDef = pOp->p4.pCtx->pFunc; sqlite3XPrintf(&x, "%s(%d)", pDef->zName, pDef->nArg); break; } #endif case P4_INT64: { sqlite3XPrintf(&x, "%lld", *pOp->p4.pI64); break; } case P4_INT32: { sqlite3XPrintf(&x, "%d", pOp->p4.i); break; } case P4_REAL: { sqlite3XPrintf(&x, "%.16g", *pOp->p4.pReal); break; } case P4_MEM: { Mem *pMem = pOp->p4.pMem; if( pMem->flags & MEM_Str ){ zP4 = pMem->z; }else if( pMem->flags & MEM_Int ){ sqlite3XPrintf(&x, "%lld", pMem->u.i); }else if( pMem->flags & MEM_Real ){ sqlite3XPrintf(&x, "%.16g", pMem->u.r); }else if( pMem->flags & MEM_Null ){ zP4 = "NULL"; }else{ assert( pMem->flags & MEM_Blob ); zP4 = "(blob)"; } break; } #ifndef SQLITE_OMIT_VIRTUALTABLE case P4_VTAB: { sqlite3_vtab *pVtab = pOp->p4.pVtab->pVtab; sqlite3XPrintf(&x, "vtab:%p", pVtab); break; } #endif case P4_INTARRAY: { int i; int *ai = pOp->p4.ai; int n = ai[0]; /* The first element of an INTARRAY is always the ** count of the number of elements to follow */ for(i=1; ip4.pTab->zName); break; } default: { zP4 = pOp->p4.z; if( zP4==0 ){ zP4 = zTemp; zTemp[0] = 0; } } } sqlite3StrAccumFinish(&x); assert( zP4!=0 ); return zP4; } #endif /* VDBE_DISPLAY_P4 */ /* ** Declare to the Vdbe that the BTree object at db->aDb[i] is used. ** ** The prepared statements need to know in advance the complete set of ** attached databases that will be use. A mask of these databases ** is maintained in p->btreeMask. The p->lockMask value is the subset of ** p->btreeMask of databases that will require a lock. */ SQLITE_PRIVATE void sqlite3VdbeUsesBtree(Vdbe *p, int i){ assert( i>=0 && idb->nDb && i<(int)sizeof(yDbMask)*8 ); assert( i<(int)sizeof(p->btreeMask)*8 ); DbMaskSet(p->btreeMask, i); if( i!=1 && sqlite3BtreeSharable(p->db->aDb[i].pBt) ){ DbMaskSet(p->lockMask, i); } } #if !defined(SQLITE_OMIT_SHARED_CACHE) /* ** If SQLite is compiled to support shared-cache mode and to be threadsafe, ** this routine obtains the mutex associated with each BtShared structure ** that may be accessed by the VM passed as an argument. In doing so it also ** sets the BtShared.db member of each of the BtShared structures, ensuring ** that the correct busy-handler callback is invoked if required. ** ** If SQLite is not threadsafe but does support shared-cache mode, then ** sqlite3BtreeEnter() is invoked to set the BtShared.db variables ** of all of BtShared structures accessible via the database handle ** associated with the VM. ** ** If SQLite is not threadsafe and does not support shared-cache mode, this ** function is a no-op. ** ** The p->btreeMask field is a bitmask of all btrees that the prepared ** statement p will ever use. Let N be the number of bits in p->btreeMask ** corresponding to btrees that use shared cache. Then the runtime of ** this routine is N*N. But as N is rarely more than 1, this should not ** be a problem. */ SQLITE_PRIVATE void sqlite3VdbeEnter(Vdbe *p){ int i; sqlite3 *db; Db *aDb; int nDb; if( DbMaskAllZero(p->lockMask) ) return; /* The common case */ db = p->db; aDb = db->aDb; nDb = db->nDb; for(i=0; ilockMask,i) && ALWAYS(aDb[i].pBt!=0) ){ sqlite3BtreeEnter(aDb[i].pBt); } } } #endif #if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE>0 /* ** Unlock all of the btrees previously locked by a call to sqlite3VdbeEnter(). */ static SQLITE_NOINLINE void vdbeLeave(Vdbe *p){ int i; sqlite3 *db; Db *aDb; int nDb; db = p->db; aDb = db->aDb; nDb = db->nDb; for(i=0; ilockMask,i) && ALWAYS(aDb[i].pBt!=0) ){ sqlite3BtreeLeave(aDb[i].pBt); } } } SQLITE_PRIVATE void sqlite3VdbeLeave(Vdbe *p){ if( DbMaskAllZero(p->lockMask) ) return; /* The common case */ vdbeLeave(p); } #endif #if defined(VDBE_PROFILE) || defined(SQLITE_DEBUG) /* ** Print a single opcode. This routine is used for debugging only. */ SQLITE_PRIVATE void sqlite3VdbePrintOp(FILE *pOut, int pc, Op *pOp){ char *zP4; char zPtr[50]; char zCom[100]; static const char *zFormat1 = "%4d %-13s %4d %4d %4d %-13s %.2X %s\n"; if( pOut==0 ) pOut = stdout; zP4 = displayP4(pOp, zPtr, sizeof(zPtr)); #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS displayComment(pOp, zP4, zCom, sizeof(zCom)); #else zCom[0] = 0; #endif /* NB: The sqlite3OpcodeName() function is implemented by code created ** by the mkopcodeh.awk and mkopcodec.awk scripts which extract the ** information from the vdbe.c source text */ fprintf(pOut, zFormat1, pc, sqlite3OpcodeName(pOp->opcode), pOp->p1, pOp->p2, pOp->p3, zP4, pOp->p5, zCom ); fflush(pOut); } #endif /* ** Initialize an array of N Mem element. */ static void initMemArray(Mem *p, int N, sqlite3 *db, u16 flags){ while( (N--)>0 ){ p->db = db; p->flags = flags; p->szMalloc = 0; #ifdef SQLITE_DEBUG p->pScopyFrom = 0; #endif p++; } } /* ** Release an array of N Mem elements */ static void releaseMemArray(Mem *p, int N){ if( p && N ){ Mem *pEnd = &p[N]; sqlite3 *db = p->db; if( db->pnBytesFreed ){ do{ if( p->szMalloc ) sqlite3DbFree(db, p->zMalloc); }while( (++p)flags & MEM_Agg ); testcase( p->flags & MEM_Dyn ); testcase( p->flags & MEM_Frame ); testcase( p->flags & MEM_RowSet ); if( p->flags&(MEM_Agg|MEM_Dyn|MEM_Frame|MEM_RowSet) ){ sqlite3VdbeMemRelease(p); }else if( p->szMalloc ){ sqlite3DbFree(db, p->zMalloc); p->szMalloc = 0; } p->flags = MEM_Undefined; }while( (++p)nChildMem]; for(i=0; inChildCsr; i++){ sqlite3VdbeFreeCursor(p->v, apCsr[i]); } releaseMemArray(aMem, p->nChildMem); sqlite3VdbeDeleteAuxData(p->v->db, &p->pAuxData, -1, 0); sqlite3DbFree(p->v->db, p); } #ifndef SQLITE_OMIT_EXPLAIN /* ** Give a listing of the program in the virtual machine. ** ** The interface is the same as sqlite3VdbeExec(). But instead of ** running the code, it invokes the callback once for each instruction. ** This feature is used to implement "EXPLAIN". ** ** When p->explain==1, each instruction is listed. When ** p->explain==2, only OP_Explain instructions are listed and these ** are shown in a different format. p->explain==2 is used to implement ** EXPLAIN QUERY PLAN. ** ** When p->explain==1, first the main program is listed, then each of ** the trigger subprograms are listed one by one. */ SQLITE_PRIVATE int sqlite3VdbeList( Vdbe *p /* The VDBE */ ){ int nRow; /* Stop when row count reaches this */ int nSub = 0; /* Number of sub-vdbes seen so far */ SubProgram **apSub = 0; /* Array of sub-vdbes */ Mem *pSub = 0; /* Memory cell hold array of subprogs */ sqlite3 *db = p->db; /* The database connection */ int i; /* Loop counter */ int rc = SQLITE_OK; /* Return code */ Mem *pMem = &p->aMem[1]; /* First Mem of result set */ assert( p->explain ); assert( p->magic==VDBE_MAGIC_RUN ); assert( p->rc==SQLITE_OK || p->rc==SQLITE_BUSY || p->rc==SQLITE_NOMEM ); /* Even though this opcode does not use dynamic strings for ** the result, result columns may become dynamic if the user calls ** sqlite3_column_text16(), causing a translation to UTF-16 encoding. */ releaseMemArray(pMem, 8); p->pResultSet = 0; if( p->rc==SQLITE_NOMEM_BKPT ){ /* This happens if a malloc() inside a call to sqlite3_column_text() or ** sqlite3_column_text16() failed. */ sqlite3OomFault(db); return SQLITE_ERROR; } /* When the number of output rows reaches nRow, that means the ** listing has finished and sqlite3_step() should return SQLITE_DONE. ** nRow is the sum of the number of rows in the main program, plus ** the sum of the number of rows in all trigger subprograms encountered ** so far. The nRow value will increase as new trigger subprograms are ** encountered, but p->pc will eventually catch up to nRow. */ nRow = p->nOp; if( p->explain==1 ){ /* The first 8 memory cells are used for the result set. So we will ** commandeer the 9th cell to use as storage for an array of pointers ** to trigger subprograms. The VDBE is guaranteed to have at least 9 ** cells. */ assert( p->nMem>9 ); pSub = &p->aMem[9]; if( pSub->flags&MEM_Blob ){ /* On the first call to sqlite3_step(), pSub will hold a NULL. It is ** initialized to a BLOB by the P4_SUBPROGRAM processing logic below */ nSub = pSub->n/sizeof(Vdbe*); apSub = (SubProgram **)pSub->z; } for(i=0; inOp; } } do{ i = p->pc++; }while( iexplain==2 && p->aOp[i].opcode!=OP_Explain ); if( i>=nRow ){ p->rc = SQLITE_OK; rc = SQLITE_DONE; }else if( db->u1.isInterrupted ){ p->rc = SQLITE_INTERRUPT; rc = SQLITE_ERROR; sqlite3VdbeError(p, sqlite3ErrStr(p->rc)); }else{ char *zP4; Op *pOp; if( inOp ){ /* The output line number is small enough that we are still in the ** main program. */ pOp = &p->aOp[i]; }else{ /* We are currently listing subprograms. Figure out which one and ** pick up the appropriate opcode. */ int j; i -= p->nOp; for(j=0; i>=apSub[j]->nOp; j++){ i -= apSub[j]->nOp; } pOp = &apSub[j]->aOp[i]; } if( p->explain==1 ){ pMem->flags = MEM_Int; pMem->u.i = i; /* Program counter */ pMem++; pMem->flags = MEM_Static|MEM_Str|MEM_Term; pMem->z = (char*)sqlite3OpcodeName(pOp->opcode); /* Opcode */ assert( pMem->z!=0 ); pMem->n = sqlite3Strlen30(pMem->z); pMem->enc = SQLITE_UTF8; pMem++; /* When an OP_Program opcode is encounter (the only opcode that has ** a P4_SUBPROGRAM argument), expand the size of the array of subprograms ** kept in p->aMem[9].z to hold the new program - assuming this subprogram ** has not already been seen. */ if( pOp->p4type==P4_SUBPROGRAM ){ int nByte = (nSub+1)*sizeof(SubProgram*); int j; for(j=0; jp4.pProgram ) break; } if( j==nSub && SQLITE_OK==sqlite3VdbeMemGrow(pSub, nByte, nSub!=0) ){ apSub = (SubProgram **)pSub->z; apSub[nSub++] = pOp->p4.pProgram; pSub->flags |= MEM_Blob; pSub->n = nSub*sizeof(SubProgram*); } } } pMem->flags = MEM_Int; pMem->u.i = pOp->p1; /* P1 */ pMem++; pMem->flags = MEM_Int; pMem->u.i = pOp->p2; /* P2 */ pMem++; pMem->flags = MEM_Int; pMem->u.i = pOp->p3; /* P3 */ pMem++; if( sqlite3VdbeMemClearAndResize(pMem, 100) ){ /* P4 */ assert( p->db->mallocFailed ); return SQLITE_ERROR; } pMem->flags = MEM_Str|MEM_Term; zP4 = displayP4(pOp, pMem->z, pMem->szMalloc); if( zP4!=pMem->z ){ pMem->n = 0; sqlite3VdbeMemSetStr(pMem, zP4, -1, SQLITE_UTF8, 0); }else{ assert( pMem->z!=0 ); pMem->n = sqlite3Strlen30(pMem->z); pMem->enc = SQLITE_UTF8; } pMem++; if( p->explain==1 ){ if( sqlite3VdbeMemClearAndResize(pMem, 4) ){ assert( p->db->mallocFailed ); return SQLITE_ERROR; } pMem->flags = MEM_Str|MEM_Term; pMem->n = 2; sqlite3_snprintf(3, pMem->z, "%.2x", pOp->p5); /* P5 */ pMem->enc = SQLITE_UTF8; pMem++; #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS if( sqlite3VdbeMemClearAndResize(pMem, 500) ){ assert( p->db->mallocFailed ); return SQLITE_ERROR; } pMem->flags = MEM_Str|MEM_Term; pMem->n = displayComment(pOp, zP4, pMem->z, 500); pMem->enc = SQLITE_UTF8; #else pMem->flags = MEM_Null; /* Comment */ #endif } p->nResColumn = 8 - 4*(p->explain-1); p->pResultSet = &p->aMem[1]; p->rc = SQLITE_OK; rc = SQLITE_ROW; } return rc; } #endif /* SQLITE_OMIT_EXPLAIN */ #ifdef SQLITE_DEBUG /* ** Print the SQL that was used to generate a VDBE program. */ SQLITE_PRIVATE void sqlite3VdbePrintSql(Vdbe *p){ const char *z = 0; if( p->zSql ){ z = p->zSql; }else if( p->nOp>=1 ){ const VdbeOp *pOp = &p->aOp[0]; if( pOp->opcode==OP_Init && pOp->p4.z!=0 ){ z = pOp->p4.z; while( sqlite3Isspace(*z) ) z++; } } if( z ) printf("SQL: [%s]\n", z); } #endif #if !defined(SQLITE_OMIT_TRACE) && defined(SQLITE_ENABLE_IOTRACE) /* ** Print an IOTRACE message showing SQL content. */ SQLITE_PRIVATE void sqlite3VdbeIOTraceSql(Vdbe *p){ int nOp = p->nOp; VdbeOp *pOp; if( sqlite3IoTrace==0 ) return; if( nOp<1 ) return; pOp = &p->aOp[0]; if( pOp->opcode==OP_Init && pOp->p4.z!=0 ){ int i, j; char z[1000]; sqlite3_snprintf(sizeof(z), z, "%s", pOp->p4.z); for(i=0; sqlite3Isspace(z[i]); i++){} for(j=0; z[i]; i++){ if( sqlite3Isspace(z[i]) ){ if( z[i-1]!=' ' ){ z[j++] = ' '; } }else{ z[j++] = z[i]; } } z[j] = 0; sqlite3IoTrace("SQL %s\n", z); } } #endif /* !SQLITE_OMIT_TRACE && SQLITE_ENABLE_IOTRACE */ /* An instance of this object describes bulk memory available for use ** by subcomponents of a prepared statement. Space is allocated out ** of a ReusableSpace object by the allocSpace() routine below. */ struct ReusableSpace { u8 *pSpace; /* Available memory */ int nFree; /* Bytes of available memory */ int nNeeded; /* Total bytes that could not be allocated */ }; /* Try to allocate nByte bytes of 8-byte aligned bulk memory for pBuf ** from the ReusableSpace object. Return a pointer to the allocated ** memory on success. If insufficient memory is available in the ** ReusableSpace object, increase the ReusableSpace.nNeeded ** value by the amount needed and return NULL. ** ** If pBuf is not initially NULL, that means that the memory has already ** been allocated by a prior call to this routine, so just return a copy ** of pBuf and leave ReusableSpace unchanged. ** ** This allocator is employed to repurpose unused slots at the end of the ** opcode array of prepared state for other memory needs of the prepared ** statement. */ static void *allocSpace( struct ReusableSpace *p, /* Bulk memory available for allocation */ void *pBuf, /* Pointer to a prior allocation */ int nByte /* Bytes of memory needed */ ){ assert( EIGHT_BYTE_ALIGNMENT(p->pSpace) ); if( pBuf==0 ){ nByte = ROUND8(nByte); if( nByte <= p->nFree ){ p->nFree -= nByte; pBuf = &p->pSpace[p->nFree]; }else{ p->nNeeded += nByte; } } assert( EIGHT_BYTE_ALIGNMENT(pBuf) ); return pBuf; } /* ** Rewind the VDBE back to the beginning in preparation for ** running it. */ SQLITE_PRIVATE void sqlite3VdbeRewind(Vdbe *p){ #if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE) int i; #endif assert( p!=0 ); assert( p->magic==VDBE_MAGIC_INIT || p->magic==VDBE_MAGIC_RESET ); /* There should be at least one opcode. */ assert( p->nOp>0 ); /* Set the magic to VDBE_MAGIC_RUN sooner rather than later. */ p->magic = VDBE_MAGIC_RUN; #ifdef SQLITE_DEBUG for(i=0; inMem; i++){ assert( p->aMem[i].db==p->db ); } #endif p->pc = -1; p->rc = SQLITE_OK; p->errorAction = OE_Abort; p->nChange = 0; p->cacheCtr = 1; p->minWriteFileFormat = 255; p->iStatement = 0; p->nFkConstraint = 0; #ifdef VDBE_PROFILE for(i=0; inOp; i++){ p->aOp[i].cnt = 0; p->aOp[i].cycles = 0; } #endif } /* ** Prepare a virtual machine for execution for the first time after ** creating the virtual machine. This involves things such ** as allocating registers and initializing the program counter. ** After the VDBE has be prepped, it can be executed by one or more ** calls to sqlite3VdbeExec(). ** ** This function may be called exactly once on each virtual machine. ** After this routine is called the VM has been "packaged" and is ready ** to run. After this routine is called, further calls to ** sqlite3VdbeAddOp() functions are prohibited. This routine disconnects ** the Vdbe from the Parse object that helped generate it so that the ** the Vdbe becomes an independent entity and the Parse object can be ** destroyed. ** ** Use the sqlite3VdbeRewind() procedure to restore a virtual machine back ** to its initial state after it has been run. */ SQLITE_PRIVATE void sqlite3VdbeMakeReady( Vdbe *p, /* The VDBE */ Parse *pParse /* Parsing context */ ){ sqlite3 *db; /* The database connection */ int nVar; /* Number of parameters */ int nMem; /* Number of VM memory registers */ int nCursor; /* Number of cursors required */ int nArg; /* Number of arguments in subprograms */ int n; /* Loop counter */ struct ReusableSpace x; /* Reusable bulk memory */ assert( p!=0 ); assert( p->nOp>0 ); assert( pParse!=0 ); assert( p->magic==VDBE_MAGIC_INIT ); assert( pParse==p->pParse ); db = p->db; assert( db->mallocFailed==0 ); nVar = pParse->nVar; nMem = pParse->nMem; nCursor = pParse->nTab; nArg = pParse->nMaxArg; /* Each cursor uses a memory cell. The first cursor (cursor 0) can ** use aMem[0] which is not otherwise used by the VDBE program. Allocate ** space at the end of aMem[] for cursors 1 and greater. ** See also: allocateCursor(). */ nMem += nCursor; if( nCursor==0 && nMem>0 ) nMem++; /* Space for aMem[0] even if not used */ /* Figure out how much reusable memory is available at the end of the ** opcode array. This extra memory will be reallocated for other elements ** of the prepared statement. */ n = ROUND8(sizeof(Op)*p->nOp); /* Bytes of opcode memory used */ x.pSpace = &((u8*)p->aOp)[n]; /* Unused opcode memory */ assert( EIGHT_BYTE_ALIGNMENT(x.pSpace) ); x.nFree = ROUNDDOWN8(pParse->szOpAlloc - n); /* Bytes of unused memory */ assert( x.nFree>=0 ); assert( EIGHT_BYTE_ALIGNMENT(&x.pSpace[x.nFree]) ); resolveP2Values(p, &nArg); p->usesStmtJournal = (u8)(pParse->isMultiWrite && pParse->mayAbort); if( pParse->explain && nMem<10 ){ nMem = 10; } p->expired = 0; /* Memory for registers, parameters, cursor, etc, is allocated in one or two ** passes. On the first pass, we try to reuse unused memory at the ** end of the opcode array. If we are unable to satisfy all memory ** requirements by reusing the opcode array tail, then the second ** pass will fill in the remainder using a fresh memory allocation. ** ** This two-pass approach that reuses as much memory as possible from ** the leftover memory at the end of the opcode array. This can significantly ** reduce the amount of memory held by a prepared statement. */ do { x.nNeeded = 0; p->aMem = allocSpace(&x, p->aMem, nMem*sizeof(Mem)); p->aVar = allocSpace(&x, p->aVar, nVar*sizeof(Mem)); p->apArg = allocSpace(&x, p->apArg, nArg*sizeof(Mem*)); p->apCsr = allocSpace(&x, p->apCsr, nCursor*sizeof(VdbeCursor*)); #ifdef SQLITE_ENABLE_STMT_SCANSTATUS p->anExec = allocSpace(&x, p->anExec, p->nOp*sizeof(i64)); #endif if( x.nNeeded==0 ) break; x.pSpace = p->pFree = sqlite3DbMallocRawNN(db, x.nNeeded); x.nFree = x.nNeeded; }while( !db->mallocFailed ); p->nzVar = pParse->nzVar; p->azVar = pParse->azVar; pParse->nzVar = 0; pParse->azVar = 0; p->explain = pParse->explain; if( db->mallocFailed ){ p->nVar = 0; p->nCursor = 0; p->nMem = 0; }else{ p->nCursor = nCursor; p->nVar = (ynVar)nVar; initMemArray(p->aVar, nVar, db, MEM_Null); p->nMem = nMem; initMemArray(p->aMem, nMem, db, MEM_Undefined); memset(p->apCsr, 0, nCursor*sizeof(VdbeCursor*)); #ifdef SQLITE_ENABLE_STMT_SCANSTATUS memset(p->anExec, 0, p->nOp*sizeof(i64)); #endif } sqlite3VdbeRewind(p); } /* ** Close a VDBE cursor and release all the resources that cursor ** happens to hold. */ SQLITE_PRIVATE void sqlite3VdbeFreeCursor(Vdbe *p, VdbeCursor *pCx){ if( pCx==0 ){ return; } assert( pCx->pBt==0 || pCx->eCurType==CURTYPE_BTREE ); switch( pCx->eCurType ){ case CURTYPE_SORTER: { sqlite3VdbeSorterClose(p->db, pCx); break; } case CURTYPE_BTREE: { if( pCx->pBt ){ sqlite3BtreeClose(pCx->pBt); /* The pCx->pCursor will be close automatically, if it exists, by ** the call above. */ }else{ assert( pCx->uc.pCursor!=0 ); sqlite3BtreeCloseCursor(pCx->uc.pCursor); } break; } #ifndef SQLITE_OMIT_VIRTUALTABLE case CURTYPE_VTAB: { sqlite3_vtab_cursor *pVCur = pCx->uc.pVCur; const sqlite3_module *pModule = pVCur->pVtab->pModule; assert( pVCur->pVtab->nRef>0 ); pVCur->pVtab->nRef--; pModule->xClose(pVCur); break; } #endif } } /* ** Close all cursors in the current frame. */ static void closeCursorsInFrame(Vdbe *p){ if( p->apCsr ){ int i; for(i=0; inCursor; i++){ VdbeCursor *pC = p->apCsr[i]; if( pC ){ sqlite3VdbeFreeCursor(p, pC); p->apCsr[i] = 0; } } } } /* ** Copy the values stored in the VdbeFrame structure to its Vdbe. This ** is used, for example, when a trigger sub-program is halted to restore ** control to the main program. */ SQLITE_PRIVATE int sqlite3VdbeFrameRestore(VdbeFrame *pFrame){ Vdbe *v = pFrame->v; closeCursorsInFrame(v); #ifdef SQLITE_ENABLE_STMT_SCANSTATUS v->anExec = pFrame->anExec; #endif v->aOp = pFrame->aOp; v->nOp = pFrame->nOp; v->aMem = pFrame->aMem; v->nMem = pFrame->nMem; v->apCsr = pFrame->apCsr; v->nCursor = pFrame->nCursor; v->db->lastRowid = pFrame->lastRowid; v->nChange = pFrame->nChange; v->db->nChange = pFrame->nDbChange; sqlite3VdbeDeleteAuxData(v->db, &v->pAuxData, -1, 0); v->pAuxData = pFrame->pAuxData; pFrame->pAuxData = 0; return pFrame->pc; } /* ** Close all cursors. ** ** Also release any dynamic memory held by the VM in the Vdbe.aMem memory ** cell array. This is necessary as the memory cell array may contain ** pointers to VdbeFrame objects, which may in turn contain pointers to ** open cursors. */ static void closeAllCursors(Vdbe *p){ if( p->pFrame ){ VdbeFrame *pFrame; for(pFrame=p->pFrame; pFrame->pParent; pFrame=pFrame->pParent); sqlite3VdbeFrameRestore(pFrame); p->pFrame = 0; p->nFrame = 0; } assert( p->nFrame==0 ); closeCursorsInFrame(p); if( p->aMem ){ releaseMemArray(p->aMem, p->nMem); } while( p->pDelFrame ){ VdbeFrame *pDel = p->pDelFrame; p->pDelFrame = pDel->pParent; sqlite3VdbeFrameDelete(pDel); } /* Delete any auxdata allocations made by the VM */ if( p->pAuxData ) sqlite3VdbeDeleteAuxData(p->db, &p->pAuxData, -1, 0); assert( p->pAuxData==0 ); } /* ** Clean up the VM after a single run. */ static void Cleanup(Vdbe *p){ sqlite3 *db = p->db; #ifdef SQLITE_DEBUG /* Execute assert() statements to ensure that the Vdbe.apCsr[] and ** Vdbe.aMem[] arrays have already been cleaned up. */ int i; if( p->apCsr ) for(i=0; inCursor; i++) assert( p->apCsr[i]==0 ); if( p->aMem ){ for(i=0; inMem; i++) assert( p->aMem[i].flags==MEM_Undefined ); } #endif sqlite3DbFree(db, p->zErrMsg); p->zErrMsg = 0; p->pResultSet = 0; } /* ** Set the number of result columns that will be returned by this SQL ** statement. This is now set at compile time, rather than during ** execution of the vdbe program so that sqlite3_column_count() can ** be called on an SQL statement before sqlite3_step(). */ SQLITE_PRIVATE void sqlite3VdbeSetNumCols(Vdbe *p, int nResColumn){ Mem *pColName; int n; sqlite3 *db = p->db; releaseMemArray(p->aColName, p->nResColumn*COLNAME_N); sqlite3DbFree(db, p->aColName); n = nResColumn*COLNAME_N; p->nResColumn = (u16)nResColumn; p->aColName = pColName = (Mem*)sqlite3DbMallocRawNN(db, sizeof(Mem)*n ); if( p->aColName==0 ) return; initMemArray(p->aColName, n, p->db, MEM_Null); } /* ** Set the name of the idx'th column to be returned by the SQL statement. ** zName must be a pointer to a nul terminated string. ** ** This call must be made after a call to sqlite3VdbeSetNumCols(). ** ** The final parameter, xDel, must be one of SQLITE_DYNAMIC, SQLITE_STATIC ** or SQLITE_TRANSIENT. If it is SQLITE_DYNAMIC, then the buffer pointed ** to by zName will be freed by sqlite3DbFree() when the vdbe is destroyed. */ SQLITE_PRIVATE int sqlite3VdbeSetColName( Vdbe *p, /* Vdbe being configured */ int idx, /* Index of column zName applies to */ int var, /* One of the COLNAME_* constants */ const char *zName, /* Pointer to buffer containing name */ void (*xDel)(void*) /* Memory management strategy for zName */ ){ int rc; Mem *pColName; assert( idxnResColumn ); assert( vardb->mallocFailed ){ assert( !zName || xDel!=SQLITE_DYNAMIC ); return SQLITE_NOMEM_BKPT; } assert( p->aColName!=0 ); pColName = &(p->aColName[idx+var*p->nResColumn]); rc = sqlite3VdbeMemSetStr(pColName, zName, -1, SQLITE_UTF8, xDel); assert( rc!=0 || !zName || (pColName->flags&MEM_Term)!=0 ); return rc; } /* ** A read or write transaction may or may not be active on database handle ** db. If a transaction is active, commit it. If there is a ** write-transaction spanning more than one database file, this routine ** takes care of the master journal trickery. */ static int vdbeCommit(sqlite3 *db, Vdbe *p){ int i; int nTrans = 0; /* Number of databases with an active write-transaction ** that are candidates for a two-phase commit using a ** master-journal */ int rc = SQLITE_OK; int needXcommit = 0; #ifdef SQLITE_OMIT_VIRTUALTABLE /* With this option, sqlite3VtabSync() is defined to be simply ** SQLITE_OK so p is not used. */ UNUSED_PARAMETER(p); #endif /* Before doing anything else, call the xSync() callback for any ** virtual module tables written in this transaction. This has to ** be done before determining whether a master journal file is ** required, as an xSync() callback may add an attached database ** to the transaction. */ rc = sqlite3VtabSync(db, p); /* This loop determines (a) if the commit hook should be invoked and ** (b) how many database files have open write transactions, not ** including the temp database. (b) is important because if more than ** one database file has an open write transaction, a master journal ** file is required for an atomic commit. */ for(i=0; rc==SQLITE_OK && inDb; i++){ Btree *pBt = db->aDb[i].pBt; if( sqlite3BtreeIsInTrans(pBt) ){ /* Whether or not a database might need a master journal depends upon ** its journal mode (among other things). This matrix determines which ** journal modes use a master journal and which do not */ static const u8 aMJNeeded[] = { /* DELETE */ 1, /* PERSIST */ 1, /* OFF */ 0, /* TRUNCATE */ 1, /* MEMORY */ 0, /* WAL */ 0 }; Pager *pPager; /* Pager associated with pBt */ needXcommit = 1; sqlite3BtreeEnter(pBt); pPager = sqlite3BtreePager(pBt); if( db->aDb[i].safety_level!=PAGER_SYNCHRONOUS_OFF && aMJNeeded[sqlite3PagerGetJournalMode(pPager)] ){ assert( i!=1 ); nTrans++; } rc = sqlite3PagerExclusiveLock(pPager); sqlite3BtreeLeave(pBt); } } if( rc!=SQLITE_OK ){ return rc; } /* If there are any write-transactions at all, invoke the commit hook */ if( needXcommit && db->xCommitCallback ){ rc = db->xCommitCallback(db->pCommitArg); if( rc ){ return SQLITE_CONSTRAINT_COMMITHOOK; } } /* The simple case - no more than one database file (not counting the ** TEMP database) has a transaction active. There is no need for the ** master-journal. ** ** If the return value of sqlite3BtreeGetFilename() is a zero length ** string, it means the main database is :memory: or a temp file. In ** that case we do not support atomic multi-file commits, so use the ** simple case then too. */ if( 0==sqlite3Strlen30(sqlite3BtreeGetFilename(db->aDb[0].pBt)) || nTrans<=1 ){ for(i=0; rc==SQLITE_OK && inDb; i++){ Btree *pBt = db->aDb[i].pBt; if( pBt ){ rc = sqlite3BtreeCommitPhaseOne(pBt, 0); } } /* Do the commit only if all databases successfully complete phase 1. ** If one of the BtreeCommitPhaseOne() calls fails, this indicates an ** IO error while deleting or truncating a journal file. It is unlikely, ** but could happen. In this case abandon processing and return the error. */ for(i=0; rc==SQLITE_OK && inDb; i++){ Btree *pBt = db->aDb[i].pBt; if( pBt ){ rc = sqlite3BtreeCommitPhaseTwo(pBt, 0); } } if( rc==SQLITE_OK ){ sqlite3VtabCommit(db); } } /* The complex case - There is a multi-file write-transaction active. ** This requires a master journal file to ensure the transaction is ** committed atomically. */ #ifndef SQLITE_OMIT_DISKIO else{ sqlite3_vfs *pVfs = db->pVfs; char *zMaster = 0; /* File-name for the master journal */ char const *zMainFile = sqlite3BtreeGetFilename(db->aDb[0].pBt); sqlite3_file *pMaster = 0; i64 offset = 0; int res; int retryCount = 0; int nMainFile; /* Select a master journal file name */ nMainFile = sqlite3Strlen30(zMainFile); zMaster = sqlite3MPrintf(db, "%s-mjXXXXXX9XXz", zMainFile); if( zMaster==0 ) return SQLITE_NOMEM_BKPT; do { u32 iRandom; if( retryCount ){ if( retryCount>100 ){ sqlite3_log(SQLITE_FULL, "MJ delete: %s", zMaster); sqlite3OsDelete(pVfs, zMaster, 0); break; }else if( retryCount==1 ){ sqlite3_log(SQLITE_FULL, "MJ collide: %s", zMaster); } } retryCount++; sqlite3_randomness(sizeof(iRandom), &iRandom); sqlite3_snprintf(13, &zMaster[nMainFile], "-mj%06X9%02X", (iRandom>>8)&0xffffff, iRandom&0xff); /* The antipenultimate character of the master journal name must ** be "9" to avoid name collisions when using 8+3 filenames. */ assert( zMaster[sqlite3Strlen30(zMaster)-3]=='9' ); sqlite3FileSuffix3(zMainFile, zMaster); rc = sqlite3OsAccess(pVfs, zMaster, SQLITE_ACCESS_EXISTS, &res); }while( rc==SQLITE_OK && res ); if( rc==SQLITE_OK ){ /* Open the master journal. */ rc = sqlite3OsOpenMalloc(pVfs, zMaster, &pMaster, SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE| SQLITE_OPEN_EXCLUSIVE|SQLITE_OPEN_MASTER_JOURNAL, 0 ); } if( rc!=SQLITE_OK ){ sqlite3DbFree(db, zMaster); return rc; } /* Write the name of each database file in the transaction into the new ** master journal file. If an error occurs at this point close ** and delete the master journal file. All the individual journal files ** still have 'null' as the master journal pointer, so they will roll ** back independently if a failure occurs. */ for(i=0; inDb; i++){ Btree *pBt = db->aDb[i].pBt; if( sqlite3BtreeIsInTrans(pBt) ){ char const *zFile = sqlite3BtreeGetJournalname(pBt); if( zFile==0 ){ continue; /* Ignore TEMP and :memory: databases */ } assert( zFile[0]!=0 ); rc = sqlite3OsWrite(pMaster, zFile, sqlite3Strlen30(zFile)+1, offset); offset += sqlite3Strlen30(zFile)+1; if( rc!=SQLITE_OK ){ sqlite3OsCloseFree(pMaster); sqlite3OsDelete(pVfs, zMaster, 0); sqlite3DbFree(db, zMaster); return rc; } } } /* Sync the master journal file. If the IOCAP_SEQUENTIAL device ** flag is set this is not required. */ if( 0==(sqlite3OsDeviceCharacteristics(pMaster)&SQLITE_IOCAP_SEQUENTIAL) && SQLITE_OK!=(rc = sqlite3OsSync(pMaster, SQLITE_SYNC_NORMAL)) ){ sqlite3OsCloseFree(pMaster); sqlite3OsDelete(pVfs, zMaster, 0); sqlite3DbFree(db, zMaster); return rc; } /* Sync all the db files involved in the transaction. The same call ** sets the master journal pointer in each individual journal. If ** an error occurs here, do not delete the master journal file. ** ** If the error occurs during the first call to ** sqlite3BtreeCommitPhaseOne(), then there is a chance that the ** master journal file will be orphaned. But we cannot delete it, ** in case the master journal file name was written into the journal ** file before the failure occurred. */ for(i=0; rc==SQLITE_OK && inDb; i++){ Btree *pBt = db->aDb[i].pBt; if( pBt ){ rc = sqlite3BtreeCommitPhaseOne(pBt, zMaster); } } sqlite3OsCloseFree(pMaster); assert( rc!=SQLITE_BUSY ); if( rc!=SQLITE_OK ){ sqlite3DbFree(db, zMaster); return rc; } /* Delete the master journal file. This commits the transaction. After ** doing this the directory is synced again before any individual ** transaction files are deleted. */ rc = sqlite3OsDelete(pVfs, zMaster, 1); sqlite3DbFree(db, zMaster); zMaster = 0; if( rc ){ return rc; } /* All files and directories have already been synced, so the following ** calls to sqlite3BtreeCommitPhaseTwo() are only closing files and ** deleting or truncating journals. If something goes wrong while ** this is happening we don't really care. The integrity of the ** transaction is already guaranteed, but some stray 'cold' journals ** may be lying around. Returning an error code won't help matters. */ disable_simulated_io_errors(); sqlite3BeginBenignMalloc(); for(i=0; inDb; i++){ Btree *pBt = db->aDb[i].pBt; if( pBt ){ sqlite3BtreeCommitPhaseTwo(pBt, 1); } } sqlite3EndBenignMalloc(); enable_simulated_io_errors(); sqlite3VtabCommit(db); } #endif return rc; } /* ** This routine checks that the sqlite3.nVdbeActive count variable ** matches the number of vdbe's in the list sqlite3.pVdbe that are ** currently active. An assertion fails if the two counts do not match. ** This is an internal self-check only - it is not an essential processing ** step. ** ** This is a no-op if NDEBUG is defined. */ #ifndef NDEBUG static void checkActiveVdbeCnt(sqlite3 *db){ Vdbe *p; int cnt = 0; int nWrite = 0; int nRead = 0; p = db->pVdbe; while( p ){ if( sqlite3_stmt_busy((sqlite3_stmt*)p) ){ cnt++; if( p->readOnly==0 ) nWrite++; if( p->bIsReader ) nRead++; } p = p->pNext; } assert( cnt==db->nVdbeActive ); assert( nWrite==db->nVdbeWrite ); assert( nRead==db->nVdbeRead ); } #else #define checkActiveVdbeCnt(x) #endif /* ** If the Vdbe passed as the first argument opened a statement-transaction, ** close it now. Argument eOp must be either SAVEPOINT_ROLLBACK or ** SAVEPOINT_RELEASE. If it is SAVEPOINT_ROLLBACK, then the statement ** transaction is rolled back. If eOp is SAVEPOINT_RELEASE, then the ** statement transaction is committed. ** ** If an IO error occurs, an SQLITE_IOERR_XXX error code is returned. ** Otherwise SQLITE_OK. */ SQLITE_PRIVATE int sqlite3VdbeCloseStatement(Vdbe *p, int eOp){ sqlite3 *const db = p->db; int rc = SQLITE_OK; /* If p->iStatement is greater than zero, then this Vdbe opened a ** statement transaction that should be closed here. The only exception ** is that an IO error may have occurred, causing an emergency rollback. ** In this case (db->nStatement==0), and there is nothing to do. */ if( db->nStatement && p->iStatement ){ int i; const int iSavepoint = p->iStatement-1; assert( eOp==SAVEPOINT_ROLLBACK || eOp==SAVEPOINT_RELEASE); assert( db->nStatement>0 ); assert( p->iStatement==(db->nStatement+db->nSavepoint) ); for(i=0; inDb; i++){ int rc2 = SQLITE_OK; Btree *pBt = db->aDb[i].pBt; if( pBt ){ if( eOp==SAVEPOINT_ROLLBACK ){ rc2 = sqlite3BtreeSavepoint(pBt, SAVEPOINT_ROLLBACK, iSavepoint); } if( rc2==SQLITE_OK ){ rc2 = sqlite3BtreeSavepoint(pBt, SAVEPOINT_RELEASE, iSavepoint); } if( rc==SQLITE_OK ){ rc = rc2; } } } db->nStatement--; p->iStatement = 0; if( rc==SQLITE_OK ){ if( eOp==SAVEPOINT_ROLLBACK ){ rc = sqlite3VtabSavepoint(db, SAVEPOINT_ROLLBACK, iSavepoint); } if( rc==SQLITE_OK ){ rc = sqlite3VtabSavepoint(db, SAVEPOINT_RELEASE, iSavepoint); } } /* If the statement transaction is being rolled back, also restore the ** database handles deferred constraint counter to the value it had when ** the statement transaction was opened. */ if( eOp==SAVEPOINT_ROLLBACK ){ db->nDeferredCons = p->nStmtDefCons; db->nDeferredImmCons = p->nStmtDefImmCons; } } return rc; } /* ** This function is called when a transaction opened by the database ** handle associated with the VM passed as an argument is about to be ** committed. If there are outstanding deferred foreign key constraint ** violations, return SQLITE_ERROR. Otherwise, SQLITE_OK. ** ** If there are outstanding FK violations and this function returns ** SQLITE_ERROR, set the result of the VM to SQLITE_CONSTRAINT_FOREIGNKEY ** and write an error message to it. Then return SQLITE_ERROR. */ #ifndef SQLITE_OMIT_FOREIGN_KEY SQLITE_PRIVATE int sqlite3VdbeCheckFk(Vdbe *p, int deferred){ sqlite3 *db = p->db; if( (deferred && (db->nDeferredCons+db->nDeferredImmCons)>0) || (!deferred && p->nFkConstraint>0) ){ p->rc = SQLITE_CONSTRAINT_FOREIGNKEY; p->errorAction = OE_Abort; sqlite3VdbeError(p, "FOREIGN KEY constraint failed"); return SQLITE_ERROR; } return SQLITE_OK; } #endif /* ** This routine is called the when a VDBE tries to halt. If the VDBE ** has made changes and is in autocommit mode, then commit those ** changes. If a rollback is needed, then do the rollback. ** ** This routine is the only way to move the state of a VM from ** SQLITE_MAGIC_RUN to SQLITE_MAGIC_HALT. It is harmless to ** call this on a VM that is in the SQLITE_MAGIC_HALT state. ** ** Return an error code. If the commit could not complete because of ** lock contention, return SQLITE_BUSY. If SQLITE_BUSY is returned, it ** means the close did not happen and needs to be repeated. */ SQLITE_PRIVATE int sqlite3VdbeHalt(Vdbe *p){ int rc; /* Used to store transient return codes */ sqlite3 *db = p->db; /* This function contains the logic that determines if a statement or ** transaction will be committed or rolled back as a result of the ** execution of this virtual machine. ** ** If any of the following errors occur: ** ** SQLITE_NOMEM ** SQLITE_IOERR ** SQLITE_FULL ** SQLITE_INTERRUPT ** ** Then the internal cache might have been left in an inconsistent ** state. We need to rollback the statement transaction, if there is ** one, or the complete transaction if there is no statement transaction. */ if( db->mallocFailed ){ p->rc = SQLITE_NOMEM_BKPT; } closeAllCursors(p); if( p->magic!=VDBE_MAGIC_RUN ){ return SQLITE_OK; } checkActiveVdbeCnt(db); /* No commit or rollback needed if the program never started or if the ** SQL statement does not read or write a database file. */ if( p->pc>=0 && p->bIsReader ){ int mrc; /* Primary error code from p->rc */ int eStatementOp = 0; int isSpecialError; /* Set to true if a 'special' error */ /* Lock all btrees used by the statement */ sqlite3VdbeEnter(p); /* Check for one of the special errors */ mrc = p->rc & 0xff; isSpecialError = mrc==SQLITE_NOMEM || mrc==SQLITE_IOERR || mrc==SQLITE_INTERRUPT || mrc==SQLITE_FULL; if( isSpecialError ){ /* If the query was read-only and the error code is SQLITE_INTERRUPT, ** no rollback is necessary. Otherwise, at least a savepoint ** transaction must be rolled back to restore the database to a ** consistent state. ** ** Even if the statement is read-only, it is important to perform ** a statement or transaction rollback operation. If the error ** occurred while writing to the journal, sub-journal or database ** file as part of an effort to free up cache space (see function ** pagerStress() in pager.c), the rollback is required to restore ** the pager to a consistent state. */ if( !p->readOnly || mrc!=SQLITE_INTERRUPT ){ if( (mrc==SQLITE_NOMEM || mrc==SQLITE_FULL) && p->usesStmtJournal ){ eStatementOp = SAVEPOINT_ROLLBACK; }else{ /* We are forced to roll back the active transaction. Before doing ** so, abort any other statements this handle currently has active. */ sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK); sqlite3CloseSavepoints(db); db->autoCommit = 1; p->nChange = 0; } } } /* Check for immediate foreign key violations. */ if( p->rc==SQLITE_OK ){ sqlite3VdbeCheckFk(p, 0); } /* If the auto-commit flag is set and this is the only active writer ** VM, then we do either a commit or rollback of the current transaction. ** ** Note: This block also runs if one of the special errors handled ** above has occurred. */ if( !sqlite3VtabInSync(db) && db->autoCommit && db->nVdbeWrite==(p->readOnly==0) ){ if( p->rc==SQLITE_OK || (p->errorAction==OE_Fail && !isSpecialError) ){ rc = sqlite3VdbeCheckFk(p, 1); if( rc!=SQLITE_OK ){ if( NEVER(p->readOnly) ){ sqlite3VdbeLeave(p); return SQLITE_ERROR; } rc = SQLITE_CONSTRAINT_FOREIGNKEY; }else{ /* The auto-commit flag is true, the vdbe program was successful ** or hit an 'OR FAIL' constraint and there are no deferred foreign ** key constraints to hold up the transaction. This means a commit ** is required. */ rc = vdbeCommit(db, p); } if( rc==SQLITE_BUSY && p->readOnly ){ sqlite3VdbeLeave(p); return SQLITE_BUSY; }else if( rc!=SQLITE_OK ){ p->rc = rc; sqlite3RollbackAll(db, SQLITE_OK); p->nChange = 0; }else{ db->nDeferredCons = 0; db->nDeferredImmCons = 0; db->flags &= ~SQLITE_DeferFKs; sqlite3CommitInternalChanges(db); } }else{ sqlite3RollbackAll(db, SQLITE_OK); p->nChange = 0; } db->nStatement = 0; }else if( eStatementOp==0 ){ if( p->rc==SQLITE_OK || p->errorAction==OE_Fail ){ eStatementOp = SAVEPOINT_RELEASE; }else if( p->errorAction==OE_Abort ){ eStatementOp = SAVEPOINT_ROLLBACK; }else{ sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK); sqlite3CloseSavepoints(db); db->autoCommit = 1; p->nChange = 0; } } /* If eStatementOp is non-zero, then a statement transaction needs to ** be committed or rolled back. Call sqlite3VdbeCloseStatement() to ** do so. If this operation returns an error, and the current statement ** error code is SQLITE_OK or SQLITE_CONSTRAINT, then promote the ** current statement error code. */ if( eStatementOp ){ rc = sqlite3VdbeCloseStatement(p, eStatementOp); if( rc ){ if( p->rc==SQLITE_OK || (p->rc&0xff)==SQLITE_CONSTRAINT ){ p->rc = rc; sqlite3DbFree(db, p->zErrMsg); p->zErrMsg = 0; } sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK); sqlite3CloseSavepoints(db); db->autoCommit = 1; p->nChange = 0; } } /* If this was an INSERT, UPDATE or DELETE and no statement transaction ** has been rolled back, update the database connection change-counter. */ if( p->changeCntOn ){ if( eStatementOp!=SAVEPOINT_ROLLBACK ){ sqlite3VdbeSetChanges(db, p->nChange); }else{ sqlite3VdbeSetChanges(db, 0); } p->nChange = 0; } /* Release the locks */ sqlite3VdbeLeave(p); } /* We have successfully halted and closed the VM. Record this fact. */ if( p->pc>=0 ){ db->nVdbeActive--; if( !p->readOnly ) db->nVdbeWrite--; if( p->bIsReader ) db->nVdbeRead--; assert( db->nVdbeActive>=db->nVdbeRead ); assert( db->nVdbeRead>=db->nVdbeWrite ); assert( db->nVdbeWrite>=0 ); } p->magic = VDBE_MAGIC_HALT; checkActiveVdbeCnt(db); if( db->mallocFailed ){ p->rc = SQLITE_NOMEM_BKPT; } /* If the auto-commit flag is set to true, then any locks that were held ** by connection db have now been released. Call sqlite3ConnectionUnlocked() ** to invoke any required unlock-notify callbacks. */ if( db->autoCommit ){ sqlite3ConnectionUnlocked(db); } assert( db->nVdbeActive>0 || db->autoCommit==0 || db->nStatement==0 ); return (p->rc==SQLITE_BUSY ? SQLITE_BUSY : SQLITE_OK); } /* ** Each VDBE holds the result of the most recent sqlite3_step() call ** in p->rc. This routine sets that result back to SQLITE_OK. */ SQLITE_PRIVATE void sqlite3VdbeResetStepResult(Vdbe *p){ p->rc = SQLITE_OK; } /* ** Copy the error code and error message belonging to the VDBE passed ** as the first argument to its database handle (so that they will be ** returned by calls to sqlite3_errcode() and sqlite3_errmsg()). ** ** This function does not clear the VDBE error code or message, just ** copies them to the database handle. */ SQLITE_PRIVATE int sqlite3VdbeTransferError(Vdbe *p){ sqlite3 *db = p->db; int rc = p->rc; if( p->zErrMsg ){ db->bBenignMalloc++; sqlite3BeginBenignMalloc(); if( db->pErr==0 ) db->pErr = sqlite3ValueNew(db); sqlite3ValueSetStr(db->pErr, -1, p->zErrMsg, SQLITE_UTF8, SQLITE_TRANSIENT); sqlite3EndBenignMalloc(); db->bBenignMalloc--; db->errCode = rc; }else{ sqlite3Error(db, rc); } return rc; } #ifdef SQLITE_ENABLE_SQLLOG /* ** If an SQLITE_CONFIG_SQLLOG hook is registered and the VM has been run, ** invoke it. */ static void vdbeInvokeSqllog(Vdbe *v){ if( sqlite3GlobalConfig.xSqllog && v->rc==SQLITE_OK && v->zSql && v->pc>=0 ){ char *zExpanded = sqlite3VdbeExpandSql(v, v->zSql); assert( v->db->init.busy==0 ); if( zExpanded ){ sqlite3GlobalConfig.xSqllog( sqlite3GlobalConfig.pSqllogArg, v->db, zExpanded, 1 ); sqlite3DbFree(v->db, zExpanded); } } } #else # define vdbeInvokeSqllog(x) #endif /* ** Clean up a VDBE after execution but do not delete the VDBE just yet. ** Write any error messages into *pzErrMsg. Return the result code. ** ** After this routine is run, the VDBE should be ready to be executed ** again. ** ** To look at it another way, this routine resets the state of the ** virtual machine from VDBE_MAGIC_RUN or VDBE_MAGIC_HALT back to ** VDBE_MAGIC_INIT. */ SQLITE_PRIVATE int sqlite3VdbeReset(Vdbe *p){ sqlite3 *db; db = p->db; /* If the VM did not run to completion or if it encountered an ** error, then it might not have been halted properly. So halt ** it now. */ sqlite3VdbeHalt(p); /* If the VDBE has be run even partially, then transfer the error code ** and error message from the VDBE into the main database structure. But ** if the VDBE has just been set to run but has not actually executed any ** instructions yet, leave the main database error information unchanged. */ if( p->pc>=0 ){ vdbeInvokeSqllog(p); sqlite3VdbeTransferError(p); sqlite3DbFree(db, p->zErrMsg); p->zErrMsg = 0; if( p->runOnlyOnce ) p->expired = 1; }else if( p->rc && p->expired ){ /* The expired flag was set on the VDBE before the first call ** to sqlite3_step(). For consistency (since sqlite3_step() was ** called), set the database error in this case as well. */ sqlite3ErrorWithMsg(db, p->rc, p->zErrMsg ? "%s" : 0, p->zErrMsg); sqlite3DbFree(db, p->zErrMsg); p->zErrMsg = 0; } /* Reclaim all memory used by the VDBE */ Cleanup(p); /* Save profiling information from this VDBE run. */ #ifdef VDBE_PROFILE { FILE *out = fopen("vdbe_profile.out", "a"); if( out ){ int i; fprintf(out, "---- "); for(i=0; inOp; i++){ fprintf(out, "%02x", p->aOp[i].opcode); } fprintf(out, "\n"); if( p->zSql ){ char c, pc = 0; fprintf(out, "-- "); for(i=0; (c = p->zSql[i])!=0; i++){ if( pc=='\n' ) fprintf(out, "-- "); putc(c, out); pc = c; } if( pc!='\n' ) fprintf(out, "\n"); } for(i=0; inOp; i++){ char zHdr[100]; sqlite3_snprintf(sizeof(zHdr), zHdr, "%6u %12llu %8llu ", p->aOp[i].cnt, p->aOp[i].cycles, p->aOp[i].cnt>0 ? p->aOp[i].cycles/p->aOp[i].cnt : 0 ); fprintf(out, "%s", zHdr); sqlite3VdbePrintOp(out, i, &p->aOp[i]); } fclose(out); } } #endif p->iCurrentTime = 0; p->magic = VDBE_MAGIC_RESET; return p->rc & db->errMask; } /* ** Clean up and delete a VDBE after execution. Return an integer which is ** the result code. Write any error message text into *pzErrMsg. */ SQLITE_PRIVATE int sqlite3VdbeFinalize(Vdbe *p){ int rc = SQLITE_OK; if( p->magic==VDBE_MAGIC_RUN || p->magic==VDBE_MAGIC_HALT ){ rc = sqlite3VdbeReset(p); assert( (rc & p->db->errMask)==rc ); } sqlite3VdbeDelete(p); return rc; } /* ** If parameter iOp is less than zero, then invoke the destructor for ** all auxiliary data pointers currently cached by the VM passed as ** the first argument. ** ** Or, if iOp is greater than or equal to zero, then the destructor is ** only invoked for those auxiliary data pointers created by the user ** function invoked by the OP_Function opcode at instruction iOp of ** VM pVdbe, and only then if: ** ** * the associated function parameter is the 32nd or later (counting ** from left to right), or ** ** * the corresponding bit in argument mask is clear (where the first ** function parameter corresponds to bit 0 etc.). */ SQLITE_PRIVATE void sqlite3VdbeDeleteAuxData(sqlite3 *db, AuxData **pp, int iOp, int mask){ while( *pp ){ AuxData *pAux = *pp; if( (iOp<0) || (pAux->iOp==iOp && (pAux->iArg>31 || !(mask & MASKBIT32(pAux->iArg)))) ){ testcase( pAux->iArg==31 ); if( pAux->xDelete ){ pAux->xDelete(pAux->pAux); } *pp = pAux->pNext; sqlite3DbFree(db, pAux); }else{ pp= &pAux->pNext; } } } /* ** Free all memory associated with the Vdbe passed as the second argument, ** except for object itself, which is preserved. ** ** The difference between this function and sqlite3VdbeDelete() is that ** VdbeDelete() also unlinks the Vdbe from the list of VMs associated with ** the database connection and frees the object itself. */ SQLITE_PRIVATE void sqlite3VdbeClearObject(sqlite3 *db, Vdbe *p){ SubProgram *pSub, *pNext; int i; assert( p->db==0 || p->db==db ); releaseMemArray(p->aColName, p->nResColumn*COLNAME_N); for(pSub=p->pProgram; pSub; pSub=pNext){ pNext = pSub->pNext; vdbeFreeOpArray(db, pSub->aOp, pSub->nOp); sqlite3DbFree(db, pSub); } if( p->magic!=VDBE_MAGIC_INIT ){ releaseMemArray(p->aVar, p->nVar); for(i=p->nzVar-1; i>=0; i--) sqlite3DbFree(db, p->azVar[i]); sqlite3DbFree(db, p->azVar); sqlite3DbFree(db, p->pFree); } vdbeFreeOpArray(db, p->aOp, p->nOp); sqlite3DbFree(db, p->aColName); sqlite3DbFree(db, p->zSql); #ifdef SQLITE_ENABLE_STMT_SCANSTATUS for(i=0; inScan; i++){ sqlite3DbFree(db, p->aScan[i].zName); } sqlite3DbFree(db, p->aScan); #endif } /* ** Delete an entire VDBE. */ SQLITE_PRIVATE void sqlite3VdbeDelete(Vdbe *p){ sqlite3 *db; if( NEVER(p==0) ) return; db = p->db; assert( sqlite3_mutex_held(db->mutex) ); sqlite3VdbeClearObject(db, p); if( p->pPrev ){ p->pPrev->pNext = p->pNext; }else{ assert( db->pVdbe==p ); db->pVdbe = p->pNext; } if( p->pNext ){ p->pNext->pPrev = p->pPrev; } p->magic = VDBE_MAGIC_DEAD; p->db = 0; sqlite3DbFree(db, p); } /* ** The cursor "p" has a pending seek operation that has not yet been ** carried out. Seek the cursor now. If an error occurs, return ** the appropriate error code. */ static int SQLITE_NOINLINE handleDeferredMoveto(VdbeCursor *p){ int res, rc; #ifdef SQLITE_TEST extern int sqlite3_search_count; #endif assert( p->deferredMoveto ); assert( p->isTable ); assert( p->eCurType==CURTYPE_BTREE ); rc = sqlite3BtreeMovetoUnpacked(p->uc.pCursor, 0, p->movetoTarget, 0, &res); if( rc ) return rc; if( res!=0 ) return SQLITE_CORRUPT_BKPT; #ifdef SQLITE_TEST sqlite3_search_count++; #endif p->deferredMoveto = 0; p->cacheStatus = CACHE_STALE; return SQLITE_OK; } /* ** Something has moved cursor "p" out of place. Maybe the row it was ** pointed to was deleted out from under it. Or maybe the btree was ** rebalanced. Whatever the cause, try to restore "p" to the place it ** is supposed to be pointing. If the row was deleted out from under the ** cursor, set the cursor to point to a NULL row. */ static int SQLITE_NOINLINE handleMovedCursor(VdbeCursor *p){ int isDifferentRow, rc; assert( p->eCurType==CURTYPE_BTREE ); assert( p->uc.pCursor!=0 ); assert( sqlite3BtreeCursorHasMoved(p->uc.pCursor) ); rc = sqlite3BtreeCursorRestore(p->uc.pCursor, &isDifferentRow); p->cacheStatus = CACHE_STALE; if( isDifferentRow ) p->nullRow = 1; return rc; } /* ** Check to ensure that the cursor is valid. Restore the cursor ** if need be. Return any I/O error from the restore operation. */ SQLITE_PRIVATE int sqlite3VdbeCursorRestore(VdbeCursor *p){ assert( p->eCurType==CURTYPE_BTREE ); if( sqlite3BtreeCursorHasMoved(p->uc.pCursor) ){ return handleMovedCursor(p); } return SQLITE_OK; } /* ** Make sure the cursor p is ready to read or write the row to which it ** was last positioned. Return an error code if an OOM fault or I/O error ** prevents us from positioning the cursor to its correct position. ** ** If a MoveTo operation is pending on the given cursor, then do that ** MoveTo now. If no move is pending, check to see if the row has been ** deleted out from under the cursor and if it has, mark the row as ** a NULL row. ** ** If the cursor is already pointing to the correct row and that row has ** not been deleted out from under the cursor, then this routine is a no-op. */ SQLITE_PRIVATE int sqlite3VdbeCursorMoveto(VdbeCursor **pp, int *piCol){ VdbeCursor *p = *pp; if( p->eCurType==CURTYPE_BTREE ){ if( p->deferredMoveto ){ int iMap; if( p->aAltMap && (iMap = p->aAltMap[1+*piCol])>0 ){ *pp = p->pAltCursor; *piCol = iMap - 1; return SQLITE_OK; } return handleDeferredMoveto(p); } if( sqlite3BtreeCursorHasMoved(p->uc.pCursor) ){ return handleMovedCursor(p); } } return SQLITE_OK; } /* ** The following functions: ** ** sqlite3VdbeSerialType() ** sqlite3VdbeSerialTypeLen() ** sqlite3VdbeSerialLen() ** sqlite3VdbeSerialPut() ** sqlite3VdbeSerialGet() ** ** encapsulate the code that serializes values for storage in SQLite ** data and index records. Each serialized value consists of a ** 'serial-type' and a blob of data. The serial type is an 8-byte unsigned ** integer, stored as a varint. ** ** In an SQLite index record, the serial type is stored directly before ** the blob of data that it corresponds to. In a table record, all serial ** types are stored at the start of the record, and the blobs of data at ** the end. Hence these functions allow the caller to handle the ** serial-type and data blob separately. ** ** The following table describes the various storage classes for data: ** ** serial type bytes of data type ** -------------- --------------- --------------- ** 0 0 NULL ** 1 1 signed integer ** 2 2 signed integer ** 3 3 signed integer ** 4 4 signed integer ** 5 6 signed integer ** 6 8 signed integer ** 7 8 IEEE float ** 8 0 Integer constant 0 ** 9 0 Integer constant 1 ** 10,11 reserved for expansion ** N>=12 and even (N-12)/2 BLOB ** N>=13 and odd (N-13)/2 text ** ** The 8 and 9 types were added in 3.3.0, file format 4. Prior versions ** of SQLite will not understand those serial types. */ /* ** Return the serial-type for the value stored in pMem. */ SQLITE_PRIVATE u32 sqlite3VdbeSerialType(Mem *pMem, int file_format, u32 *pLen){ int flags = pMem->flags; u32 n; assert( pLen!=0 ); if( flags&MEM_Null ){ *pLen = 0; return 0; } if( flags&MEM_Int ){ /* Figure out whether to use 1, 2, 4, 6 or 8 bytes. */ # define MAX_6BYTE ((((i64)0x00008000)<<32)-1) i64 i = pMem->u.i; u64 u; if( i<0 ){ u = ~i; }else{ u = i; } if( u<=127 ){ if( (i&1)==i && file_format>=4 ){ *pLen = 0; return 8+(u32)u; }else{ *pLen = 1; return 1; } } if( u<=32767 ){ *pLen = 2; return 2; } if( u<=8388607 ){ *pLen = 3; return 3; } if( u<=2147483647 ){ *pLen = 4; return 4; } if( u<=MAX_6BYTE ){ *pLen = 6; return 5; } *pLen = 8; return 6; } if( flags&MEM_Real ){ *pLen = 8; return 7; } assert( pMem->db->mallocFailed || flags&(MEM_Str|MEM_Blob) ); assert( pMem->n>=0 ); n = (u32)pMem->n; if( flags & MEM_Zero ){ n += pMem->u.nZero; } *pLen = n; return ((n*2) + 12 + ((flags&MEM_Str)!=0)); } /* ** The sizes for serial types less than 128 */ static const u8 sqlite3SmallTypeSizes[] = { /* 0 1 2 3 4 5 6 7 8 9 */ /* 0 */ 0, 1, 2, 3, 4, 6, 8, 8, 0, 0, /* 10 */ 0, 0, 0, 0, 1, 1, 2, 2, 3, 3, /* 20 */ 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, /* 30 */ 9, 9, 10, 10, 11, 11, 12, 12, 13, 13, /* 40 */ 14, 14, 15, 15, 16, 16, 17, 17, 18, 18, /* 50 */ 19, 19, 20, 20, 21, 21, 22, 22, 23, 23, /* 60 */ 24, 24, 25, 25, 26, 26, 27, 27, 28, 28, /* 70 */ 29, 29, 30, 30, 31, 31, 32, 32, 33, 33, /* 80 */ 34, 34, 35, 35, 36, 36, 37, 37, 38, 38, /* 90 */ 39, 39, 40, 40, 41, 41, 42, 42, 43, 43, /* 100 */ 44, 44, 45, 45, 46, 46, 47, 47, 48, 48, /* 110 */ 49, 49, 50, 50, 51, 51, 52, 52, 53, 53, /* 120 */ 54, 54, 55, 55, 56, 56, 57, 57 }; /* ** Return the length of the data corresponding to the supplied serial-type. */ SQLITE_PRIVATE u32 sqlite3VdbeSerialTypeLen(u32 serial_type){ if( serial_type>=128 ){ return (serial_type-12)/2; }else{ assert( serial_type<12 || sqlite3SmallTypeSizes[serial_type]==(serial_type - 12)/2 ); return sqlite3SmallTypeSizes[serial_type]; } } SQLITE_PRIVATE u8 sqlite3VdbeOneByteSerialTypeLen(u8 serial_type){ assert( serial_type<128 ); return sqlite3SmallTypeSizes[serial_type]; } /* ** If we are on an architecture with mixed-endian floating ** points (ex: ARM7) then swap the lower 4 bytes with the ** upper 4 bytes. Return the result. ** ** For most architectures, this is a no-op. ** ** (later): It is reported to me that the mixed-endian problem ** on ARM7 is an issue with GCC, not with the ARM7 chip. It seems ** that early versions of GCC stored the two words of a 64-bit ** float in the wrong order. And that error has been propagated ** ever since. The blame is not necessarily with GCC, though. ** GCC might have just copying the problem from a prior compiler. ** I am also told that newer versions of GCC that follow a different ** ABI get the byte order right. ** ** Developers using SQLite on an ARM7 should compile and run their ** application using -DSQLITE_DEBUG=1 at least once. With DEBUG ** enabled, some asserts below will ensure that the byte order of ** floating point values is correct. ** ** (2007-08-30) Frank van Vugt has studied this problem closely ** and has send his findings to the SQLite developers. Frank ** writes that some Linux kernels offer floating point hardware ** emulation that uses only 32-bit mantissas instead of a full ** 48-bits as required by the IEEE standard. (This is the ** CONFIG_FPE_FASTFPE option.) On such systems, floating point ** byte swapping becomes very complicated. To avoid problems, ** the necessary byte swapping is carried out using a 64-bit integer ** rather than a 64-bit float. Frank assures us that the code here ** works for him. We, the developers, have no way to independently ** verify this, but Frank seems to know what he is talking about ** so we trust him. */ #ifdef SQLITE_MIXED_ENDIAN_64BIT_FLOAT static u64 floatSwap(u64 in){ union { u64 r; u32 i[2]; } u; u32 t; u.r = in; t = u.i[0]; u.i[0] = u.i[1]; u.i[1] = t; return u.r; } # define swapMixedEndianFloat(X) X = floatSwap(X) #else # define swapMixedEndianFloat(X) #endif /* ** Write the serialized data blob for the value stored in pMem into ** buf. It is assumed that the caller has allocated sufficient space. ** Return the number of bytes written. ** ** nBuf is the amount of space left in buf[]. The caller is responsible ** for allocating enough space to buf[] to hold the entire field, exclusive ** of the pMem->u.nZero bytes for a MEM_Zero value. ** ** Return the number of bytes actually written into buf[]. The number ** of bytes in the zero-filled tail is included in the return value only ** if those bytes were zeroed in buf[]. */ SQLITE_PRIVATE u32 sqlite3VdbeSerialPut(u8 *buf, Mem *pMem, u32 serial_type){ u32 len; /* Integer and Real */ if( serial_type<=7 && serial_type>0 ){ u64 v; u32 i; if( serial_type==7 ){ assert( sizeof(v)==sizeof(pMem->u.r) ); memcpy(&v, &pMem->u.r, sizeof(v)); swapMixedEndianFloat(v); }else{ v = pMem->u.i; } len = i = sqlite3SmallTypeSizes[serial_type]; assert( i>0 ); do{ buf[--i] = (u8)(v&0xFF); v >>= 8; }while( i ); return len; } /* String or blob */ if( serial_type>=12 ){ assert( pMem->n + ((pMem->flags & MEM_Zero)?pMem->u.nZero:0) == (int)sqlite3VdbeSerialTypeLen(serial_type) ); len = pMem->n; if( len>0 ) memcpy(buf, pMem->z, len); return len; } /* NULL or constants 0 or 1 */ return 0; } /* Input "x" is a sequence of unsigned characters that represent a ** big-endian integer. Return the equivalent native integer */ #define ONE_BYTE_INT(x) ((i8)(x)[0]) #define TWO_BYTE_INT(x) (256*(i8)((x)[0])|(x)[1]) #define THREE_BYTE_INT(x) (65536*(i8)((x)[0])|((x)[1]<<8)|(x)[2]) #define FOUR_BYTE_UINT(x) (((u32)(x)[0]<<24)|((x)[1]<<16)|((x)[2]<<8)|(x)[3]) #define FOUR_BYTE_INT(x) (16777216*(i8)((x)[0])|((x)[1]<<16)|((x)[2]<<8)|(x)[3]) /* ** Deserialize the data blob pointed to by buf as serial type serial_type ** and store the result in pMem. Return the number of bytes read. ** ** This function is implemented as two separate routines for performance. ** The few cases that require local variables are broken out into a separate ** routine so that in most cases the overhead of moving the stack pointer ** is avoided. */ static u32 SQLITE_NOINLINE serialGet( const unsigned char *buf, /* Buffer to deserialize from */ u32 serial_type, /* Serial type to deserialize */ Mem *pMem /* Memory cell to write value into */ ){ u64 x = FOUR_BYTE_UINT(buf); u32 y = FOUR_BYTE_UINT(buf+4); x = (x<<32) + y; if( serial_type==6 ){ /* EVIDENCE-OF: R-29851-52272 Value is a big-endian 64-bit ** twos-complement integer. */ pMem->u.i = *(i64*)&x; pMem->flags = MEM_Int; testcase( pMem->u.i<0 ); }else{ /* EVIDENCE-OF: R-57343-49114 Value is a big-endian IEEE 754-2008 64-bit ** floating point number. */ #if !defined(NDEBUG) && !defined(SQLITE_OMIT_FLOATING_POINT) /* Verify that integers and floating point values use the same ** byte order. Or, that if SQLITE_MIXED_ENDIAN_64BIT_FLOAT is ** defined that 64-bit floating point values really are mixed ** endian. */ static const u64 t1 = ((u64)0x3ff00000)<<32; static const double r1 = 1.0; u64 t2 = t1; swapMixedEndianFloat(t2); assert( sizeof(r1)==sizeof(t2) && memcmp(&r1, &t2, sizeof(r1))==0 ); #endif assert( sizeof(x)==8 && sizeof(pMem->u.r)==8 ); swapMixedEndianFloat(x); memcpy(&pMem->u.r, &x, sizeof(x)); pMem->flags = sqlite3IsNaN(pMem->u.r) ? MEM_Null : MEM_Real; } return 8; } SQLITE_PRIVATE u32 sqlite3VdbeSerialGet( const unsigned char *buf, /* Buffer to deserialize from */ u32 serial_type, /* Serial type to deserialize */ Mem *pMem /* Memory cell to write value into */ ){ switch( serial_type ){ case 10: /* Reserved for future use */ case 11: /* Reserved for future use */ case 0: { /* Null */ /* EVIDENCE-OF: R-24078-09375 Value is a NULL. */ pMem->flags = MEM_Null; break; } case 1: { /* EVIDENCE-OF: R-44885-25196 Value is an 8-bit twos-complement ** integer. */ pMem->u.i = ONE_BYTE_INT(buf); pMem->flags = MEM_Int; testcase( pMem->u.i<0 ); return 1; } case 2: { /* 2-byte signed integer */ /* EVIDENCE-OF: R-49794-35026 Value is a big-endian 16-bit ** twos-complement integer. */ pMem->u.i = TWO_BYTE_INT(buf); pMem->flags = MEM_Int; testcase( pMem->u.i<0 ); return 2; } case 3: { /* 3-byte signed integer */ /* EVIDENCE-OF: R-37839-54301 Value is a big-endian 24-bit ** twos-complement integer. */ pMem->u.i = THREE_BYTE_INT(buf); pMem->flags = MEM_Int; testcase( pMem->u.i<0 ); return 3; } case 4: { /* 4-byte signed integer */ /* EVIDENCE-OF: R-01849-26079 Value is a big-endian 32-bit ** twos-complement integer. */ pMem->u.i = FOUR_BYTE_INT(buf); #ifdef __HP_cc /* Work around a sign-extension bug in the HP compiler for HP/UX */ if( buf[0]&0x80 ) pMem->u.i |= 0xffffffff80000000LL; #endif pMem->flags = MEM_Int; testcase( pMem->u.i<0 ); return 4; } case 5: { /* 6-byte signed integer */ /* EVIDENCE-OF: R-50385-09674 Value is a big-endian 48-bit ** twos-complement integer. */ pMem->u.i = FOUR_BYTE_UINT(buf+2) + (((i64)1)<<32)*TWO_BYTE_INT(buf); pMem->flags = MEM_Int; testcase( pMem->u.i<0 ); return 6; } case 6: /* 8-byte signed integer */ case 7: { /* IEEE floating point */ /* These use local variables, so do them in a separate routine ** to avoid having to move the frame pointer in the common case */ return serialGet(buf,serial_type,pMem); } case 8: /* Integer 0 */ case 9: { /* Integer 1 */ /* EVIDENCE-OF: R-12976-22893 Value is the integer 0. */ /* EVIDENCE-OF: R-18143-12121 Value is the integer 1. */ pMem->u.i = serial_type-8; pMem->flags = MEM_Int; return 0; } default: { /* EVIDENCE-OF: R-14606-31564 Value is a BLOB that is (N-12)/2 bytes in ** length. ** EVIDENCE-OF: R-28401-00140 Value is a string in the text encoding and ** (N-13)/2 bytes in length. */ static const u16 aFlag[] = { MEM_Blob|MEM_Ephem, MEM_Str|MEM_Ephem }; pMem->z = (char *)buf; pMem->n = (serial_type-12)/2; pMem->flags = aFlag[serial_type&1]; return pMem->n; } } return 0; } /* ** This routine is used to allocate sufficient space for an UnpackedRecord ** structure large enough to be used with sqlite3VdbeRecordUnpack() if ** the first argument is a pointer to KeyInfo structure pKeyInfo. ** ** The space is either allocated using sqlite3DbMallocRaw() or from within ** the unaligned buffer passed via the second and third arguments (presumably ** stack space). If the former, then *ppFree is set to a pointer that should ** be eventually freed by the caller using sqlite3DbFree(). Or, if the ** allocation comes from the pSpace/szSpace buffer, *ppFree is set to NULL ** before returning. ** ** If an OOM error occurs, NULL is returned. */ SQLITE_PRIVATE UnpackedRecord *sqlite3VdbeAllocUnpackedRecord( KeyInfo *pKeyInfo, /* Description of the record */ char *pSpace, /* Unaligned space available */ int szSpace, /* Size of pSpace[] in bytes */ char **ppFree /* OUT: Caller should free this pointer */ ){ UnpackedRecord *p; /* Unpacked record to return */ int nOff; /* Increment pSpace by nOff to align it */ int nByte; /* Number of bytes required for *p */ /* We want to shift the pointer pSpace up such that it is 8-byte aligned. ** Thus, we need to calculate a value, nOff, between 0 and 7, to shift ** it by. If pSpace is already 8-byte aligned, nOff should be zero. */ nOff = (8 - (SQLITE_PTR_TO_INT(pSpace) & 7)) & 7; nByte = ROUND8(sizeof(UnpackedRecord)) + sizeof(Mem)*(pKeyInfo->nField+1); if( nByte>szSpace+nOff ){ p = (UnpackedRecord *)sqlite3DbMallocRaw(pKeyInfo->db, nByte); *ppFree = (char *)p; if( !p ) return 0; }else{ p = (UnpackedRecord*)&pSpace[nOff]; *ppFree = 0; } p->aMem = (Mem*)&((char*)p)[ROUND8(sizeof(UnpackedRecord))]; assert( pKeyInfo->aSortOrder!=0 ); p->pKeyInfo = pKeyInfo; p->nField = pKeyInfo->nField + 1; return p; } /* ** Given the nKey-byte encoding of a record in pKey[], populate the ** UnpackedRecord structure indicated by the fourth argument with the ** contents of the decoded record. */ SQLITE_PRIVATE void sqlite3VdbeRecordUnpack( KeyInfo *pKeyInfo, /* Information about the record format */ int nKey, /* Size of the binary record */ const void *pKey, /* The binary record */ UnpackedRecord *p /* Populate this structure before returning. */ ){ const unsigned char *aKey = (const unsigned char *)pKey; int d; u32 idx; /* Offset in aKey[] to read from */ u16 u; /* Unsigned loop counter */ u32 szHdr; Mem *pMem = p->aMem; p->default_rc = 0; assert( EIGHT_BYTE_ALIGNMENT(pMem) ); idx = getVarint32(aKey, szHdr); d = szHdr; u = 0; while( idxenc = pKeyInfo->enc; pMem->db = pKeyInfo->db; /* pMem->flags = 0; // sqlite3VdbeSerialGet() will set this for us */ pMem->szMalloc = 0; pMem->z = 0; d += sqlite3VdbeSerialGet(&aKey[d], serial_type, pMem); pMem++; if( (++u)>=p->nField ) break; } assert( u<=pKeyInfo->nField + 1 ); p->nField = u; } #if SQLITE_DEBUG /* ** This function compares two index or table record keys in the same way ** as the sqlite3VdbeRecordCompare() routine. Unlike VdbeRecordCompare(), ** this function deserializes and compares values using the ** sqlite3VdbeSerialGet() and sqlite3MemCompare() functions. It is used ** in assert() statements to ensure that the optimized code in ** sqlite3VdbeRecordCompare() returns results with these two primitives. ** ** Return true if the result of comparison is equivalent to desiredResult. ** Return false if there is a disagreement. */ static int vdbeRecordCompareDebug( int nKey1, const void *pKey1, /* Left key */ const UnpackedRecord *pPKey2, /* Right key */ int desiredResult /* Correct answer */ ){ u32 d1; /* Offset into aKey[] of next data element */ u32 idx1; /* Offset into aKey[] of next header element */ u32 szHdr1; /* Number of bytes in header */ int i = 0; int rc = 0; const unsigned char *aKey1 = (const unsigned char *)pKey1; KeyInfo *pKeyInfo; Mem mem1; pKeyInfo = pPKey2->pKeyInfo; if( pKeyInfo->db==0 ) return 1; mem1.enc = pKeyInfo->enc; mem1.db = pKeyInfo->db; /* mem1.flags = 0; // Will be initialized by sqlite3VdbeSerialGet() */ VVA_ONLY( mem1.szMalloc = 0; ) /* Only needed by assert() statements */ /* Compilers may complain that mem1.u.i is potentially uninitialized. ** We could initialize it, as shown here, to silence those complaints. ** But in fact, mem1.u.i will never actually be used uninitialized, and doing ** the unnecessary initialization has a measurable negative performance ** impact, since this routine is a very high runner. And so, we choose ** to ignore the compiler warnings and leave this variable uninitialized. */ /* mem1.u.i = 0; // not needed, here to silence compiler warning */ idx1 = getVarint32(aKey1, szHdr1); if( szHdr1>98307 ) return SQLITE_CORRUPT; d1 = szHdr1; assert( pKeyInfo->nField+pKeyInfo->nXField>=pPKey2->nField || CORRUPT_DB ); assert( pKeyInfo->aSortOrder!=0 ); assert( pKeyInfo->nField>0 ); assert( idx1<=szHdr1 || CORRUPT_DB ); do{ u32 serial_type1; /* Read the serial types for the next element in each key. */ idx1 += getVarint32( aKey1+idx1, serial_type1 ); /* Verify that there is enough key space remaining to avoid ** a buffer overread. The "d1+serial_type1+2" subexpression will ** always be greater than or equal to the amount of required key space. ** Use that approximation to avoid the more expensive call to ** sqlite3VdbeSerialTypeLen() in the common case. */ if( d1+serial_type1+2>(u32)nKey1 && d1+sqlite3VdbeSerialTypeLen(serial_type1)>(u32)nKey1 ){ break; } /* Extract the values to be compared. */ d1 += sqlite3VdbeSerialGet(&aKey1[d1], serial_type1, &mem1); /* Do the comparison */ rc = sqlite3MemCompare(&mem1, &pPKey2->aMem[i], pKeyInfo->aColl[i]); if( rc!=0 ){ assert( mem1.szMalloc==0 ); /* See comment below */ if( pKeyInfo->aSortOrder[i] ){ rc = -rc; /* Invert the result for DESC sort order. */ } goto debugCompareEnd; } i++; }while( idx1nField ); /* No memory allocation is ever used on mem1. Prove this using ** the following assert(). If the assert() fails, it indicates a ** memory leak and a need to call sqlite3VdbeMemRelease(&mem1). */ assert( mem1.szMalloc==0 ); /* rc==0 here means that one of the keys ran out of fields and ** all the fields up to that point were equal. Return the default_rc ** value. */ rc = pPKey2->default_rc; debugCompareEnd: if( desiredResult==0 && rc==0 ) return 1; if( desiredResult<0 && rc<0 ) return 1; if( desiredResult>0 && rc>0 ) return 1; if( CORRUPT_DB ) return 1; if( pKeyInfo->db->mallocFailed ) return 1; return 0; } #endif #if SQLITE_DEBUG /* ** Count the number of fields (a.k.a. columns) in the record given by ** pKey,nKey. The verify that this count is less than or equal to the ** limit given by pKeyInfo->nField + pKeyInfo->nXField. ** ** If this constraint is not satisfied, it means that the high-speed ** vdbeRecordCompareInt() and vdbeRecordCompareString() routines will ** not work correctly. If this assert() ever fires, it probably means ** that the KeyInfo.nField or KeyInfo.nXField values were computed ** incorrectly. */ static void vdbeAssertFieldCountWithinLimits( int nKey, const void *pKey, /* The record to verify */ const KeyInfo *pKeyInfo /* Compare size with this KeyInfo */ ){ int nField = 0; u32 szHdr; u32 idx; u32 notUsed; const unsigned char *aKey = (const unsigned char*)pKey; if( CORRUPT_DB ) return; idx = getVarint32(aKey, szHdr); assert( nKey>=0 ); assert( szHdr<=(u32)nKey ); while( idxnField+pKeyInfo->nXField ); } #else # define vdbeAssertFieldCountWithinLimits(A,B,C) #endif /* ** Both *pMem1 and *pMem2 contain string values. Compare the two values ** using the collation sequence pColl. As usual, return a negative , zero ** or positive value if *pMem1 is less than, equal to or greater than ** *pMem2, respectively. Similar in spirit to "rc = (*pMem1) - (*pMem2);". */ static int vdbeCompareMemString( const Mem *pMem1, const Mem *pMem2, const CollSeq *pColl, u8 *prcErr /* If an OOM occurs, set to SQLITE_NOMEM */ ){ if( pMem1->enc==pColl->enc ){ /* The strings are already in the correct encoding. Call the ** comparison function directly */ return pColl->xCmp(pColl->pUser,pMem1->n,pMem1->z,pMem2->n,pMem2->z); }else{ int rc; const void *v1, *v2; int n1, n2; Mem c1; Mem c2; sqlite3VdbeMemInit(&c1, pMem1->db, MEM_Null); sqlite3VdbeMemInit(&c2, pMem1->db, MEM_Null); sqlite3VdbeMemShallowCopy(&c1, pMem1, MEM_Ephem); sqlite3VdbeMemShallowCopy(&c2, pMem2, MEM_Ephem); v1 = sqlite3ValueText((sqlite3_value*)&c1, pColl->enc); n1 = v1==0 ? 0 : c1.n; v2 = sqlite3ValueText((sqlite3_value*)&c2, pColl->enc); n2 = v2==0 ? 0 : c2.n; rc = pColl->xCmp(pColl->pUser, n1, v1, n2, v2); if( (v1==0 || v2==0) && prcErr ) *prcErr = SQLITE_NOMEM_BKPT; sqlite3VdbeMemRelease(&c1); sqlite3VdbeMemRelease(&c2); return rc; } } /* ** The input pBlob is guaranteed to be a Blob that is not marked ** with MEM_Zero. Return true if it could be a zero-blob. */ static int isAllZero(const char *z, int n){ int i; for(i=0; in; int n2 = pB2->n; /* It is possible to have a Blob value that has some non-zero content ** followed by zero content. But that only comes up for Blobs formed ** by the OP_MakeRecord opcode, and such Blobs never get passed into ** sqlite3MemCompare(). */ assert( (pB1->flags & MEM_Zero)==0 || n1==0 ); assert( (pB2->flags & MEM_Zero)==0 || n2==0 ); if( (pB1->flags|pB2->flags) & MEM_Zero ){ if( pB1->flags & pB2->flags & MEM_Zero ){ return pB1->u.nZero - pB2->u.nZero; }else if( pB1->flags & MEM_Zero ){ if( !isAllZero(pB2->z, pB2->n) ) return -1; return pB1->u.nZero - n2; }else{ if( !isAllZero(pB1->z, pB1->n) ) return +1; return n1 - pB2->u.nZero; } } c = memcmp(pB1->z, pB2->z, n1>n2 ? n2 : n1); if( c ) return c; return n1 - n2; } /* ** Do a comparison between a 64-bit signed integer and a 64-bit floating-point ** number. Return negative, zero, or positive if the first (i64) is less than, ** equal to, or greater than the second (double). */ static int sqlite3IntFloatCompare(i64 i, double r){ if( sizeof(LONGDOUBLE_TYPE)>8 ){ LONGDOUBLE_TYPE x = (LONGDOUBLE_TYPE)i; if( xr ) return +1; return 0; }else{ i64 y; double s; if( r<-9223372036854775808.0 ) return +1; if( r>9223372036854775807.0 ) return -1; y = (i64)r; if( iy ){ if( y==SMALLEST_INT64 && r>0.0 ) return -1; return +1; } s = (double)i; if( sr ) return +1; return 0; } } /* ** Compare the values contained by the two memory cells, returning ** negative, zero or positive if pMem1 is less than, equal to, or greater ** than pMem2. Sorting order is NULL's first, followed by numbers (integers ** and reals) sorted numerically, followed by text ordered by the collating ** sequence pColl and finally blob's ordered by memcmp(). ** ** Two NULL values are considered equal by this function. */ SQLITE_PRIVATE int sqlite3MemCompare(const Mem *pMem1, const Mem *pMem2, const CollSeq *pColl){ int f1, f2; int combined_flags; f1 = pMem1->flags; f2 = pMem2->flags; combined_flags = f1|f2; assert( (combined_flags & MEM_RowSet)==0 ); /* If one value is NULL, it is less than the other. If both values ** are NULL, return 0. */ if( combined_flags&MEM_Null ){ return (f2&MEM_Null) - (f1&MEM_Null); } /* At least one of the two values is a number */ if( combined_flags&(MEM_Int|MEM_Real) ){ if( (f1 & f2 & MEM_Int)!=0 ){ if( pMem1->u.i < pMem2->u.i ) return -1; if( pMem1->u.i > pMem2->u.i ) return +1; return 0; } if( (f1 & f2 & MEM_Real)!=0 ){ if( pMem1->u.r < pMem2->u.r ) return -1; if( pMem1->u.r > pMem2->u.r ) return +1; return 0; } if( (f1&MEM_Int)!=0 ){ if( (f2&MEM_Real)!=0 ){ return sqlite3IntFloatCompare(pMem1->u.i, pMem2->u.r); }else{ return -1; } } if( (f1&MEM_Real)!=0 ){ if( (f2&MEM_Int)!=0 ){ return -sqlite3IntFloatCompare(pMem2->u.i, pMem1->u.r); }else{ return -1; } } return +1; } /* If one value is a string and the other is a blob, the string is less. ** If both are strings, compare using the collating functions. */ if( combined_flags&MEM_Str ){ if( (f1 & MEM_Str)==0 ){ return 1; } if( (f2 & MEM_Str)==0 ){ return -1; } assert( pMem1->enc==pMem2->enc || pMem1->db->mallocFailed ); assert( pMem1->enc==SQLITE_UTF8 || pMem1->enc==SQLITE_UTF16LE || pMem1->enc==SQLITE_UTF16BE ); /* The collation sequence must be defined at this point, even if ** the user deletes the collation sequence after the vdbe program is ** compiled (this was not always the case). */ assert( !pColl || pColl->xCmp ); if( pColl ){ return vdbeCompareMemString(pMem1, pMem2, pColl, 0); } /* If a NULL pointer was passed as the collate function, fall through ** to the blob case and use memcmp(). */ } /* Both values must be blobs. Compare using memcmp(). */ return sqlite3BlobCompare(pMem1, pMem2); } /* ** The first argument passed to this function is a serial-type that ** corresponds to an integer - all values between 1 and 9 inclusive ** except 7. The second points to a buffer containing an integer value ** serialized according to serial_type. This function deserializes ** and returns the value. */ static i64 vdbeRecordDecodeInt(u32 serial_type, const u8 *aKey){ u32 y; assert( CORRUPT_DB || (serial_type>=1 && serial_type<=9 && serial_type!=7) ); switch( serial_type ){ case 0: case 1: testcase( aKey[0]&0x80 ); return ONE_BYTE_INT(aKey); case 2: testcase( aKey[0]&0x80 ); return TWO_BYTE_INT(aKey); case 3: testcase( aKey[0]&0x80 ); return THREE_BYTE_INT(aKey); case 4: { testcase( aKey[0]&0x80 ); y = FOUR_BYTE_UINT(aKey); return (i64)*(int*)&y; } case 5: { testcase( aKey[0]&0x80 ); return FOUR_BYTE_UINT(aKey+2) + (((i64)1)<<32)*TWO_BYTE_INT(aKey); } case 6: { u64 x = FOUR_BYTE_UINT(aKey); testcase( aKey[0]&0x80 ); x = (x<<32) | FOUR_BYTE_UINT(aKey+4); return (i64)*(i64*)&x; } } return (serial_type - 8); } /* ** This function compares the two table rows or index records ** specified by {nKey1, pKey1} and pPKey2. It returns a negative, zero ** or positive integer if key1 is less than, equal to or ** greater than key2. The {nKey1, pKey1} key must be a blob ** created by the OP_MakeRecord opcode of the VDBE. The pPKey2 ** key must be a parsed key such as obtained from ** sqlite3VdbeParseRecord. ** ** If argument bSkip is non-zero, it is assumed that the caller has already ** determined that the first fields of the keys are equal. ** ** Key1 and Key2 do not have to contain the same number of fields. If all ** fields that appear in both keys are equal, then pPKey2->default_rc is ** returned. ** ** If database corruption is discovered, set pPKey2->errCode to ** SQLITE_CORRUPT and return 0. If an OOM error is encountered, ** pPKey2->errCode is set to SQLITE_NOMEM and, if it is not NULL, the ** malloc-failed flag set on database handle (pPKey2->pKeyInfo->db). */ SQLITE_PRIVATE int sqlite3VdbeRecordCompareWithSkip( int nKey1, const void *pKey1, /* Left key */ UnpackedRecord *pPKey2, /* Right key */ int bSkip /* If true, skip the first field */ ){ u32 d1; /* Offset into aKey[] of next data element */ int i; /* Index of next field to compare */ u32 szHdr1; /* Size of record header in bytes */ u32 idx1; /* Offset of first type in header */ int rc = 0; /* Return value */ Mem *pRhs = pPKey2->aMem; /* Next field of pPKey2 to compare */ KeyInfo *pKeyInfo = pPKey2->pKeyInfo; const unsigned char *aKey1 = (const unsigned char *)pKey1; Mem mem1; /* If bSkip is true, then the caller has already determined that the first ** two elements in the keys are equal. Fix the various stack variables so ** that this routine begins comparing at the second field. */ if( bSkip ){ u32 s1; idx1 = 1 + getVarint32(&aKey1[1], s1); szHdr1 = aKey1[0]; d1 = szHdr1 + sqlite3VdbeSerialTypeLen(s1); i = 1; pRhs++; }else{ idx1 = getVarint32(aKey1, szHdr1); d1 = szHdr1; if( d1>(unsigned)nKey1 ){ pPKey2->errCode = (u8)SQLITE_CORRUPT_BKPT; return 0; /* Corruption */ } i = 0; } VVA_ONLY( mem1.szMalloc = 0; ) /* Only needed by assert() statements */ assert( pPKey2->pKeyInfo->nField+pPKey2->pKeyInfo->nXField>=pPKey2->nField || CORRUPT_DB ); assert( pPKey2->pKeyInfo->aSortOrder!=0 ); assert( pPKey2->pKeyInfo->nField>0 ); assert( idx1<=szHdr1 || CORRUPT_DB ); do{ u32 serial_type; /* RHS is an integer */ if( pRhs->flags & MEM_Int ){ serial_type = aKey1[idx1]; testcase( serial_type==12 ); if( serial_type>=10 ){ rc = +1; }else if( serial_type==0 ){ rc = -1; }else if( serial_type==7 ){ sqlite3VdbeSerialGet(&aKey1[d1], serial_type, &mem1); rc = -sqlite3IntFloatCompare(pRhs->u.i, mem1.u.r); }else{ i64 lhs = vdbeRecordDecodeInt(serial_type, &aKey1[d1]); i64 rhs = pRhs->u.i; if( lhsrhs ){ rc = +1; } } } /* RHS is real */ else if( pRhs->flags & MEM_Real ){ serial_type = aKey1[idx1]; if( serial_type>=10 ){ /* Serial types 12 or greater are strings and blobs (greater than ** numbers). Types 10 and 11 are currently "reserved for future ** use", so it doesn't really matter what the results of comparing ** them to numberic values are. */ rc = +1; }else if( serial_type==0 ){ rc = -1; }else{ sqlite3VdbeSerialGet(&aKey1[d1], serial_type, &mem1); if( serial_type==7 ){ if( mem1.u.ru.r ){ rc = -1; }else if( mem1.u.r>pRhs->u.r ){ rc = +1; } }else{ rc = sqlite3IntFloatCompare(mem1.u.i, pRhs->u.r); } } } /* RHS is a string */ else if( pRhs->flags & MEM_Str ){ getVarint32(&aKey1[idx1], serial_type); testcase( serial_type==12 ); if( serial_type<12 ){ rc = -1; }else if( !(serial_type & 0x01) ){ rc = +1; }else{ mem1.n = (serial_type - 12) / 2; testcase( (d1+mem1.n)==(unsigned)nKey1 ); testcase( (d1+mem1.n+1)==(unsigned)nKey1 ); if( (d1+mem1.n) > (unsigned)nKey1 ){ pPKey2->errCode = (u8)SQLITE_CORRUPT_BKPT; return 0; /* Corruption */ }else if( pKeyInfo->aColl[i] ){ mem1.enc = pKeyInfo->enc; mem1.db = pKeyInfo->db; mem1.flags = MEM_Str; mem1.z = (char*)&aKey1[d1]; rc = vdbeCompareMemString( &mem1, pRhs, pKeyInfo->aColl[i], &pPKey2->errCode ); }else{ int nCmp = MIN(mem1.n, pRhs->n); rc = memcmp(&aKey1[d1], pRhs->z, nCmp); if( rc==0 ) rc = mem1.n - pRhs->n; } } } /* RHS is a blob */ else if( pRhs->flags & MEM_Blob ){ assert( (pRhs->flags & MEM_Zero)==0 || pRhs->n==0 ); getVarint32(&aKey1[idx1], serial_type); testcase( serial_type==12 ); if( serial_type<12 || (serial_type & 0x01) ){ rc = -1; }else{ int nStr = (serial_type - 12) / 2; testcase( (d1+nStr)==(unsigned)nKey1 ); testcase( (d1+nStr+1)==(unsigned)nKey1 ); if( (d1+nStr) > (unsigned)nKey1 ){ pPKey2->errCode = (u8)SQLITE_CORRUPT_BKPT; return 0; /* Corruption */ }else if( pRhs->flags & MEM_Zero ){ if( !isAllZero((const char*)&aKey1[d1],nStr) ){ rc = 1; }else{ rc = nStr - pRhs->u.nZero; } }else{ int nCmp = MIN(nStr, pRhs->n); rc = memcmp(&aKey1[d1], pRhs->z, nCmp); if( rc==0 ) rc = nStr - pRhs->n; } } } /* RHS is null */ else{ serial_type = aKey1[idx1]; rc = (serial_type!=0); } if( rc!=0 ){ if( pKeyInfo->aSortOrder[i] ){ rc = -rc; } assert( vdbeRecordCompareDebug(nKey1, pKey1, pPKey2, rc) ); assert( mem1.szMalloc==0 ); /* See comment below */ return rc; } i++; pRhs++; d1 += sqlite3VdbeSerialTypeLen(serial_type); idx1 += sqlite3VarintLen(serial_type); }while( idx1<(unsigned)szHdr1 && inField && d1<=(unsigned)nKey1 ); /* No memory allocation is ever used on mem1. Prove this using ** the following assert(). If the assert() fails, it indicates a ** memory leak and a need to call sqlite3VdbeMemRelease(&mem1). */ assert( mem1.szMalloc==0 ); /* rc==0 here means that one or both of the keys ran out of fields and ** all the fields up to that point were equal. Return the default_rc ** value. */ assert( CORRUPT_DB || vdbeRecordCompareDebug(nKey1, pKey1, pPKey2, pPKey2->default_rc) || pKeyInfo->db->mallocFailed ); pPKey2->eqSeen = 1; return pPKey2->default_rc; } SQLITE_PRIVATE int sqlite3VdbeRecordCompare( int nKey1, const void *pKey1, /* Left key */ UnpackedRecord *pPKey2 /* Right key */ ){ return sqlite3VdbeRecordCompareWithSkip(nKey1, pKey1, pPKey2, 0); } /* ** This function is an optimized version of sqlite3VdbeRecordCompare() ** that (a) the first field of pPKey2 is an integer, and (b) the ** size-of-header varint at the start of (pKey1/nKey1) fits in a single ** byte (i.e. is less than 128). ** ** To avoid concerns about buffer overreads, this routine is only used ** on schemas where the maximum valid header size is 63 bytes or less. */ static int vdbeRecordCompareInt( int nKey1, const void *pKey1, /* Left key */ UnpackedRecord *pPKey2 /* Right key */ ){ const u8 *aKey = &((const u8*)pKey1)[*(const u8*)pKey1 & 0x3F]; int serial_type = ((const u8*)pKey1)[1]; int res; u32 y; u64 x; i64 v; i64 lhs; vdbeAssertFieldCountWithinLimits(nKey1, pKey1, pPKey2->pKeyInfo); assert( (*(u8*)pKey1)<=0x3F || CORRUPT_DB ); switch( serial_type ){ case 1: { /* 1-byte signed integer */ lhs = ONE_BYTE_INT(aKey); testcase( lhs<0 ); break; } case 2: { /* 2-byte signed integer */ lhs = TWO_BYTE_INT(aKey); testcase( lhs<0 ); break; } case 3: { /* 3-byte signed integer */ lhs = THREE_BYTE_INT(aKey); testcase( lhs<0 ); break; } case 4: { /* 4-byte signed integer */ y = FOUR_BYTE_UINT(aKey); lhs = (i64)*(int*)&y; testcase( lhs<0 ); break; } case 5: { /* 6-byte signed integer */ lhs = FOUR_BYTE_UINT(aKey+2) + (((i64)1)<<32)*TWO_BYTE_INT(aKey); testcase( lhs<0 ); break; } case 6: { /* 8-byte signed integer */ x = FOUR_BYTE_UINT(aKey); x = (x<<32) | FOUR_BYTE_UINT(aKey+4); lhs = *(i64*)&x; testcase( lhs<0 ); break; } case 8: lhs = 0; break; case 9: lhs = 1; break; /* This case could be removed without changing the results of running ** this code. Including it causes gcc to generate a faster switch ** statement (since the range of switch targets now starts at zero and ** is contiguous) but does not cause any duplicate code to be generated ** (as gcc is clever enough to combine the two like cases). Other ** compilers might be similar. */ case 0: case 7: return sqlite3VdbeRecordCompare(nKey1, pKey1, pPKey2); default: return sqlite3VdbeRecordCompare(nKey1, pKey1, pPKey2); } v = pPKey2->aMem[0].u.i; if( v>lhs ){ res = pPKey2->r1; }else if( vr2; }else if( pPKey2->nField>1 ){ /* The first fields of the two keys are equal. Compare the trailing ** fields. */ res = sqlite3VdbeRecordCompareWithSkip(nKey1, pKey1, pPKey2, 1); }else{ /* The first fields of the two keys are equal and there are no trailing ** fields. Return pPKey2->default_rc in this case. */ res = pPKey2->default_rc; pPKey2->eqSeen = 1; } assert( vdbeRecordCompareDebug(nKey1, pKey1, pPKey2, res) ); return res; } /* ** This function is an optimized version of sqlite3VdbeRecordCompare() ** that (a) the first field of pPKey2 is a string, that (b) the first field ** uses the collation sequence BINARY and (c) that the size-of-header varint ** at the start of (pKey1/nKey1) fits in a single byte. */ static int vdbeRecordCompareString( int nKey1, const void *pKey1, /* Left key */ UnpackedRecord *pPKey2 /* Right key */ ){ const u8 *aKey1 = (const u8*)pKey1; int serial_type; int res; assert( pPKey2->aMem[0].flags & MEM_Str ); vdbeAssertFieldCountWithinLimits(nKey1, pKey1, pPKey2->pKeyInfo); getVarint32(&aKey1[1], serial_type); if( serial_type<12 ){ res = pPKey2->r1; /* (pKey1/nKey1) is a number or a null */ }else if( !(serial_type & 0x01) ){ res = pPKey2->r2; /* (pKey1/nKey1) is a blob */ }else{ int nCmp; int nStr; int szHdr = aKey1[0]; nStr = (serial_type-12) / 2; if( (szHdr + nStr) > nKey1 ){ pPKey2->errCode = (u8)SQLITE_CORRUPT_BKPT; return 0; /* Corruption */ } nCmp = MIN( pPKey2->aMem[0].n, nStr ); res = memcmp(&aKey1[szHdr], pPKey2->aMem[0].z, nCmp); if( res==0 ){ res = nStr - pPKey2->aMem[0].n; if( res==0 ){ if( pPKey2->nField>1 ){ res = sqlite3VdbeRecordCompareWithSkip(nKey1, pKey1, pPKey2, 1); }else{ res = pPKey2->default_rc; pPKey2->eqSeen = 1; } }else if( res>0 ){ res = pPKey2->r2; }else{ res = pPKey2->r1; } }else if( res>0 ){ res = pPKey2->r2; }else{ res = pPKey2->r1; } } assert( vdbeRecordCompareDebug(nKey1, pKey1, pPKey2, res) || CORRUPT_DB || pPKey2->pKeyInfo->db->mallocFailed ); return res; } /* ** Return a pointer to an sqlite3VdbeRecordCompare() compatible function ** suitable for comparing serialized records to the unpacked record passed ** as the only argument. */ SQLITE_PRIVATE RecordCompare sqlite3VdbeFindCompare(UnpackedRecord *p){ /* varintRecordCompareInt() and varintRecordCompareString() both assume ** that the size-of-header varint that occurs at the start of each record ** fits in a single byte (i.e. is 127 or less). varintRecordCompareInt() ** also assumes that it is safe to overread a buffer by at least the ** maximum possible legal header size plus 8 bytes. Because there is ** guaranteed to be at least 74 (but not 136) bytes of padding following each ** buffer passed to varintRecordCompareInt() this makes it convenient to ** limit the size of the header to 64 bytes in cases where the first field ** is an integer. ** ** The easiest way to enforce this limit is to consider only records with ** 13 fields or less. If the first field is an integer, the maximum legal ** header size is (12*5 + 1 + 1) bytes. */ if( (p->pKeyInfo->nField + p->pKeyInfo->nXField)<=13 ){ int flags = p->aMem[0].flags; if( p->pKeyInfo->aSortOrder[0] ){ p->r1 = 1; p->r2 = -1; }else{ p->r1 = -1; p->r2 = 1; } if( (flags & MEM_Int) ){ return vdbeRecordCompareInt; } testcase( flags & MEM_Real ); testcase( flags & MEM_Null ); testcase( flags & MEM_Blob ); if( (flags & (MEM_Real|MEM_Null|MEM_Blob))==0 && p->pKeyInfo->aColl[0]==0 ){ assert( flags & MEM_Str ); return vdbeRecordCompareString; } } return sqlite3VdbeRecordCompare; } /* ** pCur points at an index entry created using the OP_MakeRecord opcode. ** Read the rowid (the last field in the record) and store it in *rowid. ** Return SQLITE_OK if everything works, or an error code otherwise. ** ** pCur might be pointing to text obtained from a corrupt database file. ** So the content cannot be trusted. Do appropriate checks on the content. */ SQLITE_PRIVATE int sqlite3VdbeIdxRowid(sqlite3 *db, BtCursor *pCur, i64 *rowid){ i64 nCellKey = 0; int rc; u32 szHdr; /* Size of the header */ u32 typeRowid; /* Serial type of the rowid */ u32 lenRowid; /* Size of the rowid */ Mem m, v; /* Get the size of the index entry. Only indices entries of less ** than 2GiB are support - anything large must be database corruption. ** Any corruption is detected in sqlite3BtreeParseCellPtr(), though, so ** this code can safely assume that nCellKey is 32-bits */ assert( sqlite3BtreeCursorIsValid(pCur) ); nCellKey = sqlite3BtreePayloadSize(pCur); assert( (nCellKey & SQLITE_MAX_U32)==(u64)nCellKey ); /* Read in the complete content of the index entry */ sqlite3VdbeMemInit(&m, db, 0); rc = sqlite3VdbeMemFromBtree(pCur, 0, (u32)nCellKey, 1, &m); if( rc ){ return rc; } /* The index entry must begin with a header size */ (void)getVarint32((u8*)m.z, szHdr); testcase( szHdr==3 ); testcase( szHdr==m.n ); if( unlikely(szHdr<3 || (int)szHdr>m.n) ){ goto idx_rowid_corruption; } /* The last field of the index should be an integer - the ROWID. ** Verify that the last entry really is an integer. */ (void)getVarint32((u8*)&m.z[szHdr-1], typeRowid); testcase( typeRowid==1 ); testcase( typeRowid==2 ); testcase( typeRowid==3 ); testcase( typeRowid==4 ); testcase( typeRowid==5 ); testcase( typeRowid==6 ); testcase( typeRowid==8 ); testcase( typeRowid==9 ); if( unlikely(typeRowid<1 || typeRowid>9 || typeRowid==7) ){ goto idx_rowid_corruption; } lenRowid = sqlite3SmallTypeSizes[typeRowid]; testcase( (u32)m.n==szHdr+lenRowid ); if( unlikely((u32)m.neCurType==CURTYPE_BTREE ); pCur = pC->uc.pCursor; assert( sqlite3BtreeCursorIsValid(pCur) ); nCellKey = sqlite3BtreePayloadSize(pCur); /* nCellKey will always be between 0 and 0xffffffff because of the way ** that btreeParseCellPtr() and sqlite3GetVarint32() are implemented */ if( nCellKey<=0 || nCellKey>0x7fffffff ){ *res = 0; return SQLITE_CORRUPT_BKPT; } sqlite3VdbeMemInit(&m, db, 0); rc = sqlite3VdbeMemFromBtree(pCur, 0, (u32)nCellKey, 1, &m); if( rc ){ return rc; } *res = sqlite3VdbeRecordCompare(m.n, m.z, pUnpacked); sqlite3VdbeMemRelease(&m); return SQLITE_OK; } /* ** This routine sets the value to be returned by subsequent calls to ** sqlite3_changes() on the database handle 'db'. */ SQLITE_PRIVATE void sqlite3VdbeSetChanges(sqlite3 *db, int nChange){ assert( sqlite3_mutex_held(db->mutex) ); db->nChange = nChange; db->nTotalChange += nChange; } /* ** Set a flag in the vdbe to update the change counter when it is finalised ** or reset. */ SQLITE_PRIVATE void sqlite3VdbeCountChanges(Vdbe *v){ v->changeCntOn = 1; } /* ** Mark every prepared statement associated with a database connection ** as expired. ** ** An expired statement means that recompilation of the statement is ** recommend. Statements expire when things happen that make their ** programs obsolete. Removing user-defined functions or collating ** sequences, or changing an authorization function are the types of ** things that make prepared statements obsolete. */ SQLITE_PRIVATE void sqlite3ExpirePreparedStatements(sqlite3 *db){ Vdbe *p; for(p = db->pVdbe; p; p=p->pNext){ p->expired = 1; } } /* ** Return the database associated with the Vdbe. */ SQLITE_PRIVATE sqlite3 *sqlite3VdbeDb(Vdbe *v){ return v->db; } /* ** Return a pointer to an sqlite3_value structure containing the value bound ** parameter iVar of VM v. Except, if the value is an SQL NULL, return ** 0 instead. Unless it is NULL, apply affinity aff (one of the SQLITE_AFF_* ** constants) to the value before returning it. ** ** The returned value must be freed by the caller using sqlite3ValueFree(). */ SQLITE_PRIVATE sqlite3_value *sqlite3VdbeGetBoundValue(Vdbe *v, int iVar, u8 aff){ assert( iVar>0 ); if( v ){ Mem *pMem = &v->aVar[iVar-1]; if( 0==(pMem->flags & MEM_Null) ){ sqlite3_value *pRet = sqlite3ValueNew(v->db); if( pRet ){ sqlite3VdbeMemCopy((Mem *)pRet, pMem); sqlite3ValueApplyAffinity(pRet, aff, SQLITE_UTF8); } return pRet; } } return 0; } /* ** Configure SQL variable iVar so that binding a new value to it signals ** to sqlite3_reoptimize() that re-preparing the statement may result ** in a better query plan. */ SQLITE_PRIVATE void sqlite3VdbeSetVarmask(Vdbe *v, int iVar){ assert( iVar>0 ); if( iVar>32 ){ v->expmask = 0xffffffff; }else{ v->expmask |= ((u32)1 << (iVar-1)); } } #ifndef SQLITE_OMIT_VIRTUALTABLE /* ** Transfer error message text from an sqlite3_vtab.zErrMsg (text stored ** in memory obtained from sqlite3_malloc) into a Vdbe.zErrMsg (text stored ** in memory obtained from sqlite3DbMalloc). */ SQLITE_PRIVATE void sqlite3VtabImportErrmsg(Vdbe *p, sqlite3_vtab *pVtab){ if( pVtab->zErrMsg ){ sqlite3 *db = p->db; sqlite3DbFree(db, p->zErrMsg); p->zErrMsg = sqlite3DbStrDup(db, pVtab->zErrMsg); sqlite3_free(pVtab->zErrMsg); pVtab->zErrMsg = 0; } } #endif /* SQLITE_OMIT_VIRTUALTABLE */ #ifdef SQLITE_ENABLE_PREUPDATE_HOOK /* ** If the second argument is not NULL, release any allocations associated ** with the memory cells in the p->aMem[] array. Also free the UnpackedRecord ** structure itself, using sqlite3DbFree(). ** ** This function is used to free UnpackedRecord structures allocated by ** the vdbeUnpackRecord() function found in vdbeapi.c. */ static void vdbeFreeUnpacked(sqlite3 *db, UnpackedRecord *p){ if( p ){ int i; for(i=0; inField; i++){ Mem *pMem = &p->aMem[i]; if( pMem->zMalloc ) sqlite3VdbeMemRelease(pMem); } sqlite3DbFree(db, p); } } #endif /* SQLITE_ENABLE_PREUPDATE_HOOK */ #ifdef SQLITE_ENABLE_PREUPDATE_HOOK /* ** Invoke the pre-update hook. If this is an UPDATE or DELETE pre-update call, ** then cursor passed as the second argument should point to the row about ** to be update or deleted. If the application calls sqlite3_preupdate_old(), ** the required value will be read from the row the cursor points to. */ SQLITE_PRIVATE void sqlite3VdbePreUpdateHook( Vdbe *v, /* Vdbe pre-update hook is invoked by */ VdbeCursor *pCsr, /* Cursor to grab old.* values from */ int op, /* SQLITE_INSERT, UPDATE or DELETE */ const char *zDb, /* Database name */ Table *pTab, /* Modified table */ i64 iKey1, /* Initial key value */ int iReg /* Register for new.* record */ ){ sqlite3 *db = v->db; i64 iKey2; PreUpdate preupdate; const char *zTbl = pTab->zName; static const u8 fakeSortOrder = 0; assert( db->pPreUpdate==0 ); memset(&preupdate, 0, sizeof(PreUpdate)); if( op==SQLITE_UPDATE ){ iKey2 = v->aMem[iReg].u.i; }else{ iKey2 = iKey1; } assert( pCsr->nField==pTab->nCol || (pCsr->nField==pTab->nCol+1 && op==SQLITE_DELETE && iReg==-1) ); preupdate.v = v; preupdate.pCsr = pCsr; preupdate.op = op; preupdate.iNewReg = iReg; preupdate.keyinfo.db = db; preupdate.keyinfo.enc = ENC(db); preupdate.keyinfo.nField = pTab->nCol; preupdate.keyinfo.aSortOrder = (u8*)&fakeSortOrder; preupdate.iKey1 = iKey1; preupdate.iKey2 = iKey2; preupdate.pTab = pTab; db->pPreUpdate = &preupdate; db->xPreUpdateCallback(db->pPreUpdateArg, db, op, zDb, zTbl, iKey1, iKey2); db->pPreUpdate = 0; sqlite3DbFree(db, preupdate.aRecord); vdbeFreeUnpacked(db, preupdate.pUnpacked); vdbeFreeUnpacked(db, preupdate.pNewUnpacked); if( preupdate.aNew ){ int i; for(i=0; inField; i++){ sqlite3VdbeMemRelease(&preupdate.aNew[i]); } sqlite3DbFree(db, preupdate.aNew); } } #endif /* SQLITE_ENABLE_PREUPDATE_HOOK */ /************** End of vdbeaux.c *********************************************/ /************** Begin file vdbeapi.c *****************************************/ /* ** 2004 May 26 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ************************************************************************* ** ** This file contains code use to implement APIs that are part of the ** VDBE. */ /* #include "sqliteInt.h" */ /* #include "vdbeInt.h" */ #ifndef SQLITE_OMIT_DEPRECATED /* ** Return TRUE (non-zero) of the statement supplied as an argument needs ** to be recompiled. A statement needs to be recompiled whenever the ** execution environment changes in a way that would alter the program ** that sqlite3_prepare() generates. For example, if new functions or ** collating sequences are registered or if an authorizer function is ** added or changed. */ SQLITE_API int sqlite3_expired(sqlite3_stmt *pStmt){ Vdbe *p = (Vdbe*)pStmt; return p==0 || p->expired; } #endif /* ** Check on a Vdbe to make sure it has not been finalized. Log ** an error and return true if it has been finalized (or is otherwise ** invalid). Return false if it is ok. */ static int vdbeSafety(Vdbe *p){ if( p->db==0 ){ sqlite3_log(SQLITE_MISUSE, "API called with finalized prepared statement"); return 1; }else{ return 0; } } static int vdbeSafetyNotNull(Vdbe *p){ if( p==0 ){ sqlite3_log(SQLITE_MISUSE, "API called with NULL prepared statement"); return 1; }else{ return vdbeSafety(p); } } #ifndef SQLITE_OMIT_TRACE /* ** Invoke the profile callback. This routine is only called if we already ** know that the profile callback is defined and needs to be invoked. */ static SQLITE_NOINLINE void invokeProfileCallback(sqlite3 *db, Vdbe *p){ sqlite3_int64 iNow; sqlite3_int64 iElapse; assert( p->startTime>0 ); assert( db->xProfile!=0 || (db->mTrace & SQLITE_TRACE_PROFILE)!=0 ); assert( db->init.busy==0 ); assert( p->zSql!=0 ); sqlite3OsCurrentTimeInt64(db->pVfs, &iNow); iElapse = (iNow - p->startTime)*1000000; if( db->xProfile ){ db->xProfile(db->pProfileArg, p->zSql, iElapse); } if( db->mTrace & SQLITE_TRACE_PROFILE ){ db->xTrace(SQLITE_TRACE_PROFILE, db->pTraceArg, p, (void*)&iElapse); } p->startTime = 0; } /* ** The checkProfileCallback(DB,P) macro checks to see if a profile callback ** is needed, and it invokes the callback if it is needed. */ # define checkProfileCallback(DB,P) \ if( ((P)->startTime)>0 ){ invokeProfileCallback(DB,P); } #else # define checkProfileCallback(DB,P) /*no-op*/ #endif /* ** The following routine destroys a virtual machine that is created by ** the sqlite3_compile() routine. The integer returned is an SQLITE_ ** success/failure code that describes the result of executing the virtual ** machine. ** ** This routine sets the error code and string returned by ** sqlite3_errcode(), sqlite3_errmsg() and sqlite3_errmsg16(). */ SQLITE_API int sqlite3_finalize(sqlite3_stmt *pStmt){ int rc; if( pStmt==0 ){ /* IMPLEMENTATION-OF: R-57228-12904 Invoking sqlite3_finalize() on a NULL ** pointer is a harmless no-op. */ rc = SQLITE_OK; }else{ Vdbe *v = (Vdbe*)pStmt; sqlite3 *db = v->db; if( vdbeSafety(v) ) return SQLITE_MISUSE_BKPT; sqlite3_mutex_enter(db->mutex); checkProfileCallback(db, v); rc = sqlite3VdbeFinalize(v); rc = sqlite3ApiExit(db, rc); sqlite3LeaveMutexAndCloseZombie(db); } return rc; } /* ** Terminate the current execution of an SQL statement and reset it ** back to its starting state so that it can be reused. A success code from ** the prior execution is returned. ** ** This routine sets the error code and string returned by ** sqlite3_errcode(), sqlite3_errmsg() and sqlite3_errmsg16(). */ SQLITE_API int sqlite3_reset(sqlite3_stmt *pStmt){ int rc; if( pStmt==0 ){ rc = SQLITE_OK; }else{ Vdbe *v = (Vdbe*)pStmt; sqlite3 *db = v->db; sqlite3_mutex_enter(db->mutex); checkProfileCallback(db, v); rc = sqlite3VdbeReset(v); sqlite3VdbeRewind(v); assert( (rc & (db->errMask))==rc ); rc = sqlite3ApiExit(db, rc); sqlite3_mutex_leave(db->mutex); } return rc; } /* ** Set all the parameters in the compiled SQL statement to NULL. */ SQLITE_API int sqlite3_clear_bindings(sqlite3_stmt *pStmt){ int i; int rc = SQLITE_OK; Vdbe *p = (Vdbe*)pStmt; #if SQLITE_THREADSAFE sqlite3_mutex *mutex = ((Vdbe*)pStmt)->db->mutex; #endif sqlite3_mutex_enter(mutex); for(i=0; inVar; i++){ sqlite3VdbeMemRelease(&p->aVar[i]); p->aVar[i].flags = MEM_Null; } if( p->isPrepareV2 && p->expmask ){ p->expired = 1; } sqlite3_mutex_leave(mutex); return rc; } /**************************** sqlite3_value_ ******************************* ** The following routines extract information from a Mem or sqlite3_value ** structure. */ SQLITE_API const void *sqlite3_value_blob(sqlite3_value *pVal){ Mem *p = (Mem*)pVal; if( p->flags & (MEM_Blob|MEM_Str) ){ if( ExpandBlob(p)!=SQLITE_OK ){ assert( p->flags==MEM_Null && p->z==0 ); return 0; } p->flags |= MEM_Blob; return p->n ? p->z : 0; }else{ return sqlite3_value_text(pVal); } } SQLITE_API int sqlite3_value_bytes(sqlite3_value *pVal){ return sqlite3ValueBytes(pVal, SQLITE_UTF8); } SQLITE_API int sqlite3_value_bytes16(sqlite3_value *pVal){ return sqlite3ValueBytes(pVal, SQLITE_UTF16NATIVE); } SQLITE_API double sqlite3_value_double(sqlite3_value *pVal){ return sqlite3VdbeRealValue((Mem*)pVal); } SQLITE_API int sqlite3_value_int(sqlite3_value *pVal){ return (int)sqlite3VdbeIntValue((Mem*)pVal); } SQLITE_API sqlite_int64 sqlite3_value_int64(sqlite3_value *pVal){ return sqlite3VdbeIntValue((Mem*)pVal); } SQLITE_API unsigned int sqlite3_value_subtype(sqlite3_value *pVal){ Mem *pMem = (Mem*)pVal; return ((pMem->flags & MEM_Subtype) ? pMem->eSubtype : 0); } SQLITE_API const unsigned char *sqlite3_value_text(sqlite3_value *pVal){ return (const unsigned char *)sqlite3ValueText(pVal, SQLITE_UTF8); } #ifndef SQLITE_OMIT_UTF16 SQLITE_API const void *sqlite3_value_text16(sqlite3_value* pVal){ return sqlite3ValueText(pVal, SQLITE_UTF16NATIVE); } SQLITE_API const void *sqlite3_value_text16be(sqlite3_value *pVal){ return sqlite3ValueText(pVal, SQLITE_UTF16BE); } SQLITE_API const void *sqlite3_value_text16le(sqlite3_value *pVal){ return sqlite3ValueText(pVal, SQLITE_UTF16LE); } #endif /* SQLITE_OMIT_UTF16 */ /* EVIDENCE-OF: R-12793-43283 Every value in SQLite has one of five ** fundamental datatypes: 64-bit signed integer 64-bit IEEE floating ** point number string BLOB NULL */ SQLITE_API int sqlite3_value_type(sqlite3_value* pVal){ static const u8 aType[] = { SQLITE_BLOB, /* 0x00 */ SQLITE_NULL, /* 0x01 */ SQLITE_TEXT, /* 0x02 */ SQLITE_NULL, /* 0x03 */ SQLITE_INTEGER, /* 0x04 */ SQLITE_NULL, /* 0x05 */ SQLITE_INTEGER, /* 0x06 */ SQLITE_NULL, /* 0x07 */ SQLITE_FLOAT, /* 0x08 */ SQLITE_NULL, /* 0x09 */ SQLITE_FLOAT, /* 0x0a */ SQLITE_NULL, /* 0x0b */ SQLITE_INTEGER, /* 0x0c */ SQLITE_NULL, /* 0x0d */ SQLITE_INTEGER, /* 0x0e */ SQLITE_NULL, /* 0x0f */ SQLITE_BLOB, /* 0x10 */ SQLITE_NULL, /* 0x11 */ SQLITE_TEXT, /* 0x12 */ SQLITE_NULL, /* 0x13 */ SQLITE_INTEGER, /* 0x14 */ SQLITE_NULL, /* 0x15 */ SQLITE_INTEGER, /* 0x16 */ SQLITE_NULL, /* 0x17 */ SQLITE_FLOAT, /* 0x18 */ SQLITE_NULL, /* 0x19 */ SQLITE_FLOAT, /* 0x1a */ SQLITE_NULL, /* 0x1b */ SQLITE_INTEGER, /* 0x1c */ SQLITE_NULL, /* 0x1d */ SQLITE_INTEGER, /* 0x1e */ SQLITE_NULL, /* 0x1f */ }; return aType[pVal->flags&MEM_AffMask]; } /* Make a copy of an sqlite3_value object */ SQLITE_API sqlite3_value *sqlite3_value_dup(const sqlite3_value *pOrig){ sqlite3_value *pNew; if( pOrig==0 ) return 0; pNew = sqlite3_malloc( sizeof(*pNew) ); if( pNew==0 ) return 0; memset(pNew, 0, sizeof(*pNew)); memcpy(pNew, pOrig, MEMCELLSIZE); pNew->flags &= ~MEM_Dyn; pNew->db = 0; if( pNew->flags&(MEM_Str|MEM_Blob) ){ pNew->flags &= ~(MEM_Static|MEM_Dyn); pNew->flags |= MEM_Ephem; if( sqlite3VdbeMemMakeWriteable(pNew)!=SQLITE_OK ){ sqlite3ValueFree(pNew); pNew = 0; } } return pNew; } /* Destroy an sqlite3_value object previously obtained from ** sqlite3_value_dup(). */ SQLITE_API void sqlite3_value_free(sqlite3_value *pOld){ sqlite3ValueFree(pOld); } /**************************** sqlite3_result_ ******************************* ** The following routines are used by user-defined functions to specify ** the function result. ** ** The setStrOrError() function calls sqlite3VdbeMemSetStr() to store the ** result as a string or blob but if the string or blob is too large, it ** then sets the error code to SQLITE_TOOBIG ** ** The invokeValueDestructor(P,X) routine invokes destructor function X() ** on value P is not going to be used and need to be destroyed. */ static void setResultStrOrError( sqlite3_context *pCtx, /* Function context */ const char *z, /* String pointer */ int n, /* Bytes in string, or negative */ u8 enc, /* Encoding of z. 0 for BLOBs */ void (*xDel)(void*) /* Destructor function */ ){ if( sqlite3VdbeMemSetStr(pCtx->pOut, z, n, enc, xDel)==SQLITE_TOOBIG ){ sqlite3_result_error_toobig(pCtx); } } static int invokeValueDestructor( const void *p, /* Value to destroy */ void (*xDel)(void*), /* The destructor */ sqlite3_context *pCtx /* Set a SQLITE_TOOBIG error if no NULL */ ){ assert( xDel!=SQLITE_DYNAMIC ); if( xDel==0 ){ /* noop */ }else if( xDel==SQLITE_TRANSIENT ){ /* noop */ }else{ xDel((void*)p); } if( pCtx ) sqlite3_result_error_toobig(pCtx); return SQLITE_TOOBIG; } SQLITE_API void sqlite3_result_blob( sqlite3_context *pCtx, const void *z, int n, void (*xDel)(void *) ){ assert( n>=0 ); assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) ); setResultStrOrError(pCtx, z, n, 0, xDel); } SQLITE_API void sqlite3_result_blob64( sqlite3_context *pCtx, const void *z, sqlite3_uint64 n, void (*xDel)(void *) ){ assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) ); assert( xDel!=SQLITE_DYNAMIC ); if( n>0x7fffffff ){ (void)invokeValueDestructor(z, xDel, pCtx); }else{ setResultStrOrError(pCtx, z, (int)n, 0, xDel); } } SQLITE_API void sqlite3_result_double(sqlite3_context *pCtx, double rVal){ assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) ); sqlite3VdbeMemSetDouble(pCtx->pOut, rVal); } SQLITE_API void sqlite3_result_error(sqlite3_context *pCtx, const char *z, int n){ assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) ); pCtx->isError = SQLITE_ERROR; pCtx->fErrorOrAux = 1; sqlite3VdbeMemSetStr(pCtx->pOut, z, n, SQLITE_UTF8, SQLITE_TRANSIENT); } #ifndef SQLITE_OMIT_UTF16 SQLITE_API void sqlite3_result_error16(sqlite3_context *pCtx, const void *z, int n){ assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) ); pCtx->isError = SQLITE_ERROR; pCtx->fErrorOrAux = 1; sqlite3VdbeMemSetStr(pCtx->pOut, z, n, SQLITE_UTF16NATIVE, SQLITE_TRANSIENT); } #endif SQLITE_API void sqlite3_result_int(sqlite3_context *pCtx, int iVal){ assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) ); sqlite3VdbeMemSetInt64(pCtx->pOut, (i64)iVal); } SQLITE_API void sqlite3_result_int64(sqlite3_context *pCtx, i64 iVal){ assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) ); sqlite3VdbeMemSetInt64(pCtx->pOut, iVal); } SQLITE_API void sqlite3_result_null(sqlite3_context *pCtx){ assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) ); sqlite3VdbeMemSetNull(pCtx->pOut); } SQLITE_API void sqlite3_result_subtype(sqlite3_context *pCtx, unsigned int eSubtype){ Mem *pOut = pCtx->pOut; assert( sqlite3_mutex_held(pOut->db->mutex) ); pOut->eSubtype = eSubtype & 0xff; pOut->flags |= MEM_Subtype; } SQLITE_API void sqlite3_result_text( sqlite3_context *pCtx, const char *z, int n, void (*xDel)(void *) ){ assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) ); setResultStrOrError(pCtx, z, n, SQLITE_UTF8, xDel); } SQLITE_API void sqlite3_result_text64( sqlite3_context *pCtx, const char *z, sqlite3_uint64 n, void (*xDel)(void *), unsigned char enc ){ assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) ); assert( xDel!=SQLITE_DYNAMIC ); if( enc==SQLITE_UTF16 ) enc = SQLITE_UTF16NATIVE; if( n>0x7fffffff ){ (void)invokeValueDestructor(z, xDel, pCtx); }else{ setResultStrOrError(pCtx, z, (int)n, enc, xDel); } } #ifndef SQLITE_OMIT_UTF16 SQLITE_API void sqlite3_result_text16( sqlite3_context *pCtx, const void *z, int n, void (*xDel)(void *) ){ assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) ); setResultStrOrError(pCtx, z, n, SQLITE_UTF16NATIVE, xDel); } SQLITE_API void sqlite3_result_text16be( sqlite3_context *pCtx, const void *z, int n, void (*xDel)(void *) ){ assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) ); setResultStrOrError(pCtx, z, n, SQLITE_UTF16BE, xDel); } SQLITE_API void sqlite3_result_text16le( sqlite3_context *pCtx, const void *z, int n, void (*xDel)(void *) ){ assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) ); setResultStrOrError(pCtx, z, n, SQLITE_UTF16LE, xDel); } #endif /* SQLITE_OMIT_UTF16 */ SQLITE_API void sqlite3_result_value(sqlite3_context *pCtx, sqlite3_value *pValue){ assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) ); sqlite3VdbeMemCopy(pCtx->pOut, pValue); } SQLITE_API void sqlite3_result_zeroblob(sqlite3_context *pCtx, int n){ assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) ); sqlite3VdbeMemSetZeroBlob(pCtx->pOut, n); } SQLITE_API int sqlite3_result_zeroblob64(sqlite3_context *pCtx, u64 n){ Mem *pOut = pCtx->pOut; assert( sqlite3_mutex_held(pOut->db->mutex) ); if( n>(u64)pOut->db->aLimit[SQLITE_LIMIT_LENGTH] ){ return SQLITE_TOOBIG; } sqlite3VdbeMemSetZeroBlob(pCtx->pOut, (int)n); return SQLITE_OK; } SQLITE_API void sqlite3_result_error_code(sqlite3_context *pCtx, int errCode){ pCtx->isError = errCode; pCtx->fErrorOrAux = 1; #ifdef SQLITE_DEBUG if( pCtx->pVdbe ) pCtx->pVdbe->rcApp = errCode; #endif if( pCtx->pOut->flags & MEM_Null ){ sqlite3VdbeMemSetStr(pCtx->pOut, sqlite3ErrStr(errCode), -1, SQLITE_UTF8, SQLITE_STATIC); } } /* Force an SQLITE_TOOBIG error. */ SQLITE_API void sqlite3_result_error_toobig(sqlite3_context *pCtx){ assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) ); pCtx->isError = SQLITE_TOOBIG; pCtx->fErrorOrAux = 1; sqlite3VdbeMemSetStr(pCtx->pOut, "string or blob too big", -1, SQLITE_UTF8, SQLITE_STATIC); } /* An SQLITE_NOMEM error. */ SQLITE_API void sqlite3_result_error_nomem(sqlite3_context *pCtx){ assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) ); sqlite3VdbeMemSetNull(pCtx->pOut); pCtx->isError = SQLITE_NOMEM_BKPT; pCtx->fErrorOrAux = 1; sqlite3OomFault(pCtx->pOut->db); } /* ** This function is called after a transaction has been committed. It ** invokes callbacks registered with sqlite3_wal_hook() as required. */ static int doWalCallbacks(sqlite3 *db){ int rc = SQLITE_OK; #ifndef SQLITE_OMIT_WAL int i; for(i=0; inDb; i++){ Btree *pBt = db->aDb[i].pBt; if( pBt ){ int nEntry; sqlite3BtreeEnter(pBt); nEntry = sqlite3PagerWalCallback(sqlite3BtreePager(pBt)); sqlite3BtreeLeave(pBt); if( db->xWalCallback && nEntry>0 && rc==SQLITE_OK ){ rc = db->xWalCallback(db->pWalArg, db, db->aDb[i].zDbSName, nEntry); } } } #endif return rc; } /* ** Execute the statement pStmt, either until a row of data is ready, the ** statement is completely executed or an error occurs. ** ** This routine implements the bulk of the logic behind the sqlite_step() ** API. The only thing omitted is the automatic recompile if a ** schema change has occurred. That detail is handled by the ** outer sqlite3_step() wrapper procedure. */ static int sqlite3Step(Vdbe *p){ sqlite3 *db; int rc; assert(p); if( p->magic!=VDBE_MAGIC_RUN ){ /* We used to require that sqlite3_reset() be called before retrying ** sqlite3_step() after any error or after SQLITE_DONE. But beginning ** with version 3.7.0, we changed this so that sqlite3_reset() would ** be called automatically instead of throwing the SQLITE_MISUSE error. ** This "automatic-reset" change is not technically an incompatibility, ** since any application that receives an SQLITE_MISUSE is broken by ** definition. ** ** Nevertheless, some published applications that were originally written ** for version 3.6.23 or earlier do in fact depend on SQLITE_MISUSE ** returns, and those were broken by the automatic-reset change. As a ** a work-around, the SQLITE_OMIT_AUTORESET compile-time restores the ** legacy behavior of returning SQLITE_MISUSE for cases where the ** previous sqlite3_step() returned something other than a SQLITE_LOCKED ** or SQLITE_BUSY error. */ #ifdef SQLITE_OMIT_AUTORESET if( (rc = p->rc&0xff)==SQLITE_BUSY || rc==SQLITE_LOCKED ){ sqlite3_reset((sqlite3_stmt*)p); }else{ return SQLITE_MISUSE_BKPT; } #else sqlite3_reset((sqlite3_stmt*)p); #endif } /* Check that malloc() has not failed. If it has, return early. */ db = p->db; if( db->mallocFailed ){ p->rc = SQLITE_NOMEM; return SQLITE_NOMEM_BKPT; } if( p->pc<=0 && p->expired ){ p->rc = SQLITE_SCHEMA; rc = SQLITE_ERROR; goto end_of_step; } if( p->pc<0 ){ /* If there are no other statements currently running, then ** reset the interrupt flag. This prevents a call to sqlite3_interrupt ** from interrupting a statement that has not yet started. */ if( db->nVdbeActive==0 ){ db->u1.isInterrupted = 0; } assert( db->nVdbeWrite>0 || db->autoCommit==0 || (db->nDeferredCons==0 && db->nDeferredImmCons==0) ); #ifndef SQLITE_OMIT_TRACE if( (db->xProfile || (db->mTrace & SQLITE_TRACE_PROFILE)!=0) && !db->init.busy && p->zSql ){ sqlite3OsCurrentTimeInt64(db->pVfs, &p->startTime); }else{ assert( p->startTime==0 ); } #endif db->nVdbeActive++; if( p->readOnly==0 ) db->nVdbeWrite++; if( p->bIsReader ) db->nVdbeRead++; p->pc = 0; } #ifdef SQLITE_DEBUG p->rcApp = SQLITE_OK; #endif #ifndef SQLITE_OMIT_EXPLAIN if( p->explain ){ rc = sqlite3VdbeList(p); }else #endif /* SQLITE_OMIT_EXPLAIN */ { db->nVdbeExec++; rc = sqlite3VdbeExec(p); db->nVdbeExec--; } #ifndef SQLITE_OMIT_TRACE /* If the statement completed successfully, invoke the profile callback */ if( rc!=SQLITE_ROW ) checkProfileCallback(db, p); #endif if( rc==SQLITE_DONE ){ assert( p->rc==SQLITE_OK ); p->rc = doWalCallbacks(db); if( p->rc!=SQLITE_OK ){ rc = SQLITE_ERROR; } } db->errCode = rc; if( SQLITE_NOMEM==sqlite3ApiExit(p->db, p->rc) ){ p->rc = SQLITE_NOMEM_BKPT; } end_of_step: /* At this point local variable rc holds the value that should be ** returned if this statement was compiled using the legacy ** sqlite3_prepare() interface. According to the docs, this can only ** be one of the values in the first assert() below. Variable p->rc ** contains the value that would be returned if sqlite3_finalize() ** were called on statement p. */ assert( rc==SQLITE_ROW || rc==SQLITE_DONE || rc==SQLITE_ERROR || (rc&0xff)==SQLITE_BUSY || rc==SQLITE_MISUSE ); assert( (p->rc!=SQLITE_ROW && p->rc!=SQLITE_DONE) || p->rc==p->rcApp ); if( p->isPrepareV2 && rc!=SQLITE_ROW && rc!=SQLITE_DONE ){ /* If this statement was prepared using sqlite3_prepare_v2(), and an ** error has occurred, then return the error code in p->rc to the ** caller. Set the error code in the database handle to the same value. */ rc = sqlite3VdbeTransferError(p); } return (rc&db->errMask); } /* ** This is the top-level implementation of sqlite3_step(). Call ** sqlite3Step() to do most of the work. If a schema error occurs, ** call sqlite3Reprepare() and try again. */ SQLITE_API int sqlite3_step(sqlite3_stmt *pStmt){ int rc = SQLITE_OK; /* Result from sqlite3Step() */ int rc2 = SQLITE_OK; /* Result from sqlite3Reprepare() */ Vdbe *v = (Vdbe*)pStmt; /* the prepared statement */ int cnt = 0; /* Counter to prevent infinite loop of reprepares */ sqlite3 *db; /* The database connection */ if( vdbeSafetyNotNull(v) ){ return SQLITE_MISUSE_BKPT; } db = v->db; sqlite3_mutex_enter(db->mutex); v->doingRerun = 0; while( (rc = sqlite3Step(v))==SQLITE_SCHEMA && cnt++ < SQLITE_MAX_SCHEMA_RETRY ){ int savedPc = v->pc; rc2 = rc = sqlite3Reprepare(v); if( rc!=SQLITE_OK) break; sqlite3_reset(pStmt); if( savedPc>=0 ) v->doingRerun = 1; assert( v->expired==0 ); } if( rc2!=SQLITE_OK ){ /* This case occurs after failing to recompile an sql statement. ** The error message from the SQL compiler has already been loaded ** into the database handle. This block copies the error message ** from the database handle into the statement and sets the statement ** program counter to 0 to ensure that when the statement is ** finalized or reset the parser error message is available via ** sqlite3_errmsg() and sqlite3_errcode(). */ const char *zErr = (const char *)sqlite3_value_text(db->pErr); sqlite3DbFree(db, v->zErrMsg); if( !db->mallocFailed ){ v->zErrMsg = sqlite3DbStrDup(db, zErr); v->rc = rc2; } else { v->zErrMsg = 0; v->rc = rc = SQLITE_NOMEM_BKPT; } } rc = sqlite3ApiExit(db, rc); sqlite3_mutex_leave(db->mutex); return rc; } /* ** Extract the user data from a sqlite3_context structure and return a ** pointer to it. */ SQLITE_API void *sqlite3_user_data(sqlite3_context *p){ assert( p && p->pFunc ); return p->pFunc->pUserData; } /* ** Extract the user data from a sqlite3_context structure and return a ** pointer to it. ** ** IMPLEMENTATION-OF: R-46798-50301 The sqlite3_context_db_handle() interface ** returns a copy of the pointer to the database connection (the 1st ** parameter) of the sqlite3_create_function() and ** sqlite3_create_function16() routines that originally registered the ** application defined function. */ SQLITE_API sqlite3 *sqlite3_context_db_handle(sqlite3_context *p){ assert( p && p->pOut ); return p->pOut->db; } /* ** Return the current time for a statement. If the current time ** is requested more than once within the same run of a single prepared ** statement, the exact same time is returned for each invocation regardless ** of the amount of time that elapses between invocations. In other words, ** the time returned is always the time of the first call. */ SQLITE_PRIVATE sqlite3_int64 sqlite3StmtCurrentTime(sqlite3_context *p){ int rc; #ifndef SQLITE_ENABLE_STAT3_OR_STAT4 sqlite3_int64 *piTime = &p->pVdbe->iCurrentTime; assert( p->pVdbe!=0 ); #else sqlite3_int64 iTime = 0; sqlite3_int64 *piTime = p->pVdbe!=0 ? &p->pVdbe->iCurrentTime : &iTime; #endif if( *piTime==0 ){ rc = sqlite3OsCurrentTimeInt64(p->pOut->db->pVfs, piTime); if( rc ) *piTime = 0; } return *piTime; } /* ** The following is the implementation of an SQL function that always ** fails with an error message stating that the function is used in the ** wrong context. The sqlite3_overload_function() API might construct ** SQL function that use this routine so that the functions will exist ** for name resolution but are actually overloaded by the xFindFunction ** method of virtual tables. */ SQLITE_PRIVATE void sqlite3InvalidFunction( sqlite3_context *context, /* The function calling context */ int NotUsed, /* Number of arguments to the function */ sqlite3_value **NotUsed2 /* Value of each argument */ ){ const char *zName = context->pFunc->zName; char *zErr; UNUSED_PARAMETER2(NotUsed, NotUsed2); zErr = sqlite3_mprintf( "unable to use function %s in the requested context", zName); sqlite3_result_error(context, zErr, -1); sqlite3_free(zErr); } /* ** Create a new aggregate context for p and return a pointer to ** its pMem->z element. */ static SQLITE_NOINLINE void *createAggContext(sqlite3_context *p, int nByte){ Mem *pMem = p->pMem; assert( (pMem->flags & MEM_Agg)==0 ); if( nByte<=0 ){ sqlite3VdbeMemSetNull(pMem); pMem->z = 0; }else{ sqlite3VdbeMemClearAndResize(pMem, nByte); pMem->flags = MEM_Agg; pMem->u.pDef = p->pFunc; if( pMem->z ){ memset(pMem->z, 0, nByte); } } return (void*)pMem->z; } /* ** Allocate or return the aggregate context for a user function. A new ** context is allocated on the first call. Subsequent calls return the ** same context that was returned on prior calls. */ SQLITE_API void *sqlite3_aggregate_context(sqlite3_context *p, int nByte){ assert( p && p->pFunc && p->pFunc->xFinalize ); assert( sqlite3_mutex_held(p->pOut->db->mutex) ); testcase( nByte<0 ); if( (p->pMem->flags & MEM_Agg)==0 ){ return createAggContext(p, nByte); }else{ return (void*)p->pMem->z; } } /* ** Return the auxiliary data pointer, if any, for the iArg'th argument to ** the user-function defined by pCtx. */ SQLITE_API void *sqlite3_get_auxdata(sqlite3_context *pCtx, int iArg){ AuxData *pAuxData; assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) ); #if SQLITE_ENABLE_STAT3_OR_STAT4 if( pCtx->pVdbe==0 ) return 0; #else assert( pCtx->pVdbe!=0 ); #endif for(pAuxData=pCtx->pVdbe->pAuxData; pAuxData; pAuxData=pAuxData->pNext){ if( pAuxData->iOp==pCtx->iOp && pAuxData->iArg==iArg ) break; } return (pAuxData ? pAuxData->pAux : 0); } /* ** Set the auxiliary data pointer and delete function, for the iArg'th ** argument to the user-function defined by pCtx. Any previous value is ** deleted by calling the delete function specified when it was set. */ SQLITE_API void sqlite3_set_auxdata( sqlite3_context *pCtx, int iArg, void *pAux, void (*xDelete)(void*) ){ AuxData *pAuxData; Vdbe *pVdbe = pCtx->pVdbe; assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) ); if( iArg<0 ) goto failed; #ifdef SQLITE_ENABLE_STAT3_OR_STAT4 if( pVdbe==0 ) goto failed; #else assert( pVdbe!=0 ); #endif for(pAuxData=pVdbe->pAuxData; pAuxData; pAuxData=pAuxData->pNext){ if( pAuxData->iOp==pCtx->iOp && pAuxData->iArg==iArg ) break; } if( pAuxData==0 ){ pAuxData = sqlite3DbMallocZero(pVdbe->db, sizeof(AuxData)); if( !pAuxData ) goto failed; pAuxData->iOp = pCtx->iOp; pAuxData->iArg = iArg; pAuxData->pNext = pVdbe->pAuxData; pVdbe->pAuxData = pAuxData; if( pCtx->fErrorOrAux==0 ){ pCtx->isError = 0; pCtx->fErrorOrAux = 1; } }else if( pAuxData->xDelete ){ pAuxData->xDelete(pAuxData->pAux); } pAuxData->pAux = pAux; pAuxData->xDelete = xDelete; return; failed: if( xDelete ){ xDelete(pAux); } } #ifndef SQLITE_OMIT_DEPRECATED /* ** Return the number of times the Step function of an aggregate has been ** called. ** ** This function is deprecated. Do not use it for new code. It is ** provide only to avoid breaking legacy code. New aggregate function ** implementations should keep their own counts within their aggregate ** context. */ SQLITE_API int sqlite3_aggregate_count(sqlite3_context *p){ assert( p && p->pMem && p->pFunc && p->pFunc->xFinalize ); return p->pMem->n; } #endif /* ** Return the number of columns in the result set for the statement pStmt. */ SQLITE_API int sqlite3_column_count(sqlite3_stmt *pStmt){ Vdbe *pVm = (Vdbe *)pStmt; return pVm ? pVm->nResColumn : 0; } /* ** Return the number of values available from the current row of the ** currently executing statement pStmt. */ SQLITE_API int sqlite3_data_count(sqlite3_stmt *pStmt){ Vdbe *pVm = (Vdbe *)pStmt; if( pVm==0 || pVm->pResultSet==0 ) return 0; return pVm->nResColumn; } /* ** Return a pointer to static memory containing an SQL NULL value. */ static const Mem *columnNullValue(void){ /* Even though the Mem structure contains an element ** of type i64, on certain architectures (x86) with certain compiler ** switches (-Os), gcc may align this Mem object on a 4-byte boundary ** instead of an 8-byte one. This all works fine, except that when ** running with SQLITE_DEBUG defined the SQLite code sometimes assert()s ** that a Mem structure is located on an 8-byte boundary. To prevent ** these assert()s from failing, when building with SQLITE_DEBUG defined ** using gcc, we force nullMem to be 8-byte aligned using the magical ** __attribute__((aligned(8))) macro. */ static const Mem nullMem #if defined(SQLITE_DEBUG) && defined(__GNUC__) __attribute__((aligned(8))) #endif = { /* .u = */ {0}, /* .flags = */ (u16)MEM_Null, /* .enc = */ (u8)0, /* .eSubtype = */ (u8)0, /* .n = */ (int)0, /* .z = */ (char*)0, /* .zMalloc = */ (char*)0, /* .szMalloc = */ (int)0, /* .uTemp = */ (u32)0, /* .db = */ (sqlite3*)0, /* .xDel = */ (void(*)(void*))0, #ifdef SQLITE_DEBUG /* .pScopyFrom = */ (Mem*)0, /* .pFiller = */ (void*)0, #endif }; return &nullMem; } /* ** Check to see if column iCol of the given statement is valid. If ** it is, return a pointer to the Mem for the value of that column. ** If iCol is not valid, return a pointer to a Mem which has a value ** of NULL. */ static Mem *columnMem(sqlite3_stmt *pStmt, int i){ Vdbe *pVm; Mem *pOut; pVm = (Vdbe *)pStmt; if( pVm==0 ) return (Mem*)columnNullValue(); assert( pVm->db ); sqlite3_mutex_enter(pVm->db->mutex); if( pVm->pResultSet!=0 && inResColumn && i>=0 ){ pOut = &pVm->pResultSet[i]; }else{ sqlite3Error(pVm->db, SQLITE_RANGE); pOut = (Mem*)columnNullValue(); } return pOut; } /* ** This function is called after invoking an sqlite3_value_XXX function on a ** column value (i.e. a value returned by evaluating an SQL expression in the ** select list of a SELECT statement) that may cause a malloc() failure. If ** malloc() has failed, the threads mallocFailed flag is cleared and the result ** code of statement pStmt set to SQLITE_NOMEM. ** ** Specifically, this is called from within: ** ** sqlite3_column_int() ** sqlite3_column_int64() ** sqlite3_column_text() ** sqlite3_column_text16() ** sqlite3_column_real() ** sqlite3_column_bytes() ** sqlite3_column_bytes16() ** sqiite3_column_blob() */ static void columnMallocFailure(sqlite3_stmt *pStmt) { /* If malloc() failed during an encoding conversion within an ** sqlite3_column_XXX API, then set the return code of the statement to ** SQLITE_NOMEM. The next call to _step() (if any) will return SQLITE_ERROR ** and _finalize() will return NOMEM. */ Vdbe *p = (Vdbe *)pStmt; if( p ){ assert( p->db!=0 ); assert( sqlite3_mutex_held(p->db->mutex) ); p->rc = sqlite3ApiExit(p->db, p->rc); sqlite3_mutex_leave(p->db->mutex); } } /**************************** sqlite3_column_ ******************************* ** The following routines are used to access elements of the current row ** in the result set. */ SQLITE_API const void *sqlite3_column_blob(sqlite3_stmt *pStmt, int i){ const void *val; val = sqlite3_value_blob( columnMem(pStmt,i) ); /* Even though there is no encoding conversion, value_blob() might ** need to call malloc() to expand the result of a zeroblob() ** expression. */ columnMallocFailure(pStmt); return val; } SQLITE_API int sqlite3_column_bytes(sqlite3_stmt *pStmt, int i){ int val = sqlite3_value_bytes( columnMem(pStmt,i) ); columnMallocFailure(pStmt); return val; } SQLITE_API int sqlite3_column_bytes16(sqlite3_stmt *pStmt, int i){ int val = sqlite3_value_bytes16( columnMem(pStmt,i) ); columnMallocFailure(pStmt); return val; } SQLITE_API double sqlite3_column_double(sqlite3_stmt *pStmt, int i){ double val = sqlite3_value_double( columnMem(pStmt,i) ); columnMallocFailure(pStmt); return val; } SQLITE_API int sqlite3_column_int(sqlite3_stmt *pStmt, int i){ int val = sqlite3_value_int( columnMem(pStmt,i) ); columnMallocFailure(pStmt); return val; } SQLITE_API sqlite_int64 sqlite3_column_int64(sqlite3_stmt *pStmt, int i){ sqlite_int64 val = sqlite3_value_int64( columnMem(pStmt,i) ); columnMallocFailure(pStmt); return val; } SQLITE_API const unsigned char *sqlite3_column_text(sqlite3_stmt *pStmt, int i){ const unsigned char *val = sqlite3_value_text( columnMem(pStmt,i) ); columnMallocFailure(pStmt); return val; } SQLITE_API sqlite3_value *sqlite3_column_value(sqlite3_stmt *pStmt, int i){ Mem *pOut = columnMem(pStmt, i); if( pOut->flags&MEM_Static ){ pOut->flags &= ~MEM_Static; pOut->flags |= MEM_Ephem; } columnMallocFailure(pStmt); return (sqlite3_value *)pOut; } #ifndef SQLITE_OMIT_UTF16 SQLITE_API const void *sqlite3_column_text16(sqlite3_stmt *pStmt, int i){ const void *val = sqlite3_value_text16( columnMem(pStmt,i) ); columnMallocFailure(pStmt); return val; } #endif /* SQLITE_OMIT_UTF16 */ SQLITE_API int sqlite3_column_type(sqlite3_stmt *pStmt, int i){ int iType = sqlite3_value_type( columnMem(pStmt,i) ); columnMallocFailure(pStmt); return iType; } /* ** Convert the N-th element of pStmt->pColName[] into a string using ** xFunc() then return that string. If N is out of range, return 0. ** ** There are up to 5 names for each column. useType determines which ** name is returned. Here are the names: ** ** 0 The column name as it should be displayed for output ** 1 The datatype name for the column ** 2 The name of the database that the column derives from ** 3 The name of the table that the column derives from ** 4 The name of the table column that the result column derives from ** ** If the result is not a simple column reference (if it is an expression ** or a constant) then useTypes 2, 3, and 4 return NULL. */ static const void *columnName( sqlite3_stmt *pStmt, int N, const void *(*xFunc)(Mem*), int useType ){ const void *ret; Vdbe *p; int n; sqlite3 *db; #ifdef SQLITE_ENABLE_API_ARMOR if( pStmt==0 ){ (void)SQLITE_MISUSE_BKPT; return 0; } #endif ret = 0; p = (Vdbe *)pStmt; db = p->db; assert( db!=0 ); n = sqlite3_column_count(pStmt); if( N=0 ){ N += useType*n; sqlite3_mutex_enter(db->mutex); assert( db->mallocFailed==0 ); ret = xFunc(&p->aColName[N]); /* A malloc may have failed inside of the xFunc() call. If this ** is the case, clear the mallocFailed flag and return NULL. */ if( db->mallocFailed ){ sqlite3OomClear(db); ret = 0; } sqlite3_mutex_leave(db->mutex); } return ret; } /* ** Return the name of the Nth column of the result set returned by SQL ** statement pStmt. */ SQLITE_API const char *sqlite3_column_name(sqlite3_stmt *pStmt, int N){ return columnName( pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_NAME); } #ifndef SQLITE_OMIT_UTF16 SQLITE_API const void *sqlite3_column_name16(sqlite3_stmt *pStmt, int N){ return columnName( pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_NAME); } #endif /* ** Constraint: If you have ENABLE_COLUMN_METADATA then you must ** not define OMIT_DECLTYPE. */ #if defined(SQLITE_OMIT_DECLTYPE) && defined(SQLITE_ENABLE_COLUMN_METADATA) # error "Must not define both SQLITE_OMIT_DECLTYPE \ and SQLITE_ENABLE_COLUMN_METADATA" #endif #ifndef SQLITE_OMIT_DECLTYPE /* ** Return the column declaration type (if applicable) of the 'i'th column ** of the result set of SQL statement pStmt. */ SQLITE_API const char *sqlite3_column_decltype(sqlite3_stmt *pStmt, int N){ return columnName( pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_DECLTYPE); } #ifndef SQLITE_OMIT_UTF16 SQLITE_API const void *sqlite3_column_decltype16(sqlite3_stmt *pStmt, int N){ return columnName( pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_DECLTYPE); } #endif /* SQLITE_OMIT_UTF16 */ #endif /* SQLITE_OMIT_DECLTYPE */ #ifdef SQLITE_ENABLE_COLUMN_METADATA /* ** Return the name of the database from which a result column derives. ** NULL is returned if the result column is an expression or constant or ** anything else which is not an unambiguous reference to a database column. */ SQLITE_API const char *sqlite3_column_database_name(sqlite3_stmt *pStmt, int N){ return columnName( pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_DATABASE); } #ifndef SQLITE_OMIT_UTF16 SQLITE_API const void *sqlite3_column_database_name16(sqlite3_stmt *pStmt, int N){ return columnName( pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_DATABASE); } #endif /* SQLITE_OMIT_UTF16 */ /* ** Return the name of the table from which a result column derives. ** NULL is returned if the result column is an expression or constant or ** anything else which is not an unambiguous reference to a database column. */ SQLITE_API const char *sqlite3_column_table_name(sqlite3_stmt *pStmt, int N){ return columnName( pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_TABLE); } #ifndef SQLITE_OMIT_UTF16 SQLITE_API const void *sqlite3_column_table_name16(sqlite3_stmt *pStmt, int N){ return columnName( pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_TABLE); } #endif /* SQLITE_OMIT_UTF16 */ /* ** Return the name of the table column from which a result column derives. ** NULL is returned if the result column is an expression or constant or ** anything else which is not an unambiguous reference to a database column. */ SQLITE_API const char *sqlite3_column_origin_name(sqlite3_stmt *pStmt, int N){ return columnName( pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_COLUMN); } #ifndef SQLITE_OMIT_UTF16 SQLITE_API const void *sqlite3_column_origin_name16(sqlite3_stmt *pStmt, int N){ return columnName( pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_COLUMN); } #endif /* SQLITE_OMIT_UTF16 */ #endif /* SQLITE_ENABLE_COLUMN_METADATA */ /******************************* sqlite3_bind_ *************************** ** ** Routines used to attach values to wildcards in a compiled SQL statement. */ /* ** Unbind the value bound to variable i in virtual machine p. This is the ** the same as binding a NULL value to the column. If the "i" parameter is ** out of range, then SQLITE_RANGE is returned. Othewise SQLITE_OK. ** ** A successful evaluation of this routine acquires the mutex on p. ** the mutex is released if any kind of error occurs. ** ** The error code stored in database p->db is overwritten with the return ** value in any case. */ static int vdbeUnbind(Vdbe *p, int i){ Mem *pVar; if( vdbeSafetyNotNull(p) ){ return SQLITE_MISUSE_BKPT; } sqlite3_mutex_enter(p->db->mutex); if( p->magic!=VDBE_MAGIC_RUN || p->pc>=0 ){ sqlite3Error(p->db, SQLITE_MISUSE); sqlite3_mutex_leave(p->db->mutex); sqlite3_log(SQLITE_MISUSE, "bind on a busy prepared statement: [%s]", p->zSql); return SQLITE_MISUSE_BKPT; } if( i<1 || i>p->nVar ){ sqlite3Error(p->db, SQLITE_RANGE); sqlite3_mutex_leave(p->db->mutex); return SQLITE_RANGE; } i--; pVar = &p->aVar[i]; sqlite3VdbeMemRelease(pVar); pVar->flags = MEM_Null; sqlite3Error(p->db, SQLITE_OK); /* If the bit corresponding to this variable in Vdbe.expmask is set, then ** binding a new value to this variable invalidates the current query plan. ** ** IMPLEMENTATION-OF: R-48440-37595 If the specific value bound to host ** parameter in the WHERE clause might influence the choice of query plan ** for a statement, then the statement will be automatically recompiled, ** as if there had been a schema change, on the first sqlite3_step() call ** following any change to the bindings of that parameter. */ if( p->isPrepareV2 && ((i<32 && p->expmask & ((u32)1 << i)) || p->expmask==0xffffffff) ){ p->expired = 1; } return SQLITE_OK; } /* ** Bind a text or BLOB value. */ static int bindText( sqlite3_stmt *pStmt, /* The statement to bind against */ int i, /* Index of the parameter to bind */ const void *zData, /* Pointer to the data to be bound */ int nData, /* Number of bytes of data to be bound */ void (*xDel)(void*), /* Destructor for the data */ u8 encoding /* Encoding for the data */ ){ Vdbe *p = (Vdbe *)pStmt; Mem *pVar; int rc; rc = vdbeUnbind(p, i); if( rc==SQLITE_OK ){ if( zData!=0 ){ pVar = &p->aVar[i-1]; rc = sqlite3VdbeMemSetStr(pVar, zData, nData, encoding, xDel); if( rc==SQLITE_OK && encoding!=0 ){ rc = sqlite3VdbeChangeEncoding(pVar, ENC(p->db)); } sqlite3Error(p->db, rc); rc = sqlite3ApiExit(p->db, rc); } sqlite3_mutex_leave(p->db->mutex); }else if( xDel!=SQLITE_STATIC && xDel!=SQLITE_TRANSIENT ){ xDel((void*)zData); } return rc; } /* ** Bind a blob value to an SQL statement variable. */ SQLITE_API int sqlite3_bind_blob( sqlite3_stmt *pStmt, int i, const void *zData, int nData, void (*xDel)(void*) ){ #ifdef SQLITE_ENABLE_API_ARMOR if( nData<0 ) return SQLITE_MISUSE_BKPT; #endif return bindText(pStmt, i, zData, nData, xDel, 0); } SQLITE_API int sqlite3_bind_blob64( sqlite3_stmt *pStmt, int i, const void *zData, sqlite3_uint64 nData, void (*xDel)(void*) ){ assert( xDel!=SQLITE_DYNAMIC ); if( nData>0x7fffffff ){ return invokeValueDestructor(zData, xDel, 0); }else{ return bindText(pStmt, i, zData, (int)nData, xDel, 0); } } SQLITE_API int sqlite3_bind_double(sqlite3_stmt *pStmt, int i, double rValue){ int rc; Vdbe *p = (Vdbe *)pStmt; rc = vdbeUnbind(p, i); if( rc==SQLITE_OK ){ sqlite3VdbeMemSetDouble(&p->aVar[i-1], rValue); sqlite3_mutex_leave(p->db->mutex); } return rc; } SQLITE_API int sqlite3_bind_int(sqlite3_stmt *p, int i, int iValue){ return sqlite3_bind_int64(p, i, (i64)iValue); } SQLITE_API int sqlite3_bind_int64(sqlite3_stmt *pStmt, int i, sqlite_int64 iValue){ int rc; Vdbe *p = (Vdbe *)pStmt; rc = vdbeUnbind(p, i); if( rc==SQLITE_OK ){ sqlite3VdbeMemSetInt64(&p->aVar[i-1], iValue); sqlite3_mutex_leave(p->db->mutex); } return rc; } SQLITE_API int sqlite3_bind_null(sqlite3_stmt *pStmt, int i){ int rc; Vdbe *p = (Vdbe*)pStmt; rc = vdbeUnbind(p, i); if( rc==SQLITE_OK ){ sqlite3_mutex_leave(p->db->mutex); } return rc; } SQLITE_API int sqlite3_bind_text( sqlite3_stmt *pStmt, int i, const char *zData, int nData, void (*xDel)(void*) ){ return bindText(pStmt, i, zData, nData, xDel, SQLITE_UTF8); } SQLITE_API int sqlite3_bind_text64( sqlite3_stmt *pStmt, int i, const char *zData, sqlite3_uint64 nData, void (*xDel)(void*), unsigned char enc ){ assert( xDel!=SQLITE_DYNAMIC ); if( nData>0x7fffffff ){ return invokeValueDestructor(zData, xDel, 0); }else{ if( enc==SQLITE_UTF16 ) enc = SQLITE_UTF16NATIVE; return bindText(pStmt, i, zData, (int)nData, xDel, enc); } } #ifndef SQLITE_OMIT_UTF16 SQLITE_API int sqlite3_bind_text16( sqlite3_stmt *pStmt, int i, const void *zData, int nData, void (*xDel)(void*) ){ return bindText(pStmt, i, zData, nData, xDel, SQLITE_UTF16NATIVE); } #endif /* SQLITE_OMIT_UTF16 */ SQLITE_API int sqlite3_bind_value(sqlite3_stmt *pStmt, int i, const sqlite3_value *pValue){ int rc; switch( sqlite3_value_type((sqlite3_value*)pValue) ){ case SQLITE_INTEGER: { rc = sqlite3_bind_int64(pStmt, i, pValue->u.i); break; } case SQLITE_FLOAT: { rc = sqlite3_bind_double(pStmt, i, pValue->u.r); break; } case SQLITE_BLOB: { if( pValue->flags & MEM_Zero ){ rc = sqlite3_bind_zeroblob(pStmt, i, pValue->u.nZero); }else{ rc = sqlite3_bind_blob(pStmt, i, pValue->z, pValue->n,SQLITE_TRANSIENT); } break; } case SQLITE_TEXT: { rc = bindText(pStmt,i, pValue->z, pValue->n, SQLITE_TRANSIENT, pValue->enc); break; } default: { rc = sqlite3_bind_null(pStmt, i); break; } } return rc; } SQLITE_API int sqlite3_bind_zeroblob(sqlite3_stmt *pStmt, int i, int n){ int rc; Vdbe *p = (Vdbe *)pStmt; rc = vdbeUnbind(p, i); if( rc==SQLITE_OK ){ sqlite3VdbeMemSetZeroBlob(&p->aVar[i-1], n); sqlite3_mutex_leave(p->db->mutex); } return rc; } SQLITE_API int sqlite3_bind_zeroblob64(sqlite3_stmt *pStmt, int i, sqlite3_uint64 n){ int rc; Vdbe *p = (Vdbe *)pStmt; sqlite3_mutex_enter(p->db->mutex); if( n>(u64)p->db->aLimit[SQLITE_LIMIT_LENGTH] ){ rc = SQLITE_TOOBIG; }else{ assert( (n & 0x7FFFFFFF)==n ); rc = sqlite3_bind_zeroblob(pStmt, i, n); } rc = sqlite3ApiExit(p->db, rc); sqlite3_mutex_leave(p->db->mutex); return rc; } /* ** Return the number of wildcards that can be potentially bound to. ** This routine is added to support DBD::SQLite. */ SQLITE_API int sqlite3_bind_parameter_count(sqlite3_stmt *pStmt){ Vdbe *p = (Vdbe*)pStmt; return p ? p->nVar : 0; } /* ** Return the name of a wildcard parameter. Return NULL if the index ** is out of range or if the wildcard is unnamed. ** ** The result is always UTF-8. */ SQLITE_API const char *sqlite3_bind_parameter_name(sqlite3_stmt *pStmt, int i){ Vdbe *p = (Vdbe*)pStmt; if( p==0 || i<1 || i>p->nzVar ){ return 0; } return p->azVar[i-1]; } /* ** Given a wildcard parameter name, return the index of the variable ** with that name. If there is no variable with the given name, ** return 0. */ SQLITE_PRIVATE int sqlite3VdbeParameterIndex(Vdbe *p, const char *zName, int nName){ int i; if( p==0 ){ return 0; } if( zName ){ for(i=0; inzVar; i++){ const char *z = p->azVar[i]; if( z && strncmp(z,zName,nName)==0 && z[nName]==0 ){ return i+1; } } } return 0; } SQLITE_API int sqlite3_bind_parameter_index(sqlite3_stmt *pStmt, const char *zName){ return sqlite3VdbeParameterIndex((Vdbe*)pStmt, zName, sqlite3Strlen30(zName)); } /* ** Transfer all bindings from the first statement over to the second. */ SQLITE_PRIVATE int sqlite3TransferBindings(sqlite3_stmt *pFromStmt, sqlite3_stmt *pToStmt){ Vdbe *pFrom = (Vdbe*)pFromStmt; Vdbe *pTo = (Vdbe*)pToStmt; int i; assert( pTo->db==pFrom->db ); assert( pTo->nVar==pFrom->nVar ); sqlite3_mutex_enter(pTo->db->mutex); for(i=0; inVar; i++){ sqlite3VdbeMemMove(&pTo->aVar[i], &pFrom->aVar[i]); } sqlite3_mutex_leave(pTo->db->mutex); return SQLITE_OK; } #ifndef SQLITE_OMIT_DEPRECATED /* ** Deprecated external interface. Internal/core SQLite code ** should call sqlite3TransferBindings. ** ** It is misuse to call this routine with statements from different ** database connections. But as this is a deprecated interface, we ** will not bother to check for that condition. ** ** If the two statements contain a different number of bindings, then ** an SQLITE_ERROR is returned. Nothing else can go wrong, so otherwise ** SQLITE_OK is returned. */ SQLITE_API int sqlite3_transfer_bindings(sqlite3_stmt *pFromStmt, sqlite3_stmt *pToStmt){ Vdbe *pFrom = (Vdbe*)pFromStmt; Vdbe *pTo = (Vdbe*)pToStmt; if( pFrom->nVar!=pTo->nVar ){ return SQLITE_ERROR; } if( pTo->isPrepareV2 && pTo->expmask ){ pTo->expired = 1; } if( pFrom->isPrepareV2 && pFrom->expmask ){ pFrom->expired = 1; } return sqlite3TransferBindings(pFromStmt, pToStmt); } #endif /* ** Return the sqlite3* database handle to which the prepared statement given ** in the argument belongs. This is the same database handle that was ** the first argument to the sqlite3_prepare() that was used to create ** the statement in the first place. */ SQLITE_API sqlite3 *sqlite3_db_handle(sqlite3_stmt *pStmt){ return pStmt ? ((Vdbe*)pStmt)->db : 0; } /* ** Return true if the prepared statement is guaranteed to not modify the ** database. */ SQLITE_API int sqlite3_stmt_readonly(sqlite3_stmt *pStmt){ return pStmt ? ((Vdbe*)pStmt)->readOnly : 1; } /* ** Return true if the prepared statement is in need of being reset. */ SQLITE_API int sqlite3_stmt_busy(sqlite3_stmt *pStmt){ Vdbe *v = (Vdbe*)pStmt; return v!=0 && v->magic==VDBE_MAGIC_RUN && v->pc>=0; } /* ** Return a pointer to the next prepared statement after pStmt associated ** with database connection pDb. If pStmt is NULL, return the first ** prepared statement for the database connection. Return NULL if there ** are no more. */ SQLITE_API sqlite3_stmt *sqlite3_next_stmt(sqlite3 *pDb, sqlite3_stmt *pStmt){ sqlite3_stmt *pNext; #ifdef SQLITE_ENABLE_API_ARMOR if( !sqlite3SafetyCheckOk(pDb) ){ (void)SQLITE_MISUSE_BKPT; return 0; } #endif sqlite3_mutex_enter(pDb->mutex); if( pStmt==0 ){ pNext = (sqlite3_stmt*)pDb->pVdbe; }else{ pNext = (sqlite3_stmt*)((Vdbe*)pStmt)->pNext; } sqlite3_mutex_leave(pDb->mutex); return pNext; } /* ** Return the value of a status counter for a prepared statement */ SQLITE_API int sqlite3_stmt_status(sqlite3_stmt *pStmt, int op, int resetFlag){ Vdbe *pVdbe = (Vdbe*)pStmt; u32 v; #ifdef SQLITE_ENABLE_API_ARMOR if( !pStmt ){ (void)SQLITE_MISUSE_BKPT; return 0; } #endif v = pVdbe->aCounter[op]; if( resetFlag ) pVdbe->aCounter[op] = 0; return (int)v; } /* ** Return the SQL associated with a prepared statement */ SQLITE_API const char *sqlite3_sql(sqlite3_stmt *pStmt){ Vdbe *p = (Vdbe *)pStmt; return p ? p->zSql : 0; } /* ** Return the SQL associated with a prepared statement with ** bound parameters expanded. Space to hold the returned string is ** obtained from sqlite3_malloc(). The caller is responsible for ** freeing the returned string by passing it to sqlite3_free(). ** ** The SQLITE_TRACE_SIZE_LIMIT puts an upper bound on the size of ** expanded bound parameters. */ SQLITE_API char *sqlite3_expanded_sql(sqlite3_stmt *pStmt){ #ifdef SQLITE_OMIT_TRACE return 0; #else char *z = 0; const char *zSql = sqlite3_sql(pStmt); if( zSql ){ Vdbe *p = (Vdbe *)pStmt; sqlite3_mutex_enter(p->db->mutex); z = sqlite3VdbeExpandSql(p, zSql); sqlite3_mutex_leave(p->db->mutex); } return z; #endif } #ifdef SQLITE_ENABLE_PREUPDATE_HOOK /* ** Allocate and populate an UnpackedRecord structure based on the serialized ** record in nKey/pKey. Return a pointer to the new UnpackedRecord structure ** if successful, or a NULL pointer if an OOM error is encountered. */ static UnpackedRecord *vdbeUnpackRecord( KeyInfo *pKeyInfo, int nKey, const void *pKey ){ char *dummy; /* Dummy argument for AllocUnpackedRecord() */ UnpackedRecord *pRet; /* Return value */ pRet = sqlite3VdbeAllocUnpackedRecord(pKeyInfo, 0, 0, &dummy); if( pRet ){ memset(pRet->aMem, 0, sizeof(Mem)*(pKeyInfo->nField+1)); sqlite3VdbeRecordUnpack(pKeyInfo, nKey, pKey, pRet); } return pRet; } /* ** This function is called from within a pre-update callback to retrieve ** a field of the row currently being updated or deleted. */ SQLITE_API int sqlite3_preupdate_old(sqlite3 *db, int iIdx, sqlite3_value **ppValue){ PreUpdate *p = db->pPreUpdate; int rc = SQLITE_OK; /* Test that this call is being made from within an SQLITE_DELETE or ** SQLITE_UPDATE pre-update callback, and that iIdx is within range. */ if( !p || p->op==SQLITE_INSERT ){ rc = SQLITE_MISUSE_BKPT; goto preupdate_old_out; } if( iIdx>=p->pCsr->nField || iIdx<0 ){ rc = SQLITE_RANGE; goto preupdate_old_out; } /* If the old.* record has not yet been loaded into memory, do so now. */ if( p->pUnpacked==0 ){ u32 nRec; u8 *aRec; nRec = sqlite3BtreePayloadSize(p->pCsr->uc.pCursor); aRec = sqlite3DbMallocRaw(db, nRec); if( !aRec ) goto preupdate_old_out; rc = sqlite3BtreeData(p->pCsr->uc.pCursor, 0, nRec, aRec); if( rc==SQLITE_OK ){ p->pUnpacked = vdbeUnpackRecord(&p->keyinfo, nRec, aRec); if( !p->pUnpacked ) rc = SQLITE_NOMEM; } if( rc!=SQLITE_OK ){ sqlite3DbFree(db, aRec); goto preupdate_old_out; } p->aRecord = aRec; } if( iIdx>=p->pUnpacked->nField ){ *ppValue = (sqlite3_value *)columnNullValue(); }else{ Mem *pMem = *ppValue = &p->pUnpacked->aMem[iIdx]; *ppValue = &p->pUnpacked->aMem[iIdx]; if( iIdx==p->pTab->iPKey ){ sqlite3VdbeMemSetInt64(pMem, p->iKey1); }else if( p->pTab->aCol[iIdx].affinity==SQLITE_AFF_REAL ){ if( pMem->flags & MEM_Int ){ sqlite3VdbeMemRealify(pMem); } } } preupdate_old_out: sqlite3Error(db, rc); return sqlite3ApiExit(db, rc); } #endif /* SQLITE_ENABLE_PREUPDATE_HOOK */ #ifdef SQLITE_ENABLE_PREUPDATE_HOOK /* ** This function is called from within a pre-update callback to retrieve ** the number of columns in the row being updated, deleted or inserted. */ SQLITE_API int sqlite3_preupdate_count(sqlite3 *db){ PreUpdate *p = db->pPreUpdate; return (p ? p->keyinfo.nField : 0); } #endif /* SQLITE_ENABLE_PREUPDATE_HOOK */ #ifdef SQLITE_ENABLE_PREUPDATE_HOOK /* ** This function is designed to be called from within a pre-update callback ** only. It returns zero if the change that caused the callback was made ** immediately by a user SQL statement. Or, if the change was made by a ** trigger program, it returns the number of trigger programs currently ** on the stack (1 for a top-level trigger, 2 for a trigger fired by a ** top-level trigger etc.). ** ** For the purposes of the previous paragraph, a foreign key CASCADE, SET NULL ** or SET DEFAULT action is considered a trigger. */ SQLITE_API int sqlite3_preupdate_depth(sqlite3 *db){ PreUpdate *p = db->pPreUpdate; return (p ? p->v->nFrame : 0); } #endif /* SQLITE_ENABLE_PREUPDATE_HOOK */ #ifdef SQLITE_ENABLE_PREUPDATE_HOOK /* ** This function is called from within a pre-update callback to retrieve ** a field of the row currently being updated or inserted. */ SQLITE_API int sqlite3_preupdate_new(sqlite3 *db, int iIdx, sqlite3_value **ppValue){ PreUpdate *p = db->pPreUpdate; int rc = SQLITE_OK; Mem *pMem; if( !p || p->op==SQLITE_DELETE ){ rc = SQLITE_MISUSE_BKPT; goto preupdate_new_out; } if( iIdx>=p->pCsr->nField || iIdx<0 ){ rc = SQLITE_RANGE; goto preupdate_new_out; } if( p->op==SQLITE_INSERT ){ /* For an INSERT, memory cell p->iNewReg contains the serialized record ** that is being inserted. Deserialize it. */ UnpackedRecord *pUnpack = p->pNewUnpacked; if( !pUnpack ){ Mem *pData = &p->v->aMem[p->iNewReg]; rc = ExpandBlob(pData); if( rc!=SQLITE_OK ) goto preupdate_new_out; pUnpack = vdbeUnpackRecord(&p->keyinfo, pData->n, pData->z); if( !pUnpack ){ rc = SQLITE_NOMEM; goto preupdate_new_out; } p->pNewUnpacked = pUnpack; } if( iIdx>=pUnpack->nField ){ pMem = (sqlite3_value *)columnNullValue(); }else{ pMem = &pUnpack->aMem[iIdx]; if( iIdx==p->pTab->iPKey ){ sqlite3VdbeMemSetInt64(pMem, p->iKey2); } } }else{ /* For an UPDATE, memory cell (p->iNewReg+1+iIdx) contains the required ** value. Make a copy of the cell contents and return a pointer to it. ** It is not safe to return a pointer to the memory cell itself as the ** caller may modify the value text encoding. */ assert( p->op==SQLITE_UPDATE ); if( !p->aNew ){ p->aNew = (Mem *)sqlite3DbMallocZero(db, sizeof(Mem) * p->pCsr->nField); if( !p->aNew ){ rc = SQLITE_NOMEM; goto preupdate_new_out; } } assert( iIdx>=0 && iIdxpCsr->nField ); pMem = &p->aNew[iIdx]; if( pMem->flags==0 ){ if( iIdx==p->pTab->iPKey ){ sqlite3VdbeMemSetInt64(pMem, p->iKey2); }else{ rc = sqlite3VdbeMemCopy(pMem, &p->v->aMem[p->iNewReg+1+iIdx]); if( rc!=SQLITE_OK ) goto preupdate_new_out; } } } *ppValue = pMem; preupdate_new_out: sqlite3Error(db, rc); return sqlite3ApiExit(db, rc); } #endif /* SQLITE_ENABLE_PREUPDATE_HOOK */ #ifdef SQLITE_ENABLE_STMT_SCANSTATUS /* ** Return status data for a single loop within query pStmt. */ SQLITE_API int sqlite3_stmt_scanstatus( sqlite3_stmt *pStmt, /* Prepared statement being queried */ int idx, /* Index of loop to report on */ int iScanStatusOp, /* Which metric to return */ void *pOut /* OUT: Write the answer here */ ){ Vdbe *p = (Vdbe*)pStmt; ScanStatus *pScan; if( idx<0 || idx>=p->nScan ) return 1; pScan = &p->aScan[idx]; switch( iScanStatusOp ){ case SQLITE_SCANSTAT_NLOOP: { *(sqlite3_int64*)pOut = p->anExec[pScan->addrLoop]; break; } case SQLITE_SCANSTAT_NVISIT: { *(sqlite3_int64*)pOut = p->anExec[pScan->addrVisit]; break; } case SQLITE_SCANSTAT_EST: { double r = 1.0; LogEst x = pScan->nEst; while( x<100 ){ x += 10; r *= 0.5; } *(double*)pOut = r*sqlite3LogEstToInt(x); break; } case SQLITE_SCANSTAT_NAME: { *(const char**)pOut = pScan->zName; break; } case SQLITE_SCANSTAT_EXPLAIN: { if( pScan->addrExplain ){ *(const char**)pOut = p->aOp[ pScan->addrExplain ].p4.z; }else{ *(const char**)pOut = 0; } break; } case SQLITE_SCANSTAT_SELECTID: { if( pScan->addrExplain ){ *(int*)pOut = p->aOp[ pScan->addrExplain ].p1; }else{ *(int*)pOut = -1; } break; } default: { return 1; } } return 0; } /* ** Zero all counters associated with the sqlite3_stmt_scanstatus() data. */ SQLITE_API void sqlite3_stmt_scanstatus_reset(sqlite3_stmt *pStmt){ Vdbe *p = (Vdbe*)pStmt; memset(p->anExec, 0, p->nOp * sizeof(i64)); } #endif /* SQLITE_ENABLE_STMT_SCANSTATUS */ /************** End of vdbeapi.c *********************************************/ /************** Begin file vdbetrace.c ***************************************/ /* ** 2009 November 25 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ************************************************************************* ** ** This file contains code used to insert the values of host parameters ** (aka "wildcards") into the SQL text output by sqlite3_trace(). ** ** The Vdbe parse-tree explainer is also found here. */ /* #include "sqliteInt.h" */ /* #include "vdbeInt.h" */ #ifndef SQLITE_OMIT_TRACE /* ** zSql is a zero-terminated string of UTF-8 SQL text. Return the number of ** bytes in this text up to but excluding the first character in ** a host parameter. If the text contains no host parameters, return ** the total number of bytes in the text. */ static int findNextHostParameter(const char *zSql, int *pnToken){ int tokenType; int nTotal = 0; int n; *pnToken = 0; while( zSql[0] ){ n = sqlite3GetToken((u8*)zSql, &tokenType); assert( n>0 && tokenType!=TK_ILLEGAL ); if( tokenType==TK_VARIABLE ){ *pnToken = n; break; } nTotal += n; zSql += n; } return nTotal; } /* ** This function returns a pointer to a nul-terminated string in memory ** obtained from sqlite3DbMalloc(). If sqlite3.nVdbeExec is 1, then the ** string contains a copy of zRawSql but with host parameters expanded to ** their current bindings. Or, if sqlite3.nVdbeExec is greater than 1, ** then the returned string holds a copy of zRawSql with "-- " prepended ** to each line of text. ** ** If the SQLITE_TRACE_SIZE_LIMIT macro is defined to an integer, then ** then long strings and blobs are truncated to that many bytes. This ** can be used to prevent unreasonably large trace strings when dealing ** with large (multi-megabyte) strings and blobs. ** ** The calling function is responsible for making sure the memory returned ** is eventually freed. ** ** ALGORITHM: Scan the input string looking for host parameters in any of ** these forms: ?, ?N, $A, @A, :A. Take care to avoid text within ** string literals, quoted identifier names, and comments. For text forms, ** the host parameter index is found by scanning the prepared ** statement for the corresponding OP_Variable opcode. Once the host ** parameter index is known, locate the value in p->aVar[]. Then render ** the value as a literal in place of the host parameter name. */ SQLITE_PRIVATE char *sqlite3VdbeExpandSql( Vdbe *p, /* The prepared statement being evaluated */ const char *zRawSql /* Raw text of the SQL statement */ ){ sqlite3 *db; /* The database connection */ int idx = 0; /* Index of a host parameter */ int nextIndex = 1; /* Index of next ? host parameter */ int n; /* Length of a token prefix */ int nToken; /* Length of the parameter token */ int i; /* Loop counter */ Mem *pVar; /* Value of a host parameter */ StrAccum out; /* Accumulate the output here */ #ifndef SQLITE_OMIT_UTF16 Mem utf8; /* Used to convert UTF16 parameters into UTF8 for display */ #endif char zBase[100]; /* Initial working space */ db = p->db; sqlite3StrAccumInit(&out, 0, zBase, sizeof(zBase), db->aLimit[SQLITE_LIMIT_LENGTH]); if( db->nVdbeExec>1 ){ while( *zRawSql ){ const char *zStart = zRawSql; while( *(zRawSql++)!='\n' && *zRawSql ); sqlite3StrAccumAppend(&out, "-- ", 3); assert( (zRawSql - zStart) > 0 ); sqlite3StrAccumAppend(&out, zStart, (int)(zRawSql-zStart)); } }else if( p->nVar==0 ){ sqlite3StrAccumAppend(&out, zRawSql, sqlite3Strlen30(zRawSql)); }else{ while( zRawSql[0] ){ n = findNextHostParameter(zRawSql, &nToken); assert( n>0 ); sqlite3StrAccumAppend(&out, zRawSql, n); zRawSql += n; assert( zRawSql[0] || nToken==0 ); if( nToken==0 ) break; if( zRawSql[0]=='?' ){ if( nToken>1 ){ assert( sqlite3Isdigit(zRawSql[1]) ); sqlite3GetInt32(&zRawSql[1], &idx); }else{ idx = nextIndex; } }else{ assert( zRawSql[0]==':' || zRawSql[0]=='$' || zRawSql[0]=='@' || zRawSql[0]=='#' ); testcase( zRawSql[0]==':' ); testcase( zRawSql[0]=='$' ); testcase( zRawSql[0]=='@' ); testcase( zRawSql[0]=='#' ); idx = sqlite3VdbeParameterIndex(p, zRawSql, nToken); assert( idx>0 ); } zRawSql += nToken; nextIndex = idx + 1; assert( idx>0 && idx<=p->nVar ); pVar = &p->aVar[idx-1]; if( pVar->flags & MEM_Null ){ sqlite3StrAccumAppend(&out, "NULL", 4); }else if( pVar->flags & MEM_Int ){ sqlite3XPrintf(&out, "%lld", pVar->u.i); }else if( pVar->flags & MEM_Real ){ sqlite3XPrintf(&out, "%!.15g", pVar->u.r); }else if( pVar->flags & MEM_Str ){ int nOut; /* Number of bytes of the string text to include in output */ #ifndef SQLITE_OMIT_UTF16 u8 enc = ENC(db); if( enc!=SQLITE_UTF8 ){ memset(&utf8, 0, sizeof(utf8)); utf8.db = db; sqlite3VdbeMemSetStr(&utf8, pVar->z, pVar->n, enc, SQLITE_STATIC); if( SQLITE_NOMEM==sqlite3VdbeChangeEncoding(&utf8, SQLITE_UTF8) ){ out.accError = STRACCUM_NOMEM; out.nAlloc = 0; } pVar = &utf8; } #endif nOut = pVar->n; #ifdef SQLITE_TRACE_SIZE_LIMIT if( nOut>SQLITE_TRACE_SIZE_LIMIT ){ nOut = SQLITE_TRACE_SIZE_LIMIT; while( nOutn && (pVar->z[nOut]&0xc0)==0x80 ){ nOut++; } } #endif sqlite3XPrintf(&out, "'%.*q'", nOut, pVar->z); #ifdef SQLITE_TRACE_SIZE_LIMIT if( nOutn ){ sqlite3XPrintf(&out, "/*+%d bytes*/", pVar->n-nOut); } #endif #ifndef SQLITE_OMIT_UTF16 if( enc!=SQLITE_UTF8 ) sqlite3VdbeMemRelease(&utf8); #endif }else if( pVar->flags & MEM_Zero ){ sqlite3XPrintf(&out, "zeroblob(%d)", pVar->u.nZero); }else{ int nOut; /* Number of bytes of the blob to include in output */ assert( pVar->flags & MEM_Blob ); sqlite3StrAccumAppend(&out, "x'", 2); nOut = pVar->n; #ifdef SQLITE_TRACE_SIZE_LIMIT if( nOut>SQLITE_TRACE_SIZE_LIMIT ) nOut = SQLITE_TRACE_SIZE_LIMIT; #endif for(i=0; iz[i]&0xff); } sqlite3StrAccumAppend(&out, "'", 1); #ifdef SQLITE_TRACE_SIZE_LIMIT if( nOutn ){ sqlite3XPrintf(&out, "/*+%d bytes*/", pVar->n-nOut); } #endif } } } if( out.accError ) sqlite3StrAccumReset(&out); return sqlite3StrAccumFinish(&out); } #endif /* #ifndef SQLITE_OMIT_TRACE */ /************** End of vdbetrace.c *******************************************/ /************** Begin file vdbe.c ********************************************/ /* ** 2001 September 15 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ************************************************************************* ** The code in this file implements the function that runs the ** bytecode of a prepared statement. ** ** Various scripts scan this source file in order to generate HTML ** documentation, headers files, or other derived files. The formatting ** of the code in this file is, therefore, important. See other comments ** in this file for details. If in doubt, do not deviate from existing ** commenting and indentation practices when changing or adding code. */ /* #include "sqliteInt.h" */ /* #include "vdbeInt.h" */ /* ** Invoke this macro on memory cells just prior to changing the ** value of the cell. This macro verifies that shallow copies are ** not misused. A shallow copy of a string or blob just copies a ** pointer to the string or blob, not the content. If the original ** is changed while the copy is still in use, the string or blob might ** be changed out from under the copy. This macro verifies that nothing ** like that ever happens. */ #ifdef SQLITE_DEBUG # define memAboutToChange(P,M) sqlite3VdbeMemAboutToChange(P,M) #else # define memAboutToChange(P,M) #endif /* ** The following global variable is incremented every time a cursor ** moves, either by the OP_SeekXX, OP_Next, or OP_Prev opcodes. The test ** procedures use this information to make sure that indices are ** working correctly. This variable has no function other than to ** help verify the correct operation of the library. */ #ifdef SQLITE_TEST SQLITE_API int sqlite3_search_count = 0; #endif /* ** When this global variable is positive, it gets decremented once before ** each instruction in the VDBE. When it reaches zero, the u1.isInterrupted ** field of the sqlite3 structure is set in order to simulate an interrupt. ** ** This facility is used for testing purposes only. It does not function ** in an ordinary build. */ #ifdef SQLITE_TEST SQLITE_API int sqlite3_interrupt_count = 0; #endif /* ** The next global variable is incremented each type the OP_Sort opcode ** is executed. The test procedures use this information to make sure that ** sorting is occurring or not occurring at appropriate times. This variable ** has no function other than to help verify the correct operation of the ** library. */ #ifdef SQLITE_TEST SQLITE_API int sqlite3_sort_count = 0; #endif /* ** The next global variable records the size of the largest MEM_Blob ** or MEM_Str that has been used by a VDBE opcode. The test procedures ** use this information to make sure that the zero-blob functionality ** is working correctly. This variable has no function other than to ** help verify the correct operation of the library. */ #ifdef SQLITE_TEST SQLITE_API int sqlite3_max_blobsize = 0; static void updateMaxBlobsize(Mem *p){ if( (p->flags & (MEM_Str|MEM_Blob))!=0 && p->n>sqlite3_max_blobsize ){ sqlite3_max_blobsize = p->n; } } #endif /* ** This macro evaluates to true if either the update hook or the preupdate ** hook are enabled for database connect DB. */ #ifdef SQLITE_ENABLE_PREUPDATE_HOOK # define HAS_UPDATE_HOOK(DB) ((DB)->xPreUpdateCallback||(DB)->xUpdateCallback) #else # define HAS_UPDATE_HOOK(DB) ((DB)->xUpdateCallback) #endif /* ** The next global variable is incremented each time the OP_Found opcode ** is executed. This is used to test whether or not the foreign key ** operation implemented using OP_FkIsZero is working. This variable ** has no function other than to help verify the correct operation of the ** library. */ #ifdef SQLITE_TEST SQLITE_API int sqlite3_found_count = 0; #endif /* ** Test a register to see if it exceeds the current maximum blob size. ** If it does, record the new maximum blob size. */ #if defined(SQLITE_TEST) && !defined(SQLITE_OMIT_BUILTIN_TEST) # define UPDATE_MAX_BLOBSIZE(P) updateMaxBlobsize(P) #else # define UPDATE_MAX_BLOBSIZE(P) #endif /* ** Invoke the VDBE coverage callback, if that callback is defined. This ** feature is used for test suite validation only and does not appear an ** production builds. ** ** M is an integer, 2 or 3, that indices how many different ways the ** branch can go. It is usually 2. "I" is the direction the branch ** goes. 0 means falls through. 1 means branch is taken. 2 means the ** second alternative branch is taken. ** ** iSrcLine is the source code line (from the __LINE__ macro) that ** generated the VDBE instruction. This instrumentation assumes that all ** source code is in a single file (the amalgamation). Special values 1 ** and 2 for the iSrcLine parameter mean that this particular branch is ** always taken or never taken, respectively. */ #if !defined(SQLITE_VDBE_COVERAGE) # define VdbeBranchTaken(I,M) #else # define VdbeBranchTaken(I,M) vdbeTakeBranch(pOp->iSrcLine,I,M) static void vdbeTakeBranch(int iSrcLine, u8 I, u8 M){ if( iSrcLine<=2 && ALWAYS(iSrcLine>0) ){ M = iSrcLine; /* Assert the truth of VdbeCoverageAlwaysTaken() and ** VdbeCoverageNeverTaken() */ assert( (M & I)==I ); }else{ if( sqlite3GlobalConfig.xVdbeBranch==0 ) return; /*NO_TEST*/ sqlite3GlobalConfig.xVdbeBranch(sqlite3GlobalConfig.pVdbeBranchArg, iSrcLine,I,M); } } #endif /* ** Convert the given register into a string if it isn't one ** already. Return non-zero if a malloc() fails. */ #define Stringify(P, enc) \ if(((P)->flags&(MEM_Str|MEM_Blob))==0 && sqlite3VdbeMemStringify(P,enc,0)) \ { goto no_mem; } /* ** An ephemeral string value (signified by the MEM_Ephem flag) contains ** a pointer to a dynamically allocated string where some other entity ** is responsible for deallocating that string. Because the register ** does not control the string, it might be deleted without the register ** knowing it. ** ** This routine converts an ephemeral string into a dynamically allocated ** string that the register itself controls. In other words, it ** converts an MEM_Ephem string into a string with P.z==P.zMalloc. */ #define Deephemeralize(P) \ if( ((P)->flags&MEM_Ephem)!=0 \ && sqlite3VdbeMemMakeWriteable(P) ){ goto no_mem;} /* Return true if the cursor was opened using the OP_OpenSorter opcode. */ #define isSorter(x) ((x)->eCurType==CURTYPE_SORTER) /* ** Allocate VdbeCursor number iCur. Return a pointer to it. Return NULL ** if we run out of memory. */ static VdbeCursor *allocateCursor( Vdbe *p, /* The virtual machine */ int iCur, /* Index of the new VdbeCursor */ int nField, /* Number of fields in the table or index */ int iDb, /* Database the cursor belongs to, or -1 */ u8 eCurType /* Type of the new cursor */ ){ /* Find the memory cell that will be used to store the blob of memory ** required for this VdbeCursor structure. It is convenient to use a ** vdbe memory cell to manage the memory allocation required for a ** VdbeCursor structure for the following reasons: ** ** * Sometimes cursor numbers are used for a couple of different ** purposes in a vdbe program. The different uses might require ** different sized allocations. Memory cells provide growable ** allocations. ** ** * When using ENABLE_MEMORY_MANAGEMENT, memory cell buffers can ** be freed lazily via the sqlite3_release_memory() API. This ** minimizes the number of malloc calls made by the system. ** ** The memory cell for cursor 0 is aMem[0]. The rest are allocated from ** the top of the register space. Cursor 1 is at Mem[p->nMem-1]. ** Cursor 2 is at Mem[p->nMem-2]. And so forth. */ Mem *pMem = iCur>0 ? &p->aMem[p->nMem-iCur] : p->aMem; int nByte; VdbeCursor *pCx = 0; nByte = ROUND8(sizeof(VdbeCursor)) + 2*sizeof(u32)*nField + (eCurType==CURTYPE_BTREE?sqlite3BtreeCursorSize():0); assert( iCur>=0 && iCurnCursor ); if( p->apCsr[iCur] ){ /*OPTIMIZATION-IF-FALSE*/ sqlite3VdbeFreeCursor(p, p->apCsr[iCur]); p->apCsr[iCur] = 0; } if( SQLITE_OK==sqlite3VdbeMemClearAndResize(pMem, nByte) ){ p->apCsr[iCur] = pCx = (VdbeCursor*)pMem->z; memset(pCx, 0, sizeof(VdbeCursor)); pCx->eCurType = eCurType; pCx->iDb = iDb; pCx->nField = nField; pCx->aOffset = &pCx->aType[nField]; if( eCurType==CURTYPE_BTREE ){ pCx->uc.pCursor = (BtCursor*) &pMem->z[ROUND8(sizeof(VdbeCursor))+2*sizeof(u32)*nField]; sqlite3BtreeCursorZero(pCx->uc.pCursor); } } return pCx; } /* ** Try to convert a value into a numeric representation if we can ** do so without loss of information. In other words, if the string ** looks like a number, convert it into a number. If it does not ** look like a number, leave it alone. ** ** If the bTryForInt flag is true, then extra effort is made to give ** an integer representation. Strings that look like floating point ** values but which have no fractional component (example: '48.00') ** will have a MEM_Int representation when bTryForInt is true. ** ** If bTryForInt is false, then if the input string contains a decimal ** point or exponential notation, the result is only MEM_Real, even ** if there is an exact integer representation of the quantity. */ static void applyNumericAffinity(Mem *pRec, int bTryForInt){ double rValue; i64 iValue; u8 enc = pRec->enc; assert( (pRec->flags & (MEM_Str|MEM_Int|MEM_Real))==MEM_Str ); if( sqlite3AtoF(pRec->z, &rValue, pRec->n, enc)==0 ) return; if( 0==sqlite3Atoi64(pRec->z, &iValue, pRec->n, enc) ){ pRec->u.i = iValue; pRec->flags |= MEM_Int; }else{ pRec->u.r = rValue; pRec->flags |= MEM_Real; if( bTryForInt ) sqlite3VdbeIntegerAffinity(pRec); } } /* ** Processing is determine by the affinity parameter: ** ** SQLITE_AFF_INTEGER: ** SQLITE_AFF_REAL: ** SQLITE_AFF_NUMERIC: ** Try to convert pRec to an integer representation or a ** floating-point representation if an integer representation ** is not possible. Note that the integer representation is ** always preferred, even if the affinity is REAL, because ** an integer representation is more space efficient on disk. ** ** SQLITE_AFF_TEXT: ** Convert pRec to a text representation. ** ** SQLITE_AFF_BLOB: ** No-op. pRec is unchanged. */ static void applyAffinity( Mem *pRec, /* The value to apply affinity to */ char affinity, /* The affinity to be applied */ u8 enc /* Use this text encoding */ ){ if( affinity>=SQLITE_AFF_NUMERIC ){ assert( affinity==SQLITE_AFF_INTEGER || affinity==SQLITE_AFF_REAL || affinity==SQLITE_AFF_NUMERIC ); if( (pRec->flags & MEM_Int)==0 ){ /*OPTIMIZATION-IF-FALSE*/ if( (pRec->flags & MEM_Real)==0 ){ if( pRec->flags & MEM_Str ) applyNumericAffinity(pRec,1); }else{ sqlite3VdbeIntegerAffinity(pRec); } } }else if( affinity==SQLITE_AFF_TEXT ){ /* Only attempt the conversion to TEXT if there is an integer or real ** representation (blob and NULL do not get converted) but no string ** representation. It would be harmless to repeat the conversion if ** there is already a string rep, but it is pointless to waste those ** CPU cycles. */ if( 0==(pRec->flags&MEM_Str) ){ /*OPTIMIZATION-IF-FALSE*/ if( (pRec->flags&(MEM_Real|MEM_Int)) ){ sqlite3VdbeMemStringify(pRec, enc, 1); } } pRec->flags &= ~(MEM_Real|MEM_Int); } } /* ** Try to convert the type of a function argument or a result column ** into a numeric representation. Use either INTEGER or REAL whichever ** is appropriate. But only do the conversion if it is possible without ** loss of information and return the revised type of the argument. */ SQLITE_API int sqlite3_value_numeric_type(sqlite3_value *pVal){ int eType = sqlite3_value_type(pVal); if( eType==SQLITE_TEXT ){ Mem *pMem = (Mem*)pVal; applyNumericAffinity(pMem, 0); eType = sqlite3_value_type(pVal); } return eType; } /* ** Exported version of applyAffinity(). This one works on sqlite3_value*, ** not the internal Mem* type. */ SQLITE_PRIVATE void sqlite3ValueApplyAffinity( sqlite3_value *pVal, u8 affinity, u8 enc ){ applyAffinity((Mem *)pVal, affinity, enc); } /* ** pMem currently only holds a string type (or maybe a BLOB that we can ** interpret as a string if we want to). Compute its corresponding ** numeric type, if has one. Set the pMem->u.r and pMem->u.i fields ** accordingly. */ static u16 SQLITE_NOINLINE computeNumericType(Mem *pMem){ assert( (pMem->flags & (MEM_Int|MEM_Real))==0 ); assert( (pMem->flags & (MEM_Str|MEM_Blob))!=0 ); if( sqlite3AtoF(pMem->z, &pMem->u.r, pMem->n, pMem->enc)==0 ){ return 0; } if( sqlite3Atoi64(pMem->z, &pMem->u.i, pMem->n, pMem->enc)==SQLITE_OK ){ return MEM_Int; } return MEM_Real; } /* ** Return the numeric type for pMem, either MEM_Int or MEM_Real or both or ** none. ** ** Unlike applyNumericAffinity(), this routine does not modify pMem->flags. ** But it does set pMem->u.r and pMem->u.i appropriately. */ static u16 numericType(Mem *pMem){ if( pMem->flags & (MEM_Int|MEM_Real) ){ return pMem->flags & (MEM_Int|MEM_Real); } if( pMem->flags & (MEM_Str|MEM_Blob) ){ return computeNumericType(pMem); } return 0; } #ifdef SQLITE_DEBUG /* ** Write a nice string representation of the contents of cell pMem ** into buffer zBuf, length nBuf. */ SQLITE_PRIVATE void sqlite3VdbeMemPrettyPrint(Mem *pMem, char *zBuf){ char *zCsr = zBuf; int f = pMem->flags; static const char *const encnames[] = {"(X)", "(8)", "(16LE)", "(16BE)"}; if( f&MEM_Blob ){ int i; char c; if( f & MEM_Dyn ){ c = 'z'; assert( (f & (MEM_Static|MEM_Ephem))==0 ); }else if( f & MEM_Static ){ c = 't'; assert( (f & (MEM_Dyn|MEM_Ephem))==0 ); }else if( f & MEM_Ephem ){ c = 'e'; assert( (f & (MEM_Static|MEM_Dyn))==0 ); }else{ c = 's'; } sqlite3_snprintf(100, zCsr, "%c", c); zCsr += sqlite3Strlen30(zCsr); sqlite3_snprintf(100, zCsr, "%d[", pMem->n); zCsr += sqlite3Strlen30(zCsr); for(i=0; i<16 && in; i++){ sqlite3_snprintf(100, zCsr, "%02X", ((int)pMem->z[i] & 0xFF)); zCsr += sqlite3Strlen30(zCsr); } for(i=0; i<16 && in; i++){ char z = pMem->z[i]; if( z<32 || z>126 ) *zCsr++ = '.'; else *zCsr++ = z; } sqlite3_snprintf(100, zCsr, "]%s", encnames[pMem->enc]); zCsr += sqlite3Strlen30(zCsr); if( f & MEM_Zero ){ sqlite3_snprintf(100, zCsr,"+%dz",pMem->u.nZero); zCsr += sqlite3Strlen30(zCsr); } *zCsr = '\0'; }else if( f & MEM_Str ){ int j, k; zBuf[0] = ' '; if( f & MEM_Dyn ){ zBuf[1] = 'z'; assert( (f & (MEM_Static|MEM_Ephem))==0 ); }else if( f & MEM_Static ){ zBuf[1] = 't'; assert( (f & (MEM_Dyn|MEM_Ephem))==0 ); }else if( f & MEM_Ephem ){ zBuf[1] = 'e'; assert( (f & (MEM_Static|MEM_Dyn))==0 ); }else{ zBuf[1] = 's'; } k = 2; sqlite3_snprintf(100, &zBuf[k], "%d", pMem->n); k += sqlite3Strlen30(&zBuf[k]); zBuf[k++] = '['; for(j=0; j<15 && jn; j++){ u8 c = pMem->z[j]; if( c>=0x20 && c<0x7f ){ zBuf[k++] = c; }else{ zBuf[k++] = '.'; } } zBuf[k++] = ']'; sqlite3_snprintf(100,&zBuf[k], encnames[pMem->enc]); k += sqlite3Strlen30(&zBuf[k]); zBuf[k++] = 0; } } #endif #ifdef SQLITE_DEBUG /* ** Print the value of a register for tracing purposes: */ static void memTracePrint(Mem *p){ if( p->flags & MEM_Undefined ){ printf(" undefined"); }else if( p->flags & MEM_Null ){ printf(" NULL"); }else if( (p->flags & (MEM_Int|MEM_Str))==(MEM_Int|MEM_Str) ){ printf(" si:%lld", p->u.i); }else if( p->flags & MEM_Int ){ printf(" i:%lld", p->u.i); #ifndef SQLITE_OMIT_FLOATING_POINT }else if( p->flags & MEM_Real ){ printf(" r:%g", p->u.r); #endif }else if( p->flags & MEM_RowSet ){ printf(" (rowset)"); }else{ char zBuf[200]; sqlite3VdbeMemPrettyPrint(p, zBuf); printf(" %s", zBuf); } if( p->flags & MEM_Subtype ) printf(" subtype=0x%02x", p->eSubtype); } static void registerTrace(int iReg, Mem *p){ printf("REG[%d] = ", iReg); memTracePrint(p); printf("\n"); } #endif #ifdef SQLITE_DEBUG # define REGISTER_TRACE(R,M) if(db->flags&SQLITE_VdbeTrace)registerTrace(R,M) #else # define REGISTER_TRACE(R,M) #endif #ifdef VDBE_PROFILE /* ** hwtime.h contains inline assembler code for implementing ** high-performance timing routines. */ /************** Include hwtime.h in the middle of vdbe.c *********************/ /************** Begin file hwtime.h ******************************************/ /* ** 2008 May 27 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ****************************************************************************** ** ** This file contains inline asm code for retrieving "high-performance" ** counters for x86 class CPUs. */ #ifndef SQLITE_HWTIME_H #define SQLITE_HWTIME_H /* ** The following routine only works on pentium-class (or newer) processors. ** It uses the RDTSC opcode to read the cycle count value out of the ** processor and returns that value. This can be used for high-res ** profiling. */ #if (defined(__GNUC__) || defined(_MSC_VER)) && \ (defined(i386) || defined(__i386__) || defined(_M_IX86)) #if defined(__GNUC__) __inline__ sqlite_uint64 sqlite3Hwtime(void){ unsigned int lo, hi; __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi)); return (sqlite_uint64)hi << 32 | lo; } #elif defined(_MSC_VER) __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){ __asm { rdtsc ret ; return value at EDX:EAX } } #endif #elif (defined(__GNUC__) && defined(__x86_64__)) __inline__ sqlite_uint64 sqlite3Hwtime(void){ unsigned long val; __asm__ __volatile__ ("rdtsc" : "=A" (val)); return val; } #elif (defined(__GNUC__) && defined(__ppc__)) __inline__ sqlite_uint64 sqlite3Hwtime(void){ unsigned long long retval; unsigned long junk; __asm__ __volatile__ ("\n\ 1: mftbu %1\n\ mftb %L0\n\ mftbu %0\n\ cmpw %0,%1\n\ bne 1b" : "=r" (retval), "=r" (junk)); return retval; } #else #error Need implementation of sqlite3Hwtime() for your platform. /* ** To compile without implementing sqlite3Hwtime() for your platform, ** you can remove the above #error and use the following ** stub function. You will lose timing support for many ** of the debugging and testing utilities, but it should at ** least compile and run. */ SQLITE_PRIVATE sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); } #endif #endif /* !defined(SQLITE_HWTIME_H) */ /************** End of hwtime.h **********************************************/ /************** Continuing where we left off in vdbe.c ***********************/ #endif #ifndef NDEBUG /* ** This function is only called from within an assert() expression. It ** checks that the sqlite3.nTransaction variable is correctly set to ** the number of non-transaction savepoints currently in the ** linked list starting at sqlite3.pSavepoint. ** ** Usage: ** ** assert( checkSavepointCount(db) ); */ static int checkSavepointCount(sqlite3 *db){ int n = 0; Savepoint *p; for(p=db->pSavepoint; p; p=p->pNext) n++; assert( n==(db->nSavepoint + db->isTransactionSavepoint) ); return 1; } #endif /* ** Return the register of pOp->p2 after first preparing it to be ** overwritten with an integer value. */ static SQLITE_NOINLINE Mem *out2PrereleaseWithClear(Mem *pOut){ sqlite3VdbeMemSetNull(pOut); pOut->flags = MEM_Int; return pOut; } static Mem *out2Prerelease(Vdbe *p, VdbeOp *pOp){ Mem *pOut; assert( pOp->p2>0 ); assert( pOp->p2<=(p->nMem+1 - p->nCursor) ); pOut = &p->aMem[pOp->p2]; memAboutToChange(p, pOut); if( VdbeMemDynamic(pOut) ){ /*OPTIMIZATION-IF-FALSE*/ return out2PrereleaseWithClear(pOut); }else{ pOut->flags = MEM_Int; return pOut; } } /* ** Execute as much of a VDBE program as we can. ** This is the core of sqlite3_step(). */ SQLITE_PRIVATE int sqlite3VdbeExec( Vdbe *p /* The VDBE */ ){ Op *aOp = p->aOp; /* Copy of p->aOp */ Op *pOp = aOp; /* Current operation */ #if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE) Op *pOrigOp; /* Value of pOp at the top of the loop */ #endif #ifdef SQLITE_DEBUG int nExtraDelete = 0; /* Verifies FORDELETE and AUXDELETE flags */ #endif int rc = SQLITE_OK; /* Value to return */ sqlite3 *db = p->db; /* The database */ u8 resetSchemaOnFault = 0; /* Reset schema after an error if positive */ u8 encoding = ENC(db); /* The database encoding */ int iCompare = 0; /* Result of last comparison */ unsigned nVmStep = 0; /* Number of virtual machine steps */ #ifndef SQLITE_OMIT_PROGRESS_CALLBACK unsigned nProgressLimit = 0;/* Invoke xProgress() when nVmStep reaches this */ #endif Mem *aMem = p->aMem; /* Copy of p->aMem */ Mem *pIn1 = 0; /* 1st input operand */ Mem *pIn2 = 0; /* 2nd input operand */ Mem *pIn3 = 0; /* 3rd input operand */ Mem *pOut = 0; /* Output operand */ int *aPermute = 0; /* Permutation of columns for OP_Compare */ i64 lastRowid = db->lastRowid; /* Saved value of the last insert ROWID */ #ifdef VDBE_PROFILE u64 start; /* CPU clock count at start of opcode */ #endif /*** INSERT STACK UNION HERE ***/ assert( p->magic==VDBE_MAGIC_RUN ); /* sqlite3_step() verifies this */ sqlite3VdbeEnter(p); if( p->rc==SQLITE_NOMEM ){ /* This happens if a malloc() inside a call to sqlite3_column_text() or ** sqlite3_column_text16() failed. */ goto no_mem; } assert( p->rc==SQLITE_OK || (p->rc&0xff)==SQLITE_BUSY ); assert( p->bIsReader || p->readOnly!=0 ); p->rc = SQLITE_OK; p->iCurrentTime = 0; assert( p->explain==0 ); p->pResultSet = 0; db->busyHandler.nBusy = 0; if( db->u1.isInterrupted ) goto abort_due_to_interrupt; sqlite3VdbeIOTraceSql(p); #ifndef SQLITE_OMIT_PROGRESS_CALLBACK if( db->xProgress ){ u32 iPrior = p->aCounter[SQLITE_STMTSTATUS_VM_STEP]; assert( 0 < db->nProgressOps ); nProgressLimit = db->nProgressOps - (iPrior % db->nProgressOps); } #endif #ifdef SQLITE_DEBUG sqlite3BeginBenignMalloc(); if( p->pc==0 && (p->db->flags & (SQLITE_VdbeListing|SQLITE_VdbeEQP|SQLITE_VdbeTrace))!=0 ){ int i; int once = 1; sqlite3VdbePrintSql(p); if( p->db->flags & SQLITE_VdbeListing ){ printf("VDBE Program Listing:\n"); for(i=0; inOp; i++){ sqlite3VdbePrintOp(stdout, i, &aOp[i]); } } if( p->db->flags & SQLITE_VdbeEQP ){ for(i=0; inOp; i++){ if( aOp[i].opcode==OP_Explain ){ if( once ) printf("VDBE Query Plan:\n"); printf("%s\n", aOp[i].p4.z); once = 0; } } } if( p->db->flags & SQLITE_VdbeTrace ) printf("VDBE Trace:\n"); } sqlite3EndBenignMalloc(); #endif for(pOp=&aOp[p->pc]; 1; pOp++){ /* Errors are detected by individual opcodes, with an immediate ** jumps to abort_due_to_error. */ assert( rc==SQLITE_OK ); assert( pOp>=aOp && pOp<&aOp[p->nOp]); #ifdef VDBE_PROFILE start = sqlite3Hwtime(); #endif nVmStep++; #ifdef SQLITE_ENABLE_STMT_SCANSTATUS if( p->anExec ) p->anExec[(int)(pOp-aOp)]++; #endif /* Only allow tracing if SQLITE_DEBUG is defined. */ #ifdef SQLITE_DEBUG if( db->flags & SQLITE_VdbeTrace ){ sqlite3VdbePrintOp(stdout, (int)(pOp - aOp), pOp); } #endif /* Check to see if we need to simulate an interrupt. This only happens ** if we have a special test build. */ #ifdef SQLITE_TEST if( sqlite3_interrupt_count>0 ){ sqlite3_interrupt_count--; if( sqlite3_interrupt_count==0 ){ sqlite3_interrupt(db); } } #endif /* Sanity checking on other operands */ #ifdef SQLITE_DEBUG { u8 opProperty = sqlite3OpcodeProperty[pOp->opcode]; if( (opProperty & OPFLG_IN1)!=0 ){ assert( pOp->p1>0 ); assert( pOp->p1<=(p->nMem+1 - p->nCursor) ); assert( memIsValid(&aMem[pOp->p1]) ); assert( sqlite3VdbeCheckMemInvariants(&aMem[pOp->p1]) ); REGISTER_TRACE(pOp->p1, &aMem[pOp->p1]); } if( (opProperty & OPFLG_IN2)!=0 ){ assert( pOp->p2>0 ); assert( pOp->p2<=(p->nMem+1 - p->nCursor) ); assert( memIsValid(&aMem[pOp->p2]) ); assert( sqlite3VdbeCheckMemInvariants(&aMem[pOp->p2]) ); REGISTER_TRACE(pOp->p2, &aMem[pOp->p2]); } if( (opProperty & OPFLG_IN3)!=0 ){ assert( pOp->p3>0 ); assert( pOp->p3<=(p->nMem+1 - p->nCursor) ); assert( memIsValid(&aMem[pOp->p3]) ); assert( sqlite3VdbeCheckMemInvariants(&aMem[pOp->p3]) ); REGISTER_TRACE(pOp->p3, &aMem[pOp->p3]); } if( (opProperty & OPFLG_OUT2)!=0 ){ assert( pOp->p2>0 ); assert( pOp->p2<=(p->nMem+1 - p->nCursor) ); memAboutToChange(p, &aMem[pOp->p2]); } if( (opProperty & OPFLG_OUT3)!=0 ){ assert( pOp->p3>0 ); assert( pOp->p3<=(p->nMem+1 - p->nCursor) ); memAboutToChange(p, &aMem[pOp->p3]); } } #endif #if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE) pOrigOp = pOp; #endif switch( pOp->opcode ){ /***************************************************************************** ** What follows is a massive switch statement where each case implements a ** separate instruction in the virtual machine. If we follow the usual ** indentation conventions, each case should be indented by 6 spaces. But ** that is a lot of wasted space on the left margin. So the code within ** the switch statement will break with convention and be flush-left. Another ** big comment (similar to this one) will mark the point in the code where ** we transition back to normal indentation. ** ** The formatting of each case is important. The makefile for SQLite ** generates two C files "opcodes.h" and "opcodes.c" by scanning this ** file looking for lines that begin with "case OP_". The opcodes.h files ** will be filled with #defines that give unique integer values to each ** opcode and the opcodes.c file is filled with an array of strings where ** each string is the symbolic name for the corresponding opcode. If the ** case statement is followed by a comment of the form "/# same as ... #/" ** that comment is used to determine the particular value of the opcode. ** ** Other keywords in the comment that follows each case are used to ** construct the OPFLG_INITIALIZER value that initializes opcodeProperty[]. ** Keywords include: in1, in2, in3, out2, out3. See ** the mkopcodeh.awk script for additional information. ** ** Documentation about VDBE opcodes is generated by scanning this file ** for lines of that contain "Opcode:". That line and all subsequent ** comment lines are used in the generation of the opcode.html documentation ** file. ** ** SUMMARY: ** ** Formatting is important to scripts that scan this file. ** Do not deviate from the formatting style currently in use. ** *****************************************************************************/ /* Opcode: Goto * P2 * * * ** ** An unconditional jump to address P2. ** The next instruction executed will be ** the one at index P2 from the beginning of ** the program. ** ** The P1 parameter is not actually used by this opcode. However, it ** is sometimes set to 1 instead of 0 as a hint to the command-line shell ** that this Goto is the bottom of a loop and that the lines from P2 down ** to the current line should be indented for EXPLAIN output. */ case OP_Goto: { /* jump */ jump_to_p2_and_check_for_interrupt: pOp = &aOp[pOp->p2 - 1]; /* Opcodes that are used as the bottom of a loop (OP_Next, OP_Prev, ** OP_VNext, OP_RowSetNext, or OP_SorterNext) all jump here upon ** completion. Check to see if sqlite3_interrupt() has been called ** or if the progress callback needs to be invoked. ** ** This code uses unstructured "goto" statements and does not look clean. ** But that is not due to sloppy coding habits. The code is written this ** way for performance, to avoid having to run the interrupt and progress ** checks on every opcode. This helps sqlite3_step() to run about 1.5% ** faster according to "valgrind --tool=cachegrind" */ check_for_interrupt: if( db->u1.isInterrupted ) goto abort_due_to_interrupt; #ifndef SQLITE_OMIT_PROGRESS_CALLBACK /* Call the progress callback if it is configured and the required number ** of VDBE ops have been executed (either since this invocation of ** sqlite3VdbeExec() or since last time the progress callback was called). ** If the progress callback returns non-zero, exit the virtual machine with ** a return code SQLITE_ABORT. */ if( db->xProgress!=0 && nVmStep>=nProgressLimit ){ assert( db->nProgressOps!=0 ); nProgressLimit = nVmStep + db->nProgressOps - (nVmStep%db->nProgressOps); if( db->xProgress(db->pProgressArg) ){ rc = SQLITE_INTERRUPT; goto abort_due_to_error; } } #endif break; } /* Opcode: Gosub P1 P2 * * * ** ** Write the current address onto register P1 ** and then jump to address P2. */ case OP_Gosub: { /* jump */ assert( pOp->p1>0 && pOp->p1<=(p->nMem+1 - p->nCursor) ); pIn1 = &aMem[pOp->p1]; assert( VdbeMemDynamic(pIn1)==0 ); memAboutToChange(p, pIn1); pIn1->flags = MEM_Int; pIn1->u.i = (int)(pOp-aOp); REGISTER_TRACE(pOp->p1, pIn1); /* Most jump operations do a goto to this spot in order to update ** the pOp pointer. */ jump_to_p2: pOp = &aOp[pOp->p2 - 1]; break; } /* Opcode: Return P1 * * * * ** ** Jump to the next instruction after the address in register P1. After ** the jump, register P1 becomes undefined. */ case OP_Return: { /* in1 */ pIn1 = &aMem[pOp->p1]; assert( pIn1->flags==MEM_Int ); pOp = &aOp[pIn1->u.i]; pIn1->flags = MEM_Undefined; break; } /* Opcode: InitCoroutine P1 P2 P3 * * ** ** Set up register P1 so that it will Yield to the coroutine ** located at address P3. ** ** If P2!=0 then the coroutine implementation immediately follows ** this opcode. So jump over the coroutine implementation to ** address P2. ** ** See also: EndCoroutine */ case OP_InitCoroutine: { /* jump */ assert( pOp->p1>0 && pOp->p1<=(p->nMem+1 - p->nCursor) ); assert( pOp->p2>=0 && pOp->p2nOp ); assert( pOp->p3>=0 && pOp->p3nOp ); pOut = &aMem[pOp->p1]; assert( !VdbeMemDynamic(pOut) ); pOut->u.i = pOp->p3 - 1; pOut->flags = MEM_Int; if( pOp->p2 ) goto jump_to_p2; break; } /* Opcode: EndCoroutine P1 * * * * ** ** The instruction at the address in register P1 is a Yield. ** Jump to the P2 parameter of that Yield. ** After the jump, register P1 becomes undefined. ** ** See also: InitCoroutine */ case OP_EndCoroutine: { /* in1 */ VdbeOp *pCaller; pIn1 = &aMem[pOp->p1]; assert( pIn1->flags==MEM_Int ); assert( pIn1->u.i>=0 && pIn1->u.inOp ); pCaller = &aOp[pIn1->u.i]; assert( pCaller->opcode==OP_Yield ); assert( pCaller->p2>=0 && pCaller->p2nOp ); pOp = &aOp[pCaller->p2 - 1]; pIn1->flags = MEM_Undefined; break; } /* Opcode: Yield P1 P2 * * * ** ** Swap the program counter with the value in register P1. This ** has the effect of yielding to a coroutine. ** ** If the coroutine that is launched by this instruction ends with ** Yield or Return then continue to the next instruction. But if ** the coroutine launched by this instruction ends with ** EndCoroutine, then jump to P2 rather than continuing with the ** next instruction. ** ** See also: InitCoroutine */ case OP_Yield: { /* in1, jump */ int pcDest; pIn1 = &aMem[pOp->p1]; assert( VdbeMemDynamic(pIn1)==0 ); pIn1->flags = MEM_Int; pcDest = (int)pIn1->u.i; pIn1->u.i = (int)(pOp - aOp); REGISTER_TRACE(pOp->p1, pIn1); pOp = &aOp[pcDest]; break; } /* Opcode: HaltIfNull P1 P2 P3 P4 P5 ** Synopsis: if r[P3]=null halt ** ** Check the value in register P3. If it is NULL then Halt using ** parameter P1, P2, and P4 as if this were a Halt instruction. If the ** value in register P3 is not NULL, then this routine is a no-op. ** The P5 parameter should be 1. */ case OP_HaltIfNull: { /* in3 */ pIn3 = &aMem[pOp->p3]; if( (pIn3->flags & MEM_Null)==0 ) break; /* Fall through into OP_Halt */ } /* Opcode: Halt P1 P2 * P4 P5 ** ** Exit immediately. All open cursors, etc are closed ** automatically. ** ** P1 is the result code returned by sqlite3_exec(), sqlite3_reset(), ** or sqlite3_finalize(). For a normal halt, this should be SQLITE_OK (0). ** For errors, it can be some other value. If P1!=0 then P2 will determine ** whether or not to rollback the current transaction. Do not rollback ** if P2==OE_Fail. Do the rollback if P2==OE_Rollback. If P2==OE_Abort, ** then back out all changes that have occurred during this execution of the ** VDBE, but do not rollback the transaction. ** ** If P4 is not null then it is an error message string. ** ** P5 is a value between 0 and 4, inclusive, that modifies the P4 string. ** ** 0: (no change) ** 1: NOT NULL contraint failed: P4 ** 2: UNIQUE constraint failed: P4 ** 3: CHECK constraint failed: P4 ** 4: FOREIGN KEY constraint failed: P4 ** ** If P5 is not zero and P4 is NULL, then everything after the ":" is ** omitted. ** ** There is an implied "Halt 0 0 0" instruction inserted at the very end of ** every program. So a jump past the last instruction of the program ** is the same as executing Halt. */ case OP_Halt: { VdbeFrame *pFrame; int pcx; pcx = (int)(pOp - aOp); if( pOp->p1==SQLITE_OK && p->pFrame ){ /* Halt the sub-program. Return control to the parent frame. */ pFrame = p->pFrame; p->pFrame = pFrame->pParent; p->nFrame--; sqlite3VdbeSetChanges(db, p->nChange); pcx = sqlite3VdbeFrameRestore(pFrame); lastRowid = db->lastRowid; if( pOp->p2==OE_Ignore ){ /* Instruction pcx is the OP_Program that invoked the sub-program ** currently being halted. If the p2 instruction of this OP_Halt ** instruction is set to OE_Ignore, then the sub-program is throwing ** an IGNORE exception. In this case jump to the address specified ** as the p2 of the calling OP_Program. */ pcx = p->aOp[pcx].p2-1; } aOp = p->aOp; aMem = p->aMem; pOp = &aOp[pcx]; break; } p->rc = pOp->p1; p->errorAction = (u8)pOp->p2; p->pc = pcx; assert( pOp->p5>=0 && pOp->p5<=4 ); if( p->rc ){ if( pOp->p5 ){ static const char * const azType[] = { "NOT NULL", "UNIQUE", "CHECK", "FOREIGN KEY" }; testcase( pOp->p5==1 ); testcase( pOp->p5==2 ); testcase( pOp->p5==3 ); testcase( pOp->p5==4 ); sqlite3VdbeError(p, "%s constraint failed", azType[pOp->p5-1]); if( pOp->p4.z ){ p->zErrMsg = sqlite3MPrintf(db, "%z: %s", p->zErrMsg, pOp->p4.z); } }else{ sqlite3VdbeError(p, "%s", pOp->p4.z); } sqlite3_log(pOp->p1, "abort at %d in [%s]: %s", pcx, p->zSql, p->zErrMsg); } rc = sqlite3VdbeHalt(p); assert( rc==SQLITE_BUSY || rc==SQLITE_OK || rc==SQLITE_ERROR ); if( rc==SQLITE_BUSY ){ p->rc = SQLITE_BUSY; }else{ assert( rc==SQLITE_OK || (p->rc&0xff)==SQLITE_CONSTRAINT ); assert( rc==SQLITE_OK || db->nDeferredCons>0 || db->nDeferredImmCons>0 ); rc = p->rc ? SQLITE_ERROR : SQLITE_DONE; } goto vdbe_return; } /* Opcode: Integer P1 P2 * * * ** Synopsis: r[P2]=P1 ** ** The 32-bit integer value P1 is written into register P2. */ case OP_Integer: { /* out2 */ pOut = out2Prerelease(p, pOp); pOut->u.i = pOp->p1; break; } /* Opcode: Int64 * P2 * P4 * ** Synopsis: r[P2]=P4 ** ** P4 is a pointer to a 64-bit integer value. ** Write that value into register P2. */ case OP_Int64: { /* out2 */ pOut = out2Prerelease(p, pOp); assert( pOp->p4.pI64!=0 ); pOut->u.i = *pOp->p4.pI64; break; } #ifndef SQLITE_OMIT_FLOATING_POINT /* Opcode: Real * P2 * P4 * ** Synopsis: r[P2]=P4 ** ** P4 is a pointer to a 64-bit floating point value. ** Write that value into register P2. */ case OP_Real: { /* same as TK_FLOAT, out2 */ pOut = out2Prerelease(p, pOp); pOut->flags = MEM_Real; assert( !sqlite3IsNaN(*pOp->p4.pReal) ); pOut->u.r = *pOp->p4.pReal; break; } #endif /* Opcode: String8 * P2 * P4 * ** Synopsis: r[P2]='P4' ** ** P4 points to a nul terminated UTF-8 string. This opcode is transformed ** into a String opcode before it is executed for the first time. During ** this transformation, the length of string P4 is computed and stored ** as the P1 parameter. */ case OP_String8: { /* same as TK_STRING, out2 */ assert( pOp->p4.z!=0 ); pOut = out2Prerelease(p, pOp); pOp->opcode = OP_String; pOp->p1 = sqlite3Strlen30(pOp->p4.z); #ifndef SQLITE_OMIT_UTF16 if( encoding!=SQLITE_UTF8 ){ rc = sqlite3VdbeMemSetStr(pOut, pOp->p4.z, -1, SQLITE_UTF8, SQLITE_STATIC); assert( rc==SQLITE_OK || rc==SQLITE_TOOBIG ); if( SQLITE_OK!=sqlite3VdbeChangeEncoding(pOut, encoding) ) goto no_mem; assert( pOut->szMalloc>0 && pOut->zMalloc==pOut->z ); assert( VdbeMemDynamic(pOut)==0 ); pOut->szMalloc = 0; pOut->flags |= MEM_Static; if( pOp->p4type==P4_DYNAMIC ){ sqlite3DbFree(db, pOp->p4.z); } pOp->p4type = P4_DYNAMIC; pOp->p4.z = pOut->z; pOp->p1 = pOut->n; } testcase( rc==SQLITE_TOOBIG ); #endif if( pOp->p1>db->aLimit[SQLITE_LIMIT_LENGTH] ){ goto too_big; } assert( rc==SQLITE_OK ); /* Fall through to the next case, OP_String */ } /* Opcode: String P1 P2 P3 P4 P5 ** Synopsis: r[P2]='P4' (len=P1) ** ** The string value P4 of length P1 (bytes) is stored in register P2. ** ** If P3 is not zero and the content of register P3 is equal to P5, then ** the datatype of the register P2 is converted to BLOB. The content is ** the same sequence of bytes, it is merely interpreted as a BLOB instead ** of a string, as if it had been CAST. In other words: ** ** if( P3!=0 and reg[P3]==P5 ) reg[P2] := CAST(reg[P2] as BLOB) */ case OP_String: { /* out2 */ assert( pOp->p4.z!=0 ); pOut = out2Prerelease(p, pOp); pOut->flags = MEM_Str|MEM_Static|MEM_Term; pOut->z = pOp->p4.z; pOut->n = pOp->p1; pOut->enc = encoding; UPDATE_MAX_BLOBSIZE(pOut); #ifndef SQLITE_LIKE_DOESNT_MATCH_BLOBS if( pOp->p3>0 ){ assert( pOp->p3<=(p->nMem+1 - p->nCursor) ); pIn3 = &aMem[pOp->p3]; assert( pIn3->flags & MEM_Int ); if( pIn3->u.i==pOp->p5 ) pOut->flags = MEM_Blob|MEM_Static|MEM_Term; } #endif break; } /* Opcode: Null P1 P2 P3 * * ** Synopsis: r[P2..P3]=NULL ** ** Write a NULL into registers P2. If P3 greater than P2, then also write ** NULL into register P3 and every register in between P2 and P3. If P3 ** is less than P2 (typically P3 is zero) then only register P2 is ** set to NULL. ** ** If the P1 value is non-zero, then also set the MEM_Cleared flag so that ** NULL values will not compare equal even if SQLITE_NULLEQ is set on ** OP_Ne or OP_Eq. */ case OP_Null: { /* out2 */ int cnt; u16 nullFlag; pOut = out2Prerelease(p, pOp); cnt = pOp->p3-pOp->p2; assert( pOp->p3<=(p->nMem+1 - p->nCursor) ); pOut->flags = nullFlag = pOp->p1 ? (MEM_Null|MEM_Cleared) : MEM_Null; pOut->n = 0; while( cnt>0 ){ pOut++; memAboutToChange(p, pOut); sqlite3VdbeMemSetNull(pOut); pOut->flags = nullFlag; pOut->n = 0; cnt--; } break; } /* Opcode: SoftNull P1 * * * * ** Synopsis: r[P1]=NULL ** ** Set register P1 to have the value NULL as seen by the OP_MakeRecord ** instruction, but do not free any string or blob memory associated with ** the register, so that if the value was a string or blob that was ** previously copied using OP_SCopy, the copies will continue to be valid. */ case OP_SoftNull: { assert( pOp->p1>0 && pOp->p1<=(p->nMem+1 - p->nCursor) ); pOut = &aMem[pOp->p1]; pOut->flags = (pOut->flags|MEM_Null)&~MEM_Undefined; break; } /* Opcode: Blob P1 P2 * P4 * ** Synopsis: r[P2]=P4 (len=P1) ** ** P4 points to a blob of data P1 bytes long. Store this ** blob in register P2. */ case OP_Blob: { /* out2 */ assert( pOp->p1 <= SQLITE_MAX_LENGTH ); pOut = out2Prerelease(p, pOp); sqlite3VdbeMemSetStr(pOut, pOp->p4.z, pOp->p1, 0, 0); pOut->enc = encoding; UPDATE_MAX_BLOBSIZE(pOut); break; } /* Opcode: Variable P1 P2 * P4 * ** Synopsis: r[P2]=parameter(P1,P4) ** ** Transfer the values of bound parameter P1 into register P2 ** ** If the parameter is named, then its name appears in P4. ** The P4 value is used by sqlite3_bind_parameter_name(). */ case OP_Variable: { /* out2 */ Mem *pVar; /* Value being transferred */ assert( pOp->p1>0 && pOp->p1<=p->nVar ); assert( pOp->p4.z==0 || pOp->p4.z==p->azVar[pOp->p1-1] ); pVar = &p->aVar[pOp->p1 - 1]; if( sqlite3VdbeMemTooBig(pVar) ){ goto too_big; } pOut = out2Prerelease(p, pOp); sqlite3VdbeMemShallowCopy(pOut, pVar, MEM_Static); UPDATE_MAX_BLOBSIZE(pOut); break; } /* Opcode: Move P1 P2 P3 * * ** Synopsis: r[P2@P3]=r[P1@P3] ** ** Move the P3 values in register P1..P1+P3-1 over into ** registers P2..P2+P3-1. Registers P1..P1+P3-1 are ** left holding a NULL. It is an error for register ranges ** P1..P1+P3-1 and P2..P2+P3-1 to overlap. It is an error ** for P3 to be less than 1. */ case OP_Move: { int n; /* Number of registers left to copy */ int p1; /* Register to copy from */ int p2; /* Register to copy to */ n = pOp->p3; p1 = pOp->p1; p2 = pOp->p2; assert( n>0 && p1>0 && p2>0 ); assert( p1+n<=p2 || p2+n<=p1 ); pIn1 = &aMem[p1]; pOut = &aMem[p2]; do{ assert( pOut<=&aMem[(p->nMem+1 - p->nCursor)] ); assert( pIn1<=&aMem[(p->nMem+1 - p->nCursor)] ); assert( memIsValid(pIn1) ); memAboutToChange(p, pOut); sqlite3VdbeMemMove(pOut, pIn1); #ifdef SQLITE_DEBUG if( pOut->pScopyFrom>=&aMem[p1] && pOut->pScopyFrompScopyFrom += pOp->p2 - p1; } #endif Deephemeralize(pOut); REGISTER_TRACE(p2++, pOut); pIn1++; pOut++; }while( --n ); break; } /* Opcode: Copy P1 P2 P3 * * ** Synopsis: r[P2@P3+1]=r[P1@P3+1] ** ** Make a copy of registers P1..P1+P3 into registers P2..P2+P3. ** ** This instruction makes a deep copy of the value. A duplicate ** is made of any string or blob constant. See also OP_SCopy. */ case OP_Copy: { int n; n = pOp->p3; pIn1 = &aMem[pOp->p1]; pOut = &aMem[pOp->p2]; assert( pOut!=pIn1 ); while( 1 ){ sqlite3VdbeMemShallowCopy(pOut, pIn1, MEM_Ephem); Deephemeralize(pOut); #ifdef SQLITE_DEBUG pOut->pScopyFrom = 0; #endif REGISTER_TRACE(pOp->p2+pOp->p3-n, pOut); if( (n--)==0 ) break; pOut++; pIn1++; } break; } /* Opcode: SCopy P1 P2 * * * ** Synopsis: r[P2]=r[P1] ** ** Make a shallow copy of register P1 into register P2. ** ** This instruction makes a shallow copy of the value. If the value ** is a string or blob, then the copy is only a pointer to the ** original and hence if the original changes so will the copy. ** Worse, if the original is deallocated, the copy becomes invalid. ** Thus the program must guarantee that the original will not change ** during the lifetime of the copy. Use OP_Copy to make a complete ** copy. */ case OP_SCopy: { /* out2 */ pIn1 = &aMem[pOp->p1]; pOut = &aMem[pOp->p2]; assert( pOut!=pIn1 ); sqlite3VdbeMemShallowCopy(pOut, pIn1, MEM_Ephem); #ifdef SQLITE_DEBUG if( pOut->pScopyFrom==0 ) pOut->pScopyFrom = pIn1; #endif break; } /* Opcode: IntCopy P1 P2 * * * ** Synopsis: r[P2]=r[P1] ** ** Transfer the integer value held in register P1 into register P2. ** ** This is an optimized version of SCopy that works only for integer ** values. */ case OP_IntCopy: { /* out2 */ pIn1 = &aMem[pOp->p1]; assert( (pIn1->flags & MEM_Int)!=0 ); pOut = &aMem[pOp->p2]; sqlite3VdbeMemSetInt64(pOut, pIn1->u.i); break; } /* Opcode: ResultRow P1 P2 * * * ** Synopsis: output=r[P1@P2] ** ** The registers P1 through P1+P2-1 contain a single row of ** results. This opcode causes the sqlite3_step() call to terminate ** with an SQLITE_ROW return code and it sets up the sqlite3_stmt ** structure to provide access to the r(P1)..r(P1+P2-1) values as ** the result row. */ case OP_ResultRow: { Mem *pMem; int i; assert( p->nResColumn==pOp->p2 ); assert( pOp->p1>0 ); assert( pOp->p1+pOp->p2<=(p->nMem+1 - p->nCursor)+1 ); #ifndef SQLITE_OMIT_PROGRESS_CALLBACK /* Run the progress counter just before returning. */ if( db->xProgress!=0 && nVmStep>=nProgressLimit && db->xProgress(db->pProgressArg)!=0 ){ rc = SQLITE_INTERRUPT; goto abort_due_to_error; } #endif /* If this statement has violated immediate foreign key constraints, do ** not return the number of rows modified. And do not RELEASE the statement ** transaction. It needs to be rolled back. */ if( SQLITE_OK!=(rc = sqlite3VdbeCheckFk(p, 0)) ){ assert( db->flags&SQLITE_CountRows ); assert( p->usesStmtJournal ); goto abort_due_to_error; } /* If the SQLITE_CountRows flag is set in sqlite3.flags mask, then ** DML statements invoke this opcode to return the number of rows ** modified to the user. This is the only way that a VM that ** opens a statement transaction may invoke this opcode. ** ** In case this is such a statement, close any statement transaction ** opened by this VM before returning control to the user. This is to ** ensure that statement-transactions are always nested, not overlapping. ** If the open statement-transaction is not closed here, then the user ** may step another VM that opens its own statement transaction. This ** may lead to overlapping statement transactions. ** ** The statement transaction is never a top-level transaction. Hence ** the RELEASE call below can never fail. */ assert( p->iStatement==0 || db->flags&SQLITE_CountRows ); rc = sqlite3VdbeCloseStatement(p, SAVEPOINT_RELEASE); assert( rc==SQLITE_OK ); /* Invalidate all ephemeral cursor row caches */ p->cacheCtr = (p->cacheCtr + 2)|1; /* Make sure the results of the current row are \000 terminated ** and have an assigned type. The results are de-ephemeralized as ** a side effect. */ pMem = p->pResultSet = &aMem[pOp->p1]; for(i=0; ip2; i++){ assert( memIsValid(&pMem[i]) ); Deephemeralize(&pMem[i]); assert( (pMem[i].flags & MEM_Ephem)==0 || (pMem[i].flags & (MEM_Str|MEM_Blob))==0 ); sqlite3VdbeMemNulTerminate(&pMem[i]); REGISTER_TRACE(pOp->p1+i, &pMem[i]); } if( db->mallocFailed ) goto no_mem; if( db->mTrace & SQLITE_TRACE_ROW ){ db->xTrace(SQLITE_TRACE_ROW, db->pTraceArg, p, 0); } /* Return SQLITE_ROW */ p->pc = (int)(pOp - aOp) + 1; rc = SQLITE_ROW; goto vdbe_return; } /* Opcode: Concat P1 P2 P3 * * ** Synopsis: r[P3]=r[P2]+r[P1] ** ** Add the text in register P1 onto the end of the text in ** register P2 and store the result in register P3. ** If either the P1 or P2 text are NULL then store NULL in P3. ** ** P3 = P2 || P1 ** ** It is illegal for P1 and P3 to be the same register. Sometimes, ** if P3 is the same register as P2, the implementation is able ** to avoid a memcpy(). */ case OP_Concat: { /* same as TK_CONCAT, in1, in2, out3 */ i64 nByte; pIn1 = &aMem[pOp->p1]; pIn2 = &aMem[pOp->p2]; pOut = &aMem[pOp->p3]; assert( pIn1!=pOut ); if( (pIn1->flags | pIn2->flags) & MEM_Null ){ sqlite3VdbeMemSetNull(pOut); break; } if( ExpandBlob(pIn1) || ExpandBlob(pIn2) ) goto no_mem; Stringify(pIn1, encoding); Stringify(pIn2, encoding); nByte = pIn1->n + pIn2->n; if( nByte>db->aLimit[SQLITE_LIMIT_LENGTH] ){ goto too_big; } if( sqlite3VdbeMemGrow(pOut, (int)nByte+2, pOut==pIn2) ){ goto no_mem; } MemSetTypeFlag(pOut, MEM_Str); if( pOut!=pIn2 ){ memcpy(pOut->z, pIn2->z, pIn2->n); } memcpy(&pOut->z[pIn2->n], pIn1->z, pIn1->n); pOut->z[nByte]=0; pOut->z[nByte+1] = 0; pOut->flags |= MEM_Term; pOut->n = (int)nByte; pOut->enc = encoding; UPDATE_MAX_BLOBSIZE(pOut); break; } /* Opcode: Add P1 P2 P3 * * ** Synopsis: r[P3]=r[P1]+r[P2] ** ** Add the value in register P1 to the value in register P2 ** and store the result in register P3. ** If either input is NULL, the result is NULL. */ /* Opcode: Multiply P1 P2 P3 * * ** Synopsis: r[P3]=r[P1]*r[P2] ** ** ** Multiply the value in register P1 by the value in register P2 ** and store the result in register P3. ** If either input is NULL, the result is NULL. */ /* Opcode: Subtract P1 P2 P3 * * ** Synopsis: r[P3]=r[P2]-r[P1] ** ** Subtract the value in register P1 from the value in register P2 ** and store the result in register P3. ** If either input is NULL, the result is NULL. */ /* Opcode: Divide P1 P2 P3 * * ** Synopsis: r[P3]=r[P2]/r[P1] ** ** Divide the value in register P1 by the value in register P2 ** and store the result in register P3 (P3=P2/P1). If the value in ** register P1 is zero, then the result is NULL. If either input is ** NULL, the result is NULL. */ /* Opcode: Remainder P1 P2 P3 * * ** Synopsis: r[P3]=r[P2]%r[P1] ** ** Compute the remainder after integer register P2 is divided by ** register P1 and store the result in register P3. ** If the value in register P1 is zero the result is NULL. ** If either operand is NULL, the result is NULL. */ case OP_Add: /* same as TK_PLUS, in1, in2, out3 */ case OP_Subtract: /* same as TK_MINUS, in1, in2, out3 */ case OP_Multiply: /* same as TK_STAR, in1, in2, out3 */ case OP_Divide: /* same as TK_SLASH, in1, in2, out3 */ case OP_Remainder: { /* same as TK_REM, in1, in2, out3 */ char bIntint; /* Started out as two integer operands */ u16 flags; /* Combined MEM_* flags from both inputs */ u16 type1; /* Numeric type of left operand */ u16 type2; /* Numeric type of right operand */ i64 iA; /* Integer value of left operand */ i64 iB; /* Integer value of right operand */ double rA; /* Real value of left operand */ double rB; /* Real value of right operand */ pIn1 = &aMem[pOp->p1]; type1 = numericType(pIn1); pIn2 = &aMem[pOp->p2]; type2 = numericType(pIn2); pOut = &aMem[pOp->p3]; flags = pIn1->flags | pIn2->flags; if( (flags & MEM_Null)!=0 ) goto arithmetic_result_is_null; if( (type1 & type2 & MEM_Int)!=0 ){ iA = pIn1->u.i; iB = pIn2->u.i; bIntint = 1; switch( pOp->opcode ){ case OP_Add: if( sqlite3AddInt64(&iB,iA) ) goto fp_math; break; case OP_Subtract: if( sqlite3SubInt64(&iB,iA) ) goto fp_math; break; case OP_Multiply: if( sqlite3MulInt64(&iB,iA) ) goto fp_math; break; case OP_Divide: { if( iA==0 ) goto arithmetic_result_is_null; if( iA==-1 && iB==SMALLEST_INT64 ) goto fp_math; iB /= iA; break; } default: { if( iA==0 ) goto arithmetic_result_is_null; if( iA==-1 ) iA = 1; iB %= iA; break; } } pOut->u.i = iB; MemSetTypeFlag(pOut, MEM_Int); }else{ bIntint = 0; fp_math: rA = sqlite3VdbeRealValue(pIn1); rB = sqlite3VdbeRealValue(pIn2); switch( pOp->opcode ){ case OP_Add: rB += rA; break; case OP_Subtract: rB -= rA; break; case OP_Multiply: rB *= rA; break; case OP_Divide: { /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */ if( rA==(double)0 ) goto arithmetic_result_is_null; rB /= rA; break; } default: { iA = (i64)rA; iB = (i64)rB; if( iA==0 ) goto arithmetic_result_is_null; if( iA==-1 ) iA = 1; rB = (double)(iB % iA); break; } } #ifdef SQLITE_OMIT_FLOATING_POINT pOut->u.i = rB; MemSetTypeFlag(pOut, MEM_Int); #else if( sqlite3IsNaN(rB) ){ goto arithmetic_result_is_null; } pOut->u.r = rB; MemSetTypeFlag(pOut, MEM_Real); if( ((type1|type2)&MEM_Real)==0 && !bIntint ){ sqlite3VdbeIntegerAffinity(pOut); } #endif } break; arithmetic_result_is_null: sqlite3VdbeMemSetNull(pOut); break; } /* Opcode: CollSeq P1 * * P4 ** ** P4 is a pointer to a CollSeq struct. If the next call to a user function ** or aggregate calls sqlite3GetFuncCollSeq(), this collation sequence will ** be returned. This is used by the built-in min(), max() and nullif() ** functions. ** ** If P1 is not zero, then it is a register that a subsequent min() or ** max() aggregate will set to 1 if the current row is not the minimum or ** maximum. The P1 register is initialized to 0 by this instruction. ** ** The interface used by the implementation of the aforementioned functions ** to retrieve the collation sequence set by this opcode is not available ** publicly. Only built-in functions have access to this feature. */ case OP_CollSeq: { assert( pOp->p4type==P4_COLLSEQ ); if( pOp->p1 ){ sqlite3VdbeMemSetInt64(&aMem[pOp->p1], 0); } break; } /* Opcode: Function0 P1 P2 P3 P4 P5 ** Synopsis: r[P3]=func(r[P2@P5]) ** ** Invoke a user function (P4 is a pointer to a FuncDef object that ** defines the function) with P5 arguments taken from register P2 and ** successors. The result of the function is stored in register P3. ** Register P3 must not be one of the function inputs. ** ** P1 is a 32-bit bitmask indicating whether or not each argument to the ** function was determined to be constant at compile time. If the first ** argument was constant then bit 0 of P1 is set. This is used to determine ** whether meta data associated with a user function argument using the ** sqlite3_set_auxdata() API may be safely retained until the next ** invocation of this opcode. ** ** See also: Function, AggStep, AggFinal */ /* Opcode: Function P1 P2 P3 P4 P5 ** Synopsis: r[P3]=func(r[P2@P5]) ** ** Invoke a user function (P4 is a pointer to an sqlite3_context object that ** contains a pointer to the function to be run) with P5 arguments taken ** from register P2 and successors. The result of the function is stored ** in register P3. Register P3 must not be one of the function inputs. ** ** P1 is a 32-bit bitmask indicating whether or not each argument to the ** function was determined to be constant at compile time. If the first ** argument was constant then bit 0 of P1 is set. This is used to determine ** whether meta data associated with a user function argument using the ** sqlite3_set_auxdata() API may be safely retained until the next ** invocation of this opcode. ** ** SQL functions are initially coded as OP_Function0 with P4 pointing ** to a FuncDef object. But on first evaluation, the P4 operand is ** automatically converted into an sqlite3_context object and the operation ** changed to this OP_Function opcode. In this way, the initialization of ** the sqlite3_context object occurs only once, rather than once for each ** evaluation of the function. ** ** See also: Function0, AggStep, AggFinal */ case OP_Function0: { int n; sqlite3_context *pCtx; assert( pOp->p4type==P4_FUNCDEF ); n = pOp->p5; assert( pOp->p3>0 && pOp->p3<=(p->nMem+1 - p->nCursor) ); assert( n==0 || (pOp->p2>0 && pOp->p2+n<=(p->nMem+1 - p->nCursor)+1) ); assert( pOp->p3p2 || pOp->p3>=pOp->p2+n ); pCtx = sqlite3DbMallocRawNN(db, sizeof(*pCtx) + (n-1)*sizeof(sqlite3_value*)); if( pCtx==0 ) goto no_mem; pCtx->pOut = 0; pCtx->pFunc = pOp->p4.pFunc; pCtx->iOp = (int)(pOp - aOp); pCtx->pVdbe = p; pCtx->argc = n; pOp->p4type = P4_FUNCCTX; pOp->p4.pCtx = pCtx; pOp->opcode = OP_Function; /* Fall through into OP_Function */ } case OP_Function: { int i; sqlite3_context *pCtx; assert( pOp->p4type==P4_FUNCCTX ); pCtx = pOp->p4.pCtx; /* If this function is inside of a trigger, the register array in aMem[] ** might change from one evaluation to the next. The next block of code ** checks to see if the register array has changed, and if so it ** reinitializes the relavant parts of the sqlite3_context object */ pOut = &aMem[pOp->p3]; if( pCtx->pOut != pOut ){ pCtx->pOut = pOut; for(i=pCtx->argc-1; i>=0; i--) pCtx->argv[i] = &aMem[pOp->p2+i]; } memAboutToChange(p, pCtx->pOut); #ifdef SQLITE_DEBUG for(i=0; iargc; i++){ assert( memIsValid(pCtx->argv[i]) ); REGISTER_TRACE(pOp->p2+i, pCtx->argv[i]); } #endif MemSetTypeFlag(pCtx->pOut, MEM_Null); pCtx->fErrorOrAux = 0; db->lastRowid = lastRowid; (*pCtx->pFunc->xSFunc)(pCtx, pCtx->argc, pCtx->argv);/* IMP: R-24505-23230 */ lastRowid = db->lastRowid; /* Remember rowid changes made by xSFunc */ /* If the function returned an error, throw an exception */ if( pCtx->fErrorOrAux ){ if( pCtx->isError ){ sqlite3VdbeError(p, "%s", sqlite3_value_text(pCtx->pOut)); rc = pCtx->isError; } sqlite3VdbeDeleteAuxData(db, &p->pAuxData, pCtx->iOp, pOp->p1); if( rc ) goto abort_due_to_error; } /* Copy the result of the function into register P3 */ if( pOut->flags & (MEM_Str|MEM_Blob) ){ sqlite3VdbeChangeEncoding(pCtx->pOut, encoding); if( sqlite3VdbeMemTooBig(pCtx->pOut) ) goto too_big; } REGISTER_TRACE(pOp->p3, pCtx->pOut); UPDATE_MAX_BLOBSIZE(pCtx->pOut); break; } /* Opcode: BitAnd P1 P2 P3 * * ** Synopsis: r[P3]=r[P1]&r[P2] ** ** Take the bit-wise AND of the values in register P1 and P2 and ** store the result in register P3. ** If either input is NULL, the result is NULL. */ /* Opcode: BitOr P1 P2 P3 * * ** Synopsis: r[P3]=r[P1]|r[P2] ** ** Take the bit-wise OR of the values in register P1 and P2 and ** store the result in register P3. ** If either input is NULL, the result is NULL. */ /* Opcode: ShiftLeft P1 P2 P3 * * ** Synopsis: r[P3]=r[P2]<>r[P1] ** ** Shift the integer value in register P2 to the right by the ** number of bits specified by the integer in register P1. ** Store the result in register P3. ** If either input is NULL, the result is NULL. */ case OP_BitAnd: /* same as TK_BITAND, in1, in2, out3 */ case OP_BitOr: /* same as TK_BITOR, in1, in2, out3 */ case OP_ShiftLeft: /* same as TK_LSHIFT, in1, in2, out3 */ case OP_ShiftRight: { /* same as TK_RSHIFT, in1, in2, out3 */ i64 iA; u64 uA; i64 iB; u8 op; pIn1 = &aMem[pOp->p1]; pIn2 = &aMem[pOp->p2]; pOut = &aMem[pOp->p3]; if( (pIn1->flags | pIn2->flags) & MEM_Null ){ sqlite3VdbeMemSetNull(pOut); break; } iA = sqlite3VdbeIntValue(pIn2); iB = sqlite3VdbeIntValue(pIn1); op = pOp->opcode; if( op==OP_BitAnd ){ iA &= iB; }else if( op==OP_BitOr ){ iA |= iB; }else if( iB!=0 ){ assert( op==OP_ShiftRight || op==OP_ShiftLeft ); /* If shifting by a negative amount, shift in the other direction */ if( iB<0 ){ assert( OP_ShiftRight==OP_ShiftLeft+1 ); op = 2*OP_ShiftLeft + 1 - op; iB = iB>(-64) ? -iB : 64; } if( iB>=64 ){ iA = (iA>=0 || op==OP_ShiftLeft) ? 0 : -1; }else{ memcpy(&uA, &iA, sizeof(uA)); if( op==OP_ShiftLeft ){ uA <<= iB; }else{ uA >>= iB; /* Sign-extend on a right shift of a negative number */ if( iA<0 ) uA |= ((((u64)0xffffffff)<<32)|0xffffffff) << (64-iB); } memcpy(&iA, &uA, sizeof(iA)); } } pOut->u.i = iA; MemSetTypeFlag(pOut, MEM_Int); break; } /* Opcode: AddImm P1 P2 * * * ** Synopsis: r[P1]=r[P1]+P2 ** ** Add the constant P2 to the value in register P1. ** The result is always an integer. ** ** To force any register to be an integer, just add 0. */ case OP_AddImm: { /* in1 */ pIn1 = &aMem[pOp->p1]; memAboutToChange(p, pIn1); sqlite3VdbeMemIntegerify(pIn1); pIn1->u.i += pOp->p2; break; } /* Opcode: MustBeInt P1 P2 * * * ** ** Force the value in register P1 to be an integer. If the value ** in P1 is not an integer and cannot be converted into an integer ** without data loss, then jump immediately to P2, or if P2==0 ** raise an SQLITE_MISMATCH exception. */ case OP_MustBeInt: { /* jump, in1 */ pIn1 = &aMem[pOp->p1]; if( (pIn1->flags & MEM_Int)==0 ){ applyAffinity(pIn1, SQLITE_AFF_NUMERIC, encoding); VdbeBranchTaken((pIn1->flags&MEM_Int)==0, 2); if( (pIn1->flags & MEM_Int)==0 ){ if( pOp->p2==0 ){ rc = SQLITE_MISMATCH; goto abort_due_to_error; }else{ goto jump_to_p2; } } } MemSetTypeFlag(pIn1, MEM_Int); break; } #ifndef SQLITE_OMIT_FLOATING_POINT /* Opcode: RealAffinity P1 * * * * ** ** If register P1 holds an integer convert it to a real value. ** ** This opcode is used when extracting information from a column that ** has REAL affinity. Such column values may still be stored as ** integers, for space efficiency, but after extraction we want them ** to have only a real value. */ case OP_RealAffinity: { /* in1 */ pIn1 = &aMem[pOp->p1]; if( pIn1->flags & MEM_Int ){ sqlite3VdbeMemRealify(pIn1); } break; } #endif #ifndef SQLITE_OMIT_CAST /* Opcode: Cast P1 P2 * * * ** Synopsis: affinity(r[P1]) ** ** Force the value in register P1 to be the type defined by P2. ** **
      **
    • TEXT **
    • BLOB **
    • NUMERIC **
    • INTEGER **
    • REAL **
    ** ** A NULL value is not changed by this routine. It remains NULL. */ case OP_Cast: { /* in1 */ assert( pOp->p2>=SQLITE_AFF_BLOB && pOp->p2<=SQLITE_AFF_REAL ); testcase( pOp->p2==SQLITE_AFF_TEXT ); testcase( pOp->p2==SQLITE_AFF_BLOB ); testcase( pOp->p2==SQLITE_AFF_NUMERIC ); testcase( pOp->p2==SQLITE_AFF_INTEGER ); testcase( pOp->p2==SQLITE_AFF_REAL ); pIn1 = &aMem[pOp->p1]; memAboutToChange(p, pIn1); rc = ExpandBlob(pIn1); sqlite3VdbeMemCast(pIn1, pOp->p2, encoding); UPDATE_MAX_BLOBSIZE(pIn1); if( rc ) goto abort_due_to_error; break; } #endif /* SQLITE_OMIT_CAST */ /* Opcode: Eq P1 P2 P3 P4 P5 ** Synopsis: IF r[P3]==r[P1] ** ** Compare the values in register P1 and P3. If reg(P3)==reg(P1) then ** jump to address P2. Or if the SQLITE_STOREP2 flag is set in P5, then ** store the result of comparison in register P2. ** ** The SQLITE_AFF_MASK portion of P5 must be an affinity character - ** SQLITE_AFF_TEXT, SQLITE_AFF_INTEGER, and so forth. An attempt is made ** to coerce both inputs according to this affinity before the ** comparison is made. If the SQLITE_AFF_MASK is 0x00, then numeric ** affinity is used. Note that the affinity conversions are stored ** back into the input registers P1 and P3. So this opcode can cause ** persistent changes to registers P1 and P3. ** ** Once any conversions have taken place, and neither value is NULL, ** the values are compared. If both values are blobs then memcmp() is ** used to determine the results of the comparison. If both values ** are text, then the appropriate collating function specified in ** P4 is used to do the comparison. If P4 is not specified then ** memcmp() is used to compare text string. If both values are ** numeric, then a numeric comparison is used. If the two values ** are of different types, then numbers are considered less than ** strings and strings are considered less than blobs. ** ** If SQLITE_NULLEQ is set in P5 then the result of comparison is always either ** true or false and is never NULL. If both operands are NULL then the result ** of comparison is true. If either operand is NULL then the result is false. ** If neither operand is NULL the result is the same as it would be if ** the SQLITE_NULLEQ flag were omitted from P5. ** ** If both SQLITE_STOREP2 and SQLITE_KEEPNULL flags are set then the ** content of r[P2] is only changed if the new value is NULL or 0 (false). ** In other words, a prior r[P2] value will not be overwritten by 1 (true). */ /* Opcode: Ne P1 P2 P3 P4 P5 ** Synopsis: IF r[P3]!=r[P1] ** ** This works just like the Eq opcode except that the jump is taken if ** the operands in registers P1 and P3 are not equal. See the Eq opcode for ** additional information. ** ** If both SQLITE_STOREP2 and SQLITE_KEEPNULL flags are set then the ** content of r[P2] is only changed if the new value is NULL or 1 (true). ** In other words, a prior r[P2] value will not be overwritten by 0 (false). */ /* Opcode: Lt P1 P2 P3 P4 P5 ** Synopsis: IF r[P3]r[P1] ** ** This works just like the Lt opcode except that the jump is taken if ** the content of register P3 is greater than the content of ** register P1. See the Lt opcode for additional information. */ /* Opcode: Ge P1 P2 P3 P4 P5 ** Synopsis: IF r[P3]>=r[P1] ** ** This works just like the Lt opcode except that the jump is taken if ** the content of register P3 is greater than or equal to the content of ** register P1. See the Lt opcode for additional information. */ case OP_Eq: /* same as TK_EQ, jump, in1, in3 */ case OP_Ne: /* same as TK_NE, jump, in1, in3 */ case OP_Lt: /* same as TK_LT, jump, in1, in3 */ case OP_Le: /* same as TK_LE, jump, in1, in3 */ case OP_Gt: /* same as TK_GT, jump, in1, in3 */ case OP_Ge: { /* same as TK_GE, jump, in1, in3 */ int res, res2; /* Result of the comparison of pIn1 against pIn3 */ char affinity; /* Affinity to use for comparison */ u16 flags1; /* Copy of initial value of pIn1->flags */ u16 flags3; /* Copy of initial value of pIn3->flags */ pIn1 = &aMem[pOp->p1]; pIn3 = &aMem[pOp->p3]; flags1 = pIn1->flags; flags3 = pIn3->flags; if( (flags1 | flags3)&MEM_Null ){ /* One or both operands are NULL */ if( pOp->p5 & SQLITE_NULLEQ ){ /* If SQLITE_NULLEQ is set (which will only happen if the operator is ** OP_Eq or OP_Ne) then take the jump or not depending on whether ** or not both operands are null. */ assert( pOp->opcode==OP_Eq || pOp->opcode==OP_Ne ); assert( (flags1 & MEM_Cleared)==0 ); assert( (pOp->p5 & SQLITE_JUMPIFNULL)==0 ); if( (flags1&MEM_Null)!=0 && (flags3&MEM_Null)!=0 && (flags3&MEM_Cleared)==0 ){ res = 0; /* Operands are equal */ }else{ res = 1; /* Operands are not equal */ } }else{ /* SQLITE_NULLEQ is clear and at least one operand is NULL, ** then the result is always NULL. ** The jump is taken if the SQLITE_JUMPIFNULL bit is set. */ if( pOp->p5 & SQLITE_STOREP2 ){ pOut = &aMem[pOp->p2]; iCompare = 1; /* Operands are not equal */ memAboutToChange(p, pOut); MemSetTypeFlag(pOut, MEM_Null); REGISTER_TRACE(pOp->p2, pOut); }else{ VdbeBranchTaken(2,3); if( pOp->p5 & SQLITE_JUMPIFNULL ){ goto jump_to_p2; } } break; } }else{ /* Neither operand is NULL. Do a comparison. */ affinity = pOp->p5 & SQLITE_AFF_MASK; if( affinity>=SQLITE_AFF_NUMERIC ){ if( (flags1 | flags3)&MEM_Str ){ if( (flags1 & (MEM_Int|MEM_Real|MEM_Str))==MEM_Str ){ applyNumericAffinity(pIn1,0); testcase( flags3!=pIn3->flags ); /* Possible if pIn1==pIn3 */ flags3 = pIn3->flags; } if( (flags3 & (MEM_Int|MEM_Real|MEM_Str))==MEM_Str ){ applyNumericAffinity(pIn3,0); } } /* Handle the common case of integer comparison here, as an ** optimization, to avoid a call to sqlite3MemCompare() */ if( (pIn1->flags & pIn3->flags & MEM_Int)!=0 ){ if( pIn3->u.i > pIn1->u.i ){ res = +1; goto compare_op; } if( pIn3->u.i < pIn1->u.i ){ res = -1; goto compare_op; } res = 0; goto compare_op; } }else if( affinity==SQLITE_AFF_TEXT ){ if( (flags1 & MEM_Str)==0 && (flags1 & (MEM_Int|MEM_Real))!=0 ){ testcase( pIn1->flags & MEM_Int ); testcase( pIn1->flags & MEM_Real ); sqlite3VdbeMemStringify(pIn1, encoding, 1); testcase( (flags1&MEM_Dyn) != (pIn1->flags&MEM_Dyn) ); flags1 = (pIn1->flags & ~MEM_TypeMask) | (flags1 & MEM_TypeMask); assert( pIn1!=pIn3 ); } if( (flags3 & MEM_Str)==0 && (flags3 & (MEM_Int|MEM_Real))!=0 ){ testcase( pIn3->flags & MEM_Int ); testcase( pIn3->flags & MEM_Real ); sqlite3VdbeMemStringify(pIn3, encoding, 1); testcase( (flags3&MEM_Dyn) != (pIn3->flags&MEM_Dyn) ); flags3 = (pIn3->flags & ~MEM_TypeMask) | (flags3 & MEM_TypeMask); } } assert( pOp->p4type==P4_COLLSEQ || pOp->p4.pColl==0 ); res = sqlite3MemCompare(pIn3, pIn1, pOp->p4.pColl); } compare_op: switch( pOp->opcode ){ case OP_Eq: res2 = res==0; break; case OP_Ne: res2 = res; break; case OP_Lt: res2 = res<0; break; case OP_Le: res2 = res<=0; break; case OP_Gt: res2 = res>0; break; default: res2 = res>=0; break; } /* Undo any changes made by applyAffinity() to the input registers. */ assert( (pIn1->flags & MEM_Dyn) == (flags1 & MEM_Dyn) ); pIn1->flags = flags1; assert( (pIn3->flags & MEM_Dyn) == (flags3 & MEM_Dyn) ); pIn3->flags = flags3; if( pOp->p5 & SQLITE_STOREP2 ){ pOut = &aMem[pOp->p2]; iCompare = res; res2 = res2!=0; /* For this path res2 must be exactly 0 or 1 */ if( (pOp->p5 & SQLITE_KEEPNULL)!=0 ){ /* The KEEPNULL flag prevents OP_Eq from overwriting a NULL with 1 ** and prevents OP_Ne from overwriting NULL with 0. This flag ** is only used in contexts where either: ** (1) op==OP_Eq && (r[P2]==NULL || r[P2]==0) ** (2) op==OP_Ne && (r[P2]==NULL || r[P2]==1) ** Therefore it is not necessary to check the content of r[P2] for ** NULL. */ assert( pOp->opcode==OP_Ne || pOp->opcode==OP_Eq ); assert( res2==0 || res2==1 ); testcase( res2==0 && pOp->opcode==OP_Eq ); testcase( res2==1 && pOp->opcode==OP_Eq ); testcase( res2==0 && pOp->opcode==OP_Ne ); testcase( res2==1 && pOp->opcode==OP_Ne ); if( (pOp->opcode==OP_Eq)==res2 ) break; } memAboutToChange(p, pOut); MemSetTypeFlag(pOut, MEM_Int); pOut->u.i = res2; REGISTER_TRACE(pOp->p2, pOut); }else{ VdbeBranchTaken(res!=0, (pOp->p5 & SQLITE_NULLEQ)?2:3); if( res2 ){ goto jump_to_p2; } } break; } /* Opcode: ElseNotEq * P2 * * * ** ** This opcode must immediately follow an OP_Lt or OP_Gt comparison operator. ** If result of an OP_Eq comparison on the same two operands ** would have be NULL or false (0), then then jump to P2. ** If the result of an OP_Eq comparison on the two previous operands ** would have been true (1), then fall through. */ case OP_ElseNotEq: { /* same as TK_ESCAPE, jump */ assert( pOp>aOp ); assert( pOp[-1].opcode==OP_Lt || pOp[-1].opcode==OP_Gt ); assert( pOp[-1].p5 & SQLITE_STOREP2 ); VdbeBranchTaken(iCompare!=0, 2); if( iCompare!=0 ) goto jump_to_p2; break; } /* Opcode: Permutation * * * P4 * ** ** Set the permutation used by the OP_Compare operator to be the array ** of integers in P4. ** ** The permutation is only valid until the next OP_Compare that has ** the OPFLAG_PERMUTE bit set in P5. Typically the OP_Permutation should ** occur immediately prior to the OP_Compare. ** ** The first integer in the P4 integer array is the length of the array ** and does not become part of the permutation. */ case OP_Permutation: { assert( pOp->p4type==P4_INTARRAY ); assert( pOp->p4.ai ); aPermute = pOp->p4.ai + 1; break; } /* Opcode: Compare P1 P2 P3 P4 P5 ** Synopsis: r[P1@P3] <-> r[P2@P3] ** ** Compare two vectors of registers in reg(P1)..reg(P1+P3-1) (call this ** vector "A") and in reg(P2)..reg(P2+P3-1) ("B"). Save the result of ** the comparison for use by the next OP_Jump instruct. ** ** If P5 has the OPFLAG_PERMUTE bit set, then the order of comparison is ** determined by the most recent OP_Permutation operator. If the ** OPFLAG_PERMUTE bit is clear, then register are compared in sequential ** order. ** ** P4 is a KeyInfo structure that defines collating sequences and sort ** orders for the comparison. The permutation applies to registers ** only. The KeyInfo elements are used sequentially. ** ** The comparison is a sort comparison, so NULLs compare equal, ** NULLs are less than numbers, numbers are less than strings, ** and strings are less than blobs. */ case OP_Compare: { int n; int i; int p1; int p2; const KeyInfo *pKeyInfo; int idx; CollSeq *pColl; /* Collating sequence to use on this term */ int bRev; /* True for DESCENDING sort order */ if( (pOp->p5 & OPFLAG_PERMUTE)==0 ) aPermute = 0; n = pOp->p3; pKeyInfo = pOp->p4.pKeyInfo; assert( n>0 ); assert( pKeyInfo!=0 ); p1 = pOp->p1; p2 = pOp->p2; #if SQLITE_DEBUG if( aPermute ){ int k, mx = 0; for(k=0; kmx ) mx = aPermute[k]; assert( p1>0 && p1+mx<=(p->nMem+1 - p->nCursor)+1 ); assert( p2>0 && p2+mx<=(p->nMem+1 - p->nCursor)+1 ); }else{ assert( p1>0 && p1+n<=(p->nMem+1 - p->nCursor)+1 ); assert( p2>0 && p2+n<=(p->nMem+1 - p->nCursor)+1 ); } #endif /* SQLITE_DEBUG */ for(i=0; inField ); pColl = pKeyInfo->aColl[i]; bRev = pKeyInfo->aSortOrder[i]; iCompare = sqlite3MemCompare(&aMem[p1+idx], &aMem[p2+idx], pColl); if( iCompare ){ if( bRev ) iCompare = -iCompare; break; } } aPermute = 0; break; } /* Opcode: Jump P1 P2 P3 * * ** ** Jump to the instruction at address P1, P2, or P3 depending on whether ** in the most recent OP_Compare instruction the P1 vector was less than ** equal to, or greater than the P2 vector, respectively. */ case OP_Jump: { /* jump */ if( iCompare<0 ){ VdbeBranchTaken(0,3); pOp = &aOp[pOp->p1 - 1]; }else if( iCompare==0 ){ VdbeBranchTaken(1,3); pOp = &aOp[pOp->p2 - 1]; }else{ VdbeBranchTaken(2,3); pOp = &aOp[pOp->p3 - 1]; } break; } /* Opcode: And P1 P2 P3 * * ** Synopsis: r[P3]=(r[P1] && r[P2]) ** ** Take the logical AND of the values in registers P1 and P2 and ** write the result into register P3. ** ** If either P1 or P2 is 0 (false) then the result is 0 even if ** the other input is NULL. A NULL and true or two NULLs give ** a NULL output. */ /* Opcode: Or P1 P2 P3 * * ** Synopsis: r[P3]=(r[P1] || r[P2]) ** ** Take the logical OR of the values in register P1 and P2 and ** store the answer in register P3. ** ** If either P1 or P2 is nonzero (true) then the result is 1 (true) ** even if the other input is NULL. A NULL and false or two NULLs ** give a NULL output. */ case OP_And: /* same as TK_AND, in1, in2, out3 */ case OP_Or: { /* same as TK_OR, in1, in2, out3 */ int v1; /* Left operand: 0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */ int v2; /* Right operand: 0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */ pIn1 = &aMem[pOp->p1]; if( pIn1->flags & MEM_Null ){ v1 = 2; }else{ v1 = sqlite3VdbeIntValue(pIn1)!=0; } pIn2 = &aMem[pOp->p2]; if( pIn2->flags & MEM_Null ){ v2 = 2; }else{ v2 = sqlite3VdbeIntValue(pIn2)!=0; } if( pOp->opcode==OP_And ){ static const unsigned char and_logic[] = { 0, 0, 0, 0, 1, 2, 0, 2, 2 }; v1 = and_logic[v1*3+v2]; }else{ static const unsigned char or_logic[] = { 0, 1, 2, 1, 1, 1, 2, 1, 2 }; v1 = or_logic[v1*3+v2]; } pOut = &aMem[pOp->p3]; if( v1==2 ){ MemSetTypeFlag(pOut, MEM_Null); }else{ pOut->u.i = v1; MemSetTypeFlag(pOut, MEM_Int); } break; } /* Opcode: Not P1 P2 * * * ** Synopsis: r[P2]= !r[P1] ** ** Interpret the value in register P1 as a boolean value. Store the ** boolean complement in register P2. If the value in register P1 is ** NULL, then a NULL is stored in P2. */ case OP_Not: { /* same as TK_NOT, in1, out2 */ pIn1 = &aMem[pOp->p1]; pOut = &aMem[pOp->p2]; sqlite3VdbeMemSetNull(pOut); if( (pIn1->flags & MEM_Null)==0 ){ pOut->flags = MEM_Int; pOut->u.i = !sqlite3VdbeIntValue(pIn1); } break; } /* Opcode: BitNot P1 P2 * * * ** Synopsis: r[P1]= ~r[P1] ** ** Interpret the content of register P1 as an integer. Store the ** ones-complement of the P1 value into register P2. If P1 holds ** a NULL then store a NULL in P2. */ case OP_BitNot: { /* same as TK_BITNOT, in1, out2 */ pIn1 = &aMem[pOp->p1]; pOut = &aMem[pOp->p2]; sqlite3VdbeMemSetNull(pOut); if( (pIn1->flags & MEM_Null)==0 ){ pOut->flags = MEM_Int; pOut->u.i = ~sqlite3VdbeIntValue(pIn1); } break; } /* Opcode: Once P1 P2 * * * ** ** If the P1 value is equal to the P1 value on the OP_Init opcode at ** instruction 0, then jump to P2. If the two P1 values differ, then ** set the P1 value on this opcode to equal the P1 value on the OP_Init ** and fall through. */ case OP_Once: { /* jump */ assert( p->aOp[0].opcode==OP_Init ); VdbeBranchTaken(p->aOp[0].p1==pOp->p1, 2); if( p->aOp[0].p1==pOp->p1 ){ goto jump_to_p2; }else{ pOp->p1 = p->aOp[0].p1; } break; } /* Opcode: If P1 P2 P3 * * ** ** Jump to P2 if the value in register P1 is true. The value ** is considered true if it is numeric and non-zero. If the value ** in P1 is NULL then take the jump if and only if P3 is non-zero. */ /* Opcode: IfNot P1 P2 P3 * * ** ** Jump to P2 if the value in register P1 is False. The value ** is considered false if it has a numeric value of zero. If the value ** in P1 is NULL then take the jump if and only if P3 is non-zero. */ case OP_If: /* jump, in1 */ case OP_IfNot: { /* jump, in1 */ int c; pIn1 = &aMem[pOp->p1]; if( pIn1->flags & MEM_Null ){ c = pOp->p3; }else{ #ifdef SQLITE_OMIT_FLOATING_POINT c = sqlite3VdbeIntValue(pIn1)!=0; #else c = sqlite3VdbeRealValue(pIn1)!=0.0; #endif if( pOp->opcode==OP_IfNot ) c = !c; } VdbeBranchTaken(c!=0, 2); if( c ){ goto jump_to_p2; } break; } /* Opcode: IsNull P1 P2 * * * ** Synopsis: if r[P1]==NULL goto P2 ** ** Jump to P2 if the value in register P1 is NULL. */ case OP_IsNull: { /* same as TK_ISNULL, jump, in1 */ pIn1 = &aMem[pOp->p1]; VdbeBranchTaken( (pIn1->flags & MEM_Null)!=0, 2); if( (pIn1->flags & MEM_Null)!=0 ){ goto jump_to_p2; } break; } /* Opcode: NotNull P1 P2 * * * ** Synopsis: if r[P1]!=NULL goto P2 ** ** Jump to P2 if the value in register P1 is not NULL. */ case OP_NotNull: { /* same as TK_NOTNULL, jump, in1 */ pIn1 = &aMem[pOp->p1]; VdbeBranchTaken( (pIn1->flags & MEM_Null)==0, 2); if( (pIn1->flags & MEM_Null)==0 ){ goto jump_to_p2; } break; } /* Opcode: Column P1 P2 P3 P4 P5 ** Synopsis: r[P3]=PX ** ** Interpret the data that cursor P1 points to as a structure built using ** the MakeRecord instruction. (See the MakeRecord opcode for additional ** information about the format of the data.) Extract the P2-th column ** from this record. If there are less that (P2+1) ** values in the record, extract a NULL. ** ** The value extracted is stored in register P3. ** ** If the column contains fewer than P2 fields, then extract a NULL. Or, ** if the P4 argument is a P4_MEM use the value of the P4 argument as ** the result. ** ** If the OPFLAG_CLEARCACHE bit is set on P5 and P1 is a pseudo-table cursor, ** then the cache of the cursor is reset prior to extracting the column. ** The first OP_Column against a pseudo-table after the value of the content ** register has changed should have this bit set. ** ** If the OPFLAG_LENGTHARG and OPFLAG_TYPEOFARG bits are set on P5 when ** the result is guaranteed to only be used as the argument of a length() ** or typeof() function, respectively. The loading of large blobs can be ** skipped for length() and all content loading can be skipped for typeof(). */ case OP_Column: { int p2; /* column number to retrieve */ VdbeCursor *pC; /* The VDBE cursor */ BtCursor *pCrsr; /* The BTree cursor */ u32 *aOffset; /* aOffset[i] is offset to start of data for i-th column */ int len; /* The length of the serialized data for the column */ int i; /* Loop counter */ Mem *pDest; /* Where to write the extracted value */ Mem sMem; /* For storing the record being decoded */ const u8 *zData; /* Part of the record being decoded */ const u8 *zHdr; /* Next unparsed byte of the header */ const u8 *zEndHdr; /* Pointer to first byte after the header */ u32 offset; /* Offset into the data */ u64 offset64; /* 64-bit offset */ u32 avail; /* Number of bytes of available data */ u32 t; /* A type code from the record header */ Mem *pReg; /* PseudoTable input register */ pC = p->apCsr[pOp->p1]; p2 = pOp->p2; /* If the cursor cache is stale, bring it up-to-date */ rc = sqlite3VdbeCursorMoveto(&pC, &p2); if( rc ) goto abort_due_to_error; assert( pOp->p3>0 && pOp->p3<=(p->nMem+1 - p->nCursor) ); pDest = &aMem[pOp->p3]; memAboutToChange(p, pDest); assert( pOp->p1>=0 && pOp->p1nCursor ); assert( pC!=0 ); assert( p2nField ); aOffset = pC->aOffset; assert( pC->eCurType!=CURTYPE_VTAB ); assert( pC->eCurType!=CURTYPE_PSEUDO || pC->nullRow ); assert( pC->eCurType!=CURTYPE_SORTER ); pCrsr = pC->uc.pCursor; if( pC->cacheStatus!=p->cacheCtr ){ /*OPTIMIZATION-IF-FALSE*/ if( pC->nullRow ){ if( pC->eCurType==CURTYPE_PSEUDO ){ assert( pC->uc.pseudoTableReg>0 ); pReg = &aMem[pC->uc.pseudoTableReg]; assert( pReg->flags & MEM_Blob ); assert( memIsValid(pReg) ); pC->payloadSize = pC->szRow = avail = pReg->n; pC->aRow = (u8*)pReg->z; }else{ sqlite3VdbeMemSetNull(pDest); goto op_column_out; } }else{ assert( pC->eCurType==CURTYPE_BTREE ); assert( pCrsr ); assert( sqlite3BtreeCursorIsValid(pCrsr) ); pC->payloadSize = sqlite3BtreePayloadSize(pCrsr); pC->aRow = sqlite3BtreePayloadFetch(pCrsr, &avail); assert( avail<=65536 ); /* Maximum page size is 64KiB */ if( pC->payloadSize <= (u32)avail ){ pC->szRow = pC->payloadSize; }else if( pC->payloadSize > (u32)db->aLimit[SQLITE_LIMIT_LENGTH] ){ goto too_big; }else{ pC->szRow = avail; } } pC->cacheStatus = p->cacheCtr; pC->iHdrOffset = getVarint32(pC->aRow, offset); pC->nHdrParsed = 0; aOffset[0] = offset; if( availaRow does not have to hold the entire row, but it does at least ** need to cover the header of the record. If pC->aRow does not contain ** the complete header, then set it to zero, forcing the header to be ** dynamically allocated. */ pC->aRow = 0; pC->szRow = 0; /* Make sure a corrupt database has not given us an oversize header. ** Do this now to avoid an oversize memory allocation. ** ** Type entries can be between 1 and 5 bytes each. But 4 and 5 byte ** types use so much data space that there can only be 4096 and 32 of ** them, respectively. So the maximum header length results from a ** 3-byte type for each of the maximum of 32768 columns plus three ** extra bytes for the header length itself. 32768*3 + 3 = 98307. */ if( offset > 98307 || offset > pC->payloadSize ){ rc = SQLITE_CORRUPT_BKPT; goto abort_due_to_error; } }else if( offset>0 ){ /*OPTIMIZATION-IF-TRUE*/ /* The following goto is an optimization. It can be omitted and ** everything will still work. But OP_Column is measurably faster ** by skipping the subsequent conditional, which is always true. */ zData = pC->aRow; assert( pC->nHdrParsed<=p2 ); /* Conditional skipped */ goto op_column_read_header; } } /* Make sure at least the first p2+1 entries of the header have been ** parsed and valid information is in aOffset[] and pC->aType[]. */ if( pC->nHdrParsed<=p2 ){ /* If there is more header available for parsing in the record, try ** to extract additional fields up through the p2+1-th field */ if( pC->iHdrOffsetaRow==0 ){ memset(&sMem, 0, sizeof(sMem)); rc = sqlite3VdbeMemFromBtree(pCrsr, 0, aOffset[0], !pC->isTable, &sMem); if( rc!=SQLITE_OK ) goto abort_due_to_error; zData = (u8*)sMem.z; }else{ zData = pC->aRow; } /* Fill in pC->aType[i] and aOffset[i] values through the p2-th field. */ op_column_read_header: i = pC->nHdrParsed; offset64 = aOffset[i]; zHdr = zData + pC->iHdrOffset; zEndHdr = zData + aOffset[0]; do{ if( (t = zHdr[0])<0x80 ){ zHdr++; offset64 += sqlite3VdbeOneByteSerialTypeLen(t); }else{ zHdr += sqlite3GetVarint32(zHdr, &t); offset64 += sqlite3VdbeSerialTypeLen(t); } pC->aType[i++] = t; aOffset[i] = (u32)(offset64 & 0xffffffff); }while( i<=p2 && zHdr=zEndHdr && (zHdr>zEndHdr || offset64!=pC->payloadSize)) || (offset64 > pC->payloadSize) ){ if( pC->aRow==0 ) sqlite3VdbeMemRelease(&sMem); rc = SQLITE_CORRUPT_BKPT; goto abort_due_to_error; } pC->nHdrParsed = i; pC->iHdrOffset = (u32)(zHdr - zData); if( pC->aRow==0 ) sqlite3VdbeMemRelease(&sMem); }else{ t = 0; } /* If after trying to extract new entries from the header, nHdrParsed is ** still not up to p2, that means that the record has fewer than p2 ** columns. So the result will be either the default value or a NULL. */ if( pC->nHdrParsed<=p2 ){ if( pOp->p4type==P4_MEM ){ sqlite3VdbeMemShallowCopy(pDest, pOp->p4.pMem, MEM_Static); }else{ sqlite3VdbeMemSetNull(pDest); } goto op_column_out; } }else{ t = pC->aType[p2]; } /* Extract the content for the p2+1-th column. Control can only ** reach this point if aOffset[p2], aOffset[p2+1], and pC->aType[p2] are ** all valid. */ assert( p2nHdrParsed ); assert( rc==SQLITE_OK ); assert( sqlite3VdbeCheckMemInvariants(pDest) ); if( VdbeMemDynamic(pDest) ){ sqlite3VdbeMemSetNull(pDest); } assert( t==pC->aType[p2] ); if( pC->szRow>=aOffset[p2+1] ){ /* This is the common case where the desired content fits on the original ** page - where the content is not on an overflow page */ zData = pC->aRow + aOffset[p2]; if( t<12 ){ sqlite3VdbeSerialGet(zData, t, pDest); }else{ /* If the column value is a string, we need a persistent value, not ** a MEM_Ephem value. This branch is a fast short-cut that is equivalent ** to calling sqlite3VdbeSerialGet() and sqlite3VdbeDeephemeralize(). */ static const u16 aFlag[] = { MEM_Blob, MEM_Str|MEM_Term }; pDest->n = len = (t-12)/2; pDest->enc = encoding; if( pDest->szMalloc < len+2 ){ pDest->flags = MEM_Null; if( sqlite3VdbeMemGrow(pDest, len+2, 0) ) goto no_mem; }else{ pDest->z = pDest->zMalloc; } memcpy(pDest->z, zData, len); pDest->z[len] = 0; pDest->z[len+1] = 0; pDest->flags = aFlag[t&1]; } }else{ pDest->enc = encoding; /* This branch happens only when content is on overflow pages */ if( ((pOp->p5 & (OPFLAG_LENGTHARG|OPFLAG_TYPEOFARG))!=0 && ((t>=12 && (t&1)==0) || (pOp->p5 & OPFLAG_TYPEOFARG)!=0)) || (len = sqlite3VdbeSerialTypeLen(t))==0 ){ /* Content is irrelevant for ** 1. the typeof() function, ** 2. the length(X) function if X is a blob, and ** 3. if the content length is zero. ** So we might as well use bogus content rather than reading ** content from disk. */ static u8 aZero[8]; /* This is the bogus content */ sqlite3VdbeSerialGet(aZero, t, pDest); }else{ rc = sqlite3VdbeMemFromBtree(pCrsr, aOffset[p2], len, !pC->isTable, pDest); if( rc!=SQLITE_OK ) goto abort_due_to_error; sqlite3VdbeSerialGet((const u8*)pDest->z, t, pDest); pDest->flags &= ~MEM_Ephem; } } op_column_out: UPDATE_MAX_BLOBSIZE(pDest); REGISTER_TRACE(pOp->p3, pDest); break; } /* Opcode: Affinity P1 P2 * P4 * ** Synopsis: affinity(r[P1@P2]) ** ** Apply affinities to a range of P2 registers starting with P1. ** ** P4 is a string that is P2 characters long. The nth character of the ** string indicates the column affinity that should be used for the nth ** memory cell in the range. */ case OP_Affinity: { const char *zAffinity; /* The affinity to be applied */ char cAff; /* A single character of affinity */ zAffinity = pOp->p4.z; assert( zAffinity!=0 ); assert( zAffinity[pOp->p2]==0 ); pIn1 = &aMem[pOp->p1]; while( (cAff = *(zAffinity++))!=0 ){ assert( pIn1 <= &p->aMem[(p->nMem+1 - p->nCursor)] ); assert( memIsValid(pIn1) ); applyAffinity(pIn1, cAff, encoding); pIn1++; } break; } /* Opcode: MakeRecord P1 P2 P3 P4 * ** Synopsis: r[P3]=mkrec(r[P1@P2]) ** ** Convert P2 registers beginning with P1 into the [record format] ** use as a data record in a database table or as a key ** in an index. The OP_Column opcode can decode the record later. ** ** P4 may be a string that is P2 characters long. The nth character of the ** string indicates the column affinity that should be used for the nth ** field of the index key. ** ** The mapping from character to affinity is given by the SQLITE_AFF_ ** macros defined in sqliteInt.h. ** ** If P4 is NULL then all index fields have the affinity BLOB. */ case OP_MakeRecord: { u8 *zNewRecord; /* A buffer to hold the data for the new record */ Mem *pRec; /* The new record */ u64 nData; /* Number of bytes of data space */ int nHdr; /* Number of bytes of header space */ i64 nByte; /* Data space required for this record */ i64 nZero; /* Number of zero bytes at the end of the record */ int nVarint; /* Number of bytes in a varint */ u32 serial_type; /* Type field */ Mem *pData0; /* First field to be combined into the record */ Mem *pLast; /* Last field of the record */ int nField; /* Number of fields in the record */ char *zAffinity; /* The affinity string for the record */ int file_format; /* File format to use for encoding */ int i; /* Space used in zNewRecord[] header */ int j; /* Space used in zNewRecord[] content */ u32 len; /* Length of a field */ /* Assuming the record contains N fields, the record format looks ** like this: ** ** ------------------------------------------------------------------------ ** | hdr-size | type 0 | type 1 | ... | type N-1 | data0 | ... | data N-1 | ** ------------------------------------------------------------------------ ** ** Data(0) is taken from register P1. Data(1) comes from register P1+1 ** and so forth. ** ** Each type field is a varint representing the serial type of the ** corresponding data element (see sqlite3VdbeSerialType()). The ** hdr-size field is also a varint which is the offset from the beginning ** of the record to data0. */ nData = 0; /* Number of bytes of data space */ nHdr = 0; /* Number of bytes of header space */ nZero = 0; /* Number of zero bytes at the end of the record */ nField = pOp->p1; zAffinity = pOp->p4.z; assert( nField>0 && pOp->p2>0 && pOp->p2+nField<=(p->nMem+1 - p->nCursor)+1 ); pData0 = &aMem[nField]; nField = pOp->p2; pLast = &pData0[nField-1]; file_format = p->minWriteFileFormat; /* Identify the output register */ assert( pOp->p3p1 || pOp->p3>=pOp->p1+pOp->p2 ); pOut = &aMem[pOp->p3]; memAboutToChange(p, pOut); /* Apply the requested affinity to all inputs */ assert( pData0<=pLast ); if( zAffinity ){ pRec = pData0; do{ applyAffinity(pRec++, *(zAffinity++), encoding); assert( zAffinity[0]==0 || pRec<=pLast ); }while( zAffinity[0] ); } /* Loop through the elements that will make up the record to figure ** out how much space is required for the new record. */ pRec = pLast; do{ assert( memIsValid(pRec) ); pRec->uTemp = serial_type = sqlite3VdbeSerialType(pRec, file_format, &len); if( pRec->flags & MEM_Zero ){ if( nData ){ if( sqlite3VdbeMemExpandBlob(pRec) ) goto no_mem; }else{ nZero += pRec->u.nZero; len -= pRec->u.nZero; } } nData += len; testcase( serial_type==127 ); testcase( serial_type==128 ); nHdr += serial_type<=127 ? 1 : sqlite3VarintLen(serial_type); if( pRec==pData0 ) break; pRec--; }while(1); /* EVIDENCE-OF: R-22564-11647 The header begins with a single varint ** which determines the total number of bytes in the header. The varint ** value is the size of the header in bytes including the size varint ** itself. */ testcase( nHdr==126 ); testcase( nHdr==127 ); if( nHdr<=126 ){ /* The common case */ nHdr += 1; }else{ /* Rare case of a really large header */ nVarint = sqlite3VarintLen(nHdr); nHdr += nVarint; if( nVarintdb->aLimit[SQLITE_LIMIT_LENGTH] ){ goto too_big; } /* Make sure the output register has a buffer large enough to store ** the new record. The output register (pOp->p3) is not allowed to ** be one of the input registers (because the following call to ** sqlite3VdbeMemClearAndResize() could clobber the value before it is used). */ if( sqlite3VdbeMemClearAndResize(pOut, (int)nByte) ){ goto no_mem; } zNewRecord = (u8 *)pOut->z; /* Write the record */ i = putVarint32(zNewRecord, nHdr); j = nHdr; assert( pData0<=pLast ); pRec = pData0; do{ serial_type = pRec->uTemp; /* EVIDENCE-OF: R-06529-47362 Following the size varint are one or more ** additional varints, one per column. */ i += putVarint32(&zNewRecord[i], serial_type); /* serial type */ /* EVIDENCE-OF: R-64536-51728 The values for each column in the record ** immediately follow the header. */ j += sqlite3VdbeSerialPut(&zNewRecord[j], pRec, serial_type); /* content */ }while( (++pRec)<=pLast ); assert( i==nHdr ); assert( j==nByte ); assert( pOp->p3>0 && pOp->p3<=(p->nMem+1 - p->nCursor) ); pOut->n = (int)nByte; pOut->flags = MEM_Blob; if( nZero ){ pOut->u.nZero = nZero; pOut->flags |= MEM_Zero; } pOut->enc = SQLITE_UTF8; /* In case the blob is ever converted to text */ REGISTER_TRACE(pOp->p3, pOut); UPDATE_MAX_BLOBSIZE(pOut); break; } /* Opcode: Count P1 P2 * * * ** Synopsis: r[P2]=count() ** ** Store the number of entries (an integer value) in the table or index ** opened by cursor P1 in register P2 */ #ifndef SQLITE_OMIT_BTREECOUNT case OP_Count: { /* out2 */ i64 nEntry; BtCursor *pCrsr; assert( p->apCsr[pOp->p1]->eCurType==CURTYPE_BTREE ); pCrsr = p->apCsr[pOp->p1]->uc.pCursor; assert( pCrsr ); nEntry = 0; /* Not needed. Only used to silence a warning. */ rc = sqlite3BtreeCount(pCrsr, &nEntry); if( rc ) goto abort_due_to_error; pOut = out2Prerelease(p, pOp); pOut->u.i = nEntry; break; } #endif /* Opcode: Savepoint P1 * * P4 * ** ** Open, release or rollback the savepoint named by parameter P4, depending ** on the value of P1. To open a new savepoint, P1==0. To release (commit) an ** existing savepoint, P1==1, or to rollback an existing savepoint P1==2. */ case OP_Savepoint: { int p1; /* Value of P1 operand */ char *zName; /* Name of savepoint */ int nName; Savepoint *pNew; Savepoint *pSavepoint; Savepoint *pTmp; int iSavepoint; int ii; p1 = pOp->p1; zName = pOp->p4.z; /* Assert that the p1 parameter is valid. Also that if there is no open ** transaction, then there cannot be any savepoints. */ assert( db->pSavepoint==0 || db->autoCommit==0 ); assert( p1==SAVEPOINT_BEGIN||p1==SAVEPOINT_RELEASE||p1==SAVEPOINT_ROLLBACK ); assert( db->pSavepoint || db->isTransactionSavepoint==0 ); assert( checkSavepointCount(db) ); assert( p->bIsReader ); if( p1==SAVEPOINT_BEGIN ){ if( db->nVdbeWrite>0 ){ /* A new savepoint cannot be created if there are active write ** statements (i.e. open read/write incremental blob handles). */ sqlite3VdbeError(p, "cannot open savepoint - SQL statements in progress"); rc = SQLITE_BUSY; }else{ nName = sqlite3Strlen30(zName); #ifndef SQLITE_OMIT_VIRTUALTABLE /* This call is Ok even if this savepoint is actually a transaction ** savepoint (and therefore should not prompt xSavepoint()) callbacks. ** If this is a transaction savepoint being opened, it is guaranteed ** that the db->aVTrans[] array is empty. */ assert( db->autoCommit==0 || db->nVTrans==0 ); rc = sqlite3VtabSavepoint(db, SAVEPOINT_BEGIN, db->nStatement+db->nSavepoint); if( rc!=SQLITE_OK ) goto abort_due_to_error; #endif /* Create a new savepoint structure. */ pNew = sqlite3DbMallocRawNN(db, sizeof(Savepoint)+nName+1); if( pNew ){ pNew->zName = (char *)&pNew[1]; memcpy(pNew->zName, zName, nName+1); /* If there is no open transaction, then mark this as a special ** "transaction savepoint". */ if( db->autoCommit ){ db->autoCommit = 0; db->isTransactionSavepoint = 1; }else{ db->nSavepoint++; } /* Link the new savepoint into the database handle's list. */ pNew->pNext = db->pSavepoint; db->pSavepoint = pNew; pNew->nDeferredCons = db->nDeferredCons; pNew->nDeferredImmCons = db->nDeferredImmCons; } } }else{ iSavepoint = 0; /* Find the named savepoint. If there is no such savepoint, then an ** an error is returned to the user. */ for( pSavepoint = db->pSavepoint; pSavepoint && sqlite3StrICmp(pSavepoint->zName, zName); pSavepoint = pSavepoint->pNext ){ iSavepoint++; } if( !pSavepoint ){ sqlite3VdbeError(p, "no such savepoint: %s", zName); rc = SQLITE_ERROR; }else if( db->nVdbeWrite>0 && p1==SAVEPOINT_RELEASE ){ /* It is not possible to release (commit) a savepoint if there are ** active write statements. */ sqlite3VdbeError(p, "cannot release savepoint - " "SQL statements in progress"); rc = SQLITE_BUSY; }else{ /* Determine whether or not this is a transaction savepoint. If so, ** and this is a RELEASE command, then the current transaction ** is committed. */ int isTransaction = pSavepoint->pNext==0 && db->isTransactionSavepoint; if( isTransaction && p1==SAVEPOINT_RELEASE ){ if( (rc = sqlite3VdbeCheckFk(p, 1))!=SQLITE_OK ){ goto vdbe_return; } db->autoCommit = 1; if( sqlite3VdbeHalt(p)==SQLITE_BUSY ){ p->pc = (int)(pOp - aOp); db->autoCommit = 0; p->rc = rc = SQLITE_BUSY; goto vdbe_return; } db->isTransactionSavepoint = 0; rc = p->rc; }else{ int isSchemaChange; iSavepoint = db->nSavepoint - iSavepoint - 1; if( p1==SAVEPOINT_ROLLBACK ){ isSchemaChange = (db->flags & SQLITE_InternChanges)!=0; for(ii=0; iinDb; ii++){ rc = sqlite3BtreeTripAllCursors(db->aDb[ii].pBt, SQLITE_ABORT_ROLLBACK, isSchemaChange==0); if( rc!=SQLITE_OK ) goto abort_due_to_error; } }else{ isSchemaChange = 0; } for(ii=0; iinDb; ii++){ rc = sqlite3BtreeSavepoint(db->aDb[ii].pBt, p1, iSavepoint); if( rc!=SQLITE_OK ){ goto abort_due_to_error; } } if( isSchemaChange ){ sqlite3ExpirePreparedStatements(db); sqlite3ResetAllSchemasOfConnection(db); db->flags = (db->flags | SQLITE_InternChanges); } } /* Regardless of whether this is a RELEASE or ROLLBACK, destroy all ** savepoints nested inside of the savepoint being operated on. */ while( db->pSavepoint!=pSavepoint ){ pTmp = db->pSavepoint; db->pSavepoint = pTmp->pNext; sqlite3DbFree(db, pTmp); db->nSavepoint--; } /* If it is a RELEASE, then destroy the savepoint being operated on ** too. If it is a ROLLBACK TO, then set the number of deferred ** constraint violations present in the database to the value stored ** when the savepoint was created. */ if( p1==SAVEPOINT_RELEASE ){ assert( pSavepoint==db->pSavepoint ); db->pSavepoint = pSavepoint->pNext; sqlite3DbFree(db, pSavepoint); if( !isTransaction ){ db->nSavepoint--; } }else{ db->nDeferredCons = pSavepoint->nDeferredCons; db->nDeferredImmCons = pSavepoint->nDeferredImmCons; } if( !isTransaction || p1==SAVEPOINT_ROLLBACK ){ rc = sqlite3VtabSavepoint(db, p1, iSavepoint); if( rc!=SQLITE_OK ) goto abort_due_to_error; } } } if( rc ) goto abort_due_to_error; break; } /* Opcode: AutoCommit P1 P2 * * * ** ** Set the database auto-commit flag to P1 (1 or 0). If P2 is true, roll ** back any currently active btree transactions. If there are any active ** VMs (apart from this one), then a ROLLBACK fails. A COMMIT fails if ** there are active writing VMs or active VMs that use shared cache. ** ** This instruction causes the VM to halt. */ case OP_AutoCommit: { int desiredAutoCommit; int iRollback; desiredAutoCommit = pOp->p1; iRollback = pOp->p2; assert( desiredAutoCommit==1 || desiredAutoCommit==0 ); assert( desiredAutoCommit==1 || iRollback==0 ); assert( db->nVdbeActive>0 ); /* At least this one VM is active */ assert( p->bIsReader ); if( desiredAutoCommit!=db->autoCommit ){ if( iRollback ){ assert( desiredAutoCommit==1 ); sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK); db->autoCommit = 1; }else if( desiredAutoCommit && db->nVdbeWrite>0 ){ /* If this instruction implements a COMMIT and other VMs are writing ** return an error indicating that the other VMs must complete first. */ sqlite3VdbeError(p, "cannot commit transaction - " "SQL statements in progress"); rc = SQLITE_BUSY; goto abort_due_to_error; }else if( (rc = sqlite3VdbeCheckFk(p, 1))!=SQLITE_OK ){ goto vdbe_return; }else{ db->autoCommit = (u8)desiredAutoCommit; } if( sqlite3VdbeHalt(p)==SQLITE_BUSY ){ p->pc = (int)(pOp - aOp); db->autoCommit = (u8)(1-desiredAutoCommit); p->rc = rc = SQLITE_BUSY; goto vdbe_return; } assert( db->nStatement==0 ); sqlite3CloseSavepoints(db); if( p->rc==SQLITE_OK ){ rc = SQLITE_DONE; }else{ rc = SQLITE_ERROR; } goto vdbe_return; }else{ sqlite3VdbeError(p, (!desiredAutoCommit)?"cannot start a transaction within a transaction":( (iRollback)?"cannot rollback - no transaction is active": "cannot commit - no transaction is active")); rc = SQLITE_ERROR; goto abort_due_to_error; } break; } /* Opcode: Transaction P1 P2 P3 P4 P5 ** ** Begin a transaction on database P1 if a transaction is not already ** active. ** If P2 is non-zero, then a write-transaction is started, or if a ** read-transaction is already active, it is upgraded to a write-transaction. ** If P2 is zero, then a read-transaction is started. ** ** P1 is the index of the database file on which the transaction is ** started. Index 0 is the main database file and index 1 is the ** file used for temporary tables. Indices of 2 or more are used for ** attached databases. ** ** If a write-transaction is started and the Vdbe.usesStmtJournal flag is ** true (this flag is set if the Vdbe may modify more than one row and may ** throw an ABORT exception), a statement transaction may also be opened. ** More specifically, a statement transaction is opened iff the database ** connection is currently not in autocommit mode, or if there are other ** active statements. A statement transaction allows the changes made by this ** VDBE to be rolled back after an error without having to roll back the ** entire transaction. If no error is encountered, the statement transaction ** will automatically commit when the VDBE halts. ** ** If P5!=0 then this opcode also checks the schema cookie against P3 ** and the schema generation counter against P4. ** The cookie changes its value whenever the database schema changes. ** This operation is used to detect when that the cookie has changed ** and that the current process needs to reread the schema. If the schema ** cookie in P3 differs from the schema cookie in the database header or ** if the schema generation counter in P4 differs from the current ** generation counter, then an SQLITE_SCHEMA error is raised and execution ** halts. The sqlite3_step() wrapper function might then reprepare the ** statement and rerun it from the beginning. */ case OP_Transaction: { Btree *pBt; int iMeta; int iGen; assert( p->bIsReader ); assert( p->readOnly==0 || pOp->p2==0 ); assert( pOp->p1>=0 && pOp->p1nDb ); assert( DbMaskTest(p->btreeMask, pOp->p1) ); if( pOp->p2 && (db->flags & SQLITE_QueryOnly)!=0 ){ rc = SQLITE_READONLY; goto abort_due_to_error; } pBt = db->aDb[pOp->p1].pBt; if( pBt ){ rc = sqlite3BtreeBeginTrans(pBt, pOp->p2); testcase( rc==SQLITE_BUSY_SNAPSHOT ); testcase( rc==SQLITE_BUSY_RECOVERY ); if( rc!=SQLITE_OK ){ if( (rc&0xff)==SQLITE_BUSY ){ p->pc = (int)(pOp - aOp); p->rc = rc; goto vdbe_return; } goto abort_due_to_error; } if( pOp->p2 && p->usesStmtJournal && (db->autoCommit==0 || db->nVdbeRead>1) ){ assert( sqlite3BtreeIsInTrans(pBt) ); if( p->iStatement==0 ){ assert( db->nStatement>=0 && db->nSavepoint>=0 ); db->nStatement++; p->iStatement = db->nSavepoint + db->nStatement; } rc = sqlite3VtabSavepoint(db, SAVEPOINT_BEGIN, p->iStatement-1); if( rc==SQLITE_OK ){ rc = sqlite3BtreeBeginStmt(pBt, p->iStatement); } /* Store the current value of the database handles deferred constraint ** counter. If the statement transaction needs to be rolled back, ** the value of this counter needs to be restored too. */ p->nStmtDefCons = db->nDeferredCons; p->nStmtDefImmCons = db->nDeferredImmCons; } /* Gather the schema version number for checking: ** IMPLEMENTATION-OF: R-03189-51135 As each SQL statement runs, the schema ** version is checked to ensure that the schema has not changed since the ** SQL statement was prepared. */ sqlite3BtreeGetMeta(pBt, BTREE_SCHEMA_VERSION, (u32 *)&iMeta); iGen = db->aDb[pOp->p1].pSchema->iGeneration; }else{ iGen = iMeta = 0; } assert( pOp->p5==0 || pOp->p4type==P4_INT32 ); if( pOp->p5 && (iMeta!=pOp->p3 || iGen!=pOp->p4.i) ){ sqlite3DbFree(db, p->zErrMsg); p->zErrMsg = sqlite3DbStrDup(db, "database schema has changed"); /* If the schema-cookie from the database file matches the cookie ** stored with the in-memory representation of the schema, do ** not reload the schema from the database file. ** ** If virtual-tables are in use, this is not just an optimization. ** Often, v-tables store their data in other SQLite tables, which ** are queried from within xNext() and other v-table methods using ** prepared queries. If such a query is out-of-date, we do not want to ** discard the database schema, as the user code implementing the ** v-table would have to be ready for the sqlite3_vtab structure itself ** to be invalidated whenever sqlite3_step() is called from within ** a v-table method. */ if( db->aDb[pOp->p1].pSchema->schema_cookie!=iMeta ){ sqlite3ResetOneSchema(db, pOp->p1); } p->expired = 1; rc = SQLITE_SCHEMA; } if( rc ) goto abort_due_to_error; break; } /* Opcode: ReadCookie P1 P2 P3 * * ** ** Read cookie number P3 from database P1 and write it into register P2. ** P3==1 is the schema version. P3==2 is the database format. ** P3==3 is the recommended pager cache size, and so forth. P1==0 is ** the main database file and P1==1 is the database file used to store ** temporary tables. ** ** There must be a read-lock on the database (either a transaction ** must be started or there must be an open cursor) before ** executing this instruction. */ case OP_ReadCookie: { /* out2 */ int iMeta; int iDb; int iCookie; assert( p->bIsReader ); iDb = pOp->p1; iCookie = pOp->p3; assert( pOp->p3=0 && iDbnDb ); assert( db->aDb[iDb].pBt!=0 ); assert( DbMaskTest(p->btreeMask, iDb) ); sqlite3BtreeGetMeta(db->aDb[iDb].pBt, iCookie, (u32 *)&iMeta); pOut = out2Prerelease(p, pOp); pOut->u.i = iMeta; break; } /* Opcode: SetCookie P1 P2 P3 * * ** ** Write the integer value P3 into cookie number P2 of database P1. ** P2==1 is the schema version. P2==2 is the database format. ** P2==3 is the recommended pager cache ** size, and so forth. P1==0 is the main database file and P1==1 is the ** database file used to store temporary tables. ** ** A transaction must be started before executing this opcode. */ case OP_SetCookie: { Db *pDb; assert( pOp->p2p1>=0 && pOp->p1nDb ); assert( DbMaskTest(p->btreeMask, pOp->p1) ); assert( p->readOnly==0 ); pDb = &db->aDb[pOp->p1]; assert( pDb->pBt!=0 ); assert( sqlite3SchemaMutexHeld(db, pOp->p1, 0) ); /* See note about index shifting on OP_ReadCookie */ rc = sqlite3BtreeUpdateMeta(pDb->pBt, pOp->p2, pOp->p3); if( pOp->p2==BTREE_SCHEMA_VERSION ){ /* When the schema cookie changes, record the new cookie internally */ pDb->pSchema->schema_cookie = pOp->p3; db->flags |= SQLITE_InternChanges; }else if( pOp->p2==BTREE_FILE_FORMAT ){ /* Record changes in the file format */ pDb->pSchema->file_format = pOp->p3; } if( pOp->p1==1 ){ /* Invalidate all prepared statements whenever the TEMP database ** schema is changed. Ticket #1644 */ sqlite3ExpirePreparedStatements(db); p->expired = 0; } if( rc ) goto abort_due_to_error; break; } /* Opcode: OpenRead P1 P2 P3 P4 P5 ** Synopsis: root=P2 iDb=P3 ** ** Open a read-only cursor for the database table whose root page is ** P2 in a database file. The database file is determined by P3. ** P3==0 means the main database, P3==1 means the database used for ** temporary tables, and P3>1 means used the corresponding attached ** database. Give the new cursor an identifier of P1. The P1 ** values need not be contiguous but all P1 values should be small integers. ** It is an error for P1 to be negative. ** ** If P5!=0 then use the content of register P2 as the root page, not ** the value of P2 itself. ** ** There will be a read lock on the database whenever there is an ** open cursor. If the database was unlocked prior to this instruction ** then a read lock is acquired as part of this instruction. A read ** lock allows other processes to read the database but prohibits ** any other process from modifying the database. The read lock is ** released when all cursors are closed. If this instruction attempts ** to get a read lock but fails, the script terminates with an ** SQLITE_BUSY error code. ** ** The P4 value may be either an integer (P4_INT32) or a pointer to ** a KeyInfo structure (P4_KEYINFO). If it is a pointer to a KeyInfo ** structure, then said structure defines the content and collating ** sequence of the index being opened. Otherwise, if P4 is an integer ** value, it is set to the number of columns in the table. ** ** See also: OpenWrite, ReopenIdx */ /* Opcode: ReopenIdx P1 P2 P3 P4 P5 ** Synopsis: root=P2 iDb=P3 ** ** The ReopenIdx opcode works exactly like ReadOpen except that it first ** checks to see if the cursor on P1 is already open with a root page ** number of P2 and if it is this opcode becomes a no-op. In other words, ** if the cursor is already open, do not reopen it. ** ** The ReopenIdx opcode may only be used with P5==0 and with P4 being ** a P4_KEYINFO object. Furthermore, the P3 value must be the same as ** every other ReopenIdx or OpenRead for the same cursor number. ** ** See the OpenRead opcode documentation for additional information. */ /* Opcode: OpenWrite P1 P2 P3 P4 P5 ** Synopsis: root=P2 iDb=P3 ** ** Open a read/write cursor named P1 on the table or index whose root ** page is P2. Or if P5!=0 use the content of register P2 to find the ** root page. ** ** The P4 value may be either an integer (P4_INT32) or a pointer to ** a KeyInfo structure (P4_KEYINFO). If it is a pointer to a KeyInfo ** structure, then said structure defines the content and collating ** sequence of the index being opened. Otherwise, if P4 is an integer ** value, it is set to the number of columns in the table, or to the ** largest index of any column of the table that is actually used. ** ** This instruction works just like OpenRead except that it opens the cursor ** in read/write mode. For a given table, there can be one or more read-only ** cursors or a single read/write cursor but not both. ** ** See also OpenRead. */ case OP_ReopenIdx: { int nField; KeyInfo *pKeyInfo; int p2; int iDb; int wrFlag; Btree *pX; VdbeCursor *pCur; Db *pDb; assert( pOp->p5==0 || pOp->p5==OPFLAG_SEEKEQ ); assert( pOp->p4type==P4_KEYINFO ); pCur = p->apCsr[pOp->p1]; if( pCur && pCur->pgnoRoot==(u32)pOp->p2 ){ assert( pCur->iDb==pOp->p3 ); /* Guaranteed by the code generator */ goto open_cursor_set_hints; } /* If the cursor is not currently open or is open on a different ** index, then fall through into OP_OpenRead to force a reopen */ case OP_OpenRead: case OP_OpenWrite: assert( pOp->opcode==OP_OpenWrite || pOp->p5==0 || pOp->p5==OPFLAG_SEEKEQ ); assert( p->bIsReader ); assert( pOp->opcode==OP_OpenRead || pOp->opcode==OP_ReopenIdx || p->readOnly==0 ); if( p->expired ){ rc = SQLITE_ABORT_ROLLBACK; goto abort_due_to_error; } nField = 0; pKeyInfo = 0; p2 = pOp->p2; iDb = pOp->p3; assert( iDb>=0 && iDbnDb ); assert( DbMaskTest(p->btreeMask, iDb) ); pDb = &db->aDb[iDb]; pX = pDb->pBt; assert( pX!=0 ); if( pOp->opcode==OP_OpenWrite ){ assert( OPFLAG_FORDELETE==BTREE_FORDELETE ); wrFlag = BTREE_WRCSR | (pOp->p5 & OPFLAG_FORDELETE); assert( sqlite3SchemaMutexHeld(db, iDb, 0) ); if( pDb->pSchema->file_format < p->minWriteFileFormat ){ p->minWriteFileFormat = pDb->pSchema->file_format; } }else{ wrFlag = 0; } if( pOp->p5 & OPFLAG_P2ISREG ){ assert( p2>0 ); assert( p2<=(p->nMem+1 - p->nCursor) ); pIn2 = &aMem[p2]; assert( memIsValid(pIn2) ); assert( (pIn2->flags & MEM_Int)!=0 ); sqlite3VdbeMemIntegerify(pIn2); p2 = (int)pIn2->u.i; /* The p2 value always comes from a prior OP_CreateTable opcode and ** that opcode will always set the p2 value to 2 or more or else fail. ** If there were a failure, the prepared statement would have halted ** before reaching this instruction. */ assert( p2>=2 ); } if( pOp->p4type==P4_KEYINFO ){ pKeyInfo = pOp->p4.pKeyInfo; assert( pKeyInfo->enc==ENC(db) ); assert( pKeyInfo->db==db ); nField = pKeyInfo->nField+pKeyInfo->nXField; }else if( pOp->p4type==P4_INT32 ){ nField = pOp->p4.i; } assert( pOp->p1>=0 ); assert( nField>=0 ); testcase( nField==0 ); /* Table with INTEGER PRIMARY KEY and nothing else */ pCur = allocateCursor(p, pOp->p1, nField, iDb, CURTYPE_BTREE); if( pCur==0 ) goto no_mem; pCur->nullRow = 1; pCur->isOrdered = 1; pCur->pgnoRoot = p2; #ifdef SQLITE_DEBUG pCur->wrFlag = wrFlag; #endif rc = sqlite3BtreeCursor(pX, p2, wrFlag, pKeyInfo, pCur->uc.pCursor); pCur->pKeyInfo = pKeyInfo; /* Set the VdbeCursor.isTable variable. Previous versions of ** SQLite used to check if the root-page flags were sane at this point ** and report database corruption if they were not, but this check has ** since moved into the btree layer. */ pCur->isTable = pOp->p4type!=P4_KEYINFO; open_cursor_set_hints: assert( OPFLAG_BULKCSR==BTREE_BULKLOAD ); assert( OPFLAG_SEEKEQ==BTREE_SEEK_EQ ); testcase( pOp->p5 & OPFLAG_BULKCSR ); #ifdef SQLITE_ENABLE_CURSOR_HINTS testcase( pOp->p2 & OPFLAG_SEEKEQ ); #endif sqlite3BtreeCursorHintFlags(pCur->uc.pCursor, (pOp->p5 & (OPFLAG_BULKCSR|OPFLAG_SEEKEQ))); if( rc ) goto abort_due_to_error; break; } /* Opcode: OpenEphemeral P1 P2 * P4 P5 ** Synopsis: nColumn=P2 ** ** Open a new cursor P1 to a transient table. ** The cursor is always opened read/write even if ** the main database is read-only. The ephemeral ** table is deleted automatically when the cursor is closed. ** ** P2 is the number of columns in the ephemeral table. ** The cursor points to a BTree table if P4==0 and to a BTree index ** if P4 is not 0. If P4 is not NULL, it points to a KeyInfo structure ** that defines the format of keys in the index. ** ** The P5 parameter can be a mask of the BTREE_* flags defined ** in btree.h. These flags control aspects of the operation of ** the btree. The BTREE_OMIT_JOURNAL and BTREE_SINGLE flags are ** added automatically. */ /* Opcode: OpenAutoindex P1 P2 * P4 * ** Synopsis: nColumn=P2 ** ** This opcode works the same as OP_OpenEphemeral. It has a ** different name to distinguish its use. Tables created using ** by this opcode will be used for automatically created transient ** indices in joins. */ case OP_OpenAutoindex: case OP_OpenEphemeral: { VdbeCursor *pCx; KeyInfo *pKeyInfo; static const int vfsFlags = SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE | SQLITE_OPEN_EXCLUSIVE | SQLITE_OPEN_DELETEONCLOSE | SQLITE_OPEN_TRANSIENT_DB; assert( pOp->p1>=0 ); assert( pOp->p2>=0 ); pCx = allocateCursor(p, pOp->p1, pOp->p2, -1, CURTYPE_BTREE); if( pCx==0 ) goto no_mem; pCx->nullRow = 1; pCx->isEphemeral = 1; rc = sqlite3BtreeOpen(db->pVfs, 0, db, &pCx->pBt, BTREE_OMIT_JOURNAL | BTREE_SINGLE | pOp->p5, vfsFlags); if( rc==SQLITE_OK ){ rc = sqlite3BtreeBeginTrans(pCx->pBt, 1); } if( rc==SQLITE_OK ){ /* If a transient index is required, create it by calling ** sqlite3BtreeCreateTable() with the BTREE_BLOBKEY flag before ** opening it. If a transient table is required, just use the ** automatically created table with root-page 1 (an BLOB_INTKEY table). */ if( (pKeyInfo = pOp->p4.pKeyInfo)!=0 ){ int pgno; assert( pOp->p4type==P4_KEYINFO ); rc = sqlite3BtreeCreateTable(pCx->pBt, &pgno, BTREE_BLOBKEY | pOp->p5); if( rc==SQLITE_OK ){ assert( pgno==MASTER_ROOT+1 ); assert( pKeyInfo->db==db ); assert( pKeyInfo->enc==ENC(db) ); pCx->pKeyInfo = pKeyInfo; rc = sqlite3BtreeCursor(pCx->pBt, pgno, BTREE_WRCSR, pKeyInfo, pCx->uc.pCursor); } pCx->isTable = 0; }else{ rc = sqlite3BtreeCursor(pCx->pBt, MASTER_ROOT, BTREE_WRCSR, 0, pCx->uc.pCursor); pCx->isTable = 1; } } if( rc ) goto abort_due_to_error; pCx->isOrdered = (pOp->p5!=BTREE_UNORDERED); break; } /* Opcode: SorterOpen P1 P2 P3 P4 * ** ** This opcode works like OP_OpenEphemeral except that it opens ** a transient index that is specifically designed to sort large ** tables using an external merge-sort algorithm. ** ** If argument P3 is non-zero, then it indicates that the sorter may ** assume that a stable sort considering the first P3 fields of each ** key is sufficient to produce the required results. */ case OP_SorterOpen: { VdbeCursor *pCx; assert( pOp->p1>=0 ); assert( pOp->p2>=0 ); pCx = allocateCursor(p, pOp->p1, pOp->p2, -1, CURTYPE_SORTER); if( pCx==0 ) goto no_mem; pCx->pKeyInfo = pOp->p4.pKeyInfo; assert( pCx->pKeyInfo->db==db ); assert( pCx->pKeyInfo->enc==ENC(db) ); rc = sqlite3VdbeSorterInit(db, pOp->p3, pCx); if( rc ) goto abort_due_to_error; break; } /* Opcode: SequenceTest P1 P2 * * * ** Synopsis: if( cursor[P1].ctr++ ) pc = P2 ** ** P1 is a sorter cursor. If the sequence counter is currently zero, jump ** to P2. Regardless of whether or not the jump is taken, increment the ** the sequence value. */ case OP_SequenceTest: { VdbeCursor *pC; assert( pOp->p1>=0 && pOp->p1nCursor ); pC = p->apCsr[pOp->p1]; assert( isSorter(pC) ); if( (pC->seqCount++)==0 ){ goto jump_to_p2; } break; } /* Opcode: OpenPseudo P1 P2 P3 * * ** Synopsis: P3 columns in r[P2] ** ** Open a new cursor that points to a fake table that contains a single ** row of data. The content of that one row is the content of memory ** register P2. In other words, cursor P1 becomes an alias for the ** MEM_Blob content contained in register P2. ** ** A pseudo-table created by this opcode is used to hold a single ** row output from the sorter so that the row can be decomposed into ** individual columns using the OP_Column opcode. The OP_Column opcode ** is the only cursor opcode that works with a pseudo-table. ** ** P3 is the number of fields in the records that will be stored by ** the pseudo-table. */ case OP_OpenPseudo: { VdbeCursor *pCx; assert( pOp->p1>=0 ); assert( pOp->p3>=0 ); pCx = allocateCursor(p, pOp->p1, pOp->p3, -1, CURTYPE_PSEUDO); if( pCx==0 ) goto no_mem; pCx->nullRow = 1; pCx->uc.pseudoTableReg = pOp->p2; pCx->isTable = 1; assert( pOp->p5==0 ); break; } /* Opcode: Close P1 * * * * ** ** Close a cursor previously opened as P1. If P1 is not ** currently open, this instruction is a no-op. */ case OP_Close: { assert( pOp->p1>=0 && pOp->p1nCursor ); sqlite3VdbeFreeCursor(p, p->apCsr[pOp->p1]); p->apCsr[pOp->p1] = 0; break; } #ifdef SQLITE_ENABLE_COLUMN_USED_MASK /* Opcode: ColumnsUsed P1 * * P4 * ** ** This opcode (which only exists if SQLite was compiled with ** SQLITE_ENABLE_COLUMN_USED_MASK) identifies which columns of the ** table or index for cursor P1 are used. P4 is a 64-bit integer ** (P4_INT64) in which the first 63 bits are one for each of the ** first 63 columns of the table or index that are actually used ** by the cursor. The high-order bit is set if any column after ** the 64th is used. */ case OP_ColumnsUsed: { VdbeCursor *pC; pC = p->apCsr[pOp->p1]; assert( pC->eCurType==CURTYPE_BTREE ); pC->maskUsed = *(u64*)pOp->p4.pI64; break; } #endif /* Opcode: SeekGE P1 P2 P3 P4 * ** Synopsis: key=r[P3@P4] ** ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys), ** use the value in register P3 as the key. If cursor P1 refers ** to an SQL index, then P3 is the first in an array of P4 registers ** that are used as an unpacked index key. ** ** Reposition cursor P1 so that it points to the smallest entry that ** is greater than or equal to the key value. If there are no records ** greater than or equal to the key and P2 is not zero, then jump to P2. ** ** If the cursor P1 was opened using the OPFLAG_SEEKEQ flag, then this ** opcode will always land on a record that equally equals the key, or ** else jump immediately to P2. When the cursor is OPFLAG_SEEKEQ, this ** opcode must be followed by an IdxLE opcode with the same arguments. ** The IdxLE opcode will be skipped if this opcode succeeds, but the ** IdxLE opcode will be used on subsequent loop iterations. ** ** This opcode leaves the cursor configured to move in forward order, ** from the beginning toward the end. In other words, the cursor is ** configured to use Next, not Prev. ** ** See also: Found, NotFound, SeekLt, SeekGt, SeekLe */ /* Opcode: SeekGT P1 P2 P3 P4 * ** Synopsis: key=r[P3@P4] ** ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys), ** use the value in register P3 as a key. If cursor P1 refers ** to an SQL index, then P3 is the first in an array of P4 registers ** that are used as an unpacked index key. ** ** Reposition cursor P1 so that it points to the smallest entry that ** is greater than the key value. If there are no records greater than ** the key and P2 is not zero, then jump to P2. ** ** This opcode leaves the cursor configured to move in forward order, ** from the beginning toward the end. In other words, the cursor is ** configured to use Next, not Prev. ** ** See also: Found, NotFound, SeekLt, SeekGe, SeekLe */ /* Opcode: SeekLT P1 P2 P3 P4 * ** Synopsis: key=r[P3@P4] ** ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys), ** use the value in register P3 as a key. If cursor P1 refers ** to an SQL index, then P3 is the first in an array of P4 registers ** that are used as an unpacked index key. ** ** Reposition cursor P1 so that it points to the largest entry that ** is less than the key value. If there are no records less than ** the key and P2 is not zero, then jump to P2. ** ** This opcode leaves the cursor configured to move in reverse order, ** from the end toward the beginning. In other words, the cursor is ** configured to use Prev, not Next. ** ** See also: Found, NotFound, SeekGt, SeekGe, SeekLe */ /* Opcode: SeekLE P1 P2 P3 P4 * ** Synopsis: key=r[P3@P4] ** ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys), ** use the value in register P3 as a key. If cursor P1 refers ** to an SQL index, then P3 is the first in an array of P4 registers ** that are used as an unpacked index key. ** ** Reposition cursor P1 so that it points to the largest entry that ** is less than or equal to the key value. If there are no records ** less than or equal to the key and P2 is not zero, then jump to P2. ** ** This opcode leaves the cursor configured to move in reverse order, ** from the end toward the beginning. In other words, the cursor is ** configured to use Prev, not Next. ** ** If the cursor P1 was opened using the OPFLAG_SEEKEQ flag, then this ** opcode will always land on a record that equally equals the key, or ** else jump immediately to P2. When the cursor is OPFLAG_SEEKEQ, this ** opcode must be followed by an IdxGE opcode with the same arguments. ** The IdxGE opcode will be skipped if this opcode succeeds, but the ** IdxGE opcode will be used on subsequent loop iterations. ** ** See also: Found, NotFound, SeekGt, SeekGe, SeekLt */ case OP_SeekLT: /* jump, in3 */ case OP_SeekLE: /* jump, in3 */ case OP_SeekGE: /* jump, in3 */ case OP_SeekGT: { /* jump, in3 */ int res; /* Comparison result */ int oc; /* Opcode */ VdbeCursor *pC; /* The cursor to seek */ UnpackedRecord r; /* The key to seek for */ int nField; /* Number of columns or fields in the key */ i64 iKey; /* The rowid we are to seek to */ int eqOnly; /* Only interested in == results */ assert( pOp->p1>=0 && pOp->p1nCursor ); assert( pOp->p2!=0 ); pC = p->apCsr[pOp->p1]; assert( pC!=0 ); assert( pC->eCurType==CURTYPE_BTREE ); assert( OP_SeekLE == OP_SeekLT+1 ); assert( OP_SeekGE == OP_SeekLT+2 ); assert( OP_SeekGT == OP_SeekLT+3 ); assert( pC->isOrdered ); assert( pC->uc.pCursor!=0 ); oc = pOp->opcode; eqOnly = 0; pC->nullRow = 0; #ifdef SQLITE_DEBUG pC->seekOp = pOp->opcode; #endif if( pC->isTable ){ /* The BTREE_SEEK_EQ flag is only set on index cursors */ assert( sqlite3BtreeCursorHasHint(pC->uc.pCursor, BTREE_SEEK_EQ)==0 ); /* The input value in P3 might be of any type: integer, real, string, ** blob, or NULL. But it needs to be an integer before we can do ** the seek, so convert it. */ pIn3 = &aMem[pOp->p3]; if( (pIn3->flags & (MEM_Int|MEM_Real|MEM_Str))==MEM_Str ){ applyNumericAffinity(pIn3, 0); } iKey = sqlite3VdbeIntValue(pIn3); /* If the P3 value could not be converted into an integer without ** loss of information, then special processing is required... */ if( (pIn3->flags & MEM_Int)==0 ){ if( (pIn3->flags & MEM_Real)==0 ){ /* If the P3 value cannot be converted into any kind of a number, ** then the seek is not possible, so jump to P2 */ VdbeBranchTaken(1,2); goto jump_to_p2; break; } /* If the approximation iKey is larger than the actual real search ** term, substitute >= for > and < for <=. e.g. if the search term ** is 4.9 and the integer approximation 5: ** ** (x > 4.9) -> (x >= 5) ** (x <= 4.9) -> (x < 5) */ if( pIn3->u.r<(double)iKey ){ assert( OP_SeekGE==(OP_SeekGT-1) ); assert( OP_SeekLT==(OP_SeekLE-1) ); assert( (OP_SeekLE & 0x0001)==(OP_SeekGT & 0x0001) ); if( (oc & 0x0001)==(OP_SeekGT & 0x0001) ) oc--; } /* If the approximation iKey is smaller than the actual real search ** term, substitute <= for < and > for >=. */ else if( pIn3->u.r>(double)iKey ){ assert( OP_SeekLE==(OP_SeekLT+1) ); assert( OP_SeekGT==(OP_SeekGE+1) ); assert( (OP_SeekLT & 0x0001)==(OP_SeekGE & 0x0001) ); if( (oc & 0x0001)==(OP_SeekLT & 0x0001) ) oc++; } } rc = sqlite3BtreeMovetoUnpacked(pC->uc.pCursor, 0, (u64)iKey, 0, &res); pC->movetoTarget = iKey; /* Used by OP_Delete */ if( rc!=SQLITE_OK ){ goto abort_due_to_error; } }else{ /* For a cursor with the BTREE_SEEK_EQ hint, only the OP_SeekGE and ** OP_SeekLE opcodes are allowed, and these must be immediately followed ** by an OP_IdxGT or OP_IdxLT opcode, respectively, with the same key. */ if( sqlite3BtreeCursorHasHint(pC->uc.pCursor, BTREE_SEEK_EQ) ){ eqOnly = 1; assert( pOp->opcode==OP_SeekGE || pOp->opcode==OP_SeekLE ); assert( pOp[1].opcode==OP_IdxLT || pOp[1].opcode==OP_IdxGT ); assert( pOp[1].p1==pOp[0].p1 ); assert( pOp[1].p2==pOp[0].p2 ); assert( pOp[1].p3==pOp[0].p3 ); assert( pOp[1].p4.i==pOp[0].p4.i ); } nField = pOp->p4.i; assert( pOp->p4type==P4_INT32 ); assert( nField>0 ); r.pKeyInfo = pC->pKeyInfo; r.nField = (u16)nField; /* The next line of code computes as follows, only faster: ** if( oc==OP_SeekGT || oc==OP_SeekLE ){ ** r.default_rc = -1; ** }else{ ** r.default_rc = +1; ** } */ r.default_rc = ((1 & (oc - OP_SeekLT)) ? -1 : +1); assert( oc!=OP_SeekGT || r.default_rc==-1 ); assert( oc!=OP_SeekLE || r.default_rc==-1 ); assert( oc!=OP_SeekGE || r.default_rc==+1 ); assert( oc!=OP_SeekLT || r.default_rc==+1 ); r.aMem = &aMem[pOp->p3]; #ifdef SQLITE_DEBUG { int i; for(i=0; iuc.pCursor, &r, 0, 0, &res); if( rc!=SQLITE_OK ){ goto abort_due_to_error; } if( eqOnly && r.eqSeen==0 ){ assert( res!=0 ); goto seek_not_found; } } pC->deferredMoveto = 0; pC->cacheStatus = CACHE_STALE; #ifdef SQLITE_TEST sqlite3_search_count++; #endif if( oc>=OP_SeekGE ){ assert( oc==OP_SeekGE || oc==OP_SeekGT ); if( res<0 || (res==0 && oc==OP_SeekGT) ){ res = 0; rc = sqlite3BtreeNext(pC->uc.pCursor, &res); if( rc!=SQLITE_OK ) goto abort_due_to_error; }else{ res = 0; } }else{ assert( oc==OP_SeekLT || oc==OP_SeekLE ); if( res>0 || (res==0 && oc==OP_SeekLT) ){ res = 0; rc = sqlite3BtreePrevious(pC->uc.pCursor, &res); if( rc!=SQLITE_OK ) goto abort_due_to_error; }else{ /* res might be negative because the table is empty. Check to ** see if this is the case. */ res = sqlite3BtreeEof(pC->uc.pCursor); } } seek_not_found: assert( pOp->p2>0 ); VdbeBranchTaken(res!=0,2); if( res ){ goto jump_to_p2; }else if( eqOnly ){ assert( pOp[1].opcode==OP_IdxLT || pOp[1].opcode==OP_IdxGT ); pOp++; /* Skip the OP_IdxLt or OP_IdxGT that follows */ } break; } /* Opcode: Found P1 P2 P3 P4 * ** Synopsis: key=r[P3@P4] ** ** If P4==0 then register P3 holds a blob constructed by MakeRecord. If ** P4>0 then register P3 is the first of P4 registers that form an unpacked ** record. ** ** Cursor P1 is on an index btree. If the record identified by P3 and P4 ** is a prefix of any entry in P1 then a jump is made to P2 and ** P1 is left pointing at the matching entry. ** ** This operation leaves the cursor in a state where it can be ** advanced in the forward direction. The Next instruction will work, ** but not the Prev instruction. ** ** See also: NotFound, NoConflict, NotExists. SeekGe */ /* Opcode: NotFound P1 P2 P3 P4 * ** Synopsis: key=r[P3@P4] ** ** If P4==0 then register P3 holds a blob constructed by MakeRecord. If ** P4>0 then register P3 is the first of P4 registers that form an unpacked ** record. ** ** Cursor P1 is on an index btree. If the record identified by P3 and P4 ** is not the prefix of any entry in P1 then a jump is made to P2. If P1 ** does contain an entry whose prefix matches the P3/P4 record then control ** falls through to the next instruction and P1 is left pointing at the ** matching entry. ** ** This operation leaves the cursor in a state where it cannot be ** advanced in either direction. In other words, the Next and Prev ** opcodes do not work after this operation. ** ** See also: Found, NotExists, NoConflict */ /* Opcode: NoConflict P1 P2 P3 P4 * ** Synopsis: key=r[P3@P4] ** ** If P4==0 then register P3 holds a blob constructed by MakeRecord. If ** P4>0 then register P3 is the first of P4 registers that form an unpacked ** record. ** ** Cursor P1 is on an index btree. If the record identified by P3 and P4 ** contains any NULL value, jump immediately to P2. If all terms of the ** record are not-NULL then a check is done to determine if any row in the ** P1 index btree has a matching key prefix. If there are no matches, jump ** immediately to P2. If there is a match, fall through and leave the P1 ** cursor pointing to the matching row. ** ** This opcode is similar to OP_NotFound with the exceptions that the ** branch is always taken if any part of the search key input is NULL. ** ** This operation leaves the cursor in a state where it cannot be ** advanced in either direction. In other words, the Next and Prev ** opcodes do not work after this operation. ** ** See also: NotFound, Found, NotExists */ case OP_NoConflict: /* jump, in3 */ case OP_NotFound: /* jump, in3 */ case OP_Found: { /* jump, in3 */ int alreadyExists; int takeJump; int ii; VdbeCursor *pC; int res; char *pFree; UnpackedRecord *pIdxKey; UnpackedRecord r; char aTempRec[ROUND8(sizeof(UnpackedRecord)) + sizeof(Mem)*4 + 7]; #ifdef SQLITE_TEST if( pOp->opcode!=OP_NoConflict ) sqlite3_found_count++; #endif assert( pOp->p1>=0 && pOp->p1nCursor ); assert( pOp->p4type==P4_INT32 ); pC = p->apCsr[pOp->p1]; assert( pC!=0 ); #ifdef SQLITE_DEBUG pC->seekOp = pOp->opcode; #endif pIn3 = &aMem[pOp->p3]; assert( pC->eCurType==CURTYPE_BTREE ); assert( pC->uc.pCursor!=0 ); assert( pC->isTable==0 ); pFree = 0; if( pOp->p4.i>0 ){ r.pKeyInfo = pC->pKeyInfo; r.nField = (u16)pOp->p4.i; r.aMem = pIn3; #ifdef SQLITE_DEBUG for(ii=0; iip3+ii, &r.aMem[ii]); } #endif pIdxKey = &r; }else{ pIdxKey = sqlite3VdbeAllocUnpackedRecord( pC->pKeyInfo, aTempRec, sizeof(aTempRec), &pFree ); if( pIdxKey==0 ) goto no_mem; assert( pIn3->flags & MEM_Blob ); (void)ExpandBlob(pIn3); sqlite3VdbeRecordUnpack(pC->pKeyInfo, pIn3->n, pIn3->z, pIdxKey); } pIdxKey->default_rc = 0; takeJump = 0; if( pOp->opcode==OP_NoConflict ){ /* For the OP_NoConflict opcode, take the jump if any of the ** input fields are NULL, since any key with a NULL will not ** conflict */ for(ii=0; iinField; ii++){ if( pIdxKey->aMem[ii].flags & MEM_Null ){ takeJump = 1; break; } } } rc = sqlite3BtreeMovetoUnpacked(pC->uc.pCursor, pIdxKey, 0, 0, &res); sqlite3DbFree(db, pFree); if( rc!=SQLITE_OK ){ goto abort_due_to_error; } pC->seekResult = res; alreadyExists = (res==0); pC->nullRow = 1-alreadyExists; pC->deferredMoveto = 0; pC->cacheStatus = CACHE_STALE; if( pOp->opcode==OP_Found ){ VdbeBranchTaken(alreadyExists!=0,2); if( alreadyExists ) goto jump_to_p2; }else{ VdbeBranchTaken(takeJump||alreadyExists==0,2); if( takeJump || !alreadyExists ) goto jump_to_p2; } break; } /* Opcode: SeekRowid P1 P2 P3 * * ** Synopsis: intkey=r[P3] ** ** P1 is the index of a cursor open on an SQL table btree (with integer ** keys). If register P3 does not contain an integer or if P1 does not ** contain a record with rowid P3 then jump immediately to P2. ** Or, if P2 is 0, raise an SQLITE_CORRUPT error. If P1 does contain ** a record with rowid P3 then ** leave the cursor pointing at that record and fall through to the next ** instruction. ** ** The OP_NotExists opcode performs the same operation, but with OP_NotExists ** the P3 register must be guaranteed to contain an integer value. With this ** opcode, register P3 might not contain an integer. ** ** The OP_NotFound opcode performs the same operation on index btrees ** (with arbitrary multi-value keys). ** ** This opcode leaves the cursor in a state where it cannot be advanced ** in either direction. In other words, the Next and Prev opcodes will ** not work following this opcode. ** ** See also: Found, NotFound, NoConflict, SeekRowid */ /* Opcode: NotExists P1 P2 P3 * * ** Synopsis: intkey=r[P3] ** ** P1 is the index of a cursor open on an SQL table btree (with integer ** keys). P3 is an integer rowid. If P1 does not contain a record with ** rowid P3 then jump immediately to P2. Or, if P2 is 0, raise an ** SQLITE_CORRUPT error. If P1 does contain a record with rowid P3 then ** leave the cursor pointing at that record and fall through to the next ** instruction. ** ** The OP_SeekRowid opcode performs the same operation but also allows the ** P3 register to contain a non-integer value, in which case the jump is ** always taken. This opcode requires that P3 always contain an integer. ** ** The OP_NotFound opcode performs the same operation on index btrees ** (with arbitrary multi-value keys). ** ** This opcode leaves the cursor in a state where it cannot be advanced ** in either direction. In other words, the Next and Prev opcodes will ** not work following this opcode. ** ** See also: Found, NotFound, NoConflict, SeekRowid */ case OP_SeekRowid: { /* jump, in3 */ VdbeCursor *pC; BtCursor *pCrsr; int res; u64 iKey; pIn3 = &aMem[pOp->p3]; if( (pIn3->flags & MEM_Int)==0 ){ applyAffinity(pIn3, SQLITE_AFF_NUMERIC, encoding); if( (pIn3->flags & MEM_Int)==0 ) goto jump_to_p2; } /* Fall through into OP_NotExists */ case OP_NotExists: /* jump, in3 */ pIn3 = &aMem[pOp->p3]; assert( pIn3->flags & MEM_Int ); assert( pOp->p1>=0 && pOp->p1nCursor ); pC = p->apCsr[pOp->p1]; assert( pC!=0 ); #ifdef SQLITE_DEBUG pC->seekOp = 0; #endif assert( pC->isTable ); assert( pC->eCurType==CURTYPE_BTREE ); pCrsr = pC->uc.pCursor; assert( pCrsr!=0 ); res = 0; iKey = pIn3->u.i; rc = sqlite3BtreeMovetoUnpacked(pCrsr, 0, iKey, 0, &res); assert( rc==SQLITE_OK || res==0 ); pC->movetoTarget = iKey; /* Used by OP_Delete */ pC->nullRow = 0; pC->cacheStatus = CACHE_STALE; pC->deferredMoveto = 0; VdbeBranchTaken(res!=0,2); pC->seekResult = res; if( res!=0 ){ assert( rc==SQLITE_OK ); if( pOp->p2==0 ){ rc = SQLITE_CORRUPT_BKPT; }else{ goto jump_to_p2; } } if( rc ) goto abort_due_to_error; break; } /* Opcode: Sequence P1 P2 * * * ** Synopsis: r[P2]=cursor[P1].ctr++ ** ** Find the next available sequence number for cursor P1. ** Write the sequence number into register P2. ** The sequence number on the cursor is incremented after this ** instruction. */ case OP_Sequence: { /* out2 */ assert( pOp->p1>=0 && pOp->p1nCursor ); assert( p->apCsr[pOp->p1]!=0 ); assert( p->apCsr[pOp->p1]->eCurType!=CURTYPE_VTAB ); pOut = out2Prerelease(p, pOp); pOut->u.i = p->apCsr[pOp->p1]->seqCount++; break; } /* Opcode: NewRowid P1 P2 P3 * * ** Synopsis: r[P2]=rowid ** ** Get a new integer record number (a.k.a "rowid") used as the key to a table. ** The record number is not previously used as a key in the database ** table that cursor P1 points to. The new record number is written ** written to register P2. ** ** If P3>0 then P3 is a register in the root frame of this VDBE that holds ** the largest previously generated record number. No new record numbers are ** allowed to be less than this value. When this value reaches its maximum, ** an SQLITE_FULL error is generated. The P3 register is updated with the ' ** generated record number. This P3 mechanism is used to help implement the ** AUTOINCREMENT feature. */ case OP_NewRowid: { /* out2 */ i64 v; /* The new rowid */ VdbeCursor *pC; /* Cursor of table to get the new rowid */ int res; /* Result of an sqlite3BtreeLast() */ int cnt; /* Counter to limit the number of searches */ Mem *pMem; /* Register holding largest rowid for AUTOINCREMENT */ VdbeFrame *pFrame; /* Root frame of VDBE */ v = 0; res = 0; pOut = out2Prerelease(p, pOp); assert( pOp->p1>=0 && pOp->p1nCursor ); pC = p->apCsr[pOp->p1]; assert( pC!=0 ); assert( pC->eCurType==CURTYPE_BTREE ); assert( pC->uc.pCursor!=0 ); { /* The next rowid or record number (different terms for the same ** thing) is obtained in a two-step algorithm. ** ** First we attempt to find the largest existing rowid and add one ** to that. But if the largest existing rowid is already the maximum ** positive integer, we have to fall through to the second ** probabilistic algorithm ** ** The second algorithm is to select a rowid at random and see if ** it already exists in the table. If it does not exist, we have ** succeeded. If the random rowid does exist, we select a new one ** and try again, up to 100 times. */ assert( pC->isTable ); #ifdef SQLITE_32BIT_ROWID # define MAX_ROWID 0x7fffffff #else /* Some compilers complain about constants of the form 0x7fffffffffffffff. ** Others complain about 0x7ffffffffffffffffLL. The following macro seems ** to provide the constant while making all compilers happy. */ # define MAX_ROWID (i64)( (((u64)0x7fffffff)<<32) | (u64)0xffffffff ) #endif if( !pC->useRandomRowid ){ rc = sqlite3BtreeLast(pC->uc.pCursor, &res); if( rc!=SQLITE_OK ){ goto abort_due_to_error; } if( res ){ v = 1; /* IMP: R-61914-48074 */ }else{ assert( sqlite3BtreeCursorIsValid(pC->uc.pCursor) ); v = sqlite3BtreeIntegerKey(pC->uc.pCursor); if( v>=MAX_ROWID ){ pC->useRandomRowid = 1; }else{ v++; /* IMP: R-29538-34987 */ } } } #ifndef SQLITE_OMIT_AUTOINCREMENT if( pOp->p3 ){ /* Assert that P3 is a valid memory cell. */ assert( pOp->p3>0 ); if( p->pFrame ){ for(pFrame=p->pFrame; pFrame->pParent; pFrame=pFrame->pParent); /* Assert that P3 is a valid memory cell. */ assert( pOp->p3<=pFrame->nMem ); pMem = &pFrame->aMem[pOp->p3]; }else{ /* Assert that P3 is a valid memory cell. */ assert( pOp->p3<=(p->nMem+1 - p->nCursor) ); pMem = &aMem[pOp->p3]; memAboutToChange(p, pMem); } assert( memIsValid(pMem) ); REGISTER_TRACE(pOp->p3, pMem); sqlite3VdbeMemIntegerify(pMem); assert( (pMem->flags & MEM_Int)!=0 ); /* mem(P3) holds an integer */ if( pMem->u.i==MAX_ROWID || pC->useRandomRowid ){ rc = SQLITE_FULL; /* IMP: R-12275-61338 */ goto abort_due_to_error; } if( vu.i+1 ){ v = pMem->u.i + 1; } pMem->u.i = v; } #endif if( pC->useRandomRowid ){ /* IMPLEMENTATION-OF: R-07677-41881 If the largest ROWID is equal to the ** largest possible integer (9223372036854775807) then the database ** engine starts picking positive candidate ROWIDs at random until ** it finds one that is not previously used. */ assert( pOp->p3==0 ); /* We cannot be in random rowid mode if this is ** an AUTOINCREMENT table. */ cnt = 0; do{ sqlite3_randomness(sizeof(v), &v); v &= (MAX_ROWID>>1); v++; /* Ensure that v is greater than zero */ }while( ((rc = sqlite3BtreeMovetoUnpacked(pC->uc.pCursor, 0, (u64)v, 0, &res))==SQLITE_OK) && (res==0) && (++cnt<100)); if( rc ) goto abort_due_to_error; if( res==0 ){ rc = SQLITE_FULL; /* IMP: R-38219-53002 */ goto abort_due_to_error; } assert( v>0 ); /* EV: R-40812-03570 */ } pC->deferredMoveto = 0; pC->cacheStatus = CACHE_STALE; } pOut->u.i = v; break; } /* Opcode: Insert P1 P2 P3 P4 P5 ** Synopsis: intkey=r[P3] data=r[P2] ** ** Write an entry into the table of cursor P1. A new entry is ** created if it doesn't already exist or the data for an existing ** entry is overwritten. The data is the value MEM_Blob stored in register ** number P2. The key is stored in register P3. The key must ** be a MEM_Int. ** ** If the OPFLAG_NCHANGE flag of P5 is set, then the row change count is ** incremented (otherwise not). If the OPFLAG_LASTROWID flag of P5 is set, ** then rowid is stored for subsequent return by the ** sqlite3_last_insert_rowid() function (otherwise it is unmodified). ** ** If the OPFLAG_USESEEKRESULT flag of P5 is set and if the result of ** the last seek operation (OP_NotExists or OP_SeekRowid) was a success, ** then this ** operation will not attempt to find the appropriate row before doing ** the insert but will instead overwrite the row that the cursor is ** currently pointing to. Presumably, the prior OP_NotExists or ** OP_SeekRowid opcode ** has already positioned the cursor correctly. This is an optimization ** that boosts performance by avoiding redundant seeks. ** ** If the OPFLAG_ISUPDATE flag is set, then this opcode is part of an ** UPDATE operation. Otherwise (if the flag is clear) then this opcode ** is part of an INSERT operation. The difference is only important to ** the update hook. ** ** Parameter P4 may point to a Table structure, or may be NULL. If it is ** not NULL, then the update-hook (sqlite3.xUpdateCallback) is invoked ** following a successful insert. ** ** (WARNING/TODO: If P1 is a pseudo-cursor and P2 is dynamically ** allocated, then ownership of P2 is transferred to the pseudo-cursor ** and register P2 becomes ephemeral. If the cursor is changed, the ** value of register P2 will then change. Make sure this does not ** cause any problems.) ** ** This instruction only works on tables. The equivalent instruction ** for indices is OP_IdxInsert. */ /* Opcode: InsertInt P1 P2 P3 P4 P5 ** Synopsis: intkey=P3 data=r[P2] ** ** This works exactly like OP_Insert except that the key is the ** integer value P3, not the value of the integer stored in register P3. */ case OP_Insert: case OP_InsertInt: { Mem *pData; /* MEM cell holding data for the record to be inserted */ Mem *pKey; /* MEM cell holding key for the record */ VdbeCursor *pC; /* Cursor to table into which insert is written */ int seekResult; /* Result of prior seek or 0 if no USESEEKRESULT flag */ const char *zDb; /* database name - used by the update hook */ Table *pTab; /* Table structure - used by update and pre-update hooks */ int op; /* Opcode for update hook: SQLITE_UPDATE or SQLITE_INSERT */ BtreePayload x; /* Payload to be inserted */ op = 0; pData = &aMem[pOp->p2]; assert( pOp->p1>=0 && pOp->p1nCursor ); assert( memIsValid(pData) ); pC = p->apCsr[pOp->p1]; assert( pC!=0 ); assert( pC->eCurType==CURTYPE_BTREE ); assert( pC->uc.pCursor!=0 ); assert( pC->isTable ); assert( pOp->p4type==P4_TABLE || pOp->p4type>=P4_STATIC ); REGISTER_TRACE(pOp->p2, pData); if( pOp->opcode==OP_Insert ){ pKey = &aMem[pOp->p3]; assert( pKey->flags & MEM_Int ); assert( memIsValid(pKey) ); REGISTER_TRACE(pOp->p3, pKey); x.nKey = pKey->u.i; }else{ assert( pOp->opcode==OP_InsertInt ); x.nKey = pOp->p3; } if( pOp->p4type==P4_TABLE && HAS_UPDATE_HOOK(db) ){ assert( pC->isTable ); assert( pC->iDb>=0 ); zDb = db->aDb[pC->iDb].zDbSName; pTab = pOp->p4.pTab; assert( HasRowid(pTab) ); op = ((pOp->p5 & OPFLAG_ISUPDATE) ? SQLITE_UPDATE : SQLITE_INSERT); }else{ pTab = 0; /* Not needed. Silence a comiler warning. */ zDb = 0; /* Not needed. Silence a compiler warning. */ } #ifdef SQLITE_ENABLE_PREUPDATE_HOOK /* Invoke the pre-update hook, if any */ if( db->xPreUpdateCallback && pOp->p4type==P4_TABLE && !(pOp->p5 & OPFLAG_ISUPDATE) ){ sqlite3VdbePreUpdateHook(p, pC, SQLITE_INSERT, zDb, pTab, x.nKey, pOp->p2); } #endif if( pOp->p5 & OPFLAG_NCHANGE ) p->nChange++; if( pOp->p5 & OPFLAG_LASTROWID ) db->lastRowid = lastRowid = x.nKey; if( pData->flags & MEM_Null ){ x.pData = 0; x.nData = 0; }else{ assert( pData->flags & (MEM_Blob|MEM_Str) ); x.pData = pData->z; x.nData = pData->n; } seekResult = ((pOp->p5 & OPFLAG_USESEEKRESULT) ? pC->seekResult : 0); if( pData->flags & MEM_Zero ){ x.nZero = pData->u.nZero; }else{ x.nZero = 0; } x.pKey = 0; rc = sqlite3BtreeInsert(pC->uc.pCursor, &x, (pOp->p5 & OPFLAG_APPEND)!=0, seekResult ); pC->deferredMoveto = 0; pC->cacheStatus = CACHE_STALE; /* Invoke the update-hook if required. */ if( rc ) goto abort_due_to_error; if( db->xUpdateCallback && op ){ db->xUpdateCallback(db->pUpdateArg, op, zDb, pTab->zName, x.nKey); } break; } /* Opcode: Delete P1 P2 P3 P4 P5 ** ** Delete the record at which the P1 cursor is currently pointing. ** ** If the OPFLAG_SAVEPOSITION bit of the P5 parameter is set, then ** the cursor will be left pointing at either the next or the previous ** record in the table. If it is left pointing at the next record, then ** the next Next instruction will be a no-op. As a result, in this case ** it is ok to delete a record from within a Next loop. If ** OPFLAG_SAVEPOSITION bit of P5 is clear, then the cursor will be ** left in an undefined state. ** ** If the OPFLAG_AUXDELETE bit is set on P5, that indicates that this ** delete one of several associated with deleting a table row and all its ** associated index entries. Exactly one of those deletes is the "primary" ** delete. The others are all on OPFLAG_FORDELETE cursors or else are ** marked with the AUXDELETE flag. ** ** If the OPFLAG_NCHANGE flag of P2 (NB: P2 not P5) is set, then the row ** change count is incremented (otherwise not). ** ** P1 must not be pseudo-table. It has to be a real table with ** multiple rows. ** ** If P4 is not NULL then it points to a Table object. In this case either ** the update or pre-update hook, or both, may be invoked. The P1 cursor must ** have been positioned using OP_NotFound prior to invoking this opcode in ** this case. Specifically, if one is configured, the pre-update hook is ** invoked if P4 is not NULL. The update-hook is invoked if one is configured, ** P4 is not NULL, and the OPFLAG_NCHANGE flag is set in P2. ** ** If the OPFLAG_ISUPDATE flag is set in P2, then P3 contains the address ** of the memory cell that contains the value that the rowid of the row will ** be set to by the update. */ case OP_Delete: { VdbeCursor *pC; const char *zDb; Table *pTab; int opflags; opflags = pOp->p2; assert( pOp->p1>=0 && pOp->p1nCursor ); pC = p->apCsr[pOp->p1]; assert( pC!=0 ); assert( pC->eCurType==CURTYPE_BTREE ); assert( pC->uc.pCursor!=0 ); assert( pC->deferredMoveto==0 ); #ifdef SQLITE_DEBUG if( pOp->p4type==P4_TABLE && HasRowid(pOp->p4.pTab) && pOp->p5==0 ){ /* If p5 is zero, the seek operation that positioned the cursor prior to ** OP_Delete will have also set the pC->movetoTarget field to the rowid of ** the row that is being deleted */ i64 iKey = sqlite3BtreeIntegerKey(pC->uc.pCursor); assert( pC->movetoTarget==iKey ); } #endif /* If the update-hook or pre-update-hook will be invoked, set zDb to ** the name of the db to pass as to it. Also set local pTab to a copy ** of p4.pTab. Finally, if p5 is true, indicating that this cursor was ** last moved with OP_Next or OP_Prev, not Seek or NotFound, set ** VdbeCursor.movetoTarget to the current rowid. */ if( pOp->p4type==P4_TABLE && HAS_UPDATE_HOOK(db) ){ assert( pC->iDb>=0 ); assert( pOp->p4.pTab!=0 ); zDb = db->aDb[pC->iDb].zDbSName; pTab = pOp->p4.pTab; if( (pOp->p5 & OPFLAG_SAVEPOSITION)!=0 && pC->isTable ){ pC->movetoTarget = sqlite3BtreeIntegerKey(pC->uc.pCursor); } }else{ zDb = 0; /* Not needed. Silence a compiler warning. */ pTab = 0; /* Not needed. Silence a compiler warning. */ } #ifdef SQLITE_ENABLE_PREUPDATE_HOOK /* Invoke the pre-update-hook if required. */ if( db->xPreUpdateCallback && pOp->p4.pTab && HasRowid(pTab) ){ assert( !(opflags & OPFLAG_ISUPDATE) || (aMem[pOp->p3].flags & MEM_Int) ); sqlite3VdbePreUpdateHook(p, pC, (opflags & OPFLAG_ISUPDATE) ? SQLITE_UPDATE : SQLITE_DELETE, zDb, pTab, pC->movetoTarget, pOp->p3 ); } if( opflags & OPFLAG_ISNOOP ) break; #endif /* Only flags that can be set are SAVEPOISTION and AUXDELETE */ assert( (pOp->p5 & ~(OPFLAG_SAVEPOSITION|OPFLAG_AUXDELETE))==0 ); assert( OPFLAG_SAVEPOSITION==BTREE_SAVEPOSITION ); assert( OPFLAG_AUXDELETE==BTREE_AUXDELETE ); #ifdef SQLITE_DEBUG if( p->pFrame==0 ){ if( pC->isEphemeral==0 && (pOp->p5 & OPFLAG_AUXDELETE)==0 && (pC->wrFlag & OPFLAG_FORDELETE)==0 ){ nExtraDelete++; } if( pOp->p2 & OPFLAG_NCHANGE ){ nExtraDelete--; } } #endif rc = sqlite3BtreeDelete(pC->uc.pCursor, pOp->p5); pC->cacheStatus = CACHE_STALE; if( rc ) goto abort_due_to_error; /* Invoke the update-hook if required. */ if( opflags & OPFLAG_NCHANGE ){ p->nChange++; if( db->xUpdateCallback && HasRowid(pTab) ){ db->xUpdateCallback(db->pUpdateArg, SQLITE_DELETE, zDb, pTab->zName, pC->movetoTarget); assert( pC->iDb>=0 ); } } break; } /* Opcode: ResetCount * * * * * ** ** The value of the change counter is copied to the database handle ** change counter (returned by subsequent calls to sqlite3_changes()). ** Then the VMs internal change counter resets to 0. ** This is used by trigger programs. */ case OP_ResetCount: { sqlite3VdbeSetChanges(db, p->nChange); p->nChange = 0; break; } /* Opcode: SorterCompare P1 P2 P3 P4 ** Synopsis: if key(P1)!=trim(r[P3],P4) goto P2 ** ** P1 is a sorter cursor. This instruction compares a prefix of the ** record blob in register P3 against a prefix of the entry that ** the sorter cursor currently points to. Only the first P4 fields ** of r[P3] and the sorter record are compared. ** ** If either P3 or the sorter contains a NULL in one of their significant ** fields (not counting the P4 fields at the end which are ignored) then ** the comparison is assumed to be equal. ** ** Fall through to next instruction if the two records compare equal to ** each other. Jump to P2 if they are different. */ case OP_SorterCompare: { VdbeCursor *pC; int res; int nKeyCol; pC = p->apCsr[pOp->p1]; assert( isSorter(pC) ); assert( pOp->p4type==P4_INT32 ); pIn3 = &aMem[pOp->p3]; nKeyCol = pOp->p4.i; res = 0; rc = sqlite3VdbeSorterCompare(pC, pIn3, nKeyCol, &res); VdbeBranchTaken(res!=0,2); if( rc ) goto abort_due_to_error; if( res ) goto jump_to_p2; break; }; /* Opcode: SorterData P1 P2 P3 * * ** Synopsis: r[P2]=data ** ** Write into register P2 the current sorter data for sorter cursor P1. ** Then clear the column header cache on cursor P3. ** ** This opcode is normally use to move a record out of the sorter and into ** a register that is the source for a pseudo-table cursor created using ** OpenPseudo. That pseudo-table cursor is the one that is identified by ** parameter P3. Clearing the P3 column cache as part of this opcode saves ** us from having to issue a separate NullRow instruction to clear that cache. */ case OP_SorterData: { VdbeCursor *pC; pOut = &aMem[pOp->p2]; pC = p->apCsr[pOp->p1]; assert( isSorter(pC) ); rc = sqlite3VdbeSorterRowkey(pC, pOut); assert( rc!=SQLITE_OK || (pOut->flags & MEM_Blob) ); assert( pOp->p1>=0 && pOp->p1nCursor ); if( rc ) goto abort_due_to_error; p->apCsr[pOp->p3]->cacheStatus = CACHE_STALE; break; } /* Opcode: RowData P1 P2 * * * ** Synopsis: r[P2]=data ** ** Write into register P2 the complete row data for cursor P1. ** There is no interpretation of the data. ** It is just copied onto the P2 register exactly as ** it is found in the database file. ** ** If the P1 cursor must be pointing to a valid row (not a NULL row) ** of a real table, not a pseudo-table. */ /* Opcode: RowKey P1 P2 * * * ** Synopsis: r[P2]=key ** ** Write into register P2 the complete row key for cursor P1. ** There is no interpretation of the data. ** The key is copied onto the P2 register exactly as ** it is found in the database file. ** ** If the P1 cursor must be pointing to a valid row (not a NULL row) ** of a real table, not a pseudo-table. */ case OP_RowKey: case OP_RowData: { VdbeCursor *pC; BtCursor *pCrsr; u32 n; pOut = &aMem[pOp->p2]; memAboutToChange(p, pOut); /* Note that RowKey and RowData are really exactly the same instruction */ assert( pOp->p1>=0 && pOp->p1nCursor ); pC = p->apCsr[pOp->p1]; assert( pC!=0 ); assert( pC->eCurType==CURTYPE_BTREE ); assert( isSorter(pC)==0 ); assert( pC->isTable || pOp->opcode!=OP_RowData ); assert( pC->isTable==0 || pOp->opcode==OP_RowData ); assert( pC->nullRow==0 ); assert( pC->uc.pCursor!=0 ); pCrsr = pC->uc.pCursor; /* The OP_RowKey and OP_RowData opcodes always follow OP_NotExists or ** OP_SeekRowid or OP_Rewind/Op_Next with no intervening instructions ** that might invalidate the cursor. ** If this where not the case, on of the following assert()s ** would fail. Should this ever change (because of changes in the code ** generator) then the fix would be to insert a call to ** sqlite3VdbeCursorMoveto(). */ assert( pC->deferredMoveto==0 ); assert( sqlite3BtreeCursorIsValid(pCrsr) ); #if 0 /* Not required due to the previous to assert() statements */ rc = sqlite3VdbeCursorMoveto(pC); if( rc!=SQLITE_OK ) goto abort_due_to_error; #endif n = sqlite3BtreePayloadSize(pCrsr); if( n>(u32)db->aLimit[SQLITE_LIMIT_LENGTH] ){ goto too_big; } testcase( n==0 ); if( sqlite3VdbeMemClearAndResize(pOut, MAX(n,32)) ){ goto no_mem; } pOut->n = n; MemSetTypeFlag(pOut, MEM_Blob); if( pC->isTable==0 ){ rc = sqlite3BtreeKey(pCrsr, 0, n, pOut->z); }else{ rc = sqlite3BtreeData(pCrsr, 0, n, pOut->z); } if( rc ) goto abort_due_to_error; pOut->enc = SQLITE_UTF8; /* In case the blob is ever cast to text */ UPDATE_MAX_BLOBSIZE(pOut); REGISTER_TRACE(pOp->p2, pOut); break; } /* Opcode: Rowid P1 P2 * * * ** Synopsis: r[P2]=rowid ** ** Store in register P2 an integer which is the key of the table entry that ** P1 is currently point to. ** ** P1 can be either an ordinary table or a virtual table. There used to ** be a separate OP_VRowid opcode for use with virtual tables, but this ** one opcode now works for both table types. */ case OP_Rowid: { /* out2 */ VdbeCursor *pC; i64 v; sqlite3_vtab *pVtab; const sqlite3_module *pModule; pOut = out2Prerelease(p, pOp); assert( pOp->p1>=0 && pOp->p1nCursor ); pC = p->apCsr[pOp->p1]; assert( pC!=0 ); assert( pC->eCurType!=CURTYPE_PSEUDO || pC->nullRow ); if( pC->nullRow ){ pOut->flags = MEM_Null; break; }else if( pC->deferredMoveto ){ v = pC->movetoTarget; #ifndef SQLITE_OMIT_VIRTUALTABLE }else if( pC->eCurType==CURTYPE_VTAB ){ assert( pC->uc.pVCur!=0 ); pVtab = pC->uc.pVCur->pVtab; pModule = pVtab->pModule; assert( pModule->xRowid ); rc = pModule->xRowid(pC->uc.pVCur, &v); sqlite3VtabImportErrmsg(p, pVtab); if( rc ) goto abort_due_to_error; #endif /* SQLITE_OMIT_VIRTUALTABLE */ }else{ assert( pC->eCurType==CURTYPE_BTREE ); assert( pC->uc.pCursor!=0 ); rc = sqlite3VdbeCursorRestore(pC); if( rc ) goto abort_due_to_error; if( pC->nullRow ){ pOut->flags = MEM_Null; break; } v = sqlite3BtreeIntegerKey(pC->uc.pCursor); } pOut->u.i = v; break; } /* Opcode: NullRow P1 * * * * ** ** Move the cursor P1 to a null row. Any OP_Column operations ** that occur while the cursor is on the null row will always ** write a NULL. */ case OP_NullRow: { VdbeCursor *pC; assert( pOp->p1>=0 && pOp->p1nCursor ); pC = p->apCsr[pOp->p1]; assert( pC!=0 ); pC->nullRow = 1; pC->cacheStatus = CACHE_STALE; if( pC->eCurType==CURTYPE_BTREE ){ assert( pC->uc.pCursor!=0 ); sqlite3BtreeClearCursor(pC->uc.pCursor); } break; } /* Opcode: Last P1 P2 P3 * * ** ** The next use of the Rowid or Column or Prev instruction for P1 ** will refer to the last entry in the database table or index. ** If the table or index is empty and P2>0, then jump immediately to P2. ** If P2 is 0 or if the table or index is not empty, fall through ** to the following instruction. ** ** This opcode leaves the cursor configured to move in reverse order, ** from the end toward the beginning. In other words, the cursor is ** configured to use Prev, not Next. */ case OP_Last: { /* jump */ VdbeCursor *pC; BtCursor *pCrsr; int res; assert( pOp->p1>=0 && pOp->p1nCursor ); pC = p->apCsr[pOp->p1]; assert( pC!=0 ); assert( pC->eCurType==CURTYPE_BTREE ); pCrsr = pC->uc.pCursor; res = 0; assert( pCrsr!=0 ); rc = sqlite3BtreeLast(pCrsr, &res); pC->nullRow = (u8)res; pC->deferredMoveto = 0; pC->cacheStatus = CACHE_STALE; pC->seekResult = pOp->p3; #ifdef SQLITE_DEBUG pC->seekOp = OP_Last; #endif if( rc ) goto abort_due_to_error; if( pOp->p2>0 ){ VdbeBranchTaken(res!=0,2); if( res ) goto jump_to_p2; } break; } /* Opcode: Sort P1 P2 * * * ** ** This opcode does exactly the same thing as OP_Rewind except that ** it increments an undocumented global variable used for testing. ** ** Sorting is accomplished by writing records into a sorting index, ** then rewinding that index and playing it back from beginning to ** end. We use the OP_Sort opcode instead of OP_Rewind to do the ** rewinding so that the global variable will be incremented and ** regression tests can determine whether or not the optimizer is ** correctly optimizing out sorts. */ case OP_SorterSort: /* jump */ case OP_Sort: { /* jump */ #ifdef SQLITE_TEST sqlite3_sort_count++; sqlite3_search_count--; #endif p->aCounter[SQLITE_STMTSTATUS_SORT]++; /* Fall through into OP_Rewind */ } /* Opcode: Rewind P1 P2 * * * ** ** The next use of the Rowid or Column or Next instruction for P1 ** will refer to the first entry in the database table or index. ** If the table or index is empty, jump immediately to P2. ** If the table or index is not empty, fall through to the following ** instruction. ** ** This opcode leaves the cursor configured to move in forward order, ** from the beginning toward the end. In other words, the cursor is ** configured to use Next, not Prev. */ case OP_Rewind: { /* jump */ VdbeCursor *pC; BtCursor *pCrsr; int res; assert( pOp->p1>=0 && pOp->p1nCursor ); pC = p->apCsr[pOp->p1]; assert( pC!=0 ); assert( isSorter(pC)==(pOp->opcode==OP_SorterSort) ); res = 1; #ifdef SQLITE_DEBUG pC->seekOp = OP_Rewind; #endif if( isSorter(pC) ){ rc = sqlite3VdbeSorterRewind(pC, &res); }else{ assert( pC->eCurType==CURTYPE_BTREE ); pCrsr = pC->uc.pCursor; assert( pCrsr ); rc = sqlite3BtreeFirst(pCrsr, &res); pC->deferredMoveto = 0; pC->cacheStatus = CACHE_STALE; } if( rc ) goto abort_due_to_error; pC->nullRow = (u8)res; assert( pOp->p2>0 && pOp->p2nOp ); VdbeBranchTaken(res!=0,2); if( res ) goto jump_to_p2; break; } /* Opcode: Next P1 P2 P3 P4 P5 ** ** Advance cursor P1 so that it points to the next key/data pair in its ** table or index. If there are no more key/value pairs then fall through ** to the following instruction. But if the cursor advance was successful, ** jump immediately to P2. ** ** The Next opcode is only valid following an SeekGT, SeekGE, or ** OP_Rewind opcode used to position the cursor. Next is not allowed ** to follow SeekLT, SeekLE, or OP_Last. ** ** The P1 cursor must be for a real table, not a pseudo-table. P1 must have ** been opened prior to this opcode or the program will segfault. ** ** The P3 value is a hint to the btree implementation. If P3==1, that ** means P1 is an SQL index and that this instruction could have been ** omitted if that index had been unique. P3 is usually 0. P3 is ** always either 0 or 1. ** ** P4 is always of type P4_ADVANCE. The function pointer points to ** sqlite3BtreeNext(). ** ** If P5 is positive and the jump is taken, then event counter ** number P5-1 in the prepared statement is incremented. ** ** See also: Prev, NextIfOpen */ /* Opcode: NextIfOpen P1 P2 P3 P4 P5 ** ** This opcode works just like Next except that if cursor P1 is not ** open it behaves a no-op. */ /* Opcode: Prev P1 P2 P3 P4 P5 ** ** Back up cursor P1 so that it points to the previous key/data pair in its ** table or index. If there is no previous key/value pairs then fall through ** to the following instruction. But if the cursor backup was successful, ** jump immediately to P2. ** ** ** The Prev opcode is only valid following an SeekLT, SeekLE, or ** OP_Last opcode used to position the cursor. Prev is not allowed ** to follow SeekGT, SeekGE, or OP_Rewind. ** ** The P1 cursor must be for a real table, not a pseudo-table. If P1 is ** not open then the behavior is undefined. ** ** The P3 value is a hint to the btree implementation. If P3==1, that ** means P1 is an SQL index and that this instruction could have been ** omitted if that index had been unique. P3 is usually 0. P3 is ** always either 0 or 1. ** ** P4 is always of type P4_ADVANCE. The function pointer points to ** sqlite3BtreePrevious(). ** ** If P5 is positive and the jump is taken, then event counter ** number P5-1 in the prepared statement is incremented. */ /* Opcode: PrevIfOpen P1 P2 P3 P4 P5 ** ** This opcode works just like Prev except that if cursor P1 is not ** open it behaves a no-op. */ case OP_SorterNext: { /* jump */ VdbeCursor *pC; int res; pC = p->apCsr[pOp->p1]; assert( isSorter(pC) ); res = 0; rc = sqlite3VdbeSorterNext(db, pC, &res); goto next_tail; case OP_PrevIfOpen: /* jump */ case OP_NextIfOpen: /* jump */ if( p->apCsr[pOp->p1]==0 ) break; /* Fall through */ case OP_Prev: /* jump */ case OP_Next: /* jump */ assert( pOp->p1>=0 && pOp->p1nCursor ); assert( pOp->p5aCounter) ); pC = p->apCsr[pOp->p1]; res = pOp->p3; assert( pC!=0 ); assert( pC->deferredMoveto==0 ); assert( pC->eCurType==CURTYPE_BTREE ); assert( res==0 || (res==1 && pC->isTable==0) ); testcase( res==1 ); assert( pOp->opcode!=OP_Next || pOp->p4.xAdvance==sqlite3BtreeNext ); assert( pOp->opcode!=OP_Prev || pOp->p4.xAdvance==sqlite3BtreePrevious ); assert( pOp->opcode!=OP_NextIfOpen || pOp->p4.xAdvance==sqlite3BtreeNext ); assert( pOp->opcode!=OP_PrevIfOpen || pOp->p4.xAdvance==sqlite3BtreePrevious); /* The Next opcode is only used after SeekGT, SeekGE, and Rewind. ** The Prev opcode is only used after SeekLT, SeekLE, and Last. */ assert( pOp->opcode!=OP_Next || pOp->opcode!=OP_NextIfOpen || pC->seekOp==OP_SeekGT || pC->seekOp==OP_SeekGE || pC->seekOp==OP_Rewind || pC->seekOp==OP_Found); assert( pOp->opcode!=OP_Prev || pOp->opcode!=OP_PrevIfOpen || pC->seekOp==OP_SeekLT || pC->seekOp==OP_SeekLE || pC->seekOp==OP_Last ); rc = pOp->p4.xAdvance(pC->uc.pCursor, &res); next_tail: pC->cacheStatus = CACHE_STALE; VdbeBranchTaken(res==0,2); if( rc ) goto abort_due_to_error; if( res==0 ){ pC->nullRow = 0; p->aCounter[pOp->p5]++; #ifdef SQLITE_TEST sqlite3_search_count++; #endif goto jump_to_p2_and_check_for_interrupt; }else{ pC->nullRow = 1; } goto check_for_interrupt; } /* Opcode: IdxInsert P1 P2 P3 * P5 ** Synopsis: key=r[P2] ** ** Register P2 holds an SQL index key made using the ** MakeRecord instructions. This opcode writes that key ** into the index P1. Data for the entry is nil. ** ** P3 is a flag that provides a hint to the b-tree layer that this ** insert is likely to be an append. ** ** If P5 has the OPFLAG_NCHANGE bit set, then the change counter is ** incremented by this instruction. If the OPFLAG_NCHANGE bit is clear, ** then the change counter is unchanged. ** ** If P5 has the OPFLAG_USESEEKRESULT bit set, then the cursor must have ** just done a seek to the spot where the new entry is to be inserted. ** This flag avoids doing an extra seek. ** ** This instruction only works for indices. The equivalent instruction ** for tables is OP_Insert. */ case OP_SorterInsert: /* in2 */ case OP_IdxInsert: { /* in2 */ VdbeCursor *pC; BtreePayload x; assert( pOp->p1>=0 && pOp->p1nCursor ); pC = p->apCsr[pOp->p1]; assert( pC!=0 ); assert( isSorter(pC)==(pOp->opcode==OP_SorterInsert) ); pIn2 = &aMem[pOp->p2]; assert( pIn2->flags & MEM_Blob ); if( pOp->p5 & OPFLAG_NCHANGE ) p->nChange++; assert( pC->eCurType==CURTYPE_BTREE || pOp->opcode==OP_SorterInsert ); assert( pC->isTable==0 ); rc = ExpandBlob(pIn2); if( rc ) goto abort_due_to_error; if( pOp->opcode==OP_SorterInsert ){ rc = sqlite3VdbeSorterWrite(pC, pIn2); }else{ x.nKey = pIn2->n; x.pKey = pIn2->z; rc = sqlite3BtreeInsert(pC->uc.pCursor, &x, pOp->p3, ((pOp->p5 & OPFLAG_USESEEKRESULT) ? pC->seekResult : 0) ); assert( pC->deferredMoveto==0 ); pC->cacheStatus = CACHE_STALE; } if( rc) goto abort_due_to_error; break; } /* Opcode: IdxDelete P1 P2 P3 * * ** Synopsis: key=r[P2@P3] ** ** The content of P3 registers starting at register P2 form ** an unpacked index key. This opcode removes that entry from the ** index opened by cursor P1. */ case OP_IdxDelete: { VdbeCursor *pC; BtCursor *pCrsr; int res; UnpackedRecord r; assert( pOp->p3>0 ); assert( pOp->p2>0 && pOp->p2+pOp->p3<=(p->nMem+1 - p->nCursor)+1 ); assert( pOp->p1>=0 && pOp->p1nCursor ); pC = p->apCsr[pOp->p1]; assert( pC!=0 ); assert( pC->eCurType==CURTYPE_BTREE ); pCrsr = pC->uc.pCursor; assert( pCrsr!=0 ); assert( pOp->p5==0 ); r.pKeyInfo = pC->pKeyInfo; r.nField = (u16)pOp->p3; r.default_rc = 0; r.aMem = &aMem[pOp->p2]; rc = sqlite3BtreeMovetoUnpacked(pCrsr, &r, 0, 0, &res); if( rc ) goto abort_due_to_error; if( res==0 ){ rc = sqlite3BtreeDelete(pCrsr, BTREE_AUXDELETE); if( rc ) goto abort_due_to_error; } assert( pC->deferredMoveto==0 ); pC->cacheStatus = CACHE_STALE; break; } /* Opcode: Seek P1 * P3 P4 * ** Synopsis: Move P3 to P1.rowid ** ** P1 is an open index cursor and P3 is a cursor on the corresponding ** table. This opcode does a deferred seek of the P3 table cursor ** to the row that corresponds to the current row of P1. ** ** This is a deferred seek. Nothing actually happens until ** the cursor is used to read a record. That way, if no reads ** occur, no unnecessary I/O happens. ** ** P4 may be an array of integers (type P4_INTARRAY) containing ** one entry for each column in the P3 table. If array entry a(i) ** is non-zero, then reading column a(i)-1 from cursor P3 is ** equivalent to performing the deferred seek and then reading column i ** from P1. This information is stored in P3 and used to redirect ** reads against P3 over to P1, thus possibly avoiding the need to ** seek and read cursor P3. */ /* Opcode: IdxRowid P1 P2 * * * ** Synopsis: r[P2]=rowid ** ** Write into register P2 an integer which is the last entry in the record at ** the end of the index key pointed to by cursor P1. This integer should be ** the rowid of the table entry to which this index entry points. ** ** See also: Rowid, MakeRecord. */ case OP_Seek: case OP_IdxRowid: { /* out2 */ VdbeCursor *pC; /* The P1 index cursor */ VdbeCursor *pTabCur; /* The P2 table cursor (OP_Seek only) */ i64 rowid; /* Rowid that P1 current points to */ assert( pOp->p1>=0 && pOp->p1nCursor ); pC = p->apCsr[pOp->p1]; assert( pC!=0 ); assert( pC->eCurType==CURTYPE_BTREE ); assert( pC->uc.pCursor!=0 ); assert( pC->isTable==0 ); assert( pC->deferredMoveto==0 ); assert( !pC->nullRow || pOp->opcode==OP_IdxRowid ); /* The IdxRowid and Seek opcodes are combined because of the commonality ** of sqlite3VdbeCursorRestore() and sqlite3VdbeIdxRowid(). */ rc = sqlite3VdbeCursorRestore(pC); /* sqlite3VbeCursorRestore() can only fail if the record has been deleted ** out from under the cursor. That will never happens for an IdxRowid ** or Seek opcode */ if( NEVER(rc!=SQLITE_OK) ) goto abort_due_to_error; if( !pC->nullRow ){ rowid = 0; /* Not needed. Only used to silence a warning. */ rc = sqlite3VdbeIdxRowid(db, pC->uc.pCursor, &rowid); if( rc!=SQLITE_OK ){ goto abort_due_to_error; } if( pOp->opcode==OP_Seek ){ assert( pOp->p3>=0 && pOp->p3nCursor ); pTabCur = p->apCsr[pOp->p3]; assert( pTabCur!=0 ); assert( pTabCur->eCurType==CURTYPE_BTREE ); assert( pTabCur->uc.pCursor!=0 ); assert( pTabCur->isTable ); pTabCur->nullRow = 0; pTabCur->movetoTarget = rowid; pTabCur->deferredMoveto = 1; assert( pOp->p4type==P4_INTARRAY || pOp->p4.ai==0 ); pTabCur->aAltMap = pOp->p4.ai; pTabCur->pAltCursor = pC; }else{ pOut = out2Prerelease(p, pOp); pOut->u.i = rowid; pOut->flags = MEM_Int; } }else{ assert( pOp->opcode==OP_IdxRowid ); sqlite3VdbeMemSetNull(&aMem[pOp->p2]); } break; } /* Opcode: IdxGE P1 P2 P3 P4 P5 ** Synopsis: key=r[P3@P4] ** ** The P4 register values beginning with P3 form an unpacked index ** key that omits the PRIMARY KEY. Compare this key value against the index ** that P1 is currently pointing to, ignoring the PRIMARY KEY or ROWID ** fields at the end. ** ** If the P1 index entry is greater than or equal to the key value ** then jump to P2. Otherwise fall through to the next instruction. */ /* Opcode: IdxGT P1 P2 P3 P4 P5 ** Synopsis: key=r[P3@P4] ** ** The P4 register values beginning with P3 form an unpacked index ** key that omits the PRIMARY KEY. Compare this key value against the index ** that P1 is currently pointing to, ignoring the PRIMARY KEY or ROWID ** fields at the end. ** ** If the P1 index entry is greater than the key value ** then jump to P2. Otherwise fall through to the next instruction. */ /* Opcode: IdxLT P1 P2 P3 P4 P5 ** Synopsis: key=r[P3@P4] ** ** The P4 register values beginning with P3 form an unpacked index ** key that omits the PRIMARY KEY or ROWID. Compare this key value against ** the index that P1 is currently pointing to, ignoring the PRIMARY KEY or ** ROWID on the P1 index. ** ** If the P1 index entry is less than the key value then jump to P2. ** Otherwise fall through to the next instruction. */ /* Opcode: IdxLE P1 P2 P3 P4 P5 ** Synopsis: key=r[P3@P4] ** ** The P4 register values beginning with P3 form an unpacked index ** key that omits the PRIMARY KEY or ROWID. Compare this key value against ** the index that P1 is currently pointing to, ignoring the PRIMARY KEY or ** ROWID on the P1 index. ** ** If the P1 index entry is less than or equal to the key value then jump ** to P2. Otherwise fall through to the next instruction. */ case OP_IdxLE: /* jump */ case OP_IdxGT: /* jump */ case OP_IdxLT: /* jump */ case OP_IdxGE: { /* jump */ VdbeCursor *pC; int res; UnpackedRecord r; assert( pOp->p1>=0 && pOp->p1nCursor ); pC = p->apCsr[pOp->p1]; assert( pC!=0 ); assert( pC->isOrdered ); assert( pC->eCurType==CURTYPE_BTREE ); assert( pC->uc.pCursor!=0); assert( pC->deferredMoveto==0 ); assert( pOp->p5==0 || pOp->p5==1 ); assert( pOp->p4type==P4_INT32 ); r.pKeyInfo = pC->pKeyInfo; r.nField = (u16)pOp->p4.i; if( pOp->opcodeopcode==OP_IdxLE || pOp->opcode==OP_IdxGT ); r.default_rc = -1; }else{ assert( pOp->opcode==OP_IdxGE || pOp->opcode==OP_IdxLT ); r.default_rc = 0; } r.aMem = &aMem[pOp->p3]; #ifdef SQLITE_DEBUG { int i; for(i=0; iopcode&1)==(OP_IdxLT&1) ){ assert( pOp->opcode==OP_IdxLE || pOp->opcode==OP_IdxLT ); res = -res; }else{ assert( pOp->opcode==OP_IdxGE || pOp->opcode==OP_IdxGT ); res++; } VdbeBranchTaken(res>0,2); if( rc ) goto abort_due_to_error; if( res>0 ) goto jump_to_p2; break; } /* Opcode: Destroy P1 P2 P3 * * ** ** Delete an entire database table or index whose root page in the database ** file is given by P1. ** ** The table being destroyed is in the main database file if P3==0. If ** P3==1 then the table to be clear is in the auxiliary database file ** that is used to store tables create using CREATE TEMPORARY TABLE. ** ** If AUTOVACUUM is enabled then it is possible that another root page ** might be moved into the newly deleted root page in order to keep all ** root pages contiguous at the beginning of the database. The former ** value of the root page that moved - its value before the move occurred - ** is stored in register P2. If no page ** movement was required (because the table being dropped was already ** the last one in the database) then a zero is stored in register P2. ** If AUTOVACUUM is disabled then a zero is stored in register P2. ** ** See also: Clear */ case OP_Destroy: { /* out2 */ int iMoved; int iDb; assert( p->readOnly==0 ); assert( pOp->p1>1 ); pOut = out2Prerelease(p, pOp); pOut->flags = MEM_Null; if( db->nVdbeRead > db->nVDestroy+1 ){ rc = SQLITE_LOCKED; p->errorAction = OE_Abort; goto abort_due_to_error; }else{ iDb = pOp->p3; assert( DbMaskTest(p->btreeMask, iDb) ); iMoved = 0; /* Not needed. Only to silence a warning. */ rc = sqlite3BtreeDropTable(db->aDb[iDb].pBt, pOp->p1, &iMoved); pOut->flags = MEM_Int; pOut->u.i = iMoved; if( rc ) goto abort_due_to_error; #ifndef SQLITE_OMIT_AUTOVACUUM if( iMoved!=0 ){ sqlite3RootPageMoved(db, iDb, iMoved, pOp->p1); /* All OP_Destroy operations occur on the same btree */ assert( resetSchemaOnFault==0 || resetSchemaOnFault==iDb+1 ); resetSchemaOnFault = iDb+1; } #endif } break; } /* Opcode: Clear P1 P2 P3 ** ** Delete all contents of the database table or index whose root page ** in the database file is given by P1. But, unlike Destroy, do not ** remove the table or index from the database file. ** ** The table being clear is in the main database file if P2==0. If ** P2==1 then the table to be clear is in the auxiliary database file ** that is used to store tables create using CREATE TEMPORARY TABLE. ** ** If the P3 value is non-zero, then the table referred to must be an ** intkey table (an SQL table, not an index). In this case the row change ** count is incremented by the number of rows in the table being cleared. ** If P3 is greater than zero, then the value stored in register P3 is ** also incremented by the number of rows in the table being cleared. ** ** See also: Destroy */ case OP_Clear: { int nChange; nChange = 0; assert( p->readOnly==0 ); assert( DbMaskTest(p->btreeMask, pOp->p2) ); rc = sqlite3BtreeClearTable( db->aDb[pOp->p2].pBt, pOp->p1, (pOp->p3 ? &nChange : 0) ); if( pOp->p3 ){ p->nChange += nChange; if( pOp->p3>0 ){ assert( memIsValid(&aMem[pOp->p3]) ); memAboutToChange(p, &aMem[pOp->p3]); aMem[pOp->p3].u.i += nChange; } } if( rc ) goto abort_due_to_error; break; } /* Opcode: ResetSorter P1 * * * * ** ** Delete all contents from the ephemeral table or sorter ** that is open on cursor P1. ** ** This opcode only works for cursors used for sorting and ** opened with OP_OpenEphemeral or OP_SorterOpen. */ case OP_ResetSorter: { VdbeCursor *pC; assert( pOp->p1>=0 && pOp->p1nCursor ); pC = p->apCsr[pOp->p1]; assert( pC!=0 ); if( isSorter(pC) ){ sqlite3VdbeSorterReset(db, pC->uc.pSorter); }else{ assert( pC->eCurType==CURTYPE_BTREE ); assert( pC->isEphemeral ); rc = sqlite3BtreeClearTableOfCursor(pC->uc.pCursor); if( rc ) goto abort_due_to_error; } break; } /* Opcode: CreateTable P1 P2 * * * ** Synopsis: r[P2]=root iDb=P1 ** ** Allocate a new table in the main database file if P1==0 or in the ** auxiliary database file if P1==1 or in an attached database if ** P1>1. Write the root page number of the new table into ** register P2 ** ** The difference between a table and an index is this: A table must ** have a 4-byte integer key and can have arbitrary data. An index ** has an arbitrary key but no data. ** ** See also: CreateIndex */ /* Opcode: CreateIndex P1 P2 * * * ** Synopsis: r[P2]=root iDb=P1 ** ** Allocate a new index in the main database file if P1==0 or in the ** auxiliary database file if P1==1 or in an attached database if ** P1>1. Write the root page number of the new table into ** register P2. ** ** See documentation on OP_CreateTable for additional information. */ case OP_CreateIndex: /* out2 */ case OP_CreateTable: { /* out2 */ int pgno; int flags; Db *pDb; pOut = out2Prerelease(p, pOp); pgno = 0; assert( pOp->p1>=0 && pOp->p1nDb ); assert( DbMaskTest(p->btreeMask, pOp->p1) ); assert( p->readOnly==0 ); pDb = &db->aDb[pOp->p1]; assert( pDb->pBt!=0 ); if( pOp->opcode==OP_CreateTable ){ /* flags = BTREE_INTKEY; */ flags = BTREE_INTKEY; }else{ flags = BTREE_BLOBKEY; } rc = sqlite3BtreeCreateTable(pDb->pBt, &pgno, flags); if( rc ) goto abort_due_to_error; pOut->u.i = pgno; break; } /* Opcode: ParseSchema P1 * * P4 * ** ** Read and parse all entries from the SQLITE_MASTER table of database P1 ** that match the WHERE clause P4. ** ** This opcode invokes the parser to create a new virtual machine, ** then runs the new virtual machine. It is thus a re-entrant opcode. */ case OP_ParseSchema: { int iDb; const char *zMaster; char *zSql; InitData initData; /* Any prepared statement that invokes this opcode will hold mutexes ** on every btree. This is a prerequisite for invoking ** sqlite3InitCallback(). */ #ifdef SQLITE_DEBUG for(iDb=0; iDbnDb; iDb++){ assert( iDb==1 || sqlite3BtreeHoldsMutex(db->aDb[iDb].pBt) ); } #endif iDb = pOp->p1; assert( iDb>=0 && iDbnDb ); assert( DbHasProperty(db, iDb, DB_SchemaLoaded) ); /* Used to be a conditional */ { zMaster = SCHEMA_TABLE(iDb); initData.db = db; initData.iDb = pOp->p1; initData.pzErrMsg = &p->zErrMsg; zSql = sqlite3MPrintf(db, "SELECT name, rootpage, sql FROM '%q'.%s WHERE %s ORDER BY rowid", db->aDb[iDb].zDbSName, zMaster, pOp->p4.z); if( zSql==0 ){ rc = SQLITE_NOMEM_BKPT; }else{ assert( db->init.busy==0 ); db->init.busy = 1; initData.rc = SQLITE_OK; assert( !db->mallocFailed ); rc = sqlite3_exec(db, zSql, sqlite3InitCallback, &initData, 0); if( rc==SQLITE_OK ) rc = initData.rc; sqlite3DbFree(db, zSql); db->init.busy = 0; } } if( rc ){ sqlite3ResetAllSchemasOfConnection(db); if( rc==SQLITE_NOMEM ){ goto no_mem; } goto abort_due_to_error; } break; } #if !defined(SQLITE_OMIT_ANALYZE) /* Opcode: LoadAnalysis P1 * * * * ** ** Read the sqlite_stat1 table for database P1 and load the content ** of that table into the internal index hash table. This will cause ** the analysis to be used when preparing all subsequent queries. */ case OP_LoadAnalysis: { assert( pOp->p1>=0 && pOp->p1nDb ); rc = sqlite3AnalysisLoad(db, pOp->p1); if( rc ) goto abort_due_to_error; break; } #endif /* !defined(SQLITE_OMIT_ANALYZE) */ /* Opcode: DropTable P1 * * P4 * ** ** Remove the internal (in-memory) data structures that describe ** the table named P4 in database P1. This is called after a table ** is dropped from disk (using the Destroy opcode) in order to keep ** the internal representation of the ** schema consistent with what is on disk. */ case OP_DropTable: { sqlite3UnlinkAndDeleteTable(db, pOp->p1, pOp->p4.z); break; } /* Opcode: DropIndex P1 * * P4 * ** ** Remove the internal (in-memory) data structures that describe ** the index named P4 in database P1. This is called after an index ** is dropped from disk (using the Destroy opcode) ** in order to keep the internal representation of the ** schema consistent with what is on disk. */ case OP_DropIndex: { sqlite3UnlinkAndDeleteIndex(db, pOp->p1, pOp->p4.z); break; } /* Opcode: DropTrigger P1 * * P4 * ** ** Remove the internal (in-memory) data structures that describe ** the trigger named P4 in database P1. This is called after a trigger ** is dropped from disk (using the Destroy opcode) in order to keep ** the internal representation of the ** schema consistent with what is on disk. */ case OP_DropTrigger: { sqlite3UnlinkAndDeleteTrigger(db, pOp->p1, pOp->p4.z); break; } #ifndef SQLITE_OMIT_INTEGRITY_CHECK /* Opcode: IntegrityCk P1 P2 P3 P4 P5 ** ** Do an analysis of the currently open database. Store in ** register P1 the text of an error message describing any problems. ** If no problems are found, store a NULL in register P1. ** ** The register P3 contains the maximum number of allowed errors. ** At most reg(P3) errors will be reported. ** In other words, the analysis stops as soon as reg(P1) errors are ** seen. Reg(P1) is updated with the number of errors remaining. ** ** The root page numbers of all tables in the database are integers ** stored in P4_INTARRAY argument. ** ** If P5 is not zero, the check is done on the auxiliary database ** file, not the main database file. ** ** This opcode is used to implement the integrity_check pragma. */ case OP_IntegrityCk: { int nRoot; /* Number of tables to check. (Number of root pages.) */ int *aRoot; /* Array of rootpage numbers for tables to be checked */ int nErr; /* Number of errors reported */ char *z; /* Text of the error report */ Mem *pnErr; /* Register keeping track of errors remaining */ assert( p->bIsReader ); nRoot = pOp->p2; aRoot = pOp->p4.ai; assert( nRoot>0 ); assert( aRoot[nRoot]==0 ); assert( pOp->p3>0 && pOp->p3<=(p->nMem+1 - p->nCursor) ); pnErr = &aMem[pOp->p3]; assert( (pnErr->flags & MEM_Int)!=0 ); assert( (pnErr->flags & (MEM_Str|MEM_Blob))==0 ); pIn1 = &aMem[pOp->p1]; assert( pOp->p5nDb ); assert( DbMaskTest(p->btreeMask, pOp->p5) ); z = sqlite3BtreeIntegrityCheck(db->aDb[pOp->p5].pBt, aRoot, nRoot, (int)pnErr->u.i, &nErr); pnErr->u.i -= nErr; sqlite3VdbeMemSetNull(pIn1); if( nErr==0 ){ assert( z==0 ); }else if( z==0 ){ goto no_mem; }else{ sqlite3VdbeMemSetStr(pIn1, z, -1, SQLITE_UTF8, sqlite3_free); } UPDATE_MAX_BLOBSIZE(pIn1); sqlite3VdbeChangeEncoding(pIn1, encoding); break; } #endif /* SQLITE_OMIT_INTEGRITY_CHECK */ /* Opcode: RowSetAdd P1 P2 * * * ** Synopsis: rowset(P1)=r[P2] ** ** Insert the integer value held by register P2 into a boolean index ** held in register P1. ** ** An assertion fails if P2 is not an integer. */ case OP_RowSetAdd: { /* in1, in2 */ pIn1 = &aMem[pOp->p1]; pIn2 = &aMem[pOp->p2]; assert( (pIn2->flags & MEM_Int)!=0 ); if( (pIn1->flags & MEM_RowSet)==0 ){ sqlite3VdbeMemSetRowSet(pIn1); if( (pIn1->flags & MEM_RowSet)==0 ) goto no_mem; } sqlite3RowSetInsert(pIn1->u.pRowSet, pIn2->u.i); break; } /* Opcode: RowSetRead P1 P2 P3 * * ** Synopsis: r[P3]=rowset(P1) ** ** Extract the smallest value from boolean index P1 and put that value into ** register P3. Or, if boolean index P1 is initially empty, leave P3 ** unchanged and jump to instruction P2. */ case OP_RowSetRead: { /* jump, in1, out3 */ i64 val; pIn1 = &aMem[pOp->p1]; if( (pIn1->flags & MEM_RowSet)==0 || sqlite3RowSetNext(pIn1->u.pRowSet, &val)==0 ){ /* The boolean index is empty */ sqlite3VdbeMemSetNull(pIn1); VdbeBranchTaken(1,2); goto jump_to_p2_and_check_for_interrupt; }else{ /* A value was pulled from the index */ VdbeBranchTaken(0,2); sqlite3VdbeMemSetInt64(&aMem[pOp->p3], val); } goto check_for_interrupt; } /* Opcode: RowSetTest P1 P2 P3 P4 ** Synopsis: if r[P3] in rowset(P1) goto P2 ** ** Register P3 is assumed to hold a 64-bit integer value. If register P1 ** contains a RowSet object and that RowSet object contains ** the value held in P3, jump to register P2. Otherwise, insert the ** integer in P3 into the RowSet and continue on to the ** next opcode. ** ** The RowSet object is optimized for the case where successive sets ** of integers, where each set contains no duplicates. Each set ** of values is identified by a unique P4 value. The first set ** must have P4==0, the final set P4=-1. P4 must be either -1 or ** non-negative. For non-negative values of P4 only the lower 4 ** bits are significant. ** ** This allows optimizations: (a) when P4==0 there is no need to test ** the rowset object for P3, as it is guaranteed not to contain it, ** (b) when P4==-1 there is no need to insert the value, as it will ** never be tested for, and (c) when a value that is part of set X is ** inserted, there is no need to search to see if the same value was ** previously inserted as part of set X (only if it was previously ** inserted as part of some other set). */ case OP_RowSetTest: { /* jump, in1, in3 */ int iSet; int exists; pIn1 = &aMem[pOp->p1]; pIn3 = &aMem[pOp->p3]; iSet = pOp->p4.i; assert( pIn3->flags&MEM_Int ); /* If there is anything other than a rowset object in memory cell P1, ** delete it now and initialize P1 with an empty rowset */ if( (pIn1->flags & MEM_RowSet)==0 ){ sqlite3VdbeMemSetRowSet(pIn1); if( (pIn1->flags & MEM_RowSet)==0 ) goto no_mem; } assert( pOp->p4type==P4_INT32 ); assert( iSet==-1 || iSet>=0 ); if( iSet ){ exists = sqlite3RowSetTest(pIn1->u.pRowSet, iSet, pIn3->u.i); VdbeBranchTaken(exists!=0,2); if( exists ) goto jump_to_p2; } if( iSet>=0 ){ sqlite3RowSetInsert(pIn1->u.pRowSet, pIn3->u.i); } break; } #ifndef SQLITE_OMIT_TRIGGER /* Opcode: Program P1 P2 P3 P4 P5 ** ** Execute the trigger program passed as P4 (type P4_SUBPROGRAM). ** ** P1 contains the address of the memory cell that contains the first memory ** cell in an array of values used as arguments to the sub-program. P2 ** contains the address to jump to if the sub-program throws an IGNORE ** exception using the RAISE() function. Register P3 contains the address ** of a memory cell in this (the parent) VM that is used to allocate the ** memory required by the sub-vdbe at runtime. ** ** P4 is a pointer to the VM containing the trigger program. ** ** If P5 is non-zero, then recursive program invocation is enabled. */ case OP_Program: { /* jump */ int nMem; /* Number of memory registers for sub-program */ int nByte; /* Bytes of runtime space required for sub-program */ Mem *pRt; /* Register to allocate runtime space */ Mem *pMem; /* Used to iterate through memory cells */ Mem *pEnd; /* Last memory cell in new array */ VdbeFrame *pFrame; /* New vdbe frame to execute in */ SubProgram *pProgram; /* Sub-program to execute */ void *t; /* Token identifying trigger */ pProgram = pOp->p4.pProgram; pRt = &aMem[pOp->p3]; assert( pProgram->nOp>0 ); /* If the p5 flag is clear, then recursive invocation of triggers is ** disabled for backwards compatibility (p5 is set if this sub-program ** is really a trigger, not a foreign key action, and the flag set ** and cleared by the "PRAGMA recursive_triggers" command is clear). ** ** It is recursive invocation of triggers, at the SQL level, that is ** disabled. In some cases a single trigger may generate more than one ** SubProgram (if the trigger may be executed with more than one different ** ON CONFLICT algorithm). SubProgram structures associated with a ** single trigger all have the same value for the SubProgram.token ** variable. */ if( pOp->p5 ){ t = pProgram->token; for(pFrame=p->pFrame; pFrame && pFrame->token!=t; pFrame=pFrame->pParent); if( pFrame ) break; } if( p->nFrame>=db->aLimit[SQLITE_LIMIT_TRIGGER_DEPTH] ){ rc = SQLITE_ERROR; sqlite3VdbeError(p, "too many levels of trigger recursion"); goto abort_due_to_error; } /* Register pRt is used to store the memory required to save the state ** of the current program, and the memory required at runtime to execute ** the trigger program. If this trigger has been fired before, then pRt ** is already allocated. Otherwise, it must be initialized. */ if( (pRt->flags&MEM_Frame)==0 ){ /* SubProgram.nMem is set to the number of memory cells used by the ** program stored in SubProgram.aOp. As well as these, one memory ** cell is required for each cursor used by the program. Set local ** variable nMem (and later, VdbeFrame.nChildMem) to this value. */ nMem = pProgram->nMem + pProgram->nCsr; assert( nMem>0 ); if( pProgram->nCsr==0 ) nMem++; nByte = ROUND8(sizeof(VdbeFrame)) + nMem * sizeof(Mem) + pProgram->nCsr * sizeof(VdbeCursor *); pFrame = sqlite3DbMallocZero(db, nByte); if( !pFrame ){ goto no_mem; } sqlite3VdbeMemRelease(pRt); pRt->flags = MEM_Frame; pRt->u.pFrame = pFrame; pFrame->v = p; pFrame->nChildMem = nMem; pFrame->nChildCsr = pProgram->nCsr; pFrame->pc = (int)(pOp - aOp); pFrame->aMem = p->aMem; pFrame->nMem = p->nMem; pFrame->apCsr = p->apCsr; pFrame->nCursor = p->nCursor; pFrame->aOp = p->aOp; pFrame->nOp = p->nOp; pFrame->token = pProgram->token; #ifdef SQLITE_ENABLE_STMT_SCANSTATUS pFrame->anExec = p->anExec; #endif pEnd = &VdbeFrameMem(pFrame)[pFrame->nChildMem]; for(pMem=VdbeFrameMem(pFrame); pMem!=pEnd; pMem++){ pMem->flags = MEM_Undefined; pMem->db = db; } }else{ pFrame = pRt->u.pFrame; assert( pProgram->nMem+pProgram->nCsr==pFrame->nChildMem || (pProgram->nCsr==0 && pProgram->nMem+1==pFrame->nChildMem) ); assert( pProgram->nCsr==pFrame->nChildCsr ); assert( (int)(pOp - aOp)==pFrame->pc ); } p->nFrame++; pFrame->pParent = p->pFrame; pFrame->lastRowid = lastRowid; pFrame->nChange = p->nChange; pFrame->nDbChange = p->db->nChange; assert( pFrame->pAuxData==0 ); pFrame->pAuxData = p->pAuxData; p->pAuxData = 0; p->nChange = 0; p->pFrame = pFrame; p->aMem = aMem = VdbeFrameMem(pFrame); p->nMem = pFrame->nChildMem; p->nCursor = (u16)pFrame->nChildCsr; p->apCsr = (VdbeCursor **)&aMem[p->nMem]; p->aOp = aOp = pProgram->aOp; p->nOp = pProgram->nOp; #ifdef SQLITE_ENABLE_STMT_SCANSTATUS p->anExec = 0; #endif pOp = &aOp[-1]; break; } /* Opcode: Param P1 P2 * * * ** ** This opcode is only ever present in sub-programs called via the ** OP_Program instruction. Copy a value currently stored in a memory ** cell of the calling (parent) frame to cell P2 in the current frames ** address space. This is used by trigger programs to access the new.* ** and old.* values. ** ** The address of the cell in the parent frame is determined by adding ** the value of the P1 argument to the value of the P1 argument to the ** calling OP_Program instruction. */ case OP_Param: { /* out2 */ VdbeFrame *pFrame; Mem *pIn; pOut = out2Prerelease(p, pOp); pFrame = p->pFrame; pIn = &pFrame->aMem[pOp->p1 + pFrame->aOp[pFrame->pc].p1]; sqlite3VdbeMemShallowCopy(pOut, pIn, MEM_Ephem); break; } #endif /* #ifndef SQLITE_OMIT_TRIGGER */ #ifndef SQLITE_OMIT_FOREIGN_KEY /* Opcode: FkCounter P1 P2 * * * ** Synopsis: fkctr[P1]+=P2 ** ** Increment a "constraint counter" by P2 (P2 may be negative or positive). ** If P1 is non-zero, the database constraint counter is incremented ** (deferred foreign key constraints). Otherwise, if P1 is zero, the ** statement counter is incremented (immediate foreign key constraints). */ case OP_FkCounter: { if( db->flags & SQLITE_DeferFKs ){ db->nDeferredImmCons += pOp->p2; }else if( pOp->p1 ){ db->nDeferredCons += pOp->p2; }else{ p->nFkConstraint += pOp->p2; } break; } /* Opcode: FkIfZero P1 P2 * * * ** Synopsis: if fkctr[P1]==0 goto P2 ** ** This opcode tests if a foreign key constraint-counter is currently zero. ** If so, jump to instruction P2. Otherwise, fall through to the next ** instruction. ** ** If P1 is non-zero, then the jump is taken if the database constraint-counter ** is zero (the one that counts deferred constraint violations). If P1 is ** zero, the jump is taken if the statement constraint-counter is zero ** (immediate foreign key constraint violations). */ case OP_FkIfZero: { /* jump */ if( pOp->p1 ){ VdbeBranchTaken(db->nDeferredCons==0 && db->nDeferredImmCons==0, 2); if( db->nDeferredCons==0 && db->nDeferredImmCons==0 ) goto jump_to_p2; }else{ VdbeBranchTaken(p->nFkConstraint==0 && db->nDeferredImmCons==0, 2); if( p->nFkConstraint==0 && db->nDeferredImmCons==0 ) goto jump_to_p2; } break; } #endif /* #ifndef SQLITE_OMIT_FOREIGN_KEY */ #ifndef SQLITE_OMIT_AUTOINCREMENT /* Opcode: MemMax P1 P2 * * * ** Synopsis: r[P1]=max(r[P1],r[P2]) ** ** P1 is a register in the root frame of this VM (the root frame is ** different from the current frame if this instruction is being executed ** within a sub-program). Set the value of register P1 to the maximum of ** its current value and the value in register P2. ** ** This instruction throws an error if the memory cell is not initially ** an integer. */ case OP_MemMax: { /* in2 */ VdbeFrame *pFrame; if( p->pFrame ){ for(pFrame=p->pFrame; pFrame->pParent; pFrame=pFrame->pParent); pIn1 = &pFrame->aMem[pOp->p1]; }else{ pIn1 = &aMem[pOp->p1]; } assert( memIsValid(pIn1) ); sqlite3VdbeMemIntegerify(pIn1); pIn2 = &aMem[pOp->p2]; sqlite3VdbeMemIntegerify(pIn2); if( pIn1->u.iu.i){ pIn1->u.i = pIn2->u.i; } break; } #endif /* SQLITE_OMIT_AUTOINCREMENT */ /* Opcode: IfPos P1 P2 P3 * * ** Synopsis: if r[P1]>0 then r[P1]-=P3, goto P2 ** ** Register P1 must contain an integer. ** If the value of register P1 is 1 or greater, subtract P3 from the ** value in P1 and jump to P2. ** ** If the initial value of register P1 is less than 1, then the ** value is unchanged and control passes through to the next instruction. */ case OP_IfPos: { /* jump, in1 */ pIn1 = &aMem[pOp->p1]; assert( pIn1->flags&MEM_Int ); VdbeBranchTaken( pIn1->u.i>0, 2); if( pIn1->u.i>0 ){ pIn1->u.i -= pOp->p3; goto jump_to_p2; } break; } /* Opcode: OffsetLimit P1 P2 P3 * * ** Synopsis: if r[P1]>0 then r[P2]=r[P1]+max(0,r[P3]) else r[P2]=(-1) ** ** This opcode performs a commonly used computation associated with ** LIMIT and OFFSET process. r[P1] holds the limit counter. r[P3] ** holds the offset counter. The opcode computes the combined value ** of the LIMIT and OFFSET and stores that value in r[P2]. The r[P2] ** value computed is the total number of rows that will need to be ** visited in order to complete the query. ** ** If r[P3] is zero or negative, that means there is no OFFSET ** and r[P2] is set to be the value of the LIMIT, r[P1]. ** ** if r[P1] is zero or negative, that means there is no LIMIT ** and r[P2] is set to -1. ** ** Otherwise, r[P2] is set to the sum of r[P1] and r[P3]. */ case OP_OffsetLimit: { /* in1, out2, in3 */ pIn1 = &aMem[pOp->p1]; pIn3 = &aMem[pOp->p3]; pOut = out2Prerelease(p, pOp); assert( pIn1->flags & MEM_Int ); assert( pIn3->flags & MEM_Int ); pOut->u.i = pIn1->u.i<=0 ? -1 : pIn1->u.i+(pIn3->u.i>0?pIn3->u.i:0); break; } /* Opcode: IfNotZero P1 P2 P3 * * ** Synopsis: if r[P1]!=0 then r[P1]-=P3, goto P2 ** ** Register P1 must contain an integer. If the content of register P1 is ** initially nonzero, then subtract P3 from the value in register P1 and ** jump to P2. If register P1 is initially zero, leave it unchanged ** and fall through. */ case OP_IfNotZero: { /* jump, in1 */ pIn1 = &aMem[pOp->p1]; assert( pIn1->flags&MEM_Int ); VdbeBranchTaken(pIn1->u.i<0, 2); if( pIn1->u.i ){ pIn1->u.i -= pOp->p3; goto jump_to_p2; } break; } /* Opcode: DecrJumpZero P1 P2 * * * ** Synopsis: if (--r[P1])==0 goto P2 ** ** Register P1 must hold an integer. Decrement the value in register P1 ** then jump to P2 if the new value is exactly zero. */ case OP_DecrJumpZero: { /* jump, in1 */ pIn1 = &aMem[pOp->p1]; assert( pIn1->flags&MEM_Int ); pIn1->u.i--; VdbeBranchTaken(pIn1->u.i==0, 2); if( pIn1->u.i==0 ) goto jump_to_p2; break; } /* Opcode: AggStep0 * P2 P3 P4 P5 ** Synopsis: accum=r[P3] step(r[P2@P5]) ** ** Execute the step function for an aggregate. The ** function has P5 arguments. P4 is a pointer to the FuncDef ** structure that specifies the function. Register P3 is the ** accumulator. ** ** The P5 arguments are taken from register P2 and its ** successors. */ /* Opcode: AggStep * P2 P3 P4 P5 ** Synopsis: accum=r[P3] step(r[P2@P5]) ** ** Execute the step function for an aggregate. The ** function has P5 arguments. P4 is a pointer to an sqlite3_context ** object that is used to run the function. Register P3 is ** as the accumulator. ** ** The P5 arguments are taken from register P2 and its ** successors. ** ** This opcode is initially coded as OP_AggStep0. On first evaluation, ** the FuncDef stored in P4 is converted into an sqlite3_context and ** the opcode is changed. In this way, the initialization of the ** sqlite3_context only happens once, instead of on each call to the ** step function. */ case OP_AggStep0: { int n; sqlite3_context *pCtx; assert( pOp->p4type==P4_FUNCDEF ); n = pOp->p5; assert( pOp->p3>0 && pOp->p3<=(p->nMem+1 - p->nCursor) ); assert( n==0 || (pOp->p2>0 && pOp->p2+n<=(p->nMem+1 - p->nCursor)+1) ); assert( pOp->p3p2 || pOp->p3>=pOp->p2+n ); pCtx = sqlite3DbMallocRawNN(db, sizeof(*pCtx) + (n-1)*sizeof(sqlite3_value*)); if( pCtx==0 ) goto no_mem; pCtx->pMem = 0; pCtx->pFunc = pOp->p4.pFunc; pCtx->iOp = (int)(pOp - aOp); pCtx->pVdbe = p; pCtx->argc = n; pOp->p4type = P4_FUNCCTX; pOp->p4.pCtx = pCtx; pOp->opcode = OP_AggStep; /* Fall through into OP_AggStep */ } case OP_AggStep: { int i; sqlite3_context *pCtx; Mem *pMem; Mem t; assert( pOp->p4type==P4_FUNCCTX ); pCtx = pOp->p4.pCtx; pMem = &aMem[pOp->p3]; /* If this function is inside of a trigger, the register array in aMem[] ** might change from one evaluation to the next. The next block of code ** checks to see if the register array has changed, and if so it ** reinitializes the relavant parts of the sqlite3_context object */ if( pCtx->pMem != pMem ){ pCtx->pMem = pMem; for(i=pCtx->argc-1; i>=0; i--) pCtx->argv[i] = &aMem[pOp->p2+i]; } #ifdef SQLITE_DEBUG for(i=0; iargc; i++){ assert( memIsValid(pCtx->argv[i]) ); REGISTER_TRACE(pOp->p2+i, pCtx->argv[i]); } #endif pMem->n++; sqlite3VdbeMemInit(&t, db, MEM_Null); pCtx->pOut = &t; pCtx->fErrorOrAux = 0; pCtx->skipFlag = 0; (pCtx->pFunc->xSFunc)(pCtx,pCtx->argc,pCtx->argv); /* IMP: R-24505-23230 */ if( pCtx->fErrorOrAux ){ if( pCtx->isError ){ sqlite3VdbeError(p, "%s", sqlite3_value_text(&t)); rc = pCtx->isError; } sqlite3VdbeMemRelease(&t); if( rc ) goto abort_due_to_error; }else{ assert( t.flags==MEM_Null ); } if( pCtx->skipFlag ){ assert( pOp[-1].opcode==OP_CollSeq ); i = pOp[-1].p1; if( i ) sqlite3VdbeMemSetInt64(&aMem[i], 1); } break; } /* Opcode: AggFinal P1 P2 * P4 * ** Synopsis: accum=r[P1] N=P2 ** ** Execute the finalizer function for an aggregate. P1 is ** the memory location that is the accumulator for the aggregate. ** ** P2 is the number of arguments that the step function takes and ** P4 is a pointer to the FuncDef for this function. The P2 ** argument is not used by this opcode. It is only there to disambiguate ** functions that can take varying numbers of arguments. The ** P4 argument is only needed for the degenerate case where ** the step function was not previously called. */ case OP_AggFinal: { Mem *pMem; assert( pOp->p1>0 && pOp->p1<=(p->nMem+1 - p->nCursor) ); pMem = &aMem[pOp->p1]; assert( (pMem->flags & ~(MEM_Null|MEM_Agg))==0 ); rc = sqlite3VdbeMemFinalize(pMem, pOp->p4.pFunc); if( rc ){ sqlite3VdbeError(p, "%s", sqlite3_value_text(pMem)); goto abort_due_to_error; } sqlite3VdbeChangeEncoding(pMem, encoding); UPDATE_MAX_BLOBSIZE(pMem); if( sqlite3VdbeMemTooBig(pMem) ){ goto too_big; } break; } #ifndef SQLITE_OMIT_WAL /* Opcode: Checkpoint P1 P2 P3 * * ** ** Checkpoint database P1. This is a no-op if P1 is not currently in ** WAL mode. Parameter P2 is one of SQLITE_CHECKPOINT_PASSIVE, FULL, ** RESTART, or TRUNCATE. Write 1 or 0 into mem[P3] if the checkpoint returns ** SQLITE_BUSY or not, respectively. Write the number of pages in the ** WAL after the checkpoint into mem[P3+1] and the number of pages ** in the WAL that have been checkpointed after the checkpoint ** completes into mem[P3+2]. However on an error, mem[P3+1] and ** mem[P3+2] are initialized to -1. */ case OP_Checkpoint: { int i; /* Loop counter */ int aRes[3]; /* Results */ Mem *pMem; /* Write results here */ assert( p->readOnly==0 ); aRes[0] = 0; aRes[1] = aRes[2] = -1; assert( pOp->p2==SQLITE_CHECKPOINT_PASSIVE || pOp->p2==SQLITE_CHECKPOINT_FULL || pOp->p2==SQLITE_CHECKPOINT_RESTART || pOp->p2==SQLITE_CHECKPOINT_TRUNCATE ); rc = sqlite3Checkpoint(db, pOp->p1, pOp->p2, &aRes[1], &aRes[2]); if( rc ){ if( rc!=SQLITE_BUSY ) goto abort_due_to_error; rc = SQLITE_OK; aRes[0] = 1; } for(i=0, pMem = &aMem[pOp->p3]; i<3; i++, pMem++){ sqlite3VdbeMemSetInt64(pMem, (i64)aRes[i]); } break; }; #endif #ifndef SQLITE_OMIT_PRAGMA /* Opcode: JournalMode P1 P2 P3 * * ** ** Change the journal mode of database P1 to P3. P3 must be one of the ** PAGER_JOURNALMODE_XXX values. If changing between the various rollback ** modes (delete, truncate, persist, off and memory), this is a simple ** operation. No IO is required. ** ** If changing into or out of WAL mode the procedure is more complicated. ** ** Write a string containing the final journal-mode to register P2. */ case OP_JournalMode: { /* out2 */ Btree *pBt; /* Btree to change journal mode of */ Pager *pPager; /* Pager associated with pBt */ int eNew; /* New journal mode */ int eOld; /* The old journal mode */ #ifndef SQLITE_OMIT_WAL const char *zFilename; /* Name of database file for pPager */ #endif pOut = out2Prerelease(p, pOp); eNew = pOp->p3; assert( eNew==PAGER_JOURNALMODE_DELETE || eNew==PAGER_JOURNALMODE_TRUNCATE || eNew==PAGER_JOURNALMODE_PERSIST || eNew==PAGER_JOURNALMODE_OFF || eNew==PAGER_JOURNALMODE_MEMORY || eNew==PAGER_JOURNALMODE_WAL || eNew==PAGER_JOURNALMODE_QUERY ); assert( pOp->p1>=0 && pOp->p1nDb ); assert( p->readOnly==0 ); pBt = db->aDb[pOp->p1].pBt; pPager = sqlite3BtreePager(pBt); eOld = sqlite3PagerGetJournalMode(pPager); if( eNew==PAGER_JOURNALMODE_QUERY ) eNew = eOld; if( !sqlite3PagerOkToChangeJournalMode(pPager) ) eNew = eOld; #ifndef SQLITE_OMIT_WAL zFilename = sqlite3PagerFilename(pPager, 1); /* Do not allow a transition to journal_mode=WAL for a database ** in temporary storage or if the VFS does not support shared memory */ if( eNew==PAGER_JOURNALMODE_WAL && (sqlite3Strlen30(zFilename)==0 /* Temp file */ || !sqlite3PagerWalSupported(pPager)) /* No shared-memory support */ ){ eNew = eOld; } if( (eNew!=eOld) && (eOld==PAGER_JOURNALMODE_WAL || eNew==PAGER_JOURNALMODE_WAL) ){ if( !db->autoCommit || db->nVdbeRead>1 ){ rc = SQLITE_ERROR; sqlite3VdbeError(p, "cannot change %s wal mode from within a transaction", (eNew==PAGER_JOURNALMODE_WAL ? "into" : "out of") ); goto abort_due_to_error; }else{ if( eOld==PAGER_JOURNALMODE_WAL ){ /* If leaving WAL mode, close the log file. If successful, the call ** to PagerCloseWal() checkpoints and deletes the write-ahead-log ** file. An EXCLUSIVE lock may still be held on the database file ** after a successful return. */ rc = sqlite3PagerCloseWal(pPager); if( rc==SQLITE_OK ){ sqlite3PagerSetJournalMode(pPager, eNew); } }else if( eOld==PAGER_JOURNALMODE_MEMORY ){ /* Cannot transition directly from MEMORY to WAL. Use mode OFF ** as an intermediate */ sqlite3PagerSetJournalMode(pPager, PAGER_JOURNALMODE_OFF); } /* Open a transaction on the database file. Regardless of the journal ** mode, this transaction always uses a rollback journal. */ assert( sqlite3BtreeIsInTrans(pBt)==0 ); if( rc==SQLITE_OK ){ rc = sqlite3BtreeSetVersion(pBt, (eNew==PAGER_JOURNALMODE_WAL ? 2 : 1)); } } } #endif /* ifndef SQLITE_OMIT_WAL */ if( rc ) eNew = eOld; eNew = sqlite3PagerSetJournalMode(pPager, eNew); pOut->flags = MEM_Str|MEM_Static|MEM_Term; pOut->z = (char *)sqlite3JournalModename(eNew); pOut->n = sqlite3Strlen30(pOut->z); pOut->enc = SQLITE_UTF8; sqlite3VdbeChangeEncoding(pOut, encoding); if( rc ) goto abort_due_to_error; break; }; #endif /* SQLITE_OMIT_PRAGMA */ #if !defined(SQLITE_OMIT_VACUUM) && !defined(SQLITE_OMIT_ATTACH) /* Opcode: Vacuum P1 * * * * ** ** Vacuum the entire database P1. P1 is 0 for "main", and 2 or more ** for an attached database. The "temp" database may not be vacuumed. */ case OP_Vacuum: { assert( p->readOnly==0 ); rc = sqlite3RunVacuum(&p->zErrMsg, db, pOp->p1); if( rc ) goto abort_due_to_error; break; } #endif #if !defined(SQLITE_OMIT_AUTOVACUUM) /* Opcode: IncrVacuum P1 P2 * * * ** ** Perform a single step of the incremental vacuum procedure on ** the P1 database. If the vacuum has finished, jump to instruction ** P2. Otherwise, fall through to the next instruction. */ case OP_IncrVacuum: { /* jump */ Btree *pBt; assert( pOp->p1>=0 && pOp->p1nDb ); assert( DbMaskTest(p->btreeMask, pOp->p1) ); assert( p->readOnly==0 ); pBt = db->aDb[pOp->p1].pBt; rc = sqlite3BtreeIncrVacuum(pBt); VdbeBranchTaken(rc==SQLITE_DONE,2); if( rc ){ if( rc!=SQLITE_DONE ) goto abort_due_to_error; rc = SQLITE_OK; goto jump_to_p2; } break; } #endif /* Opcode: Expire P1 * * * * ** ** Cause precompiled statements to expire. When an expired statement ** is executed using sqlite3_step() it will either automatically ** reprepare itself (if it was originally created using sqlite3_prepare_v2()) ** or it will fail with SQLITE_SCHEMA. ** ** If P1 is 0, then all SQL statements become expired. If P1 is non-zero, ** then only the currently executing statement is expired. */ case OP_Expire: { if( !pOp->p1 ){ sqlite3ExpirePreparedStatements(db); }else{ p->expired = 1; } break; } #ifndef SQLITE_OMIT_SHARED_CACHE /* Opcode: TableLock P1 P2 P3 P4 * ** Synopsis: iDb=P1 root=P2 write=P3 ** ** Obtain a lock on a particular table. This instruction is only used when ** the shared-cache feature is enabled. ** ** P1 is the index of the database in sqlite3.aDb[] of the database ** on which the lock is acquired. A readlock is obtained if P3==0 or ** a write lock if P3==1. ** ** P2 contains the root-page of the table to lock. ** ** P4 contains a pointer to the name of the table being locked. This is only ** used to generate an error message if the lock cannot be obtained. */ case OP_TableLock: { u8 isWriteLock = (u8)pOp->p3; if( isWriteLock || 0==(db->flags&SQLITE_ReadUncommitted) ){ int p1 = pOp->p1; assert( p1>=0 && p1nDb ); assert( DbMaskTest(p->btreeMask, p1) ); assert( isWriteLock==0 || isWriteLock==1 ); rc = sqlite3BtreeLockTable(db->aDb[p1].pBt, pOp->p2, isWriteLock); if( rc ){ if( (rc&0xFF)==SQLITE_LOCKED ){ const char *z = pOp->p4.z; sqlite3VdbeError(p, "database table is locked: %s", z); } goto abort_due_to_error; } } break; } #endif /* SQLITE_OMIT_SHARED_CACHE */ #ifndef SQLITE_OMIT_VIRTUALTABLE /* Opcode: VBegin * * * P4 * ** ** P4 may be a pointer to an sqlite3_vtab structure. If so, call the ** xBegin method for that table. ** ** Also, whether or not P4 is set, check that this is not being called from ** within a callback to a virtual table xSync() method. If it is, the error ** code will be set to SQLITE_LOCKED. */ case OP_VBegin: { VTable *pVTab; pVTab = pOp->p4.pVtab; rc = sqlite3VtabBegin(db, pVTab); if( pVTab ) sqlite3VtabImportErrmsg(p, pVTab->pVtab); if( rc ) goto abort_due_to_error; break; } #endif /* SQLITE_OMIT_VIRTUALTABLE */ #ifndef SQLITE_OMIT_VIRTUALTABLE /* Opcode: VCreate P1 P2 * * * ** ** P2 is a register that holds the name of a virtual table in database ** P1. Call the xCreate method for that table. */ case OP_VCreate: { Mem sMem; /* For storing the record being decoded */ const char *zTab; /* Name of the virtual table */ memset(&sMem, 0, sizeof(sMem)); sMem.db = db; /* Because P2 is always a static string, it is impossible for the ** sqlite3VdbeMemCopy() to fail */ assert( (aMem[pOp->p2].flags & MEM_Str)!=0 ); assert( (aMem[pOp->p2].flags & MEM_Static)!=0 ); rc = sqlite3VdbeMemCopy(&sMem, &aMem[pOp->p2]); assert( rc==SQLITE_OK ); zTab = (const char*)sqlite3_value_text(&sMem); assert( zTab || db->mallocFailed ); if( zTab ){ rc = sqlite3VtabCallCreate(db, pOp->p1, zTab, &p->zErrMsg); } sqlite3VdbeMemRelease(&sMem); if( rc ) goto abort_due_to_error; break; } #endif /* SQLITE_OMIT_VIRTUALTABLE */ #ifndef SQLITE_OMIT_VIRTUALTABLE /* Opcode: VDestroy P1 * * P4 * ** ** P4 is the name of a virtual table in database P1. Call the xDestroy method ** of that table. */ case OP_VDestroy: { db->nVDestroy++; rc = sqlite3VtabCallDestroy(db, pOp->p1, pOp->p4.z); db->nVDestroy--; if( rc ) goto abort_due_to_error; break; } #endif /* SQLITE_OMIT_VIRTUALTABLE */ #ifndef SQLITE_OMIT_VIRTUALTABLE /* Opcode: VOpen P1 * * P4 * ** ** P4 is a pointer to a virtual table object, an sqlite3_vtab structure. ** P1 is a cursor number. This opcode opens a cursor to the virtual ** table and stores that cursor in P1. */ case OP_VOpen: { VdbeCursor *pCur; sqlite3_vtab_cursor *pVCur; sqlite3_vtab *pVtab; const sqlite3_module *pModule; assert( p->bIsReader ); pCur = 0; pVCur = 0; pVtab = pOp->p4.pVtab->pVtab; if( pVtab==0 || NEVER(pVtab->pModule==0) ){ rc = SQLITE_LOCKED; goto abort_due_to_error; } pModule = pVtab->pModule; rc = pModule->xOpen(pVtab, &pVCur); sqlite3VtabImportErrmsg(p, pVtab); if( rc ) goto abort_due_to_error; /* Initialize sqlite3_vtab_cursor base class */ pVCur->pVtab = pVtab; /* Initialize vdbe cursor object */ pCur = allocateCursor(p, pOp->p1, 0, -1, CURTYPE_VTAB); if( pCur ){ pCur->uc.pVCur = pVCur; pVtab->nRef++; }else{ assert( db->mallocFailed ); pModule->xClose(pVCur); goto no_mem; } break; } #endif /* SQLITE_OMIT_VIRTUALTABLE */ #ifndef SQLITE_OMIT_VIRTUALTABLE /* Opcode: VFilter P1 P2 P3 P4 * ** Synopsis: iplan=r[P3] zplan='P4' ** ** P1 is a cursor opened using VOpen. P2 is an address to jump to if ** the filtered result set is empty. ** ** P4 is either NULL or a string that was generated by the xBestIndex ** method of the module. The interpretation of the P4 string is left ** to the module implementation. ** ** This opcode invokes the xFilter method on the virtual table specified ** by P1. The integer query plan parameter to xFilter is stored in register ** P3. Register P3+1 stores the argc parameter to be passed to the ** xFilter method. Registers P3+2..P3+1+argc are the argc ** additional parameters which are passed to ** xFilter as argv. Register P3+2 becomes argv[0] when passed to xFilter. ** ** A jump is made to P2 if the result set after filtering would be empty. */ case OP_VFilter: { /* jump */ int nArg; int iQuery; const sqlite3_module *pModule; Mem *pQuery; Mem *pArgc; sqlite3_vtab_cursor *pVCur; sqlite3_vtab *pVtab; VdbeCursor *pCur; int res; int i; Mem **apArg; pQuery = &aMem[pOp->p3]; pArgc = &pQuery[1]; pCur = p->apCsr[pOp->p1]; assert( memIsValid(pQuery) ); REGISTER_TRACE(pOp->p3, pQuery); assert( pCur->eCurType==CURTYPE_VTAB ); pVCur = pCur->uc.pVCur; pVtab = pVCur->pVtab; pModule = pVtab->pModule; /* Grab the index number and argc parameters */ assert( (pQuery->flags&MEM_Int)!=0 && pArgc->flags==MEM_Int ); nArg = (int)pArgc->u.i; iQuery = (int)pQuery->u.i; /* Invoke the xFilter method */ res = 0; apArg = p->apArg; for(i = 0; ixFilter(pVCur, iQuery, pOp->p4.z, nArg, apArg); sqlite3VtabImportErrmsg(p, pVtab); if( rc ) goto abort_due_to_error; res = pModule->xEof(pVCur); pCur->nullRow = 0; VdbeBranchTaken(res!=0,2); if( res ) goto jump_to_p2; break; } #endif /* SQLITE_OMIT_VIRTUALTABLE */ #ifndef SQLITE_OMIT_VIRTUALTABLE /* Opcode: VColumn P1 P2 P3 * * ** Synopsis: r[P3]=vcolumn(P2) ** ** Store the value of the P2-th column of ** the row of the virtual-table that the ** P1 cursor is pointing to into register P3. */ case OP_VColumn: { sqlite3_vtab *pVtab; const sqlite3_module *pModule; Mem *pDest; sqlite3_context sContext; VdbeCursor *pCur = p->apCsr[pOp->p1]; assert( pCur->eCurType==CURTYPE_VTAB ); assert( pOp->p3>0 && pOp->p3<=(p->nMem+1 - p->nCursor) ); pDest = &aMem[pOp->p3]; memAboutToChange(p, pDest); if( pCur->nullRow ){ sqlite3VdbeMemSetNull(pDest); break; } pVtab = pCur->uc.pVCur->pVtab; pModule = pVtab->pModule; assert( pModule->xColumn ); memset(&sContext, 0, sizeof(sContext)); sContext.pOut = pDest; MemSetTypeFlag(pDest, MEM_Null); rc = pModule->xColumn(pCur->uc.pVCur, &sContext, pOp->p2); sqlite3VtabImportErrmsg(p, pVtab); if( sContext.isError ){ rc = sContext.isError; } sqlite3VdbeChangeEncoding(pDest, encoding); REGISTER_TRACE(pOp->p3, pDest); UPDATE_MAX_BLOBSIZE(pDest); if( sqlite3VdbeMemTooBig(pDest) ){ goto too_big; } if( rc ) goto abort_due_to_error; break; } #endif /* SQLITE_OMIT_VIRTUALTABLE */ #ifndef SQLITE_OMIT_VIRTUALTABLE /* Opcode: VNext P1 P2 * * * ** ** Advance virtual table P1 to the next row in its result set and ** jump to instruction P2. Or, if the virtual table has reached ** the end of its result set, then fall through to the next instruction. */ case OP_VNext: { /* jump */ sqlite3_vtab *pVtab; const sqlite3_module *pModule; int res; VdbeCursor *pCur; res = 0; pCur = p->apCsr[pOp->p1]; assert( pCur->eCurType==CURTYPE_VTAB ); if( pCur->nullRow ){ break; } pVtab = pCur->uc.pVCur->pVtab; pModule = pVtab->pModule; assert( pModule->xNext ); /* Invoke the xNext() method of the module. There is no way for the ** underlying implementation to return an error if one occurs during ** xNext(). Instead, if an error occurs, true is returned (indicating that ** data is available) and the error code returned when xColumn or ** some other method is next invoked on the save virtual table cursor. */ rc = pModule->xNext(pCur->uc.pVCur); sqlite3VtabImportErrmsg(p, pVtab); if( rc ) goto abort_due_to_error; res = pModule->xEof(pCur->uc.pVCur); VdbeBranchTaken(!res,2); if( !res ){ /* If there is data, jump to P2 */ goto jump_to_p2_and_check_for_interrupt; } goto check_for_interrupt; } #endif /* SQLITE_OMIT_VIRTUALTABLE */ #ifndef SQLITE_OMIT_VIRTUALTABLE /* Opcode: VRename P1 * * P4 * ** ** P4 is a pointer to a virtual table object, an sqlite3_vtab structure. ** This opcode invokes the corresponding xRename method. The value ** in register P1 is passed as the zName argument to the xRename method. */ case OP_VRename: { sqlite3_vtab *pVtab; Mem *pName; pVtab = pOp->p4.pVtab->pVtab; pName = &aMem[pOp->p1]; assert( pVtab->pModule->xRename ); assert( memIsValid(pName) ); assert( p->readOnly==0 ); REGISTER_TRACE(pOp->p1, pName); assert( pName->flags & MEM_Str ); testcase( pName->enc==SQLITE_UTF8 ); testcase( pName->enc==SQLITE_UTF16BE ); testcase( pName->enc==SQLITE_UTF16LE ); rc = sqlite3VdbeChangeEncoding(pName, SQLITE_UTF8); if( rc ) goto abort_due_to_error; rc = pVtab->pModule->xRename(pVtab, pName->z); sqlite3VtabImportErrmsg(p, pVtab); p->expired = 0; if( rc ) goto abort_due_to_error; break; } #endif #ifndef SQLITE_OMIT_VIRTUALTABLE /* Opcode: VUpdate P1 P2 P3 P4 P5 ** Synopsis: data=r[P3@P2] ** ** P4 is a pointer to a virtual table object, an sqlite3_vtab structure. ** This opcode invokes the corresponding xUpdate method. P2 values ** are contiguous memory cells starting at P3 to pass to the xUpdate ** invocation. The value in register (P3+P2-1) corresponds to the ** p2th element of the argv array passed to xUpdate. ** ** The xUpdate method will do a DELETE or an INSERT or both. ** The argv[0] element (which corresponds to memory cell P3) ** is the rowid of a row to delete. If argv[0] is NULL then no ** deletion occurs. The argv[1] element is the rowid of the new ** row. This can be NULL to have the virtual table select the new ** rowid for itself. The subsequent elements in the array are ** the values of columns in the new row. ** ** If P2==1 then no insert is performed. argv[0] is the rowid of ** a row to delete. ** ** P1 is a boolean flag. If it is set to true and the xUpdate call ** is successful, then the value returned by sqlite3_last_insert_rowid() ** is set to the value of the rowid for the row just inserted. ** ** P5 is the error actions (OE_Replace, OE_Fail, OE_Ignore, etc) to ** apply in the case of a constraint failure on an insert or update. */ case OP_VUpdate: { sqlite3_vtab *pVtab; const sqlite3_module *pModule; int nArg; int i; sqlite_int64 rowid; Mem **apArg; Mem *pX; assert( pOp->p2==1 || pOp->p5==OE_Fail || pOp->p5==OE_Rollback || pOp->p5==OE_Abort || pOp->p5==OE_Ignore || pOp->p5==OE_Replace ); assert( p->readOnly==0 ); pVtab = pOp->p4.pVtab->pVtab; if( pVtab==0 || NEVER(pVtab->pModule==0) ){ rc = SQLITE_LOCKED; goto abort_due_to_error; } pModule = pVtab->pModule; nArg = pOp->p2; assert( pOp->p4type==P4_VTAB ); if( ALWAYS(pModule->xUpdate) ){ u8 vtabOnConflict = db->vtabOnConflict; apArg = p->apArg; pX = &aMem[pOp->p3]; for(i=0; ivtabOnConflict = pOp->p5; rc = pModule->xUpdate(pVtab, nArg, apArg, &rowid); db->vtabOnConflict = vtabOnConflict; sqlite3VtabImportErrmsg(p, pVtab); if( rc==SQLITE_OK && pOp->p1 ){ assert( nArg>1 && apArg[0] && (apArg[0]->flags&MEM_Null) ); db->lastRowid = lastRowid = rowid; } if( (rc&0xff)==SQLITE_CONSTRAINT && pOp->p4.pVtab->bConstraint ){ if( pOp->p5==OE_Ignore ){ rc = SQLITE_OK; }else{ p->errorAction = ((pOp->p5==OE_Replace) ? OE_Abort : pOp->p5); } }else{ p->nChange++; } if( rc ) goto abort_due_to_error; } break; } #endif /* SQLITE_OMIT_VIRTUALTABLE */ #ifndef SQLITE_OMIT_PAGER_PRAGMAS /* Opcode: Pagecount P1 P2 * * * ** ** Write the current number of pages in database P1 to memory cell P2. */ case OP_Pagecount: { /* out2 */ pOut = out2Prerelease(p, pOp); pOut->u.i = sqlite3BtreeLastPage(db->aDb[pOp->p1].pBt); break; } #endif #ifndef SQLITE_OMIT_PAGER_PRAGMAS /* Opcode: MaxPgcnt P1 P2 P3 * * ** ** Try to set the maximum page count for database P1 to the value in P3. ** Do not let the maximum page count fall below the current page count and ** do not change the maximum page count value if P3==0. ** ** Store the maximum page count after the change in register P2. */ case OP_MaxPgcnt: { /* out2 */ unsigned int newMax; Btree *pBt; pOut = out2Prerelease(p, pOp); pBt = db->aDb[pOp->p1].pBt; newMax = 0; if( pOp->p3 ){ newMax = sqlite3BtreeLastPage(pBt); if( newMax < (unsigned)pOp->p3 ) newMax = (unsigned)pOp->p3; } pOut->u.i = sqlite3BtreeMaxPageCount(pBt, newMax); break; } #endif /* Opcode: Init P1 P2 * P4 * ** Synopsis: Start at P2 ** ** Programs contain a single instance of this opcode as the very first ** opcode. ** ** If tracing is enabled (by the sqlite3_trace()) interface, then ** the UTF-8 string contained in P4 is emitted on the trace callback. ** Or if P4 is blank, use the string returned by sqlite3_sql(). ** ** If P2 is not zero, jump to instruction P2. ** ** Increment the value of P1 so that OP_Once opcodes will jump the ** first time they are evaluated for this run. */ case OP_Init: { /* jump */ char *zTrace; int i; /* If the P4 argument is not NULL, then it must be an SQL comment string. ** The "--" string is broken up to prevent false-positives with srcck1.c. ** ** This assert() provides evidence for: ** EVIDENCE-OF: R-50676-09860 The callback can compute the same text that ** would have been returned by the legacy sqlite3_trace() interface by ** using the X argument when X begins with "--" and invoking ** sqlite3_expanded_sql(P) otherwise. */ assert( pOp->p4.z==0 || strncmp(pOp->p4.z, "-" "- ", 3)==0 ); assert( pOp==p->aOp ); /* Always instruction 0 */ #ifndef SQLITE_OMIT_TRACE if( (db->mTrace & (SQLITE_TRACE_STMT|SQLITE_TRACE_LEGACY))!=0 && !p->doingRerun && (zTrace = (pOp->p4.z ? pOp->p4.z : p->zSql))!=0 ){ #ifndef SQLITE_OMIT_DEPRECATED if( db->mTrace & SQLITE_TRACE_LEGACY ){ void (*x)(void*,const char*) = (void(*)(void*,const char*))db->xTrace; char *z = sqlite3VdbeExpandSql(p, zTrace); x(db->pTraceArg, z); sqlite3_free(z); }else #endif { (void)db->xTrace(SQLITE_TRACE_STMT, db->pTraceArg, p, zTrace); } } #ifdef SQLITE_USE_FCNTL_TRACE zTrace = (pOp->p4.z ? pOp->p4.z : p->zSql); if( zTrace ){ int j; for(j=0; jnDb; j++){ if( DbMaskTest(p->btreeMask, j)==0 ) continue; sqlite3_file_control(db, db->aDb[j].zDbSName, SQLITE_FCNTL_TRACE, zTrace); } } #endif /* SQLITE_USE_FCNTL_TRACE */ #ifdef SQLITE_DEBUG if( (db->flags & SQLITE_SqlTrace)!=0 && (zTrace = (pOp->p4.z ? pOp->p4.z : p->zSql))!=0 ){ sqlite3DebugPrintf("SQL-trace: %s\n", zTrace); } #endif /* SQLITE_DEBUG */ #endif /* SQLITE_OMIT_TRACE */ assert( pOp->p2>0 ); if( pOp->p1>=sqlite3GlobalConfig.iOnceResetThreshold ){ for(i=1; inOp; i++){ if( p->aOp[i].opcode==OP_Once ) p->aOp[i].p1 = 0; } pOp->p1 = 0; } pOp->p1++; goto jump_to_p2; } #ifdef SQLITE_ENABLE_CURSOR_HINTS /* Opcode: CursorHint P1 * * P4 * ** ** Provide a hint to cursor P1 that it only needs to return rows that ** satisfy the Expr in P4. TK_REGISTER terms in the P4 expression refer ** to values currently held in registers. TK_COLUMN terms in the P4 ** expression refer to columns in the b-tree to which cursor P1 is pointing. */ case OP_CursorHint: { VdbeCursor *pC; assert( pOp->p1>=0 && pOp->p1nCursor ); assert( pOp->p4type==P4_EXPR ); pC = p->apCsr[pOp->p1]; if( pC ){ assert( pC->eCurType==CURTYPE_BTREE ); sqlite3BtreeCursorHint(pC->uc.pCursor, BTREE_HINT_RANGE, pOp->p4.pExpr, aMem); } break; } #endif /* SQLITE_ENABLE_CURSOR_HINTS */ /* Opcode: Noop * * * * * ** ** Do nothing. This instruction is often useful as a jump ** destination. */ /* ** The magic Explain opcode are only inserted when explain==2 (which ** is to say when the EXPLAIN QUERY PLAN syntax is used.) ** This opcode records information from the optimizer. It is the ** the same as a no-op. This opcodesnever appears in a real VM program. */ default: { /* This is really OP_Noop and OP_Explain */ assert( pOp->opcode==OP_Noop || pOp->opcode==OP_Explain ); break; } /***************************************************************************** ** The cases of the switch statement above this line should all be indented ** by 6 spaces. But the left-most 6 spaces have been removed to improve the ** readability. From this point on down, the normal indentation rules are ** restored. *****************************************************************************/ } #ifdef VDBE_PROFILE { u64 endTime = sqlite3Hwtime(); if( endTime>start ) pOrigOp->cycles += endTime - start; pOrigOp->cnt++; } #endif /* The following code adds nothing to the actual functionality ** of the program. It is only here for testing and debugging. ** On the other hand, it does burn CPU cycles every time through ** the evaluator loop. So we can leave it out when NDEBUG is defined. */ #ifndef NDEBUG assert( pOp>=&aOp[-1] && pOp<&aOp[p->nOp-1] ); #ifdef SQLITE_DEBUG if( db->flags & SQLITE_VdbeTrace ){ u8 opProperty = sqlite3OpcodeProperty[pOrigOp->opcode]; if( rc!=0 ) printf("rc=%d\n",rc); if( opProperty & (OPFLG_OUT2) ){ registerTrace(pOrigOp->p2, &aMem[pOrigOp->p2]); } if( opProperty & OPFLG_OUT3 ){ registerTrace(pOrigOp->p3, &aMem[pOrigOp->p3]); } } #endif /* SQLITE_DEBUG */ #endif /* NDEBUG */ } /* The end of the for(;;) loop the loops through opcodes */ /* If we reach this point, it means that execution is finished with ** an error of some kind. */ abort_due_to_error: if( db->mallocFailed ) rc = SQLITE_NOMEM_BKPT; assert( rc ); if( p->zErrMsg==0 && rc!=SQLITE_IOERR_NOMEM ){ sqlite3VdbeError(p, "%s", sqlite3ErrStr(rc)); } p->rc = rc; sqlite3SystemError(db, rc); testcase( sqlite3GlobalConfig.xLog!=0 ); sqlite3_log(rc, "statement aborts at %d: [%s] %s", (int)(pOp - aOp), p->zSql, p->zErrMsg); sqlite3VdbeHalt(p); if( rc==SQLITE_IOERR_NOMEM ) sqlite3OomFault(db); rc = SQLITE_ERROR; if( resetSchemaOnFault>0 ){ sqlite3ResetOneSchema(db, resetSchemaOnFault-1); } /* This is the only way out of this procedure. We have to ** release the mutexes on btrees that were acquired at the ** top. */ vdbe_return: db->lastRowid = lastRowid; testcase( nVmStep>0 ); p->aCounter[SQLITE_STMTSTATUS_VM_STEP] += (int)nVmStep; sqlite3VdbeLeave(p); assert( rc!=SQLITE_OK || nExtraDelete==0 || sqlite3_strlike("DELETE%",p->zSql,0)!=0 ); return rc; /* Jump to here if a string or blob larger than SQLITE_MAX_LENGTH ** is encountered. */ too_big: sqlite3VdbeError(p, "string or blob too big"); rc = SQLITE_TOOBIG; goto abort_due_to_error; /* Jump to here if a malloc() fails. */ no_mem: sqlite3OomFault(db); sqlite3VdbeError(p, "out of memory"); rc = SQLITE_NOMEM_BKPT; goto abort_due_to_error; /* Jump to here if the sqlite3_interrupt() API sets the interrupt ** flag. */ abort_due_to_interrupt: assert( db->u1.isInterrupted ); rc = db->mallocFailed ? SQLITE_NOMEM_BKPT : SQLITE_INTERRUPT; p->rc = rc; sqlite3VdbeError(p, "%s", sqlite3ErrStr(rc)); goto abort_due_to_error; } /************** End of vdbe.c ************************************************/ /************** Begin file vdbeblob.c ****************************************/ /* ** 2007 May 1 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ************************************************************************* ** ** This file contains code used to implement incremental BLOB I/O. */ /* #include "sqliteInt.h" */ /* #include "vdbeInt.h" */ #ifndef SQLITE_OMIT_INCRBLOB /* ** Valid sqlite3_blob* handles point to Incrblob structures. */ typedef struct Incrblob Incrblob; struct Incrblob { int flags; /* Copy of "flags" passed to sqlite3_blob_open() */ int nByte; /* Size of open blob, in bytes */ int iOffset; /* Byte offset of blob in cursor data */ int iCol; /* Table column this handle is open on */ BtCursor *pCsr; /* Cursor pointing at blob row */ sqlite3_stmt *pStmt; /* Statement holding cursor open */ sqlite3 *db; /* The associated database */ char *zDb; /* Database name */ Table *pTab; /* Table object */ }; /* ** This function is used by both blob_open() and blob_reopen(). It seeks ** the b-tree cursor associated with blob handle p to point to row iRow. ** If successful, SQLITE_OK is returned and subsequent calls to ** sqlite3_blob_read() or sqlite3_blob_write() access the specified row. ** ** If an error occurs, or if the specified row does not exist or does not ** contain a value of type TEXT or BLOB in the column nominated when the ** blob handle was opened, then an error code is returned and *pzErr may ** be set to point to a buffer containing an error message. It is the ** responsibility of the caller to free the error message buffer using ** sqlite3DbFree(). ** ** If an error does occur, then the b-tree cursor is closed. All subsequent ** calls to sqlite3_blob_read(), blob_write() or blob_reopen() will ** immediately return SQLITE_ABORT. */ static int blobSeekToRow(Incrblob *p, sqlite3_int64 iRow, char **pzErr){ int rc; /* Error code */ char *zErr = 0; /* Error message */ Vdbe *v = (Vdbe *)p->pStmt; /* Set the value of the SQL statements only variable to integer iRow. ** This is done directly instead of using sqlite3_bind_int64() to avoid ** triggering asserts related to mutexes. */ assert( v->aVar[0].flags&MEM_Int ); v->aVar[0].u.i = iRow; rc = sqlite3_step(p->pStmt); if( rc==SQLITE_ROW ){ VdbeCursor *pC = v->apCsr[0]; u32 type = pC->aType[p->iCol]; if( type<12 ){ zErr = sqlite3MPrintf(p->db, "cannot open value of type %s", type==0?"null": type==7?"real": "integer" ); rc = SQLITE_ERROR; sqlite3_finalize(p->pStmt); p->pStmt = 0; }else{ p->iOffset = pC->aType[p->iCol + pC->nField]; p->nByte = sqlite3VdbeSerialTypeLen(type); p->pCsr = pC->uc.pCursor; sqlite3BtreeIncrblobCursor(p->pCsr); } } if( rc==SQLITE_ROW ){ rc = SQLITE_OK; }else if( p->pStmt ){ rc = sqlite3_finalize(p->pStmt); p->pStmt = 0; if( rc==SQLITE_OK ){ zErr = sqlite3MPrintf(p->db, "no such rowid: %lld", iRow); rc = SQLITE_ERROR; }else{ zErr = sqlite3MPrintf(p->db, "%s", sqlite3_errmsg(p->db)); } } assert( rc!=SQLITE_OK || zErr==0 ); assert( rc!=SQLITE_ROW && rc!=SQLITE_DONE ); *pzErr = zErr; return rc; } /* ** Open a blob handle. */ SQLITE_API int sqlite3_blob_open( sqlite3* db, /* The database connection */ const char *zDb, /* The attached database containing the blob */ const char *zTable, /* The table containing the blob */ const char *zColumn, /* The column containing the blob */ sqlite_int64 iRow, /* The row containing the glob */ int flags, /* True -> read/write access, false -> read-only */ sqlite3_blob **ppBlob /* Handle for accessing the blob returned here */ ){ int nAttempt = 0; int iCol; /* Index of zColumn in row-record */ int rc = SQLITE_OK; char *zErr = 0; Table *pTab; Parse *pParse = 0; Incrblob *pBlob = 0; #ifdef SQLITE_ENABLE_API_ARMOR if( ppBlob==0 ){ return SQLITE_MISUSE_BKPT; } #endif *ppBlob = 0; #ifdef SQLITE_ENABLE_API_ARMOR if( !sqlite3SafetyCheckOk(db) || zTable==0 ){ return SQLITE_MISUSE_BKPT; } #endif flags = !!flags; /* flags = (flags ? 1 : 0); */ sqlite3_mutex_enter(db->mutex); pBlob = (Incrblob *)sqlite3DbMallocZero(db, sizeof(Incrblob)); if( !pBlob ) goto blob_open_out; pParse = sqlite3StackAllocRaw(db, sizeof(*pParse)); if( !pParse ) goto blob_open_out; do { memset(pParse, 0, sizeof(Parse)); pParse->db = db; sqlite3DbFree(db, zErr); zErr = 0; sqlite3BtreeEnterAll(db); pTab = sqlite3LocateTable(pParse, 0, zTable, zDb); if( pTab && IsVirtual(pTab) ){ pTab = 0; sqlite3ErrorMsg(pParse, "cannot open virtual table: %s", zTable); } if( pTab && !HasRowid(pTab) ){ pTab = 0; sqlite3ErrorMsg(pParse, "cannot open table without rowid: %s", zTable); } #ifndef SQLITE_OMIT_VIEW if( pTab && pTab->pSelect ){ pTab = 0; sqlite3ErrorMsg(pParse, "cannot open view: %s", zTable); } #endif if( !pTab ){ if( pParse->zErrMsg ){ sqlite3DbFree(db, zErr); zErr = pParse->zErrMsg; pParse->zErrMsg = 0; } rc = SQLITE_ERROR; sqlite3BtreeLeaveAll(db); goto blob_open_out; } pBlob->pTab = pTab; pBlob->zDb = db->aDb[sqlite3SchemaToIndex(db, pTab->pSchema)].zDbSName; /* Now search pTab for the exact column. */ for(iCol=0; iColnCol; iCol++) { if( sqlite3StrICmp(pTab->aCol[iCol].zName, zColumn)==0 ){ break; } } if( iCol==pTab->nCol ){ sqlite3DbFree(db, zErr); zErr = sqlite3MPrintf(db, "no such column: \"%s\"", zColumn); rc = SQLITE_ERROR; sqlite3BtreeLeaveAll(db); goto blob_open_out; } /* If the value is being opened for writing, check that the ** column is not indexed, and that it is not part of a foreign key. ** It is against the rules to open a column to which either of these ** descriptions applies for writing. */ if( flags ){ const char *zFault = 0; Index *pIdx; #ifndef SQLITE_OMIT_FOREIGN_KEY if( db->flags&SQLITE_ForeignKeys ){ /* Check that the column is not part of an FK child key definition. It ** is not necessary to check if it is part of a parent key, as parent ** key columns must be indexed. The check below will pick up this ** case. */ FKey *pFKey; for(pFKey=pTab->pFKey; pFKey; pFKey=pFKey->pNextFrom){ int j; for(j=0; jnCol; j++){ if( pFKey->aCol[j].iFrom==iCol ){ zFault = "foreign key"; } } } } #endif for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){ int j; for(j=0; jnKeyCol; j++){ /* FIXME: Be smarter about indexes that use expressions */ if( pIdx->aiColumn[j]==iCol || pIdx->aiColumn[j]==XN_EXPR ){ zFault = "indexed"; } } } if( zFault ){ sqlite3DbFree(db, zErr); zErr = sqlite3MPrintf(db, "cannot open %s column for writing", zFault); rc = SQLITE_ERROR; sqlite3BtreeLeaveAll(db); goto blob_open_out; } } pBlob->pStmt = (sqlite3_stmt *)sqlite3VdbeCreate(pParse); assert( pBlob->pStmt || db->mallocFailed ); if( pBlob->pStmt ){ /* This VDBE program seeks a btree cursor to the identified ** db/table/row entry. The reason for using a vdbe program instead ** of writing code to use the b-tree layer directly is that the ** vdbe program will take advantage of the various transaction, ** locking and error handling infrastructure built into the vdbe. ** ** After seeking the cursor, the vdbe executes an OP_ResultRow. ** Code external to the Vdbe then "borrows" the b-tree cursor and ** uses it to implement the blob_read(), blob_write() and ** blob_bytes() functions. ** ** The sqlite3_blob_close() function finalizes the vdbe program, ** which closes the b-tree cursor and (possibly) commits the ** transaction. */ static const int iLn = VDBE_OFFSET_LINENO(2); static const VdbeOpList openBlob[] = { {OP_TableLock, 0, 0, 0}, /* 0: Acquire a read or write lock */ {OP_OpenRead, 0, 0, 0}, /* 1: Open a cursor */ {OP_Variable, 1, 1, 0}, /* 2: Move ?1 into reg[1] */ {OP_NotExists, 0, 7, 1}, /* 3: Seek the cursor */ {OP_Column, 0, 0, 1}, /* 4 */ {OP_ResultRow, 1, 0, 0}, /* 5 */ {OP_Goto, 0, 2, 0}, /* 6 */ {OP_Close, 0, 0, 0}, /* 7 */ {OP_Halt, 0, 0, 0}, /* 8 */ }; Vdbe *v = (Vdbe *)pBlob->pStmt; int iDb = sqlite3SchemaToIndex(db, pTab->pSchema); VdbeOp *aOp; sqlite3VdbeAddOp4Int(v, OP_Transaction, iDb, flags, pTab->pSchema->schema_cookie, pTab->pSchema->iGeneration); sqlite3VdbeChangeP5(v, 1); aOp = sqlite3VdbeAddOpList(v, ArraySize(openBlob), openBlob, iLn); /* Make sure a mutex is held on the table to be accessed */ sqlite3VdbeUsesBtree(v, iDb); if( db->mallocFailed==0 ){ assert( aOp!=0 ); /* Configure the OP_TableLock instruction */ #ifdef SQLITE_OMIT_SHARED_CACHE aOp[0].opcode = OP_Noop; #else aOp[0].p1 = iDb; aOp[0].p2 = pTab->tnum; aOp[0].p3 = flags; sqlite3VdbeChangeP4(v, 1, pTab->zName, P4_TRANSIENT); } if( db->mallocFailed==0 ){ #endif /* Remove either the OP_OpenWrite or OpenRead. Set the P2 ** parameter of the other to pTab->tnum. */ if( flags ) aOp[1].opcode = OP_OpenWrite; aOp[1].p2 = pTab->tnum; aOp[1].p3 = iDb; /* Configure the number of columns. Configure the cursor to ** think that the table has one more column than it really ** does. An OP_Column to retrieve this imaginary column will ** always return an SQL NULL. This is useful because it means ** we can invoke OP_Column to fill in the vdbe cursors type ** and offset cache without causing any IO. */ aOp[1].p4type = P4_INT32; aOp[1].p4.i = pTab->nCol+1; aOp[4].p2 = pTab->nCol; pParse->nVar = 1; pParse->nMem = 1; pParse->nTab = 1; sqlite3VdbeMakeReady(v, pParse); } } pBlob->flags = flags; pBlob->iCol = iCol; pBlob->db = db; sqlite3BtreeLeaveAll(db); if( db->mallocFailed ){ goto blob_open_out; } sqlite3_bind_int64(pBlob->pStmt, 1, iRow); rc = blobSeekToRow(pBlob, iRow, &zErr); } while( (++nAttempt)mallocFailed==0 ){ *ppBlob = (sqlite3_blob *)pBlob; }else{ if( pBlob && pBlob->pStmt ) sqlite3VdbeFinalize((Vdbe *)pBlob->pStmt); sqlite3DbFree(db, pBlob); } sqlite3ErrorWithMsg(db, rc, (zErr ? "%s" : 0), zErr); sqlite3DbFree(db, zErr); sqlite3ParserReset(pParse); sqlite3StackFree(db, pParse); rc = sqlite3ApiExit(db, rc); sqlite3_mutex_leave(db->mutex); return rc; } /* ** Close a blob handle that was previously created using ** sqlite3_blob_open(). */ SQLITE_API int sqlite3_blob_close(sqlite3_blob *pBlob){ Incrblob *p = (Incrblob *)pBlob; int rc; sqlite3 *db; if( p ){ db = p->db; sqlite3_mutex_enter(db->mutex); rc = sqlite3_finalize(p->pStmt); sqlite3DbFree(db, p); sqlite3_mutex_leave(db->mutex); }else{ rc = SQLITE_OK; } return rc; } /* ** Perform a read or write operation on a blob */ static int blobReadWrite( sqlite3_blob *pBlob, void *z, int n, int iOffset, int (*xCall)(BtCursor*, u32, u32, void*) ){ int rc; Incrblob *p = (Incrblob *)pBlob; Vdbe *v; sqlite3 *db; if( p==0 ) return SQLITE_MISUSE_BKPT; db = p->db; sqlite3_mutex_enter(db->mutex); v = (Vdbe*)p->pStmt; if( n<0 || iOffset<0 || ((sqlite3_int64)iOffset+n)>p->nByte ){ /* Request is out of range. Return a transient error. */ rc = SQLITE_ERROR; }else if( v==0 ){ /* If there is no statement handle, then the blob-handle has ** already been invalidated. Return SQLITE_ABORT in this case. */ rc = SQLITE_ABORT; }else{ /* Call either BtreeData() or BtreePutData(). If SQLITE_ABORT is ** returned, clean-up the statement handle. */ assert( db == v->db ); sqlite3BtreeEnterCursor(p->pCsr); #ifdef SQLITE_ENABLE_PREUPDATE_HOOK if( xCall==sqlite3BtreePutData && db->xPreUpdateCallback ){ /* If a pre-update hook is registered and this is a write cursor, ** invoke it here. ** ** TODO: The preupdate-hook is passed SQLITE_DELETE, even though this ** operation should really be an SQLITE_UPDATE. This is probably ** incorrect, but is convenient because at this point the new.* values ** are not easily obtainable. And for the sessions module, an ** SQLITE_UPDATE where the PK columns do not change is handled in the ** same way as an SQLITE_DELETE (the SQLITE_DELETE code is actually ** slightly more efficient). Since you cannot write to a PK column ** using the incremental-blob API, this works. For the sessions module ** anyhow. */ sqlite3_int64 iKey; iKey = sqlite3BtreeIntegerKey(p->pCsr); sqlite3VdbePreUpdateHook( v, v->apCsr[0], SQLITE_DELETE, p->zDb, p->pTab, iKey, -1 ); } #endif rc = xCall(p->pCsr, iOffset+p->iOffset, n, z); sqlite3BtreeLeaveCursor(p->pCsr); if( rc==SQLITE_ABORT ){ sqlite3VdbeFinalize(v); p->pStmt = 0; }else{ v->rc = rc; } } sqlite3Error(db, rc); rc = sqlite3ApiExit(db, rc); sqlite3_mutex_leave(db->mutex); return rc; } /* ** Read data from a blob handle. */ SQLITE_API int sqlite3_blob_read(sqlite3_blob *pBlob, void *z, int n, int iOffset){ return blobReadWrite(pBlob, z, n, iOffset, sqlite3BtreeData); } /* ** Write data to a blob handle. */ SQLITE_API int sqlite3_blob_write(sqlite3_blob *pBlob, const void *z, int n, int iOffset){ return blobReadWrite(pBlob, (void *)z, n, iOffset, sqlite3BtreePutData); } /* ** Query a blob handle for the size of the data. ** ** The Incrblob.nByte field is fixed for the lifetime of the Incrblob ** so no mutex is required for access. */ SQLITE_API int sqlite3_blob_bytes(sqlite3_blob *pBlob){ Incrblob *p = (Incrblob *)pBlob; return (p && p->pStmt) ? p->nByte : 0; } /* ** Move an existing blob handle to point to a different row of the same ** database table. ** ** If an error occurs, or if the specified row does not exist or does not ** contain a blob or text value, then an error code is returned and the ** database handle error code and message set. If this happens, then all ** subsequent calls to sqlite3_blob_xxx() functions (except blob_close()) ** immediately return SQLITE_ABORT. */ SQLITE_API int sqlite3_blob_reopen(sqlite3_blob *pBlob, sqlite3_int64 iRow){ int rc; Incrblob *p = (Incrblob *)pBlob; sqlite3 *db; if( p==0 ) return SQLITE_MISUSE_BKPT; db = p->db; sqlite3_mutex_enter(db->mutex); if( p->pStmt==0 ){ /* If there is no statement handle, then the blob-handle has ** already been invalidated. Return SQLITE_ABORT in this case. */ rc = SQLITE_ABORT; }else{ char *zErr; rc = blobSeekToRow(p, iRow, &zErr); if( rc!=SQLITE_OK ){ sqlite3ErrorWithMsg(db, rc, (zErr ? "%s" : 0), zErr); sqlite3DbFree(db, zErr); } assert( rc!=SQLITE_SCHEMA ); } rc = sqlite3ApiExit(db, rc); assert( rc==SQLITE_OK || p->pStmt==0 ); sqlite3_mutex_leave(db->mutex); return rc; } #endif /* #ifndef SQLITE_OMIT_INCRBLOB */ /************** End of vdbeblob.c ********************************************/ /************** Begin file vdbesort.c ****************************************/ /* ** 2011-07-09 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ************************************************************************* ** This file contains code for the VdbeSorter object, used in concert with ** a VdbeCursor to sort large numbers of keys for CREATE INDEX statements ** or by SELECT statements with ORDER BY clauses that cannot be satisfied ** using indexes and without LIMIT clauses. ** ** The VdbeSorter object implements a multi-threaded external merge sort ** algorithm that is efficient even if the number of elements being sorted ** exceeds the available memory. ** ** Here is the (internal, non-API) interface between this module and the ** rest of the SQLite system: ** ** sqlite3VdbeSorterInit() Create a new VdbeSorter object. ** ** sqlite3VdbeSorterWrite() Add a single new row to the VdbeSorter ** object. The row is a binary blob in the ** OP_MakeRecord format that contains both ** the ORDER BY key columns and result columns ** in the case of a SELECT w/ ORDER BY, or ** the complete record for an index entry ** in the case of a CREATE INDEX. ** ** sqlite3VdbeSorterRewind() Sort all content previously added. ** Position the read cursor on the ** first sorted element. ** ** sqlite3VdbeSorterNext() Advance the read cursor to the next sorted ** element. ** ** sqlite3VdbeSorterRowkey() Return the complete binary blob for the ** row currently under the read cursor. ** ** sqlite3VdbeSorterCompare() Compare the binary blob for the row ** currently under the read cursor against ** another binary blob X and report if ** X is strictly less than the read cursor. ** Used to enforce uniqueness in a ** CREATE UNIQUE INDEX statement. ** ** sqlite3VdbeSorterClose() Close the VdbeSorter object and reclaim ** all resources. ** ** sqlite3VdbeSorterReset() Refurbish the VdbeSorter for reuse. This ** is like Close() followed by Init() only ** much faster. ** ** The interfaces above must be called in a particular order. Write() can ** only occur in between Init()/Reset() and Rewind(). Next(), Rowkey(), and ** Compare() can only occur in between Rewind() and Close()/Reset(). i.e. ** ** Init() ** for each record: Write() ** Rewind() ** Rowkey()/Compare() ** Next() ** Close() ** ** Algorithm: ** ** Records passed to the sorter via calls to Write() are initially held ** unsorted in main memory. Assuming the amount of memory used never exceeds ** a threshold, when Rewind() is called the set of records is sorted using ** an in-memory merge sort. In this case, no temporary files are required ** and subsequent calls to Rowkey(), Next() and Compare() read records ** directly from main memory. ** ** If the amount of space used to store records in main memory exceeds the ** threshold, then the set of records currently in memory are sorted and ** written to a temporary file in "Packed Memory Array" (PMA) format. ** A PMA created at this point is known as a "level-0 PMA". Higher levels ** of PMAs may be created by merging existing PMAs together - for example ** merging two or more level-0 PMAs together creates a level-1 PMA. ** ** The threshold for the amount of main memory to use before flushing ** records to a PMA is roughly the same as the limit configured for the ** page-cache of the main database. Specifically, the threshold is set to ** the value returned by "PRAGMA main.page_size" multipled by ** that returned by "PRAGMA main.cache_size", in bytes. ** ** If the sorter is running in single-threaded mode, then all PMAs generated ** are appended to a single temporary file. Or, if the sorter is running in ** multi-threaded mode then up to (N+1) temporary files may be opened, where ** N is the configured number of worker threads. In this case, instead of ** sorting the records and writing the PMA to a temporary file itself, the ** calling thread usually launches a worker thread to do so. Except, if ** there are already N worker threads running, the main thread does the work ** itself. ** ** The sorter is running in multi-threaded mode if (a) the library was built ** with pre-processor symbol SQLITE_MAX_WORKER_THREADS set to a value greater ** than zero, and (b) worker threads have been enabled at runtime by calling ** "PRAGMA threads=N" with some value of N greater than 0. ** ** When Rewind() is called, any data remaining in memory is flushed to a ** final PMA. So at this point the data is stored in some number of sorted ** PMAs within temporary files on disk. ** ** If there are fewer than SORTER_MAX_MERGE_COUNT PMAs in total and the ** sorter is running in single-threaded mode, then these PMAs are merged ** incrementally as keys are retreived from the sorter by the VDBE. The ** MergeEngine object, described in further detail below, performs this ** merge. ** ** Or, if running in multi-threaded mode, then a background thread is ** launched to merge the existing PMAs. Once the background thread has ** merged T bytes of data into a single sorted PMA, the main thread ** begins reading keys from that PMA while the background thread proceeds ** with merging the next T bytes of data. And so on. ** ** Parameter T is set to half the value of the memory threshold used ** by Write() above to determine when to create a new PMA. ** ** If there are more than SORTER_MAX_MERGE_COUNT PMAs in total when ** Rewind() is called, then a hierarchy of incremental-merges is used. ** First, T bytes of data from the first SORTER_MAX_MERGE_COUNT PMAs on ** disk are merged together. Then T bytes of data from the second set, and ** so on, such that no operation ever merges more than SORTER_MAX_MERGE_COUNT ** PMAs at a time. This done is to improve locality. ** ** If running in multi-threaded mode and there are more than ** SORTER_MAX_MERGE_COUNT PMAs on disk when Rewind() is called, then more ** than one background thread may be created. Specifically, there may be ** one background thread for each temporary file on disk, and one background ** thread to merge the output of each of the others to a single PMA for ** the main thread to read from. */ /* #include "sqliteInt.h" */ /* #include "vdbeInt.h" */ /* ** If SQLITE_DEBUG_SORTER_THREADS is defined, this module outputs various ** messages to stderr that may be helpful in understanding the performance ** characteristics of the sorter in multi-threaded mode. */ #if 0 # define SQLITE_DEBUG_SORTER_THREADS 1 #endif /* ** Hard-coded maximum amount of data to accumulate in memory before flushing ** to a level 0 PMA. The purpose of this limit is to prevent various integer ** overflows. 512MiB. */ #define SQLITE_MAX_PMASZ (1<<29) /* ** Private objects used by the sorter */ typedef struct MergeEngine MergeEngine; /* Merge PMAs together */ typedef struct PmaReader PmaReader; /* Incrementally read one PMA */ typedef struct PmaWriter PmaWriter; /* Incrementally write one PMA */ typedef struct SorterRecord SorterRecord; /* A record being sorted */ typedef struct SortSubtask SortSubtask; /* A sub-task in the sort process */ typedef struct SorterFile SorterFile; /* Temporary file object wrapper */ typedef struct SorterList SorterList; /* In-memory list of records */ typedef struct IncrMerger IncrMerger; /* Read & merge multiple PMAs */ /* ** A container for a temp file handle and the current amount of data ** stored in the file. */ struct SorterFile { sqlite3_file *pFd; /* File handle */ i64 iEof; /* Bytes of data stored in pFd */ }; /* ** An in-memory list of objects to be sorted. ** ** If aMemory==0 then each object is allocated separately and the objects ** are connected using SorterRecord.u.pNext. If aMemory!=0 then all objects ** are stored in the aMemory[] bulk memory, one right after the other, and ** are connected using SorterRecord.u.iNext. */ struct SorterList { SorterRecord *pList; /* Linked list of records */ u8 *aMemory; /* If non-NULL, bulk memory to hold pList */ int szPMA; /* Size of pList as PMA in bytes */ }; /* ** The MergeEngine object is used to combine two or more smaller PMAs into ** one big PMA using a merge operation. Separate PMAs all need to be ** combined into one big PMA in order to be able to step through the sorted ** records in order. ** ** The aReadr[] array contains a PmaReader object for each of the PMAs being ** merged. An aReadr[] object either points to a valid key or else is at EOF. ** ("EOF" means "End Of File". When aReadr[] is at EOF there is no more data.) ** For the purposes of the paragraphs below, we assume that the array is ** actually N elements in size, where N is the smallest power of 2 greater ** to or equal to the number of PMAs being merged. The extra aReadr[] elements ** are treated as if they are empty (always at EOF). ** ** The aTree[] array is also N elements in size. The value of N is stored in ** the MergeEngine.nTree variable. ** ** The final (N/2) elements of aTree[] contain the results of comparing ** pairs of PMA keys together. Element i contains the result of ** comparing aReadr[2*i-N] and aReadr[2*i-N+1]. Whichever key is smaller, the ** aTree element is set to the index of it. ** ** For the purposes of this comparison, EOF is considered greater than any ** other key value. If the keys are equal (only possible with two EOF ** values), it doesn't matter which index is stored. ** ** The (N/4) elements of aTree[] that precede the final (N/2) described ** above contains the index of the smallest of each block of 4 PmaReaders ** And so on. So that aTree[1] contains the index of the PmaReader that ** currently points to the smallest key value. aTree[0] is unused. ** ** Example: ** ** aReadr[0] -> Banana ** aReadr[1] -> Feijoa ** aReadr[2] -> Elderberry ** aReadr[3] -> Currant ** aReadr[4] -> Grapefruit ** aReadr[5] -> Apple ** aReadr[6] -> Durian ** aReadr[7] -> EOF ** ** aTree[] = { X, 5 0, 5 0, 3, 5, 6 } ** ** The current element is "Apple" (the value of the key indicated by ** PmaReader 5). When the Next() operation is invoked, PmaReader 5 will ** be advanced to the next key in its segment. Say the next key is ** "Eggplant": ** ** aReadr[5] -> Eggplant ** ** The contents of aTree[] are updated first by comparing the new PmaReader ** 5 key to the current key of PmaReader 4 (still "Grapefruit"). The PmaReader ** 5 value is still smaller, so aTree[6] is set to 5. And so on up the tree. ** The value of PmaReader 6 - "Durian" - is now smaller than that of PmaReader ** 5, so aTree[3] is set to 6. Key 0 is smaller than key 6 (Bananafile2. And instead of using a ** background thread to prepare data for the PmaReader, with a single ** threaded IncrMerger the allocate part of pTask->file2 is "refilled" with ** keys from pMerger by the calling thread whenever the PmaReader runs out ** of data. */ struct IncrMerger { SortSubtask *pTask; /* Task that owns this merger */ MergeEngine *pMerger; /* Merge engine thread reads data from */ i64 iStartOff; /* Offset to start writing file at */ int mxSz; /* Maximum bytes of data to store */ int bEof; /* Set to true when merge is finished */ int bUseThread; /* True to use a bg thread for this object */ SorterFile aFile[2]; /* aFile[0] for reading, [1] for writing */ }; /* ** An instance of this object is used for writing a PMA. ** ** The PMA is written one record at a time. Each record is of an arbitrary ** size. But I/O is more efficient if it occurs in page-sized blocks where ** each block is aligned on a page boundary. This object caches writes to ** the PMA so that aligned, page-size blocks are written. */ struct PmaWriter { int eFWErr; /* Non-zero if in an error state */ u8 *aBuffer; /* Pointer to write buffer */ int nBuffer; /* Size of write buffer in bytes */ int iBufStart; /* First byte of buffer to write */ int iBufEnd; /* Last byte of buffer to write */ i64 iWriteOff; /* Offset of start of buffer in file */ sqlite3_file *pFd; /* File handle to write to */ }; /* ** This object is the header on a single record while that record is being ** held in memory and prior to being written out as part of a PMA. ** ** How the linked list is connected depends on how memory is being managed ** by this module. If using a separate allocation for each in-memory record ** (VdbeSorter.list.aMemory==0), then the list is always connected using the ** SorterRecord.u.pNext pointers. ** ** Or, if using the single large allocation method (VdbeSorter.list.aMemory!=0), ** then while records are being accumulated the list is linked using the ** SorterRecord.u.iNext offset. This is because the aMemory[] array may ** be sqlite3Realloc()ed while records are being accumulated. Once the VM ** has finished passing records to the sorter, or when the in-memory buffer ** is full, the list is sorted. As part of the sorting process, it is ** converted to use the SorterRecord.u.pNext pointers. See function ** vdbeSorterSort() for details. */ struct SorterRecord { int nVal; /* Size of the record in bytes */ union { SorterRecord *pNext; /* Pointer to next record in list */ int iNext; /* Offset within aMemory of next record */ } u; /* The data for the record immediately follows this header */ }; /* Return a pointer to the buffer containing the record data for SorterRecord ** object p. Should be used as if: ** ** void *SRVAL(SorterRecord *p) { return (void*)&p[1]; } */ #define SRVAL(p) ((void*)((SorterRecord*)(p) + 1)) /* Maximum number of PMAs that a single MergeEngine can merge */ #define SORTER_MAX_MERGE_COUNT 16 static int vdbeIncrSwap(IncrMerger*); static void vdbeIncrFree(IncrMerger *); /* ** Free all memory belonging to the PmaReader object passed as the ** argument. All structure fields are set to zero before returning. */ static void vdbePmaReaderClear(PmaReader *pReadr){ sqlite3_free(pReadr->aAlloc); sqlite3_free(pReadr->aBuffer); if( pReadr->aMap ) sqlite3OsUnfetch(pReadr->pFd, 0, pReadr->aMap); vdbeIncrFree(pReadr->pIncr); memset(pReadr, 0, sizeof(PmaReader)); } /* ** Read the next nByte bytes of data from the PMA p. ** If successful, set *ppOut to point to a buffer containing the data ** and return SQLITE_OK. Otherwise, if an error occurs, return an SQLite ** error code. ** ** The buffer returned in *ppOut is only valid until the ** next call to this function. */ static int vdbePmaReadBlob( PmaReader *p, /* PmaReader from which to take the blob */ int nByte, /* Bytes of data to read */ u8 **ppOut /* OUT: Pointer to buffer containing data */ ){ int iBuf; /* Offset within buffer to read from */ int nAvail; /* Bytes of data available in buffer */ if( p->aMap ){ *ppOut = &p->aMap[p->iReadOff]; p->iReadOff += nByte; return SQLITE_OK; } assert( p->aBuffer ); /* If there is no more data to be read from the buffer, read the next ** p->nBuffer bytes of data from the file into it. Or, if there are less ** than p->nBuffer bytes remaining in the PMA, read all remaining data. */ iBuf = p->iReadOff % p->nBuffer; if( iBuf==0 ){ int nRead; /* Bytes to read from disk */ int rc; /* sqlite3OsRead() return code */ /* Determine how many bytes of data to read. */ if( (p->iEof - p->iReadOff) > (i64)p->nBuffer ){ nRead = p->nBuffer; }else{ nRead = (int)(p->iEof - p->iReadOff); } assert( nRead>0 ); /* Readr data from the file. Return early if an error occurs. */ rc = sqlite3OsRead(p->pFd, p->aBuffer, nRead, p->iReadOff); assert( rc!=SQLITE_IOERR_SHORT_READ ); if( rc!=SQLITE_OK ) return rc; } nAvail = p->nBuffer - iBuf; if( nByte<=nAvail ){ /* The requested data is available in the in-memory buffer. In this ** case there is no need to make a copy of the data, just return a ** pointer into the buffer to the caller. */ *ppOut = &p->aBuffer[iBuf]; p->iReadOff += nByte; }else{ /* The requested data is not all available in the in-memory buffer. ** In this case, allocate space at p->aAlloc[] to copy the requested ** range into. Then return a copy of pointer p->aAlloc to the caller. */ int nRem; /* Bytes remaining to copy */ /* Extend the p->aAlloc[] allocation if required. */ if( p->nAllocnAlloc*2); while( nByte>nNew ) nNew = nNew*2; aNew = sqlite3Realloc(p->aAlloc, nNew); if( !aNew ) return SQLITE_NOMEM_BKPT; p->nAlloc = nNew; p->aAlloc = aNew; } /* Copy as much data as is available in the buffer into the start of ** p->aAlloc[]. */ memcpy(p->aAlloc, &p->aBuffer[iBuf], nAvail); p->iReadOff += nAvail; nRem = nByte - nAvail; /* The following loop copies up to p->nBuffer bytes per iteration into ** the p->aAlloc[] buffer. */ while( nRem>0 ){ int rc; /* vdbePmaReadBlob() return code */ int nCopy; /* Number of bytes to copy */ u8 *aNext; /* Pointer to buffer to copy data from */ nCopy = nRem; if( nRem>p->nBuffer ) nCopy = p->nBuffer; rc = vdbePmaReadBlob(p, nCopy, &aNext); if( rc!=SQLITE_OK ) return rc; assert( aNext!=p->aAlloc ); memcpy(&p->aAlloc[nByte - nRem], aNext, nCopy); nRem -= nCopy; } *ppOut = p->aAlloc; } return SQLITE_OK; } /* ** Read a varint from the stream of data accessed by p. Set *pnOut to ** the value read. */ static int vdbePmaReadVarint(PmaReader *p, u64 *pnOut){ int iBuf; if( p->aMap ){ p->iReadOff += sqlite3GetVarint(&p->aMap[p->iReadOff], pnOut); }else{ iBuf = p->iReadOff % p->nBuffer; if( iBuf && (p->nBuffer-iBuf)>=9 ){ p->iReadOff += sqlite3GetVarint(&p->aBuffer[iBuf], pnOut); }else{ u8 aVarint[16], *a; int i = 0, rc; do{ rc = vdbePmaReadBlob(p, 1, &a); if( rc ) return rc; aVarint[(i++)&0xf] = a[0]; }while( (a[0]&0x80)!=0 ); sqlite3GetVarint(aVarint, pnOut); } } return SQLITE_OK; } /* ** Attempt to memory map file pFile. If successful, set *pp to point to the ** new mapping and return SQLITE_OK. If the mapping is not attempted ** (because the file is too large or the VFS layer is configured not to use ** mmap), return SQLITE_OK and set *pp to NULL. ** ** Or, if an error occurs, return an SQLite error code. The final value of ** *pp is undefined in this case. */ static int vdbeSorterMapFile(SortSubtask *pTask, SorterFile *pFile, u8 **pp){ int rc = SQLITE_OK; if( pFile->iEof<=(i64)(pTask->pSorter->db->nMaxSorterMmap) ){ sqlite3_file *pFd = pFile->pFd; if( pFd->pMethods->iVersion>=3 ){ rc = sqlite3OsFetch(pFd, 0, (int)pFile->iEof, (void**)pp); testcase( rc!=SQLITE_OK ); } } return rc; } /* ** Attach PmaReader pReadr to file pFile (if it is not already attached to ** that file) and seek it to offset iOff within the file. Return SQLITE_OK ** if successful, or an SQLite error code if an error occurs. */ static int vdbePmaReaderSeek( SortSubtask *pTask, /* Task context */ PmaReader *pReadr, /* Reader whose cursor is to be moved */ SorterFile *pFile, /* Sorter file to read from */ i64 iOff /* Offset in pFile */ ){ int rc = SQLITE_OK; assert( pReadr->pIncr==0 || pReadr->pIncr->bEof==0 ); if( sqlite3FaultSim(201) ) return SQLITE_IOERR_READ; if( pReadr->aMap ){ sqlite3OsUnfetch(pReadr->pFd, 0, pReadr->aMap); pReadr->aMap = 0; } pReadr->iReadOff = iOff; pReadr->iEof = pFile->iEof; pReadr->pFd = pFile->pFd; rc = vdbeSorterMapFile(pTask, pFile, &pReadr->aMap); if( rc==SQLITE_OK && pReadr->aMap==0 ){ int pgsz = pTask->pSorter->pgsz; int iBuf = pReadr->iReadOff % pgsz; if( pReadr->aBuffer==0 ){ pReadr->aBuffer = (u8*)sqlite3Malloc(pgsz); if( pReadr->aBuffer==0 ) rc = SQLITE_NOMEM_BKPT; pReadr->nBuffer = pgsz; } if( rc==SQLITE_OK && iBuf ){ int nRead = pgsz - iBuf; if( (pReadr->iReadOff + nRead) > pReadr->iEof ){ nRead = (int)(pReadr->iEof - pReadr->iReadOff); } rc = sqlite3OsRead( pReadr->pFd, &pReadr->aBuffer[iBuf], nRead, pReadr->iReadOff ); testcase( rc!=SQLITE_OK ); } } return rc; } /* ** Advance PmaReader pReadr to the next key in its PMA. Return SQLITE_OK if ** no error occurs, or an SQLite error code if one does. */ static int vdbePmaReaderNext(PmaReader *pReadr){ int rc = SQLITE_OK; /* Return Code */ u64 nRec = 0; /* Size of record in bytes */ if( pReadr->iReadOff>=pReadr->iEof ){ IncrMerger *pIncr = pReadr->pIncr; int bEof = 1; if( pIncr ){ rc = vdbeIncrSwap(pIncr); if( rc==SQLITE_OK && pIncr->bEof==0 ){ rc = vdbePmaReaderSeek( pIncr->pTask, pReadr, &pIncr->aFile[0], pIncr->iStartOff ); bEof = 0; } } if( bEof ){ /* This is an EOF condition */ vdbePmaReaderClear(pReadr); testcase( rc!=SQLITE_OK ); return rc; } } if( rc==SQLITE_OK ){ rc = vdbePmaReadVarint(pReadr, &nRec); } if( rc==SQLITE_OK ){ pReadr->nKey = (int)nRec; rc = vdbePmaReadBlob(pReadr, (int)nRec, &pReadr->aKey); testcase( rc!=SQLITE_OK ); } return rc; } /* ** Initialize PmaReader pReadr to scan through the PMA stored in file pFile ** starting at offset iStart and ending at offset iEof-1. This function ** leaves the PmaReader pointing to the first key in the PMA (or EOF if the ** PMA is empty). ** ** If the pnByte parameter is NULL, then it is assumed that the file ** contains a single PMA, and that that PMA omits the initial length varint. */ static int vdbePmaReaderInit( SortSubtask *pTask, /* Task context */ SorterFile *pFile, /* Sorter file to read from */ i64 iStart, /* Start offset in pFile */ PmaReader *pReadr, /* PmaReader to populate */ i64 *pnByte /* IN/OUT: Increment this value by PMA size */ ){ int rc; assert( pFile->iEof>iStart ); assert( pReadr->aAlloc==0 && pReadr->nAlloc==0 ); assert( pReadr->aBuffer==0 ); assert( pReadr->aMap==0 ); rc = vdbePmaReaderSeek(pTask, pReadr, pFile, iStart); if( rc==SQLITE_OK ){ u64 nByte = 0; /* Size of PMA in bytes */ rc = vdbePmaReadVarint(pReadr, &nByte); pReadr->iEof = pReadr->iReadOff + nByte; *pnByte += nByte; } if( rc==SQLITE_OK ){ rc = vdbePmaReaderNext(pReadr); } return rc; } /* ** A version of vdbeSorterCompare() that assumes that it has already been ** determined that the first field of key1 is equal to the first field of ** key2. */ static int vdbeSorterCompareTail( SortSubtask *pTask, /* Subtask context (for pKeyInfo) */ int *pbKey2Cached, /* True if pTask->pUnpacked is pKey2 */ const void *pKey1, int nKey1, /* Left side of comparison */ const void *pKey2, int nKey2 /* Right side of comparison */ ){ UnpackedRecord *r2 = pTask->pUnpacked; if( *pbKey2Cached==0 ){ sqlite3VdbeRecordUnpack(pTask->pSorter->pKeyInfo, nKey2, pKey2, r2); *pbKey2Cached = 1; } return sqlite3VdbeRecordCompareWithSkip(nKey1, pKey1, r2, 1); } /* ** Compare key1 (buffer pKey1, size nKey1 bytes) with key2 (buffer pKey2, ** size nKey2 bytes). Use (pTask->pKeyInfo) for the collation sequences ** used by the comparison. Return the result of the comparison. ** ** If IN/OUT parameter *pbKey2Cached is true when this function is called, ** it is assumed that (pTask->pUnpacked) contains the unpacked version ** of key2. If it is false, (pTask->pUnpacked) is populated with the unpacked ** version of key2 and *pbKey2Cached set to true before returning. ** ** If an OOM error is encountered, (pTask->pUnpacked->error_rc) is set ** to SQLITE_NOMEM. */ static int vdbeSorterCompare( SortSubtask *pTask, /* Subtask context (for pKeyInfo) */ int *pbKey2Cached, /* True if pTask->pUnpacked is pKey2 */ const void *pKey1, int nKey1, /* Left side of comparison */ const void *pKey2, int nKey2 /* Right side of comparison */ ){ UnpackedRecord *r2 = pTask->pUnpacked; if( !*pbKey2Cached ){ sqlite3VdbeRecordUnpack(pTask->pSorter->pKeyInfo, nKey2, pKey2, r2); *pbKey2Cached = 1; } return sqlite3VdbeRecordCompare(nKey1, pKey1, r2); } /* ** A specially optimized version of vdbeSorterCompare() that assumes that ** the first field of each key is a TEXT value and that the collation ** sequence to compare them with is BINARY. */ static int vdbeSorterCompareText( SortSubtask *pTask, /* Subtask context (for pKeyInfo) */ int *pbKey2Cached, /* True if pTask->pUnpacked is pKey2 */ const void *pKey1, int nKey1, /* Left side of comparison */ const void *pKey2, int nKey2 /* Right side of comparison */ ){ const u8 * const p1 = (const u8 * const)pKey1; const u8 * const p2 = (const u8 * const)pKey2; const u8 * const v1 = &p1[ p1[0] ]; /* Pointer to value 1 */ const u8 * const v2 = &p2[ p2[0] ]; /* Pointer to value 2 */ int n1; int n2; int res; getVarint32(&p1[1], n1); n1 = (n1 - 13) / 2; getVarint32(&p2[1], n2); n2 = (n2 - 13) / 2; res = memcmp(v1, v2, MIN(n1, n2)); if( res==0 ){ res = n1 - n2; } if( res==0 ){ if( pTask->pSorter->pKeyInfo->nField>1 ){ res = vdbeSorterCompareTail( pTask, pbKey2Cached, pKey1, nKey1, pKey2, nKey2 ); } }else{ if( pTask->pSorter->pKeyInfo->aSortOrder[0] ){ res = res * -1; } } return res; } /* ** A specially optimized version of vdbeSorterCompare() that assumes that ** the first field of each key is an INTEGER value. */ static int vdbeSorterCompareInt( SortSubtask *pTask, /* Subtask context (for pKeyInfo) */ int *pbKey2Cached, /* True if pTask->pUnpacked is pKey2 */ const void *pKey1, int nKey1, /* Left side of comparison */ const void *pKey2, int nKey2 /* Right side of comparison */ ){ const u8 * const p1 = (const u8 * const)pKey1; const u8 * const p2 = (const u8 * const)pKey2; const int s1 = p1[1]; /* Left hand serial type */ const int s2 = p2[1]; /* Right hand serial type */ const u8 * const v1 = &p1[ p1[0] ]; /* Pointer to value 1 */ const u8 * const v2 = &p2[ p2[0] ]; /* Pointer to value 2 */ int res; /* Return value */ assert( (s1>0 && s1<7) || s1==8 || s1==9 ); assert( (s2>0 && s2<7) || s2==8 || s2==9 ); if( s1>7 && s2>7 ){ res = s1 - s2; }else{ if( s1==s2 ){ if( (*v1 ^ *v2) & 0x80 ){ /* The two values have different signs */ res = (*v1 & 0x80) ? -1 : +1; }else{ /* The two values have the same sign. Compare using memcmp(). */ static const u8 aLen[] = {0, 1, 2, 3, 4, 6, 8 }; int i; res = 0; for(i=0; i7 ){ res = +1; }else if( s1>7 ){ res = -1; }else{ res = s1 - s2; } assert( res!=0 ); if( res>0 ){ if( *v1 & 0x80 ) res = -1; }else{ if( *v2 & 0x80 ) res = +1; } } } if( res==0 ){ if( pTask->pSorter->pKeyInfo->nField>1 ){ res = vdbeSorterCompareTail( pTask, pbKey2Cached, pKey1, nKey1, pKey2, nKey2 ); } }else if( pTask->pSorter->pKeyInfo->aSortOrder[0] ){ res = res * -1; } return res; } /* ** Initialize the temporary index cursor just opened as a sorter cursor. ** ** Usually, the sorter module uses the value of (pCsr->pKeyInfo->nField) ** to determine the number of fields that should be compared from the ** records being sorted. However, if the value passed as argument nField ** is non-zero and the sorter is able to guarantee a stable sort, nField ** is used instead. This is used when sorting records for a CREATE INDEX ** statement. In this case, keys are always delivered to the sorter in ** order of the primary key, which happens to be make up the final part ** of the records being sorted. So if the sort is stable, there is never ** any reason to compare PK fields and they can be ignored for a small ** performance boost. ** ** The sorter can guarantee a stable sort when running in single-threaded ** mode, but not in multi-threaded mode. ** ** SQLITE_OK is returned if successful, or an SQLite error code otherwise. */ SQLITE_PRIVATE int sqlite3VdbeSorterInit( sqlite3 *db, /* Database connection (for malloc()) */ int nField, /* Number of key fields in each record */ VdbeCursor *pCsr /* Cursor that holds the new sorter */ ){ int pgsz; /* Page size of main database */ int i; /* Used to iterate through aTask[] */ VdbeSorter *pSorter; /* The new sorter */ KeyInfo *pKeyInfo; /* Copy of pCsr->pKeyInfo with db==0 */ int szKeyInfo; /* Size of pCsr->pKeyInfo in bytes */ int sz; /* Size of pSorter in bytes */ int rc = SQLITE_OK; #if SQLITE_MAX_WORKER_THREADS==0 # define nWorker 0 #else int nWorker; #endif /* Initialize the upper limit on the number of worker threads */ #if SQLITE_MAX_WORKER_THREADS>0 if( sqlite3TempInMemory(db) || sqlite3GlobalConfig.bCoreMutex==0 ){ nWorker = 0; }else{ nWorker = db->aLimit[SQLITE_LIMIT_WORKER_THREADS]; } #endif /* Do not allow the total number of threads (main thread + all workers) ** to exceed the maximum merge count */ #if SQLITE_MAX_WORKER_THREADS>=SORTER_MAX_MERGE_COUNT if( nWorker>=SORTER_MAX_MERGE_COUNT ){ nWorker = SORTER_MAX_MERGE_COUNT-1; } #endif assert( pCsr->pKeyInfo && pCsr->pBt==0 ); assert( pCsr->eCurType==CURTYPE_SORTER ); szKeyInfo = sizeof(KeyInfo) + (pCsr->pKeyInfo->nField-1)*sizeof(CollSeq*); sz = sizeof(VdbeSorter) + nWorker * sizeof(SortSubtask); pSorter = (VdbeSorter*)sqlite3DbMallocZero(db, sz + szKeyInfo); pCsr->uc.pSorter = pSorter; if( pSorter==0 ){ rc = SQLITE_NOMEM_BKPT; }else{ pSorter->pKeyInfo = pKeyInfo = (KeyInfo*)((u8*)pSorter + sz); memcpy(pKeyInfo, pCsr->pKeyInfo, szKeyInfo); pKeyInfo->db = 0; if( nField && nWorker==0 ){ pKeyInfo->nXField += (pKeyInfo->nField - nField); pKeyInfo->nField = nField; } pSorter->pgsz = pgsz = sqlite3BtreeGetPageSize(db->aDb[0].pBt); pSorter->nTask = nWorker + 1; pSorter->iPrev = (u8)(nWorker - 1); pSorter->bUseThreads = (pSorter->nTask>1); pSorter->db = db; for(i=0; inTask; i++){ SortSubtask *pTask = &pSorter->aTask[i]; pTask->pSorter = pSorter; } if( !sqlite3TempInMemory(db) ){ i64 mxCache; /* Cache size in bytes*/ u32 szPma = sqlite3GlobalConfig.szPma; pSorter->mnPmaSize = szPma * pgsz; mxCache = db->aDb[0].pSchema->cache_size; if( mxCache<0 ){ /* A negative cache-size value C indicates that the cache is abs(C) ** KiB in size. */ mxCache = mxCache * -1024; }else{ mxCache = mxCache * pgsz; } mxCache = MIN(mxCache, SQLITE_MAX_PMASZ); pSorter->mxPmaSize = MAX(pSorter->mnPmaSize, (int)mxCache); /* EVIDENCE-OF: R-26747-61719 When the application provides any amount of ** scratch memory using SQLITE_CONFIG_SCRATCH, SQLite avoids unnecessary ** large heap allocations. */ if( sqlite3GlobalConfig.pScratch==0 ){ assert( pSorter->iMemory==0 ); pSorter->nMemory = pgsz; pSorter->list.aMemory = (u8*)sqlite3Malloc(pgsz); if( !pSorter->list.aMemory ) rc = SQLITE_NOMEM_BKPT; } } if( (pKeyInfo->nField+pKeyInfo->nXField)<13 && (pKeyInfo->aColl[0]==0 || pKeyInfo->aColl[0]==db->pDfltColl) ){ pSorter->typeMask = SORTER_TYPE_INTEGER | SORTER_TYPE_TEXT; } } return rc; } #undef nWorker /* Defined at the top of this function */ /* ** Free the list of sorted records starting at pRecord. */ static void vdbeSorterRecordFree(sqlite3 *db, SorterRecord *pRecord){ SorterRecord *p; SorterRecord *pNext; for(p=pRecord; p; p=pNext){ pNext = p->u.pNext; sqlite3DbFree(db, p); } } /* ** Free all resources owned by the object indicated by argument pTask. All ** fields of *pTask are zeroed before returning. */ static void vdbeSortSubtaskCleanup(sqlite3 *db, SortSubtask *pTask){ sqlite3DbFree(db, pTask->pUnpacked); #if SQLITE_MAX_WORKER_THREADS>0 /* pTask->list.aMemory can only be non-zero if it was handed memory ** from the main thread. That only occurs SQLITE_MAX_WORKER_THREADS>0 */ if( pTask->list.aMemory ){ sqlite3_free(pTask->list.aMemory); }else #endif { assert( pTask->list.aMemory==0 ); vdbeSorterRecordFree(0, pTask->list.pList); } if( pTask->file.pFd ){ sqlite3OsCloseFree(pTask->file.pFd); } if( pTask->file2.pFd ){ sqlite3OsCloseFree(pTask->file2.pFd); } memset(pTask, 0, sizeof(SortSubtask)); } #ifdef SQLITE_DEBUG_SORTER_THREADS static void vdbeSorterWorkDebug(SortSubtask *pTask, const char *zEvent){ i64 t; int iTask = (pTask - pTask->pSorter->aTask); sqlite3OsCurrentTimeInt64(pTask->pSorter->db->pVfs, &t); fprintf(stderr, "%lld:%d %s\n", t, iTask, zEvent); } static void vdbeSorterRewindDebug(const char *zEvent){ i64 t; sqlite3OsCurrentTimeInt64(sqlite3_vfs_find(0), &t); fprintf(stderr, "%lld:X %s\n", t, zEvent); } static void vdbeSorterPopulateDebug( SortSubtask *pTask, const char *zEvent ){ i64 t; int iTask = (pTask - pTask->pSorter->aTask); sqlite3OsCurrentTimeInt64(pTask->pSorter->db->pVfs, &t); fprintf(stderr, "%lld:bg%d %s\n", t, iTask, zEvent); } static void vdbeSorterBlockDebug( SortSubtask *pTask, int bBlocked, const char *zEvent ){ if( bBlocked ){ i64 t; sqlite3OsCurrentTimeInt64(pTask->pSorter->db->pVfs, &t); fprintf(stderr, "%lld:main %s\n", t, zEvent); } } #else # define vdbeSorterWorkDebug(x,y) # define vdbeSorterRewindDebug(y) # define vdbeSorterPopulateDebug(x,y) # define vdbeSorterBlockDebug(x,y,z) #endif #if SQLITE_MAX_WORKER_THREADS>0 /* ** Join thread pTask->thread. */ static int vdbeSorterJoinThread(SortSubtask *pTask){ int rc = SQLITE_OK; if( pTask->pThread ){ #ifdef SQLITE_DEBUG_SORTER_THREADS int bDone = pTask->bDone; #endif void *pRet = SQLITE_INT_TO_PTR(SQLITE_ERROR); vdbeSorterBlockDebug(pTask, !bDone, "enter"); (void)sqlite3ThreadJoin(pTask->pThread, &pRet); vdbeSorterBlockDebug(pTask, !bDone, "exit"); rc = SQLITE_PTR_TO_INT(pRet); assert( pTask->bDone==1 ); pTask->bDone = 0; pTask->pThread = 0; } return rc; } /* ** Launch a background thread to run xTask(pIn). */ static int vdbeSorterCreateThread( SortSubtask *pTask, /* Thread will use this task object */ void *(*xTask)(void*), /* Routine to run in a separate thread */ void *pIn /* Argument passed into xTask() */ ){ assert( pTask->pThread==0 && pTask->bDone==0 ); return sqlite3ThreadCreate(&pTask->pThread, xTask, pIn); } /* ** Join all outstanding threads launched by SorterWrite() to create ** level-0 PMAs. */ static int vdbeSorterJoinAll(VdbeSorter *pSorter, int rcin){ int rc = rcin; int i; /* This function is always called by the main user thread. ** ** If this function is being called after SorterRewind() has been called, ** it is possible that thread pSorter->aTask[pSorter->nTask-1].pThread ** is currently attempt to join one of the other threads. To avoid a race ** condition where this thread also attempts to join the same object, join ** thread pSorter->aTask[pSorter->nTask-1].pThread first. */ for(i=pSorter->nTask-1; i>=0; i--){ SortSubtask *pTask = &pSorter->aTask[i]; int rc2 = vdbeSorterJoinThread(pTask); if( rc==SQLITE_OK ) rc = rc2; } return rc; } #else # define vdbeSorterJoinAll(x,rcin) (rcin) # define vdbeSorterJoinThread(pTask) SQLITE_OK #endif /* ** Allocate a new MergeEngine object capable of handling up to ** nReader PmaReader inputs. ** ** nReader is automatically rounded up to the next power of two. ** nReader may not exceed SORTER_MAX_MERGE_COUNT even after rounding up. */ static MergeEngine *vdbeMergeEngineNew(int nReader){ int N = 2; /* Smallest power of two >= nReader */ int nByte; /* Total bytes of space to allocate */ MergeEngine *pNew; /* Pointer to allocated object to return */ assert( nReader<=SORTER_MAX_MERGE_COUNT ); while( NnTree = N; pNew->pTask = 0; pNew->aReadr = (PmaReader*)&pNew[1]; pNew->aTree = (int*)&pNew->aReadr[N]; } return pNew; } /* ** Free the MergeEngine object passed as the only argument. */ static void vdbeMergeEngineFree(MergeEngine *pMerger){ int i; if( pMerger ){ for(i=0; inTree; i++){ vdbePmaReaderClear(&pMerger->aReadr[i]); } } sqlite3_free(pMerger); } /* ** Free all resources associated with the IncrMerger object indicated by ** the first argument. */ static void vdbeIncrFree(IncrMerger *pIncr){ if( pIncr ){ #if SQLITE_MAX_WORKER_THREADS>0 if( pIncr->bUseThread ){ vdbeSorterJoinThread(pIncr->pTask); if( pIncr->aFile[0].pFd ) sqlite3OsCloseFree(pIncr->aFile[0].pFd); if( pIncr->aFile[1].pFd ) sqlite3OsCloseFree(pIncr->aFile[1].pFd); } #endif vdbeMergeEngineFree(pIncr->pMerger); sqlite3_free(pIncr); } } /* ** Reset a sorting cursor back to its original empty state. */ SQLITE_PRIVATE void sqlite3VdbeSorterReset(sqlite3 *db, VdbeSorter *pSorter){ int i; (void)vdbeSorterJoinAll(pSorter, SQLITE_OK); assert( pSorter->bUseThreads || pSorter->pReader==0 ); #if SQLITE_MAX_WORKER_THREADS>0 if( pSorter->pReader ){ vdbePmaReaderClear(pSorter->pReader); sqlite3DbFree(db, pSorter->pReader); pSorter->pReader = 0; } #endif vdbeMergeEngineFree(pSorter->pMerger); pSorter->pMerger = 0; for(i=0; inTask; i++){ SortSubtask *pTask = &pSorter->aTask[i]; vdbeSortSubtaskCleanup(db, pTask); pTask->pSorter = pSorter; } if( pSorter->list.aMemory==0 ){ vdbeSorterRecordFree(0, pSorter->list.pList); } pSorter->list.pList = 0; pSorter->list.szPMA = 0; pSorter->bUsePMA = 0; pSorter->iMemory = 0; pSorter->mxKeysize = 0; sqlite3DbFree(db, pSorter->pUnpacked); pSorter->pUnpacked = 0; } /* ** Free any cursor components allocated by sqlite3VdbeSorterXXX routines. */ SQLITE_PRIVATE void sqlite3VdbeSorterClose(sqlite3 *db, VdbeCursor *pCsr){ VdbeSorter *pSorter; assert( pCsr->eCurType==CURTYPE_SORTER ); pSorter = pCsr->uc.pSorter; if( pSorter ){ sqlite3VdbeSorterReset(db, pSorter); sqlite3_free(pSorter->list.aMemory); sqlite3DbFree(db, pSorter); pCsr->uc.pSorter = 0; } } #if SQLITE_MAX_MMAP_SIZE>0 /* ** The first argument is a file-handle open on a temporary file. The file ** is guaranteed to be nByte bytes or smaller in size. This function ** attempts to extend the file to nByte bytes in size and to ensure that ** the VFS has memory mapped it. ** ** Whether or not the file does end up memory mapped of course depends on ** the specific VFS implementation. */ static void vdbeSorterExtendFile(sqlite3 *db, sqlite3_file *pFd, i64 nByte){ if( nByte<=(i64)(db->nMaxSorterMmap) && pFd->pMethods->iVersion>=3 ){ void *p = 0; int chunksize = 4*1024; sqlite3OsFileControlHint(pFd, SQLITE_FCNTL_CHUNK_SIZE, &chunksize); sqlite3OsFileControlHint(pFd, SQLITE_FCNTL_SIZE_HINT, &nByte); sqlite3OsFetch(pFd, 0, (int)nByte, &p); sqlite3OsUnfetch(pFd, 0, p); } } #else # define vdbeSorterExtendFile(x,y,z) #endif /* ** Allocate space for a file-handle and open a temporary file. If successful, ** set *ppFd to point to the malloc'd file-handle and return SQLITE_OK. ** Otherwise, set *ppFd to 0 and return an SQLite error code. */ static int vdbeSorterOpenTempFile( sqlite3 *db, /* Database handle doing sort */ i64 nExtend, /* Attempt to extend file to this size */ sqlite3_file **ppFd ){ int rc; if( sqlite3FaultSim(202) ) return SQLITE_IOERR_ACCESS; rc = sqlite3OsOpenMalloc(db->pVfs, 0, ppFd, SQLITE_OPEN_TEMP_JOURNAL | SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE | SQLITE_OPEN_EXCLUSIVE | SQLITE_OPEN_DELETEONCLOSE, &rc ); if( rc==SQLITE_OK ){ i64 max = SQLITE_MAX_MMAP_SIZE; sqlite3OsFileControlHint(*ppFd, SQLITE_FCNTL_MMAP_SIZE, (void*)&max); if( nExtend>0 ){ vdbeSorterExtendFile(db, *ppFd, nExtend); } } return rc; } /* ** If it has not already been allocated, allocate the UnpackedRecord ** structure at pTask->pUnpacked. Return SQLITE_OK if successful (or ** if no allocation was required), or SQLITE_NOMEM otherwise. */ static int vdbeSortAllocUnpacked(SortSubtask *pTask){ if( pTask->pUnpacked==0 ){ char *pFree; pTask->pUnpacked = sqlite3VdbeAllocUnpackedRecord( pTask->pSorter->pKeyInfo, 0, 0, &pFree ); assert( pTask->pUnpacked==(UnpackedRecord*)pFree ); if( pFree==0 ) return SQLITE_NOMEM_BKPT; pTask->pUnpacked->nField = pTask->pSorter->pKeyInfo->nField; pTask->pUnpacked->errCode = 0; } return SQLITE_OK; } /* ** Merge the two sorted lists p1 and p2 into a single list. */ static SorterRecord *vdbeSorterMerge( SortSubtask *pTask, /* Calling thread context */ SorterRecord *p1, /* First list to merge */ SorterRecord *p2 /* Second list to merge */ ){ SorterRecord *pFinal = 0; SorterRecord **pp = &pFinal; int bCached = 0; assert( p1!=0 && p2!=0 ); for(;;){ int res; res = pTask->xCompare( pTask, &bCached, SRVAL(p1), p1->nVal, SRVAL(p2), p2->nVal ); if( res<=0 ){ *pp = p1; pp = &p1->u.pNext; p1 = p1->u.pNext; if( p1==0 ){ *pp = p2; break; } }else{ *pp = p2; pp = &p2->u.pNext; p2 = p2->u.pNext; bCached = 0; if( p2==0 ){ *pp = p1; break; } } } return pFinal; } /* ** Return the SorterCompare function to compare values collected by the ** sorter object passed as the only argument. */ static SorterCompare vdbeSorterGetCompare(VdbeSorter *p){ if( p->typeMask==SORTER_TYPE_INTEGER ){ return vdbeSorterCompareInt; }else if( p->typeMask==SORTER_TYPE_TEXT ){ return vdbeSorterCompareText; } return vdbeSorterCompare; } /* ** Sort the linked list of records headed at pTask->pList. Return ** SQLITE_OK if successful, or an SQLite error code (i.e. SQLITE_NOMEM) if ** an error occurs. */ static int vdbeSorterSort(SortSubtask *pTask, SorterList *pList){ int i; SorterRecord **aSlot; SorterRecord *p; int rc; rc = vdbeSortAllocUnpacked(pTask); if( rc!=SQLITE_OK ) return rc; p = pList->pList; pTask->xCompare = vdbeSorterGetCompare(pTask->pSorter); aSlot = (SorterRecord **)sqlite3MallocZero(64 * sizeof(SorterRecord *)); if( !aSlot ){ return SQLITE_NOMEM_BKPT; } while( p ){ SorterRecord *pNext; if( pList->aMemory ){ if( (u8*)p==pList->aMemory ){ pNext = 0; }else{ assert( p->u.iNextaMemory) ); pNext = (SorterRecord*)&pList->aMemory[p->u.iNext]; } }else{ pNext = p->u.pNext; } p->u.pNext = 0; for(i=0; aSlot[i]; i++){ p = vdbeSorterMerge(pTask, p, aSlot[i]); aSlot[i] = 0; } aSlot[i] = p; p = pNext; } p = 0; for(i=0; i<64; i++){ if( aSlot[i]==0 ) continue; p = p ? vdbeSorterMerge(pTask, p, aSlot[i]) : aSlot[i]; } pList->pList = p; sqlite3_free(aSlot); assert( pTask->pUnpacked->errCode==SQLITE_OK || pTask->pUnpacked->errCode==SQLITE_NOMEM ); return pTask->pUnpacked->errCode; } /* ** Initialize a PMA-writer object. */ static void vdbePmaWriterInit( sqlite3_file *pFd, /* File handle to write to */ PmaWriter *p, /* Object to populate */ int nBuf, /* Buffer size */ i64 iStart /* Offset of pFd to begin writing at */ ){ memset(p, 0, sizeof(PmaWriter)); p->aBuffer = (u8*)sqlite3Malloc(nBuf); if( !p->aBuffer ){ p->eFWErr = SQLITE_NOMEM_BKPT; }else{ p->iBufEnd = p->iBufStart = (iStart % nBuf); p->iWriteOff = iStart - p->iBufStart; p->nBuffer = nBuf; p->pFd = pFd; } } /* ** Write nData bytes of data to the PMA. Return SQLITE_OK ** if successful, or an SQLite error code if an error occurs. */ static void vdbePmaWriteBlob(PmaWriter *p, u8 *pData, int nData){ int nRem = nData; while( nRem>0 && p->eFWErr==0 ){ int nCopy = nRem; if( nCopy>(p->nBuffer - p->iBufEnd) ){ nCopy = p->nBuffer - p->iBufEnd; } memcpy(&p->aBuffer[p->iBufEnd], &pData[nData-nRem], nCopy); p->iBufEnd += nCopy; if( p->iBufEnd==p->nBuffer ){ p->eFWErr = sqlite3OsWrite(p->pFd, &p->aBuffer[p->iBufStart], p->iBufEnd - p->iBufStart, p->iWriteOff + p->iBufStart ); p->iBufStart = p->iBufEnd = 0; p->iWriteOff += p->nBuffer; } assert( p->iBufEndnBuffer ); nRem -= nCopy; } } /* ** Flush any buffered data to disk and clean up the PMA-writer object. ** The results of using the PMA-writer after this call are undefined. ** Return SQLITE_OK if flushing the buffered data succeeds or is not ** required. Otherwise, return an SQLite error code. ** ** Before returning, set *piEof to the offset immediately following the ** last byte written to the file. */ static int vdbePmaWriterFinish(PmaWriter *p, i64 *piEof){ int rc; if( p->eFWErr==0 && ALWAYS(p->aBuffer) && p->iBufEnd>p->iBufStart ){ p->eFWErr = sqlite3OsWrite(p->pFd, &p->aBuffer[p->iBufStart], p->iBufEnd - p->iBufStart, p->iWriteOff + p->iBufStart ); } *piEof = (p->iWriteOff + p->iBufEnd); sqlite3_free(p->aBuffer); rc = p->eFWErr; memset(p, 0, sizeof(PmaWriter)); return rc; } /* ** Write value iVal encoded as a varint to the PMA. Return ** SQLITE_OK if successful, or an SQLite error code if an error occurs. */ static void vdbePmaWriteVarint(PmaWriter *p, u64 iVal){ int nByte; u8 aByte[10]; nByte = sqlite3PutVarint(aByte, iVal); vdbePmaWriteBlob(p, aByte, nByte); } /* ** Write the current contents of in-memory linked-list pList to a level-0 ** PMA in the temp file belonging to sub-task pTask. Return SQLITE_OK if ** successful, or an SQLite error code otherwise. ** ** The format of a PMA is: ** ** * A varint. This varint contains the total number of bytes of content ** in the PMA (not including the varint itself). ** ** * One or more records packed end-to-end in order of ascending keys. ** Each record consists of a varint followed by a blob of data (the ** key). The varint is the number of bytes in the blob of data. */ static int vdbeSorterListToPMA(SortSubtask *pTask, SorterList *pList){ sqlite3 *db = pTask->pSorter->db; int rc = SQLITE_OK; /* Return code */ PmaWriter writer; /* Object used to write to the file */ #ifdef SQLITE_DEBUG /* Set iSz to the expected size of file pTask->file after writing the PMA. ** This is used by an assert() statement at the end of this function. */ i64 iSz = pList->szPMA + sqlite3VarintLen(pList->szPMA) + pTask->file.iEof; #endif vdbeSorterWorkDebug(pTask, "enter"); memset(&writer, 0, sizeof(PmaWriter)); assert( pList->szPMA>0 ); /* If the first temporary PMA file has not been opened, open it now. */ if( pTask->file.pFd==0 ){ rc = vdbeSorterOpenTempFile(db, 0, &pTask->file.pFd); assert( rc!=SQLITE_OK || pTask->file.pFd ); assert( pTask->file.iEof==0 ); assert( pTask->nPMA==0 ); } /* Try to get the file to memory map */ if( rc==SQLITE_OK ){ vdbeSorterExtendFile(db, pTask->file.pFd, pTask->file.iEof+pList->szPMA+9); } /* Sort the list */ if( rc==SQLITE_OK ){ rc = vdbeSorterSort(pTask, pList); } if( rc==SQLITE_OK ){ SorterRecord *p; SorterRecord *pNext = 0; vdbePmaWriterInit(pTask->file.pFd, &writer, pTask->pSorter->pgsz, pTask->file.iEof); pTask->nPMA++; vdbePmaWriteVarint(&writer, pList->szPMA); for(p=pList->pList; p; p=pNext){ pNext = p->u.pNext; vdbePmaWriteVarint(&writer, p->nVal); vdbePmaWriteBlob(&writer, SRVAL(p), p->nVal); if( pList->aMemory==0 ) sqlite3_free(p); } pList->pList = p; rc = vdbePmaWriterFinish(&writer, &pTask->file.iEof); } vdbeSorterWorkDebug(pTask, "exit"); assert( rc!=SQLITE_OK || pList->pList==0 ); assert( rc!=SQLITE_OK || pTask->file.iEof==iSz ); return rc; } /* ** Advance the MergeEngine to its next entry. ** Set *pbEof to true there is no next entry because ** the MergeEngine has reached the end of all its inputs. ** ** Return SQLITE_OK if successful or an error code if an error occurs. */ static int vdbeMergeEngineStep( MergeEngine *pMerger, /* The merge engine to advance to the next row */ int *pbEof /* Set TRUE at EOF. Set false for more content */ ){ int rc; int iPrev = pMerger->aTree[1];/* Index of PmaReader to advance */ SortSubtask *pTask = pMerger->pTask; /* Advance the current PmaReader */ rc = vdbePmaReaderNext(&pMerger->aReadr[iPrev]); /* Update contents of aTree[] */ if( rc==SQLITE_OK ){ int i; /* Index of aTree[] to recalculate */ PmaReader *pReadr1; /* First PmaReader to compare */ PmaReader *pReadr2; /* Second PmaReader to compare */ int bCached = 0; /* Find the first two PmaReaders to compare. The one that was just ** advanced (iPrev) and the one next to it in the array. */ pReadr1 = &pMerger->aReadr[(iPrev & 0xFFFE)]; pReadr2 = &pMerger->aReadr[(iPrev | 0x0001)]; for(i=(pMerger->nTree+iPrev)/2; i>0; i=i/2){ /* Compare pReadr1 and pReadr2. Store the result in variable iRes. */ int iRes; if( pReadr1->pFd==0 ){ iRes = +1; }else if( pReadr2->pFd==0 ){ iRes = -1; }else{ iRes = pTask->xCompare(pTask, &bCached, pReadr1->aKey, pReadr1->nKey, pReadr2->aKey, pReadr2->nKey ); } /* If pReadr1 contained the smaller value, set aTree[i] to its index. ** Then set pReadr2 to the next PmaReader to compare to pReadr1. In this ** case there is no cache of pReadr2 in pTask->pUnpacked, so set ** pKey2 to point to the record belonging to pReadr2. ** ** Alternatively, if pReadr2 contains the smaller of the two values, ** set aTree[i] to its index and update pReadr1. If vdbeSorterCompare() ** was actually called above, then pTask->pUnpacked now contains ** a value equivalent to pReadr2. So set pKey2 to NULL to prevent ** vdbeSorterCompare() from decoding pReadr2 again. ** ** If the two values were equal, then the value from the oldest ** PMA should be considered smaller. The VdbeSorter.aReadr[] array ** is sorted from oldest to newest, so pReadr1 contains older values ** than pReadr2 iff (pReadr1aTree[i] = (int)(pReadr1 - pMerger->aReadr); pReadr2 = &pMerger->aReadr[ pMerger->aTree[i ^ 0x0001] ]; bCached = 0; }else{ if( pReadr1->pFd ) bCached = 0; pMerger->aTree[i] = (int)(pReadr2 - pMerger->aReadr); pReadr1 = &pMerger->aReadr[ pMerger->aTree[i ^ 0x0001] ]; } } *pbEof = (pMerger->aReadr[pMerger->aTree[1]].pFd==0); } return (rc==SQLITE_OK ? pTask->pUnpacked->errCode : rc); } #if SQLITE_MAX_WORKER_THREADS>0 /* ** The main routine for background threads that write level-0 PMAs. */ static void *vdbeSorterFlushThread(void *pCtx){ SortSubtask *pTask = (SortSubtask*)pCtx; int rc; /* Return code */ assert( pTask->bDone==0 ); rc = vdbeSorterListToPMA(pTask, &pTask->list); pTask->bDone = 1; return SQLITE_INT_TO_PTR(rc); } #endif /* SQLITE_MAX_WORKER_THREADS>0 */ /* ** Flush the current contents of VdbeSorter.list to a new PMA, possibly ** using a background thread. */ static int vdbeSorterFlushPMA(VdbeSorter *pSorter){ #if SQLITE_MAX_WORKER_THREADS==0 pSorter->bUsePMA = 1; return vdbeSorterListToPMA(&pSorter->aTask[0], &pSorter->list); #else int rc = SQLITE_OK; int i; SortSubtask *pTask = 0; /* Thread context used to create new PMA */ int nWorker = (pSorter->nTask-1); /* Set the flag to indicate that at least one PMA has been written. ** Or will be, anyhow. */ pSorter->bUsePMA = 1; /* Select a sub-task to sort and flush the current list of in-memory ** records to disk. If the sorter is running in multi-threaded mode, ** round-robin between the first (pSorter->nTask-1) tasks. Except, if ** the background thread from a sub-tasks previous turn is still running, ** skip it. If the first (pSorter->nTask-1) sub-tasks are all still busy, ** fall back to using the final sub-task. The first (pSorter->nTask-1) ** sub-tasks are prefered as they use background threads - the final ** sub-task uses the main thread. */ for(i=0; iiPrev + i + 1) % nWorker; pTask = &pSorter->aTask[iTest]; if( pTask->bDone ){ rc = vdbeSorterJoinThread(pTask); } if( rc!=SQLITE_OK || pTask->pThread==0 ) break; } if( rc==SQLITE_OK ){ if( i==nWorker ){ /* Use the foreground thread for this operation */ rc = vdbeSorterListToPMA(&pSorter->aTask[nWorker], &pSorter->list); }else{ /* Launch a background thread for this operation */ u8 *aMem = pTask->list.aMemory; void *pCtx = (void*)pTask; assert( pTask->pThread==0 && pTask->bDone==0 ); assert( pTask->list.pList==0 ); assert( pTask->list.aMemory==0 || pSorter->list.aMemory!=0 ); pSorter->iPrev = (u8)(pTask - pSorter->aTask); pTask->list = pSorter->list; pSorter->list.pList = 0; pSorter->list.szPMA = 0; if( aMem ){ pSorter->list.aMemory = aMem; pSorter->nMemory = sqlite3MallocSize(aMem); }else if( pSorter->list.aMemory ){ pSorter->list.aMemory = sqlite3Malloc(pSorter->nMemory); if( !pSorter->list.aMemory ) return SQLITE_NOMEM_BKPT; } rc = vdbeSorterCreateThread(pTask, vdbeSorterFlushThread, pCtx); } } return rc; #endif /* SQLITE_MAX_WORKER_THREADS!=0 */ } /* ** Add a record to the sorter. */ SQLITE_PRIVATE int sqlite3VdbeSorterWrite( const VdbeCursor *pCsr, /* Sorter cursor */ Mem *pVal /* Memory cell containing record */ ){ VdbeSorter *pSorter; int rc = SQLITE_OK; /* Return Code */ SorterRecord *pNew; /* New list element */ int bFlush; /* True to flush contents of memory to PMA */ int nReq; /* Bytes of memory required */ int nPMA; /* Bytes of PMA space required */ int t; /* serial type of first record field */ assert( pCsr->eCurType==CURTYPE_SORTER ); pSorter = pCsr->uc.pSorter; getVarint32((const u8*)&pVal->z[1], t); if( t>0 && t<10 && t!=7 ){ pSorter->typeMask &= SORTER_TYPE_INTEGER; }else if( t>10 && (t & 0x01) ){ pSorter->typeMask &= SORTER_TYPE_TEXT; }else{ pSorter->typeMask = 0; } assert( pSorter ); /* Figure out whether or not the current contents of memory should be ** flushed to a PMA before continuing. If so, do so. ** ** If using the single large allocation mode (pSorter->aMemory!=0), then ** flush the contents of memory to a new PMA if (a) at least one value is ** already in memory and (b) the new value will not fit in memory. ** ** Or, if using separate allocations for each record, flush the contents ** of memory to a PMA if either of the following are true: ** ** * The total memory allocated for the in-memory list is greater ** than (page-size * cache-size), or ** ** * The total memory allocated for the in-memory list is greater ** than (page-size * 10) and sqlite3HeapNearlyFull() returns true. */ nReq = pVal->n + sizeof(SorterRecord); nPMA = pVal->n + sqlite3VarintLen(pVal->n); if( pSorter->mxPmaSize ){ if( pSorter->list.aMemory ){ bFlush = pSorter->iMemory && (pSorter->iMemory+nReq) > pSorter->mxPmaSize; }else{ bFlush = ( (pSorter->list.szPMA > pSorter->mxPmaSize) || (pSorter->list.szPMA > pSorter->mnPmaSize && sqlite3HeapNearlyFull()) ); } if( bFlush ){ rc = vdbeSorterFlushPMA(pSorter); pSorter->list.szPMA = 0; pSorter->iMemory = 0; assert( rc!=SQLITE_OK || pSorter->list.pList==0 ); } } pSorter->list.szPMA += nPMA; if( nPMA>pSorter->mxKeysize ){ pSorter->mxKeysize = nPMA; } if( pSorter->list.aMemory ){ int nMin = pSorter->iMemory + nReq; if( nMin>pSorter->nMemory ){ u8 *aNew; int iListOff = (u8*)pSorter->list.pList - pSorter->list.aMemory; int nNew = pSorter->nMemory * 2; while( nNew < nMin ) nNew = nNew*2; if( nNew > pSorter->mxPmaSize ) nNew = pSorter->mxPmaSize; if( nNew < nMin ) nNew = nMin; aNew = sqlite3Realloc(pSorter->list.aMemory, nNew); if( !aNew ) return SQLITE_NOMEM_BKPT; pSorter->list.pList = (SorterRecord*)&aNew[iListOff]; pSorter->list.aMemory = aNew; pSorter->nMemory = nNew; } pNew = (SorterRecord*)&pSorter->list.aMemory[pSorter->iMemory]; pSorter->iMemory += ROUND8(nReq); if( pSorter->list.pList ){ pNew->u.iNext = (int)((u8*)(pSorter->list.pList) - pSorter->list.aMemory); } }else{ pNew = (SorterRecord *)sqlite3Malloc(nReq); if( pNew==0 ){ return SQLITE_NOMEM_BKPT; } pNew->u.pNext = pSorter->list.pList; } memcpy(SRVAL(pNew), pVal->z, pVal->n); pNew->nVal = pVal->n; pSorter->list.pList = pNew; return rc; } /* ** Read keys from pIncr->pMerger and populate pIncr->aFile[1]. The format ** of the data stored in aFile[1] is the same as that used by regular PMAs, ** except that the number-of-bytes varint is omitted from the start. */ static int vdbeIncrPopulate(IncrMerger *pIncr){ int rc = SQLITE_OK; int rc2; i64 iStart = pIncr->iStartOff; SorterFile *pOut = &pIncr->aFile[1]; SortSubtask *pTask = pIncr->pTask; MergeEngine *pMerger = pIncr->pMerger; PmaWriter writer; assert( pIncr->bEof==0 ); vdbeSorterPopulateDebug(pTask, "enter"); vdbePmaWriterInit(pOut->pFd, &writer, pTask->pSorter->pgsz, iStart); while( rc==SQLITE_OK ){ int dummy; PmaReader *pReader = &pMerger->aReadr[ pMerger->aTree[1] ]; int nKey = pReader->nKey; i64 iEof = writer.iWriteOff + writer.iBufEnd; /* Check if the output file is full or if the input has been exhausted. ** In either case exit the loop. */ if( pReader->pFd==0 ) break; if( (iEof + nKey + sqlite3VarintLen(nKey))>(iStart + pIncr->mxSz) ) break; /* Write the next key to the output. */ vdbePmaWriteVarint(&writer, nKey); vdbePmaWriteBlob(&writer, pReader->aKey, nKey); assert( pIncr->pMerger->pTask==pTask ); rc = vdbeMergeEngineStep(pIncr->pMerger, &dummy); } rc2 = vdbePmaWriterFinish(&writer, &pOut->iEof); if( rc==SQLITE_OK ) rc = rc2; vdbeSorterPopulateDebug(pTask, "exit"); return rc; } #if SQLITE_MAX_WORKER_THREADS>0 /* ** The main routine for background threads that populate aFile[1] of ** multi-threaded IncrMerger objects. */ static void *vdbeIncrPopulateThread(void *pCtx){ IncrMerger *pIncr = (IncrMerger*)pCtx; void *pRet = SQLITE_INT_TO_PTR( vdbeIncrPopulate(pIncr) ); pIncr->pTask->bDone = 1; return pRet; } /* ** Launch a background thread to populate aFile[1] of pIncr. */ static int vdbeIncrBgPopulate(IncrMerger *pIncr){ void *p = (void*)pIncr; assert( pIncr->bUseThread ); return vdbeSorterCreateThread(pIncr->pTask, vdbeIncrPopulateThread, p); } #endif /* ** This function is called when the PmaReader corresponding to pIncr has ** finished reading the contents of aFile[0]. Its purpose is to "refill" ** aFile[0] such that the PmaReader should start rereading it from the ** beginning. ** ** For single-threaded objects, this is accomplished by literally reading ** keys from pIncr->pMerger and repopulating aFile[0]. ** ** For multi-threaded objects, all that is required is to wait until the ** background thread is finished (if it is not already) and then swap ** aFile[0] and aFile[1] in place. If the contents of pMerger have not ** been exhausted, this function also launches a new background thread ** to populate the new aFile[1]. ** ** SQLITE_OK is returned on success, or an SQLite error code otherwise. */ static int vdbeIncrSwap(IncrMerger *pIncr){ int rc = SQLITE_OK; #if SQLITE_MAX_WORKER_THREADS>0 if( pIncr->bUseThread ){ rc = vdbeSorterJoinThread(pIncr->pTask); if( rc==SQLITE_OK ){ SorterFile f0 = pIncr->aFile[0]; pIncr->aFile[0] = pIncr->aFile[1]; pIncr->aFile[1] = f0; } if( rc==SQLITE_OK ){ if( pIncr->aFile[0].iEof==pIncr->iStartOff ){ pIncr->bEof = 1; }else{ rc = vdbeIncrBgPopulate(pIncr); } } }else #endif { rc = vdbeIncrPopulate(pIncr); pIncr->aFile[0] = pIncr->aFile[1]; if( pIncr->aFile[0].iEof==pIncr->iStartOff ){ pIncr->bEof = 1; } } return rc; } /* ** Allocate and return a new IncrMerger object to read data from pMerger. ** ** If an OOM condition is encountered, return NULL. In this case free the ** pMerger argument before returning. */ static int vdbeIncrMergerNew( SortSubtask *pTask, /* The thread that will be using the new IncrMerger */ MergeEngine *pMerger, /* The MergeEngine that the IncrMerger will control */ IncrMerger **ppOut /* Write the new IncrMerger here */ ){ int rc = SQLITE_OK; IncrMerger *pIncr = *ppOut = (IncrMerger*) (sqlite3FaultSim(100) ? 0 : sqlite3MallocZero(sizeof(*pIncr))); if( pIncr ){ pIncr->pMerger = pMerger; pIncr->pTask = pTask; pIncr->mxSz = MAX(pTask->pSorter->mxKeysize+9,pTask->pSorter->mxPmaSize/2); pTask->file2.iEof += pIncr->mxSz; }else{ vdbeMergeEngineFree(pMerger); rc = SQLITE_NOMEM_BKPT; } return rc; } #if SQLITE_MAX_WORKER_THREADS>0 /* ** Set the "use-threads" flag on object pIncr. */ static void vdbeIncrMergerSetThreads(IncrMerger *pIncr){ pIncr->bUseThread = 1; pIncr->pTask->file2.iEof -= pIncr->mxSz; } #endif /* SQLITE_MAX_WORKER_THREADS>0 */ /* ** Recompute pMerger->aTree[iOut] by comparing the next keys on the ** two PmaReaders that feed that entry. Neither of the PmaReaders ** are advanced. This routine merely does the comparison. */ static void vdbeMergeEngineCompare( MergeEngine *pMerger, /* Merge engine containing PmaReaders to compare */ int iOut /* Store the result in pMerger->aTree[iOut] */ ){ int i1; int i2; int iRes; PmaReader *p1; PmaReader *p2; assert( iOutnTree && iOut>0 ); if( iOut>=(pMerger->nTree/2) ){ i1 = (iOut - pMerger->nTree/2) * 2; i2 = i1 + 1; }else{ i1 = pMerger->aTree[iOut*2]; i2 = pMerger->aTree[iOut*2+1]; } p1 = &pMerger->aReadr[i1]; p2 = &pMerger->aReadr[i2]; if( p1->pFd==0 ){ iRes = i2; }else if( p2->pFd==0 ){ iRes = i1; }else{ SortSubtask *pTask = pMerger->pTask; int bCached = 0; int res; assert( pTask->pUnpacked!=0 ); /* from vdbeSortSubtaskMain() */ res = pTask->xCompare( pTask, &bCached, p1->aKey, p1->nKey, p2->aKey, p2->nKey ); if( res<=0 ){ iRes = i1; }else{ iRes = i2; } } pMerger->aTree[iOut] = iRes; } /* ** Allowed values for the eMode parameter to vdbeMergeEngineInit() ** and vdbePmaReaderIncrMergeInit(). ** ** Only INCRINIT_NORMAL is valid in single-threaded builds (when ** SQLITE_MAX_WORKER_THREADS==0). The other values are only used ** when there exists one or more separate worker threads. */ #define INCRINIT_NORMAL 0 #define INCRINIT_TASK 1 #define INCRINIT_ROOT 2 /* ** Forward reference required as the vdbeIncrMergeInit() and ** vdbePmaReaderIncrInit() routines are called mutually recursively when ** building a merge tree. */ static int vdbePmaReaderIncrInit(PmaReader *pReadr, int eMode); /* ** Initialize the MergeEngine object passed as the second argument. Once this ** function returns, the first key of merged data may be read from the ** MergeEngine object in the usual fashion. ** ** If argument eMode is INCRINIT_ROOT, then it is assumed that any IncrMerge ** objects attached to the PmaReader objects that the merger reads from have ** already been populated, but that they have not yet populated aFile[0] and ** set the PmaReader objects up to read from it. In this case all that is ** required is to call vdbePmaReaderNext() on each PmaReader to point it at ** its first key. ** ** Otherwise, if eMode is any value other than INCRINIT_ROOT, then use ** vdbePmaReaderIncrMergeInit() to initialize each PmaReader that feeds data ** to pMerger. ** ** SQLITE_OK is returned if successful, or an SQLite error code otherwise. */ static int vdbeMergeEngineInit( SortSubtask *pTask, /* Thread that will run pMerger */ MergeEngine *pMerger, /* MergeEngine to initialize */ int eMode /* One of the INCRINIT_XXX constants */ ){ int rc = SQLITE_OK; /* Return code */ int i; /* For looping over PmaReader objects */ int nTree = pMerger->nTree; /* eMode is always INCRINIT_NORMAL in single-threaded mode */ assert( SQLITE_MAX_WORKER_THREADS>0 || eMode==INCRINIT_NORMAL ); /* Verify that the MergeEngine is assigned to a single thread */ assert( pMerger->pTask==0 ); pMerger->pTask = pTask; for(i=0; i0 && eMode==INCRINIT_ROOT ){ /* PmaReaders should be normally initialized in order, as if they are ** reading from the same temp file this makes for more linear file IO. ** However, in the INCRINIT_ROOT case, if PmaReader aReadr[nTask-1] is ** in use it will block the vdbePmaReaderNext() call while it uses ** the main thread to fill its buffer. So calling PmaReaderNext() ** on this PmaReader before any of the multi-threaded PmaReaders takes ** better advantage of multi-processor hardware. */ rc = vdbePmaReaderNext(&pMerger->aReadr[nTree-i-1]); }else{ rc = vdbePmaReaderIncrInit(&pMerger->aReadr[i], INCRINIT_NORMAL); } if( rc!=SQLITE_OK ) return rc; } for(i=pMerger->nTree-1; i>0; i--){ vdbeMergeEngineCompare(pMerger, i); } return pTask->pUnpacked->errCode; } /* ** The PmaReader passed as the first argument is guaranteed to be an ** incremental-reader (pReadr->pIncr!=0). This function serves to open ** and/or initialize the temp file related fields of the IncrMerge ** object at (pReadr->pIncr). ** ** If argument eMode is set to INCRINIT_NORMAL, then all PmaReaders ** in the sub-tree headed by pReadr are also initialized. Data is then ** loaded into the buffers belonging to pReadr and it is set to point to ** the first key in its range. ** ** If argument eMode is set to INCRINIT_TASK, then pReadr is guaranteed ** to be a multi-threaded PmaReader and this function is being called in a ** background thread. In this case all PmaReaders in the sub-tree are ** initialized as for INCRINIT_NORMAL and the aFile[1] buffer belonging to ** pReadr is populated. However, pReadr itself is not set up to point ** to its first key. A call to vdbePmaReaderNext() is still required to do ** that. ** ** The reason this function does not call vdbePmaReaderNext() immediately ** in the INCRINIT_TASK case is that vdbePmaReaderNext() assumes that it has ** to block on thread (pTask->thread) before accessing aFile[1]. But, since ** this entire function is being run by thread (pTask->thread), that will ** lead to the current background thread attempting to join itself. ** ** Finally, if argument eMode is set to INCRINIT_ROOT, it may be assumed ** that pReadr->pIncr is a multi-threaded IncrMerge objects, and that all ** child-trees have already been initialized using IncrInit(INCRINIT_TASK). ** In this case vdbePmaReaderNext() is called on all child PmaReaders and ** the current PmaReader set to point to the first key in its range. ** ** SQLITE_OK is returned if successful, or an SQLite error code otherwise. */ static int vdbePmaReaderIncrMergeInit(PmaReader *pReadr, int eMode){ int rc = SQLITE_OK; IncrMerger *pIncr = pReadr->pIncr; SortSubtask *pTask = pIncr->pTask; sqlite3 *db = pTask->pSorter->db; /* eMode is always INCRINIT_NORMAL in single-threaded mode */ assert( SQLITE_MAX_WORKER_THREADS>0 || eMode==INCRINIT_NORMAL ); rc = vdbeMergeEngineInit(pTask, pIncr->pMerger, eMode); /* Set up the required files for pIncr. A multi-theaded IncrMerge object ** requires two temp files to itself, whereas a single-threaded object ** only requires a region of pTask->file2. */ if( rc==SQLITE_OK ){ int mxSz = pIncr->mxSz; #if SQLITE_MAX_WORKER_THREADS>0 if( pIncr->bUseThread ){ rc = vdbeSorterOpenTempFile(db, mxSz, &pIncr->aFile[0].pFd); if( rc==SQLITE_OK ){ rc = vdbeSorterOpenTempFile(db, mxSz, &pIncr->aFile[1].pFd); } }else #endif /*if( !pIncr->bUseThread )*/{ if( pTask->file2.pFd==0 ){ assert( pTask->file2.iEof>0 ); rc = vdbeSorterOpenTempFile(db, pTask->file2.iEof, &pTask->file2.pFd); pTask->file2.iEof = 0; } if( rc==SQLITE_OK ){ pIncr->aFile[1].pFd = pTask->file2.pFd; pIncr->iStartOff = pTask->file2.iEof; pTask->file2.iEof += mxSz; } } } #if SQLITE_MAX_WORKER_THREADS>0 if( rc==SQLITE_OK && pIncr->bUseThread ){ /* Use the current thread to populate aFile[1], even though this ** PmaReader is multi-threaded. If this is an INCRINIT_TASK object, ** then this function is already running in background thread ** pIncr->pTask->thread. ** ** If this is the INCRINIT_ROOT object, then it is running in the ** main VDBE thread. But that is Ok, as that thread cannot return ** control to the VDBE or proceed with anything useful until the ** first results are ready from this merger object anyway. */ assert( eMode==INCRINIT_ROOT || eMode==INCRINIT_TASK ); rc = vdbeIncrPopulate(pIncr); } #endif if( rc==SQLITE_OK && (SQLITE_MAX_WORKER_THREADS==0 || eMode!=INCRINIT_TASK) ){ rc = vdbePmaReaderNext(pReadr); } return rc; } #if SQLITE_MAX_WORKER_THREADS>0 /* ** The main routine for vdbePmaReaderIncrMergeInit() operations run in ** background threads. */ static void *vdbePmaReaderBgIncrInit(void *pCtx){ PmaReader *pReader = (PmaReader*)pCtx; void *pRet = SQLITE_INT_TO_PTR( vdbePmaReaderIncrMergeInit(pReader,INCRINIT_TASK) ); pReader->pIncr->pTask->bDone = 1; return pRet; } #endif /* ** If the PmaReader passed as the first argument is not an incremental-reader ** (if pReadr->pIncr==0), then this function is a no-op. Otherwise, it invokes ** the vdbePmaReaderIncrMergeInit() function with the parameters passed to ** this routine to initialize the incremental merge. ** ** If the IncrMerger object is multi-threaded (IncrMerger.bUseThread==1), ** then a background thread is launched to call vdbePmaReaderIncrMergeInit(). ** Or, if the IncrMerger is single threaded, the same function is called ** using the current thread. */ static int vdbePmaReaderIncrInit(PmaReader *pReadr, int eMode){ IncrMerger *pIncr = pReadr->pIncr; /* Incremental merger */ int rc = SQLITE_OK; /* Return code */ if( pIncr ){ #if SQLITE_MAX_WORKER_THREADS>0 assert( pIncr->bUseThread==0 || eMode==INCRINIT_TASK ); if( pIncr->bUseThread ){ void *pCtx = (void*)pReadr; rc = vdbeSorterCreateThread(pIncr->pTask, vdbePmaReaderBgIncrInit, pCtx); }else #endif { rc = vdbePmaReaderIncrMergeInit(pReadr, eMode); } } return rc; } /* ** Allocate a new MergeEngine object to merge the contents of nPMA level-0 ** PMAs from pTask->file. If no error occurs, set *ppOut to point to ** the new object and return SQLITE_OK. Or, if an error does occur, set *ppOut ** to NULL and return an SQLite error code. ** ** When this function is called, *piOffset is set to the offset of the ** first PMA to read from pTask->file. Assuming no error occurs, it is ** set to the offset immediately following the last byte of the last ** PMA before returning. If an error does occur, then the final value of ** *piOffset is undefined. */ static int vdbeMergeEngineLevel0( SortSubtask *pTask, /* Sorter task to read from */ int nPMA, /* Number of PMAs to read */ i64 *piOffset, /* IN/OUT: Readr offset in pTask->file */ MergeEngine **ppOut /* OUT: New merge-engine */ ){ MergeEngine *pNew; /* Merge engine to return */ i64 iOff = *piOffset; int i; int rc = SQLITE_OK; *ppOut = pNew = vdbeMergeEngineNew(nPMA); if( pNew==0 ) rc = SQLITE_NOMEM_BKPT; for(i=0; iaReadr[i]; rc = vdbePmaReaderInit(pTask, &pTask->file, iOff, pReadr, &nDummy); iOff = pReadr->iEof; } if( rc!=SQLITE_OK ){ vdbeMergeEngineFree(pNew); *ppOut = 0; } *piOffset = iOff; return rc; } /* ** Return the depth of a tree comprising nPMA PMAs, assuming a fanout of ** SORTER_MAX_MERGE_COUNT. The returned value does not include leaf nodes. ** ** i.e. ** ** nPMA<=16 -> TreeDepth() == 0 ** nPMA<=256 -> TreeDepth() == 1 ** nPMA<=65536 -> TreeDepth() == 2 */ static int vdbeSorterTreeDepth(int nPMA){ int nDepth = 0; i64 nDiv = SORTER_MAX_MERGE_COUNT; while( nDiv < (i64)nPMA ){ nDiv = nDiv * SORTER_MAX_MERGE_COUNT; nDepth++; } return nDepth; } /* ** pRoot is the root of an incremental merge-tree with depth nDepth (according ** to vdbeSorterTreeDepth()). pLeaf is the iSeq'th leaf to be added to the ** tree, counting from zero. This function adds pLeaf to the tree. ** ** If successful, SQLITE_OK is returned. If an error occurs, an SQLite error ** code is returned and pLeaf is freed. */ static int vdbeSorterAddToTree( SortSubtask *pTask, /* Task context */ int nDepth, /* Depth of tree according to TreeDepth() */ int iSeq, /* Sequence number of leaf within tree */ MergeEngine *pRoot, /* Root of tree */ MergeEngine *pLeaf /* Leaf to add to tree */ ){ int rc = SQLITE_OK; int nDiv = 1; int i; MergeEngine *p = pRoot; IncrMerger *pIncr; rc = vdbeIncrMergerNew(pTask, pLeaf, &pIncr); for(i=1; iaReadr[iIter]; if( pReadr->pIncr==0 ){ MergeEngine *pNew = vdbeMergeEngineNew(SORTER_MAX_MERGE_COUNT); if( pNew==0 ){ rc = SQLITE_NOMEM_BKPT; }else{ rc = vdbeIncrMergerNew(pTask, pNew, &pReadr->pIncr); } } if( rc==SQLITE_OK ){ p = pReadr->pIncr->pMerger; nDiv = nDiv / SORTER_MAX_MERGE_COUNT; } } if( rc==SQLITE_OK ){ p->aReadr[iSeq % SORTER_MAX_MERGE_COUNT].pIncr = pIncr; }else{ vdbeIncrFree(pIncr); } return rc; } /* ** This function is called as part of a SorterRewind() operation on a sorter ** that has already written two or more level-0 PMAs to one or more temp ** files. It builds a tree of MergeEngine/IncrMerger/PmaReader objects that ** can be used to incrementally merge all PMAs on disk. ** ** If successful, SQLITE_OK is returned and *ppOut set to point to the ** MergeEngine object at the root of the tree before returning. Or, if an ** error occurs, an SQLite error code is returned and the final value ** of *ppOut is undefined. */ static int vdbeSorterMergeTreeBuild( VdbeSorter *pSorter, /* The VDBE cursor that implements the sort */ MergeEngine **ppOut /* Write the MergeEngine here */ ){ MergeEngine *pMain = 0; int rc = SQLITE_OK; int iTask; #if SQLITE_MAX_WORKER_THREADS>0 /* If the sorter uses more than one task, then create the top-level ** MergeEngine here. This MergeEngine will read data from exactly ** one PmaReader per sub-task. */ assert( pSorter->bUseThreads || pSorter->nTask==1 ); if( pSorter->nTask>1 ){ pMain = vdbeMergeEngineNew(pSorter->nTask); if( pMain==0 ) rc = SQLITE_NOMEM_BKPT; } #endif for(iTask=0; rc==SQLITE_OK && iTasknTask; iTask++){ SortSubtask *pTask = &pSorter->aTask[iTask]; assert( pTask->nPMA>0 || SQLITE_MAX_WORKER_THREADS>0 ); if( SQLITE_MAX_WORKER_THREADS==0 || pTask->nPMA ){ MergeEngine *pRoot = 0; /* Root node of tree for this task */ int nDepth = vdbeSorterTreeDepth(pTask->nPMA); i64 iReadOff = 0; if( pTask->nPMA<=SORTER_MAX_MERGE_COUNT ){ rc = vdbeMergeEngineLevel0(pTask, pTask->nPMA, &iReadOff, &pRoot); }else{ int i; int iSeq = 0; pRoot = vdbeMergeEngineNew(SORTER_MAX_MERGE_COUNT); if( pRoot==0 ) rc = SQLITE_NOMEM_BKPT; for(i=0; inPMA && rc==SQLITE_OK; i += SORTER_MAX_MERGE_COUNT){ MergeEngine *pMerger = 0; /* New level-0 PMA merger */ int nReader; /* Number of level-0 PMAs to merge */ nReader = MIN(pTask->nPMA - i, SORTER_MAX_MERGE_COUNT); rc = vdbeMergeEngineLevel0(pTask, nReader, &iReadOff, &pMerger); if( rc==SQLITE_OK ){ rc = vdbeSorterAddToTree(pTask, nDepth, iSeq++, pRoot, pMerger); } } } if( rc==SQLITE_OK ){ #if SQLITE_MAX_WORKER_THREADS>0 if( pMain!=0 ){ rc = vdbeIncrMergerNew(pTask, pRoot, &pMain->aReadr[iTask].pIncr); }else #endif { assert( pMain==0 ); pMain = pRoot; } }else{ vdbeMergeEngineFree(pRoot); } } } if( rc!=SQLITE_OK ){ vdbeMergeEngineFree(pMain); pMain = 0; } *ppOut = pMain; return rc; } /* ** This function is called as part of an sqlite3VdbeSorterRewind() operation ** on a sorter that has written two or more PMAs to temporary files. It sets ** up either VdbeSorter.pMerger (for single threaded sorters) or pReader ** (for multi-threaded sorters) so that it can be used to iterate through ** all records stored in the sorter. ** ** SQLITE_OK is returned if successful, or an SQLite error code otherwise. */ static int vdbeSorterSetupMerge(VdbeSorter *pSorter){ int rc; /* Return code */ SortSubtask *pTask0 = &pSorter->aTask[0]; MergeEngine *pMain = 0; #if SQLITE_MAX_WORKER_THREADS sqlite3 *db = pTask0->pSorter->db; int i; SorterCompare xCompare = vdbeSorterGetCompare(pSorter); for(i=0; inTask; i++){ pSorter->aTask[i].xCompare = xCompare; } #endif rc = vdbeSorterMergeTreeBuild(pSorter, &pMain); if( rc==SQLITE_OK ){ #if SQLITE_MAX_WORKER_THREADS assert( pSorter->bUseThreads==0 || pSorter->nTask>1 ); if( pSorter->bUseThreads ){ int iTask; PmaReader *pReadr = 0; SortSubtask *pLast = &pSorter->aTask[pSorter->nTask-1]; rc = vdbeSortAllocUnpacked(pLast); if( rc==SQLITE_OK ){ pReadr = (PmaReader*)sqlite3DbMallocZero(db, sizeof(PmaReader)); pSorter->pReader = pReadr; if( pReadr==0 ) rc = SQLITE_NOMEM_BKPT; } if( rc==SQLITE_OK ){ rc = vdbeIncrMergerNew(pLast, pMain, &pReadr->pIncr); if( rc==SQLITE_OK ){ vdbeIncrMergerSetThreads(pReadr->pIncr); for(iTask=0; iTask<(pSorter->nTask-1); iTask++){ IncrMerger *pIncr; if( (pIncr = pMain->aReadr[iTask].pIncr) ){ vdbeIncrMergerSetThreads(pIncr); assert( pIncr->pTask!=pLast ); } } for(iTask=0; rc==SQLITE_OK && iTasknTask; iTask++){ /* Check that: ** ** a) The incremental merge object is configured to use the ** right task, and ** b) If it is using task (nTask-1), it is configured to run ** in single-threaded mode. This is important, as the ** root merge (INCRINIT_ROOT) will be using the same task ** object. */ PmaReader *p = &pMain->aReadr[iTask]; assert( p->pIncr==0 || ( (p->pIncr->pTask==&pSorter->aTask[iTask]) /* a */ && (iTask!=pSorter->nTask-1 || p->pIncr->bUseThread==0) /* b */ )); rc = vdbePmaReaderIncrInit(p, INCRINIT_TASK); } } pMain = 0; } if( rc==SQLITE_OK ){ rc = vdbePmaReaderIncrMergeInit(pReadr, INCRINIT_ROOT); } }else #endif { rc = vdbeMergeEngineInit(pTask0, pMain, INCRINIT_NORMAL); pSorter->pMerger = pMain; pMain = 0; } } if( rc!=SQLITE_OK ){ vdbeMergeEngineFree(pMain); } return rc; } /* ** Once the sorter has been populated by calls to sqlite3VdbeSorterWrite, ** this function is called to prepare for iterating through the records ** in sorted order. */ SQLITE_PRIVATE int sqlite3VdbeSorterRewind(const VdbeCursor *pCsr, int *pbEof){ VdbeSorter *pSorter; int rc = SQLITE_OK; /* Return code */ assert( pCsr->eCurType==CURTYPE_SORTER ); pSorter = pCsr->uc.pSorter; assert( pSorter ); /* If no data has been written to disk, then do not do so now. Instead, ** sort the VdbeSorter.pRecord list. The vdbe layer will read data directly ** from the in-memory list. */ if( pSorter->bUsePMA==0 ){ if( pSorter->list.pList ){ *pbEof = 0; rc = vdbeSorterSort(&pSorter->aTask[0], &pSorter->list); }else{ *pbEof = 1; } return rc; } /* Write the current in-memory list to a PMA. When the VdbeSorterWrite() ** function flushes the contents of memory to disk, it immediately always ** creates a new list consisting of a single key immediately afterwards. ** So the list is never empty at this point. */ assert( pSorter->list.pList ); rc = vdbeSorterFlushPMA(pSorter); /* Join all threads */ rc = vdbeSorterJoinAll(pSorter, rc); vdbeSorterRewindDebug("rewind"); /* Assuming no errors have occurred, set up a merger structure to ** incrementally read and merge all remaining PMAs. */ assert( pSorter->pReader==0 ); if( rc==SQLITE_OK ){ rc = vdbeSorterSetupMerge(pSorter); *pbEof = 0; } vdbeSorterRewindDebug("rewinddone"); return rc; } /* ** Advance to the next element in the sorter. */ SQLITE_PRIVATE int sqlite3VdbeSorterNext(sqlite3 *db, const VdbeCursor *pCsr, int *pbEof){ VdbeSorter *pSorter; int rc; /* Return code */ assert( pCsr->eCurType==CURTYPE_SORTER ); pSorter = pCsr->uc.pSorter; assert( pSorter->bUsePMA || (pSorter->pReader==0 && pSorter->pMerger==0) ); if( pSorter->bUsePMA ){ assert( pSorter->pReader==0 || pSorter->pMerger==0 ); assert( pSorter->bUseThreads==0 || pSorter->pReader ); assert( pSorter->bUseThreads==1 || pSorter->pMerger ); #if SQLITE_MAX_WORKER_THREADS>0 if( pSorter->bUseThreads ){ rc = vdbePmaReaderNext(pSorter->pReader); *pbEof = (pSorter->pReader->pFd==0); }else #endif /*if( !pSorter->bUseThreads )*/ { assert( pSorter->pMerger!=0 ); assert( pSorter->pMerger->pTask==(&pSorter->aTask[0]) ); rc = vdbeMergeEngineStep(pSorter->pMerger, pbEof); } }else{ SorterRecord *pFree = pSorter->list.pList; pSorter->list.pList = pFree->u.pNext; pFree->u.pNext = 0; if( pSorter->list.aMemory==0 ) vdbeSorterRecordFree(db, pFree); *pbEof = !pSorter->list.pList; rc = SQLITE_OK; } return rc; } /* ** Return a pointer to a buffer owned by the sorter that contains the ** current key. */ static void *vdbeSorterRowkey( const VdbeSorter *pSorter, /* Sorter object */ int *pnKey /* OUT: Size of current key in bytes */ ){ void *pKey; if( pSorter->bUsePMA ){ PmaReader *pReader; #if SQLITE_MAX_WORKER_THREADS>0 if( pSorter->bUseThreads ){ pReader = pSorter->pReader; }else #endif /*if( !pSorter->bUseThreads )*/{ pReader = &pSorter->pMerger->aReadr[pSorter->pMerger->aTree[1]]; } *pnKey = pReader->nKey; pKey = pReader->aKey; }else{ *pnKey = pSorter->list.pList->nVal; pKey = SRVAL(pSorter->list.pList); } return pKey; } /* ** Copy the current sorter key into the memory cell pOut. */ SQLITE_PRIVATE int sqlite3VdbeSorterRowkey(const VdbeCursor *pCsr, Mem *pOut){ VdbeSorter *pSorter; void *pKey; int nKey; /* Sorter key to copy into pOut */ assert( pCsr->eCurType==CURTYPE_SORTER ); pSorter = pCsr->uc.pSorter; pKey = vdbeSorterRowkey(pSorter, &nKey); if( sqlite3VdbeMemClearAndResize(pOut, nKey) ){ return SQLITE_NOMEM_BKPT; } pOut->n = nKey; MemSetTypeFlag(pOut, MEM_Blob); memcpy(pOut->z, pKey, nKey); return SQLITE_OK; } /* ** Compare the key in memory cell pVal with the key that the sorter cursor ** passed as the first argument currently points to. For the purposes of ** the comparison, ignore the rowid field at the end of each record. ** ** If the sorter cursor key contains any NULL values, consider it to be ** less than pVal. Even if pVal also contains NULL values. ** ** If an error occurs, return an SQLite error code (i.e. SQLITE_NOMEM). ** Otherwise, set *pRes to a negative, zero or positive value if the ** key in pVal is smaller than, equal to or larger than the current sorter ** key. ** ** This routine forms the core of the OP_SorterCompare opcode, which in ** turn is used to verify uniqueness when constructing a UNIQUE INDEX. */ SQLITE_PRIVATE int sqlite3VdbeSorterCompare( const VdbeCursor *pCsr, /* Sorter cursor */ Mem *pVal, /* Value to compare to current sorter key */ int nKeyCol, /* Compare this many columns */ int *pRes /* OUT: Result of comparison */ ){ VdbeSorter *pSorter; UnpackedRecord *r2; KeyInfo *pKeyInfo; int i; void *pKey; int nKey; /* Sorter key to compare pVal with */ assert( pCsr->eCurType==CURTYPE_SORTER ); pSorter = pCsr->uc.pSorter; r2 = pSorter->pUnpacked; pKeyInfo = pCsr->pKeyInfo; if( r2==0 ){ char *p; r2 = pSorter->pUnpacked = sqlite3VdbeAllocUnpackedRecord(pKeyInfo,0,0,&p); assert( pSorter->pUnpacked==(UnpackedRecord*)p ); if( r2==0 ) return SQLITE_NOMEM_BKPT; r2->nField = nKeyCol; } assert( r2->nField==nKeyCol ); pKey = vdbeSorterRowkey(pSorter, &nKey); sqlite3VdbeRecordUnpack(pKeyInfo, nKey, pKey, r2); for(i=0; iaMem[i].flags & MEM_Null ){ *pRes = -1; return SQLITE_OK; } } *pRes = sqlite3VdbeRecordCompare(pVal->n, pVal->z, r2); return SQLITE_OK; } /************** End of vdbesort.c ********************************************/ /************** Begin file memjournal.c **************************************/ /* ** 2008 October 7 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ************************************************************************* ** ** This file contains code use to implement an in-memory rollback journal. ** The in-memory rollback journal is used to journal transactions for ** ":memory:" databases and when the journal_mode=MEMORY pragma is used. ** ** Update: The in-memory journal is also used to temporarily cache ** smaller journals that are not critical for power-loss recovery. ** For example, statement journals that are not too big will be held ** entirely in memory, thus reducing the number of file I/O calls, and ** more importantly, reducing temporary file creation events. If these ** journals become too large for memory, they are spilled to disk. But ** in the common case, they are usually small and no file I/O needs to ** occur. */ /* #include "sqliteInt.h" */ /* Forward references to internal structures */ typedef struct MemJournal MemJournal; typedef struct FilePoint FilePoint; typedef struct FileChunk FileChunk; /* ** The rollback journal is composed of a linked list of these structures. ** ** The zChunk array is always at least 8 bytes in size - usually much more. ** Its actual size is stored in the MemJournal.nChunkSize variable. */ struct FileChunk { FileChunk *pNext; /* Next chunk in the journal */ u8 zChunk[8]; /* Content of this chunk */ }; /* ** By default, allocate this many bytes of memory for each FileChunk object. */ #define MEMJOURNAL_DFLT_FILECHUNKSIZE 1024 /* ** For chunk size nChunkSize, return the number of bytes that should ** be allocated for each FileChunk structure. */ #define fileChunkSize(nChunkSize) (sizeof(FileChunk) + ((nChunkSize)-8)) /* ** An instance of this object serves as a cursor into the rollback journal. ** The cursor can be either for reading or writing. */ struct FilePoint { sqlite3_int64 iOffset; /* Offset from the beginning of the file */ FileChunk *pChunk; /* Specific chunk into which cursor points */ }; /* ** This structure is a subclass of sqlite3_file. Each open memory-journal ** is an instance of this class. */ struct MemJournal { const sqlite3_io_methods *pMethod; /* Parent class. MUST BE FIRST */ int nChunkSize; /* In-memory chunk-size */ int nSpill; /* Bytes of data before flushing */ int nSize; /* Bytes of data currently in memory */ FileChunk *pFirst; /* Head of in-memory chunk-list */ FilePoint endpoint; /* Pointer to the end of the file */ FilePoint readpoint; /* Pointer to the end of the last xRead() */ int flags; /* xOpen flags */ sqlite3_vfs *pVfs; /* The "real" underlying VFS */ const char *zJournal; /* Name of the journal file */ }; /* ** Read data from the in-memory journal file. This is the implementation ** of the sqlite3_vfs.xRead method. */ static int memjrnlRead( sqlite3_file *pJfd, /* The journal file from which to read */ void *zBuf, /* Put the results here */ int iAmt, /* Number of bytes to read */ sqlite_int64 iOfst /* Begin reading at this offset */ ){ MemJournal *p = (MemJournal *)pJfd; u8 *zOut = zBuf; int nRead = iAmt; int iChunkOffset; FileChunk *pChunk; #ifdef SQLITE_ENABLE_ATOMIC_WRITE if( (iAmt+iOfst)>p->endpoint.iOffset ){ return SQLITE_IOERR_SHORT_READ; } #endif assert( (iAmt+iOfst)<=p->endpoint.iOffset ); assert( p->readpoint.iOffset==0 || p->readpoint.pChunk!=0 ); if( p->readpoint.iOffset!=iOfst || iOfst==0 ){ sqlite3_int64 iOff = 0; for(pChunk=p->pFirst; ALWAYS(pChunk) && (iOff+p->nChunkSize)<=iOfst; pChunk=pChunk->pNext ){ iOff += p->nChunkSize; } }else{ pChunk = p->readpoint.pChunk; assert( pChunk!=0 ); } iChunkOffset = (int)(iOfst%p->nChunkSize); do { int iSpace = p->nChunkSize - iChunkOffset; int nCopy = MIN(nRead, (p->nChunkSize - iChunkOffset)); memcpy(zOut, (u8*)pChunk->zChunk + iChunkOffset, nCopy); zOut += nCopy; nRead -= iSpace; iChunkOffset = 0; } while( nRead>=0 && (pChunk=pChunk->pNext)!=0 && nRead>0 ); p->readpoint.iOffset = pChunk ? iOfst+iAmt : 0; p->readpoint.pChunk = pChunk; return SQLITE_OK; } /* ** Free the list of FileChunk structures headed at MemJournal.pFirst. */ static void memjrnlFreeChunks(MemJournal *p){ FileChunk *pIter; FileChunk *pNext; for(pIter=p->pFirst; pIter; pIter=pNext){ pNext = pIter->pNext; sqlite3_free(pIter); } p->pFirst = 0; } /* ** Flush the contents of memory to a real file on disk. */ static int memjrnlCreateFile(MemJournal *p){ int rc; sqlite3_file *pReal = (sqlite3_file*)p; MemJournal copy = *p; memset(p, 0, sizeof(MemJournal)); rc = sqlite3OsOpen(copy.pVfs, copy.zJournal, pReal, copy.flags, 0); if( rc==SQLITE_OK ){ int nChunk = copy.nChunkSize; i64 iOff = 0; FileChunk *pIter; for(pIter=copy.pFirst; pIter; pIter=pIter->pNext){ if( iOff + nChunk > copy.endpoint.iOffset ){ nChunk = copy.endpoint.iOffset - iOff; } rc = sqlite3OsWrite(pReal, (u8*)pIter->zChunk, nChunk, iOff); if( rc ) break; iOff += nChunk; } if( rc==SQLITE_OK ){ /* No error has occurred. Free the in-memory buffers. */ memjrnlFreeChunks(©); } } if( rc!=SQLITE_OK ){ /* If an error occurred while creating or writing to the file, restore ** the original before returning. This way, SQLite uses the in-memory ** journal data to roll back changes made to the internal page-cache ** before this function was called. */ sqlite3OsClose(pReal); *p = copy; } return rc; } /* ** Write data to the file. */ static int memjrnlWrite( sqlite3_file *pJfd, /* The journal file into which to write */ const void *zBuf, /* Take data to be written from here */ int iAmt, /* Number of bytes to write */ sqlite_int64 iOfst /* Begin writing at this offset into the file */ ){ MemJournal *p = (MemJournal *)pJfd; int nWrite = iAmt; u8 *zWrite = (u8 *)zBuf; /* If the file should be created now, create it and write the new data ** into the file on disk. */ if( p->nSpill>0 && (iAmt+iOfst)>p->nSpill ){ int rc = memjrnlCreateFile(p); if( rc==SQLITE_OK ){ rc = sqlite3OsWrite(pJfd, zBuf, iAmt, iOfst); } return rc; } /* If the contents of this write should be stored in memory */ else{ /* An in-memory journal file should only ever be appended to. Random ** access writes are not required. The only exception to this is when ** the in-memory journal is being used by a connection using the ** atomic-write optimization. In this case the first 28 bytes of the ** journal file may be written as part of committing the transaction. */ assert( iOfst==p->endpoint.iOffset || iOfst==0 ); #ifdef SQLITE_ENABLE_ATOMIC_WRITE if( iOfst==0 && p->pFirst ){ assert( p->nChunkSize>iAmt ); memcpy((u8*)p->pFirst->zChunk, zBuf, iAmt); }else #else assert( iOfst>0 || p->pFirst==0 ); #endif { while( nWrite>0 ){ FileChunk *pChunk = p->endpoint.pChunk; int iChunkOffset = (int)(p->endpoint.iOffset%p->nChunkSize); int iSpace = MIN(nWrite, p->nChunkSize - iChunkOffset); if( iChunkOffset==0 ){ /* New chunk is required to extend the file. */ FileChunk *pNew = sqlite3_malloc(fileChunkSize(p->nChunkSize)); if( !pNew ){ return SQLITE_IOERR_NOMEM_BKPT; } pNew->pNext = 0; if( pChunk ){ assert( p->pFirst ); pChunk->pNext = pNew; }else{ assert( !p->pFirst ); p->pFirst = pNew; } p->endpoint.pChunk = pNew; } memcpy((u8*)p->endpoint.pChunk->zChunk + iChunkOffset, zWrite, iSpace); zWrite += iSpace; nWrite -= iSpace; p->endpoint.iOffset += iSpace; } p->nSize = iAmt + iOfst; } } return SQLITE_OK; } /* ** Truncate the file. ** ** If the journal file is already on disk, truncate it there. Or, if it ** is still in main memory but is being truncated to zero bytes in size, ** ignore */ static int memjrnlTruncate(sqlite3_file *pJfd, sqlite_int64 size){ MemJournal *p = (MemJournal *)pJfd; if( ALWAYS(size==0) ){ memjrnlFreeChunks(p); p->nSize = 0; p->endpoint.pChunk = 0; p->endpoint.iOffset = 0; p->readpoint.pChunk = 0; p->readpoint.iOffset = 0; } return SQLITE_OK; } /* ** Close the file. */ static int memjrnlClose(sqlite3_file *pJfd){ MemJournal *p = (MemJournal *)pJfd; memjrnlFreeChunks(p); return SQLITE_OK; } /* ** Sync the file. ** ** If the real file has been created, call its xSync method. Otherwise, ** syncing an in-memory journal is a no-op. */ static int memjrnlSync(sqlite3_file *pJfd, int flags){ UNUSED_PARAMETER2(pJfd, flags); return SQLITE_OK; } /* ** Query the size of the file in bytes. */ static int memjrnlFileSize(sqlite3_file *pJfd, sqlite_int64 *pSize){ MemJournal *p = (MemJournal *)pJfd; *pSize = (sqlite_int64) p->endpoint.iOffset; return SQLITE_OK; } /* ** Table of methods for MemJournal sqlite3_file object. */ static const struct sqlite3_io_methods MemJournalMethods = { 1, /* iVersion */ memjrnlClose, /* xClose */ memjrnlRead, /* xRead */ memjrnlWrite, /* xWrite */ memjrnlTruncate, /* xTruncate */ memjrnlSync, /* xSync */ memjrnlFileSize, /* xFileSize */ 0, /* xLock */ 0, /* xUnlock */ 0, /* xCheckReservedLock */ 0, /* xFileControl */ 0, /* xSectorSize */ 0, /* xDeviceCharacteristics */ 0, /* xShmMap */ 0, /* xShmLock */ 0, /* xShmBarrier */ 0, /* xShmUnmap */ 0, /* xFetch */ 0 /* xUnfetch */ }; /* ** Open a journal file. ** ** The behaviour of the journal file depends on the value of parameter ** nSpill. If nSpill is 0, then the journal file is always create and ** accessed using the underlying VFS. If nSpill is less than zero, then ** all content is always stored in main-memory. Finally, if nSpill is a ** positive value, then the journal file is initially created in-memory ** but may be flushed to disk later on. In this case the journal file is ** flushed to disk either when it grows larger than nSpill bytes in size, ** or when sqlite3JournalCreate() is called. */ SQLITE_PRIVATE int sqlite3JournalOpen( sqlite3_vfs *pVfs, /* The VFS to use for actual file I/O */ const char *zName, /* Name of the journal file */ sqlite3_file *pJfd, /* Preallocated, blank file handle */ int flags, /* Opening flags */ int nSpill /* Bytes buffered before opening the file */ ){ MemJournal *p = (MemJournal*)pJfd; /* Zero the file-handle object. If nSpill was passed zero, initialize ** it using the sqlite3OsOpen() function of the underlying VFS. In this ** case none of the code in this module is executed as a result of calls ** made on the journal file-handle. */ memset(p, 0, sizeof(MemJournal)); if( nSpill==0 ){ return sqlite3OsOpen(pVfs, zName, pJfd, flags, 0); } if( nSpill>0 ){ p->nChunkSize = nSpill; }else{ p->nChunkSize = 8 + MEMJOURNAL_DFLT_FILECHUNKSIZE - sizeof(FileChunk); assert( MEMJOURNAL_DFLT_FILECHUNKSIZE==fileChunkSize(p->nChunkSize) ); } p->pMethod = (const sqlite3_io_methods*)&MemJournalMethods; p->nSpill = nSpill; p->flags = flags; p->zJournal = zName; p->pVfs = pVfs; return SQLITE_OK; } /* ** Open an in-memory journal file. */ SQLITE_PRIVATE void sqlite3MemJournalOpen(sqlite3_file *pJfd){ sqlite3JournalOpen(0, 0, pJfd, 0, -1); } #ifdef SQLITE_ENABLE_ATOMIC_WRITE /* ** If the argument p points to a MemJournal structure that is not an ** in-memory-only journal file (i.e. is one that was opened with a +ve ** nSpill parameter), and the underlying file has not yet been created, ** create it now. */ SQLITE_PRIVATE int sqlite3JournalCreate(sqlite3_file *p){ int rc = SQLITE_OK; if( p->pMethods==&MemJournalMethods && ((MemJournal*)p)->nSpill>0 ){ rc = memjrnlCreateFile((MemJournal*)p); } return rc; } #endif /* ** The file-handle passed as the only argument is open on a journal file. ** Return true if this "journal file" is currently stored in heap memory, ** or false otherwise. */ SQLITE_PRIVATE int sqlite3JournalIsInMemory(sqlite3_file *p){ return p->pMethods==&MemJournalMethods; } /* ** Return the number of bytes required to store a JournalFile that uses vfs ** pVfs to create the underlying on-disk files. */ SQLITE_PRIVATE int sqlite3JournalSize(sqlite3_vfs *pVfs){ return MAX(pVfs->szOsFile, (int)sizeof(MemJournal)); } /************** End of memjournal.c ******************************************/ /************** Begin file walker.c ******************************************/ /* ** 2008 August 16 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ************************************************************************* ** This file contains routines used for walking the parser tree for ** an SQL statement. */ /* #include "sqliteInt.h" */ /* #include */ /* #include */ /* ** Walk an expression tree. Invoke the callback once for each node ** of the expression, while descending. (In other words, the callback ** is invoked before visiting children.) ** ** The return value from the callback should be one of the WRC_* ** constants to specify how to proceed with the walk. ** ** WRC_Continue Continue descending down the tree. ** ** WRC_Prune Do not descend into child nodes. But allow ** the walk to continue with sibling nodes. ** ** WRC_Abort Do no more callbacks. Unwind the stack and ** return the top-level walk call. ** ** The return value from this routine is WRC_Abort to abandon the tree walk ** and WRC_Continue to continue. */ static SQLITE_NOINLINE int walkExpr(Walker *pWalker, Expr *pExpr){ int rc; testcase( ExprHasProperty(pExpr, EP_TokenOnly) ); testcase( ExprHasProperty(pExpr, EP_Reduced) ); rc = pWalker->xExprCallback(pWalker, pExpr); if( rc || ExprHasProperty(pExpr,(EP_TokenOnly|EP_Leaf)) ){ return rc & WRC_Abort; } if( pExpr->pLeft && walkExpr(pWalker, pExpr->pLeft) ) return WRC_Abort; if( pExpr->pRight && walkExpr(pWalker, pExpr->pRight) ) return WRC_Abort; if( ExprHasProperty(pExpr, EP_xIsSelect) ){ if( sqlite3WalkSelect(pWalker, pExpr->x.pSelect) ) return WRC_Abort; }else if( pExpr->x.pList ){ if( sqlite3WalkExprList(pWalker, pExpr->x.pList) ) return WRC_Abort; } return WRC_Continue; } SQLITE_PRIVATE int sqlite3WalkExpr(Walker *pWalker, Expr *pExpr){ return pExpr ? walkExpr(pWalker,pExpr) : WRC_Continue; } /* ** Call sqlite3WalkExpr() for every expression in list p or until ** an abort request is seen. */ SQLITE_PRIVATE int sqlite3WalkExprList(Walker *pWalker, ExprList *p){ int i; struct ExprList_item *pItem; if( p ){ for(i=p->nExpr, pItem=p->a; i>0; i--, pItem++){ if( sqlite3WalkExpr(pWalker, pItem->pExpr) ) return WRC_Abort; } } return WRC_Continue; } /* ** Walk all expressions associated with SELECT statement p. Do ** not invoke the SELECT callback on p, but do (of course) invoke ** any expr callbacks and SELECT callbacks that come from subqueries. ** Return WRC_Abort or WRC_Continue. */ SQLITE_PRIVATE int sqlite3WalkSelectExpr(Walker *pWalker, Select *p){ if( sqlite3WalkExprList(pWalker, p->pEList) ) return WRC_Abort; if( sqlite3WalkExpr(pWalker, p->pWhere) ) return WRC_Abort; if( sqlite3WalkExprList(pWalker, p->pGroupBy) ) return WRC_Abort; if( sqlite3WalkExpr(pWalker, p->pHaving) ) return WRC_Abort; if( sqlite3WalkExprList(pWalker, p->pOrderBy) ) return WRC_Abort; if( sqlite3WalkExpr(pWalker, p->pLimit) ) return WRC_Abort; if( sqlite3WalkExpr(pWalker, p->pOffset) ) return WRC_Abort; return WRC_Continue; } /* ** Walk the parse trees associated with all subqueries in the ** FROM clause of SELECT statement p. Do not invoke the select ** callback on p, but do invoke it on each FROM clause subquery ** and on any subqueries further down in the tree. Return ** WRC_Abort or WRC_Continue; */ SQLITE_PRIVATE int sqlite3WalkSelectFrom(Walker *pWalker, Select *p){ SrcList *pSrc; int i; struct SrcList_item *pItem; pSrc = p->pSrc; if( ALWAYS(pSrc) ){ for(i=pSrc->nSrc, pItem=pSrc->a; i>0; i--, pItem++){ if( sqlite3WalkSelect(pWalker, pItem->pSelect) ){ return WRC_Abort; } if( pItem->fg.isTabFunc && sqlite3WalkExprList(pWalker, pItem->u1.pFuncArg) ){ return WRC_Abort; } } } return WRC_Continue; } /* ** Call sqlite3WalkExpr() for every expression in Select statement p. ** Invoke sqlite3WalkSelect() for subqueries in the FROM clause and ** on the compound select chain, p->pPrior. ** ** If it is not NULL, the xSelectCallback() callback is invoked before ** the walk of the expressions and FROM clause. The xSelectCallback2() ** method, if it is not NULL, is invoked following the walk of the ** expressions and FROM clause. ** ** Return WRC_Continue under normal conditions. Return WRC_Abort if ** there is an abort request. ** ** If the Walker does not have an xSelectCallback() then this routine ** is a no-op returning WRC_Continue. */ SQLITE_PRIVATE int sqlite3WalkSelect(Walker *pWalker, Select *p){ int rc; if( p==0 || (pWalker->xSelectCallback==0 && pWalker->xSelectCallback2==0) ){ return WRC_Continue; } rc = WRC_Continue; pWalker->walkerDepth++; while( p ){ if( pWalker->xSelectCallback ){ rc = pWalker->xSelectCallback(pWalker, p); if( rc ) break; } if( sqlite3WalkSelectExpr(pWalker, p) || sqlite3WalkSelectFrom(pWalker, p) ){ pWalker->walkerDepth--; return WRC_Abort; } if( pWalker->xSelectCallback2 ){ pWalker->xSelectCallback2(pWalker, p); } p = p->pPrior; } pWalker->walkerDepth--; return rc & WRC_Abort; } /************** End of walker.c **********************************************/ /************** Begin file resolve.c *****************************************/ /* ** 2008 August 18 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ************************************************************************* ** ** This file contains routines used for walking the parser tree and ** resolve all identifiers by associating them with a particular ** table and column. */ /* #include "sqliteInt.h" */ /* #include */ /* #include */ /* ** Walk the expression tree pExpr and increase the aggregate function ** depth (the Expr.op2 field) by N on every TK_AGG_FUNCTION node. ** This needs to occur when copying a TK_AGG_FUNCTION node from an ** outer query into an inner subquery. ** ** incrAggFunctionDepth(pExpr,n) is the main routine. incrAggDepth(..) ** is a helper function - a callback for the tree walker. */ static int incrAggDepth(Walker *pWalker, Expr *pExpr){ if( pExpr->op==TK_AGG_FUNCTION ) pExpr->op2 += pWalker->u.n; return WRC_Continue; } static void incrAggFunctionDepth(Expr *pExpr, int N){ if( N>0 ){ Walker w; memset(&w, 0, sizeof(w)); w.xExprCallback = incrAggDepth; w.u.n = N; sqlite3WalkExpr(&w, pExpr); } } /* ** Turn the pExpr expression into an alias for the iCol-th column of the ** result set in pEList. ** ** If the reference is followed by a COLLATE operator, then make sure ** the COLLATE operator is preserved. For example: ** ** SELECT a+b, c+d FROM t1 ORDER BY 1 COLLATE nocase; ** ** Should be transformed into: ** ** SELECT a+b, c+d FROM t1 ORDER BY (a+b) COLLATE nocase; ** ** The nSubquery parameter specifies how many levels of subquery the ** alias is removed from the original expression. The usual value is ** zero but it might be more if the alias is contained within a subquery ** of the original expression. The Expr.op2 field of TK_AGG_FUNCTION ** structures must be increased by the nSubquery amount. */ static void resolveAlias( Parse *pParse, /* Parsing context */ ExprList *pEList, /* A result set */ int iCol, /* A column in the result set. 0..pEList->nExpr-1 */ Expr *pExpr, /* Transform this into an alias to the result set */ const char *zType, /* "GROUP" or "ORDER" or "" */ int nSubquery /* Number of subqueries that the label is moving */ ){ Expr *pOrig; /* The iCol-th column of the result set */ Expr *pDup; /* Copy of pOrig */ sqlite3 *db; /* The database connection */ assert( iCol>=0 && iColnExpr ); pOrig = pEList->a[iCol].pExpr; assert( pOrig!=0 ); db = pParse->db; pDup = sqlite3ExprDup(db, pOrig, 0); if( pDup==0 ) return; if( zType[0]!='G' ) incrAggFunctionDepth(pDup, nSubquery); if( pExpr->op==TK_COLLATE ){ pDup = sqlite3ExprAddCollateString(pParse, pDup, pExpr->u.zToken); } ExprSetProperty(pDup, EP_Alias); /* Before calling sqlite3ExprDelete(), set the EP_Static flag. This ** prevents ExprDelete() from deleting the Expr structure itself, ** allowing it to be repopulated by the memcpy() on the following line. ** The pExpr->u.zToken might point into memory that will be freed by the ** sqlite3DbFree(db, pDup) on the last line of this block, so be sure to ** make a copy of the token before doing the sqlite3DbFree(). */ ExprSetProperty(pExpr, EP_Static); sqlite3ExprDelete(db, pExpr); memcpy(pExpr, pDup, sizeof(*pExpr)); if( !ExprHasProperty(pExpr, EP_IntValue) && pExpr->u.zToken!=0 ){ assert( (pExpr->flags & (EP_Reduced|EP_TokenOnly))==0 ); pExpr->u.zToken = sqlite3DbStrDup(db, pExpr->u.zToken); pExpr->flags |= EP_MemToken; } sqlite3DbFree(db, pDup); } /* ** Return TRUE if the name zCol occurs anywhere in the USING clause. ** ** Return FALSE if the USING clause is NULL or if it does not contain ** zCol. */ static int nameInUsingClause(IdList *pUsing, const char *zCol){ if( pUsing ){ int k; for(k=0; knId; k++){ if( sqlite3StrICmp(pUsing->a[k].zName, zCol)==0 ) return 1; } } return 0; } /* ** Subqueries stores the original database, table and column names for their ** result sets in ExprList.a[].zSpan, in the form "DATABASE.TABLE.COLUMN". ** Check to see if the zSpan given to this routine matches the zDb, zTab, ** and zCol. If any of zDb, zTab, and zCol are NULL then those fields will ** match anything. */ SQLITE_PRIVATE int sqlite3MatchSpanName( const char *zSpan, const char *zCol, const char *zTab, const char *zDb ){ int n; for(n=0; ALWAYS(zSpan[n]) && zSpan[n]!='.'; n++){} if( zDb && (sqlite3StrNICmp(zSpan, zDb, n)!=0 || zDb[n]!=0) ){ return 0; } zSpan += n+1; for(n=0; ALWAYS(zSpan[n]) && zSpan[n]!='.'; n++){} if( zTab && (sqlite3StrNICmp(zSpan, zTab, n)!=0 || zTab[n]!=0) ){ return 0; } zSpan += n+1; if( zCol && sqlite3StrICmp(zSpan, zCol)!=0 ){ return 0; } return 1; } /* ** Given the name of a column of the form X.Y.Z or Y.Z or just Z, look up ** that name in the set of source tables in pSrcList and make the pExpr ** expression node refer back to that source column. The following changes ** are made to pExpr: ** ** pExpr->iDb Set the index in db->aDb[] of the database X ** (even if X is implied). ** pExpr->iTable Set to the cursor number for the table obtained ** from pSrcList. ** pExpr->pTab Points to the Table structure of X.Y (even if ** X and/or Y are implied.) ** pExpr->iColumn Set to the column number within the table. ** pExpr->op Set to TK_COLUMN. ** pExpr->pLeft Any expression this points to is deleted ** pExpr->pRight Any expression this points to is deleted. ** ** The zDb variable is the name of the database (the "X"). This value may be ** NULL meaning that name is of the form Y.Z or Z. Any available database ** can be used. The zTable variable is the name of the table (the "Y"). This ** value can be NULL if zDb is also NULL. If zTable is NULL it ** means that the form of the name is Z and that columns from any table ** can be used. ** ** If the name cannot be resolved unambiguously, leave an error message ** in pParse and return WRC_Abort. Return WRC_Prune on success. */ static int lookupName( Parse *pParse, /* The parsing context */ const char *zDb, /* Name of the database containing table, or NULL */ const char *zTab, /* Name of table containing column, or NULL */ const char *zCol, /* Name of the column. */ NameContext *pNC, /* The name context used to resolve the name */ Expr *pExpr /* Make this EXPR node point to the selected column */ ){ int i, j; /* Loop counters */ int cnt = 0; /* Number of matching column names */ int cntTab = 0; /* Number of matching table names */ int nSubquery = 0; /* How many levels of subquery */ sqlite3 *db = pParse->db; /* The database connection */ struct SrcList_item *pItem; /* Use for looping over pSrcList items */ struct SrcList_item *pMatch = 0; /* The matching pSrcList item */ NameContext *pTopNC = pNC; /* First namecontext in the list */ Schema *pSchema = 0; /* Schema of the expression */ int isTrigger = 0; /* True if resolved to a trigger column */ Table *pTab = 0; /* Table hold the row */ Column *pCol; /* A column of pTab */ assert( pNC ); /* the name context cannot be NULL. */ assert( zCol ); /* The Z in X.Y.Z cannot be NULL */ assert( !ExprHasProperty(pExpr, EP_TokenOnly|EP_Reduced) ); /* Initialize the node to no-match */ pExpr->iTable = -1; pExpr->pTab = 0; ExprSetVVAProperty(pExpr, EP_NoReduce); /* Translate the schema name in zDb into a pointer to the corresponding ** schema. If not found, pSchema will remain NULL and nothing will match ** resulting in an appropriate error message toward the end of this routine */ if( zDb ){ testcase( pNC->ncFlags & NC_PartIdx ); testcase( pNC->ncFlags & NC_IsCheck ); if( (pNC->ncFlags & (NC_PartIdx|NC_IsCheck))!=0 ){ /* Silently ignore database qualifiers inside CHECK constraints and ** partial indices. Do not raise errors because that might break ** legacy and because it does not hurt anything to just ignore the ** database name. */ zDb = 0; }else{ for(i=0; inDb; i++){ assert( db->aDb[i].zDbSName ); if( sqlite3StrICmp(db->aDb[i].zDbSName,zDb)==0 ){ pSchema = db->aDb[i].pSchema; break; } } } } /* Start at the inner-most context and move outward until a match is found */ while( pNC && cnt==0 ){ ExprList *pEList; SrcList *pSrcList = pNC->pSrcList; if( pSrcList ){ for(i=0, pItem=pSrcList->a; inSrc; i++, pItem++){ pTab = pItem->pTab; assert( pTab!=0 && pTab->zName!=0 ); assert( pTab->nCol>0 ); if( pItem->pSelect && (pItem->pSelect->selFlags & SF_NestedFrom)!=0 ){ int hit = 0; pEList = pItem->pSelect->pEList; for(j=0; jnExpr; j++){ if( sqlite3MatchSpanName(pEList->a[j].zSpan, zCol, zTab, zDb) ){ cnt++; cntTab = 2; pMatch = pItem; pExpr->iColumn = j; hit = 1; } } if( hit || zTab==0 ) continue; } if( zDb && pTab->pSchema!=pSchema ){ continue; } if( zTab ){ const char *zTabName = pItem->zAlias ? pItem->zAlias : pTab->zName; assert( zTabName!=0 ); if( sqlite3StrICmp(zTabName, zTab)!=0 ){ continue; } } if( 0==(cntTab++) ){ pMatch = pItem; } for(j=0, pCol=pTab->aCol; jnCol; j++, pCol++){ if( sqlite3StrICmp(pCol->zName, zCol)==0 ){ /* If there has been exactly one prior match and this match ** is for the right-hand table of a NATURAL JOIN or is in a ** USING clause, then skip this match. */ if( cnt==1 ){ if( pItem->fg.jointype & JT_NATURAL ) continue; if( nameInUsingClause(pItem->pUsing, zCol) ) continue; } cnt++; pMatch = pItem; /* Substitute the rowid (column -1) for the INTEGER PRIMARY KEY */ pExpr->iColumn = j==pTab->iPKey ? -1 : (i16)j; break; } } } if( pMatch ){ pExpr->iTable = pMatch->iCursor; pExpr->pTab = pMatch->pTab; /* RIGHT JOIN not (yet) supported */ assert( (pMatch->fg.jointype & JT_RIGHT)==0 ); if( (pMatch->fg.jointype & JT_LEFT)!=0 ){ ExprSetProperty(pExpr, EP_CanBeNull); } pSchema = pExpr->pTab->pSchema; } } /* if( pSrcList ) */ #ifndef SQLITE_OMIT_TRIGGER /* If we have not already resolved the name, then maybe ** it is a new.* or old.* trigger argument reference */ if( zDb==0 && zTab!=0 && cntTab==0 && pParse->pTriggerTab!=0 ){ int op = pParse->eTriggerOp; assert( op==TK_DELETE || op==TK_UPDATE || op==TK_INSERT ); if( op!=TK_DELETE && sqlite3StrICmp("new",zTab) == 0 ){ pExpr->iTable = 1; pTab = pParse->pTriggerTab; }else if( op!=TK_INSERT && sqlite3StrICmp("old",zTab)==0 ){ pExpr->iTable = 0; pTab = pParse->pTriggerTab; }else{ pTab = 0; } if( pTab ){ int iCol; pSchema = pTab->pSchema; cntTab++; for(iCol=0, pCol=pTab->aCol; iColnCol; iCol++, pCol++){ if( sqlite3StrICmp(pCol->zName, zCol)==0 ){ if( iCol==pTab->iPKey ){ iCol = -1; } break; } } if( iCol>=pTab->nCol && sqlite3IsRowid(zCol) && VisibleRowid(pTab) ){ /* IMP: R-51414-32910 */ iCol = -1; } if( iColnCol ){ cnt++; if( iCol<0 ){ pExpr->affinity = SQLITE_AFF_INTEGER; }else if( pExpr->iTable==0 ){ testcase( iCol==31 ); testcase( iCol==32 ); pParse->oldmask |= (iCol>=32 ? 0xffffffff : (((u32)1)<newmask |= (iCol>=32 ? 0xffffffff : (((u32)1)<iColumn = (i16)iCol; pExpr->pTab = pTab; isTrigger = 1; } } } #endif /* !defined(SQLITE_OMIT_TRIGGER) */ /* ** Perhaps the name is a reference to the ROWID */ if( cnt==0 && cntTab==1 && pMatch && (pNC->ncFlags & NC_IdxExpr)==0 && sqlite3IsRowid(zCol) && VisibleRowid(pMatch->pTab) ){ cnt = 1; pExpr->iColumn = -1; pExpr->affinity = SQLITE_AFF_INTEGER; } /* ** If the input is of the form Z (not Y.Z or X.Y.Z) then the name Z ** might refer to an result-set alias. This happens, for example, when ** we are resolving names in the WHERE clause of the following command: ** ** SELECT a+b AS x FROM table WHERE x<10; ** ** In cases like this, replace pExpr with a copy of the expression that ** forms the result set entry ("a+b" in the example) and return immediately. ** Note that the expression in the result set should have already been ** resolved by the time the WHERE clause is resolved. ** ** The ability to use an output result-set column in the WHERE, GROUP BY, ** or HAVING clauses, or as part of a larger expression in the ORDER BY ** clause is not standard SQL. This is a (goofy) SQLite extension, that ** is supported for backwards compatibility only. Hence, we issue a warning ** on sqlite3_log() whenever the capability is used. */ if( (pEList = pNC->pEList)!=0 && zTab==0 && cnt==0 ){ for(j=0; jnExpr; j++){ char *zAs = pEList->a[j].zName; if( zAs!=0 && sqlite3StrICmp(zAs, zCol)==0 ){ Expr *pOrig; assert( pExpr->pLeft==0 && pExpr->pRight==0 ); assert( pExpr->x.pList==0 ); assert( pExpr->x.pSelect==0 ); pOrig = pEList->a[j].pExpr; if( (pNC->ncFlags&NC_AllowAgg)==0 && ExprHasProperty(pOrig, EP_Agg) ){ sqlite3ErrorMsg(pParse, "misuse of aliased aggregate %s", zAs); return WRC_Abort; } resolveAlias(pParse, pEList, j, pExpr, "", nSubquery); cnt = 1; pMatch = 0; assert( zTab==0 && zDb==0 ); goto lookupname_end; } } } /* Advance to the next name context. The loop will exit when either ** we have a match (cnt>0) or when we run out of name contexts. */ if( cnt==0 ){ pNC = pNC->pNext; nSubquery++; } } /* ** If X and Y are NULL (in other words if only the column name Z is ** supplied) and the value of Z is enclosed in double-quotes, then ** Z is a string literal if it doesn't match any column names. In that ** case, we need to return right away and not make any changes to ** pExpr. ** ** Because no reference was made to outer contexts, the pNC->nRef ** fields are not changed in any context. */ if( cnt==0 && zTab==0 && ExprHasProperty(pExpr,EP_DblQuoted) ){ pExpr->op = TK_STRING; pExpr->pTab = 0; return WRC_Prune; } /* ** cnt==0 means there was not match. cnt>1 means there were two or ** more matches. Either way, we have an error. */ if( cnt!=1 ){ const char *zErr; zErr = cnt==0 ? "no such column" : "ambiguous column name"; if( zDb ){ sqlite3ErrorMsg(pParse, "%s: %s.%s.%s", zErr, zDb, zTab, zCol); }else if( zTab ){ sqlite3ErrorMsg(pParse, "%s: %s.%s", zErr, zTab, zCol); }else{ sqlite3ErrorMsg(pParse, "%s: %s", zErr, zCol); } pParse->checkSchema = 1; pTopNC->nErr++; } /* If a column from a table in pSrcList is referenced, then record ** this fact in the pSrcList.a[].colUsed bitmask. Column 0 causes ** bit 0 to be set. Column 1 sets bit 1. And so forth. If the ** column number is greater than the number of bits in the bitmask ** then set the high-order bit of the bitmask. */ if( pExpr->iColumn>=0 && pMatch!=0 ){ int n = pExpr->iColumn; testcase( n==BMS-1 ); if( n>=BMS ){ n = BMS-1; } assert( pMatch->iCursor==pExpr->iTable ); pMatch->colUsed |= ((Bitmask)1)<pLeft); pExpr->pLeft = 0; sqlite3ExprDelete(db, pExpr->pRight); pExpr->pRight = 0; pExpr->op = (isTrigger ? TK_TRIGGER : TK_COLUMN); lookupname_end: if( cnt==1 ){ assert( pNC!=0 ); if( !ExprHasProperty(pExpr, EP_Alias) ){ sqlite3AuthRead(pParse, pExpr, pSchema, pNC->pSrcList); } /* Increment the nRef value on all name contexts from TopNC up to ** the point where the name matched. */ for(;;){ assert( pTopNC!=0 ); pTopNC->nRef++; if( pTopNC==pNC ) break; pTopNC = pTopNC->pNext; } return WRC_Prune; } else { return WRC_Abort; } } /* ** Allocate and return a pointer to an expression to load the column iCol ** from datasource iSrc in SrcList pSrc. */ SQLITE_PRIVATE Expr *sqlite3CreateColumnExpr(sqlite3 *db, SrcList *pSrc, int iSrc, int iCol){ Expr *p = sqlite3ExprAlloc(db, TK_COLUMN, 0, 0); if( p ){ struct SrcList_item *pItem = &pSrc->a[iSrc]; p->pTab = pItem->pTab; p->iTable = pItem->iCursor; if( p->pTab->iPKey==iCol ){ p->iColumn = -1; }else{ p->iColumn = (ynVar)iCol; testcase( iCol==BMS ); testcase( iCol==BMS-1 ); pItem->colUsed |= ((Bitmask)1)<<(iCol>=BMS ? BMS-1 : iCol); } ExprSetProperty(p, EP_Resolved); } return p; } /* ** Report an error that an expression is not valid for some set of ** pNC->ncFlags values determined by validMask. */ static void notValid( Parse *pParse, /* Leave error message here */ NameContext *pNC, /* The name context */ const char *zMsg, /* Type of error */ int validMask /* Set of contexts for which prohibited */ ){ assert( (validMask&~(NC_IsCheck|NC_PartIdx|NC_IdxExpr))==0 ); if( (pNC->ncFlags & validMask)!=0 ){ const char *zIn = "partial index WHERE clauses"; if( pNC->ncFlags & NC_IdxExpr ) zIn = "index expressions"; #ifndef SQLITE_OMIT_CHECK else if( pNC->ncFlags & NC_IsCheck ) zIn = "CHECK constraints"; #endif sqlite3ErrorMsg(pParse, "%s prohibited in %s", zMsg, zIn); } } /* ** Expression p should encode a floating point value between 1.0 and 0.0. ** Return 1024 times this value. Or return -1 if p is not a floating point ** value between 1.0 and 0.0. */ static int exprProbability(Expr *p){ double r = -1.0; if( p->op!=TK_FLOAT ) return -1; sqlite3AtoF(p->u.zToken, &r, sqlite3Strlen30(p->u.zToken), SQLITE_UTF8); assert( r>=0.0 ); if( r>1.0 ) return -1; return (int)(r*134217728.0); } /* ** This routine is callback for sqlite3WalkExpr(). ** ** Resolve symbolic names into TK_COLUMN operators for the current ** node in the expression tree. Return 0 to continue the search down ** the tree or 2 to abort the tree walk. ** ** This routine also does error checking and name resolution for ** function names. The operator for aggregate functions is changed ** to TK_AGG_FUNCTION. */ static int resolveExprStep(Walker *pWalker, Expr *pExpr){ NameContext *pNC; Parse *pParse; pNC = pWalker->u.pNC; assert( pNC!=0 ); pParse = pNC->pParse; assert( pParse==pWalker->pParse ); if( ExprHasProperty(pExpr, EP_Resolved) ) return WRC_Prune; ExprSetProperty(pExpr, EP_Resolved); #ifndef NDEBUG if( pNC->pSrcList && pNC->pSrcList->nAlloc>0 ){ SrcList *pSrcList = pNC->pSrcList; int i; for(i=0; ipSrcList->nSrc; i++){ assert( pSrcList->a[i].iCursor>=0 && pSrcList->a[i].iCursornTab); } } #endif switch( pExpr->op ){ #if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY) /* The special operator TK_ROW means use the rowid for the first ** column in the FROM clause. This is used by the LIMIT and ORDER BY ** clause processing on UPDATE and DELETE statements. */ case TK_ROW: { SrcList *pSrcList = pNC->pSrcList; struct SrcList_item *pItem; assert( pSrcList && pSrcList->nSrc==1 ); pItem = pSrcList->a; pExpr->op = TK_COLUMN; pExpr->pTab = pItem->pTab; pExpr->iTable = pItem->iCursor; pExpr->iColumn = -1; pExpr->affinity = SQLITE_AFF_INTEGER; break; } #endif /* defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY) */ /* A lone identifier is the name of a column. */ case TK_ID: { return lookupName(pParse, 0, 0, pExpr->u.zToken, pNC, pExpr); } /* A table name and column name: ID.ID ** Or a database, table and column: ID.ID.ID */ case TK_DOT: { const char *zColumn; const char *zTable; const char *zDb; Expr *pRight; /* if( pSrcList==0 ) break; */ notValid(pParse, pNC, "the \".\" operator", NC_IdxExpr); pRight = pExpr->pRight; if( pRight->op==TK_ID ){ zDb = 0; zTable = pExpr->pLeft->u.zToken; zColumn = pRight->u.zToken; }else{ assert( pRight->op==TK_DOT ); zDb = pExpr->pLeft->u.zToken; zTable = pRight->pLeft->u.zToken; zColumn = pRight->pRight->u.zToken; } return lookupName(pParse, zDb, zTable, zColumn, pNC, pExpr); } /* Resolve function names */ case TK_FUNCTION: { ExprList *pList = pExpr->x.pList; /* The argument list */ int n = pList ? pList->nExpr : 0; /* Number of arguments */ int no_such_func = 0; /* True if no such function exists */ int wrong_num_args = 0; /* True if wrong number of arguments */ int is_agg = 0; /* True if is an aggregate function */ int nId; /* Number of characters in function name */ const char *zId; /* The function name. */ FuncDef *pDef; /* Information about the function */ u8 enc = ENC(pParse->db); /* The database encoding */ assert( !ExprHasProperty(pExpr, EP_xIsSelect) ); zId = pExpr->u.zToken; nId = sqlite3Strlen30(zId); pDef = sqlite3FindFunction(pParse->db, zId, n, enc, 0); if( pDef==0 ){ pDef = sqlite3FindFunction(pParse->db, zId, -2, enc, 0); if( pDef==0 ){ no_such_func = 1; }else{ wrong_num_args = 1; } }else{ is_agg = pDef->xFinalize!=0; if( pDef->funcFlags & SQLITE_FUNC_UNLIKELY ){ ExprSetProperty(pExpr, EP_Unlikely|EP_Skip); if( n==2 ){ pExpr->iTable = exprProbability(pList->a[1].pExpr); if( pExpr->iTable<0 ){ sqlite3ErrorMsg(pParse, "second argument to likelihood() must be a " "constant between 0.0 and 1.0"); pNC->nErr++; } }else{ /* EVIDENCE-OF: R-61304-29449 The unlikely(X) function is ** equivalent to likelihood(X, 0.0625). ** EVIDENCE-OF: R-01283-11636 The unlikely(X) function is ** short-hand for likelihood(X,0.0625). ** EVIDENCE-OF: R-36850-34127 The likely(X) function is short-hand ** for likelihood(X,0.9375). ** EVIDENCE-OF: R-53436-40973 The likely(X) function is equivalent ** to likelihood(X,0.9375). */ /* TUNING: unlikely() probability is 0.0625. likely() is 0.9375 */ pExpr->iTable = pDef->zName[0]=='u' ? 8388608 : 125829120; } } #ifndef SQLITE_OMIT_AUTHORIZATION { int auth = sqlite3AuthCheck(pParse, SQLITE_FUNCTION, 0,pDef->zName,0); if( auth!=SQLITE_OK ){ if( auth==SQLITE_DENY ){ sqlite3ErrorMsg(pParse, "not authorized to use function: %s", pDef->zName); pNC->nErr++; } pExpr->op = TK_NULL; return WRC_Prune; } } #endif if( pDef->funcFlags & (SQLITE_FUNC_CONSTANT|SQLITE_FUNC_SLOCHNG) ){ /* For the purposes of the EP_ConstFunc flag, date and time ** functions and other functions that change slowly are considered ** constant because they are constant for the duration of one query */ ExprSetProperty(pExpr,EP_ConstFunc); } if( (pDef->funcFlags & SQLITE_FUNC_CONSTANT)==0 ){ /* Date/time functions that use 'now', and other functions like ** sqlite_version() that might change over time cannot be used ** in an index. */ notValid(pParse, pNC, "non-deterministic functions", NC_IdxExpr|NC_PartIdx); } } if( is_agg && (pNC->ncFlags & NC_AllowAgg)==0 ){ sqlite3ErrorMsg(pParse, "misuse of aggregate function %.*s()", nId,zId); pNC->nErr++; is_agg = 0; }else if( no_such_func && pParse->db->init.busy==0 #ifdef SQLITE_ENABLE_UNKNOWN_SQL_FUNCTION && pParse->explain==0 #endif ){ sqlite3ErrorMsg(pParse, "no such function: %.*s", nId, zId); pNC->nErr++; }else if( wrong_num_args ){ sqlite3ErrorMsg(pParse,"wrong number of arguments to function %.*s()", nId, zId); pNC->nErr++; } if( is_agg ) pNC->ncFlags &= ~NC_AllowAgg; sqlite3WalkExprList(pWalker, pList); if( is_agg ){ NameContext *pNC2 = pNC; pExpr->op = TK_AGG_FUNCTION; pExpr->op2 = 0; while( pNC2 && !sqlite3FunctionUsesThisSrc(pExpr, pNC2->pSrcList) ){ pExpr->op2++; pNC2 = pNC2->pNext; } assert( pDef!=0 ); if( pNC2 ){ assert( SQLITE_FUNC_MINMAX==NC_MinMaxAgg ); testcase( (pDef->funcFlags & SQLITE_FUNC_MINMAX)!=0 ); pNC2->ncFlags |= NC_HasAgg | (pDef->funcFlags & SQLITE_FUNC_MINMAX); } pNC->ncFlags |= NC_AllowAgg; } /* FIX ME: Compute pExpr->affinity based on the expected return ** type of the function */ return WRC_Prune; } #ifndef SQLITE_OMIT_SUBQUERY case TK_SELECT: case TK_EXISTS: testcase( pExpr->op==TK_EXISTS ); #endif case TK_IN: { testcase( pExpr->op==TK_IN ); if( ExprHasProperty(pExpr, EP_xIsSelect) ){ int nRef = pNC->nRef; notValid(pParse, pNC, "subqueries", NC_IsCheck|NC_PartIdx|NC_IdxExpr); sqlite3WalkSelect(pWalker, pExpr->x.pSelect); assert( pNC->nRef>=nRef ); if( nRef!=pNC->nRef ){ ExprSetProperty(pExpr, EP_VarSelect); pNC->ncFlags |= NC_VarSelect; } } break; } case TK_VARIABLE: { notValid(pParse, pNC, "parameters", NC_IsCheck|NC_PartIdx|NC_IdxExpr); break; } case TK_EQ: case TK_NE: case TK_LT: case TK_LE: case TK_GT: case TK_GE: case TK_IS: case TK_ISNOT: { int nLeft, nRight; if( pParse->db->mallocFailed ) break; assert( pExpr->pRight!=0 ); assert( pExpr->pLeft!=0 ); nLeft = sqlite3ExprVectorSize(pExpr->pLeft); nRight = sqlite3ExprVectorSize(pExpr->pRight); if( nLeft!=nRight ){ testcase( pExpr->op==TK_EQ ); testcase( pExpr->op==TK_NE ); testcase( pExpr->op==TK_LT ); testcase( pExpr->op==TK_LE ); testcase( pExpr->op==TK_GT ); testcase( pExpr->op==TK_GE ); testcase( pExpr->op==TK_IS ); testcase( pExpr->op==TK_ISNOT ); sqlite3ErrorMsg(pParse, "row value misused"); } break; } } return (pParse->nErr || pParse->db->mallocFailed) ? WRC_Abort : WRC_Continue; } /* ** pEList is a list of expressions which are really the result set of the ** a SELECT statement. pE is a term in an ORDER BY or GROUP BY clause. ** This routine checks to see if pE is a simple identifier which corresponds ** to the AS-name of one of the terms of the expression list. If it is, ** this routine return an integer between 1 and N where N is the number of ** elements in pEList, corresponding to the matching entry. If there is ** no match, or if pE is not a simple identifier, then this routine ** return 0. ** ** pEList has been resolved. pE has not. */ static int resolveAsName( Parse *pParse, /* Parsing context for error messages */ ExprList *pEList, /* List of expressions to scan */ Expr *pE /* Expression we are trying to match */ ){ int i; /* Loop counter */ UNUSED_PARAMETER(pParse); if( pE->op==TK_ID ){ char *zCol = pE->u.zToken; for(i=0; inExpr; i++){ char *zAs = pEList->a[i].zName; if( zAs!=0 && sqlite3StrICmp(zAs, zCol)==0 ){ return i+1; } } } return 0; } /* ** pE is a pointer to an expression which is a single term in the ** ORDER BY of a compound SELECT. The expression has not been ** name resolved. ** ** At the point this routine is called, we already know that the ** ORDER BY term is not an integer index into the result set. That ** case is handled by the calling routine. ** ** Attempt to match pE against result set columns in the left-most ** SELECT statement. Return the index i of the matching column, ** as an indication to the caller that it should sort by the i-th column. ** The left-most column is 1. In other words, the value returned is the ** same integer value that would be used in the SQL statement to indicate ** the column. ** ** If there is no match, return 0. Return -1 if an error occurs. */ static int resolveOrderByTermToExprList( Parse *pParse, /* Parsing context for error messages */ Select *pSelect, /* The SELECT statement with the ORDER BY clause */ Expr *pE /* The specific ORDER BY term */ ){ int i; /* Loop counter */ ExprList *pEList; /* The columns of the result set */ NameContext nc; /* Name context for resolving pE */ sqlite3 *db; /* Database connection */ int rc; /* Return code from subprocedures */ u8 savedSuppErr; /* Saved value of db->suppressErr */ assert( sqlite3ExprIsInteger(pE, &i)==0 ); pEList = pSelect->pEList; /* Resolve all names in the ORDER BY term expression */ memset(&nc, 0, sizeof(nc)); nc.pParse = pParse; nc.pSrcList = pSelect->pSrc; nc.pEList = pEList; nc.ncFlags = NC_AllowAgg; nc.nErr = 0; db = pParse->db; savedSuppErr = db->suppressErr; db->suppressErr = 1; rc = sqlite3ResolveExprNames(&nc, pE); db->suppressErr = savedSuppErr; if( rc ) return 0; /* Try to match the ORDER BY expression against an expression ** in the result set. Return an 1-based index of the matching ** result-set entry. */ for(i=0; inExpr; i++){ if( sqlite3ExprCompare(pEList->a[i].pExpr, pE, -1)<2 ){ return i+1; } } /* If no match, return 0. */ return 0; } /* ** Generate an ORDER BY or GROUP BY term out-of-range error. */ static void resolveOutOfRangeError( Parse *pParse, /* The error context into which to write the error */ const char *zType, /* "ORDER" or "GROUP" */ int i, /* The index (1-based) of the term out of range */ int mx /* Largest permissible value of i */ ){ sqlite3ErrorMsg(pParse, "%r %s BY term out of range - should be " "between 1 and %d", i, zType, mx); } /* ** Analyze the ORDER BY clause in a compound SELECT statement. Modify ** each term of the ORDER BY clause is a constant integer between 1 ** and N where N is the number of columns in the compound SELECT. ** ** ORDER BY terms that are already an integer between 1 and N are ** unmodified. ORDER BY terms that are integers outside the range of ** 1 through N generate an error. ORDER BY terms that are expressions ** are matched against result set expressions of compound SELECT ** beginning with the left-most SELECT and working toward the right. ** At the first match, the ORDER BY expression is transformed into ** the integer column number. ** ** Return the number of errors seen. */ static int resolveCompoundOrderBy( Parse *pParse, /* Parsing context. Leave error messages here */ Select *pSelect /* The SELECT statement containing the ORDER BY */ ){ int i; ExprList *pOrderBy; ExprList *pEList; sqlite3 *db; int moreToDo = 1; pOrderBy = pSelect->pOrderBy; if( pOrderBy==0 ) return 0; db = pParse->db; #if SQLITE_MAX_COLUMN if( pOrderBy->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){ sqlite3ErrorMsg(pParse, "too many terms in ORDER BY clause"); return 1; } #endif for(i=0; inExpr; i++){ pOrderBy->a[i].done = 0; } pSelect->pNext = 0; while( pSelect->pPrior ){ pSelect->pPrior->pNext = pSelect; pSelect = pSelect->pPrior; } while( pSelect && moreToDo ){ struct ExprList_item *pItem; moreToDo = 0; pEList = pSelect->pEList; assert( pEList!=0 ); for(i=0, pItem=pOrderBy->a; inExpr; i++, pItem++){ int iCol = -1; Expr *pE, *pDup; if( pItem->done ) continue; pE = sqlite3ExprSkipCollate(pItem->pExpr); if( sqlite3ExprIsInteger(pE, &iCol) ){ if( iCol<=0 || iCol>pEList->nExpr ){ resolveOutOfRangeError(pParse, "ORDER", i+1, pEList->nExpr); return 1; } }else{ iCol = resolveAsName(pParse, pEList, pE); if( iCol==0 ){ pDup = sqlite3ExprDup(db, pE, 0); if( !db->mallocFailed ){ assert(pDup); iCol = resolveOrderByTermToExprList(pParse, pSelect, pDup); } sqlite3ExprDelete(db, pDup); } } if( iCol>0 ){ /* Convert the ORDER BY term into an integer column number iCol, ** taking care to preserve the COLLATE clause if it exists */ Expr *pNew = sqlite3Expr(db, TK_INTEGER, 0); if( pNew==0 ) return 1; pNew->flags |= EP_IntValue; pNew->u.iValue = iCol; if( pItem->pExpr==pE ){ pItem->pExpr = pNew; }else{ Expr *pParent = pItem->pExpr; assert( pParent->op==TK_COLLATE ); while( pParent->pLeft->op==TK_COLLATE ) pParent = pParent->pLeft; assert( pParent->pLeft==pE ); pParent->pLeft = pNew; } sqlite3ExprDelete(db, pE); pItem->u.x.iOrderByCol = (u16)iCol; pItem->done = 1; }else{ moreToDo = 1; } } pSelect = pSelect->pNext; } for(i=0; inExpr; i++){ if( pOrderBy->a[i].done==0 ){ sqlite3ErrorMsg(pParse, "%r ORDER BY term does not match any " "column in the result set", i+1); return 1; } } return 0; } /* ** Check every term in the ORDER BY or GROUP BY clause pOrderBy of ** the SELECT statement pSelect. If any term is reference to a ** result set expression (as determined by the ExprList.a.u.x.iOrderByCol ** field) then convert that term into a copy of the corresponding result set ** column. ** ** If any errors are detected, add an error message to pParse and ** return non-zero. Return zero if no errors are seen. */ SQLITE_PRIVATE int sqlite3ResolveOrderGroupBy( Parse *pParse, /* Parsing context. Leave error messages here */ Select *pSelect, /* The SELECT statement containing the clause */ ExprList *pOrderBy, /* The ORDER BY or GROUP BY clause to be processed */ const char *zType /* "ORDER" or "GROUP" */ ){ int i; sqlite3 *db = pParse->db; ExprList *pEList; struct ExprList_item *pItem; if( pOrderBy==0 || pParse->db->mallocFailed ) return 0; #if SQLITE_MAX_COLUMN if( pOrderBy->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){ sqlite3ErrorMsg(pParse, "too many terms in %s BY clause", zType); return 1; } #endif pEList = pSelect->pEList; assert( pEList!=0 ); /* sqlite3SelectNew() guarantees this */ for(i=0, pItem=pOrderBy->a; inExpr; i++, pItem++){ if( pItem->u.x.iOrderByCol ){ if( pItem->u.x.iOrderByCol>pEList->nExpr ){ resolveOutOfRangeError(pParse, zType, i+1, pEList->nExpr); return 1; } resolveAlias(pParse, pEList, pItem->u.x.iOrderByCol-1, pItem->pExpr, zType,0); } } return 0; } /* ** pOrderBy is an ORDER BY or GROUP BY clause in SELECT statement pSelect. ** The Name context of the SELECT statement is pNC. zType is either ** "ORDER" or "GROUP" depending on which type of clause pOrderBy is. ** ** This routine resolves each term of the clause into an expression. ** If the order-by term is an integer I between 1 and N (where N is the ** number of columns in the result set of the SELECT) then the expression ** in the resolution is a copy of the I-th result-set expression. If ** the order-by term is an identifier that corresponds to the AS-name of ** a result-set expression, then the term resolves to a copy of the ** result-set expression. Otherwise, the expression is resolved in ** the usual way - using sqlite3ResolveExprNames(). ** ** This routine returns the number of errors. If errors occur, then ** an appropriate error message might be left in pParse. (OOM errors ** excepted.) */ static int resolveOrderGroupBy( NameContext *pNC, /* The name context of the SELECT statement */ Select *pSelect, /* The SELECT statement holding pOrderBy */ ExprList *pOrderBy, /* An ORDER BY or GROUP BY clause to resolve */ const char *zType /* Either "ORDER" or "GROUP", as appropriate */ ){ int i, j; /* Loop counters */ int iCol; /* Column number */ struct ExprList_item *pItem; /* A term of the ORDER BY clause */ Parse *pParse; /* Parsing context */ int nResult; /* Number of terms in the result set */ if( pOrderBy==0 ) return 0; nResult = pSelect->pEList->nExpr; pParse = pNC->pParse; for(i=0, pItem=pOrderBy->a; inExpr; i++, pItem++){ Expr *pE = pItem->pExpr; Expr *pE2 = sqlite3ExprSkipCollate(pE); if( zType[0]!='G' ){ iCol = resolveAsName(pParse, pSelect->pEList, pE2); if( iCol>0 ){ /* If an AS-name match is found, mark this ORDER BY column as being ** a copy of the iCol-th result-set column. The subsequent call to ** sqlite3ResolveOrderGroupBy() will convert the expression to a ** copy of the iCol-th result-set expression. */ pItem->u.x.iOrderByCol = (u16)iCol; continue; } } if( sqlite3ExprIsInteger(pE2, &iCol) ){ /* The ORDER BY term is an integer constant. Again, set the column ** number so that sqlite3ResolveOrderGroupBy() will convert the ** order-by term to a copy of the result-set expression */ if( iCol<1 || iCol>0xffff ){ resolveOutOfRangeError(pParse, zType, i+1, nResult); return 1; } pItem->u.x.iOrderByCol = (u16)iCol; continue; } /* Otherwise, treat the ORDER BY term as an ordinary expression */ pItem->u.x.iOrderByCol = 0; if( sqlite3ResolveExprNames(pNC, pE) ){ return 1; } for(j=0; jpEList->nExpr; j++){ if( sqlite3ExprCompare(pE, pSelect->pEList->a[j].pExpr, -1)==0 ){ pItem->u.x.iOrderByCol = j+1; } } } return sqlite3ResolveOrderGroupBy(pParse, pSelect, pOrderBy, zType); } /* ** Resolve names in the SELECT statement p and all of its descendants. */ static int resolveSelectStep(Walker *pWalker, Select *p){ NameContext *pOuterNC; /* Context that contains this SELECT */ NameContext sNC; /* Name context of this SELECT */ int isCompound; /* True if p is a compound select */ int nCompound; /* Number of compound terms processed so far */ Parse *pParse; /* Parsing context */ int i; /* Loop counter */ ExprList *pGroupBy; /* The GROUP BY clause */ Select *pLeftmost; /* Left-most of SELECT of a compound */ sqlite3 *db; /* Database connection */ assert( p!=0 ); if( p->selFlags & SF_Resolved ){ return WRC_Prune; } pOuterNC = pWalker->u.pNC; pParse = pWalker->pParse; db = pParse->db; /* Normally sqlite3SelectExpand() will be called first and will have ** already expanded this SELECT. However, if this is a subquery within ** an expression, sqlite3ResolveExprNames() will be called without a ** prior call to sqlite3SelectExpand(). When that happens, let ** sqlite3SelectPrep() do all of the processing for this SELECT. ** sqlite3SelectPrep() will invoke both sqlite3SelectExpand() and ** this routine in the correct order. */ if( (p->selFlags & SF_Expanded)==0 ){ sqlite3SelectPrep(pParse, p, pOuterNC); return (pParse->nErr || db->mallocFailed) ? WRC_Abort : WRC_Prune; } isCompound = p->pPrior!=0; nCompound = 0; pLeftmost = p; while( p ){ assert( (p->selFlags & SF_Expanded)!=0 ); assert( (p->selFlags & SF_Resolved)==0 ); p->selFlags |= SF_Resolved; /* Resolve the expressions in the LIMIT and OFFSET clauses. These ** are not allowed to refer to any names, so pass an empty NameContext. */ memset(&sNC, 0, sizeof(sNC)); sNC.pParse = pParse; if( sqlite3ResolveExprNames(&sNC, p->pLimit) || sqlite3ResolveExprNames(&sNC, p->pOffset) ){ return WRC_Abort; } /* If the SF_Converted flags is set, then this Select object was ** was created by the convertCompoundSelectToSubquery() function. ** In this case the ORDER BY clause (p->pOrderBy) should be resolved ** as if it were part of the sub-query, not the parent. This block ** moves the pOrderBy down to the sub-query. It will be moved back ** after the names have been resolved. */ if( p->selFlags & SF_Converted ){ Select *pSub = p->pSrc->a[0].pSelect; assert( p->pSrc->nSrc==1 && p->pOrderBy ); assert( pSub->pPrior && pSub->pOrderBy==0 ); pSub->pOrderBy = p->pOrderBy; p->pOrderBy = 0; } /* Recursively resolve names in all subqueries */ for(i=0; ipSrc->nSrc; i++){ struct SrcList_item *pItem = &p->pSrc->a[i]; if( pItem->pSelect ){ NameContext *pNC; /* Used to iterate name contexts */ int nRef = 0; /* Refcount for pOuterNC and outer contexts */ const char *zSavedContext = pParse->zAuthContext; /* Count the total number of references to pOuterNC and all of its ** parent contexts. After resolving references to expressions in ** pItem->pSelect, check if this value has changed. If so, then ** SELECT statement pItem->pSelect must be correlated. Set the ** pItem->fg.isCorrelated flag if this is the case. */ for(pNC=pOuterNC; pNC; pNC=pNC->pNext) nRef += pNC->nRef; if( pItem->zName ) pParse->zAuthContext = pItem->zName; sqlite3ResolveSelectNames(pParse, pItem->pSelect, pOuterNC); pParse->zAuthContext = zSavedContext; if( pParse->nErr || db->mallocFailed ) return WRC_Abort; for(pNC=pOuterNC; pNC; pNC=pNC->pNext) nRef -= pNC->nRef; assert( pItem->fg.isCorrelated==0 && nRef<=0 ); pItem->fg.isCorrelated = (nRef!=0); } } /* Set up the local name-context to pass to sqlite3ResolveExprNames() to ** resolve the result-set expression list. */ sNC.ncFlags = NC_AllowAgg; sNC.pSrcList = p->pSrc; sNC.pNext = pOuterNC; /* Resolve names in the result set. */ if( sqlite3ResolveExprListNames(&sNC, p->pEList) ) return WRC_Abort; /* If there are no aggregate functions in the result-set, and no GROUP BY ** expression, do not allow aggregates in any of the other expressions. */ assert( (p->selFlags & SF_Aggregate)==0 ); pGroupBy = p->pGroupBy; if( pGroupBy || (sNC.ncFlags & NC_HasAgg)!=0 ){ assert( NC_MinMaxAgg==SF_MinMaxAgg ); p->selFlags |= SF_Aggregate | (sNC.ncFlags&NC_MinMaxAgg); }else{ sNC.ncFlags &= ~NC_AllowAgg; } /* If a HAVING clause is present, then there must be a GROUP BY clause. */ if( p->pHaving && !pGroupBy ){ sqlite3ErrorMsg(pParse, "a GROUP BY clause is required before HAVING"); return WRC_Abort; } /* Add the output column list to the name-context before parsing the ** other expressions in the SELECT statement. This is so that ** expressions in the WHERE clause (etc.) can refer to expressions by ** aliases in the result set. ** ** Minor point: If this is the case, then the expression will be ** re-evaluated for each reference to it. */ sNC.pEList = p->pEList; if( sqlite3ResolveExprNames(&sNC, p->pHaving) ) return WRC_Abort; if( sqlite3ResolveExprNames(&sNC, p->pWhere) ) return WRC_Abort; /* Resolve names in table-valued-function arguments */ for(i=0; ipSrc->nSrc; i++){ struct SrcList_item *pItem = &p->pSrc->a[i]; if( pItem->fg.isTabFunc && sqlite3ResolveExprListNames(&sNC, pItem->u1.pFuncArg) ){ return WRC_Abort; } } /* The ORDER BY and GROUP BY clauses may not refer to terms in ** outer queries */ sNC.pNext = 0; sNC.ncFlags |= NC_AllowAgg; /* If this is a converted compound query, move the ORDER BY clause from ** the sub-query back to the parent query. At this point each term ** within the ORDER BY clause has been transformed to an integer value. ** These integers will be replaced by copies of the corresponding result ** set expressions by the call to resolveOrderGroupBy() below. */ if( p->selFlags & SF_Converted ){ Select *pSub = p->pSrc->a[0].pSelect; p->pOrderBy = pSub->pOrderBy; pSub->pOrderBy = 0; } /* Process the ORDER BY clause for singleton SELECT statements. ** The ORDER BY clause for compounds SELECT statements is handled ** below, after all of the result-sets for all of the elements of ** the compound have been resolved. ** ** If there is an ORDER BY clause on a term of a compound-select other ** than the right-most term, then that is a syntax error. But the error ** is not detected until much later, and so we need to go ahead and ** resolve those symbols on the incorrect ORDER BY for consistency. */ if( isCompound<=nCompound /* Defer right-most ORDER BY of a compound */ && resolveOrderGroupBy(&sNC, p, p->pOrderBy, "ORDER") ){ return WRC_Abort; } if( db->mallocFailed ){ return WRC_Abort; } /* Resolve the GROUP BY clause. At the same time, make sure ** the GROUP BY clause does not contain aggregate functions. */ if( pGroupBy ){ struct ExprList_item *pItem; if( resolveOrderGroupBy(&sNC, p, pGroupBy, "GROUP") || db->mallocFailed ){ return WRC_Abort; } for(i=0, pItem=pGroupBy->a; inExpr; i++, pItem++){ if( ExprHasProperty(pItem->pExpr, EP_Agg) ){ sqlite3ErrorMsg(pParse, "aggregate functions are not allowed in " "the GROUP BY clause"); return WRC_Abort; } } } /* If this is part of a compound SELECT, check that it has the right ** number of expressions in the select list. */ if( p->pNext && p->pEList->nExpr!=p->pNext->pEList->nExpr ){ sqlite3SelectWrongNumTermsError(pParse, p->pNext); return WRC_Abort; } /* Advance to the next term of the compound */ p = p->pPrior; nCompound++; } /* Resolve the ORDER BY on a compound SELECT after all terms of ** the compound have been resolved. */ if( isCompound && resolveCompoundOrderBy(pParse, pLeftmost) ){ return WRC_Abort; } return WRC_Prune; } /* ** This routine walks an expression tree and resolves references to ** table columns and result-set columns. At the same time, do error ** checking on function usage and set a flag if any aggregate functions ** are seen. ** ** To resolve table columns references we look for nodes (or subtrees) of the ** form X.Y.Z or Y.Z or just Z where ** ** X: The name of a database. Ex: "main" or "temp" or ** the symbolic name assigned to an ATTACH-ed database. ** ** Y: The name of a table in a FROM clause. Or in a trigger ** one of the special names "old" or "new". ** ** Z: The name of a column in table Y. ** ** The node at the root of the subtree is modified as follows: ** ** Expr.op Changed to TK_COLUMN ** Expr.pTab Points to the Table object for X.Y ** Expr.iColumn The column index in X.Y. -1 for the rowid. ** Expr.iTable The VDBE cursor number for X.Y ** ** ** To resolve result-set references, look for expression nodes of the ** form Z (with no X and Y prefix) where the Z matches the right-hand ** size of an AS clause in the result-set of a SELECT. The Z expression ** is replaced by a copy of the left-hand side of the result-set expression. ** Table-name and function resolution occurs on the substituted expression ** tree. For example, in: ** ** SELECT a+b AS x, c+d AS y FROM t1 ORDER BY x; ** ** The "x" term of the order by is replaced by "a+b" to render: ** ** SELECT a+b AS x, c+d AS y FROM t1 ORDER BY a+b; ** ** Function calls are checked to make sure that the function is ** defined and that the correct number of arguments are specified. ** If the function is an aggregate function, then the NC_HasAgg flag is ** set and the opcode is changed from TK_FUNCTION to TK_AGG_FUNCTION. ** If an expression contains aggregate functions then the EP_Agg ** property on the expression is set. ** ** An error message is left in pParse if anything is amiss. The number ** if errors is returned. */ SQLITE_PRIVATE int sqlite3ResolveExprNames( NameContext *pNC, /* Namespace to resolve expressions in. */ Expr *pExpr /* The expression to be analyzed. */ ){ u16 savedHasAgg; Walker w; if( pExpr==0 ) return 0; #if SQLITE_MAX_EXPR_DEPTH>0 { Parse *pParse = pNC->pParse; if( sqlite3ExprCheckHeight(pParse, pExpr->nHeight+pNC->pParse->nHeight) ){ return 1; } pParse->nHeight += pExpr->nHeight; } #endif savedHasAgg = pNC->ncFlags & (NC_HasAgg|NC_MinMaxAgg); pNC->ncFlags &= ~(NC_HasAgg|NC_MinMaxAgg); w.pParse = pNC->pParse; w.xExprCallback = resolveExprStep; w.xSelectCallback = resolveSelectStep; w.xSelectCallback2 = 0; w.walkerDepth = 0; w.eCode = 0; w.u.pNC = pNC; sqlite3WalkExpr(&w, pExpr); #if SQLITE_MAX_EXPR_DEPTH>0 pNC->pParse->nHeight -= pExpr->nHeight; #endif if( pNC->nErr>0 || w.pParse->nErr>0 ){ ExprSetProperty(pExpr, EP_Error); } if( pNC->ncFlags & NC_HasAgg ){ ExprSetProperty(pExpr, EP_Agg); } pNC->ncFlags |= savedHasAgg; return ExprHasProperty(pExpr, EP_Error); } /* ** Resolve all names for all expression in an expression list. This is ** just like sqlite3ResolveExprNames() except that it works for an expression ** list rather than a single expression. */ SQLITE_PRIVATE int sqlite3ResolveExprListNames( NameContext *pNC, /* Namespace to resolve expressions in. */ ExprList *pList /* The expression list to be analyzed. */ ){ int i; if( pList ){ for(i=0; inExpr; i++){ if( sqlite3ResolveExprNames(pNC, pList->a[i].pExpr) ) return WRC_Abort; } } return WRC_Continue; } /* ** Resolve all names in all expressions of a SELECT and in all ** decendents of the SELECT, including compounds off of p->pPrior, ** subqueries in expressions, and subqueries used as FROM clause ** terms. ** ** See sqlite3ResolveExprNames() for a description of the kinds of ** transformations that occur. ** ** All SELECT statements should have been expanded using ** sqlite3SelectExpand() prior to invoking this routine. */ SQLITE_PRIVATE void sqlite3ResolveSelectNames( Parse *pParse, /* The parser context */ Select *p, /* The SELECT statement being coded. */ NameContext *pOuterNC /* Name context for parent SELECT statement */ ){ Walker w; assert( p!=0 ); memset(&w, 0, sizeof(w)); w.xExprCallback = resolveExprStep; w.xSelectCallback = resolveSelectStep; w.pParse = pParse; w.u.pNC = pOuterNC; sqlite3WalkSelect(&w, p); } /* ** Resolve names in expressions that can only reference a single table: ** ** * CHECK constraints ** * WHERE clauses on partial indices ** ** The Expr.iTable value for Expr.op==TK_COLUMN nodes of the expression ** is set to -1 and the Expr.iColumn value is set to the column number. ** ** Any errors cause an error message to be set in pParse. */ SQLITE_PRIVATE void sqlite3ResolveSelfReference( Parse *pParse, /* Parsing context */ Table *pTab, /* The table being referenced */ int type, /* NC_IsCheck or NC_PartIdx or NC_IdxExpr */ Expr *pExpr, /* Expression to resolve. May be NULL. */ ExprList *pList /* Expression list to resolve. May be NUL. */ ){ SrcList sSrc; /* Fake SrcList for pParse->pNewTable */ NameContext sNC; /* Name context for pParse->pNewTable */ assert( type==NC_IsCheck || type==NC_PartIdx || type==NC_IdxExpr ); memset(&sNC, 0, sizeof(sNC)); memset(&sSrc, 0, sizeof(sSrc)); sSrc.nSrc = 1; sSrc.a[0].zName = pTab->zName; sSrc.a[0].pTab = pTab; sSrc.a[0].iCursor = -1; sNC.pParse = pParse; sNC.pSrcList = &sSrc; sNC.ncFlags = type; if( sqlite3ResolveExprNames(&sNC, pExpr) ) return; if( pList ) sqlite3ResolveExprListNames(&sNC, pList); } /************** End of resolve.c *********************************************/ /************** Begin file expr.c ********************************************/ /* ** 2001 September 15 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ************************************************************************* ** This file contains routines used for analyzing expressions and ** for generating VDBE code that evaluates expressions in SQLite. */ /* #include "sqliteInt.h" */ /* Forward declarations */ static void exprCodeBetween(Parse*,Expr*,int,void(*)(Parse*,Expr*,int,int),int); static int exprCodeVector(Parse *pParse, Expr *p, int *piToFree); /* ** Return the affinity character for a single column of a table. */ SQLITE_PRIVATE char sqlite3TableColumnAffinity(Table *pTab, int iCol){ assert( iColnCol ); return iCol>=0 ? pTab->aCol[iCol].affinity : SQLITE_AFF_INTEGER; } /* ** Return the 'affinity' of the expression pExpr if any. ** ** If pExpr is a column, a reference to a column via an 'AS' alias, ** or a sub-select with a column as the return value, then the ** affinity of that column is returned. Otherwise, 0x00 is returned, ** indicating no affinity for the expression. ** ** i.e. the WHERE clause expressions in the following statements all ** have an affinity: ** ** CREATE TABLE t1(a); ** SELECT * FROM t1 WHERE a; ** SELECT a AS b FROM t1 WHERE b; ** SELECT * FROM t1 WHERE (select a from t1); */ SQLITE_PRIVATE char sqlite3ExprAffinity(Expr *pExpr){ int op; pExpr = sqlite3ExprSkipCollate(pExpr); if( pExpr->flags & EP_Generic ) return 0; op = pExpr->op; if( op==TK_SELECT ){ assert( pExpr->flags&EP_xIsSelect ); return sqlite3ExprAffinity(pExpr->x.pSelect->pEList->a[0].pExpr); } if( op==TK_REGISTER ) op = pExpr->op2; #ifndef SQLITE_OMIT_CAST if( op==TK_CAST ){ assert( !ExprHasProperty(pExpr, EP_IntValue) ); return sqlite3AffinityType(pExpr->u.zToken, 0); } #endif if( op==TK_AGG_COLUMN || op==TK_COLUMN ){ return sqlite3TableColumnAffinity(pExpr->pTab, pExpr->iColumn); } if( op==TK_SELECT_COLUMN ){ assert( pExpr->pLeft->flags&EP_xIsSelect ); return sqlite3ExprAffinity( pExpr->pLeft->x.pSelect->pEList->a[pExpr->iColumn].pExpr ); } return pExpr->affinity; } /* ** Set the collating sequence for expression pExpr to be the collating ** sequence named by pToken. Return a pointer to a new Expr node that ** implements the COLLATE operator. ** ** If a memory allocation error occurs, that fact is recorded in pParse->db ** and the pExpr parameter is returned unchanged. */ SQLITE_PRIVATE Expr *sqlite3ExprAddCollateToken( Parse *pParse, /* Parsing context */ Expr *pExpr, /* Add the "COLLATE" clause to this expression */ const Token *pCollName, /* Name of collating sequence */ int dequote /* True to dequote pCollName */ ){ if( pCollName->n>0 ){ Expr *pNew = sqlite3ExprAlloc(pParse->db, TK_COLLATE, pCollName, dequote); if( pNew ){ pNew->pLeft = pExpr; pNew->flags |= EP_Collate|EP_Skip; pExpr = pNew; } } return pExpr; } SQLITE_PRIVATE Expr *sqlite3ExprAddCollateString(Parse *pParse, Expr *pExpr, const char *zC){ Token s; assert( zC!=0 ); sqlite3TokenInit(&s, (char*)zC); return sqlite3ExprAddCollateToken(pParse, pExpr, &s, 0); } /* ** Skip over any TK_COLLATE operators and any unlikely() ** or likelihood() function at the root of an expression. */ SQLITE_PRIVATE Expr *sqlite3ExprSkipCollate(Expr *pExpr){ while( pExpr && ExprHasProperty(pExpr, EP_Skip) ){ if( ExprHasProperty(pExpr, EP_Unlikely) ){ assert( !ExprHasProperty(pExpr, EP_xIsSelect) ); assert( pExpr->x.pList->nExpr>0 ); assert( pExpr->op==TK_FUNCTION ); pExpr = pExpr->x.pList->a[0].pExpr; }else{ assert( pExpr->op==TK_COLLATE ); pExpr = pExpr->pLeft; } } return pExpr; } /* ** Return the collation sequence for the expression pExpr. If ** there is no defined collating sequence, return NULL. ** ** The collating sequence might be determined by a COLLATE operator ** or by the presence of a column with a defined collating sequence. ** COLLATE operators take first precedence. Left operands take ** precedence over right operands. */ SQLITE_PRIVATE CollSeq *sqlite3ExprCollSeq(Parse *pParse, Expr *pExpr){ sqlite3 *db = pParse->db; CollSeq *pColl = 0; Expr *p = pExpr; while( p ){ int op = p->op; if( p->flags & EP_Generic ) break; if( op==TK_CAST || op==TK_UPLUS ){ p = p->pLeft; continue; } if( op==TK_COLLATE || (op==TK_REGISTER && p->op2==TK_COLLATE) ){ pColl = sqlite3GetCollSeq(pParse, ENC(db), 0, p->u.zToken); break; } if( (op==TK_AGG_COLUMN || op==TK_COLUMN || op==TK_REGISTER || op==TK_TRIGGER) && p->pTab!=0 ){ /* op==TK_REGISTER && p->pTab!=0 happens when pExpr was originally ** a TK_COLUMN but was previously evaluated and cached in a register */ int j = p->iColumn; if( j>=0 ){ const char *zColl = p->pTab->aCol[j].zColl; pColl = sqlite3FindCollSeq(db, ENC(db), zColl, 0); } break; } if( p->flags & EP_Collate ){ if( p->pLeft && (p->pLeft->flags & EP_Collate)!=0 ){ p = p->pLeft; }else{ Expr *pNext = p->pRight; /* The Expr.x union is never used at the same time as Expr.pRight */ assert( p->x.pList==0 || p->pRight==0 ); /* p->flags holds EP_Collate and p->pLeft->flags does not. And ** p->x.pSelect cannot. So if p->x.pLeft exists, it must hold at ** least one EP_Collate. Thus the following two ALWAYS. */ if( p->x.pList!=0 && ALWAYS(!ExprHasProperty(p, EP_xIsSelect)) ){ int i; for(i=0; ALWAYS(ix.pList->nExpr); i++){ if( ExprHasProperty(p->x.pList->a[i].pExpr, EP_Collate) ){ pNext = p->x.pList->a[i].pExpr; break; } } } p = pNext; } }else{ break; } } if( sqlite3CheckCollSeq(pParse, pColl) ){ pColl = 0; } return pColl; } /* ** pExpr is an operand of a comparison operator. aff2 is the ** type affinity of the other operand. This routine returns the ** type affinity that should be used for the comparison operator. */ SQLITE_PRIVATE char sqlite3CompareAffinity(Expr *pExpr, char aff2){ char aff1 = sqlite3ExprAffinity(pExpr); if( aff1 && aff2 ){ /* Both sides of the comparison are columns. If one has numeric ** affinity, use that. Otherwise use no affinity. */ if( sqlite3IsNumericAffinity(aff1) || sqlite3IsNumericAffinity(aff2) ){ return SQLITE_AFF_NUMERIC; }else{ return SQLITE_AFF_BLOB; } }else if( !aff1 && !aff2 ){ /* Neither side of the comparison is a column. Compare the ** results directly. */ return SQLITE_AFF_BLOB; }else{ /* One side is a column, the other is not. Use the columns affinity. */ assert( aff1==0 || aff2==0 ); return (aff1 + aff2); } } /* ** pExpr is a comparison operator. Return the type affinity that should ** be applied to both operands prior to doing the comparison. */ static char comparisonAffinity(Expr *pExpr){ char aff; assert( pExpr->op==TK_EQ || pExpr->op==TK_IN || pExpr->op==TK_LT || pExpr->op==TK_GT || pExpr->op==TK_GE || pExpr->op==TK_LE || pExpr->op==TK_NE || pExpr->op==TK_IS || pExpr->op==TK_ISNOT ); assert( pExpr->pLeft ); aff = sqlite3ExprAffinity(pExpr->pLeft); if( pExpr->pRight ){ aff = sqlite3CompareAffinity(pExpr->pRight, aff); }else if( ExprHasProperty(pExpr, EP_xIsSelect) ){ aff = sqlite3CompareAffinity(pExpr->x.pSelect->pEList->a[0].pExpr, aff); }else if( NEVER(aff==0) ){ aff = SQLITE_AFF_BLOB; } return aff; } /* ** pExpr is a comparison expression, eg. '=', '<', IN(...) etc. ** idx_affinity is the affinity of an indexed column. Return true ** if the index with affinity idx_affinity may be used to implement ** the comparison in pExpr. */ SQLITE_PRIVATE int sqlite3IndexAffinityOk(Expr *pExpr, char idx_affinity){ char aff = comparisonAffinity(pExpr); switch( aff ){ case SQLITE_AFF_BLOB: return 1; case SQLITE_AFF_TEXT: return idx_affinity==SQLITE_AFF_TEXT; default: return sqlite3IsNumericAffinity(idx_affinity); } } /* ** Return the P5 value that should be used for a binary comparison ** opcode (OP_Eq, OP_Ge etc.) used to compare pExpr1 and pExpr2. */ static u8 binaryCompareP5(Expr *pExpr1, Expr *pExpr2, int jumpIfNull){ u8 aff = (char)sqlite3ExprAffinity(pExpr2); aff = (u8)sqlite3CompareAffinity(pExpr1, aff) | (u8)jumpIfNull; return aff; } /* ** Return a pointer to the collation sequence that should be used by ** a binary comparison operator comparing pLeft and pRight. ** ** If the left hand expression has a collating sequence type, then it is ** used. Otherwise the collation sequence for the right hand expression ** is used, or the default (BINARY) if neither expression has a collating ** type. ** ** Argument pRight (but not pLeft) may be a null pointer. In this case, ** it is not considered. */ SQLITE_PRIVATE CollSeq *sqlite3BinaryCompareCollSeq( Parse *pParse, Expr *pLeft, Expr *pRight ){ CollSeq *pColl; assert( pLeft ); if( pLeft->flags & EP_Collate ){ pColl = sqlite3ExprCollSeq(pParse, pLeft); }else if( pRight && (pRight->flags & EP_Collate)!=0 ){ pColl = sqlite3ExprCollSeq(pParse, pRight); }else{ pColl = sqlite3ExprCollSeq(pParse, pLeft); if( !pColl ){ pColl = sqlite3ExprCollSeq(pParse, pRight); } } return pColl; } /* ** Generate code for a comparison operator. */ static int codeCompare( Parse *pParse, /* The parsing (and code generating) context */ Expr *pLeft, /* The left operand */ Expr *pRight, /* The right operand */ int opcode, /* The comparison opcode */ int in1, int in2, /* Register holding operands */ int dest, /* Jump here if true. */ int jumpIfNull /* If true, jump if either operand is NULL */ ){ int p5; int addr; CollSeq *p4; p4 = sqlite3BinaryCompareCollSeq(pParse, pLeft, pRight); p5 = binaryCompareP5(pLeft, pRight, jumpIfNull); addr = sqlite3VdbeAddOp4(pParse->pVdbe, opcode, in2, dest, in1, (void*)p4, P4_COLLSEQ); sqlite3VdbeChangeP5(pParse->pVdbe, (u8)p5); return addr; } /* ** Return true if expression pExpr is a vector, or false otherwise. ** ** A vector is defined as any expression that results in two or more ** columns of result. Every TK_VECTOR node is an vector because the ** parser will not generate a TK_VECTOR with fewer than two entries. ** But a TK_SELECT might be either a vector or a scalar. It is only ** considered a vector if it has two or more result columns. */ SQLITE_PRIVATE int sqlite3ExprIsVector(Expr *pExpr){ return sqlite3ExprVectorSize(pExpr)>1; } /* ** If the expression passed as the only argument is of type TK_VECTOR ** return the number of expressions in the vector. Or, if the expression ** is a sub-select, return the number of columns in the sub-select. For ** any other type of expression, return 1. */ SQLITE_PRIVATE int sqlite3ExprVectorSize(Expr *pExpr){ u8 op = pExpr->op; if( op==TK_REGISTER ) op = pExpr->op2; if( op==TK_VECTOR ){ return pExpr->x.pList->nExpr; }else if( op==TK_SELECT ){ return pExpr->x.pSelect->pEList->nExpr; }else{ return 1; } } #ifndef SQLITE_OMIT_SUBQUERY /* ** Return a pointer to a subexpression of pVector that is the i-th ** column of the vector (numbered starting with 0). The caller must ** ensure that i is within range. ** ** If pVector is really a scalar (and "scalar" here includes subqueries ** that return a single column!) then return pVector unmodified. ** ** pVector retains ownership of the returned subexpression. ** ** If the vector is a (SELECT ...) then the expression returned is ** just the expression for the i-th term of the result set, and may ** not be ready for evaluation because the table cursor has not yet ** been positioned. */ SQLITE_PRIVATE Expr *sqlite3VectorFieldSubexpr(Expr *pVector, int i){ assert( iop2==0 || pVector->op==TK_REGISTER ); if( pVector->op==TK_SELECT || pVector->op2==TK_SELECT ){ return pVector->x.pSelect->pEList->a[i].pExpr; }else{ return pVector->x.pList->a[i].pExpr; } } return pVector; } #endif /* !defined(SQLITE_OMIT_SUBQUERY) */ #ifndef SQLITE_OMIT_SUBQUERY /* ** Compute and return a new Expr object which when passed to ** sqlite3ExprCode() will generate all necessary code to compute ** the iField-th column of the vector expression pVector. ** ** It is ok for pVector to be a scalar (as long as iField==0). ** In that case, this routine works like sqlite3ExprDup(). ** ** The caller owns the returned Expr object and is responsible for ** ensuring that the returned value eventually gets freed. ** ** The caller retains ownership of pVector. If pVector is a TK_SELECT, ** then the returned object will reference pVector and so pVector must remain ** valid for the life of the returned object. If pVector is a TK_VECTOR ** or a scalar expression, then it can be deleted as soon as this routine ** returns. ** ** A trick to cause a TK_SELECT pVector to be deleted together with ** the returned Expr object is to attach the pVector to the pRight field ** of the returned TK_SELECT_COLUMN Expr object. */ SQLITE_PRIVATE Expr *sqlite3ExprForVectorField( Parse *pParse, /* Parsing context */ Expr *pVector, /* The vector. List of expressions or a sub-SELECT */ int iField /* Which column of the vector to return */ ){ Expr *pRet; if( pVector->op==TK_SELECT ){ assert( pVector->flags & EP_xIsSelect ); /* The TK_SELECT_COLUMN Expr node: ** ** pLeft: pVector containing TK_SELECT ** pRight: not used. But recursively deleted. ** iColumn: Index of a column in pVector ** pLeft->iTable: First in an array of register holding result, or 0 ** if the result is not yet computed. ** ** sqlite3ExprDelete() specifically skips the recursive delete of ** pLeft on TK_SELECT_COLUMN nodes. But pRight is followed, so pVector ** can be attached to pRight to cause this node to take ownership of ** pVector. Typically there will be multiple TK_SELECT_COLUMN nodes ** with the same pLeft pointer to the pVector, but only one of them ** will own the pVector. */ pRet = sqlite3PExpr(pParse, TK_SELECT_COLUMN, 0, 0, 0); if( pRet ){ pRet->iColumn = iField; pRet->pLeft = pVector; } assert( pRet==0 || pRet->iTable==0 ); }else{ if( pVector->op==TK_VECTOR ) pVector = pVector->x.pList->a[iField].pExpr; pRet = sqlite3ExprDup(pParse->db, pVector, 0); } return pRet; } #endif /* !define(SQLITE_OMIT_SUBQUERY) */ /* ** If expression pExpr is of type TK_SELECT, generate code to evaluate ** it. Return the register in which the result is stored (or, if the ** sub-select returns more than one column, the first in an array ** of registers in which the result is stored). ** ** If pExpr is not a TK_SELECT expression, return 0. */ static int exprCodeSubselect(Parse *pParse, Expr *pExpr){ int reg = 0; #ifndef SQLITE_OMIT_SUBQUERY if( pExpr->op==TK_SELECT ){ reg = sqlite3CodeSubselect(pParse, pExpr, 0, 0); } #endif return reg; } /* ** Argument pVector points to a vector expression - either a TK_VECTOR ** or TK_SELECT that returns more than one column. This function returns ** the register number of a register that contains the value of ** element iField of the vector. ** ** If pVector is a TK_SELECT expression, then code for it must have ** already been generated using the exprCodeSubselect() routine. In this ** case parameter regSelect should be the first in an array of registers ** containing the results of the sub-select. ** ** If pVector is of type TK_VECTOR, then code for the requested field ** is generated. In this case (*pRegFree) may be set to the number of ** a temporary register to be freed by the caller before returning. ** ** Before returning, output parameter (*ppExpr) is set to point to the ** Expr object corresponding to element iElem of the vector. */ static int exprVectorRegister( Parse *pParse, /* Parse context */ Expr *pVector, /* Vector to extract element from */ int iField, /* Field to extract from pVector */ int regSelect, /* First in array of registers */ Expr **ppExpr, /* OUT: Expression element */ int *pRegFree /* OUT: Temp register to free */ ){ u8 op = pVector->op; assert( op==TK_VECTOR || op==TK_REGISTER || op==TK_SELECT ); if( op==TK_REGISTER ){ *ppExpr = sqlite3VectorFieldSubexpr(pVector, iField); return pVector->iTable+iField; } if( op==TK_SELECT ){ *ppExpr = pVector->x.pSelect->pEList->a[iField].pExpr; return regSelect+iField; } *ppExpr = pVector->x.pList->a[iField].pExpr; return sqlite3ExprCodeTemp(pParse, *ppExpr, pRegFree); } /* ** Expression pExpr is a comparison between two vector values. Compute ** the result of the comparison (1, 0, or NULL) and write that ** result into register dest. ** ** The caller must satisfy the following preconditions: ** ** if pExpr->op==TK_IS: op==TK_EQ and p5==SQLITE_NULLEQ ** if pExpr->op==TK_ISNOT: op==TK_NE and p5==SQLITE_NULLEQ ** otherwise: op==pExpr->op and p5==0 */ static void codeVectorCompare( Parse *pParse, /* Code generator context */ Expr *pExpr, /* The comparison operation */ int dest, /* Write results into this register */ u8 op, /* Comparison operator */ u8 p5 /* SQLITE_NULLEQ or zero */ ){ Vdbe *v = pParse->pVdbe; Expr *pLeft = pExpr->pLeft; Expr *pRight = pExpr->pRight; int nLeft = sqlite3ExprVectorSize(pLeft); int i; int regLeft = 0; int regRight = 0; u8 opx = op; int addrDone = sqlite3VdbeMakeLabel(v); assert( nLeft==sqlite3ExprVectorSize(pRight) ); assert( pExpr->op==TK_EQ || pExpr->op==TK_NE || pExpr->op==TK_IS || pExpr->op==TK_ISNOT || pExpr->op==TK_LT || pExpr->op==TK_GT || pExpr->op==TK_LE || pExpr->op==TK_GE ); assert( pExpr->op==op || (pExpr->op==TK_IS && op==TK_EQ) || (pExpr->op==TK_ISNOT && op==TK_NE) ); assert( p5==0 || pExpr->op!=op ); assert( p5==SQLITE_NULLEQ || pExpr->op==op ); p5 |= SQLITE_STOREP2; if( opx==TK_LE ) opx = TK_LT; if( opx==TK_GE ) opx = TK_GT; regLeft = exprCodeSubselect(pParse, pLeft); regRight = exprCodeSubselect(pParse, pRight); for(i=0; 1 /*Loop exits by "break"*/; i++){ int regFree1 = 0, regFree2 = 0; Expr *pL, *pR; int r1, r2; assert( i>=0 && i0 ) sqlite3ExprCachePush(pParse); r1 = exprVectorRegister(pParse, pLeft, i, regLeft, &pL, ®Free1); r2 = exprVectorRegister(pParse, pRight, i, regRight, &pR, ®Free2); codeCompare(pParse, pL, pR, opx, r1, r2, dest, p5); testcase(op==OP_Lt); VdbeCoverageIf(v,op==OP_Lt); testcase(op==OP_Le); VdbeCoverageIf(v,op==OP_Le); testcase(op==OP_Gt); VdbeCoverageIf(v,op==OP_Gt); testcase(op==OP_Ge); VdbeCoverageIf(v,op==OP_Ge); testcase(op==OP_Eq); VdbeCoverageIf(v,op==OP_Eq); testcase(op==OP_Ne); VdbeCoverageIf(v,op==OP_Ne); sqlite3ReleaseTempReg(pParse, regFree1); sqlite3ReleaseTempReg(pParse, regFree2); if( i>0 ) sqlite3ExprCachePop(pParse); if( i==nLeft-1 ){ break; } if( opx==TK_EQ ){ sqlite3VdbeAddOp2(v, OP_IfNot, dest, addrDone); VdbeCoverage(v); p5 |= SQLITE_KEEPNULL; }else if( opx==TK_NE ){ sqlite3VdbeAddOp2(v, OP_If, dest, addrDone); VdbeCoverage(v); p5 |= SQLITE_KEEPNULL; }else{ assert( op==TK_LT || op==TK_GT || op==TK_LE || op==TK_GE ); sqlite3VdbeAddOp2(v, OP_ElseNotEq, 0, addrDone); VdbeCoverageIf(v, op==TK_LT); VdbeCoverageIf(v, op==TK_GT); VdbeCoverageIf(v, op==TK_LE); VdbeCoverageIf(v, op==TK_GE); if( i==nLeft-2 ) opx = op; } } sqlite3VdbeResolveLabel(v, addrDone); } #if SQLITE_MAX_EXPR_DEPTH>0 /* ** Check that argument nHeight is less than or equal to the maximum ** expression depth allowed. If it is not, leave an error message in ** pParse. */ SQLITE_PRIVATE int sqlite3ExprCheckHeight(Parse *pParse, int nHeight){ int rc = SQLITE_OK; int mxHeight = pParse->db->aLimit[SQLITE_LIMIT_EXPR_DEPTH]; if( nHeight>mxHeight ){ sqlite3ErrorMsg(pParse, "Expression tree is too large (maximum depth %d)", mxHeight ); rc = SQLITE_ERROR; } return rc; } /* The following three functions, heightOfExpr(), heightOfExprList() ** and heightOfSelect(), are used to determine the maximum height ** of any expression tree referenced by the structure passed as the ** first argument. ** ** If this maximum height is greater than the current value pointed ** to by pnHeight, the second parameter, then set *pnHeight to that ** value. */ static void heightOfExpr(Expr *p, int *pnHeight){ if( p ){ if( p->nHeight>*pnHeight ){ *pnHeight = p->nHeight; } } } static void heightOfExprList(ExprList *p, int *pnHeight){ if( p ){ int i; for(i=0; inExpr; i++){ heightOfExpr(p->a[i].pExpr, pnHeight); } } } static void heightOfSelect(Select *p, int *pnHeight){ if( p ){ heightOfExpr(p->pWhere, pnHeight); heightOfExpr(p->pHaving, pnHeight); heightOfExpr(p->pLimit, pnHeight); heightOfExpr(p->pOffset, pnHeight); heightOfExprList(p->pEList, pnHeight); heightOfExprList(p->pGroupBy, pnHeight); heightOfExprList(p->pOrderBy, pnHeight); heightOfSelect(p->pPrior, pnHeight); } } /* ** Set the Expr.nHeight variable in the structure passed as an ** argument. An expression with no children, Expr.pList or ** Expr.pSelect member has a height of 1. Any other expression ** has a height equal to the maximum height of any other ** referenced Expr plus one. ** ** Also propagate EP_Propagate flags up from Expr.x.pList to Expr.flags, ** if appropriate. */ static void exprSetHeight(Expr *p){ int nHeight = 0; heightOfExpr(p->pLeft, &nHeight); heightOfExpr(p->pRight, &nHeight); if( ExprHasProperty(p, EP_xIsSelect) ){ heightOfSelect(p->x.pSelect, &nHeight); }else if( p->x.pList ){ heightOfExprList(p->x.pList, &nHeight); p->flags |= EP_Propagate & sqlite3ExprListFlags(p->x.pList); } p->nHeight = nHeight + 1; } /* ** Set the Expr.nHeight variable using the exprSetHeight() function. If ** the height is greater than the maximum allowed expression depth, ** leave an error in pParse. ** ** Also propagate all EP_Propagate flags from the Expr.x.pList into ** Expr.flags. */ SQLITE_PRIVATE void sqlite3ExprSetHeightAndFlags(Parse *pParse, Expr *p){ if( pParse->nErr ) return; exprSetHeight(p); sqlite3ExprCheckHeight(pParse, p->nHeight); } /* ** Return the maximum height of any expression tree referenced ** by the select statement passed as an argument. */ SQLITE_PRIVATE int sqlite3SelectExprHeight(Select *p){ int nHeight = 0; heightOfSelect(p, &nHeight); return nHeight; } #else /* ABOVE: Height enforcement enabled. BELOW: Height enforcement off */ /* ** Propagate all EP_Propagate flags from the Expr.x.pList into ** Expr.flags. */ SQLITE_PRIVATE void sqlite3ExprSetHeightAndFlags(Parse *pParse, Expr *p){ if( p && p->x.pList && !ExprHasProperty(p, EP_xIsSelect) ){ p->flags |= EP_Propagate & sqlite3ExprListFlags(p->x.pList); } } #define exprSetHeight(y) #endif /* SQLITE_MAX_EXPR_DEPTH>0 */ /* ** This routine is the core allocator for Expr nodes. ** ** Construct a new expression node and return a pointer to it. Memory ** for this node and for the pToken argument is a single allocation ** obtained from sqlite3DbMalloc(). The calling function ** is responsible for making sure the node eventually gets freed. ** ** If dequote is true, then the token (if it exists) is dequoted. ** If dequote is false, no dequoting is performed. The deQuote ** parameter is ignored if pToken is NULL or if the token does not ** appear to be quoted. If the quotes were of the form "..." (double-quotes) ** then the EP_DblQuoted flag is set on the expression node. ** ** Special case: If op==TK_INTEGER and pToken points to a string that ** can be translated into a 32-bit integer, then the token is not ** stored in u.zToken. Instead, the integer values is written ** into u.iValue and the EP_IntValue flag is set. No extra storage ** is allocated to hold the integer text and the dequote flag is ignored. */ SQLITE_PRIVATE Expr *sqlite3ExprAlloc( sqlite3 *db, /* Handle for sqlite3DbMallocRawNN() */ int op, /* Expression opcode */ const Token *pToken, /* Token argument. Might be NULL */ int dequote /* True to dequote */ ){ Expr *pNew; int nExtra = 0; int iValue = 0; assert( db!=0 ); if( pToken ){ if( op!=TK_INTEGER || pToken->z==0 || sqlite3GetInt32(pToken->z, &iValue)==0 ){ nExtra = pToken->n+1; assert( iValue>=0 ); } } pNew = sqlite3DbMallocRawNN(db, sizeof(Expr)+nExtra); if( pNew ){ memset(pNew, 0, sizeof(Expr)); pNew->op = (u8)op; pNew->iAgg = -1; if( pToken ){ if( nExtra==0 ){ pNew->flags |= EP_IntValue; pNew->u.iValue = iValue; }else{ pNew->u.zToken = (char*)&pNew[1]; assert( pToken->z!=0 || pToken->n==0 ); if( pToken->n ) memcpy(pNew->u.zToken, pToken->z, pToken->n); pNew->u.zToken[pToken->n] = 0; if( dequote && sqlite3Isquote(pNew->u.zToken[0]) ){ if( pNew->u.zToken[0]=='"' ) pNew->flags |= EP_DblQuoted; sqlite3Dequote(pNew->u.zToken); } } } #if SQLITE_MAX_EXPR_DEPTH>0 pNew->nHeight = 1; #endif } return pNew; } /* ** Allocate a new expression node from a zero-terminated token that has ** already been dequoted. */ SQLITE_PRIVATE Expr *sqlite3Expr( sqlite3 *db, /* Handle for sqlite3DbMallocZero() (may be null) */ int op, /* Expression opcode */ const char *zToken /* Token argument. Might be NULL */ ){ Token x; x.z = zToken; x.n = zToken ? sqlite3Strlen30(zToken) : 0; return sqlite3ExprAlloc(db, op, &x, 0); } /* ** Attach subtrees pLeft and pRight to the Expr node pRoot. ** ** If pRoot==NULL that means that a memory allocation error has occurred. ** In that case, delete the subtrees pLeft and pRight. */ SQLITE_PRIVATE void sqlite3ExprAttachSubtrees( sqlite3 *db, Expr *pRoot, Expr *pLeft, Expr *pRight ){ if( pRoot==0 ){ assert( db->mallocFailed ); sqlite3ExprDelete(db, pLeft); sqlite3ExprDelete(db, pRight); }else{ if( pRight ){ pRoot->pRight = pRight; pRoot->flags |= EP_Propagate & pRight->flags; } if( pLeft ){ pRoot->pLeft = pLeft; pRoot->flags |= EP_Propagate & pLeft->flags; } exprSetHeight(pRoot); } } /* ** Allocate an Expr node which joins as many as two subtrees. ** ** One or both of the subtrees can be NULL. Return a pointer to the new ** Expr node. Or, if an OOM error occurs, set pParse->db->mallocFailed, ** free the subtrees and return NULL. */ SQLITE_PRIVATE Expr *sqlite3PExpr( Parse *pParse, /* Parsing context */ int op, /* Expression opcode */ Expr *pLeft, /* Left operand */ Expr *pRight, /* Right operand */ const Token *pToken /* Argument token */ ){ Expr *p; if( op==TK_AND && pParse->nErr==0 ){ /* Take advantage of short-circuit false optimization for AND */ p = sqlite3ExprAnd(pParse->db, pLeft, pRight); }else{ p = sqlite3ExprAlloc(pParse->db, op & TKFLG_MASK, pToken, 1); sqlite3ExprAttachSubtrees(pParse->db, p, pLeft, pRight); } if( p ) { sqlite3ExprCheckHeight(pParse, p->nHeight); } return p; } /* ** Add pSelect to the Expr.x.pSelect field. Or, if pExpr is NULL (due ** do a memory allocation failure) then delete the pSelect object. */ SQLITE_PRIVATE void sqlite3PExprAddSelect(Parse *pParse, Expr *pExpr, Select *pSelect){ if( pExpr ){ pExpr->x.pSelect = pSelect; ExprSetProperty(pExpr, EP_xIsSelect|EP_Subquery); sqlite3ExprSetHeightAndFlags(pParse, pExpr); }else{ assert( pParse->db->mallocFailed ); sqlite3SelectDelete(pParse->db, pSelect); } } /* ** If the expression is always either TRUE or FALSE (respectively), ** then return 1. If one cannot determine the truth value of the ** expression at compile-time return 0. ** ** This is an optimization. If is OK to return 0 here even if ** the expression really is always false or false (a false negative). ** But it is a bug to return 1 if the expression might have different ** boolean values in different circumstances (a false positive.) ** ** Note that if the expression is part of conditional for a ** LEFT JOIN, then we cannot determine at compile-time whether or not ** is it true or false, so always return 0. */ static int exprAlwaysTrue(Expr *p){ int v = 0; if( ExprHasProperty(p, EP_FromJoin) ) return 0; if( !sqlite3ExprIsInteger(p, &v) ) return 0; return v!=0; } static int exprAlwaysFalse(Expr *p){ int v = 0; if( ExprHasProperty(p, EP_FromJoin) ) return 0; if( !sqlite3ExprIsInteger(p, &v) ) return 0; return v==0; } /* ** Join two expressions using an AND operator. If either expression is ** NULL, then just return the other expression. ** ** If one side or the other of the AND is known to be false, then instead ** of returning an AND expression, just return a constant expression with ** a value of false. */ SQLITE_PRIVATE Expr *sqlite3ExprAnd(sqlite3 *db, Expr *pLeft, Expr *pRight){ if( pLeft==0 ){ return pRight; }else if( pRight==0 ){ return pLeft; }else if( exprAlwaysFalse(pLeft) || exprAlwaysFalse(pRight) ){ sqlite3ExprDelete(db, pLeft); sqlite3ExprDelete(db, pRight); return sqlite3ExprAlloc(db, TK_INTEGER, &sqlite3IntTokens[0], 0); }else{ Expr *pNew = sqlite3ExprAlloc(db, TK_AND, 0, 0); sqlite3ExprAttachSubtrees(db, pNew, pLeft, pRight); return pNew; } } /* ** Construct a new expression node for a function with multiple ** arguments. */ SQLITE_PRIVATE Expr *sqlite3ExprFunction(Parse *pParse, ExprList *pList, Token *pToken){ Expr *pNew; sqlite3 *db = pParse->db; assert( pToken ); pNew = sqlite3ExprAlloc(db, TK_FUNCTION, pToken, 1); if( pNew==0 ){ sqlite3ExprListDelete(db, pList); /* Avoid memory leak when malloc fails */ return 0; } pNew->x.pList = pList; assert( !ExprHasProperty(pNew, EP_xIsSelect) ); sqlite3ExprSetHeightAndFlags(pParse, pNew); return pNew; } /* ** Assign a variable number to an expression that encodes a wildcard ** in the original SQL statement. ** ** Wildcards consisting of a single "?" are assigned the next sequential ** variable number. ** ** Wildcards of the form "?nnn" are assigned the number "nnn". We make ** sure "nnn" is not too be to avoid a denial of service attack when ** the SQL statement comes from an external source. ** ** Wildcards of the form ":aaa", "@aaa", or "$aaa" are assigned the same number ** as the previous instance of the same wildcard. Or if this is the first ** instance of the wildcard, the next sequential variable number is ** assigned. */ SQLITE_PRIVATE void sqlite3ExprAssignVarNumber(Parse *pParse, Expr *pExpr, u32 n){ sqlite3 *db = pParse->db; const char *z; if( pExpr==0 ) return; assert( !ExprHasProperty(pExpr, EP_IntValue|EP_Reduced|EP_TokenOnly) ); z = pExpr->u.zToken; assert( z!=0 ); assert( z[0]!=0 ); assert( n==sqlite3Strlen30(z) ); if( z[1]==0 ){ /* Wildcard of the form "?". Assign the next variable number */ assert( z[0]=='?' ); pExpr->iColumn = (ynVar)(++pParse->nVar); }else{ ynVar x; if( z[0]=='?' ){ /* Wildcard of the form "?nnn". Convert "nnn" to an integer and ** use it as the variable number */ i64 i; int bOk = 0==sqlite3Atoi64(&z[1], &i, n-1, SQLITE_UTF8); x = (ynVar)i; testcase( i==0 ); testcase( i==1 ); testcase( i==db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER]-1 ); testcase( i==db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ); if( bOk==0 || i<1 || i>db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ){ sqlite3ErrorMsg(pParse, "variable number must be between ?1 and ?%d", db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER]); return; } if( i>pParse->nVar ){ pParse->nVar = (int)i; } }else{ /* Wildcards like ":aaa", "$aaa" or "@aaa". Reuse the same variable ** number as the prior appearance of the same name, or if the name ** has never appeared before, reuse the same variable number */ ynVar i; for(i=x=0; inzVar; i++){ if( pParse->azVar[i] && strcmp(pParse->azVar[i],z)==0 ){ x = (ynVar)i+1; break; } } if( x==0 ) x = (ynVar)(++pParse->nVar); } pExpr->iColumn = x; if( x>pParse->nzVar ){ char **a; a = sqlite3DbRealloc(db, pParse->azVar, x*sizeof(a[0])); if( a==0 ){ assert( db->mallocFailed ); /* Error reported through mallocFailed */ return; } pParse->azVar = a; memset(&a[pParse->nzVar], 0, (x-pParse->nzVar)*sizeof(a[0])); pParse->nzVar = x; } if( pParse->azVar[x-1]==0 ){ pParse->azVar[x-1] = sqlite3DbStrNDup(db, z, n); } } if( pParse->nVar>db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ){ sqlite3ErrorMsg(pParse, "too many SQL variables"); } } /* ** Recursively delete an expression tree. */ static SQLITE_NOINLINE void sqlite3ExprDeleteNN(sqlite3 *db, Expr *p){ assert( p!=0 ); /* Sanity check: Assert that the IntValue is non-negative if it exists */ assert( !ExprHasProperty(p, EP_IntValue) || p->u.iValue>=0 ); #ifdef SQLITE_DEBUG if( ExprHasProperty(p, EP_Leaf) && !ExprHasProperty(p, EP_TokenOnly) ){ assert( p->pLeft==0 ); assert( p->pRight==0 ); assert( p->x.pSelect==0 ); } #endif if( !ExprHasProperty(p, (EP_TokenOnly|EP_Leaf)) ){ /* The Expr.x union is never used at the same time as Expr.pRight */ assert( p->x.pList==0 || p->pRight==0 ); if( p->pLeft && p->op!=TK_SELECT_COLUMN ) sqlite3ExprDeleteNN(db, p->pLeft); sqlite3ExprDelete(db, p->pRight); if( ExprHasProperty(p, EP_xIsSelect) ){ sqlite3SelectDelete(db, p->x.pSelect); }else{ sqlite3ExprListDelete(db, p->x.pList); } } if( ExprHasProperty(p, EP_MemToken) ) sqlite3DbFree(db, p->u.zToken); if( !ExprHasProperty(p, EP_Static) ){ sqlite3DbFree(db, p); } } SQLITE_PRIVATE void sqlite3ExprDelete(sqlite3 *db, Expr *p){ if( p ) sqlite3ExprDeleteNN(db, p); } /* ** Return the number of bytes allocated for the expression structure ** passed as the first argument. This is always one of EXPR_FULLSIZE, ** EXPR_REDUCEDSIZE or EXPR_TOKENONLYSIZE. */ static int exprStructSize(Expr *p){ if( ExprHasProperty(p, EP_TokenOnly) ) return EXPR_TOKENONLYSIZE; if( ExprHasProperty(p, EP_Reduced) ) return EXPR_REDUCEDSIZE; return EXPR_FULLSIZE; } /* ** The dupedExpr*Size() routines each return the number of bytes required ** to store a copy of an expression or expression tree. They differ in ** how much of the tree is measured. ** ** dupedExprStructSize() Size of only the Expr structure ** dupedExprNodeSize() Size of Expr + space for token ** dupedExprSize() Expr + token + subtree components ** *************************************************************************** ** ** The dupedExprStructSize() function returns two values OR-ed together: ** (1) the space required for a copy of the Expr structure only and ** (2) the EP_xxx flags that indicate what the structure size should be. ** The return values is always one of: ** ** EXPR_FULLSIZE ** EXPR_REDUCEDSIZE | EP_Reduced ** EXPR_TOKENONLYSIZE | EP_TokenOnly ** ** The size of the structure can be found by masking the return value ** of this routine with 0xfff. The flags can be found by masking the ** return value with EP_Reduced|EP_TokenOnly. ** ** Note that with flags==EXPRDUP_REDUCE, this routines works on full-size ** (unreduced) Expr objects as they or originally constructed by the parser. ** During expression analysis, extra information is computed and moved into ** later parts of teh Expr object and that extra information might get chopped ** off if the expression is reduced. Note also that it does not work to ** make an EXPRDUP_REDUCE copy of a reduced expression. It is only legal ** to reduce a pristine expression tree from the parser. The implementation ** of dupedExprStructSize() contain multiple assert() statements that attempt ** to enforce this constraint. */ static int dupedExprStructSize(Expr *p, int flags){ int nSize; assert( flags==EXPRDUP_REDUCE || flags==0 ); /* Only one flag value allowed */ assert( EXPR_FULLSIZE<=0xfff ); assert( (0xfff & (EP_Reduced|EP_TokenOnly))==0 ); if( 0==flags ){ nSize = EXPR_FULLSIZE; }else{ assert( !ExprHasProperty(p, EP_TokenOnly|EP_Reduced) ); assert( !ExprHasProperty(p, EP_FromJoin) ); assert( !ExprHasProperty(p, EP_MemToken) ); assert( !ExprHasProperty(p, EP_NoReduce) ); if( p->pLeft || p->x.pList ){ nSize = EXPR_REDUCEDSIZE | EP_Reduced; }else{ assert( p->pRight==0 ); nSize = EXPR_TOKENONLYSIZE | EP_TokenOnly; } } return nSize; } /* ** This function returns the space in bytes required to store the copy ** of the Expr structure and a copy of the Expr.u.zToken string (if that ** string is defined.) */ static int dupedExprNodeSize(Expr *p, int flags){ int nByte = dupedExprStructSize(p, flags) & 0xfff; if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){ nByte += sqlite3Strlen30(p->u.zToken)+1; } return ROUND8(nByte); } /* ** Return the number of bytes required to create a duplicate of the ** expression passed as the first argument. The second argument is a ** mask containing EXPRDUP_XXX flags. ** ** The value returned includes space to create a copy of the Expr struct ** itself and the buffer referred to by Expr.u.zToken, if any. ** ** If the EXPRDUP_REDUCE flag is set, then the return value includes ** space to duplicate all Expr nodes in the tree formed by Expr.pLeft ** and Expr.pRight variables (but not for any structures pointed to or ** descended from the Expr.x.pList or Expr.x.pSelect variables). */ static int dupedExprSize(Expr *p, int flags){ int nByte = 0; if( p ){ nByte = dupedExprNodeSize(p, flags); if( flags&EXPRDUP_REDUCE ){ nByte += dupedExprSize(p->pLeft, flags) + dupedExprSize(p->pRight, flags); } } return nByte; } /* ** This function is similar to sqlite3ExprDup(), except that if pzBuffer ** is not NULL then *pzBuffer is assumed to point to a buffer large enough ** to store the copy of expression p, the copies of p->u.zToken ** (if applicable), and the copies of the p->pLeft and p->pRight expressions, ** if any. Before returning, *pzBuffer is set to the first byte past the ** portion of the buffer copied into by this function. */ static Expr *exprDup(sqlite3 *db, Expr *p, int dupFlags, u8 **pzBuffer){ Expr *pNew; /* Value to return */ u8 *zAlloc; /* Memory space from which to build Expr object */ u32 staticFlag; /* EP_Static if space not obtained from malloc */ assert( db!=0 ); assert( p ); assert( dupFlags==0 || dupFlags==EXPRDUP_REDUCE ); assert( pzBuffer==0 || dupFlags==EXPRDUP_REDUCE ); /* Figure out where to write the new Expr structure. */ if( pzBuffer ){ zAlloc = *pzBuffer; staticFlag = EP_Static; }else{ zAlloc = sqlite3DbMallocRawNN(db, dupedExprSize(p, dupFlags)); staticFlag = 0; } pNew = (Expr *)zAlloc; if( pNew ){ /* Set nNewSize to the size allocated for the structure pointed to ** by pNew. This is either EXPR_FULLSIZE, EXPR_REDUCEDSIZE or ** EXPR_TOKENONLYSIZE. nToken is set to the number of bytes consumed ** by the copy of the p->u.zToken string (if any). */ const unsigned nStructSize = dupedExprStructSize(p, dupFlags); const int nNewSize = nStructSize & 0xfff; int nToken; if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){ nToken = sqlite3Strlen30(p->u.zToken) + 1; }else{ nToken = 0; } if( dupFlags ){ assert( ExprHasProperty(p, EP_Reduced)==0 ); memcpy(zAlloc, p, nNewSize); }else{ u32 nSize = (u32)exprStructSize(p); memcpy(zAlloc, p, nSize); if( nSizeflags &= ~(EP_Reduced|EP_TokenOnly|EP_Static|EP_MemToken); pNew->flags |= nStructSize & (EP_Reduced|EP_TokenOnly); pNew->flags |= staticFlag; /* Copy the p->u.zToken string, if any. */ if( nToken ){ char *zToken = pNew->u.zToken = (char*)&zAlloc[nNewSize]; memcpy(zToken, p->u.zToken, nToken); } if( 0==((p->flags|pNew->flags) & (EP_TokenOnly|EP_Leaf)) ){ /* Fill in the pNew->x.pSelect or pNew->x.pList member. */ if( ExprHasProperty(p, EP_xIsSelect) ){ pNew->x.pSelect = sqlite3SelectDup(db, p->x.pSelect, dupFlags); }else{ pNew->x.pList = sqlite3ExprListDup(db, p->x.pList, dupFlags); } } /* Fill in pNew->pLeft and pNew->pRight. */ if( ExprHasProperty(pNew, EP_Reduced|EP_TokenOnly) ){ zAlloc += dupedExprNodeSize(p, dupFlags); if( !ExprHasProperty(pNew, EP_TokenOnly|EP_Leaf) ){ pNew->pLeft = p->pLeft ? exprDup(db, p->pLeft, EXPRDUP_REDUCE, &zAlloc) : 0; pNew->pRight = p->pRight ? exprDup(db, p->pRight, EXPRDUP_REDUCE, &zAlloc) : 0; } if( pzBuffer ){ *pzBuffer = zAlloc; } }else{ if( !ExprHasProperty(p, EP_TokenOnly|EP_Leaf) ){ if( pNew->op==TK_SELECT_COLUMN ){ pNew->pLeft = p->pLeft; }else{ pNew->pLeft = sqlite3ExprDup(db, p->pLeft, 0); } pNew->pRight = sqlite3ExprDup(db, p->pRight, 0); } } } return pNew; } /* ** Create and return a deep copy of the object passed as the second ** argument. If an OOM condition is encountered, NULL is returned ** and the db->mallocFailed flag set. */ #ifndef SQLITE_OMIT_CTE static With *withDup(sqlite3 *db, With *p){ With *pRet = 0; if( p ){ int nByte = sizeof(*p) + sizeof(p->a[0]) * (p->nCte-1); pRet = sqlite3DbMallocZero(db, nByte); if( pRet ){ int i; pRet->nCte = p->nCte; for(i=0; inCte; i++){ pRet->a[i].pSelect = sqlite3SelectDup(db, p->a[i].pSelect, 0); pRet->a[i].pCols = sqlite3ExprListDup(db, p->a[i].pCols, 0); pRet->a[i].zName = sqlite3DbStrDup(db, p->a[i].zName); } } } return pRet; } #else # define withDup(x,y) 0 #endif /* ** The following group of routines make deep copies of expressions, ** expression lists, ID lists, and select statements. The copies can ** be deleted (by being passed to their respective ...Delete() routines) ** without effecting the originals. ** ** The expression list, ID, and source lists return by sqlite3ExprListDup(), ** sqlite3IdListDup(), and sqlite3SrcListDup() can not be further expanded ** by subsequent calls to sqlite*ListAppend() routines. ** ** Any tables that the SrcList might point to are not duplicated. ** ** The flags parameter contains a combination of the EXPRDUP_XXX flags. ** If the EXPRDUP_REDUCE flag is set, then the structure returned is a ** truncated version of the usual Expr structure that will be stored as ** part of the in-memory representation of the database schema. */ SQLITE_PRIVATE Expr *sqlite3ExprDup(sqlite3 *db, Expr *p, int flags){ assert( flags==0 || flags==EXPRDUP_REDUCE ); return p ? exprDup(db, p, flags, 0) : 0; } SQLITE_PRIVATE ExprList *sqlite3ExprListDup(sqlite3 *db, ExprList *p, int flags){ ExprList *pNew; struct ExprList_item *pItem, *pOldItem; int i; assert( db!=0 ); if( p==0 ) return 0; pNew = sqlite3DbMallocRawNN(db, sizeof(*pNew) ); if( pNew==0 ) return 0; pNew->nExpr = i = p->nExpr; if( (flags & EXPRDUP_REDUCE)==0 ) for(i=1; inExpr; i+=i){} pNew->a = pItem = sqlite3DbMallocRawNN(db, i*sizeof(p->a[0]) ); if( pItem==0 ){ sqlite3DbFree(db, pNew); return 0; } pOldItem = p->a; for(i=0; inExpr; i++, pItem++, pOldItem++){ Expr *pOldExpr = pOldItem->pExpr; pItem->pExpr = sqlite3ExprDup(db, pOldExpr, flags); pItem->zName = sqlite3DbStrDup(db, pOldItem->zName); pItem->zSpan = sqlite3DbStrDup(db, pOldItem->zSpan); pItem->sortOrder = pOldItem->sortOrder; pItem->done = 0; pItem->bSpanIsTab = pOldItem->bSpanIsTab; pItem->u = pOldItem->u; } return pNew; } /* ** If cursors, triggers, views and subqueries are all omitted from ** the build, then none of the following routines, except for ** sqlite3SelectDup(), can be called. sqlite3SelectDup() is sometimes ** called with a NULL argument. */ #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER) \ || !defined(SQLITE_OMIT_SUBQUERY) SQLITE_PRIVATE SrcList *sqlite3SrcListDup(sqlite3 *db, SrcList *p, int flags){ SrcList *pNew; int i; int nByte; assert( db!=0 ); if( p==0 ) return 0; nByte = sizeof(*p) + (p->nSrc>0 ? sizeof(p->a[0]) * (p->nSrc-1) : 0); pNew = sqlite3DbMallocRawNN(db, nByte ); if( pNew==0 ) return 0; pNew->nSrc = pNew->nAlloc = p->nSrc; for(i=0; inSrc; i++){ struct SrcList_item *pNewItem = &pNew->a[i]; struct SrcList_item *pOldItem = &p->a[i]; Table *pTab; pNewItem->pSchema = pOldItem->pSchema; pNewItem->zDatabase = sqlite3DbStrDup(db, pOldItem->zDatabase); pNewItem->zName = sqlite3DbStrDup(db, pOldItem->zName); pNewItem->zAlias = sqlite3DbStrDup(db, pOldItem->zAlias); pNewItem->fg = pOldItem->fg; pNewItem->iCursor = pOldItem->iCursor; pNewItem->addrFillSub = pOldItem->addrFillSub; pNewItem->regReturn = pOldItem->regReturn; if( pNewItem->fg.isIndexedBy ){ pNewItem->u1.zIndexedBy = sqlite3DbStrDup(db, pOldItem->u1.zIndexedBy); } pNewItem->pIBIndex = pOldItem->pIBIndex; if( pNewItem->fg.isTabFunc ){ pNewItem->u1.pFuncArg = sqlite3ExprListDup(db, pOldItem->u1.pFuncArg, flags); } pTab = pNewItem->pTab = pOldItem->pTab; if( pTab ){ pTab->nRef++; } pNewItem->pSelect = sqlite3SelectDup(db, pOldItem->pSelect, flags); pNewItem->pOn = sqlite3ExprDup(db, pOldItem->pOn, flags); pNewItem->pUsing = sqlite3IdListDup(db, pOldItem->pUsing); pNewItem->colUsed = pOldItem->colUsed; } return pNew; } SQLITE_PRIVATE IdList *sqlite3IdListDup(sqlite3 *db, IdList *p){ IdList *pNew; int i; assert( db!=0 ); if( p==0 ) return 0; pNew = sqlite3DbMallocRawNN(db, sizeof(*pNew) ); if( pNew==0 ) return 0; pNew->nId = p->nId; pNew->a = sqlite3DbMallocRawNN(db, p->nId*sizeof(p->a[0]) ); if( pNew->a==0 ){ sqlite3DbFree(db, pNew); return 0; } /* Note that because the size of the allocation for p->a[] is not ** necessarily a power of two, sqlite3IdListAppend() may not be called ** on the duplicate created by this function. */ for(i=0; inId; i++){ struct IdList_item *pNewItem = &pNew->a[i]; struct IdList_item *pOldItem = &p->a[i]; pNewItem->zName = sqlite3DbStrDup(db, pOldItem->zName); pNewItem->idx = pOldItem->idx; } return pNew; } SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3 *db, Select *p, int flags){ Select *pNew, *pPrior; assert( db!=0 ); if( p==0 ) return 0; pNew = sqlite3DbMallocRawNN(db, sizeof(*p) ); if( pNew==0 ) return 0; pNew->pEList = sqlite3ExprListDup(db, p->pEList, flags); pNew->pSrc = sqlite3SrcListDup(db, p->pSrc, flags); pNew->pWhere = sqlite3ExprDup(db, p->pWhere, flags); pNew->pGroupBy = sqlite3ExprListDup(db, p->pGroupBy, flags); pNew->pHaving = sqlite3ExprDup(db, p->pHaving, flags); pNew->pOrderBy = sqlite3ExprListDup(db, p->pOrderBy, flags); pNew->op = p->op; pNew->pPrior = pPrior = sqlite3SelectDup(db, p->pPrior, flags); if( pPrior ) pPrior->pNext = pNew; pNew->pNext = 0; pNew->pLimit = sqlite3ExprDup(db, p->pLimit, flags); pNew->pOffset = sqlite3ExprDup(db, p->pOffset, flags); pNew->iLimit = 0; pNew->iOffset = 0; pNew->selFlags = p->selFlags & ~SF_UsesEphemeral; pNew->addrOpenEphm[0] = -1; pNew->addrOpenEphm[1] = -1; pNew->nSelectRow = p->nSelectRow; pNew->pWith = withDup(db, p->pWith); sqlite3SelectSetName(pNew, p->zSelName); return pNew; } #else SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3 *db, Select *p, int flags){ assert( p==0 ); return 0; } #endif /* ** Add a new element to the end of an expression list. If pList is ** initially NULL, then create a new expression list. ** ** If a memory allocation error occurs, the entire list is freed and ** NULL is returned. If non-NULL is returned, then it is guaranteed ** that the new entry was successfully appended. */ SQLITE_PRIVATE ExprList *sqlite3ExprListAppend( Parse *pParse, /* Parsing context */ ExprList *pList, /* List to which to append. Might be NULL */ Expr *pExpr /* Expression to be appended. Might be NULL */ ){ sqlite3 *db = pParse->db; assert( db!=0 ); if( pList==0 ){ pList = sqlite3DbMallocRawNN(db, sizeof(ExprList) ); if( pList==0 ){ goto no_mem; } pList->nExpr = 0; pList->a = sqlite3DbMallocRawNN(db, sizeof(pList->a[0])); if( pList->a==0 ) goto no_mem; }else if( (pList->nExpr & (pList->nExpr-1))==0 ){ struct ExprList_item *a; assert( pList->nExpr>0 ); a = sqlite3DbRealloc(db, pList->a, pList->nExpr*2*sizeof(pList->a[0])); if( a==0 ){ goto no_mem; } pList->a = a; } assert( pList->a!=0 ); if( 1 ){ struct ExprList_item *pItem = &pList->a[pList->nExpr++]; memset(pItem, 0, sizeof(*pItem)); pItem->pExpr = pExpr; } return pList; no_mem: /* Avoid leaking memory if malloc has failed. */ sqlite3ExprDelete(db, pExpr); sqlite3ExprListDelete(db, pList); return 0; } /* ** pColumns and pExpr form a vector assignment which is part of the SET ** clause of an UPDATE statement. Like this: ** ** (a,b,c) = (expr1,expr2,expr3) ** Or: (a,b,c) = (SELECT x,y,z FROM ....) ** ** For each term of the vector assignment, append new entries to the ** expression list pList. In the case of a subquery on the LHS, append ** TK_SELECT_COLUMN expressions. */ SQLITE_PRIVATE ExprList *sqlite3ExprListAppendVector( Parse *pParse, /* Parsing context */ ExprList *pList, /* List to which to append. Might be NULL */ IdList *pColumns, /* List of names of LHS of the assignment */ Expr *pExpr /* Vector expression to be appended. Might be NULL */ ){ sqlite3 *db = pParse->db; int n; int i; int iFirst = pList ? pList->nExpr : 0; /* pColumns can only be NULL due to an OOM but an OOM will cause an ** exit prior to this routine being invoked */ if( NEVER(pColumns==0) ) goto vector_append_error; if( pExpr==0 ) goto vector_append_error; n = sqlite3ExprVectorSize(pExpr); if( pColumns->nId!=n ){ sqlite3ErrorMsg(pParse, "%d columns assigned %d values", pColumns->nId, n); goto vector_append_error; } for(i=0; inExpr==iFirst+i+1 ); pList->a[pList->nExpr-1].zName = pColumns->a[i].zName; pColumns->a[i].zName = 0; } } if( pExpr->op==TK_SELECT ){ if( pList && pList->a[iFirst].pExpr ){ assert( pList->a[iFirst].pExpr->op==TK_SELECT_COLUMN ); pList->a[iFirst].pExpr->pRight = pExpr; pExpr = 0; } } vector_append_error: sqlite3ExprDelete(db, pExpr); sqlite3IdListDelete(db, pColumns); return pList; } /* ** Set the sort order for the last element on the given ExprList. */ SQLITE_PRIVATE void sqlite3ExprListSetSortOrder(ExprList *p, int iSortOrder){ if( p==0 ) return; assert( SQLITE_SO_UNDEFINED<0 && SQLITE_SO_ASC>=0 && SQLITE_SO_DESC>0 ); assert( p->nExpr>0 ); if( iSortOrder<0 ){ assert( p->a[p->nExpr-1].sortOrder==SQLITE_SO_ASC ); return; } p->a[p->nExpr-1].sortOrder = (u8)iSortOrder; } /* ** Set the ExprList.a[].zName element of the most recently added item ** on the expression list. ** ** pList might be NULL following an OOM error. But pName should never be ** NULL. If a memory allocation fails, the pParse->db->mallocFailed flag ** is set. */ SQLITE_PRIVATE void sqlite3ExprListSetName( Parse *pParse, /* Parsing context */ ExprList *pList, /* List to which to add the span. */ Token *pName, /* Name to be added */ int dequote /* True to cause the name to be dequoted */ ){ assert( pList!=0 || pParse->db->mallocFailed!=0 ); if( pList ){ struct ExprList_item *pItem; assert( pList->nExpr>0 ); pItem = &pList->a[pList->nExpr-1]; assert( pItem->zName==0 ); pItem->zName = sqlite3DbStrNDup(pParse->db, pName->z, pName->n); if( dequote ) sqlite3Dequote(pItem->zName); } } /* ** Set the ExprList.a[].zSpan element of the most recently added item ** on the expression list. ** ** pList might be NULL following an OOM error. But pSpan should never be ** NULL. If a memory allocation fails, the pParse->db->mallocFailed flag ** is set. */ SQLITE_PRIVATE void sqlite3ExprListSetSpan( Parse *pParse, /* Parsing context */ ExprList *pList, /* List to which to add the span. */ ExprSpan *pSpan /* The span to be added */ ){ sqlite3 *db = pParse->db; assert( pList!=0 || db->mallocFailed!=0 ); if( pList ){ struct ExprList_item *pItem = &pList->a[pList->nExpr-1]; assert( pList->nExpr>0 ); assert( db->mallocFailed || pItem->pExpr==pSpan->pExpr ); sqlite3DbFree(db, pItem->zSpan); pItem->zSpan = sqlite3DbStrNDup(db, (char*)pSpan->zStart, (int)(pSpan->zEnd - pSpan->zStart)); } } /* ** If the expression list pEList contains more than iLimit elements, ** leave an error message in pParse. */ SQLITE_PRIVATE void sqlite3ExprListCheckLength( Parse *pParse, ExprList *pEList, const char *zObject ){ int mx = pParse->db->aLimit[SQLITE_LIMIT_COLUMN]; testcase( pEList && pEList->nExpr==mx ); testcase( pEList && pEList->nExpr==mx+1 ); if( pEList && pEList->nExpr>mx ){ sqlite3ErrorMsg(pParse, "too many columns in %s", zObject); } } /* ** Delete an entire expression list. */ static SQLITE_NOINLINE void exprListDeleteNN(sqlite3 *db, ExprList *pList){ int i; struct ExprList_item *pItem; assert( pList->a!=0 || pList->nExpr==0 ); for(pItem=pList->a, i=0; inExpr; i++, pItem++){ sqlite3ExprDelete(db, pItem->pExpr); sqlite3DbFree(db, pItem->zName); sqlite3DbFree(db, pItem->zSpan); } sqlite3DbFree(db, pList->a); sqlite3DbFree(db, pList); } SQLITE_PRIVATE void sqlite3ExprListDelete(sqlite3 *db, ExprList *pList){ if( pList ) exprListDeleteNN(db, pList); } /* ** Return the bitwise-OR of all Expr.flags fields in the given ** ExprList. */ SQLITE_PRIVATE u32 sqlite3ExprListFlags(const ExprList *pList){ int i; u32 m = 0; if( pList ){ for(i=0; inExpr; i++){ Expr *pExpr = pList->a[i].pExpr; assert( pExpr!=0 ); m |= pExpr->flags; } } return m; } /* ** These routines are Walker callbacks used to check expressions to ** see if they are "constant" for some definition of constant. The ** Walker.eCode value determines the type of "constant" we are looking ** for. ** ** These callback routines are used to implement the following: ** ** sqlite3ExprIsConstant() pWalker->eCode==1 ** sqlite3ExprIsConstantNotJoin() pWalker->eCode==2 ** sqlite3ExprIsTableConstant() pWalker->eCode==3 ** sqlite3ExprIsConstantOrFunction() pWalker->eCode==4 or 5 ** ** In all cases, the callbacks set Walker.eCode=0 and abort if the expression ** is found to not be a constant. ** ** The sqlite3ExprIsConstantOrFunction() is used for evaluating expressions ** in a CREATE TABLE statement. The Walker.eCode value is 5 when parsing ** an existing schema and 4 when processing a new statement. A bound ** parameter raises an error for new statements, but is silently converted ** to NULL for existing schemas. This allows sqlite_master tables that ** contain a bound parameter because they were generated by older versions ** of SQLite to be parsed by newer versions of SQLite without raising a ** malformed schema error. */ static int exprNodeIsConstant(Walker *pWalker, Expr *pExpr){ /* If pWalker->eCode is 2 then any term of the expression that comes from ** the ON or USING clauses of a left join disqualifies the expression ** from being considered constant. */ if( pWalker->eCode==2 && ExprHasProperty(pExpr, EP_FromJoin) ){ pWalker->eCode = 0; return WRC_Abort; } switch( pExpr->op ){ /* Consider functions to be constant if all their arguments are constant ** and either pWalker->eCode==4 or 5 or the function has the ** SQLITE_FUNC_CONST flag. */ case TK_FUNCTION: if( pWalker->eCode>=4 || ExprHasProperty(pExpr,EP_ConstFunc) ){ return WRC_Continue; }else{ pWalker->eCode = 0; return WRC_Abort; } case TK_ID: case TK_COLUMN: case TK_AGG_FUNCTION: case TK_AGG_COLUMN: testcase( pExpr->op==TK_ID ); testcase( pExpr->op==TK_COLUMN ); testcase( pExpr->op==TK_AGG_FUNCTION ); testcase( pExpr->op==TK_AGG_COLUMN ); if( pWalker->eCode==3 && pExpr->iTable==pWalker->u.iCur ){ return WRC_Continue; }else{ pWalker->eCode = 0; return WRC_Abort; } case TK_VARIABLE: if( pWalker->eCode==5 ){ /* Silently convert bound parameters that appear inside of CREATE ** statements into a NULL when parsing the CREATE statement text out ** of the sqlite_master table */ pExpr->op = TK_NULL; }else if( pWalker->eCode==4 ){ /* A bound parameter in a CREATE statement that originates from ** sqlite3_prepare() causes an error */ pWalker->eCode = 0; return WRC_Abort; } /* Fall through */ default: testcase( pExpr->op==TK_SELECT ); /* selectNodeIsConstant will disallow */ testcase( pExpr->op==TK_EXISTS ); /* selectNodeIsConstant will disallow */ return WRC_Continue; } } static int selectNodeIsConstant(Walker *pWalker, Select *NotUsed){ UNUSED_PARAMETER(NotUsed); pWalker->eCode = 0; return WRC_Abort; } static int exprIsConst(Expr *p, int initFlag, int iCur){ Walker w; memset(&w, 0, sizeof(w)); w.eCode = initFlag; w.xExprCallback = exprNodeIsConstant; w.xSelectCallback = selectNodeIsConstant; w.u.iCur = iCur; sqlite3WalkExpr(&w, p); return w.eCode; } /* ** Walk an expression tree. Return non-zero if the expression is constant ** and 0 if it involves variables or function calls. ** ** For the purposes of this function, a double-quoted string (ex: "abc") ** is considered a variable but a single-quoted string (ex: 'abc') is ** a constant. */ SQLITE_PRIVATE int sqlite3ExprIsConstant(Expr *p){ return exprIsConst(p, 1, 0); } /* ** Walk an expression tree. Return non-zero if the expression is constant ** that does no originate from the ON or USING clauses of a join. ** Return 0 if it involves variables or function calls or terms from ** an ON or USING clause. */ SQLITE_PRIVATE int sqlite3ExprIsConstantNotJoin(Expr *p){ return exprIsConst(p, 2, 0); } /* ** Walk an expression tree. Return non-zero if the expression is constant ** for any single row of the table with cursor iCur. In other words, the ** expression must not refer to any non-deterministic function nor any ** table other than iCur. */ SQLITE_PRIVATE int sqlite3ExprIsTableConstant(Expr *p, int iCur){ return exprIsConst(p, 3, iCur); } /* ** Walk an expression tree. Return non-zero if the expression is constant ** or a function call with constant arguments. Return and 0 if there ** are any variables. ** ** For the purposes of this function, a double-quoted string (ex: "abc") ** is considered a variable but a single-quoted string (ex: 'abc') is ** a constant. */ SQLITE_PRIVATE int sqlite3ExprIsConstantOrFunction(Expr *p, u8 isInit){ assert( isInit==0 || isInit==1 ); return exprIsConst(p, 4+isInit, 0); } #ifdef SQLITE_ENABLE_CURSOR_HINTS /* ** Walk an expression tree. Return 1 if the expression contains a ** subquery of some kind. Return 0 if there are no subqueries. */ SQLITE_PRIVATE int sqlite3ExprContainsSubquery(Expr *p){ Walker w; memset(&w, 0, sizeof(w)); w.eCode = 1; w.xExprCallback = sqlite3ExprWalkNoop; w.xSelectCallback = selectNodeIsConstant; sqlite3WalkExpr(&w, p); return w.eCode==0; } #endif /* ** If the expression p codes a constant integer that is small enough ** to fit in a 32-bit integer, return 1 and put the value of the integer ** in *pValue. If the expression is not an integer or if it is too big ** to fit in a signed 32-bit integer, return 0 and leave *pValue unchanged. */ SQLITE_PRIVATE int sqlite3ExprIsInteger(Expr *p, int *pValue){ int rc = 0; /* If an expression is an integer literal that fits in a signed 32-bit ** integer, then the EP_IntValue flag will have already been set */ assert( p->op!=TK_INTEGER || (p->flags & EP_IntValue)!=0 || sqlite3GetInt32(p->u.zToken, &rc)==0 ); if( p->flags & EP_IntValue ){ *pValue = p->u.iValue; return 1; } switch( p->op ){ case TK_UPLUS: { rc = sqlite3ExprIsInteger(p->pLeft, pValue); break; } case TK_UMINUS: { int v; if( sqlite3ExprIsInteger(p->pLeft, &v) ){ assert( v!=(-2147483647-1) ); *pValue = -v; rc = 1; } break; } default: break; } return rc; } /* ** Return FALSE if there is no chance that the expression can be NULL. ** ** If the expression might be NULL or if the expression is too complex ** to tell return TRUE. ** ** This routine is used as an optimization, to skip OP_IsNull opcodes ** when we know that a value cannot be NULL. Hence, a false positive ** (returning TRUE when in fact the expression can never be NULL) might ** be a small performance hit but is otherwise harmless. On the other ** hand, a false negative (returning FALSE when the result could be NULL) ** will likely result in an incorrect answer. So when in doubt, return ** TRUE. */ SQLITE_PRIVATE int sqlite3ExprCanBeNull(const Expr *p){ u8 op; while( p->op==TK_UPLUS || p->op==TK_UMINUS ){ p = p->pLeft; } op = p->op; if( op==TK_REGISTER ) op = p->op2; switch( op ){ case TK_INTEGER: case TK_STRING: case TK_FLOAT: case TK_BLOB: return 0; case TK_COLUMN: assert( p->pTab!=0 ); return ExprHasProperty(p, EP_CanBeNull) || (p->iColumn>=0 && p->pTab->aCol[p->iColumn].notNull==0); default: return 1; } } /* ** Return TRUE if the given expression is a constant which would be ** unchanged by OP_Affinity with the affinity given in the second ** argument. ** ** This routine is used to determine if the OP_Affinity operation ** can be omitted. When in doubt return FALSE. A false negative ** is harmless. A false positive, however, can result in the wrong ** answer. */ SQLITE_PRIVATE int sqlite3ExprNeedsNoAffinityChange(const Expr *p, char aff){ u8 op; if( aff==SQLITE_AFF_BLOB ) return 1; while( p->op==TK_UPLUS || p->op==TK_UMINUS ){ p = p->pLeft; } op = p->op; if( op==TK_REGISTER ) op = p->op2; switch( op ){ case TK_INTEGER: { return aff==SQLITE_AFF_INTEGER || aff==SQLITE_AFF_NUMERIC; } case TK_FLOAT: { return aff==SQLITE_AFF_REAL || aff==SQLITE_AFF_NUMERIC; } case TK_STRING: { return aff==SQLITE_AFF_TEXT; } case TK_BLOB: { return 1; } case TK_COLUMN: { assert( p->iTable>=0 ); /* p cannot be part of a CHECK constraint */ return p->iColumn<0 && (aff==SQLITE_AFF_INTEGER || aff==SQLITE_AFF_NUMERIC); } default: { return 0; } } } /* ** Return TRUE if the given string is a row-id column name. */ SQLITE_PRIVATE int sqlite3IsRowid(const char *z){ if( sqlite3StrICmp(z, "_ROWID_")==0 ) return 1; if( sqlite3StrICmp(z, "ROWID")==0 ) return 1; if( sqlite3StrICmp(z, "OID")==0 ) return 1; return 0; } /* ** pX is the RHS of an IN operator. If pX is a SELECT statement ** that can be simplified to a direct table access, then return ** a pointer to the SELECT statement. If pX is not a SELECT statement, ** or if the SELECT statement needs to be manifested into a transient ** table, then return NULL. */ #ifndef SQLITE_OMIT_SUBQUERY static Select *isCandidateForInOpt(Expr *pX){ Select *p; SrcList *pSrc; ExprList *pEList; Table *pTab; int i; if( !ExprHasProperty(pX, EP_xIsSelect) ) return 0; /* Not a subquery */ if( ExprHasProperty(pX, EP_VarSelect) ) return 0; /* Correlated subq */ p = pX->x.pSelect; if( p->pPrior ) return 0; /* Not a compound SELECT */ if( p->selFlags & (SF_Distinct|SF_Aggregate) ){ testcase( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct ); testcase( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Aggregate ); return 0; /* No DISTINCT keyword and no aggregate functions */ } assert( p->pGroupBy==0 ); /* Has no GROUP BY clause */ if( p->pLimit ) return 0; /* Has no LIMIT clause */ assert( p->pOffset==0 ); /* No LIMIT means no OFFSET */ if( p->pWhere ) return 0; /* Has no WHERE clause */ pSrc = p->pSrc; assert( pSrc!=0 ); if( pSrc->nSrc!=1 ) return 0; /* Single term in FROM clause */ if( pSrc->a[0].pSelect ) return 0; /* FROM is not a subquery or view */ pTab = pSrc->a[0].pTab; assert( pTab!=0 ); assert( pTab->pSelect==0 ); /* FROM clause is not a view */ if( IsVirtual(pTab) ) return 0; /* FROM clause not a virtual table */ pEList = p->pEList; assert( pEList!=0 ); /* All SELECT results must be columns. */ for(i=0; inExpr; i++){ Expr *pRes = pEList->a[i].pExpr; if( pRes->op!=TK_COLUMN ) return 0; assert( pRes->iTable==pSrc->a[0].iCursor ); /* Not a correlated subquery */ } return p; } #endif /* SQLITE_OMIT_SUBQUERY */ #ifndef SQLITE_OMIT_SUBQUERY /* ** Generate code that checks the left-most column of index table iCur to see if ** it contains any NULL entries. Cause the register at regHasNull to be set ** to a non-NULL value if iCur contains no NULLs. Cause register regHasNull ** to be set to NULL if iCur contains one or more NULL values. */ static void sqlite3SetHasNullFlag(Vdbe *v, int iCur, int regHasNull){ int addr1; sqlite3VdbeAddOp2(v, OP_Integer, 0, regHasNull); addr1 = sqlite3VdbeAddOp1(v, OP_Rewind, iCur); VdbeCoverage(v); sqlite3VdbeAddOp3(v, OP_Column, iCur, 0, regHasNull); sqlite3VdbeChangeP5(v, OPFLAG_TYPEOFARG); VdbeComment((v, "first_entry_in(%d)", iCur)); sqlite3VdbeJumpHere(v, addr1); } #endif #ifndef SQLITE_OMIT_SUBQUERY /* ** The argument is an IN operator with a list (not a subquery) on the ** right-hand side. Return TRUE if that list is constant. */ static int sqlite3InRhsIsConstant(Expr *pIn){ Expr *pLHS; int res; assert( !ExprHasProperty(pIn, EP_xIsSelect) ); pLHS = pIn->pLeft; pIn->pLeft = 0; res = sqlite3ExprIsConstant(pIn); pIn->pLeft = pLHS; return res; } #endif /* ** This function is used by the implementation of the IN (...) operator. ** The pX parameter is the expression on the RHS of the IN operator, which ** might be either a list of expressions or a subquery. ** ** The job of this routine is to find or create a b-tree object that can ** be used either to test for membership in the RHS set or to iterate through ** all members of the RHS set, skipping duplicates. ** ** A cursor is opened on the b-tree object that is the RHS of the IN operator ** and pX->iTable is set to the index of that cursor. ** ** The returned value of this function indicates the b-tree type, as follows: ** ** IN_INDEX_ROWID - The cursor was opened on a database table. ** IN_INDEX_INDEX_ASC - The cursor was opened on an ascending index. ** IN_INDEX_INDEX_DESC - The cursor was opened on a descending index. ** IN_INDEX_EPH - The cursor was opened on a specially created and ** populated epheremal table. ** IN_INDEX_NOOP - No cursor was allocated. The IN operator must be ** implemented as a sequence of comparisons. ** ** An existing b-tree might be used if the RHS expression pX is a simple ** subquery such as: ** ** SELECT , ... FROM ** ** If the RHS of the IN operator is a list or a more complex subquery, then ** an ephemeral table might need to be generated from the RHS and then ** pX->iTable made to point to the ephemeral table instead of an ** existing table. ** ** The inFlags parameter must contain exactly one of the bits ** IN_INDEX_MEMBERSHIP or IN_INDEX_LOOP. If inFlags contains ** IN_INDEX_MEMBERSHIP, then the generated table will be used for a ** fast membership test. When the IN_INDEX_LOOP bit is set, the ** IN index will be used to loop over all values of the RHS of the ** IN operator. ** ** When IN_INDEX_LOOP is used (and the b-tree will be used to iterate ** through the set members) then the b-tree must not contain duplicates. ** An epheremal table must be used unless the selected columns are guaranteed ** to be unique - either because it is an INTEGER PRIMARY KEY or due to ** a UNIQUE constraint or index. ** ** When IN_INDEX_MEMBERSHIP is used (and the b-tree will be used ** for fast set membership tests) then an epheremal table must ** be used unless is a single INTEGER PRIMARY KEY column or an ** index can be found with the specified as its left-most. ** ** If the IN_INDEX_NOOP_OK and IN_INDEX_MEMBERSHIP are both set and ** if the RHS of the IN operator is a list (not a subquery) then this ** routine might decide that creating an ephemeral b-tree for membership ** testing is too expensive and return IN_INDEX_NOOP. In that case, the ** calling routine should implement the IN operator using a sequence ** of Eq or Ne comparison operations. ** ** When the b-tree is being used for membership tests, the calling function ** might need to know whether or not the RHS side of the IN operator ** contains a NULL. If prRhsHasNull is not a NULL pointer and ** if there is any chance that the (...) might contain a NULL value at ** runtime, then a register is allocated and the register number written ** to *prRhsHasNull. If there is no chance that the (...) contains a ** NULL value, then *prRhsHasNull is left unchanged. ** ** If a register is allocated and its location stored in *prRhsHasNull, then ** the value in that register will be NULL if the b-tree contains one or more ** NULL values, and it will be some non-NULL value if the b-tree contains no ** NULL values. ** ** If the aiMap parameter is not NULL, it must point to an array containing ** one element for each column returned by the SELECT statement on the RHS ** of the IN(...) operator. The i'th entry of the array is populated with the ** offset of the index column that matches the i'th column returned by the ** SELECT. For example, if the expression and selected index are: ** ** (?,?,?) IN (SELECT a, b, c FROM t1) ** CREATE INDEX i1 ON t1(b, c, a); ** ** then aiMap[] is populated with {2, 0, 1}. */ #ifndef SQLITE_OMIT_SUBQUERY SQLITE_PRIVATE int sqlite3FindInIndex( Parse *pParse, /* Parsing context */ Expr *pX, /* The right-hand side (RHS) of the IN operator */ u32 inFlags, /* IN_INDEX_LOOP, _MEMBERSHIP, and/or _NOOP_OK */ int *prRhsHasNull, /* Register holding NULL status. See notes */ int *aiMap /* Mapping from Index fields to RHS fields */ ){ Select *p; /* SELECT to the right of IN operator */ int eType = 0; /* Type of RHS table. IN_INDEX_* */ int iTab = pParse->nTab++; /* Cursor of the RHS table */ int mustBeUnique; /* True if RHS must be unique */ Vdbe *v = sqlite3GetVdbe(pParse); /* Virtual machine being coded */ assert( pX->op==TK_IN ); mustBeUnique = (inFlags & IN_INDEX_LOOP)!=0; /* If the RHS of this IN(...) operator is a SELECT, and if it matters ** whether or not the SELECT result contains NULL values, check whether ** or not NULL is actually possible (it may not be, for example, due ** to NOT NULL constraints in the schema). If no NULL values are possible, ** set prRhsHasNull to 0 before continuing. */ if( prRhsHasNull && (pX->flags & EP_xIsSelect) ){ int i; ExprList *pEList = pX->x.pSelect->pEList; for(i=0; inExpr; i++){ if( sqlite3ExprCanBeNull(pEList->a[i].pExpr) ) break; } if( i==pEList->nExpr ){ prRhsHasNull = 0; } } /* Check to see if an existing table or index can be used to ** satisfy the query. This is preferable to generating a new ** ephemeral table. */ if( pParse->nErr==0 && (p = isCandidateForInOpt(pX))!=0 ){ sqlite3 *db = pParse->db; /* Database connection */ Table *pTab; /* Table
    . */ i16 iDb; /* Database idx for pTab */ ExprList *pEList = p->pEList; int nExpr = pEList->nExpr; assert( p->pEList!=0 ); /* Because of isCandidateForInOpt(p) */ assert( p->pEList->a[0].pExpr!=0 ); /* Because of isCandidateForInOpt(p) */ assert( p->pSrc!=0 ); /* Because of isCandidateForInOpt(p) */ pTab = p->pSrc->a[0].pTab; /* Code an OP_Transaction and OP_TableLock for
    . */ iDb = sqlite3SchemaToIndex(db, pTab->pSchema); sqlite3CodeVerifySchema(pParse, iDb); sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName); assert(v); /* sqlite3GetVdbe() has always been previously called */ if( nExpr==1 && pEList->a[0].pExpr->iColumn<0 ){ /* The "x IN (SELECT rowid FROM table)" case */ int iAddr = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v); sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead); eType = IN_INDEX_ROWID; sqlite3VdbeJumpHere(v, iAddr); }else{ Index *pIdx; /* Iterator variable */ int affinity_ok = 1; int i; /* Check that the affinity that will be used to perform each ** comparison is the same as the affinity of each column in table ** on the RHS of the IN operator. If it not, it is not possible to ** use any index of the RHS table. */ for(i=0; ipLeft, i); int iCol = pEList->a[i].pExpr->iColumn; char idxaff = sqlite3TableColumnAffinity(pTab,iCol); /* RHS table */ char cmpaff = sqlite3CompareAffinity(pLhs, idxaff); testcase( cmpaff==SQLITE_AFF_BLOB ); testcase( cmpaff==SQLITE_AFF_TEXT ); switch( cmpaff ){ case SQLITE_AFF_BLOB: break; case SQLITE_AFF_TEXT: /* sqlite3CompareAffinity() only returns TEXT if one side or the ** other has no affinity and the other side is TEXT. Hence, ** the only way for cmpaff to be TEXT is for idxaff to be TEXT ** and for the term on the LHS of the IN to have no affinity. */ assert( idxaff==SQLITE_AFF_TEXT ); break; default: affinity_ok = sqlite3IsNumericAffinity(idxaff); } } if( affinity_ok ){ /* Search for an existing index that will work for this IN operator */ for(pIdx=pTab->pIndex; pIdx && eType==0; pIdx=pIdx->pNext){ Bitmask colUsed; /* Columns of the index used */ Bitmask mCol; /* Mask for the current column */ if( pIdx->nColumnnColumn==BMS-2 ); testcase( pIdx->nColumn==BMS-1 ); if( pIdx->nColumn>=BMS-1 ) continue; if( mustBeUnique ){ if( pIdx->nKeyCol>nExpr ||(pIdx->nColumn>nExpr && !IsUniqueIndex(pIdx)) ){ continue; /* This index is not unique over the IN RHS columns */ } } colUsed = 0; /* Columns of index used so far */ for(i=0; ipLeft, i); Expr *pRhs = pEList->a[i].pExpr; CollSeq *pReq = sqlite3BinaryCompareCollSeq(pParse, pLhs, pRhs); int j; assert( pReq!=0 || pRhs->iColumn==XN_ROWID || pParse->nErr ); for(j=0; jaiColumn[j]!=pRhs->iColumn ) continue; assert( pIdx->azColl[j] ); if( pReq!=0 && sqlite3StrICmp(pReq->zName, pIdx->azColl[j])!=0 ){ continue; } break; } if( j==nExpr ) break; mCol = MASKBIT(j); if( mCol & colUsed ) break; /* Each column used only once */ colUsed |= mCol; if( aiMap ) aiMap[i] = j; } assert( i==nExpr || colUsed!=(MASKBIT(nExpr)-1) ); if( colUsed==(MASKBIT(nExpr)-1) ){ /* If we reach this point, that means the index pIdx is usable */ int iAddr = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v); #ifndef SQLITE_OMIT_EXPLAIN sqlite3VdbeAddOp4(v, OP_Explain, 0, 0, 0, sqlite3MPrintf(db, "USING INDEX %s FOR IN-OPERATOR",pIdx->zName), P4_DYNAMIC); #endif sqlite3VdbeAddOp3(v, OP_OpenRead, iTab, pIdx->tnum, iDb); sqlite3VdbeSetP4KeyInfo(pParse, pIdx); VdbeComment((v, "%s", pIdx->zName)); assert( IN_INDEX_INDEX_DESC == IN_INDEX_INDEX_ASC+1 ); eType = IN_INDEX_INDEX_ASC + pIdx->aSortOrder[0]; if( prRhsHasNull ){ #ifdef SQLITE_ENABLE_COLUMN_USED_MASK i64 mask = (1<nMem; if( nExpr==1 ){ sqlite3SetHasNullFlag(v, iTab, *prRhsHasNull); } } sqlite3VdbeJumpHere(v, iAddr); } } /* End loop over indexes */ } /* End if( affinity_ok ) */ } /* End if not an rowid index */ } /* End attempt to optimize using an index */ /* If no preexisting index is available for the IN clause ** and IN_INDEX_NOOP is an allowed reply ** and the RHS of the IN operator is a list, not a subquery ** and the RHS is not constant or has two or fewer terms, ** then it is not worth creating an ephemeral table to evaluate ** the IN operator so return IN_INDEX_NOOP. */ if( eType==0 && (inFlags & IN_INDEX_NOOP_OK) && !ExprHasProperty(pX, EP_xIsSelect) && (!sqlite3InRhsIsConstant(pX) || pX->x.pList->nExpr<=2) ){ eType = IN_INDEX_NOOP; } if( eType==0 ){ /* Could not find an existing table or index to use as the RHS b-tree. ** We will have to generate an ephemeral table to do the job. */ u32 savedNQueryLoop = pParse->nQueryLoop; int rMayHaveNull = 0; eType = IN_INDEX_EPH; if( inFlags & IN_INDEX_LOOP ){ pParse->nQueryLoop = 0; if( pX->pLeft->iColumn<0 && !ExprHasProperty(pX, EP_xIsSelect) ){ eType = IN_INDEX_ROWID; } }else if( prRhsHasNull ){ *prRhsHasNull = rMayHaveNull = ++pParse->nMem; } sqlite3CodeSubselect(pParse, pX, rMayHaveNull, eType==IN_INDEX_ROWID); pParse->nQueryLoop = savedNQueryLoop; }else{ pX->iTable = iTab; } if( aiMap && eType!=IN_INDEX_INDEX_ASC && eType!=IN_INDEX_INDEX_DESC ){ int i, n; n = sqlite3ExprVectorSize(pX->pLeft); for(i=0; ipLeft; int nVal = sqlite3ExprVectorSize(pLeft); Select *pSelect = (pExpr->flags & EP_xIsSelect) ? pExpr->x.pSelect : 0; char *zRet; assert( pExpr->op==TK_IN ); zRet = sqlite3DbMallocZero(pParse->db, nVal+1); if( zRet ){ int i; for(i=0; ipEList->a[i].pExpr, a); }else{ zRet[i] = a; } } zRet[nVal] = '\0'; } return zRet; } #endif #ifndef SQLITE_OMIT_SUBQUERY /* ** Load the Parse object passed as the first argument with an error ** message of the form: ** ** "sub-select returns N columns - expected M" */ SQLITE_PRIVATE void sqlite3SubselectError(Parse *pParse, int nActual, int nExpect){ const char *zFmt = "sub-select returns %d columns - expected %d"; sqlite3ErrorMsg(pParse, zFmt, nActual, nExpect); } #endif /* ** Generate code for scalar subqueries used as a subquery expression, EXISTS, ** or IN operators. Examples: ** ** (SELECT a FROM b) -- subquery ** EXISTS (SELECT a FROM b) -- EXISTS subquery ** x IN (4,5,11) -- IN operator with list on right-hand side ** x IN (SELECT a FROM b) -- IN operator with subquery on the right ** ** The pExpr parameter describes the expression that contains the IN ** operator or subquery. ** ** If parameter isRowid is non-zero, then expression pExpr is guaranteed ** to be of the form " IN (?, ?, ?)", where is a reference ** to some integer key column of a table B-Tree. In this case, use an ** intkey B-Tree to store the set of IN(...) values instead of the usual ** (slower) variable length keys B-Tree. ** ** If rMayHaveNull is non-zero, that means that the operation is an IN ** (not a SELECT or EXISTS) and that the RHS might contains NULLs. ** All this routine does is initialize the register given by rMayHaveNull ** to NULL. Calling routines will take care of changing this register ** value to non-NULL if the RHS is NULL-free. ** ** For a SELECT or EXISTS operator, return the register that holds the ** result. For a multi-column SELECT, the result is stored in a contiguous ** array of registers and the return value is the register of the left-most ** result column. Return 0 for IN operators or if an error occurs. */ #ifndef SQLITE_OMIT_SUBQUERY SQLITE_PRIVATE int sqlite3CodeSubselect( Parse *pParse, /* Parsing context */ Expr *pExpr, /* The IN, SELECT, or EXISTS operator */ int rHasNullFlag, /* Register that records whether NULLs exist in RHS */ int isRowid /* If true, LHS of IN operator is a rowid */ ){ int jmpIfDynamic = -1; /* One-time test address */ int rReg = 0; /* Register storing resulting */ Vdbe *v = sqlite3GetVdbe(pParse); if( NEVER(v==0) ) return 0; sqlite3ExprCachePush(pParse); /* The evaluation of the IN/EXISTS/SELECT must be repeated every time it ** is encountered if any of the following is true: ** ** * The right-hand side is a correlated subquery ** * The right-hand side is an expression list containing variables ** * We are inside a trigger ** ** If all of the above are false, then we can run this code just once ** save the results, and reuse the same result on subsequent invocations. */ if( !ExprHasProperty(pExpr, EP_VarSelect) ){ jmpIfDynamic = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v); } #ifndef SQLITE_OMIT_EXPLAIN if( pParse->explain==2 ){ char *zMsg = sqlite3MPrintf(pParse->db, "EXECUTE %s%s SUBQUERY %d", jmpIfDynamic>=0?"":"CORRELATED ", pExpr->op==TK_IN?"LIST":"SCALAR", pParse->iNextSelectId ); sqlite3VdbeAddOp4(v, OP_Explain, pParse->iSelectId, 0, 0, zMsg, P4_DYNAMIC); } #endif switch( pExpr->op ){ case TK_IN: { int addr; /* Address of OP_OpenEphemeral instruction */ Expr *pLeft = pExpr->pLeft; /* the LHS of the IN operator */ KeyInfo *pKeyInfo = 0; /* Key information */ int nVal; /* Size of vector pLeft */ nVal = sqlite3ExprVectorSize(pLeft); assert( !isRowid || nVal==1 ); /* Whether this is an 'x IN(SELECT...)' or an 'x IN()' ** expression it is handled the same way. An ephemeral table is ** filled with index keys representing the results from the ** SELECT or the . ** ** If the 'x' expression is a column value, or the SELECT... ** statement returns a column value, then the affinity of that ** column is used to build the index keys. If both 'x' and the ** SELECT... statement are columns, then numeric affinity is used ** if either column has NUMERIC or INTEGER affinity. If neither ** 'x' nor the SELECT... statement are columns, then numeric affinity ** is used. */ pExpr->iTable = pParse->nTab++; addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pExpr->iTable, (isRowid?0:nVal)); pKeyInfo = isRowid ? 0 : sqlite3KeyInfoAlloc(pParse->db, nVal, 1); if( ExprHasProperty(pExpr, EP_xIsSelect) ){ /* Case 1: expr IN (SELECT ...) ** ** Generate code to write the results of the select into the temporary ** table allocated and opened above. */ Select *pSelect = pExpr->x.pSelect; ExprList *pEList = pSelect->pEList; assert( !isRowid ); /* If the LHS and RHS of the IN operator do not match, that ** error will have been caught long before we reach this point. */ if( ALWAYS(pEList->nExpr==nVal) ){ SelectDest dest; int i; sqlite3SelectDestInit(&dest, SRT_Set, pExpr->iTable); dest.zAffSdst = exprINAffinity(pParse, pExpr); assert( (pExpr->iTable&0x0000FFFF)==pExpr->iTable ); pSelect->iLimit = 0; testcase( pSelect->selFlags & SF_Distinct ); testcase( pKeyInfo==0 ); /* Caused by OOM in sqlite3KeyInfoAlloc() */ if( sqlite3Select(pParse, pSelect, &dest) ){ sqlite3DbFree(pParse->db, dest.zAffSdst); sqlite3KeyInfoUnref(pKeyInfo); return 0; } sqlite3DbFree(pParse->db, dest.zAffSdst); assert( pKeyInfo!=0 ); /* OOM will cause exit after sqlite3Select() */ assert( pEList!=0 ); assert( pEList->nExpr>0 ); assert( sqlite3KeyInfoIsWriteable(pKeyInfo) ); for(i=0; iaColl[i] = sqlite3BinaryCompareCollSeq( pParse, p, pEList->a[i].pExpr ); } } }else if( ALWAYS(pExpr->x.pList!=0) ){ /* Case 2: expr IN (exprlist) ** ** For each expression, build an index key from the evaluation and ** store it in the temporary table. If is a column, then use ** that columns affinity when building index keys. If is not ** a column, use numeric affinity. */ char affinity; /* Affinity of the LHS of the IN */ int i; ExprList *pList = pExpr->x.pList; struct ExprList_item *pItem; int r1, r2, r3; affinity = sqlite3ExprAffinity(pLeft); if( !affinity ){ affinity = SQLITE_AFF_BLOB; } if( pKeyInfo ){ assert( sqlite3KeyInfoIsWriteable(pKeyInfo) ); pKeyInfo->aColl[0] = sqlite3ExprCollSeq(pParse, pExpr->pLeft); } /* Loop through each expression in . */ r1 = sqlite3GetTempReg(pParse); r2 = sqlite3GetTempReg(pParse); if( isRowid ) sqlite3VdbeAddOp2(v, OP_Null, 0, r2); for(i=pList->nExpr, pItem=pList->a; i>0; i--, pItem++){ Expr *pE2 = pItem->pExpr; int iValToIns; /* If the expression is not constant then we will need to ** disable the test that was generated above that makes sure ** this code only executes once. Because for a non-constant ** expression we need to rerun this code each time. */ if( jmpIfDynamic>=0 && !sqlite3ExprIsConstant(pE2) ){ sqlite3VdbeChangeToNoop(v, jmpIfDynamic); jmpIfDynamic = -1; } /* Evaluate the expression and insert it into the temp table */ if( isRowid && sqlite3ExprIsInteger(pE2, &iValToIns) ){ sqlite3VdbeAddOp3(v, OP_InsertInt, pExpr->iTable, r2, iValToIns); }else{ r3 = sqlite3ExprCodeTarget(pParse, pE2, r1); if( isRowid ){ sqlite3VdbeAddOp2(v, OP_MustBeInt, r3, sqlite3VdbeCurrentAddr(v)+2); VdbeCoverage(v); sqlite3VdbeAddOp3(v, OP_Insert, pExpr->iTable, r2, r3); }else{ sqlite3VdbeAddOp4(v, OP_MakeRecord, r3, 1, r2, &affinity, 1); sqlite3ExprCacheAffinityChange(pParse, r3, 1); sqlite3VdbeAddOp2(v, OP_IdxInsert, pExpr->iTable, r2); } } } sqlite3ReleaseTempReg(pParse, r1); sqlite3ReleaseTempReg(pParse, r2); } if( pKeyInfo ){ sqlite3VdbeChangeP4(v, addr, (void *)pKeyInfo, P4_KEYINFO); } break; } case TK_EXISTS: case TK_SELECT: default: { /* Case 3: (SELECT ... FROM ...) ** or: EXISTS(SELECT ... FROM ...) ** ** For a SELECT, generate code to put the values for all columns of ** the first row into an array of registers and return the index of ** the first register. ** ** If this is an EXISTS, write an integer 0 (not exists) or 1 (exists) ** into a register and return that register number. ** ** In both cases, the query is augmented with "LIMIT 1". Any ** preexisting limit is discarded in place of the new LIMIT 1. */ Select *pSel; /* SELECT statement to encode */ SelectDest dest; /* How to deal with SELECT result */ int nReg; /* Registers to allocate */ testcase( pExpr->op==TK_EXISTS ); testcase( pExpr->op==TK_SELECT ); assert( pExpr->op==TK_EXISTS || pExpr->op==TK_SELECT ); assert( ExprHasProperty(pExpr, EP_xIsSelect) ); pSel = pExpr->x.pSelect; nReg = pExpr->op==TK_SELECT ? pSel->pEList->nExpr : 1; sqlite3SelectDestInit(&dest, 0, pParse->nMem+1); pParse->nMem += nReg; if( pExpr->op==TK_SELECT ){ dest.eDest = SRT_Mem; dest.iSdst = dest.iSDParm; dest.nSdst = nReg; sqlite3VdbeAddOp3(v, OP_Null, 0, dest.iSDParm, dest.iSDParm+nReg-1); VdbeComment((v, "Init subquery result")); }else{ dest.eDest = SRT_Exists; sqlite3VdbeAddOp2(v, OP_Integer, 0, dest.iSDParm); VdbeComment((v, "Init EXISTS result")); } sqlite3ExprDelete(pParse->db, pSel->pLimit); pSel->pLimit = sqlite3ExprAlloc(pParse->db, TK_INTEGER, &sqlite3IntTokens[1], 0); pSel->iLimit = 0; pSel->selFlags &= ~SF_MultiValue; if( sqlite3Select(pParse, pSel, &dest) ){ return 0; } rReg = dest.iSDParm; ExprSetVVAProperty(pExpr, EP_NoReduce); break; } } if( rHasNullFlag ){ sqlite3SetHasNullFlag(v, pExpr->iTable, rHasNullFlag); } if( jmpIfDynamic>=0 ){ sqlite3VdbeJumpHere(v, jmpIfDynamic); } sqlite3ExprCachePop(pParse); return rReg; } #endif /* SQLITE_OMIT_SUBQUERY */ #ifndef SQLITE_OMIT_SUBQUERY /* ** Expr pIn is an IN(...) expression. This function checks that the ** sub-select on the RHS of the IN() operator has the same number of ** columns as the vector on the LHS. Or, if the RHS of the IN() is not ** a sub-query, that the LHS is a vector of size 1. */ SQLITE_PRIVATE int sqlite3ExprCheckIN(Parse *pParse, Expr *pIn){ int nVector = sqlite3ExprVectorSize(pIn->pLeft); if( (pIn->flags & EP_xIsSelect) ){ if( nVector!=pIn->x.pSelect->pEList->nExpr ){ sqlite3SubselectError(pParse, pIn->x.pSelect->pEList->nExpr, nVector); return 1; } }else if( nVector!=1 ){ if( (pIn->pLeft->flags & EP_xIsSelect) ){ sqlite3SubselectError(pParse, nVector, 1); }else{ sqlite3ErrorMsg(pParse, "row value misused"); } return 1; } return 0; } #endif #ifndef SQLITE_OMIT_SUBQUERY /* ** Generate code for an IN expression. ** ** x IN (SELECT ...) ** x IN (value, value, ...) ** ** The left-hand side (LHS) is a scalar or vector expression. The ** right-hand side (RHS) is an array of zero or more scalar values, or a ** subquery. If the RHS is a subquery, the number of result columns must ** match the number of columns in the vector on the LHS. If the RHS is ** a list of values, the LHS must be a scalar. ** ** The IN operator is true if the LHS value is contained within the RHS. ** The result is false if the LHS is definitely not in the RHS. The ** result is NULL if the presence of the LHS in the RHS cannot be ** determined due to NULLs. ** ** This routine generates code that jumps to destIfFalse if the LHS is not ** contained within the RHS. If due to NULLs we cannot determine if the LHS ** is contained in the RHS then jump to destIfNull. If the LHS is contained ** within the RHS then fall through. ** ** See the separate in-operator.md documentation file in the canonical ** SQLite source tree for additional information. */ static void sqlite3ExprCodeIN( Parse *pParse, /* Parsing and code generating context */ Expr *pExpr, /* The IN expression */ int destIfFalse, /* Jump here if LHS is not contained in the RHS */ int destIfNull /* Jump here if the results are unknown due to NULLs */ ){ int rRhsHasNull = 0; /* Register that is true if RHS contains NULL values */ int eType; /* Type of the RHS */ int rLhs; /* Register(s) holding the LHS values */ int rLhsOrig; /* LHS values prior to reordering by aiMap[] */ Vdbe *v; /* Statement under construction */ int *aiMap = 0; /* Map from vector field to index column */ char *zAff = 0; /* Affinity string for comparisons */ int nVector; /* Size of vectors for this IN operator */ int iDummy; /* Dummy parameter to exprCodeVector() */ Expr *pLeft; /* The LHS of the IN operator */ int i; /* loop counter */ int destStep2; /* Where to jump when NULLs seen in step 2 */ int destStep6 = 0; /* Start of code for Step 6 */ int addrTruthOp; /* Address of opcode that determines the IN is true */ int destNotNull; /* Jump here if a comparison is not true in step 6 */ int addrTop; /* Top of the step-6 loop */ pLeft = pExpr->pLeft; if( sqlite3ExprCheckIN(pParse, pExpr) ) return; zAff = exprINAffinity(pParse, pExpr); nVector = sqlite3ExprVectorSize(pExpr->pLeft); aiMap = (int*)sqlite3DbMallocZero( pParse->db, nVector*(sizeof(int) + sizeof(char)) + 1 ); if( pParse->db->mallocFailed ) goto sqlite3ExprCodeIN_oom_error; /* Attempt to compute the RHS. After this step, if anything other than ** IN_INDEX_NOOP is returned, the table opened ith cursor pExpr->iTable ** contains the values that make up the RHS. If IN_INDEX_NOOP is returned, ** the RHS has not yet been coded. */ v = pParse->pVdbe; assert( v!=0 ); /* OOM detected prior to this routine */ VdbeNoopComment((v, "begin IN expr")); eType = sqlite3FindInIndex(pParse, pExpr, IN_INDEX_MEMBERSHIP | IN_INDEX_NOOP_OK, destIfFalse==destIfNull ? 0 : &rRhsHasNull, aiMap); assert( pParse->nErr || nVector==1 || eType==IN_INDEX_EPH || eType==IN_INDEX_INDEX_ASC || eType==IN_INDEX_INDEX_DESC ); #ifdef SQLITE_DEBUG /* Confirm that aiMap[] contains nVector integer values between 0 and ** nVector-1. */ for(i=0; i from " IN (...)". If the LHS is a ** vector, then it is stored in an array of nVector registers starting ** at r1. ** ** sqlite3FindInIndex() might have reordered the fields of the LHS vector ** so that the fields are in the same order as an existing index. The ** aiMap[] array contains a mapping from the original LHS field order to ** the field order that matches the RHS index. */ sqlite3ExprCachePush(pParse); rLhsOrig = exprCodeVector(pParse, pLeft, &iDummy); for(i=0; ix.pList; CollSeq *pColl = sqlite3ExprCollSeq(pParse, pExpr->pLeft); int labelOk = sqlite3VdbeMakeLabel(v); int r2, regToFree; int regCkNull = 0; int ii; assert( !ExprHasProperty(pExpr, EP_xIsSelect) ); if( destIfNull!=destIfFalse ){ regCkNull = sqlite3GetTempReg(pParse); sqlite3VdbeAddOp3(v, OP_BitAnd, rLhs, rLhs, regCkNull); } for(ii=0; iinExpr; ii++){ r2 = sqlite3ExprCodeTemp(pParse, pList->a[ii].pExpr, ®ToFree); if( regCkNull && sqlite3ExprCanBeNull(pList->a[ii].pExpr) ){ sqlite3VdbeAddOp3(v, OP_BitAnd, regCkNull, r2, regCkNull); } if( iinExpr-1 || destIfNull!=destIfFalse ){ sqlite3VdbeAddOp4(v, OP_Eq, rLhs, labelOk, r2, (void*)pColl, P4_COLLSEQ); VdbeCoverageIf(v, iinExpr-1); VdbeCoverageIf(v, ii==pList->nExpr-1); sqlite3VdbeChangeP5(v, zAff[0]); }else{ assert( destIfNull==destIfFalse ); sqlite3VdbeAddOp4(v, OP_Ne, rLhs, destIfFalse, r2, (void*)pColl, P4_COLLSEQ); VdbeCoverage(v); sqlite3VdbeChangeP5(v, zAff[0] | SQLITE_JUMPIFNULL); } sqlite3ReleaseTempReg(pParse, regToFree); } if( regCkNull ){ sqlite3VdbeAddOp2(v, OP_IsNull, regCkNull, destIfNull); VdbeCoverage(v); sqlite3VdbeGoto(v, destIfFalse); } sqlite3VdbeResolveLabel(v, labelOk); sqlite3ReleaseTempReg(pParse, regCkNull); goto sqlite3ExprCodeIN_finished; } /* Step 2: Check to see if the LHS contains any NULL columns. If the ** LHS does contain NULLs then the result must be either FALSE or NULL. ** We will then skip the binary search of the RHS. */ if( destIfNull==destIfFalse ){ destStep2 = destIfFalse; }else{ destStep2 = destStep6 = sqlite3VdbeMakeLabel(v); } for(i=0; ipLeft, i); if( sqlite3ExprCanBeNull(p) ){ sqlite3VdbeAddOp2(v, OP_IsNull, rLhs+i, destStep2); VdbeCoverage(v); } } /* Step 3. The LHS is now known to be non-NULL. Do the binary search ** of the RHS using the LHS as a probe. If found, the result is ** true. */ if( eType==IN_INDEX_ROWID ){ /* In this case, the RHS is the ROWID of table b-tree and so we also ** know that the RHS is non-NULL. Hence, we combine steps 3 and 4 ** into a single opcode. */ sqlite3VdbeAddOp3(v, OP_SeekRowid, pExpr->iTable, destIfFalse, rLhs); VdbeCoverage(v); addrTruthOp = sqlite3VdbeAddOp0(v, OP_Goto); /* Return True */ }else{ sqlite3VdbeAddOp4(v, OP_Affinity, rLhs, nVector, 0, zAff, nVector); if( destIfFalse==destIfNull ){ /* Combine Step 3 and Step 5 into a single opcode */ sqlite3VdbeAddOp4Int(v, OP_NotFound, pExpr->iTable, destIfFalse, rLhs, nVector); VdbeCoverage(v); goto sqlite3ExprCodeIN_finished; } /* Ordinary Step 3, for the case where FALSE and NULL are distinct */ addrTruthOp = sqlite3VdbeAddOp4Int(v, OP_Found, pExpr->iTable, 0, rLhs, nVector); VdbeCoverage(v); } /* Step 4. If the RHS is known to be non-NULL and we did not find ** an match on the search above, then the result must be FALSE. */ if( rRhsHasNull && nVector==1 ){ sqlite3VdbeAddOp2(v, OP_NotNull, rRhsHasNull, destIfFalse); VdbeCoverage(v); } /* Step 5. If we do not care about the difference between NULL and ** FALSE, then just return false. */ if( destIfFalse==destIfNull ) sqlite3VdbeGoto(v, destIfFalse); /* Step 6: Loop through rows of the RHS. Compare each row to the LHS. ** If any comparison is NULL, then the result is NULL. If all ** comparisons are FALSE then the final result is FALSE. ** ** For a scalar LHS, it is sufficient to check just the first row ** of the RHS. */ if( destStep6 ) sqlite3VdbeResolveLabel(v, destStep6); addrTop = sqlite3VdbeAddOp2(v, OP_Rewind, pExpr->iTable, destIfFalse); VdbeCoverage(v); if( nVector>1 ){ destNotNull = sqlite3VdbeMakeLabel(v); }else{ /* For nVector==1, combine steps 6 and 7 by immediately returning ** FALSE if the first comparison is not NULL */ destNotNull = destIfFalse; } for(i=0; iiTable, i, r3); sqlite3VdbeAddOp4(v, OP_Ne, rLhs+i, destNotNull, r3, (void*)pColl, P4_COLLSEQ); VdbeCoverage(v); sqlite3ReleaseTempReg(pParse, r3); } sqlite3VdbeAddOp2(v, OP_Goto, 0, destIfNull); if( nVector>1 ){ sqlite3VdbeResolveLabel(v, destNotNull); sqlite3VdbeAddOp2(v, OP_Next, pExpr->iTable, addrTop+1); VdbeCoverage(v); /* Step 7: If we reach this point, we know that the result must ** be false. */ sqlite3VdbeAddOp2(v, OP_Goto, 0, destIfFalse); } /* Jumps here in order to return true. */ sqlite3VdbeJumpHere(v, addrTruthOp); sqlite3ExprCodeIN_finished: if( rLhs!=rLhsOrig ) sqlite3ReleaseTempReg(pParse, rLhs); sqlite3ExprCachePop(pParse); VdbeComment((v, "end IN expr")); sqlite3ExprCodeIN_oom_error: sqlite3DbFree(pParse->db, aiMap); sqlite3DbFree(pParse->db, zAff); } #endif /* SQLITE_OMIT_SUBQUERY */ #ifndef SQLITE_OMIT_FLOATING_POINT /* ** Generate an instruction that will put the floating point ** value described by z[0..n-1] into register iMem. ** ** The z[] string will probably not be zero-terminated. But the ** z[n] character is guaranteed to be something that does not look ** like the continuation of the number. */ static void codeReal(Vdbe *v, const char *z, int negateFlag, int iMem){ if( ALWAYS(z!=0) ){ double value; sqlite3AtoF(z, &value, sqlite3Strlen30(z), SQLITE_UTF8); assert( !sqlite3IsNaN(value) ); /* The new AtoF never returns NaN */ if( negateFlag ) value = -value; sqlite3VdbeAddOp4Dup8(v, OP_Real, 0, iMem, 0, (u8*)&value, P4_REAL); } } #endif /* ** Generate an instruction that will put the integer describe by ** text z[0..n-1] into register iMem. ** ** Expr.u.zToken is always UTF8 and zero-terminated. */ static void codeInteger(Parse *pParse, Expr *pExpr, int negFlag, int iMem){ Vdbe *v = pParse->pVdbe; if( pExpr->flags & EP_IntValue ){ int i = pExpr->u.iValue; assert( i>=0 ); if( negFlag ) i = -i; sqlite3VdbeAddOp2(v, OP_Integer, i, iMem); }else{ int c; i64 value; const char *z = pExpr->u.zToken; assert( z!=0 ); c = sqlite3DecOrHexToI64(z, &value); if( c==0 || (c==2 && negFlag) ){ if( negFlag ){ value = c==2 ? SMALLEST_INT64 : -value; } sqlite3VdbeAddOp4Dup8(v, OP_Int64, 0, iMem, 0, (u8*)&value, P4_INT64); }else{ #ifdef SQLITE_OMIT_FLOATING_POINT sqlite3ErrorMsg(pParse, "oversized integer: %s%s", negFlag ? "-" : "", z); #else #ifndef SQLITE_OMIT_HEX_INTEGER if( sqlite3_strnicmp(z,"0x",2)==0 ){ sqlite3ErrorMsg(pParse, "hex literal too big: %s", z); }else #endif { codeReal(v, z, negFlag, iMem); } #endif } } } /* ** Erase column-cache entry number i */ static void cacheEntryClear(Parse *pParse, int i){ if( pParse->aColCache[i].tempReg ){ if( pParse->nTempRegaTempReg) ){ pParse->aTempReg[pParse->nTempReg++] = pParse->aColCache[i].iReg; } } pParse->nColCache--; if( inColCache ){ pParse->aColCache[i] = pParse->aColCache[pParse->nColCache]; } } /* ** Record in the column cache that a particular column from a ** particular table is stored in a particular register. */ SQLITE_PRIVATE void sqlite3ExprCacheStore(Parse *pParse, int iTab, int iCol, int iReg){ int i; int minLru; int idxLru; struct yColCache *p; /* Unless an error has occurred, register numbers are always positive. */ assert( iReg>0 || pParse->nErr || pParse->db->mallocFailed ); assert( iCol>=-1 && iCol<32768 ); /* Finite column numbers */ /* The SQLITE_ColumnCache flag disables the column cache. This is used ** for testing only - to verify that SQLite always gets the same answer ** with and without the column cache. */ if( OptimizationDisabled(pParse->db, SQLITE_ColumnCache) ) return; /* First replace any existing entry. ** ** Actually, the way the column cache is currently used, we are guaranteed ** that the object will never already be in cache. Verify this guarantee. */ #ifndef NDEBUG for(i=0, p=pParse->aColCache; inColCache; i++, p++){ assert( p->iTable!=iTab || p->iColumn!=iCol ); } #endif /* If the cache is already full, delete the least recently used entry */ if( pParse->nColCache>=SQLITE_N_COLCACHE ){ minLru = 0x7fffffff; idxLru = -1; for(i=0, p=pParse->aColCache; ilrulru; } } p = &pParse->aColCache[idxLru]; }else{ p = &pParse->aColCache[pParse->nColCache++]; } /* Add the new entry to the end of the cache */ p->iLevel = pParse->iCacheLevel; p->iTable = iTab; p->iColumn = iCol; p->iReg = iReg; p->tempReg = 0; p->lru = pParse->iCacheCnt++; } /* ** Indicate that registers between iReg..iReg+nReg-1 are being overwritten. ** Purge the range of registers from the column cache. */ SQLITE_PRIVATE void sqlite3ExprCacheRemove(Parse *pParse, int iReg, int nReg){ int i = 0; while( inColCache ){ struct yColCache *p = &pParse->aColCache[i]; if( p->iReg >= iReg && p->iReg < iReg+nReg ){ cacheEntryClear(pParse, i); }else{ i++; } } } /* ** Remember the current column cache context. Any new entries added ** added to the column cache after this call are removed when the ** corresponding pop occurs. */ SQLITE_PRIVATE void sqlite3ExprCachePush(Parse *pParse){ pParse->iCacheLevel++; #ifdef SQLITE_DEBUG if( pParse->db->flags & SQLITE_VdbeAddopTrace ){ printf("PUSH to %d\n", pParse->iCacheLevel); } #endif } /* ** Remove from the column cache any entries that were added since the ** the previous sqlite3ExprCachePush operation. In other words, restore ** the cache to the state it was in prior the most recent Push. */ SQLITE_PRIVATE void sqlite3ExprCachePop(Parse *pParse){ int i = 0; assert( pParse->iCacheLevel>=1 ); pParse->iCacheLevel--; #ifdef SQLITE_DEBUG if( pParse->db->flags & SQLITE_VdbeAddopTrace ){ printf("POP to %d\n", pParse->iCacheLevel); } #endif while( inColCache ){ if( pParse->aColCache[i].iLevel>pParse->iCacheLevel ){ cacheEntryClear(pParse, i); }else{ i++; } } } /* ** When a cached column is reused, make sure that its register is ** no longer available as a temp register. ticket #3879: that same ** register might be in the cache in multiple places, so be sure to ** get them all. */ static void sqlite3ExprCachePinRegister(Parse *pParse, int iReg){ int i; struct yColCache *p; for(i=0, p=pParse->aColCache; inColCache; i++, p++){ if( p->iReg==iReg ){ p->tempReg = 0; } } } /* Generate code that will load into register regOut a value that is ** appropriate for the iIdxCol-th column of index pIdx. */ SQLITE_PRIVATE void sqlite3ExprCodeLoadIndexColumn( Parse *pParse, /* The parsing context */ Index *pIdx, /* The index whose column is to be loaded */ int iTabCur, /* Cursor pointing to a table row */ int iIdxCol, /* The column of the index to be loaded */ int regOut /* Store the index column value in this register */ ){ i16 iTabCol = pIdx->aiColumn[iIdxCol]; if( iTabCol==XN_EXPR ){ assert( pIdx->aColExpr ); assert( pIdx->aColExpr->nExpr>iIdxCol ); pParse->iSelfTab = iTabCur; sqlite3ExprCodeCopy(pParse, pIdx->aColExpr->a[iIdxCol].pExpr, regOut); }else{ sqlite3ExprCodeGetColumnOfTable(pParse->pVdbe, pIdx->pTable, iTabCur, iTabCol, regOut); } } /* ** Generate code to extract the value of the iCol-th column of a table. */ SQLITE_PRIVATE void sqlite3ExprCodeGetColumnOfTable( Vdbe *v, /* The VDBE under construction */ Table *pTab, /* The table containing the value */ int iTabCur, /* The table cursor. Or the PK cursor for WITHOUT ROWID */ int iCol, /* Index of the column to extract */ int regOut /* Extract the value into this register */ ){ if( iCol<0 || iCol==pTab->iPKey ){ sqlite3VdbeAddOp2(v, OP_Rowid, iTabCur, regOut); }else{ int op = IsVirtual(pTab) ? OP_VColumn : OP_Column; int x = iCol; if( !HasRowid(pTab) && !IsVirtual(pTab) ){ x = sqlite3ColumnOfIndex(sqlite3PrimaryKeyIndex(pTab), iCol); } sqlite3VdbeAddOp3(v, op, iTabCur, x, regOut); } if( iCol>=0 ){ sqlite3ColumnDefault(v, pTab, iCol, regOut); } } /* ** Generate code that will extract the iColumn-th column from ** table pTab and store the column value in a register. ** ** An effort is made to store the column value in register iReg. This ** is not garanteeed for GetColumn() - the result can be stored in ** any register. But the result is guaranteed to land in register iReg ** for GetColumnToReg(). ** ** There must be an open cursor to pTab in iTable when this routine ** is called. If iColumn<0 then code is generated that extracts the rowid. */ SQLITE_PRIVATE int sqlite3ExprCodeGetColumn( Parse *pParse, /* Parsing and code generating context */ Table *pTab, /* Description of the table we are reading from */ int iColumn, /* Index of the table column */ int iTable, /* The cursor pointing to the table */ int iReg, /* Store results here */ u8 p5 /* P5 value for OP_Column + FLAGS */ ){ Vdbe *v = pParse->pVdbe; int i; struct yColCache *p; for(i=0, p=pParse->aColCache; inColCache; i++, p++){ if( p->iTable==iTable && p->iColumn==iColumn ){ p->lru = pParse->iCacheCnt++; sqlite3ExprCachePinRegister(pParse, p->iReg); return p->iReg; } } assert( v!=0 ); sqlite3ExprCodeGetColumnOfTable(v, pTab, iTable, iColumn, iReg); if( p5 ){ sqlite3VdbeChangeP5(v, p5); }else{ sqlite3ExprCacheStore(pParse, iTable, iColumn, iReg); } return iReg; } SQLITE_PRIVATE void sqlite3ExprCodeGetColumnToReg( Parse *pParse, /* Parsing and code generating context */ Table *pTab, /* Description of the table we are reading from */ int iColumn, /* Index of the table column */ int iTable, /* The cursor pointing to the table */ int iReg /* Store results here */ ){ int r1 = sqlite3ExprCodeGetColumn(pParse, pTab, iColumn, iTable, iReg, 0); if( r1!=iReg ) sqlite3VdbeAddOp2(pParse->pVdbe, OP_SCopy, r1, iReg); } /* ** Clear all column cache entries. */ SQLITE_PRIVATE void sqlite3ExprCacheClear(Parse *pParse){ int i; #if SQLITE_DEBUG if( pParse->db->flags & SQLITE_VdbeAddopTrace ){ printf("CLEAR\n"); } #endif for(i=0; inColCache; i++){ if( pParse->aColCache[i].tempReg && pParse->nTempRegaTempReg) ){ pParse->aTempReg[pParse->nTempReg++] = pParse->aColCache[i].iReg; } } pParse->nColCache = 0; } /* ** Record the fact that an affinity change has occurred on iCount ** registers starting with iStart. */ SQLITE_PRIVATE void sqlite3ExprCacheAffinityChange(Parse *pParse, int iStart, int iCount){ sqlite3ExprCacheRemove(pParse, iStart, iCount); } /* ** Generate code to move content from registers iFrom...iFrom+nReg-1 ** over to iTo..iTo+nReg-1. Keep the column cache up-to-date. */ SQLITE_PRIVATE void sqlite3ExprCodeMove(Parse *pParse, int iFrom, int iTo, int nReg){ assert( iFrom>=iTo+nReg || iFrom+nReg<=iTo ); sqlite3VdbeAddOp3(pParse->pVdbe, OP_Move, iFrom, iTo, nReg); sqlite3ExprCacheRemove(pParse, iFrom, nReg); } #if defined(SQLITE_DEBUG) || defined(SQLITE_COVERAGE_TEST) /* ** Return true if any register in the range iFrom..iTo (inclusive) ** is used as part of the column cache. ** ** This routine is used within assert() and testcase() macros only ** and does not appear in a normal build. */ static int usedAsColumnCache(Parse *pParse, int iFrom, int iTo){ int i; struct yColCache *p; for(i=0, p=pParse->aColCache; inColCache; i++, p++){ int r = p->iReg; if( r>=iFrom && r<=iTo ) return 1; /*NO_TEST*/ } return 0; } #endif /* SQLITE_DEBUG || SQLITE_COVERAGE_TEST */ /* ** Convert a scalar expression node to a TK_REGISTER referencing ** register iReg. The caller must ensure that iReg already contains ** the correct value for the expression. */ static void exprToRegister(Expr *p, int iReg){ p->op2 = p->op; p->op = TK_REGISTER; p->iTable = iReg; ExprClearProperty(p, EP_Skip); } /* ** Evaluate an expression (either a vector or a scalar expression) and store ** the result in continguous temporary registers. Return the index of ** the first register used to store the result. ** ** If the returned result register is a temporary scalar, then also write ** that register number into *piFreeable. If the returned result register ** is not a temporary or if the expression is a vector set *piFreeable ** to 0. */ static int exprCodeVector(Parse *pParse, Expr *p, int *piFreeable){ int iResult; int nResult = sqlite3ExprVectorSize(p); if( nResult==1 ){ iResult = sqlite3ExprCodeTemp(pParse, p, piFreeable); }else{ *piFreeable = 0; if( p->op==TK_SELECT ){ iResult = sqlite3CodeSubselect(pParse, p, 0, 0); }else{ int i; iResult = pParse->nMem+1; pParse->nMem += nResult; for(i=0; ix.pList->a[i].pExpr, i+iResult); } } } return iResult; } /* ** Generate code into the current Vdbe to evaluate the given ** expression. Attempt to store the results in register "target". ** Return the register where results are stored. ** ** With this routine, there is no guarantee that results will ** be stored in target. The result might be stored in some other ** register if it is convenient to do so. The calling function ** must check the return code and move the results to the desired ** register. */ SQLITE_PRIVATE int sqlite3ExprCodeTarget(Parse *pParse, Expr *pExpr, int target){ Vdbe *v = pParse->pVdbe; /* The VM under construction */ int op; /* The opcode being coded */ int inReg = target; /* Results stored in register inReg */ int regFree1 = 0; /* If non-zero free this temporary register */ int regFree2 = 0; /* If non-zero free this temporary register */ int r1, r2; /* Various register numbers */ Expr tempX; /* Temporary expression node */ int p5 = 0; assert( target>0 && target<=pParse->nMem ); if( v==0 ){ assert( pParse->db->mallocFailed ); return 0; } if( pExpr==0 ){ op = TK_NULL; }else{ op = pExpr->op; } switch( op ){ case TK_AGG_COLUMN: { AggInfo *pAggInfo = pExpr->pAggInfo; struct AggInfo_col *pCol = &pAggInfo->aCol[pExpr->iAgg]; if( !pAggInfo->directMode ){ assert( pCol->iMem>0 ); return pCol->iMem; }else if( pAggInfo->useSortingIdx ){ sqlite3VdbeAddOp3(v, OP_Column, pAggInfo->sortingIdxPTab, pCol->iSorterColumn, target); return target; } /* Otherwise, fall thru into the TK_COLUMN case */ } case TK_COLUMN: { int iTab = pExpr->iTable; if( iTab<0 ){ if( pParse->ckBase>0 ){ /* Generating CHECK constraints or inserting into partial index */ return pExpr->iColumn + pParse->ckBase; }else{ /* Coding an expression that is part of an index where column names ** in the index refer to the table to which the index belongs */ iTab = pParse->iSelfTab; } } return sqlite3ExprCodeGetColumn(pParse, pExpr->pTab, pExpr->iColumn, iTab, target, pExpr->op2); } case TK_INTEGER: { codeInteger(pParse, pExpr, 0, target); return target; } #ifndef SQLITE_OMIT_FLOATING_POINT case TK_FLOAT: { assert( !ExprHasProperty(pExpr, EP_IntValue) ); codeReal(v, pExpr->u.zToken, 0, target); return target; } #endif case TK_STRING: { assert( !ExprHasProperty(pExpr, EP_IntValue) ); sqlite3VdbeLoadString(v, target, pExpr->u.zToken); return target; } case TK_NULL: { sqlite3VdbeAddOp2(v, OP_Null, 0, target); return target; } #ifndef SQLITE_OMIT_BLOB_LITERAL case TK_BLOB: { int n; const char *z; char *zBlob; assert( !ExprHasProperty(pExpr, EP_IntValue) ); assert( pExpr->u.zToken[0]=='x' || pExpr->u.zToken[0]=='X' ); assert( pExpr->u.zToken[1]=='\'' ); z = &pExpr->u.zToken[2]; n = sqlite3Strlen30(z) - 1; assert( z[n]=='\'' ); zBlob = sqlite3HexToBlob(sqlite3VdbeDb(v), z, n); sqlite3VdbeAddOp4(v, OP_Blob, n/2, target, 0, zBlob, P4_DYNAMIC); return target; } #endif case TK_VARIABLE: { assert( !ExprHasProperty(pExpr, EP_IntValue) ); assert( pExpr->u.zToken!=0 ); assert( pExpr->u.zToken[0]!=0 ); sqlite3VdbeAddOp2(v, OP_Variable, pExpr->iColumn, target); if( pExpr->u.zToken[1]!=0 ){ assert( pExpr->u.zToken[0]=='?' || strcmp(pExpr->u.zToken, pParse->azVar[pExpr->iColumn-1])==0 ); sqlite3VdbeChangeP4(v, -1, pParse->azVar[pExpr->iColumn-1], P4_STATIC); } return target; } case TK_REGISTER: { return pExpr->iTable; } #ifndef SQLITE_OMIT_CAST case TK_CAST: { /* Expressions of the form: CAST(pLeft AS token) */ inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target); if( inReg!=target ){ sqlite3VdbeAddOp2(v, OP_SCopy, inReg, target); inReg = target; } sqlite3VdbeAddOp2(v, OP_Cast, target, sqlite3AffinityType(pExpr->u.zToken, 0)); testcase( usedAsColumnCache(pParse, inReg, inReg) ); sqlite3ExprCacheAffinityChange(pParse, inReg, 1); return inReg; } #endif /* SQLITE_OMIT_CAST */ case TK_IS: case TK_ISNOT: op = (op==TK_IS) ? TK_EQ : TK_NE; p5 = SQLITE_NULLEQ; /* fall-through */ case TK_LT: case TK_LE: case TK_GT: case TK_GE: case TK_NE: case TK_EQ: { Expr *pLeft = pExpr->pLeft; if( sqlite3ExprIsVector(pLeft) ){ codeVectorCompare(pParse, pExpr, target, op, p5); }else{ r1 = sqlite3ExprCodeTemp(pParse, pLeft, ®Free1); r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, ®Free2); codeCompare(pParse, pLeft, pExpr->pRight, op, r1, r2, inReg, SQLITE_STOREP2 | p5); assert(TK_LT==OP_Lt); testcase(op==OP_Lt); VdbeCoverageIf(v,op==OP_Lt); assert(TK_LE==OP_Le); testcase(op==OP_Le); VdbeCoverageIf(v,op==OP_Le); assert(TK_GT==OP_Gt); testcase(op==OP_Gt); VdbeCoverageIf(v,op==OP_Gt); assert(TK_GE==OP_Ge); testcase(op==OP_Ge); VdbeCoverageIf(v,op==OP_Ge); assert(TK_EQ==OP_Eq); testcase(op==OP_Eq); VdbeCoverageIf(v,op==OP_Eq); assert(TK_NE==OP_Ne); testcase(op==OP_Ne); VdbeCoverageIf(v,op==OP_Ne); testcase( regFree1==0 ); testcase( regFree2==0 ); } break; } case TK_AND: case TK_OR: case TK_PLUS: case TK_STAR: case TK_MINUS: case TK_REM: case TK_BITAND: case TK_BITOR: case TK_SLASH: case TK_LSHIFT: case TK_RSHIFT: case TK_CONCAT: { assert( TK_AND==OP_And ); testcase( op==TK_AND ); assert( TK_OR==OP_Or ); testcase( op==TK_OR ); assert( TK_PLUS==OP_Add ); testcase( op==TK_PLUS ); assert( TK_MINUS==OP_Subtract ); testcase( op==TK_MINUS ); assert( TK_REM==OP_Remainder ); testcase( op==TK_REM ); assert( TK_BITAND==OP_BitAnd ); testcase( op==TK_BITAND ); assert( TK_BITOR==OP_BitOr ); testcase( op==TK_BITOR ); assert( TK_SLASH==OP_Divide ); testcase( op==TK_SLASH ); assert( TK_LSHIFT==OP_ShiftLeft ); testcase( op==TK_LSHIFT ); assert( TK_RSHIFT==OP_ShiftRight ); testcase( op==TK_RSHIFT ); assert( TK_CONCAT==OP_Concat ); testcase( op==TK_CONCAT ); r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, ®Free1); r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, ®Free2); sqlite3VdbeAddOp3(v, op, r2, r1, target); testcase( regFree1==0 ); testcase( regFree2==0 ); break; } case TK_UMINUS: { Expr *pLeft = pExpr->pLeft; assert( pLeft ); if( pLeft->op==TK_INTEGER ){ codeInteger(pParse, pLeft, 1, target); return target; #ifndef SQLITE_OMIT_FLOATING_POINT }else if( pLeft->op==TK_FLOAT ){ assert( !ExprHasProperty(pExpr, EP_IntValue) ); codeReal(v, pLeft->u.zToken, 1, target); return target; #endif }else{ tempX.op = TK_INTEGER; tempX.flags = EP_IntValue|EP_TokenOnly; tempX.u.iValue = 0; r1 = sqlite3ExprCodeTemp(pParse, &tempX, ®Free1); r2 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, ®Free2); sqlite3VdbeAddOp3(v, OP_Subtract, r2, r1, target); testcase( regFree2==0 ); } break; } case TK_BITNOT: case TK_NOT: { assert( TK_BITNOT==OP_BitNot ); testcase( op==TK_BITNOT ); assert( TK_NOT==OP_Not ); testcase( op==TK_NOT ); r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, ®Free1); testcase( regFree1==0 ); sqlite3VdbeAddOp2(v, op, r1, inReg); break; } case TK_ISNULL: case TK_NOTNULL: { int addr; assert( TK_ISNULL==OP_IsNull ); testcase( op==TK_ISNULL ); assert( TK_NOTNULL==OP_NotNull ); testcase( op==TK_NOTNULL ); sqlite3VdbeAddOp2(v, OP_Integer, 1, target); r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, ®Free1); testcase( regFree1==0 ); addr = sqlite3VdbeAddOp1(v, op, r1); VdbeCoverageIf(v, op==TK_ISNULL); VdbeCoverageIf(v, op==TK_NOTNULL); sqlite3VdbeAddOp2(v, OP_Integer, 0, target); sqlite3VdbeJumpHere(v, addr); break; } case TK_AGG_FUNCTION: { AggInfo *pInfo = pExpr->pAggInfo; if( pInfo==0 ){ assert( !ExprHasProperty(pExpr, EP_IntValue) ); sqlite3ErrorMsg(pParse, "misuse of aggregate: %s()", pExpr->u.zToken); }else{ return pInfo->aFunc[pExpr->iAgg].iMem; } break; } case TK_FUNCTION: { ExprList *pFarg; /* List of function arguments */ int nFarg; /* Number of function arguments */ FuncDef *pDef; /* The function definition object */ const char *zId; /* The function name */ u32 constMask = 0; /* Mask of function arguments that are constant */ int i; /* Loop counter */ sqlite3 *db = pParse->db; /* The database connection */ u8 enc = ENC(db); /* The text encoding used by this database */ CollSeq *pColl = 0; /* A collating sequence */ assert( !ExprHasProperty(pExpr, EP_xIsSelect) ); if( ExprHasProperty(pExpr, EP_TokenOnly) ){ pFarg = 0; }else{ pFarg = pExpr->x.pList; } nFarg = pFarg ? pFarg->nExpr : 0; assert( !ExprHasProperty(pExpr, EP_IntValue) ); zId = pExpr->u.zToken; pDef = sqlite3FindFunction(db, zId, nFarg, enc, 0); #ifdef SQLITE_ENABLE_UNKNOWN_SQL_FUNCTION if( pDef==0 && pParse->explain ){ pDef = sqlite3FindFunction(db, "unknown", nFarg, enc, 0); } #endif if( pDef==0 || pDef->xFinalize!=0 ){ sqlite3ErrorMsg(pParse, "unknown function: %s()", zId); break; } /* Attempt a direct implementation of the built-in COALESCE() and ** IFNULL() functions. This avoids unnecessary evaluation of ** arguments past the first non-NULL argument. */ if( pDef->funcFlags & SQLITE_FUNC_COALESCE ){ int endCoalesce = sqlite3VdbeMakeLabel(v); assert( nFarg>=2 ); sqlite3ExprCode(pParse, pFarg->a[0].pExpr, target); for(i=1; ia[i].pExpr, target); sqlite3ExprCachePop(pParse); } sqlite3VdbeResolveLabel(v, endCoalesce); break; } /* The UNLIKELY() function is a no-op. The result is the value ** of the first argument. */ if( pDef->funcFlags & SQLITE_FUNC_UNLIKELY ){ assert( nFarg>=1 ); return sqlite3ExprCodeTarget(pParse, pFarg->a[0].pExpr, target); } for(i=0; ia[i].pExpr) ){ testcase( i==31 ); constMask |= MASKBIT32(i); } if( (pDef->funcFlags & SQLITE_FUNC_NEEDCOLL)!=0 && !pColl ){ pColl = sqlite3ExprCollSeq(pParse, pFarg->a[i].pExpr); } } if( pFarg ){ if( constMask ){ r1 = pParse->nMem+1; pParse->nMem += nFarg; }else{ r1 = sqlite3GetTempRange(pParse, nFarg); } /* For length() and typeof() functions with a column argument, ** set the P5 parameter to the OP_Column opcode to OPFLAG_LENGTHARG ** or OPFLAG_TYPEOFARG respectively, to avoid unnecessary data ** loading. */ if( (pDef->funcFlags & (SQLITE_FUNC_LENGTH|SQLITE_FUNC_TYPEOF))!=0 ){ u8 exprOp; assert( nFarg==1 ); assert( pFarg->a[0].pExpr!=0 ); exprOp = pFarg->a[0].pExpr->op; if( exprOp==TK_COLUMN || exprOp==TK_AGG_COLUMN ){ assert( SQLITE_FUNC_LENGTH==OPFLAG_LENGTHARG ); assert( SQLITE_FUNC_TYPEOF==OPFLAG_TYPEOFARG ); testcase( pDef->funcFlags & OPFLAG_LENGTHARG ); pFarg->a[0].pExpr->op2 = pDef->funcFlags & (OPFLAG_LENGTHARG|OPFLAG_TYPEOFARG); } } sqlite3ExprCachePush(pParse); /* Ticket 2ea2425d34be */ sqlite3ExprCodeExprList(pParse, pFarg, r1, 0, SQLITE_ECEL_DUP|SQLITE_ECEL_FACTOR); sqlite3ExprCachePop(pParse); /* Ticket 2ea2425d34be */ }else{ r1 = 0; } #ifndef SQLITE_OMIT_VIRTUALTABLE /* Possibly overload the function if the first argument is ** a virtual table column. ** ** For infix functions (LIKE, GLOB, REGEXP, and MATCH) use the ** second argument, not the first, as the argument to test to ** see if it is a column in a virtual table. This is done because ** the left operand of infix functions (the operand we want to ** control overloading) ends up as the second argument to the ** function. The expression "A glob B" is equivalent to ** "glob(B,A). We want to use the A in "A glob B" to test ** for function overloading. But we use the B term in "glob(B,A)". */ if( nFarg>=2 && (pExpr->flags & EP_InfixFunc) ){ pDef = sqlite3VtabOverloadFunction(db, pDef, nFarg, pFarg->a[1].pExpr); }else if( nFarg>0 ){ pDef = sqlite3VtabOverloadFunction(db, pDef, nFarg, pFarg->a[0].pExpr); } #endif if( pDef->funcFlags & SQLITE_FUNC_NEEDCOLL ){ if( !pColl ) pColl = db->pDfltColl; sqlite3VdbeAddOp4(v, OP_CollSeq, 0, 0, 0, (char *)pColl, P4_COLLSEQ); } sqlite3VdbeAddOp4(v, OP_Function0, constMask, r1, target, (char*)pDef, P4_FUNCDEF); sqlite3VdbeChangeP5(v, (u8)nFarg); if( nFarg && constMask==0 ){ sqlite3ReleaseTempRange(pParse, r1, nFarg); } return target; } #ifndef SQLITE_OMIT_SUBQUERY case TK_EXISTS: case TK_SELECT: { int nCol; testcase( op==TK_EXISTS ); testcase( op==TK_SELECT ); if( op==TK_SELECT && (nCol = pExpr->x.pSelect->pEList->nExpr)!=1 ){ sqlite3SubselectError(pParse, nCol, 1); }else{ return sqlite3CodeSubselect(pParse, pExpr, 0, 0); } break; } case TK_SELECT_COLUMN: { if( pExpr->pLeft->iTable==0 ){ pExpr->pLeft->iTable = sqlite3CodeSubselect(pParse, pExpr->pLeft, 0, 0); } return pExpr->pLeft->iTable + pExpr->iColumn; } case TK_IN: { int destIfFalse = sqlite3VdbeMakeLabel(v); int destIfNull = sqlite3VdbeMakeLabel(v); sqlite3VdbeAddOp2(v, OP_Null, 0, target); sqlite3ExprCodeIN(pParse, pExpr, destIfFalse, destIfNull); sqlite3VdbeAddOp2(v, OP_Integer, 1, target); sqlite3VdbeResolveLabel(v, destIfFalse); sqlite3VdbeAddOp2(v, OP_AddImm, target, 0); sqlite3VdbeResolveLabel(v, destIfNull); return target; } #endif /* SQLITE_OMIT_SUBQUERY */ /* ** x BETWEEN y AND z ** ** This is equivalent to ** ** x>=y AND x<=z ** ** X is stored in pExpr->pLeft. ** Y is stored in pExpr->pList->a[0].pExpr. ** Z is stored in pExpr->pList->a[1].pExpr. */ case TK_BETWEEN: { exprCodeBetween(pParse, pExpr, target, 0, 0); return target; } case TK_SPAN: case TK_COLLATE: case TK_UPLUS: { return sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target); } case TK_TRIGGER: { /* If the opcode is TK_TRIGGER, then the expression is a reference ** to a column in the new.* or old.* pseudo-tables available to ** trigger programs. In this case Expr.iTable is set to 1 for the ** new.* pseudo-table, or 0 for the old.* pseudo-table. Expr.iColumn ** is set to the column of the pseudo-table to read, or to -1 to ** read the rowid field. ** ** The expression is implemented using an OP_Param opcode. The p1 ** parameter is set to 0 for an old.rowid reference, or to (i+1) ** to reference another column of the old.* pseudo-table, where ** i is the index of the column. For a new.rowid reference, p1 is ** set to (n+1), where n is the number of columns in each pseudo-table. ** For a reference to any other column in the new.* pseudo-table, p1 ** is set to (n+2+i), where n and i are as defined previously. For ** example, if the table on which triggers are being fired is ** declared as: ** ** CREATE TABLE t1(a, b); ** ** Then p1 is interpreted as follows: ** ** p1==0 -> old.rowid p1==3 -> new.rowid ** p1==1 -> old.a p1==4 -> new.a ** p1==2 -> old.b p1==5 -> new.b */ Table *pTab = pExpr->pTab; int p1 = pExpr->iTable * (pTab->nCol+1) + 1 + pExpr->iColumn; assert( pExpr->iTable==0 || pExpr->iTable==1 ); assert( pExpr->iColumn>=-1 && pExpr->iColumnnCol ); assert( pTab->iPKey<0 || pExpr->iColumn!=pTab->iPKey ); assert( p1>=0 && p1<(pTab->nCol*2+2) ); sqlite3VdbeAddOp2(v, OP_Param, p1, target); VdbeComment((v, "%s.%s -> $%d", (pExpr->iTable ? "new" : "old"), (pExpr->iColumn<0 ? "rowid" : pExpr->pTab->aCol[pExpr->iColumn].zName), target )); #ifndef SQLITE_OMIT_FLOATING_POINT /* If the column has REAL affinity, it may currently be stored as an ** integer. Use OP_RealAffinity to make sure it is really real. ** ** EVIDENCE-OF: R-60985-57662 SQLite will convert the value back to ** floating point when extracting it from the record. */ if( pExpr->iColumn>=0 && pTab->aCol[pExpr->iColumn].affinity==SQLITE_AFF_REAL ){ sqlite3VdbeAddOp1(v, OP_RealAffinity, target); } #endif break; } case TK_VECTOR: { sqlite3ErrorMsg(pParse, "row value misused"); break; } /* ** Form A: ** CASE x WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END ** ** Form B: ** CASE WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END ** ** Form A is can be transformed into the equivalent form B as follows: ** CASE WHEN x=e1 THEN r1 WHEN x=e2 THEN r2 ... ** WHEN x=eN THEN rN ELSE y END ** ** X (if it exists) is in pExpr->pLeft. ** Y is in the last element of pExpr->x.pList if pExpr->x.pList->nExpr is ** odd. The Y is also optional. If the number of elements in x.pList ** is even, then Y is omitted and the "otherwise" result is NULL. ** Ei is in pExpr->pList->a[i*2] and Ri is pExpr->pList->a[i*2+1]. ** ** The result of the expression is the Ri for the first matching Ei, ** or if there is no matching Ei, the ELSE term Y, or if there is ** no ELSE term, NULL. */ default: assert( op==TK_CASE ); { int endLabel; /* GOTO label for end of CASE stmt */ int nextCase; /* GOTO label for next WHEN clause */ int nExpr; /* 2x number of WHEN terms */ int i; /* Loop counter */ ExprList *pEList; /* List of WHEN terms */ struct ExprList_item *aListelem; /* Array of WHEN terms */ Expr opCompare; /* The X==Ei expression */ Expr *pX; /* The X expression */ Expr *pTest = 0; /* X==Ei (form A) or just Ei (form B) */ VVA_ONLY( int iCacheLevel = pParse->iCacheLevel; ) assert( !ExprHasProperty(pExpr, EP_xIsSelect) && pExpr->x.pList ); assert(pExpr->x.pList->nExpr > 0); pEList = pExpr->x.pList; aListelem = pEList->a; nExpr = pEList->nExpr; endLabel = sqlite3VdbeMakeLabel(v); if( (pX = pExpr->pLeft)!=0 ){ tempX = *pX; testcase( pX->op==TK_COLUMN ); exprToRegister(&tempX, exprCodeVector(pParse, &tempX, ®Free1)); testcase( regFree1==0 ); memset(&opCompare, 0, sizeof(opCompare)); opCompare.op = TK_EQ; opCompare.pLeft = &tempX; pTest = &opCompare; /* Ticket b351d95f9cd5ef17e9d9dbae18f5ca8611190001: ** The value in regFree1 might get SCopy-ed into the file result. ** So make sure that the regFree1 register is not reused for other ** purposes and possibly overwritten. */ regFree1 = 0; } for(i=0; iop==TK_COLUMN ); sqlite3ExprIfFalse(pParse, pTest, nextCase, SQLITE_JUMPIFNULL); testcase( aListelem[i+1].pExpr->op==TK_COLUMN ); sqlite3ExprCode(pParse, aListelem[i+1].pExpr, target); sqlite3VdbeGoto(v, endLabel); sqlite3ExprCachePop(pParse); sqlite3VdbeResolveLabel(v, nextCase); } if( (nExpr&1)!=0 ){ sqlite3ExprCachePush(pParse); sqlite3ExprCode(pParse, pEList->a[nExpr-1].pExpr, target); sqlite3ExprCachePop(pParse); }else{ sqlite3VdbeAddOp2(v, OP_Null, 0, target); } assert( pParse->db->mallocFailed || pParse->nErr>0 || pParse->iCacheLevel==iCacheLevel ); sqlite3VdbeResolveLabel(v, endLabel); break; } #ifndef SQLITE_OMIT_TRIGGER case TK_RAISE: { assert( pExpr->affinity==OE_Rollback || pExpr->affinity==OE_Abort || pExpr->affinity==OE_Fail || pExpr->affinity==OE_Ignore ); if( !pParse->pTriggerTab ){ sqlite3ErrorMsg(pParse, "RAISE() may only be used within a trigger-program"); return 0; } if( pExpr->affinity==OE_Abort ){ sqlite3MayAbort(pParse); } assert( !ExprHasProperty(pExpr, EP_IntValue) ); if( pExpr->affinity==OE_Ignore ){ sqlite3VdbeAddOp4( v, OP_Halt, SQLITE_OK, OE_Ignore, 0, pExpr->u.zToken,0); VdbeCoverage(v); }else{ sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_TRIGGER, pExpr->affinity, pExpr->u.zToken, 0, 0); } break; } #endif } sqlite3ReleaseTempReg(pParse, regFree1); sqlite3ReleaseTempReg(pParse, regFree2); return inReg; } /* ** Factor out the code of the given expression to initialization time. */ SQLITE_PRIVATE void sqlite3ExprCodeAtInit( Parse *pParse, /* Parsing context */ Expr *pExpr, /* The expression to code when the VDBE initializes */ int regDest, /* Store the value in this register */ u8 reusable /* True if this expression is reusable */ ){ ExprList *p; assert( ConstFactorOk(pParse) ); p = pParse->pConstExpr; pExpr = sqlite3ExprDup(pParse->db, pExpr, 0); p = sqlite3ExprListAppend(pParse, p, pExpr); if( p ){ struct ExprList_item *pItem = &p->a[p->nExpr-1]; pItem->u.iConstExprReg = regDest; pItem->reusable = reusable; } pParse->pConstExpr = p; } /* ** Generate code to evaluate an expression and store the results ** into a register. Return the register number where the results ** are stored. ** ** If the register is a temporary register that can be deallocated, ** then write its number into *pReg. If the result register is not ** a temporary, then set *pReg to zero. ** ** If pExpr is a constant, then this routine might generate this ** code to fill the register in the initialization section of the ** VDBE program, in order to factor it out of the evaluation loop. */ SQLITE_PRIVATE int sqlite3ExprCodeTemp(Parse *pParse, Expr *pExpr, int *pReg){ int r2; pExpr = sqlite3ExprSkipCollate(pExpr); if( ConstFactorOk(pParse) && pExpr->op!=TK_REGISTER && sqlite3ExprIsConstantNotJoin(pExpr) ){ ExprList *p = pParse->pConstExpr; int i; *pReg = 0; if( p ){ struct ExprList_item *pItem; for(pItem=p->a, i=p->nExpr; i>0; pItem++, i--){ if( pItem->reusable && sqlite3ExprCompare(pItem->pExpr,pExpr,-1)==0 ){ return pItem->u.iConstExprReg; } } } r2 = ++pParse->nMem; sqlite3ExprCodeAtInit(pParse, pExpr, r2, 1); }else{ int r1 = sqlite3GetTempReg(pParse); r2 = sqlite3ExprCodeTarget(pParse, pExpr, r1); if( r2==r1 ){ *pReg = r1; }else{ sqlite3ReleaseTempReg(pParse, r1); *pReg = 0; } } return r2; } /* ** Generate code that will evaluate expression pExpr and store the ** results in register target. The results are guaranteed to appear ** in register target. */ SQLITE_PRIVATE void sqlite3ExprCode(Parse *pParse, Expr *pExpr, int target){ int inReg; assert( target>0 && target<=pParse->nMem ); if( pExpr && pExpr->op==TK_REGISTER ){ sqlite3VdbeAddOp2(pParse->pVdbe, OP_Copy, pExpr->iTable, target); }else{ inReg = sqlite3ExprCodeTarget(pParse, pExpr, target); assert( pParse->pVdbe!=0 || pParse->db->mallocFailed ); if( inReg!=target && pParse->pVdbe ){ sqlite3VdbeAddOp2(pParse->pVdbe, OP_SCopy, inReg, target); } } } /* ** Make a transient copy of expression pExpr and then code it using ** sqlite3ExprCode(). This routine works just like sqlite3ExprCode() ** except that the input expression is guaranteed to be unchanged. */ SQLITE_PRIVATE void sqlite3ExprCodeCopy(Parse *pParse, Expr *pExpr, int target){ sqlite3 *db = pParse->db; pExpr = sqlite3ExprDup(db, pExpr, 0); if( !db->mallocFailed ) sqlite3ExprCode(pParse, pExpr, target); sqlite3ExprDelete(db, pExpr); } /* ** Generate code that will evaluate expression pExpr and store the ** results in register target. The results are guaranteed to appear ** in register target. If the expression is constant, then this routine ** might choose to code the expression at initialization time. */ SQLITE_PRIVATE void sqlite3ExprCodeFactorable(Parse *pParse, Expr *pExpr, int target){ if( pParse->okConstFactor && sqlite3ExprIsConstant(pExpr) ){ sqlite3ExprCodeAtInit(pParse, pExpr, target, 0); }else{ sqlite3ExprCode(pParse, pExpr, target); } } /* ** Generate code that evaluates the given expression and puts the result ** in register target. ** ** Also make a copy of the expression results into another "cache" register ** and modify the expression so that the next time it is evaluated, ** the result is a copy of the cache register. ** ** This routine is used for expressions that are used multiple ** times. They are evaluated once and the results of the expression ** are reused. */ SQLITE_PRIVATE void sqlite3ExprCodeAndCache(Parse *pParse, Expr *pExpr, int target){ Vdbe *v = pParse->pVdbe; int iMem; assert( target>0 ); assert( pExpr->op!=TK_REGISTER ); sqlite3ExprCode(pParse, pExpr, target); iMem = ++pParse->nMem; sqlite3VdbeAddOp2(v, OP_Copy, target, iMem); exprToRegister(pExpr, iMem); } /* ** Generate code that pushes the value of every element of the given ** expression list into a sequence of registers beginning at target. ** ** Return the number of elements evaluated. ** ** The SQLITE_ECEL_DUP flag prevents the arguments from being ** filled using OP_SCopy. OP_Copy must be used instead. ** ** The SQLITE_ECEL_FACTOR argument allows constant arguments to be ** factored out into initialization code. ** ** The SQLITE_ECEL_REF flag means that expressions in the list with ** ExprList.a[].u.x.iOrderByCol>0 have already been evaluated and stored ** in registers at srcReg, and so the value can be copied from there. */ SQLITE_PRIVATE int sqlite3ExprCodeExprList( Parse *pParse, /* Parsing context */ ExprList *pList, /* The expression list to be coded */ int target, /* Where to write results */ int srcReg, /* Source registers if SQLITE_ECEL_REF */ u8 flags /* SQLITE_ECEL_* flags */ ){ struct ExprList_item *pItem; int i, j, n; u8 copyOp = (flags & SQLITE_ECEL_DUP) ? OP_Copy : OP_SCopy; Vdbe *v = pParse->pVdbe; assert( pList!=0 ); assert( target>0 ); assert( pParse->pVdbe!=0 ); /* Never gets this far otherwise */ n = pList->nExpr; if( !ConstFactorOk(pParse) ) flags &= ~SQLITE_ECEL_FACTOR; for(pItem=pList->a, i=0; ipExpr; if( (flags & SQLITE_ECEL_REF)!=0 && (j = pList->a[i].u.x.iOrderByCol)>0 ){ sqlite3VdbeAddOp2(v, copyOp, j+srcReg-1, target+i); }else if( (flags & SQLITE_ECEL_FACTOR)!=0 && sqlite3ExprIsConstant(pExpr) ){ sqlite3ExprCodeAtInit(pParse, pExpr, target+i, 0); }else{ int inReg = sqlite3ExprCodeTarget(pParse, pExpr, target+i); if( inReg!=target+i ){ VdbeOp *pOp; if( copyOp==OP_Copy && (pOp=sqlite3VdbeGetOp(v, -1))->opcode==OP_Copy && pOp->p1+pOp->p3+1==inReg && pOp->p2+pOp->p3+1==target+i ){ pOp->p3++; }else{ sqlite3VdbeAddOp2(v, copyOp, inReg, target+i); } } } } return n; } /* ** Generate code for a BETWEEN operator. ** ** x BETWEEN y AND z ** ** The above is equivalent to ** ** x>=y AND x<=z ** ** Code it as such, taking care to do the common subexpression ** elimination of x. ** ** The xJumpIf parameter determines details: ** ** NULL: Store the boolean result in reg[dest] ** sqlite3ExprIfTrue: Jump to dest if true ** sqlite3ExprIfFalse: Jump to dest if false ** ** The jumpIfNull parameter is ignored if xJumpIf is NULL. */ static void exprCodeBetween( Parse *pParse, /* Parsing and code generating context */ Expr *pExpr, /* The BETWEEN expression */ int dest, /* Jump destination or storage location */ void (*xJump)(Parse*,Expr*,int,int), /* Action to take */ int jumpIfNull /* Take the jump if the BETWEEN is NULL */ ){ Expr exprAnd; /* The AND operator in x>=y AND x<=z */ Expr compLeft; /* The x>=y term */ Expr compRight; /* The x<=z term */ Expr exprX; /* The x subexpression */ int regFree1 = 0; /* Temporary use register */ memset(&compLeft, 0, sizeof(Expr)); memset(&compRight, 0, sizeof(Expr)); memset(&exprAnd, 0, sizeof(Expr)); assert( !ExprHasProperty(pExpr, EP_xIsSelect) ); exprX = *pExpr->pLeft; exprAnd.op = TK_AND; exprAnd.pLeft = &compLeft; exprAnd.pRight = &compRight; compLeft.op = TK_GE; compLeft.pLeft = &exprX; compLeft.pRight = pExpr->x.pList->a[0].pExpr; compRight.op = TK_LE; compRight.pLeft = &exprX; compRight.pRight = pExpr->x.pList->a[1].pExpr; exprToRegister(&exprX, exprCodeVector(pParse, &exprX, ®Free1)); if( xJump ){ xJump(pParse, &exprAnd, dest, jumpIfNull); }else{ exprX.flags |= EP_FromJoin; sqlite3ExprCodeTarget(pParse, &exprAnd, dest); } sqlite3ReleaseTempReg(pParse, regFree1); /* Ensure adequate test coverage */ testcase( xJump==sqlite3ExprIfTrue && jumpIfNull==0 && regFree1==0 ); testcase( xJump==sqlite3ExprIfTrue && jumpIfNull==0 && regFree1!=0 ); testcase( xJump==sqlite3ExprIfTrue && jumpIfNull!=0 && regFree1==0 ); testcase( xJump==sqlite3ExprIfTrue && jumpIfNull!=0 && regFree1!=0 ); testcase( xJump==sqlite3ExprIfFalse && jumpIfNull==0 && regFree1==0 ); testcase( xJump==sqlite3ExprIfFalse && jumpIfNull==0 && regFree1!=0 ); testcase( xJump==sqlite3ExprIfFalse && jumpIfNull!=0 && regFree1==0 ); testcase( xJump==sqlite3ExprIfFalse && jumpIfNull!=0 && regFree1!=0 ); testcase( xJump==0 ); } /* ** Generate code for a boolean expression such that a jump is made ** to the label "dest" if the expression is true but execution ** continues straight thru if the expression is false. ** ** If the expression evaluates to NULL (neither true nor false), then ** take the jump if the jumpIfNull flag is SQLITE_JUMPIFNULL. ** ** This code depends on the fact that certain token values (ex: TK_EQ) ** are the same as opcode values (ex: OP_Eq) that implement the corresponding ** operation. Special comments in vdbe.c and the mkopcodeh.awk script in ** the make process cause these values to align. Assert()s in the code ** below verify that the numbers are aligned correctly. */ SQLITE_PRIVATE void sqlite3ExprIfTrue(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){ Vdbe *v = pParse->pVdbe; int op = 0; int regFree1 = 0; int regFree2 = 0; int r1, r2; assert( jumpIfNull==SQLITE_JUMPIFNULL || jumpIfNull==0 ); if( NEVER(v==0) ) return; /* Existence of VDBE checked by caller */ if( NEVER(pExpr==0) ) return; /* No way this can happen */ op = pExpr->op; switch( op ){ case TK_AND: { int d2 = sqlite3VdbeMakeLabel(v); testcase( jumpIfNull==0 ); sqlite3ExprIfFalse(pParse, pExpr->pLeft, d2,jumpIfNull^SQLITE_JUMPIFNULL); sqlite3ExprCachePush(pParse); sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull); sqlite3VdbeResolveLabel(v, d2); sqlite3ExprCachePop(pParse); break; } case TK_OR: { testcase( jumpIfNull==0 ); sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull); sqlite3ExprCachePush(pParse); sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull); sqlite3ExprCachePop(pParse); break; } case TK_NOT: { testcase( jumpIfNull==0 ); sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull); break; } case TK_IS: case TK_ISNOT: testcase( op==TK_IS ); testcase( op==TK_ISNOT ); op = (op==TK_IS) ? TK_EQ : TK_NE; jumpIfNull = SQLITE_NULLEQ; /* Fall thru */ case TK_LT: case TK_LE: case TK_GT: case TK_GE: case TK_NE: case TK_EQ: { if( sqlite3ExprIsVector(pExpr->pLeft) ) goto default_expr; testcase( jumpIfNull==0 ); r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, ®Free1); r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, ®Free2); codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op, r1, r2, dest, jumpIfNull); assert(TK_LT==OP_Lt); testcase(op==OP_Lt); VdbeCoverageIf(v,op==OP_Lt); assert(TK_LE==OP_Le); testcase(op==OP_Le); VdbeCoverageIf(v,op==OP_Le); assert(TK_GT==OP_Gt); testcase(op==OP_Gt); VdbeCoverageIf(v,op==OP_Gt); assert(TK_GE==OP_Ge); testcase(op==OP_Ge); VdbeCoverageIf(v,op==OP_Ge); assert(TK_EQ==OP_Eq); testcase(op==OP_Eq); VdbeCoverageIf(v, op==OP_Eq && jumpIfNull==SQLITE_NULLEQ); VdbeCoverageIf(v, op==OP_Eq && jumpIfNull!=SQLITE_NULLEQ); assert(TK_NE==OP_Ne); testcase(op==OP_Ne); VdbeCoverageIf(v, op==OP_Ne && jumpIfNull==SQLITE_NULLEQ); VdbeCoverageIf(v, op==OP_Ne && jumpIfNull!=SQLITE_NULLEQ); testcase( regFree1==0 ); testcase( regFree2==0 ); break; } case TK_ISNULL: case TK_NOTNULL: { assert( TK_ISNULL==OP_IsNull ); testcase( op==TK_ISNULL ); assert( TK_NOTNULL==OP_NotNull ); testcase( op==TK_NOTNULL ); r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, ®Free1); sqlite3VdbeAddOp2(v, op, r1, dest); VdbeCoverageIf(v, op==TK_ISNULL); VdbeCoverageIf(v, op==TK_NOTNULL); testcase( regFree1==0 ); break; } case TK_BETWEEN: { testcase( jumpIfNull==0 ); exprCodeBetween(pParse, pExpr, dest, sqlite3ExprIfTrue, jumpIfNull); break; } #ifndef SQLITE_OMIT_SUBQUERY case TK_IN: { int destIfFalse = sqlite3VdbeMakeLabel(v); int destIfNull = jumpIfNull ? dest : destIfFalse; sqlite3ExprCodeIN(pParse, pExpr, destIfFalse, destIfNull); sqlite3VdbeGoto(v, dest); sqlite3VdbeResolveLabel(v, destIfFalse); break; } #endif default: { default_expr: if( exprAlwaysTrue(pExpr) ){ sqlite3VdbeGoto(v, dest); }else if( exprAlwaysFalse(pExpr) ){ /* No-op */ }else{ r1 = sqlite3ExprCodeTemp(pParse, pExpr, ®Free1); sqlite3VdbeAddOp3(v, OP_If, r1, dest, jumpIfNull!=0); VdbeCoverage(v); testcase( regFree1==0 ); testcase( jumpIfNull==0 ); } break; } } sqlite3ReleaseTempReg(pParse, regFree1); sqlite3ReleaseTempReg(pParse, regFree2); } /* ** Generate code for a boolean expression such that a jump is made ** to the label "dest" if the expression is false but execution ** continues straight thru if the expression is true. ** ** If the expression evaluates to NULL (neither true nor false) then ** jump if jumpIfNull is SQLITE_JUMPIFNULL or fall through if jumpIfNull ** is 0. */ SQLITE_PRIVATE void sqlite3ExprIfFalse(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){ Vdbe *v = pParse->pVdbe; int op = 0; int regFree1 = 0; int regFree2 = 0; int r1, r2; assert( jumpIfNull==SQLITE_JUMPIFNULL || jumpIfNull==0 ); if( NEVER(v==0) ) return; /* Existence of VDBE checked by caller */ if( pExpr==0 ) return; /* The value of pExpr->op and op are related as follows: ** ** pExpr->op op ** --------- ---------- ** TK_ISNULL OP_NotNull ** TK_NOTNULL OP_IsNull ** TK_NE OP_Eq ** TK_EQ OP_Ne ** TK_GT OP_Le ** TK_LE OP_Gt ** TK_GE OP_Lt ** TK_LT OP_Ge ** ** For other values of pExpr->op, op is undefined and unused. ** The value of TK_ and OP_ constants are arranged such that we ** can compute the mapping above using the following expression. ** Assert()s verify that the computation is correct. */ op = ((pExpr->op+(TK_ISNULL&1))^1)-(TK_ISNULL&1); /* Verify correct alignment of TK_ and OP_ constants */ assert( pExpr->op!=TK_ISNULL || op==OP_NotNull ); assert( pExpr->op!=TK_NOTNULL || op==OP_IsNull ); assert( pExpr->op!=TK_NE || op==OP_Eq ); assert( pExpr->op!=TK_EQ || op==OP_Ne ); assert( pExpr->op!=TK_LT || op==OP_Ge ); assert( pExpr->op!=TK_LE || op==OP_Gt ); assert( pExpr->op!=TK_GT || op==OP_Le ); assert( pExpr->op!=TK_GE || op==OP_Lt ); switch( pExpr->op ){ case TK_AND: { testcase( jumpIfNull==0 ); sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull); sqlite3ExprCachePush(pParse); sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull); sqlite3ExprCachePop(pParse); break; } case TK_OR: { int d2 = sqlite3VdbeMakeLabel(v); testcase( jumpIfNull==0 ); sqlite3ExprIfTrue(pParse, pExpr->pLeft, d2, jumpIfNull^SQLITE_JUMPIFNULL); sqlite3ExprCachePush(pParse); sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull); sqlite3VdbeResolveLabel(v, d2); sqlite3ExprCachePop(pParse); break; } case TK_NOT: { testcase( jumpIfNull==0 ); sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull); break; } case TK_IS: case TK_ISNOT: testcase( pExpr->op==TK_IS ); testcase( pExpr->op==TK_ISNOT ); op = (pExpr->op==TK_IS) ? TK_NE : TK_EQ; jumpIfNull = SQLITE_NULLEQ; /* Fall thru */ case TK_LT: case TK_LE: case TK_GT: case TK_GE: case TK_NE: case TK_EQ: { if( sqlite3ExprIsVector(pExpr->pLeft) ) goto default_expr; testcase( jumpIfNull==0 ); r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, ®Free1); r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, ®Free2); codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op, r1, r2, dest, jumpIfNull); assert(TK_LT==OP_Lt); testcase(op==OP_Lt); VdbeCoverageIf(v,op==OP_Lt); assert(TK_LE==OP_Le); testcase(op==OP_Le); VdbeCoverageIf(v,op==OP_Le); assert(TK_GT==OP_Gt); testcase(op==OP_Gt); VdbeCoverageIf(v,op==OP_Gt); assert(TK_GE==OP_Ge); testcase(op==OP_Ge); VdbeCoverageIf(v,op==OP_Ge); assert(TK_EQ==OP_Eq); testcase(op==OP_Eq); VdbeCoverageIf(v, op==OP_Eq && jumpIfNull!=SQLITE_NULLEQ); VdbeCoverageIf(v, op==OP_Eq && jumpIfNull==SQLITE_NULLEQ); assert(TK_NE==OP_Ne); testcase(op==OP_Ne); VdbeCoverageIf(v, op==OP_Ne && jumpIfNull!=SQLITE_NULLEQ); VdbeCoverageIf(v, op==OP_Ne && jumpIfNull==SQLITE_NULLEQ); testcase( regFree1==0 ); testcase( regFree2==0 ); break; } case TK_ISNULL: case TK_NOTNULL: { r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, ®Free1); sqlite3VdbeAddOp2(v, op, r1, dest); testcase( op==TK_ISNULL ); VdbeCoverageIf(v, op==TK_ISNULL); testcase( op==TK_NOTNULL ); VdbeCoverageIf(v, op==TK_NOTNULL); testcase( regFree1==0 ); break; } case TK_BETWEEN: { testcase( jumpIfNull==0 ); exprCodeBetween(pParse, pExpr, dest, sqlite3ExprIfFalse, jumpIfNull); break; } #ifndef SQLITE_OMIT_SUBQUERY case TK_IN: { if( jumpIfNull ){ sqlite3ExprCodeIN(pParse, pExpr, dest, dest); }else{ int destIfNull = sqlite3VdbeMakeLabel(v); sqlite3ExprCodeIN(pParse, pExpr, dest, destIfNull); sqlite3VdbeResolveLabel(v, destIfNull); } break; } #endif default: { default_expr: if( exprAlwaysFalse(pExpr) ){ sqlite3VdbeGoto(v, dest); }else if( exprAlwaysTrue(pExpr) ){ /* no-op */ }else{ r1 = sqlite3ExprCodeTemp(pParse, pExpr, ®Free1); sqlite3VdbeAddOp3(v, OP_IfNot, r1, dest, jumpIfNull!=0); VdbeCoverage(v); testcase( regFree1==0 ); testcase( jumpIfNull==0 ); } break; } } sqlite3ReleaseTempReg(pParse, regFree1); sqlite3ReleaseTempReg(pParse, regFree2); } /* ** Like sqlite3ExprIfFalse() except that a copy is made of pExpr before ** code generation, and that copy is deleted after code generation. This ** ensures that the original pExpr is unchanged. */ SQLITE_PRIVATE void sqlite3ExprIfFalseDup(Parse *pParse, Expr *pExpr, int dest,int jumpIfNull){ sqlite3 *db = pParse->db; Expr *pCopy = sqlite3ExprDup(db, pExpr, 0); if( db->mallocFailed==0 ){ sqlite3ExprIfFalse(pParse, pCopy, dest, jumpIfNull); } sqlite3ExprDelete(db, pCopy); } /* ** Do a deep comparison of two expression trees. Return 0 if the two ** expressions are completely identical. Return 1 if they differ only ** by a COLLATE operator at the top level. Return 2 if there are differences ** other than the top-level COLLATE operator. ** ** If any subelement of pB has Expr.iTable==(-1) then it is allowed ** to compare equal to an equivalent element in pA with Expr.iTable==iTab. ** ** The pA side might be using TK_REGISTER. If that is the case and pB is ** not using TK_REGISTER but is otherwise equivalent, then still return 0. ** ** Sometimes this routine will return 2 even if the two expressions ** really are equivalent. If we cannot prove that the expressions are ** identical, we return 2 just to be safe. So if this routine ** returns 2, then you do not really know for certain if the two ** expressions are the same. But if you get a 0 or 1 return, then you ** can be sure the expressions are the same. In the places where ** this routine is used, it does not hurt to get an extra 2 - that ** just might result in some slightly slower code. But returning ** an incorrect 0 or 1 could lead to a malfunction. */ SQLITE_PRIVATE int sqlite3ExprCompare(Expr *pA, Expr *pB, int iTab){ u32 combinedFlags; if( pA==0 || pB==0 ){ return pB==pA ? 0 : 2; } combinedFlags = pA->flags | pB->flags; if( combinedFlags & EP_IntValue ){ if( (pA->flags&pB->flags&EP_IntValue)!=0 && pA->u.iValue==pB->u.iValue ){ return 0; } return 2; } if( pA->op!=pB->op ){ if( pA->op==TK_COLLATE && sqlite3ExprCompare(pA->pLeft, pB, iTab)<2 ){ return 1; } if( pB->op==TK_COLLATE && sqlite3ExprCompare(pA, pB->pLeft, iTab)<2 ){ return 1; } return 2; } if( pA->op!=TK_COLUMN && pA->op!=TK_AGG_COLUMN && pA->u.zToken ){ if( pA->op==TK_FUNCTION ){ if( sqlite3StrICmp(pA->u.zToken,pB->u.zToken)!=0 ) return 2; }else if( strcmp(pA->u.zToken,pB->u.zToken)!=0 ){ return pA->op==TK_COLLATE ? 1 : 2; } } if( (pA->flags & EP_Distinct)!=(pB->flags & EP_Distinct) ) return 2; if( ALWAYS((combinedFlags & EP_TokenOnly)==0) ){ if( combinedFlags & EP_xIsSelect ) return 2; if( sqlite3ExprCompare(pA->pLeft, pB->pLeft, iTab) ) return 2; if( sqlite3ExprCompare(pA->pRight, pB->pRight, iTab) ) return 2; if( sqlite3ExprListCompare(pA->x.pList, pB->x.pList, iTab) ) return 2; if( ALWAYS((combinedFlags & EP_Reduced)==0) && pA->op!=TK_STRING ){ if( pA->iColumn!=pB->iColumn ) return 2; if( pA->iTable!=pB->iTable && (pA->iTable!=iTab || NEVER(pB->iTable>=0)) ) return 2; } } return 0; } /* ** Compare two ExprList objects. Return 0 if they are identical and ** non-zero if they differ in any way. ** ** If any subelement of pB has Expr.iTable==(-1) then it is allowed ** to compare equal to an equivalent element in pA with Expr.iTable==iTab. ** ** This routine might return non-zero for equivalent ExprLists. The ** only consequence will be disabled optimizations. But this routine ** must never return 0 if the two ExprList objects are different, or ** a malfunction will result. ** ** Two NULL pointers are considered to be the same. But a NULL pointer ** always differs from a non-NULL pointer. */ SQLITE_PRIVATE int sqlite3ExprListCompare(ExprList *pA, ExprList *pB, int iTab){ int i; if( pA==0 && pB==0 ) return 0; if( pA==0 || pB==0 ) return 1; if( pA->nExpr!=pB->nExpr ) return 1; for(i=0; inExpr; i++){ Expr *pExprA = pA->a[i].pExpr; Expr *pExprB = pB->a[i].pExpr; if( pA->a[i].sortOrder!=pB->a[i].sortOrder ) return 1; if( sqlite3ExprCompare(pExprA, pExprB, iTab) ) return 1; } return 0; } /* ** Return true if we can prove the pE2 will always be true if pE1 is ** true. Return false if we cannot complete the proof or if pE2 might ** be false. Examples: ** ** pE1: x==5 pE2: x==5 Result: true ** pE1: x>0 pE2: x==5 Result: false ** pE1: x=21 pE2: x=21 OR y=43 Result: true ** pE1: x!=123 pE2: x IS NOT NULL Result: true ** pE1: x!=?1 pE2: x IS NOT NULL Result: true ** pE1: x IS NULL pE2: x IS NOT NULL Result: false ** pE1: x IS ?2 pE2: x IS NOT NULL Reuslt: false ** ** When comparing TK_COLUMN nodes between pE1 and pE2, if pE2 has ** Expr.iTable<0 then assume a table number given by iTab. ** ** When in doubt, return false. Returning true might give a performance ** improvement. Returning false might cause a performance reduction, but ** it will always give the correct answer and is hence always safe. */ SQLITE_PRIVATE int sqlite3ExprImpliesExpr(Expr *pE1, Expr *pE2, int iTab){ if( sqlite3ExprCompare(pE1, pE2, iTab)==0 ){ return 1; } if( pE2->op==TK_OR && (sqlite3ExprImpliesExpr(pE1, pE2->pLeft, iTab) || sqlite3ExprImpliesExpr(pE1, pE2->pRight, iTab) ) ){ return 1; } if( pE2->op==TK_NOTNULL && sqlite3ExprCompare(pE1->pLeft, pE2->pLeft, iTab)==0 && (pE1->op!=TK_ISNULL && pE1->op!=TK_IS) ){ return 1; } return 0; } /* ** An instance of the following structure is used by the tree walker ** to determine if an expression can be evaluated by reference to the ** index only, without having to do a search for the corresponding ** table entry. The IdxCover.pIdx field is the index. IdxCover.iCur ** is the cursor for the table. */ struct IdxCover { Index *pIdx; /* The index to be tested for coverage */ int iCur; /* Cursor number for the table corresponding to the index */ }; /* ** Check to see if there are references to columns in table ** pWalker->u.pIdxCover->iCur can be satisfied using the index ** pWalker->u.pIdxCover->pIdx. */ static int exprIdxCover(Walker *pWalker, Expr *pExpr){ if( pExpr->op==TK_COLUMN && pExpr->iTable==pWalker->u.pIdxCover->iCur && sqlite3ColumnOfIndex(pWalker->u.pIdxCover->pIdx, pExpr->iColumn)<0 ){ pWalker->eCode = 1; return WRC_Abort; } return WRC_Continue; } /* ** Determine if an index pIdx on table with cursor iCur contains will ** the expression pExpr. Return true if the index does cover the ** expression and false if the pExpr expression references table columns ** that are not found in the index pIdx. ** ** An index covering an expression means that the expression can be ** evaluated using only the index and without having to lookup the ** corresponding table entry. */ SQLITE_PRIVATE int sqlite3ExprCoveredByIndex( Expr *pExpr, /* The index to be tested */ int iCur, /* The cursor number for the corresponding table */ Index *pIdx /* The index that might be used for coverage */ ){ Walker w; struct IdxCover xcov; memset(&w, 0, sizeof(w)); xcov.iCur = iCur; xcov.pIdx = pIdx; w.xExprCallback = exprIdxCover; w.u.pIdxCover = &xcov; sqlite3WalkExpr(&w, pExpr); return !w.eCode; } /* ** An instance of the following structure is used by the tree walker ** to count references to table columns in the arguments of an ** aggregate function, in order to implement the ** sqlite3FunctionThisSrc() routine. */ struct SrcCount { SrcList *pSrc; /* One particular FROM clause in a nested query */ int nThis; /* Number of references to columns in pSrcList */ int nOther; /* Number of references to columns in other FROM clauses */ }; /* ** Count the number of references to columns. */ static int exprSrcCount(Walker *pWalker, Expr *pExpr){ /* The NEVER() on the second term is because sqlite3FunctionUsesThisSrc() ** is always called before sqlite3ExprAnalyzeAggregates() and so the ** TK_COLUMNs have not yet been converted into TK_AGG_COLUMN. If ** sqlite3FunctionUsesThisSrc() is used differently in the future, the ** NEVER() will need to be removed. */ if( pExpr->op==TK_COLUMN || NEVER(pExpr->op==TK_AGG_COLUMN) ){ int i; struct SrcCount *p = pWalker->u.pSrcCount; SrcList *pSrc = p->pSrc; int nSrc = pSrc ? pSrc->nSrc : 0; for(i=0; iiTable==pSrc->a[i].iCursor ) break; } if( inThis++; }else{ p->nOther++; } } return WRC_Continue; } /* ** Determine if any of the arguments to the pExpr Function reference ** pSrcList. Return true if they do. Also return true if the function ** has no arguments or has only constant arguments. Return false if pExpr ** references columns but not columns of tables found in pSrcList. */ SQLITE_PRIVATE int sqlite3FunctionUsesThisSrc(Expr *pExpr, SrcList *pSrcList){ Walker w; struct SrcCount cnt; assert( pExpr->op==TK_AGG_FUNCTION ); memset(&w, 0, sizeof(w)); w.xExprCallback = exprSrcCount; w.u.pSrcCount = &cnt; cnt.pSrc = pSrcList; cnt.nThis = 0; cnt.nOther = 0; sqlite3WalkExprList(&w, pExpr->x.pList); return cnt.nThis>0 || cnt.nOther==0; } /* ** Add a new element to the pAggInfo->aCol[] array. Return the index of ** the new element. Return a negative number if malloc fails. */ static int addAggInfoColumn(sqlite3 *db, AggInfo *pInfo){ int i; pInfo->aCol = sqlite3ArrayAllocate( db, pInfo->aCol, sizeof(pInfo->aCol[0]), &pInfo->nColumn, &i ); return i; } /* ** Add a new element to the pAggInfo->aFunc[] array. Return the index of ** the new element. Return a negative number if malloc fails. */ static int addAggInfoFunc(sqlite3 *db, AggInfo *pInfo){ int i; pInfo->aFunc = sqlite3ArrayAllocate( db, pInfo->aFunc, sizeof(pInfo->aFunc[0]), &pInfo->nFunc, &i ); return i; } /* ** This is the xExprCallback for a tree walker. It is used to ** implement sqlite3ExprAnalyzeAggregates(). See sqlite3ExprAnalyzeAggregates ** for additional information. */ static int analyzeAggregate(Walker *pWalker, Expr *pExpr){ int i; NameContext *pNC = pWalker->u.pNC; Parse *pParse = pNC->pParse; SrcList *pSrcList = pNC->pSrcList; AggInfo *pAggInfo = pNC->pAggInfo; switch( pExpr->op ){ case TK_AGG_COLUMN: case TK_COLUMN: { testcase( pExpr->op==TK_AGG_COLUMN ); testcase( pExpr->op==TK_COLUMN ); /* Check to see if the column is in one of the tables in the FROM ** clause of the aggregate query */ if( ALWAYS(pSrcList!=0) ){ struct SrcList_item *pItem = pSrcList->a; for(i=0; inSrc; i++, pItem++){ struct AggInfo_col *pCol; assert( !ExprHasProperty(pExpr, EP_TokenOnly|EP_Reduced) ); if( pExpr->iTable==pItem->iCursor ){ /* If we reach this point, it means that pExpr refers to a table ** that is in the FROM clause of the aggregate query. ** ** Make an entry for the column in pAggInfo->aCol[] if there ** is not an entry there already. */ int k; pCol = pAggInfo->aCol; for(k=0; knColumn; k++, pCol++){ if( pCol->iTable==pExpr->iTable && pCol->iColumn==pExpr->iColumn ){ break; } } if( (k>=pAggInfo->nColumn) && (k = addAggInfoColumn(pParse->db, pAggInfo))>=0 ){ pCol = &pAggInfo->aCol[k]; pCol->pTab = pExpr->pTab; pCol->iTable = pExpr->iTable; pCol->iColumn = pExpr->iColumn; pCol->iMem = ++pParse->nMem; pCol->iSorterColumn = -1; pCol->pExpr = pExpr; if( pAggInfo->pGroupBy ){ int j, n; ExprList *pGB = pAggInfo->pGroupBy; struct ExprList_item *pTerm = pGB->a; n = pGB->nExpr; for(j=0; jpExpr; if( pE->op==TK_COLUMN && pE->iTable==pExpr->iTable && pE->iColumn==pExpr->iColumn ){ pCol->iSorterColumn = j; break; } } } if( pCol->iSorterColumn<0 ){ pCol->iSorterColumn = pAggInfo->nSortingColumn++; } } /* There is now an entry for pExpr in pAggInfo->aCol[] (either ** because it was there before or because we just created it). ** Convert the pExpr to be a TK_AGG_COLUMN referring to that ** pAggInfo->aCol[] entry. */ ExprSetVVAProperty(pExpr, EP_NoReduce); pExpr->pAggInfo = pAggInfo; pExpr->op = TK_AGG_COLUMN; pExpr->iAgg = (i16)k; break; } /* endif pExpr->iTable==pItem->iCursor */ } /* end loop over pSrcList */ } return WRC_Prune; } case TK_AGG_FUNCTION: { if( (pNC->ncFlags & NC_InAggFunc)==0 && pWalker->walkerDepth==pExpr->op2 ){ /* Check to see if pExpr is a duplicate of another aggregate ** function that is already in the pAggInfo structure */ struct AggInfo_func *pItem = pAggInfo->aFunc; for(i=0; inFunc; i++, pItem++){ if( sqlite3ExprCompare(pItem->pExpr, pExpr, -1)==0 ){ break; } } if( i>=pAggInfo->nFunc ){ /* pExpr is original. Make a new entry in pAggInfo->aFunc[] */ u8 enc = ENC(pParse->db); i = addAggInfoFunc(pParse->db, pAggInfo); if( i>=0 ){ assert( !ExprHasProperty(pExpr, EP_xIsSelect) ); pItem = &pAggInfo->aFunc[i]; pItem->pExpr = pExpr; pItem->iMem = ++pParse->nMem; assert( !ExprHasProperty(pExpr, EP_IntValue) ); pItem->pFunc = sqlite3FindFunction(pParse->db, pExpr->u.zToken, pExpr->x.pList ? pExpr->x.pList->nExpr : 0, enc, 0); if( pExpr->flags & EP_Distinct ){ pItem->iDistinct = pParse->nTab++; }else{ pItem->iDistinct = -1; } } } /* Make pExpr point to the appropriate pAggInfo->aFunc[] entry */ assert( !ExprHasProperty(pExpr, EP_TokenOnly|EP_Reduced) ); ExprSetVVAProperty(pExpr, EP_NoReduce); pExpr->iAgg = (i16)i; pExpr->pAggInfo = pAggInfo; return WRC_Prune; }else{ return WRC_Continue; } } } return WRC_Continue; } static int analyzeAggregatesInSelect(Walker *pWalker, Select *pSelect){ UNUSED_PARAMETER(pWalker); UNUSED_PARAMETER(pSelect); return WRC_Continue; } /* ** Analyze the pExpr expression looking for aggregate functions and ** for variables that need to be added to AggInfo object that pNC->pAggInfo ** points to. Additional entries are made on the AggInfo object as ** necessary. ** ** This routine should only be called after the expression has been ** analyzed by sqlite3ResolveExprNames(). */ SQLITE_PRIVATE void sqlite3ExprAnalyzeAggregates(NameContext *pNC, Expr *pExpr){ Walker w; memset(&w, 0, sizeof(w)); w.xExprCallback = analyzeAggregate; w.xSelectCallback = analyzeAggregatesInSelect; w.u.pNC = pNC; assert( pNC->pSrcList!=0 ); sqlite3WalkExpr(&w, pExpr); } /* ** Call sqlite3ExprAnalyzeAggregates() for every expression in an ** expression list. Return the number of errors. ** ** If an error is found, the analysis is cut short. */ SQLITE_PRIVATE void sqlite3ExprAnalyzeAggList(NameContext *pNC, ExprList *pList){ struct ExprList_item *pItem; int i; if( pList ){ for(pItem=pList->a, i=0; inExpr; i++, pItem++){ sqlite3ExprAnalyzeAggregates(pNC, pItem->pExpr); } } } /* ** Allocate a single new register for use to hold some intermediate result. */ SQLITE_PRIVATE int sqlite3GetTempReg(Parse *pParse){ if( pParse->nTempReg==0 ){ return ++pParse->nMem; } return pParse->aTempReg[--pParse->nTempReg]; } /* ** Deallocate a register, making available for reuse for some other ** purpose. ** ** If a register is currently being used by the column cache, then ** the deallocation is deferred until the column cache line that uses ** the register becomes stale. */ SQLITE_PRIVATE void sqlite3ReleaseTempReg(Parse *pParse, int iReg){ if( iReg && pParse->nTempRegaTempReg) ){ int i; struct yColCache *p; for(i=0, p=pParse->aColCache; inColCache; i++, p++){ if( p->iReg==iReg ){ p->tempReg = 1; return; } } pParse->aTempReg[pParse->nTempReg++] = iReg; } } /* ** Allocate or deallocate a block of nReg consecutive registers. */ SQLITE_PRIVATE int sqlite3GetTempRange(Parse *pParse, int nReg){ int i, n; if( nReg==1 ) return sqlite3GetTempReg(pParse); i = pParse->iRangeReg; n = pParse->nRangeReg; if( nReg<=n ){ assert( !usedAsColumnCache(pParse, i, i+n-1) ); pParse->iRangeReg += nReg; pParse->nRangeReg -= nReg; }else{ i = pParse->nMem+1; pParse->nMem += nReg; } return i; } SQLITE_PRIVATE void sqlite3ReleaseTempRange(Parse *pParse, int iReg, int nReg){ if( nReg==1 ){ sqlite3ReleaseTempReg(pParse, iReg); return; } sqlite3ExprCacheRemove(pParse, iReg, nReg); if( nReg>pParse->nRangeReg ){ pParse->nRangeReg = nReg; pParse->iRangeReg = iReg; } } /* ** Mark all temporary registers as being unavailable for reuse. */ SQLITE_PRIVATE void sqlite3ClearTempRegCache(Parse *pParse){ pParse->nTempReg = 0; pParse->nRangeReg = 0; } /* ** Validate that no temporary register falls within the range of ** iFirst..iLast, inclusive. This routine is only call from within assert() ** statements. */ #ifdef SQLITE_DEBUG SQLITE_PRIVATE int sqlite3NoTempsInRange(Parse *pParse, int iFirst, int iLast){ int i; if( pParse->nRangeReg>0 && pParse->iRangeReg+pParse->nRangeRegiRangeReg>=iFirst ){ return 0; } for(i=0; inTempReg; i++){ if( pParse->aTempReg[i]>=iFirst && pParse->aTempReg[i]<=iLast ){ return 0; } } return 1; } #endif /* SQLITE_DEBUG */ /************** End of expr.c ************************************************/ /************** Begin file alter.c *******************************************/ /* ** 2005 February 15 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ************************************************************************* ** This file contains C code routines that used to generate VDBE code ** that implements the ALTER TABLE command. */ /* #include "sqliteInt.h" */ /* ** The code in this file only exists if we are not omitting the ** ALTER TABLE logic from the build. */ #ifndef SQLITE_OMIT_ALTERTABLE /* ** This function is used by SQL generated to implement the ** ALTER TABLE command. The first argument is the text of a CREATE TABLE or ** CREATE INDEX command. The second is a table name. The table name in ** the CREATE TABLE or CREATE INDEX statement is replaced with the third ** argument and the result returned. Examples: ** ** sqlite_rename_table('CREATE TABLE abc(a, b, c)', 'def') ** -> 'CREATE TABLE def(a, b, c)' ** ** sqlite_rename_table('CREATE INDEX i ON abc(a)', 'def') ** -> 'CREATE INDEX i ON def(a, b, c)' */ static void renameTableFunc( sqlite3_context *context, int NotUsed, sqlite3_value **argv ){ unsigned char const *zSql = sqlite3_value_text(argv[0]); unsigned char const *zTableName = sqlite3_value_text(argv[1]); int token; Token tname; unsigned char const *zCsr = zSql; int len = 0; char *zRet; sqlite3 *db = sqlite3_context_db_handle(context); UNUSED_PARAMETER(NotUsed); /* The principle used to locate the table name in the CREATE TABLE ** statement is that the table name is the first non-space token that ** is immediately followed by a TK_LP or TK_USING token. */ if( zSql ){ do { if( !*zCsr ){ /* Ran out of input before finding an opening bracket. Return NULL. */ return; } /* Store the token that zCsr points to in tname. */ tname.z = (char*)zCsr; tname.n = len; /* Advance zCsr to the next token. Store that token type in 'token', ** and its length in 'len' (to be used next iteration of this loop). */ do { zCsr += len; len = sqlite3GetToken(zCsr, &token); } while( token==TK_SPACE ); assert( len>0 ); } while( token!=TK_LP && token!=TK_USING ); zRet = sqlite3MPrintf(db, "%.*s\"%w\"%s", (int)(((u8*)tname.z) - zSql), zSql, zTableName, tname.z+tname.n); sqlite3_result_text(context, zRet, -1, SQLITE_DYNAMIC); } } /* ** This C function implements an SQL user function that is used by SQL code ** generated by the ALTER TABLE ... RENAME command to modify the definition ** of any foreign key constraints that use the table being renamed as the ** parent table. It is passed three arguments: ** ** 1) The complete text of the CREATE TABLE statement being modified, ** 2) The old name of the table being renamed, and ** 3) The new name of the table being renamed. ** ** It returns the new CREATE TABLE statement. For example: ** ** sqlite_rename_parent('CREATE TABLE t1(a REFERENCES t2)', 't2', 't3') ** -> 'CREATE TABLE t1(a REFERENCES t3)' */ #ifndef SQLITE_OMIT_FOREIGN_KEY static void renameParentFunc( sqlite3_context *context, int NotUsed, sqlite3_value **argv ){ sqlite3 *db = sqlite3_context_db_handle(context); char *zOutput = 0; char *zResult; unsigned char const *zInput = sqlite3_value_text(argv[0]); unsigned char const *zOld = sqlite3_value_text(argv[1]); unsigned char const *zNew = sqlite3_value_text(argv[2]); unsigned const char *z; /* Pointer to token */ int n; /* Length of token z */ int token; /* Type of token */ UNUSED_PARAMETER(NotUsed); if( zInput==0 || zOld==0 ) return; for(z=zInput; *z; z=z+n){ n = sqlite3GetToken(z, &token); if( token==TK_REFERENCES ){ char *zParent; do { z += n; n = sqlite3GetToken(z, &token); }while( token==TK_SPACE ); if( token==TK_ILLEGAL ) break; zParent = sqlite3DbStrNDup(db, (const char *)z, n); if( zParent==0 ) break; sqlite3Dequote(zParent); if( 0==sqlite3StrICmp((const char *)zOld, zParent) ){ char *zOut = sqlite3MPrintf(db, "%s%.*s\"%w\"", (zOutput?zOutput:""), (int)(z-zInput), zInput, (const char *)zNew ); sqlite3DbFree(db, zOutput); zOutput = zOut; zInput = &z[n]; } sqlite3DbFree(db, zParent); } } zResult = sqlite3MPrintf(db, "%s%s", (zOutput?zOutput:""), zInput), sqlite3_result_text(context, zResult, -1, SQLITE_DYNAMIC); sqlite3DbFree(db, zOutput); } #endif #ifndef SQLITE_OMIT_TRIGGER /* This function is used by SQL generated to implement the ** ALTER TABLE command. The first argument is the text of a CREATE TRIGGER ** statement. The second is a table name. The table name in the CREATE ** TRIGGER statement is replaced with the third argument and the result ** returned. This is analagous to renameTableFunc() above, except for CREATE ** TRIGGER, not CREATE INDEX and CREATE TABLE. */ static void renameTriggerFunc( sqlite3_context *context, int NotUsed, sqlite3_value **argv ){ unsigned char const *zSql = sqlite3_value_text(argv[0]); unsigned char const *zTableName = sqlite3_value_text(argv[1]); int token; Token tname; int dist = 3; unsigned char const *zCsr = zSql; int len = 0; char *zRet; sqlite3 *db = sqlite3_context_db_handle(context); UNUSED_PARAMETER(NotUsed); /* The principle used to locate the table name in the CREATE TRIGGER ** statement is that the table name is the first token that is immediately ** preceded by either TK_ON or TK_DOT and immediately followed by one ** of TK_WHEN, TK_BEGIN or TK_FOR. */ if( zSql ){ do { if( !*zCsr ){ /* Ran out of input before finding the table name. Return NULL. */ return; } /* Store the token that zCsr points to in tname. */ tname.z = (char*)zCsr; tname.n = len; /* Advance zCsr to the next token. Store that token type in 'token', ** and its length in 'len' (to be used next iteration of this loop). */ do { zCsr += len; len = sqlite3GetToken(zCsr, &token); }while( token==TK_SPACE ); assert( len>0 ); /* Variable 'dist' stores the number of tokens read since the most ** recent TK_DOT or TK_ON. This means that when a WHEN, FOR or BEGIN ** token is read and 'dist' equals 2, the condition stated above ** to be met. ** ** Note that ON cannot be a database, table or column name, so ** there is no need to worry about syntax like ** "CREATE TRIGGER ... ON ON.ON BEGIN ..." etc. */ dist++; if( token==TK_DOT || token==TK_ON ){ dist = 0; } } while( dist!=2 || (token!=TK_WHEN && token!=TK_FOR && token!=TK_BEGIN) ); /* Variable tname now contains the token that is the old table-name ** in the CREATE TRIGGER statement. */ zRet = sqlite3MPrintf(db, "%.*s\"%w\"%s", (int)(((u8*)tname.z) - zSql), zSql, zTableName, tname.z+tname.n); sqlite3_result_text(context, zRet, -1, SQLITE_DYNAMIC); } } #endif /* !SQLITE_OMIT_TRIGGER */ /* ** Register built-in functions used to help implement ALTER TABLE */ SQLITE_PRIVATE void sqlite3AlterFunctions(void){ static FuncDef aAlterTableFuncs[] = { FUNCTION(sqlite_rename_table, 2, 0, 0, renameTableFunc), #ifndef SQLITE_OMIT_TRIGGER FUNCTION(sqlite_rename_trigger, 2, 0, 0, renameTriggerFunc), #endif #ifndef SQLITE_OMIT_FOREIGN_KEY FUNCTION(sqlite_rename_parent, 3, 0, 0, renameParentFunc), #endif }; sqlite3InsertBuiltinFuncs(aAlterTableFuncs, ArraySize(aAlterTableFuncs)); } /* ** This function is used to create the text of expressions of the form: ** ** name= OR name= OR ... ** ** If argument zWhere is NULL, then a pointer string containing the text ** "name=" is returned, where is the quoted version ** of the string passed as argument zConstant. The returned buffer is ** allocated using sqlite3DbMalloc(). It is the responsibility of the ** caller to ensure that it is eventually freed. ** ** If argument zWhere is not NULL, then the string returned is ** " OR name=", where is the contents of zWhere. ** In this case zWhere is passed to sqlite3DbFree() before returning. ** */ static char *whereOrName(sqlite3 *db, char *zWhere, char *zConstant){ char *zNew; if( !zWhere ){ zNew = sqlite3MPrintf(db, "name=%Q", zConstant); }else{ zNew = sqlite3MPrintf(db, "%s OR name=%Q", zWhere, zConstant); sqlite3DbFree(db, zWhere); } return zNew; } #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER) /* ** Generate the text of a WHERE expression which can be used to select all ** tables that have foreign key constraints that refer to table pTab (i.e. ** constraints for which pTab is the parent table) from the sqlite_master ** table. */ static char *whereForeignKeys(Parse *pParse, Table *pTab){ FKey *p; char *zWhere = 0; for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){ zWhere = whereOrName(pParse->db, zWhere, p->pFrom->zName); } return zWhere; } #endif /* ** Generate the text of a WHERE expression which can be used to select all ** temporary triggers on table pTab from the sqlite_temp_master table. If ** table pTab has no temporary triggers, or is itself stored in the ** temporary database, NULL is returned. */ static char *whereTempTriggers(Parse *pParse, Table *pTab){ Trigger *pTrig; char *zWhere = 0; const Schema *pTempSchema = pParse->db->aDb[1].pSchema; /* Temp db schema */ /* If the table is not located in the temp-db (in which case NULL is ** returned, loop through the tables list of triggers. For each trigger ** that is not part of the temp-db schema, add a clause to the WHERE ** expression being built up in zWhere. */ if( pTab->pSchema!=pTempSchema ){ sqlite3 *db = pParse->db; for(pTrig=sqlite3TriggerList(pParse, pTab); pTrig; pTrig=pTrig->pNext){ if( pTrig->pSchema==pTempSchema ){ zWhere = whereOrName(db, zWhere, pTrig->zName); } } } if( zWhere ){ char *zNew = sqlite3MPrintf(pParse->db, "type='trigger' AND (%s)", zWhere); sqlite3DbFree(pParse->db, zWhere); zWhere = zNew; } return zWhere; } /* ** Generate code to drop and reload the internal representation of table ** pTab from the database, including triggers and temporary triggers. ** Argument zName is the name of the table in the database schema at ** the time the generated code is executed. This can be different from ** pTab->zName if this function is being called to code part of an ** "ALTER TABLE RENAME TO" statement. */ static void reloadTableSchema(Parse *pParse, Table *pTab, const char *zName){ Vdbe *v; char *zWhere; int iDb; /* Index of database containing pTab */ #ifndef SQLITE_OMIT_TRIGGER Trigger *pTrig; #endif v = sqlite3GetVdbe(pParse); if( NEVER(v==0) ) return; assert( sqlite3BtreeHoldsAllMutexes(pParse->db) ); iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema); assert( iDb>=0 ); #ifndef SQLITE_OMIT_TRIGGER /* Drop any table triggers from the internal schema. */ for(pTrig=sqlite3TriggerList(pParse, pTab); pTrig; pTrig=pTrig->pNext){ int iTrigDb = sqlite3SchemaToIndex(pParse->db, pTrig->pSchema); assert( iTrigDb==iDb || iTrigDb==1 ); sqlite3VdbeAddOp4(v, OP_DropTrigger, iTrigDb, 0, 0, pTrig->zName, 0); } #endif /* Drop the table and index from the internal schema. */ sqlite3VdbeAddOp4(v, OP_DropTable, iDb, 0, 0, pTab->zName, 0); /* Reload the table, index and permanent trigger schemas. */ zWhere = sqlite3MPrintf(pParse->db, "tbl_name=%Q", zName); if( !zWhere ) return; sqlite3VdbeAddParseSchemaOp(v, iDb, zWhere); #ifndef SQLITE_OMIT_TRIGGER /* Now, if the table is not stored in the temp database, reload any temp ** triggers. Don't use IN(...) in case SQLITE_OMIT_SUBQUERY is defined. */ if( (zWhere=whereTempTriggers(pParse, pTab))!=0 ){ sqlite3VdbeAddParseSchemaOp(v, 1, zWhere); } #endif } /* ** Parameter zName is the name of a table that is about to be altered ** (either with ALTER TABLE ... RENAME TO or ALTER TABLE ... ADD COLUMN). ** If the table is a system table, this function leaves an error message ** in pParse->zErr (system tables may not be altered) and returns non-zero. ** ** Or, if zName is not a system table, zero is returned. */ static int isSystemTable(Parse *pParse, const char *zName){ if( sqlite3Strlen30(zName)>6 && 0==sqlite3StrNICmp(zName, "sqlite_", 7) ){ sqlite3ErrorMsg(pParse, "table %s may not be altered", zName); return 1; } return 0; } /* ** Generate code to implement the "ALTER TABLE xxx RENAME TO yyy" ** command. */ SQLITE_PRIVATE void sqlite3AlterRenameTable( Parse *pParse, /* Parser context. */ SrcList *pSrc, /* The table to rename. */ Token *pName /* The new table name. */ ){ int iDb; /* Database that contains the table */ char *zDb; /* Name of database iDb */ Table *pTab; /* Table being renamed */ char *zName = 0; /* NULL-terminated version of pName */ sqlite3 *db = pParse->db; /* Database connection */ int nTabName; /* Number of UTF-8 characters in zTabName */ const char *zTabName; /* Original name of the table */ Vdbe *v; #ifndef SQLITE_OMIT_TRIGGER char *zWhere = 0; /* Where clause to locate temp triggers */ #endif VTable *pVTab = 0; /* Non-zero if this is a v-tab with an xRename() */ int savedDbFlags; /* Saved value of db->flags */ savedDbFlags = db->flags; if( NEVER(db->mallocFailed) ) goto exit_rename_table; assert( pSrc->nSrc==1 ); assert( sqlite3BtreeHoldsAllMutexes(pParse->db) ); pTab = sqlite3LocateTableItem(pParse, 0, &pSrc->a[0]); if( !pTab ) goto exit_rename_table; iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema); zDb = db->aDb[iDb].zDbSName; db->flags |= SQLITE_PreferBuiltin; /* Get a NULL terminated version of the new table name. */ zName = sqlite3NameFromToken(db, pName); if( !zName ) goto exit_rename_table; /* Check that a table or index named 'zName' does not already exist ** in database iDb. If so, this is an error. */ if( sqlite3FindTable(db, zName, zDb) || sqlite3FindIndex(db, zName, zDb) ){ sqlite3ErrorMsg(pParse, "there is already another table or index with this name: %s", zName); goto exit_rename_table; } /* Make sure it is not a system table being altered, or a reserved name ** that the table is being renamed to. */ if( SQLITE_OK!=isSystemTable(pParse, pTab->zName) ){ goto exit_rename_table; } if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){ goto exit_rename_table; } #ifndef SQLITE_OMIT_VIEW if( pTab->pSelect ){ sqlite3ErrorMsg(pParse, "view %s may not be altered", pTab->zName); goto exit_rename_table; } #endif #ifndef SQLITE_OMIT_AUTHORIZATION /* Invoke the authorization callback. */ if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, 0) ){ goto exit_rename_table; } #endif #ifndef SQLITE_OMIT_VIRTUALTABLE if( sqlite3ViewGetColumnNames(pParse, pTab) ){ goto exit_rename_table; } if( IsVirtual(pTab) ){ pVTab = sqlite3GetVTable(db, pTab); if( pVTab->pVtab->pModule->xRename==0 ){ pVTab = 0; } } #endif /* Begin a transaction for database iDb. ** Then modify the schema cookie (since the ALTER TABLE modifies the ** schema). Open a statement transaction if the table is a virtual ** table. */ v = sqlite3GetVdbe(pParse); if( v==0 ){ goto exit_rename_table; } sqlite3BeginWriteOperation(pParse, pVTab!=0, iDb); sqlite3ChangeCookie(pParse, iDb); /* If this is a virtual table, invoke the xRename() function if ** one is defined. The xRename() callback will modify the names ** of any resources used by the v-table implementation (including other ** SQLite tables) that are identified by the name of the virtual table. */ #ifndef SQLITE_OMIT_VIRTUALTABLE if( pVTab ){ int i = ++pParse->nMem; sqlite3VdbeLoadString(v, i, zName); sqlite3VdbeAddOp4(v, OP_VRename, i, 0, 0,(const char*)pVTab, P4_VTAB); sqlite3MayAbort(pParse); } #endif /* figure out how many UTF-8 characters are in zName */ zTabName = pTab->zName; nTabName = sqlite3Utf8CharLen(zTabName, -1); #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER) if( db->flags&SQLITE_ForeignKeys ){ /* If foreign-key support is enabled, rewrite the CREATE TABLE ** statements corresponding to all child tables of foreign key constraints ** for which the renamed table is the parent table. */ if( (zWhere=whereForeignKeys(pParse, pTab))!=0 ){ sqlite3NestedParse(pParse, "UPDATE \"%w\".%s SET " "sql = sqlite_rename_parent(sql, %Q, %Q) " "WHERE %s;", zDb, SCHEMA_TABLE(iDb), zTabName, zName, zWhere); sqlite3DbFree(db, zWhere); } } #endif /* Modify the sqlite_master table to use the new table name. */ sqlite3NestedParse(pParse, "UPDATE %Q.%s SET " #ifdef SQLITE_OMIT_TRIGGER "sql = sqlite_rename_table(sql, %Q), " #else "sql = CASE " "WHEN type = 'trigger' THEN sqlite_rename_trigger(sql, %Q)" "ELSE sqlite_rename_table(sql, %Q) END, " #endif "tbl_name = %Q, " "name = CASE " "WHEN type='table' THEN %Q " "WHEN name LIKE 'sqlite_autoindex%%' AND type='index' THEN " "'sqlite_autoindex_' || %Q || substr(name,%d+18) " "ELSE name END " "WHERE tbl_name=%Q COLLATE nocase AND " "(type='table' OR type='index' OR type='trigger');", zDb, SCHEMA_TABLE(iDb), zName, zName, zName, #ifndef SQLITE_OMIT_TRIGGER zName, #endif zName, nTabName, zTabName ); #ifndef SQLITE_OMIT_AUTOINCREMENT /* If the sqlite_sequence table exists in this database, then update ** it with the new table name. */ if( sqlite3FindTable(db, "sqlite_sequence", zDb) ){ sqlite3NestedParse(pParse, "UPDATE \"%w\".sqlite_sequence set name = %Q WHERE name = %Q", zDb, zName, pTab->zName); } #endif #ifndef SQLITE_OMIT_TRIGGER /* If there are TEMP triggers on this table, modify the sqlite_temp_master ** table. Don't do this if the table being ALTERed is itself located in ** the temp database. */ if( (zWhere=whereTempTriggers(pParse, pTab))!=0 ){ sqlite3NestedParse(pParse, "UPDATE sqlite_temp_master SET " "sql = sqlite_rename_trigger(sql, %Q), " "tbl_name = %Q " "WHERE %s;", zName, zName, zWhere); sqlite3DbFree(db, zWhere); } #endif #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER) if( db->flags&SQLITE_ForeignKeys ){ FKey *p; for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){ Table *pFrom = p->pFrom; if( pFrom!=pTab ){ reloadTableSchema(pParse, p->pFrom, pFrom->zName); } } } #endif /* Drop and reload the internal table schema. */ reloadTableSchema(pParse, pTab, zName); exit_rename_table: sqlite3SrcListDelete(db, pSrc); sqlite3DbFree(db, zName); db->flags = savedDbFlags; } /* ** This function is called after an "ALTER TABLE ... ADD" statement ** has been parsed. Argument pColDef contains the text of the new ** column definition. ** ** The Table structure pParse->pNewTable was extended to include ** the new column during parsing. */ SQLITE_PRIVATE void sqlite3AlterFinishAddColumn(Parse *pParse, Token *pColDef){ Table *pNew; /* Copy of pParse->pNewTable */ Table *pTab; /* Table being altered */ int iDb; /* Database number */ const char *zDb; /* Database name */ const char *zTab; /* Table name */ char *zCol; /* Null-terminated column definition */ Column *pCol; /* The new column */ Expr *pDflt; /* Default value for the new column */ sqlite3 *db; /* The database connection; */ Vdbe *v = pParse->pVdbe; /* The prepared statement under construction */ int r1; /* Temporary registers */ db = pParse->db; if( pParse->nErr || db->mallocFailed ) return; assert( v!=0 ); pNew = pParse->pNewTable; assert( pNew ); assert( sqlite3BtreeHoldsAllMutexes(db) ); iDb = sqlite3SchemaToIndex(db, pNew->pSchema); zDb = db->aDb[iDb].zDbSName; zTab = &pNew->zName[16]; /* Skip the "sqlite_altertab_" prefix on the name */ pCol = &pNew->aCol[pNew->nCol-1]; pDflt = pCol->pDflt; pTab = sqlite3FindTable(db, zTab, zDb); assert( pTab ); #ifndef SQLITE_OMIT_AUTHORIZATION /* Invoke the authorization callback. */ if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, 0) ){ return; } #endif /* If the default value for the new column was specified with a ** literal NULL, then set pDflt to 0. This simplifies checking ** for an SQL NULL default below. */ assert( pDflt==0 || pDflt->op==TK_SPAN ); if( pDflt && pDflt->pLeft->op==TK_NULL ){ pDflt = 0; } /* Check that the new column is not specified as PRIMARY KEY or UNIQUE. ** If there is a NOT NULL constraint, then the default value for the ** column must not be NULL. */ if( pCol->colFlags & COLFLAG_PRIMKEY ){ sqlite3ErrorMsg(pParse, "Cannot add a PRIMARY KEY column"); return; } if( pNew->pIndex ){ sqlite3ErrorMsg(pParse, "Cannot add a UNIQUE column"); return; } if( (db->flags&SQLITE_ForeignKeys) && pNew->pFKey && pDflt ){ sqlite3ErrorMsg(pParse, "Cannot add a REFERENCES column with non-NULL default value"); return; } if( pCol->notNull && !pDflt ){ sqlite3ErrorMsg(pParse, "Cannot add a NOT NULL column with default value NULL"); return; } /* Ensure the default expression is something that sqlite3ValueFromExpr() ** can handle (i.e. not CURRENT_TIME etc.) */ if( pDflt ){ sqlite3_value *pVal = 0; int rc; rc = sqlite3ValueFromExpr(db, pDflt, SQLITE_UTF8, SQLITE_AFF_BLOB, &pVal); assert( rc==SQLITE_OK || rc==SQLITE_NOMEM ); if( rc!=SQLITE_OK ){ assert( db->mallocFailed == 1 ); return; } if( !pVal ){ sqlite3ErrorMsg(pParse, "Cannot add a column with non-constant default"); return; } sqlite3ValueFree(pVal); } /* Modify the CREATE TABLE statement. */ zCol = sqlite3DbStrNDup(db, (char*)pColDef->z, pColDef->n); if( zCol ){ char *zEnd = &zCol[pColDef->n-1]; int savedDbFlags = db->flags; while( zEnd>zCol && (*zEnd==';' || sqlite3Isspace(*zEnd)) ){ *zEnd-- = '\0'; } db->flags |= SQLITE_PreferBuiltin; sqlite3NestedParse(pParse, "UPDATE \"%w\".%s SET " "sql = substr(sql,1,%d) || ', ' || %Q || substr(sql,%d) " "WHERE type = 'table' AND name = %Q", zDb, SCHEMA_TABLE(iDb), pNew->addColOffset, zCol, pNew->addColOffset+1, zTab ); sqlite3DbFree(db, zCol); db->flags = savedDbFlags; } /* Make sure the schema version is at least 3. But do not upgrade ** from less than 3 to 4, as that will corrupt any preexisting DESC ** index. */ r1 = sqlite3GetTempReg(pParse); sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, r1, BTREE_FILE_FORMAT); sqlite3VdbeUsesBtree(v, iDb); sqlite3VdbeAddOp2(v, OP_AddImm, r1, -2); sqlite3VdbeAddOp2(v, OP_IfPos, r1, sqlite3VdbeCurrentAddr(v)+2); VdbeCoverage(v); sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_FILE_FORMAT, 3); sqlite3ReleaseTempReg(pParse, r1); /* Reload the schema of the modified table. */ reloadTableSchema(pParse, pTab, pTab->zName); } /* ** This function is called by the parser after the table-name in ** an "ALTER TABLE ADD" statement is parsed. Argument ** pSrc is the full-name of the table being altered. ** ** This routine makes a (partial) copy of the Table structure ** for the table being altered and sets Parse.pNewTable to point ** to it. Routines called by the parser as the column definition ** is parsed (i.e. sqlite3AddColumn()) add the new Column data to ** the copy. The copy of the Table structure is deleted by tokenize.c ** after parsing is finished. ** ** Routine sqlite3AlterFinishAddColumn() will be called to complete ** coding the "ALTER TABLE ... ADD" statement. */ SQLITE_PRIVATE void sqlite3AlterBeginAddColumn(Parse *pParse, SrcList *pSrc){ Table *pNew; Table *pTab; Vdbe *v; int iDb; int i; int nAlloc; sqlite3 *db = pParse->db; /* Look up the table being altered. */ assert( pParse->pNewTable==0 ); assert( sqlite3BtreeHoldsAllMutexes(db) ); if( db->mallocFailed ) goto exit_begin_add_column; pTab = sqlite3LocateTableItem(pParse, 0, &pSrc->a[0]); if( !pTab ) goto exit_begin_add_column; #ifndef SQLITE_OMIT_VIRTUALTABLE if( IsVirtual(pTab) ){ sqlite3ErrorMsg(pParse, "virtual tables may not be altered"); goto exit_begin_add_column; } #endif /* Make sure this is not an attempt to ALTER a view. */ if( pTab->pSelect ){ sqlite3ErrorMsg(pParse, "Cannot add a column to a view"); goto exit_begin_add_column; } if( SQLITE_OK!=isSystemTable(pParse, pTab->zName) ){ goto exit_begin_add_column; } assert( pTab->addColOffset>0 ); iDb = sqlite3SchemaToIndex(db, pTab->pSchema); /* Put a copy of the Table struct in Parse.pNewTable for the ** sqlite3AddColumn() function and friends to modify. But modify ** the name by adding an "sqlite_altertab_" prefix. By adding this ** prefix, we insure that the name will not collide with an existing ** table because user table are not allowed to have the "sqlite_" ** prefix on their name. */ pNew = (Table*)sqlite3DbMallocZero(db, sizeof(Table)); if( !pNew ) goto exit_begin_add_column; pParse->pNewTable = pNew; pNew->nRef = 1; pNew->nCol = pTab->nCol; assert( pNew->nCol>0 ); nAlloc = (((pNew->nCol-1)/8)*8)+8; assert( nAlloc>=pNew->nCol && nAlloc%8==0 && nAlloc-pNew->nCol<8 ); pNew->aCol = (Column*)sqlite3DbMallocZero(db, sizeof(Column)*nAlloc); pNew->zName = sqlite3MPrintf(db, "sqlite_altertab_%s", pTab->zName); if( !pNew->aCol || !pNew->zName ){ assert( db->mallocFailed ); goto exit_begin_add_column; } memcpy(pNew->aCol, pTab->aCol, sizeof(Column)*pNew->nCol); for(i=0; inCol; i++){ Column *pCol = &pNew->aCol[i]; pCol->zName = sqlite3DbStrDup(db, pCol->zName); pCol->zColl = 0; pCol->pDflt = 0; } pNew->pSchema = db->aDb[iDb].pSchema; pNew->addColOffset = pTab->addColOffset; pNew->nRef = 1; /* Begin a transaction and increment the schema cookie. */ sqlite3BeginWriteOperation(pParse, 0, iDb); v = sqlite3GetVdbe(pParse); if( !v ) goto exit_begin_add_column; sqlite3ChangeCookie(pParse, iDb); exit_begin_add_column: sqlite3SrcListDelete(db, pSrc); return; } #endif /* SQLITE_ALTER_TABLE */ /************** End of alter.c ***********************************************/ /************** Begin file analyze.c *****************************************/ /* ** 2005-07-08 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ************************************************************************* ** This file contains code associated with the ANALYZE command. ** ** The ANALYZE command gather statistics about the content of tables ** and indices. These statistics are made available to the query planner ** to help it make better decisions about how to perform queries. ** ** The following system tables are or have been supported: ** ** CREATE TABLE sqlite_stat1(tbl, idx, stat); ** CREATE TABLE sqlite_stat2(tbl, idx, sampleno, sample); ** CREATE TABLE sqlite_stat3(tbl, idx, nEq, nLt, nDLt, sample); ** CREATE TABLE sqlite_stat4(tbl, idx, nEq, nLt, nDLt, sample); ** ** Additional tables might be added in future releases of SQLite. ** The sqlite_stat2 table is not created or used unless the SQLite version ** is between 3.6.18 and 3.7.8, inclusive, and unless SQLite is compiled ** with SQLITE_ENABLE_STAT2. The sqlite_stat2 table is deprecated. ** The sqlite_stat2 table is superseded by sqlite_stat3, which is only ** created and used by SQLite versions 3.7.9 and later and with ** SQLITE_ENABLE_STAT3 defined. The functionality of sqlite_stat3 ** is a superset of sqlite_stat2. The sqlite_stat4 is an enhanced ** version of sqlite_stat3 and is only available when compiled with ** SQLITE_ENABLE_STAT4 and in SQLite versions 3.8.1 and later. It is ** not possible to enable both STAT3 and STAT4 at the same time. If they ** are both enabled, then STAT4 takes precedence. ** ** For most applications, sqlite_stat1 provides all the statistics required ** for the query planner to make good choices. ** ** Format of sqlite_stat1: ** ** There is normally one row per index, with the index identified by the ** name in the idx column. The tbl column is the name of the table to ** which the index belongs. In each such row, the stat column will be ** a string consisting of a list of integers. The first integer in this ** list is the number of rows in the index. (This is the same as the ** number of rows in the table, except for partial indices.) The second ** integer is the average number of rows in the index that have the same ** value in the first column of the index. The third integer is the average ** number of rows in the index that have the same value for the first two ** columns. The N-th integer (for N>1) is the average number of rows in ** the index which have the same value for the first N-1 columns. For ** a K-column index, there will be K+1 integers in the stat column. If ** the index is unique, then the last integer will be 1. ** ** The list of integers in the stat column can optionally be followed ** by the keyword "unordered". The "unordered" keyword, if it is present, ** must be separated from the last integer by a single space. If the ** "unordered" keyword is present, then the query planner assumes that ** the index is unordered and will not use the index for a range query. ** ** If the sqlite_stat1.idx column is NULL, then the sqlite_stat1.stat ** column contains a single integer which is the (estimated) number of ** rows in the table identified by sqlite_stat1.tbl. ** ** Format of sqlite_stat2: ** ** The sqlite_stat2 is only created and is only used if SQLite is compiled ** with SQLITE_ENABLE_STAT2 and if the SQLite version number is between ** 3.6.18 and 3.7.8. The "stat2" table contains additional information ** about the distribution of keys within an index. The index is identified by ** the "idx" column and the "tbl" column is the name of the table to which ** the index belongs. There are usually 10 rows in the sqlite_stat2 ** table for each index. ** ** The sqlite_stat2 entries for an index that have sampleno between 0 and 9 ** inclusive are samples of the left-most key value in the index taken at ** evenly spaced points along the index. Let the number of samples be S ** (10 in the standard build) and let C be the number of rows in the index. ** Then the sampled rows are given by: ** ** rownumber = (i*C*2 + C)/(S*2) ** ** For i between 0 and S-1. Conceptually, the index space is divided into ** S uniform buckets and the samples are the middle row from each bucket. ** ** The format for sqlite_stat2 is recorded here for legacy reference. This ** version of SQLite does not support sqlite_stat2. It neither reads nor ** writes the sqlite_stat2 table. This version of SQLite only supports ** sqlite_stat3. ** ** Format for sqlite_stat3: ** ** The sqlite_stat3 format is a subset of sqlite_stat4. Hence, the ** sqlite_stat4 format will be described first. Further information ** about sqlite_stat3 follows the sqlite_stat4 description. ** ** Format for sqlite_stat4: ** ** As with sqlite_stat2, the sqlite_stat4 table contains histogram data ** to aid the query planner in choosing good indices based on the values ** that indexed columns are compared against in the WHERE clauses of ** queries. ** ** The sqlite_stat4 table contains multiple entries for each index. ** The idx column names the index and the tbl column is the table of the ** index. If the idx and tbl columns are the same, then the sample is ** of the INTEGER PRIMARY KEY. The sample column is a blob which is the ** binary encoding of a key from the index. The nEq column is a ** list of integers. The first integer is the approximate number ** of entries in the index whose left-most column exactly matches ** the left-most column of the sample. The second integer in nEq ** is the approximate number of entries in the index where the ** first two columns match the first two columns of the sample. ** And so forth. nLt is another list of integers that show the approximate ** number of entries that are strictly less than the sample. The first ** integer in nLt contains the number of entries in the index where the ** left-most column is less than the left-most column of the sample. ** The K-th integer in the nLt entry is the number of index entries ** where the first K columns are less than the first K columns of the ** sample. The nDLt column is like nLt except that it contains the ** number of distinct entries in the index that are less than the ** sample. ** ** There can be an arbitrary number of sqlite_stat4 entries per index. ** The ANALYZE command will typically generate sqlite_stat4 tables ** that contain between 10 and 40 samples which are distributed across ** the key space, though not uniformly, and which include samples with ** large nEq values. ** ** Format for sqlite_stat3 redux: ** ** The sqlite_stat3 table is like sqlite_stat4 except that it only ** looks at the left-most column of the index. The sqlite_stat3.sample ** column contains the actual value of the left-most column instead ** of a blob encoding of the complete index key as is found in ** sqlite_stat4.sample. The nEq, nLt, and nDLt entries of sqlite_stat3 ** all contain just a single integer which is the same as the first ** integer in the equivalent columns in sqlite_stat4. */ #ifndef SQLITE_OMIT_ANALYZE /* #include "sqliteInt.h" */ #if defined(SQLITE_ENABLE_STAT4) # define IsStat4 1 # define IsStat3 0 #elif defined(SQLITE_ENABLE_STAT3) # define IsStat4 0 # define IsStat3 1 #else # define IsStat4 0 # define IsStat3 0 # undef SQLITE_STAT4_SAMPLES # define SQLITE_STAT4_SAMPLES 1 #endif #define IsStat34 (IsStat3+IsStat4) /* 1 for STAT3 or STAT4. 0 otherwise */ /* ** This routine generates code that opens the sqlite_statN tables. ** The sqlite_stat1 table is always relevant. sqlite_stat2 is now ** obsolete. sqlite_stat3 and sqlite_stat4 are only opened when ** appropriate compile-time options are provided. ** ** If the sqlite_statN tables do not previously exist, it is created. ** ** Argument zWhere may be a pointer to a buffer containing a table name, ** or it may be a NULL pointer. If it is not NULL, then all entries in ** the sqlite_statN tables associated with the named table are deleted. ** If zWhere==0, then code is generated to delete all stat table entries. */ static void openStatTable( Parse *pParse, /* Parsing context */ int iDb, /* The database we are looking in */ int iStatCur, /* Open the sqlite_stat1 table on this cursor */ const char *zWhere, /* Delete entries for this table or index */ const char *zWhereType /* Either "tbl" or "idx" */ ){ static const struct { const char *zName; const char *zCols; } aTable[] = { { "sqlite_stat1", "tbl,idx,stat" }, #if defined(SQLITE_ENABLE_STAT4) { "sqlite_stat4", "tbl,idx,neq,nlt,ndlt,sample" }, { "sqlite_stat3", 0 }, #elif defined(SQLITE_ENABLE_STAT3) { "sqlite_stat3", "tbl,idx,neq,nlt,ndlt,sample" }, { "sqlite_stat4", 0 }, #else { "sqlite_stat3", 0 }, { "sqlite_stat4", 0 }, #endif }; int i; sqlite3 *db = pParse->db; Db *pDb; Vdbe *v = sqlite3GetVdbe(pParse); int aRoot[ArraySize(aTable)]; u8 aCreateTbl[ArraySize(aTable)]; if( v==0 ) return; assert( sqlite3BtreeHoldsAllMutexes(db) ); assert( sqlite3VdbeDb(v)==db ); pDb = &db->aDb[iDb]; /* Create new statistic tables if they do not exist, or clear them ** if they do already exist. */ for(i=0; izDbSName))==0 ){ if( aTable[i].zCols ){ /* The sqlite_statN table does not exist. Create it. Note that a ** side-effect of the CREATE TABLE statement is to leave the rootpage ** of the new table in register pParse->regRoot. This is important ** because the OpenWrite opcode below will be needing it. */ sqlite3NestedParse(pParse, "CREATE TABLE %Q.%s(%s)", pDb->zDbSName, zTab, aTable[i].zCols ); aRoot[i] = pParse->regRoot; aCreateTbl[i] = OPFLAG_P2ISREG; } }else{ /* The table already exists. If zWhere is not NULL, delete all entries ** associated with the table zWhere. If zWhere is NULL, delete the ** entire contents of the table. */ aRoot[i] = pStat->tnum; aCreateTbl[i] = 0; sqlite3TableLock(pParse, iDb, aRoot[i], 1, zTab); if( zWhere ){ sqlite3NestedParse(pParse, "DELETE FROM %Q.%s WHERE %s=%Q", pDb->zDbSName, zTab, zWhereType, zWhere ); }else{ /* The sqlite_stat[134] table already exists. Delete all rows. */ sqlite3VdbeAddOp2(v, OP_Clear, aRoot[i], iDb); } } } /* Open the sqlite_stat[134] tables for writing. */ for(i=0; aTable[i].zCols; i++){ assert( inRowid ){ sqlite3DbFree(db, p->u.aRowid); p->nRowid = 0; } } #endif /* Initialize the BLOB value of a ROWID */ #ifdef SQLITE_ENABLE_STAT3_OR_STAT4 static void sampleSetRowid(sqlite3 *db, Stat4Sample *p, int n, const u8 *pData){ assert( db!=0 ); if( p->nRowid ) sqlite3DbFree(db, p->u.aRowid); p->u.aRowid = sqlite3DbMallocRawNN(db, n); if( p->u.aRowid ){ p->nRowid = n; memcpy(p->u.aRowid, pData, n); }else{ p->nRowid = 0; } } #endif /* Initialize the INTEGER value of a ROWID. */ #ifdef SQLITE_ENABLE_STAT3_OR_STAT4 static void sampleSetRowidInt64(sqlite3 *db, Stat4Sample *p, i64 iRowid){ assert( db!=0 ); if( p->nRowid ) sqlite3DbFree(db, p->u.aRowid); p->nRowid = 0; p->u.iRowid = iRowid; } #endif /* ** Copy the contents of object (*pFrom) into (*pTo). */ #ifdef SQLITE_ENABLE_STAT3_OR_STAT4 static void sampleCopy(Stat4Accum *p, Stat4Sample *pTo, Stat4Sample *pFrom){ pTo->isPSample = pFrom->isPSample; pTo->iCol = pFrom->iCol; pTo->iHash = pFrom->iHash; memcpy(pTo->anEq, pFrom->anEq, sizeof(tRowcnt)*p->nCol); memcpy(pTo->anLt, pFrom->anLt, sizeof(tRowcnt)*p->nCol); memcpy(pTo->anDLt, pFrom->anDLt, sizeof(tRowcnt)*p->nCol); if( pFrom->nRowid ){ sampleSetRowid(p->db, pTo, pFrom->nRowid, pFrom->u.aRowid); }else{ sampleSetRowidInt64(p->db, pTo, pFrom->u.iRowid); } } #endif /* ** Reclaim all memory of a Stat4Accum structure. */ static void stat4Destructor(void *pOld){ Stat4Accum *p = (Stat4Accum*)pOld; #ifdef SQLITE_ENABLE_STAT3_OR_STAT4 int i; for(i=0; inCol; i++) sampleClear(p->db, p->aBest+i); for(i=0; imxSample; i++) sampleClear(p->db, p->a+i); sampleClear(p->db, &p->current); #endif sqlite3DbFree(p->db, p); } /* ** Implementation of the stat_init(N,K,C) SQL function. The three parameters ** are: ** N: The number of columns in the index including the rowid/pk (note 1) ** K: The number of columns in the index excluding the rowid/pk. ** C: The number of rows in the index (note 2) ** ** Note 1: In the special case of the covering index that implements a ** WITHOUT ROWID table, N is the number of PRIMARY KEY columns, not the ** total number of columns in the table. ** ** Note 2: C is only used for STAT3 and STAT4. ** ** For indexes on ordinary rowid tables, N==K+1. But for indexes on ** WITHOUT ROWID tables, N=K+P where P is the number of columns in the ** PRIMARY KEY of the table. The covering index that implements the ** original WITHOUT ROWID table as N==K as a special case. ** ** This routine allocates the Stat4Accum object in heap memory. The return ** value is a pointer to the Stat4Accum object. The datatype of the ** return value is BLOB, but it is really just a pointer to the Stat4Accum ** object. */ static void statInit( sqlite3_context *context, int argc, sqlite3_value **argv ){ Stat4Accum *p; int nCol; /* Number of columns in index being sampled */ int nKeyCol; /* Number of key columns */ int nColUp; /* nCol rounded up for alignment */ int n; /* Bytes of space to allocate */ sqlite3 *db; /* Database connection */ #ifdef SQLITE_ENABLE_STAT3_OR_STAT4 int mxSample = SQLITE_STAT4_SAMPLES; #endif /* Decode the three function arguments */ UNUSED_PARAMETER(argc); nCol = sqlite3_value_int(argv[0]); assert( nCol>0 ); nColUp = sizeof(tRowcnt)<8 ? (nCol+1)&~1 : nCol; nKeyCol = sqlite3_value_int(argv[1]); assert( nKeyCol<=nCol ); assert( nKeyCol>0 ); /* Allocate the space required for the Stat4Accum object */ n = sizeof(*p) + sizeof(tRowcnt)*nColUp /* Stat4Accum.anEq */ + sizeof(tRowcnt)*nColUp /* Stat4Accum.anDLt */ #ifdef SQLITE_ENABLE_STAT3_OR_STAT4 + sizeof(tRowcnt)*nColUp /* Stat4Accum.anLt */ + sizeof(Stat4Sample)*(nCol+mxSample) /* Stat4Accum.aBest[], a[] */ + sizeof(tRowcnt)*3*nColUp*(nCol+mxSample) #endif ; db = sqlite3_context_db_handle(context); p = sqlite3DbMallocZero(db, n); if( p==0 ){ sqlite3_result_error_nomem(context); return; } p->db = db; p->nRow = 0; p->nCol = nCol; p->nKeyCol = nKeyCol; p->current.anDLt = (tRowcnt*)&p[1]; p->current.anEq = &p->current.anDLt[nColUp]; #ifdef SQLITE_ENABLE_STAT3_OR_STAT4 { u8 *pSpace; /* Allocated space not yet assigned */ int i; /* Used to iterate through p->aSample[] */ p->iGet = -1; p->mxSample = mxSample; p->nPSample = (tRowcnt)(sqlite3_value_int64(argv[2])/(mxSample/3+1) + 1); p->current.anLt = &p->current.anEq[nColUp]; p->iPrn = 0x689e962d*(u32)nCol ^ 0xd0944565*(u32)sqlite3_value_int(argv[2]); /* Set up the Stat4Accum.a[] and aBest[] arrays */ p->a = (struct Stat4Sample*)&p->current.anLt[nColUp]; p->aBest = &p->a[mxSample]; pSpace = (u8*)(&p->a[mxSample+nCol]); for(i=0; i<(mxSample+nCol); i++){ p->a[i].anEq = (tRowcnt *)pSpace; pSpace += (sizeof(tRowcnt) * nColUp); p->a[i].anLt = (tRowcnt *)pSpace; pSpace += (sizeof(tRowcnt) * nColUp); p->a[i].anDLt = (tRowcnt *)pSpace; pSpace += (sizeof(tRowcnt) * nColUp); } assert( (pSpace - (u8*)p)==n ); for(i=0; iaBest[i].iCol = i; } } #endif /* Return a pointer to the allocated object to the caller. Note that ** only the pointer (the 2nd parameter) matters. The size of the object ** (given by the 3rd parameter) is never used and can be any positive ** value. */ sqlite3_result_blob(context, p, sizeof(*p), stat4Destructor); } static const FuncDef statInitFuncdef = { 2+IsStat34, /* nArg */ SQLITE_UTF8, /* funcFlags */ 0, /* pUserData */ 0, /* pNext */ statInit, /* xSFunc */ 0, /* xFinalize */ "stat_init", /* zName */ {0} }; #ifdef SQLITE_ENABLE_STAT4 /* ** pNew and pOld are both candidate non-periodic samples selected for ** the same column (pNew->iCol==pOld->iCol). Ignoring this column and ** considering only any trailing columns and the sample hash value, this ** function returns true if sample pNew is to be preferred over pOld. ** In other words, if we assume that the cardinalities of the selected ** column for pNew and pOld are equal, is pNew to be preferred over pOld. ** ** This function assumes that for each argument sample, the contents of ** the anEq[] array from pSample->anEq[pSample->iCol+1] onwards are valid. */ static int sampleIsBetterPost( Stat4Accum *pAccum, Stat4Sample *pNew, Stat4Sample *pOld ){ int nCol = pAccum->nCol; int i; assert( pNew->iCol==pOld->iCol ); for(i=pNew->iCol+1; ianEq[i]>pOld->anEq[i] ) return 1; if( pNew->anEq[i]anEq[i] ) return 0; } if( pNew->iHash>pOld->iHash ) return 1; return 0; } #endif #ifdef SQLITE_ENABLE_STAT3_OR_STAT4 /* ** Return true if pNew is to be preferred over pOld. ** ** This function assumes that for each argument sample, the contents of ** the anEq[] array from pSample->anEq[pSample->iCol] onwards are valid. */ static int sampleIsBetter( Stat4Accum *pAccum, Stat4Sample *pNew, Stat4Sample *pOld ){ tRowcnt nEqNew = pNew->anEq[pNew->iCol]; tRowcnt nEqOld = pOld->anEq[pOld->iCol]; assert( pOld->isPSample==0 && pNew->isPSample==0 ); assert( IsStat4 || (pNew->iCol==0 && pOld->iCol==0) ); if( (nEqNew>nEqOld) ) return 1; #ifdef SQLITE_ENABLE_STAT4 if( nEqNew==nEqOld ){ if( pNew->iColiCol ) return 1; return (pNew->iCol==pOld->iCol && sampleIsBetterPost(pAccum, pNew, pOld)); } return 0; #else return (nEqNew==nEqOld && pNew->iHash>pOld->iHash); #endif } /* ** Copy the contents of sample *pNew into the p->a[] array. If necessary, ** remove the least desirable sample from p->a[] to make room. */ static void sampleInsert(Stat4Accum *p, Stat4Sample *pNew, int nEqZero){ Stat4Sample *pSample = 0; int i; assert( IsStat4 || nEqZero==0 ); #ifdef SQLITE_ENABLE_STAT4 if( pNew->isPSample==0 ){ Stat4Sample *pUpgrade = 0; assert( pNew->anEq[pNew->iCol]>0 ); /* This sample is being added because the prefix that ends in column ** iCol occurs many times in the table. However, if we have already ** added a sample that shares this prefix, there is no need to add ** this one. Instead, upgrade the priority of the highest priority ** existing sample that shares this prefix. */ for(i=p->nSample-1; i>=0; i--){ Stat4Sample *pOld = &p->a[i]; if( pOld->anEq[pNew->iCol]==0 ){ if( pOld->isPSample ) return; assert( pOld->iCol>pNew->iCol ); assert( sampleIsBetter(p, pNew, pOld) ); if( pUpgrade==0 || sampleIsBetter(p, pOld, pUpgrade) ){ pUpgrade = pOld; } } } if( pUpgrade ){ pUpgrade->iCol = pNew->iCol; pUpgrade->anEq[pUpgrade->iCol] = pNew->anEq[pUpgrade->iCol]; goto find_new_min; } } #endif /* If necessary, remove sample iMin to make room for the new sample. */ if( p->nSample>=p->mxSample ){ Stat4Sample *pMin = &p->a[p->iMin]; tRowcnt *anEq = pMin->anEq; tRowcnt *anLt = pMin->anLt; tRowcnt *anDLt = pMin->anDLt; sampleClear(p->db, pMin); memmove(pMin, &pMin[1], sizeof(p->a[0])*(p->nSample-p->iMin-1)); pSample = &p->a[p->nSample-1]; pSample->nRowid = 0; pSample->anEq = anEq; pSample->anDLt = anDLt; pSample->anLt = anLt; p->nSample = p->mxSample-1; } /* The "rows less-than" for the rowid column must be greater than that ** for the last sample in the p->a[] array. Otherwise, the samples would ** be out of order. */ #ifdef SQLITE_ENABLE_STAT4 assert( p->nSample==0 || pNew->anLt[p->nCol-1] > p->a[p->nSample-1].anLt[p->nCol-1] ); #endif /* Insert the new sample */ pSample = &p->a[p->nSample]; sampleCopy(p, pSample, pNew); p->nSample++; /* Zero the first nEqZero entries in the anEq[] array. */ memset(pSample->anEq, 0, sizeof(tRowcnt)*nEqZero); #ifdef SQLITE_ENABLE_STAT4 find_new_min: #endif if( p->nSample>=p->mxSample ){ int iMin = -1; for(i=0; imxSample; i++){ if( p->a[i].isPSample ) continue; if( iMin<0 || sampleIsBetter(p, &p->a[iMin], &p->a[i]) ){ iMin = i; } } assert( iMin>=0 ); p->iMin = iMin; } } #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */ /* ** Field iChng of the index being scanned has changed. So at this point ** p->current contains a sample that reflects the previous row of the ** index. The value of anEq[iChng] and subsequent anEq[] elements are ** correct at this point. */ static void samplePushPrevious(Stat4Accum *p, int iChng){ #ifdef SQLITE_ENABLE_STAT4 int i; /* Check if any samples from the aBest[] array should be pushed ** into IndexSample.a[] at this point. */ for(i=(p->nCol-2); i>=iChng; i--){ Stat4Sample *pBest = &p->aBest[i]; pBest->anEq[i] = p->current.anEq[i]; if( p->nSamplemxSample || sampleIsBetter(p, pBest, &p->a[p->iMin]) ){ sampleInsert(p, pBest, i); } } /* Update the anEq[] fields of any samples already collected. */ for(i=p->nSample-1; i>=0; i--){ int j; for(j=iChng; jnCol; j++){ if( p->a[i].anEq[j]==0 ) p->a[i].anEq[j] = p->current.anEq[j]; } } #endif #if defined(SQLITE_ENABLE_STAT3) && !defined(SQLITE_ENABLE_STAT4) if( iChng==0 ){ tRowcnt nLt = p->current.anLt[0]; tRowcnt nEq = p->current.anEq[0]; /* Check if this is to be a periodic sample. If so, add it. */ if( (nLt/p->nPSample)!=(nLt+nEq)/p->nPSample ){ p->current.isPSample = 1; sampleInsert(p, &p->current, 0); p->current.isPSample = 0; }else /* Or if it is a non-periodic sample. Add it in this case too. */ if( p->nSamplemxSample || sampleIsBetter(p, &p->current, &p->a[p->iMin]) ){ sampleInsert(p, &p->current, 0); } } #endif #ifndef SQLITE_ENABLE_STAT3_OR_STAT4 UNUSED_PARAMETER( p ); UNUSED_PARAMETER( iChng ); #endif } /* ** Implementation of the stat_push SQL function: stat_push(P,C,R) ** Arguments: ** ** P Pointer to the Stat4Accum object created by stat_init() ** C Index of left-most column to differ from previous row ** R Rowid for the current row. Might be a key record for ** WITHOUT ROWID tables. ** ** This SQL function always returns NULL. It's purpose it to accumulate ** statistical data and/or samples in the Stat4Accum object about the ** index being analyzed. The stat_get() SQL function will later be used to ** extract relevant information for constructing the sqlite_statN tables. ** ** The R parameter is only used for STAT3 and STAT4 */ static void statPush( sqlite3_context *context, int argc, sqlite3_value **argv ){ int i; /* The three function arguments */ Stat4Accum *p = (Stat4Accum*)sqlite3_value_blob(argv[0]); int iChng = sqlite3_value_int(argv[1]); UNUSED_PARAMETER( argc ); UNUSED_PARAMETER( context ); assert( p->nCol>0 ); assert( iChngnCol ); if( p->nRow==0 ){ /* This is the first call to this function. Do initialization. */ for(i=0; inCol; i++) p->current.anEq[i] = 1; }else{ /* Second and subsequent calls get processed here */ samplePushPrevious(p, iChng); /* Update anDLt[], anLt[] and anEq[] to reflect the values that apply ** to the current row of the index. */ for(i=0; icurrent.anEq[i]++; } for(i=iChng; inCol; i++){ p->current.anDLt[i]++; #ifdef SQLITE_ENABLE_STAT3_OR_STAT4 p->current.anLt[i] += p->current.anEq[i]; #endif p->current.anEq[i] = 1; } } p->nRow++; #ifdef SQLITE_ENABLE_STAT3_OR_STAT4 if( sqlite3_value_type(argv[2])==SQLITE_INTEGER ){ sampleSetRowidInt64(p->db, &p->current, sqlite3_value_int64(argv[2])); }else{ sampleSetRowid(p->db, &p->current, sqlite3_value_bytes(argv[2]), sqlite3_value_blob(argv[2])); } p->current.iHash = p->iPrn = p->iPrn*1103515245 + 12345; #endif #ifdef SQLITE_ENABLE_STAT4 { tRowcnt nLt = p->current.anLt[p->nCol-1]; /* Check if this is to be a periodic sample. If so, add it. */ if( (nLt/p->nPSample)!=(nLt+1)/p->nPSample ){ p->current.isPSample = 1; p->current.iCol = 0; sampleInsert(p, &p->current, p->nCol-1); p->current.isPSample = 0; } /* Update the aBest[] array. */ for(i=0; i<(p->nCol-1); i++){ p->current.iCol = i; if( i>=iChng || sampleIsBetterPost(p, &p->current, &p->aBest[i]) ){ sampleCopy(p, &p->aBest[i], &p->current); } } } #endif } static const FuncDef statPushFuncdef = { 2+IsStat34, /* nArg */ SQLITE_UTF8, /* funcFlags */ 0, /* pUserData */ 0, /* pNext */ statPush, /* xSFunc */ 0, /* xFinalize */ "stat_push", /* zName */ {0} }; #define STAT_GET_STAT1 0 /* "stat" column of stat1 table */ #define STAT_GET_ROWID 1 /* "rowid" column of stat[34] entry */ #define STAT_GET_NEQ 2 /* "neq" column of stat[34] entry */ #define STAT_GET_NLT 3 /* "nlt" column of stat[34] entry */ #define STAT_GET_NDLT 4 /* "ndlt" column of stat[34] entry */ /* ** Implementation of the stat_get(P,J) SQL function. This routine is ** used to query statistical information that has been gathered into ** the Stat4Accum object by prior calls to stat_push(). The P parameter ** has type BLOB but it is really just a pointer to the Stat4Accum object. ** The content to returned is determined by the parameter J ** which is one of the STAT_GET_xxxx values defined above. ** ** If neither STAT3 nor STAT4 are enabled, then J is always ** STAT_GET_STAT1 and is hence omitted and this routine becomes ** a one-parameter function, stat_get(P), that always returns the ** stat1 table entry information. */ static void statGet( sqlite3_context *context, int argc, sqlite3_value **argv ){ Stat4Accum *p = (Stat4Accum*)sqlite3_value_blob(argv[0]); #ifdef SQLITE_ENABLE_STAT3_OR_STAT4 /* STAT3 and STAT4 have a parameter on this routine. */ int eCall = sqlite3_value_int(argv[1]); assert( argc==2 ); assert( eCall==STAT_GET_STAT1 || eCall==STAT_GET_NEQ || eCall==STAT_GET_ROWID || eCall==STAT_GET_NLT || eCall==STAT_GET_NDLT ); if( eCall==STAT_GET_STAT1 ) #else assert( argc==1 ); #endif { /* Return the value to store in the "stat" column of the sqlite_stat1 ** table for this index. ** ** The value is a string composed of a list of integers describing ** the index. The first integer in the list is the total number of ** entries in the index. There is one additional integer in the list ** for each indexed column. This additional integer is an estimate of ** the number of rows matched by a stabbing query on the index using ** a key with the corresponding number of fields. In other words, ** if the index is on columns (a,b) and the sqlite_stat1 value is ** "100 10 2", then SQLite estimates that: ** ** * the index contains 100 rows, ** * "WHERE a=?" matches 10 rows, and ** * "WHERE a=? AND b=?" matches 2 rows. ** ** If D is the count of distinct values and K is the total number of ** rows, then each estimate is computed as: ** ** I = (K+D-1)/D */ char *z; int i; char *zRet = sqlite3MallocZero( (p->nKeyCol+1)*25 ); if( zRet==0 ){ sqlite3_result_error_nomem(context); return; } sqlite3_snprintf(24, zRet, "%llu", (u64)p->nRow); z = zRet + sqlite3Strlen30(zRet); for(i=0; inKeyCol; i++){ u64 nDistinct = p->current.anDLt[i] + 1; u64 iVal = (p->nRow + nDistinct - 1) / nDistinct; sqlite3_snprintf(24, z, " %llu", iVal); z += sqlite3Strlen30(z); assert( p->current.anEq[i] ); } assert( z[0]=='\0' && z>zRet ); sqlite3_result_text(context, zRet, -1, sqlite3_free); } #ifdef SQLITE_ENABLE_STAT3_OR_STAT4 else if( eCall==STAT_GET_ROWID ){ if( p->iGet<0 ){ samplePushPrevious(p, 0); p->iGet = 0; } if( p->iGetnSample ){ Stat4Sample *pS = p->a + p->iGet; if( pS->nRowid==0 ){ sqlite3_result_int64(context, pS->u.iRowid); }else{ sqlite3_result_blob(context, pS->u.aRowid, pS->nRowid, SQLITE_TRANSIENT); } } }else{ tRowcnt *aCnt = 0; assert( p->iGetnSample ); switch( eCall ){ case STAT_GET_NEQ: aCnt = p->a[p->iGet].anEq; break; case STAT_GET_NLT: aCnt = p->a[p->iGet].anLt; break; default: { aCnt = p->a[p->iGet].anDLt; p->iGet++; break; } } if( IsStat3 ){ sqlite3_result_int64(context, (i64)aCnt[0]); }else{ char *zRet = sqlite3MallocZero(p->nCol * 25); if( zRet==0 ){ sqlite3_result_error_nomem(context); }else{ int i; char *z = zRet; for(i=0; inCol; i++){ sqlite3_snprintf(24, z, "%llu ", (u64)aCnt[i]); z += sqlite3Strlen30(z); } assert( z[0]=='\0' && z>zRet ); z[-1] = '\0'; sqlite3_result_text(context, zRet, -1, sqlite3_free); } } } #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */ #ifndef SQLITE_DEBUG UNUSED_PARAMETER( argc ); #endif } static const FuncDef statGetFuncdef = { 1+IsStat34, /* nArg */ SQLITE_UTF8, /* funcFlags */ 0, /* pUserData */ 0, /* pNext */ statGet, /* xSFunc */ 0, /* xFinalize */ "stat_get", /* zName */ {0} }; static void callStatGet(Vdbe *v, int regStat4, int iParam, int regOut){ assert( regOut!=regStat4 && regOut!=regStat4+1 ); #ifdef SQLITE_ENABLE_STAT3_OR_STAT4 sqlite3VdbeAddOp2(v, OP_Integer, iParam, regStat4+1); #elif SQLITE_DEBUG assert( iParam==STAT_GET_STAT1 ); #else UNUSED_PARAMETER( iParam ); #endif sqlite3VdbeAddOp4(v, OP_Function0, 0, regStat4, regOut, (char*)&statGetFuncdef, P4_FUNCDEF); sqlite3VdbeChangeP5(v, 1 + IsStat34); } /* ** Generate code to do an analysis of all indices associated with ** a single table. */ static void analyzeOneTable( Parse *pParse, /* Parser context */ Table *pTab, /* Table whose indices are to be analyzed */ Index *pOnlyIdx, /* If not NULL, only analyze this one index */ int iStatCur, /* Index of VdbeCursor that writes the sqlite_stat1 table */ int iMem, /* Available memory locations begin here */ int iTab /* Next available cursor */ ){ sqlite3 *db = pParse->db; /* Database handle */ Index *pIdx; /* An index to being analyzed */ int iIdxCur; /* Cursor open on index being analyzed */ int iTabCur; /* Table cursor */ Vdbe *v; /* The virtual machine being built up */ int i; /* Loop counter */ int jZeroRows = -1; /* Jump from here if number of rows is zero */ int iDb; /* Index of database containing pTab */ u8 needTableCnt = 1; /* True to count the table */ int regNewRowid = iMem++; /* Rowid for the inserted record */ int regStat4 = iMem++; /* Register to hold Stat4Accum object */ int regChng = iMem++; /* Index of changed index field */ #ifdef SQLITE_ENABLE_STAT3_OR_STAT4 int regRowid = iMem++; /* Rowid argument passed to stat_push() */ #endif int regTemp = iMem++; /* Temporary use register */ int regTabname = iMem++; /* Register containing table name */ int regIdxname = iMem++; /* Register containing index name */ int regStat1 = iMem++; /* Value for the stat column of sqlite_stat1 */ int regPrev = iMem; /* MUST BE LAST (see below) */ pParse->nMem = MAX(pParse->nMem, iMem); v = sqlite3GetVdbe(pParse); if( v==0 || NEVER(pTab==0) ){ return; } if( pTab->tnum==0 ){ /* Do not gather statistics on views or virtual tables */ return; } if( sqlite3_strlike("sqlite_%", pTab->zName, 0)==0 ){ /* Do not gather statistics on system tables */ return; } assert( sqlite3BtreeHoldsAllMutexes(db) ); iDb = sqlite3SchemaToIndex(db, pTab->pSchema); assert( iDb>=0 ); assert( sqlite3SchemaMutexHeld(db, iDb, 0) ); #ifndef SQLITE_OMIT_AUTHORIZATION if( sqlite3AuthCheck(pParse, SQLITE_ANALYZE, pTab->zName, 0, db->aDb[iDb].zDbSName ) ){ return; } #endif /* Establish a read-lock on the table at the shared-cache level. ** Open a read-only cursor on the table. Also allocate a cursor number ** to use for scanning indexes (iIdxCur). No index cursor is opened at ** this time though. */ sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName); iTabCur = iTab++; iIdxCur = iTab++; pParse->nTab = MAX(pParse->nTab, iTab); sqlite3OpenTable(pParse, iTabCur, iDb, pTab, OP_OpenRead); sqlite3VdbeLoadString(v, regTabname, pTab->zName); for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){ int nCol; /* Number of columns in pIdx. "N" */ int addrRewind; /* Address of "OP_Rewind iIdxCur" */ int addrNextRow; /* Address of "next_row:" */ const char *zIdxName; /* Name of the index */ int nColTest; /* Number of columns to test for changes */ if( pOnlyIdx && pOnlyIdx!=pIdx ) continue; if( pIdx->pPartIdxWhere==0 ) needTableCnt = 0; if( !HasRowid(pTab) && IsPrimaryKeyIndex(pIdx) ){ nCol = pIdx->nKeyCol; zIdxName = pTab->zName; nColTest = nCol - 1; }else{ nCol = pIdx->nColumn; zIdxName = pIdx->zName; nColTest = pIdx->uniqNotNull ? pIdx->nKeyCol-1 : nCol-1; } /* Populate the register containing the index name. */ sqlite3VdbeLoadString(v, regIdxname, zIdxName); VdbeComment((v, "Analysis for %s.%s", pTab->zName, zIdxName)); /* ** Pseudo-code for loop that calls stat_push(): ** ** Rewind csr ** if eof(csr) goto end_of_scan; ** regChng = 0 ** goto chng_addr_0; ** ** next_row: ** regChng = 0 ** if( idx(0) != regPrev(0) ) goto chng_addr_0 ** regChng = 1 ** if( idx(1) != regPrev(1) ) goto chng_addr_1 ** ... ** regChng = N ** goto chng_addr_N ** ** chng_addr_0: ** regPrev(0) = idx(0) ** chng_addr_1: ** regPrev(1) = idx(1) ** ... ** ** endDistinctTest: ** regRowid = idx(rowid) ** stat_push(P, regChng, regRowid) ** Next csr ** if !eof(csr) goto next_row; ** ** end_of_scan: */ /* Make sure there are enough memory cells allocated to accommodate ** the regPrev array and a trailing rowid (the rowid slot is required ** when building a record to insert into the sample column of ** the sqlite_stat4 table. */ pParse->nMem = MAX(pParse->nMem, regPrev+nColTest); /* Open a read-only cursor on the index being analyzed. */ assert( iDb==sqlite3SchemaToIndex(db, pIdx->pSchema) ); sqlite3VdbeAddOp3(v, OP_OpenRead, iIdxCur, pIdx->tnum, iDb); sqlite3VdbeSetP4KeyInfo(pParse, pIdx); VdbeComment((v, "%s", pIdx->zName)); /* Invoke the stat_init() function. The arguments are: ** ** (1) the number of columns in the index including the rowid ** (or for a WITHOUT ROWID table, the number of PK columns), ** (2) the number of columns in the key without the rowid/pk ** (3) the number of rows in the index, ** ** ** The third argument is only used for STAT3 and STAT4 */ #ifdef SQLITE_ENABLE_STAT3_OR_STAT4 sqlite3VdbeAddOp2(v, OP_Count, iIdxCur, regStat4+3); #endif sqlite3VdbeAddOp2(v, OP_Integer, nCol, regStat4+1); sqlite3VdbeAddOp2(v, OP_Integer, pIdx->nKeyCol, regStat4+2); sqlite3VdbeAddOp4(v, OP_Function0, 0, regStat4+1, regStat4, (char*)&statInitFuncdef, P4_FUNCDEF); sqlite3VdbeChangeP5(v, 2+IsStat34); /* Implementation of the following: ** ** Rewind csr ** if eof(csr) goto end_of_scan; ** regChng = 0 ** goto next_push_0; ** */ addrRewind = sqlite3VdbeAddOp1(v, OP_Rewind, iIdxCur); VdbeCoverage(v); sqlite3VdbeAddOp2(v, OP_Integer, 0, regChng); addrNextRow = sqlite3VdbeCurrentAddr(v); if( nColTest>0 ){ int endDistinctTest = sqlite3VdbeMakeLabel(v); int *aGotoChng; /* Array of jump instruction addresses */ aGotoChng = sqlite3DbMallocRawNN(db, sizeof(int)*nColTest); if( aGotoChng==0 ) continue; /* ** next_row: ** regChng = 0 ** if( idx(0) != regPrev(0) ) goto chng_addr_0 ** regChng = 1 ** if( idx(1) != regPrev(1) ) goto chng_addr_1 ** ... ** regChng = N ** goto endDistinctTest */ sqlite3VdbeAddOp0(v, OP_Goto); addrNextRow = sqlite3VdbeCurrentAddr(v); if( nColTest==1 && pIdx->nKeyCol==1 && IsUniqueIndex(pIdx) ){ /* For a single-column UNIQUE index, once we have found a non-NULL ** row, we know that all the rest will be distinct, so skip ** subsequent distinctness tests. */ sqlite3VdbeAddOp2(v, OP_NotNull, regPrev, endDistinctTest); VdbeCoverage(v); } for(i=0; iazColl[i]); sqlite3VdbeAddOp2(v, OP_Integer, i, regChng); sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, i, regTemp); aGotoChng[i] = sqlite3VdbeAddOp4(v, OP_Ne, regTemp, 0, regPrev+i, pColl, P4_COLLSEQ); sqlite3VdbeChangeP5(v, SQLITE_NULLEQ); VdbeCoverage(v); } sqlite3VdbeAddOp2(v, OP_Integer, nColTest, regChng); sqlite3VdbeGoto(v, endDistinctTest); /* ** chng_addr_0: ** regPrev(0) = idx(0) ** chng_addr_1: ** regPrev(1) = idx(1) ** ... */ sqlite3VdbeJumpHere(v, addrNextRow-1); for(i=0; ipTable); int j, k, regKey; regKey = sqlite3GetTempRange(pParse, pPk->nKeyCol); for(j=0; jnKeyCol; j++){ k = sqlite3ColumnOfIndex(pIdx, pPk->aiColumn[j]); assert( k>=0 && knCol ); sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, k, regKey+j); VdbeComment((v, "%s", pTab->aCol[pPk->aiColumn[j]].zName)); } sqlite3VdbeAddOp3(v, OP_MakeRecord, regKey, pPk->nKeyCol, regRowid); sqlite3ReleaseTempRange(pParse, regKey, pPk->nKeyCol); } #endif assert( regChng==(regStat4+1) ); sqlite3VdbeAddOp4(v, OP_Function0, 1, regStat4, regTemp, (char*)&statPushFuncdef, P4_FUNCDEF); sqlite3VdbeChangeP5(v, 2+IsStat34); sqlite3VdbeAddOp2(v, OP_Next, iIdxCur, addrNextRow); VdbeCoverage(v); /* Add the entry to the stat1 table. */ callStatGet(v, regStat4, STAT_GET_STAT1, regStat1); assert( "BBB"[0]==SQLITE_AFF_TEXT ); sqlite3VdbeAddOp4(v, OP_MakeRecord, regTabname, 3, regTemp, "BBB", 0); sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur, regNewRowid); sqlite3VdbeAddOp3(v, OP_Insert, iStatCur, regTemp, regNewRowid); sqlite3VdbeChangeP5(v, OPFLAG_APPEND); /* Add the entries to the stat3 or stat4 table. */ #ifdef SQLITE_ENABLE_STAT3_OR_STAT4 { int regEq = regStat1; int regLt = regStat1+1; int regDLt = regStat1+2; int regSample = regStat1+3; int regCol = regStat1+4; int regSampleRowid = regCol + nCol; int addrNext; int addrIsNull; u8 seekOp = HasRowid(pTab) ? OP_NotExists : OP_NotFound; pParse->nMem = MAX(pParse->nMem, regCol+nCol); addrNext = sqlite3VdbeCurrentAddr(v); callStatGet(v, regStat4, STAT_GET_ROWID, regSampleRowid); addrIsNull = sqlite3VdbeAddOp1(v, OP_IsNull, regSampleRowid); VdbeCoverage(v); callStatGet(v, regStat4, STAT_GET_NEQ, regEq); callStatGet(v, regStat4, STAT_GET_NLT, regLt); callStatGet(v, regStat4, STAT_GET_NDLT, regDLt); sqlite3VdbeAddOp4Int(v, seekOp, iTabCur, addrNext, regSampleRowid, 0); /* We know that the regSampleRowid row exists because it was read by ** the previous loop. Thus the not-found jump of seekOp will never ** be taken */ VdbeCoverageNeverTaken(v); #ifdef SQLITE_ENABLE_STAT3 sqlite3ExprCodeLoadIndexColumn(pParse, pIdx, iTabCur, 0, regSample); #else for(i=0; izName)); sqlite3VdbeAddOp2(v, OP_Count, iTabCur, regStat1); jZeroRows = sqlite3VdbeAddOp1(v, OP_IfNot, regStat1); VdbeCoverage(v); sqlite3VdbeAddOp2(v, OP_Null, 0, regIdxname); assert( "BBB"[0]==SQLITE_AFF_TEXT ); sqlite3VdbeAddOp4(v, OP_MakeRecord, regTabname, 3, regTemp, "BBB", 0); sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur, regNewRowid); sqlite3VdbeAddOp3(v, OP_Insert, iStatCur, regTemp, regNewRowid); sqlite3VdbeChangeP5(v, OPFLAG_APPEND); sqlite3VdbeJumpHere(v, jZeroRows); } } /* ** Generate code that will cause the most recent index analysis to ** be loaded into internal hash tables where is can be used. */ static void loadAnalysis(Parse *pParse, int iDb){ Vdbe *v = sqlite3GetVdbe(pParse); if( v ){ sqlite3VdbeAddOp1(v, OP_LoadAnalysis, iDb); } } /* ** Generate code that will do an analysis of an entire database */ static void analyzeDatabase(Parse *pParse, int iDb){ sqlite3 *db = pParse->db; Schema *pSchema = db->aDb[iDb].pSchema; /* Schema of database iDb */ HashElem *k; int iStatCur; int iMem; int iTab; sqlite3BeginWriteOperation(pParse, 0, iDb); iStatCur = pParse->nTab; pParse->nTab += 3; openStatTable(pParse, iDb, iStatCur, 0, 0); iMem = pParse->nMem+1; iTab = pParse->nTab; assert( sqlite3SchemaMutexHeld(db, iDb, 0) ); for(k=sqliteHashFirst(&pSchema->tblHash); k; k=sqliteHashNext(k)){ Table *pTab = (Table*)sqliteHashData(k); analyzeOneTable(pParse, pTab, 0, iStatCur, iMem, iTab); } loadAnalysis(pParse, iDb); } /* ** Generate code that will do an analysis of a single table in ** a database. If pOnlyIdx is not NULL then it is a single index ** in pTab that should be analyzed. */ static void analyzeTable(Parse *pParse, Table *pTab, Index *pOnlyIdx){ int iDb; int iStatCur; assert( pTab!=0 ); assert( sqlite3BtreeHoldsAllMutexes(pParse->db) ); iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema); sqlite3BeginWriteOperation(pParse, 0, iDb); iStatCur = pParse->nTab; pParse->nTab += 3; if( pOnlyIdx ){ openStatTable(pParse, iDb, iStatCur, pOnlyIdx->zName, "idx"); }else{ openStatTable(pParse, iDb, iStatCur, pTab->zName, "tbl"); } analyzeOneTable(pParse, pTab, pOnlyIdx, iStatCur,pParse->nMem+1,pParse->nTab); loadAnalysis(pParse, iDb); } /* ** Generate code for the ANALYZE command. The parser calls this routine ** when it recognizes an ANALYZE command. ** ** ANALYZE -- 1 ** ANALYZE -- 2 ** ANALYZE ?.? -- 3 ** ** Form 1 causes all indices in all attached databases to be analyzed. ** Form 2 analyzes all indices the single database named. ** Form 3 analyzes all indices associated with the named table. */ SQLITE_PRIVATE void sqlite3Analyze(Parse *pParse, Token *pName1, Token *pName2){ sqlite3 *db = pParse->db; int iDb; int i; char *z, *zDb; Table *pTab; Index *pIdx; Token *pTableName; Vdbe *v; /* Read the database schema. If an error occurs, leave an error message ** and code in pParse and return NULL. */ assert( sqlite3BtreeHoldsAllMutexes(pParse->db) ); if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){ return; } assert( pName2!=0 || pName1==0 ); if( pName1==0 ){ /* Form 1: Analyze everything */ for(i=0; inDb; i++){ if( i==1 ) continue; /* Do not analyze the TEMP database */ analyzeDatabase(pParse, i); } }else if( pName2->n==0 ){ /* Form 2: Analyze the database or table named */ iDb = sqlite3FindDb(db, pName1); if( iDb>=0 ){ analyzeDatabase(pParse, iDb); }else{ z = sqlite3NameFromToken(db, pName1); if( z ){ if( (pIdx = sqlite3FindIndex(db, z, 0))!=0 ){ analyzeTable(pParse, pIdx->pTable, pIdx); }else if( (pTab = sqlite3LocateTable(pParse, 0, z, 0))!=0 ){ analyzeTable(pParse, pTab, 0); } sqlite3DbFree(db, z); } } }else{ /* Form 3: Analyze the fully qualified table name */ iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pTableName); if( iDb>=0 ){ zDb = db->aDb[iDb].zDbSName; z = sqlite3NameFromToken(db, pTableName); if( z ){ if( (pIdx = sqlite3FindIndex(db, z, zDb))!=0 ){ analyzeTable(pParse, pIdx->pTable, pIdx); }else if( (pTab = sqlite3LocateTable(pParse, 0, z, zDb))!=0 ){ analyzeTable(pParse, pTab, 0); } sqlite3DbFree(db, z); } } } v = sqlite3GetVdbe(pParse); if( v ) sqlite3VdbeAddOp0(v, OP_Expire); } /* ** Used to pass information from the analyzer reader through to the ** callback routine. */ typedef struct analysisInfo analysisInfo; struct analysisInfo { sqlite3 *db; const char *zDatabase; }; /* ** The first argument points to a nul-terminated string containing a ** list of space separated integers. Read the first nOut of these into ** the array aOut[]. */ static void decodeIntArray( char *zIntArray, /* String containing int array to decode */ int nOut, /* Number of slots in aOut[] */ tRowcnt *aOut, /* Store integers here */ LogEst *aLog, /* Or, if aOut==0, here */ Index *pIndex /* Handle extra flags for this index, if not NULL */ ){ char *z = zIntArray; int c; int i; tRowcnt v; #ifdef SQLITE_ENABLE_STAT3_OR_STAT4 if( z==0 ) z = ""; #else assert( z!=0 ); #endif for(i=0; *z && i='0' && c<='9' ){ v = v*10 + c - '0'; z++; } #ifdef SQLITE_ENABLE_STAT3_OR_STAT4 if( aOut ) aOut[i] = v; if( aLog ) aLog[i] = sqlite3LogEst(v); #else assert( aOut==0 ); UNUSED_PARAMETER(aOut); assert( aLog!=0 ); aLog[i] = sqlite3LogEst(v); #endif if( *z==' ' ) z++; } #ifndef SQLITE_ENABLE_STAT3_OR_STAT4 assert( pIndex!=0 ); { #else if( pIndex ){ #endif pIndex->bUnordered = 0; pIndex->noSkipScan = 0; while( z[0] ){ if( sqlite3_strglob("unordered*", z)==0 ){ pIndex->bUnordered = 1; }else if( sqlite3_strglob("sz=[0-9]*", z)==0 ){ pIndex->szIdxRow = sqlite3LogEst(sqlite3Atoi(z+3)); }else if( sqlite3_strglob("noskipscan*", z)==0 ){ pIndex->noSkipScan = 1; } #ifdef SQLITE_ENABLE_COSTMULT else if( sqlite3_strglob("costmult=[0-9]*",z)==0 ){ pIndex->pTable->costMult = sqlite3LogEst(sqlite3Atoi(z+9)); } #endif while( z[0]!=0 && z[0]!=' ' ) z++; while( z[0]==' ' ) z++; } } } /* ** This callback is invoked once for each index when reading the ** sqlite_stat1 table. ** ** argv[0] = name of the table ** argv[1] = name of the index (might be NULL) ** argv[2] = results of analysis - on integer for each column ** ** Entries for which argv[1]==NULL simply record the number of rows in ** the table. */ static int analysisLoader(void *pData, int argc, char **argv, char **NotUsed){ analysisInfo *pInfo = (analysisInfo*)pData; Index *pIndex; Table *pTable; const char *z; assert( argc==3 ); UNUSED_PARAMETER2(NotUsed, argc); if( argv==0 || argv[0]==0 || argv[2]==0 ){ return 0; } pTable = sqlite3FindTable(pInfo->db, argv[0], pInfo->zDatabase); if( pTable==0 ){ return 0; } if( argv[1]==0 ){ pIndex = 0; }else if( sqlite3_stricmp(argv[0],argv[1])==0 ){ pIndex = sqlite3PrimaryKeyIndex(pTable); }else{ pIndex = sqlite3FindIndex(pInfo->db, argv[1], pInfo->zDatabase); } z = argv[2]; if( pIndex ){ tRowcnt *aiRowEst = 0; int nCol = pIndex->nKeyCol+1; #ifdef SQLITE_ENABLE_STAT3_OR_STAT4 /* Index.aiRowEst may already be set here if there are duplicate ** sqlite_stat1 entries for this index. In that case just clobber ** the old data with the new instead of allocating a new array. */ if( pIndex->aiRowEst==0 ){ pIndex->aiRowEst = (tRowcnt*)sqlite3MallocZero(sizeof(tRowcnt) * nCol); if( pIndex->aiRowEst==0 ) sqlite3OomFault(pInfo->db); } aiRowEst = pIndex->aiRowEst; #endif pIndex->bUnordered = 0; decodeIntArray((char*)z, nCol, aiRowEst, pIndex->aiRowLogEst, pIndex); if( pIndex->pPartIdxWhere==0 ) pTable->nRowLogEst = pIndex->aiRowLogEst[0]; }else{ Index fakeIdx; fakeIdx.szIdxRow = pTable->szTabRow; #ifdef SQLITE_ENABLE_COSTMULT fakeIdx.pTable = pTable; #endif decodeIntArray((char*)z, 1, 0, &pTable->nRowLogEst, &fakeIdx); pTable->szTabRow = fakeIdx.szIdxRow; } return 0; } /* ** If the Index.aSample variable is not NULL, delete the aSample[] array ** and its contents. */ SQLITE_PRIVATE void sqlite3DeleteIndexSamples(sqlite3 *db, Index *pIdx){ #ifdef SQLITE_ENABLE_STAT3_OR_STAT4 if( pIdx->aSample ){ int j; for(j=0; jnSample; j++){ IndexSample *p = &pIdx->aSample[j]; sqlite3DbFree(db, p->p); } sqlite3DbFree(db, pIdx->aSample); } if( db && db->pnBytesFreed==0 ){ pIdx->nSample = 0; pIdx->aSample = 0; } #else UNUSED_PARAMETER(db); UNUSED_PARAMETER(pIdx); #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */ } #ifdef SQLITE_ENABLE_STAT3_OR_STAT4 /* ** Populate the pIdx->aAvgEq[] array based on the samples currently ** stored in pIdx->aSample[]. */ static void initAvgEq(Index *pIdx){ if( pIdx ){ IndexSample *aSample = pIdx->aSample; IndexSample *pFinal = &aSample[pIdx->nSample-1]; int iCol; int nCol = 1; if( pIdx->nSampleCol>1 ){ /* If this is stat4 data, then calculate aAvgEq[] values for all ** sample columns except the last. The last is always set to 1, as ** once the trailing PK fields are considered all index keys are ** unique. */ nCol = pIdx->nSampleCol-1; pIdx->aAvgEq[nCol] = 1; } for(iCol=0; iColnSample; int i; /* Used to iterate through samples */ tRowcnt sumEq = 0; /* Sum of the nEq values */ tRowcnt avgEq = 0; tRowcnt nRow; /* Number of rows in index */ i64 nSum100 = 0; /* Number of terms contributing to sumEq */ i64 nDist100; /* Number of distinct values in index */ if( !pIdx->aiRowEst || iCol>=pIdx->nKeyCol || pIdx->aiRowEst[iCol+1]==0 ){ nRow = pFinal->anLt[iCol]; nDist100 = (i64)100 * pFinal->anDLt[iCol]; nSample--; }else{ nRow = pIdx->aiRowEst[0]; nDist100 = ((i64)100 * pIdx->aiRowEst[0]) / pIdx->aiRowEst[iCol+1]; } pIdx->nRowEst0 = nRow; /* Set nSum to the number of distinct (iCol+1) field prefixes that ** occur in the stat4 table for this index. Set sumEq to the sum of ** the nEq values for column iCol for the same set (adding the value ** only once where there exist duplicate prefixes). */ for(i=0; inSample-1) || aSample[i].anDLt[iCol]!=aSample[i+1].anDLt[iCol] ){ sumEq += aSample[i].anEq[iCol]; nSum100 += 100; } } if( nDist100>nSum100 ){ avgEq = ((i64)100 * (nRow - sumEq))/(nDist100 - nSum100); } if( avgEq==0 ) avgEq = 1; pIdx->aAvgEq[iCol] = avgEq; } } } /* ** Look up an index by name. Or, if the name of a WITHOUT ROWID table ** is supplied instead, find the PRIMARY KEY index for that table. */ static Index *findIndexOrPrimaryKey( sqlite3 *db, const char *zName, const char *zDb ){ Index *pIdx = sqlite3FindIndex(db, zName, zDb); if( pIdx==0 ){ Table *pTab = sqlite3FindTable(db, zName, zDb); if( pTab && !HasRowid(pTab) ) pIdx = sqlite3PrimaryKeyIndex(pTab); } return pIdx; } /* ** Load the content from either the sqlite_stat4 or sqlite_stat3 table ** into the relevant Index.aSample[] arrays. ** ** Arguments zSql1 and zSql2 must point to SQL statements that return ** data equivalent to the following (statements are different for stat3, ** see the caller of this function for details): ** ** zSql1: SELECT idx,count(*) FROM %Q.sqlite_stat4 GROUP BY idx ** zSql2: SELECT idx,neq,nlt,ndlt,sample FROM %Q.sqlite_stat4 ** ** where %Q is replaced with the database name before the SQL is executed. */ static int loadStatTbl( sqlite3 *db, /* Database handle */ int bStat3, /* Assume single column records only */ const char *zSql1, /* SQL statement 1 (see above) */ const char *zSql2, /* SQL statement 2 (see above) */ const char *zDb /* Database name (e.g. "main") */ ){ int rc; /* Result codes from subroutines */ sqlite3_stmt *pStmt = 0; /* An SQL statement being run */ char *zSql; /* Text of the SQL statement */ Index *pPrevIdx = 0; /* Previous index in the loop */ IndexSample *pSample; /* A slot in pIdx->aSample[] */ assert( db->lookaside.bDisable ); zSql = sqlite3MPrintf(db, zSql1, zDb); if( !zSql ){ return SQLITE_NOMEM_BKPT; } rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0); sqlite3DbFree(db, zSql); if( rc ) return rc; while( sqlite3_step(pStmt)==SQLITE_ROW ){ int nIdxCol = 1; /* Number of columns in stat4 records */ char *zIndex; /* Index name */ Index *pIdx; /* Pointer to the index object */ int nSample; /* Number of samples */ int nByte; /* Bytes of space required */ int i; /* Bytes of space required */ tRowcnt *pSpace; zIndex = (char *)sqlite3_column_text(pStmt, 0); if( zIndex==0 ) continue; nSample = sqlite3_column_int(pStmt, 1); pIdx = findIndexOrPrimaryKey(db, zIndex, zDb); assert( pIdx==0 || bStat3 || pIdx->nSample==0 ); /* Index.nSample is non-zero at this point if data has already been ** loaded from the stat4 table. In this case ignore stat3 data. */ if( pIdx==0 || pIdx->nSample ) continue; if( bStat3==0 ){ assert( !HasRowid(pIdx->pTable) || pIdx->nColumn==pIdx->nKeyCol+1 ); if( !HasRowid(pIdx->pTable) && IsPrimaryKeyIndex(pIdx) ){ nIdxCol = pIdx->nKeyCol; }else{ nIdxCol = pIdx->nColumn; } } pIdx->nSampleCol = nIdxCol; nByte = sizeof(IndexSample) * nSample; nByte += sizeof(tRowcnt) * nIdxCol * 3 * nSample; nByte += nIdxCol * sizeof(tRowcnt); /* Space for Index.aAvgEq[] */ pIdx->aSample = sqlite3DbMallocZero(db, nByte); if( pIdx->aSample==0 ){ sqlite3_finalize(pStmt); return SQLITE_NOMEM_BKPT; } pSpace = (tRowcnt*)&pIdx->aSample[nSample]; pIdx->aAvgEq = pSpace; pSpace += nIdxCol; for(i=0; iaSample[i].anEq = pSpace; pSpace += nIdxCol; pIdx->aSample[i].anLt = pSpace; pSpace += nIdxCol; pIdx->aSample[i].anDLt = pSpace; pSpace += nIdxCol; } assert( ((u8*)pSpace)-nByte==(u8*)(pIdx->aSample) ); } rc = sqlite3_finalize(pStmt); if( rc ) return rc; zSql = sqlite3MPrintf(db, zSql2, zDb); if( !zSql ){ return SQLITE_NOMEM_BKPT; } rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0); sqlite3DbFree(db, zSql); if( rc ) return rc; while( sqlite3_step(pStmt)==SQLITE_ROW ){ char *zIndex; /* Index name */ Index *pIdx; /* Pointer to the index object */ int nCol = 1; /* Number of columns in index */ zIndex = (char *)sqlite3_column_text(pStmt, 0); if( zIndex==0 ) continue; pIdx = findIndexOrPrimaryKey(db, zIndex, zDb); if( pIdx==0 ) continue; /* This next condition is true if data has already been loaded from ** the sqlite_stat4 table. In this case ignore stat3 data. */ nCol = pIdx->nSampleCol; if( bStat3 && nCol>1 ) continue; if( pIdx!=pPrevIdx ){ initAvgEq(pPrevIdx); pPrevIdx = pIdx; } pSample = &pIdx->aSample[pIdx->nSample]; decodeIntArray((char*)sqlite3_column_text(pStmt,1),nCol,pSample->anEq,0,0); decodeIntArray((char*)sqlite3_column_text(pStmt,2),nCol,pSample->anLt,0,0); decodeIntArray((char*)sqlite3_column_text(pStmt,3),nCol,pSample->anDLt,0,0); /* Take a copy of the sample. Add two 0x00 bytes the end of the buffer. ** This is in case the sample record is corrupted. In that case, the ** sqlite3VdbeRecordCompare() may read up to two varints past the ** end of the allocated buffer before it realizes it is dealing with ** a corrupt record. Adding the two 0x00 bytes prevents this from causing ** a buffer overread. */ pSample->n = sqlite3_column_bytes(pStmt, 4); pSample->p = sqlite3DbMallocZero(db, pSample->n + 2); if( pSample->p==0 ){ sqlite3_finalize(pStmt); return SQLITE_NOMEM_BKPT; } memcpy(pSample->p, sqlite3_column_blob(pStmt, 4), pSample->n); pIdx->nSample++; } rc = sqlite3_finalize(pStmt); if( rc==SQLITE_OK ) initAvgEq(pPrevIdx); return rc; } /* ** Load content from the sqlite_stat4 and sqlite_stat3 tables into ** the Index.aSample[] arrays of all indices. */ static int loadStat4(sqlite3 *db, const char *zDb){ int rc = SQLITE_OK; /* Result codes from subroutines */ assert( db->lookaside.bDisable ); if( sqlite3FindTable(db, "sqlite_stat4", zDb) ){ rc = loadStatTbl(db, 0, "SELECT idx,count(*) FROM %Q.sqlite_stat4 GROUP BY idx", "SELECT idx,neq,nlt,ndlt,sample FROM %Q.sqlite_stat4", zDb ); } if( rc==SQLITE_OK && sqlite3FindTable(db, "sqlite_stat3", zDb) ){ rc = loadStatTbl(db, 1, "SELECT idx,count(*) FROM %Q.sqlite_stat3 GROUP BY idx", "SELECT idx,neq,nlt,ndlt,sqlite_record(sample) FROM %Q.sqlite_stat3", zDb ); } return rc; } #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */ /* ** Load the content of the sqlite_stat1 and sqlite_stat3/4 tables. The ** contents of sqlite_stat1 are used to populate the Index.aiRowEst[] ** arrays. The contents of sqlite_stat3/4 are used to populate the ** Index.aSample[] arrays. ** ** If the sqlite_stat1 table is not present in the database, SQLITE_ERROR ** is returned. In this case, even if SQLITE_ENABLE_STAT3/4 was defined ** during compilation and the sqlite_stat3/4 table is present, no data is ** read from it. ** ** If SQLITE_ENABLE_STAT3/4 was defined during compilation and the ** sqlite_stat4 table is not present in the database, SQLITE_ERROR is ** returned. However, in this case, data is read from the sqlite_stat1 ** table (if it is present) before returning. ** ** If an OOM error occurs, this function always sets db->mallocFailed. ** This means if the caller does not care about other errors, the return ** code may be ignored. */ SQLITE_PRIVATE int sqlite3AnalysisLoad(sqlite3 *db, int iDb){ analysisInfo sInfo; HashElem *i; char *zSql; int rc = SQLITE_OK; assert( iDb>=0 && iDbnDb ); assert( db->aDb[iDb].pBt!=0 ); /* Clear any prior statistics */ assert( sqlite3SchemaMutexHeld(db, iDb, 0) ); for(i=sqliteHashFirst(&db->aDb[iDb].pSchema->idxHash);i;i=sqliteHashNext(i)){ Index *pIdx = sqliteHashData(i); pIdx->aiRowLogEst[0] = 0; #ifdef SQLITE_ENABLE_STAT3_OR_STAT4 sqlite3DeleteIndexSamples(db, pIdx); pIdx->aSample = 0; #endif } /* Load new statistics out of the sqlite_stat1 table */ sInfo.db = db; sInfo.zDatabase = db->aDb[iDb].zDbSName; if( sqlite3FindTable(db, "sqlite_stat1", sInfo.zDatabase)!=0 ){ zSql = sqlite3MPrintf(db, "SELECT tbl,idx,stat FROM %Q.sqlite_stat1", sInfo.zDatabase); if( zSql==0 ){ rc = SQLITE_NOMEM_BKPT; }else{ rc = sqlite3_exec(db, zSql, analysisLoader, &sInfo, 0); sqlite3DbFree(db, zSql); } } /* Set appropriate defaults on all indexes not in the sqlite_stat1 table */ assert( sqlite3SchemaMutexHeld(db, iDb, 0) ); for(i=sqliteHashFirst(&db->aDb[iDb].pSchema->idxHash);i;i=sqliteHashNext(i)){ Index *pIdx = sqliteHashData(i); if( pIdx->aiRowLogEst[0]==0 ) sqlite3DefaultRowEst(pIdx); } /* Load the statistics from the sqlite_stat4 table. */ #ifdef SQLITE_ENABLE_STAT3_OR_STAT4 if( rc==SQLITE_OK && OptimizationEnabled(db, SQLITE_Stat34) ){ db->lookaside.bDisable++; rc = loadStat4(db, sInfo.zDatabase); db->lookaside.bDisable--; } for(i=sqliteHashFirst(&db->aDb[iDb].pSchema->idxHash);i;i=sqliteHashNext(i)){ Index *pIdx = sqliteHashData(i); sqlite3_free(pIdx->aiRowEst); pIdx->aiRowEst = 0; } #endif if( rc==SQLITE_NOMEM ){ sqlite3OomFault(db); } return rc; } #endif /* SQLITE_OMIT_ANALYZE */ /************** End of analyze.c *********************************************/ /************** Begin file attach.c ******************************************/ /* ** 2003 April 6 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ************************************************************************* ** This file contains code used to implement the ATTACH and DETACH commands. */ /* #include "sqliteInt.h" */ #ifndef SQLITE_OMIT_ATTACH /* ** Resolve an expression that was part of an ATTACH or DETACH statement. This ** is slightly different from resolving a normal SQL expression, because simple ** identifiers are treated as strings, not possible column names or aliases. ** ** i.e. if the parser sees: ** ** ATTACH DATABASE abc AS def ** ** it treats the two expressions as literal strings 'abc' and 'def' instead of ** looking for columns of the same name. ** ** This only applies to the root node of pExpr, so the statement: ** ** ATTACH DATABASE abc||def AS 'db2' ** ** will fail because neither abc or def can be resolved. */ static int resolveAttachExpr(NameContext *pName, Expr *pExpr) { int rc = SQLITE_OK; if( pExpr ){ if( pExpr->op!=TK_ID ){ rc = sqlite3ResolveExprNames(pName, pExpr); }else{ pExpr->op = TK_STRING; } } return rc; } /* ** An SQL user-function registered to do the work of an ATTACH statement. The ** three arguments to the function come directly from an attach statement: ** ** ATTACH DATABASE x AS y KEY z ** ** SELECT sqlite_attach(x, y, z) ** ** If the optional "KEY z" syntax is omitted, an SQL NULL is passed as the ** third argument. */ static void attachFunc( sqlite3_context *context, int NotUsed, sqlite3_value **argv ){ int i; int rc = 0; sqlite3 *db = sqlite3_context_db_handle(context); const char *zName; const char *zFile; char *zPath = 0; char *zErr = 0; unsigned int flags; Db *aNew; char *zErrDyn = 0; sqlite3_vfs *pVfs; UNUSED_PARAMETER(NotUsed); zFile = (const char *)sqlite3_value_text(argv[0]); zName = (const char *)sqlite3_value_text(argv[1]); if( zFile==0 ) zFile = ""; if( zName==0 ) zName = ""; /* Check for the following errors: ** ** * Too many attached databases, ** * Transaction currently open ** * Specified database name already being used. */ if( db->nDb>=db->aLimit[SQLITE_LIMIT_ATTACHED]+2 ){ zErrDyn = sqlite3MPrintf(db, "too many attached databases - max %d", db->aLimit[SQLITE_LIMIT_ATTACHED] ); goto attach_error; } if( !db->autoCommit ){ zErrDyn = sqlite3MPrintf(db, "cannot ATTACH database within transaction"); goto attach_error; } for(i=0; inDb; i++){ char *z = db->aDb[i].zDbSName; assert( z && zName ); if( sqlite3StrICmp(z, zName)==0 ){ zErrDyn = sqlite3MPrintf(db, "database %s is already in use", zName); goto attach_error; } } /* Allocate the new entry in the db->aDb[] array and initialize the schema ** hash tables. */ if( db->aDb==db->aDbStatic ){ aNew = sqlite3DbMallocRawNN(db, sizeof(db->aDb[0])*3 ); if( aNew==0 ) return; memcpy(aNew, db->aDb, sizeof(db->aDb[0])*2); }else{ aNew = sqlite3DbRealloc(db, db->aDb, sizeof(db->aDb[0])*(db->nDb+1) ); if( aNew==0 ) return; } db->aDb = aNew; aNew = &db->aDb[db->nDb]; memset(aNew, 0, sizeof(*aNew)); /* Open the database file. If the btree is successfully opened, use ** it to obtain the database schema. At this point the schema may ** or may not be initialized. */ flags = db->openFlags; rc = sqlite3ParseUri(db->pVfs->zName, zFile, &flags, &pVfs, &zPath, &zErr); if( rc!=SQLITE_OK ){ if( rc==SQLITE_NOMEM ) sqlite3OomFault(db); sqlite3_result_error(context, zErr, -1); sqlite3_free(zErr); return; } assert( pVfs ); flags |= SQLITE_OPEN_MAIN_DB; rc = sqlite3BtreeOpen(pVfs, zPath, db, &aNew->pBt, 0, flags); sqlite3_free( zPath ); db->nDb++; if( rc==SQLITE_CONSTRAINT ){ rc = SQLITE_ERROR; zErrDyn = sqlite3MPrintf(db, "database is already attached"); }else if( rc==SQLITE_OK ){ Pager *pPager; aNew->pSchema = sqlite3SchemaGet(db, aNew->pBt); if( !aNew->pSchema ){ rc = SQLITE_NOMEM_BKPT; }else if( aNew->pSchema->file_format && aNew->pSchema->enc!=ENC(db) ){ zErrDyn = sqlite3MPrintf(db, "attached databases must use the same text encoding as main database"); rc = SQLITE_ERROR; } sqlite3BtreeEnter(aNew->pBt); pPager = sqlite3BtreePager(aNew->pBt); sqlite3PagerLockingMode(pPager, db->dfltLockMode); sqlite3BtreeSecureDelete(aNew->pBt, sqlite3BtreeSecureDelete(db->aDb[0].pBt,-1) ); #ifndef SQLITE_OMIT_PAGER_PRAGMAS sqlite3BtreeSetPagerFlags(aNew->pBt, PAGER_SYNCHRONOUS_FULL | (db->flags & PAGER_FLAGS_MASK)); #endif sqlite3BtreeLeave(aNew->pBt); } aNew->safety_level = SQLITE_DEFAULT_SYNCHRONOUS+1; aNew->zDbSName = sqlite3DbStrDup(db, zName); if( rc==SQLITE_OK && aNew->zDbSName==0 ){ rc = SQLITE_NOMEM_BKPT; } #ifdef SQLITE_HAS_CODEC if( rc==SQLITE_OK ){ extern int sqlite3CodecAttach(sqlite3*, int, const void*, int); extern void sqlite3CodecGetKey(sqlite3*, int, void**, int*); int nKey; char *zKey; int t = sqlite3_value_type(argv[2]); switch( t ){ case SQLITE_INTEGER: case SQLITE_FLOAT: zErrDyn = sqlite3DbStrDup(db, "Invalid key value"); rc = SQLITE_ERROR; break; case SQLITE_TEXT: case SQLITE_BLOB: nKey = sqlite3_value_bytes(argv[2]); zKey = (char *)sqlite3_value_blob(argv[2]); rc = sqlite3CodecAttach(db, db->nDb-1, zKey, nKey); break; case SQLITE_NULL: /* No key specified. Use the key from the main database */ sqlite3CodecGetKey(db, 0, (void**)&zKey, &nKey); if( nKey || sqlite3BtreeGetOptimalReserve(db->aDb[0].pBt)>0 ){ rc = sqlite3CodecAttach(db, db->nDb-1, zKey, nKey); } break; } } #endif /* If the file was opened successfully, read the schema for the new database. ** If this fails, or if opening the file failed, then close the file and ** remove the entry from the db->aDb[] array. i.e. put everything back the way ** we found it. */ if( rc==SQLITE_OK ){ sqlite3BtreeEnterAll(db); rc = sqlite3Init(db, &zErrDyn); sqlite3BtreeLeaveAll(db); } #ifdef SQLITE_USER_AUTHENTICATION if( rc==SQLITE_OK ){ u8 newAuth = 0; rc = sqlite3UserAuthCheckLogin(db, zName, &newAuth); if( newAuthauth.authLevel ){ rc = SQLITE_AUTH_USER; } } #endif if( rc ){ int iDb = db->nDb - 1; assert( iDb>=2 ); if( db->aDb[iDb].pBt ){ sqlite3BtreeClose(db->aDb[iDb].pBt); db->aDb[iDb].pBt = 0; db->aDb[iDb].pSchema = 0; } sqlite3ResetAllSchemasOfConnection(db); db->nDb = iDb; if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){ sqlite3OomFault(db); sqlite3DbFree(db, zErrDyn); zErrDyn = sqlite3MPrintf(db, "out of memory"); }else if( zErrDyn==0 ){ zErrDyn = sqlite3MPrintf(db, "unable to open database: %s", zFile); } goto attach_error; } return; attach_error: /* Return an error if we get here */ if( zErrDyn ){ sqlite3_result_error(context, zErrDyn, -1); sqlite3DbFree(db, zErrDyn); } if( rc ) sqlite3_result_error_code(context, rc); } /* ** An SQL user-function registered to do the work of an DETACH statement. The ** three arguments to the function come directly from a detach statement: ** ** DETACH DATABASE x ** ** SELECT sqlite_detach(x) */ static void detachFunc( sqlite3_context *context, int NotUsed, sqlite3_value **argv ){ const char *zName = (const char *)sqlite3_value_text(argv[0]); sqlite3 *db = sqlite3_context_db_handle(context); int i; Db *pDb = 0; char zErr[128]; UNUSED_PARAMETER(NotUsed); if( zName==0 ) zName = ""; for(i=0; inDb; i++){ pDb = &db->aDb[i]; if( pDb->pBt==0 ) continue; if( sqlite3StrICmp(pDb->zDbSName, zName)==0 ) break; } if( i>=db->nDb ){ sqlite3_snprintf(sizeof(zErr),zErr, "no such database: %s", zName); goto detach_error; } if( i<2 ){ sqlite3_snprintf(sizeof(zErr),zErr, "cannot detach database %s", zName); goto detach_error; } if( !db->autoCommit ){ sqlite3_snprintf(sizeof(zErr), zErr, "cannot DETACH database within transaction"); goto detach_error; } if( sqlite3BtreeIsInReadTrans(pDb->pBt) || sqlite3BtreeIsInBackup(pDb->pBt) ){ sqlite3_snprintf(sizeof(zErr),zErr, "database %s is locked", zName); goto detach_error; } sqlite3BtreeClose(pDb->pBt); pDb->pBt = 0; pDb->pSchema = 0; sqlite3CollapseDatabaseArray(db); return; detach_error: sqlite3_result_error(context, zErr, -1); } /* ** This procedure generates VDBE code for a single invocation of either the ** sqlite_detach() or sqlite_attach() SQL user functions. */ static void codeAttach( Parse *pParse, /* The parser context */ int type, /* Either SQLITE_ATTACH or SQLITE_DETACH */ FuncDef const *pFunc,/* FuncDef wrapper for detachFunc() or attachFunc() */ Expr *pAuthArg, /* Expression to pass to authorization callback */ Expr *pFilename, /* Name of database file */ Expr *pDbname, /* Name of the database to use internally */ Expr *pKey /* Database key for encryption extension */ ){ int rc; NameContext sName; Vdbe *v; sqlite3* db = pParse->db; int regArgs; memset(&sName, 0, sizeof(NameContext)); sName.pParse = pParse; if( SQLITE_OK!=(rc = resolveAttachExpr(&sName, pFilename)) || SQLITE_OK!=(rc = resolveAttachExpr(&sName, pDbname)) || SQLITE_OK!=(rc = resolveAttachExpr(&sName, pKey)) ){ goto attach_end; } #ifndef SQLITE_OMIT_AUTHORIZATION if( pAuthArg ){ char *zAuthArg; if( pAuthArg->op==TK_STRING ){ zAuthArg = pAuthArg->u.zToken; }else{ zAuthArg = 0; } rc = sqlite3AuthCheck(pParse, type, zAuthArg, 0, 0); if(rc!=SQLITE_OK ){ goto attach_end; } } #endif /* SQLITE_OMIT_AUTHORIZATION */ v = sqlite3GetVdbe(pParse); regArgs = sqlite3GetTempRange(pParse, 4); sqlite3ExprCode(pParse, pFilename, regArgs); sqlite3ExprCode(pParse, pDbname, regArgs+1); sqlite3ExprCode(pParse, pKey, regArgs+2); assert( v || db->mallocFailed ); if( v ){ sqlite3VdbeAddOp4(v, OP_Function0, 0, regArgs+3-pFunc->nArg, regArgs+3, (char *)pFunc, P4_FUNCDEF); assert( pFunc->nArg==-1 || (pFunc->nArg&0xff)==pFunc->nArg ); sqlite3VdbeChangeP5(v, (u8)(pFunc->nArg)); /* Code an OP_Expire. For an ATTACH statement, set P1 to true (expire this ** statement only). For DETACH, set it to false (expire all existing ** statements). */ sqlite3VdbeAddOp1(v, OP_Expire, (type==SQLITE_ATTACH)); } attach_end: sqlite3ExprDelete(db, pFilename); sqlite3ExprDelete(db, pDbname); sqlite3ExprDelete(db, pKey); } /* ** Called by the parser to compile a DETACH statement. ** ** DETACH pDbname */ SQLITE_PRIVATE void sqlite3Detach(Parse *pParse, Expr *pDbname){ static const FuncDef detach_func = { 1, /* nArg */ SQLITE_UTF8, /* funcFlags */ 0, /* pUserData */ 0, /* pNext */ detachFunc, /* xSFunc */ 0, /* xFinalize */ "sqlite_detach", /* zName */ {0} }; codeAttach(pParse, SQLITE_DETACH, &detach_func, pDbname, 0, 0, pDbname); } /* ** Called by the parser to compile an ATTACH statement. ** ** ATTACH p AS pDbname KEY pKey */ SQLITE_PRIVATE void sqlite3Attach(Parse *pParse, Expr *p, Expr *pDbname, Expr *pKey){ static const FuncDef attach_func = { 3, /* nArg */ SQLITE_UTF8, /* funcFlags */ 0, /* pUserData */ 0, /* pNext */ attachFunc, /* xSFunc */ 0, /* xFinalize */ "sqlite_attach", /* zName */ {0} }; codeAttach(pParse, SQLITE_ATTACH, &attach_func, p, p, pDbname, pKey); } #endif /* SQLITE_OMIT_ATTACH */ /* ** Initialize a DbFixer structure. This routine must be called prior ** to passing the structure to one of the sqliteFixAAAA() routines below. */ SQLITE_PRIVATE void sqlite3FixInit( DbFixer *pFix, /* The fixer to be initialized */ Parse *pParse, /* Error messages will be written here */ int iDb, /* This is the database that must be used */ const char *zType, /* "view", "trigger", or "index" */ const Token *pName /* Name of the view, trigger, or index */ ){ sqlite3 *db; db = pParse->db; assert( db->nDb>iDb ); pFix->pParse = pParse; pFix->zDb = db->aDb[iDb].zDbSName; pFix->pSchema = db->aDb[iDb].pSchema; pFix->zType = zType; pFix->pName = pName; pFix->bVarOnly = (iDb==1); } /* ** The following set of routines walk through the parse tree and assign ** a specific database to all table references where the database name ** was left unspecified in the original SQL statement. The pFix structure ** must have been initialized by a prior call to sqlite3FixInit(). ** ** These routines are used to make sure that an index, trigger, or ** view in one database does not refer to objects in a different database. ** (Exception: indices, triggers, and views in the TEMP database are ** allowed to refer to anything.) If a reference is explicitly made ** to an object in a different database, an error message is added to ** pParse->zErrMsg and these routines return non-zero. If everything ** checks out, these routines return 0. */ SQLITE_PRIVATE int sqlite3FixSrcList( DbFixer *pFix, /* Context of the fixation */ SrcList *pList /* The Source list to check and modify */ ){ int i; const char *zDb; struct SrcList_item *pItem; if( NEVER(pList==0) ) return 0; zDb = pFix->zDb; for(i=0, pItem=pList->a; inSrc; i++, pItem++){ if( pFix->bVarOnly==0 ){ if( pItem->zDatabase && sqlite3StrICmp(pItem->zDatabase, zDb) ){ sqlite3ErrorMsg(pFix->pParse, "%s %T cannot reference objects in database %s", pFix->zType, pFix->pName, pItem->zDatabase); return 1; } sqlite3DbFree(pFix->pParse->db, pItem->zDatabase); pItem->zDatabase = 0; pItem->pSchema = pFix->pSchema; } #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER) if( sqlite3FixSelect(pFix, pItem->pSelect) ) return 1; if( sqlite3FixExpr(pFix, pItem->pOn) ) return 1; #endif } return 0; } #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER) SQLITE_PRIVATE int sqlite3FixSelect( DbFixer *pFix, /* Context of the fixation */ Select *pSelect /* The SELECT statement to be fixed to one database */ ){ while( pSelect ){ if( sqlite3FixExprList(pFix, pSelect->pEList) ){ return 1; } if( sqlite3FixSrcList(pFix, pSelect->pSrc) ){ return 1; } if( sqlite3FixExpr(pFix, pSelect->pWhere) ){ return 1; } if( sqlite3FixExprList(pFix, pSelect->pGroupBy) ){ return 1; } if( sqlite3FixExpr(pFix, pSelect->pHaving) ){ return 1; } if( sqlite3FixExprList(pFix, pSelect->pOrderBy) ){ return 1; } if( sqlite3FixExpr(pFix, pSelect->pLimit) ){ return 1; } if( sqlite3FixExpr(pFix, pSelect->pOffset) ){ return 1; } pSelect = pSelect->pPrior; } return 0; } SQLITE_PRIVATE int sqlite3FixExpr( DbFixer *pFix, /* Context of the fixation */ Expr *pExpr /* The expression to be fixed to one database */ ){ while( pExpr ){ if( pExpr->op==TK_VARIABLE ){ if( pFix->pParse->db->init.busy ){ pExpr->op = TK_NULL; }else{ sqlite3ErrorMsg(pFix->pParse, "%s cannot use variables", pFix->zType); return 1; } } if( ExprHasProperty(pExpr, EP_TokenOnly|EP_Leaf) ) break; if( ExprHasProperty(pExpr, EP_xIsSelect) ){ if( sqlite3FixSelect(pFix, pExpr->x.pSelect) ) return 1; }else{ if( sqlite3FixExprList(pFix, pExpr->x.pList) ) return 1; } if( sqlite3FixExpr(pFix, pExpr->pRight) ){ return 1; } pExpr = pExpr->pLeft; } return 0; } SQLITE_PRIVATE int sqlite3FixExprList( DbFixer *pFix, /* Context of the fixation */ ExprList *pList /* The expression to be fixed to one database */ ){ int i; struct ExprList_item *pItem; if( pList==0 ) return 0; for(i=0, pItem=pList->a; inExpr; i++, pItem++){ if( sqlite3FixExpr(pFix, pItem->pExpr) ){ return 1; } } return 0; } #endif #ifndef SQLITE_OMIT_TRIGGER SQLITE_PRIVATE int sqlite3FixTriggerStep( DbFixer *pFix, /* Context of the fixation */ TriggerStep *pStep /* The trigger step be fixed to one database */ ){ while( pStep ){ if( sqlite3FixSelect(pFix, pStep->pSelect) ){ return 1; } if( sqlite3FixExpr(pFix, pStep->pWhere) ){ return 1; } if( sqlite3FixExprList(pFix, pStep->pExprList) ){ return 1; } pStep = pStep->pNext; } return 0; } #endif /************** End of attach.c **********************************************/ /************** Begin file auth.c ********************************************/ /* ** 2003 January 11 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ************************************************************************* ** This file contains code used to implement the sqlite3_set_authorizer() ** API. This facility is an optional feature of the library. Embedded ** systems that do not need this facility may omit it by recompiling ** the library with -DSQLITE_OMIT_AUTHORIZATION=1 */ /* #include "sqliteInt.h" */ /* ** All of the code in this file may be omitted by defining a single ** macro. */ #ifndef SQLITE_OMIT_AUTHORIZATION /* ** Set or clear the access authorization function. ** ** The access authorization function is be called during the compilation ** phase to verify that the user has read and/or write access permission on ** various fields of the database. The first argument to the auth function ** is a copy of the 3rd argument to this routine. The second argument ** to the auth function is one of these constants: ** ** SQLITE_CREATE_INDEX ** SQLITE_CREATE_TABLE ** SQLITE_CREATE_TEMP_INDEX ** SQLITE_CREATE_TEMP_TABLE ** SQLITE_CREATE_TEMP_TRIGGER ** SQLITE_CREATE_TEMP_VIEW ** SQLITE_CREATE_TRIGGER ** SQLITE_CREATE_VIEW ** SQLITE_DELETE ** SQLITE_DROP_INDEX ** SQLITE_DROP_TABLE ** SQLITE_DROP_TEMP_INDEX ** SQLITE_DROP_TEMP_TABLE ** SQLITE_DROP_TEMP_TRIGGER ** SQLITE_DROP_TEMP_VIEW ** SQLITE_DROP_TRIGGER ** SQLITE_DROP_VIEW ** SQLITE_INSERT ** SQLITE_PRAGMA ** SQLITE_READ ** SQLITE_SELECT ** SQLITE_TRANSACTION ** SQLITE_UPDATE ** ** The third and fourth arguments to the auth function are the name of ** the table and the column that are being accessed. The auth function ** should return either SQLITE_OK, SQLITE_DENY, or SQLITE_IGNORE. If ** SQLITE_OK is returned, it means that access is allowed. SQLITE_DENY ** means that the SQL statement will never-run - the sqlite3_exec() call ** will return with an error. SQLITE_IGNORE means that the SQL statement ** should run but attempts to read the specified column will return NULL ** and attempts to write the column will be ignored. ** ** Setting the auth function to NULL disables this hook. The default ** setting of the auth function is NULL. */ SQLITE_API int sqlite3_set_authorizer( sqlite3 *db, int (*xAuth)(void*,int,const char*,const char*,const char*,const char*), void *pArg ){ #ifdef SQLITE_ENABLE_API_ARMOR if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT; #endif sqlite3_mutex_enter(db->mutex); db->xAuth = (sqlite3_xauth)xAuth; db->pAuthArg = pArg; sqlite3ExpirePreparedStatements(db); sqlite3_mutex_leave(db->mutex); return SQLITE_OK; } /* ** Write an error message into pParse->zErrMsg that explains that the ** user-supplied authorization function returned an illegal value. */ static void sqliteAuthBadReturnCode(Parse *pParse){ sqlite3ErrorMsg(pParse, "authorizer malfunction"); pParse->rc = SQLITE_ERROR; } /* ** Invoke the authorization callback for permission to read column zCol from ** table zTab in database zDb. This function assumes that an authorization ** callback has been registered (i.e. that sqlite3.xAuth is not NULL). ** ** If SQLITE_IGNORE is returned and pExpr is not NULL, then pExpr is changed ** to an SQL NULL expression. Otherwise, if pExpr is NULL, then SQLITE_IGNORE ** is treated as SQLITE_DENY. In this case an error is left in pParse. */ SQLITE_PRIVATE int sqlite3AuthReadCol( Parse *pParse, /* The parser context */ const char *zTab, /* Table name */ const char *zCol, /* Column name */ int iDb /* Index of containing database. */ ){ sqlite3 *db = pParse->db; /* Database handle */ char *zDb = db->aDb[iDb].zDbSName; /* Schema name of attached database */ int rc; /* Auth callback return code */ if( db->init.busy ) return SQLITE_OK; rc = db->xAuth(db->pAuthArg, SQLITE_READ, zTab,zCol,zDb,pParse->zAuthContext #ifdef SQLITE_USER_AUTHENTICATION ,db->auth.zAuthUser #endif ); if( rc==SQLITE_DENY ){ if( db->nDb>2 || iDb!=0 ){ sqlite3ErrorMsg(pParse, "access to %s.%s.%s is prohibited",zDb,zTab,zCol); }else{ sqlite3ErrorMsg(pParse, "access to %s.%s is prohibited", zTab, zCol); } pParse->rc = SQLITE_AUTH; }else if( rc!=SQLITE_IGNORE && rc!=SQLITE_OK ){ sqliteAuthBadReturnCode(pParse); } return rc; } /* ** The pExpr should be a TK_COLUMN expression. The table referred to ** is in pTabList or else it is the NEW or OLD table of a trigger. ** Check to see if it is OK to read this particular column. ** ** If the auth function returns SQLITE_IGNORE, change the TK_COLUMN ** instruction into a TK_NULL. If the auth function returns SQLITE_DENY, ** then generate an error. */ SQLITE_PRIVATE void sqlite3AuthRead( Parse *pParse, /* The parser context */ Expr *pExpr, /* The expression to check authorization on */ Schema *pSchema, /* The schema of the expression */ SrcList *pTabList /* All table that pExpr might refer to */ ){ sqlite3 *db = pParse->db; Table *pTab = 0; /* The table being read */ const char *zCol; /* Name of the column of the table */ int iSrc; /* Index in pTabList->a[] of table being read */ int iDb; /* The index of the database the expression refers to */ int iCol; /* Index of column in table */ if( db->xAuth==0 ) return; iDb = sqlite3SchemaToIndex(pParse->db, pSchema); if( iDb<0 ){ /* An attempt to read a column out of a subquery or other ** temporary table. */ return; } assert( pExpr->op==TK_COLUMN || pExpr->op==TK_TRIGGER ); if( pExpr->op==TK_TRIGGER ){ pTab = pParse->pTriggerTab; }else{ assert( pTabList ); for(iSrc=0; ALWAYS(iSrcnSrc); iSrc++){ if( pExpr->iTable==pTabList->a[iSrc].iCursor ){ pTab = pTabList->a[iSrc].pTab; break; } } } iCol = pExpr->iColumn; if( NEVER(pTab==0) ) return; if( iCol>=0 ){ assert( iColnCol ); zCol = pTab->aCol[iCol].zName; }else if( pTab->iPKey>=0 ){ assert( pTab->iPKeynCol ); zCol = pTab->aCol[pTab->iPKey].zName; }else{ zCol = "ROWID"; } assert( iDb>=0 && iDbnDb ); if( SQLITE_IGNORE==sqlite3AuthReadCol(pParse, pTab->zName, zCol, iDb) ){ pExpr->op = TK_NULL; } } /* ** Do an authorization check using the code and arguments given. Return ** either SQLITE_OK (zero) or SQLITE_IGNORE or SQLITE_DENY. If SQLITE_DENY ** is returned, then the error count and error message in pParse are ** modified appropriately. */ SQLITE_PRIVATE int sqlite3AuthCheck( Parse *pParse, int code, const char *zArg1, const char *zArg2, const char *zArg3 ){ sqlite3 *db = pParse->db; int rc; /* Don't do any authorization checks if the database is initialising ** or if the parser is being invoked from within sqlite3_declare_vtab. */ if( db->init.busy || IN_DECLARE_VTAB ){ return SQLITE_OK; } if( db->xAuth==0 ){ return SQLITE_OK; } rc = db->xAuth(db->pAuthArg, code, zArg1, zArg2, zArg3, pParse->zAuthContext #ifdef SQLITE_USER_AUTHENTICATION ,db->auth.zAuthUser #endif ); if( rc==SQLITE_DENY ){ sqlite3ErrorMsg(pParse, "not authorized"); pParse->rc = SQLITE_AUTH; }else if( rc!=SQLITE_OK && rc!=SQLITE_IGNORE ){ rc = SQLITE_DENY; sqliteAuthBadReturnCode(pParse); } return rc; } /* ** Push an authorization context. After this routine is called, the ** zArg3 argument to authorization callbacks will be zContext until ** popped. Or if pParse==0, this routine is a no-op. */ SQLITE_PRIVATE void sqlite3AuthContextPush( Parse *pParse, AuthContext *pContext, const char *zContext ){ assert( pParse ); pContext->pParse = pParse; pContext->zAuthContext = pParse->zAuthContext; pParse->zAuthContext = zContext; } /* ** Pop an authorization context that was previously pushed ** by sqlite3AuthContextPush */ SQLITE_PRIVATE void sqlite3AuthContextPop(AuthContext *pContext){ if( pContext->pParse ){ pContext->pParse->zAuthContext = pContext->zAuthContext; pContext->pParse = 0; } } #endif /* SQLITE_OMIT_AUTHORIZATION */ /************** End of auth.c ************************************************/ /************** Begin file build.c *******************************************/ /* ** 2001 September 15 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ************************************************************************* ** This file contains C code routines that are called by the SQLite parser ** when syntax rules are reduced. The routines in this file handle the ** following kinds of SQL syntax: ** ** CREATE TABLE ** DROP TABLE ** CREATE INDEX ** DROP INDEX ** creating ID lists ** BEGIN TRANSACTION ** COMMIT ** ROLLBACK */ /* #include "sqliteInt.h" */ #ifndef SQLITE_OMIT_SHARED_CACHE /* ** The TableLock structure is only used by the sqlite3TableLock() and ** codeTableLocks() functions. */ struct TableLock { int iDb; /* The database containing the table to be locked */ int iTab; /* The root page of the table to be locked */ u8 isWriteLock; /* True for write lock. False for a read lock */ const char *zName; /* Name of the table */ }; /* ** Record the fact that we want to lock a table at run-time. ** ** The table to be locked has root page iTab and is found in database iDb. ** A read or a write lock can be taken depending on isWritelock. ** ** This routine just records the fact that the lock is desired. The ** code to make the lock occur is generated by a later call to ** codeTableLocks() which occurs during sqlite3FinishCoding(). */ SQLITE_PRIVATE void sqlite3TableLock( Parse *pParse, /* Parsing context */ int iDb, /* Index of the database containing the table to lock */ int iTab, /* Root page number of the table to be locked */ u8 isWriteLock, /* True for a write lock */ const char *zName /* Name of the table to be locked */ ){ Parse *pToplevel = sqlite3ParseToplevel(pParse); int i; int nBytes; TableLock *p; assert( iDb>=0 ); for(i=0; inTableLock; i++){ p = &pToplevel->aTableLock[i]; if( p->iDb==iDb && p->iTab==iTab ){ p->isWriteLock = (p->isWriteLock || isWriteLock); return; } } nBytes = sizeof(TableLock) * (pToplevel->nTableLock+1); pToplevel->aTableLock = sqlite3DbReallocOrFree(pToplevel->db, pToplevel->aTableLock, nBytes); if( pToplevel->aTableLock ){ p = &pToplevel->aTableLock[pToplevel->nTableLock++]; p->iDb = iDb; p->iTab = iTab; p->isWriteLock = isWriteLock; p->zName = zName; }else{ pToplevel->nTableLock = 0; sqlite3OomFault(pToplevel->db); } } /* ** Code an OP_TableLock instruction for each table locked by the ** statement (configured by calls to sqlite3TableLock()). */ static void codeTableLocks(Parse *pParse){ int i; Vdbe *pVdbe; pVdbe = sqlite3GetVdbe(pParse); assert( pVdbe!=0 ); /* sqlite3GetVdbe cannot fail: VDBE already allocated */ for(i=0; inTableLock; i++){ TableLock *p = &pParse->aTableLock[i]; int p1 = p->iDb; sqlite3VdbeAddOp4(pVdbe, OP_TableLock, p1, p->iTab, p->isWriteLock, p->zName, P4_STATIC); } } #else #define codeTableLocks(x) #endif /* ** Return TRUE if the given yDbMask object is empty - if it contains no ** 1 bits. This routine is used by the DbMaskAllZero() and DbMaskNotZero() ** macros when SQLITE_MAX_ATTACHED is greater than 30. */ #if SQLITE_MAX_ATTACHED>30 SQLITE_PRIVATE int sqlite3DbMaskAllZero(yDbMask m){ int i; for(i=0; ipToplevel==0 ); db = pParse->db; if( pParse->nested ) return; if( db->mallocFailed || pParse->nErr ){ if( pParse->rc==SQLITE_OK ) pParse->rc = SQLITE_ERROR; return; } /* Begin by generating some termination code at the end of the ** vdbe program */ v = sqlite3GetVdbe(pParse); assert( !pParse->isMultiWrite || sqlite3VdbeAssertMayAbort(v, pParse->mayAbort)); if( v ){ sqlite3VdbeAddOp0(v, OP_Halt); #if SQLITE_USER_AUTHENTICATION if( pParse->nTableLock>0 && db->init.busy==0 ){ sqlite3UserAuthInit(db); if( db->auth.authLevelrc = SQLITE_AUTH_USER; return; } } #endif /* The cookie mask contains one bit for each database file open. ** (Bit 0 is for main, bit 1 is for temp, and so forth.) Bits are ** set for each database that is used. Generate code to start a ** transaction on each used database and to verify the schema cookie ** on each used database. */ if( db->mallocFailed==0 && (DbMaskNonZero(pParse->cookieMask) || pParse->pConstExpr) ){ int iDb, i; assert( sqlite3VdbeGetOp(v, 0)->opcode==OP_Init ); sqlite3VdbeJumpHere(v, 0); for(iDb=0; iDbnDb; iDb++){ Schema *pSchema; if( DbMaskTest(pParse->cookieMask, iDb)==0 ) continue; sqlite3VdbeUsesBtree(v, iDb); pSchema = db->aDb[iDb].pSchema; sqlite3VdbeAddOp4Int(v, OP_Transaction, /* Opcode */ iDb, /* P1 */ DbMaskTest(pParse->writeMask,iDb), /* P2 */ pSchema->schema_cookie, /* P3 */ pSchema->iGeneration /* P4 */ ); if( db->init.busy==0 ) sqlite3VdbeChangeP5(v, 1); VdbeComment((v, "usesStmtJournal=%d", pParse->mayAbort && pParse->isMultiWrite)); } #ifndef SQLITE_OMIT_VIRTUALTABLE for(i=0; inVtabLock; i++){ char *vtab = (char *)sqlite3GetVTable(db, pParse->apVtabLock[i]); sqlite3VdbeAddOp4(v, OP_VBegin, 0, 0, 0, vtab, P4_VTAB); } pParse->nVtabLock = 0; #endif /* Once all the cookies have been verified and transactions opened, ** obtain the required table-locks. This is a no-op unless the ** shared-cache feature is enabled. */ codeTableLocks(pParse); /* Initialize any AUTOINCREMENT data structures required. */ sqlite3AutoincrementBegin(pParse); /* Code constant expressions that where factored out of inner loops */ if( pParse->pConstExpr ){ ExprList *pEL = pParse->pConstExpr; pParse->okConstFactor = 0; for(i=0; inExpr; i++){ sqlite3ExprCode(pParse, pEL->a[i].pExpr, pEL->a[i].u.iConstExprReg); } } /* Finally, jump back to the beginning of the executable code. */ sqlite3VdbeGoto(v, 1); } } /* Get the VDBE program ready for execution */ if( v && pParse->nErr==0 && !db->mallocFailed ){ assert( pParse->iCacheLevel==0 ); /* Disables and re-enables match */ /* A minimum of one cursor is required if autoincrement is used * See ticket [a696379c1f08866] */ if( pParse->pAinc!=0 && pParse->nTab==0 ) pParse->nTab = 1; sqlite3VdbeMakeReady(v, pParse); pParse->rc = SQLITE_DONE; }else{ pParse->rc = SQLITE_ERROR; } } /* ** Run the parser and code generator recursively in order to generate ** code for the SQL statement given onto the end of the pParse context ** currently under construction. When the parser is run recursively ** this way, the final OP_Halt is not appended and other initialization ** and finalization steps are omitted because those are handling by the ** outermost parser. ** ** Not everything is nestable. This facility is designed to permit ** INSERT, UPDATE, and DELETE operations against SQLITE_MASTER. Use ** care if you decide to try to use this routine for some other purposes. */ SQLITE_PRIVATE void sqlite3NestedParse(Parse *pParse, const char *zFormat, ...){ va_list ap; char *zSql; char *zErrMsg = 0; sqlite3 *db = pParse->db; char saveBuf[PARSE_TAIL_SZ]; if( pParse->nErr ) return; assert( pParse->nested<10 ); /* Nesting should only be of limited depth */ va_start(ap, zFormat); zSql = sqlite3VMPrintf(db, zFormat, ap); va_end(ap); if( zSql==0 ){ return; /* A malloc must have failed */ } pParse->nested++; memcpy(saveBuf, PARSE_TAIL(pParse), PARSE_TAIL_SZ); memset(PARSE_TAIL(pParse), 0, PARSE_TAIL_SZ); sqlite3RunParser(pParse, zSql, &zErrMsg); sqlite3DbFree(db, zErrMsg); sqlite3DbFree(db, zSql); memcpy(PARSE_TAIL(pParse), saveBuf, PARSE_TAIL_SZ); pParse->nested--; } #if SQLITE_USER_AUTHENTICATION /* ** Return TRUE if zTable is the name of the system table that stores the ** list of users and their access credentials. */ SQLITE_PRIVATE int sqlite3UserAuthTable(const char *zTable){ return sqlite3_stricmp(zTable, "sqlite_user")==0; } #endif /* ** Locate the in-memory structure that describes a particular database ** table given the name of that table and (optionally) the name of the ** database containing the table. Return NULL if not found. ** ** If zDatabase is 0, all databases are searched for the table and the ** first matching table is returned. (No checking for duplicate table ** names is done.) The search order is TEMP first, then MAIN, then any ** auxiliary databases added using the ATTACH command. ** ** See also sqlite3LocateTable(). */ SQLITE_PRIVATE Table *sqlite3FindTable(sqlite3 *db, const char *zName, const char *zDatabase){ Table *p = 0; int i; /* All mutexes are required for schema access. Make sure we hold them. */ assert( zDatabase!=0 || sqlite3BtreeHoldsAllMutexes(db) ); #if SQLITE_USER_AUTHENTICATION /* Only the admin user is allowed to know that the sqlite_user table ** exists */ if( db->auth.authLevelnDb; i++){ int j = (i<2) ? i^1 : i; /* Search TEMP before MAIN */ if( zDatabase==0 || sqlite3StrICmp(zDatabase, db->aDb[j].zDbSName)==0 ){ assert( sqlite3SchemaMutexHeld(db, j, 0) ); p = sqlite3HashFind(&db->aDb[j].pSchema->tblHash, zName); if( p ) break; } } return p; } /* ** Locate the in-memory structure that describes a particular database ** table given the name of that table and (optionally) the name of the ** database containing the table. Return NULL if not found. Also leave an ** error message in pParse->zErrMsg. ** ** The difference between this routine and sqlite3FindTable() is that this ** routine leaves an error message in pParse->zErrMsg where ** sqlite3FindTable() does not. */ SQLITE_PRIVATE Table *sqlite3LocateTable( Parse *pParse, /* context in which to report errors */ u32 flags, /* LOCATE_VIEW or LOCATE_NOERR */ const char *zName, /* Name of the table we are looking for */ const char *zDbase /* Name of the database. Might be NULL */ ){ Table *p; /* Read the database schema. If an error occurs, leave an error message ** and code in pParse and return NULL. */ if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){ return 0; } p = sqlite3FindTable(pParse->db, zName, zDbase); if( p==0 ){ const char *zMsg = flags & LOCATE_VIEW ? "no such view" : "no such table"; #ifndef SQLITE_OMIT_VIRTUALTABLE if( sqlite3FindDbName(pParse->db, zDbase)<1 ){ /* If zName is the not the name of a table in the schema created using ** CREATE, then check to see if it is the name of an virtual table that ** can be an eponymous virtual table. */ Module *pMod = (Module*)sqlite3HashFind(&pParse->db->aModule, zName); if( pMod && sqlite3VtabEponymousTableInit(pParse, pMod) ){ return pMod->pEpoTab; } } #endif if( (flags & LOCATE_NOERR)==0 ){ if( zDbase ){ sqlite3ErrorMsg(pParse, "%s: %s.%s", zMsg, zDbase, zName); }else{ sqlite3ErrorMsg(pParse, "%s: %s", zMsg, zName); } pParse->checkSchema = 1; } } return p; } /* ** Locate the table identified by *p. ** ** This is a wrapper around sqlite3LocateTable(). The difference between ** sqlite3LocateTable() and this function is that this function restricts ** the search to schema (p->pSchema) if it is not NULL. p->pSchema may be ** non-NULL if it is part of a view or trigger program definition. See ** sqlite3FixSrcList() for details. */ SQLITE_PRIVATE Table *sqlite3LocateTableItem( Parse *pParse, u32 flags, struct SrcList_item *p ){ const char *zDb; assert( p->pSchema==0 || p->zDatabase==0 ); if( p->pSchema ){ int iDb = sqlite3SchemaToIndex(pParse->db, p->pSchema); zDb = pParse->db->aDb[iDb].zDbSName; }else{ zDb = p->zDatabase; } return sqlite3LocateTable(pParse, flags, p->zName, zDb); } /* ** Locate the in-memory structure that describes ** a particular index given the name of that index ** and the name of the database that contains the index. ** Return NULL if not found. ** ** If zDatabase is 0, all databases are searched for the ** table and the first matching index is returned. (No checking ** for duplicate index names is done.) The search order is ** TEMP first, then MAIN, then any auxiliary databases added ** using the ATTACH command. */ SQLITE_PRIVATE Index *sqlite3FindIndex(sqlite3 *db, const char *zName, const char *zDb){ Index *p = 0; int i; /* All mutexes are required for schema access. Make sure we hold them. */ assert( zDb!=0 || sqlite3BtreeHoldsAllMutexes(db) ); for(i=OMIT_TEMPDB; inDb; i++){ int j = (i<2) ? i^1 : i; /* Search TEMP before MAIN */ Schema *pSchema = db->aDb[j].pSchema; assert( pSchema ); if( zDb && sqlite3StrICmp(zDb, db->aDb[j].zDbSName) ) continue; assert( sqlite3SchemaMutexHeld(db, j, 0) ); p = sqlite3HashFind(&pSchema->idxHash, zName); if( p ) break; } return p; } /* ** Reclaim the memory used by an index */ static void freeIndex(sqlite3 *db, Index *p){ #ifndef SQLITE_OMIT_ANALYZE sqlite3DeleteIndexSamples(db, p); #endif sqlite3ExprDelete(db, p->pPartIdxWhere); sqlite3ExprListDelete(db, p->aColExpr); sqlite3DbFree(db, p->zColAff); if( p->isResized ) sqlite3DbFree(db, (void *)p->azColl); #ifdef SQLITE_ENABLE_STAT3_OR_STAT4 sqlite3_free(p->aiRowEst); #endif sqlite3DbFree(db, p); } /* ** For the index called zIdxName which is found in the database iDb, ** unlike that index from its Table then remove the index from ** the index hash table and free all memory structures associated ** with the index. */ SQLITE_PRIVATE void sqlite3UnlinkAndDeleteIndex(sqlite3 *db, int iDb, const char *zIdxName){ Index *pIndex; Hash *pHash; assert( sqlite3SchemaMutexHeld(db, iDb, 0) ); pHash = &db->aDb[iDb].pSchema->idxHash; pIndex = sqlite3HashInsert(pHash, zIdxName, 0); if( ALWAYS(pIndex) ){ if( pIndex->pTable->pIndex==pIndex ){ pIndex->pTable->pIndex = pIndex->pNext; }else{ Index *p; /* Justification of ALWAYS(); The index must be on the list of ** indices. */ p = pIndex->pTable->pIndex; while( ALWAYS(p) && p->pNext!=pIndex ){ p = p->pNext; } if( ALWAYS(p && p->pNext==pIndex) ){ p->pNext = pIndex->pNext; } } freeIndex(db, pIndex); } db->flags |= SQLITE_InternChanges; } /* ** Look through the list of open database files in db->aDb[] and if ** any have been closed, remove them from the list. Reallocate the ** db->aDb[] structure to a smaller size, if possible. ** ** Entry 0 (the "main" database) and entry 1 (the "temp" database) ** are never candidates for being collapsed. */ SQLITE_PRIVATE void sqlite3CollapseDatabaseArray(sqlite3 *db){ int i, j; for(i=j=2; inDb; i++){ struct Db *pDb = &db->aDb[i]; if( pDb->pBt==0 ){ sqlite3DbFree(db, pDb->zDbSName); pDb->zDbSName = 0; continue; } if( jaDb[j] = db->aDb[i]; } j++; } db->nDb = j; if( db->nDb<=2 && db->aDb!=db->aDbStatic ){ memcpy(db->aDbStatic, db->aDb, 2*sizeof(db->aDb[0])); sqlite3DbFree(db, db->aDb); db->aDb = db->aDbStatic; } } /* ** Reset the schema for the database at index iDb. Also reset the ** TEMP schema. */ SQLITE_PRIVATE void sqlite3ResetOneSchema(sqlite3 *db, int iDb){ Db *pDb; assert( iDbnDb ); /* Case 1: Reset the single schema identified by iDb */ pDb = &db->aDb[iDb]; assert( sqlite3SchemaMutexHeld(db, iDb, 0) ); assert( pDb->pSchema!=0 ); sqlite3SchemaClear(pDb->pSchema); /* If any database other than TEMP is reset, then also reset TEMP ** since TEMP might be holding triggers that reference tables in the ** other database. */ if( iDb!=1 ){ pDb = &db->aDb[1]; assert( pDb->pSchema!=0 ); sqlite3SchemaClear(pDb->pSchema); } return; } /* ** Erase all schema information from all attached databases (including ** "main" and "temp") for a single database connection. */ SQLITE_PRIVATE void sqlite3ResetAllSchemasOfConnection(sqlite3 *db){ int i; sqlite3BtreeEnterAll(db); for(i=0; inDb; i++){ Db *pDb = &db->aDb[i]; if( pDb->pSchema ){ sqlite3SchemaClear(pDb->pSchema); } } db->flags &= ~SQLITE_InternChanges; sqlite3VtabUnlockList(db); sqlite3BtreeLeaveAll(db); sqlite3CollapseDatabaseArray(db); } /* ** This routine is called when a commit occurs. */ SQLITE_PRIVATE void sqlite3CommitInternalChanges(sqlite3 *db){ db->flags &= ~SQLITE_InternChanges; } /* ** Delete memory allocated for the column names of a table or view (the ** Table.aCol[] array). */ SQLITE_PRIVATE void sqlite3DeleteColumnNames(sqlite3 *db, Table *pTable){ int i; Column *pCol; assert( pTable!=0 ); if( (pCol = pTable->aCol)!=0 ){ for(i=0; inCol; i++, pCol++){ sqlite3DbFree(db, pCol->zName); sqlite3ExprDelete(db, pCol->pDflt); sqlite3DbFree(db, pCol->zColl); } sqlite3DbFree(db, pTable->aCol); } } /* ** Remove the memory data structures associated with the given ** Table. No changes are made to disk by this routine. ** ** This routine just deletes the data structure. It does not unlink ** the table data structure from the hash table. But it does destroy ** memory structures of the indices and foreign keys associated with ** the table. ** ** The db parameter is optional. It is needed if the Table object ** contains lookaside memory. (Table objects in the schema do not use ** lookaside memory, but some ephemeral Table objects do.) Or the ** db parameter can be used with db->pnBytesFreed to measure the memory ** used by the Table object. */ static void SQLITE_NOINLINE deleteTable(sqlite3 *db, Table *pTable){ Index *pIndex, *pNext; TESTONLY( int nLookaside; ) /* Used to verify lookaside not used for schema */ /* Record the number of outstanding lookaside allocations in schema Tables ** prior to doing any free() operations. Since schema Tables do not use ** lookaside, this number should not change. */ TESTONLY( nLookaside = (db && (pTable->tabFlags & TF_Ephemeral)==0) ? db->lookaside.nOut : 0 ); /* Delete all indices associated with this table. */ for(pIndex = pTable->pIndex; pIndex; pIndex=pNext){ pNext = pIndex->pNext; assert( pIndex->pSchema==pTable->pSchema || (IsVirtual(pTable) && pIndex->idxType!=SQLITE_IDXTYPE_APPDEF) ); if( (db==0 || db->pnBytesFreed==0) && !IsVirtual(pTable) ){ char *zName = pIndex->zName; TESTONLY ( Index *pOld = ) sqlite3HashInsert( &pIndex->pSchema->idxHash, zName, 0 ); assert( db==0 || sqlite3SchemaMutexHeld(db, 0, pIndex->pSchema) ); assert( pOld==pIndex || pOld==0 ); } freeIndex(db, pIndex); } /* Delete any foreign keys attached to this table. */ sqlite3FkDelete(db, pTable); /* Delete the Table structure itself. */ sqlite3DeleteColumnNames(db, pTable); sqlite3DbFree(db, pTable->zName); sqlite3DbFree(db, pTable->zColAff); sqlite3SelectDelete(db, pTable->pSelect); sqlite3ExprListDelete(db, pTable->pCheck); #ifndef SQLITE_OMIT_VIRTUALTABLE sqlite3VtabClear(db, pTable); #endif sqlite3DbFree(db, pTable); /* Verify that no lookaside memory was used by schema tables */ assert( nLookaside==0 || nLookaside==db->lookaside.nOut ); } SQLITE_PRIVATE void sqlite3DeleteTable(sqlite3 *db, Table *pTable){ /* Do not delete the table until the reference count reaches zero. */ if( !pTable ) return; if( ((!db || db->pnBytesFreed==0) && (--pTable->nRef)>0) ) return; deleteTable(db, pTable); } /* ** Unlink the given table from the hash tables and the delete the ** table structure with all its indices and foreign keys. */ SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTable(sqlite3 *db, int iDb, const char *zTabName){ Table *p; Db *pDb; assert( db!=0 ); assert( iDb>=0 && iDbnDb ); assert( zTabName ); assert( sqlite3SchemaMutexHeld(db, iDb, 0) ); testcase( zTabName[0]==0 ); /* Zero-length table names are allowed */ pDb = &db->aDb[iDb]; p = sqlite3HashInsert(&pDb->pSchema->tblHash, zTabName, 0); sqlite3DeleteTable(db, p); db->flags |= SQLITE_InternChanges; } /* ** Given a token, return a string that consists of the text of that ** token. Space to hold the returned string ** is obtained from sqliteMalloc() and must be freed by the calling ** function. ** ** Any quotation marks (ex: "name", 'name', [name], or `name`) that ** surround the body of the token are removed. ** ** Tokens are often just pointers into the original SQL text and so ** are not \000 terminated and are not persistent. The returned string ** is \000 terminated and is persistent. */ SQLITE_PRIVATE char *sqlite3NameFromToken(sqlite3 *db, Token *pName){ char *zName; if( pName ){ zName = sqlite3DbStrNDup(db, (char*)pName->z, pName->n); sqlite3Dequote(zName); }else{ zName = 0; } return zName; } /* ** Open the sqlite_master table stored in database number iDb for ** writing. The table is opened using cursor 0. */ SQLITE_PRIVATE void sqlite3OpenMasterTable(Parse *p, int iDb){ Vdbe *v = sqlite3GetVdbe(p); sqlite3TableLock(p, iDb, MASTER_ROOT, 1, SCHEMA_TABLE(iDb)); sqlite3VdbeAddOp4Int(v, OP_OpenWrite, 0, MASTER_ROOT, iDb, 5); if( p->nTab==0 ){ p->nTab = 1; } } /* ** Parameter zName points to a nul-terminated buffer containing the name ** of a database ("main", "temp" or the name of an attached db). This ** function returns the index of the named database in db->aDb[], or ** -1 if the named db cannot be found. */ SQLITE_PRIVATE int sqlite3FindDbName(sqlite3 *db, const char *zName){ int i = -1; /* Database number */ if( zName ){ Db *pDb; for(i=(db->nDb-1), pDb=&db->aDb[i]; i>=0; i--, pDb--){ if( 0==sqlite3StrICmp(pDb->zDbSName, zName) ) break; } } return i; } /* ** The token *pName contains the name of a database (either "main" or ** "temp" or the name of an attached db). This routine returns the ** index of the named database in db->aDb[], or -1 if the named db ** does not exist. */ SQLITE_PRIVATE int sqlite3FindDb(sqlite3 *db, Token *pName){ int i; /* Database number */ char *zName; /* Name we are searching for */ zName = sqlite3NameFromToken(db, pName); i = sqlite3FindDbName(db, zName); sqlite3DbFree(db, zName); return i; } /* The table or view or trigger name is passed to this routine via tokens ** pName1 and pName2. If the table name was fully qualified, for example: ** ** CREATE TABLE xxx.yyy (...); ** ** Then pName1 is set to "xxx" and pName2 "yyy". On the other hand if ** the table name is not fully qualified, i.e.: ** ** CREATE TABLE yyy(...); ** ** Then pName1 is set to "yyy" and pName2 is "". ** ** This routine sets the *ppUnqual pointer to point at the token (pName1 or ** pName2) that stores the unqualified table name. The index of the ** database "xxx" is returned. */ SQLITE_PRIVATE int sqlite3TwoPartName( Parse *pParse, /* Parsing and code generating context */ Token *pName1, /* The "xxx" in the name "xxx.yyy" or "xxx" */ Token *pName2, /* The "yyy" in the name "xxx.yyy" */ Token **pUnqual /* Write the unqualified object name here */ ){ int iDb; /* Database holding the object */ sqlite3 *db = pParse->db; assert( pName2!=0 ); if( pName2->n>0 ){ if( db->init.busy ) { sqlite3ErrorMsg(pParse, "corrupt database"); return -1; } *pUnqual = pName2; iDb = sqlite3FindDb(db, pName1); if( iDb<0 ){ sqlite3ErrorMsg(pParse, "unknown database %T", pName1); return -1; } }else{ assert( db->init.iDb==0 || db->init.busy || (db->flags & SQLITE_Vacuum)!=0); iDb = db->init.iDb; *pUnqual = pName1; } return iDb; } /* ** This routine is used to check if the UTF-8 string zName is a legal ** unqualified name for a new schema object (table, index, view or ** trigger). All names are legal except those that begin with the string ** "sqlite_" (in upper, lower or mixed case). This portion of the namespace ** is reserved for internal use. */ SQLITE_PRIVATE int sqlite3CheckObjectName(Parse *pParse, const char *zName){ if( !pParse->db->init.busy && pParse->nested==0 && (pParse->db->flags & SQLITE_WriteSchema)==0 && 0==sqlite3StrNICmp(zName, "sqlite_", 7) ){ sqlite3ErrorMsg(pParse, "object name reserved for internal use: %s", zName); return SQLITE_ERROR; } return SQLITE_OK; } /* ** Return the PRIMARY KEY index of a table */ SQLITE_PRIVATE Index *sqlite3PrimaryKeyIndex(Table *pTab){ Index *p; for(p=pTab->pIndex; p && !IsPrimaryKeyIndex(p); p=p->pNext){} return p; } /* ** Return the column of index pIdx that corresponds to table ** column iCol. Return -1 if not found. */ SQLITE_PRIVATE i16 sqlite3ColumnOfIndex(Index *pIdx, i16 iCol){ int i; for(i=0; inColumn; i++){ if( iCol==pIdx->aiColumn[i] ) return i; } return -1; } /* ** Begin constructing a new table representation in memory. This is ** the first of several action routines that get called in response ** to a CREATE TABLE statement. In particular, this routine is called ** after seeing tokens "CREATE" and "TABLE" and the table name. The isTemp ** flag is true if the table should be stored in the auxiliary database ** file instead of in the main database file. This is normally the case ** when the "TEMP" or "TEMPORARY" keyword occurs in between ** CREATE and TABLE. ** ** The new table record is initialized and put in pParse->pNewTable. ** As more of the CREATE TABLE statement is parsed, additional action ** routines will be called to add more information to this record. ** At the end of the CREATE TABLE statement, the sqlite3EndTable() routine ** is called to complete the construction of the new table record. */ SQLITE_PRIVATE void sqlite3StartTable( Parse *pParse, /* Parser context */ Token *pName1, /* First part of the name of the table or view */ Token *pName2, /* Second part of the name of the table or view */ int isTemp, /* True if this is a TEMP table */ int isView, /* True if this is a VIEW */ int isVirtual, /* True if this is a VIRTUAL table */ int noErr /* Do nothing if table already exists */ ){ Table *pTable; char *zName = 0; /* The name of the new table */ sqlite3 *db = pParse->db; Vdbe *v; int iDb; /* Database number to create the table in */ Token *pName; /* Unqualified name of the table to create */ if( db->init.busy && db->init.newTnum==1 ){ /* Special case: Parsing the sqlite_master or sqlite_temp_master schema */ iDb = db->init.iDb; zName = sqlite3DbStrDup(db, SCHEMA_TABLE(iDb)); pName = pName1; }else{ /* The common case */ iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName); if( iDb<0 ) return; if( !OMIT_TEMPDB && isTemp && pName2->n>0 && iDb!=1 ){ /* If creating a temp table, the name may not be qualified. Unless ** the database name is "temp" anyway. */ sqlite3ErrorMsg(pParse, "temporary table name must be unqualified"); return; } if( !OMIT_TEMPDB && isTemp ) iDb = 1; zName = sqlite3NameFromToken(db, pName); } pParse->sNameToken = *pName; if( zName==0 ) return; if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){ goto begin_table_error; } if( db->init.iDb==1 ) isTemp = 1; #ifndef SQLITE_OMIT_AUTHORIZATION assert( isTemp==0 || isTemp==1 ); assert( isView==0 || isView==1 ); { static const u8 aCode[] = { SQLITE_CREATE_TABLE, SQLITE_CREATE_TEMP_TABLE, SQLITE_CREATE_VIEW, SQLITE_CREATE_TEMP_VIEW }; char *zDb = db->aDb[iDb].zDbSName; if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(isTemp), 0, zDb) ){ goto begin_table_error; } if( !isVirtual && sqlite3AuthCheck(pParse, (int)aCode[isTemp+2*isView], zName, 0, zDb) ){ goto begin_table_error; } } #endif /* Make sure the new table name does not collide with an existing ** index or table name in the same database. Issue an error message if ** it does. The exception is if the statement being parsed was passed ** to an sqlite3_declare_vtab() call. In that case only the column names ** and types will be used, so there is no need to test for namespace ** collisions. */ if( !IN_DECLARE_VTAB ){ char *zDb = db->aDb[iDb].zDbSName; if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){ goto begin_table_error; } pTable = sqlite3FindTable(db, zName, zDb); if( pTable ){ if( !noErr ){ sqlite3ErrorMsg(pParse, "table %T already exists", pName); }else{ assert( !db->init.busy || CORRUPT_DB ); sqlite3CodeVerifySchema(pParse, iDb); } goto begin_table_error; } if( sqlite3FindIndex(db, zName, zDb)!=0 ){ sqlite3ErrorMsg(pParse, "there is already an index named %s", zName); goto begin_table_error; } } pTable = sqlite3DbMallocZero(db, sizeof(Table)); if( pTable==0 ){ assert( db->mallocFailed ); pParse->rc = SQLITE_NOMEM_BKPT; pParse->nErr++; goto begin_table_error; } pTable->zName = zName; pTable->iPKey = -1; pTable->pSchema = db->aDb[iDb].pSchema; pTable->nRef = 1; pTable->nRowLogEst = 200; assert( 200==sqlite3LogEst(1048576) ); assert( pParse->pNewTable==0 ); pParse->pNewTable = pTable; /* If this is the magic sqlite_sequence table used by autoincrement, ** then record a pointer to this table in the main database structure ** so that INSERT can find the table easily. */ #ifndef SQLITE_OMIT_AUTOINCREMENT if( !pParse->nested && strcmp(zName, "sqlite_sequence")==0 ){ assert( sqlite3SchemaMutexHeld(db, iDb, 0) ); pTable->pSchema->pSeqTab = pTable; } #endif /* Begin generating the code that will insert the table record into ** the SQLITE_MASTER table. Note in particular that we must go ahead ** and allocate the record number for the table entry now. Before any ** PRIMARY KEY or UNIQUE keywords are parsed. Those keywords will cause ** indices to be created and the table record must come before the ** indices. Hence, the record number for the table must be allocated ** now. */ if( !db->init.busy && (v = sqlite3GetVdbe(pParse))!=0 ){ int addr1; int fileFormat; int reg1, reg2, reg3; /* nullRow[] is an OP_Record encoding of a row containing 5 NULLs */ static const char nullRow[] = { 6, 0, 0, 0, 0, 0 }; sqlite3BeginWriteOperation(pParse, 1, iDb); #ifndef SQLITE_OMIT_VIRTUALTABLE if( isVirtual ){ sqlite3VdbeAddOp0(v, OP_VBegin); } #endif /* If the file format and encoding in the database have not been set, ** set them now. */ reg1 = pParse->regRowid = ++pParse->nMem; reg2 = pParse->regRoot = ++pParse->nMem; reg3 = ++pParse->nMem; sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, reg3, BTREE_FILE_FORMAT); sqlite3VdbeUsesBtree(v, iDb); addr1 = sqlite3VdbeAddOp1(v, OP_If, reg3); VdbeCoverage(v); fileFormat = (db->flags & SQLITE_LegacyFileFmt)!=0 ? 1 : SQLITE_MAX_FILE_FORMAT; sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_FILE_FORMAT, fileFormat); sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_TEXT_ENCODING, ENC(db)); sqlite3VdbeJumpHere(v, addr1); /* This just creates a place-holder record in the sqlite_master table. ** The record created does not contain anything yet. It will be replaced ** by the real entry in code generated at sqlite3EndTable(). ** ** The rowid for the new entry is left in register pParse->regRowid. ** The root page number of the new table is left in reg pParse->regRoot. ** The rowid and root page number values are needed by the code that ** sqlite3EndTable will generate. */ #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE) if( isView || isVirtual ){ sqlite3VdbeAddOp2(v, OP_Integer, 0, reg2); }else #endif { pParse->addrCrTab = sqlite3VdbeAddOp2(v, OP_CreateTable, iDb, reg2); } sqlite3OpenMasterTable(pParse, iDb); sqlite3VdbeAddOp2(v, OP_NewRowid, 0, reg1); sqlite3VdbeAddOp4(v, OP_Blob, 6, reg3, 0, nullRow, P4_STATIC); sqlite3VdbeAddOp3(v, OP_Insert, 0, reg3, reg1); sqlite3VdbeChangeP5(v, OPFLAG_APPEND); sqlite3VdbeAddOp0(v, OP_Close); } /* Normal (non-error) return. */ return; /* If an error occurs, we jump here */ begin_table_error: sqlite3DbFree(db, zName); return; } /* Set properties of a table column based on the (magical) ** name of the column. */ #if SQLITE_ENABLE_HIDDEN_COLUMNS SQLITE_PRIVATE void sqlite3ColumnPropertiesFromName(Table *pTab, Column *pCol){ if( sqlite3_strnicmp(pCol->zName, "__hidden__", 10)==0 ){ pCol->colFlags |= COLFLAG_HIDDEN; }else if( pTab && pCol!=pTab->aCol && (pCol[-1].colFlags & COLFLAG_HIDDEN) ){ pTab->tabFlags |= TF_OOOHidden; } } #endif /* ** Add a new column to the table currently being constructed. ** ** The parser calls this routine once for each column declaration ** in a CREATE TABLE statement. sqlite3StartTable() gets called ** first to get things going. Then this routine is called for each ** column. */ SQLITE_PRIVATE void sqlite3AddColumn(Parse *pParse, Token *pName, Token *pType){ Table *p; int i; char *z; char *zType; Column *pCol; sqlite3 *db = pParse->db; if( (p = pParse->pNewTable)==0 ) return; #if SQLITE_MAX_COLUMN if( p->nCol+1>db->aLimit[SQLITE_LIMIT_COLUMN] ){ sqlite3ErrorMsg(pParse, "too many columns on %s", p->zName); return; } #endif z = sqlite3DbMallocRaw(db, pName->n + pType->n + 2); if( z==0 ) return; memcpy(z, pName->z, pName->n); z[pName->n] = 0; sqlite3Dequote(z); for(i=0; inCol; i++){ if( sqlite3_stricmp(z, p->aCol[i].zName)==0 ){ sqlite3ErrorMsg(pParse, "duplicate column name: %s", z); sqlite3DbFree(db, z); return; } } if( (p->nCol & 0x7)==0 ){ Column *aNew; aNew = sqlite3DbRealloc(db,p->aCol,(p->nCol+8)*sizeof(p->aCol[0])); if( aNew==0 ){ sqlite3DbFree(db, z); return; } p->aCol = aNew; } pCol = &p->aCol[p->nCol]; memset(pCol, 0, sizeof(p->aCol[0])); pCol->zName = z; sqlite3ColumnPropertiesFromName(p, pCol); if( pType->n==0 ){ /* If there is no type specified, columns have the default affinity ** 'BLOB'. */ pCol->affinity = SQLITE_AFF_BLOB; pCol->szEst = 1; }else{ zType = z + sqlite3Strlen30(z) + 1; memcpy(zType, pType->z, pType->n); zType[pType->n] = 0; sqlite3Dequote(zType); pCol->affinity = sqlite3AffinityType(zType, &pCol->szEst); pCol->colFlags |= COLFLAG_HASTYPE; } p->nCol++; pParse->constraintName.n = 0; } /* ** This routine is called by the parser while in the middle of ** parsing a CREATE TABLE statement. A "NOT NULL" constraint has ** been seen on a column. This routine sets the notNull flag on ** the column currently under construction. */ SQLITE_PRIVATE void sqlite3AddNotNull(Parse *pParse, int onError){ Table *p; p = pParse->pNewTable; if( p==0 || NEVER(p->nCol<1) ) return; p->aCol[p->nCol-1].notNull = (u8)onError; } /* ** Scan the column type name zType (length nType) and return the ** associated affinity type. ** ** This routine does a case-independent search of zType for the ** substrings in the following table. If one of the substrings is ** found, the corresponding affinity is returned. If zType contains ** more than one of the substrings, entries toward the top of ** the table take priority. For example, if zType is 'BLOBINT', ** SQLITE_AFF_INTEGER is returned. ** ** Substring | Affinity ** -------------------------------- ** 'INT' | SQLITE_AFF_INTEGER ** 'CHAR' | SQLITE_AFF_TEXT ** 'CLOB' | SQLITE_AFF_TEXT ** 'TEXT' | SQLITE_AFF_TEXT ** 'BLOB' | SQLITE_AFF_BLOB ** 'REAL' | SQLITE_AFF_REAL ** 'FLOA' | SQLITE_AFF_REAL ** 'DOUB' | SQLITE_AFF_REAL ** ** If none of the substrings in the above table are found, ** SQLITE_AFF_NUMERIC is returned. */ SQLITE_PRIVATE char sqlite3AffinityType(const char *zIn, u8 *pszEst){ u32 h = 0; char aff = SQLITE_AFF_NUMERIC; const char *zChar = 0; assert( zIn!=0 ); while( zIn[0] ){ h = (h<<8) + sqlite3UpperToLower[(*zIn)&0xff]; zIn++; if( h==(('c'<<24)+('h'<<16)+('a'<<8)+'r') ){ /* CHAR */ aff = SQLITE_AFF_TEXT; zChar = zIn; }else if( h==(('c'<<24)+('l'<<16)+('o'<<8)+'b') ){ /* CLOB */ aff = SQLITE_AFF_TEXT; }else if( h==(('t'<<24)+('e'<<16)+('x'<<8)+'t') ){ /* TEXT */ aff = SQLITE_AFF_TEXT; }else if( h==(('b'<<24)+('l'<<16)+('o'<<8)+'b') /* BLOB */ && (aff==SQLITE_AFF_NUMERIC || aff==SQLITE_AFF_REAL) ){ aff = SQLITE_AFF_BLOB; if( zIn[0]=='(' ) zChar = zIn; #ifndef SQLITE_OMIT_FLOATING_POINT }else if( h==(('r'<<24)+('e'<<16)+('a'<<8)+'l') /* REAL */ && aff==SQLITE_AFF_NUMERIC ){ aff = SQLITE_AFF_REAL; }else if( h==(('f'<<24)+('l'<<16)+('o'<<8)+'a') /* FLOA */ && aff==SQLITE_AFF_NUMERIC ){ aff = SQLITE_AFF_REAL; }else if( h==(('d'<<24)+('o'<<16)+('u'<<8)+'b') /* DOUB */ && aff==SQLITE_AFF_NUMERIC ){ aff = SQLITE_AFF_REAL; #endif }else if( (h&0x00FFFFFF)==(('i'<<16)+('n'<<8)+'t') ){ /* INT */ aff = SQLITE_AFF_INTEGER; break; } } /* If pszEst is not NULL, store an estimate of the field size. The ** estimate is scaled so that the size of an integer is 1. */ if( pszEst ){ *pszEst = 1; /* default size is approx 4 bytes */ if( aff255 ) v = 255; *pszEst = v; /* BLOB(k), VARCHAR(k), CHAR(k) -> r=(k/4+1) */ break; } zChar++; } }else{ *pszEst = 5; /* BLOB, TEXT, CLOB -> r=5 (approx 20 bytes)*/ } } } return aff; } /* ** The expression is the default value for the most recently added column ** of the table currently under construction. ** ** Default value expressions must be constant. Raise an exception if this ** is not the case. ** ** This routine is called by the parser while in the middle of ** parsing a CREATE TABLE statement. */ SQLITE_PRIVATE void sqlite3AddDefaultValue(Parse *pParse, ExprSpan *pSpan){ Table *p; Column *pCol; sqlite3 *db = pParse->db; p = pParse->pNewTable; if( p!=0 ){ pCol = &(p->aCol[p->nCol-1]); if( !sqlite3ExprIsConstantOrFunction(pSpan->pExpr, db->init.busy) ){ sqlite3ErrorMsg(pParse, "default value of column [%s] is not constant", pCol->zName); }else{ /* A copy of pExpr is used instead of the original, as pExpr contains ** tokens that point to volatile memory. The 'span' of the expression ** is required by pragma table_info. */ Expr x; sqlite3ExprDelete(db, pCol->pDflt); memset(&x, 0, sizeof(x)); x.op = TK_SPAN; x.u.zToken = sqlite3DbStrNDup(db, (char*)pSpan->zStart, (int)(pSpan->zEnd - pSpan->zStart)); x.pLeft = pSpan->pExpr; x.flags = EP_Skip; pCol->pDflt = sqlite3ExprDup(db, &x, EXPRDUP_REDUCE); sqlite3DbFree(db, x.u.zToken); } } sqlite3ExprDelete(db, pSpan->pExpr); } /* ** Backwards Compatibility Hack: ** ** Historical versions of SQLite accepted strings as column names in ** indexes and PRIMARY KEY constraints and in UNIQUE constraints. Example: ** ** CREATE TABLE xyz(a,b,c,d,e,PRIMARY KEY('a'),UNIQUE('b','c' COLLATE trim) ** CREATE INDEX abc ON xyz('c','d' DESC,'e' COLLATE nocase DESC); ** ** This is goofy. But to preserve backwards compatibility we continue to ** accept it. This routine does the necessary conversion. It converts ** the expression given in its argument from a TK_STRING into a TK_ID ** if the expression is just a TK_STRING with an optional COLLATE clause. ** If the epxression is anything other than TK_STRING, the expression is ** unchanged. */ static void sqlite3StringToId(Expr *p){ if( p->op==TK_STRING ){ p->op = TK_ID; }else if( p->op==TK_COLLATE && p->pLeft->op==TK_STRING ){ p->pLeft->op = TK_ID; } } /* ** Designate the PRIMARY KEY for the table. pList is a list of names ** of columns that form the primary key. If pList is NULL, then the ** most recently added column of the table is the primary key. ** ** A table can have at most one primary key. If the table already has ** a primary key (and this is the second primary key) then create an ** error. ** ** If the PRIMARY KEY is on a single column whose datatype is INTEGER, ** then we will try to use that column as the rowid. Set the Table.iPKey ** field of the table under construction to be the index of the ** INTEGER PRIMARY KEY column. Table.iPKey is set to -1 if there is ** no INTEGER PRIMARY KEY. ** ** If the key is not an INTEGER PRIMARY KEY, then create a unique ** index for the key. No index is created for INTEGER PRIMARY KEYs. */ SQLITE_PRIVATE void sqlite3AddPrimaryKey( Parse *pParse, /* Parsing context */ ExprList *pList, /* List of field names to be indexed */ int onError, /* What to do with a uniqueness conflict */ int autoInc, /* True if the AUTOINCREMENT keyword is present */ int sortOrder /* SQLITE_SO_ASC or SQLITE_SO_DESC */ ){ Table *pTab = pParse->pNewTable; Column *pCol = 0; int iCol = -1, i; int nTerm; if( pTab==0 ) goto primary_key_exit; if( pTab->tabFlags & TF_HasPrimaryKey ){ sqlite3ErrorMsg(pParse, "table \"%s\" has more than one primary key", pTab->zName); goto primary_key_exit; } pTab->tabFlags |= TF_HasPrimaryKey; if( pList==0 ){ iCol = pTab->nCol - 1; pCol = &pTab->aCol[iCol]; pCol->colFlags |= COLFLAG_PRIMKEY; nTerm = 1; }else{ nTerm = pList->nExpr; for(i=0; ia[i].pExpr); assert( pCExpr!=0 ); sqlite3StringToId(pCExpr); if( pCExpr->op==TK_ID ){ const char *zCName = pCExpr->u.zToken; for(iCol=0; iColnCol; iCol++){ if( sqlite3StrICmp(zCName, pTab->aCol[iCol].zName)==0 ){ pCol = &pTab->aCol[iCol]; pCol->colFlags |= COLFLAG_PRIMKEY; break; } } } } } if( nTerm==1 && pCol && sqlite3StrICmp(sqlite3ColumnType(pCol,""), "INTEGER")==0 && sortOrder!=SQLITE_SO_DESC ){ pTab->iPKey = iCol; pTab->keyConf = (u8)onError; assert( autoInc==0 || autoInc==1 ); pTab->tabFlags |= autoInc*TF_Autoincrement; if( pList ) pParse->iPkSortOrder = pList->a[0].sortOrder; }else if( autoInc ){ #ifndef SQLITE_OMIT_AUTOINCREMENT sqlite3ErrorMsg(pParse, "AUTOINCREMENT is only allowed on an " "INTEGER PRIMARY KEY"); #endif }else{ sqlite3CreateIndex(pParse, 0, 0, 0, pList, onError, 0, 0, sortOrder, 0, SQLITE_IDXTYPE_PRIMARYKEY); pList = 0; } primary_key_exit: sqlite3ExprListDelete(pParse->db, pList); return; } /* ** Add a new CHECK constraint to the table currently under construction. */ SQLITE_PRIVATE void sqlite3AddCheckConstraint( Parse *pParse, /* Parsing context */ Expr *pCheckExpr /* The check expression */ ){ #ifndef SQLITE_OMIT_CHECK Table *pTab = pParse->pNewTable; sqlite3 *db = pParse->db; if( pTab && !IN_DECLARE_VTAB && !sqlite3BtreeIsReadonly(db->aDb[db->init.iDb].pBt) ){ pTab->pCheck = sqlite3ExprListAppend(pParse, pTab->pCheck, pCheckExpr); if( pParse->constraintName.n ){ sqlite3ExprListSetName(pParse, pTab->pCheck, &pParse->constraintName, 1); } }else #endif { sqlite3ExprDelete(pParse->db, pCheckExpr); } } /* ** Set the collation function of the most recently parsed table column ** to the CollSeq given. */ SQLITE_PRIVATE void sqlite3AddCollateType(Parse *pParse, Token *pToken){ Table *p; int i; char *zColl; /* Dequoted name of collation sequence */ sqlite3 *db; if( (p = pParse->pNewTable)==0 ) return; i = p->nCol-1; db = pParse->db; zColl = sqlite3NameFromToken(db, pToken); if( !zColl ) return; if( sqlite3LocateCollSeq(pParse, zColl) ){ Index *pIdx; sqlite3DbFree(db, p->aCol[i].zColl); p->aCol[i].zColl = zColl; /* If the column is declared as " PRIMARY KEY COLLATE ", ** then an index may have been created on this column before the ** collation type was added. Correct this if it is the case. */ for(pIdx=p->pIndex; pIdx; pIdx=pIdx->pNext){ assert( pIdx->nKeyCol==1 ); if( pIdx->aiColumn[0]==i ){ pIdx->azColl[0] = p->aCol[i].zColl; } } }else{ sqlite3DbFree(db, zColl); } } /* ** This function returns the collation sequence for database native text ** encoding identified by the string zName, length nName. ** ** If the requested collation sequence is not available, or not available ** in the database native encoding, the collation factory is invoked to ** request it. If the collation factory does not supply such a sequence, ** and the sequence is available in another text encoding, then that is ** returned instead. ** ** If no versions of the requested collations sequence are available, or ** another error occurs, NULL is returned and an error message written into ** pParse. ** ** This routine is a wrapper around sqlite3FindCollSeq(). This routine ** invokes the collation factory if the named collation cannot be found ** and generates an error message. ** ** See also: sqlite3FindCollSeq(), sqlite3GetCollSeq() */ SQLITE_PRIVATE CollSeq *sqlite3LocateCollSeq(Parse *pParse, const char *zName){ sqlite3 *db = pParse->db; u8 enc = ENC(db); u8 initbusy = db->init.busy; CollSeq *pColl; pColl = sqlite3FindCollSeq(db, enc, zName, initbusy); if( !initbusy && (!pColl || !pColl->xCmp) ){ pColl = sqlite3GetCollSeq(pParse, enc, pColl, zName); } return pColl; } /* ** Generate code that will increment the schema cookie. ** ** The schema cookie is used to determine when the schema for the ** database changes. After each schema change, the cookie value ** changes. When a process first reads the schema it records the ** cookie. Thereafter, whenever it goes to access the database, ** it checks the cookie to make sure the schema has not changed ** since it was last read. ** ** This plan is not completely bullet-proof. It is possible for ** the schema to change multiple times and for the cookie to be ** set back to prior value. But schema changes are infrequent ** and the probability of hitting the same cookie value is only ** 1 chance in 2^32. So we're safe enough. ** ** IMPLEMENTATION-OF: R-34230-56049 SQLite automatically increments ** the schema-version whenever the schema changes. */ SQLITE_PRIVATE void sqlite3ChangeCookie(Parse *pParse, int iDb){ sqlite3 *db = pParse->db; Vdbe *v = pParse->pVdbe; assert( sqlite3SchemaMutexHeld(db, iDb, 0) ); sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_SCHEMA_VERSION, db->aDb[iDb].pSchema->schema_cookie+1); } /* ** Measure the number of characters needed to output the given ** identifier. The number returned includes any quotes used ** but does not include the null terminator. ** ** The estimate is conservative. It might be larger that what is ** really needed. */ static int identLength(const char *z){ int n; for(n=0; *z; n++, z++){ if( *z=='"' ){ n++; } } return n + 2; } /* ** The first parameter is a pointer to an output buffer. The second ** parameter is a pointer to an integer that contains the offset at ** which to write into the output buffer. This function copies the ** nul-terminated string pointed to by the third parameter, zSignedIdent, ** to the specified offset in the buffer and updates *pIdx to refer ** to the first byte after the last byte written before returning. ** ** If the string zSignedIdent consists entirely of alpha-numeric ** characters, does not begin with a digit and is not an SQL keyword, ** then it is copied to the output buffer exactly as it is. Otherwise, ** it is quoted using double-quotes. */ static void identPut(char *z, int *pIdx, char *zSignedIdent){ unsigned char *zIdent = (unsigned char*)zSignedIdent; int i, j, needQuote; i = *pIdx; for(j=0; zIdent[j]; j++){ if( !sqlite3Isalnum(zIdent[j]) && zIdent[j]!='_' ) break; } needQuote = sqlite3Isdigit(zIdent[0]) || sqlite3KeywordCode(zIdent, j)!=TK_ID || zIdent[j]!=0 || j==0; if( needQuote ) z[i++] = '"'; for(j=0; zIdent[j]; j++){ z[i++] = zIdent[j]; if( zIdent[j]=='"' ) z[i++] = '"'; } if( needQuote ) z[i++] = '"'; z[i] = 0; *pIdx = i; } /* ** Generate a CREATE TABLE statement appropriate for the given ** table. Memory to hold the text of the statement is obtained ** from sqliteMalloc() and must be freed by the calling function. */ static char *createTableStmt(sqlite3 *db, Table *p){ int i, k, n; char *zStmt; char *zSep, *zSep2, *zEnd; Column *pCol; n = 0; for(pCol = p->aCol, i=0; inCol; i++, pCol++){ n += identLength(pCol->zName) + 5; } n += identLength(p->zName); if( n<50 ){ zSep = ""; zSep2 = ","; zEnd = ")"; }else{ zSep = "\n "; zSep2 = ",\n "; zEnd = "\n)"; } n += 35 + 6*p->nCol; zStmt = sqlite3DbMallocRaw(0, n); if( zStmt==0 ){ sqlite3OomFault(db); return 0; } sqlite3_snprintf(n, zStmt, "CREATE TABLE "); k = sqlite3Strlen30(zStmt); identPut(zStmt, &k, p->zName); zStmt[k++] = '('; for(pCol=p->aCol, i=0; inCol; i++, pCol++){ static const char * const azType[] = { /* SQLITE_AFF_BLOB */ "", /* SQLITE_AFF_TEXT */ " TEXT", /* SQLITE_AFF_NUMERIC */ " NUM", /* SQLITE_AFF_INTEGER */ " INT", /* SQLITE_AFF_REAL */ " REAL" }; int len; const char *zType; sqlite3_snprintf(n-k, &zStmt[k], zSep); k += sqlite3Strlen30(&zStmt[k]); zSep = zSep2; identPut(zStmt, &k, pCol->zName); assert( pCol->affinity-SQLITE_AFF_BLOB >= 0 ); assert( pCol->affinity-SQLITE_AFF_BLOB < ArraySize(azType) ); testcase( pCol->affinity==SQLITE_AFF_BLOB ); testcase( pCol->affinity==SQLITE_AFF_TEXT ); testcase( pCol->affinity==SQLITE_AFF_NUMERIC ); testcase( pCol->affinity==SQLITE_AFF_INTEGER ); testcase( pCol->affinity==SQLITE_AFF_REAL ); zType = azType[pCol->affinity - SQLITE_AFF_BLOB]; len = sqlite3Strlen30(zType); assert( pCol->affinity==SQLITE_AFF_BLOB || pCol->affinity==sqlite3AffinityType(zType, 0) ); memcpy(&zStmt[k], zType, len); k += len; assert( k<=n ); } sqlite3_snprintf(n-k, &zStmt[k], "%s", zEnd); return zStmt; } /* ** Resize an Index object to hold N columns total. Return SQLITE_OK ** on success and SQLITE_NOMEM on an OOM error. */ static int resizeIndexObject(sqlite3 *db, Index *pIdx, int N){ char *zExtra; int nByte; if( pIdx->nColumn>=N ) return SQLITE_OK; assert( pIdx->isResized==0 ); nByte = (sizeof(char*) + sizeof(i16) + 1)*N; zExtra = sqlite3DbMallocZero(db, nByte); if( zExtra==0 ) return SQLITE_NOMEM_BKPT; memcpy(zExtra, pIdx->azColl, sizeof(char*)*pIdx->nColumn); pIdx->azColl = (const char**)zExtra; zExtra += sizeof(char*)*N; memcpy(zExtra, pIdx->aiColumn, sizeof(i16)*pIdx->nColumn); pIdx->aiColumn = (i16*)zExtra; zExtra += sizeof(i16)*N; memcpy(zExtra, pIdx->aSortOrder, pIdx->nColumn); pIdx->aSortOrder = (u8*)zExtra; pIdx->nColumn = N; pIdx->isResized = 1; return SQLITE_OK; } /* ** Estimate the total row width for a table. */ static void estimateTableWidth(Table *pTab){ unsigned wTable = 0; const Column *pTabCol; int i; for(i=pTab->nCol, pTabCol=pTab->aCol; i>0; i--, pTabCol++){ wTable += pTabCol->szEst; } if( pTab->iPKey<0 ) wTable++; pTab->szTabRow = sqlite3LogEst(wTable*4); } /* ** Estimate the average size of a row for an index. */ static void estimateIndexWidth(Index *pIdx){ unsigned wIndex = 0; int i; const Column *aCol = pIdx->pTable->aCol; for(i=0; inColumn; i++){ i16 x = pIdx->aiColumn[i]; assert( xpTable->nCol ); wIndex += x<0 ? 1 : aCol[pIdx->aiColumn[i]].szEst; } pIdx->szIdxRow = sqlite3LogEst(wIndex*4); } /* Return true if value x is found any of the first nCol entries of aiCol[] */ static int hasColumn(const i16 *aiCol, int nCol, int x){ while( nCol-- > 0 ) if( x==*(aiCol++) ) return 1; return 0; } /* ** This routine runs at the end of parsing a CREATE TABLE statement that ** has a WITHOUT ROWID clause. The job of this routine is to convert both ** internal schema data structures and the generated VDBE code so that they ** are appropriate for a WITHOUT ROWID table instead of a rowid table. ** Changes include: ** ** (1) Set all columns of the PRIMARY KEY schema object to be NOT NULL. ** (2) Convert the OP_CreateTable into an OP_CreateIndex. There is ** no rowid btree for a WITHOUT ROWID. Instead, the canonical ** data storage is a covering index btree. ** (3) Bypass the creation of the sqlite_master table entry ** for the PRIMARY KEY as the primary key index is now ** identified by the sqlite_master table entry of the table itself. ** (4) Set the Index.tnum of the PRIMARY KEY Index object in the ** schema to the rootpage from the main table. ** (5) Add all table columns to the PRIMARY KEY Index object ** so that the PRIMARY KEY is a covering index. The surplus ** columns are part of KeyInfo.nXField and are not used for ** sorting or lookup or uniqueness checks. ** (6) Replace the rowid tail on all automatically generated UNIQUE ** indices with the PRIMARY KEY columns. ** ** For virtual tables, only (1) is performed. */ static void convertToWithoutRowidTable(Parse *pParse, Table *pTab){ Index *pIdx; Index *pPk; int nPk; int i, j; sqlite3 *db = pParse->db; Vdbe *v = pParse->pVdbe; /* Mark every PRIMARY KEY column as NOT NULL (except for imposter tables) */ if( !db->init.imposterTable ){ for(i=0; inCol; i++){ if( (pTab->aCol[i].colFlags & COLFLAG_PRIMKEY)!=0 ){ pTab->aCol[i].notNull = OE_Abort; } } } /* The remaining transformations only apply to b-tree tables, not to ** virtual tables */ if( IN_DECLARE_VTAB ) return; /* Convert the OP_CreateTable opcode that would normally create the ** root-page for the table into an OP_CreateIndex opcode. The index ** created will become the PRIMARY KEY index. */ if( pParse->addrCrTab ){ assert( v ); sqlite3VdbeChangeOpcode(v, pParse->addrCrTab, OP_CreateIndex); } /* Locate the PRIMARY KEY index. Or, if this table was originally ** an INTEGER PRIMARY KEY table, create a new PRIMARY KEY index. */ if( pTab->iPKey>=0 ){ ExprList *pList; Token ipkToken; sqlite3TokenInit(&ipkToken, pTab->aCol[pTab->iPKey].zName); pList = sqlite3ExprListAppend(pParse, 0, sqlite3ExprAlloc(db, TK_ID, &ipkToken, 0)); if( pList==0 ) return; pList->a[0].sortOrder = pParse->iPkSortOrder; assert( pParse->pNewTable==pTab ); sqlite3CreateIndex(pParse, 0, 0, 0, pList, pTab->keyConf, 0, 0, 0, 0, SQLITE_IDXTYPE_PRIMARYKEY); if( db->mallocFailed ) return; pPk = sqlite3PrimaryKeyIndex(pTab); pTab->iPKey = -1; }else{ pPk = sqlite3PrimaryKeyIndex(pTab); /* Bypass the creation of the PRIMARY KEY btree and the sqlite_master ** table entry. This is only required if currently generating VDBE ** code for a CREATE TABLE (not when parsing one as part of reading ** a database schema). */ if( v ){ assert( db->init.busy==0 ); sqlite3VdbeChangeOpcode(v, pPk->tnum, OP_Goto); } /* ** Remove all redundant columns from the PRIMARY KEY. For example, change ** "PRIMARY KEY(a,b,a,b,c,b,c,d)" into just "PRIMARY KEY(a,b,c,d)". Later ** code assumes the PRIMARY KEY contains no repeated columns. */ for(i=j=1; inKeyCol; i++){ if( hasColumn(pPk->aiColumn, j, pPk->aiColumn[i]) ){ pPk->nColumn--; }else{ pPk->aiColumn[j++] = pPk->aiColumn[i]; } } pPk->nKeyCol = j; } assert( pPk!=0 ); pPk->isCovering = 1; if( !db->init.imposterTable ) pPk->uniqNotNull = 1; nPk = pPk->nKeyCol; /* The root page of the PRIMARY KEY is the table root page */ pPk->tnum = pTab->tnum; /* Update the in-memory representation of all UNIQUE indices by converting ** the final rowid column into one or more columns of the PRIMARY KEY. */ for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){ int n; if( IsPrimaryKeyIndex(pIdx) ) continue; for(i=n=0; iaiColumn, pIdx->nKeyCol, pPk->aiColumn[i]) ) n++; } if( n==0 ){ /* This index is a superset of the primary key */ pIdx->nColumn = pIdx->nKeyCol; continue; } if( resizeIndexObject(db, pIdx, pIdx->nKeyCol+n) ) return; for(i=0, j=pIdx->nKeyCol; iaiColumn, pIdx->nKeyCol, pPk->aiColumn[i]) ){ pIdx->aiColumn[j] = pPk->aiColumn[i]; pIdx->azColl[j] = pPk->azColl[i]; j++; } } assert( pIdx->nColumn>=pIdx->nKeyCol+n ); assert( pIdx->nColumn>=j ); } /* Add all table columns to the PRIMARY KEY index */ if( nPknCol ){ if( resizeIndexObject(db, pPk, pTab->nCol) ) return; for(i=0, j=nPk; inCol; i++){ if( !hasColumn(pPk->aiColumn, j, i) ){ assert( jnColumn ); pPk->aiColumn[j] = i; pPk->azColl[j] = sqlite3StrBINARY; j++; } } assert( pPk->nColumn==j ); assert( pTab->nCol==j ); }else{ pPk->nColumn = pTab->nCol; } } /* ** This routine is called to report the final ")" that terminates ** a CREATE TABLE statement. ** ** The table structure that other action routines have been building ** is added to the internal hash tables, assuming no errors have ** occurred. ** ** An entry for the table is made in the master table on disk, unless ** this is a temporary table or db->init.busy==1. When db->init.busy==1 ** it means we are reading the sqlite_master table because we just ** connected to the database or because the sqlite_master table has ** recently changed, so the entry for this table already exists in ** the sqlite_master table. We do not want to create it again. ** ** If the pSelect argument is not NULL, it means that this routine ** was called to create a table generated from a ** "CREATE TABLE ... AS SELECT ..." statement. The column names of ** the new table will match the result set of the SELECT. */ SQLITE_PRIVATE void sqlite3EndTable( Parse *pParse, /* Parse context */ Token *pCons, /* The ',' token after the last column defn. */ Token *pEnd, /* The ')' before options in the CREATE TABLE */ u8 tabOpts, /* Extra table options. Usually 0. */ Select *pSelect /* Select from a "CREATE ... AS SELECT" */ ){ Table *p; /* The new table */ sqlite3 *db = pParse->db; /* The database connection */ int iDb; /* Database in which the table lives */ Index *pIdx; /* An implied index of the table */ if( pEnd==0 && pSelect==0 ){ return; } assert( !db->mallocFailed ); p = pParse->pNewTable; if( p==0 ) return; assert( !db->init.busy || !pSelect ); /* If the db->init.busy is 1 it means we are reading the SQL off the ** "sqlite_master" or "sqlite_temp_master" table on the disk. ** So do not write to the disk again. Extract the root page number ** for the table from the db->init.newTnum field. (The page number ** should have been put there by the sqliteOpenCb routine.) ** ** If the root page number is 1, that means this is the sqlite_master ** table itself. So mark it read-only. */ if( db->init.busy ){ p->tnum = db->init.newTnum; if( p->tnum==1 ) p->tabFlags |= TF_Readonly; } /* Special processing for WITHOUT ROWID Tables */ if( tabOpts & TF_WithoutRowid ){ if( (p->tabFlags & TF_Autoincrement) ){ sqlite3ErrorMsg(pParse, "AUTOINCREMENT not allowed on WITHOUT ROWID tables"); return; } if( (p->tabFlags & TF_HasPrimaryKey)==0 ){ sqlite3ErrorMsg(pParse, "PRIMARY KEY missing on table %s", p->zName); }else{ p->tabFlags |= TF_WithoutRowid | TF_NoVisibleRowid; convertToWithoutRowidTable(pParse, p); } } iDb = sqlite3SchemaToIndex(db, p->pSchema); #ifndef SQLITE_OMIT_CHECK /* Resolve names in all CHECK constraint expressions. */ if( p->pCheck ){ sqlite3ResolveSelfReference(pParse, p, NC_IsCheck, 0, p->pCheck); } #endif /* !defined(SQLITE_OMIT_CHECK) */ /* Estimate the average row size for the table and for all implied indices */ estimateTableWidth(p); for(pIdx=p->pIndex; pIdx; pIdx=pIdx->pNext){ estimateIndexWidth(pIdx); } /* If not initializing, then create a record for the new table ** in the SQLITE_MASTER table of the database. ** ** If this is a TEMPORARY table, write the entry into the auxiliary ** file instead of into the main database file. */ if( !db->init.busy ){ int n; Vdbe *v; char *zType; /* "view" or "table" */ char *zType2; /* "VIEW" or "TABLE" */ char *zStmt; /* Text of the CREATE TABLE or CREATE VIEW statement */ v = sqlite3GetVdbe(pParse); if( NEVER(v==0) ) return; sqlite3VdbeAddOp1(v, OP_Close, 0); /* ** Initialize zType for the new view or table. */ if( p->pSelect==0 ){ /* A regular table */ zType = "table"; zType2 = "TABLE"; #ifndef SQLITE_OMIT_VIEW }else{ /* A view */ zType = "view"; zType2 = "VIEW"; #endif } /* If this is a CREATE TABLE xx AS SELECT ..., execute the SELECT ** statement to populate the new table. The root-page number for the ** new table is in register pParse->regRoot. ** ** Once the SELECT has been coded by sqlite3Select(), it is in a ** suitable state to query for the column names and types to be used ** by the new table. ** ** A shared-cache write-lock is not required to write to the new table, ** as a schema-lock must have already been obtained to create it. Since ** a schema-lock excludes all other database users, the write-lock would ** be redundant. */ if( pSelect ){ SelectDest dest; /* Where the SELECT should store results */ int regYield; /* Register holding co-routine entry-point */ int addrTop; /* Top of the co-routine */ int regRec; /* A record to be insert into the new table */ int regRowid; /* Rowid of the next row to insert */ int addrInsLoop; /* Top of the loop for inserting rows */ Table *pSelTab; /* A table that describes the SELECT results */ regYield = ++pParse->nMem; regRec = ++pParse->nMem; regRowid = ++pParse->nMem; assert(pParse->nTab==1); sqlite3MayAbort(pParse); sqlite3VdbeAddOp3(v, OP_OpenWrite, 1, pParse->regRoot, iDb); sqlite3VdbeChangeP5(v, OPFLAG_P2ISREG); pParse->nTab = 2; addrTop = sqlite3VdbeCurrentAddr(v) + 1; sqlite3VdbeAddOp3(v, OP_InitCoroutine, regYield, 0, addrTop); sqlite3SelectDestInit(&dest, SRT_Coroutine, regYield); sqlite3Select(pParse, pSelect, &dest); sqlite3VdbeEndCoroutine(v, regYield); sqlite3VdbeJumpHere(v, addrTop - 1); if( pParse->nErr ) return; pSelTab = sqlite3ResultSetOfSelect(pParse, pSelect); if( pSelTab==0 ) return; assert( p->aCol==0 ); p->nCol = pSelTab->nCol; p->aCol = pSelTab->aCol; pSelTab->nCol = 0; pSelTab->aCol = 0; sqlite3DeleteTable(db, pSelTab); addrInsLoop = sqlite3VdbeAddOp1(v, OP_Yield, dest.iSDParm); VdbeCoverage(v); sqlite3VdbeAddOp3(v, OP_MakeRecord, dest.iSdst, dest.nSdst, regRec); sqlite3TableAffinity(v, p, 0); sqlite3VdbeAddOp2(v, OP_NewRowid, 1, regRowid); sqlite3VdbeAddOp3(v, OP_Insert, 1, regRec, regRowid); sqlite3VdbeGoto(v, addrInsLoop); sqlite3VdbeJumpHere(v, addrInsLoop); sqlite3VdbeAddOp1(v, OP_Close, 1); } /* Compute the complete text of the CREATE statement */ if( pSelect ){ zStmt = createTableStmt(db, p); }else{ Token *pEnd2 = tabOpts ? &pParse->sLastToken : pEnd; n = (int)(pEnd2->z - pParse->sNameToken.z); if( pEnd2->z[0]!=';' ) n += pEnd2->n; zStmt = sqlite3MPrintf(db, "CREATE %s %.*s", zType2, n, pParse->sNameToken.z ); } /* A slot for the record has already been allocated in the ** SQLITE_MASTER table. We just need to update that slot with all ** the information we've collected. */ sqlite3NestedParse(pParse, "UPDATE %Q.%s " "SET type='%s', name=%Q, tbl_name=%Q, rootpage=#%d, sql=%Q " "WHERE rowid=#%d", db->aDb[iDb].zDbSName, SCHEMA_TABLE(iDb), zType, p->zName, p->zName, pParse->regRoot, zStmt, pParse->regRowid ); sqlite3DbFree(db, zStmt); sqlite3ChangeCookie(pParse, iDb); #ifndef SQLITE_OMIT_AUTOINCREMENT /* Check to see if we need to create an sqlite_sequence table for ** keeping track of autoincrement keys. */ if( (p->tabFlags & TF_Autoincrement)!=0 ){ Db *pDb = &db->aDb[iDb]; assert( sqlite3SchemaMutexHeld(db, iDb, 0) ); if( pDb->pSchema->pSeqTab==0 ){ sqlite3NestedParse(pParse, "CREATE TABLE %Q.sqlite_sequence(name,seq)", pDb->zDbSName ); } } #endif /* Reparse everything to update our internal data structures */ sqlite3VdbeAddParseSchemaOp(v, iDb, sqlite3MPrintf(db, "tbl_name='%q' AND type!='trigger'", p->zName)); } /* Add the table to the in-memory representation of the database. */ if( db->init.busy ){ Table *pOld; Schema *pSchema = p->pSchema; assert( sqlite3SchemaMutexHeld(db, iDb, 0) ); pOld = sqlite3HashInsert(&pSchema->tblHash, p->zName, p); if( pOld ){ assert( p==pOld ); /* Malloc must have failed inside HashInsert() */ sqlite3OomFault(db); return; } pParse->pNewTable = 0; db->flags |= SQLITE_InternChanges; #ifndef SQLITE_OMIT_ALTERTABLE if( !p->pSelect ){ const char *zName = (const char *)pParse->sNameToken.z; int nName; assert( !pSelect && pCons && pEnd ); if( pCons->z==0 ){ pCons = pEnd; } nName = (int)((const char *)pCons->z - zName); p->addColOffset = 13 + sqlite3Utf8CharLen(zName, nName); } #endif } } #ifndef SQLITE_OMIT_VIEW /* ** The parser calls this routine in order to create a new VIEW */ SQLITE_PRIVATE void sqlite3CreateView( Parse *pParse, /* The parsing context */ Token *pBegin, /* The CREATE token that begins the statement */ Token *pName1, /* The token that holds the name of the view */ Token *pName2, /* The token that holds the name of the view */ ExprList *pCNames, /* Optional list of view column names */ Select *pSelect, /* A SELECT statement that will become the new view */ int isTemp, /* TRUE for a TEMPORARY view */ int noErr /* Suppress error messages if VIEW already exists */ ){ Table *p; int n; const char *z; Token sEnd; DbFixer sFix; Token *pName = 0; int iDb; sqlite3 *db = pParse->db; if( pParse->nVar>0 ){ sqlite3ErrorMsg(pParse, "parameters are not allowed in views"); goto create_view_fail; } sqlite3StartTable(pParse, pName1, pName2, isTemp, 1, 0, noErr); p = pParse->pNewTable; if( p==0 || pParse->nErr ) goto create_view_fail; sqlite3TwoPartName(pParse, pName1, pName2, &pName); iDb = sqlite3SchemaToIndex(db, p->pSchema); sqlite3FixInit(&sFix, pParse, iDb, "view", pName); if( sqlite3FixSelect(&sFix, pSelect) ) goto create_view_fail; /* Make a copy of the entire SELECT statement that defines the view. ** This will force all the Expr.token.z values to be dynamically ** allocated rather than point to the input string - which means that ** they will persist after the current sqlite3_exec() call returns. */ p->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE); p->pCheck = sqlite3ExprListDup(db, pCNames, EXPRDUP_REDUCE); if( db->mallocFailed ) goto create_view_fail; /* Locate the end of the CREATE VIEW statement. Make sEnd point to ** the end. */ sEnd = pParse->sLastToken; assert( sEnd.z[0]!=0 ); if( sEnd.z[0]!=';' ){ sEnd.z += sEnd.n; } sEnd.n = 0; n = (int)(sEnd.z - pBegin->z); assert( n>0 ); z = pBegin->z; while( sqlite3Isspace(z[n-1]) ){ n--; } sEnd.z = &z[n-1]; sEnd.n = 1; /* Use sqlite3EndTable() to add the view to the SQLITE_MASTER table */ sqlite3EndTable(pParse, 0, &sEnd, 0, 0); create_view_fail: sqlite3SelectDelete(db, pSelect); sqlite3ExprListDelete(db, pCNames); return; } #endif /* SQLITE_OMIT_VIEW */ #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE) /* ** The Table structure pTable is really a VIEW. Fill in the names of ** the columns of the view in the pTable structure. Return the number ** of errors. If an error is seen leave an error message in pParse->zErrMsg. */ SQLITE_PRIVATE int sqlite3ViewGetColumnNames(Parse *pParse, Table *pTable){ Table *pSelTab; /* A fake table from which we get the result set */ Select *pSel; /* Copy of the SELECT that implements the view */ int nErr = 0; /* Number of errors encountered */ int n; /* Temporarily holds the number of cursors assigned */ sqlite3 *db = pParse->db; /* Database connection for malloc errors */ #ifndef SQLITE_OMIT_AUTHORIZATION sqlite3_xauth xAuth; /* Saved xAuth pointer */ #endif assert( pTable ); #ifndef SQLITE_OMIT_VIRTUALTABLE if( sqlite3VtabCallConnect(pParse, pTable) ){ return SQLITE_ERROR; } if( IsVirtual(pTable) ) return 0; #endif #ifndef SQLITE_OMIT_VIEW /* A positive nCol means the columns names for this view are ** already known. */ if( pTable->nCol>0 ) return 0; /* A negative nCol is a special marker meaning that we are currently ** trying to compute the column names. If we enter this routine with ** a negative nCol, it means two or more views form a loop, like this: ** ** CREATE VIEW one AS SELECT * FROM two; ** CREATE VIEW two AS SELECT * FROM one; ** ** Actually, the error above is now caught prior to reaching this point. ** But the following test is still important as it does come up ** in the following: ** ** CREATE TABLE main.ex1(a); ** CREATE TEMP VIEW ex1 AS SELECT a FROM ex1; ** SELECT * FROM temp.ex1; */ if( pTable->nCol<0 ){ sqlite3ErrorMsg(pParse, "view %s is circularly defined", pTable->zName); return 1; } assert( pTable->nCol>=0 ); /* If we get this far, it means we need to compute the table names. ** Note that the call to sqlite3ResultSetOfSelect() will expand any ** "*" elements in the results set of the view and will assign cursors ** to the elements of the FROM clause. But we do not want these changes ** to be permanent. So the computation is done on a copy of the SELECT ** statement that defines the view. */ assert( pTable->pSelect ); pSel = sqlite3SelectDup(db, pTable->pSelect, 0); if( pSel ){ n = pParse->nTab; sqlite3SrcListAssignCursors(pParse, pSel->pSrc); pTable->nCol = -1; db->lookaside.bDisable++; #ifndef SQLITE_OMIT_AUTHORIZATION xAuth = db->xAuth; db->xAuth = 0; pSelTab = sqlite3ResultSetOfSelect(pParse, pSel); db->xAuth = xAuth; #else pSelTab = sqlite3ResultSetOfSelect(pParse, pSel); #endif pParse->nTab = n; if( pTable->pCheck ){ /* CREATE VIEW name(arglist) AS ... ** The names of the columns in the table are taken from ** arglist which is stored in pTable->pCheck. The pCheck field ** normally holds CHECK constraints on an ordinary table, but for ** a VIEW it holds the list of column names. */ sqlite3ColumnsFromExprList(pParse, pTable->pCheck, &pTable->nCol, &pTable->aCol); if( db->mallocFailed==0 && pParse->nErr==0 && pTable->nCol==pSel->pEList->nExpr ){ sqlite3SelectAddColumnTypeAndCollation(pParse, pTable, pSel); } }else if( pSelTab ){ /* CREATE VIEW name AS... without an argument list. Construct ** the column names from the SELECT statement that defines the view. */ assert( pTable->aCol==0 ); pTable->nCol = pSelTab->nCol; pTable->aCol = pSelTab->aCol; pSelTab->nCol = 0; pSelTab->aCol = 0; assert( sqlite3SchemaMutexHeld(db, 0, pTable->pSchema) ); }else{ pTable->nCol = 0; nErr++; } sqlite3DeleteTable(db, pSelTab); sqlite3SelectDelete(db, pSel); db->lookaside.bDisable--; } else { nErr++; } pTable->pSchema->schemaFlags |= DB_UnresetViews; #endif /* SQLITE_OMIT_VIEW */ return nErr; } #endif /* !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE) */ #ifndef SQLITE_OMIT_VIEW /* ** Clear the column names from every VIEW in database idx. */ static void sqliteViewResetAll(sqlite3 *db, int idx){ HashElem *i; assert( sqlite3SchemaMutexHeld(db, idx, 0) ); if( !DbHasProperty(db, idx, DB_UnresetViews) ) return; for(i=sqliteHashFirst(&db->aDb[idx].pSchema->tblHash); i;i=sqliteHashNext(i)){ Table *pTab = sqliteHashData(i); if( pTab->pSelect ){ sqlite3DeleteColumnNames(db, pTab); pTab->aCol = 0; pTab->nCol = 0; } } DbClearProperty(db, idx, DB_UnresetViews); } #else # define sqliteViewResetAll(A,B) #endif /* SQLITE_OMIT_VIEW */ /* ** This function is called by the VDBE to adjust the internal schema ** used by SQLite when the btree layer moves a table root page. The ** root-page of a table or index in database iDb has changed from iFrom ** to iTo. ** ** Ticket #1728: The symbol table might still contain information ** on tables and/or indices that are the process of being deleted. ** If you are unlucky, one of those deleted indices or tables might ** have the same rootpage number as the real table or index that is ** being moved. So we cannot stop searching after the first match ** because the first match might be for one of the deleted indices ** or tables and not the table/index that is actually being moved. ** We must continue looping until all tables and indices with ** rootpage==iFrom have been converted to have a rootpage of iTo ** in order to be certain that we got the right one. */ #ifndef SQLITE_OMIT_AUTOVACUUM SQLITE_PRIVATE void sqlite3RootPageMoved(sqlite3 *db, int iDb, int iFrom, int iTo){ HashElem *pElem; Hash *pHash; Db *pDb; assert( sqlite3SchemaMutexHeld(db, iDb, 0) ); pDb = &db->aDb[iDb]; pHash = &pDb->pSchema->tblHash; for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){ Table *pTab = sqliteHashData(pElem); if( pTab->tnum==iFrom ){ pTab->tnum = iTo; } } pHash = &pDb->pSchema->idxHash; for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){ Index *pIdx = sqliteHashData(pElem); if( pIdx->tnum==iFrom ){ pIdx->tnum = iTo; } } } #endif /* ** Write code to erase the table with root-page iTable from database iDb. ** Also write code to modify the sqlite_master table and internal schema ** if a root-page of another table is moved by the btree-layer whilst ** erasing iTable (this can happen with an auto-vacuum database). */ static void destroyRootPage(Parse *pParse, int iTable, int iDb){ Vdbe *v = sqlite3GetVdbe(pParse); int r1 = sqlite3GetTempReg(pParse); assert( iTable>1 ); sqlite3VdbeAddOp3(v, OP_Destroy, iTable, r1, iDb); sqlite3MayAbort(pParse); #ifndef SQLITE_OMIT_AUTOVACUUM /* OP_Destroy stores an in integer r1. If this integer ** is non-zero, then it is the root page number of a table moved to ** location iTable. The following code modifies the sqlite_master table to ** reflect this. ** ** The "#NNN" in the SQL is a special constant that means whatever value ** is in register NNN. See grammar rules associated with the TK_REGISTER ** token for additional information. */ sqlite3NestedParse(pParse, "UPDATE %Q.%s SET rootpage=%d WHERE #%d AND rootpage=#%d", pParse->db->aDb[iDb].zDbSName, SCHEMA_TABLE(iDb), iTable, r1, r1); #endif sqlite3ReleaseTempReg(pParse, r1); } /* ** Write VDBE code to erase table pTab and all associated indices on disk. ** Code to update the sqlite_master tables and internal schema definitions ** in case a root-page belonging to another table is moved by the btree layer ** is also added (this can happen with an auto-vacuum database). */ static void destroyTable(Parse *pParse, Table *pTab){ #ifdef SQLITE_OMIT_AUTOVACUUM Index *pIdx; int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema); destroyRootPage(pParse, pTab->tnum, iDb); for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){ destroyRootPage(pParse, pIdx->tnum, iDb); } #else /* If the database may be auto-vacuum capable (if SQLITE_OMIT_AUTOVACUUM ** is not defined), then it is important to call OP_Destroy on the ** table and index root-pages in order, starting with the numerically ** largest root-page number. This guarantees that none of the root-pages ** to be destroyed is relocated by an earlier OP_Destroy. i.e. if the ** following were coded: ** ** OP_Destroy 4 0 ** ... ** OP_Destroy 5 0 ** ** and root page 5 happened to be the largest root-page number in the ** database, then root page 5 would be moved to page 4 by the ** "OP_Destroy 4 0" opcode. The subsequent "OP_Destroy 5 0" would hit ** a free-list page. */ int iTab = pTab->tnum; int iDestroyed = 0; while( 1 ){ Index *pIdx; int iLargest = 0; if( iDestroyed==0 || iTabpIndex; pIdx; pIdx=pIdx->pNext){ int iIdx = pIdx->tnum; assert( pIdx->pSchema==pTab->pSchema ); if( (iDestroyed==0 || (iIdxiLargest ){ iLargest = iIdx; } } if( iLargest==0 ){ return; }else{ int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema); assert( iDb>=0 && iDbdb->nDb ); destroyRootPage(pParse, iLargest, iDb); iDestroyed = iLargest; } } #endif } /* ** Remove entries from the sqlite_statN tables (for N in (1,2,3)) ** after a DROP INDEX or DROP TABLE command. */ static void sqlite3ClearStatTables( Parse *pParse, /* The parsing context */ int iDb, /* The database number */ const char *zType, /* "idx" or "tbl" */ const char *zName /* Name of index or table */ ){ int i; const char *zDbName = pParse->db->aDb[iDb].zDbSName; for(i=1; i<=4; i++){ char zTab[24]; sqlite3_snprintf(sizeof(zTab),zTab,"sqlite_stat%d",i); if( sqlite3FindTable(pParse->db, zTab, zDbName) ){ sqlite3NestedParse(pParse, "DELETE FROM %Q.%s WHERE %s=%Q", zDbName, zTab, zType, zName ); } } } /* ** Generate code to drop a table. */ SQLITE_PRIVATE void sqlite3CodeDropTable(Parse *pParse, Table *pTab, int iDb, int isView){ Vdbe *v; sqlite3 *db = pParse->db; Trigger *pTrigger; Db *pDb = &db->aDb[iDb]; v = sqlite3GetVdbe(pParse); assert( v!=0 ); sqlite3BeginWriteOperation(pParse, 1, iDb); #ifndef SQLITE_OMIT_VIRTUALTABLE if( IsVirtual(pTab) ){ sqlite3VdbeAddOp0(v, OP_VBegin); } #endif /* Drop all triggers associated with the table being dropped. Code ** is generated to remove entries from sqlite_master and/or ** sqlite_temp_master if required. */ pTrigger = sqlite3TriggerList(pParse, pTab); while( pTrigger ){ assert( pTrigger->pSchema==pTab->pSchema || pTrigger->pSchema==db->aDb[1].pSchema ); sqlite3DropTriggerPtr(pParse, pTrigger); pTrigger = pTrigger->pNext; } #ifndef SQLITE_OMIT_AUTOINCREMENT /* Remove any entries of the sqlite_sequence table associated with ** the table being dropped. This is done before the table is dropped ** at the btree level, in case the sqlite_sequence table needs to ** move as a result of the drop (can happen in auto-vacuum mode). */ if( pTab->tabFlags & TF_Autoincrement ){ sqlite3NestedParse(pParse, "DELETE FROM %Q.sqlite_sequence WHERE name=%Q", pDb->zDbSName, pTab->zName ); } #endif /* Drop all SQLITE_MASTER table and index entries that refer to the ** table. The program name loops through the master table and deletes ** every row that refers to a table of the same name as the one being ** dropped. Triggers are handled separately because a trigger can be ** created in the temp database that refers to a table in another ** database. */ sqlite3NestedParse(pParse, "DELETE FROM %Q.%s WHERE tbl_name=%Q and type!='trigger'", pDb->zDbSName, SCHEMA_TABLE(iDb), pTab->zName); if( !isView && !IsVirtual(pTab) ){ destroyTable(pParse, pTab); } /* Remove the table entry from SQLite's internal schema and modify ** the schema cookie. */ if( IsVirtual(pTab) ){ sqlite3VdbeAddOp4(v, OP_VDestroy, iDb, 0, 0, pTab->zName, 0); } sqlite3VdbeAddOp4(v, OP_DropTable, iDb, 0, 0, pTab->zName, 0); sqlite3ChangeCookie(pParse, iDb); sqliteViewResetAll(db, iDb); } /* ** This routine is called to do the work of a DROP TABLE statement. ** pName is the name of the table to be dropped. */ SQLITE_PRIVATE void sqlite3DropTable(Parse *pParse, SrcList *pName, int isView, int noErr){ Table *pTab; Vdbe *v; sqlite3 *db = pParse->db; int iDb; if( db->mallocFailed ){ goto exit_drop_table; } assert( pParse->nErr==0 ); assert( pName->nSrc==1 ); if( sqlite3ReadSchema(pParse) ) goto exit_drop_table; if( noErr ) db->suppressErr++; assert( isView==0 || isView==LOCATE_VIEW ); pTab = sqlite3LocateTableItem(pParse, isView, &pName->a[0]); if( noErr ) db->suppressErr--; if( pTab==0 ){ if( noErr ) sqlite3CodeVerifyNamedSchema(pParse, pName->a[0].zDatabase); goto exit_drop_table; } iDb = sqlite3SchemaToIndex(db, pTab->pSchema); assert( iDb>=0 && iDbnDb ); /* If pTab is a virtual table, call ViewGetColumnNames() to ensure ** it is initialized. */ if( IsVirtual(pTab) && sqlite3ViewGetColumnNames(pParse, pTab) ){ goto exit_drop_table; } #ifndef SQLITE_OMIT_AUTHORIZATION { int code; const char *zTab = SCHEMA_TABLE(iDb); const char *zDb = db->aDb[iDb].zDbSName; const char *zArg2 = 0; if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb)){ goto exit_drop_table; } if( isView ){ if( !OMIT_TEMPDB && iDb==1 ){ code = SQLITE_DROP_TEMP_VIEW; }else{ code = SQLITE_DROP_VIEW; } #ifndef SQLITE_OMIT_VIRTUALTABLE }else if( IsVirtual(pTab) ){ code = SQLITE_DROP_VTABLE; zArg2 = sqlite3GetVTable(db, pTab)->pMod->zName; #endif }else{ if( !OMIT_TEMPDB && iDb==1 ){ code = SQLITE_DROP_TEMP_TABLE; }else{ code = SQLITE_DROP_TABLE; } } if( sqlite3AuthCheck(pParse, code, pTab->zName, zArg2, zDb) ){ goto exit_drop_table; } if( sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0, zDb) ){ goto exit_drop_table; } } #endif if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0 && sqlite3StrNICmp(pTab->zName, "sqlite_stat", 11)!=0 ){ sqlite3ErrorMsg(pParse, "table %s may not be dropped", pTab->zName); goto exit_drop_table; } #ifndef SQLITE_OMIT_VIEW /* Ensure DROP TABLE is not used on a view, and DROP VIEW is not used ** on a table. */ if( isView && pTab->pSelect==0 ){ sqlite3ErrorMsg(pParse, "use DROP TABLE to delete table %s", pTab->zName); goto exit_drop_table; } if( !isView && pTab->pSelect ){ sqlite3ErrorMsg(pParse, "use DROP VIEW to delete view %s", pTab->zName); goto exit_drop_table; } #endif /* Generate code to remove the table from the master table ** on disk. */ v = sqlite3GetVdbe(pParse); if( v ){ sqlite3BeginWriteOperation(pParse, 1, iDb); sqlite3ClearStatTables(pParse, iDb, "tbl", pTab->zName); sqlite3FkDropTable(pParse, pName, pTab); sqlite3CodeDropTable(pParse, pTab, iDb, isView); } exit_drop_table: sqlite3SrcListDelete(db, pName); } /* ** This routine is called to create a new foreign key on the table ** currently under construction. pFromCol determines which columns ** in the current table point to the foreign key. If pFromCol==0 then ** connect the key to the last column inserted. pTo is the name of ** the table referred to (a.k.a the "parent" table). pToCol is a list ** of tables in the parent pTo table. flags contains all ** information about the conflict resolution algorithms specified ** in the ON DELETE, ON UPDATE and ON INSERT clauses. ** ** An FKey structure is created and added to the table currently ** under construction in the pParse->pNewTable field. ** ** The foreign key is set for IMMEDIATE processing. A subsequent call ** to sqlite3DeferForeignKey() might change this to DEFERRED. */ SQLITE_PRIVATE void sqlite3CreateForeignKey( Parse *pParse, /* Parsing context */ ExprList *pFromCol, /* Columns in this table that point to other table */ Token *pTo, /* Name of the other table */ ExprList *pToCol, /* Columns in the other table */ int flags /* Conflict resolution algorithms. */ ){ sqlite3 *db = pParse->db; #ifndef SQLITE_OMIT_FOREIGN_KEY FKey *pFKey = 0; FKey *pNextTo; Table *p = pParse->pNewTable; int nByte; int i; int nCol; char *z; assert( pTo!=0 ); if( p==0 || IN_DECLARE_VTAB ) goto fk_end; if( pFromCol==0 ){ int iCol = p->nCol-1; if( NEVER(iCol<0) ) goto fk_end; if( pToCol && pToCol->nExpr!=1 ){ sqlite3ErrorMsg(pParse, "foreign key on %s" " should reference only one column of table %T", p->aCol[iCol].zName, pTo); goto fk_end; } nCol = 1; }else if( pToCol && pToCol->nExpr!=pFromCol->nExpr ){ sqlite3ErrorMsg(pParse, "number of columns in foreign key does not match the number of " "columns in the referenced table"); goto fk_end; }else{ nCol = pFromCol->nExpr; } nByte = sizeof(*pFKey) + (nCol-1)*sizeof(pFKey->aCol[0]) + pTo->n + 1; if( pToCol ){ for(i=0; inExpr; i++){ nByte += sqlite3Strlen30(pToCol->a[i].zName) + 1; } } pFKey = sqlite3DbMallocZero(db, nByte ); if( pFKey==0 ){ goto fk_end; } pFKey->pFrom = p; pFKey->pNextFrom = p->pFKey; z = (char*)&pFKey->aCol[nCol]; pFKey->zTo = z; memcpy(z, pTo->z, pTo->n); z[pTo->n] = 0; sqlite3Dequote(z); z += pTo->n+1; pFKey->nCol = nCol; if( pFromCol==0 ){ pFKey->aCol[0].iFrom = p->nCol-1; }else{ for(i=0; inCol; j++){ if( sqlite3StrICmp(p->aCol[j].zName, pFromCol->a[i].zName)==0 ){ pFKey->aCol[i].iFrom = j; break; } } if( j>=p->nCol ){ sqlite3ErrorMsg(pParse, "unknown column \"%s\" in foreign key definition", pFromCol->a[i].zName); goto fk_end; } } } if( pToCol ){ for(i=0; ia[i].zName); pFKey->aCol[i].zCol = z; memcpy(z, pToCol->a[i].zName, n); z[n] = 0; z += n+1; } } pFKey->isDeferred = 0; pFKey->aAction[0] = (u8)(flags & 0xff); /* ON DELETE action */ pFKey->aAction[1] = (u8)((flags >> 8 ) & 0xff); /* ON UPDATE action */ assert( sqlite3SchemaMutexHeld(db, 0, p->pSchema) ); pNextTo = (FKey *)sqlite3HashInsert(&p->pSchema->fkeyHash, pFKey->zTo, (void *)pFKey ); if( pNextTo==pFKey ){ sqlite3OomFault(db); goto fk_end; } if( pNextTo ){ assert( pNextTo->pPrevTo==0 ); pFKey->pNextTo = pNextTo; pNextTo->pPrevTo = pFKey; } /* Link the foreign key to the table as the last step. */ p->pFKey = pFKey; pFKey = 0; fk_end: sqlite3DbFree(db, pFKey); #endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */ sqlite3ExprListDelete(db, pFromCol); sqlite3ExprListDelete(db, pToCol); } /* ** This routine is called when an INITIALLY IMMEDIATE or INITIALLY DEFERRED ** clause is seen as part of a foreign key definition. The isDeferred ** parameter is 1 for INITIALLY DEFERRED and 0 for INITIALLY IMMEDIATE. ** The behavior of the most recently created foreign key is adjusted ** accordingly. */ SQLITE_PRIVATE void sqlite3DeferForeignKey(Parse *pParse, int isDeferred){ #ifndef SQLITE_OMIT_FOREIGN_KEY Table *pTab; FKey *pFKey; if( (pTab = pParse->pNewTable)==0 || (pFKey = pTab->pFKey)==0 ) return; assert( isDeferred==0 || isDeferred==1 ); /* EV: R-30323-21917 */ pFKey->isDeferred = (u8)isDeferred; #endif } /* ** Generate code that will erase and refill index *pIdx. This is ** used to initialize a newly created index or to recompute the ** content of an index in response to a REINDEX command. ** ** if memRootPage is not negative, it means that the index is newly ** created. The register specified by memRootPage contains the ** root page number of the index. If memRootPage is negative, then ** the index already exists and must be cleared before being refilled and ** the root page number of the index is taken from pIndex->tnum. */ static void sqlite3RefillIndex(Parse *pParse, Index *pIndex, int memRootPage){ Table *pTab = pIndex->pTable; /* The table that is indexed */ int iTab = pParse->nTab++; /* Btree cursor used for pTab */ int iIdx = pParse->nTab++; /* Btree cursor used for pIndex */ int iSorter; /* Cursor opened by OpenSorter (if in use) */ int addr1; /* Address of top of loop */ int addr2; /* Address to jump to for next iteration */ int tnum; /* Root page of index */ int iPartIdxLabel; /* Jump to this label to skip a row */ Vdbe *v; /* Generate code into this virtual machine */ KeyInfo *pKey; /* KeyInfo for index */ int regRecord; /* Register holding assembled index record */ sqlite3 *db = pParse->db; /* The database connection */ int iDb = sqlite3SchemaToIndex(db, pIndex->pSchema); #ifndef SQLITE_OMIT_AUTHORIZATION if( sqlite3AuthCheck(pParse, SQLITE_REINDEX, pIndex->zName, 0, db->aDb[iDb].zDbSName ) ){ return; } #endif /* Require a write-lock on the table to perform this operation */ sqlite3TableLock(pParse, iDb, pTab->tnum, 1, pTab->zName); v = sqlite3GetVdbe(pParse); if( v==0 ) return; if( memRootPage>=0 ){ tnum = memRootPage; }else{ tnum = pIndex->tnum; } pKey = sqlite3KeyInfoOfIndex(pParse, pIndex); assert( pKey!=0 || db->mallocFailed || pParse->nErr ); /* Open the sorter cursor if we are to use one. */ iSorter = pParse->nTab++; sqlite3VdbeAddOp4(v, OP_SorterOpen, iSorter, 0, pIndex->nKeyCol, (char*) sqlite3KeyInfoRef(pKey), P4_KEYINFO); /* Open the table. Loop through all rows of the table, inserting index ** records into the sorter. */ sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead); addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iTab, 0); VdbeCoverage(v); regRecord = sqlite3GetTempReg(pParse); sqlite3GenerateIndexKey(pParse,pIndex,iTab,regRecord,0,&iPartIdxLabel,0,0); sqlite3VdbeAddOp2(v, OP_SorterInsert, iSorter, regRecord); sqlite3ResolvePartIdxLabel(pParse, iPartIdxLabel); sqlite3VdbeAddOp2(v, OP_Next, iTab, addr1+1); VdbeCoverage(v); sqlite3VdbeJumpHere(v, addr1); if( memRootPage<0 ) sqlite3VdbeAddOp2(v, OP_Clear, tnum, iDb); sqlite3VdbeAddOp4(v, OP_OpenWrite, iIdx, tnum, iDb, (char *)pKey, P4_KEYINFO); sqlite3VdbeChangeP5(v, OPFLAG_BULKCSR|((memRootPage>=0)?OPFLAG_P2ISREG:0)); addr1 = sqlite3VdbeAddOp2(v, OP_SorterSort, iSorter, 0); VdbeCoverage(v); if( IsUniqueIndex(pIndex) ){ int j2 = sqlite3VdbeCurrentAddr(v) + 3; sqlite3VdbeGoto(v, j2); addr2 = sqlite3VdbeCurrentAddr(v); sqlite3VdbeAddOp4Int(v, OP_SorterCompare, iSorter, j2, regRecord, pIndex->nKeyCol); VdbeCoverage(v); sqlite3UniqueConstraint(pParse, OE_Abort, pIndex); }else{ addr2 = sqlite3VdbeCurrentAddr(v); } sqlite3VdbeAddOp3(v, OP_SorterData, iSorter, regRecord, iIdx); sqlite3VdbeAddOp3(v, OP_Last, iIdx, 0, -1); sqlite3VdbeAddOp3(v, OP_IdxInsert, iIdx, regRecord, 0); sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT); sqlite3ReleaseTempReg(pParse, regRecord); sqlite3VdbeAddOp2(v, OP_SorterNext, iSorter, addr2); VdbeCoverage(v); sqlite3VdbeJumpHere(v, addr1); sqlite3VdbeAddOp1(v, OP_Close, iTab); sqlite3VdbeAddOp1(v, OP_Close, iIdx); sqlite3VdbeAddOp1(v, OP_Close, iSorter); } /* ** Allocate heap space to hold an Index object with nCol columns. ** ** Increase the allocation size to provide an extra nExtra bytes ** of 8-byte aligned space after the Index object and return a ** pointer to this extra space in *ppExtra. */ SQLITE_PRIVATE Index *sqlite3AllocateIndexObject( sqlite3 *db, /* Database connection */ i16 nCol, /* Total number of columns in the index */ int nExtra, /* Number of bytes of extra space to alloc */ char **ppExtra /* Pointer to the "extra" space */ ){ Index *p; /* Allocated index object */ int nByte; /* Bytes of space for Index object + arrays */ nByte = ROUND8(sizeof(Index)) + /* Index structure */ ROUND8(sizeof(char*)*nCol) + /* Index.azColl */ ROUND8(sizeof(LogEst)*(nCol+1) + /* Index.aiRowLogEst */ sizeof(i16)*nCol + /* Index.aiColumn */ sizeof(u8)*nCol); /* Index.aSortOrder */ p = sqlite3DbMallocZero(db, nByte + nExtra); if( p ){ char *pExtra = ((char*)p)+ROUND8(sizeof(Index)); p->azColl = (const char**)pExtra; pExtra += ROUND8(sizeof(char*)*nCol); p->aiRowLogEst = (LogEst*)pExtra; pExtra += sizeof(LogEst)*(nCol+1); p->aiColumn = (i16*)pExtra; pExtra += sizeof(i16)*nCol; p->aSortOrder = (u8*)pExtra; p->nColumn = nCol; p->nKeyCol = nCol - 1; *ppExtra = ((char*)p) + nByte; } return p; } /* ** Create a new index for an SQL table. pName1.pName2 is the name of the index ** and pTblList is the name of the table that is to be indexed. Both will ** be NULL for a primary key or an index that is created to satisfy a ** UNIQUE constraint. If pTable and pIndex are NULL, use pParse->pNewTable ** as the table to be indexed. pParse->pNewTable is a table that is ** currently being constructed by a CREATE TABLE statement. ** ** pList is a list of columns to be indexed. pList will be NULL if this ** is a primary key or unique-constraint on the most recent column added ** to the table currently under construction. */ SQLITE_PRIVATE void sqlite3CreateIndex( Parse *pParse, /* All information about this parse */ Token *pName1, /* First part of index name. May be NULL */ Token *pName2, /* Second part of index name. May be NULL */ SrcList *pTblName, /* Table to index. Use pParse->pNewTable if 0 */ ExprList *pList, /* A list of columns to be indexed */ int onError, /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */ Token *pStart, /* The CREATE token that begins this statement */ Expr *pPIWhere, /* WHERE clause for partial indices */ int sortOrder, /* Sort order of primary key when pList==NULL */ int ifNotExist, /* Omit error if index already exists */ u8 idxType /* The index type */ ){ Table *pTab = 0; /* Table to be indexed */ Index *pIndex = 0; /* The index to be created */ char *zName = 0; /* Name of the index */ int nName; /* Number of characters in zName */ int i, j; DbFixer sFix; /* For assigning database names to pTable */ int sortOrderMask; /* 1 to honor DESC in index. 0 to ignore. */ sqlite3 *db = pParse->db; Db *pDb; /* The specific table containing the indexed database */ int iDb; /* Index of the database that is being written */ Token *pName = 0; /* Unqualified name of the index to create */ struct ExprList_item *pListItem; /* For looping over pList */ int nExtra = 0; /* Space allocated for zExtra[] */ int nExtraCol; /* Number of extra columns needed */ char *zExtra = 0; /* Extra space after the Index object */ Index *pPk = 0; /* PRIMARY KEY index for WITHOUT ROWID tables */ if( db->mallocFailed || pParse->nErr>0 ){ goto exit_create_index; } if( IN_DECLARE_VTAB && idxType!=SQLITE_IDXTYPE_PRIMARYKEY ){ goto exit_create_index; } if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){ goto exit_create_index; } /* ** Find the table that is to be indexed. Return early if not found. */ if( pTblName!=0 ){ /* Use the two-part index name to determine the database ** to search for the table. 'Fix' the table name to this db ** before looking up the table. */ assert( pName1 && pName2 ); iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName); if( iDb<0 ) goto exit_create_index; assert( pName && pName->z ); #ifndef SQLITE_OMIT_TEMPDB /* If the index name was unqualified, check if the table ** is a temp table. If so, set the database to 1. Do not do this ** if initialising a database schema. */ if( !db->init.busy ){ pTab = sqlite3SrcListLookup(pParse, pTblName); if( pName2->n==0 && pTab && pTab->pSchema==db->aDb[1].pSchema ){ iDb = 1; } } #endif sqlite3FixInit(&sFix, pParse, iDb, "index", pName); if( sqlite3FixSrcList(&sFix, pTblName) ){ /* Because the parser constructs pTblName from a single identifier, ** sqlite3FixSrcList can never fail. */ assert(0); } pTab = sqlite3LocateTableItem(pParse, 0, &pTblName->a[0]); assert( db->mallocFailed==0 || pTab==0 ); if( pTab==0 ) goto exit_create_index; if( iDb==1 && db->aDb[iDb].pSchema!=pTab->pSchema ){ sqlite3ErrorMsg(pParse, "cannot create a TEMP index on non-TEMP table \"%s\"", pTab->zName); goto exit_create_index; } if( !HasRowid(pTab) ) pPk = sqlite3PrimaryKeyIndex(pTab); }else{ assert( pName==0 ); assert( pStart==0 ); pTab = pParse->pNewTable; if( !pTab ) goto exit_create_index; iDb = sqlite3SchemaToIndex(db, pTab->pSchema); } pDb = &db->aDb[iDb]; assert( pTab!=0 ); assert( pParse->nErr==0 ); if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0 && db->init.busy==0 #if SQLITE_USER_AUTHENTICATION && sqlite3UserAuthTable(pTab->zName)==0 #endif && sqlite3StrNICmp(&pTab->zName[7],"altertab_",9)!=0 ){ sqlite3ErrorMsg(pParse, "table %s may not be indexed", pTab->zName); goto exit_create_index; } #ifndef SQLITE_OMIT_VIEW if( pTab->pSelect ){ sqlite3ErrorMsg(pParse, "views may not be indexed"); goto exit_create_index; } #endif #ifndef SQLITE_OMIT_VIRTUALTABLE if( IsVirtual(pTab) ){ sqlite3ErrorMsg(pParse, "virtual tables may not be indexed"); goto exit_create_index; } #endif /* ** Find the name of the index. Make sure there is not already another ** index or table with the same name. ** ** Exception: If we are reading the names of permanent indices from the ** sqlite_master table (because some other process changed the schema) and ** one of the index names collides with the name of a temporary table or ** index, then we will continue to process this index. ** ** If pName==0 it means that we are ** dealing with a primary key or UNIQUE constraint. We have to invent our ** own name. */ if( pName ){ zName = sqlite3NameFromToken(db, pName); if( zName==0 ) goto exit_create_index; assert( pName->z!=0 ); if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){ goto exit_create_index; } if( !db->init.busy ){ if( sqlite3FindTable(db, zName, 0)!=0 ){ sqlite3ErrorMsg(pParse, "there is already a table named %s", zName); goto exit_create_index; } } if( sqlite3FindIndex(db, zName, pDb->zDbSName)!=0 ){ if( !ifNotExist ){ sqlite3ErrorMsg(pParse, "index %s already exists", zName); }else{ assert( !db->init.busy ); sqlite3CodeVerifySchema(pParse, iDb); } goto exit_create_index; } }else{ int n; Index *pLoop; for(pLoop=pTab->pIndex, n=1; pLoop; pLoop=pLoop->pNext, n++){} zName = sqlite3MPrintf(db, "sqlite_autoindex_%s_%d", pTab->zName, n); if( zName==0 ){ goto exit_create_index; } /* Automatic index names generated from within sqlite3_declare_vtab() ** must have names that are distinct from normal automatic index names. ** The following statement converts "sqlite3_autoindex..." into ** "sqlite3_butoindex..." in order to make the names distinct. ** The "vtab_err.test" test demonstrates the need of this statement. */ if( IN_DECLARE_VTAB ) zName[7]++; } /* Check for authorization to create an index. */ #ifndef SQLITE_OMIT_AUTHORIZATION { const char *zDb = pDb->zDbSName; if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(iDb), 0, zDb) ){ goto exit_create_index; } i = SQLITE_CREATE_INDEX; if( !OMIT_TEMPDB && iDb==1 ) i = SQLITE_CREATE_TEMP_INDEX; if( sqlite3AuthCheck(pParse, i, zName, pTab->zName, zDb) ){ goto exit_create_index; } } #endif /* If pList==0, it means this routine was called to make a primary ** key out of the last column added to the table under construction. ** So create a fake list to simulate this. */ if( pList==0 ){ Token prevCol; sqlite3TokenInit(&prevCol, pTab->aCol[pTab->nCol-1].zName); pList = sqlite3ExprListAppend(pParse, 0, sqlite3ExprAlloc(db, TK_ID, &prevCol, 0)); if( pList==0 ) goto exit_create_index; assert( pList->nExpr==1 ); sqlite3ExprListSetSortOrder(pList, sortOrder); }else{ sqlite3ExprListCheckLength(pParse, pList, "index"); } /* Figure out how many bytes of space are required to store explicitly ** specified collation sequence names. */ for(i=0; inExpr; i++){ Expr *pExpr = pList->a[i].pExpr; assert( pExpr!=0 ); if( pExpr->op==TK_COLLATE ){ nExtra += (1 + sqlite3Strlen30(pExpr->u.zToken)); } } /* ** Allocate the index structure. */ nName = sqlite3Strlen30(zName); nExtraCol = pPk ? pPk->nKeyCol : 1; pIndex = sqlite3AllocateIndexObject(db, pList->nExpr + nExtraCol, nName + nExtra + 1, &zExtra); if( db->mallocFailed ){ goto exit_create_index; } assert( EIGHT_BYTE_ALIGNMENT(pIndex->aiRowLogEst) ); assert( EIGHT_BYTE_ALIGNMENT(pIndex->azColl) ); pIndex->zName = zExtra; zExtra += nName + 1; memcpy(pIndex->zName, zName, nName+1); pIndex->pTable = pTab; pIndex->onError = (u8)onError; pIndex->uniqNotNull = onError!=OE_None; pIndex->idxType = idxType; pIndex->pSchema = db->aDb[iDb].pSchema; pIndex->nKeyCol = pList->nExpr; if( pPIWhere ){ sqlite3ResolveSelfReference(pParse, pTab, NC_PartIdx, pPIWhere, 0); pIndex->pPartIdxWhere = pPIWhere; pPIWhere = 0; } assert( sqlite3SchemaMutexHeld(db, iDb, 0) ); /* Check to see if we should honor DESC requests on index columns */ if( pDb->pSchema->file_format>=4 ){ sortOrderMask = -1; /* Honor DESC */ }else{ sortOrderMask = 0; /* Ignore DESC */ } /* Analyze the list of expressions that form the terms of the index and ** report any errors. In the common case where the expression is exactly ** a table column, store that column in aiColumn[]. For general expressions, ** populate pIndex->aColExpr and store XN_EXPR (-2) in aiColumn[]. ** ** TODO: Issue a warning if two or more columns of the index are identical. ** TODO: Issue a warning if the table primary key is used as part of the ** index key. */ for(i=0, pListItem=pList->a; inExpr; i++, pListItem++){ Expr *pCExpr; /* The i-th index expression */ int requestedSortOrder; /* ASC or DESC on the i-th expression */ const char *zColl; /* Collation sequence name */ sqlite3StringToId(pListItem->pExpr); sqlite3ResolveSelfReference(pParse, pTab, NC_IdxExpr, pListItem->pExpr, 0); if( pParse->nErr ) goto exit_create_index; pCExpr = sqlite3ExprSkipCollate(pListItem->pExpr); if( pCExpr->op!=TK_COLUMN ){ if( pTab==pParse->pNewTable ){ sqlite3ErrorMsg(pParse, "expressions prohibited in PRIMARY KEY and " "UNIQUE constraints"); goto exit_create_index; } if( pIndex->aColExpr==0 ){ ExprList *pCopy = sqlite3ExprListDup(db, pList, 0); pIndex->aColExpr = pCopy; if( !db->mallocFailed ){ assert( pCopy!=0 ); pListItem = &pCopy->a[i]; } } j = XN_EXPR; pIndex->aiColumn[i] = XN_EXPR; pIndex->uniqNotNull = 0; }else{ j = pCExpr->iColumn; assert( j<=0x7fff ); if( j<0 ){ j = pTab->iPKey; }else if( pTab->aCol[j].notNull==0 ){ pIndex->uniqNotNull = 0; } pIndex->aiColumn[i] = (i16)j; } zColl = 0; if( pListItem->pExpr->op==TK_COLLATE ){ int nColl; zColl = pListItem->pExpr->u.zToken; nColl = sqlite3Strlen30(zColl) + 1; assert( nExtra>=nColl ); memcpy(zExtra, zColl, nColl); zColl = zExtra; zExtra += nColl; nExtra -= nColl; }else if( j>=0 ){ zColl = pTab->aCol[j].zColl; } if( !zColl ) zColl = sqlite3StrBINARY; if( !db->init.busy && !sqlite3LocateCollSeq(pParse, zColl) ){ goto exit_create_index; } pIndex->azColl[i] = zColl; requestedSortOrder = pListItem->sortOrder & sortOrderMask; pIndex->aSortOrder[i] = (u8)requestedSortOrder; } /* Append the table key to the end of the index. For WITHOUT ROWID ** tables (when pPk!=0) this will be the declared PRIMARY KEY. For ** normal tables (when pPk==0) this will be the rowid. */ if( pPk ){ for(j=0; jnKeyCol; j++){ int x = pPk->aiColumn[j]; assert( x>=0 ); if( hasColumn(pIndex->aiColumn, pIndex->nKeyCol, x) ){ pIndex->nColumn--; }else{ pIndex->aiColumn[i] = x; pIndex->azColl[i] = pPk->azColl[j]; pIndex->aSortOrder[i] = pPk->aSortOrder[j]; i++; } } assert( i==pIndex->nColumn ); }else{ pIndex->aiColumn[i] = XN_ROWID; pIndex->azColl[i] = sqlite3StrBINARY; } sqlite3DefaultRowEst(pIndex); if( pParse->pNewTable==0 ) estimateIndexWidth(pIndex); /* If this index contains every column of its table, then mark ** it as a covering index */ assert( HasRowid(pTab) || pTab->iPKey<0 || sqlite3ColumnOfIndex(pIndex, pTab->iPKey)>=0 ); if( pTblName!=0 && pIndex->nColumn>=pTab->nCol ){ pIndex->isCovering = 1; for(j=0; jnCol; j++){ if( j==pTab->iPKey ) continue; if( sqlite3ColumnOfIndex(pIndex,j)>=0 ) continue; pIndex->isCovering = 0; break; } } if( pTab==pParse->pNewTable ){ /* This routine has been called to create an automatic index as a ** result of a PRIMARY KEY or UNIQUE clause on a column definition, or ** a PRIMARY KEY or UNIQUE clause following the column definitions. ** i.e. one of: ** ** CREATE TABLE t(x PRIMARY KEY, y); ** CREATE TABLE t(x, y, UNIQUE(x, y)); ** ** Either way, check to see if the table already has such an index. If ** so, don't bother creating this one. This only applies to ** automatically created indices. Users can do as they wish with ** explicit indices. ** ** Two UNIQUE or PRIMARY KEY constraints are considered equivalent ** (and thus suppressing the second one) even if they have different ** sort orders. ** ** If there are different collating sequences or if the columns of ** the constraint occur in different orders, then the constraints are ** considered distinct and both result in separate indices. */ Index *pIdx; for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){ int k; assert( IsUniqueIndex(pIdx) ); assert( pIdx->idxType!=SQLITE_IDXTYPE_APPDEF ); assert( IsUniqueIndex(pIndex) ); if( pIdx->nKeyCol!=pIndex->nKeyCol ) continue; for(k=0; knKeyCol; k++){ const char *z1; const char *z2; assert( pIdx->aiColumn[k]>=0 ); if( pIdx->aiColumn[k]!=pIndex->aiColumn[k] ) break; z1 = pIdx->azColl[k]; z2 = pIndex->azColl[k]; if( sqlite3StrICmp(z1, z2) ) break; } if( k==pIdx->nKeyCol ){ if( pIdx->onError!=pIndex->onError ){ /* This constraint creates the same index as a previous ** constraint specified somewhere in the CREATE TABLE statement. ** However the ON CONFLICT clauses are different. If both this ** constraint and the previous equivalent constraint have explicit ** ON CONFLICT clauses this is an error. Otherwise, use the ** explicitly specified behavior for the index. */ if( !(pIdx->onError==OE_Default || pIndex->onError==OE_Default) ){ sqlite3ErrorMsg(pParse, "conflicting ON CONFLICT clauses specified", 0); } if( pIdx->onError==OE_Default ){ pIdx->onError = pIndex->onError; } } if( idxType==SQLITE_IDXTYPE_PRIMARYKEY ) pIdx->idxType = idxType; goto exit_create_index; } } } /* Link the new Index structure to its table and to the other ** in-memory database structures. */ assert( pParse->nErr==0 ); if( db->init.busy ){ Index *p; assert( !IN_DECLARE_VTAB ); assert( sqlite3SchemaMutexHeld(db, 0, pIndex->pSchema) ); p = sqlite3HashInsert(&pIndex->pSchema->idxHash, pIndex->zName, pIndex); if( p ){ assert( p==pIndex ); /* Malloc must have failed */ sqlite3OomFault(db); goto exit_create_index; } db->flags |= SQLITE_InternChanges; if( pTblName!=0 ){ pIndex->tnum = db->init.newTnum; } } /* If this is the initial CREATE INDEX statement (or CREATE TABLE if the ** index is an implied index for a UNIQUE or PRIMARY KEY constraint) then ** emit code to allocate the index rootpage on disk and make an entry for ** the index in the sqlite_master table and populate the index with ** content. But, do not do this if we are simply reading the sqlite_master ** table to parse the schema, or if this index is the PRIMARY KEY index ** of a WITHOUT ROWID table. ** ** If pTblName==0 it means this index is generated as an implied PRIMARY KEY ** or UNIQUE index in a CREATE TABLE statement. Since the table ** has just been created, it contains no data and the index initialization ** step can be skipped. */ else if( HasRowid(pTab) || pTblName!=0 ){ Vdbe *v; char *zStmt; int iMem = ++pParse->nMem; v = sqlite3GetVdbe(pParse); if( v==0 ) goto exit_create_index; sqlite3BeginWriteOperation(pParse, 1, iDb); /* Create the rootpage for the index using CreateIndex. But before ** doing so, code a Noop instruction and store its address in ** Index.tnum. This is required in case this index is actually a ** PRIMARY KEY and the table is actually a WITHOUT ROWID table. In ** that case the convertToWithoutRowidTable() routine will replace ** the Noop with a Goto to jump over the VDBE code generated below. */ pIndex->tnum = sqlite3VdbeAddOp0(v, OP_Noop); sqlite3VdbeAddOp2(v, OP_CreateIndex, iDb, iMem); /* Gather the complete text of the CREATE INDEX statement into ** the zStmt variable */ if( pStart ){ int n = (int)(pParse->sLastToken.z - pName->z) + pParse->sLastToken.n; if( pName->z[n-1]==';' ) n--; /* A named index with an explicit CREATE INDEX statement */ zStmt = sqlite3MPrintf(db, "CREATE%s INDEX %.*s", onError==OE_None ? "" : " UNIQUE", n, pName->z); }else{ /* An automatic index created by a PRIMARY KEY or UNIQUE constraint */ /* zStmt = sqlite3MPrintf(""); */ zStmt = 0; } /* Add an entry in sqlite_master for this index */ sqlite3NestedParse(pParse, "INSERT INTO %Q.%s VALUES('index',%Q,%Q,#%d,%Q);", db->aDb[iDb].zDbSName, SCHEMA_TABLE(iDb), pIndex->zName, pTab->zName, iMem, zStmt ); sqlite3DbFree(db, zStmt); /* Fill the index with data and reparse the schema. Code an OP_Expire ** to invalidate all pre-compiled statements. */ if( pTblName ){ sqlite3RefillIndex(pParse, pIndex, iMem); sqlite3ChangeCookie(pParse, iDb); sqlite3VdbeAddParseSchemaOp(v, iDb, sqlite3MPrintf(db, "name='%q' AND type='index'", pIndex->zName)); sqlite3VdbeAddOp0(v, OP_Expire); } sqlite3VdbeJumpHere(v, pIndex->tnum); } /* When adding an index to the list of indices for a table, make ** sure all indices labeled OE_Replace come after all those labeled ** OE_Ignore. This is necessary for the correct constraint check ** processing (in sqlite3GenerateConstraintChecks()) as part of ** UPDATE and INSERT statements. */ if( db->init.busy || pTblName==0 ){ if( onError!=OE_Replace || pTab->pIndex==0 || pTab->pIndex->onError==OE_Replace){ pIndex->pNext = pTab->pIndex; pTab->pIndex = pIndex; }else{ Index *pOther = pTab->pIndex; while( pOther->pNext && pOther->pNext->onError!=OE_Replace ){ pOther = pOther->pNext; } pIndex->pNext = pOther->pNext; pOther->pNext = pIndex; } pIndex = 0; } /* Clean up before exiting */ exit_create_index: if( pIndex ) freeIndex(db, pIndex); sqlite3ExprDelete(db, pPIWhere); sqlite3ExprListDelete(db, pList); sqlite3SrcListDelete(db, pTblName); sqlite3DbFree(db, zName); } /* ** Fill the Index.aiRowEst[] array with default information - information ** to be used when we have not run the ANALYZE command. ** ** aiRowEst[0] is supposed to contain the number of elements in the index. ** Since we do not know, guess 1 million. aiRowEst[1] is an estimate of the ** number of rows in the table that match any particular value of the ** first column of the index. aiRowEst[2] is an estimate of the number ** of rows that match any particular combination of the first 2 columns ** of the index. And so forth. It must always be the case that * ** aiRowEst[N]<=aiRowEst[N-1] ** aiRowEst[N]>=1 ** ** Apart from that, we have little to go on besides intuition as to ** how aiRowEst[] should be initialized. The numbers generated here ** are based on typical values found in actual indices. */ SQLITE_PRIVATE void sqlite3DefaultRowEst(Index *pIdx){ /* 10, 9, 8, 7, 6 */ LogEst aVal[] = { 33, 32, 30, 28, 26 }; LogEst *a = pIdx->aiRowLogEst; int nCopy = MIN(ArraySize(aVal), pIdx->nKeyCol); int i; /* Set the first entry (number of rows in the index) to the estimated ** number of rows in the table, or half the number of rows in the table ** for a partial index. But do not let the estimate drop below 10. */ a[0] = pIdx->pTable->nRowLogEst; if( pIdx->pPartIdxWhere!=0 ) a[0] -= 10; assert( 10==sqlite3LogEst(2) ); if( a[0]<33 ) a[0] = 33; assert( 33==sqlite3LogEst(10) ); /* Estimate that a[1] is 10, a[2] is 9, a[3] is 8, a[4] is 7, a[5] is ** 6 and each subsequent value (if any) is 5. */ memcpy(&a[1], aVal, nCopy*sizeof(LogEst)); for(i=nCopy+1; i<=pIdx->nKeyCol; i++){ a[i] = 23; assert( 23==sqlite3LogEst(5) ); } assert( 0==sqlite3LogEst(1) ); if( IsUniqueIndex(pIdx) ) a[pIdx->nKeyCol] = 0; } /* ** This routine will drop an existing named index. This routine ** implements the DROP INDEX statement. */ SQLITE_PRIVATE void sqlite3DropIndex(Parse *pParse, SrcList *pName, int ifExists){ Index *pIndex; Vdbe *v; sqlite3 *db = pParse->db; int iDb; assert( pParse->nErr==0 ); /* Never called with prior errors */ if( db->mallocFailed ){ goto exit_drop_index; } assert( pName->nSrc==1 ); if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){ goto exit_drop_index; } pIndex = sqlite3FindIndex(db, pName->a[0].zName, pName->a[0].zDatabase); if( pIndex==0 ){ if( !ifExists ){ sqlite3ErrorMsg(pParse, "no such index: %S", pName, 0); }else{ sqlite3CodeVerifyNamedSchema(pParse, pName->a[0].zDatabase); } pParse->checkSchema = 1; goto exit_drop_index; } if( pIndex->idxType!=SQLITE_IDXTYPE_APPDEF ){ sqlite3ErrorMsg(pParse, "index associated with UNIQUE " "or PRIMARY KEY constraint cannot be dropped", 0); goto exit_drop_index; } iDb = sqlite3SchemaToIndex(db, pIndex->pSchema); #ifndef SQLITE_OMIT_AUTHORIZATION { int code = SQLITE_DROP_INDEX; Table *pTab = pIndex->pTable; const char *zDb = db->aDb[iDb].zDbSName; const char *zTab = SCHEMA_TABLE(iDb); if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){ goto exit_drop_index; } if( !OMIT_TEMPDB && iDb ) code = SQLITE_DROP_TEMP_INDEX; if( sqlite3AuthCheck(pParse, code, pIndex->zName, pTab->zName, zDb) ){ goto exit_drop_index; } } #endif /* Generate code to remove the index and from the master table */ v = sqlite3GetVdbe(pParse); if( v ){ sqlite3BeginWriteOperation(pParse, 1, iDb); sqlite3NestedParse(pParse, "DELETE FROM %Q.%s WHERE name=%Q AND type='index'", db->aDb[iDb].zDbSName, SCHEMA_TABLE(iDb), pIndex->zName ); sqlite3ClearStatTables(pParse, iDb, "idx", pIndex->zName); sqlite3ChangeCookie(pParse, iDb); destroyRootPage(pParse, pIndex->tnum, iDb); sqlite3VdbeAddOp4(v, OP_DropIndex, iDb, 0, 0, pIndex->zName, 0); } exit_drop_index: sqlite3SrcListDelete(db, pName); } /* ** pArray is a pointer to an array of objects. Each object in the ** array is szEntry bytes in size. This routine uses sqlite3DbRealloc() ** to extend the array so that there is space for a new object at the end. ** ** When this function is called, *pnEntry contains the current size of ** the array (in entries - so the allocation is ((*pnEntry) * szEntry) bytes ** in total). ** ** If the realloc() is successful (i.e. if no OOM condition occurs), the ** space allocated for the new object is zeroed, *pnEntry updated to ** reflect the new size of the array and a pointer to the new allocation ** returned. *pIdx is set to the index of the new array entry in this case. ** ** Otherwise, if the realloc() fails, *pIdx is set to -1, *pnEntry remains ** unchanged and a copy of pArray returned. */ SQLITE_PRIVATE void *sqlite3ArrayAllocate( sqlite3 *db, /* Connection to notify of malloc failures */ void *pArray, /* Array of objects. Might be reallocated */ int szEntry, /* Size of each object in the array */ int *pnEntry, /* Number of objects currently in use */ int *pIdx /* Write the index of a new slot here */ ){ char *z; int n = *pnEntry; if( (n & (n-1))==0 ){ int sz = (n==0) ? 1 : 2*n; void *pNew = sqlite3DbRealloc(db, pArray, sz*szEntry); if( pNew==0 ){ *pIdx = -1; return pArray; } pArray = pNew; } z = (char*)pArray; memset(&z[n * szEntry], 0, szEntry); *pIdx = n; ++*pnEntry; return pArray; } /* ** Append a new element to the given IdList. Create a new IdList if ** need be. ** ** A new IdList is returned, or NULL if malloc() fails. */ SQLITE_PRIVATE IdList *sqlite3IdListAppend(sqlite3 *db, IdList *pList, Token *pToken){ int i; if( pList==0 ){ pList = sqlite3DbMallocZero(db, sizeof(IdList) ); if( pList==0 ) return 0; } pList->a = sqlite3ArrayAllocate( db, pList->a, sizeof(pList->a[0]), &pList->nId, &i ); if( i<0 ){ sqlite3IdListDelete(db, pList); return 0; } pList->a[i].zName = sqlite3NameFromToken(db, pToken); return pList; } /* ** Delete an IdList. */ SQLITE_PRIVATE void sqlite3IdListDelete(sqlite3 *db, IdList *pList){ int i; if( pList==0 ) return; for(i=0; inId; i++){ sqlite3DbFree(db, pList->a[i].zName); } sqlite3DbFree(db, pList->a); sqlite3DbFree(db, pList); } /* ** Return the index in pList of the identifier named zId. Return -1 ** if not found. */ SQLITE_PRIVATE int sqlite3IdListIndex(IdList *pList, const char *zName){ int i; if( pList==0 ) return -1; for(i=0; inId; i++){ if( sqlite3StrICmp(pList->a[i].zName, zName)==0 ) return i; } return -1; } /* ** Expand the space allocated for the given SrcList object by ** creating nExtra new slots beginning at iStart. iStart is zero based. ** New slots are zeroed. ** ** For example, suppose a SrcList initially contains two entries: A,B. ** To append 3 new entries onto the end, do this: ** ** sqlite3SrcListEnlarge(db, pSrclist, 3, 2); ** ** After the call above it would contain: A, B, nil, nil, nil. ** If the iStart argument had been 1 instead of 2, then the result ** would have been: A, nil, nil, nil, B. To prepend the new slots, ** the iStart value would be 0. The result then would ** be: nil, nil, nil, A, B. ** ** If a memory allocation fails the SrcList is unchanged. The ** db->mallocFailed flag will be set to true. */ SQLITE_PRIVATE SrcList *sqlite3SrcListEnlarge( sqlite3 *db, /* Database connection to notify of OOM errors */ SrcList *pSrc, /* The SrcList to be enlarged */ int nExtra, /* Number of new slots to add to pSrc->a[] */ int iStart /* Index in pSrc->a[] of first new slot */ ){ int i; /* Sanity checking on calling parameters */ assert( iStart>=0 ); assert( nExtra>=1 ); assert( pSrc!=0 ); assert( iStart<=pSrc->nSrc ); /* Allocate additional space if needed */ if( (u32)pSrc->nSrc+nExtra>pSrc->nAlloc ){ SrcList *pNew; int nAlloc = pSrc->nSrc+nExtra; int nGot; pNew = sqlite3DbRealloc(db, pSrc, sizeof(*pSrc) + (nAlloc-1)*sizeof(pSrc->a[0]) ); if( pNew==0 ){ assert( db->mallocFailed ); return pSrc; } pSrc = pNew; nGot = (sqlite3DbMallocSize(db, pNew) - sizeof(*pSrc))/sizeof(pSrc->a[0])+1; pSrc->nAlloc = nGot; } /* Move existing slots that come after the newly inserted slots ** out of the way */ for(i=pSrc->nSrc-1; i>=iStart; i--){ pSrc->a[i+nExtra] = pSrc->a[i]; } pSrc->nSrc += nExtra; /* Zero the newly allocated slots */ memset(&pSrc->a[iStart], 0, sizeof(pSrc->a[0])*nExtra); for(i=iStart; ia[i].iCursor = -1; } /* Return a pointer to the enlarged SrcList */ return pSrc; } /* ** Append a new table name to the given SrcList. Create a new SrcList if ** need be. A new entry is created in the SrcList even if pTable is NULL. ** ** A SrcList is returned, or NULL if there is an OOM error. The returned ** SrcList might be the same as the SrcList that was input or it might be ** a new one. If an OOM error does occurs, then the prior value of pList ** that is input to this routine is automatically freed. ** ** If pDatabase is not null, it means that the table has an optional ** database name prefix. Like this: "database.table". The pDatabase ** points to the table name and the pTable points to the database name. ** The SrcList.a[].zName field is filled with the table name which might ** come from pTable (if pDatabase is NULL) or from pDatabase. ** SrcList.a[].zDatabase is filled with the database name from pTable, ** or with NULL if no database is specified. ** ** In other words, if call like this: ** ** sqlite3SrcListAppend(D,A,B,0); ** ** Then B is a table name and the database name is unspecified. If called ** like this: ** ** sqlite3SrcListAppend(D,A,B,C); ** ** Then C is the table name and B is the database name. If C is defined ** then so is B. In other words, we never have a case where: ** ** sqlite3SrcListAppend(D,A,0,C); ** ** Both pTable and pDatabase are assumed to be quoted. They are dequoted ** before being added to the SrcList. */ SQLITE_PRIVATE SrcList *sqlite3SrcListAppend( sqlite3 *db, /* Connection to notify of malloc failures */ SrcList *pList, /* Append to this SrcList. NULL creates a new SrcList */ Token *pTable, /* Table to append */ Token *pDatabase /* Database of the table */ ){ struct SrcList_item *pItem; assert( pDatabase==0 || pTable!=0 ); /* Cannot have C without B */ assert( db!=0 ); if( pList==0 ){ pList = sqlite3DbMallocRawNN(db, sizeof(SrcList) ); if( pList==0 ) return 0; pList->nAlloc = 1; pList->nSrc = 0; } pList = sqlite3SrcListEnlarge(db, pList, 1, pList->nSrc); if( db->mallocFailed ){ sqlite3SrcListDelete(db, pList); return 0; } pItem = &pList->a[pList->nSrc-1]; if( pDatabase && pDatabase->z==0 ){ pDatabase = 0; } if( pDatabase ){ Token *pTemp = pDatabase; pDatabase = pTable; pTable = pTemp; } pItem->zName = sqlite3NameFromToken(db, pTable); pItem->zDatabase = sqlite3NameFromToken(db, pDatabase); return pList; } /* ** Assign VdbeCursor index numbers to all tables in a SrcList */ SQLITE_PRIVATE void sqlite3SrcListAssignCursors(Parse *pParse, SrcList *pList){ int i; struct SrcList_item *pItem; assert(pList || pParse->db->mallocFailed ); if( pList ){ for(i=0, pItem=pList->a; inSrc; i++, pItem++){ if( pItem->iCursor>=0 ) break; pItem->iCursor = pParse->nTab++; if( pItem->pSelect ){ sqlite3SrcListAssignCursors(pParse, pItem->pSelect->pSrc); } } } } /* ** Delete an entire SrcList including all its substructure. */ SQLITE_PRIVATE void sqlite3SrcListDelete(sqlite3 *db, SrcList *pList){ int i; struct SrcList_item *pItem; if( pList==0 ) return; for(pItem=pList->a, i=0; inSrc; i++, pItem++){ sqlite3DbFree(db, pItem->zDatabase); sqlite3DbFree(db, pItem->zName); sqlite3DbFree(db, pItem->zAlias); if( pItem->fg.isIndexedBy ) sqlite3DbFree(db, pItem->u1.zIndexedBy); if( pItem->fg.isTabFunc ) sqlite3ExprListDelete(db, pItem->u1.pFuncArg); sqlite3DeleteTable(db, pItem->pTab); sqlite3SelectDelete(db, pItem->pSelect); sqlite3ExprDelete(db, pItem->pOn); sqlite3IdListDelete(db, pItem->pUsing); } sqlite3DbFree(db, pList); } /* ** This routine is called by the parser to add a new term to the ** end of a growing FROM clause. The "p" parameter is the part of ** the FROM clause that has already been constructed. "p" is NULL ** if this is the first term of the FROM clause. pTable and pDatabase ** are the name of the table and database named in the FROM clause term. ** pDatabase is NULL if the database name qualifier is missing - the ** usual case. If the term has an alias, then pAlias points to the ** alias token. If the term is a subquery, then pSubquery is the ** SELECT statement that the subquery encodes. The pTable and ** pDatabase parameters are NULL for subqueries. The pOn and pUsing ** parameters are the content of the ON and USING clauses. ** ** Return a new SrcList which encodes is the FROM with the new ** term added. */ SQLITE_PRIVATE SrcList *sqlite3SrcListAppendFromTerm( Parse *pParse, /* Parsing context */ SrcList *p, /* The left part of the FROM clause already seen */ Token *pTable, /* Name of the table to add to the FROM clause */ Token *pDatabase, /* Name of the database containing pTable */ Token *pAlias, /* The right-hand side of the AS subexpression */ Select *pSubquery, /* A subquery used in place of a table name */ Expr *pOn, /* The ON clause of a join */ IdList *pUsing /* The USING clause of a join */ ){ struct SrcList_item *pItem; sqlite3 *db = pParse->db; if( !p && (pOn || pUsing) ){ sqlite3ErrorMsg(pParse, "a JOIN clause is required before %s", (pOn ? "ON" : "USING") ); goto append_from_error; } p = sqlite3SrcListAppend(db, p, pTable, pDatabase); if( p==0 || NEVER(p->nSrc==0) ){ goto append_from_error; } pItem = &p->a[p->nSrc-1]; assert( pAlias!=0 ); if( pAlias->n ){ pItem->zAlias = sqlite3NameFromToken(db, pAlias); } pItem->pSelect = pSubquery; pItem->pOn = pOn; pItem->pUsing = pUsing; return p; append_from_error: assert( p==0 ); sqlite3ExprDelete(db, pOn); sqlite3IdListDelete(db, pUsing); sqlite3SelectDelete(db, pSubquery); return 0; } /* ** Add an INDEXED BY or NOT INDEXED clause to the most recently added ** element of the source-list passed as the second argument. */ SQLITE_PRIVATE void sqlite3SrcListIndexedBy(Parse *pParse, SrcList *p, Token *pIndexedBy){ assert( pIndexedBy!=0 ); if( p && ALWAYS(p->nSrc>0) ){ struct SrcList_item *pItem = &p->a[p->nSrc-1]; assert( pItem->fg.notIndexed==0 ); assert( pItem->fg.isIndexedBy==0 ); assert( pItem->fg.isTabFunc==0 ); if( pIndexedBy->n==1 && !pIndexedBy->z ){ /* A "NOT INDEXED" clause was supplied. See parse.y ** construct "indexed_opt" for details. */ pItem->fg.notIndexed = 1; }else{ pItem->u1.zIndexedBy = sqlite3NameFromToken(pParse->db, pIndexedBy); pItem->fg.isIndexedBy = (pItem->u1.zIndexedBy!=0); } } } /* ** Add the list of function arguments to the SrcList entry for a ** table-valued-function. */ SQLITE_PRIVATE void sqlite3SrcListFuncArgs(Parse *pParse, SrcList *p, ExprList *pList){ if( p ){ struct SrcList_item *pItem = &p->a[p->nSrc-1]; assert( pItem->fg.notIndexed==0 ); assert( pItem->fg.isIndexedBy==0 ); assert( pItem->fg.isTabFunc==0 ); pItem->u1.pFuncArg = pList; pItem->fg.isTabFunc = 1; }else{ sqlite3ExprListDelete(pParse->db, pList); } } /* ** When building up a FROM clause in the parser, the join operator ** is initially attached to the left operand. But the code generator ** expects the join operator to be on the right operand. This routine ** Shifts all join operators from left to right for an entire FROM ** clause. ** ** Example: Suppose the join is like this: ** ** A natural cross join B ** ** The operator is "natural cross join". The A and B operands are stored ** in p->a[0] and p->a[1], respectively. The parser initially stores the ** operator with A. This routine shifts that operator over to B. */ SQLITE_PRIVATE void sqlite3SrcListShiftJoinType(SrcList *p){ if( p ){ int i; for(i=p->nSrc-1; i>0; i--){ p->a[i].fg.jointype = p->a[i-1].fg.jointype; } p->a[0].fg.jointype = 0; } } /* ** Generate VDBE code for a BEGIN statement. */ SQLITE_PRIVATE void sqlite3BeginTransaction(Parse *pParse, int type){ sqlite3 *db; Vdbe *v; int i; assert( pParse!=0 ); db = pParse->db; assert( db!=0 ); if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "BEGIN", 0, 0) ){ return; } v = sqlite3GetVdbe(pParse); if( !v ) return; if( type!=TK_DEFERRED ){ for(i=0; inDb; i++){ sqlite3VdbeAddOp2(v, OP_Transaction, i, (type==TK_EXCLUSIVE)+1); sqlite3VdbeUsesBtree(v, i); } } sqlite3VdbeAddOp0(v, OP_AutoCommit); } /* ** Generate VDBE code for a COMMIT statement. */ SQLITE_PRIVATE void sqlite3CommitTransaction(Parse *pParse){ Vdbe *v; assert( pParse!=0 ); assert( pParse->db!=0 ); if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "COMMIT", 0, 0) ){ return; } v = sqlite3GetVdbe(pParse); if( v ){ sqlite3VdbeAddOp1(v, OP_AutoCommit, 1); } } /* ** Generate VDBE code for a ROLLBACK statement. */ SQLITE_PRIVATE void sqlite3RollbackTransaction(Parse *pParse){ Vdbe *v; assert( pParse!=0 ); assert( pParse->db!=0 ); if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "ROLLBACK", 0, 0) ){ return; } v = sqlite3GetVdbe(pParse); if( v ){ sqlite3VdbeAddOp2(v, OP_AutoCommit, 1, 1); } } /* ** This function is called by the parser when it parses a command to create, ** release or rollback an SQL savepoint. */ SQLITE_PRIVATE void sqlite3Savepoint(Parse *pParse, int op, Token *pName){ char *zName = sqlite3NameFromToken(pParse->db, pName); if( zName ){ Vdbe *v = sqlite3GetVdbe(pParse); #ifndef SQLITE_OMIT_AUTHORIZATION static const char * const az[] = { "BEGIN", "RELEASE", "ROLLBACK" }; assert( !SAVEPOINT_BEGIN && SAVEPOINT_RELEASE==1 && SAVEPOINT_ROLLBACK==2 ); #endif if( !v || sqlite3AuthCheck(pParse, SQLITE_SAVEPOINT, az[op], zName, 0) ){ sqlite3DbFree(pParse->db, zName); return; } sqlite3VdbeAddOp4(v, OP_Savepoint, op, 0, 0, zName, P4_DYNAMIC); } } /* ** Make sure the TEMP database is open and available for use. Return ** the number of errors. Leave any error messages in the pParse structure. */ SQLITE_PRIVATE int sqlite3OpenTempDatabase(Parse *pParse){ sqlite3 *db = pParse->db; if( db->aDb[1].pBt==0 && !pParse->explain ){ int rc; Btree *pBt; static const int flags = SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE | SQLITE_OPEN_EXCLUSIVE | SQLITE_OPEN_DELETEONCLOSE | SQLITE_OPEN_TEMP_DB; rc = sqlite3BtreeOpen(db->pVfs, 0, db, &pBt, 0, flags); if( rc!=SQLITE_OK ){ sqlite3ErrorMsg(pParse, "unable to open a temporary database " "file for storing temporary tables"); pParse->rc = rc; return 1; } db->aDb[1].pBt = pBt; assert( db->aDb[1].pSchema ); if( SQLITE_NOMEM==sqlite3BtreeSetPageSize(pBt, db->nextPagesize, -1, 0) ){ sqlite3OomFault(db); return 1; } } return 0; } /* ** Record the fact that the schema cookie will need to be verified ** for database iDb. The code to actually verify the schema cookie ** will occur at the end of the top-level VDBE and will be generated ** later, by sqlite3FinishCoding(). */ SQLITE_PRIVATE void sqlite3CodeVerifySchema(Parse *pParse, int iDb){ Parse *pToplevel = sqlite3ParseToplevel(pParse); assert( iDb>=0 && iDbdb->nDb ); assert( pParse->db->aDb[iDb].pBt!=0 || iDb==1 ); assert( iDbdb, iDb, 0) ); if( DbMaskTest(pToplevel->cookieMask, iDb)==0 ){ DbMaskSet(pToplevel->cookieMask, iDb); if( !OMIT_TEMPDB && iDb==1 ){ sqlite3OpenTempDatabase(pToplevel); } } } /* ** If argument zDb is NULL, then call sqlite3CodeVerifySchema() for each ** attached database. Otherwise, invoke it for the database named zDb only. */ SQLITE_PRIVATE void sqlite3CodeVerifyNamedSchema(Parse *pParse, const char *zDb){ sqlite3 *db = pParse->db; int i; for(i=0; inDb; i++){ Db *pDb = &db->aDb[i]; if( pDb->pBt && (!zDb || 0==sqlite3StrICmp(zDb, pDb->zDbSName)) ){ sqlite3CodeVerifySchema(pParse, i); } } } /* ** Generate VDBE code that prepares for doing an operation that ** might change the database. ** ** This routine starts a new transaction if we are not already within ** a transaction. If we are already within a transaction, then a checkpoint ** is set if the setStatement parameter is true. A checkpoint should ** be set for operations that might fail (due to a constraint) part of ** the way through and which will need to undo some writes without having to ** rollback the whole transaction. For operations where all constraints ** can be checked before any changes are made to the database, it is never ** necessary to undo a write and the checkpoint should not be set. */ SQLITE_PRIVATE void sqlite3BeginWriteOperation(Parse *pParse, int setStatement, int iDb){ Parse *pToplevel = sqlite3ParseToplevel(pParse); sqlite3CodeVerifySchema(pParse, iDb); DbMaskSet(pToplevel->writeMask, iDb); pToplevel->isMultiWrite |= setStatement; } /* ** Indicate that the statement currently under construction might write ** more than one entry (example: deleting one row then inserting another, ** inserting multiple rows in a table, or inserting a row and index entries.) ** If an abort occurs after some of these writes have completed, then it will ** be necessary to undo the completed writes. */ SQLITE_PRIVATE void sqlite3MultiWrite(Parse *pParse){ Parse *pToplevel = sqlite3ParseToplevel(pParse); pToplevel->isMultiWrite = 1; } /* ** The code generator calls this routine if is discovers that it is ** possible to abort a statement prior to completion. In order to ** perform this abort without corrupting the database, we need to make ** sure that the statement is protected by a statement transaction. ** ** Technically, we only need to set the mayAbort flag if the ** isMultiWrite flag was previously set. There is a time dependency ** such that the abort must occur after the multiwrite. This makes ** some statements involving the REPLACE conflict resolution algorithm ** go a little faster. But taking advantage of this time dependency ** makes it more difficult to prove that the code is correct (in ** particular, it prevents us from writing an effective ** implementation of sqlite3AssertMayAbort()) and so we have chosen ** to take the safe route and skip the optimization. */ SQLITE_PRIVATE void sqlite3MayAbort(Parse *pParse){ Parse *pToplevel = sqlite3ParseToplevel(pParse); pToplevel->mayAbort = 1; } /* ** Code an OP_Halt that causes the vdbe to return an SQLITE_CONSTRAINT ** error. The onError parameter determines which (if any) of the statement ** and/or current transaction is rolled back. */ SQLITE_PRIVATE void sqlite3HaltConstraint( Parse *pParse, /* Parsing context */ int errCode, /* extended error code */ int onError, /* Constraint type */ char *p4, /* Error message */ i8 p4type, /* P4_STATIC or P4_TRANSIENT */ u8 p5Errmsg /* P5_ErrMsg type */ ){ Vdbe *v = sqlite3GetVdbe(pParse); assert( (errCode&0xff)==SQLITE_CONSTRAINT ); if( onError==OE_Abort ){ sqlite3MayAbort(pParse); } sqlite3VdbeAddOp4(v, OP_Halt, errCode, onError, 0, p4, p4type); sqlite3VdbeChangeP5(v, p5Errmsg); } /* ** Code an OP_Halt due to UNIQUE or PRIMARY KEY constraint violation. */ SQLITE_PRIVATE void sqlite3UniqueConstraint( Parse *pParse, /* Parsing context */ int onError, /* Constraint type */ Index *pIdx /* The index that triggers the constraint */ ){ char *zErr; int j; StrAccum errMsg; Table *pTab = pIdx->pTable; sqlite3StrAccumInit(&errMsg, pParse->db, 0, 0, 200); if( pIdx->aColExpr ){ sqlite3XPrintf(&errMsg, "index '%q'", pIdx->zName); }else{ for(j=0; jnKeyCol; j++){ char *zCol; assert( pIdx->aiColumn[j]>=0 ); zCol = pTab->aCol[pIdx->aiColumn[j]].zName; if( j ) sqlite3StrAccumAppend(&errMsg, ", ", 2); sqlite3XPrintf(&errMsg, "%s.%s", pTab->zName, zCol); } } zErr = sqlite3StrAccumFinish(&errMsg); sqlite3HaltConstraint(pParse, IsPrimaryKeyIndex(pIdx) ? SQLITE_CONSTRAINT_PRIMARYKEY : SQLITE_CONSTRAINT_UNIQUE, onError, zErr, P4_DYNAMIC, P5_ConstraintUnique); } /* ** Code an OP_Halt due to non-unique rowid. */ SQLITE_PRIVATE void sqlite3RowidConstraint( Parse *pParse, /* Parsing context */ int onError, /* Conflict resolution algorithm */ Table *pTab /* The table with the non-unique rowid */ ){ char *zMsg; int rc; if( pTab->iPKey>=0 ){ zMsg = sqlite3MPrintf(pParse->db, "%s.%s", pTab->zName, pTab->aCol[pTab->iPKey].zName); rc = SQLITE_CONSTRAINT_PRIMARYKEY; }else{ zMsg = sqlite3MPrintf(pParse->db, "%s.rowid", pTab->zName); rc = SQLITE_CONSTRAINT_ROWID; } sqlite3HaltConstraint(pParse, rc, onError, zMsg, P4_DYNAMIC, P5_ConstraintUnique); } /* ** Check to see if pIndex uses the collating sequence pColl. Return ** true if it does and false if it does not. */ #ifndef SQLITE_OMIT_REINDEX static int collationMatch(const char *zColl, Index *pIndex){ int i; assert( zColl!=0 ); for(i=0; inColumn; i++){ const char *z = pIndex->azColl[i]; assert( z!=0 || pIndex->aiColumn[i]<0 ); if( pIndex->aiColumn[i]>=0 && 0==sqlite3StrICmp(z, zColl) ){ return 1; } } return 0; } #endif /* ** Recompute all indices of pTab that use the collating sequence pColl. ** If pColl==0 then recompute all indices of pTab. */ #ifndef SQLITE_OMIT_REINDEX static void reindexTable(Parse *pParse, Table *pTab, char const *zColl){ Index *pIndex; /* An index associated with pTab */ for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){ if( zColl==0 || collationMatch(zColl, pIndex) ){ int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema); sqlite3BeginWriteOperation(pParse, 0, iDb); sqlite3RefillIndex(pParse, pIndex, -1); } } } #endif /* ** Recompute all indices of all tables in all databases where the ** indices use the collating sequence pColl. If pColl==0 then recompute ** all indices everywhere. */ #ifndef SQLITE_OMIT_REINDEX static void reindexDatabases(Parse *pParse, char const *zColl){ Db *pDb; /* A single database */ int iDb; /* The database index number */ sqlite3 *db = pParse->db; /* The database connection */ HashElem *k; /* For looping over tables in pDb */ Table *pTab; /* A table in the database */ assert( sqlite3BtreeHoldsAllMutexes(db) ); /* Needed for schema access */ for(iDb=0, pDb=db->aDb; iDbnDb; iDb++, pDb++){ assert( pDb!=0 ); for(k=sqliteHashFirst(&pDb->pSchema->tblHash); k; k=sqliteHashNext(k)){ pTab = (Table*)sqliteHashData(k); reindexTable(pParse, pTab, zColl); } } } #endif /* ** Generate code for the REINDEX command. ** ** REINDEX -- 1 ** REINDEX -- 2 ** REINDEX ?.? -- 3 ** REINDEX ?.? -- 4 ** ** Form 1 causes all indices in all attached databases to be rebuilt. ** Form 2 rebuilds all indices in all databases that use the named ** collating function. Forms 3 and 4 rebuild the named index or all ** indices associated with the named table. */ #ifndef SQLITE_OMIT_REINDEX SQLITE_PRIVATE void sqlite3Reindex(Parse *pParse, Token *pName1, Token *pName2){ CollSeq *pColl; /* Collating sequence to be reindexed, or NULL */ char *z; /* Name of a table or index */ const char *zDb; /* Name of the database */ Table *pTab; /* A table in the database */ Index *pIndex; /* An index associated with pTab */ int iDb; /* The database index number */ sqlite3 *db = pParse->db; /* The database connection */ Token *pObjName; /* Name of the table or index to be reindexed */ /* Read the database schema. If an error occurs, leave an error message ** and code in pParse and return NULL. */ if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){ return; } if( pName1==0 ){ reindexDatabases(pParse, 0); return; }else if( NEVER(pName2==0) || pName2->z==0 ){ char *zColl; assert( pName1->z ); zColl = sqlite3NameFromToken(pParse->db, pName1); if( !zColl ) return; pColl = sqlite3FindCollSeq(db, ENC(db), zColl, 0); if( pColl ){ reindexDatabases(pParse, zColl); sqlite3DbFree(db, zColl); return; } sqlite3DbFree(db, zColl); } iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pObjName); if( iDb<0 ) return; z = sqlite3NameFromToken(db, pObjName); if( z==0 ) return; zDb = db->aDb[iDb].zDbSName; pTab = sqlite3FindTable(db, z, zDb); if( pTab ){ reindexTable(pParse, pTab, 0); sqlite3DbFree(db, z); return; } pIndex = sqlite3FindIndex(db, z, zDb); sqlite3DbFree(db, z); if( pIndex ){ sqlite3BeginWriteOperation(pParse, 0, iDb); sqlite3RefillIndex(pParse, pIndex, -1); return; } sqlite3ErrorMsg(pParse, "unable to identify the object to be reindexed"); } #endif /* ** Return a KeyInfo structure that is appropriate for the given Index. ** ** The caller should invoke sqlite3KeyInfoUnref() on the returned object ** when it has finished using it. */ SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoOfIndex(Parse *pParse, Index *pIdx){ int i; int nCol = pIdx->nColumn; int nKey = pIdx->nKeyCol; KeyInfo *pKey; if( pParse->nErr ) return 0; if( pIdx->uniqNotNull ){ pKey = sqlite3KeyInfoAlloc(pParse->db, nKey, nCol-nKey); }else{ pKey = sqlite3KeyInfoAlloc(pParse->db, nCol, 0); } if( pKey ){ assert( sqlite3KeyInfoIsWriteable(pKey) ); for(i=0; iazColl[i]; pKey->aColl[i] = zColl==sqlite3StrBINARY ? 0 : sqlite3LocateCollSeq(pParse, zColl); pKey->aSortOrder[i] = pIdx->aSortOrder[i]; } if( pParse->nErr ){ sqlite3KeyInfoUnref(pKey); pKey = 0; } } return pKey; } #ifndef SQLITE_OMIT_CTE /* ** This routine is invoked once per CTE by the parser while parsing a ** WITH clause. */ SQLITE_PRIVATE With *sqlite3WithAdd( Parse *pParse, /* Parsing context */ With *pWith, /* Existing WITH clause, or NULL */ Token *pName, /* Name of the common-table */ ExprList *pArglist, /* Optional column name list for the table */ Select *pQuery /* Query used to initialize the table */ ){ sqlite3 *db = pParse->db; With *pNew; char *zName; /* Check that the CTE name is unique within this WITH clause. If ** not, store an error in the Parse structure. */ zName = sqlite3NameFromToken(pParse->db, pName); if( zName && pWith ){ int i; for(i=0; inCte; i++){ if( sqlite3StrICmp(zName, pWith->a[i].zName)==0 ){ sqlite3ErrorMsg(pParse, "duplicate WITH table name: %s", zName); } } } if( pWith ){ int nByte = sizeof(*pWith) + (sizeof(pWith->a[1]) * pWith->nCte); pNew = sqlite3DbRealloc(db, pWith, nByte); }else{ pNew = sqlite3DbMallocZero(db, sizeof(*pWith)); } assert( (pNew!=0 && zName!=0) || db->mallocFailed ); if( db->mallocFailed ){ sqlite3ExprListDelete(db, pArglist); sqlite3SelectDelete(db, pQuery); sqlite3DbFree(db, zName); pNew = pWith; }else{ pNew->a[pNew->nCte].pSelect = pQuery; pNew->a[pNew->nCte].pCols = pArglist; pNew->a[pNew->nCte].zName = zName; pNew->a[pNew->nCte].zCteErr = 0; pNew->nCte++; } return pNew; } /* ** Free the contents of the With object passed as the second argument. */ SQLITE_PRIVATE void sqlite3WithDelete(sqlite3 *db, With *pWith){ if( pWith ){ int i; for(i=0; inCte; i++){ struct Cte *pCte = &pWith->a[i]; sqlite3ExprListDelete(db, pCte->pCols); sqlite3SelectDelete(db, pCte->pSelect); sqlite3DbFree(db, pCte->zName); } sqlite3DbFree(db, pWith); } } #endif /* !defined(SQLITE_OMIT_CTE) */ /************** End of build.c ***********************************************/ /************** Begin file callback.c ****************************************/ /* ** 2005 May 23 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ************************************************************************* ** ** This file contains functions used to access the internal hash tables ** of user defined functions and collation sequences. */ /* #include "sqliteInt.h" */ /* ** Invoke the 'collation needed' callback to request a collation sequence ** in the encoding enc of name zName, length nName. */ static void callCollNeeded(sqlite3 *db, int enc, const char *zName){ assert( !db->xCollNeeded || !db->xCollNeeded16 ); if( db->xCollNeeded ){ char *zExternal = sqlite3DbStrDup(db, zName); if( !zExternal ) return; db->xCollNeeded(db->pCollNeededArg, db, enc, zExternal); sqlite3DbFree(db, zExternal); } #ifndef SQLITE_OMIT_UTF16 if( db->xCollNeeded16 ){ char const *zExternal; sqlite3_value *pTmp = sqlite3ValueNew(db); sqlite3ValueSetStr(pTmp, -1, zName, SQLITE_UTF8, SQLITE_STATIC); zExternal = sqlite3ValueText(pTmp, SQLITE_UTF16NATIVE); if( zExternal ){ db->xCollNeeded16(db->pCollNeededArg, db, (int)ENC(db), zExternal); } sqlite3ValueFree(pTmp); } #endif } /* ** This routine is called if the collation factory fails to deliver a ** collation function in the best encoding but there may be other versions ** of this collation function (for other text encodings) available. Use one ** of these instead if they exist. Avoid a UTF-8 <-> UTF-16 conversion if ** possible. */ static int synthCollSeq(sqlite3 *db, CollSeq *pColl){ CollSeq *pColl2; char *z = pColl->zName; int i; static const u8 aEnc[] = { SQLITE_UTF16BE, SQLITE_UTF16LE, SQLITE_UTF8 }; for(i=0; i<3; i++){ pColl2 = sqlite3FindCollSeq(db, aEnc[i], z, 0); if( pColl2->xCmp!=0 ){ memcpy(pColl, pColl2, sizeof(CollSeq)); pColl->xDel = 0; /* Do not copy the destructor */ return SQLITE_OK; } } return SQLITE_ERROR; } /* ** This function is responsible for invoking the collation factory callback ** or substituting a collation sequence of a different encoding when the ** requested collation sequence is not available in the desired encoding. ** ** If it is not NULL, then pColl must point to the database native encoding ** collation sequence with name zName, length nName. ** ** The return value is either the collation sequence to be used in database ** db for collation type name zName, length nName, or NULL, if no collation ** sequence can be found. If no collation is found, leave an error message. ** ** See also: sqlite3LocateCollSeq(), sqlite3FindCollSeq() */ SQLITE_PRIVATE CollSeq *sqlite3GetCollSeq( Parse *pParse, /* Parsing context */ u8 enc, /* The desired encoding for the collating sequence */ CollSeq *pColl, /* Collating sequence with native encoding, or NULL */ const char *zName /* Collating sequence name */ ){ CollSeq *p; sqlite3 *db = pParse->db; p = pColl; if( !p ){ p = sqlite3FindCollSeq(db, enc, zName, 0); } if( !p || !p->xCmp ){ /* No collation sequence of this type for this encoding is registered. ** Call the collation factory to see if it can supply us with one. */ callCollNeeded(db, enc, zName); p = sqlite3FindCollSeq(db, enc, zName, 0); } if( p && !p->xCmp && synthCollSeq(db, p) ){ p = 0; } assert( !p || p->xCmp ); if( p==0 ){ sqlite3ErrorMsg(pParse, "no such collation sequence: %s", zName); } return p; } /* ** This routine is called on a collation sequence before it is used to ** check that it is defined. An undefined collation sequence exists when ** a database is loaded that contains references to collation sequences ** that have not been defined by sqlite3_create_collation() etc. ** ** If required, this routine calls the 'collation needed' callback to ** request a definition of the collating sequence. If this doesn't work, ** an equivalent collating sequence that uses a text encoding different ** from the main database is substituted, if one is available. */ SQLITE_PRIVATE int sqlite3CheckCollSeq(Parse *pParse, CollSeq *pColl){ if( pColl ){ const char *zName = pColl->zName; sqlite3 *db = pParse->db; CollSeq *p = sqlite3GetCollSeq(pParse, ENC(db), pColl, zName); if( !p ){ return SQLITE_ERROR; } assert( p==pColl ); } return SQLITE_OK; } /* ** Locate and return an entry from the db.aCollSeq hash table. If the entry ** specified by zName and nName is not found and parameter 'create' is ** true, then create a new entry. Otherwise return NULL. ** ** Each pointer stored in the sqlite3.aCollSeq hash table contains an ** array of three CollSeq structures. The first is the collation sequence ** preferred for UTF-8, the second UTF-16le, and the third UTF-16be. ** ** Stored immediately after the three collation sequences is a copy of ** the collation sequence name. A pointer to this string is stored in ** each collation sequence structure. */ static CollSeq *findCollSeqEntry( sqlite3 *db, /* Database connection */ const char *zName, /* Name of the collating sequence */ int create /* Create a new entry if true */ ){ CollSeq *pColl; pColl = sqlite3HashFind(&db->aCollSeq, zName); if( 0==pColl && create ){ int nName = sqlite3Strlen30(zName); pColl = sqlite3DbMallocZero(db, 3*sizeof(*pColl) + nName + 1); if( pColl ){ CollSeq *pDel = 0; pColl[0].zName = (char*)&pColl[3]; pColl[0].enc = SQLITE_UTF8; pColl[1].zName = (char*)&pColl[3]; pColl[1].enc = SQLITE_UTF16LE; pColl[2].zName = (char*)&pColl[3]; pColl[2].enc = SQLITE_UTF16BE; memcpy(pColl[0].zName, zName, nName); pColl[0].zName[nName] = 0; pDel = sqlite3HashInsert(&db->aCollSeq, pColl[0].zName, pColl); /* If a malloc() failure occurred in sqlite3HashInsert(), it will ** return the pColl pointer to be deleted (because it wasn't added ** to the hash table). */ assert( pDel==0 || pDel==pColl ); if( pDel!=0 ){ sqlite3OomFault(db); sqlite3DbFree(db, pDel); pColl = 0; } } } return pColl; } /* ** Parameter zName points to a UTF-8 encoded string nName bytes long. ** Return the CollSeq* pointer for the collation sequence named zName ** for the encoding 'enc' from the database 'db'. ** ** If the entry specified is not found and 'create' is true, then create a ** new entry. Otherwise return NULL. ** ** A separate function sqlite3LocateCollSeq() is a wrapper around ** this routine. sqlite3LocateCollSeq() invokes the collation factory ** if necessary and generates an error message if the collating sequence ** cannot be found. ** ** See also: sqlite3LocateCollSeq(), sqlite3GetCollSeq() */ SQLITE_PRIVATE CollSeq *sqlite3FindCollSeq( sqlite3 *db, u8 enc, const char *zName, int create ){ CollSeq *pColl; if( zName ){ pColl = findCollSeqEntry(db, zName, create); }else{ pColl = db->pDfltColl; } assert( SQLITE_UTF8==1 && SQLITE_UTF16LE==2 && SQLITE_UTF16BE==3 ); assert( enc>=SQLITE_UTF8 && enc<=SQLITE_UTF16BE ); if( pColl ) pColl += enc-1; return pColl; } /* During the search for the best function definition, this procedure ** is called to test how well the function passed as the first argument ** matches the request for a function with nArg arguments in a system ** that uses encoding enc. The value returned indicates how well the ** request is matched. A higher value indicates a better match. ** ** If nArg is -1 that means to only return a match (non-zero) if p->nArg ** is also -1. In other words, we are searching for a function that ** takes a variable number of arguments. ** ** If nArg is -2 that means that we are searching for any function ** regardless of the number of arguments it uses, so return a positive ** match score for any ** ** The returned value is always between 0 and 6, as follows: ** ** 0: Not a match. ** 1: UTF8/16 conversion required and function takes any number of arguments. ** 2: UTF16 byte order change required and function takes any number of args. ** 3: encoding matches and function takes any number of arguments ** 4: UTF8/16 conversion required - argument count matches exactly ** 5: UTF16 byte order conversion required - argument count matches exactly ** 6: Perfect match: encoding and argument count match exactly. ** ** If nArg==(-2) then any function with a non-null xSFunc is ** a perfect match and any function with xSFunc NULL is ** a non-match. */ #define FUNC_PERFECT_MATCH 6 /* The score for a perfect match */ static int matchQuality( FuncDef *p, /* The function we are evaluating for match quality */ int nArg, /* Desired number of arguments. (-1)==any */ u8 enc /* Desired text encoding */ ){ int match; /* nArg of -2 is a special case */ if( nArg==(-2) ) return (p->xSFunc==0) ? 0 : FUNC_PERFECT_MATCH; /* Wrong number of arguments means "no match" */ if( p->nArg!=nArg && p->nArg>=0 ) return 0; /* Give a better score to a function with a specific number of arguments ** than to function that accepts any number of arguments. */ if( p->nArg==nArg ){ match = 4; }else{ match = 1; } /* Bonus points if the text encoding matches */ if( enc==(p->funcFlags & SQLITE_FUNC_ENCMASK) ){ match += 2; /* Exact encoding match */ }else if( (enc & p->funcFlags & 2)!=0 ){ match += 1; /* Both are UTF16, but with different byte orders */ } return match; } /* ** Search a FuncDefHash for a function with the given name. Return ** a pointer to the matching FuncDef if found, or 0 if there is no match. */ static FuncDef *functionSearch( int h, /* Hash of the name */ const char *zFunc /* Name of function */ ){ FuncDef *p; for(p=sqlite3BuiltinFunctions.a[h]; p; p=p->u.pHash){ if( sqlite3StrICmp(p->zName, zFunc)==0 ){ return p; } } return 0; } /* ** Insert a new FuncDef into a FuncDefHash hash table. */ SQLITE_PRIVATE void sqlite3InsertBuiltinFuncs( FuncDef *aDef, /* List of global functions to be inserted */ int nDef /* Length of the apDef[] list */ ){ int i; for(i=0; ipNext!=&aDef[i] ); aDef[i].pNext = pOther->pNext; pOther->pNext = &aDef[i]; }else{ aDef[i].pNext = 0; aDef[i].u.pHash = sqlite3BuiltinFunctions.a[h]; sqlite3BuiltinFunctions.a[h] = &aDef[i]; } } } /* ** Locate a user function given a name, a number of arguments and a flag ** indicating whether the function prefers UTF-16 over UTF-8. Return a ** pointer to the FuncDef structure that defines that function, or return ** NULL if the function does not exist. ** ** If the createFlag argument is true, then a new (blank) FuncDef ** structure is created and liked into the "db" structure if a ** no matching function previously existed. ** ** If nArg is -2, then the first valid function found is returned. A ** function is valid if xSFunc is non-zero. The nArg==(-2) ** case is used to see if zName is a valid function name for some number ** of arguments. If nArg is -2, then createFlag must be 0. ** ** If createFlag is false, then a function with the required name and ** number of arguments may be returned even if the eTextRep flag does not ** match that requested. */ SQLITE_PRIVATE FuncDef *sqlite3FindFunction( sqlite3 *db, /* An open database */ const char *zName, /* Name of the function. zero-terminated */ int nArg, /* Number of arguments. -1 means any number */ u8 enc, /* Preferred text encoding */ u8 createFlag /* Create new entry if true and does not otherwise exist */ ){ FuncDef *p; /* Iterator variable */ FuncDef *pBest = 0; /* Best match found so far */ int bestScore = 0; /* Score of best match */ int h; /* Hash value */ int nName; /* Length of the name */ assert( nArg>=(-2) ); assert( nArg>=(-1) || createFlag==0 ); nName = sqlite3Strlen30(zName); /* First search for a match amongst the application-defined functions. */ p = (FuncDef*)sqlite3HashFind(&db->aFunc, zName); while( p ){ int score = matchQuality(p, nArg, enc); if( score>bestScore ){ pBest = p; bestScore = score; } p = p->pNext; } /* If no match is found, search the built-in functions. ** ** If the SQLITE_PreferBuiltin flag is set, then search the built-in ** functions even if a prior app-defined function was found. And give ** priority to built-in functions. ** ** Except, if createFlag is true, that means that we are trying to ** install a new function. Whatever FuncDef structure is returned it will ** have fields overwritten with new information appropriate for the ** new function. But the FuncDefs for built-in functions are read-only. ** So we must not search for built-ins when creating a new function. */ if( !createFlag && (pBest==0 || (db->flags & SQLITE_PreferBuiltin)!=0) ){ bestScore = 0; h = (sqlite3UpperToLower[(u8)zName[0]] + nName) % SQLITE_FUNC_HASH_SZ; p = functionSearch(h, zName); while( p ){ int score = matchQuality(p, nArg, enc); if( score>bestScore ){ pBest = p; bestScore = score; } p = p->pNext; } } /* If the createFlag parameter is true and the search did not reveal an ** exact match for the name, number of arguments and encoding, then add a ** new entry to the hash table and return it. */ if( createFlag && bestScorezName = (const char*)&pBest[1]; pBest->nArg = (u16)nArg; pBest->funcFlags = enc; memcpy((char*)&pBest[1], zName, nName+1); pOther = (FuncDef*)sqlite3HashInsert(&db->aFunc, pBest->zName, pBest); if( pOther==pBest ){ sqlite3DbFree(db, pBest); sqlite3OomFault(db); return 0; }else{ pBest->pNext = pOther; } } if( pBest && (pBest->xSFunc || createFlag) ){ return pBest; } return 0; } /* ** Free all resources held by the schema structure. The void* argument points ** at a Schema struct. This function does not call sqlite3DbFree(db, ) on the ** pointer itself, it just cleans up subsidiary resources (i.e. the contents ** of the schema hash tables). ** ** The Schema.cache_size variable is not cleared. */ SQLITE_PRIVATE void sqlite3SchemaClear(void *p){ Hash temp1; Hash temp2; HashElem *pElem; Schema *pSchema = (Schema *)p; temp1 = pSchema->tblHash; temp2 = pSchema->trigHash; sqlite3HashInit(&pSchema->trigHash); sqlite3HashClear(&pSchema->idxHash); for(pElem=sqliteHashFirst(&temp2); pElem; pElem=sqliteHashNext(pElem)){ sqlite3DeleteTrigger(0, (Trigger*)sqliteHashData(pElem)); } sqlite3HashClear(&temp2); sqlite3HashInit(&pSchema->tblHash); for(pElem=sqliteHashFirst(&temp1); pElem; pElem=sqliteHashNext(pElem)){ Table *pTab = sqliteHashData(pElem); sqlite3DeleteTable(0, pTab); } sqlite3HashClear(&temp1); sqlite3HashClear(&pSchema->fkeyHash); pSchema->pSeqTab = 0; if( pSchema->schemaFlags & DB_SchemaLoaded ){ pSchema->iGeneration++; pSchema->schemaFlags &= ~DB_SchemaLoaded; } } /* ** Find and return the schema associated with a BTree. Create ** a new one if necessary. */ SQLITE_PRIVATE Schema *sqlite3SchemaGet(sqlite3 *db, Btree *pBt){ Schema * p; if( pBt ){ p = (Schema *)sqlite3BtreeSchema(pBt, sizeof(Schema), sqlite3SchemaClear); }else{ p = (Schema *)sqlite3DbMallocZero(0, sizeof(Schema)); } if( !p ){ sqlite3OomFault(db); }else if ( 0==p->file_format ){ sqlite3HashInit(&p->tblHash); sqlite3HashInit(&p->idxHash); sqlite3HashInit(&p->trigHash); sqlite3HashInit(&p->fkeyHash); p->enc = SQLITE_UTF8; } return p; } /************** End of callback.c ********************************************/ /************** Begin file delete.c ******************************************/ /* ** 2001 September 15 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ************************************************************************* ** This file contains C code routines that are called by the parser ** in order to generate code for DELETE FROM statements. */ /* #include "sqliteInt.h" */ /* ** While a SrcList can in general represent multiple tables and subqueries ** (as in the FROM clause of a SELECT statement) in this case it contains ** the name of a single table, as one might find in an INSERT, DELETE, ** or UPDATE statement. Look up that table in the symbol table and ** return a pointer. Set an error message and return NULL if the table ** name is not found or if any other error occurs. ** ** The following fields are initialized appropriate in pSrc: ** ** pSrc->a[0].pTab Pointer to the Table object ** pSrc->a[0].pIndex Pointer to the INDEXED BY index, if there is one ** */ SQLITE_PRIVATE Table *sqlite3SrcListLookup(Parse *pParse, SrcList *pSrc){ struct SrcList_item *pItem = pSrc->a; Table *pTab; assert( pItem && pSrc->nSrc==1 ); pTab = sqlite3LocateTableItem(pParse, 0, pItem); sqlite3DeleteTable(pParse->db, pItem->pTab); pItem->pTab = pTab; if( pTab ){ pTab->nRef++; } if( sqlite3IndexedByLookup(pParse, pItem) ){ pTab = 0; } return pTab; } /* ** Check to make sure the given table is writable. If it is not ** writable, generate an error message and return 1. If it is ** writable return 0; */ SQLITE_PRIVATE int sqlite3IsReadOnly(Parse *pParse, Table *pTab, int viewOk){ /* A table is not writable under the following circumstances: ** ** 1) It is a virtual table and no implementation of the xUpdate method ** has been provided, or ** 2) It is a system table (i.e. sqlite_master), this call is not ** part of a nested parse and writable_schema pragma has not ** been specified. ** ** In either case leave an error message in pParse and return non-zero. */ if( ( IsVirtual(pTab) && sqlite3GetVTable(pParse->db, pTab)->pMod->pModule->xUpdate==0 ) || ( (pTab->tabFlags & TF_Readonly)!=0 && (pParse->db->flags & SQLITE_WriteSchema)==0 && pParse->nested==0 ) ){ sqlite3ErrorMsg(pParse, "table %s may not be modified", pTab->zName); return 1; } #ifndef SQLITE_OMIT_VIEW if( !viewOk && pTab->pSelect ){ sqlite3ErrorMsg(pParse,"cannot modify %s because it is a view",pTab->zName); return 1; } #endif return 0; } #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER) /* ** Evaluate a view and store its result in an ephemeral table. The ** pWhere argument is an optional WHERE clause that restricts the ** set of rows in the view that are to be added to the ephemeral table. */ SQLITE_PRIVATE void sqlite3MaterializeView( Parse *pParse, /* Parsing context */ Table *pView, /* View definition */ Expr *pWhere, /* Optional WHERE clause to be added */ int iCur /* Cursor number for ephemeral table */ ){ SelectDest dest; Select *pSel; SrcList *pFrom; sqlite3 *db = pParse->db; int iDb = sqlite3SchemaToIndex(db, pView->pSchema); pWhere = sqlite3ExprDup(db, pWhere, 0); pFrom = sqlite3SrcListAppend(db, 0, 0, 0); if( pFrom ){ assert( pFrom->nSrc==1 ); pFrom->a[0].zName = sqlite3DbStrDup(db, pView->zName); pFrom->a[0].zDatabase = sqlite3DbStrDup(db, db->aDb[iDb].zDbSName); assert( pFrom->a[0].pOn==0 ); assert( pFrom->a[0].pUsing==0 ); } pSel = sqlite3SelectNew(pParse, 0, pFrom, pWhere, 0, 0, 0, SF_IncludeHidden, 0, 0); sqlite3SelectDestInit(&dest, SRT_EphemTab, iCur); sqlite3Select(pParse, pSel, &dest); sqlite3SelectDelete(db, pSel); } #endif /* !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER) */ #if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY) /* ** Generate an expression tree to implement the WHERE, ORDER BY, ** and LIMIT/OFFSET portion of DELETE and UPDATE statements. ** ** DELETE FROM table_wxyz WHERE a<5 ORDER BY a LIMIT 1; ** \__________________________/ ** pLimitWhere (pInClause) */ SQLITE_PRIVATE Expr *sqlite3LimitWhere( Parse *pParse, /* The parser context */ SrcList *pSrc, /* the FROM clause -- which tables to scan */ Expr *pWhere, /* The WHERE clause. May be null */ ExprList *pOrderBy, /* The ORDER BY clause. May be null */ Expr *pLimit, /* The LIMIT clause. May be null */ Expr *pOffset, /* The OFFSET clause. May be null */ char *zStmtType /* Either DELETE or UPDATE. For err msgs. */ ){ Expr *pWhereRowid = NULL; /* WHERE rowid .. */ Expr *pInClause = NULL; /* WHERE rowid IN ( select ) */ Expr *pSelectRowid = NULL; /* SELECT rowid ... */ ExprList *pEList = NULL; /* Expression list contaning only pSelectRowid */ SrcList *pSelectSrc = NULL; /* SELECT rowid FROM x ... (dup of pSrc) */ Select *pSelect = NULL; /* Complete SELECT tree */ /* Check that there isn't an ORDER BY without a LIMIT clause. */ if( pOrderBy && (pLimit == 0) ) { sqlite3ErrorMsg(pParse, "ORDER BY without LIMIT on %s", zStmtType); goto limit_where_cleanup; } /* We only need to generate a select expression if there ** is a limit/offset term to enforce. */ if( pLimit == 0 ) { /* if pLimit is null, pOffset will always be null as well. */ assert( pOffset == 0 ); return pWhere; } /* Generate a select expression tree to enforce the limit/offset ** term for the DELETE or UPDATE statement. For example: ** DELETE FROM table_a WHERE col1=1 ORDER BY col2 LIMIT 1 OFFSET 1 ** becomes: ** DELETE FROM table_a WHERE rowid IN ( ** SELECT rowid FROM table_a WHERE col1=1 ORDER BY col2 LIMIT 1 OFFSET 1 ** ); */ pSelectRowid = sqlite3PExpr(pParse, TK_ROW, 0, 0, 0); if( pSelectRowid == 0 ) goto limit_where_cleanup; pEList = sqlite3ExprListAppend(pParse, 0, pSelectRowid); if( pEList == 0 ) goto limit_where_cleanup; /* duplicate the FROM clause as it is needed by both the DELETE/UPDATE tree ** and the SELECT subtree. */ pSelectSrc = sqlite3SrcListDup(pParse->db, pSrc, 0); if( pSelectSrc == 0 ) { sqlite3ExprListDelete(pParse->db, pEList); goto limit_where_cleanup; } /* generate the SELECT expression tree. */ pSelect = sqlite3SelectNew(pParse,pEList,pSelectSrc,pWhere,0,0, pOrderBy,0,pLimit,pOffset); if( pSelect == 0 ) return 0; /* now generate the new WHERE rowid IN clause for the DELETE/UDPATE */ pWhereRowid = sqlite3PExpr(pParse, TK_ROW, 0, 0, 0); pInClause = pWhereRowid ? sqlite3PExpr(pParse, TK_IN, pWhereRowid, 0, 0) : 0; sqlite3PExprAddSelect(pParse, pInClause, pSelect); return pInClause; limit_where_cleanup: sqlite3ExprDelete(pParse->db, pWhere); sqlite3ExprListDelete(pParse->db, pOrderBy); sqlite3ExprDelete(pParse->db, pLimit); sqlite3ExprDelete(pParse->db, pOffset); return 0; } #endif /* defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) */ /* && !defined(SQLITE_OMIT_SUBQUERY) */ /* ** Generate code for a DELETE FROM statement. ** ** DELETE FROM table_wxyz WHERE a<5 AND b NOT NULL; ** \________/ \________________/ ** pTabList pWhere */ SQLITE_PRIVATE void sqlite3DeleteFrom( Parse *pParse, /* The parser context */ SrcList *pTabList, /* The table from which we should delete things */ Expr *pWhere /* The WHERE clause. May be null */ ){ Vdbe *v; /* The virtual database engine */ Table *pTab; /* The table from which records will be deleted */ int i; /* Loop counter */ WhereInfo *pWInfo; /* Information about the WHERE clause */ Index *pIdx; /* For looping over indices of the table */ int iTabCur; /* Cursor number for the table */ int iDataCur = 0; /* VDBE cursor for the canonical data source */ int iIdxCur = 0; /* Cursor number of the first index */ int nIdx; /* Number of indices */ sqlite3 *db; /* Main database structure */ AuthContext sContext; /* Authorization context */ NameContext sNC; /* Name context to resolve expressions in */ int iDb; /* Database number */ int memCnt = -1; /* Memory cell used for change counting */ int rcauth; /* Value returned by authorization callback */ int eOnePass; /* ONEPASS_OFF or _SINGLE or _MULTI */ int aiCurOnePass[2]; /* The write cursors opened by WHERE_ONEPASS */ u8 *aToOpen = 0; /* Open cursor iTabCur+j if aToOpen[j] is true */ Index *pPk; /* The PRIMARY KEY index on the table */ int iPk = 0; /* First of nPk registers holding PRIMARY KEY value */ i16 nPk = 1; /* Number of columns in the PRIMARY KEY */ int iKey; /* Memory cell holding key of row to be deleted */ i16 nKey; /* Number of memory cells in the row key */ int iEphCur = 0; /* Ephemeral table holding all primary key values */ int iRowSet = 0; /* Register for rowset of rows to delete */ int addrBypass = 0; /* Address of jump over the delete logic */ int addrLoop = 0; /* Top of the delete loop */ int addrEphOpen = 0; /* Instruction to open the Ephemeral table */ int bComplex; /* True if there are triggers or FKs or ** subqueries in the WHERE clause */ #ifndef SQLITE_OMIT_TRIGGER int isView; /* True if attempting to delete from a view */ Trigger *pTrigger; /* List of table triggers, if required */ #endif memset(&sContext, 0, sizeof(sContext)); db = pParse->db; if( pParse->nErr || db->mallocFailed ){ goto delete_from_cleanup; } assert( pTabList->nSrc==1 ); /* Locate the table which we want to delete. This table has to be ** put in an SrcList structure because some of the subroutines we ** will be calling are designed to work with multiple tables and expect ** an SrcList* parameter instead of just a Table* parameter. */ pTab = sqlite3SrcListLookup(pParse, pTabList); if( pTab==0 ) goto delete_from_cleanup; /* Figure out if we have any triggers and if the table being ** deleted from is a view */ #ifndef SQLITE_OMIT_TRIGGER pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0); isView = pTab->pSelect!=0; bComplex = pTrigger || sqlite3FkRequired(pParse, pTab, 0, 0); #else # define pTrigger 0 # define isView 0 #endif #ifdef SQLITE_OMIT_VIEW # undef isView # define isView 0 #endif /* If pTab is really a view, make sure it has been initialized. */ if( sqlite3ViewGetColumnNames(pParse, pTab) ){ goto delete_from_cleanup; } if( sqlite3IsReadOnly(pParse, pTab, (pTrigger?1:0)) ){ goto delete_from_cleanup; } iDb = sqlite3SchemaToIndex(db, pTab->pSchema); assert( iDbnDb ); rcauth = sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0, db->aDb[iDb].zDbSName); assert( rcauth==SQLITE_OK || rcauth==SQLITE_DENY || rcauth==SQLITE_IGNORE ); if( rcauth==SQLITE_DENY ){ goto delete_from_cleanup; } assert(!isView || pTrigger); /* Assign cursor numbers to the table and all its indices. */ assert( pTabList->nSrc==1 ); iTabCur = pTabList->a[0].iCursor = pParse->nTab++; for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){ pParse->nTab++; } /* Start the view context */ if( isView ){ sqlite3AuthContextPush(pParse, &sContext, pTab->zName); } /* Begin generating code. */ v = sqlite3GetVdbe(pParse); if( v==0 ){ goto delete_from_cleanup; } if( pParse->nested==0 ) sqlite3VdbeCountChanges(v); sqlite3BeginWriteOperation(pParse, 1, iDb); /* If we are trying to delete from a view, realize that view into ** an ephemeral table. */ #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER) if( isView ){ sqlite3MaterializeView(pParse, pTab, pWhere, iTabCur); iDataCur = iIdxCur = iTabCur; } #endif /* Resolve the column names in the WHERE clause. */ memset(&sNC, 0, sizeof(sNC)); sNC.pParse = pParse; sNC.pSrcList = pTabList; if( sqlite3ResolveExprNames(&sNC, pWhere) ){ goto delete_from_cleanup; } /* Initialize the counter of the number of rows deleted, if ** we are counting rows. */ if( db->flags & SQLITE_CountRows ){ memCnt = ++pParse->nMem; sqlite3VdbeAddOp2(v, OP_Integer, 0, memCnt); } #ifndef SQLITE_OMIT_TRUNCATE_OPTIMIZATION /* Special case: A DELETE without a WHERE clause deletes everything. ** It is easier just to erase the whole table. Prior to version 3.6.5, ** this optimization caused the row change count (the value returned by ** API function sqlite3_count_changes) to be set incorrectly. */ if( rcauth==SQLITE_OK && pWhere==0 && !bComplex && !IsVirtual(pTab) #ifdef SQLITE_ENABLE_PREUPDATE_HOOK && db->xPreUpdateCallback==0 #endif ){ assert( !isView ); sqlite3TableLock(pParse, iDb, pTab->tnum, 1, pTab->zName); if( HasRowid(pTab) ){ sqlite3VdbeAddOp4(v, OP_Clear, pTab->tnum, iDb, memCnt, pTab->zName, P4_STATIC); } for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){ assert( pIdx->pSchema==pTab->pSchema ); sqlite3VdbeAddOp2(v, OP_Clear, pIdx->tnum, iDb); } }else #endif /* SQLITE_OMIT_TRUNCATE_OPTIMIZATION */ { u16 wcf = WHERE_ONEPASS_DESIRED|WHERE_DUPLICATES_OK|WHERE_SEEK_TABLE; if( sNC.ncFlags & NC_VarSelect ) bComplex = 1; wcf |= (bComplex ? 0 : WHERE_ONEPASS_MULTIROW); if( HasRowid(pTab) ){ /* For a rowid table, initialize the RowSet to an empty set */ pPk = 0; nPk = 1; iRowSet = ++pParse->nMem; sqlite3VdbeAddOp2(v, OP_Null, 0, iRowSet); }else{ /* For a WITHOUT ROWID table, create an ephemeral table used to ** hold all primary keys for rows to be deleted. */ pPk = sqlite3PrimaryKeyIndex(pTab); assert( pPk!=0 ); nPk = pPk->nKeyCol; iPk = pParse->nMem+1; pParse->nMem += nPk; iEphCur = pParse->nTab++; addrEphOpen = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, iEphCur, nPk); sqlite3VdbeSetP4KeyInfo(pParse, pPk); } /* Construct a query to find the rowid or primary key for every row ** to be deleted, based on the WHERE clause. Set variable eOnePass ** to indicate the strategy used to implement this delete: ** ** ONEPASS_OFF: Two-pass approach - use a FIFO for rowids/PK values. ** ONEPASS_SINGLE: One-pass approach - at most one row deleted. ** ONEPASS_MULTI: One-pass approach - any number of rows may be deleted. */ pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, 0, 0, wcf, iTabCur+1); if( pWInfo==0 ) goto delete_from_cleanup; eOnePass = sqlite3WhereOkOnePass(pWInfo, aiCurOnePass); assert( IsVirtual(pTab)==0 || eOnePass!=ONEPASS_MULTI ); assert( IsVirtual(pTab) || bComplex || eOnePass!=ONEPASS_OFF ); /* Keep track of the number of rows to be deleted */ if( db->flags & SQLITE_CountRows ){ sqlite3VdbeAddOp2(v, OP_AddImm, memCnt, 1); } /* Extract the rowid or primary key for the current row */ if( pPk ){ for(i=0; iaiColumn[i]>=0 ); sqlite3ExprCodeGetColumnOfTable(v, pTab, iTabCur, pPk->aiColumn[i], iPk+i); } iKey = iPk; }else{ iKey = pParse->nMem + 1; iKey = sqlite3ExprCodeGetColumn(pParse, pTab, -1, iTabCur, iKey, 0); if( iKey>pParse->nMem ) pParse->nMem = iKey; } if( eOnePass!=ONEPASS_OFF ){ /* For ONEPASS, no need to store the rowid/primary-key. There is only ** one, so just keep it in its register(s) and fall through to the ** delete code. */ nKey = nPk; /* OP_Found will use an unpacked key */ aToOpen = sqlite3DbMallocRawNN(db, nIdx+2); if( aToOpen==0 ){ sqlite3WhereEnd(pWInfo); goto delete_from_cleanup; } memset(aToOpen, 1, nIdx+1); aToOpen[nIdx+1] = 0; if( aiCurOnePass[0]>=0 ) aToOpen[aiCurOnePass[0]-iTabCur] = 0; if( aiCurOnePass[1]>=0 ) aToOpen[aiCurOnePass[1]-iTabCur] = 0; if( addrEphOpen ) sqlite3VdbeChangeToNoop(v, addrEphOpen); }else{ if( pPk ){ /* Add the PK key for this row to the temporary table */ iKey = ++pParse->nMem; nKey = 0; /* Zero tells OP_Found to use a composite key */ sqlite3VdbeAddOp4(v, OP_MakeRecord, iPk, nPk, iKey, sqlite3IndexAffinityStr(pParse->db, pPk), nPk); sqlite3VdbeAddOp2(v, OP_IdxInsert, iEphCur, iKey); }else{ /* Add the rowid of the row to be deleted to the RowSet */ nKey = 1; /* OP_Seek always uses a single rowid */ sqlite3VdbeAddOp2(v, OP_RowSetAdd, iRowSet, iKey); } } /* If this DELETE cannot use the ONEPASS strategy, this is the ** end of the WHERE loop */ if( eOnePass!=ONEPASS_OFF ){ addrBypass = sqlite3VdbeMakeLabel(v); }else{ sqlite3WhereEnd(pWInfo); } /* Unless this is a view, open cursors for the table we are ** deleting from and all its indices. If this is a view, then the ** only effect this statement has is to fire the INSTEAD OF ** triggers. */ if( !isView ){ int iAddrOnce = 0; if( eOnePass==ONEPASS_MULTI ){ iAddrOnce = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v); } testcase( IsVirtual(pTab) ); sqlite3OpenTableAndIndices(pParse, pTab, OP_OpenWrite, OPFLAG_FORDELETE, iTabCur, aToOpen, &iDataCur, &iIdxCur); assert( pPk || IsVirtual(pTab) || iDataCur==iTabCur ); assert( pPk || IsVirtual(pTab) || iIdxCur==iDataCur+1 ); if( eOnePass==ONEPASS_MULTI ) sqlite3VdbeJumpHere(v, iAddrOnce); } /* Set up a loop over the rowids/primary-keys that were found in the ** where-clause loop above. */ if( eOnePass!=ONEPASS_OFF ){ assert( nKey==nPk ); /* OP_Found will use an unpacked key */ if( !IsVirtual(pTab) && aToOpen[iDataCur-iTabCur] ){ assert( pPk!=0 || pTab->pSelect!=0 ); sqlite3VdbeAddOp4Int(v, OP_NotFound, iDataCur, addrBypass, iKey, nKey); VdbeCoverage(v); } }else if( pPk ){ addrLoop = sqlite3VdbeAddOp1(v, OP_Rewind, iEphCur); VdbeCoverage(v); sqlite3VdbeAddOp2(v, OP_RowKey, iEphCur, iKey); assert( nKey==0 ); /* OP_Found will use a composite key */ }else{ addrLoop = sqlite3VdbeAddOp3(v, OP_RowSetRead, iRowSet, 0, iKey); VdbeCoverage(v); assert( nKey==1 ); } /* Delete the row */ #ifndef SQLITE_OMIT_VIRTUALTABLE if( IsVirtual(pTab) ){ const char *pVTab = (const char *)sqlite3GetVTable(db, pTab); sqlite3VtabMakeWritable(pParse, pTab); sqlite3VdbeAddOp4(v, OP_VUpdate, 0, 1, iKey, pVTab, P4_VTAB); sqlite3VdbeChangeP5(v, OE_Abort); assert( eOnePass==ONEPASS_OFF || eOnePass==ONEPASS_SINGLE ); sqlite3MayAbort(pParse); if( eOnePass==ONEPASS_SINGLE && sqlite3IsToplevel(pParse) ){ pParse->isMultiWrite = 0; } }else #endif { int count = (pParse->nested==0); /* True to count changes */ int iIdxNoSeek = -1; if( bComplex==0 && aiCurOnePass[1]!=iDataCur ){ iIdxNoSeek = aiCurOnePass[1]; } sqlite3GenerateRowDelete(pParse, pTab, pTrigger, iDataCur, iIdxCur, iKey, nKey, count, OE_Default, eOnePass, iIdxNoSeek); } /* End of the loop over all rowids/primary-keys. */ if( eOnePass!=ONEPASS_OFF ){ sqlite3VdbeResolveLabel(v, addrBypass); sqlite3WhereEnd(pWInfo); }else if( pPk ){ sqlite3VdbeAddOp2(v, OP_Next, iEphCur, addrLoop+1); VdbeCoverage(v); sqlite3VdbeJumpHere(v, addrLoop); }else{ sqlite3VdbeGoto(v, addrLoop); sqlite3VdbeJumpHere(v, addrLoop); } /* Close the cursors open on the table and its indexes. */ if( !isView && !IsVirtual(pTab) ){ if( !pPk ) sqlite3VdbeAddOp1(v, OP_Close, iDataCur); for(i=0, pIdx=pTab->pIndex; pIdx; i++, pIdx=pIdx->pNext){ sqlite3VdbeAddOp1(v, OP_Close, iIdxCur + i); } } } /* End non-truncate path */ /* Update the sqlite_sequence table by storing the content of the ** maximum rowid counter values recorded while inserting into ** autoincrement tables. */ if( pParse->nested==0 && pParse->pTriggerTab==0 ){ sqlite3AutoincrementEnd(pParse); } /* Return the number of rows that were deleted. If this routine is ** generating code because of a call to sqlite3NestedParse(), do not ** invoke the callback function. */ if( (db->flags&SQLITE_CountRows) && !pParse->nested && !pParse->pTriggerTab ){ sqlite3VdbeAddOp2(v, OP_ResultRow, memCnt, 1); sqlite3VdbeSetNumCols(v, 1); sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows deleted", SQLITE_STATIC); } delete_from_cleanup: sqlite3AuthContextPop(&sContext); sqlite3SrcListDelete(db, pTabList); sqlite3ExprDelete(db, pWhere); sqlite3DbFree(db, aToOpen); return; } /* Make sure "isView" and other macros defined above are undefined. Otherwise ** they may interfere with compilation of other functions in this file ** (or in another file, if this file becomes part of the amalgamation). */ #ifdef isView #undef isView #endif #ifdef pTrigger #undef pTrigger #endif /* ** This routine generates VDBE code that causes a single row of a ** single table to be deleted. Both the original table entry and ** all indices are removed. ** ** Preconditions: ** ** 1. iDataCur is an open cursor on the btree that is the canonical data ** store for the table. (This will be either the table itself, ** in the case of a rowid table, or the PRIMARY KEY index in the case ** of a WITHOUT ROWID table.) ** ** 2. Read/write cursors for all indices of pTab must be open as ** cursor number iIdxCur+i for the i-th index. ** ** 3. The primary key for the row to be deleted must be stored in a ** sequence of nPk memory cells starting at iPk. If nPk==0 that means ** that a search record formed from OP_MakeRecord is contained in the ** single memory location iPk. ** ** eMode: ** Parameter eMode may be passed either ONEPASS_OFF (0), ONEPASS_SINGLE, or ** ONEPASS_MULTI. If eMode is not ONEPASS_OFF, then the cursor ** iDataCur already points to the row to delete. If eMode is ONEPASS_OFF ** then this function must seek iDataCur to the entry identified by iPk ** and nPk before reading from it. ** ** If eMode is ONEPASS_MULTI, then this call is being made as part ** of a ONEPASS delete that affects multiple rows. In this case, if ** iIdxNoSeek is a valid cursor number (>=0), then its position should ** be preserved following the delete operation. Or, if iIdxNoSeek is not ** a valid cursor number, the position of iDataCur should be preserved ** instead. ** ** iIdxNoSeek: ** If iIdxNoSeek is a valid cursor number (>=0), then it identifies an ** index cursor (from within array of cursors starting at iIdxCur) that ** already points to the index entry to be deleted. */ SQLITE_PRIVATE void sqlite3GenerateRowDelete( Parse *pParse, /* Parsing context */ Table *pTab, /* Table containing the row to be deleted */ Trigger *pTrigger, /* List of triggers to (potentially) fire */ int iDataCur, /* Cursor from which column data is extracted */ int iIdxCur, /* First index cursor */ int iPk, /* First memory cell containing the PRIMARY KEY */ i16 nPk, /* Number of PRIMARY KEY memory cells */ u8 count, /* If non-zero, increment the row change counter */ u8 onconf, /* Default ON CONFLICT policy for triggers */ u8 eMode, /* ONEPASS_OFF, _SINGLE, or _MULTI. See above */ int iIdxNoSeek /* Cursor number of cursor that does not need seeking */ ){ Vdbe *v = pParse->pVdbe; /* Vdbe */ int iOld = 0; /* First register in OLD.* array */ int iLabel; /* Label resolved to end of generated code */ u8 opSeek; /* Seek opcode */ /* Vdbe is guaranteed to have been allocated by this stage. */ assert( v ); VdbeModuleComment((v, "BEGIN: GenRowDel(%d,%d,%d,%d)", iDataCur, iIdxCur, iPk, (int)nPk)); /* Seek cursor iCur to the row to delete. If this row no longer exists ** (this can happen if a trigger program has already deleted it), do ** not attempt to delete it or fire any DELETE triggers. */ iLabel = sqlite3VdbeMakeLabel(v); opSeek = HasRowid(pTab) ? OP_NotExists : OP_NotFound; if( eMode==ONEPASS_OFF ){ sqlite3VdbeAddOp4Int(v, opSeek, iDataCur, iLabel, iPk, nPk); VdbeCoverageIf(v, opSeek==OP_NotExists); VdbeCoverageIf(v, opSeek==OP_NotFound); } /* If there are any triggers to fire, allocate a range of registers to ** use for the old.* references in the triggers. */ if( sqlite3FkRequired(pParse, pTab, 0, 0) || pTrigger ){ u32 mask; /* Mask of OLD.* columns in use */ int iCol; /* Iterator used while populating OLD.* */ int addrStart; /* Start of BEFORE trigger programs */ /* TODO: Could use temporary registers here. Also could attempt to ** avoid copying the contents of the rowid register. */ mask = sqlite3TriggerColmask( pParse, pTrigger, 0, 0, TRIGGER_BEFORE|TRIGGER_AFTER, pTab, onconf ); mask |= sqlite3FkOldmask(pParse, pTab); iOld = pParse->nMem+1; pParse->nMem += (1 + pTab->nCol); /* Populate the OLD.* pseudo-table register array. These values will be ** used by any BEFORE and AFTER triggers that exist. */ sqlite3VdbeAddOp2(v, OP_Copy, iPk, iOld); for(iCol=0; iColnCol; iCol++){ testcase( mask!=0xffffffff && iCol==31 ); testcase( mask!=0xffffffff && iCol==32 ); if( mask==0xffffffff || (iCol<=31 && (mask & MASKBIT32(iCol))!=0) ){ sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, iCol, iOld+iCol+1); } } /* Invoke BEFORE DELETE trigger programs. */ addrStart = sqlite3VdbeCurrentAddr(v); sqlite3CodeRowTrigger(pParse, pTrigger, TK_DELETE, 0, TRIGGER_BEFORE, pTab, iOld, onconf, iLabel ); /* If any BEFORE triggers were coded, then seek the cursor to the ** row to be deleted again. It may be that the BEFORE triggers moved ** the cursor or of already deleted the row that the cursor was ** pointing to. */ if( addrStartpSelect==0 ){ u8 p5 = 0; sqlite3GenerateRowIndexDelete(pParse, pTab, iDataCur, iIdxCur,0,iIdxNoSeek); sqlite3VdbeAddOp2(v, OP_Delete, iDataCur, (count?OPFLAG_NCHANGE:0)); sqlite3VdbeChangeP4(v, -1, (char*)pTab, P4_TABLE); if( eMode!=ONEPASS_OFF ){ sqlite3VdbeChangeP5(v, OPFLAG_AUXDELETE); } if( iIdxNoSeek>=0 ){ sqlite3VdbeAddOp1(v, OP_Delete, iIdxNoSeek); } if( eMode==ONEPASS_MULTI ) p5 |= OPFLAG_SAVEPOSITION; sqlite3VdbeChangeP5(v, p5); } /* Do any ON CASCADE, SET NULL or SET DEFAULT operations required to ** handle rows (possibly in other tables) that refer via a foreign key ** to the row just deleted. */ sqlite3FkActions(pParse, pTab, 0, iOld, 0, 0); /* Invoke AFTER DELETE trigger programs. */ sqlite3CodeRowTrigger(pParse, pTrigger, TK_DELETE, 0, TRIGGER_AFTER, pTab, iOld, onconf, iLabel ); /* Jump here if the row had already been deleted before any BEFORE ** trigger programs were invoked. Or if a trigger program throws a ** RAISE(IGNORE) exception. */ sqlite3VdbeResolveLabel(v, iLabel); VdbeModuleComment((v, "END: GenRowDel()")); } /* ** This routine generates VDBE code that causes the deletion of all ** index entries associated with a single row of a single table, pTab ** ** Preconditions: ** ** 1. A read/write cursor "iDataCur" must be open on the canonical storage ** btree for the table pTab. (This will be either the table itself ** for rowid tables or to the primary key index for WITHOUT ROWID ** tables.) ** ** 2. Read/write cursors for all indices of pTab must be open as ** cursor number iIdxCur+i for the i-th index. (The pTab->pIndex ** index is the 0-th index.) ** ** 3. The "iDataCur" cursor must be already be positioned on the row ** that is to be deleted. */ SQLITE_PRIVATE void sqlite3GenerateRowIndexDelete( Parse *pParse, /* Parsing and code generating context */ Table *pTab, /* Table containing the row to be deleted */ int iDataCur, /* Cursor of table holding data. */ int iIdxCur, /* First index cursor */ int *aRegIdx, /* Only delete if aRegIdx!=0 && aRegIdx[i]>0 */ int iIdxNoSeek /* Do not delete from this cursor */ ){ int i; /* Index loop counter */ int r1 = -1; /* Register holding an index key */ int iPartIdxLabel; /* Jump destination for skipping partial index entries */ Index *pIdx; /* Current index */ Index *pPrior = 0; /* Prior index */ Vdbe *v; /* The prepared statement under construction */ Index *pPk; /* PRIMARY KEY index, or NULL for rowid tables */ v = pParse->pVdbe; pPk = HasRowid(pTab) ? 0 : sqlite3PrimaryKeyIndex(pTab); for(i=0, pIdx=pTab->pIndex; pIdx; i++, pIdx=pIdx->pNext){ assert( iIdxCur+i!=iDataCur || pPk==pIdx ); if( aRegIdx!=0 && aRegIdx[i]==0 ) continue; if( pIdx==pPk ) continue; if( iIdxCur+i==iIdxNoSeek ) continue; VdbeModuleComment((v, "GenRowIdxDel for %s", pIdx->zName)); r1 = sqlite3GenerateIndexKey(pParse, pIdx, iDataCur, 0, 1, &iPartIdxLabel, pPrior, r1); sqlite3VdbeAddOp3(v, OP_IdxDelete, iIdxCur+i, r1, pIdx->uniqNotNull ? pIdx->nKeyCol : pIdx->nColumn); sqlite3ResolvePartIdxLabel(pParse, iPartIdxLabel); pPrior = pIdx; } } /* ** Generate code that will assemble an index key and stores it in register ** regOut. The key with be for index pIdx which is an index on pTab. ** iCur is the index of a cursor open on the pTab table and pointing to ** the entry that needs indexing. If pTab is a WITHOUT ROWID table, then ** iCur must be the cursor of the PRIMARY KEY index. ** ** Return a register number which is the first in a block of ** registers that holds the elements of the index key. The ** block of registers has already been deallocated by the time ** this routine returns. ** ** If *piPartIdxLabel is not NULL, fill it in with a label and jump ** to that label if pIdx is a partial index that should be skipped. ** The label should be resolved using sqlite3ResolvePartIdxLabel(). ** A partial index should be skipped if its WHERE clause evaluates ** to false or null. If pIdx is not a partial index, *piPartIdxLabel ** will be set to zero which is an empty label that is ignored by ** sqlite3ResolvePartIdxLabel(). ** ** The pPrior and regPrior parameters are used to implement a cache to ** avoid unnecessary register loads. If pPrior is not NULL, then it is ** a pointer to a different index for which an index key has just been ** computed into register regPrior. If the current pIdx index is generating ** its key into the same sequence of registers and if pPrior and pIdx share ** a column in common, then the register corresponding to that column already ** holds the correct value and the loading of that register is skipped. ** This optimization is helpful when doing a DELETE or an INTEGRITY_CHECK ** on a table with multiple indices, and especially with the ROWID or ** PRIMARY KEY columns of the index. */ SQLITE_PRIVATE int sqlite3GenerateIndexKey( Parse *pParse, /* Parsing context */ Index *pIdx, /* The index for which to generate a key */ int iDataCur, /* Cursor number from which to take column data */ int regOut, /* Put the new key into this register if not 0 */ int prefixOnly, /* Compute only a unique prefix of the key */ int *piPartIdxLabel, /* OUT: Jump to this label to skip partial index */ Index *pPrior, /* Previously generated index key */ int regPrior /* Register holding previous generated key */ ){ Vdbe *v = pParse->pVdbe; int j; int regBase; int nCol; if( piPartIdxLabel ){ if( pIdx->pPartIdxWhere ){ *piPartIdxLabel = sqlite3VdbeMakeLabel(v); pParse->iSelfTab = iDataCur; sqlite3ExprCachePush(pParse); sqlite3ExprIfFalseDup(pParse, pIdx->pPartIdxWhere, *piPartIdxLabel, SQLITE_JUMPIFNULL); }else{ *piPartIdxLabel = 0; } } nCol = (prefixOnly && pIdx->uniqNotNull) ? pIdx->nKeyCol : pIdx->nColumn; regBase = sqlite3GetTempRange(pParse, nCol); if( pPrior && (regBase!=regPrior || pPrior->pPartIdxWhere) ) pPrior = 0; for(j=0; jaiColumn[j]==pIdx->aiColumn[j] && pPrior->aiColumn[j]!=XN_EXPR ){ /* This column was already computed by the previous index */ continue; } sqlite3ExprCodeLoadIndexColumn(pParse, pIdx, iDataCur, j, regBase+j); /* If the column affinity is REAL but the number is an integer, then it ** might be stored in the table as an integer (using a compact ** representation) then converted to REAL by an OP_RealAffinity opcode. ** But we are getting ready to store this value back into an index, where ** it should be converted by to INTEGER again. So omit the OP_RealAffinity ** opcode if it is present */ sqlite3VdbeDeletePriorOpcode(v, OP_RealAffinity); } if( regOut ){ sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nCol, regOut); } sqlite3ReleaseTempRange(pParse, regBase, nCol); return regBase; } /* ** If a prior call to sqlite3GenerateIndexKey() generated a jump-over label ** because it was a partial index, then this routine should be called to ** resolve that label. */ SQLITE_PRIVATE void sqlite3ResolvePartIdxLabel(Parse *pParse, int iLabel){ if( iLabel ){ sqlite3VdbeResolveLabel(pParse->pVdbe, iLabel); sqlite3ExprCachePop(pParse); } } /************** End of delete.c **********************************************/ /************** Begin file func.c ********************************************/ /* ** 2002 February 23 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ************************************************************************* ** This file contains the C-language implementations for many of the SQL ** functions of SQLite. (Some function, and in particular the date and ** time functions, are implemented separately.) */ /* #include "sqliteInt.h" */ /* #include */ /* #include */ /* #include "vdbeInt.h" */ /* ** Return the collating function associated with a function. */ static CollSeq *sqlite3GetFuncCollSeq(sqlite3_context *context){ VdbeOp *pOp; assert( context->pVdbe!=0 ); pOp = &context->pVdbe->aOp[context->iOp-1]; assert( pOp->opcode==OP_CollSeq ); assert( pOp->p4type==P4_COLLSEQ ); return pOp->p4.pColl; } /* ** Indicate that the accumulator load should be skipped on this ** iteration of the aggregate loop. */ static void sqlite3SkipAccumulatorLoad(sqlite3_context *context){ context->skipFlag = 1; } /* ** Implementation of the non-aggregate min() and max() functions */ static void minmaxFunc( sqlite3_context *context, int argc, sqlite3_value **argv ){ int i; int mask; /* 0 for min() or 0xffffffff for max() */ int iBest; CollSeq *pColl; assert( argc>1 ); mask = sqlite3_user_data(context)==0 ? 0 : -1; pColl = sqlite3GetFuncCollSeq(context); assert( pColl ); assert( mask==-1 || mask==0 ); iBest = 0; if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return; for(i=1; i=0 ){ testcase( mask==0 ); iBest = i; } } sqlite3_result_value(context, argv[iBest]); } /* ** Return the type of the argument. */ static void typeofFunc( sqlite3_context *context, int NotUsed, sqlite3_value **argv ){ const char *z = 0; UNUSED_PARAMETER(NotUsed); switch( sqlite3_value_type(argv[0]) ){ case SQLITE_INTEGER: z = "integer"; break; case SQLITE_TEXT: z = "text"; break; case SQLITE_FLOAT: z = "real"; break; case SQLITE_BLOB: z = "blob"; break; default: z = "null"; break; } sqlite3_result_text(context, z, -1, SQLITE_STATIC); } /* ** Implementation of the length() function */ static void lengthFunc( sqlite3_context *context, int argc, sqlite3_value **argv ){ int len; assert( argc==1 ); UNUSED_PARAMETER(argc); switch( sqlite3_value_type(argv[0]) ){ case SQLITE_BLOB: case SQLITE_INTEGER: case SQLITE_FLOAT: { sqlite3_result_int(context, sqlite3_value_bytes(argv[0])); break; } case SQLITE_TEXT: { const unsigned char *z = sqlite3_value_text(argv[0]); if( z==0 ) return; len = 0; while( *z ){ len++; SQLITE_SKIP_UTF8(z); } sqlite3_result_int(context, len); break; } default: { sqlite3_result_null(context); break; } } } /* ** Implementation of the abs() function. ** ** IMP: R-23979-26855 The abs(X) function returns the absolute value of ** the numeric argument X. */ static void absFunc(sqlite3_context *context, int argc, sqlite3_value **argv){ assert( argc==1 ); UNUSED_PARAMETER(argc); switch( sqlite3_value_type(argv[0]) ){ case SQLITE_INTEGER: { i64 iVal = sqlite3_value_int64(argv[0]); if( iVal<0 ){ if( iVal==SMALLEST_INT64 ){ /* IMP: R-31676-45509 If X is the integer -9223372036854775808 ** then abs(X) throws an integer overflow error since there is no ** equivalent positive 64-bit two complement value. */ sqlite3_result_error(context, "integer overflow", -1); return; } iVal = -iVal; } sqlite3_result_int64(context, iVal); break; } case SQLITE_NULL: { /* IMP: R-37434-19929 Abs(X) returns NULL if X is NULL. */ sqlite3_result_null(context); break; } default: { /* Because sqlite3_value_double() returns 0.0 if the argument is not ** something that can be converted into a number, we have: ** IMP: R-01992-00519 Abs(X) returns 0.0 if X is a string or blob ** that cannot be converted to a numeric value. */ double rVal = sqlite3_value_double(argv[0]); if( rVal<0 ) rVal = -rVal; sqlite3_result_double(context, rVal); break; } } } /* ** Implementation of the instr() function. ** ** instr(haystack,needle) finds the first occurrence of needle ** in haystack and returns the number of previous characters plus 1, ** or 0 if needle does not occur within haystack. ** ** If both haystack and needle are BLOBs, then the result is one more than ** the number of bytes in haystack prior to the first occurrence of needle, ** or 0 if needle never occurs in haystack. */ static void instrFunc( sqlite3_context *context, int argc, sqlite3_value **argv ){ const unsigned char *zHaystack; const unsigned char *zNeedle; int nHaystack; int nNeedle; int typeHaystack, typeNeedle; int N = 1; int isText; UNUSED_PARAMETER(argc); typeHaystack = sqlite3_value_type(argv[0]); typeNeedle = sqlite3_value_type(argv[1]); if( typeHaystack==SQLITE_NULL || typeNeedle==SQLITE_NULL ) return; nHaystack = sqlite3_value_bytes(argv[0]); nNeedle = sqlite3_value_bytes(argv[1]); if( typeHaystack==SQLITE_BLOB && typeNeedle==SQLITE_BLOB ){ zHaystack = sqlite3_value_blob(argv[0]); zNeedle = sqlite3_value_blob(argv[1]); isText = 0; }else{ zHaystack = sqlite3_value_text(argv[0]); zNeedle = sqlite3_value_text(argv[1]); isText = 1; } while( nNeedle<=nHaystack && memcmp(zHaystack, zNeedle, nNeedle)!=0 ){ N++; do{ nHaystack--; zHaystack++; }while( isText && (zHaystack[0]&0xc0)==0x80 ); } if( nNeedle>nHaystack ) N = 0; sqlite3_result_int(context, N); } /* ** Implementation of the printf() function. */ static void printfFunc( sqlite3_context *context, int argc, sqlite3_value **argv ){ PrintfArguments x; StrAccum str; const char *zFormat; int n; sqlite3 *db = sqlite3_context_db_handle(context); if( argc>=1 && (zFormat = (const char*)sqlite3_value_text(argv[0]))!=0 ){ x.nArg = argc-1; x.nUsed = 0; x.apArg = argv+1; sqlite3StrAccumInit(&str, db, 0, 0, db->aLimit[SQLITE_LIMIT_LENGTH]); str.printfFlags = SQLITE_PRINTF_SQLFUNC; sqlite3XPrintf(&str, zFormat, &x); n = str.nChar; sqlite3_result_text(context, sqlite3StrAccumFinish(&str), n, SQLITE_DYNAMIC); } } /* ** Implementation of the substr() function. ** ** substr(x,p1,p2) returns p2 characters of x[] beginning with p1. ** p1 is 1-indexed. So substr(x,1,1) returns the first character ** of x. If x is text, then we actually count UTF-8 characters. ** If x is a blob, then we count bytes. ** ** If p1 is negative, then we begin abs(p1) from the end of x[]. ** ** If p2 is negative, return the p2 characters preceding p1. */ static void substrFunc( sqlite3_context *context, int argc, sqlite3_value **argv ){ const unsigned char *z; const unsigned char *z2; int len; int p0type; i64 p1, p2; int negP2 = 0; assert( argc==3 || argc==2 ); if( sqlite3_value_type(argv[1])==SQLITE_NULL || (argc==3 && sqlite3_value_type(argv[2])==SQLITE_NULL) ){ return; } p0type = sqlite3_value_type(argv[0]); p1 = sqlite3_value_int(argv[1]); if( p0type==SQLITE_BLOB ){ len = sqlite3_value_bytes(argv[0]); z = sqlite3_value_blob(argv[0]); if( z==0 ) return; assert( len==sqlite3_value_bytes(argv[0]) ); }else{ z = sqlite3_value_text(argv[0]); if( z==0 ) return; len = 0; if( p1<0 ){ for(z2=z; *z2; len++){ SQLITE_SKIP_UTF8(z2); } } } #ifdef SQLITE_SUBSTR_COMPATIBILITY /* If SUBSTR_COMPATIBILITY is defined then substr(X,0,N) work the same as ** as substr(X,1,N) - it returns the first N characters of X. This ** is essentially a back-out of the bug-fix in check-in [5fc125d362df4b8] ** from 2009-02-02 for compatibility of applications that exploited the ** old buggy behavior. */ if( p1==0 ) p1 = 1; /* */ #endif if( argc==3 ){ p2 = sqlite3_value_int(argv[2]); if( p2<0 ){ p2 = -p2; negP2 = 1; } }else{ p2 = sqlite3_context_db_handle(context)->aLimit[SQLITE_LIMIT_LENGTH]; } if( p1<0 ){ p1 += len; if( p1<0 ){ p2 += p1; if( p2<0 ) p2 = 0; p1 = 0; } }else if( p1>0 ){ p1--; }else if( p2>0 ){ p2--; } if( negP2 ){ p1 -= p2; if( p1<0 ){ p2 += p1; p1 = 0; } } assert( p1>=0 && p2>=0 ); if( p0type!=SQLITE_BLOB ){ while( *z && p1 ){ SQLITE_SKIP_UTF8(z); p1--; } for(z2=z; *z2 && p2; p2--){ SQLITE_SKIP_UTF8(z2); } sqlite3_result_text64(context, (char*)z, z2-z, SQLITE_TRANSIENT, SQLITE_UTF8); }else{ if( p1+p2>len ){ p2 = len-p1; if( p2<0 ) p2 = 0; } sqlite3_result_blob64(context, (char*)&z[p1], (u64)p2, SQLITE_TRANSIENT); } } /* ** Implementation of the round() function */ #ifndef SQLITE_OMIT_FLOATING_POINT static void roundFunc(sqlite3_context *context, int argc, sqlite3_value **argv){ int n = 0; double r; char *zBuf; assert( argc==1 || argc==2 ); if( argc==2 ){ if( SQLITE_NULL==sqlite3_value_type(argv[1]) ) return; n = sqlite3_value_int(argv[1]); if( n>30 ) n = 30; if( n<0 ) n = 0; } if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return; r = sqlite3_value_double(argv[0]); /* If Y==0 and X will fit in a 64-bit int, ** handle the rounding directly, ** otherwise use printf. */ if( n==0 && r>=0 && r0 ); testcase( nByte==db->aLimit[SQLITE_LIMIT_LENGTH] ); testcase( nByte==db->aLimit[SQLITE_LIMIT_LENGTH]+1 ); if( nByte>db->aLimit[SQLITE_LIMIT_LENGTH] ){ sqlite3_result_error_toobig(context); z = 0; }else{ z = sqlite3Malloc(nByte); if( !z ){ sqlite3_result_error_nomem(context); } } return z; } /* ** Implementation of the upper() and lower() SQL functions. */ static void upperFunc(sqlite3_context *context, int argc, sqlite3_value **argv){ char *z1; const char *z2; int i, n; UNUSED_PARAMETER(argc); z2 = (char*)sqlite3_value_text(argv[0]); n = sqlite3_value_bytes(argv[0]); /* Verify that the call to _bytes() does not invalidate the _text() pointer */ assert( z2==(char*)sqlite3_value_text(argv[0]) ); if( z2 ){ z1 = contextMalloc(context, ((i64)n)+1); if( z1 ){ for(i=0; imatchOne; /* "?" or "_" */ u32 matchAll = pInfo->matchAll; /* "*" or "%" */ u8 noCase = pInfo->noCase; /* True if uppercase==lowercase */ const u8 *zEscaped = 0; /* One past the last escaped input char */ while( (c = Utf8Read(zPattern))!=0 ){ if( c==matchAll ){ /* Match "*" */ /* Skip over multiple "*" characters in the pattern. If there ** are also "?" characters, skip those as well, but consume a ** single character of the input string for each "?" skipped */ while( (c=Utf8Read(zPattern)) == matchAll || c == matchOne ){ if( c==matchOne && sqlite3Utf8Read(&zString)==0 ){ return 0; } } if( c==0 ){ return 1; /* "*" at the end of the pattern matches */ }else if( c==matchOther ){ if( pInfo->matchSet==0 ){ c = sqlite3Utf8Read(&zPattern); if( c==0 ) return 0; }else{ /* "[...]" immediately follows the "*". We have to do a slow ** recursive search in this case, but it is an unusual case. */ assert( matchOther<0x80 ); /* '[' is a single-byte character */ while( *zString && patternCompare(&zPattern[-1],zString,pInfo,matchOther)==0 ){ SQLITE_SKIP_UTF8(zString); } return *zString!=0; } } /* At this point variable c contains the first character of the ** pattern string past the "*". Search in the input string for the ** first matching character and recursively contine the match from ** that point. ** ** For a case-insensitive search, set variable cx to be the same as ** c but in the other case and search the input string for either ** c or cx. */ if( c<=0x80 ){ u32 cx; if( noCase ){ cx = sqlite3Toupper(c); c = sqlite3Tolower(c); }else{ cx = c; } while( (c2 = *(zString++))!=0 ){ if( c2!=c && c2!=cx ) continue; if( patternCompare(zPattern,zString,pInfo,matchOther) ) return 1; } }else{ while( (c2 = Utf8Read(zString))!=0 ){ if( c2!=c ) continue; if( patternCompare(zPattern,zString,pInfo,matchOther) ) return 1; } } return 0; } if( c==matchOther ){ if( pInfo->matchSet==0 ){ c = sqlite3Utf8Read(&zPattern); if( c==0 ) return 0; zEscaped = zPattern; }else{ u32 prior_c = 0; int seen = 0; int invert = 0; c = sqlite3Utf8Read(&zString); if( c==0 ) return 0; c2 = sqlite3Utf8Read(&zPattern); if( c2=='^' ){ invert = 1; c2 = sqlite3Utf8Read(&zPattern); } if( c2==']' ){ if( c==']' ) seen = 1; c2 = sqlite3Utf8Read(&zPattern); } while( c2 && c2!=']' ){ if( c2=='-' && zPattern[0]!=']' && zPattern[0]!=0 && prior_c>0 ){ c2 = sqlite3Utf8Read(&zPattern); if( c>=prior_c && c<=c2 ) seen = 1; prior_c = 0; }else{ if( c==c2 ){ seen = 1; } prior_c = c2; } c2 = sqlite3Utf8Read(&zPattern); } if( c2==0 || (seen ^ invert)==0 ){ return 0; } continue; } } c2 = Utf8Read(zString); if( c==c2 ) continue; if( noCase && sqlite3Tolower(c)==sqlite3Tolower(c2) && c<0x80 && c2<0x80 ){ continue; } if( c==matchOne && zPattern!=zEscaped && c2!=0 ) continue; return 0; } return *zString==0; } /* ** The sqlite3_strglob() interface. */ SQLITE_API int sqlite3_strglob(const char *zGlobPattern, const char *zString){ return patternCompare((u8*)zGlobPattern, (u8*)zString, &globInfo, '[')==0; } /* ** The sqlite3_strlike() interface. */ SQLITE_API int sqlite3_strlike(const char *zPattern, const char *zStr, unsigned int esc){ return patternCompare((u8*)zPattern, (u8*)zStr, &likeInfoNorm, esc)==0; } /* ** Count the number of times that the LIKE operator (or GLOB which is ** just a variation of LIKE) gets called. This is used for testing ** only. */ #ifdef SQLITE_TEST SQLITE_API int sqlite3_like_count = 0; #endif /* ** Implementation of the like() SQL function. This function implements ** the build-in LIKE operator. The first argument to the function is the ** pattern and the second argument is the string. So, the SQL statements: ** ** A LIKE B ** ** is implemented as like(B,A). ** ** This same function (with a different compareInfo structure) computes ** the GLOB operator. */ static void likeFunc( sqlite3_context *context, int argc, sqlite3_value **argv ){ const unsigned char *zA, *zB; u32 escape; int nPat; sqlite3 *db = sqlite3_context_db_handle(context); struct compareInfo *pInfo = sqlite3_user_data(context); #ifdef SQLITE_LIKE_DOESNT_MATCH_BLOBS if( sqlite3_value_type(argv[0])==SQLITE_BLOB || sqlite3_value_type(argv[1])==SQLITE_BLOB ){ #ifdef SQLITE_TEST sqlite3_like_count++; #endif sqlite3_result_int(context, 0); return; } #endif zB = sqlite3_value_text(argv[0]); zA = sqlite3_value_text(argv[1]); /* Limit the length of the LIKE or GLOB pattern to avoid problems ** of deep recursion and N*N behavior in patternCompare(). */ nPat = sqlite3_value_bytes(argv[0]); testcase( nPat==db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH] ); testcase( nPat==db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH]+1 ); if( nPat > db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH] ){ sqlite3_result_error(context, "LIKE or GLOB pattern too complex", -1); return; } assert( zB==sqlite3_value_text(argv[0]) ); /* Encoding did not change */ if( argc==3 ){ /* The escape character string must consist of a single UTF-8 character. ** Otherwise, return an error. */ const unsigned char *zEsc = sqlite3_value_text(argv[2]); if( zEsc==0 ) return; if( sqlite3Utf8CharLen((char*)zEsc, -1)!=1 ){ sqlite3_result_error(context, "ESCAPE expression must be a single character", -1); return; } escape = sqlite3Utf8Read(&zEsc); }else{ escape = pInfo->matchSet; } if( zA && zB ){ #ifdef SQLITE_TEST sqlite3_like_count++; #endif sqlite3_result_int(context, patternCompare(zB, zA, pInfo, escape)); } } /* ** Implementation of the NULLIF(x,y) function. The result is the first ** argument if the arguments are different. The result is NULL if the ** arguments are equal to each other. */ static void nullifFunc( sqlite3_context *context, int NotUsed, sqlite3_value **argv ){ CollSeq *pColl = sqlite3GetFuncCollSeq(context); UNUSED_PARAMETER(NotUsed); if( sqlite3MemCompare(argv[0], argv[1], pColl)!=0 ){ sqlite3_result_value(context, argv[0]); } } /* ** Implementation of the sqlite_version() function. The result is the version ** of the SQLite library that is running. */ static void versionFunc( sqlite3_context *context, int NotUsed, sqlite3_value **NotUsed2 ){ UNUSED_PARAMETER2(NotUsed, NotUsed2); /* IMP: R-48699-48617 This function is an SQL wrapper around the ** sqlite3_libversion() C-interface. */ sqlite3_result_text(context, sqlite3_libversion(), -1, SQLITE_STATIC); } /* ** Implementation of the sqlite_source_id() function. The result is a string ** that identifies the particular version of the source code used to build ** SQLite. */ static void sourceidFunc( sqlite3_context *context, int NotUsed, sqlite3_value **NotUsed2 ){ UNUSED_PARAMETER2(NotUsed, NotUsed2); /* IMP: R-24470-31136 This function is an SQL wrapper around the ** sqlite3_sourceid() C interface. */ sqlite3_result_text(context, sqlite3_sourceid(), -1, SQLITE_STATIC); } /* ** Implementation of the sqlite_log() function. This is a wrapper around ** sqlite3_log(). The return value is NULL. The function exists purely for ** its side-effects. */ static void errlogFunc( sqlite3_context *context, int argc, sqlite3_value **argv ){ UNUSED_PARAMETER(argc); UNUSED_PARAMETER(context); sqlite3_log(sqlite3_value_int(argv[0]), "%s", sqlite3_value_text(argv[1])); } /* ** Implementation of the sqlite_compileoption_used() function. ** The result is an integer that identifies if the compiler option ** was used to build SQLite. */ #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS static void compileoptionusedFunc( sqlite3_context *context, int argc, sqlite3_value **argv ){ const char *zOptName; assert( argc==1 ); UNUSED_PARAMETER(argc); /* IMP: R-39564-36305 The sqlite_compileoption_used() SQL ** function is a wrapper around the sqlite3_compileoption_used() C/C++ ** function. */ if( (zOptName = (const char*)sqlite3_value_text(argv[0]))!=0 ){ sqlite3_result_int(context, sqlite3_compileoption_used(zOptName)); } } #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */ /* ** Implementation of the sqlite_compileoption_get() function. ** The result is a string that identifies the compiler options ** used to build SQLite. */ #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS static void compileoptiongetFunc( sqlite3_context *context, int argc, sqlite3_value **argv ){ int n; assert( argc==1 ); UNUSED_PARAMETER(argc); /* IMP: R-04922-24076 The sqlite_compileoption_get() SQL function ** is a wrapper around the sqlite3_compileoption_get() C/C++ function. */ n = sqlite3_value_int(argv[0]); sqlite3_result_text(context, sqlite3_compileoption_get(n), -1, SQLITE_STATIC); } #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */ /* Array for converting from half-bytes (nybbles) into ASCII hex ** digits. */ static const char hexdigits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' }; /* ** Implementation of the QUOTE() function. This function takes a single ** argument. If the argument is numeric, the return value is the same as ** the argument. If the argument is NULL, the return value is the string ** "NULL". Otherwise, the argument is enclosed in single quotes with ** single-quote escapes. */ static void quoteFunc(sqlite3_context *context, int argc, sqlite3_value **argv){ assert( argc==1 ); UNUSED_PARAMETER(argc); switch( sqlite3_value_type(argv[0]) ){ case SQLITE_FLOAT: { double r1, r2; char zBuf[50]; r1 = sqlite3_value_double(argv[0]); sqlite3_snprintf(sizeof(zBuf), zBuf, "%!.15g", r1); sqlite3AtoF(zBuf, &r2, 20, SQLITE_UTF8); if( r1!=r2 ){ sqlite3_snprintf(sizeof(zBuf), zBuf, "%!.20e", r1); } sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT); break; } case SQLITE_INTEGER: { sqlite3_result_value(context, argv[0]); break; } case SQLITE_BLOB: { char *zText = 0; char const *zBlob = sqlite3_value_blob(argv[0]); int nBlob = sqlite3_value_bytes(argv[0]); assert( zBlob==sqlite3_value_blob(argv[0]) ); /* No encoding change */ zText = (char *)contextMalloc(context, (2*(i64)nBlob)+4); if( zText ){ int i; for(i=0; i>4)&0x0F]; zText[(i*2)+3] = hexdigits[(zBlob[i])&0x0F]; } zText[(nBlob*2)+2] = '\''; zText[(nBlob*2)+3] = '\0'; zText[0] = 'X'; zText[1] = '\''; sqlite3_result_text(context, zText, -1, SQLITE_TRANSIENT); sqlite3_free(zText); } break; } case SQLITE_TEXT: { int i,j; u64 n; const unsigned char *zArg = sqlite3_value_text(argv[0]); char *z; if( zArg==0 ) return; for(i=0, n=0; zArg[i]; i++){ if( zArg[i]=='\'' ) n++; } z = contextMalloc(context, ((i64)i)+((i64)n)+3); if( z ){ z[0] = '\''; for(i=0, j=1; zArg[i]; i++){ z[j++] = zArg[i]; if( zArg[i]=='\'' ){ z[j++] = '\''; } } z[j++] = '\''; z[j] = 0; sqlite3_result_text(context, z, j, sqlite3_free); } break; } default: { assert( sqlite3_value_type(argv[0])==SQLITE_NULL ); sqlite3_result_text(context, "NULL", 4, SQLITE_STATIC); break; } } } /* ** The unicode() function. Return the integer unicode code-point value ** for the first character of the input string. */ static void unicodeFunc( sqlite3_context *context, int argc, sqlite3_value **argv ){ const unsigned char *z = sqlite3_value_text(argv[0]); (void)argc; if( z && z[0] ) sqlite3_result_int(context, sqlite3Utf8Read(&z)); } /* ** The char() function takes zero or more arguments, each of which is ** an integer. It constructs a string where each character of the string ** is the unicode character for the corresponding integer argument. */ static void charFunc( sqlite3_context *context, int argc, sqlite3_value **argv ){ unsigned char *z, *zOut; int i; zOut = z = sqlite3_malloc64( argc*4+1 ); if( z==0 ){ sqlite3_result_error_nomem(context); return; } for(i=0; i0x10ffff ) x = 0xfffd; c = (unsigned)(x & 0x1fffff); if( c<0x00080 ){ *zOut++ = (u8)(c&0xFF); }else if( c<0x00800 ){ *zOut++ = 0xC0 + (u8)((c>>6)&0x1F); *zOut++ = 0x80 + (u8)(c & 0x3F); }else if( c<0x10000 ){ *zOut++ = 0xE0 + (u8)((c>>12)&0x0F); *zOut++ = 0x80 + (u8)((c>>6) & 0x3F); *zOut++ = 0x80 + (u8)(c & 0x3F); }else{ *zOut++ = 0xF0 + (u8)((c>>18) & 0x07); *zOut++ = 0x80 + (u8)((c>>12) & 0x3F); *zOut++ = 0x80 + (u8)((c>>6) & 0x3F); *zOut++ = 0x80 + (u8)(c & 0x3F); } \ } sqlite3_result_text64(context, (char*)z, zOut-z, sqlite3_free, SQLITE_UTF8); } /* ** The hex() function. Interpret the argument as a blob. Return ** a hexadecimal rendering as text. */ static void hexFunc( sqlite3_context *context, int argc, sqlite3_value **argv ){ int i, n; const unsigned char *pBlob; char *zHex, *z; assert( argc==1 ); UNUSED_PARAMETER(argc); pBlob = sqlite3_value_blob(argv[0]); n = sqlite3_value_bytes(argv[0]); assert( pBlob==sqlite3_value_blob(argv[0]) ); /* No encoding change */ z = zHex = contextMalloc(context, ((i64)n)*2 + 1); if( zHex ){ for(i=0; i>4)&0xf]; *(z++) = hexdigits[c&0xf]; } *z = 0; sqlite3_result_text(context, zHex, n*2, sqlite3_free); } } /* ** The zeroblob(N) function returns a zero-filled blob of size N bytes. */ static void zeroblobFunc( sqlite3_context *context, int argc, sqlite3_value **argv ){ i64 n; int rc; assert( argc==1 ); UNUSED_PARAMETER(argc); n = sqlite3_value_int64(argv[0]); if( n<0 ) n = 0; rc = sqlite3_result_zeroblob64(context, n); /* IMP: R-00293-64994 */ if( rc ){ sqlite3_result_error_code(context, rc); } } /* ** The replace() function. Three arguments are all strings: call ** them A, B, and C. The result is also a string which is derived ** from A by replacing every occurrence of B with C. The match ** must be exact. Collating sequences are not used. */ static void replaceFunc( sqlite3_context *context, int argc, sqlite3_value **argv ){ const unsigned char *zStr; /* The input string A */ const unsigned char *zPattern; /* The pattern string B */ const unsigned char *zRep; /* The replacement string C */ unsigned char *zOut; /* The output */ int nStr; /* Size of zStr */ int nPattern; /* Size of zPattern */ int nRep; /* Size of zRep */ i64 nOut; /* Maximum size of zOut */ int loopLimit; /* Last zStr[] that might match zPattern[] */ int i, j; /* Loop counters */ assert( argc==3 ); UNUSED_PARAMETER(argc); zStr = sqlite3_value_text(argv[0]); if( zStr==0 ) return; nStr = sqlite3_value_bytes(argv[0]); assert( zStr==sqlite3_value_text(argv[0]) ); /* No encoding change */ zPattern = sqlite3_value_text(argv[1]); if( zPattern==0 ){ assert( sqlite3_value_type(argv[1])==SQLITE_NULL || sqlite3_context_db_handle(context)->mallocFailed ); return; } if( zPattern[0]==0 ){ assert( sqlite3_value_type(argv[1])!=SQLITE_NULL ); sqlite3_result_value(context, argv[0]); return; } nPattern = sqlite3_value_bytes(argv[1]); assert( zPattern==sqlite3_value_text(argv[1]) ); /* No encoding change */ zRep = sqlite3_value_text(argv[2]); if( zRep==0 ) return; nRep = sqlite3_value_bytes(argv[2]); assert( zRep==sqlite3_value_text(argv[2]) ); nOut = nStr + 1; assert( nOutaLimit[SQLITE_LIMIT_LENGTH] ); testcase( nOut-2==db->aLimit[SQLITE_LIMIT_LENGTH] ); if( nOut-1>db->aLimit[SQLITE_LIMIT_LENGTH] ){ sqlite3_result_error_toobig(context); sqlite3_free(zOut); return; } zOld = zOut; zOut = sqlite3_realloc64(zOut, (int)nOut); if( zOut==0 ){ sqlite3_result_error_nomem(context); sqlite3_free(zOld); return; } memcpy(&zOut[j], zRep, nRep); j += nRep; i += nPattern-1; } } assert( j+nStr-i+1==nOut ); memcpy(&zOut[j], &zStr[i], nStr-i); j += nStr - i; assert( j<=nOut ); zOut[j] = 0; sqlite3_result_text(context, (char*)zOut, j, sqlite3_free); } /* ** Implementation of the TRIM(), LTRIM(), and RTRIM() functions. ** The userdata is 0x1 for left trim, 0x2 for right trim, 0x3 for both. */ static void trimFunc( sqlite3_context *context, int argc, sqlite3_value **argv ){ const unsigned char *zIn; /* Input string */ const unsigned char *zCharSet; /* Set of characters to trim */ int nIn; /* Number of bytes in input */ int flags; /* 1: trimleft 2: trimright 3: trim */ int i; /* Loop counter */ unsigned char *aLen = 0; /* Length of each character in zCharSet */ unsigned char **azChar = 0; /* Individual characters in zCharSet */ int nChar; /* Number of characters in zCharSet */ if( sqlite3_value_type(argv[0])==SQLITE_NULL ){ return; } zIn = sqlite3_value_text(argv[0]); if( zIn==0 ) return; nIn = sqlite3_value_bytes(argv[0]); assert( zIn==sqlite3_value_text(argv[0]) ); if( argc==1 ){ static const unsigned char lenOne[] = { 1 }; static unsigned char * const azOne[] = { (u8*)" " }; nChar = 1; aLen = (u8*)lenOne; azChar = (unsigned char **)azOne; zCharSet = 0; }else if( (zCharSet = sqlite3_value_text(argv[1]))==0 ){ return; }else{ const unsigned char *z; for(z=zCharSet, nChar=0; *z; nChar++){ SQLITE_SKIP_UTF8(z); } if( nChar>0 ){ azChar = contextMalloc(context, ((i64)nChar)*(sizeof(char*)+1)); if( azChar==0 ){ return; } aLen = (unsigned char*)&azChar[nChar]; for(z=zCharSet, nChar=0; *z; nChar++){ azChar[nChar] = (unsigned char *)z; SQLITE_SKIP_UTF8(z); aLen[nChar] = (u8)(z - azChar[nChar]); } } } if( nChar>0 ){ flags = SQLITE_PTR_TO_INT(sqlite3_user_data(context)); if( flags & 1 ){ while( nIn>0 ){ int len = 0; for(i=0; i=nChar ) break; zIn += len; nIn -= len; } } if( flags & 2 ){ while( nIn>0 ){ int len = 0; for(i=0; i=nChar ) break; nIn -= len; } } if( zCharSet ){ sqlite3_free(azChar); } } sqlite3_result_text(context, (char*)zIn, nIn, SQLITE_TRANSIENT); } #ifdef SQLITE_ENABLE_UNKNOWN_SQL_FUNCTION /* ** The "unknown" function is automatically substituted in place of ** any unrecognized function name when doing an EXPLAIN or EXPLAIN QUERY PLAN ** when the SQLITE_ENABLE_UNKNOWN_FUNCTION compile-time option is used. ** When the "sqlite3" command-line shell is built using this functionality, ** that allows an EXPLAIN or EXPLAIN QUERY PLAN for complex queries ** involving application-defined functions to be examined in a generic ** sqlite3 shell. */ static void unknownFunc( sqlite3_context *context, int argc, sqlite3_value **argv ){ /* no-op */ } #endif /*SQLITE_ENABLE_UNKNOWN_SQL_FUNCTION*/ /* IMP: R-25361-16150 This function is omitted from SQLite by default. It ** is only available if the SQLITE_SOUNDEX compile-time option is used ** when SQLite is built. */ #ifdef SQLITE_SOUNDEX /* ** Compute the soundex encoding of a word. ** ** IMP: R-59782-00072 The soundex(X) function returns a string that is the ** soundex encoding of the string X. */ static void soundexFunc( sqlite3_context *context, int argc, sqlite3_value **argv ){ char zResult[8]; const u8 *zIn; int i, j; static const unsigned char iCode[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 0, 1, 2, 0, 0, 2, 2, 4, 5, 5, 0, 1, 2, 6, 2, 3, 0, 1, 0, 2, 0, 2, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 0, 1, 2, 0, 0, 2, 2, 4, 5, 5, 0, 1, 2, 6, 2, 3, 0, 1, 0, 2, 0, 2, 0, 0, 0, 0, 0, }; assert( argc==1 ); zIn = (u8*)sqlite3_value_text(argv[0]); if( zIn==0 ) zIn = (u8*)""; for(i=0; zIn[i] && !sqlite3Isalpha(zIn[i]); i++){} if( zIn[i] ){ u8 prevcode = iCode[zIn[i]&0x7f]; zResult[0] = sqlite3Toupper(zIn[i]); for(j=1; j<4 && zIn[i]; i++){ int code = iCode[zIn[i]&0x7f]; if( code>0 ){ if( code!=prevcode ){ prevcode = code; zResult[j++] = code + '0'; } }else{ prevcode = 0; } } while( j<4 ){ zResult[j++] = '0'; } zResult[j] = 0; sqlite3_result_text(context, zResult, 4, SQLITE_TRANSIENT); }else{ /* IMP: R-64894-50321 The string "?000" is returned if the argument ** is NULL or contains no ASCII alphabetic characters. */ sqlite3_result_text(context, "?000", 4, SQLITE_STATIC); } } #endif /* SQLITE_SOUNDEX */ #ifndef SQLITE_OMIT_LOAD_EXTENSION /* ** A function that loads a shared-library extension then returns NULL. */ static void loadExt(sqlite3_context *context, int argc, sqlite3_value **argv){ const char *zFile = (const char *)sqlite3_value_text(argv[0]); const char *zProc; sqlite3 *db = sqlite3_context_db_handle(context); char *zErrMsg = 0; /* Disallow the load_extension() SQL function unless the SQLITE_LoadExtFunc ** flag is set. See the sqlite3_enable_load_extension() API. */ if( (db->flags & SQLITE_LoadExtFunc)==0 ){ sqlite3_result_error(context, "not authorized", -1); return; } if( argc==2 ){ zProc = (const char *)sqlite3_value_text(argv[1]); }else{ zProc = 0; } if( zFile && sqlite3_load_extension(db, zFile, zProc, &zErrMsg) ){ sqlite3_result_error(context, zErrMsg, -1); sqlite3_free(zErrMsg); } } #endif /* ** An instance of the following structure holds the context of a ** sum() or avg() aggregate computation. */ typedef struct SumCtx SumCtx; struct SumCtx { double rSum; /* Floating point sum */ i64 iSum; /* Integer sum */ i64 cnt; /* Number of elements summed */ u8 overflow; /* True if integer overflow seen */ u8 approx; /* True if non-integer value was input to the sum */ }; /* ** Routines used to compute the sum, average, and total. ** ** The SUM() function follows the (broken) SQL standard which means ** that it returns NULL if it sums over no inputs. TOTAL returns ** 0.0 in that case. In addition, TOTAL always returns a float where ** SUM might return an integer if it never encounters a floating point ** value. TOTAL never fails, but SUM might through an exception if ** it overflows an integer. */ static void sumStep(sqlite3_context *context, int argc, sqlite3_value **argv){ SumCtx *p; int type; assert( argc==1 ); UNUSED_PARAMETER(argc); p = sqlite3_aggregate_context(context, sizeof(*p)); type = sqlite3_value_numeric_type(argv[0]); if( p && type!=SQLITE_NULL ){ p->cnt++; if( type==SQLITE_INTEGER ){ i64 v = sqlite3_value_int64(argv[0]); p->rSum += v; if( (p->approx|p->overflow)==0 && sqlite3AddInt64(&p->iSum, v) ){ p->overflow = 1; } }else{ p->rSum += sqlite3_value_double(argv[0]); p->approx = 1; } } } static void sumFinalize(sqlite3_context *context){ SumCtx *p; p = sqlite3_aggregate_context(context, 0); if( p && p->cnt>0 ){ if( p->overflow ){ sqlite3_result_error(context,"integer overflow",-1); }else if( p->approx ){ sqlite3_result_double(context, p->rSum); }else{ sqlite3_result_int64(context, p->iSum); } } } static void avgFinalize(sqlite3_context *context){ SumCtx *p; p = sqlite3_aggregate_context(context, 0); if( p && p->cnt>0 ){ sqlite3_result_double(context, p->rSum/(double)p->cnt); } } static void totalFinalize(sqlite3_context *context){ SumCtx *p; p = sqlite3_aggregate_context(context, 0); /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */ sqlite3_result_double(context, p ? p->rSum : (double)0); } /* ** The following structure keeps track of state information for the ** count() aggregate function. */ typedef struct CountCtx CountCtx; struct CountCtx { i64 n; }; /* ** Routines to implement the count() aggregate function. */ static void countStep(sqlite3_context *context, int argc, sqlite3_value **argv){ CountCtx *p; p = sqlite3_aggregate_context(context, sizeof(*p)); if( (argc==0 || SQLITE_NULL!=sqlite3_value_type(argv[0])) && p ){ p->n++; } #ifndef SQLITE_OMIT_DEPRECATED /* The sqlite3_aggregate_count() function is deprecated. But just to make ** sure it still operates correctly, verify that its count agrees with our ** internal count when using count(*) and when the total count can be ** expressed as a 32-bit integer. */ assert( argc==1 || p==0 || p->n>0x7fffffff || p->n==sqlite3_aggregate_count(context) ); #endif } static void countFinalize(sqlite3_context *context){ CountCtx *p; p = sqlite3_aggregate_context(context, 0); sqlite3_result_int64(context, p ? p->n : 0); } /* ** Routines to implement min() and max() aggregate functions. */ static void minmaxStep( sqlite3_context *context, int NotUsed, sqlite3_value **argv ){ Mem *pArg = (Mem *)argv[0]; Mem *pBest; UNUSED_PARAMETER(NotUsed); pBest = (Mem *)sqlite3_aggregate_context(context, sizeof(*pBest)); if( !pBest ) return; if( sqlite3_value_type(argv[0])==SQLITE_NULL ){ if( pBest->flags ) sqlite3SkipAccumulatorLoad(context); }else if( pBest->flags ){ int max; int cmp; CollSeq *pColl = sqlite3GetFuncCollSeq(context); /* This step function is used for both the min() and max() aggregates, ** the only difference between the two being that the sense of the ** comparison is inverted. For the max() aggregate, the ** sqlite3_user_data() function returns (void *)-1. For min() it ** returns (void *)db, where db is the sqlite3* database pointer. ** Therefore the next statement sets variable 'max' to 1 for the max() ** aggregate, or 0 for min(). */ max = sqlite3_user_data(context)!=0; cmp = sqlite3MemCompare(pBest, pArg, pColl); if( (max && cmp<0) || (!max && cmp>0) ){ sqlite3VdbeMemCopy(pBest, pArg); }else{ sqlite3SkipAccumulatorLoad(context); } }else{ pBest->db = sqlite3_context_db_handle(context); sqlite3VdbeMemCopy(pBest, pArg); } } static void minMaxFinalize(sqlite3_context *context){ sqlite3_value *pRes; pRes = (sqlite3_value *)sqlite3_aggregate_context(context, 0); if( pRes ){ if( pRes->flags ){ sqlite3_result_value(context, pRes); } sqlite3VdbeMemRelease(pRes); } } /* ** group_concat(EXPR, ?SEPARATOR?) */ static void groupConcatStep( sqlite3_context *context, int argc, sqlite3_value **argv ){ const char *zVal; StrAccum *pAccum; const char *zSep; int nVal, nSep; assert( argc==1 || argc==2 ); if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return; pAccum = (StrAccum*)sqlite3_aggregate_context(context, sizeof(*pAccum)); if( pAccum ){ sqlite3 *db = sqlite3_context_db_handle(context); int firstTerm = pAccum->mxAlloc==0; pAccum->mxAlloc = db->aLimit[SQLITE_LIMIT_LENGTH]; if( !firstTerm ){ if( argc==2 ){ zSep = (char*)sqlite3_value_text(argv[1]); nSep = sqlite3_value_bytes(argv[1]); }else{ zSep = ","; nSep = 1; } if( nSep ) sqlite3StrAccumAppend(pAccum, zSep, nSep); } zVal = (char*)sqlite3_value_text(argv[0]); nVal = sqlite3_value_bytes(argv[0]); if( zVal ) sqlite3StrAccumAppend(pAccum, zVal, nVal); } } static void groupConcatFinalize(sqlite3_context *context){ StrAccum *pAccum; pAccum = sqlite3_aggregate_context(context, 0); if( pAccum ){ if( pAccum->accError==STRACCUM_TOOBIG ){ sqlite3_result_error_toobig(context); }else if( pAccum->accError==STRACCUM_NOMEM ){ sqlite3_result_error_nomem(context); }else{ sqlite3_result_text(context, sqlite3StrAccumFinish(pAccum), -1, sqlite3_free); } } } /* ** This routine does per-connection function registration. Most ** of the built-in functions above are part of the global function set. ** This routine only deals with those that are not global. */ SQLITE_PRIVATE void sqlite3RegisterPerConnectionBuiltinFunctions(sqlite3 *db){ int rc = sqlite3_overload_function(db, "MATCH", 2); assert( rc==SQLITE_NOMEM || rc==SQLITE_OK ); if( rc==SQLITE_NOMEM ){ sqlite3OomFault(db); } } /* ** Set the LIKEOPT flag on the 2-argument function with the given name. */ static void setLikeOptFlag(sqlite3 *db, const char *zName, u8 flagVal){ FuncDef *pDef; pDef = sqlite3FindFunction(db, zName, 2, SQLITE_UTF8, 0); if( ALWAYS(pDef) ){ pDef->funcFlags |= flagVal; } } /* ** Register the built-in LIKE and GLOB functions. The caseSensitive ** parameter determines whether or not the LIKE operator is case ** sensitive. GLOB is always case sensitive. */ SQLITE_PRIVATE void sqlite3RegisterLikeFunctions(sqlite3 *db, int caseSensitive){ struct compareInfo *pInfo; if( caseSensitive ){ pInfo = (struct compareInfo*)&likeInfoAlt; }else{ pInfo = (struct compareInfo*)&likeInfoNorm; } sqlite3CreateFunc(db, "like", 2, SQLITE_UTF8, pInfo, likeFunc, 0, 0, 0); sqlite3CreateFunc(db, "like", 3, SQLITE_UTF8, pInfo, likeFunc, 0, 0, 0); sqlite3CreateFunc(db, "glob", 2, SQLITE_UTF8, (struct compareInfo*)&globInfo, likeFunc, 0, 0, 0); setLikeOptFlag(db, "glob", SQLITE_FUNC_LIKE | SQLITE_FUNC_CASE); setLikeOptFlag(db, "like", caseSensitive ? (SQLITE_FUNC_LIKE | SQLITE_FUNC_CASE) : SQLITE_FUNC_LIKE); } /* ** pExpr points to an expression which implements a function. If ** it is appropriate to apply the LIKE optimization to that function ** then set aWc[0] through aWc[2] to the wildcard characters and ** return TRUE. If the function is not a LIKE-style function then ** return FALSE. ** ** *pIsNocase is set to true if uppercase and lowercase are equivalent for ** the function (default for LIKE). If the function makes the distinction ** between uppercase and lowercase (as does GLOB) then *pIsNocase is set to ** false. */ SQLITE_PRIVATE int sqlite3IsLikeFunction(sqlite3 *db, Expr *pExpr, int *pIsNocase, char *aWc){ FuncDef *pDef; if( pExpr->op!=TK_FUNCTION || !pExpr->x.pList || pExpr->x.pList->nExpr!=2 ){ return 0; } assert( !ExprHasProperty(pExpr, EP_xIsSelect) ); pDef = sqlite3FindFunction(db, pExpr->u.zToken, 2, SQLITE_UTF8, 0); if( NEVER(pDef==0) || (pDef->funcFlags & SQLITE_FUNC_LIKE)==0 ){ return 0; } /* The memcpy() statement assumes that the wildcard characters are ** the first three statements in the compareInfo structure. The ** asserts() that follow verify that assumption */ memcpy(aWc, pDef->pUserData, 3); assert( (char*)&likeInfoAlt == (char*)&likeInfoAlt.matchAll ); assert( &((char*)&likeInfoAlt)[1] == (char*)&likeInfoAlt.matchOne ); assert( &((char*)&likeInfoAlt)[2] == (char*)&likeInfoAlt.matchSet ); *pIsNocase = (pDef->funcFlags & SQLITE_FUNC_CASE)==0; return 1; } /* ** All of the FuncDef structures in the aBuiltinFunc[] array above ** to the global function hash table. This occurs at start-time (as ** a consequence of calling sqlite3_initialize()). ** ** After this routine runs */ SQLITE_PRIVATE void sqlite3RegisterBuiltinFunctions(void){ /* ** The following array holds FuncDef structures for all of the functions ** defined in this file. ** ** The array cannot be constant since changes are made to the ** FuncDef.pHash elements at start-time. The elements of this array ** are read-only after initialization is complete. ** ** For peak efficiency, put the most frequently used function last. */ static FuncDef aBuiltinFunc[] = { #ifdef SQLITE_SOUNDEX FUNCTION(soundex, 1, 0, 0, soundexFunc ), #endif #ifndef SQLITE_OMIT_LOAD_EXTENSION VFUNCTION(load_extension, 1, 0, 0, loadExt ), VFUNCTION(load_extension, 2, 0, 0, loadExt ), #endif #if SQLITE_USER_AUTHENTICATION FUNCTION(sqlite_crypt, 2, 0, 0, sqlite3CryptFunc ), #endif #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS DFUNCTION(sqlite_compileoption_used,1, 0, 0, compileoptionusedFunc ), DFUNCTION(sqlite_compileoption_get, 1, 0, 0, compileoptiongetFunc ), #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */ FUNCTION2(unlikely, 1, 0, 0, noopFunc, SQLITE_FUNC_UNLIKELY), FUNCTION2(likelihood, 2, 0, 0, noopFunc, SQLITE_FUNC_UNLIKELY), FUNCTION2(likely, 1, 0, 0, noopFunc, SQLITE_FUNC_UNLIKELY), FUNCTION(ltrim, 1, 1, 0, trimFunc ), FUNCTION(ltrim, 2, 1, 0, trimFunc ), FUNCTION(rtrim, 1, 2, 0, trimFunc ), FUNCTION(rtrim, 2, 2, 0, trimFunc ), FUNCTION(trim, 1, 3, 0, trimFunc ), FUNCTION(trim, 2, 3, 0, trimFunc ), FUNCTION(min, -1, 0, 1, minmaxFunc ), FUNCTION(min, 0, 0, 1, 0 ), AGGREGATE2(min, 1, 0, 1, minmaxStep, minMaxFinalize, SQLITE_FUNC_MINMAX ), FUNCTION(max, -1, 1, 1, minmaxFunc ), FUNCTION(max, 0, 1, 1, 0 ), AGGREGATE2(max, 1, 1, 1, minmaxStep, minMaxFinalize, SQLITE_FUNC_MINMAX ), FUNCTION2(typeof, 1, 0, 0, typeofFunc, SQLITE_FUNC_TYPEOF), FUNCTION2(length, 1, 0, 0, lengthFunc, SQLITE_FUNC_LENGTH), FUNCTION(instr, 2, 0, 0, instrFunc ), FUNCTION(printf, -1, 0, 0, printfFunc ), FUNCTION(unicode, 1, 0, 0, unicodeFunc ), FUNCTION(char, -1, 0, 0, charFunc ), FUNCTION(abs, 1, 0, 0, absFunc ), #ifndef SQLITE_OMIT_FLOATING_POINT FUNCTION(round, 1, 0, 0, roundFunc ), FUNCTION(round, 2, 0, 0, roundFunc ), #endif FUNCTION(upper, 1, 0, 0, upperFunc ), FUNCTION(lower, 1, 0, 0, lowerFunc ), FUNCTION(hex, 1, 0, 0, hexFunc ), FUNCTION2(ifnull, 2, 0, 0, noopFunc, SQLITE_FUNC_COALESCE), VFUNCTION(random, 0, 0, 0, randomFunc ), VFUNCTION(randomblob, 1, 0, 0, randomBlob ), FUNCTION(nullif, 2, 0, 1, nullifFunc ), DFUNCTION(sqlite_version, 0, 0, 0, versionFunc ), DFUNCTION(sqlite_source_id, 0, 0, 0, sourceidFunc ), FUNCTION(sqlite_log, 2, 0, 0, errlogFunc ), FUNCTION(quote, 1, 0, 0, quoteFunc ), VFUNCTION(last_insert_rowid, 0, 0, 0, last_insert_rowid), VFUNCTION(changes, 0, 0, 0, changes ), VFUNCTION(total_changes, 0, 0, 0, total_changes ), FUNCTION(replace, 3, 0, 0, replaceFunc ), FUNCTION(zeroblob, 1, 0, 0, zeroblobFunc ), FUNCTION(substr, 2, 0, 0, substrFunc ), FUNCTION(substr, 3, 0, 0, substrFunc ), AGGREGATE(sum, 1, 0, 0, sumStep, sumFinalize ), AGGREGATE(total, 1, 0, 0, sumStep, totalFinalize ), AGGREGATE(avg, 1, 0, 0, sumStep, avgFinalize ), AGGREGATE2(count, 0, 0, 0, countStep, countFinalize, SQLITE_FUNC_COUNT ), AGGREGATE(count, 1, 0, 0, countStep, countFinalize ), AGGREGATE(group_concat, 1, 0, 0, groupConcatStep, groupConcatFinalize), AGGREGATE(group_concat, 2, 0, 0, groupConcatStep, groupConcatFinalize), LIKEFUNC(glob, 2, &globInfo, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE), #ifdef SQLITE_CASE_SENSITIVE_LIKE LIKEFUNC(like, 2, &likeInfoAlt, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE), LIKEFUNC(like, 3, &likeInfoAlt, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE), #else LIKEFUNC(like, 2, &likeInfoNorm, SQLITE_FUNC_LIKE), LIKEFUNC(like, 3, &likeInfoNorm, SQLITE_FUNC_LIKE), #endif #ifdef SQLITE_ENABLE_UNKNOWN_SQL_FUNCTION FUNCTION(unknown, -1, 0, 0, unknownFunc ), #endif FUNCTION(coalesce, 1, 0, 0, 0 ), FUNCTION(coalesce, 0, 0, 0, 0 ), FUNCTION2(coalesce, -1, 0, 0, noopFunc, SQLITE_FUNC_COALESCE), }; #ifndef SQLITE_OMIT_ALTERTABLE sqlite3AlterFunctions(); #endif #if defined(SQLITE_ENABLE_STAT3) || defined(SQLITE_ENABLE_STAT4) sqlite3AnalyzeFunctions(); #endif sqlite3RegisterDateTimeFunctions(); sqlite3InsertBuiltinFuncs(aBuiltinFunc, ArraySize(aBuiltinFunc)); #if 0 /* Enable to print out how the built-in functions are hashed */ { int i; FuncDef *p; for(i=0; iu.pHash){ int n = sqlite3Strlen30(p->zName); int h = p->zName[0] + n; printf(" %s(%d)", p->zName, h); } printf("\n"); } } #endif } /************** End of func.c ************************************************/ /************** Begin file fkey.c ********************************************/ /* ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ************************************************************************* ** This file contains code used by the compiler to add foreign key ** support to compiled SQL statements. */ /* #include "sqliteInt.h" */ #ifndef SQLITE_OMIT_FOREIGN_KEY #ifndef SQLITE_OMIT_TRIGGER /* ** Deferred and Immediate FKs ** -------------------------- ** ** Foreign keys in SQLite come in two flavours: deferred and immediate. ** If an immediate foreign key constraint is violated, ** SQLITE_CONSTRAINT_FOREIGNKEY is returned and the current ** statement transaction rolled back. If a ** deferred foreign key constraint is violated, no action is taken ** immediately. However if the application attempts to commit the ** transaction before fixing the constraint violation, the attempt fails. ** ** Deferred constraints are implemented using a simple counter associated ** with the database handle. The counter is set to zero each time a ** database transaction is opened. Each time a statement is executed ** that causes a foreign key violation, the counter is incremented. Each ** time a statement is executed that removes an existing violation from ** the database, the counter is decremented. When the transaction is ** committed, the commit fails if the current value of the counter is ** greater than zero. This scheme has two big drawbacks: ** ** * When a commit fails due to a deferred foreign key constraint, ** there is no way to tell which foreign constraint is not satisfied, ** or which row it is not satisfied for. ** ** * If the database contains foreign key violations when the ** transaction is opened, this may cause the mechanism to malfunction. ** ** Despite these problems, this approach is adopted as it seems simpler ** than the alternatives. ** ** INSERT operations: ** ** I.1) For each FK for which the table is the child table, search ** the parent table for a match. If none is found increment the ** constraint counter. ** ** I.2) For each FK for which the table is the parent table, ** search the child table for rows that correspond to the new ** row in the parent table. Decrement the counter for each row ** found (as the constraint is now satisfied). ** ** DELETE operations: ** ** D.1) For each FK for which the table is the child table, ** search the parent table for a row that corresponds to the ** deleted row in the child table. If such a row is not found, ** decrement the counter. ** ** D.2) For each FK for which the table is the parent table, search ** the child table for rows that correspond to the deleted row ** in the parent table. For each found increment the counter. ** ** UPDATE operations: ** ** An UPDATE command requires that all 4 steps above are taken, but only ** for FK constraints for which the affected columns are actually ** modified (values must be compared at runtime). ** ** Note that I.1 and D.1 are very similar operations, as are I.2 and D.2. ** This simplifies the implementation a bit. ** ** For the purposes of immediate FK constraints, the OR REPLACE conflict ** resolution is considered to delete rows before the new row is inserted. ** If a delete caused by OR REPLACE violates an FK constraint, an exception ** is thrown, even if the FK constraint would be satisfied after the new ** row is inserted. ** ** Immediate constraints are usually handled similarly. The only difference ** is that the counter used is stored as part of each individual statement ** object (struct Vdbe). If, after the statement has run, its immediate ** constraint counter is greater than zero, ** it returns SQLITE_CONSTRAINT_FOREIGNKEY ** and the statement transaction is rolled back. An exception is an INSERT ** statement that inserts a single row only (no triggers). In this case, ** instead of using a counter, an exception is thrown immediately if the ** INSERT violates a foreign key constraint. This is necessary as such ** an INSERT does not open a statement transaction. ** ** TODO: How should dropping a table be handled? How should renaming a ** table be handled? ** ** ** Query API Notes ** --------------- ** ** Before coding an UPDATE or DELETE row operation, the code-generator ** for those two operations needs to know whether or not the operation ** requires any FK processing and, if so, which columns of the original ** row are required by the FK processing VDBE code (i.e. if FKs were ** implemented using triggers, which of the old.* columns would be ** accessed). No information is required by the code-generator before ** coding an INSERT operation. The functions used by the UPDATE/DELETE ** generation code to query for this information are: ** ** sqlite3FkRequired() - Test to see if FK processing is required. ** sqlite3FkOldmask() - Query for the set of required old.* columns. ** ** ** Externally accessible module functions ** -------------------------------------- ** ** sqlite3FkCheck() - Check for foreign key violations. ** sqlite3FkActions() - Code triggers for ON UPDATE/ON DELETE actions. ** sqlite3FkDelete() - Delete an FKey structure. */ /* ** VDBE Calling Convention ** ----------------------- ** ** Example: ** ** For the following INSERT statement: ** ** CREATE TABLE t1(a, b INTEGER PRIMARY KEY, c); ** INSERT INTO t1 VALUES(1, 2, 3.1); ** ** Register (x): 2 (type integer) ** Register (x+1): 1 (type integer) ** Register (x+2): NULL (type NULL) ** Register (x+3): 3.1 (type real) */ /* ** A foreign key constraint requires that the key columns in the parent ** table are collectively subject to a UNIQUE or PRIMARY KEY constraint. ** Given that pParent is the parent table for foreign key constraint pFKey, ** search the schema for a unique index on the parent key columns. ** ** If successful, zero is returned. If the parent key is an INTEGER PRIMARY ** KEY column, then output variable *ppIdx is set to NULL. Otherwise, *ppIdx ** is set to point to the unique index. ** ** If the parent key consists of a single column (the foreign key constraint ** is not a composite foreign key), output variable *paiCol is set to NULL. ** Otherwise, it is set to point to an allocated array of size N, where ** N is the number of columns in the parent key. The first element of the ** array is the index of the child table column that is mapped by the FK ** constraint to the parent table column stored in the left-most column ** of index *ppIdx. The second element of the array is the index of the ** child table column that corresponds to the second left-most column of ** *ppIdx, and so on. ** ** If the required index cannot be found, either because: ** ** 1) The named parent key columns do not exist, or ** ** 2) The named parent key columns do exist, but are not subject to a ** UNIQUE or PRIMARY KEY constraint, or ** ** 3) No parent key columns were provided explicitly as part of the ** foreign key definition, and the parent table does not have a ** PRIMARY KEY, or ** ** 4) No parent key columns were provided explicitly as part of the ** foreign key definition, and the PRIMARY KEY of the parent table ** consists of a different number of columns to the child key in ** the child table. ** ** then non-zero is returned, and a "foreign key mismatch" error loaded ** into pParse. If an OOM error occurs, non-zero is returned and the ** pParse->db->mallocFailed flag is set. */ SQLITE_PRIVATE int sqlite3FkLocateIndex( Parse *pParse, /* Parse context to store any error in */ Table *pParent, /* Parent table of FK constraint pFKey */ FKey *pFKey, /* Foreign key to find index for */ Index **ppIdx, /* OUT: Unique index on parent table */ int **paiCol /* OUT: Map of index columns in pFKey */ ){ Index *pIdx = 0; /* Value to return via *ppIdx */ int *aiCol = 0; /* Value to return via *paiCol */ int nCol = pFKey->nCol; /* Number of columns in parent key */ char *zKey = pFKey->aCol[0].zCol; /* Name of left-most parent key column */ /* The caller is responsible for zeroing output parameters. */ assert( ppIdx && *ppIdx==0 ); assert( !paiCol || *paiCol==0 ); assert( pParse ); /* If this is a non-composite (single column) foreign key, check if it ** maps to the INTEGER PRIMARY KEY of table pParent. If so, leave *ppIdx ** and *paiCol set to zero and return early. ** ** Otherwise, for a composite foreign key (more than one column), allocate ** space for the aiCol array (returned via output parameter *paiCol). ** Non-composite foreign keys do not require the aiCol array. */ if( nCol==1 ){ /* The FK maps to the IPK if any of the following are true: ** ** 1) There is an INTEGER PRIMARY KEY column and the FK is implicitly ** mapped to the primary key of table pParent, or ** 2) The FK is explicitly mapped to a column declared as INTEGER ** PRIMARY KEY. */ if( pParent->iPKey>=0 ){ if( !zKey ) return 0; if( !sqlite3StrICmp(pParent->aCol[pParent->iPKey].zName, zKey) ) return 0; } }else if( paiCol ){ assert( nCol>1 ); aiCol = (int *)sqlite3DbMallocRawNN(pParse->db, nCol*sizeof(int)); if( !aiCol ) return 1; *paiCol = aiCol; } for(pIdx=pParent->pIndex; pIdx; pIdx=pIdx->pNext){ if( pIdx->nKeyCol==nCol && IsUniqueIndex(pIdx) ){ /* pIdx is a UNIQUE index (or a PRIMARY KEY) and has the right number ** of columns. If each indexed column corresponds to a foreign key ** column of pFKey, then this index is a winner. */ if( zKey==0 ){ /* If zKey is NULL, then this foreign key is implicitly mapped to ** the PRIMARY KEY of table pParent. The PRIMARY KEY index may be ** identified by the test. */ if( IsPrimaryKeyIndex(pIdx) ){ if( aiCol ){ int i; for(i=0; iaCol[i].iFrom; } break; } }else{ /* If zKey is non-NULL, then this foreign key was declared to ** map to an explicit list of columns in table pParent. Check if this ** index matches those columns. Also, check that the index uses ** the default collation sequences for each column. */ int i, j; for(i=0; iaiColumn[i]; /* Index of column in parent tbl */ const char *zDfltColl; /* Def. collation for column */ char *zIdxCol; /* Name of indexed column */ if( iCol<0 ) break; /* No foreign keys against expression indexes */ /* If the index uses a collation sequence that is different from ** the default collation sequence for the column, this index is ** unusable. Bail out early in this case. */ zDfltColl = pParent->aCol[iCol].zColl; if( !zDfltColl ) zDfltColl = sqlite3StrBINARY; if( sqlite3StrICmp(pIdx->azColl[i], zDfltColl) ) break; zIdxCol = pParent->aCol[iCol].zName; for(j=0; jaCol[j].zCol, zIdxCol)==0 ){ if( aiCol ) aiCol[i] = pFKey->aCol[j].iFrom; break; } } if( j==nCol ) break; } if( i==nCol ) break; /* pIdx is usable */ } } } if( !pIdx ){ if( !pParse->disableTriggers ){ sqlite3ErrorMsg(pParse, "foreign key mismatch - \"%w\" referencing \"%w\"", pFKey->pFrom->zName, pFKey->zTo); } sqlite3DbFree(pParse->db, aiCol); return 1; } *ppIdx = pIdx; return 0; } /* ** This function is called when a row is inserted into or deleted from the ** child table of foreign key constraint pFKey. If an SQL UPDATE is executed ** on the child table of pFKey, this function is invoked twice for each row ** affected - once to "delete" the old row, and then again to "insert" the ** new row. ** ** Each time it is called, this function generates VDBE code to locate the ** row in the parent table that corresponds to the row being inserted into ** or deleted from the child table. If the parent row can be found, no ** special action is taken. Otherwise, if the parent row can *not* be ** found in the parent table: ** ** Operation | FK type | Action taken ** -------------------------------------------------------------------------- ** INSERT immediate Increment the "immediate constraint counter". ** ** DELETE immediate Decrement the "immediate constraint counter". ** ** INSERT deferred Increment the "deferred constraint counter". ** ** DELETE deferred Decrement the "deferred constraint counter". ** ** These operations are identified in the comment at the top of this file ** (fkey.c) as "I.1" and "D.1". */ static void fkLookupParent( Parse *pParse, /* Parse context */ int iDb, /* Index of database housing pTab */ Table *pTab, /* Parent table of FK pFKey */ Index *pIdx, /* Unique index on parent key columns in pTab */ FKey *pFKey, /* Foreign key constraint */ int *aiCol, /* Map from parent key columns to child table columns */ int regData, /* Address of array containing child table row */ int nIncr, /* Increment constraint counter by this */ int isIgnore /* If true, pretend pTab contains all NULL values */ ){ int i; /* Iterator variable */ Vdbe *v = sqlite3GetVdbe(pParse); /* Vdbe to add code to */ int iCur = pParse->nTab - 1; /* Cursor number to use */ int iOk = sqlite3VdbeMakeLabel(v); /* jump here if parent key found */ /* If nIncr is less than zero, then check at runtime if there are any ** outstanding constraints to resolve. If there are not, there is no need ** to check if deleting this row resolves any outstanding violations. ** ** Check if any of the key columns in the child table row are NULL. If ** any are, then the constraint is considered satisfied. No need to ** search for a matching row in the parent table. */ if( nIncr<0 ){ sqlite3VdbeAddOp2(v, OP_FkIfZero, pFKey->isDeferred, iOk); VdbeCoverage(v); } for(i=0; inCol; i++){ int iReg = aiCol[i] + regData + 1; sqlite3VdbeAddOp2(v, OP_IsNull, iReg, iOk); VdbeCoverage(v); } if( isIgnore==0 ){ if( pIdx==0 ){ /* If pIdx is NULL, then the parent key is the INTEGER PRIMARY KEY ** column of the parent table (table pTab). */ int iMustBeInt; /* Address of MustBeInt instruction */ int regTemp = sqlite3GetTempReg(pParse); /* Invoke MustBeInt to coerce the child key value to an integer (i.e. ** apply the affinity of the parent key). If this fails, then there ** is no matching parent key. Before using MustBeInt, make a copy of ** the value. Otherwise, the value inserted into the child key column ** will have INTEGER affinity applied to it, which may not be correct. */ sqlite3VdbeAddOp2(v, OP_SCopy, aiCol[0]+1+regData, regTemp); iMustBeInt = sqlite3VdbeAddOp2(v, OP_MustBeInt, regTemp, 0); VdbeCoverage(v); /* If the parent table is the same as the child table, and we are about ** to increment the constraint-counter (i.e. this is an INSERT operation), ** then check if the row being inserted matches itself. If so, do not ** increment the constraint-counter. */ if( pTab==pFKey->pFrom && nIncr==1 ){ sqlite3VdbeAddOp3(v, OP_Eq, regData, iOk, regTemp); VdbeCoverage(v); sqlite3VdbeChangeP5(v, SQLITE_NOTNULL); } sqlite3OpenTable(pParse, iCur, iDb, pTab, OP_OpenRead); sqlite3VdbeAddOp3(v, OP_NotExists, iCur, 0, regTemp); VdbeCoverage(v); sqlite3VdbeGoto(v, iOk); sqlite3VdbeJumpHere(v, sqlite3VdbeCurrentAddr(v)-2); sqlite3VdbeJumpHere(v, iMustBeInt); sqlite3ReleaseTempReg(pParse, regTemp); }else{ int nCol = pFKey->nCol; int regTemp = sqlite3GetTempRange(pParse, nCol); int regRec = sqlite3GetTempReg(pParse); sqlite3VdbeAddOp3(v, OP_OpenRead, iCur, pIdx->tnum, iDb); sqlite3VdbeSetP4KeyInfo(pParse, pIdx); for(i=0; ipFrom && nIncr==1 ){ int iJump = sqlite3VdbeCurrentAddr(v) + nCol + 1; for(i=0; iaiColumn[i]+1+regData; assert( pIdx->aiColumn[i]>=0 ); assert( aiCol[i]!=pTab->iPKey ); if( pIdx->aiColumn[i]==pTab->iPKey ){ /* The parent key is a composite key that includes the IPK column */ iParent = regData; } sqlite3VdbeAddOp3(v, OP_Ne, iChild, iJump, iParent); VdbeCoverage(v); sqlite3VdbeChangeP5(v, SQLITE_JUMPIFNULL); } sqlite3VdbeGoto(v, iOk); } sqlite3VdbeAddOp4(v, OP_MakeRecord, regTemp, nCol, regRec, sqlite3IndexAffinityStr(pParse->db,pIdx), nCol); sqlite3VdbeAddOp4Int(v, OP_Found, iCur, iOk, regRec, 0); VdbeCoverage(v); sqlite3ReleaseTempReg(pParse, regRec); sqlite3ReleaseTempRange(pParse, regTemp, nCol); } } if( !pFKey->isDeferred && !(pParse->db->flags & SQLITE_DeferFKs) && !pParse->pToplevel && !pParse->isMultiWrite ){ /* Special case: If this is an INSERT statement that will insert exactly ** one row into the table, raise a constraint immediately instead of ** incrementing a counter. This is necessary as the VM code is being ** generated for will not open a statement transaction. */ assert( nIncr==1 ); sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_FOREIGNKEY, OE_Abort, 0, P4_STATIC, P5_ConstraintFK); }else{ if( nIncr>0 && pFKey->isDeferred==0 ){ sqlite3MayAbort(pParse); } sqlite3VdbeAddOp2(v, OP_FkCounter, pFKey->isDeferred, nIncr); } sqlite3VdbeResolveLabel(v, iOk); sqlite3VdbeAddOp1(v, OP_Close, iCur); } /* ** Return an Expr object that refers to a memory register corresponding ** to column iCol of table pTab. ** ** regBase is the first of an array of register that contains the data ** for pTab. regBase itself holds the rowid. regBase+1 holds the first ** column. regBase+2 holds the second column, and so forth. */ static Expr *exprTableRegister( Parse *pParse, /* Parsing and code generating context */ Table *pTab, /* The table whose content is at r[regBase]... */ int regBase, /* Contents of table pTab */ i16 iCol /* Which column of pTab is desired */ ){ Expr *pExpr; Column *pCol; const char *zColl; sqlite3 *db = pParse->db; pExpr = sqlite3Expr(db, TK_REGISTER, 0); if( pExpr ){ if( iCol>=0 && iCol!=pTab->iPKey ){ pCol = &pTab->aCol[iCol]; pExpr->iTable = regBase + iCol + 1; pExpr->affinity = pCol->affinity; zColl = pCol->zColl; if( zColl==0 ) zColl = db->pDfltColl->zName; pExpr = sqlite3ExprAddCollateString(pParse, pExpr, zColl); }else{ pExpr->iTable = regBase; pExpr->affinity = SQLITE_AFF_INTEGER; } } return pExpr; } /* ** Return an Expr object that refers to column iCol of table pTab which ** has cursor iCur. */ static Expr *exprTableColumn( sqlite3 *db, /* The database connection */ Table *pTab, /* The table whose column is desired */ int iCursor, /* The open cursor on the table */ i16 iCol /* The column that is wanted */ ){ Expr *pExpr = sqlite3Expr(db, TK_COLUMN, 0); if( pExpr ){ pExpr->pTab = pTab; pExpr->iTable = iCursor; pExpr->iColumn = iCol; } return pExpr; } /* ** This function is called to generate code executed when a row is deleted ** from the parent table of foreign key constraint pFKey and, if pFKey is ** deferred, when a row is inserted into the same table. When generating ** code for an SQL UPDATE operation, this function may be called twice - ** once to "delete" the old row and once to "insert" the new row. ** ** Parameter nIncr is passed -1 when inserting a row (as this may decrease ** the number of FK violations in the db) or +1 when deleting one (as this ** may increase the number of FK constraint problems). ** ** The code generated by this function scans through the rows in the child ** table that correspond to the parent table row being deleted or inserted. ** For each child row found, one of the following actions is taken: ** ** Operation | FK type | Action taken ** -------------------------------------------------------------------------- ** DELETE immediate Increment the "immediate constraint counter". ** Or, if the ON (UPDATE|DELETE) action is RESTRICT, ** throw a "FOREIGN KEY constraint failed" exception. ** ** INSERT immediate Decrement the "immediate constraint counter". ** ** DELETE deferred Increment the "deferred constraint counter". ** Or, if the ON (UPDATE|DELETE) action is RESTRICT, ** throw a "FOREIGN KEY constraint failed" exception. ** ** INSERT deferred Decrement the "deferred constraint counter". ** ** These operations are identified in the comment at the top of this file ** (fkey.c) as "I.2" and "D.2". */ static void fkScanChildren( Parse *pParse, /* Parse context */ SrcList *pSrc, /* The child table to be scanned */ Table *pTab, /* The parent table */ Index *pIdx, /* Index on parent covering the foreign key */ FKey *pFKey, /* The foreign key linking pSrc to pTab */ int *aiCol, /* Map from pIdx cols to child table cols */ int regData, /* Parent row data starts here */ int nIncr /* Amount to increment deferred counter by */ ){ sqlite3 *db = pParse->db; /* Database handle */ int i; /* Iterator variable */ Expr *pWhere = 0; /* WHERE clause to scan with */ NameContext sNameContext; /* Context used to resolve WHERE clause */ WhereInfo *pWInfo; /* Context used by sqlite3WhereXXX() */ int iFkIfZero = 0; /* Address of OP_FkIfZero */ Vdbe *v = sqlite3GetVdbe(pParse); assert( pIdx==0 || pIdx->pTable==pTab ); assert( pIdx==0 || pIdx->nKeyCol==pFKey->nCol ); assert( pIdx!=0 || pFKey->nCol==1 ); assert( pIdx!=0 || HasRowid(pTab) ); if( nIncr<0 ){ iFkIfZero = sqlite3VdbeAddOp2(v, OP_FkIfZero, pFKey->isDeferred, 0); VdbeCoverage(v); } /* Create an Expr object representing an SQL expression like: ** ** = AND = ... ** ** The collation sequence used for the comparison should be that of ** the parent key columns. The affinity of the parent key column should ** be applied to each child key value before the comparison takes place. */ for(i=0; inCol; i++){ Expr *pLeft; /* Value from parent table row */ Expr *pRight; /* Column ref to child table */ Expr *pEq; /* Expression (pLeft = pRight) */ i16 iCol; /* Index of column in child table */ const char *zCol; /* Name of column in child table */ iCol = pIdx ? pIdx->aiColumn[i] : -1; pLeft = exprTableRegister(pParse, pTab, regData, iCol); iCol = aiCol ? aiCol[i] : pFKey->aCol[0].iFrom; assert( iCol>=0 ); zCol = pFKey->pFrom->aCol[iCol].zName; pRight = sqlite3Expr(db, TK_ID, zCol); pEq = sqlite3PExpr(pParse, TK_EQ, pLeft, pRight, 0); pWhere = sqlite3ExprAnd(db, pWhere, pEq); } /* If the child table is the same as the parent table, then add terms ** to the WHERE clause that prevent this entry from being scanned. ** The added WHERE clause terms are like this: ** ** $current_rowid!=rowid ** NOT( $current_a==a AND $current_b==b AND ... ) ** ** The first form is used for rowid tables. The second form is used ** for WITHOUT ROWID tables. In the second form, the primary key is ** (a,b,...) */ if( pTab==pFKey->pFrom && nIncr>0 ){ Expr *pNe; /* Expression (pLeft != pRight) */ Expr *pLeft; /* Value from parent table row */ Expr *pRight; /* Column ref to child table */ if( HasRowid(pTab) ){ pLeft = exprTableRegister(pParse, pTab, regData, -1); pRight = exprTableColumn(db, pTab, pSrc->a[0].iCursor, -1); pNe = sqlite3PExpr(pParse, TK_NE, pLeft, pRight, 0); }else{ Expr *pEq, *pAll = 0; Index *pPk = sqlite3PrimaryKeyIndex(pTab); assert( pIdx!=0 ); for(i=0; inKeyCol; i++){ i16 iCol = pIdx->aiColumn[i]; assert( iCol>=0 ); pLeft = exprTableRegister(pParse, pTab, regData, iCol); pRight = exprTableColumn(db, pTab, pSrc->a[0].iCursor, iCol); pEq = sqlite3PExpr(pParse, TK_EQ, pLeft, pRight, 0); pAll = sqlite3ExprAnd(db, pAll, pEq); } pNe = sqlite3PExpr(pParse, TK_NOT, pAll, 0, 0); } pWhere = sqlite3ExprAnd(db, pWhere, pNe); } /* Resolve the references in the WHERE clause. */ memset(&sNameContext, 0, sizeof(NameContext)); sNameContext.pSrcList = pSrc; sNameContext.pParse = pParse; sqlite3ResolveExprNames(&sNameContext, pWhere); /* Create VDBE to loop through the entries in pSrc that match the WHERE ** clause. For each row found, increment either the deferred or immediate ** foreign key constraint counter. */ pWInfo = sqlite3WhereBegin(pParse, pSrc, pWhere, 0, 0, 0, 0); sqlite3VdbeAddOp2(v, OP_FkCounter, pFKey->isDeferred, nIncr); if( pWInfo ){ sqlite3WhereEnd(pWInfo); } /* Clean up the WHERE clause constructed above. */ sqlite3ExprDelete(db, pWhere); if( iFkIfZero ){ sqlite3VdbeJumpHere(v, iFkIfZero); } } /* ** This function returns a linked list of FKey objects (connected by ** FKey.pNextTo) holding all children of table pTab. For example, ** given the following schema: ** ** CREATE TABLE t1(a PRIMARY KEY); ** CREATE TABLE t2(b REFERENCES t1(a); ** ** Calling this function with table "t1" as an argument returns a pointer ** to the FKey structure representing the foreign key constraint on table ** "t2". Calling this function with "t2" as the argument would return a ** NULL pointer (as there are no FK constraints for which t2 is the parent ** table). */ SQLITE_PRIVATE FKey *sqlite3FkReferences(Table *pTab){ return (FKey *)sqlite3HashFind(&pTab->pSchema->fkeyHash, pTab->zName); } /* ** The second argument is a Trigger structure allocated by the ** fkActionTrigger() routine. This function deletes the Trigger structure ** and all of its sub-components. ** ** The Trigger structure or any of its sub-components may be allocated from ** the lookaside buffer belonging to database handle dbMem. */ static void fkTriggerDelete(sqlite3 *dbMem, Trigger *p){ if( p ){ TriggerStep *pStep = p->step_list; sqlite3ExprDelete(dbMem, pStep->pWhere); sqlite3ExprListDelete(dbMem, pStep->pExprList); sqlite3SelectDelete(dbMem, pStep->pSelect); sqlite3ExprDelete(dbMem, p->pWhen); sqlite3DbFree(dbMem, p); } } /* ** This function is called to generate code that runs when table pTab is ** being dropped from the database. The SrcList passed as the second argument ** to this function contains a single entry guaranteed to resolve to ** table pTab. ** ** Normally, no code is required. However, if either ** ** (a) The table is the parent table of a FK constraint, or ** (b) The table is the child table of a deferred FK constraint and it is ** determined at runtime that there are outstanding deferred FK ** constraint violations in the database, ** ** then the equivalent of "DELETE FROM " is executed before dropping ** the table from the database. Triggers are disabled while running this ** DELETE, but foreign key actions are not. */ SQLITE_PRIVATE void sqlite3FkDropTable(Parse *pParse, SrcList *pName, Table *pTab){ sqlite3 *db = pParse->db; if( (db->flags&SQLITE_ForeignKeys) && !IsVirtual(pTab) && !pTab->pSelect ){ int iSkip = 0; Vdbe *v = sqlite3GetVdbe(pParse); assert( v ); /* VDBE has already been allocated */ if( sqlite3FkReferences(pTab)==0 ){ /* Search for a deferred foreign key constraint for which this table ** is the child table. If one cannot be found, return without ** generating any VDBE code. If one can be found, then jump over ** the entire DELETE if there are no outstanding deferred constraints ** when this statement is run. */ FKey *p; for(p=pTab->pFKey; p; p=p->pNextFrom){ if( p->isDeferred || (db->flags & SQLITE_DeferFKs) ) break; } if( !p ) return; iSkip = sqlite3VdbeMakeLabel(v); sqlite3VdbeAddOp2(v, OP_FkIfZero, 1, iSkip); VdbeCoverage(v); } pParse->disableTriggers = 1; sqlite3DeleteFrom(pParse, sqlite3SrcListDup(db, pName, 0), 0); pParse->disableTriggers = 0; /* If the DELETE has generated immediate foreign key constraint ** violations, halt the VDBE and return an error at this point, before ** any modifications to the schema are made. This is because statement ** transactions are not able to rollback schema changes. ** ** If the SQLITE_DeferFKs flag is set, then this is not required, as ** the statement transaction will not be rolled back even if FK ** constraints are violated. */ if( (db->flags & SQLITE_DeferFKs)==0 ){ sqlite3VdbeAddOp2(v, OP_FkIfZero, 0, sqlite3VdbeCurrentAddr(v)+2); VdbeCoverage(v); sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_FOREIGNKEY, OE_Abort, 0, P4_STATIC, P5_ConstraintFK); } if( iSkip ){ sqlite3VdbeResolveLabel(v, iSkip); } } } /* ** The second argument points to an FKey object representing a foreign key ** for which pTab is the child table. An UPDATE statement against pTab ** is currently being processed. For each column of the table that is ** actually updated, the corresponding element in the aChange[] array ** is zero or greater (if a column is unmodified the corresponding element ** is set to -1). If the rowid column is modified by the UPDATE statement ** the bChngRowid argument is non-zero. ** ** This function returns true if any of the columns that are part of the ** child key for FK constraint *p are modified. */ static int fkChildIsModified( Table *pTab, /* Table being updated */ FKey *p, /* Foreign key for which pTab is the child */ int *aChange, /* Array indicating modified columns */ int bChngRowid /* True if rowid is modified by this update */ ){ int i; for(i=0; inCol; i++){ int iChildKey = p->aCol[i].iFrom; if( aChange[iChildKey]>=0 ) return 1; if( iChildKey==pTab->iPKey && bChngRowid ) return 1; } return 0; } /* ** The second argument points to an FKey object representing a foreign key ** for which pTab is the parent table. An UPDATE statement against pTab ** is currently being processed. For each column of the table that is ** actually updated, the corresponding element in the aChange[] array ** is zero or greater (if a column is unmodified the corresponding element ** is set to -1). If the rowid column is modified by the UPDATE statement ** the bChngRowid argument is non-zero. ** ** This function returns true if any of the columns that are part of the ** parent key for FK constraint *p are modified. */ static int fkParentIsModified( Table *pTab, FKey *p, int *aChange, int bChngRowid ){ int i; for(i=0; inCol; i++){ char *zKey = p->aCol[i].zCol; int iKey; for(iKey=0; iKeynCol; iKey++){ if( aChange[iKey]>=0 || (iKey==pTab->iPKey && bChngRowid) ){ Column *pCol = &pTab->aCol[iKey]; if( zKey ){ if( 0==sqlite3StrICmp(pCol->zName, zKey) ) return 1; }else if( pCol->colFlags & COLFLAG_PRIMKEY ){ return 1; } } } } return 0; } /* ** Return true if the parser passed as the first argument is being ** used to code a trigger that is really a "SET NULL" action belonging ** to trigger pFKey. */ static int isSetNullAction(Parse *pParse, FKey *pFKey){ Parse *pTop = sqlite3ParseToplevel(pParse); if( pTop->pTriggerPrg ){ Trigger *p = pTop->pTriggerPrg->pTrigger; if( (p==pFKey->apTrigger[0] && pFKey->aAction[0]==OE_SetNull) || (p==pFKey->apTrigger[1] && pFKey->aAction[1]==OE_SetNull) ){ return 1; } } return 0; } /* ** This function is called when inserting, deleting or updating a row of ** table pTab to generate VDBE code to perform foreign key constraint ** processing for the operation. ** ** For a DELETE operation, parameter regOld is passed the index of the ** first register in an array of (pTab->nCol+1) registers containing the ** rowid of the row being deleted, followed by each of the column values ** of the row being deleted, from left to right. Parameter regNew is passed ** zero in this case. ** ** For an INSERT operation, regOld is passed zero and regNew is passed the ** first register of an array of (pTab->nCol+1) registers containing the new ** row data. ** ** For an UPDATE operation, this function is called twice. Once before ** the original record is deleted from the table using the calling convention ** described for DELETE. Then again after the original record is deleted ** but before the new record is inserted using the INSERT convention. */ SQLITE_PRIVATE void sqlite3FkCheck( Parse *pParse, /* Parse context */ Table *pTab, /* Row is being deleted from this table */ int regOld, /* Previous row data is stored here */ int regNew, /* New row data is stored here */ int *aChange, /* Array indicating UPDATEd columns (or 0) */ int bChngRowid /* True if rowid is UPDATEd */ ){ sqlite3 *db = pParse->db; /* Database handle */ FKey *pFKey; /* Used to iterate through FKs */ int iDb; /* Index of database containing pTab */ const char *zDb; /* Name of database containing pTab */ int isIgnoreErrors = pParse->disableTriggers; /* Exactly one of regOld and regNew should be non-zero. */ assert( (regOld==0)!=(regNew==0) ); /* If foreign-keys are disabled, this function is a no-op. */ if( (db->flags&SQLITE_ForeignKeys)==0 ) return; iDb = sqlite3SchemaToIndex(db, pTab->pSchema); zDb = db->aDb[iDb].zDbSName; /* Loop through all the foreign key constraints for which pTab is the ** child table (the table that the foreign key definition is part of). */ for(pFKey=pTab->pFKey; pFKey; pFKey=pFKey->pNextFrom){ Table *pTo; /* Parent table of foreign key pFKey */ Index *pIdx = 0; /* Index on key columns in pTo */ int *aiFree = 0; int *aiCol; int iCol; int i; int bIgnore = 0; if( aChange && sqlite3_stricmp(pTab->zName, pFKey->zTo)!=0 && fkChildIsModified(pTab, pFKey, aChange, bChngRowid)==0 ){ continue; } /* Find the parent table of this foreign key. Also find a unique index ** on the parent key columns in the parent table. If either of these ** schema items cannot be located, set an error in pParse and return ** early. */ if( pParse->disableTriggers ){ pTo = sqlite3FindTable(db, pFKey->zTo, zDb); }else{ pTo = sqlite3LocateTable(pParse, 0, pFKey->zTo, zDb); } if( !pTo || sqlite3FkLocateIndex(pParse, pTo, pFKey, &pIdx, &aiFree) ){ assert( isIgnoreErrors==0 || (regOld!=0 && regNew==0) ); if( !isIgnoreErrors || db->mallocFailed ) return; if( pTo==0 ){ /* If isIgnoreErrors is true, then a table is being dropped. In this ** case SQLite runs a "DELETE FROM xxx" on the table being dropped ** before actually dropping it in order to check FK constraints. ** If the parent table of an FK constraint on the current table is ** missing, behave as if it is empty. i.e. decrement the relevant ** FK counter for each row of the current table with non-NULL keys. */ Vdbe *v = sqlite3GetVdbe(pParse); int iJump = sqlite3VdbeCurrentAddr(v) + pFKey->nCol + 1; for(i=0; inCol; i++){ int iReg = pFKey->aCol[i].iFrom + regOld + 1; sqlite3VdbeAddOp2(v, OP_IsNull, iReg, iJump); VdbeCoverage(v); } sqlite3VdbeAddOp2(v, OP_FkCounter, pFKey->isDeferred, -1); } continue; } assert( pFKey->nCol==1 || (aiFree && pIdx) ); if( aiFree ){ aiCol = aiFree; }else{ iCol = pFKey->aCol[0].iFrom; aiCol = &iCol; } for(i=0; inCol; i++){ if( aiCol[i]==pTab->iPKey ){ aiCol[i] = -1; } assert( pIdx==0 || pIdx->aiColumn[i]>=0 ); #ifndef SQLITE_OMIT_AUTHORIZATION /* Request permission to read the parent key columns. If the ** authorization callback returns SQLITE_IGNORE, behave as if any ** values read from the parent table are NULL. */ if( db->xAuth ){ int rcauth; char *zCol = pTo->aCol[pIdx ? pIdx->aiColumn[i] : pTo->iPKey].zName; rcauth = sqlite3AuthReadCol(pParse, pTo->zName, zCol, iDb); bIgnore = (rcauth==SQLITE_IGNORE); } #endif } /* Take a shared-cache advisory read-lock on the parent table. Allocate ** a cursor to use to search the unique index on the parent key columns ** in the parent table. */ sqlite3TableLock(pParse, iDb, pTo->tnum, 0, pTo->zName); pParse->nTab++; if( regOld!=0 ){ /* A row is being removed from the child table. Search for the parent. ** If the parent does not exist, removing the child row resolves an ** outstanding foreign key constraint violation. */ fkLookupParent(pParse, iDb, pTo, pIdx, pFKey, aiCol, regOld, -1, bIgnore); } if( regNew!=0 && !isSetNullAction(pParse, pFKey) ){ /* A row is being added to the child table. If a parent row cannot ** be found, adding the child row has violated the FK constraint. ** ** If this operation is being performed as part of a trigger program ** that is actually a "SET NULL" action belonging to this very ** foreign key, then omit this scan altogether. As all child key ** values are guaranteed to be NULL, it is not possible for adding ** this row to cause an FK violation. */ fkLookupParent(pParse, iDb, pTo, pIdx, pFKey, aiCol, regNew, +1, bIgnore); } sqlite3DbFree(db, aiFree); } /* Loop through all the foreign key constraints that refer to this table. ** (the "child" constraints) */ for(pFKey = sqlite3FkReferences(pTab); pFKey; pFKey=pFKey->pNextTo){ Index *pIdx = 0; /* Foreign key index for pFKey */ SrcList *pSrc; int *aiCol = 0; if( aChange && fkParentIsModified(pTab, pFKey, aChange, bChngRowid)==0 ){ continue; } if( !pFKey->isDeferred && !(db->flags & SQLITE_DeferFKs) && !pParse->pToplevel && !pParse->isMultiWrite ){ assert( regOld==0 && regNew!=0 ); /* Inserting a single row into a parent table cannot cause (or fix) ** an immediate foreign key violation. So do nothing in this case. */ continue; } if( sqlite3FkLocateIndex(pParse, pTab, pFKey, &pIdx, &aiCol) ){ if( !isIgnoreErrors || db->mallocFailed ) return; continue; } assert( aiCol || pFKey->nCol==1 ); /* Create a SrcList structure containing the child table. We need the ** child table as a SrcList for sqlite3WhereBegin() */ pSrc = sqlite3SrcListAppend(db, 0, 0, 0); if( pSrc ){ struct SrcList_item *pItem = pSrc->a; pItem->pTab = pFKey->pFrom; pItem->zName = pFKey->pFrom->zName; pItem->pTab->nRef++; pItem->iCursor = pParse->nTab++; if( regNew!=0 ){ fkScanChildren(pParse, pSrc, pTab, pIdx, pFKey, aiCol, regNew, -1); } if( regOld!=0 ){ int eAction = pFKey->aAction[aChange!=0]; fkScanChildren(pParse, pSrc, pTab, pIdx, pFKey, aiCol, regOld, 1); /* If this is a deferred FK constraint, or a CASCADE or SET NULL ** action applies, then any foreign key violations caused by ** removing the parent key will be rectified by the action trigger. ** So do not set the "may-abort" flag in this case. ** ** Note 1: If the FK is declared "ON UPDATE CASCADE", then the ** may-abort flag will eventually be set on this statement anyway ** (when this function is called as part of processing the UPDATE ** within the action trigger). ** ** Note 2: At first glance it may seem like SQLite could simply omit ** all OP_FkCounter related scans when either CASCADE or SET NULL ** applies. The trouble starts if the CASCADE or SET NULL action ** trigger causes other triggers or action rules attached to the ** child table to fire. In these cases the fk constraint counters ** might be set incorrectly if any OP_FkCounter related scans are ** omitted. */ if( !pFKey->isDeferred && eAction!=OE_Cascade && eAction!=OE_SetNull ){ sqlite3MayAbort(pParse); } } pItem->zName = 0; sqlite3SrcListDelete(db, pSrc); } sqlite3DbFree(db, aiCol); } } #define COLUMN_MASK(x) (((x)>31) ? 0xffffffff : ((u32)1<<(x))) /* ** This function is called before generating code to update or delete a ** row contained in table pTab. */ SQLITE_PRIVATE u32 sqlite3FkOldmask( Parse *pParse, /* Parse context */ Table *pTab /* Table being modified */ ){ u32 mask = 0; if( pParse->db->flags&SQLITE_ForeignKeys ){ FKey *p; int i; for(p=pTab->pFKey; p; p=p->pNextFrom){ for(i=0; inCol; i++) mask |= COLUMN_MASK(p->aCol[i].iFrom); } for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){ Index *pIdx = 0; sqlite3FkLocateIndex(pParse, pTab, p, &pIdx, 0); if( pIdx ){ for(i=0; inKeyCol; i++){ assert( pIdx->aiColumn[i]>=0 ); mask |= COLUMN_MASK(pIdx->aiColumn[i]); } } } } return mask; } /* ** This function is called before generating code to update or delete a ** row contained in table pTab. If the operation is a DELETE, then ** parameter aChange is passed a NULL value. For an UPDATE, aChange points ** to an array of size N, where N is the number of columns in table pTab. ** If the i'th column is not modified by the UPDATE, then the corresponding ** entry in the aChange[] array is set to -1. If the column is modified, ** the value is 0 or greater. Parameter chngRowid is set to true if the ** UPDATE statement modifies the rowid fields of the table. ** ** If any foreign key processing will be required, this function returns ** true. If there is no foreign key related processing, this function ** returns false. */ SQLITE_PRIVATE int sqlite3FkRequired( Parse *pParse, /* Parse context */ Table *pTab, /* Table being modified */ int *aChange, /* Non-NULL for UPDATE operations */ int chngRowid /* True for UPDATE that affects rowid */ ){ if( pParse->db->flags&SQLITE_ForeignKeys ){ if( !aChange ){ /* A DELETE operation. Foreign key processing is required if the ** table in question is either the child or parent table for any ** foreign key constraint. */ return (sqlite3FkReferences(pTab) || pTab->pFKey); }else{ /* This is an UPDATE. Foreign key processing is only required if the ** operation modifies one or more child or parent key columns. */ FKey *p; /* Check if any child key columns are being modified. */ for(p=pTab->pFKey; p; p=p->pNextFrom){ if( fkChildIsModified(pTab, p, aChange, chngRowid) ) return 1; } /* Check if any parent key columns are being modified. */ for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){ if( fkParentIsModified(pTab, p, aChange, chngRowid) ) return 1; } } } return 0; } /* ** This function is called when an UPDATE or DELETE operation is being ** compiled on table pTab, which is the parent table of foreign-key pFKey. ** If the current operation is an UPDATE, then the pChanges parameter is ** passed a pointer to the list of columns being modified. If it is a ** DELETE, pChanges is passed a NULL pointer. ** ** It returns a pointer to a Trigger structure containing a trigger ** equivalent to the ON UPDATE or ON DELETE action specified by pFKey. ** If the action is "NO ACTION" or "RESTRICT", then a NULL pointer is ** returned (these actions require no special handling by the triggers ** sub-system, code for them is created by fkScanChildren()). ** ** For example, if pFKey is the foreign key and pTab is table "p" in ** the following schema: ** ** CREATE TABLE p(pk PRIMARY KEY); ** CREATE TABLE c(ck REFERENCES p ON DELETE CASCADE); ** ** then the returned trigger structure is equivalent to: ** ** CREATE TRIGGER ... DELETE ON p BEGIN ** DELETE FROM c WHERE ck = old.pk; ** END; ** ** The returned pointer is cached as part of the foreign key object. It ** is eventually freed along with the rest of the foreign key object by ** sqlite3FkDelete(). */ static Trigger *fkActionTrigger( Parse *pParse, /* Parse context */ Table *pTab, /* Table being updated or deleted from */ FKey *pFKey, /* Foreign key to get action for */ ExprList *pChanges /* Change-list for UPDATE, NULL for DELETE */ ){ sqlite3 *db = pParse->db; /* Database handle */ int action; /* One of OE_None, OE_Cascade etc. */ Trigger *pTrigger; /* Trigger definition to return */ int iAction = (pChanges!=0); /* 1 for UPDATE, 0 for DELETE */ action = pFKey->aAction[iAction]; if( action==OE_Restrict && (db->flags & SQLITE_DeferFKs) ){ return 0; } pTrigger = pFKey->apTrigger[iAction]; if( action!=OE_None && !pTrigger ){ char const *zFrom; /* Name of child table */ int nFrom; /* Length in bytes of zFrom */ Index *pIdx = 0; /* Parent key index for this FK */ int *aiCol = 0; /* child table cols -> parent key cols */ TriggerStep *pStep = 0; /* First (only) step of trigger program */ Expr *pWhere = 0; /* WHERE clause of trigger step */ ExprList *pList = 0; /* Changes list if ON UPDATE CASCADE */ Select *pSelect = 0; /* If RESTRICT, "SELECT RAISE(...)" */ int i; /* Iterator variable */ Expr *pWhen = 0; /* WHEN clause for the trigger */ if( sqlite3FkLocateIndex(pParse, pTab, pFKey, &pIdx, &aiCol) ) return 0; assert( aiCol || pFKey->nCol==1 ); for(i=0; inCol; i++){ Token tOld = { "old", 3 }; /* Literal "old" token */ Token tNew = { "new", 3 }; /* Literal "new" token */ Token tFromCol; /* Name of column in child table */ Token tToCol; /* Name of column in parent table */ int iFromCol; /* Idx of column in child table */ Expr *pEq; /* tFromCol = OLD.tToCol */ iFromCol = aiCol ? aiCol[i] : pFKey->aCol[0].iFrom; assert( iFromCol>=0 ); assert( pIdx!=0 || (pTab->iPKey>=0 && pTab->iPKeynCol) ); assert( pIdx==0 || pIdx->aiColumn[i]>=0 ); sqlite3TokenInit(&tToCol, pTab->aCol[pIdx ? pIdx->aiColumn[i] : pTab->iPKey].zName); sqlite3TokenInit(&tFromCol, pFKey->pFrom->aCol[iFromCol].zName); /* Create the expression "OLD.zToCol = zFromCol". It is important ** that the "OLD.zToCol" term is on the LHS of the = operator, so ** that the affinity and collation sequence associated with the ** parent table are used for the comparison. */ pEq = sqlite3PExpr(pParse, TK_EQ, sqlite3PExpr(pParse, TK_DOT, sqlite3ExprAlloc(db, TK_ID, &tOld, 0), sqlite3ExprAlloc(db, TK_ID, &tToCol, 0) , 0), sqlite3ExprAlloc(db, TK_ID, &tFromCol, 0) , 0); pWhere = sqlite3ExprAnd(db, pWhere, pEq); /* For ON UPDATE, construct the next term of the WHEN clause. ** The final WHEN clause will be like this: ** ** WHEN NOT(old.col1 IS new.col1 AND ... AND old.colN IS new.colN) */ if( pChanges ){ pEq = sqlite3PExpr(pParse, TK_IS, sqlite3PExpr(pParse, TK_DOT, sqlite3ExprAlloc(db, TK_ID, &tOld, 0), sqlite3ExprAlloc(db, TK_ID, &tToCol, 0), 0), sqlite3PExpr(pParse, TK_DOT, sqlite3ExprAlloc(db, TK_ID, &tNew, 0), sqlite3ExprAlloc(db, TK_ID, &tToCol, 0), 0), 0); pWhen = sqlite3ExprAnd(db, pWhen, pEq); } if( action!=OE_Restrict && (action!=OE_Cascade || pChanges) ){ Expr *pNew; if( action==OE_Cascade ){ pNew = sqlite3PExpr(pParse, TK_DOT, sqlite3ExprAlloc(db, TK_ID, &tNew, 0), sqlite3ExprAlloc(db, TK_ID, &tToCol, 0) , 0); }else if( action==OE_SetDflt ){ Expr *pDflt = pFKey->pFrom->aCol[iFromCol].pDflt; if( pDflt ){ pNew = sqlite3ExprDup(db, pDflt, 0); }else{ pNew = sqlite3ExprAlloc(db, TK_NULL, 0, 0); } }else{ pNew = sqlite3ExprAlloc(db, TK_NULL, 0, 0); } pList = sqlite3ExprListAppend(pParse, pList, pNew); sqlite3ExprListSetName(pParse, pList, &tFromCol, 0); } } sqlite3DbFree(db, aiCol); zFrom = pFKey->pFrom->zName; nFrom = sqlite3Strlen30(zFrom); if( action==OE_Restrict ){ Token tFrom; Expr *pRaise; tFrom.z = zFrom; tFrom.n = nFrom; pRaise = sqlite3Expr(db, TK_RAISE, "FOREIGN KEY constraint failed"); if( pRaise ){ pRaise->affinity = OE_Abort; } pSelect = sqlite3SelectNew(pParse, sqlite3ExprListAppend(pParse, 0, pRaise), sqlite3SrcListAppend(db, 0, &tFrom, 0), pWhere, 0, 0, 0, 0, 0, 0 ); pWhere = 0; } /* Disable lookaside memory allocation */ db->lookaside.bDisable++; pTrigger = (Trigger *)sqlite3DbMallocZero(db, sizeof(Trigger) + /* struct Trigger */ sizeof(TriggerStep) + /* Single step in trigger program */ nFrom + 1 /* Space for pStep->zTarget */ ); if( pTrigger ){ pStep = pTrigger->step_list = (TriggerStep *)&pTrigger[1]; pStep->zTarget = (char *)&pStep[1]; memcpy((char *)pStep->zTarget, zFrom, nFrom); pStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE); pStep->pExprList = sqlite3ExprListDup(db, pList, EXPRDUP_REDUCE); pStep->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE); if( pWhen ){ pWhen = sqlite3PExpr(pParse, TK_NOT, pWhen, 0, 0); pTrigger->pWhen = sqlite3ExprDup(db, pWhen, EXPRDUP_REDUCE); } } /* Re-enable the lookaside buffer, if it was disabled earlier. */ db->lookaside.bDisable--; sqlite3ExprDelete(db, pWhere); sqlite3ExprDelete(db, pWhen); sqlite3ExprListDelete(db, pList); sqlite3SelectDelete(db, pSelect); if( db->mallocFailed==1 ){ fkTriggerDelete(db, pTrigger); return 0; } assert( pStep!=0 ); switch( action ){ case OE_Restrict: pStep->op = TK_SELECT; break; case OE_Cascade: if( !pChanges ){ pStep->op = TK_DELETE; break; } default: pStep->op = TK_UPDATE; } pStep->pTrig = pTrigger; pTrigger->pSchema = pTab->pSchema; pTrigger->pTabSchema = pTab->pSchema; pFKey->apTrigger[iAction] = pTrigger; pTrigger->op = (pChanges ? TK_UPDATE : TK_DELETE); } return pTrigger; } /* ** This function is called when deleting or updating a row to implement ** any required CASCADE, SET NULL or SET DEFAULT actions. */ SQLITE_PRIVATE void sqlite3FkActions( Parse *pParse, /* Parse context */ Table *pTab, /* Table being updated or deleted from */ ExprList *pChanges, /* Change-list for UPDATE, NULL for DELETE */ int regOld, /* Address of array containing old row */ int *aChange, /* Array indicating UPDATEd columns (or 0) */ int bChngRowid /* True if rowid is UPDATEd */ ){ /* If foreign-key support is enabled, iterate through all FKs that ** refer to table pTab. If there is an action associated with the FK ** for this operation (either update or delete), invoke the associated ** trigger sub-program. */ if( pParse->db->flags&SQLITE_ForeignKeys ){ FKey *pFKey; /* Iterator variable */ for(pFKey = sqlite3FkReferences(pTab); pFKey; pFKey=pFKey->pNextTo){ if( aChange==0 || fkParentIsModified(pTab, pFKey, aChange, bChngRowid) ){ Trigger *pAct = fkActionTrigger(pParse, pTab, pFKey, pChanges); if( pAct ){ sqlite3CodeRowTriggerDirect(pParse, pAct, pTab, regOld, OE_Abort, 0); } } } } } #endif /* ifndef SQLITE_OMIT_TRIGGER */ /* ** Free all memory associated with foreign key definitions attached to ** table pTab. Remove the deleted foreign keys from the Schema.fkeyHash ** hash table. */ SQLITE_PRIVATE void sqlite3FkDelete(sqlite3 *db, Table *pTab){ FKey *pFKey; /* Iterator variable */ FKey *pNext; /* Copy of pFKey->pNextFrom */ assert( db==0 || IsVirtual(pTab) || sqlite3SchemaMutexHeld(db, 0, pTab->pSchema) ); for(pFKey=pTab->pFKey; pFKey; pFKey=pNext){ /* Remove the FK from the fkeyHash hash table. */ if( !db || db->pnBytesFreed==0 ){ if( pFKey->pPrevTo ){ pFKey->pPrevTo->pNextTo = pFKey->pNextTo; }else{ void *p = (void *)pFKey->pNextTo; const char *z = (p ? pFKey->pNextTo->zTo : pFKey->zTo); sqlite3HashInsert(&pTab->pSchema->fkeyHash, z, p); } if( pFKey->pNextTo ){ pFKey->pNextTo->pPrevTo = pFKey->pPrevTo; } } /* EV: R-30323-21917 Each foreign key constraint in SQLite is ** classified as either immediate or deferred. */ assert( pFKey->isDeferred==0 || pFKey->isDeferred==1 ); /* Delete any triggers created to implement actions for this FK. */ #ifndef SQLITE_OMIT_TRIGGER fkTriggerDelete(db, pFKey->apTrigger[0]); fkTriggerDelete(db, pFKey->apTrigger[1]); #endif pNext = pFKey->pNextFrom; sqlite3DbFree(db, pFKey); } } #endif /* ifndef SQLITE_OMIT_FOREIGN_KEY */ /************** End of fkey.c ************************************************/ /************** Begin file insert.c ******************************************/ /* ** 2001 September 15 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ************************************************************************* ** This file contains C code routines that are called by the parser ** to handle INSERT statements in SQLite. */ /* #include "sqliteInt.h" */ /* ** Generate code that will ** ** (1) acquire a lock for table pTab then ** (2) open pTab as cursor iCur. ** ** If pTab is a WITHOUT ROWID table, then it is the PRIMARY KEY index ** for that table that is actually opened. */ SQLITE_PRIVATE void sqlite3OpenTable( Parse *pParse, /* Generate code into this VDBE */ int iCur, /* The cursor number of the table */ int iDb, /* The database index in sqlite3.aDb[] */ Table *pTab, /* The table to be opened */ int opcode /* OP_OpenRead or OP_OpenWrite */ ){ Vdbe *v; assert( !IsVirtual(pTab) ); v = sqlite3GetVdbe(pParse); assert( opcode==OP_OpenWrite || opcode==OP_OpenRead ); sqlite3TableLock(pParse, iDb, pTab->tnum, (opcode==OP_OpenWrite)?1:0, pTab->zName); if( HasRowid(pTab) ){ sqlite3VdbeAddOp4Int(v, opcode, iCur, pTab->tnum, iDb, pTab->nCol); VdbeComment((v, "%s", pTab->zName)); }else{ Index *pPk = sqlite3PrimaryKeyIndex(pTab); assert( pPk!=0 ); assert( pPk->tnum==pTab->tnum ); sqlite3VdbeAddOp3(v, opcode, iCur, pPk->tnum, iDb); sqlite3VdbeSetP4KeyInfo(pParse, pPk); VdbeComment((v, "%s", pTab->zName)); } } /* ** Return a pointer to the column affinity string associated with index ** pIdx. A column affinity string has one character for each column in ** the table, according to the affinity of the column: ** ** Character Column affinity ** ------------------------------ ** 'A' BLOB ** 'B' TEXT ** 'C' NUMERIC ** 'D' INTEGER ** 'F' REAL ** ** An extra 'D' is appended to the end of the string to cover the ** rowid that appears as the last column in every index. ** ** Memory for the buffer containing the column index affinity string ** is managed along with the rest of the Index structure. It will be ** released when sqlite3DeleteIndex() is called. */ SQLITE_PRIVATE const char *sqlite3IndexAffinityStr(sqlite3 *db, Index *pIdx){ if( !pIdx->zColAff ){ /* The first time a column affinity string for a particular index is ** required, it is allocated and populated here. It is then stored as ** a member of the Index structure for subsequent use. ** ** The column affinity string will eventually be deleted by ** sqliteDeleteIndex() when the Index structure itself is cleaned ** up. */ int n; Table *pTab = pIdx->pTable; pIdx->zColAff = (char *)sqlite3DbMallocRaw(0, pIdx->nColumn+1); if( !pIdx->zColAff ){ sqlite3OomFault(db); return 0; } for(n=0; nnColumn; n++){ i16 x = pIdx->aiColumn[n]; if( x>=0 ){ pIdx->zColAff[n] = pTab->aCol[x].affinity; }else if( x==XN_ROWID ){ pIdx->zColAff[n] = SQLITE_AFF_INTEGER; }else{ char aff; assert( x==XN_EXPR ); assert( pIdx->aColExpr!=0 ); aff = sqlite3ExprAffinity(pIdx->aColExpr->a[n].pExpr); if( aff==0 ) aff = SQLITE_AFF_BLOB; pIdx->zColAff[n] = aff; } } pIdx->zColAff[n] = 0; } return pIdx->zColAff; } /* ** Compute the affinity string for table pTab, if it has not already been ** computed. As an optimization, omit trailing SQLITE_AFF_BLOB affinities. ** ** If the affinity exists (if it is no entirely SQLITE_AFF_BLOB values) and ** if iReg>0 then code an OP_Affinity opcode that will set the affinities ** for register iReg and following. Or if affinities exists and iReg==0, ** then just set the P4 operand of the previous opcode (which should be ** an OP_MakeRecord) to the affinity string. ** ** A column affinity string has one character per column: ** ** Character Column affinity ** ------------------------------ ** 'A' BLOB ** 'B' TEXT ** 'C' NUMERIC ** 'D' INTEGER ** 'E' REAL */ SQLITE_PRIVATE void sqlite3TableAffinity(Vdbe *v, Table *pTab, int iReg){ int i; char *zColAff = pTab->zColAff; if( zColAff==0 ){ sqlite3 *db = sqlite3VdbeDb(v); zColAff = (char *)sqlite3DbMallocRaw(0, pTab->nCol+1); if( !zColAff ){ sqlite3OomFault(db); return; } for(i=0; inCol; i++){ zColAff[i] = pTab->aCol[i].affinity; } do{ zColAff[i--] = 0; }while( i>=0 && zColAff[i]==SQLITE_AFF_BLOB ); pTab->zColAff = zColAff; } i = sqlite3Strlen30(zColAff); if( i ){ if( iReg ){ sqlite3VdbeAddOp4(v, OP_Affinity, iReg, i, 0, zColAff, i); }else{ sqlite3VdbeChangeP4(v, -1, zColAff, i); } } } /* ** Return non-zero if the table pTab in database iDb or any of its indices ** have been opened at any point in the VDBE program. This is used to see if ** a statement of the form "INSERT INTO SELECT ..." can ** run without using a temporary table for the results of the SELECT. */ static int readsTable(Parse *p, int iDb, Table *pTab){ Vdbe *v = sqlite3GetVdbe(p); int i; int iEnd = sqlite3VdbeCurrentAddr(v); #ifndef SQLITE_OMIT_VIRTUALTABLE VTable *pVTab = IsVirtual(pTab) ? sqlite3GetVTable(p->db, pTab) : 0; #endif for(i=1; iopcode==OP_OpenRead && pOp->p3==iDb ){ Index *pIndex; int tnum = pOp->p2; if( tnum==pTab->tnum ){ return 1; } for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){ if( tnum==pIndex->tnum ){ return 1; } } } #ifndef SQLITE_OMIT_VIRTUALTABLE if( pOp->opcode==OP_VOpen && pOp->p4.pVtab==pVTab ){ assert( pOp->p4.pVtab!=0 ); assert( pOp->p4type==P4_VTAB ); return 1; } #endif } return 0; } #ifndef SQLITE_OMIT_AUTOINCREMENT /* ** Locate or create an AutoincInfo structure associated with table pTab ** which is in database iDb. Return the register number for the register ** that holds the maximum rowid. Return zero if pTab is not an AUTOINCREMENT ** table. (Also return zero when doing a VACUUM since we do not want to ** update the AUTOINCREMENT counters during a VACUUM.) ** ** There is at most one AutoincInfo structure per table even if the ** same table is autoincremented multiple times due to inserts within ** triggers. A new AutoincInfo structure is created if this is the ** first use of table pTab. On 2nd and subsequent uses, the original ** AutoincInfo structure is used. ** ** Three memory locations are allocated: ** ** (1) Register to hold the name of the pTab table. ** (2) Register to hold the maximum ROWID of pTab. ** (3) Register to hold the rowid in sqlite_sequence of pTab ** ** The 2nd register is the one that is returned. That is all the ** insert routine needs to know about. */ static int autoIncBegin( Parse *pParse, /* Parsing context */ int iDb, /* Index of the database holding pTab */ Table *pTab /* The table we are writing to */ ){ int memId = 0; /* Register holding maximum rowid */ if( (pTab->tabFlags & TF_Autoincrement)!=0 && (pParse->db->flags & SQLITE_Vacuum)==0 ){ Parse *pToplevel = sqlite3ParseToplevel(pParse); AutoincInfo *pInfo; pInfo = pToplevel->pAinc; while( pInfo && pInfo->pTab!=pTab ){ pInfo = pInfo->pNext; } if( pInfo==0 ){ pInfo = sqlite3DbMallocRawNN(pParse->db, sizeof(*pInfo)); if( pInfo==0 ) return 0; pInfo->pNext = pToplevel->pAinc; pToplevel->pAinc = pInfo; pInfo->pTab = pTab; pInfo->iDb = iDb; pToplevel->nMem++; /* Register to hold name of table */ pInfo->regCtr = ++pToplevel->nMem; /* Max rowid register */ pToplevel->nMem++; /* Rowid in sqlite_sequence */ } memId = pInfo->regCtr; } return memId; } /* ** This routine generates code that will initialize all of the ** register used by the autoincrement tracker. */ SQLITE_PRIVATE void sqlite3AutoincrementBegin(Parse *pParse){ AutoincInfo *p; /* Information about an AUTOINCREMENT */ sqlite3 *db = pParse->db; /* The database connection */ Db *pDb; /* Database only autoinc table */ int memId; /* Register holding max rowid */ Vdbe *v = pParse->pVdbe; /* VDBE under construction */ /* This routine is never called during trigger-generation. It is ** only called from the top-level */ assert( pParse->pTriggerTab==0 ); assert( sqlite3IsToplevel(pParse) ); assert( v ); /* We failed long ago if this is not so */ for(p = pParse->pAinc; p; p = p->pNext){ static const int iLn = VDBE_OFFSET_LINENO(2); static const VdbeOpList autoInc[] = { /* 0 */ {OP_Null, 0, 0, 0}, /* 1 */ {OP_Rewind, 0, 9, 0}, /* 2 */ {OP_Column, 0, 0, 0}, /* 3 */ {OP_Ne, 0, 7, 0}, /* 4 */ {OP_Rowid, 0, 0, 0}, /* 5 */ {OP_Column, 0, 1, 0}, /* 6 */ {OP_Goto, 0, 9, 0}, /* 7 */ {OP_Next, 0, 2, 0}, /* 8 */ {OP_Integer, 0, 0, 0}, /* 9 */ {OP_Close, 0, 0, 0} }; VdbeOp *aOp; pDb = &db->aDb[p->iDb]; memId = p->regCtr; assert( sqlite3SchemaMutexHeld(db, 0, pDb->pSchema) ); sqlite3OpenTable(pParse, 0, p->iDb, pDb->pSchema->pSeqTab, OP_OpenRead); sqlite3VdbeLoadString(v, memId-1, p->pTab->zName); aOp = sqlite3VdbeAddOpList(v, ArraySize(autoInc), autoInc, iLn); if( aOp==0 ) break; aOp[0].p2 = memId; aOp[0].p3 = memId+1; aOp[2].p3 = memId; aOp[3].p1 = memId-1; aOp[3].p3 = memId; aOp[3].p5 = SQLITE_JUMPIFNULL; aOp[4].p2 = memId+1; aOp[5].p3 = memId; aOp[8].p2 = memId; } } /* ** Update the maximum rowid for an autoincrement calculation. ** ** This routine should be called when the regRowid register holds a ** new rowid that is about to be inserted. If that new rowid is ** larger than the maximum rowid in the memId memory cell, then the ** memory cell is updated. */ static void autoIncStep(Parse *pParse, int memId, int regRowid){ if( memId>0 ){ sqlite3VdbeAddOp2(pParse->pVdbe, OP_MemMax, memId, regRowid); } } /* ** This routine generates the code needed to write autoincrement ** maximum rowid values back into the sqlite_sequence register. ** Every statement that might do an INSERT into an autoincrement ** table (either directly or through triggers) needs to call this ** routine just before the "exit" code. */ static SQLITE_NOINLINE void autoIncrementEnd(Parse *pParse){ AutoincInfo *p; Vdbe *v = pParse->pVdbe; sqlite3 *db = pParse->db; assert( v ); for(p = pParse->pAinc; p; p = p->pNext){ static const int iLn = VDBE_OFFSET_LINENO(2); static const VdbeOpList autoIncEnd[] = { /* 0 */ {OP_NotNull, 0, 2, 0}, /* 1 */ {OP_NewRowid, 0, 0, 0}, /* 2 */ {OP_MakeRecord, 0, 2, 0}, /* 3 */ {OP_Insert, 0, 0, 0}, /* 4 */ {OP_Close, 0, 0, 0} }; VdbeOp *aOp; Db *pDb = &db->aDb[p->iDb]; int iRec; int memId = p->regCtr; iRec = sqlite3GetTempReg(pParse); assert( sqlite3SchemaMutexHeld(db, 0, pDb->pSchema) ); sqlite3OpenTable(pParse, 0, p->iDb, pDb->pSchema->pSeqTab, OP_OpenWrite); aOp = sqlite3VdbeAddOpList(v, ArraySize(autoIncEnd), autoIncEnd, iLn); if( aOp==0 ) break; aOp[0].p1 = memId+1; aOp[1].p2 = memId+1; aOp[2].p1 = memId-1; aOp[2].p3 = iRec; aOp[3].p2 = iRec; aOp[3].p3 = memId+1; aOp[3].p5 = OPFLAG_APPEND; sqlite3ReleaseTempReg(pParse, iRec); } } SQLITE_PRIVATE void sqlite3AutoincrementEnd(Parse *pParse){ if( pParse->pAinc ) autoIncrementEnd(pParse); } #else /* ** If SQLITE_OMIT_AUTOINCREMENT is defined, then the three routines ** above are all no-ops */ # define autoIncBegin(A,B,C) (0) # define autoIncStep(A,B,C) #endif /* SQLITE_OMIT_AUTOINCREMENT */ /* Forward declaration */ static int xferOptimization( Parse *pParse, /* Parser context */ Table *pDest, /* The table we are inserting into */ Select *pSelect, /* A SELECT statement to use as the data source */ int onError, /* How to handle constraint errors */ int iDbDest /* The database of pDest */ ); /* ** This routine is called to handle SQL of the following forms: ** ** insert into TABLE (IDLIST) values(EXPRLIST),(EXPRLIST),... ** insert into TABLE (IDLIST) select ** insert into TABLE (IDLIST) default values ** ** The IDLIST following the table name is always optional. If omitted, ** then a list of all (non-hidden) columns for the table is substituted. ** The IDLIST appears in the pColumn parameter. pColumn is NULL if IDLIST ** is omitted. ** ** For the pSelect parameter holds the values to be inserted for the ** first two forms shown above. A VALUES clause is really just short-hand ** for a SELECT statement that omits the FROM clause and everything else ** that follows. If the pSelect parameter is NULL, that means that the ** DEFAULT VALUES form of the INSERT statement is intended. ** ** The code generated follows one of four templates. For a simple ** insert with data coming from a single-row VALUES clause, the code executes ** once straight down through. Pseudo-code follows (we call this ** the "1st template"): ** ** open write cursor to
    and its indices ** put VALUES clause expressions into registers ** write the resulting record into
    ** cleanup ** ** The three remaining templates assume the statement is of the form ** ** INSERT INTO
    SELECT ... ** ** If the SELECT clause is of the restricted form "SELECT * FROM " - ** in other words if the SELECT pulls all columns from a single table ** and there is no WHERE or LIMIT or GROUP BY or ORDER BY clauses, and ** if and are distinct tables but have identical ** schemas, including all the same indices, then a special optimization ** is invoked that copies raw records from over to . ** See the xferOptimization() function for the implementation of this ** template. This is the 2nd template. ** ** open a write cursor to
    ** open read cursor on ** transfer all records in over to
    ** close cursors ** foreach index on
    ** open a write cursor on the
    index ** open a read cursor on the corresponding index ** transfer all records from the read to the write cursors ** close cursors ** end foreach ** ** The 3rd template is for when the second template does not apply ** and the SELECT clause does not read from
    at any time. ** The generated code follows this template: ** ** X <- A ** goto B ** A: setup for the SELECT ** loop over the rows in the SELECT ** load values into registers R..R+n ** yield X ** end loop ** cleanup after the SELECT ** end-coroutine X ** B: open write cursor to
    and its indices ** C: yield X, at EOF goto D ** insert the select result into
    from R..R+n ** goto C ** D: cleanup ** ** The 4th template is used if the insert statement takes its ** values from a SELECT but the data is being inserted into a table ** that is also read as part of the SELECT. In the third form, ** we have to use an intermediate table to store the results of ** the select. The template is like this: ** ** X <- A ** goto B ** A: setup for the SELECT ** loop over the tables in the SELECT ** load value into register R..R+n ** yield X ** end loop ** cleanup after the SELECT ** end co-routine R ** B: open temp table ** L: yield X, at EOF goto M ** insert row from R..R+n into temp table ** goto L ** M: open write cursor to
    and its indices ** rewind temp table ** C: loop over rows of intermediate table ** transfer values form intermediate table into
    ** end loop ** D: cleanup */ SQLITE_PRIVATE void sqlite3Insert( Parse *pParse, /* Parser context */ SrcList *pTabList, /* Name of table into which we are inserting */ Select *pSelect, /* A SELECT statement to use as the data source */ IdList *pColumn, /* Column names corresponding to IDLIST. */ int onError /* How to handle constraint errors */ ){ sqlite3 *db; /* The main database structure */ Table *pTab; /* The table to insert into. aka TABLE */ char *zTab; /* Name of the table into which we are inserting */ int i, j, idx; /* Loop counters */ Vdbe *v; /* Generate code into this virtual machine */ Index *pIdx; /* For looping over indices of the table */ int nColumn; /* Number of columns in the data */ int nHidden = 0; /* Number of hidden columns if TABLE is virtual */ int iDataCur = 0; /* VDBE cursor that is the main data repository */ int iIdxCur = 0; /* First index cursor */ int ipkColumn = -1; /* Column that is the INTEGER PRIMARY KEY */ int endOfLoop; /* Label for the end of the insertion loop */ int srcTab = 0; /* Data comes from this temporary cursor if >=0 */ int addrInsTop = 0; /* Jump to label "D" */ int addrCont = 0; /* Top of insert loop. Label "C" in templates 3 and 4 */ SelectDest dest; /* Destination for SELECT on rhs of INSERT */ int iDb; /* Index of database holding TABLE */ u8 useTempTable = 0; /* Store SELECT results in intermediate table */ u8 appendFlag = 0; /* True if the insert is likely to be an append */ u8 withoutRowid; /* 0 for normal table. 1 for WITHOUT ROWID table */ u8 bIdListInOrder; /* True if IDLIST is in table order */ ExprList *pList = 0; /* List of VALUES() to be inserted */ /* Register allocations */ int regFromSelect = 0;/* Base register for data coming from SELECT */ int regAutoinc = 0; /* Register holding the AUTOINCREMENT counter */ int regRowCount = 0; /* Memory cell used for the row counter */ int regIns; /* Block of regs holding rowid+data being inserted */ int regRowid; /* registers holding insert rowid */ int regData; /* register holding first column to insert */ int *aRegIdx = 0; /* One register allocated to each index */ #ifndef SQLITE_OMIT_TRIGGER int isView; /* True if attempting to insert into a view */ Trigger *pTrigger; /* List of triggers on pTab, if required */ int tmask; /* Mask of trigger times */ #endif db = pParse->db; memset(&dest, 0, sizeof(dest)); if( pParse->nErr || db->mallocFailed ){ goto insert_cleanup; } /* If the Select object is really just a simple VALUES() list with a ** single row (the common case) then keep that one row of values ** and discard the other (unused) parts of the pSelect object */ if( pSelect && (pSelect->selFlags & SF_Values)!=0 && pSelect->pPrior==0 ){ pList = pSelect->pEList; pSelect->pEList = 0; sqlite3SelectDelete(db, pSelect); pSelect = 0; } /* Locate the table into which we will be inserting new information. */ assert( pTabList->nSrc==1 ); zTab = pTabList->a[0].zName; if( NEVER(zTab==0) ) goto insert_cleanup; pTab = sqlite3SrcListLookup(pParse, pTabList); if( pTab==0 ){ goto insert_cleanup; } iDb = sqlite3SchemaToIndex(db, pTab->pSchema); assert( iDbnDb ); if( sqlite3AuthCheck(pParse, SQLITE_INSERT, pTab->zName, 0, db->aDb[iDb].zDbSName) ){ goto insert_cleanup; } withoutRowid = !HasRowid(pTab); /* Figure out if we have any triggers and if the table being ** inserted into is a view */ #ifndef SQLITE_OMIT_TRIGGER pTrigger = sqlite3TriggersExist(pParse, pTab, TK_INSERT, 0, &tmask); isView = pTab->pSelect!=0; #else # define pTrigger 0 # define tmask 0 # define isView 0 #endif #ifdef SQLITE_OMIT_VIEW # undef isView # define isView 0 #endif assert( (pTrigger && tmask) || (pTrigger==0 && tmask==0) ); /* If pTab is really a view, make sure it has been initialized. ** ViewGetColumnNames() is a no-op if pTab is not a view. */ if( sqlite3ViewGetColumnNames(pParse, pTab) ){ goto insert_cleanup; } /* Cannot insert into a read-only table. */ if( sqlite3IsReadOnly(pParse, pTab, tmask) ){ goto insert_cleanup; } /* Allocate a VDBE */ v = sqlite3GetVdbe(pParse); if( v==0 ) goto insert_cleanup; if( pParse->nested==0 ) sqlite3VdbeCountChanges(v); sqlite3BeginWriteOperation(pParse, pSelect || pTrigger, iDb); #ifndef SQLITE_OMIT_XFER_OPT /* If the statement is of the form ** ** INSERT INTO SELECT * FROM ; ** ** Then special optimizations can be applied that make the transfer ** very fast and which reduce fragmentation of indices. ** ** This is the 2nd template. */ if( pColumn==0 && xferOptimization(pParse, pTab, pSelect, onError, iDb) ){ assert( !pTrigger ); assert( pList==0 ); goto insert_end; } #endif /* SQLITE_OMIT_XFER_OPT */ /* If this is an AUTOINCREMENT table, look up the sequence number in the ** sqlite_sequence table and store it in memory cell regAutoinc. */ regAutoinc = autoIncBegin(pParse, iDb, pTab); /* Allocate registers for holding the rowid of the new row, ** the content of the new row, and the assembled row record. */ regRowid = regIns = pParse->nMem+1; pParse->nMem += pTab->nCol + 1; if( IsVirtual(pTab) ){ regRowid++; pParse->nMem++; } regData = regRowid+1; /* If the INSERT statement included an IDLIST term, then make sure ** all elements of the IDLIST really are columns of the table and ** remember the column indices. ** ** If the table has an INTEGER PRIMARY KEY column and that column ** is named in the IDLIST, then record in the ipkColumn variable ** the index into IDLIST of the primary key column. ipkColumn is ** the index of the primary key as it appears in IDLIST, not as ** is appears in the original table. (The index of the INTEGER ** PRIMARY KEY in the original table is pTab->iPKey.) */ bIdListInOrder = (pTab->tabFlags & TF_OOOHidden)==0; if( pColumn ){ for(i=0; inId; i++){ pColumn->a[i].idx = -1; } for(i=0; inId; i++){ for(j=0; jnCol; j++){ if( sqlite3StrICmp(pColumn->a[i].zName, pTab->aCol[j].zName)==0 ){ pColumn->a[i].idx = j; if( i!=j ) bIdListInOrder = 0; if( j==pTab->iPKey ){ ipkColumn = i; assert( !withoutRowid ); } break; } } if( j>=pTab->nCol ){ if( sqlite3IsRowid(pColumn->a[i].zName) && !withoutRowid ){ ipkColumn = i; bIdListInOrder = 0; }else{ sqlite3ErrorMsg(pParse, "table %S has no column named %s", pTabList, 0, pColumn->a[i].zName); pParse->checkSchema = 1; goto insert_cleanup; } } } } /* Figure out how many columns of data are supplied. If the data ** is coming from a SELECT statement, then generate a co-routine that ** produces a single row of the SELECT on each invocation. The ** co-routine is the common header to the 3rd and 4th templates. */ if( pSelect ){ /* Data is coming from a SELECT or from a multi-row VALUES clause. ** Generate a co-routine to run the SELECT. */ int regYield; /* Register holding co-routine entry-point */ int addrTop; /* Top of the co-routine */ int rc; /* Result code */ regYield = ++pParse->nMem; addrTop = sqlite3VdbeCurrentAddr(v) + 1; sqlite3VdbeAddOp3(v, OP_InitCoroutine, regYield, 0, addrTop); sqlite3SelectDestInit(&dest, SRT_Coroutine, regYield); dest.iSdst = bIdListInOrder ? regData : 0; dest.nSdst = pTab->nCol; rc = sqlite3Select(pParse, pSelect, &dest); regFromSelect = dest.iSdst; if( rc || db->mallocFailed || pParse->nErr ) goto insert_cleanup; sqlite3VdbeEndCoroutine(v, regYield); sqlite3VdbeJumpHere(v, addrTop - 1); /* label B: */ assert( pSelect->pEList ); nColumn = pSelect->pEList->nExpr; /* Set useTempTable to TRUE if the result of the SELECT statement ** should be written into a temporary table (template 4). Set to ** FALSE if each output row of the SELECT can be written directly into ** the destination table (template 3). ** ** A temp table must be used if the table being updated is also one ** of the tables being read by the SELECT statement. Also use a ** temp table in the case of row triggers. */ if( pTrigger || readsTable(pParse, iDb, pTab) ){ useTempTable = 1; } if( useTempTable ){ /* Invoke the coroutine to extract information from the SELECT ** and add it to a transient table srcTab. The code generated ** here is from the 4th template: ** ** B: open temp table ** L: yield X, goto M at EOF ** insert row from R..R+n into temp table ** goto L ** M: ... */ int regRec; /* Register to hold packed record */ int regTempRowid; /* Register to hold temp table ROWID */ int addrL; /* Label "L" */ srcTab = pParse->nTab++; regRec = sqlite3GetTempReg(pParse); regTempRowid = sqlite3GetTempReg(pParse); sqlite3VdbeAddOp2(v, OP_OpenEphemeral, srcTab, nColumn); addrL = sqlite3VdbeAddOp1(v, OP_Yield, dest.iSDParm); VdbeCoverage(v); sqlite3VdbeAddOp3(v, OP_MakeRecord, regFromSelect, nColumn, regRec); sqlite3VdbeAddOp2(v, OP_NewRowid, srcTab, regTempRowid); sqlite3VdbeAddOp3(v, OP_Insert, srcTab, regRec, regTempRowid); sqlite3VdbeGoto(v, addrL); sqlite3VdbeJumpHere(v, addrL); sqlite3ReleaseTempReg(pParse, regRec); sqlite3ReleaseTempReg(pParse, regTempRowid); } }else{ /* This is the case if the data for the INSERT is coming from a ** single-row VALUES clause */ NameContext sNC; memset(&sNC, 0, sizeof(sNC)); sNC.pParse = pParse; srcTab = -1; assert( useTempTable==0 ); if( pList ){ nColumn = pList->nExpr; if( sqlite3ResolveExprListNames(&sNC, pList) ){ goto insert_cleanup; } }else{ nColumn = 0; } } /* If there is no IDLIST term but the table has an integer primary ** key, the set the ipkColumn variable to the integer primary key ** column index in the original table definition. */ if( pColumn==0 && nColumn>0 ){ ipkColumn = pTab->iPKey; } /* Make sure the number of columns in the source data matches the number ** of columns to be inserted into the table. */ for(i=0; inCol; i++){ nHidden += (IsHiddenColumn(&pTab->aCol[i]) ? 1 : 0); } if( pColumn==0 && nColumn && nColumn!=(pTab->nCol-nHidden) ){ sqlite3ErrorMsg(pParse, "table %S has %d columns but %d values were supplied", pTabList, 0, pTab->nCol-nHidden, nColumn); goto insert_cleanup; } if( pColumn!=0 && nColumn!=pColumn->nId ){ sqlite3ErrorMsg(pParse, "%d values for %d columns", nColumn, pColumn->nId); goto insert_cleanup; } /* Initialize the count of rows to be inserted */ if( db->flags & SQLITE_CountRows ){ regRowCount = ++pParse->nMem; sqlite3VdbeAddOp2(v, OP_Integer, 0, regRowCount); } /* If this is not a view, open the table and and all indices */ if( !isView ){ int nIdx; nIdx = sqlite3OpenTableAndIndices(pParse, pTab, OP_OpenWrite, 0, -1, 0, &iDataCur, &iIdxCur); aRegIdx = sqlite3DbMallocRawNN(db, sizeof(int)*(nIdx+1)); if( aRegIdx==0 ){ goto insert_cleanup; } for(i=0; inMem; } } /* This is the top of the main insertion loop */ if( useTempTable ){ /* This block codes the top of loop only. The complete loop is the ** following pseudocode (template 4): ** ** rewind temp table, if empty goto D ** C: loop over rows of intermediate table ** transfer values form intermediate table into
    ** end loop ** D: ... */ addrInsTop = sqlite3VdbeAddOp1(v, OP_Rewind, srcTab); VdbeCoverage(v); addrCont = sqlite3VdbeCurrentAddr(v); }else if( pSelect ){ /* This block codes the top of loop only. The complete loop is the ** following pseudocode (template 3): ** ** C: yield X, at EOF goto D ** insert the select result into
    from R..R+n ** goto C ** D: ... */ addrInsTop = addrCont = sqlite3VdbeAddOp1(v, OP_Yield, dest.iSDParm); VdbeCoverage(v); } /* Run the BEFORE and INSTEAD OF triggers, if there are any */ endOfLoop = sqlite3VdbeMakeLabel(v); if( tmask & TRIGGER_BEFORE ){ int regCols = sqlite3GetTempRange(pParse, pTab->nCol+1); /* build the NEW.* reference row. Note that if there is an INTEGER ** PRIMARY KEY into which a NULL is being inserted, that NULL will be ** translated into a unique ID for the row. But on a BEFORE trigger, ** we do not know what the unique ID will be (because the insert has ** not happened yet) so we substitute a rowid of -1 */ if( ipkColumn<0 ){ sqlite3VdbeAddOp2(v, OP_Integer, -1, regCols); }else{ int addr1; assert( !withoutRowid ); if( useTempTable ){ sqlite3VdbeAddOp3(v, OP_Column, srcTab, ipkColumn, regCols); }else{ assert( pSelect==0 ); /* Otherwise useTempTable is true */ sqlite3ExprCode(pParse, pList->a[ipkColumn].pExpr, regCols); } addr1 = sqlite3VdbeAddOp1(v, OP_NotNull, regCols); VdbeCoverage(v); sqlite3VdbeAddOp2(v, OP_Integer, -1, regCols); sqlite3VdbeJumpHere(v, addr1); sqlite3VdbeAddOp1(v, OP_MustBeInt, regCols); VdbeCoverage(v); } /* Cannot have triggers on a virtual table. If it were possible, ** this block would have to account for hidden column. */ assert( !IsVirtual(pTab) ); /* Create the new column data */ for(i=j=0; inCol; i++){ if( pColumn ){ for(j=0; jnId; j++){ if( pColumn->a[j].idx==i ) break; } } if( (!useTempTable && !pList) || (pColumn && j>=pColumn->nId) || (pColumn==0 && IsOrdinaryHiddenColumn(&pTab->aCol[i])) ){ sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, regCols+i+1); }else if( useTempTable ){ sqlite3VdbeAddOp3(v, OP_Column, srcTab, j, regCols+i+1); }else{ assert( pSelect==0 ); /* Otherwise useTempTable is true */ sqlite3ExprCodeAndCache(pParse, pList->a[j].pExpr, regCols+i+1); } if( pColumn==0 && !IsOrdinaryHiddenColumn(&pTab->aCol[i]) ) j++; } /* If this is an INSERT on a view with an INSTEAD OF INSERT trigger, ** do not attempt any conversions before assembling the record. ** If this is a real table, attempt conversions as required by the ** table column affinities. */ if( !isView ){ sqlite3TableAffinity(v, pTab, regCols+1); } /* Fire BEFORE or INSTEAD OF triggers */ sqlite3CodeRowTrigger(pParse, pTrigger, TK_INSERT, 0, TRIGGER_BEFORE, pTab, regCols-pTab->nCol-1, onError, endOfLoop); sqlite3ReleaseTempRange(pParse, regCols, pTab->nCol+1); } /* Compute the content of the next row to insert into a range of ** registers beginning at regIns. */ if( !isView ){ if( IsVirtual(pTab) ){ /* The row that the VUpdate opcode will delete: none */ sqlite3VdbeAddOp2(v, OP_Null, 0, regIns); } if( ipkColumn>=0 ){ if( useTempTable ){ sqlite3VdbeAddOp3(v, OP_Column, srcTab, ipkColumn, regRowid); }else if( pSelect ){ sqlite3VdbeAddOp2(v, OP_Copy, regFromSelect+ipkColumn, regRowid); }else{ VdbeOp *pOp; sqlite3ExprCode(pParse, pList->a[ipkColumn].pExpr, regRowid); pOp = sqlite3VdbeGetOp(v, -1); if( ALWAYS(pOp) && pOp->opcode==OP_Null && !IsVirtual(pTab) ){ appendFlag = 1; pOp->opcode = OP_NewRowid; pOp->p1 = iDataCur; pOp->p2 = regRowid; pOp->p3 = regAutoinc; } } /* If the PRIMARY KEY expression is NULL, then use OP_NewRowid ** to generate a unique primary key value. */ if( !appendFlag ){ int addr1; if( !IsVirtual(pTab) ){ addr1 = sqlite3VdbeAddOp1(v, OP_NotNull, regRowid); VdbeCoverage(v); sqlite3VdbeAddOp3(v, OP_NewRowid, iDataCur, regRowid, regAutoinc); sqlite3VdbeJumpHere(v, addr1); }else{ addr1 = sqlite3VdbeCurrentAddr(v); sqlite3VdbeAddOp2(v, OP_IsNull, regRowid, addr1+2); VdbeCoverage(v); } sqlite3VdbeAddOp1(v, OP_MustBeInt, regRowid); VdbeCoverage(v); } }else if( IsVirtual(pTab) || withoutRowid ){ sqlite3VdbeAddOp2(v, OP_Null, 0, regRowid); }else{ sqlite3VdbeAddOp3(v, OP_NewRowid, iDataCur, regRowid, regAutoinc); appendFlag = 1; } autoIncStep(pParse, regAutoinc, regRowid); /* Compute data for all columns of the new entry, beginning ** with the first column. */ nHidden = 0; for(i=0; inCol; i++){ int iRegStore = regRowid+1+i; if( i==pTab->iPKey ){ /* The value of the INTEGER PRIMARY KEY column is always a NULL. ** Whenever this column is read, the rowid will be substituted ** in its place. Hence, fill this column with a NULL to avoid ** taking up data space with information that will never be used. ** As there may be shallow copies of this value, make it a soft-NULL */ sqlite3VdbeAddOp1(v, OP_SoftNull, iRegStore); continue; } if( pColumn==0 ){ if( IsHiddenColumn(&pTab->aCol[i]) ){ j = -1; nHidden++; }else{ j = i - nHidden; } }else{ for(j=0; jnId; j++){ if( pColumn->a[j].idx==i ) break; } } if( j<0 || nColumn==0 || (pColumn && j>=pColumn->nId) ){ sqlite3ExprCodeFactorable(pParse, pTab->aCol[i].pDflt, iRegStore); }else if( useTempTable ){ sqlite3VdbeAddOp3(v, OP_Column, srcTab, j, iRegStore); }else if( pSelect ){ if( regFromSelect!=regData ){ sqlite3VdbeAddOp2(v, OP_SCopy, regFromSelect+j, iRegStore); } }else{ sqlite3ExprCode(pParse, pList->a[j].pExpr, iRegStore); } } /* Generate code to check constraints and generate index keys and ** do the insertion. */ #ifndef SQLITE_OMIT_VIRTUALTABLE if( IsVirtual(pTab) ){ const char *pVTab = (const char *)sqlite3GetVTable(db, pTab); sqlite3VtabMakeWritable(pParse, pTab); sqlite3VdbeAddOp4(v, OP_VUpdate, 1, pTab->nCol+2, regIns, pVTab, P4_VTAB); sqlite3VdbeChangeP5(v, onError==OE_Default ? OE_Abort : onError); sqlite3MayAbort(pParse); }else #endif { int isReplace; /* Set to true if constraints may cause a replace */ sqlite3GenerateConstraintChecks(pParse, pTab, aRegIdx, iDataCur, iIdxCur, regIns, 0, ipkColumn>=0, onError, endOfLoop, &isReplace, 0 ); sqlite3FkCheck(pParse, pTab, 0, regIns, 0, 0); sqlite3CompleteInsertion(pParse, pTab, iDataCur, iIdxCur, regIns, aRegIdx, 0, appendFlag, isReplace==0); } } /* Update the count of rows that are inserted */ if( (db->flags & SQLITE_CountRows)!=0 ){ sqlite3VdbeAddOp2(v, OP_AddImm, regRowCount, 1); } if( pTrigger ){ /* Code AFTER triggers */ sqlite3CodeRowTrigger(pParse, pTrigger, TK_INSERT, 0, TRIGGER_AFTER, pTab, regData-2-pTab->nCol, onError, endOfLoop); } /* The bottom of the main insertion loop, if the data source ** is a SELECT statement. */ sqlite3VdbeResolveLabel(v, endOfLoop); if( useTempTable ){ sqlite3VdbeAddOp2(v, OP_Next, srcTab, addrCont); VdbeCoverage(v); sqlite3VdbeJumpHere(v, addrInsTop); sqlite3VdbeAddOp1(v, OP_Close, srcTab); }else if( pSelect ){ sqlite3VdbeGoto(v, addrCont); sqlite3VdbeJumpHere(v, addrInsTop); } if( !IsVirtual(pTab) && !isView ){ /* Close all tables opened */ if( iDataCurpIndex; pIdx; pIdx=pIdx->pNext, idx++){ sqlite3VdbeAddOp1(v, OP_Close, idx+iIdxCur); } } insert_end: /* Update the sqlite_sequence table by storing the content of the ** maximum rowid counter values recorded while inserting into ** autoincrement tables. */ if( pParse->nested==0 && pParse->pTriggerTab==0 ){ sqlite3AutoincrementEnd(pParse); } /* ** Return the number of rows inserted. If this routine is ** generating code because of a call to sqlite3NestedParse(), do not ** invoke the callback function. */ if( (db->flags&SQLITE_CountRows) && !pParse->nested && !pParse->pTriggerTab ){ sqlite3VdbeAddOp2(v, OP_ResultRow, regRowCount, 1); sqlite3VdbeSetNumCols(v, 1); sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows inserted", SQLITE_STATIC); } insert_cleanup: sqlite3SrcListDelete(db, pTabList); sqlite3ExprListDelete(db, pList); sqlite3SelectDelete(db, pSelect); sqlite3IdListDelete(db, pColumn); sqlite3DbFree(db, aRegIdx); } /* Make sure "isView" and other macros defined above are undefined. Otherwise ** they may interfere with compilation of other functions in this file ** (or in another file, if this file becomes part of the amalgamation). */ #ifdef isView #undef isView #endif #ifdef pTrigger #undef pTrigger #endif #ifdef tmask #undef tmask #endif /* ** Meanings of bits in of pWalker->eCode for checkConstraintUnchanged() */ #define CKCNSTRNT_COLUMN 0x01 /* CHECK constraint uses a changing column */ #define CKCNSTRNT_ROWID 0x02 /* CHECK constraint references the ROWID */ /* This is the Walker callback from checkConstraintUnchanged(). Set ** bit 0x01 of pWalker->eCode if ** pWalker->eCode to 0 if this expression node references any of the ** columns that are being modifed by an UPDATE statement. */ static int checkConstraintExprNode(Walker *pWalker, Expr *pExpr){ if( pExpr->op==TK_COLUMN ){ assert( pExpr->iColumn>=0 || pExpr->iColumn==-1 ); if( pExpr->iColumn>=0 ){ if( pWalker->u.aiCol[pExpr->iColumn]>=0 ){ pWalker->eCode |= CKCNSTRNT_COLUMN; } }else{ pWalker->eCode |= CKCNSTRNT_ROWID; } } return WRC_Continue; } /* ** pExpr is a CHECK constraint on a row that is being UPDATE-ed. The ** only columns that are modified by the UPDATE are those for which ** aiChng[i]>=0, and also the ROWID is modified if chngRowid is true. ** ** Return true if CHECK constraint pExpr does not use any of the ** changing columns (or the rowid if it is changing). In other words, ** return true if this CHECK constraint can be skipped when validating ** the new row in the UPDATE statement. */ static int checkConstraintUnchanged(Expr *pExpr, int *aiChng, int chngRowid){ Walker w; memset(&w, 0, sizeof(w)); w.eCode = 0; w.xExprCallback = checkConstraintExprNode; w.u.aiCol = aiChng; sqlite3WalkExpr(&w, pExpr); if( !chngRowid ){ testcase( (w.eCode & CKCNSTRNT_ROWID)!=0 ); w.eCode &= ~CKCNSTRNT_ROWID; } testcase( w.eCode==0 ); testcase( w.eCode==CKCNSTRNT_COLUMN ); testcase( w.eCode==CKCNSTRNT_ROWID ); testcase( w.eCode==(CKCNSTRNT_ROWID|CKCNSTRNT_COLUMN) ); return !w.eCode; } /* ** Generate code to do constraint checks prior to an INSERT or an UPDATE ** on table pTab. ** ** The regNewData parameter is the first register in a range that contains ** the data to be inserted or the data after the update. There will be ** pTab->nCol+1 registers in this range. The first register (the one ** that regNewData points to) will contain the new rowid, or NULL in the ** case of a WITHOUT ROWID table. The second register in the range will ** contain the content of the first table column. The third register will ** contain the content of the second table column. And so forth. ** ** The regOldData parameter is similar to regNewData except that it contains ** the data prior to an UPDATE rather than afterwards. regOldData is zero ** for an INSERT. This routine can distinguish between UPDATE and INSERT by ** checking regOldData for zero. ** ** For an UPDATE, the pkChng boolean is true if the true primary key (the ** rowid for a normal table or the PRIMARY KEY for a WITHOUT ROWID table) ** might be modified by the UPDATE. If pkChng is false, then the key of ** the iDataCur content table is guaranteed to be unchanged by the UPDATE. ** ** For an INSERT, the pkChng boolean indicates whether or not the rowid ** was explicitly specified as part of the INSERT statement. If pkChng ** is zero, it means that the either rowid is computed automatically or ** that the table is a WITHOUT ROWID table and has no rowid. On an INSERT, ** pkChng will only be true if the INSERT statement provides an integer ** value for either the rowid column or its INTEGER PRIMARY KEY alias. ** ** The code generated by this routine will store new index entries into ** registers identified by aRegIdx[]. No index entry is created for ** indices where aRegIdx[i]==0. The order of indices in aRegIdx[] is ** the same as the order of indices on the linked list of indices ** at pTab->pIndex. ** ** The caller must have already opened writeable cursors on the main ** table and all applicable indices (that is to say, all indices for which ** aRegIdx[] is not zero). iDataCur is the cursor for the main table when ** inserting or updating a rowid table, or the cursor for the PRIMARY KEY ** index when operating on a WITHOUT ROWID table. iIdxCur is the cursor ** for the first index in the pTab->pIndex list. Cursors for other indices ** are at iIdxCur+N for the N-th element of the pTab->pIndex list. ** ** This routine also generates code to check constraints. NOT NULL, ** CHECK, and UNIQUE constraints are all checked. If a constraint fails, ** then the appropriate action is performed. There are five possible ** actions: ROLLBACK, ABORT, FAIL, REPLACE, and IGNORE. ** ** Constraint type Action What Happens ** --------------- ---------- ---------------------------------------- ** any ROLLBACK The current transaction is rolled back and ** sqlite3_step() returns immediately with a ** return code of SQLITE_CONSTRAINT. ** ** any ABORT Back out changes from the current command ** only (do not do a complete rollback) then ** cause sqlite3_step() to return immediately ** with SQLITE_CONSTRAINT. ** ** any FAIL Sqlite3_step() returns immediately with a ** return code of SQLITE_CONSTRAINT. The ** transaction is not rolled back and any ** changes to prior rows are retained. ** ** any IGNORE The attempt in insert or update the current ** row is skipped, without throwing an error. ** Processing continues with the next row. ** (There is an immediate jump to ignoreDest.) ** ** NOT NULL REPLACE The NULL value is replace by the default ** value for that column. If the default value ** is NULL, the action is the same as ABORT. ** ** UNIQUE REPLACE The other row that conflicts with the row ** being inserted is removed. ** ** CHECK REPLACE Illegal. The results in an exception. ** ** Which action to take is determined by the overrideError parameter. ** Or if overrideError==OE_Default, then the pParse->onError parameter ** is used. Or if pParse->onError==OE_Default then the onError value ** for the constraint is used. */ SQLITE_PRIVATE void sqlite3GenerateConstraintChecks( Parse *pParse, /* The parser context */ Table *pTab, /* The table being inserted or updated */ int *aRegIdx, /* Use register aRegIdx[i] for index i. 0 for unused */ int iDataCur, /* Canonical data cursor (main table or PK index) */ int iIdxCur, /* First index cursor */ int regNewData, /* First register in a range holding values to insert */ int regOldData, /* Previous content. 0 for INSERTs */ u8 pkChng, /* Non-zero if the rowid or PRIMARY KEY changed */ u8 overrideError, /* Override onError to this if not OE_Default */ int ignoreDest, /* Jump to this label on an OE_Ignore resolution */ int *pbMayReplace, /* OUT: Set to true if constraint may cause a replace */ int *aiChng /* column i is unchanged if aiChng[i]<0 */ ){ Vdbe *v; /* VDBE under constrution */ Index *pIdx; /* Pointer to one of the indices */ Index *pPk = 0; /* The PRIMARY KEY index */ sqlite3 *db; /* Database connection */ int i; /* loop counter */ int ix; /* Index loop counter */ int nCol; /* Number of columns */ int onError; /* Conflict resolution strategy */ int addr1; /* Address of jump instruction */ int seenReplace = 0; /* True if REPLACE is used to resolve INT PK conflict */ int nPkField; /* Number of fields in PRIMARY KEY. 1 for ROWID tables */ int ipkTop = 0; /* Top of the rowid change constraint check */ int ipkBottom = 0; /* Bottom of the rowid change constraint check */ u8 isUpdate; /* True if this is an UPDATE operation */ u8 bAffinityDone = 0; /* True if the OP_Affinity operation has been run */ int regRowid = -1; /* Register holding ROWID value */ isUpdate = regOldData!=0; db = pParse->db; v = sqlite3GetVdbe(pParse); assert( v!=0 ); assert( pTab->pSelect==0 ); /* This table is not a VIEW */ nCol = pTab->nCol; /* pPk is the PRIMARY KEY index for WITHOUT ROWID tables and NULL for ** normal rowid tables. nPkField is the number of key fields in the ** pPk index or 1 for a rowid table. In other words, nPkField is the ** number of fields in the true primary key of the table. */ if( HasRowid(pTab) ){ pPk = 0; nPkField = 1; }else{ pPk = sqlite3PrimaryKeyIndex(pTab); nPkField = pPk->nKeyCol; } /* Record that this module has started */ VdbeModuleComment((v, "BEGIN: GenCnstCks(%d,%d,%d,%d,%d)", iDataCur, iIdxCur, regNewData, regOldData, pkChng)); /* Test all NOT NULL constraints. */ for(i=0; iiPKey ){ continue; /* ROWID is never NULL */ } if( aiChng && aiChng[i]<0 ){ /* Don't bother checking for NOT NULL on columns that do not change */ continue; } onError = pTab->aCol[i].notNull; if( onError==OE_None ) continue; /* This column is allowed to be NULL */ if( overrideError!=OE_Default ){ onError = overrideError; }else if( onError==OE_Default ){ onError = OE_Abort; } if( onError==OE_Replace && pTab->aCol[i].pDflt==0 ){ onError = OE_Abort; } assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail || onError==OE_Ignore || onError==OE_Replace ); switch( onError ){ case OE_Abort: sqlite3MayAbort(pParse); /* Fall through */ case OE_Rollback: case OE_Fail: { char *zMsg = sqlite3MPrintf(db, "%s.%s", pTab->zName, pTab->aCol[i].zName); sqlite3VdbeAddOp4(v, OP_HaltIfNull, SQLITE_CONSTRAINT_NOTNULL, onError, regNewData+1+i, zMsg, P4_DYNAMIC); sqlite3VdbeChangeP5(v, P5_ConstraintNotNull); VdbeCoverage(v); break; } case OE_Ignore: { sqlite3VdbeAddOp2(v, OP_IsNull, regNewData+1+i, ignoreDest); VdbeCoverage(v); break; } default: { assert( onError==OE_Replace ); addr1 = sqlite3VdbeAddOp1(v, OP_NotNull, regNewData+1+i); VdbeCoverage(v); sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, regNewData+1+i); sqlite3VdbeJumpHere(v, addr1); break; } } } /* Test all CHECK constraints */ #ifndef SQLITE_OMIT_CHECK if( pTab->pCheck && (db->flags & SQLITE_IgnoreChecks)==0 ){ ExprList *pCheck = pTab->pCheck; pParse->ckBase = regNewData+1; onError = overrideError!=OE_Default ? overrideError : OE_Abort; for(i=0; inExpr; i++){ int allOk; Expr *pExpr = pCheck->a[i].pExpr; if( aiChng && checkConstraintUnchanged(pExpr, aiChng, pkChng) ) continue; allOk = sqlite3VdbeMakeLabel(v); sqlite3ExprIfTrue(pParse, pExpr, allOk, SQLITE_JUMPIFNULL); if( onError==OE_Ignore ){ sqlite3VdbeGoto(v, ignoreDest); }else{ char *zName = pCheck->a[i].zName; if( zName==0 ) zName = pTab->zName; if( onError==OE_Replace ) onError = OE_Abort; /* IMP: R-15569-63625 */ sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_CHECK, onError, zName, P4_TRANSIENT, P5_ConstraintCheck); } sqlite3VdbeResolveLabel(v, allOk); } } #endif /* !defined(SQLITE_OMIT_CHECK) */ /* If rowid is changing, make sure the new rowid does not previously ** exist in the table. */ if( pkChng && pPk==0 ){ int addrRowidOk = sqlite3VdbeMakeLabel(v); /* Figure out what action to take in case of a rowid collision */ onError = pTab->keyConf; if( overrideError!=OE_Default ){ onError = overrideError; }else if( onError==OE_Default ){ onError = OE_Abort; } if( isUpdate ){ /* pkChng!=0 does not mean that the rowid has change, only that ** it might have changed. Skip the conflict logic below if the rowid ** is unchanged. */ sqlite3VdbeAddOp3(v, OP_Eq, regNewData, addrRowidOk, regOldData); sqlite3VdbeChangeP5(v, SQLITE_NOTNULL); VdbeCoverage(v); } /* If the response to a rowid conflict is REPLACE but the response ** to some other UNIQUE constraint is FAIL or IGNORE, then we need ** to defer the running of the rowid conflict checking until after ** the UNIQUE constraints have run. */ if( onError==OE_Replace && overrideError!=OE_Replace ){ for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){ if( pIdx->onError==OE_Ignore || pIdx->onError==OE_Fail ){ ipkTop = sqlite3VdbeAddOp0(v, OP_Goto); break; } } } /* Check to see if the new rowid already exists in the table. Skip ** the following conflict logic if it does not. */ sqlite3VdbeAddOp3(v, OP_NotExists, iDataCur, addrRowidOk, regNewData); VdbeCoverage(v); /* Generate code that deals with a rowid collision */ switch( onError ){ default: { onError = OE_Abort; /* Fall thru into the next case */ } case OE_Rollback: case OE_Abort: case OE_Fail: { sqlite3RowidConstraint(pParse, onError, pTab); break; } case OE_Replace: { /* If there are DELETE triggers on this table and the ** recursive-triggers flag is set, call GenerateRowDelete() to ** remove the conflicting row from the table. This will fire ** the triggers and remove both the table and index b-tree entries. ** ** Otherwise, if there are no triggers or the recursive-triggers ** flag is not set, but the table has one or more indexes, call ** GenerateRowIndexDelete(). This removes the index b-tree entries ** only. The table b-tree entry will be replaced by the new entry ** when it is inserted. ** ** If either GenerateRowDelete() or GenerateRowIndexDelete() is called, ** also invoke MultiWrite() to indicate that this VDBE may require ** statement rollback (if the statement is aborted after the delete ** takes place). Earlier versions called sqlite3MultiWrite() regardless, ** but being more selective here allows statements like: ** ** REPLACE INTO t(rowid) VALUES($newrowid) ** ** to run without a statement journal if there are no indexes on the ** table. */ Trigger *pTrigger = 0; if( db->flags&SQLITE_RecTriggers ){ pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0); } if( pTrigger || sqlite3FkRequired(pParse, pTab, 0, 0) ){ sqlite3MultiWrite(pParse); sqlite3GenerateRowDelete(pParse, pTab, pTrigger, iDataCur, iIdxCur, regNewData, 1, 0, OE_Replace, 1, -1); }else{ #ifdef SQLITE_ENABLE_PREUPDATE_HOOK if( HasRowid(pTab) ){ /* This OP_Delete opcode fires the pre-update-hook only. It does ** not modify the b-tree. It is more efficient to let the coming ** OP_Insert replace the existing entry than it is to delete the ** existing entry and then insert a new one. */ sqlite3VdbeAddOp2(v, OP_Delete, iDataCur, OPFLAG_ISNOOP); sqlite3VdbeChangeP4(v, -1, (char *)pTab, P4_TABLE); } #endif /* SQLITE_ENABLE_PREUPDATE_HOOK */ if( pTab->pIndex ){ sqlite3MultiWrite(pParse); sqlite3GenerateRowIndexDelete(pParse, pTab, iDataCur, iIdxCur,0,-1); } } seenReplace = 1; break; } case OE_Ignore: { /*assert( seenReplace==0 );*/ sqlite3VdbeGoto(v, ignoreDest); break; } } sqlite3VdbeResolveLabel(v, addrRowidOk); if( ipkTop ){ ipkBottom = sqlite3VdbeAddOp0(v, OP_Goto); sqlite3VdbeJumpHere(v, ipkTop); } } /* Test all UNIQUE constraints by creating entries for each UNIQUE ** index and making sure that duplicate entries do not already exist. ** Compute the revised record entries for indices as we go. ** ** This loop also handles the case of the PRIMARY KEY index for a ** WITHOUT ROWID table. */ for(ix=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, ix++){ int regIdx; /* Range of registers hold conent for pIdx */ int regR; /* Range of registers holding conflicting PK */ int iThisCur; /* Cursor for this UNIQUE index */ int addrUniqueOk; /* Jump here if the UNIQUE constraint is satisfied */ if( aRegIdx[ix]==0 ) continue; /* Skip indices that do not change */ if( bAffinityDone==0 ){ sqlite3TableAffinity(v, pTab, regNewData+1); bAffinityDone = 1; } iThisCur = iIdxCur+ix; addrUniqueOk = sqlite3VdbeMakeLabel(v); /* Skip partial indices for which the WHERE clause is not true */ if( pIdx->pPartIdxWhere ){ sqlite3VdbeAddOp2(v, OP_Null, 0, aRegIdx[ix]); pParse->ckBase = regNewData+1; sqlite3ExprIfFalseDup(pParse, pIdx->pPartIdxWhere, addrUniqueOk, SQLITE_JUMPIFNULL); pParse->ckBase = 0; } /* Create a record for this index entry as it should appear after ** the insert or update. Store that record in the aRegIdx[ix] register */ regIdx = sqlite3GetTempRange(pParse, pIdx->nColumn); for(i=0; inColumn; i++){ int iField = pIdx->aiColumn[i]; int x; if( iField==XN_EXPR ){ pParse->ckBase = regNewData+1; sqlite3ExprCodeCopy(pParse, pIdx->aColExpr->a[i].pExpr, regIdx+i); pParse->ckBase = 0; VdbeComment((v, "%s column %d", pIdx->zName, i)); }else{ if( iField==XN_ROWID || iField==pTab->iPKey ){ if( regRowid==regIdx+i ) continue; /* ROWID already in regIdx+i */ x = regNewData; regRowid = pIdx->pPartIdxWhere ? -1 : regIdx+i; }else{ x = iField + regNewData + 1; } sqlite3VdbeAddOp2(v, iField<0 ? OP_IntCopy : OP_SCopy, x, regIdx+i); VdbeComment((v, "%s", iField<0 ? "rowid" : pTab->aCol[iField].zName)); } } sqlite3VdbeAddOp3(v, OP_MakeRecord, regIdx, pIdx->nColumn, aRegIdx[ix]); VdbeComment((v, "for %s", pIdx->zName)); sqlite3ExprCacheAffinityChange(pParse, regIdx, pIdx->nColumn); /* In an UPDATE operation, if this index is the PRIMARY KEY index ** of a WITHOUT ROWID table and there has been no change the ** primary key, then no collision is possible. The collision detection ** logic below can all be skipped. */ if( isUpdate && pPk==pIdx && pkChng==0 ){ sqlite3VdbeResolveLabel(v, addrUniqueOk); continue; } /* Find out what action to take in case there is a uniqueness conflict */ onError = pIdx->onError; if( onError==OE_None ){ sqlite3ReleaseTempRange(pParse, regIdx, pIdx->nColumn); sqlite3VdbeResolveLabel(v, addrUniqueOk); continue; /* pIdx is not a UNIQUE index */ } if( overrideError!=OE_Default ){ onError = overrideError; }else if( onError==OE_Default ){ onError = OE_Abort; } /* Check to see if the new index entry will be unique */ sqlite3VdbeAddOp4Int(v, OP_NoConflict, iThisCur, addrUniqueOk, regIdx, pIdx->nKeyCol); VdbeCoverage(v); /* Generate code to handle collisions */ regR = (pIdx==pPk) ? regIdx : sqlite3GetTempRange(pParse, nPkField); if( isUpdate || onError==OE_Replace ){ if( HasRowid(pTab) ){ sqlite3VdbeAddOp2(v, OP_IdxRowid, iThisCur, regR); /* Conflict only if the rowid of the existing index entry ** is different from old-rowid */ if( isUpdate ){ sqlite3VdbeAddOp3(v, OP_Eq, regR, addrUniqueOk, regOldData); sqlite3VdbeChangeP5(v, SQLITE_NOTNULL); VdbeCoverage(v); } }else{ int x; /* Extract the PRIMARY KEY from the end of the index entry and ** store it in registers regR..regR+nPk-1 */ if( pIdx!=pPk ){ for(i=0; inKeyCol; i++){ assert( pPk->aiColumn[i]>=0 ); x = sqlite3ColumnOfIndex(pIdx, pPk->aiColumn[i]); sqlite3VdbeAddOp3(v, OP_Column, iThisCur, x, regR+i); VdbeComment((v, "%s.%s", pTab->zName, pTab->aCol[pPk->aiColumn[i]].zName)); } } if( isUpdate ){ /* If currently processing the PRIMARY KEY of a WITHOUT ROWID ** table, only conflict if the new PRIMARY KEY values are actually ** different from the old. ** ** For a UNIQUE index, only conflict if the PRIMARY KEY values ** of the matched index row are different from the original PRIMARY ** KEY values of this row before the update. */ int addrJump = sqlite3VdbeCurrentAddr(v)+pPk->nKeyCol; int op = OP_Ne; int regCmp = (IsPrimaryKeyIndex(pIdx) ? regIdx : regR); for(i=0; inKeyCol; i++){ char *p4 = (char*)sqlite3LocateCollSeq(pParse, pPk->azColl[i]); x = pPk->aiColumn[i]; assert( x>=0 ); if( i==(pPk->nKeyCol-1) ){ addrJump = addrUniqueOk; op = OP_Eq; } sqlite3VdbeAddOp4(v, op, regOldData+1+x, addrJump, regCmp+i, p4, P4_COLLSEQ ); sqlite3VdbeChangeP5(v, SQLITE_NOTNULL); VdbeCoverageIf(v, op==OP_Eq); VdbeCoverageIf(v, op==OP_Ne); } } } } /* Generate code that executes if the new index entry is not unique */ assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail || onError==OE_Ignore || onError==OE_Replace ); switch( onError ){ case OE_Rollback: case OE_Abort: case OE_Fail: { sqlite3UniqueConstraint(pParse, onError, pIdx); break; } case OE_Ignore: { sqlite3VdbeGoto(v, ignoreDest); break; } default: { Trigger *pTrigger = 0; assert( onError==OE_Replace ); sqlite3MultiWrite(pParse); if( db->flags&SQLITE_RecTriggers ){ pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0); } sqlite3GenerateRowDelete(pParse, pTab, pTrigger, iDataCur, iIdxCur, regR, nPkField, 0, OE_Replace, (pIdx==pPk ? ONEPASS_SINGLE : ONEPASS_OFF), -1); seenReplace = 1; break; } } sqlite3VdbeResolveLabel(v, addrUniqueOk); sqlite3ReleaseTempRange(pParse, regIdx, pIdx->nColumn); if( regR!=regIdx ) sqlite3ReleaseTempRange(pParse, regR, nPkField); } if( ipkTop ){ sqlite3VdbeGoto(v, ipkTop+1); sqlite3VdbeJumpHere(v, ipkBottom); } *pbMayReplace = seenReplace; VdbeModuleComment((v, "END: GenCnstCks(%d)", seenReplace)); } /* ** This routine generates code to finish the INSERT or UPDATE operation ** that was started by a prior call to sqlite3GenerateConstraintChecks. ** A consecutive range of registers starting at regNewData contains the ** rowid and the content to be inserted. ** ** The arguments to this routine should be the same as the first six ** arguments to sqlite3GenerateConstraintChecks. */ SQLITE_PRIVATE void sqlite3CompleteInsertion( Parse *pParse, /* The parser context */ Table *pTab, /* the table into which we are inserting */ int iDataCur, /* Cursor of the canonical data source */ int iIdxCur, /* First index cursor */ int regNewData, /* Range of content */ int *aRegIdx, /* Register used by each index. 0 for unused indices */ int isUpdate, /* True for UPDATE, False for INSERT */ int appendBias, /* True if this is likely to be an append */ int useSeekResult /* True to set the USESEEKRESULT flag on OP_[Idx]Insert */ ){ Vdbe *v; /* Prepared statements under construction */ Index *pIdx; /* An index being inserted or updated */ u8 pik_flags; /* flag values passed to the btree insert */ int regData; /* Content registers (after the rowid) */ int regRec; /* Register holding assembled record for the table */ int i; /* Loop counter */ u8 bAffinityDone = 0; /* True if OP_Affinity has been run already */ v = sqlite3GetVdbe(pParse); assert( v!=0 ); assert( pTab->pSelect==0 ); /* This table is not a VIEW */ for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){ if( aRegIdx[i]==0 ) continue; bAffinityDone = 1; if( pIdx->pPartIdxWhere ){ sqlite3VdbeAddOp2(v, OP_IsNull, aRegIdx[i], sqlite3VdbeCurrentAddr(v)+2); VdbeCoverage(v); } sqlite3VdbeAddOp2(v, OP_IdxInsert, iIdxCur+i, aRegIdx[i]); pik_flags = 0; if( useSeekResult ) pik_flags = OPFLAG_USESEEKRESULT; if( IsPrimaryKeyIndex(pIdx) && !HasRowid(pTab) ){ assert( pParse->nested==0 ); pik_flags |= OPFLAG_NCHANGE; } sqlite3VdbeChangeP5(v, pik_flags); } if( !HasRowid(pTab) ) return; regData = regNewData + 1; regRec = sqlite3GetTempReg(pParse); sqlite3VdbeAddOp3(v, OP_MakeRecord, regData, pTab->nCol, regRec); if( !bAffinityDone ) sqlite3TableAffinity(v, pTab, 0); sqlite3ExprCacheAffinityChange(pParse, regData, pTab->nCol); if( pParse->nested ){ pik_flags = 0; }else{ pik_flags = OPFLAG_NCHANGE; pik_flags |= (isUpdate?OPFLAG_ISUPDATE:OPFLAG_LASTROWID); } if( appendBias ){ pik_flags |= OPFLAG_APPEND; } if( useSeekResult ){ pik_flags |= OPFLAG_USESEEKRESULT; } sqlite3VdbeAddOp3(v, OP_Insert, iDataCur, regRec, regNewData); if( !pParse->nested ){ sqlite3VdbeChangeP4(v, -1, (char *)pTab, P4_TABLE); } sqlite3VdbeChangeP5(v, pik_flags); } /* ** Allocate cursors for the pTab table and all its indices and generate ** code to open and initialized those cursors. ** ** The cursor for the object that contains the complete data (normally ** the table itself, but the PRIMARY KEY index in the case of a WITHOUT ** ROWID table) is returned in *piDataCur. The first index cursor is ** returned in *piIdxCur. The number of indices is returned. ** ** Use iBase as the first cursor (either the *piDataCur for rowid tables ** or the first index for WITHOUT ROWID tables) if it is non-negative. ** If iBase is negative, then allocate the next available cursor. ** ** For a rowid table, *piDataCur will be exactly one less than *piIdxCur. ** For a WITHOUT ROWID table, *piDataCur will be somewhere in the range ** of *piIdxCurs, depending on where the PRIMARY KEY index appears on the ** pTab->pIndex list. ** ** If pTab is a virtual table, then this routine is a no-op and the ** *piDataCur and *piIdxCur values are left uninitialized. */ SQLITE_PRIVATE int sqlite3OpenTableAndIndices( Parse *pParse, /* Parsing context */ Table *pTab, /* Table to be opened */ int op, /* OP_OpenRead or OP_OpenWrite */ u8 p5, /* P5 value for OP_Open* opcodes (except on WITHOUT ROWID) */ int iBase, /* Use this for the table cursor, if there is one */ u8 *aToOpen, /* If not NULL: boolean for each table and index */ int *piDataCur, /* Write the database source cursor number here */ int *piIdxCur /* Write the first index cursor number here */ ){ int i; int iDb; int iDataCur; Index *pIdx; Vdbe *v; assert( op==OP_OpenRead || op==OP_OpenWrite ); assert( op==OP_OpenWrite || p5==0 ); if( IsVirtual(pTab) ){ /* This routine is a no-op for virtual tables. Leave the output ** variables *piDataCur and *piIdxCur uninitialized so that valgrind ** can detect if they are used by mistake in the caller. */ return 0; } iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema); v = sqlite3GetVdbe(pParse); assert( v!=0 ); if( iBase<0 ) iBase = pParse->nTab; iDataCur = iBase++; if( piDataCur ) *piDataCur = iDataCur; if( HasRowid(pTab) && (aToOpen==0 || aToOpen[0]) ){ sqlite3OpenTable(pParse, iDataCur, iDb, pTab, op); }else{ sqlite3TableLock(pParse, iDb, pTab->tnum, op==OP_OpenWrite, pTab->zName); } if( piIdxCur ) *piIdxCur = iBase; for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){ int iIdxCur = iBase++; assert( pIdx->pSchema==pTab->pSchema ); if( IsPrimaryKeyIndex(pIdx) && !HasRowid(pTab) ){ if( piDataCur ) *piDataCur = iIdxCur; p5 = 0; } if( aToOpen==0 || aToOpen[i+1] ){ sqlite3VdbeAddOp3(v, op, iIdxCur, pIdx->tnum, iDb); sqlite3VdbeSetP4KeyInfo(pParse, pIdx); sqlite3VdbeChangeP5(v, p5); VdbeComment((v, "%s", pIdx->zName)); } } if( iBase>pParse->nTab ) pParse->nTab = iBase; return i; } #ifdef SQLITE_TEST /* ** The following global variable is incremented whenever the ** transfer optimization is used. This is used for testing ** purposes only - to make sure the transfer optimization really ** is happening when it is supposed to. */ SQLITE_API int sqlite3_xferopt_count; #endif /* SQLITE_TEST */ #ifndef SQLITE_OMIT_XFER_OPT /* ** Check to see if index pSrc is compatible as a source of data ** for index pDest in an insert transfer optimization. The rules ** for a compatible index: ** ** * The index is over the same set of columns ** * The same DESC and ASC markings occurs on all columns ** * The same onError processing (OE_Abort, OE_Ignore, etc) ** * The same collating sequence on each column ** * The index has the exact same WHERE clause */ static int xferCompatibleIndex(Index *pDest, Index *pSrc){ int i; assert( pDest && pSrc ); assert( pDest->pTable!=pSrc->pTable ); if( pDest->nKeyCol!=pSrc->nKeyCol ){ return 0; /* Different number of columns */ } if( pDest->onError!=pSrc->onError ){ return 0; /* Different conflict resolution strategies */ } for(i=0; inKeyCol; i++){ if( pSrc->aiColumn[i]!=pDest->aiColumn[i] ){ return 0; /* Different columns indexed */ } if( pSrc->aiColumn[i]==XN_EXPR ){ assert( pSrc->aColExpr!=0 && pDest->aColExpr!=0 ); if( sqlite3ExprCompare(pSrc->aColExpr->a[i].pExpr, pDest->aColExpr->a[i].pExpr, -1)!=0 ){ return 0; /* Different expressions in the index */ } } if( pSrc->aSortOrder[i]!=pDest->aSortOrder[i] ){ return 0; /* Different sort orders */ } if( sqlite3_stricmp(pSrc->azColl[i],pDest->azColl[i])!=0 ){ return 0; /* Different collating sequences */ } } if( sqlite3ExprCompare(pSrc->pPartIdxWhere, pDest->pPartIdxWhere, -1) ){ return 0; /* Different WHERE clauses */ } /* If no test above fails then the indices must be compatible */ return 1; } /* ** Attempt the transfer optimization on INSERTs of the form ** ** INSERT INTO tab1 SELECT * FROM tab2; ** ** The xfer optimization transfers raw records from tab2 over to tab1. ** Columns are not decoded and reassembled, which greatly improves ** performance. Raw index records are transferred in the same way. ** ** The xfer optimization is only attempted if tab1 and tab2 are compatible. ** There are lots of rules for determining compatibility - see comments ** embedded in the code for details. ** ** This routine returns TRUE if the optimization is guaranteed to be used. ** Sometimes the xfer optimization will only work if the destination table ** is empty - a factor that can only be determined at run-time. In that ** case, this routine generates code for the xfer optimization but also ** does a test to see if the destination table is empty and jumps over the ** xfer optimization code if the test fails. In that case, this routine ** returns FALSE so that the caller will know to go ahead and generate ** an unoptimized transfer. This routine also returns FALSE if there ** is no chance that the xfer optimization can be applied. ** ** This optimization is particularly useful at making VACUUM run faster. */ static int xferOptimization( Parse *pParse, /* Parser context */ Table *pDest, /* The table we are inserting into */ Select *pSelect, /* A SELECT statement to use as the data source */ int onError, /* How to handle constraint errors */ int iDbDest /* The database of pDest */ ){ sqlite3 *db = pParse->db; ExprList *pEList; /* The result set of the SELECT */ Table *pSrc; /* The table in the FROM clause of SELECT */ Index *pSrcIdx, *pDestIdx; /* Source and destination indices */ struct SrcList_item *pItem; /* An element of pSelect->pSrc */ int i; /* Loop counter */ int iDbSrc; /* The database of pSrc */ int iSrc, iDest; /* Cursors from source and destination */ int addr1, addr2; /* Loop addresses */ int emptyDestTest = 0; /* Address of test for empty pDest */ int emptySrcTest = 0; /* Address of test for empty pSrc */ Vdbe *v; /* The VDBE we are building */ int regAutoinc; /* Memory register used by AUTOINC */ int destHasUniqueIdx = 0; /* True if pDest has a UNIQUE index */ int regData, regRowid; /* Registers holding data and rowid */ if( pSelect==0 ){ return 0; /* Must be of the form INSERT INTO ... SELECT ... */ } if( pParse->pWith || pSelect->pWith ){ /* Do not attempt to process this query if there are an WITH clauses ** attached to it. Proceeding may generate a false "no such table: xxx" ** error if pSelect reads from a CTE named "xxx". */ return 0; } if( sqlite3TriggerList(pParse, pDest) ){ return 0; /* tab1 must not have triggers */ } #ifndef SQLITE_OMIT_VIRTUALTABLE if( pDest->tabFlags & TF_Virtual ){ return 0; /* tab1 must not be a virtual table */ } #endif if( onError==OE_Default ){ if( pDest->iPKey>=0 ) onError = pDest->keyConf; if( onError==OE_Default ) onError = OE_Abort; } assert(pSelect->pSrc); /* allocated even if there is no FROM clause */ if( pSelect->pSrc->nSrc!=1 ){ return 0; /* FROM clause must have exactly one term */ } if( pSelect->pSrc->a[0].pSelect ){ return 0; /* FROM clause cannot contain a subquery */ } if( pSelect->pWhere ){ return 0; /* SELECT may not have a WHERE clause */ } if( pSelect->pOrderBy ){ return 0; /* SELECT may not have an ORDER BY clause */ } /* Do not need to test for a HAVING clause. If HAVING is present but ** there is no ORDER BY, we will get an error. */ if( pSelect->pGroupBy ){ return 0; /* SELECT may not have a GROUP BY clause */ } if( pSelect->pLimit ){ return 0; /* SELECT may not have a LIMIT clause */ } assert( pSelect->pOffset==0 ); /* Must be so if pLimit==0 */ if( pSelect->pPrior ){ return 0; /* SELECT may not be a compound query */ } if( pSelect->selFlags & SF_Distinct ){ return 0; /* SELECT may not be DISTINCT */ } pEList = pSelect->pEList; assert( pEList!=0 ); if( pEList->nExpr!=1 ){ return 0; /* The result set must have exactly one column */ } assert( pEList->a[0].pExpr ); if( pEList->a[0].pExpr->op!=TK_ASTERISK ){ return 0; /* The result set must be the special operator "*" */ } /* At this point we have established that the statement is of the ** correct syntactic form to participate in this optimization. Now ** we have to check the semantics. */ pItem = pSelect->pSrc->a; pSrc = sqlite3LocateTableItem(pParse, 0, pItem); if( pSrc==0 ){ return 0; /* FROM clause does not contain a real table */ } if( pSrc==pDest ){ return 0; /* tab1 and tab2 may not be the same table */ } if( HasRowid(pDest)!=HasRowid(pSrc) ){ return 0; /* source and destination must both be WITHOUT ROWID or not */ } #ifndef SQLITE_OMIT_VIRTUALTABLE if( pSrc->tabFlags & TF_Virtual ){ return 0; /* tab2 must not be a virtual table */ } #endif if( pSrc->pSelect ){ return 0; /* tab2 may not be a view */ } if( pDest->nCol!=pSrc->nCol ){ return 0; /* Number of columns must be the same in tab1 and tab2 */ } if( pDest->iPKey!=pSrc->iPKey ){ return 0; /* Both tables must have the same INTEGER PRIMARY KEY */ } for(i=0; inCol; i++){ Column *pDestCol = &pDest->aCol[i]; Column *pSrcCol = &pSrc->aCol[i]; #ifdef SQLITE_ENABLE_HIDDEN_COLUMNS if( (db->flags & SQLITE_Vacuum)==0 && (pDestCol->colFlags | pSrcCol->colFlags) & COLFLAG_HIDDEN ){ return 0; /* Neither table may have __hidden__ columns */ } #endif if( pDestCol->affinity!=pSrcCol->affinity ){ return 0; /* Affinity must be the same on all columns */ } if( sqlite3_stricmp(pDestCol->zColl, pSrcCol->zColl)!=0 ){ return 0; /* Collating sequence must be the same on all columns */ } if( pDestCol->notNull && !pSrcCol->notNull ){ return 0; /* tab2 must be NOT NULL if tab1 is */ } /* Default values for second and subsequent columns need to match. */ if( i>0 ){ assert( pDestCol->pDflt==0 || pDestCol->pDflt->op==TK_SPAN ); assert( pSrcCol->pDflt==0 || pSrcCol->pDflt->op==TK_SPAN ); if( (pDestCol->pDflt==0)!=(pSrcCol->pDflt==0) || (pDestCol->pDflt && strcmp(pDestCol->pDflt->u.zToken, pSrcCol->pDflt->u.zToken)!=0) ){ return 0; /* Default values must be the same for all columns */ } } } for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){ if( IsUniqueIndex(pDestIdx) ){ destHasUniqueIdx = 1; } for(pSrcIdx=pSrc->pIndex; pSrcIdx; pSrcIdx=pSrcIdx->pNext){ if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break; } if( pSrcIdx==0 ){ return 0; /* pDestIdx has no corresponding index in pSrc */ } } #ifndef SQLITE_OMIT_CHECK if( pDest->pCheck && sqlite3ExprListCompare(pSrc->pCheck,pDest->pCheck,-1) ){ return 0; /* Tables have different CHECK constraints. Ticket #2252 */ } #endif #ifndef SQLITE_OMIT_FOREIGN_KEY /* Disallow the transfer optimization if the destination table constains ** any foreign key constraints. This is more restrictive than necessary. ** But the main beneficiary of the transfer optimization is the VACUUM ** command, and the VACUUM command disables foreign key constraints. So ** the extra complication to make this rule less restrictive is probably ** not worth the effort. Ticket [6284df89debdfa61db8073e062908af0c9b6118e] */ if( (db->flags & SQLITE_ForeignKeys)!=0 && pDest->pFKey!=0 ){ return 0; } #endif if( (db->flags & SQLITE_CountRows)!=0 ){ return 0; /* xfer opt does not play well with PRAGMA count_changes */ } /* If we get this far, it means that the xfer optimization is at ** least a possibility, though it might only work if the destination ** table (tab1) is initially empty. */ #ifdef SQLITE_TEST sqlite3_xferopt_count++; #endif iDbSrc = sqlite3SchemaToIndex(db, pSrc->pSchema); v = sqlite3GetVdbe(pParse); sqlite3CodeVerifySchema(pParse, iDbSrc); iSrc = pParse->nTab++; iDest = pParse->nTab++; regAutoinc = autoIncBegin(pParse, iDbDest, pDest); regData = sqlite3GetTempReg(pParse); regRowid = sqlite3GetTempReg(pParse); sqlite3OpenTable(pParse, iDest, iDbDest, pDest, OP_OpenWrite); assert( HasRowid(pDest) || destHasUniqueIdx ); if( (db->flags & SQLITE_Vacuum)==0 && ( (pDest->iPKey<0 && pDest->pIndex!=0) /* (1) */ || destHasUniqueIdx /* (2) */ || (onError!=OE_Abort && onError!=OE_Rollback) /* (3) */ )){ /* In some circumstances, we are able to run the xfer optimization ** only if the destination table is initially empty. Unless the ** SQLITE_Vacuum flag is set, this block generates code to make ** that determination. If SQLITE_Vacuum is set, then the destination ** table is always empty. ** ** Conditions under which the destination must be empty: ** ** (1) There is no INTEGER PRIMARY KEY but there are indices. ** (If the destination is not initially empty, the rowid fields ** of index entries might need to change.) ** ** (2) The destination has a unique index. (The xfer optimization ** is unable to test uniqueness.) ** ** (3) onError is something other than OE_Abort and OE_Rollback. */ addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iDest, 0); VdbeCoverage(v); emptyDestTest = sqlite3VdbeAddOp0(v, OP_Goto); sqlite3VdbeJumpHere(v, addr1); } if( HasRowid(pSrc) ){ sqlite3OpenTable(pParse, iSrc, iDbSrc, pSrc, OP_OpenRead); emptySrcTest = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0); VdbeCoverage(v); if( pDest->iPKey>=0 ){ addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid); addr2 = sqlite3VdbeAddOp3(v, OP_NotExists, iDest, 0, regRowid); VdbeCoverage(v); sqlite3RowidConstraint(pParse, onError, pDest); sqlite3VdbeJumpHere(v, addr2); autoIncStep(pParse, regAutoinc, regRowid); }else if( pDest->pIndex==0 ){ addr1 = sqlite3VdbeAddOp2(v, OP_NewRowid, iDest, regRowid); }else{ addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid); assert( (pDest->tabFlags & TF_Autoincrement)==0 ); } sqlite3VdbeAddOp2(v, OP_RowData, iSrc, regData); sqlite3VdbeAddOp4(v, OP_Insert, iDest, regData, regRowid, (char*)pDest, P4_TABLE); sqlite3VdbeChangeP5(v, OPFLAG_NCHANGE|OPFLAG_LASTROWID|OPFLAG_APPEND); sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1); VdbeCoverage(v); sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0); sqlite3VdbeAddOp2(v, OP_Close, iDest, 0); }else{ sqlite3TableLock(pParse, iDbDest, pDest->tnum, 1, pDest->zName); sqlite3TableLock(pParse, iDbSrc, pSrc->tnum, 0, pSrc->zName); } for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){ u8 idxInsFlags = 0; for(pSrcIdx=pSrc->pIndex; ALWAYS(pSrcIdx); pSrcIdx=pSrcIdx->pNext){ if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break; } assert( pSrcIdx ); sqlite3VdbeAddOp3(v, OP_OpenRead, iSrc, pSrcIdx->tnum, iDbSrc); sqlite3VdbeSetP4KeyInfo(pParse, pSrcIdx); VdbeComment((v, "%s", pSrcIdx->zName)); sqlite3VdbeAddOp3(v, OP_OpenWrite, iDest, pDestIdx->tnum, iDbDest); sqlite3VdbeSetP4KeyInfo(pParse, pDestIdx); sqlite3VdbeChangeP5(v, OPFLAG_BULKCSR); VdbeComment((v, "%s", pDestIdx->zName)); addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0); VdbeCoverage(v); sqlite3VdbeAddOp2(v, OP_RowKey, iSrc, regData); if( db->flags & SQLITE_Vacuum ){ /* This INSERT command is part of a VACUUM operation, which guarantees ** that the destination table is empty. If all indexed columns use ** collation sequence BINARY, then it can also be assumed that the ** index will be populated by inserting keys in strictly sorted ** order. In this case, instead of seeking within the b-tree as part ** of every OP_IdxInsert opcode, an OP_Last is added before the ** OP_IdxInsert to seek to the point within the b-tree where each key ** should be inserted. This is faster. ** ** If any of the indexed columns use a collation sequence other than ** BINARY, this optimization is disabled. This is because the user ** might change the definition of a collation sequence and then run ** a VACUUM command. In that case keys may not be written in strictly ** sorted order. */ for(i=0; inColumn; i++){ const char *zColl = pSrcIdx->azColl[i]; assert( sqlite3_stricmp(sqlite3StrBINARY, zColl)!=0 || sqlite3StrBINARY==zColl ); if( sqlite3_stricmp(sqlite3StrBINARY, zColl) ) break; } if( i==pSrcIdx->nColumn ){ idxInsFlags = OPFLAG_USESEEKRESULT; sqlite3VdbeAddOp3(v, OP_Last, iDest, 0, -1); } } if( !HasRowid(pSrc) && pDestIdx->idxType==2 ){ idxInsFlags |= OPFLAG_NCHANGE; } sqlite3VdbeAddOp3(v, OP_IdxInsert, iDest, regData, 1); sqlite3VdbeChangeP5(v, idxInsFlags); sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1+1); VdbeCoverage(v); sqlite3VdbeJumpHere(v, addr1); sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0); sqlite3VdbeAddOp2(v, OP_Close, iDest, 0); } if( emptySrcTest ) sqlite3VdbeJumpHere(v, emptySrcTest); sqlite3ReleaseTempReg(pParse, regRowid); sqlite3ReleaseTempReg(pParse, regData); if( emptyDestTest ){ sqlite3AutoincrementEnd(pParse); sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_OK, 0); sqlite3VdbeJumpHere(v, emptyDestTest); sqlite3VdbeAddOp2(v, OP_Close, iDest, 0); return 0; }else{ return 1; } } #endif /* SQLITE_OMIT_XFER_OPT */ /************** End of insert.c **********************************************/ /************** Begin file legacy.c ******************************************/ /* ** 2001 September 15 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ************************************************************************* ** Main file for the SQLite library. The routines in this file ** implement the programmer interface to the library. Routines in ** other files are for internal use by SQLite and should not be ** accessed by users of the library. */ /* #include "sqliteInt.h" */ /* ** Execute SQL code. Return one of the SQLITE_ success/failure ** codes. Also write an error message into memory obtained from ** malloc() and make *pzErrMsg point to that message. ** ** If the SQL is a query, then for each row in the query result ** the xCallback() function is called. pArg becomes the first ** argument to xCallback(). If xCallback=NULL then no callback ** is invoked, even for queries. */ SQLITE_API int sqlite3_exec( sqlite3 *db, /* The database on which the SQL executes */ const char *zSql, /* The SQL to be executed */ sqlite3_callback xCallback, /* Invoke this callback routine */ void *pArg, /* First argument to xCallback() */ char **pzErrMsg /* Write error messages here */ ){ int rc = SQLITE_OK; /* Return code */ const char *zLeftover; /* Tail of unprocessed SQL */ sqlite3_stmt *pStmt = 0; /* The current SQL statement */ char **azCols = 0; /* Names of result columns */ int callbackIsInit; /* True if callback data is initialized */ if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT; if( zSql==0 ) zSql = ""; sqlite3_mutex_enter(db->mutex); sqlite3Error(db, SQLITE_OK); while( rc==SQLITE_OK && zSql[0] ){ int nCol; char **azVals = 0; pStmt = 0; rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, &zLeftover); assert( rc==SQLITE_OK || pStmt==0 ); if( rc!=SQLITE_OK ){ continue; } if( !pStmt ){ /* this happens for a comment or white-space */ zSql = zLeftover; continue; } callbackIsInit = 0; nCol = sqlite3_column_count(pStmt); while( 1 ){ int i; rc = sqlite3_step(pStmt); /* Invoke the callback function if required */ if( xCallback && (SQLITE_ROW==rc || (SQLITE_DONE==rc && !callbackIsInit && db->flags&SQLITE_NullCallback)) ){ if( !callbackIsInit ){ azCols = sqlite3DbMallocZero(db, 2*nCol*sizeof(const char*) + 1); if( azCols==0 ){ goto exec_out; } for(i=0; ierrMask)==rc ); sqlite3_mutex_leave(db->mutex); return rc; } /************** End of legacy.c **********************************************/ /************** Begin file loadext.c *****************************************/ /* ** 2006 June 7 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ************************************************************************* ** This file contains code used to dynamically load extensions into ** the SQLite library. */ #ifndef SQLITE_CORE #define SQLITE_CORE 1 /* Disable the API redefinition in sqlite3ext.h */ #endif /************** Include sqlite3ext.h in the middle of loadext.c **************/ /************** Begin file sqlite3ext.h **************************************/ /* ** 2006 June 7 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ************************************************************************* ** This header file defines the SQLite interface for use by ** shared libraries that want to be imported as extensions into ** an SQLite instance. Shared libraries that intend to be loaded ** as extensions by SQLite should #include this file instead of ** sqlite3.h. */ #ifndef SQLITE3EXT_H #define SQLITE3EXT_H /* #include "sqlite3.h" */ /* ** The following structure holds pointers to all of the SQLite API ** routines. ** ** WARNING: In order to maintain backwards compatibility, add new ** interfaces to the end of this structure only. If you insert new ** interfaces in the middle of this structure, then older different ** versions of SQLite will not be able to load each other's shared ** libraries! */ struct sqlite3_api_routines { void * (*aggregate_context)(sqlite3_context*,int nBytes); int (*aggregate_count)(sqlite3_context*); int (*bind_blob)(sqlite3_stmt*,int,const void*,int n,void(*)(void*)); int (*bind_double)(sqlite3_stmt*,int,double); int (*bind_int)(sqlite3_stmt*,int,int); int (*bind_int64)(sqlite3_stmt*,int,sqlite_int64); int (*bind_null)(sqlite3_stmt*,int); int (*bind_parameter_count)(sqlite3_stmt*); int (*bind_parameter_index)(sqlite3_stmt*,const char*zName); const char * (*bind_parameter_name)(sqlite3_stmt*,int); int (*bind_text)(sqlite3_stmt*,int,const char*,int n,void(*)(void*)); int (*bind_text16)(sqlite3_stmt*,int,const void*,int,void(*)(void*)); int (*bind_value)(sqlite3_stmt*,int,const sqlite3_value*); int (*busy_handler)(sqlite3*,int(*)(void*,int),void*); int (*busy_timeout)(sqlite3*,int ms); int (*changes)(sqlite3*); int (*close)(sqlite3*); int (*collation_needed)(sqlite3*,void*,void(*)(void*,sqlite3*, int eTextRep,const char*)); int (*collation_needed16)(sqlite3*,void*,void(*)(void*,sqlite3*, int eTextRep,const void*)); const void * (*column_blob)(sqlite3_stmt*,int iCol); int (*column_bytes)(sqlite3_stmt*,int iCol); int (*column_bytes16)(sqlite3_stmt*,int iCol); int (*column_count)(sqlite3_stmt*pStmt); const char * (*column_database_name)(sqlite3_stmt*,int); const void * (*column_database_name16)(sqlite3_stmt*,int); const char * (*column_decltype)(sqlite3_stmt*,int i); const void * (*column_decltype16)(sqlite3_stmt*,int); double (*column_double)(sqlite3_stmt*,int iCol); int (*column_int)(sqlite3_stmt*,int iCol); sqlite_int64 (*column_int64)(sqlite3_stmt*,int iCol); const char * (*column_name)(sqlite3_stmt*,int); const void * (*column_name16)(sqlite3_stmt*,int); const char * (*column_origin_name)(sqlite3_stmt*,int); const void * (*column_origin_name16)(sqlite3_stmt*,int); const char * (*column_table_name)(sqlite3_stmt*,int); const void * (*column_table_name16)(sqlite3_stmt*,int); const unsigned char * (*column_text)(sqlite3_stmt*,int iCol); const void * (*column_text16)(sqlite3_stmt*,int iCol); int (*column_type)(sqlite3_stmt*,int iCol); sqlite3_value* (*column_value)(sqlite3_stmt*,int iCol); void * (*commit_hook)(sqlite3*,int(*)(void*),void*); int (*complete)(const char*sql); int (*complete16)(const void*sql); int (*create_collation)(sqlite3*,const char*,int,void*, int(*)(void*,int,const void*,int,const void*)); int (*create_collation16)(sqlite3*,const void*,int,void*, int(*)(void*,int,const void*,int,const void*)); int (*create_function)(sqlite3*,const char*,int,int,void*, void (*xFunc)(sqlite3_context*,int,sqlite3_value**), void (*xStep)(sqlite3_context*,int,sqlite3_value**), void (*xFinal)(sqlite3_context*)); int (*create_function16)(sqlite3*,const void*,int,int,void*, void (*xFunc)(sqlite3_context*,int,sqlite3_value**), void (*xStep)(sqlite3_context*,int,sqlite3_value**), void (*xFinal)(sqlite3_context*)); int (*create_module)(sqlite3*,const char*,const sqlite3_module*,void*); int (*data_count)(sqlite3_stmt*pStmt); sqlite3 * (*db_handle)(sqlite3_stmt*); int (*declare_vtab)(sqlite3*,const char*); int (*enable_shared_cache)(int); int (*errcode)(sqlite3*db); const char * (*errmsg)(sqlite3*); const void * (*errmsg16)(sqlite3*); int (*exec)(sqlite3*,const char*,sqlite3_callback,void*,char**); int (*expired)(sqlite3_stmt*); int (*finalize)(sqlite3_stmt*pStmt); void (*free)(void*); void (*free_table)(char**result); int (*get_autocommit)(sqlite3*); void * (*get_auxdata)(sqlite3_context*,int); int (*get_table)(sqlite3*,const char*,char***,int*,int*,char**); int (*global_recover)(void); void (*interruptx)(sqlite3*); sqlite_int64 (*last_insert_rowid)(sqlite3*); const char * (*libversion)(void); int (*libversion_number)(void); void *(*malloc)(int); char * (*mprintf)(const char*,...); int (*open)(const char*,sqlite3**); int (*open16)(const void*,sqlite3**); int (*prepare)(sqlite3*,const char*,int,sqlite3_stmt**,const char**); int (*prepare16)(sqlite3*,const void*,int,sqlite3_stmt**,const void**); void * (*profile)(sqlite3*,void(*)(void*,const char*,sqlite_uint64),void*); void (*progress_handler)(sqlite3*,int,int(*)(void*),void*); void *(*realloc)(void*,int); int (*reset)(sqlite3_stmt*pStmt); void (*result_blob)(sqlite3_context*,const void*,int,void(*)(void*)); void (*result_double)(sqlite3_context*,double); void (*result_error)(sqlite3_context*,const char*,int); void (*result_error16)(sqlite3_context*,const void*,int); void (*result_int)(sqlite3_context*,int); void (*result_int64)(sqlite3_context*,sqlite_int64); void (*result_null)(sqlite3_context*); void (*result_text)(sqlite3_context*,const char*,int,void(*)(void*)); void (*result_text16)(sqlite3_context*,const void*,int,void(*)(void*)); void (*result_text16be)(sqlite3_context*,const void*,int,void(*)(void*)); void (*result_text16le)(sqlite3_context*,const void*,int,void(*)(void*)); void (*result_value)(sqlite3_context*,sqlite3_value*); void * (*rollback_hook)(sqlite3*,void(*)(void*),void*); int (*set_authorizer)(sqlite3*,int(*)(void*,int,const char*,const char*, const char*,const char*),void*); void (*set_auxdata)(sqlite3_context*,int,void*,void (*)(void*)); char * (*snprintf)(int,char*,const char*,...); int (*step)(sqlite3_stmt*); int (*table_column_metadata)(sqlite3*,const char*,const char*,const char*, char const**,char const**,int*,int*,int*); void (*thread_cleanup)(void); int (*total_changes)(sqlite3*); void * (*trace)(sqlite3*,void(*xTrace)(void*,const char*),void*); int (*transfer_bindings)(sqlite3_stmt*,sqlite3_stmt*); void * (*update_hook)(sqlite3*,void(*)(void*,int ,char const*,char const*, sqlite_int64),void*); void * (*user_data)(sqlite3_context*); const void * (*value_blob)(sqlite3_value*); int (*value_bytes)(sqlite3_value*); int (*value_bytes16)(sqlite3_value*); double (*value_double)(sqlite3_value*); int (*value_int)(sqlite3_value*); sqlite_int64 (*value_int64)(sqlite3_value*); int (*value_numeric_type)(sqlite3_value*); const unsigned char * (*value_text)(sqlite3_value*); const void * (*value_text16)(sqlite3_value*); const void * (*value_text16be)(sqlite3_value*); const void * (*value_text16le)(sqlite3_value*); int (*value_type)(sqlite3_value*); char *(*vmprintf)(const char*,va_list); /* Added ??? */ int (*overload_function)(sqlite3*, const char *zFuncName, int nArg); /* Added by 3.3.13 */ int (*prepare_v2)(sqlite3*,const char*,int,sqlite3_stmt**,const char**); int (*prepare16_v2)(sqlite3*,const void*,int,sqlite3_stmt**,const void**); int (*clear_bindings)(sqlite3_stmt*); /* Added by 3.4.1 */ int (*create_module_v2)(sqlite3*,const char*,const sqlite3_module*,void*, void (*xDestroy)(void *)); /* Added by 3.5.0 */ int (*bind_zeroblob)(sqlite3_stmt*,int,int); int (*blob_bytes)(sqlite3_blob*); int (*blob_close)(sqlite3_blob*); int (*blob_open)(sqlite3*,const char*,const char*,const char*,sqlite3_int64, int,sqlite3_blob**); int (*blob_read)(sqlite3_blob*,void*,int,int); int (*blob_write)(sqlite3_blob*,const void*,int,int); int (*create_collation_v2)(sqlite3*,const char*,int,void*, int(*)(void*,int,const void*,int,const void*), void(*)(void*)); int (*file_control)(sqlite3*,const char*,int,void*); sqlite3_int64 (*memory_highwater)(int); sqlite3_int64 (*memory_used)(void); sqlite3_mutex *(*mutex_alloc)(int); void (*mutex_enter)(sqlite3_mutex*); void (*mutex_free)(sqlite3_mutex*); void (*mutex_leave)(sqlite3_mutex*); int (*mutex_try)(sqlite3_mutex*); int (*open_v2)(const char*,sqlite3**,int,const char*); int (*release_memory)(int); void (*result_error_nomem)(sqlite3_context*); void (*result_error_toobig)(sqlite3_context*); int (*sleep)(int); void (*soft_heap_limit)(int); sqlite3_vfs *(*vfs_find)(const char*); int (*vfs_register)(sqlite3_vfs*,int); int (*vfs_unregister)(sqlite3_vfs*); int (*xthreadsafe)(void); void (*result_zeroblob)(sqlite3_context*,int); void (*result_error_code)(sqlite3_context*,int); int (*test_control)(int, ...); void (*randomness)(int,void*); sqlite3 *(*context_db_handle)(sqlite3_context*); int (*extended_result_codes)(sqlite3*,int); int (*limit)(sqlite3*,int,int); sqlite3_stmt *(*next_stmt)(sqlite3*,sqlite3_stmt*); const char *(*sql)(sqlite3_stmt*); int (*status)(int,int*,int*,int); int (*backup_finish)(sqlite3_backup*); sqlite3_backup *(*backup_init)(sqlite3*,const char*,sqlite3*,const char*); int (*backup_pagecount)(sqlite3_backup*); int (*backup_remaining)(sqlite3_backup*); int (*backup_step)(sqlite3_backup*,int); const char *(*compileoption_get)(int); int (*compileoption_used)(const char*); int (*create_function_v2)(sqlite3*,const char*,int,int,void*, void (*xFunc)(sqlite3_context*,int,sqlite3_value**), void (*xStep)(sqlite3_context*,int,sqlite3_value**), void (*xFinal)(sqlite3_context*), void(*xDestroy)(void*)); int (*db_config)(sqlite3*,int,...); sqlite3_mutex *(*db_mutex)(sqlite3*); int (*db_status)(sqlite3*,int,int*,int*,int); int (*extended_errcode)(sqlite3*); void (*log)(int,const char*,...); sqlite3_int64 (*soft_heap_limit64)(sqlite3_int64); const char *(*sourceid)(void); int (*stmt_status)(sqlite3_stmt*,int,int); int (*strnicmp)(const char*,const char*,int); int (*unlock_notify)(sqlite3*,void(*)(void**,int),void*); int (*wal_autocheckpoint)(sqlite3*,int); int (*wal_checkpoint)(sqlite3*,const char*); void *(*wal_hook)(sqlite3*,int(*)(void*,sqlite3*,const char*,int),void*); int (*blob_reopen)(sqlite3_blob*,sqlite3_int64); int (*vtab_config)(sqlite3*,int op,...); int (*vtab_on_conflict)(sqlite3*); /* Version 3.7.16 and later */ int (*close_v2)(sqlite3*); const char *(*db_filename)(sqlite3*,const char*); int (*db_readonly)(sqlite3*,const char*); int (*db_release_memory)(sqlite3*); const char *(*errstr)(int); int (*stmt_busy)(sqlite3_stmt*); int (*stmt_readonly)(sqlite3_stmt*); int (*stricmp)(const char*,const char*); int (*uri_boolean)(const char*,const char*,int); sqlite3_int64 (*uri_int64)(const char*,const char*,sqlite3_int64); const char *(*uri_parameter)(const char*,const char*); char *(*vsnprintf)(int,char*,const char*,va_list); int (*wal_checkpoint_v2)(sqlite3*,const char*,int,int*,int*); /* Version 3.8.7 and later */ int (*auto_extension)(void(*)(void)); int (*bind_blob64)(sqlite3_stmt*,int,const void*,sqlite3_uint64, void(*)(void*)); int (*bind_text64)(sqlite3_stmt*,int,const char*,sqlite3_uint64, void(*)(void*),unsigned char); int (*cancel_auto_extension)(void(*)(void)); int (*load_extension)(sqlite3*,const char*,const char*,char**); void *(*malloc64)(sqlite3_uint64); sqlite3_uint64 (*msize)(void*); void *(*realloc64)(void*,sqlite3_uint64); void (*reset_auto_extension)(void); void (*result_blob64)(sqlite3_context*,const void*,sqlite3_uint64, void(*)(void*)); void (*result_text64)(sqlite3_context*,const char*,sqlite3_uint64, void(*)(void*), unsigned char); int (*strglob)(const char*,const char*); /* Version 3.8.11 and later */ sqlite3_value *(*value_dup)(const sqlite3_value*); void (*value_free)(sqlite3_value*); int (*result_zeroblob64)(sqlite3_context*,sqlite3_uint64); int (*bind_zeroblob64)(sqlite3_stmt*, int, sqlite3_uint64); /* Version 3.9.0 and later */ unsigned int (*value_subtype)(sqlite3_value*); void (*result_subtype)(sqlite3_context*,unsigned int); /* Version 3.10.0 and later */ int (*status64)(int,sqlite3_int64*,sqlite3_int64*,int); int (*strlike)(const char*,const char*,unsigned int); int (*db_cacheflush)(sqlite3*); /* Version 3.12.0 and later */ int (*system_errno)(sqlite3*); /* Version 3.14.0 and later */ int (*trace_v2)(sqlite3*,unsigned,int(*)(unsigned,void*,void*,void*),void*); char *(*expanded_sql)(sqlite3_stmt*); }; /* ** This is the function signature used for all extension entry points. It ** is also defined in the file "loadext.c". */ typedef int (*sqlite3_loadext_entry)( sqlite3 *db, /* Handle to the database. */ char **pzErrMsg, /* Used to set error string on failure. */ const sqlite3_api_routines *pThunk /* Extension API function pointers. */ ); /* ** The following macros redefine the API routines so that they are ** redirected through the global sqlite3_api structure. ** ** This header file is also used by the loadext.c source file ** (part of the main SQLite library - not an extension) so that ** it can get access to the sqlite3_api_routines structure ** definition. But the main library does not want to redefine ** the API. So the redefinition macros are only valid if the ** SQLITE_CORE macros is undefined. */ #if !defined(SQLITE_CORE) && !defined(SQLITE_OMIT_LOAD_EXTENSION) #define sqlite3_aggregate_context sqlite3_api->aggregate_context #ifndef SQLITE_OMIT_DEPRECATED #define sqlite3_aggregate_count sqlite3_api->aggregate_count #endif #define sqlite3_bind_blob sqlite3_api->bind_blob #define sqlite3_bind_double sqlite3_api->bind_double #define sqlite3_bind_int sqlite3_api->bind_int #define sqlite3_bind_int64 sqlite3_api->bind_int64 #define sqlite3_bind_null sqlite3_api->bind_null #define sqlite3_bind_parameter_count sqlite3_api->bind_parameter_count #define sqlite3_bind_parameter_index sqlite3_api->bind_parameter_index #define sqlite3_bind_parameter_name sqlite3_api->bind_parameter_name #define sqlite3_bind_text sqlite3_api->bind_text #define sqlite3_bind_text16 sqlite3_api->bind_text16 #define sqlite3_bind_value sqlite3_api->bind_value #define sqlite3_busy_handler sqlite3_api->busy_handler #define sqlite3_busy_timeout sqlite3_api->busy_timeout #define sqlite3_changes sqlite3_api->changes #define sqlite3_close sqlite3_api->close #define sqlite3_collation_needed sqlite3_api->collation_needed #define sqlite3_collation_needed16 sqlite3_api->collation_needed16 #define sqlite3_column_blob sqlite3_api->column_blob #define sqlite3_column_bytes sqlite3_api->column_bytes #define sqlite3_column_bytes16 sqlite3_api->column_bytes16 #define sqlite3_column_count sqlite3_api->column_count #define sqlite3_column_database_name sqlite3_api->column_database_name #define sqlite3_column_database_name16 sqlite3_api->column_database_name16 #define sqlite3_column_decltype sqlite3_api->column_decltype #define sqlite3_column_decltype16 sqlite3_api->column_decltype16 #define sqlite3_column_double sqlite3_api->column_double #define sqlite3_column_int sqlite3_api->column_int #define sqlite3_column_int64 sqlite3_api->column_int64 #define sqlite3_column_name sqlite3_api->column_name #define sqlite3_column_name16 sqlite3_api->column_name16 #define sqlite3_column_origin_name sqlite3_api->column_origin_name #define sqlite3_column_origin_name16 sqlite3_api->column_origin_name16 #define sqlite3_column_table_name sqlite3_api->column_table_name #define sqlite3_column_table_name16 sqlite3_api->column_table_name16 #define sqlite3_column_text sqlite3_api->column_text #define sqlite3_column_text16 sqlite3_api->column_text16 #define sqlite3_column_type sqlite3_api->column_type #define sqlite3_column_value sqlite3_api->column_value #define sqlite3_commit_hook sqlite3_api->commit_hook #define sqlite3_complete sqlite3_api->complete #define sqlite3_complete16 sqlite3_api->complete16 #define sqlite3_create_collation sqlite3_api->create_collation #define sqlite3_create_collation16 sqlite3_api->create_collation16 #define sqlite3_create_function sqlite3_api->create_function #define sqlite3_create_function16 sqlite3_api->create_function16 #define sqlite3_create_module sqlite3_api->create_module #define sqlite3_create_module_v2 sqlite3_api->create_module_v2 #define sqlite3_data_count sqlite3_api->data_count #define sqlite3_db_handle sqlite3_api->db_handle #define sqlite3_declare_vtab sqlite3_api->declare_vtab #define sqlite3_enable_shared_cache sqlite3_api->enable_shared_cache #define sqlite3_errcode sqlite3_api->errcode #define sqlite3_errmsg sqlite3_api->errmsg #define sqlite3_errmsg16 sqlite3_api->errmsg16 #define sqlite3_exec sqlite3_api->exec #ifndef SQLITE_OMIT_DEPRECATED #define sqlite3_expired sqlite3_api->expired #endif #define sqlite3_finalize sqlite3_api->finalize #define sqlite3_free sqlite3_api->free #define sqlite3_free_table sqlite3_api->free_table #define sqlite3_get_autocommit sqlite3_api->get_autocommit #define sqlite3_get_auxdata sqlite3_api->get_auxdata #define sqlite3_get_table sqlite3_api->get_table #ifndef SQLITE_OMIT_DEPRECATED #define sqlite3_global_recover sqlite3_api->global_recover #endif #define sqlite3_interrupt sqlite3_api->interruptx #define sqlite3_last_insert_rowid sqlite3_api->last_insert_rowid #define sqlite3_libversion sqlite3_api->libversion #define sqlite3_libversion_number sqlite3_api->libversion_number #define sqlite3_malloc sqlite3_api->malloc #define sqlite3_mprintf sqlite3_api->mprintf #define sqlite3_open sqlite3_api->open #define sqlite3_open16 sqlite3_api->open16 #define sqlite3_prepare sqlite3_api->prepare #define sqlite3_prepare16 sqlite3_api->prepare16 #define sqlite3_prepare_v2 sqlite3_api->prepare_v2 #define sqlite3_prepare16_v2 sqlite3_api->prepare16_v2 #define sqlite3_profile sqlite3_api->profile #define sqlite3_progress_handler sqlite3_api->progress_handler #define sqlite3_realloc sqlite3_api->realloc #define sqlite3_reset sqlite3_api->reset #define sqlite3_result_blob sqlite3_api->result_blob #define sqlite3_result_double sqlite3_api->result_double #define sqlite3_result_error sqlite3_api->result_error #define sqlite3_result_error16 sqlite3_api->result_error16 #define sqlite3_result_int sqlite3_api->result_int #define sqlite3_result_int64 sqlite3_api->result_int64 #define sqlite3_result_null sqlite3_api->result_null #define sqlite3_result_text sqlite3_api->result_text #define sqlite3_result_text16 sqlite3_api->result_text16 #define sqlite3_result_text16be sqlite3_api->result_text16be #define sqlite3_result_text16le sqlite3_api->result_text16le #define sqlite3_result_value sqlite3_api->result_value #define sqlite3_rollback_hook sqlite3_api->rollback_hook #define sqlite3_set_authorizer sqlite3_api->set_authorizer #define sqlite3_set_auxdata sqlite3_api->set_auxdata #define sqlite3_snprintf sqlite3_api->snprintf #define sqlite3_step sqlite3_api->step #define sqlite3_table_column_metadata sqlite3_api->table_column_metadata #define sqlite3_thread_cleanup sqlite3_api->thread_cleanup #define sqlite3_total_changes sqlite3_api->total_changes #define sqlite3_trace sqlite3_api->trace #ifndef SQLITE_OMIT_DEPRECATED #define sqlite3_transfer_bindings sqlite3_api->transfer_bindings #endif #define sqlite3_update_hook sqlite3_api->update_hook #define sqlite3_user_data sqlite3_api->user_data #define sqlite3_value_blob sqlite3_api->value_blob #define sqlite3_value_bytes sqlite3_api->value_bytes #define sqlite3_value_bytes16 sqlite3_api->value_bytes16 #define sqlite3_value_double sqlite3_api->value_double #define sqlite3_value_int sqlite3_api->value_int #define sqlite3_value_int64 sqlite3_api->value_int64 #define sqlite3_value_numeric_type sqlite3_api->value_numeric_type #define sqlite3_value_text sqlite3_api->value_text #define sqlite3_value_text16 sqlite3_api->value_text16 #define sqlite3_value_text16be sqlite3_api->value_text16be #define sqlite3_value_text16le sqlite3_api->value_text16le #define sqlite3_value_type sqlite3_api->value_type #define sqlite3_vmprintf sqlite3_api->vmprintf #define sqlite3_vsnprintf sqlite3_api->vsnprintf #define sqlite3_overload_function sqlite3_api->overload_function #define sqlite3_prepare_v2 sqlite3_api->prepare_v2 #define sqlite3_prepare16_v2 sqlite3_api->prepare16_v2 #define sqlite3_clear_bindings sqlite3_api->clear_bindings #define sqlite3_bind_zeroblob sqlite3_api->bind_zeroblob #define sqlite3_blob_bytes sqlite3_api->blob_bytes #define sqlite3_blob_close sqlite3_api->blob_close #define sqlite3_blob_open sqlite3_api->blob_open #define sqlite3_blob_read sqlite3_api->blob_read #define sqlite3_blob_write sqlite3_api->blob_write #define sqlite3_create_collation_v2 sqlite3_api->create_collation_v2 #define sqlite3_file_control sqlite3_api->file_control #define sqlite3_memory_highwater sqlite3_api->memory_highwater #define sqlite3_memory_used sqlite3_api->memory_used #define sqlite3_mutex_alloc sqlite3_api->mutex_alloc #define sqlite3_mutex_enter sqlite3_api->mutex_enter #define sqlite3_mutex_free sqlite3_api->mutex_free #define sqlite3_mutex_leave sqlite3_api->mutex_leave #define sqlite3_mutex_try sqlite3_api->mutex_try #define sqlite3_open_v2 sqlite3_api->open_v2 #define sqlite3_release_memory sqlite3_api->release_memory #define sqlite3_result_error_nomem sqlite3_api->result_error_nomem #define sqlite3_result_error_toobig sqlite3_api->result_error_toobig #define sqlite3_sleep sqlite3_api->sleep #define sqlite3_soft_heap_limit sqlite3_api->soft_heap_limit #define sqlite3_vfs_find sqlite3_api->vfs_find #define sqlite3_vfs_register sqlite3_api->vfs_register #define sqlite3_vfs_unregister sqlite3_api->vfs_unregister #define sqlite3_threadsafe sqlite3_api->xthreadsafe #define sqlite3_result_zeroblob sqlite3_api->result_zeroblob #define sqlite3_result_error_code sqlite3_api->result_error_code #define sqlite3_test_control sqlite3_api->test_control #define sqlite3_randomness sqlite3_api->randomness #define sqlite3_context_db_handle sqlite3_api->context_db_handle #define sqlite3_extended_result_codes sqlite3_api->extended_result_codes #define sqlite3_limit sqlite3_api->limit #define sqlite3_next_stmt sqlite3_api->next_stmt #define sqlite3_sql sqlite3_api->sql #define sqlite3_status sqlite3_api->status #define sqlite3_backup_finish sqlite3_api->backup_finish #define sqlite3_backup_init sqlite3_api->backup_init #define sqlite3_backup_pagecount sqlite3_api->backup_pagecount #define sqlite3_backup_remaining sqlite3_api->backup_remaining #define sqlite3_backup_step sqlite3_api->backup_step #define sqlite3_compileoption_get sqlite3_api->compileoption_get #define sqlite3_compileoption_used sqlite3_api->compileoption_used #define sqlite3_create_function_v2 sqlite3_api->create_function_v2 #define sqlite3_db_config sqlite3_api->db_config #define sqlite3_db_mutex sqlite3_api->db_mutex #define sqlite3_db_status sqlite3_api->db_status #define sqlite3_extended_errcode sqlite3_api->extended_errcode #define sqlite3_log sqlite3_api->log #define sqlite3_soft_heap_limit64 sqlite3_api->soft_heap_limit64 #define sqlite3_sourceid sqlite3_api->sourceid #define sqlite3_stmt_status sqlite3_api->stmt_status #define sqlite3_strnicmp sqlite3_api->strnicmp #define sqlite3_unlock_notify sqlite3_api->unlock_notify #define sqlite3_wal_autocheckpoint sqlite3_api->wal_autocheckpoint #define sqlite3_wal_checkpoint sqlite3_api->wal_checkpoint #define sqlite3_wal_hook sqlite3_api->wal_hook #define sqlite3_blob_reopen sqlite3_api->blob_reopen #define sqlite3_vtab_config sqlite3_api->vtab_config #define sqlite3_vtab_on_conflict sqlite3_api->vtab_on_conflict /* Version 3.7.16 and later */ #define sqlite3_close_v2 sqlite3_api->close_v2 #define sqlite3_db_filename sqlite3_api->db_filename #define sqlite3_db_readonly sqlite3_api->db_readonly #define sqlite3_db_release_memory sqlite3_api->db_release_memory #define sqlite3_errstr sqlite3_api->errstr #define sqlite3_stmt_busy sqlite3_api->stmt_busy #define sqlite3_stmt_readonly sqlite3_api->stmt_readonly #define sqlite3_stricmp sqlite3_api->stricmp #define sqlite3_uri_boolean sqlite3_api->uri_boolean #define sqlite3_uri_int64 sqlite3_api->uri_int64 #define sqlite3_uri_parameter sqlite3_api->uri_parameter #define sqlite3_uri_vsnprintf sqlite3_api->vsnprintf #define sqlite3_wal_checkpoint_v2 sqlite3_api->wal_checkpoint_v2 /* Version 3.8.7 and later */ #define sqlite3_auto_extension sqlite3_api->auto_extension #define sqlite3_bind_blob64 sqlite3_api->bind_blob64 #define sqlite3_bind_text64 sqlite3_api->bind_text64 #define sqlite3_cancel_auto_extension sqlite3_api->cancel_auto_extension #define sqlite3_load_extension sqlite3_api->load_extension #define sqlite3_malloc64 sqlite3_api->malloc64 #define sqlite3_msize sqlite3_api->msize #define sqlite3_realloc64 sqlite3_api->realloc64 #define sqlite3_reset_auto_extension sqlite3_api->reset_auto_extension #define sqlite3_result_blob64 sqlite3_api->result_blob64 #define sqlite3_result_text64 sqlite3_api->result_text64 #define sqlite3_strglob sqlite3_api->strglob /* Version 3.8.11 and later */ #define sqlite3_value_dup sqlite3_api->value_dup #define sqlite3_value_free sqlite3_api->value_free #define sqlite3_result_zeroblob64 sqlite3_api->result_zeroblob64 #define sqlite3_bind_zeroblob64 sqlite3_api->bind_zeroblob64 /* Version 3.9.0 and later */ #define sqlite3_value_subtype sqlite3_api->value_subtype #define sqlite3_result_subtype sqlite3_api->result_subtype /* Version 3.10.0 and later */ #define sqlite3_status64 sqlite3_api->status64 #define sqlite3_strlike sqlite3_api->strlike #define sqlite3_db_cacheflush sqlite3_api->db_cacheflush /* Version 3.12.0 and later */ #define sqlite3_system_errno sqlite3_api->system_errno /* Version 3.14.0 and later */ #define sqlite3_trace_v2 sqlite3_api->trace_v2 #define sqlite3_expanded_sql sqlite3_api->expanded_sql #endif /* !defined(SQLITE_CORE) && !defined(SQLITE_OMIT_LOAD_EXTENSION) */ #if !defined(SQLITE_CORE) && !defined(SQLITE_OMIT_LOAD_EXTENSION) /* This case when the file really is being compiled as a loadable ** extension */ # define SQLITE_EXTENSION_INIT1 const sqlite3_api_routines *sqlite3_api=0; # define SQLITE_EXTENSION_INIT2(v) sqlite3_api=v; # define SQLITE_EXTENSION_INIT3 \ extern const sqlite3_api_routines *sqlite3_api; #else /* This case when the file is being statically linked into the ** application */ # define SQLITE_EXTENSION_INIT1 /*no-op*/ # define SQLITE_EXTENSION_INIT2(v) (void)v; /* unused parameter */ # define SQLITE_EXTENSION_INIT3 /*no-op*/ #endif #endif /* SQLITE3EXT_H */ /************** End of sqlite3ext.h ******************************************/ /************** Continuing where we left off in loadext.c ********************/ /* #include "sqliteInt.h" */ /* #include */ #ifndef SQLITE_OMIT_LOAD_EXTENSION /* ** Some API routines are omitted when various features are ** excluded from a build of SQLite. Substitute a NULL pointer ** for any missing APIs. */ #ifndef SQLITE_ENABLE_COLUMN_METADATA # define sqlite3_column_database_name 0 # define sqlite3_column_database_name16 0 # define sqlite3_column_table_name 0 # define sqlite3_column_table_name16 0 # define sqlite3_column_origin_name 0 # define sqlite3_column_origin_name16 0 #endif #ifdef SQLITE_OMIT_AUTHORIZATION # define sqlite3_set_authorizer 0 #endif #ifdef SQLITE_OMIT_UTF16 # define sqlite3_bind_text16 0 # define sqlite3_collation_needed16 0 # define sqlite3_column_decltype16 0 # define sqlite3_column_name16 0 # define sqlite3_column_text16 0 # define sqlite3_complete16 0 # define sqlite3_create_collation16 0 # define sqlite3_create_function16 0 # define sqlite3_errmsg16 0 # define sqlite3_open16 0 # define sqlite3_prepare16 0 # define sqlite3_prepare16_v2 0 # define sqlite3_result_error16 0 # define sqlite3_result_text16 0 # define sqlite3_result_text16be 0 # define sqlite3_result_text16le 0 # define sqlite3_value_text16 0 # define sqlite3_value_text16be 0 # define sqlite3_value_text16le 0 # define sqlite3_column_database_name16 0 # define sqlite3_column_table_name16 0 # define sqlite3_column_origin_name16 0 #endif #ifdef SQLITE_OMIT_COMPLETE # define sqlite3_complete 0 # define sqlite3_complete16 0 #endif #ifdef SQLITE_OMIT_DECLTYPE # define sqlite3_column_decltype16 0 # define sqlite3_column_decltype 0 #endif #ifdef SQLITE_OMIT_PROGRESS_CALLBACK # define sqlite3_progress_handler 0 #endif #ifdef SQLITE_OMIT_VIRTUALTABLE # define sqlite3_create_module 0 # define sqlite3_create_module_v2 0 # define sqlite3_declare_vtab 0 # define sqlite3_vtab_config 0 # define sqlite3_vtab_on_conflict 0 #endif #ifdef SQLITE_OMIT_SHARED_CACHE # define sqlite3_enable_shared_cache 0 #endif #if defined(SQLITE_OMIT_TRACE) || defined(SQLITE_OMIT_DEPRECATED) # define sqlite3_profile 0 # define sqlite3_trace 0 #endif #ifdef SQLITE_OMIT_GET_TABLE # define sqlite3_free_table 0 # define sqlite3_get_table 0 #endif #ifdef SQLITE_OMIT_INCRBLOB #define sqlite3_bind_zeroblob 0 #define sqlite3_blob_bytes 0 #define sqlite3_blob_close 0 #define sqlite3_blob_open 0 #define sqlite3_blob_read 0 #define sqlite3_blob_write 0 #define sqlite3_blob_reopen 0 #endif #if defined(SQLITE_OMIT_TRACE) # define sqlite3_trace_v2 0 #endif /* ** The following structure contains pointers to all SQLite API routines. ** A pointer to this structure is passed into extensions when they are ** loaded so that the extension can make calls back into the SQLite ** library. ** ** When adding new APIs, add them to the bottom of this structure ** in order to preserve backwards compatibility. ** ** Extensions that use newer APIs should first call the ** sqlite3_libversion_number() to make sure that the API they ** intend to use is supported by the library. Extensions should ** also check to make sure that the pointer to the function is ** not NULL before calling it. */ static const sqlite3_api_routines sqlite3Apis = { sqlite3_aggregate_context, #ifndef SQLITE_OMIT_DEPRECATED sqlite3_aggregate_count, #else 0, #endif sqlite3_bind_blob, sqlite3_bind_double, sqlite3_bind_int, sqlite3_bind_int64, sqlite3_bind_null, sqlite3_bind_parameter_count, sqlite3_bind_parameter_index, sqlite3_bind_parameter_name, sqlite3_bind_text, sqlite3_bind_text16, sqlite3_bind_value, sqlite3_busy_handler, sqlite3_busy_timeout, sqlite3_changes, sqlite3_close, sqlite3_collation_needed, sqlite3_collation_needed16, sqlite3_column_blob, sqlite3_column_bytes, sqlite3_column_bytes16, sqlite3_column_count, sqlite3_column_database_name, sqlite3_column_database_name16, sqlite3_column_decltype, sqlite3_column_decltype16, sqlite3_column_double, sqlite3_column_int, sqlite3_column_int64, sqlite3_column_name, sqlite3_column_name16, sqlite3_column_origin_name, sqlite3_column_origin_name16, sqlite3_column_table_name, sqlite3_column_table_name16, sqlite3_column_text, sqlite3_column_text16, sqlite3_column_type, sqlite3_column_value, sqlite3_commit_hook, sqlite3_complete, sqlite3_complete16, sqlite3_create_collation, sqlite3_create_collation16, sqlite3_create_function, sqlite3_create_function16, sqlite3_create_module, sqlite3_data_count, sqlite3_db_handle, sqlite3_declare_vtab, sqlite3_enable_shared_cache, sqlite3_errcode, sqlite3_errmsg, sqlite3_errmsg16, sqlite3_exec, #ifndef SQLITE_OMIT_DEPRECATED sqlite3_expired, #else 0, #endif sqlite3_finalize, sqlite3_free, sqlite3_free_table, sqlite3_get_autocommit, sqlite3_get_auxdata, sqlite3_get_table, 0, /* Was sqlite3_global_recover(), but that function is deprecated */ sqlite3_interrupt, sqlite3_last_insert_rowid, sqlite3_libversion, sqlite3_libversion_number, sqlite3_malloc, sqlite3_mprintf, sqlite3_open, sqlite3_open16, sqlite3_prepare, sqlite3_prepare16, sqlite3_profile, sqlite3_progress_handler, sqlite3_realloc, sqlite3_reset, sqlite3_result_blob, sqlite3_result_double, sqlite3_result_error, sqlite3_result_error16, sqlite3_result_int, sqlite3_result_int64, sqlite3_result_null, sqlite3_result_text, sqlite3_result_text16, sqlite3_result_text16be, sqlite3_result_text16le, sqlite3_result_value, sqlite3_rollback_hook, sqlite3_set_authorizer, sqlite3_set_auxdata, sqlite3_snprintf, sqlite3_step, sqlite3_table_column_metadata, #ifndef SQLITE_OMIT_DEPRECATED sqlite3_thread_cleanup, #else 0, #endif sqlite3_total_changes, sqlite3_trace, #ifndef SQLITE_OMIT_DEPRECATED sqlite3_transfer_bindings, #else 0, #endif sqlite3_update_hook, sqlite3_user_data, sqlite3_value_blob, sqlite3_value_bytes, sqlite3_value_bytes16, sqlite3_value_double, sqlite3_value_int, sqlite3_value_int64, sqlite3_value_numeric_type, sqlite3_value_text, sqlite3_value_text16, sqlite3_value_text16be, sqlite3_value_text16le, sqlite3_value_type, sqlite3_vmprintf, /* ** The original API set ends here. All extensions can call any ** of the APIs above provided that the pointer is not NULL. But ** before calling APIs that follow, extension should check the ** sqlite3_libversion_number() to make sure they are dealing with ** a library that is new enough to support that API. ************************************************************************* */ sqlite3_overload_function, /* ** Added after 3.3.13 */ sqlite3_prepare_v2, sqlite3_prepare16_v2, sqlite3_clear_bindings, /* ** Added for 3.4.1 */ sqlite3_create_module_v2, /* ** Added for 3.5.0 */ sqlite3_bind_zeroblob, sqlite3_blob_bytes, sqlite3_blob_close, sqlite3_blob_open, sqlite3_blob_read, sqlite3_blob_write, sqlite3_create_collation_v2, sqlite3_file_control, sqlite3_memory_highwater, sqlite3_memory_used, #ifdef SQLITE_MUTEX_OMIT 0, 0, 0, 0, 0, #else sqlite3_mutex_alloc, sqlite3_mutex_enter, sqlite3_mutex_free, sqlite3_mutex_leave, sqlite3_mutex_try, #endif sqlite3_open_v2, sqlite3_release_memory, sqlite3_result_error_nomem, sqlite3_result_error_toobig, sqlite3_sleep, sqlite3_soft_heap_limit, sqlite3_vfs_find, sqlite3_vfs_register, sqlite3_vfs_unregister, /* ** Added for 3.5.8 */ sqlite3_threadsafe, sqlite3_result_zeroblob, sqlite3_result_error_code, sqlite3_test_control, sqlite3_randomness, sqlite3_context_db_handle, /* ** Added for 3.6.0 */ sqlite3_extended_result_codes, sqlite3_limit, sqlite3_next_stmt, sqlite3_sql, sqlite3_status, /* ** Added for 3.7.4 */ sqlite3_backup_finish, sqlite3_backup_init, sqlite3_backup_pagecount, sqlite3_backup_remaining, sqlite3_backup_step, #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS sqlite3_compileoption_get, sqlite3_compileoption_used, #else 0, 0, #endif sqlite3_create_function_v2, sqlite3_db_config, sqlite3_db_mutex, sqlite3_db_status, sqlite3_extended_errcode, sqlite3_log, sqlite3_soft_heap_limit64, sqlite3_sourceid, sqlite3_stmt_status, sqlite3_strnicmp, #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY sqlite3_unlock_notify, #else 0, #endif #ifndef SQLITE_OMIT_WAL sqlite3_wal_autocheckpoint, sqlite3_wal_checkpoint, sqlite3_wal_hook, #else 0, 0, 0, #endif sqlite3_blob_reopen, sqlite3_vtab_config, sqlite3_vtab_on_conflict, sqlite3_close_v2, sqlite3_db_filename, sqlite3_db_readonly, sqlite3_db_release_memory, sqlite3_errstr, sqlite3_stmt_busy, sqlite3_stmt_readonly, sqlite3_stricmp, sqlite3_uri_boolean, sqlite3_uri_int64, sqlite3_uri_parameter, sqlite3_vsnprintf, sqlite3_wal_checkpoint_v2, /* Version 3.8.7 and later */ sqlite3_auto_extension, sqlite3_bind_blob64, sqlite3_bind_text64, sqlite3_cancel_auto_extension, sqlite3_load_extension, sqlite3_malloc64, sqlite3_msize, sqlite3_realloc64, sqlite3_reset_auto_extension, sqlite3_result_blob64, sqlite3_result_text64, sqlite3_strglob, /* Version 3.8.11 and later */ (sqlite3_value*(*)(const sqlite3_value*))sqlite3_value_dup, sqlite3_value_free, sqlite3_result_zeroblob64, sqlite3_bind_zeroblob64, /* Version 3.9.0 and later */ sqlite3_value_subtype, sqlite3_result_subtype, /* Version 3.10.0 and later */ sqlite3_status64, sqlite3_strlike, sqlite3_db_cacheflush, /* Version 3.12.0 and later */ sqlite3_system_errno, /* Version 3.14.0 and later */ sqlite3_trace_v2, sqlite3_expanded_sql }; /* ** Attempt to load an SQLite extension library contained in the file ** zFile. The entry point is zProc. zProc may be 0 in which case a ** default entry point name (sqlite3_extension_init) is used. Use ** of the default name is recommended. ** ** Return SQLITE_OK on success and SQLITE_ERROR if something goes wrong. ** ** If an error occurs and pzErrMsg is not 0, then fill *pzErrMsg with ** error message text. The calling function should free this memory ** by calling sqlite3DbFree(db, ). */ static int sqlite3LoadExtension( sqlite3 *db, /* Load the extension into this database connection */ const char *zFile, /* Name of the shared library containing extension */ const char *zProc, /* Entry point. Use "sqlite3_extension_init" if 0 */ char **pzErrMsg /* Put error message here if not 0 */ ){ sqlite3_vfs *pVfs = db->pVfs; void *handle; sqlite3_loadext_entry xInit; char *zErrmsg = 0; const char *zEntry; char *zAltEntry = 0; void **aHandle; u64 nMsg = 300 + sqlite3Strlen30(zFile); int ii; int rc; /* Shared library endings to try if zFile cannot be loaded as written */ static const char *azEndings[] = { #if SQLITE_OS_WIN "dll" #elif defined(__APPLE__) "dylib" #else "so" #endif }; if( pzErrMsg ) *pzErrMsg = 0; /* Ticket #1863. To avoid a creating security problems for older ** applications that relink against newer versions of SQLite, the ** ability to run load_extension is turned off by default. One ** must call either sqlite3_enable_load_extension(db) or ** sqlite3_db_config(db, SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION, 1, 0) ** to turn on extension loading. */ if( (db->flags & SQLITE_LoadExtension)==0 ){ if( pzErrMsg ){ *pzErrMsg = sqlite3_mprintf("not authorized"); } return SQLITE_ERROR; } zEntry = zProc ? zProc : "sqlite3_extension_init"; handle = sqlite3OsDlOpen(pVfs, zFile); #if SQLITE_OS_UNIX || SQLITE_OS_WIN for(ii=0; ii sqlite3_example_init ** C:/lib/mathfuncs.dll ==> sqlite3_mathfuncs_init */ if( xInit==0 && zProc==0 ){ int iFile, iEntry, c; int ncFile = sqlite3Strlen30(zFile); zAltEntry = sqlite3_malloc64(ncFile+30); if( zAltEntry==0 ){ sqlite3OsDlClose(pVfs, handle); return SQLITE_NOMEM_BKPT; } memcpy(zAltEntry, "sqlite3_", 8); for(iFile=ncFile-1; iFile>=0 && zFile[iFile]!='/'; iFile--){} iFile++; if( sqlite3_strnicmp(zFile+iFile, "lib", 3)==0 ) iFile += 3; for(iEntry=8; (c = zFile[iFile])!=0 && c!='.'; iFile++){ if( sqlite3Isalpha(c) ){ zAltEntry[iEntry++] = (char)sqlite3UpperToLower[(unsigned)c]; } } memcpy(zAltEntry+iEntry, "_init", 6); zEntry = zAltEntry; xInit = (sqlite3_loadext_entry)sqlite3OsDlSym(pVfs, handle, zEntry); } if( xInit==0 ){ if( pzErrMsg ){ nMsg += sqlite3Strlen30(zEntry); *pzErrMsg = zErrmsg = sqlite3_malloc64(nMsg); if( zErrmsg ){ sqlite3_snprintf(nMsg, zErrmsg, "no entry point [%s] in shared library [%s]", zEntry, zFile); sqlite3OsDlError(pVfs, nMsg-1, zErrmsg); } } sqlite3OsDlClose(pVfs, handle); sqlite3_free(zAltEntry); return SQLITE_ERROR; } sqlite3_free(zAltEntry); rc = xInit(db, &zErrmsg, &sqlite3Apis); if( rc ){ if( rc==SQLITE_OK_LOAD_PERMANENTLY ) return SQLITE_OK; if( pzErrMsg ){ *pzErrMsg = sqlite3_mprintf("error during initialization: %s", zErrmsg); } sqlite3_free(zErrmsg); sqlite3OsDlClose(pVfs, handle); return SQLITE_ERROR; } /* Append the new shared library handle to the db->aExtension array. */ aHandle = sqlite3DbMallocZero(db, sizeof(handle)*(db->nExtension+1)); if( aHandle==0 ){ return SQLITE_NOMEM_BKPT; } if( db->nExtension>0 ){ memcpy(aHandle, db->aExtension, sizeof(handle)*db->nExtension); } sqlite3DbFree(db, db->aExtension); db->aExtension = aHandle; db->aExtension[db->nExtension++] = handle; return SQLITE_OK; } SQLITE_API int sqlite3_load_extension( sqlite3 *db, /* Load the extension into this database connection */ const char *zFile, /* Name of the shared library containing extension */ const char *zProc, /* Entry point. Use "sqlite3_extension_init" if 0 */ char **pzErrMsg /* Put error message here if not 0 */ ){ int rc; sqlite3_mutex_enter(db->mutex); rc = sqlite3LoadExtension(db, zFile, zProc, pzErrMsg); rc = sqlite3ApiExit(db, rc); sqlite3_mutex_leave(db->mutex); return rc; } /* ** Call this routine when the database connection is closing in order ** to clean up loaded extensions */ SQLITE_PRIVATE void sqlite3CloseExtensions(sqlite3 *db){ int i; assert( sqlite3_mutex_held(db->mutex) ); for(i=0; inExtension; i++){ sqlite3OsDlClose(db->pVfs, db->aExtension[i]); } sqlite3DbFree(db, db->aExtension); } /* ** Enable or disable extension loading. Extension loading is disabled by ** default so as not to open security holes in older applications. */ SQLITE_API int sqlite3_enable_load_extension(sqlite3 *db, int onoff){ sqlite3_mutex_enter(db->mutex); if( onoff ){ db->flags |= SQLITE_LoadExtension|SQLITE_LoadExtFunc; }else{ db->flags &= ~(SQLITE_LoadExtension|SQLITE_LoadExtFunc); } sqlite3_mutex_leave(db->mutex); return SQLITE_OK; } #endif /* !defined(SQLITE_OMIT_LOAD_EXTENSION) */ /* ** The following object holds the list of automatically loaded ** extensions. ** ** This list is shared across threads. The SQLITE_MUTEX_STATIC_MASTER ** mutex must be held while accessing this list. */ typedef struct sqlite3AutoExtList sqlite3AutoExtList; static SQLITE_WSD struct sqlite3AutoExtList { u32 nExt; /* Number of entries in aExt[] */ void (**aExt)(void); /* Pointers to the extension init functions */ } sqlite3Autoext = { 0, 0 }; /* The "wsdAutoext" macro will resolve to the autoextension ** state vector. If writable static data is unsupported on the target, ** we have to locate the state vector at run-time. In the more common ** case where writable static data is supported, wsdStat can refer directly ** to the "sqlite3Autoext" state vector declared above. */ #ifdef SQLITE_OMIT_WSD # define wsdAutoextInit \ sqlite3AutoExtList *x = &GLOBAL(sqlite3AutoExtList,sqlite3Autoext) # define wsdAutoext x[0] #else # define wsdAutoextInit # define wsdAutoext sqlite3Autoext #endif /* ** Register a statically linked extension that is automatically ** loaded by every new database connection. */ SQLITE_API int sqlite3_auto_extension( void (*xInit)(void) ){ int rc = SQLITE_OK; #ifndef SQLITE_OMIT_AUTOINIT rc = sqlite3_initialize(); if( rc ){ return rc; }else #endif { u32 i; #if SQLITE_THREADSAFE sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); #endif wsdAutoextInit; sqlite3_mutex_enter(mutex); for(i=0; i=0; i--){ if( wsdAutoext.aExt[i]==xInit ){ wsdAutoext.nExt--; wsdAutoext.aExt[i] = wsdAutoext.aExt[wsdAutoext.nExt]; n++; break; } } sqlite3_mutex_leave(mutex); return n; } /* ** Reset the automatic extension loading mechanism. */ SQLITE_API void sqlite3_reset_auto_extension(void){ #ifndef SQLITE_OMIT_AUTOINIT if( sqlite3_initialize()==SQLITE_OK ) #endif { #if SQLITE_THREADSAFE sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); #endif wsdAutoextInit; sqlite3_mutex_enter(mutex); sqlite3_free(wsdAutoext.aExt); wsdAutoext.aExt = 0; wsdAutoext.nExt = 0; sqlite3_mutex_leave(mutex); } } /* ** Load all automatic extensions. ** ** If anything goes wrong, set an error in the database connection. */ SQLITE_PRIVATE void sqlite3AutoLoadExtensions(sqlite3 *db){ u32 i; int go = 1; int rc; sqlite3_loadext_entry xInit; wsdAutoextInit; if( wsdAutoext.nExt==0 ){ /* Common case: early out without every having to acquire a mutex */ return; } for(i=0; go; i++){ char *zErrmsg; #if SQLITE_THREADSAFE sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); #endif #ifdef SQLITE_OMIT_LOAD_EXTENSION const sqlite3_api_routines *pThunk = 0; #else const sqlite3_api_routines *pThunk = &sqlite3Apis; #endif sqlite3_mutex_enter(mutex); if( i>=wsdAutoext.nExt ){ xInit = 0; go = 0; }else{ xInit = (sqlite3_loadext_entry)wsdAutoext.aExt[i]; } sqlite3_mutex_leave(mutex); zErrmsg = 0; if( xInit && (rc = xInit(db, &zErrmsg, pThunk))!=0 ){ sqlite3ErrorWithMsg(db, rc, "automatic extension loading failed: %s", zErrmsg); go = 0; } sqlite3_free(zErrmsg); } } /************** End of loadext.c *********************************************/ /************** Begin file pragma.c ******************************************/ /* ** 2003 April 6 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ************************************************************************* ** This file contains code used to implement the PRAGMA command. */ /* #include "sqliteInt.h" */ #if !defined(SQLITE_ENABLE_LOCKING_STYLE) # if defined(__APPLE__) # define SQLITE_ENABLE_LOCKING_STYLE 1 # else # define SQLITE_ENABLE_LOCKING_STYLE 0 # endif #endif /*************************************************************************** ** The "pragma.h" include file is an automatically generated file that ** that includes the PragType_XXXX macro definitions and the aPragmaName[] ** object. This ensures that the aPragmaName[] table is arranged in ** lexicographical order to facility a binary search of the pragma name. ** Do not edit pragma.h directly. Edit and rerun the script in at ** ../tool/mkpragmatab.tcl. */ /************** Include pragma.h in the middle of pragma.c *******************/ /************** Begin file pragma.h ******************************************/ /* DO NOT EDIT! ** This file is automatically generated by the script at ** ../tool/mkpragmatab.tcl. To update the set of pragmas, edit ** that script and rerun it. */ #define PragTyp_HEADER_VALUE 0 #define PragTyp_AUTO_VACUUM 1 #define PragTyp_FLAG 2 #define PragTyp_BUSY_TIMEOUT 3 #define PragTyp_CACHE_SIZE 4 #define PragTyp_CACHE_SPILL 5 #define PragTyp_CASE_SENSITIVE_LIKE 6 #define PragTyp_COLLATION_LIST 7 #define PragTyp_COMPILE_OPTIONS 8 #define PragTyp_DATA_STORE_DIRECTORY 9 #define PragTyp_DATABASE_LIST 10 #define PragTyp_DEFAULT_CACHE_SIZE 11 #define PragTyp_ENCODING 12 #define PragTyp_FOREIGN_KEY_CHECK 13 #define PragTyp_FOREIGN_KEY_LIST 14 #define PragTyp_INCREMENTAL_VACUUM 15 #define PragTyp_INDEX_INFO 16 #define PragTyp_INDEX_LIST 17 #define PragTyp_INTEGRITY_CHECK 18 #define PragTyp_JOURNAL_MODE 19 #define PragTyp_JOURNAL_SIZE_LIMIT 20 #define PragTyp_LOCK_PROXY_FILE 21 #define PragTyp_LOCKING_MODE 22 #define PragTyp_PAGE_COUNT 23 #define PragTyp_MMAP_SIZE 24 #define PragTyp_PAGE_SIZE 25 #define PragTyp_SECURE_DELETE 26 #define PragTyp_SHRINK_MEMORY 27 #define PragTyp_SOFT_HEAP_LIMIT 28 #define PragTyp_STATS 29 #define PragTyp_SYNCHRONOUS 30 #define PragTyp_TABLE_INFO 31 #define PragTyp_TEMP_STORE 32 #define PragTyp_TEMP_STORE_DIRECTORY 33 #define PragTyp_THREADS 34 #define PragTyp_WAL_AUTOCHECKPOINT 35 #define PragTyp_WAL_CHECKPOINT 36 #define PragTyp_ACTIVATE_EXTENSIONS 37 #define PragTyp_HEXKEY 38 #define PragTyp_KEY 39 #define PragTyp_REKEY 40 #define PragTyp_LOCK_STATUS 41 #define PragTyp_PARSER_TRACE 42 #define PragFlag_NeedSchema 0x01 #define PragFlag_ReadOnly 0x02 static const struct sPragmaNames { const char *const zName; /* Name of pragma */ u8 ePragTyp; /* PragTyp_XXX value */ u8 mPragFlag; /* Zero or more PragFlag_XXX values */ u32 iArg; /* Extra argument */ } aPragmaNames[] = { #if defined(SQLITE_HAS_CODEC) || defined(SQLITE_ENABLE_CEROD) { /* zName: */ "activate_extensions", /* ePragTyp: */ PragTyp_ACTIVATE_EXTENSIONS, /* ePragFlag: */ 0, /* iArg: */ 0 }, #endif #if !defined(SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS) { /* zName: */ "application_id", /* ePragTyp: */ PragTyp_HEADER_VALUE, /* ePragFlag: */ 0, /* iArg: */ BTREE_APPLICATION_ID }, #endif #if !defined(SQLITE_OMIT_AUTOVACUUM) { /* zName: */ "auto_vacuum", /* ePragTyp: */ PragTyp_AUTO_VACUUM, /* ePragFlag: */ PragFlag_NeedSchema, /* iArg: */ 0 }, #endif #if !defined(SQLITE_OMIT_FLAG_PRAGMAS) #if !defined(SQLITE_OMIT_AUTOMATIC_INDEX) { /* zName: */ "automatic_index", /* ePragTyp: */ PragTyp_FLAG, /* ePragFlag: */ 0, /* iArg: */ SQLITE_AutoIndex }, #endif #endif { /* zName: */ "busy_timeout", /* ePragTyp: */ PragTyp_BUSY_TIMEOUT, /* ePragFlag: */ 0, /* iArg: */ 0 }, #if !defined(SQLITE_OMIT_PAGER_PRAGMAS) { /* zName: */ "cache_size", /* ePragTyp: */ PragTyp_CACHE_SIZE, /* ePragFlag: */ PragFlag_NeedSchema, /* iArg: */ 0 }, #endif #if !defined(SQLITE_OMIT_FLAG_PRAGMAS) { /* zName: */ "cache_spill", /* ePragTyp: */ PragTyp_CACHE_SPILL, /* ePragFlag: */ 0, /* iArg: */ 0 }, #endif { /* zName: */ "case_sensitive_like", /* ePragTyp: */ PragTyp_CASE_SENSITIVE_LIKE, /* ePragFlag: */ 0, /* iArg: */ 0 }, { /* zName: */ "cell_size_check", /* ePragTyp: */ PragTyp_FLAG, /* ePragFlag: */ 0, /* iArg: */ SQLITE_CellSizeCk }, #if !defined(SQLITE_OMIT_FLAG_PRAGMAS) { /* zName: */ "checkpoint_fullfsync", /* ePragTyp: */ PragTyp_FLAG, /* ePragFlag: */ 0, /* iArg: */ SQLITE_CkptFullFSync }, #endif #if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS) { /* zName: */ "collation_list", /* ePragTyp: */ PragTyp_COLLATION_LIST, /* ePragFlag: */ 0, /* iArg: */ 0 }, #endif #if !defined(SQLITE_OMIT_COMPILEOPTION_DIAGS) { /* zName: */ "compile_options", /* ePragTyp: */ PragTyp_COMPILE_OPTIONS, /* ePragFlag: */ 0, /* iArg: */ 0 }, #endif #if !defined(SQLITE_OMIT_FLAG_PRAGMAS) { /* zName: */ "count_changes", /* ePragTyp: */ PragTyp_FLAG, /* ePragFlag: */ 0, /* iArg: */ SQLITE_CountRows }, #endif #if !defined(SQLITE_OMIT_PAGER_PRAGMAS) && SQLITE_OS_WIN { /* zName: */ "data_store_directory", /* ePragTyp: */ PragTyp_DATA_STORE_DIRECTORY, /* ePragFlag: */ 0, /* iArg: */ 0 }, #endif #if !defined(SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS) { /* zName: */ "data_version", /* ePragTyp: */ PragTyp_HEADER_VALUE, /* ePragFlag: */ PragFlag_ReadOnly, /* iArg: */ BTREE_DATA_VERSION }, #endif #if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS) { /* zName: */ "database_list", /* ePragTyp: */ PragTyp_DATABASE_LIST, /* ePragFlag: */ PragFlag_NeedSchema, /* iArg: */ 0 }, #endif #if !defined(SQLITE_OMIT_PAGER_PRAGMAS) && !defined(SQLITE_OMIT_DEPRECATED) { /* zName: */ "default_cache_size", /* ePragTyp: */ PragTyp_DEFAULT_CACHE_SIZE, /* ePragFlag: */ PragFlag_NeedSchema, /* iArg: */ 0 }, #endif #if !defined(SQLITE_OMIT_FLAG_PRAGMAS) #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER) { /* zName: */ "defer_foreign_keys", /* ePragTyp: */ PragTyp_FLAG, /* ePragFlag: */ 0, /* iArg: */ SQLITE_DeferFKs }, #endif #endif #if !defined(SQLITE_OMIT_FLAG_PRAGMAS) { /* zName: */ "empty_result_callbacks", /* ePragTyp: */ PragTyp_FLAG, /* ePragFlag: */ 0, /* iArg: */ SQLITE_NullCallback }, #endif #if !defined(SQLITE_OMIT_UTF16) { /* zName: */ "encoding", /* ePragTyp: */ PragTyp_ENCODING, /* ePragFlag: */ 0, /* iArg: */ 0 }, #endif #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER) { /* zName: */ "foreign_key_check", /* ePragTyp: */ PragTyp_FOREIGN_KEY_CHECK, /* ePragFlag: */ PragFlag_NeedSchema, /* iArg: */ 0 }, #endif #if !defined(SQLITE_OMIT_FOREIGN_KEY) { /* zName: */ "foreign_key_list", /* ePragTyp: */ PragTyp_FOREIGN_KEY_LIST, /* ePragFlag: */ PragFlag_NeedSchema, /* iArg: */ 0 }, #endif #if !defined(SQLITE_OMIT_FLAG_PRAGMAS) #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER) { /* zName: */ "foreign_keys", /* ePragTyp: */ PragTyp_FLAG, /* ePragFlag: */ 0, /* iArg: */ SQLITE_ForeignKeys }, #endif #endif #if !defined(SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS) { /* zName: */ "freelist_count", /* ePragTyp: */ PragTyp_HEADER_VALUE, /* ePragFlag: */ PragFlag_ReadOnly, /* iArg: */ BTREE_FREE_PAGE_COUNT }, #endif #if !defined(SQLITE_OMIT_FLAG_PRAGMAS) { /* zName: */ "full_column_names", /* ePragTyp: */ PragTyp_FLAG, /* ePragFlag: */ 0, /* iArg: */ SQLITE_FullColNames }, { /* zName: */ "fullfsync", /* ePragTyp: */ PragTyp_FLAG, /* ePragFlag: */ 0, /* iArg: */ SQLITE_FullFSync }, #endif #if defined(SQLITE_HAS_CODEC) { /* zName: */ "hexkey", /* ePragTyp: */ PragTyp_HEXKEY, /* ePragFlag: */ 0, /* iArg: */ 0 }, { /* zName: */ "hexrekey", /* ePragTyp: */ PragTyp_HEXKEY, /* ePragFlag: */ 0, /* iArg: */ 0 }, #endif #if !defined(SQLITE_OMIT_FLAG_PRAGMAS) #if !defined(SQLITE_OMIT_CHECK) { /* zName: */ "ignore_check_constraints", /* ePragTyp: */ PragTyp_FLAG, /* ePragFlag: */ 0, /* iArg: */ SQLITE_IgnoreChecks }, #endif #endif #if !defined(SQLITE_OMIT_AUTOVACUUM) { /* zName: */ "incremental_vacuum", /* ePragTyp: */ PragTyp_INCREMENTAL_VACUUM, /* ePragFlag: */ PragFlag_NeedSchema, /* iArg: */ 0 }, #endif #if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS) { /* zName: */ "index_info", /* ePragTyp: */ PragTyp_INDEX_INFO, /* ePragFlag: */ PragFlag_NeedSchema, /* iArg: */ 0 }, { /* zName: */ "index_list", /* ePragTyp: */ PragTyp_INDEX_LIST, /* ePragFlag: */ PragFlag_NeedSchema, /* iArg: */ 0 }, { /* zName: */ "index_xinfo", /* ePragTyp: */ PragTyp_INDEX_INFO, /* ePragFlag: */ PragFlag_NeedSchema, /* iArg: */ 1 }, #endif #if !defined(SQLITE_OMIT_INTEGRITY_CHECK) { /* zName: */ "integrity_check", /* ePragTyp: */ PragTyp_INTEGRITY_CHECK, /* ePragFlag: */ PragFlag_NeedSchema, /* iArg: */ 0 }, #endif #if !defined(SQLITE_OMIT_PAGER_PRAGMAS) { /* zName: */ "journal_mode", /* ePragTyp: */ PragTyp_JOURNAL_MODE, /* ePragFlag: */ PragFlag_NeedSchema, /* iArg: */ 0 }, { /* zName: */ "journal_size_limit", /* ePragTyp: */ PragTyp_JOURNAL_SIZE_LIMIT, /* ePragFlag: */ 0, /* iArg: */ 0 }, #endif #if defined(SQLITE_HAS_CODEC) { /* zName: */ "key", /* ePragTyp: */ PragTyp_KEY, /* ePragFlag: */ 0, /* iArg: */ 0 }, #endif #if !defined(SQLITE_OMIT_FLAG_PRAGMAS) { /* zName: */ "legacy_file_format", /* ePragTyp: */ PragTyp_FLAG, /* ePragFlag: */ 0, /* iArg: */ SQLITE_LegacyFileFmt }, #endif #if !defined(SQLITE_OMIT_PAGER_PRAGMAS) && SQLITE_ENABLE_LOCKING_STYLE { /* zName: */ "lock_proxy_file", /* ePragTyp: */ PragTyp_LOCK_PROXY_FILE, /* ePragFlag: */ 0, /* iArg: */ 0 }, #endif #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST) { /* zName: */ "lock_status", /* ePragTyp: */ PragTyp_LOCK_STATUS, /* ePragFlag: */ 0, /* iArg: */ 0 }, #endif #if !defined(SQLITE_OMIT_PAGER_PRAGMAS) { /* zName: */ "locking_mode", /* ePragTyp: */ PragTyp_LOCKING_MODE, /* ePragFlag: */ 0, /* iArg: */ 0 }, { /* zName: */ "max_page_count", /* ePragTyp: */ PragTyp_PAGE_COUNT, /* ePragFlag: */ PragFlag_NeedSchema, /* iArg: */ 0 }, { /* zName: */ "mmap_size", /* ePragTyp: */ PragTyp_MMAP_SIZE, /* ePragFlag: */ 0, /* iArg: */ 0 }, { /* zName: */ "page_count", /* ePragTyp: */ PragTyp_PAGE_COUNT, /* ePragFlag: */ PragFlag_NeedSchema, /* iArg: */ 0 }, { /* zName: */ "page_size", /* ePragTyp: */ PragTyp_PAGE_SIZE, /* ePragFlag: */ 0, /* iArg: */ 0 }, #endif #if defined(SQLITE_DEBUG) && !defined(SQLITE_OMIT_PARSER_TRACE) { /* zName: */ "parser_trace", /* ePragTyp: */ PragTyp_PARSER_TRACE, /* ePragFlag: */ 0, /* iArg: */ 0 }, #endif #if !defined(SQLITE_OMIT_FLAG_PRAGMAS) { /* zName: */ "query_only", /* ePragTyp: */ PragTyp_FLAG, /* ePragFlag: */ 0, /* iArg: */ SQLITE_QueryOnly }, #endif #if !defined(SQLITE_OMIT_INTEGRITY_CHECK) { /* zName: */ "quick_check", /* ePragTyp: */ PragTyp_INTEGRITY_CHECK, /* ePragFlag: */ PragFlag_NeedSchema, /* iArg: */ 0 }, #endif #if !defined(SQLITE_OMIT_FLAG_PRAGMAS) { /* zName: */ "read_uncommitted", /* ePragTyp: */ PragTyp_FLAG, /* ePragFlag: */ 0, /* iArg: */ SQLITE_ReadUncommitted }, { /* zName: */ "recursive_triggers", /* ePragTyp: */ PragTyp_FLAG, /* ePragFlag: */ 0, /* iArg: */ SQLITE_RecTriggers }, #endif #if defined(SQLITE_HAS_CODEC) { /* zName: */ "rekey", /* ePragTyp: */ PragTyp_REKEY, /* ePragFlag: */ 0, /* iArg: */ 0 }, #endif #if !defined(SQLITE_OMIT_FLAG_PRAGMAS) { /* zName: */ "reverse_unordered_selects", /* ePragTyp: */ PragTyp_FLAG, /* ePragFlag: */ 0, /* iArg: */ SQLITE_ReverseOrder }, #endif #if !defined(SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS) { /* zName: */ "schema_version", /* ePragTyp: */ PragTyp_HEADER_VALUE, /* ePragFlag: */ 0, /* iArg: */ BTREE_SCHEMA_VERSION }, #endif #if !defined(SQLITE_OMIT_PAGER_PRAGMAS) { /* zName: */ "secure_delete", /* ePragTyp: */ PragTyp_SECURE_DELETE, /* ePragFlag: */ 0, /* iArg: */ 0 }, #endif #if !defined(SQLITE_OMIT_FLAG_PRAGMAS) { /* zName: */ "short_column_names", /* ePragTyp: */ PragTyp_FLAG, /* ePragFlag: */ 0, /* iArg: */ SQLITE_ShortColNames }, #endif { /* zName: */ "shrink_memory", /* ePragTyp: */ PragTyp_SHRINK_MEMORY, /* ePragFlag: */ 0, /* iArg: */ 0 }, { /* zName: */ "soft_heap_limit", /* ePragTyp: */ PragTyp_SOFT_HEAP_LIMIT, /* ePragFlag: */ 0, /* iArg: */ 0 }, #if !defined(SQLITE_OMIT_FLAG_PRAGMAS) #if defined(SQLITE_DEBUG) { /* zName: */ "sql_trace", /* ePragTyp: */ PragTyp_FLAG, /* ePragFlag: */ 0, /* iArg: */ SQLITE_SqlTrace }, #endif #endif #if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS) { /* zName: */ "stats", /* ePragTyp: */ PragTyp_STATS, /* ePragFlag: */ PragFlag_NeedSchema, /* iArg: */ 0 }, #endif #if !defined(SQLITE_OMIT_PAGER_PRAGMAS) { /* zName: */ "synchronous", /* ePragTyp: */ PragTyp_SYNCHRONOUS, /* ePragFlag: */ PragFlag_NeedSchema, /* iArg: */ 0 }, #endif #if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS) { /* zName: */ "table_info", /* ePragTyp: */ PragTyp_TABLE_INFO, /* ePragFlag: */ PragFlag_NeedSchema, /* iArg: */ 0 }, #endif #if !defined(SQLITE_OMIT_PAGER_PRAGMAS) { /* zName: */ "temp_store", /* ePragTyp: */ PragTyp_TEMP_STORE, /* ePragFlag: */ 0, /* iArg: */ 0 }, { /* zName: */ "temp_store_directory", /* ePragTyp: */ PragTyp_TEMP_STORE_DIRECTORY, /* ePragFlag: */ 0, /* iArg: */ 0 }, #endif { /* zName: */ "threads", /* ePragTyp: */ PragTyp_THREADS, /* ePragFlag: */ 0, /* iArg: */ 0 }, #if !defined(SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS) { /* zName: */ "user_version", /* ePragTyp: */ PragTyp_HEADER_VALUE, /* ePragFlag: */ 0, /* iArg: */ BTREE_USER_VERSION }, #endif #if !defined(SQLITE_OMIT_FLAG_PRAGMAS) #if defined(SQLITE_DEBUG) { /* zName: */ "vdbe_addoptrace", /* ePragTyp: */ PragTyp_FLAG, /* ePragFlag: */ 0, /* iArg: */ SQLITE_VdbeAddopTrace }, { /* zName: */ "vdbe_debug", /* ePragTyp: */ PragTyp_FLAG, /* ePragFlag: */ 0, /* iArg: */ SQLITE_SqlTrace|SQLITE_VdbeListing|SQLITE_VdbeTrace }, { /* zName: */ "vdbe_eqp", /* ePragTyp: */ PragTyp_FLAG, /* ePragFlag: */ 0, /* iArg: */ SQLITE_VdbeEQP }, { /* zName: */ "vdbe_listing", /* ePragTyp: */ PragTyp_FLAG, /* ePragFlag: */ 0, /* iArg: */ SQLITE_VdbeListing }, { /* zName: */ "vdbe_trace", /* ePragTyp: */ PragTyp_FLAG, /* ePragFlag: */ 0, /* iArg: */ SQLITE_VdbeTrace }, #endif #endif #if !defined(SQLITE_OMIT_WAL) { /* zName: */ "wal_autocheckpoint", /* ePragTyp: */ PragTyp_WAL_AUTOCHECKPOINT, /* ePragFlag: */ 0, /* iArg: */ 0 }, { /* zName: */ "wal_checkpoint", /* ePragTyp: */ PragTyp_WAL_CHECKPOINT, /* ePragFlag: */ PragFlag_NeedSchema, /* iArg: */ 0 }, #endif #if !defined(SQLITE_OMIT_FLAG_PRAGMAS) { /* zName: */ "writable_schema", /* ePragTyp: */ PragTyp_FLAG, /* ePragFlag: */ 0, /* iArg: */ SQLITE_WriteSchema|SQLITE_RecoveryMode }, #endif }; /* Number of pragmas: 60 on by default, 73 total. */ /************** End of pragma.h **********************************************/ /************** Continuing where we left off in pragma.c *********************/ /* ** Interpret the given string as a safety level. Return 0 for OFF, ** 1 for ON or NORMAL, 2 for FULL, and 3 for EXTRA. Return 1 for an empty or ** unrecognized string argument. The FULL and EXTRA option is disallowed ** if the omitFull parameter it 1. ** ** Note that the values returned are one less that the values that ** should be passed into sqlite3BtreeSetSafetyLevel(). The is done ** to support legacy SQL code. The safety level used to be boolean ** and older scripts may have used numbers 0 for OFF and 1 for ON. */ static u8 getSafetyLevel(const char *z, int omitFull, u8 dflt){ /* 123456789 123456789 123 */ static const char zText[] = "onoffalseyestruextrafull"; static const u8 iOffset[] = {0, 1, 2, 4, 9, 12, 15, 20}; static const u8 iLength[] = {2, 2, 3, 5, 3, 4, 5, 4}; static const u8 iValue[] = {1, 0, 0, 0, 1, 1, 3, 2}; /* on no off false yes true extra full */ int i, n; if( sqlite3Isdigit(*z) ){ return (u8)sqlite3Atoi(z); } n = sqlite3Strlen30(z); for(i=0; i=0&&i<=2)?i:0); } #endif /* ifndef SQLITE_OMIT_AUTOVACUUM */ #ifndef SQLITE_OMIT_PAGER_PRAGMAS /* ** Interpret the given string as a temp db location. Return 1 for file ** backed temporary databases, 2 for the Red-Black tree in memory database ** and 0 to use the compile-time default. */ static int getTempStore(const char *z){ if( z[0]>='0' && z[0]<='2' ){ return z[0] - '0'; }else if( sqlite3StrICmp(z, "file")==0 ){ return 1; }else if( sqlite3StrICmp(z, "memory")==0 ){ return 2; }else{ return 0; } } #endif /* SQLITE_PAGER_PRAGMAS */ #ifndef SQLITE_OMIT_PAGER_PRAGMAS /* ** Invalidate temp storage, either when the temp storage is changed ** from default, or when 'file' and the temp_store_directory has changed */ static int invalidateTempStorage(Parse *pParse){ sqlite3 *db = pParse->db; if( db->aDb[1].pBt!=0 ){ if( !db->autoCommit || sqlite3BtreeIsInReadTrans(db->aDb[1].pBt) ){ sqlite3ErrorMsg(pParse, "temporary storage cannot be changed " "from within a transaction"); return SQLITE_ERROR; } sqlite3BtreeClose(db->aDb[1].pBt); db->aDb[1].pBt = 0; sqlite3ResetAllSchemasOfConnection(db); } return SQLITE_OK; } #endif /* SQLITE_PAGER_PRAGMAS */ #ifndef SQLITE_OMIT_PAGER_PRAGMAS /* ** If the TEMP database is open, close it and mark the database schema ** as needing reloading. This must be done when using the SQLITE_TEMP_STORE ** or DEFAULT_TEMP_STORE pragmas. */ static int changeTempStorage(Parse *pParse, const char *zStorageType){ int ts = getTempStore(zStorageType); sqlite3 *db = pParse->db; if( db->temp_store==ts ) return SQLITE_OK; if( invalidateTempStorage( pParse ) != SQLITE_OK ){ return SQLITE_ERROR; } db->temp_store = (u8)ts; return SQLITE_OK; } #endif /* SQLITE_PAGER_PRAGMAS */ /* ** Set the names of the first N columns to the values in azCol[] */ static void setAllColumnNames( Vdbe *v, /* The query under construction */ int N, /* Number of columns */ const char **azCol /* Names of columns */ ){ int i; sqlite3VdbeSetNumCols(v, N); for(i=0; iautoCommit ){ Db *pDb = db->aDb; int n = db->nDb; assert( SQLITE_FullFSync==PAGER_FULLFSYNC ); assert( SQLITE_CkptFullFSync==PAGER_CKPT_FULLFSYNC ); assert( SQLITE_CacheSpill==PAGER_CACHESPILL ); assert( (PAGER_FULLFSYNC | PAGER_CKPT_FULLFSYNC | PAGER_CACHESPILL) == PAGER_FLAGS_MASK ); assert( (pDb->safety_level & PAGER_SYNCHRONOUS_MASK)==pDb->safety_level ); while( (n--) > 0 ){ if( pDb->pBt ){ sqlite3BtreeSetPagerFlags(pDb->pBt, pDb->safety_level | (db->flags & PAGER_FLAGS_MASK) ); } pDb++; } } } #else # define setAllPagerFlags(X) /* no-op */ #endif /* ** Return a human-readable name for a constraint resolution action. */ #ifndef SQLITE_OMIT_FOREIGN_KEY static const char *actionName(u8 action){ const char *zName; switch( action ){ case OE_SetNull: zName = "SET NULL"; break; case OE_SetDflt: zName = "SET DEFAULT"; break; case OE_Cascade: zName = "CASCADE"; break; case OE_Restrict: zName = "RESTRICT"; break; default: zName = "NO ACTION"; assert( action==OE_None ); break; } return zName; } #endif /* ** Parameter eMode must be one of the PAGER_JOURNALMODE_XXX constants ** defined in pager.h. This function returns the associated lowercase ** journal-mode name. */ SQLITE_PRIVATE const char *sqlite3JournalModename(int eMode){ static char * const azModeName[] = { "delete", "persist", "off", "truncate", "memory" #ifndef SQLITE_OMIT_WAL , "wal" #endif }; assert( PAGER_JOURNALMODE_DELETE==0 ); assert( PAGER_JOURNALMODE_PERSIST==1 ); assert( PAGER_JOURNALMODE_OFF==2 ); assert( PAGER_JOURNALMODE_TRUNCATE==3 ); assert( PAGER_JOURNALMODE_MEMORY==4 ); assert( PAGER_JOURNALMODE_WAL==5 ); assert( eMode>=0 && eMode<=ArraySize(azModeName) ); if( eMode==ArraySize(azModeName) ) return 0; return azModeName[eMode]; } /* ** Process a pragma statement. ** ** Pragmas are of this form: ** ** PRAGMA [schema.]id [= value] ** ** The identifier might also be a string. The value is a string, and ** identifier, or a number. If minusFlag is true, then the value is ** a number that was preceded by a minus sign. ** ** If the left side is "database.id" then pId1 is the database name ** and pId2 is the id. If the left side is just "id" then pId1 is the ** id and pId2 is any empty string. */ SQLITE_PRIVATE void sqlite3Pragma( Parse *pParse, Token *pId1, /* First part of [schema.]id field */ Token *pId2, /* Second part of [schema.]id field, or NULL */ Token *pValue, /* Token for , or NULL */ int minusFlag /* True if a '-' sign preceded */ ){ char *zLeft = 0; /* Nul-terminated UTF-8 string */ char *zRight = 0; /* Nul-terminated UTF-8 string , or NULL */ const char *zDb = 0; /* The database name */ Token *pId; /* Pointer to token */ char *aFcntl[4]; /* Argument to SQLITE_FCNTL_PRAGMA */ int iDb; /* Database index for */ int lwr, upr, mid = 0; /* Binary search bounds */ int rc; /* return value form SQLITE_FCNTL_PRAGMA */ sqlite3 *db = pParse->db; /* The database connection */ Db *pDb; /* The specific database being pragmaed */ Vdbe *v = sqlite3GetVdbe(pParse); /* Prepared statement */ const struct sPragmaNames *pPragma; if( v==0 ) return; sqlite3VdbeRunOnlyOnce(v); pParse->nMem = 2; /* Interpret the [schema.] part of the pragma statement. iDb is the ** index of the database this pragma is being applied to in db.aDb[]. */ iDb = sqlite3TwoPartName(pParse, pId1, pId2, &pId); if( iDb<0 ) return; pDb = &db->aDb[iDb]; /* If the temp database has been explicitly named as part of the ** pragma, make sure it is open. */ if( iDb==1 && sqlite3OpenTempDatabase(pParse) ){ return; } zLeft = sqlite3NameFromToken(db, pId); if( !zLeft ) return; if( minusFlag ){ zRight = sqlite3MPrintf(db, "-%T", pValue); }else{ zRight = sqlite3NameFromToken(db, pValue); } assert( pId2 ); zDb = pId2->n>0 ? pDb->zDbSName : 0; if( sqlite3AuthCheck(pParse, SQLITE_PRAGMA, zLeft, zRight, zDb) ){ goto pragma_out; } /* Send an SQLITE_FCNTL_PRAGMA file-control to the underlying VFS ** connection. If it returns SQLITE_OK, then assume that the VFS ** handled the pragma and generate a no-op prepared statement. ** ** IMPLEMENTATION-OF: R-12238-55120 Whenever a PRAGMA statement is parsed, ** an SQLITE_FCNTL_PRAGMA file control is sent to the open sqlite3_file ** object corresponding to the database file to which the pragma ** statement refers. ** ** IMPLEMENTATION-OF: R-29875-31678 The argument to the SQLITE_FCNTL_PRAGMA ** file control is an array of pointers to strings (char**) in which the ** second element of the array is the name of the pragma and the third ** element is the argument to the pragma or NULL if the pragma has no ** argument. */ aFcntl[0] = 0; aFcntl[1] = zLeft; aFcntl[2] = zRight; aFcntl[3] = 0; db->busyHandler.nBusy = 0; rc = sqlite3_file_control(db, zDb, SQLITE_FCNTL_PRAGMA, (void*)aFcntl); if( rc==SQLITE_OK ){ returnSingleText(v, "result", aFcntl[0]); sqlite3_free(aFcntl[0]); goto pragma_out; } if( rc!=SQLITE_NOTFOUND ){ if( aFcntl[0] ){ sqlite3ErrorMsg(pParse, "%s", aFcntl[0]); sqlite3_free(aFcntl[0]); } pParse->nErr++; pParse->rc = rc; goto pragma_out; } /* Locate the pragma in the lookup table */ lwr = 0; upr = ArraySize(aPragmaNames)-1; while( lwr<=upr ){ mid = (lwr+upr)/2; rc = sqlite3_stricmp(zLeft, aPragmaNames[mid].zName); if( rc==0 ) break; if( rc<0 ){ upr = mid - 1; }else{ lwr = mid + 1; } } if( lwr>upr ) goto pragma_out; pPragma = &aPragmaNames[mid]; /* Make sure the database schema is loaded if the pragma requires that */ if( (pPragma->mPragFlag & PragFlag_NeedSchema)!=0 ){ if( sqlite3ReadSchema(pParse) ) goto pragma_out; } /* Jump to the appropriate pragma handler */ switch( pPragma->ePragTyp ){ #if !defined(SQLITE_OMIT_PAGER_PRAGMAS) && !defined(SQLITE_OMIT_DEPRECATED) /* ** PRAGMA [schema.]default_cache_size ** PRAGMA [schema.]default_cache_size=N ** ** The first form reports the current persistent setting for the ** page cache size. The value returned is the maximum number of ** pages in the page cache. The second form sets both the current ** page cache size value and the persistent page cache size value ** stored in the database file. ** ** Older versions of SQLite would set the default cache size to a ** negative number to indicate synchronous=OFF. These days, synchronous ** is always on by default regardless of the sign of the default cache ** size. But continue to take the absolute value of the default cache ** size of historical compatibility. */ case PragTyp_DEFAULT_CACHE_SIZE: { static const int iLn = VDBE_OFFSET_LINENO(2); static const VdbeOpList getCacheSize[] = { { OP_Transaction, 0, 0, 0}, /* 0 */ { OP_ReadCookie, 0, 1, BTREE_DEFAULT_CACHE_SIZE}, /* 1 */ { OP_IfPos, 1, 8, 0}, { OP_Integer, 0, 2, 0}, { OP_Subtract, 1, 2, 1}, { OP_IfPos, 1, 8, 0}, { OP_Integer, 0, 1, 0}, /* 6 */ { OP_Noop, 0, 0, 0}, { OP_ResultRow, 1, 1, 0}, }; VdbeOp *aOp; sqlite3VdbeUsesBtree(v, iDb); if( !zRight ){ setOneColumnName(v, "cache_size"); pParse->nMem += 2; sqlite3VdbeVerifyNoMallocRequired(v, ArraySize(getCacheSize)); aOp = sqlite3VdbeAddOpList(v, ArraySize(getCacheSize), getCacheSize, iLn); if( ONLY_IF_REALLOC_STRESS(aOp==0) ) break; aOp[0].p1 = iDb; aOp[1].p1 = iDb; aOp[6].p1 = SQLITE_DEFAULT_CACHE_SIZE; }else{ int size = sqlite3AbsInt32(sqlite3Atoi(zRight)); sqlite3BeginWriteOperation(pParse, 0, iDb); sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_DEFAULT_CACHE_SIZE, size); assert( sqlite3SchemaMutexHeld(db, iDb, 0) ); pDb->pSchema->cache_size = size; sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size); } break; } #endif /* !SQLITE_OMIT_PAGER_PRAGMAS && !SQLITE_OMIT_DEPRECATED */ #if !defined(SQLITE_OMIT_PAGER_PRAGMAS) /* ** PRAGMA [schema.]page_size ** PRAGMA [schema.]page_size=N ** ** The first form reports the current setting for the ** database page size in bytes. The second form sets the ** database page size value. The value can only be set if ** the database has not yet been created. */ case PragTyp_PAGE_SIZE: { Btree *pBt = pDb->pBt; assert( pBt!=0 ); if( !zRight ){ int size = ALWAYS(pBt) ? sqlite3BtreeGetPageSize(pBt) : 0; returnSingleInt(v, "page_size", size); }else{ /* Malloc may fail when setting the page-size, as there is an internal ** buffer that the pager module resizes using sqlite3_realloc(). */ db->nextPagesize = sqlite3Atoi(zRight); if( SQLITE_NOMEM==sqlite3BtreeSetPageSize(pBt, db->nextPagesize,-1,0) ){ sqlite3OomFault(db); } } break; } /* ** PRAGMA [schema.]secure_delete ** PRAGMA [schema.]secure_delete=ON/OFF ** ** The first form reports the current setting for the ** secure_delete flag. The second form changes the secure_delete ** flag setting and reports thenew value. */ case PragTyp_SECURE_DELETE: { Btree *pBt = pDb->pBt; int b = -1; assert( pBt!=0 ); if( zRight ){ b = sqlite3GetBoolean(zRight, 0); } if( pId2->n==0 && b>=0 ){ int ii; for(ii=0; iinDb; ii++){ sqlite3BtreeSecureDelete(db->aDb[ii].pBt, b); } } b = sqlite3BtreeSecureDelete(pBt, b); returnSingleInt(v, "secure_delete", b); break; } /* ** PRAGMA [schema.]max_page_count ** PRAGMA [schema.]max_page_count=N ** ** The first form reports the current setting for the ** maximum number of pages in the database file. The ** second form attempts to change this setting. Both ** forms return the current setting. ** ** The absolute value of N is used. This is undocumented and might ** change. The only purpose is to provide an easy way to test ** the sqlite3AbsInt32() function. ** ** PRAGMA [schema.]page_count ** ** Return the number of pages in the specified database. */ case PragTyp_PAGE_COUNT: { int iReg; sqlite3CodeVerifySchema(pParse, iDb); iReg = ++pParse->nMem; if( sqlite3Tolower(zLeft[0])=='p' ){ sqlite3VdbeAddOp2(v, OP_Pagecount, iDb, iReg); }else{ sqlite3VdbeAddOp3(v, OP_MaxPgcnt, iDb, iReg, sqlite3AbsInt32(sqlite3Atoi(zRight))); } sqlite3VdbeAddOp2(v, OP_ResultRow, iReg, 1); sqlite3VdbeSetNumCols(v, 1); sqlite3VdbeSetColName(v, 0, COLNAME_NAME, zLeft, SQLITE_TRANSIENT); break; } /* ** PRAGMA [schema.]locking_mode ** PRAGMA [schema.]locking_mode = (normal|exclusive) */ case PragTyp_LOCKING_MODE: { const char *zRet = "normal"; int eMode = getLockingMode(zRight); if( pId2->n==0 && eMode==PAGER_LOCKINGMODE_QUERY ){ /* Simple "PRAGMA locking_mode;" statement. This is a query for ** the current default locking mode (which may be different to ** the locking-mode of the main database). */ eMode = db->dfltLockMode; }else{ Pager *pPager; if( pId2->n==0 ){ /* This indicates that no database name was specified as part ** of the PRAGMA command. In this case the locking-mode must be ** set on all attached databases, as well as the main db file. ** ** Also, the sqlite3.dfltLockMode variable is set so that ** any subsequently attached databases also use the specified ** locking mode. */ int ii; assert(pDb==&db->aDb[0]); for(ii=2; iinDb; ii++){ pPager = sqlite3BtreePager(db->aDb[ii].pBt); sqlite3PagerLockingMode(pPager, eMode); } db->dfltLockMode = (u8)eMode; } pPager = sqlite3BtreePager(pDb->pBt); eMode = sqlite3PagerLockingMode(pPager, eMode); } assert( eMode==PAGER_LOCKINGMODE_NORMAL || eMode==PAGER_LOCKINGMODE_EXCLUSIVE ); if( eMode==PAGER_LOCKINGMODE_EXCLUSIVE ){ zRet = "exclusive"; } returnSingleText(v, "locking_mode", zRet); break; } /* ** PRAGMA [schema.]journal_mode ** PRAGMA [schema.]journal_mode = ** (delete|persist|off|truncate|memory|wal|off) */ case PragTyp_JOURNAL_MODE: { int eMode; /* One of the PAGER_JOURNALMODE_XXX symbols */ int ii; /* Loop counter */ setOneColumnName(v, "journal_mode"); if( zRight==0 ){ /* If there is no "=MODE" part of the pragma, do a query for the ** current mode */ eMode = PAGER_JOURNALMODE_QUERY; }else{ const char *zMode; int n = sqlite3Strlen30(zRight); for(eMode=0; (zMode = sqlite3JournalModename(eMode))!=0; eMode++){ if( sqlite3StrNICmp(zRight, zMode, n)==0 ) break; } if( !zMode ){ /* If the "=MODE" part does not match any known journal mode, ** then do a query */ eMode = PAGER_JOURNALMODE_QUERY; } } if( eMode==PAGER_JOURNALMODE_QUERY && pId2->n==0 ){ /* Convert "PRAGMA journal_mode" into "PRAGMA main.journal_mode" */ iDb = 0; pId2->n = 1; } for(ii=db->nDb-1; ii>=0; ii--){ if( db->aDb[ii].pBt && (ii==iDb || pId2->n==0) ){ sqlite3VdbeUsesBtree(v, ii); sqlite3VdbeAddOp3(v, OP_JournalMode, ii, 1, eMode); } } sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1); break; } /* ** PRAGMA [schema.]journal_size_limit ** PRAGMA [schema.]journal_size_limit=N ** ** Get or set the size limit on rollback journal files. */ case PragTyp_JOURNAL_SIZE_LIMIT: { Pager *pPager = sqlite3BtreePager(pDb->pBt); i64 iLimit = -2; if( zRight ){ sqlite3DecOrHexToI64(zRight, &iLimit); if( iLimit<-1 ) iLimit = -1; } iLimit = sqlite3PagerJournalSizeLimit(pPager, iLimit); returnSingleInt(v, "journal_size_limit", iLimit); break; } #endif /* SQLITE_OMIT_PAGER_PRAGMAS */ /* ** PRAGMA [schema.]auto_vacuum ** PRAGMA [schema.]auto_vacuum=N ** ** Get or set the value of the database 'auto-vacuum' parameter. ** The value is one of: 0 NONE 1 FULL 2 INCREMENTAL */ #ifndef SQLITE_OMIT_AUTOVACUUM case PragTyp_AUTO_VACUUM: { Btree *pBt = pDb->pBt; assert( pBt!=0 ); if( !zRight ){ returnSingleInt(v, "auto_vacuum", sqlite3BtreeGetAutoVacuum(pBt)); }else{ int eAuto = getAutoVacuum(zRight); assert( eAuto>=0 && eAuto<=2 ); db->nextAutovac = (u8)eAuto; /* Call SetAutoVacuum() to set initialize the internal auto and ** incr-vacuum flags. This is required in case this connection ** creates the database file. It is important that it is created ** as an auto-vacuum capable db. */ rc = sqlite3BtreeSetAutoVacuum(pBt, eAuto); if( rc==SQLITE_OK && (eAuto==1 || eAuto==2) ){ /* When setting the auto_vacuum mode to either "full" or ** "incremental", write the value of meta[6] in the database ** file. Before writing to meta[6], check that meta[3] indicates ** that this really is an auto-vacuum capable database. */ static const int iLn = VDBE_OFFSET_LINENO(2); static const VdbeOpList setMeta6[] = { { OP_Transaction, 0, 1, 0}, /* 0 */ { OP_ReadCookie, 0, 1, BTREE_LARGEST_ROOT_PAGE}, { OP_If, 1, 0, 0}, /* 2 */ { OP_Halt, SQLITE_OK, OE_Abort, 0}, /* 3 */ { OP_SetCookie, 0, BTREE_INCR_VACUUM, 0}, /* 4 */ }; VdbeOp *aOp; int iAddr = sqlite3VdbeCurrentAddr(v); sqlite3VdbeVerifyNoMallocRequired(v, ArraySize(setMeta6)); aOp = sqlite3VdbeAddOpList(v, ArraySize(setMeta6), setMeta6, iLn); if( ONLY_IF_REALLOC_STRESS(aOp==0) ) break; aOp[0].p1 = iDb; aOp[1].p1 = iDb; aOp[2].p2 = iAddr+4; aOp[4].p1 = iDb; aOp[4].p3 = eAuto - 1; sqlite3VdbeUsesBtree(v, iDb); } } break; } #endif /* ** PRAGMA [schema.]incremental_vacuum(N) ** ** Do N steps of incremental vacuuming on a database. */ #ifndef SQLITE_OMIT_AUTOVACUUM case PragTyp_INCREMENTAL_VACUUM: { int iLimit, addr; if( zRight==0 || !sqlite3GetInt32(zRight, &iLimit) || iLimit<=0 ){ iLimit = 0x7fffffff; } sqlite3BeginWriteOperation(pParse, 0, iDb); sqlite3VdbeAddOp2(v, OP_Integer, iLimit, 1); addr = sqlite3VdbeAddOp1(v, OP_IncrVacuum, iDb); VdbeCoverage(v); sqlite3VdbeAddOp1(v, OP_ResultRow, 1); sqlite3VdbeAddOp2(v, OP_AddImm, 1, -1); sqlite3VdbeAddOp2(v, OP_IfPos, 1, addr); VdbeCoverage(v); sqlite3VdbeJumpHere(v, addr); break; } #endif #ifndef SQLITE_OMIT_PAGER_PRAGMAS /* ** PRAGMA [schema.]cache_size ** PRAGMA [schema.]cache_size=N ** ** The first form reports the current local setting for the ** page cache size. The second form sets the local ** page cache size value. If N is positive then that is the ** number of pages in the cache. If N is negative, then the ** number of pages is adjusted so that the cache uses -N kibibytes ** of memory. */ case PragTyp_CACHE_SIZE: { assert( sqlite3SchemaMutexHeld(db, iDb, 0) ); if( !zRight ){ returnSingleInt(v, "cache_size", pDb->pSchema->cache_size); }else{ int size = sqlite3Atoi(zRight); pDb->pSchema->cache_size = size; sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size); } break; } /* ** PRAGMA [schema.]cache_spill ** PRAGMA cache_spill=BOOLEAN ** PRAGMA [schema.]cache_spill=N ** ** The first form reports the current local setting for the ** page cache spill size. The second form turns cache spill on ** or off. When turnning cache spill on, the size is set to the ** current cache_size. The third form sets a spill size that ** may be different form the cache size. ** If N is positive then that is the ** number of pages in the cache. If N is negative, then the ** number of pages is adjusted so that the cache uses -N kibibytes ** of memory. ** ** If the number of cache_spill pages is less then the number of ** cache_size pages, no spilling occurs until the page count exceeds ** the number of cache_size pages. ** ** The cache_spill=BOOLEAN setting applies to all attached schemas, ** not just the schema specified. */ case PragTyp_CACHE_SPILL: { assert( sqlite3SchemaMutexHeld(db, iDb, 0) ); if( !zRight ){ returnSingleInt(v, "cache_spill", (db->flags & SQLITE_CacheSpill)==0 ? 0 : sqlite3BtreeSetSpillSize(pDb->pBt,0)); }else{ int size = 1; if( sqlite3GetInt32(zRight, &size) ){ sqlite3BtreeSetSpillSize(pDb->pBt, size); } if( sqlite3GetBoolean(zRight, size!=0) ){ db->flags |= SQLITE_CacheSpill; }else{ db->flags &= ~SQLITE_CacheSpill; } setAllPagerFlags(db); } break; } /* ** PRAGMA [schema.]mmap_size(N) ** ** Used to set mapping size limit. The mapping size limit is ** used to limit the aggregate size of all memory mapped regions of the ** database file. If this parameter is set to zero, then memory mapping ** is not used at all. If N is negative, then the default memory map ** limit determined by sqlite3_config(SQLITE_CONFIG_MMAP_SIZE) is set. ** The parameter N is measured in bytes. ** ** This value is advisory. The underlying VFS is free to memory map ** as little or as much as it wants. Except, if N is set to 0 then the ** upper layers will never invoke the xFetch interfaces to the VFS. */ case PragTyp_MMAP_SIZE: { sqlite3_int64 sz; #if SQLITE_MAX_MMAP_SIZE>0 assert( sqlite3SchemaMutexHeld(db, iDb, 0) ); if( zRight ){ int ii; sqlite3DecOrHexToI64(zRight, &sz); if( sz<0 ) sz = sqlite3GlobalConfig.szMmap; if( pId2->n==0 ) db->szMmap = sz; for(ii=db->nDb-1; ii>=0; ii--){ if( db->aDb[ii].pBt && (ii==iDb || pId2->n==0) ){ sqlite3BtreeSetMmapLimit(db->aDb[ii].pBt, sz); } } } sz = -1; rc = sqlite3_file_control(db, zDb, SQLITE_FCNTL_MMAP_SIZE, &sz); #else sz = 0; rc = SQLITE_OK; #endif if( rc==SQLITE_OK ){ returnSingleInt(v, "mmap_size", sz); }else if( rc!=SQLITE_NOTFOUND ){ pParse->nErr++; pParse->rc = rc; } break; } /* ** PRAGMA temp_store ** PRAGMA temp_store = "default"|"memory"|"file" ** ** Return or set the local value of the temp_store flag. Changing ** the local value does not make changes to the disk file and the default ** value will be restored the next time the database is opened. ** ** Note that it is possible for the library compile-time options to ** override this setting */ case PragTyp_TEMP_STORE: { if( !zRight ){ returnSingleInt(v, "temp_store", db->temp_store); }else{ changeTempStorage(pParse, zRight); } break; } /* ** PRAGMA temp_store_directory ** PRAGMA temp_store_directory = ""|"directory_name" ** ** Return or set the local value of the temp_store_directory flag. Changing ** the value sets a specific directory to be used for temporary files. ** Setting to a null string reverts to the default temporary directory search. ** If temporary directory is changed, then invalidateTempStorage. ** */ case PragTyp_TEMP_STORE_DIRECTORY: { if( !zRight ){ returnSingleText(v, "temp_store_directory", sqlite3_temp_directory); }else{ #ifndef SQLITE_OMIT_WSD if( zRight[0] ){ int res; rc = sqlite3OsAccess(db->pVfs, zRight, SQLITE_ACCESS_READWRITE, &res); if( rc!=SQLITE_OK || res==0 ){ sqlite3ErrorMsg(pParse, "not a writable directory"); goto pragma_out; } } if( SQLITE_TEMP_STORE==0 || (SQLITE_TEMP_STORE==1 && db->temp_store<=1) || (SQLITE_TEMP_STORE==2 && db->temp_store==1) ){ invalidateTempStorage(pParse); } sqlite3_free(sqlite3_temp_directory); if( zRight[0] ){ sqlite3_temp_directory = sqlite3_mprintf("%s", zRight); }else{ sqlite3_temp_directory = 0; } #endif /* SQLITE_OMIT_WSD */ } break; } #if SQLITE_OS_WIN /* ** PRAGMA data_store_directory ** PRAGMA data_store_directory = ""|"directory_name" ** ** Return or set the local value of the data_store_directory flag. Changing ** the value sets a specific directory to be used for database files that ** were specified with a relative pathname. Setting to a null string reverts ** to the default database directory, which for database files specified with ** a relative path will probably be based on the current directory for the ** process. Database file specified with an absolute path are not impacted ** by this setting, regardless of its value. ** */ case PragTyp_DATA_STORE_DIRECTORY: { if( !zRight ){ returnSingleText(v, "data_store_directory", sqlite3_data_directory); }else{ #ifndef SQLITE_OMIT_WSD if( zRight[0] ){ int res; rc = sqlite3OsAccess(db->pVfs, zRight, SQLITE_ACCESS_READWRITE, &res); if( rc!=SQLITE_OK || res==0 ){ sqlite3ErrorMsg(pParse, "not a writable directory"); goto pragma_out; } } sqlite3_free(sqlite3_data_directory); if( zRight[0] ){ sqlite3_data_directory = sqlite3_mprintf("%s", zRight); }else{ sqlite3_data_directory = 0; } #endif /* SQLITE_OMIT_WSD */ } break; } #endif #if SQLITE_ENABLE_LOCKING_STYLE /* ** PRAGMA [schema.]lock_proxy_file ** PRAGMA [schema.]lock_proxy_file = ":auto:"|"lock_file_path" ** ** Return or set the value of the lock_proxy_file flag. Changing ** the value sets a specific file to be used for database access locks. ** */ case PragTyp_LOCK_PROXY_FILE: { if( !zRight ){ Pager *pPager = sqlite3BtreePager(pDb->pBt); char *proxy_file_path = NULL; sqlite3_file *pFile = sqlite3PagerFile(pPager); sqlite3OsFileControlHint(pFile, SQLITE_GET_LOCKPROXYFILE, &proxy_file_path); returnSingleText(v, "lock_proxy_file", proxy_file_path); }else{ Pager *pPager = sqlite3BtreePager(pDb->pBt); sqlite3_file *pFile = sqlite3PagerFile(pPager); int res; if( zRight[0] ){ res=sqlite3OsFileControl(pFile, SQLITE_SET_LOCKPROXYFILE, zRight); } else { res=sqlite3OsFileControl(pFile, SQLITE_SET_LOCKPROXYFILE, NULL); } if( res!=SQLITE_OK ){ sqlite3ErrorMsg(pParse, "failed to set lock proxy file"); goto pragma_out; } } break; } #endif /* SQLITE_ENABLE_LOCKING_STYLE */ /* ** PRAGMA [schema.]synchronous ** PRAGMA [schema.]synchronous=OFF|ON|NORMAL|FULL|EXTRA ** ** Return or set the local value of the synchronous flag. Changing ** the local value does not make changes to the disk file and the ** default value will be restored the next time the database is ** opened. */ case PragTyp_SYNCHRONOUS: { if( !zRight ){ returnSingleInt(v, "synchronous", pDb->safety_level-1); }else{ if( !db->autoCommit ){ sqlite3ErrorMsg(pParse, "Safety level may not be changed inside a transaction"); }else{ int iLevel = (getSafetyLevel(zRight,0,1)+1) & PAGER_SYNCHRONOUS_MASK; if( iLevel==0 ) iLevel = 1; pDb->safety_level = iLevel; pDb->bSyncSet = 1; setAllPagerFlags(db); } } break; } #endif /* SQLITE_OMIT_PAGER_PRAGMAS */ #ifndef SQLITE_OMIT_FLAG_PRAGMAS case PragTyp_FLAG: { if( zRight==0 ){ returnSingleInt(v, pPragma->zName, (db->flags & pPragma->iArg)!=0 ); }else{ int mask = pPragma->iArg; /* Mask of bits to set or clear. */ if( db->autoCommit==0 ){ /* Foreign key support may not be enabled or disabled while not ** in auto-commit mode. */ mask &= ~(SQLITE_ForeignKeys); } #if SQLITE_USER_AUTHENTICATION if( db->auth.authLevel==UAUTH_User ){ /* Do not allow non-admin users to modify the schema arbitrarily */ mask &= ~(SQLITE_WriteSchema); } #endif if( sqlite3GetBoolean(zRight, 0) ){ db->flags |= mask; }else{ db->flags &= ~mask; if( mask==SQLITE_DeferFKs ) db->nDeferredImmCons = 0; } /* Many of the flag-pragmas modify the code generated by the SQL ** compiler (eg. count_changes). So add an opcode to expire all ** compiled SQL statements after modifying a pragma value. */ sqlite3VdbeAddOp0(v, OP_Expire); setAllPagerFlags(db); } break; } #endif /* SQLITE_OMIT_FLAG_PRAGMAS */ #ifndef SQLITE_OMIT_SCHEMA_PRAGMAS /* ** PRAGMA table_info(
    ) ** ** Return a single row for each column of the named table. The columns of ** the returned data set are: ** ** cid: Column id (numbered from left to right, starting at 0) ** name: Column name ** type: Column declaration type. ** notnull: True if 'NOT NULL' is part of column declaration ** dflt_value: The default value for the column, if any. */ case PragTyp_TABLE_INFO: if( zRight ){ Table *pTab; pTab = sqlite3LocateTable(pParse, LOCATE_NOERR, zRight, zDb); if( pTab ){ static const char *azCol[] = { "cid", "name", "type", "notnull", "dflt_value", "pk" }; int i, k; int nHidden = 0; Column *pCol; Index *pPk = sqlite3PrimaryKeyIndex(pTab); pParse->nMem = 6; sqlite3CodeVerifySchema(pParse, iDb); setAllColumnNames(v, 6, azCol); assert( 6==ArraySize(azCol) ); sqlite3ViewGetColumnNames(pParse, pTab); for(i=0, pCol=pTab->aCol; inCol; i++, pCol++){ if( IsHiddenColumn(pCol) ){ nHidden++; continue; } if( (pCol->colFlags & COLFLAG_PRIMKEY)==0 ){ k = 0; }else if( pPk==0 ){ k = 1; }else{ for(k=1; k<=pTab->nCol && pPk->aiColumn[k-1]!=i; k++){} } assert( pCol->pDflt==0 || pCol->pDflt->op==TK_SPAN ); sqlite3VdbeMultiLoad(v, 1, "issisi", i-nHidden, pCol->zName, sqlite3ColumnType(pCol,""), pCol->notNull ? 1 : 0, pCol->pDflt ? pCol->pDflt->u.zToken : 0, k); sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 6); } } } break; case PragTyp_STATS: { static const char *azCol[] = { "table", "index", "width", "height" }; Index *pIdx; HashElem *i; v = sqlite3GetVdbe(pParse); pParse->nMem = 4; sqlite3CodeVerifySchema(pParse, iDb); setAllColumnNames(v, 4, azCol); assert( 4==ArraySize(azCol) ); for(i=sqliteHashFirst(&pDb->pSchema->tblHash); i; i=sqliteHashNext(i)){ Table *pTab = sqliteHashData(i); sqlite3VdbeMultiLoad(v, 1, "ssii", pTab->zName, 0, pTab->szTabRow, pTab->nRowLogEst); sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 4); for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){ sqlite3VdbeMultiLoad(v, 2, "sii", pIdx->zName, pIdx->szIdxRow, pIdx->aiRowLogEst[0]); sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 4); } } } break; case PragTyp_INDEX_INFO: if( zRight ){ Index *pIdx; Table *pTab; pIdx = sqlite3FindIndex(db, zRight, zDb); if( pIdx ){ static const char *azCol[] = { "seqno", "cid", "name", "desc", "coll", "key" }; int i; int mx; if( pPragma->iArg ){ /* PRAGMA index_xinfo (newer version with more rows and columns) */ mx = pIdx->nColumn; pParse->nMem = 6; }else{ /* PRAGMA index_info (legacy version) */ mx = pIdx->nKeyCol; pParse->nMem = 3; } pTab = pIdx->pTable; sqlite3CodeVerifySchema(pParse, iDb); assert( pParse->nMem<=ArraySize(azCol) ); setAllColumnNames(v, pParse->nMem, azCol); for(i=0; iaiColumn[i]; sqlite3VdbeMultiLoad(v, 1, "iis", i, cnum, cnum<0 ? 0 : pTab->aCol[cnum].zName); if( pPragma->iArg ){ sqlite3VdbeMultiLoad(v, 4, "isi", pIdx->aSortOrder[i], pIdx->azColl[i], inKeyCol); } sqlite3VdbeAddOp2(v, OP_ResultRow, 1, pParse->nMem); } } } break; case PragTyp_INDEX_LIST: if( zRight ){ Index *pIdx; Table *pTab; int i; pTab = sqlite3FindTable(db, zRight, zDb); if( pTab ){ static const char *azCol[] = { "seq", "name", "unique", "origin", "partial" }; v = sqlite3GetVdbe(pParse); pParse->nMem = 5; sqlite3CodeVerifySchema(pParse, iDb); setAllColumnNames(v, 5, azCol); assert( 5==ArraySize(azCol) ); for(pIdx=pTab->pIndex, i=0; pIdx; pIdx=pIdx->pNext, i++){ const char *azOrigin[] = { "c", "u", "pk" }; sqlite3VdbeMultiLoad(v, 1, "isisi", i, pIdx->zName, IsUniqueIndex(pIdx), azOrigin[pIdx->idxType], pIdx->pPartIdxWhere!=0); sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 5); } } } break; case PragTyp_DATABASE_LIST: { static const char *azCol[] = { "seq", "name", "file" }; int i; pParse->nMem = 3; setAllColumnNames(v, 3, azCol); assert( 3==ArraySize(azCol) ); for(i=0; inDb; i++){ if( db->aDb[i].pBt==0 ) continue; assert( db->aDb[i].zDbSName!=0 ); sqlite3VdbeMultiLoad(v, 1, "iss", i, db->aDb[i].zDbSName, sqlite3BtreeGetFilename(db->aDb[i].pBt)); sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3); } } break; case PragTyp_COLLATION_LIST: { static const char *azCol[] = { "seq", "name" }; int i = 0; HashElem *p; pParse->nMem = 2; setAllColumnNames(v, 2, azCol); assert( 2==ArraySize(azCol) ); for(p=sqliteHashFirst(&db->aCollSeq); p; p=sqliteHashNext(p)){ CollSeq *pColl = (CollSeq *)sqliteHashData(p); sqlite3VdbeMultiLoad(v, 1, "is", i++, pColl->zName); sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 2); } } break; #endif /* SQLITE_OMIT_SCHEMA_PRAGMAS */ #ifndef SQLITE_OMIT_FOREIGN_KEY case PragTyp_FOREIGN_KEY_LIST: if( zRight ){ FKey *pFK; Table *pTab; pTab = sqlite3FindTable(db, zRight, zDb); if( pTab ){ v = sqlite3GetVdbe(pParse); pFK = pTab->pFKey; if( pFK ){ static const char *azCol[] = { "id", "seq", "table", "from", "to", "on_update", "on_delete", "match" }; int i = 0; pParse->nMem = 8; sqlite3CodeVerifySchema(pParse, iDb); setAllColumnNames(v, 8, azCol); assert( 8==ArraySize(azCol) ); while(pFK){ int j; for(j=0; jnCol; j++){ sqlite3VdbeMultiLoad(v, 1, "iissssss", i, j, pFK->zTo, pTab->aCol[pFK->aCol[j].iFrom].zName, pFK->aCol[j].zCol, actionName(pFK->aAction[1]), /* ON UPDATE */ actionName(pFK->aAction[0]), /* ON DELETE */ "NONE"); sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 8); } ++i; pFK = pFK->pNextFrom; } } } } break; #endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */ #ifndef SQLITE_OMIT_FOREIGN_KEY #ifndef SQLITE_OMIT_TRIGGER case PragTyp_FOREIGN_KEY_CHECK: { FKey *pFK; /* A foreign key constraint */ Table *pTab; /* Child table contain "REFERENCES" keyword */ Table *pParent; /* Parent table that child points to */ Index *pIdx; /* Index in the parent table */ int i; /* Loop counter: Foreign key number for pTab */ int j; /* Loop counter: Field of the foreign key */ HashElem *k; /* Loop counter: Next table in schema */ int x; /* result variable */ int regResult; /* 3 registers to hold a result row */ int regKey; /* Register to hold key for checking the FK */ int regRow; /* Registers to hold a row from pTab */ int addrTop; /* Top of a loop checking foreign keys */ int addrOk; /* Jump here if the key is OK */ int *aiCols; /* child to parent column mapping */ static const char *azCol[] = { "table", "rowid", "parent", "fkid" }; regResult = pParse->nMem+1; pParse->nMem += 4; regKey = ++pParse->nMem; regRow = ++pParse->nMem; v = sqlite3GetVdbe(pParse); setAllColumnNames(v, 4, azCol); assert( 4==ArraySize(azCol) ); sqlite3CodeVerifySchema(pParse, iDb); k = sqliteHashFirst(&db->aDb[iDb].pSchema->tblHash); while( k ){ if( zRight ){ pTab = sqlite3LocateTable(pParse, 0, zRight, zDb); k = 0; }else{ pTab = (Table*)sqliteHashData(k); k = sqliteHashNext(k); } if( pTab==0 || pTab->pFKey==0 ) continue; sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName); if( pTab->nCol+regRow>pParse->nMem ) pParse->nMem = pTab->nCol + regRow; sqlite3OpenTable(pParse, 0, iDb, pTab, OP_OpenRead); sqlite3VdbeLoadString(v, regResult, pTab->zName); for(i=1, pFK=pTab->pFKey; pFK; i++, pFK=pFK->pNextFrom){ pParent = sqlite3FindTable(db, pFK->zTo, zDb); if( pParent==0 ) continue; pIdx = 0; sqlite3TableLock(pParse, iDb, pParent->tnum, 0, pParent->zName); x = sqlite3FkLocateIndex(pParse, pParent, pFK, &pIdx, 0); if( x==0 ){ if( pIdx==0 ){ sqlite3OpenTable(pParse, i, iDb, pParent, OP_OpenRead); }else{ sqlite3VdbeAddOp3(v, OP_OpenRead, i, pIdx->tnum, iDb); sqlite3VdbeSetP4KeyInfo(pParse, pIdx); } }else{ k = 0; break; } } assert( pParse->nErr>0 || pFK==0 ); if( pFK ) break; if( pParse->nTabnTab = i; addrTop = sqlite3VdbeAddOp1(v, OP_Rewind, 0); VdbeCoverage(v); for(i=1, pFK=pTab->pFKey; pFK; i++, pFK=pFK->pNextFrom){ pParent = sqlite3FindTable(db, pFK->zTo, zDb); pIdx = 0; aiCols = 0; if( pParent ){ x = sqlite3FkLocateIndex(pParse, pParent, pFK, &pIdx, &aiCols); assert( x==0 ); } addrOk = sqlite3VdbeMakeLabel(v); if( pParent && pIdx==0 ){ int iKey = pFK->aCol[0].iFrom; assert( iKey>=0 && iKeynCol ); if( iKey!=pTab->iPKey ){ sqlite3VdbeAddOp3(v, OP_Column, 0, iKey, regRow); sqlite3ColumnDefault(v, pTab, iKey, regRow); sqlite3VdbeAddOp2(v, OP_IsNull, regRow, addrOk); VdbeCoverage(v); }else{ sqlite3VdbeAddOp2(v, OP_Rowid, 0, regRow); } sqlite3VdbeAddOp3(v, OP_SeekRowid, i, 0, regRow); VdbeCoverage(v); sqlite3VdbeGoto(v, addrOk); sqlite3VdbeJumpHere(v, sqlite3VdbeCurrentAddr(v)-2); }else{ for(j=0; jnCol; j++){ sqlite3ExprCodeGetColumnOfTable(v, pTab, 0, aiCols ? aiCols[j] : pFK->aCol[j].iFrom, regRow+j); sqlite3VdbeAddOp2(v, OP_IsNull, regRow+j, addrOk); VdbeCoverage(v); } if( pParent ){ sqlite3VdbeAddOp4(v, OP_MakeRecord, regRow, pFK->nCol, regKey, sqlite3IndexAffinityStr(db,pIdx), pFK->nCol); sqlite3VdbeAddOp4Int(v, OP_Found, i, addrOk, regKey, 0); VdbeCoverage(v); } } sqlite3VdbeAddOp2(v, OP_Rowid, 0, regResult+1); sqlite3VdbeMultiLoad(v, regResult+2, "si", pFK->zTo, i-1); sqlite3VdbeAddOp2(v, OP_ResultRow, regResult, 4); sqlite3VdbeResolveLabel(v, addrOk); sqlite3DbFree(db, aiCols); } sqlite3VdbeAddOp2(v, OP_Next, 0, addrTop+1); VdbeCoverage(v); sqlite3VdbeJumpHere(v, addrTop); } } break; #endif /* !defined(SQLITE_OMIT_TRIGGER) */ #endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */ #ifndef NDEBUG case PragTyp_PARSER_TRACE: { if( zRight ){ if( sqlite3GetBoolean(zRight, 0) ){ sqlite3ParserTrace(stdout, "parser: "); }else{ sqlite3ParserTrace(0, 0); } } } break; #endif /* Reinstall the LIKE and GLOB functions. The variant of LIKE ** used will be case sensitive or not depending on the RHS. */ case PragTyp_CASE_SENSITIVE_LIKE: { if( zRight ){ sqlite3RegisterLikeFunctions(db, sqlite3GetBoolean(zRight, 0)); } } break; #ifndef SQLITE_INTEGRITY_CHECK_ERROR_MAX # define SQLITE_INTEGRITY_CHECK_ERROR_MAX 100 #endif #ifndef SQLITE_OMIT_INTEGRITY_CHECK /* Pragma "quick_check" is reduced version of ** integrity_check designed to detect most database corruption ** without most of the overhead of a full integrity-check. */ case PragTyp_INTEGRITY_CHECK: { int i, j, addr, mxErr; int isQuick = (sqlite3Tolower(zLeft[0])=='q'); /* If the PRAGMA command was of the form "PRAGMA .integrity_check", ** then iDb is set to the index of the database identified by . ** In this case, the integrity of database iDb only is verified by ** the VDBE created below. ** ** Otherwise, if the command was simply "PRAGMA integrity_check" (or ** "PRAGMA quick_check"), then iDb is set to 0. In this case, set iDb ** to -1 here, to indicate that the VDBE should verify the integrity ** of all attached databases. */ assert( iDb>=0 ); assert( iDb==0 || pId2->z ); if( pId2->z==0 ) iDb = -1; /* Initialize the VDBE program */ pParse->nMem = 6; setOneColumnName(v, "integrity_check"); /* Set the maximum error count */ mxErr = SQLITE_INTEGRITY_CHECK_ERROR_MAX; if( zRight ){ sqlite3GetInt32(zRight, &mxErr); if( mxErr<=0 ){ mxErr = SQLITE_INTEGRITY_CHECK_ERROR_MAX; } } sqlite3VdbeAddOp2(v, OP_Integer, mxErr, 1); /* reg[1] holds errors left */ /* Do an integrity check on each database file */ for(i=0; inDb; i++){ HashElem *x; Hash *pTbls; int *aRoot; int cnt = 0; int mxIdx = 0; int nIdx; if( OMIT_TEMPDB && i==1 ) continue; if( iDb>=0 && i!=iDb ) continue; sqlite3CodeVerifySchema(pParse, i); addr = sqlite3VdbeAddOp1(v, OP_IfPos, 1); /* Halt if out of errors */ VdbeCoverage(v); sqlite3VdbeAddOp2(v, OP_Halt, 0, 0); sqlite3VdbeJumpHere(v, addr); /* Do an integrity check of the B-Tree ** ** Begin by finding the root pages numbers ** for all tables and indices in the database. */ assert( sqlite3SchemaMutexHeld(db, i, 0) ); pTbls = &db->aDb[i].pSchema->tblHash; for(cnt=0, x=sqliteHashFirst(pTbls); x; x=sqliteHashNext(x)){ Table *pTab = sqliteHashData(x); Index *pIdx; if( HasRowid(pTab) ) cnt++; for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){ cnt++; } if( nIdx>mxIdx ) mxIdx = nIdx; } aRoot = sqlite3DbMallocRawNN(db, sizeof(int)*(cnt+1)); if( aRoot==0 ) break; for(cnt=0, x=sqliteHashFirst(pTbls); x; x=sqliteHashNext(x)){ Table *pTab = sqliteHashData(x); Index *pIdx; if( HasRowid(pTab) ) aRoot[cnt++] = pTab->tnum; for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){ aRoot[cnt++] = pIdx->tnum; } } aRoot[cnt] = 0; /* Make sure sufficient number of registers have been allocated */ pParse->nMem = MAX( pParse->nMem, 8+mxIdx ); /* Do the b-tree integrity checks */ sqlite3VdbeAddOp4(v, OP_IntegrityCk, 2, cnt, 1, (char*)aRoot,P4_INTARRAY); sqlite3VdbeChangeP5(v, (u8)i); addr = sqlite3VdbeAddOp1(v, OP_IsNull, 2); VdbeCoverage(v); sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, sqlite3MPrintf(db, "*** in database %s ***\n", db->aDb[i].zDbSName), P4_DYNAMIC); sqlite3VdbeAddOp3(v, OP_Move, 2, 4, 1); sqlite3VdbeAddOp3(v, OP_Concat, 4, 3, 2); sqlite3VdbeAddOp2(v, OP_ResultRow, 2, 1); sqlite3VdbeJumpHere(v, addr); /* Make sure all the indices are constructed correctly. */ for(x=sqliteHashFirst(pTbls); x && !isQuick; x=sqliteHashNext(x)){ Table *pTab = sqliteHashData(x); Index *pIdx, *pPk; Index *pPrior = 0; int loopTop; int iDataCur, iIdxCur; int r1 = -1; if( pTab->pIndex==0 ) continue; pPk = HasRowid(pTab) ? 0 : sqlite3PrimaryKeyIndex(pTab); addr = sqlite3VdbeAddOp1(v, OP_IfPos, 1); /* Stop if out of errors */ VdbeCoverage(v); sqlite3VdbeAddOp2(v, OP_Halt, 0, 0); sqlite3VdbeJumpHere(v, addr); sqlite3ExprCacheClear(pParse); sqlite3OpenTableAndIndices(pParse, pTab, OP_OpenRead, 0, 1, 0, &iDataCur, &iIdxCur); sqlite3VdbeAddOp2(v, OP_Integer, 0, 7); for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){ sqlite3VdbeAddOp2(v, OP_Integer, 0, 8+j); /* index entries counter */ } assert( pParse->nMem>=8+j ); assert( sqlite3NoTempsInRange(pParse,1,7+j) ); sqlite3VdbeAddOp2(v, OP_Rewind, iDataCur, 0); VdbeCoverage(v); loopTop = sqlite3VdbeAddOp2(v, OP_AddImm, 7, 1); /* Verify that all NOT NULL columns really are NOT NULL */ for(j=0; jnCol; j++){ char *zErr; int jmp2, jmp3; if( j==pTab->iPKey ) continue; if( pTab->aCol[j].notNull==0 ) continue; sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, j, 3); sqlite3VdbeChangeP5(v, OPFLAG_TYPEOFARG); jmp2 = sqlite3VdbeAddOp1(v, OP_NotNull, 3); VdbeCoverage(v); sqlite3VdbeAddOp2(v, OP_AddImm, 1, -1); /* Decrement error limit */ zErr = sqlite3MPrintf(db, "NULL value in %s.%s", pTab->zName, pTab->aCol[j].zName); sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, zErr, P4_DYNAMIC); sqlite3VdbeAddOp2(v, OP_ResultRow, 3, 1); jmp3 = sqlite3VdbeAddOp1(v, OP_IfPos, 1); VdbeCoverage(v); sqlite3VdbeAddOp0(v, OP_Halt); sqlite3VdbeJumpHere(v, jmp2); sqlite3VdbeJumpHere(v, jmp3); } /* Validate index entries for the current row */ for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){ int jmp2, jmp3, jmp4, jmp5; int ckUniq = sqlite3VdbeMakeLabel(v); if( pPk==pIdx ) continue; r1 = sqlite3GenerateIndexKey(pParse, pIdx, iDataCur, 0, 0, &jmp3, pPrior, r1); pPrior = pIdx; sqlite3VdbeAddOp2(v, OP_AddImm, 8+j, 1); /* increment entry count */ /* Verify that an index entry exists for the current table row */ jmp2 = sqlite3VdbeAddOp4Int(v, OP_Found, iIdxCur+j, ckUniq, r1, pIdx->nColumn); VdbeCoverage(v); sqlite3VdbeAddOp2(v, OP_AddImm, 1, -1); /* Decrement error limit */ sqlite3VdbeLoadString(v, 3, "row "); sqlite3VdbeAddOp3(v, OP_Concat, 7, 3, 3); sqlite3VdbeLoadString(v, 4, " missing from index "); sqlite3VdbeAddOp3(v, OP_Concat, 4, 3, 3); jmp5 = sqlite3VdbeLoadString(v, 4, pIdx->zName); sqlite3VdbeAddOp3(v, OP_Concat, 4, 3, 3); sqlite3VdbeAddOp2(v, OP_ResultRow, 3, 1); jmp4 = sqlite3VdbeAddOp1(v, OP_IfPos, 1); VdbeCoverage(v); sqlite3VdbeAddOp0(v, OP_Halt); sqlite3VdbeJumpHere(v, jmp2); /* For UNIQUE indexes, verify that only one entry exists with the ** current key. The entry is unique if (1) any column is NULL ** or (2) the next entry has a different key */ if( IsUniqueIndex(pIdx) ){ int uniqOk = sqlite3VdbeMakeLabel(v); int jmp6; int kk; for(kk=0; kknKeyCol; kk++){ int iCol = pIdx->aiColumn[kk]; assert( iCol!=XN_ROWID && iColnCol ); if( iCol>=0 && pTab->aCol[iCol].notNull ) continue; sqlite3VdbeAddOp2(v, OP_IsNull, r1+kk, uniqOk); VdbeCoverage(v); } jmp6 = sqlite3VdbeAddOp1(v, OP_Next, iIdxCur+j); VdbeCoverage(v); sqlite3VdbeGoto(v, uniqOk); sqlite3VdbeJumpHere(v, jmp6); sqlite3VdbeAddOp4Int(v, OP_IdxGT, iIdxCur+j, uniqOk, r1, pIdx->nKeyCol); VdbeCoverage(v); sqlite3VdbeAddOp2(v, OP_AddImm, 1, -1); /* Decrement error limit */ sqlite3VdbeLoadString(v, 3, "non-unique entry in index "); sqlite3VdbeGoto(v, jmp5); sqlite3VdbeResolveLabel(v, uniqOk); } sqlite3VdbeJumpHere(v, jmp4); sqlite3ResolvePartIdxLabel(pParse, jmp3); } sqlite3VdbeAddOp2(v, OP_Next, iDataCur, loopTop); VdbeCoverage(v); sqlite3VdbeJumpHere(v, loopTop-1); #ifndef SQLITE_OMIT_BTREECOUNT sqlite3VdbeLoadString(v, 2, "wrong # of entries in index "); for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){ if( pPk==pIdx ) continue; addr = sqlite3VdbeCurrentAddr(v); sqlite3VdbeAddOp2(v, OP_IfPos, 1, addr+2); VdbeCoverage(v); sqlite3VdbeAddOp2(v, OP_Halt, 0, 0); sqlite3VdbeAddOp2(v, OP_Count, iIdxCur+j, 3); sqlite3VdbeAddOp3(v, OP_Eq, 8+j, addr+8, 3); VdbeCoverage(v); sqlite3VdbeChangeP5(v, SQLITE_NOTNULL); sqlite3VdbeAddOp2(v, OP_AddImm, 1, -1); sqlite3VdbeLoadString(v, 3, pIdx->zName); sqlite3VdbeAddOp3(v, OP_Concat, 3, 2, 7); sqlite3VdbeAddOp2(v, OP_ResultRow, 7, 1); } #endif /* SQLITE_OMIT_BTREECOUNT */ } } { static const int iLn = VDBE_OFFSET_LINENO(2); static const VdbeOpList endCode[] = { { OP_AddImm, 1, 0, 0}, /* 0 */ { OP_If, 1, 4, 0}, /* 1 */ { OP_String8, 0, 3, 0}, /* 2 */ { OP_ResultRow, 3, 1, 0}, /* 3 */ }; VdbeOp *aOp; aOp = sqlite3VdbeAddOpList(v, ArraySize(endCode), endCode, iLn); if( aOp ){ aOp[0].p2 = -mxErr; aOp[2].p4type = P4_STATIC; aOp[2].p4.z = "ok"; } } } break; #endif /* SQLITE_OMIT_INTEGRITY_CHECK */ #ifndef SQLITE_OMIT_UTF16 /* ** PRAGMA encoding ** PRAGMA encoding = "utf-8"|"utf-16"|"utf-16le"|"utf-16be" ** ** In its first form, this pragma returns the encoding of the main ** database. If the database is not initialized, it is initialized now. ** ** The second form of this pragma is a no-op if the main database file ** has not already been initialized. In this case it sets the default ** encoding that will be used for the main database file if a new file ** is created. If an existing main database file is opened, then the ** default text encoding for the existing database is used. ** ** In all cases new databases created using the ATTACH command are ** created to use the same default text encoding as the main database. If ** the main database has not been initialized and/or created when ATTACH ** is executed, this is done before the ATTACH operation. ** ** In the second form this pragma sets the text encoding to be used in ** new database files created using this database handle. It is only ** useful if invoked immediately after the main database i */ case PragTyp_ENCODING: { static const struct EncName { char *zName; u8 enc; } encnames[] = { { "UTF8", SQLITE_UTF8 }, { "UTF-8", SQLITE_UTF8 }, /* Must be element [1] */ { "UTF-16le", SQLITE_UTF16LE }, /* Must be element [2] */ { "UTF-16be", SQLITE_UTF16BE }, /* Must be element [3] */ { "UTF16le", SQLITE_UTF16LE }, { "UTF16be", SQLITE_UTF16BE }, { "UTF-16", 0 }, /* SQLITE_UTF16NATIVE */ { "UTF16", 0 }, /* SQLITE_UTF16NATIVE */ { 0, 0 } }; const struct EncName *pEnc; if( !zRight ){ /* "PRAGMA encoding" */ if( sqlite3ReadSchema(pParse) ) goto pragma_out; assert( encnames[SQLITE_UTF8].enc==SQLITE_UTF8 ); assert( encnames[SQLITE_UTF16LE].enc==SQLITE_UTF16LE ); assert( encnames[SQLITE_UTF16BE].enc==SQLITE_UTF16BE ); returnSingleText(v, "encoding", encnames[ENC(pParse->db)].zName); }else{ /* "PRAGMA encoding = XXX" */ /* Only change the value of sqlite.enc if the database handle is not ** initialized. If the main database exists, the new sqlite.enc value ** will be overwritten when the schema is next loaded. If it does not ** already exists, it will be created to use the new encoding value. */ if( !(DbHasProperty(db, 0, DB_SchemaLoaded)) || DbHasProperty(db, 0, DB_Empty) ){ for(pEnc=&encnames[0]; pEnc->zName; pEnc++){ if( 0==sqlite3StrICmp(zRight, pEnc->zName) ){ SCHEMA_ENC(db) = ENC(db) = pEnc->enc ? pEnc->enc : SQLITE_UTF16NATIVE; break; } } if( !pEnc->zName ){ sqlite3ErrorMsg(pParse, "unsupported encoding: %s", zRight); } } } } break; #endif /* SQLITE_OMIT_UTF16 */ #ifndef SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS /* ** PRAGMA [schema.]schema_version ** PRAGMA [schema.]schema_version = ** ** PRAGMA [schema.]user_version ** PRAGMA [schema.]user_version = ** ** PRAGMA [schema.]freelist_count ** ** PRAGMA [schema.]data_version ** ** PRAGMA [schema.]application_id ** PRAGMA [schema.]application_id = ** ** The pragma's schema_version and user_version are used to set or get ** the value of the schema-version and user-version, respectively. Both ** the schema-version and the user-version are 32-bit signed integers ** stored in the database header. ** ** The schema-cookie is usually only manipulated internally by SQLite. It ** is incremented by SQLite whenever the database schema is modified (by ** creating or dropping a table or index). The schema version is used by ** SQLite each time a query is executed to ensure that the internal cache ** of the schema used when compiling the SQL query matches the schema of ** the database against which the compiled query is actually executed. ** Subverting this mechanism by using "PRAGMA schema_version" to modify ** the schema-version is potentially dangerous and may lead to program ** crashes or database corruption. Use with caution! ** ** The user-version is not used internally by SQLite. It may be used by ** applications for any purpose. */ case PragTyp_HEADER_VALUE: { int iCookie = pPragma->iArg; /* Which cookie to read or write */ sqlite3VdbeUsesBtree(v, iDb); if( zRight && (pPragma->mPragFlag & PragFlag_ReadOnly)==0 ){ /* Write the specified cookie value */ static const VdbeOpList setCookie[] = { { OP_Transaction, 0, 1, 0}, /* 0 */ { OP_SetCookie, 0, 0, 0}, /* 1 */ }; VdbeOp *aOp; sqlite3VdbeVerifyNoMallocRequired(v, ArraySize(setCookie)); aOp = sqlite3VdbeAddOpList(v, ArraySize(setCookie), setCookie, 0); if( ONLY_IF_REALLOC_STRESS(aOp==0) ) break; aOp[0].p1 = iDb; aOp[1].p1 = iDb; aOp[1].p2 = iCookie; aOp[1].p3 = sqlite3Atoi(zRight); }else{ /* Read the specified cookie value */ static const VdbeOpList readCookie[] = { { OP_Transaction, 0, 0, 0}, /* 0 */ { OP_ReadCookie, 0, 1, 0}, /* 1 */ { OP_ResultRow, 1, 1, 0} }; VdbeOp *aOp; sqlite3VdbeVerifyNoMallocRequired(v, ArraySize(readCookie)); aOp = sqlite3VdbeAddOpList(v, ArraySize(readCookie),readCookie,0); if( ONLY_IF_REALLOC_STRESS(aOp==0) ) break; aOp[0].p1 = iDb; aOp[1].p1 = iDb; aOp[1].p3 = iCookie; sqlite3VdbeSetNumCols(v, 1); sqlite3VdbeSetColName(v, 0, COLNAME_NAME, zLeft, SQLITE_TRANSIENT); sqlite3VdbeReusable(v); } } break; #endif /* SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS */ #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS /* ** PRAGMA compile_options ** ** Return the names of all compile-time options used in this build, ** one option per row. */ case PragTyp_COMPILE_OPTIONS: { int i = 0; const char *zOpt; pParse->nMem = 1; setOneColumnName(v, "compile_option"); while( (zOpt = sqlite3_compileoption_get(i++))!=0 ){ sqlite3VdbeLoadString(v, 1, zOpt); sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1); } sqlite3VdbeReusable(v); } break; #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */ #ifndef SQLITE_OMIT_WAL /* ** PRAGMA [schema.]wal_checkpoint = passive|full|restart|truncate ** ** Checkpoint the database. */ case PragTyp_WAL_CHECKPOINT: { static const char *azCol[] = { "busy", "log", "checkpointed" }; int iBt = (pId2->z?iDb:SQLITE_MAX_ATTACHED); int eMode = SQLITE_CHECKPOINT_PASSIVE; if( zRight ){ if( sqlite3StrICmp(zRight, "full")==0 ){ eMode = SQLITE_CHECKPOINT_FULL; }else if( sqlite3StrICmp(zRight, "restart")==0 ){ eMode = SQLITE_CHECKPOINT_RESTART; }else if( sqlite3StrICmp(zRight, "truncate")==0 ){ eMode = SQLITE_CHECKPOINT_TRUNCATE; } } setAllColumnNames(v, 3, azCol); assert( 3==ArraySize(azCol) ); pParse->nMem = 3; sqlite3VdbeAddOp3(v, OP_Checkpoint, iBt, eMode, 1); sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3); } break; /* ** PRAGMA wal_autocheckpoint ** PRAGMA wal_autocheckpoint = N ** ** Configure a database connection to automatically checkpoint a database ** after accumulating N frames in the log. Or query for the current value ** of N. */ case PragTyp_WAL_AUTOCHECKPOINT: { if( zRight ){ sqlite3_wal_autocheckpoint(db, sqlite3Atoi(zRight)); } returnSingleInt(v, "wal_autocheckpoint", db->xWalCallback==sqlite3WalDefaultHook ? SQLITE_PTR_TO_INT(db->pWalArg) : 0); } break; #endif /* ** PRAGMA shrink_memory ** ** IMPLEMENTATION-OF: R-23445-46109 This pragma causes the database ** connection on which it is invoked to free up as much memory as it ** can, by calling sqlite3_db_release_memory(). */ case PragTyp_SHRINK_MEMORY: { sqlite3_db_release_memory(db); break; } /* ** PRAGMA busy_timeout ** PRAGMA busy_timeout = N ** ** Call sqlite3_busy_timeout(db, N). Return the current timeout value ** if one is set. If no busy handler or a different busy handler is set ** then 0 is returned. Setting the busy_timeout to 0 or negative ** disables the timeout. */ /*case PragTyp_BUSY_TIMEOUT*/ default: { assert( pPragma->ePragTyp==PragTyp_BUSY_TIMEOUT ); if( zRight ){ sqlite3_busy_timeout(db, sqlite3Atoi(zRight)); } returnSingleInt(v, "timeout", db->busyTimeout); break; } /* ** PRAGMA soft_heap_limit ** PRAGMA soft_heap_limit = N ** ** IMPLEMENTATION-OF: R-26343-45930 This pragma invokes the ** sqlite3_soft_heap_limit64() interface with the argument N, if N is ** specified and is a non-negative integer. ** IMPLEMENTATION-OF: R-64451-07163 The soft_heap_limit pragma always ** returns the same integer that would be returned by the ** sqlite3_soft_heap_limit64(-1) C-language function. */ case PragTyp_SOFT_HEAP_LIMIT: { sqlite3_int64 N; if( zRight && sqlite3DecOrHexToI64(zRight, &N)==SQLITE_OK ){ sqlite3_soft_heap_limit64(N); } returnSingleInt(v, "soft_heap_limit", sqlite3_soft_heap_limit64(-1)); break; } /* ** PRAGMA threads ** PRAGMA threads = N ** ** Configure the maximum number of worker threads. Return the new ** maximum, which might be less than requested. */ case PragTyp_THREADS: { sqlite3_int64 N; if( zRight && sqlite3DecOrHexToI64(zRight, &N)==SQLITE_OK && N>=0 ){ sqlite3_limit(db, SQLITE_LIMIT_WORKER_THREADS, (int)(N&0x7fffffff)); } returnSingleInt(v, "threads", sqlite3_limit(db, SQLITE_LIMIT_WORKER_THREADS, -1)); break; } #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST) /* ** Report the current state of file logs for all databases */ case PragTyp_LOCK_STATUS: { static const char *const azLockName[] = { "unlocked", "shared", "reserved", "pending", "exclusive" }; static const char *azCol[] = { "database", "status" }; int i; setAllColumnNames(v, 2, azCol); assert( 2==ArraySize(azCol) ); pParse->nMem = 2; for(i=0; inDb; i++){ Btree *pBt; const char *zState = "unknown"; int j; if( db->aDb[i].zDbSName==0 ) continue; pBt = db->aDb[i].pBt; if( pBt==0 || sqlite3BtreePager(pBt)==0 ){ zState = "closed"; }else if( sqlite3_file_control(db, i ? db->aDb[i].zDbSName : 0, SQLITE_FCNTL_LOCKSTATE, &j)==SQLITE_OK ){ zState = azLockName[j]; } sqlite3VdbeMultiLoad(v, 1, "ss", db->aDb[i].zDbSName, zState); sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 2); } break; } #endif #ifdef SQLITE_HAS_CODEC case PragTyp_KEY: { if( zRight ) sqlite3_key_v2(db, zDb, zRight, sqlite3Strlen30(zRight)); break; } case PragTyp_REKEY: { if( zRight ) sqlite3_rekey_v2(db, zDb, zRight, sqlite3Strlen30(zRight)); break; } case PragTyp_HEXKEY: { if( zRight ){ u8 iByte; int i; char zKey[40]; for(i=0, iByte=0; idb; if( !db->mallocFailed && (db->flags & SQLITE_RecoveryMode)==0 ){ char *z; if( zObj==0 ) zObj = "?"; z = sqlite3MPrintf(db, "malformed database schema (%s)", zObj); if( zExtra ) z = sqlite3MPrintf(db, "%z - %s", z, zExtra); sqlite3DbFree(db, *pData->pzErrMsg); *pData->pzErrMsg = z; } pData->rc = db->mallocFailed ? SQLITE_NOMEM_BKPT : SQLITE_CORRUPT_BKPT; } /* ** This is the callback routine for the code that initializes the ** database. See sqlite3Init() below for additional information. ** This routine is also called from the OP_ParseSchema opcode of the VDBE. ** ** Each callback contains the following information: ** ** argv[0] = name of thing being created ** argv[1] = root page number for table or index. 0 for trigger or view. ** argv[2] = SQL text for the CREATE statement. ** */ SQLITE_PRIVATE int sqlite3InitCallback(void *pInit, int argc, char **argv, char **NotUsed){ InitData *pData = (InitData*)pInit; sqlite3 *db = pData->db; int iDb = pData->iDb; assert( argc==3 ); UNUSED_PARAMETER2(NotUsed, argc); assert( sqlite3_mutex_held(db->mutex) ); DbClearProperty(db, iDb, DB_Empty); if( db->mallocFailed ){ corruptSchema(pData, argv[0], 0); return 1; } assert( iDb>=0 && iDbnDb ); if( argv==0 ) return 0; /* Might happen if EMPTY_RESULT_CALLBACKS are on */ if( argv[1]==0 ){ corruptSchema(pData, argv[0], 0); }else if( sqlite3_strnicmp(argv[2],"create ",7)==0 ){ /* Call the parser to process a CREATE TABLE, INDEX or VIEW. ** But because db->init.busy is set to 1, no VDBE code is generated ** or executed. All the parser does is build the internal data ** structures that describe the table, index, or view. */ int rc; u8 saved_iDb = db->init.iDb; sqlite3_stmt *pStmt; TESTONLY(int rcp); /* Return code from sqlite3_prepare() */ assert( db->init.busy ); db->init.iDb = iDb; db->init.newTnum = sqlite3Atoi(argv[1]); db->init.orphanTrigger = 0; TESTONLY(rcp = ) sqlite3_prepare(db, argv[2], -1, &pStmt, 0); rc = db->errCode; assert( (rc&0xFF)==(rcp&0xFF) ); db->init.iDb = saved_iDb; assert( saved_iDb==0 || (db->flags & SQLITE_Vacuum)!=0 ); if( SQLITE_OK!=rc ){ if( db->init.orphanTrigger ){ assert( iDb==1 ); }else{ pData->rc = rc; if( rc==SQLITE_NOMEM ){ sqlite3OomFault(db); }else if( rc!=SQLITE_INTERRUPT && (rc&0xFF)!=SQLITE_LOCKED ){ corruptSchema(pData, argv[0], sqlite3_errmsg(db)); } } } sqlite3_finalize(pStmt); }else if( argv[0]==0 || (argv[2]!=0 && argv[2][0]!=0) ){ corruptSchema(pData, argv[0], 0); }else{ /* If the SQL column is blank it means this is an index that ** was created to be the PRIMARY KEY or to fulfill a UNIQUE ** constraint for a CREATE TABLE. The index should have already ** been created when we processed the CREATE TABLE. All we have ** to do here is record the root page number for that index. */ Index *pIndex; pIndex = sqlite3FindIndex(db, argv[0], db->aDb[iDb].zDbSName); if( pIndex==0 ){ /* This can occur if there exists an index on a TEMP table which ** has the same name as another index on a permanent index. Since ** the permanent table is hidden by the TEMP table, we can also ** safely ignore the index on the permanent table. */ /* Do Nothing */; }else if( sqlite3GetInt32(argv[1], &pIndex->tnum)==0 ){ corruptSchema(pData, argv[0], "invalid rootpage"); } } return 0; } /* ** Attempt to read the database schema and initialize internal ** data structures for a single database file. The index of the ** database file is given by iDb. iDb==0 is used for the main ** database. iDb==1 should never be used. iDb>=2 is used for ** auxiliary databases. Return one of the SQLITE_ error codes to ** indicate success or failure. */ static int sqlite3InitOne(sqlite3 *db, int iDb, char **pzErrMsg){ int rc; int i; #ifndef SQLITE_OMIT_DEPRECATED int size; #endif Db *pDb; char const *azArg[4]; int meta[5]; InitData initData; const char *zMasterName; int openedTransaction = 0; assert( iDb>=0 && iDbnDb ); assert( db->aDb[iDb].pSchema ); assert( sqlite3_mutex_held(db->mutex) ); assert( iDb==1 || sqlite3BtreeHoldsMutex(db->aDb[iDb].pBt) ); /* Construct the in-memory representation schema tables (sqlite_master or ** sqlite_temp_master) by invoking the parser directly. The appropriate ** table name will be inserted automatically by the parser so we can just ** use the abbreviation "x" here. The parser will also automatically tag ** the schema table as read-only. */ azArg[0] = zMasterName = SCHEMA_TABLE(iDb); azArg[1] = "1"; azArg[2] = "CREATE TABLE x(type text,name text,tbl_name text," "rootpage integer,sql text)"; azArg[3] = 0; initData.db = db; initData.iDb = iDb; initData.rc = SQLITE_OK; initData.pzErrMsg = pzErrMsg; sqlite3InitCallback(&initData, 3, (char **)azArg, 0); if( initData.rc ){ rc = initData.rc; goto error_out; } /* Create a cursor to hold the database open */ pDb = &db->aDb[iDb]; if( pDb->pBt==0 ){ if( !OMIT_TEMPDB && ALWAYS(iDb==1) ){ DbSetProperty(db, 1, DB_SchemaLoaded); } return SQLITE_OK; } /* If there is not already a read-only (or read-write) transaction opened ** on the b-tree database, open one now. If a transaction is opened, it ** will be closed before this function returns. */ sqlite3BtreeEnter(pDb->pBt); if( !sqlite3BtreeIsInReadTrans(pDb->pBt) ){ rc = sqlite3BtreeBeginTrans(pDb->pBt, 0); if( rc!=SQLITE_OK ){ sqlite3SetString(pzErrMsg, db, sqlite3ErrStr(rc)); goto initone_error_out; } openedTransaction = 1; } /* Get the database meta information. ** ** Meta values are as follows: ** meta[0] Schema cookie. Changes with each schema change. ** meta[1] File format of schema layer. ** meta[2] Size of the page cache. ** meta[3] Largest rootpage (auto/incr_vacuum mode) ** meta[4] Db text encoding. 1:UTF-8 2:UTF-16LE 3:UTF-16BE ** meta[5] User version ** meta[6] Incremental vacuum mode ** meta[7] unused ** meta[8] unused ** meta[9] unused ** ** Note: The #defined SQLITE_UTF* symbols in sqliteInt.h correspond to ** the possible values of meta[4]. */ for(i=0; ipBt, i+1, (u32 *)&meta[i]); } pDb->pSchema->schema_cookie = meta[BTREE_SCHEMA_VERSION-1]; /* If opening a non-empty database, check the text encoding. For the ** main database, set sqlite3.enc to the encoding of the main database. ** For an attached db, it is an error if the encoding is not the same ** as sqlite3.enc. */ if( meta[BTREE_TEXT_ENCODING-1] ){ /* text encoding */ if( iDb==0 ){ #ifndef SQLITE_OMIT_UTF16 u8 encoding; /* If opening the main database, set ENC(db). */ encoding = (u8)meta[BTREE_TEXT_ENCODING-1] & 3; if( encoding==0 ) encoding = SQLITE_UTF8; ENC(db) = encoding; #else ENC(db) = SQLITE_UTF8; #endif }else{ /* If opening an attached database, the encoding much match ENC(db) */ if( meta[BTREE_TEXT_ENCODING-1]!=ENC(db) ){ sqlite3SetString(pzErrMsg, db, "attached databases must use the same" " text encoding as main database"); rc = SQLITE_ERROR; goto initone_error_out; } } }else{ DbSetProperty(db, iDb, DB_Empty); } pDb->pSchema->enc = ENC(db); if( pDb->pSchema->cache_size==0 ){ #ifndef SQLITE_OMIT_DEPRECATED size = sqlite3AbsInt32(meta[BTREE_DEFAULT_CACHE_SIZE-1]); if( size==0 ){ size = SQLITE_DEFAULT_CACHE_SIZE; } pDb->pSchema->cache_size = size; #else pDb->pSchema->cache_size = SQLITE_DEFAULT_CACHE_SIZE; #endif sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size); } /* ** file_format==1 Version 3.0.0. ** file_format==2 Version 3.1.3. // ALTER TABLE ADD COLUMN ** file_format==3 Version 3.1.4. // ditto but with non-NULL defaults ** file_format==4 Version 3.3.0. // DESC indices. Boolean constants */ pDb->pSchema->file_format = (u8)meta[BTREE_FILE_FORMAT-1]; if( pDb->pSchema->file_format==0 ){ pDb->pSchema->file_format = 1; } if( pDb->pSchema->file_format>SQLITE_MAX_FILE_FORMAT ){ sqlite3SetString(pzErrMsg, db, "unsupported file format"); rc = SQLITE_ERROR; goto initone_error_out; } /* Ticket #2804: When we open a database in the newer file format, ** clear the legacy_file_format pragma flag so that a VACUUM will ** not downgrade the database and thus invalidate any descending ** indices that the user might have created. */ if( iDb==0 && meta[BTREE_FILE_FORMAT-1]>=4 ){ db->flags &= ~SQLITE_LegacyFileFmt; } /* Read the schema information out of the schema tables */ assert( db->init.busy ); { char *zSql; zSql = sqlite3MPrintf(db, "SELECT name, rootpage, sql FROM \"%w\".%s ORDER BY rowid", db->aDb[iDb].zDbSName, zMasterName); #ifndef SQLITE_OMIT_AUTHORIZATION { sqlite3_xauth xAuth; xAuth = db->xAuth; db->xAuth = 0; #endif rc = sqlite3_exec(db, zSql, sqlite3InitCallback, &initData, 0); #ifndef SQLITE_OMIT_AUTHORIZATION db->xAuth = xAuth; } #endif if( rc==SQLITE_OK ) rc = initData.rc; sqlite3DbFree(db, zSql); #ifndef SQLITE_OMIT_ANALYZE if( rc==SQLITE_OK ){ sqlite3AnalysisLoad(db, iDb); } #endif } if( db->mallocFailed ){ rc = SQLITE_NOMEM_BKPT; sqlite3ResetAllSchemasOfConnection(db); } if( rc==SQLITE_OK || (db->flags&SQLITE_RecoveryMode)){ /* Black magic: If the SQLITE_RecoveryMode flag is set, then consider ** the schema loaded, even if errors occurred. In this situation the ** current sqlite3_prepare() operation will fail, but the following one ** will attempt to compile the supplied statement against whatever subset ** of the schema was loaded before the error occurred. The primary ** purpose of this is to allow access to the sqlite_master table ** even when its contents have been corrupted. */ DbSetProperty(db, iDb, DB_SchemaLoaded); rc = SQLITE_OK; } /* Jump here for an error that occurs after successfully allocating ** curMain and calling sqlite3BtreeEnter(). For an error that occurs ** before that point, jump to error_out. */ initone_error_out: if( openedTransaction ){ sqlite3BtreeCommit(pDb->pBt); } sqlite3BtreeLeave(pDb->pBt); error_out: if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){ sqlite3OomFault(db); } return rc; } /* ** Initialize all database files - the main database file, the file ** used to store temporary tables, and any additional database files ** created using ATTACH statements. Return a success code. If an ** error occurs, write an error message into *pzErrMsg. ** ** After a database is initialized, the DB_SchemaLoaded bit is set ** bit is set in the flags field of the Db structure. If the database ** file was of zero-length, then the DB_Empty flag is also set. */ SQLITE_PRIVATE int sqlite3Init(sqlite3 *db, char **pzErrMsg){ int i, rc; int commit_internal = !(db->flags&SQLITE_InternChanges); assert( sqlite3_mutex_held(db->mutex) ); assert( sqlite3BtreeHoldsMutex(db->aDb[0].pBt) ); assert( db->init.busy==0 ); rc = SQLITE_OK; db->init.busy = 1; ENC(db) = SCHEMA_ENC(db); for(i=0; rc==SQLITE_OK && inDb; i++){ if( DbHasProperty(db, i, DB_SchemaLoaded) || i==1 ) continue; rc = sqlite3InitOne(db, i, pzErrMsg); if( rc ){ sqlite3ResetOneSchema(db, i); } } /* Once all the other databases have been initialized, load the schema ** for the TEMP database. This is loaded last, as the TEMP database ** schema may contain references to objects in other databases. */ #ifndef SQLITE_OMIT_TEMPDB assert( db->nDb>1 ); if( rc==SQLITE_OK && !DbHasProperty(db, 1, DB_SchemaLoaded) ){ rc = sqlite3InitOne(db, 1, pzErrMsg); if( rc ){ sqlite3ResetOneSchema(db, 1); } } #endif db->init.busy = 0; if( rc==SQLITE_OK && commit_internal ){ sqlite3CommitInternalChanges(db); } return rc; } /* ** This routine is a no-op if the database schema is already initialized. ** Otherwise, the schema is loaded. An error code is returned. */ SQLITE_PRIVATE int sqlite3ReadSchema(Parse *pParse){ int rc = SQLITE_OK; sqlite3 *db = pParse->db; assert( sqlite3_mutex_held(db->mutex) ); if( !db->init.busy ){ rc = sqlite3Init(db, &pParse->zErrMsg); } if( rc!=SQLITE_OK ){ pParse->rc = rc; pParse->nErr++; } return rc; } /* ** Check schema cookies in all databases. If any cookie is out ** of date set pParse->rc to SQLITE_SCHEMA. If all schema cookies ** make no changes to pParse->rc. */ static void schemaIsValid(Parse *pParse){ sqlite3 *db = pParse->db; int iDb; int rc; int cookie; assert( pParse->checkSchema ); assert( sqlite3_mutex_held(db->mutex) ); for(iDb=0; iDbnDb; iDb++){ int openedTransaction = 0; /* True if a transaction is opened */ Btree *pBt = db->aDb[iDb].pBt; /* Btree database to read cookie from */ if( pBt==0 ) continue; /* If there is not already a read-only (or read-write) transaction opened ** on the b-tree database, open one now. If a transaction is opened, it ** will be closed immediately after reading the meta-value. */ if( !sqlite3BtreeIsInReadTrans(pBt) ){ rc = sqlite3BtreeBeginTrans(pBt, 0); if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){ sqlite3OomFault(db); } if( rc!=SQLITE_OK ) return; openedTransaction = 1; } /* Read the schema cookie from the database. If it does not match the ** value stored as part of the in-memory schema representation, ** set Parse.rc to SQLITE_SCHEMA. */ sqlite3BtreeGetMeta(pBt, BTREE_SCHEMA_VERSION, (u32 *)&cookie); assert( sqlite3SchemaMutexHeld(db, iDb, 0) ); if( cookie!=db->aDb[iDb].pSchema->schema_cookie ){ sqlite3ResetOneSchema(db, iDb); pParse->rc = SQLITE_SCHEMA; } /* Close the transaction, if one was opened. */ if( openedTransaction ){ sqlite3BtreeCommit(pBt); } } } /* ** Convert a schema pointer into the iDb index that indicates ** which database file in db->aDb[] the schema refers to. ** ** If the same database is attached more than once, the first ** attached database is returned. */ SQLITE_PRIVATE int sqlite3SchemaToIndex(sqlite3 *db, Schema *pSchema){ int i = -1000000; /* If pSchema is NULL, then return -1000000. This happens when code in ** expr.c is trying to resolve a reference to a transient table (i.e. one ** created by a sub-select). In this case the return value of this ** function should never be used. ** ** We return -1000000 instead of the more usual -1 simply because using ** -1000000 as the incorrect index into db->aDb[] is much ** more likely to cause a segfault than -1 (of course there are assert() ** statements too, but it never hurts to play the odds). */ assert( sqlite3_mutex_held(db->mutex) ); if( pSchema ){ for(i=0; ALWAYS(inDb); i++){ if( db->aDb[i].pSchema==pSchema ){ break; } } assert( i>=0 && inDb ); } return i; } /* ** Free all memory allocations in the pParse object */ SQLITE_PRIVATE void sqlite3ParserReset(Parse *pParse){ if( pParse ){ sqlite3 *db = pParse->db; sqlite3DbFree(db, pParse->aLabel); sqlite3ExprListDelete(db, pParse->pConstExpr); if( db ){ assert( db->lookaside.bDisable >= pParse->disableLookaside ); db->lookaside.bDisable -= pParse->disableLookaside; } pParse->disableLookaside = 0; } } /* ** Compile the UTF-8 encoded SQL statement zSql into a statement handle. */ static int sqlite3Prepare( sqlite3 *db, /* Database handle. */ const char *zSql, /* UTF-8 encoded SQL statement. */ int nBytes, /* Length of zSql in bytes. */ int saveSqlFlag, /* True to copy SQL text into the sqlite3_stmt */ Vdbe *pReprepare, /* VM being reprepared */ sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */ const char **pzTail /* OUT: End of parsed string */ ){ char *zErrMsg = 0; /* Error message */ int rc = SQLITE_OK; /* Result code */ int i; /* Loop counter */ Parse sParse; /* Parsing context */ memset(&sParse, 0, PARSE_HDR_SZ); memset(PARSE_TAIL(&sParse), 0, PARSE_TAIL_SZ); sParse.pReprepare = pReprepare; assert( ppStmt && *ppStmt==0 ); /* assert( !db->mallocFailed ); // not true with SQLITE_USE_ALLOCA */ assert( sqlite3_mutex_held(db->mutex) ); /* Check to verify that it is possible to get a read lock on all ** database schemas. The inability to get a read lock indicates that ** some other database connection is holding a write-lock, which in ** turn means that the other connection has made uncommitted changes ** to the schema. ** ** Were we to proceed and prepare the statement against the uncommitted ** schema changes and if those schema changes are subsequently rolled ** back and different changes are made in their place, then when this ** prepared statement goes to run the schema cookie would fail to detect ** the schema change. Disaster would follow. ** ** This thread is currently holding mutexes on all Btrees (because ** of the sqlite3BtreeEnterAll() in sqlite3LockAndPrepare()) so it ** is not possible for another thread to start a new schema change ** while this routine is running. Hence, we do not need to hold ** locks on the schema, we just need to make sure nobody else is ** holding them. ** ** Note that setting READ_UNCOMMITTED overrides most lock detection, ** but it does *not* override schema lock detection, so this all still ** works even if READ_UNCOMMITTED is set. */ for(i=0; inDb; i++) { Btree *pBt = db->aDb[i].pBt; if( pBt ){ assert( sqlite3BtreeHoldsMutex(pBt) ); rc = sqlite3BtreeSchemaLocked(pBt); if( rc ){ const char *zDb = db->aDb[i].zDbSName; sqlite3ErrorWithMsg(db, rc, "database schema is locked: %s", zDb); testcase( db->flags & SQLITE_ReadUncommitted ); goto end_prepare; } } } sqlite3VtabUnlockList(db); sParse.db = db; if( nBytes>=0 && (nBytes==0 || zSql[nBytes-1]!=0) ){ char *zSqlCopy; int mxLen = db->aLimit[SQLITE_LIMIT_SQL_LENGTH]; testcase( nBytes==mxLen ); testcase( nBytes==mxLen+1 ); if( nBytes>mxLen ){ sqlite3ErrorWithMsg(db, SQLITE_TOOBIG, "statement too long"); rc = sqlite3ApiExit(db, SQLITE_TOOBIG); goto end_prepare; } zSqlCopy = sqlite3DbStrNDup(db, zSql, nBytes); if( zSqlCopy ){ sqlite3RunParser(&sParse, zSqlCopy, &zErrMsg); sParse.zTail = &zSql[sParse.zTail-zSqlCopy]; sqlite3DbFree(db, zSqlCopy); }else{ sParse.zTail = &zSql[nBytes]; } }else{ sqlite3RunParser(&sParse, zSql, &zErrMsg); } assert( 0==sParse.nQueryLoop ); if( sParse.rc==SQLITE_DONE ) sParse.rc = SQLITE_OK; if( sParse.checkSchema ){ schemaIsValid(&sParse); } if( db->mallocFailed ){ sParse.rc = SQLITE_NOMEM_BKPT; } if( pzTail ){ *pzTail = sParse.zTail; } rc = sParse.rc; #ifndef SQLITE_OMIT_EXPLAIN if( rc==SQLITE_OK && sParse.pVdbe && sParse.explain ){ static const char * const azColName[] = { "addr", "opcode", "p1", "p2", "p3", "p4", "p5", "comment", "selectid", "order", "from", "detail" }; int iFirst, mx; if( sParse.explain==2 ){ sqlite3VdbeSetNumCols(sParse.pVdbe, 4); iFirst = 8; mx = 12; }else{ sqlite3VdbeSetNumCols(sParse.pVdbe, 8); iFirst = 0; mx = 8; } for(i=iFirst; iinit.busy==0 ){ Vdbe *pVdbe = sParse.pVdbe; sqlite3VdbeSetSql(pVdbe, zSql, (int)(sParse.zTail-zSql), saveSqlFlag); } if( sParse.pVdbe && (rc!=SQLITE_OK || db->mallocFailed) ){ sqlite3VdbeFinalize(sParse.pVdbe); assert(!(*ppStmt)); }else{ *ppStmt = (sqlite3_stmt*)sParse.pVdbe; } if( zErrMsg ){ sqlite3ErrorWithMsg(db, rc, "%s", zErrMsg); sqlite3DbFree(db, zErrMsg); }else{ sqlite3Error(db, rc); } /* Delete any TriggerPrg structures allocated while parsing this statement. */ while( sParse.pTriggerPrg ){ TriggerPrg *pT = sParse.pTriggerPrg; sParse.pTriggerPrg = pT->pNext; sqlite3DbFree(db, pT); } end_prepare: sqlite3ParserReset(&sParse); rc = sqlite3ApiExit(db, rc); assert( (rc&db->errMask)==rc ); return rc; } static int sqlite3LockAndPrepare( sqlite3 *db, /* Database handle. */ const char *zSql, /* UTF-8 encoded SQL statement. */ int nBytes, /* Length of zSql in bytes. */ int saveSqlFlag, /* True to copy SQL text into the sqlite3_stmt */ Vdbe *pOld, /* VM being reprepared */ sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */ const char **pzTail /* OUT: End of parsed string */ ){ int rc; #ifdef SQLITE_ENABLE_API_ARMOR if( ppStmt==0 ) return SQLITE_MISUSE_BKPT; #endif *ppStmt = 0; if( !sqlite3SafetyCheckOk(db)||zSql==0 ){ return SQLITE_MISUSE_BKPT; } sqlite3_mutex_enter(db->mutex); sqlite3BtreeEnterAll(db); rc = sqlite3Prepare(db, zSql, nBytes, saveSqlFlag, pOld, ppStmt, pzTail); if( rc==SQLITE_SCHEMA ){ sqlite3_finalize(*ppStmt); rc = sqlite3Prepare(db, zSql, nBytes, saveSqlFlag, pOld, ppStmt, pzTail); } sqlite3BtreeLeaveAll(db); sqlite3_mutex_leave(db->mutex); assert( rc==SQLITE_OK || *ppStmt==0 ); return rc; } /* ** Rerun the compilation of a statement after a schema change. ** ** If the statement is successfully recompiled, return SQLITE_OK. Otherwise, ** if the statement cannot be recompiled because another connection has ** locked the sqlite3_master table, return SQLITE_LOCKED. If any other error ** occurs, return SQLITE_SCHEMA. */ SQLITE_PRIVATE int sqlite3Reprepare(Vdbe *p){ int rc; sqlite3_stmt *pNew; const char *zSql; sqlite3 *db; assert( sqlite3_mutex_held(sqlite3VdbeDb(p)->mutex) ); zSql = sqlite3_sql((sqlite3_stmt *)p); assert( zSql!=0 ); /* Reprepare only called for prepare_v2() statements */ db = sqlite3VdbeDb(p); assert( sqlite3_mutex_held(db->mutex) ); rc = sqlite3LockAndPrepare(db, zSql, -1, 0, p, &pNew, 0); if( rc ){ if( rc==SQLITE_NOMEM ){ sqlite3OomFault(db); } assert( pNew==0 ); return rc; }else{ assert( pNew!=0 ); } sqlite3VdbeSwap((Vdbe*)pNew, p); sqlite3TransferBindings(pNew, (sqlite3_stmt*)p); sqlite3VdbeResetStepResult((Vdbe*)pNew); sqlite3VdbeFinalize((Vdbe*)pNew); return SQLITE_OK; } /* ** Two versions of the official API. Legacy and new use. In the legacy ** version, the original SQL text is not saved in the prepared statement ** and so if a schema change occurs, SQLITE_SCHEMA is returned by ** sqlite3_step(). In the new version, the original SQL text is retained ** and the statement is automatically recompiled if an schema change ** occurs. */ SQLITE_API int sqlite3_prepare( sqlite3 *db, /* Database handle. */ const char *zSql, /* UTF-8 encoded SQL statement. */ int nBytes, /* Length of zSql in bytes. */ sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */ const char **pzTail /* OUT: End of parsed string */ ){ int rc; rc = sqlite3LockAndPrepare(db,zSql,nBytes,0,0,ppStmt,pzTail); assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 ); /* VERIFY: F13021 */ return rc; } SQLITE_API int sqlite3_prepare_v2( sqlite3 *db, /* Database handle. */ const char *zSql, /* UTF-8 encoded SQL statement. */ int nBytes, /* Length of zSql in bytes. */ sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */ const char **pzTail /* OUT: End of parsed string */ ){ int rc; rc = sqlite3LockAndPrepare(db,zSql,nBytes,1,0,ppStmt,pzTail); assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 ); /* VERIFY: F13021 */ return rc; } #ifndef SQLITE_OMIT_UTF16 /* ** Compile the UTF-16 encoded SQL statement zSql into a statement handle. */ static int sqlite3Prepare16( sqlite3 *db, /* Database handle. */ const void *zSql, /* UTF-16 encoded SQL statement. */ int nBytes, /* Length of zSql in bytes. */ int saveSqlFlag, /* True to save SQL text into the sqlite3_stmt */ sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */ const void **pzTail /* OUT: End of parsed string */ ){ /* This function currently works by first transforming the UTF-16 ** encoded string to UTF-8, then invoking sqlite3_prepare(). The ** tricky bit is figuring out the pointer to return in *pzTail. */ char *zSql8; const char *zTail8 = 0; int rc = SQLITE_OK; #ifdef SQLITE_ENABLE_API_ARMOR if( ppStmt==0 ) return SQLITE_MISUSE_BKPT; #endif *ppStmt = 0; if( !sqlite3SafetyCheckOk(db)||zSql==0 ){ return SQLITE_MISUSE_BKPT; } if( nBytes>=0 ){ int sz; const char *z = (const char*)zSql; for(sz=0; szmutex); zSql8 = sqlite3Utf16to8(db, zSql, nBytes, SQLITE_UTF16NATIVE); if( zSql8 ){ rc = sqlite3LockAndPrepare(db, zSql8, -1, saveSqlFlag, 0, ppStmt, &zTail8); } if( zTail8 && pzTail ){ /* If sqlite3_prepare returns a tail pointer, we calculate the ** equivalent pointer into the UTF-16 string by counting the unicode ** characters between zSql8 and zTail8, and then returning a pointer ** the same number of characters into the UTF-16 string. */ int chars_parsed = sqlite3Utf8CharLen(zSql8, (int)(zTail8-zSql8)); *pzTail = (u8 *)zSql + sqlite3Utf16ByteLen(zSql, chars_parsed); } sqlite3DbFree(db, zSql8); rc = sqlite3ApiExit(db, rc); sqlite3_mutex_leave(db->mutex); return rc; } /* ** Two versions of the official API. Legacy and new use. In the legacy ** version, the original SQL text is not saved in the prepared statement ** and so if a schema change occurs, SQLITE_SCHEMA is returned by ** sqlite3_step(). In the new version, the original SQL text is retained ** and the statement is automatically recompiled if an schema change ** occurs. */ SQLITE_API int sqlite3_prepare16( sqlite3 *db, /* Database handle. */ const void *zSql, /* UTF-16 encoded SQL statement. */ int nBytes, /* Length of zSql in bytes. */ sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */ const void **pzTail /* OUT: End of parsed string */ ){ int rc; rc = sqlite3Prepare16(db,zSql,nBytes,0,ppStmt,pzTail); assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 ); /* VERIFY: F13021 */ return rc; } SQLITE_API int sqlite3_prepare16_v2( sqlite3 *db, /* Database handle. */ const void *zSql, /* UTF-16 encoded SQL statement. */ int nBytes, /* Length of zSql in bytes. */ sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */ const void **pzTail /* OUT: End of parsed string */ ){ int rc; rc = sqlite3Prepare16(db,zSql,nBytes,1,ppStmt,pzTail); assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 ); /* VERIFY: F13021 */ return rc; } #endif /* SQLITE_OMIT_UTF16 */ /************** End of prepare.c *********************************************/ /************** Begin file select.c ******************************************/ /* ** 2001 September 15 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ************************************************************************* ** This file contains C code routines that are called by the parser ** to handle SELECT statements in SQLite. */ /* #include "sqliteInt.h" */ /* ** Trace output macros */ #if SELECTTRACE_ENABLED /***/ int sqlite3SelectTrace = 0; # define SELECTTRACE(K,P,S,X) \ if(sqlite3SelectTrace&(K)) \ sqlite3DebugPrintf("%*s%s.%p: ",(P)->nSelectIndent*2-2,"",\ (S)->zSelName,(S)),\ sqlite3DebugPrintf X #else # define SELECTTRACE(K,P,S,X) #endif /* ** An instance of the following object is used to record information about ** how to process the DISTINCT keyword, to simplify passing that information ** into the selectInnerLoop() routine. */ typedef struct DistinctCtx DistinctCtx; struct DistinctCtx { u8 isTnct; /* True if the DISTINCT keyword is present */ u8 eTnctType; /* One of the WHERE_DISTINCT_* operators */ int tabTnct; /* Ephemeral table used for DISTINCT processing */ int addrTnct; /* Address of OP_OpenEphemeral opcode for tabTnct */ }; /* ** An instance of the following object is used to record information about ** the ORDER BY (or GROUP BY) clause of query is being coded. */ typedef struct SortCtx SortCtx; struct SortCtx { ExprList *pOrderBy; /* The ORDER BY (or GROUP BY clause) */ int nOBSat; /* Number of ORDER BY terms satisfied by indices */ int iECursor; /* Cursor number for the sorter */ int regReturn; /* Register holding block-output return address */ int labelBkOut; /* Start label for the block-output subroutine */ int addrSortIndex; /* Address of the OP_SorterOpen or OP_OpenEphemeral */ int labelDone; /* Jump here when done, ex: LIMIT reached */ u8 sortFlags; /* Zero or more SORTFLAG_* bits */ u8 bOrderedInnerLoop; /* ORDER BY correctly sorts the inner loop */ }; #define SORTFLAG_UseSorter 0x01 /* Use SorterOpen instead of OpenEphemeral */ /* ** Delete all the content of a Select structure. Deallocate the structure ** itself only if bFree is true. */ static void clearSelect(sqlite3 *db, Select *p, int bFree){ while( p ){ Select *pPrior = p->pPrior; sqlite3ExprListDelete(db, p->pEList); sqlite3SrcListDelete(db, p->pSrc); sqlite3ExprDelete(db, p->pWhere); sqlite3ExprListDelete(db, p->pGroupBy); sqlite3ExprDelete(db, p->pHaving); sqlite3ExprListDelete(db, p->pOrderBy); sqlite3ExprDelete(db, p->pLimit); sqlite3ExprDelete(db, p->pOffset); if( p->pWith ) sqlite3WithDelete(db, p->pWith); if( bFree ) sqlite3DbFree(db, p); p = pPrior; bFree = 1; } } /* ** Initialize a SelectDest structure. */ SQLITE_PRIVATE void sqlite3SelectDestInit(SelectDest *pDest, int eDest, int iParm){ pDest->eDest = (u8)eDest; pDest->iSDParm = iParm; pDest->zAffSdst = 0; pDest->iSdst = 0; pDest->nSdst = 0; } /* ** Allocate a new Select structure and return a pointer to that ** structure. */ SQLITE_PRIVATE Select *sqlite3SelectNew( Parse *pParse, /* Parsing context */ ExprList *pEList, /* which columns to include in the result */ SrcList *pSrc, /* the FROM clause -- which tables to scan */ Expr *pWhere, /* the WHERE clause */ ExprList *pGroupBy, /* the GROUP BY clause */ Expr *pHaving, /* the HAVING clause */ ExprList *pOrderBy, /* the ORDER BY clause */ u32 selFlags, /* Flag parameters, such as SF_Distinct */ Expr *pLimit, /* LIMIT value. NULL means not used */ Expr *pOffset /* OFFSET value. NULL means no offset */ ){ Select *pNew; Select standin; sqlite3 *db = pParse->db; pNew = sqlite3DbMallocRawNN(db, sizeof(*pNew) ); if( pNew==0 ){ assert( db->mallocFailed ); pNew = &standin; } if( pEList==0 ){ pEList = sqlite3ExprListAppend(pParse, 0, sqlite3Expr(db,TK_ASTERISK,0)); } pNew->pEList = pEList; pNew->op = TK_SELECT; pNew->selFlags = selFlags; pNew->iLimit = 0; pNew->iOffset = 0; #if SELECTTRACE_ENABLED pNew->zSelName[0] = 0; #endif pNew->addrOpenEphm[0] = -1; pNew->addrOpenEphm[1] = -1; pNew->nSelectRow = 0; if( pSrc==0 ) pSrc = sqlite3DbMallocZero(db, sizeof(*pSrc)); pNew->pSrc = pSrc; pNew->pWhere = pWhere; pNew->pGroupBy = pGroupBy; pNew->pHaving = pHaving; pNew->pOrderBy = pOrderBy; pNew->pPrior = 0; pNew->pNext = 0; pNew->pLimit = pLimit; pNew->pOffset = pOffset; pNew->pWith = 0; assert( pOffset==0 || pLimit!=0 || pParse->nErr>0 || db->mallocFailed!=0 ); if( db->mallocFailed ) { clearSelect(db, pNew, pNew!=&standin); pNew = 0; }else{ assert( pNew->pSrc!=0 || pParse->nErr>0 ); } assert( pNew!=&standin ); return pNew; } #if SELECTTRACE_ENABLED /* ** Set the name of a Select object */ SQLITE_PRIVATE void sqlite3SelectSetName(Select *p, const char *zName){ if( p && zName ){ sqlite3_snprintf(sizeof(p->zSelName), p->zSelName, "%s", zName); } } #endif /* ** Delete the given Select structure and all of its substructures. */ SQLITE_PRIVATE void sqlite3SelectDelete(sqlite3 *db, Select *p){ if( p ) clearSelect(db, p, 1); } /* ** Return a pointer to the right-most SELECT statement in a compound. */ static Select *findRightmost(Select *p){ while( p->pNext ) p = p->pNext; return p; } /* ** Given 1 to 3 identifiers preceding the JOIN keyword, determine the ** type of join. Return an integer constant that expresses that type ** in terms of the following bit values: ** ** JT_INNER ** JT_CROSS ** JT_OUTER ** JT_NATURAL ** JT_LEFT ** JT_RIGHT ** ** A full outer join is the combination of JT_LEFT and JT_RIGHT. ** ** If an illegal or unsupported join type is seen, then still return ** a join type, but put an error in the pParse structure. */ SQLITE_PRIVATE int sqlite3JoinType(Parse *pParse, Token *pA, Token *pB, Token *pC){ int jointype = 0; Token *apAll[3]; Token *p; /* 0123456789 123456789 123456789 123 */ static const char zKeyText[] = "naturaleftouterightfullinnercross"; static const struct { u8 i; /* Beginning of keyword text in zKeyText[] */ u8 nChar; /* Length of the keyword in characters */ u8 code; /* Join type mask */ } aKeyword[] = { /* natural */ { 0, 7, JT_NATURAL }, /* left */ { 6, 4, JT_LEFT|JT_OUTER }, /* outer */ { 10, 5, JT_OUTER }, /* right */ { 14, 5, JT_RIGHT|JT_OUTER }, /* full */ { 19, 4, JT_LEFT|JT_RIGHT|JT_OUTER }, /* inner */ { 23, 5, JT_INNER }, /* cross */ { 28, 5, JT_INNER|JT_CROSS }, }; int i, j; apAll[0] = pA; apAll[1] = pB; apAll[2] = pC; for(i=0; i<3 && apAll[i]; i++){ p = apAll[i]; for(j=0; jn==aKeyword[j].nChar && sqlite3StrNICmp((char*)p->z, &zKeyText[aKeyword[j].i], p->n)==0 ){ jointype |= aKeyword[j].code; break; } } testcase( j==0 || j==1 || j==2 || j==3 || j==4 || j==5 || j==6 ); if( j>=ArraySize(aKeyword) ){ jointype |= JT_ERROR; break; } } if( (jointype & (JT_INNER|JT_OUTER))==(JT_INNER|JT_OUTER) || (jointype & JT_ERROR)!=0 ){ const char *zSp = " "; assert( pB!=0 ); if( pC==0 ){ zSp++; } sqlite3ErrorMsg(pParse, "unknown or unsupported join type: " "%T %T%s%T", pA, pB, zSp, pC); jointype = JT_INNER; }else if( (jointype & JT_OUTER)!=0 && (jointype & (JT_LEFT|JT_RIGHT))!=JT_LEFT ){ sqlite3ErrorMsg(pParse, "RIGHT and FULL OUTER JOINs are not currently supported"); jointype = JT_INNER; } return jointype; } /* ** Return the index of a column in a table. Return -1 if the column ** is not contained in the table. */ static int columnIndex(Table *pTab, const char *zCol){ int i; for(i=0; inCol; i++){ if( sqlite3StrICmp(pTab->aCol[i].zName, zCol)==0 ) return i; } return -1; } /* ** Search the first N tables in pSrc, from left to right, looking for a ** table that has a column named zCol. ** ** When found, set *piTab and *piCol to the table index and column index ** of the matching column and return TRUE. ** ** If not found, return FALSE. */ static int tableAndColumnIndex( SrcList *pSrc, /* Array of tables to search */ int N, /* Number of tables in pSrc->a[] to search */ const char *zCol, /* Name of the column we are looking for */ int *piTab, /* Write index of pSrc->a[] here */ int *piCol /* Write index of pSrc->a[*piTab].pTab->aCol[] here */ ){ int i; /* For looping over tables in pSrc */ int iCol; /* Index of column matching zCol */ assert( (piTab==0)==(piCol==0) ); /* Both or neither are NULL */ for(i=0; ia[i].pTab, zCol); if( iCol>=0 ){ if( piTab ){ *piTab = i; *piCol = iCol; } return 1; } } return 0; } /* ** This function is used to add terms implied by JOIN syntax to the ** WHERE clause expression of a SELECT statement. The new term, which ** is ANDed with the existing WHERE clause, is of the form: ** ** (tab1.col1 = tab2.col2) ** ** where tab1 is the iSrc'th table in SrcList pSrc and tab2 is the ** (iSrc+1)'th. Column col1 is column iColLeft of tab1, and col2 is ** column iColRight of tab2. */ static void addWhereTerm( Parse *pParse, /* Parsing context */ SrcList *pSrc, /* List of tables in FROM clause */ int iLeft, /* Index of first table to join in pSrc */ int iColLeft, /* Index of column in first table */ int iRight, /* Index of second table in pSrc */ int iColRight, /* Index of column in second table */ int isOuterJoin, /* True if this is an OUTER join */ Expr **ppWhere /* IN/OUT: The WHERE clause to add to */ ){ sqlite3 *db = pParse->db; Expr *pE1; Expr *pE2; Expr *pEq; assert( iLeftnSrc>iRight ); assert( pSrc->a[iLeft].pTab ); assert( pSrc->a[iRight].pTab ); pE1 = sqlite3CreateColumnExpr(db, pSrc, iLeft, iColLeft); pE2 = sqlite3CreateColumnExpr(db, pSrc, iRight, iColRight); pEq = sqlite3PExpr(pParse, TK_EQ, pE1, pE2, 0); if( pEq && isOuterJoin ){ ExprSetProperty(pEq, EP_FromJoin); assert( !ExprHasProperty(pEq, EP_TokenOnly|EP_Reduced) ); ExprSetVVAProperty(pEq, EP_NoReduce); pEq->iRightJoinTable = (i16)pE2->iTable; } *ppWhere = sqlite3ExprAnd(db, *ppWhere, pEq); } /* ** Set the EP_FromJoin property on all terms of the given expression. ** And set the Expr.iRightJoinTable to iTable for every term in the ** expression. ** ** The EP_FromJoin property is used on terms of an expression to tell ** the LEFT OUTER JOIN processing logic that this term is part of the ** join restriction specified in the ON or USING clause and not a part ** of the more general WHERE clause. These terms are moved over to the ** WHERE clause during join processing but we need to remember that they ** originated in the ON or USING clause. ** ** The Expr.iRightJoinTable tells the WHERE clause processing that the ** expression depends on table iRightJoinTable even if that table is not ** explicitly mentioned in the expression. That information is needed ** for cases like this: ** ** SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.b AND t1.x=5 ** ** The where clause needs to defer the handling of the t1.x=5 ** term until after the t2 loop of the join. In that way, a ** NULL t2 row will be inserted whenever t1.x!=5. If we do not ** defer the handling of t1.x=5, it will be processed immediately ** after the t1 loop and rows with t1.x!=5 will never appear in ** the output, which is incorrect. */ static void setJoinExpr(Expr *p, int iTable){ while( p ){ ExprSetProperty(p, EP_FromJoin); assert( !ExprHasProperty(p, EP_TokenOnly|EP_Reduced) ); ExprSetVVAProperty(p, EP_NoReduce); p->iRightJoinTable = (i16)iTable; if( p->op==TK_FUNCTION && p->x.pList ){ int i; for(i=0; ix.pList->nExpr; i++){ setJoinExpr(p->x.pList->a[i].pExpr, iTable); } } setJoinExpr(p->pLeft, iTable); p = p->pRight; } } /* ** This routine processes the join information for a SELECT statement. ** ON and USING clauses are converted into extra terms of the WHERE clause. ** NATURAL joins also create extra WHERE clause terms. ** ** The terms of a FROM clause are contained in the Select.pSrc structure. ** The left most table is the first entry in Select.pSrc. The right-most ** table is the last entry. The join operator is held in the entry to ** the left. Thus entry 0 contains the join operator for the join between ** entries 0 and 1. Any ON or USING clauses associated with the join are ** also attached to the left entry. ** ** This routine returns the number of errors encountered. */ static int sqliteProcessJoin(Parse *pParse, Select *p){ SrcList *pSrc; /* All tables in the FROM clause */ int i, j; /* Loop counters */ struct SrcList_item *pLeft; /* Left table being joined */ struct SrcList_item *pRight; /* Right table being joined */ pSrc = p->pSrc; pLeft = &pSrc->a[0]; pRight = &pLeft[1]; for(i=0; inSrc-1; i++, pRight++, pLeft++){ Table *pLeftTab = pLeft->pTab; Table *pRightTab = pRight->pTab; int isOuter; if( NEVER(pLeftTab==0 || pRightTab==0) ) continue; isOuter = (pRight->fg.jointype & JT_OUTER)!=0; /* When the NATURAL keyword is present, add WHERE clause terms for ** every column that the two tables have in common. */ if( pRight->fg.jointype & JT_NATURAL ){ if( pRight->pOn || pRight->pUsing ){ sqlite3ErrorMsg(pParse, "a NATURAL join may not have " "an ON or USING clause", 0); return 1; } for(j=0; jnCol; j++){ char *zName; /* Name of column in the right table */ int iLeft; /* Matching left table */ int iLeftCol; /* Matching column in the left table */ zName = pRightTab->aCol[j].zName; if( tableAndColumnIndex(pSrc, i+1, zName, &iLeft, &iLeftCol) ){ addWhereTerm(pParse, pSrc, iLeft, iLeftCol, i+1, j, isOuter, &p->pWhere); } } } /* Disallow both ON and USING clauses in the same join */ if( pRight->pOn && pRight->pUsing ){ sqlite3ErrorMsg(pParse, "cannot have both ON and USING " "clauses in the same join"); return 1; } /* Add the ON clause to the end of the WHERE clause, connected by ** an AND operator. */ if( pRight->pOn ){ if( isOuter ) setJoinExpr(pRight->pOn, pRight->iCursor); p->pWhere = sqlite3ExprAnd(pParse->db, p->pWhere, pRight->pOn); pRight->pOn = 0; } /* Create extra terms on the WHERE clause for each column named ** in the USING clause. Example: If the two tables to be joined are ** A and B and the USING clause names X, Y, and Z, then add this ** to the WHERE clause: A.X=B.X AND A.Y=B.Y AND A.Z=B.Z ** Report an error if any column mentioned in the USING clause is ** not contained in both tables to be joined. */ if( pRight->pUsing ){ IdList *pList = pRight->pUsing; for(j=0; jnId; j++){ char *zName; /* Name of the term in the USING clause */ int iLeft; /* Table on the left with matching column name */ int iLeftCol; /* Column number of matching column on the left */ int iRightCol; /* Column number of matching column on the right */ zName = pList->a[j].zName; iRightCol = columnIndex(pRightTab, zName); if( iRightCol<0 || !tableAndColumnIndex(pSrc, i+1, zName, &iLeft, &iLeftCol) ){ sqlite3ErrorMsg(pParse, "cannot join using column %s - column " "not present in both tables", zName); return 1; } addWhereTerm(pParse, pSrc, iLeft, iLeftCol, i+1, iRightCol, isOuter, &p->pWhere); } } } return 0; } /* Forward reference */ static KeyInfo *keyInfoFromExprList( Parse *pParse, /* Parsing context */ ExprList *pList, /* Form the KeyInfo object from this ExprList */ int iStart, /* Begin with this column of pList */ int nExtra /* Add this many extra columns to the end */ ); /* ** Generate code that will push the record in registers regData ** through regData+nData-1 onto the sorter. */ static void pushOntoSorter( Parse *pParse, /* Parser context */ SortCtx *pSort, /* Information about the ORDER BY clause */ Select *pSelect, /* The whole SELECT statement */ int regData, /* First register holding data to be sorted */ int regOrigData, /* First register holding data before packing */ int nData, /* Number of elements in the data array */ int nPrefixReg /* No. of reg prior to regData available for use */ ){ Vdbe *v = pParse->pVdbe; /* Stmt under construction */ int bSeq = ((pSort->sortFlags & SORTFLAG_UseSorter)==0); int nExpr = pSort->pOrderBy->nExpr; /* No. of ORDER BY terms */ int nBase = nExpr + bSeq + nData; /* Fields in sorter record */ int regBase; /* Regs for sorter record */ int regRecord = ++pParse->nMem; /* Assembled sorter record */ int nOBSat = pSort->nOBSat; /* ORDER BY terms to skip */ int op; /* Opcode to add sorter record to sorter */ int iLimit; /* LIMIT counter */ assert( bSeq==0 || bSeq==1 ); assert( nData==1 || regData==regOrigData ); if( nPrefixReg ){ assert( nPrefixReg==nExpr+bSeq ); regBase = regData - nExpr - bSeq; }else{ regBase = pParse->nMem + 1; pParse->nMem += nBase; } assert( pSelect->iOffset==0 || pSelect->iLimit!=0 ); iLimit = pSelect->iOffset ? pSelect->iOffset+1 : pSelect->iLimit; pSort->labelDone = sqlite3VdbeMakeLabel(v); sqlite3ExprCodeExprList(pParse, pSort->pOrderBy, regBase, regOrigData, SQLITE_ECEL_DUP|SQLITE_ECEL_REF); if( bSeq ){ sqlite3VdbeAddOp2(v, OP_Sequence, pSort->iECursor, regBase+nExpr); } if( nPrefixReg==0 ){ sqlite3ExprCodeMove(pParse, regData, regBase+nExpr+bSeq, nData); } sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase+nOBSat, nBase-nOBSat, regRecord); if( nOBSat>0 ){ int regPrevKey; /* The first nOBSat columns of the previous row */ int addrFirst; /* Address of the OP_IfNot opcode */ int addrJmp; /* Address of the OP_Jump opcode */ VdbeOp *pOp; /* Opcode that opens the sorter */ int nKey; /* Number of sorting key columns, including OP_Sequence */ KeyInfo *pKI; /* Original KeyInfo on the sorter table */ regPrevKey = pParse->nMem+1; pParse->nMem += pSort->nOBSat; nKey = nExpr - pSort->nOBSat + bSeq; if( bSeq ){ addrFirst = sqlite3VdbeAddOp1(v, OP_IfNot, regBase+nExpr); }else{ addrFirst = sqlite3VdbeAddOp1(v, OP_SequenceTest, pSort->iECursor); } VdbeCoverage(v); sqlite3VdbeAddOp3(v, OP_Compare, regPrevKey, regBase, pSort->nOBSat); pOp = sqlite3VdbeGetOp(v, pSort->addrSortIndex); if( pParse->db->mallocFailed ) return; pOp->p2 = nKey + nData; pKI = pOp->p4.pKeyInfo; memset(pKI->aSortOrder, 0, pKI->nField); /* Makes OP_Jump below testable */ sqlite3VdbeChangeP4(v, -1, (char*)pKI, P4_KEYINFO); testcase( pKI->nXField>2 ); pOp->p4.pKeyInfo = keyInfoFromExprList(pParse, pSort->pOrderBy, nOBSat, pKI->nXField-1); addrJmp = sqlite3VdbeCurrentAddr(v); sqlite3VdbeAddOp3(v, OP_Jump, addrJmp+1, 0, addrJmp+1); VdbeCoverage(v); pSort->labelBkOut = sqlite3VdbeMakeLabel(v); pSort->regReturn = ++pParse->nMem; sqlite3VdbeAddOp2(v, OP_Gosub, pSort->regReturn, pSort->labelBkOut); sqlite3VdbeAddOp1(v, OP_ResetSorter, pSort->iECursor); if( iLimit ){ sqlite3VdbeAddOp2(v, OP_IfNot, iLimit, pSort->labelDone); VdbeCoverage(v); } sqlite3VdbeJumpHere(v, addrFirst); sqlite3ExprCodeMove(pParse, regBase, regPrevKey, pSort->nOBSat); sqlite3VdbeJumpHere(v, addrJmp); } if( pSort->sortFlags & SORTFLAG_UseSorter ){ op = OP_SorterInsert; }else{ op = OP_IdxInsert; } sqlite3VdbeAddOp2(v, op, pSort->iECursor, regRecord); if( iLimit ){ int addr; int r1 = 0; /* Fill the sorter until it contains LIMIT+OFFSET entries. (The iLimit ** register is initialized with value of LIMIT+OFFSET.) After the sorter ** fills up, delete the least entry in the sorter after each insert. ** Thus we never hold more than the LIMIT+OFFSET rows in memory at once */ addr = sqlite3VdbeAddOp3(v, OP_IfNotZero, iLimit, 0, 1); VdbeCoverage(v); sqlite3VdbeAddOp1(v, OP_Last, pSort->iECursor); if( pSort->bOrderedInnerLoop ){ r1 = ++pParse->nMem; sqlite3VdbeAddOp3(v, OP_Column, pSort->iECursor, nExpr, r1); VdbeComment((v, "seq")); } sqlite3VdbeAddOp1(v, OP_Delete, pSort->iECursor); if( pSort->bOrderedInnerLoop ){ /* If the inner loop is driven by an index such that values from ** the same iteration of the inner loop are in sorted order, then ** immediately jump to the next iteration of an inner loop if the ** entry from the current iteration does not fit into the top ** LIMIT+OFFSET entries of the sorter. */ int iBrk = sqlite3VdbeCurrentAddr(v) + 2; sqlite3VdbeAddOp3(v, OP_Eq, regBase+nExpr, iBrk, r1); sqlite3VdbeChangeP5(v, SQLITE_NULLEQ); VdbeCoverage(v); } sqlite3VdbeJumpHere(v, addr); } } /* ** Add code to implement the OFFSET */ static void codeOffset( Vdbe *v, /* Generate code into this VM */ int iOffset, /* Register holding the offset counter */ int iContinue /* Jump here to skip the current record */ ){ if( iOffset>0 ){ sqlite3VdbeAddOp3(v, OP_IfPos, iOffset, iContinue, 1); VdbeCoverage(v); VdbeComment((v, "OFFSET")); } } /* ** Add code that will check to make sure the N registers starting at iMem ** form a distinct entry. iTab is a sorting index that holds previously ** seen combinations of the N values. A new entry is made in iTab ** if the current N values are new. ** ** A jump to addrRepeat is made and the N+1 values are popped from the ** stack if the top N elements are not distinct. */ static void codeDistinct( Parse *pParse, /* Parsing and code generating context */ int iTab, /* A sorting index used to test for distinctness */ int addrRepeat, /* Jump to here if not distinct */ int N, /* Number of elements */ int iMem /* First element */ ){ Vdbe *v; int r1; v = pParse->pVdbe; r1 = sqlite3GetTempReg(pParse); sqlite3VdbeAddOp4Int(v, OP_Found, iTab, addrRepeat, iMem, N); VdbeCoverage(v); sqlite3VdbeAddOp3(v, OP_MakeRecord, iMem, N, r1); sqlite3VdbeAddOp2(v, OP_IdxInsert, iTab, r1); sqlite3ReleaseTempReg(pParse, r1); } /* ** This routine generates the code for the inside of the inner loop ** of a SELECT. ** ** If srcTab is negative, then the pEList expressions ** are evaluated in order to get the data for this row. If srcTab is ** zero or more, then data is pulled from srcTab and pEList is used only ** to get number columns and the datatype for each column. */ static void selectInnerLoop( Parse *pParse, /* The parser context */ Select *p, /* The complete select statement being coded */ ExprList *pEList, /* List of values being extracted */ int srcTab, /* Pull data from this table */ SortCtx *pSort, /* If not NULL, info on how to process ORDER BY */ DistinctCtx *pDistinct, /* If not NULL, info on how to process DISTINCT */ SelectDest *pDest, /* How to dispose of the results */ int iContinue, /* Jump here to continue with next row */ int iBreak /* Jump here to break out of the inner loop */ ){ Vdbe *v = pParse->pVdbe; int i; int hasDistinct; /* True if the DISTINCT keyword is present */ int regResult; /* Start of memory holding result set */ int eDest = pDest->eDest; /* How to dispose of results */ int iParm = pDest->iSDParm; /* First argument to disposal method */ int nResultCol; /* Number of result columns */ int nPrefixReg = 0; /* Number of extra registers before regResult */ assert( v ); assert( pEList!=0 ); hasDistinct = pDistinct ? pDistinct->eTnctType : WHERE_DISTINCT_NOOP; if( pSort && pSort->pOrderBy==0 ) pSort = 0; if( pSort==0 && !hasDistinct ){ assert( iContinue!=0 ); codeOffset(v, p->iOffset, iContinue); } /* Pull the requested columns. */ nResultCol = pEList->nExpr; if( pDest->iSdst==0 ){ if( pSort ){ nPrefixReg = pSort->pOrderBy->nExpr; if( !(pSort->sortFlags & SORTFLAG_UseSorter) ) nPrefixReg++; pParse->nMem += nPrefixReg; } pDest->iSdst = pParse->nMem+1; pParse->nMem += nResultCol; }else if( pDest->iSdst+nResultCol > pParse->nMem ){ /* This is an error condition that can result, for example, when a SELECT ** on the right-hand side of an INSERT contains more result columns than ** there are columns in the table on the left. The error will be caught ** and reported later. But we need to make sure enough memory is allocated ** to avoid other spurious errors in the meantime. */ pParse->nMem += nResultCol; } pDest->nSdst = nResultCol; regResult = pDest->iSdst; if( srcTab>=0 ){ for(i=0; ia[i].zName)); } }else if( eDest!=SRT_Exists ){ /* If the destination is an EXISTS(...) expression, the actual ** values returned by the SELECT are not required. */ u8 ecelFlags; if( eDest==SRT_Mem || eDest==SRT_Output || eDest==SRT_Coroutine ){ ecelFlags = SQLITE_ECEL_DUP; }else{ ecelFlags = 0; } sqlite3ExprCodeExprList(pParse, pEList, regResult, 0, ecelFlags); } /* If the DISTINCT keyword was present on the SELECT statement ** and this row has been seen before, then do not make this row ** part of the result. */ if( hasDistinct ){ switch( pDistinct->eTnctType ){ case WHERE_DISTINCT_ORDERED: { VdbeOp *pOp; /* No longer required OpenEphemeral instr. */ int iJump; /* Jump destination */ int regPrev; /* Previous row content */ /* Allocate space for the previous row */ regPrev = pParse->nMem+1; pParse->nMem += nResultCol; /* Change the OP_OpenEphemeral coded earlier to an OP_Null ** sets the MEM_Cleared bit on the first register of the ** previous value. This will cause the OP_Ne below to always ** fail on the first iteration of the loop even if the first ** row is all NULLs. */ sqlite3VdbeChangeToNoop(v, pDistinct->addrTnct); pOp = sqlite3VdbeGetOp(v, pDistinct->addrTnct); pOp->opcode = OP_Null; pOp->p1 = 1; pOp->p2 = regPrev; iJump = sqlite3VdbeCurrentAddr(v) + nResultCol; for(i=0; ia[i].pExpr); if( idb->mallocFailed ); sqlite3VdbeAddOp3(v, OP_Copy, regResult, regPrev, nResultCol-1); break; } case WHERE_DISTINCT_UNIQUE: { sqlite3VdbeChangeToNoop(v, pDistinct->addrTnct); break; } default: { assert( pDistinct->eTnctType==WHERE_DISTINCT_UNORDERED ); codeDistinct(pParse, pDistinct->tabTnct, iContinue, nResultCol, regResult); break; } } if( pSort==0 ){ codeOffset(v, p->iOffset, iContinue); } } switch( eDest ){ /* In this mode, write each query result to the key of the temporary ** table iParm. */ #ifndef SQLITE_OMIT_COMPOUND_SELECT case SRT_Union: { int r1; r1 = sqlite3GetTempReg(pParse); sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nResultCol, r1); sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, r1); sqlite3ReleaseTempReg(pParse, r1); break; } /* Construct a record from the query result, but instead of ** saving that record, use it as a key to delete elements from ** the temporary table iParm. */ case SRT_Except: { sqlite3VdbeAddOp3(v, OP_IdxDelete, iParm, regResult, nResultCol); break; } #endif /* SQLITE_OMIT_COMPOUND_SELECT */ /* Store the result as data using a unique key. */ case SRT_Fifo: case SRT_DistFifo: case SRT_Table: case SRT_EphemTab: { int r1 = sqlite3GetTempRange(pParse, nPrefixReg+1); testcase( eDest==SRT_Table ); testcase( eDest==SRT_EphemTab ); testcase( eDest==SRT_Fifo ); testcase( eDest==SRT_DistFifo ); sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nResultCol, r1+nPrefixReg); #ifndef SQLITE_OMIT_CTE if( eDest==SRT_DistFifo ){ /* If the destination is DistFifo, then cursor (iParm+1) is open ** on an ephemeral index. If the current row is already present ** in the index, do not write it to the output. If not, add the ** current row to the index and proceed with writing it to the ** output table as well. */ int addr = sqlite3VdbeCurrentAddr(v) + 4; sqlite3VdbeAddOp4Int(v, OP_Found, iParm+1, addr, r1, 0); VdbeCoverage(v); sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm+1, r1); assert( pSort==0 ); } #endif if( pSort ){ pushOntoSorter(pParse, pSort, p, r1+nPrefixReg,regResult,1,nPrefixReg); }else{ int r2 = sqlite3GetTempReg(pParse); sqlite3VdbeAddOp2(v, OP_NewRowid, iParm, r2); sqlite3VdbeAddOp3(v, OP_Insert, iParm, r1, r2); sqlite3VdbeChangeP5(v, OPFLAG_APPEND); sqlite3ReleaseTempReg(pParse, r2); } sqlite3ReleaseTempRange(pParse, r1, nPrefixReg+1); break; } #ifndef SQLITE_OMIT_SUBQUERY /* If we are creating a set for an "expr IN (SELECT ...)" construct, ** then there should be a single item on the stack. Write this ** item into the set table with bogus data. */ case SRT_Set: { if( pSort ){ /* At first glance you would think we could optimize out the ** ORDER BY in this case since the order of entries in the set ** does not matter. But there might be a LIMIT clause, in which ** case the order does matter */ pushOntoSorter( pParse, pSort, p, regResult, regResult, nResultCol, nPrefixReg); }else{ int r1 = sqlite3GetTempReg(pParse); assert( sqlite3Strlen30(pDest->zAffSdst)==nResultCol ); sqlite3VdbeAddOp4(v, OP_MakeRecord, regResult, nResultCol, r1, pDest->zAffSdst, nResultCol); sqlite3ExprCacheAffinityChange(pParse, regResult, nResultCol); sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, r1); sqlite3ReleaseTempReg(pParse, r1); } break; } /* If any row exist in the result set, record that fact and abort. */ case SRT_Exists: { sqlite3VdbeAddOp2(v, OP_Integer, 1, iParm); /* The LIMIT clause will terminate the loop for us */ break; } /* If this is a scalar select that is part of an expression, then ** store the results in the appropriate memory cell or array of ** memory cells and break out of the scan loop. */ case SRT_Mem: { assert( nResultCol==pDest->nSdst ); if( pSort ){ pushOntoSorter( pParse, pSort, p, regResult, regResult, nResultCol, nPrefixReg); }else{ assert( regResult==iParm ); /* The LIMIT clause will jump out of the loop for us */ } break; } #endif /* #ifndef SQLITE_OMIT_SUBQUERY */ case SRT_Coroutine: /* Send data to a co-routine */ case SRT_Output: { /* Return the results */ testcase( eDest==SRT_Coroutine ); testcase( eDest==SRT_Output ); if( pSort ){ pushOntoSorter(pParse, pSort, p, regResult, regResult, nResultCol, nPrefixReg); }else if( eDest==SRT_Coroutine ){ sqlite3VdbeAddOp1(v, OP_Yield, pDest->iSDParm); }else{ sqlite3VdbeAddOp2(v, OP_ResultRow, regResult, nResultCol); sqlite3ExprCacheAffinityChange(pParse, regResult, nResultCol); } break; } #ifndef SQLITE_OMIT_CTE /* Write the results into a priority queue that is order according to ** pDest->pOrderBy (in pSO). pDest->iSDParm (in iParm) is the cursor for an ** index with pSO->nExpr+2 columns. Build a key using pSO for the first ** pSO->nExpr columns, then make sure all keys are unique by adding a ** final OP_Sequence column. The last column is the record as a blob. */ case SRT_DistQueue: case SRT_Queue: { int nKey; int r1, r2, r3; int addrTest = 0; ExprList *pSO; pSO = pDest->pOrderBy; assert( pSO ); nKey = pSO->nExpr; r1 = sqlite3GetTempReg(pParse); r2 = sqlite3GetTempRange(pParse, nKey+2); r3 = r2+nKey+1; if( eDest==SRT_DistQueue ){ /* If the destination is DistQueue, then cursor (iParm+1) is open ** on a second ephemeral index that holds all values every previously ** added to the queue. */ addrTest = sqlite3VdbeAddOp4Int(v, OP_Found, iParm+1, 0, regResult, nResultCol); VdbeCoverage(v); } sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nResultCol, r3); if( eDest==SRT_DistQueue ){ sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm+1, r3); sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT); } for(i=0; ia[i].u.x.iOrderByCol - 1, r2+i); } sqlite3VdbeAddOp2(v, OP_Sequence, iParm, r2+nKey); sqlite3VdbeAddOp3(v, OP_MakeRecord, r2, nKey+2, r1); sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, r1); if( addrTest ) sqlite3VdbeJumpHere(v, addrTest); sqlite3ReleaseTempReg(pParse, r1); sqlite3ReleaseTempRange(pParse, r2, nKey+2); break; } #endif /* SQLITE_OMIT_CTE */ #if !defined(SQLITE_OMIT_TRIGGER) /* Discard the results. This is used for SELECT statements inside ** the body of a TRIGGER. The purpose of such selects is to call ** user-defined functions that have side effects. We do not care ** about the actual results of the select. */ default: { assert( eDest==SRT_Discard ); break; } #endif } /* Jump to the end of the loop if the LIMIT is reached. Except, if ** there is a sorter, in which case the sorter has already limited ** the output for us. */ if( pSort==0 && p->iLimit ){ sqlite3VdbeAddOp2(v, OP_DecrJumpZero, p->iLimit, iBreak); VdbeCoverage(v); } } /* ** Allocate a KeyInfo object sufficient for an index of N key columns and ** X extra columns. */ SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoAlloc(sqlite3 *db, int N, int X){ int nExtra = (N+X)*(sizeof(CollSeq*)+1); KeyInfo *p = sqlite3DbMallocRawNN(db, sizeof(KeyInfo) + nExtra); if( p ){ p->aSortOrder = (u8*)&p->aColl[N+X]; p->nField = (u16)N; p->nXField = (u16)X; p->enc = ENC(db); p->db = db; p->nRef = 1; memset(&p[1], 0, nExtra); }else{ sqlite3OomFault(db); } return p; } /* ** Deallocate a KeyInfo object */ SQLITE_PRIVATE void sqlite3KeyInfoUnref(KeyInfo *p){ if( p ){ assert( p->nRef>0 ); p->nRef--; if( p->nRef==0 ) sqlite3DbFree(p->db, p); } } /* ** Make a new pointer to a KeyInfo object */ SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoRef(KeyInfo *p){ if( p ){ assert( p->nRef>0 ); p->nRef++; } return p; } #ifdef SQLITE_DEBUG /* ** Return TRUE if a KeyInfo object can be change. The KeyInfo object ** can only be changed if this is just a single reference to the object. ** ** This routine is used only inside of assert() statements. */ SQLITE_PRIVATE int sqlite3KeyInfoIsWriteable(KeyInfo *p){ return p->nRef==1; } #endif /* SQLITE_DEBUG */ /* ** Given an expression list, generate a KeyInfo structure that records ** the collating sequence for each expression in that expression list. ** ** If the ExprList is an ORDER BY or GROUP BY clause then the resulting ** KeyInfo structure is appropriate for initializing a virtual index to ** implement that clause. If the ExprList is the result set of a SELECT ** then the KeyInfo structure is appropriate for initializing a virtual ** index to implement a DISTINCT test. ** ** Space to hold the KeyInfo structure is obtained from malloc. The calling ** function is responsible for seeing that this structure is eventually ** freed. */ static KeyInfo *keyInfoFromExprList( Parse *pParse, /* Parsing context */ ExprList *pList, /* Form the KeyInfo object from this ExprList */ int iStart, /* Begin with this column of pList */ int nExtra /* Add this many extra columns to the end */ ){ int nExpr; KeyInfo *pInfo; struct ExprList_item *pItem; sqlite3 *db = pParse->db; int i; nExpr = pList->nExpr; pInfo = sqlite3KeyInfoAlloc(db, nExpr-iStart, nExtra+1); if( pInfo ){ assert( sqlite3KeyInfoIsWriteable(pInfo) ); for(i=iStart, pItem=pList->a+iStart; ipExpr); if( !pColl ) pColl = db->pDfltColl; pInfo->aColl[i-iStart] = pColl; pInfo->aSortOrder[i-iStart] = pItem->sortOrder; } } return pInfo; } /* ** Name of the connection operator, used for error messages. */ static const char *selectOpName(int id){ char *z; switch( id ){ case TK_ALL: z = "UNION ALL"; break; case TK_INTERSECT: z = "INTERSECT"; break; case TK_EXCEPT: z = "EXCEPT"; break; default: z = "UNION"; break; } return z; } #ifndef SQLITE_OMIT_EXPLAIN /* ** Unless an "EXPLAIN QUERY PLAN" command is being processed, this function ** is a no-op. Otherwise, it adds a single row of output to the EQP result, ** where the caption is of the form: ** ** "USE TEMP B-TREE FOR xxx" ** ** where xxx is one of "DISTINCT", "ORDER BY" or "GROUP BY". Exactly which ** is determined by the zUsage argument. */ static void explainTempTable(Parse *pParse, const char *zUsage){ if( pParse->explain==2 ){ Vdbe *v = pParse->pVdbe; char *zMsg = sqlite3MPrintf(pParse->db, "USE TEMP B-TREE FOR %s", zUsage); sqlite3VdbeAddOp4(v, OP_Explain, pParse->iSelectId, 0, 0, zMsg, P4_DYNAMIC); } } /* ** Assign expression b to lvalue a. A second, no-op, version of this macro ** is provided when SQLITE_OMIT_EXPLAIN is defined. This allows the code ** in sqlite3Select() to assign values to structure member variables that ** only exist if SQLITE_OMIT_EXPLAIN is not defined without polluting the ** code with #ifndef directives. */ # define explainSetInteger(a, b) a = b #else /* No-op versions of the explainXXX() functions and macros. */ # define explainTempTable(y,z) # define explainSetInteger(y,z) #endif #if !defined(SQLITE_OMIT_EXPLAIN) && !defined(SQLITE_OMIT_COMPOUND_SELECT) /* ** Unless an "EXPLAIN QUERY PLAN" command is being processed, this function ** is a no-op. Otherwise, it adds a single row of output to the EQP result, ** where the caption is of one of the two forms: ** ** "COMPOSITE SUBQUERIES iSub1 and iSub2 (op)" ** "COMPOSITE SUBQUERIES iSub1 and iSub2 USING TEMP B-TREE (op)" ** ** where iSub1 and iSub2 are the integers passed as the corresponding ** function parameters, and op is the text representation of the parameter ** of the same name. The parameter "op" must be one of TK_UNION, TK_EXCEPT, ** TK_INTERSECT or TK_ALL. The first form is used if argument bUseTmp is ** false, or the second form if it is true. */ static void explainComposite( Parse *pParse, /* Parse context */ int op, /* One of TK_UNION, TK_EXCEPT etc. */ int iSub1, /* Subquery id 1 */ int iSub2, /* Subquery id 2 */ int bUseTmp /* True if a temp table was used */ ){ assert( op==TK_UNION || op==TK_EXCEPT || op==TK_INTERSECT || op==TK_ALL ); if( pParse->explain==2 ){ Vdbe *v = pParse->pVdbe; char *zMsg = sqlite3MPrintf( pParse->db, "COMPOUND SUBQUERIES %d AND %d %s(%s)", iSub1, iSub2, bUseTmp?"USING TEMP B-TREE ":"", selectOpName(op) ); sqlite3VdbeAddOp4(v, OP_Explain, pParse->iSelectId, 0, 0, zMsg, P4_DYNAMIC); } } #else /* No-op versions of the explainXXX() functions and macros. */ # define explainComposite(v,w,x,y,z) #endif /* ** If the inner loop was generated using a non-null pOrderBy argument, ** then the results were placed in a sorter. After the loop is terminated ** we need to run the sorter and output the results. The following ** routine generates the code needed to do that. */ static void generateSortTail( Parse *pParse, /* Parsing context */ Select *p, /* The SELECT statement */ SortCtx *pSort, /* Information on the ORDER BY clause */ int nColumn, /* Number of columns of data */ SelectDest *pDest /* Write the sorted results here */ ){ Vdbe *v = pParse->pVdbe; /* The prepared statement */ int addrBreak = pSort->labelDone; /* Jump here to exit loop */ int addrContinue = sqlite3VdbeMakeLabel(v); /* Jump here for next cycle */ int addr; int addrOnce = 0; int iTab; ExprList *pOrderBy = pSort->pOrderBy; int eDest = pDest->eDest; int iParm = pDest->iSDParm; int regRow; int regRowid; int nKey; int iSortTab; /* Sorter cursor to read from */ int nSortData; /* Trailing values to read from sorter */ int i; int bSeq; /* True if sorter record includes seq. no. */ #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS struct ExprList_item *aOutEx = p->pEList->a; #endif assert( addrBreak<0 ); if( pSort->labelBkOut ){ sqlite3VdbeAddOp2(v, OP_Gosub, pSort->regReturn, pSort->labelBkOut); sqlite3VdbeGoto(v, addrBreak); sqlite3VdbeResolveLabel(v, pSort->labelBkOut); } iTab = pSort->iECursor; if( eDest==SRT_Output || eDest==SRT_Coroutine || eDest==SRT_Mem ){ regRowid = 0; regRow = pDest->iSdst; nSortData = nColumn; }else{ regRowid = sqlite3GetTempReg(pParse); regRow = sqlite3GetTempRange(pParse, nColumn); nSortData = nColumn; } nKey = pOrderBy->nExpr - pSort->nOBSat; if( pSort->sortFlags & SORTFLAG_UseSorter ){ int regSortOut = ++pParse->nMem; iSortTab = pParse->nTab++; if( pSort->labelBkOut ){ addrOnce = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v); } sqlite3VdbeAddOp3(v, OP_OpenPseudo, iSortTab, regSortOut, nKey+1+nSortData); if( addrOnce ) sqlite3VdbeJumpHere(v, addrOnce); addr = 1 + sqlite3VdbeAddOp2(v, OP_SorterSort, iTab, addrBreak); VdbeCoverage(v); codeOffset(v, p->iOffset, addrContinue); sqlite3VdbeAddOp3(v, OP_SorterData, iTab, regSortOut, iSortTab); bSeq = 0; }else{ addr = 1 + sqlite3VdbeAddOp2(v, OP_Sort, iTab, addrBreak); VdbeCoverage(v); codeOffset(v, p->iOffset, addrContinue); iSortTab = iTab; bSeq = 1; } for(i=0; izAffSdst) ); sqlite3VdbeAddOp4(v, OP_MakeRecord, regRow, nColumn, regRowid, pDest->zAffSdst, nColumn); sqlite3ExprCacheAffinityChange(pParse, regRow, nColumn); sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, regRowid); break; } case SRT_Mem: { /* The LIMIT clause will terminate the loop for us */ break; } #endif default: { assert( eDest==SRT_Output || eDest==SRT_Coroutine ); testcase( eDest==SRT_Output ); testcase( eDest==SRT_Coroutine ); if( eDest==SRT_Output ){ sqlite3VdbeAddOp2(v, OP_ResultRow, pDest->iSdst, nColumn); sqlite3ExprCacheAffinityChange(pParse, pDest->iSdst, nColumn); }else{ sqlite3VdbeAddOp1(v, OP_Yield, pDest->iSDParm); } break; } } if( regRowid ){ if( eDest==SRT_Set ){ sqlite3ReleaseTempRange(pParse, regRow, nColumn); }else{ sqlite3ReleaseTempReg(pParse, regRow); } sqlite3ReleaseTempReg(pParse, regRowid); } /* The bottom of the loop */ sqlite3VdbeResolveLabel(v, addrContinue); if( pSort->sortFlags & SORTFLAG_UseSorter ){ sqlite3VdbeAddOp2(v, OP_SorterNext, iTab, addr); VdbeCoverage(v); }else{ sqlite3VdbeAddOp2(v, OP_Next, iTab, addr); VdbeCoverage(v); } if( pSort->regReturn ) sqlite3VdbeAddOp1(v, OP_Return, pSort->regReturn); sqlite3VdbeResolveLabel(v, addrBreak); } /* ** Return a pointer to a string containing the 'declaration type' of the ** expression pExpr. The string may be treated as static by the caller. ** ** Also try to estimate the size of the returned value and return that ** result in *pEstWidth. ** ** The declaration type is the exact datatype definition extracted from the ** original CREATE TABLE statement if the expression is a column. The ** declaration type for a ROWID field is INTEGER. Exactly when an expression ** is considered a column can be complex in the presence of subqueries. The ** result-set expression in all of the following SELECT statements is ** considered a column by this function. ** ** SELECT col FROM tbl; ** SELECT (SELECT col FROM tbl; ** SELECT (SELECT col FROM tbl); ** SELECT abc FROM (SELECT col AS abc FROM tbl); ** ** The declaration type for any expression other than a column is NULL. ** ** This routine has either 3 or 6 parameters depending on whether or not ** the SQLITE_ENABLE_COLUMN_METADATA compile-time option is used. */ #ifdef SQLITE_ENABLE_COLUMN_METADATA # define columnType(A,B,C,D,E,F) columnTypeImpl(A,B,C,D,E,F) #else /* if !defined(SQLITE_ENABLE_COLUMN_METADATA) */ # define columnType(A,B,C,D,E,F) columnTypeImpl(A,B,F) #endif static const char *columnTypeImpl( NameContext *pNC, Expr *pExpr, #ifdef SQLITE_ENABLE_COLUMN_METADATA const char **pzOrigDb, const char **pzOrigTab, const char **pzOrigCol, #endif u8 *pEstWidth ){ char const *zType = 0; int j; u8 estWidth = 1; #ifdef SQLITE_ENABLE_COLUMN_METADATA char const *zOrigDb = 0; char const *zOrigTab = 0; char const *zOrigCol = 0; #endif assert( pExpr!=0 ); assert( pNC->pSrcList!=0 ); switch( pExpr->op ){ case TK_AGG_COLUMN: case TK_COLUMN: { /* The expression is a column. Locate the table the column is being ** extracted from in NameContext.pSrcList. This table may be real ** database table or a subquery. */ Table *pTab = 0; /* Table structure column is extracted from */ Select *pS = 0; /* Select the column is extracted from */ int iCol = pExpr->iColumn; /* Index of column in pTab */ testcase( pExpr->op==TK_AGG_COLUMN ); testcase( pExpr->op==TK_COLUMN ); while( pNC && !pTab ){ SrcList *pTabList = pNC->pSrcList; for(j=0;jnSrc && pTabList->a[j].iCursor!=pExpr->iTable;j++); if( jnSrc ){ pTab = pTabList->a[j].pTab; pS = pTabList->a[j].pSelect; }else{ pNC = pNC->pNext; } } if( pTab==0 ){ /* At one time, code such as "SELECT new.x" within a trigger would ** cause this condition to run. Since then, we have restructured how ** trigger code is generated and so this condition is no longer ** possible. However, it can still be true for statements like ** the following: ** ** CREATE TABLE t1(col INTEGER); ** SELECT (SELECT t1.col) FROM FROM t1; ** ** when columnType() is called on the expression "t1.col" in the ** sub-select. In this case, set the column type to NULL, even ** though it should really be "INTEGER". ** ** This is not a problem, as the column type of "t1.col" is never ** used. When columnType() is called on the expression ** "(SELECT t1.col)", the correct type is returned (see the TK_SELECT ** branch below. */ break; } assert( pTab && pExpr->pTab==pTab ); if( pS ){ /* The "table" is actually a sub-select or a view in the FROM clause ** of the SELECT statement. Return the declaration type and origin ** data for the result-set column of the sub-select. */ if( iCol>=0 && ALWAYS(iColpEList->nExpr) ){ /* If iCol is less than zero, then the expression requests the ** rowid of the sub-select or view. This expression is legal (see ** test case misc2.2.2) - it always evaluates to NULL. ** ** The ALWAYS() is because iCol>=pS->pEList->nExpr will have been ** caught already by name resolution. */ NameContext sNC; Expr *p = pS->pEList->a[iCol].pExpr; sNC.pSrcList = pS->pSrc; sNC.pNext = pNC; sNC.pParse = pNC->pParse; zType = columnType(&sNC, p,&zOrigDb,&zOrigTab,&zOrigCol, &estWidth); } }else if( pTab->pSchema ){ /* A real table */ assert( !pS ); if( iCol<0 ) iCol = pTab->iPKey; assert( iCol==-1 || (iCol>=0 && iColnCol) ); #ifdef SQLITE_ENABLE_COLUMN_METADATA if( iCol<0 ){ zType = "INTEGER"; zOrigCol = "rowid"; }else{ zOrigCol = pTab->aCol[iCol].zName; zType = sqlite3ColumnType(&pTab->aCol[iCol],0); estWidth = pTab->aCol[iCol].szEst; } zOrigTab = pTab->zName; if( pNC->pParse ){ int iDb = sqlite3SchemaToIndex(pNC->pParse->db, pTab->pSchema); zOrigDb = pNC->pParse->db->aDb[iDb].zDbSName; } #else if( iCol<0 ){ zType = "INTEGER"; }else{ zType = sqlite3ColumnType(&pTab->aCol[iCol],0); estWidth = pTab->aCol[iCol].szEst; } #endif } break; } #ifndef SQLITE_OMIT_SUBQUERY case TK_SELECT: { /* The expression is a sub-select. Return the declaration type and ** origin info for the single column in the result set of the SELECT ** statement. */ NameContext sNC; Select *pS = pExpr->x.pSelect; Expr *p = pS->pEList->a[0].pExpr; assert( ExprHasProperty(pExpr, EP_xIsSelect) ); sNC.pSrcList = pS->pSrc; sNC.pNext = pNC; sNC.pParse = pNC->pParse; zType = columnType(&sNC, p, &zOrigDb, &zOrigTab, &zOrigCol, &estWidth); break; } #endif } #ifdef SQLITE_ENABLE_COLUMN_METADATA if( pzOrigDb ){ assert( pzOrigTab && pzOrigCol ); *pzOrigDb = zOrigDb; *pzOrigTab = zOrigTab; *pzOrigCol = zOrigCol; } #endif if( pEstWidth ) *pEstWidth = estWidth; return zType; } /* ** Generate code that will tell the VDBE the declaration types of columns ** in the result set. */ static void generateColumnTypes( Parse *pParse, /* Parser context */ SrcList *pTabList, /* List of tables */ ExprList *pEList /* Expressions defining the result set */ ){ #ifndef SQLITE_OMIT_DECLTYPE Vdbe *v = pParse->pVdbe; int i; NameContext sNC; sNC.pSrcList = pTabList; sNC.pParse = pParse; for(i=0; inExpr; i++){ Expr *p = pEList->a[i].pExpr; const char *zType; #ifdef SQLITE_ENABLE_COLUMN_METADATA const char *zOrigDb = 0; const char *zOrigTab = 0; const char *zOrigCol = 0; zType = columnType(&sNC, p, &zOrigDb, &zOrigTab, &zOrigCol, 0); /* The vdbe must make its own copy of the column-type and other ** column specific strings, in case the schema is reset before this ** virtual machine is deleted. */ sqlite3VdbeSetColName(v, i, COLNAME_DATABASE, zOrigDb, SQLITE_TRANSIENT); sqlite3VdbeSetColName(v, i, COLNAME_TABLE, zOrigTab, SQLITE_TRANSIENT); sqlite3VdbeSetColName(v, i, COLNAME_COLUMN, zOrigCol, SQLITE_TRANSIENT); #else zType = columnType(&sNC, p, 0, 0, 0, 0); #endif sqlite3VdbeSetColName(v, i, COLNAME_DECLTYPE, zType, SQLITE_TRANSIENT); } #endif /* !defined(SQLITE_OMIT_DECLTYPE) */ } /* ** Generate code that will tell the VDBE the names of columns ** in the result set. This information is used to provide the ** azCol[] values in the callback. */ static void generateColumnNames( Parse *pParse, /* Parser context */ SrcList *pTabList, /* List of tables */ ExprList *pEList /* Expressions defining the result set */ ){ Vdbe *v = pParse->pVdbe; int i, j; sqlite3 *db = pParse->db; int fullNames, shortNames; #ifndef SQLITE_OMIT_EXPLAIN /* If this is an EXPLAIN, skip this step */ if( pParse->explain ){ return; } #endif if( pParse->colNamesSet || db->mallocFailed ) return; assert( v!=0 ); assert( pTabList!=0 ); pParse->colNamesSet = 1; fullNames = (db->flags & SQLITE_FullColNames)!=0; shortNames = (db->flags & SQLITE_ShortColNames)!=0; sqlite3VdbeSetNumCols(v, pEList->nExpr); for(i=0; inExpr; i++){ Expr *p; p = pEList->a[i].pExpr; if( NEVER(p==0) ) continue; if( pEList->a[i].zName ){ char *zName = pEList->a[i].zName; sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, SQLITE_TRANSIENT); }else if( p->op==TK_COLUMN || p->op==TK_AGG_COLUMN ){ Table *pTab; char *zCol; int iCol = p->iColumn; for(j=0; ALWAYS(jnSrc); j++){ if( pTabList->a[j].iCursor==p->iTable ) break; } assert( jnSrc ); pTab = pTabList->a[j].pTab; if( iCol<0 ) iCol = pTab->iPKey; assert( iCol==-1 || (iCol>=0 && iColnCol) ); if( iCol<0 ){ zCol = "rowid"; }else{ zCol = pTab->aCol[iCol].zName; } if( !shortNames && !fullNames ){ sqlite3VdbeSetColName(v, i, COLNAME_NAME, sqlite3DbStrDup(db, pEList->a[i].zSpan), SQLITE_DYNAMIC); }else if( fullNames ){ char *zName = 0; zName = sqlite3MPrintf(db, "%s.%s", pTab->zName, zCol); sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, SQLITE_DYNAMIC); }else{ sqlite3VdbeSetColName(v, i, COLNAME_NAME, zCol, SQLITE_TRANSIENT); } }else{ const char *z = pEList->a[i].zSpan; z = z==0 ? sqlite3MPrintf(db, "column%d", i+1) : sqlite3DbStrDup(db, z); sqlite3VdbeSetColName(v, i, COLNAME_NAME, z, SQLITE_DYNAMIC); } } generateColumnTypes(pParse, pTabList, pEList); } /* ** Given an expression list (which is really the list of expressions ** that form the result set of a SELECT statement) compute appropriate ** column names for a table that would hold the expression list. ** ** All column names will be unique. ** ** Only the column names are computed. Column.zType, Column.zColl, ** and other fields of Column are zeroed. ** ** Return SQLITE_OK on success. If a memory allocation error occurs, ** store NULL in *paCol and 0 in *pnCol and return SQLITE_NOMEM. */ SQLITE_PRIVATE int sqlite3ColumnsFromExprList( Parse *pParse, /* Parsing context */ ExprList *pEList, /* Expr list from which to derive column names */ i16 *pnCol, /* Write the number of columns here */ Column **paCol /* Write the new column list here */ ){ sqlite3 *db = pParse->db; /* Database connection */ int i, j; /* Loop counters */ u32 cnt; /* Index added to make the name unique */ Column *aCol, *pCol; /* For looping over result columns */ int nCol; /* Number of columns in the result set */ Expr *p; /* Expression for a single result column */ char *zName; /* Column name */ int nName; /* Size of name in zName[] */ Hash ht; /* Hash table of column names */ sqlite3HashInit(&ht); if( pEList ){ nCol = pEList->nExpr; aCol = sqlite3DbMallocZero(db, sizeof(aCol[0])*nCol); testcase( aCol==0 ); }else{ nCol = 0; aCol = 0; } assert( nCol==(i16)nCol ); *pnCol = nCol; *paCol = aCol; for(i=0, pCol=aCol; imallocFailed; i++, pCol++){ /* Get an appropriate name for the column */ p = sqlite3ExprSkipCollate(pEList->a[i].pExpr); if( (zName = pEList->a[i].zName)!=0 ){ /* If the column contains an "AS " phrase, use as the name */ }else{ Expr *pColExpr = p; /* The expression that is the result column name */ Table *pTab; /* Table associated with this expression */ while( pColExpr->op==TK_DOT ){ pColExpr = pColExpr->pRight; assert( pColExpr!=0 ); } if( pColExpr->op==TK_COLUMN && ALWAYS(pColExpr->pTab!=0) ){ /* For columns use the column name name */ int iCol = pColExpr->iColumn; pTab = pColExpr->pTab; if( iCol<0 ) iCol = pTab->iPKey; zName = iCol>=0 ? pTab->aCol[iCol].zName : "rowid"; }else if( pColExpr->op==TK_ID ){ assert( !ExprHasProperty(pColExpr, EP_IntValue) ); zName = pColExpr->u.zToken; }else{ /* Use the original text of the column expression as its name */ zName = pEList->a[i].zSpan; } } zName = sqlite3MPrintf(db, "%s", zName); /* Make sure the column name is unique. If the name is not unique, ** append an integer to the name so that it becomes unique. */ cnt = 0; while( zName && sqlite3HashFind(&ht, zName)!=0 ){ nName = sqlite3Strlen30(zName); if( nName>0 ){ for(j=nName-1; j>0 && sqlite3Isdigit(zName[j]); j--){} if( zName[j]==':' ) nName = j; } zName = sqlite3MPrintf(db, "%.*z:%u", nName, zName, ++cnt); if( cnt>3 ) sqlite3_randomness(sizeof(cnt), &cnt); } pCol->zName = zName; sqlite3ColumnPropertiesFromName(0, pCol); if( zName && sqlite3HashInsert(&ht, zName, pCol)==pCol ){ sqlite3OomFault(db); } } sqlite3HashClear(&ht); if( db->mallocFailed ){ for(j=0; jdb; NameContext sNC; Column *pCol; CollSeq *pColl; int i; Expr *p; struct ExprList_item *a; u64 szAll = 0; assert( pSelect!=0 ); assert( (pSelect->selFlags & SF_Resolved)!=0 ); assert( pTab->nCol==pSelect->pEList->nExpr || db->mallocFailed ); if( db->mallocFailed ) return; memset(&sNC, 0, sizeof(sNC)); sNC.pSrcList = pSelect->pSrc; a = pSelect->pEList->a; for(i=0, pCol=pTab->aCol; inCol; i++, pCol++){ const char *zType; int n, m; p = a[i].pExpr; zType = columnType(&sNC, p, 0, 0, 0, &pCol->szEst); szAll += pCol->szEst; pCol->affinity = sqlite3ExprAffinity(p); if( zType && (m = sqlite3Strlen30(zType))>0 ){ n = sqlite3Strlen30(pCol->zName); pCol->zName = sqlite3DbReallocOrFree(db, pCol->zName, n+m+2); if( pCol->zName ){ memcpy(&pCol->zName[n+1], zType, m+1); pCol->colFlags |= COLFLAG_HASTYPE; } } if( pCol->affinity==0 ) pCol->affinity = SQLITE_AFF_BLOB; pColl = sqlite3ExprCollSeq(pParse, p); if( pColl && pCol->zColl==0 ){ pCol->zColl = sqlite3DbStrDup(db, pColl->zName); } } pTab->szTabRow = sqlite3LogEst(szAll*4); } /* ** Given a SELECT statement, generate a Table structure that describes ** the result set of that SELECT. */ SQLITE_PRIVATE Table *sqlite3ResultSetOfSelect(Parse *pParse, Select *pSelect){ Table *pTab; sqlite3 *db = pParse->db; int savedFlags; savedFlags = db->flags; db->flags &= ~SQLITE_FullColNames; db->flags |= SQLITE_ShortColNames; sqlite3SelectPrep(pParse, pSelect, 0); if( pParse->nErr ) return 0; while( pSelect->pPrior ) pSelect = pSelect->pPrior; db->flags = savedFlags; pTab = sqlite3DbMallocZero(db, sizeof(Table) ); if( pTab==0 ){ return 0; } /* The sqlite3ResultSetOfSelect() is only used n contexts where lookaside ** is disabled */ assert( db->lookaside.bDisable ); pTab->nRef = 1; pTab->zName = 0; pTab->nRowLogEst = 200; assert( 200==sqlite3LogEst(1048576) ); sqlite3ColumnsFromExprList(pParse, pSelect->pEList, &pTab->nCol, &pTab->aCol); sqlite3SelectAddColumnTypeAndCollation(pParse, pTab, pSelect); pTab->iPKey = -1; if( db->mallocFailed ){ sqlite3DeleteTable(db, pTab); return 0; } return pTab; } /* ** Get a VDBE for the given parser context. Create a new one if necessary. ** If an error occurs, return NULL and leave a message in pParse. */ static SQLITE_NOINLINE Vdbe *allocVdbe(Parse *pParse){ Vdbe *v = pParse->pVdbe = sqlite3VdbeCreate(pParse); if( v ) sqlite3VdbeAddOp2(v, OP_Init, 0, 1); if( pParse->pToplevel==0 && OptimizationEnabled(pParse->db,SQLITE_FactorOutConst) ){ pParse->okConstFactor = 1; } return v; } SQLITE_PRIVATE Vdbe *sqlite3GetVdbe(Parse *pParse){ Vdbe *v = pParse->pVdbe; return v ? v : allocVdbe(pParse); } /* ** Compute the iLimit and iOffset fields of the SELECT based on the ** pLimit and pOffset expressions. pLimit and pOffset hold the expressions ** that appear in the original SQL statement after the LIMIT and OFFSET ** keywords. Or NULL if those keywords are omitted. iLimit and iOffset ** are the integer memory register numbers for counters used to compute ** the limit and offset. If there is no limit and/or offset, then ** iLimit and iOffset are negative. ** ** This routine changes the values of iLimit and iOffset only if ** a limit or offset is defined by pLimit and pOffset. iLimit and ** iOffset should have been preset to appropriate default values (zero) ** prior to calling this routine. ** ** The iOffset register (if it exists) is initialized to the value ** of the OFFSET. The iLimit register is initialized to LIMIT. Register ** iOffset+1 is initialized to LIMIT+OFFSET. ** ** Only if pLimit!=0 or pOffset!=0 do the limit registers get ** redefined. The UNION ALL operator uses this property to force ** the reuse of the same limit and offset registers across multiple ** SELECT statements. */ static void computeLimitRegisters(Parse *pParse, Select *p, int iBreak){ Vdbe *v = 0; int iLimit = 0; int iOffset; int n; if( p->iLimit ) return; /* ** "LIMIT -1" always shows all rows. There is some ** controversy about what the correct behavior should be. ** The current implementation interprets "LIMIT 0" to mean ** no rows. */ sqlite3ExprCacheClear(pParse); assert( p->pOffset==0 || p->pLimit!=0 ); if( p->pLimit ){ p->iLimit = iLimit = ++pParse->nMem; v = sqlite3GetVdbe(pParse); assert( v!=0 ); if( sqlite3ExprIsInteger(p->pLimit, &n) ){ sqlite3VdbeAddOp2(v, OP_Integer, n, iLimit); VdbeComment((v, "LIMIT counter")); if( n==0 ){ sqlite3VdbeGoto(v, iBreak); }else if( n>=0 && p->nSelectRow>sqlite3LogEst((u64)n) ){ p->nSelectRow = sqlite3LogEst((u64)n); p->selFlags |= SF_FixedLimit; } }else{ sqlite3ExprCode(pParse, p->pLimit, iLimit); sqlite3VdbeAddOp1(v, OP_MustBeInt, iLimit); VdbeCoverage(v); VdbeComment((v, "LIMIT counter")); sqlite3VdbeAddOp2(v, OP_IfNot, iLimit, iBreak); VdbeCoverage(v); } if( p->pOffset ){ p->iOffset = iOffset = ++pParse->nMem; pParse->nMem++; /* Allocate an extra register for limit+offset */ sqlite3ExprCode(pParse, p->pOffset, iOffset); sqlite3VdbeAddOp1(v, OP_MustBeInt, iOffset); VdbeCoverage(v); VdbeComment((v, "OFFSET counter")); sqlite3VdbeAddOp3(v, OP_OffsetLimit, iLimit, iOffset+1, iOffset); VdbeComment((v, "LIMIT+OFFSET")); } } } #ifndef SQLITE_OMIT_COMPOUND_SELECT /* ** Return the appropriate collating sequence for the iCol-th column of ** the result set for the compound-select statement "p". Return NULL if ** the column has no default collating sequence. ** ** The collating sequence for the compound select is taken from the ** left-most term of the select that has a collating sequence. */ static CollSeq *multiSelectCollSeq(Parse *pParse, Select *p, int iCol){ CollSeq *pRet; if( p->pPrior ){ pRet = multiSelectCollSeq(pParse, p->pPrior, iCol); }else{ pRet = 0; } assert( iCol>=0 ); /* iCol must be less than p->pEList->nExpr. Otherwise an error would ** have been thrown during name resolution and we would not have gotten ** this far */ if( pRet==0 && ALWAYS(iColpEList->nExpr) ){ pRet = sqlite3ExprCollSeq(pParse, p->pEList->a[iCol].pExpr); } return pRet; } /* ** The select statement passed as the second parameter is a compound SELECT ** with an ORDER BY clause. This function allocates and returns a KeyInfo ** structure suitable for implementing the ORDER BY. ** ** Space to hold the KeyInfo structure is obtained from malloc. The calling ** function is responsible for ensuring that this structure is eventually ** freed. */ static KeyInfo *multiSelectOrderByKeyInfo(Parse *pParse, Select *p, int nExtra){ ExprList *pOrderBy = p->pOrderBy; int nOrderBy = p->pOrderBy->nExpr; sqlite3 *db = pParse->db; KeyInfo *pRet = sqlite3KeyInfoAlloc(db, nOrderBy+nExtra, 1); if( pRet ){ int i; for(i=0; ia[i]; Expr *pTerm = pItem->pExpr; CollSeq *pColl; if( pTerm->flags & EP_Collate ){ pColl = sqlite3ExprCollSeq(pParse, pTerm); }else{ pColl = multiSelectCollSeq(pParse, p, pItem->u.x.iOrderByCol-1); if( pColl==0 ) pColl = db->pDfltColl; pOrderBy->a[i].pExpr = sqlite3ExprAddCollateString(pParse, pTerm, pColl->zName); } assert( sqlite3KeyInfoIsWriteable(pRet) ); pRet->aColl[i] = pColl; pRet->aSortOrder[i] = pOrderBy->a[i].sortOrder; } } return pRet; } #ifndef SQLITE_OMIT_CTE /* ** This routine generates VDBE code to compute the content of a WITH RECURSIVE ** query of the form: ** ** AS ( UNION [ALL] ) ** \___________/ \_______________/ ** p->pPrior p ** ** ** There is exactly one reference to the recursive-table in the FROM clause ** of recursive-query, marked with the SrcList->a[].fg.isRecursive flag. ** ** The setup-query runs once to generate an initial set of rows that go ** into a Queue table. Rows are extracted from the Queue table one by ** one. Each row extracted from Queue is output to pDest. Then the single ** extracted row (now in the iCurrent table) becomes the content of the ** recursive-table for a recursive-query run. The output of the recursive-query ** is added back into the Queue table. Then another row is extracted from Queue ** and the iteration continues until the Queue table is empty. ** ** If the compound query operator is UNION then no duplicate rows are ever ** inserted into the Queue table. The iDistinct table keeps a copy of all rows ** that have ever been inserted into Queue and causes duplicates to be ** discarded. If the operator is UNION ALL, then duplicates are allowed. ** ** If the query has an ORDER BY, then entries in the Queue table are kept in ** ORDER BY order and the first entry is extracted for each cycle. Without ** an ORDER BY, the Queue table is just a FIFO. ** ** If a LIMIT clause is provided, then the iteration stops after LIMIT rows ** have been output to pDest. A LIMIT of zero means to output no rows and a ** negative LIMIT means to output all rows. If there is also an OFFSET clause ** with a positive value, then the first OFFSET outputs are discarded rather ** than being sent to pDest. The LIMIT count does not begin until after OFFSET ** rows have been skipped. */ static void generateWithRecursiveQuery( Parse *pParse, /* Parsing context */ Select *p, /* The recursive SELECT to be coded */ SelectDest *pDest /* What to do with query results */ ){ SrcList *pSrc = p->pSrc; /* The FROM clause of the recursive query */ int nCol = p->pEList->nExpr; /* Number of columns in the recursive table */ Vdbe *v = pParse->pVdbe; /* The prepared statement under construction */ Select *pSetup = p->pPrior; /* The setup query */ int addrTop; /* Top of the loop */ int addrCont, addrBreak; /* CONTINUE and BREAK addresses */ int iCurrent = 0; /* The Current table */ int regCurrent; /* Register holding Current table */ int iQueue; /* The Queue table */ int iDistinct = 0; /* To ensure unique results if UNION */ int eDest = SRT_Fifo; /* How to write to Queue */ SelectDest destQueue; /* SelectDest targetting the Queue table */ int i; /* Loop counter */ int rc; /* Result code */ ExprList *pOrderBy; /* The ORDER BY clause */ Expr *pLimit, *pOffset; /* Saved LIMIT and OFFSET */ int regLimit, regOffset; /* Registers used by LIMIT and OFFSET */ /* Obtain authorization to do a recursive query */ if( sqlite3AuthCheck(pParse, SQLITE_RECURSIVE, 0, 0, 0) ) return; /* Process the LIMIT and OFFSET clauses, if they exist */ addrBreak = sqlite3VdbeMakeLabel(v); computeLimitRegisters(pParse, p, addrBreak); pLimit = p->pLimit; pOffset = p->pOffset; regLimit = p->iLimit; regOffset = p->iOffset; p->pLimit = p->pOffset = 0; p->iLimit = p->iOffset = 0; pOrderBy = p->pOrderBy; /* Locate the cursor number of the Current table */ for(i=0; ALWAYS(inSrc); i++){ if( pSrc->a[i].fg.isRecursive ){ iCurrent = pSrc->a[i].iCursor; break; } } /* Allocate cursors numbers for Queue and Distinct. The cursor number for ** the Distinct table must be exactly one greater than Queue in order ** for the SRT_DistFifo and SRT_DistQueue destinations to work. */ iQueue = pParse->nTab++; if( p->op==TK_UNION ){ eDest = pOrderBy ? SRT_DistQueue : SRT_DistFifo; iDistinct = pParse->nTab++; }else{ eDest = pOrderBy ? SRT_Queue : SRT_Fifo; } sqlite3SelectDestInit(&destQueue, eDest, iQueue); /* Allocate cursors for Current, Queue, and Distinct. */ regCurrent = ++pParse->nMem; sqlite3VdbeAddOp3(v, OP_OpenPseudo, iCurrent, regCurrent, nCol); if( pOrderBy ){ KeyInfo *pKeyInfo = multiSelectOrderByKeyInfo(pParse, p, 1); sqlite3VdbeAddOp4(v, OP_OpenEphemeral, iQueue, pOrderBy->nExpr+2, 0, (char*)pKeyInfo, P4_KEYINFO); destQueue.pOrderBy = pOrderBy; }else{ sqlite3VdbeAddOp2(v, OP_OpenEphemeral, iQueue, nCol); } VdbeComment((v, "Queue table")); if( iDistinct ){ p->addrOpenEphm[0] = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, iDistinct, 0); p->selFlags |= SF_UsesEphemeral; } /* Detach the ORDER BY clause from the compound SELECT */ p->pOrderBy = 0; /* Store the results of the setup-query in Queue. */ pSetup->pNext = 0; rc = sqlite3Select(pParse, pSetup, &destQueue); pSetup->pNext = p; if( rc ) goto end_of_recursive_query; /* Find the next row in the Queue and output that row */ addrTop = sqlite3VdbeAddOp2(v, OP_Rewind, iQueue, addrBreak); VdbeCoverage(v); /* Transfer the next row in Queue over to Current */ sqlite3VdbeAddOp1(v, OP_NullRow, iCurrent); /* To reset column cache */ if( pOrderBy ){ sqlite3VdbeAddOp3(v, OP_Column, iQueue, pOrderBy->nExpr+1, regCurrent); }else{ sqlite3VdbeAddOp2(v, OP_RowData, iQueue, regCurrent); } sqlite3VdbeAddOp1(v, OP_Delete, iQueue); /* Output the single row in Current */ addrCont = sqlite3VdbeMakeLabel(v); codeOffset(v, regOffset, addrCont); selectInnerLoop(pParse, p, p->pEList, iCurrent, 0, 0, pDest, addrCont, addrBreak); if( regLimit ){ sqlite3VdbeAddOp2(v, OP_DecrJumpZero, regLimit, addrBreak); VdbeCoverage(v); } sqlite3VdbeResolveLabel(v, addrCont); /* Execute the recursive SELECT taking the single row in Current as ** the value for the recursive-table. Store the results in the Queue. */ if( p->selFlags & SF_Aggregate ){ sqlite3ErrorMsg(pParse, "recursive aggregate queries not supported"); }else{ p->pPrior = 0; sqlite3Select(pParse, p, &destQueue); assert( p->pPrior==0 ); p->pPrior = pSetup; } /* Keep running the loop until the Queue is empty */ sqlite3VdbeGoto(v, addrTop); sqlite3VdbeResolveLabel(v, addrBreak); end_of_recursive_query: sqlite3ExprListDelete(pParse->db, p->pOrderBy); p->pOrderBy = pOrderBy; p->pLimit = pLimit; p->pOffset = pOffset; return; } #endif /* SQLITE_OMIT_CTE */ /* Forward references */ static int multiSelectOrderBy( Parse *pParse, /* Parsing context */ Select *p, /* The right-most of SELECTs to be coded */ SelectDest *pDest /* What to do with query results */ ); /* ** Handle the special case of a compound-select that originates from a ** VALUES clause. By handling this as a special case, we avoid deep ** recursion, and thus do not need to enforce the SQLITE_LIMIT_COMPOUND_SELECT ** on a VALUES clause. ** ** Because the Select object originates from a VALUES clause: ** (1) It has no LIMIT or OFFSET ** (2) All terms are UNION ALL ** (3) There is no ORDER BY clause */ static int multiSelectValues( Parse *pParse, /* Parsing context */ Select *p, /* The right-most of SELECTs to be coded */ SelectDest *pDest /* What to do with query results */ ){ Select *pPrior; int nRow = 1; int rc = 0; assert( p->selFlags & SF_MultiValue ); do{ assert( p->selFlags & SF_Values ); assert( p->op==TK_ALL || (p->op==TK_SELECT && p->pPrior==0) ); assert( p->pLimit==0 ); assert( p->pOffset==0 ); assert( p->pNext==0 || p->pEList->nExpr==p->pNext->pEList->nExpr ); if( p->pPrior==0 ) break; assert( p->pPrior->pNext==p ); p = p->pPrior; nRow++; }while(1); while( p ){ pPrior = p->pPrior; p->pPrior = 0; rc = sqlite3Select(pParse, p, pDest); p->pPrior = pPrior; if( rc ) break; p->nSelectRow = nRow; p = p->pNext; } return rc; } /* ** This routine is called to process a compound query form from ** two or more separate queries using UNION, UNION ALL, EXCEPT, or ** INTERSECT ** ** "p" points to the right-most of the two queries. the query on the ** left is p->pPrior. The left query could also be a compound query ** in which case this routine will be called recursively. ** ** The results of the total query are to be written into a destination ** of type eDest with parameter iParm. ** ** Example 1: Consider a three-way compound SQL statement. ** ** SELECT a FROM t1 UNION SELECT b FROM t2 UNION SELECT c FROM t3 ** ** This statement is parsed up as follows: ** ** SELECT c FROM t3 ** | ** `-----> SELECT b FROM t2 ** | ** `------> SELECT a FROM t1 ** ** The arrows in the diagram above represent the Select.pPrior pointer. ** So if this routine is called with p equal to the t3 query, then ** pPrior will be the t2 query. p->op will be TK_UNION in this case. ** ** Notice that because of the way SQLite parses compound SELECTs, the ** individual selects always group from left to right. */ static int multiSelect( Parse *pParse, /* Parsing context */ Select *p, /* The right-most of SELECTs to be coded */ SelectDest *pDest /* What to do with query results */ ){ int rc = SQLITE_OK; /* Success code from a subroutine */ Select *pPrior; /* Another SELECT immediately to our left */ Vdbe *v; /* Generate code to this VDBE */ SelectDest dest; /* Alternative data destination */ Select *pDelete = 0; /* Chain of simple selects to delete */ sqlite3 *db; /* Database connection */ #ifndef SQLITE_OMIT_EXPLAIN int iSub1 = 0; /* EQP id of left-hand query */ int iSub2 = 0; /* EQP id of right-hand query */ #endif /* Make sure there is no ORDER BY or LIMIT clause on prior SELECTs. Only ** the last (right-most) SELECT in the series may have an ORDER BY or LIMIT. */ assert( p && p->pPrior ); /* Calling function guarantees this much */ assert( (p->selFlags & SF_Recursive)==0 || p->op==TK_ALL || p->op==TK_UNION ); db = pParse->db; pPrior = p->pPrior; dest = *pDest; if( pPrior->pOrderBy ){ sqlite3ErrorMsg(pParse,"ORDER BY clause should come after %s not before", selectOpName(p->op)); rc = 1; goto multi_select_end; } if( pPrior->pLimit ){ sqlite3ErrorMsg(pParse,"LIMIT clause should come after %s not before", selectOpName(p->op)); rc = 1; goto multi_select_end; } v = sqlite3GetVdbe(pParse); assert( v!=0 ); /* The VDBE already created by calling function */ /* Create the destination temporary table if necessary */ if( dest.eDest==SRT_EphemTab ){ assert( p->pEList ); sqlite3VdbeAddOp2(v, OP_OpenEphemeral, dest.iSDParm, p->pEList->nExpr); dest.eDest = SRT_Table; } /* Special handling for a compound-select that originates as a VALUES clause. */ if( p->selFlags & SF_MultiValue ){ rc = multiSelectValues(pParse, p, &dest); goto multi_select_end; } /* Make sure all SELECTs in the statement have the same number of elements ** in their result sets. */ assert( p->pEList && pPrior->pEList ); assert( p->pEList->nExpr==pPrior->pEList->nExpr ); #ifndef SQLITE_OMIT_CTE if( p->selFlags & SF_Recursive ){ generateWithRecursiveQuery(pParse, p, &dest); }else #endif /* Compound SELECTs that have an ORDER BY clause are handled separately. */ if( p->pOrderBy ){ return multiSelectOrderBy(pParse, p, pDest); }else /* Generate code for the left and right SELECT statements. */ switch( p->op ){ case TK_ALL: { int addr = 0; int nLimit; assert( !pPrior->pLimit ); pPrior->iLimit = p->iLimit; pPrior->iOffset = p->iOffset; pPrior->pLimit = p->pLimit; pPrior->pOffset = p->pOffset; explainSetInteger(iSub1, pParse->iNextSelectId); rc = sqlite3Select(pParse, pPrior, &dest); p->pLimit = 0; p->pOffset = 0; if( rc ){ goto multi_select_end; } p->pPrior = 0; p->iLimit = pPrior->iLimit; p->iOffset = pPrior->iOffset; if( p->iLimit ){ addr = sqlite3VdbeAddOp1(v, OP_IfNot, p->iLimit); VdbeCoverage(v); VdbeComment((v, "Jump ahead if LIMIT reached")); if( p->iOffset ){ sqlite3VdbeAddOp3(v, OP_OffsetLimit, p->iLimit, p->iOffset+1, p->iOffset); } } explainSetInteger(iSub2, pParse->iNextSelectId); rc = sqlite3Select(pParse, p, &dest); testcase( rc!=SQLITE_OK ); pDelete = p->pPrior; p->pPrior = pPrior; p->nSelectRow = sqlite3LogEstAdd(p->nSelectRow, pPrior->nSelectRow); if( pPrior->pLimit && sqlite3ExprIsInteger(pPrior->pLimit, &nLimit) && nLimit>0 && p->nSelectRow > sqlite3LogEst((u64)nLimit) ){ p->nSelectRow = sqlite3LogEst((u64)nLimit); } if( addr ){ sqlite3VdbeJumpHere(v, addr); } break; } case TK_EXCEPT: case TK_UNION: { int unionTab; /* Cursor number of the temporary table holding result */ u8 op = 0; /* One of the SRT_ operations to apply to self */ int priorOp; /* The SRT_ operation to apply to prior selects */ Expr *pLimit, *pOffset; /* Saved values of p->nLimit and p->nOffset */ int addr; SelectDest uniondest; testcase( p->op==TK_EXCEPT ); testcase( p->op==TK_UNION ); priorOp = SRT_Union; if( dest.eDest==priorOp ){ /* We can reuse a temporary table generated by a SELECT to our ** right. */ assert( p->pLimit==0 ); /* Not allowed on leftward elements */ assert( p->pOffset==0 ); /* Not allowed on leftward elements */ unionTab = dest.iSDParm; }else{ /* We will need to create our own temporary table to hold the ** intermediate results. */ unionTab = pParse->nTab++; assert( p->pOrderBy==0 ); addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, unionTab, 0); assert( p->addrOpenEphm[0] == -1 ); p->addrOpenEphm[0] = addr; findRightmost(p)->selFlags |= SF_UsesEphemeral; assert( p->pEList ); } /* Code the SELECT statements to our left */ assert( !pPrior->pOrderBy ); sqlite3SelectDestInit(&uniondest, priorOp, unionTab); explainSetInteger(iSub1, pParse->iNextSelectId); rc = sqlite3Select(pParse, pPrior, &uniondest); if( rc ){ goto multi_select_end; } /* Code the current SELECT statement */ if( p->op==TK_EXCEPT ){ op = SRT_Except; }else{ assert( p->op==TK_UNION ); op = SRT_Union; } p->pPrior = 0; pLimit = p->pLimit; p->pLimit = 0; pOffset = p->pOffset; p->pOffset = 0; uniondest.eDest = op; explainSetInteger(iSub2, pParse->iNextSelectId); rc = sqlite3Select(pParse, p, &uniondest); testcase( rc!=SQLITE_OK ); /* Query flattening in sqlite3Select() might refill p->pOrderBy. ** Be sure to delete p->pOrderBy, therefore, to avoid a memory leak. */ sqlite3ExprListDelete(db, p->pOrderBy); pDelete = p->pPrior; p->pPrior = pPrior; p->pOrderBy = 0; if( p->op==TK_UNION ){ p->nSelectRow = sqlite3LogEstAdd(p->nSelectRow, pPrior->nSelectRow); } sqlite3ExprDelete(db, p->pLimit); p->pLimit = pLimit; p->pOffset = pOffset; p->iLimit = 0; p->iOffset = 0; /* Convert the data in the temporary table into whatever form ** it is that we currently need. */ assert( unionTab==dest.iSDParm || dest.eDest!=priorOp ); if( dest.eDest!=priorOp ){ int iCont, iBreak, iStart; assert( p->pEList ); if( dest.eDest==SRT_Output ){ Select *pFirst = p; while( pFirst->pPrior ) pFirst = pFirst->pPrior; generateColumnNames(pParse, pFirst->pSrc, pFirst->pEList); } iBreak = sqlite3VdbeMakeLabel(v); iCont = sqlite3VdbeMakeLabel(v); computeLimitRegisters(pParse, p, iBreak); sqlite3VdbeAddOp2(v, OP_Rewind, unionTab, iBreak); VdbeCoverage(v); iStart = sqlite3VdbeCurrentAddr(v); selectInnerLoop(pParse, p, p->pEList, unionTab, 0, 0, &dest, iCont, iBreak); sqlite3VdbeResolveLabel(v, iCont); sqlite3VdbeAddOp2(v, OP_Next, unionTab, iStart); VdbeCoverage(v); sqlite3VdbeResolveLabel(v, iBreak); sqlite3VdbeAddOp2(v, OP_Close, unionTab, 0); } break; } default: assert( p->op==TK_INTERSECT ); { int tab1, tab2; int iCont, iBreak, iStart; Expr *pLimit, *pOffset; int addr; SelectDest intersectdest; int r1; /* INTERSECT is different from the others since it requires ** two temporary tables. Hence it has its own case. Begin ** by allocating the tables we will need. */ tab1 = pParse->nTab++; tab2 = pParse->nTab++; assert( p->pOrderBy==0 ); addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, tab1, 0); assert( p->addrOpenEphm[0] == -1 ); p->addrOpenEphm[0] = addr; findRightmost(p)->selFlags |= SF_UsesEphemeral; assert( p->pEList ); /* Code the SELECTs to our left into temporary table "tab1". */ sqlite3SelectDestInit(&intersectdest, SRT_Union, tab1); explainSetInteger(iSub1, pParse->iNextSelectId); rc = sqlite3Select(pParse, pPrior, &intersectdest); if( rc ){ goto multi_select_end; } /* Code the current SELECT into temporary table "tab2" */ addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, tab2, 0); assert( p->addrOpenEphm[1] == -1 ); p->addrOpenEphm[1] = addr; p->pPrior = 0; pLimit = p->pLimit; p->pLimit = 0; pOffset = p->pOffset; p->pOffset = 0; intersectdest.iSDParm = tab2; explainSetInteger(iSub2, pParse->iNextSelectId); rc = sqlite3Select(pParse, p, &intersectdest); testcase( rc!=SQLITE_OK ); pDelete = p->pPrior; p->pPrior = pPrior; if( p->nSelectRow>pPrior->nSelectRow ) p->nSelectRow = pPrior->nSelectRow; sqlite3ExprDelete(db, p->pLimit); p->pLimit = pLimit; p->pOffset = pOffset; /* Generate code to take the intersection of the two temporary ** tables. */ assert( p->pEList ); if( dest.eDest==SRT_Output ){ Select *pFirst = p; while( pFirst->pPrior ) pFirst = pFirst->pPrior; generateColumnNames(pParse, pFirst->pSrc, pFirst->pEList); } iBreak = sqlite3VdbeMakeLabel(v); iCont = sqlite3VdbeMakeLabel(v); computeLimitRegisters(pParse, p, iBreak); sqlite3VdbeAddOp2(v, OP_Rewind, tab1, iBreak); VdbeCoverage(v); r1 = sqlite3GetTempReg(pParse); iStart = sqlite3VdbeAddOp2(v, OP_RowKey, tab1, r1); sqlite3VdbeAddOp4Int(v, OP_NotFound, tab2, iCont, r1, 0); VdbeCoverage(v); sqlite3ReleaseTempReg(pParse, r1); selectInnerLoop(pParse, p, p->pEList, tab1, 0, 0, &dest, iCont, iBreak); sqlite3VdbeResolveLabel(v, iCont); sqlite3VdbeAddOp2(v, OP_Next, tab1, iStart); VdbeCoverage(v); sqlite3VdbeResolveLabel(v, iBreak); sqlite3VdbeAddOp2(v, OP_Close, tab2, 0); sqlite3VdbeAddOp2(v, OP_Close, tab1, 0); break; } } explainComposite(pParse, p->op, iSub1, iSub2, p->op!=TK_ALL); /* Compute collating sequences used by ** temporary tables needed to implement the compound select. ** Attach the KeyInfo structure to all temporary tables. ** ** This section is run by the right-most SELECT statement only. ** SELECT statements to the left always skip this part. The right-most ** SELECT might also skip this part if it has no ORDER BY clause and ** no temp tables are required. */ if( p->selFlags & SF_UsesEphemeral ){ int i; /* Loop counter */ KeyInfo *pKeyInfo; /* Collating sequence for the result set */ Select *pLoop; /* For looping through SELECT statements */ CollSeq **apColl; /* For looping through pKeyInfo->aColl[] */ int nCol; /* Number of columns in result set */ assert( p->pNext==0 ); nCol = p->pEList->nExpr; pKeyInfo = sqlite3KeyInfoAlloc(db, nCol, 1); if( !pKeyInfo ){ rc = SQLITE_NOMEM_BKPT; goto multi_select_end; } for(i=0, apColl=pKeyInfo->aColl; ipDfltColl; } } for(pLoop=p; pLoop; pLoop=pLoop->pPrior){ for(i=0; i<2; i++){ int addr = pLoop->addrOpenEphm[i]; if( addr<0 ){ /* If [0] is unused then [1] is also unused. So we can ** always safely abort as soon as the first unused slot is found */ assert( pLoop->addrOpenEphm[1]<0 ); break; } sqlite3VdbeChangeP2(v, addr, nCol); sqlite3VdbeChangeP4(v, addr, (char*)sqlite3KeyInfoRef(pKeyInfo), P4_KEYINFO); pLoop->addrOpenEphm[i] = -1; } } sqlite3KeyInfoUnref(pKeyInfo); } multi_select_end: pDest->iSdst = dest.iSdst; pDest->nSdst = dest.nSdst; sqlite3SelectDelete(db, pDelete); return rc; } #endif /* SQLITE_OMIT_COMPOUND_SELECT */ /* ** Error message for when two or more terms of a compound select have different ** size result sets. */ SQLITE_PRIVATE void sqlite3SelectWrongNumTermsError(Parse *pParse, Select *p){ if( p->selFlags & SF_Values ){ sqlite3ErrorMsg(pParse, "all VALUES must have the same number of terms"); }else{ sqlite3ErrorMsg(pParse, "SELECTs to the left and right of %s" " do not have the same number of result columns", selectOpName(p->op)); } } /* ** Code an output subroutine for a coroutine implementation of a ** SELECT statment. ** ** The data to be output is contained in pIn->iSdst. There are ** pIn->nSdst columns to be output. pDest is where the output should ** be sent. ** ** regReturn is the number of the register holding the subroutine ** return address. ** ** If regPrev>0 then it is the first register in a vector that ** records the previous output. mem[regPrev] is a flag that is false ** if there has been no previous output. If regPrev>0 then code is ** generated to suppress duplicates. pKeyInfo is used for comparing ** keys. ** ** If the LIMIT found in p->iLimit is reached, jump immediately to ** iBreak. */ static int generateOutputSubroutine( Parse *pParse, /* Parsing context */ Select *p, /* The SELECT statement */ SelectDest *pIn, /* Coroutine supplying data */ SelectDest *pDest, /* Where to send the data */ int regReturn, /* The return address register */ int regPrev, /* Previous result register. No uniqueness if 0 */ KeyInfo *pKeyInfo, /* For comparing with previous entry */ int iBreak /* Jump here if we hit the LIMIT */ ){ Vdbe *v = pParse->pVdbe; int iContinue; int addr; addr = sqlite3VdbeCurrentAddr(v); iContinue = sqlite3VdbeMakeLabel(v); /* Suppress duplicates for UNION, EXCEPT, and INTERSECT */ if( regPrev ){ int addr1, addr2; addr1 = sqlite3VdbeAddOp1(v, OP_IfNot, regPrev); VdbeCoverage(v); addr2 = sqlite3VdbeAddOp4(v, OP_Compare, pIn->iSdst, regPrev+1, pIn->nSdst, (char*)sqlite3KeyInfoRef(pKeyInfo), P4_KEYINFO); sqlite3VdbeAddOp3(v, OP_Jump, addr2+2, iContinue, addr2+2); VdbeCoverage(v); sqlite3VdbeJumpHere(v, addr1); sqlite3VdbeAddOp3(v, OP_Copy, pIn->iSdst, regPrev+1, pIn->nSdst-1); sqlite3VdbeAddOp2(v, OP_Integer, 1, regPrev); } if( pParse->db->mallocFailed ) return 0; /* Suppress the first OFFSET entries if there is an OFFSET clause */ codeOffset(v, p->iOffset, iContinue); assert( pDest->eDest!=SRT_Exists ); assert( pDest->eDest!=SRT_Table ); switch( pDest->eDest ){ /* Store the result as data using a unique key. */ case SRT_EphemTab: { int r1 = sqlite3GetTempReg(pParse); int r2 = sqlite3GetTempReg(pParse); sqlite3VdbeAddOp3(v, OP_MakeRecord, pIn->iSdst, pIn->nSdst, r1); sqlite3VdbeAddOp2(v, OP_NewRowid, pDest->iSDParm, r2); sqlite3VdbeAddOp3(v, OP_Insert, pDest->iSDParm, r1, r2); sqlite3VdbeChangeP5(v, OPFLAG_APPEND); sqlite3ReleaseTempReg(pParse, r2); sqlite3ReleaseTempReg(pParse, r1); break; } #ifndef SQLITE_OMIT_SUBQUERY /* If we are creating a set for an "expr IN (SELECT ...)". */ case SRT_Set: { int r1; testcase( pIn->nSdst>1 ); r1 = sqlite3GetTempReg(pParse); sqlite3VdbeAddOp4(v, OP_MakeRecord, pIn->iSdst, pIn->nSdst, r1, pDest->zAffSdst, pIn->nSdst); sqlite3ExprCacheAffinityChange(pParse, pIn->iSdst, pIn->nSdst); sqlite3VdbeAddOp2(v, OP_IdxInsert, pDest->iSDParm, r1); sqlite3ReleaseTempReg(pParse, r1); break; } /* If this is a scalar select that is part of an expression, then ** store the results in the appropriate memory cell and break out ** of the scan loop. */ case SRT_Mem: { assert( pIn->nSdst==1 || pParse->nErr>0 ); testcase( pIn->nSdst!=1 ); sqlite3ExprCodeMove(pParse, pIn->iSdst, pDest->iSDParm, 1); /* The LIMIT clause will jump out of the loop for us */ break; } #endif /* #ifndef SQLITE_OMIT_SUBQUERY */ /* The results are stored in a sequence of registers ** starting at pDest->iSdst. Then the co-routine yields. */ case SRT_Coroutine: { if( pDest->iSdst==0 ){ pDest->iSdst = sqlite3GetTempRange(pParse, pIn->nSdst); pDest->nSdst = pIn->nSdst; } sqlite3ExprCodeMove(pParse, pIn->iSdst, pDest->iSdst, pIn->nSdst); sqlite3VdbeAddOp1(v, OP_Yield, pDest->iSDParm); break; } /* If none of the above, then the result destination must be ** SRT_Output. This routine is never called with any other ** destination other than the ones handled above or SRT_Output. ** ** For SRT_Output, results are stored in a sequence of registers. ** Then the OP_ResultRow opcode is used to cause sqlite3_step() to ** return the next row of result. */ default: { assert( pDest->eDest==SRT_Output ); sqlite3VdbeAddOp2(v, OP_ResultRow, pIn->iSdst, pIn->nSdst); sqlite3ExprCacheAffinityChange(pParse, pIn->iSdst, pIn->nSdst); break; } } /* Jump to the end of the loop if the LIMIT is reached. */ if( p->iLimit ){ sqlite3VdbeAddOp2(v, OP_DecrJumpZero, p->iLimit, iBreak); VdbeCoverage(v); } /* Generate the subroutine return */ sqlite3VdbeResolveLabel(v, iContinue); sqlite3VdbeAddOp1(v, OP_Return, regReturn); return addr; } /* ** Alternative compound select code generator for cases when there ** is an ORDER BY clause. ** ** We assume a query of the following form: ** ** ORDER BY ** ** is one of UNION ALL, UNION, EXCEPT, or INTERSECT. The idea ** is to code both and with the ORDER BY clause as ** co-routines. Then run the co-routines in parallel and merge the results ** into the output. In addition to the two coroutines (called selectA and ** selectB) there are 7 subroutines: ** ** outA: Move the output of the selectA coroutine into the output ** of the compound query. ** ** outB: Move the output of the selectB coroutine into the output ** of the compound query. (Only generated for UNION and ** UNION ALL. EXCEPT and INSERTSECT never output a row that ** appears only in B.) ** ** AltB: Called when there is data from both coroutines and AB. ** ** EofA: Called when data is exhausted from selectA. ** ** EofB: Called when data is exhausted from selectB. ** ** The implementation of the latter five subroutines depend on which ** is used: ** ** ** UNION ALL UNION EXCEPT INTERSECT ** ------------- ----------------- -------------- ----------------- ** AltB: outA, nextA outA, nextA outA, nextA nextA ** ** AeqB: outA, nextA nextA nextA outA, nextA ** ** AgtB: outB, nextB outB, nextB nextB nextB ** ** EofA: outB, nextB outB, nextB halt halt ** ** EofB: outA, nextA outA, nextA outA, nextA halt ** ** In the AltB, AeqB, and AgtB subroutines, an EOF on A following nextA ** causes an immediate jump to EofA and an EOF on B following nextB causes ** an immediate jump to EofB. Within EofA and EofB, and EOF on entry or ** following nextX causes a jump to the end of the select processing. ** ** Duplicate removal in the UNION, EXCEPT, and INTERSECT cases is handled ** within the output subroutine. The regPrev register set holds the previously ** output value. A comparison is made against this value and the output ** is skipped if the next results would be the same as the previous. ** ** The implementation plan is to implement the two coroutines and seven ** subroutines first, then put the control logic at the bottom. Like this: ** ** goto Init ** coA: coroutine for left query (A) ** coB: coroutine for right query (B) ** outA: output one row of A ** outB: output one row of B (UNION and UNION ALL only) ** EofA: ... ** EofB: ... ** AltB: ... ** AeqB: ... ** AgtB: ... ** Init: initialize coroutine registers ** yield coA ** if eof(A) goto EofA ** yield coB ** if eof(B) goto EofB ** Cmpr: Compare A, B ** Jump AltB, AeqB, AgtB ** End: ... ** ** We call AltB, AeqB, AgtB, EofA, and EofB "subroutines" but they are not ** actually called using Gosub and they do not Return. EofA and EofB loop ** until all data is exhausted then jump to the "end" labe. AltB, AeqB, ** and AgtB jump to either L2 or to one of EofA or EofB. */ #ifndef SQLITE_OMIT_COMPOUND_SELECT static int multiSelectOrderBy( Parse *pParse, /* Parsing context */ Select *p, /* The right-most of SELECTs to be coded */ SelectDest *pDest /* What to do with query results */ ){ int i, j; /* Loop counters */ Select *pPrior; /* Another SELECT immediately to our left */ Vdbe *v; /* Generate code to this VDBE */ SelectDest destA; /* Destination for coroutine A */ SelectDest destB; /* Destination for coroutine B */ int regAddrA; /* Address register for select-A coroutine */ int regAddrB; /* Address register for select-B coroutine */ int addrSelectA; /* Address of the select-A coroutine */ int addrSelectB; /* Address of the select-B coroutine */ int regOutA; /* Address register for the output-A subroutine */ int regOutB; /* Address register for the output-B subroutine */ int addrOutA; /* Address of the output-A subroutine */ int addrOutB = 0; /* Address of the output-B subroutine */ int addrEofA; /* Address of the select-A-exhausted subroutine */ int addrEofA_noB; /* Alternate addrEofA if B is uninitialized */ int addrEofB; /* Address of the select-B-exhausted subroutine */ int addrAltB; /* Address of the AB subroutine */ int regLimitA; /* Limit register for select-A */ int regLimitB; /* Limit register for select-A */ int regPrev; /* A range of registers to hold previous output */ int savedLimit; /* Saved value of p->iLimit */ int savedOffset; /* Saved value of p->iOffset */ int labelCmpr; /* Label for the start of the merge algorithm */ int labelEnd; /* Label for the end of the overall SELECT stmt */ int addr1; /* Jump instructions that get retargetted */ int op; /* One of TK_ALL, TK_UNION, TK_EXCEPT, TK_INTERSECT */ KeyInfo *pKeyDup = 0; /* Comparison information for duplicate removal */ KeyInfo *pKeyMerge; /* Comparison information for merging rows */ sqlite3 *db; /* Database connection */ ExprList *pOrderBy; /* The ORDER BY clause */ int nOrderBy; /* Number of terms in the ORDER BY clause */ int *aPermute; /* Mapping from ORDER BY terms to result set columns */ #ifndef SQLITE_OMIT_EXPLAIN int iSub1; /* EQP id of left-hand query */ int iSub2; /* EQP id of right-hand query */ #endif assert( p->pOrderBy!=0 ); assert( pKeyDup==0 ); /* "Managed" code needs this. Ticket #3382. */ db = pParse->db; v = pParse->pVdbe; assert( v!=0 ); /* Already thrown the error if VDBE alloc failed */ labelEnd = sqlite3VdbeMakeLabel(v); labelCmpr = sqlite3VdbeMakeLabel(v); /* Patch up the ORDER BY clause */ op = p->op; pPrior = p->pPrior; assert( pPrior->pOrderBy==0 ); pOrderBy = p->pOrderBy; assert( pOrderBy ); nOrderBy = pOrderBy->nExpr; /* For operators other than UNION ALL we have to make sure that ** the ORDER BY clause covers every term of the result set. Add ** terms to the ORDER BY clause as necessary. */ if( op!=TK_ALL ){ for(i=1; db->mallocFailed==0 && i<=p->pEList->nExpr; i++){ struct ExprList_item *pItem; for(j=0, pItem=pOrderBy->a; ju.x.iOrderByCol>0 ); if( pItem->u.x.iOrderByCol==i ) break; } if( j==nOrderBy ){ Expr *pNew = sqlite3Expr(db, TK_INTEGER, 0); if( pNew==0 ) return SQLITE_NOMEM_BKPT; pNew->flags |= EP_IntValue; pNew->u.iValue = i; pOrderBy = sqlite3ExprListAppend(pParse, pOrderBy, pNew); if( pOrderBy ) pOrderBy->a[nOrderBy++].u.x.iOrderByCol = (u16)i; } } } /* Compute the comparison permutation and keyinfo that is used with ** the permutation used to determine if the next ** row of results comes from selectA or selectB. Also add explicit ** collations to the ORDER BY clause terms so that when the subqueries ** to the right and the left are evaluated, they use the correct ** collation. */ aPermute = sqlite3DbMallocRawNN(db, sizeof(int)*(nOrderBy + 1)); if( aPermute ){ struct ExprList_item *pItem; aPermute[0] = nOrderBy; for(i=1, pItem=pOrderBy->a; i<=nOrderBy; i++, pItem++){ assert( pItem->u.x.iOrderByCol>0 ); assert( pItem->u.x.iOrderByCol<=p->pEList->nExpr ); aPermute[i] = pItem->u.x.iOrderByCol - 1; } pKeyMerge = multiSelectOrderByKeyInfo(pParse, p, 1); }else{ pKeyMerge = 0; } /* Reattach the ORDER BY clause to the query. */ p->pOrderBy = pOrderBy; pPrior->pOrderBy = sqlite3ExprListDup(pParse->db, pOrderBy, 0); /* Allocate a range of temporary registers and the KeyInfo needed ** for the logic that removes duplicate result rows when the ** operator is UNION, EXCEPT, or INTERSECT (but not UNION ALL). */ if( op==TK_ALL ){ regPrev = 0; }else{ int nExpr = p->pEList->nExpr; assert( nOrderBy>=nExpr || db->mallocFailed ); regPrev = pParse->nMem+1; pParse->nMem += nExpr+1; sqlite3VdbeAddOp2(v, OP_Integer, 0, regPrev); pKeyDup = sqlite3KeyInfoAlloc(db, nExpr, 1); if( pKeyDup ){ assert( sqlite3KeyInfoIsWriteable(pKeyDup) ); for(i=0; iaColl[i] = multiSelectCollSeq(pParse, p, i); pKeyDup->aSortOrder[i] = 0; } } } /* Separate the left and the right query from one another */ p->pPrior = 0; pPrior->pNext = 0; sqlite3ResolveOrderGroupBy(pParse, p, p->pOrderBy, "ORDER"); if( pPrior->pPrior==0 ){ sqlite3ResolveOrderGroupBy(pParse, pPrior, pPrior->pOrderBy, "ORDER"); } /* Compute the limit registers */ computeLimitRegisters(pParse, p, labelEnd); if( p->iLimit && op==TK_ALL ){ regLimitA = ++pParse->nMem; regLimitB = ++pParse->nMem; sqlite3VdbeAddOp2(v, OP_Copy, p->iOffset ? p->iOffset+1 : p->iLimit, regLimitA); sqlite3VdbeAddOp2(v, OP_Copy, regLimitA, regLimitB); }else{ regLimitA = regLimitB = 0; } sqlite3ExprDelete(db, p->pLimit); p->pLimit = 0; sqlite3ExprDelete(db, p->pOffset); p->pOffset = 0; regAddrA = ++pParse->nMem; regAddrB = ++pParse->nMem; regOutA = ++pParse->nMem; regOutB = ++pParse->nMem; sqlite3SelectDestInit(&destA, SRT_Coroutine, regAddrA); sqlite3SelectDestInit(&destB, SRT_Coroutine, regAddrB); /* Generate a coroutine to evaluate the SELECT statement to the ** left of the compound operator - the "A" select. */ addrSelectA = sqlite3VdbeCurrentAddr(v) + 1; addr1 = sqlite3VdbeAddOp3(v, OP_InitCoroutine, regAddrA, 0, addrSelectA); VdbeComment((v, "left SELECT")); pPrior->iLimit = regLimitA; explainSetInteger(iSub1, pParse->iNextSelectId); sqlite3Select(pParse, pPrior, &destA); sqlite3VdbeEndCoroutine(v, regAddrA); sqlite3VdbeJumpHere(v, addr1); /* Generate a coroutine to evaluate the SELECT statement on ** the right - the "B" select */ addrSelectB = sqlite3VdbeCurrentAddr(v) + 1; addr1 = sqlite3VdbeAddOp3(v, OP_InitCoroutine, regAddrB, 0, addrSelectB); VdbeComment((v, "right SELECT")); savedLimit = p->iLimit; savedOffset = p->iOffset; p->iLimit = regLimitB; p->iOffset = 0; explainSetInteger(iSub2, pParse->iNextSelectId); sqlite3Select(pParse, p, &destB); p->iLimit = savedLimit; p->iOffset = savedOffset; sqlite3VdbeEndCoroutine(v, regAddrB); /* Generate a subroutine that outputs the current row of the A ** select as the next output row of the compound select. */ VdbeNoopComment((v, "Output routine for A")); addrOutA = generateOutputSubroutine(pParse, p, &destA, pDest, regOutA, regPrev, pKeyDup, labelEnd); /* Generate a subroutine that outputs the current row of the B ** select as the next output row of the compound select. */ if( op==TK_ALL || op==TK_UNION ){ VdbeNoopComment((v, "Output routine for B")); addrOutB = generateOutputSubroutine(pParse, p, &destB, pDest, regOutB, regPrev, pKeyDup, labelEnd); } sqlite3KeyInfoUnref(pKeyDup); /* Generate a subroutine to run when the results from select A ** are exhausted and only data in select B remains. */ if( op==TK_EXCEPT || op==TK_INTERSECT ){ addrEofA_noB = addrEofA = labelEnd; }else{ VdbeNoopComment((v, "eof-A subroutine")); addrEofA = sqlite3VdbeAddOp2(v, OP_Gosub, regOutB, addrOutB); addrEofA_noB = sqlite3VdbeAddOp2(v, OP_Yield, regAddrB, labelEnd); VdbeCoverage(v); sqlite3VdbeGoto(v, addrEofA); p->nSelectRow = sqlite3LogEstAdd(p->nSelectRow, pPrior->nSelectRow); } /* Generate a subroutine to run when the results from select B ** are exhausted and only data in select A remains. */ if( op==TK_INTERSECT ){ addrEofB = addrEofA; if( p->nSelectRow > pPrior->nSelectRow ) p->nSelectRow = pPrior->nSelectRow; }else{ VdbeNoopComment((v, "eof-B subroutine")); addrEofB = sqlite3VdbeAddOp2(v, OP_Gosub, regOutA, addrOutA); sqlite3VdbeAddOp2(v, OP_Yield, regAddrA, labelEnd); VdbeCoverage(v); sqlite3VdbeGoto(v, addrEofB); } /* Generate code to handle the case of AB */ VdbeNoopComment((v, "A-gt-B subroutine")); addrAgtB = sqlite3VdbeCurrentAddr(v); if( op==TK_ALL || op==TK_UNION ){ sqlite3VdbeAddOp2(v, OP_Gosub, regOutB, addrOutB); } sqlite3VdbeAddOp2(v, OP_Yield, regAddrB, addrEofB); VdbeCoverage(v); sqlite3VdbeGoto(v, labelCmpr); /* This code runs once to initialize everything. */ sqlite3VdbeJumpHere(v, addr1); sqlite3VdbeAddOp2(v, OP_Yield, regAddrA, addrEofA_noB); VdbeCoverage(v); sqlite3VdbeAddOp2(v, OP_Yield, regAddrB, addrEofB); VdbeCoverage(v); /* Implement the main merge loop */ sqlite3VdbeResolveLabel(v, labelCmpr); sqlite3VdbeAddOp4(v, OP_Permutation, 0, 0, 0, (char*)aPermute, P4_INTARRAY); sqlite3VdbeAddOp4(v, OP_Compare, destA.iSdst, destB.iSdst, nOrderBy, (char*)pKeyMerge, P4_KEYINFO); sqlite3VdbeChangeP5(v, OPFLAG_PERMUTE); sqlite3VdbeAddOp3(v, OP_Jump, addrAltB, addrAeqB, addrAgtB); VdbeCoverage(v); /* Jump to the this point in order to terminate the query. */ sqlite3VdbeResolveLabel(v, labelEnd); /* Set the number of output columns */ if( pDest->eDest==SRT_Output ){ Select *pFirst = pPrior; while( pFirst->pPrior ) pFirst = pFirst->pPrior; generateColumnNames(pParse, pFirst->pSrc, pFirst->pEList); } /* Reassembly the compound query so that it will be freed correctly ** by the calling function */ if( p->pPrior ){ sqlite3SelectDelete(db, p->pPrior); } p->pPrior = pPrior; pPrior->pNext = p; /*** TBD: Insert subroutine calls to close cursors on incomplete **** subqueries ****/ explainComposite(pParse, p->op, iSub1, iSub2, 0); return pParse->nErr!=0; } #endif #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) /* Forward Declarations */ static void substExprList(sqlite3*, ExprList*, int, ExprList*); static void substSelect(sqlite3*, Select *, int, ExprList*, int); /* ** Scan through the expression pExpr. Replace every reference to ** a column in table number iTable with a copy of the iColumn-th ** entry in pEList. (But leave references to the ROWID column ** unchanged.) ** ** This routine is part of the flattening procedure. A subquery ** whose result set is defined by pEList appears as entry in the ** FROM clause of a SELECT such that the VDBE cursor assigned to that ** FORM clause entry is iTable. This routine make the necessary ** changes to pExpr so that it refers directly to the source table ** of the subquery rather the result set of the subquery. */ static Expr *substExpr( sqlite3 *db, /* Report malloc errors to this connection */ Expr *pExpr, /* Expr in which substitution occurs */ int iTable, /* Table to be substituted */ ExprList *pEList /* Substitute expressions */ ){ if( pExpr==0 ) return 0; if( pExpr->op==TK_COLUMN && pExpr->iTable==iTable ){ if( pExpr->iColumn<0 ){ pExpr->op = TK_NULL; }else{ Expr *pNew; assert( pEList!=0 && pExpr->iColumnnExpr ); assert( pExpr->pLeft==0 && pExpr->pRight==0 ); pNew = sqlite3ExprDup(db, pEList->a[pExpr->iColumn].pExpr, 0); sqlite3ExprDelete(db, pExpr); pExpr = pNew; } }else{ pExpr->pLeft = substExpr(db, pExpr->pLeft, iTable, pEList); pExpr->pRight = substExpr(db, pExpr->pRight, iTable, pEList); if( ExprHasProperty(pExpr, EP_xIsSelect) ){ substSelect(db, pExpr->x.pSelect, iTable, pEList, 1); }else{ substExprList(db, pExpr->x.pList, iTable, pEList); } } return pExpr; } static void substExprList( sqlite3 *db, /* Report malloc errors here */ ExprList *pList, /* List to scan and in which to make substitutes */ int iTable, /* Table to be substituted */ ExprList *pEList /* Substitute values */ ){ int i; if( pList==0 ) return; for(i=0; inExpr; i++){ pList->a[i].pExpr = substExpr(db, pList->a[i].pExpr, iTable, pEList); } } static void substSelect( sqlite3 *db, /* Report malloc errors here */ Select *p, /* SELECT statement in which to make substitutions */ int iTable, /* Table to be replaced */ ExprList *pEList, /* Substitute values */ int doPrior /* Do substitutes on p->pPrior too */ ){ SrcList *pSrc; struct SrcList_item *pItem; int i; if( !p ) return; do{ substExprList(db, p->pEList, iTable, pEList); substExprList(db, p->pGroupBy, iTable, pEList); substExprList(db, p->pOrderBy, iTable, pEList); p->pHaving = substExpr(db, p->pHaving, iTable, pEList); p->pWhere = substExpr(db, p->pWhere, iTable, pEList); pSrc = p->pSrc; assert( pSrc!=0 ); for(i=pSrc->nSrc, pItem=pSrc->a; i>0; i--, pItem++){ substSelect(db, pItem->pSelect, iTable, pEList, 1); if( pItem->fg.isTabFunc ){ substExprList(db, pItem->u1.pFuncArg, iTable, pEList); } } }while( doPrior && (p = p->pPrior)!=0 ); } #endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */ #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) /* ** This routine attempts to flatten subqueries as a performance optimization. ** This routine returns 1 if it makes changes and 0 if no flattening occurs. ** ** To understand the concept of flattening, consider the following ** query: ** ** SELECT a FROM (SELECT x+y AS a FROM t1 WHERE z<100) WHERE a>5 ** ** The default way of implementing this query is to execute the ** subquery first and store the results in a temporary table, then ** run the outer query on that temporary table. This requires two ** passes over the data. Furthermore, because the temporary table ** has no indices, the WHERE clause on the outer query cannot be ** optimized. ** ** This routine attempts to rewrite queries such as the above into ** a single flat select, like this: ** ** SELECT x+y AS a FROM t1 WHERE z<100 AND a>5 ** ** The code generated for this simplification gives the same result ** but only has to scan the data once. And because indices might ** exist on the table t1, a complete scan of the data might be ** avoided. ** ** Flattening is only attempted if all of the following are true: ** ** (1) The subquery and the outer query do not both use aggregates. ** ** (2) The subquery is not an aggregate or (2a) the outer query is not a join ** and (2b) the outer query does not use subqueries other than the one ** FROM-clause subquery that is a candidate for flattening. (2b is ** due to ticket [2f7170d73bf9abf80] from 2015-02-09.) ** ** (3) The subquery is not the right operand of a left outer join ** (Originally ticket #306. Strengthened by ticket #3300) ** ** (4) The subquery is not DISTINCT. ** ** (**) At one point restrictions (4) and (5) defined a subset of DISTINCT ** sub-queries that were excluded from this optimization. Restriction ** (4) has since been expanded to exclude all DISTINCT subqueries. ** ** (6) The subquery does not use aggregates or the outer query is not ** DISTINCT. ** ** (7) The subquery has a FROM clause. TODO: For subqueries without ** A FROM clause, consider adding a FROM close with the special ** table sqlite_once that consists of a single row containing a ** single NULL. ** ** (8) The subquery does not use LIMIT or the outer query is not a join. ** ** (9) The subquery does not use LIMIT or the outer query does not use ** aggregates. ** ** (**) Restriction (10) was removed from the code on 2005-02-05 but we ** accidently carried the comment forward until 2014-09-15. Original ** text: "The subquery does not use aggregates or the outer query ** does not use LIMIT." ** ** (11) The subquery and the outer query do not both have ORDER BY clauses. ** ** (**) Not implemented. Subsumed into restriction (3). Was previously ** a separate restriction deriving from ticket #350. ** ** (13) The subquery and outer query do not both use LIMIT. ** ** (14) The subquery does not use OFFSET. ** ** (15) The outer query is not part of a compound select or the ** subquery does not have a LIMIT clause. ** (See ticket #2339 and ticket [02a8e81d44]). ** ** (16) The outer query is not an aggregate or the subquery does ** not contain ORDER BY. (Ticket #2942) This used to not matter ** until we introduced the group_concat() function. ** ** (17) The sub-query is not a compound select, or it is a UNION ALL ** compound clause made up entirely of non-aggregate queries, and ** the parent query: ** ** * is not itself part of a compound select, ** * is not an aggregate or DISTINCT query, and ** * is not a join ** ** The parent and sub-query may contain WHERE clauses. Subject to ** rules (11), (13) and (14), they may also contain ORDER BY, ** LIMIT and OFFSET clauses. The subquery cannot use any compound ** operator other than UNION ALL because all the other compound ** operators have an implied DISTINCT which is disallowed by ** restriction (4). ** ** Also, each component of the sub-query must return the same number ** of result columns. This is actually a requirement for any compound ** SELECT statement, but all the code here does is make sure that no ** such (illegal) sub-query is flattened. The caller will detect the ** syntax error and return a detailed message. ** ** (18) If the sub-query is a compound select, then all terms of the ** ORDER by clause of the parent must be simple references to ** columns of the sub-query. ** ** (19) The subquery does not use LIMIT or the outer query does not ** have a WHERE clause. ** ** (20) If the sub-query is a compound select, then it must not use ** an ORDER BY clause. Ticket #3773. We could relax this constraint ** somewhat by saying that the terms of the ORDER BY clause must ** appear as unmodified result columns in the outer query. But we ** have other optimizations in mind to deal with that case. ** ** (21) The subquery does not use LIMIT or the outer query is not ** DISTINCT. (See ticket [752e1646fc]). ** ** (22) The subquery is not a recursive CTE. ** ** (23) The parent is not a recursive CTE, or the sub-query is not a ** compound query. This restriction is because transforming the ** parent to a compound query confuses the code that handles ** recursive queries in multiSelect(). ** ** (24) The subquery is not an aggregate that uses the built-in min() or ** or max() functions. (Without this restriction, a query like: ** "SELECT x FROM (SELECT max(y), x FROM t1)" would not necessarily ** return the value X for which Y was maximal.) ** ** ** In this routine, the "p" parameter is a pointer to the outer query. ** The subquery is p->pSrc->a[iFrom]. isAgg is true if the outer query ** uses aggregates and subqueryIsAgg is true if the subquery uses aggregates. ** ** If flattening is not attempted, this routine is a no-op and returns 0. ** If flattening is attempted this routine returns 1. ** ** All of the expression analysis must occur on both the outer query and ** the subquery before this routine runs. */ static int flattenSubquery( Parse *pParse, /* Parsing context */ Select *p, /* The parent or outer SELECT statement */ int iFrom, /* Index in p->pSrc->a[] of the inner subquery */ int isAgg, /* True if outer SELECT uses aggregate functions */ int subqueryIsAgg /* True if the subquery uses aggregate functions */ ){ const char *zSavedAuthContext = pParse->zAuthContext; Select *pParent; /* Current UNION ALL term of the other query */ Select *pSub; /* The inner query or "subquery" */ Select *pSub1; /* Pointer to the rightmost select in sub-query */ SrcList *pSrc; /* The FROM clause of the outer query */ SrcList *pSubSrc; /* The FROM clause of the subquery */ ExprList *pList; /* The result set of the outer query */ int iParent; /* VDBE cursor number of the pSub result set temp table */ int i; /* Loop counter */ Expr *pWhere; /* The WHERE clause */ struct SrcList_item *pSubitem; /* The subquery */ sqlite3 *db = pParse->db; /* Check to see if flattening is permitted. Return 0 if not. */ assert( p!=0 ); assert( p->pPrior==0 ); /* Unable to flatten compound queries */ if( OptimizationDisabled(db, SQLITE_QueryFlattener) ) return 0; pSrc = p->pSrc; assert( pSrc && iFrom>=0 && iFromnSrc ); pSubitem = &pSrc->a[iFrom]; iParent = pSubitem->iCursor; pSub = pSubitem->pSelect; assert( pSub!=0 ); if( subqueryIsAgg ){ if( isAgg ) return 0; /* Restriction (1) */ if( pSrc->nSrc>1 ) return 0; /* Restriction (2a) */ if( (p->pWhere && ExprHasProperty(p->pWhere,EP_Subquery)) || (sqlite3ExprListFlags(p->pEList) & EP_Subquery)!=0 || (sqlite3ExprListFlags(p->pOrderBy) & EP_Subquery)!=0 ){ return 0; /* Restriction (2b) */ } } pSubSrc = pSub->pSrc; assert( pSubSrc ); /* Prior to version 3.1.2, when LIMIT and OFFSET had to be simple constants, ** not arbitrary expressions, we allowed some combining of LIMIT and OFFSET ** because they could be computed at compile-time. But when LIMIT and OFFSET ** became arbitrary expressions, we were forced to add restrictions (13) ** and (14). */ if( pSub->pLimit && p->pLimit ) return 0; /* Restriction (13) */ if( pSub->pOffset ) return 0; /* Restriction (14) */ if( (p->selFlags & SF_Compound)!=0 && pSub->pLimit ){ return 0; /* Restriction (15) */ } if( pSubSrc->nSrc==0 ) return 0; /* Restriction (7) */ if( pSub->selFlags & SF_Distinct ) return 0; /* Restriction (5) */ if( pSub->pLimit && (pSrc->nSrc>1 || isAgg) ){ return 0; /* Restrictions (8)(9) */ } if( (p->selFlags & SF_Distinct)!=0 && subqueryIsAgg ){ return 0; /* Restriction (6) */ } if( p->pOrderBy && pSub->pOrderBy ){ return 0; /* Restriction (11) */ } if( isAgg && pSub->pOrderBy ) return 0; /* Restriction (16) */ if( pSub->pLimit && p->pWhere ) return 0; /* Restriction (19) */ if( pSub->pLimit && (p->selFlags & SF_Distinct)!=0 ){ return 0; /* Restriction (21) */ } testcase( pSub->selFlags & SF_Recursive ); testcase( pSub->selFlags & SF_MinMaxAgg ); if( pSub->selFlags & (SF_Recursive|SF_MinMaxAgg) ){ return 0; /* Restrictions (22) and (24) */ } if( (p->selFlags & SF_Recursive) && pSub->pPrior ){ return 0; /* Restriction (23) */ } /* OBSOLETE COMMENT 1: ** Restriction 3: If the subquery is a join, make sure the subquery is ** not used as the right operand of an outer join. Examples of why this ** is not allowed: ** ** t1 LEFT OUTER JOIN (t2 JOIN t3) ** ** If we flatten the above, we would get ** ** (t1 LEFT OUTER JOIN t2) JOIN t3 ** ** which is not at all the same thing. ** ** OBSOLETE COMMENT 2: ** Restriction 12: If the subquery is the right operand of a left outer ** join, make sure the subquery has no WHERE clause. ** An examples of why this is not allowed: ** ** t1 LEFT OUTER JOIN (SELECT * FROM t2 WHERE t2.x>0) ** ** If we flatten the above, we would get ** ** (t1 LEFT OUTER JOIN t2) WHERE t2.x>0 ** ** But the t2.x>0 test will always fail on a NULL row of t2, which ** effectively converts the OUTER JOIN into an INNER JOIN. ** ** THIS OVERRIDES OBSOLETE COMMENTS 1 AND 2 ABOVE: ** Ticket #3300 shows that flattening the right term of a LEFT JOIN ** is fraught with danger. Best to avoid the whole thing. If the ** subquery is the right term of a LEFT JOIN, then do not flatten. */ if( (pSubitem->fg.jointype & JT_OUTER)!=0 ){ return 0; } /* Restriction 17: If the sub-query is a compound SELECT, then it must ** use only the UNION ALL operator. And none of the simple select queries ** that make up the compound SELECT are allowed to be aggregate or distinct ** queries. */ if( pSub->pPrior ){ if( pSub->pOrderBy ){ return 0; /* Restriction 20 */ } if( isAgg || (p->selFlags & SF_Distinct)!=0 || pSrc->nSrc!=1 ){ return 0; } for(pSub1=pSub; pSub1; pSub1=pSub1->pPrior){ testcase( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct ); testcase( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))==SF_Aggregate ); assert( pSub->pSrc!=0 ); assert( pSub->pEList->nExpr==pSub1->pEList->nExpr ); if( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))!=0 || (pSub1->pPrior && pSub1->op!=TK_ALL) || pSub1->pSrc->nSrc<1 ){ return 0; } testcase( pSub1->pSrc->nSrc>1 ); } /* Restriction 18. */ if( p->pOrderBy ){ int ii; for(ii=0; iipOrderBy->nExpr; ii++){ if( p->pOrderBy->a[ii].u.x.iOrderByCol==0 ) return 0; } } } /***** If we reach this point, flattening is permitted. *****/ SELECTTRACE(1,pParse,p,("flatten %s.%p from term %d\n", pSub->zSelName, pSub, iFrom)); /* Authorize the subquery */ pParse->zAuthContext = pSubitem->zName; TESTONLY(i =) sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0); testcase( i==SQLITE_DENY ); pParse->zAuthContext = zSavedAuthContext; /* If the sub-query is a compound SELECT statement, then (by restrictions ** 17 and 18 above) it must be a UNION ALL and the parent query must ** be of the form: ** ** SELECT FROM () ** ** followed by any ORDER BY, LIMIT and/or OFFSET clauses. This block ** creates N-1 copies of the parent query without any ORDER BY, LIMIT or ** OFFSET clauses and joins them to the left-hand-side of the original ** using UNION ALL operators. In this case N is the number of simple ** select statements in the compound sub-query. ** ** Example: ** ** SELECT a+1 FROM ( ** SELECT x FROM tab ** UNION ALL ** SELECT y FROM tab ** UNION ALL ** SELECT abs(z*2) FROM tab2 ** ) WHERE a!=5 ORDER BY 1 ** ** Transformed into: ** ** SELECT x+1 FROM tab WHERE x+1!=5 ** UNION ALL ** SELECT y+1 FROM tab WHERE y+1!=5 ** UNION ALL ** SELECT abs(z*2)+1 FROM tab2 WHERE abs(z*2)+1!=5 ** ORDER BY 1 ** ** We call this the "compound-subquery flattening". */ for(pSub=pSub->pPrior; pSub; pSub=pSub->pPrior){ Select *pNew; ExprList *pOrderBy = p->pOrderBy; Expr *pLimit = p->pLimit; Expr *pOffset = p->pOffset; Select *pPrior = p->pPrior; p->pOrderBy = 0; p->pSrc = 0; p->pPrior = 0; p->pLimit = 0; p->pOffset = 0; pNew = sqlite3SelectDup(db, p, 0); sqlite3SelectSetName(pNew, pSub->zSelName); p->pOffset = pOffset; p->pLimit = pLimit; p->pOrderBy = pOrderBy; p->pSrc = pSrc; p->op = TK_ALL; if( pNew==0 ){ p->pPrior = pPrior; }else{ pNew->pPrior = pPrior; if( pPrior ) pPrior->pNext = pNew; pNew->pNext = p; p->pPrior = pNew; SELECTTRACE(2,pParse,p, ("compound-subquery flattener creates %s.%p as peer\n", pNew->zSelName, pNew)); } if( db->mallocFailed ) return 1; } /* Begin flattening the iFrom-th entry of the FROM clause ** in the outer query. */ pSub = pSub1 = pSubitem->pSelect; /* Delete the transient table structure associated with the ** subquery */ sqlite3DbFree(db, pSubitem->zDatabase); sqlite3DbFree(db, pSubitem->zName); sqlite3DbFree(db, pSubitem->zAlias); pSubitem->zDatabase = 0; pSubitem->zName = 0; pSubitem->zAlias = 0; pSubitem->pSelect = 0; /* Defer deleting the Table object associated with the ** subquery until code generation is ** complete, since there may still exist Expr.pTab entries that ** refer to the subquery even after flattening. Ticket #3346. ** ** pSubitem->pTab is always non-NULL by test restrictions and tests above. */ if( ALWAYS(pSubitem->pTab!=0) ){ Table *pTabToDel = pSubitem->pTab; if( pTabToDel->nRef==1 ){ Parse *pToplevel = sqlite3ParseToplevel(pParse); pTabToDel->pNextZombie = pToplevel->pZombieTab; pToplevel->pZombieTab = pTabToDel; }else{ pTabToDel->nRef--; } pSubitem->pTab = 0; } /* The following loop runs once for each term in a compound-subquery ** flattening (as described above). If we are doing a different kind ** of flattening - a flattening other than a compound-subquery flattening - ** then this loop only runs once. ** ** This loop moves all of the FROM elements of the subquery into the ** the FROM clause of the outer query. Before doing this, remember ** the cursor number for the original outer query FROM element in ** iParent. The iParent cursor will never be used. Subsequent code ** will scan expressions looking for iParent references and replace ** those references with expressions that resolve to the subquery FROM ** elements we are now copying in. */ for(pParent=p; pParent; pParent=pParent->pPrior, pSub=pSub->pPrior){ int nSubSrc; u8 jointype = 0; pSubSrc = pSub->pSrc; /* FROM clause of subquery */ nSubSrc = pSubSrc->nSrc; /* Number of terms in subquery FROM clause */ pSrc = pParent->pSrc; /* FROM clause of the outer query */ if( pSrc ){ assert( pParent==p ); /* First time through the loop */ jointype = pSubitem->fg.jointype; }else{ assert( pParent!=p ); /* 2nd and subsequent times through the loop */ pSrc = pParent->pSrc = sqlite3SrcListAppend(db, 0, 0, 0); if( pSrc==0 ){ assert( db->mallocFailed ); break; } } /* The subquery uses a single slot of the FROM clause of the outer ** query. If the subquery has more than one element in its FROM clause, ** then expand the outer query to make space for it to hold all elements ** of the subquery. ** ** Example: ** ** SELECT * FROM tabA, (SELECT * FROM sub1, sub2), tabB; ** ** The outer query has 3 slots in its FROM clause. One slot of the ** outer query (the middle slot) is used by the subquery. The next ** block of code will expand the outer query FROM clause to 4 slots. ** The middle slot is expanded to two slots in order to make space ** for the two elements in the FROM clause of the subquery. */ if( nSubSrc>1 ){ pParent->pSrc = pSrc = sqlite3SrcListEnlarge(db, pSrc, nSubSrc-1,iFrom+1); if( db->mallocFailed ){ break; } } /* Transfer the FROM clause terms from the subquery into the ** outer query. */ for(i=0; ia[i+iFrom].pUsing); assert( pSrc->a[i+iFrom].fg.isTabFunc==0 ); pSrc->a[i+iFrom] = pSubSrc->a[i]; memset(&pSubSrc->a[i], 0, sizeof(pSubSrc->a[i])); } pSrc->a[iFrom].fg.jointype = jointype; /* Now begin substituting subquery result set expressions for ** references to the iParent in the outer query. ** ** Example: ** ** SELECT a+5, b*10 FROM (SELECT x*3 AS a, y+10 AS b FROM t1) WHERE a>b; ** \ \_____________ subquery __________/ / ** \_____________________ outer query ______________________________/ ** ** We look at every expression in the outer query and every place we see ** "a" we substitute "x*3" and every place we see "b" we substitute "y+10". */ pList = pParent->pEList; for(i=0; inExpr; i++){ if( pList->a[i].zName==0 ){ char *zName = sqlite3DbStrDup(db, pList->a[i].zSpan); sqlite3Dequote(zName); pList->a[i].zName = zName; } } if( pSub->pOrderBy ){ /* At this point, any non-zero iOrderByCol values indicate that the ** ORDER BY column expression is identical to the iOrderByCol'th ** expression returned by SELECT statement pSub. Since these values ** do not necessarily correspond to columns in SELECT statement pParent, ** zero them before transfering the ORDER BY clause. ** ** Not doing this may cause an error if a subsequent call to this ** function attempts to flatten a compound sub-query into pParent ** (the only way this can happen is if the compound sub-query is ** currently part of pSub->pSrc). See ticket [d11a6e908f]. */ ExprList *pOrderBy = pSub->pOrderBy; for(i=0; inExpr; i++){ pOrderBy->a[i].u.x.iOrderByCol = 0; } assert( pParent->pOrderBy==0 ); assert( pSub->pPrior==0 ); pParent->pOrderBy = pOrderBy; pSub->pOrderBy = 0; } pWhere = sqlite3ExprDup(db, pSub->pWhere, 0); if( subqueryIsAgg ){ assert( pParent->pHaving==0 ); pParent->pHaving = pParent->pWhere; pParent->pWhere = pWhere; pParent->pHaving = sqlite3ExprAnd(db, sqlite3ExprDup(db, pSub->pHaving, 0), pParent->pHaving ); assert( pParent->pGroupBy==0 ); pParent->pGroupBy = sqlite3ExprListDup(db, pSub->pGroupBy, 0); }else{ pParent->pWhere = sqlite3ExprAnd(db, pWhere, pParent->pWhere); } substSelect(db, pParent, iParent, pSub->pEList, 0); /* The flattened query is distinct if either the inner or the ** outer query is distinct. */ pParent->selFlags |= pSub->selFlags & SF_Distinct; /* ** SELECT ... FROM (SELECT ... LIMIT a OFFSET b) LIMIT x OFFSET y; ** ** One is tempted to try to add a and b to combine the limits. But this ** does not work if either limit is negative. */ if( pSub->pLimit ){ pParent->pLimit = pSub->pLimit; pSub->pLimit = 0; } } /* Finially, delete what is left of the subquery and return ** success. */ sqlite3SelectDelete(db, pSub1); #if SELECTTRACE_ENABLED if( sqlite3SelectTrace & 0x100 ){ SELECTTRACE(0x100,pParse,p,("After flattening:\n")); sqlite3TreeViewSelect(0, p, 0); } #endif return 1; } #endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */ #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) /* ** Make copies of relevant WHERE clause terms of the outer query into ** the WHERE clause of subquery. Example: ** ** SELECT * FROM (SELECT a AS x, c-d AS y FROM t1) WHERE x=5 AND y=10; ** ** Transformed into: ** ** SELECT * FROM (SELECT a AS x, c-d AS y FROM t1 WHERE a=5 AND c-d=10) ** WHERE x=5 AND y=10; ** ** The hope is that the terms added to the inner query will make it more ** efficient. ** ** Do not attempt this optimization if: ** ** (1) The inner query is an aggregate. (In that case, we'd really want ** to copy the outer WHERE-clause terms onto the HAVING clause of the ** inner query. But they probably won't help there so do not bother.) ** ** (2) The inner query is the recursive part of a common table expression. ** ** (3) The inner query has a LIMIT clause (since the changes to the WHERE ** close would change the meaning of the LIMIT). ** ** (4) The inner query is the right operand of a LEFT JOIN. (The caller ** enforces this restriction since this routine does not have enough ** information to know.) ** ** (5) The WHERE clause expression originates in the ON or USING clause ** of a LEFT JOIN. ** ** Return 0 if no changes are made and non-zero if one or more WHERE clause ** terms are duplicated into the subquery. */ static int pushDownWhereTerms( sqlite3 *db, /* The database connection (for malloc()) */ Select *pSubq, /* The subquery whose WHERE clause is to be augmented */ Expr *pWhere, /* The WHERE clause of the outer query */ int iCursor /* Cursor number of the subquery */ ){ Expr *pNew; int nChng = 0; Select *pX; /* For looping over compound SELECTs in pSubq */ if( pWhere==0 ) return 0; for(pX=pSubq; pX; pX=pX->pPrior){ if( (pX->selFlags & (SF_Aggregate|SF_Recursive))!=0 ){ testcase( pX->selFlags & SF_Aggregate ); testcase( pX->selFlags & SF_Recursive ); testcase( pX!=pSubq ); return 0; /* restrictions (1) and (2) */ } } if( pSubq->pLimit!=0 ){ return 0; /* restriction (3) */ } while( pWhere->op==TK_AND ){ nChng += pushDownWhereTerms(db, pSubq, pWhere->pRight, iCursor); pWhere = pWhere->pLeft; } if( ExprHasProperty(pWhere,EP_FromJoin) ) return 0; /* restriction 5 */ if( sqlite3ExprIsTableConstant(pWhere, iCursor) ){ nChng++; while( pSubq ){ pNew = sqlite3ExprDup(db, pWhere, 0); pNew = substExpr(db, pNew, iCursor, pSubq->pEList); pSubq->pWhere = sqlite3ExprAnd(db, pSubq->pWhere, pNew); pSubq = pSubq->pPrior; } } return nChng; } #endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */ /* ** Based on the contents of the AggInfo structure indicated by the first ** argument, this function checks if the following are true: ** ** * the query contains just a single aggregate function, ** * the aggregate function is either min() or max(), and ** * the argument to the aggregate function is a column value. ** ** If all of the above are true, then WHERE_ORDERBY_MIN or WHERE_ORDERBY_MAX ** is returned as appropriate. Also, *ppMinMax is set to point to the ** list of arguments passed to the aggregate before returning. ** ** Or, if the conditions above are not met, *ppMinMax is set to 0 and ** WHERE_ORDERBY_NORMAL is returned. */ static u8 minMaxQuery(AggInfo *pAggInfo, ExprList **ppMinMax){ int eRet = WHERE_ORDERBY_NORMAL; /* Return value */ *ppMinMax = 0; if( pAggInfo->nFunc==1 ){ Expr *pExpr = pAggInfo->aFunc[0].pExpr; /* Aggregate function */ ExprList *pEList = pExpr->x.pList; /* Arguments to agg function */ assert( pExpr->op==TK_AGG_FUNCTION ); if( pEList && pEList->nExpr==1 && pEList->a[0].pExpr->op==TK_AGG_COLUMN ){ const char *zFunc = pExpr->u.zToken; if( sqlite3StrICmp(zFunc, "min")==0 ){ eRet = WHERE_ORDERBY_MIN; *ppMinMax = pEList; }else if( sqlite3StrICmp(zFunc, "max")==0 ){ eRet = WHERE_ORDERBY_MAX; *ppMinMax = pEList; } } } assert( *ppMinMax==0 || (*ppMinMax)->nExpr==1 ); return eRet; } /* ** The select statement passed as the first argument is an aggregate query. ** The second argument is the associated aggregate-info object. This ** function tests if the SELECT is of the form: ** ** SELECT count(*) FROM ** ** where table is a database table, not a sub-select or view. If the query ** does match this pattern, then a pointer to the Table object representing ** is returned. Otherwise, 0 is returned. */ static Table *isSimpleCount(Select *p, AggInfo *pAggInfo){ Table *pTab; Expr *pExpr; assert( !p->pGroupBy ); if( p->pWhere || p->pEList->nExpr!=1 || p->pSrc->nSrc!=1 || p->pSrc->a[0].pSelect ){ return 0; } pTab = p->pSrc->a[0].pTab; pExpr = p->pEList->a[0].pExpr; assert( pTab && !pTab->pSelect && pExpr ); if( IsVirtual(pTab) ) return 0; if( pExpr->op!=TK_AGG_FUNCTION ) return 0; if( NEVER(pAggInfo->nFunc==0) ) return 0; if( (pAggInfo->aFunc[0].pFunc->funcFlags&SQLITE_FUNC_COUNT)==0 ) return 0; if( pExpr->flags&EP_Distinct ) return 0; return pTab; } /* ** If the source-list item passed as an argument was augmented with an ** INDEXED BY clause, then try to locate the specified index. If there ** was such a clause and the named index cannot be found, return ** SQLITE_ERROR and leave an error in pParse. Otherwise, populate ** pFrom->pIndex and return SQLITE_OK. */ SQLITE_PRIVATE int sqlite3IndexedByLookup(Parse *pParse, struct SrcList_item *pFrom){ if( pFrom->pTab && pFrom->fg.isIndexedBy ){ Table *pTab = pFrom->pTab; char *zIndexedBy = pFrom->u1.zIndexedBy; Index *pIdx; for(pIdx=pTab->pIndex; pIdx && sqlite3StrICmp(pIdx->zName, zIndexedBy); pIdx=pIdx->pNext ); if( !pIdx ){ sqlite3ErrorMsg(pParse, "no such index: %s", zIndexedBy, 0); pParse->checkSchema = 1; return SQLITE_ERROR; } pFrom->pIBIndex = pIdx; } return SQLITE_OK; } /* ** Detect compound SELECT statements that use an ORDER BY clause with ** an alternative collating sequence. ** ** SELECT ... FROM t1 EXCEPT SELECT ... FROM t2 ORDER BY .. COLLATE ... ** ** These are rewritten as a subquery: ** ** SELECT * FROM (SELECT ... FROM t1 EXCEPT SELECT ... FROM t2) ** ORDER BY ... COLLATE ... ** ** This transformation is necessary because the multiSelectOrderBy() routine ** above that generates the code for a compound SELECT with an ORDER BY clause ** uses a merge algorithm that requires the same collating sequence on the ** result columns as on the ORDER BY clause. See ticket ** http://www.sqlite.org/src/info/6709574d2a ** ** This transformation is only needed for EXCEPT, INTERSECT, and UNION. ** The UNION ALL operator works fine with multiSelectOrderBy() even when ** there are COLLATE terms in the ORDER BY. */ static int convertCompoundSelectToSubquery(Walker *pWalker, Select *p){ int i; Select *pNew; Select *pX; sqlite3 *db; struct ExprList_item *a; SrcList *pNewSrc; Parse *pParse; Token dummy; if( p->pPrior==0 ) return WRC_Continue; if( p->pOrderBy==0 ) return WRC_Continue; for(pX=p; pX && (pX->op==TK_ALL || pX->op==TK_SELECT); pX=pX->pPrior){} if( pX==0 ) return WRC_Continue; a = p->pOrderBy->a; for(i=p->pOrderBy->nExpr-1; i>=0; i--){ if( a[i].pExpr->flags & EP_Collate ) break; } if( i<0 ) return WRC_Continue; /* If we reach this point, that means the transformation is required. */ pParse = pWalker->pParse; db = pParse->db; pNew = sqlite3DbMallocZero(db, sizeof(*pNew) ); if( pNew==0 ) return WRC_Abort; memset(&dummy, 0, sizeof(dummy)); pNewSrc = sqlite3SrcListAppendFromTerm(pParse,0,0,0,&dummy,pNew,0,0); if( pNewSrc==0 ) return WRC_Abort; *pNew = *p; p->pSrc = pNewSrc; p->pEList = sqlite3ExprListAppend(pParse, 0, sqlite3Expr(db, TK_ASTERISK, 0)); p->op = TK_SELECT; p->pWhere = 0; pNew->pGroupBy = 0; pNew->pHaving = 0; pNew->pOrderBy = 0; p->pPrior = 0; p->pNext = 0; p->pWith = 0; p->selFlags &= ~SF_Compound; assert( (p->selFlags & SF_Converted)==0 ); p->selFlags |= SF_Converted; assert( pNew->pPrior!=0 ); pNew->pPrior->pNext = pNew; pNew->pLimit = 0; pNew->pOffset = 0; return WRC_Continue; } /* ** Check to see if the FROM clause term pFrom has table-valued function ** arguments. If it does, leave an error message in pParse and return ** non-zero, since pFrom is not allowed to be a table-valued function. */ static int cannotBeFunction(Parse *pParse, struct SrcList_item *pFrom){ if( pFrom->fg.isTabFunc ){ sqlite3ErrorMsg(pParse, "'%s' is not a function", pFrom->zName); return 1; } return 0; } #ifndef SQLITE_OMIT_CTE /* ** Argument pWith (which may be NULL) points to a linked list of nested ** WITH contexts, from inner to outermost. If the table identified by ** FROM clause element pItem is really a common-table-expression (CTE) ** then return a pointer to the CTE definition for that table. Otherwise ** return NULL. ** ** If a non-NULL value is returned, set *ppContext to point to the With ** object that the returned CTE belongs to. */ static struct Cte *searchWith( With *pWith, /* Current innermost WITH clause */ struct SrcList_item *pItem, /* FROM clause element to resolve */ With **ppContext /* OUT: WITH clause return value belongs to */ ){ const char *zName; if( pItem->zDatabase==0 && (zName = pItem->zName)!=0 ){ With *p; for(p=pWith; p; p=p->pOuter){ int i; for(i=0; inCte; i++){ if( sqlite3StrICmp(zName, p->a[i].zName)==0 ){ *ppContext = p; return &p->a[i]; } } } } return 0; } /* The code generator maintains a stack of active WITH clauses ** with the inner-most WITH clause being at the top of the stack. ** ** This routine pushes the WITH clause passed as the second argument ** onto the top of the stack. If argument bFree is true, then this ** WITH clause will never be popped from the stack. In this case it ** should be freed along with the Parse object. In other cases, when ** bFree==0, the With object will be freed along with the SELECT ** statement with which it is associated. */ SQLITE_PRIVATE void sqlite3WithPush(Parse *pParse, With *pWith, u8 bFree){ assert( bFree==0 || (pParse->pWith==0 && pParse->pWithToFree==0) ); if( pWith ){ assert( pParse->pWith!=pWith ); pWith->pOuter = pParse->pWith; pParse->pWith = pWith; if( bFree ) pParse->pWithToFree = pWith; } } /* ** This function checks if argument pFrom refers to a CTE declared by ** a WITH clause on the stack currently maintained by the parser. And, ** if currently processing a CTE expression, if it is a recursive ** reference to the current CTE. ** ** If pFrom falls into either of the two categories above, pFrom->pTab ** and other fields are populated accordingly. The caller should check ** (pFrom->pTab!=0) to determine whether or not a successful match ** was found. ** ** Whether or not a match is found, SQLITE_OK is returned if no error ** occurs. If an error does occur, an error message is stored in the ** parser and some error code other than SQLITE_OK returned. */ static int withExpand( Walker *pWalker, struct SrcList_item *pFrom ){ Parse *pParse = pWalker->pParse; sqlite3 *db = pParse->db; struct Cte *pCte; /* Matched CTE (or NULL if no match) */ With *pWith; /* WITH clause that pCte belongs to */ assert( pFrom->pTab==0 ); pCte = searchWith(pParse->pWith, pFrom, &pWith); if( pCte ){ Table *pTab; ExprList *pEList; Select *pSel; Select *pLeft; /* Left-most SELECT statement */ int bMayRecursive; /* True if compound joined by UNION [ALL] */ With *pSavedWith; /* Initial value of pParse->pWith */ /* If pCte->zCteErr is non-NULL at this point, then this is an illegal ** recursive reference to CTE pCte. Leave an error in pParse and return ** early. If pCte->zCteErr is NULL, then this is not a recursive reference. ** In this case, proceed. */ if( pCte->zCteErr ){ sqlite3ErrorMsg(pParse, pCte->zCteErr, pCte->zName); return SQLITE_ERROR; } if( cannotBeFunction(pParse, pFrom) ) return SQLITE_ERROR; assert( pFrom->pTab==0 ); pFrom->pTab = pTab = sqlite3DbMallocZero(db, sizeof(Table)); if( pTab==0 ) return WRC_Abort; pTab->nRef = 1; pTab->zName = sqlite3DbStrDup(db, pCte->zName); pTab->iPKey = -1; pTab->nRowLogEst = 200; assert( 200==sqlite3LogEst(1048576) ); pTab->tabFlags |= TF_Ephemeral | TF_NoVisibleRowid; pFrom->pSelect = sqlite3SelectDup(db, pCte->pSelect, 0); if( db->mallocFailed ) return SQLITE_NOMEM_BKPT; assert( pFrom->pSelect ); /* Check if this is a recursive CTE. */ pSel = pFrom->pSelect; bMayRecursive = ( pSel->op==TK_ALL || pSel->op==TK_UNION ); if( bMayRecursive ){ int i; SrcList *pSrc = pFrom->pSelect->pSrc; for(i=0; inSrc; i++){ struct SrcList_item *pItem = &pSrc->a[i]; if( pItem->zDatabase==0 && pItem->zName!=0 && 0==sqlite3StrICmp(pItem->zName, pCte->zName) ){ pItem->pTab = pTab; pItem->fg.isRecursive = 1; pTab->nRef++; pSel->selFlags |= SF_Recursive; } } } /* Only one recursive reference is permitted. */ if( pTab->nRef>2 ){ sqlite3ErrorMsg( pParse, "multiple references to recursive table: %s", pCte->zName ); return SQLITE_ERROR; } assert( pTab->nRef==1 || ((pSel->selFlags&SF_Recursive) && pTab->nRef==2 )); pCte->zCteErr = "circular reference: %s"; pSavedWith = pParse->pWith; pParse->pWith = pWith; sqlite3WalkSelect(pWalker, bMayRecursive ? pSel->pPrior : pSel); pParse->pWith = pWith; for(pLeft=pSel; pLeft->pPrior; pLeft=pLeft->pPrior); pEList = pLeft->pEList; if( pCte->pCols ){ if( pEList && pEList->nExpr!=pCte->pCols->nExpr ){ sqlite3ErrorMsg(pParse, "table %s has %d values for %d columns", pCte->zName, pEList->nExpr, pCte->pCols->nExpr ); pParse->pWith = pSavedWith; return SQLITE_ERROR; } pEList = pCte->pCols; } sqlite3ColumnsFromExprList(pParse, pEList, &pTab->nCol, &pTab->aCol); if( bMayRecursive ){ if( pSel->selFlags & SF_Recursive ){ pCte->zCteErr = "multiple recursive references: %s"; }else{ pCte->zCteErr = "recursive reference in a subquery: %s"; } sqlite3WalkSelect(pWalker, pSel); } pCte->zCteErr = 0; pParse->pWith = pSavedWith; } return SQLITE_OK; } #endif #ifndef SQLITE_OMIT_CTE /* ** If the SELECT passed as the second argument has an associated WITH ** clause, pop it from the stack stored as part of the Parse object. ** ** This function is used as the xSelectCallback2() callback by ** sqlite3SelectExpand() when walking a SELECT tree to resolve table ** names and other FROM clause elements. */ static void selectPopWith(Walker *pWalker, Select *p){ Parse *pParse = pWalker->pParse; With *pWith = findRightmost(p)->pWith; if( pWith!=0 ){ assert( pParse->pWith==pWith ); pParse->pWith = pWith->pOuter; } } #else #define selectPopWith 0 #endif /* ** This routine is a Walker callback for "expanding" a SELECT statement. ** "Expanding" means to do the following: ** ** (1) Make sure VDBE cursor numbers have been assigned to every ** element of the FROM clause. ** ** (2) Fill in the pTabList->a[].pTab fields in the SrcList that ** defines FROM clause. When views appear in the FROM clause, ** fill pTabList->a[].pSelect with a copy of the SELECT statement ** that implements the view. A copy is made of the view's SELECT ** statement so that we can freely modify or delete that statement ** without worrying about messing up the persistent representation ** of the view. ** ** (3) Add terms to the WHERE clause to accommodate the NATURAL keyword ** on joins and the ON and USING clause of joins. ** ** (4) Scan the list of columns in the result set (pEList) looking ** for instances of the "*" operator or the TABLE.* operator. ** If found, expand each "*" to be every column in every table ** and TABLE.* to be every column in TABLE. ** */ static int selectExpander(Walker *pWalker, Select *p){ Parse *pParse = pWalker->pParse; int i, j, k; SrcList *pTabList; ExprList *pEList; struct SrcList_item *pFrom; sqlite3 *db = pParse->db; Expr *pE, *pRight, *pExpr; u16 selFlags = p->selFlags; p->selFlags |= SF_Expanded; if( db->mallocFailed ){ return WRC_Abort; } if( NEVER(p->pSrc==0) || (selFlags & SF_Expanded)!=0 ){ return WRC_Prune; } pTabList = p->pSrc; pEList = p->pEList; if( pWalker->xSelectCallback2==selectPopWith ){ sqlite3WithPush(pParse, findRightmost(p)->pWith, 0); } /* Make sure cursor numbers have been assigned to all entries in ** the FROM clause of the SELECT statement. */ sqlite3SrcListAssignCursors(pParse, pTabList); /* Look up every table named in the FROM clause of the select. If ** an entry of the FROM clause is a subquery instead of a table or view, ** then create a transient table structure to describe the subquery. */ for(i=0, pFrom=pTabList->a; inSrc; i++, pFrom++){ Table *pTab; assert( pFrom->fg.isRecursive==0 || pFrom->pTab!=0 ); if( pFrom->fg.isRecursive ) continue; assert( pFrom->pTab==0 ); #ifndef SQLITE_OMIT_CTE if( withExpand(pWalker, pFrom) ) return WRC_Abort; if( pFrom->pTab ) {} else #endif if( pFrom->zName==0 ){ #ifndef SQLITE_OMIT_SUBQUERY Select *pSel = pFrom->pSelect; /* A sub-query in the FROM clause of a SELECT */ assert( pSel!=0 ); assert( pFrom->pTab==0 ); if( sqlite3WalkSelect(pWalker, pSel) ) return WRC_Abort; pFrom->pTab = pTab = sqlite3DbMallocZero(db, sizeof(Table)); if( pTab==0 ) return WRC_Abort; pTab->nRef = 1; pTab->zName = sqlite3MPrintf(db, "sqlite_sq_%p", (void*)pTab); while( pSel->pPrior ){ pSel = pSel->pPrior; } sqlite3ColumnsFromExprList(pParse, pSel->pEList,&pTab->nCol,&pTab->aCol); pTab->iPKey = -1; pTab->nRowLogEst = 200; assert( 200==sqlite3LogEst(1048576) ); pTab->tabFlags |= TF_Ephemeral; #endif }else{ /* An ordinary table or view name in the FROM clause */ assert( pFrom->pTab==0 ); pFrom->pTab = pTab = sqlite3LocateTableItem(pParse, 0, pFrom); if( pTab==0 ) return WRC_Abort; if( pTab->nRef==0xffff ){ sqlite3ErrorMsg(pParse, "too many references to \"%s\": max 65535", pTab->zName); pFrom->pTab = 0; return WRC_Abort; } pTab->nRef++; if( !IsVirtual(pTab) && cannotBeFunction(pParse, pFrom) ){ return WRC_Abort; } #if !defined(SQLITE_OMIT_VIEW) || !defined (SQLITE_OMIT_VIRTUALTABLE) if( IsVirtual(pTab) || pTab->pSelect ){ i16 nCol; if( sqlite3ViewGetColumnNames(pParse, pTab) ) return WRC_Abort; assert( pFrom->pSelect==0 ); pFrom->pSelect = sqlite3SelectDup(db, pTab->pSelect, 0); sqlite3SelectSetName(pFrom->pSelect, pTab->zName); nCol = pTab->nCol; pTab->nCol = -1; sqlite3WalkSelect(pWalker, pFrom->pSelect); pTab->nCol = nCol; } #endif } /* Locate the index named by the INDEXED BY clause, if any. */ if( sqlite3IndexedByLookup(pParse, pFrom) ){ return WRC_Abort; } } /* Process NATURAL keywords, and ON and USING clauses of joins. */ if( db->mallocFailed || sqliteProcessJoin(pParse, p) ){ return WRC_Abort; } /* For every "*" that occurs in the column list, insert the names of ** all columns in all tables. And for every TABLE.* insert the names ** of all columns in TABLE. The parser inserted a special expression ** with the TK_ASTERISK operator for each "*" that it found in the column ** list. The following code just has to locate the TK_ASTERISK ** expressions and expand each one to the list of all columns in ** all tables. ** ** The first loop just checks to see if there are any "*" operators ** that need expanding. */ for(k=0; knExpr; k++){ pE = pEList->a[k].pExpr; if( pE->op==TK_ASTERISK ) break; assert( pE->op!=TK_DOT || pE->pRight!=0 ); assert( pE->op!=TK_DOT || (pE->pLeft!=0 && pE->pLeft->op==TK_ID) ); if( pE->op==TK_DOT && pE->pRight->op==TK_ASTERISK ) break; } if( knExpr ){ /* ** If we get here it means the result set contains one or more "*" ** operators that need to be expanded. Loop through each expression ** in the result set and expand them one by one. */ struct ExprList_item *a = pEList->a; ExprList *pNew = 0; int flags = pParse->db->flags; int longNames = (flags & SQLITE_FullColNames)!=0 && (flags & SQLITE_ShortColNames)==0; for(k=0; knExpr; k++){ pE = a[k].pExpr; pRight = pE->pRight; assert( pE->op!=TK_DOT || pRight!=0 ); if( pE->op!=TK_ASTERISK && (pE->op!=TK_DOT || pRight->op!=TK_ASTERISK) ){ /* This particular expression does not need to be expanded. */ pNew = sqlite3ExprListAppend(pParse, pNew, a[k].pExpr); if( pNew ){ pNew->a[pNew->nExpr-1].zName = a[k].zName; pNew->a[pNew->nExpr-1].zSpan = a[k].zSpan; a[k].zName = 0; a[k].zSpan = 0; } a[k].pExpr = 0; }else{ /* This expression is a "*" or a "TABLE.*" and needs to be ** expanded. */ int tableSeen = 0; /* Set to 1 when TABLE matches */ char *zTName = 0; /* text of name of TABLE */ if( pE->op==TK_DOT ){ assert( pE->pLeft!=0 ); assert( !ExprHasProperty(pE->pLeft, EP_IntValue) ); zTName = pE->pLeft->u.zToken; } for(i=0, pFrom=pTabList->a; inSrc; i++, pFrom++){ Table *pTab = pFrom->pTab; Select *pSub = pFrom->pSelect; char *zTabName = pFrom->zAlias; const char *zSchemaName = 0; int iDb; if( zTabName==0 ){ zTabName = pTab->zName; } if( db->mallocFailed ) break; if( pSub==0 || (pSub->selFlags & SF_NestedFrom)==0 ){ pSub = 0; if( zTName && sqlite3StrICmp(zTName, zTabName)!=0 ){ continue; } iDb = sqlite3SchemaToIndex(db, pTab->pSchema); zSchemaName = iDb>=0 ? db->aDb[iDb].zDbSName : "*"; } for(j=0; jnCol; j++){ char *zName = pTab->aCol[j].zName; char *zColname; /* The computed column name */ char *zToFree; /* Malloced string that needs to be freed */ Token sColname; /* Computed column name as a token */ assert( zName ); if( zTName && pSub && sqlite3MatchSpanName(pSub->pEList->a[j].zSpan, 0, zTName, 0)==0 ){ continue; } /* If a column is marked as 'hidden', omit it from the expanded ** result-set list unless the SELECT has the SF_IncludeHidden ** bit set. */ if( (p->selFlags & SF_IncludeHidden)==0 && IsHiddenColumn(&pTab->aCol[j]) ){ continue; } tableSeen = 1; if( i>0 && zTName==0 ){ if( (pFrom->fg.jointype & JT_NATURAL)!=0 && tableAndColumnIndex(pTabList, i, zName, 0, 0) ){ /* In a NATURAL join, omit the join columns from the ** table to the right of the join */ continue; } if( sqlite3IdListIndex(pFrom->pUsing, zName)>=0 ){ /* In a join with a USING clause, omit columns in the ** using clause from the table on the right. */ continue; } } pRight = sqlite3Expr(db, TK_ID, zName); zColname = zName; zToFree = 0; if( longNames || pTabList->nSrc>1 ){ Expr *pLeft; pLeft = sqlite3Expr(db, TK_ID, zTabName); pExpr = sqlite3PExpr(pParse, TK_DOT, pLeft, pRight, 0); if( zSchemaName ){ pLeft = sqlite3Expr(db, TK_ID, zSchemaName); pExpr = sqlite3PExpr(pParse, TK_DOT, pLeft, pExpr, 0); } if( longNames ){ zColname = sqlite3MPrintf(db, "%s.%s", zTabName, zName); zToFree = zColname; } }else{ pExpr = pRight; } pNew = sqlite3ExprListAppend(pParse, pNew, pExpr); sqlite3TokenInit(&sColname, zColname); sqlite3ExprListSetName(pParse, pNew, &sColname, 0); if( pNew && (p->selFlags & SF_NestedFrom)!=0 ){ struct ExprList_item *pX = &pNew->a[pNew->nExpr-1]; if( pSub ){ pX->zSpan = sqlite3DbStrDup(db, pSub->pEList->a[j].zSpan); testcase( pX->zSpan==0 ); }else{ pX->zSpan = sqlite3MPrintf(db, "%s.%s.%s", zSchemaName, zTabName, zColname); testcase( pX->zSpan==0 ); } pX->bSpanIsTab = 1; } sqlite3DbFree(db, zToFree); } } if( !tableSeen ){ if( zTName ){ sqlite3ErrorMsg(pParse, "no such table: %s", zTName); }else{ sqlite3ErrorMsg(pParse, "no tables specified"); } } } } sqlite3ExprListDelete(db, pEList); p->pEList = pNew; } #if SQLITE_MAX_COLUMN if( p->pEList && p->pEList->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){ sqlite3ErrorMsg(pParse, "too many columns in result set"); return WRC_Abort; } #endif return WRC_Continue; } /* ** No-op routine for the parse-tree walker. ** ** When this routine is the Walker.xExprCallback then expression trees ** are walked without any actions being taken at each node. Presumably, ** when this routine is used for Walker.xExprCallback then ** Walker.xSelectCallback is set to do something useful for every ** subquery in the parser tree. */ SQLITE_PRIVATE int sqlite3ExprWalkNoop(Walker *NotUsed, Expr *NotUsed2){ UNUSED_PARAMETER2(NotUsed, NotUsed2); return WRC_Continue; } /* ** This routine "expands" a SELECT statement and all of its subqueries. ** For additional information on what it means to "expand" a SELECT ** statement, see the comment on the selectExpand worker callback above. ** ** Expanding a SELECT statement is the first step in processing a ** SELECT statement. The SELECT statement must be expanded before ** name resolution is performed. ** ** If anything goes wrong, an error message is written into pParse. ** The calling function can detect the problem by looking at pParse->nErr ** and/or pParse->db->mallocFailed. */ static void sqlite3SelectExpand(Parse *pParse, Select *pSelect){ Walker w; memset(&w, 0, sizeof(w)); w.xExprCallback = sqlite3ExprWalkNoop; w.pParse = pParse; if( pParse->hasCompound ){ w.xSelectCallback = convertCompoundSelectToSubquery; sqlite3WalkSelect(&w, pSelect); } w.xSelectCallback = selectExpander; if( (pSelect->selFlags & SF_MultiValue)==0 ){ w.xSelectCallback2 = selectPopWith; } sqlite3WalkSelect(&w, pSelect); } #ifndef SQLITE_OMIT_SUBQUERY /* ** This is a Walker.xSelectCallback callback for the sqlite3SelectTypeInfo() ** interface. ** ** For each FROM-clause subquery, add Column.zType and Column.zColl ** information to the Table structure that represents the result set ** of that subquery. ** ** The Table structure that represents the result set was constructed ** by selectExpander() but the type and collation information was omitted ** at that point because identifiers had not yet been resolved. This ** routine is called after identifier resolution. */ static void selectAddSubqueryTypeInfo(Walker *pWalker, Select *p){ Parse *pParse; int i; SrcList *pTabList; struct SrcList_item *pFrom; assert( p->selFlags & SF_Resolved ); assert( (p->selFlags & SF_HasTypeInfo)==0 ); p->selFlags |= SF_HasTypeInfo; pParse = pWalker->pParse; pTabList = p->pSrc; for(i=0, pFrom=pTabList->a; inSrc; i++, pFrom++){ Table *pTab = pFrom->pTab; assert( pTab!=0 ); if( (pTab->tabFlags & TF_Ephemeral)!=0 ){ /* A sub-query in the FROM clause of a SELECT */ Select *pSel = pFrom->pSelect; if( pSel ){ while( pSel->pPrior ) pSel = pSel->pPrior; sqlite3SelectAddColumnTypeAndCollation(pParse, pTab, pSel); } } } } #endif /* ** This routine adds datatype and collating sequence information to ** the Table structures of all FROM-clause subqueries in a ** SELECT statement. ** ** Use this routine after name resolution. */ static void sqlite3SelectAddTypeInfo(Parse *pParse, Select *pSelect){ #ifndef SQLITE_OMIT_SUBQUERY Walker w; memset(&w, 0, sizeof(w)); w.xSelectCallback2 = selectAddSubqueryTypeInfo; w.xExprCallback = sqlite3ExprWalkNoop; w.pParse = pParse; sqlite3WalkSelect(&w, pSelect); #endif } /* ** This routine sets up a SELECT statement for processing. The ** following is accomplished: ** ** * VDBE Cursor numbers are assigned to all FROM-clause terms. ** * Ephemeral Table objects are created for all FROM-clause subqueries. ** * ON and USING clauses are shifted into WHERE statements ** * Wildcards "*" and "TABLE.*" in result sets are expanded. ** * Identifiers in expression are matched to tables. ** ** This routine acts recursively on all subqueries within the SELECT. */ SQLITE_PRIVATE void sqlite3SelectPrep( Parse *pParse, /* The parser context */ Select *p, /* The SELECT statement being coded. */ NameContext *pOuterNC /* Name context for container */ ){ sqlite3 *db; if( NEVER(p==0) ) return; db = pParse->db; if( db->mallocFailed ) return; if( p->selFlags & SF_HasTypeInfo ) return; sqlite3SelectExpand(pParse, p); if( pParse->nErr || db->mallocFailed ) return; sqlite3ResolveSelectNames(pParse, p, pOuterNC); if( pParse->nErr || db->mallocFailed ) return; sqlite3SelectAddTypeInfo(pParse, p); } /* ** Reset the aggregate accumulator. ** ** The aggregate accumulator is a set of memory cells that hold ** intermediate results while calculating an aggregate. This ** routine generates code that stores NULLs in all of those memory ** cells. */ static void resetAccumulator(Parse *pParse, AggInfo *pAggInfo){ Vdbe *v = pParse->pVdbe; int i; struct AggInfo_func *pFunc; int nReg = pAggInfo->nFunc + pAggInfo->nColumn; if( nReg==0 ) return; #ifdef SQLITE_DEBUG /* Verify that all AggInfo registers are within the range specified by ** AggInfo.mnReg..AggInfo.mxReg */ assert( nReg==pAggInfo->mxReg-pAggInfo->mnReg+1 ); for(i=0; inColumn; i++){ assert( pAggInfo->aCol[i].iMem>=pAggInfo->mnReg && pAggInfo->aCol[i].iMem<=pAggInfo->mxReg ); } for(i=0; inFunc; i++){ assert( pAggInfo->aFunc[i].iMem>=pAggInfo->mnReg && pAggInfo->aFunc[i].iMem<=pAggInfo->mxReg ); } #endif sqlite3VdbeAddOp3(v, OP_Null, 0, pAggInfo->mnReg, pAggInfo->mxReg); for(pFunc=pAggInfo->aFunc, i=0; inFunc; i++, pFunc++){ if( pFunc->iDistinct>=0 ){ Expr *pE = pFunc->pExpr; assert( !ExprHasProperty(pE, EP_xIsSelect) ); if( pE->x.pList==0 || pE->x.pList->nExpr!=1 ){ sqlite3ErrorMsg(pParse, "DISTINCT aggregates must have exactly one " "argument"); pFunc->iDistinct = -1; }else{ KeyInfo *pKeyInfo = keyInfoFromExprList(pParse, pE->x.pList, 0, 0); sqlite3VdbeAddOp4(v, OP_OpenEphemeral, pFunc->iDistinct, 0, 0, (char*)pKeyInfo, P4_KEYINFO); } } } } /* ** Invoke the OP_AggFinalize opcode for every aggregate function ** in the AggInfo structure. */ static void finalizeAggFunctions(Parse *pParse, AggInfo *pAggInfo){ Vdbe *v = pParse->pVdbe; int i; struct AggInfo_func *pF; for(i=0, pF=pAggInfo->aFunc; inFunc; i++, pF++){ ExprList *pList = pF->pExpr->x.pList; assert( !ExprHasProperty(pF->pExpr, EP_xIsSelect) ); sqlite3VdbeAddOp4(v, OP_AggFinal, pF->iMem, pList ? pList->nExpr : 0, 0, (void*)pF->pFunc, P4_FUNCDEF); } } /* ** Update the accumulator memory cells for an aggregate based on ** the current cursor position. */ static void updateAccumulator(Parse *pParse, AggInfo *pAggInfo){ Vdbe *v = pParse->pVdbe; int i; int regHit = 0; int addrHitTest = 0; struct AggInfo_func *pF; struct AggInfo_col *pC; pAggInfo->directMode = 1; for(i=0, pF=pAggInfo->aFunc; inFunc; i++, pF++){ int nArg; int addrNext = 0; int regAgg; ExprList *pList = pF->pExpr->x.pList; assert( !ExprHasProperty(pF->pExpr, EP_xIsSelect) ); if( pList ){ nArg = pList->nExpr; regAgg = sqlite3GetTempRange(pParse, nArg); sqlite3ExprCodeExprList(pParse, pList, regAgg, 0, SQLITE_ECEL_DUP); }else{ nArg = 0; regAgg = 0; } if( pF->iDistinct>=0 ){ addrNext = sqlite3VdbeMakeLabel(v); testcase( nArg==0 ); /* Error condition */ testcase( nArg>1 ); /* Also an error */ codeDistinct(pParse, pF->iDistinct, addrNext, 1, regAgg); } if( pF->pFunc->funcFlags & SQLITE_FUNC_NEEDCOLL ){ CollSeq *pColl = 0; struct ExprList_item *pItem; int j; assert( pList!=0 ); /* pList!=0 if pF->pFunc has NEEDCOLL */ for(j=0, pItem=pList->a; !pColl && jpExpr); } if( !pColl ){ pColl = pParse->db->pDfltColl; } if( regHit==0 && pAggInfo->nAccumulator ) regHit = ++pParse->nMem; sqlite3VdbeAddOp4(v, OP_CollSeq, regHit, 0, 0, (char *)pColl, P4_COLLSEQ); } sqlite3VdbeAddOp4(v, OP_AggStep0, 0, regAgg, pF->iMem, (void*)pF->pFunc, P4_FUNCDEF); sqlite3VdbeChangeP5(v, (u8)nArg); sqlite3ExprCacheAffinityChange(pParse, regAgg, nArg); sqlite3ReleaseTempRange(pParse, regAgg, nArg); if( addrNext ){ sqlite3VdbeResolveLabel(v, addrNext); sqlite3ExprCacheClear(pParse); } } /* Before populating the accumulator registers, clear the column cache. ** Otherwise, if any of the required column values are already present ** in registers, sqlite3ExprCode() may use OP_SCopy to copy the value ** to pC->iMem. But by the time the value is used, the original register ** may have been used, invalidating the underlying buffer holding the ** text or blob value. See ticket [883034dcb5]. ** ** Another solution would be to change the OP_SCopy used to copy cached ** values to an OP_Copy. */ if( regHit ){ addrHitTest = sqlite3VdbeAddOp1(v, OP_If, regHit); VdbeCoverage(v); } sqlite3ExprCacheClear(pParse); for(i=0, pC=pAggInfo->aCol; inAccumulator; i++, pC++){ sqlite3ExprCode(pParse, pC->pExpr, pC->iMem); } pAggInfo->directMode = 0; sqlite3ExprCacheClear(pParse); if( addrHitTest ){ sqlite3VdbeJumpHere(v, addrHitTest); } } /* ** Add a single OP_Explain instruction to the VDBE to explain a simple ** count(*) query ("SELECT count(*) FROM pTab"). */ #ifndef SQLITE_OMIT_EXPLAIN static void explainSimpleCount( Parse *pParse, /* Parse context */ Table *pTab, /* Table being queried */ Index *pIdx /* Index used to optimize scan, or NULL */ ){ if( pParse->explain==2 ){ int bCover = (pIdx!=0 && (HasRowid(pTab) || !IsPrimaryKeyIndex(pIdx))); char *zEqp = sqlite3MPrintf(pParse->db, "SCAN TABLE %s%s%s", pTab->zName, bCover ? " USING COVERING INDEX " : "", bCover ? pIdx->zName : "" ); sqlite3VdbeAddOp4( pParse->pVdbe, OP_Explain, pParse->iSelectId, 0, 0, zEqp, P4_DYNAMIC ); } } #else # define explainSimpleCount(a,b,c) #endif /* ** Generate code for the SELECT statement given in the p argument. ** ** The results are returned according to the SelectDest structure. ** See comments in sqliteInt.h for further information. ** ** This routine returns the number of errors. If any errors are ** encountered, then an appropriate error message is left in ** pParse->zErrMsg. ** ** This routine does NOT free the Select structure passed in. The ** calling function needs to do that. */ SQLITE_PRIVATE int sqlite3Select( Parse *pParse, /* The parser context */ Select *p, /* The SELECT statement being coded. */ SelectDest *pDest /* What to do with the query results */ ){ int i, j; /* Loop counters */ WhereInfo *pWInfo; /* Return from sqlite3WhereBegin() */ Vdbe *v; /* The virtual machine under construction */ int isAgg; /* True for select lists like "count(*)" */ ExprList *pEList = 0; /* List of columns to extract. */ SrcList *pTabList; /* List of tables to select from */ Expr *pWhere; /* The WHERE clause. May be NULL */ ExprList *pGroupBy; /* The GROUP BY clause. May be NULL */ Expr *pHaving; /* The HAVING clause. May be NULL */ int rc = 1; /* Value to return from this function */ DistinctCtx sDistinct; /* Info on how to code the DISTINCT keyword */ SortCtx sSort; /* Info on how to code the ORDER BY clause */ AggInfo sAggInfo; /* Information used by aggregate queries */ int iEnd; /* Address of the end of the query */ sqlite3 *db; /* The database connection */ #ifndef SQLITE_OMIT_EXPLAIN int iRestoreSelectId = pParse->iSelectId; pParse->iSelectId = pParse->iNextSelectId++; #endif db = pParse->db; if( p==0 || db->mallocFailed || pParse->nErr ){ return 1; } if( sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0) ) return 1; memset(&sAggInfo, 0, sizeof(sAggInfo)); #if SELECTTRACE_ENABLED pParse->nSelectIndent++; SELECTTRACE(1,pParse,p, ("begin processing:\n")); if( sqlite3SelectTrace & 0x100 ){ sqlite3TreeViewSelect(0, p, 0); } #endif assert( p->pOrderBy==0 || pDest->eDest!=SRT_DistFifo ); assert( p->pOrderBy==0 || pDest->eDest!=SRT_Fifo ); assert( p->pOrderBy==0 || pDest->eDest!=SRT_DistQueue ); assert( p->pOrderBy==0 || pDest->eDest!=SRT_Queue ); if( IgnorableOrderby(pDest) ){ assert(pDest->eDest==SRT_Exists || pDest->eDest==SRT_Union || pDest->eDest==SRT_Except || pDest->eDest==SRT_Discard || pDest->eDest==SRT_Queue || pDest->eDest==SRT_DistFifo || pDest->eDest==SRT_DistQueue || pDest->eDest==SRT_Fifo); /* If ORDER BY makes no difference in the output then neither does ** DISTINCT so it can be removed too. */ sqlite3ExprListDelete(db, p->pOrderBy); p->pOrderBy = 0; p->selFlags &= ~SF_Distinct; } sqlite3SelectPrep(pParse, p, 0); memset(&sSort, 0, sizeof(sSort)); sSort.pOrderBy = p->pOrderBy; pTabList = p->pSrc; if( pParse->nErr || db->mallocFailed ){ goto select_end; } assert( p->pEList!=0 ); isAgg = (p->selFlags & SF_Aggregate)!=0; #if SELECTTRACE_ENABLED if( sqlite3SelectTrace & 0x100 ){ SELECTTRACE(0x100,pParse,p, ("after name resolution:\n")); sqlite3TreeViewSelect(0, p, 0); } #endif /* Try to flatten subqueries in the FROM clause up into the main query */ #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) for(i=0; !p->pPrior && inSrc; i++){ struct SrcList_item *pItem = &pTabList->a[i]; Select *pSub = pItem->pSelect; int isAggSub; Table *pTab = pItem->pTab; if( pSub==0 ) continue; /* Catch mismatch in the declared columns of a view and the number of ** columns in the SELECT on the RHS */ if( pTab->nCol!=pSub->pEList->nExpr ){ sqlite3ErrorMsg(pParse, "expected %d columns for '%s' but got %d", pTab->nCol, pTab->zName, pSub->pEList->nExpr); goto select_end; } isAggSub = (pSub->selFlags & SF_Aggregate)!=0; if( flattenSubquery(pParse, p, i, isAgg, isAggSub) ){ /* This subquery can be absorbed into its parent. */ if( isAggSub ){ isAgg = 1; p->selFlags |= SF_Aggregate; } i = -1; } pTabList = p->pSrc; if( db->mallocFailed ) goto select_end; if( !IgnorableOrderby(pDest) ){ sSort.pOrderBy = p->pOrderBy; } } #endif /* Get a pointer the VDBE under construction, allocating a new VDBE if one ** does not already exist */ v = sqlite3GetVdbe(pParse); if( v==0 ) goto select_end; #ifndef SQLITE_OMIT_COMPOUND_SELECT /* Handle compound SELECT statements using the separate multiSelect() ** procedure. */ if( p->pPrior ){ rc = multiSelect(pParse, p, pDest); explainSetInteger(pParse->iSelectId, iRestoreSelectId); #if SELECTTRACE_ENABLED SELECTTRACE(1,pParse,p,("end compound-select processing\n")); pParse->nSelectIndent--; #endif return rc; } #endif /* Generate code for all sub-queries in the FROM clause */ #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) for(i=0; inSrc; i++){ struct SrcList_item *pItem = &pTabList->a[i]; SelectDest dest; Select *pSub = pItem->pSelect; if( pSub==0 ) continue; /* Sometimes the code for a subquery will be generated more than ** once, if the subquery is part of the WHERE clause in a LEFT JOIN, ** for example. In that case, do not regenerate the code to manifest ** a view or the co-routine to implement a view. The first instance ** is sufficient, though the subroutine to manifest the view does need ** to be invoked again. */ if( pItem->addrFillSub ){ if( pItem->fg.viaCoroutine==0 ){ sqlite3VdbeAddOp2(v, OP_Gosub, pItem->regReturn, pItem->addrFillSub); } continue; } /* Increment Parse.nHeight by the height of the largest expression ** tree referred to by this, the parent select. The child select ** may contain expression trees of at most ** (SQLITE_MAX_EXPR_DEPTH-Parse.nHeight) height. This is a bit ** more conservative than necessary, but much easier than enforcing ** an exact limit. */ pParse->nHeight += sqlite3SelectExprHeight(p); /* Make copies of constant WHERE-clause terms in the outer query down ** inside the subquery. This can help the subquery to run more efficiently. */ if( (pItem->fg.jointype & JT_OUTER)==0 && pushDownWhereTerms(db, pSub, p->pWhere, pItem->iCursor) ){ #if SELECTTRACE_ENABLED if( sqlite3SelectTrace & 0x100 ){ SELECTTRACE(0x100,pParse,p,("After WHERE-clause push-down:\n")); sqlite3TreeViewSelect(0, p, 0); } #endif } /* Generate code to implement the subquery ** ** The subquery is implemented as a co-routine if all of these are true: ** (1) The subquery is guaranteed to be the outer loop (so that it ** does not need to be computed more than once) ** (2) The ALL keyword after SELECT is omitted. (Applications are ** allowed to say "SELECT ALL" instead of just "SELECT" to disable ** the use of co-routines.) ** (3) Co-routines are not disabled using sqlite3_test_control() ** with SQLITE_TESTCTRL_OPTIMIZATIONS. ** ** TODO: Are there other reasons beside (1) to use a co-routine ** implementation? */ if( i==0 && (pTabList->nSrc==1 || (pTabList->a[1].fg.jointype&(JT_LEFT|JT_CROSS))!=0) /* (1) */ && (p->selFlags & SF_All)==0 /* (2) */ && OptimizationEnabled(db, SQLITE_SubqCoroutine) /* (3) */ ){ /* Implement a co-routine that will return a single row of the result ** set on each invocation. */ int addrTop = sqlite3VdbeCurrentAddr(v)+1; pItem->regReturn = ++pParse->nMem; sqlite3VdbeAddOp3(v, OP_InitCoroutine, pItem->regReturn, 0, addrTop); VdbeComment((v, "%s", pItem->pTab->zName)); pItem->addrFillSub = addrTop; sqlite3SelectDestInit(&dest, SRT_Coroutine, pItem->regReturn); explainSetInteger(pItem->iSelectId, (u8)pParse->iNextSelectId); sqlite3Select(pParse, pSub, &dest); pItem->pTab->nRowLogEst = pSub->nSelectRow; pItem->fg.viaCoroutine = 1; pItem->regResult = dest.iSdst; sqlite3VdbeEndCoroutine(v, pItem->regReturn); sqlite3VdbeJumpHere(v, addrTop-1); sqlite3ClearTempRegCache(pParse); }else{ /* Generate a subroutine that will fill an ephemeral table with ** the content of this subquery. pItem->addrFillSub will point ** to the address of the generated subroutine. pItem->regReturn ** is a register allocated to hold the subroutine return address */ int topAddr; int onceAddr = 0; int retAddr; assert( pItem->addrFillSub==0 ); pItem->regReturn = ++pParse->nMem; topAddr = sqlite3VdbeAddOp2(v, OP_Integer, 0, pItem->regReturn); pItem->addrFillSub = topAddr+1; if( pItem->fg.isCorrelated==0 ){ /* If the subquery is not correlated and if we are not inside of ** a trigger, then we only need to compute the value of the subquery ** once. */ onceAddr = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v); VdbeComment((v, "materialize \"%s\"", pItem->pTab->zName)); }else{ VdbeNoopComment((v, "materialize \"%s\"", pItem->pTab->zName)); } sqlite3SelectDestInit(&dest, SRT_EphemTab, pItem->iCursor); explainSetInteger(pItem->iSelectId, (u8)pParse->iNextSelectId); sqlite3Select(pParse, pSub, &dest); pItem->pTab->nRowLogEst = pSub->nSelectRow; if( onceAddr ) sqlite3VdbeJumpHere(v, onceAddr); retAddr = sqlite3VdbeAddOp1(v, OP_Return, pItem->regReturn); VdbeComment((v, "end %s", pItem->pTab->zName)); sqlite3VdbeChangeP1(v, topAddr, retAddr); sqlite3ClearTempRegCache(pParse); } if( db->mallocFailed ) goto select_end; pParse->nHeight -= sqlite3SelectExprHeight(p); } #endif /* Various elements of the SELECT copied into local variables for ** convenience */ pEList = p->pEList; pWhere = p->pWhere; pGroupBy = p->pGroupBy; pHaving = p->pHaving; sDistinct.isTnct = (p->selFlags & SF_Distinct)!=0; #if SELECTTRACE_ENABLED if( sqlite3SelectTrace & 0x400 ){ SELECTTRACE(0x400,pParse,p,("After all FROM-clause analysis:\n")); sqlite3TreeViewSelect(0, p, 0); } #endif /* If the query is DISTINCT with an ORDER BY but is not an aggregate, and ** if the select-list is the same as the ORDER BY list, then this query ** can be rewritten as a GROUP BY. In other words, this: ** ** SELECT DISTINCT xyz FROM ... ORDER BY xyz ** ** is transformed to: ** ** SELECT xyz FROM ... GROUP BY xyz ORDER BY xyz ** ** The second form is preferred as a single index (or temp-table) may be ** used for both the ORDER BY and DISTINCT processing. As originally ** written the query must use a temp-table for at least one of the ORDER ** BY and DISTINCT, and an index or separate temp-table for the other. */ if( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct && sqlite3ExprListCompare(sSort.pOrderBy, pEList, -1)==0 ){ p->selFlags &= ~SF_Distinct; pGroupBy = p->pGroupBy = sqlite3ExprListDup(db, pEList, 0); /* Notice that even thought SF_Distinct has been cleared from p->selFlags, ** the sDistinct.isTnct is still set. Hence, isTnct represents the ** original setting of the SF_Distinct flag, not the current setting */ assert( sDistinct.isTnct ); #if SELECTTRACE_ENABLED if( sqlite3SelectTrace & 0x400 ){ SELECTTRACE(0x400,pParse,p,("Transform DISTINCT into GROUP BY:\n")); sqlite3TreeViewSelect(0, p, 0); } #endif } /* If there is an ORDER BY clause, then create an ephemeral index to ** do the sorting. But this sorting ephemeral index might end up ** being unused if the data can be extracted in pre-sorted order. ** If that is the case, then the OP_OpenEphemeral instruction will be ** changed to an OP_Noop once we figure out that the sorting index is ** not needed. The sSort.addrSortIndex variable is used to facilitate ** that change. */ if( sSort.pOrderBy ){ KeyInfo *pKeyInfo; pKeyInfo = keyInfoFromExprList(pParse, sSort.pOrderBy, 0, pEList->nExpr); sSort.iECursor = pParse->nTab++; sSort.addrSortIndex = sqlite3VdbeAddOp4(v, OP_OpenEphemeral, sSort.iECursor, sSort.pOrderBy->nExpr+1+pEList->nExpr, 0, (char*)pKeyInfo, P4_KEYINFO ); }else{ sSort.addrSortIndex = -1; } /* If the output is destined for a temporary table, open that table. */ if( pDest->eDest==SRT_EphemTab ){ sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pDest->iSDParm, pEList->nExpr); } /* Set the limiter. */ iEnd = sqlite3VdbeMakeLabel(v); p->nSelectRow = 320; /* 4 billion rows */ computeLimitRegisters(pParse, p, iEnd); if( p->iLimit==0 && sSort.addrSortIndex>=0 ){ sqlite3VdbeChangeOpcode(v, sSort.addrSortIndex, OP_SorterOpen); sSort.sortFlags |= SORTFLAG_UseSorter; } /* Open an ephemeral index to use for the distinct set. */ if( p->selFlags & SF_Distinct ){ sDistinct.tabTnct = pParse->nTab++; sDistinct.addrTnct = sqlite3VdbeAddOp4(v, OP_OpenEphemeral, sDistinct.tabTnct, 0, 0, (char*)keyInfoFromExprList(pParse, p->pEList,0,0), P4_KEYINFO); sqlite3VdbeChangeP5(v, BTREE_UNORDERED); sDistinct.eTnctType = WHERE_DISTINCT_UNORDERED; }else{ sDistinct.eTnctType = WHERE_DISTINCT_NOOP; } if( !isAgg && pGroupBy==0 ){ /* No aggregate functions and no GROUP BY clause */ u16 wctrlFlags = (sDistinct.isTnct ? WHERE_WANT_DISTINCT : 0); assert( WHERE_USE_LIMIT==SF_FixedLimit ); wctrlFlags |= p->selFlags & SF_FixedLimit; /* Begin the database scan. */ pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, sSort.pOrderBy, p->pEList, wctrlFlags, p->nSelectRow); if( pWInfo==0 ) goto select_end; if( sqlite3WhereOutputRowCount(pWInfo) < p->nSelectRow ){ p->nSelectRow = sqlite3WhereOutputRowCount(pWInfo); } if( sDistinct.isTnct && sqlite3WhereIsDistinct(pWInfo) ){ sDistinct.eTnctType = sqlite3WhereIsDistinct(pWInfo); } if( sSort.pOrderBy ){ sSort.nOBSat = sqlite3WhereIsOrdered(pWInfo); sSort.bOrderedInnerLoop = sqlite3WhereOrderedInnerLoop(pWInfo); if( sSort.nOBSat==sSort.pOrderBy->nExpr ){ sSort.pOrderBy = 0; } } /* If sorting index that was created by a prior OP_OpenEphemeral ** instruction ended up not being needed, then change the OP_OpenEphemeral ** into an OP_Noop. */ if( sSort.addrSortIndex>=0 && sSort.pOrderBy==0 ){ sqlite3VdbeChangeToNoop(v, sSort.addrSortIndex); } /* Use the standard inner loop. */ selectInnerLoop(pParse, p, pEList, -1, &sSort, &sDistinct, pDest, sqlite3WhereContinueLabel(pWInfo), sqlite3WhereBreakLabel(pWInfo)); /* End the database scan loop. */ sqlite3WhereEnd(pWInfo); }else{ /* This case when there exist aggregate functions or a GROUP BY clause ** or both */ NameContext sNC; /* Name context for processing aggregate information */ int iAMem; /* First Mem address for storing current GROUP BY */ int iBMem; /* First Mem address for previous GROUP BY */ int iUseFlag; /* Mem address holding flag indicating that at least ** one row of the input to the aggregator has been ** processed */ int iAbortFlag; /* Mem address which causes query abort if positive */ int groupBySort; /* Rows come from source in GROUP BY order */ int addrEnd; /* End of processing for this SELECT */ int sortPTab = 0; /* Pseudotable used to decode sorting results */ int sortOut = 0; /* Output register from the sorter */ int orderByGrp = 0; /* True if the GROUP BY and ORDER BY are the same */ /* Remove any and all aliases between the result set and the ** GROUP BY clause. */ if( pGroupBy ){ int k; /* Loop counter */ struct ExprList_item *pItem; /* For looping over expression in a list */ for(k=p->pEList->nExpr, pItem=p->pEList->a; k>0; k--, pItem++){ pItem->u.x.iAlias = 0; } for(k=pGroupBy->nExpr, pItem=pGroupBy->a; k>0; k--, pItem++){ pItem->u.x.iAlias = 0; } assert( 66==sqlite3LogEst(100) ); if( p->nSelectRow>66 ) p->nSelectRow = 66; }else{ assert( 0==sqlite3LogEst(1) ); p->nSelectRow = 0; } /* If there is both a GROUP BY and an ORDER BY clause and they are ** identical, then it may be possible to disable the ORDER BY clause ** on the grounds that the GROUP BY will cause elements to come out ** in the correct order. It also may not - the GROUP BY might use a ** database index that causes rows to be grouped together as required ** but not actually sorted. Either way, record the fact that the ** ORDER BY and GROUP BY clauses are the same by setting the orderByGrp ** variable. */ if( sqlite3ExprListCompare(pGroupBy, sSort.pOrderBy, -1)==0 ){ orderByGrp = 1; } /* Create a label to jump to when we want to abort the query */ addrEnd = sqlite3VdbeMakeLabel(v); /* Convert TK_COLUMN nodes into TK_AGG_COLUMN and make entries in ** sAggInfo for all TK_AGG_FUNCTION nodes in expressions of the ** SELECT statement. */ memset(&sNC, 0, sizeof(sNC)); sNC.pParse = pParse; sNC.pSrcList = pTabList; sNC.pAggInfo = &sAggInfo; sAggInfo.mnReg = pParse->nMem+1; sAggInfo.nSortingColumn = pGroupBy ? pGroupBy->nExpr : 0; sAggInfo.pGroupBy = pGroupBy; sqlite3ExprAnalyzeAggList(&sNC, pEList); sqlite3ExprAnalyzeAggList(&sNC, sSort.pOrderBy); if( pHaving ){ sqlite3ExprAnalyzeAggregates(&sNC, pHaving); } sAggInfo.nAccumulator = sAggInfo.nColumn; for(i=0; ix.pList); sNC.ncFlags &= ~NC_InAggFunc; } sAggInfo.mxReg = pParse->nMem; if( db->mallocFailed ) goto select_end; /* Processing for aggregates with GROUP BY is very different and ** much more complex than aggregates without a GROUP BY. */ if( pGroupBy ){ KeyInfo *pKeyInfo; /* Keying information for the group by clause */ int addr1; /* A-vs-B comparision jump */ int addrOutputRow; /* Start of subroutine that outputs a result row */ int regOutputRow; /* Return address register for output subroutine */ int addrSetAbort; /* Set the abort flag and return */ int addrTopOfLoop; /* Top of the input loop */ int addrSortingIdx; /* The OP_OpenEphemeral for the sorting index */ int addrReset; /* Subroutine for resetting the accumulator */ int regReset; /* Return address register for reset subroutine */ /* If there is a GROUP BY clause we might need a sorting index to ** implement it. Allocate that sorting index now. If it turns out ** that we do not need it after all, the OP_SorterOpen instruction ** will be converted into a Noop. */ sAggInfo.sortingIdx = pParse->nTab++; pKeyInfo = keyInfoFromExprList(pParse, pGroupBy, 0, sAggInfo.nColumn); addrSortingIdx = sqlite3VdbeAddOp4(v, OP_SorterOpen, sAggInfo.sortingIdx, sAggInfo.nSortingColumn, 0, (char*)pKeyInfo, P4_KEYINFO); /* Initialize memory locations used by GROUP BY aggregate processing */ iUseFlag = ++pParse->nMem; iAbortFlag = ++pParse->nMem; regOutputRow = ++pParse->nMem; addrOutputRow = sqlite3VdbeMakeLabel(v); regReset = ++pParse->nMem; addrReset = sqlite3VdbeMakeLabel(v); iAMem = pParse->nMem + 1; pParse->nMem += pGroupBy->nExpr; iBMem = pParse->nMem + 1; pParse->nMem += pGroupBy->nExpr; sqlite3VdbeAddOp2(v, OP_Integer, 0, iAbortFlag); VdbeComment((v, "clear abort flag")); sqlite3VdbeAddOp2(v, OP_Integer, 0, iUseFlag); VdbeComment((v, "indicate accumulator empty")); sqlite3VdbeAddOp3(v, OP_Null, 0, iAMem, iAMem+pGroupBy->nExpr-1); /* Begin a loop that will extract all source rows in GROUP BY order. ** This might involve two separate loops with an OP_Sort in between, or ** it might be a single loop that uses an index to extract information ** in the right order to begin with. */ sqlite3VdbeAddOp2(v, OP_Gosub, regReset, addrReset); pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, pGroupBy, 0, WHERE_GROUPBY | (orderByGrp ? WHERE_SORTBYGROUP : 0), 0 ); if( pWInfo==0 ) goto select_end; if( sqlite3WhereIsOrdered(pWInfo)==pGroupBy->nExpr ){ /* The optimizer is able to deliver rows in group by order so ** we do not have to sort. The OP_OpenEphemeral table will be ** cancelled later because we still need to use the pKeyInfo */ groupBySort = 0; }else{ /* Rows are coming out in undetermined order. We have to push ** each row into a sorting index, terminate the first loop, ** then loop over the sorting index in order to get the output ** in sorted order */ int regBase; int regRecord; int nCol; int nGroupBy; explainTempTable(pParse, (sDistinct.isTnct && (p->selFlags&SF_Distinct)==0) ? "DISTINCT" : "GROUP BY"); groupBySort = 1; nGroupBy = pGroupBy->nExpr; nCol = nGroupBy; j = nGroupBy; for(i=0; i=j ){ nCol++; j++; } } regBase = sqlite3GetTempRange(pParse, nCol); sqlite3ExprCacheClear(pParse); sqlite3ExprCodeExprList(pParse, pGroupBy, regBase, 0, 0); j = nGroupBy; for(i=0; iiSorterColumn>=j ){ int r1 = j + regBase; sqlite3ExprCodeGetColumnToReg(pParse, pCol->pTab, pCol->iColumn, pCol->iTable, r1); j++; } } regRecord = sqlite3GetTempReg(pParse); sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nCol, regRecord); sqlite3VdbeAddOp2(v, OP_SorterInsert, sAggInfo.sortingIdx, regRecord); sqlite3ReleaseTempReg(pParse, regRecord); sqlite3ReleaseTempRange(pParse, regBase, nCol); sqlite3WhereEnd(pWInfo); sAggInfo.sortingIdxPTab = sortPTab = pParse->nTab++; sortOut = sqlite3GetTempReg(pParse); sqlite3VdbeAddOp3(v, OP_OpenPseudo, sortPTab, sortOut, nCol); sqlite3VdbeAddOp2(v, OP_SorterSort, sAggInfo.sortingIdx, addrEnd); VdbeComment((v, "GROUP BY sort")); VdbeCoverage(v); sAggInfo.useSortingIdx = 1; sqlite3ExprCacheClear(pParse); } /* If the index or temporary table used by the GROUP BY sort ** will naturally deliver rows in the order required by the ORDER BY ** clause, cancel the ephemeral table open coded earlier. ** ** This is an optimization - the correct answer should result regardless. ** Use the SQLITE_GroupByOrder flag with SQLITE_TESTCTRL_OPTIMIZER to ** disable this optimization for testing purposes. */ if( orderByGrp && OptimizationEnabled(db, SQLITE_GroupByOrder) && (groupBySort || sqlite3WhereIsSorted(pWInfo)) ){ sSort.pOrderBy = 0; sqlite3VdbeChangeToNoop(v, sSort.addrSortIndex); } /* Evaluate the current GROUP BY terms and store in b0, b1, b2... ** (b0 is memory location iBMem+0, b1 is iBMem+1, and so forth) ** Then compare the current GROUP BY terms against the GROUP BY terms ** from the previous row currently stored in a0, a1, a2... */ addrTopOfLoop = sqlite3VdbeCurrentAddr(v); sqlite3ExprCacheClear(pParse); if( groupBySort ){ sqlite3VdbeAddOp3(v, OP_SorterData, sAggInfo.sortingIdx, sortOut, sortPTab); } for(j=0; jnExpr; j++){ if( groupBySort ){ sqlite3VdbeAddOp3(v, OP_Column, sortPTab, j, iBMem+j); }else{ sAggInfo.directMode = 1; sqlite3ExprCode(pParse, pGroupBy->a[j].pExpr, iBMem+j); } } sqlite3VdbeAddOp4(v, OP_Compare, iAMem, iBMem, pGroupBy->nExpr, (char*)sqlite3KeyInfoRef(pKeyInfo), P4_KEYINFO); addr1 = sqlite3VdbeCurrentAddr(v); sqlite3VdbeAddOp3(v, OP_Jump, addr1+1, 0, addr1+1); VdbeCoverage(v); /* Generate code that runs whenever the GROUP BY changes. ** Changes in the GROUP BY are detected by the previous code ** block. If there were no changes, this block is skipped. ** ** This code copies current group by terms in b0,b1,b2,... ** over to a0,a1,a2. It then calls the output subroutine ** and resets the aggregate accumulator registers in preparation ** for the next GROUP BY batch. */ sqlite3ExprCodeMove(pParse, iBMem, iAMem, pGroupBy->nExpr); sqlite3VdbeAddOp2(v, OP_Gosub, regOutputRow, addrOutputRow); VdbeComment((v, "output one row")); sqlite3VdbeAddOp2(v, OP_IfPos, iAbortFlag, addrEnd); VdbeCoverage(v); VdbeComment((v, "check abort flag")); sqlite3VdbeAddOp2(v, OP_Gosub, regReset, addrReset); VdbeComment((v, "reset accumulator")); /* Update the aggregate accumulators based on the content of ** the current row */ sqlite3VdbeJumpHere(v, addr1); updateAccumulator(pParse, &sAggInfo); sqlite3VdbeAddOp2(v, OP_Integer, 1, iUseFlag); VdbeComment((v, "indicate data in accumulator")); /* End of the loop */ if( groupBySort ){ sqlite3VdbeAddOp2(v, OP_SorterNext, sAggInfo.sortingIdx, addrTopOfLoop); VdbeCoverage(v); }else{ sqlite3WhereEnd(pWInfo); sqlite3VdbeChangeToNoop(v, addrSortingIdx); } /* Output the final row of result */ sqlite3VdbeAddOp2(v, OP_Gosub, regOutputRow, addrOutputRow); VdbeComment((v, "output final row")); /* Jump over the subroutines */ sqlite3VdbeGoto(v, addrEnd); /* Generate a subroutine that outputs a single row of the result ** set. This subroutine first looks at the iUseFlag. If iUseFlag ** is less than or equal to zero, the subroutine is a no-op. If ** the processing calls for the query to abort, this subroutine ** increments the iAbortFlag memory location before returning in ** order to signal the caller to abort. */ addrSetAbort = sqlite3VdbeCurrentAddr(v); sqlite3VdbeAddOp2(v, OP_Integer, 1, iAbortFlag); VdbeComment((v, "set abort flag")); sqlite3VdbeAddOp1(v, OP_Return, regOutputRow); sqlite3VdbeResolveLabel(v, addrOutputRow); addrOutputRow = sqlite3VdbeCurrentAddr(v); sqlite3VdbeAddOp2(v, OP_IfPos, iUseFlag, addrOutputRow+2); VdbeCoverage(v); VdbeComment((v, "Groupby result generator entry point")); sqlite3VdbeAddOp1(v, OP_Return, regOutputRow); finalizeAggFunctions(pParse, &sAggInfo); sqlite3ExprIfFalse(pParse, pHaving, addrOutputRow+1, SQLITE_JUMPIFNULL); selectInnerLoop(pParse, p, p->pEList, -1, &sSort, &sDistinct, pDest, addrOutputRow+1, addrSetAbort); sqlite3VdbeAddOp1(v, OP_Return, regOutputRow); VdbeComment((v, "end groupby result generator")); /* Generate a subroutine that will reset the group-by accumulator */ sqlite3VdbeResolveLabel(v, addrReset); resetAccumulator(pParse, &sAggInfo); sqlite3VdbeAddOp1(v, OP_Return, regReset); } /* endif pGroupBy. Begin aggregate queries without GROUP BY: */ else { ExprList *pDel = 0; #ifndef SQLITE_OMIT_BTREECOUNT Table *pTab; if( (pTab = isSimpleCount(p, &sAggInfo))!=0 ){ /* If isSimpleCount() returns a pointer to a Table structure, then ** the SQL statement is of the form: ** ** SELECT count(*) FROM ** ** where the Table structure returned represents table . ** ** This statement is so common that it is optimized specially. The ** OP_Count instruction is executed either on the intkey table that ** contains the data for table or on one of its indexes. It ** is better to execute the op on an index, as indexes are almost ** always spread across less pages than their corresponding tables. */ const int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema); const int iCsr = pParse->nTab++; /* Cursor to scan b-tree */ Index *pIdx; /* Iterator variable */ KeyInfo *pKeyInfo = 0; /* Keyinfo for scanned index */ Index *pBest = 0; /* Best index found so far */ int iRoot = pTab->tnum; /* Root page of scanned b-tree */ sqlite3CodeVerifySchema(pParse, iDb); sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName); /* Search for the index that has the lowest scan cost. ** ** (2011-04-15) Do not do a full scan of an unordered index. ** ** (2013-10-03) Do not count the entries in a partial index. ** ** In practice the KeyInfo structure will not be used. It is only ** passed to keep OP_OpenRead happy. */ if( !HasRowid(pTab) ) pBest = sqlite3PrimaryKeyIndex(pTab); for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){ if( pIdx->bUnordered==0 && pIdx->szIdxRowszTabRow && pIdx->pPartIdxWhere==0 && (!pBest || pIdx->szIdxRowszIdxRow) ){ pBest = pIdx; } } if( pBest ){ iRoot = pBest->tnum; pKeyInfo = sqlite3KeyInfoOfIndex(pParse, pBest); } /* Open a read-only cursor, execute the OP_Count, close the cursor. */ sqlite3VdbeAddOp4Int(v, OP_OpenRead, iCsr, iRoot, iDb, 1); if( pKeyInfo ){ sqlite3VdbeChangeP4(v, -1, (char *)pKeyInfo, P4_KEYINFO); } sqlite3VdbeAddOp2(v, OP_Count, iCsr, sAggInfo.aFunc[0].iMem); sqlite3VdbeAddOp1(v, OP_Close, iCsr); explainSimpleCount(pParse, pTab, pBest); }else #endif /* SQLITE_OMIT_BTREECOUNT */ { /* Check if the query is of one of the following forms: ** ** SELECT min(x) FROM ... ** SELECT max(x) FROM ... ** ** If it is, then ask the code in where.c to attempt to sort results ** as if there was an "ORDER ON x" or "ORDER ON x DESC" clause. ** If where.c is able to produce results sorted in this order, then ** add vdbe code to break out of the processing loop after the ** first iteration (since the first iteration of the loop is ** guaranteed to operate on the row with the minimum or maximum ** value of x, the only row required). ** ** A special flag must be passed to sqlite3WhereBegin() to slightly ** modify behavior as follows: ** ** + If the query is a "SELECT min(x)", then the loop coded by ** where.c should not iterate over any values with a NULL value ** for x. ** ** + The optimizer code in where.c (the thing that decides which ** index or indices to use) should place a different priority on ** satisfying the 'ORDER BY' clause than it does in other cases. ** Refer to code and comments in where.c for details. */ ExprList *pMinMax = 0; u8 flag = WHERE_ORDERBY_NORMAL; assert( p->pGroupBy==0 ); assert( flag==0 ); if( p->pHaving==0 ){ flag = minMaxQuery(&sAggInfo, &pMinMax); } assert( flag==0 || (pMinMax!=0 && pMinMax->nExpr==1) ); if( flag ){ pMinMax = sqlite3ExprListDup(db, pMinMax, 0); pDel = pMinMax; assert( db->mallocFailed || pMinMax!=0 ); if( !db->mallocFailed ){ pMinMax->a[0].sortOrder = flag!=WHERE_ORDERBY_MIN ?1:0; pMinMax->a[0].pExpr->op = TK_COLUMN; } } /* This case runs if the aggregate has no GROUP BY clause. The ** processing is much simpler since there is only a single row ** of output. */ resetAccumulator(pParse, &sAggInfo); pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, pMinMax,0,flag,0); if( pWInfo==0 ){ sqlite3ExprListDelete(db, pDel); goto select_end; } updateAccumulator(pParse, &sAggInfo); assert( pMinMax==0 || pMinMax->nExpr==1 ); if( sqlite3WhereIsOrdered(pWInfo)>0 ){ sqlite3VdbeGoto(v, sqlite3WhereBreakLabel(pWInfo)); VdbeComment((v, "%s() by index", (flag==WHERE_ORDERBY_MIN?"min":"max"))); } sqlite3WhereEnd(pWInfo); finalizeAggFunctions(pParse, &sAggInfo); } sSort.pOrderBy = 0; sqlite3ExprIfFalse(pParse, pHaving, addrEnd, SQLITE_JUMPIFNULL); selectInnerLoop(pParse, p, p->pEList, -1, 0, 0, pDest, addrEnd, addrEnd); sqlite3ExprListDelete(db, pDel); } sqlite3VdbeResolveLabel(v, addrEnd); } /* endif aggregate query */ if( sDistinct.eTnctType==WHERE_DISTINCT_UNORDERED ){ explainTempTable(pParse, "DISTINCT"); } /* If there is an ORDER BY clause, then we need to sort the results ** and send them to the callback one by one. */ if( sSort.pOrderBy ){ explainTempTable(pParse, sSort.nOBSat>0 ? "RIGHT PART OF ORDER BY":"ORDER BY"); generateSortTail(pParse, p, &sSort, pEList->nExpr, pDest); } /* Jump here to skip this query */ sqlite3VdbeResolveLabel(v, iEnd); /* The SELECT has been coded. If there is an error in the Parse structure, ** set the return code to 1. Otherwise 0. */ rc = (pParse->nErr>0); /* Control jumps to here if an error is encountered above, or upon ** successful coding of the SELECT. */ select_end: explainSetInteger(pParse->iSelectId, iRestoreSelectId); /* Identify column names if results of the SELECT are to be output. */ if( rc==SQLITE_OK && pDest->eDest==SRT_Output ){ generateColumnNames(pParse, pTabList, pEList); } sqlite3DbFree(db, sAggInfo.aCol); sqlite3DbFree(db, sAggInfo.aFunc); #if SELECTTRACE_ENABLED SELECTTRACE(1,pParse,p,("end processing\n")); pParse->nSelectIndent--; #endif return rc; } /************** End of select.c **********************************************/ /************** Begin file table.c *******************************************/ /* ** 2001 September 15 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ************************************************************************* ** This file contains the sqlite3_get_table() and sqlite3_free_table() ** interface routines. These are just wrappers around the main ** interface routine of sqlite3_exec(). ** ** These routines are in a separate files so that they will not be linked ** if they are not used. */ /* #include "sqliteInt.h" */ /* #include */ /* #include */ #ifndef SQLITE_OMIT_GET_TABLE /* ** This structure is used to pass data from sqlite3_get_table() through ** to the callback function is uses to build the result. */ typedef struct TabResult { char **azResult; /* Accumulated output */ char *zErrMsg; /* Error message text, if an error occurs */ u32 nAlloc; /* Slots allocated for azResult[] */ u32 nRow; /* Number of rows in the result */ u32 nColumn; /* Number of columns in the result */ u32 nData; /* Slots used in azResult[]. (nRow+1)*nColumn */ int rc; /* Return code from sqlite3_exec() */ } TabResult; /* ** This routine is called once for each row in the result table. Its job ** is to fill in the TabResult structure appropriately, allocating new ** memory as necessary. */ static int sqlite3_get_table_cb(void *pArg, int nCol, char **argv, char **colv){ TabResult *p = (TabResult*)pArg; /* Result accumulator */ int need; /* Slots needed in p->azResult[] */ int i; /* Loop counter */ char *z; /* A single column of result */ /* Make sure there is enough space in p->azResult to hold everything ** we need to remember from this invocation of the callback. */ if( p->nRow==0 && argv!=0 ){ need = nCol*2; }else{ need = nCol; } if( p->nData + need > p->nAlloc ){ char **azNew; p->nAlloc = p->nAlloc*2 + need; azNew = sqlite3_realloc64( p->azResult, sizeof(char*)*p->nAlloc ); if( azNew==0 ) goto malloc_failed; p->azResult = azNew; } /* If this is the first row, then generate an extra row containing ** the names of all columns. */ if( p->nRow==0 ){ p->nColumn = nCol; for(i=0; iazResult[p->nData++] = z; } }else if( (int)p->nColumn!=nCol ){ sqlite3_free(p->zErrMsg); p->zErrMsg = sqlite3_mprintf( "sqlite3_get_table() called with two or more incompatible queries" ); p->rc = SQLITE_ERROR; return 1; } /* Copy over the row data */ if( argv!=0 ){ for(i=0; iazResult[p->nData++] = z; } p->nRow++; } return 0; malloc_failed: p->rc = SQLITE_NOMEM_BKPT; return 1; } /* ** Query the database. But instead of invoking a callback for each row, ** malloc() for space to hold the result and return the entire results ** at the conclusion of the call. ** ** The result that is written to ***pazResult is held in memory obtained ** from malloc(). But the caller cannot free this memory directly. ** Instead, the entire table should be passed to sqlite3_free_table() when ** the calling procedure is finished using it. */ SQLITE_API int sqlite3_get_table( sqlite3 *db, /* The database on which the SQL executes */ const char *zSql, /* The SQL to be executed */ char ***pazResult, /* Write the result table here */ int *pnRow, /* Write the number of rows in the result here */ int *pnColumn, /* Write the number of columns of result here */ char **pzErrMsg /* Write error messages here */ ){ int rc; TabResult res; #ifdef SQLITE_ENABLE_API_ARMOR if( !sqlite3SafetyCheckOk(db) || pazResult==0 ) return SQLITE_MISUSE_BKPT; #endif *pazResult = 0; if( pnColumn ) *pnColumn = 0; if( pnRow ) *pnRow = 0; if( pzErrMsg ) *pzErrMsg = 0; res.zErrMsg = 0; res.nRow = 0; res.nColumn = 0; res.nData = 1; res.nAlloc = 20; res.rc = SQLITE_OK; res.azResult = sqlite3_malloc64(sizeof(char*)*res.nAlloc ); if( res.azResult==0 ){ db->errCode = SQLITE_NOMEM; return SQLITE_NOMEM_BKPT; } res.azResult[0] = 0; rc = sqlite3_exec(db, zSql, sqlite3_get_table_cb, &res, pzErrMsg); assert( sizeof(res.azResult[0])>= sizeof(res.nData) ); res.azResult[0] = SQLITE_INT_TO_PTR(res.nData); if( (rc&0xff)==SQLITE_ABORT ){ sqlite3_free_table(&res.azResult[1]); if( res.zErrMsg ){ if( pzErrMsg ){ sqlite3_free(*pzErrMsg); *pzErrMsg = sqlite3_mprintf("%s",res.zErrMsg); } sqlite3_free(res.zErrMsg); } db->errCode = res.rc; /* Assume 32-bit assignment is atomic */ return res.rc; } sqlite3_free(res.zErrMsg); if( rc!=SQLITE_OK ){ sqlite3_free_table(&res.azResult[1]); return rc; } if( res.nAlloc>res.nData ){ char **azNew; azNew = sqlite3_realloc64( res.azResult, sizeof(char*)*res.nData ); if( azNew==0 ){ sqlite3_free_table(&res.azResult[1]); db->errCode = SQLITE_NOMEM; return SQLITE_NOMEM_BKPT; } res.azResult = azNew; } *pazResult = &res.azResult[1]; if( pnColumn ) *pnColumn = res.nColumn; if( pnRow ) *pnRow = res.nRow; return rc; } /* ** This routine frees the space the sqlite3_get_table() malloced. */ SQLITE_API void sqlite3_free_table( char **azResult /* Result returned from sqlite3_get_table() */ ){ if( azResult ){ int i, n; azResult--; assert( azResult!=0 ); n = SQLITE_PTR_TO_INT(azResult[0]); for(i=1; ipNext; sqlite3ExprDelete(db, pTmp->pWhere); sqlite3ExprListDelete(db, pTmp->pExprList); sqlite3SelectDelete(db, pTmp->pSelect); sqlite3IdListDelete(db, pTmp->pIdList); sqlite3DbFree(db, pTmp); } } /* ** Given table pTab, return a list of all the triggers attached to ** the table. The list is connected by Trigger.pNext pointers. ** ** All of the triggers on pTab that are in the same database as pTab ** are already attached to pTab->pTrigger. But there might be additional ** triggers on pTab in the TEMP schema. This routine prepends all ** TEMP triggers on pTab to the beginning of the pTab->pTrigger list ** and returns the combined list. ** ** To state it another way: This routine returns a list of all triggers ** that fire off of pTab. The list will include any TEMP triggers on ** pTab as well as the triggers lised in pTab->pTrigger. */ SQLITE_PRIVATE Trigger *sqlite3TriggerList(Parse *pParse, Table *pTab){ Schema * const pTmpSchema = pParse->db->aDb[1].pSchema; Trigger *pList = 0; /* List of triggers to return */ if( pParse->disableTriggers ){ return 0; } if( pTmpSchema!=pTab->pSchema ){ HashElem *p; assert( sqlite3SchemaMutexHeld(pParse->db, 0, pTmpSchema) ); for(p=sqliteHashFirst(&pTmpSchema->trigHash); p; p=sqliteHashNext(p)){ Trigger *pTrig = (Trigger *)sqliteHashData(p); if( pTrig->pTabSchema==pTab->pSchema && 0==sqlite3StrICmp(pTrig->table, pTab->zName) ){ pTrig->pNext = (pList ? pList : pTab->pTrigger); pList = pTrig; } } } return (pList ? pList : pTab->pTrigger); } /* ** This is called by the parser when it sees a CREATE TRIGGER statement ** up to the point of the BEGIN before the trigger actions. A Trigger ** structure is generated based on the information available and stored ** in pParse->pNewTrigger. After the trigger actions have been parsed, the ** sqlite3FinishTrigger() function is called to complete the trigger ** construction process. */ SQLITE_PRIVATE void sqlite3BeginTrigger( Parse *pParse, /* The parse context of the CREATE TRIGGER statement */ Token *pName1, /* The name of the trigger */ Token *pName2, /* The name of the trigger */ int tr_tm, /* One of TK_BEFORE, TK_AFTER, TK_INSTEAD */ int op, /* One of TK_INSERT, TK_UPDATE, TK_DELETE */ IdList *pColumns, /* column list if this is an UPDATE OF trigger */ SrcList *pTableName,/* The name of the table/view the trigger applies to */ Expr *pWhen, /* WHEN clause */ int isTemp, /* True if the TEMPORARY keyword is present */ int noErr /* Suppress errors if the trigger already exists */ ){ Trigger *pTrigger = 0; /* The new trigger */ Table *pTab; /* Table that the trigger fires off of */ char *zName = 0; /* Name of the trigger */ sqlite3 *db = pParse->db; /* The database connection */ int iDb; /* The database to store the trigger in */ Token *pName; /* The unqualified db name */ DbFixer sFix; /* State vector for the DB fixer */ assert( pName1!=0 ); /* pName1->z might be NULL, but not pName1 itself */ assert( pName2!=0 ); assert( op==TK_INSERT || op==TK_UPDATE || op==TK_DELETE ); assert( op>0 && op<0xff ); if( isTemp ){ /* If TEMP was specified, then the trigger name may not be qualified. */ if( pName2->n>0 ){ sqlite3ErrorMsg(pParse, "temporary trigger may not have qualified name"); goto trigger_cleanup; } iDb = 1; pName = pName1; }else{ /* Figure out the db that the trigger will be created in */ iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName); if( iDb<0 ){ goto trigger_cleanup; } } if( !pTableName || db->mallocFailed ){ goto trigger_cleanup; } /* A long-standing parser bug is that this syntax was allowed: ** ** CREATE TRIGGER attached.demo AFTER INSERT ON attached.tab .... ** ^^^^^^^^ ** ** To maintain backwards compatibility, ignore the database ** name on pTableName if we are reparsing out of SQLITE_MASTER. */ if( db->init.busy && iDb!=1 ){ sqlite3DbFree(db, pTableName->a[0].zDatabase); pTableName->a[0].zDatabase = 0; } /* If the trigger name was unqualified, and the table is a temp table, ** then set iDb to 1 to create the trigger in the temporary database. ** If sqlite3SrcListLookup() returns 0, indicating the table does not ** exist, the error is caught by the block below. */ pTab = sqlite3SrcListLookup(pParse, pTableName); if( db->init.busy==0 && pName2->n==0 && pTab && pTab->pSchema==db->aDb[1].pSchema ){ iDb = 1; } /* Ensure the table name matches database name and that the table exists */ if( db->mallocFailed ) goto trigger_cleanup; assert( pTableName->nSrc==1 ); sqlite3FixInit(&sFix, pParse, iDb, "trigger", pName); if( sqlite3FixSrcList(&sFix, pTableName) ){ goto trigger_cleanup; } pTab = sqlite3SrcListLookup(pParse, pTableName); if( !pTab ){ /* The table does not exist. */ if( db->init.iDb==1 ){ /* Ticket #3810. ** Normally, whenever a table is dropped, all associated triggers are ** dropped too. But if a TEMP trigger is created on a non-TEMP table ** and the table is dropped by a different database connection, the ** trigger is not visible to the database connection that does the ** drop so the trigger cannot be dropped. This results in an ** "orphaned trigger" - a trigger whose associated table is missing. */ db->init.orphanTrigger = 1; } goto trigger_cleanup; } if( IsVirtual(pTab) ){ sqlite3ErrorMsg(pParse, "cannot create triggers on virtual tables"); goto trigger_cleanup; } /* Check that the trigger name is not reserved and that no trigger of the ** specified name exists */ zName = sqlite3NameFromToken(db, pName); if( !zName || SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){ goto trigger_cleanup; } assert( sqlite3SchemaMutexHeld(db, iDb, 0) ); if( sqlite3HashFind(&(db->aDb[iDb].pSchema->trigHash),zName) ){ if( !noErr ){ sqlite3ErrorMsg(pParse, "trigger %T already exists", pName); }else{ assert( !db->init.busy ); sqlite3CodeVerifySchema(pParse, iDb); } goto trigger_cleanup; } /* Do not create a trigger on a system table */ if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0 ){ sqlite3ErrorMsg(pParse, "cannot create trigger on system table"); goto trigger_cleanup; } /* INSTEAD of triggers are only for views and views only support INSTEAD ** of triggers. */ if( pTab->pSelect && tr_tm!=TK_INSTEAD ){ sqlite3ErrorMsg(pParse, "cannot create %s trigger on view: %S", (tr_tm == TK_BEFORE)?"BEFORE":"AFTER", pTableName, 0); goto trigger_cleanup; } if( !pTab->pSelect && tr_tm==TK_INSTEAD ){ sqlite3ErrorMsg(pParse, "cannot create INSTEAD OF" " trigger on table: %S", pTableName, 0); goto trigger_cleanup; } #ifndef SQLITE_OMIT_AUTHORIZATION { int iTabDb = sqlite3SchemaToIndex(db, pTab->pSchema); int code = SQLITE_CREATE_TRIGGER; const char *zDb = db->aDb[iTabDb].zDbSName; const char *zDbTrig = isTemp ? db->aDb[1].zDbSName : zDb; if( iTabDb==1 || isTemp ) code = SQLITE_CREATE_TEMP_TRIGGER; if( sqlite3AuthCheck(pParse, code, zName, pTab->zName, zDbTrig) ){ goto trigger_cleanup; } if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(iTabDb),0,zDb)){ goto trigger_cleanup; } } #endif /* INSTEAD OF triggers can only appear on views and BEFORE triggers ** cannot appear on views. So we might as well translate every ** INSTEAD OF trigger into a BEFORE trigger. It simplifies code ** elsewhere. */ if (tr_tm == TK_INSTEAD){ tr_tm = TK_BEFORE; } /* Build the Trigger object */ pTrigger = (Trigger*)sqlite3DbMallocZero(db, sizeof(Trigger)); if( pTrigger==0 ) goto trigger_cleanup; pTrigger->zName = zName; zName = 0; pTrigger->table = sqlite3DbStrDup(db, pTableName->a[0].zName); pTrigger->pSchema = db->aDb[iDb].pSchema; pTrigger->pTabSchema = pTab->pSchema; pTrigger->op = (u8)op; pTrigger->tr_tm = tr_tm==TK_BEFORE ? TRIGGER_BEFORE : TRIGGER_AFTER; pTrigger->pWhen = sqlite3ExprDup(db, pWhen, EXPRDUP_REDUCE); pTrigger->pColumns = sqlite3IdListDup(db, pColumns); assert( pParse->pNewTrigger==0 ); pParse->pNewTrigger = pTrigger; trigger_cleanup: sqlite3DbFree(db, zName); sqlite3SrcListDelete(db, pTableName); sqlite3IdListDelete(db, pColumns); sqlite3ExprDelete(db, pWhen); if( !pParse->pNewTrigger ){ sqlite3DeleteTrigger(db, pTrigger); }else{ assert( pParse->pNewTrigger==pTrigger ); } } /* ** This routine is called after all of the trigger actions have been parsed ** in order to complete the process of building the trigger. */ SQLITE_PRIVATE void sqlite3FinishTrigger( Parse *pParse, /* Parser context */ TriggerStep *pStepList, /* The triggered program */ Token *pAll /* Token that describes the complete CREATE TRIGGER */ ){ Trigger *pTrig = pParse->pNewTrigger; /* Trigger being finished */ char *zName; /* Name of trigger */ sqlite3 *db = pParse->db; /* The database */ DbFixer sFix; /* Fixer object */ int iDb; /* Database containing the trigger */ Token nameToken; /* Trigger name for error reporting */ pParse->pNewTrigger = 0; if( NEVER(pParse->nErr) || !pTrig ) goto triggerfinish_cleanup; zName = pTrig->zName; iDb = sqlite3SchemaToIndex(pParse->db, pTrig->pSchema); pTrig->step_list = pStepList; while( pStepList ){ pStepList->pTrig = pTrig; pStepList = pStepList->pNext; } sqlite3TokenInit(&nameToken, pTrig->zName); sqlite3FixInit(&sFix, pParse, iDb, "trigger", &nameToken); if( sqlite3FixTriggerStep(&sFix, pTrig->step_list) || sqlite3FixExpr(&sFix, pTrig->pWhen) ){ goto triggerfinish_cleanup; } /* if we are not initializing, ** build the sqlite_master entry */ if( !db->init.busy ){ Vdbe *v; char *z; /* Make an entry in the sqlite_master table */ v = sqlite3GetVdbe(pParse); if( v==0 ) goto triggerfinish_cleanup; sqlite3BeginWriteOperation(pParse, 0, iDb); z = sqlite3DbStrNDup(db, (char*)pAll->z, pAll->n); sqlite3NestedParse(pParse, "INSERT INTO %Q.%s VALUES('trigger',%Q,%Q,0,'CREATE TRIGGER %q')", db->aDb[iDb].zDbSName, SCHEMA_TABLE(iDb), zName, pTrig->table, z); sqlite3DbFree(db, z); sqlite3ChangeCookie(pParse, iDb); sqlite3VdbeAddParseSchemaOp(v, iDb, sqlite3MPrintf(db, "type='trigger' AND name='%q'", zName)); } if( db->init.busy ){ Trigger *pLink = pTrig; Hash *pHash = &db->aDb[iDb].pSchema->trigHash; assert( sqlite3SchemaMutexHeld(db, iDb, 0) ); pTrig = sqlite3HashInsert(pHash, zName, pTrig); if( pTrig ){ sqlite3OomFault(db); }else if( pLink->pSchema==pLink->pTabSchema ){ Table *pTab; pTab = sqlite3HashFind(&pLink->pTabSchema->tblHash, pLink->table); assert( pTab!=0 ); pLink->pNext = pTab->pTrigger; pTab->pTrigger = pLink; } } triggerfinish_cleanup: sqlite3DeleteTrigger(db, pTrig); assert( !pParse->pNewTrigger ); sqlite3DeleteTriggerStep(db, pStepList); } /* ** Turn a SELECT statement (that the pSelect parameter points to) into ** a trigger step. Return a pointer to a TriggerStep structure. ** ** The parser calls this routine when it finds a SELECT statement in ** body of a TRIGGER. */ SQLITE_PRIVATE TriggerStep *sqlite3TriggerSelectStep(sqlite3 *db, Select *pSelect){ TriggerStep *pTriggerStep = sqlite3DbMallocZero(db, sizeof(TriggerStep)); if( pTriggerStep==0 ) { sqlite3SelectDelete(db, pSelect); return 0; } pTriggerStep->op = TK_SELECT; pTriggerStep->pSelect = pSelect; pTriggerStep->orconf = OE_Default; return pTriggerStep; } /* ** Allocate space to hold a new trigger step. The allocated space ** holds both the TriggerStep object and the TriggerStep.target.z string. ** ** If an OOM error occurs, NULL is returned and db->mallocFailed is set. */ static TriggerStep *triggerStepAllocate( sqlite3 *db, /* Database connection */ u8 op, /* Trigger opcode */ Token *pName /* The target name */ ){ TriggerStep *pTriggerStep; pTriggerStep = sqlite3DbMallocZero(db, sizeof(TriggerStep) + pName->n + 1); if( pTriggerStep ){ char *z = (char*)&pTriggerStep[1]; memcpy(z, pName->z, pName->n); sqlite3Dequote(z); pTriggerStep->zTarget = z; pTriggerStep->op = op; } return pTriggerStep; } /* ** Build a trigger step out of an INSERT statement. Return a pointer ** to the new trigger step. ** ** The parser calls this routine when it sees an INSERT inside the ** body of a trigger. */ SQLITE_PRIVATE TriggerStep *sqlite3TriggerInsertStep( sqlite3 *db, /* The database connection */ Token *pTableName, /* Name of the table into which we insert */ IdList *pColumn, /* List of columns in pTableName to insert into */ Select *pSelect, /* A SELECT statement that supplies values */ u8 orconf /* The conflict algorithm (OE_Abort, OE_Replace, etc.) */ ){ TriggerStep *pTriggerStep; assert(pSelect != 0 || db->mallocFailed); pTriggerStep = triggerStepAllocate(db, TK_INSERT, pTableName); if( pTriggerStep ){ pTriggerStep->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE); pTriggerStep->pIdList = pColumn; pTriggerStep->orconf = orconf; }else{ sqlite3IdListDelete(db, pColumn); } sqlite3SelectDelete(db, pSelect); return pTriggerStep; } /* ** Construct a trigger step that implements an UPDATE statement and return ** a pointer to that trigger step. The parser calls this routine when it ** sees an UPDATE statement inside the body of a CREATE TRIGGER. */ SQLITE_PRIVATE TriggerStep *sqlite3TriggerUpdateStep( sqlite3 *db, /* The database connection */ Token *pTableName, /* Name of the table to be updated */ ExprList *pEList, /* The SET clause: list of column and new values */ Expr *pWhere, /* The WHERE clause */ u8 orconf /* The conflict algorithm. (OE_Abort, OE_Ignore, etc) */ ){ TriggerStep *pTriggerStep; pTriggerStep = triggerStepAllocate(db, TK_UPDATE, pTableName); if( pTriggerStep ){ pTriggerStep->pExprList = sqlite3ExprListDup(db, pEList, EXPRDUP_REDUCE); pTriggerStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE); pTriggerStep->orconf = orconf; } sqlite3ExprListDelete(db, pEList); sqlite3ExprDelete(db, pWhere); return pTriggerStep; } /* ** Construct a trigger step that implements a DELETE statement and return ** a pointer to that trigger step. The parser calls this routine when it ** sees a DELETE statement inside the body of a CREATE TRIGGER. */ SQLITE_PRIVATE TriggerStep *sqlite3TriggerDeleteStep( sqlite3 *db, /* Database connection */ Token *pTableName, /* The table from which rows are deleted */ Expr *pWhere /* The WHERE clause */ ){ TriggerStep *pTriggerStep; pTriggerStep = triggerStepAllocate(db, TK_DELETE, pTableName); if( pTriggerStep ){ pTriggerStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE); pTriggerStep->orconf = OE_Default; } sqlite3ExprDelete(db, pWhere); return pTriggerStep; } /* ** Recursively delete a Trigger structure */ SQLITE_PRIVATE void sqlite3DeleteTrigger(sqlite3 *db, Trigger *pTrigger){ if( pTrigger==0 ) return; sqlite3DeleteTriggerStep(db, pTrigger->step_list); sqlite3DbFree(db, pTrigger->zName); sqlite3DbFree(db, pTrigger->table); sqlite3ExprDelete(db, pTrigger->pWhen); sqlite3IdListDelete(db, pTrigger->pColumns); sqlite3DbFree(db, pTrigger); } /* ** This function is called to drop a trigger from the database schema. ** ** This may be called directly from the parser and therefore identifies ** the trigger by name. The sqlite3DropTriggerPtr() routine does the ** same job as this routine except it takes a pointer to the trigger ** instead of the trigger name. **/ SQLITE_PRIVATE void sqlite3DropTrigger(Parse *pParse, SrcList *pName, int noErr){ Trigger *pTrigger = 0; int i; const char *zDb; const char *zName; sqlite3 *db = pParse->db; if( db->mallocFailed ) goto drop_trigger_cleanup; if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){ goto drop_trigger_cleanup; } assert( pName->nSrc==1 ); zDb = pName->a[0].zDatabase; zName = pName->a[0].zName; assert( zDb!=0 || sqlite3BtreeHoldsAllMutexes(db) ); for(i=OMIT_TEMPDB; inDb; i++){ int j = (i<2) ? i^1 : i; /* Search TEMP before MAIN */ if( zDb && sqlite3StrICmp(db->aDb[j].zDbSName, zDb) ) continue; assert( sqlite3SchemaMutexHeld(db, j, 0) ); pTrigger = sqlite3HashFind(&(db->aDb[j].pSchema->trigHash), zName); if( pTrigger ) break; } if( !pTrigger ){ if( !noErr ){ sqlite3ErrorMsg(pParse, "no such trigger: %S", pName, 0); }else{ sqlite3CodeVerifyNamedSchema(pParse, zDb); } pParse->checkSchema = 1; goto drop_trigger_cleanup; } sqlite3DropTriggerPtr(pParse, pTrigger); drop_trigger_cleanup: sqlite3SrcListDelete(db, pName); } /* ** Return a pointer to the Table structure for the table that a trigger ** is set on. */ static Table *tableOfTrigger(Trigger *pTrigger){ return sqlite3HashFind(&pTrigger->pTabSchema->tblHash, pTrigger->table); } /* ** Drop a trigger given a pointer to that trigger. */ SQLITE_PRIVATE void sqlite3DropTriggerPtr(Parse *pParse, Trigger *pTrigger){ Table *pTable; Vdbe *v; sqlite3 *db = pParse->db; int iDb; iDb = sqlite3SchemaToIndex(pParse->db, pTrigger->pSchema); assert( iDb>=0 && iDbnDb ); pTable = tableOfTrigger(pTrigger); assert( pTable ); assert( pTable->pSchema==pTrigger->pSchema || iDb==1 ); #ifndef SQLITE_OMIT_AUTHORIZATION { int code = SQLITE_DROP_TRIGGER; const char *zDb = db->aDb[iDb].zDbSName; const char *zTab = SCHEMA_TABLE(iDb); if( iDb==1 ) code = SQLITE_DROP_TEMP_TRIGGER; if( sqlite3AuthCheck(pParse, code, pTrigger->zName, pTable->zName, zDb) || sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){ return; } } #endif /* Generate code to destroy the database record of the trigger. */ assert( pTable!=0 ); if( (v = sqlite3GetVdbe(pParse))!=0 ){ sqlite3NestedParse(pParse, "DELETE FROM %Q.%s WHERE name=%Q AND type='trigger'", db->aDb[iDb].zDbSName, SCHEMA_TABLE(iDb), pTrigger->zName ); sqlite3ChangeCookie(pParse, iDb); sqlite3VdbeAddOp4(v, OP_DropTrigger, iDb, 0, 0, pTrigger->zName, 0); } } /* ** Remove a trigger from the hash tables of the sqlite* pointer. */ SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTrigger(sqlite3 *db, int iDb, const char *zName){ Trigger *pTrigger; Hash *pHash; assert( sqlite3SchemaMutexHeld(db, iDb, 0) ); pHash = &(db->aDb[iDb].pSchema->trigHash); pTrigger = sqlite3HashInsert(pHash, zName, 0); if( ALWAYS(pTrigger) ){ if( pTrigger->pSchema==pTrigger->pTabSchema ){ Table *pTab = tableOfTrigger(pTrigger); Trigger **pp; for(pp=&pTab->pTrigger; *pp!=pTrigger; pp=&((*pp)->pNext)); *pp = (*pp)->pNext; } sqlite3DeleteTrigger(db, pTrigger); db->flags |= SQLITE_InternChanges; } } /* ** pEList is the SET clause of an UPDATE statement. Each entry ** in pEList is of the format =. If any of the entries ** in pEList have an which matches an identifier in pIdList, ** then return TRUE. If pIdList==NULL, then it is considered a ** wildcard that matches anything. Likewise if pEList==NULL then ** it matches anything so always return true. Return false only ** if there is no match. */ static int checkColumnOverlap(IdList *pIdList, ExprList *pEList){ int e; if( pIdList==0 || NEVER(pEList==0) ) return 1; for(e=0; enExpr; e++){ if( sqlite3IdListIndex(pIdList, pEList->a[e].zName)>=0 ) return 1; } return 0; } /* ** Return a list of all triggers on table pTab if there exists at least ** one trigger that must be fired when an operation of type 'op' is ** performed on the table, and, if that operation is an UPDATE, if at ** least one of the columns in pChanges is being modified. */ SQLITE_PRIVATE Trigger *sqlite3TriggersExist( Parse *pParse, /* Parse context */ Table *pTab, /* The table the contains the triggers */ int op, /* one of TK_DELETE, TK_INSERT, TK_UPDATE */ ExprList *pChanges, /* Columns that change in an UPDATE statement */ int *pMask /* OUT: Mask of TRIGGER_BEFORE|TRIGGER_AFTER */ ){ int mask = 0; Trigger *pList = 0; Trigger *p; if( (pParse->db->flags & SQLITE_EnableTrigger)!=0 ){ pList = sqlite3TriggerList(pParse, pTab); } assert( pList==0 || IsVirtual(pTab)==0 ); for(p=pList; p; p=p->pNext){ if( p->op==op && checkColumnOverlap(p->pColumns, pChanges) ){ mask |= p->tr_tm; } } if( pMask ){ *pMask = mask; } return (mask ? pList : 0); } /* ** Convert the pStep->zTarget string into a SrcList and return a pointer ** to that SrcList. ** ** This routine adds a specific database name, if needed, to the target when ** forming the SrcList. This prevents a trigger in one database from ** referring to a target in another database. An exception is when the ** trigger is in TEMP in which case it can refer to any other database it ** wants. */ static SrcList *targetSrcList( Parse *pParse, /* The parsing context */ TriggerStep *pStep /* The trigger containing the target token */ ){ sqlite3 *db = pParse->db; int iDb; /* Index of the database to use */ SrcList *pSrc; /* SrcList to be returned */ pSrc = sqlite3SrcListAppend(db, 0, 0, 0); if( pSrc ){ assert( pSrc->nSrc>0 ); pSrc->a[pSrc->nSrc-1].zName = sqlite3DbStrDup(db, pStep->zTarget); iDb = sqlite3SchemaToIndex(db, pStep->pTrig->pSchema); if( iDb==0 || iDb>=2 ){ const char *zDb; assert( iDbnDb ); zDb = db->aDb[iDb].zDbSName; pSrc->a[pSrc->nSrc-1].zDatabase = sqlite3DbStrDup(db, zDb); } } return pSrc; } /* ** Generate VDBE code for the statements inside the body of a single ** trigger. */ static int codeTriggerProgram( Parse *pParse, /* The parser context */ TriggerStep *pStepList, /* List of statements inside the trigger body */ int orconf /* Conflict algorithm. (OE_Abort, etc) */ ){ TriggerStep *pStep; Vdbe *v = pParse->pVdbe; sqlite3 *db = pParse->db; assert( pParse->pTriggerTab && pParse->pToplevel ); assert( pStepList ); assert( v!=0 ); for(pStep=pStepList; pStep; pStep=pStep->pNext){ /* Figure out the ON CONFLICT policy that will be used for this step ** of the trigger program. If the statement that caused this trigger ** to fire had an explicit ON CONFLICT, then use it. Otherwise, use ** the ON CONFLICT policy that was specified as part of the trigger ** step statement. Example: ** ** CREATE TRIGGER AFTER INSERT ON t1 BEGIN; ** INSERT OR REPLACE INTO t2 VALUES(new.a, new.b); ** END; ** ** INSERT INTO t1 ... ; -- insert into t2 uses REPLACE policy ** INSERT OR IGNORE INTO t1 ... ; -- insert into t2 uses IGNORE policy */ pParse->eOrconf = (orconf==OE_Default)?pStep->orconf:(u8)orconf; assert( pParse->okConstFactor==0 ); switch( pStep->op ){ case TK_UPDATE: { sqlite3Update(pParse, targetSrcList(pParse, pStep), sqlite3ExprListDup(db, pStep->pExprList, 0), sqlite3ExprDup(db, pStep->pWhere, 0), pParse->eOrconf ); break; } case TK_INSERT: { sqlite3Insert(pParse, targetSrcList(pParse, pStep), sqlite3SelectDup(db, pStep->pSelect, 0), sqlite3IdListDup(db, pStep->pIdList), pParse->eOrconf ); break; } case TK_DELETE: { sqlite3DeleteFrom(pParse, targetSrcList(pParse, pStep), sqlite3ExprDup(db, pStep->pWhere, 0) ); break; } default: assert( pStep->op==TK_SELECT ); { SelectDest sDest; Select *pSelect = sqlite3SelectDup(db, pStep->pSelect, 0); sqlite3SelectDestInit(&sDest, SRT_Discard, 0); sqlite3Select(pParse, pSelect, &sDest); sqlite3SelectDelete(db, pSelect); break; } } if( pStep->op!=TK_SELECT ){ sqlite3VdbeAddOp0(v, OP_ResetCount); } } return 0; } #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS /* ** This function is used to add VdbeComment() annotations to a VDBE ** program. It is not used in production code, only for debugging. */ static const char *onErrorText(int onError){ switch( onError ){ case OE_Abort: return "abort"; case OE_Rollback: return "rollback"; case OE_Fail: return "fail"; case OE_Replace: return "replace"; case OE_Ignore: return "ignore"; case OE_Default: return "default"; } return "n/a"; } #endif /* ** Parse context structure pFrom has just been used to create a sub-vdbe ** (trigger program). If an error has occurred, transfer error information ** from pFrom to pTo. */ static void transferParseError(Parse *pTo, Parse *pFrom){ assert( pFrom->zErrMsg==0 || pFrom->nErr ); assert( pTo->zErrMsg==0 || pTo->nErr ); if( pTo->nErr==0 ){ pTo->zErrMsg = pFrom->zErrMsg; pTo->nErr = pFrom->nErr; pTo->rc = pFrom->rc; }else{ sqlite3DbFree(pFrom->db, pFrom->zErrMsg); } } /* ** Create and populate a new TriggerPrg object with a sub-program ** implementing trigger pTrigger with ON CONFLICT policy orconf. */ static TriggerPrg *codeRowTrigger( Parse *pParse, /* Current parse context */ Trigger *pTrigger, /* Trigger to code */ Table *pTab, /* The table pTrigger is attached to */ int orconf /* ON CONFLICT policy to code trigger program with */ ){ Parse *pTop = sqlite3ParseToplevel(pParse); sqlite3 *db = pParse->db; /* Database handle */ TriggerPrg *pPrg; /* Value to return */ Expr *pWhen = 0; /* Duplicate of trigger WHEN expression */ Vdbe *v; /* Temporary VM */ NameContext sNC; /* Name context for sub-vdbe */ SubProgram *pProgram = 0; /* Sub-vdbe for trigger program */ Parse *pSubParse; /* Parse context for sub-vdbe */ int iEndTrigger = 0; /* Label to jump to if WHEN is false */ assert( pTrigger->zName==0 || pTab==tableOfTrigger(pTrigger) ); assert( pTop->pVdbe ); /* Allocate the TriggerPrg and SubProgram objects. To ensure that they ** are freed if an error occurs, link them into the Parse.pTriggerPrg ** list of the top-level Parse object sooner rather than later. */ pPrg = sqlite3DbMallocZero(db, sizeof(TriggerPrg)); if( !pPrg ) return 0; pPrg->pNext = pTop->pTriggerPrg; pTop->pTriggerPrg = pPrg; pPrg->pProgram = pProgram = sqlite3DbMallocZero(db, sizeof(SubProgram)); if( !pProgram ) return 0; sqlite3VdbeLinkSubProgram(pTop->pVdbe, pProgram); pPrg->pTrigger = pTrigger; pPrg->orconf = orconf; pPrg->aColmask[0] = 0xffffffff; pPrg->aColmask[1] = 0xffffffff; /* Allocate and populate a new Parse context to use for coding the ** trigger sub-program. */ pSubParse = sqlite3StackAllocZero(db, sizeof(Parse)); if( !pSubParse ) return 0; memset(&sNC, 0, sizeof(sNC)); sNC.pParse = pSubParse; pSubParse->db = db; pSubParse->pTriggerTab = pTab; pSubParse->pToplevel = pTop; pSubParse->zAuthContext = pTrigger->zName; pSubParse->eTriggerOp = pTrigger->op; pSubParse->nQueryLoop = pParse->nQueryLoop; v = sqlite3GetVdbe(pSubParse); if( v ){ VdbeComment((v, "Start: %s.%s (%s %s%s%s ON %s)", pTrigger->zName, onErrorText(orconf), (pTrigger->tr_tm==TRIGGER_BEFORE ? "BEFORE" : "AFTER"), (pTrigger->op==TK_UPDATE ? "UPDATE" : ""), (pTrigger->op==TK_INSERT ? "INSERT" : ""), (pTrigger->op==TK_DELETE ? "DELETE" : ""), pTab->zName )); #ifndef SQLITE_OMIT_TRACE sqlite3VdbeChangeP4(v, -1, sqlite3MPrintf(db, "-- TRIGGER %s", pTrigger->zName), P4_DYNAMIC ); #endif /* If one was specified, code the WHEN clause. If it evaluates to false ** (or NULL) the sub-vdbe is immediately halted by jumping to the ** OP_Halt inserted at the end of the program. */ if( pTrigger->pWhen ){ pWhen = sqlite3ExprDup(db, pTrigger->pWhen, 0); if( SQLITE_OK==sqlite3ResolveExprNames(&sNC, pWhen) && db->mallocFailed==0 ){ iEndTrigger = sqlite3VdbeMakeLabel(v); sqlite3ExprIfFalse(pSubParse, pWhen, iEndTrigger, SQLITE_JUMPIFNULL); } sqlite3ExprDelete(db, pWhen); } /* Code the trigger program into the sub-vdbe. */ codeTriggerProgram(pSubParse, pTrigger->step_list, orconf); /* Insert an OP_Halt at the end of the sub-program. */ if( iEndTrigger ){ sqlite3VdbeResolveLabel(v, iEndTrigger); } sqlite3VdbeAddOp0(v, OP_Halt); VdbeComment((v, "End: %s.%s", pTrigger->zName, onErrorText(orconf))); transferParseError(pParse, pSubParse); if( db->mallocFailed==0 ){ pProgram->aOp = sqlite3VdbeTakeOpArray(v, &pProgram->nOp, &pTop->nMaxArg); } pProgram->nMem = pSubParse->nMem; pProgram->nCsr = pSubParse->nTab; pProgram->token = (void *)pTrigger; pPrg->aColmask[0] = pSubParse->oldmask; pPrg->aColmask[1] = pSubParse->newmask; sqlite3VdbeDelete(v); } assert( !pSubParse->pAinc && !pSubParse->pZombieTab ); assert( !pSubParse->pTriggerPrg && !pSubParse->nMaxArg ); sqlite3ParserReset(pSubParse); sqlite3StackFree(db, pSubParse); return pPrg; } /* ** Return a pointer to a TriggerPrg object containing the sub-program for ** trigger pTrigger with default ON CONFLICT algorithm orconf. If no such ** TriggerPrg object exists, a new object is allocated and populated before ** being returned. */ static TriggerPrg *getRowTrigger( Parse *pParse, /* Current parse context */ Trigger *pTrigger, /* Trigger to code */ Table *pTab, /* The table trigger pTrigger is attached to */ int orconf /* ON CONFLICT algorithm. */ ){ Parse *pRoot = sqlite3ParseToplevel(pParse); TriggerPrg *pPrg; assert( pTrigger->zName==0 || pTab==tableOfTrigger(pTrigger) ); /* It may be that this trigger has already been coded (or is in the ** process of being coded). If this is the case, then an entry with ** a matching TriggerPrg.pTrigger field will be present somewhere ** in the Parse.pTriggerPrg list. Search for such an entry. */ for(pPrg=pRoot->pTriggerPrg; pPrg && (pPrg->pTrigger!=pTrigger || pPrg->orconf!=orconf); pPrg=pPrg->pNext ); /* If an existing TriggerPrg could not be located, create a new one. */ if( !pPrg ){ pPrg = codeRowTrigger(pParse, pTrigger, pTab, orconf); } return pPrg; } /* ** Generate code for the trigger program associated with trigger p on ** table pTab. The reg, orconf and ignoreJump parameters passed to this ** function are the same as those described in the header function for ** sqlite3CodeRowTrigger() */ SQLITE_PRIVATE void sqlite3CodeRowTriggerDirect( Parse *pParse, /* Parse context */ Trigger *p, /* Trigger to code */ Table *pTab, /* The table to code triggers from */ int reg, /* Reg array containing OLD.* and NEW.* values */ int orconf, /* ON CONFLICT policy */ int ignoreJump /* Instruction to jump to for RAISE(IGNORE) */ ){ Vdbe *v = sqlite3GetVdbe(pParse); /* Main VM */ TriggerPrg *pPrg; pPrg = getRowTrigger(pParse, p, pTab, orconf); assert( pPrg || pParse->nErr || pParse->db->mallocFailed ); /* Code the OP_Program opcode in the parent VDBE. P4 of the OP_Program ** is a pointer to the sub-vdbe containing the trigger program. */ if( pPrg ){ int bRecursive = (p->zName && 0==(pParse->db->flags&SQLITE_RecTriggers)); sqlite3VdbeAddOp4(v, OP_Program, reg, ignoreJump, ++pParse->nMem, (const char *)pPrg->pProgram, P4_SUBPROGRAM); VdbeComment( (v, "Call: %s.%s", (p->zName?p->zName:"fkey"), onErrorText(orconf))); /* Set the P5 operand of the OP_Program instruction to non-zero if ** recursive invocation of this trigger program is disallowed. Recursive ** invocation is disallowed if (a) the sub-program is really a trigger, ** not a foreign key action, and (b) the flag to enable recursive triggers ** is clear. */ sqlite3VdbeChangeP5(v, (u8)bRecursive); } } /* ** This is called to code the required FOR EACH ROW triggers for an operation ** on table pTab. The operation to code triggers for (INSERT, UPDATE or DELETE) ** is given by the op parameter. The tr_tm parameter determines whether the ** BEFORE or AFTER triggers are coded. If the operation is an UPDATE, then ** parameter pChanges is passed the list of columns being modified. ** ** If there are no triggers that fire at the specified time for the specified ** operation on pTab, this function is a no-op. ** ** The reg argument is the address of the first in an array of registers ** that contain the values substituted for the new.* and old.* references ** in the trigger program. If N is the number of columns in table pTab ** (a copy of pTab->nCol), then registers are populated as follows: ** ** Register Contains ** ------------------------------------------------------ ** reg+0 OLD.rowid ** reg+1 OLD.* value of left-most column of pTab ** ... ... ** reg+N OLD.* value of right-most column of pTab ** reg+N+1 NEW.rowid ** reg+N+2 OLD.* value of left-most column of pTab ** ... ... ** reg+N+N+1 NEW.* value of right-most column of pTab ** ** For ON DELETE triggers, the registers containing the NEW.* values will ** never be accessed by the trigger program, so they are not allocated or ** populated by the caller (there is no data to populate them with anyway). ** Similarly, for ON INSERT triggers the values stored in the OLD.* registers ** are never accessed, and so are not allocated by the caller. So, for an ** ON INSERT trigger, the value passed to this function as parameter reg ** is not a readable register, although registers (reg+N) through ** (reg+N+N+1) are. ** ** Parameter orconf is the default conflict resolution algorithm for the ** trigger program to use (REPLACE, IGNORE etc.). Parameter ignoreJump ** is the instruction that control should jump to if a trigger program ** raises an IGNORE exception. */ SQLITE_PRIVATE void sqlite3CodeRowTrigger( Parse *pParse, /* Parse context */ Trigger *pTrigger, /* List of triggers on table pTab */ int op, /* One of TK_UPDATE, TK_INSERT, TK_DELETE */ ExprList *pChanges, /* Changes list for any UPDATE OF triggers */ int tr_tm, /* One of TRIGGER_BEFORE, TRIGGER_AFTER */ Table *pTab, /* The table to code triggers from */ int reg, /* The first in an array of registers (see above) */ int orconf, /* ON CONFLICT policy */ int ignoreJump /* Instruction to jump to for RAISE(IGNORE) */ ){ Trigger *p; /* Used to iterate through pTrigger list */ assert( op==TK_UPDATE || op==TK_INSERT || op==TK_DELETE ); assert( tr_tm==TRIGGER_BEFORE || tr_tm==TRIGGER_AFTER ); assert( (op==TK_UPDATE)==(pChanges!=0) ); for(p=pTrigger; p; p=p->pNext){ /* Sanity checking: The schema for the trigger and for the table are ** always defined. The trigger must be in the same schema as the table ** or else it must be a TEMP trigger. */ assert( p->pSchema!=0 ); assert( p->pTabSchema!=0 ); assert( p->pSchema==p->pTabSchema || p->pSchema==pParse->db->aDb[1].pSchema ); /* Determine whether we should code this trigger */ if( p->op==op && p->tr_tm==tr_tm && checkColumnOverlap(p->pColumns, pChanges) ){ sqlite3CodeRowTriggerDirect(pParse, p, pTab, reg, orconf, ignoreJump); } } } /* ** Triggers may access values stored in the old.* or new.* pseudo-table. ** This function returns a 32-bit bitmask indicating which columns of the ** old.* or new.* tables actually are used by triggers. This information ** may be used by the caller, for example, to avoid having to load the entire ** old.* record into memory when executing an UPDATE or DELETE command. ** ** Bit 0 of the returned mask is set if the left-most column of the ** table may be accessed using an [old|new].reference. Bit 1 is set if ** the second leftmost column value is required, and so on. If there ** are more than 32 columns in the table, and at least one of the columns ** with an index greater than 32 may be accessed, 0xffffffff is returned. ** ** It is not possible to determine if the old.rowid or new.rowid column is ** accessed by triggers. The caller must always assume that it is. ** ** Parameter isNew must be either 1 or 0. If it is 0, then the mask returned ** applies to the old.* table. If 1, the new.* table. ** ** Parameter tr_tm must be a mask with one or both of the TRIGGER_BEFORE ** and TRIGGER_AFTER bits set. Values accessed by BEFORE triggers are only ** included in the returned mask if the TRIGGER_BEFORE bit is set in the ** tr_tm parameter. Similarly, values accessed by AFTER triggers are only ** included in the returned mask if the TRIGGER_AFTER bit is set in tr_tm. */ SQLITE_PRIVATE u32 sqlite3TriggerColmask( Parse *pParse, /* Parse context */ Trigger *pTrigger, /* List of triggers on table pTab */ ExprList *pChanges, /* Changes list for any UPDATE OF triggers */ int isNew, /* 1 for new.* ref mask, 0 for old.* ref mask */ int tr_tm, /* Mask of TRIGGER_BEFORE|TRIGGER_AFTER */ Table *pTab, /* The table to code triggers from */ int orconf /* Default ON CONFLICT policy for trigger steps */ ){ const int op = pChanges ? TK_UPDATE : TK_DELETE; u32 mask = 0; Trigger *p; assert( isNew==1 || isNew==0 ); for(p=pTrigger; p; p=p->pNext){ if( p->op==op && (tr_tm&p->tr_tm) && checkColumnOverlap(p->pColumns,pChanges) ){ TriggerPrg *pPrg; pPrg = getRowTrigger(pParse, p, pTab, orconf); if( pPrg ){ mask |= pPrg->aColmask[isNew]; } } } return mask; } #endif /* !defined(SQLITE_OMIT_TRIGGER) */ /************** End of trigger.c *********************************************/ /************** Begin file update.c ******************************************/ /* ** 2001 September 15 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ************************************************************************* ** This file contains C code routines that are called by the parser ** to handle UPDATE statements. */ /* #include "sqliteInt.h" */ #ifndef SQLITE_OMIT_VIRTUALTABLE /* Forward declaration */ static void updateVirtualTable( Parse *pParse, /* The parsing context */ SrcList *pSrc, /* The virtual table to be modified */ Table *pTab, /* The virtual table */ ExprList *pChanges, /* The columns to change in the UPDATE statement */ Expr *pRowidExpr, /* Expression used to recompute the rowid */ int *aXRef, /* Mapping from columns of pTab to entries in pChanges */ Expr *pWhere, /* WHERE clause of the UPDATE statement */ int onError /* ON CONFLICT strategy */ ); #endif /* SQLITE_OMIT_VIRTUALTABLE */ /* ** The most recently coded instruction was an OP_Column to retrieve the ** i-th column of table pTab. This routine sets the P4 parameter of the ** OP_Column to the default value, if any. ** ** The default value of a column is specified by a DEFAULT clause in the ** column definition. This was either supplied by the user when the table ** was created, or added later to the table definition by an ALTER TABLE ** command. If the latter, then the row-records in the table btree on disk ** may not contain a value for the column and the default value, taken ** from the P4 parameter of the OP_Column instruction, is returned instead. ** If the former, then all row-records are guaranteed to include a value ** for the column and the P4 value is not required. ** ** Column definitions created by an ALTER TABLE command may only have ** literal default values specified: a number, null or a string. (If a more ** complicated default expression value was provided, it is evaluated ** when the ALTER TABLE is executed and one of the literal values written ** into the sqlite_master table.) ** ** Therefore, the P4 parameter is only required if the default value for ** the column is a literal number, string or null. The sqlite3ValueFromExpr() ** function is capable of transforming these types of expressions into ** sqlite3_value objects. ** ** If parameter iReg is not negative, code an OP_RealAffinity instruction ** on register iReg. This is used when an equivalent integer value is ** stored in place of an 8-byte floating point value in order to save ** space. */ SQLITE_PRIVATE void sqlite3ColumnDefault(Vdbe *v, Table *pTab, int i, int iReg){ assert( pTab!=0 ); if( !pTab->pSelect ){ sqlite3_value *pValue = 0; u8 enc = ENC(sqlite3VdbeDb(v)); Column *pCol = &pTab->aCol[i]; VdbeComment((v, "%s.%s", pTab->zName, pCol->zName)); assert( inCol ); sqlite3ValueFromExpr(sqlite3VdbeDb(v), pCol->pDflt, enc, pCol->affinity, &pValue); if( pValue ){ sqlite3VdbeChangeP4(v, -1, (const char *)pValue, P4_MEM); } #ifndef SQLITE_OMIT_FLOATING_POINT if( pTab->aCol[i].affinity==SQLITE_AFF_REAL ){ sqlite3VdbeAddOp1(v, OP_RealAffinity, iReg); } #endif } } /* ** Process an UPDATE statement. ** ** UPDATE OR IGNORE table_wxyz SET a=b, c=d WHERE e<5 AND f NOT NULL; ** \_______/ \________/ \______/ \________________/ * onError pTabList pChanges pWhere */ SQLITE_PRIVATE void sqlite3Update( Parse *pParse, /* The parser context */ SrcList *pTabList, /* The table in which we should change things */ ExprList *pChanges, /* Things to be changed */ Expr *pWhere, /* The WHERE clause. May be null */ int onError /* How to handle constraint errors */ ){ int i, j; /* Loop counters */ Table *pTab; /* The table to be updated */ int addrTop = 0; /* VDBE instruction address of the start of the loop */ WhereInfo *pWInfo; /* Information about the WHERE clause */ Vdbe *v; /* The virtual database engine */ Index *pIdx; /* For looping over indices */ Index *pPk; /* The PRIMARY KEY index for WITHOUT ROWID tables */ int nIdx; /* Number of indices that need updating */ int iBaseCur; /* Base cursor number */ int iDataCur; /* Cursor for the canonical data btree */ int iIdxCur; /* Cursor for the first index */ sqlite3 *db; /* The database structure */ int *aRegIdx = 0; /* One register assigned to each index to be updated */ int *aXRef = 0; /* aXRef[i] is the index in pChanges->a[] of the ** an expression for the i-th column of the table. ** aXRef[i]==-1 if the i-th column is not changed. */ u8 *aToOpen; /* 1 for tables and indices to be opened */ u8 chngPk; /* PRIMARY KEY changed in a WITHOUT ROWID table */ u8 chngRowid; /* Rowid changed in a normal table */ u8 chngKey; /* Either chngPk or chngRowid */ Expr *pRowidExpr = 0; /* Expression defining the new record number */ AuthContext sContext; /* The authorization context */ NameContext sNC; /* The name-context to resolve expressions in */ int iDb; /* Database containing the table being updated */ int okOnePass; /* True for one-pass algorithm without the FIFO */ int hasFK; /* True if foreign key processing is required */ int labelBreak; /* Jump here to break out of UPDATE loop */ int labelContinue; /* Jump here to continue next step of UPDATE loop */ #ifndef SQLITE_OMIT_TRIGGER int isView; /* True when updating a view (INSTEAD OF trigger) */ Trigger *pTrigger; /* List of triggers on pTab, if required */ int tmask; /* Mask of TRIGGER_BEFORE|TRIGGER_AFTER */ #endif int newmask; /* Mask of NEW.* columns accessed by BEFORE triggers */ int iEph = 0; /* Ephemeral table holding all primary key values */ int nKey = 0; /* Number of elements in regKey for WITHOUT ROWID */ int aiCurOnePass[2]; /* The write cursors opened by WHERE_ONEPASS */ /* Register Allocations */ int regRowCount = 0; /* A count of rows changed */ int regOldRowid = 0; /* The old rowid */ int regNewRowid = 0; /* The new rowid */ int regNew = 0; /* Content of the NEW.* table in triggers */ int regOld = 0; /* Content of OLD.* table in triggers */ int regRowSet = 0; /* Rowset of rows to be updated */ int regKey = 0; /* composite PRIMARY KEY value */ memset(&sContext, 0, sizeof(sContext)); db = pParse->db; if( pParse->nErr || db->mallocFailed ){ goto update_cleanup; } assert( pTabList->nSrc==1 ); /* Locate the table which we want to update. */ pTab = sqlite3SrcListLookup(pParse, pTabList); if( pTab==0 ) goto update_cleanup; iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema); /* Figure out if we have any triggers and if the table being ** updated is a view. */ #ifndef SQLITE_OMIT_TRIGGER pTrigger = sqlite3TriggersExist(pParse, pTab, TK_UPDATE, pChanges, &tmask); isView = pTab->pSelect!=0; assert( pTrigger || tmask==0 ); #else # define pTrigger 0 # define isView 0 # define tmask 0 #endif #ifdef SQLITE_OMIT_VIEW # undef isView # define isView 0 #endif if( sqlite3ViewGetColumnNames(pParse, pTab) ){ goto update_cleanup; } if( sqlite3IsReadOnly(pParse, pTab, tmask) ){ goto update_cleanup; } /* Allocate a cursors for the main database table and for all indices. ** The index cursors might not be used, but if they are used they ** need to occur right after the database cursor. So go ahead and ** allocate enough space, just in case. */ pTabList->a[0].iCursor = iBaseCur = iDataCur = pParse->nTab++; iIdxCur = iDataCur+1; pPk = HasRowid(pTab) ? 0 : sqlite3PrimaryKeyIndex(pTab); for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){ if( IsPrimaryKeyIndex(pIdx) && pPk!=0 ){ iDataCur = pParse->nTab; pTabList->a[0].iCursor = iDataCur; } pParse->nTab++; } /* Allocate space for aXRef[], aRegIdx[], and aToOpen[]. ** Initialize aXRef[] and aToOpen[] to their default values. */ aXRef = sqlite3DbMallocRawNN(db, sizeof(int) * (pTab->nCol+nIdx) + nIdx+2 ); if( aXRef==0 ) goto update_cleanup; aRegIdx = aXRef+pTab->nCol; aToOpen = (u8*)(aRegIdx+nIdx); memset(aToOpen, 1, nIdx+1); aToOpen[nIdx+1] = 0; for(i=0; inCol; i++) aXRef[i] = -1; /* Initialize the name-context */ memset(&sNC, 0, sizeof(sNC)); sNC.pParse = pParse; sNC.pSrcList = pTabList; /* Resolve the column names in all the expressions of the ** of the UPDATE statement. Also find the column index ** for each column to be updated in the pChanges array. For each ** column to be updated, make sure we have authorization to change ** that column. */ chngRowid = chngPk = 0; for(i=0; inExpr; i++){ if( sqlite3ResolveExprNames(&sNC, pChanges->a[i].pExpr) ){ goto update_cleanup; } for(j=0; jnCol; j++){ if( sqlite3StrICmp(pTab->aCol[j].zName, pChanges->a[i].zName)==0 ){ if( j==pTab->iPKey ){ chngRowid = 1; pRowidExpr = pChanges->a[i].pExpr; }else if( pPk && (pTab->aCol[j].colFlags & COLFLAG_PRIMKEY)!=0 ){ chngPk = 1; } aXRef[j] = i; break; } } if( j>=pTab->nCol ){ if( pPk==0 && sqlite3IsRowid(pChanges->a[i].zName) ){ j = -1; chngRowid = 1; pRowidExpr = pChanges->a[i].pExpr; }else{ sqlite3ErrorMsg(pParse, "no such column: %s", pChanges->a[i].zName); pParse->checkSchema = 1; goto update_cleanup; } } #ifndef SQLITE_OMIT_AUTHORIZATION { int rc; rc = sqlite3AuthCheck(pParse, SQLITE_UPDATE, pTab->zName, j<0 ? "ROWID" : pTab->aCol[j].zName, db->aDb[iDb].zDbSName); if( rc==SQLITE_DENY ){ goto update_cleanup; }else if( rc==SQLITE_IGNORE ){ aXRef[j] = -1; } } #endif } assert( (chngRowid & chngPk)==0 ); assert( chngRowid==0 || chngRowid==1 ); assert( chngPk==0 || chngPk==1 ); chngKey = chngRowid + chngPk; /* The SET expressions are not actually used inside the WHERE loop. ** So reset the colUsed mask. Unless this is a virtual table. In that ** case, set all bits of the colUsed mask (to ensure that the virtual ** table implementation makes all columns available). */ pTabList->a[0].colUsed = IsVirtual(pTab) ? ALLBITS : 0; hasFK = sqlite3FkRequired(pParse, pTab, aXRef, chngKey); /* There is one entry in the aRegIdx[] array for each index on the table ** being updated. Fill in aRegIdx[] with a register number that will hold ** the key for accessing each index. ** ** FIXME: Be smarter about omitting indexes that use expressions. */ for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){ int reg; if( chngKey || hasFK || pIdx->pPartIdxWhere || pIdx==pPk ){ reg = ++pParse->nMem; }else{ reg = 0; for(i=0; inKeyCol; i++){ i16 iIdxCol = pIdx->aiColumn[i]; if( iIdxCol<0 || aXRef[iIdxCol]>=0 ){ reg = ++pParse->nMem; break; } } } if( reg==0 ) aToOpen[j+1] = 0; aRegIdx[j] = reg; } /* Begin generating code. */ v = sqlite3GetVdbe(pParse); if( v==0 ) goto update_cleanup; if( pParse->nested==0 ) sqlite3VdbeCountChanges(v); sqlite3BeginWriteOperation(pParse, 1, iDb); /* Allocate required registers. */ if( !IsVirtual(pTab) ){ regRowSet = ++pParse->nMem; regOldRowid = regNewRowid = ++pParse->nMem; if( chngPk || pTrigger || hasFK ){ regOld = pParse->nMem + 1; pParse->nMem += pTab->nCol; } if( chngKey || pTrigger || hasFK ){ regNewRowid = ++pParse->nMem; } regNew = pParse->nMem + 1; pParse->nMem += pTab->nCol; } /* Start the view context. */ if( isView ){ sqlite3AuthContextPush(pParse, &sContext, pTab->zName); } /* If we are trying to update a view, realize that view into ** an ephemeral table. */ #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER) if( isView ){ sqlite3MaterializeView(pParse, pTab, pWhere, iDataCur); } #endif /* Resolve the column names in all the expressions in the ** WHERE clause. */ if( sqlite3ResolveExprNames(&sNC, pWhere) ){ goto update_cleanup; } #ifndef SQLITE_OMIT_VIRTUALTABLE /* Virtual tables must be handled separately */ if( IsVirtual(pTab) ){ updateVirtualTable(pParse, pTabList, pTab, pChanges, pRowidExpr, aXRef, pWhere, onError); goto update_cleanup; } #endif /* Begin the database scan */ if( HasRowid(pTab) ){ sqlite3VdbeAddOp3(v, OP_Null, 0, regRowSet, regOldRowid); pWInfo = sqlite3WhereBegin( pParse, pTabList, pWhere, 0, 0, WHERE_ONEPASS_DESIRED | WHERE_SEEK_TABLE, iIdxCur ); if( pWInfo==0 ) goto update_cleanup; okOnePass = sqlite3WhereOkOnePass(pWInfo, aiCurOnePass); /* Remember the rowid of every item to be updated. */ sqlite3VdbeAddOp2(v, OP_Rowid, iDataCur, regOldRowid); if( !okOnePass ){ sqlite3VdbeAddOp2(v, OP_RowSetAdd, regRowSet, regOldRowid); } /* End the database scan loop. */ sqlite3WhereEnd(pWInfo); }else{ int iPk; /* First of nPk memory cells holding PRIMARY KEY value */ i16 nPk; /* Number of components of the PRIMARY KEY */ int addrOpen; /* Address of the OpenEphemeral instruction */ assert( pPk!=0 ); nPk = pPk->nKeyCol; iPk = pParse->nMem+1; pParse->nMem += nPk; regKey = ++pParse->nMem; iEph = pParse->nTab++; sqlite3VdbeAddOp2(v, OP_Null, 0, iPk); addrOpen = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, iEph, nPk); sqlite3VdbeSetP4KeyInfo(pParse, pPk); pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, 0, 0, WHERE_ONEPASS_DESIRED, iIdxCur); if( pWInfo==0 ) goto update_cleanup; okOnePass = sqlite3WhereOkOnePass(pWInfo, aiCurOnePass); for(i=0; iaiColumn[i]>=0 ); sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, pPk->aiColumn[i], iPk+i); } if( okOnePass ){ sqlite3VdbeChangeToNoop(v, addrOpen); nKey = nPk; regKey = iPk; }else{ sqlite3VdbeAddOp4(v, OP_MakeRecord, iPk, nPk, regKey, sqlite3IndexAffinityStr(db, pPk), nPk); sqlite3VdbeAddOp2(v, OP_IdxInsert, iEph, regKey); } sqlite3WhereEnd(pWInfo); } /* Initialize the count of updated rows */ if( (db->flags & SQLITE_CountRows) && !pParse->pTriggerTab ){ regRowCount = ++pParse->nMem; sqlite3VdbeAddOp2(v, OP_Integer, 0, regRowCount); } labelBreak = sqlite3VdbeMakeLabel(v); if( !isView ){ /* ** Open every index that needs updating. Note that if any ** index could potentially invoke a REPLACE conflict resolution ** action, then we need to open all indices because we might need ** to be deleting some records. */ if( onError==OE_Replace ){ memset(aToOpen, 1, nIdx+1); }else{ for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){ if( pIdx->onError==OE_Replace ){ memset(aToOpen, 1, nIdx+1); break; } } } if( okOnePass ){ if( aiCurOnePass[0]>=0 ) aToOpen[aiCurOnePass[0]-iBaseCur] = 0; if( aiCurOnePass[1]>=0 ) aToOpen[aiCurOnePass[1]-iBaseCur] = 0; } sqlite3OpenTableAndIndices(pParse, pTab, OP_OpenWrite, 0, iBaseCur, aToOpen, 0, 0); } /* Top of the update loop */ if( okOnePass ){ if( aToOpen[iDataCur-iBaseCur] && !isView ){ assert( pPk ); sqlite3VdbeAddOp4Int(v, OP_NotFound, iDataCur, labelBreak, regKey, nKey); VdbeCoverageNeverTaken(v); } labelContinue = labelBreak; sqlite3VdbeAddOp2(v, OP_IsNull, pPk ? regKey : regOldRowid, labelBreak); VdbeCoverageIf(v, pPk==0); VdbeCoverageIf(v, pPk!=0); }else if( pPk ){ labelContinue = sqlite3VdbeMakeLabel(v); sqlite3VdbeAddOp2(v, OP_Rewind, iEph, labelBreak); VdbeCoverage(v); addrTop = sqlite3VdbeAddOp2(v, OP_RowKey, iEph, regKey); sqlite3VdbeAddOp4Int(v, OP_NotFound, iDataCur, labelContinue, regKey, 0); VdbeCoverage(v); }else{ labelContinue = sqlite3VdbeAddOp3(v, OP_RowSetRead, regRowSet, labelBreak, regOldRowid); VdbeCoverage(v); sqlite3VdbeAddOp3(v, OP_NotExists, iDataCur, labelContinue, regOldRowid); VdbeCoverage(v); } /* If the record number will change, set register regNewRowid to ** contain the new value. If the record number is not being modified, ** then regNewRowid is the same register as regOldRowid, which is ** already populated. */ assert( chngKey || pTrigger || hasFK || regOldRowid==regNewRowid ); if( chngRowid ){ sqlite3ExprCode(pParse, pRowidExpr, regNewRowid); sqlite3VdbeAddOp1(v, OP_MustBeInt, regNewRowid); VdbeCoverage(v); } /* Compute the old pre-UPDATE content of the row being changed, if that ** information is needed */ if( chngPk || hasFK || pTrigger ){ u32 oldmask = (hasFK ? sqlite3FkOldmask(pParse, pTab) : 0); oldmask |= sqlite3TriggerColmask(pParse, pTrigger, pChanges, 0, TRIGGER_BEFORE|TRIGGER_AFTER, pTab, onError ); for(i=0; inCol; i++){ if( oldmask==0xffffffff || (i<32 && (oldmask & MASKBIT32(i))!=0) || (pTab->aCol[i].colFlags & COLFLAG_PRIMKEY)!=0 ){ testcase( oldmask!=0xffffffff && i==31 ); sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, i, regOld+i); }else{ sqlite3VdbeAddOp2(v, OP_Null, 0, regOld+i); } } if( chngRowid==0 && pPk==0 ){ sqlite3VdbeAddOp2(v, OP_Copy, regOldRowid, regNewRowid); } } /* Populate the array of registers beginning at regNew with the new ** row data. This array is used to check constants, create the new ** table and index records, and as the values for any new.* references ** made by triggers. ** ** If there are one or more BEFORE triggers, then do not populate the ** registers associated with columns that are (a) not modified by ** this UPDATE statement and (b) not accessed by new.* references. The ** values for registers not modified by the UPDATE must be reloaded from ** the database after the BEFORE triggers are fired anyway (as the trigger ** may have modified them). So not loading those that are not going to ** be used eliminates some redundant opcodes. */ newmask = sqlite3TriggerColmask( pParse, pTrigger, pChanges, 1, TRIGGER_BEFORE, pTab, onError ); for(i=0; inCol; i++){ if( i==pTab->iPKey ){ sqlite3VdbeAddOp2(v, OP_Null, 0, regNew+i); }else{ j = aXRef[i]; if( j>=0 ){ sqlite3ExprCode(pParse, pChanges->a[j].pExpr, regNew+i); }else if( 0==(tmask&TRIGGER_BEFORE) || i>31 || (newmask & MASKBIT32(i)) ){ /* This branch loads the value of a column that will not be changed ** into a register. This is done if there are no BEFORE triggers, or ** if there are one or more BEFORE triggers that use this value via ** a new.* reference in a trigger program. */ testcase( i==31 ); testcase( i==32 ); sqlite3ExprCodeGetColumnToReg(pParse, pTab, i, iDataCur, regNew+i); }else{ sqlite3VdbeAddOp2(v, OP_Null, 0, regNew+i); } } } /* Fire any BEFORE UPDATE triggers. This happens before constraints are ** verified. One could argue that this is wrong. */ if( tmask&TRIGGER_BEFORE ){ sqlite3TableAffinity(v, pTab, regNew); sqlite3CodeRowTrigger(pParse, pTrigger, TK_UPDATE, pChanges, TRIGGER_BEFORE, pTab, regOldRowid, onError, labelContinue); /* The row-trigger may have deleted the row being updated. In this ** case, jump to the next row. No updates or AFTER triggers are ** required. This behavior - what happens when the row being updated ** is deleted or renamed by a BEFORE trigger - is left undefined in the ** documentation. */ if( pPk ){ sqlite3VdbeAddOp4Int(v, OP_NotFound, iDataCur, labelContinue,regKey,nKey); VdbeCoverage(v); }else{ sqlite3VdbeAddOp3(v, OP_NotExists, iDataCur, labelContinue, regOldRowid); VdbeCoverage(v); } /* If it did not delete it, the row-trigger may still have modified ** some of the columns of the row being updated. Load the values for ** all columns not modified by the update statement into their ** registers in case this has happened. */ for(i=0; inCol; i++){ if( aXRef[i]<0 && i!=pTab->iPKey ){ sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, i, regNew+i); } } } if( !isView ){ int addr1 = 0; /* Address of jump instruction */ int bReplace = 0; /* True if REPLACE conflict resolution might happen */ /* Do constraint checks. */ assert( regOldRowid>0 ); sqlite3GenerateConstraintChecks(pParse, pTab, aRegIdx, iDataCur, iIdxCur, regNewRowid, regOldRowid, chngKey, onError, labelContinue, &bReplace, aXRef); /* Do FK constraint checks. */ if( hasFK ){ sqlite3FkCheck(pParse, pTab, regOldRowid, 0, aXRef, chngKey); } /* Delete the index entries associated with the current record. */ if( bReplace || chngKey ){ if( pPk ){ addr1 = sqlite3VdbeAddOp4Int(v, OP_NotFound, iDataCur, 0, regKey, nKey); }else{ addr1 = sqlite3VdbeAddOp3(v, OP_NotExists, iDataCur, 0, regOldRowid); } VdbeCoverageNeverTaken(v); } sqlite3GenerateRowIndexDelete(pParse, pTab, iDataCur, iIdxCur, aRegIdx, -1); /* If changing the rowid value, or if there are foreign key constraints ** to process, delete the old record. Otherwise, add a noop OP_Delete ** to invoke the pre-update hook. ** ** That (regNew==regnewRowid+1) is true is also important for the ** pre-update hook. If the caller invokes preupdate_new(), the returned ** value is copied from memory cell (regNewRowid+1+iCol), where iCol ** is the column index supplied by the user. */ assert( regNew==regNewRowid+1 ); #ifdef SQLITE_ENABLE_PREUPDATE_HOOK sqlite3VdbeAddOp3(v, OP_Delete, iDataCur, OPFLAG_ISUPDATE | ((hasFK || chngKey || pPk!=0) ? 0 : OPFLAG_ISNOOP), regNewRowid ); if( !pParse->nested ){ sqlite3VdbeChangeP4(v, -1, (char*)pTab, P4_TABLE); } #else if( hasFK || chngKey || pPk!=0 ){ sqlite3VdbeAddOp2(v, OP_Delete, iDataCur, 0); } #endif if( bReplace || chngKey ){ sqlite3VdbeJumpHere(v, addr1); } if( hasFK ){ sqlite3FkCheck(pParse, pTab, 0, regNewRowid, aXRef, chngKey); } /* Insert the new index entries and the new record. */ sqlite3CompleteInsertion(pParse, pTab, iDataCur, iIdxCur, regNewRowid, aRegIdx, 1, 0, 0); /* Do any ON CASCADE, SET NULL or SET DEFAULT operations required to ** handle rows (possibly in other tables) that refer via a foreign key ** to the row just updated. */ if( hasFK ){ sqlite3FkActions(pParse, pTab, pChanges, regOldRowid, aXRef, chngKey); } } /* Increment the row counter */ if( (db->flags & SQLITE_CountRows) && !pParse->pTriggerTab){ sqlite3VdbeAddOp2(v, OP_AddImm, regRowCount, 1); } sqlite3CodeRowTrigger(pParse, pTrigger, TK_UPDATE, pChanges, TRIGGER_AFTER, pTab, regOldRowid, onError, labelContinue); /* Repeat the above with the next record to be updated, until ** all record selected by the WHERE clause have been updated. */ if( okOnePass ){ /* Nothing to do at end-of-loop for a single-pass */ }else if( pPk ){ sqlite3VdbeResolveLabel(v, labelContinue); sqlite3VdbeAddOp2(v, OP_Next, iEph, addrTop); VdbeCoverage(v); }else{ sqlite3VdbeGoto(v, labelContinue); } sqlite3VdbeResolveLabel(v, labelBreak); /* Close all tables */ for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){ assert( aRegIdx ); if( aToOpen[i+1] ){ sqlite3VdbeAddOp2(v, OP_Close, iIdxCur+i, 0); } } if( iDataCurnested==0 && pParse->pTriggerTab==0 ){ sqlite3AutoincrementEnd(pParse); } /* ** Return the number of rows that were changed. If this routine is ** generating code because of a call to sqlite3NestedParse(), do not ** invoke the callback function. */ if( (db->flags&SQLITE_CountRows) && !pParse->pTriggerTab && !pParse->nested ){ sqlite3VdbeAddOp2(v, OP_ResultRow, regRowCount, 1); sqlite3VdbeSetNumCols(v, 1); sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows updated", SQLITE_STATIC); } update_cleanup: sqlite3AuthContextPop(&sContext); sqlite3DbFree(db, aXRef); /* Also frees aRegIdx[] and aToOpen[] */ sqlite3SrcListDelete(db, pTabList); sqlite3ExprListDelete(db, pChanges); sqlite3ExprDelete(db, pWhere); return; } /* Make sure "isView" and other macros defined above are undefined. Otherwise ** they may interfere with compilation of other functions in this file ** (or in another file, if this file becomes part of the amalgamation). */ #ifdef isView #undef isView #endif #ifdef pTrigger #undef pTrigger #endif #ifndef SQLITE_OMIT_VIRTUALTABLE /* ** Generate code for an UPDATE of a virtual table. ** ** There are two possible strategies - the default and the special ** "onepass" strategy. Onepass is only used if the virtual table ** implementation indicates that pWhere may match at most one row. ** ** The default strategy is to create an ephemeral table that contains ** for each row to be changed: ** ** (A) The original rowid of that row. ** (B) The revised rowid for the row. ** (C) The content of every column in the row. ** ** Then loop through the contents of this ephemeral table executing a ** VUpdate for each row. When finished, drop the ephemeral table. ** ** The "onepass" strategy does not use an ephemeral table. Instead, it ** stores the same values (A, B and C above) in a register array and ** makes a single invocation of VUpdate. */ static void updateVirtualTable( Parse *pParse, /* The parsing context */ SrcList *pSrc, /* The virtual table to be modified */ Table *pTab, /* The virtual table */ ExprList *pChanges, /* The columns to change in the UPDATE statement */ Expr *pRowid, /* Expression used to recompute the rowid */ int *aXRef, /* Mapping from columns of pTab to entries in pChanges */ Expr *pWhere, /* WHERE clause of the UPDATE statement */ int onError /* ON CONFLICT strategy */ ){ Vdbe *v = pParse->pVdbe; /* Virtual machine under construction */ int ephemTab; /* Table holding the result of the SELECT */ int i; /* Loop counter */ sqlite3 *db = pParse->db; /* Database connection */ const char *pVTab = (const char*)sqlite3GetVTable(db, pTab); WhereInfo *pWInfo; int nArg = 2 + pTab->nCol; /* Number of arguments to VUpdate */ int regArg; /* First register in VUpdate arg array */ int regRec; /* Register in which to assemble record */ int regRowid; /* Register for ephem table rowid */ int iCsr = pSrc->a[0].iCursor; /* Cursor used for virtual table scan */ int aDummy[2]; /* Unused arg for sqlite3WhereOkOnePass() */ int bOnePass; /* True to use onepass strategy */ int addr; /* Address of OP_OpenEphemeral */ /* Allocate nArg registers to martial the arguments to VUpdate. Then ** create and open the ephemeral table in which the records created from ** these arguments will be temporarily stored. */ assert( v ); ephemTab = pParse->nTab++; addr= sqlite3VdbeAddOp2(v, OP_OpenEphemeral, ephemTab, nArg); regArg = pParse->nMem + 1; pParse->nMem += nArg; regRec = ++pParse->nMem; regRowid = ++pParse->nMem; /* Start scanning the virtual table */ pWInfo = sqlite3WhereBegin(pParse, pSrc, pWhere, 0,0,WHERE_ONEPASS_DESIRED,0); if( pWInfo==0 ) return; /* Populate the argument registers. */ sqlite3VdbeAddOp2(v, OP_Rowid, iCsr, regArg); if( pRowid ){ sqlite3ExprCode(pParse, pRowid, regArg+1); }else{ sqlite3VdbeAddOp2(v, OP_Rowid, iCsr, regArg+1); } for(i=0; inCol; i++){ if( aXRef[i]>=0 ){ sqlite3ExprCode(pParse, pChanges->a[aXRef[i]].pExpr, regArg+2+i); }else{ sqlite3VdbeAddOp3(v, OP_VColumn, iCsr, i, regArg+2+i); } } bOnePass = sqlite3WhereOkOnePass(pWInfo, aDummy); if( bOnePass ){ /* If using the onepass strategy, no-op out the OP_OpenEphemeral coded ** above. Also, if this is a top-level parse (not a trigger), clear the ** multi-write flag so that the VM does not open a statement journal */ sqlite3VdbeChangeToNoop(v, addr); if( sqlite3IsToplevel(pParse) ){ pParse->isMultiWrite = 0; } }else{ /* Create a record from the argument register contents and insert it into ** the ephemeral table. */ sqlite3VdbeAddOp3(v, OP_MakeRecord, regArg, nArg, regRec); sqlite3VdbeAddOp2(v, OP_NewRowid, ephemTab, regRowid); sqlite3VdbeAddOp3(v, OP_Insert, ephemTab, regRec, regRowid); } if( bOnePass==0 ){ /* End the virtual table scan */ sqlite3WhereEnd(pWInfo); /* Begin scannning through the ephemeral table. */ addr = sqlite3VdbeAddOp1(v, OP_Rewind, ephemTab); VdbeCoverage(v); /* Extract arguments from the current row of the ephemeral table and ** invoke the VUpdate method. */ for(i=0; i=2 || iDb==0) ){ sqlite3VdbeAddOp1(v, OP_Vacuum, iDb); sqlite3VdbeUsesBtree(v, iDb); } return; } /* ** This routine implements the OP_Vacuum opcode of the VDBE. */ SQLITE_PRIVATE int sqlite3RunVacuum(char **pzErrMsg, sqlite3 *db, int iDb){ int rc = SQLITE_OK; /* Return code from service routines */ Btree *pMain; /* The database being vacuumed */ Btree *pTemp; /* The temporary database we vacuum into */ int saved_flags; /* Saved value of the db->flags */ int saved_nChange; /* Saved value of db->nChange */ int saved_nTotalChange; /* Saved value of db->nTotalChange */ u8 saved_mTrace; /* Saved trace settings */ Db *pDb = 0; /* Database to detach at end of vacuum */ int isMemDb; /* True if vacuuming a :memory: database */ int nRes; /* Bytes of reserved space at the end of each page */ int nDb; /* Number of attached databases */ const char *zDbMain; /* Schema name of database to vacuum */ if( !db->autoCommit ){ sqlite3SetString(pzErrMsg, db, "cannot VACUUM from within a transaction"); return SQLITE_ERROR; } if( db->nVdbeActive>1 ){ sqlite3SetString(pzErrMsg, db,"cannot VACUUM - SQL statements in progress"); return SQLITE_ERROR; } /* Save the current value of the database flags so that it can be ** restored before returning. Then set the writable-schema flag, and ** disable CHECK and foreign key constraints. */ saved_flags = db->flags; saved_nChange = db->nChange; saved_nTotalChange = db->nTotalChange; saved_mTrace = db->mTrace; db->flags |= (SQLITE_WriteSchema | SQLITE_IgnoreChecks | SQLITE_PreferBuiltin | SQLITE_Vacuum); db->flags &= ~(SQLITE_ForeignKeys | SQLITE_ReverseOrder | SQLITE_CountRows); db->mTrace = 0; zDbMain = db->aDb[iDb].zDbSName; pMain = db->aDb[iDb].pBt; isMemDb = sqlite3PagerIsMemdb(sqlite3BtreePager(pMain)); /* Attach the temporary database as 'vacuum_db'. The synchronous pragma ** can be set to 'off' for this file, as it is not recovered if a crash ** occurs anyway. The integrity of the database is maintained by a ** (possibly synchronous) transaction opened on the main database before ** sqlite3BtreeCopyFile() is called. ** ** An optimisation would be to use a non-journaled pager. ** (Later:) I tried setting "PRAGMA vacuum_db.journal_mode=OFF" but ** that actually made the VACUUM run slower. Very little journalling ** actually occurs when doing a vacuum since the vacuum_db is initially ** empty. Only the journal header is written. Apparently it takes more ** time to parse and run the PRAGMA to turn journalling off than it does ** to write the journal header file. */ nDb = db->nDb; rc = execSql(db, pzErrMsg, "ATTACH''AS vacuum_db"); if( rc!=SQLITE_OK ) goto end_of_vacuum; assert( (db->nDb-1)==nDb ); pDb = &db->aDb[nDb]; assert( strcmp(pDb->zDbSName,"vacuum_db")==0 ); pTemp = pDb->pBt; /* The call to execSql() to attach the temp database has left the file ** locked (as there was more than one active statement when the transaction ** to read the schema was concluded. Unlock it here so that this doesn't ** cause problems for the call to BtreeSetPageSize() below. */ sqlite3BtreeCommit(pTemp); nRes = sqlite3BtreeGetOptimalReserve(pMain); /* A VACUUM cannot change the pagesize of an encrypted database. */ #ifdef SQLITE_HAS_CODEC if( db->nextPagesize ){ extern void sqlite3CodecGetKey(sqlite3*, int, void**, int*); int nKey; char *zKey; sqlite3CodecGetKey(db, 0, (void**)&zKey, &nKey); if( nKey ) db->nextPagesize = 0; } #endif sqlite3BtreeSetCacheSize(pTemp, db->aDb[iDb].pSchema->cache_size); sqlite3BtreeSetSpillSize(pTemp, sqlite3BtreeSetSpillSize(pMain,0)); sqlite3BtreeSetPagerFlags(pTemp, PAGER_SYNCHRONOUS_OFF|PAGER_CACHESPILL); /* Begin a transaction and take an exclusive lock on the main database ** file. This is done before the sqlite3BtreeGetPageSize(pMain) call below, ** to ensure that we do not try to change the page-size on a WAL database. */ rc = execSql(db, pzErrMsg, "BEGIN"); if( rc!=SQLITE_OK ) goto end_of_vacuum; rc = sqlite3BtreeBeginTrans(pMain, 2); if( rc!=SQLITE_OK ) goto end_of_vacuum; /* Do not attempt to change the page size for a WAL database */ if( sqlite3PagerGetJournalMode(sqlite3BtreePager(pMain)) ==PAGER_JOURNALMODE_WAL ){ db->nextPagesize = 0; } if( sqlite3BtreeSetPageSize(pTemp, sqlite3BtreeGetPageSize(pMain), nRes, 0) || (!isMemDb && sqlite3BtreeSetPageSize(pTemp, db->nextPagesize, nRes, 0)) || NEVER(db->mallocFailed) ){ rc = SQLITE_NOMEM_BKPT; goto end_of_vacuum; } #ifndef SQLITE_OMIT_AUTOVACUUM sqlite3BtreeSetAutoVacuum(pTemp, db->nextAutovac>=0 ? db->nextAutovac : sqlite3BtreeGetAutoVacuum(pMain)); #endif /* Query the schema of the main database. Create a mirror schema ** in the temporary database. */ db->init.iDb = nDb; /* force new CREATE statements into vacuum_db */ rc = execSqlF(db, pzErrMsg, "SELECT sql FROM \"%w\".sqlite_master" " WHERE type='table'AND name<>'sqlite_sequence'" " AND coalesce(rootpage,1)>0", zDbMain ); if( rc!=SQLITE_OK ) goto end_of_vacuum; rc = execSqlF(db, pzErrMsg, "SELECT sql FROM \"%w\".sqlite_master" " WHERE type='index' AND length(sql)>10", zDbMain ); if( rc!=SQLITE_OK ) goto end_of_vacuum; db->init.iDb = 0; /* Loop through the tables in the main database. For each, do ** an "INSERT INTO vacuum_db.xxx SELECT * FROM main.xxx;" to copy ** the contents to the temporary database. */ rc = execSqlF(db, pzErrMsg, "SELECT'INSERT INTO vacuum_db.'||quote(name)" "||' SELECT*FROM\"%w\".'||quote(name)" "FROM vacuum_db.sqlite_master " "WHERE type='table'AND coalesce(rootpage,1)>0", zDbMain ); assert( (db->flags & SQLITE_Vacuum)!=0 ); db->flags &= ~SQLITE_Vacuum; if( rc!=SQLITE_OK ) goto end_of_vacuum; /* Copy the triggers, views, and virtual tables from the main database ** over to the temporary database. None of these objects has any ** associated storage, so all we have to do is copy their entries ** from the SQLITE_MASTER table. */ rc = execSqlF(db, pzErrMsg, "INSERT INTO vacuum_db.sqlite_master" " SELECT*FROM \"%w\".sqlite_master" " WHERE type IN('view','trigger')" " OR(type='table'AND rootpage=0)", zDbMain ); if( rc ) goto end_of_vacuum; /* At this point, there is a write transaction open on both the ** vacuum database and the main database. Assuming no error occurs, ** both transactions are closed by this block - the main database ** transaction by sqlite3BtreeCopyFile() and the other by an explicit ** call to sqlite3BtreeCommit(). */ { u32 meta; int i; /* This array determines which meta meta values are preserved in the ** vacuum. Even entries are the meta value number and odd entries ** are an increment to apply to the meta value after the vacuum. ** The increment is used to increase the schema cookie so that other ** connections to the same database will know to reread the schema. */ static const unsigned char aCopy[] = { BTREE_SCHEMA_VERSION, 1, /* Add one to the old schema cookie */ BTREE_DEFAULT_CACHE_SIZE, 0, /* Preserve the default page cache size */ BTREE_TEXT_ENCODING, 0, /* Preserve the text encoding */ BTREE_USER_VERSION, 0, /* Preserve the user version */ BTREE_APPLICATION_ID, 0, /* Preserve the application id */ }; assert( 1==sqlite3BtreeIsInTrans(pTemp) ); assert( 1==sqlite3BtreeIsInTrans(pMain) ); /* Copy Btree meta values */ for(i=0; iflags */ db->init.iDb = 0; db->flags = saved_flags; db->nChange = saved_nChange; db->nTotalChange = saved_nTotalChange; db->mTrace = saved_mTrace; sqlite3BtreeSetPageSize(pMain, -1, -1, 1); /* Currently there is an SQL level transaction open on the vacuum ** database. No locks are held on any other files (since the main file ** was committed at the btree level). So it safe to end the transaction ** by manually setting the autoCommit flag to true and detaching the ** vacuum database. The vacuum_db journal file is deleted when the pager ** is closed by the DETACH. */ db->autoCommit = 1; if( pDb ){ sqlite3BtreeClose(pDb->pBt); pDb->pBt = 0; pDb->pSchema = 0; } /* This both clears the schemas and reduces the size of the db->aDb[] ** array. */ sqlite3ResetAllSchemasOfConnection(db); return rc; } #endif /* SQLITE_OMIT_VACUUM && SQLITE_OMIT_ATTACH */ /************** End of vacuum.c **********************************************/ /************** Begin file vtab.c ********************************************/ /* ** 2006 June 10 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ************************************************************************* ** This file contains code used to help implement virtual tables. */ #ifndef SQLITE_OMIT_VIRTUALTABLE /* #include "sqliteInt.h" */ /* ** Before a virtual table xCreate() or xConnect() method is invoked, the ** sqlite3.pVtabCtx member variable is set to point to an instance of ** this struct allocated on the stack. It is used by the implementation of ** the sqlite3_declare_vtab() and sqlite3_vtab_config() APIs, both of which ** are invoked only from within xCreate and xConnect methods. */ struct VtabCtx { VTable *pVTable; /* The virtual table being constructed */ Table *pTab; /* The Table object to which the virtual table belongs */ VtabCtx *pPrior; /* Parent context (if any) */ int bDeclared; /* True after sqlite3_declare_vtab() is called */ }; /* ** The actual function that does the work of creating a new module. ** This function implements the sqlite3_create_module() and ** sqlite3_create_module_v2() interfaces. */ static int createModule( sqlite3 *db, /* Database in which module is registered */ const char *zName, /* Name assigned to this module */ const sqlite3_module *pModule, /* The definition of the module */ void *pAux, /* Context pointer for xCreate/xConnect */ void (*xDestroy)(void *) /* Module destructor function */ ){ int rc = SQLITE_OK; int nName; sqlite3_mutex_enter(db->mutex); nName = sqlite3Strlen30(zName); if( sqlite3HashFind(&db->aModule, zName) ){ rc = SQLITE_MISUSE_BKPT; }else{ Module *pMod; pMod = (Module *)sqlite3DbMallocRawNN(db, sizeof(Module) + nName + 1); if( pMod ){ Module *pDel; char *zCopy = (char *)(&pMod[1]); memcpy(zCopy, zName, nName+1); pMod->zName = zCopy; pMod->pModule = pModule; pMod->pAux = pAux; pMod->xDestroy = xDestroy; pMod->pEpoTab = 0; pDel = (Module *)sqlite3HashInsert(&db->aModule,zCopy,(void*)pMod); assert( pDel==0 || pDel==pMod ); if( pDel ){ sqlite3OomFault(db); sqlite3DbFree(db, pDel); } } } rc = sqlite3ApiExit(db, rc); if( rc!=SQLITE_OK && xDestroy ) xDestroy(pAux); sqlite3_mutex_leave(db->mutex); return rc; } /* ** External API function used to create a new virtual-table module. */ SQLITE_API int sqlite3_create_module( sqlite3 *db, /* Database in which module is registered */ const char *zName, /* Name assigned to this module */ const sqlite3_module *pModule, /* The definition of the module */ void *pAux /* Context pointer for xCreate/xConnect */ ){ #ifdef SQLITE_ENABLE_API_ARMOR if( !sqlite3SafetyCheckOk(db) || zName==0 ) return SQLITE_MISUSE_BKPT; #endif return createModule(db, zName, pModule, pAux, 0); } /* ** External API function used to create a new virtual-table module. */ SQLITE_API int sqlite3_create_module_v2( sqlite3 *db, /* Database in which module is registered */ const char *zName, /* Name assigned to this module */ const sqlite3_module *pModule, /* The definition of the module */ void *pAux, /* Context pointer for xCreate/xConnect */ void (*xDestroy)(void *) /* Module destructor function */ ){ #ifdef SQLITE_ENABLE_API_ARMOR if( !sqlite3SafetyCheckOk(db) || zName==0 ) return SQLITE_MISUSE_BKPT; #endif return createModule(db, zName, pModule, pAux, xDestroy); } /* ** Lock the virtual table so that it cannot be disconnected. ** Locks nest. Every lock should have a corresponding unlock. ** If an unlock is omitted, resources leaks will occur. ** ** If a disconnect is attempted while a virtual table is locked, ** the disconnect is deferred until all locks have been removed. */ SQLITE_PRIVATE void sqlite3VtabLock(VTable *pVTab){ pVTab->nRef++; } /* ** pTab is a pointer to a Table structure representing a virtual-table. ** Return a pointer to the VTable object used by connection db to access ** this virtual-table, if one has been created, or NULL otherwise. */ SQLITE_PRIVATE VTable *sqlite3GetVTable(sqlite3 *db, Table *pTab){ VTable *pVtab; assert( IsVirtual(pTab) ); for(pVtab=pTab->pVTable; pVtab && pVtab->db!=db; pVtab=pVtab->pNext); return pVtab; } /* ** Decrement the ref-count on a virtual table object. When the ref-count ** reaches zero, call the xDisconnect() method to delete the object. */ SQLITE_PRIVATE void sqlite3VtabUnlock(VTable *pVTab){ sqlite3 *db = pVTab->db; assert( db ); assert( pVTab->nRef>0 ); assert( db->magic==SQLITE_MAGIC_OPEN || db->magic==SQLITE_MAGIC_ZOMBIE ); pVTab->nRef--; if( pVTab->nRef==0 ){ sqlite3_vtab *p = pVTab->pVtab; if( p ){ p->pModule->xDisconnect(p); } sqlite3DbFree(db, pVTab); } } /* ** Table p is a virtual table. This function moves all elements in the ** p->pVTable list to the sqlite3.pDisconnect lists of their associated ** database connections to be disconnected at the next opportunity. ** Except, if argument db is not NULL, then the entry associated with ** connection db is left in the p->pVTable list. */ static VTable *vtabDisconnectAll(sqlite3 *db, Table *p){ VTable *pRet = 0; VTable *pVTable = p->pVTable; p->pVTable = 0; /* Assert that the mutex (if any) associated with the BtShared database ** that contains table p is held by the caller. See header comments ** above function sqlite3VtabUnlockList() for an explanation of why ** this makes it safe to access the sqlite3.pDisconnect list of any ** database connection that may have an entry in the p->pVTable list. */ assert( db==0 || sqlite3SchemaMutexHeld(db, 0, p->pSchema) ); while( pVTable ){ sqlite3 *db2 = pVTable->db; VTable *pNext = pVTable->pNext; assert( db2 ); if( db2==db ){ pRet = pVTable; p->pVTable = pRet; pRet->pNext = 0; }else{ pVTable->pNext = db2->pDisconnect; db2->pDisconnect = pVTable; } pVTable = pNext; } assert( !db || pRet ); return pRet; } /* ** Table *p is a virtual table. This function removes the VTable object ** for table *p associated with database connection db from the linked ** list in p->pVTab. It also decrements the VTable ref count. This is ** used when closing database connection db to free all of its VTable ** objects without disturbing the rest of the Schema object (which may ** be being used by other shared-cache connections). */ SQLITE_PRIVATE void sqlite3VtabDisconnect(sqlite3 *db, Table *p){ VTable **ppVTab; assert( IsVirtual(p) ); assert( sqlite3BtreeHoldsAllMutexes(db) ); assert( sqlite3_mutex_held(db->mutex) ); for(ppVTab=&p->pVTable; *ppVTab; ppVTab=&(*ppVTab)->pNext){ if( (*ppVTab)->db==db ){ VTable *pVTab = *ppVTab; *ppVTab = pVTab->pNext; sqlite3VtabUnlock(pVTab); break; } } } /* ** Disconnect all the virtual table objects in the sqlite3.pDisconnect list. ** ** This function may only be called when the mutexes associated with all ** shared b-tree databases opened using connection db are held by the ** caller. This is done to protect the sqlite3.pDisconnect list. The ** sqlite3.pDisconnect list is accessed only as follows: ** ** 1) By this function. In this case, all BtShared mutexes and the mutex ** associated with the database handle itself must be held. ** ** 2) By function vtabDisconnectAll(), when it adds a VTable entry to ** the sqlite3.pDisconnect list. In this case either the BtShared mutex ** associated with the database the virtual table is stored in is held ** or, if the virtual table is stored in a non-sharable database, then ** the database handle mutex is held. ** ** As a result, a sqlite3.pDisconnect cannot be accessed simultaneously ** by multiple threads. It is thread-safe. */ SQLITE_PRIVATE void sqlite3VtabUnlockList(sqlite3 *db){ VTable *p = db->pDisconnect; db->pDisconnect = 0; assert( sqlite3BtreeHoldsAllMutexes(db) ); assert( sqlite3_mutex_held(db->mutex) ); if( p ){ sqlite3ExpirePreparedStatements(db); do { VTable *pNext = p->pNext; sqlite3VtabUnlock(p); p = pNext; }while( p ); } } /* ** Clear any and all virtual-table information from the Table record. ** This routine is called, for example, just before deleting the Table ** record. ** ** Since it is a virtual-table, the Table structure contains a pointer ** to the head of a linked list of VTable structures. Each VTable ** structure is associated with a single sqlite3* user of the schema. ** The reference count of the VTable structure associated with database ** connection db is decremented immediately (which may lead to the ** structure being xDisconnected and free). Any other VTable structures ** in the list are moved to the sqlite3.pDisconnect list of the associated ** database connection. */ SQLITE_PRIVATE void sqlite3VtabClear(sqlite3 *db, Table *p){ if( !db || db->pnBytesFreed==0 ) vtabDisconnectAll(0, p); if( p->azModuleArg ){ int i; for(i=0; inModuleArg; i++){ if( i!=1 ) sqlite3DbFree(db, p->azModuleArg[i]); } sqlite3DbFree(db, p->azModuleArg); } } /* ** Add a new module argument to pTable->azModuleArg[]. ** The string is not copied - the pointer is stored. The ** string will be freed automatically when the table is ** deleted. */ static void addModuleArgument(sqlite3 *db, Table *pTable, char *zArg){ int nBytes = sizeof(char *)*(2+pTable->nModuleArg); char **azModuleArg; azModuleArg = sqlite3DbRealloc(db, pTable->azModuleArg, nBytes); if( azModuleArg==0 ){ sqlite3DbFree(db, zArg); }else{ int i = pTable->nModuleArg++; azModuleArg[i] = zArg; azModuleArg[i+1] = 0; pTable->azModuleArg = azModuleArg; } } /* ** The parser calls this routine when it first sees a CREATE VIRTUAL TABLE ** statement. The module name has been parsed, but the optional list ** of parameters that follow the module name are still pending. */ SQLITE_PRIVATE void sqlite3VtabBeginParse( Parse *pParse, /* Parsing context */ Token *pName1, /* Name of new table, or database name */ Token *pName2, /* Name of new table or NULL */ Token *pModuleName, /* Name of the module for the virtual table */ int ifNotExists /* No error if the table already exists */ ){ int iDb; /* The database the table is being created in */ Table *pTable; /* The new virtual table */ sqlite3 *db; /* Database connection */ sqlite3StartTable(pParse, pName1, pName2, 0, 0, 1, ifNotExists); pTable = pParse->pNewTable; if( pTable==0 ) return; assert( 0==pTable->pIndex ); db = pParse->db; iDb = sqlite3SchemaToIndex(db, pTable->pSchema); assert( iDb>=0 ); pTable->tabFlags |= TF_Virtual; pTable->nModuleArg = 0; addModuleArgument(db, pTable, sqlite3NameFromToken(db, pModuleName)); addModuleArgument(db, pTable, 0); addModuleArgument(db, pTable, sqlite3DbStrDup(db, pTable->zName)); assert( (pParse->sNameToken.z==pName2->z && pName2->z!=0) || (pParse->sNameToken.z==pName1->z && pName2->z==0) ); pParse->sNameToken.n = (int)( &pModuleName->z[pModuleName->n] - pParse->sNameToken.z ); #ifndef SQLITE_OMIT_AUTHORIZATION /* Creating a virtual table invokes the authorization callback twice. ** The first invocation, to obtain permission to INSERT a row into the ** sqlite_master table, has already been made by sqlite3StartTable(). ** The second call, to obtain permission to create the table, is made now. */ if( pTable->azModuleArg ){ sqlite3AuthCheck(pParse, SQLITE_CREATE_VTABLE, pTable->zName, pTable->azModuleArg[0], pParse->db->aDb[iDb].zDbSName); } #endif } /* ** This routine takes the module argument that has been accumulating ** in pParse->zArg[] and appends it to the list of arguments on the ** virtual table currently under construction in pParse->pTable. */ static void addArgumentToVtab(Parse *pParse){ if( pParse->sArg.z && pParse->pNewTable ){ const char *z = (const char*)pParse->sArg.z; int n = pParse->sArg.n; sqlite3 *db = pParse->db; addModuleArgument(db, pParse->pNewTable, sqlite3DbStrNDup(db, z, n)); } } /* ** The parser calls this routine after the CREATE VIRTUAL TABLE statement ** has been completely parsed. */ SQLITE_PRIVATE void sqlite3VtabFinishParse(Parse *pParse, Token *pEnd){ Table *pTab = pParse->pNewTable; /* The table being constructed */ sqlite3 *db = pParse->db; /* The database connection */ if( pTab==0 ) return; addArgumentToVtab(pParse); pParse->sArg.z = 0; if( pTab->nModuleArg<1 ) return; /* If the CREATE VIRTUAL TABLE statement is being entered for the ** first time (in other words if the virtual table is actually being ** created now instead of just being read out of sqlite_master) then ** do additional initialization work and store the statement text ** in the sqlite_master table. */ if( !db->init.busy ){ char *zStmt; char *zWhere; int iDb; int iReg; Vdbe *v; /* Compute the complete text of the CREATE VIRTUAL TABLE statement */ if( pEnd ){ pParse->sNameToken.n = (int)(pEnd->z - pParse->sNameToken.z) + pEnd->n; } zStmt = sqlite3MPrintf(db, "CREATE VIRTUAL TABLE %T", &pParse->sNameToken); /* A slot for the record has already been allocated in the ** SQLITE_MASTER table. We just need to update that slot with all ** the information we've collected. ** ** The VM register number pParse->regRowid holds the rowid of an ** entry in the sqlite_master table tht was created for this vtab ** by sqlite3StartTable(). */ iDb = sqlite3SchemaToIndex(db, pTab->pSchema); sqlite3NestedParse(pParse, "UPDATE %Q.%s " "SET type='table', name=%Q, tbl_name=%Q, rootpage=0, sql=%Q " "WHERE rowid=#%d", db->aDb[iDb].zDbSName, SCHEMA_TABLE(iDb), pTab->zName, pTab->zName, zStmt, pParse->regRowid ); sqlite3DbFree(db, zStmt); v = sqlite3GetVdbe(pParse); sqlite3ChangeCookie(pParse, iDb); sqlite3VdbeAddOp0(v, OP_Expire); zWhere = sqlite3MPrintf(db, "name='%q' AND type='table'", pTab->zName); sqlite3VdbeAddParseSchemaOp(v, iDb, zWhere); iReg = ++pParse->nMem; sqlite3VdbeLoadString(v, iReg, pTab->zName); sqlite3VdbeAddOp2(v, OP_VCreate, iDb, iReg); } /* If we are rereading the sqlite_master table create the in-memory ** record of the table. The xConnect() method is not called until ** the first time the virtual table is used in an SQL statement. This ** allows a schema that contains virtual tables to be loaded before ** the required virtual table implementations are registered. */ else { Table *pOld; Schema *pSchema = pTab->pSchema; const char *zName = pTab->zName; assert( sqlite3SchemaMutexHeld(db, 0, pSchema) ); pOld = sqlite3HashInsert(&pSchema->tblHash, zName, pTab); if( pOld ){ sqlite3OomFault(db); assert( pTab==pOld ); /* Malloc must have failed inside HashInsert() */ return; } pParse->pNewTable = 0; } } /* ** The parser calls this routine when it sees the first token ** of an argument to the module name in a CREATE VIRTUAL TABLE statement. */ SQLITE_PRIVATE void sqlite3VtabArgInit(Parse *pParse){ addArgumentToVtab(pParse); pParse->sArg.z = 0; pParse->sArg.n = 0; } /* ** The parser calls this routine for each token after the first token ** in an argument to the module name in a CREATE VIRTUAL TABLE statement. */ SQLITE_PRIVATE void sqlite3VtabArgExtend(Parse *pParse, Token *p){ Token *pArg = &pParse->sArg; if( pArg->z==0 ){ pArg->z = p->z; pArg->n = p->n; }else{ assert(pArg->z <= p->z); pArg->n = (int)(&p->z[p->n] - pArg->z); } } /* ** Invoke a virtual table constructor (either xCreate or xConnect). The ** pointer to the function to invoke is passed as the fourth parameter ** to this procedure. */ static int vtabCallConstructor( sqlite3 *db, Table *pTab, Module *pMod, int (*xConstruct)(sqlite3*,void*,int,const char*const*,sqlite3_vtab**,char**), char **pzErr ){ VtabCtx sCtx; VTable *pVTable; int rc; const char *const*azArg = (const char *const*)pTab->azModuleArg; int nArg = pTab->nModuleArg; char *zErr = 0; char *zModuleName; int iDb; VtabCtx *pCtx; /* Check that the virtual-table is not already being initialized */ for(pCtx=db->pVtabCtx; pCtx; pCtx=pCtx->pPrior){ if( pCtx->pTab==pTab ){ *pzErr = sqlite3MPrintf(db, "vtable constructor called recursively: %s", pTab->zName ); return SQLITE_LOCKED; } } zModuleName = sqlite3MPrintf(db, "%s", pTab->zName); if( !zModuleName ){ return SQLITE_NOMEM_BKPT; } pVTable = sqlite3DbMallocZero(db, sizeof(VTable)); if( !pVTable ){ sqlite3DbFree(db, zModuleName); return SQLITE_NOMEM_BKPT; } pVTable->db = db; pVTable->pMod = pMod; iDb = sqlite3SchemaToIndex(db, pTab->pSchema); pTab->azModuleArg[1] = db->aDb[iDb].zDbSName; /* Invoke the virtual table constructor */ assert( &db->pVtabCtx ); assert( xConstruct ); sCtx.pTab = pTab; sCtx.pVTable = pVTable; sCtx.pPrior = db->pVtabCtx; sCtx.bDeclared = 0; db->pVtabCtx = &sCtx; rc = xConstruct(db, pMod->pAux, nArg, azArg, &pVTable->pVtab, &zErr); db->pVtabCtx = sCtx.pPrior; if( rc==SQLITE_NOMEM ) sqlite3OomFault(db); assert( sCtx.pTab==pTab ); if( SQLITE_OK!=rc ){ if( zErr==0 ){ *pzErr = sqlite3MPrintf(db, "vtable constructor failed: %s", zModuleName); }else { *pzErr = sqlite3MPrintf(db, "%s", zErr); sqlite3_free(zErr); } sqlite3DbFree(db, pVTable); }else if( ALWAYS(pVTable->pVtab) ){ /* Justification of ALWAYS(): A correct vtab constructor must allocate ** the sqlite3_vtab object if successful. */ memset(pVTable->pVtab, 0, sizeof(pVTable->pVtab[0])); pVTable->pVtab->pModule = pMod->pModule; pVTable->nRef = 1; if( sCtx.bDeclared==0 ){ const char *zFormat = "vtable constructor did not declare schema: %s"; *pzErr = sqlite3MPrintf(db, zFormat, pTab->zName); sqlite3VtabUnlock(pVTable); rc = SQLITE_ERROR; }else{ int iCol; u8 oooHidden = 0; /* If everything went according to plan, link the new VTable structure ** into the linked list headed by pTab->pVTable. Then loop through the ** columns of the table to see if any of them contain the token "hidden". ** If so, set the Column COLFLAG_HIDDEN flag and remove the token from ** the type string. */ pVTable->pNext = pTab->pVTable; pTab->pVTable = pVTable; for(iCol=0; iColnCol; iCol++){ char *zType = sqlite3ColumnType(&pTab->aCol[iCol], ""); int nType; int i = 0; nType = sqlite3Strlen30(zType); for(i=0; i0 ){ assert(zType[i-1]==' '); zType[i-1] = '\0'; } pTab->aCol[iCol].colFlags |= COLFLAG_HIDDEN; oooHidden = TF_OOOHidden; }else{ pTab->tabFlags |= oooHidden; } } } } sqlite3DbFree(db, zModuleName); return rc; } /* ** This function is invoked by the parser to call the xConnect() method ** of the virtual table pTab. If an error occurs, an error code is returned ** and an error left in pParse. ** ** This call is a no-op if table pTab is not a virtual table. */ SQLITE_PRIVATE int sqlite3VtabCallConnect(Parse *pParse, Table *pTab){ sqlite3 *db = pParse->db; const char *zMod; Module *pMod; int rc; assert( pTab ); if( (pTab->tabFlags & TF_Virtual)==0 || sqlite3GetVTable(db, pTab) ){ return SQLITE_OK; } /* Locate the required virtual table module */ zMod = pTab->azModuleArg[0]; pMod = (Module*)sqlite3HashFind(&db->aModule, zMod); if( !pMod ){ const char *zModule = pTab->azModuleArg[0]; sqlite3ErrorMsg(pParse, "no such module: %s", zModule); rc = SQLITE_ERROR; }else{ char *zErr = 0; rc = vtabCallConstructor(db, pTab, pMod, pMod->pModule->xConnect, &zErr); if( rc!=SQLITE_OK ){ sqlite3ErrorMsg(pParse, "%s", zErr); } sqlite3DbFree(db, zErr); } return rc; } /* ** Grow the db->aVTrans[] array so that there is room for at least one ** more v-table. Return SQLITE_NOMEM if a malloc fails, or SQLITE_OK otherwise. */ static int growVTrans(sqlite3 *db){ const int ARRAY_INCR = 5; /* Grow the sqlite3.aVTrans array if required */ if( (db->nVTrans%ARRAY_INCR)==0 ){ VTable **aVTrans; int nBytes = sizeof(sqlite3_vtab *) * (db->nVTrans + ARRAY_INCR); aVTrans = sqlite3DbRealloc(db, (void *)db->aVTrans, nBytes); if( !aVTrans ){ return SQLITE_NOMEM_BKPT; } memset(&aVTrans[db->nVTrans], 0, sizeof(sqlite3_vtab *)*ARRAY_INCR); db->aVTrans = aVTrans; } return SQLITE_OK; } /* ** Add the virtual table pVTab to the array sqlite3.aVTrans[]. Space should ** have already been reserved using growVTrans(). */ static void addToVTrans(sqlite3 *db, VTable *pVTab){ /* Add pVtab to the end of sqlite3.aVTrans */ db->aVTrans[db->nVTrans++] = pVTab; sqlite3VtabLock(pVTab); } /* ** This function is invoked by the vdbe to call the xCreate method ** of the virtual table named zTab in database iDb. ** ** If an error occurs, *pzErr is set to point to an English language ** description of the error and an SQLITE_XXX error code is returned. ** In this case the caller must call sqlite3DbFree(db, ) on *pzErr. */ SQLITE_PRIVATE int sqlite3VtabCallCreate(sqlite3 *db, int iDb, const char *zTab, char **pzErr){ int rc = SQLITE_OK; Table *pTab; Module *pMod; const char *zMod; pTab = sqlite3FindTable(db, zTab, db->aDb[iDb].zDbSName); assert( pTab && (pTab->tabFlags & TF_Virtual)!=0 && !pTab->pVTable ); /* Locate the required virtual table module */ zMod = pTab->azModuleArg[0]; pMod = (Module*)sqlite3HashFind(&db->aModule, zMod); /* If the module has been registered and includes a Create method, ** invoke it now. If the module has not been registered, return an ** error. Otherwise, do nothing. */ if( pMod==0 || pMod->pModule->xCreate==0 || pMod->pModule->xDestroy==0 ){ *pzErr = sqlite3MPrintf(db, "no such module: %s", zMod); rc = SQLITE_ERROR; }else{ rc = vtabCallConstructor(db, pTab, pMod, pMod->pModule->xCreate, pzErr); } /* Justification of ALWAYS(): The xConstructor method is required to ** create a valid sqlite3_vtab if it returns SQLITE_OK. */ if( rc==SQLITE_OK && ALWAYS(sqlite3GetVTable(db, pTab)) ){ rc = growVTrans(db); if( rc==SQLITE_OK ){ addToVTrans(db, sqlite3GetVTable(db, pTab)); } } return rc; } /* ** This function is used to set the schema of a virtual table. It is only ** valid to call this function from within the xCreate() or xConnect() of a ** virtual table module. */ SQLITE_API int sqlite3_declare_vtab(sqlite3 *db, const char *zCreateTable){ VtabCtx *pCtx; Parse *pParse; int rc = SQLITE_OK; Table *pTab; char *zErr = 0; #ifdef SQLITE_ENABLE_API_ARMOR if( !sqlite3SafetyCheckOk(db) || zCreateTable==0 ){ return SQLITE_MISUSE_BKPT; } #endif sqlite3_mutex_enter(db->mutex); pCtx = db->pVtabCtx; if( !pCtx || pCtx->bDeclared ){ sqlite3Error(db, SQLITE_MISUSE); sqlite3_mutex_leave(db->mutex); return SQLITE_MISUSE_BKPT; } pTab = pCtx->pTab; assert( (pTab->tabFlags & TF_Virtual)!=0 ); pParse = sqlite3StackAllocZero(db, sizeof(*pParse)); if( pParse==0 ){ rc = SQLITE_NOMEM_BKPT; }else{ pParse->declareVtab = 1; pParse->db = db; pParse->nQueryLoop = 1; if( SQLITE_OK==sqlite3RunParser(pParse, zCreateTable, &zErr) && pParse->pNewTable && !db->mallocFailed && !pParse->pNewTable->pSelect && (pParse->pNewTable->tabFlags & TF_Virtual)==0 ){ if( !pTab->aCol ){ Table *pNew = pParse->pNewTable; Index *pIdx; pTab->aCol = pNew->aCol; pTab->nCol = pNew->nCol; pTab->tabFlags |= pNew->tabFlags & (TF_WithoutRowid|TF_NoVisibleRowid); pNew->nCol = 0; pNew->aCol = 0; assert( pTab->pIndex==0 ); if( !HasRowid(pNew) && pCtx->pVTable->pMod->pModule->xUpdate!=0 ){ rc = SQLITE_ERROR; } pIdx = pNew->pIndex; if( pIdx ){ assert( pIdx->pNext==0 ); pTab->pIndex = pIdx; pNew->pIndex = 0; pIdx->pTable = pTab; } } pCtx->bDeclared = 1; }else{ sqlite3ErrorWithMsg(db, SQLITE_ERROR, (zErr ? "%s" : 0), zErr); sqlite3DbFree(db, zErr); rc = SQLITE_ERROR; } pParse->declareVtab = 0; if( pParse->pVdbe ){ sqlite3VdbeFinalize(pParse->pVdbe); } sqlite3DeleteTable(db, pParse->pNewTable); sqlite3ParserReset(pParse); sqlite3StackFree(db, pParse); } assert( (rc&0xff)==rc ); rc = sqlite3ApiExit(db, rc); sqlite3_mutex_leave(db->mutex); return rc; } /* ** This function is invoked by the vdbe to call the xDestroy method ** of the virtual table named zTab in database iDb. This occurs ** when a DROP TABLE is mentioned. ** ** This call is a no-op if zTab is not a virtual table. */ SQLITE_PRIVATE int sqlite3VtabCallDestroy(sqlite3 *db, int iDb, const char *zTab){ int rc = SQLITE_OK; Table *pTab; pTab = sqlite3FindTable(db, zTab, db->aDb[iDb].zDbSName); if( pTab!=0 && ALWAYS(pTab->pVTable!=0) ){ VTable *p; int (*xDestroy)(sqlite3_vtab *); for(p=pTab->pVTable; p; p=p->pNext){ assert( p->pVtab ); if( p->pVtab->nRef>0 ){ return SQLITE_LOCKED; } } p = vtabDisconnectAll(db, pTab); xDestroy = p->pMod->pModule->xDestroy; assert( xDestroy!=0 ); /* Checked before the virtual table is created */ rc = xDestroy(p->pVtab); /* Remove the sqlite3_vtab* from the aVTrans[] array, if applicable */ if( rc==SQLITE_OK ){ assert( pTab->pVTable==p && p->pNext==0 ); p->pVtab = 0; pTab->pVTable = 0; sqlite3VtabUnlock(p); } } return rc; } /* ** This function invokes either the xRollback or xCommit method ** of each of the virtual tables in the sqlite3.aVTrans array. The method ** called is identified by the second argument, "offset", which is ** the offset of the method to call in the sqlite3_module structure. ** ** The array is cleared after invoking the callbacks. */ static void callFinaliser(sqlite3 *db, int offset){ int i; if( db->aVTrans ){ VTable **aVTrans = db->aVTrans; db->aVTrans = 0; for(i=0; inVTrans; i++){ VTable *pVTab = aVTrans[i]; sqlite3_vtab *p = pVTab->pVtab; if( p ){ int (*x)(sqlite3_vtab *); x = *(int (**)(sqlite3_vtab *))((char *)p->pModule + offset); if( x ) x(p); } pVTab->iSavepoint = 0; sqlite3VtabUnlock(pVTab); } sqlite3DbFree(db, aVTrans); db->nVTrans = 0; } } /* ** Invoke the xSync method of all virtual tables in the sqlite3.aVTrans ** array. Return the error code for the first error that occurs, or ** SQLITE_OK if all xSync operations are successful. ** ** If an error message is available, leave it in p->zErrMsg. */ SQLITE_PRIVATE int sqlite3VtabSync(sqlite3 *db, Vdbe *p){ int i; int rc = SQLITE_OK; VTable **aVTrans = db->aVTrans; db->aVTrans = 0; for(i=0; rc==SQLITE_OK && inVTrans; i++){ int (*x)(sqlite3_vtab *); sqlite3_vtab *pVtab = aVTrans[i]->pVtab; if( pVtab && (x = pVtab->pModule->xSync)!=0 ){ rc = x(pVtab); sqlite3VtabImportErrmsg(p, pVtab); } } db->aVTrans = aVTrans; return rc; } /* ** Invoke the xRollback method of all virtual tables in the ** sqlite3.aVTrans array. Then clear the array itself. */ SQLITE_PRIVATE int sqlite3VtabRollback(sqlite3 *db){ callFinaliser(db, offsetof(sqlite3_module,xRollback)); return SQLITE_OK; } /* ** Invoke the xCommit method of all virtual tables in the ** sqlite3.aVTrans array. Then clear the array itself. */ SQLITE_PRIVATE int sqlite3VtabCommit(sqlite3 *db){ callFinaliser(db, offsetof(sqlite3_module,xCommit)); return SQLITE_OK; } /* ** If the virtual table pVtab supports the transaction interface ** (xBegin/xRollback/xCommit and optionally xSync) and a transaction is ** not currently open, invoke the xBegin method now. ** ** If the xBegin call is successful, place the sqlite3_vtab pointer ** in the sqlite3.aVTrans array. */ SQLITE_PRIVATE int sqlite3VtabBegin(sqlite3 *db, VTable *pVTab){ int rc = SQLITE_OK; const sqlite3_module *pModule; /* Special case: If db->aVTrans is NULL and db->nVTrans is greater ** than zero, then this function is being called from within a ** virtual module xSync() callback. It is illegal to write to ** virtual module tables in this case, so return SQLITE_LOCKED. */ if( sqlite3VtabInSync(db) ){ return SQLITE_LOCKED; } if( !pVTab ){ return SQLITE_OK; } pModule = pVTab->pVtab->pModule; if( pModule->xBegin ){ int i; /* If pVtab is already in the aVTrans array, return early */ for(i=0; inVTrans; i++){ if( db->aVTrans[i]==pVTab ){ return SQLITE_OK; } } /* Invoke the xBegin method. If successful, add the vtab to the ** sqlite3.aVTrans[] array. */ rc = growVTrans(db); if( rc==SQLITE_OK ){ rc = pModule->xBegin(pVTab->pVtab); if( rc==SQLITE_OK ){ int iSvpt = db->nStatement + db->nSavepoint; addToVTrans(db, pVTab); if( iSvpt && pModule->xSavepoint ){ pVTab->iSavepoint = iSvpt; rc = pModule->xSavepoint(pVTab->pVtab, iSvpt-1); } } } } return rc; } /* ** Invoke either the xSavepoint, xRollbackTo or xRelease method of all ** virtual tables that currently have an open transaction. Pass iSavepoint ** as the second argument to the virtual table method invoked. ** ** If op is SAVEPOINT_BEGIN, the xSavepoint method is invoked. If it is ** SAVEPOINT_ROLLBACK, the xRollbackTo method. Otherwise, if op is ** SAVEPOINT_RELEASE, then the xRelease method of each virtual table with ** an open transaction is invoked. ** ** If any virtual table method returns an error code other than SQLITE_OK, ** processing is abandoned and the error returned to the caller of this ** function immediately. If all calls to virtual table methods are successful, ** SQLITE_OK is returned. */ SQLITE_PRIVATE int sqlite3VtabSavepoint(sqlite3 *db, int op, int iSavepoint){ int rc = SQLITE_OK; assert( op==SAVEPOINT_RELEASE||op==SAVEPOINT_ROLLBACK||op==SAVEPOINT_BEGIN ); assert( iSavepoint>=-1 ); if( db->aVTrans ){ int i; for(i=0; rc==SQLITE_OK && inVTrans; i++){ VTable *pVTab = db->aVTrans[i]; const sqlite3_module *pMod = pVTab->pMod->pModule; if( pVTab->pVtab && pMod->iVersion>=2 ){ int (*xMethod)(sqlite3_vtab *, int); switch( op ){ case SAVEPOINT_BEGIN: xMethod = pMod->xSavepoint; pVTab->iSavepoint = iSavepoint+1; break; case SAVEPOINT_ROLLBACK: xMethod = pMod->xRollbackTo; break; default: xMethod = pMod->xRelease; break; } if( xMethod && pVTab->iSavepoint>iSavepoint ){ rc = xMethod(pVTab->pVtab, iSavepoint); } } } } return rc; } /* ** The first parameter (pDef) is a function implementation. The ** second parameter (pExpr) is the first argument to this function. ** If pExpr is a column in a virtual table, then let the virtual ** table implementation have an opportunity to overload the function. ** ** This routine is used to allow virtual table implementations to ** overload MATCH, LIKE, GLOB, and REGEXP operators. ** ** Return either the pDef argument (indicating no change) or a ** new FuncDef structure that is marked as ephemeral using the ** SQLITE_FUNC_EPHEM flag. */ SQLITE_PRIVATE FuncDef *sqlite3VtabOverloadFunction( sqlite3 *db, /* Database connection for reporting malloc problems */ FuncDef *pDef, /* Function to possibly overload */ int nArg, /* Number of arguments to the function */ Expr *pExpr /* First argument to the function */ ){ Table *pTab; sqlite3_vtab *pVtab; sqlite3_module *pMod; void (*xSFunc)(sqlite3_context*,int,sqlite3_value**) = 0; void *pArg = 0; FuncDef *pNew; int rc = 0; char *zLowerName; unsigned char *z; /* Check to see the left operand is a column in a virtual table */ if( NEVER(pExpr==0) ) return pDef; if( pExpr->op!=TK_COLUMN ) return pDef; pTab = pExpr->pTab; if( NEVER(pTab==0) ) return pDef; if( (pTab->tabFlags & TF_Virtual)==0 ) return pDef; pVtab = sqlite3GetVTable(db, pTab)->pVtab; assert( pVtab!=0 ); assert( pVtab->pModule!=0 ); pMod = (sqlite3_module *)pVtab->pModule; if( pMod->xFindFunction==0 ) return pDef; /* Call the xFindFunction method on the virtual table implementation ** to see if the implementation wants to overload this function */ zLowerName = sqlite3DbStrDup(db, pDef->zName); if( zLowerName ){ for(z=(unsigned char*)zLowerName; *z; z++){ *z = sqlite3UpperToLower[*z]; } rc = pMod->xFindFunction(pVtab, nArg, zLowerName, &xSFunc, &pArg); sqlite3DbFree(db, zLowerName); } if( rc==0 ){ return pDef; } /* Create a new ephemeral function definition for the overloaded ** function */ pNew = sqlite3DbMallocZero(db, sizeof(*pNew) + sqlite3Strlen30(pDef->zName) + 1); if( pNew==0 ){ return pDef; } *pNew = *pDef; pNew->zName = (const char*)&pNew[1]; memcpy((char*)&pNew[1], pDef->zName, sqlite3Strlen30(pDef->zName)+1); pNew->xSFunc = xSFunc; pNew->pUserData = pArg; pNew->funcFlags |= SQLITE_FUNC_EPHEM; return pNew; } /* ** Make sure virtual table pTab is contained in the pParse->apVirtualLock[] ** array so that an OP_VBegin will get generated for it. Add pTab to the ** array if it is missing. If pTab is already in the array, this routine ** is a no-op. */ SQLITE_PRIVATE void sqlite3VtabMakeWritable(Parse *pParse, Table *pTab){ Parse *pToplevel = sqlite3ParseToplevel(pParse); int i, n; Table **apVtabLock; assert( IsVirtual(pTab) ); for(i=0; inVtabLock; i++){ if( pTab==pToplevel->apVtabLock[i] ) return; } n = (pToplevel->nVtabLock+1)*sizeof(pToplevel->apVtabLock[0]); apVtabLock = sqlite3_realloc64(pToplevel->apVtabLock, n); if( apVtabLock ){ pToplevel->apVtabLock = apVtabLock; pToplevel->apVtabLock[pToplevel->nVtabLock++] = pTab; }else{ sqlite3OomFault(pToplevel->db); } } /* ** Check to see if virtual table module pMod can be have an eponymous ** virtual table instance. If it can, create one if one does not already ** exist. Return non-zero if the eponymous virtual table instance exists ** when this routine returns, and return zero if it does not exist. ** ** An eponymous virtual table instance is one that is named after its ** module, and more importantly, does not require a CREATE VIRTUAL TABLE ** statement in order to come into existance. Eponymous virtual table ** instances always exist. They cannot be DROP-ed. ** ** Any virtual table module for which xConnect and xCreate are the same ** method can have an eponymous virtual table instance. */ SQLITE_PRIVATE int sqlite3VtabEponymousTableInit(Parse *pParse, Module *pMod){ const sqlite3_module *pModule = pMod->pModule; Table *pTab; char *zErr = 0; int rc; sqlite3 *db = pParse->db; if( pMod->pEpoTab ) return 1; if( pModule->xCreate!=0 && pModule->xCreate!=pModule->xConnect ) return 0; pTab = sqlite3DbMallocZero(db, sizeof(Table)); if( pTab==0 ) return 0; pTab->zName = sqlite3DbStrDup(db, pMod->zName); if( pTab->zName==0 ){ sqlite3DbFree(db, pTab); return 0; } pMod->pEpoTab = pTab; pTab->nRef = 1; pTab->pSchema = db->aDb[0].pSchema; pTab->tabFlags |= TF_Virtual; pTab->nModuleArg = 0; pTab->iPKey = -1; addModuleArgument(db, pTab, sqlite3DbStrDup(db, pTab->zName)); addModuleArgument(db, pTab, 0); addModuleArgument(db, pTab, sqlite3DbStrDup(db, pTab->zName)); rc = vtabCallConstructor(db, pTab, pMod, pModule->xConnect, &zErr); if( rc ){ sqlite3ErrorMsg(pParse, "%s", zErr); sqlite3DbFree(db, zErr); sqlite3VtabEponymousTableClear(db, pMod); return 0; } return 1; } /* ** Erase the eponymous virtual table instance associated with ** virtual table module pMod, if it exists. */ SQLITE_PRIVATE void sqlite3VtabEponymousTableClear(sqlite3 *db, Module *pMod){ Table *pTab = pMod->pEpoTab; if( pTab!=0 ){ /* Mark the table as Ephemeral prior to deleting it, so that the ** sqlite3DeleteTable() routine will know that it is not stored in ** the schema. */ pTab->tabFlags |= TF_Ephemeral; sqlite3DeleteTable(db, pTab); pMod->pEpoTab = 0; } } /* ** Return the ON CONFLICT resolution mode in effect for the virtual ** table update operation currently in progress. ** ** The results of this routine are undefined unless it is called from ** within an xUpdate method. */ SQLITE_API int sqlite3_vtab_on_conflict(sqlite3 *db){ static const unsigned char aMap[] = { SQLITE_ROLLBACK, SQLITE_ABORT, SQLITE_FAIL, SQLITE_IGNORE, SQLITE_REPLACE }; #ifdef SQLITE_ENABLE_API_ARMOR if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT; #endif assert( OE_Rollback==1 && OE_Abort==2 && OE_Fail==3 ); assert( OE_Ignore==4 && OE_Replace==5 ); assert( db->vtabOnConflict>=1 && db->vtabOnConflict<=5 ); return (int)aMap[db->vtabOnConflict-1]; } /* ** Call from within the xCreate() or xConnect() methods to provide ** the SQLite core with additional information about the behavior ** of the virtual table being implemented. */ SQLITE_API int sqlite3_vtab_config(sqlite3 *db, int op, ...){ va_list ap; int rc = SQLITE_OK; #ifdef SQLITE_ENABLE_API_ARMOR if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT; #endif sqlite3_mutex_enter(db->mutex); va_start(ap, op); switch( op ){ case SQLITE_VTAB_CONSTRAINT_SUPPORT: { VtabCtx *p = db->pVtabCtx; if( !p ){ rc = SQLITE_MISUSE_BKPT; }else{ assert( p->pTab==0 || (p->pTab->tabFlags & TF_Virtual)!=0 ); p->pVTable->bConstraint = (u8)va_arg(ap, int); } break; } default: rc = SQLITE_MISUSE_BKPT; break; } va_end(ap); if( rc!=SQLITE_OK ) sqlite3Error(db, rc); sqlite3_mutex_leave(db->mutex); return rc; } #endif /* SQLITE_OMIT_VIRTUALTABLE */ /************** End of vtab.c ************************************************/ /************** Begin file wherecode.c ***************************************/ /* ** 2015-06-06 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ************************************************************************* ** This module contains C code that generates VDBE code used to process ** the WHERE clause of SQL statements. ** ** This file was split off from where.c on 2015-06-06 in order to reduce the ** size of where.c and make it easier to edit. This file contains the routines ** that actually generate the bulk of the WHERE loop code. The original where.c ** file retains the code that does query planning and analysis. */ /* #include "sqliteInt.h" */ /************** Include whereInt.h in the middle of wherecode.c **************/ /************** Begin file whereInt.h ****************************************/ /* ** 2013-11-12 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ************************************************************************* ** ** This file contains structure and macro definitions for the query ** planner logic in "where.c". These definitions are broken out into ** a separate source file for easier editing. */ /* ** Trace output macros */ #if defined(SQLITE_TEST) || defined(SQLITE_DEBUG) /***/ int sqlite3WhereTrace; #endif #if defined(SQLITE_DEBUG) \ && (defined(SQLITE_TEST) || defined(SQLITE_ENABLE_WHERETRACE)) # define WHERETRACE(K,X) if(sqlite3WhereTrace&(K)) sqlite3DebugPrintf X # define WHERETRACE_ENABLED 1 #else # define WHERETRACE(K,X) #endif /* Forward references */ typedef struct WhereClause WhereClause; typedef struct WhereMaskSet WhereMaskSet; typedef struct WhereOrInfo WhereOrInfo; typedef struct WhereAndInfo WhereAndInfo; typedef struct WhereLevel WhereLevel; typedef struct WhereLoop WhereLoop; typedef struct WherePath WherePath; typedef struct WhereTerm WhereTerm; typedef struct WhereLoopBuilder WhereLoopBuilder; typedef struct WhereScan WhereScan; typedef struct WhereOrCost WhereOrCost; typedef struct WhereOrSet WhereOrSet; /* ** This object contains information needed to implement a single nested ** loop in WHERE clause. ** ** Contrast this object with WhereLoop. This object describes the ** implementation of the loop. WhereLoop describes the algorithm. ** This object contains a pointer to the WhereLoop algorithm as one of ** its elements. ** ** The WhereInfo object contains a single instance of this object for ** each term in the FROM clause (which is to say, for each of the ** nested loops as implemented). The order of WhereLevel objects determines ** the loop nested order, with WhereInfo.a[0] being the outer loop and ** WhereInfo.a[WhereInfo.nLevel-1] being the inner loop. */ struct WhereLevel { int iLeftJoin; /* Memory cell used to implement LEFT OUTER JOIN */ int iTabCur; /* The VDBE cursor used to access the table */ int iIdxCur; /* The VDBE cursor used to access pIdx */ int addrBrk; /* Jump here to break out of the loop */ int addrNxt; /* Jump here to start the next IN combination */ int addrSkip; /* Jump here for next iteration of skip-scan */ int addrCont; /* Jump here to continue with the next loop cycle */ int addrFirst; /* First instruction of interior of the loop */ int addrBody; /* Beginning of the body of this loop */ #ifndef SQLITE_LIKE_DOESNT_MATCH_BLOBS u32 iLikeRepCntr; /* LIKE range processing counter register (times 2) */ int addrLikeRep; /* LIKE range processing address */ #endif u8 iFrom; /* Which entry in the FROM clause */ u8 op, p3, p5; /* Opcode, P3 & P5 of the opcode that ends the loop */ int p1, p2; /* Operands of the opcode used to ends the loop */ union { /* Information that depends on pWLoop->wsFlags */ struct { int nIn; /* Number of entries in aInLoop[] */ struct InLoop { int iCur; /* The VDBE cursor used by this IN operator */ int addrInTop; /* Top of the IN loop */ u8 eEndLoopOp; /* IN Loop terminator. OP_Next or OP_Prev */ } *aInLoop; /* Information about each nested IN operator */ } in; /* Used when pWLoop->wsFlags&WHERE_IN_ABLE */ Index *pCovidx; /* Possible covering index for WHERE_MULTI_OR */ } u; struct WhereLoop *pWLoop; /* The selected WhereLoop object */ Bitmask notReady; /* FROM entries not usable at this level */ #ifdef SQLITE_ENABLE_STMT_SCANSTATUS int addrVisit; /* Address at which row is visited */ #endif }; /* ** Each instance of this object represents an algorithm for evaluating one ** term of a join. Every term of the FROM clause will have at least ** one corresponding WhereLoop object (unless INDEXED BY constraints ** prevent a query solution - which is an error) and many terms of the ** FROM clause will have multiple WhereLoop objects, each describing a ** potential way of implementing that FROM-clause term, together with ** dependencies and cost estimates for using the chosen algorithm. ** ** Query planning consists of building up a collection of these WhereLoop ** objects, then computing a particular sequence of WhereLoop objects, with ** one WhereLoop object per FROM clause term, that satisfy all dependencies ** and that minimize the overall cost. */ struct WhereLoop { Bitmask prereq; /* Bitmask of other loops that must run first */ Bitmask maskSelf; /* Bitmask identifying table iTab */ #ifdef SQLITE_DEBUG char cId; /* Symbolic ID of this loop for debugging use */ #endif u8 iTab; /* Position in FROM clause of table for this loop */ u8 iSortIdx; /* Sorting index number. 0==None */ LogEst rSetup; /* One-time setup cost (ex: create transient index) */ LogEst rRun; /* Cost of running each loop */ LogEst nOut; /* Estimated number of output rows */ union { struct { /* Information for internal btree tables */ u16 nEq; /* Number of equality constraints */ u16 nBtm; /* Size of BTM vector */ u16 nTop; /* Size of TOP vector */ Index *pIndex; /* Index used, or NULL */ } btree; struct { /* Information for virtual tables */ int idxNum; /* Index number */ u8 needFree; /* True if sqlite3_free(idxStr) is needed */ i8 isOrdered; /* True if satisfies ORDER BY */ u16 omitMask; /* Terms that may be omitted */ char *idxStr; /* Index identifier string */ } vtab; } u; u32 wsFlags; /* WHERE_* flags describing the plan */ u16 nLTerm; /* Number of entries in aLTerm[] */ u16 nSkip; /* Number of NULL aLTerm[] entries */ /**** whereLoopXfer() copies fields above ***********************/ # define WHERE_LOOP_XFER_SZ offsetof(WhereLoop,nLSlot) u16 nLSlot; /* Number of slots allocated for aLTerm[] */ WhereTerm **aLTerm; /* WhereTerms used */ WhereLoop *pNextLoop; /* Next WhereLoop object in the WhereClause */ WhereTerm *aLTermSpace[3]; /* Initial aLTerm[] space */ }; /* This object holds the prerequisites and the cost of running a ** subquery on one operand of an OR operator in the WHERE clause. ** See WhereOrSet for additional information */ struct WhereOrCost { Bitmask prereq; /* Prerequisites */ LogEst rRun; /* Cost of running this subquery */ LogEst nOut; /* Number of outputs for this subquery */ }; /* The WhereOrSet object holds a set of possible WhereOrCosts that ** correspond to the subquery(s) of OR-clause processing. Only the ** best N_OR_COST elements are retained. */ #define N_OR_COST 3 struct WhereOrSet { u16 n; /* Number of valid a[] entries */ WhereOrCost a[N_OR_COST]; /* Set of best costs */ }; /* ** Each instance of this object holds a sequence of WhereLoop objects ** that implement some or all of a query plan. ** ** Think of each WhereLoop object as a node in a graph with arcs ** showing dependencies and costs for travelling between nodes. (That is ** not a completely accurate description because WhereLoop costs are a ** vector, not a scalar, and because dependencies are many-to-one, not ** one-to-one as are graph nodes. But it is a useful visualization aid.) ** Then a WherePath object is a path through the graph that visits some ** or all of the WhereLoop objects once. ** ** The "solver" works by creating the N best WherePath objects of length ** 1. Then using those as a basis to compute the N best WherePath objects ** of length 2. And so forth until the length of WherePaths equals the ** number of nodes in the FROM clause. The best (lowest cost) WherePath ** at the end is the chosen query plan. */ struct WherePath { Bitmask maskLoop; /* Bitmask of all WhereLoop objects in this path */ Bitmask revLoop; /* aLoop[]s that should be reversed for ORDER BY */ LogEst nRow; /* Estimated number of rows generated by this path */ LogEst rCost; /* Total cost of this path */ LogEst rUnsorted; /* Total cost of this path ignoring sorting costs */ i8 isOrdered; /* No. of ORDER BY terms satisfied. -1 for unknown */ WhereLoop **aLoop; /* Array of WhereLoop objects implementing this path */ }; /* ** The query generator uses an array of instances of this structure to ** help it analyze the subexpressions of the WHERE clause. Each WHERE ** clause subexpression is separated from the others by AND operators, ** usually, or sometimes subexpressions separated by OR. ** ** All WhereTerms are collected into a single WhereClause structure. ** The following identity holds: ** ** WhereTerm.pWC->a[WhereTerm.idx] == WhereTerm ** ** When a term is of the form: ** ** X ** ** where X is a column name and is one of certain operators, ** then WhereTerm.leftCursor and WhereTerm.u.leftColumn record the ** cursor number and column number for X. WhereTerm.eOperator records ** the using a bitmask encoding defined by WO_xxx below. The ** use of a bitmask encoding for the operator allows us to search ** quickly for terms that match any of several different operators. ** ** A WhereTerm might also be two or more subterms connected by OR: ** ** (t1.X ) OR (t1.Y ) OR .... ** ** In this second case, wtFlag has the TERM_ORINFO bit set and eOperator==WO_OR ** and the WhereTerm.u.pOrInfo field points to auxiliary information that ** is collected about the OR clause. ** ** If a term in the WHERE clause does not match either of the two previous ** categories, then eOperator==0. The WhereTerm.pExpr field is still set ** to the original subexpression content and wtFlags is set up appropriately ** but no other fields in the WhereTerm object are meaningful. ** ** When eOperator!=0, prereqRight and prereqAll record sets of cursor numbers, ** but they do so indirectly. A single WhereMaskSet structure translates ** cursor number into bits and the translated bit is stored in the prereq ** fields. The translation is used in order to maximize the number of ** bits that will fit in a Bitmask. The VDBE cursor numbers might be ** spread out over the non-negative integers. For example, the cursor ** numbers might be 3, 8, 9, 10, 20, 23, 41, and 45. The WhereMaskSet ** translates these sparse cursor numbers into consecutive integers ** beginning with 0 in order to make the best possible use of the available ** bits in the Bitmask. So, in the example above, the cursor numbers ** would be mapped into integers 0 through 7. ** ** The number of terms in a join is limited by the number of bits ** in prereqRight and prereqAll. The default is 64 bits, hence SQLite ** is only able to process joins with 64 or fewer tables. */ struct WhereTerm { Expr *pExpr; /* Pointer to the subexpression that is this term */ WhereClause *pWC; /* The clause this term is part of */ LogEst truthProb; /* Probability of truth for this expression */ u16 wtFlags; /* TERM_xxx bit flags. See below */ u16 eOperator; /* A WO_xx value describing */ u8 nChild; /* Number of children that must disable us */ u8 eMatchOp; /* Op for vtab MATCH/LIKE/GLOB/REGEXP terms */ int iParent; /* Disable pWC->a[iParent] when this term disabled */ int leftCursor; /* Cursor number of X in "X " */ int iField; /* Field in (?,?,?) IN (SELECT...) vector */ union { int leftColumn; /* Column number of X in "X " */ WhereOrInfo *pOrInfo; /* Extra information if (eOperator & WO_OR)!=0 */ WhereAndInfo *pAndInfo; /* Extra information if (eOperator& WO_AND)!=0 */ } u; Bitmask prereqRight; /* Bitmask of tables used by pExpr->pRight */ Bitmask prereqAll; /* Bitmask of tables referenced by pExpr */ }; /* ** Allowed values of WhereTerm.wtFlags */ #define TERM_DYNAMIC 0x01 /* Need to call sqlite3ExprDelete(db, pExpr) */ #define TERM_VIRTUAL 0x02 /* Added by the optimizer. Do not code */ #define TERM_CODED 0x04 /* This term is already coded */ #define TERM_COPIED 0x08 /* Has a child */ #define TERM_ORINFO 0x10 /* Need to free the WhereTerm.u.pOrInfo object */ #define TERM_ANDINFO 0x20 /* Need to free the WhereTerm.u.pAndInfo obj */ #define TERM_OR_OK 0x40 /* Used during OR-clause processing */ #ifdef SQLITE_ENABLE_STAT3_OR_STAT4 # define TERM_VNULL 0x80 /* Manufactured x>NULL or x<=NULL term */ #else # define TERM_VNULL 0x00 /* Disabled if not using stat3 */ #endif #define TERM_LIKEOPT 0x100 /* Virtual terms from the LIKE optimization */ #define TERM_LIKECOND 0x200 /* Conditionally this LIKE operator term */ #define TERM_LIKE 0x400 /* The original LIKE operator */ #define TERM_IS 0x800 /* Term.pExpr is an IS operator */ /* ** An instance of the WhereScan object is used as an iterator for locating ** terms in the WHERE clause that are useful to the query planner. */ struct WhereScan { WhereClause *pOrigWC; /* Original, innermost WhereClause */ WhereClause *pWC; /* WhereClause currently being scanned */ const char *zCollName; /* Required collating sequence, if not NULL */ Expr *pIdxExpr; /* Search for this index expression */ char idxaff; /* Must match this affinity, if zCollName!=NULL */ unsigned char nEquiv; /* Number of entries in aEquiv[] */ unsigned char iEquiv; /* Next unused slot in aEquiv[] */ u32 opMask; /* Acceptable operators */ int k; /* Resume scanning at this->pWC->a[this->k] */ int aiCur[11]; /* Cursors in the equivalence class */ i16 aiColumn[11]; /* Corresponding column number in the eq-class */ }; /* ** An instance of the following structure holds all information about a ** WHERE clause. Mostly this is a container for one or more WhereTerms. ** ** Explanation of pOuter: For a WHERE clause of the form ** ** a AND ((b AND c) OR (d AND e)) AND f ** ** There are separate WhereClause objects for the whole clause and for ** the subclauses "(b AND c)" and "(d AND e)". The pOuter field of the ** subclauses points to the WhereClause object for the whole clause. */ struct WhereClause { WhereInfo *pWInfo; /* WHERE clause processing context */ WhereClause *pOuter; /* Outer conjunction */ u8 op; /* Split operator. TK_AND or TK_OR */ int nTerm; /* Number of terms */ int nSlot; /* Number of entries in a[] */ WhereTerm *a; /* Each a[] describes a term of the WHERE cluase */ #if defined(SQLITE_SMALL_STACK) WhereTerm aStatic[1]; /* Initial static space for a[] */ #else WhereTerm aStatic[8]; /* Initial static space for a[] */ #endif }; /* ** A WhereTerm with eOperator==WO_OR has its u.pOrInfo pointer set to ** a dynamically allocated instance of the following structure. */ struct WhereOrInfo { WhereClause wc; /* Decomposition into subterms */ Bitmask indexable; /* Bitmask of all indexable tables in the clause */ }; /* ** A WhereTerm with eOperator==WO_AND has its u.pAndInfo pointer set to ** a dynamically allocated instance of the following structure. */ struct WhereAndInfo { WhereClause wc; /* The subexpression broken out */ }; /* ** An instance of the following structure keeps track of a mapping ** between VDBE cursor numbers and bits of the bitmasks in WhereTerm. ** ** The VDBE cursor numbers are small integers contained in ** SrcList_item.iCursor and Expr.iTable fields. For any given WHERE ** clause, the cursor numbers might not begin with 0 and they might ** contain gaps in the numbering sequence. But we want to make maximum ** use of the bits in our bitmasks. This structure provides a mapping ** from the sparse cursor numbers into consecutive integers beginning ** with 0. ** ** If WhereMaskSet.ix[A]==B it means that The A-th bit of a Bitmask ** corresponds VDBE cursor number B. The A-th bit of a bitmask is 1<3, 5->1, 8->2, 29->0, ** 57->5, 73->4. Or one of 719 other combinations might be used. It ** does not really matter. What is important is that sparse cursor ** numbers all get mapped into bit numbers that begin with 0 and contain ** no gaps. */ struct WhereMaskSet { int n; /* Number of assigned cursor values */ int ix[BMS]; /* Cursor assigned to each bit */ }; /* ** Initialize a WhereMaskSet object */ #define initMaskSet(P) (P)->n=0 /* ** This object is a convenience wrapper holding all information needed ** to construct WhereLoop objects for a particular query. */ struct WhereLoopBuilder { WhereInfo *pWInfo; /* Information about this WHERE */ WhereClause *pWC; /* WHERE clause terms */ ExprList *pOrderBy; /* ORDER BY clause */ WhereLoop *pNew; /* Template WhereLoop */ WhereOrSet *pOrSet; /* Record best loops here, if not NULL */ #ifdef SQLITE_ENABLE_STAT3_OR_STAT4 UnpackedRecord *pRec; /* Probe for stat4 (if required) */ int nRecValid; /* Number of valid fields currently in pRec */ #endif }; /* ** The WHERE clause processing routine has two halves. The ** first part does the start of the WHERE loop and the second ** half does the tail of the WHERE loop. An instance of ** this structure is returned by the first half and passed ** into the second half to give some continuity. ** ** An instance of this object holds the complete state of the query ** planner. */ struct WhereInfo { Parse *pParse; /* Parsing and code generating context */ SrcList *pTabList; /* List of tables in the join */ ExprList *pOrderBy; /* The ORDER BY clause or NULL */ ExprList *pDistinctSet; /* DISTINCT over all these values */ LogEst iLimit; /* LIMIT if wctrlFlags has WHERE_USE_LIMIT */ int aiCurOnePass[2]; /* OP_OpenWrite cursors for the ONEPASS opt */ int iContinue; /* Jump here to continue with next record */ int iBreak; /* Jump here to break out of the loop */ int savedNQueryLoop; /* pParse->nQueryLoop outside the WHERE loop */ u16 wctrlFlags; /* Flags originally passed to sqlite3WhereBegin() */ u8 nLevel; /* Number of nested loop */ i8 nOBSat; /* Number of ORDER BY terms satisfied by indices */ u8 sorted; /* True if really sorted (not just grouped) */ u8 eOnePass; /* ONEPASS_OFF, or _SINGLE, or _MULTI */ u8 untestedTerms; /* Not all WHERE terms resolved by outer loop */ u8 eDistinct; /* One of the WHERE_DISTINCT_* values */ u8 bOrderedInnerLoop; /* True if only the inner-most loop is ordered */ int iTop; /* The very beginning of the WHERE loop */ WhereLoop *pLoops; /* List of all WhereLoop objects */ Bitmask revMask; /* Mask of ORDER BY terms that need reversing */ LogEst nRowOut; /* Estimated number of output rows */ WhereClause sWC; /* Decomposition of the WHERE clause */ WhereMaskSet sMaskSet; /* Map cursor numbers to bitmasks */ WhereLevel a[1]; /* Information about each nest loop in WHERE */ }; /* ** Private interfaces - callable only by other where.c routines. ** ** where.c: */ SQLITE_PRIVATE Bitmask sqlite3WhereGetMask(WhereMaskSet*,int); #ifdef WHERETRACE_ENABLED SQLITE_PRIVATE void sqlite3WhereClausePrint(WhereClause *pWC); #endif SQLITE_PRIVATE WhereTerm *sqlite3WhereFindTerm( WhereClause *pWC, /* The WHERE clause to be searched */ int iCur, /* Cursor number of LHS */ int iColumn, /* Column number of LHS */ Bitmask notReady, /* RHS must not overlap with this mask */ u32 op, /* Mask of WO_xx values describing operator */ Index *pIdx /* Must be compatible with this index, if not NULL */ ); /* wherecode.c: */ #ifndef SQLITE_OMIT_EXPLAIN SQLITE_PRIVATE int sqlite3WhereExplainOneScan( Parse *pParse, /* Parse context */ SrcList *pTabList, /* Table list this loop refers to */ WhereLevel *pLevel, /* Scan to write OP_Explain opcode for */ int iLevel, /* Value for "level" column of output */ int iFrom, /* Value for "from" column of output */ u16 wctrlFlags /* Flags passed to sqlite3WhereBegin() */ ); #else # define sqlite3WhereExplainOneScan(u,v,w,x,y,z) 0 #endif /* SQLITE_OMIT_EXPLAIN */ #ifdef SQLITE_ENABLE_STMT_SCANSTATUS SQLITE_PRIVATE void sqlite3WhereAddScanStatus( Vdbe *v, /* Vdbe to add scanstatus entry to */ SrcList *pSrclist, /* FROM clause pLvl reads data from */ WhereLevel *pLvl, /* Level to add scanstatus() entry for */ int addrExplain /* Address of OP_Explain (or 0) */ ); #else # define sqlite3WhereAddScanStatus(a, b, c, d) ((void)d) #endif SQLITE_PRIVATE Bitmask sqlite3WhereCodeOneLoopStart( WhereInfo *pWInfo, /* Complete information about the WHERE clause */ int iLevel, /* Which level of pWInfo->a[] should be coded */ Bitmask notReady /* Which tables are currently available */ ); /* whereexpr.c: */ SQLITE_PRIVATE void sqlite3WhereClauseInit(WhereClause*,WhereInfo*); SQLITE_PRIVATE void sqlite3WhereClauseClear(WhereClause*); SQLITE_PRIVATE void sqlite3WhereSplit(WhereClause*,Expr*,u8); SQLITE_PRIVATE Bitmask sqlite3WhereExprUsage(WhereMaskSet*, Expr*); SQLITE_PRIVATE Bitmask sqlite3WhereExprListUsage(WhereMaskSet*, ExprList*); SQLITE_PRIVATE void sqlite3WhereExprAnalyze(SrcList*, WhereClause*); SQLITE_PRIVATE void sqlite3WhereTabFuncArgs(Parse*, struct SrcList_item*, WhereClause*); /* ** Bitmasks for the operators on WhereTerm objects. These are all ** operators that are of interest to the query planner. An ** OR-ed combination of these values can be used when searching for ** particular WhereTerms within a WhereClause. ** ** Value constraints: ** WO_EQ == SQLITE_INDEX_CONSTRAINT_EQ ** WO_LT == SQLITE_INDEX_CONSTRAINT_LT ** WO_LE == SQLITE_INDEX_CONSTRAINT_LE ** WO_GT == SQLITE_INDEX_CONSTRAINT_GT ** WO_GE == SQLITE_INDEX_CONSTRAINT_GE ** WO_MATCH == SQLITE_INDEX_CONSTRAINT_MATCH */ #define WO_IN 0x0001 #define WO_EQ 0x0002 #define WO_LT (WO_EQ<<(TK_LT-TK_EQ)) #define WO_LE (WO_EQ<<(TK_LE-TK_EQ)) #define WO_GT (WO_EQ<<(TK_GT-TK_EQ)) #define WO_GE (WO_EQ<<(TK_GE-TK_EQ)) #define WO_MATCH 0x0040 #define WO_IS 0x0080 #define WO_ISNULL 0x0100 #define WO_OR 0x0200 /* Two or more OR-connected terms */ #define WO_AND 0x0400 /* Two or more AND-connected terms */ #define WO_EQUIV 0x0800 /* Of the form A==B, both columns */ #define WO_NOOP 0x1000 /* This term does not restrict search space */ #define WO_ALL 0x1fff /* Mask of all possible WO_* values */ #define WO_SINGLE 0x01ff /* Mask of all non-compound WO_* values */ /* ** These are definitions of bits in the WhereLoop.wsFlags field. ** The particular combination of bits in each WhereLoop help to ** determine the algorithm that WhereLoop represents. */ #define WHERE_COLUMN_EQ 0x00000001 /* x=EXPR */ #define WHERE_COLUMN_RANGE 0x00000002 /* xEXPR */ #define WHERE_COLUMN_IN 0x00000004 /* x IN (...) */ #define WHERE_COLUMN_NULL 0x00000008 /* x IS NULL */ #define WHERE_CONSTRAINT 0x0000000f /* Any of the WHERE_COLUMN_xxx values */ #define WHERE_TOP_LIMIT 0x00000010 /* xEXPR or x>=EXPR constraint */ #define WHERE_BOTH_LIMIT 0x00000030 /* Both x>EXPR and xaiColumn[i]; if( i==XN_EXPR ) return ""; if( i==XN_ROWID ) return "rowid"; return pIdx->pTable->aCol[i].zName; } /* ** This routine is a helper for explainIndexRange() below ** ** pStr holds the text of an expression that we are building up one term ** at a time. This routine adds a new term to the end of the expression. ** Terms are separated by AND so add the "AND" text for second and subsequent ** terms only. */ static void explainAppendTerm( StrAccum *pStr, /* The text expression being built */ Index *pIdx, /* Index to read column names from */ int nTerm, /* Number of terms */ int iTerm, /* Zero-based index of first term. */ int bAnd, /* Non-zero to append " AND " */ const char *zOp /* Name of the operator */ ){ int i; assert( nTerm>=1 ); if( bAnd ) sqlite3StrAccumAppend(pStr, " AND ", 5); if( nTerm>1 ) sqlite3StrAccumAppend(pStr, "(", 1); for(i=0; i1 ) sqlite3StrAccumAppend(pStr, ")", 1); sqlite3StrAccumAppend(pStr, zOp, 1); if( nTerm>1 ) sqlite3StrAccumAppend(pStr, "(", 1); for(i=0; i1 ) sqlite3StrAccumAppend(pStr, ")", 1); } /* ** Argument pLevel describes a strategy for scanning table pTab. This ** function appends text to pStr that describes the subset of table ** rows scanned by the strategy in the form of an SQL expression. ** ** For example, if the query: ** ** SELECT * FROM t1 WHERE a=1 AND b>2; ** ** is run and there is an index on (a, b), then this function returns a ** string similar to: ** ** "a=? AND b>?" */ static void explainIndexRange(StrAccum *pStr, WhereLoop *pLoop){ Index *pIndex = pLoop->u.btree.pIndex; u16 nEq = pLoop->u.btree.nEq; u16 nSkip = pLoop->nSkip; int i, j; if( nEq==0 && (pLoop->wsFlags&(WHERE_BTM_LIMIT|WHERE_TOP_LIMIT))==0 ) return; sqlite3StrAccumAppend(pStr, " (", 2); for(i=0; i=nSkip ? "%s=?" : "ANY(%s)", z); } j = i; if( pLoop->wsFlags&WHERE_BTM_LIMIT ){ explainAppendTerm(pStr, pIndex, pLoop->u.btree.nBtm, j, i, ">"); i = 1; } if( pLoop->wsFlags&WHERE_TOP_LIMIT ){ explainAppendTerm(pStr, pIndex, pLoop->u.btree.nTop, j, i, "<"); } sqlite3StrAccumAppend(pStr, ")", 1); } /* ** This function is a no-op unless currently processing an EXPLAIN QUERY PLAN ** command, or if either SQLITE_DEBUG or SQLITE_ENABLE_STMT_SCANSTATUS was ** defined at compile-time. If it is not a no-op, a single OP_Explain opcode ** is added to the output to describe the table scan strategy in pLevel. ** ** If an OP_Explain opcode is added to the VM, its address is returned. ** Otherwise, if no OP_Explain is coded, zero is returned. */ SQLITE_PRIVATE int sqlite3WhereExplainOneScan( Parse *pParse, /* Parse context */ SrcList *pTabList, /* Table list this loop refers to */ WhereLevel *pLevel, /* Scan to write OP_Explain opcode for */ int iLevel, /* Value for "level" column of output */ int iFrom, /* Value for "from" column of output */ u16 wctrlFlags /* Flags passed to sqlite3WhereBegin() */ ){ int ret = 0; #if !defined(SQLITE_DEBUG) && !defined(SQLITE_ENABLE_STMT_SCANSTATUS) if( pParse->explain==2 ) #endif { struct SrcList_item *pItem = &pTabList->a[pLevel->iFrom]; Vdbe *v = pParse->pVdbe; /* VM being constructed */ sqlite3 *db = pParse->db; /* Database handle */ int iId = pParse->iSelectId; /* Select id (left-most output column) */ int isSearch; /* True for a SEARCH. False for SCAN. */ WhereLoop *pLoop; /* The controlling WhereLoop object */ u32 flags; /* Flags that describe this loop */ char *zMsg; /* Text to add to EQP output */ StrAccum str; /* EQP output string */ char zBuf[100]; /* Initial space for EQP output string */ pLoop = pLevel->pWLoop; flags = pLoop->wsFlags; if( (flags&WHERE_MULTI_OR) || (wctrlFlags&WHERE_OR_SUBCLAUSE) ) return 0; isSearch = (flags&(WHERE_BTM_LIMIT|WHERE_TOP_LIMIT))!=0 || ((flags&WHERE_VIRTUALTABLE)==0 && (pLoop->u.btree.nEq>0)) || (wctrlFlags&(WHERE_ORDERBY_MIN|WHERE_ORDERBY_MAX)); sqlite3StrAccumInit(&str, db, zBuf, sizeof(zBuf), SQLITE_MAX_LENGTH); sqlite3StrAccumAppendAll(&str, isSearch ? "SEARCH" : "SCAN"); if( pItem->pSelect ){ sqlite3XPrintf(&str, " SUBQUERY %d", pItem->iSelectId); }else{ sqlite3XPrintf(&str, " TABLE %s", pItem->zName); } if( pItem->zAlias ){ sqlite3XPrintf(&str, " AS %s", pItem->zAlias); } if( (flags & (WHERE_IPK|WHERE_VIRTUALTABLE))==0 ){ const char *zFmt = 0; Index *pIdx; assert( pLoop->u.btree.pIndex!=0 ); pIdx = pLoop->u.btree.pIndex; assert( !(flags&WHERE_AUTO_INDEX) || (flags&WHERE_IDX_ONLY) ); if( !HasRowid(pItem->pTab) && IsPrimaryKeyIndex(pIdx) ){ if( isSearch ){ zFmt = "PRIMARY KEY"; } }else if( flags & WHERE_PARTIALIDX ){ zFmt = "AUTOMATIC PARTIAL COVERING INDEX"; }else if( flags & WHERE_AUTO_INDEX ){ zFmt = "AUTOMATIC COVERING INDEX"; }else if( flags & WHERE_IDX_ONLY ){ zFmt = "COVERING INDEX %s"; }else{ zFmt = "INDEX %s"; } if( zFmt ){ sqlite3StrAccumAppend(&str, " USING ", 7); sqlite3XPrintf(&str, zFmt, pIdx->zName); explainIndexRange(&str, pLoop); } }else if( (flags & WHERE_IPK)!=0 && (flags & WHERE_CONSTRAINT)!=0 ){ const char *zRangeOp; if( flags&(WHERE_COLUMN_EQ|WHERE_COLUMN_IN) ){ zRangeOp = "="; }else if( (flags&WHERE_BOTH_LIMIT)==WHERE_BOTH_LIMIT ){ zRangeOp = ">? AND rowid<"; }else if( flags&WHERE_BTM_LIMIT ){ zRangeOp = ">"; }else{ assert( flags&WHERE_TOP_LIMIT); zRangeOp = "<"; } sqlite3XPrintf(&str, " USING INTEGER PRIMARY KEY (rowid%s?)",zRangeOp); } #ifndef SQLITE_OMIT_VIRTUALTABLE else if( (flags & WHERE_VIRTUALTABLE)!=0 ){ sqlite3XPrintf(&str, " VIRTUAL TABLE INDEX %d:%s", pLoop->u.vtab.idxNum, pLoop->u.vtab.idxStr); } #endif #ifdef SQLITE_EXPLAIN_ESTIMATED_ROWS if( pLoop->nOut>=10 ){ sqlite3XPrintf(&str, " (~%llu rows)", sqlite3LogEstToInt(pLoop->nOut)); }else{ sqlite3StrAccumAppend(&str, " (~1 row)", 9); } #endif zMsg = sqlite3StrAccumFinish(&str); ret = sqlite3VdbeAddOp4(v, OP_Explain, iId, iLevel, iFrom, zMsg,P4_DYNAMIC); } return ret; } #endif /* SQLITE_OMIT_EXPLAIN */ #ifdef SQLITE_ENABLE_STMT_SCANSTATUS /* ** Configure the VM passed as the first argument with an ** sqlite3_stmt_scanstatus() entry corresponding to the scan used to ** implement level pLvl. Argument pSrclist is a pointer to the FROM ** clause that the scan reads data from. ** ** If argument addrExplain is not 0, it must be the address of an ** OP_Explain instruction that describes the same loop. */ SQLITE_PRIVATE void sqlite3WhereAddScanStatus( Vdbe *v, /* Vdbe to add scanstatus entry to */ SrcList *pSrclist, /* FROM clause pLvl reads data from */ WhereLevel *pLvl, /* Level to add scanstatus() entry for */ int addrExplain /* Address of OP_Explain (or 0) */ ){ const char *zObj = 0; WhereLoop *pLoop = pLvl->pWLoop; if( (pLoop->wsFlags & WHERE_VIRTUALTABLE)==0 && pLoop->u.btree.pIndex!=0 ){ zObj = pLoop->u.btree.pIndex->zName; }else{ zObj = pSrclist->a[pLvl->iFrom].zName; } sqlite3VdbeScanStatus( v, addrExplain, pLvl->addrBody, pLvl->addrVisit, pLoop->nOut, zObj ); } #endif /* ** Disable a term in the WHERE clause. Except, do not disable the term ** if it controls a LEFT OUTER JOIN and it did not originate in the ON ** or USING clause of that join. ** ** Consider the term t2.z='ok' in the following queries: ** ** (1) SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x WHERE t2.z='ok' ** (2) SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x AND t2.z='ok' ** (3) SELECT * FROM t1, t2 WHERE t1.a=t2.x AND t2.z='ok' ** ** The t2.z='ok' is disabled in the in (2) because it originates ** in the ON clause. The term is disabled in (3) because it is not part ** of a LEFT OUTER JOIN. In (1), the term is not disabled. ** ** Disabling a term causes that term to not be tested in the inner loop ** of the join. Disabling is an optimization. When terms are satisfied ** by indices, we disable them to prevent redundant tests in the inner ** loop. We would get the correct results if nothing were ever disabled, ** but joins might run a little slower. The trick is to disable as much ** as we can without disabling too much. If we disabled in (1), we'd get ** the wrong answer. See ticket #813. ** ** If all the children of a term are disabled, then that term is also ** automatically disabled. In this way, terms get disabled if derived ** virtual terms are tested first. For example: ** ** x GLOB 'abc*' AND x>='abc' AND x<'acd' ** \___________/ \______/ \_____/ ** parent child1 child2 ** ** Only the parent term was in the original WHERE clause. The child1 ** and child2 terms were added by the LIKE optimization. If both of ** the virtual child terms are valid, then testing of the parent can be ** skipped. ** ** Usually the parent term is marked as TERM_CODED. But if the parent ** term was originally TERM_LIKE, then the parent gets TERM_LIKECOND instead. ** The TERM_LIKECOND marking indicates that the term should be coded inside ** a conditional such that is only evaluated on the second pass of a ** LIKE-optimization loop, when scanning BLOBs instead of strings. */ static void disableTerm(WhereLevel *pLevel, WhereTerm *pTerm){ int nLoop = 0; while( ALWAYS(pTerm!=0) && (pTerm->wtFlags & TERM_CODED)==0 && (pLevel->iLeftJoin==0 || ExprHasProperty(pTerm->pExpr, EP_FromJoin)) && (pLevel->notReady & pTerm->prereqAll)==0 ){ if( nLoop && (pTerm->wtFlags & TERM_LIKE)!=0 ){ pTerm->wtFlags |= TERM_LIKECOND; }else{ pTerm->wtFlags |= TERM_CODED; } if( pTerm->iParent<0 ) break; pTerm = &pTerm->pWC->a[pTerm->iParent]; pTerm->nChild--; if( pTerm->nChild!=0 ) break; nLoop++; } } /* ** Code an OP_Affinity opcode to apply the column affinity string zAff ** to the n registers starting at base. ** ** As an optimization, SQLITE_AFF_BLOB entries (which are no-ops) at the ** beginning and end of zAff are ignored. If all entries in zAff are ** SQLITE_AFF_BLOB, then no code gets generated. ** ** This routine makes its own copy of zAff so that the caller is free ** to modify zAff after this routine returns. */ static void codeApplyAffinity(Parse *pParse, int base, int n, char *zAff){ Vdbe *v = pParse->pVdbe; if( zAff==0 ){ assert( pParse->db->mallocFailed ); return; } assert( v!=0 ); /* Adjust base and n to skip over SQLITE_AFF_BLOB entries at the beginning ** and end of the affinity string. */ while( n>0 && zAff[0]==SQLITE_AFF_BLOB ){ n--; base++; zAff++; } while( n>1 && zAff[n-1]==SQLITE_AFF_BLOB ){ n--; } /* Code the OP_Affinity opcode if there is anything left to do. */ if( n>0 ){ sqlite3VdbeAddOp4(v, OP_Affinity, base, n, 0, zAff, n); sqlite3ExprCacheAffinityChange(pParse, base, n); } } /* ** Expression pRight, which is the RHS of a comparison operation, is ** either a vector of n elements or, if n==1, a scalar expression. ** Before the comparison operation, affinity zAff is to be applied ** to the pRight values. This function modifies characters within the ** affinity string to SQLITE_AFF_BLOB if either: ** ** * the comparison will be performed with no affinity, or ** * the affinity change in zAff is guaranteed not to change the value. */ static void updateRangeAffinityStr( Expr *pRight, /* RHS of comparison */ int n, /* Number of vector elements in comparison */ char *zAff /* Affinity string to modify */ ){ int i; for(i=0; ipExpr; Vdbe *v = pParse->pVdbe; int iReg; /* Register holding results */ assert( pLevel->pWLoop->aLTerm[iEq]==pTerm ); assert( iTarget>0 ); if( pX->op==TK_EQ || pX->op==TK_IS ){ iReg = sqlite3ExprCodeTarget(pParse, pX->pRight, iTarget); }else if( pX->op==TK_ISNULL ){ iReg = iTarget; sqlite3VdbeAddOp2(v, OP_Null, 0, iReg); #ifndef SQLITE_OMIT_SUBQUERY }else{ int eType = IN_INDEX_NOOP; int iTab; struct InLoop *pIn; WhereLoop *pLoop = pLevel->pWLoop; int i; int nEq = 0; int *aiMap = 0; if( (pLoop->wsFlags & WHERE_VIRTUALTABLE)==0 && pLoop->u.btree.pIndex!=0 && pLoop->u.btree.pIndex->aSortOrder[iEq] ){ testcase( iEq==0 ); testcase( bRev ); bRev = !bRev; } assert( pX->op==TK_IN ); iReg = iTarget; for(i=0; iaLTerm[i] && pLoop->aLTerm[i]->pExpr==pX ){ disableTerm(pLevel, pTerm); return iTarget; } } for(i=iEq;inLTerm; i++){ if( ALWAYS(pLoop->aLTerm[i]) && pLoop->aLTerm[i]->pExpr==pX ) nEq++; } if( (pX->flags & EP_xIsSelect)==0 || pX->x.pSelect->pEList->nExpr==1 ){ eType = sqlite3FindInIndex(pParse, pX, IN_INDEX_LOOP, 0, 0); }else{ Select *pSelect = pX->x.pSelect; sqlite3 *db = pParse->db; ExprList *pOrigRhs = pSelect->pEList; ExprList *pOrigLhs = pX->pLeft->x.pList; ExprList *pRhs = 0; /* New Select.pEList for RHS */ ExprList *pLhs = 0; /* New pX->pLeft vector */ for(i=iEq;inLTerm; i++){ if( pLoop->aLTerm[i]->pExpr==pX ){ int iField = pLoop->aLTerm[i]->iField - 1; Expr *pNewRhs = sqlite3ExprDup(db, pOrigRhs->a[iField].pExpr, 0); Expr *pNewLhs = sqlite3ExprDup(db, pOrigLhs->a[iField].pExpr, 0); pRhs = sqlite3ExprListAppend(pParse, pRhs, pNewRhs); pLhs = sqlite3ExprListAppend(pParse, pLhs, pNewLhs); } } if( !db->mallocFailed ){ Expr *pLeft = pX->pLeft; if( pSelect->pOrderBy ){ /* If the SELECT statement has an ORDER BY clause, zero the ** iOrderByCol variables. These are set to non-zero when an ** ORDER BY term exactly matches one of the terms of the ** result-set. Since the result-set of the SELECT statement may ** have been modified or reordered, these variables are no longer ** set correctly. Since setting them is just an optimization, ** it's easiest just to zero them here. */ ExprList *pOrderBy = pSelect->pOrderBy; for(i=0; inExpr; i++){ pOrderBy->a[i].u.x.iOrderByCol = 0; } } /* Take care here not to generate a TK_VECTOR containing only a ** single value. Since the parser never creates such a vector, some ** of the subroutines do not handle this case. */ if( pLhs->nExpr==1 ){ pX->pLeft = pLhs->a[0].pExpr; }else{ pLeft->x.pList = pLhs; aiMap = (int*)sqlite3DbMallocZero(pParse->db, sizeof(int) * nEq); testcase( aiMap==0 ); } pSelect->pEList = pRhs; eType = sqlite3FindInIndex(pParse, pX, IN_INDEX_LOOP, 0, aiMap); testcase( aiMap!=0 && aiMap[0]!=0 ); pSelect->pEList = pOrigRhs; pLeft->x.pList = pOrigLhs; pX->pLeft = pLeft; } sqlite3ExprListDelete(pParse->db, pLhs); sqlite3ExprListDelete(pParse->db, pRhs); } if( eType==IN_INDEX_INDEX_DESC ){ testcase( bRev ); bRev = !bRev; } iTab = pX->iTable; sqlite3VdbeAddOp2(v, bRev ? OP_Last : OP_Rewind, iTab, 0); VdbeCoverageIf(v, bRev); VdbeCoverageIf(v, !bRev); assert( (pLoop->wsFlags & WHERE_MULTI_OR)==0 ); pLoop->wsFlags |= WHERE_IN_ABLE; if( pLevel->u.in.nIn==0 ){ pLevel->addrNxt = sqlite3VdbeMakeLabel(v); } i = pLevel->u.in.nIn; pLevel->u.in.nIn += nEq; pLevel->u.in.aInLoop = sqlite3DbReallocOrFree(pParse->db, pLevel->u.in.aInLoop, sizeof(pLevel->u.in.aInLoop[0])*pLevel->u.in.nIn); pIn = pLevel->u.in.aInLoop; if( pIn ){ int iMap = 0; /* Index in aiMap[] */ pIn += i; for(i=iEq;inLTerm; i++){ if( pLoop->aLTerm[i]->pExpr==pX ){ int iOut = iReg + i - iEq; if( eType==IN_INDEX_ROWID ){ testcase( nEq>1 ); /* Happens with a UNIQUE index on ROWID */ pIn->addrInTop = sqlite3VdbeAddOp2(v, OP_Rowid, iTab, iOut); }else{ int iCol = aiMap ? aiMap[iMap++] : 0; pIn->addrInTop = sqlite3VdbeAddOp3(v,OP_Column,iTab, iCol, iOut); } sqlite3VdbeAddOp1(v, OP_IsNull, iOut); VdbeCoverage(v); if( i==iEq ){ pIn->iCur = iTab; pIn->eEndLoopOp = bRev ? OP_PrevIfOpen : OP_NextIfOpen; }else{ pIn->eEndLoopOp = OP_Noop; } pIn++; } } }else{ pLevel->u.in.nIn = 0; } sqlite3DbFree(pParse->db, aiMap); #endif } disableTerm(pLevel, pTerm); return iReg; } /* ** Generate code that will evaluate all == and IN constraints for an ** index scan. ** ** For example, consider table t1(a,b,c,d,e,f) with index i1(a,b,c). ** Suppose the WHERE clause is this: a==5 AND b IN (1,2,3) AND c>5 AND c<10 ** The index has as many as three equality constraints, but in this ** example, the third "c" value is an inequality. So only two ** constraints are coded. This routine will generate code to evaluate ** a==5 and b IN (1,2,3). The current values for a and b will be stored ** in consecutive registers and the index of the first register is returned. ** ** In the example above nEq==2. But this subroutine works for any value ** of nEq including 0. If nEq==0, this routine is nearly a no-op. ** The only thing it does is allocate the pLevel->iMem memory cell and ** compute the affinity string. ** ** The nExtraReg parameter is 0 or 1. It is 0 if all WHERE clause constraints ** are == or IN and are covered by the nEq. nExtraReg is 1 if there is ** an inequality constraint (such as the "c>=5 AND c<10" in the example) that ** occurs after the nEq quality constraints. ** ** This routine allocates a range of nEq+nExtraReg memory cells and returns ** the index of the first memory cell in that range. The code that ** calls this routine will use that memory range to store keys for ** start and termination conditions of the loop. ** key value of the loop. If one or more IN operators appear, then ** this routine allocates an additional nEq memory cells for internal ** use. ** ** Before returning, *pzAff is set to point to a buffer containing a ** copy of the column affinity string of the index allocated using ** sqlite3DbMalloc(). Except, entries in the copy of the string associated ** with equality constraints that use BLOB or NONE affinity are set to ** SQLITE_AFF_BLOB. This is to deal with SQL such as the following: ** ** CREATE TABLE t1(a TEXT PRIMARY KEY, b); ** SELECT ... FROM t1 AS t2, t1 WHERE t1.a = t2.b; ** ** In the example above, the index on t1(a) has TEXT affinity. But since ** the right hand side of the equality constraint (t2.b) has BLOB/NONE affinity, ** no conversion should be attempted before using a t2.b value as part of ** a key to search the index. Hence the first byte in the returned affinity ** string in this example would be set to SQLITE_AFF_BLOB. */ static int codeAllEqualityTerms( Parse *pParse, /* Parsing context */ WhereLevel *pLevel, /* Which nested loop of the FROM we are coding */ int bRev, /* Reverse the order of IN operators */ int nExtraReg, /* Number of extra registers to allocate */ char **pzAff /* OUT: Set to point to affinity string */ ){ u16 nEq; /* The number of == or IN constraints to code */ u16 nSkip; /* Number of left-most columns to skip */ Vdbe *v = pParse->pVdbe; /* The vm under construction */ Index *pIdx; /* The index being used for this loop */ WhereTerm *pTerm; /* A single constraint term */ WhereLoop *pLoop; /* The WhereLoop object */ int j; /* Loop counter */ int regBase; /* Base register */ int nReg; /* Number of registers to allocate */ char *zAff; /* Affinity string to return */ /* This module is only called on query plans that use an index. */ pLoop = pLevel->pWLoop; assert( (pLoop->wsFlags & WHERE_VIRTUALTABLE)==0 ); nEq = pLoop->u.btree.nEq; nSkip = pLoop->nSkip; pIdx = pLoop->u.btree.pIndex; assert( pIdx!=0 ); /* Figure out how many memory cells we will need then allocate them. */ regBase = pParse->nMem + 1; nReg = pLoop->u.btree.nEq + nExtraReg; pParse->nMem += nReg; zAff = sqlite3DbStrDup(pParse->db,sqlite3IndexAffinityStr(pParse->db,pIdx)); assert( zAff!=0 || pParse->db->mallocFailed ); if( nSkip ){ int iIdxCur = pLevel->iIdxCur; sqlite3VdbeAddOp1(v, (bRev?OP_Last:OP_Rewind), iIdxCur); VdbeCoverageIf(v, bRev==0); VdbeCoverageIf(v, bRev!=0); VdbeComment((v, "begin skip-scan on %s", pIdx->zName)); j = sqlite3VdbeAddOp0(v, OP_Goto); pLevel->addrSkip = sqlite3VdbeAddOp4Int(v, (bRev?OP_SeekLT:OP_SeekGT), iIdxCur, 0, regBase, nSkip); VdbeCoverageIf(v, bRev==0); VdbeCoverageIf(v, bRev!=0); sqlite3VdbeJumpHere(v, j); for(j=0; jaiColumn[j]==XN_EXPR ); VdbeComment((v, "%s", explainIndexColumnName(pIdx, j))); } } /* Evaluate the equality constraints */ assert( zAff==0 || (int)strlen(zAff)>=nEq ); for(j=nSkip; jaLTerm[j]; assert( pTerm!=0 ); /* The following testcase is true for indices with redundant columns. ** Ex: CREATE INDEX i1 ON t1(a,b,a); SELECT * FROM t1 WHERE a=0 AND b=0; */ testcase( (pTerm->wtFlags & TERM_CODED)!=0 ); testcase( pTerm->wtFlags & TERM_VIRTUAL ); r1 = codeEqualityTerm(pParse, pTerm, pLevel, j, bRev, regBase+j); if( r1!=regBase+j ){ if( nReg==1 ){ sqlite3ReleaseTempReg(pParse, regBase); regBase = r1; }else{ sqlite3VdbeAddOp2(v, OP_SCopy, r1, regBase+j); } } if( pTerm->eOperator & WO_IN ){ if( pTerm->pExpr->flags & EP_xIsSelect ){ /* No affinity ever needs to be (or should be) applied to a value ** from the RHS of an "? IN (SELECT ...)" expression. The ** sqlite3FindInIndex() routine has already ensured that the ** affinity of the comparison has been applied to the value. */ if( zAff ) zAff[j] = SQLITE_AFF_BLOB; } }else if( (pTerm->eOperator & WO_ISNULL)==0 ){ Expr *pRight = pTerm->pExpr->pRight; if( (pTerm->wtFlags & TERM_IS)==0 && sqlite3ExprCanBeNull(pRight) ){ sqlite3VdbeAddOp2(v, OP_IsNull, regBase+j, pLevel->addrBrk); VdbeCoverage(v); } if( zAff ){ if( sqlite3CompareAffinity(pRight, zAff[j])==SQLITE_AFF_BLOB ){ zAff[j] = SQLITE_AFF_BLOB; } if( sqlite3ExprNeedsNoAffinityChange(pRight, zAff[j]) ){ zAff[j] = SQLITE_AFF_BLOB; } } } } *pzAff = zAff; return regBase; } #ifndef SQLITE_LIKE_DOESNT_MATCH_BLOBS /* ** If the most recently coded instruction is a constant range constraint ** (a string literal) that originated from the LIKE optimization, then ** set P3 and P5 on the OP_String opcode so that the string will be cast ** to a BLOB at appropriate times. ** ** The LIKE optimization trys to evaluate "x LIKE 'abc%'" as a range ** expression: "x>='ABC' AND x<'abd'". But this requires that the range ** scan loop run twice, once for strings and a second time for BLOBs. ** The OP_String opcodes on the second pass convert the upper and lower ** bound string constants to blobs. This routine makes the necessary changes ** to the OP_String opcodes for that to happen. ** ** Except, of course, if SQLITE_LIKE_DOESNT_MATCH_BLOBS is defined, then ** only the one pass through the string space is required, so this routine ** becomes a no-op. */ static void whereLikeOptimizationStringFixup( Vdbe *v, /* prepared statement under construction */ WhereLevel *pLevel, /* The loop that contains the LIKE operator */ WhereTerm *pTerm /* The upper or lower bound just coded */ ){ if( pTerm->wtFlags & TERM_LIKEOPT ){ VdbeOp *pOp; assert( pLevel->iLikeRepCntr>0 ); pOp = sqlite3VdbeGetOp(v, -1); assert( pOp!=0 ); assert( pOp->opcode==OP_String8 || pTerm->pWC->pWInfo->pParse->db->mallocFailed ); pOp->p3 = (int)(pLevel->iLikeRepCntr>>1); /* Register holding counter */ pOp->p5 = (u8)(pLevel->iLikeRepCntr&1); /* ASC or DESC */ } } #else # define whereLikeOptimizationStringFixup(A,B,C) #endif #ifdef SQLITE_ENABLE_CURSOR_HINTS /* ** Information is passed from codeCursorHint() down to individual nodes of ** the expression tree (by sqlite3WalkExpr()) using an instance of this ** structure. */ struct CCurHint { int iTabCur; /* Cursor for the main table */ int iIdxCur; /* Cursor for the index, if pIdx!=0. Unused otherwise */ Index *pIdx; /* The index used to access the table */ }; /* ** This function is called for every node of an expression that is a candidate ** for a cursor hint on an index cursor. For TK_COLUMN nodes that reference ** the table CCurHint.iTabCur, verify that the same column can be ** accessed through the index. If it cannot, then set pWalker->eCode to 1. */ static int codeCursorHintCheckExpr(Walker *pWalker, Expr *pExpr){ struct CCurHint *pHint = pWalker->u.pCCurHint; assert( pHint->pIdx!=0 ); if( pExpr->op==TK_COLUMN && pExpr->iTable==pHint->iTabCur && sqlite3ColumnOfIndex(pHint->pIdx, pExpr->iColumn)<0 ){ pWalker->eCode = 1; } return WRC_Continue; } /* ** Test whether or not expression pExpr, which was part of a WHERE clause, ** should be included in the cursor-hint for a table that is on the rhs ** of a LEFT JOIN. Set Walker.eCode to non-zero before returning if the ** expression is not suitable. ** ** An expression is unsuitable if it might evaluate to non NULL even if ** a TK_COLUMN node that does affect the value of the expression is set ** to NULL. For example: ** ** col IS NULL ** col IS NOT NULL ** coalesce(col, 1) ** CASE WHEN col THEN 0 ELSE 1 END */ static int codeCursorHintIsOrFunction(Walker *pWalker, Expr *pExpr){ if( pExpr->op==TK_IS || pExpr->op==TK_ISNULL || pExpr->op==TK_ISNOT || pExpr->op==TK_NOTNULL || pExpr->op==TK_CASE ){ pWalker->eCode = 1; }else if( pExpr->op==TK_FUNCTION ){ int d1; char d2[3]; if( 0==sqlite3IsLikeFunction(pWalker->pParse->db, pExpr, &d1, d2) ){ pWalker->eCode = 1; } } return WRC_Continue; } /* ** This function is called on every node of an expression tree used as an ** argument to the OP_CursorHint instruction. If the node is a TK_COLUMN ** that accesses any table other than the one identified by ** CCurHint.iTabCur, then do the following: ** ** 1) allocate a register and code an OP_Column instruction to read ** the specified column into the new register, and ** ** 2) transform the expression node to a TK_REGISTER node that reads ** from the newly populated register. ** ** Also, if the node is a TK_COLUMN that does access the table idenified ** by pCCurHint.iTabCur, and an index is being used (which we will ** know because CCurHint.pIdx!=0) then transform the TK_COLUMN into ** an access of the index rather than the original table. */ static int codeCursorHintFixExpr(Walker *pWalker, Expr *pExpr){ int rc = WRC_Continue; struct CCurHint *pHint = pWalker->u.pCCurHint; if( pExpr->op==TK_COLUMN ){ if( pExpr->iTable!=pHint->iTabCur ){ Vdbe *v = pWalker->pParse->pVdbe; int reg = ++pWalker->pParse->nMem; /* Register for column value */ sqlite3ExprCodeGetColumnOfTable( v, pExpr->pTab, pExpr->iTable, pExpr->iColumn, reg ); pExpr->op = TK_REGISTER; pExpr->iTable = reg; }else if( pHint->pIdx!=0 ){ pExpr->iTable = pHint->iIdxCur; pExpr->iColumn = sqlite3ColumnOfIndex(pHint->pIdx, pExpr->iColumn); assert( pExpr->iColumn>=0 ); } }else if( pExpr->op==TK_AGG_FUNCTION ){ /* An aggregate function in the WHERE clause of a query means this must ** be a correlated sub-query, and expression pExpr is an aggregate from ** the parent context. Do not walk the function arguments in this case. ** ** todo: It should be possible to replace this node with a TK_REGISTER ** expression, as the result of the expression must be stored in a ** register at this point. The same holds for TK_AGG_COLUMN nodes. */ rc = WRC_Prune; } return rc; } /* ** Insert an OP_CursorHint instruction if it is appropriate to do so. */ static void codeCursorHint( struct SrcList_item *pTabItem, /* FROM clause item */ WhereInfo *pWInfo, /* The where clause */ WhereLevel *pLevel, /* Which loop to provide hints for */ WhereTerm *pEndRange /* Hint this end-of-scan boundary term if not NULL */ ){ Parse *pParse = pWInfo->pParse; sqlite3 *db = pParse->db; Vdbe *v = pParse->pVdbe; Expr *pExpr = 0; WhereLoop *pLoop = pLevel->pWLoop; int iCur; WhereClause *pWC; WhereTerm *pTerm; int i, j; struct CCurHint sHint; Walker sWalker; if( OptimizationDisabled(db, SQLITE_CursorHints) ) return; iCur = pLevel->iTabCur; assert( iCur==pWInfo->pTabList->a[pLevel->iFrom].iCursor ); sHint.iTabCur = iCur; sHint.iIdxCur = pLevel->iIdxCur; sHint.pIdx = pLoop->u.btree.pIndex; memset(&sWalker, 0, sizeof(sWalker)); sWalker.pParse = pParse; sWalker.u.pCCurHint = &sHint; pWC = &pWInfo->sWC; for(i=0; inTerm; i++){ pTerm = &pWC->a[i]; if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue; if( pTerm->prereqAll & pLevel->notReady ) continue; /* Any terms specified as part of the ON(...) clause for any LEFT ** JOIN for which the current table is not the rhs are omitted ** from the cursor-hint. ** ** If this table is the rhs of a LEFT JOIN, "IS" or "IS NULL" terms ** that were specified as part of the WHERE clause must be excluded. ** This is to address the following: ** ** SELECT ... t1 LEFT JOIN t2 ON (t1.a=t2.b) WHERE t2.c IS NULL; ** ** Say there is a single row in t2 that matches (t1.a=t2.b), but its ** t2.c values is not NULL. If the (t2.c IS NULL) constraint is ** pushed down to the cursor, this row is filtered out, causing ** SQLite to synthesize a row of NULL values. Which does match the ** WHERE clause, and so the query returns a row. Which is incorrect. ** ** For the same reason, WHERE terms such as: ** ** WHERE 1 = (t2.c IS NULL) ** ** are also excluded. See codeCursorHintIsOrFunction() for details. */ if( pTabItem->fg.jointype & JT_LEFT ){ Expr *pExpr = pTerm->pExpr; if( !ExprHasProperty(pExpr, EP_FromJoin) || pExpr->iRightJoinTable!=pTabItem->iCursor ){ sWalker.eCode = 0; sWalker.xExprCallback = codeCursorHintIsOrFunction; sqlite3WalkExpr(&sWalker, pTerm->pExpr); if( sWalker.eCode ) continue; } }else{ if( ExprHasProperty(pTerm->pExpr, EP_FromJoin) ) continue; } /* All terms in pWLoop->aLTerm[] except pEndRange are used to initialize ** the cursor. These terms are not needed as hints for a pure range ** scan (that has no == terms) so omit them. */ if( pLoop->u.btree.nEq==0 && pTerm!=pEndRange ){ for(j=0; jnLTerm && pLoop->aLTerm[j]!=pTerm; j++){} if( jnLTerm ) continue; } /* No subqueries or non-deterministic functions allowed */ if( sqlite3ExprContainsSubquery(pTerm->pExpr) ) continue; /* For an index scan, make sure referenced columns are actually in ** the index. */ if( sHint.pIdx!=0 ){ sWalker.eCode = 0; sWalker.xExprCallback = codeCursorHintCheckExpr; sqlite3WalkExpr(&sWalker, pTerm->pExpr); if( sWalker.eCode ) continue; } /* If we survive all prior tests, that means this term is worth hinting */ pExpr = sqlite3ExprAnd(db, pExpr, sqlite3ExprDup(db, pTerm->pExpr, 0)); } if( pExpr!=0 ){ sWalker.xExprCallback = codeCursorHintFixExpr; sqlite3WalkExpr(&sWalker, pExpr); sqlite3VdbeAddOp4(v, OP_CursorHint, (sHint.pIdx ? sHint.iIdxCur : sHint.iTabCur), 0, 0, (const char*)pExpr, P4_EXPR); } } #else # define codeCursorHint(A,B,C,D) /* No-op */ #endif /* SQLITE_ENABLE_CURSOR_HINTS */ /* ** Cursor iCur is open on an intkey b-tree (a table). Register iRowid contains ** a rowid value just read from cursor iIdxCur, open on index pIdx. This ** function generates code to do a deferred seek of cursor iCur to the ** rowid stored in register iRowid. ** ** Normally, this is just: ** ** OP_Seek $iCur $iRowid ** ** However, if the scan currently being coded is a branch of an OR-loop and ** the statement currently being coded is a SELECT, then P3 of the OP_Seek ** is set to iIdxCur and P4 is set to point to an array of integers ** containing one entry for each column of the table cursor iCur is open ** on. For each table column, if the column is the i'th column of the ** index, then the corresponding array entry is set to (i+1). If the column ** does not appear in the index at all, the array entry is set to 0. */ static void codeDeferredSeek( WhereInfo *pWInfo, /* Where clause context */ Index *pIdx, /* Index scan is using */ int iCur, /* Cursor for IPK b-tree */ int iIdxCur /* Index cursor */ ){ Parse *pParse = pWInfo->pParse; /* Parse context */ Vdbe *v = pParse->pVdbe; /* Vdbe to generate code within */ assert( iIdxCur>0 ); assert( pIdx->aiColumn[pIdx->nColumn-1]==-1 ); sqlite3VdbeAddOp3(v, OP_Seek, iIdxCur, 0, iCur); if( (pWInfo->wctrlFlags & WHERE_OR_SUBCLAUSE) && DbMaskAllZero(sqlite3ParseToplevel(pParse)->writeMask) ){ int i; Table *pTab = pIdx->pTable; int *ai = (int*)sqlite3DbMallocZero(pParse->db, sizeof(int)*(pTab->nCol+1)); if( ai ){ ai[0] = pTab->nCol; for(i=0; inColumn-1; i++){ assert( pIdx->aiColumn[i]nCol ); if( pIdx->aiColumn[i]>=0 ) ai[pIdx->aiColumn[i]+1] = i+1; } sqlite3VdbeChangeP4(v, -1, (char*)ai, P4_INTARRAY); } } } /* ** If the expression passed as the second argument is a vector, generate ** code to write the first nReg elements of the vector into an array ** of registers starting with iReg. ** ** If the expression is not a vector, then nReg must be passed 1. In ** this case, generate code to evaluate the expression and leave the ** result in register iReg. */ static void codeExprOrVector(Parse *pParse, Expr *p, int iReg, int nReg){ assert( nReg>0 ); if( sqlite3ExprIsVector(p) ){ #ifndef SQLITE_OMIT_SUBQUERY if( (p->flags & EP_xIsSelect) ){ Vdbe *v = pParse->pVdbe; int iSelect = sqlite3CodeSubselect(pParse, p, 0, 0); sqlite3VdbeAddOp3(v, OP_Copy, iSelect, iReg, nReg-1); }else #endif { int i; ExprList *pList = p->x.pList; assert( nReg<=pList->nExpr ); for(i=0; ia[i].pExpr, iReg+i); } } }else{ assert( nReg==1 ); sqlite3ExprCode(pParse, p, iReg); } } /* ** Generate code for the start of the iLevel-th loop in the WHERE clause ** implementation described by pWInfo. */ SQLITE_PRIVATE Bitmask sqlite3WhereCodeOneLoopStart( WhereInfo *pWInfo, /* Complete information about the WHERE clause */ int iLevel, /* Which level of pWInfo->a[] should be coded */ Bitmask notReady /* Which tables are currently available */ ){ int j, k; /* Loop counters */ int iCur; /* The VDBE cursor for the table */ int addrNxt; /* Where to jump to continue with the next IN case */ int omitTable; /* True if we use the index only */ int bRev; /* True if we need to scan in reverse order */ WhereLevel *pLevel; /* The where level to be coded */ WhereLoop *pLoop; /* The WhereLoop object being coded */ WhereClause *pWC; /* Decomposition of the entire WHERE clause */ WhereTerm *pTerm; /* A WHERE clause term */ Parse *pParse; /* Parsing context */ sqlite3 *db; /* Database connection */ Vdbe *v; /* The prepared stmt under constructions */ struct SrcList_item *pTabItem; /* FROM clause term being coded */ int addrBrk; /* Jump here to break out of the loop */ int addrCont; /* Jump here to continue with next cycle */ int iRowidReg = 0; /* Rowid is stored in this register, if not zero */ int iReleaseReg = 0; /* Temp register to free before returning */ pParse = pWInfo->pParse; v = pParse->pVdbe; pWC = &pWInfo->sWC; db = pParse->db; pLevel = &pWInfo->a[iLevel]; pLoop = pLevel->pWLoop; pTabItem = &pWInfo->pTabList->a[pLevel->iFrom]; iCur = pTabItem->iCursor; pLevel->notReady = notReady & ~sqlite3WhereGetMask(&pWInfo->sMaskSet, iCur); bRev = (pWInfo->revMask>>iLevel)&1; omitTable = (pLoop->wsFlags & WHERE_IDX_ONLY)!=0 && (pWInfo->wctrlFlags & WHERE_OR_SUBCLAUSE)==0; VdbeModuleComment((v, "Begin WHERE-loop%d: %s",iLevel,pTabItem->pTab->zName)); /* Create labels for the "break" and "continue" instructions ** for the current loop. Jump to addrBrk to break out of a loop. ** Jump to cont to go immediately to the next iteration of the ** loop. ** ** When there is an IN operator, we also have a "addrNxt" label that ** means to continue with the next IN value combination. When ** there are no IN operators in the constraints, the "addrNxt" label ** is the same as "addrBrk". */ addrBrk = pLevel->addrBrk = pLevel->addrNxt = sqlite3VdbeMakeLabel(v); addrCont = pLevel->addrCont = sqlite3VdbeMakeLabel(v); /* If this is the right table of a LEFT OUTER JOIN, allocate and ** initialize a memory cell that records if this table matches any ** row of the left table of the join. */ if( pLevel->iFrom>0 && (pTabItem[0].fg.jointype & JT_LEFT)!=0 ){ pLevel->iLeftJoin = ++pParse->nMem; sqlite3VdbeAddOp2(v, OP_Integer, 0, pLevel->iLeftJoin); VdbeComment((v, "init LEFT JOIN no-match flag")); } /* Special case of a FROM clause subquery implemented as a co-routine */ if( pTabItem->fg.viaCoroutine ){ int regYield = pTabItem->regReturn; sqlite3VdbeAddOp3(v, OP_InitCoroutine, regYield, 0, pTabItem->addrFillSub); pLevel->p2 = sqlite3VdbeAddOp2(v, OP_Yield, regYield, addrBrk); VdbeCoverage(v); VdbeComment((v, "next row of \"%s\"", pTabItem->pTab->zName)); pLevel->op = OP_Goto; }else #ifndef SQLITE_OMIT_VIRTUALTABLE if( (pLoop->wsFlags & WHERE_VIRTUALTABLE)!=0 ){ /* Case 1: The table is a virtual-table. Use the VFilter and VNext ** to access the data. */ int iReg; /* P3 Value for OP_VFilter */ int addrNotFound; int nConstraint = pLoop->nLTerm; int iIn; /* Counter for IN constraints */ sqlite3ExprCachePush(pParse); iReg = sqlite3GetTempRange(pParse, nConstraint+2); addrNotFound = pLevel->addrBrk; for(j=0; jaLTerm[j]; if( NEVER(pTerm==0) ) continue; if( pTerm->eOperator & WO_IN ){ codeEqualityTerm(pParse, pTerm, pLevel, j, bRev, iTarget); addrNotFound = pLevel->addrNxt; }else{ Expr *pRight = pTerm->pExpr->pRight; codeExprOrVector(pParse, pRight, iTarget, 1); } } sqlite3VdbeAddOp2(v, OP_Integer, pLoop->u.vtab.idxNum, iReg); sqlite3VdbeAddOp2(v, OP_Integer, nConstraint, iReg+1); sqlite3VdbeAddOp4(v, OP_VFilter, iCur, addrNotFound, iReg, pLoop->u.vtab.idxStr, pLoop->u.vtab.needFree ? P4_MPRINTF : P4_STATIC); VdbeCoverage(v); pLoop->u.vtab.needFree = 0; pLevel->p1 = iCur; pLevel->op = pWInfo->eOnePass ? OP_Noop : OP_VNext; pLevel->p2 = sqlite3VdbeCurrentAddr(v); iIn = pLevel->u.in.nIn; for(j=nConstraint-1; j>=0; j--){ pTerm = pLoop->aLTerm[j]; if( j<16 && (pLoop->u.vtab.omitMask>>j)&1 ){ disableTerm(pLevel, pTerm); }else if( (pTerm->eOperator & WO_IN)!=0 ){ Expr *pCompare; /* The comparison operator */ Expr *pRight; /* RHS of the comparison */ VdbeOp *pOp; /* Opcode to access the value of the IN constraint */ /* Reload the constraint value into reg[iReg+j+2]. The same value ** was loaded into the same register prior to the OP_VFilter, but ** the xFilter implementation might have changed the datatype or ** encoding of the value in the register, so it *must* be reloaded. */ assert( pLevel->u.in.aInLoop!=0 || db->mallocFailed ); if( !db->mallocFailed ){ assert( iIn>0 ); pOp = sqlite3VdbeGetOp(v, pLevel->u.in.aInLoop[--iIn].addrInTop); assert( pOp->opcode==OP_Column || pOp->opcode==OP_Rowid ); assert( pOp->opcode!=OP_Column || pOp->p3==iReg+j+2 ); assert( pOp->opcode!=OP_Rowid || pOp->p2==iReg+j+2 ); testcase( pOp->opcode==OP_Rowid ); sqlite3VdbeAddOp3(v, pOp->opcode, pOp->p1, pOp->p2, pOp->p3); } /* Generate code that will continue to the next row if ** the IN constraint is not satisfied */ pCompare = sqlite3PExpr(pParse, TK_EQ, 0, 0, 0); assert( pCompare!=0 || db->mallocFailed ); if( pCompare ){ pCompare->pLeft = pTerm->pExpr->pLeft; pCompare->pRight = pRight = sqlite3Expr(db, TK_REGISTER, 0); if( pRight ){ pRight->iTable = iReg+j+2; sqlite3ExprIfFalse(pParse, pCompare, pLevel->addrCont, 0); } pCompare->pLeft = 0; sqlite3ExprDelete(db, pCompare); } } } /* These registers need to be preserved in case there is an IN operator ** loop. So we could deallocate the registers here (and potentially ** reuse them later) if (pLoop->wsFlags & WHERE_IN_ABLE)==0. But it seems ** simpler and safer to simply not reuse the registers. ** ** sqlite3ReleaseTempRange(pParse, iReg, nConstraint+2); */ sqlite3ExprCachePop(pParse); }else #endif /* SQLITE_OMIT_VIRTUALTABLE */ if( (pLoop->wsFlags & WHERE_IPK)!=0 && (pLoop->wsFlags & (WHERE_COLUMN_IN|WHERE_COLUMN_EQ))!=0 ){ /* Case 2: We can directly reference a single row using an ** equality comparison against the ROWID field. Or ** we reference multiple rows using a "rowid IN (...)" ** construct. */ assert( pLoop->u.btree.nEq==1 ); pTerm = pLoop->aLTerm[0]; assert( pTerm!=0 ); assert( pTerm->pExpr!=0 ); assert( omitTable==0 ); testcase( pTerm->wtFlags & TERM_VIRTUAL ); iReleaseReg = ++pParse->nMem; iRowidReg = codeEqualityTerm(pParse, pTerm, pLevel, 0, bRev, iReleaseReg); if( iRowidReg!=iReleaseReg ) sqlite3ReleaseTempReg(pParse, iReleaseReg); addrNxt = pLevel->addrNxt; sqlite3VdbeAddOp3(v, OP_SeekRowid, iCur, addrNxt, iRowidReg); VdbeCoverage(v); sqlite3ExprCacheAffinityChange(pParse, iRowidReg, 1); sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg); VdbeComment((v, "pk")); pLevel->op = OP_Noop; }else if( (pLoop->wsFlags & WHERE_IPK)!=0 && (pLoop->wsFlags & WHERE_COLUMN_RANGE)!=0 ){ /* Case 3: We have an inequality comparison against the ROWID field. */ int testOp = OP_Noop; int start; int memEndValue = 0; WhereTerm *pStart, *pEnd; assert( omitTable==0 ); j = 0; pStart = pEnd = 0; if( pLoop->wsFlags & WHERE_BTM_LIMIT ) pStart = pLoop->aLTerm[j++]; if( pLoop->wsFlags & WHERE_TOP_LIMIT ) pEnd = pLoop->aLTerm[j++]; assert( pStart!=0 || pEnd!=0 ); if( bRev ){ pTerm = pStart; pStart = pEnd; pEnd = pTerm; } codeCursorHint(pTabItem, pWInfo, pLevel, pEnd); if( pStart ){ Expr *pX; /* The expression that defines the start bound */ int r1, rTemp; /* Registers for holding the start boundary */ int op; /* Cursor seek operation */ /* The following constant maps TK_xx codes into corresponding ** seek opcodes. It depends on a particular ordering of TK_xx */ const u8 aMoveOp[] = { /* TK_GT */ OP_SeekGT, /* TK_LE */ OP_SeekLE, /* TK_LT */ OP_SeekLT, /* TK_GE */ OP_SeekGE }; assert( TK_LE==TK_GT+1 ); /* Make sure the ordering.. */ assert( TK_LT==TK_GT+2 ); /* ... of the TK_xx values... */ assert( TK_GE==TK_GT+3 ); /* ... is correcct. */ assert( (pStart->wtFlags & TERM_VNULL)==0 ); testcase( pStart->wtFlags & TERM_VIRTUAL ); pX = pStart->pExpr; assert( pX!=0 ); testcase( pStart->leftCursor!=iCur ); /* transitive constraints */ if( sqlite3ExprIsVector(pX->pRight) ){ r1 = rTemp = sqlite3GetTempReg(pParse); codeExprOrVector(pParse, pX->pRight, r1, 1); op = aMoveOp[(pX->op - TK_GT) | 0x0001]; }else{ r1 = sqlite3ExprCodeTemp(pParse, pX->pRight, &rTemp); disableTerm(pLevel, pStart); op = aMoveOp[(pX->op - TK_GT)]; } sqlite3VdbeAddOp3(v, op, iCur, addrBrk, r1); VdbeComment((v, "pk")); VdbeCoverageIf(v, pX->op==TK_GT); VdbeCoverageIf(v, pX->op==TK_LE); VdbeCoverageIf(v, pX->op==TK_LT); VdbeCoverageIf(v, pX->op==TK_GE); sqlite3ExprCacheAffinityChange(pParse, r1, 1); sqlite3ReleaseTempReg(pParse, rTemp); }else{ sqlite3VdbeAddOp2(v, bRev ? OP_Last : OP_Rewind, iCur, addrBrk); VdbeCoverageIf(v, bRev==0); VdbeCoverageIf(v, bRev!=0); } if( pEnd ){ Expr *pX; pX = pEnd->pExpr; assert( pX!=0 ); assert( (pEnd->wtFlags & TERM_VNULL)==0 ); testcase( pEnd->leftCursor!=iCur ); /* Transitive constraints */ testcase( pEnd->wtFlags & TERM_VIRTUAL ); memEndValue = ++pParse->nMem; codeExprOrVector(pParse, pX->pRight, memEndValue, 1); if( 0==sqlite3ExprIsVector(pX->pRight) && (pX->op==TK_LT || pX->op==TK_GT) ){ testOp = bRev ? OP_Le : OP_Ge; }else{ testOp = bRev ? OP_Lt : OP_Gt; } if( 0==sqlite3ExprIsVector(pX->pRight) ){ disableTerm(pLevel, pEnd); } } start = sqlite3VdbeCurrentAddr(v); pLevel->op = bRev ? OP_Prev : OP_Next; pLevel->p1 = iCur; pLevel->p2 = start; assert( pLevel->p5==0 ); if( testOp!=OP_Noop ){ iRowidReg = ++pParse->nMem; sqlite3VdbeAddOp2(v, OP_Rowid, iCur, iRowidReg); sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg); sqlite3VdbeAddOp3(v, testOp, memEndValue, addrBrk, iRowidReg); VdbeCoverageIf(v, testOp==OP_Le); VdbeCoverageIf(v, testOp==OP_Lt); VdbeCoverageIf(v, testOp==OP_Ge); VdbeCoverageIf(v, testOp==OP_Gt); sqlite3VdbeChangeP5(v, SQLITE_AFF_NUMERIC | SQLITE_JUMPIFNULL); } }else if( pLoop->wsFlags & WHERE_INDEXED ){ /* Case 4: A scan using an index. ** ** The WHERE clause may contain zero or more equality ** terms ("==" or "IN" operators) that refer to the N ** left-most columns of the index. It may also contain ** inequality constraints (>, <, >= or <=) on the indexed ** column that immediately follows the N equalities. Only ** the right-most column can be an inequality - the rest must ** use the "==" and "IN" operators. For example, if the ** index is on (x,y,z), then the following clauses are all ** optimized: ** ** x=5 ** x=5 AND y=10 ** x=5 AND y<10 ** x=5 AND y>5 AND y<10 ** x=5 AND y=5 AND z<=10 ** ** The z<10 term of the following cannot be used, only ** the x=5 term: ** ** x=5 AND z<10 ** ** N may be zero if there are inequality constraints. ** If there are no inequality constraints, then N is at ** least one. ** ** This case is also used when there are no WHERE clause ** constraints but an index is selected anyway, in order ** to force the output order to conform to an ORDER BY. */ static const u8 aStartOp[] = { 0, 0, OP_Rewind, /* 2: (!start_constraints && startEq && !bRev) */ OP_Last, /* 3: (!start_constraints && startEq && bRev) */ OP_SeekGT, /* 4: (start_constraints && !startEq && !bRev) */ OP_SeekLT, /* 5: (start_constraints && !startEq && bRev) */ OP_SeekGE, /* 6: (start_constraints && startEq && !bRev) */ OP_SeekLE /* 7: (start_constraints && startEq && bRev) */ }; static const u8 aEndOp[] = { OP_IdxGE, /* 0: (end_constraints && !bRev && !endEq) */ OP_IdxGT, /* 1: (end_constraints && !bRev && endEq) */ OP_IdxLE, /* 2: (end_constraints && bRev && !endEq) */ OP_IdxLT, /* 3: (end_constraints && bRev && endEq) */ }; u16 nEq = pLoop->u.btree.nEq; /* Number of == or IN terms */ u16 nBtm = pLoop->u.btree.nBtm; /* Length of BTM vector */ u16 nTop = pLoop->u.btree.nTop; /* Length of TOP vector */ int regBase; /* Base register holding constraint values */ WhereTerm *pRangeStart = 0; /* Inequality constraint at range start */ WhereTerm *pRangeEnd = 0; /* Inequality constraint at range end */ int startEq; /* True if range start uses ==, >= or <= */ int endEq; /* True if range end uses ==, >= or <= */ int start_constraints; /* Start of range is constrained */ int nConstraint; /* Number of constraint terms */ Index *pIdx; /* The index we will be using */ int iIdxCur; /* The VDBE cursor for the index */ int nExtraReg = 0; /* Number of extra registers needed */ int op; /* Instruction opcode */ char *zStartAff; /* Affinity for start of range constraint */ char *zEndAff = 0; /* Affinity for end of range constraint */ u8 bSeekPastNull = 0; /* True to seek past initial nulls */ u8 bStopAtNull = 0; /* Add condition to terminate at NULLs */ pIdx = pLoop->u.btree.pIndex; iIdxCur = pLevel->iIdxCur; assert( nEq>=pLoop->nSkip ); /* If this loop satisfies a sort order (pOrderBy) request that ** was passed to this function to implement a "SELECT min(x) ..." ** query, then the caller will only allow the loop to run for ** a single iteration. This means that the first row returned ** should not have a NULL value stored in 'x'. If column 'x' is ** the first one after the nEq equality constraints in the index, ** this requires some special handling. */ assert( pWInfo->pOrderBy==0 || pWInfo->pOrderBy->nExpr==1 || (pWInfo->wctrlFlags&WHERE_ORDERBY_MIN)==0 ); if( (pWInfo->wctrlFlags&WHERE_ORDERBY_MIN)!=0 && pWInfo->nOBSat>0 && (pIdx->nKeyCol>nEq) ){ assert( pLoop->nSkip==0 ); bSeekPastNull = 1; nExtraReg = 1; } /* Find any inequality constraint terms for the start and end ** of the range. */ j = nEq; if( pLoop->wsFlags & WHERE_BTM_LIMIT ){ pRangeStart = pLoop->aLTerm[j++]; nExtraReg = MAX(nExtraReg, pLoop->u.btree.nBtm); /* Like optimization range constraints always occur in pairs */ assert( (pRangeStart->wtFlags & TERM_LIKEOPT)==0 || (pLoop->wsFlags & WHERE_TOP_LIMIT)!=0 ); } if( pLoop->wsFlags & WHERE_TOP_LIMIT ){ pRangeEnd = pLoop->aLTerm[j++]; nExtraReg = MAX(nExtraReg, pLoop->u.btree.nTop); #ifndef SQLITE_LIKE_DOESNT_MATCH_BLOBS if( (pRangeEnd->wtFlags & TERM_LIKEOPT)!=0 ){ assert( pRangeStart!=0 ); /* LIKE opt constraints */ assert( pRangeStart->wtFlags & TERM_LIKEOPT ); /* occur in pairs */ pLevel->iLikeRepCntr = (u32)++pParse->nMem; sqlite3VdbeAddOp2(v, OP_Integer, 1, (int)pLevel->iLikeRepCntr); VdbeComment((v, "LIKE loop counter")); pLevel->addrLikeRep = sqlite3VdbeCurrentAddr(v); /* iLikeRepCntr actually stores 2x the counter register number. The ** bottom bit indicates whether the search order is ASC or DESC. */ testcase( bRev ); testcase( pIdx->aSortOrder[nEq]==SQLITE_SO_DESC ); assert( (bRev & ~1)==0 ); pLevel->iLikeRepCntr <<=1; pLevel->iLikeRepCntr |= bRev ^ (pIdx->aSortOrder[nEq]==SQLITE_SO_DESC); } #endif if( pRangeStart==0 ){ j = pIdx->aiColumn[nEq]; if( (j>=0 && pIdx->pTable->aCol[j].notNull==0) || j==XN_EXPR ){ bSeekPastNull = 1; } } } assert( pRangeEnd==0 || (pRangeEnd->wtFlags & TERM_VNULL)==0 ); /* If we are doing a reverse order scan on an ascending index, or ** a forward order scan on a descending index, interchange the ** start and end terms (pRangeStart and pRangeEnd). */ if( (nEqnKeyCol && bRev==(pIdx->aSortOrder[nEq]==SQLITE_SO_ASC)) || (bRev && pIdx->nKeyCol==nEq) ){ SWAP(WhereTerm *, pRangeEnd, pRangeStart); SWAP(u8, bSeekPastNull, bStopAtNull); SWAP(u8, nBtm, nTop); } /* Generate code to evaluate all constraint terms using == or IN ** and store the values of those terms in an array of registers ** starting at regBase. */ codeCursorHint(pTabItem, pWInfo, pLevel, pRangeEnd); regBase = codeAllEqualityTerms(pParse,pLevel,bRev,nExtraReg,&zStartAff); assert( zStartAff==0 || sqlite3Strlen30(zStartAff)>=nEq ); if( zStartAff && nTop ){ zEndAff = sqlite3DbStrDup(db, &zStartAff[nEq]); } addrNxt = pLevel->addrNxt; testcase( pRangeStart && (pRangeStart->eOperator & WO_LE)!=0 ); testcase( pRangeStart && (pRangeStart->eOperator & WO_GE)!=0 ); testcase( pRangeEnd && (pRangeEnd->eOperator & WO_LE)!=0 ); testcase( pRangeEnd && (pRangeEnd->eOperator & WO_GE)!=0 ); startEq = !pRangeStart || pRangeStart->eOperator & (WO_LE|WO_GE); endEq = !pRangeEnd || pRangeEnd->eOperator & (WO_LE|WO_GE); start_constraints = pRangeStart || nEq>0; /* Seek the index cursor to the start of the range. */ nConstraint = nEq; if( pRangeStart ){ Expr *pRight = pRangeStart->pExpr->pRight; codeExprOrVector(pParse, pRight, regBase+nEq, nBtm); whereLikeOptimizationStringFixup(v, pLevel, pRangeStart); if( (pRangeStart->wtFlags & TERM_VNULL)==0 && sqlite3ExprCanBeNull(pRight) ){ sqlite3VdbeAddOp2(v, OP_IsNull, regBase+nEq, addrNxt); VdbeCoverage(v); } if( zStartAff ){ updateRangeAffinityStr(pRight, nBtm, &zStartAff[nEq]); } nConstraint += nBtm; testcase( pRangeStart->wtFlags & TERM_VIRTUAL ); if( sqlite3ExprIsVector(pRight)==0 ){ disableTerm(pLevel, pRangeStart); }else{ startEq = 1; } bSeekPastNull = 0; }else if( bSeekPastNull ){ sqlite3VdbeAddOp2(v, OP_Null, 0, regBase+nEq); nConstraint++; startEq = 0; start_constraints = 1; } codeApplyAffinity(pParse, regBase, nConstraint - bSeekPastNull, zStartAff); if( pLoop->nSkip>0 && nConstraint==pLoop->nSkip ){ /* The skip-scan logic inside the call to codeAllEqualityConstraints() ** above has already left the cursor sitting on the correct row, ** so no further seeking is needed */ }else{ op = aStartOp[(start_constraints<<2) + (startEq<<1) + bRev]; assert( op!=0 ); sqlite3VdbeAddOp4Int(v, op, iIdxCur, addrNxt, regBase, nConstraint); VdbeCoverage(v); VdbeCoverageIf(v, op==OP_Rewind); testcase( op==OP_Rewind ); VdbeCoverageIf(v, op==OP_Last); testcase( op==OP_Last ); VdbeCoverageIf(v, op==OP_SeekGT); testcase( op==OP_SeekGT ); VdbeCoverageIf(v, op==OP_SeekGE); testcase( op==OP_SeekGE ); VdbeCoverageIf(v, op==OP_SeekLE); testcase( op==OP_SeekLE ); VdbeCoverageIf(v, op==OP_SeekLT); testcase( op==OP_SeekLT ); } /* Load the value for the inequality constraint at the end of the ** range (if any). */ nConstraint = nEq; if( pRangeEnd ){ Expr *pRight = pRangeEnd->pExpr->pRight; sqlite3ExprCacheRemove(pParse, regBase+nEq, 1); codeExprOrVector(pParse, pRight, regBase+nEq, nTop); whereLikeOptimizationStringFixup(v, pLevel, pRangeEnd); if( (pRangeEnd->wtFlags & TERM_VNULL)==0 && sqlite3ExprCanBeNull(pRight) ){ sqlite3VdbeAddOp2(v, OP_IsNull, regBase+nEq, addrNxt); VdbeCoverage(v); } if( zEndAff ){ updateRangeAffinityStr(pRight, nTop, zEndAff); codeApplyAffinity(pParse, regBase+nEq, nTop, zEndAff); }else{ assert( pParse->db->mallocFailed ); } nConstraint += nTop; testcase( pRangeEnd->wtFlags & TERM_VIRTUAL ); if( sqlite3ExprIsVector(pRight)==0 ){ disableTerm(pLevel, pRangeEnd); }else{ endEq = 1; } }else if( bStopAtNull ){ sqlite3VdbeAddOp2(v, OP_Null, 0, regBase+nEq); endEq = 0; nConstraint++; } sqlite3DbFree(db, zStartAff); sqlite3DbFree(db, zEndAff); /* Top of the loop body */ pLevel->p2 = sqlite3VdbeCurrentAddr(v); /* Check if the index cursor is past the end of the range. */ if( nConstraint ){ op = aEndOp[bRev*2 + endEq]; sqlite3VdbeAddOp4Int(v, op, iIdxCur, addrNxt, regBase, nConstraint); testcase( op==OP_IdxGT ); VdbeCoverageIf(v, op==OP_IdxGT ); testcase( op==OP_IdxGE ); VdbeCoverageIf(v, op==OP_IdxGE ); testcase( op==OP_IdxLT ); VdbeCoverageIf(v, op==OP_IdxLT ); testcase( op==OP_IdxLE ); VdbeCoverageIf(v, op==OP_IdxLE ); } /* Seek the table cursor, if required */ if( omitTable ){ /* pIdx is a covering index. No need to access the main table. */ }else if( HasRowid(pIdx->pTable) ){ if( (pWInfo->wctrlFlags & WHERE_SEEK_TABLE)!=0 ){ iRowidReg = ++pParse->nMem; sqlite3VdbeAddOp2(v, OP_IdxRowid, iIdxCur, iRowidReg); sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg); sqlite3VdbeAddOp3(v, OP_NotExists, iCur, 0, iRowidReg); VdbeCoverage(v); }else{ codeDeferredSeek(pWInfo, pIdx, iCur, iIdxCur); } }else if( iCur!=iIdxCur ){ Index *pPk = sqlite3PrimaryKeyIndex(pIdx->pTable); iRowidReg = sqlite3GetTempRange(pParse, pPk->nKeyCol); for(j=0; jnKeyCol; j++){ k = sqlite3ColumnOfIndex(pIdx, pPk->aiColumn[j]); sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, k, iRowidReg+j); } sqlite3VdbeAddOp4Int(v, OP_NotFound, iCur, addrCont, iRowidReg, pPk->nKeyCol); VdbeCoverage(v); } /* Record the instruction used to terminate the loop. */ if( pLoop->wsFlags & WHERE_ONEROW ){ pLevel->op = OP_Noop; }else if( bRev ){ pLevel->op = OP_Prev; }else{ pLevel->op = OP_Next; } pLevel->p1 = iIdxCur; pLevel->p3 = (pLoop->wsFlags&WHERE_UNQ_WANTED)!=0 ? 1:0; if( (pLoop->wsFlags & WHERE_CONSTRAINT)==0 ){ pLevel->p5 = SQLITE_STMTSTATUS_FULLSCAN_STEP; }else{ assert( pLevel->p5==0 ); } }else #ifndef SQLITE_OMIT_OR_OPTIMIZATION if( pLoop->wsFlags & WHERE_MULTI_OR ){ /* Case 5: Two or more separately indexed terms connected by OR ** ** Example: ** ** CREATE TABLE t1(a,b,c,d); ** CREATE INDEX i1 ON t1(a); ** CREATE INDEX i2 ON t1(b); ** CREATE INDEX i3 ON t1(c); ** ** SELECT * FROM t1 WHERE a=5 OR b=7 OR (c=11 AND d=13) ** ** In the example, there are three indexed terms connected by OR. ** The top of the loop looks like this: ** ** Null 1 # Zero the rowset in reg 1 ** ** Then, for each indexed term, the following. The arguments to ** RowSetTest are such that the rowid of the current row is inserted ** into the RowSet. If it is already present, control skips the ** Gosub opcode and jumps straight to the code generated by WhereEnd(). ** ** sqlite3WhereBegin() ** RowSetTest # Insert rowid into rowset ** Gosub 2 A ** sqlite3WhereEnd() ** ** Following the above, code to terminate the loop. Label A, the target ** of the Gosub above, jumps to the instruction right after the Goto. ** ** Null 1 # Zero the rowset in reg 1 ** Goto B # The loop is finished. ** ** A: # Return data, whatever. ** ** Return 2 # Jump back to the Gosub ** ** B: ** ** Added 2014-05-26: If the table is a WITHOUT ROWID table, then ** use an ephemeral index instead of a RowSet to record the primary ** keys of the rows we have already seen. ** */ WhereClause *pOrWc; /* The OR-clause broken out into subterms */ SrcList *pOrTab; /* Shortened table list or OR-clause generation */ Index *pCov = 0; /* Potential covering index (or NULL) */ int iCovCur = pParse->nTab++; /* Cursor used for index scans (if any) */ int regReturn = ++pParse->nMem; /* Register used with OP_Gosub */ int regRowset = 0; /* Register for RowSet object */ int regRowid = 0; /* Register holding rowid */ int iLoopBody = sqlite3VdbeMakeLabel(v); /* Start of loop body */ int iRetInit; /* Address of regReturn init */ int untestedTerms = 0; /* Some terms not completely tested */ int ii; /* Loop counter */ u16 wctrlFlags; /* Flags for sub-WHERE clause */ Expr *pAndExpr = 0; /* An ".. AND (...)" expression */ Table *pTab = pTabItem->pTab; pTerm = pLoop->aLTerm[0]; assert( pTerm!=0 ); assert( pTerm->eOperator & WO_OR ); assert( (pTerm->wtFlags & TERM_ORINFO)!=0 ); pOrWc = &pTerm->u.pOrInfo->wc; pLevel->op = OP_Return; pLevel->p1 = regReturn; /* Set up a new SrcList in pOrTab containing the table being scanned ** by this loop in the a[0] slot and all notReady tables in a[1..] slots. ** This becomes the SrcList in the recursive call to sqlite3WhereBegin(). */ if( pWInfo->nLevel>1 ){ int nNotReady; /* The number of notReady tables */ struct SrcList_item *origSrc; /* Original list of tables */ nNotReady = pWInfo->nLevel - iLevel - 1; pOrTab = sqlite3StackAllocRaw(db, sizeof(*pOrTab)+ nNotReady*sizeof(pOrTab->a[0])); if( pOrTab==0 ) return notReady; pOrTab->nAlloc = (u8)(nNotReady + 1); pOrTab->nSrc = pOrTab->nAlloc; memcpy(pOrTab->a, pTabItem, sizeof(*pTabItem)); origSrc = pWInfo->pTabList->a; for(k=1; k<=nNotReady; k++){ memcpy(&pOrTab->a[k], &origSrc[pLevel[k].iFrom], sizeof(pOrTab->a[k])); } }else{ pOrTab = pWInfo->pTabList; } /* Initialize the rowset register to contain NULL. An SQL NULL is ** equivalent to an empty rowset. Or, create an ephemeral index ** capable of holding primary keys in the case of a WITHOUT ROWID. ** ** Also initialize regReturn to contain the address of the instruction ** immediately following the OP_Return at the bottom of the loop. This ** is required in a few obscure LEFT JOIN cases where control jumps ** over the top of the loop into the body of it. In this case the ** correct response for the end-of-loop code (the OP_Return) is to ** fall through to the next instruction, just as an OP_Next does if ** called on an uninitialized cursor. */ if( (pWInfo->wctrlFlags & WHERE_DUPLICATES_OK)==0 ){ if( HasRowid(pTab) ){ regRowset = ++pParse->nMem; sqlite3VdbeAddOp2(v, OP_Null, 0, regRowset); }else{ Index *pPk = sqlite3PrimaryKeyIndex(pTab); regRowset = pParse->nTab++; sqlite3VdbeAddOp2(v, OP_OpenEphemeral, regRowset, pPk->nKeyCol); sqlite3VdbeSetP4KeyInfo(pParse, pPk); } regRowid = ++pParse->nMem; } iRetInit = sqlite3VdbeAddOp2(v, OP_Integer, 0, regReturn); /* If the original WHERE clause is z of the form: (x1 OR x2 OR ...) AND y ** Then for every term xN, evaluate as the subexpression: xN AND z ** That way, terms in y that are factored into the disjunction will ** be picked up by the recursive calls to sqlite3WhereBegin() below. ** ** Actually, each subexpression is converted to "xN AND w" where w is ** the "interesting" terms of z - terms that did not originate in the ** ON or USING clause of a LEFT JOIN, and terms that are usable as ** indices. ** ** This optimization also only applies if the (x1 OR x2 OR ...) term ** is not contained in the ON clause of a LEFT JOIN. ** See ticket http://www.sqlite.org/src/info/f2369304e4 */ if( pWC->nTerm>1 ){ int iTerm; for(iTerm=0; iTermnTerm; iTerm++){ Expr *pExpr = pWC->a[iTerm].pExpr; if( &pWC->a[iTerm] == pTerm ) continue; if( ExprHasProperty(pExpr, EP_FromJoin) ) continue; testcase( pWC->a[iTerm].wtFlags & TERM_VIRTUAL ); testcase( pWC->a[iTerm].wtFlags & TERM_CODED ); if( (pWC->a[iTerm].wtFlags & (TERM_VIRTUAL|TERM_CODED))!=0 ) continue; if( (pWC->a[iTerm].eOperator & WO_ALL)==0 ) continue; testcase( pWC->a[iTerm].wtFlags & TERM_ORINFO ); pExpr = sqlite3ExprDup(db, pExpr, 0); pAndExpr = sqlite3ExprAnd(db, pAndExpr, pExpr); } if( pAndExpr ){ pAndExpr = sqlite3PExpr(pParse, TK_AND|TKFLG_DONTFOLD, 0, pAndExpr, 0); } } /* Run a separate WHERE clause for each term of the OR clause. After ** eliminating duplicates from other WHERE clauses, the action for each ** sub-WHERE clause is to to invoke the main loop body as a subroutine. */ wctrlFlags = WHERE_OR_SUBCLAUSE | (pWInfo->wctrlFlags & WHERE_SEEK_TABLE); for(ii=0; iinTerm; ii++){ WhereTerm *pOrTerm = &pOrWc->a[ii]; if( pOrTerm->leftCursor==iCur || (pOrTerm->eOperator & WO_AND)!=0 ){ WhereInfo *pSubWInfo; /* Info for single OR-term scan */ Expr *pOrExpr = pOrTerm->pExpr; /* Current OR clause term */ int jmp1 = 0; /* Address of jump operation */ if( pAndExpr && !ExprHasProperty(pOrExpr, EP_FromJoin) ){ pAndExpr->pLeft = pOrExpr; pOrExpr = pAndExpr; } /* Loop through table entries that match term pOrTerm. */ WHERETRACE(0xffff, ("Subplan for OR-clause:\n")); pSubWInfo = sqlite3WhereBegin(pParse, pOrTab, pOrExpr, 0, 0, wctrlFlags, iCovCur); assert( pSubWInfo || pParse->nErr || db->mallocFailed ); if( pSubWInfo ){ WhereLoop *pSubLoop; int addrExplain = sqlite3WhereExplainOneScan( pParse, pOrTab, &pSubWInfo->a[0], iLevel, pLevel->iFrom, 0 ); sqlite3WhereAddScanStatus(v, pOrTab, &pSubWInfo->a[0], addrExplain); /* This is the sub-WHERE clause body. First skip over ** duplicate rows from prior sub-WHERE clauses, and record the ** rowid (or PRIMARY KEY) for the current row so that the same ** row will be skipped in subsequent sub-WHERE clauses. */ if( (pWInfo->wctrlFlags & WHERE_DUPLICATES_OK)==0 ){ int r; int iSet = ((ii==pOrWc->nTerm-1)?-1:ii); if( HasRowid(pTab) ){ r = sqlite3ExprCodeGetColumn(pParse, pTab, -1, iCur, regRowid, 0); jmp1 = sqlite3VdbeAddOp4Int(v, OP_RowSetTest, regRowset, 0, r,iSet); VdbeCoverage(v); }else{ Index *pPk = sqlite3PrimaryKeyIndex(pTab); int nPk = pPk->nKeyCol; int iPk; /* Read the PK into an array of temp registers. */ r = sqlite3GetTempRange(pParse, nPk); for(iPk=0; iPkaiColumn[iPk]; sqlite3ExprCodeGetColumnToReg(pParse, pTab, iCol, iCur, r+iPk); } /* Check if the temp table already contains this key. If so, ** the row has already been included in the result set and ** can be ignored (by jumping past the Gosub below). Otherwise, ** insert the key into the temp table and proceed with processing ** the row. ** ** Use some of the same optimizations as OP_RowSetTest: If iSet ** is zero, assume that the key cannot already be present in ** the temp table. And if iSet is -1, assume that there is no ** need to insert the key into the temp table, as it will never ** be tested for. */ if( iSet ){ jmp1 = sqlite3VdbeAddOp4Int(v, OP_Found, regRowset, 0, r, nPk); VdbeCoverage(v); } if( iSet>=0 ){ sqlite3VdbeAddOp3(v, OP_MakeRecord, r, nPk, regRowid); sqlite3VdbeAddOp3(v, OP_IdxInsert, regRowset, regRowid, 0); if( iSet ) sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT); } /* Release the array of temp registers */ sqlite3ReleaseTempRange(pParse, r, nPk); } } /* Invoke the main loop body as a subroutine */ sqlite3VdbeAddOp2(v, OP_Gosub, regReturn, iLoopBody); /* Jump here (skipping the main loop body subroutine) if the ** current sub-WHERE row is a duplicate from prior sub-WHEREs. */ if( jmp1 ) sqlite3VdbeJumpHere(v, jmp1); /* The pSubWInfo->untestedTerms flag means that this OR term ** contained one or more AND term from a notReady table. The ** terms from the notReady table could not be tested and will ** need to be tested later. */ if( pSubWInfo->untestedTerms ) untestedTerms = 1; /* If all of the OR-connected terms are optimized using the same ** index, and the index is opened using the same cursor number ** by each call to sqlite3WhereBegin() made by this loop, it may ** be possible to use that index as a covering index. ** ** If the call to sqlite3WhereBegin() above resulted in a scan that ** uses an index, and this is either the first OR-connected term ** processed or the index is the same as that used by all previous ** terms, set pCov to the candidate covering index. Otherwise, set ** pCov to NULL to indicate that no candidate covering index will ** be available. */ pSubLoop = pSubWInfo->a[0].pWLoop; assert( (pSubLoop->wsFlags & WHERE_AUTO_INDEX)==0 ); if( (pSubLoop->wsFlags & WHERE_INDEXED)!=0 && (ii==0 || pSubLoop->u.btree.pIndex==pCov) && (HasRowid(pTab) || !IsPrimaryKeyIndex(pSubLoop->u.btree.pIndex)) ){ assert( pSubWInfo->a[0].iIdxCur==iCovCur ); pCov = pSubLoop->u.btree.pIndex; }else{ pCov = 0; } /* Finish the loop through table entries that match term pOrTerm. */ sqlite3WhereEnd(pSubWInfo); } } } pLevel->u.pCovidx = pCov; if( pCov ) pLevel->iIdxCur = iCovCur; if( pAndExpr ){ pAndExpr->pLeft = 0; sqlite3ExprDelete(db, pAndExpr); } sqlite3VdbeChangeP1(v, iRetInit, sqlite3VdbeCurrentAddr(v)); sqlite3VdbeGoto(v, pLevel->addrBrk); sqlite3VdbeResolveLabel(v, iLoopBody); if( pWInfo->nLevel>1 ) sqlite3StackFree(db, pOrTab); if( !untestedTerms ) disableTerm(pLevel, pTerm); }else #endif /* SQLITE_OMIT_OR_OPTIMIZATION */ { /* Case 6: There is no usable index. We must do a complete ** scan of the entire table. */ static const u8 aStep[] = { OP_Next, OP_Prev }; static const u8 aStart[] = { OP_Rewind, OP_Last }; assert( bRev==0 || bRev==1 ); if( pTabItem->fg.isRecursive ){ /* Tables marked isRecursive have only a single row that is stored in ** a pseudo-cursor. No need to Rewind or Next such cursors. */ pLevel->op = OP_Noop; }else{ codeCursorHint(pTabItem, pWInfo, pLevel, 0); pLevel->op = aStep[bRev]; pLevel->p1 = iCur; pLevel->p2 = 1 + sqlite3VdbeAddOp2(v, aStart[bRev], iCur, addrBrk); VdbeCoverageIf(v, bRev==0); VdbeCoverageIf(v, bRev!=0); pLevel->p5 = SQLITE_STMTSTATUS_FULLSCAN_STEP; } } #ifdef SQLITE_ENABLE_STMT_SCANSTATUS pLevel->addrVisit = sqlite3VdbeCurrentAddr(v); #endif /* Insert code to test every subexpression that can be completely ** computed using the current set of tables. */ for(pTerm=pWC->a, j=pWC->nTerm; j>0; j--, pTerm++){ Expr *pE; int skipLikeAddr = 0; testcase( pTerm->wtFlags & TERM_VIRTUAL ); testcase( pTerm->wtFlags & TERM_CODED ); if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue; if( (pTerm->prereqAll & pLevel->notReady)!=0 ){ testcase( pWInfo->untestedTerms==0 && (pWInfo->wctrlFlags & WHERE_OR_SUBCLAUSE)!=0 ); pWInfo->untestedTerms = 1; continue; } pE = pTerm->pExpr; assert( pE!=0 ); if( pLevel->iLeftJoin && !ExprHasProperty(pE, EP_FromJoin) ){ continue; } if( pTerm->wtFlags & TERM_LIKECOND ){ /* If the TERM_LIKECOND flag is set, that means that the range search ** is sufficient to guarantee that the LIKE operator is true, so we ** can skip the call to the like(A,B) function. But this only works ** for strings. So do not skip the call to the function on the pass ** that compares BLOBs. */ #ifdef SQLITE_LIKE_DOESNT_MATCH_BLOBS continue; #else u32 x = pLevel->iLikeRepCntr; assert( x>0 ); skipLikeAddr = sqlite3VdbeAddOp1(v, (x&1)? OP_IfNot : OP_If, (int)(x>>1)); VdbeCoverage(v); #endif } sqlite3ExprIfFalse(pParse, pE, addrCont, SQLITE_JUMPIFNULL); if( skipLikeAddr ) sqlite3VdbeJumpHere(v, skipLikeAddr); pTerm->wtFlags |= TERM_CODED; } /* Insert code to test for implied constraints based on transitivity ** of the "==" operator. ** ** Example: If the WHERE clause contains "t1.a=t2.b" and "t2.b=123" ** and we are coding the t1 loop and the t2 loop has not yet coded, ** then we cannot use the "t1.a=t2.b" constraint, but we can code ** the implied "t1.a=123" constraint. */ for(pTerm=pWC->a, j=pWC->nTerm; j>0; j--, pTerm++){ Expr *pE, sEAlt; WhereTerm *pAlt; if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue; if( (pTerm->eOperator & (WO_EQ|WO_IS))==0 ) continue; if( (pTerm->eOperator & WO_EQUIV)==0 ) continue; if( pTerm->leftCursor!=iCur ) continue; if( pLevel->iLeftJoin ) continue; pE = pTerm->pExpr; assert( !ExprHasProperty(pE, EP_FromJoin) ); assert( (pTerm->prereqRight & pLevel->notReady)!=0 ); pAlt = sqlite3WhereFindTerm(pWC, iCur, pTerm->u.leftColumn, notReady, WO_EQ|WO_IN|WO_IS, 0); if( pAlt==0 ) continue; if( pAlt->wtFlags & (TERM_CODED) ) continue; testcase( pAlt->eOperator & WO_EQ ); testcase( pAlt->eOperator & WO_IS ); testcase( pAlt->eOperator & WO_IN ); VdbeModuleComment((v, "begin transitive constraint")); sEAlt = *pAlt->pExpr; sEAlt.pLeft = pE->pLeft; sqlite3ExprIfFalse(pParse, &sEAlt, addrCont, SQLITE_JUMPIFNULL); } /* For a LEFT OUTER JOIN, generate code that will record the fact that ** at least one row of the right table has matched the left table. */ if( pLevel->iLeftJoin ){ pLevel->addrFirst = sqlite3VdbeCurrentAddr(v); sqlite3VdbeAddOp2(v, OP_Integer, 1, pLevel->iLeftJoin); VdbeComment((v, "record LEFT JOIN hit")); sqlite3ExprCacheClear(pParse); for(pTerm=pWC->a, j=0; jnTerm; j++, pTerm++){ testcase( pTerm->wtFlags & TERM_VIRTUAL ); testcase( pTerm->wtFlags & TERM_CODED ); if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue; if( (pTerm->prereqAll & pLevel->notReady)!=0 ){ assert( pWInfo->untestedTerms ); continue; } assert( pTerm->pExpr ); sqlite3ExprIfFalse(pParse, pTerm->pExpr, addrCont, SQLITE_JUMPIFNULL); pTerm->wtFlags |= TERM_CODED; } } return pLevel->notReady; } /************** End of wherecode.c *******************************************/ /************** Begin file whereexpr.c ***************************************/ /* ** 2015-06-08 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ************************************************************************* ** This module contains C code that generates VDBE code used to process ** the WHERE clause of SQL statements. ** ** This file was originally part of where.c but was split out to improve ** readability and editabiliity. This file contains utility routines for ** analyzing Expr objects in the WHERE clause. */ /* #include "sqliteInt.h" */ /* #include "whereInt.h" */ /* Forward declarations */ static void exprAnalyze(SrcList*, WhereClause*, int); /* ** Deallocate all memory associated with a WhereOrInfo object. */ static void whereOrInfoDelete(sqlite3 *db, WhereOrInfo *p){ sqlite3WhereClauseClear(&p->wc); sqlite3DbFree(db, p); } /* ** Deallocate all memory associated with a WhereAndInfo object. */ static void whereAndInfoDelete(sqlite3 *db, WhereAndInfo *p){ sqlite3WhereClauseClear(&p->wc); sqlite3DbFree(db, p); } /* ** Add a single new WhereTerm entry to the WhereClause object pWC. ** The new WhereTerm object is constructed from Expr p and with wtFlags. ** The index in pWC->a[] of the new WhereTerm is returned on success. ** 0 is returned if the new WhereTerm could not be added due to a memory ** allocation error. The memory allocation failure will be recorded in ** the db->mallocFailed flag so that higher-level functions can detect it. ** ** This routine will increase the size of the pWC->a[] array as necessary. ** ** If the wtFlags argument includes TERM_DYNAMIC, then responsibility ** for freeing the expression p is assumed by the WhereClause object pWC. ** This is true even if this routine fails to allocate a new WhereTerm. ** ** WARNING: This routine might reallocate the space used to store ** WhereTerms. All pointers to WhereTerms should be invalidated after ** calling this routine. Such pointers may be reinitialized by referencing ** the pWC->a[] array. */ static int whereClauseInsert(WhereClause *pWC, Expr *p, u16 wtFlags){ WhereTerm *pTerm; int idx; testcase( wtFlags & TERM_VIRTUAL ); if( pWC->nTerm>=pWC->nSlot ){ WhereTerm *pOld = pWC->a; sqlite3 *db = pWC->pWInfo->pParse->db; pWC->a = sqlite3DbMallocRawNN(db, sizeof(pWC->a[0])*pWC->nSlot*2 ); if( pWC->a==0 ){ if( wtFlags & TERM_DYNAMIC ){ sqlite3ExprDelete(db, p); } pWC->a = pOld; return 0; } memcpy(pWC->a, pOld, sizeof(pWC->a[0])*pWC->nTerm); if( pOld!=pWC->aStatic ){ sqlite3DbFree(db, pOld); } pWC->nSlot = sqlite3DbMallocSize(db, pWC->a)/sizeof(pWC->a[0]); } pTerm = &pWC->a[idx = pWC->nTerm++]; if( p && ExprHasProperty(p, EP_Unlikely) ){ pTerm->truthProb = sqlite3LogEst(p->iTable) - 270; }else{ pTerm->truthProb = 1; } pTerm->pExpr = sqlite3ExprSkipCollate(p); pTerm->wtFlags = wtFlags; pTerm->pWC = pWC; pTerm->iParent = -1; memset(&pTerm->eOperator, 0, sizeof(WhereTerm) - offsetof(WhereTerm,eOperator)); return idx; } /* ** Return TRUE if the given operator is one of the operators that is ** allowed for an indexable WHERE clause term. The allowed operators are ** "=", "<", ">", "<=", ">=", "IN", "IS", and "IS NULL" */ static int allowedOp(int op){ assert( TK_GT>TK_EQ && TK_GTTK_EQ && TK_LTTK_EQ && TK_LE=TK_EQ && op<=TK_GE) || op==TK_ISNULL || op==TK_IS; } /* ** Commute a comparison operator. Expressions of the form "X op Y" ** are converted into "Y op X". ** ** If left/right precedence rules come into play when determining the ** collating sequence, then COLLATE operators are adjusted to ensure ** that the collating sequence does not change. For example: ** "Y collate NOCASE op X" becomes "X op Y" because any collation sequence on ** the left hand side of a comparison overrides any collation sequence ** attached to the right. For the same reason the EP_Collate flag ** is not commuted. */ static void exprCommute(Parse *pParse, Expr *pExpr){ u16 expRight = (pExpr->pRight->flags & EP_Collate); u16 expLeft = (pExpr->pLeft->flags & EP_Collate); assert( allowedOp(pExpr->op) && pExpr->op!=TK_IN ); if( expRight==expLeft ){ /* Either X and Y both have COLLATE operator or neither do */ if( expRight ){ /* Both X and Y have COLLATE operators. Make sure X is always ** used by clearing the EP_Collate flag from Y. */ pExpr->pRight->flags &= ~EP_Collate; }else if( sqlite3ExprCollSeq(pParse, pExpr->pLeft)!=0 ){ /* Neither X nor Y have COLLATE operators, but X has a non-default ** collating sequence. So add the EP_Collate marker on X to cause ** it to be searched first. */ pExpr->pLeft->flags |= EP_Collate; } } SWAP(Expr*,pExpr->pRight,pExpr->pLeft); if( pExpr->op>=TK_GT ){ assert( TK_LT==TK_GT+2 ); assert( TK_GE==TK_LE+2 ); assert( TK_GT>TK_EQ ); assert( TK_GTop>=TK_GT && pExpr->op<=TK_GE ); pExpr->op = ((pExpr->op-TK_GT)^2)+TK_GT; } } /* ** Translate from TK_xx operator to WO_xx bitmask. */ static u16 operatorMask(int op){ u16 c; assert( allowedOp(op) ); if( op==TK_IN ){ c = WO_IN; }else if( op==TK_ISNULL ){ c = WO_ISNULL; }else if( op==TK_IS ){ c = WO_IS; }else{ assert( (WO_EQ<<(op-TK_EQ)) < 0x7fff ); c = (u16)(WO_EQ<<(op-TK_EQ)); } assert( op!=TK_ISNULL || c==WO_ISNULL ); assert( op!=TK_IN || c==WO_IN ); assert( op!=TK_EQ || c==WO_EQ ); assert( op!=TK_LT || c==WO_LT ); assert( op!=TK_LE || c==WO_LE ); assert( op!=TK_GT || c==WO_GT ); assert( op!=TK_GE || c==WO_GE ); assert( op!=TK_IS || c==WO_IS ); return c; } #ifndef SQLITE_OMIT_LIKE_OPTIMIZATION /* ** Check to see if the given expression is a LIKE or GLOB operator that ** can be optimized using inequality constraints. Return TRUE if it is ** so and false if not. ** ** In order for the operator to be optimizible, the RHS must be a string ** literal that does not begin with a wildcard. The LHS must be a column ** that may only be NULL, a string, or a BLOB, never a number. (This means ** that virtual tables cannot participate in the LIKE optimization.) The ** collating sequence for the column on the LHS must be appropriate for ** the operator. */ static int isLikeOrGlob( Parse *pParse, /* Parsing and code generating context */ Expr *pExpr, /* Test this expression */ Expr **ppPrefix, /* Pointer to TK_STRING expression with pattern prefix */ int *pisComplete, /* True if the only wildcard is % in the last character */ int *pnoCase /* True if uppercase is equivalent to lowercase */ ){ const char *z = 0; /* String on RHS of LIKE operator */ Expr *pRight, *pLeft; /* Right and left size of LIKE operator */ ExprList *pList; /* List of operands to the LIKE operator */ int c; /* One character in z[] */ int cnt; /* Number of non-wildcard prefix characters */ char wc[3]; /* Wildcard characters */ sqlite3 *db = pParse->db; /* Database connection */ sqlite3_value *pVal = 0; int op; /* Opcode of pRight */ int rc; /* Result code to return */ if( !sqlite3IsLikeFunction(db, pExpr, pnoCase, wc) ){ return 0; } #ifdef SQLITE_EBCDIC if( *pnoCase ) return 0; #endif pList = pExpr->x.pList; pLeft = pList->a[1].pExpr; if( pLeft->op!=TK_COLUMN || sqlite3ExprAffinity(pLeft)!=SQLITE_AFF_TEXT || IsVirtual(pLeft->pTab) /* Value might be numeric */ ){ /* IMP: R-02065-49465 The left-hand side of the LIKE or GLOB operator must ** be the name of an indexed column with TEXT affinity. */ return 0; } assert( pLeft->iColumn!=(-1) ); /* Because IPK never has AFF_TEXT */ pRight = sqlite3ExprSkipCollate(pList->a[0].pExpr); op = pRight->op; if( op==TK_VARIABLE ){ Vdbe *pReprepare = pParse->pReprepare; int iCol = pRight->iColumn; pVal = sqlite3VdbeGetBoundValue(pReprepare, iCol, SQLITE_AFF_BLOB); if( pVal && sqlite3_value_type(pVal)==SQLITE_TEXT ){ z = (char *)sqlite3_value_text(pVal); } sqlite3VdbeSetVarmask(pParse->pVdbe, iCol); assert( pRight->op==TK_VARIABLE || pRight->op==TK_REGISTER ); }else if( op==TK_STRING ){ z = pRight->u.zToken; } if( z ){ cnt = 0; while( (c=z[cnt])!=0 && c!=wc[0] && c!=wc[1] && c!=wc[2] ){ cnt++; } if( cnt!=0 && 255!=(u8)z[cnt-1] ){ Expr *pPrefix; *pisComplete = c==wc[0] && z[cnt+1]==0; pPrefix = sqlite3Expr(db, TK_STRING, z); if( pPrefix ) pPrefix->u.zToken[cnt] = 0; *ppPrefix = pPrefix; if( op==TK_VARIABLE ){ Vdbe *v = pParse->pVdbe; sqlite3VdbeSetVarmask(v, pRight->iColumn); if( *pisComplete && pRight->u.zToken[1] ){ /* If the rhs of the LIKE expression is a variable, and the current ** value of the variable means there is no need to invoke the LIKE ** function, then no OP_Variable will be added to the program. ** This causes problems for the sqlite3_bind_parameter_name() ** API. To work around them, add a dummy OP_Variable here. */ int r1 = sqlite3GetTempReg(pParse); sqlite3ExprCodeTarget(pParse, pRight, r1); sqlite3VdbeChangeP3(v, sqlite3VdbeCurrentAddr(v)-1, 0); sqlite3ReleaseTempReg(pParse, r1); } } }else{ z = 0; } } rc = (z!=0); sqlite3ValueFree(pVal); return rc; } #endif /* SQLITE_OMIT_LIKE_OPTIMIZATION */ #ifndef SQLITE_OMIT_VIRTUALTABLE /* ** Check to see if the given expression is of the form ** ** column OP expr ** ** where OP is one of MATCH, GLOB, LIKE or REGEXP and "column" is a ** column of a virtual table. ** ** If it is then return TRUE. If not, return FALSE. */ static int isMatchOfColumn( Expr *pExpr, /* Test this expression */ unsigned char *peOp2 /* OUT: 0 for MATCH, or else an op2 value */ ){ static const struct Op2 { const char *zOp; unsigned char eOp2; } aOp[] = { { "match", SQLITE_INDEX_CONSTRAINT_MATCH }, { "glob", SQLITE_INDEX_CONSTRAINT_GLOB }, { "like", SQLITE_INDEX_CONSTRAINT_LIKE }, { "regexp", SQLITE_INDEX_CONSTRAINT_REGEXP } }; ExprList *pList; Expr *pCol; /* Column reference */ int i; if( pExpr->op!=TK_FUNCTION ){ return 0; } pList = pExpr->x.pList; if( pList==0 || pList->nExpr!=2 ){ return 0; } pCol = pList->a[1].pExpr; if( pCol->op!=TK_COLUMN || !IsVirtual(pCol->pTab) ){ return 0; } for(i=0; iu.zToken, aOp[i].zOp)==0 ){ *peOp2 = aOp[i].eOp2; return 1; } } return 0; } #endif /* SQLITE_OMIT_VIRTUALTABLE */ /* ** If the pBase expression originated in the ON or USING clause of ** a join, then transfer the appropriate markings over to derived. */ static void transferJoinMarkings(Expr *pDerived, Expr *pBase){ if( pDerived ){ pDerived->flags |= pBase->flags & EP_FromJoin; pDerived->iRightJoinTable = pBase->iRightJoinTable; } } /* ** Mark term iChild as being a child of term iParent */ static void markTermAsChild(WhereClause *pWC, int iChild, int iParent){ pWC->a[iChild].iParent = iParent; pWC->a[iChild].truthProb = pWC->a[iParent].truthProb; pWC->a[iParent].nChild++; } /* ** Return the N-th AND-connected subterm of pTerm. Or if pTerm is not ** a conjunction, then return just pTerm when N==0. If N is exceeds ** the number of available subterms, return NULL. */ static WhereTerm *whereNthSubterm(WhereTerm *pTerm, int N){ if( pTerm->eOperator!=WO_AND ){ return N==0 ? pTerm : 0; } if( Nu.pAndInfo->wc.nTerm ){ return &pTerm->u.pAndInfo->wc.a[N]; } return 0; } /* ** Subterms pOne and pTwo are contained within WHERE clause pWC. The ** two subterms are in disjunction - they are OR-ed together. ** ** If these two terms are both of the form: "A op B" with the same ** A and B values but different operators and if the operators are ** compatible (if one is = and the other is <, for example) then ** add a new virtual AND term to pWC that is the combination of the ** two. ** ** Some examples: ** ** x x<=y ** x=y OR x=y --> x=y ** x<=y OR x x<=y ** ** The following is NOT generated: ** ** xy --> x!=y */ static void whereCombineDisjuncts( SrcList *pSrc, /* the FROM clause */ WhereClause *pWC, /* The complete WHERE clause */ WhereTerm *pOne, /* First disjunct */ WhereTerm *pTwo /* Second disjunct */ ){ u16 eOp = pOne->eOperator | pTwo->eOperator; sqlite3 *db; /* Database connection (for malloc) */ Expr *pNew; /* New virtual expression */ int op; /* Operator for the combined expression */ int idxNew; /* Index in pWC of the next virtual term */ if( (pOne->eOperator & (WO_EQ|WO_LT|WO_LE|WO_GT|WO_GE))==0 ) return; if( (pTwo->eOperator & (WO_EQ|WO_LT|WO_LE|WO_GT|WO_GE))==0 ) return; if( (eOp & (WO_EQ|WO_LT|WO_LE))!=eOp && (eOp & (WO_EQ|WO_GT|WO_GE))!=eOp ) return; assert( pOne->pExpr->pLeft!=0 && pOne->pExpr->pRight!=0 ); assert( pTwo->pExpr->pLeft!=0 && pTwo->pExpr->pRight!=0 ); if( sqlite3ExprCompare(pOne->pExpr->pLeft, pTwo->pExpr->pLeft, -1) ) return; if( sqlite3ExprCompare(pOne->pExpr->pRight, pTwo->pExpr->pRight, -1) )return; /* If we reach this point, it means the two subterms can be combined */ if( (eOp & (eOp-1))!=0 ){ if( eOp & (WO_LT|WO_LE) ){ eOp = WO_LE; }else{ assert( eOp & (WO_GT|WO_GE) ); eOp = WO_GE; } } db = pWC->pWInfo->pParse->db; pNew = sqlite3ExprDup(db, pOne->pExpr, 0); if( pNew==0 ) return; for(op=TK_EQ; eOp!=(WO_EQ<<(op-TK_EQ)); op++){ assert( opop = op; idxNew = whereClauseInsert(pWC, pNew, TERM_VIRTUAL|TERM_DYNAMIC); exprAnalyze(pSrc, pWC, idxNew); } #if !defined(SQLITE_OMIT_OR_OPTIMIZATION) && !defined(SQLITE_OMIT_SUBQUERY) /* ** Analyze a term that consists of two or more OR-connected ** subterms. So in: ** ** ... WHERE (a=5) AND (b=7 OR c=9 OR d=13) AND (d=13) ** ^^^^^^^^^^^^^^^^^^^^ ** ** This routine analyzes terms such as the middle term in the above example. ** A WhereOrTerm object is computed and attached to the term under ** analysis, regardless of the outcome of the analysis. Hence: ** ** WhereTerm.wtFlags |= TERM_ORINFO ** WhereTerm.u.pOrInfo = a dynamically allocated WhereOrTerm object ** ** The term being analyzed must have two or more of OR-connected subterms. ** A single subterm might be a set of AND-connected sub-subterms. ** Examples of terms under analysis: ** ** (A) t1.x=t2.y OR t1.x=t2.z OR t1.y=15 OR t1.z=t3.a+5 ** (B) x=expr1 OR expr2=x OR x=expr3 ** (C) t1.x=t2.y OR (t1.x=t2.z AND t1.y=15) ** (D) x=expr1 OR (y>11 AND y<22 AND z LIKE '*hello*') ** (E) (p.a=1 AND q.b=2 AND r.c=3) OR (p.x=4 AND q.y=5 AND r.z=6) ** (F) x>A OR (x=A AND y>=B) ** ** CASE 1: ** ** If all subterms are of the form T.C=expr for some single column of C and ** a single table T (as shown in example B above) then create a new virtual ** term that is an equivalent IN expression. In other words, if the term ** being analyzed is: ** ** x = expr1 OR expr2 = x OR x = expr3 ** ** then create a new virtual term like this: ** ** x IN (expr1,expr2,expr3) ** ** CASE 2: ** ** If there are exactly two disjuncts and one side has x>A and the other side ** has x=A (for the same x and A) then add a new virtual conjunct term to the ** WHERE clause of the form "x>=A". Example: ** ** x>A OR (x=A AND y>B) adds: x>=A ** ** The added conjunct can sometimes be helpful in query planning. ** ** CASE 3: ** ** If all subterms are indexable by a single table T, then set ** ** WhereTerm.eOperator = WO_OR ** WhereTerm.u.pOrInfo->indexable |= the cursor number for table T ** ** A subterm is "indexable" if it is of the form ** "T.C " where C is any column of table T and ** is one of "=", "<", "<=", ">", ">=", "IS NULL", or "IN". ** A subterm is also indexable if it is an AND of two or more ** subsubterms at least one of which is indexable. Indexable AND ** subterms have their eOperator set to WO_AND and they have ** u.pAndInfo set to a dynamically allocated WhereAndTerm object. ** ** From another point of view, "indexable" means that the subterm could ** potentially be used with an index if an appropriate index exists. ** This analysis does not consider whether or not the index exists; that ** is decided elsewhere. This analysis only looks at whether subterms ** appropriate for indexing exist. ** ** All examples A through E above satisfy case 3. But if a term ** also satisfies case 1 (such as B) we know that the optimizer will ** always prefer case 1, so in that case we pretend that case 3 is not ** satisfied. ** ** It might be the case that multiple tables are indexable. For example, ** (E) above is indexable on tables P, Q, and R. ** ** Terms that satisfy case 3 are candidates for lookup by using ** separate indices to find rowids for each subterm and composing ** the union of all rowids using a RowSet object. This is similar ** to "bitmap indices" in other database engines. ** ** OTHERWISE: ** ** If none of cases 1, 2, or 3 apply, then leave the eOperator set to ** zero. This term is not useful for search. */ static void exprAnalyzeOrTerm( SrcList *pSrc, /* the FROM clause */ WhereClause *pWC, /* the complete WHERE clause */ int idxTerm /* Index of the OR-term to be analyzed */ ){ WhereInfo *pWInfo = pWC->pWInfo; /* WHERE clause processing context */ Parse *pParse = pWInfo->pParse; /* Parser context */ sqlite3 *db = pParse->db; /* Database connection */ WhereTerm *pTerm = &pWC->a[idxTerm]; /* The term to be analyzed */ Expr *pExpr = pTerm->pExpr; /* The expression of the term */ int i; /* Loop counters */ WhereClause *pOrWc; /* Breakup of pTerm into subterms */ WhereTerm *pOrTerm; /* A Sub-term within the pOrWc */ WhereOrInfo *pOrInfo; /* Additional information associated with pTerm */ Bitmask chngToIN; /* Tables that might satisfy case 1 */ Bitmask indexable; /* Tables that are indexable, satisfying case 2 */ /* ** Break the OR clause into its separate subterms. The subterms are ** stored in a WhereClause structure containing within the WhereOrInfo ** object that is attached to the original OR clause term. */ assert( (pTerm->wtFlags & (TERM_DYNAMIC|TERM_ORINFO|TERM_ANDINFO))==0 ); assert( pExpr->op==TK_OR ); pTerm->u.pOrInfo = pOrInfo = sqlite3DbMallocZero(db, sizeof(*pOrInfo)); if( pOrInfo==0 ) return; pTerm->wtFlags |= TERM_ORINFO; pOrWc = &pOrInfo->wc; memset(pOrWc->aStatic, 0, sizeof(pOrWc->aStatic)); sqlite3WhereClauseInit(pOrWc, pWInfo); sqlite3WhereSplit(pOrWc, pExpr, TK_OR); sqlite3WhereExprAnalyze(pSrc, pOrWc); if( db->mallocFailed ) return; assert( pOrWc->nTerm>=2 ); /* ** Compute the set of tables that might satisfy cases 1 or 3. */ indexable = ~(Bitmask)0; chngToIN = ~(Bitmask)0; for(i=pOrWc->nTerm-1, pOrTerm=pOrWc->a; i>=0 && indexable; i--, pOrTerm++){ if( (pOrTerm->eOperator & WO_SINGLE)==0 ){ WhereAndInfo *pAndInfo; assert( (pOrTerm->wtFlags & (TERM_ANDINFO|TERM_ORINFO))==0 ); chngToIN = 0; pAndInfo = sqlite3DbMallocRawNN(db, sizeof(*pAndInfo)); if( pAndInfo ){ WhereClause *pAndWC; WhereTerm *pAndTerm; int j; Bitmask b = 0; pOrTerm->u.pAndInfo = pAndInfo; pOrTerm->wtFlags |= TERM_ANDINFO; pOrTerm->eOperator = WO_AND; pAndWC = &pAndInfo->wc; memset(pAndWC->aStatic, 0, sizeof(pAndWC->aStatic)); sqlite3WhereClauseInit(pAndWC, pWC->pWInfo); sqlite3WhereSplit(pAndWC, pOrTerm->pExpr, TK_AND); sqlite3WhereExprAnalyze(pSrc, pAndWC); pAndWC->pOuter = pWC; if( !db->mallocFailed ){ for(j=0, pAndTerm=pAndWC->a; jnTerm; j++, pAndTerm++){ assert( pAndTerm->pExpr ); if( allowedOp(pAndTerm->pExpr->op) || pAndTerm->eOperator==WO_MATCH ){ b |= sqlite3WhereGetMask(&pWInfo->sMaskSet, pAndTerm->leftCursor); } } } indexable &= b; } }else if( pOrTerm->wtFlags & TERM_COPIED ){ /* Skip this term for now. We revisit it when we process the ** corresponding TERM_VIRTUAL term */ }else{ Bitmask b; b = sqlite3WhereGetMask(&pWInfo->sMaskSet, pOrTerm->leftCursor); if( pOrTerm->wtFlags & TERM_VIRTUAL ){ WhereTerm *pOther = &pOrWc->a[pOrTerm->iParent]; b |= sqlite3WhereGetMask(&pWInfo->sMaskSet, pOther->leftCursor); } indexable &= b; if( (pOrTerm->eOperator & WO_EQ)==0 ){ chngToIN = 0; }else{ chngToIN &= b; } } } /* ** Record the set of tables that satisfy case 3. The set might be ** empty. */ pOrInfo->indexable = indexable; pTerm->eOperator = indexable==0 ? 0 : WO_OR; /* For a two-way OR, attempt to implementation case 2. */ if( indexable && pOrWc->nTerm==2 ){ int iOne = 0; WhereTerm *pOne; while( (pOne = whereNthSubterm(&pOrWc->a[0],iOne++))!=0 ){ int iTwo = 0; WhereTerm *pTwo; while( (pTwo = whereNthSubterm(&pOrWc->a[1],iTwo++))!=0 ){ whereCombineDisjuncts(pSrc, pWC, pOne, pTwo); } } } /* ** chngToIN holds a set of tables that *might* satisfy case 1. But ** we have to do some additional checking to see if case 1 really ** is satisfied. ** ** chngToIN will hold either 0, 1, or 2 bits. The 0-bit case means ** that there is no possibility of transforming the OR clause into an ** IN operator because one or more terms in the OR clause contain ** something other than == on a column in the single table. The 1-bit ** case means that every term of the OR clause is of the form ** "table.column=expr" for some single table. The one bit that is set ** will correspond to the common table. We still need to check to make ** sure the same column is used on all terms. The 2-bit case is when ** the all terms are of the form "table1.column=table2.column". It ** might be possible to form an IN operator with either table1.column ** or table2.column as the LHS if either is common to every term of ** the OR clause. ** ** Note that terms of the form "table.column1=table.column2" (the ** same table on both sizes of the ==) cannot be optimized. */ if( chngToIN ){ int okToChngToIN = 0; /* True if the conversion to IN is valid */ int iColumn = -1; /* Column index on lhs of IN operator */ int iCursor = -1; /* Table cursor common to all terms */ int j = 0; /* Loop counter */ /* Search for a table and column that appears on one side or the ** other of the == operator in every subterm. That table and column ** will be recorded in iCursor and iColumn. There might not be any ** such table and column. Set okToChngToIN if an appropriate table ** and column is found but leave okToChngToIN false if not found. */ for(j=0; j<2 && !okToChngToIN; j++){ pOrTerm = pOrWc->a; for(i=pOrWc->nTerm-1; i>=0; i--, pOrTerm++){ assert( pOrTerm->eOperator & WO_EQ ); pOrTerm->wtFlags &= ~TERM_OR_OK; if( pOrTerm->leftCursor==iCursor ){ /* This is the 2-bit case and we are on the second iteration and ** current term is from the first iteration. So skip this term. */ assert( j==1 ); continue; } if( (chngToIN & sqlite3WhereGetMask(&pWInfo->sMaskSet, pOrTerm->leftCursor))==0 ){ /* This term must be of the form t1.a==t2.b where t2 is in the ** chngToIN set but t1 is not. This term will be either preceded ** or follwed by an inverted copy (t2.b==t1.a). Skip this term ** and use its inversion. */ testcase( pOrTerm->wtFlags & TERM_COPIED ); testcase( pOrTerm->wtFlags & TERM_VIRTUAL ); assert( pOrTerm->wtFlags & (TERM_COPIED|TERM_VIRTUAL) ); continue; } iColumn = pOrTerm->u.leftColumn; iCursor = pOrTerm->leftCursor; break; } if( i<0 ){ /* No candidate table+column was found. This can only occur ** on the second iteration */ assert( j==1 ); assert( IsPowerOfTwo(chngToIN) ); assert( chngToIN==sqlite3WhereGetMask(&pWInfo->sMaskSet, iCursor) ); break; } testcase( j==1 ); /* We have found a candidate table and column. Check to see if that ** table and column is common to every term in the OR clause */ okToChngToIN = 1; for(; i>=0 && okToChngToIN; i--, pOrTerm++){ assert( pOrTerm->eOperator & WO_EQ ); if( pOrTerm->leftCursor!=iCursor ){ pOrTerm->wtFlags &= ~TERM_OR_OK; }else if( pOrTerm->u.leftColumn!=iColumn ){ okToChngToIN = 0; }else{ int affLeft, affRight; /* If the right-hand side is also a column, then the affinities ** of both right and left sides must be such that no type ** conversions are required on the right. (Ticket #2249) */ affRight = sqlite3ExprAffinity(pOrTerm->pExpr->pRight); affLeft = sqlite3ExprAffinity(pOrTerm->pExpr->pLeft); if( affRight!=0 && affRight!=affLeft ){ okToChngToIN = 0; }else{ pOrTerm->wtFlags |= TERM_OR_OK; } } } } /* At this point, okToChngToIN is true if original pTerm satisfies ** case 1. In that case, construct a new virtual term that is ** pTerm converted into an IN operator. */ if( okToChngToIN ){ Expr *pDup; /* A transient duplicate expression */ ExprList *pList = 0; /* The RHS of the IN operator */ Expr *pLeft = 0; /* The LHS of the IN operator */ Expr *pNew; /* The complete IN operator */ for(i=pOrWc->nTerm-1, pOrTerm=pOrWc->a; i>=0; i--, pOrTerm++){ if( (pOrTerm->wtFlags & TERM_OR_OK)==0 ) continue; assert( pOrTerm->eOperator & WO_EQ ); assert( pOrTerm->leftCursor==iCursor ); assert( pOrTerm->u.leftColumn==iColumn ); pDup = sqlite3ExprDup(db, pOrTerm->pExpr->pRight, 0); pList = sqlite3ExprListAppend(pWInfo->pParse, pList, pDup); pLeft = pOrTerm->pExpr->pLeft; } assert( pLeft!=0 ); pDup = sqlite3ExprDup(db, pLeft, 0); pNew = sqlite3PExpr(pParse, TK_IN, pDup, 0, 0); if( pNew ){ int idxNew; transferJoinMarkings(pNew, pExpr); assert( !ExprHasProperty(pNew, EP_xIsSelect) ); pNew->x.pList = pList; idxNew = whereClauseInsert(pWC, pNew, TERM_VIRTUAL|TERM_DYNAMIC); testcase( idxNew==0 ); exprAnalyze(pSrc, pWC, idxNew); pTerm = &pWC->a[idxTerm]; markTermAsChild(pWC, idxNew, idxTerm); }else{ sqlite3ExprListDelete(db, pList); } pTerm->eOperator = WO_NOOP; /* case 1 trumps case 3 */ } } } #endif /* !SQLITE_OMIT_OR_OPTIMIZATION && !SQLITE_OMIT_SUBQUERY */ /* ** We already know that pExpr is a binary operator where both operands are ** column references. This routine checks to see if pExpr is an equivalence ** relation: ** 1. The SQLITE_Transitive optimization must be enabled ** 2. Must be either an == or an IS operator ** 3. Not originating in the ON clause of an OUTER JOIN ** 4. The affinities of A and B must be compatible ** 5a. Both operands use the same collating sequence OR ** 5b. The overall collating sequence is BINARY ** If this routine returns TRUE, that means that the RHS can be substituted ** for the LHS anyplace else in the WHERE clause where the LHS column occurs. ** This is an optimization. No harm comes from returning 0. But if 1 is ** returned when it should not be, then incorrect answers might result. */ static int termIsEquivalence(Parse *pParse, Expr *pExpr){ char aff1, aff2; CollSeq *pColl; const char *zColl1, *zColl2; if( !OptimizationEnabled(pParse->db, SQLITE_Transitive) ) return 0; if( pExpr->op!=TK_EQ && pExpr->op!=TK_IS ) return 0; if( ExprHasProperty(pExpr, EP_FromJoin) ) return 0; aff1 = sqlite3ExprAffinity(pExpr->pLeft); aff2 = sqlite3ExprAffinity(pExpr->pRight); if( aff1!=aff2 && (!sqlite3IsNumericAffinity(aff1) || !sqlite3IsNumericAffinity(aff2)) ){ return 0; } pColl = sqlite3BinaryCompareCollSeq(pParse, pExpr->pLeft, pExpr->pRight); if( pColl==0 || sqlite3StrICmp(pColl->zName, "BINARY")==0 ) return 1; pColl = sqlite3ExprCollSeq(pParse, pExpr->pLeft); zColl1 = pColl ? pColl->zName : 0; pColl = sqlite3ExprCollSeq(pParse, pExpr->pRight); zColl2 = pColl ? pColl->zName : 0; return sqlite3_stricmp(zColl1, zColl2)==0; } /* ** Recursively walk the expressions of a SELECT statement and generate ** a bitmask indicating which tables are used in that expression ** tree. */ static Bitmask exprSelectUsage(WhereMaskSet *pMaskSet, Select *pS){ Bitmask mask = 0; while( pS ){ SrcList *pSrc = pS->pSrc; mask |= sqlite3WhereExprListUsage(pMaskSet, pS->pEList); mask |= sqlite3WhereExprListUsage(pMaskSet, pS->pGroupBy); mask |= sqlite3WhereExprListUsage(pMaskSet, pS->pOrderBy); mask |= sqlite3WhereExprUsage(pMaskSet, pS->pWhere); mask |= sqlite3WhereExprUsage(pMaskSet, pS->pHaving); if( ALWAYS(pSrc!=0) ){ int i; for(i=0; inSrc; i++){ mask |= exprSelectUsage(pMaskSet, pSrc->a[i].pSelect); mask |= sqlite3WhereExprUsage(pMaskSet, pSrc->a[i].pOn); } } pS = pS->pPrior; } return mask; } /* ** Expression pExpr is one operand of a comparison operator that might ** be useful for indexing. This routine checks to see if pExpr appears ** in any index. Return TRUE (1) if pExpr is an indexed term and return ** FALSE (0) if not. If TRUE is returned, also set *piCur to the cursor ** number of the table that is indexed and *piColumn to the column number ** of the column that is indexed, or XN_EXPR (-2) if an expression is being ** indexed. ** ** If pExpr is a TK_COLUMN column reference, then this routine always returns ** true even if that particular column is not indexed, because the column ** might be added to an automatic index later. */ static int exprMightBeIndexed( SrcList *pFrom, /* The FROM clause */ int op, /* The specific comparison operator */ Bitmask mPrereq, /* Bitmask of FROM clause terms referenced by pExpr */ Expr *pExpr, /* An operand of a comparison operator */ int *piCur, /* Write the referenced table cursor number here */ int *piColumn /* Write the referenced table column number here */ ){ Index *pIdx; int i; int iCur; /* If this expression is a vector to the left or right of a ** inequality constraint (>, <, >= or <=), perform the processing ** on the first element of the vector. */ assert( TK_GT+1==TK_LE && TK_GT+2==TK_LT && TK_GT+3==TK_GE ); assert( TK_ISop==TK_VECTOR && (op>=TK_GT && ALWAYS(op<=TK_GE)) ){ pExpr = pExpr->x.pList->a[0].pExpr; } if( pExpr->op==TK_COLUMN ){ *piCur = pExpr->iTable; *piColumn = pExpr->iColumn; return 1; } if( mPrereq==0 ) return 0; /* No table references */ if( (mPrereq&(mPrereq-1))!=0 ) return 0; /* Refs more than one table */ for(i=0; mPrereq>1; i++, mPrereq>>=1){} iCur = pFrom->a[i].iCursor; for(pIdx=pFrom->a[i].pTab->pIndex; pIdx; pIdx=pIdx->pNext){ if( pIdx->aColExpr==0 ) continue; for(i=0; inKeyCol; i++){ if( pIdx->aiColumn[i]!=XN_EXPR ) continue; if( sqlite3ExprCompare(pExpr, pIdx->aColExpr->a[i].pExpr, iCur)==0 ){ *piCur = iCur; *piColumn = XN_EXPR; return 1; } } } return 0; } /* ** The input to this routine is an WhereTerm structure with only the ** "pExpr" field filled in. The job of this routine is to analyze the ** subexpression and populate all the other fields of the WhereTerm ** structure. ** ** If the expression is of the form " X" it gets commuted ** to the standard form of "X ". ** ** If the expression is of the form "X Y" where both X and Y are ** columns, then the original expression is unchanged and a new virtual ** term of the form "Y X" is added to the WHERE clause and ** analyzed separately. The original term is marked with TERM_COPIED ** and the new term is marked with TERM_DYNAMIC (because it's pExpr ** needs to be freed with the WhereClause) and TERM_VIRTUAL (because it ** is a commuted copy of a prior term.) The original term has nChild=1 ** and the copy has idxParent set to the index of the original term. */ static void exprAnalyze( SrcList *pSrc, /* the FROM clause */ WhereClause *pWC, /* the WHERE clause */ int idxTerm /* Index of the term to be analyzed */ ){ WhereInfo *pWInfo = pWC->pWInfo; /* WHERE clause processing context */ WhereTerm *pTerm; /* The term to be analyzed */ WhereMaskSet *pMaskSet; /* Set of table index masks */ Expr *pExpr; /* The expression to be analyzed */ Bitmask prereqLeft; /* Prerequesites of the pExpr->pLeft */ Bitmask prereqAll; /* Prerequesites of pExpr */ Bitmask extraRight = 0; /* Extra dependencies on LEFT JOIN */ Expr *pStr1 = 0; /* RHS of LIKE/GLOB operator */ int isComplete = 0; /* RHS of LIKE/GLOB ends with wildcard */ int noCase = 0; /* uppercase equivalent to lowercase */ int op; /* Top-level operator. pExpr->op */ Parse *pParse = pWInfo->pParse; /* Parsing context */ sqlite3 *db = pParse->db; /* Database connection */ unsigned char eOp2; /* op2 value for LIKE/REGEXP/GLOB */ if( db->mallocFailed ){ return; } pTerm = &pWC->a[idxTerm]; pMaskSet = &pWInfo->sMaskSet; pExpr = pTerm->pExpr; assert( pExpr->op!=TK_AS && pExpr->op!=TK_COLLATE ); prereqLeft = sqlite3WhereExprUsage(pMaskSet, pExpr->pLeft); op = pExpr->op; if( op==TK_IN ){ assert( pExpr->pRight==0 ); if( sqlite3ExprCheckIN(pParse, pExpr) ) return; if( ExprHasProperty(pExpr, EP_xIsSelect) ){ pTerm->prereqRight = exprSelectUsage(pMaskSet, pExpr->x.pSelect); }else{ pTerm->prereqRight = sqlite3WhereExprListUsage(pMaskSet, pExpr->x.pList); } }else if( op==TK_ISNULL ){ pTerm->prereqRight = 0; }else{ pTerm->prereqRight = sqlite3WhereExprUsage(pMaskSet, pExpr->pRight); } prereqAll = sqlite3WhereExprUsage(pMaskSet, pExpr); if( ExprHasProperty(pExpr, EP_FromJoin) ){ Bitmask x = sqlite3WhereGetMask(pMaskSet, pExpr->iRightJoinTable); prereqAll |= x; extraRight = x-1; /* ON clause terms may not be used with an index ** on left table of a LEFT JOIN. Ticket #3015 */ } pTerm->prereqAll = prereqAll; pTerm->leftCursor = -1; pTerm->iParent = -1; pTerm->eOperator = 0; if( allowedOp(op) ){ int iCur, iColumn; Expr *pLeft = sqlite3ExprSkipCollate(pExpr->pLeft); Expr *pRight = sqlite3ExprSkipCollate(pExpr->pRight); u16 opMask = (pTerm->prereqRight & prereqLeft)==0 ? WO_ALL : WO_EQUIV; if( pTerm->iField>0 ){ assert( op==TK_IN ); assert( pLeft->op==TK_VECTOR ); pLeft = pLeft->x.pList->a[pTerm->iField-1].pExpr; } if( exprMightBeIndexed(pSrc, op, prereqLeft, pLeft, &iCur, &iColumn) ){ pTerm->leftCursor = iCur; pTerm->u.leftColumn = iColumn; pTerm->eOperator = operatorMask(op) & opMask; } if( op==TK_IS ) pTerm->wtFlags |= TERM_IS; if( pRight && exprMightBeIndexed(pSrc, op, pTerm->prereqRight, pRight, &iCur,&iColumn) ){ WhereTerm *pNew; Expr *pDup; u16 eExtraOp = 0; /* Extra bits for pNew->eOperator */ assert( pTerm->iField==0 ); if( pTerm->leftCursor>=0 ){ int idxNew; pDup = sqlite3ExprDup(db, pExpr, 0); if( db->mallocFailed ){ sqlite3ExprDelete(db, pDup); return; } idxNew = whereClauseInsert(pWC, pDup, TERM_VIRTUAL|TERM_DYNAMIC); if( idxNew==0 ) return; pNew = &pWC->a[idxNew]; markTermAsChild(pWC, idxNew, idxTerm); if( op==TK_IS ) pNew->wtFlags |= TERM_IS; pTerm = &pWC->a[idxTerm]; pTerm->wtFlags |= TERM_COPIED; if( termIsEquivalence(pParse, pDup) ){ pTerm->eOperator |= WO_EQUIV; eExtraOp = WO_EQUIV; } }else{ pDup = pExpr; pNew = pTerm; } exprCommute(pParse, pDup); pNew->leftCursor = iCur; pNew->u.leftColumn = iColumn; testcase( (prereqLeft | extraRight) != prereqLeft ); pNew->prereqRight = prereqLeft | extraRight; pNew->prereqAll = prereqAll; pNew->eOperator = (operatorMask(pDup->op) + eExtraOp) & opMask; } } #ifndef SQLITE_OMIT_BETWEEN_OPTIMIZATION /* If a term is the BETWEEN operator, create two new virtual terms ** that define the range that the BETWEEN implements. For example: ** ** a BETWEEN b AND c ** ** is converted into: ** ** (a BETWEEN b AND c) AND (a>=b) AND (a<=c) ** ** The two new terms are added onto the end of the WhereClause object. ** The new terms are "dynamic" and are children of the original BETWEEN ** term. That means that if the BETWEEN term is coded, the children are ** skipped. Or, if the children are satisfied by an index, the original ** BETWEEN term is skipped. */ else if( pExpr->op==TK_BETWEEN && pWC->op==TK_AND ){ ExprList *pList = pExpr->x.pList; int i; static const u8 ops[] = {TK_GE, TK_LE}; assert( pList!=0 ); assert( pList->nExpr==2 ); for(i=0; i<2; i++){ Expr *pNewExpr; int idxNew; pNewExpr = sqlite3PExpr(pParse, ops[i], sqlite3ExprDup(db, pExpr->pLeft, 0), sqlite3ExprDup(db, pList->a[i].pExpr, 0), 0); transferJoinMarkings(pNewExpr, pExpr); idxNew = whereClauseInsert(pWC, pNewExpr, TERM_VIRTUAL|TERM_DYNAMIC); testcase( idxNew==0 ); exprAnalyze(pSrc, pWC, idxNew); pTerm = &pWC->a[idxTerm]; markTermAsChild(pWC, idxNew, idxTerm); } } #endif /* SQLITE_OMIT_BETWEEN_OPTIMIZATION */ #if !defined(SQLITE_OMIT_OR_OPTIMIZATION) && !defined(SQLITE_OMIT_SUBQUERY) /* Analyze a term that is composed of two or more subterms connected by ** an OR operator. */ else if( pExpr->op==TK_OR ){ assert( pWC->op==TK_AND ); exprAnalyzeOrTerm(pSrc, pWC, idxTerm); pTerm = &pWC->a[idxTerm]; } #endif /* SQLITE_OMIT_OR_OPTIMIZATION */ #ifndef SQLITE_OMIT_LIKE_OPTIMIZATION /* Add constraints to reduce the search space on a LIKE or GLOB ** operator. ** ** A like pattern of the form "x LIKE 'aBc%'" is changed into constraints ** ** x>='ABC' AND x<'abd' AND x LIKE 'aBc%' ** ** The last character of the prefix "abc" is incremented to form the ** termination condition "abd". If case is not significant (the default ** for LIKE) then the lower-bound is made all uppercase and the upper- ** bound is made all lowercase so that the bounds also work when comparing ** BLOBs. */ if( pWC->op==TK_AND && isLikeOrGlob(pParse, pExpr, &pStr1, &isComplete, &noCase) ){ Expr *pLeft; /* LHS of LIKE/GLOB operator */ Expr *pStr2; /* Copy of pStr1 - RHS of LIKE/GLOB operator */ Expr *pNewExpr1; Expr *pNewExpr2; int idxNew1; int idxNew2; const char *zCollSeqName; /* Name of collating sequence */ const u16 wtFlags = TERM_LIKEOPT | TERM_VIRTUAL | TERM_DYNAMIC; pLeft = pExpr->x.pList->a[1].pExpr; pStr2 = sqlite3ExprDup(db, pStr1, 0); /* Convert the lower bound to upper-case and the upper bound to ** lower-case (upper-case is less than lower-case in ASCII) so that ** the range constraints also work for BLOBs */ if( noCase && !pParse->db->mallocFailed ){ int i; char c; pTerm->wtFlags |= TERM_LIKE; for(i=0; (c = pStr1->u.zToken[i])!=0; i++){ pStr1->u.zToken[i] = sqlite3Toupper(c); pStr2->u.zToken[i] = sqlite3Tolower(c); } } if( !db->mallocFailed ){ u8 c, *pC; /* Last character before the first wildcard */ pC = (u8*)&pStr2->u.zToken[sqlite3Strlen30(pStr2->u.zToken)-1]; c = *pC; if( noCase ){ /* The point is to increment the last character before the first ** wildcard. But if we increment '@', that will push it into the ** alphabetic range where case conversions will mess up the ** inequality. To avoid this, make sure to also run the full ** LIKE on all candidate expressions by clearing the isComplete flag */ if( c=='A'-1 ) isComplete = 0; c = sqlite3UpperToLower[c]; } *pC = c + 1; } zCollSeqName = noCase ? "NOCASE" : "BINARY"; pNewExpr1 = sqlite3ExprDup(db, pLeft, 0); pNewExpr1 = sqlite3PExpr(pParse, TK_GE, sqlite3ExprAddCollateString(pParse,pNewExpr1,zCollSeqName), pStr1, 0); transferJoinMarkings(pNewExpr1, pExpr); idxNew1 = whereClauseInsert(pWC, pNewExpr1, wtFlags); testcase( idxNew1==0 ); exprAnalyze(pSrc, pWC, idxNew1); pNewExpr2 = sqlite3ExprDup(db, pLeft, 0); pNewExpr2 = sqlite3PExpr(pParse, TK_LT, sqlite3ExprAddCollateString(pParse,pNewExpr2,zCollSeqName), pStr2, 0); transferJoinMarkings(pNewExpr2, pExpr); idxNew2 = whereClauseInsert(pWC, pNewExpr2, wtFlags); testcase( idxNew2==0 ); exprAnalyze(pSrc, pWC, idxNew2); pTerm = &pWC->a[idxTerm]; if( isComplete ){ markTermAsChild(pWC, idxNew1, idxTerm); markTermAsChild(pWC, idxNew2, idxTerm); } } #endif /* SQLITE_OMIT_LIKE_OPTIMIZATION */ #ifndef SQLITE_OMIT_VIRTUALTABLE /* Add a WO_MATCH auxiliary term to the constraint set if the ** current expression is of the form: column MATCH expr. ** This information is used by the xBestIndex methods of ** virtual tables. The native query optimizer does not attempt ** to do anything with MATCH functions. */ if( pWC->op==TK_AND && isMatchOfColumn(pExpr, &eOp2) ){ int idxNew; Expr *pRight, *pLeft; WhereTerm *pNewTerm; Bitmask prereqColumn, prereqExpr; pRight = pExpr->x.pList->a[0].pExpr; pLeft = pExpr->x.pList->a[1].pExpr; prereqExpr = sqlite3WhereExprUsage(pMaskSet, pRight); prereqColumn = sqlite3WhereExprUsage(pMaskSet, pLeft); if( (prereqExpr & prereqColumn)==0 ){ Expr *pNewExpr; pNewExpr = sqlite3PExpr(pParse, TK_MATCH, 0, sqlite3ExprDup(db, pRight, 0), 0); idxNew = whereClauseInsert(pWC, pNewExpr, TERM_VIRTUAL|TERM_DYNAMIC); testcase( idxNew==0 ); pNewTerm = &pWC->a[idxNew]; pNewTerm->prereqRight = prereqExpr; pNewTerm->leftCursor = pLeft->iTable; pNewTerm->u.leftColumn = pLeft->iColumn; pNewTerm->eOperator = WO_MATCH; pNewTerm->eMatchOp = eOp2; markTermAsChild(pWC, idxNew, idxTerm); pTerm = &pWC->a[idxTerm]; pTerm->wtFlags |= TERM_COPIED; pNewTerm->prereqAll = pTerm->prereqAll; } } #endif /* SQLITE_OMIT_VIRTUALTABLE */ /* If there is a vector == or IS term - e.g. "(a, b) == (?, ?)" - create ** new terms for each component comparison - "a = ?" and "b = ?". The ** new terms completely replace the original vector comparison, which is ** no longer used. ** ** This is only required if at least one side of the comparison operation ** is not a sub-select. */ if( pWC->op==TK_AND && (pExpr->op==TK_EQ || pExpr->op==TK_IS) && sqlite3ExprIsVector(pExpr->pLeft) && ( (pExpr->pLeft->flags & EP_xIsSelect)==0 || (pExpr->pRight->flags & EP_xIsSelect)==0 )){ int nLeft = sqlite3ExprVectorSize(pExpr->pLeft); int i; assert( nLeft==sqlite3ExprVectorSize(pExpr->pRight) ); for(i=0; ipLeft, i); Expr *pRight = sqlite3ExprForVectorField(pParse, pExpr->pRight, i); pNew = sqlite3PExpr(pParse, pExpr->op, pLeft, pRight, 0); transferJoinMarkings(pNew, pExpr); idxNew = whereClauseInsert(pWC, pNew, TERM_DYNAMIC); exprAnalyze(pSrc, pWC, idxNew); } pTerm = &pWC->a[idxTerm]; pTerm->wtFlags = TERM_CODED|TERM_VIRTUAL; /* Disable the original */ pTerm->eOperator = 0; } /* If there is a vector IN term - e.g. "(a, b) IN (SELECT ...)" - create ** a virtual term for each vector component. The expression object ** used by each such virtual term is pExpr (the full vector IN(...) ** expression). The WhereTerm.iField variable identifies the index within ** the vector on the LHS that the virtual term represents. ** ** This only works if the RHS is a simple SELECT, not a compound */ if( pWC->op==TK_AND && pExpr->op==TK_IN && pTerm->iField==0 && pExpr->pLeft->op==TK_VECTOR && pExpr->x.pSelect->pPrior==0 ){ int i; for(i=0; ipLeft); i++){ int idxNew; idxNew = whereClauseInsert(pWC, pExpr, TERM_VIRTUAL); pWC->a[idxNew].iField = i+1; exprAnalyze(pSrc, pWC, idxNew); markTermAsChild(pWC, idxNew, idxTerm); } } #ifdef SQLITE_ENABLE_STAT3_OR_STAT4 /* When sqlite_stat3 histogram data is available an operator of the ** form "x IS NOT NULL" can sometimes be evaluated more efficiently ** as "x>NULL" if x is not an INTEGER PRIMARY KEY. So construct a ** virtual term of that form. ** ** Note that the virtual term must be tagged with TERM_VNULL. */ if( pExpr->op==TK_NOTNULL && pExpr->pLeft->op==TK_COLUMN && pExpr->pLeft->iColumn>=0 && OptimizationEnabled(db, SQLITE_Stat34) ){ Expr *pNewExpr; Expr *pLeft = pExpr->pLeft; int idxNew; WhereTerm *pNewTerm; pNewExpr = sqlite3PExpr(pParse, TK_GT, sqlite3ExprDup(db, pLeft, 0), sqlite3ExprAlloc(db, TK_NULL, 0, 0), 0); idxNew = whereClauseInsert(pWC, pNewExpr, TERM_VIRTUAL|TERM_DYNAMIC|TERM_VNULL); if( idxNew ){ pNewTerm = &pWC->a[idxNew]; pNewTerm->prereqRight = 0; pNewTerm->leftCursor = pLeft->iTable; pNewTerm->u.leftColumn = pLeft->iColumn; pNewTerm->eOperator = WO_GT; markTermAsChild(pWC, idxNew, idxTerm); pTerm = &pWC->a[idxTerm]; pTerm->wtFlags |= TERM_COPIED; pNewTerm->prereqAll = pTerm->prereqAll; } } #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */ /* Prevent ON clause terms of a LEFT JOIN from being used to drive ** an index for tables to the left of the join. */ pTerm->prereqRight |= extraRight; } /*************************************************************************** ** Routines with file scope above. Interface to the rest of the where.c ** subsystem follows. ***************************************************************************/ /* ** This routine identifies subexpressions in the WHERE clause where ** each subexpression is separated by the AND operator or some other ** operator specified in the op parameter. The WhereClause structure ** is filled with pointers to subexpressions. For example: ** ** WHERE a=='hello' AND coalesce(b,11)<10 AND (c+12!=d OR c==22) ** \________/ \_______________/ \________________/ ** slot[0] slot[1] slot[2] ** ** The original WHERE clause in pExpr is unaltered. All this routine ** does is make slot[] entries point to substructure within pExpr. ** ** In the previous sentence and in the diagram, "slot[]" refers to ** the WhereClause.a[] array. The slot[] array grows as needed to contain ** all terms of the WHERE clause. */ SQLITE_PRIVATE void sqlite3WhereSplit(WhereClause *pWC, Expr *pExpr, u8 op){ Expr *pE2 = sqlite3ExprSkipCollate(pExpr); pWC->op = op; if( pE2==0 ) return; if( pE2->op!=op ){ whereClauseInsert(pWC, pExpr, 0); }else{ sqlite3WhereSplit(pWC, pE2->pLeft, op); sqlite3WhereSplit(pWC, pE2->pRight, op); } } /* ** Initialize a preallocated WhereClause structure. */ SQLITE_PRIVATE void sqlite3WhereClauseInit( WhereClause *pWC, /* The WhereClause to be initialized */ WhereInfo *pWInfo /* The WHERE processing context */ ){ pWC->pWInfo = pWInfo; pWC->pOuter = 0; pWC->nTerm = 0; pWC->nSlot = ArraySize(pWC->aStatic); pWC->a = pWC->aStatic; } /* ** Deallocate a WhereClause structure. The WhereClause structure ** itself is not freed. This routine is the inverse of ** sqlite3WhereClauseInit(). */ SQLITE_PRIVATE void sqlite3WhereClauseClear(WhereClause *pWC){ int i; WhereTerm *a; sqlite3 *db = pWC->pWInfo->pParse->db; for(i=pWC->nTerm-1, a=pWC->a; i>=0; i--, a++){ if( a->wtFlags & TERM_DYNAMIC ){ sqlite3ExprDelete(db, a->pExpr); } if( a->wtFlags & TERM_ORINFO ){ whereOrInfoDelete(db, a->u.pOrInfo); }else if( a->wtFlags & TERM_ANDINFO ){ whereAndInfoDelete(db, a->u.pAndInfo); } } if( pWC->a!=pWC->aStatic ){ sqlite3DbFree(db, pWC->a); } } /* ** These routines walk (recursively) an expression tree and generate ** a bitmask indicating which tables are used in that expression ** tree. */ SQLITE_PRIVATE Bitmask sqlite3WhereExprUsage(WhereMaskSet *pMaskSet, Expr *p){ Bitmask mask; if( p==0 ) return 0; if( p->op==TK_COLUMN ){ mask = sqlite3WhereGetMask(pMaskSet, p->iTable); return mask; } assert( !ExprHasProperty(p, EP_TokenOnly) ); mask = p->pRight ? sqlite3WhereExprUsage(pMaskSet, p->pRight) : 0; if( p->pLeft ) mask |= sqlite3WhereExprUsage(pMaskSet, p->pLeft); if( ExprHasProperty(p, EP_xIsSelect) ){ mask |= exprSelectUsage(pMaskSet, p->x.pSelect); }else if( p->x.pList ){ mask |= sqlite3WhereExprListUsage(pMaskSet, p->x.pList); } return mask; } SQLITE_PRIVATE Bitmask sqlite3WhereExprListUsage(WhereMaskSet *pMaskSet, ExprList *pList){ int i; Bitmask mask = 0; if( pList ){ for(i=0; inExpr; i++){ mask |= sqlite3WhereExprUsage(pMaskSet, pList->a[i].pExpr); } } return mask; } /* ** Call exprAnalyze on all terms in a WHERE clause. ** ** Note that exprAnalyze() might add new virtual terms onto the ** end of the WHERE clause. We do not want to analyze these new ** virtual terms, so start analyzing at the end and work forward ** so that the added virtual terms are never processed. */ SQLITE_PRIVATE void sqlite3WhereExprAnalyze( SrcList *pTabList, /* the FROM clause */ WhereClause *pWC /* the WHERE clause to be analyzed */ ){ int i; for(i=pWC->nTerm-1; i>=0; i--){ exprAnalyze(pTabList, pWC, i); } } /* ** For table-valued-functions, transform the function arguments into ** new WHERE clause terms. ** ** Each function argument translates into an equality constraint against ** a HIDDEN column in the table. */ SQLITE_PRIVATE void sqlite3WhereTabFuncArgs( Parse *pParse, /* Parsing context */ struct SrcList_item *pItem, /* The FROM clause term to process */ WhereClause *pWC /* Xfer function arguments to here */ ){ Table *pTab; int j, k; ExprList *pArgs; Expr *pColRef; Expr *pTerm; if( pItem->fg.isTabFunc==0 ) return; pTab = pItem->pTab; assert( pTab!=0 ); pArgs = pItem->u1.pFuncArg; if( pArgs==0 ) return; for(j=k=0; jnExpr; j++){ while( knCol && (pTab->aCol[k].colFlags & COLFLAG_HIDDEN)==0 ){k++;} if( k>=pTab->nCol ){ sqlite3ErrorMsg(pParse, "too many arguments on %s() - max %d", pTab->zName, j); return; } pColRef = sqlite3ExprAlloc(pParse->db, TK_COLUMN, 0, 0); if( pColRef==0 ) return; pColRef->iTable = pItem->iCursor; pColRef->iColumn = k++; pColRef->pTab = pTab; pTerm = sqlite3PExpr(pParse, TK_EQ, pColRef, sqlite3ExprDup(pParse->db, pArgs->a[j].pExpr, 0), 0); whereClauseInsert(pWC, pTerm, TERM_DYNAMIC); } } /************** End of whereexpr.c *******************************************/ /************** Begin file where.c *******************************************/ /* ** 2001 September 15 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ************************************************************************* ** This module contains C code that generates VDBE code used to process ** the WHERE clause of SQL statements. This module is responsible for ** generating the code that loops through a table looking for applicable ** rows. Indices are selected and used to speed the search when doing ** so is applicable. Because this module is responsible for selecting ** indices, you might also think of this module as the "query optimizer". */ /* #include "sqliteInt.h" */ /* #include "whereInt.h" */ /* Forward declaration of methods */ static int whereLoopResize(sqlite3*, WhereLoop*, int); /* Test variable that can be set to enable WHERE tracing */ #if defined(SQLITE_TEST) || defined(SQLITE_DEBUG) /***/ int sqlite3WhereTrace = 0; #endif /* ** Return the estimated number of output rows from a WHERE clause */ SQLITE_PRIVATE LogEst sqlite3WhereOutputRowCount(WhereInfo *pWInfo){ return pWInfo->nRowOut; } /* ** Return one of the WHERE_DISTINCT_xxxxx values to indicate how this ** WHERE clause returns outputs for DISTINCT processing. */ SQLITE_PRIVATE int sqlite3WhereIsDistinct(WhereInfo *pWInfo){ return pWInfo->eDistinct; } /* ** Return TRUE if the WHERE clause returns rows in ORDER BY order. ** Return FALSE if the output needs to be sorted. */ SQLITE_PRIVATE int sqlite3WhereIsOrdered(WhereInfo *pWInfo){ return pWInfo->nOBSat; } /* ** Return TRUE if the innermost loop of the WHERE clause implementation ** returns rows in ORDER BY order for complete run of the inner loop. ** ** Across multiple iterations of outer loops, the output rows need not be ** sorted. As long as rows are sorted for just the innermost loop, this ** routine can return TRUE. */ SQLITE_PRIVATE int sqlite3WhereOrderedInnerLoop(WhereInfo *pWInfo){ return pWInfo->bOrderedInnerLoop; } /* ** Return the VDBE address or label to jump to in order to continue ** immediately with the next row of a WHERE clause. */ SQLITE_PRIVATE int sqlite3WhereContinueLabel(WhereInfo *pWInfo){ assert( pWInfo->iContinue!=0 ); return pWInfo->iContinue; } /* ** Return the VDBE address or label to jump to in order to break ** out of a WHERE loop. */ SQLITE_PRIVATE int sqlite3WhereBreakLabel(WhereInfo *pWInfo){ return pWInfo->iBreak; } /* ** Return ONEPASS_OFF (0) if an UPDATE or DELETE statement is unable to ** operate directly on the rowis returned by a WHERE clause. Return ** ONEPASS_SINGLE (1) if the statement can operation directly because only ** a single row is to be changed. Return ONEPASS_MULTI (2) if the one-pass ** optimization can be used on multiple ** ** If the ONEPASS optimization is used (if this routine returns true) ** then also write the indices of open cursors used by ONEPASS ** into aiCur[0] and aiCur[1]. iaCur[0] gets the cursor of the data ** table and iaCur[1] gets the cursor used by an auxiliary index. ** Either value may be -1, indicating that cursor is not used. ** Any cursors returned will have been opened for writing. ** ** aiCur[0] and aiCur[1] both get -1 if the where-clause logic is ** unable to use the ONEPASS optimization. */ SQLITE_PRIVATE int sqlite3WhereOkOnePass(WhereInfo *pWInfo, int *aiCur){ memcpy(aiCur, pWInfo->aiCurOnePass, sizeof(int)*2); #ifdef WHERETRACE_ENABLED if( sqlite3WhereTrace && pWInfo->eOnePass!=ONEPASS_OFF ){ sqlite3DebugPrintf("%s cursors: %d %d\n", pWInfo->eOnePass==ONEPASS_SINGLE ? "ONEPASS_SINGLE" : "ONEPASS_MULTI", aiCur[0], aiCur[1]); } #endif return pWInfo->eOnePass; } /* ** Move the content of pSrc into pDest */ static void whereOrMove(WhereOrSet *pDest, WhereOrSet *pSrc){ pDest->n = pSrc->n; memcpy(pDest->a, pSrc->a, pDest->n*sizeof(pDest->a[0])); } /* ** Try to insert a new prerequisite/cost entry into the WhereOrSet pSet. ** ** The new entry might overwrite an existing entry, or it might be ** appended, or it might be discarded. Do whatever is the right thing ** so that pSet keeps the N_OR_COST best entries seen so far. */ static int whereOrInsert( WhereOrSet *pSet, /* The WhereOrSet to be updated */ Bitmask prereq, /* Prerequisites of the new entry */ LogEst rRun, /* Run-cost of the new entry */ LogEst nOut /* Number of outputs for the new entry */ ){ u16 i; WhereOrCost *p; for(i=pSet->n, p=pSet->a; i>0; i--, p++){ if( rRun<=p->rRun && (prereq & p->prereq)==prereq ){ goto whereOrInsert_done; } if( p->rRun<=rRun && (p->prereq & prereq)==p->prereq ){ return 0; } } if( pSet->na[pSet->n++]; p->nOut = nOut; }else{ p = pSet->a; for(i=1; in; i++){ if( p->rRun>pSet->a[i].rRun ) p = pSet->a + i; } if( p->rRun<=rRun ) return 0; } whereOrInsert_done: p->prereq = prereq; p->rRun = rRun; if( p->nOut>nOut ) p->nOut = nOut; return 1; } /* ** Return the bitmask for the given cursor number. Return 0 if ** iCursor is not in the set. */ SQLITE_PRIVATE Bitmask sqlite3WhereGetMask(WhereMaskSet *pMaskSet, int iCursor){ int i; assert( pMaskSet->n<=(int)sizeof(Bitmask)*8 ); for(i=0; in; i++){ if( pMaskSet->ix[i]==iCursor ){ return MASKBIT(i); } } return 0; } /* ** Create a new mask for cursor iCursor. ** ** There is one cursor per table in the FROM clause. The number of ** tables in the FROM clause is limited by a test early in the ** sqlite3WhereBegin() routine. So we know that the pMaskSet->ix[] ** array will never overflow. */ static void createMask(WhereMaskSet *pMaskSet, int iCursor){ assert( pMaskSet->n < ArraySize(pMaskSet->ix) ); pMaskSet->ix[pMaskSet->n++] = iCursor; } /* ** Advance to the next WhereTerm that matches according to the criteria ** established when the pScan object was initialized by whereScanInit(). ** Return NULL if there are no more matching WhereTerms. */ static WhereTerm *whereScanNext(WhereScan *pScan){ int iCur; /* The cursor on the LHS of the term */ i16 iColumn; /* The column on the LHS of the term. -1 for IPK */ Expr *pX; /* An expression being tested */ WhereClause *pWC; /* Shorthand for pScan->pWC */ WhereTerm *pTerm; /* The term being tested */ int k = pScan->k; /* Where to start scanning */ while( pScan->iEquiv<=pScan->nEquiv ){ iCur = pScan->aiCur[pScan->iEquiv-1]; iColumn = pScan->aiColumn[pScan->iEquiv-1]; if( iColumn==XN_EXPR && pScan->pIdxExpr==0 ) return 0; while( (pWC = pScan->pWC)!=0 ){ for(pTerm=pWC->a+k; knTerm; k++, pTerm++){ if( pTerm->leftCursor==iCur && pTerm->u.leftColumn==iColumn && (iColumn!=XN_EXPR || sqlite3ExprCompare(pTerm->pExpr->pLeft,pScan->pIdxExpr,iCur)==0) && (pScan->iEquiv<=1 || !ExprHasProperty(pTerm->pExpr, EP_FromJoin)) ){ if( (pTerm->eOperator & WO_EQUIV)!=0 && pScan->nEquivaiCur) && (pX = sqlite3ExprSkipCollate(pTerm->pExpr->pRight))->op==TK_COLUMN ){ int j; for(j=0; jnEquiv; j++){ if( pScan->aiCur[j]==pX->iTable && pScan->aiColumn[j]==pX->iColumn ){ break; } } if( j==pScan->nEquiv ){ pScan->aiCur[j] = pX->iTable; pScan->aiColumn[j] = pX->iColumn; pScan->nEquiv++; } } if( (pTerm->eOperator & pScan->opMask)!=0 ){ /* Verify the affinity and collating sequence match */ if( pScan->zCollName && (pTerm->eOperator & WO_ISNULL)==0 ){ CollSeq *pColl; Parse *pParse = pWC->pWInfo->pParse; pX = pTerm->pExpr; if( !sqlite3IndexAffinityOk(pX, pScan->idxaff) ){ continue; } assert(pX->pLeft); pColl = sqlite3BinaryCompareCollSeq(pParse, pX->pLeft, pX->pRight); if( pColl==0 ) pColl = pParse->db->pDfltColl; if( sqlite3StrICmp(pColl->zName, pScan->zCollName) ){ continue; } } if( (pTerm->eOperator & (WO_EQ|WO_IS))!=0 && (pX = pTerm->pExpr->pRight)->op==TK_COLUMN && pX->iTable==pScan->aiCur[0] && pX->iColumn==pScan->aiColumn[0] ){ testcase( pTerm->eOperator & WO_IS ); continue; } pScan->k = k+1; return pTerm; } } } pScan->pWC = pScan->pWC->pOuter; k = 0; } pScan->pWC = pScan->pOrigWC; k = 0; pScan->iEquiv++; } return 0; } /* ** Initialize a WHERE clause scanner object. Return a pointer to the ** first match. Return NULL if there are no matches. ** ** The scanner will be searching the WHERE clause pWC. It will look ** for terms of the form "X " where X is column iColumn of table ** iCur. Or if pIdx!=0 then X is column iColumn of index pIdx. pIdx ** must be one of the indexes of table iCur. ** ** The must be one of the operators described by opMask. ** ** If the search is for X and the WHERE clause contains terms of the ** form X=Y then this routine might also return terms of the form ** "Y ". The number of levels of transitivity is limited, ** but is enough to handle most commonly occurring SQL statements. ** ** If X is not the INTEGER PRIMARY KEY then X must be compatible with ** index pIdx. */ static WhereTerm *whereScanInit( WhereScan *pScan, /* The WhereScan object being initialized */ WhereClause *pWC, /* The WHERE clause to be scanned */ int iCur, /* Cursor to scan for */ int iColumn, /* Column to scan for */ u32 opMask, /* Operator(s) to scan for */ Index *pIdx /* Must be compatible with this index */ ){ int j = 0; /* memset(pScan, 0, sizeof(*pScan)); */ pScan->pOrigWC = pWC; pScan->pWC = pWC; pScan->pIdxExpr = 0; if( pIdx ){ j = iColumn; iColumn = pIdx->aiColumn[j]; if( iColumn==XN_EXPR ) pScan->pIdxExpr = pIdx->aColExpr->a[j].pExpr; if( iColumn==pIdx->pTable->iPKey ) iColumn = XN_ROWID; } if( pIdx && iColumn>=0 ){ pScan->idxaff = pIdx->pTable->aCol[iColumn].affinity; pScan->zCollName = pIdx->azColl[j]; }else{ pScan->idxaff = 0; pScan->zCollName = 0; } pScan->opMask = opMask; pScan->k = 0; pScan->aiCur[0] = iCur; pScan->aiColumn[0] = iColumn; pScan->nEquiv = 1; pScan->iEquiv = 1; return whereScanNext(pScan); } /* ** Search for a term in the WHERE clause that is of the form "X " ** where X is a reference to the iColumn of table iCur or of index pIdx ** if pIdx!=0 and is one of the WO_xx operator codes specified by ** the op parameter. Return a pointer to the term. Return 0 if not found. ** ** If pIdx!=0 then it must be one of the indexes of table iCur. ** Search for terms matching the iColumn-th column of pIdx ** rather than the iColumn-th column of table iCur. ** ** The term returned might by Y= if there is another constraint in ** the WHERE clause that specifies that X=Y. Any such constraints will be ** identified by the WO_EQUIV bit in the pTerm->eOperator field. The ** aiCur[]/iaColumn[] arrays hold X and all its equivalents. There are 11 ** slots in aiCur[]/aiColumn[] so that means we can look for X plus up to 10 ** other equivalent values. Hence a search for X will return if X=A1 ** and A1=A2 and A2=A3 and ... and A9=A10 and A10=. ** ** If there are multiple terms in the WHERE clause of the form "X " ** then try for the one with no dependencies on - in other words where ** is a constant expression of some kind. Only return entries of ** the form "X Y" where Y is a column in another table if no terms of ** the form "X " exist. If no terms with a constant RHS ** exist, try to return a term that does not use WO_EQUIV. */ SQLITE_PRIVATE WhereTerm *sqlite3WhereFindTerm( WhereClause *pWC, /* The WHERE clause to be searched */ int iCur, /* Cursor number of LHS */ int iColumn, /* Column number of LHS */ Bitmask notReady, /* RHS must not overlap with this mask */ u32 op, /* Mask of WO_xx values describing operator */ Index *pIdx /* Must be compatible with this index, if not NULL */ ){ WhereTerm *pResult = 0; WhereTerm *p; WhereScan scan; p = whereScanInit(&scan, pWC, iCur, iColumn, op, pIdx); op &= WO_EQ|WO_IS; while( p ){ if( (p->prereqRight & notReady)==0 ){ if( p->prereqRight==0 && (p->eOperator&op)!=0 ){ testcase( p->eOperator & WO_IS ); return p; } if( pResult==0 ) pResult = p; } p = whereScanNext(&scan); } return pResult; } /* ** This function searches pList for an entry that matches the iCol-th column ** of index pIdx. ** ** If such an expression is found, its index in pList->a[] is returned. If ** no expression is found, -1 is returned. */ static int findIndexCol( Parse *pParse, /* Parse context */ ExprList *pList, /* Expression list to search */ int iBase, /* Cursor for table associated with pIdx */ Index *pIdx, /* Index to match column of */ int iCol /* Column of index to match */ ){ int i; const char *zColl = pIdx->azColl[iCol]; for(i=0; inExpr; i++){ Expr *p = sqlite3ExprSkipCollate(pList->a[i].pExpr); if( p->op==TK_COLUMN && p->iColumn==pIdx->aiColumn[iCol] && p->iTable==iBase ){ CollSeq *pColl = sqlite3ExprCollSeq(pParse, pList->a[i].pExpr); if( pColl && 0==sqlite3StrICmp(pColl->zName, zColl) ){ return i; } } } return -1; } /* ** Return TRUE if the iCol-th column of index pIdx is NOT NULL */ static int indexColumnNotNull(Index *pIdx, int iCol){ int j; assert( pIdx!=0 ); assert( iCol>=0 && iColnColumn ); j = pIdx->aiColumn[iCol]; if( j>=0 ){ return pIdx->pTable->aCol[j].notNull; }else if( j==(-1) ){ return 1; }else{ assert( j==(-2) ); return 0; /* Assume an indexed expression can always yield a NULL */ } } /* ** Return true if the DISTINCT expression-list passed as the third argument ** is redundant. ** ** A DISTINCT list is redundant if any subset of the columns in the ** DISTINCT list are collectively unique and individually non-null. */ static int isDistinctRedundant( Parse *pParse, /* Parsing context */ SrcList *pTabList, /* The FROM clause */ WhereClause *pWC, /* The WHERE clause */ ExprList *pDistinct /* The result set that needs to be DISTINCT */ ){ Table *pTab; Index *pIdx; int i; int iBase; /* If there is more than one table or sub-select in the FROM clause of ** this query, then it will not be possible to show that the DISTINCT ** clause is redundant. */ if( pTabList->nSrc!=1 ) return 0; iBase = pTabList->a[0].iCursor; pTab = pTabList->a[0].pTab; /* If any of the expressions is an IPK column on table iBase, then return ** true. Note: The (p->iTable==iBase) part of this test may be false if the ** current SELECT is a correlated sub-query. */ for(i=0; inExpr; i++){ Expr *p = sqlite3ExprSkipCollate(pDistinct->a[i].pExpr); if( p->op==TK_COLUMN && p->iTable==iBase && p->iColumn<0 ) return 1; } /* Loop through all indices on the table, checking each to see if it makes ** the DISTINCT qualifier redundant. It does so if: ** ** 1. The index is itself UNIQUE, and ** ** 2. All of the columns in the index are either part of the pDistinct ** list, or else the WHERE clause contains a term of the form "col=X", ** where X is a constant value. The collation sequences of the ** comparison and select-list expressions must match those of the index. ** ** 3. All of those index columns for which the WHERE clause does not ** contain a "col=X" term are subject to a NOT NULL constraint. */ for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){ if( !IsUniqueIndex(pIdx) ) continue; for(i=0; inKeyCol; i++){ if( 0==sqlite3WhereFindTerm(pWC, iBase, i, ~(Bitmask)0, WO_EQ, pIdx) ){ if( findIndexCol(pParse, pDistinct, iBase, pIdx, i)<0 ) break; if( indexColumnNotNull(pIdx, i)==0 ) break; } } if( i==pIdx->nKeyCol ){ /* This index implies that the DISTINCT qualifier is redundant. */ return 1; } } return 0; } /* ** Estimate the logarithm of the input value to base 2. */ static LogEst estLog(LogEst N){ return N<=10 ? 0 : sqlite3LogEst(N) - 33; } /* ** Convert OP_Column opcodes to OP_Copy in previously generated code. ** ** This routine runs over generated VDBE code and translates OP_Column ** opcodes into OP_Copy when the table is being accessed via co-routine ** instead of via table lookup. ** ** If the bIncrRowid parameter is 0, then any OP_Rowid instructions on ** cursor iTabCur are transformed into OP_Null. Or, if bIncrRowid is non-zero, ** then each OP_Rowid is transformed into an instruction to increment the ** value stored in its output register. */ static void translateColumnToCopy( Vdbe *v, /* The VDBE containing code to translate */ int iStart, /* Translate from this opcode to the end */ int iTabCur, /* OP_Column/OP_Rowid references to this table */ int iRegister, /* The first column is in this register */ int bIncrRowid /* If non-zero, transform OP_rowid to OP_AddImm(1) */ ){ VdbeOp *pOp = sqlite3VdbeGetOp(v, iStart); int iEnd = sqlite3VdbeCurrentAddr(v); for(; iStartp1!=iTabCur ) continue; if( pOp->opcode==OP_Column ){ pOp->opcode = OP_Copy; pOp->p1 = pOp->p2 + iRegister; pOp->p2 = pOp->p3; pOp->p3 = 0; }else if( pOp->opcode==OP_Rowid ){ if( bIncrRowid ){ /* Increment the value stored in the P2 operand of the OP_Rowid. */ pOp->opcode = OP_AddImm; pOp->p1 = pOp->p2; pOp->p2 = 1; }else{ pOp->opcode = OP_Null; pOp->p1 = 0; pOp->p3 = 0; } } } } /* ** Two routines for printing the content of an sqlite3_index_info ** structure. Used for testing and debugging only. If neither ** SQLITE_TEST or SQLITE_DEBUG are defined, then these routines ** are no-ops. */ #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(WHERETRACE_ENABLED) static void TRACE_IDX_INPUTS(sqlite3_index_info *p){ int i; if( !sqlite3WhereTrace ) return; for(i=0; inConstraint; i++){ sqlite3DebugPrintf(" constraint[%d]: col=%d termid=%d op=%d usabled=%d\n", i, p->aConstraint[i].iColumn, p->aConstraint[i].iTermOffset, p->aConstraint[i].op, p->aConstraint[i].usable); } for(i=0; inOrderBy; i++){ sqlite3DebugPrintf(" orderby[%d]: col=%d desc=%d\n", i, p->aOrderBy[i].iColumn, p->aOrderBy[i].desc); } } static void TRACE_IDX_OUTPUTS(sqlite3_index_info *p){ int i; if( !sqlite3WhereTrace ) return; for(i=0; inConstraint; i++){ sqlite3DebugPrintf(" usage[%d]: argvIdx=%d omit=%d\n", i, p->aConstraintUsage[i].argvIndex, p->aConstraintUsage[i].omit); } sqlite3DebugPrintf(" idxNum=%d\n", p->idxNum); sqlite3DebugPrintf(" idxStr=%s\n", p->idxStr); sqlite3DebugPrintf(" orderByConsumed=%d\n", p->orderByConsumed); sqlite3DebugPrintf(" estimatedCost=%g\n", p->estimatedCost); sqlite3DebugPrintf(" estimatedRows=%lld\n", p->estimatedRows); } #else #define TRACE_IDX_INPUTS(A) #define TRACE_IDX_OUTPUTS(A) #endif #ifndef SQLITE_OMIT_AUTOMATIC_INDEX /* ** Return TRUE if the WHERE clause term pTerm is of a form where it ** could be used with an index to access pSrc, assuming an appropriate ** index existed. */ static int termCanDriveIndex( WhereTerm *pTerm, /* WHERE clause term to check */ struct SrcList_item *pSrc, /* Table we are trying to access */ Bitmask notReady /* Tables in outer loops of the join */ ){ char aff; if( pTerm->leftCursor!=pSrc->iCursor ) return 0; if( (pTerm->eOperator & (WO_EQ|WO_IS))==0 ) return 0; if( (pTerm->prereqRight & notReady)!=0 ) return 0; if( pTerm->u.leftColumn<0 ) return 0; aff = pSrc->pTab->aCol[pTerm->u.leftColumn].affinity; if( !sqlite3IndexAffinityOk(pTerm->pExpr, aff) ) return 0; testcase( pTerm->pExpr->op==TK_IS ); return 1; } #endif #ifndef SQLITE_OMIT_AUTOMATIC_INDEX /* ** Generate code to construct the Index object for an automatic index ** and to set up the WhereLevel object pLevel so that the code generator ** makes use of the automatic index. */ static void constructAutomaticIndex( Parse *pParse, /* The parsing context */ WhereClause *pWC, /* The WHERE clause */ struct SrcList_item *pSrc, /* The FROM clause term to get the next index */ Bitmask notReady, /* Mask of cursors that are not available */ WhereLevel *pLevel /* Write new index here */ ){ int nKeyCol; /* Number of columns in the constructed index */ WhereTerm *pTerm; /* A single term of the WHERE clause */ WhereTerm *pWCEnd; /* End of pWC->a[] */ Index *pIdx; /* Object describing the transient index */ Vdbe *v; /* Prepared statement under construction */ int addrInit; /* Address of the initialization bypass jump */ Table *pTable; /* The table being indexed */ int addrTop; /* Top of the index fill loop */ int regRecord; /* Register holding an index record */ int n; /* Column counter */ int i; /* Loop counter */ int mxBitCol; /* Maximum column in pSrc->colUsed */ CollSeq *pColl; /* Collating sequence to on a column */ WhereLoop *pLoop; /* The Loop object */ char *zNotUsed; /* Extra space on the end of pIdx */ Bitmask idxCols; /* Bitmap of columns used for indexing */ Bitmask extraCols; /* Bitmap of additional columns */ u8 sentWarning = 0; /* True if a warnning has been issued */ Expr *pPartial = 0; /* Partial Index Expression */ int iContinue = 0; /* Jump here to skip excluded rows */ struct SrcList_item *pTabItem; /* FROM clause term being indexed */ int addrCounter = 0; /* Address where integer counter is initialized */ int regBase; /* Array of registers where record is assembled */ /* Generate code to skip over the creation and initialization of the ** transient index on 2nd and subsequent iterations of the loop. */ v = pParse->pVdbe; assert( v!=0 ); addrInit = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v); /* Count the number of columns that will be added to the index ** and used to match WHERE clause constraints */ nKeyCol = 0; pTable = pSrc->pTab; pWCEnd = &pWC->a[pWC->nTerm]; pLoop = pLevel->pWLoop; idxCols = 0; for(pTerm=pWC->a; pTermpExpr; assert( !ExprHasProperty(pExpr, EP_FromJoin) /* prereq always non-zero */ || pExpr->iRightJoinTable!=pSrc->iCursor /* for the right-hand */ || pLoop->prereq!=0 ); /* table of a LEFT JOIN */ if( pLoop->prereq==0 && (pTerm->wtFlags & TERM_VIRTUAL)==0 && !ExprHasProperty(pExpr, EP_FromJoin) && sqlite3ExprIsTableConstant(pExpr, pSrc->iCursor) ){ pPartial = sqlite3ExprAnd(pParse->db, pPartial, sqlite3ExprDup(pParse->db, pExpr, 0)); } if( termCanDriveIndex(pTerm, pSrc, notReady) ){ int iCol = pTerm->u.leftColumn; Bitmask cMask = iCol>=BMS ? MASKBIT(BMS-1) : MASKBIT(iCol); testcase( iCol==BMS ); testcase( iCol==BMS-1 ); if( !sentWarning ){ sqlite3_log(SQLITE_WARNING_AUTOINDEX, "automatic index on %s(%s)", pTable->zName, pTable->aCol[iCol].zName); sentWarning = 1; } if( (idxCols & cMask)==0 ){ if( whereLoopResize(pParse->db, pLoop, nKeyCol+1) ){ goto end_auto_index_create; } pLoop->aLTerm[nKeyCol++] = pTerm; idxCols |= cMask; } } } assert( nKeyCol>0 ); pLoop->u.btree.nEq = pLoop->nLTerm = nKeyCol; pLoop->wsFlags = WHERE_COLUMN_EQ | WHERE_IDX_ONLY | WHERE_INDEXED | WHERE_AUTO_INDEX; /* Count the number of additional columns needed to create a ** covering index. A "covering index" is an index that contains all ** columns that are needed by the query. With a covering index, the ** original table never needs to be accessed. Automatic indices must ** be a covering index because the index will not be updated if the ** original table changes and the index and table cannot both be used ** if they go out of sync. */ extraCols = pSrc->colUsed & (~idxCols | MASKBIT(BMS-1)); mxBitCol = MIN(BMS-1,pTable->nCol); testcase( pTable->nCol==BMS-1 ); testcase( pTable->nCol==BMS-2 ); for(i=0; icolUsed & MASKBIT(BMS-1) ){ nKeyCol += pTable->nCol - BMS + 1; } /* Construct the Index object to describe this index */ pIdx = sqlite3AllocateIndexObject(pParse->db, nKeyCol+1, 0, &zNotUsed); if( pIdx==0 ) goto end_auto_index_create; pLoop->u.btree.pIndex = pIdx; pIdx->zName = "auto-index"; pIdx->pTable = pTable; n = 0; idxCols = 0; for(pTerm=pWC->a; pTermu.leftColumn; Bitmask cMask = iCol>=BMS ? MASKBIT(BMS-1) : MASKBIT(iCol); testcase( iCol==BMS-1 ); testcase( iCol==BMS ); if( (idxCols & cMask)==0 ){ Expr *pX = pTerm->pExpr; idxCols |= cMask; pIdx->aiColumn[n] = pTerm->u.leftColumn; pColl = sqlite3BinaryCompareCollSeq(pParse, pX->pLeft, pX->pRight); pIdx->azColl[n] = pColl ? pColl->zName : sqlite3StrBINARY; n++; } } } assert( (u32)n==pLoop->u.btree.nEq ); /* Add additional columns needed to make the automatic index into ** a covering index */ for(i=0; iaiColumn[n] = i; pIdx->azColl[n] = sqlite3StrBINARY; n++; } } if( pSrc->colUsed & MASKBIT(BMS-1) ){ for(i=BMS-1; inCol; i++){ pIdx->aiColumn[n] = i; pIdx->azColl[n] = sqlite3StrBINARY; n++; } } assert( n==nKeyCol ); pIdx->aiColumn[n] = XN_ROWID; pIdx->azColl[n] = sqlite3StrBINARY; /* Create the automatic index */ assert( pLevel->iIdxCur>=0 ); pLevel->iIdxCur = pParse->nTab++; sqlite3VdbeAddOp2(v, OP_OpenAutoindex, pLevel->iIdxCur, nKeyCol+1); sqlite3VdbeSetP4KeyInfo(pParse, pIdx); VdbeComment((v, "for %s", pTable->zName)); /* Fill the automatic index with content */ sqlite3ExprCachePush(pParse); pTabItem = &pWC->pWInfo->pTabList->a[pLevel->iFrom]; if( pTabItem->fg.viaCoroutine ){ int regYield = pTabItem->regReturn; addrCounter = sqlite3VdbeAddOp2(v, OP_Integer, 0, 0); sqlite3VdbeAddOp3(v, OP_InitCoroutine, regYield, 0, pTabItem->addrFillSub); addrTop = sqlite3VdbeAddOp1(v, OP_Yield, regYield); VdbeCoverage(v); VdbeComment((v, "next row of \"%s\"", pTabItem->pTab->zName)); }else{ addrTop = sqlite3VdbeAddOp1(v, OP_Rewind, pLevel->iTabCur); VdbeCoverage(v); } if( pPartial ){ iContinue = sqlite3VdbeMakeLabel(v); sqlite3ExprIfFalse(pParse, pPartial, iContinue, SQLITE_JUMPIFNULL); pLoop->wsFlags |= WHERE_PARTIALIDX; } regRecord = sqlite3GetTempReg(pParse); regBase = sqlite3GenerateIndexKey( pParse, pIdx, pLevel->iTabCur, regRecord, 0, 0, 0, 0 ); sqlite3VdbeAddOp2(v, OP_IdxInsert, pLevel->iIdxCur, regRecord); sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT); if( pPartial ) sqlite3VdbeResolveLabel(v, iContinue); if( pTabItem->fg.viaCoroutine ){ sqlite3VdbeChangeP2(v, addrCounter, regBase+n); translateColumnToCopy(v, addrTop, pLevel->iTabCur, pTabItem->regResult, 1); sqlite3VdbeGoto(v, addrTop); pTabItem->fg.viaCoroutine = 0; }else{ sqlite3VdbeAddOp2(v, OP_Next, pLevel->iTabCur, addrTop+1); VdbeCoverage(v); } sqlite3VdbeChangeP5(v, SQLITE_STMTSTATUS_AUTOINDEX); sqlite3VdbeJumpHere(v, addrTop); sqlite3ReleaseTempReg(pParse, regRecord); sqlite3ExprCachePop(pParse); /* Jump here when skipping the initialization */ sqlite3VdbeJumpHere(v, addrInit); end_auto_index_create: sqlite3ExprDelete(pParse->db, pPartial); } #endif /* SQLITE_OMIT_AUTOMATIC_INDEX */ #ifndef SQLITE_OMIT_VIRTUALTABLE /* ** Allocate and populate an sqlite3_index_info structure. It is the ** responsibility of the caller to eventually release the structure ** by passing the pointer returned by this function to sqlite3_free(). */ static sqlite3_index_info *allocateIndexInfo( Parse *pParse, WhereClause *pWC, Bitmask mUnusable, /* Ignore terms with these prereqs */ struct SrcList_item *pSrc, ExprList *pOrderBy, u16 *pmNoOmit /* Mask of terms not to omit */ ){ int i, j; int nTerm; struct sqlite3_index_constraint *pIdxCons; struct sqlite3_index_orderby *pIdxOrderBy; struct sqlite3_index_constraint_usage *pUsage; WhereTerm *pTerm; int nOrderBy; sqlite3_index_info *pIdxInfo; u16 mNoOmit = 0; /* Count the number of possible WHERE clause constraints referring ** to this virtual table */ for(i=nTerm=0, pTerm=pWC->a; inTerm; i++, pTerm++){ if( pTerm->leftCursor != pSrc->iCursor ) continue; if( pTerm->prereqRight & mUnusable ) continue; assert( IsPowerOfTwo(pTerm->eOperator & ~WO_EQUIV) ); testcase( pTerm->eOperator & WO_IN ); testcase( pTerm->eOperator & WO_ISNULL ); testcase( pTerm->eOperator & WO_IS ); testcase( pTerm->eOperator & WO_ALL ); if( (pTerm->eOperator & ~(WO_ISNULL|WO_EQUIV|WO_IS))==0 ) continue; if( pTerm->wtFlags & TERM_VNULL ) continue; assert( pTerm->u.leftColumn>=(-1) ); nTerm++; } /* If the ORDER BY clause contains only columns in the current ** virtual table then allocate space for the aOrderBy part of ** the sqlite3_index_info structure. */ nOrderBy = 0; if( pOrderBy ){ int n = pOrderBy->nExpr; for(i=0; ia[i].pExpr; if( pExpr->op!=TK_COLUMN || pExpr->iTable!=pSrc->iCursor ) break; } if( i==n){ nOrderBy = n; } } /* Allocate the sqlite3_index_info structure */ pIdxInfo = sqlite3DbMallocZero(pParse->db, sizeof(*pIdxInfo) + (sizeof(*pIdxCons) + sizeof(*pUsage))*nTerm + sizeof(*pIdxOrderBy)*nOrderBy ); if( pIdxInfo==0 ){ sqlite3ErrorMsg(pParse, "out of memory"); return 0; } /* Initialize the structure. The sqlite3_index_info structure contains ** many fields that are declared "const" to prevent xBestIndex from ** changing them. We have to do some funky casting in order to ** initialize those fields. */ pIdxCons = (struct sqlite3_index_constraint*)&pIdxInfo[1]; pIdxOrderBy = (struct sqlite3_index_orderby*)&pIdxCons[nTerm]; pUsage = (struct sqlite3_index_constraint_usage*)&pIdxOrderBy[nOrderBy]; *(int*)&pIdxInfo->nConstraint = nTerm; *(int*)&pIdxInfo->nOrderBy = nOrderBy; *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint = pIdxCons; *(struct sqlite3_index_orderby**)&pIdxInfo->aOrderBy = pIdxOrderBy; *(struct sqlite3_index_constraint_usage**)&pIdxInfo->aConstraintUsage = pUsage; for(i=j=0, pTerm=pWC->a; inTerm; i++, pTerm++){ u8 op; if( pTerm->leftCursor != pSrc->iCursor ) continue; if( pTerm->prereqRight & mUnusable ) continue; assert( IsPowerOfTwo(pTerm->eOperator & ~WO_EQUIV) ); testcase( pTerm->eOperator & WO_IN ); testcase( pTerm->eOperator & WO_IS ); testcase( pTerm->eOperator & WO_ISNULL ); testcase( pTerm->eOperator & WO_ALL ); if( (pTerm->eOperator & ~(WO_ISNULL|WO_EQUIV|WO_IS))==0 ) continue; if( pTerm->wtFlags & TERM_VNULL ) continue; assert( pTerm->u.leftColumn>=(-1) ); pIdxCons[j].iColumn = pTerm->u.leftColumn; pIdxCons[j].iTermOffset = i; op = (u8)pTerm->eOperator & WO_ALL; if( op==WO_IN ) op = WO_EQ; if( op==WO_MATCH ){ op = pTerm->eMatchOp; } pIdxCons[j].op = op; /* The direct assignment in the previous line is possible only because ** the WO_ and SQLITE_INDEX_CONSTRAINT_ codes are identical. The ** following asserts verify this fact. */ assert( WO_EQ==SQLITE_INDEX_CONSTRAINT_EQ ); assert( WO_LT==SQLITE_INDEX_CONSTRAINT_LT ); assert( WO_LE==SQLITE_INDEX_CONSTRAINT_LE ); assert( WO_GT==SQLITE_INDEX_CONSTRAINT_GT ); assert( WO_GE==SQLITE_INDEX_CONSTRAINT_GE ); assert( WO_MATCH==SQLITE_INDEX_CONSTRAINT_MATCH ); assert( pTerm->eOperator & (WO_IN|WO_EQ|WO_LT|WO_LE|WO_GT|WO_GE|WO_MATCH) ); if( op & (WO_LT|WO_LE|WO_GT|WO_GE) && sqlite3ExprIsVector(pTerm->pExpr->pRight) ){ if( i<16 ) mNoOmit |= (1 << i); if( op==WO_LT ) pIdxCons[j].op = WO_LE; if( op==WO_GT ) pIdxCons[j].op = WO_GE; } j++; } for(i=0; ia[i].pExpr; pIdxOrderBy[i].iColumn = pExpr->iColumn; pIdxOrderBy[i].desc = pOrderBy->a[i].sortOrder; } *pmNoOmit = mNoOmit; return pIdxInfo; } /* ** The table object reference passed as the second argument to this function ** must represent a virtual table. This function invokes the xBestIndex() ** method of the virtual table with the sqlite3_index_info object that ** comes in as the 3rd argument to this function. ** ** If an error occurs, pParse is populated with an error message and a ** non-zero value is returned. Otherwise, 0 is returned and the output ** part of the sqlite3_index_info structure is left populated. ** ** Whether or not an error is returned, it is the responsibility of the ** caller to eventually free p->idxStr if p->needToFreeIdxStr indicates ** that this is required. */ static int vtabBestIndex(Parse *pParse, Table *pTab, sqlite3_index_info *p){ sqlite3_vtab *pVtab = sqlite3GetVTable(pParse->db, pTab)->pVtab; int rc; TRACE_IDX_INPUTS(p); rc = pVtab->pModule->xBestIndex(pVtab, p); TRACE_IDX_OUTPUTS(p); if( rc!=SQLITE_OK ){ if( rc==SQLITE_NOMEM ){ sqlite3OomFault(pParse->db); }else if( !pVtab->zErrMsg ){ sqlite3ErrorMsg(pParse, "%s", sqlite3ErrStr(rc)); }else{ sqlite3ErrorMsg(pParse, "%s", pVtab->zErrMsg); } } sqlite3_free(pVtab->zErrMsg); pVtab->zErrMsg = 0; #if 0 /* This error is now caught by the caller. ** Search for "xBestIndex malfunction" below */ for(i=0; inConstraint; i++){ if( !p->aConstraint[i].usable && p->aConstraintUsage[i].argvIndex>0 ){ sqlite3ErrorMsg(pParse, "table %s: xBestIndex returned an invalid plan", pTab->zName); } } #endif return pParse->nErr; } #endif /* !defined(SQLITE_OMIT_VIRTUALTABLE) */ #ifdef SQLITE_ENABLE_STAT3_OR_STAT4 /* ** Estimate the location of a particular key among all keys in an ** index. Store the results in aStat as follows: ** ** aStat[0] Est. number of rows less than pRec ** aStat[1] Est. number of rows equal to pRec ** ** Return the index of the sample that is the smallest sample that ** is greater than or equal to pRec. Note that this index is not an index ** into the aSample[] array - it is an index into a virtual set of samples ** based on the contents of aSample[] and the number of fields in record ** pRec. */ static int whereKeyStats( Parse *pParse, /* Database connection */ Index *pIdx, /* Index to consider domain of */ UnpackedRecord *pRec, /* Vector of values to consider */ int roundUp, /* Round up if true. Round down if false */ tRowcnt *aStat /* OUT: stats written here */ ){ IndexSample *aSample = pIdx->aSample; int iCol; /* Index of required stats in anEq[] etc. */ int i; /* Index of first sample >= pRec */ int iSample; /* Smallest sample larger than or equal to pRec */ int iMin = 0; /* Smallest sample not yet tested */ int iTest; /* Next sample to test */ int res; /* Result of comparison operation */ int nField; /* Number of fields in pRec */ tRowcnt iLower = 0; /* anLt[] + anEq[] of largest sample pRec is > */ #ifndef SQLITE_DEBUG UNUSED_PARAMETER( pParse ); #endif assert( pRec!=0 ); assert( pIdx->nSample>0 ); assert( pRec->nField>0 && pRec->nField<=pIdx->nSampleCol ); /* Do a binary search to find the first sample greater than or equal ** to pRec. If pRec contains a single field, the set of samples to search ** is simply the aSample[] array. If the samples in aSample[] contain more ** than one fields, all fields following the first are ignored. ** ** If pRec contains N fields, where N is more than one, then as well as the ** samples in aSample[] (truncated to N fields), the search also has to ** consider prefixes of those samples. For example, if the set of samples ** in aSample is: ** ** aSample[0] = (a, 5) ** aSample[1] = (a, 10) ** aSample[2] = (b, 5) ** aSample[3] = (c, 100) ** aSample[4] = (c, 105) ** ** Then the search space should ideally be the samples above and the ** unique prefixes [a], [b] and [c]. But since that is hard to organize, ** the code actually searches this set: ** ** 0: (a) ** 1: (a, 5) ** 2: (a, 10) ** 3: (a, 10) ** 4: (b) ** 5: (b, 5) ** 6: (c) ** 7: (c, 100) ** 8: (c, 105) ** 9: (c, 105) ** ** For each sample in the aSample[] array, N samples are present in the ** effective sample array. In the above, samples 0 and 1 are based on ** sample aSample[0]. Samples 2 and 3 on aSample[1] etc. ** ** Often, sample i of each block of N effective samples has (i+1) fields. ** Except, each sample may be extended to ensure that it is greater than or ** equal to the previous sample in the array. For example, in the above, ** sample 2 is the first sample of a block of N samples, so at first it ** appears that it should be 1 field in size. However, that would make it ** smaller than sample 1, so the binary search would not work. As a result, ** it is extended to two fields. The duplicates that this creates do not ** cause any problems. */ nField = pRec->nField; iCol = 0; iSample = pIdx->nSample * nField; do{ int iSamp; /* Index in aSample[] of test sample */ int n; /* Number of fields in test sample */ iTest = (iMin+iSample)/2; iSamp = iTest / nField; if( iSamp>0 ){ /* The proposed effective sample is a prefix of sample aSample[iSamp]. ** Specifically, the shortest prefix of at least (1 + iTest%nField) ** fields that is greater than the previous effective sample. */ for(n=(iTest % nField) + 1; nnField = n; res = sqlite3VdbeRecordCompare(aSample[iSamp].n, aSample[iSamp].p, pRec); if( res<0 ){ iLower = aSample[iSamp].anLt[n-1] + aSample[iSamp].anEq[n-1]; iMin = iTest+1; }else if( res==0 && ndb->mallocFailed==0 ){ if( res==0 ){ /* If (res==0) is true, then pRec must be equal to sample i. */ assert( inSample ); assert( iCol==nField-1 ); pRec->nField = nField; assert( 0==sqlite3VdbeRecordCompare(aSample[i].n, aSample[i].p, pRec) || pParse->db->mallocFailed ); }else{ /* Unless i==pIdx->nSample, indicating that pRec is larger than ** all samples in the aSample[] array, pRec must be smaller than the ** (iCol+1) field prefix of sample i. */ assert( i<=pIdx->nSample && i>=0 ); pRec->nField = iCol+1; assert( i==pIdx->nSample || sqlite3VdbeRecordCompare(aSample[i].n, aSample[i].p, pRec)>0 || pParse->db->mallocFailed ); /* if i==0 and iCol==0, then record pRec is smaller than all samples ** in the aSample[] array. Otherwise, if (iCol>0) then pRec must ** be greater than or equal to the (iCol) field prefix of sample i. ** If (i>0), then pRec must also be greater than sample (i-1). */ if( iCol>0 ){ pRec->nField = iCol; assert( sqlite3VdbeRecordCompare(aSample[i].n, aSample[i].p, pRec)<=0 || pParse->db->mallocFailed ); } if( i>0 ){ pRec->nField = nField; assert( sqlite3VdbeRecordCompare(aSample[i-1].n, aSample[i-1].p, pRec)<0 || pParse->db->mallocFailed ); } } } #endif /* ifdef SQLITE_DEBUG */ if( res==0 ){ /* Record pRec is equal to sample i */ assert( iCol==nField-1 ); aStat[0] = aSample[i].anLt[iCol]; aStat[1] = aSample[i].anEq[iCol]; }else{ /* At this point, the (iCol+1) field prefix of aSample[i] is the first ** sample that is greater than pRec. Or, if i==pIdx->nSample then pRec ** is larger than all samples in the array. */ tRowcnt iUpper, iGap; if( i>=pIdx->nSample ){ iUpper = sqlite3LogEstToInt(pIdx->aiRowLogEst[0]); }else{ iUpper = aSample[i].anLt[iCol]; } if( iLower>=iUpper ){ iGap = 0; }else{ iGap = iUpper - iLower; } if( roundUp ){ iGap = (iGap*2)/3; }else{ iGap = iGap/3; } aStat[0] = iLower + iGap; aStat[1] = pIdx->aAvgEq[iCol]; } /* Restore the pRec->nField value before returning. */ pRec->nField = nField; return i; } #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */ /* ** If it is not NULL, pTerm is a term that provides an upper or lower ** bound on a range scan. Without considering pTerm, it is estimated ** that the scan will visit nNew rows. This function returns the number ** estimated to be visited after taking pTerm into account. ** ** If the user explicitly specified a likelihood() value for this term, ** then the return value is the likelihood multiplied by the number of ** input rows. Otherwise, this function assumes that an "IS NOT NULL" term ** has a likelihood of 0.50, and any other term a likelihood of 0.25. */ static LogEst whereRangeAdjust(WhereTerm *pTerm, LogEst nNew){ LogEst nRet = nNew; if( pTerm ){ if( pTerm->truthProb<=0 ){ nRet += pTerm->truthProb; }else if( (pTerm->wtFlags & TERM_VNULL)==0 ){ nRet -= 20; assert( 20==sqlite3LogEst(4) ); } } return nRet; } #ifdef SQLITE_ENABLE_STAT3_OR_STAT4 /* ** Return the affinity for a single column of an index. */ SQLITE_PRIVATE char sqlite3IndexColumnAffinity(sqlite3 *db, Index *pIdx, int iCol){ assert( iCol>=0 && iColnColumn ); if( !pIdx->zColAff ){ if( sqlite3IndexAffinityStr(db, pIdx)==0 ) return SQLITE_AFF_BLOB; } return pIdx->zColAff[iCol]; } #endif #ifdef SQLITE_ENABLE_STAT3_OR_STAT4 /* ** This function is called to estimate the number of rows visited by a ** range-scan on a skip-scan index. For example: ** ** CREATE INDEX i1 ON t1(a, b, c); ** SELECT * FROM t1 WHERE a=? AND c BETWEEN ? AND ?; ** ** Value pLoop->nOut is currently set to the estimated number of rows ** visited for scanning (a=? AND b=?). This function reduces that estimate ** by some factor to account for the (c BETWEEN ? AND ?) expression based ** on the stat4 data for the index. this scan will be peformed multiple ** times (once for each (a,b) combination that matches a=?) is dealt with ** by the caller. ** ** It does this by scanning through all stat4 samples, comparing values ** extracted from pLower and pUpper with the corresponding column in each ** sample. If L and U are the number of samples found to be less than or ** equal to the values extracted from pLower and pUpper respectively, and ** N is the total number of samples, the pLoop->nOut value is adjusted ** as follows: ** ** nOut = nOut * ( min(U - L, 1) / N ) ** ** If pLower is NULL, or a value cannot be extracted from the term, L is ** set to zero. If pUpper is NULL, or a value cannot be extracted from it, ** U is set to N. ** ** Normally, this function sets *pbDone to 1 before returning. However, ** if no value can be extracted from either pLower or pUpper (and so the ** estimate of the number of rows delivered remains unchanged), *pbDone ** is left as is. ** ** If an error occurs, an SQLite error code is returned. Otherwise, ** SQLITE_OK. */ static int whereRangeSkipScanEst( Parse *pParse, /* Parsing & code generating context */ WhereTerm *pLower, /* Lower bound on the range. ex: "x>123" Might be NULL */ WhereTerm *pUpper, /* Upper bound on the range. ex: "x<455" Might be NULL */ WhereLoop *pLoop, /* Update the .nOut value of this loop */ int *pbDone /* Set to true if at least one expr. value extracted */ ){ Index *p = pLoop->u.btree.pIndex; int nEq = pLoop->u.btree.nEq; sqlite3 *db = pParse->db; int nLower = -1; int nUpper = p->nSample+1; int rc = SQLITE_OK; u8 aff = sqlite3IndexColumnAffinity(db, p, nEq); CollSeq *pColl; sqlite3_value *p1 = 0; /* Value extracted from pLower */ sqlite3_value *p2 = 0; /* Value extracted from pUpper */ sqlite3_value *pVal = 0; /* Value extracted from record */ pColl = sqlite3LocateCollSeq(pParse, p->azColl[nEq]); if( pLower ){ rc = sqlite3Stat4ValueFromExpr(pParse, pLower->pExpr->pRight, aff, &p1); nLower = 0; } if( pUpper && rc==SQLITE_OK ){ rc = sqlite3Stat4ValueFromExpr(pParse, pUpper->pExpr->pRight, aff, &p2); nUpper = p2 ? 0 : p->nSample; } if( p1 || p2 ){ int i; int nDiff; for(i=0; rc==SQLITE_OK && inSample; i++){ rc = sqlite3Stat4Column(db, p->aSample[i].p, p->aSample[i].n, nEq, &pVal); if( rc==SQLITE_OK && p1 ){ int res = sqlite3MemCompare(p1, pVal, pColl); if( res>=0 ) nLower++; } if( rc==SQLITE_OK && p2 ){ int res = sqlite3MemCompare(p2, pVal, pColl); if( res>=0 ) nUpper++; } } nDiff = (nUpper - nLower); if( nDiff<=0 ) nDiff = 1; /* If there is both an upper and lower bound specified, and the ** comparisons indicate that they are close together, use the fallback ** method (assume that the scan visits 1/64 of the rows) for estimating ** the number of rows visited. Otherwise, estimate the number of rows ** using the method described in the header comment for this function. */ if( nDiff!=1 || pUpper==0 || pLower==0 ){ int nAdjust = (sqlite3LogEst(p->nSample) - sqlite3LogEst(nDiff)); pLoop->nOut -= nAdjust; *pbDone = 1; WHERETRACE(0x10, ("range skip-scan regions: %u..%u adjust=%d est=%d\n", nLower, nUpper, nAdjust*-1, pLoop->nOut)); } }else{ assert( *pbDone==0 ); } sqlite3ValueFree(p1); sqlite3ValueFree(p2); sqlite3ValueFree(pVal); return rc; } #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */ /* ** This function is used to estimate the number of rows that will be visited ** by scanning an index for a range of values. The range may have an upper ** bound, a lower bound, or both. The WHERE clause terms that set the upper ** and lower bounds are represented by pLower and pUpper respectively. For ** example, assuming that index p is on t1(a): ** ** ... FROM t1 WHERE a > ? AND a < ? ... ** |_____| |_____| ** | | ** pLower pUpper ** ** If either of the upper or lower bound is not present, then NULL is passed in ** place of the corresponding WhereTerm. ** ** The value in (pBuilder->pNew->u.btree.nEq) is the number of the index ** column subject to the range constraint. Or, equivalently, the number of ** equality constraints optimized by the proposed index scan. For example, ** assuming index p is on t1(a, b), and the SQL query is: ** ** ... FROM t1 WHERE a = ? AND b > ? AND b < ? ... ** ** then nEq is set to 1 (as the range restricted column, b, is the second ** left-most column of the index). Or, if the query is: ** ** ... FROM t1 WHERE a > ? AND a < ? ... ** ** then nEq is set to 0. ** ** When this function is called, *pnOut is set to the sqlite3LogEst() of the ** number of rows that the index scan is expected to visit without ** considering the range constraints. If nEq is 0, then *pnOut is the number of ** rows in the index. Assuming no error occurs, *pnOut is adjusted (reduced) ** to account for the range constraints pLower and pUpper. ** ** In the absence of sqlite_stat4 ANALYZE data, or if such data cannot be ** used, a single range inequality reduces the search space by a factor of 4. ** and a pair of constraints (x>? AND x123" Might be NULL */ WhereTerm *pUpper, /* Upper bound on the range. ex: "x<455" Might be NULL */ WhereLoop *pLoop /* Modify the .nOut and maybe .rRun fields */ ){ int rc = SQLITE_OK; int nOut = pLoop->nOut; LogEst nNew; #ifdef SQLITE_ENABLE_STAT3_OR_STAT4 Index *p = pLoop->u.btree.pIndex; int nEq = pLoop->u.btree.nEq; if( p->nSample>0 && nEqnSampleCol ){ if( nEq==pBuilder->nRecValid ){ UnpackedRecord *pRec = pBuilder->pRec; tRowcnt a[2]; int nBtm = pLoop->u.btree.nBtm; int nTop = pLoop->u.btree.nTop; /* Variable iLower will be set to the estimate of the number of rows in ** the index that are less than the lower bound of the range query. The ** lower bound being the concatenation of $P and $L, where $P is the ** key-prefix formed by the nEq values matched against the nEq left-most ** columns of the index, and $L is the value in pLower. ** ** Or, if pLower is NULL or $L cannot be extracted from it (because it ** is not a simple variable or literal value), the lower bound of the ** range is $P. Due to a quirk in the way whereKeyStats() works, even ** if $L is available, whereKeyStats() is called for both ($P) and ** ($P:$L) and the larger of the two returned values is used. ** ** Similarly, iUpper is to be set to the estimate of the number of rows ** less than the upper bound of the range query. Where the upper bound ** is either ($P) or ($P:$U). Again, even if $U is available, both values ** of iUpper are requested of whereKeyStats() and the smaller used. ** ** The number of rows between the two bounds is then just iUpper-iLower. */ tRowcnt iLower; /* Rows less than the lower bound */ tRowcnt iUpper; /* Rows less than the upper bound */ int iLwrIdx = -2; /* aSample[] for the lower bound */ int iUprIdx = -1; /* aSample[] for the upper bound */ if( pRec ){ testcase( pRec->nField!=pBuilder->nRecValid ); pRec->nField = pBuilder->nRecValid; } /* Determine iLower and iUpper using ($P) only. */ if( nEq==0 ){ iLower = 0; iUpper = p->nRowEst0; }else{ /* Note: this call could be optimized away - since the same values must ** have been requested when testing key $P in whereEqualScanEst(). */ whereKeyStats(pParse, p, pRec, 0, a); iLower = a[0]; iUpper = a[0] + a[1]; } assert( pLower==0 || (pLower->eOperator & (WO_GT|WO_GE))!=0 ); assert( pUpper==0 || (pUpper->eOperator & (WO_LT|WO_LE))!=0 ); assert( p->aSortOrder!=0 ); if( p->aSortOrder[nEq] ){ /* The roles of pLower and pUpper are swapped for a DESC index */ SWAP(WhereTerm*, pLower, pUpper); SWAP(int, nBtm, nTop); } /* If possible, improve on the iLower estimate using ($P:$L). */ if( pLower ){ int n; /* Values extracted from pExpr */ Expr *pExpr = pLower->pExpr->pRight; rc = sqlite3Stat4ProbeSetValue(pParse, p, &pRec, pExpr, nBtm, nEq, &n); if( rc==SQLITE_OK && n ){ tRowcnt iNew; u16 mask = WO_GT|WO_LE; if( sqlite3ExprVectorSize(pExpr)>n ) mask = (WO_LE|WO_LT); iLwrIdx = whereKeyStats(pParse, p, pRec, 0, a); iNew = a[0] + ((pLower->eOperator & mask) ? a[1] : 0); if( iNew>iLower ) iLower = iNew; nOut--; pLower = 0; } } /* If possible, improve on the iUpper estimate using ($P:$U). */ if( pUpper ){ int n; /* Values extracted from pExpr */ Expr *pExpr = pUpper->pExpr->pRight; rc = sqlite3Stat4ProbeSetValue(pParse, p, &pRec, pExpr, nTop, nEq, &n); if( rc==SQLITE_OK && n ){ tRowcnt iNew; u16 mask = WO_GT|WO_LE; if( sqlite3ExprVectorSize(pExpr)>n ) mask = (WO_LE|WO_LT); iUprIdx = whereKeyStats(pParse, p, pRec, 1, a); iNew = a[0] + ((pUpper->eOperator & mask) ? a[1] : 0); if( iNewpRec = pRec; if( rc==SQLITE_OK ){ if( iUpper>iLower ){ nNew = sqlite3LogEst(iUpper - iLower); /* TUNING: If both iUpper and iLower are derived from the same ** sample, then assume they are 4x more selective. This brings ** the estimated selectivity more in line with what it would be ** if estimated without the use of STAT3/4 tables. */ if( iLwrIdx==iUprIdx ) nNew -= 20; assert( 20==sqlite3LogEst(4) ); }else{ nNew = 10; assert( 10==sqlite3LogEst(2) ); } if( nNewwtFlags & TERM_VNULL)==0 ); nNew = whereRangeAdjust(pLower, nOut); nNew = whereRangeAdjust(pUpper, nNew); /* TUNING: If there is both an upper and lower limit and neither limit ** has an application-defined likelihood(), assume the range is ** reduced by an additional 75%. This means that, by default, an open-ended ** range query (e.g. col > ?) is assumed to match 1/4 of the rows in the ** index. While a closed range (e.g. col BETWEEN ? AND ?) is estimated to ** match 1/64 of the index. */ if( pLower && pLower->truthProb>0 && pUpper && pUpper->truthProb>0 ){ nNew -= 20; } nOut -= (pLower!=0) + (pUpper!=0); if( nNew<10 ) nNew = 10; if( nNewnOut>nOut ){ WHERETRACE(0x10,("Range scan lowers nOut from %d to %d\n", pLoop->nOut, nOut)); } #endif pLoop->nOut = (LogEst)nOut; return rc; } #ifdef SQLITE_ENABLE_STAT3_OR_STAT4 /* ** Estimate the number of rows that will be returned based on ** an equality constraint x=VALUE and where that VALUE occurs in ** the histogram data. This only works when x is the left-most ** column of an index and sqlite_stat3 histogram data is available ** for that index. When pExpr==NULL that means the constraint is ** "x IS NULL" instead of "x=VALUE". ** ** Write the estimated row count into *pnRow and return SQLITE_OK. ** If unable to make an estimate, leave *pnRow unchanged and return ** non-zero. ** ** This routine can fail if it is unable to load a collating sequence ** required for string comparison, or if unable to allocate memory ** for a UTF conversion required for comparison. The error is stored ** in the pParse structure. */ static int whereEqualScanEst( Parse *pParse, /* Parsing & code generating context */ WhereLoopBuilder *pBuilder, Expr *pExpr, /* Expression for VALUE in the x=VALUE constraint */ tRowcnt *pnRow /* Write the revised row estimate here */ ){ Index *p = pBuilder->pNew->u.btree.pIndex; int nEq = pBuilder->pNew->u.btree.nEq; UnpackedRecord *pRec = pBuilder->pRec; int rc; /* Subfunction return code */ tRowcnt a[2]; /* Statistics */ int bOk; assert( nEq>=1 ); assert( nEq<=p->nColumn ); assert( p->aSample!=0 ); assert( p->nSample>0 ); assert( pBuilder->nRecValidnRecValid<(nEq-1) ){ return SQLITE_NOTFOUND; } /* This is an optimization only. The call to sqlite3Stat4ProbeSetValue() ** below would return the same value. */ if( nEq>=p->nColumn ){ *pnRow = 1; return SQLITE_OK; } rc = sqlite3Stat4ProbeSetValue(pParse, p, &pRec, pExpr, 1, nEq-1, &bOk); pBuilder->pRec = pRec; if( rc!=SQLITE_OK ) return rc; if( bOk==0 ) return SQLITE_NOTFOUND; pBuilder->nRecValid = nEq; whereKeyStats(pParse, p, pRec, 0, a); WHERETRACE(0x10,("equality scan regions %s(%d): %d\n", p->zName, nEq-1, (int)a[1])); *pnRow = a[1]; return rc; } #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */ #ifdef SQLITE_ENABLE_STAT3_OR_STAT4 /* ** Estimate the number of rows that will be returned based on ** an IN constraint where the right-hand side of the IN operator ** is a list of values. Example: ** ** WHERE x IN (1,2,3,4) ** ** Write the estimated row count into *pnRow and return SQLITE_OK. ** If unable to make an estimate, leave *pnRow unchanged and return ** non-zero. ** ** This routine can fail if it is unable to load a collating sequence ** required for string comparison, or if unable to allocate memory ** for a UTF conversion required for comparison. The error is stored ** in the pParse structure. */ static int whereInScanEst( Parse *pParse, /* Parsing & code generating context */ WhereLoopBuilder *pBuilder, ExprList *pList, /* The value list on the RHS of "x IN (v1,v2,v3,...)" */ tRowcnt *pnRow /* Write the revised row estimate here */ ){ Index *p = pBuilder->pNew->u.btree.pIndex; i64 nRow0 = sqlite3LogEstToInt(p->aiRowLogEst[0]); int nRecValid = pBuilder->nRecValid; int rc = SQLITE_OK; /* Subfunction return code */ tRowcnt nEst; /* Number of rows for a single term */ tRowcnt nRowEst = 0; /* New estimate of the number of rows */ int i; /* Loop counter */ assert( p->aSample!=0 ); for(i=0; rc==SQLITE_OK && inExpr; i++){ nEst = nRow0; rc = whereEqualScanEst(pParse, pBuilder, pList->a[i].pExpr, &nEst); nRowEst += nEst; pBuilder->nRecValid = nRecValid; } if( rc==SQLITE_OK ){ if( nRowEst > nRow0 ) nRowEst = nRow0; *pnRow = nRowEst; WHERETRACE(0x10,("IN row estimate: est=%d\n", nRowEst)); } assert( pBuilder->nRecValid==nRecValid ); return rc; } #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */ #ifdef WHERETRACE_ENABLED /* ** Print the content of a WhereTerm object */ static void whereTermPrint(WhereTerm *pTerm, int iTerm){ if( pTerm==0 ){ sqlite3DebugPrintf("TERM-%-3d NULL\n", iTerm); }else{ char zType[4]; char zLeft[50]; memcpy(zType, "...", 4); if( pTerm->wtFlags & TERM_VIRTUAL ) zType[0] = 'V'; if( pTerm->eOperator & WO_EQUIV ) zType[1] = 'E'; if( ExprHasProperty(pTerm->pExpr, EP_FromJoin) ) zType[2] = 'L'; if( pTerm->eOperator & WO_SINGLE ){ sqlite3_snprintf(sizeof(zLeft),zLeft,"left={%d:%d}", pTerm->leftCursor, pTerm->u.leftColumn); }else if( (pTerm->eOperator & WO_OR)!=0 && pTerm->u.pOrInfo!=0 ){ sqlite3_snprintf(sizeof(zLeft),zLeft,"indexable=0x%lld", pTerm->u.pOrInfo->indexable); }else{ sqlite3_snprintf(sizeof(zLeft),zLeft,"left=%d", pTerm->leftCursor); } sqlite3DebugPrintf( "TERM-%-3d %p %s %-12s prob=%-3d op=0x%03x wtFlags=0x%04x", iTerm, pTerm, zType, zLeft, pTerm->truthProb, pTerm->eOperator, pTerm->wtFlags); if( pTerm->iField ){ sqlite3DebugPrintf(" iField=%d\n", pTerm->iField); }else{ sqlite3DebugPrintf("\n"); } sqlite3TreeViewExpr(0, pTerm->pExpr, 0); } } #endif #ifdef WHERETRACE_ENABLED /* ** Show the complete content of a WhereClause */ SQLITE_PRIVATE void sqlite3WhereClausePrint(WhereClause *pWC){ int i; for(i=0; inTerm; i++){ whereTermPrint(&pWC->a[i], i); } } #endif #ifdef WHERETRACE_ENABLED /* ** Print a WhereLoop object for debugging purposes */ static void whereLoopPrint(WhereLoop *p, WhereClause *pWC){ WhereInfo *pWInfo = pWC->pWInfo; int nb = 1+(pWInfo->pTabList->nSrc+3)/4; struct SrcList_item *pItem = pWInfo->pTabList->a + p->iTab; Table *pTab = pItem->pTab; Bitmask mAll = (((Bitmask)1)<<(nb*4)) - 1; sqlite3DebugPrintf("%c%2d.%0*llx.%0*llx", p->cId, p->iTab, nb, p->maskSelf, nb, p->prereq & mAll); sqlite3DebugPrintf(" %12s", pItem->zAlias ? pItem->zAlias : pTab->zName); if( (p->wsFlags & WHERE_VIRTUALTABLE)==0 ){ const char *zName; if( p->u.btree.pIndex && (zName = p->u.btree.pIndex->zName)!=0 ){ if( strncmp(zName, "sqlite_autoindex_", 17)==0 ){ int i = sqlite3Strlen30(zName) - 1; while( zName[i]!='_' ) i--; zName += i; } sqlite3DebugPrintf(".%-16s %2d", zName, p->u.btree.nEq); }else{ sqlite3DebugPrintf("%20s",""); } }else{ char *z; if( p->u.vtab.idxStr ){ z = sqlite3_mprintf("(%d,\"%s\",%x)", p->u.vtab.idxNum, p->u.vtab.idxStr, p->u.vtab.omitMask); }else{ z = sqlite3_mprintf("(%d,%x)", p->u.vtab.idxNum, p->u.vtab.omitMask); } sqlite3DebugPrintf(" %-19s", z); sqlite3_free(z); } if( p->wsFlags & WHERE_SKIPSCAN ){ sqlite3DebugPrintf(" f %05x %d-%d", p->wsFlags, p->nLTerm,p->nSkip); }else{ sqlite3DebugPrintf(" f %05x N %d", p->wsFlags, p->nLTerm); } sqlite3DebugPrintf(" cost %d,%d,%d\n", p->rSetup, p->rRun, p->nOut); if( p->nLTerm && (sqlite3WhereTrace & 0x100)!=0 ){ int i; for(i=0; inLTerm; i++){ whereTermPrint(p->aLTerm[i], i); } } } #endif /* ** Convert bulk memory into a valid WhereLoop that can be passed ** to whereLoopClear harmlessly. */ static void whereLoopInit(WhereLoop *p){ p->aLTerm = p->aLTermSpace; p->nLTerm = 0; p->nLSlot = ArraySize(p->aLTermSpace); p->wsFlags = 0; } /* ** Clear the WhereLoop.u union. Leave WhereLoop.pLTerm intact. */ static void whereLoopClearUnion(sqlite3 *db, WhereLoop *p){ if( p->wsFlags & (WHERE_VIRTUALTABLE|WHERE_AUTO_INDEX) ){ if( (p->wsFlags & WHERE_VIRTUALTABLE)!=0 && p->u.vtab.needFree ){ sqlite3_free(p->u.vtab.idxStr); p->u.vtab.needFree = 0; p->u.vtab.idxStr = 0; }else if( (p->wsFlags & WHERE_AUTO_INDEX)!=0 && p->u.btree.pIndex!=0 ){ sqlite3DbFree(db, p->u.btree.pIndex->zColAff); sqlite3DbFree(db, p->u.btree.pIndex); p->u.btree.pIndex = 0; } } } /* ** Deallocate internal memory used by a WhereLoop object */ static void whereLoopClear(sqlite3 *db, WhereLoop *p){ if( p->aLTerm!=p->aLTermSpace ) sqlite3DbFree(db, p->aLTerm); whereLoopClearUnion(db, p); whereLoopInit(p); } /* ** Increase the memory allocation for pLoop->aLTerm[] to be at least n. */ static int whereLoopResize(sqlite3 *db, WhereLoop *p, int n){ WhereTerm **paNew; if( p->nLSlot>=n ) return SQLITE_OK; n = (n+7)&~7; paNew = sqlite3DbMallocRawNN(db, sizeof(p->aLTerm[0])*n); if( paNew==0 ) return SQLITE_NOMEM_BKPT; memcpy(paNew, p->aLTerm, sizeof(p->aLTerm[0])*p->nLSlot); if( p->aLTerm!=p->aLTermSpace ) sqlite3DbFree(db, p->aLTerm); p->aLTerm = paNew; p->nLSlot = n; return SQLITE_OK; } /* ** Transfer content from the second pLoop into the first. */ static int whereLoopXfer(sqlite3 *db, WhereLoop *pTo, WhereLoop *pFrom){ whereLoopClearUnion(db, pTo); if( whereLoopResize(db, pTo, pFrom->nLTerm) ){ memset(&pTo->u, 0, sizeof(pTo->u)); return SQLITE_NOMEM_BKPT; } memcpy(pTo, pFrom, WHERE_LOOP_XFER_SZ); memcpy(pTo->aLTerm, pFrom->aLTerm, pTo->nLTerm*sizeof(pTo->aLTerm[0])); if( pFrom->wsFlags & WHERE_VIRTUALTABLE ){ pFrom->u.vtab.needFree = 0; }else if( (pFrom->wsFlags & WHERE_AUTO_INDEX)!=0 ){ pFrom->u.btree.pIndex = 0; } return SQLITE_OK; } /* ** Delete a WhereLoop object */ static void whereLoopDelete(sqlite3 *db, WhereLoop *p){ whereLoopClear(db, p); sqlite3DbFree(db, p); } /* ** Free a WhereInfo structure */ static void whereInfoFree(sqlite3 *db, WhereInfo *pWInfo){ if( ALWAYS(pWInfo) ){ int i; for(i=0; inLevel; i++){ WhereLevel *pLevel = &pWInfo->a[i]; if( pLevel->pWLoop && (pLevel->pWLoop->wsFlags & WHERE_IN_ABLE) ){ sqlite3DbFree(db, pLevel->u.in.aInLoop); } } sqlite3WhereClauseClear(&pWInfo->sWC); while( pWInfo->pLoops ){ WhereLoop *p = pWInfo->pLoops; pWInfo->pLoops = p->pNextLoop; whereLoopDelete(db, p); } sqlite3DbFree(db, pWInfo); } } /* ** Return TRUE if all of the following are true: ** ** (1) X has the same or lower cost that Y ** (2) X is a proper subset of Y ** (3) X skips at least as many columns as Y ** ** By "proper subset" we mean that X uses fewer WHERE clause terms ** than Y and that every WHERE clause term used by X is also used ** by Y. ** ** If X is a proper subset of Y then Y is a better choice and ought ** to have a lower cost. This routine returns TRUE when that cost ** relationship is inverted and needs to be adjusted. The third rule ** was added because if X uses skip-scan less than Y it still might ** deserve a lower cost even if it is a proper subset of Y. */ static int whereLoopCheaperProperSubset( const WhereLoop *pX, /* First WhereLoop to compare */ const WhereLoop *pY /* Compare against this WhereLoop */ ){ int i, j; if( pX->nLTerm-pX->nSkip >= pY->nLTerm-pY->nSkip ){ return 0; /* X is not a subset of Y */ } if( pY->nSkip > pX->nSkip ) return 0; if( pX->rRun >= pY->rRun ){ if( pX->rRun > pY->rRun ) return 0; /* X costs more than Y */ if( pX->nOut > pY->nOut ) return 0; /* X costs more than Y */ } for(i=pX->nLTerm-1; i>=0; i--){ if( pX->aLTerm[i]==0 ) continue; for(j=pY->nLTerm-1; j>=0; j--){ if( pY->aLTerm[j]==pX->aLTerm[i] ) break; } if( j<0 ) return 0; /* X not a subset of Y since term X[i] not used by Y */ } return 1; /* All conditions meet */ } /* ** Try to adjust the cost of WhereLoop pTemplate upwards or downwards so ** that: ** ** (1) pTemplate costs less than any other WhereLoops that are a proper ** subset of pTemplate ** ** (2) pTemplate costs more than any other WhereLoops for which pTemplate ** is a proper subset. ** ** To say "WhereLoop X is a proper subset of Y" means that X uses fewer ** WHERE clause terms than Y and that every WHERE clause term used by X is ** also used by Y. */ static void whereLoopAdjustCost(const WhereLoop *p, WhereLoop *pTemplate){ if( (pTemplate->wsFlags & WHERE_INDEXED)==0 ) return; for(; p; p=p->pNextLoop){ if( p->iTab!=pTemplate->iTab ) continue; if( (p->wsFlags & WHERE_INDEXED)==0 ) continue; if( whereLoopCheaperProperSubset(p, pTemplate) ){ /* Adjust pTemplate cost downward so that it is cheaper than its ** subset p. */ WHERETRACE(0x80,("subset cost adjustment %d,%d to %d,%d\n", pTemplate->rRun, pTemplate->nOut, p->rRun, p->nOut-1)); pTemplate->rRun = p->rRun; pTemplate->nOut = p->nOut - 1; }else if( whereLoopCheaperProperSubset(pTemplate, p) ){ /* Adjust pTemplate cost upward so that it is costlier than p since ** pTemplate is a proper subset of p */ WHERETRACE(0x80,("subset cost adjustment %d,%d to %d,%d\n", pTemplate->rRun, pTemplate->nOut, p->rRun, p->nOut+1)); pTemplate->rRun = p->rRun; pTemplate->nOut = p->nOut + 1; } } } /* ** Search the list of WhereLoops in *ppPrev looking for one that can be ** supplanted by pTemplate. ** ** Return NULL if the WhereLoop list contains an entry that can supplant ** pTemplate, in other words if pTemplate does not belong on the list. ** ** If pX is a WhereLoop that pTemplate can supplant, then return the ** link that points to pX. ** ** If pTemplate cannot supplant any existing element of the list but needs ** to be added to the list, then return a pointer to the tail of the list. */ static WhereLoop **whereLoopFindLesser( WhereLoop **ppPrev, const WhereLoop *pTemplate ){ WhereLoop *p; for(p=(*ppPrev); p; ppPrev=&p->pNextLoop, p=*ppPrev){ if( p->iTab!=pTemplate->iTab || p->iSortIdx!=pTemplate->iSortIdx ){ /* If either the iTab or iSortIdx values for two WhereLoop are different ** then those WhereLoops need to be considered separately. Neither is ** a candidate to replace the other. */ continue; } /* In the current implementation, the rSetup value is either zero ** or the cost of building an automatic index (NlogN) and the NlogN ** is the same for compatible WhereLoops. */ assert( p->rSetup==0 || pTemplate->rSetup==0 || p->rSetup==pTemplate->rSetup ); /* whereLoopAddBtree() always generates and inserts the automatic index ** case first. Hence compatible candidate WhereLoops never have a larger ** rSetup. Call this SETUP-INVARIANT */ assert( p->rSetup>=pTemplate->rSetup ); /* Any loop using an appliation-defined index (or PRIMARY KEY or ** UNIQUE constraint) with one or more == constraints is better ** than an automatic index. Unless it is a skip-scan. */ if( (p->wsFlags & WHERE_AUTO_INDEX)!=0 && (pTemplate->nSkip)==0 && (pTemplate->wsFlags & WHERE_INDEXED)!=0 && (pTemplate->wsFlags & WHERE_COLUMN_EQ)!=0 && (p->prereq & pTemplate->prereq)==pTemplate->prereq ){ break; } /* If existing WhereLoop p is better than pTemplate, pTemplate can be ** discarded. WhereLoop p is better if: ** (1) p has no more dependencies than pTemplate, and ** (2) p has an equal or lower cost than pTemplate */ if( (p->prereq & pTemplate->prereq)==p->prereq /* (1) */ && p->rSetup<=pTemplate->rSetup /* (2a) */ && p->rRun<=pTemplate->rRun /* (2b) */ && p->nOut<=pTemplate->nOut /* (2c) */ ){ return 0; /* Discard pTemplate */ } /* If pTemplate is always better than p, then cause p to be overwritten ** with pTemplate. pTemplate is better than p if: ** (1) pTemplate has no more dependences than p, and ** (2) pTemplate has an equal or lower cost than p. */ if( (p->prereq & pTemplate->prereq)==pTemplate->prereq /* (1) */ && p->rRun>=pTemplate->rRun /* (2a) */ && p->nOut>=pTemplate->nOut /* (2b) */ ){ assert( p->rSetup>=pTemplate->rSetup ); /* SETUP-INVARIANT above */ break; /* Cause p to be overwritten by pTemplate */ } } return ppPrev; } /* ** Insert or replace a WhereLoop entry using the template supplied. ** ** An existing WhereLoop entry might be overwritten if the new template ** is better and has fewer dependencies. Or the template will be ignored ** and no insert will occur if an existing WhereLoop is faster and has ** fewer dependencies than the template. Otherwise a new WhereLoop is ** added based on the template. ** ** If pBuilder->pOrSet is not NULL then we care about only the ** prerequisites and rRun and nOut costs of the N best loops. That ** information is gathered in the pBuilder->pOrSet object. This special ** processing mode is used only for OR clause processing. ** ** When accumulating multiple loops (when pBuilder->pOrSet is NULL) we ** still might overwrite similar loops with the new template if the ** new template is better. Loops may be overwritten if the following ** conditions are met: ** ** (1) They have the same iTab. ** (2) They have the same iSortIdx. ** (3) The template has same or fewer dependencies than the current loop ** (4) The template has the same or lower cost than the current loop */ static int whereLoopInsert(WhereLoopBuilder *pBuilder, WhereLoop *pTemplate){ WhereLoop **ppPrev, *p; WhereInfo *pWInfo = pBuilder->pWInfo; sqlite3 *db = pWInfo->pParse->db; int rc; /* If pBuilder->pOrSet is defined, then only keep track of the costs ** and prereqs. */ if( pBuilder->pOrSet!=0 ){ if( pTemplate->nLTerm ){ #if WHERETRACE_ENABLED u16 n = pBuilder->pOrSet->n; int x = #endif whereOrInsert(pBuilder->pOrSet, pTemplate->prereq, pTemplate->rRun, pTemplate->nOut); #if WHERETRACE_ENABLED /* 0x8 */ if( sqlite3WhereTrace & 0x8 ){ sqlite3DebugPrintf(x?" or-%d: ":" or-X: ", n); whereLoopPrint(pTemplate, pBuilder->pWC); } #endif } return SQLITE_OK; } /* Look for an existing WhereLoop to replace with pTemplate */ whereLoopAdjustCost(pWInfo->pLoops, pTemplate); ppPrev = whereLoopFindLesser(&pWInfo->pLoops, pTemplate); if( ppPrev==0 ){ /* There already exists a WhereLoop on the list that is better ** than pTemplate, so just ignore pTemplate */ #if WHERETRACE_ENABLED /* 0x8 */ if( sqlite3WhereTrace & 0x8 ){ sqlite3DebugPrintf(" skip: "); whereLoopPrint(pTemplate, pBuilder->pWC); } #endif return SQLITE_OK; }else{ p = *ppPrev; } /* If we reach this point it means that either p[] should be overwritten ** with pTemplate[] if p[] exists, or if p==NULL then allocate a new ** WhereLoop and insert it. */ #if WHERETRACE_ENABLED /* 0x8 */ if( sqlite3WhereTrace & 0x8 ){ if( p!=0 ){ sqlite3DebugPrintf("replace: "); whereLoopPrint(p, pBuilder->pWC); } sqlite3DebugPrintf(" add: "); whereLoopPrint(pTemplate, pBuilder->pWC); } #endif if( p==0 ){ /* Allocate a new WhereLoop to add to the end of the list */ *ppPrev = p = sqlite3DbMallocRawNN(db, sizeof(WhereLoop)); if( p==0 ) return SQLITE_NOMEM_BKPT; whereLoopInit(p); p->pNextLoop = 0; }else{ /* We will be overwriting WhereLoop p[]. But before we do, first ** go through the rest of the list and delete any other entries besides ** p[] that are also supplated by pTemplate */ WhereLoop **ppTail = &p->pNextLoop; WhereLoop *pToDel; while( *ppTail ){ ppTail = whereLoopFindLesser(ppTail, pTemplate); if( ppTail==0 ) break; pToDel = *ppTail; if( pToDel==0 ) break; *ppTail = pToDel->pNextLoop; #if WHERETRACE_ENABLED /* 0x8 */ if( sqlite3WhereTrace & 0x8 ){ sqlite3DebugPrintf(" delete: "); whereLoopPrint(pToDel, pBuilder->pWC); } #endif whereLoopDelete(db, pToDel); } } rc = whereLoopXfer(db, p, pTemplate); if( (p->wsFlags & WHERE_VIRTUALTABLE)==0 ){ Index *pIndex = p->u.btree.pIndex; if( pIndex && pIndex->tnum==0 ){ p->u.btree.pIndex = 0; } } return rc; } /* ** Adjust the WhereLoop.nOut value downward to account for terms of the ** WHERE clause that reference the loop but which are not used by an ** index. * ** For every WHERE clause term that is not used by the index ** and which has a truth probability assigned by one of the likelihood(), ** likely(), or unlikely() SQL functions, reduce the estimated number ** of output rows by the probability specified. ** ** TUNING: For every WHERE clause term that is not used by the index ** and which does not have an assigned truth probability, heuristics ** described below are used to try to estimate the truth probability. ** TODO --> Perhaps this is something that could be improved by better ** table statistics. ** ** Heuristic 1: Estimate the truth probability as 93.75%. The 93.75% ** value corresponds to -1 in LogEst notation, so this means decrement ** the WhereLoop.nOut field for every such WHERE clause term. ** ** Heuristic 2: If there exists one or more WHERE clause terms of the ** form "x==EXPR" and EXPR is not a constant 0 or 1, then make sure the ** final output row estimate is no greater than 1/4 of the total number ** of rows in the table. In other words, assume that x==EXPR will filter ** out at least 3 out of 4 rows. If EXPR is -1 or 0 or 1, then maybe the ** "x" column is boolean or else -1 or 0 or 1 is a common default value ** on the "x" column and so in that case only cap the output row estimate ** at 1/2 instead of 1/4. */ static void whereLoopOutputAdjust( WhereClause *pWC, /* The WHERE clause */ WhereLoop *pLoop, /* The loop to adjust downward */ LogEst nRow /* Number of rows in the entire table */ ){ WhereTerm *pTerm, *pX; Bitmask notAllowed = ~(pLoop->prereq|pLoop->maskSelf); int i, j, k; LogEst iReduce = 0; /* pLoop->nOut should not exceed nRow-iReduce */ assert( (pLoop->wsFlags & WHERE_AUTO_INDEX)==0 ); for(i=pWC->nTerm, pTerm=pWC->a; i>0; i--, pTerm++){ if( (pTerm->wtFlags & TERM_VIRTUAL)!=0 ) break; if( (pTerm->prereqAll & pLoop->maskSelf)==0 ) continue; if( (pTerm->prereqAll & notAllowed)!=0 ) continue; for(j=pLoop->nLTerm-1; j>=0; j--){ pX = pLoop->aLTerm[j]; if( pX==0 ) continue; if( pX==pTerm ) break; if( pX->iParent>=0 && (&pWC->a[pX->iParent])==pTerm ) break; } if( j<0 ){ if( pTerm->truthProb<=0 ){ /* If a truth probability is specified using the likelihood() hints, ** then use the probability provided by the application. */ pLoop->nOut += pTerm->truthProb; }else{ /* In the absence of explicit truth probabilities, use heuristics to ** guess a reasonable truth probability. */ pLoop->nOut--; if( pTerm->eOperator&(WO_EQ|WO_IS) ){ Expr *pRight = pTerm->pExpr->pRight; testcase( pTerm->pExpr->op==TK_IS ); if( sqlite3ExprIsInteger(pRight, &k) && k>=(-1) && k<=1 ){ k = 10; }else{ k = 20; } if( iReducenOut > nRow-iReduce ) pLoop->nOut = nRow - iReduce; } /* ** Term pTerm is a vector range comparison operation. The first comparison ** in the vector can be optimized using column nEq of the index. This ** function returns the total number of vector elements that can be used ** as part of the range comparison. ** ** For example, if the query is: ** ** WHERE a = ? AND (b, c, d) > (?, ?, ?) ** ** and the index: ** ** CREATE INDEX ... ON (a, b, c, d, e) ** ** then this function would be invoked with nEq=1. The value returned in ** this case is 3. */ static int whereRangeVectorLen( Parse *pParse, /* Parsing context */ int iCur, /* Cursor open on pIdx */ Index *pIdx, /* The index to be used for a inequality constraint */ int nEq, /* Number of prior equality constraints on same index */ WhereTerm *pTerm /* The vector inequality constraint */ ){ int nCmp = sqlite3ExprVectorSize(pTerm->pExpr->pLeft); int i; nCmp = MIN(nCmp, (pIdx->nColumn - nEq)); for(i=1; ipExpr->pLeft->x.pList->a[i].pExpr; Expr *pRhs = pTerm->pExpr->pRight; if( pRhs->flags & EP_xIsSelect ){ pRhs = pRhs->x.pSelect->pEList->a[i].pExpr; }else{ pRhs = pRhs->x.pList->a[i].pExpr; } /* Check that the LHS of the comparison is a column reference to ** the right column of the right source table. And that the sort ** order of the index column is the same as the sort order of the ** leftmost index column. */ if( pLhs->op!=TK_COLUMN || pLhs->iTable!=iCur || pLhs->iColumn!=pIdx->aiColumn[i+nEq] || pIdx->aSortOrder[i+nEq]!=pIdx->aSortOrder[nEq] ){ break; } testcase( pLhs->iColumn==XN_ROWID ); aff = sqlite3CompareAffinity(pRhs, sqlite3ExprAffinity(pLhs)); idxaff = sqlite3TableColumnAffinity(pIdx->pTable, pLhs->iColumn); if( aff!=idxaff ) break; pColl = sqlite3BinaryCompareCollSeq(pParse, pLhs, pRhs); if( pColl==0 ) break; if( sqlite3StrICmp(pColl->zName, pIdx->azColl[i+nEq]) ) break; } return i; } /* ** Adjust the cost C by the costMult facter T. This only occurs if ** compiled with -DSQLITE_ENABLE_COSTMULT */ #ifdef SQLITE_ENABLE_COSTMULT # define ApplyCostMultiplier(C,T) C += T #else # define ApplyCostMultiplier(C,T) #endif /* ** We have so far matched pBuilder->pNew->u.btree.nEq terms of the ** index pIndex. Try to match one more. ** ** When this function is called, pBuilder->pNew->nOut contains the ** number of rows expected to be visited by filtering using the nEq ** terms only. If it is modified, this value is restored before this ** function returns. ** ** If pProbe->tnum==0, that means pIndex is a fake index used for the ** INTEGER PRIMARY KEY. */ static int whereLoopAddBtreeIndex( WhereLoopBuilder *pBuilder, /* The WhereLoop factory */ struct SrcList_item *pSrc, /* FROM clause term being analyzed */ Index *pProbe, /* An index on pSrc */ LogEst nInMul /* log(Number of iterations due to IN) */ ){ WhereInfo *pWInfo = pBuilder->pWInfo; /* WHERE analyse context */ Parse *pParse = pWInfo->pParse; /* Parsing context */ sqlite3 *db = pParse->db; /* Database connection malloc context */ WhereLoop *pNew; /* Template WhereLoop under construction */ WhereTerm *pTerm; /* A WhereTerm under consideration */ int opMask; /* Valid operators for constraints */ WhereScan scan; /* Iterator for WHERE terms */ Bitmask saved_prereq; /* Original value of pNew->prereq */ u16 saved_nLTerm; /* Original value of pNew->nLTerm */ u16 saved_nEq; /* Original value of pNew->u.btree.nEq */ u16 saved_nBtm; /* Original value of pNew->u.btree.nBtm */ u16 saved_nTop; /* Original value of pNew->u.btree.nTop */ u16 saved_nSkip; /* Original value of pNew->nSkip */ u32 saved_wsFlags; /* Original value of pNew->wsFlags */ LogEst saved_nOut; /* Original value of pNew->nOut */ int rc = SQLITE_OK; /* Return code */ LogEst rSize; /* Number of rows in the table */ LogEst rLogSize; /* Logarithm of table size */ WhereTerm *pTop = 0, *pBtm = 0; /* Top and bottom range constraints */ pNew = pBuilder->pNew; if( db->mallocFailed ) return SQLITE_NOMEM_BKPT; WHERETRACE(0x800, ("BEGIN addBtreeIdx(%s), nEq=%d\n", pProbe->zName, pNew->u.btree.nEq)); assert( (pNew->wsFlags & WHERE_VIRTUALTABLE)==0 ); assert( (pNew->wsFlags & WHERE_TOP_LIMIT)==0 ); if( pNew->wsFlags & WHERE_BTM_LIMIT ){ opMask = WO_LT|WO_LE; }else{ assert( pNew->u.btree.nBtm==0 ); opMask = WO_EQ|WO_IN|WO_GT|WO_GE|WO_LT|WO_LE|WO_ISNULL|WO_IS; } if( pProbe->bUnordered ) opMask &= ~(WO_GT|WO_GE|WO_LT|WO_LE); assert( pNew->u.btree.nEqnColumn ); saved_nEq = pNew->u.btree.nEq; saved_nBtm = pNew->u.btree.nBtm; saved_nTop = pNew->u.btree.nTop; saved_nSkip = pNew->nSkip; saved_nLTerm = pNew->nLTerm; saved_wsFlags = pNew->wsFlags; saved_prereq = pNew->prereq; saved_nOut = pNew->nOut; pTerm = whereScanInit(&scan, pBuilder->pWC, pSrc->iCursor, saved_nEq, opMask, pProbe); pNew->rSetup = 0; rSize = pProbe->aiRowLogEst[0]; rLogSize = estLog(rSize); for(; rc==SQLITE_OK && pTerm!=0; pTerm = whereScanNext(&scan)){ u16 eOp = pTerm->eOperator; /* Shorthand for pTerm->eOperator */ LogEst rCostIdx; LogEst nOutUnadjusted; /* nOut before IN() and WHERE adjustments */ int nIn = 0; #ifdef SQLITE_ENABLE_STAT3_OR_STAT4 int nRecValid = pBuilder->nRecValid; #endif if( (eOp==WO_ISNULL || (pTerm->wtFlags&TERM_VNULL)!=0) && indexColumnNotNull(pProbe, saved_nEq) ){ continue; /* ignore IS [NOT] NULL constraints on NOT NULL columns */ } if( pTerm->prereqRight & pNew->maskSelf ) continue; /* Do not allow the upper bound of a LIKE optimization range constraint ** to mix with a lower range bound from some other source */ if( pTerm->wtFlags & TERM_LIKEOPT && pTerm->eOperator==WO_LT ) continue; /* Do not allow IS constraints from the WHERE clause to be used by the ** right table of a LEFT JOIN. Only constraints in the ON clause are ** allowed */ if( (pSrc->fg.jointype & JT_LEFT)!=0 && !ExprHasProperty(pTerm->pExpr, EP_FromJoin) && (eOp & (WO_IS|WO_ISNULL))!=0 ){ testcase( eOp & WO_IS ); testcase( eOp & WO_ISNULL ); continue; } pNew->wsFlags = saved_wsFlags; pNew->u.btree.nEq = saved_nEq; pNew->u.btree.nBtm = saved_nBtm; pNew->u.btree.nTop = saved_nTop; pNew->nLTerm = saved_nLTerm; if( whereLoopResize(db, pNew, pNew->nLTerm+1) ) break; /* OOM */ pNew->aLTerm[pNew->nLTerm++] = pTerm; pNew->prereq = (saved_prereq | pTerm->prereqRight) & ~pNew->maskSelf; assert( nInMul==0 || (pNew->wsFlags & WHERE_COLUMN_NULL)!=0 || (pNew->wsFlags & WHERE_COLUMN_IN)!=0 || (pNew->wsFlags & WHERE_SKIPSCAN)!=0 ); if( eOp & WO_IN ){ Expr *pExpr = pTerm->pExpr; pNew->wsFlags |= WHERE_COLUMN_IN; if( ExprHasProperty(pExpr, EP_xIsSelect) ){ /* "x IN (SELECT ...)": TUNING: the SELECT returns 25 rows */ int i; nIn = 46; assert( 46==sqlite3LogEst(25) ); /* The expression may actually be of the form (x, y) IN (SELECT...). ** In this case there is a separate term for each of (x) and (y). ** However, the nIn multiplier should only be applied once, not once ** for each such term. The following loop checks that pTerm is the ** first such term in use, and sets nIn back to 0 if it is not. */ for(i=0; inLTerm-1; i++){ if( pNew->aLTerm[i] && pNew->aLTerm[i]->pExpr==pExpr ) nIn = 0; } }else if( ALWAYS(pExpr->x.pList && pExpr->x.pList->nExpr) ){ /* "x IN (value, value, ...)" */ nIn = sqlite3LogEst(pExpr->x.pList->nExpr); assert( nIn>0 ); /* RHS always has 2 or more terms... The parser ** changes "x IN (?)" into "x=?". */ } }else if( eOp & (WO_EQ|WO_IS) ){ int iCol = pProbe->aiColumn[saved_nEq]; pNew->wsFlags |= WHERE_COLUMN_EQ; assert( saved_nEq==pNew->u.btree.nEq ); if( iCol==XN_ROWID || (iCol>0 && nInMul==0 && saved_nEq==pProbe->nKeyCol-1) ){ if( iCol>=0 && pProbe->uniqNotNull==0 ){ pNew->wsFlags |= WHERE_UNQ_WANTED; }else{ pNew->wsFlags |= WHERE_ONEROW; } } }else if( eOp & WO_ISNULL ){ pNew->wsFlags |= WHERE_COLUMN_NULL; }else if( eOp & (WO_GT|WO_GE) ){ testcase( eOp & WO_GT ); testcase( eOp & WO_GE ); pNew->wsFlags |= WHERE_COLUMN_RANGE|WHERE_BTM_LIMIT; pNew->u.btree.nBtm = whereRangeVectorLen( pParse, pSrc->iCursor, pProbe, saved_nEq, pTerm ); pBtm = pTerm; pTop = 0; if( pTerm->wtFlags & TERM_LIKEOPT ){ /* Range contraints that come from the LIKE optimization are ** always used in pairs. */ pTop = &pTerm[1]; assert( (pTop-(pTerm->pWC->a))pWC->nTerm ); assert( pTop->wtFlags & TERM_LIKEOPT ); assert( pTop->eOperator==WO_LT ); if( whereLoopResize(db, pNew, pNew->nLTerm+1) ) break; /* OOM */ pNew->aLTerm[pNew->nLTerm++] = pTop; pNew->wsFlags |= WHERE_TOP_LIMIT; pNew->u.btree.nTop = 1; } }else{ assert( eOp & (WO_LT|WO_LE) ); testcase( eOp & WO_LT ); testcase( eOp & WO_LE ); pNew->wsFlags |= WHERE_COLUMN_RANGE|WHERE_TOP_LIMIT; pNew->u.btree.nTop = whereRangeVectorLen( pParse, pSrc->iCursor, pProbe, saved_nEq, pTerm ); pTop = pTerm; pBtm = (pNew->wsFlags & WHERE_BTM_LIMIT)!=0 ? pNew->aLTerm[pNew->nLTerm-2] : 0; } /* At this point pNew->nOut is set to the number of rows expected to ** be visited by the index scan before considering term pTerm, or the ** values of nIn and nInMul. In other words, assuming that all ** "x IN(...)" terms are replaced with "x = ?". This block updates ** the value of pNew->nOut to account for pTerm (but not nIn/nInMul). */ assert( pNew->nOut==saved_nOut ); if( pNew->wsFlags & WHERE_COLUMN_RANGE ){ /* Adjust nOut using stat3/stat4 data. Or, if there is no stat3/stat4 ** data, using some other estimate. */ whereRangeScanEst(pParse, pBuilder, pBtm, pTop, pNew); }else{ int nEq = ++pNew->u.btree.nEq; assert( eOp & (WO_ISNULL|WO_EQ|WO_IN|WO_IS) ); assert( pNew->nOut==saved_nOut ); if( pTerm->truthProb<=0 && pProbe->aiColumn[saved_nEq]>=0 ){ assert( (eOp & WO_IN) || nIn==0 ); testcase( eOp & WO_IN ); pNew->nOut += pTerm->truthProb; pNew->nOut -= nIn; }else{ #ifdef SQLITE_ENABLE_STAT3_OR_STAT4 tRowcnt nOut = 0; if( nInMul==0 && pProbe->nSample && pNew->u.btree.nEq<=pProbe->nSampleCol && ((eOp & WO_IN)==0 || !ExprHasProperty(pTerm->pExpr, EP_xIsSelect)) ){ Expr *pExpr = pTerm->pExpr; if( (eOp & (WO_EQ|WO_ISNULL|WO_IS))!=0 ){ testcase( eOp & WO_EQ ); testcase( eOp & WO_IS ); testcase( eOp & WO_ISNULL ); rc = whereEqualScanEst(pParse, pBuilder, pExpr->pRight, &nOut); }else{ rc = whereInScanEst(pParse, pBuilder, pExpr->x.pList, &nOut); } if( rc==SQLITE_NOTFOUND ) rc = SQLITE_OK; if( rc!=SQLITE_OK ) break; /* Jump out of the pTerm loop */ if( nOut ){ pNew->nOut = sqlite3LogEst(nOut); if( pNew->nOut>saved_nOut ) pNew->nOut = saved_nOut; pNew->nOut -= nIn; } } if( nOut==0 ) #endif { pNew->nOut += (pProbe->aiRowLogEst[nEq] - pProbe->aiRowLogEst[nEq-1]); if( eOp & WO_ISNULL ){ /* TUNING: If there is no likelihood() value, assume that a ** "col IS NULL" expression matches twice as many rows ** as (col=?). */ pNew->nOut += 10; } } } } /* Set rCostIdx to the cost of visiting selected rows in index. Add ** it to pNew->rRun, which is currently set to the cost of the index ** seek only. Then, if this is a non-covering index, add the cost of ** visiting the rows in the main table. */ rCostIdx = pNew->nOut + 1 + (15*pProbe->szIdxRow)/pSrc->pTab->szTabRow; pNew->rRun = sqlite3LogEstAdd(rLogSize, rCostIdx); if( (pNew->wsFlags & (WHERE_IDX_ONLY|WHERE_IPK))==0 ){ pNew->rRun = sqlite3LogEstAdd(pNew->rRun, pNew->nOut + 16); } ApplyCostMultiplier(pNew->rRun, pProbe->pTable->costMult); nOutUnadjusted = pNew->nOut; pNew->rRun += nInMul + nIn; pNew->nOut += nInMul + nIn; whereLoopOutputAdjust(pBuilder->pWC, pNew, rSize); rc = whereLoopInsert(pBuilder, pNew); if( pNew->wsFlags & WHERE_COLUMN_RANGE ){ pNew->nOut = saved_nOut; }else{ pNew->nOut = nOutUnadjusted; } if( (pNew->wsFlags & WHERE_TOP_LIMIT)==0 && pNew->u.btree.nEqnColumn ){ whereLoopAddBtreeIndex(pBuilder, pSrc, pProbe, nInMul+nIn); } pNew->nOut = saved_nOut; #ifdef SQLITE_ENABLE_STAT3_OR_STAT4 pBuilder->nRecValid = nRecValid; #endif } pNew->prereq = saved_prereq; pNew->u.btree.nEq = saved_nEq; pNew->u.btree.nBtm = saved_nBtm; pNew->u.btree.nTop = saved_nTop; pNew->nSkip = saved_nSkip; pNew->wsFlags = saved_wsFlags; pNew->nOut = saved_nOut; pNew->nLTerm = saved_nLTerm; /* Consider using a skip-scan if there are no WHERE clause constraints ** available for the left-most terms of the index, and if the average ** number of repeats in the left-most terms is at least 18. ** ** The magic number 18 is selected on the basis that scanning 17 rows ** is almost always quicker than an index seek (even though if the index ** contains fewer than 2^17 rows we assume otherwise in other parts of ** the code). And, even if it is not, it should not be too much slower. ** On the other hand, the extra seeks could end up being significantly ** more expensive. */ assert( 42==sqlite3LogEst(18) ); if( saved_nEq==saved_nSkip && saved_nEq+1nKeyCol && pProbe->noSkipScan==0 && pProbe->aiRowLogEst[saved_nEq+1]>=42 /* TUNING: Minimum for skip-scan */ && (rc = whereLoopResize(db, pNew, pNew->nLTerm+1))==SQLITE_OK ){ LogEst nIter; pNew->u.btree.nEq++; pNew->nSkip++; pNew->aLTerm[pNew->nLTerm++] = 0; pNew->wsFlags |= WHERE_SKIPSCAN; nIter = pProbe->aiRowLogEst[saved_nEq] - pProbe->aiRowLogEst[saved_nEq+1]; pNew->nOut -= nIter; /* TUNING: Because uncertainties in the estimates for skip-scan queries, ** add a 1.375 fudge factor to make skip-scan slightly less likely. */ nIter += 5; whereLoopAddBtreeIndex(pBuilder, pSrc, pProbe, nIter + nInMul); pNew->nOut = saved_nOut; pNew->u.btree.nEq = saved_nEq; pNew->nSkip = saved_nSkip; pNew->wsFlags = saved_wsFlags; } WHERETRACE(0x800, ("END addBtreeIdx(%s), nEq=%d, rc=%d\n", pProbe->zName, saved_nEq, rc)); return rc; } /* ** Return True if it is possible that pIndex might be useful in ** implementing the ORDER BY clause in pBuilder. ** ** Return False if pBuilder does not contain an ORDER BY clause or ** if there is no way for pIndex to be useful in implementing that ** ORDER BY clause. */ static int indexMightHelpWithOrderBy( WhereLoopBuilder *pBuilder, Index *pIndex, int iCursor ){ ExprList *pOB; ExprList *aColExpr; int ii, jj; if( pIndex->bUnordered ) return 0; if( (pOB = pBuilder->pWInfo->pOrderBy)==0 ) return 0; for(ii=0; iinExpr; ii++){ Expr *pExpr = sqlite3ExprSkipCollate(pOB->a[ii].pExpr); if( pExpr->op==TK_COLUMN && pExpr->iTable==iCursor ){ if( pExpr->iColumn<0 ) return 1; for(jj=0; jjnKeyCol; jj++){ if( pExpr->iColumn==pIndex->aiColumn[jj] ) return 1; } }else if( (aColExpr = pIndex->aColExpr)!=0 ){ for(jj=0; jjnKeyCol; jj++){ if( pIndex->aiColumn[jj]!=XN_EXPR ) continue; if( sqlite3ExprCompare(pExpr,aColExpr->a[jj].pExpr,iCursor)==0 ){ return 1; } } } } return 0; } /* ** Return a bitmask where 1s indicate that the corresponding column of ** the table is used by an index. Only the first 63 columns are considered. */ static Bitmask columnsInIndex(Index *pIdx){ Bitmask m = 0; int j; for(j=pIdx->nColumn-1; j>=0; j--){ int x = pIdx->aiColumn[j]; if( x>=0 ){ testcase( x==BMS-1 ); testcase( x==BMS-2 ); if( xop==TK_AND ){ if( !whereUsablePartialIndex(iTab,pWC,pWhere->pLeft) ) return 0; pWhere = pWhere->pRight; } for(i=0, pTerm=pWC->a; inTerm; i++, pTerm++){ Expr *pExpr = pTerm->pExpr; if( sqlite3ExprImpliesExpr(pExpr, pWhere, iTab) && (!ExprHasProperty(pExpr, EP_FromJoin) || pExpr->iRightJoinTable==iTab) ){ return 1; } } return 0; } /* ** Add all WhereLoop objects for a single table of the join where the table ** is identified by pBuilder->pNew->iTab. That table is guaranteed to be ** a b-tree table, not a virtual table. ** ** The costs (WhereLoop.rRun) of the b-tree loops added by this function ** are calculated as follows: ** ** For a full scan, assuming the table (or index) contains nRow rows: ** ** cost = nRow * 3.0 // full-table scan ** cost = nRow * K // scan of covering index ** cost = nRow * (K+3.0) // scan of non-covering index ** ** where K is a value between 1.1 and 3.0 set based on the relative ** estimated average size of the index and table records. ** ** For an index scan, where nVisit is the number of index rows visited ** by the scan, and nSeek is the number of seek operations required on ** the index b-tree: ** ** cost = nSeek * (log(nRow) + K * nVisit) // covering index ** cost = nSeek * (log(nRow) + (K+3.0) * nVisit) // non-covering index ** ** Normally, nSeek is 1. nSeek values greater than 1 come about if the ** WHERE clause includes "x IN (....)" terms used in place of "x=?". Or when ** implicit "x IN (SELECT x FROM tbl)" terms are added for skip-scans. ** ** The estimated values (nRow, nVisit, nSeek) often contain a large amount ** of uncertainty. For this reason, scoring is designed to pick plans that ** "do the least harm" if the estimates are inaccurate. For example, a ** log(nRow) factor is omitted from a non-covering index scan in order to ** bias the scoring in favor of using an index, since the worst-case ** performance of using an index is far better than the worst-case performance ** of a full table scan. */ static int whereLoopAddBtree( WhereLoopBuilder *pBuilder, /* WHERE clause information */ Bitmask mPrereq /* Extra prerequesites for using this table */ ){ WhereInfo *pWInfo; /* WHERE analysis context */ Index *pProbe; /* An index we are evaluating */ Index sPk; /* A fake index object for the primary key */ LogEst aiRowEstPk[2]; /* The aiRowLogEst[] value for the sPk index */ i16 aiColumnPk = -1; /* The aColumn[] value for the sPk index */ SrcList *pTabList; /* The FROM clause */ struct SrcList_item *pSrc; /* The FROM clause btree term to add */ WhereLoop *pNew; /* Template WhereLoop object */ int rc = SQLITE_OK; /* Return code */ int iSortIdx = 1; /* Index number */ int b; /* A boolean value */ LogEst rSize; /* number of rows in the table */ LogEst rLogSize; /* Logarithm of the number of rows in the table */ WhereClause *pWC; /* The parsed WHERE clause */ Table *pTab; /* Table being queried */ pNew = pBuilder->pNew; pWInfo = pBuilder->pWInfo; pTabList = pWInfo->pTabList; pSrc = pTabList->a + pNew->iTab; pTab = pSrc->pTab; pWC = pBuilder->pWC; assert( !IsVirtual(pSrc->pTab) ); if( pSrc->pIBIndex ){ /* An INDEXED BY clause specifies a particular index to use */ pProbe = pSrc->pIBIndex; }else if( !HasRowid(pTab) ){ pProbe = pTab->pIndex; }else{ /* There is no INDEXED BY clause. Create a fake Index object in local ** variable sPk to represent the rowid primary key index. Make this ** fake index the first in a chain of Index objects with all of the real ** indices to follow */ Index *pFirst; /* First of real indices on the table */ memset(&sPk, 0, sizeof(Index)); sPk.nKeyCol = 1; sPk.nColumn = 1; sPk.aiColumn = &aiColumnPk; sPk.aiRowLogEst = aiRowEstPk; sPk.onError = OE_Replace; sPk.pTable = pTab; sPk.szIdxRow = pTab->szTabRow; aiRowEstPk[0] = pTab->nRowLogEst; aiRowEstPk[1] = 0; pFirst = pSrc->pTab->pIndex; if( pSrc->fg.notIndexed==0 ){ /* The real indices of the table are only considered if the ** NOT INDEXED qualifier is omitted from the FROM clause */ sPk.pNext = pFirst; } pProbe = &sPk; } rSize = pTab->nRowLogEst; rLogSize = estLog(rSize); #ifndef SQLITE_OMIT_AUTOMATIC_INDEX /* Automatic indexes */ if( !pBuilder->pOrSet /* Not part of an OR optimization */ && (pWInfo->wctrlFlags & WHERE_OR_SUBCLAUSE)==0 && (pWInfo->pParse->db->flags & SQLITE_AutoIndex)!=0 && pSrc->pIBIndex==0 /* Has no INDEXED BY clause */ && !pSrc->fg.notIndexed /* Has no NOT INDEXED clause */ && HasRowid(pTab) /* Not WITHOUT ROWID table. (FIXME: Why not?) */ && !pSrc->fg.isCorrelated /* Not a correlated subquery */ && !pSrc->fg.isRecursive /* Not a recursive common table expression. */ ){ /* Generate auto-index WhereLoops */ WhereTerm *pTerm; WhereTerm *pWCEnd = pWC->a + pWC->nTerm; for(pTerm=pWC->a; rc==SQLITE_OK && pTermprereqRight & pNew->maskSelf ) continue; if( termCanDriveIndex(pTerm, pSrc, 0) ){ pNew->u.btree.nEq = 1; pNew->nSkip = 0; pNew->u.btree.pIndex = 0; pNew->nLTerm = 1; pNew->aLTerm[0] = pTerm; /* TUNING: One-time cost for computing the automatic index is ** estimated to be X*N*log2(N) where N is the number of rows in ** the table being indexed and where X is 7 (LogEst=28) for normal ** tables or 1.375 (LogEst=4) for views and subqueries. The value ** of X is smaller for views and subqueries so that the query planner ** will be more aggressive about generating automatic indexes for ** those objects, since there is no opportunity to add schema ** indexes on subqueries and views. */ pNew->rSetup = rLogSize + rSize + 4; if( pTab->pSelect==0 && (pTab->tabFlags & TF_Ephemeral)==0 ){ pNew->rSetup += 24; } ApplyCostMultiplier(pNew->rSetup, pTab->costMult); if( pNew->rSetup<0 ) pNew->rSetup = 0; /* TUNING: Each index lookup yields 20 rows in the table. This ** is more than the usual guess of 10 rows, since we have no way ** of knowing how selective the index will ultimately be. It would ** not be unreasonable to make this value much larger. */ pNew->nOut = 43; assert( 43==sqlite3LogEst(20) ); pNew->rRun = sqlite3LogEstAdd(rLogSize,pNew->nOut); pNew->wsFlags = WHERE_AUTO_INDEX; pNew->prereq = mPrereq | pTerm->prereqRight; rc = whereLoopInsert(pBuilder, pNew); } } } #endif /* SQLITE_OMIT_AUTOMATIC_INDEX */ /* Loop over all indices */ for(; rc==SQLITE_OK && pProbe; pProbe=pProbe->pNext, iSortIdx++){ if( pProbe->pPartIdxWhere!=0 && !whereUsablePartialIndex(pSrc->iCursor, pWC, pProbe->pPartIdxWhere) ){ testcase( pNew->iTab!=pSrc->iCursor ); /* See ticket [98d973b8f5] */ continue; /* Partial index inappropriate for this query */ } rSize = pProbe->aiRowLogEst[0]; pNew->u.btree.nEq = 0; pNew->u.btree.nBtm = 0; pNew->u.btree.nTop = 0; pNew->nSkip = 0; pNew->nLTerm = 0; pNew->iSortIdx = 0; pNew->rSetup = 0; pNew->prereq = mPrereq; pNew->nOut = rSize; pNew->u.btree.pIndex = pProbe; b = indexMightHelpWithOrderBy(pBuilder, pProbe, pSrc->iCursor); /* The ONEPASS_DESIRED flags never occurs together with ORDER BY */ assert( (pWInfo->wctrlFlags & WHERE_ONEPASS_DESIRED)==0 || b==0 ); if( pProbe->tnum<=0 ){ /* Integer primary key index */ pNew->wsFlags = WHERE_IPK; /* Full table scan */ pNew->iSortIdx = b ? iSortIdx : 0; /* TUNING: Cost of full table scan is (N*3.0). */ pNew->rRun = rSize + 16; ApplyCostMultiplier(pNew->rRun, pTab->costMult); whereLoopOutputAdjust(pWC, pNew, rSize); rc = whereLoopInsert(pBuilder, pNew); pNew->nOut = rSize; if( rc ) break; }else{ Bitmask m; if( pProbe->isCovering ){ pNew->wsFlags = WHERE_IDX_ONLY | WHERE_INDEXED; m = 0; }else{ m = pSrc->colUsed & ~columnsInIndex(pProbe); pNew->wsFlags = (m==0) ? (WHERE_IDX_ONLY|WHERE_INDEXED) : WHERE_INDEXED; } /* Full scan via index */ if( b || !HasRowid(pTab) || pProbe->pPartIdxWhere!=0 || ( m==0 && pProbe->bUnordered==0 && (pProbe->szIdxRowszTabRow) && (pWInfo->wctrlFlags & WHERE_ONEPASS_DESIRED)==0 && sqlite3GlobalConfig.bUseCis && OptimizationEnabled(pWInfo->pParse->db, SQLITE_CoverIdxScan) ) ){ pNew->iSortIdx = b ? iSortIdx : 0; /* The cost of visiting the index rows is N*K, where K is ** between 1.1 and 3.0, depending on the relative sizes of the ** index and table rows. */ pNew->rRun = rSize + 1 + (15*pProbe->szIdxRow)/pTab->szTabRow; if( m!=0 ){ /* If this is a non-covering index scan, add in the cost of ** doing table lookups. The cost will be 3x the number of ** lookups. Take into account WHERE clause terms that can be ** satisfied using just the index, and that do not require a ** table lookup. */ LogEst nLookup = rSize + 16; /* Base cost: N*3 */ int ii; int iCur = pSrc->iCursor; WhereClause *pWC2 = &pWInfo->sWC; for(ii=0; iinTerm; ii++){ WhereTerm *pTerm = &pWC2->a[ii]; if( !sqlite3ExprCoveredByIndex(pTerm->pExpr, iCur, pProbe) ){ break; } /* pTerm can be evaluated using just the index. So reduce ** the expected number of table lookups accordingly */ if( pTerm->truthProb<=0 ){ nLookup += pTerm->truthProb; }else{ nLookup--; if( pTerm->eOperator & (WO_EQ|WO_IS) ) nLookup -= 19; } } pNew->rRun = sqlite3LogEstAdd(pNew->rRun, nLookup); } ApplyCostMultiplier(pNew->rRun, pTab->costMult); whereLoopOutputAdjust(pWC, pNew, rSize); rc = whereLoopInsert(pBuilder, pNew); pNew->nOut = rSize; if( rc ) break; } } rc = whereLoopAddBtreeIndex(pBuilder, pSrc, pProbe, 0); #ifdef SQLITE_ENABLE_STAT3_OR_STAT4 sqlite3Stat4ProbeFree(pBuilder->pRec); pBuilder->nRecValid = 0; pBuilder->pRec = 0; #endif /* If there was an INDEXED BY clause, then only that one index is ** considered. */ if( pSrc->pIBIndex ) break; } return rc; } #ifndef SQLITE_OMIT_VIRTUALTABLE /* ** Argument pIdxInfo is already populated with all constraints that may ** be used by the virtual table identified by pBuilder->pNew->iTab. This ** function marks a subset of those constraints usable, invokes the ** xBestIndex method and adds the returned plan to pBuilder. ** ** A constraint is marked usable if: ** ** * Argument mUsable indicates that its prerequisites are available, and ** ** * It is not one of the operators specified in the mExclude mask passed ** as the fourth argument (which in practice is either WO_IN or 0). ** ** Argument mPrereq is a mask of tables that must be scanned before the ** virtual table in question. These are added to the plans prerequisites ** before it is added to pBuilder. ** ** Output parameter *pbIn is set to true if the plan added to pBuilder ** uses one or more WO_IN terms, or false otherwise. */ static int whereLoopAddVirtualOne( WhereLoopBuilder *pBuilder, Bitmask mPrereq, /* Mask of tables that must be used. */ Bitmask mUsable, /* Mask of usable tables */ u16 mExclude, /* Exclude terms using these operators */ sqlite3_index_info *pIdxInfo, /* Populated object for xBestIndex */ u16 mNoOmit, /* Do not omit these constraints */ int *pbIn /* OUT: True if plan uses an IN(...) op */ ){ WhereClause *pWC = pBuilder->pWC; struct sqlite3_index_constraint *pIdxCons; struct sqlite3_index_constraint_usage *pUsage = pIdxInfo->aConstraintUsage; int i; int mxTerm; int rc = SQLITE_OK; WhereLoop *pNew = pBuilder->pNew; Parse *pParse = pBuilder->pWInfo->pParse; struct SrcList_item *pSrc = &pBuilder->pWInfo->pTabList->a[pNew->iTab]; int nConstraint = pIdxInfo->nConstraint; assert( (mUsable & mPrereq)==mPrereq ); *pbIn = 0; pNew->prereq = mPrereq; /* Set the usable flag on the subset of constraints identified by ** arguments mUsable and mExclude. */ pIdxCons = *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint; for(i=0; ia[pIdxCons->iTermOffset]; pIdxCons->usable = 0; if( (pTerm->prereqRight & mUsable)==pTerm->prereqRight && (pTerm->eOperator & mExclude)==0 ){ pIdxCons->usable = 1; } } /* Initialize the output fields of the sqlite3_index_info structure */ memset(pUsage, 0, sizeof(pUsage[0])*nConstraint); assert( pIdxInfo->needToFreeIdxStr==0 ); pIdxInfo->idxStr = 0; pIdxInfo->idxNum = 0; pIdxInfo->orderByConsumed = 0; pIdxInfo->estimatedCost = SQLITE_BIG_DBL / (double)2; pIdxInfo->estimatedRows = 25; pIdxInfo->idxFlags = 0; pIdxInfo->colUsed = (sqlite3_int64)pSrc->colUsed; /* Invoke the virtual table xBestIndex() method */ rc = vtabBestIndex(pParse, pSrc->pTab, pIdxInfo); if( rc ) return rc; mxTerm = -1; assert( pNew->nLSlot>=nConstraint ); for(i=0; iaLTerm[i] = 0; pNew->u.vtab.omitMask = 0; pIdxCons = *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint; for(i=0; i=0 ){ WhereTerm *pTerm; int j = pIdxCons->iTermOffset; if( iTerm>=nConstraint || j<0 || j>=pWC->nTerm || pNew->aLTerm[iTerm]!=0 || pIdxCons->usable==0 ){ rc = SQLITE_ERROR; sqlite3ErrorMsg(pParse,"%s.xBestIndex malfunction",pSrc->pTab->zName); return rc; } testcase( iTerm==nConstraint-1 ); testcase( j==0 ); testcase( j==pWC->nTerm-1 ); pTerm = &pWC->a[j]; pNew->prereq |= pTerm->prereqRight; assert( iTermnLSlot ); pNew->aLTerm[iTerm] = pTerm; if( iTerm>mxTerm ) mxTerm = iTerm; testcase( iTerm==15 ); testcase( iTerm==16 ); if( iTerm<16 && pUsage[i].omit ) pNew->u.vtab.omitMask |= 1<eOperator & WO_IN)!=0 ){ /* A virtual table that is constrained by an IN clause may not ** consume the ORDER BY clause because (1) the order of IN terms ** is not necessarily related to the order of output terms and ** (2) Multiple outputs from a single IN value will not merge ** together. */ pIdxInfo->orderByConsumed = 0; pIdxInfo->idxFlags &= ~SQLITE_INDEX_SCAN_UNIQUE; *pbIn = 1; assert( (mExclude & WO_IN)==0 ); } } } pNew->u.vtab.omitMask &= ~mNoOmit; pNew->nLTerm = mxTerm+1; assert( pNew->nLTerm<=pNew->nLSlot ); pNew->u.vtab.idxNum = pIdxInfo->idxNum; pNew->u.vtab.needFree = pIdxInfo->needToFreeIdxStr; pIdxInfo->needToFreeIdxStr = 0; pNew->u.vtab.idxStr = pIdxInfo->idxStr; pNew->u.vtab.isOrdered = (i8)(pIdxInfo->orderByConsumed ? pIdxInfo->nOrderBy : 0); pNew->rSetup = 0; pNew->rRun = sqlite3LogEstFromDouble(pIdxInfo->estimatedCost); pNew->nOut = sqlite3LogEst(pIdxInfo->estimatedRows); /* Set the WHERE_ONEROW flag if the xBestIndex() method indicated ** that the scan will visit at most one row. Clear it otherwise. */ if( pIdxInfo->idxFlags & SQLITE_INDEX_SCAN_UNIQUE ){ pNew->wsFlags |= WHERE_ONEROW; }else{ pNew->wsFlags &= ~WHERE_ONEROW; } rc = whereLoopInsert(pBuilder, pNew); if( pNew->u.vtab.needFree ){ sqlite3_free(pNew->u.vtab.idxStr); pNew->u.vtab.needFree = 0; } WHERETRACE(0xffff, (" bIn=%d prereqIn=%04llx prereqOut=%04llx\n", *pbIn, (sqlite3_uint64)mPrereq, (sqlite3_uint64)(pNew->prereq & ~mPrereq))); return rc; } /* ** Add all WhereLoop objects for a table of the join identified by ** pBuilder->pNew->iTab. That table is guaranteed to be a virtual table. ** ** If there are no LEFT or CROSS JOIN joins in the query, both mPrereq and ** mUnusable are set to 0. Otherwise, mPrereq is a mask of all FROM clause ** entries that occur before the virtual table in the FROM clause and are ** separated from it by at least one LEFT or CROSS JOIN. Similarly, the ** mUnusable mask contains all FROM clause entries that occur after the ** virtual table and are separated from it by at least one LEFT or ** CROSS JOIN. ** ** For example, if the query were: ** ** ... FROM t1, t2 LEFT JOIN t3, t4, vt CROSS JOIN t5, t6; ** ** then mPrereq corresponds to (t1, t2) and mUnusable to (t5, t6). ** ** All the tables in mPrereq must be scanned before the current virtual ** table. So any terms for which all prerequisites are satisfied by ** mPrereq may be specified as "usable" in all calls to xBestIndex. ** Conversely, all tables in mUnusable must be scanned after the current ** virtual table, so any terms for which the prerequisites overlap with ** mUnusable should always be configured as "not-usable" for xBestIndex. */ static int whereLoopAddVirtual( WhereLoopBuilder *pBuilder, /* WHERE clause information */ Bitmask mPrereq, /* Tables that must be scanned before this one */ Bitmask mUnusable /* Tables that must be scanned after this one */ ){ int rc = SQLITE_OK; /* Return code */ WhereInfo *pWInfo; /* WHERE analysis context */ Parse *pParse; /* The parsing context */ WhereClause *pWC; /* The WHERE clause */ struct SrcList_item *pSrc; /* The FROM clause term to search */ sqlite3_index_info *p; /* Object to pass to xBestIndex() */ int nConstraint; /* Number of constraints in p */ int bIn; /* True if plan uses IN(...) operator */ WhereLoop *pNew; Bitmask mBest; /* Tables used by best possible plan */ u16 mNoOmit; assert( (mPrereq & mUnusable)==0 ); pWInfo = pBuilder->pWInfo; pParse = pWInfo->pParse; pWC = pBuilder->pWC; pNew = pBuilder->pNew; pSrc = &pWInfo->pTabList->a[pNew->iTab]; assert( IsVirtual(pSrc->pTab) ); p = allocateIndexInfo(pParse, pWC, mUnusable, pSrc, pBuilder->pOrderBy, &mNoOmit); if( p==0 ) return SQLITE_NOMEM_BKPT; pNew->rSetup = 0; pNew->wsFlags = WHERE_VIRTUALTABLE; pNew->nLTerm = 0; pNew->u.vtab.needFree = 0; nConstraint = p->nConstraint; if( whereLoopResize(pParse->db, pNew, nConstraint) ){ sqlite3DbFree(pParse->db, p); return SQLITE_NOMEM_BKPT; } /* First call xBestIndex() with all constraints usable. */ WHERETRACE(0x40, (" VirtualOne: all usable\n")); rc = whereLoopAddVirtualOne(pBuilder, mPrereq, ALLBITS, 0, p, mNoOmit, &bIn); /* If the call to xBestIndex() with all terms enabled produced a plan ** that does not require any source tables (IOW: a plan with mBest==0), ** then there is no point in making any further calls to xBestIndex() ** since they will all return the same result (if the xBestIndex() ** implementation is sane). */ if( rc==SQLITE_OK && (mBest = (pNew->prereq & ~mPrereq))!=0 ){ int seenZero = 0; /* True if a plan with no prereqs seen */ int seenZeroNoIN = 0; /* Plan with no prereqs and no IN(...) seen */ Bitmask mPrev = 0; Bitmask mBestNoIn = 0; /* If the plan produced by the earlier call uses an IN(...) term, call ** xBestIndex again, this time with IN(...) terms disabled. */ if( bIn ){ WHERETRACE(0x40, (" VirtualOne: all usable w/o IN\n")); rc = whereLoopAddVirtualOne( pBuilder, mPrereq, ALLBITS, WO_IN, p, mNoOmit, &bIn); assert( bIn==0 ); mBestNoIn = pNew->prereq & ~mPrereq; if( mBestNoIn==0 ){ seenZero = 1; seenZeroNoIN = 1; } } /* Call xBestIndex once for each distinct value of (prereqRight & ~mPrereq) ** in the set of terms that apply to the current virtual table. */ while( rc==SQLITE_OK ){ int i; Bitmask mNext = ALLBITS; assert( mNext>0 ); for(i=0; ia[p->aConstraint[i].iTermOffset].prereqRight & ~mPrereq ); if( mThis>mPrev && mThisprereq==mPrereq ){ seenZero = 1; if( bIn==0 ) seenZeroNoIN = 1; } } /* If the calls to xBestIndex() in the above loop did not find a plan ** that requires no source tables at all (i.e. one guaranteed to be ** usable), make a call here with all source tables disabled */ if( rc==SQLITE_OK && seenZero==0 ){ WHERETRACE(0x40, (" VirtualOne: all disabled\n")); rc = whereLoopAddVirtualOne( pBuilder, mPrereq, mPrereq, 0, p, mNoOmit, &bIn); if( bIn==0 ) seenZeroNoIN = 1; } /* If the calls to xBestIndex() have so far failed to find a plan ** that requires no source tables at all and does not use an IN(...) ** operator, make a final call to obtain one here. */ if( rc==SQLITE_OK && seenZeroNoIN==0 ){ WHERETRACE(0x40, (" VirtualOne: all disabled and w/o IN\n")); rc = whereLoopAddVirtualOne( pBuilder, mPrereq, mPrereq, WO_IN, p, mNoOmit, &bIn); } } if( p->needToFreeIdxStr ) sqlite3_free(p->idxStr); sqlite3DbFree(pParse->db, p); return rc; } #endif /* SQLITE_OMIT_VIRTUALTABLE */ /* ** Add WhereLoop entries to handle OR terms. This works for either ** btrees or virtual tables. */ static int whereLoopAddOr( WhereLoopBuilder *pBuilder, Bitmask mPrereq, Bitmask mUnusable ){ WhereInfo *pWInfo = pBuilder->pWInfo; WhereClause *pWC; WhereLoop *pNew; WhereTerm *pTerm, *pWCEnd; int rc = SQLITE_OK; int iCur; WhereClause tempWC; WhereLoopBuilder sSubBuild; WhereOrSet sSum, sCur; struct SrcList_item *pItem; pWC = pBuilder->pWC; pWCEnd = pWC->a + pWC->nTerm; pNew = pBuilder->pNew; memset(&sSum, 0, sizeof(sSum)); pItem = pWInfo->pTabList->a + pNew->iTab; iCur = pItem->iCursor; for(pTerm=pWC->a; pTermeOperator & WO_OR)!=0 && (pTerm->u.pOrInfo->indexable & pNew->maskSelf)!=0 ){ WhereClause * const pOrWC = &pTerm->u.pOrInfo->wc; WhereTerm * const pOrWCEnd = &pOrWC->a[pOrWC->nTerm]; WhereTerm *pOrTerm; int once = 1; int i, j; sSubBuild = *pBuilder; sSubBuild.pOrderBy = 0; sSubBuild.pOrSet = &sCur; WHERETRACE(0x200, ("Begin processing OR-clause %p\n", pTerm)); for(pOrTerm=pOrWC->a; pOrTermeOperator & WO_AND)!=0 ){ sSubBuild.pWC = &pOrTerm->u.pAndInfo->wc; }else if( pOrTerm->leftCursor==iCur ){ tempWC.pWInfo = pWC->pWInfo; tempWC.pOuter = pWC; tempWC.op = TK_AND; tempWC.nTerm = 1; tempWC.a = pOrTerm; sSubBuild.pWC = &tempWC; }else{ continue; } sCur.n = 0; #ifdef WHERETRACE_ENABLED WHERETRACE(0x200, ("OR-term %d of %p has %d subterms:\n", (int)(pOrTerm-pOrWC->a), pTerm, sSubBuild.pWC->nTerm)); if( sqlite3WhereTrace & 0x400 ){ sqlite3WhereClausePrint(sSubBuild.pWC); } #endif #ifndef SQLITE_OMIT_VIRTUALTABLE if( IsVirtual(pItem->pTab) ){ rc = whereLoopAddVirtual(&sSubBuild, mPrereq, mUnusable); }else #endif { rc = whereLoopAddBtree(&sSubBuild, mPrereq); } if( rc==SQLITE_OK ){ rc = whereLoopAddOr(&sSubBuild, mPrereq, mUnusable); } assert( rc==SQLITE_OK || sCur.n==0 ); if( sCur.n==0 ){ sSum.n = 0; break; }else if( once ){ whereOrMove(&sSum, &sCur); once = 0; }else{ WhereOrSet sPrev; whereOrMove(&sPrev, &sSum); sSum.n = 0; for(i=0; inLTerm = 1; pNew->aLTerm[0] = pTerm; pNew->wsFlags = WHERE_MULTI_OR; pNew->rSetup = 0; pNew->iSortIdx = 0; memset(&pNew->u, 0, sizeof(pNew->u)); for(i=0; rc==SQLITE_OK && irRun = sSum.a[i].rRun + 1; pNew->nOut = sSum.a[i].nOut; pNew->prereq = sSum.a[i].prereq; rc = whereLoopInsert(pBuilder, pNew); } WHERETRACE(0x200, ("End processing OR-clause %p\n", pTerm)); } } return rc; } /* ** Add all WhereLoop objects for all tables */ static int whereLoopAddAll(WhereLoopBuilder *pBuilder){ WhereInfo *pWInfo = pBuilder->pWInfo; Bitmask mPrereq = 0; Bitmask mPrior = 0; int iTab; SrcList *pTabList = pWInfo->pTabList; struct SrcList_item *pItem; struct SrcList_item *pEnd = &pTabList->a[pWInfo->nLevel]; sqlite3 *db = pWInfo->pParse->db; int rc = SQLITE_OK; WhereLoop *pNew; u8 priorJointype = 0; /* Loop over the tables in the join, from left to right */ pNew = pBuilder->pNew; whereLoopInit(pNew); for(iTab=0, pItem=pTabList->a; pItemiTab = iTab; pNew->maskSelf = sqlite3WhereGetMask(&pWInfo->sMaskSet, pItem->iCursor); if( ((pItem->fg.jointype|priorJointype) & (JT_LEFT|JT_CROSS))!=0 ){ /* This condition is true when pItem is the FROM clause term on the ** right-hand-side of a LEFT or CROSS JOIN. */ mPrereq = mPrior; } priorJointype = pItem->fg.jointype; #ifndef SQLITE_OMIT_VIRTUALTABLE if( IsVirtual(pItem->pTab) ){ struct SrcList_item *p; for(p=&pItem[1]; pfg.jointype & (JT_LEFT|JT_CROSS)) ){ mUnusable |= sqlite3WhereGetMask(&pWInfo->sMaskSet, p->iCursor); } } rc = whereLoopAddVirtual(pBuilder, mPrereq, mUnusable); }else #endif /* SQLITE_OMIT_VIRTUALTABLE */ { rc = whereLoopAddBtree(pBuilder, mPrereq); } if( rc==SQLITE_OK ){ rc = whereLoopAddOr(pBuilder, mPrereq, mUnusable); } mPrior |= pNew->maskSelf; if( rc || db->mallocFailed ) break; } whereLoopClear(db, pNew); return rc; } /* ** Examine a WherePath (with the addition of the extra WhereLoop of the 5th ** parameters) to see if it outputs rows in the requested ORDER BY ** (or GROUP BY) without requiring a separate sort operation. Return N: ** ** N>0: N terms of the ORDER BY clause are satisfied ** N==0: No terms of the ORDER BY clause are satisfied ** N<0: Unknown yet how many terms of ORDER BY might be satisfied. ** ** Note that processing for WHERE_GROUPBY and WHERE_DISTINCTBY is not as ** strict. With GROUP BY and DISTINCT the only requirement is that ** equivalent rows appear immediately adjacent to one another. GROUP BY ** and DISTINCT do not require rows to appear in any particular order as long ** as equivalent rows are grouped together. Thus for GROUP BY and DISTINCT ** the pOrderBy terms can be matched in any order. With ORDER BY, the ** pOrderBy terms must be matched in strict left-to-right order. */ static i8 wherePathSatisfiesOrderBy( WhereInfo *pWInfo, /* The WHERE clause */ ExprList *pOrderBy, /* ORDER BY or GROUP BY or DISTINCT clause to check */ WherePath *pPath, /* The WherePath to check */ u16 wctrlFlags, /* WHERE_GROUPBY or _DISTINCTBY or _ORDERBY_LIMIT */ u16 nLoop, /* Number of entries in pPath->aLoop[] */ WhereLoop *pLast, /* Add this WhereLoop to the end of pPath->aLoop[] */ Bitmask *pRevMask /* OUT: Mask of WhereLoops to run in reverse order */ ){ u8 revSet; /* True if rev is known */ u8 rev; /* Composite sort order */ u8 revIdx; /* Index sort order */ u8 isOrderDistinct; /* All prior WhereLoops are order-distinct */ u8 distinctColumns; /* True if the loop has UNIQUE NOT NULL columns */ u8 isMatch; /* iColumn matches a term of the ORDER BY clause */ u16 eqOpMask; /* Allowed equality operators */ u16 nKeyCol; /* Number of key columns in pIndex */ u16 nColumn; /* Total number of ordered columns in the index */ u16 nOrderBy; /* Number terms in the ORDER BY clause */ int iLoop; /* Index of WhereLoop in pPath being processed */ int i, j; /* Loop counters */ int iCur; /* Cursor number for current WhereLoop */ int iColumn; /* A column number within table iCur */ WhereLoop *pLoop = 0; /* Current WhereLoop being processed. */ WhereTerm *pTerm; /* A single term of the WHERE clause */ Expr *pOBExpr; /* An expression from the ORDER BY clause */ CollSeq *pColl; /* COLLATE function from an ORDER BY clause term */ Index *pIndex; /* The index associated with pLoop */ sqlite3 *db = pWInfo->pParse->db; /* Database connection */ Bitmask obSat = 0; /* Mask of ORDER BY terms satisfied so far */ Bitmask obDone; /* Mask of all ORDER BY terms */ Bitmask orderDistinctMask; /* Mask of all well-ordered loops */ Bitmask ready; /* Mask of inner loops */ /* ** We say the WhereLoop is "one-row" if it generates no more than one ** row of output. A WhereLoop is one-row if all of the following are true: ** (a) All index columns match with WHERE_COLUMN_EQ. ** (b) The index is unique ** Any WhereLoop with an WHERE_COLUMN_EQ constraint on the rowid is one-row. ** Every one-row WhereLoop will have the WHERE_ONEROW bit set in wsFlags. ** ** We say the WhereLoop is "order-distinct" if the set of columns from ** that WhereLoop that are in the ORDER BY clause are different for every ** row of the WhereLoop. Every one-row WhereLoop is automatically ** order-distinct. A WhereLoop that has no columns in the ORDER BY clause ** is not order-distinct. To be order-distinct is not quite the same as being ** UNIQUE since a UNIQUE column or index can have multiple rows that ** are NULL and NULL values are equivalent for the purpose of order-distinct. ** To be order-distinct, the columns must be UNIQUE and NOT NULL. ** ** The rowid for a table is always UNIQUE and NOT NULL so whenever the ** rowid appears in the ORDER BY clause, the corresponding WhereLoop is ** automatically order-distinct. */ assert( pOrderBy!=0 ); if( nLoop && OptimizationDisabled(db, SQLITE_OrderByIdxJoin) ) return 0; nOrderBy = pOrderBy->nExpr; testcase( nOrderBy==BMS-1 ); if( nOrderBy>BMS-1 ) return 0; /* Cannot optimize overly large ORDER BYs */ isOrderDistinct = 1; obDone = MASKBIT(nOrderBy)-1; orderDistinctMask = 0; ready = 0; eqOpMask = WO_EQ | WO_IS | WO_ISNULL; if( wctrlFlags & WHERE_ORDERBY_LIMIT ) eqOpMask |= WO_IN; for(iLoop=0; isOrderDistinct && obSat0 ) ready |= pLoop->maskSelf; if( iLoopaLoop[iLoop]; if( wctrlFlags & WHERE_ORDERBY_LIMIT ) continue; }else{ pLoop = pLast; } if( pLoop->wsFlags & WHERE_VIRTUALTABLE ){ if( pLoop->u.vtab.isOrdered ) obSat = obDone; break; } iCur = pWInfo->pTabList->a[pLoop->iTab].iCursor; /* Mark off any ORDER BY term X that is a column in the table of ** the current loop for which there is term in the WHERE ** clause of the form X IS NULL or X=? that reference only outer ** loops. */ for(i=0; ia[i].pExpr); if( pOBExpr->op!=TK_COLUMN ) continue; if( pOBExpr->iTable!=iCur ) continue; pTerm = sqlite3WhereFindTerm(&pWInfo->sWC, iCur, pOBExpr->iColumn, ~ready, eqOpMask, 0); if( pTerm==0 ) continue; if( pTerm->eOperator==WO_IN ){ /* IN terms are only valid for sorting in the ORDER BY LIMIT ** optimization, and then only if they are actually used ** by the query plan */ assert( wctrlFlags & WHERE_ORDERBY_LIMIT ); for(j=0; jnLTerm && pTerm!=pLoop->aLTerm[j]; j++){} if( j>=pLoop->nLTerm ) continue; } if( (pTerm->eOperator&(WO_EQ|WO_IS))!=0 && pOBExpr->iColumn>=0 ){ const char *z1, *z2; pColl = sqlite3ExprCollSeq(pWInfo->pParse, pOrderBy->a[i].pExpr); if( !pColl ) pColl = db->pDfltColl; z1 = pColl->zName; pColl = sqlite3ExprCollSeq(pWInfo->pParse, pTerm->pExpr); if( !pColl ) pColl = db->pDfltColl; z2 = pColl->zName; if( sqlite3StrICmp(z1, z2)!=0 ) continue; testcase( pTerm->pExpr->op==TK_IS ); } obSat |= MASKBIT(i); } if( (pLoop->wsFlags & WHERE_ONEROW)==0 ){ if( pLoop->wsFlags & WHERE_IPK ){ pIndex = 0; nKeyCol = 0; nColumn = 1; }else if( (pIndex = pLoop->u.btree.pIndex)==0 || pIndex->bUnordered ){ return 0; }else{ nKeyCol = pIndex->nKeyCol; nColumn = pIndex->nColumn; assert( nColumn==nKeyCol+1 || !HasRowid(pIndex->pTable) ); assert( pIndex->aiColumn[nColumn-1]==XN_ROWID || !HasRowid(pIndex->pTable)); isOrderDistinct = IsUniqueIndex(pIndex); } /* Loop through all columns of the index and deal with the ones ** that are not constrained by == or IN. */ rev = revSet = 0; distinctColumns = 0; for(j=0; j=pLoop->u.btree.nEq || (pLoop->aLTerm[j]==0)==(jnSkip) ); if( ju.btree.nEq && j>=pLoop->nSkip ){ u16 eOp = pLoop->aLTerm[j]->eOperator; /* Skip over == and IS and ISNULL terms. (Also skip IN terms when ** doing WHERE_ORDERBY_LIMIT processing). ** ** If the current term is a column of an ((?,?) IN (SELECT...)) ** expression for which the SELECT returns more than one column, ** check that it is the only column used by this loop. Otherwise, ** if it is one of two or more, none of the columns can be ** considered to match an ORDER BY term. */ if( (eOp & eqOpMask)!=0 ){ if( eOp & WO_ISNULL ){ testcase( isOrderDistinct ); isOrderDistinct = 0; } continue; }else if( ALWAYS(eOp & WO_IN) ){ /* ALWAYS() justification: eOp is an equality operator due to the ** ju.btree.nEq constraint above. Any equality other ** than WO_IN is captured by the previous "if". So this one ** always has to be WO_IN. */ Expr *pX = pLoop->aLTerm[j]->pExpr; for(i=j+1; iu.btree.nEq; i++){ if( pLoop->aLTerm[i]->pExpr==pX ){ assert( (pLoop->aLTerm[i]->eOperator & WO_IN) ); bOnce = 0; break; } } } } /* Get the column number in the table (iColumn) and sort order ** (revIdx) for the j-th column of the index. */ if( pIndex ){ iColumn = pIndex->aiColumn[j]; revIdx = pIndex->aSortOrder[j]; if( iColumn==pIndex->pTable->iPKey ) iColumn = -1; }else{ iColumn = XN_ROWID; revIdx = 0; } /* An unconstrained column that might be NULL means that this ** WhereLoop is not well-ordered */ if( isOrderDistinct && iColumn>=0 && j>=pLoop->u.btree.nEq && pIndex->pTable->aCol[iColumn].notNull==0 ){ isOrderDistinct = 0; } /* Find the ORDER BY term that corresponds to the j-th column ** of the index and mark that ORDER BY term off */ isMatch = 0; for(i=0; bOnce && ia[i].pExpr); testcase( wctrlFlags & WHERE_GROUPBY ); testcase( wctrlFlags & WHERE_DISTINCTBY ); if( (wctrlFlags & (WHERE_GROUPBY|WHERE_DISTINCTBY))==0 ) bOnce = 0; if( iColumn>=(-1) ){ if( pOBExpr->op!=TK_COLUMN ) continue; if( pOBExpr->iTable!=iCur ) continue; if( pOBExpr->iColumn!=iColumn ) continue; }else{ if( sqlite3ExprCompare(pOBExpr,pIndex->aColExpr->a[j].pExpr,iCur) ){ continue; } } if( iColumn>=0 ){ pColl = sqlite3ExprCollSeq(pWInfo->pParse, pOrderBy->a[i].pExpr); if( !pColl ) pColl = db->pDfltColl; if( sqlite3StrICmp(pColl->zName, pIndex->azColl[j])!=0 ) continue; } isMatch = 1; break; } if( isMatch && (wctrlFlags & WHERE_GROUPBY)==0 ){ /* Make sure the sort order is compatible in an ORDER BY clause. ** Sort order is irrelevant for a GROUP BY clause. */ if( revSet ){ if( (rev ^ revIdx)!=pOrderBy->a[i].sortOrder ) isMatch = 0; }else{ rev = revIdx ^ pOrderBy->a[i].sortOrder; if( rev ) *pRevMask |= MASKBIT(iLoop); revSet = 1; } } if( isMatch ){ if( iColumn==XN_ROWID ){ testcase( distinctColumns==0 ); distinctColumns = 1; } obSat |= MASKBIT(i); }else{ /* No match found */ if( j==0 || jmaskSelf; for(i=0; ia[i].pExpr; mTerm = sqlite3WhereExprUsage(&pWInfo->sMaskSet,p); if( mTerm==0 && !sqlite3ExprIsConstant(p) ) continue; if( (mTerm&~orderDistinctMask)==0 ){ obSat |= MASKBIT(i); } } } } /* End the loop over all WhereLoops from outer-most down to inner-most */ if( obSat==obDone ) return (i8)nOrderBy; if( !isOrderDistinct ){ for(i=nOrderBy-1; i>0; i--){ Bitmask m = MASKBIT(i) - 1; if( (obSat&m)==m ) return i; } return 0; } return -1; } /* ** If the WHERE_GROUPBY flag is set in the mask passed to sqlite3WhereBegin(), ** the planner assumes that the specified pOrderBy list is actually a GROUP ** BY clause - and so any order that groups rows as required satisfies the ** request. ** ** Normally, in this case it is not possible for the caller to determine ** whether or not the rows are really being delivered in sorted order, or ** just in some other order that provides the required grouping. However, ** if the WHERE_SORTBYGROUP flag is also passed to sqlite3WhereBegin(), then ** this function may be called on the returned WhereInfo object. It returns ** true if the rows really will be sorted in the specified order, or false ** otherwise. ** ** For example, assuming: ** ** CREATE INDEX i1 ON t1(x, Y); ** ** then ** ** SELECT * FROM t1 GROUP BY x,y ORDER BY x,y; -- IsSorted()==1 ** SELECT * FROM t1 GROUP BY y,x ORDER BY y,x; -- IsSorted()==0 */ SQLITE_PRIVATE int sqlite3WhereIsSorted(WhereInfo *pWInfo){ assert( pWInfo->wctrlFlags & WHERE_GROUPBY ); assert( pWInfo->wctrlFlags & WHERE_SORTBYGROUP ); return pWInfo->sorted; } #ifdef WHERETRACE_ENABLED /* For debugging use only: */ static const char *wherePathName(WherePath *pPath, int nLoop, WhereLoop *pLast){ static char zName[65]; int i; for(i=0; iaLoop[i]->cId; } if( pLast ) zName[i++] = pLast->cId; zName[i] = 0; return zName; } #endif /* ** Return the cost of sorting nRow rows, assuming that the keys have ** nOrderby columns and that the first nSorted columns are already in ** order. */ static LogEst whereSortingCost( WhereInfo *pWInfo, LogEst nRow, int nOrderBy, int nSorted ){ /* TUNING: Estimated cost of a full external sort, where N is ** the number of rows to sort is: ** ** cost = (3.0 * N * log(N)). ** ** Or, if the order-by clause has X terms but only the last Y ** terms are out of order, then block-sorting will reduce the ** sorting cost to: ** ** cost = (3.0 * N * log(N)) * (Y/X) ** ** The (Y/X) term is implemented using stack variable rScale ** below. */ LogEst rScale, rSortCost; assert( nOrderBy>0 && 66==sqlite3LogEst(100) ); rScale = sqlite3LogEst((nOrderBy-nSorted)*100/nOrderBy) - 66; rSortCost = nRow + rScale + 16; /* Multiple by log(M) where M is the number of output rows. ** Use the LIMIT for M if it is smaller */ if( (pWInfo->wctrlFlags & WHERE_USE_LIMIT)!=0 && pWInfo->iLimitiLimit; } rSortCost += estLog(nRow); return rSortCost; } /* ** Given the list of WhereLoop objects at pWInfo->pLoops, this routine ** attempts to find the lowest cost path that visits each WhereLoop ** once. This path is then loaded into the pWInfo->a[].pWLoop fields. ** ** Assume that the total number of output rows that will need to be sorted ** will be nRowEst (in the 10*log2 representation). Or, ignore sorting ** costs if nRowEst==0. ** ** Return SQLITE_OK on success or SQLITE_NOMEM of a memory allocation ** error occurs. */ static int wherePathSolver(WhereInfo *pWInfo, LogEst nRowEst){ int mxChoice; /* Maximum number of simultaneous paths tracked */ int nLoop; /* Number of terms in the join */ Parse *pParse; /* Parsing context */ sqlite3 *db; /* The database connection */ int iLoop; /* Loop counter over the terms of the join */ int ii, jj; /* Loop counters */ int mxI = 0; /* Index of next entry to replace */ int nOrderBy; /* Number of ORDER BY clause terms */ LogEst mxCost = 0; /* Maximum cost of a set of paths */ LogEst mxUnsorted = 0; /* Maximum unsorted cost of a set of path */ int nTo, nFrom; /* Number of valid entries in aTo[] and aFrom[] */ WherePath *aFrom; /* All nFrom paths at the previous level */ WherePath *aTo; /* The nTo best paths at the current level */ WherePath *pFrom; /* An element of aFrom[] that we are working on */ WherePath *pTo; /* An element of aTo[] that we are working on */ WhereLoop *pWLoop; /* One of the WhereLoop objects */ WhereLoop **pX; /* Used to divy up the pSpace memory */ LogEst *aSortCost = 0; /* Sorting and partial sorting costs */ char *pSpace; /* Temporary memory used by this routine */ int nSpace; /* Bytes of space allocated at pSpace */ pParse = pWInfo->pParse; db = pParse->db; nLoop = pWInfo->nLevel; /* TUNING: For simple queries, only the best path is tracked. ** For 2-way joins, the 5 best paths are followed. ** For joins of 3 or more tables, track the 10 best paths */ mxChoice = (nLoop<=1) ? 1 : (nLoop==2 ? 5 : 10); assert( nLoop<=pWInfo->pTabList->nSrc ); WHERETRACE(0x002, ("---- begin solver. (nRowEst=%d)\n", nRowEst)); /* If nRowEst is zero and there is an ORDER BY clause, ignore it. In this ** case the purpose of this call is to estimate the number of rows returned ** by the overall query. Once this estimate has been obtained, the caller ** will invoke this function a second time, passing the estimate as the ** nRowEst parameter. */ if( pWInfo->pOrderBy==0 || nRowEst==0 ){ nOrderBy = 0; }else{ nOrderBy = pWInfo->pOrderBy->nExpr; } /* Allocate and initialize space for aTo, aFrom and aSortCost[] */ nSpace = (sizeof(WherePath)+sizeof(WhereLoop*)*nLoop)*mxChoice*2; nSpace += sizeof(LogEst) * nOrderBy; pSpace = sqlite3DbMallocRawNN(db, nSpace); if( pSpace==0 ) return SQLITE_NOMEM_BKPT; aTo = (WherePath*)pSpace; aFrom = aTo+mxChoice; memset(aFrom, 0, sizeof(aFrom[0])); pX = (WhereLoop**)(aFrom+mxChoice); for(ii=mxChoice*2, pFrom=aTo; ii>0; ii--, pFrom++, pX += nLoop){ pFrom->aLoop = pX; } if( nOrderBy ){ /* If there is an ORDER BY clause and it is not being ignored, set up ** space for the aSortCost[] array. Each element of the aSortCost array ** is either zero - meaning it has not yet been initialized - or the ** cost of sorting nRowEst rows of data where the first X terms of ** the ORDER BY clause are already in order, where X is the array ** index. */ aSortCost = (LogEst*)pX; memset(aSortCost, 0, sizeof(LogEst) * nOrderBy); } assert( aSortCost==0 || &pSpace[nSpace]==(char*)&aSortCost[nOrderBy] ); assert( aSortCost!=0 || &pSpace[nSpace]==(char*)pX ); /* Seed the search with a single WherePath containing zero WhereLoops. ** ** TUNING: Do not let the number of iterations go above 28. If the cost ** of computing an automatic index is not paid back within the first 28 ** rows, then do not use the automatic index. */ aFrom[0].nRow = MIN(pParse->nQueryLoop, 48); assert( 48==sqlite3LogEst(28) ); nFrom = 1; assert( aFrom[0].isOrdered==0 ); if( nOrderBy ){ /* If nLoop is zero, then there are no FROM terms in the query. Since ** in this case the query may return a maximum of one row, the results ** are already in the requested order. Set isOrdered to nOrderBy to ** indicate this. Or, if nLoop is greater than zero, set isOrdered to ** -1, indicating that the result set may or may not be ordered, ** depending on the loops added to the current plan. */ aFrom[0].isOrdered = nLoop>0 ? -1 : nOrderBy; } /* Compute successively longer WherePaths using the previous generation ** of WherePaths as the basis for the next. Keep track of the mxChoice ** best paths at each generation */ for(iLoop=0; iLooppLoops; pWLoop; pWLoop=pWLoop->pNextLoop){ LogEst nOut; /* Rows visited by (pFrom+pWLoop) */ LogEst rCost; /* Cost of path (pFrom+pWLoop) */ LogEst rUnsorted; /* Unsorted cost of (pFrom+pWLoop) */ i8 isOrdered = pFrom->isOrdered; /* isOrdered for (pFrom+pWLoop) */ Bitmask maskNew; /* Mask of src visited by (..) */ Bitmask revMask = 0; /* Mask of rev-order loops for (..) */ if( (pWLoop->prereq & ~pFrom->maskLoop)!=0 ) continue; if( (pWLoop->maskSelf & pFrom->maskLoop)!=0 ) continue; if( (pWLoop->wsFlags & WHERE_AUTO_INDEX)!=0 && pFrom->nRow<10 ){ /* Do not use an automatic index if the this loop is expected ** to run less than 2 times. */ assert( 10==sqlite3LogEst(2) ); continue; } /* At this point, pWLoop is a candidate to be the next loop. ** Compute its cost */ rUnsorted = sqlite3LogEstAdd(pWLoop->rSetup,pWLoop->rRun + pFrom->nRow); rUnsorted = sqlite3LogEstAdd(rUnsorted, pFrom->rUnsorted); nOut = pFrom->nRow + pWLoop->nOut; maskNew = pFrom->maskLoop | pWLoop->maskSelf; if( isOrdered<0 ){ isOrdered = wherePathSatisfiesOrderBy(pWInfo, pWInfo->pOrderBy, pFrom, pWInfo->wctrlFlags, iLoop, pWLoop, &revMask); }else{ revMask = pFrom->revLoop; } if( isOrdered>=0 && isOrderedisOrdered^isOrdered)&0x80)==0" is equivalent ** to (pTo->isOrdered==(-1))==(isOrdered==(-1))" for the range ** of legal values for isOrdered, -1..64. */ for(jj=0, pTo=aTo; jjmaskLoop==maskNew && ((pTo->isOrdered^isOrdered)&0x80)==0 ){ testcase( jj==nTo-1 ); break; } } if( jj>=nTo ){ /* None of the existing best-so-far paths match the candidate. */ if( nTo>=mxChoice && (rCost>mxCost || (rCost==mxCost && rUnsorted>=mxUnsorted)) ){ /* The current candidate is no better than any of the mxChoice ** paths currently in the best-so-far buffer. So discard ** this candidate as not viable. */ #ifdef WHERETRACE_ENABLED /* 0x4 */ if( sqlite3WhereTrace&0x4 ){ sqlite3DebugPrintf("Skip %s cost=%-3d,%3d order=%c\n", wherePathName(pFrom, iLoop, pWLoop), rCost, nOut, isOrdered>=0 ? isOrdered+'0' : '?'); } #endif continue; } /* If we reach this points it means that the new candidate path ** needs to be added to the set of best-so-far paths. */ if( nTo=0 ? isOrdered+'0' : '?'); } #endif }else{ /* Control reaches here if best-so-far path pTo=aTo[jj] covers the ** same set of loops and has the sam isOrdered setting as the ** candidate path. Check to see if the candidate should replace ** pTo or if the candidate should be skipped */ if( pTo->rCostrCost==rCost && pTo->nRow<=nOut) ){ #ifdef WHERETRACE_ENABLED /* 0x4 */ if( sqlite3WhereTrace&0x4 ){ sqlite3DebugPrintf( "Skip %s cost=%-3d,%3d order=%c", wherePathName(pFrom, iLoop, pWLoop), rCost, nOut, isOrdered>=0 ? isOrdered+'0' : '?'); sqlite3DebugPrintf(" vs %s cost=%-3d,%d order=%c\n", wherePathName(pTo, iLoop+1, 0), pTo->rCost, pTo->nRow, pTo->isOrdered>=0 ? pTo->isOrdered+'0' : '?'); } #endif /* Discard the candidate path from further consideration */ testcase( pTo->rCost==rCost ); continue; } testcase( pTo->rCost==rCost+1 ); /* Control reaches here if the candidate path is better than the ** pTo path. Replace pTo with the candidate. */ #ifdef WHERETRACE_ENABLED /* 0x4 */ if( sqlite3WhereTrace&0x4 ){ sqlite3DebugPrintf( "Update %s cost=%-3d,%3d order=%c", wherePathName(pFrom, iLoop, pWLoop), rCost, nOut, isOrdered>=0 ? isOrdered+'0' : '?'); sqlite3DebugPrintf(" was %s cost=%-3d,%3d order=%c\n", wherePathName(pTo, iLoop+1, 0), pTo->rCost, pTo->nRow, pTo->isOrdered>=0 ? pTo->isOrdered+'0' : '?'); } #endif } /* pWLoop is a winner. Add it to the set of best so far */ pTo->maskLoop = pFrom->maskLoop | pWLoop->maskSelf; pTo->revLoop = revMask; pTo->nRow = nOut; pTo->rCost = rCost; pTo->rUnsorted = rUnsorted; pTo->isOrdered = isOrdered; memcpy(pTo->aLoop, pFrom->aLoop, sizeof(WhereLoop*)*iLoop); pTo->aLoop[iLoop] = pWLoop; if( nTo>=mxChoice ){ mxI = 0; mxCost = aTo[0].rCost; mxUnsorted = aTo[0].nRow; for(jj=1, pTo=&aTo[1]; jjrCost>mxCost || (pTo->rCost==mxCost && pTo->rUnsorted>mxUnsorted) ){ mxCost = pTo->rCost; mxUnsorted = pTo->rUnsorted; mxI = jj; } } } } } #ifdef WHERETRACE_ENABLED /* >=2 */ if( sqlite3WhereTrace & 0x02 ){ sqlite3DebugPrintf("---- after round %d ----\n", iLoop); for(ii=0, pTo=aTo; iirCost, pTo->nRow, pTo->isOrdered>=0 ? (pTo->isOrdered+'0') : '?'); if( pTo->isOrdered>0 ){ sqlite3DebugPrintf(" rev=0x%llx\n", pTo->revLoop); }else{ sqlite3DebugPrintf("\n"); } } } #endif /* Swap the roles of aFrom and aTo for the next generation */ pFrom = aTo; aTo = aFrom; aFrom = pFrom; nFrom = nTo; } if( nFrom==0 ){ sqlite3ErrorMsg(pParse, "no query solution"); sqlite3DbFree(db, pSpace); return SQLITE_ERROR; } /* Find the lowest cost path. pFrom will be left pointing to that path */ pFrom = aFrom; for(ii=1; iirCost>aFrom[ii].rCost ) pFrom = &aFrom[ii]; } assert( pWInfo->nLevel==nLoop ); /* Load the lowest cost path into pWInfo */ for(iLoop=0; iLoopa + iLoop; pLevel->pWLoop = pWLoop = pFrom->aLoop[iLoop]; pLevel->iFrom = pWLoop->iTab; pLevel->iTabCur = pWInfo->pTabList->a[pLevel->iFrom].iCursor; } if( (pWInfo->wctrlFlags & WHERE_WANT_DISTINCT)!=0 && (pWInfo->wctrlFlags & WHERE_DISTINCTBY)==0 && pWInfo->eDistinct==WHERE_DISTINCT_NOOP && nRowEst ){ Bitmask notUsed; int rc = wherePathSatisfiesOrderBy(pWInfo, pWInfo->pDistinctSet, pFrom, WHERE_DISTINCTBY, nLoop-1, pFrom->aLoop[nLoop-1], ¬Used); if( rc==pWInfo->pDistinctSet->nExpr ){ pWInfo->eDistinct = WHERE_DISTINCT_ORDERED; } } if( pWInfo->pOrderBy ){ if( pWInfo->wctrlFlags & WHERE_DISTINCTBY ){ if( pFrom->isOrdered==pWInfo->pOrderBy->nExpr ){ pWInfo->eDistinct = WHERE_DISTINCT_ORDERED; } }else{ pWInfo->nOBSat = pFrom->isOrdered; pWInfo->revMask = pFrom->revLoop; if( pWInfo->nOBSat<=0 ){ pWInfo->nOBSat = 0; if( nLoop>0 ){ u32 wsFlags = pFrom->aLoop[nLoop-1]->wsFlags; if( (wsFlags & WHERE_ONEROW)==0 && (wsFlags&(WHERE_IPK|WHERE_COLUMN_IN))!=(WHERE_IPK|WHERE_COLUMN_IN) ){ Bitmask m = 0; int rc = wherePathSatisfiesOrderBy(pWInfo, pWInfo->pOrderBy, pFrom, WHERE_ORDERBY_LIMIT, nLoop-1, pFrom->aLoop[nLoop-1], &m); testcase( wsFlags & WHERE_IPK ); testcase( wsFlags & WHERE_COLUMN_IN ); if( rc==pWInfo->pOrderBy->nExpr ){ pWInfo->bOrderedInnerLoop = 1; pWInfo->revMask = m; } } } } } if( (pWInfo->wctrlFlags & WHERE_SORTBYGROUP) && pWInfo->nOBSat==pWInfo->pOrderBy->nExpr && nLoop>0 ){ Bitmask revMask = 0; int nOrder = wherePathSatisfiesOrderBy(pWInfo, pWInfo->pOrderBy, pFrom, 0, nLoop-1, pFrom->aLoop[nLoop-1], &revMask ); assert( pWInfo->sorted==0 ); if( nOrder==pWInfo->pOrderBy->nExpr ){ pWInfo->sorted = 1; pWInfo->revMask = revMask; } } } pWInfo->nRowOut = pFrom->nRow; /* Free temporary memory and return success */ sqlite3DbFree(db, pSpace); return SQLITE_OK; } /* ** Most queries use only a single table (they are not joins) and have ** simple == constraints against indexed fields. This routine attempts ** to plan those simple cases using much less ceremony than the ** general-purpose query planner, and thereby yield faster sqlite3_prepare() ** times for the common case. ** ** Return non-zero on success, if this query can be handled by this ** no-frills query planner. Return zero if this query needs the ** general-purpose query planner. */ static int whereShortCut(WhereLoopBuilder *pBuilder){ WhereInfo *pWInfo; struct SrcList_item *pItem; WhereClause *pWC; WhereTerm *pTerm; WhereLoop *pLoop; int iCur; int j; Table *pTab; Index *pIdx; pWInfo = pBuilder->pWInfo; if( pWInfo->wctrlFlags & WHERE_OR_SUBCLAUSE ) return 0; assert( pWInfo->pTabList->nSrc>=1 ); pItem = pWInfo->pTabList->a; pTab = pItem->pTab; if( IsVirtual(pTab) ) return 0; if( pItem->fg.isIndexedBy ) return 0; iCur = pItem->iCursor; pWC = &pWInfo->sWC; pLoop = pBuilder->pNew; pLoop->wsFlags = 0; pLoop->nSkip = 0; pTerm = sqlite3WhereFindTerm(pWC, iCur, -1, 0, WO_EQ|WO_IS, 0); if( pTerm ){ testcase( pTerm->eOperator & WO_IS ); pLoop->wsFlags = WHERE_COLUMN_EQ|WHERE_IPK|WHERE_ONEROW; pLoop->aLTerm[0] = pTerm; pLoop->nLTerm = 1; pLoop->u.btree.nEq = 1; /* TUNING: Cost of a rowid lookup is 10 */ pLoop->rRun = 33; /* 33==sqlite3LogEst(10) */ }else{ for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){ int opMask; assert( pLoop->aLTermSpace==pLoop->aLTerm ); if( !IsUniqueIndex(pIdx) || pIdx->pPartIdxWhere!=0 || pIdx->nKeyCol>ArraySize(pLoop->aLTermSpace) ) continue; opMask = pIdx->uniqNotNull ? (WO_EQ|WO_IS) : WO_EQ; for(j=0; jnKeyCol; j++){ pTerm = sqlite3WhereFindTerm(pWC, iCur, j, 0, opMask, pIdx); if( pTerm==0 ) break; testcase( pTerm->eOperator & WO_IS ); pLoop->aLTerm[j] = pTerm; } if( j!=pIdx->nKeyCol ) continue; pLoop->wsFlags = WHERE_COLUMN_EQ|WHERE_ONEROW|WHERE_INDEXED; if( pIdx->isCovering || (pItem->colUsed & ~columnsInIndex(pIdx))==0 ){ pLoop->wsFlags |= WHERE_IDX_ONLY; } pLoop->nLTerm = j; pLoop->u.btree.nEq = j; pLoop->u.btree.pIndex = pIdx; /* TUNING: Cost of a unique index lookup is 15 */ pLoop->rRun = 39; /* 39==sqlite3LogEst(15) */ break; } } if( pLoop->wsFlags ){ pLoop->nOut = (LogEst)1; pWInfo->a[0].pWLoop = pLoop; pLoop->maskSelf = sqlite3WhereGetMask(&pWInfo->sMaskSet, iCur); pWInfo->a[0].iTabCur = iCur; pWInfo->nRowOut = 1; if( pWInfo->pOrderBy ) pWInfo->nOBSat = pWInfo->pOrderBy->nExpr; if( pWInfo->wctrlFlags & WHERE_WANT_DISTINCT ){ pWInfo->eDistinct = WHERE_DISTINCT_UNIQUE; } #ifdef SQLITE_DEBUG pLoop->cId = '0'; #endif return 1; } return 0; } /* ** Generate the beginning of the loop used for WHERE clause processing. ** The return value is a pointer to an opaque structure that contains ** information needed to terminate the loop. Later, the calling routine ** should invoke sqlite3WhereEnd() with the return value of this function ** in order to complete the WHERE clause processing. ** ** If an error occurs, this routine returns NULL. ** ** The basic idea is to do a nested loop, one loop for each table in ** the FROM clause of a select. (INSERT and UPDATE statements are the ** same as a SELECT with only a single table in the FROM clause.) For ** example, if the SQL is this: ** ** SELECT * FROM t1, t2, t3 WHERE ...; ** ** Then the code generated is conceptually like the following: ** ** foreach row1 in t1 do \ Code generated ** foreach row2 in t2 do |-- by sqlite3WhereBegin() ** foreach row3 in t3 do / ** ... ** end \ Code generated ** end |-- by sqlite3WhereEnd() ** end / ** ** Note that the loops might not be nested in the order in which they ** appear in the FROM clause if a different order is better able to make ** use of indices. Note also that when the IN operator appears in ** the WHERE clause, it might result in additional nested loops for ** scanning through all values on the right-hand side of the IN. ** ** There are Btree cursors associated with each table. t1 uses cursor ** number pTabList->a[0].iCursor. t2 uses the cursor pTabList->a[1].iCursor. ** And so forth. This routine generates code to open those VDBE cursors ** and sqlite3WhereEnd() generates the code to close them. ** ** The code that sqlite3WhereBegin() generates leaves the cursors named ** in pTabList pointing at their appropriate entries. The [...] code ** can use OP_Column and OP_Rowid opcodes on these cursors to extract ** data from the various tables of the loop. ** ** If the WHERE clause is empty, the foreach loops must each scan their ** entire tables. Thus a three-way join is an O(N^3) operation. But if ** the tables have indices and there are terms in the WHERE clause that ** refer to those indices, a complete table scan can be avoided and the ** code will run much faster. Most of the work of this routine is checking ** to see if there are indices that can be used to speed up the loop. ** ** Terms of the WHERE clause are also used to limit which rows actually ** make it to the "..." in the middle of the loop. After each "foreach", ** terms of the WHERE clause that use only terms in that loop and outer ** loops are evaluated and if false a jump is made around all subsequent ** inner loops (or around the "..." if the test occurs within the inner- ** most loop) ** ** OUTER JOINS ** ** An outer join of tables t1 and t2 is conceptally coded as follows: ** ** foreach row1 in t1 do ** flag = 0 ** foreach row2 in t2 do ** start: ** ... ** flag = 1 ** end ** if flag==0 then ** move the row2 cursor to a null row ** goto start ** fi ** end ** ** ORDER BY CLAUSE PROCESSING ** ** pOrderBy is a pointer to the ORDER BY clause (or the GROUP BY clause ** if the WHERE_GROUPBY flag is set in wctrlFlags) of a SELECT statement ** if there is one. If there is no ORDER BY clause or if this routine ** is called from an UPDATE or DELETE statement, then pOrderBy is NULL. ** ** The iIdxCur parameter is the cursor number of an index. If ** WHERE_OR_SUBCLAUSE is set, iIdxCur is the cursor number of an index ** to use for OR clause processing. The WHERE clause should use this ** specific cursor. If WHERE_ONEPASS_DESIRED is set, then iIdxCur is ** the first cursor in an array of cursors for all indices. iIdxCur should ** be used to compute the appropriate cursor depending on which index is ** used. */ SQLITE_PRIVATE WhereInfo *sqlite3WhereBegin( Parse *pParse, /* The parser context */ SrcList *pTabList, /* FROM clause: A list of all tables to be scanned */ Expr *pWhere, /* The WHERE clause */ ExprList *pOrderBy, /* An ORDER BY (or GROUP BY) clause, or NULL */ ExprList *pDistinctSet, /* Try not to output two rows that duplicate these */ u16 wctrlFlags, /* The WHERE_* flags defined in sqliteInt.h */ int iAuxArg /* If WHERE_OR_SUBCLAUSE is set, index cursor number ** If WHERE_USE_LIMIT, then the limit amount */ ){ int nByteWInfo; /* Num. bytes allocated for WhereInfo struct */ int nTabList; /* Number of elements in pTabList */ WhereInfo *pWInfo; /* Will become the return value of this function */ Vdbe *v = pParse->pVdbe; /* The virtual database engine */ Bitmask notReady; /* Cursors that are not yet positioned */ WhereLoopBuilder sWLB; /* The WhereLoop builder */ WhereMaskSet *pMaskSet; /* The expression mask set */ WhereLevel *pLevel; /* A single level in pWInfo->a[] */ WhereLoop *pLoop; /* Pointer to a single WhereLoop object */ int ii; /* Loop counter */ sqlite3 *db; /* Database connection */ int rc; /* Return code */ u8 bFordelete = 0; /* OPFLAG_FORDELETE or zero, as appropriate */ assert( (wctrlFlags & WHERE_ONEPASS_MULTIROW)==0 || ( (wctrlFlags & WHERE_ONEPASS_DESIRED)!=0 && (wctrlFlags & WHERE_OR_SUBCLAUSE)==0 )); /* Only one of WHERE_OR_SUBCLAUSE or WHERE_USE_LIMIT */ assert( (wctrlFlags & WHERE_OR_SUBCLAUSE)==0 || (wctrlFlags & WHERE_USE_LIMIT)==0 ); /* Variable initialization */ db = pParse->db; memset(&sWLB, 0, sizeof(sWLB)); /* An ORDER/GROUP BY clause of more than 63 terms cannot be optimized */ testcase( pOrderBy && pOrderBy->nExpr==BMS-1 ); if( pOrderBy && pOrderBy->nExpr>=BMS ) pOrderBy = 0; sWLB.pOrderBy = pOrderBy; /* Disable the DISTINCT optimization if SQLITE_DistinctOpt is set via ** sqlite3_test_ctrl(SQLITE_TESTCTRL_OPTIMIZATIONS,...) */ if( OptimizationDisabled(db, SQLITE_DistinctOpt) ){ wctrlFlags &= ~WHERE_WANT_DISTINCT; } /* The number of tables in the FROM clause is limited by the number of ** bits in a Bitmask */ testcase( pTabList->nSrc==BMS ); if( pTabList->nSrc>BMS ){ sqlite3ErrorMsg(pParse, "at most %d tables in a join", BMS); return 0; } /* This function normally generates a nested loop for all tables in ** pTabList. But if the WHERE_OR_SUBCLAUSE flag is set, then we should ** only generate code for the first table in pTabList and assume that ** any cursors associated with subsequent tables are uninitialized. */ nTabList = (wctrlFlags & WHERE_OR_SUBCLAUSE) ? 1 : pTabList->nSrc; /* Allocate and initialize the WhereInfo structure that will become the ** return value. A single allocation is used to store the WhereInfo ** struct, the contents of WhereInfo.a[], the WhereClause structure ** and the WhereMaskSet structure. Since WhereClause contains an 8-byte ** field (type Bitmask) it must be aligned on an 8-byte boundary on ** some architectures. Hence the ROUND8() below. */ nByteWInfo = ROUND8(sizeof(WhereInfo)+(nTabList-1)*sizeof(WhereLevel)); pWInfo = sqlite3DbMallocRawNN(db, nByteWInfo + sizeof(WhereLoop)); if( db->mallocFailed ){ sqlite3DbFree(db, pWInfo); pWInfo = 0; goto whereBeginError; } pWInfo->pParse = pParse; pWInfo->pTabList = pTabList; pWInfo->pOrderBy = pOrderBy; pWInfo->pDistinctSet = pDistinctSet; pWInfo->aiCurOnePass[0] = pWInfo->aiCurOnePass[1] = -1; pWInfo->nLevel = nTabList; pWInfo->iBreak = pWInfo->iContinue = sqlite3VdbeMakeLabel(v); pWInfo->wctrlFlags = wctrlFlags; pWInfo->iLimit = iAuxArg; pWInfo->savedNQueryLoop = pParse->nQueryLoop; memset(&pWInfo->nOBSat, 0, offsetof(WhereInfo,sWC) - offsetof(WhereInfo,nOBSat)); memset(&pWInfo->a[0], 0, sizeof(WhereLoop)+nTabList*sizeof(WhereLevel)); assert( pWInfo->eOnePass==ONEPASS_OFF ); /* ONEPASS defaults to OFF */ pMaskSet = &pWInfo->sMaskSet; sWLB.pWInfo = pWInfo; sWLB.pWC = &pWInfo->sWC; sWLB.pNew = (WhereLoop*)(((char*)pWInfo)+nByteWInfo); assert( EIGHT_BYTE_ALIGNMENT(sWLB.pNew) ); whereLoopInit(sWLB.pNew); #ifdef SQLITE_DEBUG sWLB.pNew->cId = '*'; #endif /* Split the WHERE clause into separate subexpressions where each ** subexpression is separated by an AND operator. */ initMaskSet(pMaskSet); sqlite3WhereClauseInit(&pWInfo->sWC, pWInfo); sqlite3WhereSplit(&pWInfo->sWC, pWhere, TK_AND); /* Special case: a WHERE clause that is constant. Evaluate the ** expression and either jump over all of the code or fall thru. */ for(ii=0; iinTerm; ii++){ if( nTabList==0 || sqlite3ExprIsConstantNotJoin(sWLB.pWC->a[ii].pExpr) ){ sqlite3ExprIfFalse(pParse, sWLB.pWC->a[ii].pExpr, pWInfo->iBreak, SQLITE_JUMPIFNULL); sWLB.pWC->a[ii].wtFlags |= TERM_CODED; } } /* Special case: No FROM clause */ if( nTabList==0 ){ if( pOrderBy ) pWInfo->nOBSat = pOrderBy->nExpr; if( wctrlFlags & WHERE_WANT_DISTINCT ){ pWInfo->eDistinct = WHERE_DISTINCT_UNIQUE; } } /* Assign a bit from the bitmask to every term in the FROM clause. ** ** The N-th term of the FROM clause is assigned a bitmask of 1<nSrc tables in ** pTabList, not just the first nTabList tables. nTabList is normally ** equal to pTabList->nSrc but might be shortened to 1 if the ** WHERE_OR_SUBCLAUSE flag is set. */ for(ii=0; iinSrc; ii++){ createMask(pMaskSet, pTabList->a[ii].iCursor); sqlite3WhereTabFuncArgs(pParse, &pTabList->a[ii], &pWInfo->sWC); } #ifdef SQLITE_DEBUG for(ii=0; iinSrc; ii++){ Bitmask m = sqlite3WhereGetMask(pMaskSet, pTabList->a[ii].iCursor); assert( m==MASKBIT(ii) ); } #endif /* Analyze all of the subexpressions. */ sqlite3WhereExprAnalyze(pTabList, &pWInfo->sWC); if( db->mallocFailed ) goto whereBeginError; if( wctrlFlags & WHERE_WANT_DISTINCT ){ if( isDistinctRedundant(pParse, pTabList, &pWInfo->sWC, pDistinctSet) ){ /* The DISTINCT marking is pointless. Ignore it. */ pWInfo->eDistinct = WHERE_DISTINCT_UNIQUE; }else if( pOrderBy==0 ){ /* Try to ORDER BY the result set to make distinct processing easier */ pWInfo->wctrlFlags |= WHERE_DISTINCTBY; pWInfo->pOrderBy = pDistinctSet; } } /* Construct the WhereLoop objects */ #if defined(WHERETRACE_ENABLED) if( sqlite3WhereTrace & 0xffff ){ sqlite3DebugPrintf("*** Optimizer Start *** (wctrlFlags: 0x%x",wctrlFlags); if( wctrlFlags & WHERE_USE_LIMIT ){ sqlite3DebugPrintf(", limit: %d", iAuxArg); } sqlite3DebugPrintf(")\n"); } if( sqlite3WhereTrace & 0x100 ){ /* Display all terms of the WHERE clause */ sqlite3WhereClausePrint(sWLB.pWC); } #endif if( nTabList!=1 || whereShortCut(&sWLB)==0 ){ rc = whereLoopAddAll(&sWLB); if( rc ) goto whereBeginError; #ifdef WHERETRACE_ENABLED if( sqlite3WhereTrace ){ /* Display all of the WhereLoop objects */ WhereLoop *p; int i; static const char zLabel[] = "0123456789abcdefghijklmnopqrstuvwyxz" "ABCDEFGHIJKLMNOPQRSTUVWYXZ"; for(p=pWInfo->pLoops, i=0; p; p=p->pNextLoop, i++){ p->cId = zLabel[i%sizeof(zLabel)]; whereLoopPrint(p, sWLB.pWC); } } #endif wherePathSolver(pWInfo, 0); if( db->mallocFailed ) goto whereBeginError; if( pWInfo->pOrderBy ){ wherePathSolver(pWInfo, pWInfo->nRowOut+1); if( db->mallocFailed ) goto whereBeginError; } } if( pWInfo->pOrderBy==0 && (db->flags & SQLITE_ReverseOrder)!=0 ){ pWInfo->revMask = ALLBITS; } if( pParse->nErr || NEVER(db->mallocFailed) ){ goto whereBeginError; } #ifdef WHERETRACE_ENABLED if( sqlite3WhereTrace ){ sqlite3DebugPrintf("---- Solution nRow=%d", pWInfo->nRowOut); if( pWInfo->nOBSat>0 ){ sqlite3DebugPrintf(" ORDERBY=%d,0x%llx", pWInfo->nOBSat, pWInfo->revMask); } switch( pWInfo->eDistinct ){ case WHERE_DISTINCT_UNIQUE: { sqlite3DebugPrintf(" DISTINCT=unique"); break; } case WHERE_DISTINCT_ORDERED: { sqlite3DebugPrintf(" DISTINCT=ordered"); break; } case WHERE_DISTINCT_UNORDERED: { sqlite3DebugPrintf(" DISTINCT=unordered"); break; } } sqlite3DebugPrintf("\n"); for(ii=0; iinLevel; ii++){ whereLoopPrint(pWInfo->a[ii].pWLoop, sWLB.pWC); } } #endif /* Attempt to omit tables from the join that do not effect the result */ if( pWInfo->nLevel>=2 && pDistinctSet!=0 && OptimizationEnabled(db, SQLITE_OmitNoopJoin) ){ Bitmask tabUsed = sqlite3WhereExprListUsage(pMaskSet, pDistinctSet); if( sWLB.pOrderBy ){ tabUsed |= sqlite3WhereExprListUsage(pMaskSet, sWLB.pOrderBy); } while( pWInfo->nLevel>=2 ){ WhereTerm *pTerm, *pEnd; pLoop = pWInfo->a[pWInfo->nLevel-1].pWLoop; if( (pWInfo->pTabList->a[pLoop->iTab].fg.jointype & JT_LEFT)==0 ) break; if( (wctrlFlags & WHERE_WANT_DISTINCT)==0 && (pLoop->wsFlags & WHERE_ONEROW)==0 ){ break; } if( (tabUsed & pLoop->maskSelf)!=0 ) break; pEnd = sWLB.pWC->a + sWLB.pWC->nTerm; for(pTerm=sWLB.pWC->a; pTermprereqAll & pLoop->maskSelf)!=0 && !ExprHasProperty(pTerm->pExpr, EP_FromJoin) ){ break; } } if( pTerm drop loop %c not used\n", pLoop->cId)); pWInfo->nLevel--; nTabList--; } } WHERETRACE(0xffff,("*** Optimizer Finished ***\n")); pWInfo->pParse->nQueryLoop += pWInfo->nRowOut; /* If the caller is an UPDATE or DELETE statement that is requesting ** to use a one-pass algorithm, determine if this is appropriate. */ assert( (wctrlFlags & WHERE_ONEPASS_DESIRED)==0 || pWInfo->nLevel==1 ); if( (wctrlFlags & WHERE_ONEPASS_DESIRED)!=0 ){ int wsFlags = pWInfo->a[0].pWLoop->wsFlags; int bOnerow = (wsFlags & WHERE_ONEROW)!=0; if( bOnerow || ((wctrlFlags & WHERE_ONEPASS_MULTIROW)!=0 && 0==(wsFlags & WHERE_VIRTUALTABLE)) ){ pWInfo->eOnePass = bOnerow ? ONEPASS_SINGLE : ONEPASS_MULTI; if( HasRowid(pTabList->a[0].pTab) && (wsFlags & WHERE_IDX_ONLY) ){ if( wctrlFlags & WHERE_ONEPASS_MULTIROW ){ bFordelete = OPFLAG_FORDELETE; } pWInfo->a[0].pWLoop->wsFlags = (wsFlags & ~WHERE_IDX_ONLY); } } } /* Open all tables in the pTabList and any indices selected for ** searching those tables. */ for(ii=0, pLevel=pWInfo->a; iia[pLevel->iFrom]; pTab = pTabItem->pTab; iDb = sqlite3SchemaToIndex(db, pTab->pSchema); pLoop = pLevel->pWLoop; if( (pTab->tabFlags & TF_Ephemeral)!=0 || pTab->pSelect ){ /* Do nothing */ }else #ifndef SQLITE_OMIT_VIRTUALTABLE if( (pLoop->wsFlags & WHERE_VIRTUALTABLE)!=0 ){ const char *pVTab = (const char *)sqlite3GetVTable(db, pTab); int iCur = pTabItem->iCursor; sqlite3VdbeAddOp4(v, OP_VOpen, iCur, 0, 0, pVTab, P4_VTAB); }else if( IsVirtual(pTab) ){ /* noop */ }else #endif if( (pLoop->wsFlags & WHERE_IDX_ONLY)==0 && (wctrlFlags & WHERE_OR_SUBCLAUSE)==0 ){ int op = OP_OpenRead; if( pWInfo->eOnePass!=ONEPASS_OFF ){ op = OP_OpenWrite; pWInfo->aiCurOnePass[0] = pTabItem->iCursor; }; sqlite3OpenTable(pParse, pTabItem->iCursor, iDb, pTab, op); assert( pTabItem->iCursor==pLevel->iTabCur ); testcase( pWInfo->eOnePass==ONEPASS_OFF && pTab->nCol==BMS-1 ); testcase( pWInfo->eOnePass==ONEPASS_OFF && pTab->nCol==BMS ); if( pWInfo->eOnePass==ONEPASS_OFF && pTab->nColcolUsed; int n = 0; for(; b; b=b>>1, n++){} sqlite3VdbeChangeP4(v, -1, SQLITE_INT_TO_PTR(n), P4_INT32); assert( n<=pTab->nCol ); } #ifdef SQLITE_ENABLE_CURSOR_HINTS if( pLoop->u.btree.pIndex!=0 ){ sqlite3VdbeChangeP5(v, OPFLAG_SEEKEQ|bFordelete); }else #endif { sqlite3VdbeChangeP5(v, bFordelete); } #ifdef SQLITE_ENABLE_COLUMN_USED_MASK sqlite3VdbeAddOp4Dup8(v, OP_ColumnsUsed, pTabItem->iCursor, 0, 0, (const u8*)&pTabItem->colUsed, P4_INT64); #endif }else{ sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName); } if( pLoop->wsFlags & WHERE_INDEXED ){ Index *pIx = pLoop->u.btree.pIndex; int iIndexCur; int op = OP_OpenRead; /* iAuxArg is always set if to a positive value if ONEPASS is possible */ assert( iAuxArg!=0 || (pWInfo->wctrlFlags & WHERE_ONEPASS_DESIRED)==0 ); if( !HasRowid(pTab) && IsPrimaryKeyIndex(pIx) && (wctrlFlags & WHERE_OR_SUBCLAUSE)!=0 ){ /* This is one term of an OR-optimization using the PRIMARY KEY of a ** WITHOUT ROWID table. No need for a separate index */ iIndexCur = pLevel->iTabCur; op = 0; }else if( pWInfo->eOnePass!=ONEPASS_OFF ){ Index *pJ = pTabItem->pTab->pIndex; iIndexCur = iAuxArg; assert( wctrlFlags & WHERE_ONEPASS_DESIRED ); while( ALWAYS(pJ) && pJ!=pIx ){ iIndexCur++; pJ = pJ->pNext; } op = OP_OpenWrite; pWInfo->aiCurOnePass[1] = iIndexCur; }else if( iAuxArg && (wctrlFlags & WHERE_OR_SUBCLAUSE)!=0 ){ iIndexCur = iAuxArg; op = OP_ReopenIdx; }else{ iIndexCur = pParse->nTab++; } pLevel->iIdxCur = iIndexCur; assert( pIx->pSchema==pTab->pSchema ); assert( iIndexCur>=0 ); if( op ){ sqlite3VdbeAddOp3(v, op, iIndexCur, pIx->tnum, iDb); sqlite3VdbeSetP4KeyInfo(pParse, pIx); if( (pLoop->wsFlags & WHERE_CONSTRAINT)!=0 && (pLoop->wsFlags & (WHERE_COLUMN_RANGE|WHERE_SKIPSCAN))==0 && (pWInfo->wctrlFlags&WHERE_ORDERBY_MIN)==0 ){ sqlite3VdbeChangeP5(v, OPFLAG_SEEKEQ); /* Hint to COMDB2 */ } VdbeComment((v, "%s", pIx->zName)); #ifdef SQLITE_ENABLE_COLUMN_USED_MASK { u64 colUsed = 0; int ii, jj; for(ii=0; iinColumn; ii++){ jj = pIx->aiColumn[ii]; if( jj<0 ) continue; if( jj>63 ) jj = 63; if( (pTabItem->colUsed & MASKBIT(jj))==0 ) continue; colUsed |= ((u64)1)<<(ii<63 ? ii : 63); } sqlite3VdbeAddOp4Dup8(v, OP_ColumnsUsed, iIndexCur, 0, 0, (u8*)&colUsed, P4_INT64); } #endif /* SQLITE_ENABLE_COLUMN_USED_MASK */ } } if( iDb>=0 ) sqlite3CodeVerifySchema(pParse, iDb); } pWInfo->iTop = sqlite3VdbeCurrentAddr(v); if( db->mallocFailed ) goto whereBeginError; /* Generate the code to do the search. Each iteration of the for ** loop below generates code for a single nested loop of the VM ** program. */ notReady = ~(Bitmask)0; for(ii=0; iia[ii]; wsFlags = pLevel->pWLoop->wsFlags; #ifndef SQLITE_OMIT_AUTOMATIC_INDEX if( (pLevel->pWLoop->wsFlags & WHERE_AUTO_INDEX)!=0 ){ constructAutomaticIndex(pParse, &pWInfo->sWC, &pTabList->a[pLevel->iFrom], notReady, pLevel); if( db->mallocFailed ) goto whereBeginError; } #endif addrExplain = sqlite3WhereExplainOneScan( pParse, pTabList, pLevel, ii, pLevel->iFrom, wctrlFlags ); pLevel->addrBody = sqlite3VdbeCurrentAddr(v); notReady = sqlite3WhereCodeOneLoopStart(pWInfo, ii, notReady); pWInfo->iContinue = pLevel->addrCont; if( (wsFlags&WHERE_MULTI_OR)==0 && (wctrlFlags&WHERE_OR_SUBCLAUSE)==0 ){ sqlite3WhereAddScanStatus(v, pTabList, pLevel, addrExplain); } } /* Done. */ VdbeModuleComment((v, "Begin WHERE-core")); return pWInfo; /* Jump here if malloc fails */ whereBeginError: if( pWInfo ){ pParse->nQueryLoop = pWInfo->savedNQueryLoop; whereInfoFree(db, pWInfo); } return 0; } /* ** Generate the end of the WHERE loop. See comments on ** sqlite3WhereBegin() for additional information. */ SQLITE_PRIVATE void sqlite3WhereEnd(WhereInfo *pWInfo){ Parse *pParse = pWInfo->pParse; Vdbe *v = pParse->pVdbe; int i; WhereLevel *pLevel; WhereLoop *pLoop; SrcList *pTabList = pWInfo->pTabList; sqlite3 *db = pParse->db; /* Generate loop termination code. */ VdbeModuleComment((v, "End WHERE-core")); sqlite3ExprCacheClear(pParse); for(i=pWInfo->nLevel-1; i>=0; i--){ int addr; pLevel = &pWInfo->a[i]; pLoop = pLevel->pWLoop; sqlite3VdbeResolveLabel(v, pLevel->addrCont); if( pLevel->op!=OP_Noop ){ sqlite3VdbeAddOp3(v, pLevel->op, pLevel->p1, pLevel->p2, pLevel->p3); sqlite3VdbeChangeP5(v, pLevel->p5); VdbeCoverage(v); VdbeCoverageIf(v, pLevel->op==OP_Next); VdbeCoverageIf(v, pLevel->op==OP_Prev); VdbeCoverageIf(v, pLevel->op==OP_VNext); } if( pLoop->wsFlags & WHERE_IN_ABLE && pLevel->u.in.nIn>0 ){ struct InLoop *pIn; int j; sqlite3VdbeResolveLabel(v, pLevel->addrNxt); for(j=pLevel->u.in.nIn, pIn=&pLevel->u.in.aInLoop[j-1]; j>0; j--, pIn--){ sqlite3VdbeJumpHere(v, pIn->addrInTop+1); if( pIn->eEndLoopOp!=OP_Noop ){ sqlite3VdbeAddOp2(v, pIn->eEndLoopOp, pIn->iCur, pIn->addrInTop); VdbeCoverage(v); VdbeCoverageIf(v, pIn->eEndLoopOp==OP_PrevIfOpen); VdbeCoverageIf(v, pIn->eEndLoopOp==OP_NextIfOpen); } sqlite3VdbeJumpHere(v, pIn->addrInTop-1); } } sqlite3VdbeResolveLabel(v, pLevel->addrBrk); if( pLevel->addrSkip ){ sqlite3VdbeGoto(v, pLevel->addrSkip); VdbeComment((v, "next skip-scan on %s", pLoop->u.btree.pIndex->zName)); sqlite3VdbeJumpHere(v, pLevel->addrSkip); sqlite3VdbeJumpHere(v, pLevel->addrSkip-2); } #ifndef SQLITE_LIKE_DOESNT_MATCH_BLOBS if( pLevel->addrLikeRep ){ sqlite3VdbeAddOp2(v, OP_DecrJumpZero, (int)(pLevel->iLikeRepCntr>>1), pLevel->addrLikeRep); VdbeCoverage(v); } #endif if( pLevel->iLeftJoin ){ int ws = pLoop->wsFlags; addr = sqlite3VdbeAddOp1(v, OP_IfPos, pLevel->iLeftJoin); VdbeCoverage(v); assert( (ws & WHERE_IDX_ONLY)==0 || (ws & WHERE_INDEXED)!=0 ); if( (ws & WHERE_IDX_ONLY)==0 ){ sqlite3VdbeAddOp1(v, OP_NullRow, pTabList->a[i].iCursor); } if( (ws & WHERE_INDEXED) || ((ws & WHERE_MULTI_OR) && pLevel->u.pCovidx) ){ sqlite3VdbeAddOp1(v, OP_NullRow, pLevel->iIdxCur); } if( pLevel->op==OP_Return ){ sqlite3VdbeAddOp2(v, OP_Gosub, pLevel->p1, pLevel->addrFirst); }else{ sqlite3VdbeGoto(v, pLevel->addrFirst); } sqlite3VdbeJumpHere(v, addr); } VdbeModuleComment((v, "End WHERE-loop%d: %s", i, pWInfo->pTabList->a[pLevel->iFrom].pTab->zName)); } /* The "break" point is here, just past the end of the outer loop. ** Set it. */ sqlite3VdbeResolveLabel(v, pWInfo->iBreak); assert( pWInfo->nLevel<=pTabList->nSrc ); for(i=0, pLevel=pWInfo->a; inLevel; i++, pLevel++){ int k, last; VdbeOp *pOp; Index *pIdx = 0; struct SrcList_item *pTabItem = &pTabList->a[pLevel->iFrom]; Table *pTab = pTabItem->pTab; assert( pTab!=0 ); pLoop = pLevel->pWLoop; /* For a co-routine, change all OP_Column references to the table of ** the co-routine into OP_Copy of result contained in a register. ** OP_Rowid becomes OP_Null. */ if( pTabItem->fg.viaCoroutine && !db->mallocFailed ){ translateColumnToCopy(v, pLevel->addrBody, pLevel->iTabCur, pTabItem->regResult, 0); continue; } /* Close all of the cursors that were opened by sqlite3WhereBegin. ** Except, do not close cursors that will be reused by the OR optimization ** (WHERE_OR_SUBCLAUSE). And do not close the OP_OpenWrite cursors ** created for the ONEPASS optimization. */ if( (pTab->tabFlags & TF_Ephemeral)==0 && pTab->pSelect==0 && (pWInfo->wctrlFlags & WHERE_OR_SUBCLAUSE)==0 ){ int ws = pLoop->wsFlags; if( pWInfo->eOnePass==ONEPASS_OFF && (ws & WHERE_IDX_ONLY)==0 ){ sqlite3VdbeAddOp1(v, OP_Close, pTabItem->iCursor); } if( (ws & WHERE_INDEXED)!=0 && (ws & (WHERE_IPK|WHERE_AUTO_INDEX))==0 && pLevel->iIdxCur!=pWInfo->aiCurOnePass[1] ){ sqlite3VdbeAddOp1(v, OP_Close, pLevel->iIdxCur); } } /* If this scan uses an index, make VDBE code substitutions to read data ** from the index instead of from the table where possible. In some cases ** this optimization prevents the table from ever being read, which can ** yield a significant performance boost. ** ** Calls to the code generator in between sqlite3WhereBegin and ** sqlite3WhereEnd will have created code that references the table ** directly. This loop scans all that code looking for opcodes ** that reference the table and converts them into opcodes that ** reference the index. */ if( pLoop->wsFlags & (WHERE_INDEXED|WHERE_IDX_ONLY) ){ pIdx = pLoop->u.btree.pIndex; }else if( pLoop->wsFlags & WHERE_MULTI_OR ){ pIdx = pLevel->u.pCovidx; } if( pIdx && (pWInfo->eOnePass==ONEPASS_OFF || !HasRowid(pIdx->pTable)) && !db->mallocFailed ){ last = sqlite3VdbeCurrentAddr(v); k = pLevel->addrBody; pOp = sqlite3VdbeGetOp(v, k); for(; kp1!=pLevel->iTabCur ) continue; if( pOp->opcode==OP_Column ){ int x = pOp->p2; assert( pIdx->pTable==pTab ); if( !HasRowid(pTab) ){ Index *pPk = sqlite3PrimaryKeyIndex(pTab); x = pPk->aiColumn[x]; assert( x>=0 ); } x = sqlite3ColumnOfIndex(pIdx, x); if( x>=0 ){ pOp->p2 = x; pOp->p1 = pLevel->iIdxCur; } assert( (pLoop->wsFlags & WHERE_IDX_ONLY)==0 || x>=0 ); }else if( pOp->opcode==OP_Rowid ){ pOp->p1 = pLevel->iIdxCur; pOp->opcode = OP_IdxRowid; } } } } /* Final cleanup */ pParse->nQueryLoop = pWInfo->savedNQueryLoop; whereInfoFree(db, pWInfo); return; } /************** End of where.c ***********************************************/ /************** Begin file parse.c *******************************************/ /* ** 2000-05-29 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ************************************************************************* ** Driver template for the LEMON parser generator. ** ** The "lemon" program processes an LALR(1) input grammar file, then uses ** this template to construct a parser. The "lemon" program inserts text ** at each "%%" line. Also, any "P-a-r-s-e" identifer prefix (without the ** interstitial "-" characters) contained in this template is changed into ** the value of the %name directive from the grammar. Otherwise, the content ** of this template is copied straight through into the generate parser ** source file. ** ** The following is the concatenation of all %include directives from the ** input grammar file: */ /* #include */ /************ Begin %include sections from the grammar ************************/ /* #include "sqliteInt.h" */ /* ** Disable all error recovery processing in the parser push-down ** automaton. */ #define YYNOERRORRECOVERY 1 /* ** Make yytestcase() the same as testcase() */ #define yytestcase(X) testcase(X) /* ** Indicate that sqlite3ParserFree() will never be called with a null ** pointer. */ #define YYPARSEFREENEVERNULL 1 /* ** Alternative datatype for the argument to the malloc() routine passed ** into sqlite3ParserAlloc(). The default is size_t. */ #define YYMALLOCARGTYPE u64 /* ** An instance of this structure holds information about the ** LIMIT clause of a SELECT statement. */ struct LimitVal { Expr *pLimit; /* The LIMIT expression. NULL if there is no limit */ Expr *pOffset; /* The OFFSET expression. NULL if there is none */ }; /* ** An instance of the following structure describes the event of a ** TRIGGER. "a" is the event type, one of TK_UPDATE, TK_INSERT, ** TK_DELETE, or TK_INSTEAD. If the event is of the form ** ** UPDATE ON (a,b,c) ** ** Then the "b" IdList records the list "a,b,c". */ struct TrigEvent { int a; IdList * b; }; /* ** Disable lookaside memory allocation for objects that might be ** shared across database connections. */ static void disableLookaside(Parse *pParse){ pParse->disableLookaside++; pParse->db->lookaside.bDisable++; } /* ** For a compound SELECT statement, make sure p->pPrior->pNext==p for ** all elements in the list. And make sure list length does not exceed ** SQLITE_LIMIT_COMPOUND_SELECT. */ static void parserDoubleLinkSelect(Parse *pParse, Select *p){ if( p->pPrior ){ Select *pNext = 0, *pLoop; int mxSelect, cnt = 0; for(pLoop=p; pLoop; pNext=pLoop, pLoop=pLoop->pPrior, cnt++){ pLoop->pNext = pNext; pLoop->selFlags |= SF_Compound; } if( (p->selFlags & SF_MultiValue)==0 && (mxSelect = pParse->db->aLimit[SQLITE_LIMIT_COMPOUND_SELECT])>0 && cnt>mxSelect ){ sqlite3ErrorMsg(pParse, "too many terms in compound SELECT"); } } } /* This is a utility routine used to set the ExprSpan.zStart and ** ExprSpan.zEnd values of pOut so that the span covers the complete ** range of text beginning with pStart and going to the end of pEnd. */ static void spanSet(ExprSpan *pOut, Token *pStart, Token *pEnd){ pOut->zStart = pStart->z; pOut->zEnd = &pEnd->z[pEnd->n]; } /* Construct a new Expr object from a single identifier. Use the ** new Expr to populate pOut. Set the span of pOut to be the identifier ** that created the expression. */ static void spanExpr(ExprSpan *pOut, Parse *pParse, int op, Token t){ Expr *p = sqlite3DbMallocRawNN(pParse->db, sizeof(Expr)+t.n+1); if( p ){ memset(p, 0, sizeof(Expr)); p->op = (u8)op; p->flags = EP_Leaf; p->iAgg = -1; p->u.zToken = (char*)&p[1]; memcpy(p->u.zToken, t.z, t.n); p->u.zToken[t.n] = 0; if( sqlite3Isquote(p->u.zToken[0]) ){ if( p->u.zToken[0]=='"' ) p->flags |= EP_DblQuoted; sqlite3Dequote(p->u.zToken); } #if SQLITE_MAX_EXPR_DEPTH>0 p->nHeight = 1; #endif } pOut->pExpr = p; pOut->zStart = t.z; pOut->zEnd = &t.z[t.n]; } /* This routine constructs a binary expression node out of two ExprSpan ** objects and uses the result to populate a new ExprSpan object. */ static void spanBinaryExpr( Parse *pParse, /* The parsing context. Errors accumulate here */ int op, /* The binary operation */ ExprSpan *pLeft, /* The left operand, and output */ ExprSpan *pRight /* The right operand */ ){ pLeft->pExpr = sqlite3PExpr(pParse, op, pLeft->pExpr, pRight->pExpr, 0); pLeft->zEnd = pRight->zEnd; } /* If doNot is true, then add a TK_NOT Expr-node wrapper around the ** outside of *ppExpr. */ static void exprNot(Parse *pParse, int doNot, ExprSpan *pSpan){ if( doNot ){ pSpan->pExpr = sqlite3PExpr(pParse, TK_NOT, pSpan->pExpr, 0, 0); } } /* Construct an expression node for a unary postfix operator */ static void spanUnaryPostfix( Parse *pParse, /* Parsing context to record errors */ int op, /* The operator */ ExprSpan *pOperand, /* The operand, and output */ Token *pPostOp /* The operand token for setting the span */ ){ pOperand->pExpr = sqlite3PExpr(pParse, op, pOperand->pExpr, 0, 0); pOperand->zEnd = &pPostOp->z[pPostOp->n]; } /* A routine to convert a binary TK_IS or TK_ISNOT expression into a ** unary TK_ISNULL or TK_NOTNULL expression. */ static void binaryToUnaryIfNull(Parse *pParse, Expr *pY, Expr *pA, int op){ sqlite3 *db = pParse->db; if( pA && pY && pY->op==TK_NULL ){ pA->op = (u8)op; sqlite3ExprDelete(db, pA->pRight); pA->pRight = 0; } } /* Construct an expression node for a unary prefix operator */ static void spanUnaryPrefix( ExprSpan *pOut, /* Write the new expression node here */ Parse *pParse, /* Parsing context to record errors */ int op, /* The operator */ ExprSpan *pOperand, /* The operand */ Token *pPreOp /* The operand token for setting the span */ ){ pOut->zStart = pPreOp->z; pOut->pExpr = sqlite3PExpr(pParse, op, pOperand->pExpr, 0, 0); pOut->zEnd = pOperand->zEnd; } /* Add a single new term to an ExprList that is used to store a ** list of identifiers. Report an error if the ID list contains ** a COLLATE clause or an ASC or DESC keyword, except ignore the ** error while parsing a legacy schema. */ static ExprList *parserAddExprIdListTerm( Parse *pParse, ExprList *pPrior, Token *pIdToken, int hasCollate, int sortOrder ){ ExprList *p = sqlite3ExprListAppend(pParse, pPrior, 0); if( (hasCollate || sortOrder!=SQLITE_SO_UNDEFINED) && pParse->db->init.busy==0 ){ sqlite3ErrorMsg(pParse, "syntax error after column name \"%.*s\"", pIdToken->n, pIdToken->z); } sqlite3ExprListSetName(pParse, p, pIdToken, 1); return p; } /**************** End of %include directives **********************************/ /* These constants specify the various numeric values for terminal symbols ** in a format understandable to "makeheaders". This section is blank unless ** "lemon" is run with the "-m" command-line option. ***************** Begin makeheaders token definitions *************************/ /**************** End makeheaders token definitions ***************************/ /* The next sections is a series of control #defines. ** various aspects of the generated parser. ** YYCODETYPE is the data type used to store the integer codes ** that represent terminal and non-terminal symbols. ** "unsigned char" is used if there are fewer than ** 256 symbols. Larger types otherwise. ** YYNOCODE is a number of type YYCODETYPE that is not used for ** any terminal or nonterminal symbol. ** YYFALLBACK If defined, this indicates that one or more tokens ** (also known as: "terminal symbols") have fall-back ** values which should be used if the original symbol ** would not parse. This permits keywords to sometimes ** be used as identifiers, for example. ** YYACTIONTYPE is the data type used for "action codes" - numbers ** that indicate what to do in response to the next ** token. ** sqlite3ParserTOKENTYPE is the data type used for minor type for terminal ** symbols. Background: A "minor type" is a semantic ** value associated with a terminal or non-terminal ** symbols. For example, for an "ID" terminal symbol, ** the minor type might be the name of the identifier. ** Each non-terminal can have a different minor type. ** Terminal symbols all have the same minor type, though. ** This macros defines the minor type for terminal ** symbols. ** YYMINORTYPE is the data type used for all minor types. ** This is typically a union of many types, one of ** which is sqlite3ParserTOKENTYPE. The entry in the union ** for terminal symbols is called "yy0". ** YYSTACKDEPTH is the maximum depth of the parser's stack. If ** zero the stack is dynamically sized using realloc() ** sqlite3ParserARG_SDECL A static variable declaration for the %extra_argument ** sqlite3ParserARG_PDECL A parameter declaration for the %extra_argument ** sqlite3ParserARG_STORE Code to store %extra_argument into yypParser ** sqlite3ParserARG_FETCH Code to extract %extra_argument from yypParser ** YYERRORSYMBOL is the code number of the error symbol. If not ** defined, then do no error processing. ** YYNSTATE the combined number of states. ** YYNRULE the number of rules in the grammar ** YY_MAX_SHIFT Maximum value for shift actions ** YY_MIN_SHIFTREDUCE Minimum value for shift-reduce actions ** YY_MAX_SHIFTREDUCE Maximum value for shift-reduce actions ** YY_MIN_REDUCE Maximum value for reduce actions ** YY_ERROR_ACTION The yy_action[] code for syntax error ** YY_ACCEPT_ACTION The yy_action[] code for accept ** YY_NO_ACTION The yy_action[] code for no-op */ #ifndef INTERFACE # define INTERFACE 1 #endif /************* Begin control #defines *****************************************/ #define YYCODETYPE unsigned char #define YYNOCODE 252 #define YYACTIONTYPE unsigned short int #define YYWILDCARD 96 #define sqlite3ParserTOKENTYPE Token typedef union { int yyinit; sqlite3ParserTOKENTYPE yy0; Expr* yy72; TriggerStep* yy145; ExprList* yy148; SrcList* yy185; ExprSpan yy190; int yy194; Select* yy243; IdList* yy254; With* yy285; struct TrigEvent yy332; struct LimitVal yy354; struct {int value; int mask;} yy497; } YYMINORTYPE; #ifndef YYSTACKDEPTH #define YYSTACKDEPTH 100 #endif #define sqlite3ParserARG_SDECL Parse *pParse; #define sqlite3ParserARG_PDECL ,Parse *pParse #define sqlite3ParserARG_FETCH Parse *pParse = yypParser->pParse #define sqlite3ParserARG_STORE yypParser->pParse = pParse #define YYFALLBACK 1 #define YYNSTATE 456 #define YYNRULE 332 #define YY_MAX_SHIFT 455 #define YY_MIN_SHIFTREDUCE 668 #define YY_MAX_SHIFTREDUCE 999 #define YY_MIN_REDUCE 1000 #define YY_MAX_REDUCE 1331 #define YY_ERROR_ACTION 1332 #define YY_ACCEPT_ACTION 1333 #define YY_NO_ACTION 1334 /************* End control #defines *******************************************/ /* Define the yytestcase() macro to be a no-op if is not already defined ** otherwise. ** ** Applications can choose to define yytestcase() in the %include section ** to a macro that can assist in verifying code coverage. For production ** code the yytestcase() macro should be turned off. But it is useful ** for testing. */ #ifndef yytestcase # define yytestcase(X) #endif /* Next are the tables used to determine what action to take based on the ** current state and lookahead token. These tables are used to implement ** functions that take a state number and lookahead value and return an ** action integer. ** ** Suppose the action integer is N. Then the action is determined as ** follows ** ** 0 <= N <= YY_MAX_SHIFT Shift N. That is, push the lookahead ** token onto the stack and goto state N. ** ** N between YY_MIN_SHIFTREDUCE Shift to an arbitrary state then ** and YY_MAX_SHIFTREDUCE reduce by rule N-YY_MIN_SHIFTREDUCE. ** ** N between YY_MIN_REDUCE Reduce by rule N-YY_MIN_REDUCE ** and YY_MAX_REDUCE ** ** N == YY_ERROR_ACTION A syntax error has occurred. ** ** N == YY_ACCEPT_ACTION The parser accepts its input. ** ** N == YY_NO_ACTION No such action. Denotes unused ** slots in the yy_action[] table. ** ** The action table is constructed as a single large table named yy_action[]. ** Given state S and lookahead X, the action is computed as either: ** ** (A) N = yy_action[ yy_shift_ofst[S] + X ] ** (B) N = yy_default[S] ** ** The (A) formula is preferred. The B formula is used instead if: ** (1) The yy_shift_ofst[S]+X value is out of range, or ** (2) yy_lookahead[yy_shift_ofst[S]+X] is not equal to X, or ** (3) yy_shift_ofst[S] equal YY_SHIFT_USE_DFLT. ** (Implementation note: YY_SHIFT_USE_DFLT is chosen so that ** YY_SHIFT_USE_DFLT+X will be out of range for all possible lookaheads X. ** Hence only tests (1) and (2) need to be evaluated.) ** ** The formulas above are for computing the action when the lookahead is ** a terminal symbol. If the lookahead is a non-terminal (as occurs after ** a reduce action) then the yy_reduce_ofst[] array is used in place of ** the yy_shift_ofst[] array and YY_REDUCE_USE_DFLT is used in place of ** YY_SHIFT_USE_DFLT. ** ** The following are the tables generated in this section: ** ** yy_action[] A single table containing all actions. ** yy_lookahead[] A table containing the lookahead for each entry in ** yy_action. Used to detect hash collisions. ** yy_shift_ofst[] For each state, the offset into yy_action for ** shifting terminals. ** yy_reduce_ofst[] For each state, the offset into yy_action for ** shifting non-terminals after a reduce. ** yy_default[] Default action for each state. ** *********** Begin parsing tables **********************************************/ #define YY_ACTTAB_COUNT (1567) static const YYACTIONTYPE yy_action[] = { /* 0 */ 325, 832, 351, 825, 5, 203, 203, 819, 99, 100, /* 10 */ 90, 842, 842, 854, 857, 846, 846, 97, 97, 98, /* 20 */ 98, 98, 98, 301, 96, 96, 96, 96, 95, 95, /* 30 */ 94, 94, 94, 93, 351, 325, 977, 977, 824, 824, /* 40 */ 826, 947, 354, 99, 100, 90, 842, 842, 854, 857, /* 50 */ 846, 846, 97, 97, 98, 98, 98, 98, 338, 96, /* 60 */ 96, 96, 96, 95, 95, 94, 94, 94, 93, 351, /* 70 */ 95, 95, 94, 94, 94, 93, 351, 791, 977, 977, /* 80 */ 325, 94, 94, 94, 93, 351, 792, 75, 99, 100, /* 90 */ 90, 842, 842, 854, 857, 846, 846, 97, 97, 98, /* 100 */ 98, 98, 98, 450, 96, 96, 96, 96, 95, 95, /* 110 */ 94, 94, 94, 93, 351, 1333, 155, 155, 2, 325, /* 120 */ 275, 146, 132, 52, 52, 93, 351, 99, 100, 90, /* 130 */ 842, 842, 854, 857, 846, 846, 97, 97, 98, 98, /* 140 */ 98, 98, 101, 96, 96, 96, 96, 95, 95, 94, /* 150 */ 94, 94, 93, 351, 958, 958, 325, 268, 428, 413, /* 160 */ 411, 61, 752, 752, 99, 100, 90, 842, 842, 854, /* 170 */ 857, 846, 846, 97, 97, 98, 98, 98, 98, 60, /* 180 */ 96, 96, 96, 96, 95, 95, 94, 94, 94, 93, /* 190 */ 351, 325, 270, 329, 273, 277, 959, 960, 250, 99, /* 200 */ 100, 90, 842, 842, 854, 857, 846, 846, 97, 97, /* 210 */ 98, 98, 98, 98, 301, 96, 96, 96, 96, 95, /* 220 */ 95, 94, 94, 94, 93, 351, 325, 938, 1326, 698, /* 230 */ 706, 1326, 242, 412, 99, 100, 90, 842, 842, 854, /* 240 */ 857, 846, 846, 97, 97, 98, 98, 98, 98, 347, /* 250 */ 96, 96, 96, 96, 95, 95, 94, 94, 94, 93, /* 260 */ 351, 325, 938, 1327, 384, 699, 1327, 381, 379, 99, /* 270 */ 100, 90, 842, 842, 854, 857, 846, 846, 97, 97, /* 280 */ 98, 98, 98, 98, 701, 96, 96, 96, 96, 95, /* 290 */ 95, 94, 94, 94, 93, 351, 325, 92, 89, 178, /* 300 */ 833, 936, 373, 700, 99, 100, 90, 842, 842, 854, /* 310 */ 857, 846, 846, 97, 97, 98, 98, 98, 98, 375, /* 320 */ 96, 96, 96, 96, 95, 95, 94, 94, 94, 93, /* 330 */ 351, 325, 1276, 947, 354, 818, 936, 739, 739, 99, /* 340 */ 100, 90, 842, 842, 854, 857, 846, 846, 97, 97, /* 350 */ 98, 98, 98, 98, 230, 96, 96, 96, 96, 95, /* 360 */ 95, 94, 94, 94, 93, 351, 325, 969, 227, 92, /* 370 */ 89, 178, 373, 300, 99, 100, 90, 842, 842, 854, /* 380 */ 857, 846, 846, 97, 97, 98, 98, 98, 98, 921, /* 390 */ 96, 96, 96, 96, 95, 95, 94, 94, 94, 93, /* 400 */ 351, 325, 449, 447, 447, 447, 147, 737, 737, 99, /* 410 */ 100, 90, 842, 842, 854, 857, 846, 846, 97, 97, /* 420 */ 98, 98, 98, 98, 296, 96, 96, 96, 96, 95, /* 430 */ 95, 94, 94, 94, 93, 351, 325, 419, 231, 958, /* 440 */ 958, 158, 25, 422, 99, 100, 90, 842, 842, 854, /* 450 */ 857, 846, 846, 97, 97, 98, 98, 98, 98, 450, /* 460 */ 96, 96, 96, 96, 95, 95, 94, 94, 94, 93, /* 470 */ 351, 443, 224, 224, 420, 958, 958, 962, 325, 52, /* 480 */ 52, 959, 960, 176, 415, 78, 99, 100, 90, 842, /* 490 */ 842, 854, 857, 846, 846, 97, 97, 98, 98, 98, /* 500 */ 98, 379, 96, 96, 96, 96, 95, 95, 94, 94, /* 510 */ 94, 93, 351, 325, 428, 418, 298, 959, 960, 962, /* 520 */ 81, 99, 88, 90, 842, 842, 854, 857, 846, 846, /* 530 */ 97, 97, 98, 98, 98, 98, 717, 96, 96, 96, /* 540 */ 96, 95, 95, 94, 94, 94, 93, 351, 325, 843, /* 550 */ 843, 855, 858, 996, 318, 343, 379, 100, 90, 842, /* 560 */ 842, 854, 857, 846, 846, 97, 97, 98, 98, 98, /* 570 */ 98, 450, 96, 96, 96, 96, 95, 95, 94, 94, /* 580 */ 94, 93, 351, 325, 350, 350, 350, 260, 377, 340, /* 590 */ 929, 52, 52, 90, 842, 842, 854, 857, 846, 846, /* 600 */ 97, 97, 98, 98, 98, 98, 361, 96, 96, 96, /* 610 */ 96, 95, 95, 94, 94, 94, 93, 351, 86, 445, /* 620 */ 847, 3, 1203, 361, 360, 378, 344, 813, 958, 958, /* 630 */ 1300, 86, 445, 729, 3, 212, 169, 287, 405, 282, /* 640 */ 404, 199, 232, 450, 300, 760, 83, 84, 280, 245, /* 650 */ 262, 365, 251, 85, 352, 352, 92, 89, 178, 83, /* 660 */ 84, 242, 412, 52, 52, 448, 85, 352, 352, 246, /* 670 */ 959, 960, 194, 455, 670, 402, 399, 398, 448, 243, /* 680 */ 221, 114, 434, 776, 361, 450, 397, 268, 747, 224, /* 690 */ 224, 132, 132, 198, 832, 434, 452, 451, 428, 427, /* 700 */ 819, 415, 734, 713, 132, 52, 52, 832, 268, 452, /* 710 */ 451, 734, 194, 819, 363, 402, 399, 398, 450, 1271, /* 720 */ 1271, 23, 958, 958, 86, 445, 397, 3, 228, 429, /* 730 */ 895, 824, 824, 826, 827, 19, 203, 720, 52, 52, /* 740 */ 428, 408, 439, 249, 824, 824, 826, 827, 19, 229, /* 750 */ 403, 153, 83, 84, 761, 177, 241, 450, 721, 85, /* 760 */ 352, 352, 120, 157, 959, 960, 58, 977, 409, 355, /* 770 */ 330, 448, 268, 428, 430, 320, 790, 32, 32, 86, /* 780 */ 445, 776, 3, 341, 98, 98, 98, 98, 434, 96, /* 790 */ 96, 96, 96, 95, 95, 94, 94, 94, 93, 351, /* 800 */ 832, 120, 452, 451, 813, 887, 819, 83, 84, 977, /* 810 */ 813, 132, 410, 920, 85, 352, 352, 132, 407, 789, /* 820 */ 958, 958, 92, 89, 178, 917, 448, 262, 370, 261, /* 830 */ 82, 914, 80, 262, 370, 261, 776, 824, 824, 826, /* 840 */ 827, 19, 934, 434, 96, 96, 96, 96, 95, 95, /* 850 */ 94, 94, 94, 93, 351, 832, 74, 452, 451, 958, /* 860 */ 958, 819, 959, 960, 120, 92, 89, 178, 945, 2, /* 870 */ 918, 965, 268, 1, 976, 76, 445, 762, 3, 708, /* 880 */ 901, 901, 387, 958, 958, 757, 919, 371, 740, 778, /* 890 */ 756, 257, 824, 824, 826, 827, 19, 417, 741, 450, /* 900 */ 24, 959, 960, 83, 84, 369, 958, 958, 177, 226, /* 910 */ 85, 352, 352, 885, 315, 314, 313, 215, 311, 10, /* 920 */ 10, 683, 448, 349, 348, 959, 960, 909, 777, 157, /* 930 */ 120, 958, 958, 337, 776, 416, 711, 310, 450, 434, /* 940 */ 450, 321, 450, 791, 103, 200, 175, 450, 959, 960, /* 950 */ 908, 832, 792, 452, 451, 9, 9, 819, 10, 10, /* 960 */ 52, 52, 51, 51, 180, 716, 248, 10, 10, 171, /* 970 */ 170, 167, 339, 959, 960, 247, 984, 702, 702, 450, /* 980 */ 715, 233, 686, 982, 889, 983, 182, 914, 824, 824, /* 990 */ 826, 827, 19, 183, 256, 423, 132, 181, 394, 10, /* 1000 */ 10, 889, 891, 749, 958, 958, 917, 268, 985, 198, /* 1010 */ 985, 349, 348, 425, 415, 299, 817, 832, 326, 825, /* 1020 */ 120, 332, 133, 819, 268, 98, 98, 98, 98, 91, /* 1030 */ 96, 96, 96, 96, 95, 95, 94, 94, 94, 93, /* 1040 */ 351, 157, 810, 371, 382, 359, 959, 960, 358, 268, /* 1050 */ 450, 918, 368, 324, 824, 824, 826, 450, 709, 450, /* 1060 */ 264, 380, 889, 450, 877, 746, 253, 919, 255, 433, /* 1070 */ 36, 36, 234, 450, 234, 120, 269, 37, 37, 12, /* 1080 */ 12, 334, 272, 27, 27, 450, 330, 118, 450, 162, /* 1090 */ 742, 280, 450, 38, 38, 450, 985, 356, 985, 450, /* 1100 */ 709, 1210, 450, 132, 450, 39, 39, 450, 40, 40, /* 1110 */ 450, 362, 41, 41, 450, 42, 42, 450, 254, 28, /* 1120 */ 28, 450, 29, 29, 31, 31, 450, 43, 43, 450, /* 1130 */ 44, 44, 450, 714, 45, 45, 450, 11, 11, 767, /* 1140 */ 450, 46, 46, 450, 268, 450, 105, 105, 450, 47, /* 1150 */ 47, 450, 48, 48, 450, 237, 33, 33, 450, 172, /* 1160 */ 49, 49, 450, 50, 50, 34, 34, 274, 122, 122, /* 1170 */ 450, 123, 123, 450, 124, 124, 450, 898, 56, 56, /* 1180 */ 450, 897, 35, 35, 450, 267, 450, 817, 450, 817, /* 1190 */ 106, 106, 450, 53, 53, 385, 107, 107, 450, 817, /* 1200 */ 108, 108, 817, 450, 104, 104, 121, 121, 119, 119, /* 1210 */ 450, 117, 112, 112, 450, 276, 450, 225, 111, 111, /* 1220 */ 450, 730, 450, 109, 109, 450, 673, 674, 675, 912, /* 1230 */ 110, 110, 317, 998, 55, 55, 57, 57, 692, 331, /* 1240 */ 54, 54, 26, 26, 696, 30, 30, 317, 937, 197, /* 1250 */ 196, 195, 335, 281, 336, 446, 331, 745, 689, 436, /* 1260 */ 440, 444, 120, 72, 386, 223, 175, 345, 757, 933, /* 1270 */ 20, 286, 319, 756, 815, 372, 374, 202, 202, 202, /* 1280 */ 263, 395, 285, 74, 208, 21, 696, 719, 718, 884, /* 1290 */ 120, 120, 120, 120, 120, 754, 278, 828, 77, 74, /* 1300 */ 726, 727, 785, 783, 880, 202, 999, 208, 894, 893, /* 1310 */ 894, 893, 694, 816, 763, 116, 774, 1290, 431, 432, /* 1320 */ 302, 999, 390, 303, 823, 697, 691, 680, 159, 289, /* 1330 */ 679, 884, 681, 952, 291, 218, 293, 7, 316, 828, /* 1340 */ 173, 805, 259, 364, 252, 911, 376, 713, 295, 435, /* 1350 */ 308, 168, 955, 993, 135, 400, 990, 284, 882, 881, /* 1360 */ 205, 928, 926, 59, 333, 62, 144, 156, 130, 72, /* 1370 */ 802, 366, 367, 393, 137, 185, 189, 160, 139, 383, /* 1380 */ 67, 896, 140, 141, 142, 148, 389, 812, 775, 266, /* 1390 */ 219, 190, 154, 391, 913, 876, 271, 406, 191, 322, /* 1400 */ 682, 733, 192, 342, 732, 724, 731, 711, 723, 421, /* 1410 */ 705, 71, 323, 6, 204, 771, 288, 79, 297, 346, /* 1420 */ 772, 704, 290, 283, 703, 770, 292, 294, 967, 239, /* 1430 */ 769, 102, 862, 438, 426, 240, 424, 442, 73, 213, /* 1440 */ 688, 238, 22, 453, 953, 214, 217, 216, 454, 677, /* 1450 */ 676, 671, 753, 125, 115, 235, 126, 669, 353, 166, /* 1460 */ 127, 244, 179, 357, 306, 304, 305, 307, 113, 892, /* 1470 */ 327, 890, 811, 328, 134, 128, 136, 138, 743, 258, /* 1480 */ 907, 184, 143, 129, 910, 186, 63, 64, 145, 187, /* 1490 */ 906, 65, 8, 66, 13, 188, 202, 899, 265, 149, /* 1500 */ 987, 388, 150, 685, 161, 392, 285, 193, 279, 396, /* 1510 */ 151, 401, 68, 14, 15, 722, 69, 236, 831, 131, /* 1520 */ 830, 860, 70, 751, 16, 414, 755, 4, 174, 220, /* 1530 */ 222, 784, 201, 152, 779, 77, 74, 17, 18, 875, /* 1540 */ 861, 859, 916, 864, 915, 207, 206, 942, 163, 437, /* 1550 */ 948, 943, 164, 209, 1002, 441, 863, 165, 210, 829, /* 1560 */ 695, 87, 312, 211, 1292, 1291, 309, }; static const YYCODETYPE yy_lookahead[] = { /* 0 */ 19, 95, 53, 97, 22, 24, 24, 101, 27, 28, /* 10 */ 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, /* 20 */ 39, 40, 41, 152, 43, 44, 45, 46, 47, 48, /* 30 */ 49, 50, 51, 52, 53, 19, 55, 55, 132, 133, /* 40 */ 134, 1, 2, 27, 28, 29, 30, 31, 32, 33, /* 50 */ 34, 35, 36, 37, 38, 39, 40, 41, 187, 43, /* 60 */ 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, /* 70 */ 47, 48, 49, 50, 51, 52, 53, 61, 97, 97, /* 80 */ 19, 49, 50, 51, 52, 53, 70, 26, 27, 28, /* 90 */ 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, /* 100 */ 39, 40, 41, 152, 43, 44, 45, 46, 47, 48, /* 110 */ 49, 50, 51, 52, 53, 144, 145, 146, 147, 19, /* 120 */ 16, 22, 92, 172, 173, 52, 53, 27, 28, 29, /* 130 */ 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, /* 140 */ 40, 41, 81, 43, 44, 45, 46, 47, 48, 49, /* 150 */ 50, 51, 52, 53, 55, 56, 19, 152, 207, 208, /* 160 */ 115, 24, 117, 118, 27, 28, 29, 30, 31, 32, /* 170 */ 33, 34, 35, 36, 37, 38, 39, 40, 41, 79, /* 180 */ 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, /* 190 */ 53, 19, 88, 157, 90, 23, 97, 98, 193, 27, /* 200 */ 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, /* 210 */ 38, 39, 40, 41, 152, 43, 44, 45, 46, 47, /* 220 */ 48, 49, 50, 51, 52, 53, 19, 22, 23, 172, /* 230 */ 23, 26, 119, 120, 27, 28, 29, 30, 31, 32, /* 240 */ 33, 34, 35, 36, 37, 38, 39, 40, 41, 187, /* 250 */ 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, /* 260 */ 53, 19, 22, 23, 228, 23, 26, 231, 152, 27, /* 270 */ 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, /* 280 */ 38, 39, 40, 41, 172, 43, 44, 45, 46, 47, /* 290 */ 48, 49, 50, 51, 52, 53, 19, 221, 222, 223, /* 300 */ 23, 96, 152, 172, 27, 28, 29, 30, 31, 32, /* 310 */ 33, 34, 35, 36, 37, 38, 39, 40, 41, 152, /* 320 */ 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, /* 330 */ 53, 19, 0, 1, 2, 23, 96, 190, 191, 27, /* 340 */ 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, /* 350 */ 38, 39, 40, 41, 238, 43, 44, 45, 46, 47, /* 360 */ 48, 49, 50, 51, 52, 53, 19, 185, 218, 221, /* 370 */ 222, 223, 152, 152, 27, 28, 29, 30, 31, 32, /* 380 */ 33, 34, 35, 36, 37, 38, 39, 40, 41, 241, /* 390 */ 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, /* 400 */ 53, 19, 152, 168, 169, 170, 22, 190, 191, 27, /* 410 */ 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, /* 420 */ 38, 39, 40, 41, 152, 43, 44, 45, 46, 47, /* 430 */ 48, 49, 50, 51, 52, 53, 19, 19, 218, 55, /* 440 */ 56, 24, 22, 152, 27, 28, 29, 30, 31, 32, /* 450 */ 33, 34, 35, 36, 37, 38, 39, 40, 41, 152, /* 460 */ 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, /* 470 */ 53, 250, 194, 195, 56, 55, 56, 55, 19, 172, /* 480 */ 173, 97, 98, 152, 206, 138, 27, 28, 29, 30, /* 490 */ 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, /* 500 */ 41, 152, 43, 44, 45, 46, 47, 48, 49, 50, /* 510 */ 51, 52, 53, 19, 207, 208, 152, 97, 98, 97, /* 520 */ 138, 27, 28, 29, 30, 31, 32, 33, 34, 35, /* 530 */ 36, 37, 38, 39, 40, 41, 181, 43, 44, 45, /* 540 */ 46, 47, 48, 49, 50, 51, 52, 53, 19, 30, /* 550 */ 31, 32, 33, 247, 248, 19, 152, 28, 29, 30, /* 560 */ 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, /* 570 */ 41, 152, 43, 44, 45, 46, 47, 48, 49, 50, /* 580 */ 51, 52, 53, 19, 168, 169, 170, 238, 19, 53, /* 590 */ 152, 172, 173, 29, 30, 31, 32, 33, 34, 35, /* 600 */ 36, 37, 38, 39, 40, 41, 152, 43, 44, 45, /* 610 */ 46, 47, 48, 49, 50, 51, 52, 53, 19, 20, /* 620 */ 101, 22, 23, 169, 170, 56, 207, 85, 55, 56, /* 630 */ 23, 19, 20, 26, 22, 99, 100, 101, 102, 103, /* 640 */ 104, 105, 238, 152, 152, 210, 47, 48, 112, 152, /* 650 */ 108, 109, 110, 54, 55, 56, 221, 222, 223, 47, /* 660 */ 48, 119, 120, 172, 173, 66, 54, 55, 56, 152, /* 670 */ 97, 98, 99, 148, 149, 102, 103, 104, 66, 154, /* 680 */ 23, 156, 83, 26, 230, 152, 113, 152, 163, 194, /* 690 */ 195, 92, 92, 30, 95, 83, 97, 98, 207, 208, /* 700 */ 101, 206, 179, 180, 92, 172, 173, 95, 152, 97, /* 710 */ 98, 188, 99, 101, 219, 102, 103, 104, 152, 119, /* 720 */ 120, 196, 55, 56, 19, 20, 113, 22, 193, 163, /* 730 */ 11, 132, 133, 134, 135, 136, 24, 65, 172, 173, /* 740 */ 207, 208, 250, 152, 132, 133, 134, 135, 136, 193, /* 750 */ 78, 84, 47, 48, 49, 98, 199, 152, 86, 54, /* 760 */ 55, 56, 196, 152, 97, 98, 209, 55, 163, 244, /* 770 */ 107, 66, 152, 207, 208, 164, 175, 172, 173, 19, /* 780 */ 20, 124, 22, 111, 38, 39, 40, 41, 83, 43, /* 790 */ 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, /* 800 */ 95, 196, 97, 98, 85, 152, 101, 47, 48, 97, /* 810 */ 85, 92, 207, 193, 54, 55, 56, 92, 49, 175, /* 820 */ 55, 56, 221, 222, 223, 12, 66, 108, 109, 110, /* 830 */ 137, 163, 139, 108, 109, 110, 26, 132, 133, 134, /* 840 */ 135, 136, 152, 83, 43, 44, 45, 46, 47, 48, /* 850 */ 49, 50, 51, 52, 53, 95, 26, 97, 98, 55, /* 860 */ 56, 101, 97, 98, 196, 221, 222, 223, 146, 147, /* 870 */ 57, 171, 152, 22, 26, 19, 20, 49, 22, 179, /* 880 */ 108, 109, 110, 55, 56, 116, 73, 219, 75, 124, /* 890 */ 121, 152, 132, 133, 134, 135, 136, 163, 85, 152, /* 900 */ 232, 97, 98, 47, 48, 237, 55, 56, 98, 5, /* 910 */ 54, 55, 56, 193, 10, 11, 12, 13, 14, 172, /* 920 */ 173, 17, 66, 47, 48, 97, 98, 152, 124, 152, /* 930 */ 196, 55, 56, 186, 124, 152, 106, 160, 152, 83, /* 940 */ 152, 164, 152, 61, 22, 211, 212, 152, 97, 98, /* 950 */ 152, 95, 70, 97, 98, 172, 173, 101, 172, 173, /* 960 */ 172, 173, 172, 173, 60, 181, 62, 172, 173, 47, /* 970 */ 48, 123, 186, 97, 98, 71, 100, 55, 56, 152, /* 980 */ 181, 186, 21, 107, 152, 109, 82, 163, 132, 133, /* 990 */ 134, 135, 136, 89, 16, 207, 92, 93, 19, 172, /* 1000 */ 173, 169, 170, 195, 55, 56, 12, 152, 132, 30, /* 1010 */ 134, 47, 48, 186, 206, 225, 152, 95, 114, 97, /* 1020 */ 196, 245, 246, 101, 152, 38, 39, 40, 41, 42, /* 1030 */ 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, /* 1040 */ 53, 152, 163, 219, 152, 141, 97, 98, 193, 152, /* 1050 */ 152, 57, 91, 164, 132, 133, 134, 152, 55, 152, /* 1060 */ 152, 237, 230, 152, 103, 193, 88, 73, 90, 75, /* 1070 */ 172, 173, 183, 152, 185, 196, 152, 172, 173, 172, /* 1080 */ 173, 217, 152, 172, 173, 152, 107, 22, 152, 24, /* 1090 */ 193, 112, 152, 172, 173, 152, 132, 242, 134, 152, /* 1100 */ 97, 140, 152, 92, 152, 172, 173, 152, 172, 173, /* 1110 */ 152, 100, 172, 173, 152, 172, 173, 152, 140, 172, /* 1120 */ 173, 152, 172, 173, 172, 173, 152, 172, 173, 152, /* 1130 */ 172, 173, 152, 152, 172, 173, 152, 172, 173, 213, /* 1140 */ 152, 172, 173, 152, 152, 152, 172, 173, 152, 172, /* 1150 */ 173, 152, 172, 173, 152, 210, 172, 173, 152, 26, /* 1160 */ 172, 173, 152, 172, 173, 172, 173, 152, 172, 173, /* 1170 */ 152, 172, 173, 152, 172, 173, 152, 59, 172, 173, /* 1180 */ 152, 63, 172, 173, 152, 193, 152, 152, 152, 152, /* 1190 */ 172, 173, 152, 172, 173, 77, 172, 173, 152, 152, /* 1200 */ 172, 173, 152, 152, 172, 173, 172, 173, 172, 173, /* 1210 */ 152, 22, 172, 173, 152, 152, 152, 22, 172, 173, /* 1220 */ 152, 152, 152, 172, 173, 152, 7, 8, 9, 163, /* 1230 */ 172, 173, 22, 23, 172, 173, 172, 173, 166, 167, /* 1240 */ 172, 173, 172, 173, 55, 172, 173, 22, 23, 108, /* 1250 */ 109, 110, 217, 152, 217, 166, 167, 163, 163, 163, /* 1260 */ 163, 163, 196, 130, 217, 211, 212, 217, 116, 23, /* 1270 */ 22, 101, 26, 121, 23, 23, 23, 26, 26, 26, /* 1280 */ 23, 23, 112, 26, 26, 37, 97, 100, 101, 55, /* 1290 */ 196, 196, 196, 196, 196, 23, 23, 55, 26, 26, /* 1300 */ 7, 8, 23, 152, 23, 26, 96, 26, 132, 132, /* 1310 */ 134, 134, 23, 152, 152, 26, 152, 122, 152, 191, /* 1320 */ 152, 96, 234, 152, 152, 152, 152, 152, 197, 210, /* 1330 */ 152, 97, 152, 152, 210, 233, 210, 198, 150, 97, /* 1340 */ 184, 201, 239, 214, 214, 201, 239, 180, 214, 227, /* 1350 */ 200, 198, 155, 67, 243, 176, 69, 175, 175, 175, /* 1360 */ 122, 159, 159, 240, 159, 240, 22, 220, 27, 130, /* 1370 */ 201, 18, 159, 18, 189, 158, 158, 220, 192, 159, /* 1380 */ 137, 236, 192, 192, 192, 189, 74, 189, 159, 235, /* 1390 */ 159, 158, 22, 177, 201, 201, 159, 107, 158, 177, /* 1400 */ 159, 174, 158, 76, 174, 182, 174, 106, 182, 125, /* 1410 */ 174, 107, 177, 22, 159, 216, 215, 137, 159, 53, /* 1420 */ 216, 176, 215, 174, 174, 216, 215, 215, 174, 229, /* 1430 */ 216, 129, 224, 177, 126, 229, 127, 177, 128, 25, /* 1440 */ 162, 226, 26, 161, 13, 153, 6, 153, 151, 151, /* 1450 */ 151, 151, 205, 165, 178, 178, 165, 4, 3, 22, /* 1460 */ 165, 142, 15, 94, 202, 204, 203, 201, 16, 23, /* 1470 */ 249, 23, 120, 249, 246, 111, 131, 123, 20, 16, /* 1480 */ 1, 125, 123, 111, 56, 64, 37, 37, 131, 122, /* 1490 */ 1, 37, 5, 37, 22, 107, 26, 80, 140, 80, /* 1500 */ 87, 72, 107, 20, 24, 19, 112, 105, 23, 79, /* 1510 */ 22, 79, 22, 22, 22, 58, 22, 79, 23, 68, /* 1520 */ 23, 23, 26, 116, 22, 26, 23, 22, 122, 23, /* 1530 */ 23, 56, 64, 22, 124, 26, 26, 64, 64, 23, /* 1540 */ 23, 23, 23, 11, 23, 22, 26, 23, 22, 24, /* 1550 */ 1, 23, 22, 26, 251, 24, 23, 22, 122, 23, /* 1560 */ 23, 22, 15, 122, 122, 122, 23, }; #define YY_SHIFT_USE_DFLT (1567) #define YY_SHIFT_COUNT (455) #define YY_SHIFT_MIN (-94) #define YY_SHIFT_MAX (1549) static const short yy_shift_ofst[] = { /* 0 */ 40, 599, 904, 612, 760, 760, 760, 760, 725, -19, /* 10 */ 16, 16, 100, 760, 760, 760, 760, 760, 760, 760, /* 20 */ 876, 876, 573, 542, 719, 600, 61, 137, 172, 207, /* 30 */ 242, 277, 312, 347, 382, 417, 459, 459, 459, 459, /* 40 */ 459, 459, 459, 459, 459, 459, 459, 459, 459, 459, /* 50 */ 459, 459, 459, 494, 459, 529, 564, 564, 705, 760, /* 60 */ 760, 760, 760, 760, 760, 760, 760, 760, 760, 760, /* 70 */ 760, 760, 760, 760, 760, 760, 760, 760, 760, 760, /* 80 */ 760, 760, 760, 760, 760, 760, 760, 760, 760, 760, /* 90 */ 856, 760, 760, 760, 760, 760, 760, 760, 760, 760, /* 100 */ 760, 760, 760, 760, 987, 746, 746, 746, 746, 746, /* 110 */ 801, 23, 32, 949, 961, 979, 964, 964, 949, 73, /* 120 */ 113, -51, 1567, 1567, 1567, 536, 536, 536, 99, 99, /* 130 */ 813, 813, 667, 205, 240, 949, 949, 949, 949, 949, /* 140 */ 949, 949, 949, 949, 949, 949, 949, 949, 949, 949, /* 150 */ 949, 949, 949, 949, 949, 332, 1011, 422, 422, 113, /* 160 */ 30, 30, 30, 30, 30, 30, 1567, 1567, 1567, 922, /* 170 */ -94, -94, 384, 613, 828, 420, 765, 804, 851, 949, /* 180 */ 949, 949, 949, 949, 949, 949, 949, 949, 949, 949, /* 190 */ 949, 949, 949, 949, 949, 672, 672, 672, 949, 949, /* 200 */ 657, 949, 949, 949, -18, 949, 949, 994, 949, 949, /* 210 */ 949, 949, 949, 949, 949, 949, 949, 949, 772, 1118, /* 220 */ 712, 712, 712, 810, 45, 769, 1219, 1133, 418, 418, /* 230 */ 569, 1133, 569, 830, 607, 663, 882, 418, 693, 882, /* 240 */ 882, 848, 1152, 1065, 1286, 1238, 1238, 1287, 1287, 1238, /* 250 */ 1344, 1341, 1239, 1353, 1353, 1353, 1353, 1238, 1355, 1239, /* 260 */ 1344, 1341, 1341, 1239, 1238, 1355, 1243, 1312, 1238, 1238, /* 270 */ 1355, 1370, 1238, 1355, 1238, 1355, 1370, 1290, 1290, 1290, /* 280 */ 1327, 1370, 1290, 1301, 1290, 1327, 1290, 1290, 1284, 1304, /* 290 */ 1284, 1304, 1284, 1304, 1284, 1304, 1238, 1391, 1238, 1280, /* 300 */ 1370, 1366, 1366, 1370, 1302, 1308, 1310, 1309, 1239, 1414, /* 310 */ 1416, 1431, 1431, 1440, 1440, 1440, 1440, 1567, 1567, 1567, /* 320 */ 1567, 1567, 1567, 1567, 1567, 519, 978, 1210, 1225, 104, /* 330 */ 1141, 1189, 1246, 1248, 1251, 1252, 1253, 1257, 1258, 1273, /* 340 */ 1003, 1187, 1293, 1170, 1272, 1279, 1234, 1281, 1176, 1177, /* 350 */ 1289, 1242, 1195, 1453, 1455, 1437, 1319, 1447, 1369, 1452, /* 360 */ 1446, 1448, 1352, 1345, 1364, 1354, 1458, 1356, 1463, 1479, /* 370 */ 1359, 1357, 1449, 1450, 1454, 1456, 1372, 1428, 1421, 1367, /* 380 */ 1489, 1487, 1472, 1388, 1358, 1417, 1470, 1419, 1413, 1429, /* 390 */ 1395, 1480, 1483, 1486, 1394, 1402, 1488, 1430, 1490, 1491, /* 400 */ 1485, 1492, 1432, 1457, 1494, 1438, 1451, 1495, 1497, 1498, /* 410 */ 1496, 1407, 1502, 1503, 1505, 1499, 1406, 1506, 1507, 1475, /* 420 */ 1468, 1511, 1410, 1509, 1473, 1510, 1474, 1516, 1509, 1517, /* 430 */ 1518, 1519, 1520, 1521, 1523, 1532, 1524, 1526, 1525, 1527, /* 440 */ 1528, 1530, 1531, 1527, 1533, 1535, 1536, 1537, 1539, 1436, /* 450 */ 1441, 1442, 1443, 1543, 1547, 1549, }; #define YY_REDUCE_USE_DFLT (-130) #define YY_REDUCE_COUNT (324) #define YY_REDUCE_MIN (-129) #define YY_REDUCE_MAX (1300) static const short yy_reduce_ofst[] = { /* 0 */ -29, 566, 525, 605, -49, 307, 491, 533, 668, 435, /* 10 */ 601, 644, 148, 747, 786, 795, 419, 788, 827, 790, /* 20 */ 454, 832, 889, 495, 824, 734, 76, 76, 76, 76, /* 30 */ 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, /* 40 */ 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, /* 50 */ 76, 76, 76, 76, 76, 76, 76, 76, 783, 898, /* 60 */ 905, 907, 911, 921, 933, 936, 940, 943, 947, 950, /* 70 */ 952, 955, 958, 962, 965, 969, 974, 977, 980, 984, /* 80 */ 988, 991, 993, 996, 999, 1002, 1006, 1010, 1018, 1021, /* 90 */ 1024, 1028, 1032, 1034, 1036, 1040, 1046, 1051, 1058, 1062, /* 100 */ 1064, 1068, 1070, 1073, 76, 76, 76, 76, 76, 76, /* 110 */ 76, 76, 76, 855, 36, 523, 235, 416, 777, 76, /* 120 */ 278, 76, 76, 76, 76, 700, 700, 700, 150, 220, /* 130 */ 147, 217, 221, 306, 306, 611, 5, 535, 556, 620, /* 140 */ 720, 872, 897, 116, 864, 349, 1035, 1037, 404, 1047, /* 150 */ 992, -129, 1050, 492, 62, 722, 879, 1072, 1089, 808, /* 160 */ 1066, 1094, 1095, 1096, 1097, 1098, 776, 1054, 557, 57, /* 170 */ 112, 131, 167, 182, 250, 272, 291, 331, 364, 438, /* 180 */ 497, 517, 591, 653, 690, 739, 775, 798, 892, 908, /* 190 */ 924, 930, 1015, 1063, 1069, 355, 784, 799, 981, 1101, /* 200 */ 926, 1151, 1161, 1162, 945, 1164, 1166, 1128, 1168, 1171, /* 210 */ 1172, 250, 1173, 1174, 1175, 1178, 1180, 1181, 1088, 1102, /* 220 */ 1119, 1124, 1126, 926, 1131, 1139, 1188, 1140, 1129, 1130, /* 230 */ 1103, 1144, 1107, 1179, 1156, 1167, 1182, 1134, 1122, 1183, /* 240 */ 1184, 1150, 1153, 1197, 1111, 1202, 1203, 1123, 1125, 1205, /* 250 */ 1147, 1185, 1169, 1186, 1190, 1191, 1192, 1213, 1217, 1193, /* 260 */ 1157, 1196, 1198, 1194, 1220, 1218, 1145, 1154, 1229, 1231, /* 270 */ 1233, 1216, 1237, 1240, 1241, 1244, 1222, 1227, 1230, 1232, /* 280 */ 1223, 1235, 1236, 1245, 1249, 1226, 1250, 1254, 1199, 1201, /* 290 */ 1204, 1207, 1209, 1211, 1214, 1212, 1255, 1208, 1259, 1215, /* 300 */ 1256, 1200, 1206, 1260, 1247, 1261, 1263, 1262, 1266, 1278, /* 310 */ 1282, 1292, 1294, 1297, 1298, 1299, 1300, 1221, 1224, 1228, /* 320 */ 1288, 1291, 1276, 1277, 1295, }; static const YYACTIONTYPE yy_default[] = { /* 0 */ 1281, 1271, 1271, 1271, 1203, 1203, 1203, 1203, 1271, 1096, /* 10 */ 1125, 1125, 1255, 1332, 1332, 1332, 1332, 1332, 1332, 1202, /* 20 */ 1332, 1332, 1332, 1332, 1271, 1100, 1131, 1332, 1332, 1332, /* 30 */ 1332, 1204, 1205, 1332, 1332, 1332, 1254, 1256, 1141, 1140, /* 40 */ 1139, 1138, 1237, 1112, 1136, 1129, 1133, 1204, 1198, 1199, /* 50 */ 1197, 1201, 1205, 1332, 1132, 1167, 1182, 1166, 1332, 1332, /* 60 */ 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, /* 70 */ 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, /* 80 */ 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, /* 90 */ 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, /* 100 */ 1332, 1332, 1332, 1332, 1176, 1181, 1188, 1180, 1177, 1169, /* 110 */ 1168, 1170, 1171, 1332, 1019, 1067, 1332, 1332, 1332, 1172, /* 120 */ 1332, 1173, 1185, 1184, 1183, 1262, 1289, 1288, 1332, 1332, /* 130 */ 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, /* 140 */ 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, /* 150 */ 1332, 1332, 1332, 1332, 1332, 1281, 1271, 1025, 1025, 1332, /* 160 */ 1271, 1271, 1271, 1271, 1271, 1271, 1267, 1100, 1091, 1332, /* 170 */ 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, /* 180 */ 1259, 1257, 1332, 1218, 1332, 1332, 1332, 1332, 1332, 1332, /* 190 */ 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, /* 200 */ 1332, 1332, 1332, 1332, 1096, 1332, 1332, 1332, 1332, 1332, /* 210 */ 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1283, 1332, 1232, /* 220 */ 1096, 1096, 1096, 1098, 1080, 1090, 1004, 1135, 1114, 1114, /* 230 */ 1321, 1135, 1321, 1042, 1303, 1039, 1125, 1114, 1200, 1125, /* 240 */ 1125, 1097, 1090, 1332, 1324, 1105, 1105, 1323, 1323, 1105, /* 250 */ 1146, 1070, 1135, 1076, 1076, 1076, 1076, 1105, 1016, 1135, /* 260 */ 1146, 1070, 1070, 1135, 1105, 1016, 1236, 1318, 1105, 1105, /* 270 */ 1016, 1211, 1105, 1016, 1105, 1016, 1211, 1068, 1068, 1068, /* 280 */ 1057, 1211, 1068, 1042, 1068, 1057, 1068, 1068, 1118, 1113, /* 290 */ 1118, 1113, 1118, 1113, 1118, 1113, 1105, 1206, 1105, 1332, /* 300 */ 1211, 1215, 1215, 1211, 1130, 1119, 1128, 1126, 1135, 1022, /* 310 */ 1060, 1286, 1286, 1282, 1282, 1282, 1282, 1329, 1329, 1267, /* 320 */ 1298, 1298, 1044, 1044, 1298, 1332, 1332, 1332, 1332, 1332, /* 330 */ 1332, 1293, 1332, 1220, 1332, 1332, 1332, 1332, 1332, 1332, /* 340 */ 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, /* 350 */ 1332, 1332, 1152, 1332, 1000, 1264, 1332, 1332, 1263, 1332, /* 360 */ 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, /* 370 */ 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1320, /* 380 */ 1332, 1332, 1332, 1332, 1332, 1332, 1235, 1234, 1332, 1332, /* 390 */ 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, /* 400 */ 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, /* 410 */ 1332, 1082, 1332, 1332, 1332, 1307, 1332, 1332, 1332, 1332, /* 420 */ 1332, 1332, 1332, 1127, 1332, 1120, 1332, 1332, 1311, 1332, /* 430 */ 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1273, /* 440 */ 1332, 1332, 1332, 1272, 1332, 1332, 1332, 1332, 1332, 1154, /* 450 */ 1332, 1153, 1157, 1332, 1010, 1332, }; /********** End of lemon-generated parsing tables *****************************/ /* The next table maps tokens (terminal symbols) into fallback tokens. ** If a construct like the following: ** ** %fallback ID X Y Z. ** ** appears in the grammar, then ID becomes a fallback token for X, Y, ** and Z. Whenever one of the tokens X, Y, or Z is input to the parser ** but it does not parse, the type of the token is changed to ID and ** the parse is retried before an error is thrown. ** ** This feature can be used, for example, to cause some keywords in a language ** to revert to identifiers if they keyword does not apply in the context where ** it appears. */ #ifdef YYFALLBACK static const YYCODETYPE yyFallback[] = { 0, /* $ => nothing */ 0, /* SEMI => nothing */ 55, /* EXPLAIN => ID */ 55, /* QUERY => ID */ 55, /* PLAN => ID */ 55, /* BEGIN => ID */ 0, /* TRANSACTION => nothing */ 55, /* DEFERRED => ID */ 55, /* IMMEDIATE => ID */ 55, /* EXCLUSIVE => ID */ 0, /* COMMIT => nothing */ 55, /* END => ID */ 55, /* ROLLBACK => ID */ 55, /* SAVEPOINT => ID */ 55, /* RELEASE => ID */ 0, /* TO => nothing */ 0, /* TABLE => nothing */ 0, /* CREATE => nothing */ 55, /* IF => ID */ 0, /* NOT => nothing */ 0, /* EXISTS => nothing */ 55, /* TEMP => ID */ 0, /* LP => nothing */ 0, /* RP => nothing */ 0, /* AS => nothing */ 55, /* WITHOUT => ID */ 0, /* COMMA => nothing */ 0, /* OR => nothing */ 0, /* AND => nothing */ 0, /* IS => nothing */ 55, /* MATCH => ID */ 55, /* LIKE_KW => ID */ 0, /* BETWEEN => nothing */ 0, /* IN => nothing */ 0, /* ISNULL => nothing */ 0, /* NOTNULL => nothing */ 0, /* NE => nothing */ 0, /* EQ => nothing */ 0, /* GT => nothing */ 0, /* LE => nothing */ 0, /* LT => nothing */ 0, /* GE => nothing */ 0, /* ESCAPE => nothing */ 0, /* BITAND => nothing */ 0, /* BITOR => nothing */ 0, /* LSHIFT => nothing */ 0, /* RSHIFT => nothing */ 0, /* PLUS => nothing */ 0, /* MINUS => nothing */ 0, /* STAR => nothing */ 0, /* SLASH => nothing */ 0, /* REM => nothing */ 0, /* CONCAT => nothing */ 0, /* COLLATE => nothing */ 0, /* BITNOT => nothing */ 0, /* ID => nothing */ 0, /* INDEXED => nothing */ 55, /* ABORT => ID */ 55, /* ACTION => ID */ 55, /* AFTER => ID */ 55, /* ANALYZE => ID */ 55, /* ASC => ID */ 55, /* ATTACH => ID */ 55, /* BEFORE => ID */ 55, /* BY => ID */ 55, /* CASCADE => ID */ 55, /* CAST => ID */ 55, /* COLUMNKW => ID */ 55, /* CONFLICT => ID */ 55, /* DATABASE => ID */ 55, /* DESC => ID */ 55, /* DETACH => ID */ 55, /* EACH => ID */ 55, /* FAIL => ID */ 55, /* FOR => ID */ 55, /* IGNORE => ID */ 55, /* INITIALLY => ID */ 55, /* INSTEAD => ID */ 55, /* NO => ID */ 55, /* KEY => ID */ 55, /* OF => ID */ 55, /* OFFSET => ID */ 55, /* PRAGMA => ID */ 55, /* RAISE => ID */ 55, /* RECURSIVE => ID */ 55, /* REPLACE => ID */ 55, /* RESTRICT => ID */ 55, /* ROW => ID */ 55, /* TRIGGER => ID */ 55, /* VACUUM => ID */ 55, /* VIEW => ID */ 55, /* VIRTUAL => ID */ 55, /* WITH => ID */ 55, /* REINDEX => ID */ 55, /* RENAME => ID */ 55, /* CTIME_KW => ID */ }; #endif /* YYFALLBACK */ /* The following structure represents a single element of the ** parser's stack. Information stored includes: ** ** + The state number for the parser at this level of the stack. ** ** + The value of the token stored at this level of the stack. ** (In other words, the "major" token.) ** ** + The semantic value stored at this level of the stack. This is ** the information used by the action routines in the grammar. ** It is sometimes called the "minor" token. ** ** After the "shift" half of a SHIFTREDUCE action, the stateno field ** actually contains the reduce action for the second half of the ** SHIFTREDUCE. */ struct yyStackEntry { YYACTIONTYPE stateno; /* The state-number, or reduce action in SHIFTREDUCE */ YYCODETYPE major; /* The major token value. This is the code ** number for the token at this stack level */ YYMINORTYPE minor; /* The user-supplied minor token value. This ** is the value of the token */ }; typedef struct yyStackEntry yyStackEntry; /* The state of the parser is completely contained in an instance of ** the following structure */ struct yyParser { yyStackEntry *yytos; /* Pointer to top element of the stack */ #ifdef YYTRACKMAXSTACKDEPTH int yyhwm; /* High-water mark of the stack */ #endif #ifndef YYNOERRORRECOVERY int yyerrcnt; /* Shifts left before out of the error */ #endif sqlite3ParserARG_SDECL /* A place to hold %extra_argument */ #if YYSTACKDEPTH<=0 int yystksz; /* Current side of the stack */ yyStackEntry *yystack; /* The parser's stack */ yyStackEntry yystk0; /* First stack entry */ #else yyStackEntry yystack[YYSTACKDEPTH]; /* The parser's stack */ #endif }; typedef struct yyParser yyParser; #ifndef NDEBUG /* #include */ static FILE *yyTraceFILE = 0; static char *yyTracePrompt = 0; #endif /* NDEBUG */ #ifndef NDEBUG /* ** Turn parser tracing on by giving a stream to which to write the trace ** and a prompt to preface each trace message. Tracing is turned off ** by making either argument NULL ** ** Inputs: **
      **
    • A FILE* to which trace output should be written. ** If NULL, then tracing is turned off. **
    • A prefix string written at the beginning of every ** line of trace output. If NULL, then tracing is ** turned off. **
    ** ** Outputs: ** None. */ SQLITE_PRIVATE void sqlite3ParserTrace(FILE *TraceFILE, char *zTracePrompt){ yyTraceFILE = TraceFILE; yyTracePrompt = zTracePrompt; if( yyTraceFILE==0 ) yyTracePrompt = 0; else if( yyTracePrompt==0 ) yyTraceFILE = 0; } #endif /* NDEBUG */ #ifndef NDEBUG /* For tracing shifts, the names of all terminals and nonterminals ** are required. The following table supplies these names */ static const char *const yyTokenName[] = { "$", "SEMI", "EXPLAIN", "QUERY", "PLAN", "BEGIN", "TRANSACTION", "DEFERRED", "IMMEDIATE", "EXCLUSIVE", "COMMIT", "END", "ROLLBACK", "SAVEPOINT", "RELEASE", "TO", "TABLE", "CREATE", "IF", "NOT", "EXISTS", "TEMP", "LP", "RP", "AS", "WITHOUT", "COMMA", "OR", "AND", "IS", "MATCH", "LIKE_KW", "BETWEEN", "IN", "ISNULL", "NOTNULL", "NE", "EQ", "GT", "LE", "LT", "GE", "ESCAPE", "BITAND", "BITOR", "LSHIFT", "RSHIFT", "PLUS", "MINUS", "STAR", "SLASH", "REM", "CONCAT", "COLLATE", "BITNOT", "ID", "INDEXED", "ABORT", "ACTION", "AFTER", "ANALYZE", "ASC", "ATTACH", "BEFORE", "BY", "CASCADE", "CAST", "COLUMNKW", "CONFLICT", "DATABASE", "DESC", "DETACH", "EACH", "FAIL", "FOR", "IGNORE", "INITIALLY", "INSTEAD", "NO", "KEY", "OF", "OFFSET", "PRAGMA", "RAISE", "RECURSIVE", "REPLACE", "RESTRICT", "ROW", "TRIGGER", "VACUUM", "VIEW", "VIRTUAL", "WITH", "REINDEX", "RENAME", "CTIME_KW", "ANY", "STRING", "JOIN_KW", "CONSTRAINT", "DEFAULT", "NULL", "PRIMARY", "UNIQUE", "CHECK", "REFERENCES", "AUTOINCR", "ON", "INSERT", "DELETE", "UPDATE", "SET", "DEFERRABLE", "FOREIGN", "DROP", "UNION", "ALL", "EXCEPT", "INTERSECT", "SELECT", "VALUES", "DISTINCT", "DOT", "FROM", "JOIN", "USING", "ORDER", "GROUP", "HAVING", "LIMIT", "WHERE", "INTO", "FLOAT", "BLOB", "INTEGER", "VARIABLE", "CASE", "WHEN", "THEN", "ELSE", "INDEX", "ALTER", "ADD", "error", "input", "cmdlist", "ecmd", "explain", "cmdx", "cmd", "transtype", "trans_opt", "nm", "savepoint_opt", "create_table", "create_table_args", "createkw", "temp", "ifnotexists", "dbnm", "columnlist", "conslist_opt", "table_options", "select", "columnname", "carglist", "typetoken", "typename", "signed", "plus_num", "minus_num", "ccons", "term", "expr", "onconf", "sortorder", "autoinc", "eidlist_opt", "refargs", "defer_subclause", "refarg", "refact", "init_deferred_pred_opt", "conslist", "tconscomma", "tcons", "sortlist", "eidlist", "defer_subclause_opt", "orconf", "resolvetype", "raisetype", "ifexists", "fullname", "selectnowith", "oneselect", "with", "multiselect_op", "distinct", "selcollist", "from", "where_opt", "groupby_opt", "having_opt", "orderby_opt", "limit_opt", "values", "nexprlist", "exprlist", "sclp", "as", "seltablist", "stl_prefix", "joinop", "indexed_opt", "on_opt", "using_opt", "idlist", "setlist", "insert_cmd", "idlist_opt", "likeop", "between_op", "in_op", "paren_exprlist", "case_operand", "case_exprlist", "case_else", "uniqueflag", "collate", "nmnum", "trigger_decl", "trigger_cmd_list", "trigger_time", "trigger_event", "foreach_clause", "when_clause", "trigger_cmd", "trnm", "tridxby", "database_kw_opt", "key_opt", "add_column_fullname", "kwcolumn_opt", "create_vtab", "vtabarglist", "vtabarg", "vtabargtoken", "lp", "anylist", "wqlist", }; #endif /* NDEBUG */ #ifndef NDEBUG /* For tracing reduce actions, the names of all rules are required. */ static const char *const yyRuleName[] = { /* 0 */ "explain ::= EXPLAIN", /* 1 */ "explain ::= EXPLAIN QUERY PLAN", /* 2 */ "cmdx ::= cmd", /* 3 */ "cmd ::= BEGIN transtype trans_opt", /* 4 */ "transtype ::=", /* 5 */ "transtype ::= DEFERRED", /* 6 */ "transtype ::= IMMEDIATE", /* 7 */ "transtype ::= EXCLUSIVE", /* 8 */ "cmd ::= COMMIT trans_opt", /* 9 */ "cmd ::= END trans_opt", /* 10 */ "cmd ::= ROLLBACK trans_opt", /* 11 */ "cmd ::= SAVEPOINT nm", /* 12 */ "cmd ::= RELEASE savepoint_opt nm", /* 13 */ "cmd ::= ROLLBACK trans_opt TO savepoint_opt nm", /* 14 */ "create_table ::= createkw temp TABLE ifnotexists nm dbnm", /* 15 */ "createkw ::= CREATE", /* 16 */ "ifnotexists ::=", /* 17 */ "ifnotexists ::= IF NOT EXISTS", /* 18 */ "temp ::= TEMP", /* 19 */ "temp ::=", /* 20 */ "create_table_args ::= LP columnlist conslist_opt RP table_options", /* 21 */ "create_table_args ::= AS select", /* 22 */ "table_options ::=", /* 23 */ "table_options ::= WITHOUT nm", /* 24 */ "columnname ::= nm typetoken", /* 25 */ "typetoken ::=", /* 26 */ "typetoken ::= typename LP signed RP", /* 27 */ "typetoken ::= typename LP signed COMMA signed RP", /* 28 */ "typename ::= typename ID|STRING", /* 29 */ "ccons ::= CONSTRAINT nm", /* 30 */ "ccons ::= DEFAULT term", /* 31 */ "ccons ::= DEFAULT LP expr RP", /* 32 */ "ccons ::= DEFAULT PLUS term", /* 33 */ "ccons ::= DEFAULT MINUS term", /* 34 */ "ccons ::= DEFAULT ID|INDEXED", /* 35 */ "ccons ::= NOT NULL onconf", /* 36 */ "ccons ::= PRIMARY KEY sortorder onconf autoinc", /* 37 */ "ccons ::= UNIQUE onconf", /* 38 */ "ccons ::= CHECK LP expr RP", /* 39 */ "ccons ::= REFERENCES nm eidlist_opt refargs", /* 40 */ "ccons ::= defer_subclause", /* 41 */ "ccons ::= COLLATE ID|STRING", /* 42 */ "autoinc ::=", /* 43 */ "autoinc ::= AUTOINCR", /* 44 */ "refargs ::=", /* 45 */ "refargs ::= refargs refarg", /* 46 */ "refarg ::= MATCH nm", /* 47 */ "refarg ::= ON INSERT refact", /* 48 */ "refarg ::= ON DELETE refact", /* 49 */ "refarg ::= ON UPDATE refact", /* 50 */ "refact ::= SET NULL", /* 51 */ "refact ::= SET DEFAULT", /* 52 */ "refact ::= CASCADE", /* 53 */ "refact ::= RESTRICT", /* 54 */ "refact ::= NO ACTION", /* 55 */ "defer_subclause ::= NOT DEFERRABLE init_deferred_pred_opt", /* 56 */ "defer_subclause ::= DEFERRABLE init_deferred_pred_opt", /* 57 */ "init_deferred_pred_opt ::=", /* 58 */ "init_deferred_pred_opt ::= INITIALLY DEFERRED", /* 59 */ "init_deferred_pred_opt ::= INITIALLY IMMEDIATE", /* 60 */ "conslist_opt ::=", /* 61 */ "tconscomma ::= COMMA", /* 62 */ "tcons ::= CONSTRAINT nm", /* 63 */ "tcons ::= PRIMARY KEY LP sortlist autoinc RP onconf", /* 64 */ "tcons ::= UNIQUE LP sortlist RP onconf", /* 65 */ "tcons ::= CHECK LP expr RP onconf", /* 66 */ "tcons ::= FOREIGN KEY LP eidlist RP REFERENCES nm eidlist_opt refargs defer_subclause_opt", /* 67 */ "defer_subclause_opt ::=", /* 68 */ "onconf ::=", /* 69 */ "onconf ::= ON CONFLICT resolvetype", /* 70 */ "orconf ::=", /* 71 */ "orconf ::= OR resolvetype", /* 72 */ "resolvetype ::= IGNORE", /* 73 */ "resolvetype ::= REPLACE", /* 74 */ "cmd ::= DROP TABLE ifexists fullname", /* 75 */ "ifexists ::= IF EXISTS", /* 76 */ "ifexists ::=", /* 77 */ "cmd ::= createkw temp VIEW ifnotexists nm dbnm eidlist_opt AS select", /* 78 */ "cmd ::= DROP VIEW ifexists fullname", /* 79 */ "cmd ::= select", /* 80 */ "select ::= with selectnowith", /* 81 */ "selectnowith ::= selectnowith multiselect_op oneselect", /* 82 */ "multiselect_op ::= UNION", /* 83 */ "multiselect_op ::= UNION ALL", /* 84 */ "multiselect_op ::= EXCEPT|INTERSECT", /* 85 */ "oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt orderby_opt limit_opt", /* 86 */ "values ::= VALUES LP nexprlist RP", /* 87 */ "values ::= values COMMA LP exprlist RP", /* 88 */ "distinct ::= DISTINCT", /* 89 */ "distinct ::= ALL", /* 90 */ "distinct ::=", /* 91 */ "sclp ::=", /* 92 */ "selcollist ::= sclp expr as", /* 93 */ "selcollist ::= sclp STAR", /* 94 */ "selcollist ::= sclp nm DOT STAR", /* 95 */ "as ::= AS nm", /* 96 */ "as ::=", /* 97 */ "from ::=", /* 98 */ "from ::= FROM seltablist", /* 99 */ "stl_prefix ::= seltablist joinop", /* 100 */ "stl_prefix ::=", /* 101 */ "seltablist ::= stl_prefix nm dbnm as indexed_opt on_opt using_opt", /* 102 */ "seltablist ::= stl_prefix nm dbnm LP exprlist RP as on_opt using_opt", /* 103 */ "seltablist ::= stl_prefix LP select RP as on_opt using_opt", /* 104 */ "seltablist ::= stl_prefix LP seltablist RP as on_opt using_opt", /* 105 */ "dbnm ::=", /* 106 */ "dbnm ::= DOT nm", /* 107 */ "fullname ::= nm dbnm", /* 108 */ "joinop ::= COMMA|JOIN", /* 109 */ "joinop ::= JOIN_KW JOIN", /* 110 */ "joinop ::= JOIN_KW nm JOIN", /* 111 */ "joinop ::= JOIN_KW nm nm JOIN", /* 112 */ "on_opt ::= ON expr", /* 113 */ "on_opt ::=", /* 114 */ "indexed_opt ::=", /* 115 */ "indexed_opt ::= INDEXED BY nm", /* 116 */ "indexed_opt ::= NOT INDEXED", /* 117 */ "using_opt ::= USING LP idlist RP", /* 118 */ "using_opt ::=", /* 119 */ "orderby_opt ::=", /* 120 */ "orderby_opt ::= ORDER BY sortlist", /* 121 */ "sortlist ::= sortlist COMMA expr sortorder", /* 122 */ "sortlist ::= expr sortorder", /* 123 */ "sortorder ::= ASC", /* 124 */ "sortorder ::= DESC", /* 125 */ "sortorder ::=", /* 126 */ "groupby_opt ::=", /* 127 */ "groupby_opt ::= GROUP BY nexprlist", /* 128 */ "having_opt ::=", /* 129 */ "having_opt ::= HAVING expr", /* 130 */ "limit_opt ::=", /* 131 */ "limit_opt ::= LIMIT expr", /* 132 */ "limit_opt ::= LIMIT expr OFFSET expr", /* 133 */ "limit_opt ::= LIMIT expr COMMA expr", /* 134 */ "cmd ::= with DELETE FROM fullname indexed_opt where_opt", /* 135 */ "where_opt ::=", /* 136 */ "where_opt ::= WHERE expr", /* 137 */ "cmd ::= with UPDATE orconf fullname indexed_opt SET setlist where_opt", /* 138 */ "setlist ::= setlist COMMA nm EQ expr", /* 139 */ "setlist ::= setlist COMMA LP idlist RP EQ expr", /* 140 */ "setlist ::= nm EQ expr", /* 141 */ "setlist ::= LP idlist RP EQ expr", /* 142 */ "cmd ::= with insert_cmd INTO fullname idlist_opt select", /* 143 */ "cmd ::= with insert_cmd INTO fullname idlist_opt DEFAULT VALUES", /* 144 */ "insert_cmd ::= INSERT orconf", /* 145 */ "insert_cmd ::= REPLACE", /* 146 */ "idlist_opt ::=", /* 147 */ "idlist_opt ::= LP idlist RP", /* 148 */ "idlist ::= idlist COMMA nm", /* 149 */ "idlist ::= nm", /* 150 */ "expr ::= LP expr RP", /* 151 */ "term ::= NULL", /* 152 */ "expr ::= ID|INDEXED", /* 153 */ "expr ::= JOIN_KW", /* 154 */ "expr ::= nm DOT nm", /* 155 */ "expr ::= nm DOT nm DOT nm", /* 156 */ "term ::= FLOAT|BLOB", /* 157 */ "term ::= STRING", /* 158 */ "term ::= INTEGER", /* 159 */ "expr ::= VARIABLE", /* 160 */ "expr ::= expr COLLATE ID|STRING", /* 161 */ "expr ::= CAST LP expr AS typetoken RP", /* 162 */ "expr ::= ID|INDEXED LP distinct exprlist RP", /* 163 */ "expr ::= ID|INDEXED LP STAR RP", /* 164 */ "term ::= CTIME_KW", /* 165 */ "expr ::= LP nexprlist COMMA expr RP", /* 166 */ "expr ::= expr AND expr", /* 167 */ "expr ::= expr OR expr", /* 168 */ "expr ::= expr LT|GT|GE|LE expr", /* 169 */ "expr ::= expr EQ|NE expr", /* 170 */ "expr ::= expr BITAND|BITOR|LSHIFT|RSHIFT expr", /* 171 */ "expr ::= expr PLUS|MINUS expr", /* 172 */ "expr ::= expr STAR|SLASH|REM expr", /* 173 */ "expr ::= expr CONCAT expr", /* 174 */ "likeop ::= LIKE_KW|MATCH", /* 175 */ "likeop ::= NOT LIKE_KW|MATCH", /* 176 */ "expr ::= expr likeop expr", /* 177 */ "expr ::= expr likeop expr ESCAPE expr", /* 178 */ "expr ::= expr ISNULL|NOTNULL", /* 179 */ "expr ::= expr NOT NULL", /* 180 */ "expr ::= expr IS expr", /* 181 */ "expr ::= expr IS NOT expr", /* 182 */ "expr ::= NOT expr", /* 183 */ "expr ::= BITNOT expr", /* 184 */ "expr ::= MINUS expr", /* 185 */ "expr ::= PLUS expr", /* 186 */ "between_op ::= BETWEEN", /* 187 */ "between_op ::= NOT BETWEEN", /* 188 */ "expr ::= expr between_op expr AND expr", /* 189 */ "in_op ::= IN", /* 190 */ "in_op ::= NOT IN", /* 191 */ "expr ::= expr in_op LP exprlist RP", /* 192 */ "expr ::= LP select RP", /* 193 */ "expr ::= expr in_op LP select RP", /* 194 */ "expr ::= expr in_op nm dbnm paren_exprlist", /* 195 */ "expr ::= EXISTS LP select RP", /* 196 */ "expr ::= CASE case_operand case_exprlist case_else END", /* 197 */ "case_exprlist ::= case_exprlist WHEN expr THEN expr", /* 198 */ "case_exprlist ::= WHEN expr THEN expr", /* 199 */ "case_else ::= ELSE expr", /* 200 */ "case_else ::=", /* 201 */ "case_operand ::= expr", /* 202 */ "case_operand ::=", /* 203 */ "exprlist ::=", /* 204 */ "nexprlist ::= nexprlist COMMA expr", /* 205 */ "nexprlist ::= expr", /* 206 */ "paren_exprlist ::=", /* 207 */ "paren_exprlist ::= LP exprlist RP", /* 208 */ "cmd ::= createkw uniqueflag INDEX ifnotexists nm dbnm ON nm LP sortlist RP where_opt", /* 209 */ "uniqueflag ::= UNIQUE", /* 210 */ "uniqueflag ::=", /* 211 */ "eidlist_opt ::=", /* 212 */ "eidlist_opt ::= LP eidlist RP", /* 213 */ "eidlist ::= eidlist COMMA nm collate sortorder", /* 214 */ "eidlist ::= nm collate sortorder", /* 215 */ "collate ::=", /* 216 */ "collate ::= COLLATE ID|STRING", /* 217 */ "cmd ::= DROP INDEX ifexists fullname", /* 218 */ "cmd ::= VACUUM", /* 219 */ "cmd ::= VACUUM nm", /* 220 */ "cmd ::= PRAGMA nm dbnm", /* 221 */ "cmd ::= PRAGMA nm dbnm EQ nmnum", /* 222 */ "cmd ::= PRAGMA nm dbnm LP nmnum RP", /* 223 */ "cmd ::= PRAGMA nm dbnm EQ minus_num", /* 224 */ "cmd ::= PRAGMA nm dbnm LP minus_num RP", /* 225 */ "plus_num ::= PLUS INTEGER|FLOAT", /* 226 */ "minus_num ::= MINUS INTEGER|FLOAT", /* 227 */ "cmd ::= createkw trigger_decl BEGIN trigger_cmd_list END", /* 228 */ "trigger_decl ::= temp TRIGGER ifnotexists nm dbnm trigger_time trigger_event ON fullname foreach_clause when_clause", /* 229 */ "trigger_time ::= BEFORE", /* 230 */ "trigger_time ::= AFTER", /* 231 */ "trigger_time ::= INSTEAD OF", /* 232 */ "trigger_time ::=", /* 233 */ "trigger_event ::= DELETE|INSERT", /* 234 */ "trigger_event ::= UPDATE", /* 235 */ "trigger_event ::= UPDATE OF idlist", /* 236 */ "when_clause ::=", /* 237 */ "when_clause ::= WHEN expr", /* 238 */ "trigger_cmd_list ::= trigger_cmd_list trigger_cmd SEMI", /* 239 */ "trigger_cmd_list ::= trigger_cmd SEMI", /* 240 */ "trnm ::= nm DOT nm", /* 241 */ "tridxby ::= INDEXED BY nm", /* 242 */ "tridxby ::= NOT INDEXED", /* 243 */ "trigger_cmd ::= UPDATE orconf trnm tridxby SET setlist where_opt", /* 244 */ "trigger_cmd ::= insert_cmd INTO trnm idlist_opt select", /* 245 */ "trigger_cmd ::= DELETE FROM trnm tridxby where_opt", /* 246 */ "trigger_cmd ::= select", /* 247 */ "expr ::= RAISE LP IGNORE RP", /* 248 */ "expr ::= RAISE LP raisetype COMMA nm RP", /* 249 */ "raisetype ::= ROLLBACK", /* 250 */ "raisetype ::= ABORT", /* 251 */ "raisetype ::= FAIL", /* 252 */ "cmd ::= DROP TRIGGER ifexists fullname", /* 253 */ "cmd ::= ATTACH database_kw_opt expr AS expr key_opt", /* 254 */ "cmd ::= DETACH database_kw_opt expr", /* 255 */ "key_opt ::=", /* 256 */ "key_opt ::= KEY expr", /* 257 */ "cmd ::= REINDEX", /* 258 */ "cmd ::= REINDEX nm dbnm", /* 259 */ "cmd ::= ANALYZE", /* 260 */ "cmd ::= ANALYZE nm dbnm", /* 261 */ "cmd ::= ALTER TABLE fullname RENAME TO nm", /* 262 */ "cmd ::= ALTER TABLE add_column_fullname ADD kwcolumn_opt columnname carglist", /* 263 */ "add_column_fullname ::= fullname", /* 264 */ "cmd ::= create_vtab", /* 265 */ "cmd ::= create_vtab LP vtabarglist RP", /* 266 */ "create_vtab ::= createkw VIRTUAL TABLE ifnotexists nm dbnm USING nm", /* 267 */ "vtabarg ::=", /* 268 */ "vtabargtoken ::= ANY", /* 269 */ "vtabargtoken ::= lp anylist RP", /* 270 */ "lp ::= LP", /* 271 */ "with ::=", /* 272 */ "with ::= WITH wqlist", /* 273 */ "with ::= WITH RECURSIVE wqlist", /* 274 */ "wqlist ::= nm eidlist_opt AS LP select RP", /* 275 */ "wqlist ::= wqlist COMMA nm eidlist_opt AS LP select RP", /* 276 */ "input ::= cmdlist", /* 277 */ "cmdlist ::= cmdlist ecmd", /* 278 */ "cmdlist ::= ecmd", /* 279 */ "ecmd ::= SEMI", /* 280 */ "ecmd ::= explain cmdx SEMI", /* 281 */ "explain ::=", /* 282 */ "trans_opt ::=", /* 283 */ "trans_opt ::= TRANSACTION", /* 284 */ "trans_opt ::= TRANSACTION nm", /* 285 */ "savepoint_opt ::= SAVEPOINT", /* 286 */ "savepoint_opt ::=", /* 287 */ "cmd ::= create_table create_table_args", /* 288 */ "columnlist ::= columnlist COMMA columnname carglist", /* 289 */ "columnlist ::= columnname carglist", /* 290 */ "nm ::= ID|INDEXED", /* 291 */ "nm ::= STRING", /* 292 */ "nm ::= JOIN_KW", /* 293 */ "typetoken ::= typename", /* 294 */ "typename ::= ID|STRING", /* 295 */ "signed ::= plus_num", /* 296 */ "signed ::= minus_num", /* 297 */ "carglist ::= carglist ccons", /* 298 */ "carglist ::=", /* 299 */ "ccons ::= NULL onconf", /* 300 */ "conslist_opt ::= COMMA conslist", /* 301 */ "conslist ::= conslist tconscomma tcons", /* 302 */ "conslist ::= tcons", /* 303 */ "tconscomma ::=", /* 304 */ "defer_subclause_opt ::= defer_subclause", /* 305 */ "resolvetype ::= raisetype", /* 306 */ "selectnowith ::= oneselect", /* 307 */ "oneselect ::= values", /* 308 */ "sclp ::= selcollist COMMA", /* 309 */ "as ::= ID|STRING", /* 310 */ "expr ::= term", /* 311 */ "exprlist ::= nexprlist", /* 312 */ "nmnum ::= plus_num", /* 313 */ "nmnum ::= nm", /* 314 */ "nmnum ::= ON", /* 315 */ "nmnum ::= DELETE", /* 316 */ "nmnum ::= DEFAULT", /* 317 */ "plus_num ::= INTEGER|FLOAT", /* 318 */ "foreach_clause ::=", /* 319 */ "foreach_clause ::= FOR EACH ROW", /* 320 */ "trnm ::= nm", /* 321 */ "tridxby ::=", /* 322 */ "database_kw_opt ::= DATABASE", /* 323 */ "database_kw_opt ::=", /* 324 */ "kwcolumn_opt ::=", /* 325 */ "kwcolumn_opt ::= COLUMNKW", /* 326 */ "vtabarglist ::= vtabarg", /* 327 */ "vtabarglist ::= vtabarglist COMMA vtabarg", /* 328 */ "vtabarg ::= vtabarg vtabargtoken", /* 329 */ "anylist ::=", /* 330 */ "anylist ::= anylist LP anylist RP", /* 331 */ "anylist ::= anylist ANY", }; #endif /* NDEBUG */ #if YYSTACKDEPTH<=0 /* ** Try to increase the size of the parser stack. Return the number ** of errors. Return 0 on success. */ static int yyGrowStack(yyParser *p){ int newSize; int idx; yyStackEntry *pNew; newSize = p->yystksz*2 + 100; idx = p->yytos ? (int)(p->yytos - p->yystack) : 0; if( p->yystack==&p->yystk0 ){ pNew = malloc(newSize*sizeof(pNew[0])); if( pNew ) pNew[0] = p->yystk0; }else{ pNew = realloc(p->yystack, newSize*sizeof(pNew[0])); } if( pNew ){ p->yystack = pNew; p->yytos = &p->yystack[idx]; #ifndef NDEBUG if( yyTraceFILE ){ fprintf(yyTraceFILE,"%sStack grows from %d to %d entries.\n", yyTracePrompt, p->yystksz, newSize); } #endif p->yystksz = newSize; } return pNew==0; } #endif /* Datatype of the argument to the memory allocated passed as the ** second argument to sqlite3ParserAlloc() below. This can be changed by ** putting an appropriate #define in the %include section of the input ** grammar. */ #ifndef YYMALLOCARGTYPE # define YYMALLOCARGTYPE size_t #endif /* ** This function allocates a new parser. ** The only argument is a pointer to a function which works like ** malloc. ** ** Inputs: ** A pointer to the function used to allocate memory. ** ** Outputs: ** A pointer to a parser. This pointer is used in subsequent calls ** to sqlite3Parser and sqlite3ParserFree. */ SQLITE_PRIVATE void *sqlite3ParserAlloc(void *(*mallocProc)(YYMALLOCARGTYPE)){ yyParser *pParser; pParser = (yyParser*)(*mallocProc)( (YYMALLOCARGTYPE)sizeof(yyParser) ); if( pParser ){ #ifdef YYTRACKMAXSTACKDEPTH pParser->yyhwm = 0; #endif #if YYSTACKDEPTH<=0 pParser->yytos = NULL; pParser->yystack = NULL; pParser->yystksz = 0; if( yyGrowStack(pParser) ){ pParser->yystack = &pParser->yystk0; pParser->yystksz = 1; } #endif #ifndef YYNOERRORRECOVERY pParser->yyerrcnt = -1; #endif pParser->yytos = pParser->yystack; pParser->yystack[0].stateno = 0; pParser->yystack[0].major = 0; } return pParser; } /* The following function deletes the "minor type" or semantic value ** associated with a symbol. The symbol can be either a terminal ** or nonterminal. "yymajor" is the symbol code, and "yypminor" is ** a pointer to the value to be deleted. The code used to do the ** deletions is derived from the %destructor and/or %token_destructor ** directives of the input grammar. */ static void yy_destructor( yyParser *yypParser, /* The parser */ YYCODETYPE yymajor, /* Type code for object to destroy */ YYMINORTYPE *yypminor /* The object to be destroyed */ ){ sqlite3ParserARG_FETCH; switch( yymajor ){ /* Here is inserted the actions which take place when a ** terminal or non-terminal is destroyed. This can happen ** when the symbol is popped from the stack during a ** reduce or during error processing or when a parser is ** being destroyed before it is finished parsing. ** ** Note: during a reduce, the only symbols destroyed are those ** which appear on the RHS of the rule, but which are *not* used ** inside the C code. */ /********* Begin destructor definitions ***************************************/ case 163: /* select */ case 194: /* selectnowith */ case 195: /* oneselect */ case 206: /* values */ { sqlite3SelectDelete(pParse->db, (yypminor->yy243)); } break; case 172: /* term */ case 173: /* expr */ { sqlite3ExprDelete(pParse->db, (yypminor->yy190).pExpr); } break; case 177: /* eidlist_opt */ case 186: /* sortlist */ case 187: /* eidlist */ case 199: /* selcollist */ case 202: /* groupby_opt */ case 204: /* orderby_opt */ case 207: /* nexprlist */ case 208: /* exprlist */ case 209: /* sclp */ case 218: /* setlist */ case 224: /* paren_exprlist */ case 226: /* case_exprlist */ { sqlite3ExprListDelete(pParse->db, (yypminor->yy148)); } break; case 193: /* fullname */ case 200: /* from */ case 211: /* seltablist */ case 212: /* stl_prefix */ { sqlite3SrcListDelete(pParse->db, (yypminor->yy185)); } break; case 196: /* with */ case 250: /* wqlist */ { sqlite3WithDelete(pParse->db, (yypminor->yy285)); } break; case 201: /* where_opt */ case 203: /* having_opt */ case 215: /* on_opt */ case 225: /* case_operand */ case 227: /* case_else */ case 236: /* when_clause */ case 241: /* key_opt */ { sqlite3ExprDelete(pParse->db, (yypminor->yy72)); } break; case 216: /* using_opt */ case 217: /* idlist */ case 220: /* idlist_opt */ { sqlite3IdListDelete(pParse->db, (yypminor->yy254)); } break; case 232: /* trigger_cmd_list */ case 237: /* trigger_cmd */ { sqlite3DeleteTriggerStep(pParse->db, (yypminor->yy145)); } break; case 234: /* trigger_event */ { sqlite3IdListDelete(pParse->db, (yypminor->yy332).b); } break; /********* End destructor definitions *****************************************/ default: break; /* If no destructor action specified: do nothing */ } } /* ** Pop the parser's stack once. ** ** If there is a destructor routine associated with the token which ** is popped from the stack, then call it. */ static void yy_pop_parser_stack(yyParser *pParser){ yyStackEntry *yytos; assert( pParser->yytos!=0 ); assert( pParser->yytos > pParser->yystack ); yytos = pParser->yytos--; #ifndef NDEBUG if( yyTraceFILE ){ fprintf(yyTraceFILE,"%sPopping %s\n", yyTracePrompt, yyTokenName[yytos->major]); } #endif yy_destructor(pParser, yytos->major, &yytos->minor); } /* ** Deallocate and destroy a parser. Destructors are called for ** all stack elements before shutting the parser down. ** ** If the YYPARSEFREENEVERNULL macro exists (for example because it ** is defined in a %include section of the input grammar) then it is ** assumed that the input pointer is never NULL. */ SQLITE_PRIVATE void sqlite3ParserFree( void *p, /* The parser to be deleted */ void (*freeProc)(void*) /* Function used to reclaim memory */ ){ yyParser *pParser = (yyParser*)p; #ifndef YYPARSEFREENEVERNULL if( pParser==0 ) return; #endif while( pParser->yytos>pParser->yystack ) yy_pop_parser_stack(pParser); #if YYSTACKDEPTH<=0 if( pParser->yystack!=&pParser->yystk0 ) free(pParser->yystack); #endif (*freeProc)((void*)pParser); } /* ** Return the peak depth of the stack for a parser. */ #ifdef YYTRACKMAXSTACKDEPTH SQLITE_PRIVATE int sqlite3ParserStackPeak(void *p){ yyParser *pParser = (yyParser*)p; return pParser->yyhwm; } #endif /* ** Find the appropriate action for a parser given the terminal ** look-ahead token iLookAhead. */ static unsigned int yy_find_shift_action( yyParser *pParser, /* The parser */ YYCODETYPE iLookAhead /* The look-ahead token */ ){ int i; int stateno = pParser->yytos->stateno; if( stateno>=YY_MIN_REDUCE ) return stateno; assert( stateno <= YY_SHIFT_COUNT ); do{ i = yy_shift_ofst[stateno]; assert( iLookAhead!=YYNOCODE ); i += iLookAhead; if( i<0 || i>=YY_ACTTAB_COUNT || yy_lookahead[i]!=iLookAhead ){ #ifdef YYFALLBACK YYCODETYPE iFallback; /* Fallback token */ if( iLookAhead %s\n", yyTracePrompt, yyTokenName[iLookAhead], yyTokenName[iFallback]); } #endif assert( yyFallback[iFallback]==0 ); /* Fallback loop must terminate */ iLookAhead = iFallback; continue; } #endif #ifdef YYWILDCARD { int j = i - iLookAhead + YYWILDCARD; if( #if YY_SHIFT_MIN+YYWILDCARD<0 j>=0 && #endif #if YY_SHIFT_MAX+YYWILDCARD>=YY_ACTTAB_COUNT j0 ){ #ifndef NDEBUG if( yyTraceFILE ){ fprintf(yyTraceFILE, "%sWILDCARD %s => %s\n", yyTracePrompt, yyTokenName[iLookAhead], yyTokenName[YYWILDCARD]); } #endif /* NDEBUG */ return yy_action[j]; } } #endif /* YYWILDCARD */ return yy_default[stateno]; }else{ return yy_action[i]; } }while(1); } /* ** Find the appropriate action for a parser given the non-terminal ** look-ahead token iLookAhead. */ static int yy_find_reduce_action( int stateno, /* Current state number */ YYCODETYPE iLookAhead /* The look-ahead token */ ){ int i; #ifdef YYERRORSYMBOL if( stateno>YY_REDUCE_COUNT ){ return yy_default[stateno]; } #else assert( stateno<=YY_REDUCE_COUNT ); #endif i = yy_reduce_ofst[stateno]; assert( i!=YY_REDUCE_USE_DFLT ); assert( iLookAhead!=YYNOCODE ); i += iLookAhead; #ifdef YYERRORSYMBOL if( i<0 || i>=YY_ACTTAB_COUNT || yy_lookahead[i]!=iLookAhead ){ return yy_default[stateno]; } #else assert( i>=0 && iyytos--; #ifndef NDEBUG if( yyTraceFILE ){ fprintf(yyTraceFILE,"%sStack Overflow!\n",yyTracePrompt); } #endif while( yypParser->yytos>yypParser->yystack ) yy_pop_parser_stack(yypParser); /* Here code is inserted which will execute if the parser ** stack every overflows */ /******** Begin %stack_overflow code ******************************************/ sqlite3ErrorMsg(pParse, "parser stack overflow"); /******** End %stack_overflow code ********************************************/ sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument var */ } /* ** Print tracing information for a SHIFT action */ #ifndef NDEBUG static void yyTraceShift(yyParser *yypParser, int yyNewState){ if( yyTraceFILE ){ if( yyNewStateyytos->major], yyNewState); }else{ fprintf(yyTraceFILE,"%sShift '%s'\n", yyTracePrompt,yyTokenName[yypParser->yytos->major]); } } } #else # define yyTraceShift(X,Y) #endif /* ** Perform a shift action. */ static void yy_shift( yyParser *yypParser, /* The parser to be shifted */ int yyNewState, /* The new state to shift in */ int yyMajor, /* The major token to shift in */ sqlite3ParserTOKENTYPE yyMinor /* The minor token to shift in */ ){ yyStackEntry *yytos; yypParser->yytos++; #ifdef YYTRACKMAXSTACKDEPTH if( (int)(yypParser->yytos - yypParser->yystack)>yypParser->yyhwm ){ yypParser->yyhwm++; assert( yypParser->yyhwm == (int)(yypParser->yytos - yypParser->yystack) ); } #endif #if YYSTACKDEPTH>0 if( yypParser->yytos>=&yypParser->yystack[YYSTACKDEPTH] ){ yyStackOverflow(yypParser); return; } #else if( yypParser->yytos>=&yypParser->yystack[yypParser->yystksz] ){ if( yyGrowStack(yypParser) ){ yyStackOverflow(yypParser); return; } } #endif if( yyNewState > YY_MAX_SHIFT ){ yyNewState += YY_MIN_REDUCE - YY_MIN_SHIFTREDUCE; } yytos = yypParser->yytos; yytos->stateno = (YYACTIONTYPE)yyNewState; yytos->major = (YYCODETYPE)yyMajor; yytos->minor.yy0 = yyMinor; yyTraceShift(yypParser, yyNewState); } /* The following table contains information about every rule that ** is used during the reduce. */ static const struct { YYCODETYPE lhs; /* Symbol on the left-hand side of the rule */ unsigned char nrhs; /* Number of right-hand side symbols in the rule */ } yyRuleInfo[] = { { 147, 1 }, { 147, 3 }, { 148, 1 }, { 149, 3 }, { 150, 0 }, { 150, 1 }, { 150, 1 }, { 150, 1 }, { 149, 2 }, { 149, 2 }, { 149, 2 }, { 149, 2 }, { 149, 3 }, { 149, 5 }, { 154, 6 }, { 156, 1 }, { 158, 0 }, { 158, 3 }, { 157, 1 }, { 157, 0 }, { 155, 5 }, { 155, 2 }, { 162, 0 }, { 162, 2 }, { 164, 2 }, { 166, 0 }, { 166, 4 }, { 166, 6 }, { 167, 2 }, { 171, 2 }, { 171, 2 }, { 171, 4 }, { 171, 3 }, { 171, 3 }, { 171, 2 }, { 171, 3 }, { 171, 5 }, { 171, 2 }, { 171, 4 }, { 171, 4 }, { 171, 1 }, { 171, 2 }, { 176, 0 }, { 176, 1 }, { 178, 0 }, { 178, 2 }, { 180, 2 }, { 180, 3 }, { 180, 3 }, { 180, 3 }, { 181, 2 }, { 181, 2 }, { 181, 1 }, { 181, 1 }, { 181, 2 }, { 179, 3 }, { 179, 2 }, { 182, 0 }, { 182, 2 }, { 182, 2 }, { 161, 0 }, { 184, 1 }, { 185, 2 }, { 185, 7 }, { 185, 5 }, { 185, 5 }, { 185, 10 }, { 188, 0 }, { 174, 0 }, { 174, 3 }, { 189, 0 }, { 189, 2 }, { 190, 1 }, { 190, 1 }, { 149, 4 }, { 192, 2 }, { 192, 0 }, { 149, 9 }, { 149, 4 }, { 149, 1 }, { 163, 2 }, { 194, 3 }, { 197, 1 }, { 197, 2 }, { 197, 1 }, { 195, 9 }, { 206, 4 }, { 206, 5 }, { 198, 1 }, { 198, 1 }, { 198, 0 }, { 209, 0 }, { 199, 3 }, { 199, 2 }, { 199, 4 }, { 210, 2 }, { 210, 0 }, { 200, 0 }, { 200, 2 }, { 212, 2 }, { 212, 0 }, { 211, 7 }, { 211, 9 }, { 211, 7 }, { 211, 7 }, { 159, 0 }, { 159, 2 }, { 193, 2 }, { 213, 1 }, { 213, 2 }, { 213, 3 }, { 213, 4 }, { 215, 2 }, { 215, 0 }, { 214, 0 }, { 214, 3 }, { 214, 2 }, { 216, 4 }, { 216, 0 }, { 204, 0 }, { 204, 3 }, { 186, 4 }, { 186, 2 }, { 175, 1 }, { 175, 1 }, { 175, 0 }, { 202, 0 }, { 202, 3 }, { 203, 0 }, { 203, 2 }, { 205, 0 }, { 205, 2 }, { 205, 4 }, { 205, 4 }, { 149, 6 }, { 201, 0 }, { 201, 2 }, { 149, 8 }, { 218, 5 }, { 218, 7 }, { 218, 3 }, { 218, 5 }, { 149, 6 }, { 149, 7 }, { 219, 2 }, { 219, 1 }, { 220, 0 }, { 220, 3 }, { 217, 3 }, { 217, 1 }, { 173, 3 }, { 172, 1 }, { 173, 1 }, { 173, 1 }, { 173, 3 }, { 173, 5 }, { 172, 1 }, { 172, 1 }, { 172, 1 }, { 173, 1 }, { 173, 3 }, { 173, 6 }, { 173, 5 }, { 173, 4 }, { 172, 1 }, { 173, 5 }, { 173, 3 }, { 173, 3 }, { 173, 3 }, { 173, 3 }, { 173, 3 }, { 173, 3 }, { 173, 3 }, { 173, 3 }, { 221, 1 }, { 221, 2 }, { 173, 3 }, { 173, 5 }, { 173, 2 }, { 173, 3 }, { 173, 3 }, { 173, 4 }, { 173, 2 }, { 173, 2 }, { 173, 2 }, { 173, 2 }, { 222, 1 }, { 222, 2 }, { 173, 5 }, { 223, 1 }, { 223, 2 }, { 173, 5 }, { 173, 3 }, { 173, 5 }, { 173, 5 }, { 173, 4 }, { 173, 5 }, { 226, 5 }, { 226, 4 }, { 227, 2 }, { 227, 0 }, { 225, 1 }, { 225, 0 }, { 208, 0 }, { 207, 3 }, { 207, 1 }, { 224, 0 }, { 224, 3 }, { 149, 12 }, { 228, 1 }, { 228, 0 }, { 177, 0 }, { 177, 3 }, { 187, 5 }, { 187, 3 }, { 229, 0 }, { 229, 2 }, { 149, 4 }, { 149, 1 }, { 149, 2 }, { 149, 3 }, { 149, 5 }, { 149, 6 }, { 149, 5 }, { 149, 6 }, { 169, 2 }, { 170, 2 }, { 149, 5 }, { 231, 11 }, { 233, 1 }, { 233, 1 }, { 233, 2 }, { 233, 0 }, { 234, 1 }, { 234, 1 }, { 234, 3 }, { 236, 0 }, { 236, 2 }, { 232, 3 }, { 232, 2 }, { 238, 3 }, { 239, 3 }, { 239, 2 }, { 237, 7 }, { 237, 5 }, { 237, 5 }, { 237, 1 }, { 173, 4 }, { 173, 6 }, { 191, 1 }, { 191, 1 }, { 191, 1 }, { 149, 4 }, { 149, 6 }, { 149, 3 }, { 241, 0 }, { 241, 2 }, { 149, 1 }, { 149, 3 }, { 149, 1 }, { 149, 3 }, { 149, 6 }, { 149, 7 }, { 242, 1 }, { 149, 1 }, { 149, 4 }, { 244, 8 }, { 246, 0 }, { 247, 1 }, { 247, 3 }, { 248, 1 }, { 196, 0 }, { 196, 2 }, { 196, 3 }, { 250, 6 }, { 250, 8 }, { 144, 1 }, { 145, 2 }, { 145, 1 }, { 146, 1 }, { 146, 3 }, { 147, 0 }, { 151, 0 }, { 151, 1 }, { 151, 2 }, { 153, 1 }, { 153, 0 }, { 149, 2 }, { 160, 4 }, { 160, 2 }, { 152, 1 }, { 152, 1 }, { 152, 1 }, { 166, 1 }, { 167, 1 }, { 168, 1 }, { 168, 1 }, { 165, 2 }, { 165, 0 }, { 171, 2 }, { 161, 2 }, { 183, 3 }, { 183, 1 }, { 184, 0 }, { 188, 1 }, { 190, 1 }, { 194, 1 }, { 195, 1 }, { 209, 2 }, { 210, 1 }, { 173, 1 }, { 208, 1 }, { 230, 1 }, { 230, 1 }, { 230, 1 }, { 230, 1 }, { 230, 1 }, { 169, 1 }, { 235, 0 }, { 235, 3 }, { 238, 1 }, { 239, 0 }, { 240, 1 }, { 240, 0 }, { 243, 0 }, { 243, 1 }, { 245, 1 }, { 245, 3 }, { 246, 2 }, { 249, 0 }, { 249, 4 }, { 249, 2 }, }; static void yy_accept(yyParser*); /* Forward Declaration */ /* ** Perform a reduce action and the shift that must immediately ** follow the reduce. */ static void yy_reduce( yyParser *yypParser, /* The parser */ unsigned int yyruleno /* Number of the rule by which to reduce */ ){ int yygoto; /* The next state */ int yyact; /* The next action */ yyStackEntry *yymsp; /* The top of the parser's stack */ int yysize; /* Amount to pop the stack */ sqlite3ParserARG_FETCH; yymsp = yypParser->yytos; #ifndef NDEBUG if( yyTraceFILE && yyruleno<(int)(sizeof(yyRuleName)/sizeof(yyRuleName[0])) ){ yysize = yyRuleInfo[yyruleno].nrhs; fprintf(yyTraceFILE, "%sReduce [%s], go to state %d.\n", yyTracePrompt, yyRuleName[yyruleno], yymsp[-yysize].stateno); } #endif /* NDEBUG */ /* Check that the stack is large enough to grow by a single entry ** if the RHS of the rule is empty. This ensures that there is room ** enough on the stack to push the LHS value */ if( yyRuleInfo[yyruleno].nrhs==0 ){ #ifdef YYTRACKMAXSTACKDEPTH if( (int)(yypParser->yytos - yypParser->yystack)>yypParser->yyhwm ){ yypParser->yyhwm++; assert( yypParser->yyhwm == (int)(yypParser->yytos - yypParser->yystack)); } #endif #if YYSTACKDEPTH>0 if( yypParser->yytos>=&yypParser->yystack[YYSTACKDEPTH-1] ){ yyStackOverflow(yypParser); return; } #else if( yypParser->yytos>=&yypParser->yystack[yypParser->yystksz-1] ){ if( yyGrowStack(yypParser) ){ yyStackOverflow(yypParser); return; } yymsp = yypParser->yytos; } #endif } switch( yyruleno ){ /* Beginning here are the reduction cases. A typical example ** follows: ** case 0: ** #line ** { ... } // User supplied code ** #line ** break; */ /********** Begin reduce actions **********************************************/ YYMINORTYPE yylhsminor; case 0: /* explain ::= EXPLAIN */ { pParse->explain = 1; } break; case 1: /* explain ::= EXPLAIN QUERY PLAN */ { pParse->explain = 2; } break; case 2: /* cmdx ::= cmd */ { sqlite3FinishCoding(pParse); } break; case 3: /* cmd ::= BEGIN transtype trans_opt */ {sqlite3BeginTransaction(pParse, yymsp[-1].minor.yy194);} break; case 4: /* transtype ::= */ {yymsp[1].minor.yy194 = TK_DEFERRED;} break; case 5: /* transtype ::= DEFERRED */ case 6: /* transtype ::= IMMEDIATE */ yytestcase(yyruleno==6); case 7: /* transtype ::= EXCLUSIVE */ yytestcase(yyruleno==7); {yymsp[0].minor.yy194 = yymsp[0].major; /*A-overwrites-X*/} break; case 8: /* cmd ::= COMMIT trans_opt */ case 9: /* cmd ::= END trans_opt */ yytestcase(yyruleno==9); {sqlite3CommitTransaction(pParse);} break; case 10: /* cmd ::= ROLLBACK trans_opt */ {sqlite3RollbackTransaction(pParse);} break; case 11: /* cmd ::= SAVEPOINT nm */ { sqlite3Savepoint(pParse, SAVEPOINT_BEGIN, &yymsp[0].minor.yy0); } break; case 12: /* cmd ::= RELEASE savepoint_opt nm */ { sqlite3Savepoint(pParse, SAVEPOINT_RELEASE, &yymsp[0].minor.yy0); } break; case 13: /* cmd ::= ROLLBACK trans_opt TO savepoint_opt nm */ { sqlite3Savepoint(pParse, SAVEPOINT_ROLLBACK, &yymsp[0].minor.yy0); } break; case 14: /* create_table ::= createkw temp TABLE ifnotexists nm dbnm */ { sqlite3StartTable(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0,yymsp[-4].minor.yy194,0,0,yymsp[-2].minor.yy194); } break; case 15: /* createkw ::= CREATE */ {disableLookaside(pParse);} break; case 16: /* ifnotexists ::= */ case 19: /* temp ::= */ yytestcase(yyruleno==19); case 22: /* table_options ::= */ yytestcase(yyruleno==22); case 42: /* autoinc ::= */ yytestcase(yyruleno==42); case 57: /* init_deferred_pred_opt ::= */ yytestcase(yyruleno==57); case 67: /* defer_subclause_opt ::= */ yytestcase(yyruleno==67); case 76: /* ifexists ::= */ yytestcase(yyruleno==76); case 90: /* distinct ::= */ yytestcase(yyruleno==90); case 215: /* collate ::= */ yytestcase(yyruleno==215); {yymsp[1].minor.yy194 = 0;} break; case 17: /* ifnotexists ::= IF NOT EXISTS */ {yymsp[-2].minor.yy194 = 1;} break; case 18: /* temp ::= TEMP */ case 43: /* autoinc ::= AUTOINCR */ yytestcase(yyruleno==43); {yymsp[0].minor.yy194 = 1;} break; case 20: /* create_table_args ::= LP columnlist conslist_opt RP table_options */ { sqlite3EndTable(pParse,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0,yymsp[0].minor.yy194,0); } break; case 21: /* create_table_args ::= AS select */ { sqlite3EndTable(pParse,0,0,0,yymsp[0].minor.yy243); sqlite3SelectDelete(pParse->db, yymsp[0].minor.yy243); } break; case 23: /* table_options ::= WITHOUT nm */ { if( yymsp[0].minor.yy0.n==5 && sqlite3_strnicmp(yymsp[0].minor.yy0.z,"rowid",5)==0 ){ yymsp[-1].minor.yy194 = TF_WithoutRowid | TF_NoVisibleRowid; }else{ yymsp[-1].minor.yy194 = 0; sqlite3ErrorMsg(pParse, "unknown table option: %.*s", yymsp[0].minor.yy0.n, yymsp[0].minor.yy0.z); } } break; case 24: /* columnname ::= nm typetoken */ {sqlite3AddColumn(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0);} break; case 25: /* typetoken ::= */ case 60: /* conslist_opt ::= */ yytestcase(yyruleno==60); case 96: /* as ::= */ yytestcase(yyruleno==96); {yymsp[1].minor.yy0.n = 0; yymsp[1].minor.yy0.z = 0;} break; case 26: /* typetoken ::= typename LP signed RP */ { yymsp[-3].minor.yy0.n = (int)(&yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n] - yymsp[-3].minor.yy0.z); } break; case 27: /* typetoken ::= typename LP signed COMMA signed RP */ { yymsp[-5].minor.yy0.n = (int)(&yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n] - yymsp[-5].minor.yy0.z); } break; case 28: /* typename ::= typename ID|STRING */ {yymsp[-1].minor.yy0.n=yymsp[0].minor.yy0.n+(int)(yymsp[0].minor.yy0.z-yymsp[-1].minor.yy0.z);} break; case 29: /* ccons ::= CONSTRAINT nm */ case 62: /* tcons ::= CONSTRAINT nm */ yytestcase(yyruleno==62); {pParse->constraintName = yymsp[0].minor.yy0;} break; case 30: /* ccons ::= DEFAULT term */ case 32: /* ccons ::= DEFAULT PLUS term */ yytestcase(yyruleno==32); {sqlite3AddDefaultValue(pParse,&yymsp[0].minor.yy190);} break; case 31: /* ccons ::= DEFAULT LP expr RP */ {sqlite3AddDefaultValue(pParse,&yymsp[-1].minor.yy190);} break; case 33: /* ccons ::= DEFAULT MINUS term */ { ExprSpan v; v.pExpr = sqlite3PExpr(pParse, TK_UMINUS, yymsp[0].minor.yy190.pExpr, 0, 0); v.zStart = yymsp[-1].minor.yy0.z; v.zEnd = yymsp[0].minor.yy190.zEnd; sqlite3AddDefaultValue(pParse,&v); } break; case 34: /* ccons ::= DEFAULT ID|INDEXED */ { ExprSpan v; spanExpr(&v, pParse, TK_STRING, yymsp[0].minor.yy0); sqlite3AddDefaultValue(pParse,&v); } break; case 35: /* ccons ::= NOT NULL onconf */ {sqlite3AddNotNull(pParse, yymsp[0].minor.yy194);} break; case 36: /* ccons ::= PRIMARY KEY sortorder onconf autoinc */ {sqlite3AddPrimaryKey(pParse,0,yymsp[-1].minor.yy194,yymsp[0].minor.yy194,yymsp[-2].minor.yy194);} break; case 37: /* ccons ::= UNIQUE onconf */ {sqlite3CreateIndex(pParse,0,0,0,0,yymsp[0].minor.yy194,0,0,0,0, SQLITE_IDXTYPE_UNIQUE);} break; case 38: /* ccons ::= CHECK LP expr RP */ {sqlite3AddCheckConstraint(pParse,yymsp[-1].minor.yy190.pExpr);} break; case 39: /* ccons ::= REFERENCES nm eidlist_opt refargs */ {sqlite3CreateForeignKey(pParse,0,&yymsp[-2].minor.yy0,yymsp[-1].minor.yy148,yymsp[0].minor.yy194);} break; case 40: /* ccons ::= defer_subclause */ {sqlite3DeferForeignKey(pParse,yymsp[0].minor.yy194);} break; case 41: /* ccons ::= COLLATE ID|STRING */ {sqlite3AddCollateType(pParse, &yymsp[0].minor.yy0);} break; case 44: /* refargs ::= */ { yymsp[1].minor.yy194 = OE_None*0x0101; /* EV: R-19803-45884 */} break; case 45: /* refargs ::= refargs refarg */ { yymsp[-1].minor.yy194 = (yymsp[-1].minor.yy194 & ~yymsp[0].minor.yy497.mask) | yymsp[0].minor.yy497.value; } break; case 46: /* refarg ::= MATCH nm */ { yymsp[-1].minor.yy497.value = 0; yymsp[-1].minor.yy497.mask = 0x000000; } break; case 47: /* refarg ::= ON INSERT refact */ { yymsp[-2].minor.yy497.value = 0; yymsp[-2].minor.yy497.mask = 0x000000; } break; case 48: /* refarg ::= ON DELETE refact */ { yymsp[-2].minor.yy497.value = yymsp[0].minor.yy194; yymsp[-2].minor.yy497.mask = 0x0000ff; } break; case 49: /* refarg ::= ON UPDATE refact */ { yymsp[-2].minor.yy497.value = yymsp[0].minor.yy194<<8; yymsp[-2].minor.yy497.mask = 0x00ff00; } break; case 50: /* refact ::= SET NULL */ { yymsp[-1].minor.yy194 = OE_SetNull; /* EV: R-33326-45252 */} break; case 51: /* refact ::= SET DEFAULT */ { yymsp[-1].minor.yy194 = OE_SetDflt; /* EV: R-33326-45252 */} break; case 52: /* refact ::= CASCADE */ { yymsp[0].minor.yy194 = OE_Cascade; /* EV: R-33326-45252 */} break; case 53: /* refact ::= RESTRICT */ { yymsp[0].minor.yy194 = OE_Restrict; /* EV: R-33326-45252 */} break; case 54: /* refact ::= NO ACTION */ { yymsp[-1].minor.yy194 = OE_None; /* EV: R-33326-45252 */} break; case 55: /* defer_subclause ::= NOT DEFERRABLE init_deferred_pred_opt */ {yymsp[-2].minor.yy194 = 0;} break; case 56: /* defer_subclause ::= DEFERRABLE init_deferred_pred_opt */ case 71: /* orconf ::= OR resolvetype */ yytestcase(yyruleno==71); case 144: /* insert_cmd ::= INSERT orconf */ yytestcase(yyruleno==144); {yymsp[-1].minor.yy194 = yymsp[0].minor.yy194;} break; case 58: /* init_deferred_pred_opt ::= INITIALLY DEFERRED */ case 75: /* ifexists ::= IF EXISTS */ yytestcase(yyruleno==75); case 187: /* between_op ::= NOT BETWEEN */ yytestcase(yyruleno==187); case 190: /* in_op ::= NOT IN */ yytestcase(yyruleno==190); case 216: /* collate ::= COLLATE ID|STRING */ yytestcase(yyruleno==216); {yymsp[-1].minor.yy194 = 1;} break; case 59: /* init_deferred_pred_opt ::= INITIALLY IMMEDIATE */ {yymsp[-1].minor.yy194 = 0;} break; case 61: /* tconscomma ::= COMMA */ {pParse->constraintName.n = 0;} break; case 63: /* tcons ::= PRIMARY KEY LP sortlist autoinc RP onconf */ {sqlite3AddPrimaryKey(pParse,yymsp[-3].minor.yy148,yymsp[0].minor.yy194,yymsp[-2].minor.yy194,0);} break; case 64: /* tcons ::= UNIQUE LP sortlist RP onconf */ {sqlite3CreateIndex(pParse,0,0,0,yymsp[-2].minor.yy148,yymsp[0].minor.yy194,0,0,0,0, SQLITE_IDXTYPE_UNIQUE);} break; case 65: /* tcons ::= CHECK LP expr RP onconf */ {sqlite3AddCheckConstraint(pParse,yymsp[-2].minor.yy190.pExpr);} break; case 66: /* tcons ::= FOREIGN KEY LP eidlist RP REFERENCES nm eidlist_opt refargs defer_subclause_opt */ { sqlite3CreateForeignKey(pParse, yymsp[-6].minor.yy148, &yymsp[-3].minor.yy0, yymsp[-2].minor.yy148, yymsp[-1].minor.yy194); sqlite3DeferForeignKey(pParse, yymsp[0].minor.yy194); } break; case 68: /* onconf ::= */ case 70: /* orconf ::= */ yytestcase(yyruleno==70); {yymsp[1].minor.yy194 = OE_Default;} break; case 69: /* onconf ::= ON CONFLICT resolvetype */ {yymsp[-2].minor.yy194 = yymsp[0].minor.yy194;} break; case 72: /* resolvetype ::= IGNORE */ {yymsp[0].minor.yy194 = OE_Ignore;} break; case 73: /* resolvetype ::= REPLACE */ case 145: /* insert_cmd ::= REPLACE */ yytestcase(yyruleno==145); {yymsp[0].minor.yy194 = OE_Replace;} break; case 74: /* cmd ::= DROP TABLE ifexists fullname */ { sqlite3DropTable(pParse, yymsp[0].minor.yy185, 0, yymsp[-1].minor.yy194); } break; case 77: /* cmd ::= createkw temp VIEW ifnotexists nm dbnm eidlist_opt AS select */ { sqlite3CreateView(pParse, &yymsp[-8].minor.yy0, &yymsp[-4].minor.yy0, &yymsp[-3].minor.yy0, yymsp[-2].minor.yy148, yymsp[0].minor.yy243, yymsp[-7].minor.yy194, yymsp[-5].minor.yy194); } break; case 78: /* cmd ::= DROP VIEW ifexists fullname */ { sqlite3DropTable(pParse, yymsp[0].minor.yy185, 1, yymsp[-1].minor.yy194); } break; case 79: /* cmd ::= select */ { SelectDest dest = {SRT_Output, 0, 0, 0, 0, 0}; sqlite3Select(pParse, yymsp[0].minor.yy243, &dest); sqlite3SelectDelete(pParse->db, yymsp[0].minor.yy243); } break; case 80: /* select ::= with selectnowith */ { Select *p = yymsp[0].minor.yy243; if( p ){ p->pWith = yymsp[-1].minor.yy285; parserDoubleLinkSelect(pParse, p); }else{ sqlite3WithDelete(pParse->db, yymsp[-1].minor.yy285); } yymsp[-1].minor.yy243 = p; /*A-overwrites-W*/ } break; case 81: /* selectnowith ::= selectnowith multiselect_op oneselect */ { Select *pRhs = yymsp[0].minor.yy243; Select *pLhs = yymsp[-2].minor.yy243; if( pRhs && pRhs->pPrior ){ SrcList *pFrom; Token x; x.n = 0; parserDoubleLinkSelect(pParse, pRhs); pFrom = sqlite3SrcListAppendFromTerm(pParse,0,0,0,&x,pRhs,0,0); pRhs = sqlite3SelectNew(pParse,0,pFrom,0,0,0,0,0,0,0); } if( pRhs ){ pRhs->op = (u8)yymsp[-1].minor.yy194; pRhs->pPrior = pLhs; if( ALWAYS(pLhs) ) pLhs->selFlags &= ~SF_MultiValue; pRhs->selFlags &= ~SF_MultiValue; if( yymsp[-1].minor.yy194!=TK_ALL ) pParse->hasCompound = 1; }else{ sqlite3SelectDelete(pParse->db, pLhs); } yymsp[-2].minor.yy243 = pRhs; } break; case 82: /* multiselect_op ::= UNION */ case 84: /* multiselect_op ::= EXCEPT|INTERSECT */ yytestcase(yyruleno==84); {yymsp[0].minor.yy194 = yymsp[0].major; /*A-overwrites-OP*/} break; case 83: /* multiselect_op ::= UNION ALL */ {yymsp[-1].minor.yy194 = TK_ALL;} break; case 85: /* oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt orderby_opt limit_opt */ { #if SELECTTRACE_ENABLED Token s = yymsp[-8].minor.yy0; /*A-overwrites-S*/ #endif yymsp[-8].minor.yy243 = sqlite3SelectNew(pParse,yymsp[-6].minor.yy148,yymsp[-5].minor.yy185,yymsp[-4].minor.yy72,yymsp[-3].minor.yy148,yymsp[-2].minor.yy72,yymsp[-1].minor.yy148,yymsp[-7].minor.yy194,yymsp[0].minor.yy354.pLimit,yymsp[0].minor.yy354.pOffset); #if SELECTTRACE_ENABLED /* Populate the Select.zSelName[] string that is used to help with ** query planner debugging, to differentiate between multiple Select ** objects in a complex query. ** ** If the SELECT keyword is immediately followed by a C-style comment ** then extract the first few alphanumeric characters from within that ** comment to be the zSelName value. Otherwise, the label is #N where ** is an integer that is incremented with each SELECT statement seen. */ if( yymsp[-8].minor.yy243!=0 ){ const char *z = s.z+6; int i; sqlite3_snprintf(sizeof(yymsp[-8].minor.yy243->zSelName), yymsp[-8].minor.yy243->zSelName, "#%d", ++pParse->nSelect); while( z[0]==' ' ) z++; if( z[0]=='/' && z[1]=='*' ){ z += 2; while( z[0]==' ' ) z++; for(i=0; sqlite3Isalnum(z[i]); i++){} sqlite3_snprintf(sizeof(yymsp[-8].minor.yy243->zSelName), yymsp[-8].minor.yy243->zSelName, "%.*s", i, z); } } #endif /* SELECTRACE_ENABLED */ } break; case 86: /* values ::= VALUES LP nexprlist RP */ { yymsp[-3].minor.yy243 = sqlite3SelectNew(pParse,yymsp[-1].minor.yy148,0,0,0,0,0,SF_Values,0,0); } break; case 87: /* values ::= values COMMA LP exprlist RP */ { Select *pRight, *pLeft = yymsp[-4].minor.yy243; pRight = sqlite3SelectNew(pParse,yymsp[-1].minor.yy148,0,0,0,0,0,SF_Values|SF_MultiValue,0,0); if( ALWAYS(pLeft) ) pLeft->selFlags &= ~SF_MultiValue; if( pRight ){ pRight->op = TK_ALL; pRight->pPrior = pLeft; yymsp[-4].minor.yy243 = pRight; }else{ yymsp[-4].minor.yy243 = pLeft; } } break; case 88: /* distinct ::= DISTINCT */ {yymsp[0].minor.yy194 = SF_Distinct;} break; case 89: /* distinct ::= ALL */ {yymsp[0].minor.yy194 = SF_All;} break; case 91: /* sclp ::= */ case 119: /* orderby_opt ::= */ yytestcase(yyruleno==119); case 126: /* groupby_opt ::= */ yytestcase(yyruleno==126); case 203: /* exprlist ::= */ yytestcase(yyruleno==203); case 206: /* paren_exprlist ::= */ yytestcase(yyruleno==206); case 211: /* eidlist_opt ::= */ yytestcase(yyruleno==211); {yymsp[1].minor.yy148 = 0;} break; case 92: /* selcollist ::= sclp expr as */ { yymsp[-2].minor.yy148 = sqlite3ExprListAppend(pParse, yymsp[-2].minor.yy148, yymsp[-1].minor.yy190.pExpr); if( yymsp[0].minor.yy0.n>0 ) sqlite3ExprListSetName(pParse, yymsp[-2].minor.yy148, &yymsp[0].minor.yy0, 1); sqlite3ExprListSetSpan(pParse,yymsp[-2].minor.yy148,&yymsp[-1].minor.yy190); } break; case 93: /* selcollist ::= sclp STAR */ { Expr *p = sqlite3Expr(pParse->db, TK_ASTERISK, 0); yymsp[-1].minor.yy148 = sqlite3ExprListAppend(pParse, yymsp[-1].minor.yy148, p); } break; case 94: /* selcollist ::= sclp nm DOT STAR */ { Expr *pRight = sqlite3PExpr(pParse, TK_ASTERISK, 0, 0, 0); Expr *pLeft = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-2].minor.yy0); Expr *pDot = sqlite3PExpr(pParse, TK_DOT, pLeft, pRight, 0); yymsp[-3].minor.yy148 = sqlite3ExprListAppend(pParse,yymsp[-3].minor.yy148, pDot); } break; case 95: /* as ::= AS nm */ case 106: /* dbnm ::= DOT nm */ yytestcase(yyruleno==106); case 225: /* plus_num ::= PLUS INTEGER|FLOAT */ yytestcase(yyruleno==225); case 226: /* minus_num ::= MINUS INTEGER|FLOAT */ yytestcase(yyruleno==226); {yymsp[-1].minor.yy0 = yymsp[0].minor.yy0;} break; case 97: /* from ::= */ {yymsp[1].minor.yy185 = sqlite3DbMallocZero(pParse->db, sizeof(*yymsp[1].minor.yy185));} break; case 98: /* from ::= FROM seltablist */ { yymsp[-1].minor.yy185 = yymsp[0].minor.yy185; sqlite3SrcListShiftJoinType(yymsp[-1].minor.yy185); } break; case 99: /* stl_prefix ::= seltablist joinop */ { if( ALWAYS(yymsp[-1].minor.yy185 && yymsp[-1].minor.yy185->nSrc>0) ) yymsp[-1].minor.yy185->a[yymsp[-1].minor.yy185->nSrc-1].fg.jointype = (u8)yymsp[0].minor.yy194; } break; case 100: /* stl_prefix ::= */ {yymsp[1].minor.yy185 = 0;} break; case 101: /* seltablist ::= stl_prefix nm dbnm as indexed_opt on_opt using_opt */ { yymsp[-6].minor.yy185 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy185,&yymsp[-5].minor.yy0,&yymsp[-4].minor.yy0,&yymsp[-3].minor.yy0,0,yymsp[-1].minor.yy72,yymsp[0].minor.yy254); sqlite3SrcListIndexedBy(pParse, yymsp[-6].minor.yy185, &yymsp[-2].minor.yy0); } break; case 102: /* seltablist ::= stl_prefix nm dbnm LP exprlist RP as on_opt using_opt */ { yymsp[-8].minor.yy185 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-8].minor.yy185,&yymsp[-7].minor.yy0,&yymsp[-6].minor.yy0,&yymsp[-2].minor.yy0,0,yymsp[-1].minor.yy72,yymsp[0].minor.yy254); sqlite3SrcListFuncArgs(pParse, yymsp[-8].minor.yy185, yymsp[-4].minor.yy148); } break; case 103: /* seltablist ::= stl_prefix LP select RP as on_opt using_opt */ { yymsp[-6].minor.yy185 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy185,0,0,&yymsp[-2].minor.yy0,yymsp[-4].minor.yy243,yymsp[-1].minor.yy72,yymsp[0].minor.yy254); } break; case 104: /* seltablist ::= stl_prefix LP seltablist RP as on_opt using_opt */ { if( yymsp[-6].minor.yy185==0 && yymsp[-2].minor.yy0.n==0 && yymsp[-1].minor.yy72==0 && yymsp[0].minor.yy254==0 ){ yymsp[-6].minor.yy185 = yymsp[-4].minor.yy185; }else if( yymsp[-4].minor.yy185->nSrc==1 ){ yymsp[-6].minor.yy185 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy185,0,0,&yymsp[-2].minor.yy0,0,yymsp[-1].minor.yy72,yymsp[0].minor.yy254); if( yymsp[-6].minor.yy185 ){ struct SrcList_item *pNew = &yymsp[-6].minor.yy185->a[yymsp[-6].minor.yy185->nSrc-1]; struct SrcList_item *pOld = yymsp[-4].minor.yy185->a; pNew->zName = pOld->zName; pNew->zDatabase = pOld->zDatabase; pNew->pSelect = pOld->pSelect; pOld->zName = pOld->zDatabase = 0; pOld->pSelect = 0; } sqlite3SrcListDelete(pParse->db, yymsp[-4].minor.yy185); }else{ Select *pSubquery; sqlite3SrcListShiftJoinType(yymsp[-4].minor.yy185); pSubquery = sqlite3SelectNew(pParse,0,yymsp[-4].minor.yy185,0,0,0,0,SF_NestedFrom,0,0); yymsp[-6].minor.yy185 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy185,0,0,&yymsp[-2].minor.yy0,pSubquery,yymsp[-1].minor.yy72,yymsp[0].minor.yy254); } } break; case 105: /* dbnm ::= */ case 114: /* indexed_opt ::= */ yytestcase(yyruleno==114); {yymsp[1].minor.yy0.z=0; yymsp[1].minor.yy0.n=0;} break; case 107: /* fullname ::= nm dbnm */ {yymsp[-1].minor.yy185 = sqlite3SrcListAppend(pParse->db,0,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0); /*A-overwrites-X*/} break; case 108: /* joinop ::= COMMA|JOIN */ { yymsp[0].minor.yy194 = JT_INNER; } break; case 109: /* joinop ::= JOIN_KW JOIN */ {yymsp[-1].minor.yy194 = sqlite3JoinType(pParse,&yymsp[-1].minor.yy0,0,0); /*X-overwrites-A*/} break; case 110: /* joinop ::= JOIN_KW nm JOIN */ {yymsp[-2].minor.yy194 = sqlite3JoinType(pParse,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0,0); /*X-overwrites-A*/} break; case 111: /* joinop ::= JOIN_KW nm nm JOIN */ {yymsp[-3].minor.yy194 = sqlite3JoinType(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0);/*X-overwrites-A*/} break; case 112: /* on_opt ::= ON expr */ case 129: /* having_opt ::= HAVING expr */ yytestcase(yyruleno==129); case 136: /* where_opt ::= WHERE expr */ yytestcase(yyruleno==136); case 199: /* case_else ::= ELSE expr */ yytestcase(yyruleno==199); {yymsp[-1].minor.yy72 = yymsp[0].minor.yy190.pExpr;} break; case 113: /* on_opt ::= */ case 128: /* having_opt ::= */ yytestcase(yyruleno==128); case 135: /* where_opt ::= */ yytestcase(yyruleno==135); case 200: /* case_else ::= */ yytestcase(yyruleno==200); case 202: /* case_operand ::= */ yytestcase(yyruleno==202); {yymsp[1].minor.yy72 = 0;} break; case 115: /* indexed_opt ::= INDEXED BY nm */ {yymsp[-2].minor.yy0 = yymsp[0].minor.yy0;} break; case 116: /* indexed_opt ::= NOT INDEXED */ {yymsp[-1].minor.yy0.z=0; yymsp[-1].minor.yy0.n=1;} break; case 117: /* using_opt ::= USING LP idlist RP */ {yymsp[-3].minor.yy254 = yymsp[-1].minor.yy254;} break; case 118: /* using_opt ::= */ case 146: /* idlist_opt ::= */ yytestcase(yyruleno==146); {yymsp[1].minor.yy254 = 0;} break; case 120: /* orderby_opt ::= ORDER BY sortlist */ case 127: /* groupby_opt ::= GROUP BY nexprlist */ yytestcase(yyruleno==127); {yymsp[-2].minor.yy148 = yymsp[0].minor.yy148;} break; case 121: /* sortlist ::= sortlist COMMA expr sortorder */ { yymsp[-3].minor.yy148 = sqlite3ExprListAppend(pParse,yymsp[-3].minor.yy148,yymsp[-1].minor.yy190.pExpr); sqlite3ExprListSetSortOrder(yymsp[-3].minor.yy148,yymsp[0].minor.yy194); } break; case 122: /* sortlist ::= expr sortorder */ { yymsp[-1].minor.yy148 = sqlite3ExprListAppend(pParse,0,yymsp[-1].minor.yy190.pExpr); /*A-overwrites-Y*/ sqlite3ExprListSetSortOrder(yymsp[-1].minor.yy148,yymsp[0].minor.yy194); } break; case 123: /* sortorder ::= ASC */ {yymsp[0].minor.yy194 = SQLITE_SO_ASC;} break; case 124: /* sortorder ::= DESC */ {yymsp[0].minor.yy194 = SQLITE_SO_DESC;} break; case 125: /* sortorder ::= */ {yymsp[1].minor.yy194 = SQLITE_SO_UNDEFINED;} break; case 130: /* limit_opt ::= */ {yymsp[1].minor.yy354.pLimit = 0; yymsp[1].minor.yy354.pOffset = 0;} break; case 131: /* limit_opt ::= LIMIT expr */ {yymsp[-1].minor.yy354.pLimit = yymsp[0].minor.yy190.pExpr; yymsp[-1].minor.yy354.pOffset = 0;} break; case 132: /* limit_opt ::= LIMIT expr OFFSET expr */ {yymsp[-3].minor.yy354.pLimit = yymsp[-2].minor.yy190.pExpr; yymsp[-3].minor.yy354.pOffset = yymsp[0].minor.yy190.pExpr;} break; case 133: /* limit_opt ::= LIMIT expr COMMA expr */ {yymsp[-3].minor.yy354.pOffset = yymsp[-2].minor.yy190.pExpr; yymsp[-3].minor.yy354.pLimit = yymsp[0].minor.yy190.pExpr;} break; case 134: /* cmd ::= with DELETE FROM fullname indexed_opt where_opt */ { sqlite3WithPush(pParse, yymsp[-5].minor.yy285, 1); sqlite3SrcListIndexedBy(pParse, yymsp[-2].minor.yy185, &yymsp[-1].minor.yy0); sqlite3DeleteFrom(pParse,yymsp[-2].minor.yy185,yymsp[0].minor.yy72); } break; case 137: /* cmd ::= with UPDATE orconf fullname indexed_opt SET setlist where_opt */ { sqlite3WithPush(pParse, yymsp[-7].minor.yy285, 1); sqlite3SrcListIndexedBy(pParse, yymsp[-4].minor.yy185, &yymsp[-3].minor.yy0); sqlite3ExprListCheckLength(pParse,yymsp[-1].minor.yy148,"set list"); sqlite3Update(pParse,yymsp[-4].minor.yy185,yymsp[-1].minor.yy148,yymsp[0].minor.yy72,yymsp[-5].minor.yy194); } break; case 138: /* setlist ::= setlist COMMA nm EQ expr */ { yymsp[-4].minor.yy148 = sqlite3ExprListAppend(pParse, yymsp[-4].minor.yy148, yymsp[0].minor.yy190.pExpr); sqlite3ExprListSetName(pParse, yymsp[-4].minor.yy148, &yymsp[-2].minor.yy0, 1); } break; case 139: /* setlist ::= setlist COMMA LP idlist RP EQ expr */ { yymsp[-6].minor.yy148 = sqlite3ExprListAppendVector(pParse, yymsp[-6].minor.yy148, yymsp[-3].minor.yy254, yymsp[0].minor.yy190.pExpr); } break; case 140: /* setlist ::= nm EQ expr */ { yylhsminor.yy148 = sqlite3ExprListAppend(pParse, 0, yymsp[0].minor.yy190.pExpr); sqlite3ExprListSetName(pParse, yylhsminor.yy148, &yymsp[-2].minor.yy0, 1); } yymsp[-2].minor.yy148 = yylhsminor.yy148; break; case 141: /* setlist ::= LP idlist RP EQ expr */ { yymsp[-4].minor.yy148 = sqlite3ExprListAppendVector(pParse, 0, yymsp[-3].minor.yy254, yymsp[0].minor.yy190.pExpr); } break; case 142: /* cmd ::= with insert_cmd INTO fullname idlist_opt select */ { sqlite3WithPush(pParse, yymsp[-5].minor.yy285, 1); sqlite3Insert(pParse, yymsp[-2].minor.yy185, yymsp[0].minor.yy243, yymsp[-1].minor.yy254, yymsp[-4].minor.yy194); } break; case 143: /* cmd ::= with insert_cmd INTO fullname idlist_opt DEFAULT VALUES */ { sqlite3WithPush(pParse, yymsp[-6].minor.yy285, 1); sqlite3Insert(pParse, yymsp[-3].minor.yy185, 0, yymsp[-2].minor.yy254, yymsp[-5].minor.yy194); } break; case 147: /* idlist_opt ::= LP idlist RP */ {yymsp[-2].minor.yy254 = yymsp[-1].minor.yy254;} break; case 148: /* idlist ::= idlist COMMA nm */ {yymsp[-2].minor.yy254 = sqlite3IdListAppend(pParse->db,yymsp[-2].minor.yy254,&yymsp[0].minor.yy0);} break; case 149: /* idlist ::= nm */ {yymsp[0].minor.yy254 = sqlite3IdListAppend(pParse->db,0,&yymsp[0].minor.yy0); /*A-overwrites-Y*/} break; case 150: /* expr ::= LP expr RP */ {spanSet(&yymsp[-2].minor.yy190,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0); /*A-overwrites-B*/ yymsp[-2].minor.yy190.pExpr = yymsp[-1].minor.yy190.pExpr;} break; case 151: /* term ::= NULL */ case 156: /* term ::= FLOAT|BLOB */ yytestcase(yyruleno==156); case 157: /* term ::= STRING */ yytestcase(yyruleno==157); {spanExpr(&yymsp[0].minor.yy190,pParse,yymsp[0].major,yymsp[0].minor.yy0);/*A-overwrites-X*/} break; case 152: /* expr ::= ID|INDEXED */ case 153: /* expr ::= JOIN_KW */ yytestcase(yyruleno==153); {spanExpr(&yymsp[0].minor.yy190,pParse,TK_ID,yymsp[0].minor.yy0); /*A-overwrites-X*/} break; case 154: /* expr ::= nm DOT nm */ { Expr *temp1 = sqlite3ExprAlloc(pParse->db, TK_ID, &yymsp[-2].minor.yy0, 1); Expr *temp2 = sqlite3ExprAlloc(pParse->db, TK_ID, &yymsp[0].minor.yy0, 1); spanSet(&yymsp[-2].minor.yy190,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0); /*A-overwrites-X*/ yymsp[-2].minor.yy190.pExpr = sqlite3PExpr(pParse, TK_DOT, temp1, temp2, 0); } break; case 155: /* expr ::= nm DOT nm DOT nm */ { Expr *temp1 = sqlite3ExprAlloc(pParse->db, TK_ID, &yymsp[-4].minor.yy0, 1); Expr *temp2 = sqlite3ExprAlloc(pParse->db, TK_ID, &yymsp[-2].minor.yy0, 1); Expr *temp3 = sqlite3ExprAlloc(pParse->db, TK_ID, &yymsp[0].minor.yy0, 1); Expr *temp4 = sqlite3PExpr(pParse, TK_DOT, temp2, temp3, 0); spanSet(&yymsp[-4].minor.yy190,&yymsp[-4].minor.yy0,&yymsp[0].minor.yy0); /*A-overwrites-X*/ yymsp[-4].minor.yy190.pExpr = sqlite3PExpr(pParse, TK_DOT, temp1, temp4, 0); } break; case 158: /* term ::= INTEGER */ { yylhsminor.yy190.pExpr = sqlite3ExprAlloc(pParse->db, TK_INTEGER, &yymsp[0].minor.yy0, 1); yylhsminor.yy190.zStart = yymsp[0].minor.yy0.z; yylhsminor.yy190.zEnd = yymsp[0].minor.yy0.z + yymsp[0].minor.yy0.n; if( yylhsminor.yy190.pExpr ) yylhsminor.yy190.pExpr->flags |= EP_Leaf; } yymsp[0].minor.yy190 = yylhsminor.yy190; break; case 159: /* expr ::= VARIABLE */ { if( !(yymsp[0].minor.yy0.z[0]=='#' && sqlite3Isdigit(yymsp[0].minor.yy0.z[1])) ){ u32 n = yymsp[0].minor.yy0.n; spanExpr(&yymsp[0].minor.yy190, pParse, TK_VARIABLE, yymsp[0].minor.yy0); sqlite3ExprAssignVarNumber(pParse, yymsp[0].minor.yy190.pExpr, n); }else{ /* When doing a nested parse, one can include terms in an expression ** that look like this: #1 #2 ... These terms refer to registers ** in the virtual machine. #N is the N-th register. */ Token t = yymsp[0].minor.yy0; /*A-overwrites-X*/ assert( t.n>=2 ); spanSet(&yymsp[0].minor.yy190, &t, &t); if( pParse->nested==0 ){ sqlite3ErrorMsg(pParse, "near \"%T\": syntax error", &t); yymsp[0].minor.yy190.pExpr = 0; }else{ yymsp[0].minor.yy190.pExpr = sqlite3PExpr(pParse, TK_REGISTER, 0, 0, 0); if( yymsp[0].minor.yy190.pExpr ) sqlite3GetInt32(&t.z[1], &yymsp[0].minor.yy190.pExpr->iTable); } } } break; case 160: /* expr ::= expr COLLATE ID|STRING */ { yymsp[-2].minor.yy190.pExpr = sqlite3ExprAddCollateToken(pParse, yymsp[-2].minor.yy190.pExpr, &yymsp[0].minor.yy0, 1); yymsp[-2].minor.yy190.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n]; } break; case 161: /* expr ::= CAST LP expr AS typetoken RP */ { spanSet(&yymsp[-5].minor.yy190,&yymsp[-5].minor.yy0,&yymsp[0].minor.yy0); /*A-overwrites-X*/ yymsp[-5].minor.yy190.pExpr = sqlite3PExpr(pParse, TK_CAST, yymsp[-3].minor.yy190.pExpr, 0, &yymsp[-1].minor.yy0); } break; case 162: /* expr ::= ID|INDEXED LP distinct exprlist RP */ { if( yymsp[-1].minor.yy148 && yymsp[-1].minor.yy148->nExpr>pParse->db->aLimit[SQLITE_LIMIT_FUNCTION_ARG] ){ sqlite3ErrorMsg(pParse, "too many arguments on function %T", &yymsp[-4].minor.yy0); } yylhsminor.yy190.pExpr = sqlite3ExprFunction(pParse, yymsp[-1].minor.yy148, &yymsp[-4].minor.yy0); spanSet(&yylhsminor.yy190,&yymsp[-4].minor.yy0,&yymsp[0].minor.yy0); if( yymsp[-2].minor.yy194==SF_Distinct && yylhsminor.yy190.pExpr ){ yylhsminor.yy190.pExpr->flags |= EP_Distinct; } } yymsp[-4].minor.yy190 = yylhsminor.yy190; break; case 163: /* expr ::= ID|INDEXED LP STAR RP */ { yylhsminor.yy190.pExpr = sqlite3ExprFunction(pParse, 0, &yymsp[-3].minor.yy0); spanSet(&yylhsminor.yy190,&yymsp[-3].minor.yy0,&yymsp[0].minor.yy0); } yymsp[-3].minor.yy190 = yylhsminor.yy190; break; case 164: /* term ::= CTIME_KW */ { yylhsminor.yy190.pExpr = sqlite3ExprFunction(pParse, 0, &yymsp[0].minor.yy0); spanSet(&yylhsminor.yy190, &yymsp[0].minor.yy0, &yymsp[0].minor.yy0); } yymsp[0].minor.yy190 = yylhsminor.yy190; break; case 165: /* expr ::= LP nexprlist COMMA expr RP */ { ExprList *pList = sqlite3ExprListAppend(pParse, yymsp[-3].minor.yy148, yymsp[-1].minor.yy190.pExpr); yylhsminor.yy190.pExpr = sqlite3PExpr(pParse, TK_VECTOR, 0, 0, 0); if( yylhsminor.yy190.pExpr ){ yylhsminor.yy190.pExpr->x.pList = pList; spanSet(&yylhsminor.yy190, &yymsp[-4].minor.yy0, &yymsp[0].minor.yy0); }else{ sqlite3ExprListDelete(pParse->db, pList); } } yymsp[-4].minor.yy190 = yylhsminor.yy190; break; case 166: /* expr ::= expr AND expr */ case 167: /* expr ::= expr OR expr */ yytestcase(yyruleno==167); case 168: /* expr ::= expr LT|GT|GE|LE expr */ yytestcase(yyruleno==168); case 169: /* expr ::= expr EQ|NE expr */ yytestcase(yyruleno==169); case 170: /* expr ::= expr BITAND|BITOR|LSHIFT|RSHIFT expr */ yytestcase(yyruleno==170); case 171: /* expr ::= expr PLUS|MINUS expr */ yytestcase(yyruleno==171); case 172: /* expr ::= expr STAR|SLASH|REM expr */ yytestcase(yyruleno==172); case 173: /* expr ::= expr CONCAT expr */ yytestcase(yyruleno==173); {spanBinaryExpr(pParse,yymsp[-1].major,&yymsp[-2].minor.yy190,&yymsp[0].minor.yy190);} break; case 174: /* likeop ::= LIKE_KW|MATCH */ {yymsp[0].minor.yy0=yymsp[0].minor.yy0;/*A-overwrites-X*/} break; case 175: /* likeop ::= NOT LIKE_KW|MATCH */ {yymsp[-1].minor.yy0=yymsp[0].minor.yy0; yymsp[-1].minor.yy0.n|=0x80000000; /*yymsp[-1].minor.yy0-overwrite-yymsp[0].minor.yy0*/} break; case 176: /* expr ::= expr likeop expr */ { ExprList *pList; int bNot = yymsp[-1].minor.yy0.n & 0x80000000; yymsp[-1].minor.yy0.n &= 0x7fffffff; pList = sqlite3ExprListAppend(pParse,0, yymsp[0].minor.yy190.pExpr); pList = sqlite3ExprListAppend(pParse,pList, yymsp[-2].minor.yy190.pExpr); yymsp[-2].minor.yy190.pExpr = sqlite3ExprFunction(pParse, pList, &yymsp[-1].minor.yy0); exprNot(pParse, bNot, &yymsp[-2].minor.yy190); yymsp[-2].minor.yy190.zEnd = yymsp[0].minor.yy190.zEnd; if( yymsp[-2].minor.yy190.pExpr ) yymsp[-2].minor.yy190.pExpr->flags |= EP_InfixFunc; } break; case 177: /* expr ::= expr likeop expr ESCAPE expr */ { ExprList *pList; int bNot = yymsp[-3].minor.yy0.n & 0x80000000; yymsp[-3].minor.yy0.n &= 0x7fffffff; pList = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy190.pExpr); pList = sqlite3ExprListAppend(pParse,pList, yymsp[-4].minor.yy190.pExpr); pList = sqlite3ExprListAppend(pParse,pList, yymsp[0].minor.yy190.pExpr); yymsp[-4].minor.yy190.pExpr = sqlite3ExprFunction(pParse, pList, &yymsp[-3].minor.yy0); exprNot(pParse, bNot, &yymsp[-4].minor.yy190); yymsp[-4].minor.yy190.zEnd = yymsp[0].minor.yy190.zEnd; if( yymsp[-4].minor.yy190.pExpr ) yymsp[-4].minor.yy190.pExpr->flags |= EP_InfixFunc; } break; case 178: /* expr ::= expr ISNULL|NOTNULL */ {spanUnaryPostfix(pParse,yymsp[0].major,&yymsp[-1].minor.yy190,&yymsp[0].minor.yy0);} break; case 179: /* expr ::= expr NOT NULL */ {spanUnaryPostfix(pParse,TK_NOTNULL,&yymsp[-2].minor.yy190,&yymsp[0].minor.yy0);} break; case 180: /* expr ::= expr IS expr */ { spanBinaryExpr(pParse,TK_IS,&yymsp[-2].minor.yy190,&yymsp[0].minor.yy190); binaryToUnaryIfNull(pParse, yymsp[0].minor.yy190.pExpr, yymsp[-2].minor.yy190.pExpr, TK_ISNULL); } break; case 181: /* expr ::= expr IS NOT expr */ { spanBinaryExpr(pParse,TK_ISNOT,&yymsp[-3].minor.yy190,&yymsp[0].minor.yy190); binaryToUnaryIfNull(pParse, yymsp[0].minor.yy190.pExpr, yymsp[-3].minor.yy190.pExpr, TK_NOTNULL); } break; case 182: /* expr ::= NOT expr */ case 183: /* expr ::= BITNOT expr */ yytestcase(yyruleno==183); {spanUnaryPrefix(&yymsp[-1].minor.yy190,pParse,yymsp[-1].major,&yymsp[0].minor.yy190,&yymsp[-1].minor.yy0);/*A-overwrites-B*/} break; case 184: /* expr ::= MINUS expr */ {spanUnaryPrefix(&yymsp[-1].minor.yy190,pParse,TK_UMINUS,&yymsp[0].minor.yy190,&yymsp[-1].minor.yy0);/*A-overwrites-B*/} break; case 185: /* expr ::= PLUS expr */ {spanUnaryPrefix(&yymsp[-1].minor.yy190,pParse,TK_UPLUS,&yymsp[0].minor.yy190,&yymsp[-1].minor.yy0);/*A-overwrites-B*/} break; case 186: /* between_op ::= BETWEEN */ case 189: /* in_op ::= IN */ yytestcase(yyruleno==189); {yymsp[0].minor.yy194 = 0;} break; case 188: /* expr ::= expr between_op expr AND expr */ { ExprList *pList = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy190.pExpr); pList = sqlite3ExprListAppend(pParse,pList, yymsp[0].minor.yy190.pExpr); yymsp[-4].minor.yy190.pExpr = sqlite3PExpr(pParse, TK_BETWEEN, yymsp[-4].minor.yy190.pExpr, 0, 0); if( yymsp[-4].minor.yy190.pExpr ){ yymsp[-4].minor.yy190.pExpr->x.pList = pList; }else{ sqlite3ExprListDelete(pParse->db, pList); } exprNot(pParse, yymsp[-3].minor.yy194, &yymsp[-4].minor.yy190); yymsp[-4].minor.yy190.zEnd = yymsp[0].minor.yy190.zEnd; } break; case 191: /* expr ::= expr in_op LP exprlist RP */ { if( yymsp[-1].minor.yy148==0 ){ /* Expressions of the form ** ** expr1 IN () ** expr1 NOT IN () ** ** simplify to constants 0 (false) and 1 (true), respectively, ** regardless of the value of expr1. */ sqlite3ExprDelete(pParse->db, yymsp[-4].minor.yy190.pExpr); yymsp[-4].minor.yy190.pExpr = sqlite3PExpr(pParse, TK_INTEGER, 0, 0, &sqlite3IntTokens[yymsp[-3].minor.yy194]); }else if( yymsp[-1].minor.yy148->nExpr==1 ){ /* Expressions of the form: ** ** expr1 IN (?1) ** expr1 NOT IN (?2) ** ** with exactly one value on the RHS can be simplified to something ** like this: ** ** expr1 == ?1 ** expr1 <> ?2 ** ** But, the RHS of the == or <> is marked with the EP_Generic flag ** so that it may not contribute to the computation of comparison ** affinity or the collating sequence to use for comparison. Otherwise, ** the semantics would be subtly different from IN or NOT IN. */ Expr *pRHS = yymsp[-1].minor.yy148->a[0].pExpr; yymsp[-1].minor.yy148->a[0].pExpr = 0; sqlite3ExprListDelete(pParse->db, yymsp[-1].minor.yy148); /* pRHS cannot be NULL because a malloc error would have been detected ** before now and control would have never reached this point */ if( ALWAYS(pRHS) ){ pRHS->flags &= ~EP_Collate; pRHS->flags |= EP_Generic; } yymsp[-4].minor.yy190.pExpr = sqlite3PExpr(pParse, yymsp[-3].minor.yy194 ? TK_NE : TK_EQ, yymsp[-4].minor.yy190.pExpr, pRHS, 0); }else{ yymsp[-4].minor.yy190.pExpr = sqlite3PExpr(pParse, TK_IN, yymsp[-4].minor.yy190.pExpr, 0, 0); if( yymsp[-4].minor.yy190.pExpr ){ yymsp[-4].minor.yy190.pExpr->x.pList = yymsp[-1].minor.yy148; sqlite3ExprSetHeightAndFlags(pParse, yymsp[-4].minor.yy190.pExpr); }else{ sqlite3ExprListDelete(pParse->db, yymsp[-1].minor.yy148); } exprNot(pParse, yymsp[-3].minor.yy194, &yymsp[-4].minor.yy190); } yymsp[-4].minor.yy190.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n]; } break; case 192: /* expr ::= LP select RP */ { spanSet(&yymsp[-2].minor.yy190,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0); /*A-overwrites-B*/ yymsp[-2].minor.yy190.pExpr = sqlite3PExpr(pParse, TK_SELECT, 0, 0, 0); sqlite3PExprAddSelect(pParse, yymsp[-2].minor.yy190.pExpr, yymsp[-1].minor.yy243); } break; case 193: /* expr ::= expr in_op LP select RP */ { yymsp[-4].minor.yy190.pExpr = sqlite3PExpr(pParse, TK_IN, yymsp[-4].minor.yy190.pExpr, 0, 0); sqlite3PExprAddSelect(pParse, yymsp[-4].minor.yy190.pExpr, yymsp[-1].minor.yy243); exprNot(pParse, yymsp[-3].minor.yy194, &yymsp[-4].minor.yy190); yymsp[-4].minor.yy190.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n]; } break; case 194: /* expr ::= expr in_op nm dbnm paren_exprlist */ { SrcList *pSrc = sqlite3SrcListAppend(pParse->db, 0,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0); Select *pSelect = sqlite3SelectNew(pParse, 0,pSrc,0,0,0,0,0,0,0); if( yymsp[0].minor.yy148 ) sqlite3SrcListFuncArgs(pParse, pSelect ? pSrc : 0, yymsp[0].minor.yy148); yymsp[-4].minor.yy190.pExpr = sqlite3PExpr(pParse, TK_IN, yymsp[-4].minor.yy190.pExpr, 0, 0); sqlite3PExprAddSelect(pParse, yymsp[-4].minor.yy190.pExpr, pSelect); exprNot(pParse, yymsp[-3].minor.yy194, &yymsp[-4].minor.yy190); yymsp[-4].minor.yy190.zEnd = yymsp[-1].minor.yy0.z ? &yymsp[-1].minor.yy0.z[yymsp[-1].minor.yy0.n] : &yymsp[-2].minor.yy0.z[yymsp[-2].minor.yy0.n]; } break; case 195: /* expr ::= EXISTS LP select RP */ { Expr *p; spanSet(&yymsp[-3].minor.yy190,&yymsp[-3].minor.yy0,&yymsp[0].minor.yy0); /*A-overwrites-B*/ p = yymsp[-3].minor.yy190.pExpr = sqlite3PExpr(pParse, TK_EXISTS, 0, 0, 0); sqlite3PExprAddSelect(pParse, p, yymsp[-1].minor.yy243); } break; case 196: /* expr ::= CASE case_operand case_exprlist case_else END */ { spanSet(&yymsp[-4].minor.yy190,&yymsp[-4].minor.yy0,&yymsp[0].minor.yy0); /*A-overwrites-C*/ yymsp[-4].minor.yy190.pExpr = sqlite3PExpr(pParse, TK_CASE, yymsp[-3].minor.yy72, 0, 0); if( yymsp[-4].minor.yy190.pExpr ){ yymsp[-4].minor.yy190.pExpr->x.pList = yymsp[-1].minor.yy72 ? sqlite3ExprListAppend(pParse,yymsp[-2].minor.yy148,yymsp[-1].minor.yy72) : yymsp[-2].minor.yy148; sqlite3ExprSetHeightAndFlags(pParse, yymsp[-4].minor.yy190.pExpr); }else{ sqlite3ExprListDelete(pParse->db, yymsp[-2].minor.yy148); sqlite3ExprDelete(pParse->db, yymsp[-1].minor.yy72); } } break; case 197: /* case_exprlist ::= case_exprlist WHEN expr THEN expr */ { yymsp[-4].minor.yy148 = sqlite3ExprListAppend(pParse,yymsp[-4].minor.yy148, yymsp[-2].minor.yy190.pExpr); yymsp[-4].minor.yy148 = sqlite3ExprListAppend(pParse,yymsp[-4].minor.yy148, yymsp[0].minor.yy190.pExpr); } break; case 198: /* case_exprlist ::= WHEN expr THEN expr */ { yymsp[-3].minor.yy148 = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy190.pExpr); yymsp[-3].minor.yy148 = sqlite3ExprListAppend(pParse,yymsp[-3].minor.yy148, yymsp[0].minor.yy190.pExpr); } break; case 201: /* case_operand ::= expr */ {yymsp[0].minor.yy72 = yymsp[0].minor.yy190.pExpr; /*A-overwrites-X*/} break; case 204: /* nexprlist ::= nexprlist COMMA expr */ {yymsp[-2].minor.yy148 = sqlite3ExprListAppend(pParse,yymsp[-2].minor.yy148,yymsp[0].minor.yy190.pExpr);} break; case 205: /* nexprlist ::= expr */ {yymsp[0].minor.yy148 = sqlite3ExprListAppend(pParse,0,yymsp[0].minor.yy190.pExpr); /*A-overwrites-Y*/} break; case 207: /* paren_exprlist ::= LP exprlist RP */ case 212: /* eidlist_opt ::= LP eidlist RP */ yytestcase(yyruleno==212); {yymsp[-2].minor.yy148 = yymsp[-1].minor.yy148;} break; case 208: /* cmd ::= createkw uniqueflag INDEX ifnotexists nm dbnm ON nm LP sortlist RP where_opt */ { sqlite3CreateIndex(pParse, &yymsp[-7].minor.yy0, &yymsp[-6].minor.yy0, sqlite3SrcListAppend(pParse->db,0,&yymsp[-4].minor.yy0,0), yymsp[-2].minor.yy148, yymsp[-10].minor.yy194, &yymsp[-11].minor.yy0, yymsp[0].minor.yy72, SQLITE_SO_ASC, yymsp[-8].minor.yy194, SQLITE_IDXTYPE_APPDEF); } break; case 209: /* uniqueflag ::= UNIQUE */ case 250: /* raisetype ::= ABORT */ yytestcase(yyruleno==250); {yymsp[0].minor.yy194 = OE_Abort;} break; case 210: /* uniqueflag ::= */ {yymsp[1].minor.yy194 = OE_None;} break; case 213: /* eidlist ::= eidlist COMMA nm collate sortorder */ { yymsp[-4].minor.yy148 = parserAddExprIdListTerm(pParse, yymsp[-4].minor.yy148, &yymsp[-2].minor.yy0, yymsp[-1].minor.yy194, yymsp[0].minor.yy194); } break; case 214: /* eidlist ::= nm collate sortorder */ { yymsp[-2].minor.yy148 = parserAddExprIdListTerm(pParse, 0, &yymsp[-2].minor.yy0, yymsp[-1].minor.yy194, yymsp[0].minor.yy194); /*A-overwrites-Y*/ } break; case 217: /* cmd ::= DROP INDEX ifexists fullname */ {sqlite3DropIndex(pParse, yymsp[0].minor.yy185, yymsp[-1].minor.yy194);} break; case 218: /* cmd ::= VACUUM */ {sqlite3Vacuum(pParse,0);} break; case 219: /* cmd ::= VACUUM nm */ {sqlite3Vacuum(pParse,&yymsp[0].minor.yy0);} break; case 220: /* cmd ::= PRAGMA nm dbnm */ {sqlite3Pragma(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0,0,0);} break; case 221: /* cmd ::= PRAGMA nm dbnm EQ nmnum */ {sqlite3Pragma(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0,0);} break; case 222: /* cmd ::= PRAGMA nm dbnm LP nmnum RP */ {sqlite3Pragma(pParse,&yymsp[-4].minor.yy0,&yymsp[-3].minor.yy0,&yymsp[-1].minor.yy0,0);} break; case 223: /* cmd ::= PRAGMA nm dbnm EQ minus_num */ {sqlite3Pragma(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0,1);} break; case 224: /* cmd ::= PRAGMA nm dbnm LP minus_num RP */ {sqlite3Pragma(pParse,&yymsp[-4].minor.yy0,&yymsp[-3].minor.yy0,&yymsp[-1].minor.yy0,1);} break; case 227: /* cmd ::= createkw trigger_decl BEGIN trigger_cmd_list END */ { Token all; all.z = yymsp[-3].minor.yy0.z; all.n = (int)(yymsp[0].minor.yy0.z - yymsp[-3].minor.yy0.z) + yymsp[0].minor.yy0.n; sqlite3FinishTrigger(pParse, yymsp[-1].minor.yy145, &all); } break; case 228: /* trigger_decl ::= temp TRIGGER ifnotexists nm dbnm trigger_time trigger_event ON fullname foreach_clause when_clause */ { sqlite3BeginTrigger(pParse, &yymsp[-7].minor.yy0, &yymsp[-6].minor.yy0, yymsp[-5].minor.yy194, yymsp[-4].minor.yy332.a, yymsp[-4].minor.yy332.b, yymsp[-2].minor.yy185, yymsp[0].minor.yy72, yymsp[-10].minor.yy194, yymsp[-8].minor.yy194); yymsp[-10].minor.yy0 = (yymsp[-6].minor.yy0.n==0?yymsp[-7].minor.yy0:yymsp[-6].minor.yy0); /*A-overwrites-T*/ } break; case 229: /* trigger_time ::= BEFORE */ { yymsp[0].minor.yy194 = TK_BEFORE; } break; case 230: /* trigger_time ::= AFTER */ { yymsp[0].minor.yy194 = TK_AFTER; } break; case 231: /* trigger_time ::= INSTEAD OF */ { yymsp[-1].minor.yy194 = TK_INSTEAD;} break; case 232: /* trigger_time ::= */ { yymsp[1].minor.yy194 = TK_BEFORE; } break; case 233: /* trigger_event ::= DELETE|INSERT */ case 234: /* trigger_event ::= UPDATE */ yytestcase(yyruleno==234); {yymsp[0].minor.yy332.a = yymsp[0].major; /*A-overwrites-X*/ yymsp[0].minor.yy332.b = 0;} break; case 235: /* trigger_event ::= UPDATE OF idlist */ {yymsp[-2].minor.yy332.a = TK_UPDATE; yymsp[-2].minor.yy332.b = yymsp[0].minor.yy254;} break; case 236: /* when_clause ::= */ case 255: /* key_opt ::= */ yytestcase(yyruleno==255); { yymsp[1].minor.yy72 = 0; } break; case 237: /* when_clause ::= WHEN expr */ case 256: /* key_opt ::= KEY expr */ yytestcase(yyruleno==256); { yymsp[-1].minor.yy72 = yymsp[0].minor.yy190.pExpr; } break; case 238: /* trigger_cmd_list ::= trigger_cmd_list trigger_cmd SEMI */ { assert( yymsp[-2].minor.yy145!=0 ); yymsp[-2].minor.yy145->pLast->pNext = yymsp[-1].minor.yy145; yymsp[-2].minor.yy145->pLast = yymsp[-1].minor.yy145; } break; case 239: /* trigger_cmd_list ::= trigger_cmd SEMI */ { assert( yymsp[-1].minor.yy145!=0 ); yymsp[-1].minor.yy145->pLast = yymsp[-1].minor.yy145; } break; case 240: /* trnm ::= nm DOT nm */ { yymsp[-2].minor.yy0 = yymsp[0].minor.yy0; sqlite3ErrorMsg(pParse, "qualified table names are not allowed on INSERT, UPDATE, and DELETE " "statements within triggers"); } break; case 241: /* tridxby ::= INDEXED BY nm */ { sqlite3ErrorMsg(pParse, "the INDEXED BY clause is not allowed on UPDATE or DELETE statements " "within triggers"); } break; case 242: /* tridxby ::= NOT INDEXED */ { sqlite3ErrorMsg(pParse, "the NOT INDEXED clause is not allowed on UPDATE or DELETE statements " "within triggers"); } break; case 243: /* trigger_cmd ::= UPDATE orconf trnm tridxby SET setlist where_opt */ {yymsp[-6].minor.yy145 = sqlite3TriggerUpdateStep(pParse->db, &yymsp[-4].minor.yy0, yymsp[-1].minor.yy148, yymsp[0].minor.yy72, yymsp[-5].minor.yy194);} break; case 244: /* trigger_cmd ::= insert_cmd INTO trnm idlist_opt select */ {yymsp[-4].minor.yy145 = sqlite3TriggerInsertStep(pParse->db, &yymsp[-2].minor.yy0, yymsp[-1].minor.yy254, yymsp[0].minor.yy243, yymsp[-4].minor.yy194);/*A-overwrites-R*/} break; case 245: /* trigger_cmd ::= DELETE FROM trnm tridxby where_opt */ {yymsp[-4].minor.yy145 = sqlite3TriggerDeleteStep(pParse->db, &yymsp[-2].minor.yy0, yymsp[0].minor.yy72);} break; case 246: /* trigger_cmd ::= select */ {yymsp[0].minor.yy145 = sqlite3TriggerSelectStep(pParse->db, yymsp[0].minor.yy243); /*A-overwrites-X*/} break; case 247: /* expr ::= RAISE LP IGNORE RP */ { spanSet(&yymsp[-3].minor.yy190,&yymsp[-3].minor.yy0,&yymsp[0].minor.yy0); /*A-overwrites-X*/ yymsp[-3].minor.yy190.pExpr = sqlite3PExpr(pParse, TK_RAISE, 0, 0, 0); if( yymsp[-3].minor.yy190.pExpr ){ yymsp[-3].minor.yy190.pExpr->affinity = OE_Ignore; } } break; case 248: /* expr ::= RAISE LP raisetype COMMA nm RP */ { spanSet(&yymsp[-5].minor.yy190,&yymsp[-5].minor.yy0,&yymsp[0].minor.yy0); /*A-overwrites-X*/ yymsp[-5].minor.yy190.pExpr = sqlite3PExpr(pParse, TK_RAISE, 0, 0, &yymsp[-1].minor.yy0); if( yymsp[-5].minor.yy190.pExpr ) { yymsp[-5].minor.yy190.pExpr->affinity = (char)yymsp[-3].minor.yy194; } } break; case 249: /* raisetype ::= ROLLBACK */ {yymsp[0].minor.yy194 = OE_Rollback;} break; case 251: /* raisetype ::= FAIL */ {yymsp[0].minor.yy194 = OE_Fail;} break; case 252: /* cmd ::= DROP TRIGGER ifexists fullname */ { sqlite3DropTrigger(pParse,yymsp[0].minor.yy185,yymsp[-1].minor.yy194); } break; case 253: /* cmd ::= ATTACH database_kw_opt expr AS expr key_opt */ { sqlite3Attach(pParse, yymsp[-3].minor.yy190.pExpr, yymsp[-1].minor.yy190.pExpr, yymsp[0].minor.yy72); } break; case 254: /* cmd ::= DETACH database_kw_opt expr */ { sqlite3Detach(pParse, yymsp[0].minor.yy190.pExpr); } break; case 257: /* cmd ::= REINDEX */ {sqlite3Reindex(pParse, 0, 0);} break; case 258: /* cmd ::= REINDEX nm dbnm */ {sqlite3Reindex(pParse, &yymsp[-1].minor.yy0, &yymsp[0].minor.yy0);} break; case 259: /* cmd ::= ANALYZE */ {sqlite3Analyze(pParse, 0, 0);} break; case 260: /* cmd ::= ANALYZE nm dbnm */ {sqlite3Analyze(pParse, &yymsp[-1].minor.yy0, &yymsp[0].minor.yy0);} break; case 261: /* cmd ::= ALTER TABLE fullname RENAME TO nm */ { sqlite3AlterRenameTable(pParse,yymsp[-3].minor.yy185,&yymsp[0].minor.yy0); } break; case 262: /* cmd ::= ALTER TABLE add_column_fullname ADD kwcolumn_opt columnname carglist */ { yymsp[-1].minor.yy0.n = (int)(pParse->sLastToken.z-yymsp[-1].minor.yy0.z) + pParse->sLastToken.n; sqlite3AlterFinishAddColumn(pParse, &yymsp[-1].minor.yy0); } break; case 263: /* add_column_fullname ::= fullname */ { disableLookaside(pParse); sqlite3AlterBeginAddColumn(pParse, yymsp[0].minor.yy185); } break; case 264: /* cmd ::= create_vtab */ {sqlite3VtabFinishParse(pParse,0);} break; case 265: /* cmd ::= create_vtab LP vtabarglist RP */ {sqlite3VtabFinishParse(pParse,&yymsp[0].minor.yy0);} break; case 266: /* create_vtab ::= createkw VIRTUAL TABLE ifnotexists nm dbnm USING nm */ { sqlite3VtabBeginParse(pParse, &yymsp[-3].minor.yy0, &yymsp[-2].minor.yy0, &yymsp[0].minor.yy0, yymsp[-4].minor.yy194); } break; case 267: /* vtabarg ::= */ {sqlite3VtabArgInit(pParse);} break; case 268: /* vtabargtoken ::= ANY */ case 269: /* vtabargtoken ::= lp anylist RP */ yytestcase(yyruleno==269); case 270: /* lp ::= LP */ yytestcase(yyruleno==270); {sqlite3VtabArgExtend(pParse,&yymsp[0].minor.yy0);} break; case 271: /* with ::= */ {yymsp[1].minor.yy285 = 0;} break; case 272: /* with ::= WITH wqlist */ { yymsp[-1].minor.yy285 = yymsp[0].minor.yy285; } break; case 273: /* with ::= WITH RECURSIVE wqlist */ { yymsp[-2].minor.yy285 = yymsp[0].minor.yy285; } break; case 274: /* wqlist ::= nm eidlist_opt AS LP select RP */ { yymsp[-5].minor.yy285 = sqlite3WithAdd(pParse, 0, &yymsp[-5].minor.yy0, yymsp[-4].minor.yy148, yymsp[-1].minor.yy243); /*A-overwrites-X*/ } break; case 275: /* wqlist ::= wqlist COMMA nm eidlist_opt AS LP select RP */ { yymsp[-7].minor.yy285 = sqlite3WithAdd(pParse, yymsp[-7].minor.yy285, &yymsp[-5].minor.yy0, yymsp[-4].minor.yy148, yymsp[-1].minor.yy243); } break; default: /* (276) input ::= cmdlist */ yytestcase(yyruleno==276); /* (277) cmdlist ::= cmdlist ecmd */ yytestcase(yyruleno==277); /* (278) cmdlist ::= ecmd (OPTIMIZED OUT) */ assert(yyruleno!=278); /* (279) ecmd ::= SEMI */ yytestcase(yyruleno==279); /* (280) ecmd ::= explain cmdx SEMI */ yytestcase(yyruleno==280); /* (281) explain ::= */ yytestcase(yyruleno==281); /* (282) trans_opt ::= */ yytestcase(yyruleno==282); /* (283) trans_opt ::= TRANSACTION */ yytestcase(yyruleno==283); /* (284) trans_opt ::= TRANSACTION nm */ yytestcase(yyruleno==284); /* (285) savepoint_opt ::= SAVEPOINT */ yytestcase(yyruleno==285); /* (286) savepoint_opt ::= */ yytestcase(yyruleno==286); /* (287) cmd ::= create_table create_table_args */ yytestcase(yyruleno==287); /* (288) columnlist ::= columnlist COMMA columnname carglist */ yytestcase(yyruleno==288); /* (289) columnlist ::= columnname carglist */ yytestcase(yyruleno==289); /* (290) nm ::= ID|INDEXED */ yytestcase(yyruleno==290); /* (291) nm ::= STRING */ yytestcase(yyruleno==291); /* (292) nm ::= JOIN_KW */ yytestcase(yyruleno==292); /* (293) typetoken ::= typename */ yytestcase(yyruleno==293); /* (294) typename ::= ID|STRING */ yytestcase(yyruleno==294); /* (295) signed ::= plus_num (OPTIMIZED OUT) */ assert(yyruleno!=295); /* (296) signed ::= minus_num (OPTIMIZED OUT) */ assert(yyruleno!=296); /* (297) carglist ::= carglist ccons */ yytestcase(yyruleno==297); /* (298) carglist ::= */ yytestcase(yyruleno==298); /* (299) ccons ::= NULL onconf */ yytestcase(yyruleno==299); /* (300) conslist_opt ::= COMMA conslist */ yytestcase(yyruleno==300); /* (301) conslist ::= conslist tconscomma tcons */ yytestcase(yyruleno==301); /* (302) conslist ::= tcons (OPTIMIZED OUT) */ assert(yyruleno!=302); /* (303) tconscomma ::= */ yytestcase(yyruleno==303); /* (304) defer_subclause_opt ::= defer_subclause (OPTIMIZED OUT) */ assert(yyruleno!=304); /* (305) resolvetype ::= raisetype (OPTIMIZED OUT) */ assert(yyruleno!=305); /* (306) selectnowith ::= oneselect (OPTIMIZED OUT) */ assert(yyruleno!=306); /* (307) oneselect ::= values */ yytestcase(yyruleno==307); /* (308) sclp ::= selcollist COMMA */ yytestcase(yyruleno==308); /* (309) as ::= ID|STRING */ yytestcase(yyruleno==309); /* (310) expr ::= term (OPTIMIZED OUT) */ assert(yyruleno!=310); /* (311) exprlist ::= nexprlist */ yytestcase(yyruleno==311); /* (312) nmnum ::= plus_num (OPTIMIZED OUT) */ assert(yyruleno!=312); /* (313) nmnum ::= nm (OPTIMIZED OUT) */ assert(yyruleno!=313); /* (314) nmnum ::= ON */ yytestcase(yyruleno==314); /* (315) nmnum ::= DELETE */ yytestcase(yyruleno==315); /* (316) nmnum ::= DEFAULT */ yytestcase(yyruleno==316); /* (317) plus_num ::= INTEGER|FLOAT */ yytestcase(yyruleno==317); /* (318) foreach_clause ::= */ yytestcase(yyruleno==318); /* (319) foreach_clause ::= FOR EACH ROW */ yytestcase(yyruleno==319); /* (320) trnm ::= nm */ yytestcase(yyruleno==320); /* (321) tridxby ::= */ yytestcase(yyruleno==321); /* (322) database_kw_opt ::= DATABASE */ yytestcase(yyruleno==322); /* (323) database_kw_opt ::= */ yytestcase(yyruleno==323); /* (324) kwcolumn_opt ::= */ yytestcase(yyruleno==324); /* (325) kwcolumn_opt ::= COLUMNKW */ yytestcase(yyruleno==325); /* (326) vtabarglist ::= vtabarg */ yytestcase(yyruleno==326); /* (327) vtabarglist ::= vtabarglist COMMA vtabarg */ yytestcase(yyruleno==327); /* (328) vtabarg ::= vtabarg vtabargtoken */ yytestcase(yyruleno==328); /* (329) anylist ::= */ yytestcase(yyruleno==329); /* (330) anylist ::= anylist LP anylist RP */ yytestcase(yyruleno==330); /* (331) anylist ::= anylist ANY */ yytestcase(yyruleno==331); break; /********** End reduce actions ************************************************/ }; assert( yyrulenoYY_MAX_SHIFT ){ yyact += YY_MIN_REDUCE - YY_MIN_SHIFTREDUCE; } yymsp -= yysize-1; yypParser->yytos = yymsp; yymsp->stateno = (YYACTIONTYPE)yyact; yymsp->major = (YYCODETYPE)yygoto; yyTraceShift(yypParser, yyact); }else{ assert( yyact == YY_ACCEPT_ACTION ); yypParser->yytos -= yysize; yy_accept(yypParser); } } /* ** The following code executes when the parse fails */ #ifndef YYNOERRORRECOVERY static void yy_parse_failed( yyParser *yypParser /* The parser */ ){ sqlite3ParserARG_FETCH; #ifndef NDEBUG if( yyTraceFILE ){ fprintf(yyTraceFILE,"%sFail!\n",yyTracePrompt); } #endif while( yypParser->yytos>yypParser->yystack ) yy_pop_parser_stack(yypParser); /* Here code is inserted which will be executed whenever the ** parser fails */ /************ Begin %parse_failure code ***************************************/ /************ End %parse_failure code *****************************************/ sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */ } #endif /* YYNOERRORRECOVERY */ /* ** The following code executes when a syntax error first occurs. */ static void yy_syntax_error( yyParser *yypParser, /* The parser */ int yymajor, /* The major type of the error token */ sqlite3ParserTOKENTYPE yyminor /* The minor type of the error token */ ){ sqlite3ParserARG_FETCH; #define TOKEN yyminor /************ Begin %syntax_error code ****************************************/ UNUSED_PARAMETER(yymajor); /* Silence some compiler warnings */ assert( TOKEN.z[0] ); /* The tokenizer always gives us a token */ sqlite3ErrorMsg(pParse, "near \"%T\": syntax error", &TOKEN); /************ End %syntax_error code ******************************************/ sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */ } /* ** The following is executed when the parser accepts */ static void yy_accept( yyParser *yypParser /* The parser */ ){ sqlite3ParserARG_FETCH; #ifndef NDEBUG if( yyTraceFILE ){ fprintf(yyTraceFILE,"%sAccept!\n",yyTracePrompt); } #endif #ifndef YYNOERRORRECOVERY yypParser->yyerrcnt = -1; #endif assert( yypParser->yytos==yypParser->yystack ); /* Here code is inserted which will be executed whenever the ** parser accepts */ /*********** Begin %parse_accept code *****************************************/ /*********** End %parse_accept code *******************************************/ sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */ } /* The main parser program. ** The first argument is a pointer to a structure obtained from ** "sqlite3ParserAlloc" which describes the current state of the parser. ** The second argument is the major token number. The third is ** the minor token. The fourth optional argument is whatever the ** user wants (and specified in the grammar) and is available for ** use by the action routines. ** ** Inputs: **
      **
    • A pointer to the parser (an opaque structure.) **
    • The major token number. **
    • The minor token number. **
    • An option argument of a grammar-specified type. **
    ** ** Outputs: ** None. */ SQLITE_PRIVATE void sqlite3Parser( void *yyp, /* The parser */ int yymajor, /* The major token code number */ sqlite3ParserTOKENTYPE yyminor /* The value for the token */ sqlite3ParserARG_PDECL /* Optional %extra_argument parameter */ ){ YYMINORTYPE yyminorunion; unsigned int yyact; /* The parser action. */ #if !defined(YYERRORSYMBOL) && !defined(YYNOERRORRECOVERY) int yyendofinput; /* True if we are at the end of input */ #endif #ifdef YYERRORSYMBOL int yyerrorhit = 0; /* True if yymajor has invoked an error */ #endif yyParser *yypParser; /* The parser */ yypParser = (yyParser*)yyp; assert( yypParser->yytos!=0 ); #if !defined(YYERRORSYMBOL) && !defined(YYNOERRORRECOVERY) yyendofinput = (yymajor==0); #endif sqlite3ParserARG_STORE; #ifndef NDEBUG if( yyTraceFILE ){ fprintf(yyTraceFILE,"%sInput '%s'\n",yyTracePrompt,yyTokenName[yymajor]); } #endif do{ yyact = yy_find_shift_action(yypParser,(YYCODETYPE)yymajor); if( yyact <= YY_MAX_SHIFTREDUCE ){ yy_shift(yypParser,yyact,yymajor,yyminor); #ifndef YYNOERRORRECOVERY yypParser->yyerrcnt--; #endif yymajor = YYNOCODE; }else if( yyact <= YY_MAX_REDUCE ){ yy_reduce(yypParser,yyact-YY_MIN_REDUCE); }else{ assert( yyact == YY_ERROR_ACTION ); yyminorunion.yy0 = yyminor; #ifdef YYERRORSYMBOL int yymx; #endif #ifndef NDEBUG if( yyTraceFILE ){ fprintf(yyTraceFILE,"%sSyntax Error!\n",yyTracePrompt); } #endif #ifdef YYERRORSYMBOL /* A syntax error has occurred. ** The response to an error depends upon whether or not the ** grammar defines an error token "ERROR". ** ** This is what we do if the grammar does define ERROR: ** ** * Call the %syntax_error function. ** ** * Begin popping the stack until we enter a state where ** it is legal to shift the error symbol, then shift ** the error symbol. ** ** * Set the error count to three. ** ** * Begin accepting and shifting new tokens. No new error ** processing will occur until three tokens have been ** shifted successfully. ** */ if( yypParser->yyerrcnt<0 ){ yy_syntax_error(yypParser,yymajor,yyminor); } yymx = yypParser->yytos->major; if( yymx==YYERRORSYMBOL || yyerrorhit ){ #ifndef NDEBUG if( yyTraceFILE ){ fprintf(yyTraceFILE,"%sDiscard input token %s\n", yyTracePrompt,yyTokenName[yymajor]); } #endif yy_destructor(yypParser, (YYCODETYPE)yymajor, &yyminorunion); yymajor = YYNOCODE; }else{ while( yypParser->yytos >= yypParser->yystack && yymx != YYERRORSYMBOL && (yyact = yy_find_reduce_action( yypParser->yytos->stateno, YYERRORSYMBOL)) >= YY_MIN_REDUCE ){ yy_pop_parser_stack(yypParser); } if( yypParser->yytos < yypParser->yystack || yymajor==0 ){ yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion); yy_parse_failed(yypParser); #ifndef YYNOERRORRECOVERY yypParser->yyerrcnt = -1; #endif yymajor = YYNOCODE; }else if( yymx!=YYERRORSYMBOL ){ yy_shift(yypParser,yyact,YYERRORSYMBOL,yyminor); } } yypParser->yyerrcnt = 3; yyerrorhit = 1; #elif defined(YYNOERRORRECOVERY) /* If the YYNOERRORRECOVERY macro is defined, then do not attempt to ** do any kind of error recovery. Instead, simply invoke the syntax ** error routine and continue going as if nothing had happened. ** ** Applications can set this macro (for example inside %include) if ** they intend to abandon the parse upon the first syntax error seen. */ yy_syntax_error(yypParser,yymajor, yyminor); yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion); yymajor = YYNOCODE; #else /* YYERRORSYMBOL is not defined */ /* This is what we do if the grammar does not define ERROR: ** ** * Report an error message, and throw away the input token. ** ** * If the input token is $, then fail the parse. ** ** As before, subsequent error messages are suppressed until ** three input tokens have been successfully shifted. */ if( yypParser->yyerrcnt<=0 ){ yy_syntax_error(yypParser,yymajor, yyminor); } yypParser->yyerrcnt = 3; yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion); if( yyendofinput ){ yy_parse_failed(yypParser); #ifndef YYNOERRORRECOVERY yypParser->yyerrcnt = -1; #endif } yymajor = YYNOCODE; #endif } }while( yymajor!=YYNOCODE && yypParser->yytos>yypParser->yystack ); #ifndef NDEBUG if( yyTraceFILE ){ yyStackEntry *i; char cDiv = '['; fprintf(yyTraceFILE,"%sReturn. Stack=",yyTracePrompt); for(i=&yypParser->yystack[1]; i<=yypParser->yytos; i++){ fprintf(yyTraceFILE,"%c%s", cDiv, yyTokenName[i->major]); cDiv = ' '; } fprintf(yyTraceFILE,"]\n"); } #endif return; } /************** End of parse.c ***********************************************/ /************** Begin file tokenize.c ****************************************/ /* ** 2001 September 15 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ************************************************************************* ** An tokenizer for SQL ** ** This file contains C code that splits an SQL input string up into ** individual tokens and sends those tokens one-by-one over to the ** parser for analysis. */ /* #include "sqliteInt.h" */ /* #include */ /* Character classes for tokenizing ** ** In the sqlite3GetToken() function, a switch() on aiClass[c] is implemented ** using a lookup table, whereas a switch() directly on c uses a binary search. ** The lookup table is much faster. To maximize speed, and to ensure that ** a lookup table is used, all of the classes need to be small integers and ** all of them need to be used within the switch. */ #define CC_X 0 /* The letter 'x', or start of BLOB literal */ #define CC_KYWD 1 /* Alphabetics or '_'. Usable in a keyword */ #define CC_ID 2 /* unicode characters usable in IDs */ #define CC_DIGIT 3 /* Digits */ #define CC_DOLLAR 4 /* '$' */ #define CC_VARALPHA 5 /* '@', '#', ':'. Alphabetic SQL variables */ #define CC_VARNUM 6 /* '?'. Numeric SQL variables */ #define CC_SPACE 7 /* Space characters */ #define CC_QUOTE 8 /* '"', '\'', or '`'. String literals, quoted ids */ #define CC_QUOTE2 9 /* '['. [...] style quoted ids */ #define CC_PIPE 10 /* '|'. Bitwise OR or concatenate */ #define CC_MINUS 11 /* '-'. Minus or SQL-style comment */ #define CC_LT 12 /* '<'. Part of < or <= or <> */ #define CC_GT 13 /* '>'. Part of > or >= */ #define CC_EQ 14 /* '='. Part of = or == */ #define CC_BANG 15 /* '!'. Part of != */ #define CC_SLASH 16 /* '/'. / or c-style comment */ #define CC_LP 17 /* '(' */ #define CC_RP 18 /* ')' */ #define CC_SEMI 19 /* ';' */ #define CC_PLUS 20 /* '+' */ #define CC_STAR 21 /* '*' */ #define CC_PERCENT 22 /* '%' */ #define CC_COMMA 23 /* ',' */ #define CC_AND 24 /* '&' */ #define CC_TILDA 25 /* '~' */ #define CC_DOT 26 /* '.' */ #define CC_ILLEGAL 27 /* Illegal character */ static const unsigned char aiClass[] = { #ifdef SQLITE_ASCII /* x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xa xb xc xd xe xf */ /* 0x */ 27, 27, 27, 27, 27, 27, 27, 27, 27, 7, 7, 27, 7, 7, 27, 27, /* 1x */ 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, /* 2x */ 7, 15, 8, 5, 4, 22, 24, 8, 17, 18, 21, 20, 23, 11, 26, 16, /* 3x */ 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 5, 19, 12, 14, 13, 6, /* 4x */ 5, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 5x */ 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 9, 27, 27, 27, 1, /* 6x */ 8, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 7x */ 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 27, 10, 27, 25, 27, /* 8x */ 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, /* 9x */ 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, /* Ax */ 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, /* Bx */ 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, /* Cx */ 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, /* Dx */ 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, /* Ex */ 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, /* Fx */ 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2 #endif #ifdef SQLITE_EBCDIC /* x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xa xb xc xd xe xf */ /* 0x */ 27, 27, 27, 27, 27, 7, 27, 27, 27, 27, 27, 27, 7, 7, 27, 27, /* 1x */ 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, /* 2x */ 27, 27, 27, 27, 27, 7, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, /* 3x */ 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, /* 4x */ 7, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 12, 17, 20, 10, /* 5x */ 24, 27, 27, 27, 27, 27, 27, 27, 27, 27, 15, 4, 21, 18, 19, 27, /* 6x */ 11, 16, 27, 27, 27, 27, 27, 27, 27, 27, 27, 23, 22, 1, 13, 7, /* 7x */ 27, 27, 27, 27, 27, 27, 27, 27, 27, 8, 5, 5, 5, 8, 14, 8, /* 8x */ 27, 1, 1, 1, 1, 1, 1, 1, 1, 1, 27, 27, 27, 27, 27, 27, /* 9x */ 27, 1, 1, 1, 1, 1, 1, 1, 1, 1, 27, 27, 27, 27, 27, 27, /* 9x */ 25, 1, 1, 1, 1, 1, 1, 0, 1, 1, 27, 27, 27, 27, 27, 27, /* Bx */ 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 9, 27, 27, 27, 27, 27, /* Cx */ 27, 1, 1, 1, 1, 1, 1, 1, 1, 1, 27, 27, 27, 27, 27, 27, /* Dx */ 27, 1, 1, 1, 1, 1, 1, 1, 1, 1, 27, 27, 27, 27, 27, 27, /* Ex */ 27, 27, 1, 1, 1, 1, 1, 0, 1, 1, 27, 27, 27, 27, 27, 27, /* Fx */ 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 27, 27, 27, 27, 27, 27, #endif }; /* ** The charMap() macro maps alphabetic characters (only) into their ** lower-case ASCII equivalent. On ASCII machines, this is just ** an upper-to-lower case map. On EBCDIC machines we also need ** to adjust the encoding. The mapping is only valid for alphabetics ** which are the only characters for which this feature is used. ** ** Used by keywordhash.h */ #ifdef SQLITE_ASCII # define charMap(X) sqlite3UpperToLower[(unsigned char)X] #endif #ifdef SQLITE_EBCDIC # define charMap(X) ebcdicToAscii[(unsigned char)X] const unsigned char ebcdicToAscii[] = { /* 0 1 2 3 4 5 6 7 8 9 A B C D E F */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0x */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 1x */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 2x */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 3x */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 4x */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 5x */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 95, 0, 0, /* 6x */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 7x */ 0, 97, 98, 99,100,101,102,103,104,105, 0, 0, 0, 0, 0, 0, /* 8x */ 0,106,107,108,109,110,111,112,113,114, 0, 0, 0, 0, 0, 0, /* 9x */ 0, 0,115,116,117,118,119,120,121,122, 0, 0, 0, 0, 0, 0, /* Ax */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Bx */ 0, 97, 98, 99,100,101,102,103,104,105, 0, 0, 0, 0, 0, 0, /* Cx */ 0,106,107,108,109,110,111,112,113,114, 0, 0, 0, 0, 0, 0, /* Dx */ 0, 0,115,116,117,118,119,120,121,122, 0, 0, 0, 0, 0, 0, /* Ex */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Fx */ }; #endif /* ** The sqlite3KeywordCode function looks up an identifier to determine if ** it is a keyword. If it is a keyword, the token code of that keyword is ** returned. If the input is not a keyword, TK_ID is returned. ** ** The implementation of this routine was generated by a program, ** mkkeywordhash.c, located in the tool subdirectory of the distribution. ** The output of the mkkeywordhash.c program is written into a file ** named keywordhash.h and then included into this source file by ** the #include below. */ /************** Include keywordhash.h in the middle of tokenize.c ************/ /************** Begin file keywordhash.h *************************************/ /***** This file contains automatically generated code ****** ** ** The code in this file has been automatically generated by ** ** sqlite/tool/mkkeywordhash.c ** ** The code in this file implements a function that determines whether ** or not a given identifier is really an SQL keyword. The same thing ** might be implemented more directly using a hand-written hash table. ** But by using this automatically generated code, the size of the code ** is substantially reduced. This is important for embedded applications ** on platforms with limited memory. */ /* Hash score: 182 */ static int keywordCode(const char *z, int n, int *pType){ /* zText[] encodes 834 bytes of keywords in 554 bytes */ /* REINDEXEDESCAPEACHECKEYBEFOREIGNOREGEXPLAINSTEADDATABASELECT */ /* ABLEFTHENDEFERRABLELSEXCEPTRANSACTIONATURALTERAISEXCLUSIVE */ /* XISTSAVEPOINTERSECTRIGGEREFERENCESCONSTRAINTOFFSETEMPORARY */ /* UNIQUERYWITHOUTERELEASEATTACHAVINGROUPDATEBEGINNERECURSIVE */ /* BETWEENOTNULLIKECASCADELETECASECOLLATECREATECURRENT_DATEDETACH */ /* IMMEDIATEJOINSERTMATCHPLANALYZEPRAGMABORTVALUESVIRTUALIMITWHEN */ /* WHERENAMEAFTEREPLACEANDEFAULTAUTOINCREMENTCASTCOLUMNCOMMIT */ /* CONFLICTCROSSCURRENT_TIMESTAMPRIMARYDEFERREDISTINCTDROPFAIL */ /* FROMFULLGLOBYIFISNULLORDERESTRICTRIGHTROLLBACKROWUNIONUSING */ /* VACUUMVIEWINITIALLY */ static const char zText[553] = { 'R','E','I','N','D','E','X','E','D','E','S','C','A','P','E','A','C','H', 'E','C','K','E','Y','B','E','F','O','R','E','I','G','N','O','R','E','G', 'E','X','P','L','A','I','N','S','T','E','A','D','D','A','T','A','B','A', 'S','E','L','E','C','T','A','B','L','E','F','T','H','E','N','D','E','F', 'E','R','R','A','B','L','E','L','S','E','X','C','E','P','T','R','A','N', 'S','A','C','T','I','O','N','A','T','U','R','A','L','T','E','R','A','I', 'S','E','X','C','L','U','S','I','V','E','X','I','S','T','S','A','V','E', 'P','O','I','N','T','E','R','S','E','C','T','R','I','G','G','E','R','E', 'F','E','R','E','N','C','E','S','C','O','N','S','T','R','A','I','N','T', 'O','F','F','S','E','T','E','M','P','O','R','A','R','Y','U','N','I','Q', 'U','E','R','Y','W','I','T','H','O','U','T','E','R','E','L','E','A','S', 'E','A','T','T','A','C','H','A','V','I','N','G','R','O','U','P','D','A', 'T','E','B','E','G','I','N','N','E','R','E','C','U','R','S','I','V','E', 'B','E','T','W','E','E','N','O','T','N','U','L','L','I','K','E','C','A', 'S','C','A','D','E','L','E','T','E','C','A','S','E','C','O','L','L','A', 'T','E','C','R','E','A','T','E','C','U','R','R','E','N','T','_','D','A', 'T','E','D','E','T','A','C','H','I','M','M','E','D','I','A','T','E','J', 'O','I','N','S','E','R','T','M','A','T','C','H','P','L','A','N','A','L', 'Y','Z','E','P','R','A','G','M','A','B','O','R','T','V','A','L','U','E', 'S','V','I','R','T','U','A','L','I','M','I','T','W','H','E','N','W','H', 'E','R','E','N','A','M','E','A','F','T','E','R','E','P','L','A','C','E', 'A','N','D','E','F','A','U','L','T','A','U','T','O','I','N','C','R','E', 'M','E','N','T','C','A','S','T','C','O','L','U','M','N','C','O','M','M', 'I','T','C','O','N','F','L','I','C','T','C','R','O','S','S','C','U','R', 'R','E','N','T','_','T','I','M','E','S','T','A','M','P','R','I','M','A', 'R','Y','D','E','F','E','R','R','E','D','I','S','T','I','N','C','T','D', 'R','O','P','F','A','I','L','F','R','O','M','F','U','L','L','G','L','O', 'B','Y','I','F','I','S','N','U','L','L','O','R','D','E','R','E','S','T', 'R','I','C','T','R','I','G','H','T','R','O','L','L','B','A','C','K','R', 'O','W','U','N','I','O','N','U','S','I','N','G','V','A','C','U','U','M', 'V','I','E','W','I','N','I','T','I','A','L','L','Y', }; static const unsigned char aHash[127] = { 76, 105, 117, 74, 0, 45, 0, 0, 82, 0, 77, 0, 0, 42, 12, 78, 15, 0, 116, 85, 54, 112, 0, 19, 0, 0, 121, 0, 119, 115, 0, 22, 93, 0, 9, 0, 0, 70, 71, 0, 69, 6, 0, 48, 90, 102, 0, 118, 101, 0, 0, 44, 0, 103, 24, 0, 17, 0, 122, 53, 23, 0, 5, 110, 25, 96, 0, 0, 124, 106, 60, 123, 57, 28, 55, 0, 91, 0, 100, 26, 0, 99, 0, 0, 0, 95, 92, 97, 88, 109, 14, 39, 108, 0, 81, 0, 18, 89, 111, 32, 0, 120, 80, 113, 62, 46, 84, 0, 0, 94, 40, 59, 114, 0, 36, 0, 0, 29, 0, 86, 63, 64, 0, 20, 61, 0, 56, }; static const unsigned char aNext[124] = { 0, 0, 0, 0, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 13, 0, 0, 0, 0, 0, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 33, 0, 21, 0, 0, 0, 0, 0, 50, 0, 43, 3, 47, 0, 0, 0, 0, 30, 0, 58, 0, 38, 0, 0, 0, 1, 66, 0, 0, 67, 0, 41, 0, 0, 0, 0, 0, 0, 49, 65, 0, 0, 0, 0, 31, 52, 16, 34, 10, 0, 0, 0, 0, 0, 0, 0, 11, 72, 79, 0, 8, 0, 104, 98, 0, 107, 0, 87, 0, 75, 51, 0, 27, 37, 73, 83, 0, 35, 68, 0, 0, }; static const unsigned char aLen[124] = { 7, 7, 5, 4, 6, 4, 5, 3, 6, 7, 3, 6, 6, 7, 7, 3, 8, 2, 6, 5, 4, 4, 3, 10, 4, 6, 11, 6, 2, 7, 5, 5, 9, 6, 9, 9, 7, 10, 10, 4, 6, 2, 3, 9, 4, 2, 6, 5, 7, 4, 5, 7, 6, 6, 5, 6, 5, 5, 9, 7, 7, 3, 2, 4, 4, 7, 3, 6, 4, 7, 6, 12, 6, 9, 4, 6, 5, 4, 7, 6, 5, 6, 7, 5, 4, 5, 6, 5, 7, 3, 7, 13, 2, 2, 4, 6, 6, 8, 5, 17, 12, 7, 8, 8, 2, 4, 4, 4, 4, 4, 2, 2, 6, 5, 8, 5, 8, 3, 5, 5, 6, 4, 9, 3, }; static const unsigned short int aOffset[124] = { 0, 2, 2, 8, 9, 14, 16, 20, 23, 25, 25, 29, 33, 36, 41, 46, 48, 53, 54, 59, 62, 65, 67, 69, 78, 81, 86, 91, 95, 96, 101, 105, 109, 117, 122, 128, 136, 142, 152, 159, 162, 162, 165, 167, 167, 171, 176, 179, 184, 184, 188, 192, 199, 204, 209, 212, 218, 221, 225, 234, 240, 240, 240, 243, 246, 250, 251, 255, 261, 265, 272, 278, 290, 296, 305, 307, 313, 318, 320, 327, 332, 337, 343, 349, 354, 358, 361, 367, 371, 378, 380, 387, 389, 391, 400, 404, 410, 416, 424, 429, 429, 445, 452, 459, 460, 467, 471, 475, 479, 483, 486, 488, 490, 496, 500, 508, 513, 521, 524, 529, 534, 540, 544, 549, }; static const unsigned char aCode[124] = { TK_REINDEX, TK_INDEXED, TK_INDEX, TK_DESC, TK_ESCAPE, TK_EACH, TK_CHECK, TK_KEY, TK_BEFORE, TK_FOREIGN, TK_FOR, TK_IGNORE, TK_LIKE_KW, TK_EXPLAIN, TK_INSTEAD, TK_ADD, TK_DATABASE, TK_AS, TK_SELECT, TK_TABLE, TK_JOIN_KW, TK_THEN, TK_END, TK_DEFERRABLE, TK_ELSE, TK_EXCEPT, TK_TRANSACTION,TK_ACTION, TK_ON, TK_JOIN_KW, TK_ALTER, TK_RAISE, TK_EXCLUSIVE, TK_EXISTS, TK_SAVEPOINT, TK_INTERSECT, TK_TRIGGER, TK_REFERENCES, TK_CONSTRAINT, TK_INTO, TK_OFFSET, TK_OF, TK_SET, TK_TEMP, TK_TEMP, TK_OR, TK_UNIQUE, TK_QUERY, TK_WITHOUT, TK_WITH, TK_JOIN_KW, TK_RELEASE, TK_ATTACH, TK_HAVING, TK_GROUP, TK_UPDATE, TK_BEGIN, TK_JOIN_KW, TK_RECURSIVE, TK_BETWEEN, TK_NOTNULL, TK_NOT, TK_NO, TK_NULL, TK_LIKE_KW, TK_CASCADE, TK_ASC, TK_DELETE, TK_CASE, TK_COLLATE, TK_CREATE, TK_CTIME_KW, TK_DETACH, TK_IMMEDIATE, TK_JOIN, TK_INSERT, TK_MATCH, TK_PLAN, TK_ANALYZE, TK_PRAGMA, TK_ABORT, TK_VALUES, TK_VIRTUAL, TK_LIMIT, TK_WHEN, TK_WHERE, TK_RENAME, TK_AFTER, TK_REPLACE, TK_AND, TK_DEFAULT, TK_AUTOINCR, TK_TO, TK_IN, TK_CAST, TK_COLUMNKW, TK_COMMIT, TK_CONFLICT, TK_JOIN_KW, TK_CTIME_KW, TK_CTIME_KW, TK_PRIMARY, TK_DEFERRED, TK_DISTINCT, TK_IS, TK_DROP, TK_FAIL, TK_FROM, TK_JOIN_KW, TK_LIKE_KW, TK_BY, TK_IF, TK_ISNULL, TK_ORDER, TK_RESTRICT, TK_JOIN_KW, TK_ROLLBACK, TK_ROW, TK_UNION, TK_USING, TK_VACUUM, TK_VIEW, TK_INITIALLY, TK_ALL, }; int i, j; const char *zKW; if( n>=2 ){ i = ((charMap(z[0])*4) ^ (charMap(z[n-1])*3) ^ n) % 127; for(i=((int)aHash[i])-1; i>=0; i=((int)aNext[i])-1){ if( aLen[i]!=n ) continue; j = 0; zKW = &zText[aOffset[i]]; #ifdef SQLITE_ASCII while( j=0x42 && sqlite3IsEbcdicIdChar[c-0x40])) #endif /* Make the IdChar function accessible from ctime.c */ #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS SQLITE_PRIVATE int sqlite3IsIdChar(u8 c){ return IdChar(c); } #endif /* ** Return the length (in bytes) of the token that begins at z[0]. ** Store the token type in *tokenType before returning. */ SQLITE_PRIVATE int sqlite3GetToken(const unsigned char *z, int *tokenType){ int i, c; switch( aiClass[*z] ){ /* Switch on the character-class of the first byte ** of the token. See the comment on the CC_ defines ** above. */ case CC_SPACE: { testcase( z[0]==' ' ); testcase( z[0]=='\t' ); testcase( z[0]=='\n' ); testcase( z[0]=='\f' ); testcase( z[0]=='\r' ); for(i=1; sqlite3Isspace(z[i]); i++){} *tokenType = TK_SPACE; return i; } case CC_MINUS: { if( z[1]=='-' ){ for(i=2; (c=z[i])!=0 && c!='\n'; i++){} *tokenType = TK_SPACE; /* IMP: R-22934-25134 */ return i; } *tokenType = TK_MINUS; return 1; } case CC_LP: { *tokenType = TK_LP; return 1; } case CC_RP: { *tokenType = TK_RP; return 1; } case CC_SEMI: { *tokenType = TK_SEMI; return 1; } case CC_PLUS: { *tokenType = TK_PLUS; return 1; } case CC_STAR: { *tokenType = TK_STAR; return 1; } case CC_SLASH: { if( z[1]!='*' || z[2]==0 ){ *tokenType = TK_SLASH; return 1; } for(i=3, c=z[2]; (c!='*' || z[i]!='/') && (c=z[i])!=0; i++){} if( c ) i++; *tokenType = TK_SPACE; /* IMP: R-22934-25134 */ return i; } case CC_PERCENT: { *tokenType = TK_REM; return 1; } case CC_EQ: { *tokenType = TK_EQ; return 1 + (z[1]=='='); } case CC_LT: { if( (c=z[1])=='=' ){ *tokenType = TK_LE; return 2; }else if( c=='>' ){ *tokenType = TK_NE; return 2; }else if( c=='<' ){ *tokenType = TK_LSHIFT; return 2; }else{ *tokenType = TK_LT; return 1; } } case CC_GT: { if( (c=z[1])=='=' ){ *tokenType = TK_GE; return 2; }else if( c=='>' ){ *tokenType = TK_RSHIFT; return 2; }else{ *tokenType = TK_GT; return 1; } } case CC_BANG: { if( z[1]!='=' ){ *tokenType = TK_ILLEGAL; return 1; }else{ *tokenType = TK_NE; return 2; } } case CC_PIPE: { if( z[1]!='|' ){ *tokenType = TK_BITOR; return 1; }else{ *tokenType = TK_CONCAT; return 2; } } case CC_COMMA: { *tokenType = TK_COMMA; return 1; } case CC_AND: { *tokenType = TK_BITAND; return 1; } case CC_TILDA: { *tokenType = TK_BITNOT; return 1; } case CC_QUOTE: { int delim = z[0]; testcase( delim=='`' ); testcase( delim=='\'' ); testcase( delim=='"' ); for(i=1; (c=z[i])!=0; i++){ if( c==delim ){ if( z[i+1]==delim ){ i++; }else{ break; } } } if( c=='\'' ){ *tokenType = TK_STRING; return i+1; }else if( c!=0 ){ *tokenType = TK_ID; return i+1; }else{ *tokenType = TK_ILLEGAL; return i; } } case CC_DOT: { #ifndef SQLITE_OMIT_FLOATING_POINT if( !sqlite3Isdigit(z[1]) ) #endif { *tokenType = TK_DOT; return 1; } /* If the next character is a digit, this is a floating point ** number that begins with ".". Fall thru into the next case */ } case CC_DIGIT: { testcase( z[0]=='0' ); testcase( z[0]=='1' ); testcase( z[0]=='2' ); testcase( z[0]=='3' ); testcase( z[0]=='4' ); testcase( z[0]=='5' ); testcase( z[0]=='6' ); testcase( z[0]=='7' ); testcase( z[0]=='8' ); testcase( z[0]=='9' ); *tokenType = TK_INTEGER; #ifndef SQLITE_OMIT_HEX_INTEGER if( z[0]=='0' && (z[1]=='x' || z[1]=='X') && sqlite3Isxdigit(z[2]) ){ for(i=3; sqlite3Isxdigit(z[i]); i++){} return i; } #endif for(i=0; sqlite3Isdigit(z[i]); i++){} #ifndef SQLITE_OMIT_FLOATING_POINT if( z[i]=='.' ){ i++; while( sqlite3Isdigit(z[i]) ){ i++; } *tokenType = TK_FLOAT; } if( (z[i]=='e' || z[i]=='E') && ( sqlite3Isdigit(z[i+1]) || ((z[i+1]=='+' || z[i+1]=='-') && sqlite3Isdigit(z[i+2])) ) ){ i += 2; while( sqlite3Isdigit(z[i]) ){ i++; } *tokenType = TK_FLOAT; } #endif while( IdChar(z[i]) ){ *tokenType = TK_ILLEGAL; i++; } return i; } case CC_QUOTE2: { for(i=1, c=z[0]; c!=']' && (c=z[i])!=0; i++){} *tokenType = c==']' ? TK_ID : TK_ILLEGAL; return i; } case CC_VARNUM: { *tokenType = TK_VARIABLE; for(i=1; sqlite3Isdigit(z[i]); i++){} return i; } case CC_DOLLAR: case CC_VARALPHA: { int n = 0; testcase( z[0]=='$' ); testcase( z[0]=='@' ); testcase( z[0]==':' ); testcase( z[0]=='#' ); *tokenType = TK_VARIABLE; for(i=1; (c=z[i])!=0; i++){ if( IdChar(c) ){ n++; #ifndef SQLITE_OMIT_TCL_VARIABLE }else if( c=='(' && n>0 ){ do{ i++; }while( (c=z[i])!=0 && !sqlite3Isspace(c) && c!=')' ); if( c==')' ){ i++; }else{ *tokenType = TK_ILLEGAL; } break; }else if( c==':' && z[i+1]==':' ){ i++; #endif }else{ break; } } if( n==0 ) *tokenType = TK_ILLEGAL; return i; } case CC_KYWD: { for(i=1; aiClass[z[i]]<=CC_KYWD; i++){} if( IdChar(z[i]) ){ /* This token started out using characters that can appear in keywords, ** but z[i] is a character not allowed within keywords, so this must ** be an identifier instead */ i++; break; } *tokenType = TK_ID; return keywordCode((char*)z, i, tokenType); } case CC_X: { #ifndef SQLITE_OMIT_BLOB_LITERAL testcase( z[0]=='x' ); testcase( z[0]=='X' ); if( z[1]=='\'' ){ *tokenType = TK_BLOB; for(i=2; sqlite3Isxdigit(z[i]); i++){} if( z[i]!='\'' || i%2 ){ *tokenType = TK_ILLEGAL; while( z[i] && z[i]!='\'' ){ i++; } } if( z[i] ) i++; return i; } #endif /* If it is not a BLOB literal, then it must be an ID, since no ** SQL keywords start with the letter 'x'. Fall through */ } case CC_ID: { i = 1; break; } default: { *tokenType = TK_ILLEGAL; return 1; } } while( IdChar(z[i]) ){ i++; } *tokenType = TK_ID; return i; } /* ** Run the parser on the given SQL string. The parser structure is ** passed in. An SQLITE_ status code is returned. If an error occurs ** then an and attempt is made to write an error message into ** memory obtained from sqlite3_malloc() and to make *pzErrMsg point to that ** error message. */ SQLITE_PRIVATE int sqlite3RunParser(Parse *pParse, const char *zSql, char **pzErrMsg){ int nErr = 0; /* Number of errors encountered */ int i; /* Loop counter */ void *pEngine; /* The LEMON-generated LALR(1) parser */ int tokenType; /* type of the next token */ int lastTokenParsed = -1; /* type of the previous token */ sqlite3 *db = pParse->db; /* The database connection */ int mxSqlLen; /* Max length of an SQL string */ assert( zSql!=0 ); mxSqlLen = db->aLimit[SQLITE_LIMIT_SQL_LENGTH]; if( db->nVdbeActive==0 ){ db->u1.isInterrupted = 0; } pParse->rc = SQLITE_OK; pParse->zTail = zSql; i = 0; assert( pzErrMsg!=0 ); /* sqlite3ParserTrace(stdout, "parser: "); */ pEngine = sqlite3ParserAlloc(sqlite3Malloc); if( pEngine==0 ){ sqlite3OomFault(db); return SQLITE_NOMEM_BKPT; } assert( pParse->pNewTable==0 ); assert( pParse->pNewTrigger==0 ); assert( pParse->nVar==0 ); assert( pParse->nzVar==0 ); assert( pParse->azVar==0 ); while( 1 ){ assert( i>=0 ); if( zSql[i]!=0 ){ pParse->sLastToken.z = &zSql[i]; pParse->sLastToken.n = sqlite3GetToken((u8*)&zSql[i],&tokenType); i += pParse->sLastToken.n; if( i>mxSqlLen ){ pParse->rc = SQLITE_TOOBIG; break; } }else{ /* Upon reaching the end of input, call the parser two more times ** with tokens TK_SEMI and 0, in that order. */ if( lastTokenParsed==TK_SEMI ){ tokenType = 0; }else if( lastTokenParsed==0 ){ break; }else{ tokenType = TK_SEMI; } } if( tokenType>=TK_SPACE ){ assert( tokenType==TK_SPACE || tokenType==TK_ILLEGAL ); if( db->u1.isInterrupted ){ pParse->rc = SQLITE_INTERRUPT; break; } if( tokenType==TK_ILLEGAL ){ sqlite3ErrorMsg(pParse, "unrecognized token: \"%T\"", &pParse->sLastToken); break; } }else{ sqlite3Parser(pEngine, tokenType, pParse->sLastToken, pParse); lastTokenParsed = tokenType; if( pParse->rc!=SQLITE_OK || db->mallocFailed ) break; } } assert( nErr==0 ); pParse->zTail = &zSql[i]; #ifdef YYTRACKMAXSTACKDEPTH sqlite3_mutex_enter(sqlite3MallocMutex()); sqlite3StatusHighwater(SQLITE_STATUS_PARSER_STACK, sqlite3ParserStackPeak(pEngine) ); sqlite3_mutex_leave(sqlite3MallocMutex()); #endif /* YYDEBUG */ sqlite3ParserFree(pEngine, sqlite3_free); if( db->mallocFailed ){ pParse->rc = SQLITE_NOMEM_BKPT; } if( pParse->rc!=SQLITE_OK && pParse->rc!=SQLITE_DONE && pParse->zErrMsg==0 ){ pParse->zErrMsg = sqlite3MPrintf(db, "%s", sqlite3ErrStr(pParse->rc)); } assert( pzErrMsg!=0 ); if( pParse->zErrMsg ){ *pzErrMsg = pParse->zErrMsg; sqlite3_log(pParse->rc, "%s", *pzErrMsg); pParse->zErrMsg = 0; nErr++; } if( pParse->pVdbe && pParse->nErr>0 && pParse->nested==0 ){ sqlite3VdbeDelete(pParse->pVdbe); pParse->pVdbe = 0; } #ifndef SQLITE_OMIT_SHARED_CACHE if( pParse->nested==0 ){ sqlite3DbFree(db, pParse->aTableLock); pParse->aTableLock = 0; pParse->nTableLock = 0; } #endif #ifndef SQLITE_OMIT_VIRTUALTABLE sqlite3_free(pParse->apVtabLock); #endif if( !IN_DECLARE_VTAB ){ /* If the pParse->declareVtab flag is set, do not delete any table ** structure built up in pParse->pNewTable. The calling code (see vtab.c) ** will take responsibility for freeing the Table structure. */ sqlite3DeleteTable(db, pParse->pNewTable); } if( pParse->pWithToFree ) sqlite3WithDelete(db, pParse->pWithToFree); sqlite3DeleteTrigger(db, pParse->pNewTrigger); for(i=pParse->nzVar-1; i>=0; i--) sqlite3DbFree(db, pParse->azVar[i]); sqlite3DbFree(db, pParse->azVar); while( pParse->pAinc ){ AutoincInfo *p = pParse->pAinc; pParse->pAinc = p->pNext; sqlite3DbFree(db, p); } while( pParse->pZombieTab ){ Table *p = pParse->pZombieTab; pParse->pZombieTab = p->pNextZombie; sqlite3DeleteTable(db, p); } assert( nErr==0 || pParse->rc!=SQLITE_OK ); return nErr; } /************** End of tokenize.c ********************************************/ /************** Begin file complete.c ****************************************/ /* ** 2001 September 15 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ************************************************************************* ** An tokenizer for SQL ** ** This file contains C code that implements the sqlite3_complete() API. ** This code used to be part of the tokenizer.c source file. But by ** separating it out, the code will be automatically omitted from ** static links that do not use it. */ /* #include "sqliteInt.h" */ #ifndef SQLITE_OMIT_COMPLETE /* ** This is defined in tokenize.c. We just have to import the definition. */ #ifndef SQLITE_AMALGAMATION #ifdef SQLITE_ASCII #define IdChar(C) ((sqlite3CtypeMap[(unsigned char)C]&0x46)!=0) #endif #ifdef SQLITE_EBCDIC SQLITE_PRIVATE const char sqlite3IsEbcdicIdChar[]; #define IdChar(C) (((c=C)>=0x42 && sqlite3IsEbcdicIdChar[c-0x40])) #endif #endif /* SQLITE_AMALGAMATION */ /* ** Token types used by the sqlite3_complete() routine. See the header ** comments on that procedure for additional information. */ #define tkSEMI 0 #define tkWS 1 #define tkOTHER 2 #ifndef SQLITE_OMIT_TRIGGER #define tkEXPLAIN 3 #define tkCREATE 4 #define tkTEMP 5 #define tkTRIGGER 6 #define tkEND 7 #endif /* ** Return TRUE if the given SQL string ends in a semicolon. ** ** Special handling is require for CREATE TRIGGER statements. ** Whenever the CREATE TRIGGER keywords are seen, the statement ** must end with ";END;". ** ** This implementation uses a state machine with 8 states: ** ** (0) INVALID We have not yet seen a non-whitespace character. ** ** (1) START At the beginning or end of an SQL statement. This routine ** returns 1 if it ends in the START state and 0 if it ends ** in any other state. ** ** (2) NORMAL We are in the middle of statement which ends with a single ** semicolon. ** ** (3) EXPLAIN The keyword EXPLAIN has been seen at the beginning of ** a statement. ** ** (4) CREATE The keyword CREATE has been seen at the beginning of a ** statement, possibly preceded by EXPLAIN and/or followed by ** TEMP or TEMPORARY ** ** (5) TRIGGER We are in the middle of a trigger definition that must be ** ended by a semicolon, the keyword END, and another semicolon. ** ** (6) SEMI We've seen the first semicolon in the ";END;" that occurs at ** the end of a trigger definition. ** ** (7) END We've seen the ";END" of the ";END;" that occurs at the end ** of a trigger definition. ** ** Transitions between states above are determined by tokens extracted ** from the input. The following tokens are significant: ** ** (0) tkSEMI A semicolon. ** (1) tkWS Whitespace. ** (2) tkOTHER Any other SQL token. ** (3) tkEXPLAIN The "explain" keyword. ** (4) tkCREATE The "create" keyword. ** (5) tkTEMP The "temp" or "temporary" keyword. ** (6) tkTRIGGER The "trigger" keyword. ** (7) tkEND The "end" keyword. ** ** Whitespace never causes a state transition and is always ignored. ** This means that a SQL string of all whitespace is invalid. ** ** If we compile with SQLITE_OMIT_TRIGGER, all of the computation needed ** to recognize the end of a trigger can be omitted. All we have to do ** is look for a semicolon that is not part of an string or comment. */ SQLITE_API int sqlite3_complete(const char *zSql){ u8 state = 0; /* Current state, using numbers defined in header comment */ u8 token; /* Value of the next token */ #ifndef SQLITE_OMIT_TRIGGER /* A complex statement machine used to detect the end of a CREATE TRIGGER ** statement. This is the normal case. */ static const u8 trans[8][8] = { /* Token: */ /* State: ** SEMI WS OTHER EXPLAIN CREATE TEMP TRIGGER END */ /* 0 INVALID: */ { 1, 0, 2, 3, 4, 2, 2, 2, }, /* 1 START: */ { 1, 1, 2, 3, 4, 2, 2, 2, }, /* 2 NORMAL: */ { 1, 2, 2, 2, 2, 2, 2, 2, }, /* 3 EXPLAIN: */ { 1, 3, 3, 2, 4, 2, 2, 2, }, /* 4 CREATE: */ { 1, 4, 2, 2, 2, 4, 5, 2, }, /* 5 TRIGGER: */ { 6, 5, 5, 5, 5, 5, 5, 5, }, /* 6 SEMI: */ { 6, 6, 5, 5, 5, 5, 5, 7, }, /* 7 END: */ { 1, 7, 5, 5, 5, 5, 5, 5, }, }; #else /* If triggers are not supported by this compile then the statement machine ** used to detect the end of a statement is much simpler */ static const u8 trans[3][3] = { /* Token: */ /* State: ** SEMI WS OTHER */ /* 0 INVALID: */ { 1, 0, 2, }, /* 1 START: */ { 1, 1, 2, }, /* 2 NORMAL: */ { 1, 2, 2, }, }; #endif /* SQLITE_OMIT_TRIGGER */ #ifdef SQLITE_ENABLE_API_ARMOR if( zSql==0 ){ (void)SQLITE_MISUSE_BKPT; return 0; } #endif while( *zSql ){ switch( *zSql ){ case ';': { /* A semicolon */ token = tkSEMI; break; } case ' ': case '\r': case '\t': case '\n': case '\f': { /* White space is ignored */ token = tkWS; break; } case '/': { /* C-style comments */ if( zSql[1]!='*' ){ token = tkOTHER; break; } zSql += 2; while( zSql[0] && (zSql[0]!='*' || zSql[1]!='/') ){ zSql++; } if( zSql[0]==0 ) return 0; zSql++; token = tkWS; break; } case '-': { /* SQL-style comments from "--" to end of line */ if( zSql[1]!='-' ){ token = tkOTHER; break; } while( *zSql && *zSql!='\n' ){ zSql++; } if( *zSql==0 ) return state==1; token = tkWS; break; } case '[': { /* Microsoft-style identifiers in [...] */ zSql++; while( *zSql && *zSql!=']' ){ zSql++; } if( *zSql==0 ) return 0; token = tkOTHER; break; } case '`': /* Grave-accent quoted symbols used by MySQL */ case '"': /* single- and double-quoted strings */ case '\'': { int c = *zSql; zSql++; while( *zSql && *zSql!=c ){ zSql++; } if( *zSql==0 ) return 0; token = tkOTHER; break; } default: { #ifdef SQLITE_EBCDIC unsigned char c; #endif if( IdChar((u8)*zSql) ){ /* Keywords and unquoted identifiers */ int nId; for(nId=1; IdChar(zSql[nId]); nId++){} #ifdef SQLITE_OMIT_TRIGGER token = tkOTHER; #else switch( *zSql ){ case 'c': case 'C': { if( nId==6 && sqlite3StrNICmp(zSql, "create", 6)==0 ){ token = tkCREATE; }else{ token = tkOTHER; } break; } case 't': case 'T': { if( nId==7 && sqlite3StrNICmp(zSql, "trigger", 7)==0 ){ token = tkTRIGGER; }else if( nId==4 && sqlite3StrNICmp(zSql, "temp", 4)==0 ){ token = tkTEMP; }else if( nId==9 && sqlite3StrNICmp(zSql, "temporary", 9)==0 ){ token = tkTEMP; }else{ token = tkOTHER; } break; } case 'e': case 'E': { if( nId==3 && sqlite3StrNICmp(zSql, "end", 3)==0 ){ token = tkEND; }else #ifndef SQLITE_OMIT_EXPLAIN if( nId==7 && sqlite3StrNICmp(zSql, "explain", 7)==0 ){ token = tkEXPLAIN; }else #endif { token = tkOTHER; } break; } default: { token = tkOTHER; break; } } #endif /* SQLITE_OMIT_TRIGGER */ zSql += nId-1; }else{ /* Operators and special symbols */ token = tkOTHER; } break; } } state = trans[state][token]; zSql++; } return state==1; } #ifndef SQLITE_OMIT_UTF16 /* ** This routine is the same as the sqlite3_complete() routine described ** above, except that the parameter is required to be UTF-16 encoded, not ** UTF-8. */ SQLITE_API int sqlite3_complete16(const void *zSql){ sqlite3_value *pVal; char const *zSql8; int rc; #ifndef SQLITE_OMIT_AUTOINIT rc = sqlite3_initialize(); if( rc ) return rc; #endif pVal = sqlite3ValueNew(0); sqlite3ValueSetStr(pVal, -1, zSql, SQLITE_UTF16NATIVE, SQLITE_STATIC); zSql8 = sqlite3ValueText(pVal, SQLITE_UTF8); if( zSql8 ){ rc = sqlite3_complete(zSql8); }else{ rc = SQLITE_NOMEM_BKPT; } sqlite3ValueFree(pVal); return rc & 0xff; } #endif /* SQLITE_OMIT_UTF16 */ #endif /* SQLITE_OMIT_COMPLETE */ /************** End of complete.c ********************************************/ /************** Begin file main.c ********************************************/ /* ** 2001 September 15 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ************************************************************************* ** Main file for the SQLite library. The routines in this file ** implement the programmer interface to the library. Routines in ** other files are for internal use by SQLite and should not be ** accessed by users of the library. */ /* #include "sqliteInt.h" */ #ifdef SQLITE_ENABLE_FTS3 /************** Include fts3.h in the middle of main.c ***********************/ /************** Begin file fts3.h ********************************************/ /* ** 2006 Oct 10 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ****************************************************************************** ** ** This header file is used by programs that want to link against the ** FTS3 library. All it does is declare the sqlite3Fts3Init() interface. */ /* #include "sqlite3.h" */ #if 0 extern "C" { #endif /* __cplusplus */ SQLITE_PRIVATE int sqlite3Fts3Init(sqlite3 *db); #if 0 } /* extern "C" */ #endif /* __cplusplus */ /************** End of fts3.h ************************************************/ /************** Continuing where we left off in main.c ***********************/ #endif #ifdef SQLITE_ENABLE_RTREE /************** Include rtree.h in the middle of main.c **********************/ /************** Begin file rtree.h *******************************************/ /* ** 2008 May 26 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ****************************************************************************** ** ** This header file is used by programs that want to link against the ** RTREE library. All it does is declare the sqlite3RtreeInit() interface. */ /* #include "sqlite3.h" */ #if 0 extern "C" { #endif /* __cplusplus */ SQLITE_PRIVATE int sqlite3RtreeInit(sqlite3 *db); #if 0 } /* extern "C" */ #endif /* __cplusplus */ /************** End of rtree.h ***********************************************/ /************** Continuing where we left off in main.c ***********************/ #endif #ifdef SQLITE_ENABLE_ICU /************** Include sqliteicu.h in the middle of main.c ******************/ /************** Begin file sqliteicu.h ***************************************/ /* ** 2008 May 26 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ****************************************************************************** ** ** This header file is used by programs that want to link against the ** ICU extension. All it does is declare the sqlite3IcuInit() interface. */ /* #include "sqlite3.h" */ #if 0 extern "C" { #endif /* __cplusplus */ SQLITE_PRIVATE int sqlite3IcuInit(sqlite3 *db); #if 0 } /* extern "C" */ #endif /* __cplusplus */ /************** End of sqliteicu.h *******************************************/ /************** Continuing where we left off in main.c ***********************/ #endif #ifdef SQLITE_ENABLE_JSON1 SQLITE_PRIVATE int sqlite3Json1Init(sqlite3*); #endif #ifdef SQLITE_ENABLE_FTS5 SQLITE_PRIVATE int sqlite3Fts5Init(sqlite3*); #endif #ifndef SQLITE_AMALGAMATION /* IMPLEMENTATION-OF: R-46656-45156 The sqlite3_version[] string constant ** contains the text of SQLITE_VERSION macro. */ SQLITE_API const char sqlite3_version[] = SQLITE_VERSION; #endif /* IMPLEMENTATION-OF: R-53536-42575 The sqlite3_libversion() function returns ** a pointer to the to the sqlite3_version[] string constant. */ SQLITE_API const char *sqlite3_libversion(void){ return sqlite3_version; } /* IMPLEMENTATION-OF: R-63124-39300 The sqlite3_sourceid() function returns a ** pointer to a string constant whose value is the same as the ** SQLITE_SOURCE_ID C preprocessor macro. */ SQLITE_API const char *sqlite3_sourceid(void){ return SQLITE_SOURCE_ID; } /* IMPLEMENTATION-OF: R-35210-63508 The sqlite3_libversion_number() function ** returns an integer equal to SQLITE_VERSION_NUMBER. */ SQLITE_API int sqlite3_libversion_number(void){ return SQLITE_VERSION_NUMBER; } /* IMPLEMENTATION-OF: R-20790-14025 The sqlite3_threadsafe() function returns ** zero if and only if SQLite was compiled with mutexing code omitted due to ** the SQLITE_THREADSAFE compile-time option being set to 0. */ SQLITE_API int sqlite3_threadsafe(void){ return SQLITE_THREADSAFE; } /* ** When compiling the test fixture or with debugging enabled (on Win32), ** this variable being set to non-zero will cause OSTRACE macros to emit ** extra diagnostic information. */ #ifdef SQLITE_HAVE_OS_TRACE # ifndef SQLITE_DEBUG_OS_TRACE # define SQLITE_DEBUG_OS_TRACE 0 # endif int sqlite3OSTrace = SQLITE_DEBUG_OS_TRACE; #endif #if !defined(SQLITE_OMIT_TRACE) && defined(SQLITE_ENABLE_IOTRACE) /* ** If the following function pointer is not NULL and if ** SQLITE_ENABLE_IOTRACE is enabled, then messages describing ** I/O active are written using this function. These messages ** are intended for debugging activity only. */ SQLITE_API void (SQLITE_CDECL *sqlite3IoTrace)(const char*, ...) = 0; #endif /* ** If the following global variable points to a string which is the ** name of a directory, then that directory will be used to store ** temporary files. ** ** See also the "PRAGMA temp_store_directory" SQL command. */ SQLITE_API char *sqlite3_temp_directory = 0; /* ** If the following global variable points to a string which is the ** name of a directory, then that directory will be used to store ** all database files specified with a relative pathname. ** ** See also the "PRAGMA data_store_directory" SQL command. */ SQLITE_API char *sqlite3_data_directory = 0; /* ** Initialize SQLite. ** ** This routine must be called to initialize the memory allocation, ** VFS, and mutex subsystems prior to doing any serious work with ** SQLite. But as long as you do not compile with SQLITE_OMIT_AUTOINIT ** this routine will be called automatically by key routines such as ** sqlite3_open(). ** ** This routine is a no-op except on its very first call for the process, ** or for the first call after a call to sqlite3_shutdown. ** ** The first thread to call this routine runs the initialization to ** completion. If subsequent threads call this routine before the first ** thread has finished the initialization process, then the subsequent ** threads must block until the first thread finishes with the initialization. ** ** The first thread might call this routine recursively. Recursive ** calls to this routine should not block, of course. Otherwise the ** initialization process would never complete. ** ** Let X be the first thread to enter this routine. Let Y be some other ** thread. Then while the initial invocation of this routine by X is ** incomplete, it is required that: ** ** * Calls to this routine from Y must block until the outer-most ** call by X completes. ** ** * Recursive calls to this routine from thread X return immediately ** without blocking. */ SQLITE_API int sqlite3_initialize(void){ MUTEX_LOGIC( sqlite3_mutex *pMaster; ) /* The main static mutex */ int rc; /* Result code */ #ifdef SQLITE_EXTRA_INIT int bRunExtraInit = 0; /* Extra initialization needed */ #endif #ifdef SQLITE_OMIT_WSD rc = sqlite3_wsd_init(4096, 24); if( rc!=SQLITE_OK ){ return rc; } #endif /* If the following assert() fails on some obscure processor/compiler ** combination, the work-around is to set the correct pointer ** size at compile-time using -DSQLITE_PTRSIZE=n compile-time option */ assert( SQLITE_PTRSIZE==sizeof(char*) ); /* If SQLite is already completely initialized, then this call ** to sqlite3_initialize() should be a no-op. But the initialization ** must be complete. So isInit must not be set until the very end ** of this routine. */ if( sqlite3GlobalConfig.isInit ) return SQLITE_OK; /* Make sure the mutex subsystem is initialized. If unable to ** initialize the mutex subsystem, return early with the error. ** If the system is so sick that we are unable to allocate a mutex, ** there is not much SQLite is going to be able to do. ** ** The mutex subsystem must take care of serializing its own ** initialization. */ rc = sqlite3MutexInit(); if( rc ) return rc; /* Initialize the malloc() system and the recursive pInitMutex mutex. ** This operation is protected by the STATIC_MASTER mutex. Note that ** MutexAlloc() is called for a static mutex prior to initializing the ** malloc subsystem - this implies that the allocation of a static ** mutex must not require support from the malloc subsystem. */ MUTEX_LOGIC( pMaster = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); ) sqlite3_mutex_enter(pMaster); sqlite3GlobalConfig.isMutexInit = 1; if( !sqlite3GlobalConfig.isMallocInit ){ rc = sqlite3MallocInit(); } if( rc==SQLITE_OK ){ sqlite3GlobalConfig.isMallocInit = 1; if( !sqlite3GlobalConfig.pInitMutex ){ sqlite3GlobalConfig.pInitMutex = sqlite3MutexAlloc(SQLITE_MUTEX_RECURSIVE); if( sqlite3GlobalConfig.bCoreMutex && !sqlite3GlobalConfig.pInitMutex ){ rc = SQLITE_NOMEM_BKPT; } } } if( rc==SQLITE_OK ){ sqlite3GlobalConfig.nRefInitMutex++; } sqlite3_mutex_leave(pMaster); /* If rc is not SQLITE_OK at this point, then either the malloc ** subsystem could not be initialized or the system failed to allocate ** the pInitMutex mutex. Return an error in either case. */ if( rc!=SQLITE_OK ){ return rc; } /* Do the rest of the initialization under the recursive mutex so ** that we will be able to handle recursive calls into ** sqlite3_initialize(). The recursive calls normally come through ** sqlite3_os_init() when it invokes sqlite3_vfs_register(), but other ** recursive calls might also be possible. ** ** IMPLEMENTATION-OF: R-00140-37445 SQLite automatically serializes calls ** to the xInit method, so the xInit method need not be threadsafe. ** ** The following mutex is what serializes access to the appdef pcache xInit ** methods. The sqlite3_pcache_methods.xInit() all is embedded in the ** call to sqlite3PcacheInitialize(). */ sqlite3_mutex_enter(sqlite3GlobalConfig.pInitMutex); if( sqlite3GlobalConfig.isInit==0 && sqlite3GlobalConfig.inProgress==0 ){ sqlite3GlobalConfig.inProgress = 1; #ifdef SQLITE_ENABLE_SQLLOG { extern void sqlite3_init_sqllog(void); sqlite3_init_sqllog(); } #endif memset(&sqlite3BuiltinFunctions, 0, sizeof(sqlite3BuiltinFunctions)); sqlite3RegisterBuiltinFunctions(); if( sqlite3GlobalConfig.isPCacheInit==0 ){ rc = sqlite3PcacheInitialize(); } if( rc==SQLITE_OK ){ sqlite3GlobalConfig.isPCacheInit = 1; rc = sqlite3OsInit(); } if( rc==SQLITE_OK ){ sqlite3PCacheBufferSetup( sqlite3GlobalConfig.pPage, sqlite3GlobalConfig.szPage, sqlite3GlobalConfig.nPage); sqlite3GlobalConfig.isInit = 1; #ifdef SQLITE_EXTRA_INIT bRunExtraInit = 1; #endif } sqlite3GlobalConfig.inProgress = 0; } sqlite3_mutex_leave(sqlite3GlobalConfig.pInitMutex); /* Go back under the static mutex and clean up the recursive ** mutex to prevent a resource leak. */ sqlite3_mutex_enter(pMaster); sqlite3GlobalConfig.nRefInitMutex--; if( sqlite3GlobalConfig.nRefInitMutex<=0 ){ assert( sqlite3GlobalConfig.nRefInitMutex==0 ); sqlite3_mutex_free(sqlite3GlobalConfig.pInitMutex); sqlite3GlobalConfig.pInitMutex = 0; } sqlite3_mutex_leave(pMaster); /* The following is just a sanity check to make sure SQLite has ** been compiled correctly. It is important to run this code, but ** we don't want to run it too often and soak up CPU cycles for no ** reason. So we run it once during initialization. */ #ifndef NDEBUG #ifndef SQLITE_OMIT_FLOATING_POINT /* This section of code's only "output" is via assert() statements. */ if ( rc==SQLITE_OK ){ u64 x = (((u64)1)<<63)-1; double y; assert(sizeof(x)==8); assert(sizeof(x)==sizeof(y)); memcpy(&y, &x, 8); assert( sqlite3IsNaN(y) ); } #endif #endif /* Do extra initialization steps requested by the SQLITE_EXTRA_INIT ** compile-time option. */ #ifdef SQLITE_EXTRA_INIT if( bRunExtraInit ){ int SQLITE_EXTRA_INIT(const char*); rc = SQLITE_EXTRA_INIT(0); } #endif return rc; } /* ** Undo the effects of sqlite3_initialize(). Must not be called while ** there are outstanding database connections or memory allocations or ** while any part of SQLite is otherwise in use in any thread. This ** routine is not threadsafe. But it is safe to invoke this routine ** on when SQLite is already shut down. If SQLite is already shut down ** when this routine is invoked, then this routine is a harmless no-op. */ SQLITE_API int sqlite3_shutdown(void){ #ifdef SQLITE_OMIT_WSD int rc = sqlite3_wsd_init(4096, 24); if( rc!=SQLITE_OK ){ return rc; } #endif if( sqlite3GlobalConfig.isInit ){ #ifdef SQLITE_EXTRA_SHUTDOWN void SQLITE_EXTRA_SHUTDOWN(void); SQLITE_EXTRA_SHUTDOWN(); #endif sqlite3_os_end(); sqlite3_reset_auto_extension(); sqlite3GlobalConfig.isInit = 0; } if( sqlite3GlobalConfig.isPCacheInit ){ sqlite3PcacheShutdown(); sqlite3GlobalConfig.isPCacheInit = 0; } if( sqlite3GlobalConfig.isMallocInit ){ sqlite3MallocEnd(); sqlite3GlobalConfig.isMallocInit = 0; #ifndef SQLITE_OMIT_SHUTDOWN_DIRECTORIES /* The heap subsystem has now been shutdown and these values are supposed ** to be NULL or point to memory that was obtained from sqlite3_malloc(), ** which would rely on that heap subsystem; therefore, make sure these ** values cannot refer to heap memory that was just invalidated when the ** heap subsystem was shutdown. This is only done if the current call to ** this function resulted in the heap subsystem actually being shutdown. */ sqlite3_data_directory = 0; sqlite3_temp_directory = 0; #endif } if( sqlite3GlobalConfig.isMutexInit ){ sqlite3MutexEnd(); sqlite3GlobalConfig.isMutexInit = 0; } return SQLITE_OK; } /* ** This API allows applications to modify the global configuration of ** the SQLite library at run-time. ** ** This routine should only be called when there are no outstanding ** database connections or memory allocations. This routine is not ** threadsafe. Failure to heed these warnings can lead to unpredictable ** behavior. */ SQLITE_API int sqlite3_config(int op, ...){ va_list ap; int rc = SQLITE_OK; /* sqlite3_config() shall return SQLITE_MISUSE if it is invoked while ** the SQLite library is in use. */ if( sqlite3GlobalConfig.isInit ) return SQLITE_MISUSE_BKPT; va_start(ap, op); switch( op ){ /* Mutex configuration options are only available in a threadsafe ** compile. */ #if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0 /* IMP: R-54466-46756 */ case SQLITE_CONFIG_SINGLETHREAD: { /* EVIDENCE-OF: R-02748-19096 This option sets the threading mode to ** Single-thread. */ sqlite3GlobalConfig.bCoreMutex = 0; /* Disable mutex on core */ sqlite3GlobalConfig.bFullMutex = 0; /* Disable mutex on connections */ break; } #endif #if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0 /* IMP: R-20520-54086 */ case SQLITE_CONFIG_MULTITHREAD: { /* EVIDENCE-OF: R-14374-42468 This option sets the threading mode to ** Multi-thread. */ sqlite3GlobalConfig.bCoreMutex = 1; /* Enable mutex on core */ sqlite3GlobalConfig.bFullMutex = 0; /* Disable mutex on connections */ break; } #endif #if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0 /* IMP: R-59593-21810 */ case SQLITE_CONFIG_SERIALIZED: { /* EVIDENCE-OF: R-41220-51800 This option sets the threading mode to ** Serialized. */ sqlite3GlobalConfig.bCoreMutex = 1; /* Enable mutex on core */ sqlite3GlobalConfig.bFullMutex = 1; /* Enable mutex on connections */ break; } #endif #if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0 /* IMP: R-63666-48755 */ case SQLITE_CONFIG_MUTEX: { /* Specify an alternative mutex implementation */ sqlite3GlobalConfig.mutex = *va_arg(ap, sqlite3_mutex_methods*); break; } #endif #if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0 /* IMP: R-14450-37597 */ case SQLITE_CONFIG_GETMUTEX: { /* Retrieve the current mutex implementation */ *va_arg(ap, sqlite3_mutex_methods*) = sqlite3GlobalConfig.mutex; break; } #endif case SQLITE_CONFIG_MALLOC: { /* EVIDENCE-OF: R-55594-21030 The SQLITE_CONFIG_MALLOC option takes a ** single argument which is a pointer to an instance of the ** sqlite3_mem_methods structure. The argument specifies alternative ** low-level memory allocation routines to be used in place of the memory ** allocation routines built into SQLite. */ sqlite3GlobalConfig.m = *va_arg(ap, sqlite3_mem_methods*); break; } case SQLITE_CONFIG_GETMALLOC: { /* EVIDENCE-OF: R-51213-46414 The SQLITE_CONFIG_GETMALLOC option takes a ** single argument which is a pointer to an instance of the ** sqlite3_mem_methods structure. The sqlite3_mem_methods structure is ** filled with the currently defined memory allocation routines. */ if( sqlite3GlobalConfig.m.xMalloc==0 ) sqlite3MemSetDefault(); *va_arg(ap, sqlite3_mem_methods*) = sqlite3GlobalConfig.m; break; } case SQLITE_CONFIG_MEMSTATUS: { /* EVIDENCE-OF: R-61275-35157 The SQLITE_CONFIG_MEMSTATUS option takes ** single argument of type int, interpreted as a boolean, which enables ** or disables the collection of memory allocation statistics. */ sqlite3GlobalConfig.bMemstat = va_arg(ap, int); break; } case SQLITE_CONFIG_SCRATCH: { /* EVIDENCE-OF: R-08404-60887 There are three arguments to ** SQLITE_CONFIG_SCRATCH: A pointer an 8-byte aligned memory buffer from ** which the scratch allocations will be drawn, the size of each scratch ** allocation (sz), and the maximum number of scratch allocations (N). */ sqlite3GlobalConfig.pScratch = va_arg(ap, void*); sqlite3GlobalConfig.szScratch = va_arg(ap, int); sqlite3GlobalConfig.nScratch = va_arg(ap, int); break; } case SQLITE_CONFIG_PAGECACHE: { /* EVIDENCE-OF: R-18761-36601 There are three arguments to ** SQLITE_CONFIG_PAGECACHE: A pointer to 8-byte aligned memory (pMem), ** the size of each page cache line (sz), and the number of cache lines ** (N). */ sqlite3GlobalConfig.pPage = va_arg(ap, void*); sqlite3GlobalConfig.szPage = va_arg(ap, int); sqlite3GlobalConfig.nPage = va_arg(ap, int); break; } case SQLITE_CONFIG_PCACHE_HDRSZ: { /* EVIDENCE-OF: R-39100-27317 The SQLITE_CONFIG_PCACHE_HDRSZ option takes ** a single parameter which is a pointer to an integer and writes into ** that integer the number of extra bytes per page required for each page ** in SQLITE_CONFIG_PAGECACHE. */ *va_arg(ap, int*) = sqlite3HeaderSizeBtree() + sqlite3HeaderSizePcache() + sqlite3HeaderSizePcache1(); break; } case SQLITE_CONFIG_PCACHE: { /* no-op */ break; } case SQLITE_CONFIG_GETPCACHE: { /* now an error */ rc = SQLITE_ERROR; break; } case SQLITE_CONFIG_PCACHE2: { /* EVIDENCE-OF: R-63325-48378 The SQLITE_CONFIG_PCACHE2 option takes a ** single argument which is a pointer to an sqlite3_pcache_methods2 ** object. This object specifies the interface to a custom page cache ** implementation. */ sqlite3GlobalConfig.pcache2 = *va_arg(ap, sqlite3_pcache_methods2*); break; } case SQLITE_CONFIG_GETPCACHE2: { /* EVIDENCE-OF: R-22035-46182 The SQLITE_CONFIG_GETPCACHE2 option takes a ** single argument which is a pointer to an sqlite3_pcache_methods2 ** object. SQLite copies of the current page cache implementation into ** that object. */ if( sqlite3GlobalConfig.pcache2.xInit==0 ){ sqlite3PCacheSetDefault(); } *va_arg(ap, sqlite3_pcache_methods2*) = sqlite3GlobalConfig.pcache2; break; } /* EVIDENCE-OF: R-06626-12911 The SQLITE_CONFIG_HEAP option is only ** available if SQLite is compiled with either SQLITE_ENABLE_MEMSYS3 or ** SQLITE_ENABLE_MEMSYS5 and returns SQLITE_ERROR if invoked otherwise. */ #if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5) case SQLITE_CONFIG_HEAP: { /* EVIDENCE-OF: R-19854-42126 There are three arguments to ** SQLITE_CONFIG_HEAP: An 8-byte aligned pointer to the memory, the ** number of bytes in the memory buffer, and the minimum allocation size. */ sqlite3GlobalConfig.pHeap = va_arg(ap, void*); sqlite3GlobalConfig.nHeap = va_arg(ap, int); sqlite3GlobalConfig.mnReq = va_arg(ap, int); if( sqlite3GlobalConfig.mnReq<1 ){ sqlite3GlobalConfig.mnReq = 1; }else if( sqlite3GlobalConfig.mnReq>(1<<12) ){ /* cap min request size at 2^12 */ sqlite3GlobalConfig.mnReq = (1<<12); } if( sqlite3GlobalConfig.pHeap==0 ){ /* EVIDENCE-OF: R-49920-60189 If the first pointer (the memory pointer) ** is NULL, then SQLite reverts to using its default memory allocator ** (the system malloc() implementation), undoing any prior invocation of ** SQLITE_CONFIG_MALLOC. ** ** Setting sqlite3GlobalConfig.m to all zeros will cause malloc to ** revert to its default implementation when sqlite3_initialize() is run */ memset(&sqlite3GlobalConfig.m, 0, sizeof(sqlite3GlobalConfig.m)); }else{ /* EVIDENCE-OF: R-61006-08918 If the memory pointer is not NULL then the ** alternative memory allocator is engaged to handle all of SQLites ** memory allocation needs. */ #ifdef SQLITE_ENABLE_MEMSYS3 sqlite3GlobalConfig.m = *sqlite3MemGetMemsys3(); #endif #ifdef SQLITE_ENABLE_MEMSYS5 sqlite3GlobalConfig.m = *sqlite3MemGetMemsys5(); #endif } break; } #endif case SQLITE_CONFIG_LOOKASIDE: { sqlite3GlobalConfig.szLookaside = va_arg(ap, int); sqlite3GlobalConfig.nLookaside = va_arg(ap, int); break; } /* Record a pointer to the logger function and its first argument. ** The default is NULL. Logging is disabled if the function pointer is ** NULL. */ case SQLITE_CONFIG_LOG: { /* MSVC is picky about pulling func ptrs from va lists. ** http://support.microsoft.com/kb/47961 ** sqlite3GlobalConfig.xLog = va_arg(ap, void(*)(void*,int,const char*)); */ typedef void(*LOGFUNC_t)(void*,int,const char*); sqlite3GlobalConfig.xLog = va_arg(ap, LOGFUNC_t); sqlite3GlobalConfig.pLogArg = va_arg(ap, void*); break; } /* EVIDENCE-OF: R-55548-33817 The compile-time setting for URI filenames ** can be changed at start-time using the ** sqlite3_config(SQLITE_CONFIG_URI,1) or ** sqlite3_config(SQLITE_CONFIG_URI,0) configuration calls. */ case SQLITE_CONFIG_URI: { /* EVIDENCE-OF: R-25451-61125 The SQLITE_CONFIG_URI option takes a single ** argument of type int. If non-zero, then URI handling is globally ** enabled. If the parameter is zero, then URI handling is globally ** disabled. */ sqlite3GlobalConfig.bOpenUri = va_arg(ap, int); break; } case SQLITE_CONFIG_COVERING_INDEX_SCAN: { /* EVIDENCE-OF: R-36592-02772 The SQLITE_CONFIG_COVERING_INDEX_SCAN ** option takes a single integer argument which is interpreted as a ** boolean in order to enable or disable the use of covering indices for ** full table scans in the query optimizer. */ sqlite3GlobalConfig.bUseCis = va_arg(ap, int); break; } #ifdef SQLITE_ENABLE_SQLLOG case SQLITE_CONFIG_SQLLOG: { typedef void(*SQLLOGFUNC_t)(void*, sqlite3*, const char*, int); sqlite3GlobalConfig.xSqllog = va_arg(ap, SQLLOGFUNC_t); sqlite3GlobalConfig.pSqllogArg = va_arg(ap, void *); break; } #endif case SQLITE_CONFIG_MMAP_SIZE: { /* EVIDENCE-OF: R-58063-38258 SQLITE_CONFIG_MMAP_SIZE takes two 64-bit ** integer (sqlite3_int64) values that are the default mmap size limit ** (the default setting for PRAGMA mmap_size) and the maximum allowed ** mmap size limit. */ sqlite3_int64 szMmap = va_arg(ap, sqlite3_int64); sqlite3_int64 mxMmap = va_arg(ap, sqlite3_int64); /* EVIDENCE-OF: R-53367-43190 If either argument to this option is ** negative, then that argument is changed to its compile-time default. ** ** EVIDENCE-OF: R-34993-45031 The maximum allowed mmap size will be ** silently truncated if necessary so that it does not exceed the ** compile-time maximum mmap size set by the SQLITE_MAX_MMAP_SIZE ** compile-time option. */ if( mxMmap<0 || mxMmap>SQLITE_MAX_MMAP_SIZE ){ mxMmap = SQLITE_MAX_MMAP_SIZE; } if( szMmap<0 ) szMmap = SQLITE_DEFAULT_MMAP_SIZE; if( szMmap>mxMmap) szMmap = mxMmap; sqlite3GlobalConfig.mxMmap = mxMmap; sqlite3GlobalConfig.szMmap = szMmap; break; } #if SQLITE_OS_WIN && defined(SQLITE_WIN32_MALLOC) /* IMP: R-04780-55815 */ case SQLITE_CONFIG_WIN32_HEAPSIZE: { /* EVIDENCE-OF: R-34926-03360 SQLITE_CONFIG_WIN32_HEAPSIZE takes a 32-bit ** unsigned integer value that specifies the maximum size of the created ** heap. */ sqlite3GlobalConfig.nHeap = va_arg(ap, int); break; } #endif case SQLITE_CONFIG_PMASZ: { sqlite3GlobalConfig.szPma = va_arg(ap, unsigned int); break; } case SQLITE_CONFIG_STMTJRNL_SPILL: { sqlite3GlobalConfig.nStmtSpill = va_arg(ap, int); break; } default: { rc = SQLITE_ERROR; break; } } va_end(ap); return rc; } /* ** Set up the lookaside buffers for a database connection. ** Return SQLITE_OK on success. ** If lookaside is already active, return SQLITE_BUSY. ** ** The sz parameter is the number of bytes in each lookaside slot. ** The cnt parameter is the number of slots. If pStart is NULL the ** space for the lookaside memory is obtained from sqlite3_malloc(). ** If pStart is not NULL then it is sz*cnt bytes of memory to use for ** the lookaside memory. */ static int setupLookaside(sqlite3 *db, void *pBuf, int sz, int cnt){ #ifndef SQLITE_OMIT_LOOKASIDE void *pStart; if( db->lookaside.nOut ){ return SQLITE_BUSY; } /* Free any existing lookaside buffer for this handle before ** allocating a new one so we don't have to have space for ** both at the same time. */ if( db->lookaside.bMalloced ){ sqlite3_free(db->lookaside.pStart); } /* The size of a lookaside slot after ROUNDDOWN8 needs to be larger ** than a pointer to be useful. */ sz = ROUNDDOWN8(sz); /* IMP: R-33038-09382 */ if( sz<=(int)sizeof(LookasideSlot*) ) sz = 0; if( cnt<0 ) cnt = 0; if( sz==0 || cnt==0 ){ sz = 0; pStart = 0; }else if( pBuf==0 ){ sqlite3BeginBenignMalloc(); pStart = sqlite3Malloc( sz*cnt ); /* IMP: R-61949-35727 */ sqlite3EndBenignMalloc(); if( pStart ) cnt = sqlite3MallocSize(pStart)/sz; }else{ pStart = pBuf; } db->lookaside.pStart = pStart; db->lookaside.pFree = 0; db->lookaside.sz = (u16)sz; if( pStart ){ int i; LookasideSlot *p; assert( sz > (int)sizeof(LookasideSlot*) ); p = (LookasideSlot*)pStart; for(i=cnt-1; i>=0; i--){ p->pNext = db->lookaside.pFree; db->lookaside.pFree = p; p = (LookasideSlot*)&((u8*)p)[sz]; } db->lookaside.pEnd = p; db->lookaside.bDisable = 0; db->lookaside.bMalloced = pBuf==0 ?1:0; }else{ db->lookaside.pStart = db; db->lookaside.pEnd = db; db->lookaside.bDisable = 1; db->lookaside.bMalloced = 0; } #endif /* SQLITE_OMIT_LOOKASIDE */ return SQLITE_OK; } /* ** Return the mutex associated with a database connection. */ SQLITE_API sqlite3_mutex *sqlite3_db_mutex(sqlite3 *db){ #ifdef SQLITE_ENABLE_API_ARMOR if( !sqlite3SafetyCheckOk(db) ){ (void)SQLITE_MISUSE_BKPT; return 0; } #endif return db->mutex; } /* ** Free up as much memory as we can from the given database ** connection. */ SQLITE_API int sqlite3_db_release_memory(sqlite3 *db){ int i; #ifdef SQLITE_ENABLE_API_ARMOR if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT; #endif sqlite3_mutex_enter(db->mutex); sqlite3BtreeEnterAll(db); for(i=0; inDb; i++){ Btree *pBt = db->aDb[i].pBt; if( pBt ){ Pager *pPager = sqlite3BtreePager(pBt); sqlite3PagerShrink(pPager); } } sqlite3BtreeLeaveAll(db); sqlite3_mutex_leave(db->mutex); return SQLITE_OK; } /* ** Flush any dirty pages in the pager-cache for any attached database ** to disk. */ SQLITE_API int sqlite3_db_cacheflush(sqlite3 *db){ int i; int rc = SQLITE_OK; int bSeenBusy = 0; #ifdef SQLITE_ENABLE_API_ARMOR if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT; #endif sqlite3_mutex_enter(db->mutex); sqlite3BtreeEnterAll(db); for(i=0; rc==SQLITE_OK && inDb; i++){ Btree *pBt = db->aDb[i].pBt; if( pBt && sqlite3BtreeIsInTrans(pBt) ){ Pager *pPager = sqlite3BtreePager(pBt); rc = sqlite3PagerFlush(pPager); if( rc==SQLITE_BUSY ){ bSeenBusy = 1; rc = SQLITE_OK; } } } sqlite3BtreeLeaveAll(db); sqlite3_mutex_leave(db->mutex); return ((rc==SQLITE_OK && bSeenBusy) ? SQLITE_BUSY : rc); } /* ** Configuration settings for an individual database connection */ SQLITE_API int sqlite3_db_config(sqlite3 *db, int op, ...){ va_list ap; int rc; va_start(ap, op); switch( op ){ case SQLITE_DBCONFIG_MAINDBNAME: { db->aDb[0].zDbSName = va_arg(ap,char*); rc = SQLITE_OK; break; } case SQLITE_DBCONFIG_LOOKASIDE: { void *pBuf = va_arg(ap, void*); /* IMP: R-26835-10964 */ int sz = va_arg(ap, int); /* IMP: R-47871-25994 */ int cnt = va_arg(ap, int); /* IMP: R-04460-53386 */ rc = setupLookaside(db, pBuf, sz, cnt); break; } default: { static const struct { int op; /* The opcode */ u32 mask; /* Mask of the bit in sqlite3.flags to set/clear */ } aFlagOp[] = { { SQLITE_DBCONFIG_ENABLE_FKEY, SQLITE_ForeignKeys }, { SQLITE_DBCONFIG_ENABLE_TRIGGER, SQLITE_EnableTrigger }, { SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER, SQLITE_Fts3Tokenizer }, { SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION, SQLITE_LoadExtension }, }; unsigned int i; rc = SQLITE_ERROR; /* IMP: R-42790-23372 */ for(i=0; iflags; if( onoff>0 ){ db->flags |= aFlagOp[i].mask; }else if( onoff==0 ){ db->flags &= ~aFlagOp[i].mask; } if( oldFlags!=db->flags ){ sqlite3ExpirePreparedStatements(db); } if( pRes ){ *pRes = (db->flags & aFlagOp[i].mask)!=0; } rc = SQLITE_OK; break; } } break; } } va_end(ap); return rc; } /* ** Return true if the buffer z[0..n-1] contains all spaces. */ static int allSpaces(const char *z, int n){ while( n>0 && z[n-1]==' ' ){ n--; } return n==0; } /* ** This is the default collating function named "BINARY" which is always ** available. ** ** If the padFlag argument is not NULL then space padding at the end ** of strings is ignored. This implements the RTRIM collation. */ static int binCollFunc( void *padFlag, int nKey1, const void *pKey1, int nKey2, const void *pKey2 ){ int rc, n; n = nKey1lastRowid; } /* ** Return the number of changes in the most recent call to sqlite3_exec(). */ SQLITE_API int sqlite3_changes(sqlite3 *db){ #ifdef SQLITE_ENABLE_API_ARMOR if( !sqlite3SafetyCheckOk(db) ){ (void)SQLITE_MISUSE_BKPT; return 0; } #endif return db->nChange; } /* ** Return the number of changes since the database handle was opened. */ SQLITE_API int sqlite3_total_changes(sqlite3 *db){ #ifdef SQLITE_ENABLE_API_ARMOR if( !sqlite3SafetyCheckOk(db) ){ (void)SQLITE_MISUSE_BKPT; return 0; } #endif return db->nTotalChange; } /* ** Close all open savepoints. This function only manipulates fields of the ** database handle object, it does not close any savepoints that may be open ** at the b-tree/pager level. */ SQLITE_PRIVATE void sqlite3CloseSavepoints(sqlite3 *db){ while( db->pSavepoint ){ Savepoint *pTmp = db->pSavepoint; db->pSavepoint = pTmp->pNext; sqlite3DbFree(db, pTmp); } db->nSavepoint = 0; db->nStatement = 0; db->isTransactionSavepoint = 0; } /* ** Invoke the destructor function associated with FuncDef p, if any. Except, ** if this is not the last copy of the function, do not invoke it. Multiple ** copies of a single function are created when create_function() is called ** with SQLITE_ANY as the encoding. */ static void functionDestroy(sqlite3 *db, FuncDef *p){ FuncDestructor *pDestructor = p->u.pDestructor; if( pDestructor ){ pDestructor->nRef--; if( pDestructor->nRef==0 ){ pDestructor->xDestroy(pDestructor->pUserData); sqlite3DbFree(db, pDestructor); } } } /* ** Disconnect all sqlite3_vtab objects that belong to database connection ** db. This is called when db is being closed. */ static void disconnectAllVtab(sqlite3 *db){ #ifndef SQLITE_OMIT_VIRTUALTABLE int i; HashElem *p; sqlite3BtreeEnterAll(db); for(i=0; inDb; i++){ Schema *pSchema = db->aDb[i].pSchema; if( db->aDb[i].pSchema ){ for(p=sqliteHashFirst(&pSchema->tblHash); p; p=sqliteHashNext(p)){ Table *pTab = (Table *)sqliteHashData(p); if( IsVirtual(pTab) ) sqlite3VtabDisconnect(db, pTab); } } } for(p=sqliteHashFirst(&db->aModule); p; p=sqliteHashNext(p)){ Module *pMod = (Module *)sqliteHashData(p); if( pMod->pEpoTab ){ sqlite3VtabDisconnect(db, pMod->pEpoTab); } } sqlite3VtabUnlockList(db); sqlite3BtreeLeaveAll(db); #else UNUSED_PARAMETER(db); #endif } /* ** Return TRUE if database connection db has unfinalized prepared ** statements or unfinished sqlite3_backup objects. */ static int connectionIsBusy(sqlite3 *db){ int j; assert( sqlite3_mutex_held(db->mutex) ); if( db->pVdbe ) return 1; for(j=0; jnDb; j++){ Btree *pBt = db->aDb[j].pBt; if( pBt && sqlite3BtreeIsInBackup(pBt) ) return 1; } return 0; } /* ** Close an existing SQLite database */ static int sqlite3Close(sqlite3 *db, int forceZombie){ if( !db ){ /* EVIDENCE-OF: R-63257-11740 Calling sqlite3_close() or ** sqlite3_close_v2() with a NULL pointer argument is a harmless no-op. */ return SQLITE_OK; } if( !sqlite3SafetyCheckSickOrOk(db) ){ return SQLITE_MISUSE_BKPT; } sqlite3_mutex_enter(db->mutex); if( db->mTrace & SQLITE_TRACE_CLOSE ){ db->xTrace(SQLITE_TRACE_CLOSE, db->pTraceArg, db, 0); } /* Force xDisconnect calls on all virtual tables */ disconnectAllVtab(db); /* If a transaction is open, the disconnectAllVtab() call above ** will not have called the xDisconnect() method on any virtual ** tables in the db->aVTrans[] array. The following sqlite3VtabRollback() ** call will do so. We need to do this before the check for active ** SQL statements below, as the v-table implementation may be storing ** some prepared statements internally. */ sqlite3VtabRollback(db); /* Legacy behavior (sqlite3_close() behavior) is to return ** SQLITE_BUSY if the connection can not be closed immediately. */ if( !forceZombie && connectionIsBusy(db) ){ sqlite3ErrorWithMsg(db, SQLITE_BUSY, "unable to close due to unfinalized " "statements or unfinished backups"); sqlite3_mutex_leave(db->mutex); return SQLITE_BUSY; } #ifdef SQLITE_ENABLE_SQLLOG if( sqlite3GlobalConfig.xSqllog ){ /* Closing the handle. Fourth parameter is passed the value 2. */ sqlite3GlobalConfig.xSqllog(sqlite3GlobalConfig.pSqllogArg, db, 0, 2); } #endif /* Convert the connection into a zombie and then close it. */ db->magic = SQLITE_MAGIC_ZOMBIE; sqlite3LeaveMutexAndCloseZombie(db); return SQLITE_OK; } /* ** Two variations on the public interface for closing a database ** connection. The sqlite3_close() version returns SQLITE_BUSY and ** leaves the connection option if there are unfinalized prepared ** statements or unfinished sqlite3_backups. The sqlite3_close_v2() ** version forces the connection to become a zombie if there are ** unclosed resources, and arranges for deallocation when the last ** prepare statement or sqlite3_backup closes. */ SQLITE_API int sqlite3_close(sqlite3 *db){ return sqlite3Close(db,0); } SQLITE_API int sqlite3_close_v2(sqlite3 *db){ return sqlite3Close(db,1); } /* ** Close the mutex on database connection db. ** ** Furthermore, if database connection db is a zombie (meaning that there ** has been a prior call to sqlite3_close(db) or sqlite3_close_v2(db)) and ** every sqlite3_stmt has now been finalized and every sqlite3_backup has ** finished, then free all resources. */ SQLITE_PRIVATE void sqlite3LeaveMutexAndCloseZombie(sqlite3 *db){ HashElem *i; /* Hash table iterator */ int j; /* If there are outstanding sqlite3_stmt or sqlite3_backup objects ** or if the connection has not yet been closed by sqlite3_close_v2(), ** then just leave the mutex and return. */ if( db->magic!=SQLITE_MAGIC_ZOMBIE || connectionIsBusy(db) ){ sqlite3_mutex_leave(db->mutex); return; } /* If we reach this point, it means that the database connection has ** closed all sqlite3_stmt and sqlite3_backup objects and has been ** passed to sqlite3_close (meaning that it is a zombie). Therefore, ** go ahead and free all resources. */ /* If a transaction is open, roll it back. This also ensures that if ** any database schemas have been modified by an uncommitted transaction ** they are reset. And that the required b-tree mutex is held to make ** the pager rollback and schema reset an atomic operation. */ sqlite3RollbackAll(db, SQLITE_OK); /* Free any outstanding Savepoint structures. */ sqlite3CloseSavepoints(db); /* Close all database connections */ for(j=0; jnDb; j++){ struct Db *pDb = &db->aDb[j]; if( pDb->pBt ){ sqlite3BtreeClose(pDb->pBt); pDb->pBt = 0; if( j!=1 ){ pDb->pSchema = 0; } } } /* Clear the TEMP schema separately and last */ if( db->aDb[1].pSchema ){ sqlite3SchemaClear(db->aDb[1].pSchema); } sqlite3VtabUnlockList(db); /* Free up the array of auxiliary databases */ sqlite3CollapseDatabaseArray(db); assert( db->nDb<=2 ); assert( db->aDb==db->aDbStatic ); /* Tell the code in notify.c that the connection no longer holds any ** locks and does not require any further unlock-notify callbacks. */ sqlite3ConnectionClosed(db); for(i=sqliteHashFirst(&db->aFunc); i; i=sqliteHashNext(i)){ FuncDef *pNext, *p; p = sqliteHashData(i); do{ functionDestroy(db, p); pNext = p->pNext; sqlite3DbFree(db, p); p = pNext; }while( p ); } sqlite3HashClear(&db->aFunc); for(i=sqliteHashFirst(&db->aCollSeq); i; i=sqliteHashNext(i)){ CollSeq *pColl = (CollSeq *)sqliteHashData(i); /* Invoke any destructors registered for collation sequence user data. */ for(j=0; j<3; j++){ if( pColl[j].xDel ){ pColl[j].xDel(pColl[j].pUser); } } sqlite3DbFree(db, pColl); } sqlite3HashClear(&db->aCollSeq); #ifndef SQLITE_OMIT_VIRTUALTABLE for(i=sqliteHashFirst(&db->aModule); i; i=sqliteHashNext(i)){ Module *pMod = (Module *)sqliteHashData(i); if( pMod->xDestroy ){ pMod->xDestroy(pMod->pAux); } sqlite3VtabEponymousTableClear(db, pMod); sqlite3DbFree(db, pMod); } sqlite3HashClear(&db->aModule); #endif sqlite3Error(db, SQLITE_OK); /* Deallocates any cached error strings. */ sqlite3ValueFree(db->pErr); sqlite3CloseExtensions(db); #if SQLITE_USER_AUTHENTICATION sqlite3_free(db->auth.zAuthUser); sqlite3_free(db->auth.zAuthPW); #endif db->magic = SQLITE_MAGIC_ERROR; /* The temp-database schema is allocated differently from the other schema ** objects (using sqliteMalloc() directly, instead of sqlite3BtreeSchema()). ** So it needs to be freed here. Todo: Why not roll the temp schema into ** the same sqliteMalloc() as the one that allocates the database ** structure? */ sqlite3DbFree(db, db->aDb[1].pSchema); sqlite3_mutex_leave(db->mutex); db->magic = SQLITE_MAGIC_CLOSED; sqlite3_mutex_free(db->mutex); assert( db->lookaside.nOut==0 ); /* Fails on a lookaside memory leak */ if( db->lookaside.bMalloced ){ sqlite3_free(db->lookaside.pStart); } sqlite3_free(db); } /* ** Rollback all database files. If tripCode is not SQLITE_OK, then ** any write cursors are invalidated ("tripped" - as in "tripping a circuit ** breaker") and made to return tripCode if there are any further ** attempts to use that cursor. Read cursors remain open and valid ** but are "saved" in case the table pages are moved around. */ SQLITE_PRIVATE void sqlite3RollbackAll(sqlite3 *db, int tripCode){ int i; int inTrans = 0; int schemaChange; assert( sqlite3_mutex_held(db->mutex) ); sqlite3BeginBenignMalloc(); /* Obtain all b-tree mutexes before making any calls to BtreeRollback(). ** This is important in case the transaction being rolled back has ** modified the database schema. If the b-tree mutexes are not taken ** here, then another shared-cache connection might sneak in between ** the database rollback and schema reset, which can cause false ** corruption reports in some cases. */ sqlite3BtreeEnterAll(db); schemaChange = (db->flags & SQLITE_InternChanges)!=0 && db->init.busy==0; for(i=0; inDb; i++){ Btree *p = db->aDb[i].pBt; if( p ){ if( sqlite3BtreeIsInTrans(p) ){ inTrans = 1; } sqlite3BtreeRollback(p, tripCode, !schemaChange); } } sqlite3VtabRollback(db); sqlite3EndBenignMalloc(); if( (db->flags&SQLITE_InternChanges)!=0 && db->init.busy==0 ){ sqlite3ExpirePreparedStatements(db); sqlite3ResetAllSchemasOfConnection(db); } sqlite3BtreeLeaveAll(db); /* Any deferred constraint violations have now been resolved. */ db->nDeferredCons = 0; db->nDeferredImmCons = 0; db->flags &= ~SQLITE_DeferFKs; /* If one has been configured, invoke the rollback-hook callback */ if( db->xRollbackCallback && (inTrans || !db->autoCommit) ){ db->xRollbackCallback(db->pRollbackArg); } } /* ** Return a static string containing the name corresponding to the error code ** specified in the argument. */ #if defined(SQLITE_NEED_ERR_NAME) SQLITE_PRIVATE const char *sqlite3ErrName(int rc){ const char *zName = 0; int i, origRc = rc; for(i=0; i<2 && zName==0; i++, rc &= 0xff){ switch( rc ){ case SQLITE_OK: zName = "SQLITE_OK"; break; case SQLITE_ERROR: zName = "SQLITE_ERROR"; break; case SQLITE_INTERNAL: zName = "SQLITE_INTERNAL"; break; case SQLITE_PERM: zName = "SQLITE_PERM"; break; case SQLITE_ABORT: zName = "SQLITE_ABORT"; break; case SQLITE_ABORT_ROLLBACK: zName = "SQLITE_ABORT_ROLLBACK"; break; case SQLITE_BUSY: zName = "SQLITE_BUSY"; break; case SQLITE_BUSY_RECOVERY: zName = "SQLITE_BUSY_RECOVERY"; break; case SQLITE_BUSY_SNAPSHOT: zName = "SQLITE_BUSY_SNAPSHOT"; break; case SQLITE_LOCKED: zName = "SQLITE_LOCKED"; break; case SQLITE_LOCKED_SHAREDCACHE: zName = "SQLITE_LOCKED_SHAREDCACHE";break; case SQLITE_NOMEM: zName = "SQLITE_NOMEM"; break; case SQLITE_READONLY: zName = "SQLITE_READONLY"; break; case SQLITE_READONLY_RECOVERY: zName = "SQLITE_READONLY_RECOVERY"; break; case SQLITE_READONLY_CANTLOCK: zName = "SQLITE_READONLY_CANTLOCK"; break; case SQLITE_READONLY_ROLLBACK: zName = "SQLITE_READONLY_ROLLBACK"; break; case SQLITE_READONLY_DBMOVED: zName = "SQLITE_READONLY_DBMOVED"; break; case SQLITE_INTERRUPT: zName = "SQLITE_INTERRUPT"; break; case SQLITE_IOERR: zName = "SQLITE_IOERR"; break; case SQLITE_IOERR_READ: zName = "SQLITE_IOERR_READ"; break; case SQLITE_IOERR_SHORT_READ: zName = "SQLITE_IOERR_SHORT_READ"; break; case SQLITE_IOERR_WRITE: zName = "SQLITE_IOERR_WRITE"; break; case SQLITE_IOERR_FSYNC: zName = "SQLITE_IOERR_FSYNC"; break; case SQLITE_IOERR_DIR_FSYNC: zName = "SQLITE_IOERR_DIR_FSYNC"; break; case SQLITE_IOERR_TRUNCATE: zName = "SQLITE_IOERR_TRUNCATE"; break; case SQLITE_IOERR_FSTAT: zName = "SQLITE_IOERR_FSTAT"; break; case SQLITE_IOERR_UNLOCK: zName = "SQLITE_IOERR_UNLOCK"; break; case SQLITE_IOERR_RDLOCK: zName = "SQLITE_IOERR_RDLOCK"; break; case SQLITE_IOERR_DELETE: zName = "SQLITE_IOERR_DELETE"; break; case SQLITE_IOERR_NOMEM: zName = "SQLITE_IOERR_NOMEM"; break; case SQLITE_IOERR_ACCESS: zName = "SQLITE_IOERR_ACCESS"; break; case SQLITE_IOERR_CHECKRESERVEDLOCK: zName = "SQLITE_IOERR_CHECKRESERVEDLOCK"; break; case SQLITE_IOERR_LOCK: zName = "SQLITE_IOERR_LOCK"; break; case SQLITE_IOERR_CLOSE: zName = "SQLITE_IOERR_CLOSE"; break; case SQLITE_IOERR_DIR_CLOSE: zName = "SQLITE_IOERR_DIR_CLOSE"; break; case SQLITE_IOERR_SHMOPEN: zName = "SQLITE_IOERR_SHMOPEN"; break; case SQLITE_IOERR_SHMSIZE: zName = "SQLITE_IOERR_SHMSIZE"; break; case SQLITE_IOERR_SHMLOCK: zName = "SQLITE_IOERR_SHMLOCK"; break; case SQLITE_IOERR_SHMMAP: zName = "SQLITE_IOERR_SHMMAP"; break; case SQLITE_IOERR_SEEK: zName = "SQLITE_IOERR_SEEK"; break; case SQLITE_IOERR_DELETE_NOENT: zName = "SQLITE_IOERR_DELETE_NOENT";break; case SQLITE_IOERR_MMAP: zName = "SQLITE_IOERR_MMAP"; break; case SQLITE_IOERR_GETTEMPPATH: zName = "SQLITE_IOERR_GETTEMPPATH"; break; case SQLITE_IOERR_CONVPATH: zName = "SQLITE_IOERR_CONVPATH"; break; case SQLITE_CORRUPT: zName = "SQLITE_CORRUPT"; break; case SQLITE_CORRUPT_VTAB: zName = "SQLITE_CORRUPT_VTAB"; break; case SQLITE_NOTFOUND: zName = "SQLITE_NOTFOUND"; break; case SQLITE_FULL: zName = "SQLITE_FULL"; break; case SQLITE_CANTOPEN: zName = "SQLITE_CANTOPEN"; break; case SQLITE_CANTOPEN_NOTEMPDIR: zName = "SQLITE_CANTOPEN_NOTEMPDIR";break; case SQLITE_CANTOPEN_ISDIR: zName = "SQLITE_CANTOPEN_ISDIR"; break; case SQLITE_CANTOPEN_FULLPATH: zName = "SQLITE_CANTOPEN_FULLPATH"; break; case SQLITE_CANTOPEN_CONVPATH: zName = "SQLITE_CANTOPEN_CONVPATH"; break; case SQLITE_PROTOCOL: zName = "SQLITE_PROTOCOL"; break; case SQLITE_EMPTY: zName = "SQLITE_EMPTY"; break; case SQLITE_SCHEMA: zName = "SQLITE_SCHEMA"; break; case SQLITE_TOOBIG: zName = "SQLITE_TOOBIG"; break; case SQLITE_CONSTRAINT: zName = "SQLITE_CONSTRAINT"; break; case SQLITE_CONSTRAINT_UNIQUE: zName = "SQLITE_CONSTRAINT_UNIQUE"; break; case SQLITE_CONSTRAINT_TRIGGER: zName = "SQLITE_CONSTRAINT_TRIGGER";break; case SQLITE_CONSTRAINT_FOREIGNKEY: zName = "SQLITE_CONSTRAINT_FOREIGNKEY"; break; case SQLITE_CONSTRAINT_CHECK: zName = "SQLITE_CONSTRAINT_CHECK"; break; case SQLITE_CONSTRAINT_PRIMARYKEY: zName = "SQLITE_CONSTRAINT_PRIMARYKEY"; break; case SQLITE_CONSTRAINT_NOTNULL: zName = "SQLITE_CONSTRAINT_NOTNULL";break; case SQLITE_CONSTRAINT_COMMITHOOK: zName = "SQLITE_CONSTRAINT_COMMITHOOK"; break; case SQLITE_CONSTRAINT_VTAB: zName = "SQLITE_CONSTRAINT_VTAB"; break; case SQLITE_CONSTRAINT_FUNCTION: zName = "SQLITE_CONSTRAINT_FUNCTION"; break; case SQLITE_CONSTRAINT_ROWID: zName = "SQLITE_CONSTRAINT_ROWID"; break; case SQLITE_MISMATCH: zName = "SQLITE_MISMATCH"; break; case SQLITE_MISUSE: zName = "SQLITE_MISUSE"; break; case SQLITE_NOLFS: zName = "SQLITE_NOLFS"; break; case SQLITE_AUTH: zName = "SQLITE_AUTH"; break; case SQLITE_FORMAT: zName = "SQLITE_FORMAT"; break; case SQLITE_RANGE: zName = "SQLITE_RANGE"; break; case SQLITE_NOTADB: zName = "SQLITE_NOTADB"; break; case SQLITE_ROW: zName = "SQLITE_ROW"; break; case SQLITE_NOTICE: zName = "SQLITE_NOTICE"; break; case SQLITE_NOTICE_RECOVER_WAL: zName = "SQLITE_NOTICE_RECOVER_WAL";break; case SQLITE_NOTICE_RECOVER_ROLLBACK: zName = "SQLITE_NOTICE_RECOVER_ROLLBACK"; break; case SQLITE_WARNING: zName = "SQLITE_WARNING"; break; case SQLITE_WARNING_AUTOINDEX: zName = "SQLITE_WARNING_AUTOINDEX"; break; case SQLITE_DONE: zName = "SQLITE_DONE"; break; } } if( zName==0 ){ static char zBuf[50]; sqlite3_snprintf(sizeof(zBuf), zBuf, "SQLITE_UNKNOWN(%d)", origRc); zName = zBuf; } return zName; } #endif /* ** Return a static string that describes the kind of error specified in the ** argument. */ SQLITE_PRIVATE const char *sqlite3ErrStr(int rc){ static const char* const aMsg[] = { /* SQLITE_OK */ "not an error", /* SQLITE_ERROR */ "SQL logic error or missing database", /* SQLITE_INTERNAL */ 0, /* SQLITE_PERM */ "access permission denied", /* SQLITE_ABORT */ "callback requested query abort", /* SQLITE_BUSY */ "database is locked", /* SQLITE_LOCKED */ "database table is locked", /* SQLITE_NOMEM */ "out of memory", /* SQLITE_READONLY */ "attempt to write a readonly database", /* SQLITE_INTERRUPT */ "interrupted", /* SQLITE_IOERR */ "disk I/O error", /* SQLITE_CORRUPT */ "database disk image is malformed", /* SQLITE_NOTFOUND */ "unknown operation", /* SQLITE_FULL */ "database or disk is full", /* SQLITE_CANTOPEN */ "unable to open database file", /* SQLITE_PROTOCOL */ "locking protocol", /* SQLITE_EMPTY */ "table contains no data", /* SQLITE_SCHEMA */ "database schema has changed", /* SQLITE_TOOBIG */ "string or blob too big", /* SQLITE_CONSTRAINT */ "constraint failed", /* SQLITE_MISMATCH */ "datatype mismatch", /* SQLITE_MISUSE */ "library routine called out of sequence", /* SQLITE_NOLFS */ "large file support is disabled", /* SQLITE_AUTH */ "authorization denied", /* SQLITE_FORMAT */ "auxiliary database format error", /* SQLITE_RANGE */ "bind or column index out of range", /* SQLITE_NOTADB */ "file is encrypted or is not a database", }; const char *zErr = "unknown error"; switch( rc ){ case SQLITE_ABORT_ROLLBACK: { zErr = "abort due to ROLLBACK"; break; } default: { rc &= 0xff; if( ALWAYS(rc>=0) && rcbusyTimeout; int delay, prior; assert( count>=0 ); if( count < NDELAY ){ delay = delays[count]; prior = totals[count]; }else{ delay = delays[NDELAY-1]; prior = totals[NDELAY-1] + delay*(count-(NDELAY-1)); } if( prior + delay > timeout ){ delay = timeout - prior; if( delay<=0 ) return 0; } sqlite3OsSleep(db->pVfs, delay*1000); return 1; #else sqlite3 *db = (sqlite3 *)ptr; int timeout = ((sqlite3 *)ptr)->busyTimeout; if( (count+1)*1000 > timeout ){ return 0; } sqlite3OsSleep(db->pVfs, 1000000); return 1; #endif } /* ** Invoke the given busy handler. ** ** This routine is called when an operation failed with a lock. ** If this routine returns non-zero, the lock is retried. If it ** returns 0, the operation aborts with an SQLITE_BUSY error. */ SQLITE_PRIVATE int sqlite3InvokeBusyHandler(BusyHandler *p){ int rc; if( NEVER(p==0) || p->xFunc==0 || p->nBusy<0 ) return 0; rc = p->xFunc(p->pArg, p->nBusy); if( rc==0 ){ p->nBusy = -1; }else{ p->nBusy++; } return rc; } /* ** This routine sets the busy callback for an Sqlite database to the ** given callback function with the given argument. */ SQLITE_API int sqlite3_busy_handler( sqlite3 *db, int (*xBusy)(void*,int), void *pArg ){ #ifdef SQLITE_ENABLE_API_ARMOR if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT; #endif sqlite3_mutex_enter(db->mutex); db->busyHandler.xFunc = xBusy; db->busyHandler.pArg = pArg; db->busyHandler.nBusy = 0; db->busyTimeout = 0; sqlite3_mutex_leave(db->mutex); return SQLITE_OK; } #ifndef SQLITE_OMIT_PROGRESS_CALLBACK /* ** This routine sets the progress callback for an Sqlite database to the ** given callback function with the given argument. The progress callback will ** be invoked every nOps opcodes. */ SQLITE_API void sqlite3_progress_handler( sqlite3 *db, int nOps, int (*xProgress)(void*), void *pArg ){ #ifdef SQLITE_ENABLE_API_ARMOR if( !sqlite3SafetyCheckOk(db) ){ (void)SQLITE_MISUSE_BKPT; return; } #endif sqlite3_mutex_enter(db->mutex); if( nOps>0 ){ db->xProgress = xProgress; db->nProgressOps = (unsigned)nOps; db->pProgressArg = pArg; }else{ db->xProgress = 0; db->nProgressOps = 0; db->pProgressArg = 0; } sqlite3_mutex_leave(db->mutex); } #endif /* ** This routine installs a default busy handler that waits for the ** specified number of milliseconds before returning 0. */ SQLITE_API int sqlite3_busy_timeout(sqlite3 *db, int ms){ #ifdef SQLITE_ENABLE_API_ARMOR if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT; #endif if( ms>0 ){ sqlite3_busy_handler(db, sqliteDefaultBusyCallback, (void*)db); db->busyTimeout = ms; }else{ sqlite3_busy_handler(db, 0, 0); } return SQLITE_OK; } /* ** Cause any pending operation to stop at its earliest opportunity. */ SQLITE_API void sqlite3_interrupt(sqlite3 *db){ #ifdef SQLITE_ENABLE_API_ARMOR if( !sqlite3SafetyCheckOk(db) ){ (void)SQLITE_MISUSE_BKPT; return; } #endif db->u1.isInterrupted = 1; } /* ** This function is exactly the same as sqlite3_create_function(), except ** that it is designed to be called by internal code. The difference is ** that if a malloc() fails in sqlite3_create_function(), an error code ** is returned and the mallocFailed flag cleared. */ SQLITE_PRIVATE int sqlite3CreateFunc( sqlite3 *db, const char *zFunctionName, int nArg, int enc, void *pUserData, void (*xSFunc)(sqlite3_context*,int,sqlite3_value **), void (*xStep)(sqlite3_context*,int,sqlite3_value **), void (*xFinal)(sqlite3_context*), FuncDestructor *pDestructor ){ FuncDef *p; int nName; int extraFlags; assert( sqlite3_mutex_held(db->mutex) ); if( zFunctionName==0 || (xSFunc && (xFinal || xStep)) || (!xSFunc && (xFinal && !xStep)) || (!xSFunc && (!xFinal && xStep)) || (nArg<-1 || nArg>SQLITE_MAX_FUNCTION_ARG) || (255<(nName = sqlite3Strlen30( zFunctionName))) ){ return SQLITE_MISUSE_BKPT; } assert( SQLITE_FUNC_CONSTANT==SQLITE_DETERMINISTIC ); extraFlags = enc & SQLITE_DETERMINISTIC; enc &= (SQLITE_FUNC_ENCMASK|SQLITE_ANY); #ifndef SQLITE_OMIT_UTF16 /* If SQLITE_UTF16 is specified as the encoding type, transform this ** to one of SQLITE_UTF16LE or SQLITE_UTF16BE using the ** SQLITE_UTF16NATIVE macro. SQLITE_UTF16 is not used internally. ** ** If SQLITE_ANY is specified, add three versions of the function ** to the hash table. */ if( enc==SQLITE_UTF16 ){ enc = SQLITE_UTF16NATIVE; }else if( enc==SQLITE_ANY ){ int rc; rc = sqlite3CreateFunc(db, zFunctionName, nArg, SQLITE_UTF8|extraFlags, pUserData, xSFunc, xStep, xFinal, pDestructor); if( rc==SQLITE_OK ){ rc = sqlite3CreateFunc(db, zFunctionName, nArg, SQLITE_UTF16LE|extraFlags, pUserData, xSFunc, xStep, xFinal, pDestructor); } if( rc!=SQLITE_OK ){ return rc; } enc = SQLITE_UTF16BE; } #else enc = SQLITE_UTF8; #endif /* Check if an existing function is being overridden or deleted. If so, ** and there are active VMs, then return SQLITE_BUSY. If a function ** is being overridden/deleted but there are no active VMs, allow the ** operation to continue but invalidate all precompiled statements. */ p = sqlite3FindFunction(db, zFunctionName, nArg, (u8)enc, 0); if( p && (p->funcFlags & SQLITE_FUNC_ENCMASK)==enc && p->nArg==nArg ){ if( db->nVdbeActive ){ sqlite3ErrorWithMsg(db, SQLITE_BUSY, "unable to delete/modify user-function due to active statements"); assert( !db->mallocFailed ); return SQLITE_BUSY; }else{ sqlite3ExpirePreparedStatements(db); } } p = sqlite3FindFunction(db, zFunctionName, nArg, (u8)enc, 1); assert(p || db->mallocFailed); if( !p ){ return SQLITE_NOMEM_BKPT; } /* If an older version of the function with a configured destructor is ** being replaced invoke the destructor function here. */ functionDestroy(db, p); if( pDestructor ){ pDestructor->nRef++; } p->u.pDestructor = pDestructor; p->funcFlags = (p->funcFlags & SQLITE_FUNC_ENCMASK) | extraFlags; testcase( p->funcFlags & SQLITE_DETERMINISTIC ); p->xSFunc = xSFunc ? xSFunc : xStep; p->xFinalize = xFinal; p->pUserData = pUserData; p->nArg = (u16)nArg; return SQLITE_OK; } /* ** Create new user functions. */ SQLITE_API int sqlite3_create_function( sqlite3 *db, const char *zFunc, int nArg, int enc, void *p, void (*xSFunc)(sqlite3_context*,int,sqlite3_value **), void (*xStep)(sqlite3_context*,int,sqlite3_value **), void (*xFinal)(sqlite3_context*) ){ return sqlite3_create_function_v2(db, zFunc, nArg, enc, p, xSFunc, xStep, xFinal, 0); } SQLITE_API int sqlite3_create_function_v2( sqlite3 *db, const char *zFunc, int nArg, int enc, void *p, void (*xSFunc)(sqlite3_context*,int,sqlite3_value **), void (*xStep)(sqlite3_context*,int,sqlite3_value **), void (*xFinal)(sqlite3_context*), void (*xDestroy)(void *) ){ int rc = SQLITE_ERROR; FuncDestructor *pArg = 0; #ifdef SQLITE_ENABLE_API_ARMOR if( !sqlite3SafetyCheckOk(db) ){ return SQLITE_MISUSE_BKPT; } #endif sqlite3_mutex_enter(db->mutex); if( xDestroy ){ pArg = (FuncDestructor *)sqlite3DbMallocZero(db, sizeof(FuncDestructor)); if( !pArg ){ xDestroy(p); goto out; } pArg->xDestroy = xDestroy; pArg->pUserData = p; } rc = sqlite3CreateFunc(db, zFunc, nArg, enc, p, xSFunc, xStep, xFinal, pArg); if( pArg && pArg->nRef==0 ){ assert( rc!=SQLITE_OK ); xDestroy(p); sqlite3DbFree(db, pArg); } out: rc = sqlite3ApiExit(db, rc); sqlite3_mutex_leave(db->mutex); return rc; } #ifndef SQLITE_OMIT_UTF16 SQLITE_API int sqlite3_create_function16( sqlite3 *db, const void *zFunctionName, int nArg, int eTextRep, void *p, void (*xSFunc)(sqlite3_context*,int,sqlite3_value**), void (*xStep)(sqlite3_context*,int,sqlite3_value**), void (*xFinal)(sqlite3_context*) ){ int rc; char *zFunc8; #ifdef SQLITE_ENABLE_API_ARMOR if( !sqlite3SafetyCheckOk(db) || zFunctionName==0 ) return SQLITE_MISUSE_BKPT; #endif sqlite3_mutex_enter(db->mutex); assert( !db->mallocFailed ); zFunc8 = sqlite3Utf16to8(db, zFunctionName, -1, SQLITE_UTF16NATIVE); rc = sqlite3CreateFunc(db, zFunc8, nArg, eTextRep, p, xSFunc,xStep,xFinal,0); sqlite3DbFree(db, zFunc8); rc = sqlite3ApiExit(db, rc); sqlite3_mutex_leave(db->mutex); return rc; } #endif /* ** Declare that a function has been overloaded by a virtual table. ** ** If the function already exists as a regular global function, then ** this routine is a no-op. If the function does not exist, then create ** a new one that always throws a run-time error. ** ** When virtual tables intend to provide an overloaded function, they ** should call this routine to make sure the global function exists. ** A global function must exist in order for name resolution to work ** properly. */ SQLITE_API int sqlite3_overload_function( sqlite3 *db, const char *zName, int nArg ){ int rc = SQLITE_OK; #ifdef SQLITE_ENABLE_API_ARMOR if( !sqlite3SafetyCheckOk(db) || zName==0 || nArg<-2 ){ return SQLITE_MISUSE_BKPT; } #endif sqlite3_mutex_enter(db->mutex); if( sqlite3FindFunction(db, zName, nArg, SQLITE_UTF8, 0)==0 ){ rc = sqlite3CreateFunc(db, zName, nArg, SQLITE_UTF8, 0, sqlite3InvalidFunction, 0, 0, 0); } rc = sqlite3ApiExit(db, rc); sqlite3_mutex_leave(db->mutex); return rc; } #ifndef SQLITE_OMIT_TRACE /* ** Register a trace function. The pArg from the previously registered trace ** is returned. ** ** A NULL trace function means that no tracing is executes. A non-NULL ** trace is a pointer to a function that is invoked at the start of each ** SQL statement. */ #ifndef SQLITE_OMIT_DEPRECATED SQLITE_API void *sqlite3_trace(sqlite3 *db, void(*xTrace)(void*,const char*), void *pArg){ void *pOld; #ifdef SQLITE_ENABLE_API_ARMOR if( !sqlite3SafetyCheckOk(db) ){ (void)SQLITE_MISUSE_BKPT; return 0; } #endif sqlite3_mutex_enter(db->mutex); pOld = db->pTraceArg; db->mTrace = xTrace ? SQLITE_TRACE_LEGACY : 0; db->xTrace = (int(*)(u32,void*,void*,void*))xTrace; db->pTraceArg = pArg; sqlite3_mutex_leave(db->mutex); return pOld; } #endif /* SQLITE_OMIT_DEPRECATED */ /* Register a trace callback using the version-2 interface. */ SQLITE_API int sqlite3_trace_v2( sqlite3 *db, /* Trace this connection */ unsigned mTrace, /* Mask of events to be traced */ int(*xTrace)(unsigned,void*,void*,void*), /* Callback to invoke */ void *pArg /* Context */ ){ #ifdef SQLITE_ENABLE_API_ARMOR if( !sqlite3SafetyCheckOk(db) ){ return SQLITE_MISUSE_BKPT; } #endif sqlite3_mutex_enter(db->mutex); if( mTrace==0 ) xTrace = 0; if( xTrace==0 ) mTrace = 0; db->mTrace = mTrace; db->xTrace = xTrace; db->pTraceArg = pArg; sqlite3_mutex_leave(db->mutex); return SQLITE_OK; } #ifndef SQLITE_OMIT_DEPRECATED /* ** Register a profile function. The pArg from the previously registered ** profile function is returned. ** ** A NULL profile function means that no profiling is executes. A non-NULL ** profile is a pointer to a function that is invoked at the conclusion of ** each SQL statement that is run. */ SQLITE_API void *sqlite3_profile( sqlite3 *db, void (*xProfile)(void*,const char*,sqlite_uint64), void *pArg ){ void *pOld; #ifdef SQLITE_ENABLE_API_ARMOR if( !sqlite3SafetyCheckOk(db) ){ (void)SQLITE_MISUSE_BKPT; return 0; } #endif sqlite3_mutex_enter(db->mutex); pOld = db->pProfileArg; db->xProfile = xProfile; db->pProfileArg = pArg; sqlite3_mutex_leave(db->mutex); return pOld; } #endif /* SQLITE_OMIT_DEPRECATED */ #endif /* SQLITE_OMIT_TRACE */ /* ** Register a function to be invoked when a transaction commits. ** If the invoked function returns non-zero, then the commit becomes a ** rollback. */ SQLITE_API void *sqlite3_commit_hook( sqlite3 *db, /* Attach the hook to this database */ int (*xCallback)(void*), /* Function to invoke on each commit */ void *pArg /* Argument to the function */ ){ void *pOld; #ifdef SQLITE_ENABLE_API_ARMOR if( !sqlite3SafetyCheckOk(db) ){ (void)SQLITE_MISUSE_BKPT; return 0; } #endif sqlite3_mutex_enter(db->mutex); pOld = db->pCommitArg; db->xCommitCallback = xCallback; db->pCommitArg = pArg; sqlite3_mutex_leave(db->mutex); return pOld; } /* ** Register a callback to be invoked each time a row is updated, ** inserted or deleted using this database connection. */ SQLITE_API void *sqlite3_update_hook( sqlite3 *db, /* Attach the hook to this database */ void (*xCallback)(void*,int,char const *,char const *,sqlite_int64), void *pArg /* Argument to the function */ ){ void *pRet; #ifdef SQLITE_ENABLE_API_ARMOR if( !sqlite3SafetyCheckOk(db) ){ (void)SQLITE_MISUSE_BKPT; return 0; } #endif sqlite3_mutex_enter(db->mutex); pRet = db->pUpdateArg; db->xUpdateCallback = xCallback; db->pUpdateArg = pArg; sqlite3_mutex_leave(db->mutex); return pRet; } /* ** Register a callback to be invoked each time a transaction is rolled ** back by this database connection. */ SQLITE_API void *sqlite3_rollback_hook( sqlite3 *db, /* Attach the hook to this database */ void (*xCallback)(void*), /* Callback function */ void *pArg /* Argument to the function */ ){ void *pRet; #ifdef SQLITE_ENABLE_API_ARMOR if( !sqlite3SafetyCheckOk(db) ){ (void)SQLITE_MISUSE_BKPT; return 0; } #endif sqlite3_mutex_enter(db->mutex); pRet = db->pRollbackArg; db->xRollbackCallback = xCallback; db->pRollbackArg = pArg; sqlite3_mutex_leave(db->mutex); return pRet; } #ifdef SQLITE_ENABLE_PREUPDATE_HOOK /* ** Register a callback to be invoked each time a row is updated, ** inserted or deleted using this database connection. */ SQLITE_API void *sqlite3_preupdate_hook( sqlite3 *db, /* Attach the hook to this database */ void(*xCallback)( /* Callback function */ void*,sqlite3*,int,char const*,char const*,sqlite3_int64,sqlite3_int64), void *pArg /* First callback argument */ ){ void *pRet; sqlite3_mutex_enter(db->mutex); pRet = db->pPreUpdateArg; db->xPreUpdateCallback = xCallback; db->pPreUpdateArg = pArg; sqlite3_mutex_leave(db->mutex); return pRet; } #endif /* SQLITE_ENABLE_PREUPDATE_HOOK */ #ifndef SQLITE_OMIT_WAL /* ** The sqlite3_wal_hook() callback registered by sqlite3_wal_autocheckpoint(). ** Invoke sqlite3_wal_checkpoint if the number of frames in the log file ** is greater than sqlite3.pWalArg cast to an integer (the value configured by ** wal_autocheckpoint()). */ SQLITE_PRIVATE int sqlite3WalDefaultHook( void *pClientData, /* Argument */ sqlite3 *db, /* Connection */ const char *zDb, /* Database */ int nFrame /* Size of WAL */ ){ if( nFrame>=SQLITE_PTR_TO_INT(pClientData) ){ sqlite3BeginBenignMalloc(); sqlite3_wal_checkpoint(db, zDb); sqlite3EndBenignMalloc(); } return SQLITE_OK; } #endif /* SQLITE_OMIT_WAL */ /* ** Configure an sqlite3_wal_hook() callback to automatically checkpoint ** a database after committing a transaction if there are nFrame or ** more frames in the log file. Passing zero or a negative value as the ** nFrame parameter disables automatic checkpoints entirely. ** ** The callback registered by this function replaces any existing callback ** registered using sqlite3_wal_hook(). Likewise, registering a callback ** using sqlite3_wal_hook() disables the automatic checkpoint mechanism ** configured by this function. */ SQLITE_API int sqlite3_wal_autocheckpoint(sqlite3 *db, int nFrame){ #ifdef SQLITE_OMIT_WAL UNUSED_PARAMETER(db); UNUSED_PARAMETER(nFrame); #else #ifdef SQLITE_ENABLE_API_ARMOR if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT; #endif if( nFrame>0 ){ sqlite3_wal_hook(db, sqlite3WalDefaultHook, SQLITE_INT_TO_PTR(nFrame)); }else{ sqlite3_wal_hook(db, 0, 0); } #endif return SQLITE_OK; } /* ** Register a callback to be invoked each time a transaction is written ** into the write-ahead-log by this database connection. */ SQLITE_API void *sqlite3_wal_hook( sqlite3 *db, /* Attach the hook to this db handle */ int(*xCallback)(void *, sqlite3*, const char*, int), void *pArg /* First argument passed to xCallback() */ ){ #ifndef SQLITE_OMIT_WAL void *pRet; #ifdef SQLITE_ENABLE_API_ARMOR if( !sqlite3SafetyCheckOk(db) ){ (void)SQLITE_MISUSE_BKPT; return 0; } #endif sqlite3_mutex_enter(db->mutex); pRet = db->pWalArg; db->xWalCallback = xCallback; db->pWalArg = pArg; sqlite3_mutex_leave(db->mutex); return pRet; #else return 0; #endif } /* ** Checkpoint database zDb. */ SQLITE_API int sqlite3_wal_checkpoint_v2( sqlite3 *db, /* Database handle */ const char *zDb, /* Name of attached database (or NULL) */ int eMode, /* SQLITE_CHECKPOINT_* value */ int *pnLog, /* OUT: Size of WAL log in frames */ int *pnCkpt /* OUT: Total number of frames checkpointed */ ){ #ifdef SQLITE_OMIT_WAL return SQLITE_OK; #else int rc; /* Return code */ int iDb = SQLITE_MAX_ATTACHED; /* sqlite3.aDb[] index of db to checkpoint */ #ifdef SQLITE_ENABLE_API_ARMOR if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT; #endif /* Initialize the output variables to -1 in case an error occurs. */ if( pnLog ) *pnLog = -1; if( pnCkpt ) *pnCkpt = -1; assert( SQLITE_CHECKPOINT_PASSIVE==0 ); assert( SQLITE_CHECKPOINT_FULL==1 ); assert( SQLITE_CHECKPOINT_RESTART==2 ); assert( SQLITE_CHECKPOINT_TRUNCATE==3 ); if( eModeSQLITE_CHECKPOINT_TRUNCATE ){ /* EVIDENCE-OF: R-03996-12088 The M parameter must be a valid checkpoint ** mode: */ return SQLITE_MISUSE; } sqlite3_mutex_enter(db->mutex); if( zDb && zDb[0] ){ iDb = sqlite3FindDbName(db, zDb); } if( iDb<0 ){ rc = SQLITE_ERROR; sqlite3ErrorWithMsg(db, SQLITE_ERROR, "unknown database: %s", zDb); }else{ db->busyHandler.nBusy = 0; rc = sqlite3Checkpoint(db, iDb, eMode, pnLog, pnCkpt); sqlite3Error(db, rc); } rc = sqlite3ApiExit(db, rc); sqlite3_mutex_leave(db->mutex); return rc; #endif } /* ** Checkpoint database zDb. If zDb is NULL, or if the buffer zDb points ** to contains a zero-length string, all attached databases are ** checkpointed. */ SQLITE_API int sqlite3_wal_checkpoint(sqlite3 *db, const char *zDb){ /* EVIDENCE-OF: R-41613-20553 The sqlite3_wal_checkpoint(D,X) is equivalent to ** sqlite3_wal_checkpoint_v2(D,X,SQLITE_CHECKPOINT_PASSIVE,0,0). */ return sqlite3_wal_checkpoint_v2(db,zDb,SQLITE_CHECKPOINT_PASSIVE,0,0); } #ifndef SQLITE_OMIT_WAL /* ** Run a checkpoint on database iDb. This is a no-op if database iDb is ** not currently open in WAL mode. ** ** If a transaction is open on the database being checkpointed, this ** function returns SQLITE_LOCKED and a checkpoint is not attempted. If ** an error occurs while running the checkpoint, an SQLite error code is ** returned (i.e. SQLITE_IOERR). Otherwise, SQLITE_OK. ** ** The mutex on database handle db should be held by the caller. The mutex ** associated with the specific b-tree being checkpointed is taken by ** this function while the checkpoint is running. ** ** If iDb is passed SQLITE_MAX_ATTACHED, then all attached databases are ** checkpointed. If an error is encountered it is returned immediately - ** no attempt is made to checkpoint any remaining databases. ** ** Parameter eMode is one of SQLITE_CHECKPOINT_PASSIVE, FULL or RESTART. */ SQLITE_PRIVATE int sqlite3Checkpoint(sqlite3 *db, int iDb, int eMode, int *pnLog, int *pnCkpt){ int rc = SQLITE_OK; /* Return code */ int i; /* Used to iterate through attached dbs */ int bBusy = 0; /* True if SQLITE_BUSY has been encountered */ assert( sqlite3_mutex_held(db->mutex) ); assert( !pnLog || *pnLog==-1 ); assert( !pnCkpt || *pnCkpt==-1 ); for(i=0; inDb && rc==SQLITE_OK; i++){ if( i==iDb || iDb==SQLITE_MAX_ATTACHED ){ rc = sqlite3BtreeCheckpoint(db->aDb[i].pBt, eMode, pnLog, pnCkpt); pnLog = 0; pnCkpt = 0; if( rc==SQLITE_BUSY ){ bBusy = 1; rc = SQLITE_OK; } } } return (rc==SQLITE_OK && bBusy) ? SQLITE_BUSY : rc; } #endif /* SQLITE_OMIT_WAL */ /* ** This function returns true if main-memory should be used instead of ** a temporary file for transient pager files and statement journals. ** The value returned depends on the value of db->temp_store (runtime ** parameter) and the compile time value of SQLITE_TEMP_STORE. The ** following table describes the relationship between these two values ** and this functions return value. ** ** SQLITE_TEMP_STORE db->temp_store Location of temporary database ** ----------------- -------------- ------------------------------ ** 0 any file (return 0) ** 1 1 file (return 0) ** 1 2 memory (return 1) ** 1 0 file (return 0) ** 2 1 file (return 0) ** 2 2 memory (return 1) ** 2 0 memory (return 1) ** 3 any memory (return 1) */ SQLITE_PRIVATE int sqlite3TempInMemory(const sqlite3 *db){ #if SQLITE_TEMP_STORE==1 return ( db->temp_store==2 ); #endif #if SQLITE_TEMP_STORE==2 return ( db->temp_store!=1 ); #endif #if SQLITE_TEMP_STORE==3 UNUSED_PARAMETER(db); return 1; #endif #if SQLITE_TEMP_STORE<1 || SQLITE_TEMP_STORE>3 UNUSED_PARAMETER(db); return 0; #endif } /* ** Return UTF-8 encoded English language explanation of the most recent ** error. */ SQLITE_API const char *sqlite3_errmsg(sqlite3 *db){ const char *z; if( !db ){ return sqlite3ErrStr(SQLITE_NOMEM_BKPT); } if( !sqlite3SafetyCheckSickOrOk(db) ){ return sqlite3ErrStr(SQLITE_MISUSE_BKPT); } sqlite3_mutex_enter(db->mutex); if( db->mallocFailed ){ z = sqlite3ErrStr(SQLITE_NOMEM_BKPT); }else{ testcase( db->pErr==0 ); z = (char*)sqlite3_value_text(db->pErr); assert( !db->mallocFailed ); if( z==0 ){ z = sqlite3ErrStr(db->errCode); } } sqlite3_mutex_leave(db->mutex); return z; } #ifndef SQLITE_OMIT_UTF16 /* ** Return UTF-16 encoded English language explanation of the most recent ** error. */ SQLITE_API const void *sqlite3_errmsg16(sqlite3 *db){ static const u16 outOfMem[] = { 'o', 'u', 't', ' ', 'o', 'f', ' ', 'm', 'e', 'm', 'o', 'r', 'y', 0 }; static const u16 misuse[] = { 'l', 'i', 'b', 'r', 'a', 'r', 'y', ' ', 'r', 'o', 'u', 't', 'i', 'n', 'e', ' ', 'c', 'a', 'l', 'l', 'e', 'd', ' ', 'o', 'u', 't', ' ', 'o', 'f', ' ', 's', 'e', 'q', 'u', 'e', 'n', 'c', 'e', 0 }; const void *z; if( !db ){ return (void *)outOfMem; } if( !sqlite3SafetyCheckSickOrOk(db) ){ return (void *)misuse; } sqlite3_mutex_enter(db->mutex); if( db->mallocFailed ){ z = (void *)outOfMem; }else{ z = sqlite3_value_text16(db->pErr); if( z==0 ){ sqlite3ErrorWithMsg(db, db->errCode, sqlite3ErrStr(db->errCode)); z = sqlite3_value_text16(db->pErr); } /* A malloc() may have failed within the call to sqlite3_value_text16() ** above. If this is the case, then the db->mallocFailed flag needs to ** be cleared before returning. Do this directly, instead of via ** sqlite3ApiExit(), to avoid setting the database handle error message. */ sqlite3OomClear(db); } sqlite3_mutex_leave(db->mutex); return z; } #endif /* SQLITE_OMIT_UTF16 */ /* ** Return the most recent error code generated by an SQLite routine. If NULL is ** passed to this function, we assume a malloc() failed during sqlite3_open(). */ SQLITE_API int sqlite3_errcode(sqlite3 *db){ if( db && !sqlite3SafetyCheckSickOrOk(db) ){ return SQLITE_MISUSE_BKPT; } if( !db || db->mallocFailed ){ return SQLITE_NOMEM_BKPT; } return db->errCode & db->errMask; } SQLITE_API int sqlite3_extended_errcode(sqlite3 *db){ if( db && !sqlite3SafetyCheckSickOrOk(db) ){ return SQLITE_MISUSE_BKPT; } if( !db || db->mallocFailed ){ return SQLITE_NOMEM_BKPT; } return db->errCode; } SQLITE_API int sqlite3_system_errno(sqlite3 *db){ return db ? db->iSysErrno : 0; } /* ** Return a string that describes the kind of error specified in the ** argument. For now, this simply calls the internal sqlite3ErrStr() ** function. */ SQLITE_API const char *sqlite3_errstr(int rc){ return sqlite3ErrStr(rc); } /* ** Create a new collating function for database "db". The name is zName ** and the encoding is enc. */ static int createCollation( sqlite3* db, const char *zName, u8 enc, void* pCtx, int(*xCompare)(void*,int,const void*,int,const void*), void(*xDel)(void*) ){ CollSeq *pColl; int enc2; assert( sqlite3_mutex_held(db->mutex) ); /* If SQLITE_UTF16 is specified as the encoding type, transform this ** to one of SQLITE_UTF16LE or SQLITE_UTF16BE using the ** SQLITE_UTF16NATIVE macro. SQLITE_UTF16 is not used internally. */ enc2 = enc; testcase( enc2==SQLITE_UTF16 ); testcase( enc2==SQLITE_UTF16_ALIGNED ); if( enc2==SQLITE_UTF16 || enc2==SQLITE_UTF16_ALIGNED ){ enc2 = SQLITE_UTF16NATIVE; } if( enc2SQLITE_UTF16BE ){ return SQLITE_MISUSE_BKPT; } /* Check if this call is removing or replacing an existing collation ** sequence. If so, and there are active VMs, return busy. If there ** are no active VMs, invalidate any pre-compiled statements. */ pColl = sqlite3FindCollSeq(db, (u8)enc2, zName, 0); if( pColl && pColl->xCmp ){ if( db->nVdbeActive ){ sqlite3ErrorWithMsg(db, SQLITE_BUSY, "unable to delete/modify collation sequence due to active statements"); return SQLITE_BUSY; } sqlite3ExpirePreparedStatements(db); /* If collation sequence pColl was created directly by a call to ** sqlite3_create_collation, and not generated by synthCollSeq(), ** then any copies made by synthCollSeq() need to be invalidated. ** Also, collation destructor - CollSeq.xDel() - function may need ** to be called. */ if( (pColl->enc & ~SQLITE_UTF16_ALIGNED)==enc2 ){ CollSeq *aColl = sqlite3HashFind(&db->aCollSeq, zName); int j; for(j=0; j<3; j++){ CollSeq *p = &aColl[j]; if( p->enc==pColl->enc ){ if( p->xDel ){ p->xDel(p->pUser); } p->xCmp = 0; } } } } pColl = sqlite3FindCollSeq(db, (u8)enc2, zName, 1); if( pColl==0 ) return SQLITE_NOMEM_BKPT; pColl->xCmp = xCompare; pColl->pUser = pCtx; pColl->xDel = xDel; pColl->enc = (u8)(enc2 | (enc & SQLITE_UTF16_ALIGNED)); sqlite3Error(db, SQLITE_OK); return SQLITE_OK; } /* ** This array defines hard upper bounds on limit values. The ** initializer must be kept in sync with the SQLITE_LIMIT_* ** #defines in sqlite3.h. */ static const int aHardLimit[] = { SQLITE_MAX_LENGTH, SQLITE_MAX_SQL_LENGTH, SQLITE_MAX_COLUMN, SQLITE_MAX_EXPR_DEPTH, SQLITE_MAX_COMPOUND_SELECT, SQLITE_MAX_VDBE_OP, SQLITE_MAX_FUNCTION_ARG, SQLITE_MAX_ATTACHED, SQLITE_MAX_LIKE_PATTERN_LENGTH, SQLITE_MAX_VARIABLE_NUMBER, /* IMP: R-38091-32352 */ SQLITE_MAX_TRIGGER_DEPTH, SQLITE_MAX_WORKER_THREADS, }; /* ** Make sure the hard limits are set to reasonable values */ #if SQLITE_MAX_LENGTH<100 # error SQLITE_MAX_LENGTH must be at least 100 #endif #if SQLITE_MAX_SQL_LENGTH<100 # error SQLITE_MAX_SQL_LENGTH must be at least 100 #endif #if SQLITE_MAX_SQL_LENGTH>SQLITE_MAX_LENGTH # error SQLITE_MAX_SQL_LENGTH must not be greater than SQLITE_MAX_LENGTH #endif #if SQLITE_MAX_COMPOUND_SELECT<2 # error SQLITE_MAX_COMPOUND_SELECT must be at least 2 #endif #if SQLITE_MAX_VDBE_OP<40 # error SQLITE_MAX_VDBE_OP must be at least 40 #endif #if SQLITE_MAX_FUNCTION_ARG<0 || SQLITE_MAX_FUNCTION_ARG>127 # error SQLITE_MAX_FUNCTION_ARG must be between 0 and 127 #endif #if SQLITE_MAX_ATTACHED<0 || SQLITE_MAX_ATTACHED>125 # error SQLITE_MAX_ATTACHED must be between 0 and 125 #endif #if SQLITE_MAX_LIKE_PATTERN_LENGTH<1 # error SQLITE_MAX_LIKE_PATTERN_LENGTH must be at least 1 #endif #if SQLITE_MAX_COLUMN>32767 # error SQLITE_MAX_COLUMN must not exceed 32767 #endif #if SQLITE_MAX_TRIGGER_DEPTH<1 # error SQLITE_MAX_TRIGGER_DEPTH must be at least 1 #endif #if SQLITE_MAX_WORKER_THREADS<0 || SQLITE_MAX_WORKER_THREADS>50 # error SQLITE_MAX_WORKER_THREADS must be between 0 and 50 #endif /* ** Change the value of a limit. Report the old value. ** If an invalid limit index is supplied, report -1. ** Make no changes but still report the old value if the ** new limit is negative. ** ** A new lower limit does not shrink existing constructs. ** It merely prevents new constructs that exceed the limit ** from forming. */ SQLITE_API int sqlite3_limit(sqlite3 *db, int limitId, int newLimit){ int oldLimit; #ifdef SQLITE_ENABLE_API_ARMOR if( !sqlite3SafetyCheckOk(db) ){ (void)SQLITE_MISUSE_BKPT; return -1; } #endif /* EVIDENCE-OF: R-30189-54097 For each limit category SQLITE_LIMIT_NAME ** there is a hard upper bound set at compile-time by a C preprocessor ** macro called SQLITE_MAX_NAME. (The "_LIMIT_" in the name is changed to ** "_MAX_".) */ assert( aHardLimit[SQLITE_LIMIT_LENGTH]==SQLITE_MAX_LENGTH ); assert( aHardLimit[SQLITE_LIMIT_SQL_LENGTH]==SQLITE_MAX_SQL_LENGTH ); assert( aHardLimit[SQLITE_LIMIT_COLUMN]==SQLITE_MAX_COLUMN ); assert( aHardLimit[SQLITE_LIMIT_EXPR_DEPTH]==SQLITE_MAX_EXPR_DEPTH ); assert( aHardLimit[SQLITE_LIMIT_COMPOUND_SELECT]==SQLITE_MAX_COMPOUND_SELECT); assert( aHardLimit[SQLITE_LIMIT_VDBE_OP]==SQLITE_MAX_VDBE_OP ); assert( aHardLimit[SQLITE_LIMIT_FUNCTION_ARG]==SQLITE_MAX_FUNCTION_ARG ); assert( aHardLimit[SQLITE_LIMIT_ATTACHED]==SQLITE_MAX_ATTACHED ); assert( aHardLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH]== SQLITE_MAX_LIKE_PATTERN_LENGTH ); assert( aHardLimit[SQLITE_LIMIT_VARIABLE_NUMBER]==SQLITE_MAX_VARIABLE_NUMBER); assert( aHardLimit[SQLITE_LIMIT_TRIGGER_DEPTH]==SQLITE_MAX_TRIGGER_DEPTH ); assert( aHardLimit[SQLITE_LIMIT_WORKER_THREADS]==SQLITE_MAX_WORKER_THREADS ); assert( SQLITE_LIMIT_WORKER_THREADS==(SQLITE_N_LIMIT-1) ); if( limitId<0 || limitId>=SQLITE_N_LIMIT ){ return -1; } oldLimit = db->aLimit[limitId]; if( newLimit>=0 ){ /* IMP: R-52476-28732 */ if( newLimit>aHardLimit[limitId] ){ newLimit = aHardLimit[limitId]; /* IMP: R-51463-25634 */ } db->aLimit[limitId] = newLimit; } return oldLimit; /* IMP: R-53341-35419 */ } /* ** This function is used to parse both URIs and non-URI filenames passed by the ** user to API functions sqlite3_open() or sqlite3_open_v2(), and for database ** URIs specified as part of ATTACH statements. ** ** The first argument to this function is the name of the VFS to use (or ** a NULL to signify the default VFS) if the URI does not contain a "vfs=xxx" ** query parameter. The second argument contains the URI (or non-URI filename) ** itself. When this function is called the *pFlags variable should contain ** the default flags to open the database handle with. The value stored in ** *pFlags may be updated before returning if the URI filename contains ** "cache=xxx" or "mode=xxx" query parameters. ** ** If successful, SQLITE_OK is returned. In this case *ppVfs is set to point to ** the VFS that should be used to open the database file. *pzFile is set to ** point to a buffer containing the name of the file to open. It is the ** responsibility of the caller to eventually call sqlite3_free() to release ** this buffer. ** ** If an error occurs, then an SQLite error code is returned and *pzErrMsg ** may be set to point to a buffer containing an English language error ** message. It is the responsibility of the caller to eventually release ** this buffer by calling sqlite3_free(). */ SQLITE_PRIVATE int sqlite3ParseUri( const char *zDefaultVfs, /* VFS to use if no "vfs=xxx" query option */ const char *zUri, /* Nul-terminated URI to parse */ unsigned int *pFlags, /* IN/OUT: SQLITE_OPEN_XXX flags */ sqlite3_vfs **ppVfs, /* OUT: VFS to use */ char **pzFile, /* OUT: Filename component of URI */ char **pzErrMsg /* OUT: Error message (if rc!=SQLITE_OK) */ ){ int rc = SQLITE_OK; unsigned int flags = *pFlags; const char *zVfs = zDefaultVfs; char *zFile; char c; int nUri = sqlite3Strlen30(zUri); assert( *pzErrMsg==0 ); if( ((flags & SQLITE_OPEN_URI) /* IMP: R-48725-32206 */ || sqlite3GlobalConfig.bOpenUri) /* IMP: R-51689-46548 */ && nUri>=5 && memcmp(zUri, "file:", 5)==0 /* IMP: R-57884-37496 */ ){ char *zOpt; int eState; /* Parser state when parsing URI */ int iIn; /* Input character index */ int iOut = 0; /* Output character index */ u64 nByte = nUri+2; /* Bytes of space to allocate */ /* Make sure the SQLITE_OPEN_URI flag is set to indicate to the VFS xOpen ** method that there may be extra parameters following the file-name. */ flags |= SQLITE_OPEN_URI; for(iIn=0; iIn=0 && octet<256 ); if( octet==0 ){ /* This branch is taken when "%00" appears within the URI. In this ** case we ignore all text in the remainder of the path, name or ** value currently being parsed. So ignore the current character ** and skip to the next "?", "=" or "&", as appropriate. */ while( (c = zUri[iIn])!=0 && c!='#' && (eState!=0 || c!='?') && (eState!=1 || (c!='=' && c!='&')) && (eState!=2 || c!='&') ){ iIn++; } continue; } c = octet; }else if( eState==1 && (c=='&' || c=='=') ){ if( zFile[iOut-1]==0 ){ /* An empty option name. Ignore this option altogether. */ while( zUri[iIn] && zUri[iIn]!='#' && zUri[iIn-1]!='&' ) iIn++; continue; } if( c=='&' ){ zFile[iOut++] = '\0'; }else{ eState = 2; } c = 0; }else if( (eState==0 && c=='?') || (eState==2 && c=='&') ){ c = 0; eState = 1; } zFile[iOut++] = c; } if( eState==1 ) zFile[iOut++] = '\0'; zFile[iOut++] = '\0'; zFile[iOut++] = '\0'; /* Check if there were any options specified that should be interpreted ** here. Options that are interpreted here include "vfs" and those that ** correspond to flags that may be passed to the sqlite3_open_v2() ** method. */ zOpt = &zFile[sqlite3Strlen30(zFile)+1]; while( zOpt[0] ){ int nOpt = sqlite3Strlen30(zOpt); char *zVal = &zOpt[nOpt+1]; int nVal = sqlite3Strlen30(zVal); if( nOpt==3 && memcmp("vfs", zOpt, 3)==0 ){ zVfs = zVal; }else{ struct OpenMode { const char *z; int mode; } *aMode = 0; char *zModeType = 0; int mask = 0; int limit = 0; if( nOpt==5 && memcmp("cache", zOpt, 5)==0 ){ static struct OpenMode aCacheMode[] = { { "shared", SQLITE_OPEN_SHAREDCACHE }, { "private", SQLITE_OPEN_PRIVATECACHE }, { 0, 0 } }; mask = SQLITE_OPEN_SHAREDCACHE|SQLITE_OPEN_PRIVATECACHE; aMode = aCacheMode; limit = mask; zModeType = "cache"; } if( nOpt==4 && memcmp("mode", zOpt, 4)==0 ){ static struct OpenMode aOpenMode[] = { { "ro", SQLITE_OPEN_READONLY }, { "rw", SQLITE_OPEN_READWRITE }, { "rwc", SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE }, { "memory", SQLITE_OPEN_MEMORY }, { 0, 0 } }; mask = SQLITE_OPEN_READONLY | SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE | SQLITE_OPEN_MEMORY; aMode = aOpenMode; limit = mask & flags; zModeType = "access"; } if( aMode ){ int i; int mode = 0; for(i=0; aMode[i].z; i++){ const char *z = aMode[i].z; if( nVal==sqlite3Strlen30(z) && 0==memcmp(zVal, z, nVal) ){ mode = aMode[i].mode; break; } } if( mode==0 ){ *pzErrMsg = sqlite3_mprintf("no such %s mode: %s", zModeType, zVal); rc = SQLITE_ERROR; goto parse_uri_out; } if( (mode & ~SQLITE_OPEN_MEMORY)>limit ){ *pzErrMsg = sqlite3_mprintf("%s mode not allowed: %s", zModeType, zVal); rc = SQLITE_PERM; goto parse_uri_out; } flags = (flags & ~mask) | mode; } } zOpt = &zVal[nVal+1]; } }else{ zFile = sqlite3_malloc64(nUri+2); if( !zFile ) return SQLITE_NOMEM_BKPT; memcpy(zFile, zUri, nUri); zFile[nUri] = '\0'; zFile[nUri+1] = '\0'; flags &= ~SQLITE_OPEN_URI; } *ppVfs = sqlite3_vfs_find(zVfs); if( *ppVfs==0 ){ *pzErrMsg = sqlite3_mprintf("no such vfs: %s", zVfs); rc = SQLITE_ERROR; } parse_uri_out: if( rc!=SQLITE_OK ){ sqlite3_free(zFile); zFile = 0; } *pFlags = flags; *pzFile = zFile; return rc; } /* ** This routine does the work of opening a database on behalf of ** sqlite3_open() and sqlite3_open16(). The database filename "zFilename" ** is UTF-8 encoded. */ static int openDatabase( const char *zFilename, /* Database filename UTF-8 encoded */ sqlite3 **ppDb, /* OUT: Returned database handle */ unsigned int flags, /* Operational flags */ const char *zVfs /* Name of the VFS to use */ ){ sqlite3 *db; /* Store allocated handle here */ int rc; /* Return code */ int isThreadsafe; /* True for threadsafe connections */ char *zOpen = 0; /* Filename argument to pass to BtreeOpen() */ char *zErrMsg = 0; /* Error message from sqlite3ParseUri() */ #ifdef SQLITE_ENABLE_API_ARMOR if( ppDb==0 ) return SQLITE_MISUSE_BKPT; #endif *ppDb = 0; #ifndef SQLITE_OMIT_AUTOINIT rc = sqlite3_initialize(); if( rc ) return rc; #endif /* Only allow sensible combinations of bits in the flags argument. ** Throw an error if any non-sense combination is used. If we ** do not block illegal combinations here, it could trigger ** assert() statements in deeper layers. Sensible combinations ** are: ** ** 1: SQLITE_OPEN_READONLY ** 2: SQLITE_OPEN_READWRITE ** 6: SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE */ assert( SQLITE_OPEN_READONLY == 0x01 ); assert( SQLITE_OPEN_READWRITE == 0x02 ); assert( SQLITE_OPEN_CREATE == 0x04 ); testcase( (1<<(flags&7))==0x02 ); /* READONLY */ testcase( (1<<(flags&7))==0x04 ); /* READWRITE */ testcase( (1<<(flags&7))==0x40 ); /* READWRITE | CREATE */ if( ((1<<(flags&7)) & 0x46)==0 ){ return SQLITE_MISUSE_BKPT; /* IMP: R-65497-44594 */ } if( sqlite3GlobalConfig.bCoreMutex==0 ){ isThreadsafe = 0; }else if( flags & SQLITE_OPEN_NOMUTEX ){ isThreadsafe = 0; }else if( flags & SQLITE_OPEN_FULLMUTEX ){ isThreadsafe = 1; }else{ isThreadsafe = sqlite3GlobalConfig.bFullMutex; } if( flags & SQLITE_OPEN_PRIVATECACHE ){ flags &= ~SQLITE_OPEN_SHAREDCACHE; }else if( sqlite3GlobalConfig.sharedCacheEnabled ){ flags |= SQLITE_OPEN_SHAREDCACHE; } /* Remove harmful bits from the flags parameter ** ** The SQLITE_OPEN_NOMUTEX and SQLITE_OPEN_FULLMUTEX flags were ** dealt with in the previous code block. Besides these, the only ** valid input flags for sqlite3_open_v2() are SQLITE_OPEN_READONLY, ** SQLITE_OPEN_READWRITE, SQLITE_OPEN_CREATE, SQLITE_OPEN_SHAREDCACHE, ** SQLITE_OPEN_PRIVATECACHE, and some reserved bits. Silently mask ** off all other flags. */ flags &= ~( SQLITE_OPEN_DELETEONCLOSE | SQLITE_OPEN_EXCLUSIVE | SQLITE_OPEN_MAIN_DB | SQLITE_OPEN_TEMP_DB | SQLITE_OPEN_TRANSIENT_DB | SQLITE_OPEN_MAIN_JOURNAL | SQLITE_OPEN_TEMP_JOURNAL | SQLITE_OPEN_SUBJOURNAL | SQLITE_OPEN_MASTER_JOURNAL | SQLITE_OPEN_NOMUTEX | SQLITE_OPEN_FULLMUTEX | SQLITE_OPEN_WAL ); /* Allocate the sqlite data structure */ db = sqlite3MallocZero( sizeof(sqlite3) ); if( db==0 ) goto opendb_out; if( isThreadsafe ){ db->mutex = sqlite3MutexAlloc(SQLITE_MUTEX_RECURSIVE); if( db->mutex==0 ){ sqlite3_free(db); db = 0; goto opendb_out; } } sqlite3_mutex_enter(db->mutex); db->errMask = 0xff; db->nDb = 2; db->magic = SQLITE_MAGIC_BUSY; db->aDb = db->aDbStatic; assert( sizeof(db->aLimit)==sizeof(aHardLimit) ); memcpy(db->aLimit, aHardLimit, sizeof(db->aLimit)); db->aLimit[SQLITE_LIMIT_WORKER_THREADS] = SQLITE_DEFAULT_WORKER_THREADS; db->autoCommit = 1; db->nextAutovac = -1; db->szMmap = sqlite3GlobalConfig.szMmap; db->nextPagesize = 0; db->nMaxSorterMmap = 0x7FFFFFFF; db->flags |= SQLITE_ShortColNames | SQLITE_EnableTrigger | SQLITE_CacheSpill #if !defined(SQLITE_DEFAULT_AUTOMATIC_INDEX) || SQLITE_DEFAULT_AUTOMATIC_INDEX | SQLITE_AutoIndex #endif #if SQLITE_DEFAULT_CKPTFULLFSYNC | SQLITE_CkptFullFSync #endif #if SQLITE_DEFAULT_FILE_FORMAT<4 | SQLITE_LegacyFileFmt #endif #ifdef SQLITE_ENABLE_LOAD_EXTENSION | SQLITE_LoadExtension #endif #if SQLITE_DEFAULT_RECURSIVE_TRIGGERS | SQLITE_RecTriggers #endif #if defined(SQLITE_DEFAULT_FOREIGN_KEYS) && SQLITE_DEFAULT_FOREIGN_KEYS | SQLITE_ForeignKeys #endif #if defined(SQLITE_REVERSE_UNORDERED_SELECTS) | SQLITE_ReverseOrder #endif #if defined(SQLITE_ENABLE_OVERSIZE_CELL_CHECK) | SQLITE_CellSizeCk #endif #if defined(SQLITE_ENABLE_FTS3_TOKENIZER) | SQLITE_Fts3Tokenizer #endif ; sqlite3HashInit(&db->aCollSeq); #ifndef SQLITE_OMIT_VIRTUALTABLE sqlite3HashInit(&db->aModule); #endif /* Add the default collation sequence BINARY. BINARY works for both UTF-8 ** and UTF-16, so add a version for each to avoid any unnecessary ** conversions. The only error that can occur here is a malloc() failure. ** ** EVIDENCE-OF: R-52786-44878 SQLite defines three built-in collating ** functions: */ createCollation(db, sqlite3StrBINARY, SQLITE_UTF8, 0, binCollFunc, 0); createCollation(db, sqlite3StrBINARY, SQLITE_UTF16BE, 0, binCollFunc, 0); createCollation(db, sqlite3StrBINARY, SQLITE_UTF16LE, 0, binCollFunc, 0); createCollation(db, "NOCASE", SQLITE_UTF8, 0, nocaseCollatingFunc, 0); createCollation(db, "RTRIM", SQLITE_UTF8, (void*)1, binCollFunc, 0); if( db->mallocFailed ){ goto opendb_out; } /* EVIDENCE-OF: R-08308-17224 The default collating function for all ** strings is BINARY. */ db->pDfltColl = sqlite3FindCollSeq(db, SQLITE_UTF8, sqlite3StrBINARY, 0); assert( db->pDfltColl!=0 ); /* Parse the filename/URI argument. */ db->openFlags = flags; rc = sqlite3ParseUri(zVfs, zFilename, &flags, &db->pVfs, &zOpen, &zErrMsg); if( rc!=SQLITE_OK ){ if( rc==SQLITE_NOMEM ) sqlite3OomFault(db); sqlite3ErrorWithMsg(db, rc, zErrMsg ? "%s" : 0, zErrMsg); sqlite3_free(zErrMsg); goto opendb_out; } /* Open the backend database driver */ rc = sqlite3BtreeOpen(db->pVfs, zOpen, db, &db->aDb[0].pBt, 0, flags | SQLITE_OPEN_MAIN_DB); if( rc!=SQLITE_OK ){ if( rc==SQLITE_IOERR_NOMEM ){ rc = SQLITE_NOMEM_BKPT; } sqlite3Error(db, rc); goto opendb_out; } sqlite3BtreeEnter(db->aDb[0].pBt); db->aDb[0].pSchema = sqlite3SchemaGet(db, db->aDb[0].pBt); if( !db->mallocFailed ) ENC(db) = SCHEMA_ENC(db); sqlite3BtreeLeave(db->aDb[0].pBt); db->aDb[1].pSchema = sqlite3SchemaGet(db, 0); /* The default safety_level for the main database is FULL; for the temp ** database it is OFF. This matches the pager layer defaults. */ db->aDb[0].zDbSName = "main"; db->aDb[0].safety_level = SQLITE_DEFAULT_SYNCHRONOUS+1; db->aDb[1].zDbSName = "temp"; db->aDb[1].safety_level = PAGER_SYNCHRONOUS_OFF; db->magic = SQLITE_MAGIC_OPEN; if( db->mallocFailed ){ goto opendb_out; } /* Register all built-in functions, but do not attempt to read the ** database schema yet. This is delayed until the first time the database ** is accessed. */ sqlite3Error(db, SQLITE_OK); sqlite3RegisterPerConnectionBuiltinFunctions(db); rc = sqlite3_errcode(db); #ifdef SQLITE_ENABLE_FTS5 /* Register any built-in FTS5 module before loading the automatic ** extensions. This allows automatic extensions to register FTS5 ** tokenizers and auxiliary functions. */ if( !db->mallocFailed && rc==SQLITE_OK ){ rc = sqlite3Fts5Init(db); } #endif /* Load automatic extensions - extensions that have been registered ** using the sqlite3_automatic_extension() API. */ if( rc==SQLITE_OK ){ sqlite3AutoLoadExtensions(db); rc = sqlite3_errcode(db); if( rc!=SQLITE_OK ){ goto opendb_out; } } #ifdef SQLITE_ENABLE_FTS1 if( !db->mallocFailed ){ extern int sqlite3Fts1Init(sqlite3*); rc = sqlite3Fts1Init(db); } #endif #ifdef SQLITE_ENABLE_FTS2 if( !db->mallocFailed && rc==SQLITE_OK ){ extern int sqlite3Fts2Init(sqlite3*); rc = sqlite3Fts2Init(db); } #endif #ifdef SQLITE_ENABLE_FTS3 /* automatically defined by SQLITE_ENABLE_FTS4 */ if( !db->mallocFailed && rc==SQLITE_OK ){ rc = sqlite3Fts3Init(db); } #endif #ifdef SQLITE_ENABLE_ICU if( !db->mallocFailed && rc==SQLITE_OK ){ rc = sqlite3IcuInit(db); } #endif #ifdef SQLITE_ENABLE_RTREE if( !db->mallocFailed && rc==SQLITE_OK){ rc = sqlite3RtreeInit(db); } #endif #ifdef SQLITE_ENABLE_DBSTAT_VTAB if( !db->mallocFailed && rc==SQLITE_OK){ rc = sqlite3DbstatRegister(db); } #endif #ifdef SQLITE_ENABLE_JSON1 if( !db->mallocFailed && rc==SQLITE_OK){ rc = sqlite3Json1Init(db); } #endif /* -DSQLITE_DEFAULT_LOCKING_MODE=1 makes EXCLUSIVE the default locking ** mode. -DSQLITE_DEFAULT_LOCKING_MODE=0 make NORMAL the default locking ** mode. Doing nothing at all also makes NORMAL the default. */ #ifdef SQLITE_DEFAULT_LOCKING_MODE db->dfltLockMode = SQLITE_DEFAULT_LOCKING_MODE; sqlite3PagerLockingMode(sqlite3BtreePager(db->aDb[0].pBt), SQLITE_DEFAULT_LOCKING_MODE); #endif if( rc ) sqlite3Error(db, rc); /* Enable the lookaside-malloc subsystem */ setupLookaside(db, 0, sqlite3GlobalConfig.szLookaside, sqlite3GlobalConfig.nLookaside); sqlite3_wal_autocheckpoint(db, SQLITE_DEFAULT_WAL_AUTOCHECKPOINT); opendb_out: if( db ){ assert( db->mutex!=0 || isThreadsafe==0 || sqlite3GlobalConfig.bFullMutex==0 ); sqlite3_mutex_leave(db->mutex); } rc = sqlite3_errcode(db); assert( db!=0 || rc==SQLITE_NOMEM ); if( rc==SQLITE_NOMEM ){ sqlite3_close(db); db = 0; }else if( rc!=SQLITE_OK ){ db->magic = SQLITE_MAGIC_SICK; } *ppDb = db; #ifdef SQLITE_ENABLE_SQLLOG if( sqlite3GlobalConfig.xSqllog ){ /* Opening a db handle. Fourth parameter is passed 0. */ void *pArg = sqlite3GlobalConfig.pSqllogArg; sqlite3GlobalConfig.xSqllog(pArg, db, zFilename, 0); } #endif #if defined(SQLITE_HAS_CODEC) if( rc==SQLITE_OK ){ const char *zHexKey = sqlite3_uri_parameter(zOpen, "hexkey"); if( zHexKey && zHexKey[0] ){ u8 iByte; int i; char zKey[40]; for(i=0, iByte=0; imutex); assert( !db->mallocFailed ); rc = createCollation(db, zName, (u8)enc, pCtx, xCompare, xDel); rc = sqlite3ApiExit(db, rc); sqlite3_mutex_leave(db->mutex); return rc; } #ifndef SQLITE_OMIT_UTF16 /* ** Register a new collation sequence with the database handle db. */ SQLITE_API int sqlite3_create_collation16( sqlite3* db, const void *zName, int enc, void* pCtx, int(*xCompare)(void*,int,const void*,int,const void*) ){ int rc = SQLITE_OK; char *zName8; #ifdef SQLITE_ENABLE_API_ARMOR if( !sqlite3SafetyCheckOk(db) || zName==0 ) return SQLITE_MISUSE_BKPT; #endif sqlite3_mutex_enter(db->mutex); assert( !db->mallocFailed ); zName8 = sqlite3Utf16to8(db, zName, -1, SQLITE_UTF16NATIVE); if( zName8 ){ rc = createCollation(db, zName8, (u8)enc, pCtx, xCompare, 0); sqlite3DbFree(db, zName8); } rc = sqlite3ApiExit(db, rc); sqlite3_mutex_leave(db->mutex); return rc; } #endif /* SQLITE_OMIT_UTF16 */ /* ** Register a collation sequence factory callback with the database handle ** db. Replace any previously installed collation sequence factory. */ SQLITE_API int sqlite3_collation_needed( sqlite3 *db, void *pCollNeededArg, void(*xCollNeeded)(void*,sqlite3*,int eTextRep,const char*) ){ #ifdef SQLITE_ENABLE_API_ARMOR if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT; #endif sqlite3_mutex_enter(db->mutex); db->xCollNeeded = xCollNeeded; db->xCollNeeded16 = 0; db->pCollNeededArg = pCollNeededArg; sqlite3_mutex_leave(db->mutex); return SQLITE_OK; } #ifndef SQLITE_OMIT_UTF16 /* ** Register a collation sequence factory callback with the database handle ** db. Replace any previously installed collation sequence factory. */ SQLITE_API int sqlite3_collation_needed16( sqlite3 *db, void *pCollNeededArg, void(*xCollNeeded16)(void*,sqlite3*,int eTextRep,const void*) ){ #ifdef SQLITE_ENABLE_API_ARMOR if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT; #endif sqlite3_mutex_enter(db->mutex); db->xCollNeeded = 0; db->xCollNeeded16 = xCollNeeded16; db->pCollNeededArg = pCollNeededArg; sqlite3_mutex_leave(db->mutex); return SQLITE_OK; } #endif /* SQLITE_OMIT_UTF16 */ #ifndef SQLITE_OMIT_DEPRECATED /* ** This function is now an anachronism. It used to be used to recover from a ** malloc() failure, but SQLite now does this automatically. */ SQLITE_API int sqlite3_global_recover(void){ return SQLITE_OK; } #endif /* ** Test to see whether or not the database connection is in autocommit ** mode. Return TRUE if it is and FALSE if not. Autocommit mode is on ** by default. Autocommit is disabled by a BEGIN statement and reenabled ** by the next COMMIT or ROLLBACK. */ SQLITE_API int sqlite3_get_autocommit(sqlite3 *db){ #ifdef SQLITE_ENABLE_API_ARMOR if( !sqlite3SafetyCheckOk(db) ){ (void)SQLITE_MISUSE_BKPT; return 0; } #endif return db->autoCommit; } /* ** The following routines are substitutes for constants SQLITE_CORRUPT, ** SQLITE_MISUSE, SQLITE_CANTOPEN, SQLITE_NOMEM and possibly other error ** constants. They serve two purposes: ** ** 1. Serve as a convenient place to set a breakpoint in a debugger ** to detect when version error conditions occurs. ** ** 2. Invoke sqlite3_log() to provide the source code location where ** a low-level error is first detected. */ static int reportError(int iErr, int lineno, const char *zType){ sqlite3_log(iErr, "%s at line %d of [%.10s]", zType, lineno, 20+sqlite3_sourceid()); return iErr; } SQLITE_PRIVATE int sqlite3CorruptError(int lineno){ testcase( sqlite3GlobalConfig.xLog!=0 ); return reportError(SQLITE_CORRUPT, lineno, "database corruption"); } SQLITE_PRIVATE int sqlite3MisuseError(int lineno){ testcase( sqlite3GlobalConfig.xLog!=0 ); return reportError(SQLITE_MISUSE, lineno, "misuse"); } SQLITE_PRIVATE int sqlite3CantopenError(int lineno){ testcase( sqlite3GlobalConfig.xLog!=0 ); return reportError(SQLITE_CANTOPEN, lineno, "cannot open file"); } #ifdef SQLITE_DEBUG SQLITE_PRIVATE int sqlite3NomemError(int lineno){ testcase( sqlite3GlobalConfig.xLog!=0 ); return reportError(SQLITE_NOMEM, lineno, "OOM"); } SQLITE_PRIVATE int sqlite3IoerrnomemError(int lineno){ testcase( sqlite3GlobalConfig.xLog!=0 ); return reportError(SQLITE_IOERR_NOMEM, lineno, "I/O OOM error"); } #endif #ifndef SQLITE_OMIT_DEPRECATED /* ** This is a convenience routine that makes sure that all thread-specific ** data for this thread has been deallocated. ** ** SQLite no longer uses thread-specific data so this routine is now a ** no-op. It is retained for historical compatibility. */ SQLITE_API void sqlite3_thread_cleanup(void){ } #endif /* ** Return meta information about a specific column of a database table. ** See comment in sqlite3.h (sqlite.h.in) for details. */ SQLITE_API int sqlite3_table_column_metadata( sqlite3 *db, /* Connection handle */ const char *zDbName, /* Database name or NULL */ const char *zTableName, /* Table name */ const char *zColumnName, /* Column name */ char const **pzDataType, /* OUTPUT: Declared data type */ char const **pzCollSeq, /* OUTPUT: Collation sequence name */ int *pNotNull, /* OUTPUT: True if NOT NULL constraint exists */ int *pPrimaryKey, /* OUTPUT: True if column part of PK */ int *pAutoinc /* OUTPUT: True if column is auto-increment */ ){ int rc; char *zErrMsg = 0; Table *pTab = 0; Column *pCol = 0; int iCol = 0; char const *zDataType = 0; char const *zCollSeq = 0; int notnull = 0; int primarykey = 0; int autoinc = 0; #ifdef SQLITE_ENABLE_API_ARMOR if( !sqlite3SafetyCheckOk(db) || zTableName==0 ){ return SQLITE_MISUSE_BKPT; } #endif /* Ensure the database schema has been loaded */ sqlite3_mutex_enter(db->mutex); sqlite3BtreeEnterAll(db); rc = sqlite3Init(db, &zErrMsg); if( SQLITE_OK!=rc ){ goto error_out; } /* Locate the table in question */ pTab = sqlite3FindTable(db, zTableName, zDbName); if( !pTab || pTab->pSelect ){ pTab = 0; goto error_out; } /* Find the column for which info is requested */ if( zColumnName==0 ){ /* Query for existance of table only */ }else{ for(iCol=0; iColnCol; iCol++){ pCol = &pTab->aCol[iCol]; if( 0==sqlite3StrICmp(pCol->zName, zColumnName) ){ break; } } if( iCol==pTab->nCol ){ if( HasRowid(pTab) && sqlite3IsRowid(zColumnName) ){ iCol = pTab->iPKey; pCol = iCol>=0 ? &pTab->aCol[iCol] : 0; }else{ pTab = 0; goto error_out; } } } /* The following block stores the meta information that will be returned ** to the caller in local variables zDataType, zCollSeq, notnull, primarykey ** and autoinc. At this point there are two possibilities: ** ** 1. The specified column name was rowid", "oid" or "_rowid_" ** and there is no explicitly declared IPK column. ** ** 2. The table is not a view and the column name identified an ** explicitly declared column. Copy meta information from *pCol. */ if( pCol ){ zDataType = sqlite3ColumnType(pCol,0); zCollSeq = pCol->zColl; notnull = pCol->notNull!=0; primarykey = (pCol->colFlags & COLFLAG_PRIMKEY)!=0; autoinc = pTab->iPKey==iCol && (pTab->tabFlags & TF_Autoincrement)!=0; }else{ zDataType = "INTEGER"; primarykey = 1; } if( !zCollSeq ){ zCollSeq = sqlite3StrBINARY; } error_out: sqlite3BtreeLeaveAll(db); /* Whether the function call succeeded or failed, set the output parameters ** to whatever their local counterparts contain. If an error did occur, ** this has the effect of zeroing all output parameters. */ if( pzDataType ) *pzDataType = zDataType; if( pzCollSeq ) *pzCollSeq = zCollSeq; if( pNotNull ) *pNotNull = notnull; if( pPrimaryKey ) *pPrimaryKey = primarykey; if( pAutoinc ) *pAutoinc = autoinc; if( SQLITE_OK==rc && !pTab ){ sqlite3DbFree(db, zErrMsg); zErrMsg = sqlite3MPrintf(db, "no such table column: %s.%s", zTableName, zColumnName); rc = SQLITE_ERROR; } sqlite3ErrorWithMsg(db, rc, (zErrMsg?"%s":0), zErrMsg); sqlite3DbFree(db, zErrMsg); rc = sqlite3ApiExit(db, rc); sqlite3_mutex_leave(db->mutex); return rc; } /* ** Sleep for a little while. Return the amount of time slept. */ SQLITE_API int sqlite3_sleep(int ms){ sqlite3_vfs *pVfs; int rc; pVfs = sqlite3_vfs_find(0); if( pVfs==0 ) return 0; /* This function works in milliseconds, but the underlying OsSleep() ** API uses microseconds. Hence the 1000's. */ rc = (sqlite3OsSleep(pVfs, 1000*ms)/1000); return rc; } /* ** Enable or disable the extended result codes. */ SQLITE_API int sqlite3_extended_result_codes(sqlite3 *db, int onoff){ #ifdef SQLITE_ENABLE_API_ARMOR if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT; #endif sqlite3_mutex_enter(db->mutex); db->errMask = onoff ? 0xffffffff : 0xff; sqlite3_mutex_leave(db->mutex); return SQLITE_OK; } /* ** Invoke the xFileControl method on a particular database. */ SQLITE_API int sqlite3_file_control(sqlite3 *db, const char *zDbName, int op, void *pArg){ int rc = SQLITE_ERROR; Btree *pBtree; #ifdef SQLITE_ENABLE_API_ARMOR if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT; #endif sqlite3_mutex_enter(db->mutex); pBtree = sqlite3DbNameToBtree(db, zDbName); if( pBtree ){ Pager *pPager; sqlite3_file *fd; sqlite3BtreeEnter(pBtree); pPager = sqlite3BtreePager(pBtree); assert( pPager!=0 ); fd = sqlite3PagerFile(pPager); assert( fd!=0 ); if( op==SQLITE_FCNTL_FILE_POINTER ){ *(sqlite3_file**)pArg = fd; rc = SQLITE_OK; }else if( op==SQLITE_FCNTL_VFS_POINTER ){ *(sqlite3_vfs**)pArg = sqlite3PagerVfs(pPager); rc = SQLITE_OK; }else if( op==SQLITE_FCNTL_JOURNAL_POINTER ){ *(sqlite3_file**)pArg = sqlite3PagerJrnlFile(pPager); rc = SQLITE_OK; }else if( fd->pMethods ){ rc = sqlite3OsFileControl(fd, op, pArg); }else{ rc = SQLITE_NOTFOUND; } sqlite3BtreeLeave(pBtree); } sqlite3_mutex_leave(db->mutex); return rc; } /* ** Interface to the testing logic. */ SQLITE_API int sqlite3_test_control(int op, ...){ int rc = 0; #ifdef SQLITE_OMIT_BUILTIN_TEST UNUSED_PARAMETER(op); #else va_list ap; va_start(ap, op); switch( op ){ /* ** Save the current state of the PRNG. */ case SQLITE_TESTCTRL_PRNG_SAVE: { sqlite3PrngSaveState(); break; } /* ** Restore the state of the PRNG to the last state saved using ** PRNG_SAVE. If PRNG_SAVE has never before been called, then ** this verb acts like PRNG_RESET. */ case SQLITE_TESTCTRL_PRNG_RESTORE: { sqlite3PrngRestoreState(); break; } /* ** Reset the PRNG back to its uninitialized state. The next call ** to sqlite3_randomness() will reseed the PRNG using a single call ** to the xRandomness method of the default VFS. */ case SQLITE_TESTCTRL_PRNG_RESET: { sqlite3_randomness(0,0); break; } /* ** sqlite3_test_control(BITVEC_TEST, size, program) ** ** Run a test against a Bitvec object of size. The program argument ** is an array of integers that defines the test. Return -1 on a ** memory allocation error, 0 on success, or non-zero for an error. ** See the sqlite3BitvecBuiltinTest() for additional information. */ case SQLITE_TESTCTRL_BITVEC_TEST: { int sz = va_arg(ap, int); int *aProg = va_arg(ap, int*); rc = sqlite3BitvecBuiltinTest(sz, aProg); break; } /* ** sqlite3_test_control(FAULT_INSTALL, xCallback) ** ** Arrange to invoke xCallback() whenever sqlite3FaultSim() is called, ** if xCallback is not NULL. ** ** As a test of the fault simulator mechanism itself, sqlite3FaultSim(0) ** is called immediately after installing the new callback and the return ** value from sqlite3FaultSim(0) becomes the return from ** sqlite3_test_control(). */ case SQLITE_TESTCTRL_FAULT_INSTALL: { /* MSVC is picky about pulling func ptrs from va lists. ** http://support.microsoft.com/kb/47961 ** sqlite3GlobalConfig.xTestCallback = va_arg(ap, int(*)(int)); */ typedef int(*TESTCALLBACKFUNC_t)(int); sqlite3GlobalConfig.xTestCallback = va_arg(ap, TESTCALLBACKFUNC_t); rc = sqlite3FaultSim(0); break; } /* ** sqlite3_test_control(BENIGN_MALLOC_HOOKS, xBegin, xEnd) ** ** Register hooks to call to indicate which malloc() failures ** are benign. */ case SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS: { typedef void (*void_function)(void); void_function xBenignBegin; void_function xBenignEnd; xBenignBegin = va_arg(ap, void_function); xBenignEnd = va_arg(ap, void_function); sqlite3BenignMallocHooks(xBenignBegin, xBenignEnd); break; } /* ** sqlite3_test_control(SQLITE_TESTCTRL_PENDING_BYTE, unsigned int X) ** ** Set the PENDING byte to the value in the argument, if X>0. ** Make no changes if X==0. Return the value of the pending byte ** as it existing before this routine was called. ** ** IMPORTANT: Changing the PENDING byte from 0x40000000 results in ** an incompatible database file format. Changing the PENDING byte ** while any database connection is open results in undefined and ** deleterious behavior. */ case SQLITE_TESTCTRL_PENDING_BYTE: { rc = PENDING_BYTE; #ifndef SQLITE_OMIT_WSD { unsigned int newVal = va_arg(ap, unsigned int); if( newVal ) sqlite3PendingByte = newVal; } #endif break; } /* ** sqlite3_test_control(SQLITE_TESTCTRL_ASSERT, int X) ** ** This action provides a run-time test to see whether or not ** assert() was enabled at compile-time. If X is true and assert() ** is enabled, then the return value is true. If X is true and ** assert() is disabled, then the return value is zero. If X is ** false and assert() is enabled, then the assertion fires and the ** process aborts. If X is false and assert() is disabled, then the ** return value is zero. */ case SQLITE_TESTCTRL_ASSERT: { volatile int x = 0; assert( /*side-effects-ok*/ (x = va_arg(ap,int))!=0 ); rc = x; break; } /* ** sqlite3_test_control(SQLITE_TESTCTRL_ALWAYS, int X) ** ** This action provides a run-time test to see how the ALWAYS and ** NEVER macros were defined at compile-time. ** ** The return value is ALWAYS(X). ** ** The recommended test is X==2. If the return value is 2, that means ** ALWAYS() and NEVER() are both no-op pass-through macros, which is the ** default setting. If the return value is 1, then ALWAYS() is either ** hard-coded to true or else it asserts if its argument is false. ** The first behavior (hard-coded to true) is the case if ** SQLITE_TESTCTRL_ASSERT shows that assert() is disabled and the second ** behavior (assert if the argument to ALWAYS() is false) is the case if ** SQLITE_TESTCTRL_ASSERT shows that assert() is enabled. ** ** The run-time test procedure might look something like this: ** ** if( sqlite3_test_control(SQLITE_TESTCTRL_ALWAYS, 2)==2 ){ ** // ALWAYS() and NEVER() are no-op pass-through macros ** }else if( sqlite3_test_control(SQLITE_TESTCTRL_ASSERT, 1) ){ ** // ALWAYS(x) asserts that x is true. NEVER(x) asserts x is false. ** }else{ ** // ALWAYS(x) is a constant 1. NEVER(x) is a constant 0. ** } */ case SQLITE_TESTCTRL_ALWAYS: { int x = va_arg(ap,int); rc = ALWAYS(x); break; } /* ** sqlite3_test_control(SQLITE_TESTCTRL_BYTEORDER); ** ** The integer returned reveals the byte-order of the computer on which ** SQLite is running: ** ** 1 big-endian, determined at run-time ** 10 little-endian, determined at run-time ** 432101 big-endian, determined at compile-time ** 123410 little-endian, determined at compile-time */ case SQLITE_TESTCTRL_BYTEORDER: { rc = SQLITE_BYTEORDER*100 + SQLITE_LITTLEENDIAN*10 + SQLITE_BIGENDIAN; break; } /* sqlite3_test_control(SQLITE_TESTCTRL_RESERVE, sqlite3 *db, int N) ** ** Set the nReserve size to N for the main database on the database ** connection db. */ case SQLITE_TESTCTRL_RESERVE: { sqlite3 *db = va_arg(ap, sqlite3*); int x = va_arg(ap,int); sqlite3_mutex_enter(db->mutex); sqlite3BtreeSetPageSize(db->aDb[0].pBt, 0, x, 0); sqlite3_mutex_leave(db->mutex); break; } /* sqlite3_test_control(SQLITE_TESTCTRL_OPTIMIZATIONS, sqlite3 *db, int N) ** ** Enable or disable various optimizations for testing purposes. The ** argument N is a bitmask of optimizations to be disabled. For normal ** operation N should be 0. The idea is that a test program (like the ** SQL Logic Test or SLT test module) can run the same SQL multiple times ** with various optimizations disabled to verify that the same answer ** is obtained in every case. */ case SQLITE_TESTCTRL_OPTIMIZATIONS: { sqlite3 *db = va_arg(ap, sqlite3*); db->dbOptFlags = (u16)(va_arg(ap, int) & 0xffff); break; } #ifdef SQLITE_N_KEYWORD /* sqlite3_test_control(SQLITE_TESTCTRL_ISKEYWORD, const char *zWord) ** ** If zWord is a keyword recognized by the parser, then return the ** number of keywords. Or if zWord is not a keyword, return 0. ** ** This test feature is only available in the amalgamation since ** the SQLITE_N_KEYWORD macro is not defined in this file if SQLite ** is built using separate source files. */ case SQLITE_TESTCTRL_ISKEYWORD: { const char *zWord = va_arg(ap, const char*); int n = sqlite3Strlen30(zWord); rc = (sqlite3KeywordCode((u8*)zWord, n)!=TK_ID) ? SQLITE_N_KEYWORD : 0; break; } #endif /* sqlite3_test_control(SQLITE_TESTCTRL_SCRATCHMALLOC, sz, &pNew, pFree); ** ** Pass pFree into sqlite3ScratchFree(). ** If sz>0 then allocate a scratch buffer into pNew. */ case SQLITE_TESTCTRL_SCRATCHMALLOC: { void *pFree, **ppNew; int sz; sz = va_arg(ap, int); ppNew = va_arg(ap, void**); pFree = va_arg(ap, void*); if( sz ) *ppNew = sqlite3ScratchMalloc(sz); sqlite3ScratchFree(pFree); break; } /* sqlite3_test_control(SQLITE_TESTCTRL_LOCALTIME_FAULT, int onoff); ** ** If parameter onoff is non-zero, configure the wrappers so that all ** subsequent calls to localtime() and variants fail. If onoff is zero, ** undo this setting. */ case SQLITE_TESTCTRL_LOCALTIME_FAULT: { sqlite3GlobalConfig.bLocaltimeFault = va_arg(ap, int); break; } /* sqlite3_test_control(SQLITE_TESTCTRL_NEVER_CORRUPT, int); ** ** Set or clear a flag that indicates that the database file is always well- ** formed and never corrupt. This flag is clear by default, indicating that ** database files might have arbitrary corruption. Setting the flag during ** testing causes certain assert() statements in the code to be activated ** that demonstrat invariants on well-formed database files. */ case SQLITE_TESTCTRL_NEVER_CORRUPT: { sqlite3GlobalConfig.neverCorrupt = va_arg(ap, int); break; } /* Set the threshold at which OP_Once counters reset back to zero. ** By default this is 0x7ffffffe (over 2 billion), but that value is ** too big to test in a reasonable amount of time, so this control is ** provided to set a small and easily reachable reset value. */ case SQLITE_TESTCTRL_ONCE_RESET_THRESHOLD: { sqlite3GlobalConfig.iOnceResetThreshold = va_arg(ap, int); break; } /* sqlite3_test_control(SQLITE_TESTCTRL_VDBE_COVERAGE, xCallback, ptr); ** ** Set the VDBE coverage callback function to xCallback with context ** pointer ptr. */ case SQLITE_TESTCTRL_VDBE_COVERAGE: { #ifdef SQLITE_VDBE_COVERAGE typedef void (*branch_callback)(void*,int,u8,u8); sqlite3GlobalConfig.xVdbeBranch = va_arg(ap,branch_callback); sqlite3GlobalConfig.pVdbeBranchArg = va_arg(ap,void*); #endif break; } /* sqlite3_test_control(SQLITE_TESTCTRL_SORTER_MMAP, db, nMax); */ case SQLITE_TESTCTRL_SORTER_MMAP: { sqlite3 *db = va_arg(ap, sqlite3*); db->nMaxSorterMmap = va_arg(ap, int); break; } /* sqlite3_test_control(SQLITE_TESTCTRL_ISINIT); ** ** Return SQLITE_OK if SQLite has been initialized and SQLITE_ERROR if ** not. */ case SQLITE_TESTCTRL_ISINIT: { if( sqlite3GlobalConfig.isInit==0 ) rc = SQLITE_ERROR; break; } /* sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, db, dbName, onOff, tnum); ** ** This test control is used to create imposter tables. "db" is a pointer ** to the database connection. dbName is the database name (ex: "main" or ** "temp") which will receive the imposter. "onOff" turns imposter mode on ** or off. "tnum" is the root page of the b-tree to which the imposter ** table should connect. ** ** Enable imposter mode only when the schema has already been parsed. Then ** run a single CREATE TABLE statement to construct the imposter table in ** the parsed schema. Then turn imposter mode back off again. ** ** If onOff==0 and tnum>0 then reset the schema for all databases, causing ** the schema to be reparsed the next time it is needed. This has the ** effect of erasing all imposter tables. */ case SQLITE_TESTCTRL_IMPOSTER: { sqlite3 *db = va_arg(ap, sqlite3*); sqlite3_mutex_enter(db->mutex); db->init.iDb = sqlite3FindDbName(db, va_arg(ap,const char*)); db->init.busy = db->init.imposterTable = va_arg(ap,int); db->init.newTnum = va_arg(ap,int); if( db->init.busy==0 && db->init.newTnum>0 ){ sqlite3ResetAllSchemasOfConnection(db); } sqlite3_mutex_leave(db->mutex); break; } } va_end(ap); #endif /* SQLITE_OMIT_BUILTIN_TEST */ return rc; } /* ** This is a utility routine, useful to VFS implementations, that checks ** to see if a database file was a URI that contained a specific query ** parameter, and if so obtains the value of the query parameter. ** ** The zFilename argument is the filename pointer passed into the xOpen() ** method of a VFS implementation. The zParam argument is the name of the ** query parameter we seek. This routine returns the value of the zParam ** parameter if it exists. If the parameter does not exist, this routine ** returns a NULL pointer. */ SQLITE_API const char *sqlite3_uri_parameter(const char *zFilename, const char *zParam){ if( zFilename==0 || zParam==0 ) return 0; zFilename += sqlite3Strlen30(zFilename) + 1; while( zFilename[0] ){ int x = strcmp(zFilename, zParam); zFilename += sqlite3Strlen30(zFilename) + 1; if( x==0 ) return zFilename; zFilename += sqlite3Strlen30(zFilename) + 1; } return 0; } /* ** Return a boolean value for a query parameter. */ SQLITE_API int sqlite3_uri_boolean(const char *zFilename, const char *zParam, int bDflt){ const char *z = sqlite3_uri_parameter(zFilename, zParam); bDflt = bDflt!=0; return z ? sqlite3GetBoolean(z, bDflt) : bDflt; } /* ** Return a 64-bit integer value for a query parameter. */ SQLITE_API sqlite3_int64 sqlite3_uri_int64( const char *zFilename, /* Filename as passed to xOpen */ const char *zParam, /* URI parameter sought */ sqlite3_int64 bDflt /* return if parameter is missing */ ){ const char *z = sqlite3_uri_parameter(zFilename, zParam); sqlite3_int64 v; if( z && sqlite3DecOrHexToI64(z, &v)==SQLITE_OK ){ bDflt = v; } return bDflt; } /* ** Return the Btree pointer identified by zDbName. Return NULL if not found. */ SQLITE_PRIVATE Btree *sqlite3DbNameToBtree(sqlite3 *db, const char *zDbName){ int i; for(i=0; inDb; i++){ if( db->aDb[i].pBt && (zDbName==0 || sqlite3StrICmp(zDbName, db->aDb[i].zDbSName)==0) ){ return db->aDb[i].pBt; } } return 0; } /* ** Return the filename of the database associated with a database ** connection. */ SQLITE_API const char *sqlite3_db_filename(sqlite3 *db, const char *zDbName){ Btree *pBt; #ifdef SQLITE_ENABLE_API_ARMOR if( !sqlite3SafetyCheckOk(db) ){ (void)SQLITE_MISUSE_BKPT; return 0; } #endif pBt = sqlite3DbNameToBtree(db, zDbName); return pBt ? sqlite3BtreeGetFilename(pBt) : 0; } /* ** Return 1 if database is read-only or 0 if read/write. Return -1 if ** no such database exists. */ SQLITE_API int sqlite3_db_readonly(sqlite3 *db, const char *zDbName){ Btree *pBt; #ifdef SQLITE_ENABLE_API_ARMOR if( !sqlite3SafetyCheckOk(db) ){ (void)SQLITE_MISUSE_BKPT; return -1; } #endif pBt = sqlite3DbNameToBtree(db, zDbName); return pBt ? sqlite3BtreeIsReadonly(pBt) : -1; } #ifdef SQLITE_ENABLE_SNAPSHOT /* ** Obtain a snapshot handle for the snapshot of database zDb currently ** being read by handle db. */ SQLITE_API int sqlite3_snapshot_get( sqlite3 *db, const char *zDb, sqlite3_snapshot **ppSnapshot ){ int rc = SQLITE_ERROR; #ifndef SQLITE_OMIT_WAL int iDb; #ifdef SQLITE_ENABLE_API_ARMOR if( !sqlite3SafetyCheckOk(db) ){ return SQLITE_MISUSE_BKPT; } #endif sqlite3_mutex_enter(db->mutex); iDb = sqlite3FindDbName(db, zDb); if( iDb==0 || iDb>1 ){ Btree *pBt = db->aDb[iDb].pBt; if( 0==sqlite3BtreeIsInTrans(pBt) ){ rc = sqlite3BtreeBeginTrans(pBt, 0); if( rc==SQLITE_OK ){ rc = sqlite3PagerSnapshotGet(sqlite3BtreePager(pBt), ppSnapshot); } } } sqlite3_mutex_leave(db->mutex); #endif /* SQLITE_OMIT_WAL */ return rc; } /* ** Open a read-transaction on the snapshot idendified by pSnapshot. */ SQLITE_API int sqlite3_snapshot_open( sqlite3 *db, const char *zDb, sqlite3_snapshot *pSnapshot ){ int rc = SQLITE_ERROR; #ifndef SQLITE_OMIT_WAL #ifdef SQLITE_ENABLE_API_ARMOR if( !sqlite3SafetyCheckOk(db) ){ return SQLITE_MISUSE_BKPT; } #endif sqlite3_mutex_enter(db->mutex); if( db->autoCommit==0 ){ int iDb; iDb = sqlite3FindDbName(db, zDb); if( iDb==0 || iDb>1 ){ Btree *pBt = db->aDb[iDb].pBt; if( 0==sqlite3BtreeIsInReadTrans(pBt) ){ rc = sqlite3PagerSnapshotOpen(sqlite3BtreePager(pBt), pSnapshot); if( rc==SQLITE_OK ){ rc = sqlite3BtreeBeginTrans(pBt, 0); sqlite3PagerSnapshotOpen(sqlite3BtreePager(pBt), 0); } } } } sqlite3_mutex_leave(db->mutex); #endif /* SQLITE_OMIT_WAL */ return rc; } /* ** Free a snapshot handle obtained from sqlite3_snapshot_get(). */ SQLITE_API void sqlite3_snapshot_free(sqlite3_snapshot *pSnapshot){ sqlite3_free(pSnapshot); } #endif /* SQLITE_ENABLE_SNAPSHOT */ /************** End of main.c ************************************************/ /************** Begin file notify.c ******************************************/ /* ** 2009 March 3 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ************************************************************************* ** ** This file contains the implementation of the sqlite3_unlock_notify() ** API method and its associated functionality. */ /* #include "sqliteInt.h" */ /* #include "btreeInt.h" */ /* Omit this entire file if SQLITE_ENABLE_UNLOCK_NOTIFY is not defined. */ #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY /* ** Public interfaces: ** ** sqlite3ConnectionBlocked() ** sqlite3ConnectionUnlocked() ** sqlite3ConnectionClosed() ** sqlite3_unlock_notify() */ #define assertMutexHeld() \ assert( sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER)) ) /* ** Head of a linked list of all sqlite3 objects created by this process ** for which either sqlite3.pBlockingConnection or sqlite3.pUnlockConnection ** is not NULL. This variable may only accessed while the STATIC_MASTER ** mutex is held. */ static sqlite3 *SQLITE_WSD sqlite3BlockedList = 0; #ifndef NDEBUG /* ** This function is a complex assert() that verifies the following ** properties of the blocked connections list: ** ** 1) Each entry in the list has a non-NULL value for either ** pUnlockConnection or pBlockingConnection, or both. ** ** 2) All entries in the list that share a common value for ** xUnlockNotify are grouped together. ** ** 3) If the argument db is not NULL, then none of the entries in the ** blocked connections list have pUnlockConnection or pBlockingConnection ** set to db. This is used when closing connection db. */ static void checkListProperties(sqlite3 *db){ sqlite3 *p; for(p=sqlite3BlockedList; p; p=p->pNextBlocked){ int seen = 0; sqlite3 *p2; /* Verify property (1) */ assert( p->pUnlockConnection || p->pBlockingConnection ); /* Verify property (2) */ for(p2=sqlite3BlockedList; p2!=p; p2=p2->pNextBlocked){ if( p2->xUnlockNotify==p->xUnlockNotify ) seen = 1; assert( p2->xUnlockNotify==p->xUnlockNotify || !seen ); assert( db==0 || p->pUnlockConnection!=db ); assert( db==0 || p->pBlockingConnection!=db ); } } } #else # define checkListProperties(x) #endif /* ** Remove connection db from the blocked connections list. If connection ** db is not currently a part of the list, this function is a no-op. */ static void removeFromBlockedList(sqlite3 *db){ sqlite3 **pp; assertMutexHeld(); for(pp=&sqlite3BlockedList; *pp; pp = &(*pp)->pNextBlocked){ if( *pp==db ){ *pp = (*pp)->pNextBlocked; break; } } } /* ** Add connection db to the blocked connections list. It is assumed ** that it is not already a part of the list. */ static void addToBlockedList(sqlite3 *db){ sqlite3 **pp; assertMutexHeld(); for( pp=&sqlite3BlockedList; *pp && (*pp)->xUnlockNotify!=db->xUnlockNotify; pp=&(*pp)->pNextBlocked ); db->pNextBlocked = *pp; *pp = db; } /* ** Obtain the STATIC_MASTER mutex. */ static void enterMutex(void){ sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER)); checkListProperties(0); } /* ** Release the STATIC_MASTER mutex. */ static void leaveMutex(void){ assertMutexHeld(); checkListProperties(0); sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER)); } /* ** Register an unlock-notify callback. ** ** This is called after connection "db" has attempted some operation ** but has received an SQLITE_LOCKED error because another connection ** (call it pOther) in the same process was busy using the same shared ** cache. pOther is found by looking at db->pBlockingConnection. ** ** If there is no blocking connection, the callback is invoked immediately, ** before this routine returns. ** ** If pOther is already blocked on db, then report SQLITE_LOCKED, to indicate ** a deadlock. ** ** Otherwise, make arrangements to invoke xNotify when pOther drops ** its locks. ** ** Each call to this routine overrides any prior callbacks registered ** on the same "db". If xNotify==0 then any prior callbacks are immediately ** cancelled. */ SQLITE_API int sqlite3_unlock_notify( sqlite3 *db, void (*xNotify)(void **, int), void *pArg ){ int rc = SQLITE_OK; sqlite3_mutex_enter(db->mutex); enterMutex(); if( xNotify==0 ){ removeFromBlockedList(db); db->pBlockingConnection = 0; db->pUnlockConnection = 0; db->xUnlockNotify = 0; db->pUnlockArg = 0; }else if( 0==db->pBlockingConnection ){ /* The blocking transaction has been concluded. Or there never was a ** blocking transaction. In either case, invoke the notify callback ** immediately. */ xNotify(&pArg, 1); }else{ sqlite3 *p; for(p=db->pBlockingConnection; p && p!=db; p=p->pUnlockConnection){} if( p ){ rc = SQLITE_LOCKED; /* Deadlock detected. */ }else{ db->pUnlockConnection = db->pBlockingConnection; db->xUnlockNotify = xNotify; db->pUnlockArg = pArg; removeFromBlockedList(db); addToBlockedList(db); } } leaveMutex(); assert( !db->mallocFailed ); sqlite3ErrorWithMsg(db, rc, (rc?"database is deadlocked":0)); sqlite3_mutex_leave(db->mutex); return rc; } /* ** This function is called while stepping or preparing a statement ** associated with connection db. The operation will return SQLITE_LOCKED ** to the user because it requires a lock that will not be available ** until connection pBlocker concludes its current transaction. */ SQLITE_PRIVATE void sqlite3ConnectionBlocked(sqlite3 *db, sqlite3 *pBlocker){ enterMutex(); if( db->pBlockingConnection==0 && db->pUnlockConnection==0 ){ addToBlockedList(db); } db->pBlockingConnection = pBlocker; leaveMutex(); } /* ** This function is called when ** the transaction opened by database db has just finished. Locks held ** by database connection db have been released. ** ** This function loops through each entry in the blocked connections ** list and does the following: ** ** 1) If the sqlite3.pBlockingConnection member of a list entry is ** set to db, then set pBlockingConnection=0. ** ** 2) If the sqlite3.pUnlockConnection member of a list entry is ** set to db, then invoke the configured unlock-notify callback and ** set pUnlockConnection=0. ** ** 3) If the two steps above mean that pBlockingConnection==0 and ** pUnlockConnection==0, remove the entry from the blocked connections ** list. */ SQLITE_PRIVATE void sqlite3ConnectionUnlocked(sqlite3 *db){ void (*xUnlockNotify)(void **, int) = 0; /* Unlock-notify cb to invoke */ int nArg = 0; /* Number of entries in aArg[] */ sqlite3 **pp; /* Iterator variable */ void **aArg; /* Arguments to the unlock callback */ void **aDyn = 0; /* Dynamically allocated space for aArg[] */ void *aStatic[16]; /* Starter space for aArg[]. No malloc required */ aArg = aStatic; enterMutex(); /* Enter STATIC_MASTER mutex */ /* This loop runs once for each entry in the blocked-connections list. */ for(pp=&sqlite3BlockedList; *pp; /* no-op */ ){ sqlite3 *p = *pp; /* Step 1. */ if( p->pBlockingConnection==db ){ p->pBlockingConnection = 0; } /* Step 2. */ if( p->pUnlockConnection==db ){ assert( p->xUnlockNotify ); if( p->xUnlockNotify!=xUnlockNotify && nArg!=0 ){ xUnlockNotify(aArg, nArg); nArg = 0; } sqlite3BeginBenignMalloc(); assert( aArg==aDyn || (aDyn==0 && aArg==aStatic) ); assert( nArg<=(int)ArraySize(aStatic) || aArg==aDyn ); if( (!aDyn && nArg==(int)ArraySize(aStatic)) || (aDyn && nArg==(int)(sqlite3MallocSize(aDyn)/sizeof(void*))) ){ /* The aArg[] array needs to grow. */ void **pNew = (void **)sqlite3Malloc(nArg*sizeof(void *)*2); if( pNew ){ memcpy(pNew, aArg, nArg*sizeof(void *)); sqlite3_free(aDyn); aDyn = aArg = pNew; }else{ /* This occurs when the array of context pointers that need to ** be passed to the unlock-notify callback is larger than the ** aStatic[] array allocated on the stack and the attempt to ** allocate a larger array from the heap has failed. ** ** This is a difficult situation to handle. Returning an error ** code to the caller is insufficient, as even if an error code ** is returned the transaction on connection db will still be ** closed and the unlock-notify callbacks on blocked connections ** will go unissued. This might cause the application to wait ** indefinitely for an unlock-notify callback that will never ** arrive. ** ** Instead, invoke the unlock-notify callback with the context ** array already accumulated. We can then clear the array and ** begin accumulating any further context pointers without ** requiring any dynamic allocation. This is sub-optimal because ** it means that instead of one callback with a large array of ** context pointers the application will receive two or more ** callbacks with smaller arrays of context pointers, which will ** reduce the applications ability to prioritize multiple ** connections. But it is the best that can be done under the ** circumstances. */ xUnlockNotify(aArg, nArg); nArg = 0; } } sqlite3EndBenignMalloc(); aArg[nArg++] = p->pUnlockArg; xUnlockNotify = p->xUnlockNotify; p->pUnlockConnection = 0; p->xUnlockNotify = 0; p->pUnlockArg = 0; } /* Step 3. */ if( p->pBlockingConnection==0 && p->pUnlockConnection==0 ){ /* Remove connection p from the blocked connections list. */ *pp = p->pNextBlocked; p->pNextBlocked = 0; }else{ pp = &p->pNextBlocked; } } if( nArg!=0 ){ xUnlockNotify(aArg, nArg); } sqlite3_free(aDyn); leaveMutex(); /* Leave STATIC_MASTER mutex */ } /* ** This is called when the database connection passed as an argument is ** being closed. The connection is removed from the blocked list. */ SQLITE_PRIVATE void sqlite3ConnectionClosed(sqlite3 *db){ sqlite3ConnectionUnlocked(db); enterMutex(); removeFromBlockedList(db); checkListProperties(db); leaveMutex(); } #endif /************** End of notify.c **********************************************/ /************** Begin file fts3.c ********************************************/ /* ** 2006 Oct 10 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ****************************************************************************** ** ** This is an SQLite module implementing full-text search. */ /* ** The code in this file is only compiled if: ** ** * The FTS3 module is being built as an extension ** (in which case SQLITE_CORE is not defined), or ** ** * The FTS3 module is being built into the core of ** SQLite (in which case SQLITE_ENABLE_FTS3 is defined). */ /* The full-text index is stored in a series of b+tree (-like) ** structures called segments which map terms to doclists. The ** structures are like b+trees in layout, but are constructed from the ** bottom up in optimal fashion and are not updatable. Since trees ** are built from the bottom up, things will be described from the ** bottom up. ** ** **** Varints **** ** The basic unit of encoding is a variable-length integer called a ** varint. We encode variable-length integers in little-endian order ** using seven bits * per byte as follows: ** ** KEY: ** A = 0xxxxxxx 7 bits of data and one flag bit ** B = 1xxxxxxx 7 bits of data and one flag bit ** ** 7 bits - A ** 14 bits - BA ** 21 bits - BBA ** and so on. ** ** This is similar in concept to how sqlite encodes "varints" but ** the encoding is not the same. SQLite varints are big-endian ** are are limited to 9 bytes in length whereas FTS3 varints are ** little-endian and can be up to 10 bytes in length (in theory). ** ** Example encodings: ** ** 1: 0x01 ** 127: 0x7f ** 128: 0x81 0x00 ** ** **** Document lists **** ** A doclist (document list) holds a docid-sorted list of hits for a ** given term. Doclists hold docids and associated token positions. ** A docid is the unique integer identifier for a single document. ** A position is the index of a word within the document. The first ** word of the document has a position of 0. ** ** FTS3 used to optionally store character offsets using a compile-time ** option. But that functionality is no longer supported. ** ** A doclist is stored like this: ** ** array { ** varint docid; (delta from previous doclist) ** array { (position list for column 0) ** varint position; (2 more than the delta from previous position) ** } ** array { ** varint POS_COLUMN; (marks start of position list for new column) ** varint column; (index of new column) ** array { ** varint position; (2 more than the delta from previous position) ** } ** } ** varint POS_END; (marks end of positions for this document. ** } ** ** Here, array { X } means zero or more occurrences of X, adjacent in ** memory. A "position" is an index of a token in the token stream ** generated by the tokenizer. Note that POS_END and POS_COLUMN occur ** in the same logical place as the position element, and act as sentinals ** ending a position list array. POS_END is 0. POS_COLUMN is 1. ** The positions numbers are not stored literally but rather as two more ** than the difference from the prior position, or the just the position plus ** 2 for the first position. Example: ** ** label: A B C D E F G H I J K ** value: 123 5 9 1 1 14 35 0 234 72 0 ** ** The 123 value is the first docid. For column zero in this document ** there are two matches at positions 3 and 10 (5-2 and 9-2+3). The 1 ** at D signals the start of a new column; the 1 at E indicates that the ** new column is column number 1. There are two positions at 12 and 45 ** (14-2 and 35-2+12). The 0 at H indicate the end-of-document. The ** 234 at I is the delta to next docid (357). It has one position 70 ** (72-2) and then terminates with the 0 at K. ** ** A "position-list" is the list of positions for multiple columns for ** a single docid. A "column-list" is the set of positions for a single ** column. Hence, a position-list consists of one or more column-lists, ** a document record consists of a docid followed by a position-list and ** a doclist consists of one or more document records. ** ** A bare doclist omits the position information, becoming an ** array of varint-encoded docids. ** **** Segment leaf nodes **** ** Segment leaf nodes store terms and doclists, ordered by term. Leaf ** nodes are written using LeafWriter, and read using LeafReader (to ** iterate through a single leaf node's data) and LeavesReader (to ** iterate through a segment's entire leaf layer). Leaf nodes have ** the format: ** ** varint iHeight; (height from leaf level, always 0) ** varint nTerm; (length of first term) ** char pTerm[nTerm]; (content of first term) ** varint nDoclist; (length of term's associated doclist) ** char pDoclist[nDoclist]; (content of doclist) ** array { ** (further terms are delta-encoded) ** varint nPrefix; (length of prefix shared with previous term) ** varint nSuffix; (length of unshared suffix) ** char pTermSuffix[nSuffix];(unshared suffix of next term) ** varint nDoclist; (length of term's associated doclist) ** char pDoclist[nDoclist]; (content of doclist) ** } ** ** Here, array { X } means zero or more occurrences of X, adjacent in ** memory. ** ** Leaf nodes are broken into blocks which are stored contiguously in ** the %_segments table in sorted order. This means that when the end ** of a node is reached, the next term is in the node with the next ** greater node id. ** ** New data is spilled to a new leaf node when the current node ** exceeds LEAF_MAX bytes (default 2048). New data which itself is ** larger than STANDALONE_MIN (default 1024) is placed in a standalone ** node (a leaf node with a single term and doclist). The goal of ** these settings is to pack together groups of small doclists while ** making it efficient to directly access large doclists. The ** assumption is that large doclists represent terms which are more ** likely to be query targets. ** ** TODO(shess) It may be useful for blocking decisions to be more ** dynamic. For instance, it may make more sense to have a 2.5k leaf ** node rather than splitting into 2k and .5k nodes. My intuition is ** that this might extend through 2x or 4x the pagesize. ** ** **** Segment interior nodes **** ** Segment interior nodes store blockids for subtree nodes and terms ** to describe what data is stored by the each subtree. Interior ** nodes are written using InteriorWriter, and read using ** InteriorReader. InteriorWriters are created as needed when ** SegmentWriter creates new leaf nodes, or when an interior node ** itself grows too big and must be split. The format of interior ** nodes: ** ** varint iHeight; (height from leaf level, always >0) ** varint iBlockid; (block id of node's leftmost subtree) ** optional { ** varint nTerm; (length of first term) ** char pTerm[nTerm]; (content of first term) ** array { ** (further terms are delta-encoded) ** varint nPrefix; (length of shared prefix with previous term) ** varint nSuffix; (length of unshared suffix) ** char pTermSuffix[nSuffix]; (unshared suffix of next term) ** } ** } ** ** Here, optional { X } means an optional element, while array { X } ** means zero or more occurrences of X, adjacent in memory. ** ** An interior node encodes n terms separating n+1 subtrees. The ** subtree blocks are contiguous, so only the first subtree's blockid ** is encoded. The subtree at iBlockid will contain all terms less ** than the first term encoded (or all terms if no term is encoded). ** Otherwise, for terms greater than or equal to pTerm[i] but less ** than pTerm[i+1], the subtree for that term will be rooted at ** iBlockid+i. Interior nodes only store enough term data to ** distinguish adjacent children (if the rightmost term of the left ** child is "something", and the leftmost term of the right child is ** "wicked", only "w" is stored). ** ** New data is spilled to a new interior node at the same height when ** the current node exceeds INTERIOR_MAX bytes (default 2048). ** INTERIOR_MIN_TERMS (default 7) keeps large terms from monopolizing ** interior nodes and making the tree too skinny. The interior nodes ** at a given height are naturally tracked by interior nodes at ** height+1, and so on. ** ** **** Segment directory **** ** The segment directory in table %_segdir stores meta-information for ** merging and deleting segments, and also the root node of the ** segment's tree. ** ** The root node is the top node of the segment's tree after encoding ** the entire segment, restricted to ROOT_MAX bytes (default 1024). ** This could be either a leaf node or an interior node. If the top ** node requires more than ROOT_MAX bytes, it is flushed to %_segments ** and a new root interior node is generated (which should always fit ** within ROOT_MAX because it only needs space for 2 varints, the ** height and the blockid of the previous root). ** ** The meta-information in the segment directory is: ** level - segment level (see below) ** idx - index within level ** - (level,idx uniquely identify a segment) ** start_block - first leaf node ** leaves_end_block - last leaf node ** end_block - last block (including interior nodes) ** root - contents of root node ** ** If the root node is a leaf node, then start_block, ** leaves_end_block, and end_block are all 0. ** ** **** Segment merging **** ** To amortize update costs, segments are grouped into levels and ** merged in batches. Each increase in level represents exponentially ** more documents. ** ** New documents (actually, document updates) are tokenized and ** written individually (using LeafWriter) to a level 0 segment, with ** incrementing idx. When idx reaches MERGE_COUNT (default 16), all ** level 0 segments are merged into a single level 1 segment. Level 1 ** is populated like level 0, and eventually MERGE_COUNT level 1 ** segments are merged to a single level 2 segment (representing ** MERGE_COUNT^2 updates), and so on. ** ** A segment merge traverses all segments at a given level in ** parallel, performing a straightforward sorted merge. Since segment ** leaf nodes are written in to the %_segments table in order, this ** merge traverses the underlying sqlite disk structures efficiently. ** After the merge, all segment blocks from the merged level are ** deleted. ** ** MERGE_COUNT controls how often we merge segments. 16 seems to be ** somewhat of a sweet spot for insertion performance. 32 and 64 show ** very similar performance numbers to 16 on insertion, though they're ** a tiny bit slower (perhaps due to more overhead in merge-time ** sorting). 8 is about 20% slower than 16, 4 about 50% slower than ** 16, 2 about 66% slower than 16. ** ** At query time, high MERGE_COUNT increases the number of segments ** which need to be scanned and merged. For instance, with 100k docs ** inserted: ** ** MERGE_COUNT segments ** 16 25 ** 8 12 ** 4 10 ** 2 6 ** ** This appears to have only a moderate impact on queries for very ** frequent terms (which are somewhat dominated by segment merge ** costs), and infrequent and non-existent terms still seem to be fast ** even with many segments. ** ** TODO(shess) That said, it would be nice to have a better query-side ** argument for MERGE_COUNT of 16. Also, it is possible/likely that ** optimizations to things like doclist merging will swing the sweet ** spot around. ** ** ** **** Handling of deletions and updates **** ** Since we're using a segmented structure, with no docid-oriented ** index into the term index, we clearly cannot simply update the term ** index when a document is deleted or updated. For deletions, we ** write an empty doclist (varint(docid) varint(POS_END)), for updates ** we simply write the new doclist. Segment merges overwrite older ** data for a particular docid with newer data, so deletes or updates ** will eventually overtake the earlier data and knock it out. The ** query logic likewise merges doclists so that newer data knocks out ** older data. */ /************** Include fts3Int.h in the middle of fts3.c ********************/ /************** Begin file fts3Int.h *****************************************/ /* ** 2009 Nov 12 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ****************************************************************************** ** */ #ifndef _FTSINT_H #define _FTSINT_H #if !defined(NDEBUG) && !defined(SQLITE_DEBUG) # define NDEBUG 1 #endif /* FTS3/FTS4 require virtual tables */ #ifdef SQLITE_OMIT_VIRTUALTABLE # undef SQLITE_ENABLE_FTS3 # undef SQLITE_ENABLE_FTS4 #endif /* ** FTS4 is really an extension for FTS3. It is enabled using the ** SQLITE_ENABLE_FTS3 macro. But to avoid confusion we also all ** the SQLITE_ENABLE_FTS4 macro to serve as an alisse for SQLITE_ENABLE_FTS3. */ #if defined(SQLITE_ENABLE_FTS4) && !defined(SQLITE_ENABLE_FTS3) # define SQLITE_ENABLE_FTS3 #endif #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) /* If not building as part of the core, include sqlite3ext.h. */ #ifndef SQLITE_CORE /* # include "sqlite3ext.h" */ SQLITE_EXTENSION_INIT3 #endif /* #include "sqlite3.h" */ /************** Include fts3_tokenizer.h in the middle of fts3Int.h **********/ /************** Begin file fts3_tokenizer.h **********************************/ /* ** 2006 July 10 ** ** The author disclaims copyright to this source code. ** ************************************************************************* ** Defines the interface to tokenizers used by fulltext-search. There ** are three basic components: ** ** sqlite3_tokenizer_module is a singleton defining the tokenizer ** interface functions. This is essentially the class structure for ** tokenizers. ** ** sqlite3_tokenizer is used to define a particular tokenizer, perhaps ** including customization information defined at creation time. ** ** sqlite3_tokenizer_cursor is generated by a tokenizer to generate ** tokens from a particular input. */ #ifndef _FTS3_TOKENIZER_H_ #define _FTS3_TOKENIZER_H_ /* TODO(shess) Only used for SQLITE_OK and SQLITE_DONE at this time. ** If tokenizers are to be allowed to call sqlite3_*() functions, then ** we will need a way to register the API consistently. */ /* #include "sqlite3.h" */ /* ** Structures used by the tokenizer interface. When a new tokenizer ** implementation is registered, the caller provides a pointer to ** an sqlite3_tokenizer_module containing pointers to the callback ** functions that make up an implementation. ** ** When an fts3 table is created, it passes any arguments passed to ** the tokenizer clause of the CREATE VIRTUAL TABLE statement to the ** sqlite3_tokenizer_module.xCreate() function of the requested tokenizer ** implementation. The xCreate() function in turn returns an ** sqlite3_tokenizer structure representing the specific tokenizer to ** be used for the fts3 table (customized by the tokenizer clause arguments). ** ** To tokenize an input buffer, the sqlite3_tokenizer_module.xOpen() ** method is called. It returns an sqlite3_tokenizer_cursor object ** that may be used to tokenize a specific input buffer based on ** the tokenization rules supplied by a specific sqlite3_tokenizer ** object. */ typedef struct sqlite3_tokenizer_module sqlite3_tokenizer_module; typedef struct sqlite3_tokenizer sqlite3_tokenizer; typedef struct sqlite3_tokenizer_cursor sqlite3_tokenizer_cursor; struct sqlite3_tokenizer_module { /* ** Structure version. Should always be set to 0 or 1. */ int iVersion; /* ** Create a new tokenizer. The values in the argv[] array are the ** arguments passed to the "tokenizer" clause of the CREATE VIRTUAL ** TABLE statement that created the fts3 table. For example, if ** the following SQL is executed: ** ** CREATE .. USING fts3( ... , tokenizer arg1 arg2) ** ** then argc is set to 2, and the argv[] array contains pointers ** to the strings "arg1" and "arg2". ** ** This method should return either SQLITE_OK (0), or an SQLite error ** code. If SQLITE_OK is returned, then *ppTokenizer should be set ** to point at the newly created tokenizer structure. The generic ** sqlite3_tokenizer.pModule variable should not be initialized by ** this callback. The caller will do so. */ int (*xCreate)( int argc, /* Size of argv array */ const char *const*argv, /* Tokenizer argument strings */ sqlite3_tokenizer **ppTokenizer /* OUT: Created tokenizer */ ); /* ** Destroy an existing tokenizer. The fts3 module calls this method ** exactly once for each successful call to xCreate(). */ int (*xDestroy)(sqlite3_tokenizer *pTokenizer); /* ** Create a tokenizer cursor to tokenize an input buffer. The caller ** is responsible for ensuring that the input buffer remains valid ** until the cursor is closed (using the xClose() method). */ int (*xOpen)( sqlite3_tokenizer *pTokenizer, /* Tokenizer object */ const char *pInput, int nBytes, /* Input buffer */ sqlite3_tokenizer_cursor **ppCursor /* OUT: Created tokenizer cursor */ ); /* ** Destroy an existing tokenizer cursor. The fts3 module calls this ** method exactly once for each successful call to xOpen(). */ int (*xClose)(sqlite3_tokenizer_cursor *pCursor); /* ** Retrieve the next token from the tokenizer cursor pCursor. This ** method should either return SQLITE_OK and set the values of the ** "OUT" variables identified below, or SQLITE_DONE to indicate that ** the end of the buffer has been reached, or an SQLite error code. ** ** *ppToken should be set to point at a buffer containing the ** normalized version of the token (i.e. after any case-folding and/or ** stemming has been performed). *pnBytes should be set to the length ** of this buffer in bytes. The input text that generated the token is ** identified by the byte offsets returned in *piStartOffset and ** *piEndOffset. *piStartOffset should be set to the index of the first ** byte of the token in the input buffer. *piEndOffset should be set ** to the index of the first byte just past the end of the token in ** the input buffer. ** ** The buffer *ppToken is set to point at is managed by the tokenizer ** implementation. It is only required to be valid until the next call ** to xNext() or xClose(). */ /* TODO(shess) current implementation requires pInput to be ** nul-terminated. This should either be fixed, or pInput/nBytes ** should be converted to zInput. */ int (*xNext)( sqlite3_tokenizer_cursor *pCursor, /* Tokenizer cursor */ const char **ppToken, int *pnBytes, /* OUT: Normalized text for token */ int *piStartOffset, /* OUT: Byte offset of token in input buffer */ int *piEndOffset, /* OUT: Byte offset of end of token in input buffer */ int *piPosition /* OUT: Number of tokens returned before this one */ ); /*********************************************************************** ** Methods below this point are only available if iVersion>=1. */ /* ** Configure the language id of a tokenizer cursor. */ int (*xLanguageid)(sqlite3_tokenizer_cursor *pCsr, int iLangid); }; struct sqlite3_tokenizer { const sqlite3_tokenizer_module *pModule; /* The module for this tokenizer */ /* Tokenizer implementations will typically add additional fields */ }; struct sqlite3_tokenizer_cursor { sqlite3_tokenizer *pTokenizer; /* Tokenizer for this cursor. */ /* Tokenizer implementations will typically add additional fields */ }; int fts3_global_term_cnt(int iTerm, int iCol); int fts3_term_cnt(int iTerm, int iCol); #endif /* _FTS3_TOKENIZER_H_ */ /************** End of fts3_tokenizer.h **************************************/ /************** Continuing where we left off in fts3Int.h ********************/ /************** Include fts3_hash.h in the middle of fts3Int.h ***************/ /************** Begin file fts3_hash.h ***************************************/ /* ** 2001 September 22 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ************************************************************************* ** This is the header file for the generic hash-table implementation ** used in SQLite. We've modified it slightly to serve as a standalone ** hash table implementation for the full-text indexing module. ** */ #ifndef _FTS3_HASH_H_ #define _FTS3_HASH_H_ /* Forward declarations of structures. */ typedef struct Fts3Hash Fts3Hash; typedef struct Fts3HashElem Fts3HashElem; /* A complete hash table is an instance of the following structure. ** The internals of this structure are intended to be opaque -- client ** code should not attempt to access or modify the fields of this structure ** directly. Change this structure only by using the routines below. ** However, many of the "procedures" and "functions" for modifying and ** accessing this structure are really macros, so we can't really make ** this structure opaque. */ struct Fts3Hash { char keyClass; /* HASH_INT, _POINTER, _STRING, _BINARY */ char copyKey; /* True if copy of key made on insert */ int count; /* Number of entries in this table */ Fts3HashElem *first; /* The first element of the array */ int htsize; /* Number of buckets in the hash table */ struct _fts3ht { /* the hash table */ int count; /* Number of entries with this hash */ Fts3HashElem *chain; /* Pointer to first entry with this hash */ } *ht; }; /* Each element in the hash table is an instance of the following ** structure. All elements are stored on a single doubly-linked list. ** ** Again, this structure is intended to be opaque, but it can't really ** be opaque because it is used by macros. */ struct Fts3HashElem { Fts3HashElem *next, *prev; /* Next and previous elements in the table */ void *data; /* Data associated with this element */ void *pKey; int nKey; /* Key associated with this element */ }; /* ** There are 2 different modes of operation for a hash table: ** ** FTS3_HASH_STRING pKey points to a string that is nKey bytes long ** (including the null-terminator, if any). Case ** is respected in comparisons. ** ** FTS3_HASH_BINARY pKey points to binary data nKey bytes long. ** memcmp() is used to compare keys. ** ** A copy of the key is made if the copyKey parameter to fts3HashInit is 1. */ #define FTS3_HASH_STRING 1 #define FTS3_HASH_BINARY 2 /* ** Access routines. To delete, insert a NULL pointer. */ SQLITE_PRIVATE void sqlite3Fts3HashInit(Fts3Hash *pNew, char keyClass, char copyKey); SQLITE_PRIVATE void *sqlite3Fts3HashInsert(Fts3Hash*, const void *pKey, int nKey, void *pData); SQLITE_PRIVATE void *sqlite3Fts3HashFind(const Fts3Hash*, const void *pKey, int nKey); SQLITE_PRIVATE void sqlite3Fts3HashClear(Fts3Hash*); SQLITE_PRIVATE Fts3HashElem *sqlite3Fts3HashFindElem(const Fts3Hash *, const void *, int); /* ** Shorthand for the functions above */ #define fts3HashInit sqlite3Fts3HashInit #define fts3HashInsert sqlite3Fts3HashInsert #define fts3HashFind sqlite3Fts3HashFind #define fts3HashClear sqlite3Fts3HashClear #define fts3HashFindElem sqlite3Fts3HashFindElem /* ** Macros for looping over all elements of a hash table. The idiom is ** like this: ** ** Fts3Hash h; ** Fts3HashElem *p; ** ... ** for(p=fts3HashFirst(&h); p; p=fts3HashNext(p)){ ** SomeStructure *pData = fts3HashData(p); ** // do something with pData ** } */ #define fts3HashFirst(H) ((H)->first) #define fts3HashNext(E) ((E)->next) #define fts3HashData(E) ((E)->data) #define fts3HashKey(E) ((E)->pKey) #define fts3HashKeysize(E) ((E)->nKey) /* ** Number of entries in a hash table */ #define fts3HashCount(H) ((H)->count) #endif /* _FTS3_HASH_H_ */ /************** End of fts3_hash.h *******************************************/ /************** Continuing where we left off in fts3Int.h ********************/ /* ** This constant determines the maximum depth of an FTS expression tree ** that the library will create and use. FTS uses recursion to perform ** various operations on the query tree, so the disadvantage of a large ** limit is that it may allow very large queries to use large amounts ** of stack space (perhaps causing a stack overflow). */ #ifndef SQLITE_FTS3_MAX_EXPR_DEPTH # define SQLITE_FTS3_MAX_EXPR_DEPTH 12 #endif /* ** This constant controls how often segments are merged. Once there are ** FTS3_MERGE_COUNT segments of level N, they are merged into a single ** segment of level N+1. */ #define FTS3_MERGE_COUNT 16 /* ** This is the maximum amount of data (in bytes) to store in the ** Fts3Table.pendingTerms hash table. Normally, the hash table is ** populated as documents are inserted/updated/deleted in a transaction ** and used to create a new segment when the transaction is committed. ** However if this limit is reached midway through a transaction, a new ** segment is created and the hash table cleared immediately. */ #define FTS3_MAX_PENDING_DATA (1*1024*1024) /* ** Macro to return the number of elements in an array. SQLite has a ** similar macro called ArraySize(). Use a different name to avoid ** a collision when building an amalgamation with built-in FTS3. */ #define SizeofArray(X) ((int)(sizeof(X)/sizeof(X[0]))) #ifndef MIN # define MIN(x,y) ((x)<(y)?(x):(y)) #endif #ifndef MAX # define MAX(x,y) ((x)>(y)?(x):(y)) #endif /* ** Maximum length of a varint encoded integer. The varint format is different ** from that used by SQLite, so the maximum length is 10, not 9. */ #define FTS3_VARINT_MAX 10 /* ** FTS4 virtual tables may maintain multiple indexes - one index of all terms ** in the document set and zero or more prefix indexes. All indexes are stored ** as one or more b+-trees in the %_segments and %_segdir tables. ** ** It is possible to determine which index a b+-tree belongs to based on the ** value stored in the "%_segdir.level" column. Given this value L, the index ** that the b+-tree belongs to is (L<<10). In other words, all b+-trees with ** level values between 0 and 1023 (inclusive) belong to index 0, all levels ** between 1024 and 2047 to index 1, and so on. ** ** It is considered impossible for an index to use more than 1024 levels. In ** theory though this may happen, but only after at least ** (FTS3_MERGE_COUNT^1024) separate flushes of the pending-terms tables. */ #define FTS3_SEGDIR_MAXLEVEL 1024 #define FTS3_SEGDIR_MAXLEVEL_STR "1024" /* ** The testcase() macro is only used by the amalgamation. If undefined, ** make it a no-op. */ #ifndef testcase # define testcase(X) #endif /* ** Terminator values for position-lists and column-lists. */ #define POS_COLUMN (1) /* Column-list terminator */ #define POS_END (0) /* Position-list terminator */ /* ** This section provides definitions to allow the ** FTS3 extension to be compiled outside of the ** amalgamation. */ #ifndef SQLITE_AMALGAMATION /* ** Macros indicating that conditional expressions are always true or ** false. */ #ifdef SQLITE_COVERAGE_TEST # define ALWAYS(x) (1) # define NEVER(X) (0) #elif defined(SQLITE_DEBUG) # define ALWAYS(x) sqlite3Fts3Always((x)!=0) # define NEVER(x) sqlite3Fts3Never((x)!=0) SQLITE_PRIVATE int sqlite3Fts3Always(int b); SQLITE_PRIVATE int sqlite3Fts3Never(int b); #else # define ALWAYS(x) (x) # define NEVER(x) (x) #endif /* ** Internal types used by SQLite. */ typedef unsigned char u8; /* 1-byte (or larger) unsigned integer */ typedef short int i16; /* 2-byte (or larger) signed integer */ typedef unsigned int u32; /* 4-byte unsigned integer */ typedef sqlite3_uint64 u64; /* 8-byte unsigned integer */ typedef sqlite3_int64 i64; /* 8-byte signed integer */ /* ** Macro used to suppress compiler warnings for unused parameters. */ #define UNUSED_PARAMETER(x) (void)(x) /* ** Activate assert() only if SQLITE_TEST is enabled. */ #if !defined(NDEBUG) && !defined(SQLITE_DEBUG) # define NDEBUG 1 #endif /* ** The TESTONLY macro is used to enclose variable declarations or ** other bits of code that are needed to support the arguments ** within testcase() and assert() macros. */ #if defined(SQLITE_DEBUG) || defined(SQLITE_COVERAGE_TEST) # define TESTONLY(X) X #else # define TESTONLY(X) #endif #endif /* SQLITE_AMALGAMATION */ #ifdef SQLITE_DEBUG SQLITE_PRIVATE int sqlite3Fts3Corrupt(void); # define FTS_CORRUPT_VTAB sqlite3Fts3Corrupt() #else # define FTS_CORRUPT_VTAB SQLITE_CORRUPT_VTAB #endif typedef struct Fts3Table Fts3Table; typedef struct Fts3Cursor Fts3Cursor; typedef struct Fts3Expr Fts3Expr; typedef struct Fts3Phrase Fts3Phrase; typedef struct Fts3PhraseToken Fts3PhraseToken; typedef struct Fts3Doclist Fts3Doclist; typedef struct Fts3SegFilter Fts3SegFilter; typedef struct Fts3DeferredToken Fts3DeferredToken; typedef struct Fts3SegReader Fts3SegReader; typedef struct Fts3MultiSegReader Fts3MultiSegReader; typedef struct MatchinfoBuffer MatchinfoBuffer; /* ** A connection to a fulltext index is an instance of the following ** structure. The xCreate and xConnect methods create an instance ** of this structure and xDestroy and xDisconnect free that instance. ** All other methods receive a pointer to the structure as one of their ** arguments. */ struct Fts3Table { sqlite3_vtab base; /* Base class used by SQLite core */ sqlite3 *db; /* The database connection */ const char *zDb; /* logical database name */ const char *zName; /* virtual table name */ int nColumn; /* number of named columns in virtual table */ char **azColumn; /* column names. malloced */ u8 *abNotindexed; /* True for 'notindexed' columns */ sqlite3_tokenizer *pTokenizer; /* tokenizer for inserts and queries */ char *zContentTbl; /* content=xxx option, or NULL */ char *zLanguageid; /* languageid=xxx option, or NULL */ int nAutoincrmerge; /* Value configured by 'automerge' */ u32 nLeafAdd; /* Number of leaf blocks added this trans */ /* Precompiled statements used by the implementation. Each of these ** statements is run and reset within a single virtual table API call. */ sqlite3_stmt *aStmt[40]; char *zReadExprlist; char *zWriteExprlist; int nNodeSize; /* Soft limit for node size */ u8 bFts4; /* True for FTS4, false for FTS3 */ u8 bHasStat; /* True if %_stat table exists (2==unknown) */ u8 bHasDocsize; /* True if %_docsize table exists */ u8 bDescIdx; /* True if doclists are in reverse order */ u8 bIgnoreSavepoint; /* True to ignore xSavepoint invocations */ int nPgsz; /* Page size for host database */ char *zSegmentsTbl; /* Name of %_segments table */ sqlite3_blob *pSegments; /* Blob handle open on %_segments table */ /* ** The following array of hash tables is used to buffer pending index ** updates during transactions. All pending updates buffered at any one ** time must share a common language-id (see the FTS4 langid= feature). ** The current language id is stored in variable iPrevLangid. ** ** A single FTS4 table may have multiple full-text indexes. For each index ** there is an entry in the aIndex[] array. Index 0 is an index of all the ** terms that appear in the document set. Each subsequent index in aIndex[] ** is an index of prefixes of a specific length. ** ** Variable nPendingData contains an estimate the memory consumed by the ** pending data structures, including hash table overhead, but not including ** malloc overhead. When nPendingData exceeds nMaxPendingData, all hash ** tables are flushed to disk. Variable iPrevDocid is the docid of the most ** recently inserted record. */ int nIndex; /* Size of aIndex[] */ struct Fts3Index { int nPrefix; /* Prefix length (0 for main terms index) */ Fts3Hash hPending; /* Pending terms table for this index */ } *aIndex; int nMaxPendingData; /* Max pending data before flush to disk */ int nPendingData; /* Current bytes of pending data */ sqlite_int64 iPrevDocid; /* Docid of most recently inserted document */ int iPrevLangid; /* Langid of recently inserted document */ int bPrevDelete; /* True if last operation was a delete */ #if defined(SQLITE_DEBUG) || defined(SQLITE_COVERAGE_TEST) /* State variables used for validating that the transaction control ** methods of the virtual table are called at appropriate times. These ** values do not contribute to FTS functionality; they are used for ** verifying the operation of the SQLite core. */ int inTransaction; /* True after xBegin but before xCommit/xRollback */ int mxSavepoint; /* Largest valid xSavepoint integer */ #endif #ifdef SQLITE_TEST /* True to disable the incremental doclist optimization. This is controled ** by special insert command 'test-no-incr-doclist'. */ int bNoIncrDoclist; #endif }; /* ** When the core wants to read from the virtual table, it creates a ** virtual table cursor (an instance of the following structure) using ** the xOpen method. Cursors are destroyed using the xClose method. */ struct Fts3Cursor { sqlite3_vtab_cursor base; /* Base class used by SQLite core */ i16 eSearch; /* Search strategy (see below) */ u8 isEof; /* True if at End Of Results */ u8 isRequireSeek; /* True if must seek pStmt to %_content row */ sqlite3_stmt *pStmt; /* Prepared statement in use by the cursor */ Fts3Expr *pExpr; /* Parsed MATCH query string */ int iLangid; /* Language being queried for */ int nPhrase; /* Number of matchable phrases in query */ Fts3DeferredToken *pDeferred; /* Deferred search tokens, if any */ sqlite3_int64 iPrevId; /* Previous id read from aDoclist */ char *pNextId; /* Pointer into the body of aDoclist */ char *aDoclist; /* List of docids for full-text queries */ int nDoclist; /* Size of buffer at aDoclist */ u8 bDesc; /* True to sort in descending order */ int eEvalmode; /* An FTS3_EVAL_XX constant */ int nRowAvg; /* Average size of database rows, in pages */ sqlite3_int64 nDoc; /* Documents in table */ i64 iMinDocid; /* Minimum docid to return */ i64 iMaxDocid; /* Maximum docid to return */ int isMatchinfoNeeded; /* True when aMatchinfo[] needs filling in */ MatchinfoBuffer *pMIBuffer; /* Buffer for matchinfo data */ }; #define FTS3_EVAL_FILTER 0 #define FTS3_EVAL_NEXT 1 #define FTS3_EVAL_MATCHINFO 2 /* ** The Fts3Cursor.eSearch member is always set to one of the following. ** Actualy, Fts3Cursor.eSearch can be greater than or equal to ** FTS3_FULLTEXT_SEARCH. If so, then Fts3Cursor.eSearch - 2 is the index ** of the column to be searched. For example, in ** ** CREATE VIRTUAL TABLE ex1 USING fts3(a,b,c,d); ** SELECT docid FROM ex1 WHERE b MATCH 'one two three'; ** ** Because the LHS of the MATCH operator is 2nd column "b", ** Fts3Cursor.eSearch will be set to FTS3_FULLTEXT_SEARCH+1. (+0 for a, ** +1 for b, +2 for c, +3 for d.) If the LHS of MATCH were "ex1" ** indicating that all columns should be searched, ** then eSearch would be set to FTS3_FULLTEXT_SEARCH+4. */ #define FTS3_FULLSCAN_SEARCH 0 /* Linear scan of %_content table */ #define FTS3_DOCID_SEARCH 1 /* Lookup by rowid on %_content table */ #define FTS3_FULLTEXT_SEARCH 2 /* Full-text index search */ /* ** The lower 16-bits of the sqlite3_index_info.idxNum value set by ** the xBestIndex() method contains the Fts3Cursor.eSearch value described ** above. The upper 16-bits contain a combination of the following ** bits, used to describe extra constraints on full-text searches. */ #define FTS3_HAVE_LANGID 0x00010000 /* languageid=? */ #define FTS3_HAVE_DOCID_GE 0x00020000 /* docid>=? */ #define FTS3_HAVE_DOCID_LE 0x00040000 /* docid<=? */ struct Fts3Doclist { char *aAll; /* Array containing doclist (or NULL) */ int nAll; /* Size of a[] in bytes */ char *pNextDocid; /* Pointer to next docid */ sqlite3_int64 iDocid; /* Current docid (if pList!=0) */ int bFreeList; /* True if pList should be sqlite3_free()d */ char *pList; /* Pointer to position list following iDocid */ int nList; /* Length of position list */ }; /* ** A "phrase" is a sequence of one or more tokens that must match in ** sequence. A single token is the base case and the most common case. ** For a sequence of tokens contained in double-quotes (i.e. "one two three") ** nToken will be the number of tokens in the string. */ struct Fts3PhraseToken { char *z; /* Text of the token */ int n; /* Number of bytes in buffer z */ int isPrefix; /* True if token ends with a "*" character */ int bFirst; /* True if token must appear at position 0 */ /* Variables above this point are populated when the expression is ** parsed (by code in fts3_expr.c). Below this point the variables are ** used when evaluating the expression. */ Fts3DeferredToken *pDeferred; /* Deferred token object for this token */ Fts3MultiSegReader *pSegcsr; /* Segment-reader for this token */ }; struct Fts3Phrase { /* Cache of doclist for this phrase. */ Fts3Doclist doclist; int bIncr; /* True if doclist is loaded incrementally */ int iDoclistToken; /* Used by sqlite3Fts3EvalPhrasePoslist() if this is a descendent of an ** OR condition. */ char *pOrPoslist; i64 iOrDocid; /* Variables below this point are populated by fts3_expr.c when parsing ** a MATCH expression. Everything above is part of the evaluation phase. */ int nToken; /* Number of tokens in the phrase */ int iColumn; /* Index of column this phrase must match */ Fts3PhraseToken aToken[1]; /* One entry for each token in the phrase */ }; /* ** A tree of these objects forms the RHS of a MATCH operator. ** ** If Fts3Expr.eType is FTSQUERY_PHRASE and isLoaded is true, then aDoclist ** points to a malloced buffer, size nDoclist bytes, containing the results ** of this phrase query in FTS3 doclist format. As usual, the initial ** "Length" field found in doclists stored on disk is omitted from this ** buffer. ** ** Variable aMI is used only for FTSQUERY_NEAR nodes to store the global ** matchinfo data. If it is not NULL, it points to an array of size nCol*3, ** where nCol is the number of columns in the queried FTS table. The array ** is populated as follows: ** ** aMI[iCol*3 + 0] = Undefined ** aMI[iCol*3 + 1] = Number of occurrences ** aMI[iCol*3 + 2] = Number of rows containing at least one instance ** ** The aMI array is allocated using sqlite3_malloc(). It should be freed ** when the expression node is. */ struct Fts3Expr { int eType; /* One of the FTSQUERY_XXX values defined below */ int nNear; /* Valid if eType==FTSQUERY_NEAR */ Fts3Expr *pParent; /* pParent->pLeft==this or pParent->pRight==this */ Fts3Expr *pLeft; /* Left operand */ Fts3Expr *pRight; /* Right operand */ Fts3Phrase *pPhrase; /* Valid if eType==FTSQUERY_PHRASE */ /* The following are used by the fts3_eval.c module. */ sqlite3_int64 iDocid; /* Current docid */ u8 bEof; /* True this expression is at EOF already */ u8 bStart; /* True if iDocid is valid */ u8 bDeferred; /* True if this expression is entirely deferred */ /* The following are used by the fts3_snippet.c module. */ int iPhrase; /* Index of this phrase in matchinfo() results */ u32 *aMI; /* See above */ }; /* ** Candidate values for Fts3Query.eType. Note that the order of the first ** four values is in order of precedence when parsing expressions. For ** example, the following: ** ** "a OR b AND c NOT d NEAR e" ** ** is equivalent to: ** ** "a OR (b AND (c NOT (d NEAR e)))" */ #define FTSQUERY_NEAR 1 #define FTSQUERY_NOT 2 #define FTSQUERY_AND 3 #define FTSQUERY_OR 4 #define FTSQUERY_PHRASE 5 /* fts3_write.c */ SQLITE_PRIVATE int sqlite3Fts3UpdateMethod(sqlite3_vtab*,int,sqlite3_value**,sqlite3_int64*); SQLITE_PRIVATE int sqlite3Fts3PendingTermsFlush(Fts3Table *); SQLITE_PRIVATE void sqlite3Fts3PendingTermsClear(Fts3Table *); SQLITE_PRIVATE int sqlite3Fts3Optimize(Fts3Table *); SQLITE_PRIVATE int sqlite3Fts3SegReaderNew(int, int, sqlite3_int64, sqlite3_int64, sqlite3_int64, const char *, int, Fts3SegReader**); SQLITE_PRIVATE int sqlite3Fts3SegReaderPending( Fts3Table*,int,const char*,int,int,Fts3SegReader**); SQLITE_PRIVATE void sqlite3Fts3SegReaderFree(Fts3SegReader *); SQLITE_PRIVATE int sqlite3Fts3AllSegdirs(Fts3Table*, int, int, int, sqlite3_stmt **); SQLITE_PRIVATE int sqlite3Fts3ReadBlock(Fts3Table*, sqlite3_int64, char **, int*, int*); SQLITE_PRIVATE int sqlite3Fts3SelectDoctotal(Fts3Table *, sqlite3_stmt **); SQLITE_PRIVATE int sqlite3Fts3SelectDocsize(Fts3Table *, sqlite3_int64, sqlite3_stmt **); #ifndef SQLITE_DISABLE_FTS4_DEFERRED SQLITE_PRIVATE void sqlite3Fts3FreeDeferredTokens(Fts3Cursor *); SQLITE_PRIVATE int sqlite3Fts3DeferToken(Fts3Cursor *, Fts3PhraseToken *, int); SQLITE_PRIVATE int sqlite3Fts3CacheDeferredDoclists(Fts3Cursor *); SQLITE_PRIVATE void sqlite3Fts3FreeDeferredDoclists(Fts3Cursor *); SQLITE_PRIVATE int sqlite3Fts3DeferredTokenList(Fts3DeferredToken *, char **, int *); #else # define sqlite3Fts3FreeDeferredTokens(x) # define sqlite3Fts3DeferToken(x,y,z) SQLITE_OK # define sqlite3Fts3CacheDeferredDoclists(x) SQLITE_OK # define sqlite3Fts3FreeDeferredDoclists(x) # define sqlite3Fts3DeferredTokenList(x,y,z) SQLITE_OK #endif SQLITE_PRIVATE void sqlite3Fts3SegmentsClose(Fts3Table *); SQLITE_PRIVATE int sqlite3Fts3MaxLevel(Fts3Table *, int *); /* Special values interpreted by sqlite3SegReaderCursor() */ #define FTS3_SEGCURSOR_PENDING -1 #define FTS3_SEGCURSOR_ALL -2 SQLITE_PRIVATE int sqlite3Fts3SegReaderStart(Fts3Table*, Fts3MultiSegReader*, Fts3SegFilter*); SQLITE_PRIVATE int sqlite3Fts3SegReaderStep(Fts3Table *, Fts3MultiSegReader *); SQLITE_PRIVATE void sqlite3Fts3SegReaderFinish(Fts3MultiSegReader *); SQLITE_PRIVATE int sqlite3Fts3SegReaderCursor(Fts3Table *, int, int, int, const char *, int, int, int, Fts3MultiSegReader *); /* Flags allowed as part of the 4th argument to SegmentReaderIterate() */ #define FTS3_SEGMENT_REQUIRE_POS 0x00000001 #define FTS3_SEGMENT_IGNORE_EMPTY 0x00000002 #define FTS3_SEGMENT_COLUMN_FILTER 0x00000004 #define FTS3_SEGMENT_PREFIX 0x00000008 #define FTS3_SEGMENT_SCAN 0x00000010 #define FTS3_SEGMENT_FIRST 0x00000020 /* Type passed as 4th argument to SegmentReaderIterate() */ struct Fts3SegFilter { const char *zTerm; int nTerm; int iCol; int flags; }; struct Fts3MultiSegReader { /* Used internally by sqlite3Fts3SegReaderXXX() calls */ Fts3SegReader **apSegment; /* Array of Fts3SegReader objects */ int nSegment; /* Size of apSegment array */ int nAdvance; /* How many seg-readers to advance */ Fts3SegFilter *pFilter; /* Pointer to filter object */ char *aBuffer; /* Buffer to merge doclists in */ int nBuffer; /* Allocated size of aBuffer[] in bytes */ int iColFilter; /* If >=0, filter for this column */ int bRestart; /* Used by fts3.c only. */ int nCost; /* Cost of running iterator */ int bLookup; /* True if a lookup of a single entry. */ /* Output values. Valid only after Fts3SegReaderStep() returns SQLITE_ROW. */ char *zTerm; /* Pointer to term buffer */ int nTerm; /* Size of zTerm in bytes */ char *aDoclist; /* Pointer to doclist buffer */ int nDoclist; /* Size of aDoclist[] in bytes */ }; SQLITE_PRIVATE int sqlite3Fts3Incrmerge(Fts3Table*,int,int); #define fts3GetVarint32(p, piVal) ( \ (*(u8*)(p)&0x80) ? sqlite3Fts3GetVarint32(p, piVal) : (*piVal=*(u8*)(p), 1) \ ) /* fts3.c */ SQLITE_PRIVATE void sqlite3Fts3ErrMsg(char**,const char*,...); SQLITE_PRIVATE int sqlite3Fts3PutVarint(char *, sqlite3_int64); SQLITE_PRIVATE int sqlite3Fts3GetVarint(const char *, sqlite_int64 *); SQLITE_PRIVATE int sqlite3Fts3GetVarint32(const char *, int *); SQLITE_PRIVATE int sqlite3Fts3VarintLen(sqlite3_uint64); SQLITE_PRIVATE void sqlite3Fts3Dequote(char *); SQLITE_PRIVATE void sqlite3Fts3DoclistPrev(int,char*,int,char**,sqlite3_int64*,int*,u8*); SQLITE_PRIVATE int sqlite3Fts3EvalPhraseStats(Fts3Cursor *, Fts3Expr *, u32 *); SQLITE_PRIVATE int sqlite3Fts3FirstFilter(sqlite3_int64, char *, int, char *); SQLITE_PRIVATE void sqlite3Fts3CreateStatTable(int*, Fts3Table*); SQLITE_PRIVATE int sqlite3Fts3EvalTestDeferred(Fts3Cursor *pCsr, int *pRc); /* fts3_tokenizer.c */ SQLITE_PRIVATE const char *sqlite3Fts3NextToken(const char *, int *); SQLITE_PRIVATE int sqlite3Fts3InitHashTable(sqlite3 *, Fts3Hash *, const char *); SQLITE_PRIVATE int sqlite3Fts3InitTokenizer(Fts3Hash *pHash, const char *, sqlite3_tokenizer **, char ** ); SQLITE_PRIVATE int sqlite3Fts3IsIdChar(char); /* fts3_snippet.c */ SQLITE_PRIVATE void sqlite3Fts3Offsets(sqlite3_context*, Fts3Cursor*); SQLITE_PRIVATE void sqlite3Fts3Snippet(sqlite3_context *, Fts3Cursor *, const char *, const char *, const char *, int, int ); SQLITE_PRIVATE void sqlite3Fts3Matchinfo(sqlite3_context *, Fts3Cursor *, const char *); SQLITE_PRIVATE void sqlite3Fts3MIBufferFree(MatchinfoBuffer *p); /* fts3_expr.c */ SQLITE_PRIVATE int sqlite3Fts3ExprParse(sqlite3_tokenizer *, int, char **, int, int, int, const char *, int, Fts3Expr **, char ** ); SQLITE_PRIVATE void sqlite3Fts3ExprFree(Fts3Expr *); #ifdef SQLITE_TEST SQLITE_PRIVATE int sqlite3Fts3ExprInitTestInterface(sqlite3 *db); SQLITE_PRIVATE int sqlite3Fts3InitTerm(sqlite3 *db); #endif SQLITE_PRIVATE int sqlite3Fts3OpenTokenizer(sqlite3_tokenizer *, int, const char *, int, sqlite3_tokenizer_cursor ** ); /* fts3_aux.c */ SQLITE_PRIVATE int sqlite3Fts3InitAux(sqlite3 *db); SQLITE_PRIVATE void sqlite3Fts3EvalPhraseCleanup(Fts3Phrase *); SQLITE_PRIVATE int sqlite3Fts3MsrIncrStart( Fts3Table*, Fts3MultiSegReader*, int, const char*, int); SQLITE_PRIVATE int sqlite3Fts3MsrIncrNext( Fts3Table *, Fts3MultiSegReader *, sqlite3_int64 *, char **, int *); SQLITE_PRIVATE int sqlite3Fts3EvalPhrasePoslist(Fts3Cursor *, Fts3Expr *, int iCol, char **); SQLITE_PRIVATE int sqlite3Fts3MsrOvfl(Fts3Cursor *, Fts3MultiSegReader *, int *); SQLITE_PRIVATE int sqlite3Fts3MsrIncrRestart(Fts3MultiSegReader *pCsr); /* fts3_tokenize_vtab.c */ SQLITE_PRIVATE int sqlite3Fts3InitTok(sqlite3*, Fts3Hash *); /* fts3_unicode2.c (functions generated by parsing unicode text files) */ #ifndef SQLITE_DISABLE_FTS3_UNICODE SQLITE_PRIVATE int sqlite3FtsUnicodeFold(int, int); SQLITE_PRIVATE int sqlite3FtsUnicodeIsalnum(int); SQLITE_PRIVATE int sqlite3FtsUnicodeIsdiacritic(int); #endif #endif /* !SQLITE_CORE || SQLITE_ENABLE_FTS3 */ #endif /* _FTSINT_H */ /************** End of fts3Int.h *********************************************/ /************** Continuing where we left off in fts3.c ***********************/ #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) #if defined(SQLITE_ENABLE_FTS3) && !defined(SQLITE_CORE) # define SQLITE_CORE 1 #endif /* #include */ /* #include */ /* #include */ /* #include */ /* #include */ /* #include */ /* #include "fts3.h" */ #ifndef SQLITE_CORE /* # include "sqlite3ext.h" */ SQLITE_EXTENSION_INIT1 #endif static int fts3EvalNext(Fts3Cursor *pCsr); static int fts3EvalStart(Fts3Cursor *pCsr); static int fts3TermSegReaderCursor( Fts3Cursor *, const char *, int, int, Fts3MultiSegReader **); #ifndef SQLITE_AMALGAMATION # if defined(SQLITE_DEBUG) SQLITE_PRIVATE int sqlite3Fts3Always(int b) { assert( b ); return b; } SQLITE_PRIVATE int sqlite3Fts3Never(int b) { assert( !b ); return b; } # endif #endif /* ** Write a 64-bit variable-length integer to memory starting at p[0]. ** The length of data written will be between 1 and FTS3_VARINT_MAX bytes. ** The number of bytes written is returned. */ SQLITE_PRIVATE int sqlite3Fts3PutVarint(char *p, sqlite_int64 v){ unsigned char *q = (unsigned char *) p; sqlite_uint64 vu = v; do{ *q++ = (unsigned char) ((vu & 0x7f) | 0x80); vu >>= 7; }while( vu!=0 ); q[-1] &= 0x7f; /* turn off high bit in final byte */ assert( q - (unsigned char *)p <= FTS3_VARINT_MAX ); return (int) (q - (unsigned char *)p); } #define GETVARINT_STEP(v, ptr, shift, mask1, mask2, var, ret) \ v = (v & mask1) | ( (*ptr++) << shift ); \ if( (v & mask2)==0 ){ var = v; return ret; } #define GETVARINT_INIT(v, ptr, shift, mask1, mask2, var, ret) \ v = (*ptr++); \ if( (v & mask2)==0 ){ var = v; return ret; } /* ** Read a 64-bit variable-length integer from memory starting at p[0]. ** Return the number of bytes read, or 0 on error. ** The value is stored in *v. */ SQLITE_PRIVATE int sqlite3Fts3GetVarint(const char *p, sqlite_int64 *v){ const char *pStart = p; u32 a; u64 b; int shift; GETVARINT_INIT(a, p, 0, 0x00, 0x80, *v, 1); GETVARINT_STEP(a, p, 7, 0x7F, 0x4000, *v, 2); GETVARINT_STEP(a, p, 14, 0x3FFF, 0x200000, *v, 3); GETVARINT_STEP(a, p, 21, 0x1FFFFF, 0x10000000, *v, 4); b = (a & 0x0FFFFFFF ); for(shift=28; shift<=63; shift+=7){ u64 c = *p++; b += (c&0x7F) << shift; if( (c & 0x80)==0 ) break; } *v = b; return (int)(p - pStart); } /* ** Similar to sqlite3Fts3GetVarint(), except that the output is truncated to a ** 32-bit integer before it is returned. */ SQLITE_PRIVATE int sqlite3Fts3GetVarint32(const char *p, int *pi){ u32 a; #ifndef fts3GetVarint32 GETVARINT_INIT(a, p, 0, 0x00, 0x80, *pi, 1); #else a = (*p++); assert( a & 0x80 ); #endif GETVARINT_STEP(a, p, 7, 0x7F, 0x4000, *pi, 2); GETVARINT_STEP(a, p, 14, 0x3FFF, 0x200000, *pi, 3); GETVARINT_STEP(a, p, 21, 0x1FFFFF, 0x10000000, *pi, 4); a = (a & 0x0FFFFFFF ); *pi = (int)(a | ((u32)(*p & 0x0F) << 28)); return 5; } /* ** Return the number of bytes required to encode v as a varint */ SQLITE_PRIVATE int sqlite3Fts3VarintLen(sqlite3_uint64 v){ int i = 0; do{ i++; v >>= 7; }while( v!=0 ); return i; } /* ** Convert an SQL-style quoted string into a normal string by removing ** the quote characters. The conversion is done in-place. If the ** input does not begin with a quote character, then this routine ** is a no-op. ** ** Examples: ** ** "abc" becomes abc ** 'xyz' becomes xyz ** [pqr] becomes pqr ** `mno` becomes mno ** */ SQLITE_PRIVATE void sqlite3Fts3Dequote(char *z){ char quote; /* Quote character (if any ) */ quote = z[0]; if( quote=='[' || quote=='\'' || quote=='"' || quote=='`' ){ int iIn = 1; /* Index of next byte to read from input */ int iOut = 0; /* Index of next byte to write to output */ /* If the first byte was a '[', then the close-quote character is a ']' */ if( quote=='[' ) quote = ']'; while( z[iIn] ){ if( z[iIn]==quote ){ if( z[iIn+1]!=quote ) break; z[iOut++] = quote; iIn += 2; }else{ z[iOut++] = z[iIn++]; } } z[iOut] = '\0'; } } /* ** Read a single varint from the doclist at *pp and advance *pp to point ** to the first byte past the end of the varint. Add the value of the varint ** to *pVal. */ static void fts3GetDeltaVarint(char **pp, sqlite3_int64 *pVal){ sqlite3_int64 iVal; *pp += sqlite3Fts3GetVarint(*pp, &iVal); *pVal += iVal; } /* ** When this function is called, *pp points to the first byte following a ** varint that is part of a doclist (or position-list, or any other list ** of varints). This function moves *pp to point to the start of that varint, ** and sets *pVal by the varint value. ** ** Argument pStart points to the first byte of the doclist that the ** varint is part of. */ static void fts3GetReverseVarint( char **pp, char *pStart, sqlite3_int64 *pVal ){ sqlite3_int64 iVal; char *p; /* Pointer p now points at the first byte past the varint we are ** interested in. So, unless the doclist is corrupt, the 0x80 bit is ** clear on character p[-1]. */ for(p = (*pp)-2; p>=pStart && *p&0x80; p--); p++; *pp = p; sqlite3Fts3GetVarint(p, &iVal); *pVal = iVal; } /* ** The xDisconnect() virtual table method. */ static int fts3DisconnectMethod(sqlite3_vtab *pVtab){ Fts3Table *p = (Fts3Table *)pVtab; int i; assert( p->nPendingData==0 ); assert( p->pSegments==0 ); /* Free any prepared statements held */ for(i=0; iaStmt); i++){ sqlite3_finalize(p->aStmt[i]); } sqlite3_free(p->zSegmentsTbl); sqlite3_free(p->zReadExprlist); sqlite3_free(p->zWriteExprlist); sqlite3_free(p->zContentTbl); sqlite3_free(p->zLanguageid); /* Invoke the tokenizer destructor to free the tokenizer. */ p->pTokenizer->pModule->xDestroy(p->pTokenizer); sqlite3_free(p); return SQLITE_OK; } /* ** Write an error message into *pzErr */ SQLITE_PRIVATE void sqlite3Fts3ErrMsg(char **pzErr, const char *zFormat, ...){ va_list ap; sqlite3_free(*pzErr); va_start(ap, zFormat); *pzErr = sqlite3_vmprintf(zFormat, ap); va_end(ap); } /* ** Construct one or more SQL statements from the format string given ** and then evaluate those statements. The success code is written ** into *pRc. ** ** If *pRc is initially non-zero then this routine is a no-op. */ static void fts3DbExec( int *pRc, /* Success code */ sqlite3 *db, /* Database in which to run SQL */ const char *zFormat, /* Format string for SQL */ ... /* Arguments to the format string */ ){ va_list ap; char *zSql; if( *pRc ) return; va_start(ap, zFormat); zSql = sqlite3_vmprintf(zFormat, ap); va_end(ap); if( zSql==0 ){ *pRc = SQLITE_NOMEM; }else{ *pRc = sqlite3_exec(db, zSql, 0, 0, 0); sqlite3_free(zSql); } } /* ** The xDestroy() virtual table method. */ static int fts3DestroyMethod(sqlite3_vtab *pVtab){ Fts3Table *p = (Fts3Table *)pVtab; int rc = SQLITE_OK; /* Return code */ const char *zDb = p->zDb; /* Name of database (e.g. "main", "temp") */ sqlite3 *db = p->db; /* Database handle */ /* Drop the shadow tables */ if( p->zContentTbl==0 ){ fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_content'", zDb, p->zName); } fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_segments'", zDb,p->zName); fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_segdir'", zDb, p->zName); fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_docsize'", zDb, p->zName); fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_stat'", zDb, p->zName); /* If everything has worked, invoke fts3DisconnectMethod() to free the ** memory associated with the Fts3Table structure and return SQLITE_OK. ** Otherwise, return an SQLite error code. */ return (rc==SQLITE_OK ? fts3DisconnectMethod(pVtab) : rc); } /* ** Invoke sqlite3_declare_vtab() to declare the schema for the FTS3 table ** passed as the first argument. This is done as part of the xConnect() ** and xCreate() methods. ** ** If *pRc is non-zero when this function is called, it is a no-op. ** Otherwise, if an error occurs, an SQLite error code is stored in *pRc ** before returning. */ static void fts3DeclareVtab(int *pRc, Fts3Table *p){ if( *pRc==SQLITE_OK ){ int i; /* Iterator variable */ int rc; /* Return code */ char *zSql; /* SQL statement passed to declare_vtab() */ char *zCols; /* List of user defined columns */ const char *zLanguageid; zLanguageid = (p->zLanguageid ? p->zLanguageid : "__langid"); sqlite3_vtab_config(p->db, SQLITE_VTAB_CONSTRAINT_SUPPORT, 1); /* Create a list of user columns for the virtual table */ zCols = sqlite3_mprintf("%Q, ", p->azColumn[0]); for(i=1; zCols && inColumn; i++){ zCols = sqlite3_mprintf("%z%Q, ", zCols, p->azColumn[i]); } /* Create the whole "CREATE TABLE" statement to pass to SQLite */ zSql = sqlite3_mprintf( "CREATE TABLE x(%s %Q HIDDEN, docid HIDDEN, %Q HIDDEN)", zCols, p->zName, zLanguageid ); if( !zCols || !zSql ){ rc = SQLITE_NOMEM; }else{ rc = sqlite3_declare_vtab(p->db, zSql); } sqlite3_free(zSql); sqlite3_free(zCols); *pRc = rc; } } /* ** Create the %_stat table if it does not already exist. */ SQLITE_PRIVATE void sqlite3Fts3CreateStatTable(int *pRc, Fts3Table *p){ fts3DbExec(pRc, p->db, "CREATE TABLE IF NOT EXISTS %Q.'%q_stat'" "(id INTEGER PRIMARY KEY, value BLOB);", p->zDb, p->zName ); if( (*pRc)==SQLITE_OK ) p->bHasStat = 1; } /* ** Create the backing store tables (%_content, %_segments and %_segdir) ** required by the FTS3 table passed as the only argument. This is done ** as part of the vtab xCreate() method. ** ** If the p->bHasDocsize boolean is true (indicating that this is an ** FTS4 table, not an FTS3 table) then also create the %_docsize and ** %_stat tables required by FTS4. */ static int fts3CreateTables(Fts3Table *p){ int rc = SQLITE_OK; /* Return code */ int i; /* Iterator variable */ sqlite3 *db = p->db; /* The database connection */ if( p->zContentTbl==0 ){ const char *zLanguageid = p->zLanguageid; char *zContentCols; /* Columns of %_content table */ /* Create a list of user columns for the content table */ zContentCols = sqlite3_mprintf("docid INTEGER PRIMARY KEY"); for(i=0; zContentCols && inColumn; i++){ char *z = p->azColumn[i]; zContentCols = sqlite3_mprintf("%z, 'c%d%q'", zContentCols, i, z); } if( zLanguageid && zContentCols ){ zContentCols = sqlite3_mprintf("%z, langid", zContentCols, zLanguageid); } if( zContentCols==0 ) rc = SQLITE_NOMEM; /* Create the content table */ fts3DbExec(&rc, db, "CREATE TABLE %Q.'%q_content'(%s)", p->zDb, p->zName, zContentCols ); sqlite3_free(zContentCols); } /* Create other tables */ fts3DbExec(&rc, db, "CREATE TABLE %Q.'%q_segments'(blockid INTEGER PRIMARY KEY, block BLOB);", p->zDb, p->zName ); fts3DbExec(&rc, db, "CREATE TABLE %Q.'%q_segdir'(" "level INTEGER," "idx INTEGER," "start_block INTEGER," "leaves_end_block INTEGER," "end_block INTEGER," "root BLOB," "PRIMARY KEY(level, idx)" ");", p->zDb, p->zName ); if( p->bHasDocsize ){ fts3DbExec(&rc, db, "CREATE TABLE %Q.'%q_docsize'(docid INTEGER PRIMARY KEY, size BLOB);", p->zDb, p->zName ); } assert( p->bHasStat==p->bFts4 ); if( p->bHasStat ){ sqlite3Fts3CreateStatTable(&rc, p); } return rc; } /* ** Store the current database page-size in bytes in p->nPgsz. ** ** If *pRc is non-zero when this function is called, it is a no-op. ** Otherwise, if an error occurs, an SQLite error code is stored in *pRc ** before returning. */ static void fts3DatabasePageSize(int *pRc, Fts3Table *p){ if( *pRc==SQLITE_OK ){ int rc; /* Return code */ char *zSql; /* SQL text "PRAGMA %Q.page_size" */ sqlite3_stmt *pStmt; /* Compiled "PRAGMA %Q.page_size" statement */ zSql = sqlite3_mprintf("PRAGMA %Q.page_size", p->zDb); if( !zSql ){ rc = SQLITE_NOMEM; }else{ rc = sqlite3_prepare(p->db, zSql, -1, &pStmt, 0); if( rc==SQLITE_OK ){ sqlite3_step(pStmt); p->nPgsz = sqlite3_column_int(pStmt, 0); rc = sqlite3_finalize(pStmt); }else if( rc==SQLITE_AUTH ){ p->nPgsz = 1024; rc = SQLITE_OK; } } assert( p->nPgsz>0 || rc!=SQLITE_OK ); sqlite3_free(zSql); *pRc = rc; } } /* ** "Special" FTS4 arguments are column specifications of the following form: ** ** = ** ** There may not be whitespace surrounding the "=" character. The ** term may be quoted, but the may not. */ static int fts3IsSpecialColumn( const char *z, int *pnKey, char **pzValue ){ char *zValue; const char *zCsr = z; while( *zCsr!='=' ){ if( *zCsr=='\0' ) return 0; zCsr++; } *pnKey = (int)(zCsr-z); zValue = sqlite3_mprintf("%s", &zCsr[1]); if( zValue ){ sqlite3Fts3Dequote(zValue); } *pzValue = zValue; return 1; } /* ** Append the output of a printf() style formatting to an existing string. */ static void fts3Appendf( int *pRc, /* IN/OUT: Error code */ char **pz, /* IN/OUT: Pointer to string buffer */ const char *zFormat, /* Printf format string to append */ ... /* Arguments for printf format string */ ){ if( *pRc==SQLITE_OK ){ va_list ap; char *z; va_start(ap, zFormat); z = sqlite3_vmprintf(zFormat, ap); va_end(ap); if( z && *pz ){ char *z2 = sqlite3_mprintf("%s%s", *pz, z); sqlite3_free(z); z = z2; } if( z==0 ) *pRc = SQLITE_NOMEM; sqlite3_free(*pz); *pz = z; } } /* ** Return a copy of input string zInput enclosed in double-quotes (") and ** with all double quote characters escaped. For example: ** ** fts3QuoteId("un \"zip\"") -> "un \"\"zip\"\"" ** ** The pointer returned points to memory obtained from sqlite3_malloc(). It ** is the callers responsibility to call sqlite3_free() to release this ** memory. */ static char *fts3QuoteId(char const *zInput){ int nRet; char *zRet; nRet = 2 + (int)strlen(zInput)*2 + 1; zRet = sqlite3_malloc(nRet); if( zRet ){ int i; char *z = zRet; *(z++) = '"'; for(i=0; zInput[i]; i++){ if( zInput[i]=='"' ) *(z++) = '"'; *(z++) = zInput[i]; } *(z++) = '"'; *(z++) = '\0'; } return zRet; } /* ** Return a list of comma separated SQL expressions and a FROM clause that ** could be used in a SELECT statement such as the following: ** ** SELECT FROM %_content AS x ... ** ** to return the docid, followed by each column of text data in order ** from left to write. If parameter zFunc is not NULL, then instead of ** being returned directly each column of text data is passed to an SQL ** function named zFunc first. For example, if zFunc is "unzip" and the ** table has the three user-defined columns "a", "b", and "c", the following ** string is returned: ** ** "docid, unzip(x.'a'), unzip(x.'b'), unzip(x.'c') FROM %_content AS x" ** ** The pointer returned points to a buffer allocated by sqlite3_malloc(). It ** is the responsibility of the caller to eventually free it. ** ** If *pRc is not SQLITE_OK when this function is called, it is a no-op (and ** a NULL pointer is returned). Otherwise, if an OOM error is encountered ** by this function, NULL is returned and *pRc is set to SQLITE_NOMEM. If ** no error occurs, *pRc is left unmodified. */ static char *fts3ReadExprList(Fts3Table *p, const char *zFunc, int *pRc){ char *zRet = 0; char *zFree = 0; char *zFunction; int i; if( p->zContentTbl==0 ){ if( !zFunc ){ zFunction = ""; }else{ zFree = zFunction = fts3QuoteId(zFunc); } fts3Appendf(pRc, &zRet, "docid"); for(i=0; inColumn; i++){ fts3Appendf(pRc, &zRet, ",%s(x.'c%d%q')", zFunction, i, p->azColumn[i]); } if( p->zLanguageid ){ fts3Appendf(pRc, &zRet, ", x.%Q", "langid"); } sqlite3_free(zFree); }else{ fts3Appendf(pRc, &zRet, "rowid"); for(i=0; inColumn; i++){ fts3Appendf(pRc, &zRet, ", x.'%q'", p->azColumn[i]); } if( p->zLanguageid ){ fts3Appendf(pRc, &zRet, ", x.%Q", p->zLanguageid); } } fts3Appendf(pRc, &zRet, " FROM '%q'.'%q%s' AS x", p->zDb, (p->zContentTbl ? p->zContentTbl : p->zName), (p->zContentTbl ? "" : "_content") ); return zRet; } /* ** Return a list of N comma separated question marks, where N is the number ** of columns in the %_content table (one for the docid plus one for each ** user-defined text column). ** ** If argument zFunc is not NULL, then all but the first question mark ** is preceded by zFunc and an open bracket, and followed by a closed ** bracket. For example, if zFunc is "zip" and the FTS3 table has three ** user-defined text columns, the following string is returned: ** ** "?, zip(?), zip(?), zip(?)" ** ** The pointer returned points to a buffer allocated by sqlite3_malloc(). It ** is the responsibility of the caller to eventually free it. ** ** If *pRc is not SQLITE_OK when this function is called, it is a no-op (and ** a NULL pointer is returned). Otherwise, if an OOM error is encountered ** by this function, NULL is returned and *pRc is set to SQLITE_NOMEM. If ** no error occurs, *pRc is left unmodified. */ static char *fts3WriteExprList(Fts3Table *p, const char *zFunc, int *pRc){ char *zRet = 0; char *zFree = 0; char *zFunction; int i; if( !zFunc ){ zFunction = ""; }else{ zFree = zFunction = fts3QuoteId(zFunc); } fts3Appendf(pRc, &zRet, "?"); for(i=0; inColumn; i++){ fts3Appendf(pRc, &zRet, ",%s(?)", zFunction); } if( p->zLanguageid ){ fts3Appendf(pRc, &zRet, ", ?"); } sqlite3_free(zFree); return zRet; } /* ** This function interprets the string at (*pp) as a non-negative integer ** value. It reads the integer and sets *pnOut to the value read, then ** sets *pp to point to the byte immediately following the last byte of ** the integer value. ** ** Only decimal digits ('0'..'9') may be part of an integer value. ** ** If *pp does not being with a decimal digit SQLITE_ERROR is returned and ** the output value undefined. Otherwise SQLITE_OK is returned. ** ** This function is used when parsing the "prefix=" FTS4 parameter. */ static int fts3GobbleInt(const char **pp, int *pnOut){ const int MAX_NPREFIX = 10000000; const char *p; /* Iterator pointer */ int nInt = 0; /* Output value */ for(p=*pp; p[0]>='0' && p[0]<='9'; p++){ nInt = nInt * 10 + (p[0] - '0'); if( nInt>MAX_NPREFIX ){ nInt = 0; break; } } if( p==*pp ) return SQLITE_ERROR; *pnOut = nInt; *pp = p; return SQLITE_OK; } /* ** This function is called to allocate an array of Fts3Index structures ** representing the indexes maintained by the current FTS table. FTS tables ** always maintain the main "terms" index, but may also maintain one or ** more "prefix" indexes, depending on the value of the "prefix=" parameter ** (if any) specified as part of the CREATE VIRTUAL TABLE statement. ** ** Argument zParam is passed the value of the "prefix=" option if one was ** specified, or NULL otherwise. ** ** If no error occurs, SQLITE_OK is returned and *apIndex set to point to ** the allocated array. *pnIndex is set to the number of elements in the ** array. If an error does occur, an SQLite error code is returned. ** ** Regardless of whether or not an error is returned, it is the responsibility ** of the caller to call sqlite3_free() on the output array to free it. */ static int fts3PrefixParameter( const char *zParam, /* ABC in prefix=ABC parameter to parse */ int *pnIndex, /* OUT: size of *apIndex[] array */ struct Fts3Index **apIndex /* OUT: Array of indexes for this table */ ){ struct Fts3Index *aIndex; /* Allocated array */ int nIndex = 1; /* Number of entries in array */ if( zParam && zParam[0] ){ const char *p; nIndex++; for(p=zParam; *p; p++){ if( *p==',' ) nIndex++; } } aIndex = sqlite3_malloc(sizeof(struct Fts3Index) * nIndex); *apIndex = aIndex; if( !aIndex ){ return SQLITE_NOMEM; } memset(aIndex, 0, sizeof(struct Fts3Index) * nIndex); if( zParam ){ const char *p = zParam; int i; for(i=1; i=0 ); if( nPrefix==0 ){ nIndex--; i--; }else{ aIndex[i].nPrefix = nPrefix; } p++; } } *pnIndex = nIndex; return SQLITE_OK; } /* ** This function is called when initializing an FTS4 table that uses the ** content=xxx option. It determines the number of and names of the columns ** of the new FTS4 table. ** ** The third argument passed to this function is the value passed to the ** config=xxx option (i.e. "xxx"). This function queries the database for ** a table of that name. If found, the output variables are populated ** as follows: ** ** *pnCol: Set to the number of columns table xxx has, ** ** *pnStr: Set to the total amount of space required to store a copy ** of each columns name, including the nul-terminator. ** ** *pazCol: Set to point to an array of *pnCol strings. Each string is ** the name of the corresponding column in table xxx. The array ** and its contents are allocated using a single allocation. It ** is the responsibility of the caller to free this allocation ** by eventually passing the *pazCol value to sqlite3_free(). ** ** If the table cannot be found, an error code is returned and the output ** variables are undefined. Or, if an OOM is encountered, SQLITE_NOMEM is ** returned (and the output variables are undefined). */ static int fts3ContentColumns( sqlite3 *db, /* Database handle */ const char *zDb, /* Name of db (i.e. "main", "temp" etc.) */ const char *zTbl, /* Name of content table */ const char ***pazCol, /* OUT: Malloc'd array of column names */ int *pnCol, /* OUT: Size of array *pazCol */ int *pnStr, /* OUT: Bytes of string content */ char **pzErr /* OUT: error message */ ){ int rc = SQLITE_OK; /* Return code */ char *zSql; /* "SELECT *" statement on zTbl */ sqlite3_stmt *pStmt = 0; /* Compiled version of zSql */ zSql = sqlite3_mprintf("SELECT * FROM %Q.%Q", zDb, zTbl); if( !zSql ){ rc = SQLITE_NOMEM; }else{ rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0); if( rc!=SQLITE_OK ){ sqlite3Fts3ErrMsg(pzErr, "%s", sqlite3_errmsg(db)); } } sqlite3_free(zSql); if( rc==SQLITE_OK ){ const char **azCol; /* Output array */ int nStr = 0; /* Size of all column names (incl. 0x00) */ int nCol; /* Number of table columns */ int i; /* Used to iterate through columns */ /* Loop through the returned columns. Set nStr to the number of bytes of ** space required to store a copy of each column name, including the ** nul-terminator byte. */ nCol = sqlite3_column_count(pStmt); for(i=0; i module name ("fts3" or "fts4") ** argv[1] -> database name ** argv[2] -> table name ** argv[...] -> "column name" and other module argument fields. */ static int fts3InitVtab( int isCreate, /* True for xCreate, false for xConnect */ sqlite3 *db, /* The SQLite database connection */ void *pAux, /* Hash table containing tokenizers */ int argc, /* Number of elements in argv array */ const char * const *argv, /* xCreate/xConnect argument array */ sqlite3_vtab **ppVTab, /* Write the resulting vtab structure here */ char **pzErr /* Write any error message here */ ){ Fts3Hash *pHash = (Fts3Hash *)pAux; Fts3Table *p = 0; /* Pointer to allocated vtab */ int rc = SQLITE_OK; /* Return code */ int i; /* Iterator variable */ int nByte; /* Size of allocation used for *p */ int iCol; /* Column index */ int nString = 0; /* Bytes required to hold all column names */ int nCol = 0; /* Number of columns in the FTS table */ char *zCsr; /* Space for holding column names */ int nDb; /* Bytes required to hold database name */ int nName; /* Bytes required to hold table name */ int isFts4 = (argv[0][3]=='4'); /* True for FTS4, false for FTS3 */ const char **aCol; /* Array of column names */ sqlite3_tokenizer *pTokenizer = 0; /* Tokenizer for this table */ int nIndex = 0; /* Size of aIndex[] array */ struct Fts3Index *aIndex = 0; /* Array of indexes for this table */ /* The results of parsing supported FTS4 key=value options: */ int bNoDocsize = 0; /* True to omit %_docsize table */ int bDescIdx = 0; /* True to store descending indexes */ char *zPrefix = 0; /* Prefix parameter value (or NULL) */ char *zCompress = 0; /* compress=? parameter (or NULL) */ char *zUncompress = 0; /* uncompress=? parameter (or NULL) */ char *zContent = 0; /* content=? parameter (or NULL) */ char *zLanguageid = 0; /* languageid=? parameter (or NULL) */ char **azNotindexed = 0; /* The set of notindexed= columns */ int nNotindexed = 0; /* Size of azNotindexed[] array */ assert( strlen(argv[0])==4 ); assert( (sqlite3_strnicmp(argv[0], "fts4", 4)==0 && isFts4) || (sqlite3_strnicmp(argv[0], "fts3", 4)==0 && !isFts4) ); nDb = (int)strlen(argv[1]) + 1; nName = (int)strlen(argv[2]) + 1; nByte = sizeof(const char *) * (argc-2); aCol = (const char **)sqlite3_malloc(nByte); if( aCol ){ memset((void*)aCol, 0, nByte); azNotindexed = (char **)sqlite3_malloc(nByte); } if( azNotindexed ){ memset(azNotindexed, 0, nByte); } if( !aCol || !azNotindexed ){ rc = SQLITE_NOMEM; goto fts3_init_out; } /* Loop through all of the arguments passed by the user to the FTS3/4 ** module (i.e. all the column names and special arguments). This loop ** does the following: ** ** + Figures out the number of columns the FTSX table will have, and ** the number of bytes of space that must be allocated to store copies ** of the column names. ** ** + If there is a tokenizer specification included in the arguments, ** initializes the tokenizer pTokenizer. */ for(i=3; rc==SQLITE_OK && i8 && 0==sqlite3_strnicmp(z, "tokenize", 8) && 0==sqlite3Fts3IsIdChar(z[8]) ){ rc = sqlite3Fts3InitTokenizer(pHash, &z[9], &pTokenizer, pzErr); } /* Check if it is an FTS4 special argument. */ else if( isFts4 && fts3IsSpecialColumn(z, &nKey, &zVal) ){ struct Fts4Option { const char *zOpt; int nOpt; } aFts4Opt[] = { { "matchinfo", 9 }, /* 0 -> MATCHINFO */ { "prefix", 6 }, /* 1 -> PREFIX */ { "compress", 8 }, /* 2 -> COMPRESS */ { "uncompress", 10 }, /* 3 -> UNCOMPRESS */ { "order", 5 }, /* 4 -> ORDER */ { "content", 7 }, /* 5 -> CONTENT */ { "languageid", 10 }, /* 6 -> LANGUAGEID */ { "notindexed", 10 } /* 7 -> NOTINDEXED */ }; int iOpt; if( !zVal ){ rc = SQLITE_NOMEM; }else{ for(iOpt=0; iOptnOpt && !sqlite3_strnicmp(z, pOp->zOpt, pOp->nOpt) ){ break; } } if( iOpt==SizeofArray(aFts4Opt) ){ sqlite3Fts3ErrMsg(pzErr, "unrecognized parameter: %s", z); rc = SQLITE_ERROR; }else{ switch( iOpt ){ case 0: /* MATCHINFO */ if( strlen(zVal)!=4 || sqlite3_strnicmp(zVal, "fts3", 4) ){ sqlite3Fts3ErrMsg(pzErr, "unrecognized matchinfo: %s", zVal); rc = SQLITE_ERROR; } bNoDocsize = 1; break; case 1: /* PREFIX */ sqlite3_free(zPrefix); zPrefix = zVal; zVal = 0; break; case 2: /* COMPRESS */ sqlite3_free(zCompress); zCompress = zVal; zVal = 0; break; case 3: /* UNCOMPRESS */ sqlite3_free(zUncompress); zUncompress = zVal; zVal = 0; break; case 4: /* ORDER */ if( (strlen(zVal)!=3 || sqlite3_strnicmp(zVal, "asc", 3)) && (strlen(zVal)!=4 || sqlite3_strnicmp(zVal, "desc", 4)) ){ sqlite3Fts3ErrMsg(pzErr, "unrecognized order: %s", zVal); rc = SQLITE_ERROR; } bDescIdx = (zVal[0]=='d' || zVal[0]=='D'); break; case 5: /* CONTENT */ sqlite3_free(zContent); zContent = zVal; zVal = 0; break; case 6: /* LANGUAGEID */ assert( iOpt==6 ); sqlite3_free(zLanguageid); zLanguageid = zVal; zVal = 0; break; case 7: /* NOTINDEXED */ azNotindexed[nNotindexed++] = zVal; zVal = 0; break; } } sqlite3_free(zVal); } } /* Otherwise, the argument is a column name. */ else { nString += (int)(strlen(z) + 1); aCol[nCol++] = z; } } /* If a content=xxx option was specified, the following: ** ** 1. Ignore any compress= and uncompress= options. ** ** 2. If no column names were specified as part of the CREATE VIRTUAL ** TABLE statement, use all columns from the content table. */ if( rc==SQLITE_OK && zContent ){ sqlite3_free(zCompress); sqlite3_free(zUncompress); zCompress = 0; zUncompress = 0; if( nCol==0 ){ sqlite3_free((void*)aCol); aCol = 0; rc = fts3ContentColumns(db, argv[1], zContent,&aCol,&nCol,&nString,pzErr); /* If a languageid= option was specified, remove the language id ** column from the aCol[] array. */ if( rc==SQLITE_OK && zLanguageid ){ int j; for(j=0; jdb = db; p->nColumn = nCol; p->nPendingData = 0; p->azColumn = (char **)&p[1]; p->pTokenizer = pTokenizer; p->nMaxPendingData = FTS3_MAX_PENDING_DATA; p->bHasDocsize = (isFts4 && bNoDocsize==0); p->bHasStat = isFts4; p->bFts4 = isFts4; p->bDescIdx = bDescIdx; p->nAutoincrmerge = 0xff; /* 0xff means setting unknown */ p->zContentTbl = zContent; p->zLanguageid = zLanguageid; zContent = 0; zLanguageid = 0; TESTONLY( p->inTransaction = -1 ); TESTONLY( p->mxSavepoint = -1 ); p->aIndex = (struct Fts3Index *)&p->azColumn[nCol]; memcpy(p->aIndex, aIndex, sizeof(struct Fts3Index) * nIndex); p->nIndex = nIndex; for(i=0; iaIndex[i].hPending, FTS3_HASH_STRING, 1); } p->abNotindexed = (u8 *)&p->aIndex[nIndex]; /* Fill in the zName and zDb fields of the vtab structure. */ zCsr = (char *)&p->abNotindexed[nCol]; p->zName = zCsr; memcpy(zCsr, argv[2], nName); zCsr += nName; p->zDb = zCsr; memcpy(zCsr, argv[1], nDb); zCsr += nDb; /* Fill in the azColumn array */ for(iCol=0; iColazColumn[iCol] = zCsr; zCsr += n+1; assert( zCsr <= &((char *)p)[nByte] ); } /* Fill in the abNotindexed array */ for(iCol=0; iColazColumn[iCol]); for(i=0; iazColumn[iCol], zNot, n) ){ p->abNotindexed[iCol] = 1; sqlite3_free(zNot); azNotindexed[i] = 0; } } } for(i=0; izReadExprlist = fts3ReadExprList(p, zUncompress, &rc); p->zWriteExprlist = fts3WriteExprList(p, zCompress, &rc); if( rc!=SQLITE_OK ) goto fts3_init_out; /* If this is an xCreate call, create the underlying tables in the ** database. TODO: For xConnect(), it could verify that said tables exist. */ if( isCreate ){ rc = fts3CreateTables(p); } /* Check to see if a legacy fts3 table has been "upgraded" by the ** addition of a %_stat table so that it can use incremental merge. */ if( !isFts4 && !isCreate ){ p->bHasStat = 2; } /* Figure out the page-size for the database. This is required in order to ** estimate the cost of loading large doclists from the database. */ fts3DatabasePageSize(&rc, p); p->nNodeSize = p->nPgsz-35; /* Declare the table schema to SQLite. */ fts3DeclareVtab(&rc, p); fts3_init_out: sqlite3_free(zPrefix); sqlite3_free(aIndex); sqlite3_free(zCompress); sqlite3_free(zUncompress); sqlite3_free(zContent); sqlite3_free(zLanguageid); for(i=0; ipModule->xDestroy(pTokenizer); } }else{ assert( p->pSegments==0 ); *ppVTab = &p->base; } return rc; } /* ** The xConnect() and xCreate() methods for the virtual table. All the ** work is done in function fts3InitVtab(). */ static int fts3ConnectMethod( sqlite3 *db, /* Database connection */ void *pAux, /* Pointer to tokenizer hash table */ int argc, /* Number of elements in argv array */ const char * const *argv, /* xCreate/xConnect argument array */ sqlite3_vtab **ppVtab, /* OUT: New sqlite3_vtab object */ char **pzErr /* OUT: sqlite3_malloc'd error message */ ){ return fts3InitVtab(0, db, pAux, argc, argv, ppVtab, pzErr); } static int fts3CreateMethod( sqlite3 *db, /* Database connection */ void *pAux, /* Pointer to tokenizer hash table */ int argc, /* Number of elements in argv array */ const char * const *argv, /* xCreate/xConnect argument array */ sqlite3_vtab **ppVtab, /* OUT: New sqlite3_vtab object */ char **pzErr /* OUT: sqlite3_malloc'd error message */ ){ return fts3InitVtab(1, db, pAux, argc, argv, ppVtab, pzErr); } /* ** Set the pIdxInfo->estimatedRows variable to nRow. Unless this ** extension is currently being used by a version of SQLite too old to ** support estimatedRows. In that case this function is a no-op. */ static void fts3SetEstimatedRows(sqlite3_index_info *pIdxInfo, i64 nRow){ #if SQLITE_VERSION_NUMBER>=3008002 if( sqlite3_libversion_number()>=3008002 ){ pIdxInfo->estimatedRows = nRow; } #endif } /* ** Set the SQLITE_INDEX_SCAN_UNIQUE flag in pIdxInfo->flags. Unless this ** extension is currently being used by a version of SQLite too old to ** support index-info flags. In that case this function is a no-op. */ static void fts3SetUniqueFlag(sqlite3_index_info *pIdxInfo){ #if SQLITE_VERSION_NUMBER>=3008012 if( sqlite3_libversion_number()>=3008012 ){ pIdxInfo->idxFlags |= SQLITE_INDEX_SCAN_UNIQUE; } #endif } /* ** Implementation of the xBestIndex method for FTS3 tables. There ** are three possible strategies, in order of preference: ** ** 1. Direct lookup by rowid or docid. ** 2. Full-text search using a MATCH operator on a non-docid column. ** 3. Linear scan of %_content table. */ static int fts3BestIndexMethod(sqlite3_vtab *pVTab, sqlite3_index_info *pInfo){ Fts3Table *p = (Fts3Table *)pVTab; int i; /* Iterator variable */ int iCons = -1; /* Index of constraint to use */ int iLangidCons = -1; /* Index of langid=x constraint, if present */ int iDocidGe = -1; /* Index of docid>=x constraint, if present */ int iDocidLe = -1; /* Index of docid<=x constraint, if present */ int iIdx; /* By default use a full table scan. This is an expensive option, ** so search through the constraints to see if a more efficient ** strategy is possible. */ pInfo->idxNum = FTS3_FULLSCAN_SEARCH; pInfo->estimatedCost = 5000000; for(i=0; inConstraint; i++){ int bDocid; /* True if this constraint is on docid */ struct sqlite3_index_constraint *pCons = &pInfo->aConstraint[i]; if( pCons->usable==0 ){ if( pCons->op==SQLITE_INDEX_CONSTRAINT_MATCH ){ /* There exists an unusable MATCH constraint. This means that if ** the planner does elect to use the results of this call as part ** of the overall query plan the user will see an "unable to use ** function MATCH in the requested context" error. To discourage ** this, return a very high cost here. */ pInfo->idxNum = FTS3_FULLSCAN_SEARCH; pInfo->estimatedCost = 1e50; fts3SetEstimatedRows(pInfo, ((sqlite3_int64)1) << 50); return SQLITE_OK; } continue; } bDocid = (pCons->iColumn<0 || pCons->iColumn==p->nColumn+1); /* A direct lookup on the rowid or docid column. Assign a cost of 1.0. */ if( iCons<0 && pCons->op==SQLITE_INDEX_CONSTRAINT_EQ && bDocid ){ pInfo->idxNum = FTS3_DOCID_SEARCH; pInfo->estimatedCost = 1.0; iCons = i; } /* A MATCH constraint. Use a full-text search. ** ** If there is more than one MATCH constraint available, use the first ** one encountered. If there is both a MATCH constraint and a direct ** rowid/docid lookup, prefer the MATCH strategy. This is done even ** though the rowid/docid lookup is faster than a MATCH query, selecting ** it would lead to an "unable to use function MATCH in the requested ** context" error. */ if( pCons->op==SQLITE_INDEX_CONSTRAINT_MATCH && pCons->iColumn>=0 && pCons->iColumn<=p->nColumn ){ pInfo->idxNum = FTS3_FULLTEXT_SEARCH + pCons->iColumn; pInfo->estimatedCost = 2.0; iCons = i; } /* Equality constraint on the langid column */ if( pCons->op==SQLITE_INDEX_CONSTRAINT_EQ && pCons->iColumn==p->nColumn + 2 ){ iLangidCons = i; } if( bDocid ){ switch( pCons->op ){ case SQLITE_INDEX_CONSTRAINT_GE: case SQLITE_INDEX_CONSTRAINT_GT: iDocidGe = i; break; case SQLITE_INDEX_CONSTRAINT_LE: case SQLITE_INDEX_CONSTRAINT_LT: iDocidLe = i; break; } } } /* If using a docid=? or rowid=? strategy, set the UNIQUE flag. */ if( pInfo->idxNum==FTS3_DOCID_SEARCH ) fts3SetUniqueFlag(pInfo); iIdx = 1; if( iCons>=0 ){ pInfo->aConstraintUsage[iCons].argvIndex = iIdx++; pInfo->aConstraintUsage[iCons].omit = 1; } if( iLangidCons>=0 ){ pInfo->idxNum |= FTS3_HAVE_LANGID; pInfo->aConstraintUsage[iLangidCons].argvIndex = iIdx++; } if( iDocidGe>=0 ){ pInfo->idxNum |= FTS3_HAVE_DOCID_GE; pInfo->aConstraintUsage[iDocidGe].argvIndex = iIdx++; } if( iDocidLe>=0 ){ pInfo->idxNum |= FTS3_HAVE_DOCID_LE; pInfo->aConstraintUsage[iDocidLe].argvIndex = iIdx++; } /* Regardless of the strategy selected, FTS can deliver rows in rowid (or ** docid) order. Both ascending and descending are possible. */ if( pInfo->nOrderBy==1 ){ struct sqlite3_index_orderby *pOrder = &pInfo->aOrderBy[0]; if( pOrder->iColumn<0 || pOrder->iColumn==p->nColumn+1 ){ if( pOrder->desc ){ pInfo->idxStr = "DESC"; }else{ pInfo->idxStr = "ASC"; } pInfo->orderByConsumed = 1; } } assert( p->pSegments==0 ); return SQLITE_OK; } /* ** Implementation of xOpen method. */ static int fts3OpenMethod(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCsr){ sqlite3_vtab_cursor *pCsr; /* Allocated cursor */ UNUSED_PARAMETER(pVTab); /* Allocate a buffer large enough for an Fts3Cursor structure. If the ** allocation succeeds, zero it and return SQLITE_OK. Otherwise, ** if the allocation fails, return SQLITE_NOMEM. */ *ppCsr = pCsr = (sqlite3_vtab_cursor *)sqlite3_malloc(sizeof(Fts3Cursor)); if( !pCsr ){ return SQLITE_NOMEM; } memset(pCsr, 0, sizeof(Fts3Cursor)); return SQLITE_OK; } /* ** Close the cursor. For additional information see the documentation ** on the xClose method of the virtual table interface. */ static int fts3CloseMethod(sqlite3_vtab_cursor *pCursor){ Fts3Cursor *pCsr = (Fts3Cursor *)pCursor; assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 ); sqlite3_finalize(pCsr->pStmt); sqlite3Fts3ExprFree(pCsr->pExpr); sqlite3Fts3FreeDeferredTokens(pCsr); sqlite3_free(pCsr->aDoclist); sqlite3Fts3MIBufferFree(pCsr->pMIBuffer); assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 ); sqlite3_free(pCsr); return SQLITE_OK; } /* ** If pCsr->pStmt has not been prepared (i.e. if pCsr->pStmt==0), then ** compose and prepare an SQL statement of the form: ** ** "SELECT FROM %_content WHERE rowid = ?" ** ** (or the equivalent for a content=xxx table) and set pCsr->pStmt to ** it. If an error occurs, return an SQLite error code. ** ** Otherwise, set *ppStmt to point to pCsr->pStmt and return SQLITE_OK. */ static int fts3CursorSeekStmt(Fts3Cursor *pCsr, sqlite3_stmt **ppStmt){ int rc = SQLITE_OK; if( pCsr->pStmt==0 ){ Fts3Table *p = (Fts3Table *)pCsr->base.pVtab; char *zSql; zSql = sqlite3_mprintf("SELECT %s WHERE rowid = ?", p->zReadExprlist); if( !zSql ) return SQLITE_NOMEM; rc = sqlite3_prepare_v2(p->db, zSql, -1, &pCsr->pStmt, 0); sqlite3_free(zSql); } *ppStmt = pCsr->pStmt; return rc; } /* ** Position the pCsr->pStmt statement so that it is on the row ** of the %_content table that contains the last match. Return ** SQLITE_OK on success. */ static int fts3CursorSeek(sqlite3_context *pContext, Fts3Cursor *pCsr){ int rc = SQLITE_OK; if( pCsr->isRequireSeek ){ sqlite3_stmt *pStmt = 0; rc = fts3CursorSeekStmt(pCsr, &pStmt); if( rc==SQLITE_OK ){ sqlite3_bind_int64(pCsr->pStmt, 1, pCsr->iPrevId); pCsr->isRequireSeek = 0; if( SQLITE_ROW==sqlite3_step(pCsr->pStmt) ){ return SQLITE_OK; }else{ rc = sqlite3_reset(pCsr->pStmt); if( rc==SQLITE_OK && ((Fts3Table *)pCsr->base.pVtab)->zContentTbl==0 ){ /* If no row was found and no error has occurred, then the %_content ** table is missing a row that is present in the full-text index. ** The data structures are corrupt. */ rc = FTS_CORRUPT_VTAB; pCsr->isEof = 1; } } } } if( rc!=SQLITE_OK && pContext ){ sqlite3_result_error_code(pContext, rc); } return rc; } /* ** This function is used to process a single interior node when searching ** a b-tree for a term or term prefix. The node data is passed to this ** function via the zNode/nNode parameters. The term to search for is ** passed in zTerm/nTerm. ** ** If piFirst is not NULL, then this function sets *piFirst to the blockid ** of the child node that heads the sub-tree that may contain the term. ** ** If piLast is not NULL, then *piLast is set to the right-most child node ** that heads a sub-tree that may contain a term for which zTerm/nTerm is ** a prefix. ** ** If an OOM error occurs, SQLITE_NOMEM is returned. Otherwise, SQLITE_OK. */ static int fts3ScanInteriorNode( const char *zTerm, /* Term to select leaves for */ int nTerm, /* Size of term zTerm in bytes */ const char *zNode, /* Buffer containing segment interior node */ int nNode, /* Size of buffer at zNode */ sqlite3_int64 *piFirst, /* OUT: Selected child node */ sqlite3_int64 *piLast /* OUT: Selected child node */ ){ int rc = SQLITE_OK; /* Return code */ const char *zCsr = zNode; /* Cursor to iterate through node */ const char *zEnd = &zCsr[nNode];/* End of interior node buffer */ char *zBuffer = 0; /* Buffer to load terms into */ int nAlloc = 0; /* Size of allocated buffer */ int isFirstTerm = 1; /* True when processing first term on page */ sqlite3_int64 iChild; /* Block id of child node to descend to */ /* Skip over the 'height' varint that occurs at the start of every ** interior node. Then load the blockid of the left-child of the b-tree ** node into variable iChild. ** ** Even if the data structure on disk is corrupted, this (reading two ** varints from the buffer) does not risk an overread. If zNode is a ** root node, then the buffer comes from a SELECT statement. SQLite does ** not make this guarantee explicitly, but in practice there are always ** either more than 20 bytes of allocated space following the nNode bytes of ** contents, or two zero bytes. Or, if the node is read from the %_segments ** table, then there are always 20 bytes of zeroed padding following the ** nNode bytes of content (see sqlite3Fts3ReadBlock() for details). */ zCsr += sqlite3Fts3GetVarint(zCsr, &iChild); zCsr += sqlite3Fts3GetVarint(zCsr, &iChild); if( zCsr>zEnd ){ return FTS_CORRUPT_VTAB; } while( zCsrzEnd ){ rc = FTS_CORRUPT_VTAB; goto finish_scan; } if( nPrefix+nSuffix>nAlloc ){ char *zNew; nAlloc = (nPrefix+nSuffix) * 2; zNew = (char *)sqlite3_realloc(zBuffer, nAlloc); if( !zNew ){ rc = SQLITE_NOMEM; goto finish_scan; } zBuffer = zNew; } assert( zBuffer ); memcpy(&zBuffer[nPrefix], zCsr, nSuffix); nBuffer = nPrefix + nSuffix; zCsr += nSuffix; /* Compare the term we are searching for with the term just loaded from ** the interior node. If the specified term is greater than or equal ** to the term from the interior node, then all terms on the sub-tree ** headed by node iChild are smaller than zTerm. No need to search ** iChild. ** ** If the interior node term is larger than the specified term, then ** the tree headed by iChild may contain the specified term. */ cmp = memcmp(zTerm, zBuffer, (nBuffer>nTerm ? nTerm : nBuffer)); if( piFirst && (cmp<0 || (cmp==0 && nBuffer>nTerm)) ){ *piFirst = iChild; piFirst = 0; } if( piLast && cmp<0 ){ *piLast = iChild; piLast = 0; } iChild++; }; if( piFirst ) *piFirst = iChild; if( piLast ) *piLast = iChild; finish_scan: sqlite3_free(zBuffer); return rc; } /* ** The buffer pointed to by argument zNode (size nNode bytes) contains an ** interior node of a b-tree segment. The zTerm buffer (size nTerm bytes) ** contains a term. This function searches the sub-tree headed by the zNode ** node for the range of leaf nodes that may contain the specified term ** or terms for which the specified term is a prefix. ** ** If piLeaf is not NULL, then *piLeaf is set to the blockid of the ** left-most leaf node in the tree that may contain the specified term. ** If piLeaf2 is not NULL, then *piLeaf2 is set to the blockid of the ** right-most leaf node that may contain a term for which the specified ** term is a prefix. ** ** It is possible that the range of returned leaf nodes does not contain ** the specified term or any terms for which it is a prefix. However, if the ** segment does contain any such terms, they are stored within the identified ** range. Because this function only inspects interior segment nodes (and ** never loads leaf nodes into memory), it is not possible to be sure. ** ** If an error occurs, an error code other than SQLITE_OK is returned. */ static int fts3SelectLeaf( Fts3Table *p, /* Virtual table handle */ const char *zTerm, /* Term to select leaves for */ int nTerm, /* Size of term zTerm in bytes */ const char *zNode, /* Buffer containing segment interior node */ int nNode, /* Size of buffer at zNode */ sqlite3_int64 *piLeaf, /* Selected leaf node */ sqlite3_int64 *piLeaf2 /* Selected leaf node */ ){ int rc = SQLITE_OK; /* Return code */ int iHeight; /* Height of this node in tree */ assert( piLeaf || piLeaf2 ); fts3GetVarint32(zNode, &iHeight); rc = fts3ScanInteriorNode(zTerm, nTerm, zNode, nNode, piLeaf, piLeaf2); assert( !piLeaf2 || !piLeaf || rc!=SQLITE_OK || (*piLeaf<=*piLeaf2) ); if( rc==SQLITE_OK && iHeight>1 ){ char *zBlob = 0; /* Blob read from %_segments table */ int nBlob = 0; /* Size of zBlob in bytes */ if( piLeaf && piLeaf2 && (*piLeaf!=*piLeaf2) ){ rc = sqlite3Fts3ReadBlock(p, *piLeaf, &zBlob, &nBlob, 0); if( rc==SQLITE_OK ){ rc = fts3SelectLeaf(p, zTerm, nTerm, zBlob, nBlob, piLeaf, 0); } sqlite3_free(zBlob); piLeaf = 0; zBlob = 0; } if( rc==SQLITE_OK ){ rc = sqlite3Fts3ReadBlock(p, piLeaf?*piLeaf:*piLeaf2, &zBlob, &nBlob, 0); } if( rc==SQLITE_OK ){ rc = fts3SelectLeaf(p, zTerm, nTerm, zBlob, nBlob, piLeaf, piLeaf2); } sqlite3_free(zBlob); } return rc; } /* ** This function is used to create delta-encoded serialized lists of FTS3 ** varints. Each call to this function appends a single varint to a list. */ static void fts3PutDeltaVarint( char **pp, /* IN/OUT: Output pointer */ sqlite3_int64 *piPrev, /* IN/OUT: Previous value written to list */ sqlite3_int64 iVal /* Write this value to the list */ ){ assert( iVal-*piPrev > 0 || (*piPrev==0 && iVal==0) ); *pp += sqlite3Fts3PutVarint(*pp, iVal-*piPrev); *piPrev = iVal; } /* ** When this function is called, *ppPoslist is assumed to point to the ** start of a position-list. After it returns, *ppPoslist points to the ** first byte after the position-list. ** ** A position list is list of positions (delta encoded) and columns for ** a single document record of a doclist. So, in other words, this ** routine advances *ppPoslist so that it points to the next docid in ** the doclist, or to the first byte past the end of the doclist. ** ** If pp is not NULL, then the contents of the position list are copied ** to *pp. *pp is set to point to the first byte past the last byte copied ** before this function returns. */ static void fts3PoslistCopy(char **pp, char **ppPoslist){ char *pEnd = *ppPoslist; char c = 0; /* The end of a position list is marked by a zero encoded as an FTS3 ** varint. A single POS_END (0) byte. Except, if the 0 byte is preceded by ** a byte with the 0x80 bit set, then it is not a varint 0, but the tail ** of some other, multi-byte, value. ** ** The following while-loop moves pEnd to point to the first byte that is not ** immediately preceded by a byte with the 0x80 bit set. Then increments ** pEnd once more so that it points to the byte immediately following the ** last byte in the position-list. */ while( *pEnd | c ){ c = *pEnd++ & 0x80; testcase( c!=0 && (*pEnd)==0 ); } pEnd++; /* Advance past the POS_END terminator byte */ if( pp ){ int n = (int)(pEnd - *ppPoslist); char *p = *pp; memcpy(p, *ppPoslist, n); p += n; *pp = p; } *ppPoslist = pEnd; } /* ** When this function is called, *ppPoslist is assumed to point to the ** start of a column-list. After it returns, *ppPoslist points to the ** to the terminator (POS_COLUMN or POS_END) byte of the column-list. ** ** A column-list is list of delta-encoded positions for a single column ** within a single document within a doclist. ** ** The column-list is terminated either by a POS_COLUMN varint (1) or ** a POS_END varint (0). This routine leaves *ppPoslist pointing to ** the POS_COLUMN or POS_END that terminates the column-list. ** ** If pp is not NULL, then the contents of the column-list are copied ** to *pp. *pp is set to point to the first byte past the last byte copied ** before this function returns. The POS_COLUMN or POS_END terminator ** is not copied into *pp. */ static void fts3ColumnlistCopy(char **pp, char **ppPoslist){ char *pEnd = *ppPoslist; char c = 0; /* A column-list is terminated by either a 0x01 or 0x00 byte that is ** not part of a multi-byte varint. */ while( 0xFE & (*pEnd | c) ){ c = *pEnd++ & 0x80; testcase( c!=0 && ((*pEnd)&0xfe)==0 ); } if( pp ){ int n = (int)(pEnd - *ppPoslist); char *p = *pp; memcpy(p, *ppPoslist, n); p += n; *pp = p; } *ppPoslist = pEnd; } /* ** Value used to signify the end of an position-list. This is safe because ** it is not possible to have a document with 2^31 terms. */ #define POSITION_LIST_END 0x7fffffff /* ** This function is used to help parse position-lists. When this function is ** called, *pp may point to the start of the next varint in the position-list ** being parsed, or it may point to 1 byte past the end of the position-list ** (in which case **pp will be a terminator bytes POS_END (0) or ** (1)). ** ** If *pp points past the end of the current position-list, set *pi to ** POSITION_LIST_END and return. Otherwise, read the next varint from *pp, ** increment the current value of *pi by the value read, and set *pp to ** point to the next value before returning. ** ** Before calling this routine *pi must be initialized to the value of ** the previous position, or zero if we are reading the first position ** in the position-list. Because positions are delta-encoded, the value ** of the previous position is needed in order to compute the value of ** the next position. */ static void fts3ReadNextPos( char **pp, /* IN/OUT: Pointer into position-list buffer */ sqlite3_int64 *pi /* IN/OUT: Value read from position-list */ ){ if( (**pp)&0xFE ){ fts3GetDeltaVarint(pp, pi); *pi -= 2; }else{ *pi = POSITION_LIST_END; } } /* ** If parameter iCol is not 0, write an POS_COLUMN (1) byte followed by ** the value of iCol encoded as a varint to *pp. This will start a new ** column list. ** ** Set *pp to point to the byte just after the last byte written before ** returning (do not modify it if iCol==0). Return the total number of bytes ** written (0 if iCol==0). */ static int fts3PutColNumber(char **pp, int iCol){ int n = 0; /* Number of bytes written */ if( iCol ){ char *p = *pp; /* Output pointer */ n = 1 + sqlite3Fts3PutVarint(&p[1], iCol); *p = 0x01; *pp = &p[n]; } return n; } /* ** Compute the union of two position lists. The output written ** into *pp contains all positions of both *pp1 and *pp2 in sorted ** order and with any duplicates removed. All pointers are ** updated appropriately. The caller is responsible for insuring ** that there is enough space in *pp to hold the complete output. */ static void fts3PoslistMerge( char **pp, /* Output buffer */ char **pp1, /* Left input list */ char **pp2 /* Right input list */ ){ char *p = *pp; char *p1 = *pp1; char *p2 = *pp2; while( *p1 || *p2 ){ int iCol1; /* The current column index in pp1 */ int iCol2; /* The current column index in pp2 */ if( *p1==POS_COLUMN ) fts3GetVarint32(&p1[1], &iCol1); else if( *p1==POS_END ) iCol1 = POSITION_LIST_END; else iCol1 = 0; if( *p2==POS_COLUMN ) fts3GetVarint32(&p2[1], &iCol2); else if( *p2==POS_END ) iCol2 = POSITION_LIST_END; else iCol2 = 0; if( iCol1==iCol2 ){ sqlite3_int64 i1 = 0; /* Last position from pp1 */ sqlite3_int64 i2 = 0; /* Last position from pp2 */ sqlite3_int64 iPrev = 0; int n = fts3PutColNumber(&p, iCol1); p1 += n; p2 += n; /* At this point, both p1 and p2 point to the start of column-lists ** for the same column (the column with index iCol1 and iCol2). ** A column-list is a list of non-negative delta-encoded varints, each ** incremented by 2 before being stored. Each list is terminated by a ** POS_END (0) or POS_COLUMN (1). The following block merges the two lists ** and writes the results to buffer p. p is left pointing to the byte ** after the list written. No terminator (POS_END or POS_COLUMN) is ** written to the output. */ fts3GetDeltaVarint(&p1, &i1); fts3GetDeltaVarint(&p2, &i2); do { fts3PutDeltaVarint(&p, &iPrev, (i1pos(*pp1) && pos(*pp2)-pos(*pp1)<=nToken). i.e. ** when the *pp1 token appears before the *pp2 token, but not more than nToken ** slots before it. ** ** e.g. nToken==1 searches for adjacent positions. */ static int fts3PoslistPhraseMerge( char **pp, /* IN/OUT: Preallocated output buffer */ int nToken, /* Maximum difference in token positions */ int isSaveLeft, /* Save the left position */ int isExact, /* If *pp1 is exactly nTokens before *pp2 */ char **pp1, /* IN/OUT: Left input list */ char **pp2 /* IN/OUT: Right input list */ ){ char *p = *pp; char *p1 = *pp1; char *p2 = *pp2; int iCol1 = 0; int iCol2 = 0; /* Never set both isSaveLeft and isExact for the same invocation. */ assert( isSaveLeft==0 || isExact==0 ); assert( p!=0 && *p1!=0 && *p2!=0 ); if( *p1==POS_COLUMN ){ p1++; p1 += fts3GetVarint32(p1, &iCol1); } if( *p2==POS_COLUMN ){ p2++; p2 += fts3GetVarint32(p2, &iCol2); } while( 1 ){ if( iCol1==iCol2 ){ char *pSave = p; sqlite3_int64 iPrev = 0; sqlite3_int64 iPos1 = 0; sqlite3_int64 iPos2 = 0; if( iCol1 ){ *p++ = POS_COLUMN; p += sqlite3Fts3PutVarint(p, iCol1); } assert( *p1!=POS_END && *p1!=POS_COLUMN ); assert( *p2!=POS_END && *p2!=POS_COLUMN ); fts3GetDeltaVarint(&p1, &iPos1); iPos1 -= 2; fts3GetDeltaVarint(&p2, &iPos2); iPos2 -= 2; while( 1 ){ if( iPos2==iPos1+nToken || (isExact==0 && iPos2>iPos1 && iPos2<=iPos1+nToken) ){ sqlite3_int64 iSave; iSave = isSaveLeft ? iPos1 : iPos2; fts3PutDeltaVarint(&p, &iPrev, iSave+2); iPrev -= 2; pSave = 0; assert( p ); } if( (!isSaveLeft && iPos2<=(iPos1+nToken)) || iPos2<=iPos1 ){ if( (*p2&0xFE)==0 ) break; fts3GetDeltaVarint(&p2, &iPos2); iPos2 -= 2; }else{ if( (*p1&0xFE)==0 ) break; fts3GetDeltaVarint(&p1, &iPos1); iPos1 -= 2; } } if( pSave ){ assert( pp && p ); p = pSave; } fts3ColumnlistCopy(0, &p1); fts3ColumnlistCopy(0, &p2); assert( (*p1&0xFE)==0 && (*p2&0xFE)==0 ); if( 0==*p1 || 0==*p2 ) break; p1++; p1 += fts3GetVarint32(p1, &iCol1); p2++; p2 += fts3GetVarint32(p2, &iCol2); } /* Advance pointer p1 or p2 (whichever corresponds to the smaller of ** iCol1 and iCol2) so that it points to either the 0x00 that marks the ** end of the position list, or the 0x01 that precedes the next ** column-number in the position list. */ else if( iCol1=pEnd ){ *pp = 0; }else{ sqlite3_int64 iVal; *pp += sqlite3Fts3GetVarint(*pp, &iVal); if( bDescIdx ){ *pVal -= iVal; }else{ *pVal += iVal; } } } /* ** This function is used to write a single varint to a buffer. The varint ** is written to *pp. Before returning, *pp is set to point 1 byte past the ** end of the value written. ** ** If *pbFirst is zero when this function is called, the value written to ** the buffer is that of parameter iVal. ** ** If *pbFirst is non-zero when this function is called, then the value ** written is either (iVal-*piPrev) (if bDescIdx is zero) or (*piPrev-iVal) ** (if bDescIdx is non-zero). ** ** Before returning, this function always sets *pbFirst to 1 and *piPrev ** to the value of parameter iVal. */ static void fts3PutDeltaVarint3( char **pp, /* IN/OUT: Output pointer */ int bDescIdx, /* True for descending docids */ sqlite3_int64 *piPrev, /* IN/OUT: Previous value written to list */ int *pbFirst, /* IN/OUT: True after first int written */ sqlite3_int64 iVal /* Write this value to the list */ ){ sqlite3_int64 iWrite; if( bDescIdx==0 || *pbFirst==0 ){ iWrite = iVal - *piPrev; }else{ iWrite = *piPrev - iVal; } assert( *pbFirst || *piPrev==0 ); assert( *pbFirst==0 || iWrite>0 ); *pp += sqlite3Fts3PutVarint(*pp, iWrite); *piPrev = iVal; *pbFirst = 1; } /* ** This macro is used by various functions that merge doclists. The two ** arguments are 64-bit docid values. If the value of the stack variable ** bDescDoclist is 0 when this macro is invoked, then it returns (i1-i2). ** Otherwise, (i2-i1). ** ** Using this makes it easier to write code that can merge doclists that are ** sorted in either ascending or descending order. */ #define DOCID_CMP(i1, i2) ((bDescDoclist?-1:1) * (i1-i2)) /* ** This function does an "OR" merge of two doclists (output contains all ** positions contained in either argument doclist). If the docids in the ** input doclists are sorted in ascending order, parameter bDescDoclist ** should be false. If they are sorted in ascending order, it should be ** passed a non-zero value. ** ** If no error occurs, *paOut is set to point at an sqlite3_malloc'd buffer ** containing the output doclist and SQLITE_OK is returned. In this case ** *pnOut is set to the number of bytes in the output doclist. ** ** If an error occurs, an SQLite error code is returned. The output values ** are undefined in this case. */ static int fts3DoclistOrMerge( int bDescDoclist, /* True if arguments are desc */ char *a1, int n1, /* First doclist */ char *a2, int n2, /* Second doclist */ char **paOut, int *pnOut /* OUT: Malloc'd doclist */ ){ sqlite3_int64 i1 = 0; sqlite3_int64 i2 = 0; sqlite3_int64 iPrev = 0; char *pEnd1 = &a1[n1]; char *pEnd2 = &a2[n2]; char *p1 = a1; char *p2 = a2; char *p; char *aOut; int bFirstOut = 0; *paOut = 0; *pnOut = 0; /* Allocate space for the output. Both the input and output doclists ** are delta encoded. If they are in ascending order (bDescDoclist==0), ** then the first docid in each list is simply encoded as a varint. For ** each subsequent docid, the varint stored is the difference between the ** current and previous docid (a positive number - since the list is in ** ascending order). ** ** The first docid written to the output is therefore encoded using the ** same number of bytes as it is in whichever of the input lists it is ** read from. And each subsequent docid read from the same input list ** consumes either the same or less bytes as it did in the input (since ** the difference between it and the previous value in the output must ** be a positive value less than or equal to the delta value read from ** the input list). The same argument applies to all but the first docid ** read from the 'other' list. And to the contents of all position lists ** that will be copied and merged from the input to the output. ** ** However, if the first docid copied to the output is a negative number, ** then the encoding of the first docid from the 'other' input list may ** be larger in the output than it was in the input (since the delta value ** may be a larger positive integer than the actual docid). ** ** The space required to store the output is therefore the sum of the ** sizes of the two inputs, plus enough space for exactly one of the input ** docids to grow. ** ** A symetric argument may be made if the doclists are in descending ** order. */ aOut = sqlite3_malloc(n1+n2+FTS3_VARINT_MAX-1); if( !aOut ) return SQLITE_NOMEM; p = aOut; fts3GetDeltaVarint3(&p1, pEnd1, 0, &i1); fts3GetDeltaVarint3(&p2, pEnd2, 0, &i2); while( p1 || p2 ){ sqlite3_int64 iDiff = DOCID_CMP(i1, i2); if( p2 && p1 && iDiff==0 ){ fts3PutDeltaVarint3(&p, bDescDoclist, &iPrev, &bFirstOut, i1); fts3PoslistMerge(&p, &p1, &p2); fts3GetDeltaVarint3(&p1, pEnd1, bDescDoclist, &i1); fts3GetDeltaVarint3(&p2, pEnd2, bDescDoclist, &i2); }else if( !p2 || (p1 && iDiff<0) ){ fts3PutDeltaVarint3(&p, bDescDoclist, &iPrev, &bFirstOut, i1); fts3PoslistCopy(&p, &p1); fts3GetDeltaVarint3(&p1, pEnd1, bDescDoclist, &i1); }else{ fts3PutDeltaVarint3(&p, bDescDoclist, &iPrev, &bFirstOut, i2); fts3PoslistCopy(&p, &p2); fts3GetDeltaVarint3(&p2, pEnd2, bDescDoclist, &i2); } } *paOut = aOut; *pnOut = (int)(p-aOut); assert( *pnOut<=n1+n2+FTS3_VARINT_MAX-1 ); return SQLITE_OK; } /* ** This function does a "phrase" merge of two doclists. In a phrase merge, ** the output contains a copy of each position from the right-hand input ** doclist for which there is a position in the left-hand input doclist ** exactly nDist tokens before it. ** ** If the docids in the input doclists are sorted in ascending order, ** parameter bDescDoclist should be false. If they are sorted in ascending ** order, it should be passed a non-zero value. ** ** The right-hand input doclist is overwritten by this function. */ static int fts3DoclistPhraseMerge( int bDescDoclist, /* True if arguments are desc */ int nDist, /* Distance from left to right (1=adjacent) */ char *aLeft, int nLeft, /* Left doclist */ char **paRight, int *pnRight /* IN/OUT: Right/output doclist */ ){ sqlite3_int64 i1 = 0; sqlite3_int64 i2 = 0; sqlite3_int64 iPrev = 0; char *aRight = *paRight; char *pEnd1 = &aLeft[nLeft]; char *pEnd2 = &aRight[*pnRight]; char *p1 = aLeft; char *p2 = aRight; char *p; int bFirstOut = 0; char *aOut; assert( nDist>0 ); if( bDescDoclist ){ aOut = sqlite3_malloc(*pnRight + FTS3_VARINT_MAX); if( aOut==0 ) return SQLITE_NOMEM; }else{ aOut = aRight; } p = aOut; fts3GetDeltaVarint3(&p1, pEnd1, 0, &i1); fts3GetDeltaVarint3(&p2, pEnd2, 0, &i2); while( p1 && p2 ){ sqlite3_int64 iDiff = DOCID_CMP(i1, i2); if( iDiff==0 ){ char *pSave = p; sqlite3_int64 iPrevSave = iPrev; int bFirstOutSave = bFirstOut; fts3PutDeltaVarint3(&p, bDescDoclist, &iPrev, &bFirstOut, i1); if( 0==fts3PoslistPhraseMerge(&p, nDist, 0, 1, &p1, &p2) ){ p = pSave; iPrev = iPrevSave; bFirstOut = bFirstOutSave; } fts3GetDeltaVarint3(&p1, pEnd1, bDescDoclist, &i1); fts3GetDeltaVarint3(&p2, pEnd2, bDescDoclist, &i2); }else if( iDiff<0 ){ fts3PoslistCopy(0, &p1); fts3GetDeltaVarint3(&p1, pEnd1, bDescDoclist, &i1); }else{ fts3PoslistCopy(0, &p2); fts3GetDeltaVarint3(&p2, pEnd2, bDescDoclist, &i2); } } *pnRight = (int)(p - aOut); if( bDescDoclist ){ sqlite3_free(aRight); *paRight = aOut; } return SQLITE_OK; } /* ** Argument pList points to a position list nList bytes in size. This ** function checks to see if the position list contains any entries for ** a token in position 0 (of any column). If so, it writes argument iDelta ** to the output buffer pOut, followed by a position list consisting only ** of the entries from pList at position 0, and terminated by an 0x00 byte. ** The value returned is the number of bytes written to pOut (if any). */ SQLITE_PRIVATE int sqlite3Fts3FirstFilter( sqlite3_int64 iDelta, /* Varint that may be written to pOut */ char *pList, /* Position list (no 0x00 term) */ int nList, /* Size of pList in bytes */ char *pOut /* Write output here */ ){ int nOut = 0; int bWritten = 0; /* True once iDelta has been written */ char *p = pList; char *pEnd = &pList[nList]; if( *p!=0x01 ){ if( *p==0x02 ){ nOut += sqlite3Fts3PutVarint(&pOut[nOut], iDelta); pOut[nOut++] = 0x02; bWritten = 1; } fts3ColumnlistCopy(0, &p); } while( paaOutput); i++){ if( pTS->aaOutput[i] ){ if( !aOut ){ aOut = pTS->aaOutput[i]; nOut = pTS->anOutput[i]; pTS->aaOutput[i] = 0; }else{ int nNew; char *aNew; int rc = fts3DoclistOrMerge(p->bDescIdx, pTS->aaOutput[i], pTS->anOutput[i], aOut, nOut, &aNew, &nNew ); if( rc!=SQLITE_OK ){ sqlite3_free(aOut); return rc; } sqlite3_free(pTS->aaOutput[i]); sqlite3_free(aOut); pTS->aaOutput[i] = 0; aOut = aNew; nOut = nNew; } } } pTS->aaOutput[0] = aOut; pTS->anOutput[0] = nOut; return SQLITE_OK; } /* ** Merge the doclist aDoclist/nDoclist into the TermSelect object passed ** as the first argument. The merge is an "OR" merge (see function ** fts3DoclistOrMerge() for details). ** ** This function is called with the doclist for each term that matches ** a queried prefix. It merges all these doclists into one, the doclist ** for the specified prefix. Since there can be a very large number of ** doclists to merge, the merging is done pair-wise using the TermSelect ** object. ** ** This function returns SQLITE_OK if the merge is successful, or an ** SQLite error code (SQLITE_NOMEM) if an error occurs. */ static int fts3TermSelectMerge( Fts3Table *p, /* FTS table handle */ TermSelect *pTS, /* TermSelect object to merge into */ char *aDoclist, /* Pointer to doclist */ int nDoclist /* Size of aDoclist in bytes */ ){ if( pTS->aaOutput[0]==0 ){ /* If this is the first term selected, copy the doclist to the output ** buffer using memcpy(). ** ** Add FTS3_VARINT_MAX bytes of unused space to the end of the ** allocation. This is so as to ensure that the buffer is big enough ** to hold the current doclist AND'd with any other doclist. If the ** doclists are stored in order=ASC order, this padding would not be ** required (since the size of [doclistA AND doclistB] is always less ** than or equal to the size of [doclistA] in that case). But this is ** not true for order=DESC. For example, a doclist containing (1, -1) ** may be smaller than (-1), as in the first example the -1 may be stored ** as a single-byte delta, whereas in the second it must be stored as a ** FTS3_VARINT_MAX byte varint. ** ** Similar padding is added in the fts3DoclistOrMerge() function. */ pTS->aaOutput[0] = sqlite3_malloc(nDoclist + FTS3_VARINT_MAX + 1); pTS->anOutput[0] = nDoclist; if( pTS->aaOutput[0] ){ memcpy(pTS->aaOutput[0], aDoclist, nDoclist); }else{ return SQLITE_NOMEM; } }else{ char *aMerge = aDoclist; int nMerge = nDoclist; int iOut; for(iOut=0; iOutaaOutput); iOut++){ if( pTS->aaOutput[iOut]==0 ){ assert( iOut>0 ); pTS->aaOutput[iOut] = aMerge; pTS->anOutput[iOut] = nMerge; break; }else{ char *aNew; int nNew; int rc = fts3DoclistOrMerge(p->bDescIdx, aMerge, nMerge, pTS->aaOutput[iOut], pTS->anOutput[iOut], &aNew, &nNew ); if( rc!=SQLITE_OK ){ if( aMerge!=aDoclist ) sqlite3_free(aMerge); return rc; } if( aMerge!=aDoclist ) sqlite3_free(aMerge); sqlite3_free(pTS->aaOutput[iOut]); pTS->aaOutput[iOut] = 0; aMerge = aNew; nMerge = nNew; if( (iOut+1)==SizeofArray(pTS->aaOutput) ){ pTS->aaOutput[iOut] = aMerge; pTS->anOutput[iOut] = nMerge; } } } } return SQLITE_OK; } /* ** Append SegReader object pNew to the end of the pCsr->apSegment[] array. */ static int fts3SegReaderCursorAppend( Fts3MultiSegReader *pCsr, Fts3SegReader *pNew ){ if( (pCsr->nSegment%16)==0 ){ Fts3SegReader **apNew; int nByte = (pCsr->nSegment + 16)*sizeof(Fts3SegReader*); apNew = (Fts3SegReader **)sqlite3_realloc(pCsr->apSegment, nByte); if( !apNew ){ sqlite3Fts3SegReaderFree(pNew); return SQLITE_NOMEM; } pCsr->apSegment = apNew; } pCsr->apSegment[pCsr->nSegment++] = pNew; return SQLITE_OK; } /* ** Add seg-reader objects to the Fts3MultiSegReader object passed as the ** 8th argument. ** ** This function returns SQLITE_OK if successful, or an SQLite error code ** otherwise. */ static int fts3SegReaderCursor( Fts3Table *p, /* FTS3 table handle */ int iLangid, /* Language id */ int iIndex, /* Index to search (from 0 to p->nIndex-1) */ int iLevel, /* Level of segments to scan */ const char *zTerm, /* Term to query for */ int nTerm, /* Size of zTerm in bytes */ int isPrefix, /* True for a prefix search */ int isScan, /* True to scan from zTerm to EOF */ Fts3MultiSegReader *pCsr /* Cursor object to populate */ ){ int rc = SQLITE_OK; /* Error code */ sqlite3_stmt *pStmt = 0; /* Statement to iterate through segments */ int rc2; /* Result of sqlite3_reset() */ /* If iLevel is less than 0 and this is not a scan, include a seg-reader ** for the pending-terms. If this is a scan, then this call must be being ** made by an fts4aux module, not an FTS table. In this case calling ** Fts3SegReaderPending might segfault, as the data structures used by ** fts4aux are not completely populated. So it's easiest to filter these ** calls out here. */ if( iLevel<0 && p->aIndex ){ Fts3SegReader *pSeg = 0; rc = sqlite3Fts3SegReaderPending(p, iIndex, zTerm, nTerm, isPrefix||isScan, &pSeg); if( rc==SQLITE_OK && pSeg ){ rc = fts3SegReaderCursorAppend(pCsr, pSeg); } } if( iLevel!=FTS3_SEGCURSOR_PENDING ){ if( rc==SQLITE_OK ){ rc = sqlite3Fts3AllSegdirs(p, iLangid, iIndex, iLevel, &pStmt); } while( rc==SQLITE_OK && SQLITE_ROW==(rc = sqlite3_step(pStmt)) ){ Fts3SegReader *pSeg = 0; /* Read the values returned by the SELECT into local variables. */ sqlite3_int64 iStartBlock = sqlite3_column_int64(pStmt, 1); sqlite3_int64 iLeavesEndBlock = sqlite3_column_int64(pStmt, 2); sqlite3_int64 iEndBlock = sqlite3_column_int64(pStmt, 3); int nRoot = sqlite3_column_bytes(pStmt, 4); char const *zRoot = sqlite3_column_blob(pStmt, 4); /* If zTerm is not NULL, and this segment is not stored entirely on its ** root node, the range of leaves scanned can be reduced. Do this. */ if( iStartBlock && zTerm ){ sqlite3_int64 *pi = (isPrefix ? &iLeavesEndBlock : 0); rc = fts3SelectLeaf(p, zTerm, nTerm, zRoot, nRoot, &iStartBlock, pi); if( rc!=SQLITE_OK ) goto finished; if( isPrefix==0 && isScan==0 ) iLeavesEndBlock = iStartBlock; } rc = sqlite3Fts3SegReaderNew(pCsr->nSegment+1, (isPrefix==0 && isScan==0), iStartBlock, iLeavesEndBlock, iEndBlock, zRoot, nRoot, &pSeg ); if( rc!=SQLITE_OK ) goto finished; rc = fts3SegReaderCursorAppend(pCsr, pSeg); } } finished: rc2 = sqlite3_reset(pStmt); if( rc==SQLITE_DONE ) rc = rc2; return rc; } /* ** Set up a cursor object for iterating through a full-text index or a ** single level therein. */ SQLITE_PRIVATE int sqlite3Fts3SegReaderCursor( Fts3Table *p, /* FTS3 table handle */ int iLangid, /* Language-id to search */ int iIndex, /* Index to search (from 0 to p->nIndex-1) */ int iLevel, /* Level of segments to scan */ const char *zTerm, /* Term to query for */ int nTerm, /* Size of zTerm in bytes */ int isPrefix, /* True for a prefix search */ int isScan, /* True to scan from zTerm to EOF */ Fts3MultiSegReader *pCsr /* Cursor object to populate */ ){ assert( iIndex>=0 && iIndexnIndex ); assert( iLevel==FTS3_SEGCURSOR_ALL || iLevel==FTS3_SEGCURSOR_PENDING || iLevel>=0 ); assert( iLevelbase.pVtab; if( isPrefix ){ for(i=1; bFound==0 && inIndex; i++){ if( p->aIndex[i].nPrefix==nTerm ){ bFound = 1; rc = sqlite3Fts3SegReaderCursor(p, pCsr->iLangid, i, FTS3_SEGCURSOR_ALL, zTerm, nTerm, 0, 0, pSegcsr ); pSegcsr->bLookup = 1; } } for(i=1; bFound==0 && inIndex; i++){ if( p->aIndex[i].nPrefix==nTerm+1 ){ bFound = 1; rc = sqlite3Fts3SegReaderCursor(p, pCsr->iLangid, i, FTS3_SEGCURSOR_ALL, zTerm, nTerm, 1, 0, pSegcsr ); if( rc==SQLITE_OK ){ rc = fts3SegReaderCursorAddZero( p, pCsr->iLangid, zTerm, nTerm, pSegcsr ); } } } } if( bFound==0 ){ rc = sqlite3Fts3SegReaderCursor(p, pCsr->iLangid, 0, FTS3_SEGCURSOR_ALL, zTerm, nTerm, isPrefix, 0, pSegcsr ); pSegcsr->bLookup = !isPrefix; } } *ppSegcsr = pSegcsr; return rc; } /* ** Free an Fts3MultiSegReader allocated by fts3TermSegReaderCursor(). */ static void fts3SegReaderCursorFree(Fts3MultiSegReader *pSegcsr){ sqlite3Fts3SegReaderFinish(pSegcsr); sqlite3_free(pSegcsr); } /* ** This function retrieves the doclist for the specified term (or term ** prefix) from the database. */ static int fts3TermSelect( Fts3Table *p, /* Virtual table handle */ Fts3PhraseToken *pTok, /* Token to query for */ int iColumn, /* Column to query (or -ve for all columns) */ int *pnOut, /* OUT: Size of buffer at *ppOut */ char **ppOut /* OUT: Malloced result buffer */ ){ int rc; /* Return code */ Fts3MultiSegReader *pSegcsr; /* Seg-reader cursor for this term */ TermSelect tsc; /* Object for pair-wise doclist merging */ Fts3SegFilter filter; /* Segment term filter configuration */ pSegcsr = pTok->pSegcsr; memset(&tsc, 0, sizeof(TermSelect)); filter.flags = FTS3_SEGMENT_IGNORE_EMPTY | FTS3_SEGMENT_REQUIRE_POS | (pTok->isPrefix ? FTS3_SEGMENT_PREFIX : 0) | (pTok->bFirst ? FTS3_SEGMENT_FIRST : 0) | (iColumnnColumn ? FTS3_SEGMENT_COLUMN_FILTER : 0); filter.iCol = iColumn; filter.zTerm = pTok->z; filter.nTerm = pTok->n; rc = sqlite3Fts3SegReaderStart(p, pSegcsr, &filter); while( SQLITE_OK==rc && SQLITE_ROW==(rc = sqlite3Fts3SegReaderStep(p, pSegcsr)) ){ rc = fts3TermSelectMerge(p, &tsc, pSegcsr->aDoclist, pSegcsr->nDoclist); } if( rc==SQLITE_OK ){ rc = fts3TermSelectFinishMerge(p, &tsc); } if( rc==SQLITE_OK ){ *ppOut = tsc.aaOutput[0]; *pnOut = tsc.anOutput[0]; }else{ int i; for(i=0; ipSegcsr = 0; return rc; } /* ** This function counts the total number of docids in the doclist stored ** in buffer aList[], size nList bytes. ** ** If the isPoslist argument is true, then it is assumed that the doclist ** contains a position-list following each docid. Otherwise, it is assumed ** that the doclist is simply a list of docids stored as delta encoded ** varints. */ static int fts3DoclistCountDocids(char *aList, int nList){ int nDoc = 0; /* Return value */ if( aList ){ char *aEnd = &aList[nList]; /* Pointer to one byte after EOF */ char *p = aList; /* Cursor */ while( peSearch==FTS3_DOCID_SEARCH || pCsr->eSearch==FTS3_FULLSCAN_SEARCH ){ if( SQLITE_ROW!=sqlite3_step(pCsr->pStmt) ){ pCsr->isEof = 1; rc = sqlite3_reset(pCsr->pStmt); }else{ pCsr->iPrevId = sqlite3_column_int64(pCsr->pStmt, 0); rc = SQLITE_OK; } }else{ rc = fts3EvalNext((Fts3Cursor *)pCursor); } assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 ); return rc; } /* ** The following are copied from sqliteInt.h. ** ** Constants for the largest and smallest possible 64-bit signed integers. ** These macros are designed to work correctly on both 32-bit and 64-bit ** compilers. */ #ifndef SQLITE_AMALGAMATION # define LARGEST_INT64 (0xffffffff|(((sqlite3_int64)0x7fffffff)<<32)) # define SMALLEST_INT64 (((sqlite3_int64)-1) - LARGEST_INT64) #endif /* ** If the numeric type of argument pVal is "integer", then return it ** converted to a 64-bit signed integer. Otherwise, return a copy of ** the second parameter, iDefault. */ static sqlite3_int64 fts3DocidRange(sqlite3_value *pVal, i64 iDefault){ if( pVal ){ int eType = sqlite3_value_numeric_type(pVal); if( eType==SQLITE_INTEGER ){ return sqlite3_value_int64(pVal); } } return iDefault; } /* ** This is the xFilter interface for the virtual table. See ** the virtual table xFilter method documentation for additional ** information. ** ** If idxNum==FTS3_FULLSCAN_SEARCH then do a full table scan against ** the %_content table. ** ** If idxNum==FTS3_DOCID_SEARCH then do a docid lookup for a single entry ** in the %_content table. ** ** If idxNum>=FTS3_FULLTEXT_SEARCH then use the full text index. The ** column on the left-hand side of the MATCH operator is column ** number idxNum-FTS3_FULLTEXT_SEARCH, 0 indexed. argv[0] is the right-hand ** side of the MATCH operator. */ static int fts3FilterMethod( sqlite3_vtab_cursor *pCursor, /* The cursor used for this query */ int idxNum, /* Strategy index */ const char *idxStr, /* Unused */ int nVal, /* Number of elements in apVal */ sqlite3_value **apVal /* Arguments for the indexing scheme */ ){ int rc = SQLITE_OK; char *zSql; /* SQL statement used to access %_content */ int eSearch; Fts3Table *p = (Fts3Table *)pCursor->pVtab; Fts3Cursor *pCsr = (Fts3Cursor *)pCursor; sqlite3_value *pCons = 0; /* The MATCH or rowid constraint, if any */ sqlite3_value *pLangid = 0; /* The "langid = ?" constraint, if any */ sqlite3_value *pDocidGe = 0; /* The "docid >= ?" constraint, if any */ sqlite3_value *pDocidLe = 0; /* The "docid <= ?" constraint, if any */ int iIdx; UNUSED_PARAMETER(idxStr); UNUSED_PARAMETER(nVal); eSearch = (idxNum & 0x0000FFFF); assert( eSearch>=0 && eSearch<=(FTS3_FULLTEXT_SEARCH+p->nColumn) ); assert( p->pSegments==0 ); /* Collect arguments into local variables */ iIdx = 0; if( eSearch!=FTS3_FULLSCAN_SEARCH ) pCons = apVal[iIdx++]; if( idxNum & FTS3_HAVE_LANGID ) pLangid = apVal[iIdx++]; if( idxNum & FTS3_HAVE_DOCID_GE ) pDocidGe = apVal[iIdx++]; if( idxNum & FTS3_HAVE_DOCID_LE ) pDocidLe = apVal[iIdx++]; assert( iIdx==nVal ); /* In case the cursor has been used before, clear it now. */ sqlite3_finalize(pCsr->pStmt); sqlite3_free(pCsr->aDoclist); sqlite3Fts3MIBufferFree(pCsr->pMIBuffer); sqlite3Fts3ExprFree(pCsr->pExpr); memset(&pCursor[1], 0, sizeof(Fts3Cursor)-sizeof(sqlite3_vtab_cursor)); /* Set the lower and upper bounds on docids to return */ pCsr->iMinDocid = fts3DocidRange(pDocidGe, SMALLEST_INT64); pCsr->iMaxDocid = fts3DocidRange(pDocidLe, LARGEST_INT64); if( idxStr ){ pCsr->bDesc = (idxStr[0]=='D'); }else{ pCsr->bDesc = p->bDescIdx; } pCsr->eSearch = (i16)eSearch; if( eSearch!=FTS3_DOCID_SEARCH && eSearch!=FTS3_FULLSCAN_SEARCH ){ int iCol = eSearch-FTS3_FULLTEXT_SEARCH; const char *zQuery = (const char *)sqlite3_value_text(pCons); if( zQuery==0 && sqlite3_value_type(pCons)!=SQLITE_NULL ){ return SQLITE_NOMEM; } pCsr->iLangid = 0; if( pLangid ) pCsr->iLangid = sqlite3_value_int(pLangid); assert( p->base.zErrMsg==0 ); rc = sqlite3Fts3ExprParse(p->pTokenizer, pCsr->iLangid, p->azColumn, p->bFts4, p->nColumn, iCol, zQuery, -1, &pCsr->pExpr, &p->base.zErrMsg ); if( rc!=SQLITE_OK ){ return rc; } rc = fts3EvalStart(pCsr); sqlite3Fts3SegmentsClose(p); if( rc!=SQLITE_OK ) return rc; pCsr->pNextId = pCsr->aDoclist; pCsr->iPrevId = 0; } /* Compile a SELECT statement for this cursor. For a full-table-scan, the ** statement loops through all rows of the %_content table. For a ** full-text query or docid lookup, the statement retrieves a single ** row by docid. */ if( eSearch==FTS3_FULLSCAN_SEARCH ){ if( pDocidGe || pDocidLe ){ zSql = sqlite3_mprintf( "SELECT %s WHERE rowid BETWEEN %lld AND %lld ORDER BY rowid %s", p->zReadExprlist, pCsr->iMinDocid, pCsr->iMaxDocid, (pCsr->bDesc ? "DESC" : "ASC") ); }else{ zSql = sqlite3_mprintf("SELECT %s ORDER BY rowid %s", p->zReadExprlist, (pCsr->bDesc ? "DESC" : "ASC") ); } if( zSql ){ rc = sqlite3_prepare_v2(p->db, zSql, -1, &pCsr->pStmt, 0); sqlite3_free(zSql); }else{ rc = SQLITE_NOMEM; } }else if( eSearch==FTS3_DOCID_SEARCH ){ rc = fts3CursorSeekStmt(pCsr, &pCsr->pStmt); if( rc==SQLITE_OK ){ rc = sqlite3_bind_value(pCsr->pStmt, 1, pCons); } } if( rc!=SQLITE_OK ) return rc; return fts3NextMethod(pCursor); } /* ** This is the xEof method of the virtual table. SQLite calls this ** routine to find out if it has reached the end of a result set. */ static int fts3EofMethod(sqlite3_vtab_cursor *pCursor){ return ((Fts3Cursor *)pCursor)->isEof; } /* ** This is the xRowid method. The SQLite core calls this routine to ** retrieve the rowid for the current row of the result set. fts3 ** exposes %_content.docid as the rowid for the virtual table. The ** rowid should be written to *pRowid. */ static int fts3RowidMethod(sqlite3_vtab_cursor *pCursor, sqlite_int64 *pRowid){ Fts3Cursor *pCsr = (Fts3Cursor *) pCursor; *pRowid = pCsr->iPrevId; return SQLITE_OK; } /* ** This is the xColumn method, called by SQLite to request a value from ** the row that the supplied cursor currently points to. ** ** If: ** ** (iCol < p->nColumn) -> The value of the iCol'th user column. ** (iCol == p->nColumn) -> Magic column with the same name as the table. ** (iCol == p->nColumn+1) -> Docid column ** (iCol == p->nColumn+2) -> Langid column */ static int fts3ColumnMethod( sqlite3_vtab_cursor *pCursor, /* Cursor to retrieve value from */ sqlite3_context *pCtx, /* Context for sqlite3_result_xxx() calls */ int iCol /* Index of column to read value from */ ){ int rc = SQLITE_OK; /* Return Code */ Fts3Cursor *pCsr = (Fts3Cursor *) pCursor; Fts3Table *p = (Fts3Table *)pCursor->pVtab; /* The column value supplied by SQLite must be in range. */ assert( iCol>=0 && iCol<=p->nColumn+2 ); if( iCol==p->nColumn+1 ){ /* This call is a request for the "docid" column. Since "docid" is an ** alias for "rowid", use the xRowid() method to obtain the value. */ sqlite3_result_int64(pCtx, pCsr->iPrevId); }else if( iCol==p->nColumn ){ /* The extra column whose name is the same as the table. ** Return a blob which is a pointer to the cursor. */ sqlite3_result_blob(pCtx, &pCsr, sizeof(pCsr), SQLITE_TRANSIENT); }else if( iCol==p->nColumn+2 && pCsr->pExpr ){ sqlite3_result_int64(pCtx, pCsr->iLangid); }else{ /* The requested column is either a user column (one that contains ** indexed data), or the language-id column. */ rc = fts3CursorSeek(0, pCsr); if( rc==SQLITE_OK ){ if( iCol==p->nColumn+2 ){ int iLangid = 0; if( p->zLanguageid ){ iLangid = sqlite3_column_int(pCsr->pStmt, p->nColumn+1); } sqlite3_result_int(pCtx, iLangid); }else if( sqlite3_data_count(pCsr->pStmt)>(iCol+1) ){ sqlite3_result_value(pCtx, sqlite3_column_value(pCsr->pStmt, iCol+1)); } } } assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 ); return rc; } /* ** This function is the implementation of the xUpdate callback used by ** FTS3 virtual tables. It is invoked by SQLite each time a row is to be ** inserted, updated or deleted. */ static int fts3UpdateMethod( sqlite3_vtab *pVtab, /* Virtual table handle */ int nArg, /* Size of argument array */ sqlite3_value **apVal, /* Array of arguments */ sqlite_int64 *pRowid /* OUT: The affected (or effected) rowid */ ){ return sqlite3Fts3UpdateMethod(pVtab, nArg, apVal, pRowid); } /* ** Implementation of xSync() method. Flush the contents of the pending-terms ** hash-table to the database. */ static int fts3SyncMethod(sqlite3_vtab *pVtab){ /* Following an incremental-merge operation, assuming that the input ** segments are not completely consumed (the usual case), they are updated ** in place to remove the entries that have already been merged. This ** involves updating the leaf block that contains the smallest unmerged ** entry and each block (if any) between the leaf and the root node. So ** if the height of the input segment b-trees is N, and input segments ** are merged eight at a time, updating the input segments at the end ** of an incremental-merge requires writing (8*(1+N)) blocks. N is usually ** small - often between 0 and 2. So the overhead of the incremental ** merge is somewhere between 8 and 24 blocks. To avoid this overhead ** dwarfing the actual productive work accomplished, the incremental merge ** is only attempted if it will write at least 64 leaf blocks. Hence ** nMinMerge. ** ** Of course, updating the input segments also involves deleting a bunch ** of blocks from the segments table. But this is not considered overhead ** as it would also be required by a crisis-merge that used the same input ** segments. */ const u32 nMinMerge = 64; /* Minimum amount of incr-merge work to do */ Fts3Table *p = (Fts3Table*)pVtab; int rc = sqlite3Fts3PendingTermsFlush(p); if( rc==SQLITE_OK && p->nLeafAdd>(nMinMerge/16) && p->nAutoincrmerge && p->nAutoincrmerge!=0xff ){ int mxLevel = 0; /* Maximum relative level value in db */ int A; /* Incr-merge parameter A */ rc = sqlite3Fts3MaxLevel(p, &mxLevel); assert( rc==SQLITE_OK || mxLevel==0 ); A = p->nLeafAdd * mxLevel; A += (A/2); if( A>(int)nMinMerge ) rc = sqlite3Fts3Incrmerge(p, A, p->nAutoincrmerge); } sqlite3Fts3SegmentsClose(p); return rc; } /* ** If it is currently unknown whether or not the FTS table has an %_stat ** table (if p->bHasStat==2), attempt to determine this (set p->bHasStat ** to 0 or 1). Return SQLITE_OK if successful, or an SQLite error code ** if an error occurs. */ static int fts3SetHasStat(Fts3Table *p){ int rc = SQLITE_OK; if( p->bHasStat==2 ){ const char *zFmt ="SELECT 1 FROM %Q.sqlite_master WHERE tbl_name='%q_stat'"; char *zSql = sqlite3_mprintf(zFmt, p->zDb, p->zName); if( zSql ){ sqlite3_stmt *pStmt = 0; rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0); if( rc==SQLITE_OK ){ int bHasStat = (sqlite3_step(pStmt)==SQLITE_ROW); rc = sqlite3_finalize(pStmt); if( rc==SQLITE_OK ) p->bHasStat = bHasStat; } sqlite3_free(zSql); }else{ rc = SQLITE_NOMEM; } } return rc; } /* ** Implementation of xBegin() method. */ static int fts3BeginMethod(sqlite3_vtab *pVtab){ Fts3Table *p = (Fts3Table*)pVtab; UNUSED_PARAMETER(pVtab); assert( p->pSegments==0 ); assert( p->nPendingData==0 ); assert( p->inTransaction!=1 ); TESTONLY( p->inTransaction = 1 ); TESTONLY( p->mxSavepoint = -1; ); p->nLeafAdd = 0; return fts3SetHasStat(p); } /* ** Implementation of xCommit() method. This is a no-op. The contents of ** the pending-terms hash-table have already been flushed into the database ** by fts3SyncMethod(). */ static int fts3CommitMethod(sqlite3_vtab *pVtab){ TESTONLY( Fts3Table *p = (Fts3Table*)pVtab ); UNUSED_PARAMETER(pVtab); assert( p->nPendingData==0 ); assert( p->inTransaction!=0 ); assert( p->pSegments==0 ); TESTONLY( p->inTransaction = 0 ); TESTONLY( p->mxSavepoint = -1; ); return SQLITE_OK; } /* ** Implementation of xRollback(). Discard the contents of the pending-terms ** hash-table. Any changes made to the database are reverted by SQLite. */ static int fts3RollbackMethod(sqlite3_vtab *pVtab){ Fts3Table *p = (Fts3Table*)pVtab; sqlite3Fts3PendingTermsClear(p); assert( p->inTransaction!=0 ); TESTONLY( p->inTransaction = 0 ); TESTONLY( p->mxSavepoint = -1; ); return SQLITE_OK; } /* ** When called, *ppPoslist must point to the byte immediately following the ** end of a position-list. i.e. ( (*ppPoslist)[-1]==POS_END ). This function ** moves *ppPoslist so that it instead points to the first byte of the ** same position list. */ static void fts3ReversePoslist(char *pStart, char **ppPoslist){ char *p = &(*ppPoslist)[-2]; char c = 0; /* Skip backwards passed any trailing 0x00 bytes added by NearTrim() */ while( p>pStart && (c=*p--)==0 ); /* Search backwards for a varint with value zero (the end of the previous ** poslist). This is an 0x00 byte preceded by some byte that does not ** have the 0x80 bit set. */ while( p>pStart && (*p & 0x80) | c ){ c = *p--; } assert( p==pStart || c==0 ); /* At this point p points to that preceding byte without the 0x80 bit ** set. So to find the start of the poslist, skip forward 2 bytes then ** over a varint. ** ** Normally. The other case is that p==pStart and the poslist to return ** is the first in the doclist. In this case do not skip forward 2 bytes. ** The second part of the if condition (c==0 && *ppPoslist>&p[2]) ** is required for cases where the first byte of a doclist and the ** doclist is empty. For example, if the first docid is 10, a doclist ** that begins with: ** ** 0x0A 0x00 */ if( p>pStart || (c==0 && *ppPoslist>&p[2]) ){ p = &p[2]; } while( *p++&0x80 ); *ppPoslist = p; } /* ** Helper function used by the implementation of the overloaded snippet(), ** offsets() and optimize() SQL functions. ** ** If the value passed as the third argument is a blob of size ** sizeof(Fts3Cursor*), then the blob contents are copied to the ** output variable *ppCsr and SQLITE_OK is returned. Otherwise, an error ** message is written to context pContext and SQLITE_ERROR returned. The ** string passed via zFunc is used as part of the error message. */ static int fts3FunctionArg( sqlite3_context *pContext, /* SQL function call context */ const char *zFunc, /* Function name */ sqlite3_value *pVal, /* argv[0] passed to function */ Fts3Cursor **ppCsr /* OUT: Store cursor handle here */ ){ Fts3Cursor *pRet; if( sqlite3_value_type(pVal)!=SQLITE_BLOB || sqlite3_value_bytes(pVal)!=sizeof(Fts3Cursor *) ){ char *zErr = sqlite3_mprintf("illegal first argument to %s", zFunc); sqlite3_result_error(pContext, zErr, -1); sqlite3_free(zErr); return SQLITE_ERROR; } memcpy(&pRet, sqlite3_value_blob(pVal), sizeof(Fts3Cursor *)); *ppCsr = pRet; return SQLITE_OK; } /* ** Implementation of the snippet() function for FTS3 */ static void fts3SnippetFunc( sqlite3_context *pContext, /* SQLite function call context */ int nVal, /* Size of apVal[] array */ sqlite3_value **apVal /* Array of arguments */ ){ Fts3Cursor *pCsr; /* Cursor handle passed through apVal[0] */ const char *zStart = ""; const char *zEnd = ""; const char *zEllipsis = "..."; int iCol = -1; int nToken = 15; /* Default number of tokens in snippet */ /* There must be at least one argument passed to this function (otherwise ** the non-overloaded version would have been called instead of this one). */ assert( nVal>=1 ); if( nVal>6 ){ sqlite3_result_error(pContext, "wrong number of arguments to function snippet()", -1); return; } if( fts3FunctionArg(pContext, "snippet", apVal[0], &pCsr) ) return; switch( nVal ){ case 6: nToken = sqlite3_value_int(apVal[5]); case 5: iCol = sqlite3_value_int(apVal[4]); case 4: zEllipsis = (const char*)sqlite3_value_text(apVal[3]); case 3: zEnd = (const char*)sqlite3_value_text(apVal[2]); case 2: zStart = (const char*)sqlite3_value_text(apVal[1]); } if( !zEllipsis || !zEnd || !zStart ){ sqlite3_result_error_nomem(pContext); }else if( nToken==0 ){ sqlite3_result_text(pContext, "", -1, SQLITE_STATIC); }else if( SQLITE_OK==fts3CursorSeek(pContext, pCsr) ){ sqlite3Fts3Snippet(pContext, pCsr, zStart, zEnd, zEllipsis, iCol, nToken); } } /* ** Implementation of the offsets() function for FTS3 */ static void fts3OffsetsFunc( sqlite3_context *pContext, /* SQLite function call context */ int nVal, /* Size of argument array */ sqlite3_value **apVal /* Array of arguments */ ){ Fts3Cursor *pCsr; /* Cursor handle passed through apVal[0] */ UNUSED_PARAMETER(nVal); assert( nVal==1 ); if( fts3FunctionArg(pContext, "offsets", apVal[0], &pCsr) ) return; assert( pCsr ); if( SQLITE_OK==fts3CursorSeek(pContext, pCsr) ){ sqlite3Fts3Offsets(pContext, pCsr); } } /* ** Implementation of the special optimize() function for FTS3. This ** function merges all segments in the database to a single segment. ** Example usage is: ** ** SELECT optimize(t) FROM t LIMIT 1; ** ** where 't' is the name of an FTS3 table. */ static void fts3OptimizeFunc( sqlite3_context *pContext, /* SQLite function call context */ int nVal, /* Size of argument array */ sqlite3_value **apVal /* Array of arguments */ ){ int rc; /* Return code */ Fts3Table *p; /* Virtual table handle */ Fts3Cursor *pCursor; /* Cursor handle passed through apVal[0] */ UNUSED_PARAMETER(nVal); assert( nVal==1 ); if( fts3FunctionArg(pContext, "optimize", apVal[0], &pCursor) ) return; p = (Fts3Table *)pCursor->base.pVtab; assert( p ); rc = sqlite3Fts3Optimize(p); switch( rc ){ case SQLITE_OK: sqlite3_result_text(pContext, "Index optimized", -1, SQLITE_STATIC); break; case SQLITE_DONE: sqlite3_result_text(pContext, "Index already optimal", -1, SQLITE_STATIC); break; default: sqlite3_result_error_code(pContext, rc); break; } } /* ** Implementation of the matchinfo() function for FTS3 */ static void fts3MatchinfoFunc( sqlite3_context *pContext, /* SQLite function call context */ int nVal, /* Size of argument array */ sqlite3_value **apVal /* Array of arguments */ ){ Fts3Cursor *pCsr; /* Cursor handle passed through apVal[0] */ assert( nVal==1 || nVal==2 ); if( SQLITE_OK==fts3FunctionArg(pContext, "matchinfo", apVal[0], &pCsr) ){ const char *zArg = 0; if( nVal>1 ){ zArg = (const char *)sqlite3_value_text(apVal[1]); } sqlite3Fts3Matchinfo(pContext, pCsr, zArg); } } /* ** This routine implements the xFindFunction method for the FTS3 ** virtual table. */ static int fts3FindFunctionMethod( sqlite3_vtab *pVtab, /* Virtual table handle */ int nArg, /* Number of SQL function arguments */ const char *zName, /* Name of SQL function */ void (**pxFunc)(sqlite3_context*,int,sqlite3_value**), /* OUT: Result */ void **ppArg /* Unused */ ){ struct Overloaded { const char *zName; void (*xFunc)(sqlite3_context*,int,sqlite3_value**); } aOverload[] = { { "snippet", fts3SnippetFunc }, { "offsets", fts3OffsetsFunc }, { "optimize", fts3OptimizeFunc }, { "matchinfo", fts3MatchinfoFunc }, }; int i; /* Iterator variable */ UNUSED_PARAMETER(pVtab); UNUSED_PARAMETER(nArg); UNUSED_PARAMETER(ppArg); for(i=0; idb; /* Database connection */ int rc; /* Return Code */ /* At this point it must be known if the %_stat table exists or not. ** So bHasStat may not be 2. */ rc = fts3SetHasStat(p); /* As it happens, the pending terms table is always empty here. This is ** because an "ALTER TABLE RENAME TABLE" statement inside a transaction ** always opens a savepoint transaction. And the xSavepoint() method ** flushes the pending terms table. But leave the (no-op) call to ** PendingTermsFlush() in in case that changes. */ assert( p->nPendingData==0 ); if( rc==SQLITE_OK ){ rc = sqlite3Fts3PendingTermsFlush(p); } if( p->zContentTbl==0 ){ fts3DbExec(&rc, db, "ALTER TABLE %Q.'%q_content' RENAME TO '%q_content';", p->zDb, p->zName, zName ); } if( p->bHasDocsize ){ fts3DbExec(&rc, db, "ALTER TABLE %Q.'%q_docsize' RENAME TO '%q_docsize';", p->zDb, p->zName, zName ); } if( p->bHasStat ){ fts3DbExec(&rc, db, "ALTER TABLE %Q.'%q_stat' RENAME TO '%q_stat';", p->zDb, p->zName, zName ); } fts3DbExec(&rc, db, "ALTER TABLE %Q.'%q_segments' RENAME TO '%q_segments';", p->zDb, p->zName, zName ); fts3DbExec(&rc, db, "ALTER TABLE %Q.'%q_segdir' RENAME TO '%q_segdir';", p->zDb, p->zName, zName ); return rc; } /* ** The xSavepoint() method. ** ** Flush the contents of the pending-terms table to disk. */ static int fts3SavepointMethod(sqlite3_vtab *pVtab, int iSavepoint){ int rc = SQLITE_OK; UNUSED_PARAMETER(iSavepoint); assert( ((Fts3Table *)pVtab)->inTransaction ); assert( ((Fts3Table *)pVtab)->mxSavepoint < iSavepoint ); TESTONLY( ((Fts3Table *)pVtab)->mxSavepoint = iSavepoint ); if( ((Fts3Table *)pVtab)->bIgnoreSavepoint==0 ){ rc = fts3SyncMethod(pVtab); } return rc; } /* ** The xRelease() method. ** ** This is a no-op. */ static int fts3ReleaseMethod(sqlite3_vtab *pVtab, int iSavepoint){ TESTONLY( Fts3Table *p = (Fts3Table*)pVtab ); UNUSED_PARAMETER(iSavepoint); UNUSED_PARAMETER(pVtab); assert( p->inTransaction ); assert( p->mxSavepoint >= iSavepoint ); TESTONLY( p->mxSavepoint = iSavepoint-1 ); return SQLITE_OK; } /* ** The xRollbackTo() method. ** ** Discard the contents of the pending terms table. */ static int fts3RollbackToMethod(sqlite3_vtab *pVtab, int iSavepoint){ Fts3Table *p = (Fts3Table*)pVtab; UNUSED_PARAMETER(iSavepoint); assert( p->inTransaction ); assert( p->mxSavepoint >= iSavepoint ); TESTONLY( p->mxSavepoint = iSavepoint ); sqlite3Fts3PendingTermsClear(p); return SQLITE_OK; } static const sqlite3_module fts3Module = { /* iVersion */ 2, /* xCreate */ fts3CreateMethod, /* xConnect */ fts3ConnectMethod, /* xBestIndex */ fts3BestIndexMethod, /* xDisconnect */ fts3DisconnectMethod, /* xDestroy */ fts3DestroyMethod, /* xOpen */ fts3OpenMethod, /* xClose */ fts3CloseMethod, /* xFilter */ fts3FilterMethod, /* xNext */ fts3NextMethod, /* xEof */ fts3EofMethod, /* xColumn */ fts3ColumnMethod, /* xRowid */ fts3RowidMethod, /* xUpdate */ fts3UpdateMethod, /* xBegin */ fts3BeginMethod, /* xSync */ fts3SyncMethod, /* xCommit */ fts3CommitMethod, /* xRollback */ fts3RollbackMethod, /* xFindFunction */ fts3FindFunctionMethod, /* xRename */ fts3RenameMethod, /* xSavepoint */ fts3SavepointMethod, /* xRelease */ fts3ReleaseMethod, /* xRollbackTo */ fts3RollbackToMethod, }; /* ** This function is registered as the module destructor (called when an ** FTS3 enabled database connection is closed). It frees the memory ** allocated for the tokenizer hash table. */ static void hashDestroy(void *p){ Fts3Hash *pHash = (Fts3Hash *)p; sqlite3Fts3HashClear(pHash); sqlite3_free(pHash); } /* ** The fts3 built-in tokenizers - "simple", "porter" and "icu"- are ** implemented in files fts3_tokenizer1.c, fts3_porter.c and fts3_icu.c ** respectively. The following three forward declarations are for functions ** declared in these files used to retrieve the respective implementations. ** ** Calling sqlite3Fts3SimpleTokenizerModule() sets the value pointed ** to by the argument to point to the "simple" tokenizer implementation. ** And so on. */ SQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule(sqlite3_tokenizer_module const**ppModule); SQLITE_PRIVATE void sqlite3Fts3PorterTokenizerModule(sqlite3_tokenizer_module const**ppModule); #ifndef SQLITE_DISABLE_FTS3_UNICODE SQLITE_PRIVATE void sqlite3Fts3UnicodeTokenizer(sqlite3_tokenizer_module const**ppModule); #endif #ifdef SQLITE_ENABLE_ICU SQLITE_PRIVATE void sqlite3Fts3IcuTokenizerModule(sqlite3_tokenizer_module const**ppModule); #endif /* ** Initialize the fts3 extension. If this extension is built as part ** of the sqlite library, then this function is called directly by ** SQLite. If fts3 is built as a dynamically loadable extension, this ** function is called by the sqlite3_extension_init() entry point. */ SQLITE_PRIVATE int sqlite3Fts3Init(sqlite3 *db){ int rc = SQLITE_OK; Fts3Hash *pHash = 0; const sqlite3_tokenizer_module *pSimple = 0; const sqlite3_tokenizer_module *pPorter = 0; #ifndef SQLITE_DISABLE_FTS3_UNICODE const sqlite3_tokenizer_module *pUnicode = 0; #endif #ifdef SQLITE_ENABLE_ICU const sqlite3_tokenizer_module *pIcu = 0; sqlite3Fts3IcuTokenizerModule(&pIcu); #endif #ifndef SQLITE_DISABLE_FTS3_UNICODE sqlite3Fts3UnicodeTokenizer(&pUnicode); #endif #ifdef SQLITE_TEST rc = sqlite3Fts3InitTerm(db); if( rc!=SQLITE_OK ) return rc; #endif rc = sqlite3Fts3InitAux(db); if( rc!=SQLITE_OK ) return rc; sqlite3Fts3SimpleTokenizerModule(&pSimple); sqlite3Fts3PorterTokenizerModule(&pPorter); /* Allocate and initialize the hash-table used to store tokenizers. */ pHash = sqlite3_malloc(sizeof(Fts3Hash)); if( !pHash ){ rc = SQLITE_NOMEM; }else{ sqlite3Fts3HashInit(pHash, FTS3_HASH_STRING, 1); } /* Load the built-in tokenizers into the hash table */ if( rc==SQLITE_OK ){ if( sqlite3Fts3HashInsert(pHash, "simple", 7, (void *)pSimple) || sqlite3Fts3HashInsert(pHash, "porter", 7, (void *)pPorter) #ifndef SQLITE_DISABLE_FTS3_UNICODE || sqlite3Fts3HashInsert(pHash, "unicode61", 10, (void *)pUnicode) #endif #ifdef SQLITE_ENABLE_ICU || (pIcu && sqlite3Fts3HashInsert(pHash, "icu", 4, (void *)pIcu)) #endif ){ rc = SQLITE_NOMEM; } } #ifdef SQLITE_TEST if( rc==SQLITE_OK ){ rc = sqlite3Fts3ExprInitTestInterface(db); } #endif /* Create the virtual table wrapper around the hash-table and overload ** the two scalar functions. If this is successful, register the ** module with sqlite. */ if( SQLITE_OK==rc && SQLITE_OK==(rc = sqlite3Fts3InitHashTable(db, pHash, "fts3_tokenizer")) && SQLITE_OK==(rc = sqlite3_overload_function(db, "snippet", -1)) && SQLITE_OK==(rc = sqlite3_overload_function(db, "offsets", 1)) && SQLITE_OK==(rc = sqlite3_overload_function(db, "matchinfo", 1)) && SQLITE_OK==(rc = sqlite3_overload_function(db, "matchinfo", 2)) && SQLITE_OK==(rc = sqlite3_overload_function(db, "optimize", 1)) ){ rc = sqlite3_create_module_v2( db, "fts3", &fts3Module, (void *)pHash, hashDestroy ); if( rc==SQLITE_OK ){ rc = sqlite3_create_module_v2( db, "fts4", &fts3Module, (void *)pHash, 0 ); } if( rc==SQLITE_OK ){ rc = sqlite3Fts3InitTok(db, (void *)pHash); } return rc; } /* An error has occurred. Delete the hash table and return the error code. */ assert( rc!=SQLITE_OK ); if( pHash ){ sqlite3Fts3HashClear(pHash); sqlite3_free(pHash); } return rc; } /* ** Allocate an Fts3MultiSegReader for each token in the expression headed ** by pExpr. ** ** An Fts3SegReader object is a cursor that can seek or scan a range of ** entries within a single segment b-tree. An Fts3MultiSegReader uses multiple ** Fts3SegReader objects internally to provide an interface to seek or scan ** within the union of all segments of a b-tree. Hence the name. ** ** If the allocated Fts3MultiSegReader just seeks to a single entry in a ** segment b-tree (if the term is not a prefix or it is a prefix for which ** there exists prefix b-tree of the right length) then it may be traversed ** and merged incrementally. Otherwise, it has to be merged into an in-memory ** doclist and then traversed. */ static void fts3EvalAllocateReaders( Fts3Cursor *pCsr, /* FTS cursor handle */ Fts3Expr *pExpr, /* Allocate readers for this expression */ int *pnToken, /* OUT: Total number of tokens in phrase. */ int *pnOr, /* OUT: Total number of OR nodes in expr. */ int *pRc /* IN/OUT: Error code */ ){ if( pExpr && SQLITE_OK==*pRc ){ if( pExpr->eType==FTSQUERY_PHRASE ){ int i; int nToken = pExpr->pPhrase->nToken; *pnToken += nToken; for(i=0; ipPhrase->aToken[i]; int rc = fts3TermSegReaderCursor(pCsr, pToken->z, pToken->n, pToken->isPrefix, &pToken->pSegcsr ); if( rc!=SQLITE_OK ){ *pRc = rc; return; } } assert( pExpr->pPhrase->iDoclistToken==0 ); pExpr->pPhrase->iDoclistToken = -1; }else{ *pnOr += (pExpr->eType==FTSQUERY_OR); fts3EvalAllocateReaders(pCsr, pExpr->pLeft, pnToken, pnOr, pRc); fts3EvalAllocateReaders(pCsr, pExpr->pRight, pnToken, pnOr, pRc); } } } /* ** Arguments pList/nList contain the doclist for token iToken of phrase p. ** It is merged into the main doclist stored in p->doclist.aAll/nAll. ** ** This function assumes that pList points to a buffer allocated using ** sqlite3_malloc(). This function takes responsibility for eventually ** freeing the buffer. ** ** SQLITE_OK is returned if successful, or SQLITE_NOMEM if an error occurs. */ static int fts3EvalPhraseMergeToken( Fts3Table *pTab, /* FTS Table pointer */ Fts3Phrase *p, /* Phrase to merge pList/nList into */ int iToken, /* Token pList/nList corresponds to */ char *pList, /* Pointer to doclist */ int nList /* Number of bytes in pList */ ){ int rc = SQLITE_OK; assert( iToken!=p->iDoclistToken ); if( pList==0 ){ sqlite3_free(p->doclist.aAll); p->doclist.aAll = 0; p->doclist.nAll = 0; } else if( p->iDoclistToken<0 ){ p->doclist.aAll = pList; p->doclist.nAll = nList; } else if( p->doclist.aAll==0 ){ sqlite3_free(pList); } else { char *pLeft; char *pRight; int nLeft; int nRight; int nDiff; if( p->iDoclistTokendoclist.aAll; nLeft = p->doclist.nAll; pRight = pList; nRight = nList; nDiff = iToken - p->iDoclistToken; }else{ pRight = p->doclist.aAll; nRight = p->doclist.nAll; pLeft = pList; nLeft = nList; nDiff = p->iDoclistToken - iToken; } rc = fts3DoclistPhraseMerge( pTab->bDescIdx, nDiff, pLeft, nLeft, &pRight, &nRight ); sqlite3_free(pLeft); p->doclist.aAll = pRight; p->doclist.nAll = nRight; } if( iToken>p->iDoclistToken ) p->iDoclistToken = iToken; return rc; } /* ** Load the doclist for phrase p into p->doclist.aAll/nAll. The loaded doclist ** does not take deferred tokens into account. ** ** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code. */ static int fts3EvalPhraseLoad( Fts3Cursor *pCsr, /* FTS Cursor handle */ Fts3Phrase *p /* Phrase object */ ){ Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab; int iToken; int rc = SQLITE_OK; for(iToken=0; rc==SQLITE_OK && iTokennToken; iToken++){ Fts3PhraseToken *pToken = &p->aToken[iToken]; assert( pToken->pDeferred==0 || pToken->pSegcsr==0 ); if( pToken->pSegcsr ){ int nThis = 0; char *pThis = 0; rc = fts3TermSelect(pTab, pToken, p->iColumn, &nThis, &pThis); if( rc==SQLITE_OK ){ rc = fts3EvalPhraseMergeToken(pTab, p, iToken, pThis, nThis); } } assert( pToken->pSegcsr==0 ); } return rc; } /* ** This function is called on each phrase after the position lists for ** any deferred tokens have been loaded into memory. It updates the phrases ** current position list to include only those positions that are really ** instances of the phrase (after considering deferred tokens). If this ** means that the phrase does not appear in the current row, doclist.pList ** and doclist.nList are both zeroed. ** ** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code. */ static int fts3EvalDeferredPhrase(Fts3Cursor *pCsr, Fts3Phrase *pPhrase){ int iToken; /* Used to iterate through phrase tokens */ char *aPoslist = 0; /* Position list for deferred tokens */ int nPoslist = 0; /* Number of bytes in aPoslist */ int iPrev = -1; /* Token number of previous deferred token */ assert( pPhrase->doclist.bFreeList==0 ); for(iToken=0; iTokennToken; iToken++){ Fts3PhraseToken *pToken = &pPhrase->aToken[iToken]; Fts3DeferredToken *pDeferred = pToken->pDeferred; if( pDeferred ){ char *pList; int nList; int rc = sqlite3Fts3DeferredTokenList(pDeferred, &pList, &nList); if( rc!=SQLITE_OK ) return rc; if( pList==0 ){ sqlite3_free(aPoslist); pPhrase->doclist.pList = 0; pPhrase->doclist.nList = 0; return SQLITE_OK; }else if( aPoslist==0 ){ aPoslist = pList; nPoslist = nList; }else{ char *aOut = pList; char *p1 = aPoslist; char *p2 = aOut; assert( iPrev>=0 ); fts3PoslistPhraseMerge(&aOut, iToken-iPrev, 0, 1, &p1, &p2); sqlite3_free(aPoslist); aPoslist = pList; nPoslist = (int)(aOut - aPoslist); if( nPoslist==0 ){ sqlite3_free(aPoslist); pPhrase->doclist.pList = 0; pPhrase->doclist.nList = 0; return SQLITE_OK; } } iPrev = iToken; } } if( iPrev>=0 ){ int nMaxUndeferred = pPhrase->iDoclistToken; if( nMaxUndeferred<0 ){ pPhrase->doclist.pList = aPoslist; pPhrase->doclist.nList = nPoslist; pPhrase->doclist.iDocid = pCsr->iPrevId; pPhrase->doclist.bFreeList = 1; }else{ int nDistance; char *p1; char *p2; char *aOut; if( nMaxUndeferred>iPrev ){ p1 = aPoslist; p2 = pPhrase->doclist.pList; nDistance = nMaxUndeferred - iPrev; }else{ p1 = pPhrase->doclist.pList; p2 = aPoslist; nDistance = iPrev - nMaxUndeferred; } aOut = (char *)sqlite3_malloc(nPoslist+8); if( !aOut ){ sqlite3_free(aPoslist); return SQLITE_NOMEM; } pPhrase->doclist.pList = aOut; if( fts3PoslistPhraseMerge(&aOut, nDistance, 0, 1, &p1, &p2) ){ pPhrase->doclist.bFreeList = 1; pPhrase->doclist.nList = (int)(aOut - pPhrase->doclist.pList); }else{ sqlite3_free(aOut); pPhrase->doclist.pList = 0; pPhrase->doclist.nList = 0; } sqlite3_free(aPoslist); } } return SQLITE_OK; } /* ** Maximum number of tokens a phrase may have to be considered for the ** incremental doclists strategy. */ #define MAX_INCR_PHRASE_TOKENS 4 /* ** This function is called for each Fts3Phrase in a full-text query ** expression to initialize the mechanism for returning rows. Once this ** function has been called successfully on an Fts3Phrase, it may be ** used with fts3EvalPhraseNext() to iterate through the matching docids. ** ** If parameter bOptOk is true, then the phrase may (or may not) use the ** incremental loading strategy. Otherwise, the entire doclist is loaded into ** memory within this call. ** ** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code. */ static int fts3EvalPhraseStart(Fts3Cursor *pCsr, int bOptOk, Fts3Phrase *p){ Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab; int rc = SQLITE_OK; /* Error code */ int i; /* Determine if doclists may be loaded from disk incrementally. This is ** possible if the bOptOk argument is true, the FTS doclists will be ** scanned in forward order, and the phrase consists of ** MAX_INCR_PHRASE_TOKENS or fewer tokens, none of which are are "^first" ** tokens or prefix tokens that cannot use a prefix-index. */ int bHaveIncr = 0; int bIncrOk = (bOptOk && pCsr->bDesc==pTab->bDescIdx && p->nToken<=MAX_INCR_PHRASE_TOKENS && p->nToken>0 #ifdef SQLITE_TEST && pTab->bNoIncrDoclist==0 #endif ); for(i=0; bIncrOk==1 && inToken; i++){ Fts3PhraseToken *pToken = &p->aToken[i]; if( pToken->bFirst || (pToken->pSegcsr!=0 && !pToken->pSegcsr->bLookup) ){ bIncrOk = 0; } if( pToken->pSegcsr ) bHaveIncr = 1; } if( bIncrOk && bHaveIncr ){ /* Use the incremental approach. */ int iCol = (p->iColumn >= pTab->nColumn ? -1 : p->iColumn); for(i=0; rc==SQLITE_OK && inToken; i++){ Fts3PhraseToken *pToken = &p->aToken[i]; Fts3MultiSegReader *pSegcsr = pToken->pSegcsr; if( pSegcsr ){ rc = sqlite3Fts3MsrIncrStart(pTab, pSegcsr, iCol, pToken->z, pToken->n); } } p->bIncr = 1; }else{ /* Load the full doclist for the phrase into memory. */ rc = fts3EvalPhraseLoad(pCsr, p); p->bIncr = 0; } assert( rc!=SQLITE_OK || p->nToken<1 || p->aToken[0].pSegcsr==0 || p->bIncr ); return rc; } /* ** This function is used to iterate backwards (from the end to start) ** through doclists. It is used by this module to iterate through phrase ** doclists in reverse and by the fts3_write.c module to iterate through ** pending-terms lists when writing to databases with "order=desc". ** ** The doclist may be sorted in ascending (parameter bDescIdx==0) or ** descending (parameter bDescIdx==1) order of docid. Regardless, this ** function iterates from the end of the doclist to the beginning. */ SQLITE_PRIVATE void sqlite3Fts3DoclistPrev( int bDescIdx, /* True if the doclist is desc */ char *aDoclist, /* Pointer to entire doclist */ int nDoclist, /* Length of aDoclist in bytes */ char **ppIter, /* IN/OUT: Iterator pointer */ sqlite3_int64 *piDocid, /* IN/OUT: Docid pointer */ int *pnList, /* OUT: List length pointer */ u8 *pbEof /* OUT: End-of-file flag */ ){ char *p = *ppIter; assert( nDoclist>0 ); assert( *pbEof==0 ); assert( p || *piDocid==0 ); assert( !p || (p>aDoclist && p<&aDoclist[nDoclist]) ); if( p==0 ){ sqlite3_int64 iDocid = 0; char *pNext = 0; char *pDocid = aDoclist; char *pEnd = &aDoclist[nDoclist]; int iMul = 1; while( pDocid0 ); assert( *pbEof==0 ); assert( p || *piDocid==0 ); assert( !p || (p>=aDoclist && p<=&aDoclist[nDoclist]) ); if( p==0 ){ p = aDoclist; p += sqlite3Fts3GetVarint(p, piDocid); }else{ fts3PoslistCopy(0, &p); while( p<&aDoclist[nDoclist] && *p==0 ) p++; if( p>=&aDoclist[nDoclist] ){ *pbEof = 1; }else{ sqlite3_int64 iVar; p += sqlite3Fts3GetVarint(p, &iVar); *piDocid += ((bDescIdx ? -1 : 1) * iVar); } } *ppIter = p; } /* ** Advance the iterator pDL to the next entry in pDL->aAll/nAll. Set *pbEof ** to true if EOF is reached. */ static void fts3EvalDlPhraseNext( Fts3Table *pTab, Fts3Doclist *pDL, u8 *pbEof ){ char *pIter; /* Used to iterate through aAll */ char *pEnd = &pDL->aAll[pDL->nAll]; /* 1 byte past end of aAll */ if( pDL->pNextDocid ){ pIter = pDL->pNextDocid; }else{ pIter = pDL->aAll; } if( pIter>=pEnd ){ /* We have already reached the end of this doclist. EOF. */ *pbEof = 1; }else{ sqlite3_int64 iDelta; pIter += sqlite3Fts3GetVarint(pIter, &iDelta); if( pTab->bDescIdx==0 || pDL->pNextDocid==0 ){ pDL->iDocid += iDelta; }else{ pDL->iDocid -= iDelta; } pDL->pList = pIter; fts3PoslistCopy(0, &pIter); pDL->nList = (int)(pIter - pDL->pList); /* pIter now points just past the 0x00 that terminates the position- ** list for document pDL->iDocid. However, if this position-list was ** edited in place by fts3EvalNearTrim(), then pIter may not actually ** point to the start of the next docid value. The following line deals ** with this case by advancing pIter past the zero-padding added by ** fts3EvalNearTrim(). */ while( pIterpNextDocid = pIter; assert( pIter>=&pDL->aAll[pDL->nAll] || *pIter ); *pbEof = 0; } } /* ** Helper type used by fts3EvalIncrPhraseNext() and incrPhraseTokenNext(). */ typedef struct TokenDoclist TokenDoclist; struct TokenDoclist { int bIgnore; sqlite3_int64 iDocid; char *pList; int nList; }; /* ** Token pToken is an incrementally loaded token that is part of a ** multi-token phrase. Advance it to the next matching document in the ** database and populate output variable *p with the details of the new ** entry. Or, if the iterator has reached EOF, set *pbEof to true. ** ** If an error occurs, return an SQLite error code. Otherwise, return ** SQLITE_OK. */ static int incrPhraseTokenNext( Fts3Table *pTab, /* Virtual table handle */ Fts3Phrase *pPhrase, /* Phrase to advance token of */ int iToken, /* Specific token to advance */ TokenDoclist *p, /* OUT: Docid and doclist for new entry */ u8 *pbEof /* OUT: True if iterator is at EOF */ ){ int rc = SQLITE_OK; if( pPhrase->iDoclistToken==iToken ){ assert( p->bIgnore==0 ); assert( pPhrase->aToken[iToken].pSegcsr==0 ); fts3EvalDlPhraseNext(pTab, &pPhrase->doclist, pbEof); p->pList = pPhrase->doclist.pList; p->nList = pPhrase->doclist.nList; p->iDocid = pPhrase->doclist.iDocid; }else{ Fts3PhraseToken *pToken = &pPhrase->aToken[iToken]; assert( pToken->pDeferred==0 ); assert( pToken->pSegcsr || pPhrase->iDoclistToken>=0 ); if( pToken->pSegcsr ){ assert( p->bIgnore==0 ); rc = sqlite3Fts3MsrIncrNext( pTab, pToken->pSegcsr, &p->iDocid, &p->pList, &p->nList ); if( p->pList==0 ) *pbEof = 1; }else{ p->bIgnore = 1; } } return rc; } /* ** The phrase iterator passed as the second argument: ** ** * features at least one token that uses an incremental doclist, and ** ** * does not contain any deferred tokens. ** ** Advance it to the next matching documnent in the database and populate ** the Fts3Doclist.pList and nList fields. ** ** If there is no "next" entry and no error occurs, then *pbEof is set to ** 1 before returning. Otherwise, if no error occurs and the iterator is ** successfully advanced, *pbEof is set to 0. ** ** If an error occurs, return an SQLite error code. Otherwise, return ** SQLITE_OK. */ static int fts3EvalIncrPhraseNext( Fts3Cursor *pCsr, /* FTS Cursor handle */ Fts3Phrase *p, /* Phrase object to advance to next docid */ u8 *pbEof /* OUT: Set to 1 if EOF */ ){ int rc = SQLITE_OK; Fts3Doclist *pDL = &p->doclist; Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab; u8 bEof = 0; /* This is only called if it is guaranteed that the phrase has at least ** one incremental token. In which case the bIncr flag is set. */ assert( p->bIncr==1 ); if( p->nToken==1 && p->bIncr ){ rc = sqlite3Fts3MsrIncrNext(pTab, p->aToken[0].pSegcsr, &pDL->iDocid, &pDL->pList, &pDL->nList ); if( pDL->pList==0 ) bEof = 1; }else{ int bDescDoclist = pCsr->bDesc; struct TokenDoclist a[MAX_INCR_PHRASE_TOKENS]; memset(a, 0, sizeof(a)); assert( p->nToken<=MAX_INCR_PHRASE_TOKENS ); assert( p->iDoclistTokennToken && bEof==0; i++){ rc = incrPhraseTokenNext(pTab, p, i, &a[i], &bEof); if( a[i].bIgnore==0 && (bMaxSet==0 || DOCID_CMP(iMax, a[i].iDocid)<0) ){ iMax = a[i].iDocid; bMaxSet = 1; } } assert( rc!=SQLITE_OK || (p->nToken>=1 && a[p->nToken-1].bIgnore==0) ); assert( rc!=SQLITE_OK || bMaxSet ); /* Keep advancing iterators until they all point to the same document */ for(i=0; inToken; i++){ while( rc==SQLITE_OK && bEof==0 && a[i].bIgnore==0 && DOCID_CMP(a[i].iDocid, iMax)<0 ){ rc = incrPhraseTokenNext(pTab, p, i, &a[i], &bEof); if( DOCID_CMP(a[i].iDocid, iMax)>0 ){ iMax = a[i].iDocid; i = 0; } } } /* Check if the current entries really are a phrase match */ if( bEof==0 ){ int nList = 0; int nByte = a[p->nToken-1].nList; char *aDoclist = sqlite3_malloc(nByte+1); if( !aDoclist ) return SQLITE_NOMEM; memcpy(aDoclist, a[p->nToken-1].pList, nByte+1); for(i=0; i<(p->nToken-1); i++){ if( a[i].bIgnore==0 ){ char *pL = a[i].pList; char *pR = aDoclist; char *pOut = aDoclist; int nDist = p->nToken-1-i; int res = fts3PoslistPhraseMerge(&pOut, nDist, 0, 1, &pL, &pR); if( res==0 ) break; nList = (int)(pOut - aDoclist); } } if( i==(p->nToken-1) ){ pDL->iDocid = iMax; pDL->pList = aDoclist; pDL->nList = nList; pDL->bFreeList = 1; break; } sqlite3_free(aDoclist); } } } *pbEof = bEof; return rc; } /* ** Attempt to move the phrase iterator to point to the next matching docid. ** If an error occurs, return an SQLite error code. Otherwise, return ** SQLITE_OK. ** ** If there is no "next" entry and no error occurs, then *pbEof is set to ** 1 before returning. Otherwise, if no error occurs and the iterator is ** successfully advanced, *pbEof is set to 0. */ static int fts3EvalPhraseNext( Fts3Cursor *pCsr, /* FTS Cursor handle */ Fts3Phrase *p, /* Phrase object to advance to next docid */ u8 *pbEof /* OUT: Set to 1 if EOF */ ){ int rc = SQLITE_OK; Fts3Doclist *pDL = &p->doclist; Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab; if( p->bIncr ){ rc = fts3EvalIncrPhraseNext(pCsr, p, pbEof); }else if( pCsr->bDesc!=pTab->bDescIdx && pDL->nAll ){ sqlite3Fts3DoclistPrev(pTab->bDescIdx, pDL->aAll, pDL->nAll, &pDL->pNextDocid, &pDL->iDocid, &pDL->nList, pbEof ); pDL->pList = pDL->pNextDocid; }else{ fts3EvalDlPhraseNext(pTab, pDL, pbEof); } return rc; } /* ** ** If *pRc is not SQLITE_OK when this function is called, it is a no-op. ** Otherwise, fts3EvalPhraseStart() is called on all phrases within the ** expression. Also the Fts3Expr.bDeferred variable is set to true for any ** expressions for which all descendent tokens are deferred. ** ** If parameter bOptOk is zero, then it is guaranteed that the ** Fts3Phrase.doclist.aAll/nAll variables contain the entire doclist for ** each phrase in the expression (subject to deferred token processing). ** Or, if bOptOk is non-zero, then one or more tokens within the expression ** may be loaded incrementally, meaning doclist.aAll/nAll is not available. ** ** If an error occurs within this function, *pRc is set to an SQLite error ** code before returning. */ static void fts3EvalStartReaders( Fts3Cursor *pCsr, /* FTS Cursor handle */ Fts3Expr *pExpr, /* Expression to initialize phrases in */ int *pRc /* IN/OUT: Error code */ ){ if( pExpr && SQLITE_OK==*pRc ){ if( pExpr->eType==FTSQUERY_PHRASE ){ int nToken = pExpr->pPhrase->nToken; if( nToken ){ int i; for(i=0; ipPhrase->aToken[i].pDeferred==0 ) break; } pExpr->bDeferred = (i==nToken); } *pRc = fts3EvalPhraseStart(pCsr, 1, pExpr->pPhrase); }else{ fts3EvalStartReaders(pCsr, pExpr->pLeft, pRc); fts3EvalStartReaders(pCsr, pExpr->pRight, pRc); pExpr->bDeferred = (pExpr->pLeft->bDeferred && pExpr->pRight->bDeferred); } } } /* ** An array of the following structures is assembled as part of the process ** of selecting tokens to defer before the query starts executing (as part ** of the xFilter() method). There is one element in the array for each ** token in the FTS expression. ** ** Tokens are divided into AND/NEAR clusters. All tokens in a cluster belong ** to phrases that are connected only by AND and NEAR operators (not OR or ** NOT). When determining tokens to defer, each AND/NEAR cluster is considered ** separately. The root of a tokens AND/NEAR cluster is stored in ** Fts3TokenAndCost.pRoot. */ typedef struct Fts3TokenAndCost Fts3TokenAndCost; struct Fts3TokenAndCost { Fts3Phrase *pPhrase; /* The phrase the token belongs to */ int iToken; /* Position of token in phrase */ Fts3PhraseToken *pToken; /* The token itself */ Fts3Expr *pRoot; /* Root of NEAR/AND cluster */ int nOvfl; /* Number of overflow pages to load doclist */ int iCol; /* The column the token must match */ }; /* ** This function is used to populate an allocated Fts3TokenAndCost array. ** ** If *pRc is not SQLITE_OK when this function is called, it is a no-op. ** Otherwise, if an error occurs during execution, *pRc is set to an ** SQLite error code. */ static void fts3EvalTokenCosts( Fts3Cursor *pCsr, /* FTS Cursor handle */ Fts3Expr *pRoot, /* Root of current AND/NEAR cluster */ Fts3Expr *pExpr, /* Expression to consider */ Fts3TokenAndCost **ppTC, /* Write new entries to *(*ppTC)++ */ Fts3Expr ***ppOr, /* Write new OR root to *(*ppOr)++ */ int *pRc /* IN/OUT: Error code */ ){ if( *pRc==SQLITE_OK ){ if( pExpr->eType==FTSQUERY_PHRASE ){ Fts3Phrase *pPhrase = pExpr->pPhrase; int i; for(i=0; *pRc==SQLITE_OK && inToken; i++){ Fts3TokenAndCost *pTC = (*ppTC)++; pTC->pPhrase = pPhrase; pTC->iToken = i; pTC->pRoot = pRoot; pTC->pToken = &pPhrase->aToken[i]; pTC->iCol = pPhrase->iColumn; *pRc = sqlite3Fts3MsrOvfl(pCsr, pTC->pToken->pSegcsr, &pTC->nOvfl); } }else if( pExpr->eType!=FTSQUERY_NOT ){ assert( pExpr->eType==FTSQUERY_OR || pExpr->eType==FTSQUERY_AND || pExpr->eType==FTSQUERY_NEAR ); assert( pExpr->pLeft && pExpr->pRight ); if( pExpr->eType==FTSQUERY_OR ){ pRoot = pExpr->pLeft; **ppOr = pRoot; (*ppOr)++; } fts3EvalTokenCosts(pCsr, pRoot, pExpr->pLeft, ppTC, ppOr, pRc); if( pExpr->eType==FTSQUERY_OR ){ pRoot = pExpr->pRight; **ppOr = pRoot; (*ppOr)++; } fts3EvalTokenCosts(pCsr, pRoot, pExpr->pRight, ppTC, ppOr, pRc); } } } /* ** Determine the average document (row) size in pages. If successful, ** write this value to *pnPage and return SQLITE_OK. Otherwise, return ** an SQLite error code. ** ** The average document size in pages is calculated by first calculating ** determining the average size in bytes, B. If B is less than the amount ** of data that will fit on a single leaf page of an intkey table in ** this database, then the average docsize is 1. Otherwise, it is 1 plus ** the number of overflow pages consumed by a record B bytes in size. */ static int fts3EvalAverageDocsize(Fts3Cursor *pCsr, int *pnPage){ if( pCsr->nRowAvg==0 ){ /* The average document size, which is required to calculate the cost ** of each doclist, has not yet been determined. Read the required ** data from the %_stat table to calculate it. ** ** Entry 0 of the %_stat table is a blob containing (nCol+1) FTS3 ** varints, where nCol is the number of columns in the FTS3 table. ** The first varint is the number of documents currently stored in ** the table. The following nCol varints contain the total amount of ** data stored in all rows of each column of the table, from left ** to right. */ int rc; Fts3Table *p = (Fts3Table*)pCsr->base.pVtab; sqlite3_stmt *pStmt; sqlite3_int64 nDoc = 0; sqlite3_int64 nByte = 0; const char *pEnd; const char *a; rc = sqlite3Fts3SelectDoctotal(p, &pStmt); if( rc!=SQLITE_OK ) return rc; a = sqlite3_column_blob(pStmt, 0); assert( a ); pEnd = &a[sqlite3_column_bytes(pStmt, 0)]; a += sqlite3Fts3GetVarint(a, &nDoc); while( anDoc = nDoc; pCsr->nRowAvg = (int)(((nByte / nDoc) + p->nPgsz) / p->nPgsz); assert( pCsr->nRowAvg>0 ); rc = sqlite3_reset(pStmt); if( rc!=SQLITE_OK ) return rc; } *pnPage = pCsr->nRowAvg; return SQLITE_OK; } /* ** This function is called to select the tokens (if any) that will be ** deferred. The array aTC[] has already been populated when this is ** called. ** ** This function is called once for each AND/NEAR cluster in the ** expression. Each invocation determines which tokens to defer within ** the cluster with root node pRoot. See comments above the definition ** of struct Fts3TokenAndCost for more details. ** ** If no error occurs, SQLITE_OK is returned and sqlite3Fts3DeferToken() ** called on each token to defer. Otherwise, an SQLite error code is ** returned. */ static int fts3EvalSelectDeferred( Fts3Cursor *pCsr, /* FTS Cursor handle */ Fts3Expr *pRoot, /* Consider tokens with this root node */ Fts3TokenAndCost *aTC, /* Array of expression tokens and costs */ int nTC /* Number of entries in aTC[] */ ){ Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab; int nDocSize = 0; /* Number of pages per doc loaded */ int rc = SQLITE_OK; /* Return code */ int ii; /* Iterator variable for various purposes */ int nOvfl = 0; /* Total overflow pages used by doclists */ int nToken = 0; /* Total number of tokens in cluster */ int nMinEst = 0; /* The minimum count for any phrase so far. */ int nLoad4 = 1; /* (Phrases that will be loaded)^4. */ /* Tokens are never deferred for FTS tables created using the content=xxx ** option. The reason being that it is not guaranteed that the content ** table actually contains the same data as the index. To prevent this from ** causing any problems, the deferred token optimization is completely ** disabled for content=xxx tables. */ if( pTab->zContentTbl ){ return SQLITE_OK; } /* Count the tokens in this AND/NEAR cluster. If none of the doclists ** associated with the tokens spill onto overflow pages, or if there is ** only 1 token, exit early. No tokens to defer in this case. */ for(ii=0; ii0 ); /* Iterate through all tokens in this AND/NEAR cluster, in ascending order ** of the number of overflow pages that will be loaded by the pager layer ** to retrieve the entire doclist for the token from the full-text index. ** Load the doclists for tokens that are either: ** ** a. The cheapest token in the entire query (i.e. the one visited by the ** first iteration of this loop), or ** ** b. Part of a multi-token phrase. ** ** After each token doclist is loaded, merge it with the others from the ** same phrase and count the number of documents that the merged doclist ** contains. Set variable "nMinEst" to the smallest number of documents in ** any phrase doclist for which 1 or more token doclists have been loaded. ** Let nOther be the number of other phrases for which it is certain that ** one or more tokens will not be deferred. ** ** Then, for each token, defer it if loading the doclist would result in ** loading N or more overflow pages into memory, where N is computed as: ** ** (nMinEst + 4^nOther - 1) / (4^nOther) */ for(ii=0; iinOvfl) ){ pTC = &aTC[iTC]; } } assert( pTC ); if( ii && pTC->nOvfl>=((nMinEst+(nLoad4/4)-1)/(nLoad4/4))*nDocSize ){ /* The number of overflow pages to load for this (and therefore all ** subsequent) tokens is greater than the estimated number of pages ** that will be loaded if all subsequent tokens are deferred. */ Fts3PhraseToken *pToken = pTC->pToken; rc = sqlite3Fts3DeferToken(pCsr, pToken, pTC->iCol); fts3SegReaderCursorFree(pToken->pSegcsr); pToken->pSegcsr = 0; }else{ /* Set nLoad4 to the value of (4^nOther) for the next iteration of the ** for-loop. Except, limit the value to 2^24 to prevent it from ** overflowing the 32-bit integer it is stored in. */ if( ii<12 ) nLoad4 = nLoad4*4; if( ii==0 || (pTC->pPhrase->nToken>1 && ii!=nToken-1) ){ /* Either this is the cheapest token in the entire query, or it is ** part of a multi-token phrase. Either way, the entire doclist will ** (eventually) be loaded into memory. It may as well be now. */ Fts3PhraseToken *pToken = pTC->pToken; int nList = 0; char *pList = 0; rc = fts3TermSelect(pTab, pToken, pTC->iCol, &nList, &pList); assert( rc==SQLITE_OK || pList==0 ); if( rc==SQLITE_OK ){ rc = fts3EvalPhraseMergeToken( pTab, pTC->pPhrase, pTC->iToken,pList,nList ); } if( rc==SQLITE_OK ){ int nCount; nCount = fts3DoclistCountDocids( pTC->pPhrase->doclist.aAll, pTC->pPhrase->doclist.nAll ); if( ii==0 || nCountpToken = 0; } return rc; } /* ** This function is called from within the xFilter method. It initializes ** the full-text query currently stored in pCsr->pExpr. To iterate through ** the results of a query, the caller does: ** ** fts3EvalStart(pCsr); ** while( 1 ){ ** fts3EvalNext(pCsr); ** if( pCsr->bEof ) break; ** ... return row pCsr->iPrevId to the caller ... ** } */ static int fts3EvalStart(Fts3Cursor *pCsr){ Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab; int rc = SQLITE_OK; int nToken = 0; int nOr = 0; /* Allocate a MultiSegReader for each token in the expression. */ fts3EvalAllocateReaders(pCsr, pCsr->pExpr, &nToken, &nOr, &rc); /* Determine which, if any, tokens in the expression should be deferred. */ #ifndef SQLITE_DISABLE_FTS4_DEFERRED if( rc==SQLITE_OK && nToken>1 && pTab->bFts4 ){ Fts3TokenAndCost *aTC; Fts3Expr **apOr; aTC = (Fts3TokenAndCost *)sqlite3_malloc( sizeof(Fts3TokenAndCost) * nToken + sizeof(Fts3Expr *) * nOr * 2 ); apOr = (Fts3Expr **)&aTC[nToken]; if( !aTC ){ rc = SQLITE_NOMEM; }else{ int ii; Fts3TokenAndCost *pTC = aTC; Fts3Expr **ppOr = apOr; fts3EvalTokenCosts(pCsr, 0, pCsr->pExpr, &pTC, &ppOr, &rc); nToken = (int)(pTC-aTC); nOr = (int)(ppOr-apOr); if( rc==SQLITE_OK ){ rc = fts3EvalSelectDeferred(pCsr, 0, aTC, nToken); for(ii=0; rc==SQLITE_OK && iipExpr, &rc); return rc; } /* ** Invalidate the current position list for phrase pPhrase. */ static void fts3EvalInvalidatePoslist(Fts3Phrase *pPhrase){ if( pPhrase->doclist.bFreeList ){ sqlite3_free(pPhrase->doclist.pList); } pPhrase->doclist.pList = 0; pPhrase->doclist.nList = 0; pPhrase->doclist.bFreeList = 0; } /* ** This function is called to edit the position list associated with ** the phrase object passed as the fifth argument according to a NEAR ** condition. For example: ** ** abc NEAR/5 "def ghi" ** ** Parameter nNear is passed the NEAR distance of the expression (5 in ** the example above). When this function is called, *paPoslist points to ** the position list, and *pnToken is the number of phrase tokens in, the ** phrase on the other side of the NEAR operator to pPhrase. For example, ** if pPhrase refers to the "def ghi" phrase, then *paPoslist points to ** the position list associated with phrase "abc". ** ** All positions in the pPhrase position list that are not sufficiently ** close to a position in the *paPoslist position list are removed. If this ** leaves 0 positions, zero is returned. Otherwise, non-zero. ** ** Before returning, *paPoslist is set to point to the position lsit ** associated with pPhrase. And *pnToken is set to the number of tokens in ** pPhrase. */ static int fts3EvalNearTrim( int nNear, /* NEAR distance. As in "NEAR/nNear". */ char *aTmp, /* Temporary space to use */ char **paPoslist, /* IN/OUT: Position list */ int *pnToken, /* IN/OUT: Tokens in phrase of *paPoslist */ Fts3Phrase *pPhrase /* The phrase object to trim the doclist of */ ){ int nParam1 = nNear + pPhrase->nToken; int nParam2 = nNear + *pnToken; int nNew; char *p2; char *pOut; int res; assert( pPhrase->doclist.pList ); p2 = pOut = pPhrase->doclist.pList; res = fts3PoslistNearMerge( &pOut, aTmp, nParam1, nParam2, paPoslist, &p2 ); if( res ){ nNew = (int)(pOut - pPhrase->doclist.pList) - 1; assert( pPhrase->doclist.pList[nNew]=='\0' ); assert( nNew<=pPhrase->doclist.nList && nNew>0 ); memset(&pPhrase->doclist.pList[nNew], 0, pPhrase->doclist.nList - nNew); pPhrase->doclist.nList = nNew; *paPoslist = pPhrase->doclist.pList; *pnToken = pPhrase->nToken; } return res; } /* ** This function is a no-op if *pRc is other than SQLITE_OK when it is called. ** Otherwise, it advances the expression passed as the second argument to ** point to the next matching row in the database. Expressions iterate through ** matching rows in docid order. Ascending order if Fts3Cursor.bDesc is zero, ** or descending if it is non-zero. ** ** If an error occurs, *pRc is set to an SQLite error code. Otherwise, if ** successful, the following variables in pExpr are set: ** ** Fts3Expr.bEof (non-zero if EOF - there is no next row) ** Fts3Expr.iDocid (valid if bEof==0. The docid of the next row) ** ** If the expression is of type FTSQUERY_PHRASE, and the expression is not ** at EOF, then the following variables are populated with the position list ** for the phrase for the visited row: ** ** FTs3Expr.pPhrase->doclist.nList (length of pList in bytes) ** FTs3Expr.pPhrase->doclist.pList (pointer to position list) ** ** It says above that this function advances the expression to the next ** matching row. This is usually true, but there are the following exceptions: ** ** 1. Deferred tokens are not taken into account. If a phrase consists ** entirely of deferred tokens, it is assumed to match every row in ** the db. In this case the position-list is not populated at all. ** ** Or, if a phrase contains one or more deferred tokens and one or ** more non-deferred tokens, then the expression is advanced to the ** next possible match, considering only non-deferred tokens. In other ** words, if the phrase is "A B C", and "B" is deferred, the expression ** is advanced to the next row that contains an instance of "A * C", ** where "*" may match any single token. The position list in this case ** is populated as for "A * C" before returning. ** ** 2. NEAR is treated as AND. If the expression is "x NEAR y", it is ** advanced to point to the next row that matches "x AND y". ** ** See sqlite3Fts3EvalTestDeferred() for details on testing if a row is ** really a match, taking into account deferred tokens and NEAR operators. */ static void fts3EvalNextRow( Fts3Cursor *pCsr, /* FTS Cursor handle */ Fts3Expr *pExpr, /* Expr. to advance to next matching row */ int *pRc /* IN/OUT: Error code */ ){ if( *pRc==SQLITE_OK ){ int bDescDoclist = pCsr->bDesc; /* Used by DOCID_CMP() macro */ assert( pExpr->bEof==0 ); pExpr->bStart = 1; switch( pExpr->eType ){ case FTSQUERY_NEAR: case FTSQUERY_AND: { Fts3Expr *pLeft = pExpr->pLeft; Fts3Expr *pRight = pExpr->pRight; assert( !pLeft->bDeferred || !pRight->bDeferred ); if( pLeft->bDeferred ){ /* LHS is entirely deferred. So we assume it matches every row. ** Advance the RHS iterator to find the next row visited. */ fts3EvalNextRow(pCsr, pRight, pRc); pExpr->iDocid = pRight->iDocid; pExpr->bEof = pRight->bEof; }else if( pRight->bDeferred ){ /* RHS is entirely deferred. So we assume it matches every row. ** Advance the LHS iterator to find the next row visited. */ fts3EvalNextRow(pCsr, pLeft, pRc); pExpr->iDocid = pLeft->iDocid; pExpr->bEof = pLeft->bEof; }else{ /* Neither the RHS or LHS are deferred. */ fts3EvalNextRow(pCsr, pLeft, pRc); fts3EvalNextRow(pCsr, pRight, pRc); while( !pLeft->bEof && !pRight->bEof && *pRc==SQLITE_OK ){ sqlite3_int64 iDiff = DOCID_CMP(pLeft->iDocid, pRight->iDocid); if( iDiff==0 ) break; if( iDiff<0 ){ fts3EvalNextRow(pCsr, pLeft, pRc); }else{ fts3EvalNextRow(pCsr, pRight, pRc); } } pExpr->iDocid = pLeft->iDocid; pExpr->bEof = (pLeft->bEof || pRight->bEof); if( pExpr->eType==FTSQUERY_NEAR && pExpr->bEof ){ if( pRight->pPhrase && pRight->pPhrase->doclist.aAll ){ Fts3Doclist *pDl = &pRight->pPhrase->doclist; while( *pRc==SQLITE_OK && pRight->bEof==0 ){ memset(pDl->pList, 0, pDl->nList); fts3EvalNextRow(pCsr, pRight, pRc); } } if( pLeft->pPhrase && pLeft->pPhrase->doclist.aAll ){ Fts3Doclist *pDl = &pLeft->pPhrase->doclist; while( *pRc==SQLITE_OK && pLeft->bEof==0 ){ memset(pDl->pList, 0, pDl->nList); fts3EvalNextRow(pCsr, pLeft, pRc); } } } } break; } case FTSQUERY_OR: { Fts3Expr *pLeft = pExpr->pLeft; Fts3Expr *pRight = pExpr->pRight; sqlite3_int64 iCmp = DOCID_CMP(pLeft->iDocid, pRight->iDocid); assert( pLeft->bStart || pLeft->iDocid==pRight->iDocid ); assert( pRight->bStart || pLeft->iDocid==pRight->iDocid ); if( pRight->bEof || (pLeft->bEof==0 && iCmp<0) ){ fts3EvalNextRow(pCsr, pLeft, pRc); }else if( pLeft->bEof || (pRight->bEof==0 && iCmp>0) ){ fts3EvalNextRow(pCsr, pRight, pRc); }else{ fts3EvalNextRow(pCsr, pLeft, pRc); fts3EvalNextRow(pCsr, pRight, pRc); } pExpr->bEof = (pLeft->bEof && pRight->bEof); iCmp = DOCID_CMP(pLeft->iDocid, pRight->iDocid); if( pRight->bEof || (pLeft->bEof==0 && iCmp<0) ){ pExpr->iDocid = pLeft->iDocid; }else{ pExpr->iDocid = pRight->iDocid; } break; } case FTSQUERY_NOT: { Fts3Expr *pLeft = pExpr->pLeft; Fts3Expr *pRight = pExpr->pRight; if( pRight->bStart==0 ){ fts3EvalNextRow(pCsr, pRight, pRc); assert( *pRc!=SQLITE_OK || pRight->bStart ); } fts3EvalNextRow(pCsr, pLeft, pRc); if( pLeft->bEof==0 ){ while( !*pRc && !pRight->bEof && DOCID_CMP(pLeft->iDocid, pRight->iDocid)>0 ){ fts3EvalNextRow(pCsr, pRight, pRc); } } pExpr->iDocid = pLeft->iDocid; pExpr->bEof = pLeft->bEof; break; } default: { Fts3Phrase *pPhrase = pExpr->pPhrase; fts3EvalInvalidatePoslist(pPhrase); *pRc = fts3EvalPhraseNext(pCsr, pPhrase, &pExpr->bEof); pExpr->iDocid = pPhrase->doclist.iDocid; break; } } } } /* ** If *pRc is not SQLITE_OK, or if pExpr is not the root node of a NEAR ** cluster, then this function returns 1 immediately. ** ** Otherwise, it checks if the current row really does match the NEAR ** expression, using the data currently stored in the position lists ** (Fts3Expr->pPhrase.doclist.pList/nList) for each phrase in the expression. ** ** If the current row is a match, the position list associated with each ** phrase in the NEAR expression is edited in place to contain only those ** phrase instances sufficiently close to their peers to satisfy all NEAR ** constraints. In this case it returns 1. If the NEAR expression does not ** match the current row, 0 is returned. The position lists may or may not ** be edited if 0 is returned. */ static int fts3EvalNearTest(Fts3Expr *pExpr, int *pRc){ int res = 1; /* The following block runs if pExpr is the root of a NEAR query. ** For example, the query: ** ** "w" NEAR "x" NEAR "y" NEAR "z" ** ** which is represented in tree form as: ** ** | ** +--NEAR--+ <-- root of NEAR query ** | | ** +--NEAR--+ "z" ** | | ** +--NEAR--+ "y" ** | | ** "w" "x" ** ** The right-hand child of a NEAR node is always a phrase. The ** left-hand child may be either a phrase or a NEAR node. There are ** no exceptions to this - it's the way the parser in fts3_expr.c works. */ if( *pRc==SQLITE_OK && pExpr->eType==FTSQUERY_NEAR && pExpr->bEof==0 && (pExpr->pParent==0 || pExpr->pParent->eType!=FTSQUERY_NEAR) ){ Fts3Expr *p; int nTmp = 0; /* Bytes of temp space */ char *aTmp; /* Temp space for PoslistNearMerge() */ /* Allocate temporary working space. */ for(p=pExpr; p->pLeft; p=p->pLeft){ nTmp += p->pRight->pPhrase->doclist.nList; } nTmp += p->pPhrase->doclist.nList; if( nTmp==0 ){ res = 0; }else{ aTmp = sqlite3_malloc(nTmp*2); if( !aTmp ){ *pRc = SQLITE_NOMEM; res = 0; }else{ char *aPoslist = p->pPhrase->doclist.pList; int nToken = p->pPhrase->nToken; for(p=p->pParent;res && p && p->eType==FTSQUERY_NEAR; p=p->pParent){ Fts3Phrase *pPhrase = p->pRight->pPhrase; int nNear = p->nNear; res = fts3EvalNearTrim(nNear, aTmp, &aPoslist, &nToken, pPhrase); } aPoslist = pExpr->pRight->pPhrase->doclist.pList; nToken = pExpr->pRight->pPhrase->nToken; for(p=pExpr->pLeft; p && res; p=p->pLeft){ int nNear; Fts3Phrase *pPhrase; assert( p->pParent && p->pParent->pLeft==p ); nNear = p->pParent->nNear; pPhrase = ( p->eType==FTSQUERY_NEAR ? p->pRight->pPhrase : p->pPhrase ); res = fts3EvalNearTrim(nNear, aTmp, &aPoslist, &nToken, pPhrase); } } sqlite3_free(aTmp); } } return res; } /* ** This function is a helper function for sqlite3Fts3EvalTestDeferred(). ** Assuming no error occurs or has occurred, It returns non-zero if the ** expression passed as the second argument matches the row that pCsr ** currently points to, or zero if it does not. ** ** If *pRc is not SQLITE_OK when this function is called, it is a no-op. ** If an error occurs during execution of this function, *pRc is set to ** the appropriate SQLite error code. In this case the returned value is ** undefined. */ static int fts3EvalTestExpr( Fts3Cursor *pCsr, /* FTS cursor handle */ Fts3Expr *pExpr, /* Expr to test. May or may not be root. */ int *pRc /* IN/OUT: Error code */ ){ int bHit = 1; /* Return value */ if( *pRc==SQLITE_OK ){ switch( pExpr->eType ){ case FTSQUERY_NEAR: case FTSQUERY_AND: bHit = ( fts3EvalTestExpr(pCsr, pExpr->pLeft, pRc) && fts3EvalTestExpr(pCsr, pExpr->pRight, pRc) && fts3EvalNearTest(pExpr, pRc) ); /* If the NEAR expression does not match any rows, zero the doclist for ** all phrases involved in the NEAR. This is because the snippet(), ** offsets() and matchinfo() functions are not supposed to recognize ** any instances of phrases that are part of unmatched NEAR queries. ** For example if this expression: ** ** ... MATCH 'a OR (b NEAR c)' ** ** is matched against a row containing: ** ** 'a b d e' ** ** then any snippet() should ony highlight the "a" term, not the "b" ** (as "b" is part of a non-matching NEAR clause). */ if( bHit==0 && pExpr->eType==FTSQUERY_NEAR && (pExpr->pParent==0 || pExpr->pParent->eType!=FTSQUERY_NEAR) ){ Fts3Expr *p; for(p=pExpr; p->pPhrase==0; p=p->pLeft){ if( p->pRight->iDocid==pCsr->iPrevId ){ fts3EvalInvalidatePoslist(p->pRight->pPhrase); } } if( p->iDocid==pCsr->iPrevId ){ fts3EvalInvalidatePoslist(p->pPhrase); } } break; case FTSQUERY_OR: { int bHit1 = fts3EvalTestExpr(pCsr, pExpr->pLeft, pRc); int bHit2 = fts3EvalTestExpr(pCsr, pExpr->pRight, pRc); bHit = bHit1 || bHit2; break; } case FTSQUERY_NOT: bHit = ( fts3EvalTestExpr(pCsr, pExpr->pLeft, pRc) && !fts3EvalTestExpr(pCsr, pExpr->pRight, pRc) ); break; default: { #ifndef SQLITE_DISABLE_FTS4_DEFERRED if( pCsr->pDeferred && (pExpr->iDocid==pCsr->iPrevId || pExpr->bDeferred) ){ Fts3Phrase *pPhrase = pExpr->pPhrase; assert( pExpr->bDeferred || pPhrase->doclist.bFreeList==0 ); if( pExpr->bDeferred ){ fts3EvalInvalidatePoslist(pPhrase); } *pRc = fts3EvalDeferredPhrase(pCsr, pPhrase); bHit = (pPhrase->doclist.pList!=0); pExpr->iDocid = pCsr->iPrevId; }else #endif { bHit = (pExpr->bEof==0 && pExpr->iDocid==pCsr->iPrevId); } break; } } } return bHit; } /* ** This function is called as the second part of each xNext operation when ** iterating through the results of a full-text query. At this point the ** cursor points to a row that matches the query expression, with the ** following caveats: ** ** * Up until this point, "NEAR" operators in the expression have been ** treated as "AND". ** ** * Deferred tokens have not yet been considered. ** ** If *pRc is not SQLITE_OK when this function is called, it immediately ** returns 0. Otherwise, it tests whether or not after considering NEAR ** operators and deferred tokens the current row is still a match for the ** expression. It returns 1 if both of the following are true: ** ** 1. *pRc is SQLITE_OK when this function returns, and ** ** 2. After scanning the current FTS table row for the deferred tokens, ** it is determined that the row does *not* match the query. ** ** Or, if no error occurs and it seems the current row does match the FTS ** query, return 0. */ SQLITE_PRIVATE int sqlite3Fts3EvalTestDeferred(Fts3Cursor *pCsr, int *pRc){ int rc = *pRc; int bMiss = 0; if( rc==SQLITE_OK ){ /* If there are one or more deferred tokens, load the current row into ** memory and scan it to determine the position list for each deferred ** token. Then, see if this row is really a match, considering deferred ** tokens and NEAR operators (neither of which were taken into account ** earlier, by fts3EvalNextRow()). */ if( pCsr->pDeferred ){ rc = fts3CursorSeek(0, pCsr); if( rc==SQLITE_OK ){ rc = sqlite3Fts3CacheDeferredDoclists(pCsr); } } bMiss = (0==fts3EvalTestExpr(pCsr, pCsr->pExpr, &rc)); /* Free the position-lists accumulated for each deferred token above. */ sqlite3Fts3FreeDeferredDoclists(pCsr); *pRc = rc; } return (rc==SQLITE_OK && bMiss); } /* ** Advance to the next document that matches the FTS expression in ** Fts3Cursor.pExpr. */ static int fts3EvalNext(Fts3Cursor *pCsr){ int rc = SQLITE_OK; /* Return Code */ Fts3Expr *pExpr = pCsr->pExpr; assert( pCsr->isEof==0 ); if( pExpr==0 ){ pCsr->isEof = 1; }else{ do { if( pCsr->isRequireSeek==0 ){ sqlite3_reset(pCsr->pStmt); } assert( sqlite3_data_count(pCsr->pStmt)==0 ); fts3EvalNextRow(pCsr, pExpr, &rc); pCsr->isEof = pExpr->bEof; pCsr->isRequireSeek = 1; pCsr->isMatchinfoNeeded = 1; pCsr->iPrevId = pExpr->iDocid; }while( pCsr->isEof==0 && sqlite3Fts3EvalTestDeferred(pCsr, &rc) ); } /* Check if the cursor is past the end of the docid range specified ** by Fts3Cursor.iMinDocid/iMaxDocid. If so, set the EOF flag. */ if( rc==SQLITE_OK && ( (pCsr->bDesc==0 && pCsr->iPrevId>pCsr->iMaxDocid) || (pCsr->bDesc!=0 && pCsr->iPrevIdiMinDocid) )){ pCsr->isEof = 1; } return rc; } /* ** Restart interation for expression pExpr so that the next call to ** fts3EvalNext() visits the first row. Do not allow incremental ** loading or merging of phrase doclists for this iteration. ** ** If *pRc is other than SQLITE_OK when this function is called, it is ** a no-op. If an error occurs within this function, *pRc is set to an ** SQLite error code before returning. */ static void fts3EvalRestart( Fts3Cursor *pCsr, Fts3Expr *pExpr, int *pRc ){ if( pExpr && *pRc==SQLITE_OK ){ Fts3Phrase *pPhrase = pExpr->pPhrase; if( pPhrase ){ fts3EvalInvalidatePoslist(pPhrase); if( pPhrase->bIncr ){ int i; for(i=0; inToken; i++){ Fts3PhraseToken *pToken = &pPhrase->aToken[i]; assert( pToken->pDeferred==0 ); if( pToken->pSegcsr ){ sqlite3Fts3MsrIncrRestart(pToken->pSegcsr); } } *pRc = fts3EvalPhraseStart(pCsr, 0, pPhrase); } pPhrase->doclist.pNextDocid = 0; pPhrase->doclist.iDocid = 0; pPhrase->pOrPoslist = 0; } pExpr->iDocid = 0; pExpr->bEof = 0; pExpr->bStart = 0; fts3EvalRestart(pCsr, pExpr->pLeft, pRc); fts3EvalRestart(pCsr, pExpr->pRight, pRc); } } /* ** After allocating the Fts3Expr.aMI[] array for each phrase in the ** expression rooted at pExpr, the cursor iterates through all rows matched ** by pExpr, calling this function for each row. This function increments ** the values in Fts3Expr.aMI[] according to the position-list currently ** found in Fts3Expr.pPhrase->doclist.pList for each of the phrase ** expression nodes. */ static void fts3EvalUpdateCounts(Fts3Expr *pExpr){ if( pExpr ){ Fts3Phrase *pPhrase = pExpr->pPhrase; if( pPhrase && pPhrase->doclist.pList ){ int iCol = 0; char *p = pPhrase->doclist.pList; assert( *p ); while( 1 ){ u8 c = 0; int iCnt = 0; while( 0xFE & (*p | c) ){ if( (c&0x80)==0 ) iCnt++; c = *p++ & 0x80; } /* aMI[iCol*3 + 1] = Number of occurrences ** aMI[iCol*3 + 2] = Number of rows containing at least one instance */ pExpr->aMI[iCol*3 + 1] += iCnt; pExpr->aMI[iCol*3 + 2] += (iCnt>0); if( *p==0x00 ) break; p++; p += fts3GetVarint32(p, &iCol); } } fts3EvalUpdateCounts(pExpr->pLeft); fts3EvalUpdateCounts(pExpr->pRight); } } /* ** Expression pExpr must be of type FTSQUERY_PHRASE. ** ** If it is not already allocated and populated, this function allocates and ** populates the Fts3Expr.aMI[] array for expression pExpr. If pExpr is part ** of a NEAR expression, then it also allocates and populates the same array ** for all other phrases that are part of the NEAR expression. ** ** SQLITE_OK is returned if the aMI[] array is successfully allocated and ** populated. Otherwise, if an error occurs, an SQLite error code is returned. */ static int fts3EvalGatherStats( Fts3Cursor *pCsr, /* Cursor object */ Fts3Expr *pExpr /* FTSQUERY_PHRASE expression */ ){ int rc = SQLITE_OK; /* Return code */ assert( pExpr->eType==FTSQUERY_PHRASE ); if( pExpr->aMI==0 ){ Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab; Fts3Expr *pRoot; /* Root of NEAR expression */ Fts3Expr *p; /* Iterator used for several purposes */ sqlite3_int64 iPrevId = pCsr->iPrevId; sqlite3_int64 iDocid; u8 bEof; /* Find the root of the NEAR expression */ pRoot = pExpr; while( pRoot->pParent && pRoot->pParent->eType==FTSQUERY_NEAR ){ pRoot = pRoot->pParent; } iDocid = pRoot->iDocid; bEof = pRoot->bEof; assert( pRoot->bStart ); /* Allocate space for the aMSI[] array of each FTSQUERY_PHRASE node */ for(p=pRoot; p; p=p->pLeft){ Fts3Expr *pE = (p->eType==FTSQUERY_PHRASE?p:p->pRight); assert( pE->aMI==0 ); pE->aMI = (u32 *)sqlite3_malloc(pTab->nColumn * 3 * sizeof(u32)); if( !pE->aMI ) return SQLITE_NOMEM; memset(pE->aMI, 0, pTab->nColumn * 3 * sizeof(u32)); } fts3EvalRestart(pCsr, pRoot, &rc); while( pCsr->isEof==0 && rc==SQLITE_OK ){ do { /* Ensure the %_content statement is reset. */ if( pCsr->isRequireSeek==0 ) sqlite3_reset(pCsr->pStmt); assert( sqlite3_data_count(pCsr->pStmt)==0 ); /* Advance to the next document */ fts3EvalNextRow(pCsr, pRoot, &rc); pCsr->isEof = pRoot->bEof; pCsr->isRequireSeek = 1; pCsr->isMatchinfoNeeded = 1; pCsr->iPrevId = pRoot->iDocid; }while( pCsr->isEof==0 && pRoot->eType==FTSQUERY_NEAR && sqlite3Fts3EvalTestDeferred(pCsr, &rc) ); if( rc==SQLITE_OK && pCsr->isEof==0 ){ fts3EvalUpdateCounts(pRoot); } } pCsr->isEof = 0; pCsr->iPrevId = iPrevId; if( bEof ){ pRoot->bEof = bEof; }else{ /* Caution: pRoot may iterate through docids in ascending or descending ** order. For this reason, even though it seems more defensive, the ** do loop can not be written: ** ** do {...} while( pRoot->iDocidbEof==0 ); }while( pRoot->iDocid!=iDocid && rc==SQLITE_OK ); } } return rc; } /* ** This function is used by the matchinfo() module to query a phrase ** expression node for the following information: ** ** 1. The total number of occurrences of the phrase in each column of ** the FTS table (considering all rows), and ** ** 2. For each column, the number of rows in the table for which the ** column contains at least one instance of the phrase. ** ** If no error occurs, SQLITE_OK is returned and the values for each column ** written into the array aiOut as follows: ** ** aiOut[iCol*3 + 1] = Number of occurrences ** aiOut[iCol*3 + 2] = Number of rows containing at least one instance ** ** Caveats: ** ** * If a phrase consists entirely of deferred tokens, then all output ** values are set to the number of documents in the table. In other ** words we assume that very common tokens occur exactly once in each ** column of each row of the table. ** ** * If a phrase contains some deferred tokens (and some non-deferred ** tokens), count the potential occurrence identified by considering ** the non-deferred tokens instead of actual phrase occurrences. ** ** * If the phrase is part of a NEAR expression, then only phrase instances ** that meet the NEAR constraint are included in the counts. */ SQLITE_PRIVATE int sqlite3Fts3EvalPhraseStats( Fts3Cursor *pCsr, /* FTS cursor handle */ Fts3Expr *pExpr, /* Phrase expression */ u32 *aiOut /* Array to write results into (see above) */ ){ Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab; int rc = SQLITE_OK; int iCol; if( pExpr->bDeferred && pExpr->pParent->eType!=FTSQUERY_NEAR ){ assert( pCsr->nDoc>0 ); for(iCol=0; iColnColumn; iCol++){ aiOut[iCol*3 + 1] = (u32)pCsr->nDoc; aiOut[iCol*3 + 2] = (u32)pCsr->nDoc; } }else{ rc = fts3EvalGatherStats(pCsr, pExpr); if( rc==SQLITE_OK ){ assert( pExpr->aMI ); for(iCol=0; iColnColumn; iCol++){ aiOut[iCol*3 + 1] = pExpr->aMI[iCol*3 + 1]; aiOut[iCol*3 + 2] = pExpr->aMI[iCol*3 + 2]; } } } return rc; } /* ** The expression pExpr passed as the second argument to this function ** must be of type FTSQUERY_PHRASE. ** ** The returned value is either NULL or a pointer to a buffer containing ** a position-list indicating the occurrences of the phrase in column iCol ** of the current row. ** ** More specifically, the returned buffer contains 1 varint for each ** occurrence of the phrase in the column, stored using the normal (delta+2) ** compression and is terminated by either an 0x01 or 0x00 byte. For example, ** if the requested column contains "a b X c d X X" and the position-list ** for 'X' is requested, the buffer returned may contain: ** ** 0x04 0x05 0x03 0x01 or 0x04 0x05 0x03 0x00 ** ** This function works regardless of whether or not the phrase is deferred, ** incremental, or neither. */ SQLITE_PRIVATE int sqlite3Fts3EvalPhrasePoslist( Fts3Cursor *pCsr, /* FTS3 cursor object */ Fts3Expr *pExpr, /* Phrase to return doclist for */ int iCol, /* Column to return position list for */ char **ppOut /* OUT: Pointer to position list */ ){ Fts3Phrase *pPhrase = pExpr->pPhrase; Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab; char *pIter; int iThis; sqlite3_int64 iDocid; /* If this phrase is applies specifically to some column other than ** column iCol, return a NULL pointer. */ *ppOut = 0; assert( iCol>=0 && iColnColumn ); if( (pPhrase->iColumnnColumn && pPhrase->iColumn!=iCol) ){ return SQLITE_OK; } iDocid = pExpr->iDocid; pIter = pPhrase->doclist.pList; if( iDocid!=pCsr->iPrevId || pExpr->bEof ){ int rc = SQLITE_OK; int bDescDoclist = pTab->bDescIdx; /* For DOCID_CMP macro */ int bOr = 0; u8 bTreeEof = 0; Fts3Expr *p; /* Used to iterate from pExpr to root */ Fts3Expr *pNear; /* Most senior NEAR ancestor (or pExpr) */ int bMatch; /* Check if this phrase descends from an OR expression node. If not, ** return NULL. Otherwise, the entry that corresponds to docid ** pCsr->iPrevId may lie earlier in the doclist buffer. Or, if the ** tree that the node is part of has been marked as EOF, but the node ** itself is not EOF, then it may point to an earlier entry. */ pNear = pExpr; for(p=pExpr->pParent; p; p=p->pParent){ if( p->eType==FTSQUERY_OR ) bOr = 1; if( p->eType==FTSQUERY_NEAR ) pNear = p; if( p->bEof ) bTreeEof = 1; } if( bOr==0 ) return SQLITE_OK; /* This is the descendent of an OR node. In this case we cannot use ** an incremental phrase. Load the entire doclist for the phrase ** into memory in this case. */ if( pPhrase->bIncr ){ int bEofSave = pNear->bEof; fts3EvalRestart(pCsr, pNear, &rc); while( rc==SQLITE_OK && !pNear->bEof ){ fts3EvalNextRow(pCsr, pNear, &rc); if( bEofSave==0 && pNear->iDocid==iDocid ) break; } assert( rc!=SQLITE_OK || pPhrase->bIncr==0 ); } if( bTreeEof ){ while( rc==SQLITE_OK && !pNear->bEof ){ fts3EvalNextRow(pCsr, pNear, &rc); } } if( rc!=SQLITE_OK ) return rc; bMatch = 1; for(p=pNear; p; p=p->pLeft){ u8 bEof = 0; Fts3Expr *pTest = p; Fts3Phrase *pPh; assert( pTest->eType==FTSQUERY_NEAR || pTest->eType==FTSQUERY_PHRASE ); if( pTest->eType==FTSQUERY_NEAR ) pTest = pTest->pRight; assert( pTest->eType==FTSQUERY_PHRASE ); pPh = pTest->pPhrase; pIter = pPh->pOrPoslist; iDocid = pPh->iOrDocid; if( pCsr->bDesc==bDescDoclist ){ bEof = !pPh->doclist.nAll || (pIter >= (pPh->doclist.aAll + pPh->doclist.nAll)); while( (pIter==0 || DOCID_CMP(iDocid, pCsr->iPrevId)<0 ) && bEof==0 ){ sqlite3Fts3DoclistNext( bDescDoclist, pPh->doclist.aAll, pPh->doclist.nAll, &pIter, &iDocid, &bEof ); } }else{ bEof = !pPh->doclist.nAll || (pIter && pIter<=pPh->doclist.aAll); while( (pIter==0 || DOCID_CMP(iDocid, pCsr->iPrevId)>0 ) && bEof==0 ){ int dummy; sqlite3Fts3DoclistPrev( bDescDoclist, pPh->doclist.aAll, pPh->doclist.nAll, &pIter, &iDocid, &dummy, &bEof ); } } pPh->pOrPoslist = pIter; pPh->iOrDocid = iDocid; if( bEof || iDocid!=pCsr->iPrevId ) bMatch = 0; } if( bMatch ){ pIter = pPhrase->pOrPoslist; }else{ pIter = 0; } } if( pIter==0 ) return SQLITE_OK; if( *pIter==0x01 ){ pIter++; pIter += fts3GetVarint32(pIter, &iThis); }else{ iThis = 0; } while( iThisdoclist, and ** * any Fts3MultiSegReader objects held by phrase tokens. */ SQLITE_PRIVATE void sqlite3Fts3EvalPhraseCleanup(Fts3Phrase *pPhrase){ if( pPhrase ){ int i; sqlite3_free(pPhrase->doclist.aAll); fts3EvalInvalidatePoslist(pPhrase); memset(&pPhrase->doclist, 0, sizeof(Fts3Doclist)); for(i=0; inToken; i++){ fts3SegReaderCursorFree(pPhrase->aToken[i].pSegcsr); pPhrase->aToken[i].pSegcsr = 0; } } } /* ** Return SQLITE_CORRUPT_VTAB. */ #ifdef SQLITE_DEBUG SQLITE_PRIVATE int sqlite3Fts3Corrupt(){ return SQLITE_CORRUPT_VTAB; } #endif #if !SQLITE_CORE /* ** Initialize API pointer table, if required. */ #ifdef _WIN32 __declspec(dllexport) #endif SQLITE_API int sqlite3_fts3_init( sqlite3 *db, char **pzErrMsg, const sqlite3_api_routines *pApi ){ SQLITE_EXTENSION_INIT2(pApi) return sqlite3Fts3Init(db); } #endif #endif /************** End of fts3.c ************************************************/ /************** Begin file fts3_aux.c ****************************************/ /* ** 2011 Jan 27 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ****************************************************************************** ** */ /* #include "fts3Int.h" */ #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) /* #include */ /* #include */ typedef struct Fts3auxTable Fts3auxTable; typedef struct Fts3auxCursor Fts3auxCursor; struct Fts3auxTable { sqlite3_vtab base; /* Base class used by SQLite core */ Fts3Table *pFts3Tab; }; struct Fts3auxCursor { sqlite3_vtab_cursor base; /* Base class used by SQLite core */ Fts3MultiSegReader csr; /* Must be right after "base" */ Fts3SegFilter filter; char *zStop; int nStop; /* Byte-length of string zStop */ int iLangid; /* Language id to query */ int isEof; /* True if cursor is at EOF */ sqlite3_int64 iRowid; /* Current rowid */ int iCol; /* Current value of 'col' column */ int nStat; /* Size of aStat[] array */ struct Fts3auxColstats { sqlite3_int64 nDoc; /* 'documents' values for current csr row */ sqlite3_int64 nOcc; /* 'occurrences' values for current csr row */ } *aStat; }; /* ** Schema of the terms table. */ #define FTS3_AUX_SCHEMA \ "CREATE TABLE x(term, col, documents, occurrences, languageid HIDDEN)" /* ** This function does all the work for both the xConnect and xCreate methods. ** These tables have no persistent representation of their own, so xConnect ** and xCreate are identical operations. */ static int fts3auxConnectMethod( sqlite3 *db, /* Database connection */ void *pUnused, /* Unused */ int argc, /* Number of elements in argv array */ const char * const *argv, /* xCreate/xConnect argument array */ sqlite3_vtab **ppVtab, /* OUT: New sqlite3_vtab object */ char **pzErr /* OUT: sqlite3_malloc'd error message */ ){ char const *zDb; /* Name of database (e.g. "main") */ char const *zFts3; /* Name of fts3 table */ int nDb; /* Result of strlen(zDb) */ int nFts3; /* Result of strlen(zFts3) */ int nByte; /* Bytes of space to allocate here */ int rc; /* value returned by declare_vtab() */ Fts3auxTable *p; /* Virtual table object to return */ UNUSED_PARAMETER(pUnused); /* The user should invoke this in one of two forms: ** ** CREATE VIRTUAL TABLE xxx USING fts4aux(fts4-table); ** CREATE VIRTUAL TABLE xxx USING fts4aux(fts4-table-db, fts4-table); */ if( argc!=4 && argc!=5 ) goto bad_args; zDb = argv[1]; nDb = (int)strlen(zDb); if( argc==5 ){ if( nDb==4 && 0==sqlite3_strnicmp("temp", zDb, 4) ){ zDb = argv[3]; nDb = (int)strlen(zDb); zFts3 = argv[4]; }else{ goto bad_args; } }else{ zFts3 = argv[3]; } nFts3 = (int)strlen(zFts3); rc = sqlite3_declare_vtab(db, FTS3_AUX_SCHEMA); if( rc!=SQLITE_OK ) return rc; nByte = sizeof(Fts3auxTable) + sizeof(Fts3Table) + nDb + nFts3 + 2; p = (Fts3auxTable *)sqlite3_malloc(nByte); if( !p ) return SQLITE_NOMEM; memset(p, 0, nByte); p->pFts3Tab = (Fts3Table *)&p[1]; p->pFts3Tab->zDb = (char *)&p->pFts3Tab[1]; p->pFts3Tab->zName = &p->pFts3Tab->zDb[nDb+1]; p->pFts3Tab->db = db; p->pFts3Tab->nIndex = 1; memcpy((char *)p->pFts3Tab->zDb, zDb, nDb); memcpy((char *)p->pFts3Tab->zName, zFts3, nFts3); sqlite3Fts3Dequote((char *)p->pFts3Tab->zName); *ppVtab = (sqlite3_vtab *)p; return SQLITE_OK; bad_args: sqlite3Fts3ErrMsg(pzErr, "invalid arguments to fts4aux constructor"); return SQLITE_ERROR; } /* ** This function does the work for both the xDisconnect and xDestroy methods. ** These tables have no persistent representation of their own, so xDisconnect ** and xDestroy are identical operations. */ static int fts3auxDisconnectMethod(sqlite3_vtab *pVtab){ Fts3auxTable *p = (Fts3auxTable *)pVtab; Fts3Table *pFts3 = p->pFts3Tab; int i; /* Free any prepared statements held */ for(i=0; iaStmt); i++){ sqlite3_finalize(pFts3->aStmt[i]); } sqlite3_free(pFts3->zSegmentsTbl); sqlite3_free(p); return SQLITE_OK; } #define FTS4AUX_EQ_CONSTRAINT 1 #define FTS4AUX_GE_CONSTRAINT 2 #define FTS4AUX_LE_CONSTRAINT 4 /* ** xBestIndex - Analyze a WHERE and ORDER BY clause. */ static int fts3auxBestIndexMethod( sqlite3_vtab *pVTab, sqlite3_index_info *pInfo ){ int i; int iEq = -1; int iGe = -1; int iLe = -1; int iLangid = -1; int iNext = 1; /* Next free argvIndex value */ UNUSED_PARAMETER(pVTab); /* This vtab delivers always results in "ORDER BY term ASC" order. */ if( pInfo->nOrderBy==1 && pInfo->aOrderBy[0].iColumn==0 && pInfo->aOrderBy[0].desc==0 ){ pInfo->orderByConsumed = 1; } /* Search for equality and range constraints on the "term" column. ** And equality constraints on the hidden "languageid" column. */ for(i=0; inConstraint; i++){ if( pInfo->aConstraint[i].usable ){ int op = pInfo->aConstraint[i].op; int iCol = pInfo->aConstraint[i].iColumn; if( iCol==0 ){ if( op==SQLITE_INDEX_CONSTRAINT_EQ ) iEq = i; if( op==SQLITE_INDEX_CONSTRAINT_LT ) iLe = i; if( op==SQLITE_INDEX_CONSTRAINT_LE ) iLe = i; if( op==SQLITE_INDEX_CONSTRAINT_GT ) iGe = i; if( op==SQLITE_INDEX_CONSTRAINT_GE ) iGe = i; } if( iCol==4 ){ if( op==SQLITE_INDEX_CONSTRAINT_EQ ) iLangid = i; } } } if( iEq>=0 ){ pInfo->idxNum = FTS4AUX_EQ_CONSTRAINT; pInfo->aConstraintUsage[iEq].argvIndex = iNext++; pInfo->estimatedCost = 5; }else{ pInfo->idxNum = 0; pInfo->estimatedCost = 20000; if( iGe>=0 ){ pInfo->idxNum += FTS4AUX_GE_CONSTRAINT; pInfo->aConstraintUsage[iGe].argvIndex = iNext++; pInfo->estimatedCost /= 2; } if( iLe>=0 ){ pInfo->idxNum += FTS4AUX_LE_CONSTRAINT; pInfo->aConstraintUsage[iLe].argvIndex = iNext++; pInfo->estimatedCost /= 2; } } if( iLangid>=0 ){ pInfo->aConstraintUsage[iLangid].argvIndex = iNext++; pInfo->estimatedCost--; } return SQLITE_OK; } /* ** xOpen - Open a cursor. */ static int fts3auxOpenMethod(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCsr){ Fts3auxCursor *pCsr; /* Pointer to cursor object to return */ UNUSED_PARAMETER(pVTab); pCsr = (Fts3auxCursor *)sqlite3_malloc(sizeof(Fts3auxCursor)); if( !pCsr ) return SQLITE_NOMEM; memset(pCsr, 0, sizeof(Fts3auxCursor)); *ppCsr = (sqlite3_vtab_cursor *)pCsr; return SQLITE_OK; } /* ** xClose - Close a cursor. */ static int fts3auxCloseMethod(sqlite3_vtab_cursor *pCursor){ Fts3Table *pFts3 = ((Fts3auxTable *)pCursor->pVtab)->pFts3Tab; Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor; sqlite3Fts3SegmentsClose(pFts3); sqlite3Fts3SegReaderFinish(&pCsr->csr); sqlite3_free((void *)pCsr->filter.zTerm); sqlite3_free(pCsr->zStop); sqlite3_free(pCsr->aStat); sqlite3_free(pCsr); return SQLITE_OK; } static int fts3auxGrowStatArray(Fts3auxCursor *pCsr, int nSize){ if( nSize>pCsr->nStat ){ struct Fts3auxColstats *aNew; aNew = (struct Fts3auxColstats *)sqlite3_realloc(pCsr->aStat, sizeof(struct Fts3auxColstats) * nSize ); if( aNew==0 ) return SQLITE_NOMEM; memset(&aNew[pCsr->nStat], 0, sizeof(struct Fts3auxColstats) * (nSize - pCsr->nStat) ); pCsr->aStat = aNew; pCsr->nStat = nSize; } return SQLITE_OK; } /* ** xNext - Advance the cursor to the next row, if any. */ static int fts3auxNextMethod(sqlite3_vtab_cursor *pCursor){ Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor; Fts3Table *pFts3 = ((Fts3auxTable *)pCursor->pVtab)->pFts3Tab; int rc; /* Increment our pretend rowid value. */ pCsr->iRowid++; for(pCsr->iCol++; pCsr->iColnStat; pCsr->iCol++){ if( pCsr->aStat[pCsr->iCol].nDoc>0 ) return SQLITE_OK; } rc = sqlite3Fts3SegReaderStep(pFts3, &pCsr->csr); if( rc==SQLITE_ROW ){ int i = 0; int nDoclist = pCsr->csr.nDoclist; char *aDoclist = pCsr->csr.aDoclist; int iCol; int eState = 0; if( pCsr->zStop ){ int n = (pCsr->nStopcsr.nTerm) ? pCsr->nStop : pCsr->csr.nTerm; int mc = memcmp(pCsr->zStop, pCsr->csr.zTerm, n); if( mc<0 || (mc==0 && pCsr->csr.nTerm>pCsr->nStop) ){ pCsr->isEof = 1; return SQLITE_OK; } } if( fts3auxGrowStatArray(pCsr, 2) ) return SQLITE_NOMEM; memset(pCsr->aStat, 0, sizeof(struct Fts3auxColstats) * pCsr->nStat); iCol = 0; while( iaStat[0].nDoc++; eState = 1; iCol = 0; break; /* State 1. In this state we are expecting either a 1, indicating ** that the following integer will be a column number, or the ** start of a position list for column 0. ** ** The only difference between state 1 and state 2 is that if the ** integer encountered in state 1 is not 0 or 1, then we need to ** increment the column 0 "nDoc" count for this term. */ case 1: assert( iCol==0 ); if( v>1 ){ pCsr->aStat[1].nDoc++; } eState = 2; /* fall through */ case 2: if( v==0 ){ /* 0x00. Next integer will be a docid. */ eState = 0; }else if( v==1 ){ /* 0x01. Next integer will be a column number. */ eState = 3; }else{ /* 2 or greater. A position. */ pCsr->aStat[iCol+1].nOcc++; pCsr->aStat[0].nOcc++; } break; /* State 3. The integer just read is a column number. */ default: assert( eState==3 ); iCol = (int)v; if( fts3auxGrowStatArray(pCsr, iCol+2) ) return SQLITE_NOMEM; pCsr->aStat[iCol+1].nDoc++; eState = 2; break; } } pCsr->iCol = 0; rc = SQLITE_OK; }else{ pCsr->isEof = 1; } return rc; } /* ** xFilter - Initialize a cursor to point at the start of its data. */ static int fts3auxFilterMethod( sqlite3_vtab_cursor *pCursor, /* The cursor used for this query */ int idxNum, /* Strategy index */ const char *idxStr, /* Unused */ int nVal, /* Number of elements in apVal */ sqlite3_value **apVal /* Arguments for the indexing scheme */ ){ Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor; Fts3Table *pFts3 = ((Fts3auxTable *)pCursor->pVtab)->pFts3Tab; int rc; int isScan = 0; int iLangVal = 0; /* Language id to query */ int iEq = -1; /* Index of term=? value in apVal */ int iGe = -1; /* Index of term>=? value in apVal */ int iLe = -1; /* Index of term<=? value in apVal */ int iLangid = -1; /* Index of languageid=? value in apVal */ int iNext = 0; UNUSED_PARAMETER(nVal); UNUSED_PARAMETER(idxStr); assert( idxStr==0 ); assert( idxNum==FTS4AUX_EQ_CONSTRAINT || idxNum==0 || idxNum==FTS4AUX_LE_CONSTRAINT || idxNum==FTS4AUX_GE_CONSTRAINT || idxNum==(FTS4AUX_LE_CONSTRAINT|FTS4AUX_GE_CONSTRAINT) ); if( idxNum==FTS4AUX_EQ_CONSTRAINT ){ iEq = iNext++; }else{ isScan = 1; if( idxNum & FTS4AUX_GE_CONSTRAINT ){ iGe = iNext++; } if( idxNum & FTS4AUX_LE_CONSTRAINT ){ iLe = iNext++; } } if( iNextfilter.zTerm); sqlite3Fts3SegReaderFinish(&pCsr->csr); sqlite3_free((void *)pCsr->filter.zTerm); sqlite3_free(pCsr->aStat); memset(&pCsr->csr, 0, ((u8*)&pCsr[1]) - (u8*)&pCsr->csr); pCsr->filter.flags = FTS3_SEGMENT_REQUIRE_POS|FTS3_SEGMENT_IGNORE_EMPTY; if( isScan ) pCsr->filter.flags |= FTS3_SEGMENT_SCAN; if( iEq>=0 || iGe>=0 ){ const unsigned char *zStr = sqlite3_value_text(apVal[0]); assert( (iEq==0 && iGe==-1) || (iEq==-1 && iGe==0) ); if( zStr ){ pCsr->filter.zTerm = sqlite3_mprintf("%s", zStr); pCsr->filter.nTerm = sqlite3_value_bytes(apVal[0]); if( pCsr->filter.zTerm==0 ) return SQLITE_NOMEM; } } if( iLe>=0 ){ pCsr->zStop = sqlite3_mprintf("%s", sqlite3_value_text(apVal[iLe])); pCsr->nStop = sqlite3_value_bytes(apVal[iLe]); if( pCsr->zStop==0 ) return SQLITE_NOMEM; } if( iLangid>=0 ){ iLangVal = sqlite3_value_int(apVal[iLangid]); /* If the user specified a negative value for the languageid, use zero ** instead. This works, as the "languageid=?" constraint will also ** be tested by the VDBE layer. The test will always be false (since ** this module will not return a row with a negative languageid), and ** so the overall query will return zero rows. */ if( iLangVal<0 ) iLangVal = 0; } pCsr->iLangid = iLangVal; rc = sqlite3Fts3SegReaderCursor(pFts3, iLangVal, 0, FTS3_SEGCURSOR_ALL, pCsr->filter.zTerm, pCsr->filter.nTerm, 0, isScan, &pCsr->csr ); if( rc==SQLITE_OK ){ rc = sqlite3Fts3SegReaderStart(pFts3, &pCsr->csr, &pCsr->filter); } if( rc==SQLITE_OK ) rc = fts3auxNextMethod(pCursor); return rc; } /* ** xEof - Return true if the cursor is at EOF, or false otherwise. */ static int fts3auxEofMethod(sqlite3_vtab_cursor *pCursor){ Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor; return pCsr->isEof; } /* ** xColumn - Return a column value. */ static int fts3auxColumnMethod( sqlite3_vtab_cursor *pCursor, /* Cursor to retrieve value from */ sqlite3_context *pCtx, /* Context for sqlite3_result_xxx() calls */ int iCol /* Index of column to read value from */ ){ Fts3auxCursor *p = (Fts3auxCursor *)pCursor; assert( p->isEof==0 ); switch( iCol ){ case 0: /* term */ sqlite3_result_text(pCtx, p->csr.zTerm, p->csr.nTerm, SQLITE_TRANSIENT); break; case 1: /* col */ if( p->iCol ){ sqlite3_result_int(pCtx, p->iCol-1); }else{ sqlite3_result_text(pCtx, "*", -1, SQLITE_STATIC); } break; case 2: /* documents */ sqlite3_result_int64(pCtx, p->aStat[p->iCol].nDoc); break; case 3: /* occurrences */ sqlite3_result_int64(pCtx, p->aStat[p->iCol].nOcc); break; default: /* languageid */ assert( iCol==4 ); sqlite3_result_int(pCtx, p->iLangid); break; } return SQLITE_OK; } /* ** xRowid - Return the current rowid for the cursor. */ static int fts3auxRowidMethod( sqlite3_vtab_cursor *pCursor, /* Cursor to retrieve value from */ sqlite_int64 *pRowid /* OUT: Rowid value */ ){ Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor; *pRowid = pCsr->iRowid; return SQLITE_OK; } /* ** Register the fts3aux module with database connection db. Return SQLITE_OK ** if successful or an error code if sqlite3_create_module() fails. */ SQLITE_PRIVATE int sqlite3Fts3InitAux(sqlite3 *db){ static const sqlite3_module fts3aux_module = { 0, /* iVersion */ fts3auxConnectMethod, /* xCreate */ fts3auxConnectMethod, /* xConnect */ fts3auxBestIndexMethod, /* xBestIndex */ fts3auxDisconnectMethod, /* xDisconnect */ fts3auxDisconnectMethod, /* xDestroy */ fts3auxOpenMethod, /* xOpen */ fts3auxCloseMethod, /* xClose */ fts3auxFilterMethod, /* xFilter */ fts3auxNextMethod, /* xNext */ fts3auxEofMethod, /* xEof */ fts3auxColumnMethod, /* xColumn */ fts3auxRowidMethod, /* xRowid */ 0, /* xUpdate */ 0, /* xBegin */ 0, /* xSync */ 0, /* xCommit */ 0, /* xRollback */ 0, /* xFindFunction */ 0, /* xRename */ 0, /* xSavepoint */ 0, /* xRelease */ 0 /* xRollbackTo */ }; int rc; /* Return code */ rc = sqlite3_create_module(db, "fts4aux", &fts3aux_module, 0); return rc; } #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */ /************** End of fts3_aux.c ********************************************/ /************** Begin file fts3_expr.c ***************************************/ /* ** 2008 Nov 28 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ****************************************************************************** ** ** This module contains code that implements a parser for fts3 query strings ** (the right-hand argument to the MATCH operator). Because the supported ** syntax is relatively simple, the whole tokenizer/parser system is ** hand-coded. */ /* #include "fts3Int.h" */ #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) /* ** By default, this module parses the legacy syntax that has been ** traditionally used by fts3. Or, if SQLITE_ENABLE_FTS3_PARENTHESIS ** is defined, then it uses the new syntax. The differences between ** the new and the old syntaxes are: ** ** a) The new syntax supports parenthesis. The old does not. ** ** b) The new syntax supports the AND and NOT operators. The old does not. ** ** c) The old syntax supports the "-" token qualifier. This is not ** supported by the new syntax (it is replaced by the NOT operator). ** ** d) When using the old syntax, the OR operator has a greater precedence ** than an implicit AND. When using the new, both implicity and explicit ** AND operators have a higher precedence than OR. ** ** If compiled with SQLITE_TEST defined, then this module exports the ** symbol "int sqlite3_fts3_enable_parentheses". Setting this variable ** to zero causes the module to use the old syntax. If it is set to ** non-zero the new syntax is activated. This is so both syntaxes can ** be tested using a single build of testfixture. ** ** The following describes the syntax supported by the fts3 MATCH ** operator in a similar format to that used by the lemon parser ** generator. This module does not use actually lemon, it uses a ** custom parser. ** ** query ::= andexpr (OR andexpr)*. ** ** andexpr ::= notexpr (AND? notexpr)*. ** ** notexpr ::= nearexpr (NOT nearexpr|-TOKEN)*. ** notexpr ::= LP query RP. ** ** nearexpr ::= phrase (NEAR distance_opt nearexpr)*. ** ** distance_opt ::= . ** distance_opt ::= / INTEGER. ** ** phrase ::= TOKEN. ** phrase ::= COLUMN:TOKEN. ** phrase ::= "TOKEN TOKEN TOKEN...". */ #ifdef SQLITE_TEST SQLITE_API int sqlite3_fts3_enable_parentheses = 0; #else # ifdef SQLITE_ENABLE_FTS3_PARENTHESIS # define sqlite3_fts3_enable_parentheses 1 # else # define sqlite3_fts3_enable_parentheses 0 # endif #endif /* ** Default span for NEAR operators. */ #define SQLITE_FTS3_DEFAULT_NEAR_PARAM 10 /* #include */ /* #include */ /* ** isNot: ** This variable is used by function getNextNode(). When getNextNode() is ** called, it sets ParseContext.isNot to true if the 'next node' is a ** FTSQUERY_PHRASE with a unary "-" attached to it. i.e. "mysql" in the ** FTS3 query "sqlite -mysql". Otherwise, ParseContext.isNot is set to ** zero. */ typedef struct ParseContext ParseContext; struct ParseContext { sqlite3_tokenizer *pTokenizer; /* Tokenizer module */ int iLangid; /* Language id used with tokenizer */ const char **azCol; /* Array of column names for fts3 table */ int bFts4; /* True to allow FTS4-only syntax */ int nCol; /* Number of entries in azCol[] */ int iDefaultCol; /* Default column to query */ int isNot; /* True if getNextNode() sees a unary - */ sqlite3_context *pCtx; /* Write error message here */ int nNest; /* Number of nested brackets */ }; /* ** This function is equivalent to the standard isspace() function. ** ** The standard isspace() can be awkward to use safely, because although it ** is defined to accept an argument of type int, its behavior when passed ** an integer that falls outside of the range of the unsigned char type ** is undefined (and sometimes, "undefined" means segfault). This wrapper ** is defined to accept an argument of type char, and always returns 0 for ** any values that fall outside of the range of the unsigned char type (i.e. ** negative values). */ static int fts3isspace(char c){ return c==' ' || c=='\t' || c=='\n' || c=='\r' || c=='\v' || c=='\f'; } /* ** Allocate nByte bytes of memory using sqlite3_malloc(). If successful, ** zero the memory before returning a pointer to it. If unsuccessful, ** return NULL. */ static void *fts3MallocZero(int nByte){ void *pRet = sqlite3_malloc(nByte); if( pRet ) memset(pRet, 0, nByte); return pRet; } SQLITE_PRIVATE int sqlite3Fts3OpenTokenizer( sqlite3_tokenizer *pTokenizer, int iLangid, const char *z, int n, sqlite3_tokenizer_cursor **ppCsr ){ sqlite3_tokenizer_module const *pModule = pTokenizer->pModule; sqlite3_tokenizer_cursor *pCsr = 0; int rc; rc = pModule->xOpen(pTokenizer, z, n, &pCsr); assert( rc==SQLITE_OK || pCsr==0 ); if( rc==SQLITE_OK ){ pCsr->pTokenizer = pTokenizer; if( pModule->iVersion>=1 ){ rc = pModule->xLanguageid(pCsr, iLangid); if( rc!=SQLITE_OK ){ pModule->xClose(pCsr); pCsr = 0; } } } *ppCsr = pCsr; return rc; } /* ** Function getNextNode(), which is called by fts3ExprParse(), may itself ** call fts3ExprParse(). So this forward declaration is required. */ static int fts3ExprParse(ParseContext *, const char *, int, Fts3Expr **, int *); /* ** Extract the next token from buffer z (length n) using the tokenizer ** and other information (column names etc.) in pParse. Create an Fts3Expr ** structure of type FTSQUERY_PHRASE containing a phrase consisting of this ** single token and set *ppExpr to point to it. If the end of the buffer is ** reached before a token is found, set *ppExpr to zero. It is the ** responsibility of the caller to eventually deallocate the allocated ** Fts3Expr structure (if any) by passing it to sqlite3_free(). ** ** Return SQLITE_OK if successful, or SQLITE_NOMEM if a memory allocation ** fails. */ static int getNextToken( ParseContext *pParse, /* fts3 query parse context */ int iCol, /* Value for Fts3Phrase.iColumn */ const char *z, int n, /* Input string */ Fts3Expr **ppExpr, /* OUT: expression */ int *pnConsumed /* OUT: Number of bytes consumed */ ){ sqlite3_tokenizer *pTokenizer = pParse->pTokenizer; sqlite3_tokenizer_module const *pModule = pTokenizer->pModule; int rc; sqlite3_tokenizer_cursor *pCursor; Fts3Expr *pRet = 0; int i = 0; /* Set variable i to the maximum number of bytes of input to tokenize. */ for(i=0; iiLangid, z, i, &pCursor); if( rc==SQLITE_OK ){ const char *zToken; int nToken = 0, iStart = 0, iEnd = 0, iPosition = 0; int nByte; /* total space to allocate */ rc = pModule->xNext(pCursor, &zToken, &nToken, &iStart, &iEnd, &iPosition); if( rc==SQLITE_OK ){ nByte = sizeof(Fts3Expr) + sizeof(Fts3Phrase) + nToken; pRet = (Fts3Expr *)fts3MallocZero(nByte); if( !pRet ){ rc = SQLITE_NOMEM; }else{ pRet->eType = FTSQUERY_PHRASE; pRet->pPhrase = (Fts3Phrase *)&pRet[1]; pRet->pPhrase->nToken = 1; pRet->pPhrase->iColumn = iCol; pRet->pPhrase->aToken[0].n = nToken; pRet->pPhrase->aToken[0].z = (char *)&pRet->pPhrase[1]; memcpy(pRet->pPhrase->aToken[0].z, zToken, nToken); if( iEndpPhrase->aToken[0].isPrefix = 1; iEnd++; } while( 1 ){ if( !sqlite3_fts3_enable_parentheses && iStart>0 && z[iStart-1]=='-' ){ pParse->isNot = 1; iStart--; }else if( pParse->bFts4 && iStart>0 && z[iStart-1]=='^' ){ pRet->pPhrase->aToken[0].bFirst = 1; iStart--; }else{ break; } } } *pnConsumed = iEnd; }else if( i && rc==SQLITE_DONE ){ rc = SQLITE_OK; } pModule->xClose(pCursor); } *ppExpr = pRet; return rc; } /* ** Enlarge a memory allocation. If an out-of-memory allocation occurs, ** then free the old allocation. */ static void *fts3ReallocOrFree(void *pOrig, int nNew){ void *pRet = sqlite3_realloc(pOrig, nNew); if( !pRet ){ sqlite3_free(pOrig); } return pRet; } /* ** Buffer zInput, length nInput, contains the contents of a quoted string ** that appeared as part of an fts3 query expression. Neither quote character ** is included in the buffer. This function attempts to tokenize the entire ** input buffer and create an Fts3Expr structure of type FTSQUERY_PHRASE ** containing the results. ** ** If successful, SQLITE_OK is returned and *ppExpr set to point at the ** allocated Fts3Expr structure. Otherwise, either SQLITE_NOMEM (out of memory ** error) or SQLITE_ERROR (tokenization error) is returned and *ppExpr set ** to 0. */ static int getNextString( ParseContext *pParse, /* fts3 query parse context */ const char *zInput, int nInput, /* Input string */ Fts3Expr **ppExpr /* OUT: expression */ ){ sqlite3_tokenizer *pTokenizer = pParse->pTokenizer; sqlite3_tokenizer_module const *pModule = pTokenizer->pModule; int rc; Fts3Expr *p = 0; sqlite3_tokenizer_cursor *pCursor = 0; char *zTemp = 0; int nTemp = 0; const int nSpace = sizeof(Fts3Expr) + sizeof(Fts3Phrase); int nToken = 0; /* The final Fts3Expr data structure, including the Fts3Phrase, ** Fts3PhraseToken structures token buffers are all stored as a single ** allocation so that the expression can be freed with a single call to ** sqlite3_free(). Setting this up requires a two pass approach. ** ** The first pass, in the block below, uses a tokenizer cursor to iterate ** through the tokens in the expression. This pass uses fts3ReallocOrFree() ** to assemble data in two dynamic buffers: ** ** Buffer p: Points to the Fts3Expr structure, followed by the Fts3Phrase ** structure, followed by the array of Fts3PhraseToken ** structures. This pass only populates the Fts3PhraseToken array. ** ** Buffer zTemp: Contains copies of all tokens. ** ** The second pass, in the block that begins "if( rc==SQLITE_DONE )" below, ** appends buffer zTemp to buffer p, and fills in the Fts3Expr and Fts3Phrase ** structures. */ rc = sqlite3Fts3OpenTokenizer( pTokenizer, pParse->iLangid, zInput, nInput, &pCursor); if( rc==SQLITE_OK ){ int ii; for(ii=0; rc==SQLITE_OK; ii++){ const char *zByte; int nByte = 0, iBegin = 0, iEnd = 0, iPos = 0; rc = pModule->xNext(pCursor, &zByte, &nByte, &iBegin, &iEnd, &iPos); if( rc==SQLITE_OK ){ Fts3PhraseToken *pToken; p = fts3ReallocOrFree(p, nSpace + ii*sizeof(Fts3PhraseToken)); if( !p ) goto no_mem; zTemp = fts3ReallocOrFree(zTemp, nTemp + nByte); if( !zTemp ) goto no_mem; assert( nToken==ii ); pToken = &((Fts3Phrase *)(&p[1]))->aToken[ii]; memset(pToken, 0, sizeof(Fts3PhraseToken)); memcpy(&zTemp[nTemp], zByte, nByte); nTemp += nByte; pToken->n = nByte; pToken->isPrefix = (iEndbFirst = (iBegin>0 && zInput[iBegin-1]=='^'); nToken = ii+1; } } pModule->xClose(pCursor); pCursor = 0; } if( rc==SQLITE_DONE ){ int jj; char *zBuf = 0; p = fts3ReallocOrFree(p, nSpace + nToken*sizeof(Fts3PhraseToken) + nTemp); if( !p ) goto no_mem; memset(p, 0, (char *)&(((Fts3Phrase *)&p[1])->aToken[0])-(char *)p); p->eType = FTSQUERY_PHRASE; p->pPhrase = (Fts3Phrase *)&p[1]; p->pPhrase->iColumn = pParse->iDefaultCol; p->pPhrase->nToken = nToken; zBuf = (char *)&p->pPhrase->aToken[nToken]; if( zTemp ){ memcpy(zBuf, zTemp, nTemp); sqlite3_free(zTemp); }else{ assert( nTemp==0 ); } for(jj=0; jjpPhrase->nToken; jj++){ p->pPhrase->aToken[jj].z = zBuf; zBuf += p->pPhrase->aToken[jj].n; } rc = SQLITE_OK; } *ppExpr = p; return rc; no_mem: if( pCursor ){ pModule->xClose(pCursor); } sqlite3_free(zTemp); sqlite3_free(p); *ppExpr = 0; return SQLITE_NOMEM; } /* ** The output variable *ppExpr is populated with an allocated Fts3Expr ** structure, or set to 0 if the end of the input buffer is reached. ** ** Returns an SQLite error code. SQLITE_OK if everything works, SQLITE_NOMEM ** if a malloc failure occurs, or SQLITE_ERROR if a parse error is encountered. ** If SQLITE_ERROR is returned, pContext is populated with an error message. */ static int getNextNode( ParseContext *pParse, /* fts3 query parse context */ const char *z, int n, /* Input string */ Fts3Expr **ppExpr, /* OUT: expression */ int *pnConsumed /* OUT: Number of bytes consumed */ ){ static const struct Fts3Keyword { char *z; /* Keyword text */ unsigned char n; /* Length of the keyword */ unsigned char parenOnly; /* Only valid in paren mode */ unsigned char eType; /* Keyword code */ } aKeyword[] = { { "OR" , 2, 0, FTSQUERY_OR }, { "AND", 3, 1, FTSQUERY_AND }, { "NOT", 3, 1, FTSQUERY_NOT }, { "NEAR", 4, 0, FTSQUERY_NEAR } }; int ii; int iCol; int iColLen; int rc; Fts3Expr *pRet = 0; const char *zInput = z; int nInput = n; pParse->isNot = 0; /* Skip over any whitespace before checking for a keyword, an open or ** close bracket, or a quoted string. */ while( nInput>0 && fts3isspace(*zInput) ){ nInput--; zInput++; } if( nInput==0 ){ return SQLITE_DONE; } /* See if we are dealing with a keyword. */ for(ii=0; ii<(int)(sizeof(aKeyword)/sizeof(struct Fts3Keyword)); ii++){ const struct Fts3Keyword *pKey = &aKeyword[ii]; if( (pKey->parenOnly & ~sqlite3_fts3_enable_parentheses)!=0 ){ continue; } if( nInput>=pKey->n && 0==memcmp(zInput, pKey->z, pKey->n) ){ int nNear = SQLITE_FTS3_DEFAULT_NEAR_PARAM; int nKey = pKey->n; char cNext; /* If this is a "NEAR" keyword, check for an explicit nearness. */ if( pKey->eType==FTSQUERY_NEAR ){ assert( nKey==4 ); if( zInput[4]=='/' && zInput[5]>='0' && zInput[5]<='9' ){ nNear = 0; for(nKey=5; zInput[nKey]>='0' && zInput[nKey]<='9'; nKey++){ nNear = nNear * 10 + (zInput[nKey] - '0'); } } } /* At this point this is probably a keyword. But for that to be true, ** the next byte must contain either whitespace, an open or close ** parenthesis, a quote character, or EOF. */ cNext = zInput[nKey]; if( fts3isspace(cNext) || cNext=='"' || cNext=='(' || cNext==')' || cNext==0 ){ pRet = (Fts3Expr *)fts3MallocZero(sizeof(Fts3Expr)); if( !pRet ){ return SQLITE_NOMEM; } pRet->eType = pKey->eType; pRet->nNear = nNear; *ppExpr = pRet; *pnConsumed = (int)((zInput - z) + nKey); return SQLITE_OK; } /* Turns out that wasn't a keyword after all. This happens if the ** user has supplied a token such as "ORacle". Continue. */ } } /* See if we are dealing with a quoted phrase. If this is the case, then ** search for the closing quote and pass the whole string to getNextString() ** for processing. This is easy to do, as fts3 has no syntax for escaping ** a quote character embedded in a string. */ if( *zInput=='"' ){ for(ii=1; iinNest++; rc = fts3ExprParse(pParse, zInput+1, nInput-1, ppExpr, &nConsumed); if( rc==SQLITE_OK && !*ppExpr ){ rc = SQLITE_DONE; } *pnConsumed = (int)(zInput - z) + 1 + nConsumed; return rc; }else if( *zInput==')' ){ pParse->nNest--; *pnConsumed = (int)((zInput - z) + 1); *ppExpr = 0; return SQLITE_DONE; } } /* If control flows to this point, this must be a regular token, or ** the end of the input. Read a regular token using the sqlite3_tokenizer ** interface. Before doing so, figure out if there is an explicit ** column specifier for the token. ** ** TODO: Strangely, it is not possible to associate a column specifier ** with a quoted phrase, only with a single token. Not sure if this was ** an implementation artifact or an intentional decision when fts3 was ** first implemented. Whichever it was, this module duplicates the ** limitation. */ iCol = pParse->iDefaultCol; iColLen = 0; for(ii=0; iinCol; ii++){ const char *zStr = pParse->azCol[ii]; int nStr = (int)strlen(zStr); if( nInput>nStr && zInput[nStr]==':' && sqlite3_strnicmp(zStr, zInput, nStr)==0 ){ iCol = ii; iColLen = (int)((zInput - z) + nStr + 1); break; } } rc = getNextToken(pParse, iCol, &z[iColLen], n-iColLen, ppExpr, pnConsumed); *pnConsumed += iColLen; return rc; } /* ** The argument is an Fts3Expr structure for a binary operator (any type ** except an FTSQUERY_PHRASE). Return an integer value representing the ** precedence of the operator. Lower values have a higher precedence (i.e. ** group more tightly). For example, in the C language, the == operator ** groups more tightly than ||, and would therefore have a higher precedence. ** ** When using the new fts3 query syntax (when SQLITE_ENABLE_FTS3_PARENTHESIS ** is defined), the order of the operators in precedence from highest to ** lowest is: ** ** NEAR ** NOT ** AND (including implicit ANDs) ** OR ** ** Note that when using the old query syntax, the OR operator has a higher ** precedence than the AND operator. */ static int opPrecedence(Fts3Expr *p){ assert( p->eType!=FTSQUERY_PHRASE ); if( sqlite3_fts3_enable_parentheses ){ return p->eType; }else if( p->eType==FTSQUERY_NEAR ){ return 1; }else if( p->eType==FTSQUERY_OR ){ return 2; } assert( p->eType==FTSQUERY_AND ); return 3; } /* ** Argument ppHead contains a pointer to the current head of a query ** expression tree being parsed. pPrev is the expression node most recently ** inserted into the tree. This function adds pNew, which is always a binary ** operator node, into the expression tree based on the relative precedence ** of pNew and the existing nodes of the tree. This may result in the head ** of the tree changing, in which case *ppHead is set to the new root node. */ static void insertBinaryOperator( Fts3Expr **ppHead, /* Pointer to the root node of a tree */ Fts3Expr *pPrev, /* Node most recently inserted into the tree */ Fts3Expr *pNew /* New binary node to insert into expression tree */ ){ Fts3Expr *pSplit = pPrev; while( pSplit->pParent && opPrecedence(pSplit->pParent)<=opPrecedence(pNew) ){ pSplit = pSplit->pParent; } if( pSplit->pParent ){ assert( pSplit->pParent->pRight==pSplit ); pSplit->pParent->pRight = pNew; pNew->pParent = pSplit->pParent; }else{ *ppHead = pNew; } pNew->pLeft = pSplit; pSplit->pParent = pNew; } /* ** Parse the fts3 query expression found in buffer z, length n. This function ** returns either when the end of the buffer is reached or an unmatched ** closing bracket - ')' - is encountered. ** ** If successful, SQLITE_OK is returned, *ppExpr is set to point to the ** parsed form of the expression and *pnConsumed is set to the number of ** bytes read from buffer z. Otherwise, *ppExpr is set to 0 and SQLITE_NOMEM ** (out of memory error) or SQLITE_ERROR (parse error) is returned. */ static int fts3ExprParse( ParseContext *pParse, /* fts3 query parse context */ const char *z, int n, /* Text of MATCH query */ Fts3Expr **ppExpr, /* OUT: Parsed query structure */ int *pnConsumed /* OUT: Number of bytes consumed */ ){ Fts3Expr *pRet = 0; Fts3Expr *pPrev = 0; Fts3Expr *pNotBranch = 0; /* Only used in legacy parse mode */ int nIn = n; const char *zIn = z; int rc = SQLITE_OK; int isRequirePhrase = 1; while( rc==SQLITE_OK ){ Fts3Expr *p = 0; int nByte = 0; rc = getNextNode(pParse, zIn, nIn, &p, &nByte); assert( nByte>0 || (rc!=SQLITE_OK && p==0) ); if( rc==SQLITE_OK ){ if( p ){ int isPhrase; if( !sqlite3_fts3_enable_parentheses && p->eType==FTSQUERY_PHRASE && pParse->isNot ){ /* Create an implicit NOT operator. */ Fts3Expr *pNot = fts3MallocZero(sizeof(Fts3Expr)); if( !pNot ){ sqlite3Fts3ExprFree(p); rc = SQLITE_NOMEM; goto exprparse_out; } pNot->eType = FTSQUERY_NOT; pNot->pRight = p; p->pParent = pNot; if( pNotBranch ){ pNot->pLeft = pNotBranch; pNotBranch->pParent = pNot; } pNotBranch = pNot; p = pPrev; }else{ int eType = p->eType; isPhrase = (eType==FTSQUERY_PHRASE || p->pLeft); /* The isRequirePhrase variable is set to true if a phrase or ** an expression contained in parenthesis is required. If a ** binary operator (AND, OR, NOT or NEAR) is encounted when ** isRequirePhrase is set, this is a syntax error. */ if( !isPhrase && isRequirePhrase ){ sqlite3Fts3ExprFree(p); rc = SQLITE_ERROR; goto exprparse_out; } if( isPhrase && !isRequirePhrase ){ /* Insert an implicit AND operator. */ Fts3Expr *pAnd; assert( pRet && pPrev ); pAnd = fts3MallocZero(sizeof(Fts3Expr)); if( !pAnd ){ sqlite3Fts3ExprFree(p); rc = SQLITE_NOMEM; goto exprparse_out; } pAnd->eType = FTSQUERY_AND; insertBinaryOperator(&pRet, pPrev, pAnd); pPrev = pAnd; } /* This test catches attempts to make either operand of a NEAR ** operator something other than a phrase. For example, either of ** the following: ** ** (bracketed expression) NEAR phrase ** phrase NEAR (bracketed expression) ** ** Return an error in either case. */ if( pPrev && ( (eType==FTSQUERY_NEAR && !isPhrase && pPrev->eType!=FTSQUERY_PHRASE) || (eType!=FTSQUERY_PHRASE && isPhrase && pPrev->eType==FTSQUERY_NEAR) )){ sqlite3Fts3ExprFree(p); rc = SQLITE_ERROR; goto exprparse_out; } if( isPhrase ){ if( pRet ){ assert( pPrev && pPrev->pLeft && pPrev->pRight==0 ); pPrev->pRight = p; p->pParent = pPrev; }else{ pRet = p; } }else{ insertBinaryOperator(&pRet, pPrev, p); } isRequirePhrase = !isPhrase; } pPrev = p; } assert( nByte>0 ); } assert( rc!=SQLITE_OK || (nByte>0 && nByte<=nIn) ); nIn -= nByte; zIn += nByte; } if( rc==SQLITE_DONE && pRet && isRequirePhrase ){ rc = SQLITE_ERROR; } if( rc==SQLITE_DONE ){ rc = SQLITE_OK; if( !sqlite3_fts3_enable_parentheses && pNotBranch ){ if( !pRet ){ rc = SQLITE_ERROR; }else{ Fts3Expr *pIter = pNotBranch; while( pIter->pLeft ){ pIter = pIter->pLeft; } pIter->pLeft = pRet; pRet->pParent = pIter; pRet = pNotBranch; } } } *pnConsumed = n - nIn; exprparse_out: if( rc!=SQLITE_OK ){ sqlite3Fts3ExprFree(pRet); sqlite3Fts3ExprFree(pNotBranch); pRet = 0; } *ppExpr = pRet; return rc; } /* ** Return SQLITE_ERROR if the maximum depth of the expression tree passed ** as the only argument is more than nMaxDepth. */ static int fts3ExprCheckDepth(Fts3Expr *p, int nMaxDepth){ int rc = SQLITE_OK; if( p ){ if( nMaxDepth<0 ){ rc = SQLITE_TOOBIG; }else{ rc = fts3ExprCheckDepth(p->pLeft, nMaxDepth-1); if( rc==SQLITE_OK ){ rc = fts3ExprCheckDepth(p->pRight, nMaxDepth-1); } } } return rc; } /* ** This function attempts to transform the expression tree at (*pp) to ** an equivalent but more balanced form. The tree is modified in place. ** If successful, SQLITE_OK is returned and (*pp) set to point to the ** new root expression node. ** ** nMaxDepth is the maximum allowable depth of the balanced sub-tree. ** ** Otherwise, if an error occurs, an SQLite error code is returned and ** expression (*pp) freed. */ static int fts3ExprBalance(Fts3Expr **pp, int nMaxDepth){ int rc = SQLITE_OK; /* Return code */ Fts3Expr *pRoot = *pp; /* Initial root node */ Fts3Expr *pFree = 0; /* List of free nodes. Linked by pParent. */ int eType = pRoot->eType; /* Type of node in this tree */ if( nMaxDepth==0 ){ rc = SQLITE_ERROR; } if( rc==SQLITE_OK ){ if( (eType==FTSQUERY_AND || eType==FTSQUERY_OR) ){ Fts3Expr **apLeaf; apLeaf = (Fts3Expr **)sqlite3_malloc(sizeof(Fts3Expr *) * nMaxDepth); if( 0==apLeaf ){ rc = SQLITE_NOMEM; }else{ memset(apLeaf, 0, sizeof(Fts3Expr *) * nMaxDepth); } if( rc==SQLITE_OK ){ int i; Fts3Expr *p; /* Set $p to point to the left-most leaf in the tree of eType nodes. */ for(p=pRoot; p->eType==eType; p=p->pLeft){ assert( p->pParent==0 || p->pParent->pLeft==p ); assert( p->pLeft && p->pRight ); } /* This loop runs once for each leaf in the tree of eType nodes. */ while( 1 ){ int iLvl; Fts3Expr *pParent = p->pParent; /* Current parent of p */ assert( pParent==0 || pParent->pLeft==p ); p->pParent = 0; if( pParent ){ pParent->pLeft = 0; }else{ pRoot = 0; } rc = fts3ExprBalance(&p, nMaxDepth-1); if( rc!=SQLITE_OK ) break; for(iLvl=0; p && iLvlpLeft = apLeaf[iLvl]; pFree->pRight = p; pFree->pLeft->pParent = pFree; pFree->pRight->pParent = pFree; p = pFree; pFree = pFree->pParent; p->pParent = 0; apLeaf[iLvl] = 0; } } if( p ){ sqlite3Fts3ExprFree(p); rc = SQLITE_TOOBIG; break; } /* If that was the last leaf node, break out of the loop */ if( pParent==0 ) break; /* Set $p to point to the next leaf in the tree of eType nodes */ for(p=pParent->pRight; p->eType==eType; p=p->pLeft); /* Remove pParent from the original tree. */ assert( pParent->pParent==0 || pParent->pParent->pLeft==pParent ); pParent->pRight->pParent = pParent->pParent; if( pParent->pParent ){ pParent->pParent->pLeft = pParent->pRight; }else{ assert( pParent==pRoot ); pRoot = pParent->pRight; } /* Link pParent into the free node list. It will be used as an ** internal node of the new tree. */ pParent->pParent = pFree; pFree = pParent; } if( rc==SQLITE_OK ){ p = 0; for(i=0; ipParent = 0; }else{ assert( pFree!=0 ); pFree->pRight = p; pFree->pLeft = apLeaf[i]; pFree->pLeft->pParent = pFree; pFree->pRight->pParent = pFree; p = pFree; pFree = pFree->pParent; p->pParent = 0; } } } pRoot = p; }else{ /* An error occurred. Delete the contents of the apLeaf[] array ** and pFree list. Everything else is cleaned up by the call to ** sqlite3Fts3ExprFree(pRoot) below. */ Fts3Expr *pDel; for(i=0; ipParent; sqlite3_free(pDel); } } assert( pFree==0 ); sqlite3_free( apLeaf ); } }else if( eType==FTSQUERY_NOT ){ Fts3Expr *pLeft = pRoot->pLeft; Fts3Expr *pRight = pRoot->pRight; pRoot->pLeft = 0; pRoot->pRight = 0; pLeft->pParent = 0; pRight->pParent = 0; rc = fts3ExprBalance(&pLeft, nMaxDepth-1); if( rc==SQLITE_OK ){ rc = fts3ExprBalance(&pRight, nMaxDepth-1); } if( rc!=SQLITE_OK ){ sqlite3Fts3ExprFree(pRight); sqlite3Fts3ExprFree(pLeft); }else{ assert( pLeft && pRight ); pRoot->pLeft = pLeft; pLeft->pParent = pRoot; pRoot->pRight = pRight; pRight->pParent = pRoot; } } } if( rc!=SQLITE_OK ){ sqlite3Fts3ExprFree(pRoot); pRoot = 0; } *pp = pRoot; return rc; } /* ** This function is similar to sqlite3Fts3ExprParse(), with the following ** differences: ** ** 1. It does not do expression rebalancing. ** 2. It does not check that the expression does not exceed the ** maximum allowable depth. ** 3. Even if it fails, *ppExpr may still be set to point to an ** expression tree. It should be deleted using sqlite3Fts3ExprFree() ** in this case. */ static int fts3ExprParseUnbalanced( sqlite3_tokenizer *pTokenizer, /* Tokenizer module */ int iLangid, /* Language id for tokenizer */ char **azCol, /* Array of column names for fts3 table */ int bFts4, /* True to allow FTS4-only syntax */ int nCol, /* Number of entries in azCol[] */ int iDefaultCol, /* Default column to query */ const char *z, int n, /* Text of MATCH query */ Fts3Expr **ppExpr /* OUT: Parsed query structure */ ){ int nParsed; int rc; ParseContext sParse; memset(&sParse, 0, sizeof(ParseContext)); sParse.pTokenizer = pTokenizer; sParse.iLangid = iLangid; sParse.azCol = (const char **)azCol; sParse.nCol = nCol; sParse.iDefaultCol = iDefaultCol; sParse.bFts4 = bFts4; if( z==0 ){ *ppExpr = 0; return SQLITE_OK; } if( n<0 ){ n = (int)strlen(z); } rc = fts3ExprParse(&sParse, z, n, ppExpr, &nParsed); assert( rc==SQLITE_OK || *ppExpr==0 ); /* Check for mismatched parenthesis */ if( rc==SQLITE_OK && sParse.nNest ){ rc = SQLITE_ERROR; } return rc; } /* ** Parameters z and n contain a pointer to and length of a buffer containing ** an fts3 query expression, respectively. This function attempts to parse the ** query expression and create a tree of Fts3Expr structures representing the ** parsed expression. If successful, *ppExpr is set to point to the head ** of the parsed expression tree and SQLITE_OK is returned. If an error ** occurs, either SQLITE_NOMEM (out-of-memory error) or SQLITE_ERROR (parse ** error) is returned and *ppExpr is set to 0. ** ** If parameter n is a negative number, then z is assumed to point to a ** nul-terminated string and the length is determined using strlen(). ** ** The first parameter, pTokenizer, is passed the fts3 tokenizer module to ** use to normalize query tokens while parsing the expression. The azCol[] ** array, which is assumed to contain nCol entries, should contain the names ** of each column in the target fts3 table, in order from left to right. ** Column names must be nul-terminated strings. ** ** The iDefaultCol parameter should be passed the index of the table column ** that appears on the left-hand-side of the MATCH operator (the default ** column to match against for tokens for which a column name is not explicitly ** specified as part of the query string), or -1 if tokens may by default ** match any table column. */ SQLITE_PRIVATE int sqlite3Fts3ExprParse( sqlite3_tokenizer *pTokenizer, /* Tokenizer module */ int iLangid, /* Language id for tokenizer */ char **azCol, /* Array of column names for fts3 table */ int bFts4, /* True to allow FTS4-only syntax */ int nCol, /* Number of entries in azCol[] */ int iDefaultCol, /* Default column to query */ const char *z, int n, /* Text of MATCH query */ Fts3Expr **ppExpr, /* OUT: Parsed query structure */ char **pzErr /* OUT: Error message (sqlite3_malloc) */ ){ int rc = fts3ExprParseUnbalanced( pTokenizer, iLangid, azCol, bFts4, nCol, iDefaultCol, z, n, ppExpr ); /* Rebalance the expression. And check that its depth does not exceed ** SQLITE_FTS3_MAX_EXPR_DEPTH. */ if( rc==SQLITE_OK && *ppExpr ){ rc = fts3ExprBalance(ppExpr, SQLITE_FTS3_MAX_EXPR_DEPTH); if( rc==SQLITE_OK ){ rc = fts3ExprCheckDepth(*ppExpr, SQLITE_FTS3_MAX_EXPR_DEPTH); } } if( rc!=SQLITE_OK ){ sqlite3Fts3ExprFree(*ppExpr); *ppExpr = 0; if( rc==SQLITE_TOOBIG ){ sqlite3Fts3ErrMsg(pzErr, "FTS expression tree is too large (maximum depth %d)", SQLITE_FTS3_MAX_EXPR_DEPTH ); rc = SQLITE_ERROR; }else if( rc==SQLITE_ERROR ){ sqlite3Fts3ErrMsg(pzErr, "malformed MATCH expression: [%s]", z); } } return rc; } /* ** Free a single node of an expression tree. */ static void fts3FreeExprNode(Fts3Expr *p){ assert( p->eType==FTSQUERY_PHRASE || p->pPhrase==0 ); sqlite3Fts3EvalPhraseCleanup(p->pPhrase); sqlite3_free(p->aMI); sqlite3_free(p); } /* ** Free a parsed fts3 query expression allocated by sqlite3Fts3ExprParse(). ** ** This function would be simpler if it recursively called itself. But ** that would mean passing a sufficiently large expression to ExprParse() ** could cause a stack overflow. */ SQLITE_PRIVATE void sqlite3Fts3ExprFree(Fts3Expr *pDel){ Fts3Expr *p; assert( pDel==0 || pDel->pParent==0 ); for(p=pDel; p && (p->pLeft||p->pRight); p=(p->pLeft ? p->pLeft : p->pRight)){ assert( p->pParent==0 || p==p->pParent->pRight || p==p->pParent->pLeft ); } while( p ){ Fts3Expr *pParent = p->pParent; fts3FreeExprNode(p); if( pParent && p==pParent->pLeft && pParent->pRight ){ p = pParent->pRight; while( p && (p->pLeft || p->pRight) ){ assert( p==p->pParent->pRight || p==p->pParent->pLeft ); p = (p->pLeft ? p->pLeft : p->pRight); } }else{ p = pParent; } } } /**************************************************************************** ***************************************************************************** ** Everything after this point is just test code. */ #ifdef SQLITE_TEST /* #include */ /* ** Function to query the hash-table of tokenizers (see README.tokenizers). */ static int queryTestTokenizer( sqlite3 *db, const char *zName, const sqlite3_tokenizer_module **pp ){ int rc; sqlite3_stmt *pStmt; const char zSql[] = "SELECT fts3_tokenizer(?)"; *pp = 0; rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0); if( rc!=SQLITE_OK ){ return rc; } sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC); if( SQLITE_ROW==sqlite3_step(pStmt) ){ if( sqlite3_column_type(pStmt, 0)==SQLITE_BLOB ){ memcpy((void *)pp, sqlite3_column_blob(pStmt, 0), sizeof(*pp)); } } return sqlite3_finalize(pStmt); } /* ** Return a pointer to a buffer containing a text representation of the ** expression passed as the first argument. The buffer is obtained from ** sqlite3_malloc(). It is the responsibility of the caller to use ** sqlite3_free() to release the memory. If an OOM condition is encountered, ** NULL is returned. ** ** If the second argument is not NULL, then its contents are prepended to ** the returned expression text and then freed using sqlite3_free(). */ static char *exprToString(Fts3Expr *pExpr, char *zBuf){ if( pExpr==0 ){ return sqlite3_mprintf(""); } switch( pExpr->eType ){ case FTSQUERY_PHRASE: { Fts3Phrase *pPhrase = pExpr->pPhrase; int i; zBuf = sqlite3_mprintf( "%zPHRASE %d 0", zBuf, pPhrase->iColumn); for(i=0; zBuf && inToken; i++){ zBuf = sqlite3_mprintf("%z %.*s%s", zBuf, pPhrase->aToken[i].n, pPhrase->aToken[i].z, (pPhrase->aToken[i].isPrefix?"+":"") ); } return zBuf; } case FTSQUERY_NEAR: zBuf = sqlite3_mprintf("%zNEAR/%d ", zBuf, pExpr->nNear); break; case FTSQUERY_NOT: zBuf = sqlite3_mprintf("%zNOT ", zBuf); break; case FTSQUERY_AND: zBuf = sqlite3_mprintf("%zAND ", zBuf); break; case FTSQUERY_OR: zBuf = sqlite3_mprintf("%zOR ", zBuf); break; } if( zBuf ) zBuf = sqlite3_mprintf("%z{", zBuf); if( zBuf ) zBuf = exprToString(pExpr->pLeft, zBuf); if( zBuf ) zBuf = sqlite3_mprintf("%z} {", zBuf); if( zBuf ) zBuf = exprToString(pExpr->pRight, zBuf); if( zBuf ) zBuf = sqlite3_mprintf("%z}", zBuf); return zBuf; } /* ** This is the implementation of a scalar SQL function used to test the ** expression parser. It should be called as follows: ** ** fts3_exprtest(, , , ...); ** ** The first argument, , is the name of the fts3 tokenizer used ** to parse the query expression (see README.tokenizers). The second argument ** is the query expression to parse. Each subsequent argument is the name ** of a column of the fts3 table that the query expression may refer to. ** For example: ** ** SELECT fts3_exprtest('simple', 'Bill col2:Bloggs', 'col1', 'col2'); */ static void fts3ExprTest( sqlite3_context *context, int argc, sqlite3_value **argv ){ sqlite3_tokenizer_module const *pModule = 0; sqlite3_tokenizer *pTokenizer = 0; int rc; char **azCol = 0; const char *zExpr; int nExpr; int nCol; int ii; Fts3Expr *pExpr; char *zBuf = 0; sqlite3 *db = sqlite3_context_db_handle(context); if( argc<3 ){ sqlite3_result_error(context, "Usage: fts3_exprtest(tokenizer, expr, col1, ...", -1 ); return; } rc = queryTestTokenizer(db, (const char *)sqlite3_value_text(argv[0]), &pModule); if( rc==SQLITE_NOMEM ){ sqlite3_result_error_nomem(context); goto exprtest_out; }else if( !pModule ){ sqlite3_result_error(context, "No such tokenizer module", -1); goto exprtest_out; } rc = pModule->xCreate(0, 0, &pTokenizer); assert( rc==SQLITE_NOMEM || rc==SQLITE_OK ); if( rc==SQLITE_NOMEM ){ sqlite3_result_error_nomem(context); goto exprtest_out; } pTokenizer->pModule = pModule; zExpr = (const char *)sqlite3_value_text(argv[1]); nExpr = sqlite3_value_bytes(argv[1]); nCol = argc-2; azCol = (char **)sqlite3_malloc(nCol*sizeof(char *)); if( !azCol ){ sqlite3_result_error_nomem(context); goto exprtest_out; } for(ii=0; iixDestroy(pTokenizer); } sqlite3_free(azCol); } /* ** Register the query expression parser test function fts3_exprtest() ** with database connection db. */ SQLITE_PRIVATE int sqlite3Fts3ExprInitTestInterface(sqlite3* db){ int rc = sqlite3_create_function( db, "fts3_exprtest", -1, SQLITE_UTF8, 0, fts3ExprTest, 0, 0 ); if( rc==SQLITE_OK ){ rc = sqlite3_create_function(db, "fts3_exprtest_rebalance", -1, SQLITE_UTF8, (void *)1, fts3ExprTest, 0, 0 ); } return rc; } #endif #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */ /************** End of fts3_expr.c *******************************************/ /************** Begin file fts3_hash.c ***************************************/ /* ** 2001 September 22 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ************************************************************************* ** This is the implementation of generic hash-tables used in SQLite. ** We've modified it slightly to serve as a standalone hash table ** implementation for the full-text indexing module. */ /* ** The code in this file is only compiled if: ** ** * The FTS3 module is being built as an extension ** (in which case SQLITE_CORE is not defined), or ** ** * The FTS3 module is being built into the core of ** SQLite (in which case SQLITE_ENABLE_FTS3 is defined). */ /* #include "fts3Int.h" */ #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) /* #include */ /* #include */ /* #include */ /* #include "fts3_hash.h" */ /* ** Malloc and Free functions */ static void *fts3HashMalloc(int n){ void *p = sqlite3_malloc(n); if( p ){ memset(p, 0, n); } return p; } static void fts3HashFree(void *p){ sqlite3_free(p); } /* Turn bulk memory into a hash table object by initializing the ** fields of the Hash structure. ** ** "pNew" is a pointer to the hash table that is to be initialized. ** keyClass is one of the constants ** FTS3_HASH_BINARY or FTS3_HASH_STRING. The value of keyClass ** determines what kind of key the hash table will use. "copyKey" is ** true if the hash table should make its own private copy of keys and ** false if it should just use the supplied pointer. */ SQLITE_PRIVATE void sqlite3Fts3HashInit(Fts3Hash *pNew, char keyClass, char copyKey){ assert( pNew!=0 ); assert( keyClass>=FTS3_HASH_STRING && keyClass<=FTS3_HASH_BINARY ); pNew->keyClass = keyClass; pNew->copyKey = copyKey; pNew->first = 0; pNew->count = 0; pNew->htsize = 0; pNew->ht = 0; } /* Remove all entries from a hash table. Reclaim all memory. ** Call this routine to delete a hash table or to reset a hash table ** to the empty state. */ SQLITE_PRIVATE void sqlite3Fts3HashClear(Fts3Hash *pH){ Fts3HashElem *elem; /* For looping over all elements of the table */ assert( pH!=0 ); elem = pH->first; pH->first = 0; fts3HashFree(pH->ht); pH->ht = 0; pH->htsize = 0; while( elem ){ Fts3HashElem *next_elem = elem->next; if( pH->copyKey && elem->pKey ){ fts3HashFree(elem->pKey); } fts3HashFree(elem); elem = next_elem; } pH->count = 0; } /* ** Hash and comparison functions when the mode is FTS3_HASH_STRING */ static int fts3StrHash(const void *pKey, int nKey){ const char *z = (const char *)pKey; unsigned h = 0; if( nKey<=0 ) nKey = (int) strlen(z); while( nKey > 0 ){ h = (h<<3) ^ h ^ *z++; nKey--; } return (int)(h & 0x7fffffff); } static int fts3StrCompare(const void *pKey1, int n1, const void *pKey2, int n2){ if( n1!=n2 ) return 1; return strncmp((const char*)pKey1,(const char*)pKey2,n1); } /* ** Hash and comparison functions when the mode is FTS3_HASH_BINARY */ static int fts3BinHash(const void *pKey, int nKey){ int h = 0; const char *z = (const char *)pKey; while( nKey-- > 0 ){ h = (h<<3) ^ h ^ *(z++); } return h & 0x7fffffff; } static int fts3BinCompare(const void *pKey1, int n1, const void *pKey2, int n2){ if( n1!=n2 ) return 1; return memcmp(pKey1,pKey2,n1); } /* ** Return a pointer to the appropriate hash function given the key class. ** ** The C syntax in this function definition may be unfamilar to some ** programmers, so we provide the following additional explanation: ** ** The name of the function is "ftsHashFunction". The function takes a ** single parameter "keyClass". The return value of ftsHashFunction() ** is a pointer to another function. Specifically, the return value ** of ftsHashFunction() is a pointer to a function that takes two parameters ** with types "const void*" and "int" and returns an "int". */ static int (*ftsHashFunction(int keyClass))(const void*,int){ if( keyClass==FTS3_HASH_STRING ){ return &fts3StrHash; }else{ assert( keyClass==FTS3_HASH_BINARY ); return &fts3BinHash; } } /* ** Return a pointer to the appropriate hash function given the key class. ** ** For help in interpreted the obscure C code in the function definition, ** see the header comment on the previous function. */ static int (*ftsCompareFunction(int keyClass))(const void*,int,const void*,int){ if( keyClass==FTS3_HASH_STRING ){ return &fts3StrCompare; }else{ assert( keyClass==FTS3_HASH_BINARY ); return &fts3BinCompare; } } /* Link an element into the hash table */ static void fts3HashInsertElement( Fts3Hash *pH, /* The complete hash table */ struct _fts3ht *pEntry, /* The entry into which pNew is inserted */ Fts3HashElem *pNew /* The element to be inserted */ ){ Fts3HashElem *pHead; /* First element already in pEntry */ pHead = pEntry->chain; if( pHead ){ pNew->next = pHead; pNew->prev = pHead->prev; if( pHead->prev ){ pHead->prev->next = pNew; } else { pH->first = pNew; } pHead->prev = pNew; }else{ pNew->next = pH->first; if( pH->first ){ pH->first->prev = pNew; } pNew->prev = 0; pH->first = pNew; } pEntry->count++; pEntry->chain = pNew; } /* Resize the hash table so that it cantains "new_size" buckets. ** "new_size" must be a power of 2. The hash table might fail ** to resize if sqliteMalloc() fails. ** ** Return non-zero if a memory allocation error occurs. */ static int fts3Rehash(Fts3Hash *pH, int new_size){ struct _fts3ht *new_ht; /* The new hash table */ Fts3HashElem *elem, *next_elem; /* For looping over existing elements */ int (*xHash)(const void*,int); /* The hash function */ assert( (new_size & (new_size-1))==0 ); new_ht = (struct _fts3ht *)fts3HashMalloc( new_size*sizeof(struct _fts3ht) ); if( new_ht==0 ) return 1; fts3HashFree(pH->ht); pH->ht = new_ht; pH->htsize = new_size; xHash = ftsHashFunction(pH->keyClass); for(elem=pH->first, pH->first=0; elem; elem = next_elem){ int h = (*xHash)(elem->pKey, elem->nKey) & (new_size-1); next_elem = elem->next; fts3HashInsertElement(pH, &new_ht[h], elem); } return 0; } /* This function (for internal use only) locates an element in an ** hash table that matches the given key. The hash for this key has ** already been computed and is passed as the 4th parameter. */ static Fts3HashElem *fts3FindElementByHash( const Fts3Hash *pH, /* The pH to be searched */ const void *pKey, /* The key we are searching for */ int nKey, int h /* The hash for this key. */ ){ Fts3HashElem *elem; /* Used to loop thru the element list */ int count; /* Number of elements left to test */ int (*xCompare)(const void*,int,const void*,int); /* comparison function */ if( pH->ht ){ struct _fts3ht *pEntry = &pH->ht[h]; elem = pEntry->chain; count = pEntry->count; xCompare = ftsCompareFunction(pH->keyClass); while( count-- && elem ){ if( (*xCompare)(elem->pKey,elem->nKey,pKey,nKey)==0 ){ return elem; } elem = elem->next; } } return 0; } /* Remove a single entry from the hash table given a pointer to that ** element and a hash on the element's key. */ static void fts3RemoveElementByHash( Fts3Hash *pH, /* The pH containing "elem" */ Fts3HashElem* elem, /* The element to be removed from the pH */ int h /* Hash value for the element */ ){ struct _fts3ht *pEntry; if( elem->prev ){ elem->prev->next = elem->next; }else{ pH->first = elem->next; } if( elem->next ){ elem->next->prev = elem->prev; } pEntry = &pH->ht[h]; if( pEntry->chain==elem ){ pEntry->chain = elem->next; } pEntry->count--; if( pEntry->count<=0 ){ pEntry->chain = 0; } if( pH->copyKey && elem->pKey ){ fts3HashFree(elem->pKey); } fts3HashFree( elem ); pH->count--; if( pH->count<=0 ){ assert( pH->first==0 ); assert( pH->count==0 ); fts3HashClear(pH); } } SQLITE_PRIVATE Fts3HashElem *sqlite3Fts3HashFindElem( const Fts3Hash *pH, const void *pKey, int nKey ){ int h; /* A hash on key */ int (*xHash)(const void*,int); /* The hash function */ if( pH==0 || pH->ht==0 ) return 0; xHash = ftsHashFunction(pH->keyClass); assert( xHash!=0 ); h = (*xHash)(pKey,nKey); assert( (pH->htsize & (pH->htsize-1))==0 ); return fts3FindElementByHash(pH,pKey,nKey, h & (pH->htsize-1)); } /* ** Attempt to locate an element of the hash table pH with a key ** that matches pKey,nKey. Return the data for this element if it is ** found, or NULL if there is no match. */ SQLITE_PRIVATE void *sqlite3Fts3HashFind(const Fts3Hash *pH, const void *pKey, int nKey){ Fts3HashElem *pElem; /* The element that matches key (if any) */ pElem = sqlite3Fts3HashFindElem(pH, pKey, nKey); return pElem ? pElem->data : 0; } /* Insert an element into the hash table pH. The key is pKey,nKey ** and the data is "data". ** ** If no element exists with a matching key, then a new ** element is created. A copy of the key is made if the copyKey ** flag is set. NULL is returned. ** ** If another element already exists with the same key, then the ** new data replaces the old data and the old data is returned. ** The key is not copied in this instance. If a malloc fails, then ** the new data is returned and the hash table is unchanged. ** ** If the "data" parameter to this function is NULL, then the ** element corresponding to "key" is removed from the hash table. */ SQLITE_PRIVATE void *sqlite3Fts3HashInsert( Fts3Hash *pH, /* The hash table to insert into */ const void *pKey, /* The key */ int nKey, /* Number of bytes in the key */ void *data /* The data */ ){ int hraw; /* Raw hash value of the key */ int h; /* the hash of the key modulo hash table size */ Fts3HashElem *elem; /* Used to loop thru the element list */ Fts3HashElem *new_elem; /* New element added to the pH */ int (*xHash)(const void*,int); /* The hash function */ assert( pH!=0 ); xHash = ftsHashFunction(pH->keyClass); assert( xHash!=0 ); hraw = (*xHash)(pKey, nKey); assert( (pH->htsize & (pH->htsize-1))==0 ); h = hraw & (pH->htsize-1); elem = fts3FindElementByHash(pH,pKey,nKey,h); if( elem ){ void *old_data = elem->data; if( data==0 ){ fts3RemoveElementByHash(pH,elem,h); }else{ elem->data = data; } return old_data; } if( data==0 ) return 0; if( (pH->htsize==0 && fts3Rehash(pH,8)) || (pH->count>=pH->htsize && fts3Rehash(pH, pH->htsize*2)) ){ pH->count = 0; return data; } assert( pH->htsize>0 ); new_elem = (Fts3HashElem*)fts3HashMalloc( sizeof(Fts3HashElem) ); if( new_elem==0 ) return data; if( pH->copyKey && pKey!=0 ){ new_elem->pKey = fts3HashMalloc( nKey ); if( new_elem->pKey==0 ){ fts3HashFree(new_elem); return data; } memcpy((void*)new_elem->pKey, pKey, nKey); }else{ new_elem->pKey = (void*)pKey; } new_elem->nKey = nKey; pH->count++; assert( pH->htsize>0 ); assert( (pH->htsize & (pH->htsize-1))==0 ); h = hraw & (pH->htsize-1); fts3HashInsertElement(pH, &pH->ht[h], new_elem); new_elem->data = data; return 0; } #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */ /************** End of fts3_hash.c *******************************************/ /************** Begin file fts3_porter.c *************************************/ /* ** 2006 September 30 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ************************************************************************* ** Implementation of the full-text-search tokenizer that implements ** a Porter stemmer. */ /* ** The code in this file is only compiled if: ** ** * The FTS3 module is being built as an extension ** (in which case SQLITE_CORE is not defined), or ** ** * The FTS3 module is being built into the core of ** SQLite (in which case SQLITE_ENABLE_FTS3 is defined). */ /* #include "fts3Int.h" */ #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) /* #include */ /* #include */ /* #include */ /* #include */ /* #include "fts3_tokenizer.h" */ /* ** Class derived from sqlite3_tokenizer */ typedef struct porter_tokenizer { sqlite3_tokenizer base; /* Base class */ } porter_tokenizer; /* ** Class derived from sqlite3_tokenizer_cursor */ typedef struct porter_tokenizer_cursor { sqlite3_tokenizer_cursor base; const char *zInput; /* input we are tokenizing */ int nInput; /* size of the input */ int iOffset; /* current position in zInput */ int iToken; /* index of next token to be returned */ char *zToken; /* storage for current token */ int nAllocated; /* space allocated to zToken buffer */ } porter_tokenizer_cursor; /* ** Create a new tokenizer instance. */ static int porterCreate( int argc, const char * const *argv, sqlite3_tokenizer **ppTokenizer ){ porter_tokenizer *t; UNUSED_PARAMETER(argc); UNUSED_PARAMETER(argv); t = (porter_tokenizer *) sqlite3_malloc(sizeof(*t)); if( t==NULL ) return SQLITE_NOMEM; memset(t, 0, sizeof(*t)); *ppTokenizer = &t->base; return SQLITE_OK; } /* ** Destroy a tokenizer */ static int porterDestroy(sqlite3_tokenizer *pTokenizer){ sqlite3_free(pTokenizer); return SQLITE_OK; } /* ** Prepare to begin tokenizing a particular string. The input ** string to be tokenized is zInput[0..nInput-1]. A cursor ** used to incrementally tokenize this string is returned in ** *ppCursor. */ static int porterOpen( sqlite3_tokenizer *pTokenizer, /* The tokenizer */ const char *zInput, int nInput, /* String to be tokenized */ sqlite3_tokenizer_cursor **ppCursor /* OUT: Tokenization cursor */ ){ porter_tokenizer_cursor *c; UNUSED_PARAMETER(pTokenizer); c = (porter_tokenizer_cursor *) sqlite3_malloc(sizeof(*c)); if( c==NULL ) return SQLITE_NOMEM; c->zInput = zInput; if( zInput==0 ){ c->nInput = 0; }else if( nInput<0 ){ c->nInput = (int)strlen(zInput); }else{ c->nInput = nInput; } c->iOffset = 0; /* start tokenizing at the beginning */ c->iToken = 0; c->zToken = NULL; /* no space allocated, yet. */ c->nAllocated = 0; *ppCursor = &c->base; return SQLITE_OK; } /* ** Close a tokenization cursor previously opened by a call to ** porterOpen() above. */ static int porterClose(sqlite3_tokenizer_cursor *pCursor){ porter_tokenizer_cursor *c = (porter_tokenizer_cursor *) pCursor; sqlite3_free(c->zToken); sqlite3_free(c); return SQLITE_OK; } /* ** Vowel or consonant */ static const char cType[] = { 0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0, 1, 1, 1, 2, 1 }; /* ** isConsonant() and isVowel() determine if their first character in ** the string they point to is a consonant or a vowel, according ** to Porter ruls. ** ** A consonate is any letter other than 'a', 'e', 'i', 'o', or 'u'. ** 'Y' is a consonant unless it follows another consonant, ** in which case it is a vowel. ** ** In these routine, the letters are in reverse order. So the 'y' rule ** is that 'y' is a consonant unless it is followed by another ** consonent. */ static int isVowel(const char*); static int isConsonant(const char *z){ int j; char x = *z; if( x==0 ) return 0; assert( x>='a' && x<='z' ); j = cType[x-'a']; if( j<2 ) return j; return z[1]==0 || isVowel(z + 1); } static int isVowel(const char *z){ int j; char x = *z; if( x==0 ) return 0; assert( x>='a' && x<='z' ); j = cType[x-'a']; if( j<2 ) return 1-j; return isConsonant(z + 1); } /* ** Let any sequence of one or more vowels be represented by V and let ** C be sequence of one or more consonants. Then every word can be ** represented as: ** ** [C] (VC){m} [V] ** ** In prose: A word is an optional consonant followed by zero or ** vowel-consonant pairs followed by an optional vowel. "m" is the ** number of vowel consonant pairs. This routine computes the value ** of m for the first i bytes of a word. ** ** Return true if the m-value for z is 1 or more. In other words, ** return true if z contains at least one vowel that is followed ** by a consonant. ** ** In this routine z[] is in reverse order. So we are really looking ** for an instance of a consonant followed by a vowel. */ static int m_gt_0(const char *z){ while( isVowel(z) ){ z++; } if( *z==0 ) return 0; while( isConsonant(z) ){ z++; } return *z!=0; } /* Like mgt0 above except we are looking for a value of m which is ** exactly 1 */ static int m_eq_1(const char *z){ while( isVowel(z) ){ z++; } if( *z==0 ) return 0; while( isConsonant(z) ){ z++; } if( *z==0 ) return 0; while( isVowel(z) ){ z++; } if( *z==0 ) return 1; while( isConsonant(z) ){ z++; } return *z==0; } /* Like mgt0 above except we are looking for a value of m>1 instead ** or m>0 */ static int m_gt_1(const char *z){ while( isVowel(z) ){ z++; } if( *z==0 ) return 0; while( isConsonant(z) ){ z++; } if( *z==0 ) return 0; while( isVowel(z) ){ z++; } if( *z==0 ) return 0; while( isConsonant(z) ){ z++; } return *z!=0; } /* ** Return TRUE if there is a vowel anywhere within z[0..n-1] */ static int hasVowel(const char *z){ while( isConsonant(z) ){ z++; } return *z!=0; } /* ** Return TRUE if the word ends in a double consonant. ** ** The text is reversed here. So we are really looking at ** the first two characters of z[]. */ static int doubleConsonant(const char *z){ return isConsonant(z) && z[0]==z[1]; } /* ** Return TRUE if the word ends with three letters which ** are consonant-vowel-consonent and where the final consonant ** is not 'w', 'x', or 'y'. ** ** The word is reversed here. So we are really checking the ** first three letters and the first one cannot be in [wxy]. */ static int star_oh(const char *z){ return isConsonant(z) && z[0]!='w' && z[0]!='x' && z[0]!='y' && isVowel(z+1) && isConsonant(z+2); } /* ** If the word ends with zFrom and xCond() is true for the stem ** of the word that preceeds the zFrom ending, then change the ** ending to zTo. ** ** The input word *pz and zFrom are both in reverse order. zTo ** is in normal order. ** ** Return TRUE if zFrom matches. Return FALSE if zFrom does not ** match. Not that TRUE is returned even if xCond() fails and ** no substitution occurs. */ static int stem( char **pz, /* The word being stemmed (Reversed) */ const char *zFrom, /* If the ending matches this... (Reversed) */ const char *zTo, /* ... change the ending to this (not reversed) */ int (*xCond)(const char*) /* Condition that must be true */ ){ char *z = *pz; while( *zFrom && *zFrom==*z ){ z++; zFrom++; } if( *zFrom!=0 ) return 0; if( xCond && !xCond(z) ) return 1; while( *zTo ){ *(--z) = *(zTo++); } *pz = z; return 1; } /* ** This is the fallback stemmer used when the porter stemmer is ** inappropriate. The input word is copied into the output with ** US-ASCII case folding. If the input word is too long (more ** than 20 bytes if it contains no digits or more than 6 bytes if ** it contains digits) then word is truncated to 20 or 6 bytes ** by taking 10 or 3 bytes from the beginning and end. */ static void copy_stemmer(const char *zIn, int nIn, char *zOut, int *pnOut){ int i, mx, j; int hasDigit = 0; for(i=0; i='A' && c<='Z' ){ zOut[i] = c - 'A' + 'a'; }else{ if( c>='0' && c<='9' ) hasDigit = 1; zOut[i] = c; } } mx = hasDigit ? 3 : 10; if( nIn>mx*2 ){ for(j=mx, i=nIn-mx; i=(int)sizeof(zReverse)-7 ){ /* The word is too big or too small for the porter stemmer. ** Fallback to the copy stemmer */ copy_stemmer(zIn, nIn, zOut, pnOut); return; } for(i=0, j=sizeof(zReverse)-6; i='A' && c<='Z' ){ zReverse[j] = c + 'a' - 'A'; }else if( c>='a' && c<='z' ){ zReverse[j] = c; }else{ /* The use of a character not in [a-zA-Z] means that we fallback ** to the copy stemmer */ copy_stemmer(zIn, nIn, zOut, pnOut); return; } } memset(&zReverse[sizeof(zReverse)-5], 0, 5); z = &zReverse[j+1]; /* Step 1a */ if( z[0]=='s' ){ if( !stem(&z, "sess", "ss", 0) && !stem(&z, "sei", "i", 0) && !stem(&z, "ss", "ss", 0) ){ z++; } } /* Step 1b */ z2 = z; if( stem(&z, "dee", "ee", m_gt_0) ){ /* Do nothing. The work was all in the test */ }else if( (stem(&z, "gni", "", hasVowel) || stem(&z, "de", "", hasVowel)) && z!=z2 ){ if( stem(&z, "ta", "ate", 0) || stem(&z, "lb", "ble", 0) || stem(&z, "zi", "ize", 0) ){ /* Do nothing. The work was all in the test */ }else if( doubleConsonant(z) && (*z!='l' && *z!='s' && *z!='z') ){ z++; }else if( m_eq_1(z) && star_oh(z) ){ *(--z) = 'e'; } } /* Step 1c */ if( z[0]=='y' && hasVowel(z+1) ){ z[0] = 'i'; } /* Step 2 */ switch( z[1] ){ case 'a': if( !stem(&z, "lanoita", "ate", m_gt_0) ){ stem(&z, "lanoit", "tion", m_gt_0); } break; case 'c': if( !stem(&z, "icne", "ence", m_gt_0) ){ stem(&z, "icna", "ance", m_gt_0); } break; case 'e': stem(&z, "rezi", "ize", m_gt_0); break; case 'g': stem(&z, "igol", "log", m_gt_0); break; case 'l': if( !stem(&z, "ilb", "ble", m_gt_0) && !stem(&z, "illa", "al", m_gt_0) && !stem(&z, "iltne", "ent", m_gt_0) && !stem(&z, "ile", "e", m_gt_0) ){ stem(&z, "ilsuo", "ous", m_gt_0); } break; case 'o': if( !stem(&z, "noitazi", "ize", m_gt_0) && !stem(&z, "noita", "ate", m_gt_0) ){ stem(&z, "rota", "ate", m_gt_0); } break; case 's': if( !stem(&z, "msila", "al", m_gt_0) && !stem(&z, "ssenevi", "ive", m_gt_0) && !stem(&z, "ssenluf", "ful", m_gt_0) ){ stem(&z, "ssensuo", "ous", m_gt_0); } break; case 't': if( !stem(&z, "itila", "al", m_gt_0) && !stem(&z, "itivi", "ive", m_gt_0) ){ stem(&z, "itilib", "ble", m_gt_0); } break; } /* Step 3 */ switch( z[0] ){ case 'e': if( !stem(&z, "etaci", "ic", m_gt_0) && !stem(&z, "evita", "", m_gt_0) ){ stem(&z, "ezila", "al", m_gt_0); } break; case 'i': stem(&z, "itici", "ic", m_gt_0); break; case 'l': if( !stem(&z, "laci", "ic", m_gt_0) ){ stem(&z, "luf", "", m_gt_0); } break; case 's': stem(&z, "ssen", "", m_gt_0); break; } /* Step 4 */ switch( z[1] ){ case 'a': if( z[0]=='l' && m_gt_1(z+2) ){ z += 2; } break; case 'c': if( z[0]=='e' && z[2]=='n' && (z[3]=='a' || z[3]=='e') && m_gt_1(z+4) ){ z += 4; } break; case 'e': if( z[0]=='r' && m_gt_1(z+2) ){ z += 2; } break; case 'i': if( z[0]=='c' && m_gt_1(z+2) ){ z += 2; } break; case 'l': if( z[0]=='e' && z[2]=='b' && (z[3]=='a' || z[3]=='i') && m_gt_1(z+4) ){ z += 4; } break; case 'n': if( z[0]=='t' ){ if( z[2]=='a' ){ if( m_gt_1(z+3) ){ z += 3; } }else if( z[2]=='e' ){ if( !stem(&z, "tneme", "", m_gt_1) && !stem(&z, "tnem", "", m_gt_1) ){ stem(&z, "tne", "", m_gt_1); } } } break; case 'o': if( z[0]=='u' ){ if( m_gt_1(z+2) ){ z += 2; } }else if( z[3]=='s' || z[3]=='t' ){ stem(&z, "noi", "", m_gt_1); } break; case 's': if( z[0]=='m' && z[2]=='i' && m_gt_1(z+3) ){ z += 3; } break; case 't': if( !stem(&z, "eta", "", m_gt_1) ){ stem(&z, "iti", "", m_gt_1); } break; case 'u': if( z[0]=='s' && z[2]=='o' && m_gt_1(z+3) ){ z += 3; } break; case 'v': case 'z': if( z[0]=='e' && z[2]=='i' && m_gt_1(z+3) ){ z += 3; } break; } /* Step 5a */ if( z[0]=='e' ){ if( m_gt_1(z+1) ){ z++; }else if( m_eq_1(z+1) && !star_oh(z+1) ){ z++; } } /* Step 5b */ if( m_gt_1(z) && z[0]=='l' && z[1]=='l' ){ z++; } /* z[] is now the stemmed word in reverse order. Flip it back ** around into forward order and return. */ *pnOut = i = (int)strlen(z); zOut[i] = 0; while( *z ){ zOut[--i] = *(z++); } } /* ** Characters that can be part of a token. We assume any character ** whose value is greater than 0x80 (any UTF character) can be ** part of a token. In other words, delimiters all must have ** values of 0x7f or lower. */ static const char porterIdChar[] = { /* x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xA xB xC xD xE xF */ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, /* 3x */ 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 4x */ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, /* 5x */ 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 6x */ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, /* 7x */ }; #define isDelim(C) (((ch=C)&0x80)==0 && (ch<0x30 || !porterIdChar[ch-0x30])) /* ** Extract the next token from a tokenization cursor. The cursor must ** have been opened by a prior call to porterOpen(). */ static int porterNext( sqlite3_tokenizer_cursor *pCursor, /* Cursor returned by porterOpen */ const char **pzToken, /* OUT: *pzToken is the token text */ int *pnBytes, /* OUT: Number of bytes in token */ int *piStartOffset, /* OUT: Starting offset of token */ int *piEndOffset, /* OUT: Ending offset of token */ int *piPosition /* OUT: Position integer of token */ ){ porter_tokenizer_cursor *c = (porter_tokenizer_cursor *) pCursor; const char *z = c->zInput; while( c->iOffsetnInput ){ int iStartOffset, ch; /* Scan past delimiter characters */ while( c->iOffsetnInput && isDelim(z[c->iOffset]) ){ c->iOffset++; } /* Count non-delimiter characters. */ iStartOffset = c->iOffset; while( c->iOffsetnInput && !isDelim(z[c->iOffset]) ){ c->iOffset++; } if( c->iOffset>iStartOffset ){ int n = c->iOffset-iStartOffset; if( n>c->nAllocated ){ char *pNew; c->nAllocated = n+20; pNew = sqlite3_realloc(c->zToken, c->nAllocated); if( !pNew ) return SQLITE_NOMEM; c->zToken = pNew; } porter_stemmer(&z[iStartOffset], n, c->zToken, pnBytes); *pzToken = c->zToken; *piStartOffset = iStartOffset; *piEndOffset = c->iOffset; *piPosition = c->iToken++; return SQLITE_OK; } } return SQLITE_DONE; } /* ** The set of routines that implement the porter-stemmer tokenizer */ static const sqlite3_tokenizer_module porterTokenizerModule = { 0, porterCreate, porterDestroy, porterOpen, porterClose, porterNext, 0 }; /* ** Allocate a new porter tokenizer. Return a pointer to the new ** tokenizer in *ppModule */ SQLITE_PRIVATE void sqlite3Fts3PorterTokenizerModule( sqlite3_tokenizer_module const**ppModule ){ *ppModule = &porterTokenizerModule; } #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */ /************** End of fts3_porter.c *****************************************/ /************** Begin file fts3_tokenizer.c **********************************/ /* ** 2007 June 22 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ****************************************************************************** ** ** This is part of an SQLite module implementing full-text search. ** This particular file implements the generic tokenizer interface. */ /* ** The code in this file is only compiled if: ** ** * The FTS3 module is being built as an extension ** (in which case SQLITE_CORE is not defined), or ** ** * The FTS3 module is being built into the core of ** SQLite (in which case SQLITE_ENABLE_FTS3 is defined). */ /* #include "fts3Int.h" */ #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) /* #include */ /* #include */ /* ** Return true if the two-argument version of fts3_tokenizer() ** has been activated via a prior call to sqlite3_db_config(db, ** SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER, 1, 0); */ static int fts3TokenizerEnabled(sqlite3_context *context){ sqlite3 *db = sqlite3_context_db_handle(context); int isEnabled = 0; sqlite3_db_config(db,SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER,-1,&isEnabled); return isEnabled; } /* ** Implementation of the SQL scalar function for accessing the underlying ** hash table. This function may be called as follows: ** ** SELECT (); ** SELECT (, ); ** ** where is the name passed as the second argument ** to the sqlite3Fts3InitHashTable() function (e.g. 'fts3_tokenizer'). ** ** If the argument is specified, it must be a blob value ** containing a pointer to be stored as the hash data corresponding ** to the string . If is not specified, then ** the string must already exist in the has table. Otherwise, ** an error is returned. ** ** Whether or not the argument is specified, the value returned ** is a blob containing the pointer stored as the hash data corresponding ** to string (after the hash-table is updated, if applicable). */ static void fts3TokenizerFunc( sqlite3_context *context, int argc, sqlite3_value **argv ){ Fts3Hash *pHash; void *pPtr = 0; const unsigned char *zName; int nName; assert( argc==1 || argc==2 ); pHash = (Fts3Hash *)sqlite3_user_data(context); zName = sqlite3_value_text(argv[0]); nName = sqlite3_value_bytes(argv[0])+1; if( argc==2 ){ if( fts3TokenizerEnabled(context) ){ void *pOld; int n = sqlite3_value_bytes(argv[1]); if( zName==0 || n!=sizeof(pPtr) ){ sqlite3_result_error(context, "argument type mismatch", -1); return; } pPtr = *(void **)sqlite3_value_blob(argv[1]); pOld = sqlite3Fts3HashInsert(pHash, (void *)zName, nName, pPtr); if( pOld==pPtr ){ sqlite3_result_error(context, "out of memory", -1); } }else{ sqlite3_result_error(context, "fts3tokenize disabled", -1); return; } }else{ if( zName ){ pPtr = sqlite3Fts3HashFind(pHash, zName, nName); } if( !pPtr ){ char *zErr = sqlite3_mprintf("unknown tokenizer: %s", zName); sqlite3_result_error(context, zErr, -1); sqlite3_free(zErr); return; } } sqlite3_result_blob(context, (void *)&pPtr, sizeof(pPtr), SQLITE_TRANSIENT); } SQLITE_PRIVATE int sqlite3Fts3IsIdChar(char c){ static const char isFtsIdChar[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0x */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 1x */ 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 2x */ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, /* 3x */ 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 4x */ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, /* 5x */ 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 6x */ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, /* 7x */ }; return (c&0x80 || isFtsIdChar[(int)(c)]); } SQLITE_PRIVATE const char *sqlite3Fts3NextToken(const char *zStr, int *pn){ const char *z1; const char *z2 = 0; /* Find the start of the next token. */ z1 = zStr; while( z2==0 ){ char c = *z1; switch( c ){ case '\0': return 0; /* No more tokens here */ case '\'': case '"': case '`': { z2 = z1; while( *++z2 && (*z2!=c || *++z2==c) ); break; } case '[': z2 = &z1[1]; while( *z2 && z2[0]!=']' ) z2++; if( *z2 ) z2++; break; default: if( sqlite3Fts3IsIdChar(*z1) ){ z2 = &z1[1]; while( sqlite3Fts3IsIdChar(*z2) ) z2++; }else{ z1++; } } } *pn = (int)(z2-z1); return z1; } SQLITE_PRIVATE int sqlite3Fts3InitTokenizer( Fts3Hash *pHash, /* Tokenizer hash table */ const char *zArg, /* Tokenizer name */ sqlite3_tokenizer **ppTok, /* OUT: Tokenizer (if applicable) */ char **pzErr /* OUT: Set to malloced error message */ ){ int rc; char *z = (char *)zArg; int n = 0; char *zCopy; char *zEnd; /* Pointer to nul-term of zCopy */ sqlite3_tokenizer_module *m; zCopy = sqlite3_mprintf("%s", zArg); if( !zCopy ) return SQLITE_NOMEM; zEnd = &zCopy[strlen(zCopy)]; z = (char *)sqlite3Fts3NextToken(zCopy, &n); if( z==0 ){ assert( n==0 ); z = zCopy; } z[n] = '\0'; sqlite3Fts3Dequote(z); m = (sqlite3_tokenizer_module *)sqlite3Fts3HashFind(pHash,z,(int)strlen(z)+1); if( !m ){ sqlite3Fts3ErrMsg(pzErr, "unknown tokenizer: %s", z); rc = SQLITE_ERROR; }else{ char const **aArg = 0; int iArg = 0; z = &z[n+1]; while( zxCreate(iArg, aArg, ppTok); assert( rc!=SQLITE_OK || *ppTok ); if( rc!=SQLITE_OK ){ sqlite3Fts3ErrMsg(pzErr, "unknown tokenizer"); }else{ (*ppTok)->pModule = m; } sqlite3_free((void *)aArg); } sqlite3_free(zCopy); return rc; } #ifdef SQLITE_TEST #if defined(INCLUDE_SQLITE_TCL_H) # include "sqlite_tcl.h" #else # include "tcl.h" #endif /* #include */ /* ** Implementation of a special SQL scalar function for testing tokenizers ** designed to be used in concert with the Tcl testing framework. This ** function must be called with two or more arguments: ** ** SELECT (, ..., ); ** ** where is the name passed as the second argument ** to the sqlite3Fts3InitHashTable() function (e.g. 'fts3_tokenizer') ** concatenated with the string '_test' (e.g. 'fts3_tokenizer_test'). ** ** The return value is a string that may be interpreted as a Tcl ** list. For each token in the , three elements are ** added to the returned list. The first is the token position, the ** second is the token text (folded, stemmed, etc.) and the third is the ** substring of associated with the token. For example, ** using the built-in "simple" tokenizer: ** ** SELECT fts_tokenizer_test('simple', 'I don't see how'); ** ** will return the string: ** ** "{0 i I 1 dont don't 2 see see 3 how how}" ** */ static void testFunc( sqlite3_context *context, int argc, sqlite3_value **argv ){ Fts3Hash *pHash; sqlite3_tokenizer_module *p; sqlite3_tokenizer *pTokenizer = 0; sqlite3_tokenizer_cursor *pCsr = 0; const char *zErr = 0; const char *zName; int nName; const char *zInput; int nInput; const char *azArg[64]; const char *zToken; int nToken = 0; int iStart = 0; int iEnd = 0; int iPos = 0; int i; Tcl_Obj *pRet; if( argc<2 ){ sqlite3_result_error(context, "insufficient arguments", -1); return; } nName = sqlite3_value_bytes(argv[0]); zName = (const char *)sqlite3_value_text(argv[0]); nInput = sqlite3_value_bytes(argv[argc-1]); zInput = (const char *)sqlite3_value_text(argv[argc-1]); pHash = (Fts3Hash *)sqlite3_user_data(context); p = (sqlite3_tokenizer_module *)sqlite3Fts3HashFind(pHash, zName, nName+1); if( !p ){ char *zErr2 = sqlite3_mprintf("unknown tokenizer: %s", zName); sqlite3_result_error(context, zErr2, -1); sqlite3_free(zErr2); return; } pRet = Tcl_NewObj(); Tcl_IncrRefCount(pRet); for(i=1; ixCreate(argc-2, azArg, &pTokenizer) ){ zErr = "error in xCreate()"; goto finish; } pTokenizer->pModule = p; if( sqlite3Fts3OpenTokenizer(pTokenizer, 0, zInput, nInput, &pCsr) ){ zErr = "error in xOpen()"; goto finish; } while( SQLITE_OK==p->xNext(pCsr, &zToken, &nToken, &iStart, &iEnd, &iPos) ){ Tcl_ListObjAppendElement(0, pRet, Tcl_NewIntObj(iPos)); Tcl_ListObjAppendElement(0, pRet, Tcl_NewStringObj(zToken, nToken)); zToken = &zInput[iStart]; nToken = iEnd-iStart; Tcl_ListObjAppendElement(0, pRet, Tcl_NewStringObj(zToken, nToken)); } if( SQLITE_OK!=p->xClose(pCsr) ){ zErr = "error in xClose()"; goto finish; } if( SQLITE_OK!=p->xDestroy(pTokenizer) ){ zErr = "error in xDestroy()"; goto finish; } finish: if( zErr ){ sqlite3_result_error(context, zErr, -1); }else{ sqlite3_result_text(context, Tcl_GetString(pRet), -1, SQLITE_TRANSIENT); } Tcl_DecrRefCount(pRet); } static int registerTokenizer( sqlite3 *db, char *zName, const sqlite3_tokenizer_module *p ){ int rc; sqlite3_stmt *pStmt; const char zSql[] = "SELECT fts3_tokenizer(?, ?)"; rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0); if( rc!=SQLITE_OK ){ return rc; } sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC); sqlite3_bind_blob(pStmt, 2, &p, sizeof(p), SQLITE_STATIC); sqlite3_step(pStmt); return sqlite3_finalize(pStmt); } static int queryTokenizer( sqlite3 *db, char *zName, const sqlite3_tokenizer_module **pp ){ int rc; sqlite3_stmt *pStmt; const char zSql[] = "SELECT fts3_tokenizer(?)"; *pp = 0; rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0); if( rc!=SQLITE_OK ){ return rc; } sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC); if( SQLITE_ROW==sqlite3_step(pStmt) ){ if( sqlite3_column_type(pStmt, 0)==SQLITE_BLOB ){ memcpy((void *)pp, sqlite3_column_blob(pStmt, 0), sizeof(*pp)); } } return sqlite3_finalize(pStmt); } SQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule(sqlite3_tokenizer_module const**ppModule); /* ** Implementation of the scalar function fts3_tokenizer_internal_test(). ** This function is used for testing only, it is not included in the ** build unless SQLITE_TEST is defined. ** ** The purpose of this is to test that the fts3_tokenizer() function ** can be used as designed by the C-code in the queryTokenizer and ** registerTokenizer() functions above. These two functions are repeated ** in the README.tokenizer file as an example, so it is important to ** test them. ** ** To run the tests, evaluate the fts3_tokenizer_internal_test() scalar ** function with no arguments. An assert() will fail if a problem is ** detected. i.e.: ** ** SELECT fts3_tokenizer_internal_test(); ** */ static void intTestFunc( sqlite3_context *context, int argc, sqlite3_value **argv ){ int rc; const sqlite3_tokenizer_module *p1; const sqlite3_tokenizer_module *p2; sqlite3 *db = (sqlite3 *)sqlite3_user_data(context); UNUSED_PARAMETER(argc); UNUSED_PARAMETER(argv); /* Test the query function */ sqlite3Fts3SimpleTokenizerModule(&p1); rc = queryTokenizer(db, "simple", &p2); assert( rc==SQLITE_OK ); assert( p1==p2 ); rc = queryTokenizer(db, "nosuchtokenizer", &p2); assert( rc==SQLITE_ERROR ); assert( p2==0 ); assert( 0==strcmp(sqlite3_errmsg(db), "unknown tokenizer: nosuchtokenizer") ); /* Test the storage function */ if( fts3TokenizerEnabled(context) ){ rc = registerTokenizer(db, "nosuchtokenizer", p1); assert( rc==SQLITE_OK ); rc = queryTokenizer(db, "nosuchtokenizer", &p2); assert( rc==SQLITE_OK ); assert( p2==p1 ); } sqlite3_result_text(context, "ok", -1, SQLITE_STATIC); } #endif /* ** Set up SQL objects in database db used to access the contents of ** the hash table pointed to by argument pHash. The hash table must ** been initialized to use string keys, and to take a private copy ** of the key when a value is inserted. i.e. by a call similar to: ** ** sqlite3Fts3HashInit(pHash, FTS3_HASH_STRING, 1); ** ** This function adds a scalar function (see header comment above ** fts3TokenizerFunc() in this file for details) and, if ENABLE_TABLE is ** defined at compilation time, a temporary virtual table (see header ** comment above struct HashTableVtab) to the database schema. Both ** provide read/write access to the contents of *pHash. ** ** The third argument to this function, zName, is used as the name ** of both the scalar and, if created, the virtual table. */ SQLITE_PRIVATE int sqlite3Fts3InitHashTable( sqlite3 *db, Fts3Hash *pHash, const char *zName ){ int rc = SQLITE_OK; void *p = (void *)pHash; const int any = SQLITE_ANY; #ifdef SQLITE_TEST char *zTest = 0; char *zTest2 = 0; void *pdb = (void *)db; zTest = sqlite3_mprintf("%s_test", zName); zTest2 = sqlite3_mprintf("%s_internal_test", zName); if( !zTest || !zTest2 ){ rc = SQLITE_NOMEM; } #endif if( SQLITE_OK==rc ){ rc = sqlite3_create_function(db, zName, 1, any, p, fts3TokenizerFunc, 0, 0); } if( SQLITE_OK==rc ){ rc = sqlite3_create_function(db, zName, 2, any, p, fts3TokenizerFunc, 0, 0); } #ifdef SQLITE_TEST if( SQLITE_OK==rc ){ rc = sqlite3_create_function(db, zTest, -1, any, p, testFunc, 0, 0); } if( SQLITE_OK==rc ){ rc = sqlite3_create_function(db, zTest2, 0, any, pdb, intTestFunc, 0, 0); } #endif #ifdef SQLITE_TEST sqlite3_free(zTest); sqlite3_free(zTest2); #endif return rc; } #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */ /************** End of fts3_tokenizer.c **************************************/ /************** Begin file fts3_tokenizer1.c *********************************/ /* ** 2006 Oct 10 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ****************************************************************************** ** ** Implementation of the "simple" full-text-search tokenizer. */ /* ** The code in this file is only compiled if: ** ** * The FTS3 module is being built as an extension ** (in which case SQLITE_CORE is not defined), or ** ** * The FTS3 module is being built into the core of ** SQLite (in which case SQLITE_ENABLE_FTS3 is defined). */ /* #include "fts3Int.h" */ #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) /* #include */ /* #include */ /* #include */ /* #include */ /* #include "fts3_tokenizer.h" */ typedef struct simple_tokenizer { sqlite3_tokenizer base; char delim[128]; /* flag ASCII delimiters */ } simple_tokenizer; typedef struct simple_tokenizer_cursor { sqlite3_tokenizer_cursor base; const char *pInput; /* input we are tokenizing */ int nBytes; /* size of the input */ int iOffset; /* current position in pInput */ int iToken; /* index of next token to be returned */ char *pToken; /* storage for current token */ int nTokenAllocated; /* space allocated to zToken buffer */ } simple_tokenizer_cursor; static int simpleDelim(simple_tokenizer *t, unsigned char c){ return c<0x80 && t->delim[c]; } static int fts3_isalnum(int x){ return (x>='0' && x<='9') || (x>='A' && x<='Z') || (x>='a' && x<='z'); } /* ** Create a new tokenizer instance. */ static int simpleCreate( int argc, const char * const *argv, sqlite3_tokenizer **ppTokenizer ){ simple_tokenizer *t; t = (simple_tokenizer *) sqlite3_malloc(sizeof(*t)); if( t==NULL ) return SQLITE_NOMEM; memset(t, 0, sizeof(*t)); /* TODO(shess) Delimiters need to remain the same from run to run, ** else we need to reindex. One solution would be a meta-table to ** track such information in the database, then we'd only want this ** information on the initial create. */ if( argc>1 ){ int i, n = (int)strlen(argv[1]); for(i=0; i=0x80 ){ sqlite3_free(t); return SQLITE_ERROR; } t->delim[ch] = 1; } } else { /* Mark non-alphanumeric ASCII characters as delimiters */ int i; for(i=1; i<0x80; i++){ t->delim[i] = !fts3_isalnum(i) ? -1 : 0; } } *ppTokenizer = &t->base; return SQLITE_OK; } /* ** Destroy a tokenizer */ static int simpleDestroy(sqlite3_tokenizer *pTokenizer){ sqlite3_free(pTokenizer); return SQLITE_OK; } /* ** Prepare to begin tokenizing a particular string. The input ** string to be tokenized is pInput[0..nBytes-1]. A cursor ** used to incrementally tokenize this string is returned in ** *ppCursor. */ static int simpleOpen( sqlite3_tokenizer *pTokenizer, /* The tokenizer */ const char *pInput, int nBytes, /* String to be tokenized */ sqlite3_tokenizer_cursor **ppCursor /* OUT: Tokenization cursor */ ){ simple_tokenizer_cursor *c; UNUSED_PARAMETER(pTokenizer); c = (simple_tokenizer_cursor *) sqlite3_malloc(sizeof(*c)); if( c==NULL ) return SQLITE_NOMEM; c->pInput = pInput; if( pInput==0 ){ c->nBytes = 0; }else if( nBytes<0 ){ c->nBytes = (int)strlen(pInput); }else{ c->nBytes = nBytes; } c->iOffset = 0; /* start tokenizing at the beginning */ c->iToken = 0; c->pToken = NULL; /* no space allocated, yet. */ c->nTokenAllocated = 0; *ppCursor = &c->base; return SQLITE_OK; } /* ** Close a tokenization cursor previously opened by a call to ** simpleOpen() above. */ static int simpleClose(sqlite3_tokenizer_cursor *pCursor){ simple_tokenizer_cursor *c = (simple_tokenizer_cursor *) pCursor; sqlite3_free(c->pToken); sqlite3_free(c); return SQLITE_OK; } /* ** Extract the next token from a tokenization cursor. The cursor must ** have been opened by a prior call to simpleOpen(). */ static int simpleNext( sqlite3_tokenizer_cursor *pCursor, /* Cursor returned by simpleOpen */ const char **ppToken, /* OUT: *ppToken is the token text */ int *pnBytes, /* OUT: Number of bytes in token */ int *piStartOffset, /* OUT: Starting offset of token */ int *piEndOffset, /* OUT: Ending offset of token */ int *piPosition /* OUT: Position integer of token */ ){ simple_tokenizer_cursor *c = (simple_tokenizer_cursor *) pCursor; simple_tokenizer *t = (simple_tokenizer *) pCursor->pTokenizer; unsigned char *p = (unsigned char *)c->pInput; while( c->iOffsetnBytes ){ int iStartOffset; /* Scan past delimiter characters */ while( c->iOffsetnBytes && simpleDelim(t, p[c->iOffset]) ){ c->iOffset++; } /* Count non-delimiter characters. */ iStartOffset = c->iOffset; while( c->iOffsetnBytes && !simpleDelim(t, p[c->iOffset]) ){ c->iOffset++; } if( c->iOffset>iStartOffset ){ int i, n = c->iOffset-iStartOffset; if( n>c->nTokenAllocated ){ char *pNew; c->nTokenAllocated = n+20; pNew = sqlite3_realloc(c->pToken, c->nTokenAllocated); if( !pNew ) return SQLITE_NOMEM; c->pToken = pNew; } for(i=0; ipToken[i] = (char)((ch>='A' && ch<='Z') ? ch-'A'+'a' : ch); } *ppToken = c->pToken; *pnBytes = n; *piStartOffset = iStartOffset; *piEndOffset = c->iOffset; *piPosition = c->iToken++; return SQLITE_OK; } } return SQLITE_DONE; } /* ** The set of routines that implement the simple tokenizer */ static const sqlite3_tokenizer_module simpleTokenizerModule = { 0, simpleCreate, simpleDestroy, simpleOpen, simpleClose, simpleNext, 0, }; /* ** Allocate a new simple tokenizer. Return a pointer to the new ** tokenizer in *ppModule */ SQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule( sqlite3_tokenizer_module const**ppModule ){ *ppModule = &simpleTokenizerModule; } #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */ /************** End of fts3_tokenizer1.c *************************************/ /************** Begin file fts3_tokenize_vtab.c ******************************/ /* ** 2013 Apr 22 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ****************************************************************************** ** ** This file contains code for the "fts3tokenize" virtual table module. ** An fts3tokenize virtual table is created as follows: ** ** CREATE VIRTUAL TABLE USING fts3tokenize( ** , , ... ** ); ** ** The table created has the following schema: ** ** CREATE TABLE (input, token, start, end, position) ** ** When queried, the query must include a WHERE clause of type: ** ** input = ** ** The virtual table module tokenizes this , using the FTS3 ** tokenizer specified by the arguments to the CREATE VIRTUAL TABLE ** statement and returns one row for each token in the result. With ** fields set as follows: ** ** input: Always set to a copy of ** token: A token from the input. ** start: Byte offset of the token within the input . ** end: Byte offset of the byte immediately following the end of the ** token within the input string. ** pos: Token offset of token within input. ** */ /* #include "fts3Int.h" */ #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) /* #include */ /* #include */ typedef struct Fts3tokTable Fts3tokTable; typedef struct Fts3tokCursor Fts3tokCursor; /* ** Virtual table structure. */ struct Fts3tokTable { sqlite3_vtab base; /* Base class used by SQLite core */ const sqlite3_tokenizer_module *pMod; sqlite3_tokenizer *pTok; }; /* ** Virtual table cursor structure. */ struct Fts3tokCursor { sqlite3_vtab_cursor base; /* Base class used by SQLite core */ char *zInput; /* Input string */ sqlite3_tokenizer_cursor *pCsr; /* Cursor to iterate through zInput */ int iRowid; /* Current 'rowid' value */ const char *zToken; /* Current 'token' value */ int nToken; /* Size of zToken in bytes */ int iStart; /* Current 'start' value */ int iEnd; /* Current 'end' value */ int iPos; /* Current 'pos' value */ }; /* ** Query FTS for the tokenizer implementation named zName. */ static int fts3tokQueryTokenizer( Fts3Hash *pHash, const char *zName, const sqlite3_tokenizer_module **pp, char **pzErr ){ sqlite3_tokenizer_module *p; int nName = (int)strlen(zName); p = (sqlite3_tokenizer_module *)sqlite3Fts3HashFind(pHash, zName, nName+1); if( !p ){ sqlite3Fts3ErrMsg(pzErr, "unknown tokenizer: %s", zName); return SQLITE_ERROR; } *pp = p; return SQLITE_OK; } /* ** The second argument, argv[], is an array of pointers to nul-terminated ** strings. This function makes a copy of the array and strings into a ** single block of memory. It then dequotes any of the strings that appear ** to be quoted. ** ** If successful, output parameter *pazDequote is set to point at the ** array of dequoted strings and SQLITE_OK is returned. The caller is ** responsible for eventually calling sqlite3_free() to free the array ** in this case. Or, if an error occurs, an SQLite error code is returned. ** The final value of *pazDequote is undefined in this case. */ static int fts3tokDequoteArray( int argc, /* Number of elements in argv[] */ const char * const *argv, /* Input array */ char ***pazDequote /* Output array */ ){ int rc = SQLITE_OK; /* Return code */ if( argc==0 ){ *pazDequote = 0; }else{ int i; int nByte = 0; char **azDequote; for(i=0; ixCreate((nDequote>1 ? nDequote-1 : 0), azArg, &pTok); } if( rc==SQLITE_OK ){ pTab = (Fts3tokTable *)sqlite3_malloc(sizeof(Fts3tokTable)); if( pTab==0 ){ rc = SQLITE_NOMEM; } } if( rc==SQLITE_OK ){ memset(pTab, 0, sizeof(Fts3tokTable)); pTab->pMod = pMod; pTab->pTok = pTok; *ppVtab = &pTab->base; }else{ if( pTok ){ pMod->xDestroy(pTok); } } sqlite3_free(azDequote); return rc; } /* ** This function does the work for both the xDisconnect and xDestroy methods. ** These tables have no persistent representation of their own, so xDisconnect ** and xDestroy are identical operations. */ static int fts3tokDisconnectMethod(sqlite3_vtab *pVtab){ Fts3tokTable *pTab = (Fts3tokTable *)pVtab; pTab->pMod->xDestroy(pTab->pTok); sqlite3_free(pTab); return SQLITE_OK; } /* ** xBestIndex - Analyze a WHERE and ORDER BY clause. */ static int fts3tokBestIndexMethod( sqlite3_vtab *pVTab, sqlite3_index_info *pInfo ){ int i; UNUSED_PARAMETER(pVTab); for(i=0; inConstraint; i++){ if( pInfo->aConstraint[i].usable && pInfo->aConstraint[i].iColumn==0 && pInfo->aConstraint[i].op==SQLITE_INDEX_CONSTRAINT_EQ ){ pInfo->idxNum = 1; pInfo->aConstraintUsage[i].argvIndex = 1; pInfo->aConstraintUsage[i].omit = 1; pInfo->estimatedCost = 1; return SQLITE_OK; } } pInfo->idxNum = 0; assert( pInfo->estimatedCost>1000000.0 ); return SQLITE_OK; } /* ** xOpen - Open a cursor. */ static int fts3tokOpenMethod(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCsr){ Fts3tokCursor *pCsr; UNUSED_PARAMETER(pVTab); pCsr = (Fts3tokCursor *)sqlite3_malloc(sizeof(Fts3tokCursor)); if( pCsr==0 ){ return SQLITE_NOMEM; } memset(pCsr, 0, sizeof(Fts3tokCursor)); *ppCsr = (sqlite3_vtab_cursor *)pCsr; return SQLITE_OK; } /* ** Reset the tokenizer cursor passed as the only argument. As if it had ** just been returned by fts3tokOpenMethod(). */ static void fts3tokResetCursor(Fts3tokCursor *pCsr){ if( pCsr->pCsr ){ Fts3tokTable *pTab = (Fts3tokTable *)(pCsr->base.pVtab); pTab->pMod->xClose(pCsr->pCsr); pCsr->pCsr = 0; } sqlite3_free(pCsr->zInput); pCsr->zInput = 0; pCsr->zToken = 0; pCsr->nToken = 0; pCsr->iStart = 0; pCsr->iEnd = 0; pCsr->iPos = 0; pCsr->iRowid = 0; } /* ** xClose - Close a cursor. */ static int fts3tokCloseMethod(sqlite3_vtab_cursor *pCursor){ Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor; fts3tokResetCursor(pCsr); sqlite3_free(pCsr); return SQLITE_OK; } /* ** xNext - Advance the cursor to the next row, if any. */ static int fts3tokNextMethod(sqlite3_vtab_cursor *pCursor){ Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor; Fts3tokTable *pTab = (Fts3tokTable *)(pCursor->pVtab); int rc; /* Return code */ pCsr->iRowid++; rc = pTab->pMod->xNext(pCsr->pCsr, &pCsr->zToken, &pCsr->nToken, &pCsr->iStart, &pCsr->iEnd, &pCsr->iPos ); if( rc!=SQLITE_OK ){ fts3tokResetCursor(pCsr); if( rc==SQLITE_DONE ) rc = SQLITE_OK; } return rc; } /* ** xFilter - Initialize a cursor to point at the start of its data. */ static int fts3tokFilterMethod( sqlite3_vtab_cursor *pCursor, /* The cursor used for this query */ int idxNum, /* Strategy index */ const char *idxStr, /* Unused */ int nVal, /* Number of elements in apVal */ sqlite3_value **apVal /* Arguments for the indexing scheme */ ){ int rc = SQLITE_ERROR; Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor; Fts3tokTable *pTab = (Fts3tokTable *)(pCursor->pVtab); UNUSED_PARAMETER(idxStr); UNUSED_PARAMETER(nVal); fts3tokResetCursor(pCsr); if( idxNum==1 ){ const char *zByte = (const char *)sqlite3_value_text(apVal[0]); int nByte = sqlite3_value_bytes(apVal[0]); pCsr->zInput = sqlite3_malloc(nByte+1); if( pCsr->zInput==0 ){ rc = SQLITE_NOMEM; }else{ memcpy(pCsr->zInput, zByte, nByte); pCsr->zInput[nByte] = 0; rc = pTab->pMod->xOpen(pTab->pTok, pCsr->zInput, nByte, &pCsr->pCsr); if( rc==SQLITE_OK ){ pCsr->pCsr->pTokenizer = pTab->pTok; } } } if( rc!=SQLITE_OK ) return rc; return fts3tokNextMethod(pCursor); } /* ** xEof - Return true if the cursor is at EOF, or false otherwise. */ static int fts3tokEofMethod(sqlite3_vtab_cursor *pCursor){ Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor; return (pCsr->zToken==0); } /* ** xColumn - Return a column value. */ static int fts3tokColumnMethod( sqlite3_vtab_cursor *pCursor, /* Cursor to retrieve value from */ sqlite3_context *pCtx, /* Context for sqlite3_result_xxx() calls */ int iCol /* Index of column to read value from */ ){ Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor; /* CREATE TABLE x(input, token, start, end, position) */ switch( iCol ){ case 0: sqlite3_result_text(pCtx, pCsr->zInput, -1, SQLITE_TRANSIENT); break; case 1: sqlite3_result_text(pCtx, pCsr->zToken, pCsr->nToken, SQLITE_TRANSIENT); break; case 2: sqlite3_result_int(pCtx, pCsr->iStart); break; case 3: sqlite3_result_int(pCtx, pCsr->iEnd); break; default: assert( iCol==4 ); sqlite3_result_int(pCtx, pCsr->iPos); break; } return SQLITE_OK; } /* ** xRowid - Return the current rowid for the cursor. */ static int fts3tokRowidMethod( sqlite3_vtab_cursor *pCursor, /* Cursor to retrieve value from */ sqlite_int64 *pRowid /* OUT: Rowid value */ ){ Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor; *pRowid = (sqlite3_int64)pCsr->iRowid; return SQLITE_OK; } /* ** Register the fts3tok module with database connection db. Return SQLITE_OK ** if successful or an error code if sqlite3_create_module() fails. */ SQLITE_PRIVATE int sqlite3Fts3InitTok(sqlite3 *db, Fts3Hash *pHash){ static const sqlite3_module fts3tok_module = { 0, /* iVersion */ fts3tokConnectMethod, /* xCreate */ fts3tokConnectMethod, /* xConnect */ fts3tokBestIndexMethod, /* xBestIndex */ fts3tokDisconnectMethod, /* xDisconnect */ fts3tokDisconnectMethod, /* xDestroy */ fts3tokOpenMethod, /* xOpen */ fts3tokCloseMethod, /* xClose */ fts3tokFilterMethod, /* xFilter */ fts3tokNextMethod, /* xNext */ fts3tokEofMethod, /* xEof */ fts3tokColumnMethod, /* xColumn */ fts3tokRowidMethod, /* xRowid */ 0, /* xUpdate */ 0, /* xBegin */ 0, /* xSync */ 0, /* xCommit */ 0, /* xRollback */ 0, /* xFindFunction */ 0, /* xRename */ 0, /* xSavepoint */ 0, /* xRelease */ 0 /* xRollbackTo */ }; int rc; /* Return code */ rc = sqlite3_create_module(db, "fts3tokenize", &fts3tok_module, (void*)pHash); return rc; } #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */ /************** End of fts3_tokenize_vtab.c **********************************/ /************** Begin file fts3_write.c **************************************/ /* ** 2009 Oct 23 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ****************************************************************************** ** ** This file is part of the SQLite FTS3 extension module. Specifically, ** this file contains code to insert, update and delete rows from FTS3 ** tables. It also contains code to merge FTS3 b-tree segments. Some ** of the sub-routines used to merge segments are also used by the query ** code in fts3.c. */ /* #include "fts3Int.h" */ #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) /* #include */ /* #include */ /* #include */ #define FTS_MAX_APPENDABLE_HEIGHT 16 /* ** When full-text index nodes are loaded from disk, the buffer that they ** are loaded into has the following number of bytes of padding at the end ** of it. i.e. if a full-text index node is 900 bytes in size, then a buffer ** of 920 bytes is allocated for it. ** ** This means that if we have a pointer into a buffer containing node data, ** it is always safe to read up to two varints from it without risking an ** overread, even if the node data is corrupted. */ #define FTS3_NODE_PADDING (FTS3_VARINT_MAX*2) /* ** Under certain circumstances, b-tree nodes (doclists) can be loaded into ** memory incrementally instead of all at once. This can be a big performance ** win (reduced IO and CPU) if SQLite stops calling the virtual table xNext() ** method before retrieving all query results (as may happen, for example, ** if a query has a LIMIT clause). ** ** Incremental loading is used for b-tree nodes FTS3_NODE_CHUNK_THRESHOLD ** bytes and larger. Nodes are loaded in chunks of FTS3_NODE_CHUNKSIZE bytes. ** The code is written so that the hard lower-limit for each of these values ** is 1. Clearly such small values would be inefficient, but can be useful ** for testing purposes. ** ** If this module is built with SQLITE_TEST defined, these constants may ** be overridden at runtime for testing purposes. File fts3_test.c contains ** a Tcl interface to read and write the values. */ #ifdef SQLITE_TEST int test_fts3_node_chunksize = (4*1024); int test_fts3_node_chunk_threshold = (4*1024)*4; # define FTS3_NODE_CHUNKSIZE test_fts3_node_chunksize # define FTS3_NODE_CHUNK_THRESHOLD test_fts3_node_chunk_threshold #else # define FTS3_NODE_CHUNKSIZE (4*1024) # define FTS3_NODE_CHUNK_THRESHOLD (FTS3_NODE_CHUNKSIZE*4) #endif /* ** The two values that may be meaningfully bound to the :1 parameter in ** statements SQL_REPLACE_STAT and SQL_SELECT_STAT. */ #define FTS_STAT_DOCTOTAL 0 #define FTS_STAT_INCRMERGEHINT 1 #define FTS_STAT_AUTOINCRMERGE 2 /* ** If FTS_LOG_MERGES is defined, call sqlite3_log() to report each automatic ** and incremental merge operation that takes place. This is used for ** debugging FTS only, it should not usually be turned on in production ** systems. */ #ifdef FTS3_LOG_MERGES static void fts3LogMerge(int nMerge, sqlite3_int64 iAbsLevel){ sqlite3_log(SQLITE_OK, "%d-way merge from level %d", nMerge, (int)iAbsLevel); } #else #define fts3LogMerge(x, y) #endif typedef struct PendingList PendingList; typedef struct SegmentNode SegmentNode; typedef struct SegmentWriter SegmentWriter; /* ** An instance of the following data structure is used to build doclists ** incrementally. See function fts3PendingListAppend() for details. */ struct PendingList { int nData; char *aData; int nSpace; sqlite3_int64 iLastDocid; sqlite3_int64 iLastCol; sqlite3_int64 iLastPos; }; /* ** Each cursor has a (possibly empty) linked list of the following objects. */ struct Fts3DeferredToken { Fts3PhraseToken *pToken; /* Pointer to corresponding expr token */ int iCol; /* Column token must occur in */ Fts3DeferredToken *pNext; /* Next in list of deferred tokens */ PendingList *pList; /* Doclist is assembled here */ }; /* ** An instance of this structure is used to iterate through the terms on ** a contiguous set of segment b-tree leaf nodes. Although the details of ** this structure are only manipulated by code in this file, opaque handles ** of type Fts3SegReader* are also used by code in fts3.c to iterate through ** terms when querying the full-text index. See functions: ** ** sqlite3Fts3SegReaderNew() ** sqlite3Fts3SegReaderFree() ** sqlite3Fts3SegReaderIterate() ** ** Methods used to manipulate Fts3SegReader structures: ** ** fts3SegReaderNext() ** fts3SegReaderFirstDocid() ** fts3SegReaderNextDocid() */ struct Fts3SegReader { int iIdx; /* Index within level, or 0x7FFFFFFF for PT */ u8 bLookup; /* True for a lookup only */ u8 rootOnly; /* True for a root-only reader */ sqlite3_int64 iStartBlock; /* Rowid of first leaf block to traverse */ sqlite3_int64 iLeafEndBlock; /* Rowid of final leaf block to traverse */ sqlite3_int64 iEndBlock; /* Rowid of final block in segment (or 0) */ sqlite3_int64 iCurrentBlock; /* Current leaf block (or 0) */ char *aNode; /* Pointer to node data (or NULL) */ int nNode; /* Size of buffer at aNode (or 0) */ int nPopulate; /* If >0, bytes of buffer aNode[] loaded */ sqlite3_blob *pBlob; /* If not NULL, blob handle to read node */ Fts3HashElem **ppNextElem; /* Variables set by fts3SegReaderNext(). These may be read directly ** by the caller. They are valid from the time SegmentReaderNew() returns ** until SegmentReaderNext() returns something other than SQLITE_OK ** (i.e. SQLITE_DONE). */ int nTerm; /* Number of bytes in current term */ char *zTerm; /* Pointer to current term */ int nTermAlloc; /* Allocated size of zTerm buffer */ char *aDoclist; /* Pointer to doclist of current entry */ int nDoclist; /* Size of doclist in current entry */ /* The following variables are used by fts3SegReaderNextDocid() to iterate ** through the current doclist (aDoclist/nDoclist). */ char *pOffsetList; int nOffsetList; /* For descending pending seg-readers only */ sqlite3_int64 iDocid; }; #define fts3SegReaderIsPending(p) ((p)->ppNextElem!=0) #define fts3SegReaderIsRootOnly(p) ((p)->rootOnly!=0) /* ** An instance of this structure is used to create a segment b-tree in the ** database. The internal details of this type are only accessed by the ** following functions: ** ** fts3SegWriterAdd() ** fts3SegWriterFlush() ** fts3SegWriterFree() */ struct SegmentWriter { SegmentNode *pTree; /* Pointer to interior tree structure */ sqlite3_int64 iFirst; /* First slot in %_segments written */ sqlite3_int64 iFree; /* Next free slot in %_segments */ char *zTerm; /* Pointer to previous term buffer */ int nTerm; /* Number of bytes in zTerm */ int nMalloc; /* Size of malloc'd buffer at zMalloc */ char *zMalloc; /* Malloc'd space (possibly) used for zTerm */ int nSize; /* Size of allocation at aData */ int nData; /* Bytes of data in aData */ char *aData; /* Pointer to block from malloc() */ i64 nLeafData; /* Number of bytes of leaf data written */ }; /* ** Type SegmentNode is used by the following three functions to create ** the interior part of the segment b+-tree structures (everything except ** the leaf nodes). These functions and type are only ever used by code ** within the fts3SegWriterXXX() family of functions described above. ** ** fts3NodeAddTerm() ** fts3NodeWrite() ** fts3NodeFree() ** ** When a b+tree is written to the database (either as a result of a merge ** or the pending-terms table being flushed), leaves are written into the ** database file as soon as they are completely populated. The interior of ** the tree is assembled in memory and written out only once all leaves have ** been populated and stored. This is Ok, as the b+-tree fanout is usually ** very large, meaning that the interior of the tree consumes relatively ** little memory. */ struct SegmentNode { SegmentNode *pParent; /* Parent node (or NULL for root node) */ SegmentNode *pRight; /* Pointer to right-sibling */ SegmentNode *pLeftmost; /* Pointer to left-most node of this depth */ int nEntry; /* Number of terms written to node so far */ char *zTerm; /* Pointer to previous term buffer */ int nTerm; /* Number of bytes in zTerm */ int nMalloc; /* Size of malloc'd buffer at zMalloc */ char *zMalloc; /* Malloc'd space (possibly) used for zTerm */ int nData; /* Bytes of valid data so far */ char *aData; /* Node data */ }; /* ** Valid values for the second argument to fts3SqlStmt(). */ #define SQL_DELETE_CONTENT 0 #define SQL_IS_EMPTY 1 #define SQL_DELETE_ALL_CONTENT 2 #define SQL_DELETE_ALL_SEGMENTS 3 #define SQL_DELETE_ALL_SEGDIR 4 #define SQL_DELETE_ALL_DOCSIZE 5 #define SQL_DELETE_ALL_STAT 6 #define SQL_SELECT_CONTENT_BY_ROWID 7 #define SQL_NEXT_SEGMENT_INDEX 8 #define SQL_INSERT_SEGMENTS 9 #define SQL_NEXT_SEGMENTS_ID 10 #define SQL_INSERT_SEGDIR 11 #define SQL_SELECT_LEVEL 12 #define SQL_SELECT_LEVEL_RANGE 13 #define SQL_SELECT_LEVEL_COUNT 14 #define SQL_SELECT_SEGDIR_MAX_LEVEL 15 #define SQL_DELETE_SEGDIR_LEVEL 16 #define SQL_DELETE_SEGMENTS_RANGE 17 #define SQL_CONTENT_INSERT 18 #define SQL_DELETE_DOCSIZE 19 #define SQL_REPLACE_DOCSIZE 20 #define SQL_SELECT_DOCSIZE 21 #define SQL_SELECT_STAT 22 #define SQL_REPLACE_STAT 23 #define SQL_SELECT_ALL_PREFIX_LEVEL 24 #define SQL_DELETE_ALL_TERMS_SEGDIR 25 #define SQL_DELETE_SEGDIR_RANGE 26 #define SQL_SELECT_ALL_LANGID 27 #define SQL_FIND_MERGE_LEVEL 28 #define SQL_MAX_LEAF_NODE_ESTIMATE 29 #define SQL_DELETE_SEGDIR_ENTRY 30 #define SQL_SHIFT_SEGDIR_ENTRY 31 #define SQL_SELECT_SEGDIR 32 #define SQL_CHOMP_SEGDIR 33 #define SQL_SEGMENT_IS_APPENDABLE 34 #define SQL_SELECT_INDEXES 35 #define SQL_SELECT_MXLEVEL 36 #define SQL_SELECT_LEVEL_RANGE2 37 #define SQL_UPDATE_LEVEL_IDX 38 #define SQL_UPDATE_LEVEL 39 /* ** This function is used to obtain an SQLite prepared statement handle ** for the statement identified by the second argument. If successful, ** *pp is set to the requested statement handle and SQLITE_OK returned. ** Otherwise, an SQLite error code is returned and *pp is set to 0. ** ** If argument apVal is not NULL, then it must point to an array with ** at least as many entries as the requested statement has bound ** parameters. The values are bound to the statements parameters before ** returning. */ static int fts3SqlStmt( Fts3Table *p, /* Virtual table handle */ int eStmt, /* One of the SQL_XXX constants above */ sqlite3_stmt **pp, /* OUT: Statement handle */ sqlite3_value **apVal /* Values to bind to statement */ ){ const char *azSql[] = { /* 0 */ "DELETE FROM %Q.'%q_content' WHERE rowid = ?", /* 1 */ "SELECT NOT EXISTS(SELECT docid FROM %Q.'%q_content' WHERE rowid!=?)", /* 2 */ "DELETE FROM %Q.'%q_content'", /* 3 */ "DELETE FROM %Q.'%q_segments'", /* 4 */ "DELETE FROM %Q.'%q_segdir'", /* 5 */ "DELETE FROM %Q.'%q_docsize'", /* 6 */ "DELETE FROM %Q.'%q_stat'", /* 7 */ "SELECT %s WHERE rowid=?", /* 8 */ "SELECT (SELECT max(idx) FROM %Q.'%q_segdir' WHERE level = ?) + 1", /* 9 */ "REPLACE INTO %Q.'%q_segments'(blockid, block) VALUES(?, ?)", /* 10 */ "SELECT coalesce((SELECT max(blockid) FROM %Q.'%q_segments') + 1, 1)", /* 11 */ "REPLACE INTO %Q.'%q_segdir' VALUES(?,?,?,?,?,?)", /* Return segments in order from oldest to newest.*/ /* 12 */ "SELECT idx, start_block, leaves_end_block, end_block, root " "FROM %Q.'%q_segdir' WHERE level = ? ORDER BY idx ASC", /* 13 */ "SELECT idx, start_block, leaves_end_block, end_block, root " "FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?" "ORDER BY level DESC, idx ASC", /* 14 */ "SELECT count(*) FROM %Q.'%q_segdir' WHERE level = ?", /* 15 */ "SELECT max(level) FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?", /* 16 */ "DELETE FROM %Q.'%q_segdir' WHERE level = ?", /* 17 */ "DELETE FROM %Q.'%q_segments' WHERE blockid BETWEEN ? AND ?", /* 18 */ "INSERT INTO %Q.'%q_content' VALUES(%s)", /* 19 */ "DELETE FROM %Q.'%q_docsize' WHERE docid = ?", /* 20 */ "REPLACE INTO %Q.'%q_docsize' VALUES(?,?)", /* 21 */ "SELECT size FROM %Q.'%q_docsize' WHERE docid=?", /* 22 */ "SELECT value FROM %Q.'%q_stat' WHERE id=?", /* 23 */ "REPLACE INTO %Q.'%q_stat' VALUES(?,?)", /* 24 */ "", /* 25 */ "", /* 26 */ "DELETE FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?", /* 27 */ "SELECT ? UNION SELECT level / (1024 * ?) FROM %Q.'%q_segdir'", /* This statement is used to determine which level to read the input from ** when performing an incremental merge. It returns the absolute level number ** of the oldest level in the db that contains at least ? segments. Or, ** if no level in the FTS index contains more than ? segments, the statement ** returns zero rows. */ /* 28 */ "SELECT level, count(*) AS cnt FROM %Q.'%q_segdir' " " GROUP BY level HAVING cnt>=?" " ORDER BY (level %% 1024) ASC LIMIT 1", /* Estimate the upper limit on the number of leaf nodes in a new segment ** created by merging the oldest :2 segments from absolute level :1. See ** function sqlite3Fts3Incrmerge() for details. */ /* 29 */ "SELECT 2 * total(1 + leaves_end_block - start_block) " " FROM %Q.'%q_segdir' WHERE level = ? AND idx < ?", /* SQL_DELETE_SEGDIR_ENTRY ** Delete the %_segdir entry on absolute level :1 with index :2. */ /* 30 */ "DELETE FROM %Q.'%q_segdir' WHERE level = ? AND idx = ?", /* SQL_SHIFT_SEGDIR_ENTRY ** Modify the idx value for the segment with idx=:3 on absolute level :2 ** to :1. */ /* 31 */ "UPDATE %Q.'%q_segdir' SET idx = ? WHERE level=? AND idx=?", /* SQL_SELECT_SEGDIR ** Read a single entry from the %_segdir table. The entry from absolute ** level :1 with index value :2. */ /* 32 */ "SELECT idx, start_block, leaves_end_block, end_block, root " "FROM %Q.'%q_segdir' WHERE level = ? AND idx = ?", /* SQL_CHOMP_SEGDIR ** Update the start_block (:1) and root (:2) fields of the %_segdir ** entry located on absolute level :3 with index :4. */ /* 33 */ "UPDATE %Q.'%q_segdir' SET start_block = ?, root = ?" "WHERE level = ? AND idx = ?", /* SQL_SEGMENT_IS_APPENDABLE ** Return a single row if the segment with end_block=? is appendable. Or ** no rows otherwise. */ /* 34 */ "SELECT 1 FROM %Q.'%q_segments' WHERE blockid=? AND block IS NULL", /* SQL_SELECT_INDEXES ** Return the list of valid segment indexes for absolute level ? */ /* 35 */ "SELECT idx FROM %Q.'%q_segdir' WHERE level=? ORDER BY 1 ASC", /* SQL_SELECT_MXLEVEL ** Return the largest relative level in the FTS index or indexes. */ /* 36 */ "SELECT max( level %% 1024 ) FROM %Q.'%q_segdir'", /* Return segments in order from oldest to newest.*/ /* 37 */ "SELECT level, idx, end_block " "FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ? " "ORDER BY level DESC, idx ASC", /* Update statements used while promoting segments */ /* 38 */ "UPDATE OR FAIL %Q.'%q_segdir' SET level=-1,idx=? " "WHERE level=? AND idx=?", /* 39 */ "UPDATE OR FAIL %Q.'%q_segdir' SET level=? WHERE level=-1" }; int rc = SQLITE_OK; sqlite3_stmt *pStmt; assert( SizeofArray(azSql)==SizeofArray(p->aStmt) ); assert( eStmt=0 ); pStmt = p->aStmt[eStmt]; if( !pStmt ){ char *zSql; if( eStmt==SQL_CONTENT_INSERT ){ zSql = sqlite3_mprintf(azSql[eStmt], p->zDb, p->zName, p->zWriteExprlist); }else if( eStmt==SQL_SELECT_CONTENT_BY_ROWID ){ zSql = sqlite3_mprintf(azSql[eStmt], p->zReadExprlist); }else{ zSql = sqlite3_mprintf(azSql[eStmt], p->zDb, p->zName); } if( !zSql ){ rc = SQLITE_NOMEM; }else{ rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, NULL); sqlite3_free(zSql); assert( rc==SQLITE_OK || pStmt==0 ); p->aStmt[eStmt] = pStmt; } } if( apVal ){ int i; int nParam = sqlite3_bind_parameter_count(pStmt); for(i=0; rc==SQLITE_OK && inPendingData==0 ){ sqlite3_stmt *pStmt; rc = fts3SqlStmt(p, SQL_DELETE_SEGDIR_LEVEL, &pStmt, 0); if( rc==SQLITE_OK ){ sqlite3_bind_null(pStmt, 1); sqlite3_step(pStmt); rc = sqlite3_reset(pStmt); } } return rc; } /* ** FTS maintains a separate indexes for each language-id (a 32-bit integer). ** Within each language id, a separate index is maintained to store the ** document terms, and each configured prefix size (configured the FTS ** "prefix=" option). And each index consists of multiple levels ("relative ** levels"). ** ** All three of these values (the language id, the specific index and the ** level within the index) are encoded in 64-bit integer values stored ** in the %_segdir table on disk. This function is used to convert three ** separate component values into the single 64-bit integer value that ** can be used to query the %_segdir table. ** ** Specifically, each language-id/index combination is allocated 1024 ** 64-bit integer level values ("absolute levels"). The main terms index ** for language-id 0 is allocate values 0-1023. The first prefix index ** (if any) for language-id 0 is allocated values 1024-2047. And so on. ** Language 1 indexes are allocated immediately following language 0. ** ** So, for a system with nPrefix prefix indexes configured, the block of ** absolute levels that corresponds to language-id iLangid and index ** iIndex starts at absolute level ((iLangid * (nPrefix+1) + iIndex) * 1024). */ static sqlite3_int64 getAbsoluteLevel( Fts3Table *p, /* FTS3 table handle */ int iLangid, /* Language id */ int iIndex, /* Index in p->aIndex[] */ int iLevel /* Level of segments */ ){ sqlite3_int64 iBase; /* First absolute level for iLangid/iIndex */ assert( iLangid>=0 ); assert( p->nIndex>0 ); assert( iIndex>=0 && iIndexnIndex ); iBase = ((sqlite3_int64)iLangid * p->nIndex + iIndex) * FTS3_SEGDIR_MAXLEVEL; return iBase + iLevel; } /* ** Set *ppStmt to a statement handle that may be used to iterate through ** all rows in the %_segdir table, from oldest to newest. If successful, ** return SQLITE_OK. If an error occurs while preparing the statement, ** return an SQLite error code. ** ** There is only ever one instance of this SQL statement compiled for ** each FTS3 table. ** ** The statement returns the following columns from the %_segdir table: ** ** 0: idx ** 1: start_block ** 2: leaves_end_block ** 3: end_block ** 4: root */ SQLITE_PRIVATE int sqlite3Fts3AllSegdirs( Fts3Table *p, /* FTS3 table */ int iLangid, /* Language being queried */ int iIndex, /* Index for p->aIndex[] */ int iLevel, /* Level to select (relative level) */ sqlite3_stmt **ppStmt /* OUT: Compiled statement */ ){ int rc; sqlite3_stmt *pStmt = 0; assert( iLevel==FTS3_SEGCURSOR_ALL || iLevel>=0 ); assert( iLevel=0 && iIndexnIndex ); if( iLevel<0 ){ /* "SELECT * FROM %_segdir WHERE level BETWEEN ? AND ? ORDER BY ..." */ rc = fts3SqlStmt(p, SQL_SELECT_LEVEL_RANGE, &pStmt, 0); if( rc==SQLITE_OK ){ sqlite3_bind_int64(pStmt, 1, getAbsoluteLevel(p, iLangid, iIndex, 0)); sqlite3_bind_int64(pStmt, 2, getAbsoluteLevel(p, iLangid, iIndex, FTS3_SEGDIR_MAXLEVEL-1) ); } }else{ /* "SELECT * FROM %_segdir WHERE level = ? ORDER BY ..." */ rc = fts3SqlStmt(p, SQL_SELECT_LEVEL, &pStmt, 0); if( rc==SQLITE_OK ){ sqlite3_bind_int64(pStmt, 1, getAbsoluteLevel(p, iLangid, iIndex,iLevel)); } } *ppStmt = pStmt; return rc; } /* ** Append a single varint to a PendingList buffer. SQLITE_OK is returned ** if successful, or an SQLite error code otherwise. ** ** This function also serves to allocate the PendingList structure itself. ** For example, to create a new PendingList structure containing two ** varints: ** ** PendingList *p = 0; ** fts3PendingListAppendVarint(&p, 1); ** fts3PendingListAppendVarint(&p, 2); */ static int fts3PendingListAppendVarint( PendingList **pp, /* IN/OUT: Pointer to PendingList struct */ sqlite3_int64 i /* Value to append to data */ ){ PendingList *p = *pp; /* Allocate or grow the PendingList as required. */ if( !p ){ p = sqlite3_malloc(sizeof(*p) + 100); if( !p ){ return SQLITE_NOMEM; } p->nSpace = 100; p->aData = (char *)&p[1]; p->nData = 0; } else if( p->nData+FTS3_VARINT_MAX+1>p->nSpace ){ int nNew = p->nSpace * 2; p = sqlite3_realloc(p, sizeof(*p) + nNew); if( !p ){ sqlite3_free(*pp); *pp = 0; return SQLITE_NOMEM; } p->nSpace = nNew; p->aData = (char *)&p[1]; } /* Append the new serialized varint to the end of the list. */ p->nData += sqlite3Fts3PutVarint(&p->aData[p->nData], i); p->aData[p->nData] = '\0'; *pp = p; return SQLITE_OK; } /* ** Add a docid/column/position entry to a PendingList structure. Non-zero ** is returned if the structure is sqlite3_realloced as part of adding ** the entry. Otherwise, zero. ** ** If an OOM error occurs, *pRc is set to SQLITE_NOMEM before returning. ** Zero is always returned in this case. Otherwise, if no OOM error occurs, ** it is set to SQLITE_OK. */ static int fts3PendingListAppend( PendingList **pp, /* IN/OUT: PendingList structure */ sqlite3_int64 iDocid, /* Docid for entry to add */ sqlite3_int64 iCol, /* Column for entry to add */ sqlite3_int64 iPos, /* Position of term for entry to add */ int *pRc /* OUT: Return code */ ){ PendingList *p = *pp; int rc = SQLITE_OK; assert( !p || p->iLastDocid<=iDocid ); if( !p || p->iLastDocid!=iDocid ){ sqlite3_int64 iDelta = iDocid - (p ? p->iLastDocid : 0); if( p ){ assert( p->nDatanSpace ); assert( p->aData[p->nData]==0 ); p->nData++; } if( SQLITE_OK!=(rc = fts3PendingListAppendVarint(&p, iDelta)) ){ goto pendinglistappend_out; } p->iLastCol = -1; p->iLastPos = 0; p->iLastDocid = iDocid; } if( iCol>0 && p->iLastCol!=iCol ){ if( SQLITE_OK!=(rc = fts3PendingListAppendVarint(&p, 1)) || SQLITE_OK!=(rc = fts3PendingListAppendVarint(&p, iCol)) ){ goto pendinglistappend_out; } p->iLastCol = iCol; p->iLastPos = 0; } if( iCol>=0 ){ assert( iPos>p->iLastPos || (iPos==0 && p->iLastPos==0) ); rc = fts3PendingListAppendVarint(&p, 2+iPos-p->iLastPos); if( rc==SQLITE_OK ){ p->iLastPos = iPos; } } pendinglistappend_out: *pRc = rc; if( p!=*pp ){ *pp = p; return 1; } return 0; } /* ** Free a PendingList object allocated by fts3PendingListAppend(). */ static void fts3PendingListDelete(PendingList *pList){ sqlite3_free(pList); } /* ** Add an entry to one of the pending-terms hash tables. */ static int fts3PendingTermsAddOne( Fts3Table *p, int iCol, int iPos, Fts3Hash *pHash, /* Pending terms hash table to add entry to */ const char *zToken, int nToken ){ PendingList *pList; int rc = SQLITE_OK; pList = (PendingList *)fts3HashFind(pHash, zToken, nToken); if( pList ){ p->nPendingData -= (pList->nData + nToken + sizeof(Fts3HashElem)); } if( fts3PendingListAppend(&pList, p->iPrevDocid, iCol, iPos, &rc) ){ if( pList==fts3HashInsert(pHash, zToken, nToken, pList) ){ /* Malloc failed while inserting the new entry. This can only ** happen if there was no previous entry for this token. */ assert( 0==fts3HashFind(pHash, zToken, nToken) ); sqlite3_free(pList); rc = SQLITE_NOMEM; } } if( rc==SQLITE_OK ){ p->nPendingData += (pList->nData + nToken + sizeof(Fts3HashElem)); } return rc; } /* ** Tokenize the nul-terminated string zText and add all tokens to the ** pending-terms hash-table. The docid used is that currently stored in ** p->iPrevDocid, and the column is specified by argument iCol. ** ** If successful, SQLITE_OK is returned. Otherwise, an SQLite error code. */ static int fts3PendingTermsAdd( Fts3Table *p, /* Table into which text will be inserted */ int iLangid, /* Language id to use */ const char *zText, /* Text of document to be inserted */ int iCol, /* Column into which text is being inserted */ u32 *pnWord /* IN/OUT: Incr. by number tokens inserted */ ){ int rc; int iStart = 0; int iEnd = 0; int iPos = 0; int nWord = 0; char const *zToken; int nToken = 0; sqlite3_tokenizer *pTokenizer = p->pTokenizer; sqlite3_tokenizer_module const *pModule = pTokenizer->pModule; sqlite3_tokenizer_cursor *pCsr; int (*xNext)(sqlite3_tokenizer_cursor *pCursor, const char**,int*,int*,int*,int*); assert( pTokenizer && pModule ); /* If the user has inserted a NULL value, this function may be called with ** zText==0. In this case, add zero token entries to the hash table and ** return early. */ if( zText==0 ){ *pnWord = 0; return SQLITE_OK; } rc = sqlite3Fts3OpenTokenizer(pTokenizer, iLangid, zText, -1, &pCsr); if( rc!=SQLITE_OK ){ return rc; } xNext = pModule->xNext; while( SQLITE_OK==rc && SQLITE_OK==(rc = xNext(pCsr, &zToken, &nToken, &iStart, &iEnd, &iPos)) ){ int i; if( iPos>=nWord ) nWord = iPos+1; /* Positions cannot be negative; we use -1 as a terminator internally. ** Tokens must have a non-zero length. */ if( iPos<0 || !zToken || nToken<=0 ){ rc = SQLITE_ERROR; break; } /* Add the term to the terms index */ rc = fts3PendingTermsAddOne( p, iCol, iPos, &p->aIndex[0].hPending, zToken, nToken ); /* Add the term to each of the prefix indexes that it is not too ** short for. */ for(i=1; rc==SQLITE_OK && inIndex; i++){ struct Fts3Index *pIndex = &p->aIndex[i]; if( nTokennPrefix ) continue; rc = fts3PendingTermsAddOne( p, iCol, iPos, &pIndex->hPending, zToken, pIndex->nPrefix ); } } pModule->xClose(pCsr); *pnWord += nWord; return (rc==SQLITE_DONE ? SQLITE_OK : rc); } /* ** Calling this function indicates that subsequent calls to ** fts3PendingTermsAdd() are to add term/position-list pairs for the ** contents of the document with docid iDocid. */ static int fts3PendingTermsDocid( Fts3Table *p, /* Full-text table handle */ int bDelete, /* True if this op is a delete */ int iLangid, /* Language id of row being written */ sqlite_int64 iDocid /* Docid of row being written */ ){ assert( iLangid>=0 ); assert( bDelete==1 || bDelete==0 ); /* TODO(shess) Explore whether partially flushing the buffer on ** forced-flush would provide better performance. I suspect that if ** we ordered the doclists by size and flushed the largest until the ** buffer was half empty, that would let the less frequent terms ** generate longer doclists. */ if( iDocidiPrevDocid || (iDocid==p->iPrevDocid && p->bPrevDelete==0) || p->iPrevLangid!=iLangid || p->nPendingData>p->nMaxPendingData ){ int rc = sqlite3Fts3PendingTermsFlush(p); if( rc!=SQLITE_OK ) return rc; } p->iPrevDocid = iDocid; p->iPrevLangid = iLangid; p->bPrevDelete = bDelete; return SQLITE_OK; } /* ** Discard the contents of the pending-terms hash tables. */ SQLITE_PRIVATE void sqlite3Fts3PendingTermsClear(Fts3Table *p){ int i; for(i=0; inIndex; i++){ Fts3HashElem *pElem; Fts3Hash *pHash = &p->aIndex[i].hPending; for(pElem=fts3HashFirst(pHash); pElem; pElem=fts3HashNext(pElem)){ PendingList *pList = (PendingList *)fts3HashData(pElem); fts3PendingListDelete(pList); } fts3HashClear(pHash); } p->nPendingData = 0; } /* ** This function is called by the xUpdate() method as part of an INSERT ** operation. It adds entries for each term in the new record to the ** pendingTerms hash table. ** ** Argument apVal is the same as the similarly named argument passed to ** fts3InsertData(). Parameter iDocid is the docid of the new row. */ static int fts3InsertTerms( Fts3Table *p, int iLangid, sqlite3_value **apVal, u32 *aSz ){ int i; /* Iterator variable */ for(i=2; inColumn+2; i++){ int iCol = i-2; if( p->abNotindexed[iCol]==0 ){ const char *zText = (const char *)sqlite3_value_text(apVal[i]); int rc = fts3PendingTermsAdd(p, iLangid, zText, iCol, &aSz[iCol]); if( rc!=SQLITE_OK ){ return rc; } aSz[p->nColumn] += sqlite3_value_bytes(apVal[i]); } } return SQLITE_OK; } /* ** This function is called by the xUpdate() method for an INSERT operation. ** The apVal parameter is passed a copy of the apVal argument passed by ** SQLite to the xUpdate() method. i.e: ** ** apVal[0] Not used for INSERT. ** apVal[1] rowid ** apVal[2] Left-most user-defined column ** ... ** apVal[p->nColumn+1] Right-most user-defined column ** apVal[p->nColumn+2] Hidden column with same name as table ** apVal[p->nColumn+3] Hidden "docid" column (alias for rowid) ** apVal[p->nColumn+4] Hidden languageid column */ static int fts3InsertData( Fts3Table *p, /* Full-text table */ sqlite3_value **apVal, /* Array of values to insert */ sqlite3_int64 *piDocid /* OUT: Docid for row just inserted */ ){ int rc; /* Return code */ sqlite3_stmt *pContentInsert; /* INSERT INTO %_content VALUES(...) */ if( p->zContentTbl ){ sqlite3_value *pRowid = apVal[p->nColumn+3]; if( sqlite3_value_type(pRowid)==SQLITE_NULL ){ pRowid = apVal[1]; } if( sqlite3_value_type(pRowid)!=SQLITE_INTEGER ){ return SQLITE_CONSTRAINT; } *piDocid = sqlite3_value_int64(pRowid); return SQLITE_OK; } /* Locate the statement handle used to insert data into the %_content ** table. The SQL for this statement is: ** ** INSERT INTO %_content VALUES(?, ?, ?, ...) ** ** The statement features N '?' variables, where N is the number of user ** defined columns in the FTS3 table, plus one for the docid field. */ rc = fts3SqlStmt(p, SQL_CONTENT_INSERT, &pContentInsert, &apVal[1]); if( rc==SQLITE_OK && p->zLanguageid ){ rc = sqlite3_bind_int( pContentInsert, p->nColumn+2, sqlite3_value_int(apVal[p->nColumn+4]) ); } if( rc!=SQLITE_OK ) return rc; /* There is a quirk here. The users INSERT statement may have specified ** a value for the "rowid" field, for the "docid" field, or for both. ** Which is a problem, since "rowid" and "docid" are aliases for the ** same value. For example: ** ** INSERT INTO fts3tbl(rowid, docid) VALUES(1, 2); ** ** In FTS3, this is an error. It is an error to specify non-NULL values ** for both docid and some other rowid alias. */ if( SQLITE_NULL!=sqlite3_value_type(apVal[3+p->nColumn]) ){ if( SQLITE_NULL==sqlite3_value_type(apVal[0]) && SQLITE_NULL!=sqlite3_value_type(apVal[1]) ){ /* A rowid/docid conflict. */ return SQLITE_ERROR; } rc = sqlite3_bind_value(pContentInsert, 1, apVal[3+p->nColumn]); if( rc!=SQLITE_OK ) return rc; } /* Execute the statement to insert the record. Set *piDocid to the ** new docid value. */ sqlite3_step(pContentInsert); rc = sqlite3_reset(pContentInsert); *piDocid = sqlite3_last_insert_rowid(p->db); return rc; } /* ** Remove all data from the FTS3 table. Clear the hash table containing ** pending terms. */ static int fts3DeleteAll(Fts3Table *p, int bContent){ int rc = SQLITE_OK; /* Return code */ /* Discard the contents of the pending-terms hash table. */ sqlite3Fts3PendingTermsClear(p); /* Delete everything from the shadow tables. Except, leave %_content as ** is if bContent is false. */ assert( p->zContentTbl==0 || bContent==0 ); if( bContent ) fts3SqlExec(&rc, p, SQL_DELETE_ALL_CONTENT, 0); fts3SqlExec(&rc, p, SQL_DELETE_ALL_SEGMENTS, 0); fts3SqlExec(&rc, p, SQL_DELETE_ALL_SEGDIR, 0); if( p->bHasDocsize ){ fts3SqlExec(&rc, p, SQL_DELETE_ALL_DOCSIZE, 0); } if( p->bHasStat ){ fts3SqlExec(&rc, p, SQL_DELETE_ALL_STAT, 0); } return rc; } /* ** */ static int langidFromSelect(Fts3Table *p, sqlite3_stmt *pSelect){ int iLangid = 0; if( p->zLanguageid ) iLangid = sqlite3_column_int(pSelect, p->nColumn+1); return iLangid; } /* ** The first element in the apVal[] array is assumed to contain the docid ** (an integer) of a row about to be deleted. Remove all terms from the ** full-text index. */ static void fts3DeleteTerms( int *pRC, /* Result code */ Fts3Table *p, /* The FTS table to delete from */ sqlite3_value *pRowid, /* The docid to be deleted */ u32 *aSz, /* Sizes of deleted document written here */ int *pbFound /* OUT: Set to true if row really does exist */ ){ int rc; sqlite3_stmt *pSelect; assert( *pbFound==0 ); if( *pRC ) return; rc = fts3SqlStmt(p, SQL_SELECT_CONTENT_BY_ROWID, &pSelect, &pRowid); if( rc==SQLITE_OK ){ if( SQLITE_ROW==sqlite3_step(pSelect) ){ int i; int iLangid = langidFromSelect(p, pSelect); i64 iDocid = sqlite3_column_int64(pSelect, 0); rc = fts3PendingTermsDocid(p, 1, iLangid, iDocid); for(i=1; rc==SQLITE_OK && i<=p->nColumn; i++){ int iCol = i-1; if( p->abNotindexed[iCol]==0 ){ const char *zText = (const char *)sqlite3_column_text(pSelect, i); rc = fts3PendingTermsAdd(p, iLangid, zText, -1, &aSz[iCol]); aSz[p->nColumn] += sqlite3_column_bytes(pSelect, i); } } if( rc!=SQLITE_OK ){ sqlite3_reset(pSelect); *pRC = rc; return; } *pbFound = 1; } rc = sqlite3_reset(pSelect); }else{ sqlite3_reset(pSelect); } *pRC = rc; } /* ** Forward declaration to account for the circular dependency between ** functions fts3SegmentMerge() and fts3AllocateSegdirIdx(). */ static int fts3SegmentMerge(Fts3Table *, int, int, int); /* ** This function allocates a new level iLevel index in the segdir table. ** Usually, indexes are allocated within a level sequentially starting ** with 0, so the allocated index is one greater than the value returned ** by: ** ** SELECT max(idx) FROM %_segdir WHERE level = :iLevel ** ** However, if there are already FTS3_MERGE_COUNT indexes at the requested ** level, they are merged into a single level (iLevel+1) segment and the ** allocated index is 0. ** ** If successful, *piIdx is set to the allocated index slot and SQLITE_OK ** returned. Otherwise, an SQLite error code is returned. */ static int fts3AllocateSegdirIdx( Fts3Table *p, int iLangid, /* Language id */ int iIndex, /* Index for p->aIndex */ int iLevel, int *piIdx ){ int rc; /* Return Code */ sqlite3_stmt *pNextIdx; /* Query for next idx at level iLevel */ int iNext = 0; /* Result of query pNextIdx */ assert( iLangid>=0 ); assert( p->nIndex>=1 ); /* Set variable iNext to the next available segdir index at level iLevel. */ rc = fts3SqlStmt(p, SQL_NEXT_SEGMENT_INDEX, &pNextIdx, 0); if( rc==SQLITE_OK ){ sqlite3_bind_int64( pNextIdx, 1, getAbsoluteLevel(p, iLangid, iIndex, iLevel) ); if( SQLITE_ROW==sqlite3_step(pNextIdx) ){ iNext = sqlite3_column_int(pNextIdx, 0); } rc = sqlite3_reset(pNextIdx); } if( rc==SQLITE_OK ){ /* If iNext is FTS3_MERGE_COUNT, indicating that level iLevel is already ** full, merge all segments in level iLevel into a single iLevel+1 ** segment and allocate (newly freed) index 0 at level iLevel. Otherwise, ** if iNext is less than FTS3_MERGE_COUNT, allocate index iNext. */ if( iNext>=FTS3_MERGE_COUNT ){ fts3LogMerge(16, getAbsoluteLevel(p, iLangid, iIndex, iLevel)); rc = fts3SegmentMerge(p, iLangid, iIndex, iLevel); *piIdx = 0; }else{ *piIdx = iNext; } } return rc; } /* ** The %_segments table is declared as follows: ** ** CREATE TABLE %_segments(blockid INTEGER PRIMARY KEY, block BLOB) ** ** This function reads data from a single row of the %_segments table. The ** specific row is identified by the iBlockid parameter. If paBlob is not ** NULL, then a buffer is allocated using sqlite3_malloc() and populated ** with the contents of the blob stored in the "block" column of the ** identified table row is. Whether or not paBlob is NULL, *pnBlob is set ** to the size of the blob in bytes before returning. ** ** If an error occurs, or the table does not contain the specified row, ** an SQLite error code is returned. Otherwise, SQLITE_OK is returned. If ** paBlob is non-NULL, then it is the responsibility of the caller to ** eventually free the returned buffer. ** ** This function may leave an open sqlite3_blob* handle in the ** Fts3Table.pSegments variable. This handle is reused by subsequent calls ** to this function. The handle may be closed by calling the ** sqlite3Fts3SegmentsClose() function. Reusing a blob handle is a handy ** performance improvement, but the blob handle should always be closed ** before control is returned to the user (to prevent a lock being held ** on the database file for longer than necessary). Thus, any virtual table ** method (xFilter etc.) that may directly or indirectly call this function ** must call sqlite3Fts3SegmentsClose() before returning. */ SQLITE_PRIVATE int sqlite3Fts3ReadBlock( Fts3Table *p, /* FTS3 table handle */ sqlite3_int64 iBlockid, /* Access the row with blockid=$iBlockid */ char **paBlob, /* OUT: Blob data in malloc'd buffer */ int *pnBlob, /* OUT: Size of blob data */ int *pnLoad /* OUT: Bytes actually loaded */ ){ int rc; /* Return code */ /* pnBlob must be non-NULL. paBlob may be NULL or non-NULL. */ assert( pnBlob ); if( p->pSegments ){ rc = sqlite3_blob_reopen(p->pSegments, iBlockid); }else{ if( 0==p->zSegmentsTbl ){ p->zSegmentsTbl = sqlite3_mprintf("%s_segments", p->zName); if( 0==p->zSegmentsTbl ) return SQLITE_NOMEM; } rc = sqlite3_blob_open( p->db, p->zDb, p->zSegmentsTbl, "block", iBlockid, 0, &p->pSegments ); } if( rc==SQLITE_OK ){ int nByte = sqlite3_blob_bytes(p->pSegments); *pnBlob = nByte; if( paBlob ){ char *aByte = sqlite3_malloc(nByte + FTS3_NODE_PADDING); if( !aByte ){ rc = SQLITE_NOMEM; }else{ if( pnLoad && nByte>(FTS3_NODE_CHUNK_THRESHOLD) ){ nByte = FTS3_NODE_CHUNKSIZE; *pnLoad = nByte; } rc = sqlite3_blob_read(p->pSegments, aByte, nByte, 0); memset(&aByte[nByte], 0, FTS3_NODE_PADDING); if( rc!=SQLITE_OK ){ sqlite3_free(aByte); aByte = 0; } } *paBlob = aByte; } } return rc; } /* ** Close the blob handle at p->pSegments, if it is open. See comments above ** the sqlite3Fts3ReadBlock() function for details. */ SQLITE_PRIVATE void sqlite3Fts3SegmentsClose(Fts3Table *p){ sqlite3_blob_close(p->pSegments); p->pSegments = 0; } static int fts3SegReaderIncrRead(Fts3SegReader *pReader){ int nRead; /* Number of bytes to read */ int rc; /* Return code */ nRead = MIN(pReader->nNode - pReader->nPopulate, FTS3_NODE_CHUNKSIZE); rc = sqlite3_blob_read( pReader->pBlob, &pReader->aNode[pReader->nPopulate], nRead, pReader->nPopulate ); if( rc==SQLITE_OK ){ pReader->nPopulate += nRead; memset(&pReader->aNode[pReader->nPopulate], 0, FTS3_NODE_PADDING); if( pReader->nPopulate==pReader->nNode ){ sqlite3_blob_close(pReader->pBlob); pReader->pBlob = 0; pReader->nPopulate = 0; } } return rc; } static int fts3SegReaderRequire(Fts3SegReader *pReader, char *pFrom, int nByte){ int rc = SQLITE_OK; assert( !pReader->pBlob || (pFrom>=pReader->aNode && pFrom<&pReader->aNode[pReader->nNode]) ); while( pReader->pBlob && rc==SQLITE_OK && (pFrom - pReader->aNode + nByte)>pReader->nPopulate ){ rc = fts3SegReaderIncrRead(pReader); } return rc; } /* ** Set an Fts3SegReader cursor to point at EOF. */ static void fts3SegReaderSetEof(Fts3SegReader *pSeg){ if( !fts3SegReaderIsRootOnly(pSeg) ){ sqlite3_free(pSeg->aNode); sqlite3_blob_close(pSeg->pBlob); pSeg->pBlob = 0; } pSeg->aNode = 0; } /* ** Move the iterator passed as the first argument to the next term in the ** segment. If successful, SQLITE_OK is returned. If there is no next term, ** SQLITE_DONE. Otherwise, an SQLite error code. */ static int fts3SegReaderNext( Fts3Table *p, Fts3SegReader *pReader, int bIncr ){ int rc; /* Return code of various sub-routines */ char *pNext; /* Cursor variable */ int nPrefix; /* Number of bytes in term prefix */ int nSuffix; /* Number of bytes in term suffix */ if( !pReader->aDoclist ){ pNext = pReader->aNode; }else{ pNext = &pReader->aDoclist[pReader->nDoclist]; } if( !pNext || pNext>=&pReader->aNode[pReader->nNode] ){ if( fts3SegReaderIsPending(pReader) ){ Fts3HashElem *pElem = *(pReader->ppNextElem); sqlite3_free(pReader->aNode); pReader->aNode = 0; if( pElem ){ char *aCopy; PendingList *pList = (PendingList *)fts3HashData(pElem); int nCopy = pList->nData+1; pReader->zTerm = (char *)fts3HashKey(pElem); pReader->nTerm = fts3HashKeysize(pElem); aCopy = (char*)sqlite3_malloc(nCopy); if( !aCopy ) return SQLITE_NOMEM; memcpy(aCopy, pList->aData, nCopy); pReader->nNode = pReader->nDoclist = nCopy; pReader->aNode = pReader->aDoclist = aCopy; pReader->ppNextElem++; assert( pReader->aNode ); } return SQLITE_OK; } fts3SegReaderSetEof(pReader); /* If iCurrentBlock>=iLeafEndBlock, this is an EOF condition. All leaf ** blocks have already been traversed. */ assert( pReader->iCurrentBlock<=pReader->iLeafEndBlock ); if( pReader->iCurrentBlock>=pReader->iLeafEndBlock ){ return SQLITE_OK; } rc = sqlite3Fts3ReadBlock( p, ++pReader->iCurrentBlock, &pReader->aNode, &pReader->nNode, (bIncr ? &pReader->nPopulate : 0) ); if( rc!=SQLITE_OK ) return rc; assert( pReader->pBlob==0 ); if( bIncr && pReader->nPopulatenNode ){ pReader->pBlob = p->pSegments; p->pSegments = 0; } pNext = pReader->aNode; } assert( !fts3SegReaderIsPending(pReader) ); rc = fts3SegReaderRequire(pReader, pNext, FTS3_VARINT_MAX*2); if( rc!=SQLITE_OK ) return rc; /* Because of the FTS3_NODE_PADDING bytes of padding, the following is ** safe (no risk of overread) even if the node data is corrupted. */ pNext += fts3GetVarint32(pNext, &nPrefix); pNext += fts3GetVarint32(pNext, &nSuffix); if( nPrefix<0 || nSuffix<=0 || &pNext[nSuffix]>&pReader->aNode[pReader->nNode] ){ return FTS_CORRUPT_VTAB; } if( nPrefix+nSuffix>pReader->nTermAlloc ){ int nNew = (nPrefix+nSuffix)*2; char *zNew = sqlite3_realloc(pReader->zTerm, nNew); if( !zNew ){ return SQLITE_NOMEM; } pReader->zTerm = zNew; pReader->nTermAlloc = nNew; } rc = fts3SegReaderRequire(pReader, pNext, nSuffix+FTS3_VARINT_MAX); if( rc!=SQLITE_OK ) return rc; memcpy(&pReader->zTerm[nPrefix], pNext, nSuffix); pReader->nTerm = nPrefix+nSuffix; pNext += nSuffix; pNext += fts3GetVarint32(pNext, &pReader->nDoclist); pReader->aDoclist = pNext; pReader->pOffsetList = 0; /* Check that the doclist does not appear to extend past the end of the ** b-tree node. And that the final byte of the doclist is 0x00. If either ** of these statements is untrue, then the data structure is corrupt. */ if( &pReader->aDoclist[pReader->nDoclist]>&pReader->aNode[pReader->nNode] || (pReader->nPopulate==0 && pReader->aDoclist[pReader->nDoclist-1]) ){ return FTS_CORRUPT_VTAB; } return SQLITE_OK; } /* ** Set the SegReader to point to the first docid in the doclist associated ** with the current term. */ static int fts3SegReaderFirstDocid(Fts3Table *pTab, Fts3SegReader *pReader){ int rc = SQLITE_OK; assert( pReader->aDoclist ); assert( !pReader->pOffsetList ); if( pTab->bDescIdx && fts3SegReaderIsPending(pReader) ){ u8 bEof = 0; pReader->iDocid = 0; pReader->nOffsetList = 0; sqlite3Fts3DoclistPrev(0, pReader->aDoclist, pReader->nDoclist, &pReader->pOffsetList, &pReader->iDocid, &pReader->nOffsetList, &bEof ); }else{ rc = fts3SegReaderRequire(pReader, pReader->aDoclist, FTS3_VARINT_MAX); if( rc==SQLITE_OK ){ int n = sqlite3Fts3GetVarint(pReader->aDoclist, &pReader->iDocid); pReader->pOffsetList = &pReader->aDoclist[n]; } } return rc; } /* ** Advance the SegReader to point to the next docid in the doclist ** associated with the current term. ** ** If arguments ppOffsetList and pnOffsetList are not NULL, then ** *ppOffsetList is set to point to the first column-offset list ** in the doclist entry (i.e. immediately past the docid varint). ** *pnOffsetList is set to the length of the set of column-offset ** lists, not including the nul-terminator byte. For example: */ static int fts3SegReaderNextDocid( Fts3Table *pTab, Fts3SegReader *pReader, /* Reader to advance to next docid */ char **ppOffsetList, /* OUT: Pointer to current position-list */ int *pnOffsetList /* OUT: Length of *ppOffsetList in bytes */ ){ int rc = SQLITE_OK; char *p = pReader->pOffsetList; char c = 0; assert( p ); if( pTab->bDescIdx && fts3SegReaderIsPending(pReader) ){ /* A pending-terms seg-reader for an FTS4 table that uses order=desc. ** Pending-terms doclists are always built up in ascending order, so ** we have to iterate through them backwards here. */ u8 bEof = 0; if( ppOffsetList ){ *ppOffsetList = pReader->pOffsetList; *pnOffsetList = pReader->nOffsetList - 1; } sqlite3Fts3DoclistPrev(0, pReader->aDoclist, pReader->nDoclist, &p, &pReader->iDocid, &pReader->nOffsetList, &bEof ); if( bEof ){ pReader->pOffsetList = 0; }else{ pReader->pOffsetList = p; } }else{ char *pEnd = &pReader->aDoclist[pReader->nDoclist]; /* Pointer p currently points at the first byte of an offset list. The ** following block advances it to point one byte past the end of ** the same offset list. */ while( 1 ){ /* The following line of code (and the "p++" below the while() loop) is ** normally all that is required to move pointer p to the desired ** position. The exception is if this node is being loaded from disk ** incrementally and pointer "p" now points to the first byte past ** the populated part of pReader->aNode[]. */ while( *p | c ) c = *p++ & 0x80; assert( *p==0 ); if( pReader->pBlob==0 || p<&pReader->aNode[pReader->nPopulate] ) break; rc = fts3SegReaderIncrRead(pReader); if( rc!=SQLITE_OK ) return rc; } p++; /* If required, populate the output variables with a pointer to and the ** size of the previous offset-list. */ if( ppOffsetList ){ *ppOffsetList = pReader->pOffsetList; *pnOffsetList = (int)(p - pReader->pOffsetList - 1); } /* List may have been edited in place by fts3EvalNearTrim() */ while( p=pEnd ){ pReader->pOffsetList = 0; }else{ rc = fts3SegReaderRequire(pReader, p, FTS3_VARINT_MAX); if( rc==SQLITE_OK ){ sqlite3_int64 iDelta; pReader->pOffsetList = p + sqlite3Fts3GetVarint(p, &iDelta); if( pTab->bDescIdx ){ pReader->iDocid -= iDelta; }else{ pReader->iDocid += iDelta; } } } } return SQLITE_OK; } SQLITE_PRIVATE int sqlite3Fts3MsrOvfl( Fts3Cursor *pCsr, Fts3MultiSegReader *pMsr, int *pnOvfl ){ Fts3Table *p = (Fts3Table*)pCsr->base.pVtab; int nOvfl = 0; int ii; int rc = SQLITE_OK; int pgsz = p->nPgsz; assert( p->bFts4 ); assert( pgsz>0 ); for(ii=0; rc==SQLITE_OK && iinSegment; ii++){ Fts3SegReader *pReader = pMsr->apSegment[ii]; if( !fts3SegReaderIsPending(pReader) && !fts3SegReaderIsRootOnly(pReader) ){ sqlite3_int64 jj; for(jj=pReader->iStartBlock; jj<=pReader->iLeafEndBlock; jj++){ int nBlob; rc = sqlite3Fts3ReadBlock(p, jj, 0, &nBlob, 0); if( rc!=SQLITE_OK ) break; if( (nBlob+35)>pgsz ){ nOvfl += (nBlob + 34)/pgsz; } } } } *pnOvfl = nOvfl; return rc; } /* ** Free all allocations associated with the iterator passed as the ** second argument. */ SQLITE_PRIVATE void sqlite3Fts3SegReaderFree(Fts3SegReader *pReader){ if( pReader ){ if( !fts3SegReaderIsPending(pReader) ){ sqlite3_free(pReader->zTerm); } if( !fts3SegReaderIsRootOnly(pReader) ){ sqlite3_free(pReader->aNode); } sqlite3_blob_close(pReader->pBlob); } sqlite3_free(pReader); } /* ** Allocate a new SegReader object. */ SQLITE_PRIVATE int sqlite3Fts3SegReaderNew( int iAge, /* Segment "age". */ int bLookup, /* True for a lookup only */ sqlite3_int64 iStartLeaf, /* First leaf to traverse */ sqlite3_int64 iEndLeaf, /* Final leaf to traverse */ sqlite3_int64 iEndBlock, /* Final block of segment */ const char *zRoot, /* Buffer containing root node */ int nRoot, /* Size of buffer containing root node */ Fts3SegReader **ppReader /* OUT: Allocated Fts3SegReader */ ){ Fts3SegReader *pReader; /* Newly allocated SegReader object */ int nExtra = 0; /* Bytes to allocate segment root node */ assert( iStartLeaf<=iEndLeaf ); if( iStartLeaf==0 ){ nExtra = nRoot + FTS3_NODE_PADDING; } pReader = (Fts3SegReader *)sqlite3_malloc(sizeof(Fts3SegReader) + nExtra); if( !pReader ){ return SQLITE_NOMEM; } memset(pReader, 0, sizeof(Fts3SegReader)); pReader->iIdx = iAge; pReader->bLookup = bLookup!=0; pReader->iStartBlock = iStartLeaf; pReader->iLeafEndBlock = iEndLeaf; pReader->iEndBlock = iEndBlock; if( nExtra ){ /* The entire segment is stored in the root node. */ pReader->aNode = (char *)&pReader[1]; pReader->rootOnly = 1; pReader->nNode = nRoot; memcpy(pReader->aNode, zRoot, nRoot); memset(&pReader->aNode[nRoot], 0, FTS3_NODE_PADDING); }else{ pReader->iCurrentBlock = iStartLeaf-1; } *ppReader = pReader; return SQLITE_OK; } /* ** This is a comparison function used as a qsort() callback when sorting ** an array of pending terms by term. This occurs as part of flushing ** the contents of the pending-terms hash table to the database. */ static int SQLITE_CDECL fts3CompareElemByTerm( const void *lhs, const void *rhs ){ char *z1 = fts3HashKey(*(Fts3HashElem **)lhs); char *z2 = fts3HashKey(*(Fts3HashElem **)rhs); int n1 = fts3HashKeysize(*(Fts3HashElem **)lhs); int n2 = fts3HashKeysize(*(Fts3HashElem **)rhs); int n = (n1aIndex */ const char *zTerm, /* Term to search for */ int nTerm, /* Size of buffer zTerm */ int bPrefix, /* True for a prefix iterator */ Fts3SegReader **ppReader /* OUT: SegReader for pending-terms */ ){ Fts3SegReader *pReader = 0; /* Fts3SegReader object to return */ Fts3HashElem *pE; /* Iterator variable */ Fts3HashElem **aElem = 0; /* Array of term hash entries to scan */ int nElem = 0; /* Size of array at aElem */ int rc = SQLITE_OK; /* Return Code */ Fts3Hash *pHash; pHash = &p->aIndex[iIndex].hPending; if( bPrefix ){ int nAlloc = 0; /* Size of allocated array at aElem */ for(pE=fts3HashFirst(pHash); pE; pE=fts3HashNext(pE)){ char *zKey = (char *)fts3HashKey(pE); int nKey = fts3HashKeysize(pE); if( nTerm==0 || (nKey>=nTerm && 0==memcmp(zKey, zTerm, nTerm)) ){ if( nElem==nAlloc ){ Fts3HashElem **aElem2; nAlloc += 16; aElem2 = (Fts3HashElem **)sqlite3_realloc( aElem, nAlloc*sizeof(Fts3HashElem *) ); if( !aElem2 ){ rc = SQLITE_NOMEM; nElem = 0; break; } aElem = aElem2; } aElem[nElem++] = pE; } } /* If more than one term matches the prefix, sort the Fts3HashElem ** objects in term order using qsort(). This uses the same comparison ** callback as is used when flushing terms to disk. */ if( nElem>1 ){ qsort(aElem, nElem, sizeof(Fts3HashElem *), fts3CompareElemByTerm); } }else{ /* The query is a simple term lookup that matches at most one term in ** the index. All that is required is a straight hash-lookup. ** ** Because the stack address of pE may be accessed via the aElem pointer ** below, the "Fts3HashElem *pE" must be declared so that it is valid ** within this entire function, not just this "else{...}" block. */ pE = fts3HashFindElem(pHash, zTerm, nTerm); if( pE ){ aElem = &pE; nElem = 1; } } if( nElem>0 ){ int nByte = sizeof(Fts3SegReader) + (nElem+1)*sizeof(Fts3HashElem *); pReader = (Fts3SegReader *)sqlite3_malloc(nByte); if( !pReader ){ rc = SQLITE_NOMEM; }else{ memset(pReader, 0, nByte); pReader->iIdx = 0x7FFFFFFF; pReader->ppNextElem = (Fts3HashElem **)&pReader[1]; memcpy(pReader->ppNextElem, aElem, nElem*sizeof(Fts3HashElem *)); } } if( bPrefix ){ sqlite3_free(aElem); } *ppReader = pReader; return rc; } /* ** Compare the entries pointed to by two Fts3SegReader structures. ** Comparison is as follows: ** ** 1) EOF is greater than not EOF. ** ** 2) The current terms (if any) are compared using memcmp(). If one ** term is a prefix of another, the longer term is considered the ** larger. ** ** 3) By segment age. An older segment is considered larger. */ static int fts3SegReaderCmp(Fts3SegReader *pLhs, Fts3SegReader *pRhs){ int rc; if( pLhs->aNode && pRhs->aNode ){ int rc2 = pLhs->nTerm - pRhs->nTerm; if( rc2<0 ){ rc = memcmp(pLhs->zTerm, pRhs->zTerm, pLhs->nTerm); }else{ rc = memcmp(pLhs->zTerm, pRhs->zTerm, pRhs->nTerm); } if( rc==0 ){ rc = rc2; } }else{ rc = (pLhs->aNode==0) - (pRhs->aNode==0); } if( rc==0 ){ rc = pRhs->iIdx - pLhs->iIdx; } assert( rc!=0 ); return rc; } /* ** A different comparison function for SegReader structures. In this ** version, it is assumed that each SegReader points to an entry in ** a doclist for identical terms. Comparison is made as follows: ** ** 1) EOF (end of doclist in this case) is greater than not EOF. ** ** 2) By current docid. ** ** 3) By segment age. An older segment is considered larger. */ static int fts3SegReaderDoclistCmp(Fts3SegReader *pLhs, Fts3SegReader *pRhs){ int rc = (pLhs->pOffsetList==0)-(pRhs->pOffsetList==0); if( rc==0 ){ if( pLhs->iDocid==pRhs->iDocid ){ rc = pRhs->iIdx - pLhs->iIdx; }else{ rc = (pLhs->iDocid > pRhs->iDocid) ? 1 : -1; } } assert( pLhs->aNode && pRhs->aNode ); return rc; } static int fts3SegReaderDoclistCmpRev(Fts3SegReader *pLhs, Fts3SegReader *pRhs){ int rc = (pLhs->pOffsetList==0)-(pRhs->pOffsetList==0); if( rc==0 ){ if( pLhs->iDocid==pRhs->iDocid ){ rc = pRhs->iIdx - pLhs->iIdx; }else{ rc = (pLhs->iDocid < pRhs->iDocid) ? 1 : -1; } } assert( pLhs->aNode && pRhs->aNode ); return rc; } /* ** Compare the term that the Fts3SegReader object passed as the first argument ** points to with the term specified by arguments zTerm and nTerm. ** ** If the pSeg iterator is already at EOF, return 0. Otherwise, return ** -ve if the pSeg term is less than zTerm/nTerm, 0 if the two terms are ** equal, or +ve if the pSeg term is greater than zTerm/nTerm. */ static int fts3SegReaderTermCmp( Fts3SegReader *pSeg, /* Segment reader object */ const char *zTerm, /* Term to compare to */ int nTerm /* Size of term zTerm in bytes */ ){ int res = 0; if( pSeg->aNode ){ if( pSeg->nTerm>nTerm ){ res = memcmp(pSeg->zTerm, zTerm, nTerm); }else{ res = memcmp(pSeg->zTerm, zTerm, pSeg->nTerm); } if( res==0 ){ res = pSeg->nTerm-nTerm; } } return res; } /* ** Argument apSegment is an array of nSegment elements. It is known that ** the final (nSegment-nSuspect) members are already in sorted order ** (according to the comparison function provided). This function shuffles ** the array around until all entries are in sorted order. */ static void fts3SegReaderSort( Fts3SegReader **apSegment, /* Array to sort entries of */ int nSegment, /* Size of apSegment array */ int nSuspect, /* Unsorted entry count */ int (*xCmp)(Fts3SegReader *, Fts3SegReader *) /* Comparison function */ ){ int i; /* Iterator variable */ assert( nSuspect<=nSegment ); if( nSuspect==nSegment ) nSuspect--; for(i=nSuspect-1; i>=0; i--){ int j; for(j=i; j<(nSegment-1); j++){ Fts3SegReader *pTmp; if( xCmp(apSegment[j], apSegment[j+1])<0 ) break; pTmp = apSegment[j+1]; apSegment[j+1] = apSegment[j]; apSegment[j] = pTmp; } } #ifndef NDEBUG /* Check that the list really is sorted now. */ for(i=0; i<(nSuspect-1); i++){ assert( xCmp(apSegment[i], apSegment[i+1])<0 ); } #endif } /* ** Insert a record into the %_segments table. */ static int fts3WriteSegment( Fts3Table *p, /* Virtual table handle */ sqlite3_int64 iBlock, /* Block id for new block */ char *z, /* Pointer to buffer containing block data */ int n /* Size of buffer z in bytes */ ){ sqlite3_stmt *pStmt; int rc = fts3SqlStmt(p, SQL_INSERT_SEGMENTS, &pStmt, 0); if( rc==SQLITE_OK ){ sqlite3_bind_int64(pStmt, 1, iBlock); sqlite3_bind_blob(pStmt, 2, z, n, SQLITE_STATIC); sqlite3_step(pStmt); rc = sqlite3_reset(pStmt); } return rc; } /* ** Find the largest relative level number in the table. If successful, set ** *pnMax to this value and return SQLITE_OK. Otherwise, if an error occurs, ** set *pnMax to zero and return an SQLite error code. */ SQLITE_PRIVATE int sqlite3Fts3MaxLevel(Fts3Table *p, int *pnMax){ int rc; int mxLevel = 0; sqlite3_stmt *pStmt = 0; rc = fts3SqlStmt(p, SQL_SELECT_MXLEVEL, &pStmt, 0); if( rc==SQLITE_OK ){ if( SQLITE_ROW==sqlite3_step(pStmt) ){ mxLevel = sqlite3_column_int(pStmt, 0); } rc = sqlite3_reset(pStmt); } *pnMax = mxLevel; return rc; } /* ** Insert a record into the %_segdir table. */ static int fts3WriteSegdir( Fts3Table *p, /* Virtual table handle */ sqlite3_int64 iLevel, /* Value for "level" field (absolute level) */ int iIdx, /* Value for "idx" field */ sqlite3_int64 iStartBlock, /* Value for "start_block" field */ sqlite3_int64 iLeafEndBlock, /* Value for "leaves_end_block" field */ sqlite3_int64 iEndBlock, /* Value for "end_block" field */ sqlite3_int64 nLeafData, /* Bytes of leaf data in segment */ char *zRoot, /* Blob value for "root" field */ int nRoot /* Number of bytes in buffer zRoot */ ){ sqlite3_stmt *pStmt; int rc = fts3SqlStmt(p, SQL_INSERT_SEGDIR, &pStmt, 0); if( rc==SQLITE_OK ){ sqlite3_bind_int64(pStmt, 1, iLevel); sqlite3_bind_int(pStmt, 2, iIdx); sqlite3_bind_int64(pStmt, 3, iStartBlock); sqlite3_bind_int64(pStmt, 4, iLeafEndBlock); if( nLeafData==0 ){ sqlite3_bind_int64(pStmt, 5, iEndBlock); }else{ char *zEnd = sqlite3_mprintf("%lld %lld", iEndBlock, nLeafData); if( !zEnd ) return SQLITE_NOMEM; sqlite3_bind_text(pStmt, 5, zEnd, -1, sqlite3_free); } sqlite3_bind_blob(pStmt, 6, zRoot, nRoot, SQLITE_STATIC); sqlite3_step(pStmt); rc = sqlite3_reset(pStmt); } return rc; } /* ** Return the size of the common prefix (if any) shared by zPrev and ** zNext, in bytes. For example, ** ** fts3PrefixCompress("abc", 3, "abcdef", 6) // returns 3 ** fts3PrefixCompress("abX", 3, "abcdef", 6) // returns 2 ** fts3PrefixCompress("abX", 3, "Xbcdef", 6) // returns 0 */ static int fts3PrefixCompress( const char *zPrev, /* Buffer containing previous term */ int nPrev, /* Size of buffer zPrev in bytes */ const char *zNext, /* Buffer containing next term */ int nNext /* Size of buffer zNext in bytes */ ){ int n; UNUSED_PARAMETER(nNext); for(n=0; nnData; /* Current size of node in bytes */ int nReq = nData; /* Required space after adding zTerm */ int nPrefix; /* Number of bytes of prefix compression */ int nSuffix; /* Suffix length */ nPrefix = fts3PrefixCompress(pTree->zTerm, pTree->nTerm, zTerm, nTerm); nSuffix = nTerm-nPrefix; nReq += sqlite3Fts3VarintLen(nPrefix)+sqlite3Fts3VarintLen(nSuffix)+nSuffix; if( nReq<=p->nNodeSize || !pTree->zTerm ){ if( nReq>p->nNodeSize ){ /* An unusual case: this is the first term to be added to the node ** and the static node buffer (p->nNodeSize bytes) is not large ** enough. Use a separately malloced buffer instead This wastes ** p->nNodeSize bytes, but since this scenario only comes about when ** the database contain two terms that share a prefix of almost 2KB, ** this is not expected to be a serious problem. */ assert( pTree->aData==(char *)&pTree[1] ); pTree->aData = (char *)sqlite3_malloc(nReq); if( !pTree->aData ){ return SQLITE_NOMEM; } } if( pTree->zTerm ){ /* There is no prefix-length field for first term in a node */ nData += sqlite3Fts3PutVarint(&pTree->aData[nData], nPrefix); } nData += sqlite3Fts3PutVarint(&pTree->aData[nData], nSuffix); memcpy(&pTree->aData[nData], &zTerm[nPrefix], nSuffix); pTree->nData = nData + nSuffix; pTree->nEntry++; if( isCopyTerm ){ if( pTree->nMalloczMalloc, nTerm*2); if( !zNew ){ return SQLITE_NOMEM; } pTree->nMalloc = nTerm*2; pTree->zMalloc = zNew; } pTree->zTerm = pTree->zMalloc; memcpy(pTree->zTerm, zTerm, nTerm); pTree->nTerm = nTerm; }else{ pTree->zTerm = (char *)zTerm; pTree->nTerm = nTerm; } return SQLITE_OK; } } /* If control flows to here, it was not possible to append zTerm to the ** current node. Create a new node (a right-sibling of the current node). ** If this is the first node in the tree, the term is added to it. ** ** Otherwise, the term is not added to the new node, it is left empty for ** now. Instead, the term is inserted into the parent of pTree. If pTree ** has no parent, one is created here. */ pNew = (SegmentNode *)sqlite3_malloc(sizeof(SegmentNode) + p->nNodeSize); if( !pNew ){ return SQLITE_NOMEM; } memset(pNew, 0, sizeof(SegmentNode)); pNew->nData = 1 + FTS3_VARINT_MAX; pNew->aData = (char *)&pNew[1]; if( pTree ){ SegmentNode *pParent = pTree->pParent; rc = fts3NodeAddTerm(p, &pParent, isCopyTerm, zTerm, nTerm); if( pTree->pParent==0 ){ pTree->pParent = pParent; } pTree->pRight = pNew; pNew->pLeftmost = pTree->pLeftmost; pNew->pParent = pParent; pNew->zMalloc = pTree->zMalloc; pNew->nMalloc = pTree->nMalloc; pTree->zMalloc = 0; }else{ pNew->pLeftmost = pNew; rc = fts3NodeAddTerm(p, &pNew, isCopyTerm, zTerm, nTerm); } *ppTree = pNew; return rc; } /* ** Helper function for fts3NodeWrite(). */ static int fts3TreeFinishNode( SegmentNode *pTree, int iHeight, sqlite3_int64 iLeftChild ){ int nStart; assert( iHeight>=1 && iHeight<128 ); nStart = FTS3_VARINT_MAX - sqlite3Fts3VarintLen(iLeftChild); pTree->aData[nStart] = (char)iHeight; sqlite3Fts3PutVarint(&pTree->aData[nStart+1], iLeftChild); return nStart; } /* ** Write the buffer for the segment node pTree and all of its peers to the ** database. Then call this function recursively to write the parent of ** pTree and its peers to the database. ** ** Except, if pTree is a root node, do not write it to the database. Instead, ** set output variables *paRoot and *pnRoot to contain the root node. ** ** If successful, SQLITE_OK is returned and output variable *piLast is ** set to the largest blockid written to the database (or zero if no ** blocks were written to the db). Otherwise, an SQLite error code is ** returned. */ static int fts3NodeWrite( Fts3Table *p, /* Virtual table handle */ SegmentNode *pTree, /* SegmentNode handle */ int iHeight, /* Height of this node in tree */ sqlite3_int64 iLeaf, /* Block id of first leaf node */ sqlite3_int64 iFree, /* Block id of next free slot in %_segments */ sqlite3_int64 *piLast, /* OUT: Block id of last entry written */ char **paRoot, /* OUT: Data for root node */ int *pnRoot /* OUT: Size of root node in bytes */ ){ int rc = SQLITE_OK; if( !pTree->pParent ){ /* Root node of the tree. */ int nStart = fts3TreeFinishNode(pTree, iHeight, iLeaf); *piLast = iFree-1; *pnRoot = pTree->nData - nStart; *paRoot = &pTree->aData[nStart]; }else{ SegmentNode *pIter; sqlite3_int64 iNextFree = iFree; sqlite3_int64 iNextLeaf = iLeaf; for(pIter=pTree->pLeftmost; pIter && rc==SQLITE_OK; pIter=pIter->pRight){ int nStart = fts3TreeFinishNode(pIter, iHeight, iNextLeaf); int nWrite = pIter->nData - nStart; rc = fts3WriteSegment(p, iNextFree, &pIter->aData[nStart], nWrite); iNextFree++; iNextLeaf += (pIter->nEntry+1); } if( rc==SQLITE_OK ){ assert( iNextLeaf==iFree ); rc = fts3NodeWrite( p, pTree->pParent, iHeight+1, iFree, iNextFree, piLast, paRoot, pnRoot ); } } return rc; } /* ** Free all memory allocations associated with the tree pTree. */ static void fts3NodeFree(SegmentNode *pTree){ if( pTree ){ SegmentNode *p = pTree->pLeftmost; fts3NodeFree(p->pParent); while( p ){ SegmentNode *pRight = p->pRight; if( p->aData!=(char *)&p[1] ){ sqlite3_free(p->aData); } assert( pRight==0 || p->zMalloc==0 ); sqlite3_free(p->zMalloc); sqlite3_free(p); p = pRight; } } } /* ** Add a term to the segment being constructed by the SegmentWriter object ** *ppWriter. When adding the first term to a segment, *ppWriter should ** be passed NULL. This function will allocate a new SegmentWriter object ** and return it via the input/output variable *ppWriter in this case. ** ** If successful, SQLITE_OK is returned. Otherwise, an SQLite error code. */ static int fts3SegWriterAdd( Fts3Table *p, /* Virtual table handle */ SegmentWriter **ppWriter, /* IN/OUT: SegmentWriter handle */ int isCopyTerm, /* True if buffer zTerm must be copied */ const char *zTerm, /* Pointer to buffer containing term */ int nTerm, /* Size of term in bytes */ const char *aDoclist, /* Pointer to buffer containing doclist */ int nDoclist /* Size of doclist in bytes */ ){ int nPrefix; /* Size of term prefix in bytes */ int nSuffix; /* Size of term suffix in bytes */ int nReq; /* Number of bytes required on leaf page */ int nData; SegmentWriter *pWriter = *ppWriter; if( !pWriter ){ int rc; sqlite3_stmt *pStmt; /* Allocate the SegmentWriter structure */ pWriter = (SegmentWriter *)sqlite3_malloc(sizeof(SegmentWriter)); if( !pWriter ) return SQLITE_NOMEM; memset(pWriter, 0, sizeof(SegmentWriter)); *ppWriter = pWriter; /* Allocate a buffer in which to accumulate data */ pWriter->aData = (char *)sqlite3_malloc(p->nNodeSize); if( !pWriter->aData ) return SQLITE_NOMEM; pWriter->nSize = p->nNodeSize; /* Find the next free blockid in the %_segments table */ rc = fts3SqlStmt(p, SQL_NEXT_SEGMENTS_ID, &pStmt, 0); if( rc!=SQLITE_OK ) return rc; if( SQLITE_ROW==sqlite3_step(pStmt) ){ pWriter->iFree = sqlite3_column_int64(pStmt, 0); pWriter->iFirst = pWriter->iFree; } rc = sqlite3_reset(pStmt); if( rc!=SQLITE_OK ) return rc; } nData = pWriter->nData; nPrefix = fts3PrefixCompress(pWriter->zTerm, pWriter->nTerm, zTerm, nTerm); nSuffix = nTerm-nPrefix; /* Figure out how many bytes are required by this new entry */ nReq = sqlite3Fts3VarintLen(nPrefix) + /* varint containing prefix size */ sqlite3Fts3VarintLen(nSuffix) + /* varint containing suffix size */ nSuffix + /* Term suffix */ sqlite3Fts3VarintLen(nDoclist) + /* Size of doclist */ nDoclist; /* Doclist data */ if( nData>0 && nData+nReq>p->nNodeSize ){ int rc; /* The current leaf node is full. Write it out to the database. */ rc = fts3WriteSegment(p, pWriter->iFree++, pWriter->aData, nData); if( rc!=SQLITE_OK ) return rc; p->nLeafAdd++; /* Add the current term to the interior node tree. The term added to ** the interior tree must: ** ** a) be greater than the largest term on the leaf node just written ** to the database (still available in pWriter->zTerm), and ** ** b) be less than or equal to the term about to be added to the new ** leaf node (zTerm/nTerm). ** ** In other words, it must be the prefix of zTerm 1 byte longer than ** the common prefix (if any) of zTerm and pWriter->zTerm. */ assert( nPrefixpTree, isCopyTerm, zTerm, nPrefix+1); if( rc!=SQLITE_OK ) return rc; nData = 0; pWriter->nTerm = 0; nPrefix = 0; nSuffix = nTerm; nReq = 1 + /* varint containing prefix size */ sqlite3Fts3VarintLen(nTerm) + /* varint containing suffix size */ nTerm + /* Term suffix */ sqlite3Fts3VarintLen(nDoclist) + /* Size of doclist */ nDoclist; /* Doclist data */ } /* Increase the total number of bytes written to account for the new entry. */ pWriter->nLeafData += nReq; /* If the buffer currently allocated is too small for this entry, realloc ** the buffer to make it large enough. */ if( nReq>pWriter->nSize ){ char *aNew = sqlite3_realloc(pWriter->aData, nReq); if( !aNew ) return SQLITE_NOMEM; pWriter->aData = aNew; pWriter->nSize = nReq; } assert( nData+nReq<=pWriter->nSize ); /* Append the prefix-compressed term and doclist to the buffer. */ nData += sqlite3Fts3PutVarint(&pWriter->aData[nData], nPrefix); nData += sqlite3Fts3PutVarint(&pWriter->aData[nData], nSuffix); memcpy(&pWriter->aData[nData], &zTerm[nPrefix], nSuffix); nData += nSuffix; nData += sqlite3Fts3PutVarint(&pWriter->aData[nData], nDoclist); memcpy(&pWriter->aData[nData], aDoclist, nDoclist); pWriter->nData = nData + nDoclist; /* Save the current term so that it can be used to prefix-compress the next. ** If the isCopyTerm parameter is true, then the buffer pointed to by ** zTerm is transient, so take a copy of the term data. Otherwise, just ** store a copy of the pointer. */ if( isCopyTerm ){ if( nTerm>pWriter->nMalloc ){ char *zNew = sqlite3_realloc(pWriter->zMalloc, nTerm*2); if( !zNew ){ return SQLITE_NOMEM; } pWriter->nMalloc = nTerm*2; pWriter->zMalloc = zNew; pWriter->zTerm = zNew; } assert( pWriter->zTerm==pWriter->zMalloc ); memcpy(pWriter->zTerm, zTerm, nTerm); }else{ pWriter->zTerm = (char *)zTerm; } pWriter->nTerm = nTerm; return SQLITE_OK; } /* ** Flush all data associated with the SegmentWriter object pWriter to the ** database. This function must be called after all terms have been added ** to the segment using fts3SegWriterAdd(). If successful, SQLITE_OK is ** returned. Otherwise, an SQLite error code. */ static int fts3SegWriterFlush( Fts3Table *p, /* Virtual table handle */ SegmentWriter *pWriter, /* SegmentWriter to flush to the db */ sqlite3_int64 iLevel, /* Value for 'level' column of %_segdir */ int iIdx /* Value for 'idx' column of %_segdir */ ){ int rc; /* Return code */ if( pWriter->pTree ){ sqlite3_int64 iLast = 0; /* Largest block id written to database */ sqlite3_int64 iLastLeaf; /* Largest leaf block id written to db */ char *zRoot = NULL; /* Pointer to buffer containing root node */ int nRoot = 0; /* Size of buffer zRoot */ iLastLeaf = pWriter->iFree; rc = fts3WriteSegment(p, pWriter->iFree++, pWriter->aData, pWriter->nData); if( rc==SQLITE_OK ){ rc = fts3NodeWrite(p, pWriter->pTree, 1, pWriter->iFirst, pWriter->iFree, &iLast, &zRoot, &nRoot); } if( rc==SQLITE_OK ){ rc = fts3WriteSegdir(p, iLevel, iIdx, pWriter->iFirst, iLastLeaf, iLast, pWriter->nLeafData, zRoot, nRoot); } }else{ /* The entire tree fits on the root node. Write it to the segdir table. */ rc = fts3WriteSegdir(p, iLevel, iIdx, 0, 0, 0, pWriter->nLeafData, pWriter->aData, pWriter->nData); } p->nLeafAdd++; return rc; } /* ** Release all memory held by the SegmentWriter object passed as the ** first argument. */ static void fts3SegWriterFree(SegmentWriter *pWriter){ if( pWriter ){ sqlite3_free(pWriter->aData); sqlite3_free(pWriter->zMalloc); fts3NodeFree(pWriter->pTree); sqlite3_free(pWriter); } } /* ** The first value in the apVal[] array is assumed to contain an integer. ** This function tests if there exist any documents with docid values that ** are different from that integer. i.e. if deleting the document with docid ** pRowid would mean the FTS3 table were empty. ** ** If successful, *pisEmpty is set to true if the table is empty except for ** document pRowid, or false otherwise, and SQLITE_OK is returned. If an ** error occurs, an SQLite error code is returned. */ static int fts3IsEmpty(Fts3Table *p, sqlite3_value *pRowid, int *pisEmpty){ sqlite3_stmt *pStmt; int rc; if( p->zContentTbl ){ /* If using the content=xxx option, assume the table is never empty */ *pisEmpty = 0; rc = SQLITE_OK; }else{ rc = fts3SqlStmt(p, SQL_IS_EMPTY, &pStmt, &pRowid); if( rc==SQLITE_OK ){ if( SQLITE_ROW==sqlite3_step(pStmt) ){ *pisEmpty = sqlite3_column_int(pStmt, 0); } rc = sqlite3_reset(pStmt); } } return rc; } /* ** Set *pnMax to the largest segment level in the database for the index ** iIndex. ** ** Segment levels are stored in the 'level' column of the %_segdir table. ** ** Return SQLITE_OK if successful, or an SQLite error code if not. */ static int fts3SegmentMaxLevel( Fts3Table *p, int iLangid, int iIndex, sqlite3_int64 *pnMax ){ sqlite3_stmt *pStmt; int rc; assert( iIndex>=0 && iIndexnIndex ); /* Set pStmt to the compiled version of: ** ** SELECT max(level) FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ? ** ** (1024 is actually the value of macro FTS3_SEGDIR_PREFIXLEVEL_STR). */ rc = fts3SqlStmt(p, SQL_SELECT_SEGDIR_MAX_LEVEL, &pStmt, 0); if( rc!=SQLITE_OK ) return rc; sqlite3_bind_int64(pStmt, 1, getAbsoluteLevel(p, iLangid, iIndex, 0)); sqlite3_bind_int64(pStmt, 2, getAbsoluteLevel(p, iLangid, iIndex, FTS3_SEGDIR_MAXLEVEL-1) ); if( SQLITE_ROW==sqlite3_step(pStmt) ){ *pnMax = sqlite3_column_int64(pStmt, 0); } return sqlite3_reset(pStmt); } /* ** iAbsLevel is an absolute level that may be assumed to exist within ** the database. This function checks if it is the largest level number ** within its index. Assuming no error occurs, *pbMax is set to 1 if ** iAbsLevel is indeed the largest level, or 0 otherwise, and SQLITE_OK ** is returned. If an error occurs, an error code is returned and the ** final value of *pbMax is undefined. */ static int fts3SegmentIsMaxLevel(Fts3Table *p, i64 iAbsLevel, int *pbMax){ /* Set pStmt to the compiled version of: ** ** SELECT max(level) FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ? ** ** (1024 is actually the value of macro FTS3_SEGDIR_PREFIXLEVEL_STR). */ sqlite3_stmt *pStmt; int rc = fts3SqlStmt(p, SQL_SELECT_SEGDIR_MAX_LEVEL, &pStmt, 0); if( rc!=SQLITE_OK ) return rc; sqlite3_bind_int64(pStmt, 1, iAbsLevel+1); sqlite3_bind_int64(pStmt, 2, ((iAbsLevel/FTS3_SEGDIR_MAXLEVEL)+1) * FTS3_SEGDIR_MAXLEVEL ); *pbMax = 0; if( SQLITE_ROW==sqlite3_step(pStmt) ){ *pbMax = sqlite3_column_type(pStmt, 0)==SQLITE_NULL; } return sqlite3_reset(pStmt); } /* ** Delete all entries in the %_segments table associated with the segment ** opened with seg-reader pSeg. This function does not affect the contents ** of the %_segdir table. */ static int fts3DeleteSegment( Fts3Table *p, /* FTS table handle */ Fts3SegReader *pSeg /* Segment to delete */ ){ int rc = SQLITE_OK; /* Return code */ if( pSeg->iStartBlock ){ sqlite3_stmt *pDelete; /* SQL statement to delete rows */ rc = fts3SqlStmt(p, SQL_DELETE_SEGMENTS_RANGE, &pDelete, 0); if( rc==SQLITE_OK ){ sqlite3_bind_int64(pDelete, 1, pSeg->iStartBlock); sqlite3_bind_int64(pDelete, 2, pSeg->iEndBlock); sqlite3_step(pDelete); rc = sqlite3_reset(pDelete); } } return rc; } /* ** This function is used after merging multiple segments into a single large ** segment to delete the old, now redundant, segment b-trees. Specifically, ** it: ** ** 1) Deletes all %_segments entries for the segments associated with ** each of the SegReader objects in the array passed as the third ** argument, and ** ** 2) deletes all %_segdir entries with level iLevel, or all %_segdir ** entries regardless of level if (iLevel<0). ** ** SQLITE_OK is returned if successful, otherwise an SQLite error code. */ static int fts3DeleteSegdir( Fts3Table *p, /* Virtual table handle */ int iLangid, /* Language id */ int iIndex, /* Index for p->aIndex */ int iLevel, /* Level of %_segdir entries to delete */ Fts3SegReader **apSegment, /* Array of SegReader objects */ int nReader /* Size of array apSegment */ ){ int rc = SQLITE_OK; /* Return Code */ int i; /* Iterator variable */ sqlite3_stmt *pDelete = 0; /* SQL statement to delete rows */ for(i=0; rc==SQLITE_OK && i=0 || iLevel==FTS3_SEGCURSOR_ALL ); if( iLevel==FTS3_SEGCURSOR_ALL ){ rc = fts3SqlStmt(p, SQL_DELETE_SEGDIR_RANGE, &pDelete, 0); if( rc==SQLITE_OK ){ sqlite3_bind_int64(pDelete, 1, getAbsoluteLevel(p, iLangid, iIndex, 0)); sqlite3_bind_int64(pDelete, 2, getAbsoluteLevel(p, iLangid, iIndex, FTS3_SEGDIR_MAXLEVEL-1) ); } }else{ rc = fts3SqlStmt(p, SQL_DELETE_SEGDIR_LEVEL, &pDelete, 0); if( rc==SQLITE_OK ){ sqlite3_bind_int64( pDelete, 1, getAbsoluteLevel(p, iLangid, iIndex, iLevel) ); } } if( rc==SQLITE_OK ){ sqlite3_step(pDelete); rc = sqlite3_reset(pDelete); } return rc; } /* ** When this function is called, buffer *ppList (size *pnList bytes) contains ** a position list that may (or may not) feature multiple columns. This ** function adjusts the pointer *ppList and the length *pnList so that they ** identify the subset of the position list that corresponds to column iCol. ** ** If there are no entries in the input position list for column iCol, then ** *pnList is set to zero before returning. ** ** If parameter bZero is non-zero, then any part of the input list following ** the end of the output list is zeroed before returning. */ static void fts3ColumnFilter( int iCol, /* Column to filter on */ int bZero, /* Zero out anything following *ppList */ char **ppList, /* IN/OUT: Pointer to position list */ int *pnList /* IN/OUT: Size of buffer *ppList in bytes */ ){ char *pList = *ppList; int nList = *pnList; char *pEnd = &pList[nList]; int iCurrent = 0; char *p = pList; assert( iCol>=0 ); while( 1 ){ char c = 0; while( ppMsr->nBuffer ){ char *pNew; pMsr->nBuffer = nList*2; pNew = (char *)sqlite3_realloc(pMsr->aBuffer, pMsr->nBuffer); if( !pNew ) return SQLITE_NOMEM; pMsr->aBuffer = pNew; } memcpy(pMsr->aBuffer, pList, nList); return SQLITE_OK; } SQLITE_PRIVATE int sqlite3Fts3MsrIncrNext( Fts3Table *p, /* Virtual table handle */ Fts3MultiSegReader *pMsr, /* Multi-segment-reader handle */ sqlite3_int64 *piDocid, /* OUT: Docid value */ char **paPoslist, /* OUT: Pointer to position list */ int *pnPoslist /* OUT: Size of position list in bytes */ ){ int nMerge = pMsr->nAdvance; Fts3SegReader **apSegment = pMsr->apSegment; int (*xCmp)(Fts3SegReader *, Fts3SegReader *) = ( p->bDescIdx ? fts3SegReaderDoclistCmpRev : fts3SegReaderDoclistCmp ); if( nMerge==0 ){ *paPoslist = 0; return SQLITE_OK; } while( 1 ){ Fts3SegReader *pSeg; pSeg = pMsr->apSegment[0]; if( pSeg->pOffsetList==0 ){ *paPoslist = 0; break; }else{ int rc; char *pList; int nList; int j; sqlite3_int64 iDocid = apSegment[0]->iDocid; rc = fts3SegReaderNextDocid(p, apSegment[0], &pList, &nList); j = 1; while( rc==SQLITE_OK && jpOffsetList && apSegment[j]->iDocid==iDocid ){ rc = fts3SegReaderNextDocid(p, apSegment[j], 0, 0); j++; } if( rc!=SQLITE_OK ) return rc; fts3SegReaderSort(pMsr->apSegment, nMerge, j, xCmp); if( nList>0 && fts3SegReaderIsPending(apSegment[0]) ){ rc = fts3MsrBufferData(pMsr, pList, nList+1); if( rc!=SQLITE_OK ) return rc; assert( (pMsr->aBuffer[nList] & 0xFE)==0x00 ); pList = pMsr->aBuffer; } if( pMsr->iColFilter>=0 ){ fts3ColumnFilter(pMsr->iColFilter, 1, &pList, &nList); } if( nList>0 ){ *paPoslist = pList; *piDocid = iDocid; *pnPoslist = nList; break; } } } return SQLITE_OK; } static int fts3SegReaderStart( Fts3Table *p, /* Virtual table handle */ Fts3MultiSegReader *pCsr, /* Cursor object */ const char *zTerm, /* Term searched for (or NULL) */ int nTerm /* Length of zTerm in bytes */ ){ int i; int nSeg = pCsr->nSegment; /* If the Fts3SegFilter defines a specific term (or term prefix) to search ** for, then advance each segment iterator until it points to a term of ** equal or greater value than the specified term. This prevents many ** unnecessary merge/sort operations for the case where single segment ** b-tree leaf nodes contain more than one term. */ for(i=0; pCsr->bRestart==0 && inSegment; i++){ int res = 0; Fts3SegReader *pSeg = pCsr->apSegment[i]; do { int rc = fts3SegReaderNext(p, pSeg, 0); if( rc!=SQLITE_OK ) return rc; }while( zTerm && (res = fts3SegReaderTermCmp(pSeg, zTerm, nTerm))<0 ); if( pSeg->bLookup && res!=0 ){ fts3SegReaderSetEof(pSeg); } } fts3SegReaderSort(pCsr->apSegment, nSeg, nSeg, fts3SegReaderCmp); return SQLITE_OK; } SQLITE_PRIVATE int sqlite3Fts3SegReaderStart( Fts3Table *p, /* Virtual table handle */ Fts3MultiSegReader *pCsr, /* Cursor object */ Fts3SegFilter *pFilter /* Restrictions on range of iteration */ ){ pCsr->pFilter = pFilter; return fts3SegReaderStart(p, pCsr, pFilter->zTerm, pFilter->nTerm); } SQLITE_PRIVATE int sqlite3Fts3MsrIncrStart( Fts3Table *p, /* Virtual table handle */ Fts3MultiSegReader *pCsr, /* Cursor object */ int iCol, /* Column to match on. */ const char *zTerm, /* Term to iterate through a doclist for */ int nTerm /* Number of bytes in zTerm */ ){ int i; int rc; int nSegment = pCsr->nSegment; int (*xCmp)(Fts3SegReader *, Fts3SegReader *) = ( p->bDescIdx ? fts3SegReaderDoclistCmpRev : fts3SegReaderDoclistCmp ); assert( pCsr->pFilter==0 ); assert( zTerm && nTerm>0 ); /* Advance each segment iterator until it points to the term zTerm/nTerm. */ rc = fts3SegReaderStart(p, pCsr, zTerm, nTerm); if( rc!=SQLITE_OK ) return rc; /* Determine how many of the segments actually point to zTerm/nTerm. */ for(i=0; iapSegment[i]; if( !pSeg->aNode || fts3SegReaderTermCmp(pSeg, zTerm, nTerm) ){ break; } } pCsr->nAdvance = i; /* Advance each of the segments to point to the first docid. */ for(i=0; inAdvance; i++){ rc = fts3SegReaderFirstDocid(p, pCsr->apSegment[i]); if( rc!=SQLITE_OK ) return rc; } fts3SegReaderSort(pCsr->apSegment, i, i, xCmp); assert( iCol<0 || iColnColumn ); pCsr->iColFilter = iCol; return SQLITE_OK; } /* ** This function is called on a MultiSegReader that has been started using ** sqlite3Fts3MsrIncrStart(). One or more calls to MsrIncrNext() may also ** have been made. Calling this function puts the MultiSegReader in such ** a state that if the next two calls are: ** ** sqlite3Fts3SegReaderStart() ** sqlite3Fts3SegReaderStep() ** ** then the entire doclist for the term is available in ** MultiSegReader.aDoclist/nDoclist. */ SQLITE_PRIVATE int sqlite3Fts3MsrIncrRestart(Fts3MultiSegReader *pCsr){ int i; /* Used to iterate through segment-readers */ assert( pCsr->zTerm==0 ); assert( pCsr->nTerm==0 ); assert( pCsr->aDoclist==0 ); assert( pCsr->nDoclist==0 ); pCsr->nAdvance = 0; pCsr->bRestart = 1; for(i=0; inSegment; i++){ pCsr->apSegment[i]->pOffsetList = 0; pCsr->apSegment[i]->nOffsetList = 0; pCsr->apSegment[i]->iDocid = 0; } return SQLITE_OK; } SQLITE_PRIVATE int sqlite3Fts3SegReaderStep( Fts3Table *p, /* Virtual table handle */ Fts3MultiSegReader *pCsr /* Cursor object */ ){ int rc = SQLITE_OK; int isIgnoreEmpty = (pCsr->pFilter->flags & FTS3_SEGMENT_IGNORE_EMPTY); int isRequirePos = (pCsr->pFilter->flags & FTS3_SEGMENT_REQUIRE_POS); int isColFilter = (pCsr->pFilter->flags & FTS3_SEGMENT_COLUMN_FILTER); int isPrefix = (pCsr->pFilter->flags & FTS3_SEGMENT_PREFIX); int isScan = (pCsr->pFilter->flags & FTS3_SEGMENT_SCAN); int isFirst = (pCsr->pFilter->flags & FTS3_SEGMENT_FIRST); Fts3SegReader **apSegment = pCsr->apSegment; int nSegment = pCsr->nSegment; Fts3SegFilter *pFilter = pCsr->pFilter; int (*xCmp)(Fts3SegReader *, Fts3SegReader *) = ( p->bDescIdx ? fts3SegReaderDoclistCmpRev : fts3SegReaderDoclistCmp ); if( pCsr->nSegment==0 ) return SQLITE_OK; do { int nMerge; int i; /* Advance the first pCsr->nAdvance entries in the apSegment[] array ** forward. Then sort the list in order of current term again. */ for(i=0; inAdvance; i++){ Fts3SegReader *pSeg = apSegment[i]; if( pSeg->bLookup ){ fts3SegReaderSetEof(pSeg); }else{ rc = fts3SegReaderNext(p, pSeg, 0); } if( rc!=SQLITE_OK ) return rc; } fts3SegReaderSort(apSegment, nSegment, pCsr->nAdvance, fts3SegReaderCmp); pCsr->nAdvance = 0; /* If all the seg-readers are at EOF, we're finished. return SQLITE_OK. */ assert( rc==SQLITE_OK ); if( apSegment[0]->aNode==0 ) break; pCsr->nTerm = apSegment[0]->nTerm; pCsr->zTerm = apSegment[0]->zTerm; /* If this is a prefix-search, and if the term that apSegment[0] points ** to does not share a suffix with pFilter->zTerm/nTerm, then all ** required callbacks have been made. In this case exit early. ** ** Similarly, if this is a search for an exact match, and the first term ** of segment apSegment[0] is not a match, exit early. */ if( pFilter->zTerm && !isScan ){ if( pCsr->nTermnTerm || (!isPrefix && pCsr->nTerm>pFilter->nTerm) || memcmp(pCsr->zTerm, pFilter->zTerm, pFilter->nTerm) ){ break; } } nMerge = 1; while( nMergeaNode && apSegment[nMerge]->nTerm==pCsr->nTerm && 0==memcmp(pCsr->zTerm, apSegment[nMerge]->zTerm, pCsr->nTerm) ){ nMerge++; } assert( isIgnoreEmpty || (isRequirePos && !isColFilter) ); if( nMerge==1 && !isIgnoreEmpty && !isFirst && (p->bDescIdx==0 || fts3SegReaderIsPending(apSegment[0])==0) ){ pCsr->nDoclist = apSegment[0]->nDoclist; if( fts3SegReaderIsPending(apSegment[0]) ){ rc = fts3MsrBufferData(pCsr, apSegment[0]->aDoclist, pCsr->nDoclist); pCsr->aDoclist = pCsr->aBuffer; }else{ pCsr->aDoclist = apSegment[0]->aDoclist; } if( rc==SQLITE_OK ) rc = SQLITE_ROW; }else{ int nDoclist = 0; /* Size of doclist */ sqlite3_int64 iPrev = 0; /* Previous docid stored in doclist */ /* The current term of the first nMerge entries in the array ** of Fts3SegReader objects is the same. The doclists must be merged ** and a single term returned with the merged doclist. */ for(i=0; ipOffsetList ){ int j; /* Number of segments that share a docid */ char *pList = 0; int nList = 0; int nByte; sqlite3_int64 iDocid = apSegment[0]->iDocid; fts3SegReaderNextDocid(p, apSegment[0], &pList, &nList); j = 1; while( jpOffsetList && apSegment[j]->iDocid==iDocid ){ fts3SegReaderNextDocid(p, apSegment[j], 0, 0); j++; } if( isColFilter ){ fts3ColumnFilter(pFilter->iCol, 0, &pList, &nList); } if( !isIgnoreEmpty || nList>0 ){ /* Calculate the 'docid' delta value to write into the merged ** doclist. */ sqlite3_int64 iDelta; if( p->bDescIdx && nDoclist>0 ){ iDelta = iPrev - iDocid; }else{ iDelta = iDocid - iPrev; } assert( iDelta>0 || (nDoclist==0 && iDelta==iDocid) ); assert( nDoclist>0 || iDelta==iDocid ); nByte = sqlite3Fts3VarintLen(iDelta) + (isRequirePos?nList+1:0); if( nDoclist+nByte>pCsr->nBuffer ){ char *aNew; pCsr->nBuffer = (nDoclist+nByte)*2; aNew = sqlite3_realloc(pCsr->aBuffer, pCsr->nBuffer); if( !aNew ){ return SQLITE_NOMEM; } pCsr->aBuffer = aNew; } if( isFirst ){ char *a = &pCsr->aBuffer[nDoclist]; int nWrite; nWrite = sqlite3Fts3FirstFilter(iDelta, pList, nList, a); if( nWrite ){ iPrev = iDocid; nDoclist += nWrite; } }else{ nDoclist += sqlite3Fts3PutVarint(&pCsr->aBuffer[nDoclist], iDelta); iPrev = iDocid; if( isRequirePos ){ memcpy(&pCsr->aBuffer[nDoclist], pList, nList); nDoclist += nList; pCsr->aBuffer[nDoclist++] = '\0'; } } } fts3SegReaderSort(apSegment, nMerge, j, xCmp); } if( nDoclist>0 ){ pCsr->aDoclist = pCsr->aBuffer; pCsr->nDoclist = nDoclist; rc = SQLITE_ROW; } } pCsr->nAdvance = nMerge; }while( rc==SQLITE_OK ); return rc; } SQLITE_PRIVATE void sqlite3Fts3SegReaderFinish( Fts3MultiSegReader *pCsr /* Cursor object */ ){ if( pCsr ){ int i; for(i=0; inSegment; i++){ sqlite3Fts3SegReaderFree(pCsr->apSegment[i]); } sqlite3_free(pCsr->apSegment); sqlite3_free(pCsr->aBuffer); pCsr->nSegment = 0; pCsr->apSegment = 0; pCsr->aBuffer = 0; } } /* ** Decode the "end_block" field, selected by column iCol of the SELECT ** statement passed as the first argument. ** ** The "end_block" field may contain either an integer, or a text field ** containing the text representation of two non-negative integers separated ** by one or more space (0x20) characters. In the first case, set *piEndBlock ** to the integer value and *pnByte to zero before returning. In the second, ** set *piEndBlock to the first value and *pnByte to the second. */ static void fts3ReadEndBlockField( sqlite3_stmt *pStmt, int iCol, i64 *piEndBlock, i64 *pnByte ){ const unsigned char *zText = sqlite3_column_text(pStmt, iCol); if( zText ){ int i; int iMul = 1; i64 iVal = 0; for(i=0; zText[i]>='0' && zText[i]<='9'; i++){ iVal = iVal*10 + (zText[i] - '0'); } *piEndBlock = iVal; while( zText[i]==' ' ) i++; iVal = 0; if( zText[i]=='-' ){ i++; iMul = -1; } for(/* no-op */; zText[i]>='0' && zText[i]<='9'; i++){ iVal = iVal*10 + (zText[i] - '0'); } *pnByte = (iVal * (i64)iMul); } } /* ** A segment of size nByte bytes has just been written to absolute level ** iAbsLevel. Promote any segments that should be promoted as a result. */ static int fts3PromoteSegments( Fts3Table *p, /* FTS table handle */ sqlite3_int64 iAbsLevel, /* Absolute level just updated */ sqlite3_int64 nByte /* Size of new segment at iAbsLevel */ ){ int rc = SQLITE_OK; sqlite3_stmt *pRange; rc = fts3SqlStmt(p, SQL_SELECT_LEVEL_RANGE2, &pRange, 0); if( rc==SQLITE_OK ){ int bOk = 0; i64 iLast = (iAbsLevel/FTS3_SEGDIR_MAXLEVEL + 1) * FTS3_SEGDIR_MAXLEVEL - 1; i64 nLimit = (nByte*3)/2; /* Loop through all entries in the %_segdir table corresponding to ** segments in this index on levels greater than iAbsLevel. If there is ** at least one such segment, and it is possible to determine that all ** such segments are smaller than nLimit bytes in size, they will be ** promoted to level iAbsLevel. */ sqlite3_bind_int64(pRange, 1, iAbsLevel+1); sqlite3_bind_int64(pRange, 2, iLast); while( SQLITE_ROW==sqlite3_step(pRange) ){ i64 nSize = 0, dummy; fts3ReadEndBlockField(pRange, 2, &dummy, &nSize); if( nSize<=0 || nSize>nLimit ){ /* If nSize==0, then the %_segdir.end_block field does not not ** contain a size value. This happens if it was written by an ** old version of FTS. In this case it is not possible to determine ** the size of the segment, and so segment promotion does not ** take place. */ bOk = 0; break; } bOk = 1; } rc = sqlite3_reset(pRange); if( bOk ){ int iIdx = 0; sqlite3_stmt *pUpdate1 = 0; sqlite3_stmt *pUpdate2 = 0; if( rc==SQLITE_OK ){ rc = fts3SqlStmt(p, SQL_UPDATE_LEVEL_IDX, &pUpdate1, 0); } if( rc==SQLITE_OK ){ rc = fts3SqlStmt(p, SQL_UPDATE_LEVEL, &pUpdate2, 0); } if( rc==SQLITE_OK ){ /* Loop through all %_segdir entries for segments in this index with ** levels equal to or greater than iAbsLevel. As each entry is visited, ** updated it to set (level = -1) and (idx = N), where N is 0 for the ** oldest segment in the range, 1 for the next oldest, and so on. ** ** In other words, move all segments being promoted to level -1, ** setting the "idx" fields as appropriate to keep them in the same ** order. The contents of level -1 (which is never used, except ** transiently here), will be moved back to level iAbsLevel below. */ sqlite3_bind_int64(pRange, 1, iAbsLevel); while( SQLITE_ROW==sqlite3_step(pRange) ){ sqlite3_bind_int(pUpdate1, 1, iIdx++); sqlite3_bind_int(pUpdate1, 2, sqlite3_column_int(pRange, 0)); sqlite3_bind_int(pUpdate1, 3, sqlite3_column_int(pRange, 1)); sqlite3_step(pUpdate1); rc = sqlite3_reset(pUpdate1); if( rc!=SQLITE_OK ){ sqlite3_reset(pRange); break; } } } if( rc==SQLITE_OK ){ rc = sqlite3_reset(pRange); } /* Move level -1 to level iAbsLevel */ if( rc==SQLITE_OK ){ sqlite3_bind_int64(pUpdate2, 1, iAbsLevel); sqlite3_step(pUpdate2); rc = sqlite3_reset(pUpdate2); } } } return rc; } /* ** Merge all level iLevel segments in the database into a single ** iLevel+1 segment. Or, if iLevel<0, merge all segments into a ** single segment with a level equal to the numerically largest level ** currently present in the database. ** ** If this function is called with iLevel<0, but there is only one ** segment in the database, SQLITE_DONE is returned immediately. ** Otherwise, if successful, SQLITE_OK is returned. If an error occurs, ** an SQLite error code is returned. */ static int fts3SegmentMerge( Fts3Table *p, int iLangid, /* Language id to merge */ int iIndex, /* Index in p->aIndex[] to merge */ int iLevel /* Level to merge */ ){ int rc; /* Return code */ int iIdx = 0; /* Index of new segment */ sqlite3_int64 iNewLevel = 0; /* Level/index to create new segment at */ SegmentWriter *pWriter = 0; /* Used to write the new, merged, segment */ Fts3SegFilter filter; /* Segment term filter condition */ Fts3MultiSegReader csr; /* Cursor to iterate through level(s) */ int bIgnoreEmpty = 0; /* True to ignore empty segments */ i64 iMaxLevel = 0; /* Max level number for this index/langid */ assert( iLevel==FTS3_SEGCURSOR_ALL || iLevel==FTS3_SEGCURSOR_PENDING || iLevel>=0 ); assert( iLevel=0 && iIndexnIndex ); rc = sqlite3Fts3SegReaderCursor(p, iLangid, iIndex, iLevel, 0, 0, 1, 0, &csr); if( rc!=SQLITE_OK || csr.nSegment==0 ) goto finished; if( iLevel!=FTS3_SEGCURSOR_PENDING ){ rc = fts3SegmentMaxLevel(p, iLangid, iIndex, &iMaxLevel); if( rc!=SQLITE_OK ) goto finished; } if( iLevel==FTS3_SEGCURSOR_ALL ){ /* This call is to merge all segments in the database to a single ** segment. The level of the new segment is equal to the numerically ** greatest segment level currently present in the database for this ** index. The idx of the new segment is always 0. */ if( csr.nSegment==1 && 0==fts3SegReaderIsPending(csr.apSegment[0]) ){ rc = SQLITE_DONE; goto finished; } iNewLevel = iMaxLevel; bIgnoreEmpty = 1; }else{ /* This call is to merge all segments at level iLevel. find the next ** available segment index at level iLevel+1. The call to ** fts3AllocateSegdirIdx() will merge the segments at level iLevel+1 to ** a single iLevel+2 segment if necessary. */ assert( FTS3_SEGCURSOR_PENDING==-1 ); iNewLevel = getAbsoluteLevel(p, iLangid, iIndex, iLevel+1); rc = fts3AllocateSegdirIdx(p, iLangid, iIndex, iLevel+1, &iIdx); bIgnoreEmpty = (iLevel!=FTS3_SEGCURSOR_PENDING) && (iNewLevel>iMaxLevel); } if( rc!=SQLITE_OK ) goto finished; assert( csr.nSegment>0 ); assert( iNewLevel>=getAbsoluteLevel(p, iLangid, iIndex, 0) ); assert( iNewLevelnLeafData); } } } finished: fts3SegWriterFree(pWriter); sqlite3Fts3SegReaderFinish(&csr); return rc; } /* ** Flush the contents of pendingTerms to level 0 segments. */ SQLITE_PRIVATE int sqlite3Fts3PendingTermsFlush(Fts3Table *p){ int rc = SQLITE_OK; int i; for(i=0; rc==SQLITE_OK && inIndex; i++){ rc = fts3SegmentMerge(p, p->iPrevLangid, i, FTS3_SEGCURSOR_PENDING); if( rc==SQLITE_DONE ) rc = SQLITE_OK; } sqlite3Fts3PendingTermsClear(p); /* Determine the auto-incr-merge setting if unknown. If enabled, ** estimate the number of leaf blocks of content to be written */ if( rc==SQLITE_OK && p->bHasStat && p->nAutoincrmerge==0xff && p->nLeafAdd>0 ){ sqlite3_stmt *pStmt = 0; rc = fts3SqlStmt(p, SQL_SELECT_STAT, &pStmt, 0); if( rc==SQLITE_OK ){ sqlite3_bind_int(pStmt, 1, FTS_STAT_AUTOINCRMERGE); rc = sqlite3_step(pStmt); if( rc==SQLITE_ROW ){ p->nAutoincrmerge = sqlite3_column_int(pStmt, 0); if( p->nAutoincrmerge==1 ) p->nAutoincrmerge = 8; }else if( rc==SQLITE_DONE ){ p->nAutoincrmerge = 0; } rc = sqlite3_reset(pStmt); } } return rc; } /* ** Encode N integers as varints into a blob. */ static void fts3EncodeIntArray( int N, /* The number of integers to encode */ u32 *a, /* The integer values */ char *zBuf, /* Write the BLOB here */ int *pNBuf /* Write number of bytes if zBuf[] used here */ ){ int i, j; for(i=j=0; iiPrevDocid. The sizes are encoded as ** a blob of varints. */ static void fts3InsertDocsize( int *pRC, /* Result code */ Fts3Table *p, /* Table into which to insert */ u32 *aSz /* Sizes of each column, in tokens */ ){ char *pBlob; /* The BLOB encoding of the document size */ int nBlob; /* Number of bytes in the BLOB */ sqlite3_stmt *pStmt; /* Statement used to insert the encoding */ int rc; /* Result code from subfunctions */ if( *pRC ) return; pBlob = sqlite3_malloc( 10*p->nColumn ); if( pBlob==0 ){ *pRC = SQLITE_NOMEM; return; } fts3EncodeIntArray(p->nColumn, aSz, pBlob, &nBlob); rc = fts3SqlStmt(p, SQL_REPLACE_DOCSIZE, &pStmt, 0); if( rc ){ sqlite3_free(pBlob); *pRC = rc; return; } sqlite3_bind_int64(pStmt, 1, p->iPrevDocid); sqlite3_bind_blob(pStmt, 2, pBlob, nBlob, sqlite3_free); sqlite3_step(pStmt); *pRC = sqlite3_reset(pStmt); } /* ** Record 0 of the %_stat table contains a blob consisting of N varints, ** where N is the number of user defined columns in the fts3 table plus ** two. If nCol is the number of user defined columns, then values of the ** varints are set as follows: ** ** Varint 0: Total number of rows in the table. ** ** Varint 1..nCol: For each column, the total number of tokens stored in ** the column for all rows of the table. ** ** Varint 1+nCol: The total size, in bytes, of all text values in all ** columns of all rows of the table. ** */ static void fts3UpdateDocTotals( int *pRC, /* The result code */ Fts3Table *p, /* Table being updated */ u32 *aSzIns, /* Size increases */ u32 *aSzDel, /* Size decreases */ int nChng /* Change in the number of documents */ ){ char *pBlob; /* Storage for BLOB written into %_stat */ int nBlob; /* Size of BLOB written into %_stat */ u32 *a; /* Array of integers that becomes the BLOB */ sqlite3_stmt *pStmt; /* Statement for reading and writing */ int i; /* Loop counter */ int rc; /* Result code from subfunctions */ const int nStat = p->nColumn+2; if( *pRC ) return; a = sqlite3_malloc( (sizeof(u32)+10)*nStat ); if( a==0 ){ *pRC = SQLITE_NOMEM; return; } pBlob = (char*)&a[nStat]; rc = fts3SqlStmt(p, SQL_SELECT_STAT, &pStmt, 0); if( rc ){ sqlite3_free(a); *pRC = rc; return; } sqlite3_bind_int(pStmt, 1, FTS_STAT_DOCTOTAL); if( sqlite3_step(pStmt)==SQLITE_ROW ){ fts3DecodeIntArray(nStat, a, sqlite3_column_blob(pStmt, 0), sqlite3_column_bytes(pStmt, 0)); }else{ memset(a, 0, sizeof(u32)*(nStat) ); } rc = sqlite3_reset(pStmt); if( rc!=SQLITE_OK ){ sqlite3_free(a); *pRC = rc; return; } if( nChng<0 && a[0]<(u32)(-nChng) ){ a[0] = 0; }else{ a[0] += nChng; } for(i=0; inColumn+1; i++){ u32 x = a[i+1]; if( x+aSzIns[i] < aSzDel[i] ){ x = 0; }else{ x = x + aSzIns[i] - aSzDel[i]; } a[i+1] = x; } fts3EncodeIntArray(nStat, a, pBlob, &nBlob); rc = fts3SqlStmt(p, SQL_REPLACE_STAT, &pStmt, 0); if( rc ){ sqlite3_free(a); *pRC = rc; return; } sqlite3_bind_int(pStmt, 1, FTS_STAT_DOCTOTAL); sqlite3_bind_blob(pStmt, 2, pBlob, nBlob, SQLITE_STATIC); sqlite3_step(pStmt); *pRC = sqlite3_reset(pStmt); sqlite3_free(a); } /* ** Merge the entire database so that there is one segment for each ** iIndex/iLangid combination. */ static int fts3DoOptimize(Fts3Table *p, int bReturnDone){ int bSeenDone = 0; int rc; sqlite3_stmt *pAllLangid = 0; rc = fts3SqlStmt(p, SQL_SELECT_ALL_LANGID, &pAllLangid, 0); if( rc==SQLITE_OK ){ int rc2; sqlite3_bind_int(pAllLangid, 1, p->iPrevLangid); sqlite3_bind_int(pAllLangid, 2, p->nIndex); while( sqlite3_step(pAllLangid)==SQLITE_ROW ){ int i; int iLangid = sqlite3_column_int(pAllLangid, 0); for(i=0; rc==SQLITE_OK && inIndex; i++){ rc = fts3SegmentMerge(p, iLangid, i, FTS3_SEGCURSOR_ALL); if( rc==SQLITE_DONE ){ bSeenDone = 1; rc = SQLITE_OK; } } } rc2 = sqlite3_reset(pAllLangid); if( rc==SQLITE_OK ) rc = rc2; } sqlite3Fts3SegmentsClose(p); sqlite3Fts3PendingTermsClear(p); return (rc==SQLITE_OK && bReturnDone && bSeenDone) ? SQLITE_DONE : rc; } /* ** This function is called when the user executes the following statement: ** ** INSERT INTO () VALUES('rebuild'); ** ** The entire FTS index is discarded and rebuilt. If the table is one ** created using the content=xxx option, then the new index is based on ** the current contents of the xxx table. Otherwise, it is rebuilt based ** on the contents of the %_content table. */ static int fts3DoRebuild(Fts3Table *p){ int rc; /* Return Code */ rc = fts3DeleteAll(p, 0); if( rc==SQLITE_OK ){ u32 *aSz = 0; u32 *aSzIns = 0; u32 *aSzDel = 0; sqlite3_stmt *pStmt = 0; int nEntry = 0; /* Compose and prepare an SQL statement to loop through the content table */ char *zSql = sqlite3_mprintf("SELECT %s" , p->zReadExprlist); if( !zSql ){ rc = SQLITE_NOMEM; }else{ rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0); sqlite3_free(zSql); } if( rc==SQLITE_OK ){ int nByte = sizeof(u32) * (p->nColumn+1)*3; aSz = (u32 *)sqlite3_malloc(nByte); if( aSz==0 ){ rc = SQLITE_NOMEM; }else{ memset(aSz, 0, nByte); aSzIns = &aSz[p->nColumn+1]; aSzDel = &aSzIns[p->nColumn+1]; } } while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){ int iCol; int iLangid = langidFromSelect(p, pStmt); rc = fts3PendingTermsDocid(p, 0, iLangid, sqlite3_column_int64(pStmt, 0)); memset(aSz, 0, sizeof(aSz[0]) * (p->nColumn+1)); for(iCol=0; rc==SQLITE_OK && iColnColumn; iCol++){ if( p->abNotindexed[iCol]==0 ){ const char *z = (const char *) sqlite3_column_text(pStmt, iCol+1); rc = fts3PendingTermsAdd(p, iLangid, z, iCol, &aSz[iCol]); aSz[p->nColumn] += sqlite3_column_bytes(pStmt, iCol+1); } } if( p->bHasDocsize ){ fts3InsertDocsize(&rc, p, aSz); } if( rc!=SQLITE_OK ){ sqlite3_finalize(pStmt); pStmt = 0; }else{ nEntry++; for(iCol=0; iCol<=p->nColumn; iCol++){ aSzIns[iCol] += aSz[iCol]; } } } if( p->bFts4 ){ fts3UpdateDocTotals(&rc, p, aSzIns, aSzDel, nEntry); } sqlite3_free(aSz); if( pStmt ){ int rc2 = sqlite3_finalize(pStmt); if( rc==SQLITE_OK ){ rc = rc2; } } } return rc; } /* ** This function opens a cursor used to read the input data for an ** incremental merge operation. Specifically, it opens a cursor to scan ** the oldest nSeg segments (idx=0 through idx=(nSeg-1)) in absolute ** level iAbsLevel. */ static int fts3IncrmergeCsr( Fts3Table *p, /* FTS3 table handle */ sqlite3_int64 iAbsLevel, /* Absolute level to open */ int nSeg, /* Number of segments to merge */ Fts3MultiSegReader *pCsr /* Cursor object to populate */ ){ int rc; /* Return Code */ sqlite3_stmt *pStmt = 0; /* Statement used to read %_segdir entry */ int nByte; /* Bytes allocated at pCsr->apSegment[] */ /* Allocate space for the Fts3MultiSegReader.aCsr[] array */ memset(pCsr, 0, sizeof(*pCsr)); nByte = sizeof(Fts3SegReader *) * nSeg; pCsr->apSegment = (Fts3SegReader **)sqlite3_malloc(nByte); if( pCsr->apSegment==0 ){ rc = SQLITE_NOMEM; }else{ memset(pCsr->apSegment, 0, nByte); rc = fts3SqlStmt(p, SQL_SELECT_LEVEL, &pStmt, 0); } if( rc==SQLITE_OK ){ int i; int rc2; sqlite3_bind_int64(pStmt, 1, iAbsLevel); assert( pCsr->nSegment==0 ); for(i=0; rc==SQLITE_OK && sqlite3_step(pStmt)==SQLITE_ROW && iapSegment[i] ); pCsr->nSegment++; } rc2 = sqlite3_reset(pStmt); if( rc==SQLITE_OK ) rc = rc2; } return rc; } typedef struct IncrmergeWriter IncrmergeWriter; typedef struct NodeWriter NodeWriter; typedef struct Blob Blob; typedef struct NodeReader NodeReader; /* ** An instance of the following structure is used as a dynamic buffer ** to build up nodes or other blobs of data in. ** ** The function blobGrowBuffer() is used to extend the allocation. */ struct Blob { char *a; /* Pointer to allocation */ int n; /* Number of valid bytes of data in a[] */ int nAlloc; /* Allocated size of a[] (nAlloc>=n) */ }; /* ** This structure is used to build up buffers containing segment b-tree ** nodes (blocks). */ struct NodeWriter { sqlite3_int64 iBlock; /* Current block id */ Blob key; /* Last key written to the current block */ Blob block; /* Current block image */ }; /* ** An object of this type contains the state required to create or append ** to an appendable b-tree segment. */ struct IncrmergeWriter { int nLeafEst; /* Space allocated for leaf blocks */ int nWork; /* Number of leaf pages flushed */ sqlite3_int64 iAbsLevel; /* Absolute level of input segments */ int iIdx; /* Index of *output* segment in iAbsLevel+1 */ sqlite3_int64 iStart; /* Block number of first allocated block */ sqlite3_int64 iEnd; /* Block number of last allocated block */ sqlite3_int64 nLeafData; /* Bytes of leaf page data so far */ u8 bNoLeafData; /* If true, store 0 for segment size */ NodeWriter aNodeWriter[FTS_MAX_APPENDABLE_HEIGHT]; }; /* ** An object of the following type is used to read data from a single ** FTS segment node. See the following functions: ** ** nodeReaderInit() ** nodeReaderNext() ** nodeReaderRelease() */ struct NodeReader { const char *aNode; int nNode; int iOff; /* Current offset within aNode[] */ /* Output variables. Containing the current node entry. */ sqlite3_int64 iChild; /* Pointer to child node */ Blob term; /* Current term */ const char *aDoclist; /* Pointer to doclist */ int nDoclist; /* Size of doclist in bytes */ }; /* ** If *pRc is not SQLITE_OK when this function is called, it is a no-op. ** Otherwise, if the allocation at pBlob->a is not already at least nMin ** bytes in size, extend (realloc) it to be so. ** ** If an OOM error occurs, set *pRc to SQLITE_NOMEM and leave pBlob->a ** unmodified. Otherwise, if the allocation succeeds, update pBlob->nAlloc ** to reflect the new size of the pBlob->a[] buffer. */ static void blobGrowBuffer(Blob *pBlob, int nMin, int *pRc){ if( *pRc==SQLITE_OK && nMin>pBlob->nAlloc ){ int nAlloc = nMin; char *a = (char *)sqlite3_realloc(pBlob->a, nAlloc); if( a ){ pBlob->nAlloc = nAlloc; pBlob->a = a; }else{ *pRc = SQLITE_NOMEM; } } } /* ** Attempt to advance the node-reader object passed as the first argument to ** the next entry on the node. ** ** Return an error code if an error occurs (SQLITE_NOMEM is possible). ** Otherwise return SQLITE_OK. If there is no next entry on the node ** (e.g. because the current entry is the last) set NodeReader->aNode to ** NULL to indicate EOF. Otherwise, populate the NodeReader structure output ** variables for the new entry. */ static int nodeReaderNext(NodeReader *p){ int bFirst = (p->term.n==0); /* True for first term on the node */ int nPrefix = 0; /* Bytes to copy from previous term */ int nSuffix = 0; /* Bytes to append to the prefix */ int rc = SQLITE_OK; /* Return code */ assert( p->aNode ); if( p->iChild && bFirst==0 ) p->iChild++; if( p->iOff>=p->nNode ){ /* EOF */ p->aNode = 0; }else{ if( bFirst==0 ){ p->iOff += fts3GetVarint32(&p->aNode[p->iOff], &nPrefix); } p->iOff += fts3GetVarint32(&p->aNode[p->iOff], &nSuffix); blobGrowBuffer(&p->term, nPrefix+nSuffix, &rc); if( rc==SQLITE_OK ){ memcpy(&p->term.a[nPrefix], &p->aNode[p->iOff], nSuffix); p->term.n = nPrefix+nSuffix; p->iOff += nSuffix; if( p->iChild==0 ){ p->iOff += fts3GetVarint32(&p->aNode[p->iOff], &p->nDoclist); p->aDoclist = &p->aNode[p->iOff]; p->iOff += p->nDoclist; } } } assert( p->iOff<=p->nNode ); return rc; } /* ** Release all dynamic resources held by node-reader object *p. */ static void nodeReaderRelease(NodeReader *p){ sqlite3_free(p->term.a); } /* ** Initialize a node-reader object to read the node in buffer aNode/nNode. ** ** If successful, SQLITE_OK is returned and the NodeReader object set to ** point to the first entry on the node (if any). Otherwise, an SQLite ** error code is returned. */ static int nodeReaderInit(NodeReader *p, const char *aNode, int nNode){ memset(p, 0, sizeof(NodeReader)); p->aNode = aNode; p->nNode = nNode; /* Figure out if this is a leaf or an internal node. */ if( p->aNode[0] ){ /* An internal node. */ p->iOff = 1 + sqlite3Fts3GetVarint(&p->aNode[1], &p->iChild); }else{ p->iOff = 1; } return nodeReaderNext(p); } /* ** This function is called while writing an FTS segment each time a leaf o ** node is finished and written to disk. The key (zTerm/nTerm) is guaranteed ** to be greater than the largest key on the node just written, but smaller ** than or equal to the first key that will be written to the next leaf ** node. ** ** The block id of the leaf node just written to disk may be found in ** (pWriter->aNodeWriter[0].iBlock) when this function is called. */ static int fts3IncrmergePush( Fts3Table *p, /* Fts3 table handle */ IncrmergeWriter *pWriter, /* Writer object */ const char *zTerm, /* Term to write to internal node */ int nTerm /* Bytes at zTerm */ ){ sqlite3_int64 iPtr = pWriter->aNodeWriter[0].iBlock; int iLayer; assert( nTerm>0 ); for(iLayer=1; ALWAYS(iLayeraNodeWriter[iLayer]; int rc = SQLITE_OK; int nPrefix; int nSuffix; int nSpace; /* Figure out how much space the key will consume if it is written to ** the current node of layer iLayer. Due to the prefix compression, ** the space required changes depending on which node the key is to ** be added to. */ nPrefix = fts3PrefixCompress(pNode->key.a, pNode->key.n, zTerm, nTerm); nSuffix = nTerm - nPrefix; nSpace = sqlite3Fts3VarintLen(nPrefix); nSpace += sqlite3Fts3VarintLen(nSuffix) + nSuffix; if( pNode->key.n==0 || (pNode->block.n + nSpace)<=p->nNodeSize ){ /* If the current node of layer iLayer contains zero keys, or if adding ** the key to it will not cause it to grow to larger than nNodeSize ** bytes in size, write the key here. */ Blob *pBlk = &pNode->block; if( pBlk->n==0 ){ blobGrowBuffer(pBlk, p->nNodeSize, &rc); if( rc==SQLITE_OK ){ pBlk->a[0] = (char)iLayer; pBlk->n = 1 + sqlite3Fts3PutVarint(&pBlk->a[1], iPtr); } } blobGrowBuffer(pBlk, pBlk->n + nSpace, &rc); blobGrowBuffer(&pNode->key, nTerm, &rc); if( rc==SQLITE_OK ){ if( pNode->key.n ){ pBlk->n += sqlite3Fts3PutVarint(&pBlk->a[pBlk->n], nPrefix); } pBlk->n += sqlite3Fts3PutVarint(&pBlk->a[pBlk->n], nSuffix); memcpy(&pBlk->a[pBlk->n], &zTerm[nPrefix], nSuffix); pBlk->n += nSuffix; memcpy(pNode->key.a, zTerm, nTerm); pNode->key.n = nTerm; } }else{ /* Otherwise, flush the current node of layer iLayer to disk. ** Then allocate a new, empty sibling node. The key will be written ** into the parent of this node. */ rc = fts3WriteSegment(p, pNode->iBlock, pNode->block.a, pNode->block.n); assert( pNode->block.nAlloc>=p->nNodeSize ); pNode->block.a[0] = (char)iLayer; pNode->block.n = 1 + sqlite3Fts3PutVarint(&pNode->block.a[1], iPtr+1); iNextPtr = pNode->iBlock; pNode->iBlock++; pNode->key.n = 0; } if( rc!=SQLITE_OK || iNextPtr==0 ) return rc; iPtr = iNextPtr; } assert( 0 ); return 0; } /* ** Append a term and (optionally) doclist to the FTS segment node currently ** stored in blob *pNode. The node need not contain any terms, but the ** header must be written before this function is called. ** ** A node header is a single 0x00 byte for a leaf node, or a height varint ** followed by the left-hand-child varint for an internal node. ** ** The term to be appended is passed via arguments zTerm/nTerm. For a ** leaf node, the doclist is passed as aDoclist/nDoclist. For an internal ** node, both aDoclist and nDoclist must be passed 0. ** ** If the size of the value in blob pPrev is zero, then this is the first ** term written to the node. Otherwise, pPrev contains a copy of the ** previous term. Before this function returns, it is updated to contain a ** copy of zTerm/nTerm. ** ** It is assumed that the buffer associated with pNode is already large ** enough to accommodate the new entry. The buffer associated with pPrev ** is extended by this function if requrired. ** ** If an error (i.e. OOM condition) occurs, an SQLite error code is ** returned. Otherwise, SQLITE_OK. */ static int fts3AppendToNode( Blob *pNode, /* Current node image to append to */ Blob *pPrev, /* Buffer containing previous term written */ const char *zTerm, /* New term to write */ int nTerm, /* Size of zTerm in bytes */ const char *aDoclist, /* Doclist (or NULL) to write */ int nDoclist /* Size of aDoclist in bytes */ ){ int rc = SQLITE_OK; /* Return code */ int bFirst = (pPrev->n==0); /* True if this is the first term written */ int nPrefix; /* Size of term prefix in bytes */ int nSuffix; /* Size of term suffix in bytes */ /* Node must have already been started. There must be a doclist for a ** leaf node, and there must not be a doclist for an internal node. */ assert( pNode->n>0 ); assert( (pNode->a[0]=='\0')==(aDoclist!=0) ); blobGrowBuffer(pPrev, nTerm, &rc); if( rc!=SQLITE_OK ) return rc; nPrefix = fts3PrefixCompress(pPrev->a, pPrev->n, zTerm, nTerm); nSuffix = nTerm - nPrefix; memcpy(pPrev->a, zTerm, nTerm); pPrev->n = nTerm; if( bFirst==0 ){ pNode->n += sqlite3Fts3PutVarint(&pNode->a[pNode->n], nPrefix); } pNode->n += sqlite3Fts3PutVarint(&pNode->a[pNode->n], nSuffix); memcpy(&pNode->a[pNode->n], &zTerm[nPrefix], nSuffix); pNode->n += nSuffix; if( aDoclist ){ pNode->n += sqlite3Fts3PutVarint(&pNode->a[pNode->n], nDoclist); memcpy(&pNode->a[pNode->n], aDoclist, nDoclist); pNode->n += nDoclist; } assert( pNode->n<=pNode->nAlloc ); return SQLITE_OK; } /* ** Append the current term and doclist pointed to by cursor pCsr to the ** appendable b-tree segment opened for writing by pWriter. ** ** Return SQLITE_OK if successful, or an SQLite error code otherwise. */ static int fts3IncrmergeAppend( Fts3Table *p, /* Fts3 table handle */ IncrmergeWriter *pWriter, /* Writer object */ Fts3MultiSegReader *pCsr /* Cursor containing term and doclist */ ){ const char *zTerm = pCsr->zTerm; int nTerm = pCsr->nTerm; const char *aDoclist = pCsr->aDoclist; int nDoclist = pCsr->nDoclist; int rc = SQLITE_OK; /* Return code */ int nSpace; /* Total space in bytes required on leaf */ int nPrefix; /* Size of prefix shared with previous term */ int nSuffix; /* Size of suffix (nTerm - nPrefix) */ NodeWriter *pLeaf; /* Object used to write leaf nodes */ pLeaf = &pWriter->aNodeWriter[0]; nPrefix = fts3PrefixCompress(pLeaf->key.a, pLeaf->key.n, zTerm, nTerm); nSuffix = nTerm - nPrefix; nSpace = sqlite3Fts3VarintLen(nPrefix); nSpace += sqlite3Fts3VarintLen(nSuffix) + nSuffix; nSpace += sqlite3Fts3VarintLen(nDoclist) + nDoclist; /* If the current block is not empty, and if adding this term/doclist ** to the current block would make it larger than Fts3Table.nNodeSize ** bytes, write this block out to the database. */ if( pLeaf->block.n>0 && (pLeaf->block.n + nSpace)>p->nNodeSize ){ rc = fts3WriteSegment(p, pLeaf->iBlock, pLeaf->block.a, pLeaf->block.n); pWriter->nWork++; /* Add the current term to the parent node. The term added to the ** parent must: ** ** a) be greater than the largest term on the leaf node just written ** to the database (still available in pLeaf->key), and ** ** b) be less than or equal to the term about to be added to the new ** leaf node (zTerm/nTerm). ** ** In other words, it must be the prefix of zTerm 1 byte longer than ** the common prefix (if any) of zTerm and pWriter->zTerm. */ if( rc==SQLITE_OK ){ rc = fts3IncrmergePush(p, pWriter, zTerm, nPrefix+1); } /* Advance to the next output block */ pLeaf->iBlock++; pLeaf->key.n = 0; pLeaf->block.n = 0; nSuffix = nTerm; nSpace = 1; nSpace += sqlite3Fts3VarintLen(nSuffix) + nSuffix; nSpace += sqlite3Fts3VarintLen(nDoclist) + nDoclist; } pWriter->nLeafData += nSpace; blobGrowBuffer(&pLeaf->block, pLeaf->block.n + nSpace, &rc); if( rc==SQLITE_OK ){ if( pLeaf->block.n==0 ){ pLeaf->block.n = 1; pLeaf->block.a[0] = '\0'; } rc = fts3AppendToNode( &pLeaf->block, &pLeaf->key, zTerm, nTerm, aDoclist, nDoclist ); } return rc; } /* ** This function is called to release all dynamic resources held by the ** merge-writer object pWriter, and if no error has occurred, to flush ** all outstanding node buffers held by pWriter to disk. ** ** If *pRc is not SQLITE_OK when this function is called, then no attempt ** is made to write any data to disk. Instead, this function serves only ** to release outstanding resources. ** ** Otherwise, if *pRc is initially SQLITE_OK and an error occurs while ** flushing buffers to disk, *pRc is set to an SQLite error code before ** returning. */ static void fts3IncrmergeRelease( Fts3Table *p, /* FTS3 table handle */ IncrmergeWriter *pWriter, /* Merge-writer object */ int *pRc /* IN/OUT: Error code */ ){ int i; /* Used to iterate through non-root layers */ int iRoot; /* Index of root in pWriter->aNodeWriter */ NodeWriter *pRoot; /* NodeWriter for root node */ int rc = *pRc; /* Error code */ /* Set iRoot to the index in pWriter->aNodeWriter[] of the output segment ** root node. If the segment fits entirely on a single leaf node, iRoot ** will be set to 0. If the root node is the parent of the leaves, iRoot ** will be 1. And so on. */ for(iRoot=FTS_MAX_APPENDABLE_HEIGHT-1; iRoot>=0; iRoot--){ NodeWriter *pNode = &pWriter->aNodeWriter[iRoot]; if( pNode->block.n>0 ) break; assert( *pRc || pNode->block.nAlloc==0 ); assert( *pRc || pNode->key.nAlloc==0 ); sqlite3_free(pNode->block.a); sqlite3_free(pNode->key.a); } /* Empty output segment. This is a no-op. */ if( iRoot<0 ) return; /* The entire output segment fits on a single node. Normally, this means ** the node would be stored as a blob in the "root" column of the %_segdir ** table. However, this is not permitted in this case. The problem is that ** space has already been reserved in the %_segments table, and so the ** start_block and end_block fields of the %_segdir table must be populated. ** And, by design or by accident, released versions of FTS cannot handle ** segments that fit entirely on the root node with start_block!=0. ** ** Instead, create a synthetic root node that contains nothing but a ** pointer to the single content node. So that the segment consists of a ** single leaf and a single interior (root) node. ** ** Todo: Better might be to defer allocating space in the %_segments ** table until we are sure it is needed. */ if( iRoot==0 ){ Blob *pBlock = &pWriter->aNodeWriter[1].block; blobGrowBuffer(pBlock, 1 + FTS3_VARINT_MAX, &rc); if( rc==SQLITE_OK ){ pBlock->a[0] = 0x01; pBlock->n = 1 + sqlite3Fts3PutVarint( &pBlock->a[1], pWriter->aNodeWriter[0].iBlock ); } iRoot = 1; } pRoot = &pWriter->aNodeWriter[iRoot]; /* Flush all currently outstanding nodes to disk. */ for(i=0; iaNodeWriter[i]; if( pNode->block.n>0 && rc==SQLITE_OK ){ rc = fts3WriteSegment(p, pNode->iBlock, pNode->block.a, pNode->block.n); } sqlite3_free(pNode->block.a); sqlite3_free(pNode->key.a); } /* Write the %_segdir record. */ if( rc==SQLITE_OK ){ rc = fts3WriteSegdir(p, pWriter->iAbsLevel+1, /* level */ pWriter->iIdx, /* idx */ pWriter->iStart, /* start_block */ pWriter->aNodeWriter[0].iBlock, /* leaves_end_block */ pWriter->iEnd, /* end_block */ (pWriter->bNoLeafData==0 ? pWriter->nLeafData : 0), /* end_block */ pRoot->block.a, pRoot->block.n /* root */ ); } sqlite3_free(pRoot->block.a); sqlite3_free(pRoot->key.a); *pRc = rc; } /* ** Compare the term in buffer zLhs (size in bytes nLhs) with that in ** zRhs (size in bytes nRhs) using memcmp. If one term is a prefix of ** the other, it is considered to be smaller than the other. ** ** Return -ve if zLhs is smaller than zRhs, 0 if it is equal, or +ve ** if it is greater. */ static int fts3TermCmp( const char *zLhs, int nLhs, /* LHS of comparison */ const char *zRhs, int nRhs /* RHS of comparison */ ){ int nCmp = MIN(nLhs, nRhs); int res; res = memcmp(zLhs, zRhs, nCmp); if( res==0 ) res = nLhs - nRhs; return res; } /* ** Query to see if the entry in the %_segments table with blockid iEnd is ** NULL. If no error occurs and the entry is NULL, set *pbRes 1 before ** returning. Otherwise, set *pbRes to 0. ** ** Or, if an error occurs while querying the database, return an SQLite ** error code. The final value of *pbRes is undefined in this case. ** ** This is used to test if a segment is an "appendable" segment. If it ** is, then a NULL entry has been inserted into the %_segments table ** with blockid %_segdir.end_block. */ static int fts3IsAppendable(Fts3Table *p, sqlite3_int64 iEnd, int *pbRes){ int bRes = 0; /* Result to set *pbRes to */ sqlite3_stmt *pCheck = 0; /* Statement to query database with */ int rc; /* Return code */ rc = fts3SqlStmt(p, SQL_SEGMENT_IS_APPENDABLE, &pCheck, 0); if( rc==SQLITE_OK ){ sqlite3_bind_int64(pCheck, 1, iEnd); if( SQLITE_ROW==sqlite3_step(pCheck) ) bRes = 1; rc = sqlite3_reset(pCheck); } *pbRes = bRes; return rc; } /* ** This function is called when initializing an incremental-merge operation. ** It checks if the existing segment with index value iIdx at absolute level ** (iAbsLevel+1) can be appended to by the incremental merge. If it can, the ** merge-writer object *pWriter is initialized to write to it. ** ** An existing segment can be appended to by an incremental merge if: ** ** * It was initially created as an appendable segment (with all required ** space pre-allocated), and ** ** * The first key read from the input (arguments zKey and nKey) is ** greater than the largest key currently stored in the potential ** output segment. */ static int fts3IncrmergeLoad( Fts3Table *p, /* Fts3 table handle */ sqlite3_int64 iAbsLevel, /* Absolute level of input segments */ int iIdx, /* Index of candidate output segment */ const char *zKey, /* First key to write */ int nKey, /* Number of bytes in nKey */ IncrmergeWriter *pWriter /* Populate this object */ ){ int rc; /* Return code */ sqlite3_stmt *pSelect = 0; /* SELECT to read %_segdir entry */ rc = fts3SqlStmt(p, SQL_SELECT_SEGDIR, &pSelect, 0); if( rc==SQLITE_OK ){ sqlite3_int64 iStart = 0; /* Value of %_segdir.start_block */ sqlite3_int64 iLeafEnd = 0; /* Value of %_segdir.leaves_end_block */ sqlite3_int64 iEnd = 0; /* Value of %_segdir.end_block */ const char *aRoot = 0; /* Pointer to %_segdir.root buffer */ int nRoot = 0; /* Size of aRoot[] in bytes */ int rc2; /* Return code from sqlite3_reset() */ int bAppendable = 0; /* Set to true if segment is appendable */ /* Read the %_segdir entry for index iIdx absolute level (iAbsLevel+1) */ sqlite3_bind_int64(pSelect, 1, iAbsLevel+1); sqlite3_bind_int(pSelect, 2, iIdx); if( sqlite3_step(pSelect)==SQLITE_ROW ){ iStart = sqlite3_column_int64(pSelect, 1); iLeafEnd = sqlite3_column_int64(pSelect, 2); fts3ReadEndBlockField(pSelect, 3, &iEnd, &pWriter->nLeafData); if( pWriter->nLeafData<0 ){ pWriter->nLeafData = pWriter->nLeafData * -1; } pWriter->bNoLeafData = (pWriter->nLeafData==0); nRoot = sqlite3_column_bytes(pSelect, 4); aRoot = sqlite3_column_blob(pSelect, 4); }else{ return sqlite3_reset(pSelect); } /* Check for the zero-length marker in the %_segments table */ rc = fts3IsAppendable(p, iEnd, &bAppendable); /* Check that zKey/nKey is larger than the largest key the candidate */ if( rc==SQLITE_OK && bAppendable ){ char *aLeaf = 0; int nLeaf = 0; rc = sqlite3Fts3ReadBlock(p, iLeafEnd, &aLeaf, &nLeaf, 0); if( rc==SQLITE_OK ){ NodeReader reader; for(rc = nodeReaderInit(&reader, aLeaf, nLeaf); rc==SQLITE_OK && reader.aNode; rc = nodeReaderNext(&reader) ){ assert( reader.aNode ); } if( fts3TermCmp(zKey, nKey, reader.term.a, reader.term.n)<=0 ){ bAppendable = 0; } nodeReaderRelease(&reader); } sqlite3_free(aLeaf); } if( rc==SQLITE_OK && bAppendable ){ /* It is possible to append to this segment. Set up the IncrmergeWriter ** object to do so. */ int i; int nHeight = (int)aRoot[0]; NodeWriter *pNode; pWriter->nLeafEst = (int)((iEnd - iStart) + 1)/FTS_MAX_APPENDABLE_HEIGHT; pWriter->iStart = iStart; pWriter->iEnd = iEnd; pWriter->iAbsLevel = iAbsLevel; pWriter->iIdx = iIdx; for(i=nHeight+1; iaNodeWriter[i].iBlock = pWriter->iStart + i*pWriter->nLeafEst; } pNode = &pWriter->aNodeWriter[nHeight]; pNode->iBlock = pWriter->iStart + pWriter->nLeafEst*nHeight; blobGrowBuffer(&pNode->block, MAX(nRoot, p->nNodeSize), &rc); if( rc==SQLITE_OK ){ memcpy(pNode->block.a, aRoot, nRoot); pNode->block.n = nRoot; } for(i=nHeight; i>=0 && rc==SQLITE_OK; i--){ NodeReader reader; pNode = &pWriter->aNodeWriter[i]; rc = nodeReaderInit(&reader, pNode->block.a, pNode->block.n); while( reader.aNode && rc==SQLITE_OK ) rc = nodeReaderNext(&reader); blobGrowBuffer(&pNode->key, reader.term.n, &rc); if( rc==SQLITE_OK ){ memcpy(pNode->key.a, reader.term.a, reader.term.n); pNode->key.n = reader.term.n; if( i>0 ){ char *aBlock = 0; int nBlock = 0; pNode = &pWriter->aNodeWriter[i-1]; pNode->iBlock = reader.iChild; rc = sqlite3Fts3ReadBlock(p, reader.iChild, &aBlock, &nBlock, 0); blobGrowBuffer(&pNode->block, MAX(nBlock, p->nNodeSize), &rc); if( rc==SQLITE_OK ){ memcpy(pNode->block.a, aBlock, nBlock); pNode->block.n = nBlock; } sqlite3_free(aBlock); } } nodeReaderRelease(&reader); } } rc2 = sqlite3_reset(pSelect); if( rc==SQLITE_OK ) rc = rc2; } return rc; } /* ** Determine the largest segment index value that exists within absolute ** level iAbsLevel+1. If no error occurs, set *piIdx to this value plus ** one before returning SQLITE_OK. Or, if there are no segments at all ** within level iAbsLevel, set *piIdx to zero. ** ** If an error occurs, return an SQLite error code. The final value of ** *piIdx is undefined in this case. */ static int fts3IncrmergeOutputIdx( Fts3Table *p, /* FTS Table handle */ sqlite3_int64 iAbsLevel, /* Absolute index of input segments */ int *piIdx /* OUT: Next free index at iAbsLevel+1 */ ){ int rc; sqlite3_stmt *pOutputIdx = 0; /* SQL used to find output index */ rc = fts3SqlStmt(p, SQL_NEXT_SEGMENT_INDEX, &pOutputIdx, 0); if( rc==SQLITE_OK ){ sqlite3_bind_int64(pOutputIdx, 1, iAbsLevel+1); sqlite3_step(pOutputIdx); *piIdx = sqlite3_column_int(pOutputIdx, 0); rc = sqlite3_reset(pOutputIdx); } return rc; } /* ** Allocate an appendable output segment on absolute level iAbsLevel+1 ** with idx value iIdx. ** ** In the %_segdir table, a segment is defined by the values in three ** columns: ** ** start_block ** leaves_end_block ** end_block ** ** When an appendable segment is allocated, it is estimated that the ** maximum number of leaf blocks that may be required is the sum of the ** number of leaf blocks consumed by the input segments, plus the number ** of input segments, multiplied by two. This value is stored in stack ** variable nLeafEst. ** ** A total of 16*nLeafEst blocks are allocated when an appendable segment ** is created ((1 + end_block - start_block)==16*nLeafEst). The contiguous ** array of leaf nodes starts at the first block allocated. The array ** of interior nodes that are parents of the leaf nodes start at block ** (start_block + (1 + end_block - start_block) / 16). And so on. ** ** In the actual code below, the value "16" is replaced with the ** pre-processor macro FTS_MAX_APPENDABLE_HEIGHT. */ static int fts3IncrmergeWriter( Fts3Table *p, /* Fts3 table handle */ sqlite3_int64 iAbsLevel, /* Absolute level of input segments */ int iIdx, /* Index of new output segment */ Fts3MultiSegReader *pCsr, /* Cursor that data will be read from */ IncrmergeWriter *pWriter /* Populate this object */ ){ int rc; /* Return Code */ int i; /* Iterator variable */ int nLeafEst = 0; /* Blocks allocated for leaf nodes */ sqlite3_stmt *pLeafEst = 0; /* SQL used to determine nLeafEst */ sqlite3_stmt *pFirstBlock = 0; /* SQL used to determine first block */ /* Calculate nLeafEst. */ rc = fts3SqlStmt(p, SQL_MAX_LEAF_NODE_ESTIMATE, &pLeafEst, 0); if( rc==SQLITE_OK ){ sqlite3_bind_int64(pLeafEst, 1, iAbsLevel); sqlite3_bind_int64(pLeafEst, 2, pCsr->nSegment); if( SQLITE_ROW==sqlite3_step(pLeafEst) ){ nLeafEst = sqlite3_column_int(pLeafEst, 0); } rc = sqlite3_reset(pLeafEst); } if( rc!=SQLITE_OK ) return rc; /* Calculate the first block to use in the output segment */ rc = fts3SqlStmt(p, SQL_NEXT_SEGMENTS_ID, &pFirstBlock, 0); if( rc==SQLITE_OK ){ if( SQLITE_ROW==sqlite3_step(pFirstBlock) ){ pWriter->iStart = sqlite3_column_int64(pFirstBlock, 0); pWriter->iEnd = pWriter->iStart - 1; pWriter->iEnd += nLeafEst * FTS_MAX_APPENDABLE_HEIGHT; } rc = sqlite3_reset(pFirstBlock); } if( rc!=SQLITE_OK ) return rc; /* Insert the marker in the %_segments table to make sure nobody tries ** to steal the space just allocated. This is also used to identify ** appendable segments. */ rc = fts3WriteSegment(p, pWriter->iEnd, 0, 0); if( rc!=SQLITE_OK ) return rc; pWriter->iAbsLevel = iAbsLevel; pWriter->nLeafEst = nLeafEst; pWriter->iIdx = iIdx; /* Set up the array of NodeWriter objects */ for(i=0; iaNodeWriter[i].iBlock = pWriter->iStart + i*pWriter->nLeafEst; } return SQLITE_OK; } /* ** Remove an entry from the %_segdir table. This involves running the ** following two statements: ** ** DELETE FROM %_segdir WHERE level = :iAbsLevel AND idx = :iIdx ** UPDATE %_segdir SET idx = idx - 1 WHERE level = :iAbsLevel AND idx > :iIdx ** ** The DELETE statement removes the specific %_segdir level. The UPDATE ** statement ensures that the remaining segments have contiguously allocated ** idx values. */ static int fts3RemoveSegdirEntry( Fts3Table *p, /* FTS3 table handle */ sqlite3_int64 iAbsLevel, /* Absolute level to delete from */ int iIdx /* Index of %_segdir entry to delete */ ){ int rc; /* Return code */ sqlite3_stmt *pDelete = 0; /* DELETE statement */ rc = fts3SqlStmt(p, SQL_DELETE_SEGDIR_ENTRY, &pDelete, 0); if( rc==SQLITE_OK ){ sqlite3_bind_int64(pDelete, 1, iAbsLevel); sqlite3_bind_int(pDelete, 2, iIdx); sqlite3_step(pDelete); rc = sqlite3_reset(pDelete); } return rc; } /* ** One or more segments have just been removed from absolute level iAbsLevel. ** Update the 'idx' values of the remaining segments in the level so that ** the idx values are a contiguous sequence starting from 0. */ static int fts3RepackSegdirLevel( Fts3Table *p, /* FTS3 table handle */ sqlite3_int64 iAbsLevel /* Absolute level to repack */ ){ int rc; /* Return code */ int *aIdx = 0; /* Array of remaining idx values */ int nIdx = 0; /* Valid entries in aIdx[] */ int nAlloc = 0; /* Allocated size of aIdx[] */ int i; /* Iterator variable */ sqlite3_stmt *pSelect = 0; /* Select statement to read idx values */ sqlite3_stmt *pUpdate = 0; /* Update statement to modify idx values */ rc = fts3SqlStmt(p, SQL_SELECT_INDEXES, &pSelect, 0); if( rc==SQLITE_OK ){ int rc2; sqlite3_bind_int64(pSelect, 1, iAbsLevel); while( SQLITE_ROW==sqlite3_step(pSelect) ){ if( nIdx>=nAlloc ){ int *aNew; nAlloc += 16; aNew = sqlite3_realloc(aIdx, nAlloc*sizeof(int)); if( !aNew ){ rc = SQLITE_NOMEM; break; } aIdx = aNew; } aIdx[nIdx++] = sqlite3_column_int(pSelect, 0); } rc2 = sqlite3_reset(pSelect); if( rc==SQLITE_OK ) rc = rc2; } if( rc==SQLITE_OK ){ rc = fts3SqlStmt(p, SQL_SHIFT_SEGDIR_ENTRY, &pUpdate, 0); } if( rc==SQLITE_OK ){ sqlite3_bind_int64(pUpdate, 2, iAbsLevel); } assert( p->bIgnoreSavepoint==0 ); p->bIgnoreSavepoint = 1; for(i=0; rc==SQLITE_OK && ibIgnoreSavepoint = 0; sqlite3_free(aIdx); return rc; } static void fts3StartNode(Blob *pNode, int iHeight, sqlite3_int64 iChild){ pNode->a[0] = (char)iHeight; if( iChild ){ assert( pNode->nAlloc>=1+sqlite3Fts3VarintLen(iChild) ); pNode->n = 1 + sqlite3Fts3PutVarint(&pNode->a[1], iChild); }else{ assert( pNode->nAlloc>=1 ); pNode->n = 1; } } /* ** The first two arguments are a pointer to and the size of a segment b-tree ** node. The node may be a leaf or an internal node. ** ** This function creates a new node image in blob object *pNew by copying ** all terms that are greater than or equal to zTerm/nTerm (for leaf nodes) ** or greater than zTerm/nTerm (for internal nodes) from aNode/nNode. */ static int fts3TruncateNode( const char *aNode, /* Current node image */ int nNode, /* Size of aNode in bytes */ Blob *pNew, /* OUT: Write new node image here */ const char *zTerm, /* Omit all terms smaller than this */ int nTerm, /* Size of zTerm in bytes */ sqlite3_int64 *piBlock /* OUT: Block number in next layer down */ ){ NodeReader reader; /* Reader object */ Blob prev = {0, 0, 0}; /* Previous term written to new node */ int rc = SQLITE_OK; /* Return code */ int bLeaf = aNode[0]=='\0'; /* True for a leaf node */ /* Allocate required output space */ blobGrowBuffer(pNew, nNode, &rc); if( rc!=SQLITE_OK ) return rc; pNew->n = 0; /* Populate new node buffer */ for(rc = nodeReaderInit(&reader, aNode, nNode); rc==SQLITE_OK && reader.aNode; rc = nodeReaderNext(&reader) ){ if( pNew->n==0 ){ int res = fts3TermCmp(reader.term.a, reader.term.n, zTerm, nTerm); if( res<0 || (bLeaf==0 && res==0) ) continue; fts3StartNode(pNew, (int)aNode[0], reader.iChild); *piBlock = reader.iChild; } rc = fts3AppendToNode( pNew, &prev, reader.term.a, reader.term.n, reader.aDoclist, reader.nDoclist ); if( rc!=SQLITE_OK ) break; } if( pNew->n==0 ){ fts3StartNode(pNew, (int)aNode[0], reader.iChild); *piBlock = reader.iChild; } assert( pNew->n<=pNew->nAlloc ); nodeReaderRelease(&reader); sqlite3_free(prev.a); return rc; } /* ** Remove all terms smaller than zTerm/nTerm from segment iIdx in absolute ** level iAbsLevel. This may involve deleting entries from the %_segments ** table, and modifying existing entries in both the %_segments and %_segdir ** tables. ** ** SQLITE_OK is returned if the segment is updated successfully. Or an ** SQLite error code otherwise. */ static int fts3TruncateSegment( Fts3Table *p, /* FTS3 table handle */ sqlite3_int64 iAbsLevel, /* Absolute level of segment to modify */ int iIdx, /* Index within level of segment to modify */ const char *zTerm, /* Remove terms smaller than this */ int nTerm /* Number of bytes in buffer zTerm */ ){ int rc = SQLITE_OK; /* Return code */ Blob root = {0,0,0}; /* New root page image */ Blob block = {0,0,0}; /* Buffer used for any other block */ sqlite3_int64 iBlock = 0; /* Block id */ sqlite3_int64 iNewStart = 0; /* New value for iStartBlock */ sqlite3_int64 iOldStart = 0; /* Old value for iStartBlock */ sqlite3_stmt *pFetch = 0; /* Statement used to fetch segdir */ rc = fts3SqlStmt(p, SQL_SELECT_SEGDIR, &pFetch, 0); if( rc==SQLITE_OK ){ int rc2; /* sqlite3_reset() return code */ sqlite3_bind_int64(pFetch, 1, iAbsLevel); sqlite3_bind_int(pFetch, 2, iIdx); if( SQLITE_ROW==sqlite3_step(pFetch) ){ const char *aRoot = sqlite3_column_blob(pFetch, 4); int nRoot = sqlite3_column_bytes(pFetch, 4); iOldStart = sqlite3_column_int64(pFetch, 1); rc = fts3TruncateNode(aRoot, nRoot, &root, zTerm, nTerm, &iBlock); } rc2 = sqlite3_reset(pFetch); if( rc==SQLITE_OK ) rc = rc2; } while( rc==SQLITE_OK && iBlock ){ char *aBlock = 0; int nBlock = 0; iNewStart = iBlock; rc = sqlite3Fts3ReadBlock(p, iBlock, &aBlock, &nBlock, 0); if( rc==SQLITE_OK ){ rc = fts3TruncateNode(aBlock, nBlock, &block, zTerm, nTerm, &iBlock); } if( rc==SQLITE_OK ){ rc = fts3WriteSegment(p, iNewStart, block.a, block.n); } sqlite3_free(aBlock); } /* Variable iNewStart now contains the first valid leaf node. */ if( rc==SQLITE_OK && iNewStart ){ sqlite3_stmt *pDel = 0; rc = fts3SqlStmt(p, SQL_DELETE_SEGMENTS_RANGE, &pDel, 0); if( rc==SQLITE_OK ){ sqlite3_bind_int64(pDel, 1, iOldStart); sqlite3_bind_int64(pDel, 2, iNewStart-1); sqlite3_step(pDel); rc = sqlite3_reset(pDel); } } if( rc==SQLITE_OK ){ sqlite3_stmt *pChomp = 0; rc = fts3SqlStmt(p, SQL_CHOMP_SEGDIR, &pChomp, 0); if( rc==SQLITE_OK ){ sqlite3_bind_int64(pChomp, 1, iNewStart); sqlite3_bind_blob(pChomp, 2, root.a, root.n, SQLITE_STATIC); sqlite3_bind_int64(pChomp, 3, iAbsLevel); sqlite3_bind_int(pChomp, 4, iIdx); sqlite3_step(pChomp); rc = sqlite3_reset(pChomp); } } sqlite3_free(root.a); sqlite3_free(block.a); return rc; } /* ** This function is called after an incrmental-merge operation has run to ** merge (or partially merge) two or more segments from absolute level ** iAbsLevel. ** ** Each input segment is either removed from the db completely (if all of ** its data was copied to the output segment by the incrmerge operation) ** or modified in place so that it no longer contains those entries that ** have been duplicated in the output segment. */ static int fts3IncrmergeChomp( Fts3Table *p, /* FTS table handle */ sqlite3_int64 iAbsLevel, /* Absolute level containing segments */ Fts3MultiSegReader *pCsr, /* Chomp all segments opened by this cursor */ int *pnRem /* Number of segments not deleted */ ){ int i; int nRem = 0; int rc = SQLITE_OK; for(i=pCsr->nSegment-1; i>=0 && rc==SQLITE_OK; i--){ Fts3SegReader *pSeg = 0; int j; /* Find the Fts3SegReader object with Fts3SegReader.iIdx==i. It is hiding ** somewhere in the pCsr->apSegment[] array. */ for(j=0; ALWAYS(jnSegment); j++){ pSeg = pCsr->apSegment[j]; if( pSeg->iIdx==i ) break; } assert( jnSegment && pSeg->iIdx==i ); if( pSeg->aNode==0 ){ /* Seg-reader is at EOF. Remove the entire input segment. */ rc = fts3DeleteSegment(p, pSeg); if( rc==SQLITE_OK ){ rc = fts3RemoveSegdirEntry(p, iAbsLevel, pSeg->iIdx); } *pnRem = 0; }else{ /* The incremental merge did not copy all the data from this ** segment to the upper level. The segment is modified in place ** so that it contains no keys smaller than zTerm/nTerm. */ const char *zTerm = pSeg->zTerm; int nTerm = pSeg->nTerm; rc = fts3TruncateSegment(p, iAbsLevel, pSeg->iIdx, zTerm, nTerm); nRem++; } } if( rc==SQLITE_OK && nRem!=pCsr->nSegment ){ rc = fts3RepackSegdirLevel(p, iAbsLevel); } *pnRem = nRem; return rc; } /* ** Store an incr-merge hint in the database. */ static int fts3IncrmergeHintStore(Fts3Table *p, Blob *pHint){ sqlite3_stmt *pReplace = 0; int rc; /* Return code */ rc = fts3SqlStmt(p, SQL_REPLACE_STAT, &pReplace, 0); if( rc==SQLITE_OK ){ sqlite3_bind_int(pReplace, 1, FTS_STAT_INCRMERGEHINT); sqlite3_bind_blob(pReplace, 2, pHint->a, pHint->n, SQLITE_STATIC); sqlite3_step(pReplace); rc = sqlite3_reset(pReplace); } return rc; } /* ** Load an incr-merge hint from the database. The incr-merge hint, if one ** exists, is stored in the rowid==1 row of the %_stat table. ** ** If successful, populate blob *pHint with the value read from the %_stat ** table and return SQLITE_OK. Otherwise, if an error occurs, return an ** SQLite error code. */ static int fts3IncrmergeHintLoad(Fts3Table *p, Blob *pHint){ sqlite3_stmt *pSelect = 0; int rc; pHint->n = 0; rc = fts3SqlStmt(p, SQL_SELECT_STAT, &pSelect, 0); if( rc==SQLITE_OK ){ int rc2; sqlite3_bind_int(pSelect, 1, FTS_STAT_INCRMERGEHINT); if( SQLITE_ROW==sqlite3_step(pSelect) ){ const char *aHint = sqlite3_column_blob(pSelect, 0); int nHint = sqlite3_column_bytes(pSelect, 0); if( aHint ){ blobGrowBuffer(pHint, nHint, &rc); if( rc==SQLITE_OK ){ memcpy(pHint->a, aHint, nHint); pHint->n = nHint; } } } rc2 = sqlite3_reset(pSelect); if( rc==SQLITE_OK ) rc = rc2; } return rc; } /* ** If *pRc is not SQLITE_OK when this function is called, it is a no-op. ** Otherwise, append an entry to the hint stored in blob *pHint. Each entry ** consists of two varints, the absolute level number of the input segments ** and the number of input segments. ** ** If successful, leave *pRc set to SQLITE_OK and return. If an error occurs, ** set *pRc to an SQLite error code before returning. */ static void fts3IncrmergeHintPush( Blob *pHint, /* Hint blob to append to */ i64 iAbsLevel, /* First varint to store in hint */ int nInput, /* Second varint to store in hint */ int *pRc /* IN/OUT: Error code */ ){ blobGrowBuffer(pHint, pHint->n + 2*FTS3_VARINT_MAX, pRc); if( *pRc==SQLITE_OK ){ pHint->n += sqlite3Fts3PutVarint(&pHint->a[pHint->n], iAbsLevel); pHint->n += sqlite3Fts3PutVarint(&pHint->a[pHint->n], (i64)nInput); } } /* ** Read the last entry (most recently pushed) from the hint blob *pHint ** and then remove the entry. Write the two values read to *piAbsLevel and ** *pnInput before returning. ** ** If no error occurs, return SQLITE_OK. If the hint blob in *pHint does ** not contain at least two valid varints, return SQLITE_CORRUPT_VTAB. */ static int fts3IncrmergeHintPop(Blob *pHint, i64 *piAbsLevel, int *pnInput){ const int nHint = pHint->n; int i; i = pHint->n-2; while( i>0 && (pHint->a[i-1] & 0x80) ) i--; while( i>0 && (pHint->a[i-1] & 0x80) ) i--; pHint->n = i; i += sqlite3Fts3GetVarint(&pHint->a[i], piAbsLevel); i += fts3GetVarint32(&pHint->a[i], pnInput); if( i!=nHint ) return FTS_CORRUPT_VTAB; return SQLITE_OK; } /* ** Attempt an incremental merge that writes nMerge leaf blocks. ** ** Incremental merges happen nMin segments at a time. The segments ** to be merged are the nMin oldest segments (the ones with the smallest ** values for the _segdir.idx field) in the highest level that contains ** at least nMin segments. Multiple merges might occur in an attempt to ** write the quota of nMerge leaf blocks. */ SQLITE_PRIVATE int sqlite3Fts3Incrmerge(Fts3Table *p, int nMerge, int nMin){ int rc; /* Return code */ int nRem = nMerge; /* Number of leaf pages yet to be written */ Fts3MultiSegReader *pCsr; /* Cursor used to read input data */ Fts3SegFilter *pFilter; /* Filter used with cursor pCsr */ IncrmergeWriter *pWriter; /* Writer object */ int nSeg = 0; /* Number of input segments */ sqlite3_int64 iAbsLevel = 0; /* Absolute level number to work on */ Blob hint = {0, 0, 0}; /* Hint read from %_stat table */ int bDirtyHint = 0; /* True if blob 'hint' has been modified */ /* Allocate space for the cursor, filter and writer objects */ const int nAlloc = sizeof(*pCsr) + sizeof(*pFilter) + sizeof(*pWriter); pWriter = (IncrmergeWriter *)sqlite3_malloc(nAlloc); if( !pWriter ) return SQLITE_NOMEM; pFilter = (Fts3SegFilter *)&pWriter[1]; pCsr = (Fts3MultiSegReader *)&pFilter[1]; rc = fts3IncrmergeHintLoad(p, &hint); while( rc==SQLITE_OK && nRem>0 ){ const i64 nMod = FTS3_SEGDIR_MAXLEVEL * p->nIndex; sqlite3_stmt *pFindLevel = 0; /* SQL used to determine iAbsLevel */ int bUseHint = 0; /* True if attempting to append */ int iIdx = 0; /* Largest idx in level (iAbsLevel+1) */ /* Search the %_segdir table for the absolute level with the smallest ** relative level number that contains at least nMin segments, if any. ** If one is found, set iAbsLevel to the absolute level number and ** nSeg to nMin. If no level with at least nMin segments can be found, ** set nSeg to -1. */ rc = fts3SqlStmt(p, SQL_FIND_MERGE_LEVEL, &pFindLevel, 0); sqlite3_bind_int(pFindLevel, 1, MAX(2, nMin)); if( sqlite3_step(pFindLevel)==SQLITE_ROW ){ iAbsLevel = sqlite3_column_int64(pFindLevel, 0); nSeg = sqlite3_column_int(pFindLevel, 1); assert( nSeg>=2 ); }else{ nSeg = -1; } rc = sqlite3_reset(pFindLevel); /* If the hint read from the %_stat table is not empty, check if the ** last entry in it specifies a relative level smaller than or equal ** to the level identified by the block above (if any). If so, this ** iteration of the loop will work on merging at the hinted level. */ if( rc==SQLITE_OK && hint.n ){ int nHint = hint.n; sqlite3_int64 iHintAbsLevel = 0; /* Hint level */ int nHintSeg = 0; /* Hint number of segments */ rc = fts3IncrmergeHintPop(&hint, &iHintAbsLevel, &nHintSeg); if( nSeg<0 || (iAbsLevel % nMod) >= (iHintAbsLevel % nMod) ){ iAbsLevel = iHintAbsLevel; nSeg = nHintSeg; bUseHint = 1; bDirtyHint = 1; }else{ /* This undoes the effect of the HintPop() above - so that no entry ** is removed from the hint blob. */ hint.n = nHint; } } /* If nSeg is less that zero, then there is no level with at least ** nMin segments and no hint in the %_stat table. No work to do. ** Exit early in this case. */ if( nSeg<0 ) break; /* Open a cursor to iterate through the contents of the oldest nSeg ** indexes of absolute level iAbsLevel. If this cursor is opened using ** the 'hint' parameters, it is possible that there are less than nSeg ** segments available in level iAbsLevel. In this case, no work is ** done on iAbsLevel - fall through to the next iteration of the loop ** to start work on some other level. */ memset(pWriter, 0, nAlloc); pFilter->flags = FTS3_SEGMENT_REQUIRE_POS; if( rc==SQLITE_OK ){ rc = fts3IncrmergeOutputIdx(p, iAbsLevel, &iIdx); assert( bUseHint==1 || bUseHint==0 ); if( iIdx==0 || (bUseHint && iIdx==1) ){ int bIgnore = 0; rc = fts3SegmentIsMaxLevel(p, iAbsLevel+1, &bIgnore); if( bIgnore ){ pFilter->flags |= FTS3_SEGMENT_IGNORE_EMPTY; } } } if( rc==SQLITE_OK ){ rc = fts3IncrmergeCsr(p, iAbsLevel, nSeg, pCsr); } if( SQLITE_OK==rc && pCsr->nSegment==nSeg && SQLITE_OK==(rc = sqlite3Fts3SegReaderStart(p, pCsr, pFilter)) && SQLITE_ROW==(rc = sqlite3Fts3SegReaderStep(p, pCsr)) ){ if( bUseHint && iIdx>0 ){ const char *zKey = pCsr->zTerm; int nKey = pCsr->nTerm; rc = fts3IncrmergeLoad(p, iAbsLevel, iIdx-1, zKey, nKey, pWriter); }else{ rc = fts3IncrmergeWriter(p, iAbsLevel, iIdx, pCsr, pWriter); } if( rc==SQLITE_OK && pWriter->nLeafEst ){ fts3LogMerge(nSeg, iAbsLevel); do { rc = fts3IncrmergeAppend(p, pWriter, pCsr); if( rc==SQLITE_OK ) rc = sqlite3Fts3SegReaderStep(p, pCsr); if( pWriter->nWork>=nRem && rc==SQLITE_ROW ) rc = SQLITE_OK; }while( rc==SQLITE_ROW ); /* Update or delete the input segments */ if( rc==SQLITE_OK ){ nRem -= (1 + pWriter->nWork); rc = fts3IncrmergeChomp(p, iAbsLevel, pCsr, &nSeg); if( nSeg!=0 ){ bDirtyHint = 1; fts3IncrmergeHintPush(&hint, iAbsLevel, nSeg, &rc); } } } if( nSeg!=0 ){ pWriter->nLeafData = pWriter->nLeafData * -1; } fts3IncrmergeRelease(p, pWriter, &rc); if( nSeg==0 && pWriter->bNoLeafData==0 ){ fts3PromoteSegments(p, iAbsLevel+1, pWriter->nLeafData); } } sqlite3Fts3SegReaderFinish(pCsr); } /* Write the hint values into the %_stat table for the next incr-merger */ if( bDirtyHint && rc==SQLITE_OK ){ rc = fts3IncrmergeHintStore(p, &hint); } sqlite3_free(pWriter); sqlite3_free(hint.a); return rc; } /* ** Convert the text beginning at *pz into an integer and return ** its value. Advance *pz to point to the first character past ** the integer. */ static int fts3Getint(const char **pz){ const char *z = *pz; int i = 0; while( (*z)>='0' && (*z)<='9' ) i = 10*i + *(z++) - '0'; *pz = z; return i; } /* ** Process statements of the form: ** ** INSERT INTO table(table) VALUES('merge=A,B'); ** ** A and B are integers that decode to be the number of leaf pages ** written for the merge, and the minimum number of segments on a level ** before it will be selected for a merge, respectively. */ static int fts3DoIncrmerge( Fts3Table *p, /* FTS3 table handle */ const char *zParam /* Nul-terminated string containing "A,B" */ ){ int rc; int nMin = (FTS3_MERGE_COUNT / 2); int nMerge = 0; const char *z = zParam; /* Read the first integer value */ nMerge = fts3Getint(&z); /* If the first integer value is followed by a ',', read the second ** integer value. */ if( z[0]==',' && z[1]!='\0' ){ z++; nMin = fts3Getint(&z); } if( z[0]!='\0' || nMin<2 ){ rc = SQLITE_ERROR; }else{ rc = SQLITE_OK; if( !p->bHasStat ){ assert( p->bFts4==0 ); sqlite3Fts3CreateStatTable(&rc, p); } if( rc==SQLITE_OK ){ rc = sqlite3Fts3Incrmerge(p, nMerge, nMin); } sqlite3Fts3SegmentsClose(p); } return rc; } /* ** Process statements of the form: ** ** INSERT INTO table(table) VALUES('automerge=X'); ** ** where X is an integer. X==0 means to turn automerge off. X!=0 means ** turn it on. The setting is persistent. */ static int fts3DoAutoincrmerge( Fts3Table *p, /* FTS3 table handle */ const char *zParam /* Nul-terminated string containing boolean */ ){ int rc = SQLITE_OK; sqlite3_stmt *pStmt = 0; p->nAutoincrmerge = fts3Getint(&zParam); if( p->nAutoincrmerge==1 || p->nAutoincrmerge>FTS3_MERGE_COUNT ){ p->nAutoincrmerge = 8; } if( !p->bHasStat ){ assert( p->bFts4==0 ); sqlite3Fts3CreateStatTable(&rc, p); if( rc ) return rc; } rc = fts3SqlStmt(p, SQL_REPLACE_STAT, &pStmt, 0); if( rc ) return rc; sqlite3_bind_int(pStmt, 1, FTS_STAT_AUTOINCRMERGE); sqlite3_bind_int(pStmt, 2, p->nAutoincrmerge); sqlite3_step(pStmt); rc = sqlite3_reset(pStmt); return rc; } /* ** Return a 64-bit checksum for the FTS index entry specified by the ** arguments to this function. */ static u64 fts3ChecksumEntry( const char *zTerm, /* Pointer to buffer containing term */ int nTerm, /* Size of zTerm in bytes */ int iLangid, /* Language id for current row */ int iIndex, /* Index (0..Fts3Table.nIndex-1) */ i64 iDocid, /* Docid for current row. */ int iCol, /* Column number */ int iPos /* Position */ ){ int i; u64 ret = (u64)iDocid; ret += (ret<<3) + iLangid; ret += (ret<<3) + iIndex; ret += (ret<<3) + iCol; ret += (ret<<3) + iPos; for(i=0; inIndex-1) */ int *pRc /* OUT: Return code */ ){ Fts3SegFilter filter; Fts3MultiSegReader csr; int rc; u64 cksum = 0; assert( *pRc==SQLITE_OK ); memset(&filter, 0, sizeof(filter)); memset(&csr, 0, sizeof(csr)); filter.flags = FTS3_SEGMENT_REQUIRE_POS|FTS3_SEGMENT_IGNORE_EMPTY; filter.flags |= FTS3_SEGMENT_SCAN; rc = sqlite3Fts3SegReaderCursor( p, iLangid, iIndex, FTS3_SEGCURSOR_ALL, 0, 0, 0, 1,&csr ); if( rc==SQLITE_OK ){ rc = sqlite3Fts3SegReaderStart(p, &csr, &filter); } if( rc==SQLITE_OK ){ while( SQLITE_ROW==(rc = sqlite3Fts3SegReaderStep(p, &csr)) ){ char *pCsr = csr.aDoclist; char *pEnd = &pCsr[csr.nDoclist]; i64 iDocid = 0; i64 iCol = 0; i64 iPos = 0; pCsr += sqlite3Fts3GetVarint(pCsr, &iDocid); while( pCsriPrevLangid); sqlite3_bind_int(pAllLangid, 2, p->nIndex); while( rc==SQLITE_OK && sqlite3_step(pAllLangid)==SQLITE_ROW ){ int iLangid = sqlite3_column_int(pAllLangid, 0); int i; for(i=0; inIndex; i++){ cksum1 = cksum1 ^ fts3ChecksumIndex(p, iLangid, i, &rc); } } rc2 = sqlite3_reset(pAllLangid); if( rc==SQLITE_OK ) rc = rc2; } /* This block calculates the checksum according to the %_content table */ if( rc==SQLITE_OK ){ sqlite3_tokenizer_module const *pModule = p->pTokenizer->pModule; sqlite3_stmt *pStmt = 0; char *zSql; zSql = sqlite3_mprintf("SELECT %s" , p->zReadExprlist); if( !zSql ){ rc = SQLITE_NOMEM; }else{ rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0); sqlite3_free(zSql); } while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){ i64 iDocid = sqlite3_column_int64(pStmt, 0); int iLang = langidFromSelect(p, pStmt); int iCol; for(iCol=0; rc==SQLITE_OK && iColnColumn; iCol++){ if( p->abNotindexed[iCol]==0 ){ const char *zText = (const char *)sqlite3_column_text(pStmt, iCol+1); int nText = sqlite3_column_bytes(pStmt, iCol+1); sqlite3_tokenizer_cursor *pT = 0; rc = sqlite3Fts3OpenTokenizer(p->pTokenizer, iLang, zText, nText,&pT); while( rc==SQLITE_OK ){ char const *zToken; /* Buffer containing token */ int nToken = 0; /* Number of bytes in token */ int iDum1 = 0, iDum2 = 0; /* Dummy variables */ int iPos = 0; /* Position of token in zText */ rc = pModule->xNext(pT, &zToken, &nToken, &iDum1, &iDum2, &iPos); if( rc==SQLITE_OK ){ int i; cksum2 = cksum2 ^ fts3ChecksumEntry( zToken, nToken, iLang, 0, iDocid, iCol, iPos ); for(i=1; inIndex; i++){ if( p->aIndex[i].nPrefix<=nToken ){ cksum2 = cksum2 ^ fts3ChecksumEntry( zToken, p->aIndex[i].nPrefix, iLang, i, iDocid, iCol, iPos ); } } } } if( pT ) pModule->xClose(pT); if( rc==SQLITE_DONE ) rc = SQLITE_OK; } } } sqlite3_finalize(pStmt); } *pbOk = (cksum1==cksum2); return rc; } /* ** Run the integrity-check. If no error occurs and the current contents of ** the FTS index are correct, return SQLITE_OK. Or, if the contents of the ** FTS index are incorrect, return SQLITE_CORRUPT_VTAB. ** ** Or, if an error (e.g. an OOM or IO error) occurs, return an SQLite ** error code. ** ** The integrity-check works as follows. For each token and indexed token ** prefix in the document set, a 64-bit checksum is calculated (by code ** in fts3ChecksumEntry()) based on the following: ** ** + The index number (0 for the main index, 1 for the first prefix ** index etc.), ** + The token (or token prefix) text itself, ** + The language-id of the row it appears in, ** + The docid of the row it appears in, ** + The column it appears in, and ** + The tokens position within that column. ** ** The checksums for all entries in the index are XORed together to create ** a single checksum for the entire index. ** ** The integrity-check code calculates the same checksum in two ways: ** ** 1. By scanning the contents of the FTS index, and ** 2. By scanning and tokenizing the content table. ** ** If the two checksums are identical, the integrity-check is deemed to have ** passed. */ static int fts3DoIntegrityCheck( Fts3Table *p /* FTS3 table handle */ ){ int rc; int bOk = 0; rc = fts3IntegrityCheck(p, &bOk); if( rc==SQLITE_OK && bOk==0 ) rc = FTS_CORRUPT_VTAB; return rc; } /* ** Handle a 'special' INSERT of the form: ** ** "INSERT INTO tbl(tbl) VALUES()" ** ** Argument pVal contains the result of . Currently the only ** meaningful value to insert is the text 'optimize'. */ static int fts3SpecialInsert(Fts3Table *p, sqlite3_value *pVal){ int rc; /* Return Code */ const char *zVal = (const char *)sqlite3_value_text(pVal); int nVal = sqlite3_value_bytes(pVal); if( !zVal ){ return SQLITE_NOMEM; }else if( nVal==8 && 0==sqlite3_strnicmp(zVal, "optimize", 8) ){ rc = fts3DoOptimize(p, 0); }else if( nVal==7 && 0==sqlite3_strnicmp(zVal, "rebuild", 7) ){ rc = fts3DoRebuild(p); }else if( nVal==15 && 0==sqlite3_strnicmp(zVal, "integrity-check", 15) ){ rc = fts3DoIntegrityCheck(p); }else if( nVal>6 && 0==sqlite3_strnicmp(zVal, "merge=", 6) ){ rc = fts3DoIncrmerge(p, &zVal[6]); }else if( nVal>10 && 0==sqlite3_strnicmp(zVal, "automerge=", 10) ){ rc = fts3DoAutoincrmerge(p, &zVal[10]); #ifdef SQLITE_TEST }else if( nVal>9 && 0==sqlite3_strnicmp(zVal, "nodesize=", 9) ){ p->nNodeSize = atoi(&zVal[9]); rc = SQLITE_OK; }else if( nVal>11 && 0==sqlite3_strnicmp(zVal, "maxpending=", 9) ){ p->nMaxPendingData = atoi(&zVal[11]); rc = SQLITE_OK; }else if( nVal>21 && 0==sqlite3_strnicmp(zVal, "test-no-incr-doclist=", 21) ){ p->bNoIncrDoclist = atoi(&zVal[21]); rc = SQLITE_OK; #endif }else{ rc = SQLITE_ERROR; } return rc; } #ifndef SQLITE_DISABLE_FTS4_DEFERRED /* ** Delete all cached deferred doclists. Deferred doclists are cached ** (allocated) by the sqlite3Fts3CacheDeferredDoclists() function. */ SQLITE_PRIVATE void sqlite3Fts3FreeDeferredDoclists(Fts3Cursor *pCsr){ Fts3DeferredToken *pDef; for(pDef=pCsr->pDeferred; pDef; pDef=pDef->pNext){ fts3PendingListDelete(pDef->pList); pDef->pList = 0; } } /* ** Free all entries in the pCsr->pDeffered list. Entries are added to ** this list using sqlite3Fts3DeferToken(). */ SQLITE_PRIVATE void sqlite3Fts3FreeDeferredTokens(Fts3Cursor *pCsr){ Fts3DeferredToken *pDef; Fts3DeferredToken *pNext; for(pDef=pCsr->pDeferred; pDef; pDef=pNext){ pNext = pDef->pNext; fts3PendingListDelete(pDef->pList); sqlite3_free(pDef); } pCsr->pDeferred = 0; } /* ** Generate deferred-doclists for all tokens in the pCsr->pDeferred list ** based on the row that pCsr currently points to. ** ** A deferred-doclist is like any other doclist with position information ** included, except that it only contains entries for a single row of the ** table, not for all rows. */ SQLITE_PRIVATE int sqlite3Fts3CacheDeferredDoclists(Fts3Cursor *pCsr){ int rc = SQLITE_OK; /* Return code */ if( pCsr->pDeferred ){ int i; /* Used to iterate through table columns */ sqlite3_int64 iDocid; /* Docid of the row pCsr points to */ Fts3DeferredToken *pDef; /* Used to iterate through deferred tokens */ Fts3Table *p = (Fts3Table *)pCsr->base.pVtab; sqlite3_tokenizer *pT = p->pTokenizer; sqlite3_tokenizer_module const *pModule = pT->pModule; assert( pCsr->isRequireSeek==0 ); iDocid = sqlite3_column_int64(pCsr->pStmt, 0); for(i=0; inColumn && rc==SQLITE_OK; i++){ if( p->abNotindexed[i]==0 ){ const char *zText = (const char *)sqlite3_column_text(pCsr->pStmt, i+1); sqlite3_tokenizer_cursor *pTC = 0; rc = sqlite3Fts3OpenTokenizer(pT, pCsr->iLangid, zText, -1, &pTC); while( rc==SQLITE_OK ){ char const *zToken; /* Buffer containing token */ int nToken = 0; /* Number of bytes in token */ int iDum1 = 0, iDum2 = 0; /* Dummy variables */ int iPos = 0; /* Position of token in zText */ rc = pModule->xNext(pTC, &zToken, &nToken, &iDum1, &iDum2, &iPos); for(pDef=pCsr->pDeferred; pDef && rc==SQLITE_OK; pDef=pDef->pNext){ Fts3PhraseToken *pPT = pDef->pToken; if( (pDef->iCol>=p->nColumn || pDef->iCol==i) && (pPT->bFirst==0 || iPos==0) && (pPT->n==nToken || (pPT->isPrefix && pPT->nz, pPT->n)) ){ fts3PendingListAppend(&pDef->pList, iDocid, i, iPos, &rc); } } } if( pTC ) pModule->xClose(pTC); if( rc==SQLITE_DONE ) rc = SQLITE_OK; } } for(pDef=pCsr->pDeferred; pDef && rc==SQLITE_OK; pDef=pDef->pNext){ if( pDef->pList ){ rc = fts3PendingListAppendVarint(&pDef->pList, 0); } } } return rc; } SQLITE_PRIVATE int sqlite3Fts3DeferredTokenList( Fts3DeferredToken *p, char **ppData, int *pnData ){ char *pRet; int nSkip; sqlite3_int64 dummy; *ppData = 0; *pnData = 0; if( p->pList==0 ){ return SQLITE_OK; } pRet = (char *)sqlite3_malloc(p->pList->nData); if( !pRet ) return SQLITE_NOMEM; nSkip = sqlite3Fts3GetVarint(p->pList->aData, &dummy); *pnData = p->pList->nData - nSkip; *ppData = pRet; memcpy(pRet, &p->pList->aData[nSkip], *pnData); return SQLITE_OK; } /* ** Add an entry for token pToken to the pCsr->pDeferred list. */ SQLITE_PRIVATE int sqlite3Fts3DeferToken( Fts3Cursor *pCsr, /* Fts3 table cursor */ Fts3PhraseToken *pToken, /* Token to defer */ int iCol /* Column that token must appear in (or -1) */ ){ Fts3DeferredToken *pDeferred; pDeferred = sqlite3_malloc(sizeof(*pDeferred)); if( !pDeferred ){ return SQLITE_NOMEM; } memset(pDeferred, 0, sizeof(*pDeferred)); pDeferred->pToken = pToken; pDeferred->pNext = pCsr->pDeferred; pDeferred->iCol = iCol; pCsr->pDeferred = pDeferred; assert( pToken->pDeferred==0 ); pToken->pDeferred = pDeferred; return SQLITE_OK; } #endif /* ** SQLite value pRowid contains the rowid of a row that may or may not be ** present in the FTS3 table. If it is, delete it and adjust the contents ** of subsiduary data structures accordingly. */ static int fts3DeleteByRowid( Fts3Table *p, sqlite3_value *pRowid, int *pnChng, /* IN/OUT: Decrement if row is deleted */ u32 *aSzDel ){ int rc = SQLITE_OK; /* Return code */ int bFound = 0; /* True if *pRowid really is in the table */ fts3DeleteTerms(&rc, p, pRowid, aSzDel, &bFound); if( bFound && rc==SQLITE_OK ){ int isEmpty = 0; /* Deleting *pRowid leaves the table empty */ rc = fts3IsEmpty(p, pRowid, &isEmpty); if( rc==SQLITE_OK ){ if( isEmpty ){ /* Deleting this row means the whole table is empty. In this case ** delete the contents of all three tables and throw away any ** data in the pendingTerms hash table. */ rc = fts3DeleteAll(p, 1); *pnChng = 0; memset(aSzDel, 0, sizeof(u32) * (p->nColumn+1) * 2); }else{ *pnChng = *pnChng - 1; if( p->zContentTbl==0 ){ fts3SqlExec(&rc, p, SQL_DELETE_CONTENT, &pRowid); } if( p->bHasDocsize ){ fts3SqlExec(&rc, p, SQL_DELETE_DOCSIZE, &pRowid); } } } } return rc; } /* ** This function does the work for the xUpdate method of FTS3 virtual ** tables. The schema of the virtual table being: ** ** CREATE TABLE
    ( ** , **
    HIDDEN, ** docid HIDDEN, ** HIDDEN ** ); ** ** */ SQLITE_PRIVATE int sqlite3Fts3UpdateMethod( sqlite3_vtab *pVtab, /* FTS3 vtab object */ int nArg, /* Size of argument array */ sqlite3_value **apVal, /* Array of arguments */ sqlite_int64 *pRowid /* OUT: The affected (or effected) rowid */ ){ Fts3Table *p = (Fts3Table *)pVtab; int rc = SQLITE_OK; /* Return Code */ int isRemove = 0; /* True for an UPDATE or DELETE */ u32 *aSzIns = 0; /* Sizes of inserted documents */ u32 *aSzDel = 0; /* Sizes of deleted documents */ int nChng = 0; /* Net change in number of documents */ int bInsertDone = 0; /* At this point it must be known if the %_stat table exists or not. ** So bHasStat may not be 2. */ assert( p->bHasStat==0 || p->bHasStat==1 ); assert( p->pSegments==0 ); assert( nArg==1 /* DELETE operations */ || nArg==(2 + p->nColumn + 3) /* INSERT or UPDATE operations */ ); /* Check for a "special" INSERT operation. One of the form: ** ** INSERT INTO xyz(xyz) VALUES('command'); */ if( nArg>1 && sqlite3_value_type(apVal[0])==SQLITE_NULL && sqlite3_value_type(apVal[p->nColumn+2])!=SQLITE_NULL ){ rc = fts3SpecialInsert(p, apVal[p->nColumn+2]); goto update_out; } if( nArg>1 && sqlite3_value_int(apVal[2 + p->nColumn + 2])<0 ){ rc = SQLITE_CONSTRAINT; goto update_out; } /* Allocate space to hold the change in document sizes */ aSzDel = sqlite3_malloc( sizeof(aSzDel[0])*(p->nColumn+1)*2 ); if( aSzDel==0 ){ rc = SQLITE_NOMEM; goto update_out; } aSzIns = &aSzDel[p->nColumn+1]; memset(aSzDel, 0, sizeof(aSzDel[0])*(p->nColumn+1)*2); rc = fts3Writelock(p); if( rc!=SQLITE_OK ) goto update_out; /* If this is an INSERT operation, or an UPDATE that modifies the rowid ** value, then this operation requires constraint handling. ** ** If the on-conflict mode is REPLACE, this means that the existing row ** should be deleted from the database before inserting the new row. Or, ** if the on-conflict mode is other than REPLACE, then this method must ** detect the conflict and return SQLITE_CONSTRAINT before beginning to ** modify the database file. */ if( nArg>1 && p->zContentTbl==0 ){ /* Find the value object that holds the new rowid value. */ sqlite3_value *pNewRowid = apVal[3+p->nColumn]; if( sqlite3_value_type(pNewRowid)==SQLITE_NULL ){ pNewRowid = apVal[1]; } if( sqlite3_value_type(pNewRowid)!=SQLITE_NULL && ( sqlite3_value_type(apVal[0])==SQLITE_NULL || sqlite3_value_int64(apVal[0])!=sqlite3_value_int64(pNewRowid) )){ /* The new rowid is not NULL (in this case the rowid will be ** automatically assigned and there is no chance of a conflict), and ** the statement is either an INSERT or an UPDATE that modifies the ** rowid column. So if the conflict mode is REPLACE, then delete any ** existing row with rowid=pNewRowid. ** ** Or, if the conflict mode is not REPLACE, insert the new record into ** the %_content table. If we hit the duplicate rowid constraint (or any ** other error) while doing so, return immediately. ** ** This branch may also run if pNewRowid contains a value that cannot ** be losslessly converted to an integer. In this case, the eventual ** call to fts3InsertData() (either just below or further on in this ** function) will return SQLITE_MISMATCH. If fts3DeleteByRowid is ** invoked, it will delete zero rows (since no row will have ** docid=$pNewRowid if $pNewRowid is not an integer value). */ if( sqlite3_vtab_on_conflict(p->db)==SQLITE_REPLACE ){ rc = fts3DeleteByRowid(p, pNewRowid, &nChng, aSzDel); }else{ rc = fts3InsertData(p, apVal, pRowid); bInsertDone = 1; } } } if( rc!=SQLITE_OK ){ goto update_out; } /* If this is a DELETE or UPDATE operation, remove the old record. */ if( sqlite3_value_type(apVal[0])!=SQLITE_NULL ){ assert( sqlite3_value_type(apVal[0])==SQLITE_INTEGER ); rc = fts3DeleteByRowid(p, apVal[0], &nChng, aSzDel); isRemove = 1; } /* If this is an INSERT or UPDATE operation, insert the new record. */ if( nArg>1 && rc==SQLITE_OK ){ int iLangid = sqlite3_value_int(apVal[2 + p->nColumn + 2]); if( bInsertDone==0 ){ rc = fts3InsertData(p, apVal, pRowid); if( rc==SQLITE_CONSTRAINT && p->zContentTbl==0 ){ rc = FTS_CORRUPT_VTAB; } } if( rc==SQLITE_OK && (!isRemove || *pRowid!=p->iPrevDocid ) ){ rc = fts3PendingTermsDocid(p, 0, iLangid, *pRowid); } if( rc==SQLITE_OK ){ assert( p->iPrevDocid==*pRowid ); rc = fts3InsertTerms(p, iLangid, apVal, aSzIns); } if( p->bHasDocsize ){ fts3InsertDocsize(&rc, p, aSzIns); } nChng++; } if( p->bFts4 ){ fts3UpdateDocTotals(&rc, p, aSzIns, aSzDel, nChng); } update_out: sqlite3_free(aSzDel); sqlite3Fts3SegmentsClose(p); return rc; } /* ** Flush any data in the pending-terms hash table to disk. If successful, ** merge all segments in the database (including the new segment, if ** there was any data to flush) into a single segment. */ SQLITE_PRIVATE int sqlite3Fts3Optimize(Fts3Table *p){ int rc; rc = sqlite3_exec(p->db, "SAVEPOINT fts3", 0, 0, 0); if( rc==SQLITE_OK ){ rc = fts3DoOptimize(p, 1); if( rc==SQLITE_OK || rc==SQLITE_DONE ){ int rc2 = sqlite3_exec(p->db, "RELEASE fts3", 0, 0, 0); if( rc2!=SQLITE_OK ) rc = rc2; }else{ sqlite3_exec(p->db, "ROLLBACK TO fts3", 0, 0, 0); sqlite3_exec(p->db, "RELEASE fts3", 0, 0, 0); } } sqlite3Fts3SegmentsClose(p); return rc; } #endif /************** End of fts3_write.c ******************************************/ /************** Begin file fts3_snippet.c ************************************/ /* ** 2009 Oct 23 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ****************************************************************************** */ /* #include "fts3Int.h" */ #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) /* #include */ /* #include */ /* ** Characters that may appear in the second argument to matchinfo(). */ #define FTS3_MATCHINFO_NPHRASE 'p' /* 1 value */ #define FTS3_MATCHINFO_NCOL 'c' /* 1 value */ #define FTS3_MATCHINFO_NDOC 'n' /* 1 value */ #define FTS3_MATCHINFO_AVGLENGTH 'a' /* nCol values */ #define FTS3_MATCHINFO_LENGTH 'l' /* nCol values */ #define FTS3_MATCHINFO_LCS 's' /* nCol values */ #define FTS3_MATCHINFO_HITS 'x' /* 3*nCol*nPhrase values */ #define FTS3_MATCHINFO_LHITS 'y' /* nCol*nPhrase values */ #define FTS3_MATCHINFO_LHITS_BM 'b' /* nCol*nPhrase values */ /* ** The default value for the second argument to matchinfo(). */ #define FTS3_MATCHINFO_DEFAULT "pcx" /* ** Used as an fts3ExprIterate() context when loading phrase doclists to ** Fts3Expr.aDoclist[]/nDoclist. */ typedef struct LoadDoclistCtx LoadDoclistCtx; struct LoadDoclistCtx { Fts3Cursor *pCsr; /* FTS3 Cursor */ int nPhrase; /* Number of phrases seen so far */ int nToken; /* Number of tokens seen so far */ }; /* ** The following types are used as part of the implementation of the ** fts3BestSnippet() routine. */ typedef struct SnippetIter SnippetIter; typedef struct SnippetPhrase SnippetPhrase; typedef struct SnippetFragment SnippetFragment; struct SnippetIter { Fts3Cursor *pCsr; /* Cursor snippet is being generated from */ int iCol; /* Extract snippet from this column */ int nSnippet; /* Requested snippet length (in tokens) */ int nPhrase; /* Number of phrases in query */ SnippetPhrase *aPhrase; /* Array of size nPhrase */ int iCurrent; /* First token of current snippet */ }; struct SnippetPhrase { int nToken; /* Number of tokens in phrase */ char *pList; /* Pointer to start of phrase position list */ int iHead; /* Next value in position list */ char *pHead; /* Position list data following iHead */ int iTail; /* Next value in trailing position list */ char *pTail; /* Position list data following iTail */ }; struct SnippetFragment { int iCol; /* Column snippet is extracted from */ int iPos; /* Index of first token in snippet */ u64 covered; /* Mask of query phrases covered */ u64 hlmask; /* Mask of snippet terms to highlight */ }; /* ** This type is used as an fts3ExprIterate() context object while ** accumulating the data returned by the matchinfo() function. */ typedef struct MatchInfo MatchInfo; struct MatchInfo { Fts3Cursor *pCursor; /* FTS3 Cursor */ int nCol; /* Number of columns in table */ int nPhrase; /* Number of matchable phrases in query */ sqlite3_int64 nDoc; /* Number of docs in database */ char flag; u32 *aMatchinfo; /* Pre-allocated buffer */ }; /* ** An instance of this structure is used to manage a pair of buffers, each ** (nElem * sizeof(u32)) bytes in size. See the MatchinfoBuffer code below ** for details. */ struct MatchinfoBuffer { u8 aRef[3]; int nElem; int bGlobal; /* Set if global data is loaded */ char *zMatchinfo; u32 aMatchinfo[1]; }; /* ** The snippet() and offsets() functions both return text values. An instance ** of the following structure is used to accumulate those values while the ** functions are running. See fts3StringAppend() for details. */ typedef struct StrBuffer StrBuffer; struct StrBuffer { char *z; /* Pointer to buffer containing string */ int n; /* Length of z in bytes (excl. nul-term) */ int nAlloc; /* Allocated size of buffer z in bytes */ }; /************************************************************************* ** Start of MatchinfoBuffer code. */ /* ** Allocate a two-slot MatchinfoBuffer object. */ static MatchinfoBuffer *fts3MIBufferNew(int nElem, const char *zMatchinfo){ MatchinfoBuffer *pRet; int nByte = sizeof(u32) * (2*nElem + 1) + sizeof(MatchinfoBuffer); int nStr = (int)strlen(zMatchinfo); pRet = sqlite3_malloc(nByte + nStr+1); if( pRet ){ memset(pRet, 0, nByte); pRet->aMatchinfo[0] = (u8*)(&pRet->aMatchinfo[1]) - (u8*)pRet; pRet->aMatchinfo[1+nElem] = pRet->aMatchinfo[0] + sizeof(u32)*(nElem+1); pRet->nElem = nElem; pRet->zMatchinfo = ((char*)pRet) + nByte; memcpy(pRet->zMatchinfo, zMatchinfo, nStr+1); pRet->aRef[0] = 1; } return pRet; } static void fts3MIBufferFree(void *p){ MatchinfoBuffer *pBuf = (MatchinfoBuffer*)((u8*)p - ((u32*)p)[-1]); assert( (u32*)p==&pBuf->aMatchinfo[1] || (u32*)p==&pBuf->aMatchinfo[pBuf->nElem+2] ); if( (u32*)p==&pBuf->aMatchinfo[1] ){ pBuf->aRef[1] = 0; }else{ pBuf->aRef[2] = 0; } if( pBuf->aRef[0]==0 && pBuf->aRef[1]==0 && pBuf->aRef[2]==0 ){ sqlite3_free(pBuf); } } static void (*fts3MIBufferAlloc(MatchinfoBuffer *p, u32 **paOut))(void*){ void (*xRet)(void*) = 0; u32 *aOut = 0; if( p->aRef[1]==0 ){ p->aRef[1] = 1; aOut = &p->aMatchinfo[1]; xRet = fts3MIBufferFree; } else if( p->aRef[2]==0 ){ p->aRef[2] = 1; aOut = &p->aMatchinfo[p->nElem+2]; xRet = fts3MIBufferFree; }else{ aOut = (u32*)sqlite3_malloc(p->nElem * sizeof(u32)); if( aOut ){ xRet = sqlite3_free; if( p->bGlobal ) memcpy(aOut, &p->aMatchinfo[1], p->nElem*sizeof(u32)); } } *paOut = aOut; return xRet; } static void fts3MIBufferSetGlobal(MatchinfoBuffer *p){ p->bGlobal = 1; memcpy(&p->aMatchinfo[2+p->nElem], &p->aMatchinfo[1], p->nElem*sizeof(u32)); } /* ** Free a MatchinfoBuffer object allocated using fts3MIBufferNew() */ SQLITE_PRIVATE void sqlite3Fts3MIBufferFree(MatchinfoBuffer *p){ if( p ){ assert( p->aRef[0]==1 ); p->aRef[0] = 0; if( p->aRef[0]==0 && p->aRef[1]==0 && p->aRef[2]==0 ){ sqlite3_free(p); } } } /* ** End of MatchinfoBuffer code. *************************************************************************/ /* ** This function is used to help iterate through a position-list. A position ** list is a list of unique integers, sorted from smallest to largest. Each ** element of the list is represented by an FTS3 varint that takes the value ** of the difference between the current element and the previous one plus ** two. For example, to store the position-list: ** ** 4 9 113 ** ** the three varints: ** ** 6 7 106 ** ** are encoded. ** ** When this function is called, *pp points to the start of an element of ** the list. *piPos contains the value of the previous entry in the list. ** After it returns, *piPos contains the value of the next element of the ** list and *pp is advanced to the following varint. */ static void fts3GetDeltaPosition(char **pp, int *piPos){ int iVal; *pp += fts3GetVarint32(*pp, &iVal); *piPos += (iVal-2); } /* ** Helper function for fts3ExprIterate() (see below). */ static int fts3ExprIterate2( Fts3Expr *pExpr, /* Expression to iterate phrases of */ int *piPhrase, /* Pointer to phrase counter */ int (*x)(Fts3Expr*,int,void*), /* Callback function to invoke for phrases */ void *pCtx /* Second argument to pass to callback */ ){ int rc; /* Return code */ int eType = pExpr->eType; /* Type of expression node pExpr */ if( eType!=FTSQUERY_PHRASE ){ assert( pExpr->pLeft && pExpr->pRight ); rc = fts3ExprIterate2(pExpr->pLeft, piPhrase, x, pCtx); if( rc==SQLITE_OK && eType!=FTSQUERY_NOT ){ rc = fts3ExprIterate2(pExpr->pRight, piPhrase, x, pCtx); } }else{ rc = x(pExpr, *piPhrase, pCtx); (*piPhrase)++; } return rc; } /* ** Iterate through all phrase nodes in an FTS3 query, except those that ** are part of a sub-tree that is the right-hand-side of a NOT operator. ** For each phrase node found, the supplied callback function is invoked. ** ** If the callback function returns anything other than SQLITE_OK, ** the iteration is abandoned and the error code returned immediately. ** Otherwise, SQLITE_OK is returned after a callback has been made for ** all eligible phrase nodes. */ static int fts3ExprIterate( Fts3Expr *pExpr, /* Expression to iterate phrases of */ int (*x)(Fts3Expr*,int,void*), /* Callback function to invoke for phrases */ void *pCtx /* Second argument to pass to callback */ ){ int iPhrase = 0; /* Variable used as the phrase counter */ return fts3ExprIterate2(pExpr, &iPhrase, x, pCtx); } /* ** This is an fts3ExprIterate() callback used while loading the doclists ** for each phrase into Fts3Expr.aDoclist[]/nDoclist. See also ** fts3ExprLoadDoclists(). */ static int fts3ExprLoadDoclistsCb(Fts3Expr *pExpr, int iPhrase, void *ctx){ int rc = SQLITE_OK; Fts3Phrase *pPhrase = pExpr->pPhrase; LoadDoclistCtx *p = (LoadDoclistCtx *)ctx; UNUSED_PARAMETER(iPhrase); p->nPhrase++; p->nToken += pPhrase->nToken; return rc; } /* ** Load the doclists for each phrase in the query associated with FTS3 cursor ** pCsr. ** ** If pnPhrase is not NULL, then *pnPhrase is set to the number of matchable ** phrases in the expression (all phrases except those directly or ** indirectly descended from the right-hand-side of a NOT operator). If ** pnToken is not NULL, then it is set to the number of tokens in all ** matchable phrases of the expression. */ static int fts3ExprLoadDoclists( Fts3Cursor *pCsr, /* Fts3 cursor for current query */ int *pnPhrase, /* OUT: Number of phrases in query */ int *pnToken /* OUT: Number of tokens in query */ ){ int rc; /* Return Code */ LoadDoclistCtx sCtx = {0,0,0}; /* Context for fts3ExprIterate() */ sCtx.pCsr = pCsr; rc = fts3ExprIterate(pCsr->pExpr, fts3ExprLoadDoclistsCb, (void *)&sCtx); if( pnPhrase ) *pnPhrase = sCtx.nPhrase; if( pnToken ) *pnToken = sCtx.nToken; return rc; } static int fts3ExprPhraseCountCb(Fts3Expr *pExpr, int iPhrase, void *ctx){ (*(int *)ctx)++; pExpr->iPhrase = iPhrase; return SQLITE_OK; } static int fts3ExprPhraseCount(Fts3Expr *pExpr){ int nPhrase = 0; (void)fts3ExprIterate(pExpr, fts3ExprPhraseCountCb, (void *)&nPhrase); return nPhrase; } /* ** Advance the position list iterator specified by the first two ** arguments so that it points to the first element with a value greater ** than or equal to parameter iNext. */ static void fts3SnippetAdvance(char **ppIter, int *piIter, int iNext){ char *pIter = *ppIter; if( pIter ){ int iIter = *piIter; while( iIteriCurrent<0 ){ /* The SnippetIter object has just been initialized. The first snippet ** candidate always starts at offset 0 (even if this candidate has a ** score of 0.0). */ pIter->iCurrent = 0; /* Advance the 'head' iterator of each phrase to the first offset that ** is greater than or equal to (iNext+nSnippet). */ for(i=0; inPhrase; i++){ SnippetPhrase *pPhrase = &pIter->aPhrase[i]; fts3SnippetAdvance(&pPhrase->pHead, &pPhrase->iHead, pIter->nSnippet); } }else{ int iStart; int iEnd = 0x7FFFFFFF; for(i=0; inPhrase; i++){ SnippetPhrase *pPhrase = &pIter->aPhrase[i]; if( pPhrase->pHead && pPhrase->iHeadiHead; } } if( iEnd==0x7FFFFFFF ){ return 1; } pIter->iCurrent = iStart = iEnd - pIter->nSnippet + 1; for(i=0; inPhrase; i++){ SnippetPhrase *pPhrase = &pIter->aPhrase[i]; fts3SnippetAdvance(&pPhrase->pHead, &pPhrase->iHead, iEnd+1); fts3SnippetAdvance(&pPhrase->pTail, &pPhrase->iTail, iStart); } } return 0; } /* ** Retrieve information about the current candidate snippet of snippet ** iterator pIter. */ static void fts3SnippetDetails( SnippetIter *pIter, /* Snippet iterator */ u64 mCovered, /* Bitmask of phrases already covered */ int *piToken, /* OUT: First token of proposed snippet */ int *piScore, /* OUT: "Score" for this snippet */ u64 *pmCover, /* OUT: Bitmask of phrases covered */ u64 *pmHighlight /* OUT: Bitmask of terms to highlight */ ){ int iStart = pIter->iCurrent; /* First token of snippet */ int iScore = 0; /* Score of this snippet */ int i; /* Loop counter */ u64 mCover = 0; /* Mask of phrases covered by this snippet */ u64 mHighlight = 0; /* Mask of tokens to highlight in snippet */ for(i=0; inPhrase; i++){ SnippetPhrase *pPhrase = &pIter->aPhrase[i]; if( pPhrase->pTail ){ char *pCsr = pPhrase->pTail; int iCsr = pPhrase->iTail; while( iCsr<(iStart+pIter->nSnippet) ){ int j; u64 mPhrase = (u64)1 << i; u64 mPos = (u64)1 << (iCsr - iStart); assert( iCsr>=iStart ); if( (mCover|mCovered)&mPhrase ){ iScore++; }else{ iScore += 1000; } mCover |= mPhrase; for(j=0; jnToken; j++){ mHighlight |= (mPos>>j); } if( 0==(*pCsr & 0x0FE) ) break; fts3GetDeltaPosition(&pCsr, &iCsr); } } } /* Set the output variables before returning. */ *piToken = iStart; *piScore = iScore; *pmCover = mCover; *pmHighlight = mHighlight; } /* ** This function is an fts3ExprIterate() callback used by fts3BestSnippet(). ** Each invocation populates an element of the SnippetIter.aPhrase[] array. */ static int fts3SnippetFindPositions(Fts3Expr *pExpr, int iPhrase, void *ctx){ SnippetIter *p = (SnippetIter *)ctx; SnippetPhrase *pPhrase = &p->aPhrase[iPhrase]; char *pCsr; int rc; pPhrase->nToken = pExpr->pPhrase->nToken; rc = sqlite3Fts3EvalPhrasePoslist(p->pCsr, pExpr, p->iCol, &pCsr); assert( rc==SQLITE_OK || pCsr==0 ); if( pCsr ){ int iFirst = 0; pPhrase->pList = pCsr; fts3GetDeltaPosition(&pCsr, &iFirst); assert( iFirst>=0 ); pPhrase->pHead = pCsr; pPhrase->pTail = pCsr; pPhrase->iHead = iFirst; pPhrase->iTail = iFirst; }else{ assert( rc!=SQLITE_OK || ( pPhrase->pList==0 && pPhrase->pHead==0 && pPhrase->pTail==0 )); } return rc; } /* ** Select the fragment of text consisting of nFragment contiguous tokens ** from column iCol that represent the "best" snippet. The best snippet ** is the snippet with the highest score, where scores are calculated ** by adding: ** ** (a) +1 point for each occurrence of a matchable phrase in the snippet. ** ** (b) +1000 points for the first occurrence of each matchable phrase in ** the snippet for which the corresponding mCovered bit is not set. ** ** The selected snippet parameters are stored in structure *pFragment before ** returning. The score of the selected snippet is stored in *piScore ** before returning. */ static int fts3BestSnippet( int nSnippet, /* Desired snippet length */ Fts3Cursor *pCsr, /* Cursor to create snippet for */ int iCol, /* Index of column to create snippet from */ u64 mCovered, /* Mask of phrases already covered */ u64 *pmSeen, /* IN/OUT: Mask of phrases seen */ SnippetFragment *pFragment, /* OUT: Best snippet found */ int *piScore /* OUT: Score of snippet pFragment */ ){ int rc; /* Return Code */ int nList; /* Number of phrases in expression */ SnippetIter sIter; /* Iterates through snippet candidates */ int nByte; /* Number of bytes of space to allocate */ int iBestScore = -1; /* Best snippet score found so far */ int i; /* Loop counter */ memset(&sIter, 0, sizeof(sIter)); /* Iterate through the phrases in the expression to count them. The same ** callback makes sure the doclists are loaded for each phrase. */ rc = fts3ExprLoadDoclists(pCsr, &nList, 0); if( rc!=SQLITE_OK ){ return rc; } /* Now that it is known how many phrases there are, allocate and zero ** the required space using malloc(). */ nByte = sizeof(SnippetPhrase) * nList; sIter.aPhrase = (SnippetPhrase *)sqlite3_malloc(nByte); if( !sIter.aPhrase ){ return SQLITE_NOMEM; } memset(sIter.aPhrase, 0, nByte); /* Initialize the contents of the SnippetIter object. Then iterate through ** the set of phrases in the expression to populate the aPhrase[] array. */ sIter.pCsr = pCsr; sIter.iCol = iCol; sIter.nSnippet = nSnippet; sIter.nPhrase = nList; sIter.iCurrent = -1; rc = fts3ExprIterate(pCsr->pExpr, fts3SnippetFindPositions, (void*)&sIter); if( rc==SQLITE_OK ){ /* Set the *pmSeen output variable. */ for(i=0; iiCol = iCol; while( !fts3SnippetNextCandidate(&sIter) ){ int iPos; int iScore; u64 mCover; u64 mHighlite; fts3SnippetDetails(&sIter, mCovered, &iPos, &iScore, &mCover,&mHighlite); assert( iScore>=0 ); if( iScore>iBestScore ){ pFragment->iPos = iPos; pFragment->hlmask = mHighlite; pFragment->covered = mCover; iBestScore = iScore; } } *piScore = iBestScore; } sqlite3_free(sIter.aPhrase); return rc; } /* ** Append a string to the string-buffer passed as the first argument. ** ** If nAppend is negative, then the length of the string zAppend is ** determined using strlen(). */ static int fts3StringAppend( StrBuffer *pStr, /* Buffer to append to */ const char *zAppend, /* Pointer to data to append to buffer */ int nAppend /* Size of zAppend in bytes (or -1) */ ){ if( nAppend<0 ){ nAppend = (int)strlen(zAppend); } /* If there is insufficient space allocated at StrBuffer.z, use realloc() ** to grow the buffer until so that it is big enough to accomadate the ** appended data. */ if( pStr->n+nAppend+1>=pStr->nAlloc ){ int nAlloc = pStr->nAlloc+nAppend+100; char *zNew = sqlite3_realloc(pStr->z, nAlloc); if( !zNew ){ return SQLITE_NOMEM; } pStr->z = zNew; pStr->nAlloc = nAlloc; } assert( pStr->z!=0 && (pStr->nAlloc >= pStr->n+nAppend+1) ); /* Append the data to the string buffer. */ memcpy(&pStr->z[pStr->n], zAppend, nAppend); pStr->n += nAppend; pStr->z[pStr->n] = '\0'; return SQLITE_OK; } /* ** The fts3BestSnippet() function often selects snippets that end with a ** query term. That is, the final term of the snippet is always a term ** that requires highlighting. For example, if 'X' is a highlighted term ** and '.' is a non-highlighted term, BestSnippet() may select: ** ** ........X.....X ** ** This function "shifts" the beginning of the snippet forward in the ** document so that there are approximately the same number of ** non-highlighted terms to the right of the final highlighted term as there ** are to the left of the first highlighted term. For example, to this: ** ** ....X.....X.... ** ** This is done as part of extracting the snippet text, not when selecting ** the snippet. Snippet selection is done based on doclists only, so there ** is no way for fts3BestSnippet() to know whether or not the document ** actually contains terms that follow the final highlighted term. */ static int fts3SnippetShift( Fts3Table *pTab, /* FTS3 table snippet comes from */ int iLangid, /* Language id to use in tokenizing */ int nSnippet, /* Number of tokens desired for snippet */ const char *zDoc, /* Document text to extract snippet from */ int nDoc, /* Size of buffer zDoc in bytes */ int *piPos, /* IN/OUT: First token of snippet */ u64 *pHlmask /* IN/OUT: Mask of tokens to highlight */ ){ u64 hlmask = *pHlmask; /* Local copy of initial highlight-mask */ if( hlmask ){ int nLeft; /* Tokens to the left of first highlight */ int nRight; /* Tokens to the right of last highlight */ int nDesired; /* Ideal number of tokens to shift forward */ for(nLeft=0; !(hlmask & ((u64)1 << nLeft)); nLeft++); for(nRight=0; !(hlmask & ((u64)1 << (nSnippet-1-nRight))); nRight++); nDesired = (nLeft-nRight)/2; /* Ideally, the start of the snippet should be pushed forward in the ** document nDesired tokens. This block checks if there are actually ** nDesired tokens to the right of the snippet. If so, *piPos and ** *pHlMask are updated to shift the snippet nDesired tokens to the ** right. Otherwise, the snippet is shifted by the number of tokens ** available. */ if( nDesired>0 ){ int nShift; /* Number of tokens to shift snippet by */ int iCurrent = 0; /* Token counter */ int rc; /* Return Code */ sqlite3_tokenizer_module *pMod; sqlite3_tokenizer_cursor *pC; pMod = (sqlite3_tokenizer_module *)pTab->pTokenizer->pModule; /* Open a cursor on zDoc/nDoc. Check if there are (nSnippet+nDesired) ** or more tokens in zDoc/nDoc. */ rc = sqlite3Fts3OpenTokenizer(pTab->pTokenizer, iLangid, zDoc, nDoc, &pC); if( rc!=SQLITE_OK ){ return rc; } while( rc==SQLITE_OK && iCurrent<(nSnippet+nDesired) ){ const char *ZDUMMY; int DUMMY1 = 0, DUMMY2 = 0, DUMMY3 = 0; rc = pMod->xNext(pC, &ZDUMMY, &DUMMY1, &DUMMY2, &DUMMY3, &iCurrent); } pMod->xClose(pC); if( rc!=SQLITE_OK && rc!=SQLITE_DONE ){ return rc; } nShift = (rc==SQLITE_DONE)+iCurrent-nSnippet; assert( nShift<=nDesired ); if( nShift>0 ){ *piPos += nShift; *pHlmask = hlmask >> nShift; } } } return SQLITE_OK; } /* ** Extract the snippet text for fragment pFragment from cursor pCsr and ** append it to string buffer pOut. */ static int fts3SnippetText( Fts3Cursor *pCsr, /* FTS3 Cursor */ SnippetFragment *pFragment, /* Snippet to extract */ int iFragment, /* Fragment number */ int isLast, /* True for final fragment in snippet */ int nSnippet, /* Number of tokens in extracted snippet */ const char *zOpen, /* String inserted before highlighted term */ const char *zClose, /* String inserted after highlighted term */ const char *zEllipsis, /* String inserted between snippets */ StrBuffer *pOut /* Write output here */ ){ Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab; int rc; /* Return code */ const char *zDoc; /* Document text to extract snippet from */ int nDoc; /* Size of zDoc in bytes */ int iCurrent = 0; /* Current token number of document */ int iEnd = 0; /* Byte offset of end of current token */ int isShiftDone = 0; /* True after snippet is shifted */ int iPos = pFragment->iPos; /* First token of snippet */ u64 hlmask = pFragment->hlmask; /* Highlight-mask for snippet */ int iCol = pFragment->iCol+1; /* Query column to extract text from */ sqlite3_tokenizer_module *pMod; /* Tokenizer module methods object */ sqlite3_tokenizer_cursor *pC; /* Tokenizer cursor open on zDoc/nDoc */ zDoc = (const char *)sqlite3_column_text(pCsr->pStmt, iCol); if( zDoc==0 ){ if( sqlite3_column_type(pCsr->pStmt, iCol)!=SQLITE_NULL ){ return SQLITE_NOMEM; } return SQLITE_OK; } nDoc = sqlite3_column_bytes(pCsr->pStmt, iCol); /* Open a token cursor on the document. */ pMod = (sqlite3_tokenizer_module *)pTab->pTokenizer->pModule; rc = sqlite3Fts3OpenTokenizer(pTab->pTokenizer, pCsr->iLangid, zDoc,nDoc,&pC); if( rc!=SQLITE_OK ){ return rc; } while( rc==SQLITE_OK ){ const char *ZDUMMY; /* Dummy argument used with tokenizer */ int DUMMY1 = -1; /* Dummy argument used with tokenizer */ int iBegin = 0; /* Offset in zDoc of start of token */ int iFin = 0; /* Offset in zDoc of end of token */ int isHighlight = 0; /* True for highlighted terms */ /* Variable DUMMY1 is initialized to a negative value above. Elsewhere ** in the FTS code the variable that the third argument to xNext points to ** is initialized to zero before the first (*but not necessarily ** subsequent*) call to xNext(). This is done for a particular application ** that needs to know whether or not the tokenizer is being used for ** snippet generation or for some other purpose. ** ** Extreme care is required when writing code to depend on this ** initialization. It is not a documented part of the tokenizer interface. ** If a tokenizer is used directly by any code outside of FTS, this ** convention might not be respected. */ rc = pMod->xNext(pC, &ZDUMMY, &DUMMY1, &iBegin, &iFin, &iCurrent); if( rc!=SQLITE_OK ){ if( rc==SQLITE_DONE ){ /* Special case - the last token of the snippet is also the last token ** of the column. Append any punctuation that occurred between the end ** of the previous token and the end of the document to the output. ** Then break out of the loop. */ rc = fts3StringAppend(pOut, &zDoc[iEnd], -1); } break; } if( iCurrentiLangid, nSnippet, &zDoc[iBegin], n, &iPos, &hlmask ); isShiftDone = 1; /* Now that the shift has been done, check if the initial "..." are ** required. They are required if (a) this is not the first fragment, ** or (b) this fragment does not begin at position 0 of its column. */ if( rc==SQLITE_OK ){ if( iPos>0 || iFragment>0 ){ rc = fts3StringAppend(pOut, zEllipsis, -1); }else if( iBegin ){ rc = fts3StringAppend(pOut, zDoc, iBegin); } } if( rc!=SQLITE_OK || iCurrent=(iPos+nSnippet) ){ if( isLast ){ rc = fts3StringAppend(pOut, zEllipsis, -1); } break; } /* Set isHighlight to true if this term should be highlighted. */ isHighlight = (hlmask & ((u64)1 << (iCurrent-iPos)))!=0; if( iCurrent>iPos ) rc = fts3StringAppend(pOut, &zDoc[iEnd], iBegin-iEnd); if( rc==SQLITE_OK && isHighlight ) rc = fts3StringAppend(pOut, zOpen, -1); if( rc==SQLITE_OK ) rc = fts3StringAppend(pOut, &zDoc[iBegin], iFin-iBegin); if( rc==SQLITE_OK && isHighlight ) rc = fts3StringAppend(pOut, zClose, -1); iEnd = iFin; } pMod->xClose(pC); return rc; } /* ** This function is used to count the entries in a column-list (a ** delta-encoded list of term offsets within a single column of a single ** row). When this function is called, *ppCollist should point to the ** beginning of the first varint in the column-list (the varint that ** contains the position of the first matching term in the column data). ** Before returning, *ppCollist is set to point to the first byte after ** the last varint in the column-list (either the 0x00 signifying the end ** of the position-list, or the 0x01 that precedes the column number of ** the next column in the position-list). ** ** The number of elements in the column-list is returned. */ static int fts3ColumnlistCount(char **ppCollist){ char *pEnd = *ppCollist; char c = 0; int nEntry = 0; /* A column-list is terminated by either a 0x01 or 0x00. */ while( 0xFE & (*pEnd | c) ){ c = *pEnd++ & 0x80; if( !c ) nEntry++; } *ppCollist = pEnd; return nEntry; } /* ** This function gathers 'y' or 'b' data for a single phrase. */ static void fts3ExprLHits( Fts3Expr *pExpr, /* Phrase expression node */ MatchInfo *p /* Matchinfo context */ ){ Fts3Table *pTab = (Fts3Table *)p->pCursor->base.pVtab; int iStart; Fts3Phrase *pPhrase = pExpr->pPhrase; char *pIter = pPhrase->doclist.pList; int iCol = 0; assert( p->flag==FTS3_MATCHINFO_LHITS_BM || p->flag==FTS3_MATCHINFO_LHITS ); if( p->flag==FTS3_MATCHINFO_LHITS ){ iStart = pExpr->iPhrase * p->nCol; }else{ iStart = pExpr->iPhrase * ((p->nCol + 31) / 32); } while( 1 ){ int nHit = fts3ColumnlistCount(&pIter); if( (pPhrase->iColumn>=pTab->nColumn || pPhrase->iColumn==iCol) ){ if( p->flag==FTS3_MATCHINFO_LHITS ){ p->aMatchinfo[iStart + iCol] = (u32)nHit; }else if( nHit ){ p->aMatchinfo[iStart + (iCol+1)/32] |= (1 << (iCol&0x1F)); } } assert( *pIter==0x00 || *pIter==0x01 ); if( *pIter!=0x01 ) break; pIter++; pIter += fts3GetVarint32(pIter, &iCol); } } /* ** Gather the results for matchinfo directives 'y' and 'b'. */ static void fts3ExprLHitGather( Fts3Expr *pExpr, MatchInfo *p ){ assert( (pExpr->pLeft==0)==(pExpr->pRight==0) ); if( pExpr->bEof==0 && pExpr->iDocid==p->pCursor->iPrevId ){ if( pExpr->pLeft ){ fts3ExprLHitGather(pExpr->pLeft, p); fts3ExprLHitGather(pExpr->pRight, p); }else{ fts3ExprLHits(pExpr, p); } } } /* ** fts3ExprIterate() callback used to collect the "global" matchinfo stats ** for a single query. ** ** fts3ExprIterate() callback to load the 'global' elements of a ** FTS3_MATCHINFO_HITS matchinfo array. The global stats are those elements ** of the matchinfo array that are constant for all rows returned by the ** current query. ** ** Argument pCtx is actually a pointer to a struct of type MatchInfo. This ** function populates Matchinfo.aMatchinfo[] as follows: ** ** for(iCol=0; iColpCursor, pExpr, &p->aMatchinfo[3*iPhrase*p->nCol] ); } /* ** fts3ExprIterate() callback used to collect the "local" part of the ** FTS3_MATCHINFO_HITS array. The local stats are those elements of the ** array that are different for each row returned by the query. */ static int fts3ExprLocalHitsCb( Fts3Expr *pExpr, /* Phrase expression node */ int iPhrase, /* Phrase number */ void *pCtx /* Pointer to MatchInfo structure */ ){ int rc = SQLITE_OK; MatchInfo *p = (MatchInfo *)pCtx; int iStart = iPhrase * p->nCol * 3; int i; for(i=0; inCol && rc==SQLITE_OK; i++){ char *pCsr; rc = sqlite3Fts3EvalPhrasePoslist(p->pCursor, pExpr, i, &pCsr); if( pCsr ){ p->aMatchinfo[iStart+i*3] = fts3ColumnlistCount(&pCsr); }else{ p->aMatchinfo[iStart+i*3] = 0; } } return rc; } static int fts3MatchinfoCheck( Fts3Table *pTab, char cArg, char **pzErr ){ if( (cArg==FTS3_MATCHINFO_NPHRASE) || (cArg==FTS3_MATCHINFO_NCOL) || (cArg==FTS3_MATCHINFO_NDOC && pTab->bFts4) || (cArg==FTS3_MATCHINFO_AVGLENGTH && pTab->bFts4) || (cArg==FTS3_MATCHINFO_LENGTH && pTab->bHasDocsize) || (cArg==FTS3_MATCHINFO_LCS) || (cArg==FTS3_MATCHINFO_HITS) || (cArg==FTS3_MATCHINFO_LHITS) || (cArg==FTS3_MATCHINFO_LHITS_BM) ){ return SQLITE_OK; } sqlite3Fts3ErrMsg(pzErr, "unrecognized matchinfo request: %c", cArg); return SQLITE_ERROR; } static int fts3MatchinfoSize(MatchInfo *pInfo, char cArg){ int nVal; /* Number of integers output by cArg */ switch( cArg ){ case FTS3_MATCHINFO_NDOC: case FTS3_MATCHINFO_NPHRASE: case FTS3_MATCHINFO_NCOL: nVal = 1; break; case FTS3_MATCHINFO_AVGLENGTH: case FTS3_MATCHINFO_LENGTH: case FTS3_MATCHINFO_LCS: nVal = pInfo->nCol; break; case FTS3_MATCHINFO_LHITS: nVal = pInfo->nCol * pInfo->nPhrase; break; case FTS3_MATCHINFO_LHITS_BM: nVal = pInfo->nPhrase * ((pInfo->nCol + 31) / 32); break; default: assert( cArg==FTS3_MATCHINFO_HITS ); nVal = pInfo->nCol * pInfo->nPhrase * 3; break; } return nVal; } static int fts3MatchinfoSelectDoctotal( Fts3Table *pTab, sqlite3_stmt **ppStmt, sqlite3_int64 *pnDoc, const char **paLen ){ sqlite3_stmt *pStmt; const char *a; sqlite3_int64 nDoc; if( !*ppStmt ){ int rc = sqlite3Fts3SelectDoctotal(pTab, ppStmt); if( rc!=SQLITE_OK ) return rc; } pStmt = *ppStmt; assert( sqlite3_data_count(pStmt)==1 ); a = sqlite3_column_blob(pStmt, 0); a += sqlite3Fts3GetVarint(a, &nDoc); if( nDoc==0 ) return FTS_CORRUPT_VTAB; *pnDoc = (u32)nDoc; if( paLen ) *paLen = a; return SQLITE_OK; } /* ** An instance of the following structure is used to store state while ** iterating through a multi-column position-list corresponding to the ** hits for a single phrase on a single row in order to calculate the ** values for a matchinfo() FTS3_MATCHINFO_LCS request. */ typedef struct LcsIterator LcsIterator; struct LcsIterator { Fts3Expr *pExpr; /* Pointer to phrase expression */ int iPosOffset; /* Tokens count up to end of this phrase */ char *pRead; /* Cursor used to iterate through aDoclist */ int iPos; /* Current position */ }; /* ** If LcsIterator.iCol is set to the following value, the iterator has ** finished iterating through all offsets for all columns. */ #define LCS_ITERATOR_FINISHED 0x7FFFFFFF; static int fts3MatchinfoLcsCb( Fts3Expr *pExpr, /* Phrase expression node */ int iPhrase, /* Phrase number (numbered from zero) */ void *pCtx /* Pointer to MatchInfo structure */ ){ LcsIterator *aIter = (LcsIterator *)pCtx; aIter[iPhrase].pExpr = pExpr; return SQLITE_OK; } /* ** Advance the iterator passed as an argument to the next position. Return ** 1 if the iterator is at EOF or if it now points to the start of the ** position list for the next column. */ static int fts3LcsIteratorAdvance(LcsIterator *pIter){ char *pRead = pIter->pRead; sqlite3_int64 iRead; int rc = 0; pRead += sqlite3Fts3GetVarint(pRead, &iRead); if( iRead==0 || iRead==1 ){ pRead = 0; rc = 1; }else{ pIter->iPos += (int)(iRead-2); } pIter->pRead = pRead; return rc; } /* ** This function implements the FTS3_MATCHINFO_LCS matchinfo() flag. ** ** If the call is successful, the longest-common-substring lengths for each ** column are written into the first nCol elements of the pInfo->aMatchinfo[] ** array before returning. SQLITE_OK is returned in this case. ** ** Otherwise, if an error occurs, an SQLite error code is returned and the ** data written to the first nCol elements of pInfo->aMatchinfo[] is ** undefined. */ static int fts3MatchinfoLcs(Fts3Cursor *pCsr, MatchInfo *pInfo){ LcsIterator *aIter; int i; int iCol; int nToken = 0; /* Allocate and populate the array of LcsIterator objects. The array ** contains one element for each matchable phrase in the query. **/ aIter = sqlite3_malloc(sizeof(LcsIterator) * pCsr->nPhrase); if( !aIter ) return SQLITE_NOMEM; memset(aIter, 0, sizeof(LcsIterator) * pCsr->nPhrase); (void)fts3ExprIterate(pCsr->pExpr, fts3MatchinfoLcsCb, (void*)aIter); for(i=0; inPhrase; i++){ LcsIterator *pIter = &aIter[i]; nToken -= pIter->pExpr->pPhrase->nToken; pIter->iPosOffset = nToken; } for(iCol=0; iColnCol; iCol++){ int nLcs = 0; /* LCS value for this column */ int nLive = 0; /* Number of iterators in aIter not at EOF */ for(i=0; inPhrase; i++){ int rc; LcsIterator *pIt = &aIter[i]; rc = sqlite3Fts3EvalPhrasePoslist(pCsr, pIt->pExpr, iCol, &pIt->pRead); if( rc!=SQLITE_OK ) return rc; if( pIt->pRead ){ pIt->iPos = pIt->iPosOffset; fts3LcsIteratorAdvance(&aIter[i]); nLive++; } } while( nLive>0 ){ LcsIterator *pAdv = 0; /* The iterator to advance by one position */ int nThisLcs = 0; /* LCS for the current iterator positions */ for(i=0; inPhrase; i++){ LcsIterator *pIter = &aIter[i]; if( pIter->pRead==0 ){ /* This iterator is already at EOF for this column. */ nThisLcs = 0; }else{ if( pAdv==0 || pIter->iPosiPos ){ pAdv = pIter; } if( nThisLcs==0 || pIter->iPos==pIter[-1].iPos ){ nThisLcs++; }else{ nThisLcs = 1; } if( nThisLcs>nLcs ) nLcs = nThisLcs; } } if( fts3LcsIteratorAdvance(pAdv) ) nLive--; } pInfo->aMatchinfo[iCol] = nLcs; } sqlite3_free(aIter); return SQLITE_OK; } /* ** Populate the buffer pInfo->aMatchinfo[] with an array of integers to ** be returned by the matchinfo() function. Argument zArg contains the ** format string passed as the second argument to matchinfo (or the ** default value "pcx" if no second argument was specified). The format ** string has already been validated and the pInfo->aMatchinfo[] array ** is guaranteed to be large enough for the output. ** ** If bGlobal is true, then populate all fields of the matchinfo() output. ** If it is false, then assume that those fields that do not change between ** rows (i.e. FTS3_MATCHINFO_NPHRASE, NCOL, NDOC, AVGLENGTH and part of HITS) ** have already been populated. ** ** Return SQLITE_OK if successful, or an SQLite error code if an error ** occurs. If a value other than SQLITE_OK is returned, the state the ** pInfo->aMatchinfo[] buffer is left in is undefined. */ static int fts3MatchinfoValues( Fts3Cursor *pCsr, /* FTS3 cursor object */ int bGlobal, /* True to grab the global stats */ MatchInfo *pInfo, /* Matchinfo context object */ const char *zArg /* Matchinfo format string */ ){ int rc = SQLITE_OK; int i; Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab; sqlite3_stmt *pSelect = 0; for(i=0; rc==SQLITE_OK && zArg[i]; i++){ pInfo->flag = zArg[i]; switch( zArg[i] ){ case FTS3_MATCHINFO_NPHRASE: if( bGlobal ) pInfo->aMatchinfo[0] = pInfo->nPhrase; break; case FTS3_MATCHINFO_NCOL: if( bGlobal ) pInfo->aMatchinfo[0] = pInfo->nCol; break; case FTS3_MATCHINFO_NDOC: if( bGlobal ){ sqlite3_int64 nDoc = 0; rc = fts3MatchinfoSelectDoctotal(pTab, &pSelect, &nDoc, 0); pInfo->aMatchinfo[0] = (u32)nDoc; } break; case FTS3_MATCHINFO_AVGLENGTH: if( bGlobal ){ sqlite3_int64 nDoc; /* Number of rows in table */ const char *a; /* Aggregate column length array */ rc = fts3MatchinfoSelectDoctotal(pTab, &pSelect, &nDoc, &a); if( rc==SQLITE_OK ){ int iCol; for(iCol=0; iColnCol; iCol++){ u32 iVal; sqlite3_int64 nToken; a += sqlite3Fts3GetVarint(a, &nToken); iVal = (u32)(((u32)(nToken&0xffffffff)+nDoc/2)/nDoc); pInfo->aMatchinfo[iCol] = iVal; } } } break; case FTS3_MATCHINFO_LENGTH: { sqlite3_stmt *pSelectDocsize = 0; rc = sqlite3Fts3SelectDocsize(pTab, pCsr->iPrevId, &pSelectDocsize); if( rc==SQLITE_OK ){ int iCol; const char *a = sqlite3_column_blob(pSelectDocsize, 0); for(iCol=0; iColnCol; iCol++){ sqlite3_int64 nToken; a += sqlite3Fts3GetVarint(a, &nToken); pInfo->aMatchinfo[iCol] = (u32)nToken; } } sqlite3_reset(pSelectDocsize); break; } case FTS3_MATCHINFO_LCS: rc = fts3ExprLoadDoclists(pCsr, 0, 0); if( rc==SQLITE_OK ){ rc = fts3MatchinfoLcs(pCsr, pInfo); } break; case FTS3_MATCHINFO_LHITS_BM: case FTS3_MATCHINFO_LHITS: { int nZero = fts3MatchinfoSize(pInfo, zArg[i]) * sizeof(u32); memset(pInfo->aMatchinfo, 0, nZero); fts3ExprLHitGather(pCsr->pExpr, pInfo); break; } default: { Fts3Expr *pExpr; assert( zArg[i]==FTS3_MATCHINFO_HITS ); pExpr = pCsr->pExpr; rc = fts3ExprLoadDoclists(pCsr, 0, 0); if( rc!=SQLITE_OK ) break; if( bGlobal ){ if( pCsr->pDeferred ){ rc = fts3MatchinfoSelectDoctotal(pTab, &pSelect, &pInfo->nDoc, 0); if( rc!=SQLITE_OK ) break; } rc = fts3ExprIterate(pExpr, fts3ExprGlobalHitsCb,(void*)pInfo); sqlite3Fts3EvalTestDeferred(pCsr, &rc); if( rc!=SQLITE_OK ) break; } (void)fts3ExprIterate(pExpr, fts3ExprLocalHitsCb,(void*)pInfo); break; } } pInfo->aMatchinfo += fts3MatchinfoSize(pInfo, zArg[i]); } sqlite3_reset(pSelect); return rc; } /* ** Populate pCsr->aMatchinfo[] with data for the current row. The ** 'matchinfo' data is an array of 32-bit unsigned integers (C type u32). */ static void fts3GetMatchinfo( sqlite3_context *pCtx, /* Return results here */ Fts3Cursor *pCsr, /* FTS3 Cursor object */ const char *zArg /* Second argument to matchinfo() function */ ){ MatchInfo sInfo; Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab; int rc = SQLITE_OK; int bGlobal = 0; /* Collect 'global' stats as well as local */ u32 *aOut = 0; void (*xDestroyOut)(void*) = 0; memset(&sInfo, 0, sizeof(MatchInfo)); sInfo.pCursor = pCsr; sInfo.nCol = pTab->nColumn; /* If there is cached matchinfo() data, but the format string for the ** cache does not match the format string for this request, discard ** the cached data. */ if( pCsr->pMIBuffer && strcmp(pCsr->pMIBuffer->zMatchinfo, zArg) ){ sqlite3Fts3MIBufferFree(pCsr->pMIBuffer); pCsr->pMIBuffer = 0; } /* If Fts3Cursor.pMIBuffer is NULL, then this is the first time the ** matchinfo function has been called for this query. In this case ** allocate the array used to accumulate the matchinfo data and ** initialize those elements that are constant for every row. */ if( pCsr->pMIBuffer==0 ){ int nMatchinfo = 0; /* Number of u32 elements in match-info */ int i; /* Used to iterate through zArg */ /* Determine the number of phrases in the query */ pCsr->nPhrase = fts3ExprPhraseCount(pCsr->pExpr); sInfo.nPhrase = pCsr->nPhrase; /* Determine the number of integers in the buffer returned by this call. */ for(i=0; zArg[i]; i++){ char *zErr = 0; if( fts3MatchinfoCheck(pTab, zArg[i], &zErr) ){ sqlite3_result_error(pCtx, zErr, -1); sqlite3_free(zErr); return; } nMatchinfo += fts3MatchinfoSize(&sInfo, zArg[i]); } /* Allocate space for Fts3Cursor.aMatchinfo[] and Fts3Cursor.zMatchinfo. */ pCsr->pMIBuffer = fts3MIBufferNew(nMatchinfo, zArg); if( !pCsr->pMIBuffer ) rc = SQLITE_NOMEM; pCsr->isMatchinfoNeeded = 1; bGlobal = 1; } if( rc==SQLITE_OK ){ xDestroyOut = fts3MIBufferAlloc(pCsr->pMIBuffer, &aOut); if( xDestroyOut==0 ){ rc = SQLITE_NOMEM; } } if( rc==SQLITE_OK ){ sInfo.aMatchinfo = aOut; sInfo.nPhrase = pCsr->nPhrase; rc = fts3MatchinfoValues(pCsr, bGlobal, &sInfo, zArg); if( bGlobal ){ fts3MIBufferSetGlobal(pCsr->pMIBuffer); } } if( rc!=SQLITE_OK ){ sqlite3_result_error_code(pCtx, rc); if( xDestroyOut ) xDestroyOut(aOut); }else{ int n = pCsr->pMIBuffer->nElem * sizeof(u32); sqlite3_result_blob(pCtx, aOut, n, xDestroyOut); } } /* ** Implementation of snippet() function. */ SQLITE_PRIVATE void sqlite3Fts3Snippet( sqlite3_context *pCtx, /* SQLite function call context */ Fts3Cursor *pCsr, /* Cursor object */ const char *zStart, /* Snippet start text - "" */ const char *zEnd, /* Snippet end text - "" */ const char *zEllipsis, /* Snippet ellipsis text - "..." */ int iCol, /* Extract snippet from this column */ int nToken /* Approximate number of tokens in snippet */ ){ Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab; int rc = SQLITE_OK; int i; StrBuffer res = {0, 0, 0}; /* The returned text includes up to four fragments of text extracted from ** the data in the current row. The first iteration of the for(...) loop ** below attempts to locate a single fragment of text nToken tokens in ** size that contains at least one instance of all phrases in the query ** expression that appear in the current row. If such a fragment of text ** cannot be found, the second iteration of the loop attempts to locate ** a pair of fragments, and so on. */ int nSnippet = 0; /* Number of fragments in this snippet */ SnippetFragment aSnippet[4]; /* Maximum of 4 fragments per snippet */ int nFToken = -1; /* Number of tokens in each fragment */ if( !pCsr->pExpr ){ sqlite3_result_text(pCtx, "", 0, SQLITE_STATIC); return; } for(nSnippet=1; 1; nSnippet++){ int iSnip; /* Loop counter 0..nSnippet-1 */ u64 mCovered = 0; /* Bitmask of phrases covered by snippet */ u64 mSeen = 0; /* Bitmask of phrases seen by BestSnippet() */ if( nToken>=0 ){ nFToken = (nToken+nSnippet-1) / nSnippet; }else{ nFToken = -1 * nToken; } for(iSnip=0; iSnipnColumn; iRead++){ SnippetFragment sF = {0, 0, 0, 0}; int iS = 0; if( iCol>=0 && iRead!=iCol ) continue; /* Find the best snippet of nFToken tokens in column iRead. */ rc = fts3BestSnippet(nFToken, pCsr, iRead, mCovered, &mSeen, &sF, &iS); if( rc!=SQLITE_OK ){ goto snippet_out; } if( iS>iBestScore ){ *pFragment = sF; iBestScore = iS; } } mCovered |= pFragment->covered; } /* If all query phrases seen by fts3BestSnippet() are present in at least ** one of the nSnippet snippet fragments, break out of the loop. */ assert( (mCovered&mSeen)==mCovered ); if( mSeen==mCovered || nSnippet==SizeofArray(aSnippet) ) break; } assert( nFToken>0 ); for(i=0; ipCsr, pExpr, p->iCol, &pList); nTerm = pExpr->pPhrase->nToken; if( pList ){ fts3GetDeltaPosition(&pList, &iPos); assert( iPos>=0 ); } for(iTerm=0; iTermaTerm[p->iTerm++]; pT->iOff = nTerm-iTerm-1; pT->pList = pList; pT->iPos = iPos; } return rc; } /* ** Implementation of offsets() function. */ SQLITE_PRIVATE void sqlite3Fts3Offsets( sqlite3_context *pCtx, /* SQLite function call context */ Fts3Cursor *pCsr /* Cursor object */ ){ Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab; sqlite3_tokenizer_module const *pMod = pTab->pTokenizer->pModule; int rc; /* Return Code */ int nToken; /* Number of tokens in query */ int iCol; /* Column currently being processed */ StrBuffer res = {0, 0, 0}; /* Result string */ TermOffsetCtx sCtx; /* Context for fts3ExprTermOffsetInit() */ if( !pCsr->pExpr ){ sqlite3_result_text(pCtx, "", 0, SQLITE_STATIC); return; } memset(&sCtx, 0, sizeof(sCtx)); assert( pCsr->isRequireSeek==0 ); /* Count the number of terms in the query */ rc = fts3ExprLoadDoclists(pCsr, 0, &nToken); if( rc!=SQLITE_OK ) goto offsets_out; /* Allocate the array of TermOffset iterators. */ sCtx.aTerm = (TermOffset *)sqlite3_malloc(sizeof(TermOffset)*nToken); if( 0==sCtx.aTerm ){ rc = SQLITE_NOMEM; goto offsets_out; } sCtx.iDocid = pCsr->iPrevId; sCtx.pCsr = pCsr; /* Loop through the table columns, appending offset information to ** string-buffer res for each column. */ for(iCol=0; iColnColumn; iCol++){ sqlite3_tokenizer_cursor *pC; /* Tokenizer cursor */ const char *ZDUMMY; /* Dummy argument used with xNext() */ int NDUMMY = 0; /* Dummy argument used with xNext() */ int iStart = 0; int iEnd = 0; int iCurrent = 0; const char *zDoc; int nDoc; /* Initialize the contents of sCtx.aTerm[] for column iCol. There is ** no way that this operation can fail, so the return code from ** fts3ExprIterate() can be discarded. */ sCtx.iCol = iCol; sCtx.iTerm = 0; (void)fts3ExprIterate(pCsr->pExpr, fts3ExprTermOffsetInit, (void*)&sCtx); /* Retreive the text stored in column iCol. If an SQL NULL is stored ** in column iCol, jump immediately to the next iteration of the loop. ** If an OOM occurs while retrieving the data (this can happen if SQLite ** needs to transform the data from utf-16 to utf-8), return SQLITE_NOMEM ** to the caller. */ zDoc = (const char *)sqlite3_column_text(pCsr->pStmt, iCol+1); nDoc = sqlite3_column_bytes(pCsr->pStmt, iCol+1); if( zDoc==0 ){ if( sqlite3_column_type(pCsr->pStmt, iCol+1)==SQLITE_NULL ){ continue; } rc = SQLITE_NOMEM; goto offsets_out; } /* Initialize a tokenizer iterator to iterate through column iCol. */ rc = sqlite3Fts3OpenTokenizer(pTab->pTokenizer, pCsr->iLangid, zDoc, nDoc, &pC ); if( rc!=SQLITE_OK ) goto offsets_out; rc = pMod->xNext(pC, &ZDUMMY, &NDUMMY, &iStart, &iEnd, &iCurrent); while( rc==SQLITE_OK ){ int i; /* Used to loop through terms */ int iMinPos = 0x7FFFFFFF; /* Position of next token */ TermOffset *pTerm = 0; /* TermOffset associated with next token */ for(i=0; ipList && (pT->iPos-pT->iOff)iPos-pT->iOff; pTerm = pT; } } if( !pTerm ){ /* All offsets for this column have been gathered. */ rc = SQLITE_DONE; }else{ assert( iCurrent<=iMinPos ); if( 0==(0xFE&*pTerm->pList) ){ pTerm->pList = 0; }else{ fts3GetDeltaPosition(&pTerm->pList, &pTerm->iPos); } while( rc==SQLITE_OK && iCurrentxNext(pC, &ZDUMMY, &NDUMMY, &iStart, &iEnd, &iCurrent); } if( rc==SQLITE_OK ){ char aBuffer[64]; sqlite3_snprintf(sizeof(aBuffer), aBuffer, "%d %d %d %d ", iCol, pTerm-sCtx.aTerm, iStart, iEnd-iStart ); rc = fts3StringAppend(&res, aBuffer, -1); }else if( rc==SQLITE_DONE && pTab->zContentTbl==0 ){ rc = FTS_CORRUPT_VTAB; } } } if( rc==SQLITE_DONE ){ rc = SQLITE_OK; } pMod->xClose(pC); if( rc!=SQLITE_OK ) goto offsets_out; } offsets_out: sqlite3_free(sCtx.aTerm); assert( rc!=SQLITE_DONE ); sqlite3Fts3SegmentsClose(pTab); if( rc!=SQLITE_OK ){ sqlite3_result_error_code(pCtx, rc); sqlite3_free(res.z); }else{ sqlite3_result_text(pCtx, res.z, res.n-1, sqlite3_free); } return; } /* ** Implementation of matchinfo() function. */ SQLITE_PRIVATE void sqlite3Fts3Matchinfo( sqlite3_context *pContext, /* Function call context */ Fts3Cursor *pCsr, /* FTS3 table cursor */ const char *zArg /* Second arg to matchinfo() function */ ){ Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab; const char *zFormat; if( zArg ){ zFormat = zArg; }else{ zFormat = FTS3_MATCHINFO_DEFAULT; } if( !pCsr->pExpr ){ sqlite3_result_blob(pContext, "", 0, SQLITE_STATIC); return; }else{ /* Retrieve matchinfo() data. */ fts3GetMatchinfo(pContext, pCsr, zFormat); sqlite3Fts3SegmentsClose(pTab); } } #endif /************** End of fts3_snippet.c ****************************************/ /************** Begin file fts3_unicode.c ************************************/ /* ** 2012 May 24 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ****************************************************************************** ** ** Implementation of the "unicode" full-text-search tokenizer. */ #ifndef SQLITE_DISABLE_FTS3_UNICODE /* #include "fts3Int.h" */ #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) /* #include */ /* #include */ /* #include */ /* #include */ /* #include "fts3_tokenizer.h" */ /* ** The following two macros - READ_UTF8 and WRITE_UTF8 - have been copied ** from the sqlite3 source file utf.c. If this file is compiled as part ** of the amalgamation, they are not required. */ #ifndef SQLITE_AMALGAMATION static const unsigned char sqlite3Utf8Trans1[] = { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x00, 0x01, 0x02, 0x03, 0x00, 0x01, 0x00, 0x00, }; #define READ_UTF8(zIn, zTerm, c) \ c = *(zIn++); \ if( c>=0xc0 ){ \ c = sqlite3Utf8Trans1[c-0xc0]; \ while( zIn!=zTerm && (*zIn & 0xc0)==0x80 ){ \ c = (c<<6) + (0x3f & *(zIn++)); \ } \ if( c<0x80 \ || (c&0xFFFFF800)==0xD800 \ || (c&0xFFFFFFFE)==0xFFFE ){ c = 0xFFFD; } \ } #define WRITE_UTF8(zOut, c) { \ if( c<0x00080 ){ \ *zOut++ = (u8)(c&0xFF); \ } \ else if( c<0x00800 ){ \ *zOut++ = 0xC0 + (u8)((c>>6)&0x1F); \ *zOut++ = 0x80 + (u8)(c & 0x3F); \ } \ else if( c<0x10000 ){ \ *zOut++ = 0xE0 + (u8)((c>>12)&0x0F); \ *zOut++ = 0x80 + (u8)((c>>6) & 0x3F); \ *zOut++ = 0x80 + (u8)(c & 0x3F); \ }else{ \ *zOut++ = 0xF0 + (u8)((c>>18) & 0x07); \ *zOut++ = 0x80 + (u8)((c>>12) & 0x3F); \ *zOut++ = 0x80 + (u8)((c>>6) & 0x3F); \ *zOut++ = 0x80 + (u8)(c & 0x3F); \ } \ } #endif /* ifndef SQLITE_AMALGAMATION */ typedef struct unicode_tokenizer unicode_tokenizer; typedef struct unicode_cursor unicode_cursor; struct unicode_tokenizer { sqlite3_tokenizer base; int bRemoveDiacritic; int nException; int *aiException; }; struct unicode_cursor { sqlite3_tokenizer_cursor base; const unsigned char *aInput; /* Input text being tokenized */ int nInput; /* Size of aInput[] in bytes */ int iOff; /* Current offset within aInput[] */ int iToken; /* Index of next token to be returned */ char *zToken; /* storage for current token */ int nAlloc; /* space allocated at zToken */ }; /* ** Destroy a tokenizer allocated by unicodeCreate(). */ static int unicodeDestroy(sqlite3_tokenizer *pTokenizer){ if( pTokenizer ){ unicode_tokenizer *p = (unicode_tokenizer *)pTokenizer; sqlite3_free(p->aiException); sqlite3_free(p); } return SQLITE_OK; } /* ** As part of a tokenchars= or separators= option, the CREATE VIRTUAL TABLE ** statement has specified that the tokenizer for this table shall consider ** all characters in string zIn/nIn to be separators (if bAlnum==0) or ** token characters (if bAlnum==1). ** ** For each codepoint in the zIn/nIn string, this function checks if the ** sqlite3FtsUnicodeIsalnum() function already returns the desired result. ** If so, no action is taken. Otherwise, the codepoint is added to the ** unicode_tokenizer.aiException[] array. For the purposes of tokenization, ** the return value of sqlite3FtsUnicodeIsalnum() is inverted for all ** codepoints in the aiException[] array. ** ** If a standalone diacritic mark (one that sqlite3FtsUnicodeIsdiacritic() ** identifies as a diacritic) occurs in the zIn/nIn string it is ignored. ** It is not possible to change the behavior of the tokenizer with respect ** to these codepoints. */ static int unicodeAddExceptions( unicode_tokenizer *p, /* Tokenizer to add exceptions to */ int bAlnum, /* Replace Isalnum() return value with this */ const char *zIn, /* Array of characters to make exceptions */ int nIn /* Length of z in bytes */ ){ const unsigned char *z = (const unsigned char *)zIn; const unsigned char *zTerm = &z[nIn]; int iCode; int nEntry = 0; assert( bAlnum==0 || bAlnum==1 ); while( zaiException, (p->nException+nEntry)*sizeof(int)); if( aNew==0 ) return SQLITE_NOMEM; nNew = p->nException; z = (const unsigned char *)zIn; while( zi; j--) aNew[j] = aNew[j-1]; aNew[i] = iCode; nNew++; } } p->aiException = aNew; p->nException = nNew; } return SQLITE_OK; } /* ** Return true if the p->aiException[] array contains the value iCode. */ static int unicodeIsException(unicode_tokenizer *p, int iCode){ if( p->nException>0 ){ int *a = p->aiException; int iLo = 0; int iHi = p->nException-1; while( iHi>=iLo ){ int iTest = (iHi + iLo) / 2; if( iCode==a[iTest] ){ return 1; }else if( iCode>a[iTest] ){ iLo = iTest+1; }else{ iHi = iTest-1; } } } return 0; } /* ** Return true if, for the purposes of tokenization, codepoint iCode is ** considered a token character (not a separator). */ static int unicodeIsAlnum(unicode_tokenizer *p, int iCode){ assert( (sqlite3FtsUnicodeIsalnum(iCode) & 0xFFFFFFFE)==0 ); return sqlite3FtsUnicodeIsalnum(iCode) ^ unicodeIsException(p, iCode); } /* ** Create a new tokenizer instance. */ static int unicodeCreate( int nArg, /* Size of array argv[] */ const char * const *azArg, /* Tokenizer creation arguments */ sqlite3_tokenizer **pp /* OUT: New tokenizer handle */ ){ unicode_tokenizer *pNew; /* New tokenizer object */ int i; int rc = SQLITE_OK; pNew = (unicode_tokenizer *) sqlite3_malloc(sizeof(unicode_tokenizer)); if( pNew==NULL ) return SQLITE_NOMEM; memset(pNew, 0, sizeof(unicode_tokenizer)); pNew->bRemoveDiacritic = 1; for(i=0; rc==SQLITE_OK && ibRemoveDiacritic = 1; } else if( n==19 && memcmp("remove_diacritics=0", z, 19)==0 ){ pNew->bRemoveDiacritic = 0; } else if( n>=11 && memcmp("tokenchars=", z, 11)==0 ){ rc = unicodeAddExceptions(pNew, 1, &z[11], n-11); } else if( n>=11 && memcmp("separators=", z, 11)==0 ){ rc = unicodeAddExceptions(pNew, 0, &z[11], n-11); } else{ /* Unrecognized argument */ rc = SQLITE_ERROR; } } if( rc!=SQLITE_OK ){ unicodeDestroy((sqlite3_tokenizer *)pNew); pNew = 0; } *pp = (sqlite3_tokenizer *)pNew; return rc; } /* ** Prepare to begin tokenizing a particular string. The input ** string to be tokenized is pInput[0..nBytes-1]. A cursor ** used to incrementally tokenize this string is returned in ** *ppCursor. */ static int unicodeOpen( sqlite3_tokenizer *p, /* The tokenizer */ const char *aInput, /* Input string */ int nInput, /* Size of string aInput in bytes */ sqlite3_tokenizer_cursor **pp /* OUT: New cursor object */ ){ unicode_cursor *pCsr; pCsr = (unicode_cursor *)sqlite3_malloc(sizeof(unicode_cursor)); if( pCsr==0 ){ return SQLITE_NOMEM; } memset(pCsr, 0, sizeof(unicode_cursor)); pCsr->aInput = (const unsigned char *)aInput; if( aInput==0 ){ pCsr->nInput = 0; }else if( nInput<0 ){ pCsr->nInput = (int)strlen(aInput); }else{ pCsr->nInput = nInput; } *pp = &pCsr->base; UNUSED_PARAMETER(p); return SQLITE_OK; } /* ** Close a tokenization cursor previously opened by a call to ** simpleOpen() above. */ static int unicodeClose(sqlite3_tokenizer_cursor *pCursor){ unicode_cursor *pCsr = (unicode_cursor *) pCursor; sqlite3_free(pCsr->zToken); sqlite3_free(pCsr); return SQLITE_OK; } /* ** Extract the next token from a tokenization cursor. The cursor must ** have been opened by a prior call to simpleOpen(). */ static int unicodeNext( sqlite3_tokenizer_cursor *pC, /* Cursor returned by simpleOpen */ const char **paToken, /* OUT: Token text */ int *pnToken, /* OUT: Number of bytes at *paToken */ int *piStart, /* OUT: Starting offset of token */ int *piEnd, /* OUT: Ending offset of token */ int *piPos /* OUT: Position integer of token */ ){ unicode_cursor *pCsr = (unicode_cursor *)pC; unicode_tokenizer *p = ((unicode_tokenizer *)pCsr->base.pTokenizer); int iCode = 0; char *zOut; const unsigned char *z = &pCsr->aInput[pCsr->iOff]; const unsigned char *zStart = z; const unsigned char *zEnd; const unsigned char *zTerm = &pCsr->aInput[pCsr->nInput]; /* Scan past any delimiter characters before the start of the next token. ** Return SQLITE_DONE early if this takes us all the way to the end of ** the input. */ while( z=zTerm ) return SQLITE_DONE; zOut = pCsr->zToken; do { int iOut; /* Grow the output buffer if required. */ if( (zOut-pCsr->zToken)>=(pCsr->nAlloc-4) ){ char *zNew = sqlite3_realloc(pCsr->zToken, pCsr->nAlloc+64); if( !zNew ) return SQLITE_NOMEM; zOut = &zNew[zOut - pCsr->zToken]; pCsr->zToken = zNew; pCsr->nAlloc += 64; } /* Write the folded case of the last character read to the output */ zEnd = z; iOut = sqlite3FtsUnicodeFold(iCode, p->bRemoveDiacritic); if( iOut ){ WRITE_UTF8(zOut, iOut); } /* If the cursor is not at EOF, read the next character */ if( z>=zTerm ) break; READ_UTF8(z, zTerm, iCode); }while( unicodeIsAlnum(p, iCode) || sqlite3FtsUnicodeIsdiacritic(iCode) ); /* Set the output variables and return. */ pCsr->iOff = (int)(z - pCsr->aInput); *paToken = pCsr->zToken; *pnToken = (int)(zOut - pCsr->zToken); *piStart = (int)(zStart - pCsr->aInput); *piEnd = (int)(zEnd - pCsr->aInput); *piPos = pCsr->iToken++; return SQLITE_OK; } /* ** Set *ppModule to a pointer to the sqlite3_tokenizer_module ** structure for the unicode tokenizer. */ SQLITE_PRIVATE void sqlite3Fts3UnicodeTokenizer(sqlite3_tokenizer_module const **ppModule){ static const sqlite3_tokenizer_module module = { 0, unicodeCreate, unicodeDestroy, unicodeOpen, unicodeClose, unicodeNext, 0, }; *ppModule = &module; } #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */ #endif /* ifndef SQLITE_DISABLE_FTS3_UNICODE */ /************** End of fts3_unicode.c ****************************************/ /************** Begin file fts3_unicode2.c ***********************************/ /* ** 2012 May 25 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ****************************************************************************** */ /* ** DO NOT EDIT THIS MACHINE GENERATED FILE. */ #ifndef SQLITE_DISABLE_FTS3_UNICODE #if defined(SQLITE_ENABLE_FTS3) || defined(SQLITE_ENABLE_FTS4) /* #include */ /* ** Return true if the argument corresponds to a unicode codepoint ** classified as either a letter or a number. Otherwise false. ** ** The results are undefined if the value passed to this function ** is less than zero. */ SQLITE_PRIVATE int sqlite3FtsUnicodeIsalnum(int c){ /* Each unsigned integer in the following array corresponds to a contiguous ** range of unicode codepoints that are not either letters or numbers (i.e. ** codepoints for which this function should return 0). ** ** The most significant 22 bits in each 32-bit value contain the first ** codepoint in the range. The least significant 10 bits are used to store ** the size of the range (always at least 1). In other words, the value ** ((C<<22) + N) represents a range of N codepoints starting with codepoint ** C. It is not possible to represent a range larger than 1023 codepoints ** using this format. */ static const unsigned int aEntry[] = { 0x00000030, 0x0000E807, 0x00016C06, 0x0001EC2F, 0x0002AC07, 0x0002D001, 0x0002D803, 0x0002EC01, 0x0002FC01, 0x00035C01, 0x0003DC01, 0x000B0804, 0x000B480E, 0x000B9407, 0x000BB401, 0x000BBC81, 0x000DD401, 0x000DF801, 0x000E1002, 0x000E1C01, 0x000FD801, 0x00120808, 0x00156806, 0x00162402, 0x00163C01, 0x00164437, 0x0017CC02, 0x00180005, 0x00181816, 0x00187802, 0x00192C15, 0x0019A804, 0x0019C001, 0x001B5001, 0x001B580F, 0x001B9C07, 0x001BF402, 0x001C000E, 0x001C3C01, 0x001C4401, 0x001CC01B, 0x001E980B, 0x001FAC09, 0x001FD804, 0x00205804, 0x00206C09, 0x00209403, 0x0020A405, 0x0020C00F, 0x00216403, 0x00217801, 0x0023901B, 0x00240004, 0x0024E803, 0x0024F812, 0x00254407, 0x00258804, 0x0025C001, 0x00260403, 0x0026F001, 0x0026F807, 0x00271C02, 0x00272C03, 0x00275C01, 0x00278802, 0x0027C802, 0x0027E802, 0x00280403, 0x0028F001, 0x0028F805, 0x00291C02, 0x00292C03, 0x00294401, 0x0029C002, 0x0029D401, 0x002A0403, 0x002AF001, 0x002AF808, 0x002B1C03, 0x002B2C03, 0x002B8802, 0x002BC002, 0x002C0403, 0x002CF001, 0x002CF807, 0x002D1C02, 0x002D2C03, 0x002D5802, 0x002D8802, 0x002DC001, 0x002E0801, 0x002EF805, 0x002F1803, 0x002F2804, 0x002F5C01, 0x002FCC08, 0x00300403, 0x0030F807, 0x00311803, 0x00312804, 0x00315402, 0x00318802, 0x0031FC01, 0x00320802, 0x0032F001, 0x0032F807, 0x00331803, 0x00332804, 0x00335402, 0x00338802, 0x00340802, 0x0034F807, 0x00351803, 0x00352804, 0x00355C01, 0x00358802, 0x0035E401, 0x00360802, 0x00372801, 0x00373C06, 0x00375801, 0x00376008, 0x0037C803, 0x0038C401, 0x0038D007, 0x0038FC01, 0x00391C09, 0x00396802, 0x003AC401, 0x003AD006, 0x003AEC02, 0x003B2006, 0x003C041F, 0x003CD00C, 0x003DC417, 0x003E340B, 0x003E6424, 0x003EF80F, 0x003F380D, 0x0040AC14, 0x00412806, 0x00415804, 0x00417803, 0x00418803, 0x00419C07, 0x0041C404, 0x0042080C, 0x00423C01, 0x00426806, 0x0043EC01, 0x004D740C, 0x004E400A, 0x00500001, 0x0059B402, 0x005A0001, 0x005A6C02, 0x005BAC03, 0x005C4803, 0x005CC805, 0x005D4802, 0x005DC802, 0x005ED023, 0x005F6004, 0x005F7401, 0x0060000F, 0x0062A401, 0x0064800C, 0x0064C00C, 0x00650001, 0x00651002, 0x0066C011, 0x00672002, 0x00677822, 0x00685C05, 0x00687802, 0x0069540A, 0x0069801D, 0x0069FC01, 0x006A8007, 0x006AA006, 0x006C0005, 0x006CD011, 0x006D6823, 0x006E0003, 0x006E840D, 0x006F980E, 0x006FF004, 0x00709014, 0x0070EC05, 0x0071F802, 0x00730008, 0x00734019, 0x0073B401, 0x0073C803, 0x00770027, 0x0077F004, 0x007EF401, 0x007EFC03, 0x007F3403, 0x007F7403, 0x007FB403, 0x007FF402, 0x00800065, 0x0081A806, 0x0081E805, 0x00822805, 0x0082801A, 0x00834021, 0x00840002, 0x00840C04, 0x00842002, 0x00845001, 0x00845803, 0x00847806, 0x00849401, 0x00849C01, 0x0084A401, 0x0084B801, 0x0084E802, 0x00850005, 0x00852804, 0x00853C01, 0x00864264, 0x00900027, 0x0091000B, 0x0092704E, 0x00940200, 0x009C0475, 0x009E53B9, 0x00AD400A, 0x00B39406, 0x00B3BC03, 0x00B3E404, 0x00B3F802, 0x00B5C001, 0x00B5FC01, 0x00B7804F, 0x00B8C00C, 0x00BA001A, 0x00BA6C59, 0x00BC00D6, 0x00BFC00C, 0x00C00005, 0x00C02019, 0x00C0A807, 0x00C0D802, 0x00C0F403, 0x00C26404, 0x00C28001, 0x00C3EC01, 0x00C64002, 0x00C6580A, 0x00C70024, 0x00C8001F, 0x00C8A81E, 0x00C94001, 0x00C98020, 0x00CA2827, 0x00CB003F, 0x00CC0100, 0x01370040, 0x02924037, 0x0293F802, 0x02983403, 0x0299BC10, 0x029A7C01, 0x029BC008, 0x029C0017, 0x029C8002, 0x029E2402, 0x02A00801, 0x02A01801, 0x02A02C01, 0x02A08C09, 0x02A0D804, 0x02A1D004, 0x02A20002, 0x02A2D011, 0x02A33802, 0x02A38012, 0x02A3E003, 0x02A4980A, 0x02A51C0D, 0x02A57C01, 0x02A60004, 0x02A6CC1B, 0x02A77802, 0x02A8A40E, 0x02A90C01, 0x02A93002, 0x02A97004, 0x02A9DC03, 0x02A9EC01, 0x02AAC001, 0x02AAC803, 0x02AADC02, 0x02AAF802, 0x02AB0401, 0x02AB7802, 0x02ABAC07, 0x02ABD402, 0x02AF8C0B, 0x03600001, 0x036DFC02, 0x036FFC02, 0x037FFC01, 0x03EC7801, 0x03ECA401, 0x03EEC810, 0x03F4F802, 0x03F7F002, 0x03F8001A, 0x03F88007, 0x03F8C023, 0x03F95013, 0x03F9A004, 0x03FBFC01, 0x03FC040F, 0x03FC6807, 0x03FCEC06, 0x03FD6C0B, 0x03FF8007, 0x03FFA007, 0x03FFE405, 0x04040003, 0x0404DC09, 0x0405E411, 0x0406400C, 0x0407402E, 0x040E7C01, 0x040F4001, 0x04215C01, 0x04247C01, 0x0424FC01, 0x04280403, 0x04281402, 0x04283004, 0x0428E003, 0x0428FC01, 0x04294009, 0x0429FC01, 0x042CE407, 0x04400003, 0x0440E016, 0x04420003, 0x0442C012, 0x04440003, 0x04449C0E, 0x04450004, 0x04460003, 0x0446CC0E, 0x04471404, 0x045AAC0D, 0x0491C004, 0x05BD442E, 0x05BE3C04, 0x074000F6, 0x07440027, 0x0744A4B5, 0x07480046, 0x074C0057, 0x075B0401, 0x075B6C01, 0x075BEC01, 0x075C5401, 0x075CD401, 0x075D3C01, 0x075DBC01, 0x075E2401, 0x075EA401, 0x075F0C01, 0x07BBC002, 0x07C0002C, 0x07C0C064, 0x07C2800F, 0x07C2C40E, 0x07C3040F, 0x07C3440F, 0x07C4401F, 0x07C4C03C, 0x07C5C02B, 0x07C7981D, 0x07C8402B, 0x07C90009, 0x07C94002, 0x07CC0021, 0x07CCC006, 0x07CCDC46, 0x07CE0014, 0x07CE8025, 0x07CF1805, 0x07CF8011, 0x07D0003F, 0x07D10001, 0x07D108B6, 0x07D3E404, 0x07D4003E, 0x07D50004, 0x07D54018, 0x07D7EC46, 0x07D9140B, 0x07DA0046, 0x07DC0074, 0x38000401, 0x38008060, 0x380400F0, }; static const unsigned int aAscii[4] = { 0xFFFFFFFF, 0xFC00FFFF, 0xF8000001, 0xF8000001, }; if( c<128 ){ return ( (aAscii[c >> 5] & (1 << (c & 0x001F)))==0 ); }else if( c<(1<<22) ){ unsigned int key = (((unsigned int)c)<<10) | 0x000003FF; int iRes = 0; int iHi = sizeof(aEntry)/sizeof(aEntry[0]) - 1; int iLo = 0; while( iHi>=iLo ){ int iTest = (iHi + iLo) / 2; if( key >= aEntry[iTest] ){ iRes = iTest; iLo = iTest+1; }else{ iHi = iTest-1; } } assert( aEntry[0]=aEntry[iRes] ); return (((unsigned int)c) >= ((aEntry[iRes]>>10) + (aEntry[iRes]&0x3FF))); } return 1; } /* ** If the argument is a codepoint corresponding to a lowercase letter ** in the ASCII range with a diacritic added, return the codepoint ** of the ASCII letter only. For example, if passed 235 - "LATIN ** SMALL LETTER E WITH DIAERESIS" - return 65 ("LATIN SMALL LETTER ** E"). The resuls of passing a codepoint that corresponds to an ** uppercase letter are undefined. */ static int remove_diacritic(int c){ unsigned short aDia[] = { 0, 1797, 1848, 1859, 1891, 1928, 1940, 1995, 2024, 2040, 2060, 2110, 2168, 2206, 2264, 2286, 2344, 2383, 2472, 2488, 2516, 2596, 2668, 2732, 2782, 2842, 2894, 2954, 2984, 3000, 3028, 3336, 3456, 3696, 3712, 3728, 3744, 3896, 3912, 3928, 3968, 4008, 4040, 4106, 4138, 4170, 4202, 4234, 4266, 4296, 4312, 4344, 4408, 4424, 4472, 4504, 6148, 6198, 6264, 6280, 6360, 6429, 6505, 6529, 61448, 61468, 61534, 61592, 61642, 61688, 61704, 61726, 61784, 61800, 61836, 61880, 61914, 61948, 61998, 62122, 62154, 62200, 62218, 62302, 62364, 62442, 62478, 62536, 62554, 62584, 62604, 62640, 62648, 62656, 62664, 62730, 62924, 63050, 63082, 63274, 63390, }; char aChar[] = { '\0', 'a', 'c', 'e', 'i', 'n', 'o', 'u', 'y', 'y', 'a', 'c', 'd', 'e', 'e', 'g', 'h', 'i', 'j', 'k', 'l', 'n', 'o', 'r', 's', 't', 'u', 'u', 'w', 'y', 'z', 'o', 'u', 'a', 'i', 'o', 'u', 'g', 'k', 'o', 'j', 'g', 'n', 'a', 'e', 'i', 'o', 'r', 'u', 's', 't', 'h', 'a', 'e', 'o', 'y', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', 'a', 'b', 'd', 'd', 'e', 'f', 'g', 'h', 'h', 'i', 'k', 'l', 'l', 'm', 'n', 'p', 'r', 'r', 's', 't', 'u', 'v', 'w', 'w', 'x', 'y', 'z', 'h', 't', 'w', 'y', 'a', 'e', 'i', 'o', 'u', 'y', }; unsigned int key = (((unsigned int)c)<<3) | 0x00000007; int iRes = 0; int iHi = sizeof(aDia)/sizeof(aDia[0]) - 1; int iLo = 0; while( iHi>=iLo ){ int iTest = (iHi + iLo) / 2; if( key >= aDia[iTest] ){ iRes = iTest; iLo = iTest+1; }else{ iHi = iTest-1; } } assert( key>=aDia[iRes] ); return ((c > (aDia[iRes]>>3) + (aDia[iRes]&0x07)) ? c : (int)aChar[iRes]); } /* ** Return true if the argument interpreted as a unicode codepoint ** is a diacritical modifier character. */ SQLITE_PRIVATE int sqlite3FtsUnicodeIsdiacritic(int c){ unsigned int mask0 = 0x08029FDF; unsigned int mask1 = 0x000361F8; if( c<768 || c>817 ) return 0; return (c < 768+32) ? (mask0 & (1 << (c-768))) : (mask1 & (1 << (c-768-32))); } /* ** Interpret the argument as a unicode codepoint. If the codepoint ** is an upper case character that has a lower case equivalent, ** return the codepoint corresponding to the lower case version. ** Otherwise, return a copy of the argument. ** ** The results are undefined if the value passed to this function ** is less than zero. */ SQLITE_PRIVATE int sqlite3FtsUnicodeFold(int c, int bRemoveDiacritic){ /* Each entry in the following array defines a rule for folding a range ** of codepoints to lower case. The rule applies to a range of nRange ** codepoints starting at codepoint iCode. ** ** If the least significant bit in flags is clear, then the rule applies ** to all nRange codepoints (i.e. all nRange codepoints are upper case and ** need to be folded). Or, if it is set, then the rule only applies to ** every second codepoint in the range, starting with codepoint C. ** ** The 7 most significant bits in flags are an index into the aiOff[] ** array. If a specific codepoint C does require folding, then its lower ** case equivalent is ((C + aiOff[flags>>1]) & 0xFFFF). ** ** The contents of this array are generated by parsing the CaseFolding.txt ** file distributed as part of the "Unicode Character Database". See ** http://www.unicode.org for details. */ static const struct TableEntry { unsigned short iCode; unsigned char flags; unsigned char nRange; } aEntry[] = { {65, 14, 26}, {181, 64, 1}, {192, 14, 23}, {216, 14, 7}, {256, 1, 48}, {306, 1, 6}, {313, 1, 16}, {330, 1, 46}, {376, 116, 1}, {377, 1, 6}, {383, 104, 1}, {385, 50, 1}, {386, 1, 4}, {390, 44, 1}, {391, 0, 1}, {393, 42, 2}, {395, 0, 1}, {398, 32, 1}, {399, 38, 1}, {400, 40, 1}, {401, 0, 1}, {403, 42, 1}, {404, 46, 1}, {406, 52, 1}, {407, 48, 1}, {408, 0, 1}, {412, 52, 1}, {413, 54, 1}, {415, 56, 1}, {416, 1, 6}, {422, 60, 1}, {423, 0, 1}, {425, 60, 1}, {428, 0, 1}, {430, 60, 1}, {431, 0, 1}, {433, 58, 2}, {435, 1, 4}, {439, 62, 1}, {440, 0, 1}, {444, 0, 1}, {452, 2, 1}, {453, 0, 1}, {455, 2, 1}, {456, 0, 1}, {458, 2, 1}, {459, 1, 18}, {478, 1, 18}, {497, 2, 1}, {498, 1, 4}, {502, 122, 1}, {503, 134, 1}, {504, 1, 40}, {544, 110, 1}, {546, 1, 18}, {570, 70, 1}, {571, 0, 1}, {573, 108, 1}, {574, 68, 1}, {577, 0, 1}, {579, 106, 1}, {580, 28, 1}, {581, 30, 1}, {582, 1, 10}, {837, 36, 1}, {880, 1, 4}, {886, 0, 1}, {902, 18, 1}, {904, 16, 3}, {908, 26, 1}, {910, 24, 2}, {913, 14, 17}, {931, 14, 9}, {962, 0, 1}, {975, 4, 1}, {976, 140, 1}, {977, 142, 1}, {981, 146, 1}, {982, 144, 1}, {984, 1, 24}, {1008, 136, 1}, {1009, 138, 1}, {1012, 130, 1}, {1013, 128, 1}, {1015, 0, 1}, {1017, 152, 1}, {1018, 0, 1}, {1021, 110, 3}, {1024, 34, 16}, {1040, 14, 32}, {1120, 1, 34}, {1162, 1, 54}, {1216, 6, 1}, {1217, 1, 14}, {1232, 1, 88}, {1329, 22, 38}, {4256, 66, 38}, {4295, 66, 1}, {4301, 66, 1}, {7680, 1, 150}, {7835, 132, 1}, {7838, 96, 1}, {7840, 1, 96}, {7944, 150, 8}, {7960, 150, 6}, {7976, 150, 8}, {7992, 150, 8}, {8008, 150, 6}, {8025, 151, 8}, {8040, 150, 8}, {8072, 150, 8}, {8088, 150, 8}, {8104, 150, 8}, {8120, 150, 2}, {8122, 126, 2}, {8124, 148, 1}, {8126, 100, 1}, {8136, 124, 4}, {8140, 148, 1}, {8152, 150, 2}, {8154, 120, 2}, {8168, 150, 2}, {8170, 118, 2}, {8172, 152, 1}, {8184, 112, 2}, {8186, 114, 2}, {8188, 148, 1}, {8486, 98, 1}, {8490, 92, 1}, {8491, 94, 1}, {8498, 12, 1}, {8544, 8, 16}, {8579, 0, 1}, {9398, 10, 26}, {11264, 22, 47}, {11360, 0, 1}, {11362, 88, 1}, {11363, 102, 1}, {11364, 90, 1}, {11367, 1, 6}, {11373, 84, 1}, {11374, 86, 1}, {11375, 80, 1}, {11376, 82, 1}, {11378, 0, 1}, {11381, 0, 1}, {11390, 78, 2}, {11392, 1, 100}, {11499, 1, 4}, {11506, 0, 1}, {42560, 1, 46}, {42624, 1, 24}, {42786, 1, 14}, {42802, 1, 62}, {42873, 1, 4}, {42877, 76, 1}, {42878, 1, 10}, {42891, 0, 1}, {42893, 74, 1}, {42896, 1, 4}, {42912, 1, 10}, {42922, 72, 1}, {65313, 14, 26}, }; static const unsigned short aiOff[] = { 1, 2, 8, 15, 16, 26, 28, 32, 37, 38, 40, 48, 63, 64, 69, 71, 79, 80, 116, 202, 203, 205, 206, 207, 209, 210, 211, 213, 214, 217, 218, 219, 775, 7264, 10792, 10795, 23228, 23256, 30204, 54721, 54753, 54754, 54756, 54787, 54793, 54809, 57153, 57274, 57921, 58019, 58363, 61722, 65268, 65341, 65373, 65406, 65408, 65410, 65415, 65424, 65436, 65439, 65450, 65462, 65472, 65476, 65478, 65480, 65482, 65488, 65506, 65511, 65514, 65521, 65527, 65528, 65529, }; int ret = c; assert( c>=0 ); assert( sizeof(unsigned short)==2 && sizeof(unsigned char)==1 ); if( c<128 ){ if( c>='A' && c<='Z' ) ret = c + ('a' - 'A'); }else if( c<65536 ){ int iHi = sizeof(aEntry)/sizeof(aEntry[0]) - 1; int iLo = 0; int iRes = -1; while( iHi>=iLo ){ int iTest = (iHi + iLo) / 2; int cmp = (c - aEntry[iTest].iCode); if( cmp>=0 ){ iRes = iTest; iLo = iTest+1; }else{ iHi = iTest-1; } } assert( iRes<0 || c>=aEntry[iRes].iCode ); if( iRes>=0 ){ const struct TableEntry *p = &aEntry[iRes]; if( c<(p->iCode + p->nRange) && 0==(0x01 & p->flags & (p->iCode ^ c)) ){ ret = (c + (aiOff[p->flags>>1])) & 0x0000FFFF; assert( ret>0 ); } } if( bRemoveDiacritic ) ret = remove_diacritic(ret); } else if( c>=66560 && c<66600 ){ ret = c + 40; } return ret; } #endif /* defined(SQLITE_ENABLE_FTS3) || defined(SQLITE_ENABLE_FTS4) */ #endif /* !defined(SQLITE_DISABLE_FTS3_UNICODE) */ /************** End of fts3_unicode2.c ***************************************/ /************** Begin file rtree.c *******************************************/ /* ** 2001 September 15 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ************************************************************************* ** This file contains code for implementations of the r-tree and r*-tree ** algorithms packaged as an SQLite virtual table module. */ /* ** Database Format of R-Tree Tables ** -------------------------------- ** ** The data structure for a single virtual r-tree table is stored in three ** native SQLite tables declared as follows. In each case, the '%' character ** in the table name is replaced with the user-supplied name of the r-tree ** table. ** ** CREATE TABLE %_node(nodeno INTEGER PRIMARY KEY, data BLOB) ** CREATE TABLE %_parent(nodeno INTEGER PRIMARY KEY, parentnode INTEGER) ** CREATE TABLE %_rowid(rowid INTEGER PRIMARY KEY, nodeno INTEGER) ** ** The data for each node of the r-tree structure is stored in the %_node ** table. For each node that is not the root node of the r-tree, there is ** an entry in the %_parent table associating the node with its parent. ** And for each row of data in the table, there is an entry in the %_rowid ** table that maps from the entries rowid to the id of the node that it ** is stored on. ** ** The root node of an r-tree always exists, even if the r-tree table is ** empty. The nodeno of the root node is always 1. All other nodes in the ** table must be the same size as the root node. The content of each node ** is formatted as follows: ** ** 1. If the node is the root node (node 1), then the first 2 bytes ** of the node contain the tree depth as a big-endian integer. ** For non-root nodes, the first 2 bytes are left unused. ** ** 2. The next 2 bytes contain the number of entries currently ** stored in the node. ** ** 3. The remainder of the node contains the node entries. Each entry ** consists of a single 8-byte integer followed by an even number ** of 4-byte coordinates. For leaf nodes the integer is the rowid ** of a record. For internal nodes it is the node number of a ** child page. */ #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_RTREE) #ifndef SQLITE_CORE /* #include "sqlite3ext.h" */ SQLITE_EXTENSION_INIT1 #else /* #include "sqlite3.h" */ #endif /* #include */ /* #include */ /* #include */ #ifndef SQLITE_AMALGAMATION #include "sqlite3rtree.h" typedef sqlite3_int64 i64; typedef unsigned char u8; typedef unsigned short u16; typedef unsigned int u32; #endif /* The following macro is used to suppress compiler warnings. */ #ifndef UNUSED_PARAMETER # define UNUSED_PARAMETER(x) (void)(x) #endif typedef struct Rtree Rtree; typedef struct RtreeCursor RtreeCursor; typedef struct RtreeNode RtreeNode; typedef struct RtreeCell RtreeCell; typedef struct RtreeConstraint RtreeConstraint; typedef struct RtreeMatchArg RtreeMatchArg; typedef struct RtreeGeomCallback RtreeGeomCallback; typedef union RtreeCoord RtreeCoord; typedef struct RtreeSearchPoint RtreeSearchPoint; /* The rtree may have between 1 and RTREE_MAX_DIMENSIONS dimensions. */ #define RTREE_MAX_DIMENSIONS 5 /* Size of hash table Rtree.aHash. This hash table is not expected to ** ever contain very many entries, so a fixed number of buckets is ** used. */ #define HASHSIZE 97 /* The xBestIndex method of this virtual table requires an estimate of ** the number of rows in the virtual table to calculate the costs of ** various strategies. If possible, this estimate is loaded from the ** sqlite_stat1 table (with RTREE_MIN_ROWEST as a hard-coded minimum). ** Otherwise, if no sqlite_stat1 entry is available, use ** RTREE_DEFAULT_ROWEST. */ #define RTREE_DEFAULT_ROWEST 1048576 #define RTREE_MIN_ROWEST 100 /* ** An rtree virtual-table object. */ struct Rtree { sqlite3_vtab base; /* Base class. Must be first */ sqlite3 *db; /* Host database connection */ int iNodeSize; /* Size in bytes of each node in the node table */ u8 nDim; /* Number of dimensions */ u8 eCoordType; /* RTREE_COORD_REAL32 or RTREE_COORD_INT32 */ u8 nBytesPerCell; /* Bytes consumed per cell */ int iDepth; /* Current depth of the r-tree structure */ char *zDb; /* Name of database containing r-tree table */ char *zName; /* Name of r-tree table */ int nBusy; /* Current number of users of this structure */ i64 nRowEst; /* Estimated number of rows in this table */ /* List of nodes removed during a CondenseTree operation. List is ** linked together via the pointer normally used for hash chains - ** RtreeNode.pNext. RtreeNode.iNode stores the depth of the sub-tree ** headed by the node (leaf nodes have RtreeNode.iNode==0). */ RtreeNode *pDeleted; int iReinsertHeight; /* Height of sub-trees Reinsert() has run on */ /* Statements to read/write/delete a record from xxx_node */ sqlite3_stmt *pReadNode; sqlite3_stmt *pWriteNode; sqlite3_stmt *pDeleteNode; /* Statements to read/write/delete a record from xxx_rowid */ sqlite3_stmt *pReadRowid; sqlite3_stmt *pWriteRowid; sqlite3_stmt *pDeleteRowid; /* Statements to read/write/delete a record from xxx_parent */ sqlite3_stmt *pReadParent; sqlite3_stmt *pWriteParent; sqlite3_stmt *pDeleteParent; RtreeNode *aHash[HASHSIZE]; /* Hash table of in-memory nodes. */ }; /* Possible values for Rtree.eCoordType: */ #define RTREE_COORD_REAL32 0 #define RTREE_COORD_INT32 1 /* ** If SQLITE_RTREE_INT_ONLY is defined, then this virtual table will ** only deal with integer coordinates. No floating point operations ** will be done. */ #ifdef SQLITE_RTREE_INT_ONLY typedef sqlite3_int64 RtreeDValue; /* High accuracy coordinate */ typedef int RtreeValue; /* Low accuracy coordinate */ # define RTREE_ZERO 0 #else typedef double RtreeDValue; /* High accuracy coordinate */ typedef float RtreeValue; /* Low accuracy coordinate */ # define RTREE_ZERO 0.0 #endif /* ** When doing a search of an r-tree, instances of the following structure ** record intermediate results from the tree walk. ** ** The id is always a node-id. For iLevel>=1 the id is the node-id of ** the node that the RtreeSearchPoint represents. When iLevel==0, however, ** the id is of the parent node and the cell that RtreeSearchPoint ** represents is the iCell-th entry in the parent node. */ struct RtreeSearchPoint { RtreeDValue rScore; /* The score for this node. Smallest goes first. */ sqlite3_int64 id; /* Node ID */ u8 iLevel; /* 0=entries. 1=leaf node. 2+ for higher */ u8 eWithin; /* PARTLY_WITHIN or FULLY_WITHIN */ u8 iCell; /* Cell index within the node */ }; /* ** The minimum number of cells allowed for a node is a third of the ** maximum. In Gutman's notation: ** ** m = M/3 ** ** If an R*-tree "Reinsert" operation is required, the same number of ** cells are removed from the overfull node and reinserted into the tree. */ #define RTREE_MINCELLS(p) ((((p)->iNodeSize-4)/(p)->nBytesPerCell)/3) #define RTREE_REINSERT(p) RTREE_MINCELLS(p) #define RTREE_MAXCELLS 51 /* ** The smallest possible node-size is (512-64)==448 bytes. And the largest ** supported cell size is 48 bytes (8 byte rowid + ten 4 byte coordinates). ** Therefore all non-root nodes must contain at least 3 entries. Since ** 2^40 is greater than 2^64, an r-tree structure always has a depth of ** 40 or less. */ #define RTREE_MAX_DEPTH 40 /* ** Number of entries in the cursor RtreeNode cache. The first entry is ** used to cache the RtreeNode for RtreeCursor.sPoint. The remaining ** entries cache the RtreeNode for the first elements of the priority queue. */ #define RTREE_CACHE_SZ 5 /* ** An rtree cursor object. */ struct RtreeCursor { sqlite3_vtab_cursor base; /* Base class. Must be first */ u8 atEOF; /* True if at end of search */ u8 bPoint; /* True if sPoint is valid */ int iStrategy; /* Copy of idxNum search parameter */ int nConstraint; /* Number of entries in aConstraint */ RtreeConstraint *aConstraint; /* Search constraints. */ int nPointAlloc; /* Number of slots allocated for aPoint[] */ int nPoint; /* Number of slots used in aPoint[] */ int mxLevel; /* iLevel value for root of the tree */ RtreeSearchPoint *aPoint; /* Priority queue for search points */ RtreeSearchPoint sPoint; /* Cached next search point */ RtreeNode *aNode[RTREE_CACHE_SZ]; /* Rtree node cache */ u32 anQueue[RTREE_MAX_DEPTH+1]; /* Number of queued entries by iLevel */ }; /* Return the Rtree of a RtreeCursor */ #define RTREE_OF_CURSOR(X) ((Rtree*)((X)->base.pVtab)) /* ** A coordinate can be either a floating point number or a integer. All ** coordinates within a single R-Tree are always of the same time. */ union RtreeCoord { RtreeValue f; /* Floating point value */ int i; /* Integer value */ u32 u; /* Unsigned for byte-order conversions */ }; /* ** The argument is an RtreeCoord. Return the value stored within the RtreeCoord ** formatted as a RtreeDValue (double or int64). This macro assumes that local ** variable pRtree points to the Rtree structure associated with the ** RtreeCoord. */ #ifdef SQLITE_RTREE_INT_ONLY # define DCOORD(coord) ((RtreeDValue)coord.i) #else # define DCOORD(coord) ( \ (pRtree->eCoordType==RTREE_COORD_REAL32) ? \ ((double)coord.f) : \ ((double)coord.i) \ ) #endif /* ** A search constraint. */ struct RtreeConstraint { int iCoord; /* Index of constrained coordinate */ int op; /* Constraining operation */ union { RtreeDValue rValue; /* Constraint value. */ int (*xGeom)(sqlite3_rtree_geometry*,int,RtreeDValue*,int*); int (*xQueryFunc)(sqlite3_rtree_query_info*); } u; sqlite3_rtree_query_info *pInfo; /* xGeom and xQueryFunc argument */ }; /* Possible values for RtreeConstraint.op */ #define RTREE_EQ 0x41 /* A */ #define RTREE_LE 0x42 /* B */ #define RTREE_LT 0x43 /* C */ #define RTREE_GE 0x44 /* D */ #define RTREE_GT 0x45 /* E */ #define RTREE_MATCH 0x46 /* F: Old-style sqlite3_rtree_geometry_callback() */ #define RTREE_QUERY 0x47 /* G: New-style sqlite3_rtree_query_callback() */ /* ** An rtree structure node. */ struct RtreeNode { RtreeNode *pParent; /* Parent node */ i64 iNode; /* The node number */ int nRef; /* Number of references to this node */ int isDirty; /* True if the node needs to be written to disk */ u8 *zData; /* Content of the node, as should be on disk */ RtreeNode *pNext; /* Next node in this hash collision chain */ }; /* Return the number of cells in a node */ #define NCELL(pNode) readInt16(&(pNode)->zData[2]) /* ** A single cell from a node, deserialized */ struct RtreeCell { i64 iRowid; /* Node or entry ID */ RtreeCoord aCoord[RTREE_MAX_DIMENSIONS*2]; /* Bounding box coordinates */ }; /* ** This object becomes the sqlite3_user_data() for the SQL functions ** that are created by sqlite3_rtree_geometry_callback() and ** sqlite3_rtree_query_callback() and which appear on the right of MATCH ** operators in order to constrain a search. ** ** xGeom and xQueryFunc are the callback functions. Exactly one of ** xGeom and xQueryFunc fields is non-NULL, depending on whether the ** SQL function was created using sqlite3_rtree_geometry_callback() or ** sqlite3_rtree_query_callback(). ** ** This object is deleted automatically by the destructor mechanism in ** sqlite3_create_function_v2(). */ struct RtreeGeomCallback { int (*xGeom)(sqlite3_rtree_geometry*, int, RtreeDValue*, int*); int (*xQueryFunc)(sqlite3_rtree_query_info*); void (*xDestructor)(void*); void *pContext; }; /* ** Value for the first field of every RtreeMatchArg object. The MATCH ** operator tests that the first field of a blob operand matches this ** value to avoid operating on invalid blobs (which could cause a segfault). */ #define RTREE_GEOMETRY_MAGIC 0x891245AB /* ** An instance of this structure (in the form of a BLOB) is returned by ** the SQL functions that sqlite3_rtree_geometry_callback() and ** sqlite3_rtree_query_callback() create, and is read as the right-hand ** operand to the MATCH operator of an R-Tree. */ struct RtreeMatchArg { u32 magic; /* Always RTREE_GEOMETRY_MAGIC */ RtreeGeomCallback cb; /* Info about the callback functions */ int nParam; /* Number of parameters to the SQL function */ sqlite3_value **apSqlParam; /* Original SQL parameter values */ RtreeDValue aParam[1]; /* Values for parameters to the SQL function */ }; #ifndef MAX # define MAX(x,y) ((x) < (y) ? (y) : (x)) #endif #ifndef MIN # define MIN(x,y) ((x) > (y) ? (y) : (x)) #endif /* ** Functions to deserialize a 16 bit integer, 32 bit real number and ** 64 bit integer. The deserialized value is returned. */ static int readInt16(u8 *p){ return (p[0]<<8) + p[1]; } static void readCoord(u8 *p, RtreeCoord *pCoord){ pCoord->u = ( (((u32)p[0]) << 24) + (((u32)p[1]) << 16) + (((u32)p[2]) << 8) + (((u32)p[3]) << 0) ); } static i64 readInt64(u8 *p){ return ( (((i64)p[0]) << 56) + (((i64)p[1]) << 48) + (((i64)p[2]) << 40) + (((i64)p[3]) << 32) + (((i64)p[4]) << 24) + (((i64)p[5]) << 16) + (((i64)p[6]) << 8) + (((i64)p[7]) << 0) ); } /* ** Functions to serialize a 16 bit integer, 32 bit real number and ** 64 bit integer. The value returned is the number of bytes written ** to the argument buffer (always 2, 4 and 8 respectively). */ static int writeInt16(u8 *p, int i){ p[0] = (i>> 8)&0xFF; p[1] = (i>> 0)&0xFF; return 2; } static int writeCoord(u8 *p, RtreeCoord *pCoord){ u32 i; assert( sizeof(RtreeCoord)==4 ); assert( sizeof(u32)==4 ); i = pCoord->u; p[0] = (i>>24)&0xFF; p[1] = (i>>16)&0xFF; p[2] = (i>> 8)&0xFF; p[3] = (i>> 0)&0xFF; return 4; } static int writeInt64(u8 *p, i64 i){ p[0] = (i>>56)&0xFF; p[1] = (i>>48)&0xFF; p[2] = (i>>40)&0xFF; p[3] = (i>>32)&0xFF; p[4] = (i>>24)&0xFF; p[5] = (i>>16)&0xFF; p[6] = (i>> 8)&0xFF; p[7] = (i>> 0)&0xFF; return 8; } /* ** Increment the reference count of node p. */ static void nodeReference(RtreeNode *p){ if( p ){ p->nRef++; } } /* ** Clear the content of node p (set all bytes to 0x00). */ static void nodeZero(Rtree *pRtree, RtreeNode *p){ memset(&p->zData[2], 0, pRtree->iNodeSize-2); p->isDirty = 1; } /* ** Given a node number iNode, return the corresponding key to use ** in the Rtree.aHash table. */ static int nodeHash(i64 iNode){ return iNode % HASHSIZE; } /* ** Search the node hash table for node iNode. If found, return a pointer ** to it. Otherwise, return 0. */ static RtreeNode *nodeHashLookup(Rtree *pRtree, i64 iNode){ RtreeNode *p; for(p=pRtree->aHash[nodeHash(iNode)]; p && p->iNode!=iNode; p=p->pNext); return p; } /* ** Add node pNode to the node hash table. */ static void nodeHashInsert(Rtree *pRtree, RtreeNode *pNode){ int iHash; assert( pNode->pNext==0 ); iHash = nodeHash(pNode->iNode); pNode->pNext = pRtree->aHash[iHash]; pRtree->aHash[iHash] = pNode; } /* ** Remove node pNode from the node hash table. */ static void nodeHashDelete(Rtree *pRtree, RtreeNode *pNode){ RtreeNode **pp; if( pNode->iNode!=0 ){ pp = &pRtree->aHash[nodeHash(pNode->iNode)]; for( ; (*pp)!=pNode; pp = &(*pp)->pNext){ assert(*pp); } *pp = pNode->pNext; pNode->pNext = 0; } } /* ** Allocate and return new r-tree node. Initially, (RtreeNode.iNode==0), ** indicating that node has not yet been assigned a node number. It is ** assigned a node number when nodeWrite() is called to write the ** node contents out to the database. */ static RtreeNode *nodeNew(Rtree *pRtree, RtreeNode *pParent){ RtreeNode *pNode; pNode = (RtreeNode *)sqlite3_malloc(sizeof(RtreeNode) + pRtree->iNodeSize); if( pNode ){ memset(pNode, 0, sizeof(RtreeNode) + pRtree->iNodeSize); pNode->zData = (u8 *)&pNode[1]; pNode->nRef = 1; pNode->pParent = pParent; pNode->isDirty = 1; nodeReference(pParent); } return pNode; } /* ** Obtain a reference to an r-tree node. */ static int nodeAcquire( Rtree *pRtree, /* R-tree structure */ i64 iNode, /* Node number to load */ RtreeNode *pParent, /* Either the parent node or NULL */ RtreeNode **ppNode /* OUT: Acquired node */ ){ int rc; int rc2 = SQLITE_OK; RtreeNode *pNode; /* Check if the requested node is already in the hash table. If so, ** increase its reference count and return it. */ if( (pNode = nodeHashLookup(pRtree, iNode)) ){ assert( !pParent || !pNode->pParent || pNode->pParent==pParent ); if( pParent && !pNode->pParent ){ nodeReference(pParent); pNode->pParent = pParent; } pNode->nRef++; *ppNode = pNode; return SQLITE_OK; } sqlite3_bind_int64(pRtree->pReadNode, 1, iNode); rc = sqlite3_step(pRtree->pReadNode); if( rc==SQLITE_ROW ){ const u8 *zBlob = sqlite3_column_blob(pRtree->pReadNode, 0); if( pRtree->iNodeSize==sqlite3_column_bytes(pRtree->pReadNode, 0) ){ pNode = (RtreeNode *)sqlite3_malloc(sizeof(RtreeNode)+pRtree->iNodeSize); if( !pNode ){ rc2 = SQLITE_NOMEM; }else{ pNode->pParent = pParent; pNode->zData = (u8 *)&pNode[1]; pNode->nRef = 1; pNode->iNode = iNode; pNode->isDirty = 0; pNode->pNext = 0; memcpy(pNode->zData, zBlob, pRtree->iNodeSize); nodeReference(pParent); } } } rc = sqlite3_reset(pRtree->pReadNode); if( rc==SQLITE_OK ) rc = rc2; /* If the root node was just loaded, set pRtree->iDepth to the height ** of the r-tree structure. A height of zero means all data is stored on ** the root node. A height of one means the children of the root node ** are the leaves, and so on. If the depth as specified on the root node ** is greater than RTREE_MAX_DEPTH, the r-tree structure must be corrupt. */ if( pNode && iNode==1 ){ pRtree->iDepth = readInt16(pNode->zData); if( pRtree->iDepth>RTREE_MAX_DEPTH ){ rc = SQLITE_CORRUPT_VTAB; } } /* If no error has occurred so far, check if the "number of entries" ** field on the node is too large. If so, set the return code to ** SQLITE_CORRUPT_VTAB. */ if( pNode && rc==SQLITE_OK ){ if( NCELL(pNode)>((pRtree->iNodeSize-4)/pRtree->nBytesPerCell) ){ rc = SQLITE_CORRUPT_VTAB; } } if( rc==SQLITE_OK ){ if( pNode!=0 ){ nodeHashInsert(pRtree, pNode); }else{ rc = SQLITE_CORRUPT_VTAB; } *ppNode = pNode; }else{ sqlite3_free(pNode); *ppNode = 0; } return rc; } /* ** Overwrite cell iCell of node pNode with the contents of pCell. */ static void nodeOverwriteCell( Rtree *pRtree, /* The overall R-Tree */ RtreeNode *pNode, /* The node into which the cell is to be written */ RtreeCell *pCell, /* The cell to write */ int iCell /* Index into pNode into which pCell is written */ ){ int ii; u8 *p = &pNode->zData[4 + pRtree->nBytesPerCell*iCell]; p += writeInt64(p, pCell->iRowid); for(ii=0; ii<(pRtree->nDim*2); ii++){ p += writeCoord(p, &pCell->aCoord[ii]); } pNode->isDirty = 1; } /* ** Remove the cell with index iCell from node pNode. */ static void nodeDeleteCell(Rtree *pRtree, RtreeNode *pNode, int iCell){ u8 *pDst = &pNode->zData[4 + pRtree->nBytesPerCell*iCell]; u8 *pSrc = &pDst[pRtree->nBytesPerCell]; int nByte = (NCELL(pNode) - iCell - 1) * pRtree->nBytesPerCell; memmove(pDst, pSrc, nByte); writeInt16(&pNode->zData[2], NCELL(pNode)-1); pNode->isDirty = 1; } /* ** Insert the contents of cell pCell into node pNode. If the insert ** is successful, return SQLITE_OK. ** ** If there is not enough free space in pNode, return SQLITE_FULL. */ static int nodeInsertCell( Rtree *pRtree, /* The overall R-Tree */ RtreeNode *pNode, /* Write new cell into this node */ RtreeCell *pCell /* The cell to be inserted */ ){ int nCell; /* Current number of cells in pNode */ int nMaxCell; /* Maximum number of cells for pNode */ nMaxCell = (pRtree->iNodeSize-4)/pRtree->nBytesPerCell; nCell = NCELL(pNode); assert( nCell<=nMaxCell ); if( nCellzData[2], nCell+1); pNode->isDirty = 1; } return (nCell==nMaxCell); } /* ** If the node is dirty, write it out to the database. */ static int nodeWrite(Rtree *pRtree, RtreeNode *pNode){ int rc = SQLITE_OK; if( pNode->isDirty ){ sqlite3_stmt *p = pRtree->pWriteNode; if( pNode->iNode ){ sqlite3_bind_int64(p, 1, pNode->iNode); }else{ sqlite3_bind_null(p, 1); } sqlite3_bind_blob(p, 2, pNode->zData, pRtree->iNodeSize, SQLITE_STATIC); sqlite3_step(p); pNode->isDirty = 0; rc = sqlite3_reset(p); if( pNode->iNode==0 && rc==SQLITE_OK ){ pNode->iNode = sqlite3_last_insert_rowid(pRtree->db); nodeHashInsert(pRtree, pNode); } } return rc; } /* ** Release a reference to a node. If the node is dirty and the reference ** count drops to zero, the node data is written to the database. */ static int nodeRelease(Rtree *pRtree, RtreeNode *pNode){ int rc = SQLITE_OK; if( pNode ){ assert( pNode->nRef>0 ); pNode->nRef--; if( pNode->nRef==0 ){ if( pNode->iNode==1 ){ pRtree->iDepth = -1; } if( pNode->pParent ){ rc = nodeRelease(pRtree, pNode->pParent); } if( rc==SQLITE_OK ){ rc = nodeWrite(pRtree, pNode); } nodeHashDelete(pRtree, pNode); sqlite3_free(pNode); } } return rc; } /* ** Return the 64-bit integer value associated with cell iCell of ** node pNode. If pNode is a leaf node, this is a rowid. If it is ** an internal node, then the 64-bit integer is a child page number. */ static i64 nodeGetRowid( Rtree *pRtree, /* The overall R-Tree */ RtreeNode *pNode, /* The node from which to extract the ID */ int iCell /* The cell index from which to extract the ID */ ){ assert( iCellzData[4 + pRtree->nBytesPerCell*iCell]); } /* ** Return coordinate iCoord from cell iCell in node pNode. */ static void nodeGetCoord( Rtree *pRtree, /* The overall R-Tree */ RtreeNode *pNode, /* The node from which to extract a coordinate */ int iCell, /* The index of the cell within the node */ int iCoord, /* Which coordinate to extract */ RtreeCoord *pCoord /* OUT: Space to write result to */ ){ readCoord(&pNode->zData[12 + pRtree->nBytesPerCell*iCell + 4*iCoord], pCoord); } /* ** Deserialize cell iCell of node pNode. Populate the structure pointed ** to by pCell with the results. */ static void nodeGetCell( Rtree *pRtree, /* The overall R-Tree */ RtreeNode *pNode, /* The node containing the cell to be read */ int iCell, /* Index of the cell within the node */ RtreeCell *pCell /* OUT: Write the cell contents here */ ){ u8 *pData; RtreeCoord *pCoord; int ii; pCell->iRowid = nodeGetRowid(pRtree, pNode, iCell); pData = pNode->zData + (12 + pRtree->nBytesPerCell*iCell); pCoord = pCell->aCoord; for(ii=0; iinDim*2; ii++){ readCoord(&pData[ii*4], &pCoord[ii]); } } /* Forward declaration for the function that does the work of ** the virtual table module xCreate() and xConnect() methods. */ static int rtreeInit( sqlite3 *, void *, int, const char *const*, sqlite3_vtab **, char **, int ); /* ** Rtree virtual table module xCreate method. */ static int rtreeCreate( sqlite3 *db, void *pAux, int argc, const char *const*argv, sqlite3_vtab **ppVtab, char **pzErr ){ return rtreeInit(db, pAux, argc, argv, ppVtab, pzErr, 1); } /* ** Rtree virtual table module xConnect method. */ static int rtreeConnect( sqlite3 *db, void *pAux, int argc, const char *const*argv, sqlite3_vtab **ppVtab, char **pzErr ){ return rtreeInit(db, pAux, argc, argv, ppVtab, pzErr, 0); } /* ** Increment the r-tree reference count. */ static void rtreeReference(Rtree *pRtree){ pRtree->nBusy++; } /* ** Decrement the r-tree reference count. When the reference count reaches ** zero the structure is deleted. */ static void rtreeRelease(Rtree *pRtree){ pRtree->nBusy--; if( pRtree->nBusy==0 ){ sqlite3_finalize(pRtree->pReadNode); sqlite3_finalize(pRtree->pWriteNode); sqlite3_finalize(pRtree->pDeleteNode); sqlite3_finalize(pRtree->pReadRowid); sqlite3_finalize(pRtree->pWriteRowid); sqlite3_finalize(pRtree->pDeleteRowid); sqlite3_finalize(pRtree->pReadParent); sqlite3_finalize(pRtree->pWriteParent); sqlite3_finalize(pRtree->pDeleteParent); sqlite3_free(pRtree); } } /* ** Rtree virtual table module xDisconnect method. */ static int rtreeDisconnect(sqlite3_vtab *pVtab){ rtreeRelease((Rtree *)pVtab); return SQLITE_OK; } /* ** Rtree virtual table module xDestroy method. */ static int rtreeDestroy(sqlite3_vtab *pVtab){ Rtree *pRtree = (Rtree *)pVtab; int rc; char *zCreate = sqlite3_mprintf( "DROP TABLE '%q'.'%q_node';" "DROP TABLE '%q'.'%q_rowid';" "DROP TABLE '%q'.'%q_parent';", pRtree->zDb, pRtree->zName, pRtree->zDb, pRtree->zName, pRtree->zDb, pRtree->zName ); if( !zCreate ){ rc = SQLITE_NOMEM; }else{ rc = sqlite3_exec(pRtree->db, zCreate, 0, 0, 0); sqlite3_free(zCreate); } if( rc==SQLITE_OK ){ rtreeRelease(pRtree); } return rc; } /* ** Rtree virtual table module xOpen method. */ static int rtreeOpen(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor){ int rc = SQLITE_NOMEM; RtreeCursor *pCsr; pCsr = (RtreeCursor *)sqlite3_malloc(sizeof(RtreeCursor)); if( pCsr ){ memset(pCsr, 0, sizeof(RtreeCursor)); pCsr->base.pVtab = pVTab; rc = SQLITE_OK; } *ppCursor = (sqlite3_vtab_cursor *)pCsr; return rc; } /* ** Free the RtreeCursor.aConstraint[] array and its contents. */ static void freeCursorConstraints(RtreeCursor *pCsr){ if( pCsr->aConstraint ){ int i; /* Used to iterate through constraint array */ for(i=0; inConstraint; i++){ sqlite3_rtree_query_info *pInfo = pCsr->aConstraint[i].pInfo; if( pInfo ){ if( pInfo->xDelUser ) pInfo->xDelUser(pInfo->pUser); sqlite3_free(pInfo); } } sqlite3_free(pCsr->aConstraint); pCsr->aConstraint = 0; } } /* ** Rtree virtual table module xClose method. */ static int rtreeClose(sqlite3_vtab_cursor *cur){ Rtree *pRtree = (Rtree *)(cur->pVtab); int ii; RtreeCursor *pCsr = (RtreeCursor *)cur; freeCursorConstraints(pCsr); sqlite3_free(pCsr->aPoint); for(ii=0; iiaNode[ii]); sqlite3_free(pCsr); return SQLITE_OK; } /* ** Rtree virtual table module xEof method. ** ** Return non-zero if the cursor does not currently point to a valid ** record (i.e if the scan has finished), or zero otherwise. */ static int rtreeEof(sqlite3_vtab_cursor *cur){ RtreeCursor *pCsr = (RtreeCursor *)cur; return pCsr->atEOF; } /* ** Convert raw bits from the on-disk RTree record into a coordinate value. ** The on-disk format is big-endian and needs to be converted for little- ** endian platforms. The on-disk record stores integer coordinates if ** eInt is true and it stores 32-bit floating point records if eInt is ** false. a[] is the four bytes of the on-disk record to be decoded. ** Store the results in "r". ** ** There are three versions of this macro, one each for little-endian and ** big-endian processors and a third generic implementation. The endian- ** specific implementations are much faster and are preferred if the ** processor endianness is known at compile-time. The SQLITE_BYTEORDER ** macro is part of sqliteInt.h and hence the endian-specific ** implementation will only be used if this module is compiled as part ** of the amalgamation. */ #if defined(SQLITE_BYTEORDER) && SQLITE_BYTEORDER==1234 #define RTREE_DECODE_COORD(eInt, a, r) { \ RtreeCoord c; /* Coordinate decoded */ \ memcpy(&c.u,a,4); \ c.u = ((c.u>>24)&0xff)|((c.u>>8)&0xff00)| \ ((c.u&0xff)<<24)|((c.u&0xff00)<<8); \ r = eInt ? (sqlite3_rtree_dbl)c.i : (sqlite3_rtree_dbl)c.f; \ } #elif defined(SQLITE_BYTEORDER) && SQLITE_BYTEORDER==4321 #define RTREE_DECODE_COORD(eInt, a, r) { \ RtreeCoord c; /* Coordinate decoded */ \ memcpy(&c.u,a,4); \ r = eInt ? (sqlite3_rtree_dbl)c.i : (sqlite3_rtree_dbl)c.f; \ } #else #define RTREE_DECODE_COORD(eInt, a, r) { \ RtreeCoord c; /* Coordinate decoded */ \ c.u = ((u32)a[0]<<24) + ((u32)a[1]<<16) \ +((u32)a[2]<<8) + a[3]; \ r = eInt ? (sqlite3_rtree_dbl)c.i : (sqlite3_rtree_dbl)c.f; \ } #endif /* ** Check the RTree node or entry given by pCellData and p against the MATCH ** constraint pConstraint. */ static int rtreeCallbackConstraint( RtreeConstraint *pConstraint, /* The constraint to test */ int eInt, /* True if RTree holding integer coordinates */ u8 *pCellData, /* Raw cell content */ RtreeSearchPoint *pSearch, /* Container of this cell */ sqlite3_rtree_dbl *prScore, /* OUT: score for the cell */ int *peWithin /* OUT: visibility of the cell */ ){ int i; /* Loop counter */ sqlite3_rtree_query_info *pInfo = pConstraint->pInfo; /* Callback info */ int nCoord = pInfo->nCoord; /* No. of coordinates */ int rc; /* Callback return code */ sqlite3_rtree_dbl aCoord[RTREE_MAX_DIMENSIONS*2]; /* Decoded coordinates */ assert( pConstraint->op==RTREE_MATCH || pConstraint->op==RTREE_QUERY ); assert( nCoord==2 || nCoord==4 || nCoord==6 || nCoord==8 || nCoord==10 ); if( pConstraint->op==RTREE_QUERY && pSearch->iLevel==1 ){ pInfo->iRowid = readInt64(pCellData); } pCellData += 8; for(i=0; iop==RTREE_MATCH ){ rc = pConstraint->u.xGeom((sqlite3_rtree_geometry*)pInfo, nCoord, aCoord, &i); if( i==0 ) *peWithin = NOT_WITHIN; *prScore = RTREE_ZERO; }else{ pInfo->aCoord = aCoord; pInfo->iLevel = pSearch->iLevel - 1; pInfo->rScore = pInfo->rParentScore = pSearch->rScore; pInfo->eWithin = pInfo->eParentWithin = pSearch->eWithin; rc = pConstraint->u.xQueryFunc(pInfo); if( pInfo->eWithin<*peWithin ) *peWithin = pInfo->eWithin; if( pInfo->rScore<*prScore || *prScorerScore; } } return rc; } /* ** Check the internal RTree node given by pCellData against constraint p. ** If this constraint cannot be satisfied by any child within the node, ** set *peWithin to NOT_WITHIN. */ static void rtreeNonleafConstraint( RtreeConstraint *p, /* The constraint to test */ int eInt, /* True if RTree holds integer coordinates */ u8 *pCellData, /* Raw cell content as appears on disk */ int *peWithin /* Adjust downward, as appropriate */ ){ sqlite3_rtree_dbl val; /* Coordinate value convert to a double */ /* p->iCoord might point to either a lower or upper bound coordinate ** in a coordinate pair. But make pCellData point to the lower bound. */ pCellData += 8 + 4*(p->iCoord&0xfe); assert(p->op==RTREE_LE || p->op==RTREE_LT || p->op==RTREE_GE || p->op==RTREE_GT || p->op==RTREE_EQ ); switch( p->op ){ case RTREE_LE: case RTREE_LT: case RTREE_EQ: RTREE_DECODE_COORD(eInt, pCellData, val); /* val now holds the lower bound of the coordinate pair */ if( p->u.rValue>=val ) return; if( p->op!=RTREE_EQ ) break; /* RTREE_LE and RTREE_LT end here */ /* Fall through for the RTREE_EQ case */ default: /* RTREE_GT or RTREE_GE, or fallthrough of RTREE_EQ */ pCellData += 4; RTREE_DECODE_COORD(eInt, pCellData, val); /* val now holds the upper bound of the coordinate pair */ if( p->u.rValue<=val ) return; } *peWithin = NOT_WITHIN; } /* ** Check the leaf RTree cell given by pCellData against constraint p. ** If this constraint is not satisfied, set *peWithin to NOT_WITHIN. ** If the constraint is satisfied, leave *peWithin unchanged. ** ** The constraint is of the form: xN op $val ** ** The op is given by p->op. The xN is p->iCoord-th coordinate in ** pCellData. $val is given by p->u.rValue. */ static void rtreeLeafConstraint( RtreeConstraint *p, /* The constraint to test */ int eInt, /* True if RTree holds integer coordinates */ u8 *pCellData, /* Raw cell content as appears on disk */ int *peWithin /* Adjust downward, as appropriate */ ){ RtreeDValue xN; /* Coordinate value converted to a double */ assert(p->op==RTREE_LE || p->op==RTREE_LT || p->op==RTREE_GE || p->op==RTREE_GT || p->op==RTREE_EQ ); pCellData += 8 + p->iCoord*4; RTREE_DECODE_COORD(eInt, pCellData, xN); switch( p->op ){ case RTREE_LE: if( xN <= p->u.rValue ) return; break; case RTREE_LT: if( xN < p->u.rValue ) return; break; case RTREE_GE: if( xN >= p->u.rValue ) return; break; case RTREE_GT: if( xN > p->u.rValue ) return; break; default: if( xN == p->u.rValue ) return; break; } *peWithin = NOT_WITHIN; } /* ** One of the cells in node pNode is guaranteed to have a 64-bit ** integer value equal to iRowid. Return the index of this cell. */ static int nodeRowidIndex( Rtree *pRtree, RtreeNode *pNode, i64 iRowid, int *piIndex ){ int ii; int nCell = NCELL(pNode); assert( nCell<200 ); for(ii=0; iipParent; if( pParent ){ return nodeRowidIndex(pRtree, pParent, pNode->iNode, piIndex); } *piIndex = -1; return SQLITE_OK; } /* ** Compare two search points. Return negative, zero, or positive if the first ** is less than, equal to, or greater than the second. ** ** The rScore is the primary key. Smaller rScore values come first. ** If the rScore is a tie, then use iLevel as the tie breaker with smaller ** iLevel values coming first. In this way, if rScore is the same for all ** SearchPoints, then iLevel becomes the deciding factor and the result ** is a depth-first search, which is the desired default behavior. */ static int rtreeSearchPointCompare( const RtreeSearchPoint *pA, const RtreeSearchPoint *pB ){ if( pA->rScorerScore ) return -1; if( pA->rScore>pB->rScore ) return +1; if( pA->iLeveliLevel ) return -1; if( pA->iLevel>pB->iLevel ) return +1; return 0; } /* ** Interchange to search points in a cursor. */ static void rtreeSearchPointSwap(RtreeCursor *p, int i, int j){ RtreeSearchPoint t = p->aPoint[i]; assert( iaPoint[i] = p->aPoint[j]; p->aPoint[j] = t; i++; j++; if( i=RTREE_CACHE_SZ ){ nodeRelease(RTREE_OF_CURSOR(p), p->aNode[i]); p->aNode[i] = 0; }else{ RtreeNode *pTemp = p->aNode[i]; p->aNode[i] = p->aNode[j]; p->aNode[j] = pTemp; } } } /* ** Return the search point with the lowest current score. */ static RtreeSearchPoint *rtreeSearchPointFirst(RtreeCursor *pCur){ return pCur->bPoint ? &pCur->sPoint : pCur->nPoint ? pCur->aPoint : 0; } /* ** Get the RtreeNode for the search point with the lowest score. */ static RtreeNode *rtreeNodeOfFirstSearchPoint(RtreeCursor *pCur, int *pRC){ sqlite3_int64 id; int ii = 1 - pCur->bPoint; assert( ii==0 || ii==1 ); assert( pCur->bPoint || pCur->nPoint ); if( pCur->aNode[ii]==0 ){ assert( pRC!=0 ); id = ii ? pCur->aPoint[0].id : pCur->sPoint.id; *pRC = nodeAcquire(RTREE_OF_CURSOR(pCur), id, 0, &pCur->aNode[ii]); } return pCur->aNode[ii]; } /* ** Push a new element onto the priority queue */ static RtreeSearchPoint *rtreeEnqueue( RtreeCursor *pCur, /* The cursor */ RtreeDValue rScore, /* Score for the new search point */ u8 iLevel /* Level for the new search point */ ){ int i, j; RtreeSearchPoint *pNew; if( pCur->nPoint>=pCur->nPointAlloc ){ int nNew = pCur->nPointAlloc*2 + 8; pNew = sqlite3_realloc(pCur->aPoint, nNew*sizeof(pCur->aPoint[0])); if( pNew==0 ) return 0; pCur->aPoint = pNew; pCur->nPointAlloc = nNew; } i = pCur->nPoint++; pNew = pCur->aPoint + i; pNew->rScore = rScore; pNew->iLevel = iLevel; assert( iLevel<=RTREE_MAX_DEPTH ); while( i>0 ){ RtreeSearchPoint *pParent; j = (i-1)/2; pParent = pCur->aPoint + j; if( rtreeSearchPointCompare(pNew, pParent)>=0 ) break; rtreeSearchPointSwap(pCur, j, i); i = j; pNew = pParent; } return pNew; } /* ** Allocate a new RtreeSearchPoint and return a pointer to it. Return ** NULL if malloc fails. */ static RtreeSearchPoint *rtreeSearchPointNew( RtreeCursor *pCur, /* The cursor */ RtreeDValue rScore, /* Score for the new search point */ u8 iLevel /* Level for the new search point */ ){ RtreeSearchPoint *pNew, *pFirst; pFirst = rtreeSearchPointFirst(pCur); pCur->anQueue[iLevel]++; if( pFirst==0 || pFirst->rScore>rScore || (pFirst->rScore==rScore && pFirst->iLevel>iLevel) ){ if( pCur->bPoint ){ int ii; pNew = rtreeEnqueue(pCur, rScore, iLevel); if( pNew==0 ) return 0; ii = (int)(pNew - pCur->aPoint) + 1; if( iiaNode[ii]==0 ); pCur->aNode[ii] = pCur->aNode[0]; }else{ nodeRelease(RTREE_OF_CURSOR(pCur), pCur->aNode[0]); } pCur->aNode[0] = 0; *pNew = pCur->sPoint; } pCur->sPoint.rScore = rScore; pCur->sPoint.iLevel = iLevel; pCur->bPoint = 1; return &pCur->sPoint; }else{ return rtreeEnqueue(pCur, rScore, iLevel); } } #if 0 /* Tracing routines for the RtreeSearchPoint queue */ static void tracePoint(RtreeSearchPoint *p, int idx, RtreeCursor *pCur){ if( idx<0 ){ printf(" s"); }else{ printf("%2d", idx); } printf(" %d.%05lld.%02d %g %d", p->iLevel, p->id, p->iCell, p->rScore, p->eWithin ); idx++; if( idxaNode[idx]); }else{ printf("\n"); } } static void traceQueue(RtreeCursor *pCur, const char *zPrefix){ int ii; printf("=== %9s ", zPrefix); if( pCur->bPoint ){ tracePoint(&pCur->sPoint, -1, pCur); } for(ii=0; iinPoint; ii++){ if( ii>0 || pCur->bPoint ) printf(" "); tracePoint(&pCur->aPoint[ii], ii, pCur); } } # define RTREE_QUEUE_TRACE(A,B) traceQueue(A,B) #else # define RTREE_QUEUE_TRACE(A,B) /* no-op */ #endif /* Remove the search point with the lowest current score. */ static void rtreeSearchPointPop(RtreeCursor *p){ int i, j, k, n; i = 1 - p->bPoint; assert( i==0 || i==1 ); if( p->aNode[i] ){ nodeRelease(RTREE_OF_CURSOR(p), p->aNode[i]); p->aNode[i] = 0; } if( p->bPoint ){ p->anQueue[p->sPoint.iLevel]--; p->bPoint = 0; }else if( p->nPoint ){ p->anQueue[p->aPoint[0].iLevel]--; n = --p->nPoint; p->aPoint[0] = p->aPoint[n]; if( naNode[1] = p->aNode[n+1]; p->aNode[n+1] = 0; } i = 0; while( (j = i*2+1)aPoint[k], &p->aPoint[j])<0 ){ if( rtreeSearchPointCompare(&p->aPoint[k], &p->aPoint[i])<0 ){ rtreeSearchPointSwap(p, i, k); i = k; }else{ break; } }else{ if( rtreeSearchPointCompare(&p->aPoint[j], &p->aPoint[i])<0 ){ rtreeSearchPointSwap(p, i, j); i = j; }else{ break; } } } } } /* ** Continue the search on cursor pCur until the front of the queue ** contains an entry suitable for returning as a result-set row, ** or until the RtreeSearchPoint queue is empty, indicating that the ** query has completed. */ static int rtreeStepToLeaf(RtreeCursor *pCur){ RtreeSearchPoint *p; Rtree *pRtree = RTREE_OF_CURSOR(pCur); RtreeNode *pNode; int eWithin; int rc = SQLITE_OK; int nCell; int nConstraint = pCur->nConstraint; int ii; int eInt; RtreeSearchPoint x; eInt = pRtree->eCoordType==RTREE_COORD_INT32; while( (p = rtreeSearchPointFirst(pCur))!=0 && p->iLevel>0 ){ pNode = rtreeNodeOfFirstSearchPoint(pCur, &rc); if( rc ) return rc; nCell = NCELL(pNode); assert( nCell<200 ); while( p->iCellzData + (4+pRtree->nBytesPerCell*p->iCell); eWithin = FULLY_WITHIN; for(ii=0; iiaConstraint + ii; if( pConstraint->op>=RTREE_MATCH ){ rc = rtreeCallbackConstraint(pConstraint, eInt, pCellData, p, &rScore, &eWithin); if( rc ) return rc; }else if( p->iLevel==1 ){ rtreeLeafConstraint(pConstraint, eInt, pCellData, &eWithin); }else{ rtreeNonleafConstraint(pConstraint, eInt, pCellData, &eWithin); } if( eWithin==NOT_WITHIN ) break; } p->iCell++; if( eWithin==NOT_WITHIN ) continue; x.iLevel = p->iLevel - 1; if( x.iLevel ){ x.id = readInt64(pCellData); x.iCell = 0; }else{ x.id = p->id; x.iCell = p->iCell - 1; } if( p->iCell>=nCell ){ RTREE_QUEUE_TRACE(pCur, "POP-S:"); rtreeSearchPointPop(pCur); } if( rScoreeWithin = eWithin; p->id = x.id; p->iCell = x.iCell; RTREE_QUEUE_TRACE(pCur, "PUSH-S:"); break; } if( p->iCell>=nCell ){ RTREE_QUEUE_TRACE(pCur, "POP-Se:"); rtreeSearchPointPop(pCur); } } pCur->atEOF = p==0; return SQLITE_OK; } /* ** Rtree virtual table module xNext method. */ static int rtreeNext(sqlite3_vtab_cursor *pVtabCursor){ RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor; int rc = SQLITE_OK; /* Move to the next entry that matches the configured constraints. */ RTREE_QUEUE_TRACE(pCsr, "POP-Nx:"); rtreeSearchPointPop(pCsr); rc = rtreeStepToLeaf(pCsr); return rc; } /* ** Rtree virtual table module xRowid method. */ static int rtreeRowid(sqlite3_vtab_cursor *pVtabCursor, sqlite_int64 *pRowid){ RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor; RtreeSearchPoint *p = rtreeSearchPointFirst(pCsr); int rc = SQLITE_OK; RtreeNode *pNode = rtreeNodeOfFirstSearchPoint(pCsr, &rc); if( rc==SQLITE_OK && p ){ *pRowid = nodeGetRowid(RTREE_OF_CURSOR(pCsr), pNode, p->iCell); } return rc; } /* ** Rtree virtual table module xColumn method. */ static int rtreeColumn(sqlite3_vtab_cursor *cur, sqlite3_context *ctx, int i){ Rtree *pRtree = (Rtree *)cur->pVtab; RtreeCursor *pCsr = (RtreeCursor *)cur; RtreeSearchPoint *p = rtreeSearchPointFirst(pCsr); RtreeCoord c; int rc = SQLITE_OK; RtreeNode *pNode = rtreeNodeOfFirstSearchPoint(pCsr, &rc); if( rc ) return rc; if( p==0 ) return SQLITE_OK; if( i==0 ){ sqlite3_result_int64(ctx, nodeGetRowid(pRtree, pNode, p->iCell)); }else{ if( rc ) return rc; nodeGetCoord(pRtree, pNode, p->iCell, i-1, &c); #ifndef SQLITE_RTREE_INT_ONLY if( pRtree->eCoordType==RTREE_COORD_REAL32 ){ sqlite3_result_double(ctx, c.f); }else #endif { assert( pRtree->eCoordType==RTREE_COORD_INT32 ); sqlite3_result_int(ctx, c.i); } } return SQLITE_OK; } /* ** Use nodeAcquire() to obtain the leaf node containing the record with ** rowid iRowid. If successful, set *ppLeaf to point to the node and ** return SQLITE_OK. If there is no such record in the table, set ** *ppLeaf to 0 and return SQLITE_OK. If an error occurs, set *ppLeaf ** to zero and return an SQLite error code. */ static int findLeafNode( Rtree *pRtree, /* RTree to search */ i64 iRowid, /* The rowid searching for */ RtreeNode **ppLeaf, /* Write the node here */ sqlite3_int64 *piNode /* Write the node-id here */ ){ int rc; *ppLeaf = 0; sqlite3_bind_int64(pRtree->pReadRowid, 1, iRowid); if( sqlite3_step(pRtree->pReadRowid)==SQLITE_ROW ){ i64 iNode = sqlite3_column_int64(pRtree->pReadRowid, 0); if( piNode ) *piNode = iNode; rc = nodeAcquire(pRtree, iNode, 0, ppLeaf); sqlite3_reset(pRtree->pReadRowid); }else{ rc = sqlite3_reset(pRtree->pReadRowid); } return rc; } /* ** This function is called to configure the RtreeConstraint object passed ** as the second argument for a MATCH constraint. The value passed as the ** first argument to this function is the right-hand operand to the MATCH ** operator. */ static int deserializeGeometry(sqlite3_value *pValue, RtreeConstraint *pCons){ RtreeMatchArg *pBlob; /* BLOB returned by geometry function */ sqlite3_rtree_query_info *pInfo; /* Callback information */ int nBlob; /* Size of the geometry function blob */ int nExpected; /* Expected size of the BLOB */ /* Check that value is actually a blob. */ if( sqlite3_value_type(pValue)!=SQLITE_BLOB ) return SQLITE_ERROR; /* Check that the blob is roughly the right size. */ nBlob = sqlite3_value_bytes(pValue); if( nBlob<(int)sizeof(RtreeMatchArg) ){ return SQLITE_ERROR; } pInfo = (sqlite3_rtree_query_info*)sqlite3_malloc( sizeof(*pInfo)+nBlob ); if( !pInfo ) return SQLITE_NOMEM; memset(pInfo, 0, sizeof(*pInfo)); pBlob = (RtreeMatchArg*)&pInfo[1]; memcpy(pBlob, sqlite3_value_blob(pValue), nBlob); nExpected = (int)(sizeof(RtreeMatchArg) + pBlob->nParam*sizeof(sqlite3_value*) + (pBlob->nParam-1)*sizeof(RtreeDValue)); if( pBlob->magic!=RTREE_GEOMETRY_MAGIC || nBlob!=nExpected ){ sqlite3_free(pInfo); return SQLITE_ERROR; } pInfo->pContext = pBlob->cb.pContext; pInfo->nParam = pBlob->nParam; pInfo->aParam = pBlob->aParam; pInfo->apSqlParam = pBlob->apSqlParam; if( pBlob->cb.xGeom ){ pCons->u.xGeom = pBlob->cb.xGeom; }else{ pCons->op = RTREE_QUERY; pCons->u.xQueryFunc = pBlob->cb.xQueryFunc; } pCons->pInfo = pInfo; return SQLITE_OK; } /* ** Rtree virtual table module xFilter method. */ static int rtreeFilter( sqlite3_vtab_cursor *pVtabCursor, int idxNum, const char *idxStr, int argc, sqlite3_value **argv ){ Rtree *pRtree = (Rtree *)pVtabCursor->pVtab; RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor; RtreeNode *pRoot = 0; int ii; int rc = SQLITE_OK; int iCell = 0; rtreeReference(pRtree); /* Reset the cursor to the same state as rtreeOpen() leaves it in. */ freeCursorConstraints(pCsr); sqlite3_free(pCsr->aPoint); memset(pCsr, 0, sizeof(RtreeCursor)); pCsr->base.pVtab = (sqlite3_vtab*)pRtree; pCsr->iStrategy = idxNum; if( idxNum==1 ){ /* Special case - lookup by rowid. */ RtreeNode *pLeaf; /* Leaf on which the required cell resides */ RtreeSearchPoint *p; /* Search point for the leaf */ i64 iRowid = sqlite3_value_int64(argv[0]); i64 iNode = 0; rc = findLeafNode(pRtree, iRowid, &pLeaf, &iNode); if( rc==SQLITE_OK && pLeaf!=0 ){ p = rtreeSearchPointNew(pCsr, RTREE_ZERO, 0); assert( p!=0 ); /* Always returns pCsr->sPoint */ pCsr->aNode[0] = pLeaf; p->id = iNode; p->eWithin = PARTLY_WITHIN; rc = nodeRowidIndex(pRtree, pLeaf, iRowid, &iCell); p->iCell = iCell; RTREE_QUEUE_TRACE(pCsr, "PUSH-F1:"); }else{ pCsr->atEOF = 1; } }else{ /* Normal case - r-tree scan. Set up the RtreeCursor.aConstraint array ** with the configured constraints. */ rc = nodeAcquire(pRtree, 1, 0, &pRoot); if( rc==SQLITE_OK && argc>0 ){ pCsr->aConstraint = sqlite3_malloc(sizeof(RtreeConstraint)*argc); pCsr->nConstraint = argc; if( !pCsr->aConstraint ){ rc = SQLITE_NOMEM; }else{ memset(pCsr->aConstraint, 0, sizeof(RtreeConstraint)*argc); memset(pCsr->anQueue, 0, sizeof(u32)*(pRtree->iDepth + 1)); assert( (idxStr==0 && argc==0) || (idxStr && (int)strlen(idxStr)==argc*2) ); for(ii=0; iiaConstraint[ii]; p->op = idxStr[ii*2]; p->iCoord = idxStr[ii*2+1]-'0'; if( p->op>=RTREE_MATCH ){ /* A MATCH operator. The right-hand-side must be a blob that ** can be cast into an RtreeMatchArg object. One created using ** an sqlite3_rtree_geometry_callback() SQL user function. */ rc = deserializeGeometry(argv[ii], p); if( rc!=SQLITE_OK ){ break; } p->pInfo->nCoord = pRtree->nDim*2; p->pInfo->anQueue = pCsr->anQueue; p->pInfo->mxLevel = pRtree->iDepth + 1; }else{ #ifdef SQLITE_RTREE_INT_ONLY p->u.rValue = sqlite3_value_int64(argv[ii]); #else p->u.rValue = sqlite3_value_double(argv[ii]); #endif } } } } if( rc==SQLITE_OK ){ RtreeSearchPoint *pNew; pNew = rtreeSearchPointNew(pCsr, RTREE_ZERO, pRtree->iDepth+1); if( pNew==0 ) return SQLITE_NOMEM; pNew->id = 1; pNew->iCell = 0; pNew->eWithin = PARTLY_WITHIN; assert( pCsr->bPoint==1 ); pCsr->aNode[0] = pRoot; pRoot = 0; RTREE_QUEUE_TRACE(pCsr, "PUSH-Fm:"); rc = rtreeStepToLeaf(pCsr); } } nodeRelease(pRtree, pRoot); rtreeRelease(pRtree); return rc; } /* ** Set the pIdxInfo->estimatedRows variable to nRow. Unless this ** extension is currently being used by a version of SQLite too old to ** support estimatedRows. In that case this function is a no-op. */ static void setEstimatedRows(sqlite3_index_info *pIdxInfo, i64 nRow){ #if SQLITE_VERSION_NUMBER>=3008002 if( sqlite3_libversion_number()>=3008002 ){ pIdxInfo->estimatedRows = nRow; } #endif } /* ** Rtree virtual table module xBestIndex method. There are three ** table scan strategies to choose from (in order from most to ** least desirable): ** ** idxNum idxStr Strategy ** ------------------------------------------------ ** 1 Unused Direct lookup by rowid. ** 2 See below R-tree query or full-table scan. ** ------------------------------------------------ ** ** If strategy 1 is used, then idxStr is not meaningful. If strategy ** 2 is used, idxStr is formatted to contain 2 bytes for each ** constraint used. The first two bytes of idxStr correspond to ** the constraint in sqlite3_index_info.aConstraintUsage[] with ** (argvIndex==1) etc. ** ** The first of each pair of bytes in idxStr identifies the constraint ** operator as follows: ** ** Operator Byte Value ** ---------------------- ** = 0x41 ('A') ** <= 0x42 ('B') ** < 0x43 ('C') ** >= 0x44 ('D') ** > 0x45 ('E') ** MATCH 0x46 ('F') ** ---------------------- ** ** The second of each pair of bytes identifies the coordinate column ** to which the constraint applies. The leftmost coordinate column ** is 'a', the second from the left 'b' etc. */ static int rtreeBestIndex(sqlite3_vtab *tab, sqlite3_index_info *pIdxInfo){ Rtree *pRtree = (Rtree*)tab; int rc = SQLITE_OK; int ii; int bMatch = 0; /* True if there exists a MATCH constraint */ i64 nRow; /* Estimated rows returned by this scan */ int iIdx = 0; char zIdxStr[RTREE_MAX_DIMENSIONS*8+1]; memset(zIdxStr, 0, sizeof(zIdxStr)); /* Check if there exists a MATCH constraint - even an unusable one. If there ** is, do not consider the lookup-by-rowid plan as using such a plan would ** require the VDBE to evaluate the MATCH constraint, which is not currently ** possible. */ for(ii=0; iinConstraint; ii++){ if( pIdxInfo->aConstraint[ii].op==SQLITE_INDEX_CONSTRAINT_MATCH ){ bMatch = 1; } } assert( pIdxInfo->idxStr==0 ); for(ii=0; iinConstraint && iIdx<(int)(sizeof(zIdxStr)-1); ii++){ struct sqlite3_index_constraint *p = &pIdxInfo->aConstraint[ii]; if( bMatch==0 && p->usable && p->iColumn==0 && p->op==SQLITE_INDEX_CONSTRAINT_EQ ){ /* We have an equality constraint on the rowid. Use strategy 1. */ int jj; for(jj=0; jjaConstraintUsage[jj].argvIndex = 0; pIdxInfo->aConstraintUsage[jj].omit = 0; } pIdxInfo->idxNum = 1; pIdxInfo->aConstraintUsage[ii].argvIndex = 1; pIdxInfo->aConstraintUsage[jj].omit = 1; /* This strategy involves a two rowid lookups on an B-Tree structures ** and then a linear search of an R-Tree node. This should be ** considered almost as quick as a direct rowid lookup (for which ** sqlite uses an internal cost of 0.0). It is expected to return ** a single row. */ pIdxInfo->estimatedCost = 30.0; setEstimatedRows(pIdxInfo, 1); return SQLITE_OK; } if( p->usable && (p->iColumn>0 || p->op==SQLITE_INDEX_CONSTRAINT_MATCH) ){ u8 op; switch( p->op ){ case SQLITE_INDEX_CONSTRAINT_EQ: op = RTREE_EQ; break; case SQLITE_INDEX_CONSTRAINT_GT: op = RTREE_GT; break; case SQLITE_INDEX_CONSTRAINT_LE: op = RTREE_LE; break; case SQLITE_INDEX_CONSTRAINT_LT: op = RTREE_LT; break; case SQLITE_INDEX_CONSTRAINT_GE: op = RTREE_GE; break; default: assert( p->op==SQLITE_INDEX_CONSTRAINT_MATCH ); op = RTREE_MATCH; break; } zIdxStr[iIdx++] = op; zIdxStr[iIdx++] = p->iColumn - 1 + '0'; pIdxInfo->aConstraintUsage[ii].argvIndex = (iIdx/2); pIdxInfo->aConstraintUsage[ii].omit = 1; } } pIdxInfo->idxNum = 2; pIdxInfo->needToFreeIdxStr = 1; if( iIdx>0 && 0==(pIdxInfo->idxStr = sqlite3_mprintf("%s", zIdxStr)) ){ return SQLITE_NOMEM; } nRow = pRtree->nRowEst >> (iIdx/2); pIdxInfo->estimatedCost = (double)6.0 * (double)nRow; setEstimatedRows(pIdxInfo, nRow); return rc; } /* ** Return the N-dimensional volumn of the cell stored in *p. */ static RtreeDValue cellArea(Rtree *pRtree, RtreeCell *p){ RtreeDValue area = (RtreeDValue)1; int ii; for(ii=0; ii<(pRtree->nDim*2); ii+=2){ area = (area * (DCOORD(p->aCoord[ii+1]) - DCOORD(p->aCoord[ii]))); } return area; } /* ** Return the margin length of cell p. The margin length is the sum ** of the objects size in each dimension. */ static RtreeDValue cellMargin(Rtree *pRtree, RtreeCell *p){ RtreeDValue margin = (RtreeDValue)0; int ii; for(ii=0; ii<(pRtree->nDim*2); ii+=2){ margin += (DCOORD(p->aCoord[ii+1]) - DCOORD(p->aCoord[ii])); } return margin; } /* ** Store the union of cells p1 and p2 in p1. */ static void cellUnion(Rtree *pRtree, RtreeCell *p1, RtreeCell *p2){ int ii; if( pRtree->eCoordType==RTREE_COORD_REAL32 ){ for(ii=0; ii<(pRtree->nDim*2); ii+=2){ p1->aCoord[ii].f = MIN(p1->aCoord[ii].f, p2->aCoord[ii].f); p1->aCoord[ii+1].f = MAX(p1->aCoord[ii+1].f, p2->aCoord[ii+1].f); } }else{ for(ii=0; ii<(pRtree->nDim*2); ii+=2){ p1->aCoord[ii].i = MIN(p1->aCoord[ii].i, p2->aCoord[ii].i); p1->aCoord[ii+1].i = MAX(p1->aCoord[ii+1].i, p2->aCoord[ii+1].i); } } } /* ** Return true if the area covered by p2 is a subset of the area covered ** by p1. False otherwise. */ static int cellContains(Rtree *pRtree, RtreeCell *p1, RtreeCell *p2){ int ii; int isInt = (pRtree->eCoordType==RTREE_COORD_INT32); for(ii=0; ii<(pRtree->nDim*2); ii+=2){ RtreeCoord *a1 = &p1->aCoord[ii]; RtreeCoord *a2 = &p2->aCoord[ii]; if( (!isInt && (a2[0].fa1[1].f)) || ( isInt && (a2[0].ia1[1].i)) ){ return 0; } } return 1; } /* ** Return the amount cell p would grow by if it were unioned with pCell. */ static RtreeDValue cellGrowth(Rtree *pRtree, RtreeCell *p, RtreeCell *pCell){ RtreeDValue area; RtreeCell cell; memcpy(&cell, p, sizeof(RtreeCell)); area = cellArea(pRtree, &cell); cellUnion(pRtree, &cell, pCell); return (cellArea(pRtree, &cell)-area); } static RtreeDValue cellOverlap( Rtree *pRtree, RtreeCell *p, RtreeCell *aCell, int nCell ){ int ii; RtreeDValue overlap = RTREE_ZERO; for(ii=0; iinDim*2); jj+=2){ RtreeDValue x1, x2; x1 = MAX(DCOORD(p->aCoord[jj]), DCOORD(aCell[ii].aCoord[jj])); x2 = MIN(DCOORD(p->aCoord[jj+1]), DCOORD(aCell[ii].aCoord[jj+1])); if( x2iDepth-iHeight); ii++){ int iCell; sqlite3_int64 iBest = 0; RtreeDValue fMinGrowth = RTREE_ZERO; RtreeDValue fMinArea = RTREE_ZERO; int nCell = NCELL(pNode); RtreeCell cell; RtreeNode *pChild; RtreeCell *aCell = 0; /* Select the child node which will be enlarged the least if pCell ** is inserted into it. Resolve ties by choosing the entry with ** the smallest area. */ for(iCell=0; iCellpParent ){ RtreeNode *pParent = p->pParent; RtreeCell cell; int iCell; if( nodeParentIndex(pRtree, p, &iCell) ){ return SQLITE_CORRUPT_VTAB; } nodeGetCell(pRtree, pParent, iCell, &cell); if( !cellContains(pRtree, &cell, pCell) ){ cellUnion(pRtree, &cell, pCell); nodeOverwriteCell(pRtree, pParent, &cell, iCell); } p = pParent; } return SQLITE_OK; } /* ** Write mapping (iRowid->iNode) to the _rowid table. */ static int rowidWrite(Rtree *pRtree, sqlite3_int64 iRowid, sqlite3_int64 iNode){ sqlite3_bind_int64(pRtree->pWriteRowid, 1, iRowid); sqlite3_bind_int64(pRtree->pWriteRowid, 2, iNode); sqlite3_step(pRtree->pWriteRowid); return sqlite3_reset(pRtree->pWriteRowid); } /* ** Write mapping (iNode->iPar) to the _parent table. */ static int parentWrite(Rtree *pRtree, sqlite3_int64 iNode, sqlite3_int64 iPar){ sqlite3_bind_int64(pRtree->pWriteParent, 1, iNode); sqlite3_bind_int64(pRtree->pWriteParent, 2, iPar); sqlite3_step(pRtree->pWriteParent); return sqlite3_reset(pRtree->pWriteParent); } static int rtreeInsertCell(Rtree *, RtreeNode *, RtreeCell *, int); /* ** Arguments aIdx, aDistance and aSpare all point to arrays of size ** nIdx. The aIdx array contains the set of integers from 0 to ** (nIdx-1) in no particular order. This function sorts the values ** in aIdx according to the indexed values in aDistance. For ** example, assuming the inputs: ** ** aIdx = { 0, 1, 2, 3 } ** aDistance = { 5.0, 2.0, 7.0, 6.0 } ** ** this function sets the aIdx array to contain: ** ** aIdx = { 0, 1, 2, 3 } ** ** The aSpare array is used as temporary working space by the ** sorting algorithm. */ static void SortByDistance( int *aIdx, int nIdx, RtreeDValue *aDistance, int *aSpare ){ if( nIdx>1 ){ int iLeft = 0; int iRight = 0; int nLeft = nIdx/2; int nRight = nIdx-nLeft; int *aLeft = aIdx; int *aRight = &aIdx[nLeft]; SortByDistance(aLeft, nLeft, aDistance, aSpare); SortByDistance(aRight, nRight, aDistance, aSpare); memcpy(aSpare, aLeft, sizeof(int)*nLeft); aLeft = aSpare; while( iLeft1 ){ int iLeft = 0; int iRight = 0; int nLeft = nIdx/2; int nRight = nIdx-nLeft; int *aLeft = aIdx; int *aRight = &aIdx[nLeft]; SortByDimension(pRtree, aLeft, nLeft, iDim, aCell, aSpare); SortByDimension(pRtree, aRight, nRight, iDim, aCell, aSpare); memcpy(aSpare, aLeft, sizeof(int)*nLeft); aLeft = aSpare; while( iLeftnDim+1)*(sizeof(int*)+nCell*sizeof(int)); aaSorted = (int **)sqlite3_malloc(nByte); if( !aaSorted ){ return SQLITE_NOMEM; } aSpare = &((int *)&aaSorted[pRtree->nDim])[pRtree->nDim*nCell]; memset(aaSorted, 0, nByte); for(ii=0; iinDim; ii++){ int jj; aaSorted[ii] = &((int *)&aaSorted[pRtree->nDim])[ii*nCell]; for(jj=0; jjnDim; ii++){ RtreeDValue margin = RTREE_ZERO; RtreeDValue fBestOverlap = RTREE_ZERO; RtreeDValue fBestArea = RTREE_ZERO; int iBestLeft = 0; int nLeft; for( nLeft=RTREE_MINCELLS(pRtree); nLeft<=(nCell-RTREE_MINCELLS(pRtree)); nLeft++ ){ RtreeCell left; RtreeCell right; int kk; RtreeDValue overlap; RtreeDValue area; memcpy(&left, &aCell[aaSorted[ii][0]], sizeof(RtreeCell)); memcpy(&right, &aCell[aaSorted[ii][nCell-1]], sizeof(RtreeCell)); for(kk=1; kk<(nCell-1); kk++){ if( kk0 ){ RtreeNode *pChild = nodeHashLookup(pRtree, iRowid); if( pChild ){ nodeRelease(pRtree, pChild->pParent); nodeReference(pNode); pChild->pParent = pNode; } } return xSetMapping(pRtree, iRowid, pNode->iNode); } static int SplitNode( Rtree *pRtree, RtreeNode *pNode, RtreeCell *pCell, int iHeight ){ int i; int newCellIsRight = 0; int rc = SQLITE_OK; int nCell = NCELL(pNode); RtreeCell *aCell; int *aiUsed; RtreeNode *pLeft = 0; RtreeNode *pRight = 0; RtreeCell leftbbox; RtreeCell rightbbox; /* Allocate an array and populate it with a copy of pCell and ** all cells from node pLeft. Then zero the original node. */ aCell = sqlite3_malloc((sizeof(RtreeCell)+sizeof(int))*(nCell+1)); if( !aCell ){ rc = SQLITE_NOMEM; goto splitnode_out; } aiUsed = (int *)&aCell[nCell+1]; memset(aiUsed, 0, sizeof(int)*(nCell+1)); for(i=0; iiNode==1 ){ pRight = nodeNew(pRtree, pNode); pLeft = nodeNew(pRtree, pNode); pRtree->iDepth++; pNode->isDirty = 1; writeInt16(pNode->zData, pRtree->iDepth); }else{ pLeft = pNode; pRight = nodeNew(pRtree, pLeft->pParent); nodeReference(pLeft); } if( !pLeft || !pRight ){ rc = SQLITE_NOMEM; goto splitnode_out; } memset(pLeft->zData, 0, pRtree->iNodeSize); memset(pRight->zData, 0, pRtree->iNodeSize); rc = splitNodeStartree(pRtree, aCell, nCell, pLeft, pRight, &leftbbox, &rightbbox); if( rc!=SQLITE_OK ){ goto splitnode_out; } /* Ensure both child nodes have node numbers assigned to them by calling ** nodeWrite(). Node pRight always needs a node number, as it was created ** by nodeNew() above. But node pLeft sometimes already has a node number. ** In this case avoid the all to nodeWrite(). */ if( SQLITE_OK!=(rc = nodeWrite(pRtree, pRight)) || (0==pLeft->iNode && SQLITE_OK!=(rc = nodeWrite(pRtree, pLeft))) ){ goto splitnode_out; } rightbbox.iRowid = pRight->iNode; leftbbox.iRowid = pLeft->iNode; if( pNode->iNode==1 ){ rc = rtreeInsertCell(pRtree, pLeft->pParent, &leftbbox, iHeight+1); if( rc!=SQLITE_OK ){ goto splitnode_out; } }else{ RtreeNode *pParent = pLeft->pParent; int iCell; rc = nodeParentIndex(pRtree, pLeft, &iCell); if( rc==SQLITE_OK ){ nodeOverwriteCell(pRtree, pParent, &leftbbox, iCell); rc = AdjustTree(pRtree, pParent, &leftbbox); } if( rc!=SQLITE_OK ){ goto splitnode_out; } } if( (rc = rtreeInsertCell(pRtree, pRight->pParent, &rightbbox, iHeight+1)) ){ goto splitnode_out; } for(i=0; iiRowid ){ newCellIsRight = 1; } if( rc!=SQLITE_OK ){ goto splitnode_out; } } if( pNode->iNode==1 ){ for(i=0; iiRowid, pLeft, iHeight); } if( rc==SQLITE_OK ){ rc = nodeRelease(pRtree, pRight); pRight = 0; } if( rc==SQLITE_OK ){ rc = nodeRelease(pRtree, pLeft); pLeft = 0; } splitnode_out: nodeRelease(pRtree, pRight); nodeRelease(pRtree, pLeft); sqlite3_free(aCell); return rc; } /* ** If node pLeaf is not the root of the r-tree and its pParent pointer is ** still NULL, load all ancestor nodes of pLeaf into memory and populate ** the pLeaf->pParent chain all the way up to the root node. ** ** This operation is required when a row is deleted (or updated - an update ** is implemented as a delete followed by an insert). SQLite provides the ** rowid of the row to delete, which can be used to find the leaf on which ** the entry resides (argument pLeaf). Once the leaf is located, this ** function is called to determine its ancestry. */ static int fixLeafParent(Rtree *pRtree, RtreeNode *pLeaf){ int rc = SQLITE_OK; RtreeNode *pChild = pLeaf; while( rc==SQLITE_OK && pChild->iNode!=1 && pChild->pParent==0 ){ int rc2 = SQLITE_OK; /* sqlite3_reset() return code */ sqlite3_bind_int64(pRtree->pReadParent, 1, pChild->iNode); rc = sqlite3_step(pRtree->pReadParent); if( rc==SQLITE_ROW ){ RtreeNode *pTest; /* Used to test for reference loops */ i64 iNode; /* Node number of parent node */ /* Before setting pChild->pParent, test that we are not creating a ** loop of references (as we would if, say, pChild==pParent). We don't ** want to do this as it leads to a memory leak when trying to delete ** the referenced counted node structures. */ iNode = sqlite3_column_int64(pRtree->pReadParent, 0); for(pTest=pLeaf; pTest && pTest->iNode!=iNode; pTest=pTest->pParent); if( !pTest ){ rc2 = nodeAcquire(pRtree, iNode, 0, &pChild->pParent); } } rc = sqlite3_reset(pRtree->pReadParent); if( rc==SQLITE_OK ) rc = rc2; if( rc==SQLITE_OK && !pChild->pParent ) rc = SQLITE_CORRUPT_VTAB; pChild = pChild->pParent; } return rc; } static int deleteCell(Rtree *, RtreeNode *, int, int); static int removeNode(Rtree *pRtree, RtreeNode *pNode, int iHeight){ int rc; int rc2; RtreeNode *pParent = 0; int iCell; assert( pNode->nRef==1 ); /* Remove the entry in the parent cell. */ rc = nodeParentIndex(pRtree, pNode, &iCell); if( rc==SQLITE_OK ){ pParent = pNode->pParent; pNode->pParent = 0; rc = deleteCell(pRtree, pParent, iCell, iHeight+1); } rc2 = nodeRelease(pRtree, pParent); if( rc==SQLITE_OK ){ rc = rc2; } if( rc!=SQLITE_OK ){ return rc; } /* Remove the xxx_node entry. */ sqlite3_bind_int64(pRtree->pDeleteNode, 1, pNode->iNode); sqlite3_step(pRtree->pDeleteNode); if( SQLITE_OK!=(rc = sqlite3_reset(pRtree->pDeleteNode)) ){ return rc; } /* Remove the xxx_parent entry. */ sqlite3_bind_int64(pRtree->pDeleteParent, 1, pNode->iNode); sqlite3_step(pRtree->pDeleteParent); if( SQLITE_OK!=(rc = sqlite3_reset(pRtree->pDeleteParent)) ){ return rc; } /* Remove the node from the in-memory hash table and link it into ** the Rtree.pDeleted list. Its contents will be re-inserted later on. */ nodeHashDelete(pRtree, pNode); pNode->iNode = iHeight; pNode->pNext = pRtree->pDeleted; pNode->nRef++; pRtree->pDeleted = pNode; return SQLITE_OK; } static int fixBoundingBox(Rtree *pRtree, RtreeNode *pNode){ RtreeNode *pParent = pNode->pParent; int rc = SQLITE_OK; if( pParent ){ int ii; int nCell = NCELL(pNode); RtreeCell box; /* Bounding box for pNode */ nodeGetCell(pRtree, pNode, 0, &box); for(ii=1; iiiNode; rc = nodeParentIndex(pRtree, pNode, &ii); if( rc==SQLITE_OK ){ nodeOverwriteCell(pRtree, pParent, &box, ii); rc = fixBoundingBox(pRtree, pParent); } } return rc; } /* ** Delete the cell at index iCell of node pNode. After removing the ** cell, adjust the r-tree data structure if required. */ static int deleteCell(Rtree *pRtree, RtreeNode *pNode, int iCell, int iHeight){ RtreeNode *pParent; int rc; if( SQLITE_OK!=(rc = fixLeafParent(pRtree, pNode)) ){ return rc; } /* Remove the cell from the node. This call just moves bytes around ** the in-memory node image, so it cannot fail. */ nodeDeleteCell(pRtree, pNode, iCell); /* If the node is not the tree root and now has less than the minimum ** number of cells, remove it from the tree. Otherwise, update the ** cell in the parent node so that it tightly contains the updated ** node. */ pParent = pNode->pParent; assert( pParent || pNode->iNode==1 ); if( pParent ){ if( NCELL(pNode)nDim; iDim++){ aCenterCoord[iDim] += DCOORD(aCell[ii].aCoord[iDim*2]); aCenterCoord[iDim] += DCOORD(aCell[ii].aCoord[iDim*2+1]); } } for(iDim=0; iDimnDim; iDim++){ aCenterCoord[iDim] = (aCenterCoord[iDim]/(nCell*(RtreeDValue)2)); } for(ii=0; iinDim; iDim++){ RtreeDValue coord = (DCOORD(aCell[ii].aCoord[iDim*2+1]) - DCOORD(aCell[ii].aCoord[iDim*2])); aDistance[ii] += (coord-aCenterCoord[iDim])*(coord-aCenterCoord[iDim]); } } SortByDistance(aOrder, nCell, aDistance, aSpare); nodeZero(pRtree, pNode); for(ii=0; rc==SQLITE_OK && ii<(nCell-(RTREE_MINCELLS(pRtree)+1)); ii++){ RtreeCell *p = &aCell[aOrder[ii]]; nodeInsertCell(pRtree, pNode, p); if( p->iRowid==pCell->iRowid ){ if( iHeight==0 ){ rc = rowidWrite(pRtree, p->iRowid, pNode->iNode); }else{ rc = parentWrite(pRtree, p->iRowid, pNode->iNode); } } } if( rc==SQLITE_OK ){ rc = fixBoundingBox(pRtree, pNode); } for(; rc==SQLITE_OK && iiiNode currently contains ** the height of the sub-tree headed by the cell. */ RtreeNode *pInsert; RtreeCell *p = &aCell[aOrder[ii]]; rc = ChooseLeaf(pRtree, p, iHeight, &pInsert); if( rc==SQLITE_OK ){ int rc2; rc = rtreeInsertCell(pRtree, pInsert, p, iHeight); rc2 = nodeRelease(pRtree, pInsert); if( rc==SQLITE_OK ){ rc = rc2; } } } sqlite3_free(aCell); return rc; } /* ** Insert cell pCell into node pNode. Node pNode is the head of a ** subtree iHeight high (leaf nodes have iHeight==0). */ static int rtreeInsertCell( Rtree *pRtree, RtreeNode *pNode, RtreeCell *pCell, int iHeight ){ int rc = SQLITE_OK; if( iHeight>0 ){ RtreeNode *pChild = nodeHashLookup(pRtree, pCell->iRowid); if( pChild ){ nodeRelease(pRtree, pChild->pParent); nodeReference(pNode); pChild->pParent = pNode; } } if( nodeInsertCell(pRtree, pNode, pCell) ){ if( iHeight<=pRtree->iReinsertHeight || pNode->iNode==1){ rc = SplitNode(pRtree, pNode, pCell, iHeight); }else{ pRtree->iReinsertHeight = iHeight; rc = Reinsert(pRtree, pNode, pCell, iHeight); } }else{ rc = AdjustTree(pRtree, pNode, pCell); if( rc==SQLITE_OK ){ if( iHeight==0 ){ rc = rowidWrite(pRtree, pCell->iRowid, pNode->iNode); }else{ rc = parentWrite(pRtree, pCell->iRowid, pNode->iNode); } } } return rc; } static int reinsertNodeContent(Rtree *pRtree, RtreeNode *pNode){ int ii; int rc = SQLITE_OK; int nCell = NCELL(pNode); for(ii=0; rc==SQLITE_OK && iiiNode currently contains ** the height of the sub-tree headed by the cell. */ rc = ChooseLeaf(pRtree, &cell, (int)pNode->iNode, &pInsert); if( rc==SQLITE_OK ){ int rc2; rc = rtreeInsertCell(pRtree, pInsert, &cell, (int)pNode->iNode); rc2 = nodeRelease(pRtree, pInsert); if( rc==SQLITE_OK ){ rc = rc2; } } } return rc; } /* ** Select a currently unused rowid for a new r-tree record. */ static int newRowid(Rtree *pRtree, i64 *piRowid){ int rc; sqlite3_bind_null(pRtree->pWriteRowid, 1); sqlite3_bind_null(pRtree->pWriteRowid, 2); sqlite3_step(pRtree->pWriteRowid); rc = sqlite3_reset(pRtree->pWriteRowid); *piRowid = sqlite3_last_insert_rowid(pRtree->db); return rc; } /* ** Remove the entry with rowid=iDelete from the r-tree structure. */ static int rtreeDeleteRowid(Rtree *pRtree, sqlite3_int64 iDelete){ int rc; /* Return code */ RtreeNode *pLeaf = 0; /* Leaf node containing record iDelete */ int iCell; /* Index of iDelete cell in pLeaf */ RtreeNode *pRoot; /* Root node of rtree structure */ /* Obtain a reference to the root node to initialize Rtree.iDepth */ rc = nodeAcquire(pRtree, 1, 0, &pRoot); /* Obtain a reference to the leaf node that contains the entry ** about to be deleted. */ if( rc==SQLITE_OK ){ rc = findLeafNode(pRtree, iDelete, &pLeaf, 0); } /* Delete the cell in question from the leaf node. */ if( rc==SQLITE_OK ){ int rc2; rc = nodeRowidIndex(pRtree, pLeaf, iDelete, &iCell); if( rc==SQLITE_OK ){ rc = deleteCell(pRtree, pLeaf, iCell, 0); } rc2 = nodeRelease(pRtree, pLeaf); if( rc==SQLITE_OK ){ rc = rc2; } } /* Delete the corresponding entry in the _rowid table. */ if( rc==SQLITE_OK ){ sqlite3_bind_int64(pRtree->pDeleteRowid, 1, iDelete); sqlite3_step(pRtree->pDeleteRowid); rc = sqlite3_reset(pRtree->pDeleteRowid); } /* Check if the root node now has exactly one child. If so, remove ** it, schedule the contents of the child for reinsertion and ** reduce the tree height by one. ** ** This is equivalent to copying the contents of the child into ** the root node (the operation that Gutman's paper says to perform ** in this scenario). */ if( rc==SQLITE_OK && pRtree->iDepth>0 && NCELL(pRoot)==1 ){ int rc2; RtreeNode *pChild; i64 iChild = nodeGetRowid(pRtree, pRoot, 0); rc = nodeAcquire(pRtree, iChild, pRoot, &pChild); if( rc==SQLITE_OK ){ rc = removeNode(pRtree, pChild, pRtree->iDepth-1); } rc2 = nodeRelease(pRtree, pChild); if( rc==SQLITE_OK ) rc = rc2; if( rc==SQLITE_OK ){ pRtree->iDepth--; writeInt16(pRoot->zData, pRtree->iDepth); pRoot->isDirty = 1; } } /* Re-insert the contents of any underfull nodes removed from the tree. */ for(pLeaf=pRtree->pDeleted; pLeaf; pLeaf=pRtree->pDeleted){ if( rc==SQLITE_OK ){ rc = reinsertNodeContent(pRtree, pLeaf); } pRtree->pDeleted = pLeaf->pNext; sqlite3_free(pLeaf); } /* Release the reference to the root node. */ if( rc==SQLITE_OK ){ rc = nodeRelease(pRtree, pRoot); }else{ nodeRelease(pRtree, pRoot); } return rc; } /* ** Rounding constants for float->double conversion. */ #define RNDTOWARDS (1.0 - 1.0/8388608.0) /* Round towards zero */ #define RNDAWAY (1.0 + 1.0/8388608.0) /* Round away from zero */ #if !defined(SQLITE_RTREE_INT_ONLY) /* ** Convert an sqlite3_value into an RtreeValue (presumably a float) ** while taking care to round toward negative or positive, respectively. */ static RtreeValue rtreeValueDown(sqlite3_value *v){ double d = sqlite3_value_double(v); float f = (float)d; if( f>d ){ f = (float)(d*(d<0 ? RNDAWAY : RNDTOWARDS)); } return f; } static RtreeValue rtreeValueUp(sqlite3_value *v){ double d = sqlite3_value_double(v); float f = (float)d; if( fbase.zErrMsg) to an appropriate value and returns ** SQLITE_CONSTRAINT. ** ** Parameter iCol is the index of the leftmost column involved in the ** constraint failure. If it is 0, then the constraint that failed is ** the unique constraint on the id column. Otherwise, it is the rtree ** (c1<=c2) constraint on columns iCol and iCol+1 that has failed. ** ** If an OOM occurs, SQLITE_NOMEM is returned instead of SQLITE_CONSTRAINT. */ static int rtreeConstraintError(Rtree *pRtree, int iCol){ sqlite3_stmt *pStmt = 0; char *zSql; int rc; assert( iCol==0 || iCol%2 ); zSql = sqlite3_mprintf("SELECT * FROM %Q.%Q", pRtree->zDb, pRtree->zName); if( zSql ){ rc = sqlite3_prepare_v2(pRtree->db, zSql, -1, &pStmt, 0); }else{ rc = SQLITE_NOMEM; } sqlite3_free(zSql); if( rc==SQLITE_OK ){ if( iCol==0 ){ const char *zCol = sqlite3_column_name(pStmt, 0); pRtree->base.zErrMsg = sqlite3_mprintf( "UNIQUE constraint failed: %s.%s", pRtree->zName, zCol ); }else{ const char *zCol1 = sqlite3_column_name(pStmt, iCol); const char *zCol2 = sqlite3_column_name(pStmt, iCol+1); pRtree->base.zErrMsg = sqlite3_mprintf( "rtree constraint failed: %s.(%s<=%s)", pRtree->zName, zCol1, zCol2 ); } } sqlite3_finalize(pStmt); return (rc==SQLITE_OK ? SQLITE_CONSTRAINT : rc); } /* ** The xUpdate method for rtree module virtual tables. */ static int rtreeUpdate( sqlite3_vtab *pVtab, int nData, sqlite3_value **azData, sqlite_int64 *pRowid ){ Rtree *pRtree = (Rtree *)pVtab; int rc = SQLITE_OK; RtreeCell cell; /* New cell to insert if nData>1 */ int bHaveRowid = 0; /* Set to 1 after new rowid is determined */ rtreeReference(pRtree); assert(nData>=1); cell.iRowid = 0; /* Used only to suppress a compiler warning */ /* Constraint handling. A write operation on an r-tree table may return ** SQLITE_CONSTRAINT for two reasons: ** ** 1. A duplicate rowid value, or ** 2. The supplied data violates the "x2>=x1" constraint. ** ** In the first case, if the conflict-handling mode is REPLACE, then ** the conflicting row can be removed before proceeding. In the second ** case, SQLITE_CONSTRAINT must be returned regardless of the ** conflict-handling mode specified by the user. */ if( nData>1 ){ int ii; /* Populate the cell.aCoord[] array. The first coordinate is azData[3]. ** ** NB: nData can only be less than nDim*2+3 if the rtree is mis-declared ** with "column" that are interpreted as table constraints. ** Example: CREATE VIRTUAL TABLE bad USING rtree(x,y,CHECK(y>5)); ** This problem was discovered after years of use, so we silently ignore ** these kinds of misdeclared tables to avoid breaking any legacy. */ assert( nData<=(pRtree->nDim*2 + 3) ); #ifndef SQLITE_RTREE_INT_ONLY if( pRtree->eCoordType==RTREE_COORD_REAL32 ){ for(ii=0; iicell.aCoord[ii+1].f ){ rc = rtreeConstraintError(pRtree, ii+1); goto constraint; } } }else #endif { for(ii=0; iicell.aCoord[ii+1].i ){ rc = rtreeConstraintError(pRtree, ii+1); goto constraint; } } } /* If a rowid value was supplied, check if it is already present in ** the table. If so, the constraint has failed. */ if( sqlite3_value_type(azData[2])!=SQLITE_NULL ){ cell.iRowid = sqlite3_value_int64(azData[2]); if( sqlite3_value_type(azData[0])==SQLITE_NULL || sqlite3_value_int64(azData[0])!=cell.iRowid ){ int steprc; sqlite3_bind_int64(pRtree->pReadRowid, 1, cell.iRowid); steprc = sqlite3_step(pRtree->pReadRowid); rc = sqlite3_reset(pRtree->pReadRowid); if( SQLITE_ROW==steprc ){ if( sqlite3_vtab_on_conflict(pRtree->db)==SQLITE_REPLACE ){ rc = rtreeDeleteRowid(pRtree, cell.iRowid); }else{ rc = rtreeConstraintError(pRtree, 0); goto constraint; } } } bHaveRowid = 1; } } /* If azData[0] is not an SQL NULL value, it is the rowid of a ** record to delete from the r-tree table. The following block does ** just that. */ if( sqlite3_value_type(azData[0])!=SQLITE_NULL ){ rc = rtreeDeleteRowid(pRtree, sqlite3_value_int64(azData[0])); } /* If the azData[] array contains more than one element, elements ** (azData[2]..azData[argc-1]) contain a new record to insert into ** the r-tree structure. */ if( rc==SQLITE_OK && nData>1 ){ /* Insert the new record into the r-tree */ RtreeNode *pLeaf = 0; /* Figure out the rowid of the new row. */ if( bHaveRowid==0 ){ rc = newRowid(pRtree, &cell.iRowid); } *pRowid = cell.iRowid; if( rc==SQLITE_OK ){ rc = ChooseLeaf(pRtree, &cell, 0, &pLeaf); } if( rc==SQLITE_OK ){ int rc2; pRtree->iReinsertHeight = -1; rc = rtreeInsertCell(pRtree, pLeaf, &cell, 0); rc2 = nodeRelease(pRtree, pLeaf); if( rc==SQLITE_OK ){ rc = rc2; } } } constraint: rtreeRelease(pRtree); return rc; } /* ** The xRename method for rtree module virtual tables. */ static int rtreeRename(sqlite3_vtab *pVtab, const char *zNewName){ Rtree *pRtree = (Rtree *)pVtab; int rc = SQLITE_NOMEM; char *zSql = sqlite3_mprintf( "ALTER TABLE %Q.'%q_node' RENAME TO \"%w_node\";" "ALTER TABLE %Q.'%q_parent' RENAME TO \"%w_parent\";" "ALTER TABLE %Q.'%q_rowid' RENAME TO \"%w_rowid\";" , pRtree->zDb, pRtree->zName, zNewName , pRtree->zDb, pRtree->zName, zNewName , pRtree->zDb, pRtree->zName, zNewName ); if( zSql ){ rc = sqlite3_exec(pRtree->db, zSql, 0, 0, 0); sqlite3_free(zSql); } return rc; } /* ** This function populates the pRtree->nRowEst variable with an estimate ** of the number of rows in the virtual table. If possible, this is based ** on sqlite_stat1 data. Otherwise, use RTREE_DEFAULT_ROWEST. */ static int rtreeQueryStat1(sqlite3 *db, Rtree *pRtree){ const char *zFmt = "SELECT stat FROM %Q.sqlite_stat1 WHERE tbl = '%q_rowid'"; char *zSql; sqlite3_stmt *p; int rc; i64 nRow = 0; rc = sqlite3_table_column_metadata( db, pRtree->zDb, "sqlite_stat1",0,0,0,0,0,0 ); if( rc!=SQLITE_OK ){ pRtree->nRowEst = RTREE_DEFAULT_ROWEST; return rc==SQLITE_ERROR ? SQLITE_OK : rc; } zSql = sqlite3_mprintf(zFmt, pRtree->zDb, pRtree->zName); if( zSql==0 ){ rc = SQLITE_NOMEM; }else{ rc = sqlite3_prepare_v2(db, zSql, -1, &p, 0); if( rc==SQLITE_OK ){ if( sqlite3_step(p)==SQLITE_ROW ) nRow = sqlite3_column_int64(p, 0); rc = sqlite3_finalize(p); }else if( rc!=SQLITE_NOMEM ){ rc = SQLITE_OK; } if( rc==SQLITE_OK ){ if( nRow==0 ){ pRtree->nRowEst = RTREE_DEFAULT_ROWEST; }else{ pRtree->nRowEst = MAX(nRow, RTREE_MIN_ROWEST); } } sqlite3_free(zSql); } return rc; } static sqlite3_module rtreeModule = { 0, /* iVersion */ rtreeCreate, /* xCreate - create a table */ rtreeConnect, /* xConnect - connect to an existing table */ rtreeBestIndex, /* xBestIndex - Determine search strategy */ rtreeDisconnect, /* xDisconnect - Disconnect from a table */ rtreeDestroy, /* xDestroy - Drop a table */ rtreeOpen, /* xOpen - open a cursor */ rtreeClose, /* xClose - close a cursor */ rtreeFilter, /* xFilter - configure scan constraints */ rtreeNext, /* xNext - advance a cursor */ rtreeEof, /* xEof */ rtreeColumn, /* xColumn - read data */ rtreeRowid, /* xRowid - read data */ rtreeUpdate, /* xUpdate - write data */ 0, /* xBegin - begin transaction */ 0, /* xSync - sync transaction */ 0, /* xCommit - commit transaction */ 0, /* xRollback - rollback transaction */ 0, /* xFindFunction - function overloading */ rtreeRename, /* xRename - rename the table */ 0, /* xSavepoint */ 0, /* xRelease */ 0 /* xRollbackTo */ }; static int rtreeSqlInit( Rtree *pRtree, sqlite3 *db, const char *zDb, const char *zPrefix, int isCreate ){ int rc = SQLITE_OK; #define N_STATEMENT 9 static const char *azSql[N_STATEMENT] = { /* Read and write the xxx_node table */ "SELECT data FROM '%q'.'%q_node' WHERE nodeno = :1", "INSERT OR REPLACE INTO '%q'.'%q_node' VALUES(:1, :2)", "DELETE FROM '%q'.'%q_node' WHERE nodeno = :1", /* Read and write the xxx_rowid table */ "SELECT nodeno FROM '%q'.'%q_rowid' WHERE rowid = :1", "INSERT OR REPLACE INTO '%q'.'%q_rowid' VALUES(:1, :2)", "DELETE FROM '%q'.'%q_rowid' WHERE rowid = :1", /* Read and write the xxx_parent table */ "SELECT parentnode FROM '%q'.'%q_parent' WHERE nodeno = :1", "INSERT OR REPLACE INTO '%q'.'%q_parent' VALUES(:1, :2)", "DELETE FROM '%q'.'%q_parent' WHERE nodeno = :1" }; sqlite3_stmt **appStmt[N_STATEMENT]; int i; pRtree->db = db; if( isCreate ){ char *zCreate = sqlite3_mprintf( "CREATE TABLE \"%w\".\"%w_node\"(nodeno INTEGER PRIMARY KEY, data BLOB);" "CREATE TABLE \"%w\".\"%w_rowid\"(rowid INTEGER PRIMARY KEY, nodeno INTEGER);" "CREATE TABLE \"%w\".\"%w_parent\"(nodeno INTEGER PRIMARY KEY," " parentnode INTEGER);" "INSERT INTO '%q'.'%q_node' VALUES(1, zeroblob(%d))", zDb, zPrefix, zDb, zPrefix, zDb, zPrefix, zDb, zPrefix, pRtree->iNodeSize ); if( !zCreate ){ return SQLITE_NOMEM; } rc = sqlite3_exec(db, zCreate, 0, 0, 0); sqlite3_free(zCreate); if( rc!=SQLITE_OK ){ return rc; } } appStmt[0] = &pRtree->pReadNode; appStmt[1] = &pRtree->pWriteNode; appStmt[2] = &pRtree->pDeleteNode; appStmt[3] = &pRtree->pReadRowid; appStmt[4] = &pRtree->pWriteRowid; appStmt[5] = &pRtree->pDeleteRowid; appStmt[6] = &pRtree->pReadParent; appStmt[7] = &pRtree->pWriteParent; appStmt[8] = &pRtree->pDeleteParent; rc = rtreeQueryStat1(db, pRtree); for(i=0; iiNodeSize is populated and SQLITE_OK returned. ** Otherwise, an SQLite error code is returned. ** ** If this function is being called as part of an xConnect(), then the rtree ** table already exists. In this case the node-size is determined by inspecting ** the root node of the tree. ** ** Otherwise, for an xCreate(), use 64 bytes less than the database page-size. ** This ensures that each node is stored on a single database page. If the ** database page-size is so large that more than RTREE_MAXCELLS entries ** would fit in a single node, use a smaller node-size. */ static int getNodeSize( sqlite3 *db, /* Database handle */ Rtree *pRtree, /* Rtree handle */ int isCreate, /* True for xCreate, false for xConnect */ char **pzErr /* OUT: Error message, if any */ ){ int rc; char *zSql; if( isCreate ){ int iPageSize = 0; zSql = sqlite3_mprintf("PRAGMA %Q.page_size", pRtree->zDb); rc = getIntFromStmt(db, zSql, &iPageSize); if( rc==SQLITE_OK ){ pRtree->iNodeSize = iPageSize-64; if( (4+pRtree->nBytesPerCell*RTREE_MAXCELLS)iNodeSize ){ pRtree->iNodeSize = 4+pRtree->nBytesPerCell*RTREE_MAXCELLS; } }else{ *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db)); } }else{ zSql = sqlite3_mprintf( "SELECT length(data) FROM '%q'.'%q_node' WHERE nodeno = 1", pRtree->zDb, pRtree->zName ); rc = getIntFromStmt(db, zSql, &pRtree->iNodeSize); if( rc!=SQLITE_OK ){ *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db)); } } sqlite3_free(zSql); return rc; } /* ** This function is the implementation of both the xConnect and xCreate ** methods of the r-tree virtual table. ** ** argv[0] -> module name ** argv[1] -> database name ** argv[2] -> table name ** argv[...] -> column names... */ static int rtreeInit( sqlite3 *db, /* Database connection */ void *pAux, /* One of the RTREE_COORD_* constants */ int argc, const char *const*argv, /* Parameters to CREATE TABLE statement */ sqlite3_vtab **ppVtab, /* OUT: New virtual table */ char **pzErr, /* OUT: Error message, if any */ int isCreate /* True for xCreate, false for xConnect */ ){ int rc = SQLITE_OK; Rtree *pRtree; int nDb; /* Length of string argv[1] */ int nName; /* Length of string argv[2] */ int eCoordType = (pAux ? RTREE_COORD_INT32 : RTREE_COORD_REAL32); const char *aErrMsg[] = { 0, /* 0 */ "Wrong number of columns for an rtree table", /* 1 */ "Too few columns for an rtree table", /* 2 */ "Too many columns for an rtree table" /* 3 */ }; int iErr = (argc<6) ? 2 : argc>(RTREE_MAX_DIMENSIONS*2+4) ? 3 : argc%2; if( aErrMsg[iErr] ){ *pzErr = sqlite3_mprintf("%s", aErrMsg[iErr]); return SQLITE_ERROR; } sqlite3_vtab_config(db, SQLITE_VTAB_CONSTRAINT_SUPPORT, 1); /* Allocate the sqlite3_vtab structure */ nDb = (int)strlen(argv[1]); nName = (int)strlen(argv[2]); pRtree = (Rtree *)sqlite3_malloc(sizeof(Rtree)+nDb+nName+2); if( !pRtree ){ return SQLITE_NOMEM; } memset(pRtree, 0, sizeof(Rtree)+nDb+nName+2); pRtree->nBusy = 1; pRtree->base.pModule = &rtreeModule; pRtree->zDb = (char *)&pRtree[1]; pRtree->zName = &pRtree->zDb[nDb+1]; pRtree->nDim = (argc-4)/2; pRtree->nBytesPerCell = 8 + pRtree->nDim*4*2; pRtree->eCoordType = eCoordType; memcpy(pRtree->zDb, argv[1], nDb); memcpy(pRtree->zName, argv[2], nName); /* Figure out the node size to use. */ rc = getNodeSize(db, pRtree, isCreate, pzErr); /* Create/Connect to the underlying relational database schema. If ** that is successful, call sqlite3_declare_vtab() to configure ** the r-tree table schema. */ if( rc==SQLITE_OK ){ if( (rc = rtreeSqlInit(pRtree, db, argv[1], argv[2], isCreate)) ){ *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db)); }else{ char *zSql = sqlite3_mprintf("CREATE TABLE x(%s", argv[3]); char *zTmp; int ii; for(ii=4; zSql && iinBusy==1 ); rtreeRelease(pRtree); } return rc; } /* ** Implementation of a scalar function that decodes r-tree nodes to ** human readable strings. This can be used for debugging and analysis. ** ** The scalar function takes two arguments: (1) the number of dimensions ** to the rtree (between 1 and 5, inclusive) and (2) a blob of data containing ** an r-tree node. For a two-dimensional r-tree structure called "rt", to ** deserialize all nodes, a statement like: ** ** SELECT rtreenode(2, data) FROM rt_node; ** ** The human readable string takes the form of a Tcl list with one ** entry for each cell in the r-tree node. Each entry is itself a ** list, containing the 8-byte rowid/pageno followed by the ** *2 coordinates. */ static void rtreenode(sqlite3_context *ctx, int nArg, sqlite3_value **apArg){ char *zText = 0; RtreeNode node; Rtree tree; int ii; UNUSED_PARAMETER(nArg); memset(&node, 0, sizeof(RtreeNode)); memset(&tree, 0, sizeof(Rtree)); tree.nDim = sqlite3_value_int(apArg[0]); tree.nBytesPerCell = 8 + 8 * tree.nDim; node.zData = (u8 *)sqlite3_value_blob(apArg[1]); for(ii=0; iixDestructor ) pInfo->xDestructor(pInfo->pContext); sqlite3_free(p); } /* ** This routine frees the BLOB that is returned by geomCallback(). */ static void rtreeMatchArgFree(void *pArg){ int i; RtreeMatchArg *p = (RtreeMatchArg*)pArg; for(i=0; inParam; i++){ sqlite3_value_free(p->apSqlParam[i]); } sqlite3_free(p); } /* ** Each call to sqlite3_rtree_geometry_callback() or ** sqlite3_rtree_query_callback() creates an ordinary SQLite ** scalar function that is implemented by this routine. ** ** All this function does is construct an RtreeMatchArg object that ** contains the geometry-checking callback routines and a list of ** parameters to this function, then return that RtreeMatchArg object ** as a BLOB. ** ** The R-Tree MATCH operator will read the returned BLOB, deserialize ** the RtreeMatchArg object, and use the RtreeMatchArg object to figure ** out which elements of the R-Tree should be returned by the query. */ static void geomCallback(sqlite3_context *ctx, int nArg, sqlite3_value **aArg){ RtreeGeomCallback *pGeomCtx = (RtreeGeomCallback *)sqlite3_user_data(ctx); RtreeMatchArg *pBlob; int nBlob; int memErr = 0; nBlob = sizeof(RtreeMatchArg) + (nArg-1)*sizeof(RtreeDValue) + nArg*sizeof(sqlite3_value*); pBlob = (RtreeMatchArg *)sqlite3_malloc(nBlob); if( !pBlob ){ sqlite3_result_error_nomem(ctx); }else{ int i; pBlob->magic = RTREE_GEOMETRY_MAGIC; pBlob->cb = pGeomCtx[0]; pBlob->apSqlParam = (sqlite3_value**)&pBlob->aParam[nArg]; pBlob->nParam = nArg; for(i=0; iapSqlParam[i] = sqlite3_value_dup(aArg[i]); if( pBlob->apSqlParam[i]==0 ) memErr = 1; #ifdef SQLITE_RTREE_INT_ONLY pBlob->aParam[i] = sqlite3_value_int64(aArg[i]); #else pBlob->aParam[i] = sqlite3_value_double(aArg[i]); #endif } if( memErr ){ sqlite3_result_error_nomem(ctx); rtreeMatchArgFree(pBlob); }else{ sqlite3_result_blob(ctx, pBlob, nBlob, rtreeMatchArgFree); } } } /* ** Register a new geometry function for use with the r-tree MATCH operator. */ SQLITE_API int sqlite3_rtree_geometry_callback( sqlite3 *db, /* Register SQL function on this connection */ const char *zGeom, /* Name of the new SQL function */ int (*xGeom)(sqlite3_rtree_geometry*,int,RtreeDValue*,int*), /* Callback */ void *pContext /* Extra data associated with the callback */ ){ RtreeGeomCallback *pGeomCtx; /* Context object for new user-function */ /* Allocate and populate the context object. */ pGeomCtx = (RtreeGeomCallback *)sqlite3_malloc(sizeof(RtreeGeomCallback)); if( !pGeomCtx ) return SQLITE_NOMEM; pGeomCtx->xGeom = xGeom; pGeomCtx->xQueryFunc = 0; pGeomCtx->xDestructor = 0; pGeomCtx->pContext = pContext; return sqlite3_create_function_v2(db, zGeom, -1, SQLITE_ANY, (void *)pGeomCtx, geomCallback, 0, 0, rtreeFreeCallback ); } /* ** Register a new 2nd-generation geometry function for use with the ** r-tree MATCH operator. */ SQLITE_API int sqlite3_rtree_query_callback( sqlite3 *db, /* Register SQL function on this connection */ const char *zQueryFunc, /* Name of new SQL function */ int (*xQueryFunc)(sqlite3_rtree_query_info*), /* Callback */ void *pContext, /* Extra data passed into the callback */ void (*xDestructor)(void*) /* Destructor for the extra data */ ){ RtreeGeomCallback *pGeomCtx; /* Context object for new user-function */ /* Allocate and populate the context object. */ pGeomCtx = (RtreeGeomCallback *)sqlite3_malloc(sizeof(RtreeGeomCallback)); if( !pGeomCtx ) return SQLITE_NOMEM; pGeomCtx->xGeom = 0; pGeomCtx->xQueryFunc = xQueryFunc; pGeomCtx->xDestructor = xDestructor; pGeomCtx->pContext = pContext; return sqlite3_create_function_v2(db, zQueryFunc, -1, SQLITE_ANY, (void *)pGeomCtx, geomCallback, 0, 0, rtreeFreeCallback ); } #if !SQLITE_CORE #ifdef _WIN32 __declspec(dllexport) #endif SQLITE_API int sqlite3_rtree_init( sqlite3 *db, char **pzErrMsg, const sqlite3_api_routines *pApi ){ SQLITE_EXTENSION_INIT2(pApi) return sqlite3RtreeInit(db); } #endif #endif /************** End of rtree.c ***********************************************/ /************** Begin file icu.c *********************************************/ /* ** 2007 May 6 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ************************************************************************* ** $Id: icu.c,v 1.7 2007/12/13 21:54:11 drh Exp $ ** ** This file implements an integration between the ICU library ** ("International Components for Unicode", an open-source library ** for handling unicode data) and SQLite. The integration uses ** ICU to provide the following to SQLite: ** ** * An implementation of the SQL regexp() function (and hence REGEXP ** operator) using the ICU uregex_XX() APIs. ** ** * Implementations of the SQL scalar upper() and lower() functions ** for case mapping. ** ** * Integration of ICU and SQLite collation sequences. ** ** * An implementation of the LIKE operator that uses ICU to ** provide case-independent matching. */ #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_ICU) /* Include ICU headers */ #include #include #include #include /* #include */ #ifndef SQLITE_CORE /* #include "sqlite3ext.h" */ SQLITE_EXTENSION_INIT1 #else /* #include "sqlite3.h" */ #endif /* ** Maximum length (in bytes) of the pattern in a LIKE or GLOB ** operator. */ #ifndef SQLITE_MAX_LIKE_PATTERN_LENGTH # define SQLITE_MAX_LIKE_PATTERN_LENGTH 50000 #endif /* ** Version of sqlite3_free() that is always a function, never a macro. */ static void xFree(void *p){ sqlite3_free(p); } /* ** This lookup table is used to help decode the first byte of ** a multi-byte UTF8 character. It is copied here from SQLite source ** code file utf8.c. */ static const unsigned char icuUtf8Trans1[] = { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x00, 0x01, 0x02, 0x03, 0x00, 0x01, 0x00, 0x00, }; #define SQLITE_ICU_READ_UTF8(zIn, c) \ c = *(zIn++); \ if( c>=0xc0 ){ \ c = icuUtf8Trans1[c-0xc0]; \ while( (*zIn & 0xc0)==0x80 ){ \ c = (c<<6) + (0x3f & *(zIn++)); \ } \ } #define SQLITE_ICU_SKIP_UTF8(zIn) \ assert( *zIn ); \ if( *(zIn++)>=0xc0 ){ \ while( (*zIn & 0xc0)==0x80 ){zIn++;} \ } /* ** Compare two UTF-8 strings for equality where the first string is ** a "LIKE" expression. Return true (1) if they are the same and ** false (0) if they are different. */ static int icuLikeCompare( const uint8_t *zPattern, /* LIKE pattern */ const uint8_t *zString, /* The UTF-8 string to compare against */ const UChar32 uEsc /* The escape character */ ){ static const int MATCH_ONE = (UChar32)'_'; static const int MATCH_ALL = (UChar32)'%'; int prevEscape = 0; /* True if the previous character was uEsc */ while( 1 ){ /* Read (and consume) the next character from the input pattern. */ UChar32 uPattern; SQLITE_ICU_READ_UTF8(zPattern, uPattern); if( uPattern==0 ) break; /* There are now 4 possibilities: ** ** 1. uPattern is an unescaped match-all character "%", ** 2. uPattern is an unescaped match-one character "_", ** 3. uPattern is an unescaped escape character, or ** 4. uPattern is to be handled as an ordinary character */ if( !prevEscape && uPattern==MATCH_ALL ){ /* Case 1. */ uint8_t c; /* Skip any MATCH_ALL or MATCH_ONE characters that follow a ** MATCH_ALL. For each MATCH_ONE, skip one character in the ** test string. */ while( (c=*zPattern) == MATCH_ALL || c == MATCH_ONE ){ if( c==MATCH_ONE ){ if( *zString==0 ) return 0; SQLITE_ICU_SKIP_UTF8(zString); } zPattern++; } if( *zPattern==0 ) return 1; while( *zString ){ if( icuLikeCompare(zPattern, zString, uEsc) ){ return 1; } SQLITE_ICU_SKIP_UTF8(zString); } return 0; }else if( !prevEscape && uPattern==MATCH_ONE ){ /* Case 2. */ if( *zString==0 ) return 0; SQLITE_ICU_SKIP_UTF8(zString); }else if( !prevEscape && uPattern==uEsc){ /* Case 3. */ prevEscape = 1; }else{ /* Case 4. */ UChar32 uString; SQLITE_ICU_READ_UTF8(zString, uString); uString = u_foldCase(uString, U_FOLD_CASE_DEFAULT); uPattern = u_foldCase(uPattern, U_FOLD_CASE_DEFAULT); if( uString!=uPattern ){ return 0; } prevEscape = 0; } } return *zString==0; } /* ** Implementation of the like() SQL function. This function implements ** the build-in LIKE operator. The first argument to the function is the ** pattern and the second argument is the string. So, the SQL statements: ** ** A LIKE B ** ** is implemented as like(B, A). If there is an escape character E, ** ** A LIKE B ESCAPE E ** ** is mapped to like(B, A, E). */ static void icuLikeFunc( sqlite3_context *context, int argc, sqlite3_value **argv ){ const unsigned char *zA = sqlite3_value_text(argv[0]); const unsigned char *zB = sqlite3_value_text(argv[1]); UChar32 uEsc = 0; /* Limit the length of the LIKE or GLOB pattern to avoid problems ** of deep recursion and N*N behavior in patternCompare(). */ if( sqlite3_value_bytes(argv[0])>SQLITE_MAX_LIKE_PATTERN_LENGTH ){ sqlite3_result_error(context, "LIKE or GLOB pattern too complex", -1); return; } if( argc==3 ){ /* The escape character string must consist of a single UTF-8 character. ** Otherwise, return an error. */ int nE= sqlite3_value_bytes(argv[2]); const unsigned char *zE = sqlite3_value_text(argv[2]); int i = 0; if( zE==0 ) return; U8_NEXT(zE, i, nE, uEsc); if( i!=nE){ sqlite3_result_error(context, "ESCAPE expression must be a single character", -1); return; } } if( zA && zB ){ sqlite3_result_int(context, icuLikeCompare(zA, zB, uEsc)); } } /* ** This function is called when an ICU function called from within ** the implementation of an SQL scalar function returns an error. ** ** The scalar function context passed as the first argument is ** loaded with an error message based on the following two args. */ static void icuFunctionError( sqlite3_context *pCtx, /* SQLite scalar function context */ const char *zName, /* Name of ICU function that failed */ UErrorCode e /* Error code returned by ICU function */ ){ char zBuf[128]; sqlite3_snprintf(128, zBuf, "ICU error: %s(): %s", zName, u_errorName(e)); zBuf[127] = '\0'; sqlite3_result_error(pCtx, zBuf, -1); } /* ** Function to delete compiled regexp objects. Registered as ** a destructor function with sqlite3_set_auxdata(). */ static void icuRegexpDelete(void *p){ URegularExpression *pExpr = (URegularExpression *)p; uregex_close(pExpr); } /* ** Implementation of SQLite REGEXP operator. This scalar function takes ** two arguments. The first is a regular expression pattern to compile ** the second is a string to match against that pattern. If either ** argument is an SQL NULL, then NULL Is returned. Otherwise, the result ** is 1 if the string matches the pattern, or 0 otherwise. ** ** SQLite maps the regexp() function to the regexp() operator such ** that the following two are equivalent: ** ** zString REGEXP zPattern ** regexp(zPattern, zString) ** ** Uses the following ICU regexp APIs: ** ** uregex_open() ** uregex_matches() ** uregex_close() */ static void icuRegexpFunc(sqlite3_context *p, int nArg, sqlite3_value **apArg){ UErrorCode status = U_ZERO_ERROR; URegularExpression *pExpr; UBool res; const UChar *zString = sqlite3_value_text16(apArg[1]); (void)nArg; /* Unused parameter */ /* If the left hand side of the regexp operator is NULL, ** then the result is also NULL. */ if( !zString ){ return; } pExpr = sqlite3_get_auxdata(p, 0); if( !pExpr ){ const UChar *zPattern = sqlite3_value_text16(apArg[0]); if( !zPattern ){ return; } pExpr = uregex_open(zPattern, -1, 0, 0, &status); if( U_SUCCESS(status) ){ sqlite3_set_auxdata(p, 0, pExpr, icuRegexpDelete); }else{ assert(!pExpr); icuFunctionError(p, "uregex_open", status); return; } } /* Configure the text that the regular expression operates on. */ uregex_setText(pExpr, zString, -1, &status); if( !U_SUCCESS(status) ){ icuFunctionError(p, "uregex_setText", status); return; } /* Attempt the match */ res = uregex_matches(pExpr, 0, &status); if( !U_SUCCESS(status) ){ icuFunctionError(p, "uregex_matches", status); return; } /* Set the text that the regular expression operates on to a NULL ** pointer. This is not really necessary, but it is tidier than ** leaving the regular expression object configured with an invalid ** pointer after this function returns. */ uregex_setText(pExpr, 0, 0, &status); /* Return 1 or 0. */ sqlite3_result_int(p, res ? 1 : 0); } /* ** Implementations of scalar functions for case mapping - upper() and ** lower(). Function upper() converts its input to upper-case (ABC). ** Function lower() converts to lower-case (abc). ** ** ICU provides two types of case mapping, "general" case mapping and ** "language specific". Refer to ICU documentation for the differences ** between the two. ** ** To utilise "general" case mapping, the upper() or lower() scalar ** functions are invoked with one argument: ** ** upper('ABC') -> 'abc' ** lower('abc') -> 'ABC' ** ** To access ICU "language specific" case mapping, upper() or lower() ** should be invoked with two arguments. The second argument is the name ** of the locale to use. Passing an empty string ("") or SQL NULL value ** as the second argument is the same as invoking the 1 argument version ** of upper() or lower(). ** ** lower('I', 'en_us') -> 'i' ** lower('I', 'tr_tr') -> '\u131' (small dotless i) ** ** http://www.icu-project.org/userguide/posix.html#case_mappings */ static void icuCaseFunc16(sqlite3_context *p, int nArg, sqlite3_value **apArg){ const UChar *zInput; /* Pointer to input string */ UChar *zOutput = 0; /* Pointer to output buffer */ int nInput; /* Size of utf-16 input string in bytes */ int nOut; /* Size of output buffer in bytes */ int cnt; int bToUpper; /* True for toupper(), false for tolower() */ UErrorCode status; const char *zLocale = 0; assert(nArg==1 || nArg==2); bToUpper = (sqlite3_user_data(p)!=0); if( nArg==2 ){ zLocale = (const char *)sqlite3_value_text(apArg[1]); } zInput = sqlite3_value_text16(apArg[0]); if( !zInput ){ return; } nOut = nInput = sqlite3_value_bytes16(apArg[0]); if( nOut==0 ){ sqlite3_result_text16(p, "", 0, SQLITE_STATIC); return; } for(cnt=0; cnt<2; cnt++){ UChar *zNew = sqlite3_realloc(zOutput, nOut); if( zNew==0 ){ sqlite3_free(zOutput); sqlite3_result_error_nomem(p); return; } zOutput = zNew; status = U_ZERO_ERROR; if( bToUpper ){ nOut = 2*u_strToUpper(zOutput,nOut/2,zInput,nInput/2,zLocale,&status); }else{ nOut = 2*u_strToLower(zOutput,nOut/2,zInput,nInput/2,zLocale,&status); } if( U_SUCCESS(status) ){ sqlite3_result_text16(p, zOutput, nOut, xFree); }else if( status==U_BUFFER_OVERFLOW_ERROR ){ assert( cnt==0 ); continue; }else{ icuFunctionError(p, bToUpper ? "u_strToUpper" : "u_strToLower", status); } return; } assert( 0 ); /* Unreachable */ } /* ** Collation sequence destructor function. The pCtx argument points to ** a UCollator structure previously allocated using ucol_open(). */ static void icuCollationDel(void *pCtx){ UCollator *p = (UCollator *)pCtx; ucol_close(p); } /* ** Collation sequence comparison function. The pCtx argument points to ** a UCollator structure previously allocated using ucol_open(). */ static int icuCollationColl( void *pCtx, int nLeft, const void *zLeft, int nRight, const void *zRight ){ UCollationResult res; UCollator *p = (UCollator *)pCtx; res = ucol_strcoll(p, (UChar *)zLeft, nLeft/2, (UChar *)zRight, nRight/2); switch( res ){ case UCOL_LESS: return -1; case UCOL_GREATER: return +1; case UCOL_EQUAL: return 0; } assert(!"Unexpected return value from ucol_strcoll()"); return 0; } /* ** Implementation of the scalar function icu_load_collation(). ** ** This scalar function is used to add ICU collation based collation ** types to an SQLite database connection. It is intended to be called ** as follows: ** ** SELECT icu_load_collation(, ); ** ** Where is a string containing an ICU locale identifier (i.e. ** "en_AU", "tr_TR" etc.) and is the name of the ** collation sequence to create. */ static void icuLoadCollation( sqlite3_context *p, int nArg, sqlite3_value **apArg ){ sqlite3 *db = (sqlite3 *)sqlite3_user_data(p); UErrorCode status = U_ZERO_ERROR; const char *zLocale; /* Locale identifier - (eg. "jp_JP") */ const char *zName; /* SQL Collation sequence name (eg. "japanese") */ UCollator *pUCollator; /* ICU library collation object */ int rc; /* Return code from sqlite3_create_collation_x() */ assert(nArg==2); (void)nArg; /* Unused parameter */ zLocale = (const char *)sqlite3_value_text(apArg[0]); zName = (const char *)sqlite3_value_text(apArg[1]); if( !zLocale || !zName ){ return; } pUCollator = ucol_open(zLocale, &status); if( !U_SUCCESS(status) ){ icuFunctionError(p, "ucol_open", status); return; } assert(p); rc = sqlite3_create_collation_v2(db, zName, SQLITE_UTF16, (void *)pUCollator, icuCollationColl, icuCollationDel ); if( rc!=SQLITE_OK ){ ucol_close(pUCollator); sqlite3_result_error(p, "Error registering collation function", -1); } } /* ** Register the ICU extension functions with database db. */ SQLITE_PRIVATE int sqlite3IcuInit(sqlite3 *db){ struct IcuScalar { const char *zName; /* Function name */ int nArg; /* Number of arguments */ int enc; /* Optimal text encoding */ void *pContext; /* sqlite3_user_data() context */ void (*xFunc)(sqlite3_context*,int,sqlite3_value**); } scalars[] = { {"regexp", 2, SQLITE_ANY, 0, icuRegexpFunc}, {"lower", 1, SQLITE_UTF16, 0, icuCaseFunc16}, {"lower", 2, SQLITE_UTF16, 0, icuCaseFunc16}, {"upper", 1, SQLITE_UTF16, (void*)1, icuCaseFunc16}, {"upper", 2, SQLITE_UTF16, (void*)1, icuCaseFunc16}, {"lower", 1, SQLITE_UTF8, 0, icuCaseFunc16}, {"lower", 2, SQLITE_UTF8, 0, icuCaseFunc16}, {"upper", 1, SQLITE_UTF8, (void*)1, icuCaseFunc16}, {"upper", 2, SQLITE_UTF8, (void*)1, icuCaseFunc16}, {"like", 2, SQLITE_UTF8, 0, icuLikeFunc}, {"like", 3, SQLITE_UTF8, 0, icuLikeFunc}, {"icu_load_collation", 2, SQLITE_UTF8, (void*)db, icuLoadCollation}, }; int rc = SQLITE_OK; int i; for(i=0; rc==SQLITE_OK && i<(int)(sizeof(scalars)/sizeof(scalars[0])); i++){ struct IcuScalar *p = &scalars[i]; rc = sqlite3_create_function( db, p->zName, p->nArg, p->enc, p->pContext, p->xFunc, 0, 0 ); } return rc; } #if !SQLITE_CORE #ifdef _WIN32 __declspec(dllexport) #endif SQLITE_API int sqlite3_icu_init( sqlite3 *db, char **pzErrMsg, const sqlite3_api_routines *pApi ){ SQLITE_EXTENSION_INIT2(pApi) return sqlite3IcuInit(db); } #endif #endif /************** End of icu.c *************************************************/ /************** Begin file fts3_icu.c ****************************************/ /* ** 2007 June 22 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ************************************************************************* ** This file implements a tokenizer for fts3 based on the ICU library. */ /* #include "fts3Int.h" */ #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) #ifdef SQLITE_ENABLE_ICU /* #include */ /* #include */ /* #include "fts3_tokenizer.h" */ #include /* #include */ /* #include */ #include typedef struct IcuTokenizer IcuTokenizer; typedef struct IcuCursor IcuCursor; struct IcuTokenizer { sqlite3_tokenizer base; char *zLocale; }; struct IcuCursor { sqlite3_tokenizer_cursor base; UBreakIterator *pIter; /* ICU break-iterator object */ int nChar; /* Number of UChar elements in pInput */ UChar *aChar; /* Copy of input using utf-16 encoding */ int *aOffset; /* Offsets of each character in utf-8 input */ int nBuffer; char *zBuffer; int iToken; }; /* ** Create a new tokenizer instance. */ static int icuCreate( int argc, /* Number of entries in argv[] */ const char * const *argv, /* Tokenizer creation arguments */ sqlite3_tokenizer **ppTokenizer /* OUT: Created tokenizer */ ){ IcuTokenizer *p; int n = 0; if( argc>0 ){ n = strlen(argv[0])+1; } p = (IcuTokenizer *)sqlite3_malloc(sizeof(IcuTokenizer)+n); if( !p ){ return SQLITE_NOMEM; } memset(p, 0, sizeof(IcuTokenizer)); if( n ){ p->zLocale = (char *)&p[1]; memcpy(p->zLocale, argv[0], n); } *ppTokenizer = (sqlite3_tokenizer *)p; return SQLITE_OK; } /* ** Destroy a tokenizer */ static int icuDestroy(sqlite3_tokenizer *pTokenizer){ IcuTokenizer *p = (IcuTokenizer *)pTokenizer; sqlite3_free(p); return SQLITE_OK; } /* ** Prepare to begin tokenizing a particular string. The input ** string to be tokenized is pInput[0..nBytes-1]. A cursor ** used to incrementally tokenize this string is returned in ** *ppCursor. */ static int icuOpen( sqlite3_tokenizer *pTokenizer, /* The tokenizer */ const char *zInput, /* Input string */ int nInput, /* Length of zInput in bytes */ sqlite3_tokenizer_cursor **ppCursor /* OUT: Tokenization cursor */ ){ IcuTokenizer *p = (IcuTokenizer *)pTokenizer; IcuCursor *pCsr; const int32_t opt = U_FOLD_CASE_DEFAULT; UErrorCode status = U_ZERO_ERROR; int nChar; UChar32 c; int iInput = 0; int iOut = 0; *ppCursor = 0; if( zInput==0 ){ nInput = 0; zInput = ""; }else if( nInput<0 ){ nInput = strlen(zInput); } nChar = nInput+1; pCsr = (IcuCursor *)sqlite3_malloc( sizeof(IcuCursor) + /* IcuCursor */ ((nChar+3)&~3) * sizeof(UChar) + /* IcuCursor.aChar[] */ (nChar+1) * sizeof(int) /* IcuCursor.aOffset[] */ ); if( !pCsr ){ return SQLITE_NOMEM; } memset(pCsr, 0, sizeof(IcuCursor)); pCsr->aChar = (UChar *)&pCsr[1]; pCsr->aOffset = (int *)&pCsr->aChar[(nChar+3)&~3]; pCsr->aOffset[iOut] = iInput; U8_NEXT(zInput, iInput, nInput, c); while( c>0 ){ int isError = 0; c = u_foldCase(c, opt); U16_APPEND(pCsr->aChar, iOut, nChar, c, isError); if( isError ){ sqlite3_free(pCsr); return SQLITE_ERROR; } pCsr->aOffset[iOut] = iInput; if( iInputpIter = ubrk_open(UBRK_WORD, p->zLocale, pCsr->aChar, iOut, &status); if( !U_SUCCESS(status) ){ sqlite3_free(pCsr); return SQLITE_ERROR; } pCsr->nChar = iOut; ubrk_first(pCsr->pIter); *ppCursor = (sqlite3_tokenizer_cursor *)pCsr; return SQLITE_OK; } /* ** Close a tokenization cursor previously opened by a call to icuOpen(). */ static int icuClose(sqlite3_tokenizer_cursor *pCursor){ IcuCursor *pCsr = (IcuCursor *)pCursor; ubrk_close(pCsr->pIter); sqlite3_free(pCsr->zBuffer); sqlite3_free(pCsr); return SQLITE_OK; } /* ** Extract the next token from a tokenization cursor. */ static int icuNext( sqlite3_tokenizer_cursor *pCursor, /* Cursor returned by simpleOpen */ const char **ppToken, /* OUT: *ppToken is the token text */ int *pnBytes, /* OUT: Number of bytes in token */ int *piStartOffset, /* OUT: Starting offset of token */ int *piEndOffset, /* OUT: Ending offset of token */ int *piPosition /* OUT: Position integer of token */ ){ IcuCursor *pCsr = (IcuCursor *)pCursor; int iStart = 0; int iEnd = 0; int nByte = 0; while( iStart==iEnd ){ UChar32 c; iStart = ubrk_current(pCsr->pIter); iEnd = ubrk_next(pCsr->pIter); if( iEnd==UBRK_DONE ){ return SQLITE_DONE; } while( iStartaChar, iWhite, pCsr->nChar, c); if( u_isspace(c) ){ iStart = iWhite; }else{ break; } } assert(iStart<=iEnd); } do { UErrorCode status = U_ZERO_ERROR; if( nByte ){ char *zNew = sqlite3_realloc(pCsr->zBuffer, nByte); if( !zNew ){ return SQLITE_NOMEM; } pCsr->zBuffer = zNew; pCsr->nBuffer = nByte; } u_strToUTF8( pCsr->zBuffer, pCsr->nBuffer, &nByte, /* Output vars */ &pCsr->aChar[iStart], iEnd-iStart, /* Input vars */ &status /* Output success/failure */ ); } while( nByte>pCsr->nBuffer ); *ppToken = pCsr->zBuffer; *pnBytes = nByte; *piStartOffset = pCsr->aOffset[iStart]; *piEndOffset = pCsr->aOffset[iEnd]; *piPosition = pCsr->iToken++; return SQLITE_OK; } /* ** The set of routines that implement the simple tokenizer */ static const sqlite3_tokenizer_module icuTokenizerModule = { 0, /* iVersion */ icuCreate, /* xCreate */ icuDestroy, /* xCreate */ icuOpen, /* xOpen */ icuClose, /* xClose */ icuNext, /* xNext */ 0, /* xLanguageid */ }; /* ** Set *ppModule to point at the implementation of the ICU tokenizer. */ SQLITE_PRIVATE void sqlite3Fts3IcuTokenizerModule( sqlite3_tokenizer_module const**ppModule ){ *ppModule = &icuTokenizerModule; } #endif /* defined(SQLITE_ENABLE_ICU) */ #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */ /************** End of fts3_icu.c ********************************************/ /************** Begin file sqlite3rbu.c **************************************/ /* ** 2014 August 30 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ************************************************************************* ** ** ** OVERVIEW ** ** The RBU extension requires that the RBU update be packaged as an ** SQLite database. The tables it expects to find are described in ** sqlite3rbu.h. Essentially, for each table xyz in the target database ** that the user wishes to write to, a corresponding data_xyz table is ** created in the RBU database and populated with one row for each row to ** update, insert or delete from the target table. ** ** The update proceeds in three stages: ** ** 1) The database is updated. The modified database pages are written ** to a *-oal file. A *-oal file is just like a *-wal file, except ** that it is named "-oal" instead of "-wal". ** Because regular SQLite clients do not look for file named ** "-oal", they go on using the original database in ** rollback mode while the *-oal file is being generated. ** ** During this stage RBU does not update the database by writing ** directly to the target tables. Instead it creates "imposter" ** tables using the SQLITE_TESTCTRL_IMPOSTER interface that it uses ** to update each b-tree individually. All updates required by each ** b-tree are completed before moving on to the next, and all ** updates are done in sorted key order. ** ** 2) The "-oal" file is moved to the equivalent "-wal" ** location using a call to rename(2). Before doing this the RBU ** module takes an EXCLUSIVE lock on the database file, ensuring ** that there are no other active readers. ** ** Once the EXCLUSIVE lock is released, any other database readers ** detect the new *-wal file and read the database in wal mode. At ** this point they see the new version of the database - including ** the updates made as part of the RBU update. ** ** 3) The new *-wal file is checkpointed. This proceeds in the same way ** as a regular database checkpoint, except that a single frame is ** checkpointed each time sqlite3rbu_step() is called. If the RBU ** handle is closed before the entire *-wal file is checkpointed, ** the checkpoint progress is saved in the RBU database and the ** checkpoint can be resumed by another RBU client at some point in ** the future. ** ** POTENTIAL PROBLEMS ** ** The rename() call might not be portable. And RBU is not currently ** syncing the directory after renaming the file. ** ** When state is saved, any commit to the *-oal file and the commit to ** the RBU update database are not atomic. So if the power fails at the ** wrong moment they might get out of sync. As the main database will be ** committed before the RBU update database this will likely either just ** pass unnoticed, or result in SQLITE_CONSTRAINT errors (due to UNIQUE ** constraint violations). ** ** If some client does modify the target database mid RBU update, or some ** other error occurs, the RBU extension will keep throwing errors. It's ** not really clear how to get out of this state. The system could just ** by delete the RBU update database and *-oal file and have the device ** download the update again and start over. ** ** At present, for an UPDATE, both the new.* and old.* records are ** collected in the rbu_xyz table. And for both UPDATEs and DELETEs all ** fields are collected. This means we're probably writing a lot more ** data to disk when saving the state of an ongoing update to the RBU ** update database than is strictly necessary. ** */ /* #include */ /* #include */ /* #include */ /* #include "sqlite3.h" */ #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_RBU) /************** Include sqlite3rbu.h in the middle of sqlite3rbu.c ***********/ /************** Begin file sqlite3rbu.h **************************************/ /* ** 2014 August 30 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ************************************************************************* ** ** This file contains the public interface for the RBU extension. */ /* ** SUMMARY ** ** Writing a transaction containing a large number of operations on ** b-tree indexes that are collectively larger than the available cache ** memory can be very inefficient. ** ** The problem is that in order to update a b-tree, the leaf page (at least) ** containing the entry being inserted or deleted must be modified. If the ** working set of leaves is larger than the available cache memory, then a ** single leaf that is modified more than once as part of the transaction ** may be loaded from or written to the persistent media multiple times. ** Additionally, because the index updates are likely to be applied in ** random order, access to pages within the database is also likely to be in ** random order, which is itself quite inefficient. ** ** One way to improve the situation is to sort the operations on each index ** by index key before applying them to the b-tree. This leads to an IO ** pattern that resembles a single linear scan through the index b-tree, ** and all but guarantees each modified leaf page is loaded and stored ** exactly once. SQLite uses this trick to improve the performance of ** CREATE INDEX commands. This extension allows it to be used to improve ** the performance of large transactions on existing databases. ** ** Additionally, this extension allows the work involved in writing the ** large transaction to be broken down into sub-transactions performed ** sequentially by separate processes. This is useful if the system cannot ** guarantee that a single update process will run for long enough to apply ** the entire update, for example because the update is being applied on a ** mobile device that is frequently rebooted. Even after the writer process ** has committed one or more sub-transactions, other database clients continue ** to read from the original database snapshot. In other words, partially ** applied transactions are not visible to other clients. ** ** "RBU" stands for "Resumable Bulk Update". As in a large database update ** transmitted via a wireless network to a mobile device. A transaction ** applied using this extension is hence refered to as an "RBU update". ** ** ** LIMITATIONS ** ** An "RBU update" transaction is subject to the following limitations: ** ** * The transaction must consist of INSERT, UPDATE and DELETE operations ** only. ** ** * INSERT statements may not use any default values. ** ** * UPDATE and DELETE statements must identify their target rows by ** non-NULL PRIMARY KEY values. Rows with NULL values stored in PRIMARY ** KEY fields may not be updated or deleted. If the table being written ** has no PRIMARY KEY, affected rows must be identified by rowid. ** ** * UPDATE statements may not modify PRIMARY KEY columns. ** ** * No triggers will be fired. ** ** * No foreign key violations are detected or reported. ** ** * CHECK constraints are not enforced. ** ** * No constraint handling mode except for "OR ROLLBACK" is supported. ** ** ** PREPARATION ** ** An "RBU update" is stored as a separate SQLite database. A database ** containing an RBU update is an "RBU database". For each table in the ** target database to be updated, the RBU database should contain a table ** named "data_" containing the same set of columns as the ** target table, and one more - "rbu_control". The data_% table should ** have no PRIMARY KEY or UNIQUE constraints, but each column should have ** the same type as the corresponding column in the target database. ** The "rbu_control" column should have no type at all. For example, if ** the target database contains: ** ** CREATE TABLE t1(a INTEGER PRIMARY KEY, b TEXT, c UNIQUE); ** ** Then the RBU database should contain: ** ** CREATE TABLE data_t1(a INTEGER, b TEXT, c, rbu_control); ** ** The order of the columns in the data_% table does not matter. ** ** Instead of a regular table, the RBU database may also contain virtual ** tables or view named using the data_ naming scheme. ** ** Instead of the plain data_ naming scheme, RBU database tables ** may also be named data_, where is any sequence ** of zero or more numeric characters (0-9). This can be significant because ** tables within the RBU database are always processed in order sorted by ** name. By judicious selection of the portion of the names ** of the RBU tables the user can therefore control the order in which they ** are processed. This can be useful, for example, to ensure that "external ** content" FTS4 tables are updated before their underlying content tables. ** ** If the target database table is a virtual table or a table that has no ** PRIMARY KEY declaration, the data_% table must also contain a column ** named "rbu_rowid". This column is mapped to the tables implicit primary ** key column - "rowid". Virtual tables for which the "rowid" column does ** not function like a primary key value cannot be updated using RBU. For ** example, if the target db contains either of the following: ** ** CREATE VIRTUAL TABLE x1 USING fts3(a, b); ** CREATE TABLE x1(a, b) ** ** then the RBU database should contain: ** ** CREATE TABLE data_x1(a, b, rbu_rowid, rbu_control); ** ** All non-hidden columns (i.e. all columns matched by "SELECT *") of the ** target table must be present in the input table. For virtual tables, ** hidden columns are optional - they are updated by RBU if present in ** the input table, or not otherwise. For example, to write to an fts4 ** table with a hidden languageid column such as: ** ** CREATE VIRTUAL TABLE ft1 USING fts4(a, b, languageid='langid'); ** ** Either of the following input table schemas may be used: ** ** CREATE TABLE data_ft1(a, b, langid, rbu_rowid, rbu_control); ** CREATE TABLE data_ft1(a, b, rbu_rowid, rbu_control); ** ** For each row to INSERT into the target database as part of the RBU ** update, the corresponding data_% table should contain a single record ** with the "rbu_control" column set to contain integer value 0. The ** other columns should be set to the values that make up the new record ** to insert. ** ** If the target database table has an INTEGER PRIMARY KEY, it is not ** possible to insert a NULL value into the IPK column. Attempting to ** do so results in an SQLITE_MISMATCH error. ** ** For each row to DELETE from the target database as part of the RBU ** update, the corresponding data_% table should contain a single record ** with the "rbu_control" column set to contain integer value 1. The ** real primary key values of the row to delete should be stored in the ** corresponding columns of the data_% table. The values stored in the ** other columns are not used. ** ** For each row to UPDATE from the target database as part of the RBU ** update, the corresponding data_% table should contain a single record ** with the "rbu_control" column set to contain a value of type text. ** The real primary key values identifying the row to update should be ** stored in the corresponding columns of the data_% table row, as should ** the new values of all columns being update. The text value in the ** "rbu_control" column must contain the same number of characters as ** there are columns in the target database table, and must consist entirely ** of 'x' and '.' characters (or in some special cases 'd' - see below). For ** each column that is being updated, the corresponding character is set to ** 'x'. For those that remain as they are, the corresponding character of the ** rbu_control value should be set to '.'. For example, given the tables ** above, the update statement: ** ** UPDATE t1 SET c = 'usa' WHERE a = 4; ** ** is represented by the data_t1 row created by: ** ** INSERT INTO data_t1(a, b, c, rbu_control) VALUES(4, NULL, 'usa', '..x'); ** ** Instead of an 'x' character, characters of the rbu_control value specified ** for UPDATEs may also be set to 'd'. In this case, instead of updating the ** target table with the value stored in the corresponding data_% column, the ** user-defined SQL function "rbu_delta()" is invoked and the result stored in ** the target table column. rbu_delta() is invoked with two arguments - the ** original value currently stored in the target table column and the ** value specified in the data_xxx table. ** ** For example, this row: ** ** INSERT INTO data_t1(a, b, c, rbu_control) VALUES(4, NULL, 'usa', '..d'); ** ** is similar to an UPDATE statement such as: ** ** UPDATE t1 SET c = rbu_delta(c, 'usa') WHERE a = 4; ** ** Finally, if an 'f' character appears in place of a 'd' or 's' in an ** ota_control string, the contents of the data_xxx table column is assumed ** to be a "fossil delta" - a patch to be applied to a blob value in the ** format used by the fossil source-code management system. In this case ** the existing value within the target database table must be of type BLOB. ** It is replaced by the result of applying the specified fossil delta to ** itself. ** ** If the target database table is a virtual table or a table with no PRIMARY ** KEY, the rbu_control value should not include a character corresponding ** to the rbu_rowid value. For example, this: ** ** INSERT INTO data_ft1(a, b, rbu_rowid, rbu_control) ** VALUES(NULL, 'usa', 12, '.x'); ** ** causes a result similar to: ** ** UPDATE ft1 SET b = 'usa' WHERE rowid = 12; ** ** The data_xxx tables themselves should have no PRIMARY KEY declarations. ** However, RBU is more efficient if reading the rows in from each data_xxx ** table in "rowid" order is roughly the same as reading them sorted by ** the PRIMARY KEY of the corresponding target database table. In other ** words, rows should be sorted using the destination table PRIMARY KEY ** fields before they are inserted into the data_xxx tables. ** ** USAGE ** ** The API declared below allows an application to apply an RBU update ** stored on disk to an existing target database. Essentially, the ** application: ** ** 1) Opens an RBU handle using the sqlite3rbu_open() function. ** ** 2) Registers any required virtual table modules with the database ** handle returned by sqlite3rbu_db(). Also, if required, register ** the rbu_delta() implementation. ** ** 3) Calls the sqlite3rbu_step() function one or more times on ** the new handle. Each call to sqlite3rbu_step() performs a single ** b-tree operation, so thousands of calls may be required to apply ** a complete update. ** ** 4) Calls sqlite3rbu_close() to close the RBU update handle. If ** sqlite3rbu_step() has been called enough times to completely ** apply the update to the target database, then the RBU database ** is marked as fully applied. Otherwise, the state of the RBU ** update application is saved in the RBU database for later ** resumption. ** ** See comments below for more detail on APIs. ** ** If an update is only partially applied to the target database by the ** time sqlite3rbu_close() is called, various state information is saved ** within the RBU database. This allows subsequent processes to automatically ** resume the RBU update from where it left off. ** ** To remove all RBU extension state information, returning an RBU database ** to its original contents, it is sufficient to drop all tables that begin ** with the prefix "rbu_" ** ** DATABASE LOCKING ** ** An RBU update may not be applied to a database in WAL mode. Attempting ** to do so is an error (SQLITE_ERROR). ** ** While an RBU handle is open, a SHARED lock may be held on the target ** database file. This means it is possible for other clients to read the ** database, but not to write it. ** ** If an RBU update is started and then suspended before it is completed, ** then an external client writes to the database, then attempting to resume ** the suspended RBU update is also an error (SQLITE_BUSY). */ #ifndef _SQLITE3RBU_H #define _SQLITE3RBU_H /* #include "sqlite3.h" ** Required for error code definitions ** */ #if 0 extern "C" { #endif typedef struct sqlite3rbu sqlite3rbu; /* ** Open an RBU handle. ** ** Argument zTarget is the path to the target database. Argument zRbu is ** the path to the RBU database. Each call to this function must be matched ** by a call to sqlite3rbu_close(). When opening the databases, RBU passes ** the SQLITE_CONFIG_URI flag to sqlite3_open_v2(). So if either zTarget ** or zRbu begin with "file:", it will be interpreted as an SQLite ** database URI, not a regular file name. ** ** If the zState argument is passed a NULL value, the RBU extension stores ** the current state of the update (how many rows have been updated, which ** indexes are yet to be updated etc.) within the RBU database itself. This ** can be convenient, as it means that the RBU application does not need to ** organize removing a separate state file after the update is concluded. ** Or, if zState is non-NULL, it must be a path to a database file in which ** the RBU extension can store the state of the update. ** ** When resuming an RBU update, the zState argument must be passed the same ** value as when the RBU update was started. ** ** Once the RBU update is finished, the RBU extension does not ** automatically remove any zState database file, even if it created it. ** ** By default, RBU uses the default VFS to access the files on disk. To ** use a VFS other than the default, an SQLite "file:" URI containing a ** "vfs=..." option may be passed as the zTarget option. ** ** IMPORTANT NOTE FOR ZIPVFS USERS: The RBU extension works with all of ** SQLite's built-in VFSs, including the multiplexor VFS. However it does ** not work out of the box with zipvfs. Refer to the comment describing ** the zipvfs_create_vfs() API below for details on using RBU with zipvfs. */ SQLITE_API sqlite3rbu *sqlite3rbu_open( const char *zTarget, const char *zRbu, const char *zState ); /* ** Open an RBU handle to perform an RBU vacuum on database file zTarget. ** An RBU vacuum is similar to SQLite's built-in VACUUM command, except ** that it can be suspended and resumed like an RBU update. ** ** The second argument to this function identifies a database in which ** to store the state of the RBU vacuum operation if it is suspended. The ** first time sqlite3rbu_vacuum() is called, to start an RBU vacuum ** operation, the state database should either not exist or be empty ** (contain no tables). If an RBU vacuum is suspended by calling ** sqlite3rbu_close() on the RBU handle before sqlite3rbu_step() has ** returned SQLITE_DONE, the vacuum state is stored in the state database. ** The vacuum can be resumed by calling this function to open a new RBU ** handle specifying the same target and state databases. ** ** If the second argument passed to this function is NULL, then the ** name of the state database is "-vacuum", where ** is the name of the target database file. In this case, on UNIX, if the ** state database is not already present in the file-system, it is created ** with the same permissions as the target db is made. ** ** This function does not delete the state database after an RBU vacuum ** is completed, even if it created it. However, if the call to ** sqlite3rbu_close() returns any value other than SQLITE_OK, the contents ** of the state tables within the state database are zeroed. This way, ** the next call to sqlite3rbu_vacuum() opens a handle that starts a ** new RBU vacuum operation. ** ** As with sqlite3rbu_open(), Zipvfs users should rever to the comment ** describing the sqlite3rbu_create_vfs() API function below for ** a description of the complications associated with using RBU with ** zipvfs databases. */ SQLITE_API sqlite3rbu *sqlite3rbu_vacuum( const char *zTarget, const char *zState ); /* ** Internally, each RBU connection uses a separate SQLite database ** connection to access the target and rbu update databases. This ** API allows the application direct access to these database handles. ** ** The first argument passed to this function must be a valid, open, RBU ** handle. The second argument should be passed zero to access the target ** database handle, or non-zero to access the rbu update database handle. ** Accessing the underlying database handles may be useful in the ** following scenarios: ** ** * If any target tables are virtual tables, it may be necessary to ** call sqlite3_create_module() on the target database handle to ** register the required virtual table implementations. ** ** * If the data_xxx tables in the RBU source database are virtual ** tables, the application may need to call sqlite3_create_module() on ** the rbu update db handle to any required virtual table ** implementations. ** ** * If the application uses the "rbu_delta()" feature described above, ** it must use sqlite3_create_function() or similar to register the ** rbu_delta() implementation with the target database handle. ** ** If an error has occurred, either while opening or stepping the RBU object, ** this function may return NULL. The error code and message may be collected ** when sqlite3rbu_close() is called. ** ** Database handles returned by this function remain valid until the next ** call to any sqlite3rbu_xxx() function other than sqlite3rbu_db(). */ SQLITE_API sqlite3 *sqlite3rbu_db(sqlite3rbu*, int bRbu); /* ** Do some work towards applying the RBU update to the target db. ** ** Return SQLITE_DONE if the update has been completely applied, or ** SQLITE_OK if no error occurs but there remains work to do to apply ** the RBU update. If an error does occur, some other error code is ** returned. ** ** Once a call to sqlite3rbu_step() has returned a value other than ** SQLITE_OK, all subsequent calls on the same RBU handle are no-ops ** that immediately return the same value. */ SQLITE_API int sqlite3rbu_step(sqlite3rbu *pRbu); /* ** Force RBU to save its state to disk. ** ** If a power failure or application crash occurs during an update, following ** system recovery RBU may resume the update from the point at which the state ** was last saved. In other words, from the most recent successful call to ** sqlite3rbu_close() or this function. ** ** SQLITE_OK is returned if successful, or an SQLite error code otherwise. */ SQLITE_API int sqlite3rbu_savestate(sqlite3rbu *pRbu); /* ** Close an RBU handle. ** ** If the RBU update has been completely applied, mark the RBU database ** as fully applied. Otherwise, assuming no error has occurred, save the ** current state of the RBU update appliation to the RBU database. ** ** If an error has already occurred as part of an sqlite3rbu_step() ** or sqlite3rbu_open() call, or if one occurs within this function, an ** SQLite error code is returned. Additionally, *pzErrmsg may be set to ** point to a buffer containing a utf-8 formatted English language error ** message. It is the responsibility of the caller to eventually free any ** such buffer using sqlite3_free(). ** ** Otherwise, if no error occurs, this function returns SQLITE_OK if the ** update has been partially applied, or SQLITE_DONE if it has been ** completely applied. */ SQLITE_API int sqlite3rbu_close(sqlite3rbu *pRbu, char **pzErrmsg); /* ** Return the total number of key-value operations (inserts, deletes or ** updates) that have been performed on the target database since the ** current RBU update was started. */ SQLITE_API sqlite3_int64 sqlite3rbu_progress(sqlite3rbu *pRbu); /* ** Obtain permyriadage (permyriadage is to 10000 as percentage is to 100) ** progress indications for the two stages of an RBU update. This API may ** be useful for driving GUI progress indicators and similar. ** ** An RBU update is divided into two stages: ** ** * Stage 1, in which changes are accumulated in an oal/wal file, and ** * Stage 2, in which the contents of the wal file are copied into the ** main database. ** ** The update is visible to non-RBU clients during stage 2. During stage 1 ** non-RBU reader clients may see the original database. ** ** If this API is called during stage 2 of the update, output variable ** (*pnOne) is set to 10000 to indicate that stage 1 has finished and (*pnTwo) ** to a value between 0 and 10000 to indicate the permyriadage progress of ** stage 2. A value of 5000 indicates that stage 2 is half finished, ** 9000 indicates that it is 90% finished, and so on. ** ** If this API is called during stage 1 of the update, output variable ** (*pnTwo) is set to 0 to indicate that stage 2 has not yet started. The ** value to which (*pnOne) is set depends on whether or not the RBU ** database contains an "rbu_count" table. The rbu_count table, if it ** exists, must contain the same columns as the following: ** ** CREATE TABLE rbu_count(tbl TEXT PRIMARY KEY, cnt INTEGER) WITHOUT ROWID; ** ** There must be one row in the table for each source (data_xxx) table within ** the RBU database. The 'tbl' column should contain the name of the source ** table. The 'cnt' column should contain the number of rows within the ** source table. ** ** If the rbu_count table is present and populated correctly and this ** API is called during stage 1, the *pnOne output variable is set to the ** permyriadage progress of the same stage. If the rbu_count table does ** not exist, then (*pnOne) is set to -1 during stage 1. If the rbu_count ** table exists but is not correctly populated, the value of the *pnOne ** output variable during stage 1 is undefined. */ SQLITE_API void sqlite3rbu_bp_progress(sqlite3rbu *pRbu, int *pnOne, int *pnTwo); /* ** Obtain an indication as to the current stage of an RBU update or vacuum. ** This function always returns one of the SQLITE_RBU_STATE_XXX constants ** defined in this file. Return values should be interpreted as follows: ** ** SQLITE_RBU_STATE_OAL: ** RBU is currently building a *-oal file. The next call to sqlite3rbu_step() ** may either add further data to the *-oal file, or compute data that will ** be added by a subsequent call. ** ** SQLITE_RBU_STATE_MOVE: ** RBU has finished building the *-oal file. The next call to sqlite3rbu_step() ** will move the *-oal file to the equivalent *-wal path. If the current ** operation is an RBU update, then the updated version of the database ** file will become visible to ordinary SQLite clients following the next ** call to sqlite3rbu_step(). ** ** SQLITE_RBU_STATE_CHECKPOINT: ** RBU is currently performing an incremental checkpoint. The next call to ** sqlite3rbu_step() will copy a page of data from the *-wal file into ** the target database file. ** ** SQLITE_RBU_STATE_DONE: ** The RBU operation has finished. Any subsequent calls to sqlite3rbu_step() ** will immediately return SQLITE_DONE. ** ** SQLITE_RBU_STATE_ERROR: ** An error has occurred. Any subsequent calls to sqlite3rbu_step() will ** immediately return the SQLite error code associated with the error. */ #define SQLITE_RBU_STATE_OAL 1 #define SQLITE_RBU_STATE_MOVE 2 #define SQLITE_RBU_STATE_CHECKPOINT 3 #define SQLITE_RBU_STATE_DONE 4 #define SQLITE_RBU_STATE_ERROR 5 SQLITE_API int sqlite3rbu_state(sqlite3rbu *pRbu); /* ** Create an RBU VFS named zName that accesses the underlying file-system ** via existing VFS zParent. Or, if the zParent parameter is passed NULL, ** then the new RBU VFS uses the default system VFS to access the file-system. ** The new object is registered as a non-default VFS with SQLite before ** returning. ** ** Part of the RBU implementation uses a custom VFS object. Usually, this ** object is created and deleted automatically by RBU. ** ** The exception is for applications that also use zipvfs. In this case, ** the custom VFS must be explicitly created by the user before the RBU ** handle is opened. The RBU VFS should be installed so that the zipvfs ** VFS uses the RBU VFS, which in turn uses any other VFS layers in use ** (for example multiplexor) to access the file-system. For example, ** to assemble an RBU enabled VFS stack that uses both zipvfs and ** multiplexor (error checking omitted): ** ** // Create a VFS named "multiplex" (not the default). ** sqlite3_multiplex_initialize(0, 0); ** ** // Create an rbu VFS named "rbu" that uses multiplexor. If the ** // second argument were replaced with NULL, the "rbu" VFS would ** // access the file-system via the system default VFS, bypassing the ** // multiplexor. ** sqlite3rbu_create_vfs("rbu", "multiplex"); ** ** // Create a zipvfs VFS named "zipvfs" that uses rbu. ** zipvfs_create_vfs_v3("zipvfs", "rbu", 0, xCompressorAlgorithmDetector); ** ** // Make zipvfs the default VFS. ** sqlite3_vfs_register(sqlite3_vfs_find("zipvfs"), 1); ** ** Because the default VFS created above includes a RBU functionality, it ** may be used by RBU clients. Attempting to use RBU with a zipvfs VFS stack ** that does not include the RBU layer results in an error. ** ** The overhead of adding the "rbu" VFS to the system is negligible for ** non-RBU users. There is no harm in an application accessing the ** file-system via "rbu" all the time, even if it only uses RBU functionality ** occasionally. */ SQLITE_API int sqlite3rbu_create_vfs(const char *zName, const char *zParent); /* ** Deregister and destroy an RBU vfs created by an earlier call to ** sqlite3rbu_create_vfs(). ** ** VFS objects are not reference counted. If a VFS object is destroyed ** before all database handles that use it have been closed, the results ** are undefined. */ SQLITE_API void sqlite3rbu_destroy_vfs(const char *zName); #if 0 } /* end of the 'extern "C"' block */ #endif #endif /* _SQLITE3RBU_H */ /************** End of sqlite3rbu.h ******************************************/ /************** Continuing where we left off in sqlite3rbu.c *****************/ #if defined(_WIN32_WCE) /* #include "windows.h" */ #endif /* Maximum number of prepared UPDATE statements held by this module */ #define SQLITE_RBU_UPDATE_CACHESIZE 16 /* ** Swap two objects of type TYPE. */ #if !defined(SQLITE_AMALGAMATION) # define SWAP(TYPE,A,B) {TYPE t=A; A=B; B=t;} #endif /* ** The rbu_state table is used to save the state of a partially applied ** update so that it can be resumed later. The table consists of integer ** keys mapped to values as follows: ** ** RBU_STATE_STAGE: ** May be set to integer values 1, 2, 4 or 5. As follows: ** 1: the *-rbu file is currently under construction. ** 2: the *-rbu file has been constructed, but not yet moved ** to the *-wal path. ** 4: the checkpoint is underway. ** 5: the rbu update has been checkpointed. ** ** RBU_STATE_TBL: ** Only valid if STAGE==1. The target database name of the table ** currently being written. ** ** RBU_STATE_IDX: ** Only valid if STAGE==1. The target database name of the index ** currently being written, or NULL if the main table is currently being ** updated. ** ** RBU_STATE_ROW: ** Only valid if STAGE==1. Number of rows already processed for the current ** table/index. ** ** RBU_STATE_PROGRESS: ** Trbul number of sqlite3rbu_step() calls made so far as part of this ** rbu update. ** ** RBU_STATE_CKPT: ** Valid if STAGE==4. The 64-bit checksum associated with the wal-index ** header created by recovering the *-wal file. This is used to detect ** cases when another client appends frames to the *-wal file in the ** middle of an incremental checkpoint (an incremental checkpoint cannot ** be continued if this happens). ** ** RBU_STATE_COOKIE: ** Valid if STAGE==1. The current change-counter cookie value in the ** target db file. ** ** RBU_STATE_OALSZ: ** Valid if STAGE==1. The size in bytes of the *-oal file. */ #define RBU_STATE_STAGE 1 #define RBU_STATE_TBL 2 #define RBU_STATE_IDX 3 #define RBU_STATE_ROW 4 #define RBU_STATE_PROGRESS 5 #define RBU_STATE_CKPT 6 #define RBU_STATE_COOKIE 7 #define RBU_STATE_OALSZ 8 #define RBU_STATE_PHASEONESTEP 9 #define RBU_STAGE_OAL 1 #define RBU_STAGE_MOVE 2 #define RBU_STAGE_CAPTURE 3 #define RBU_STAGE_CKPT 4 #define RBU_STAGE_DONE 5 #define RBU_CREATE_STATE \ "CREATE TABLE IF NOT EXISTS %s.rbu_state(k INTEGER PRIMARY KEY, v)" typedef struct RbuFrame RbuFrame; typedef struct RbuObjIter RbuObjIter; typedef struct RbuState RbuState; typedef struct rbu_vfs rbu_vfs; typedef struct rbu_file rbu_file; typedef struct RbuUpdateStmt RbuUpdateStmt; #if !defined(SQLITE_AMALGAMATION) typedef unsigned int u32; typedef unsigned short u16; typedef unsigned char u8; typedef sqlite3_int64 i64; #endif /* ** These values must match the values defined in wal.c for the equivalent ** locks. These are not magic numbers as they are part of the SQLite file ** format. */ #define WAL_LOCK_WRITE 0 #define WAL_LOCK_CKPT 1 #define WAL_LOCK_READ0 3 #define SQLITE_FCNTL_RBUCNT 5149216 /* ** A structure to store values read from the rbu_state table in memory. */ struct RbuState { int eStage; char *zTbl; char *zIdx; i64 iWalCksum; int nRow; i64 nProgress; u32 iCookie; i64 iOalSz; i64 nPhaseOneStep; }; struct RbuUpdateStmt { char *zMask; /* Copy of update mask used with pUpdate */ sqlite3_stmt *pUpdate; /* Last update statement (or NULL) */ RbuUpdateStmt *pNext; }; /* ** An iterator of this type is used to iterate through all objects in ** the target database that require updating. For each such table, the ** iterator visits, in order: ** ** * the table itself, ** * each index of the table (zero or more points to visit), and ** * a special "cleanup table" state. ** ** abIndexed: ** If the table has no indexes on it, abIndexed is set to NULL. Otherwise, ** it points to an array of flags nTblCol elements in size. The flag is ** set for each column that is either a part of the PK or a part of an ** index. Or clear otherwise. ** */ struct RbuObjIter { sqlite3_stmt *pTblIter; /* Iterate through tables */ sqlite3_stmt *pIdxIter; /* Index iterator */ int nTblCol; /* Size of azTblCol[] array */ char **azTblCol; /* Array of unquoted target column names */ char **azTblType; /* Array of target column types */ int *aiSrcOrder; /* src table col -> target table col */ u8 *abTblPk; /* Array of flags, set on target PK columns */ u8 *abNotNull; /* Array of flags, set on NOT NULL columns */ u8 *abIndexed; /* Array of flags, set on indexed & PK cols */ int eType; /* Table type - an RBU_PK_XXX value */ /* Output variables. zTbl==0 implies EOF. */ int bCleanup; /* True in "cleanup" state */ const char *zTbl; /* Name of target db table */ const char *zDataTbl; /* Name of rbu db table (or null) */ const char *zIdx; /* Name of target db index (or null) */ int iTnum; /* Root page of current object */ int iPkTnum; /* If eType==EXTERNAL, root of PK index */ int bUnique; /* Current index is unique */ int nIndex; /* Number of aux. indexes on table zTbl */ /* Statements created by rbuObjIterPrepareAll() */ int nCol; /* Number of columns in current object */ sqlite3_stmt *pSelect; /* Source data */ sqlite3_stmt *pInsert; /* Statement for INSERT operations */ sqlite3_stmt *pDelete; /* Statement for DELETE ops */ sqlite3_stmt *pTmpInsert; /* Insert into rbu_tmp_$zDataTbl */ /* Last UPDATE used (for PK b-tree updates only), or NULL. */ RbuUpdateStmt *pRbuUpdate; }; /* ** Values for RbuObjIter.eType ** ** 0: Table does not exist (error) ** 1: Table has an implicit rowid. ** 2: Table has an explicit IPK column. ** 3: Table has an external PK index. ** 4: Table is WITHOUT ROWID. ** 5: Table is a virtual table. */ #define RBU_PK_NOTABLE 0 #define RBU_PK_NONE 1 #define RBU_PK_IPK 2 #define RBU_PK_EXTERNAL 3 #define RBU_PK_WITHOUT_ROWID 4 #define RBU_PK_VTAB 5 /* ** Within the RBU_STAGE_OAL stage, each call to sqlite3rbu_step() performs ** one of the following operations. */ #define RBU_INSERT 1 /* Insert on a main table b-tree */ #define RBU_DELETE 2 /* Delete a row from a main table b-tree */ #define RBU_REPLACE 3 /* Delete and then insert a row */ #define RBU_IDX_DELETE 4 /* Delete a row from an aux. index b-tree */ #define RBU_IDX_INSERT 5 /* Insert on an aux. index b-tree */ #define RBU_UPDATE 6 /* Update a row in a main table b-tree */ /* ** A single step of an incremental checkpoint - frame iWalFrame of the wal ** file should be copied to page iDbPage of the database file. */ struct RbuFrame { u32 iDbPage; u32 iWalFrame; }; /* ** RBU handle. ** ** nPhaseOneStep: ** If the RBU database contains an rbu_count table, this value is set to ** a running estimate of the number of b-tree operations required to ** finish populating the *-oal file. This allows the sqlite3_bp_progress() ** API to calculate the permyriadage progress of populating the *-oal file ** using the formula: ** ** permyriadage = (10000 * nProgress) / nPhaseOneStep ** ** nPhaseOneStep is initialized to the sum of: ** ** nRow * (nIndex + 1) ** ** for all source tables in the RBU database, where nRow is the number ** of rows in the source table and nIndex the number of indexes on the ** corresponding target database table. ** ** This estimate is accurate if the RBU update consists entirely of ** INSERT operations. However, it is inaccurate if: ** ** * the RBU update contains any UPDATE operations. If the PK specified ** for an UPDATE operation does not exist in the target table, then ** no b-tree operations are required on index b-trees. Or if the ** specified PK does exist, then (nIndex*2) such operations are ** required (one delete and one insert on each index b-tree). ** ** * the RBU update contains any DELETE operations for which the specified ** PK does not exist. In this case no operations are required on index ** b-trees. ** ** * the RBU update contains REPLACE operations. These are similar to ** UPDATE operations. ** ** nPhaseOneStep is updated to account for the conditions above during the ** first pass of each source table. The updated nPhaseOneStep value is ** stored in the rbu_state table if the RBU update is suspended. */ struct sqlite3rbu { int eStage; /* Value of RBU_STATE_STAGE field */ sqlite3 *dbMain; /* target database handle */ sqlite3 *dbRbu; /* rbu database handle */ char *zTarget; /* Path to target db */ char *zRbu; /* Path to rbu db */ char *zState; /* Path to state db (or NULL if zRbu) */ char zStateDb[5]; /* Db name for state ("stat" or "main") */ int rc; /* Value returned by last rbu_step() call */ char *zErrmsg; /* Error message if rc!=SQLITE_OK */ int nStep; /* Rows processed for current object */ int nProgress; /* Rows processed for all objects */ RbuObjIter objiter; /* Iterator for skipping through tbl/idx */ const char *zVfsName; /* Name of automatically created rbu vfs */ rbu_file *pTargetFd; /* File handle open on target db */ i64 iOalSz; i64 nPhaseOneStep; /* The following state variables are used as part of the incremental ** checkpoint stage (eStage==RBU_STAGE_CKPT). See comments surrounding ** function rbuSetupCheckpoint() for details. */ u32 iMaxFrame; /* Largest iWalFrame value in aFrame[] */ u32 mLock; int nFrame; /* Entries in aFrame[] array */ int nFrameAlloc; /* Allocated size of aFrame[] array */ RbuFrame *aFrame; int pgsz; u8 *aBuf; i64 iWalCksum; /* Used in RBU vacuum mode only */ int nRbu; /* Number of RBU VFS in the stack */ rbu_file *pRbuFd; /* Fd for main db of dbRbu */ }; /* ** An rbu VFS is implemented using an instance of this structure. */ struct rbu_vfs { sqlite3_vfs base; /* rbu VFS shim methods */ sqlite3_vfs *pRealVfs; /* Underlying VFS */ sqlite3_mutex *mutex; /* Mutex to protect pMain */ rbu_file *pMain; /* Linked list of main db files */ }; /* ** Each file opened by an rbu VFS is represented by an instance of ** the following structure. */ struct rbu_file { sqlite3_file base; /* sqlite3_file methods */ sqlite3_file *pReal; /* Underlying file handle */ rbu_vfs *pRbuVfs; /* Pointer to the rbu_vfs object */ sqlite3rbu *pRbu; /* Pointer to rbu object (rbu target only) */ int openFlags; /* Flags this file was opened with */ u32 iCookie; /* Cookie value for main db files */ u8 iWriteVer; /* "write-version" value for main db files */ u8 bNolock; /* True to fail EXCLUSIVE locks */ int nShm; /* Number of entries in apShm[] array */ char **apShm; /* Array of mmap'd *-shm regions */ char *zDel; /* Delete this when closing file */ const char *zWal; /* Wal filename for this main db file */ rbu_file *pWalFd; /* Wal file descriptor for this main db */ rbu_file *pMainNext; /* Next MAIN_DB file */ }; /* ** True for an RBU vacuum handle, or false otherwise. */ #define rbuIsVacuum(p) ((p)->zTarget==0) /************************************************************************* ** The following three functions, found below: ** ** rbuDeltaGetInt() ** rbuDeltaChecksum() ** rbuDeltaApply() ** ** are lifted from the fossil source code (http://fossil-scm.org). They ** are used to implement the scalar SQL function rbu_fossil_delta(). */ /* ** Read bytes from *pz and convert them into a positive integer. When ** finished, leave *pz pointing to the first character past the end of ** the integer. The *pLen parameter holds the length of the string ** in *pz and is decremented once for each character in the integer. */ static unsigned int rbuDeltaGetInt(const char **pz, int *pLen){ static const signed char zValue[] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, -1, -1, -1, -1, -1, -1, -1, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, -1, -1, -1, -1, 36, -1, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, -1, -1, -1, 63, -1, }; unsigned int v = 0; int c; unsigned char *z = (unsigned char*)*pz; unsigned char *zStart = z; while( (c = zValue[0x7f&*(z++)])>=0 ){ v = (v<<6) + c; } z--; *pLen -= z - zStart; *pz = (char*)z; return v; } /* ** Compute a 32-bit checksum on the N-byte buffer. Return the result. */ static unsigned int rbuDeltaChecksum(const char *zIn, size_t N){ const unsigned char *z = (const unsigned char *)zIn; unsigned sum0 = 0; unsigned sum1 = 0; unsigned sum2 = 0; unsigned sum3 = 0; while(N >= 16){ sum0 += ((unsigned)z[0] + z[4] + z[8] + z[12]); sum1 += ((unsigned)z[1] + z[5] + z[9] + z[13]); sum2 += ((unsigned)z[2] + z[6] + z[10]+ z[14]); sum3 += ((unsigned)z[3] + z[7] + z[11]+ z[15]); z += 16; N -= 16; } while(N >= 4){ sum0 += z[0]; sum1 += z[1]; sum2 += z[2]; sum3 += z[3]; z += 4; N -= 4; } sum3 += (sum2 << 8) + (sum1 << 16) + (sum0 << 24); switch(N){ case 3: sum3 += (z[2] << 8); case 2: sum3 += (z[1] << 16); case 1: sum3 += (z[0] << 24); default: ; } return sum3; } /* ** Apply a delta. ** ** The output buffer should be big enough to hold the whole output ** file and a NUL terminator at the end. The delta_output_size() ** routine will determine this size for you. ** ** The delta string should be null-terminated. But the delta string ** may contain embedded NUL characters (if the input and output are ** binary files) so we also have to pass in the length of the delta in ** the lenDelta parameter. ** ** This function returns the size of the output file in bytes (excluding ** the final NUL terminator character). Except, if the delta string is ** malformed or intended for use with a source file other than zSrc, ** then this routine returns -1. ** ** Refer to the delta_create() documentation above for a description ** of the delta file format. */ static int rbuDeltaApply( const char *zSrc, /* The source or pattern file */ int lenSrc, /* Length of the source file */ const char *zDelta, /* Delta to apply to the pattern */ int lenDelta, /* Length of the delta */ char *zOut /* Write the output into this preallocated buffer */ ){ unsigned int limit; unsigned int total = 0; #ifndef FOSSIL_OMIT_DELTA_CKSUM_TEST char *zOrigOut = zOut; #endif limit = rbuDeltaGetInt(&zDelta, &lenDelta); if( *zDelta!='\n' ){ /* ERROR: size integer not terminated by "\n" */ return -1; } zDelta++; lenDelta--; while( *zDelta && lenDelta>0 ){ unsigned int cnt, ofst; cnt = rbuDeltaGetInt(&zDelta, &lenDelta); switch( zDelta[0] ){ case '@': { zDelta++; lenDelta--; ofst = rbuDeltaGetInt(&zDelta, &lenDelta); if( lenDelta>0 && zDelta[0]!=',' ){ /* ERROR: copy command not terminated by ',' */ return -1; } zDelta++; lenDelta--; total += cnt; if( total>limit ){ /* ERROR: copy exceeds output file size */ return -1; } if( (int)(ofst+cnt) > lenSrc ){ /* ERROR: copy extends past end of input */ return -1; } memcpy(zOut, &zSrc[ofst], cnt); zOut += cnt; break; } case ':': { zDelta++; lenDelta--; total += cnt; if( total>limit ){ /* ERROR: insert command gives an output larger than predicted */ return -1; } if( (int)cnt>lenDelta ){ /* ERROR: insert count exceeds size of delta */ return -1; } memcpy(zOut, zDelta, cnt); zOut += cnt; zDelta += cnt; lenDelta -= cnt; break; } case ';': { zDelta++; lenDelta--; zOut[0] = 0; #ifndef FOSSIL_OMIT_DELTA_CKSUM_TEST if( cnt!=rbuDeltaChecksum(zOrigOut, total) ){ /* ERROR: bad checksum */ return -1; } #endif if( total!=limit ){ /* ERROR: generated size does not match predicted size */ return -1; } return total; } default: { /* ERROR: unknown delta operator */ return -1; } } } /* ERROR: unterminated delta */ return -1; } static int rbuDeltaOutputSize(const char *zDelta, int lenDelta){ int size; size = rbuDeltaGetInt(&zDelta, &lenDelta); if( *zDelta!='\n' ){ /* ERROR: size integer not terminated by "\n" */ return -1; } return size; } /* ** End of code taken from fossil. *************************************************************************/ /* ** Implementation of SQL scalar function rbu_fossil_delta(). ** ** This function applies a fossil delta patch to a blob. Exactly two ** arguments must be passed to this function. The first is the blob to ** patch and the second the patch to apply. If no error occurs, this ** function returns the patched blob. */ static void rbuFossilDeltaFunc( sqlite3_context *context, int argc, sqlite3_value **argv ){ const char *aDelta; int nDelta; const char *aOrig; int nOrig; int nOut; int nOut2; char *aOut; assert( argc==2 ); nOrig = sqlite3_value_bytes(argv[0]); aOrig = (const char*)sqlite3_value_blob(argv[0]); nDelta = sqlite3_value_bytes(argv[1]); aDelta = (const char*)sqlite3_value_blob(argv[1]); /* Figure out the size of the output */ nOut = rbuDeltaOutputSize(aDelta, nDelta); if( nOut<0 ){ sqlite3_result_error(context, "corrupt fossil delta", -1); return; } aOut = sqlite3_malloc(nOut+1); if( aOut==0 ){ sqlite3_result_error_nomem(context); }else{ nOut2 = rbuDeltaApply(aOrig, nOrig, aDelta, nDelta, aOut); if( nOut2!=nOut ){ sqlite3_result_error(context, "corrupt fossil delta", -1); }else{ sqlite3_result_blob(context, aOut, nOut, sqlite3_free); } } } /* ** Prepare the SQL statement in buffer zSql against database handle db. ** If successful, set *ppStmt to point to the new statement and return ** SQLITE_OK. ** ** Otherwise, if an error does occur, set *ppStmt to NULL and return ** an SQLite error code. Additionally, set output variable *pzErrmsg to ** point to a buffer containing an error message. It is the responsibility ** of the caller to (eventually) free this buffer using sqlite3_free(). */ static int prepareAndCollectError( sqlite3 *db, sqlite3_stmt **ppStmt, char **pzErrmsg, const char *zSql ){ int rc = sqlite3_prepare_v2(db, zSql, -1, ppStmt, 0); if( rc!=SQLITE_OK ){ *pzErrmsg = sqlite3_mprintf("%s", sqlite3_errmsg(db)); *ppStmt = 0; } return rc; } /* ** Reset the SQL statement passed as the first argument. Return a copy ** of the value returned by sqlite3_reset(). ** ** If an error has occurred, then set *pzErrmsg to point to a buffer ** containing an error message. It is the responsibility of the caller ** to eventually free this buffer using sqlite3_free(). */ static int resetAndCollectError(sqlite3_stmt *pStmt, char **pzErrmsg){ int rc = sqlite3_reset(pStmt); if( rc!=SQLITE_OK ){ *pzErrmsg = sqlite3_mprintf("%s", sqlite3_errmsg(sqlite3_db_handle(pStmt))); } return rc; } /* ** Unless it is NULL, argument zSql points to a buffer allocated using ** sqlite3_malloc containing an SQL statement. This function prepares the SQL ** statement against database db and frees the buffer. If statement ** compilation is successful, *ppStmt is set to point to the new statement ** handle and SQLITE_OK is returned. ** ** Otherwise, if an error occurs, *ppStmt is set to NULL and an error code ** returned. In this case, *pzErrmsg may also be set to point to an error ** message. It is the responsibility of the caller to free this error message ** buffer using sqlite3_free(). ** ** If argument zSql is NULL, this function assumes that an OOM has occurred. ** In this case SQLITE_NOMEM is returned and *ppStmt set to NULL. */ static int prepareFreeAndCollectError( sqlite3 *db, sqlite3_stmt **ppStmt, char **pzErrmsg, char *zSql ){ int rc; assert( *pzErrmsg==0 ); if( zSql==0 ){ rc = SQLITE_NOMEM; *ppStmt = 0; }else{ rc = prepareAndCollectError(db, ppStmt, pzErrmsg, zSql); sqlite3_free(zSql); } return rc; } /* ** Free the RbuObjIter.azTblCol[] and RbuObjIter.abTblPk[] arrays allocated ** by an earlier call to rbuObjIterCacheTableInfo(). */ static void rbuObjIterFreeCols(RbuObjIter *pIter){ int i; for(i=0; inTblCol; i++){ sqlite3_free(pIter->azTblCol[i]); sqlite3_free(pIter->azTblType[i]); } sqlite3_free(pIter->azTblCol); pIter->azTblCol = 0; pIter->azTblType = 0; pIter->aiSrcOrder = 0; pIter->abTblPk = 0; pIter->abNotNull = 0; pIter->nTblCol = 0; pIter->eType = 0; /* Invalid value */ } /* ** Finalize all statements and free all allocations that are specific to ** the current object (table/index pair). */ static void rbuObjIterClearStatements(RbuObjIter *pIter){ RbuUpdateStmt *pUp; sqlite3_finalize(pIter->pSelect); sqlite3_finalize(pIter->pInsert); sqlite3_finalize(pIter->pDelete); sqlite3_finalize(pIter->pTmpInsert); pUp = pIter->pRbuUpdate; while( pUp ){ RbuUpdateStmt *pTmp = pUp->pNext; sqlite3_finalize(pUp->pUpdate); sqlite3_free(pUp); pUp = pTmp; } pIter->pSelect = 0; pIter->pInsert = 0; pIter->pDelete = 0; pIter->pRbuUpdate = 0; pIter->pTmpInsert = 0; pIter->nCol = 0; } /* ** Clean up any resources allocated as part of the iterator object passed ** as the only argument. */ static void rbuObjIterFinalize(RbuObjIter *pIter){ rbuObjIterClearStatements(pIter); sqlite3_finalize(pIter->pTblIter); sqlite3_finalize(pIter->pIdxIter); rbuObjIterFreeCols(pIter); memset(pIter, 0, sizeof(RbuObjIter)); } /* ** Advance the iterator to the next position. ** ** If no error occurs, SQLITE_OK is returned and the iterator is left ** pointing to the next entry. Otherwise, an error code and message is ** left in the RBU handle passed as the first argument. A copy of the ** error code is returned. */ static int rbuObjIterNext(sqlite3rbu *p, RbuObjIter *pIter){ int rc = p->rc; if( rc==SQLITE_OK ){ /* Free any SQLite statements used while processing the previous object */ rbuObjIterClearStatements(pIter); if( pIter->zIdx==0 ){ rc = sqlite3_exec(p->dbMain, "DROP TRIGGER IF EXISTS temp.rbu_insert_tr;" "DROP TRIGGER IF EXISTS temp.rbu_update1_tr;" "DROP TRIGGER IF EXISTS temp.rbu_update2_tr;" "DROP TRIGGER IF EXISTS temp.rbu_delete_tr;" , 0, 0, &p->zErrmsg ); } if( rc==SQLITE_OK ){ if( pIter->bCleanup ){ rbuObjIterFreeCols(pIter); pIter->bCleanup = 0; rc = sqlite3_step(pIter->pTblIter); if( rc!=SQLITE_ROW ){ rc = resetAndCollectError(pIter->pTblIter, &p->zErrmsg); pIter->zTbl = 0; }else{ pIter->zTbl = (const char*)sqlite3_column_text(pIter->pTblIter, 0); pIter->zDataTbl = (const char*)sqlite3_column_text(pIter->pTblIter,1); rc = (pIter->zDataTbl && pIter->zTbl) ? SQLITE_OK : SQLITE_NOMEM; } }else{ if( pIter->zIdx==0 ){ sqlite3_stmt *pIdx = pIter->pIdxIter; rc = sqlite3_bind_text(pIdx, 1, pIter->zTbl, -1, SQLITE_STATIC); } if( rc==SQLITE_OK ){ rc = sqlite3_step(pIter->pIdxIter); if( rc!=SQLITE_ROW ){ rc = resetAndCollectError(pIter->pIdxIter, &p->zErrmsg); pIter->bCleanup = 1; pIter->zIdx = 0; }else{ pIter->zIdx = (const char*)sqlite3_column_text(pIter->pIdxIter, 0); pIter->iTnum = sqlite3_column_int(pIter->pIdxIter, 1); pIter->bUnique = sqlite3_column_int(pIter->pIdxIter, 2); rc = pIter->zIdx ? SQLITE_OK : SQLITE_NOMEM; } } } } } if( rc!=SQLITE_OK ){ rbuObjIterFinalize(pIter); p->rc = rc; } return rc; } /* ** The implementation of the rbu_target_name() SQL function. This function ** accepts one or two arguments. The first argument is the name of a table - ** the name of a table in the RBU database. The second, if it is present, is 1 ** for a view or 0 for a table. ** ** For a non-vacuum RBU handle, if the table name matches the pattern: ** ** data[0-9]_ ** ** where is any sequence of 1 or more characters, is returned. ** Otherwise, if the only argument does not match the above pattern, an SQL ** NULL is returned. ** ** "data_t1" -> "t1" ** "data0123_t2" -> "t2" ** "dataAB_t3" -> NULL ** ** For an rbu vacuum handle, a copy of the first argument is returned if ** the second argument is either missing or 0 (not a view). */ static void rbuTargetNameFunc( sqlite3_context *pCtx, int argc, sqlite3_value **argv ){ sqlite3rbu *p = sqlite3_user_data(pCtx); const char *zIn; assert( argc==1 || argc==2 ); zIn = (const char*)sqlite3_value_text(argv[0]); if( zIn ){ if( rbuIsVacuum(p) ){ if( argc==1 || 0==sqlite3_value_int(argv[1]) ){ sqlite3_result_text(pCtx, zIn, -1, SQLITE_STATIC); } }else{ if( strlen(zIn)>4 && memcmp("data", zIn, 4)==0 ){ int i; for(i=4; zIn[i]>='0' && zIn[i]<='9'; i++); if( zIn[i]=='_' && zIn[i+1] ){ sqlite3_result_text(pCtx, &zIn[i+1], -1, SQLITE_STATIC); } } } } } /* ** Initialize the iterator structure passed as the second argument. ** ** If no error occurs, SQLITE_OK is returned and the iterator is left ** pointing to the first entry. Otherwise, an error code and message is ** left in the RBU handle passed as the first argument. A copy of the ** error code is returned. */ static int rbuObjIterFirst(sqlite3rbu *p, RbuObjIter *pIter){ int rc; memset(pIter, 0, sizeof(RbuObjIter)); rc = prepareFreeAndCollectError(p->dbRbu, &pIter->pTblIter, &p->zErrmsg, sqlite3_mprintf( "SELECT rbu_target_name(name, type='view') AS target, name " "FROM sqlite_master " "WHERE type IN ('table', 'view') AND target IS NOT NULL " " %s " "ORDER BY name" , rbuIsVacuum(p) ? "AND rootpage!=0 AND rootpage IS NOT NULL" : "")); if( rc==SQLITE_OK ){ rc = prepareAndCollectError(p->dbMain, &pIter->pIdxIter, &p->zErrmsg, "SELECT name, rootpage, sql IS NULL OR substr(8, 6)=='UNIQUE' " " FROM main.sqlite_master " " WHERE type='index' AND tbl_name = ?" ); } pIter->bCleanup = 1; p->rc = rc; return rbuObjIterNext(p, pIter); } /* ** This is a wrapper around "sqlite3_mprintf(zFmt, ...)". If an OOM occurs, ** an error code is stored in the RBU handle passed as the first argument. ** ** If an error has already occurred (p->rc is already set to something other ** than SQLITE_OK), then this function returns NULL without modifying the ** stored error code. In this case it still calls sqlite3_free() on any ** printf() parameters associated with %z conversions. */ static char *rbuMPrintf(sqlite3rbu *p, const char *zFmt, ...){ char *zSql = 0; va_list ap; va_start(ap, zFmt); zSql = sqlite3_vmprintf(zFmt, ap); if( p->rc==SQLITE_OK ){ if( zSql==0 ) p->rc = SQLITE_NOMEM; }else{ sqlite3_free(zSql); zSql = 0; } va_end(ap); return zSql; } /* ** Argument zFmt is a sqlite3_mprintf() style format string. The trailing ** arguments are the usual subsitution values. This function performs ** the printf() style substitutions and executes the result as an SQL ** statement on the RBU handles database. ** ** If an error occurs, an error code and error message is stored in the ** RBU handle. If an error has already occurred when this function is ** called, it is a no-op. */ static int rbuMPrintfExec(sqlite3rbu *p, sqlite3 *db, const char *zFmt, ...){ va_list ap; char *zSql; va_start(ap, zFmt); zSql = sqlite3_vmprintf(zFmt, ap); if( p->rc==SQLITE_OK ){ if( zSql==0 ){ p->rc = SQLITE_NOMEM; }else{ p->rc = sqlite3_exec(db, zSql, 0, 0, &p->zErrmsg); } } sqlite3_free(zSql); va_end(ap); return p->rc; } /* ** Attempt to allocate and return a pointer to a zeroed block of nByte ** bytes. ** ** If an error (i.e. an OOM condition) occurs, return NULL and leave an ** error code in the rbu handle passed as the first argument. Or, if an ** error has already occurred when this function is called, return NULL ** immediately without attempting the allocation or modifying the stored ** error code. */ static void *rbuMalloc(sqlite3rbu *p, int nByte){ void *pRet = 0; if( p->rc==SQLITE_OK ){ assert( nByte>0 ); pRet = sqlite3_malloc64(nByte); if( pRet==0 ){ p->rc = SQLITE_NOMEM; }else{ memset(pRet, 0, nByte); } } return pRet; } /* ** Allocate and zero the pIter->azTblCol[] and abTblPk[] arrays so that ** there is room for at least nCol elements. If an OOM occurs, store an ** error code in the RBU handle passed as the first argument. */ static void rbuAllocateIterArrays(sqlite3rbu *p, RbuObjIter *pIter, int nCol){ int nByte = (2*sizeof(char*) + sizeof(int) + 3*sizeof(u8)) * nCol; char **azNew; azNew = (char**)rbuMalloc(p, nByte); if( azNew ){ pIter->azTblCol = azNew; pIter->azTblType = &azNew[nCol]; pIter->aiSrcOrder = (int*)&pIter->azTblType[nCol]; pIter->abTblPk = (u8*)&pIter->aiSrcOrder[nCol]; pIter->abNotNull = (u8*)&pIter->abTblPk[nCol]; pIter->abIndexed = (u8*)&pIter->abNotNull[nCol]; } } /* ** The first argument must be a nul-terminated string. This function ** returns a copy of the string in memory obtained from sqlite3_malloc(). ** It is the responsibility of the caller to eventually free this memory ** using sqlite3_free(). ** ** If an OOM condition is encountered when attempting to allocate memory, ** output variable (*pRc) is set to SQLITE_NOMEM before returning. Otherwise, ** if the allocation succeeds, (*pRc) is left unchanged. */ static char *rbuStrndup(const char *zStr, int *pRc){ char *zRet = 0; assert( *pRc==SQLITE_OK ); if( zStr ){ size_t nCopy = strlen(zStr) + 1; zRet = (char*)sqlite3_malloc64(nCopy); if( zRet ){ memcpy(zRet, zStr, nCopy); }else{ *pRc = SQLITE_NOMEM; } } return zRet; } /* ** Finalize the statement passed as the second argument. ** ** If the sqlite3_finalize() call indicates that an error occurs, and the ** rbu handle error code is not already set, set the error code and error ** message accordingly. */ static void rbuFinalize(sqlite3rbu *p, sqlite3_stmt *pStmt){ sqlite3 *db = sqlite3_db_handle(pStmt); int rc = sqlite3_finalize(pStmt); if( p->rc==SQLITE_OK && rc!=SQLITE_OK ){ p->rc = rc; p->zErrmsg = sqlite3_mprintf("%s", sqlite3_errmsg(db)); } } /* Determine the type of a table. ** ** peType is of type (int*), a pointer to an output parameter of type ** (int). This call sets the output parameter as follows, depending ** on the type of the table specified by parameters dbName and zTbl. ** ** RBU_PK_NOTABLE: No such table. ** RBU_PK_NONE: Table has an implicit rowid. ** RBU_PK_IPK: Table has an explicit IPK column. ** RBU_PK_EXTERNAL: Table has an external PK index. ** RBU_PK_WITHOUT_ROWID: Table is WITHOUT ROWID. ** RBU_PK_VTAB: Table is a virtual table. ** ** Argument *piPk is also of type (int*), and also points to an output ** parameter. Unless the table has an external primary key index ** (i.e. unless *peType is set to 3), then *piPk is set to zero. Or, ** if the table does have an external primary key index, then *piPk ** is set to the root page number of the primary key index before ** returning. ** ** ALGORITHM: ** ** if( no entry exists in sqlite_master ){ ** return RBU_PK_NOTABLE ** }else if( sql for the entry starts with "CREATE VIRTUAL" ){ ** return RBU_PK_VTAB ** }else if( "PRAGMA index_list()" for the table contains a "pk" index ){ ** if( the index that is the pk exists in sqlite_master ){ ** *piPK = rootpage of that index. ** return RBU_PK_EXTERNAL ** }else{ ** return RBU_PK_WITHOUT_ROWID ** } ** }else if( "PRAGMA table_info()" lists one or more "pk" columns ){ ** return RBU_PK_IPK ** }else{ ** return RBU_PK_NONE ** } */ static void rbuTableType( sqlite3rbu *p, const char *zTab, int *peType, int *piTnum, int *piPk ){ /* ** 0) SELECT count(*) FROM sqlite_master where name=%Q AND IsVirtual(%Q) ** 1) PRAGMA index_list = ? ** 2) SELECT count(*) FROM sqlite_master where name=%Q ** 3) PRAGMA table_info = ? */ sqlite3_stmt *aStmt[4] = {0, 0, 0, 0}; *peType = RBU_PK_NOTABLE; *piPk = 0; assert( p->rc==SQLITE_OK ); p->rc = prepareFreeAndCollectError(p->dbMain, &aStmt[0], &p->zErrmsg, sqlite3_mprintf( "SELECT (sql LIKE 'create virtual%%'), rootpage" " FROM sqlite_master" " WHERE name=%Q", zTab )); if( p->rc!=SQLITE_OK || sqlite3_step(aStmt[0])!=SQLITE_ROW ){ /* Either an error, or no such table. */ goto rbuTableType_end; } if( sqlite3_column_int(aStmt[0], 0) ){ *peType = RBU_PK_VTAB; /* virtual table */ goto rbuTableType_end; } *piTnum = sqlite3_column_int(aStmt[0], 1); p->rc = prepareFreeAndCollectError(p->dbMain, &aStmt[1], &p->zErrmsg, sqlite3_mprintf("PRAGMA index_list=%Q",zTab) ); if( p->rc ) goto rbuTableType_end; while( sqlite3_step(aStmt[1])==SQLITE_ROW ){ const u8 *zOrig = sqlite3_column_text(aStmt[1], 3); const u8 *zIdx = sqlite3_column_text(aStmt[1], 1); if( zOrig && zIdx && zOrig[0]=='p' ){ p->rc = prepareFreeAndCollectError(p->dbMain, &aStmt[2], &p->zErrmsg, sqlite3_mprintf( "SELECT rootpage FROM sqlite_master WHERE name = %Q", zIdx )); if( p->rc==SQLITE_OK ){ if( sqlite3_step(aStmt[2])==SQLITE_ROW ){ *piPk = sqlite3_column_int(aStmt[2], 0); *peType = RBU_PK_EXTERNAL; }else{ *peType = RBU_PK_WITHOUT_ROWID; } } goto rbuTableType_end; } } p->rc = prepareFreeAndCollectError(p->dbMain, &aStmt[3], &p->zErrmsg, sqlite3_mprintf("PRAGMA table_info=%Q",zTab) ); if( p->rc==SQLITE_OK ){ while( sqlite3_step(aStmt[3])==SQLITE_ROW ){ if( sqlite3_column_int(aStmt[3],5)>0 ){ *peType = RBU_PK_IPK; /* explicit IPK column */ goto rbuTableType_end; } } *peType = RBU_PK_NONE; } rbuTableType_end: { unsigned int i; for(i=0; iabIndexed[] array. */ static void rbuObjIterCacheIndexedCols(sqlite3rbu *p, RbuObjIter *pIter){ sqlite3_stmt *pList = 0; int bIndex = 0; if( p->rc==SQLITE_OK ){ memcpy(pIter->abIndexed, pIter->abTblPk, sizeof(u8)*pIter->nTblCol); p->rc = prepareFreeAndCollectError(p->dbMain, &pList, &p->zErrmsg, sqlite3_mprintf("PRAGMA main.index_list = %Q", pIter->zTbl) ); } pIter->nIndex = 0; while( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pList) ){ const char *zIdx = (const char*)sqlite3_column_text(pList, 1); sqlite3_stmt *pXInfo = 0; if( zIdx==0 ) break; p->rc = prepareFreeAndCollectError(p->dbMain, &pXInfo, &p->zErrmsg, sqlite3_mprintf("PRAGMA main.index_xinfo = %Q", zIdx) ); while( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pXInfo) ){ int iCid = sqlite3_column_int(pXInfo, 1); if( iCid>=0 ) pIter->abIndexed[iCid] = 1; } rbuFinalize(p, pXInfo); bIndex = 1; pIter->nIndex++; } if( pIter->eType==RBU_PK_WITHOUT_ROWID ){ /* "PRAGMA index_list" includes the main PK b-tree */ pIter->nIndex--; } rbuFinalize(p, pList); if( bIndex==0 ) pIter->abIndexed = 0; } /* ** If they are not already populated, populate the pIter->azTblCol[], ** pIter->abTblPk[], pIter->nTblCol and pIter->bRowid variables according to ** the table (not index) that the iterator currently points to. ** ** Return SQLITE_OK if successful, or an SQLite error code otherwise. If ** an error does occur, an error code and error message are also left in ** the RBU handle. */ static int rbuObjIterCacheTableInfo(sqlite3rbu *p, RbuObjIter *pIter){ if( pIter->azTblCol==0 ){ sqlite3_stmt *pStmt = 0; int nCol = 0; int i; /* for() loop iterator variable */ int bRbuRowid = 0; /* If input table has column "rbu_rowid" */ int iOrder = 0; int iTnum = 0; /* Figure out the type of table this step will deal with. */ assert( pIter->eType==0 ); rbuTableType(p, pIter->zTbl, &pIter->eType, &iTnum, &pIter->iPkTnum); if( p->rc==SQLITE_OK && pIter->eType==RBU_PK_NOTABLE ){ p->rc = SQLITE_ERROR; p->zErrmsg = sqlite3_mprintf("no such table: %s", pIter->zTbl); } if( p->rc ) return p->rc; if( pIter->zIdx==0 ) pIter->iTnum = iTnum; assert( pIter->eType==RBU_PK_NONE || pIter->eType==RBU_PK_IPK || pIter->eType==RBU_PK_EXTERNAL || pIter->eType==RBU_PK_WITHOUT_ROWID || pIter->eType==RBU_PK_VTAB ); /* Populate the azTblCol[] and nTblCol variables based on the columns ** of the input table. Ignore any input table columns that begin with ** "rbu_". */ p->rc = prepareFreeAndCollectError(p->dbRbu, &pStmt, &p->zErrmsg, sqlite3_mprintf("SELECT * FROM '%q'", pIter->zDataTbl) ); if( p->rc==SQLITE_OK ){ nCol = sqlite3_column_count(pStmt); rbuAllocateIterArrays(p, pIter, nCol); } for(i=0; p->rc==SQLITE_OK && irc); pIter->aiSrcOrder[pIter->nTblCol] = pIter->nTblCol; pIter->azTblCol[pIter->nTblCol++] = zCopy; } else if( 0==sqlite3_stricmp("rbu_rowid", zName) ){ bRbuRowid = 1; } } sqlite3_finalize(pStmt); pStmt = 0; if( p->rc==SQLITE_OK && rbuIsVacuum(p)==0 && bRbuRowid!=(pIter->eType==RBU_PK_VTAB || pIter->eType==RBU_PK_NONE) ){ p->rc = SQLITE_ERROR; p->zErrmsg = sqlite3_mprintf( "table %q %s rbu_rowid column", pIter->zDataTbl, (bRbuRowid ? "may not have" : "requires") ); } /* Check that all non-HIDDEN columns in the destination table are also ** present in the input table. Populate the abTblPk[], azTblType[] and ** aiTblOrder[] arrays at the same time. */ if( p->rc==SQLITE_OK ){ p->rc = prepareFreeAndCollectError(p->dbMain, &pStmt, &p->zErrmsg, sqlite3_mprintf("PRAGMA table_info(%Q)", pIter->zTbl) ); } while( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){ const char *zName = (const char*)sqlite3_column_text(pStmt, 1); if( zName==0 ) break; /* An OOM - finalize() below returns S_NOMEM */ for(i=iOrder; inTblCol; i++){ if( 0==strcmp(zName, pIter->azTblCol[i]) ) break; } if( i==pIter->nTblCol ){ p->rc = SQLITE_ERROR; p->zErrmsg = sqlite3_mprintf("column missing from %q: %s", pIter->zDataTbl, zName ); }else{ int iPk = sqlite3_column_int(pStmt, 5); int bNotNull = sqlite3_column_int(pStmt, 3); const char *zType = (const char*)sqlite3_column_text(pStmt, 2); if( i!=iOrder ){ SWAP(int, pIter->aiSrcOrder[i], pIter->aiSrcOrder[iOrder]); SWAP(char*, pIter->azTblCol[i], pIter->azTblCol[iOrder]); } pIter->azTblType[iOrder] = rbuStrndup(zType, &p->rc); pIter->abTblPk[iOrder] = (iPk!=0); pIter->abNotNull[iOrder] = (u8)bNotNull || (iPk!=0); iOrder++; } } rbuFinalize(p, pStmt); rbuObjIterCacheIndexedCols(p, pIter); assert( pIter->eType!=RBU_PK_VTAB || pIter->abIndexed==0 ); assert( pIter->eType!=RBU_PK_VTAB || pIter->nIndex==0 ); } return p->rc; } /* ** This function constructs and returns a pointer to a nul-terminated ** string containing some SQL clause or list based on one or more of the ** column names currently stored in the pIter->azTblCol[] array. */ static char *rbuObjIterGetCollist( sqlite3rbu *p, /* RBU object */ RbuObjIter *pIter /* Object iterator for column names */ ){ char *zList = 0; const char *zSep = ""; int i; for(i=0; inTblCol; i++){ const char *z = pIter->azTblCol[i]; zList = rbuMPrintf(p, "%z%s\"%w\"", zList, zSep, z); zSep = ", "; } return zList; } /* ** This function is used to create a SELECT list (the list of SQL ** expressions that follows a SELECT keyword) for a SELECT statement ** used to read from an data_xxx or rbu_tmp_xxx table while updating the ** index object currently indicated by the iterator object passed as the ** second argument. A "PRAGMA index_xinfo = " statement is used ** to obtain the required information. ** ** If the index is of the following form: ** ** CREATE INDEX i1 ON t1(c, b COLLATE nocase); ** ** and "t1" is a table with an explicit INTEGER PRIMARY KEY column ** "ipk", the returned string is: ** ** "`c` COLLATE 'BINARY', `b` COLLATE 'NOCASE', `ipk` COLLATE 'BINARY'" ** ** As well as the returned string, three other malloc'd strings are ** returned via output parameters. As follows: ** ** pzImposterCols: ... ** pzImposterPk: ... ** pzWhere: ... */ static char *rbuObjIterGetIndexCols( sqlite3rbu *p, /* RBU object */ RbuObjIter *pIter, /* Object iterator for column names */ char **pzImposterCols, /* OUT: Columns for imposter table */ char **pzImposterPk, /* OUT: Imposter PK clause */ char **pzWhere, /* OUT: WHERE clause */ int *pnBind /* OUT: Trbul number of columns */ ){ int rc = p->rc; /* Error code */ int rc2; /* sqlite3_finalize() return code */ char *zRet = 0; /* String to return */ char *zImpCols = 0; /* String to return via *pzImposterCols */ char *zImpPK = 0; /* String to return via *pzImposterPK */ char *zWhere = 0; /* String to return via *pzWhere */ int nBind = 0; /* Value to return via *pnBind */ const char *zCom = ""; /* Set to ", " later on */ const char *zAnd = ""; /* Set to " AND " later on */ sqlite3_stmt *pXInfo = 0; /* PRAGMA index_xinfo = ? */ if( rc==SQLITE_OK ){ assert( p->zErrmsg==0 ); rc = prepareFreeAndCollectError(p->dbMain, &pXInfo, &p->zErrmsg, sqlite3_mprintf("PRAGMA main.index_xinfo = %Q", pIter->zIdx) ); } while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pXInfo) ){ int iCid = sqlite3_column_int(pXInfo, 1); int bDesc = sqlite3_column_int(pXInfo, 3); const char *zCollate = (const char*)sqlite3_column_text(pXInfo, 4); const char *zCol; const char *zType; if( iCid<0 ){ /* An integer primary key. If the table has an explicit IPK, use ** its name. Otherwise, use "rbu_rowid". */ if( pIter->eType==RBU_PK_IPK ){ int i; for(i=0; pIter->abTblPk[i]==0; i++); assert( inTblCol ); zCol = pIter->azTblCol[i]; }else if( rbuIsVacuum(p) ){ zCol = "_rowid_"; }else{ zCol = "rbu_rowid"; } zType = "INTEGER"; }else{ zCol = pIter->azTblCol[iCid]; zType = pIter->azTblType[iCid]; } zRet = sqlite3_mprintf("%z%s\"%w\" COLLATE %Q", zRet, zCom, zCol, zCollate); if( pIter->bUnique==0 || sqlite3_column_int(pXInfo, 5) ){ const char *zOrder = (bDesc ? " DESC" : ""); zImpPK = sqlite3_mprintf("%z%s\"rbu_imp_%d%w\"%s", zImpPK, zCom, nBind, zCol, zOrder ); } zImpCols = sqlite3_mprintf("%z%s\"rbu_imp_%d%w\" %s COLLATE %Q", zImpCols, zCom, nBind, zCol, zType, zCollate ); zWhere = sqlite3_mprintf( "%z%s\"rbu_imp_%d%w\" IS ?", zWhere, zAnd, nBind, zCol ); if( zRet==0 || zImpPK==0 || zImpCols==0 || zWhere==0 ) rc = SQLITE_NOMEM; zCom = ", "; zAnd = " AND "; nBind++; } rc2 = sqlite3_finalize(pXInfo); if( rc==SQLITE_OK ) rc = rc2; if( rc!=SQLITE_OK ){ sqlite3_free(zRet); sqlite3_free(zImpCols); sqlite3_free(zImpPK); sqlite3_free(zWhere); zRet = 0; zImpCols = 0; zImpPK = 0; zWhere = 0; p->rc = rc; } *pzImposterCols = zImpCols; *pzImposterPk = zImpPK; *pzWhere = zWhere; *pnBind = nBind; return zRet; } /* ** Assuming the current table columns are "a", "b" and "c", and the zObj ** paramter is passed "old", return a string of the form: ** ** "old.a, old.b, old.b" ** ** With the column names escaped. ** ** For tables with implicit rowids - RBU_PK_EXTERNAL and RBU_PK_NONE, append ** the text ", old._rowid_" to the returned value. */ static char *rbuObjIterGetOldlist( sqlite3rbu *p, RbuObjIter *pIter, const char *zObj ){ char *zList = 0; if( p->rc==SQLITE_OK && pIter->abIndexed ){ const char *zS = ""; int i; for(i=0; inTblCol; i++){ if( pIter->abIndexed[i] ){ const char *zCol = pIter->azTblCol[i]; zList = sqlite3_mprintf("%z%s%s.\"%w\"", zList, zS, zObj, zCol); }else{ zList = sqlite3_mprintf("%z%sNULL", zList, zS); } zS = ", "; if( zList==0 ){ p->rc = SQLITE_NOMEM; break; } } /* For a table with implicit rowids, append "old._rowid_" to the list. */ if( pIter->eType==RBU_PK_EXTERNAL || pIter->eType==RBU_PK_NONE ){ zList = rbuMPrintf(p, "%z, %s._rowid_", zList, zObj); } } return zList; } /* ** Return an expression that can be used in a WHERE clause to match the ** primary key of the current table. For example, if the table is: ** ** CREATE TABLE t1(a, b, c, PRIMARY KEY(b, c)); ** ** Return the string: ** ** "b = ?1 AND c = ?2" */ static char *rbuObjIterGetWhere( sqlite3rbu *p, RbuObjIter *pIter ){ char *zList = 0; if( pIter->eType==RBU_PK_VTAB || pIter->eType==RBU_PK_NONE ){ zList = rbuMPrintf(p, "_rowid_ = ?%d", pIter->nTblCol+1); }else if( pIter->eType==RBU_PK_EXTERNAL ){ const char *zSep = ""; int i; for(i=0; inTblCol; i++){ if( pIter->abTblPk[i] ){ zList = rbuMPrintf(p, "%z%sc%d=?%d", zList, zSep, i, i+1); zSep = " AND "; } } zList = rbuMPrintf(p, "_rowid_ = (SELECT id FROM rbu_imposter2 WHERE %z)", zList ); }else{ const char *zSep = ""; int i; for(i=0; inTblCol; i++){ if( pIter->abTblPk[i] ){ const char *zCol = pIter->azTblCol[i]; zList = rbuMPrintf(p, "%z%s\"%w\"=?%d", zList, zSep, zCol, i+1); zSep = " AND "; } } } return zList; } /* ** The SELECT statement iterating through the keys for the current object ** (p->objiter.pSelect) currently points to a valid row. However, there ** is something wrong with the rbu_control value in the rbu_control value ** stored in the (p->nCol+1)'th column. Set the error code and error message ** of the RBU handle to something reflecting this. */ static void rbuBadControlError(sqlite3rbu *p){ p->rc = SQLITE_ERROR; p->zErrmsg = sqlite3_mprintf("invalid rbu_control value"); } /* ** Return a nul-terminated string containing the comma separated list of ** assignments that should be included following the "SET" keyword of ** an UPDATE statement used to update the table object that the iterator ** passed as the second argument currently points to if the rbu_control ** column of the data_xxx table entry is set to zMask. ** ** The memory for the returned string is obtained from sqlite3_malloc(). ** It is the responsibility of the caller to eventually free it using ** sqlite3_free(). ** ** If an OOM error is encountered when allocating space for the new ** string, an error code is left in the rbu handle passed as the first ** argument and NULL is returned. Or, if an error has already occurred ** when this function is called, NULL is returned immediately, without ** attempting the allocation or modifying the stored error code. */ static char *rbuObjIterGetSetlist( sqlite3rbu *p, RbuObjIter *pIter, const char *zMask ){ char *zList = 0; if( p->rc==SQLITE_OK ){ int i; if( (int)strlen(zMask)!=pIter->nTblCol ){ rbuBadControlError(p); }else{ const char *zSep = ""; for(i=0; inTblCol; i++){ char c = zMask[pIter->aiSrcOrder[i]]; if( c=='x' ){ zList = rbuMPrintf(p, "%z%s\"%w\"=?%d", zList, zSep, pIter->azTblCol[i], i+1 ); zSep = ", "; } else if( c=='d' ){ zList = rbuMPrintf(p, "%z%s\"%w\"=rbu_delta(\"%w\", ?%d)", zList, zSep, pIter->azTblCol[i], pIter->azTblCol[i], i+1 ); zSep = ", "; } else if( c=='f' ){ zList = rbuMPrintf(p, "%z%s\"%w\"=rbu_fossil_delta(\"%w\", ?%d)", zList, zSep, pIter->azTblCol[i], pIter->azTblCol[i], i+1 ); zSep = ", "; } } } } return zList; } /* ** Return a nul-terminated string consisting of nByte comma separated ** "?" expressions. For example, if nByte is 3, return a pointer to ** a buffer containing the string "?,?,?". ** ** The memory for the returned string is obtained from sqlite3_malloc(). ** It is the responsibility of the caller to eventually free it using ** sqlite3_free(). ** ** If an OOM error is encountered when allocating space for the new ** string, an error code is left in the rbu handle passed as the first ** argument and NULL is returned. Or, if an error has already occurred ** when this function is called, NULL is returned immediately, without ** attempting the allocation or modifying the stored error code. */ static char *rbuObjIterGetBindlist(sqlite3rbu *p, int nBind){ char *zRet = 0; int nByte = nBind*2 + 1; zRet = (char*)rbuMalloc(p, nByte); if( zRet ){ int i; for(i=0; izIdx==0 ); if( p->rc==SQLITE_OK ){ const char *zSep = "PRIMARY KEY("; sqlite3_stmt *pXList = 0; /* PRAGMA index_list = (pIter->zTbl) */ sqlite3_stmt *pXInfo = 0; /* PRAGMA index_xinfo = */ p->rc = prepareFreeAndCollectError(p->dbMain, &pXList, &p->zErrmsg, sqlite3_mprintf("PRAGMA main.index_list = %Q", pIter->zTbl) ); while( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pXList) ){ const char *zOrig = (const char*)sqlite3_column_text(pXList,3); if( zOrig && strcmp(zOrig, "pk")==0 ){ const char *zIdx = (const char*)sqlite3_column_text(pXList,1); if( zIdx ){ p->rc = prepareFreeAndCollectError(p->dbMain, &pXInfo, &p->zErrmsg, sqlite3_mprintf("PRAGMA main.index_xinfo = %Q", zIdx) ); } break; } } rbuFinalize(p, pXList); while( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pXInfo) ){ if( sqlite3_column_int(pXInfo, 5) ){ /* int iCid = sqlite3_column_int(pXInfo, 0); */ const char *zCol = (const char*)sqlite3_column_text(pXInfo, 2); const char *zDesc = sqlite3_column_int(pXInfo, 3) ? " DESC" : ""; z = rbuMPrintf(p, "%z%s\"%w\"%s", z, zSep, zCol, zDesc); zSep = ", "; } } z = rbuMPrintf(p, "%z)", z); rbuFinalize(p, pXInfo); } return z; } /* ** This function creates the second imposter table used when writing to ** a table b-tree where the table has an external primary key. If the ** iterator passed as the second argument does not currently point to ** a table (not index) with an external primary key, this function is a ** no-op. ** ** Assuming the iterator does point to a table with an external PK, this ** function creates a WITHOUT ROWID imposter table named "rbu_imposter2" ** used to access that PK index. For example, if the target table is ** declared as follows: ** ** CREATE TABLE t1(a, b TEXT, c REAL, PRIMARY KEY(b, c)); ** ** then the imposter table schema is: ** ** CREATE TABLE rbu_imposter2(c1 TEXT, c2 REAL, id INTEGER) WITHOUT ROWID; ** */ static void rbuCreateImposterTable2(sqlite3rbu *p, RbuObjIter *pIter){ if( p->rc==SQLITE_OK && pIter->eType==RBU_PK_EXTERNAL ){ int tnum = pIter->iPkTnum; /* Root page of PK index */ sqlite3_stmt *pQuery = 0; /* SELECT name ... WHERE rootpage = $tnum */ const char *zIdx = 0; /* Name of PK index */ sqlite3_stmt *pXInfo = 0; /* PRAGMA main.index_xinfo = $zIdx */ const char *zComma = ""; char *zCols = 0; /* Used to build up list of table cols */ char *zPk = 0; /* Used to build up table PK declaration */ /* Figure out the name of the primary key index for the current table. ** This is needed for the argument to "PRAGMA index_xinfo". Set ** zIdx to point to a nul-terminated string containing this name. */ p->rc = prepareAndCollectError(p->dbMain, &pQuery, &p->zErrmsg, "SELECT name FROM sqlite_master WHERE rootpage = ?" ); if( p->rc==SQLITE_OK ){ sqlite3_bind_int(pQuery, 1, tnum); if( SQLITE_ROW==sqlite3_step(pQuery) ){ zIdx = (const char*)sqlite3_column_text(pQuery, 0); } } if( zIdx ){ p->rc = prepareFreeAndCollectError(p->dbMain, &pXInfo, &p->zErrmsg, sqlite3_mprintf("PRAGMA main.index_xinfo = %Q", zIdx) ); } rbuFinalize(p, pQuery); while( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pXInfo) ){ int bKey = sqlite3_column_int(pXInfo, 5); if( bKey ){ int iCid = sqlite3_column_int(pXInfo, 1); int bDesc = sqlite3_column_int(pXInfo, 3); const char *zCollate = (const char*)sqlite3_column_text(pXInfo, 4); zCols = rbuMPrintf(p, "%z%sc%d %s COLLATE %s", zCols, zComma, iCid, pIter->azTblType[iCid], zCollate ); zPk = rbuMPrintf(p, "%z%sc%d%s", zPk, zComma, iCid, bDesc?" DESC":""); zComma = ", "; } } zCols = rbuMPrintf(p, "%z, id INTEGER", zCols); rbuFinalize(p, pXInfo); sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 1, tnum); rbuMPrintfExec(p, p->dbMain, "CREATE TABLE rbu_imposter2(%z, PRIMARY KEY(%z)) WITHOUT ROWID", zCols, zPk ); sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 0, 0); } } /* ** If an error has already occurred when this function is called, it ** immediately returns zero (without doing any work). Or, if an error ** occurs during the execution of this function, it sets the error code ** in the sqlite3rbu object indicated by the first argument and returns ** zero. ** ** The iterator passed as the second argument is guaranteed to point to ** a table (not an index) when this function is called. This function ** attempts to create any imposter table required to write to the main ** table b-tree of the table before returning. Non-zero is returned if ** an imposter table are created, or zero otherwise. ** ** An imposter table is required in all cases except RBU_PK_VTAB. Only ** virtual tables are written to directly. The imposter table has the ** same schema as the actual target table (less any UNIQUE constraints). ** More precisely, the "same schema" means the same columns, types, ** collation sequences. For tables that do not have an external PRIMARY ** KEY, it also means the same PRIMARY KEY declaration. */ static void rbuCreateImposterTable(sqlite3rbu *p, RbuObjIter *pIter){ if( p->rc==SQLITE_OK && pIter->eType!=RBU_PK_VTAB ){ int tnum = pIter->iTnum; const char *zComma = ""; char *zSql = 0; int iCol; sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 0, 1); for(iCol=0; p->rc==SQLITE_OK && iColnTblCol; iCol++){ const char *zPk = ""; const char *zCol = pIter->azTblCol[iCol]; const char *zColl = 0; p->rc = sqlite3_table_column_metadata( p->dbMain, "main", pIter->zTbl, zCol, 0, &zColl, 0, 0, 0 ); if( pIter->eType==RBU_PK_IPK && pIter->abTblPk[iCol] ){ /* If the target table column is an "INTEGER PRIMARY KEY", add ** "PRIMARY KEY" to the imposter table column declaration. */ zPk = "PRIMARY KEY "; } zSql = rbuMPrintf(p, "%z%s\"%w\" %s %sCOLLATE %s%s", zSql, zComma, zCol, pIter->azTblType[iCol], zPk, zColl, (pIter->abNotNull[iCol] ? " NOT NULL" : "") ); zComma = ", "; } if( pIter->eType==RBU_PK_WITHOUT_ROWID ){ char *zPk = rbuWithoutRowidPK(p, pIter); if( zPk ){ zSql = rbuMPrintf(p, "%z, %z", zSql, zPk); } } sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 1, tnum); rbuMPrintfExec(p, p->dbMain, "CREATE TABLE \"rbu_imp_%w\"(%z)%s", pIter->zTbl, zSql, (pIter->eType==RBU_PK_WITHOUT_ROWID ? " WITHOUT ROWID" : "") ); sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 0, 0); } } /* ** Prepare a statement used to insert rows into the "rbu_tmp_xxx" table. ** Specifically a statement of the form: ** ** INSERT INTO rbu_tmp_xxx VALUES(?, ?, ? ...); ** ** The number of bound variables is equal to the number of columns in ** the target table, plus one (for the rbu_control column), plus one more ** (for the rbu_rowid column) if the target table is an implicit IPK or ** virtual table. */ static void rbuObjIterPrepareTmpInsert( sqlite3rbu *p, RbuObjIter *pIter, const char *zCollist, const char *zRbuRowid ){ int bRbuRowid = (pIter->eType==RBU_PK_EXTERNAL || pIter->eType==RBU_PK_NONE); char *zBind = rbuObjIterGetBindlist(p, pIter->nTblCol + 1 + bRbuRowid); if( zBind ){ assert( pIter->pTmpInsert==0 ); p->rc = prepareFreeAndCollectError( p->dbRbu, &pIter->pTmpInsert, &p->zErrmsg, sqlite3_mprintf( "INSERT INTO %s.'rbu_tmp_%q'(rbu_control,%s%s) VALUES(%z)", p->zStateDb, pIter->zDataTbl, zCollist, zRbuRowid, zBind )); } } static void rbuTmpInsertFunc( sqlite3_context *pCtx, int nVal, sqlite3_value **apVal ){ sqlite3rbu *p = sqlite3_user_data(pCtx); int rc = SQLITE_OK; int i; assert( sqlite3_value_int(apVal[0])!=0 || p->objiter.eType==RBU_PK_EXTERNAL || p->objiter.eType==RBU_PK_NONE ); if( sqlite3_value_int(apVal[0])!=0 ){ p->nPhaseOneStep += p->objiter.nIndex; } for(i=0; rc==SQLITE_OK && iobjiter.pTmpInsert, i+1, apVal[i]); } if( rc==SQLITE_OK ){ sqlite3_step(p->objiter.pTmpInsert); rc = sqlite3_reset(p->objiter.pTmpInsert); } if( rc!=SQLITE_OK ){ sqlite3_result_error_code(pCtx, rc); } } /* ** Ensure that the SQLite statement handles required to update the ** target database object currently indicated by the iterator passed ** as the second argument are available. */ static int rbuObjIterPrepareAll( sqlite3rbu *p, RbuObjIter *pIter, int nOffset /* Add "LIMIT -1 OFFSET $nOffset" to SELECT */ ){ assert( pIter->bCleanup==0 ); if( pIter->pSelect==0 && rbuObjIterCacheTableInfo(p, pIter)==SQLITE_OK ){ const int tnum = pIter->iTnum; char *zCollist = 0; /* List of indexed columns */ char **pz = &p->zErrmsg; const char *zIdx = pIter->zIdx; char *zLimit = 0; if( nOffset ){ zLimit = sqlite3_mprintf(" LIMIT -1 OFFSET %d", nOffset); if( !zLimit ) p->rc = SQLITE_NOMEM; } if( zIdx ){ const char *zTbl = pIter->zTbl; char *zImposterCols = 0; /* Columns for imposter table */ char *zImposterPK = 0; /* Primary key declaration for imposter */ char *zWhere = 0; /* WHERE clause on PK columns */ char *zBind = 0; int nBind = 0; assert( pIter->eType!=RBU_PK_VTAB ); zCollist = rbuObjIterGetIndexCols( p, pIter, &zImposterCols, &zImposterPK, &zWhere, &nBind ); zBind = rbuObjIterGetBindlist(p, nBind); /* Create the imposter table used to write to this index. */ sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 0, 1); sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 1,tnum); rbuMPrintfExec(p, p->dbMain, "CREATE TABLE \"rbu_imp_%w\"( %s, PRIMARY KEY( %s ) ) WITHOUT ROWID", zTbl, zImposterCols, zImposterPK ); sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 0, 0); /* Create the statement to insert index entries */ pIter->nCol = nBind; if( p->rc==SQLITE_OK ){ p->rc = prepareFreeAndCollectError( p->dbMain, &pIter->pInsert, &p->zErrmsg, sqlite3_mprintf("INSERT INTO \"rbu_imp_%w\" VALUES(%s)", zTbl, zBind) ); } /* And to delete index entries */ if( rbuIsVacuum(p)==0 && p->rc==SQLITE_OK ){ p->rc = prepareFreeAndCollectError( p->dbMain, &pIter->pDelete, &p->zErrmsg, sqlite3_mprintf("DELETE FROM \"rbu_imp_%w\" WHERE %s", zTbl, zWhere) ); } /* Create the SELECT statement to read keys in sorted order */ if( p->rc==SQLITE_OK ){ char *zSql; if( rbuIsVacuum(p) ){ zSql = sqlite3_mprintf( "SELECT %s, 0 AS rbu_control FROM '%q' ORDER BY %s%s", zCollist, pIter->zDataTbl, zCollist, zLimit ); }else if( pIter->eType==RBU_PK_EXTERNAL || pIter->eType==RBU_PK_NONE ){ zSql = sqlite3_mprintf( "SELECT %s, rbu_control FROM %s.'rbu_tmp_%q' ORDER BY %s%s", zCollist, p->zStateDb, pIter->zDataTbl, zCollist, zLimit ); }else{ zSql = sqlite3_mprintf( "SELECT %s, rbu_control FROM %s.'rbu_tmp_%q' " "UNION ALL " "SELECT %s, rbu_control FROM '%q' " "WHERE typeof(rbu_control)='integer' AND rbu_control!=1 " "ORDER BY %s%s", zCollist, p->zStateDb, pIter->zDataTbl, zCollist, pIter->zDataTbl, zCollist, zLimit ); } p->rc = prepareFreeAndCollectError(p->dbRbu, &pIter->pSelect, pz, zSql); } sqlite3_free(zImposterCols); sqlite3_free(zImposterPK); sqlite3_free(zWhere); sqlite3_free(zBind); }else{ int bRbuRowid = (pIter->eType==RBU_PK_VTAB) ||(pIter->eType==RBU_PK_NONE) ||(pIter->eType==RBU_PK_EXTERNAL && rbuIsVacuum(p)); const char *zTbl = pIter->zTbl; /* Table this step applies to */ const char *zWrite; /* Imposter table name */ char *zBindings = rbuObjIterGetBindlist(p, pIter->nTblCol + bRbuRowid); char *zWhere = rbuObjIterGetWhere(p, pIter); char *zOldlist = rbuObjIterGetOldlist(p, pIter, "old"); char *zNewlist = rbuObjIterGetOldlist(p, pIter, "new"); zCollist = rbuObjIterGetCollist(p, pIter); pIter->nCol = pIter->nTblCol; /* Create the imposter table or tables (if required). */ rbuCreateImposterTable(p, pIter); rbuCreateImposterTable2(p, pIter); zWrite = (pIter->eType==RBU_PK_VTAB ? "" : "rbu_imp_"); /* Create the INSERT statement to write to the target PK b-tree */ if( p->rc==SQLITE_OK ){ p->rc = prepareFreeAndCollectError(p->dbMain, &pIter->pInsert, pz, sqlite3_mprintf( "INSERT INTO \"%s%w\"(%s%s) VALUES(%s)", zWrite, zTbl, zCollist, (bRbuRowid ? ", _rowid_" : ""), zBindings ) ); } /* Create the DELETE statement to write to the target PK b-tree. ** Because it only performs INSERT operations, this is not required for ** an rbu vacuum handle. */ if( rbuIsVacuum(p)==0 && p->rc==SQLITE_OK ){ p->rc = prepareFreeAndCollectError(p->dbMain, &pIter->pDelete, pz, sqlite3_mprintf( "DELETE FROM \"%s%w\" WHERE %s", zWrite, zTbl, zWhere ) ); } if( rbuIsVacuum(p)==0 && pIter->abIndexed ){ const char *zRbuRowid = ""; if( pIter->eType==RBU_PK_EXTERNAL || pIter->eType==RBU_PK_NONE ){ zRbuRowid = ", rbu_rowid"; } /* Create the rbu_tmp_xxx table and the triggers to populate it. */ rbuMPrintfExec(p, p->dbRbu, "CREATE TABLE IF NOT EXISTS %s.'rbu_tmp_%q' AS " "SELECT *%s FROM '%q' WHERE 0;" , p->zStateDb, pIter->zDataTbl , (pIter->eType==RBU_PK_EXTERNAL ? ", 0 AS rbu_rowid" : "") , pIter->zDataTbl ); rbuMPrintfExec(p, p->dbMain, "CREATE TEMP TRIGGER rbu_delete_tr BEFORE DELETE ON \"%s%w\" " "BEGIN " " SELECT rbu_tmp_insert(3, %s);" "END;" "CREATE TEMP TRIGGER rbu_update1_tr BEFORE UPDATE ON \"%s%w\" " "BEGIN " " SELECT rbu_tmp_insert(3, %s);" "END;" "CREATE TEMP TRIGGER rbu_update2_tr AFTER UPDATE ON \"%s%w\" " "BEGIN " " SELECT rbu_tmp_insert(4, %s);" "END;", zWrite, zTbl, zOldlist, zWrite, zTbl, zOldlist, zWrite, zTbl, zNewlist ); if( pIter->eType==RBU_PK_EXTERNAL || pIter->eType==RBU_PK_NONE ){ rbuMPrintfExec(p, p->dbMain, "CREATE TEMP TRIGGER rbu_insert_tr AFTER INSERT ON \"%s%w\" " "BEGIN " " SELECT rbu_tmp_insert(0, %s);" "END;", zWrite, zTbl, zNewlist ); } rbuObjIterPrepareTmpInsert(p, pIter, zCollist, zRbuRowid); } /* Create the SELECT statement to read keys from data_xxx */ if( p->rc==SQLITE_OK ){ const char *zRbuRowid = ""; if( bRbuRowid ){ zRbuRowid = rbuIsVacuum(p) ? ",_rowid_ " : ",rbu_rowid"; } p->rc = prepareFreeAndCollectError(p->dbRbu, &pIter->pSelect, pz, sqlite3_mprintf( "SELECT %s,%s rbu_control%s FROM '%q'%s", zCollist, (rbuIsVacuum(p) ? "0 AS " : ""), zRbuRowid, pIter->zDataTbl, zLimit ) ); } sqlite3_free(zWhere); sqlite3_free(zOldlist); sqlite3_free(zNewlist); sqlite3_free(zBindings); } sqlite3_free(zCollist); sqlite3_free(zLimit); } return p->rc; } /* ** Set output variable *ppStmt to point to an UPDATE statement that may ** be used to update the imposter table for the main table b-tree of the ** table object that pIter currently points to, assuming that the ** rbu_control column of the data_xyz table contains zMask. ** ** If the zMask string does not specify any columns to update, then this ** is not an error. Output variable *ppStmt is set to NULL in this case. */ static int rbuGetUpdateStmt( sqlite3rbu *p, /* RBU handle */ RbuObjIter *pIter, /* Object iterator */ const char *zMask, /* rbu_control value ('x.x.') */ sqlite3_stmt **ppStmt /* OUT: UPDATE statement handle */ ){ RbuUpdateStmt **pp; RbuUpdateStmt *pUp = 0; int nUp = 0; /* In case an error occurs */ *ppStmt = 0; /* Search for an existing statement. If one is found, shift it to the front ** of the LRU queue and return immediately. Otherwise, leave nUp pointing ** to the number of statements currently in the cache and pUp to the ** last object in the list. */ for(pp=&pIter->pRbuUpdate; *pp; pp=&((*pp)->pNext)){ pUp = *pp; if( strcmp(pUp->zMask, zMask)==0 ){ *pp = pUp->pNext; pUp->pNext = pIter->pRbuUpdate; pIter->pRbuUpdate = pUp; *ppStmt = pUp->pUpdate; return SQLITE_OK; } nUp++; } assert( pUp==0 || pUp->pNext==0 ); if( nUp>=SQLITE_RBU_UPDATE_CACHESIZE ){ for(pp=&pIter->pRbuUpdate; *pp!=pUp; pp=&((*pp)->pNext)); *pp = 0; sqlite3_finalize(pUp->pUpdate); pUp->pUpdate = 0; }else{ pUp = (RbuUpdateStmt*)rbuMalloc(p, sizeof(RbuUpdateStmt)+pIter->nTblCol+1); } if( pUp ){ char *zWhere = rbuObjIterGetWhere(p, pIter); char *zSet = rbuObjIterGetSetlist(p, pIter, zMask); char *zUpdate = 0; pUp->zMask = (char*)&pUp[1]; memcpy(pUp->zMask, zMask, pIter->nTblCol); pUp->pNext = pIter->pRbuUpdate; pIter->pRbuUpdate = pUp; if( zSet ){ const char *zPrefix = ""; if( pIter->eType!=RBU_PK_VTAB ) zPrefix = "rbu_imp_"; zUpdate = sqlite3_mprintf("UPDATE \"%s%w\" SET %s WHERE %s", zPrefix, pIter->zTbl, zSet, zWhere ); p->rc = prepareFreeAndCollectError( p->dbMain, &pUp->pUpdate, &p->zErrmsg, zUpdate ); *ppStmt = pUp->pUpdate; } sqlite3_free(zWhere); sqlite3_free(zSet); } return p->rc; } static sqlite3 *rbuOpenDbhandle( sqlite3rbu *p, const char *zName, int bUseVfs ){ sqlite3 *db = 0; if( p->rc==SQLITE_OK ){ const int flags = SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|SQLITE_OPEN_URI; p->rc = sqlite3_open_v2(zName, &db, flags, bUseVfs ? p->zVfsName : 0); if( p->rc ){ p->zErrmsg = sqlite3_mprintf("%s", sqlite3_errmsg(db)); sqlite3_close(db); db = 0; } } return db; } /* ** Free an RbuState object allocated by rbuLoadState(). */ static void rbuFreeState(RbuState *p){ if( p ){ sqlite3_free(p->zTbl); sqlite3_free(p->zIdx); sqlite3_free(p); } } /* ** Allocate an RbuState object and load the contents of the rbu_state ** table into it. Return a pointer to the new object. It is the ** responsibility of the caller to eventually free the object using ** sqlite3_free(). ** ** If an error occurs, leave an error code and message in the rbu handle ** and return NULL. */ static RbuState *rbuLoadState(sqlite3rbu *p){ RbuState *pRet = 0; sqlite3_stmt *pStmt = 0; int rc; int rc2; pRet = (RbuState*)rbuMalloc(p, sizeof(RbuState)); if( pRet==0 ) return 0; rc = prepareFreeAndCollectError(p->dbRbu, &pStmt, &p->zErrmsg, sqlite3_mprintf("SELECT k, v FROM %s.rbu_state", p->zStateDb) ); while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){ switch( sqlite3_column_int(pStmt, 0) ){ case RBU_STATE_STAGE: pRet->eStage = sqlite3_column_int(pStmt, 1); if( pRet->eStage!=RBU_STAGE_OAL && pRet->eStage!=RBU_STAGE_MOVE && pRet->eStage!=RBU_STAGE_CKPT ){ p->rc = SQLITE_CORRUPT; } break; case RBU_STATE_TBL: pRet->zTbl = rbuStrndup((char*)sqlite3_column_text(pStmt, 1), &rc); break; case RBU_STATE_IDX: pRet->zIdx = rbuStrndup((char*)sqlite3_column_text(pStmt, 1), &rc); break; case RBU_STATE_ROW: pRet->nRow = sqlite3_column_int(pStmt, 1); break; case RBU_STATE_PROGRESS: pRet->nProgress = sqlite3_column_int64(pStmt, 1); break; case RBU_STATE_CKPT: pRet->iWalCksum = sqlite3_column_int64(pStmt, 1); break; case RBU_STATE_COOKIE: pRet->iCookie = (u32)sqlite3_column_int64(pStmt, 1); break; case RBU_STATE_OALSZ: pRet->iOalSz = (u32)sqlite3_column_int64(pStmt, 1); break; case RBU_STATE_PHASEONESTEP: pRet->nPhaseOneStep = sqlite3_column_int64(pStmt, 1); break; default: rc = SQLITE_CORRUPT; break; } } rc2 = sqlite3_finalize(pStmt); if( rc==SQLITE_OK ) rc = rc2; p->rc = rc; return pRet; } /* ** Open the database handle and attach the RBU database as "rbu". If an ** error occurs, leave an error code and message in the RBU handle. */ static void rbuOpenDatabase(sqlite3rbu *p){ assert( p->rc || (p->dbMain==0 && p->dbRbu==0) ); assert( p->rc || rbuIsVacuum(p) || p->zTarget!=0 ); /* Open the RBU database */ p->dbRbu = rbuOpenDbhandle(p, p->zRbu, 1); if( p->rc==SQLITE_OK && rbuIsVacuum(p) ){ sqlite3_file_control(p->dbRbu, "main", SQLITE_FCNTL_RBUCNT, (void*)p); if( p->zState==0 ){ const char *zFile = sqlite3_db_filename(p->dbRbu, "main"); p->zState = rbuMPrintf(p, "file://%s-vacuum?modeof=%s", zFile, zFile); } } /* If using separate RBU and state databases, attach the state database to ** the RBU db handle now. */ if( p->zState ){ rbuMPrintfExec(p, p->dbRbu, "ATTACH %Q AS stat", p->zState); memcpy(p->zStateDb, "stat", 4); }else{ memcpy(p->zStateDb, "main", 4); } #if 0 if( p->rc==SQLITE_OK && rbuIsVacuum(p) ){ p->rc = sqlite3_exec(p->dbRbu, "BEGIN", 0, 0, 0); } #endif /* If it has not already been created, create the rbu_state table */ rbuMPrintfExec(p, p->dbRbu, RBU_CREATE_STATE, p->zStateDb); #if 0 if( rbuIsVacuum(p) ){ if( p->rc==SQLITE_OK ){ int rc2; int bOk = 0; sqlite3_stmt *pCnt = 0; p->rc = prepareAndCollectError(p->dbRbu, &pCnt, &p->zErrmsg, "SELECT count(*) FROM stat.sqlite_master" ); if( p->rc==SQLITE_OK && sqlite3_step(pCnt)==SQLITE_ROW && 1==sqlite3_column_int(pCnt, 0) ){ bOk = 1; } rc2 = sqlite3_finalize(pCnt); if( p->rc==SQLITE_OK ) p->rc = rc2; if( p->rc==SQLITE_OK && bOk==0 ){ p->rc = SQLITE_ERROR; p->zErrmsg = sqlite3_mprintf("invalid state database"); } if( p->rc==SQLITE_OK ){ p->rc = sqlite3_exec(p->dbRbu, "COMMIT", 0, 0, 0); } } } #endif if( p->rc==SQLITE_OK && rbuIsVacuum(p) ){ int bOpen = 0; int rc; p->nRbu = 0; p->pRbuFd = 0; rc = sqlite3_file_control(p->dbRbu, "main", SQLITE_FCNTL_RBUCNT, (void*)p); if( rc!=SQLITE_NOTFOUND ) p->rc = rc; if( p->eStage>=RBU_STAGE_MOVE ){ bOpen = 1; }else{ RbuState *pState = rbuLoadState(p); if( pState ){ bOpen = (pState->eStage>RBU_STAGE_MOVE); rbuFreeState(pState); } } if( bOpen ) p->dbMain = rbuOpenDbhandle(p, p->zRbu, p->nRbu<=1); } p->eStage = 0; if( p->rc==SQLITE_OK && p->dbMain==0 ){ if( !rbuIsVacuum(p) ){ p->dbMain = rbuOpenDbhandle(p, p->zTarget, 1); }else if( p->pRbuFd->pWalFd ){ p->rc = SQLITE_ERROR; p->zErrmsg = sqlite3_mprintf("cannot vacuum wal mode database"); }else{ char *zTarget; char *zExtra = 0; if( strlen(p->zRbu)>=5 && 0==memcmp("file:", p->zRbu, 5) ){ zExtra = &p->zRbu[5]; while( *zExtra ){ if( *zExtra++=='?' ) break; } if( *zExtra=='\0' ) zExtra = 0; } zTarget = sqlite3_mprintf("file:%s-vacuum?rbu_memory=1%s%s", sqlite3_db_filename(p->dbRbu, "main"), (zExtra==0 ? "" : "&"), (zExtra==0 ? "" : zExtra) ); if( zTarget==0 ){ p->rc = SQLITE_NOMEM; return; } p->dbMain = rbuOpenDbhandle(p, zTarget, p->nRbu<=1); sqlite3_free(zTarget); } } if( p->rc==SQLITE_OK ){ p->rc = sqlite3_create_function(p->dbMain, "rbu_tmp_insert", -1, SQLITE_UTF8, (void*)p, rbuTmpInsertFunc, 0, 0 ); } if( p->rc==SQLITE_OK ){ p->rc = sqlite3_create_function(p->dbMain, "rbu_fossil_delta", 2, SQLITE_UTF8, 0, rbuFossilDeltaFunc, 0, 0 ); } if( p->rc==SQLITE_OK ){ p->rc = sqlite3_create_function(p->dbRbu, "rbu_target_name", -1, SQLITE_UTF8, (void*)p, rbuTargetNameFunc, 0, 0 ); } if( p->rc==SQLITE_OK ){ p->rc = sqlite3_file_control(p->dbMain, "main", SQLITE_FCNTL_RBU, (void*)p); } rbuMPrintfExec(p, p->dbMain, "SELECT * FROM sqlite_master"); /* Mark the database file just opened as an RBU target database. If ** this call returns SQLITE_NOTFOUND, then the RBU vfs is not in use. ** This is an error. */ if( p->rc==SQLITE_OK ){ p->rc = sqlite3_file_control(p->dbMain, "main", SQLITE_FCNTL_RBU, (void*)p); } if( p->rc==SQLITE_NOTFOUND ){ p->rc = SQLITE_ERROR; p->zErrmsg = sqlite3_mprintf("rbu vfs not found"); } } /* ** This routine is a copy of the sqlite3FileSuffix3() routine from the core. ** It is a no-op unless SQLITE_ENABLE_8_3_NAMES is defined. ** ** If SQLITE_ENABLE_8_3_NAMES is set at compile-time and if the database ** filename in zBaseFilename is a URI with the "8_3_names=1" parameter and ** if filename in z[] has a suffix (a.k.a. "extension") that is longer than ** three characters, then shorten the suffix on z[] to be the last three ** characters of the original suffix. ** ** If SQLITE_ENABLE_8_3_NAMES is set to 2 at compile-time, then always ** do the suffix shortening regardless of URI parameter. ** ** Examples: ** ** test.db-journal => test.nal ** test.db-wal => test.wal ** test.db-shm => test.shm ** test.db-mj7f3319fa => test.9fa */ static void rbuFileSuffix3(const char *zBase, char *z){ #ifdef SQLITE_ENABLE_8_3_NAMES #if SQLITE_ENABLE_8_3_NAMES<2 if( sqlite3_uri_boolean(zBase, "8_3_names", 0) ) #endif { int i, sz; sz = (int)strlen(z)&0xffffff; for(i=sz-1; i>0 && z[i]!='/' && z[i]!='.'; i--){} if( z[i]=='.' && sz>i+4 ) memmove(&z[i+1], &z[sz-3], 4); } #endif } /* ** Return the current wal-index header checksum for the target database ** as a 64-bit integer. ** ** The checksum is store in the first page of xShmMap memory as an 8-byte ** blob starting at byte offset 40. */ static i64 rbuShmChecksum(sqlite3rbu *p){ i64 iRet = 0; if( p->rc==SQLITE_OK ){ sqlite3_file *pDb = p->pTargetFd->pReal; u32 volatile *ptr; p->rc = pDb->pMethods->xShmMap(pDb, 0, 32*1024, 0, (void volatile**)&ptr); if( p->rc==SQLITE_OK ){ iRet = ((i64)ptr[10] << 32) + ptr[11]; } } return iRet; } /* ** This function is called as part of initializing or reinitializing an ** incremental checkpoint. ** ** It populates the sqlite3rbu.aFrame[] array with the set of ** (wal frame -> db page) copy operations required to checkpoint the ** current wal file, and obtains the set of shm locks required to safely ** perform the copy operations directly on the file-system. ** ** If argument pState is not NULL, then the incremental checkpoint is ** being resumed. In this case, if the checksum of the wal-index-header ** following recovery is not the same as the checksum saved in the RbuState ** object, then the rbu handle is set to DONE state. This occurs if some ** other client appends a transaction to the wal file in the middle of ** an incremental checkpoint. */ static void rbuSetupCheckpoint(sqlite3rbu *p, RbuState *pState){ /* If pState is NULL, then the wal file may not have been opened and ** recovered. Running a read-statement here to ensure that doing so ** does not interfere with the "capture" process below. */ if( pState==0 ){ p->eStage = 0; if( p->rc==SQLITE_OK ){ p->rc = sqlite3_exec(p->dbMain, "SELECT * FROM sqlite_master", 0, 0, 0); } } /* Assuming no error has occurred, run a "restart" checkpoint with the ** sqlite3rbu.eStage variable set to CAPTURE. This turns on the following ** special behaviour in the rbu VFS: ** ** * If the exclusive shm WRITER or READ0 lock cannot be obtained, ** the checkpoint fails with SQLITE_BUSY (normally SQLite would ** proceed with running a passive checkpoint instead of failing). ** ** * Attempts to read from the *-wal file or write to the database file ** do not perform any IO. Instead, the frame/page combinations that ** would be read/written are recorded in the sqlite3rbu.aFrame[] ** array. ** ** * Calls to xShmLock(UNLOCK) to release the exclusive shm WRITER, ** READ0 and CHECKPOINT locks taken as part of the checkpoint are ** no-ops. These locks will not be released until the connection ** is closed. ** ** * Attempting to xSync() the database file causes an SQLITE_INTERNAL ** error. ** ** As a result, unless an error (i.e. OOM or SQLITE_BUSY) occurs, the ** checkpoint below fails with SQLITE_INTERNAL, and leaves the aFrame[] ** array populated with a set of (frame -> page) mappings. Because the ** WRITER, CHECKPOINT and READ0 locks are still held, it is safe to copy ** data from the wal file into the database file according to the ** contents of aFrame[]. */ if( p->rc==SQLITE_OK ){ int rc2; p->eStage = RBU_STAGE_CAPTURE; rc2 = sqlite3_exec(p->dbMain, "PRAGMA main.wal_checkpoint=restart", 0, 0,0); if( rc2!=SQLITE_INTERNAL ) p->rc = rc2; } if( p->rc==SQLITE_OK ){ p->eStage = RBU_STAGE_CKPT; p->nStep = (pState ? pState->nRow : 0); p->aBuf = rbuMalloc(p, p->pgsz); p->iWalCksum = rbuShmChecksum(p); } if( p->rc==SQLITE_OK && pState && pState->iWalCksum!=p->iWalCksum ){ p->rc = SQLITE_DONE; p->eStage = RBU_STAGE_DONE; } } /* ** Called when iAmt bytes are read from offset iOff of the wal file while ** the rbu object is in capture mode. Record the frame number of the frame ** being read in the aFrame[] array. */ static int rbuCaptureWalRead(sqlite3rbu *pRbu, i64 iOff, int iAmt){ const u32 mReq = (1<mLock!=mReq ){ pRbu->rc = SQLITE_BUSY; return SQLITE_INTERNAL; } pRbu->pgsz = iAmt; if( pRbu->nFrame==pRbu->nFrameAlloc ){ int nNew = (pRbu->nFrameAlloc ? pRbu->nFrameAlloc : 64) * 2; RbuFrame *aNew; aNew = (RbuFrame*)sqlite3_realloc64(pRbu->aFrame, nNew * sizeof(RbuFrame)); if( aNew==0 ) return SQLITE_NOMEM; pRbu->aFrame = aNew; pRbu->nFrameAlloc = nNew; } iFrame = (u32)((iOff-32) / (i64)(iAmt+24)) + 1; if( pRbu->iMaxFrame